package org . vaadin . teemu . clara . demo ; import java . io . BufferedReader ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import org . vaadin . teemu . clara . Clara ; import org . vaadin . teemu . clara . inflater . LayoutInflaterException ; import com . vaadin . Application ; import com . vaadin . terminal . ThemeResource ; import com . vaadin . ui . Button ; import com . vaadin . ui . Button . ClickEvent ; import com . vaadin . ui . Component ; import com . vaadin . ui . Embedded ; import com . vaadin . ui . HorizontalLayout ; import com . vaadin . ui . HorizontalSplitPanel ; import com . vaadin . ui . TextArea ; import com . vaadin . ui . VerticalLayout ; import com . vaadin . ui . Window ; import com . vaadin . ui . Window . Notification ; @ SuppressWarnings ( "" ) public class DemoApplication extends Application { private DemoController controller ; private TextArea xmlArea ; private HorizontalSplitPanel split = new HorizontalSplitPanel ( ) ; private Window mainWindow ; @ Override public void init ( ) { setTheme ( "" ) ; setMainWindow ( mainWindow = new Window ( ) ) ; controller = new DemoController ( mainWindow ) ; mainWindow . setContent ( split ) ; VerticalLayout editor = new VerticalLayout ( ) ; editor . setSpacing ( true ) ; editor . setMargin ( false , false , false , true ) ; editor . setHeight ( "" ) ; editor . addComponent ( xmlArea = createXmlArea ( ) ) ; editor . setExpandRatio ( xmlArea , ) ; editor . addComponent ( createUpdateButton ( ) ) ; HorizontalLayout wrapper = new HorizontalLayout ( ) ; wrapper . setMargin ( true ) ; wrapper . setSizeFull ( ) ; wrapper . addComponent ( createLogo ( ) ) ; wrapper . addComponent ( editor ) ; wrapper . setExpandRatio ( editor , ) ; split . setFirstComponent ( wrapper ) ; updateLayout ( ) ; } private Component createLogo ( ) { Embedded logo = new Embedded ( null , new ThemeResource ( "" ) ) ; logo . setHeight ( "" ) ; logo . setWidth ( "" ) ; return logo ; } private TextArea createXmlArea ( ) { TextArea area = new TextArea ( ) ; area . setStyleName ( "" ) ; area . setSizeFull ( ) ; area . setValue ( readStartingPoint ( ) ) ; return area ; } private Button createUpdateButton ( ) { return new Button ( "" , new Button . ClickListener ( ) { public void buttonClick ( ClickEvent event ) { updateLayout ( ) ; } } ) ; } private String readStartingPoint ( ) { BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( getClass ( ) . getClassLoader ( ) . getResourceAsStream ( "" ) ) ) ; StringBuilder xml = new StringBuilder ( ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { xml . append ( line ) ; xml . append ( "" ) ; } return xml . toString ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return null ; } private void updateLayout ( ) { try { Component c = Clara . create ( new ByteArrayInputStream ( xmlArea . getValue ( ) . toString ( ) . getBytes ( ) ) , controller ) ; split . replaceComponent ( split . getSecondComponent ( ) , c ) ; } catch ( LayoutInflaterException e ) { mainWindow . showNotification ( e . getMessage ( ) , Notification . TYPE_ERROR_MESSAGE ) ; } } } package org . vaadin . teemu . clara . demo ; import java . util . Date ; import org . vaadin . teemu . clara . binder . annotation . DataSource ; import org . vaadin . teemu . clara . binder . annotation . EventHandler ; import com . vaadin . data . Container ; import com . vaadin . data . Property ; import com . vaadin . data . Property . ValueChangeEvent ; import com . vaadin . data . util . IndexedContainer ; import com . vaadin . data . util . ObjectProperty ; import com . vaadin . ui . Button . ClickEvent ; import com . vaadin . ui . Window ; public class DemoController { private Window window ; public DemoController ( Window window ) { this . window = window ; } @ DataSource ( "" ) public Property getDateProperty ( ) { return new ObjectProperty < Date > ( new Date ( ) ) ; } @ DataSource ( "" ) public Container getPersonContainer ( ) { IndexedContainer container = new IndexedContainer ( ) ; container . addContainerProperty ( "" , String . class , "" ) ; container . addContainerProperty ( "" , Integer . class , ) ; Object itemId = container . addItem ( ) ; container . getItem ( itemId ) . getItemProperty ( "" ) . setValue ( "" ) ; container . getItem ( itemId ) . getItemProperty ( "" ) . setValue ( ) ; itemId = container . addItem ( ) ; container . getItem ( itemId ) . getItemProperty ( "" ) . setValue ( "" ) ; container . getItem ( itemId ) . getItemProperty ( "" ) . setValue ( ) ; return container ; } @ EventHandler ( "" ) public void handleButtonClick ( ClickEvent event ) { window . showNotification ( "" ) ; } @ EventHandler ( "" ) public void handleAnotherButtonClick ( ClickEvent event ) { window . showNotification ( "" ) ; } @ EventHandler ( "" ) public void someValueChanged ( ValueChangeEvent event ) { window . showNotification ( "" + event . getProperty ( ) . getValue ( ) ) ; } } package org . vaadin . teemu . clara ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; import org . junit . Before ; import org . junit . Test ; import org . vaadin . teemu . clara . inflater . PrimitiveAttributeParser ; public class PrimitiveAttributeParserTest { private PrimitiveAttributeParser handler ; @ Before public void setUp ( ) { handler = new PrimitiveAttributeParser ( ) ; } @ Test public void testBoolean ( ) throws Exception { assertTrue ( handler . isSupported ( Boolean . TYPE ) ) ; assertTrue ( handler . isSupported ( Boolean . class ) ) ; assertEquals ( true , handler . getValueAs ( "" , Boolean . TYPE ) ) ; assertEquals ( false , handler . getValueAs ( "" , Boolean . TYPE ) ) ; assertEquals ( true , handler . getValueAs ( "" , Boolean . class ) ) ; assertEquals ( false , handler . getValueAs ( "" , Boolean . class ) ) ; } @ Test public void testInteger ( ) throws Exception { assertTrue ( handler . isSupported ( Integer . TYPE ) ) ; assertTrue ( handler . isSupported ( Integer . class ) ) ; assertEquals ( , handler . getValueAs ( "" , Integer . TYPE ) ) ; assertEquals ( - , handler . getValueAs ( "" , Integer . TYPE ) ) ; assertEquals ( , handler . getValueAs ( "" , Integer . class ) ) ; assertEquals ( - , handler . getValueAs ( "" , Integer . class ) ) ; } @ Test public void testByte ( ) throws Exception { assertTrue ( handler . isSupported ( Byte . TYPE ) ) ; assertTrue ( handler . isSupported ( Byte . class ) ) ; assertEquals ( ( byte ) , handler . getValueAs ( "" , Byte . TYPE ) ) ; assertEquals ( ( byte ) - , handler . getValueAs ( "" , Byte . TYPE ) ) ; assertEquals ( ( byte ) , handler . getValueAs ( "" , Byte . class ) ) ; assertEquals ( ( byte ) - , handler . getValueAs ( "" , Byte . class ) ) ; } @ Test public void testShort ( ) throws Exception { assertTrue ( handler . isSupported ( Short . TYPE ) ) ; assertTrue ( handler . isSupported ( Short . class ) ) ; assertEquals ( ( short ) , handler . getValueAs ( "" , Short . TYPE ) ) ; assertEquals ( ( short ) - , handler . getValueAs ( "" , Short . TYPE ) ) ; assertEquals ( ( short ) , handler . getValueAs ( "" , Short . class ) ) ; assertEquals ( ( short ) - , handler . getValueAs ( "" , Short . class ) ) ; } @ Test public void testLong ( ) throws Exception { assertTrue ( handler . isSupported ( Long . TYPE ) ) ; assertTrue ( handler . isSupported ( Long . class ) ) ; assertEquals ( ( long ) , handler . getValueAs ( "" , Long . TYPE ) ) ; assertEquals ( ( long ) - , handler . getValueAs ( "" , Long . TYPE ) ) ; assertEquals ( ( long ) , handler . getValueAs ( "" , Long . class ) ) ; assertEquals ( ( long ) - , handler . getValueAs ( "" , Long . class ) ) ; } @ Test public void testCharacter ( ) throws Exception { assertTrue ( handler . isSupported ( Character . TYPE ) ) ; assertTrue ( handler . isSupported ( Character . class ) ) ; assertEquals ( '' , handler . getValueAs ( "" , Character . TYPE ) ) ; assertEquals ( '' , handler . getValueAs ( "" , Character . class ) ) ; } @ Test public void testFloat ( ) throws Exception { assertTrue ( handler . isSupported ( Float . TYPE ) ) ; assertTrue ( handler . isSupported ( Float . class ) ) ; assertEquals ( , handler . getValueAs ( "" , Float . TYPE ) ) ; assertEquals ( , handler . getValueAs ( "" , Float . class ) ) ; } @ Test public void testDouble ( ) throws Exception { assertTrue ( handler . isSupported ( Double . TYPE ) ) ; assertTrue ( handler . isSupported ( Double . class ) ) ; assertEquals ( , handler . getValueAs ( "" , Double . TYPE ) ) ; assertEquals ( , handler . getValueAs ( "" , Double . class ) ) ; } @ Test public void testString ( ) throws Exception { assertTrue ( handler . isSupported ( String . class ) ) ; assertEquals ( "" , handler . getValueAs ( "" , String . class ) ) ; } } package org . vaadin . teemu . clara . util ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import org . junit . Test ; import com . vaadin . ui . Button ; public class ReflectionUtilsTest { public static class ClassToExamine { public void setFooBar ( ) { } public void setFooBar ( String foo ) { } public void setFooBar ( int foo ) { } public void setFooBar ( String foo , int bar ) { } } @ Test public void test_getMethodsByNameAndParamCount ( ) { assertEquals ( , ReflectionUtils . getMethodsByNameAndParamCount ( ClassToExamine . class , "" , ) . size ( ) ) ; assertEquals ( , ReflectionUtils . getMethodsByNameAndParamCount ( ClassToExamine . class , "" , ) . size ( ) ) ; assertEquals ( , ReflectionUtils . getMethodsByNameAndParamCount ( ClassToExamine . class , "" , ) . size ( ) ) ; assertEquals ( , ReflectionUtils . getMethodsByNameAndParamCount ( ClassToExamine . class , "" , ) . size ( ) ) ; assertEquals ( , ReflectionUtils . getMethodsByNameAndParamCount ( ClassToExamine . class , "" , ) . size ( ) ) ; } @ Test public void test_isComponent ( ) { assertTrue ( ReflectionUtils . isComponent ( Button . class ) ) ; assertFalse ( ReflectionUtils . isComponent ( ClassToExamine . class ) ) ; assertFalse ( ReflectionUtils . isComponent ( null ) ) ; } } package org . vaadin . teemu . clara ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . io . InputStream ; import org . junit . Before ; import org . junit . Test ; import org . vaadin . teemu . clara . inflater . LayoutInflater ; import org . vaadin . teemu . clara . inflater . LayoutInflaterException ; import com . vaadin . ui . Button ; import com . vaadin . ui . Component ; import com . vaadin . ui . VerticalLayout ; public class LayoutInflaterTest { private LayoutInflater inflater ; @ Before public void setUp ( ) { inflater = new LayoutInflater ( ) ; } private InputStream getXml ( String fileName ) { return getClass ( ) . getClassLoader ( ) . getResourceAsStream ( fileName ) ; } @ Test public void inflate_singleButton_buttonInstantiated ( ) { Button button = ( Button ) inflater . inflate ( getXml ( "" ) ) ; assertEquals ( com . vaadin . ui . Button . class , button . getClass ( ) ) ; assertEquals ( "" , button . getCaption ( ) ) ; assertEquals ( true , button . isReadOnly ( ) ) ; } @ Test public void inflate_singleButtonNoNamespace_buttonInstantiated ( ) { Component button = inflater . inflate ( getXml ( "" ) ) ; assertEquals ( com . vaadin . ui . Button . class , button . getClass ( ) ) ; assertEquals ( "" , button . getCaption ( ) ) ; assertEquals ( true , button . isReadOnly ( ) ) ; } @ Test public void inflate_singleLayout_layoutWithMarginsInstantiated ( ) { Component layout = inflater . inflate ( getXml ( "" ) ) ; assertEquals ( com . vaadin . ui . VerticalLayout . class , layout . getClass ( ) ) ; assertTrue ( ( ( VerticalLayout ) layout ) . getMargin ( ) . hasTop ( ) ) ; assertFalse ( ( ( VerticalLayout ) layout ) . getMargin ( ) . hasRight ( ) ) ; assertFalse ( ( ( VerticalLayout ) layout ) . getMargin ( ) . hasBottom ( ) ) ; assertTrue ( ( ( VerticalLayout ) layout ) . getMargin ( ) . hasLeft ( ) ) ; } @ Test public void inflate_layoutAttributes_layoutAttributesApplied ( ) { Component layout = inflater . inflate ( getXml ( "" ) ) ; assertEquals ( com . vaadin . ui . VerticalLayout . class , layout . getClass ( ) ) ; VerticalLayout verticalLayout = ( VerticalLayout ) layout ; Component button = verticalLayout . getComponentIterator ( ) . next ( ) ; assertEquals ( , verticalLayout . getExpandRatio ( button ) , ) ; } @ Test public void inflate_componentHasWidth_widthAttributeApplied ( ) { Component layout = inflater . inflate ( getXml ( "" ) ) ; Button button200px = ( Button ) Clara . findComponentById ( layout , "" ) ; assertEquals ( , button200px . getWidth ( ) , ) ; } @ Test public void inflate_addAttributeInterceptor_valueInterceptedCorrectly ( ) { LayoutInflater interceptingInflater = new LayoutInflater ( ) ; AttributeInterceptor interceptor = new AttributeInterceptor ( ) { @ Override public void intercept ( AttributeContext attributeContext ) { if ( attributeContext . getValue ( ) . getClass ( ) == String . class ) { String value = ( String ) attributeContext . getValue ( ) ; if ( value . startsWith ( "" ) ) { attributeContext . setValue ( "" ) ; } } try { attributeContext . proceed ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; interceptingInflater . addInterceptor ( interceptor ) ; Component interceptedView = interceptingInflater . inflate ( getXml ( "" ) ) ; Component view = inflater . inflate ( getXml ( "" ) ) ; Button button200px = ( Button ) Clara . findComponentById ( interceptedView , "" ) ; assertEquals ( "" , button200px . getCaption ( ) ) ; button200px = ( Button ) Clara . findComponentById ( view , "" ) ; assertEquals ( "" , button200px . getCaption ( ) ) ; } @ Test public void inflate_singleButton_findByIdWorks ( ) { Component view = inflater . inflate ( getXml ( "" ) ) ; assertEquals ( com . vaadin . ui . Button . class , Clara . findComponentById ( view , "" ) . getClass ( ) ) ; assertEquals ( null , Clara . findComponentById ( view , "" ) ) ; } @ Test ( expected = LayoutInflaterException . class ) public void inflate_nonComponent_exceptionThrown ( ) { inflater . inflate ( getXml ( "" ) ) ; } @ Test ( expected = LayoutInflaterException . class ) public void inflate_duplicateId_exceptionThrown ( ) { inflater . inflate ( getXml ( "" ) ) ; } @ Test ( expected = LayoutInflaterException . class ) public void inflate_IOException_exceptionThrown ( ) { inflater . inflate ( new InputStream ( ) { @ Override public int read ( ) throws IOException { throw new IOException ( ) ; } } ) ; } @ Test ( expected = LayoutInflaterException . class ) public void inflate_invalidXml_exceptionThrown ( ) { inflater . inflate ( new ByteArrayInputStream ( "" . getBytes ( ) ) ) ; } } package org . vaadin . teemu . clara ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import java . io . InputStream ; import org . junit . Before ; import org . junit . Test ; import org . vaadin . teemu . clara . binder . annotation . EventHandler ; import com . vaadin . ui . Button ; import com . vaadin . ui . Component ; public class ClaraIntegrationTest { private InputStream xml ; private Controller controller ; private AttributeInterceptor firstInterceptor ; private AttributeInterceptor secondInterceptor ; public static class Controller { private boolean clicked ; @ EventHandler ( "" ) public void clicked ( Button . ClickEvent event ) { clicked = true ; } } @ Before public void setUp ( ) { xml = getXml ( "" ) ; controller = new Controller ( ) ; firstInterceptor = getInterceptor ( ) ; secondInterceptor = getSecondInterceptor ( ) ; } @ Test public void testCreateMethod_usingAllParametersWithTwoInterceptors_interceptorsAndControllerCalled ( ) { Component layout = Clara . create ( xml , controller , firstInterceptor , secondInterceptor ) ; Button button200px = ( Button ) Clara . findComponentById ( layout , "" ) ; assertEquals ( "" , button200px . getCaption ( ) ) ; assertFalse ( controller . clicked ) ; button200px . click ( ) ; assertTrue ( controller . clicked ) ; } @ Test public void testCreateMethod_usingAllParameters_interceptorAndControllerCalled ( ) { Component layout = Clara . create ( xml , controller , firstInterceptor ) ; Button button200px = ( Button ) Clara . findComponentById ( layout , "" ) ; assertEquals ( "" , button200px . getCaption ( ) ) ; assertFalse ( controller . clicked ) ; button200px . click ( ) ; assertTrue ( controller . clicked ) ; } @ Test public void testCreateMethod_usingOnlyController_controllerCalled ( ) { Component layout = Clara . create ( xml , controller ) ; Button button200px = ( Button ) Clara . findComponentById ( layout , "" ) ; assertEquals ( "" , button200px . getCaption ( ) ) ; assertFalse ( controller . clicked ) ; button200px . click ( ) ; assertTrue ( controller . clicked ) ; } @ Test public void testCreateMethod_usingNoParameters_componentInflatedCorrectly ( ) { Component layout = Clara . create ( xml ) ; Button button200px = ( Button ) Clara . findComponentById ( layout , "" ) ; assertEquals ( "" , button200px . getCaption ( ) ) ; } private InputStream getXml ( String fileName ) { return getClass ( ) . getClassLoader ( ) . getResourceAsStream ( fileName ) ; } public AttributeInterceptor getInterceptor ( ) { return new AttributeInterceptor ( ) { @ Override public void intercept ( AttributeContext attributeContext ) { if ( attributeContext . getValue ( ) . getClass ( ) == String . class ) { String value = ( String ) attributeContext . getValue ( ) ; if ( value . startsWith ( "" ) ) { attributeContext . setValue ( "" ) ; } } try { attributeContext . proceed ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; } public AttributeInterceptor getSecondInterceptor ( ) { return new AttributeInterceptor ( ) { @ Override public void intercept ( AttributeContext attributeContext ) { if ( attributeContext . getValue ( ) . getClass ( ) == String . class ) { String value = ( String ) attributeContext . getValue ( ) ; if ( value . startsWith ( "" ) ) { attributeContext . setValue ( "" ) ; } } try { attributeContext . proceed ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; } } package org . vaadin . teemu . clara ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; import java . io . InputStream ; import java . lang . reflect . Method ; import java . util . Date ; import org . junit . Before ; import org . junit . Test ; import org . vaadin . teemu . clara . binder . Binder ; import org . vaadin . teemu . clara . binder . annotation . DataSource ; import org . vaadin . teemu . clara . binder . annotation . EventHandler ; import org . vaadin . teemu . clara . inflater . LayoutInflater ; import com . vaadin . data . Property ; import com . vaadin . ui . Button ; import com . vaadin . ui . Button . ClickEvent ; import com . vaadin . ui . DateField ; public class BinderTest { private LayoutInflater inflater ; private boolean clickCalled ; @ Before public void setUp ( ) { inflater = new LayoutInflater ( ) ; } private InputStream getXml ( String fileName ) { return getClass ( ) . getClassLoader ( ) . getResourceAsStream ( fileName ) ; } @ EventHandler ( "" ) public void handleButtonClick ( ClickEvent event ) { clickCalled = true ; } @ DataSource ( "" ) public Property getDataSource ( ) { Date date = new Date ( ) ; return new com . vaadin . data . util . ObjectProperty < Date > ( date ) ; } @ Test public void bind_clickListener_clickListenerInvoked ( ) { Button button = ( Button ) inflater . inflate ( getXml ( "" ) ) ; Binder binder = new Binder ( ) ; binder . bind ( button , this ) ; clickCalled = false ; simulateButtonClick ( button ) ; assertTrue ( "" , clickCalled ) ; } @ Test public void bind_dataSource_dataSourceAttached ( ) { DateField view = ( DateField ) inflater . inflate ( getXml ( "" ) ) ; Binder binder = new Binder ( ) ; binder . bind ( view , this ) ; Date value = ( Date ) view . getValue ( ) ; assertEquals ( , value . getTime ( ) ) ; } private void simulateButtonClick ( Button button ) { Method fireClick ; try { fireClick = Button . class . getDeclaredMethod ( "" ) ; fireClick . setAccessible ( true ) ; fireClick . invoke ( button ) ; } catch ( Exception e ) { throw new RuntimeException ( "" , e ) ; } } } package org . vaadin . teemu . clara ; import com . vaadin . ui . Component ; public interface AttributeInterceptor { void intercept ( AttributeContext invocationContext ) ; } package org . vaadin . teemu . clara ; import java . lang . reflect . Method ; public abstract class AttributeContext { private Object value ; private Method setter ; public AttributeContext ( Method setter , Object value ) { this . value = value ; this . setter = setter ; } public abstract void proceed ( ) throws Exception ; public Object getValue ( ) { return value ; } public void setValue ( Object value ) { this . value = value ; } public Method getSetter ( ) { return setter ; } } package org . vaadin . teemu . clara . binder ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; import java . util . Set ; import java . util . logging . Logger ; import org . vaadin . teemu . clara . Clara ; import org . vaadin . teemu . clara . binder . annotation . DataSource ; import org . vaadin . teemu . clara . binder . annotation . EventHandler ; import org . vaadin . teemu . clara . util . ReflectionUtils ; import com . vaadin . data . Container ; import com . vaadin . data . Item ; import com . vaadin . data . Property ; import com . vaadin . ui . Component ; public class Binder { protected Logger getLogger ( ) { return Logger . getLogger ( Binder . class . getName ( ) ) ; } public void bind ( Component componentRoot , Object controller ) { Method [ ] methods = controller . getClass ( ) . getMethods ( ) ; for ( Method method : methods ) { if ( method . isAnnotationPresent ( DataSource . class ) ) { bindDataSource ( componentRoot , controller , method , method . getAnnotation ( DataSource . class ) ) ; } if ( method . isAnnotationPresent ( EventHandler . class ) ) { bindEventHandler ( componentRoot , controller , method , method . getAnnotation ( EventHandler . class ) ) ; } } } private void bindEventHandler ( Component componentRoot , Object controller , Method method , EventHandler eventListener ) { String componentId = eventListener . value ( ) ; Component component = Clara . findComponentById ( componentRoot , componentId ) ; Class < ? > eventClass = ( method . getParameterTypes ( ) . length > ? method . getParameterTypes ( ) [ ] : null ) ; if ( eventClass != null && component != null ) { Method addListenerMethod = getAddListenerMethod ( component . getClass ( ) , eventClass ) ; if ( addListenerMethod != null ) { try { Object listener = createListenerProxy ( addListenerMethod . getParameterTypes ( ) [ ] , eventClass , method , controller ) ; addListenerMethod . invoke ( component , listener ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } } } private Object createListenerProxy ( Class < ? > listenerClass , final Class < ? > eventClass , final Method listenerMethod , final Object controller ) { Object proxy = Proxy . newProxyInstance ( listenerClass . getClassLoader ( ) , new Class < ? > [ ] { listenerClass } , new InvocationHandler ( ) { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { if ( args != null && args . length > && eventClass . isAssignableFrom ( args [ ] . getClass ( ) ) ) { getLogger ( ) . fine ( String . format ( "" , method . getName ( ) , listenerMethod . getName ( ) ) ) ; return listenerMethod . invoke ( controller , args ) ; } getLogger ( ) . fine ( String . format ( "" , method . getName ( ) , controller . getClass ( ) ) ) ; return method . invoke ( controller , args ) ; } } ) ; getLogger ( ) . fine ( String . format ( "" , listenerClass ) ) ; return proxy ; } private Method getAddListenerMethod ( Class < ? extends Component > componentClass , Class < ? > eventClass ) { Set < Method > methods = ReflectionUtils . getMethodsByNameAndParamCount ( componentClass , "" , ) ; for ( Method method : methods ) { Class < ? > listenerClass = method . getParameterTypes ( ) [ ] ; Method [ ] listenerMethods = listenerClass . getMethods ( ) ; for ( Method listenerMethod : listenerMethods ) { if ( listenerMethod . getParameterTypes ( ) . length == && listenerMethod . getParameterTypes ( ) [ ] . equals ( eventClass ) ) { return method ; } } } return null ; } private void bindDataSource ( Component componentRoot , Object controller , Method method , DataSource dataSource ) { String componentId = dataSource . value ( ) ; Component component = Clara . findComponentById ( componentRoot , componentId ) ; Class < ? > dataSourceClass = method . getReturnType ( ) ; try { if ( isContainer ( dataSourceClass ) && component instanceof Container . Viewer ) { ( ( Container . Viewer ) component ) . setContainerDataSource ( ( Container ) method . invoke ( controller ) ) ; } else if ( isProperty ( dataSourceClass ) && component instanceof Property . Viewer ) { ( ( Property . Viewer ) component ) . setPropertyDataSource ( ( Property ) method . invoke ( controller ) ) ; } else if ( isItem ( dataSourceClass ) && component instanceof Item . Viewer ) { ( ( Item . Viewer ) component ) . setItemDataSource ( ( Item ) method . invoke ( controller ) ) ; } } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } private boolean isContainer ( Class < ? > dataSourceClass ) { return Container . class . isAssignableFrom ( dataSourceClass ) ; } private boolean isItem ( Class < ? > dataSourceClass ) { return Item . class . isAssignableFrom ( dataSourceClass ) ; } private boolean isProperty ( Class < ? > dataSourceClass ) { return Property . class . isAssignableFrom ( dataSourceClass ) ; } } package org . vaadin . teemu . clara . binder . annotation ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . vaadin . ui . Button ; import com . vaadin . ui . Button . ClickEvent ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . METHOD ) public @ interface EventHandler { String value ( ) ; } package org . vaadin . teemu . clara . binder . annotation ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . vaadin . data . Container ; import com . vaadin . data . Item ; import com . vaadin . data . Property ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . METHOD ) public @ interface DataSource { String value ( ) ; } package org . vaadin . teemu . clara . util ; import java . lang . reflect . Method ; import java . util . HashSet ; import java . util . Set ; import com . vaadin . ui . Component ; public class ReflectionUtils { private ReflectionUtils ( ) { throw new AssertionError ( ) ; } public static Set < Method > getMethodsByNameAndParamCount ( Class < ? > clazz , String methodName , int numberOfParams ) { Set < Method > methods = new HashSet < Method > ( ) ; for ( Method method : clazz . getMethods ( ) ) { if ( method . getName ( ) . equals ( methodName ) && method . getParameterTypes ( ) . length == numberOfParams ) { methods . add ( method ) ; } } return methods ; } public static boolean isComponent ( Class < ? > componentClass ) { if ( componentClass != null ) { return Component . class . isAssignableFrom ( componentClass ) ; } else { return false ; } } } package org . vaadin . teemu . clara ; import java . io . InputStream ; import java . util . Iterator ; import org . vaadin . teemu . clara . binder . Binder ; import org . vaadin . teemu . clara . inflater . LayoutInflater ; import com . vaadin . ui . Component ; import com . vaadin . ui . ComponentContainer ; public class Clara { public static Component create ( InputStream xml ) { return create ( xml , null ) ; } public static Component create ( InputStream xml , Object controller , AttributeInterceptor ... interceptors ) { LayoutInflater inflater = new LayoutInflater ( ) ; if ( interceptors != null ) { for ( AttributeInterceptor interceptor : interceptors ) { inflater . addInterceptor ( interceptor ) ; } } Component result = inflater . inflate ( xml ) ; if ( controller != null ) { Binder binder = new Binder ( ) ; binder . bind ( result , controller ) ; } return result ; } public static Component findComponentById ( Component root , String componentId ) { if ( componentId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( componentId . equals ( root . getDebugId ( ) ) ) { return root ; } else if ( root instanceof ComponentContainer ) { for ( Iterator < Component > i = ( ( ComponentContainer ) root ) . getComponentIterator ( ) ; i . hasNext ( ) ; ) { Component c = findComponentById ( i . next ( ) , componentId ) ; if ( c != null ) { return c ; } } } return null ; } } package org . vaadin . teemu . clara . inflater ; public interface AttributeParser { boolean isSupported ( Class < ? > valueType ) ; Object getValueAs ( String value , Class < ? > valueType ) ; } package org . vaadin . teemu . clara . inflater ; import java . util . HashMap ; import java . util . Map ; import java . util . Stack ; import org . xml . sax . Attributes ; import org . xml . sax . SAXException ; import org . xml . sax . helpers . DefaultHandler ; import com . vaadin . ui . Component ; import com . vaadin . ui . ComponentContainer ; class LayoutInflaterContentHandler extends DefaultHandler { private static final String URN_NAMESPACE_ID = "" ; private static final String DEFAULT_NAMESPACE = "" + URN_NAMESPACE_ID + "" ; private static final String LAYOUT_ATTRIBUTE_NAMESPACE = "" ; private Stack < Component > componentStack = new Stack < Component > ( ) ; private ComponentContainer currentContainer ; private Component currentComponent ; private Component root ; private final ComponentManager componentFactory ; private final Map < String , Component > idMap = new HashMap < String , Component > ( ) ; public LayoutInflaterContentHandler ( ComponentManager componentFactory ) { this . componentFactory = componentFactory ; } public Component getRoot ( ) { return root ; } @ Override public void startElement ( String uri , String localName , String qName , Attributes attributes ) throws SAXException { super . startElement ( uri , localName , qName , attributes ) ; if ( uri == null || uri . length ( ) == ) { uri = DEFAULT_NAMESPACE ; } currentComponent = null ; if ( uri . startsWith ( "" + URN_NAMESPACE_ID + "" ) ) { String packageName = uri . substring ( ( "" + URN_NAMESPACE_ID + "" ) . length ( ) ) ; String className = localName ; Map < String , String > attributeMap = getAttributeMap ( attributes ) ; Map < String , String > layoutAttributeMap = getLayoutAttributeMap ( attributes ) ; currentComponent = componentFactory . createComponent ( packageName , className , attributeMap ) ; if ( currentComponent . getDebugId ( ) != null ) { idMap . put ( currentComponent . getDebugId ( ) , currentComponent ) ; } if ( root == null ) { root = currentComponent ; } if ( currentContainer != null ) { currentContainer . addComponent ( currentComponent ) ; componentFactory . applyLayoutAttributes ( currentContainer , currentComponent , layoutAttributeMap ) ; } if ( currentComponent instanceof ComponentContainer ) { currentContainer = ( ComponentContainer ) currentComponent ; } componentStack . push ( currentComponent ) ; } } private Map < String , String > getAttributeMap ( Attributes attributes ) { Map < String , String > attributeMap = new HashMap < String , String > ( attributes . getLength ( ) ) ; for ( int i = ; i < attributes . getLength ( ) ; i ++ ) { if ( ! attributes . getURI ( i ) . equals ( LAYOUT_ATTRIBUTE_NAMESPACE ) ) { String value = attributes . getValue ( i ) ; String name = attributes . getLocalName ( i ) ; if ( name . equals ( "" ) ) { if ( idMap . containsKey ( value ) ) { throw new LayoutInflaterException ( String . format ( "" , value ) ) ; } name = "" ; } attributeMap . put ( name , value ) ; } } return attributeMap ; } private Map < String , String > getLayoutAttributeMap ( Attributes attributes ) { Map < String , String > attributeMap = new HashMap < String , String > ( attributes . getLength ( ) ) ; for ( int i = ; i < attributes . getLength ( ) ; i ++ ) { if ( attributes . getURI ( i ) . equals ( LAYOUT_ATTRIBUTE_NAMESPACE ) ) { String value = attributes . getValue ( i ) ; String name = attributes . getLocalName ( i ) ; attributeMap . put ( name , value ) ; } } return attributeMap ; } @ Override public void endElement ( String uri , String localName , String qName ) throws SAXException { super . endElement ( uri , localName , qName ) ; Component component = componentStack . pop ( ) ; if ( component instanceof ComponentContainer ) { currentContainer = ( ComponentContainer ) component . getParent ( ) ; } } public Map < String , Component > getIdMap ( ) { return idMap ; } } package org . vaadin . teemu . clara . inflater ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . logging . Logger ; import org . vaadin . teemu . clara . AttributeContext ; import org . vaadin . teemu . clara . AttributeInterceptor ; import org . vaadin . teemu . clara . util . ReflectionUtils ; import com . vaadin . ui . Component ; import com . vaadin . ui . ComponentContainer ; public class DefaultComponentManager implements ComponentManager { private List < AttributeParser > attributeParsers = new ArrayList < AttributeParser > ( ) ; private List < AttributeInterceptor > interceptors = new ArrayList < AttributeInterceptor > ( ) ; private Logger getLogger ( ) { return Logger . getLogger ( DefaultComponentManager . class . getName ( ) ) ; } public DefaultComponentManager ( ) { addAttributeParser ( new PrimitiveAttributeParser ( ) ) ; addAttributeParser ( new VaadinAttributeParser ( ) ) ; } public void addAttributeParser ( AttributeParser handler ) { attributeParsers . add ( handler ) ; } public void removeAttributeParser ( AttributeParser handler ) { attributeParsers . remove ( handler ) ; } public Component createComponent ( String namespace , String name , Map < String , String > attributes ) throws ComponentInstantiationException { try { Class < ? extends Component > componentClass = resolveComponentClass ( namespace , name ) ; Component newComponent = componentClass . newInstance ( ) ; handleAttributes ( newComponent , attributes ) ; return newComponent ; } catch ( Exception e ) { throw createException ( e , namespace , name ) ; } } protected ComponentInstantiationException createException ( Exception e , String namespace , String name ) { String message = String . format ( "" , namespace , name ) ; if ( e != null ) { return new ComponentInstantiationException ( message , e ) ; } else { return new ComponentInstantiationException ( message ) ; } } @ SuppressWarnings ( "" ) protected Class < ? extends Component > resolveComponentClass ( String namespace , String name ) throws ClassNotFoundException { String qualifiedClassName = namespace + "" + name ; Class < ? > componentClass = null ; componentClass = Class . forName ( qualifiedClassName ) ; if ( ReflectionUtils . isComponent ( componentClass ) ) { return ( Class < ? extends Component > ) componentClass ; } else { throw new IllegalArgumentException ( String . format ( "" , componentClass . getName ( ) , Component . class . getName ( ) ) ) ; } } protected void handleAttributes ( Component component , Map < String , String > attributes ) { getLogger ( ) . fine ( attributes . toString ( ) ) ; try { for ( Map . Entry < String , String > attribute : attributes . entrySet ( ) ) { Method setter = getSetter ( attribute . getKey ( ) , component . getClass ( ) ) ; if ( setter != null ) { AttributeParser handler = getHandlerFor ( setter . getParameterTypes ( ) [ ] ) ; if ( handler != null ) { String attributeValue = attribute . getValue ( ) ; if ( attributeValue == null || attributeValue . length ( ) == ) { invokeWithInterceptors ( setter , component , attributeValue ) ; } else { invokeWithInterceptors ( setter , component , handler . getValueAs ( attributeValue , setter . getParameterTypes ( ) [ ] ) ) ; } } } } } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } protected void invokeWithInterceptors ( final Method methodToInvoke , final Object obj , final Object ... args ) throws IllegalArgumentException , IllegalAccessException , InvocationTargetException { if ( interceptors . isEmpty ( ) ) { methodToInvoke . invoke ( obj , args ) ; } else { final LinkedList < AttributeInterceptor > interceptorsCopy = new LinkedList < AttributeInterceptor > ( interceptors ) ; AttributeInterceptor interceptor = interceptorsCopy . pop ( ) ; interceptor . intercept ( new AttributeContext ( methodToInvoke , args . length > ? args [ ] : args [ ] ) { @ Override public void proceed ( ) throws Exception { if ( interceptorsCopy . size ( ) > ) { interceptorsCopy . pop ( ) . intercept ( this ) ; } else { if ( args . length > ) { methodToInvoke . invoke ( obj , args [ ] , this . getValue ( ) ) ; } else { methodToInvoke . invoke ( obj , this . getValue ( ) ) ; } } } } ) ; } } protected AttributeParser getHandlerFor ( Class < ? > type ) { for ( AttributeParser handler : attributeParsers ) { if ( handler . isSupported ( type ) ) { return handler ; } } return null ; } public void applyLayoutAttributes ( ComponentContainer container , Component component , Map < String , String > attributes ) { if ( ! component . getParent ( ) . equals ( container ) ) { throw new IllegalStateException ( "" ) ; } try { for ( Map . Entry < String , String > attribute : attributes . entrySet ( ) ) { Method layoutMethod = getLayoutMethod ( container . getClass ( ) , attribute . getKey ( ) ) ; if ( layoutMethod != null ) { AttributeParser handler = getHandlerFor ( layoutMethod . getParameterTypes ( ) [ ] ) ; if ( handler != null ) { invokeWithInterceptors ( layoutMethod , container , component , handler . getValueAs ( attribute . getValue ( ) , layoutMethod . getParameterTypes ( ) [ ] ) ) ; } } } } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } private Method getSetter ( String propertyName , Class < ? extends Component > componentClass ) { Set < Method > writeMethods = ReflectionUtils . getMethodsByNameAndParamCount ( componentClass , "" + capitalize ( propertyName ) , ) ; return selectPreferredMethod ( writeMethods , ) ; } private static String capitalize ( String propertyName ) { if ( propertyName . length ( ) > ) { return propertyName . substring ( , ) . toUpperCase ( ) + propertyName . substring ( ) ; } return "" ; } private Method getLayoutMethod ( Class < ? extends ComponentContainer > layoutClass , String propertyName ) { String methodToLookFor = "" + propertyName . substring ( , ) . toUpperCase ( ) + propertyName . substring ( ) ; Set < Method > settersWithTwoParams = ReflectionUtils . getMethodsByNameAndParamCount ( layoutClass , methodToLookFor , ) ; return selectPreferredMethod ( settersWithTwoParams , ) ; } private Method selectPreferredMethod ( Set < Method > methods , int dataParamIndex ) { Method candidate = null ; for ( Method method : methods ) { if ( dataParamIndex > && ! ReflectionUtils . isComponent ( method . getParameterTypes ( ) [ ] ) ) { continue ; } Class < ? > parameterType = method . getParameterTypes ( ) [ dataParamIndex ] ; AttributeParser handler = getHandlerFor ( parameterType ) ; if ( handler != null && ! ( handler instanceof PrimitiveAttributeParser ) ) { return method ; } if ( method . isAnnotationPresent ( Deprecated . class ) || ! parameterType . equals ( String . class ) ) { candidate = method ; } else { return method ; } } return candidate ; } @ Override public void addInterceptor ( AttributeInterceptor attributeInterceptor ) { interceptors . add ( attributeInterceptor ) ; } @ Override public void removeInterceptor ( AttributeInterceptor attributeInterceptor ) { interceptors . remove ( attributeInterceptor ) ; } } package org . vaadin . teemu . clara . inflater ; @ SuppressWarnings ( "" ) public class LayoutInflaterException extends RuntimeException { public LayoutInflaterException ( String message ) { super ( message ) ; } public LayoutInflaterException ( String message , Throwable e ) { super ( message , e ) ; } public LayoutInflaterException ( Throwable e ) { super ( e ) ; } } package org . vaadin . teemu . clara . inflater ; @ SuppressWarnings ( "" ) public class ComponentInstantiationException extends RuntimeException { public ComponentInstantiationException ( ) { super ( ) ; } public ComponentInstantiationException ( String message ) { super ( message ) ; } public ComponentInstantiationException ( String message , Throwable e ) { super ( message , e ) ; } } package org . vaadin . teemu . clara . inflater ; import java . util . Arrays ; import java . util . List ; public class PrimitiveAttributeParser implements AttributeParser { @ SuppressWarnings ( "" ) private static final List < Class < ? > > supportedClasses = Arrays . asList ( String . class , Object . class , Boolean . class , Integer . class , Byte . class , Short . class , Long . class , Character . class , Float . class , Double . class ) ; public boolean isSupported ( Class < ? > valueType ) { return valueType != null && ( valueType . isPrimitive ( ) || supportedClasses . contains ( valueType ) ) ; } public Object getValueAs ( String value , Class < ? > type ) { if ( type == String . class || type == Object . class ) { return value ; } if ( type == Boolean . TYPE || type == Boolean . class ) { return Boolean . valueOf ( value ) ; } if ( type == Integer . TYPE || type == Integer . class ) { return Integer . valueOf ( value ) ; } if ( type == Byte . TYPE || type == Byte . class ) { return Byte . valueOf ( value ) ; } if ( type == Short . TYPE || type == Short . class ) { return Short . valueOf ( value ) ; } if ( type == Long . TYPE || type == Long . class ) { return Long . valueOf ( value ) ; } if ( type == Character . TYPE || type == Character . class ) { return value . charAt ( ) ; } if ( type == Float . TYPE || type == Float . class ) { return Float . valueOf ( value ) ; } if ( type == Double . TYPE || type == Double . class ) { return Double . valueOf ( value ) ; } return null ; } } package org . vaadin . teemu . clara . inflater ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import org . vaadin . teemu . clara . AttributeInterceptor ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; import org . xml . sax . XMLReader ; import org . xml . sax . helpers . XMLReaderFactory ; import com . vaadin . Application ; import com . vaadin . service . ApplicationContext ; import com . vaadin . ui . Component ; public class LayoutInflater { private ComponentManager componentManager = new DefaultComponentManager ( ) ; public void setComponentManager ( ComponentManager componentManager ) { this . componentManager = componentManager ; } public Component inflate ( Application app , String xmlFile ) throws LayoutInflaterException { File layoutFile = getLayoutFile ( app . getContext ( ) , xmlFile ) ; try { return inflate ( new FileInputStream ( layoutFile ) ) ; } catch ( FileNotFoundException e ) { throw new LayoutInflaterException ( "" + layoutFile . getAbsolutePath ( ) + "" ) ; } } public Component inflate ( InputStream xml ) throws LayoutInflaterException { try { LayoutInflaterContentHandler handler = new LayoutInflaterContentHandler ( componentManager ) ; XMLReader parser = XMLReaderFactory . createXMLReader ( ) ; parser . setContentHandler ( handler ) ; parser . parse ( new InputSource ( xml ) ) ; return handler . getRoot ( ) ; } catch ( SAXException e ) { throw new LayoutInflaterException ( e ) ; } catch ( IOException e ) { throw new LayoutInflaterException ( e ) ; } catch ( ComponentInstantiationException e ) { throw new LayoutInflaterException ( e . getMessage ( ) , e ) ; } } public void addInterceptor ( AttributeInterceptor attributeInterceptor ) { componentManager . addInterceptor ( attributeInterceptor ) ; } public void removeInterceptor ( AttributeInterceptor attributeInterceptor ) { componentManager . removeInterceptor ( attributeInterceptor ) ; } private static File getLayoutFile ( ApplicationContext context , String filepath ) { return new File ( context . getBaseDirectory ( ) . getAbsoluteFile ( ) + File . separator + "" + File . separator + "" + File . separator + filepath ) ; } } package org . vaadin . teemu . clara . inflater ; import java . util . Map ; import org . vaadin . teemu . clara . AttributeInterceptor ; import com . vaadin . ui . Component ; import com . vaadin . ui . ComponentContainer ; public interface ComponentManager { Component createComponent ( String namespace , String name , Map < String , String > attributes ) throws ComponentInstantiationException ; void applyLayoutAttributes ( ComponentContainer container , Component component , Map < String , String > attributes ) ; void addInterceptor ( AttributeInterceptor attributeInterceptor ) ; void removeInterceptor ( AttributeInterceptor attributeInterceptor ) ; } package org . vaadin . teemu . clara . inflater ; import java . util . HashMap ; import java . util . Map ; import com . vaadin . ui . Alignment ; import com . vaadin . ui . Layout . MarginInfo ; public class VaadinAttributeParser implements AttributeParser { protected static final Map < String , Alignment > alignmentMap ; static { alignmentMap = new HashMap < String , Alignment > ( ) ; alignmentMap . put ( "" , Alignment . BOTTOM_CENTER ) ; alignmentMap . put ( "" , Alignment . BOTTOM_LEFT ) ; alignmentMap . put ( "" , Alignment . BOTTOM_RIGHT ) ; alignmentMap . put ( "" , Alignment . MIDDLE_CENTER ) ; alignmentMap . put ( "" , Alignment . MIDDLE_LEFT ) ; alignmentMap . put ( "" , Alignment . MIDDLE_RIGHT ) ; alignmentMap . put ( "" , Alignment . TOP_CENTER ) ; alignmentMap . put ( "" , Alignment . TOP_LEFT ) ; alignmentMap . put ( "" , Alignment . TOP_RIGHT ) ; } public boolean isSupported ( Class < ? > valueType ) { return valueType != null && ( valueType == MarginInfo . class || valueType == Alignment . class ) ; } public Object getValueAs ( String value , Class < ? > valueType ) { if ( valueType == MarginInfo . class ) { return parseMarginInfo ( value ) ; } else if ( valueType == Alignment . class ) { return parseAlignment ( value ) ; } return null ; } private Object parseAlignment ( String value ) { return alignmentMap . get ( value ) ; } protected MarginInfo parseMarginInfo ( String margin ) { if ( margin . length ( ) > ) { String [ ] margins = margin . split ( "" ) ; if ( margins . length == ) { return new MarginInfo ( Boolean . valueOf ( margins [ ] ) , Boolean . valueOf ( margins [ ] ) , Boolean . valueOf ( margins [ ] ) , Boolean . valueOf ( margins [ ] ) ) ; } } return new MarginInfo ( Boolean . valueOf ( margin ) ) ; } } package net . sf . sveditor . core . templates ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import org . osgi . framework . Bundle ; public class PluginInStreamProvider implements ITemplateInStreamProvider { Bundle fBundle ; public PluginInStreamProvider ( Bundle bundle ) { fBundle = bundle ; } public InputStream openStream ( String path ) { URL url = fBundle . getEntry ( path ) ; InputStream in = null ; if ( url != null ) { try { in = url . openStream ( ) ; } catch ( IOException e ) { } } return in ; } public void closeStream ( InputStream in ) { try { in . close ( ) ; } catch ( IOException e ) { } } } package net . sf . sveditor . core . templates ; import java . util . List ; public interface IExternalTemplatePathProvider { List < String > getExternalTemplatePath ( ) ; } package net . sf . sveditor . core . templates ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; public class TemplateFSFileCreator implements ITemplateFileCreator { private File fRoot ; public TemplateFSFileCreator ( File root ) { fRoot = root ; } public void createFile ( String path , InputStream content ) { File file = new File ( fRoot , path ) ; byte tmp [ ] = new byte [ ] ; int len ; if ( ! file . getParentFile ( ) . exists ( ) ) { file . getParentFile ( ) . mkdirs ( ) ; } try { FileOutputStream fos = new FileOutputStream ( file ) ; while ( ( len = content . read ( tmp , , tmp . length ) ) > ) { fos . write ( tmp , , len ) ; } fos . close ( ) ; } catch ( IOException e ) { } } public OutputStream openStream ( String path ) { File target = new File ( fRoot , path ) ; try { return new FileOutputStream ( target ) ; } catch ( IOException e ) { } return null ; } public void closeStream ( OutputStream out ) { try { out . close ( ) ; } catch ( IOException e ) { } } } package net . sf . sveditor . core . templates ; import java . io . File ; import java . io . InputStream ; import java . util . List ; public abstract class AbstractExternalTemplateFinder extends AbstractTemplateFinder { private ITemplateInStreamProvider fInProvider ; public AbstractExternalTemplateFinder ( ITemplateInStreamProvider in_provider ) { super ( ) ; fInProvider = in_provider ; } @ Override public void find ( ) { List < String > paths = findTemplatePaths ( ) ; for ( String path : paths ) { fLog . debug ( LEVEL_MIN , "" + path ) ; InputStream in = openFile ( path ) ; File tmpl_dir = new File ( path ) . getParentFile ( ) ; if ( in == null ) { fLog . error ( "" + path + "" ) ; continue ; } SVTParser p = new SVTParser ( tmpl_dir . getPath ( ) , fInProvider ) ; try { p . parse ( in ) ; } catch ( Exception e ) { fLog . error ( "" + path + "" + e . getMessage ( ) , e ) ; } for ( TemplateCategory c : p . getCategories ( ) ) { fLog . debug ( LEVEL_MID , "" + c . getId ( ) + "" + c . getName ( ) ) ; } fCategories . addAll ( p . getCategories ( ) ) ; for ( TemplateInfo ti : p . getTemplates ( ) ) { fTemplates . add ( ti ) ; fLog . debug ( LEVEL_MID , "" + ti . getId ( ) + "" + ti . getName ( ) ) ; if ( ! ti . getTemplates ( ) . iterator ( ) . hasNext ( ) ) { List < String > files = listFiles ( tmpl_dir . getPath ( ) ) ; for ( String file : files ) { File f = new File ( file ) ; if ( ! f . getName ( ) . endsWith ( "" ) && ! f . getName ( ) . startsWith ( "" ) ) { File fn = new File ( file ) ; ti . addTemplate ( file , fn . getName ( ) ) ; } } } } closeStream ( in ) ; } } protected abstract List < String > findTemplatePaths ( ) ; protected abstract List < String > listFiles ( String path ) ; protected abstract InputStream openFile ( String path ) ; protected abstract void closeStream ( InputStream in ) ; } package net . sf . sveditor . core . templates ; import java . io . InputStream ; public interface ITemplateFileCreator { void createFile ( String path , InputStream content ) ; } package net . sf . sveditor . core . templates ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . log . LogFactory ; public class FSExternalTemplateFinder extends AbstractExternalTemplateFinder { private File fPath ; public FSExternalTemplateFinder ( File path ) { super ( new FSInStreamProvider ( ) ) ; fPath = path ; fLog = LogFactory . getLogHandle ( "" ) ; } @ Override protected List < String > findTemplatePaths ( ) { List < String > template_paths = new ArrayList < String > ( ) ; findTemplatePaths ( template_paths , fPath ) ; return template_paths ; } private void findTemplatePaths ( List < String > paths , File path ) { File files [ ] = path . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { if ( file . isDirectory ( ) ) { findTemplatePaths ( paths , file ) ; } else if ( file . getName ( ) . endsWith ( "" ) ) { paths . add ( file . getAbsolutePath ( ) ) ; } } } } @ Override protected List < String > listFiles ( String path ) { File file = new File ( path ) ; List < String > ret = new ArrayList < String > ( ) ; if ( file . isDirectory ( ) ) { File files [ ] = file . listFiles ( ) ; if ( files != null ) { for ( File f : files ) { if ( f . isFile ( ) ) { ret . add ( f . getAbsolutePath ( ) ) ; } } } } return ret ; } @ Override protected InputStream openFile ( String path ) { InputStream in = null ; try { in = new FileInputStream ( path ) ; } catch ( IOException e ) { } return in ; } @ Override protected void closeStream ( InputStream in ) { try { if ( in != null ) { in . close ( ) ; } } catch ( IOException e ) { } } } package net . sf . sveditor . core . templates ; import java . io . InputStream ; public interface ITemplateInStreamProvider { InputStream openStream ( String path ) ; void closeStream ( InputStream in ) ; } package net . sf . sveditor . core . templates ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; import org . xml . sax . ErrorHandler ; import org . xml . sax . SAXException ; import org . xml . sax . SAXParseException ; public class SVTParser { private Document fDocument ; private List < TemplateInfo > fTemplates ; private List < TemplateCategory > fCategories ; private LogHandle fLog ; private ITemplateInStreamProvider fInProvider ; private String fTemplateBase ; public SVTParser ( String template_base , ITemplateInStreamProvider in_provider ) { fTemplates = new ArrayList < TemplateInfo > ( ) ; fCategories = new ArrayList < TemplateCategory > ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; fInProvider = in_provider ; fTemplateBase = template_base ; } public void parse ( InputStream in ) throws Exception { DocumentBuilderFactory f = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder b = f . newDocumentBuilder ( ) ; fTemplates . clear ( ) ; fCategories . clear ( ) ; b . setErrorHandler ( fErrorHandler ) ; fDocument = b . parse ( in ) ; NodeList sv_template_list = fDocument . getElementsByTagName ( "" ) ; if ( sv_template_list . getLength ( ) == ) { return ; } Element sv_template = ( Element ) sv_template_list . item ( ) ; NodeList category_list = sv_template . getElementsByTagName ( "" ) ; for ( int i = ; i < category_list . getLength ( ) ; i ++ ) { addCategory ( ( Element ) category_list . item ( i ) ) ; } NodeList template_list = sv_template . getElementsByTagName ( "" ) ; for ( int i = ; i < template_list . getLength ( ) ; i ++ ) { addTemplate ( ( Element ) template_list . item ( i ) ) ; } } public List < TemplateCategory > getCategories ( ) { return fCategories ; } public List < TemplateInfo > getTemplates ( ) { return fTemplates ; } private void addCategory ( Element category ) { String name = category . getAttribute ( "" ) ; String id = category . getAttribute ( "" ) ; String parent = category . getAttribute ( "" ) ; if ( parent == null ) { parent = "" ; } TemplateCategory c = new TemplateCategory ( id , name , parent ) ; NodeList dl = category . getElementsByTagName ( "" ) ; if ( dl . getLength ( ) > ) { Element desc = ( Element ) dl . item ( ) ; c . setDescription ( desc . getTextContent ( ) ) ; } if ( ! fCategories . contains ( c ) ) { fCategories . add ( c ) ; } } private void addTemplate ( Element template ) { String name = template . getAttribute ( "" ) ; String id = template . getAttribute ( "" ) ; String category = template . getAttribute ( "" ) ; TemplateInfo t = new TemplateInfo ( id , name , category , "" , fInProvider ) ; NodeList description = template . getElementsByTagName ( "" ) ; if ( description . getLength ( ) > ) { Element e = ( Element ) description . item ( ) ; t . setDescription ( e . getTextContent ( ) ) ; } NodeList files = template . getElementsByTagName ( "" ) ; if ( files . getLength ( ) > ) { Element e = ( Element ) files . item ( ) ; NodeList file_list = e . getElementsByTagName ( "" ) ; for ( int i = ; i < file_list . getLength ( ) ; i ++ ) { Element file = ( Element ) file_list . item ( i ) ; String filename = file . getAttribute ( "" ) ; String tmpl_path = file . getAttribute ( "" ) ; filename = filename . trim ( ) ; tmpl_path = tmpl_path . trim ( ) ; t . addTemplate ( fTemplateBase + "" + tmpl_path , filename ) ; } } NodeList parameters = template . getElementsByTagName ( "" ) ; if ( parameters . getLength ( ) > ) { Element e = ( Element ) parameters . item ( ) ; NodeList parameters_list = e . getElementsByTagName ( "" ) ; for ( int i = ; i < parameters_list . getLength ( ) ; i ++ ) { Element parameter = ( Element ) parameters_list . item ( i ) ; TemplateParameterType p_type = TemplateParameterType . ParameterType_Id ; String p_name = parameter . getAttribute ( "" ) ; String p_type_s = parameter . getAttribute ( "" ) ; String p_dflt = parameter . getAttribute ( "" ) ; String p_ext = parameter . getAttribute ( "" ) ; String p_restr = parameter . getAttribute ( "" ) ; if ( p_type_s . equals ( "" ) ) { p_type = TemplateParameterType . ParameterType_Class ; } else if ( p_type_s . equals ( "" ) ) { p_type = TemplateParameterType . ParameterType_Id ; } else if ( p_type_s . equals ( "" ) ) { p_type = TemplateParameterType . ParameterType_Int ; } TemplateParameter p = new TemplateParameter ( p_type , p_name , p_dflt , p_ext ) ; if ( p_restr != null && ! p_restr . trim ( ) . equals ( "" ) ) { String restr [ ] = p_restr . split ( "" ) ; for ( String r : restr ) { r = r . trim ( ) ; p . addValue ( r ) ; } } t . addParameter ( p ) ; } } fTemplates . add ( t ) ; } private ErrorHandler fErrorHandler = new ErrorHandler ( ) { public void error ( SAXParseException arg0 ) throws SAXException { throw arg0 ; } public void fatalError ( SAXParseException arg0 ) throws SAXException { throw arg0 ; } public void warning ( SAXParseException arg0 ) throws SAXException { } } ; } package net . sf . sveditor . core . templates ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; public class FSInStreamProvider implements ITemplateInStreamProvider { public InputStream openStream ( String path ) { File file = new File ( path ) ; InputStream in = null ; try { in = new FileInputStream ( file ) ; } catch ( IOException e ) { } return in ; } public void closeStream ( InputStream in ) { try { in . close ( ) ; } catch ( IOException e ) { } } } package net . sf . sveditor . core . templates ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . log . LogFactory ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; public class WSExternalTemplateFinder extends AbstractExternalTemplateFinder { private IContainer fPath ; public WSExternalTemplateFinder ( IContainer path ) { super ( new WSInStreamProvider ( ) ) ; fPath = path ; fLog = LogFactory . getLogHandle ( "" ) ; } @ Override protected List < String > findTemplatePaths ( ) { List < String > templates = new ArrayList < String > ( ) ; findTemplatePaths ( templates , fPath ) ; return templates ; } private void findTemplatePaths ( List < String > templates , IContainer parent ) { IResource resources [ ] = null ; try { resources = parent . members ( ) ; } catch ( CoreException e ) { } if ( resources != null ) { for ( IResource r : resources ) { if ( r instanceof IFile && r . getName ( ) . endsWith ( "" ) ) { templates . add ( ( ( IFile ) r ) . getFullPath ( ) . toOSString ( ) ) ; } else if ( r instanceof IContainer ) { findTemplatePaths ( templates , ( IContainer ) r ) ; } } } } @ Override protected List < String > listFiles ( String path ) { List < String > files = new ArrayList < String > ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IContainer c = null ; try { c = root . getFolder ( new Path ( path ) ) ; } catch ( IllegalArgumentException e ) { } if ( c == null ) { if ( path . startsWith ( "" ) ) { String pname = path . substring ( ) ; try { c = root . getProject ( pname ) ; } catch ( IllegalArgumentException e ) { } } } if ( c != null ) { IResource resources [ ] = null ; try { resources = c . members ( ) ; } catch ( CoreException e ) { } if ( resources != null ) { for ( IResource r : resources ) { if ( r instanceof IFile ) { files . add ( ( ( IFile ) r ) . getFullPath ( ) . toOSString ( ) ) ; } } } } return files ; } @ Override protected InputStream openFile ( String path ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; InputStream in = null ; IFile file = root . getFile ( new Path ( path ) ) ; if ( file . exists ( ) ) { for ( int i = ; i < ; i ++ ) { try { in = file . getContents ( ) ; break ; } catch ( CoreException e ) { fLog . error ( "" + path + "" + e . getMessage ( ) , e ) ; if ( e . getMessage ( ) . contains ( "" ) ) { try { file . getParent ( ) . refreshLocal ( IResource . DEPTH_INFINITE , new NullProgressMonitor ( ) ) ; } catch ( CoreException e2 ) { } } } } } else { fLog . debug ( LEVEL_MID , "" + path + "" ) ; } return in ; } @ Override protected void closeStream ( InputStream in ) { try { in . close ( ) ; } catch ( IOException e ) { } } } package net . sf . sveditor . core . templates ; import java . io . IOException ; import java . io . InputStream ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Path ; public class WSInStreamProvider implements ITemplateInStreamProvider { public InputStream openStream ( String path ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; InputStream in = null ; try { IFile file = root . getFile ( new Path ( path ) ) ; if ( file . exists ( ) ) { in = file . getContents ( ) ; } } catch ( CoreException e ) { } return in ; } public void closeStream ( InputStream in ) { try { in . close ( ) ; } catch ( IOException e ) { } } } package net . sf . sveditor . core . templates ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . Set ; public class DynamicTemplateParameterProvider implements ITemplateParameterProvider { public boolean providesParameter ( String id ) { return ( id . equals ( "" ) || id . equals ( "" ) ) ; } public String getParameterValue ( String id , String arg ) { if ( id . equals ( "" ) ) { return System . getProperty ( "" ) ; } else if ( id . equals ( "" ) ) { SimpleDateFormat format ; if ( arg != null ) { format = new SimpleDateFormat ( arg ) ; } else { format = new SimpleDateFormat ( "" ) ; } return format . format ( new Date ( ) ) ; } else { return null ; } } } package net . sf . sveditor . core . templates ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . log . LogFactory ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . Platform ; import org . osgi . framework . Bundle ; public class ExtensionTemplateFinder extends AbstractTemplateFinder { public ExtensionTemplateFinder ( ) { super ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public void find ( ) { IExtensionRegistry ext_rgy = Platform . getExtensionRegistry ( ) ; IExtensionPoint ext_pt = ext_rgy . getExtensionPoint ( SVCorePlugin . PLUGIN_ID , "" ) ; IExtension ext_list [ ] = ext_pt . getExtensions ( ) ; for ( IExtension ext : ext_list ) { IConfigurationElement ce_l [ ] = ext . getConfigurationElements ( ) ; for ( IConfigurationElement ce : ce_l ) { String name = ce . getName ( ) ; if ( name . equals ( "" ) ) { addCategory ( ce ) ; } else if ( name . equals ( "" ) ) { addTemplate ( ce ) ; } else { fLog . error ( "" + name + "" ) ; } } } } private void addCategory ( IConfigurationElement ce ) { String id = ce . getAttribute ( "" ) ; String name = ce . getAttribute ( "" ) ; String parent = ce . getAttribute ( "" ) ; TemplateCategory c = new TemplateCategory ( id , name , parent ) ; for ( IConfigurationElement ci : ce . getChildren ( ) ) { if ( ci . getName ( ) . equals ( "" ) ) { c . setDescription ( ci . getValue ( ) ) ; } } fCategories . add ( c ) ; } private void addTemplate ( IConfigurationElement ce ) { String id = ce . getAttribute ( "" ) ; String name = ce . getAttribute ( "" ) ; String category = ce . getAttribute ( "" ) ; String description = "" ; Bundle bundle = Platform . getBundle ( ce . getContributor ( ) . getName ( ) ) ; for ( IConfigurationElement ce_c : ce . getChildren ( ) ) { if ( ce_c . getName ( ) . equals ( "" ) ) { description = ce_c . getValue ( ) ; } } TemplateInfo info = new TemplateInfo ( id , name , category , description , new PluginInStreamProvider ( bundle ) ) ; fTemplates . add ( info ) ; for ( IConfigurationElement ce_c : ce . getChildren ( ) ) { if ( ce_c . getName ( ) . equals ( "" ) ) { for ( IConfigurationElement tmpl : ce_c . getChildren ( ) ) { String template = tmpl . getAttribute ( "" ) ; String tmpl_name = tmpl . getAttribute ( "" ) ; info . addTemplate ( new Tuple < String , String > ( template , tmpl_name ) ) ; } } else if ( ce_c . getName ( ) . equals ( "" ) ) { for ( IConfigurationElement p : ce_c . getChildren ( ) ) { if ( p . getName ( ) . equals ( "" ) ) { String p_type = p . getAttribute ( "" ) ; String p_name = p . getAttribute ( "" ) ; String p_dflt = p . getAttribute ( "" ) ; String p_ext_from = p . getAttribute ( "" ) ; String p_restr = p . getAttribute ( "" ) ; TemplateParameterType type = null ; if ( p_type . equals ( "" ) ) { type = TemplateParameterType . ParameterType_Int ; } else if ( p_type . equals ( "" ) ) { type = TemplateParameterType . ParameterType_Id ; } else if ( p_type . equals ( "" ) ) { type = TemplateParameterType . ParameterType_Class ; } else { fLog . error ( "" + p_type + "" ) ; continue ; } TemplateParameter tp = new TemplateParameter ( type , p_name , p_dflt , p_ext_from ) ; if ( p_restr != null && ! p_restr . trim ( ) . equals ( "" ) ) { String r [ ] = p_restr . split ( "" ) ; for ( String rs : r ) { rs = rs . trim ( ) ; if ( ! rs . equals ( "" ) ) { tp . addValue ( rs ) ; } } } info . addParameter ( tp ) ; } } } } } } package net . sf . sveditor . core . templates ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . Tuple ; public class TemplateInfo { private String fId ; private String fName ; private String fCategoryId ; private String fDescription ; private List < Tuple < String , String > > fTemplateList ; private List < TemplateParameter > fParameters ; private ITemplateInStreamProvider fStreamProvider ; public TemplateInfo ( String id , String name , String category_id , String description , ITemplateInStreamProvider stream_provider ) { fId = id ; fName = name ; fCategoryId = ( category_id != null ) ? category_id : "" ; fDescription = description ; fTemplateList = new ArrayList < Tuple < String , String > > ( ) ; fParameters = new ArrayList < TemplateParameter > ( ) ; fStreamProvider = stream_provider ; } public String getId ( ) { return fId ; } public String getName ( ) { return fName ; } public String getCategoryId ( ) { return fCategoryId ; } public void setCategoryId ( String id ) { fCategoryId = id ; } public void setDescription ( String description ) { fDescription = description ; } public String getDescription ( ) { return fDescription ; } public Iterable < Tuple < String , String > > getTemplates ( ) { return new Iterable < Tuple < String , String > > ( ) { public Iterator < Tuple < String , String > > iterator ( ) { return fTemplateList . iterator ( ) ; } } ; } public void addTemplate ( String template , String filename ) { addTemplate ( new Tuple < String , String > ( template , filename ) ) ; } public void addTemplate ( Tuple < String , String > template ) { fTemplateList . add ( template ) ; } public void addParameter ( TemplateParameter p ) { fParameters . add ( p ) ; } public List < TemplateParameter > getParameters ( ) { return fParameters ; } public InputStream openTemplate ( String path ) { return fStreamProvider . openStream ( path ) ; } public void closeTemplate ( InputStream in ) { fStreamProvider . closeStream ( in ) ; } } package net . sf . sveditor . core . templates ; import java . util . ArrayList ; import java . util . List ; public class TemplateParameter { private TemplateParameterType fType ; private String fName ; private String fDefault ; private String fValue ; private String fExtFrom ; private List < String > fValues ; public TemplateParameter ( TemplateParameterType type , String name , String dflt , String ext_from ) { fType = type ; fName = name ; fDefault = dflt ; fValue = dflt ; fExtFrom = ext_from ; fValues = new ArrayList < String > ( ) ; } public TemplateParameterType getType ( ) { return fType ; } public String getTypeName ( ) { switch ( fType ) { case ParameterType_Id : { if ( fValues . size ( ) == ) { return "" ; } else { return "" ; } } case ParameterType_Class : return "" ; case ParameterType_Int : return "" ; default : return "" ; } } public String getName ( ) { return fName ; } public String getDefault ( ) { return fDefault ; } public String getValue ( ) { return fValue ; } public void setValue ( String val ) { fValue = val ; } public String getExtFrom ( ) { return fExtFrom ; } public List < String > getValues ( ) { return fValues ; } public void addValue ( String value ) { if ( ! fValues . contains ( value ) ) { fValues . add ( value ) ; } } public TemplateParameter duplicate ( ) { TemplateParameter p = new TemplateParameter ( fType , fName , fDefault , fExtFrom ) ; p . setValue ( fValue ) ; for ( String v : fValues ) { p . addValue ( v ) ; } return p ; } } package net . sf . sveditor . core . templates ; public enum TemplateParameterType { ParameterType_Id , ParameterType_Int , ParameterType_Class } package net . sf . sveditor . core . templates ; import java . io . File ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . resources . IContainer ; public class TemplateRegistry implements ILogLevel { private static LogHandle fLog ; private List < TemplateCategory > fCategories ; private List < TemplateInfo > fTemplates ; private Map < String , List < TemplateInfo > > fCategoryMap ; private List < IExternalTemplatePathProvider > fPathProviders ; private boolean fLoadExtPoints ; static { fLog = LogFactory . getLogHandle ( "" ) ; } public TemplateRegistry ( boolean load_exts ) { fCategories = new ArrayList < TemplateCategory > ( ) ; fTemplates = new ArrayList < TemplateInfo > ( ) ; fCategoryMap = new HashMap < String , List < TemplateInfo > > ( ) ; fPathProviders = new ArrayList < IExternalTemplatePathProvider > ( ) ; fLoadExtPoints = load_exts ; load_extensions ( ) ; } public void addPathProvider ( IExternalTemplatePathProvider p ) { fPathProviders . add ( p ) ; } public void clearPathProviders ( ) { fPathProviders . clear ( ) ; } public List < TemplateCategory > getCategories ( ) { return fCategories ; } public List < String > getCategoryNames ( ) { List < String > ret = new ArrayList < String > ( ) ; for ( TemplateCategory c : fCategories ) { ret . add ( c . getName ( ) ) ; } return ret ; } public List < String > getCategoryIDs ( ) { List < String > ret = new ArrayList < String > ( ) ; for ( TemplateCategory c : fCategories ) { ret . add ( c . getId ( ) ) ; } return ret ; } public List < TemplateInfo > getTemplates ( String id ) { List < TemplateInfo > ret = new ArrayList < TemplateInfo > ( ) ; if ( id == null ) { id = "" ; } if ( fCategoryMap . containsKey ( id ) ) { ret . addAll ( fCategoryMap . get ( id ) ) ; } return ret ; } public TemplateInfo findTemplate ( String id ) { for ( TemplateInfo info : fTemplates ) { if ( info . getId ( ) . equals ( id ) ) { return info ; } } return null ; } public void load_extensions ( ) { fLog . debug ( LEVEL_MID , "" ) ; List < AbstractTemplateFinder > template_finders = new ArrayList < AbstractTemplateFinder > ( ) ; fTemplates . clear ( ) ; fCategories . clear ( ) ; fCategoryMap . clear ( ) ; if ( fLoadExtPoints ) { template_finders . add ( new ExtensionTemplateFinder ( ) ) ; } if ( fPathProviders . size ( ) > ) { for ( IExternalTemplatePathProvider p : fPathProviders ) { for ( String path : p . getExternalTemplatePath ( ) ) { fLog . debug ( LEVEL_MID , "" + path + "" ) ; if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; IContainer c = SVFileUtils . getWorkspaceFolder ( path ) ; template_finders . add ( new WSExternalTemplateFinder ( c ) ) ; } else { template_finders . add ( new FSExternalTemplateFinder ( new File ( path ) ) ) ; } } } } for ( AbstractTemplateFinder f : template_finders ) { f . find ( ) ; List < TemplateInfo > tmpl_list = f . getTemplates ( ) ; List < TemplateCategory > category_list = f . getCategories ( ) ; fTemplates . addAll ( tmpl_list ) ; for ( TemplateCategory new_c : category_list ) { if ( ! fCategories . contains ( new_c ) ) { fCategories . add ( new_c ) ; } } } for ( int i = ; i < fCategories . size ( ) ; i ++ ) { for ( int j = i + ; j < fCategories . size ( ) ; j ++ ) { TemplateCategory c_i = fCategories . get ( i ) ; TemplateCategory c_j = fCategories . get ( j ) ; if ( c_j . getName ( ) . compareTo ( c_i . getName ( ) ) < ) { fCategories . set ( j , c_i ) ; fCategories . set ( i , c_j ) ; } } } for ( TemplateInfo t : fTemplates ) { if ( t . getCategoryId ( ) == null || t . getCategoryId ( ) . trim ( ) . equals ( "" ) ) { if ( ! fCategoryMap . containsKey ( "" ) ) { TemplateCategory c = new TemplateCategory ( "" , "" , "" ) ; c . setDescription ( "" ) ; t . setCategoryId ( "" ) ; } } if ( ! fCategoryMap . containsKey ( t . getCategoryId ( ) ) ) { fCategoryMap . put ( t . getCategoryId ( ) , new ArrayList < TemplateInfo > ( ) ) ; } fCategoryMap . get ( t . getCategoryId ( ) ) . add ( t ) ; } for ( Entry < String , List < TemplateInfo > > c : fCategoryMap . entrySet ( ) ) { List < TemplateInfo > t = c . getValue ( ) ; for ( int i = ; i < t . size ( ) ; i ++ ) { for ( int j = i + ; j < t . size ( ) ; j ++ ) { TemplateInfo t_i = t . get ( i ) ; TemplateInfo t_j = t . get ( j ) ; if ( t_j . getName ( ) . compareTo ( t_i . getName ( ) ) < ) { t . set ( i , t_j ) ; t . set ( j , t_i ) ; } } } } } } package net . sf . sveditor . core . templates ; public class DefaultTemplateParameterProvider extends TemplateParameterProvider { public static final String FILE_HEADER = "" ; public static final String FILE_HEADER_DFLT = "" + "" + "" ; public static final String FILE_FOOTER = "" ; public static final String FILE_FOOTER_DFLT = "" ; public DefaultTemplateParameterProvider ( ITemplateParameterProvider p ) { super ( ) ; set_defaults ( ) ; if ( p . providesParameter ( FILE_HEADER ) ) { setTag ( FILE_HEADER , p . getParameterValue ( FILE_HEADER , null ) ) ; } if ( p . providesParameter ( FILE_FOOTER ) ) { setTag ( FILE_HEADER , p . getParameterValue ( FILE_FOOTER , null ) ) ; } } private void set_defaults ( ) { setTag ( FILE_HEADER , FILE_HEADER_DFLT ) ; setTag ( FILE_FOOTER , FILE_FOOTER_DFLT ) ; } } package net . sf . sveditor . core . templates ; public class TemplateCategory implements Comparable < TemplateCategory > { private String fId ; private String fName ; private String fDescription ; private String fParent ; public TemplateCategory ( String id , String name , String parent ) { fId = id ; fName = name ; fDescription = "" ; fParent = parent ; } public String getId ( ) { return fId ; } public String getName ( ) { return fName ; } public String getDescription ( ) { return fDescription ; } public void setDescription ( String desc ) { fDescription = desc ; } public String getParent ( ) { return fParent ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof TemplateCategory ) { return fId . equals ( ( ( TemplateCategory ) obj ) . fId ) ; } else { return false ; } } public int compareTo ( TemplateCategory o ) { return fName . compareTo ( o . fName ) ; } } package net . sf . sveditor . core . templates ; public interface ITemplateParameterProvider { boolean providesParameter ( String id ) ; String getParameterValue ( String id , String arg ) ; } package net . sf . sveditor . core . templates ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogHandle ; public abstract class AbstractTemplateFinder implements ILogLevel { protected LogHandle fLog ; protected List < TemplateInfo > fTemplates ; protected List < TemplateCategory > fCategories ; public AbstractTemplateFinder ( ) { fTemplates = new ArrayList < TemplateInfo > ( ) ; fCategories = new ArrayList < TemplateCategory > ( ) ; } public abstract void find ( ) ; public List < TemplateInfo > getTemplates ( ) { return fTemplates ; } public List < TemplateCategory > getCategories ( ) { return fCategories ; } protected void addTemplate ( TemplateInfo template ) { fTemplates . add ( template ) ; } protected void addCategory ( TemplateCategory category ) { fCategories . add ( category ) ; } } package net . sf . sveditor . core . templates ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . scanutils . InputStreamTextScanner ; import net . sf . sveditor . core . text . TagProcessor ; public class TemplateProcessor { private ITemplateFileCreator fStreamProvider ; private static final String fDefaultFileHeader = "" + "" + "" ; public TemplateProcessor ( ITemplateFileCreator provider ) { fStreamProvider = provider ; } public static List < String > getOutputFiles ( TemplateInfo template , TagProcessor proc ) { List < String > ret = new ArrayList < String > ( ) ; for ( Tuple < String , String > t : template . getTemplates ( ) ) { String name = proc . process ( t . second ( ) ) ; ret . add ( name ) ; } return ret ; } public void process ( TemplateInfo template , TagProcessor proc ) { TemplateParameterProvider local_p = new TemplateParameterProvider ( ) ; proc . addParameterProvider ( local_p ) ; for ( Tuple < String , String > t : template . getTemplates ( ) ) { int n_replacements = ; String templ = t . first ( ) ; String name = proc . process ( t . second ( ) ) ; name = name . trim ( ) ; local_p . setTag ( "" , name ) ; InputStream in = template . openTemplate ( templ ) ; ByteArrayInputStream in_t = readInputStream ( in ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; do { try { n_replacements = proc . process ( in_t , out ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } in_t = new ByteArrayInputStream ( out . toByteArray ( ) ) ; out = new ByteArrayOutputStream ( ) ; } while ( n_replacements > ) ; InputStream in_ind = null ; if ( should_sv_indent ( name ) ) { SVIndentScanner scanner = new SVIndentScanner ( new InputStreamTextScanner ( in_t , name ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; in_ind = new StringInputStream ( indenter . indent ( ) ) ; } else { in_ind = in_t ; } fStreamProvider . createFile ( name , in_ind ) ; template . closeTemplate ( in ) ; } proc . removeParameterProvider ( local_p ) ; } private boolean should_sv_indent ( String name ) { String ext = "" ; if ( name . lastIndexOf ( '' ) != - ) { ext = name . substring ( name . lastIndexOf ( '' ) ) ; } List < String > exts = SVCorePlugin . getDefault ( ) . getDefaultSVExts ( ) ; return exts . contains ( ext ) ; } private ByteArrayInputStream readInputStream ( InputStream in ) { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; byte tmp [ ] = new byte [ ] ; int len ; try { while ( ( len = in . read ( tmp , , tmp . length ) ) > ) { bos . write ( tmp , , len ) ; } } catch ( IOException e ) { } return new ByteArrayInputStream ( bos . toByteArray ( ) ) ; } } package net . sf . sveditor . core . templates ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; public class SVTUtils { public static boolean ensureExpectedSections ( Document doc , Element sv_template ) { NodeList nl = sv_template . getChildNodes ( ) ; boolean ret = false ; for ( int i = ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n instanceof Element ) { Element e = ( Element ) n ; if ( e . getNodeName ( ) . equals ( "" ) ) { ret |= ensureExpectedTemplateSections ( doc , e ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { ret |= ensureExpectedCategorySections ( doc , e ) ; } } } return ret ; } private static boolean ensureExpectedTemplateSections ( Document doc , Element template ) { boolean ret = false ; ret |= addElementIfMissing ( doc , template , "" ) ; ret |= addElementIfMissing ( doc , template , "" ) ; ret |= addElementIfMissing ( doc , template , "" ) ; return ret ; } private static boolean ensureExpectedCategorySections ( Document doc , Element template ) { boolean ret = false ; ret |= addElementIfMissing ( doc , template , "" ) ; return ret ; } private static boolean addElementIfMissing ( Document doc , Element e , String elem ) { NodeList nl = e . getChildNodes ( ) ; boolean found = false ; boolean ret = false ; for ( int i = ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n instanceof Element && ( ( Element ) n ) . getNodeName ( ) . equals ( elem ) ) { found = true ; break ; } } if ( ! found ) { Element new_e = doc . createElement ( elem ) ; e . appendChild ( new_e ) ; ret = true ; } return ret ; } } package net . sf . sveditor . core . templates ; import java . util . HashMap ; import java . util . Map ; public class TemplateParameterProvider implements ITemplateParameterProvider { private Map < String , String > fTagMap ; public TemplateParameterProvider ( ) { fTagMap = new HashMap < String , String > ( ) ; } public TemplateParameterProvider ( Map < String , String > init ) { this ( ) ; fTagMap . putAll ( init ) ; } public TemplateParameterProvider ( TemplateParameterProvider init ) { this ( ) ; fTagMap . putAll ( init . fTagMap ) ; } public boolean providesParameter ( String id ) { return fTagMap . containsKey ( id ) ; } public String getParameterValue ( String id , String arg ) { return getTag ( id ) ; } public void setTag ( String tag , String value ) { if ( fTagMap . containsKey ( tag ) ) { fTagMap . remove ( tag ) ; } fTagMap . put ( tag , value ) ; } public void removeTag ( String tag ) { fTagMap . remove ( tag ) ; } public boolean hasTag ( String tag ) { return fTagMap . containsKey ( tag ) ; } public String getTag ( String tag ) { return fTagMap . get ( tag ) ; } public void appendTag ( String tag , String value ) { String val ; if ( fTagMap . containsKey ( tag ) ) { val = fTagMap . get ( tag ) ; fTagMap . remove ( tag ) ; } else { val = "" ; } val += value ; fTagMap . put ( tag , val ) ; } } package net . sf . sveditor . core . content_assist ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; public class SVCompletionProposal { private ISVDBItemBase fItem ; private String fPrefix ; private String fReplacement ; private int fReplacementOffset ; private int fReplacementLength ; private SVCompletionProposalType fType ; public SVCompletionProposal ( ISVDBItemBase item , String prefix , int replacementOffset , int replacementLength ) { fItem = item ; fPrefix = prefix ; fReplacement = SVDBItem . getName ( item ) ; fReplacementOffset = replacementOffset ; fReplacementLength = replacementLength ; fType = SVCompletionProposalType . SVObject ; } public String getPrefix ( ) { return fPrefix ; } public String getReplacement ( ) { return fReplacement ; } public void setReplacement ( String replacement ) { fReplacement = replacement ; } public SVCompletionProposal ( String replacement , int startOffset , int replacementLength ) { fReplacement = replacement ; fReplacementOffset = startOffset ; fReplacementLength = replacementLength ; fType = SVCompletionProposalType . Unknown ; } public SVCompletionProposal ( String replacement , int startOffset , int replacementLength , SVCompletionProposalType type ) { fReplacement = replacement ; fReplacementOffset = startOffset ; fReplacementLength = replacementLength ; fType = type ; } public ISVDBItemBase getItem ( ) { return fItem ; } public SVCompletionProposalType getType ( ) { return fType ; } public int getReplacementOffset ( ) { return fReplacementOffset ; } public int getReplacementLength ( ) { return fReplacementLength ; } } package net . sf . sveditor . core . content_assist ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . IFieldItemAttr ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBInterfaceDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModportDecl ; import net . sf . sveditor . core . db . SVDBModportItem ; import net . sf . sveditor . core . db . SVDBModportPortsDecl ; import net . sf . sveditor . core . db . SVDBModportSimplePort ; import net . sf . sveditor . core . db . SVDBModportSimplePortsDecl ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . SVDBTypeInfoEnumerator ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . search . SVDBFindByName ; import net . sf . sveditor . core . db . search . SVDBFindByNameInClassHierarchy ; import net . sf . sveditor . core . db . search . SVDBFindByNameInScopes ; import net . sf . sveditor . core . db . search . SVDBFindByNameMatcher ; import net . sf . sveditor . core . db . search . SVDBFindContentAssistNameMatcher ; import net . sf . sveditor . core . db . search . SVDBFindDefaultNameMatcher ; import net . sf . sveditor . core . db . search . SVDBFindIncludedFile ; import net . sf . sveditor . core . db . search . SVDBFindNamedModIfcClassIfc ; import net . sf . sveditor . core . db . search . SVDBFindSuperClass ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . db . utils . SVDBSearchUtils ; import net . sf . sveditor . core . expr_utils . SVContentAssistExprVisitor ; import net . sf . sveditor . core . expr_utils . SVExprContext ; import net . sf . sveditor . core . expr_utils . SVExprContext . ContextType ; import net . sf . sveditor . core . expr_utils . SVExprScanner ; import net . sf . sveditor . core . expr_utils . SVExprUtilsParser ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . scanutils . IBIDITextScanner ; import org . eclipse . core . runtime . NullProgressMonitor ; public abstract class AbstractCompletionProcessor implements ILogLevel { protected List < SVCompletionProposal > fCompletionProposals ; protected LogHandle fLog ; public AbstractCompletionProcessor ( ) { fCompletionProposals = new ArrayList < SVCompletionProposal > ( ) ; } protected abstract ISVDBIndexIterator getIndexIterator ( ) ; protected abstract SVDBFile getSVDBFile ( ) ; protected void addProposal ( SVCompletionProposal p ) { boolean found = false ; synchronized ( fCompletionProposals ) { for ( SVCompletionProposal p_t : fCompletionProposals ) { if ( p_t . equals ( p ) ) { found = true ; break ; } } if ( ! found ) { fCompletionProposals . add ( p ) ; } } } public List < SVCompletionProposal > getCompletionProposals ( ) { return fCompletionProposals ; } public void computeProposals ( IBIDITextScanner scanner , SVDBFile active_file , int lineno ) { computeProposals ( scanner , active_file , lineno , - ) ; } public void computeProposals ( IBIDITextScanner scanner , SVDBFile active_file , int lineno , int linepos ) { SVExprScanner expr_scan = new SVExprScanner ( ) ; synchronized ( fCompletionProposals ) { fCompletionProposals . clear ( ) ; } fLog . debug ( LEVEL_MID , "" + active_file . getFilePath ( ) + "" + lineno + "" + linepos ) ; ISVDBScopeItem src_scope = SVDBSearchUtils . findActiveScope ( active_file , lineno ) ; if ( src_scope != null ) { fLog . debug ( LEVEL_MID , "" + src_scope . getType ( ) + "" + SVDBItem . getName ( src_scope ) ) ; } SVExprContext ctxt = expr_scan . extractExprContext ( scanner , false ) ; fLog . debug ( LEVEL_MID , "" + ctxt . fType + "" + ctxt . fTrigger + "" + ctxt . fRoot + "" + ctxt . fLeaf + "" + ctxt . fStart ) ; if ( ctxt . fTrigger != null ) { if ( ctxt . fTrigger . equals ( "" ) ) { findMacroItems ( ctxt , getIndexIterator ( ) ) ; } else if ( ctxt . fRoot != null && ( ctxt . fTrigger . equals ( "" ) || ctxt . fTrigger . equals ( "" ) || ctxt . fTrigger . equals ( "" ) || ctxt . fTrigger . equals ( "" ) ) ) { if ( ctxt . fTrigger . equals ( "" ) || ctxt . fTrigger . equals ( "" ) ) { SVDBExpr expr = null ; SVExprUtilsParser parser = new SVExprUtilsParser ( ctxt ) ; try { expr = parser . parsers ( ) . exprParser ( ) . expression ( ) ; } catch ( SVParseException e ) { fLog . debug ( LEVEL_MID , "" , e ) ; return ; } SVContentAssistExprVisitor v = new SVContentAssistExprVisitor ( src_scope , SVDBFindDefaultNameMatcher . getDefault ( ) , getIndexIterator ( ) ) ; ISVDBItemBase item = null ; if ( expr != null ) { item = v . findTypeItem ( expr ) ; } if ( item == null ) { fLog . debug ( LEVEL_MID , "" ) ; return ; } fLog . debug ( LEVEL_MID , "" + item . getType ( ) + "" + SVDBItem . getName ( item ) ) ; findTriggeredProposals ( ctxt , src_scope , item ) ; } else if ( ctxt . fTrigger . equals ( "" ) ) { SVDBExpr expr = null ; SVExprUtilsParser parser = new SVExprUtilsParser ( ctxt ) ; try { expr = parser . parsers ( ) . exprParser ( ) . expression ( ) ; } catch ( SVParseException e ) { fLog . debug ( LEVEL_MID , "" , e ) ; return ; } SVContentAssistExprVisitor v = new SVContentAssistExprVisitor ( src_scope , SVDBFindDefaultNameMatcher . getDefault ( ) , getIndexIterator ( ) ) ; ISVDBItemBase item = null ; if ( expr != null ) { try { item = v . findTypeItem ( expr ) ; } catch ( RuntimeException e ) { } } if ( item == null ) { fLog . debug ( LEVEL_MID , "" ) ; } fLog . debug ( LEVEL_MID , "" + ( ( item != null ) ? ( item . getType ( ) + "" + SVDBItem . getName ( item ) ) : "" ) ) ; findAssignTriggeredProposals ( ctxt , src_scope , item ) ; } else if ( ctxt . fTrigger . equals ( "" ) ) { if ( ctxt . fRoot . startsWith ( "" ) ) { findEndLabelProposals ( ctxt , src_scope ) ; } else { findUntriggeredProposals ( ctxt , src_scope ) ; } } else { } } else if ( ctxt . fTrigger . equals ( "" ) ) { fLog . debug ( LEVEL_MID , "" ) ; findPortCompletionProposals ( ctxt , src_scope , lineno , linepos ) ; } else { } } else { findUntriggeredProposals ( ctxt , src_scope ) ; } order_proposals ( ctxt . fLeaf , fCompletionProposals ) ; } private void findTriggeredProposals ( SVExprContext ctxt , ISVDBChildItem src_scope , ISVDBItemBase leaf_item ) { boolean static_ref = ctxt . fTrigger . equals ( "" ) ; fLog . debug ( "" + leaf_item . getType ( ) ) ; if ( leaf_item . getType ( ) == SVDBItemType . ClassDecl || leaf_item . getType ( ) == SVDBItemType . TypeInfoStruct || leaf_item . getType ( ) == SVDBItemType . InterfaceDecl || leaf_item . getType ( ) == SVDBItemType . ModuleDecl ) { SVDBFindContentAssistNameMatcher matcher = new SVDBFindContentAssistNameMatcher ( ) ; SVDBFindSuperClass super_finder = new SVDBFindSuperClass ( getIndexIterator ( ) ) ; ISVDBChildParent si = ( ISVDBChildParent ) leaf_item ; while ( si != null ) { for ( ISVDBChildItem it : si . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt v = ( SVDBVarDeclStmt ) it ; if ( ( v . getAttr ( ) & SVDBVarDeclStmt . FieldAttr_Static ) != == static_ref ) { for ( ISVDBItemBase it_1 : ( ( SVDBVarDeclStmt ) it ) . getChildren ( ) ) { debug ( "" + SVDBItem . getName ( it_1 ) ) ; if ( matcher . match ( ( ISVDBNamedItem ) it_1 , ctxt . fLeaf ) ) { addProposal ( it_1 , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } } else if ( it . getType ( ) == SVDBItemType . TypedefStmt ) { SVDBTypedefStmt td_stmt = ( SVDBTypedefStmt ) it ; if ( matcher . match ( td_stmt , ctxt . fLeaf ) ) { addProposal ( td_stmt , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } if ( td_stmt . getTypeInfo ( ) != null && td_stmt . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoEnum ) { SVDBTypeInfoEnum enum_type = ( SVDBTypeInfoEnum ) td_stmt . getTypeInfo ( ) ; for ( SVDBTypeInfoEnumerator enumerator : enum_type . getEnumerators ( ) ) { if ( matcher . match ( enumerator , ctxt . fLeaf ) ) { addProposal ( enumerator , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } } else if ( it . getType ( ) == SVDBItemType . ModportDecl ) { for ( ISVDBItemBase it_1 : ( ( SVDBModportDecl ) it ) . getChildren ( ) ) { debug ( "" + SVDBItem . getName ( it_1 ) ) ; if ( matcher . match ( ( ISVDBNamedItem ) it_1 , ctxt . fLeaf ) ) { addProposal ( it_1 , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } else if ( it . getType ( ) == SVDBItemType . ModIfcInst ) { for ( ISVDBItemBase it_1 : ( ( SVDBModIfcInst ) it ) . getChildren ( ) ) { if ( matcher . match ( ( ISVDBNamedItem ) it_1 , ctxt . fLeaf ) ) { addProposal ( it_1 , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } else if ( it instanceof ISVDBNamedItem ) { if ( matcher . match ( ( ISVDBNamedItem ) it , ctxt . fLeaf ) ) { addProposal ( it , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } if ( si . getType ( ) == SVDBItemType . ClassDecl ) { SVDBClassDecl cls_decl = ( SVDBClassDecl ) si ; si = super_finder . find ( cls_decl ) ; } else { if ( si . getType ( ) . isElemOf ( SVDBItemType . InterfaceDecl ) ) { SVDBInterfaceDecl ifc = ( SVDBInterfaceDecl ) si ; for ( SVDBParamPortDecl p : ifc . getPorts ( ) ) { for ( ISVDBItemBase vi : p . getChildren ( ) ) { if ( matcher . match ( ( ISVDBNamedItem ) vi , ctxt . fLeaf ) ) { addProposal ( vi , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } } si = null ; } } } else if ( leaf_item . getType ( ) == SVDBItemType . PackageDecl ) { SVDBFindContentAssistNameMatcher matcher = new SVDBFindContentAssistNameMatcher ( ) ; if ( ! static_ref ) { fLog . debug ( "" ) ; } ISVDBIndexIterator index_it = getIndexIterator ( ) ; SVDBPackageDecl pkg_decl = ( SVDBPackageDecl ) leaf_item ; List < SVDBDeclCacheItem > result = index_it . findGlobalScopeDecl ( new NullProgressMonitor ( ) , pkg_decl . getName ( ) , new SVDBFindByNameMatcher ( SVDBItemType . PackageDecl ) ) ; if ( result . size ( ) > ) { SVDBDeclCacheItem pkg_item = result . get ( ) ; List < SVDBDeclCacheItem > pkg_items = index_it . findPackageDecl ( new NullProgressMonitor ( ) , pkg_item ) ; for ( SVDBDeclCacheItem ci : pkg_items ) { ISVDBItemBase item = ci . getSVDBItem ( ) ; if ( item . getType ( ) == SVDBItemType . TypedefStmt ) { SVDBTypedefStmt td_stmt = ( SVDBTypedefStmt ) item ; if ( matcher . match ( td_stmt , ctxt . fLeaf ) ) { addProposal ( td_stmt , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } if ( td_stmt . getTypeInfo ( ) != null && td_stmt . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoEnum ) { SVDBTypeInfoEnum enum_type = ( SVDBTypeInfoEnum ) td_stmt . getTypeInfo ( ) ; for ( SVDBTypeInfoEnumerator enumerator : enum_type . getEnumerators ( ) ) { if ( matcher . match ( enumerator , ctxt . fLeaf ) ) { addProposal ( enumerator , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } } else if ( item instanceof ISVDBNamedItem ) { ISVDBNamedItem ni = ( ISVDBNamedItem ) item ; fLog . debug ( "" + ni . getName ( ) + "" ) ; if ( matcher . match ( ni , ctxt . fLeaf ) ) { addProposal ( item , ctxt . fLeaf , true , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } else { fLog . debug ( "" + SVDBItem . getName ( item ) ) ; } } } else { fLog . debug ( "" + pkg_decl . getName ( ) + "" ) ; } System . out . println ( "" ) ; } else if ( leaf_item . getType ( ) == SVDBItemType . VarDeclItem ) { ISVDBItemBase item_type = getItemType ( leaf_item ) ; if ( item_type != null && item_type . getType ( ) . isElemOf ( SVDBItemType . ClassDecl ) ) { ISVDBScopeItem si = ( ISVDBScopeItem ) item_type ; SVDBFindContentAssistNameMatcher matcher = new SVDBFindContentAssistNameMatcher ( ) ; for ( ISVDBItemBase it : si . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . VarDeclStmt ) { for ( ISVDBItemBase it_1 : ( ( SVDBVarDeclStmt ) it ) . getChildren ( ) ) { debug ( "" + SVDBItem . getName ( it_1 ) ) ; if ( matcher . match ( ( ISVDBNamedItem ) it_1 , ctxt . fLeaf ) ) { addProposal ( it_1 , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } else if ( it instanceof ISVDBNamedItem ) { if ( matcher . match ( ( ISVDBNamedItem ) it , ctxt . fLeaf ) ) { addProposal ( it , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } } } else if ( leaf_item . getType ( ) == SVDBItemType . ModportItem ) { SVDBFindContentAssistNameMatcher matcher = new SVDBFindContentAssistNameMatcher ( ) ; SVDBModportItem mpi = ( SVDBModportItem ) leaf_item ; for ( SVDBModportPortsDecl pd : mpi . getPortsList ( ) ) { if ( pd . getType ( ) == SVDBItemType . ModportSimplePortsDecl ) { SVDBModportSimplePortsDecl simple_pd = ( SVDBModportSimplePortsDecl ) pd ; for ( SVDBModportSimplePort p : simple_pd . getPortList ( ) ) { if ( matcher . match ( p , ctxt . fLeaf ) ) { addProposal ( p , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } else { fLog . debug ( LEVEL_MIN , "" + pd . getType ( ) ) ; } } } } private void findAssignTriggeredProposals ( SVExprContext ctxt , ISVDBChildItem src_scope , ISVDBItemBase item ) { fLog . debug ( "" + ctxt . fLeaf + "" ) ; List < ISVDBItemBase > result = new ArrayList < ISVDBItemBase > ( ) ; List < ISVDBItemBase > tmp = null ; SVDBFindContentAssistNameMatcher matcher = new SVDBFindContentAssistNameMatcher ( ) ; SVDBFindByNameInScopes finder_s = new SVDBFindByNameInScopes ( getIndexIterator ( ) , matcher ) ; tmp = finder_s . find ( src_scope , ctxt . fLeaf , false ) ; result . addAll ( tmp ) ; SVDBFindByNameInClassHierarchy finder_h = new SVDBFindByNameInClassHierarchy ( getIndexIterator ( ) , matcher ) ; tmp = finder_h . find ( src_scope , ctxt . fLeaf ) ; result . addAll ( tmp ) ; if ( result . size ( ) > ) { for ( int i = ; i < result . size ( ) ; i ++ ) { boolean add = true ; if ( result . get ( i ) . getType ( ) == SVDBItemType . Function && ( ( ISVDBNamedItem ) result . get ( i ) ) . getName ( ) . equals ( "" ) ) { add = false ; } if ( add ) { addProposal ( result . get ( i ) , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } SVDBFindNamedModIfcClassIfc finder_cls = new SVDBFindNamedModIfcClassIfc ( getIndexIterator ( ) , matcher ) ; List < ISVDBChildItem > cl_l = finder_cls . find ( ctxt . fLeaf ) ; if ( cl_l . size ( ) > ) { fLog . debug ( "" + ctxt . fLeaf + "" + cl_l . size ( ) ) ; for ( ISVDBChildItem cl : cl_l ) { fLog . debug ( "" + cl . getType ( ) + "" + SVDBItem . getName ( cl ) ) ; } for ( ISVDBItemBase it : cl_l ) { addProposal ( it , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } else { fLog . debug ( "" + ctxt . fLeaf + "" ) ; } SVDBFindByName finder_tf = new SVDBFindByName ( getIndexIterator ( ) , matcher ) ; List < ISVDBItemBase > it_l = finder_tf . find ( ctxt . fLeaf ) ; for ( int i = ; i < it_l . size ( ) ; i ++ ) { if ( it_l . get ( i ) . getType ( ) == SVDBItemType . Function || it_l . get ( i ) . getType ( ) == SVDBItemType . Task ) { SVDBTask tf = ( SVDBTask ) it_l . get ( i ) ; if ( ( tf . getAttr ( ) & IFieldItemAttr . FieldAttr_Extern ) == && tf . getName ( ) . contains ( "" ) ) { it_l . remove ( i ) ; i -- ; } ISVDBItemBase scope_t = tf ; while ( scope_t != null && scope_t . getType ( ) != SVDBItemType . ClassDecl && scope_t . getType ( ) != SVDBItemType . ModuleDecl ) { scope_t = ( ( ISVDBChildItem ) scope_t ) . getParent ( ) ; } if ( scope_t != null && ( scope_t . getType ( ) == SVDBItemType . ClassDecl || scope_t . getType ( ) == SVDBItemType . ModuleDecl ) ) { it_l . remove ( i ) ; i -- ; } } } if ( it_l != null && it_l . size ( ) > ) { fLog . debug ( "" + ctxt . fLeaf + "" ) ; for ( ISVDBItemBase it : it_l ) { fLog . debug ( "" + it . getType ( ) + "" + ( ( ISVDBNamedItem ) it ) . getName ( ) ) ; } for ( ISVDBItemBase it : it_l ) { addProposal ( it , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } else { fLog . debug ( "" + ctxt . fLeaf + "" ) ; } fLog . debug ( "" + ( ( item != null ) ? item . getType ( ) : "" ) ) ; if ( item != null && ( item . getType ( ) == SVDBItemType . ClassDecl ) && ( "" . startsWith ( ctxt . fLeaf ) || ctxt . fLeaf . equals ( "" ) ) ) { SVDBClassDecl cls = ( SVDBClassDecl ) item ; fLog . debug ( "" + SVDBItem . getName ( item ) ) ; for ( ISVDBChildItem c : cls . getChildren ( ) ) { if ( c . getType ( ) == SVDBItemType . Function ) { SVDBFunction f = ( SVDBFunction ) c ; if ( f . getName ( ) . equals ( "" ) ) { addProposal ( c , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } } } private void findPortCompletionProposals ( SVExprContext ctxt , ISVDBChildParent src_scope , int lineno , int linepos ) { fLog . debug ( "" ) ; SVDBFindContentAssistNameMatcher matcher = new SVDBFindContentAssistNameMatcher ( ) ; fLog . debug ( "" ) ; if ( src_scope == null || ( src_scope . getType ( ) != SVDBItemType . ModuleDecl && src_scope . getType ( ) != SVDBItemType . InterfaceDecl ) ) { fLog . debug ( "" + src_scope + "" ) ; return ; } fLog . debug ( "" ) ; SVDBModIfcInst inst = findInst ( src_scope , lineno , linepos ) ; fLog . debug ( "" ) ; if ( inst == null ) { fLog . debug ( "" ) ; return ; } fLog . debug ( "" ) ; fLog . debug ( "" + inst . getTypeName ( ) ) ; SVDBModIfcDecl decl ; SVDBFindNamedModIfcClassIfc finder = new SVDBFindNamedModIfcClassIfc ( getIndexIterator ( ) ) ; List < ISVDBChildItem > result = finder . find ( inst . getTypeName ( ) ) ; if ( result . size ( ) > && ( result . get ( ) . getType ( ) == SVDBItemType . ModuleDecl || result . get ( ) . getType ( ) == SVDBItemType . InterfaceDecl ) ) { decl = ( SVDBModIfcDecl ) result . get ( ) ; } else { fLog . debug ( "" + inst . getTypeName ( ) + "" ) ; return ; } for ( SVDBParamPortDecl p : decl . getPorts ( ) ) { for ( ISVDBChildItem pi : p . getChildren ( ) ) { if ( matcher . match ( ( ISVDBNamedItem ) pi , ctxt . fLeaf ) ) { addProposal ( pi , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } fLog . debug ( "" ) ; } private SVDBModIfcInst findInst ( ISVDBChildParent p , int lineno , int linepos ) { SVDBModIfcInst last_inst = null ; for ( ISVDBChildItem c : p . getChildren ( ) ) { if ( c . getType ( ) == SVDBItemType . ModIfcInst ) { last_inst = ( SVDBModIfcInst ) c ; if ( c . getLocation ( ) . getLine ( ) > lineno ) { break ; } } else if ( c instanceof ISVDBChildParent ) { if ( c . getLocation ( ) != null && c . getLocation ( ) . getLine ( ) > lineno ) { break ; } if ( ( last_inst = findInst ( ( ISVDBChildParent ) c , lineno , linepos ) ) != null ) { break ; } } } return last_inst ; } private void findEndLabelProposals ( SVExprContext ctxt , ISVDBChildItem src_scope ) { fLog . debug ( "" + ctxt . fLeaf + "" ) ; fLog . debug ( "" + SVDBItem . getName ( src_scope ) ) ; if ( src_scope == null || ! ( src_scope instanceof ISVDBNamedItem ) ) { return ; } ISVDBNamedItem item = ( ISVDBNamedItem ) src_scope ; if ( ctxt . fLeaf . equals ( "" ) || item . getName ( ) . startsWith ( ctxt . fLeaf ) ) { addProposal ( new SVCompletionProposal ( ( ( ISVDBNamedItem ) src_scope ) . getName ( ) , ctxt . fStart , ctxt . fLeaf . length ( ) ) ) ; } else { findUntriggeredProposals ( ctxt , src_scope ) ; } } private void findUntriggeredProposals ( SVExprContext ctxt , ISVDBChildItem src_scope ) { fLog . debug ( "" + ctxt . fLeaf + "" ) ; List < ISVDBItemBase > result = null ; SVDBFindContentAssistNameMatcher matcher = new SVDBFindContentAssistNameMatcher ( ) ; SVDBFindByNameInScopes finder_s = new SVDBFindByNameInScopes ( getIndexIterator ( ) , matcher ) ; fLog . debug ( "" ) ; result = finder_s . find ( src_scope , ctxt . fLeaf , false ) ; fLog . debug ( "" + result . size ( ) + "" ) ; for ( int i = ; i < result . size ( ) ; i ++ ) { if ( ! ( SVDBItem . getName ( result . get ( i ) ) . equals ( ctxt . fLeaf ) && isSameScopeVarDecl ( src_scope , result . get ( i ) ) ) ) { addProposal ( result . get ( i ) , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } SVDBFindByNameInClassHierarchy finder_h = new SVDBFindByNameInClassHierarchy ( getIndexIterator ( ) , matcher ) ; result = finder_h . find ( src_scope , ctxt . fLeaf ) ; if ( result . size ( ) > ) { for ( int i = ; i < result . size ( ) ; i ++ ) { boolean add = true ; if ( ctxt . fTrigger != null && ctxt . fTrigger . equals ( "" ) && "" . startsWith ( ctxt . fLeaf ) ) { if ( result . get ( i ) . getType ( ) == SVDBItemType . Function && ( ( ISVDBNamedItem ) result . get ( i ) ) . getName ( ) . equals ( "" ) ) { add = false ; } } if ( ctxt . fType == ContextType . Extends ) { fLog . debug ( "" + result . get ( i ) . getType ( ) ) ; if ( result . get ( i ) . getType ( ) != SVDBItemType . ClassDecl ) { add = false ; } } if ( add ) { addProposal ( result . get ( i ) , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } SVDBFindNamedModIfcClassIfc finder_cls = new SVDBFindNamedModIfcClassIfc ( getIndexIterator ( ) , matcher ) ; List < ISVDBChildItem > cl_l = finder_cls . find ( ctxt . fLeaf ) ; if ( cl_l . size ( ) > ) { fLog . debug ( "" + ctxt . fLeaf + "" + cl_l . size ( ) ) ; for ( ISVDBChildItem cl : cl_l ) { fLog . debug ( "" + cl . getType ( ) + "" + SVDBItem . getName ( cl ) ) ; } for ( ISVDBItemBase it : cl_l ) { if ( ctxt . fType == ContextType . Extends ) { if ( it . getType ( ) == SVDBItemType . ClassDecl ) { addProposal ( it , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } else { addProposal ( it , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } else { fLog . debug ( "" + ctxt . fLeaf + "" ) ; } if ( ctxt . fType != ContextType . Extends ) { SVDBFindByName finder_tf = new SVDBFindByName ( getIndexIterator ( ) , matcher ) ; List < ISVDBItemBase > it_l = finder_tf . find ( ctxt . fLeaf , SVDBItemType . Task , SVDBItemType . Function , SVDBItemType . VarDeclStmt , SVDBItemType . PackageDecl , SVDBItemType . TypedefStmt ) ; for ( int i = ; i < it_l . size ( ) ; i ++ ) { if ( it_l . get ( i ) . getType ( ) == SVDBItemType . Function || it_l . get ( i ) . getType ( ) == SVDBItemType . Task ) { SVDBTask tf = ( SVDBTask ) it_l . get ( i ) ; if ( ( tf . getAttr ( ) & IFieldItemAttr . FieldAttr_Extern ) == && tf . getName ( ) . contains ( "" ) ) { it_l . remove ( i ) ; i -- ; } ISVDBItemBase scope_t = tf ; while ( scope_t != null && scope_t . getType ( ) != SVDBItemType . ClassDecl && scope_t . getType ( ) != SVDBItemType . ModuleDecl ) { scope_t = ( ( ISVDBChildItem ) scope_t ) . getParent ( ) ; } if ( scope_t != null && ( scope_t . getType ( ) == SVDBItemType . ClassDecl || scope_t . getType ( ) == SVDBItemType . ModuleDecl ) ) { it_l . remove ( i ) ; i -- ; } } } if ( it_l != null && it_l . size ( ) > ) { fLog . debug ( "" + ctxt . fLeaf + "" ) ; for ( ISVDBItemBase it : it_l ) { fLog . debug ( "" + it . getType ( ) + "" + ( ( ISVDBNamedItem ) it ) . getName ( ) ) ; } for ( ISVDBItemBase it : it_l ) { addProposal ( it , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } else { fLog . debug ( "" + ctxt . fLeaf + "" ) ; } } } private boolean isSameScopeVarDecl ( ISVDBChildItem src_scope , ISVDBItemBase proposal ) { if ( proposal instanceof SVDBVarDeclItem ) { SVDBVarDeclItem v = ( SVDBVarDeclItem ) proposal ; if ( v . getParent ( ) != null && v . getParent ( ) . getParent ( ) != null ) { return ( v . getParent ( ) . getParent ( ) == src_scope ) ; } } return false ; } private void findMacroItems ( SVExprContext ctxt , ISVDBIndexIterator index_it ) { SVDBFindContentAssistNameMatcher matcher = new SVDBFindContentAssistNameMatcher ( ) ; if ( ctxt . fRoot != null && ctxt . fRoot . equals ( "" ) ) { SVDBFindIncludedFile finder = new SVDBFindIncludedFile ( index_it , matcher ) ; List < SVDBFile > it_l = finder . find ( ctxt . fLeaf ) ; if ( it_l . size ( ) > ) { addProposal ( it_l . get ( ) , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } else { List < SVDBDeclCacheItem > result = index_it . findGlobalScopeDecl ( new NullProgressMonitor ( ) , ctxt . fLeaf , new SVDBFindContentAssistNameMatcher ( SVDBItemType . MacroDef ) ) ; for ( SVDBDeclCacheItem i : result ) { fLog . debug ( LEVEL_MID , "" + i . getName ( ) ) ; addProposal ( i . getSVDBItem ( ) , ctxt . fLeaf , ctxt . fStart , ctxt . fLeaf . length ( ) ) ; } } } private ISVDBItemBase getItemType ( ISVDBItemBase item ) { SVDBTypeInfo ti = null ; if ( item . getType ( ) == SVDBItemType . VarDeclStmt ) { ti = ( ( SVDBVarDeclStmt ) item ) . getTypeInfo ( ) ; } else if ( item . getType ( ) == SVDBItemType . VarDeclItem ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) item ; if ( vi . getParent ( ) != null ) { ti = vi . getParent ( ) . getTypeInfo ( ) ; } } if ( ti != null ) { ISVDBItemBase target = resolveType ( ti ) ; if ( target != null ) { return target ; } } return ti ; } private ISVDBItemBase resolveType ( SVDBTypeInfo ti ) { ISVDBItemBase target = null ; if ( ti . getType ( ) == SVDBItemType . TypeInfoUserDef ) { SVDBFindByName finder = new SVDBFindByName ( getIndexIterator ( ) ) ; List < ISVDBItemBase > ret = finder . find ( ti . getName ( ) ) ; if ( ret . size ( ) > ) { target = ret . get ( ) ; } } else if ( ti . getType ( ) == SVDBItemType . TypeInfoStruct ) { } else { } if ( target != null ) { if ( target . getType ( ) == SVDBItemType . TypedefStmt ) { target = resolveType ( ( ( SVDBTypedefStmt ) target ) . getTypeInfo ( ) ) ; } } return target ; } protected boolean isPrefix ( String pre , SVDBItem it ) { return it . getName ( ) . toLowerCase ( ) . startsWith ( pre . toLowerCase ( ) ) ; } private void order_proposals ( String prefix , List < SVCompletionProposal > proposals ) { synchronized ( proposals ) { for ( int i = ; i < proposals . size ( ) ; i ++ ) { SVCompletionProposal p = proposals . get ( i ) ; if ( p . getItem ( ) != null && SVDBStmt . isType ( p . getItem ( ) , SVDBItemType . TypedefStmt ) ) { boolean found = false ; for ( SVCompletionProposal p_t : proposals ) { if ( p_t != p && p_t . getItem ( ) != null && SVDBItem . getName ( p_t . getItem ( ) ) . equals ( SVDBItem . getName ( p . getItem ( ) ) ) ) { found = true ; break ; } } if ( found ) { proposals . remove ( i ) ; i -- ; } } } for ( int i = ; i < proposals . size ( ) ; i ++ ) { SVCompletionProposal p_i = proposals . get ( i ) ; for ( int j = i + ; j < proposals . size ( ) ; j ++ ) { SVCompletionProposal p_j = proposals . get ( j ) ; String s_i , s_j ; if ( p_i . getItem ( ) != null ) { s_i = SVDBItem . getName ( p_i . getItem ( ) ) ; } else { s_i = p_i . getReplacement ( ) ; } if ( p_j . getItem ( ) != null ) { s_j = SVDBItem . getName ( p_j . getItem ( ) ) ; } else { s_j = p_j . getReplacement ( ) ; } if ( s_i . compareTo ( s_j ) > ) { proposals . set ( i , p_j ) ; proposals . set ( j , p_i ) ; p_i = p_j ; } } } for ( int i = ; i < proposals . size ( ) ; i ++ ) { SVCompletionProposal p_i = proposals . get ( i ) ; for ( int j = i + ; j < proposals . size ( ) ; j ++ ) { SVCompletionProposal p_j = proposals . get ( j ) ; String s_i , s_j ; if ( p_i . getItem ( ) != null ) { s_i = SVDBItem . getName ( p_i . getItem ( ) ) ; } else { s_i = p_i . getReplacement ( ) ; } if ( p_j . getItem ( ) != null ) { s_j = SVDBItem . getName ( p_j . getItem ( ) ) ; } else { s_j = p_j . getReplacement ( ) ; } if ( prefix . compareTo ( s_i ) < prefix . compareTo ( s_j ) ) { proposals . set ( i , p_j ) ; proposals . set ( j , p_i ) ; p_i = p_j ; } } } } } protected void addProposal ( ISVDBItemBase it , String prefix , int replacementOffset , int replacementLength ) { addProposal ( it , prefix , false , replacementOffset , replacementLength ) ; } protected void addProposal ( ISVDBItemBase it , String prefix , boolean name_based_check , int replacementOffset , int replacementLength ) { boolean found = false ; synchronized ( fCompletionProposals ) { for ( SVCompletionProposal p : fCompletionProposals ) { if ( p . getItem ( ) != null ) { if ( p . getItem ( ) == it ) { found = true ; break ; } else if ( name_based_check ) { if ( p . getItem ( ) instanceof ISVDBNamedItem && it instanceof ISVDBNamedItem ) { ISVDBNamedItem i1 = ( ISVDBNamedItem ) p . getItem ( ) ; ISVDBNamedItem i2 = ( ISVDBNamedItem ) it ; if ( i1 . getName ( ) == null || i1 . getName ( ) == null ) { if ( i1 . getName ( ) == i2 . getName ( ) ) { found = true ; break ; } } else if ( i1 . getName ( ) . equals ( i2 . getName ( ) ) ) { found = true ; break ; } } } } } if ( ! found ) { debug ( "" + SVDBItem . getName ( it ) + "" + it . getType ( ) ) ; addProposal ( new SVCompletionProposal ( it , prefix , replacementOffset , replacementLength ) ) ; } } } protected void debug ( String msg ) { fLog . debug ( msg ) ; } } package net . sf . sveditor . core . content_assist ; import java . util . ArrayList ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; public class SVCompletionProposalUtils { private int fTFMaxCharsPerLine = ; private int fTFPortsPerLine = ; private boolean fTFNamedPorts = true ; private int fModIfcInstMaxCharsPerLine = ; private int fModIfcInstPortsPerLine = ; private boolean fModIfcInstNamedPorts = true ; public SVCompletionProposalUtils ( ) { } public void setTFMaxCharsPerLine ( int max ) { fTFMaxCharsPerLine = max ; } public void setTFPortsPerLine ( int max ) { fTFPortsPerLine = max ; } public void setTFNamedPorts ( boolean named ) { fTFNamedPorts = named ; } public void setModIfcInstMaxCharsPerLine ( int max ) { fModIfcInstMaxCharsPerLine = max ; } public void setModIfcInstPortsPerLine ( int max ) { fModIfcInstPortsPerLine = max ; } public void setModIfcInstNamedPorts ( boolean named ) { fModIfcInstNamedPorts = named ; } private static String escapeId ( String id ) { StringBuilder sb = new StringBuilder ( id ) ; for ( int i = ; i < sb . length ( ) ; i ++ ) { if ( sb . charAt ( i ) == '' ) { sb . insert ( i , '' ) ; i ++ ; } } return sb . toString ( ) ; } public static String getLineIndent ( String doc , String indent_incr ) { StringBuilder doc_str = new StringBuilder ( doc ) ; int last_line_idx = doc_str . lastIndexOf ( "" ) ; String indent = "" ; if ( last_line_idx != - ) { int end_line_idx = last_line_idx ; while ( end_line_idx < doc_str . length ( ) && Character . isWhitespace ( doc_str . charAt ( end_line_idx ) ) ) { end_line_idx ++ ; } indent = doc_str . substring ( last_line_idx + , end_line_idx ) ; } return indent ; } public String createTFTemplate ( SVDBTask tf , String subseq_line_indent , int first_line_pos , int subseq_line_pos ) { String newline = "" + subseq_line_indent ; StringBuilder r = new StringBuilder ( ) ; int curr_pos = first_line_pos ; int longest_string = ; int port_length = ; int port_count = ; ArrayList < String > all_ports = new ArrayList < String > ( ) ; ArrayList < String > all_types = new ArrayList < String > ( ) ; for ( int i = ; i < tf . getParams ( ) . size ( ) ; i ++ ) { SVDBParamPortDecl param = tf . getParams ( ) . get ( i ) ; for ( ISVDBChildItem c : param . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; all_ports . add ( vi . getName ( ) ) ; all_types . add ( param . getTypeName ( ) ) ; port_count ++ ; port_length += vi . getName ( ) . length ( ) ; if ( vi . getName ( ) . length ( ) > longest_string ) { longest_string = vi . getName ( ) . length ( ) ; } } } boolean multi_line_instantiation = false ; int multiplier = fTFNamedPorts ? : ; if ( ( ( fTFMaxCharsPerLine != ) && ( ( first_line_pos + ( port_length * multiplier ) + ( * multiplier ) ) > ( ( fTFMaxCharsPerLine * ) / ) ) ) || ( ( fTFPortsPerLine != ) && ( port_count > fTFPortsPerLine ) ) ) { multi_line_instantiation = true ; curr_pos = subseq_line_pos ; } else { newline = "" ; } r . append ( escapeId ( SVDBItem . getName ( tf ) ) + "" + newline ) ; for ( int i = ; i < port_count ; i ++ ) { StringBuilder padding = new StringBuilder ( "" ) ; String name_str = all_ports . get ( i ) ; if ( multi_line_instantiation ) { for ( int cnt = name_str . length ( ) ; cnt < longest_string + ; cnt ++ ) { padding . append ( "" ) ; } } if ( fTFNamedPorts == true ) { r . append ( "" ) ; r . append ( name_str + padding . toString ( ) ) ; r . append ( "" ) ; curr_pos += + name_str . length ( ) + padding . toString ( ) . length ( ) ; } r . append ( "" + all_ports . get ( i ) + "" + padding . toString ( ) ) ; curr_pos += + all_ports . get ( i ) . length ( ) + padding . toString ( ) . length ( ) ; if ( fTFNamedPorts == true ) { r . append ( "" ) ; curr_pos ++ ; } if ( i + < port_count ) { r . append ( "" ) ; curr_pos += ; if ( ( fTFPortsPerLine != && multi_line_instantiation && ( ( ( i + ) % fTFPortsPerLine ) == ) ) || ( curr_pos > ( * fTFMaxCharsPerLine ) / ) ) { r . append ( newline ) ; curr_pos = subseq_line_pos ; } } } r . append ( "" ) ; return r . toString ( ) ; } public String createModuleTemplate ( SVDBModIfcDecl tf , String subseq_line_indent , int first_line_pos , int subseq_line_pos ) { String newline = "" + subseq_line_indent ; StringBuilder r = new StringBuilder ( ) ; int curr_pos = first_line_pos ; int longest_string = ; int port_len = ; int param_len = ; int port_count = ; int param_count = ; ArrayList < String > all_ports = new ArrayList < String > ( ) ; ArrayList < String > all_types = new ArrayList < String > ( ) ; ArrayList < String > all_params = new ArrayList < String > ( ) ; for ( int i = ; i < tf . getParameters ( ) . size ( ) ; i ++ ) { String param_name = tf . getParameters ( ) . get ( i ) . getName ( ) ; all_params . add ( param_name ) ; param_count ++ ; int len = param_name . length ( ) ; param_len += len ; if ( len > longest_string ) { longest_string = len ; } } for ( int i = ; i < tf . getPorts ( ) . size ( ) ; i ++ ) { SVDBParamPortDecl param = tf . getPorts ( ) . get ( i ) ; for ( ISVDBChildItem c : param . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; all_ports . add ( vi . getName ( ) ) ; all_types . add ( param . getTypeName ( ) ) ; port_count ++ ; int len = vi . getName ( ) . length ( ) ; port_len += len ; if ( len > longest_string ) { longest_string = len ; } } } boolean multi_line_instantiation = false ; int multiplier = fModIfcInstNamedPorts ? : ; if ( ( ( fModIfcInstMaxCharsPerLine != ) && ( ( first_line_pos + ( ( port_len + param_len ) * multiplier ) + ( * multiplier ) ) > ( ( fModIfcInstMaxCharsPerLine * ) / ) ) ) || ( ( fModIfcInstPortsPerLine != ) && ( ( port_count > fModIfcInstPortsPerLine ) || ( param_count > fModIfcInstPortsPerLine ) ) ) ) { multi_line_instantiation = true ; curr_pos = subseq_line_pos ; } else { newline = "" ; } r . append ( escapeId ( SVDBItem . getName ( tf ) ) ) ; if ( param_count != ) { r . append ( "" + newline ) ; for ( int i = ; i < param_count ; i ++ ) { StringBuilder padding = new StringBuilder ( "" ) ; String name_str = all_params . get ( i ) ; if ( multi_line_instantiation ) { for ( int cnt = name_str . length ( ) ; cnt < longest_string + ; cnt ++ ) { padding . append ( "" ) ; } } if ( fModIfcInstNamedPorts == true ) { r . append ( "" ) ; r . append ( name_str + padding . toString ( ) ) ; r . append ( "" ) ; curr_pos += + name_str . length ( ) + padding . toString ( ) . length ( ) ; } r . append ( "" + name_str + "" + padding . toString ( ) ) ; curr_pos += + name_str . length ( ) + padding . toString ( ) . length ( ) ; if ( fModIfcInstNamedPorts == true ) { r . append ( "" ) ; curr_pos ++ ; } if ( i + < param_count ) { r . append ( "" ) ; curr_pos += ; if ( ( fModIfcInstPortsPerLine != && multi_line_instantiation && ( ( ( i + ) % fModIfcInstPortsPerLine ) == ) ) || ( curr_pos > ( * fModIfcInstMaxCharsPerLine ) / ) ) { r . append ( newline ) ; curr_pos = subseq_line_pos ; } } } r . append ( escapeId ( newline + "" ) ) ; } r . append ( "" + escapeId ( SVDBItem . getName ( tf ) ) + "" + "" + newline ) ; if ( ! newline . isEmpty ( ) ) curr_pos = subseq_line_pos ; for ( int i = ; i < port_count ; i ++ ) { StringBuilder padding = new StringBuilder ( "" ) ; String name_str = all_ports . get ( i ) ; if ( multi_line_instantiation ) { for ( int cnt = name_str . length ( ) ; cnt < longest_string + ; cnt ++ ) { padding . append ( "" ) ; } } if ( fModIfcInstNamedPorts == true ) { r . append ( "" ) ; r . append ( name_str + padding . toString ( ) ) ; r . append ( "" ) ; curr_pos += + name_str . length ( ) + padding . toString ( ) . length ( ) ; } r . append ( "" + all_ports . get ( i ) + "" + padding . toString ( ) ) ; curr_pos += + all_ports . get ( i ) . length ( ) + padding . toString ( ) . length ( ) ; if ( fModIfcInstNamedPorts == true ) { r . append ( "" ) ; curr_pos ++ ; } if ( i + < port_count ) { r . append ( "" ) ; curr_pos += ; if ( ( fModIfcInstPortsPerLine != && multi_line_instantiation && ( ( ( i + ) % fModIfcInstPortsPerLine ) == ) ) || ( curr_pos > ( * fModIfcInstMaxCharsPerLine ) / ) ) { r . append ( newline ) ; curr_pos = subseq_line_pos ; } } } r . append ( "" ) ; return r . toString ( ) ; } } package net . sf . sveditor . core . content_assist ; public enum SVCompletionProposalType { SVObject , Keyword , Unknown } package net . sf . sveditor . core . indent ; import java . util . List ; public class SVIndentStmt { protected List < SVIndentStmt > fStmtList ; protected SVIndentStmtType fType ; public SVIndentStmt ( SVIndentStmtType type ) { fType = type ; } public SVIndentStmtType getType ( ) { return fType ; } } package net . sf . sveditor . core . indent ; public class SVIndentToken { protected SVIndentTokenType fType ; protected String fLeadingWS ; protected String fTrailingWS = "" ; protected String fImage ; protected boolean fEndLine ; protected boolean fStartLine ; protected boolean fDoIt ; protected int fPos ; protected int fLineno ; public SVIndentToken ( SVIndentTokenType type , String leading_ws , String image ) { fType = type ; fLeadingWS = leading_ws ; fTrailingWS = "" ; fImage = image ; fDoIt = true ; } protected SVIndentToken ( SVIndentTokenType type , String leading_ws ) { fType = type ; fLeadingWS = leading_ws ; fTrailingWS = "" ; fImage = "" ; fDoIt = true ; } public boolean isId ( String s ) { return ( getType ( ) == SVIndentTokenType . Identifier && getImage ( ) . equals ( s ) ) ; } public boolean isOp ( String ... s ) { if ( getType ( ) == SVIndentTokenType . Operator ) { if ( s . length == ) { return true ; } else { for ( String s_i : s ) { if ( getImage ( ) . equals ( s_i ) ) { return true ; } } } } return false ; } public boolean isPreProc ( ) { return ( getType ( ) == SVIndentTokenType . Identifier && getImage ( ) . startsWith ( "" ) ) ; } public void setPos ( int pos ) { fPos = pos ; } public int getPos ( ) { return fPos ; } public void setLineno ( int lineno ) { fLineno = lineno ; } public int getLineno ( ) { return fLineno ; } public SVIndentTokenType getType ( ) { return fType ; } public void setTrailingWS ( String trailing_ws ) { fTrailingWS = trailing_ws ; } public String getTrailingWS ( ) { return fTrailingWS ; } public boolean isEndLine ( ) { return fEndLine ; } public void setIsEndLine ( boolean end ) { fEndLine = end ; } public boolean isStartLine ( ) { return fStartLine ; } public void setIsStartLine ( boolean start ) { fStartLine = start ; } public String getLeadingWS ( ) { return fLeadingWS ; } public void setLeadingWS ( String leading_ws ) { fLeadingWS = leading_ws ; } public String getImage ( ) { return fImage ; } public void setImage ( String image ) { fImage = image ; } public boolean getDoIt ( ) { return fDoIt ; } public void setDoIt ( boolean doit ) { fDoIt = doit ; } public boolean isBlankLine ( ) { return ( fStartLine && fEndLine && fImage . trim ( ) . equals ( "" ) ) ; } public boolean isComment ( ) { return ( fType == SVIndentTokenType . SingleLineComment || fType == SVIndentTokenType . MultiLineComment ) ; } } package net . sf . sveditor . core . indent ; import java . util . HashSet ; import java . util . Set ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . ITextScanner ; public class SVIndentScanner implements ISVIndentScanner { private ITextScanner fScanner ; private int fUngetCh ; private int fLastCh [ ] = { - , - } ; private int fLastChT = - ; private int fLineno ; private boolean fStartLine ; private String fLeadingWS ; private SVIndentToken fCurrent ; private static Set < String > fScopeKeywords ; private static Set < String > fQualifiers ; private StringBuilder fTmp ; private static final boolean fDebugEn = false ; private static Set < String > fOperators ; private LogHandle fLog ; private static final String fOperatorList [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , ">" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; static { fScopeKeywords = new HashSet < String > ( ) ; fScopeKeywords . add ( "" ) ; fScopeKeywords . add ( "" ) ; fScopeKeywords . add ( "" ) ; fScopeKeywords . add ( "" ) ; fQualifiers = new HashSet < String > ( ) ; fQualifiers . add ( "" ) ; fQualifiers . add ( "" ) ; fQualifiers . add ( "" ) ; fQualifiers . add ( "" ) ; fQualifiers . add ( "" ) ; fOperators = new HashSet < String > ( ) ; for ( String op : fOperatorList ) { if ( ! fOperators . contains ( op ) ) { fOperators . add ( op ) ; } } } public SVIndentScanner ( ITextScanner scanner ) { fTmp = new StringBuilder ( ) ; fScanner = scanner ; fUngetCh = - ; fLastCh [ ] = - ; fLastCh [ ] = '' ; fLineno = ; fLog = LogFactory . getLogHandle ( "" ) ; fStartLine = true ; } public SVIndentToken next ( ) { boolean start_line ; int pos = ; SVIndentToken token = null ; start_line = fStartLine ; fStartLine = false ; if ( fLeadingWS == null ) { pos = ( int ) fScanner . getPos ( ) ; fLeadingWS = getIndent ( ) ; } int c = get_ch ( ) ; int lineno = fLineno ; if ( fDebugEn ) { debug ( "" + ( char ) c + "" ) ; } if ( c == '' ) { token = new SVIndentToken ( SVIndentTokenType . BlankLine , fLeadingWS ) ; fStartLine = true ; token . setIsEndLine ( true ) ; } else if ( c == '' ) { int c2 = get_ch ( ) ; if ( c2 == '' ) { token = read_single_line_comment ( fLeadingWS ) ; token . setIsEndLine ( true ) ; } else if ( c2 == '' ) { token = read_multi_line_comment ( fLeadingWS ) ; } else { unget_ch ( c2 ) ; token = new SVIndentToken ( SVIndentTokenType . Operator , fLeadingWS , "" ) ; } } else if ( c == '' ) { int last_c = - ; fTmp . setLength ( ) ; fTmp . append ( ( char ) c ) ; while ( ( c = get_ch ( ) ) != - && ( c != '' || last_c == '' ) ) { fTmp . append ( ( char ) c ) ; last_c = c ; } fTmp . append ( ( char ) c ) ; token = new SVIndentToken ( SVIndentTokenType . String , fLeadingWS , fTmp . toString ( ) ) ; } else if ( c == '' || c == '' || Character . isJavaIdentifierStart ( c ) ) { boolean is_macro = ( c == '' ) ; int tmp_c = c ; if ( is_macro ) { c = get_ch ( ) ; } String id = readIdentifier ( c ) ; if ( is_macro ) { id = ( char ) tmp_c + id ; } token = new SVIndentToken ( SVIndentTokenType . Identifier , fLeadingWS , id ) ; } else if ( c == '' ) { token = new SVIndentToken ( SVIndentTokenType . Operator , fLeadingWS , "" ) ; } else if ( Character . isDigit ( c ) || c == '' ) { fTmp . setLength ( ) ; if ( c == '' ) { int c2 = get_ch ( ) ; if ( ( c2 >= '' && c2 <= '' ) || ( c2 >= '' && c2 <= '' ) ) { fTmp . append ( ( char ) c ) ; fTmp . append ( ( char ) c2 ) ; } else { unget_ch ( c2 ) ; token = new SVIndentToken ( SVIndentTokenType . Operator , fLeadingWS , "" ) ; } } else { fTmp . append ( ( char ) c ) ; } if ( token == null ) { while ( ( c = get_ch ( ) ) != - && ( c == '' || Character . isDigit ( c ) || ( c >= '' && c <= '' ) || ( c >= '' && c <= '' ) ) ) { fTmp . append ( ( char ) c ) ; } unget_ch ( c ) ; token = new SVIndentToken ( SVIndentTokenType . Number , fLeadingWS , fTmp . toString ( ) ) ; } } else if ( c == - ) { if ( fDebugEn ) { debug ( "" ) ; } token = null ; } else { fTmp . setLength ( ) ; fTmp . append ( ( char ) c ) ; while ( fOperators . contains ( fTmp . toString ( ) ) ) { if ( ( c = get_ch ( ) ) == - ) { break ; } fTmp . append ( ( char ) c ) ; } if ( fDebugEn ) { debug ( "" + fTmp . toString ( ) + "" ) ; } if ( ! fOperators . contains ( fTmp . toString ( ) ) ) { if ( fTmp . length ( ) > ) { fTmp . setLength ( fTmp . length ( ) - ) ; unget_ch ( c ) ; } else { unget_ch ( c ) ; } } if ( fOperators . contains ( fTmp . toString ( ) ) ) { token = new SVIndentToken ( SVIndentTokenType . Operator , fLeadingWS , fTmp . toString ( ) ) ; } else { token = null ; fLog . error ( "" + ( char ) c + "" ) ; } } fLeadingWS = null ; if ( token != null ) { token . setLineno ( lineno ) ; token . setPos ( pos ) ; c = get_ch ( ) ; if ( c == '' ) { token . setIsEndLine ( true ) ; fStartLine = true ; if ( token . getType ( ) == SVIndentTokenType . BlankLine ) { unget_ch ( c ) ; } else { fTmp . setLength ( ) ; while ( ( c = get_ch ( ) ) != - && Character . isWhitespace ( c ) && c != '' ) { fTmp . append ( ( char ) c ) ; } unget_ch ( c ) ; fLeadingWS = fTmp . toString ( ) ; } } else { if ( token . getType ( ) == SVIndentTokenType . BlankLine ) { unget_ch ( c ) ; } else { fTmp . setLength ( ) ; unget_ch ( c ) ; pos = ( int ) fScanner . getPos ( ) ; while ( ( c = get_ch ( ) ) != - && Character . isWhitespace ( c ) && c != '' ) { fTmp . append ( ( char ) c ) ; } if ( c == '' ) { token . setIsEndLine ( true ) ; token . setTrailingWS ( fTmp . toString ( ) ) ; fStartLine = true ; } else { fLeadingWS = fTmp . toString ( ) ; unget_ch ( c ) ; } } } token . setIsStartLine ( start_line ) ; if ( fDebugEn ) { debug ( "" + ( ( token . getType ( ) == SVIndentTokenType . Identifier || token . getType ( ) == SVIndentTokenType . Operator ) ? token . getImage ( ) : token . getType ( ) ) + "" + token . getLineno ( ) ) ; } } else { if ( fDebugEn ) { debug ( "" ) ; } } fCurrent = token ; return token ; } public SVIndentToken current ( ) { return fCurrent ; } private SVIndentToken read_single_line_comment ( String leading_ws ) { int c ; fTmp . setLength ( ) ; fTmp . append ( "" ) ; while ( ( c = get_ch ( ) ) != - && c != '' ) { fTmp . append ( ( char ) c ) ; } unget_ch ( c ) ; return new SVIndentToken ( SVIndentTokenType . SingleLineComment , leading_ws , fTmp . toString ( ) ) ; } private SVMultiLineIndentToken read_multi_line_comment ( String leading_ws ) { SVMultiLineIndentToken ret = new SVMultiLineIndentToken ( leading_ws ) ; int comment [ ] = { - , - } , c ; boolean read_newline = false ; fTmp . setLength ( ) ; fTmp . append ( "" ) ; while ( ( c = get_ch ( ) ) != - ) { if ( read_newline ) { if ( Character . isWhitespace ( c ) && c != '' ) { fTmp . append ( ( char ) c ) ; } else { leading_ws = fTmp . toString ( ) ; fTmp . setLength ( ) ; read_newline = false ; unget_ch ( c ) ; } } else { if ( c == '' ) { SVIndentToken tok = new SVIndentToken ( SVIndentTokenType . MultiLineComment , leading_ws , fTmp . toString ( ) ) ; tok . setIsEndLine ( true ) ; read_newline = true ; ret . addCommentLines ( tok ) ; fTmp . setLength ( ) ; leading_ws = "" ; } else { comment [ ] = comment [ ] ; comment [ ] = c ; fTmp . append ( ( char ) c ) ; if ( comment [ ] == '' && comment [ ] == '' ) { break ; } } } } if ( fTmp . length ( ) > ) { ret . addCommentLines ( new SVIndentToken ( SVIndentTokenType . MultiLineComment , leading_ws , fTmp . toString ( ) ) ) ; } if ( c == - ) { return null ; } else { return ret ; } } private String readIdentifier ( int c ) { fTmp . setLength ( ) ; fTmp . append ( ( char ) c ) ; while ( ( c = get_ch ( ) ) != - && Character . isJavaIdentifierPart ( c ) ) { fTmp . append ( ( char ) c ) ; } unget_ch ( c ) ; return fTmp . toString ( ) ; } private String getIndent ( ) { int c ; fTmp . setLength ( ) ; while ( ( c = get_ch ( ) ) != - && Character . isWhitespace ( c ) && c != '' ) { fTmp . append ( ( char ) c ) ; } if ( c != - ) { unget_ch ( c ) ; } return fTmp . toString ( ) ; } private int get_ch ( ) { int c = - ; if ( fUngetCh != - ) { c = fUngetCh ; fUngetCh = - ; } else { c = fScanner . get_ch ( ) ; if ( fDebugEn ) { debug ( "" + ( char ) c + "" ) ; } fLastCh [ ] = fLastCh [ ] ; fLastCh [ ] = c ; if ( fLastChT == '' ) { fLineno ++ ; } fLastChT = c ; } return c ; } private void unget_ch ( int ch ) { fUngetCh = ch ; } private void debug ( String msg ) { if ( fDebugEn ) { fLog . debug ( msg ) ; } } } package net . sf . sveditor . core . indent ; public interface ISVIndentScanner { SVIndentToken next ( ) ; SVIndentToken current ( ) ; } package net . sf . sveditor . core . indent ; public class SVIndentLoopStmt { } package net . sf . sveditor . core . indent ; import java . util . ArrayList ; import java . util . List ; public class SVMultiLineIndentToken extends SVIndentToken { private List < SVIndentToken > fCommentList ; public SVMultiLineIndentToken ( String leading_ws ) { super ( SVIndentTokenType . MultiLineComment , leading_ws ) ; fCommentList = new ArrayList < SVIndentToken > ( ) ; } public List < SVIndentToken > getCommentLines ( ) { return fCommentList ; } public void addCommentLines ( SVIndentToken tok ) { fCommentList . add ( tok ) ; } @ Override public String getImage ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = ; i < fCommentList . size ( ) ; i ++ ) { SVIndentToken line = fCommentList . get ( i ) ; if ( i != ) { sb . append ( line . getLeadingWS ( ) ) ; } sb . append ( line . getImage ( ) ) ; if ( line . isEndLine ( ) ) { sb . append ( "" ) ; } } return sb . toString ( ) ; } @ Override public void setImage ( String image ) { System . out . println ( "" ) ; } } package net . sf . sveditor . core . indent ; import java . io . ByteArrayOutputStream ; import java . io . PrintStream ; import java . util . ArrayList ; 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 . regex . Pattern ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVDefaultIndenter2 implements ISVIndenter { private ISVIndentScanner fScanner ; private Stack < Tuple < String , Boolean > > fIndentStack ; private List < SVIndentToken > fTokenList ; private SVIndentToken fCurrent ; private String fCurrentIndent ; private LogHandle fLog ; private int fQualifiers ; private static final boolean fDebugEn = false ; private int fNLeftParen , fNRightParen ; private String fIndentIncr = "" ; private Pattern fTabReplacePattern ; private int fAdaptiveIndentEnd ; private boolean fTestMode ; static private Map < String , Integer > fQualifierMap ; static private Set < String > fPreProcDirectives ; private class IndentEOFException extends RuntimeException { private static final long serialVersionUID = ; } static { fQualifierMap = new HashMap < String , Integer > ( ) ; fQualifierMap . put ( "" , << ) ; fQualifierMap . put ( "" , << ) ; fQualifierMap . put ( "" , << ) ; fQualifierMap . put ( "" , << ) ; fQualifierMap . put ( "" , << ) ; fQualifierMap . put ( "" , << ) ; fPreProcDirectives = new HashSet < String > ( ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; fPreProcDirectives . add ( "" ) ; } public SVDefaultIndenter2 ( ) { fIndentStack = new Stack < Tuple < String , Boolean > > ( ) ; fTokenList = new ArrayList < SVIndentToken > ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public void setAdaptiveIndent ( boolean adaptive ) { } public void setIndentIncr ( String incr ) { fIndentIncr = incr ; if ( fIndentIncr . charAt ( ) != '' ) { fTabReplacePattern = Pattern . compile ( "" ) ; } else { fTabReplacePattern = null ; } } public void setAdaptiveIndentEnd ( int lineno ) { fAdaptiveIndentEnd = lineno ; } public void setTestMode ( boolean tm ) { fTestMode = tm ; } public void init ( ISVIndentScanner scanner ) { fScanner = scanner ; push_indent_stack ( "" , true ) ; } public String indent ( ) { return indent ( - , - ) ; } public String indent ( int start_line , int end_line ) { StringBuilder sb = new StringBuilder ( ) ; SVIndentToken tok ; fNLeftParen = fNRightParen = ; while ( ( tok = next ( ) ) != null ) { try { do { if ( tok . getType ( ) == SVIndentTokenType . Identifier && fQualifierMap . containsKey ( tok . getImage ( ) ) ) { fQualifiers |= fQualifierMap . get ( tok . getImage ( ) ) ; tok = next ( ) ; } else if ( tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) ) { tok = indent_ifc_module_class ( tok . getImage ( ) ) ; fQualifiers = ; } else if ( tok . isId ( "" ) ) { tok = indent_config ( tok . getImage ( ) ) ; fQualifiers = ; } else if ( tok . isId ( "" ) ) { tok = indent_covergroup ( ) ; } else if ( tok . isId ( "" ) || tok . isId ( "" ) ) { tok = indent_task_function ( tok . getImage ( ) ) ; fQualifiers = ; } else if ( tok . isId ( "" ) ) { tok = indent_typedef ( ) ; fQualifiers = ; } else if ( tok . isOp ( "" ) ) { fQualifiers = ; tok = next ( ) ; } else { tok = next ( ) ; } } while ( ( tok = current ( ) ) != null ) ; } catch ( IndentEOFException e ) { break ; } catch ( RuntimeException e ) { if ( fTestMode ) { throw e ; } } } if ( fTestMode ) { if ( fIndentStack . size ( ) != ) { throw new RuntimeException ( "" + fIndentStack . size ( ) + "" ) ; } } if ( fDebugEn ) { debug ( "" ) ; } for ( SVIndentToken t : fTokenList ) { if ( ( t . getLineno ( ) >= start_line || start_line == - ) && ( t . getLineno ( ) <= end_line || end_line == - ) ) { if ( fDebugEn ) { debug ( "" + t . getType ( ) + "" + t . getLineno ( ) + "" + t . getImage ( ) ) ; } String leading_ws = t . getLeadingWS ( ) ; if ( t . isStartLine ( ) && fTabReplacePattern != null ) { leading_ws = fTabReplacePattern . matcher ( leading_ws ) . replaceAll ( fIndentIncr ) ; } sb . append ( leading_ws + t . getImage ( ) + t . getTrailingWS ( ) + ( ( t . isEndLine ( ) ) ? "" : "" ) ) ; } } return sb . toString ( ) ; } public String getLineIndent ( int lineno ) { String ret = null ; for ( SVIndentToken t : fTokenList ) { if ( t . getLineno ( ) == lineno ) { ret = t . getLeadingWS ( ) ; if ( t . isStartLine ( ) && fTabReplacePattern != null ) { ret = fTabReplacePattern . matcher ( ret ) . replaceAll ( fIndentIncr ) ; } break ; } } return ret ; } public boolean isQualifierSet ( String key ) { return ( ( fQualifierMap . get ( key ) & fQualifiers ) != ) ; } private SVIndentToken indent_if ( boolean is_else_if ) { SVIndentToken tok = current ( ) ; if ( fDebugEn ) { debug ( "" + tok . getImage ( ) ) ; } start_of_scope ( tok ) ; tok = next_s ( ) ; if ( tok . isOp ( "" ) ) { tok = consume_expression ( ) ; } else { return tok ; } tok = indent_if_stmts ( null ) ; if ( tok . isId ( "" ) ) { tok = next_s ( ) ; if ( tok . isId ( "" ) ) { tok = indent_if ( true ) ; } else { start_of_scope ( tok ) ; tok = indent_if_stmts ( null ) ; } } if ( fDebugEn ) { debug ( "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) ) ; } return tok ; } private SVIndentToken indent_if_stmts ( String parent ) { SVIndentToken tok = current_s ( ) ; if ( tok . isId ( "" ) ) { parent = "" ; boolean begin_is_start_line = tok . isStartLine ( ) ; if ( begin_is_start_line ) { enter_scope ( tok ) ; start_of_scope ( tok ) ; } tok = next_s ( ) ; if ( ! begin_is_start_line ) { enter_scope ( tok ) ; } else { enter_scope ( tok ) ; } while ( tok != null ) { if ( fDebugEn ) { debug ( "" + tok . getType ( ) + "" + tok . getImage ( ) ) ; } if ( tok . isId ( "" ) ) { leave_scope ( tok ) ; if ( begin_is_start_line ) { leave_scope ( ) ; } if ( fDebugEn ) { debug ( "" + peek_indent ( ) + "" ) ; } tok = next_s ( ) ; if ( begin_is_start_line ) { set_indent ( tok , false ) ; } tok = consume_labeled_block ( tok ) ; break ; } else { tok = indent_block_or_statement ( parent , true ) ; } } } else { enter_scope ( tok ) ; tok = indent_stmt ( parent ) ; leave_scope ( tok ) ; } return tok ; } private SVIndentToken indent_fork ( ) { SVIndentToken tok = current ( ) ; start_of_scope ( tok ) ; tok = next_s ( ) ; enter_scope ( tok ) ; while ( tok != null && ! tok . isId ( "" ) && ! tok . isId ( "" ) && ! tok . isId ( "" ) ) { tok = indent_block_or_statement ( "" , true ) ; } leave_scope ( tok ) ; tok = next_s ( ) ; return tok ; } private SVIndentToken indent_loop_stmt ( ) { SVIndentToken tok , first ; tok = first = current ( ) ; start_of_scope ( tok ) ; if ( fDebugEn ) { debug ( "" + tok . getImage ( ) ) ; } if ( ! tok . isId ( "" ) && ! tok . isId ( "" ) ) { tok = next_s ( ) ; if ( tok . isOp ( "" ) ) { tok = consume_expression ( ) ; } else { return tok ; } } else { tok = next_s ( ) ; } tok = indent_if_stmts ( null ) ; if ( first . isId ( "" ) ) { while ( ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } tok = next_s ( ) ; } if ( fDebugEn ) { debug ( "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) ) ; } return tok ; } private SVIndentToken indent_typedef ( ) { SVIndentToken tok = current ( ) ; boolean enum_struct = false ; start_of_scope ( tok ) ; if ( fDebugEn ) { debug ( "" ) ; } tok = next_s ( ) ; if ( tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) ) { tok = indent_struct_union_enum ( "" ) ; enum_struct = true ; } while ( ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } tok = next_s ( ) ; if ( fDebugEn ) { debug ( "" ) ; } if ( ! enum_struct ) { leave_scope ( tok ) ; } return tok ; } private SVIndentToken indent_struct_union_enum ( String parent ) { SVIndentToken tok = next_s ( ) ; if ( ! parent . equals ( "" ) ) { start_of_scope ( tok ) ; } while ( ! tok . isOp ( "" , "" ) ) { tok = next_s ( ) ; } if ( tok . isOp ( "" ) ) { tok = next_s ( ) ; if ( ! tok . isOp ( "" ) ) { enter_scope ( tok ) ; } while ( ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } } leave_scope ( tok ) ; return tok ; } private SVIndentToken indent_ifc_module_class ( String item ) { SVIndentToken tok = current_s ( ) ; String end = get_end_kw ( item ) ; if ( fDebugEn ) { debug ( "" + item + "" ) ; } start_of_scope ( tok ) ; tok = next_s ( ) ; start_of_scope ( tok ) ; while ( ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } leave_scope ( tok ) ; tok = next_s ( ) ; enter_scope ( tok ) ; fQualifiers = ; while ( tok != null ) { if ( tok . isId ( end ) ) { break ; } else if ( tok . getType ( ) == SVIndentTokenType . Identifier && fQualifierMap . containsKey ( tok . getImage ( ) ) ) { fQualifiers |= fQualifierMap . get ( tok . getImage ( ) ) ; tok = next_s ( ) ; } else if ( tok . isId ( "" ) || tok . isId ( "" ) ) { tok = indent_task_function ( tok . getImage ( ) ) ; fQualifiers = ; } else if ( tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) ) { tok = indent_ifc_module_class ( tok . getImage ( ) ) ; fQualifiers = ; } else if ( tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) ) { tok = indent_struct_union_enum ( "" ) ; fQualifiers = ; } else if ( tok . isId ( "" ) || is_always ( tok ) || tok . isId ( "" ) ) { tok = next_s ( ) ; if ( tok . isOp ( "" ) ) { tok = next_s ( ) ; tok = consume_expression ( ) ; } if ( current ( ) . getImage ( ) . equals ( "" ) ) { tok = indent_block_or_statement ( null , false ) ; } else { tok = indent_block_or_statement ( null , false ) ; } fQualifiers = ; } else if ( tok . isId ( "" ) ) { tok = indent_covergroup ( ) ; fQualifiers = ; } else if ( tok . isId ( "" ) ) { tok = indent_constraint ( ) ; fQualifiers = ; } else if ( tok . isPreProc ( ) && tok . isStartLine ( ) ) { while ( ! tok . isEndLine ( ) && ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } tok = next_s ( ) ; fQualifiers = ; } else { tok = indent_block_or_statement ( item , true ) ; } } leave_scope ( tok ) ; end_of_scope ( tok ) ; tok = consume_labeled_block ( next_s ( ) ) ; if ( fDebugEn ) { debug ( "" + item + "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) ) ; } return tok ; } private SVIndentToken indent_config ( String item ) { SVIndentToken tok = current_s ( ) ; String end = "" ; if ( fDebugEn ) { debug ( "" + item + "" ) ; } start_of_scope ( tok ) ; tok = next_s ( ) ; while ( ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } tok = next_s ( ) ; enter_scope ( tok ) ; fQualifiers = ; while ( tok != null ) { if ( tok . isId ( end ) ) { break ; } else { tok = indent_block_or_statement ( item , true ) ; } } leave_scope ( tok ) ; end_of_scope ( tok ) ; tok = consume_labeled_block ( next_s ( ) ) ; if ( fDebugEn ) { debug ( "" + item + "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) ) ; } return tok ; } private static boolean is_always ( SVIndentToken tok ) { return ( tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) ) ; } private SVIndentToken indent_covergroup ( ) { SVIndentToken tok = current_s ( ) ; start_of_scope ( tok ) ; if ( fDebugEn ) { debug ( "" ) ; } start_of_scope ( tok ) ; while ( tok != null && ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } leave_scope ( ) ; tok = next_s ( ) ; enter_scope ( tok ) ; while ( tok != null ) { if ( tok . isId ( "" ) ) { leave_scope ( tok ) ; break ; } else { tok = indent_covergroup_item ( ) ; } } tok = next_s ( ) ; if ( fDebugEn ) { debug ( "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) ) ; } return tok ; } private SVIndentToken indent_constraint ( ) { SVIndentToken tok = current_s ( ) ; start_of_scope ( tok ) ; tok = next_s ( ) ; tok = next_s ( ) ; if ( ! tok . isOp ( "" ) ) { return tok ; } tok = next_s ( ) ; enter_scope ( tok ) ; while ( ! tok . isOp ( "" ) ) { tok = indent_constraint_stmt ( ) ; } leave_scope ( tok ) ; tok = next_s ( ) ; return tok ; } private SVIndentToken indent_covergroup_item ( ) { SVIndentToken tok = current ( ) ; tok = next_s ( ) ; start_of_scope ( tok ) ; enter_scope ( tok ) ; while ( ! tok . isOp ( "" ) && ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } leave_scope ( tok ) ; if ( tok . isOp ( "" ) ) { boolean do_indent = true ; int lb_count = , rb_count = ; start_of_scope ( tok ) ; do { tok = next_s ( ) ; if ( do_indent ) { enter_scope ( tok ) ; do_indent = false ; } if ( tok . isOp ( "" ) ) { lb_count ++ ; start_of_scope ( tok ) ; do_indent = true ; } else if ( tok . isOp ( "" ) ) { rb_count ++ ; leave_scope ( tok ) ; } } while ( lb_count != rb_count ) ; } tok = next_s ( ) ; return tok ; } private SVIndentToken indent_task_function ( String item ) { SVIndentToken tok = current_s ( ) ; start_of_scope ( tok ) ; String end = get_end_kw ( item ) ; if ( fDebugEn ) { debug ( "" + item + "" ) ; } while ( tok != null && ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } if ( ! isQualifierSet ( "" ) ) { enter_scope ( tok ) ; tok = next_s ( ) ; while ( tok != null ) { if ( tok . isId ( end ) ) { break ; } else { tok = indent_block_or_statement ( item , true ) ; } } leave_scope ( tok ) ; tok = consume_labeled_block ( next_s ( ) ) ; } else { leave_scope ( ) ; tok = next_s ( ) ; } if ( fDebugEn ) { debug ( "" + item + "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) ) ; } end_of_scope ( ) ; return tok ; } private SVIndentToken indent_block_or_statement ( String parent , boolean parent_is_block ) { SVIndentToken tok = current ( ) ; if ( fDebugEn ) { debug ( "" + parent_is_block + "" + tok . getImage ( ) ) ; } if ( tok . isId ( "" ) ) { parent = "" ; start_of_scope ( tok ) ; tok = next_s ( ) ; enter_scope ( tok ) ; while ( tok != null ) { if ( fDebugEn ) { debug ( "" + tok . getType ( ) + "" + tok . getImage ( ) ) ; } if ( tok . isId ( "" ) ) { leave_scope ( tok ) ; if ( fDebugEn ) { debug ( "" + peek_indent ( ) + "" ) ; } tok = next_s ( ) ; tok = consume_labeled_block ( tok ) ; break ; } else { tok = indent_block_or_statement ( parent , true ) ; } } } else { if ( ! parent_is_block ) { start_of_scope ( tok ) ; enter_scope ( tok ) ; } tok = indent_stmt ( parent ) ; if ( ! parent_is_block ) { leave_scope ( tok ) ; } } if ( fDebugEn ) { debug ( "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) + "" + parent ) ; } return tok ; } private SVIndentToken indent_stmt ( String parent ) { SVIndentToken tok = current_s ( ) ; if ( fDebugEn ) { debug ( "" + parent + "" + tok . getImage ( ) ) ; } if ( tok . isId ( "" ) ) { tok = indent_if ( false ) ; } else if ( tok . isId ( "" ) ) { tok = indent_fork ( ) ; } else if ( tok . isId ( "" ) || tok . isId ( "" ) ) { tok = indent_case ( ) ; } else if ( is_always ( tok ) || tok . isId ( "" ) || tok . isId ( "" ) ) { enter_scope ( tok ) ; if ( ( tok = next_s ( ) ) . isOp ( "" ) ) { tok = next_s ( ) ; tok = next_s ( ) ; indent_block_or_statement ( null , false ) ; } leave_scope ( ) ; } else if ( tok . isId ( "" ) ) { tok = indent_typedef ( ) ; } else if ( tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) ) { tok = indent_loop_stmt ( ) ; } else { boolean do_next = true ; while ( ! tok . isOp ( "" ) ) { if ( parent != null ) { if ( ( parent . equals ( "" ) && tok . isId ( "" ) ) || tok . isId ( "" + parent ) ) { do_next = false ; break ; } else if ( parent . equals ( "" ) && ( tok . isId ( "" ) || tok . isId ( "" ) || tok . isId ( "" ) ) ) { do_next = false ; break ; } } if ( tok . isOp ( "" ) ) { start_of_scope ( tok ) ; } else if ( tok . isOp ( "" ) ) { leave_scope ( ) ; } tok = next_s ( ) ; } if ( do_next ) { tok = next_s ( ) ; } } if ( fDebugEn ) { debug ( "" + parent + "" + tok . getImage ( ) ) ; } return tok ; } private SVIndentToken indent_constraint_block_or_stmt ( ) { SVIndentToken tok = current_s ( ) ; if ( tok . isOp ( "" ) ) { start_of_scope ( tok ) ; tok = next_s ( ) ; enter_scope ( tok ) ; while ( ! tok . isOp ( "" ) ) { tok = indent_constraint_block_or_stmt ( ) ; } leave_scope ( tok ) ; tok = next_s ( ) ; } else { tok = indent_constraint_stmt ( ) ; } return tok ; } private SVIndentToken indent_constraint_if_block_or_stmt ( ) { SVIndentToken tok = current_s ( ) ; if ( tok . isOp ( "" ) ) { boolean begin_is_start_line = tok . isStartLine ( ) ; if ( begin_is_start_line ) { enter_scope ( tok ) ; } tok = next_s ( ) ; if ( ! begin_is_start_line ) { enter_scope ( tok ) ; } while ( ! tok . isOp ( "" ) ) { tok = indent_constraint_block_or_stmt ( ) ; } leave_scope ( tok ) ; tok = next_s ( ) ; } else { enter_scope ( tok ) ; tok = indent_constraint_stmt ( ) ; leave_scope ( tok ) ; } return tok ; } private SVIndentToken indent_constraint_stmt ( ) { SVIndentToken tok = current_s ( ) ; if ( tok . isId ( "" ) ) { tok = indent_constraint_if ( false ) ; } else if ( tok . isOp ( "" ) ) { tok = consume_expression ( ) ; if ( tok . isOp ( "" ) || tok . isOp ( "" ) ) { tok = next_s ( ) ; tok = indent_constraint_block_or_stmt ( ) ; } } else { while ( ! tok . isOp ( "" ) ) { tok = next_s ( ) ; } tok = next_s ( ) ; } return tok ; } private SVIndentToken indent_constraint_if ( boolean is_else_if ) { SVIndentToken tok = current ( ) ; if ( fDebugEn ) { debug ( "" + tok . getImage ( ) ) ; } start_of_scope ( tok ) ; tok = next_s ( ) ; if ( tok . isOp ( "" ) ) { tok = consume_expression ( ) ; } else { return tok ; } enter_scope ( tok ) ; tok = indent_constraint_if_block_or_stmt ( ) ; if ( tok . isId ( "" ) ) { tok = next_s ( ) ; if ( tok . isId ( "" ) ) { tok = indent_constraint_if ( true ) ; } else { tok = indent_constraint_block_or_stmt ( ) ; } } if ( fDebugEn ) { debug ( "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) ) ; } return tok ; } private SVIndentToken indent_case ( ) { SVIndentToken tok = current ( ) ; String type = tok . getImage ( ) ; enter_scope ( tok ) ; start_of_scope ( tok ) ; if ( type . equals ( "" ) ) { tok = next_s ( ) ; } tok = next_s ( ) ; enter_scope ( tok ) ; while ( ! tok . isId ( "" ) ) { while ( ! tok . isOp ( "" ) && ! tok . isId ( "" ) ) { tok = next_s ( ) ; } if ( tok . isOp ( "" ) ) { tok = next_s ( ) ; tok = indent_block_or_statement ( "" , false ) ; } } leave_scope ( ) ; if ( tok . isId ( "" ) ) { set_indent ( tok , false ) ; } tok = next_s ( ) ; return tok ; } private void start_of_scope ( SVIndentToken tok ) { incr_indent ( true ) ; if ( fDebugEn ) { debug ( "" + peek_indent ( ) + "" ) ; } } private void end_of_scope ( ) { end_of_scope ( null ) ; } private void end_of_scope ( SVIndentToken tok ) { } private void enter_scope ( SVIndentToken tok ) { set_indent ( tok , false ) ; if ( fDebugEn ) { debug ( "" + peek_indent ( ) + "" ) ; } } private void leave_scope ( ) { leave_scope ( null ) ; } private void leave_scope ( SVIndentToken tok ) { pop_indent ( tok ) ; if ( fDebugEn ) { debug ( "" + peek_indent ( ) + "" ) ; } } private void push_indent_stack ( String indent , boolean provisional ) { if ( fDebugEn ) { debug ( "" + ( fIndentStack . size ( ) + ) + "" + indent + "" + provisional ) ; } fIndentStack . push ( new Tuple < String , Boolean > ( indent , provisional ) ) ; } private String peek_indent ( ) { return fIndentStack . peek ( ) . first ( ) ; } private void incr_indent ( boolean provisional ) { push_indent_stack ( fIndentStack . peek ( ) . first ( ) + fIndentIncr , provisional ) ; if ( fDebugEn ) { debug ( "" + provisional + "" + "" + peek_indent ( ) + "" ) ; } } private void pop_indent ( SVIndentToken tok ) { if ( fDebugEn ) { String img = ( tok != null ) ? tok . getImage ( ) : "" ; debug ( "" + ( fIndentStack . size ( ) - ) + "" + img + "" ) ; } if ( fIndentStack . size ( ) > ) { fIndentStack . pop ( ) ; } else { if ( fTestMode ) { throw new RuntimeException ( "" ) ; } if ( fDebugEn ) { debug ( "" ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; PrintStream ps = new PrintStream ( bos ) ; try { throw new Exception ( ) ; } catch ( Exception e ) { e . printStackTrace ( ps ) ; } ps . flush ( ) ; debug ( bos . toString ( ) ) ; } } if ( tok != null ) { set_indent ( tok , false ) ; } if ( fDebugEn ) { debug ( "" + peek_indent ( ) + "" ) ; } } private void set_indent ( SVIndentToken tok , boolean implicit ) { if ( tok . isStartLine ( ) ) { if ( isAdaptiveTraining ( tok ) && fIndentStack . peek ( ) . second ( ) && ! tok . isBlankLine ( ) && ! tok . isComment ( ) ) { if ( fDebugEn ) { debug ( "" + fIndentStack . peek ( ) . first ( ) + "" + fCurrentIndent + "" + tok . getImage ( ) + "" ) ; } fIndentStack . peek ( ) . setFirst ( fCurrentIndent ) ; } debug ( "" + implicit + "" + tok . getImage ( ) + "" + peek_indent ( ) + "" ) ; tok . setLeadingWS ( peek_indent ( ) ) ; } } private void indent_multi_line_comment ( SVIndentToken tok ) { SVMultiLineIndentToken ml_comment = ( SVMultiLineIndentToken ) tok ; if ( tok . isStartLine ( ) ) { set_indent ( tok , false ) ; for ( SVIndentToken line : ml_comment . getCommentLines ( ) ) { if ( line . getImage ( ) . startsWith ( "" ) ) { line . setLeadingWS ( peek_indent ( ) + "" ) ; } } } else { if ( fDebugEn ) { debug ( "" ) ; } } } private SVIndentToken consume_labeled_block ( SVIndentToken tok ) { if ( tok . isOp ( "" ) ) { tok = next_s ( ) ; tok = next_s ( ) ; } return tok ; } private SVIndentToken consume_expression ( ) { SVIndentToken tok = current ( ) ; int n_lbrace = , n_rbrace = ; do { if ( tok . isOp ( "" ) ) { n_lbrace ++ ; } else if ( tok . isOp ( "" ) ) { n_rbrace ++ ; } tok = next_s ( ) ; } while ( n_lbrace != n_rbrace ) ; return tok ; } private boolean isAdaptiveTraining ( SVIndentToken tok ) { return ( fAdaptiveIndentEnd != - && tok . getLineno ( ) <= fAdaptiveIndentEnd ) ; } private SVIndentToken next ( ) { SVIndentToken tok = null ; while ( ( tok = fScanner . next ( ) ) != null && ( tok . getType ( ) == SVIndentTokenType . BlankLine || tok . getType ( ) == SVIndentTokenType . MultiLineComment || tok . getType ( ) == SVIndentTokenType . SingleLineComment || ( tok . isPreProc ( ) && fPreProcDirectives . contains ( tok . getImage ( ) ) ) ) ) { if ( tok . getType ( ) == SVIndentTokenType . SingleLineComment ) { set_indent ( tok , true ) ; fTokenList . add ( tok ) ; } else if ( tok . getType ( ) == SVIndentTokenType . MultiLineComment ) { indent_multi_line_comment ( tok ) ; fTokenList . add ( tok ) ; } else if ( tok . isPreProc ( ) && ! tok . getImage ( ) . equals ( "" ) ) { Stack < Tuple < String , Boolean > > stack = fIndentStack ; fIndentStack = new Stack < Tuple < String , Boolean > > ( ) ; push_indent_stack ( "" , false ) ; set_indent ( tok , true ) ; while ( tok != null && ! tok . isEndLine ( ) ) { fTokenList . add ( tok ) ; tok = fScanner . next ( ) ; if ( fDebugEn ) { debug ( "" + ( ( tok != null ) ? tok . getImage ( ) : "" ) ) ; } } if ( tok != null ) { fTokenList . add ( tok ) ; } fIndentStack = stack ; } else { fTokenList . add ( tok ) ; } } if ( tok != null ) { if ( tok . isOp ( "" ) ) { if ( fNLeftParen == fNRightParen ) { } fNLeftParen ++ ; } else if ( tok . isOp ( "" ) ) { fNRightParen ++ ; if ( fNLeftParen == fNRightParen ) { fNLeftParen = fNRightParen = ; } } if ( tok . isStartLine ( ) ) { fCurrentIndent = tok . getLeadingWS ( ) ; set_indent ( tok , true ) ; } fTokenList . add ( tok ) ; } fCurrent = tok ; return tok ; } private SVIndentToken current ( ) { return fCurrent ; } private SVIndentToken current_s ( ) { if ( current ( ) == null ) { throw new RuntimeException ( ) ; } return current ( ) ; } private SVIndentToken next_s ( ) { SVIndentToken ret = next ( ) ; if ( fDebugEn ) { if ( ret != null ) { debug ( "" + ret . getImage ( ) ) ; } else { debug ( "" ) ; } } if ( ret == null ) { throw new IndentEOFException ( ) ; } return ret ; } private static String get_end_kw ( String kw ) { if ( kw . equals ( "" ) ) { return "" ; } else { return "" + kw ; } } private void debug ( String msg ) { if ( fDebugEn ) { fLog . debug ( msg ) ; } } } package net . sf . sveditor . core . indent ; import java . util . ArrayList ; import java . util . List ; public class SVIndentExprToken extends SVIndentToken { protected List < SVIndentToken > fExprElems ; public SVIndentExprToken ( String leading_ws ) { super ( SVIndentTokenType . Expression , leading_ws ) ; fExprElems = new ArrayList < SVIndentToken > ( ) ; } public List < SVIndentToken > getExprElems ( ) { return fExprElems ; } public void addExprElem ( SVIndentToken elem ) { fExprElems . add ( elem ) ; } @ Override public String getImage ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = ; i < fExprElems . size ( ) ; i ++ ) { SVIndentToken tok = fExprElems . get ( i ) ; if ( i > ) { sb . append ( tok . getLeadingWS ( ) ) ; } sb . append ( tok . getImage ( ) ) ; } return sb . toString ( ) ; } } package net . sf . sveditor . core . indent ; public interface ISVIndenter { void setIndentIncr ( String incr ) ; void init ( ISVIndentScanner scanner ) ; String indent ( ) ; String indent ( int start , int end ) ; String getLineIndent ( int lineno ) ; void setAdaptiveIndent ( boolean en ) ; void setAdaptiveIndentEnd ( int lineno ) ; void setTestMode ( boolean tm ) ; } package net . sf . sveditor . core . indent ; public enum SVIndentStmtType { Block , Loop , If , Case } package net . sf . sveditor . core . indent ; public enum SVIndentTokenType { Identifier , Operator , Expression , MultiLineComment , SingleLineComment , Number , BlankLine , String } package net . sf . sveditor . core . log ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . List ; public class LogCategory { private String fCategory ; private int fLogLevel ; private List < WeakReference < ILogHandle > > fLogHandles ; public LogCategory ( String category , int level ) { fCategory = category ; fLogLevel = level ; fLogHandles = new ArrayList < WeakReference < ILogHandle > > ( ) ; } public String getCategory ( ) { return fCategory ; } public void setLogLevel ( int level ) { fLogLevel = level ; for ( int i = ; i < fLogHandles . size ( ) ; i ++ ) { WeakReference < ILogHandle > lr = fLogHandles . get ( i ) ; if ( lr . get ( ) == null ) { fLogHandles . remove ( i ) ; i -- ; } else { lr . get ( ) . setDebugLevel ( level ) ; } } } public int getLogLevel ( ) { return fLogLevel ; } public void addLogHandle ( ILogHandle handle ) { handle . setDebugLevel ( fLogLevel ) ; fLogHandles . add ( new WeakReference < ILogHandle > ( handle ) ) ; } public void removeLogHandle ( ILogHandle handle ) { fLogHandles . remove ( handle ) ; } } package net . sf . sveditor . core . log ; public interface ILogListener { int Type_Info = ; int Type_Debug = ; int Type_Error = ; void message ( ILogHandle handle , int type , int level , String message ) ; } package net . sf . sveditor . core . log ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; public class LogFactory implements ILogListener { private static LogFactory fDefault ; private Map < String , LogHandle > fLogHandleMap ; private int fLogLevel = ; private Map < String , LogCategory > fLogHandleCategoryMap ; private List < WeakReference < ILogListener > > fLogListeners ; public LogFactory ( ) { fLogHandleMap = new HashMap < String , LogHandle > ( ) ; fLogHandleCategoryMap = new HashMap < String , LogCategory > ( ) ; fLogListeners = new ArrayList < WeakReference < ILogListener > > ( ) ; } public synchronized static LogFactory getDefault ( ) { if ( fDefault == null ) { fDefault = new LogFactory ( ) ; } return fDefault ; } public static synchronized LogHandle getLogHandle ( String name ) { return getLogHandle ( name , ILogHandle . LOG_CAT_DEFAULT ) ; } public void setLogLevel ( String category , int level ) { if ( category == null ) { fLogLevel = level ; for ( Entry < String , LogCategory > e : fLogHandleCategoryMap . entrySet ( ) ) { e . getValue ( ) . setLogLevel ( level ) ; } } else { LogCategory cat ; if ( fLogHandleCategoryMap . containsKey ( category ) ) { cat = new LogCategory ( category , level ) ; fLogHandleCategoryMap . put ( category , cat ) ; } else { cat = fLogHandleCategoryMap . get ( category ) ; } cat . setLogLevel ( level ) ; } } public static synchronized LogHandle getLogHandle ( String name , String category ) { LogFactory f = getDefault ( ) ; boolean created = false ; LogHandle handle = null ; synchronized ( f . fLogHandleMap ) { if ( ! f . fLogHandleMap . containsKey ( name ) ) { handle = new LogHandle ( name , category ) ; handle . init ( f ) ; f . fLogHandleMap . put ( name , handle ) ; created = true ; } else { handle = f . fLogHandleMap . get ( name ) ; } } if ( created ) { synchronized ( f . fLogHandleCategoryMap ) { LogCategory cat ; if ( ! f . fLogHandleCategoryMap . containsKey ( handle . getCategory ( ) ) ) { cat = new LogCategory ( handle . getCategory ( ) , f . fLogLevel ) ; f . fLogHandleCategoryMap . put ( handle . getCategory ( ) , cat ) ; } else { cat = f . fLogHandleCategoryMap . get ( handle . getCategory ( ) ) ; } cat . addLogHandle ( handle ) ; } } return handle ; } public static void removeLogHandle ( LogHandle log ) { LogFactory f = getDefault ( ) ; synchronized ( f . fLogHandleMap ) { f . fLogHandleMap . remove ( log . getName ( ) ) ; } synchronized ( f . fLogHandleCategoryMap ) { f . fLogHandleCategoryMap . get ( log . getCategory ( ) ) . removeLogHandle ( log ) ; } } public void addLogListener ( ILogListener l ) { synchronized ( fLogListeners ) { fLogListeners . add ( new WeakReference < ILogListener > ( l ) ) ; } } public void removeLogListener ( ILogListener l ) { synchronized ( fLogListeners ) { for ( int i = ; i < fLogListeners . size ( ) ; i ++ ) { if ( fLogListeners . get ( i ) . get ( ) == l ) { fLogListeners . remove ( i ) ; } } } } public void message ( ILogHandle handle , int type , int level , String message ) { synchronized ( fLogListeners ) { for ( int i = ; i < fLogListeners . size ( ) ; i ++ ) { WeakReference < ILogListener > lr = fLogListeners . get ( i ) ; if ( lr . get ( ) == null ) { fLogListeners . remove ( i ) ; i -- ; } else { lr . get ( ) . message ( handle , type , level , message ) ; } } } } } package net . sf . sveditor . core . log ; public interface ILogHandle extends ILogLevel { String LOG_CAT_DEFAULT = "" ; String LOG_CAT_PARSER = "" ; String getName ( ) ; void init ( ILogListener parent ) ; void print ( int type , int level , String msg ) ; void println ( int type , int level , String msg ) ; boolean isEnabled ( ) ; int getDebugLevel ( ) ; void setDebugLevel ( int level ) ; void addLogLevelListener ( ILogLevelListener l ) ; } package net . sf . sveditor . core . log ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . List ; public class LogHandle implements ILogHandle { private String fName ; private String fCategory ; private ILogListener fListener ; private int fDebugLevel = ; private int fIndent ; private List < WeakReference < ILogLevelListener > > fLogLevelListeners ; public LogHandle ( String name ) { this ( name , LOG_CAT_DEFAULT ) ; } public LogHandle ( String name , String category ) { fName = name ; fCategory = category ; fLogLevelListeners = new ArrayList < WeakReference < ILogLevelListener > > ( ) ; } public void init ( ILogListener parent ) { fListener = parent ; } public String getName ( ) { return fName ; } public String getCategory ( ) { return fCategory ; } public void addLogLevelListener ( ILogLevelListener l ) { fLogLevelListeners . add ( new WeakReference < ILogLevelListener > ( l ) ) ; } public void setDebugLevel ( int level ) { if ( fDebugLevel != level ) { fDebugLevel = level ; for ( int i = ; i < fLogLevelListeners . size ( ) ; i ++ ) { WeakReference < ILogLevelListener > l = fLogLevelListeners . get ( i ) ; if ( l == null || l . get ( ) == null ) { fLogLevelListeners . remove ( i ) ; i -- ; } else { l . get ( ) . logLevelChanged ( this ) ; } } } fDebugLevel = level ; } public int getDebugLevel ( ) { return fDebugLevel ; } public boolean isEnabled ( ) { return ( fDebugLevel > ) ; } public boolean isEnabled ( int level ) { return ( fDebugLevel > level ) ; } public void print ( int type , int level , String msg ) { } public void println ( int type , int level , String msg ) { fListener . message ( this , type , level , msg ) ; } public void note ( String msg ) { println ( ILogListener . Type_Info , , msg ) ; } public void debug ( String msg ) { println ( ILogListener . Type_Debug , , ( fIndent > ) ? ( indent ( fIndent ) + msg ) : msg ) ; } public void debug ( String msg , Exception e ) { int level = ILogListener . Type_Error + ILogListener . Type_Debug ; println ( level , , msg ) ; println ( level , , e . getMessage ( ) ) ; for ( StackTraceElement s_e : e . getStackTrace ( ) ) { String m = "" + s_e . getClassName ( ) + "" + s_e . getMethodName ( ) + "" + s_e . getFileName ( ) + "" + s_e . getLineNumber ( ) + "" ; println ( level , , m ) ; } } public void debug ( int level , String msg ) { println ( ILogListener . Type_Debug , level , ( fIndent > ) ? ( indent ( fIndent ) + msg ) : msg ) ; } public void debug ( int level , String msg , Exception e ) { int type = ILogListener . Type_Error + ILogListener . Type_Debug ; println ( type , level , msg ) ; println ( type , level , e . getMessage ( ) ) ; for ( StackTraceElement s_e : e . getStackTrace ( ) ) { String m = "" + s_e . getClassName ( ) + "" + s_e . getMethodName ( ) + "" + s_e . getFileName ( ) + "" + s_e . getLineNumber ( ) + "" ; println ( type , level , m ) ; } } public void enter ( String msg ) { debug ( msg ) ; fIndent ++ ; } public void leave ( String msg ) { if ( fIndent > ) { fIndent -- ; } debug ( msg ) ; } public void error ( String msg ) { println ( ILogListener . Type_Error , fDebugLevel , msg ) ; } public void error ( String msg , Exception e ) { println ( ILogListener . Type_Error , fDebugLevel , msg ) ; println ( ILogListener . Type_Error , fDebugLevel , e . getMessage ( ) ) ; for ( StackTraceElement s_e : e . getStackTrace ( ) ) { println ( ILogListener . Type_Error , fDebugLevel , "" + s_e . getClassName ( ) + "" + s_e . getMethodName ( ) + "" + s_e . getFileName ( ) + "" + s_e . getLineNumber ( ) + "" ) ; } } private String indent ( int ind ) { String ret = "" ; while ( ind -- > ) { ret += "" ; } return ret ; } } package net . sf . sveditor . core . log ; public interface ILogLevelListener extends ILogLevel { void logLevelChanged ( ILogHandle handle ) ; } package net . sf . sveditor . core . log ; public interface ILogLevel { int LEVEL_OFF = ; int LEVEL_MIN = ; int LEVEL_MID = ; int LEVEL_MAX = ; } package net . sf . sveditor . core . job_mgr ; import org . eclipse . core . runtime . NullProgressMonitor ; public class JobMgrWorkerThread extends Thread { public enum ThreadState { Waiting , Working } ; private ThreadState fState ; private int fIdleTimeout = ; private JobMgr fJobMgr ; public JobMgrWorkerThread ( JobMgr mgr ) { super ( "" ) ; fJobMgr = mgr ; } public synchronized ThreadState getThreadState ( ) { return fState ; } @ Override public void run ( ) { while ( true ) { IJob job = fJobMgr . dequeueJob ( fIdleTimeout ) ; if ( job != null ) { try { job . run ( new NullProgressMonitor ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } fJobMgr . jobEnded ( job ) ; } else { if ( fJobMgr . tryToExit ( this ) ) { break ; } } } } } package net . sf . sveditor . core . job_mgr ; public interface IJobMgr { IJob createJob ( ) ; void queueJob ( IJob job ) ; void addJobListener ( IJobListener l ) ; void removeJobListener ( IJobListener l ) ; void dispose ( ) ; } package net . sf . sveditor . core . job_mgr ; public interface IJobListener { void jobStarted ( IJob job ) ; void jobEnded ( IJob job ) ; } package net . sf . sveditor . core . job_mgr ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IJob { void init ( String name , Runnable runnable ) ; String getName ( ) ; void setPriority ( int p ) ; int getPriority ( ) ; void run ( IProgressMonitor monitor ) ; void addListener ( IJobListener l ) ; void removeListener ( IJobListener l ) ; void clearListeners ( ) ; void join ( ) ; boolean join ( int wait_ms ) ; } package net . sf . sveditor . core . job_mgr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . job_mgr . JobMgrWorkerThread . ThreadState ; public class JobMgr implements IJobMgr { private List < IJobListener > fJobListeners ; private List < JobMgrWorkerThread > fThreadPool ; private List < IJob > fJobQueue ; private int fMaxThreads ; private boolean fDisposed ; public JobMgr ( ) { fJobListeners = new ArrayList < IJobListener > ( ) ; fThreadPool = new ArrayList < JobMgrWorkerThread > ( ) ; fJobQueue = new ArrayList < IJob > ( ) ; fMaxThreads = ; } public void dispose ( ) { fDisposed = true ; synchronized ( fThreadPool ) { while ( fThreadPool . size ( ) > ) { try { fThreadPool . wait ( ) ; } catch ( InterruptedException e ) { break ; } } } } public void addJobListener ( IJobListener l ) { synchronized ( fJobListeners ) { fJobListeners . add ( l ) ; } } public void removeJobListener ( IJobListener l ) { synchronized ( fJobListeners ) { fJobListeners . remove ( l ) ; } } public IJob createJob ( ) { return new JobMgrJob ( ) ; } public void queueJob ( IJob job ) { checkWorkerThreads ( ) ; synchronized ( fJobQueue ) { if ( fJobQueue . size ( ) == || fJobQueue . get ( fJobQueue . size ( ) - ) . getPriority ( ) <= job . getPriority ( ) ) { fJobQueue . add ( job ) ; } else { boolean added = false ; for ( int i = ; i < fJobQueue . size ( ) ; i ++ ) { if ( fJobQueue . get ( i ) . getPriority ( ) > job . getPriority ( ) ) { fJobQueue . add ( i , job ) ; added = true ; break ; } } if ( ! added ) { fJobQueue . add ( job ) ; } } fJobQueue . notifyAll ( ) ; } } private void checkWorkerThreads ( ) { synchronized ( fThreadPool ) { boolean all_busy = true ; for ( JobMgrWorkerThread t : fThreadPool ) { if ( t . getThreadState ( ) == ThreadState . Waiting ) { all_busy = false ; } } if ( all_busy && fThreadPool . size ( ) < fMaxThreads ) { JobMgrWorkerThread t = new JobMgrWorkerThread ( this ) ; fThreadPool . add ( t ) ; t . start ( ) ; } } } public IJob dequeueJob ( int idle_timeout ) { IJob job = null ; for ( int i = ; i < ; i ++ ) { synchronized ( fJobQueue ) { if ( fJobQueue . size ( ) > ) { job = fJobQueue . remove ( ) ; break ; } else if ( i == ) { try { fJobQueue . wait ( idle_timeout ) ; } catch ( InterruptedException e ) { } } } } if ( job != null ) { jobStarted ( job ) ; } return job ; } private void jobStarted ( IJob job ) { synchronized ( fJobListeners ) { for ( IJobListener l : fJobListeners ) { l . jobStarted ( job ) ; } } } void jobEnded ( IJob job ) { synchronized ( fJobListeners ) { for ( IJobListener l : fJobListeners ) { l . jobEnded ( job ) ; } } } public boolean tryToExit ( JobMgrWorkerThread t ) { boolean can_exit = true ; synchronized ( fThreadPool ) { can_exit = ( fThreadPool . size ( ) > || fDisposed ) ; if ( can_exit ) { fThreadPool . remove ( t ) ; fThreadPool . notifyAll ( ) ; } } return can_exit ; } } package net . sf . sveditor . core . job_mgr ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; public class JobMgrJob implements IJob { private List < IJobListener > fJobListeners ; private String fName ; private Runnable fRunnable ; private Object fJobDoneMutex ; private boolean fJobDone ; private int fPriority = ; public JobMgrJob ( ) { fJobListeners = new ArrayList < IJobListener > ( ) ; fJobDoneMutex = new Object ( ) ; } public void init ( String name , Runnable runnable ) { fName = name ; fRunnable = runnable ; fJobDone = false ; } public String getName ( ) { return fName ; } public void setPriority ( int p ) { fPriority = p ; } public int getPriority ( ) { return fPriority ; } public void run ( IProgressMonitor monitor ) { try { jobStarted ( ) ; fRunnable . run ( ) ; } finally { jobEnded ( ) ; } } private void jobStarted ( ) { synchronized ( fJobDoneMutex ) { fJobDone = false ; } synchronized ( fJobListeners ) { for ( IJobListener l : fJobListeners ) { l . jobStarted ( this ) ; } } } private void jobEnded ( ) { synchronized ( fJobDoneMutex ) { fJobDone = true ; fJobDoneMutex . notifyAll ( ) ; } synchronized ( fJobListeners ) { for ( IJobListener l : fJobListeners ) { l . jobEnded ( this ) ; } } } public void addListener ( IJobListener l ) { synchronized ( fJobListeners ) { fJobListeners . add ( l ) ; } } public void removeListener ( IJobListener l ) { synchronized ( fJobListeners ) { fJobListeners . remove ( l ) ; } } public void clearListeners ( ) { synchronized ( fJobListeners ) { fJobListeners . clear ( ) ; } } public void join ( ) { synchronized ( fJobDoneMutex ) { while ( ! fJobDone ) { try { fJobDoneMutex . wait ( ) ; } catch ( InterruptedException e ) { break ; } } } } public boolean join ( int wait_ms ) { boolean job_done = false ; synchronized ( fJobDoneMutex ) { if ( ! fJobDone ) { try { fJobDoneMutex . wait ( wait_ms ) ; } catch ( InterruptedException e ) { } } job_done = fJobDone ; } return job_done ; } } package net . sf . sveditor . core . job_mgr ; public class SVJobException extends Exception { private static final long serialVersionUID = ; public SVJobException ( String msg ) { super ( msg ) ; } } package net . sf . sveditor . core . dirtree ; import java . util . ArrayList ; import java . util . List ; public class SVDBDirTreeNode { private String fName ; private boolean fIsDir ; private SVDBDirTreeNode fParent ; private List < SVDBDirTreeNode > fChildren ; public SVDBDirTreeNode ( SVDBDirTreeNode parent , String name , boolean is_dir ) { fParent = parent ; fName = name ; fIsDir = is_dir ; fChildren = new ArrayList < SVDBDirTreeNode > ( ) ; } public void addChild ( SVDBDirTreeNode node ) { fChildren . add ( node ) ; } public List < SVDBDirTreeNode > getChildren ( ) { return fChildren ; } public boolean isDir ( ) { return fIsDir ; } public String getName ( ) { return fName ; } public SVDBDirTreeNode getParent ( ) { return fParent ; } public SVDBDirTreeNode findChild ( String name ) { for ( SVDBDirTreeNode n : fChildren ) { if ( n . getName ( ) . equals ( name ) ) { return n ; } } return null ; } @ Override public int hashCode ( ) { return fName . hashCode ( ) ; } } package net . sf . sveditor . core . dirtree ; import net . sf . sveditor . core . SVFileUtils ; public class SVDBDirTreeFactory { private SVDBDirTreeNode fRoot ; public SVDBDirTreeFactory ( ) { fRoot = new SVDBDirTreeNode ( null , "" , true ) ; } public void addPath ( String path , boolean is_dir ) { path = SVFileUtils . normalize ( path ) ; String path_s [ ] = path . split ( "" ) ; addPath ( fRoot , path_s , , is_dir ) ; } private void addPath ( SVDBDirTreeNode parent , String path_s [ ] , int path_idx , boolean is_dir ) { String elem = path_s [ path_idx ] ; SVDBDirTreeNode child ; if ( ( child = parent . findChild ( elem ) ) == null ) { child = new SVDBDirTreeNode ( parent , elem , ( is_dir || path_idx + != path_s . length ) ) ; parent . addChild ( child ) ; } if ( path_idx + < path_s . length ) { addPath ( child , path_s , path_idx + , is_dir ) ; } } public SVDBDirTreeNode buildTree ( ) { return fRoot ; } } package net . sf . sveditor . core ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import java . io . PrintWriter ; import java . security . MessageDigest ; import java . util . regex . Pattern ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Path ; public class SVFileUtils { private static Pattern fWinPathPattern ; public static boolean fIsWinPlatform ; static { fWinPathPattern = Pattern . compile ( "" ) ; } public static String getPathParent ( String path ) { String parent = new File ( path ) . getParent ( ) ; if ( parent == null ) { parent = path ; } return fWinPathPattern . matcher ( parent ) . replaceAll ( "" ) ; } public static String getPathLeaf ( String path ) { String leaf = new File ( path ) . getName ( ) ; return leaf ; } public static String normalize ( String path ) { if ( path . indexOf ( '' ) != - ) { path = fWinPathPattern . matcher ( path ) . replaceAll ( "" ) ; if ( path . length ( ) >= && path . charAt ( ) == '' && Character . isLetter ( path . charAt ( ) ) && path . charAt ( ) == '' ) { path = path . substring ( ) ; } } return path ; } public static IContainer getWorkspaceFolder ( String path ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IResource r = null ; IProject p = null ; path = normalize ( path ) ; try { if ( ( r = root . getFolder ( new Path ( path ) ) ) != null && r . exists ( ) ) { return ( IContainer ) r ; } } catch ( IllegalArgumentException e ) { } String pname = path ; if ( pname . startsWith ( "" ) ) { pname = pname . substring ( ) ; } if ( pname . endsWith ( "" ) ) { pname = pname . substring ( , pname . length ( ) - ) ; } for ( IProject p_t : root . getProjects ( ) ) { if ( p_t . getName ( ) . equals ( pname ) ) { p = p_t ; break ; } } return p ; } public static IFile getWorkspaceFile ( String path ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IFile f = null ; path = normalize ( path ) ; f = root . getFile ( new Path ( path ) ) ; if ( ! f . exists ( ) ) { f = null ; } return f ; } public static IFile findWorkspaceFile ( String path ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IFile f = root . getFileForLocation ( new Path ( path ) ) ; return f ; } public static IContainer findWorkspaceFolder ( String path ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IContainer c = root . getContainerForLocation ( new Path ( path ) ) ; return c ; } private static String convertToHex ( byte [ ] data ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < data . length ; i ++ ) { int halfbyte = ( data [ i ] > > > ) & ; int two_halfs = ; do { if ( ( <= halfbyte ) && ( halfbyte <= ) ) buf . append ( ( char ) ( '' + halfbyte ) ) ; else buf . append ( ( char ) ( '' + ( halfbyte - ) ) ) ; halfbyte = data [ i ] & ; } while ( two_halfs ++ < ) ; } return buf . toString ( ) ; } public static String computeMD5 ( String text ) { try { MessageDigest md ; md = MessageDigest . getInstance ( "" ) ; byte [ ] md5hash = new byte [ ] ; md . update ( text . getBytes ( "" ) , , text . length ( ) ) ; md5hash = md . digest ( ) ; return convertToHex ( md5hash ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return "" ; } public static void writeToFile ( File file , String content ) { try { PrintWriter out = new PrintWriter ( new FileWriter ( file . toString ( ) ) ) ; out . print ( content ) ; out . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } public static void delete ( File file ) { if ( ! file . exists ( ) ) { return ; } if ( file . isDirectory ( ) ) { for ( File f : file . listFiles ( ) ) { delete ( f ) ; } } file . delete ( ) ; } } package net . sf . sveditor . core . db ; public class SVDBGenerateBlock extends SVDBScopeItem { public SVDBGenerateBlock ( ) { super ( "" , SVDBItemType . GenerateBlock ) ; } public SVDBGenerateBlock ( String name ) { super ( name , SVDBItemType . GenerateBlock ) ; } } package net . sf . sveditor . core . db ; import java . util . Iterator ; public class SVDBUtil { public static int getChildrenSize ( ISVDBChildParent p ) { int count = ; Iterator < ISVDBChildItem > it = p . getChildren ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { count ++ ; it . next ( ) ; } return count ; } public static ISVDBChildItem getFirstChildItem ( ISVDBChildParent p ) { Iterator < ISVDBChildItem > it = p . getChildren ( ) . iterator ( ) ; if ( it . hasNext ( ) ) { return it . next ( ) ; } else { return null ; } } public static void addAllChildren ( ISVDBChildParent dest , ISVDBChildParent src ) { for ( ISVDBChildItem c : src . getChildren ( ) ) { dest . addChildItem ( c ) ; } } } package net . sf . sveditor . core . db ; public interface ISVDBChildParent extends ISVDBChildItem , ISVDBAddChildItem { Iterable < ISVDBChildItem > getChildren ( ) ; } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBModIfcClassParam extends SVDBItem { public SVDBExpr fDefault ; public SVDBTypeInfo fDefaultType ; public SVDBModIfcClassParam ( ) { super ( "" , SVDBItemType . ModIfcClassParam ) ; } public SVDBModIfcClassParam ( String name ) { super ( name , SVDBItemType . ModIfcClassParam ) ; } public SVDBExpr getDefault ( ) { return fDefault ; } public void setDefault ( SVDBExpr dflt ) { fDefault = dflt ; } public SVDBTypeInfo getDefaultType ( ) { return fDefaultType ; } public void setDefaultType ( SVDBTypeInfo type ) { fDefaultType = type ; } public SVDBModIfcClassParam duplicate ( ) { return ( SVDBModIfcClassParam ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; fDefault = ( ( SVDBModIfcClassParam ) other ) . fDefault ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBClassDecl extends SVDBScopeItem { public List < SVDBModIfcClassParam > fParams ; public SVDBTypeInfoClassType fClassType ; public SVDBTypeInfoClassType fSuperClass ; public SVDBClassDecl ( ) { this ( "" ) ; } public SVDBClassDecl ( String name ) { super ( name , SVDBItemType . ClassDecl ) ; } public List < SVDBModIfcClassParam > getParameters ( ) { return fParams ; } public void addParameters ( List < SVDBModIfcClassParam > params ) { if ( fParams == null ) { fParams = new ArrayList < SVDBModIfcClassParam > ( ) ; } fParams . addAll ( params ) ; } public SVDBTypeInfoClassType getClassType ( ) { return fClassType ; } public void setClassType ( SVDBTypeInfoClassType cls_type ) { fClassType = cls_type ; } public SVDBTypeInfoClassType getSuperClass ( ) { return fSuperClass ; } public void setSuperClass ( SVDBTypeInfoClassType super_class ) { fSuperClass = super_class ; } public SVDBClassDecl duplicate ( ) { return ( SVDBClassDecl ) SVDBItemUtils . duplicate ( this ) ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; SVDBClassDecl o = ( SVDBClassDecl ) other ; if ( o . fParams != null ) { fParams = new ArrayList < SVDBModIfcClassParam > ( ) ; for ( SVDBModIfcClassParam p : o . fParams ) { fParams . add ( p ) ; } } else { fParams = null ; } setSuperClass ( o . getSuperClass ( ) ) ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; public class SVDBTask extends SVDBScopeItem implements IFieldItemAttr { public List < SVDBParamPortDecl > fParams ; public int fAttr ; public SVDBTask ( ) { super ( "" , SVDBItemType . Task ) ; } public SVDBTask ( String name , SVDBItemType type ) { super ( name , type ) ; fParams = new ArrayList < SVDBParamPortDecl > ( ) ; } public void setAttr ( int attr ) { fAttr = attr ; } public int getAttr ( ) { return fAttr ; } public void addParam ( SVDBParamPortDecl p ) { p . setParent ( this ) ; fParams . add ( p ) ; } public List < SVDBParamPortDecl > getParams ( ) { return fParams ; } public void setParams ( List < SVDBParamPortDecl > params ) { fParams = params ; for ( SVDBParamPortDecl p : params ) { p . setParent ( this ) ; } } public void init ( SVDBItemBase other ) { super . init ( other ) ; fAttr = ( ( SVDBTask ) other ) . fAttr ; fParams . clear ( ) ; for ( SVDBParamPortDecl p : ( ( SVDBTask ) other ) . fParams ) { fParams . add ( ( SVDBParamPortDecl ) p . duplicate ( ) ) ; } } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBTask ) { boolean ret = super . equals ( obj ) ; SVDBTask o = ( SVDBTask ) obj ; if ( o . fName == null || fName == null ) { ret &= ( o . fName == fName ) ; } else { ret &= o . fName . equals ( fName ) ; } return ret ; } return false ; } } package net . sf . sveditor . core . db ; public class SVDBLocation { public int fLine ; public int fPos ; public SVDBLocation ( int line , int pos ) { fLine = line ; fPos = pos ; } public SVDBLocation ( SVDBLocation other ) { fLine = other . fLine ; fPos = other . fPos ; } public int getLine ( ) { return fLine ; } public int getPos ( ) { return fPos ; } public void init ( SVDBLocation other ) { fLine = other . fLine ; fPos = other . fPos ; } public SVDBLocation duplicate ( ) { return new SVDBLocation ( this ) ; } public boolean equals ( Object other ) { if ( other instanceof SVDBLocation ) { boolean ret = true ; SVDBLocation o = ( SVDBLocation ) other ; ret &= ( o . fLine == fLine && o . fPos == fPos ) ; return ret ; } return false ; } public String toString ( ) { return "" + fLine ; } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; public class SVDBCoverCrossBinsSel extends SVDBItem { public SVDBExpr fSelectExpr ; public SVDBCoverCrossBinsSel ( ) { super ( "" , SVDBItemType . CoverCrossBinsSel ) ; } public SVDBCoverCrossBinsSel ( SVDBIdentifierExpr id ) { super ( id , SVDBItemType . CoverCrossBinsSel ) ; } public void setSelectExpr ( SVDBExpr expr ) { fSelectExpr = expr ; } public SVDBExpr getSelectExpr ( ) { return fSelectExpr ; } } package net . sf . sveditor . core . db ; public interface ISVDBItemBase { SVDBItemType getType ( ) ; SVDBLocation getLocation ( ) ; void setLocation ( SVDBLocation location ) ; ISVDBItemBase duplicate ( ) ; void init ( ISVDBItemBase other ) ; boolean equals ( ISVDBItemBase other , boolean recurse ) ; } package net . sf . sveditor . core . db ; public interface IMemberAttr { int LOCAL = ( << ) ; } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; public class SVDBModIfcDecl extends SVDBScopeItem { public List < SVDBModIfcClassParam > fParams ; public List < SVDBParamPortDecl > fPorts ; protected SVDBModIfcDecl ( String name , SVDBItemType type ) { super ( name , type ) ; fParams = new ArrayList < SVDBModIfcClassParam > ( ) ; fPorts = new ArrayList < SVDBParamPortDecl > ( ) ; } public List < SVDBModIfcClassParam > getParameters ( ) { return fParams ; } public List < SVDBParamPortDecl > getPorts ( ) { return fPorts ; } public boolean isParameterized ( ) { return ( fParams != null && fParams . size ( ) > ) ; } public SVDBModIfcDecl duplicate ( ) { return ( SVDBModIfcDecl ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; SVDBModIfcDecl o = ( SVDBModIfcDecl ) other ; if ( o . fParams != null ) { fParams . clear ( ) ; for ( SVDBModIfcClassParam p : o . fParams ) { fParams . add ( ( SVDBModIfcClassParam ) p . duplicate ( ) ) ; } } else { fParams = null ; } fPorts . clear ( ) ; fPorts . addAll ( o . fPorts ) ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBBind extends SVDBChildItem implements ISVDBAddChildItem , ISVDBNamedItem { public SVDBExpr fTargetTypeName ; public List < SVDBExpr > fTargetInstNameList ; public SVDBModIfcInst fBindInst ; public SVDBBind ( ) { super ( SVDBItemType . Bind ) ; fTargetInstNameList = new ArrayList < SVDBExpr > ( ) ; } public String getName ( ) { return fTargetTypeName . toString ( ) ; } public void setTargetTypeName ( SVDBExpr name ) { fTargetTypeName = name ; } public SVDBExpr getTargetTypeName ( ) { return fTargetTypeName ; } public List < SVDBExpr > getTargetInstNameList ( ) { return fTargetInstNameList ; } public void addTargetInstName ( SVDBExpr name ) { fTargetInstNameList . add ( name ) ; } public void setBindInst ( SVDBModIfcInst inst ) { fBindInst = inst ; } public SVDBModIfcInst getBindInst ( ) { return fBindInst ; } public void addChildItem ( ISVDBChildItem item ) { if ( item instanceof SVDBModIfcInst ) { fBindInst = ( SVDBModIfcInst ) item ; } else { fBindInst = null ; } } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConfigDesignStmt extends SVDBStmt { public List < SVDBExpr > fCellIdentifiers ; public SVDBConfigDesignStmt ( ) { super ( SVDBItemType . ConfigDesignStmt ) ; fCellIdentifiers = new ArrayList < SVDBExpr > ( ) ; } public void addCellIdentifier ( SVDBExpr id ) { fCellIdentifiers . add ( id ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBLabeledStmt extends SVDBBodyStmt { public String fLabel ; public SVDBLabeledStmt ( ) { super ( SVDBItemType . LabeledStmt ) ; } public String getLabel ( ) { return fLabel ; } public void setLabel ( String label ) { fLabel = label ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConstraintSolveBeforeStmt extends SVDBStmt { public List < SVDBExpr > fSolveBeforeList ; public List < SVDBExpr > fSolveAfterList ; public SVDBConstraintSolveBeforeStmt ( ) { super ( SVDBItemType . ConstraintSolveBeforeStmt ) ; fSolveBeforeList = new ArrayList < SVDBExpr > ( ) ; fSolveAfterList = new ArrayList < SVDBExpr > ( ) ; } public List < SVDBExpr > getSolveBeforeList ( ) { return fSolveBeforeList ; } public void addSolveBefore ( SVDBExpr expr ) { fSolveBeforeList . add ( expr ) ; } public List < SVDBExpr > getSolveAfterList ( ) { return fSolveAfterList ; } public void addSolveAfter ( SVDBExpr expr ) { fSolveAfterList . add ( expr ) ; } public SVDBConstraintSolveBeforeStmt duplicate ( ) { return ( SVDBConstraintSolveBeforeStmt ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBDelayControlStmt extends SVDBBodyStmt { public SVDBExpr fExpr ; public SVDBDelayControlStmt ( ) { super ( SVDBItemType . DelayControlStmt ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBDefParamItem extends SVDBStmt { public SVDBExpr fTarget ; public SVDBExpr fExpr ; public SVDBDefParamItem ( ) { super ( SVDBItemType . DefParamItem ) ; } public void setTarget ( SVDBExpr expr ) { fTarget = expr ; } public SVDBExpr getTarget ( ) { return fTarget ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBIfStmt extends SVDBStmt implements ISVDBAddChildItem { public SVDBExpr fCondExpr ; @ SVDBDoNotSaveAttr private int fAddIdx ; public SVDBStmt fIfStmt ; public SVDBStmt fElseStmt ; public SVDBIfStmt ( ) { super ( SVDBItemType . IfStmt ) ; } public SVDBIfStmt ( SVDBExpr expr ) { super ( SVDBItemType . IfStmt ) ; fCondExpr = expr ; } public SVDBExpr getCond ( ) { return fCondExpr ; } public SVDBStmt getIfStmt ( ) { return fIfStmt ; } public void setIfStmt ( SVDBStmt stmt ) { fIfStmt = stmt ; } public SVDBStmt getElseStmt ( ) { return fElseStmt ; } public void setElseStmt ( SVDBStmt stmt ) { fElseStmt = stmt ; } public void addChildItem ( ISVDBChildItem item ) { if ( fAddIdx ++ == ) { fIfStmt = ( SVDBStmt ) item ; } else if ( fAddIdx ++ == ) { fElseStmt = ( SVDBStmt ) item ; } if ( item != null ) { item . setParent ( this ) ; } } @ Override public void init ( ISVDBItemBase other ) { SVDBIfStmt o = ( SVDBIfStmt ) other ; if ( o . fCondExpr != null ) { fCondExpr = o . fCondExpr . duplicate ( ) ; } else { fCondExpr = null ; } if ( o . fIfStmt != null ) { fIfStmt = o . fIfStmt . duplicate ( ) ; } else { fIfStmt = null ; } if ( o . fElseStmt != null ) { fElseStmt = o . fElseStmt . duplicate ( ) ; } else { fElseStmt = null ; } super . init ( other ) ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . db . IFieldItemAttr ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfo ; public class SVDBVarDeclStmt extends SVDBStmt implements IFieldItemAttr , ISVDBChildParent { public SVDBTypeInfo fTypeInfo ; public int fFieldAttr ; public List < SVDBVarDeclItem > fVarList ; public SVDBVarDeclStmt ( ) { super ( SVDBItemType . VarDeclStmt ) ; } public SVDBVarDeclStmt ( SVDBTypeInfo type , int attr ) { this ( SVDBItemType . VarDeclStmt , type , attr ) ; } public SVDBVarDeclStmt ( SVDBItemType stmt_type , SVDBTypeInfo type , int attr ) { super ( stmt_type ) ; fTypeInfo = type ; fVarList = new ArrayList < SVDBVarDeclItem > ( ) ; } public static String getName ( SVDBVarDeclStmt stmt ) { StringBuilder sb = new StringBuilder ( ) ; for ( ISVDBChildItem vi : stmt . getChildren ( ) ) { sb . append ( SVDBItem . getName ( vi ) ) ; sb . append ( "" ) ; } if ( sb . length ( ) > ) { sb . setLength ( sb . length ( ) - ) ; } return sb . toString ( ) ; } public String getTypeName ( ) { if ( fTypeInfo != null ) { return fTypeInfo . getName ( ) ; } else { return null ; } } public void setTypeInfo ( SVDBTypeInfo ti ) { fTypeInfo = ti ; } public SVDBTypeInfo getTypeInfo ( ) { return fTypeInfo ; } public int getAttr ( ) { return fFieldAttr ; } public void setAttr ( int attr ) { fFieldAttr |= attr ; } public void resetAttr ( int attr ) { fFieldAttr = attr ; } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fVarList . add ( ( SVDBVarDeclItem ) item ) ; } @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fVarList . iterator ( ) ; } } ; } public SVDBVarDeclStmt duplicate ( ) { return ( SVDBVarDeclStmt ) super . duplicate ( ) ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBVarDeclStmt ) { SVDBVarDeclStmt o = ( SVDBVarDeclStmt ) obj ; if ( fFieldAttr != o . fFieldAttr ) { return false ; } if ( fTypeInfo == null || o . fTypeInfo == null ) { if ( fTypeInfo != o . fTypeInfo ) { return false ; } } else if ( ! fTypeInfo . equals ( o . fTypeInfo ) ) { return false ; } return super . equals ( obj ) ; } return false ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConfigInstClauseStmt extends SVDBConfigRuleStmtBase { public SVDBExpr fInstName ; public SVDBConfigInstClauseStmt ( ) { super ( SVDBItemType . ConfigInstClauseStmt ) ; } public void setInstName ( SVDBExpr inst ) { fInstName = inst ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBNullStmt extends SVDBStmt { public SVDBNullStmt ( ) { super ( SVDBItemType . NullStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBClockingEventExpr ; import net . sf . sveditor . core . db . expr . SVDBClockingEventExpr . ClockingEventType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBAlwaysStmt extends SVDBBodyStmt { public enum AlwaysType { Always , AlwaysComb , AlwaysLatch , AlwaysFF } ; public AlwaysType fAlwaysType ; public SVDBClockingEventExpr fAlwaysEventExprType ; public SVDBAlwaysStmt ( ) { this ( AlwaysType . Always ) ; fAlwaysEventExprType = new SVDBClockingEventExpr ( ) ; } public SVDBAlwaysStmt ( AlwaysType type ) { super ( SVDBItemType . AlwaysStmt ) ; fAlwaysType = type ; fAlwaysEventExprType = new SVDBClockingEventExpr ( ) ; } public AlwaysType getAlwaysType ( ) { return fAlwaysType ; } public ClockingEventType getAlwaysEventType ( ) { return fAlwaysEventExprType . getClockingEventType ( ) ; } public void setAlwaysEventType ( ClockingEventType type ) { fAlwaysEventExprType . setClockingEventType ( type ) ; } public SVDBExpr getEventExpr ( ) { return fAlwaysEventExprType . getExpr ( ) ; } public void setEventExpr ( SVDBExpr expr ) { fAlwaysEventExprType . setExpr ( expr ) ; } public SVDBClockingEventExpr getCBEventExpr ( ) { return fAlwaysEventExprType ; } public void setCBEventExpr ( SVDBClockingEventExpr cbExpr ) { fAlwaysEventExprType = cbExpr ; } @ Override public SVDBAlwaysStmt duplicate ( ) { return ( SVDBAlwaysStmt ) super . duplicate ( ) ; } @ Override public void init ( ISVDBItemBase other ) { super . init ( other ) ; fAlwaysType = ( ( SVDBAlwaysStmt ) other ) . fAlwaysType ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBAlwaysStmt ) { boolean ret = true ; ret &= ( ( SVDBAlwaysStmt ) obj ) . fAlwaysType . equals ( fAlwaysType ) ; ret &= super . equals ( obj ) ; return ret ; } return false ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBCoverageOptionStmt extends SVDBStmt implements ISVDBNamedItem { public boolean fIsTypeOption ; public String fName ; public SVDBExpr fExpr ; public SVDBCoverageOptionStmt ( ) { super ( SVDBItemType . CoverageOptionStmt ) ; } public SVDBCoverageOptionStmt ( String name , boolean is_type_option ) { super ( SVDBItemType . CoverageOptionStmt ) ; fName = name ; fIsTypeOption = is_type_option ; } public boolean isTypeOption ( ) { return fIsTypeOption ; } public void setName ( String name ) { fName = name ; } public String getName ( ) { return fName ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBWaitForkStmt extends SVDBWaitStmt { public SVDBWaitForkStmt ( ) { super ( SVDBItemType . WaitForkStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConstraintDistListItem extends SVDBStmt { public SVDBExpr fLHS ; public SVDBExpr fRHS ; public boolean fIsDist ; public SVDBConstraintDistListItem ( ) { super ( SVDBItemType . ConstraintDistListItem ) ; } public void setLHS ( SVDBExpr lhs ) { fLHS = lhs ; } public SVDBExpr getLHS ( ) { return fLHS ; } public void setRHS ( SVDBExpr rhs ) { fRHS = rhs ; } public SVDBExpr getRHS ( ) { return fRHS ; } public boolean isDist ( ) { return fIsDist ; } public void setIsDist ( boolean is_dist ) { fIsDist = is_dist ; } public SVDBConstraintDistListItem duplicate ( ) { return ( SVDBConstraintDistListItem ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBConstraintSetStmt extends SVDBStmt { public List < SVDBStmt > fConstraintList ; public SVDBConstraintSetStmt ( ) { super ( SVDBItemType . ConstraintSetStmt ) ; fConstraintList = new ArrayList < SVDBStmt > ( ) ; } public List < SVDBStmt > getConstraintList ( ) { return fConstraintList ; } public void addConstraintStmt ( SVDBStmt stmt ) { fConstraintList . add ( stmt ) ; } public SVDBConstraintSetStmt duplicate ( ) { return ( SVDBConstraintSetStmt ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBForeachStmt extends SVDBBodyStmt { public SVDBExpr fCond ; public SVDBForeachStmt ( ) { super ( SVDBItemType . ForeachStmt ) ; } public void setCond ( SVDBExpr cond ) { fCond = cond ; } public SVDBExpr getCond ( ) { return fCond ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBImportStmt extends SVDBStmt implements ISVDBChildParent { public List < SVDBImportItem > fImportList ; public SVDBImportStmt ( ) { super ( SVDBItemType . ImportStmt ) ; fImportList = new ArrayList < SVDBImportItem > ( ) ; } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fImportList . add ( ( SVDBImportItem ) item ) ; } @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fImportList . iterator ( ) ; } } ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBWaitOrderStmt extends SVDBBodyStmt { public SVDBWaitOrderStmt ( ) { super ( SVDBItemType . WaitOrderStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfo ; public class SVDBTypedefStmt extends SVDBStmt implements ISVDBNamedItem { public SVDBTypeInfo fTypeInfo ; public String fName ; public SVDBTypedefStmt ( ) { super ( SVDBItemType . TypedefStmt ) ; } public SVDBTypedefStmt ( SVDBTypeInfo type ) { super ( SVDBItemType . TypedefStmt ) ; fTypeInfo = type ; } public SVDBTypedefStmt ( SVDBTypeInfo type , String name ) { this ( type ) ; fName = name ; } public String getName ( ) { return fName ; } public void setName ( String name ) { fName = name ; } public SVDBTypeInfo getTypeInfo ( ) { return fTypeInfo ; } @ Override public SVDBTypedefStmt duplicate ( ) { return ( SVDBTypedefStmt ) super . duplicate ( ) ; } @ Override public void init ( ISVDBItemBase other ) { super . init ( other ) ; SVDBTypedefStmt ot = ( SVDBTypedefStmt ) other ; fTypeInfo = ot . fTypeInfo . duplicate ( ) ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBTypedefStmt ) { SVDBTypedefStmt o = ( SVDBTypedefStmt ) obj ; if ( ! o . fTypeInfo . equals ( fTypeInfo ) ) { return false ; } return super . equals ( obj ) ; } return false ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBAssertStmt extends SVDBStmt { public SVDBExpr fExpr ; public SVDBExpr fDelay ; public SVDBActionBlockStmt fActionBlock ; public SVDBAssertStmt ( ) { this ( SVDBItemType . AssertStmt ) ; } protected SVDBAssertStmt ( SVDBItemType type ) { super ( type ) ; } public void setDelay ( SVDBExpr delay ) { fDelay = delay ; } public SVDBExpr getDelay ( ) { return fDelay ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setActionBlock ( SVDBActionBlockStmt stmt ) { fActionBlock = stmt ; } public SVDBActionBlockStmt getActionBlock ( ) { return fActionBlock ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBDisableStmt extends SVDBStmt { public SVDBExpr fHierarchicalId ; public SVDBDisableStmt ( ) { this ( SVDBItemType . DisableStmt ) ; } protected SVDBDisableStmt ( SVDBItemType type ) { super ( type ) ; } public void setHierarchicalId ( SVDBExpr expr ) { fHierarchicalId = expr ; } public SVDBExpr getHierarchicalId ( ) { return fHierarchicalId ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBProceduralContAssignStmt extends SVDBStmt { public enum AssignType { Assign , Deassign , Force , Release } ; public AssignType fAssignType ; public SVDBExpr fExpr ; public SVDBProceduralContAssignStmt ( ) { super ( SVDBItemType . ProceduralContAssignStmt ) ; } public SVDBProceduralContAssignStmt ( AssignType type ) { super ( SVDBItemType . ProceduralContAssignStmt ) ; fAssignType = type ; } public AssignType getAssignType ( ) { return fAssignType ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBChildItem ; public interface ISVDBBodyStmt extends ISVDBChildItem { SVDBStmt getBody ( ) ; void setBody ( SVDBStmt stmt ) ; } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBContinueStmt extends SVDBStmt { public SVDBContinueStmt ( ) { super ( SVDBItemType . ContinueStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConfigCellClauseStmt extends SVDBConfigRuleStmtBase { public SVDBExpr fCellId ; public SVDBConfigCellClauseStmt ( ) { super ( SVDBItemType . ConfigCellClauseStmt ) ; } public void setCellId ( SVDBExpr id ) { fCellId = id ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBEventControlStmt extends SVDBBodyStmt { public SVDBExpr fExpr ; public SVDBEventControlStmt ( ) { super ( SVDBItemType . EventControlStmt ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBForStmt extends SVDBBodyStmt { public SVDBStmt fInitExpr ; public SVDBStmt fTestStmt ; public SVDBStmt fIncrStmt ; public SVDBForStmt ( ) { super ( SVDBItemType . ForStmt ) ; } public SVDBStmt getInitExpr ( ) { return fInitExpr ; } public void setInitStmt ( SVDBStmt stmt ) { fInitExpr = stmt ; } public SVDBStmt getTestExpr ( ) { return fTestStmt ; } public void setTestStmt ( SVDBStmt stmt ) { fTestStmt = stmt ; } public SVDBStmt getIncrStmt ( ) { return fIncrStmt ; } public void setIncrstmt ( SVDBStmt stmt ) { fIncrStmt = stmt ; } public SVDBForStmt duplicate ( ) { return ( SVDBForStmt ) super . duplicate ( ) ; } public void init ( ISVDBItemBase other ) { super . init ( other ) ; SVDBForStmt o = ( SVDBForStmt ) other ; if ( o . fIncrStmt != null ) { fIncrStmt = o . fIncrStmt . duplicate ( ) ; } else { fIncrStmt = null ; } if ( o . fTestStmt != null ) { fTestStmt = o . fTestStmt . duplicate ( ) ; } else { fTestStmt = null ; } if ( o . fInitExpr != null ) { fInitExpr = o . fInitExpr . duplicate ( ) ; } else { fInitExpr = null ; } } @ Override public boolean equals ( ISVDBItemBase obj , boolean full ) { if ( ! super . equals ( obj , full ) ) { return false ; } if ( ! ( obj instanceof SVDBForStmt ) ) { return false ; } SVDBForStmt o = ( SVDBForStmt ) obj ; boolean ret = true ; if ( full ) { if ( fInitExpr == null || o . fInitExpr == null ) { ret &= ( fInitExpr == o . fInitExpr ) ; } else { ret &= fInitExpr . equals ( o . fInitExpr ) ; } if ( fTestStmt == null || o . getTestExpr ( ) == null ) { ret &= ( fTestStmt == o . getTestExpr ( ) ) ; } else { ret &= fTestStmt . equals ( o . getTestExpr ( ) ) ; } if ( fIncrStmt == null || o . getIncrStmt ( ) == null ) { ret &= ( fIncrStmt == o . getIncrStmt ( ) ) ; } else { ret &= fIncrStmt . equals ( o . getIncrStmt ( ) ) ; } } return ret ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConstraintForeachStmt extends SVDBStmt { public SVDBExpr fExpr ; public SVDBStmt fStmt ; public SVDBConstraintForeachStmt ( ) { super ( SVDBItemType . ConstraintForeachStmt ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setStmt ( SVDBStmt stmt ) { fStmt = stmt ; } public SVDBStmt getStmt ( ) { return fStmt ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBAssumeStmt extends SVDBAssertStmt { public SVDBAssumeStmt ( ) { super ( SVDBItemType . AssumeStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBCaseItem extends SVDBBodyStmt { public List < SVDBExpr > fCaseExprList ; public SVDBCaseItem ( ) { super ( SVDBItemType . CaseItem ) ; fCaseExprList = new ArrayList < SVDBExpr > ( ) ; } public List < SVDBExpr > getExprList ( ) { return fCaseExprList ; } public void addExpr ( SVDBExpr expr ) { fCaseExprList . add ( expr ) ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBExportStmt extends SVDBStmt implements ISVDBChildParent { public List < SVDBExportItem > fExportList ; public SVDBExportStmt ( ) { super ( SVDBItemType . ExportStmt ) ; fExportList = new ArrayList < SVDBExportItem > ( ) ; } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fExportList . add ( ( SVDBExportItem ) item ) ; } @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fExportList . iterator ( ) ; } } ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBRepeatStmt extends SVDBBodyStmt { public SVDBExpr fRepeatExpr ; public SVDBRepeatStmt ( ) { super ( SVDBItemType . RepeatStmt ) ; } public void setExpr ( SVDBExpr expr ) { fRepeatExpr = expr ; } public SVDBExpr getExpr ( ) { return fRepeatExpr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; import net . sf . sveditor . core . db . utils . SVDBSingleItemIterable ; public class SVDBBodyStmt extends SVDBStmt implements ISVDBBodyStmt , ISVDBAddChildItem , ISVDBChildParent { public SVDBStmt fBody ; @ SVDBDoNotSaveAttr private int fAddIdx ; protected SVDBBodyStmt ( SVDBItemType stmt_type ) { super ( stmt_type ) ; } public void setBody ( SVDBStmt stmt ) { fBody = stmt ; } public SVDBStmt getBody ( ) { return fBody ; } public Iterable < ISVDBChildItem > getChildren ( ) { return new SVDBSingleItemIterable < ISVDBChildItem > ( fBody ) ; } public void addChildItem ( ISVDBChildItem item ) { if ( fAddIdx ++ == ) { fBody = ( SVDBStmt ) item ; if ( fBody != null ) { fBody . setParent ( this ) ; } } } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBCoverStmt extends SVDBAssertStmt { public SVDBCoverStmt ( ) { super ( SVDBItemType . CoverStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBCoverageCrossBinsSelectStmt extends SVDBStmt { public SVDBCoverageBinsType fBinsType ; public SVDBExpr fBinsName ; public SVDBExpr fSelectCondition ; public SVDBExpr fIffExpr ; public SVDBCoverageCrossBinsSelectStmt ( ) { super ( SVDBItemType . CoverageCrossBinsSelectStmt ) ; } public SVDBCoverageBinsType getBinsType ( ) { return fBinsType ; } public void setBinsType ( SVDBCoverageBinsType type ) { fBinsType = type ; } public void setBinsType ( String type ) { if ( type . equals ( "" ) ) { fBinsType = SVDBCoverageBinsType . IgnoreBins ; } else if ( type . equals ( "" ) ) { fBinsType = SVDBCoverageBinsType . IllegalBins ; } else { fBinsType = SVDBCoverageBinsType . Bins ; } } public SVDBExpr getBinsName ( ) { return fBinsName ; } public void setBinsName ( SVDBExpr name ) { fBinsName = name ; } public SVDBExpr getSelectCondition ( ) { return fSelectCondition ; } public void setSelectCondition ( SVDBExpr expr ) { fSelectCondition = expr ; } public SVDBExpr getIffExpr ( ) { return fIffExpr ; } public void setIffExpr ( SVDBExpr iff ) { fIffExpr = iff ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBInitialStmt extends SVDBBodyStmt { public SVDBInitialStmt ( ) { super ( SVDBItemType . InitialStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConstraintDistListStmt extends SVDBStmt { public List < SVDBExpr > fLHS ; public List < SVDBConstraintDistListItem > fDistItems ; public SVDBConstraintDistListStmt ( ) { super ( SVDBItemType . ConstraintDistListStmt ) ; fLHS = new ArrayList < SVDBExpr > ( ) ; fDistItems = new ArrayList < SVDBConstraintDistListItem > ( ) ; } public void addLHS ( SVDBExpr lhs ) { fLHS . add ( lhs ) ; } public List < SVDBExpr > getLHS ( ) { return fLHS ; } public List < SVDBConstraintDistListItem > getDistItems ( ) { return fDistItems ; } public void addDistItem ( SVDBConstraintDistListItem item ) { fDistItems . add ( item ) ; } public SVDBConstraintDistListStmt duplicate ( ) { return ( SVDBConstraintDistListStmt ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBExportItem extends SVDBStmt { public String fExport ; public SVDBExportItem ( ) { super ( SVDBItemType . ExportItem ) ; } public String getExport ( ) { return fExport ; } public void setExport ( String exp ) { fExport = exp ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConstraintImplStmt extends SVDBStmt { public SVDBExpr fExpr ; public SVDBStmt fConstraint ; public SVDBConstraintImplStmt ( ) { super ( SVDBItemType . ConstraintImplStmt ) ; } public SVDBConstraintImplStmt ( SVDBExpr expr , SVDBStmt constraint ) { super ( SVDBItemType . ConstraintImplStmt ) ; fExpr = expr ; fConstraint = constraint ; } public SVDBExpr getExpr ( ) { return fExpr ; } public SVDBStmt getConstraintSet ( ) { return fConstraint ; } public SVDBConstraintImplStmt duplicate ( ) { return ( SVDBConstraintImplStmt ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBExprStmt extends SVDBStmt { public SVDBExpr fExpr ; public SVDBExprStmt ( ) { super ( SVDBItemType . ExprStmt ) ; } public SVDBExprStmt ( SVDBExpr expr ) { super ( SVDBItemType . ExprStmt ) ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . attr . SVDBParentAttr ; public class SVDBBlockStmt extends SVDBStmt implements ISVDBScopeItem { @ SVDBParentAttr public ISVDBChildItem fParent ; public List < ISVDBItemBase > fItems ; public SVDBLocation fEndLocation ; public String fBlockName ; public SVDBBlockStmt ( ) { super ( SVDBItemType . BlockStmt ) ; fBlockName = "" ; fItems = new ArrayList < ISVDBItemBase > ( ) ; } public SVDBBlockStmt ( SVDBItemType type ) { super ( type ) ; fBlockName = "" ; fItems = new ArrayList < ISVDBItemBase > ( ) ; } public void addChildItem ( ISVDBChildItem item ) { fItems . add ( item ) ; if ( item != null ) { item . setParent ( this ) ; } } @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fItems . iterator ( ) ; } } ; } public void addItem ( ISVDBItemBase item ) { fItems . add ( item ) ; if ( item != null && item instanceof ISVDBChildItem ) { ( ( ISVDBChildItem ) item ) . setParent ( this ) ; } } public String getBlockName ( ) { return fBlockName ; } public void setBlockName ( String name ) { fBlockName = name ; } public ISVDBChildItem getParent ( ) { return fParent ; } public void setParent ( ISVDBChildItem parent ) { fParent = parent ; } public SVDBLocation getEndLocation ( ) { return fEndLocation ; } public void setEndLocation ( SVDBLocation loc ) { fEndLocation = loc ; } public List < ISVDBItemBase > getItems ( ) { return fItems ; } @ Override public SVDBBlockStmt duplicate ( ) { return ( SVDBBlockStmt ) super . duplicate ( ) ; } @ Override public void init ( ISVDBItemBase other ) { SVDBBlockStmt o = ( SVDBBlockStmt ) other ; super . init ( other ) ; fBlockName = o . getBlockName ( ) ; if ( o . getEndLocation ( ) == null ) { fEndLocation = null ; } else { fEndLocation = o . getEndLocation ( ) . duplicate ( ) ; } fItems . clear ( ) ; for ( ISVDBItemBase i : o . getItems ( ) ) { fItems . add ( i . duplicate ( ) ) ; } fParent = o . getParent ( ) ; } @ Override public boolean equals ( ISVDBItemBase obj , boolean full ) { if ( ! super . equals ( obj , full ) ) { return false ; } boolean ret = true ; return ret ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfo ; public class SVDBParamPortDecl extends SVDBVarDeclStmt { public static final int Direction_Ref = ( << ) ; public static final int Direction_Const = ( << ) ; public static final int Direction_Var = ( << ) ; public static final int Direction_Input = ( << ) ; public static final int Direction_Output = ( << ) ; public static final int Direction_Inout = ( << ) ; public static final int WireType_Shift = ; public static final int WireType_none = ( << WireType_Shift ) ; public static final int WireType_supply0 = ( << WireType_Shift ) ; public static final int Direction_supply1 = ( << WireType_Shift ) ; public static final int Direction_tri = ( << WireType_Shift ) ; public static final int Direction_triand = ( << WireType_Shift ) ; public static final int Direction_trior = ( << WireType_Shift ) ; public static final int Direction_trireg = ( << WireType_Shift ) ; public static final int Direction_tri0 = ( << WireType_Shift ) ; public static final int Direction_tri1 = ( << WireType_Shift ) ; public static final int Direction_uwire = ( << WireType_Shift ) ; public static final int Direction_wire = ( << WireType_Shift ) ; public static final int Direction_wand = ( << WireType_Shift ) ; public static final int Direction_wor = ( << WireType_Shift ) ; public int fDir ; public SVDBParamPortDecl ( ) { super ( SVDBItemType . ParamPortDecl , null , ) ; } public SVDBParamPortDecl ( SVDBTypeInfo type ) { super ( SVDBItemType . ParamPortDecl , type , ) ; fDir = Direction_Input ; } public void setDir ( int dir ) { fDir = dir ; } public int getDir ( ) { return fDir ; } public int getWireType ( ) { return ( fDir & ( << WireType_Shift ) ) ; } public SVDBParamPortDecl duplicate ( ) { return ( SVDBParamPortDecl ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; fDir = ( ( SVDBParamPortDecl ) other ) . fDir ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBParamPortDecl ) { SVDBParamPortDecl o = ( SVDBParamPortDecl ) obj ; if ( o . fDir != fDir ) { return false ; } return super . equals ( obj ) ; } return false ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBAssignStmt extends SVDBStmt { public SVDBExpr fLHS ; public String fOp ; public SVDBExpr fDelayExpr ; public SVDBExpr fRHS ; public SVDBAssignStmt ( ) { super ( SVDBItemType . AssignStmt ) ; } public void setLHS ( SVDBExpr lhs ) { fLHS = lhs ; } public SVDBExpr getLHS ( ) { return fLHS ; } public void setOp ( String op ) { fOp = op ; } public String getOp ( ) { return fOp ; } public void setRHS ( SVDBExpr expr ) { fRHS = expr ; } public SVDBExpr getRHS ( ) { return fRHS ; } public void setDelayExpr ( SVDBExpr expr ) { fDelayExpr = expr ; } public SVDBExpr getDelayExpr ( ) { return fDelayExpr ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBParamValueAssignList ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConfigRuleStmtBase extends SVDBStmt { public boolean fIsLibList ; public List < SVDBExpr > fLibUseList ; public SVDBExpr fLibCellId ; public SVDBParamValueAssignList fParamValueAssign ; public SVDBConfigRuleStmtBase ( SVDBItemType type ) { super ( type ) ; fLibUseList = new ArrayList < SVDBExpr > ( ) ; } public void addLib ( SVDBExpr lib ) { fLibUseList . add ( lib ) ; } public void setLibCellId ( SVDBExpr id ) { fLibCellId = id ; } public void setParamAssign ( SVDBParamValueAssignList assign ) { fParamValueAssign = assign ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFinalStmt extends SVDBBodyStmt { public SVDBFinalStmt ( ) { super ( SVDBItemType . FinalStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBWaitStmt extends SVDBBodyStmt { public SVDBExpr fExpr ; public SVDBWaitStmt ( ) { this ( SVDBItemType . WaitStmt ) ; } protected SVDBWaitStmt ( SVDBItemType type ) { super ( type ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBForkStmt extends SVDBBlockStmt { public enum JoinType { Join , JoinNone , JoinAny } ; public JoinType fJoinType ; public SVDBForkStmt ( ) { super ( SVDBItemType . ForkStmt ) ; } public JoinType getJoinType ( ) { return fJoinType ; } public void setJoinType ( JoinType join_type ) { fJoinType = join_type ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBWhileStmt extends SVDBBodyStmt { public SVDBExpr fCond ; public SVDBWhileStmt ( ) { super ( SVDBItemType . WhileStmt ) ; } public SVDBWhileStmt ( SVDBExpr cond ) { super ( SVDBItemType . WhileStmt ) ; fCond = cond ; } public SVDBExpr getExpr ( ) { return fCond ; } public void setExpr ( SVDBExpr expr ) { fCond = expr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBTimePrecisionStmt extends SVDBStmt { public String fArg1 ; public String fArg2 ; public SVDBTimePrecisionStmt ( ) { super ( SVDBItemType . TimePrecisionStmt ) ; } public String getArg1 ( ) { return fArg1 ; } public void setArg1 ( String arg1 ) { fArg1 = arg1 ; } public String getArg2 ( ) { return fArg2 ; } public void setArg2 ( String arg2 ) { fArg2 = arg2 ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; public class SVDBActionBlockStmt extends SVDBStmt implements ISVDBAddChildItem { @ SVDBDoNotSaveAttr private int fAddIdx ; public SVDBStmt fStmt ; public SVDBStmt fElseStmt ; public SVDBActionBlockStmt ( ) { super ( SVDBItemType . ActionBlockStmt ) ; } public void setStmt ( SVDBStmt stmt ) { fStmt = stmt ; } public SVDBStmt getStmt ( ) { return fStmt ; } public void setElseStmt ( SVDBStmt stmt ) { fElseStmt = stmt ; } public SVDBStmt getElseStmt ( ) { return fElseStmt ; } public void addChildItem ( ISVDBChildItem item ) { if ( fAddIdx ++ == ) { fStmt = ( SVDBStmt ) item ; } else if ( fAddIdx ++ == ) { fStmt = ( SVDBStmt ) item ; } } } package net . sf . sveditor . core . db . stmt ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBVarDeclItem extends SVDBStmt implements ISVDBNamedItem { public String fName ; public int fAttr ; public int fVarAttr ; public List < SVDBVarDimItem > fArrayDim ; public SVDBExpr fInitExpr ; public SVDBVarDeclItem ( ) { super ( SVDBItemType . VarDeclItem ) ; } public SVDBVarDeclItem ( String name ) { super ( SVDBItemType . VarDeclItem ) ; fName = name ; } public void setName ( String name ) { fName = name ; } public String getName ( ) { return fName ; } public void setInitExpr ( SVDBExpr expr ) { fInitExpr = expr ; } public SVDBExpr getInitExpr ( ) { return fInitExpr ; } public int getAttr ( ) { return fAttr ; } public void setAttr ( int attr ) { fAttr |= attr ; } public void resetAttr ( int attr ) { fAttr = attr ; } public List < SVDBVarDimItem > getArrayDim ( ) { return fArrayDim ; } public void setArrayDim ( List < SVDBVarDimItem > dim ) { fArrayDim = dim ; } public SVDBVarDeclStmt getParent ( ) { return ( SVDBVarDeclStmt ) fParent ; } public void setParent ( ISVDBChildItem parent ) { fParent = parent ; } public SVDBVarDeclItem duplicate ( ) { return ( SVDBVarDeclItem ) super . duplicate ( ) ; } public void init ( ISVDBItemBase other ) { } public boolean equals ( ISVDBItemBase other , boolean recurse ) { return false ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBConfigDefaultClauseStmt extends SVDBConfigRuleStmtBase { public SVDBConfigDefaultClauseStmt ( ) { super ( SVDBItemType . ConfigDefaultClauseStmt ) ; fIsLibList = true ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBReturnStmt extends SVDBStmt { public SVDBExpr fReturnExpr ; public SVDBReturnStmt ( ) { super ( SVDBItemType . ReturnStmt ) ; } public void setExpr ( SVDBExpr expr ) { fReturnExpr = expr ; } public SVDBExpr getExpr ( ) { return fReturnExpr ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBDefParamStmt extends SVDBStmt { public List < SVDBDefParamItem > fParamAssignList ; public SVDBDefParamStmt ( ) { super ( SVDBItemType . DefParamStmt ) ; fParamAssignList = new ArrayList < SVDBDefParamItem > ( ) ; } public List < SVDBDefParamItem > getParamAssignList ( ) { return fParamAssignList ; } public void addParamAssign ( SVDBDefParamItem item ) { fParamAssignList . add ( item ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBBreakStmt extends SVDBStmt { public SVDBBreakStmt ( ) { super ( SVDBItemType . BreakStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBImportItem extends SVDBStmt { public String fImport ; public SVDBImportItem ( ) { super ( SVDBItemType . ImportItem ) ; } public String getImport ( ) { return fImport ; } public void setImport ( String imp ) { fImport = imp ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBTimeUnitsStmt extends SVDBStmt { public String fUnits ; public SVDBTimeUnitsStmt ( ) { super ( SVDBItemType . TimeUnitsStmt ) ; } public String getUnits ( ) { return fUnits ; } public void setUnits ( String units ) { fUnits = units ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBDoWhileStmt extends SVDBBodyStmt { public SVDBExpr fCond ; public SVDBDoWhileStmt ( ) { super ( SVDBItemType . DoWhileStmt ) ; } public void setCond ( SVDBExpr cond ) { fCond = cond ; } public SVDBExpr getCond ( ) { return fCond ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBConstraintIfStmt extends SVDBStmt { public SVDBExpr fIfExpr ; public SVDBStmt fConstraint ; public SVDBStmt fElse ; public boolean fElseIf ; public SVDBConstraintIfStmt ( ) { super ( SVDBItemType . ConstraintIfStmt ) ; } public SVDBConstraintIfStmt ( SVDBExpr expr , SVDBStmt constraint , SVDBStmt else_expr , boolean else_if ) { super ( SVDBItemType . ConstraintIfStmt ) ; fIfExpr = expr ; fConstraint = constraint ; fElse = else_expr ; fElseIf = else_if ; } public SVDBExpr getExpr ( ) { return fIfExpr ; } public SVDBStmt getConstraint ( ) { return fConstraint ; } public SVDBStmt getElseClause ( ) { return fElse ; } public boolean isElseIf ( ) { return fElseIf ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBForeverStmt extends SVDBBodyStmt { public SVDBForeverStmt ( ) { super ( SVDBItemType . ForeverStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBCaseStmt extends SVDBStmt { public enum CaseType { Case , Casex , Casez , Randcase } ; public CaseType fCaseType ; public SVDBExpr fExpr ; public List < SVDBCaseItem > fCaseItemList ; public SVDBCaseStmt ( ) { this ( CaseType . Case ) ; } public SVDBCaseStmt ( CaseType type ) { super ( SVDBItemType . CaseStmt ) ; fCaseItemList = new ArrayList < SVDBCaseItem > ( ) ; fCaseType = type ; } public CaseType getCaseType ( ) { return fCaseType ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public List < SVDBCaseItem > getCaseItemList ( ) { return fCaseItemList ; } public void addCaseItem ( SVDBCaseItem item ) { fCaseItemList . add ( item ) ; } } package net . sf . sveditor . core . db . stmt ; public enum SVDBCoverageBinsType { Bins , IllegalBins , IgnoreBins } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBVarDimItem extends SVDBStmt { public enum DimType { Unsized , Sized , Associative , Queue } ; public DimType fDimType ; public SVDBExpr fExpr ; public SVDBTypeInfo fTypeInfo ; public SVDBVarDimItem ( ) { super ( SVDBItemType . VarDimItem ) ; } public void setDimType ( DimType type ) { fDimType = type ; } public DimType getDimType ( ) { return fDimType ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBTypeInfo getTypeInfo ( ) { return fTypeInfo ; } public void setTypeInfo ( SVDBTypeInfo type_info ) { fTypeInfo = type_info ; } public String toString ( ) { String ret = "" ; if ( fDimType != null ) { switch ( fDimType ) { case Associative : if ( fTypeInfo != null ) { ret += fTypeInfo . toString ( ) ; } break ; case Queue : ret += "" ; break ; case Sized : if ( fExpr != null ) { ret += fExpr . toString ( ) ; } break ; case Unsized : break ; } } ret += "" ; return ret ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBEventTriggerStmt extends SVDBStmt { public SVDBStmt fDelayOrEventControl ; public SVDBExpr fHierarchicalEventIdentifier ; public SVDBEventTriggerStmt ( ) { super ( SVDBItemType . EventTriggerStmt ) ; } public SVDBStmt getDelayOrEventControl ( ) { return fDelayOrEventControl ; } public void setDelayOrEventControl ( SVDBStmt stmt ) { fDelayOrEventControl = stmt ; } public SVDBExpr getHierarchicalEventIdentifier ( ) { return fHierarchicalEventIdentifier ; } public void setHierarchicalEventIdentifier ( SVDBExpr expr ) { fHierarchicalEventIdentifier = expr ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBDisableForkStmt extends SVDBDisableStmt { public SVDBDisableForkStmt ( ) { super ( SVDBItemType . DisableForkStmt ) ; } } package net . sf . sveditor . core . db . stmt ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBChildItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBStmt extends SVDBChildItem { protected SVDBStmt ( SVDBItemType type ) { super ( type ) ; } @ Override public void init ( ISVDBItemBase other ) { super . init ( other ) ; } @ Override public boolean equals ( Object obj ) { return super . equals ( obj ) ; } @ Override public SVDBStmt duplicate ( ) { return ( SVDBStmt ) super . duplicate ( ) ; } @ Override public boolean equals ( ISVDBItemBase obj , boolean full ) { return super . equals ( obj , full ) ; } public static boolean isType ( ISVDBItemBase item , SVDBItemType ... types ) { boolean ret = true ; if ( ret ) { ret = false ; for ( SVDBItemType t : types ) { if ( t == item . getType ( ) ) { ret = true ; break ; } } } return ret ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBTypeInfoEnum extends SVDBTypeInfo { public List < SVDBTypeInfoEnumerator > fEnumerators ; public SVDBTypeInfoEnum ( ) { this ( "" ) ; } public SVDBTypeInfoEnum ( String typename ) { super ( typename , SVDBItemType . TypeInfoEnum ) ; fEnumerators = new ArrayList < SVDBTypeInfoEnumerator > ( ) ; } public void addEnumerator ( SVDBTypeInfoEnumerator e ) { e . setParent ( this ) ; fEnumerators . add ( e ) ; } public List < SVDBTypeInfoEnumerator > getEnumerators ( ) { return fEnumerators ; } public String toString ( ) { return getName ( ) ; } } package net . sf . sveditor . core . db ; public interface ISVDBEndLocation { SVDBLocation getEndLocation ( ) ; void setEndLocation ( SVDBLocation loc ) ; } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBScopeItem extends SVDBItem implements ISVDBScopeItem { public List < ISVDBChildItem > fItems ; public SVDBLocation fEndLocation ; protected SVDBScopeItem ( String name , SVDBItemType type ) { super ( name , type ) ; fItems = new ArrayList < ISVDBChildItem > ( ) ; } public SVDBScopeItem ( ) { super ( "" , SVDBItemType . NullExpr ) ; fItems = new ArrayList < ISVDBChildItem > ( ) ; } public void setEndLocation ( SVDBLocation loc ) { fEndLocation = loc ; } public SVDBLocation getEndLocation ( ) { return fEndLocation ; } public void addItem ( ISVDBItemBase item ) { if ( item instanceof ISVDBChildItem ) { ( ( ISVDBChildItem ) item ) . setParent ( this ) ; fItems . add ( ( ISVDBChildItem ) item ) ; } else { throw new RuntimeException ( "" + item . getClass ( ) . getName ( ) ) ; } } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fItems . add ( item ) ; } @ Deprecated @ SuppressWarnings ( { "" , "" } ) public List < ISVDBItemBase > getItems ( ) { return ( List < ISVDBItemBase > ) ( ( List ) fItems ) ; } public Iterable < ISVDBChildItem > getChildren ( ) { return fItems ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBScopeItem ) { SVDBScopeItem o = ( SVDBScopeItem ) obj ; if ( fEndLocation == null || o . fEndLocation == null ) { if ( fEndLocation != o . fEndLocation ) { return false ; } } else if ( ! fEndLocation . equals ( o . fEndLocation ) ) { return false ; } if ( fItems . size ( ) == o . fItems . size ( ) ) { for ( int i = ; i < fItems . size ( ) ; i ++ ) { if ( ! fItems . get ( i ) . equals ( o . fItems . get ( i ) ) ) { return false ; } } } else { return false ; } return super . equals ( obj ) ; } return false ; } } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . SVDBTypeInfoEnumerator ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBDeclCacheItem implements ISVDBNamedItem { public String fFileName ; @ SVDBDoNotSaveAttr private ISVDBDeclCache fParent ; public String fName ; public SVDBItemType fType ; public boolean fIsFileTreeItem ; public SVDBDeclCacheItem ( ) { } public SVDBDeclCacheItem ( ISVDBDeclCache parent , String filename , String name , SVDBItemType type , boolean is_ft_item ) { fParent = parent ; fFileName = filename ; fName = name ; fType = type ; fIsFileTreeItem = is_ft_item ; } public void init ( ISVDBDeclCache parent ) { fParent = parent ; } public String getFilename ( ) { return fFileName ; } public void setFilename ( String filename ) { fFileName = filename ; } public String getName ( ) { return fName ; } public void setName ( String name ) { fName = name ; } public boolean isFileTreeItem ( ) { return fIsFileTreeItem ; } public void setParent ( ISVDBDeclCache parent ) { fParent = parent ; } public ISVDBDeclCache getParent ( ) { return fParent ; } public SVDBItemType getType ( ) { return fType ; } public void setType ( SVDBItemType type ) { fType = type ; } public ISVDBItemBase getSVDBItem ( ) { if ( fParent == null ) { return null ; } SVDBFile file = fParent . getDeclFile ( new NullProgressMonitor ( ) , this ) ; if ( file != null ) { for ( ISVDBChildItem c : file . getChildren ( ) ) { if ( SVDBItem . getName ( c ) . equals ( fName ) && c . getType ( ) == getType ( ) ) { return c ; } else if ( c instanceof ISVDBChildParent ) { ISVDBItemBase i = getSVDBItem ( ( ISVDBChildParent ) c ) ; if ( i != null ) { return i ; } } else if ( getType ( ) == SVDBItemType . TypeInfoEnumerator && c . getType ( ) == SVDBItemType . TypedefStmt ) { SVDBTypedefStmt stmt = ( SVDBTypedefStmt ) c ; if ( stmt . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoEnum ) { SVDBTypeInfoEnum e = ( SVDBTypeInfoEnum ) stmt . getTypeInfo ( ) ; for ( SVDBTypeInfoEnumerator en : e . getEnumerators ( ) ) { if ( en . getName ( ) . equals ( getName ( ) ) ) { return en ; } } } } } } return null ; } private ISVDBItemBase getSVDBItem ( ISVDBChildParent p ) { for ( ISVDBChildItem c : p . getChildren ( ) ) { if ( SVDBItem . getName ( c ) . equals ( fName ) && c . getType ( ) == fType ) { return c ; } } return null ; } public SVDBFile getFile ( ) { if ( fParent == null ) { System . out . println ( "" + fType + "" + fName + "" ) ; return null ; } else { return fParent . getDeclFile ( new NullProgressMonitor ( ) , this ) ; } } public SVDBFile getFilePP ( ) { if ( fParent == null ) { System . out . println ( "" + fType + "" + fName + "" ) ; return null ; } else { return fParent . getDeclFilePP ( new NullProgressMonitor ( ) , this ) ; } } } package net . sf . sveditor . core . db . index ; import java . lang . ref . Reference ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCacheFactory ; import net . sf . sveditor . core . db . index . cache . InMemoryIndexCache ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . SubProgressMonitor ; public class SVDBIndexRegistry implements ILogLevel { public static final String GLOBAL_PROJECT = "" ; private SVDBIndexCollectionMgr fIndexCollectionMgr ; private SVDBIndexCollection fGlobalIndexMgr ; private List < Reference < ISVDBIndex > > fIndexList ; private ISVDBIndexCacheFactory fCacheFactory ; private boolean fAutoRebuildEn ; private LogHandle fLog ; public SVDBIndexRegistry ( ) { this ( false ) ; } public SVDBIndexRegistry ( boolean standalone_test_mode ) { fIndexList = new ArrayList < Reference < ISVDBIndex > > ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; fAutoRebuildEn = true ; fIndexCollectionMgr = new SVDBIndexCollectionMgr ( ) ; } public void setEnableAutoRebuild ( boolean en ) { fAutoRebuildEn = en ; clearStaleIndexes ( ) ; for ( Reference < ISVDBIndex > i : fIndexList ) { if ( i . get ( ) != null ) { i . get ( ) . setEnableAutoRebuild ( fAutoRebuildEn ) ; } } } public SVDBIndexCollectionMgr getIndexCollectionMgr ( ) { return fIndexCollectionMgr ; } public void init ( ISVDBIndexCacheFactory cache_factory ) { fCacheFactory = cache_factory ; fIndexList . clear ( ) ; fGlobalIndexMgr = getGlobalIndexMgr ( ) ; } public void test_init ( ISVDBIndexCacheFactory cache_factory ) { fCacheFactory = cache_factory ; fIndexList . clear ( ) ; } public List < ISVDBIndex > getAllProjectLists ( ) { List < ISVDBIndex > ret = new ArrayList < ISVDBIndex > ( ) ; synchronized ( fIndexList ) { for ( Reference < ISVDBIndex > i : fIndexList ) { if ( i . get ( ) != null ) { ret . add ( i . get ( ) ) ; } } } return ret ; } public List < ISVDBIndex > getProjectIndexList ( String project ) { List < ISVDBIndex > ret = new ArrayList < ISVDBIndex > ( ) ; clearStaleIndexes ( ) ; synchronized ( fIndexList ) { for ( Reference < ISVDBIndex > i : fIndexList ) { if ( i . get ( ) != null && i . get ( ) . getProject ( ) . equals ( project ) ) { ret . add ( i . get ( ) ) ; } } } return ret ; } public List < ISVDBIndex > getIndexList ( ) { List < ISVDBIndex > ret = new ArrayList < ISVDBIndex > ( ) ; clearStaleIndexes ( ) ; synchronized ( fIndexList ) { for ( Reference < ISVDBIndex > i : fIndexList ) { if ( i . get ( ) != null ) { ret . add ( i . get ( ) ) ; } } } return ret ; } public void disposeIndex ( ISVDBIndex index ) { fLog . debug ( LEVEL_MID , "" + index . getBaseLocation ( ) + "" + index . getConfig ( ) ) ; synchronized ( fIndexList ) { fIndexList . remove ( index ) ; } index . dispose ( ) ; } public SVDBIndexCollection getGlobalIndexMgr ( ) { if ( fGlobalIndexMgr == null ) { fGlobalIndexMgr = new SVDBIndexCollection ( fIndexCollectionMgr , GLOBAL_PROJECT ) ; ISVDBIndex index = findCreateIndex ( new NullProgressMonitor ( ) , SVDBIndexRegistry . GLOBAL_PROJECT , SVCorePlugin . SV_BUILTIN_LIBRARY , SVDBPluginLibIndexFactory . TYPE , null ) ; if ( index != null ) { fGlobalIndexMgr . addPluginLibrary ( index ) ; } } return fGlobalIndexMgr ; } public ISVDBIndex findCreateIndex ( IProgressMonitor monitor , String project , String base_location , String type , SVDBIndexConfig config ) { ISVDBIndex ret = null ; base_location = SVFileUtils . normalize ( base_location ) ; fLog . debug ( "" + base_location + "" + type ) ; synchronized ( fIndexList ) { for ( Reference < ISVDBIndex > i : fIndexList ) { ISVDBIndex index = i . get ( ) ; if ( index != null && index . getProject ( ) . equals ( project ) && index . getBaseLocation ( ) . equals ( base_location ) && index . getTypeID ( ) . equals ( type ) ) { ret = index ; break ; } } } if ( ret != null ) { if ( ! SVDBIndexConfig . equals ( config , ret . getConfig ( ) ) ) { fLog . debug ( LEVEL_MID , "" + ret . getBaseLocation ( ) + "" ) ; disposeIndex ( ret ) ; ret = null ; } } if ( ret == null ) { fLog . debug ( "" ) ; ISVDBIndexFactory factory = findFactory ( type ) ; ISVDBIndexCache cache = null ; if ( type . equals ( SVDBShadowIndexFactory . TYPE ) ) { cache = new InMemoryIndexCache ( ) ; } else { cache = fCacheFactory . createIndexCache ( project , base_location ) ; } ret = factory . createSVDBIndex ( project , base_location , cache , config ) ; ret . setEnableAutoRebuild ( fAutoRebuildEn ) ; SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; ret . init ( m ) ; synchronized ( fIndexList ) { fIndexList . add ( new WeakReference < ISVDBIndex > ( ret ) ) ; } } else { fLog . debug ( "" ) ; } return ret ; } public ISVDBIndex findCreateIndex ( String project , String base_location , String type , ISVDBIndexFactory factory , SVDBIndexConfig config ) { return findCreateIndex ( new NullProgressMonitor ( ) , project , base_location , type , factory , config ) ; } public ISVDBIndex findCreateIndex ( IProgressMonitor monitor , String project , String base_location , String type , ISVDBIndexFactory factory , SVDBIndexConfig config ) { ISVDBIndex ret = null ; fLog . debug ( "" + base_location + "" + type ) ; synchronized ( fIndexList ) { for ( Reference < ISVDBIndex > i : fIndexList ) { ISVDBIndex index = i . get ( ) ; if ( index != null && index . getProject ( ) . equals ( project ) && index . getBaseLocation ( ) . equals ( base_location ) && index . getTypeID ( ) . equals ( type ) ) { ret = index ; break ; } } } if ( ret == null ) { fLog . debug ( "" ) ; ISVDBIndexCache cache = fCacheFactory . createIndexCache ( project , base_location ) ; ret = factory . createSVDBIndex ( project , base_location , cache , config ) ; ret . setEnableAutoRebuild ( fAutoRebuildEn ) ; SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; ret . init ( m ) ; synchronized ( fIndexList ) { fIndexList . add ( new WeakReference < ISVDBIndex > ( ret ) ) ; } } else { fLog . debug ( "" ) ; } return ret ; } public void rebuildIndex ( IProgressMonitor monitor , String project ) { fLog . debug ( "" + project + "" ) ; clearStaleIndexes ( ) ; synchronized ( fIndexList ) { for ( Reference < ISVDBIndex > i : fIndexList ) { ISVDBIndex index = i . get ( ) ; if ( index != null && index . getProject ( ) . equals ( project ) ) { index . rebuildIndex ( monitor ) ; } } } } public void save_state ( ) { fLog . debug ( "" ) ; synchronized ( fIndexList ) { for ( Reference < ISVDBIndex > i : fIndexList ) { ISVDBIndex index = i . get ( ) ; if ( index != null ) { index . dispose ( ) ; } } } if ( fCacheFactory != null ) { List < ISVDBIndexCache > cache_l = new ArrayList < ISVDBIndexCache > ( ) ; synchronized ( fIndexList ) { for ( Reference < ISVDBIndex > i : fIndexList ) { ISVDBIndex index = i . get ( ) ; if ( index != null && ! cache_l . contains ( index . getCache ( ) ) && index . getCache ( ) != null ) { cache_l . add ( index . getCache ( ) ) ; } } } fCacheFactory . compactCache ( cache_l ) ; } } private ISVDBIndexFactory findFactory ( String type ) { ISVDBIndexFactory ret = null ; IExtensionRegistry rgy = Platform . getExtensionRegistry ( ) ; IExtensionPoint ext_pt = rgy . getExtensionPoint ( SVCorePlugin . PLUGIN_ID , "" ) ; for ( IExtension ext_l : ext_pt . getExtensions ( ) ) { for ( IConfigurationElement cel : ext_l . getConfigurationElements ( ) ) { String id = cel . getAttribute ( "" ) ; if ( type . equals ( id ) ) { try { ret = ( ISVDBIndexFactory ) cel . createExecutableExtension ( "" ) ; } catch ( Exception e ) { fLog . error ( "" + "" + id + "" , e ) ; } break ; } } } return ret ; } private void clearStaleIndexes ( ) { synchronized ( fIndexList ) { for ( int i = ; i < fIndexList . size ( ) ; i ++ ) { if ( fIndexList . get ( i ) . get ( ) == null ) { System . out . println ( "" ) ; fIndexList . remove ( i ) ; i -- ; } } } } } package net . sf . sveditor . core . db . index ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . project . SVDBSourceCollection ; import net . sf . sveditor . core . fileset . AbstractSVFileMatcher ; import net . sf . sveditor . core . fileset . SVFileSet ; import net . sf . sveditor . core . fileset . SVFilesystemFileMatcher ; import net . sf . sveditor . core . fileset . SVWorkspaceFileMatcher ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVDBSourceCollectionIndexFactory implements ISVDBIndexFactory { public static final String TYPE = "" ; public static final String FILESET = "" ; private LogHandle fLog ; public SVDBSourceCollectionIndexFactory ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } public ISVDBIndex createSVDBIndex ( String project_name , String base_location , ISVDBIndexCache cache , SVDBIndexConfig config ) { ISVDBIndex ret ; ISVDBFileSystemProvider fs_provider = null ; List < AbstractSVFileMatcher > matcher_list = new ArrayList < AbstractSVFileMatcher > ( ) ; fLog . debug ( "" + project_name + "" + base_location ) ; SVFileSet fs = null ; AbstractSVFileMatcher matcher = null ; if ( config != null ) { fs = ( SVFileSet ) config . get ( FILESET ) ; } if ( base_location . startsWith ( "" ) ) { if ( fs == null ) { fs = new SVFileSet ( base_location ) ; fs . getIncludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionIncludes ( ) ) ) ; fs . getExcludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionExcludes ( ) ) ) ; } matcher = new SVWorkspaceFileMatcher ( ) ; matcher . addFileSet ( fs ) ; fs_provider = new SVDBWSFileSystemProvider ( ) ; matcher_list . add ( matcher ) ; } else { if ( fs == null ) { fs = new SVFileSet ( base_location ) ; fs . getIncludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionIncludes ( ) ) ) ; fs . getExcludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionExcludes ( ) ) ) ; } matcher = new SVFilesystemFileMatcher ( ) ; matcher . addFileSet ( fs ) ; fs_provider = new SVDBFSFileSystemProvider ( ) ; matcher_list . add ( matcher ) ; } ret = new SVDBSourceCollectionIndex ( project_name , base_location , matcher_list , fs_provider , cache , config ) ; return ret ; } } package net . sf . sveditor . core . db . index ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . lang . ref . Reference ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IResourceDeltaVisitor ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; public class SVDBWSFileSystemProvider implements ISVDBFileSystemProvider , IResourceChangeListener , IResourceDeltaVisitor { private List < Reference < ISVDBFileSystemChangeListener > > fChangeListeners ; public SVDBWSFileSystemProvider ( ) { fChangeListeners = new ArrayList < Reference < ISVDBFileSystemChangeListener > > ( ) ; } public void init ( String path ) { IFile file ; IContainer folder = null ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; } try { folder = root . getFolder ( new Path ( path ) ) ; if ( ! folder . exists ( ) ) { file = root . getFile ( new Path ( path ) ) ; folder = file . getParent ( ) ; if ( ! folder . exists ( ) ) { folder = null ; } } } catch ( IllegalArgumentException e ) { } if ( folder == null ) { String pname = path ; if ( pname . startsWith ( "" ) ) { pname = pname . substring ( ) ; } if ( pname . endsWith ( "" ) ) { pname = pname . substring ( , pname . length ( ) - ) ; } for ( IProject p_t : root . getProjects ( ) ) { if ( p_t . isOpen ( ) && p_t . getName ( ) . equals ( pname ) ) { folder = p_t ; } } } if ( folder != null ) { try { folder . refreshLocal ( IResource . DEPTH_INFINITE , null ) ; } catch ( CoreException e ) { } } ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( this ) ; } public void addMarker ( String path , final String type , final int lineno , final String msg ) { if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; final IFile file = root . getFile ( new Path ( path ) ) ; int severity ; if ( type . equals ( MARKER_TYPE_ERROR ) ) { severity = IMarker . SEVERITY_ERROR ; } else if ( type . equals ( MARKER_TYPE_WARNING ) ) { severity = IMarker . SEVERITY_WARNING ; } else { severity = IMarker . SEVERITY_INFO ; } SVCorePlugin . getDefault ( ) . propagateMarker ( file , severity , lineno , msg ) ; } } public void clearMarkers ( String path ) { if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IFile file = root . getFile ( new Path ( path ) ) ; if ( file . exists ( ) ) { try { IMarker markers [ ] = file . findMarkers ( IMarker . PROBLEM , true , IResource . DEPTH_INFINITE ) ; for ( IMarker m : markers ) { m . delete ( ) ; } } catch ( CoreException e ) { } } } } public void dispose ( ) { ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( this ) ; } public boolean fileExists ( String path ) { if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; try { IFile file = root . getFile ( new Path ( path ) ) ; IFolder folder = root . getFolder ( new Path ( path ) ) ; return ( file . exists ( ) || folder . exists ( ) ) ; } catch ( IllegalArgumentException e ) { return false ; } } else { return new File ( path ) . exists ( ) ; } } public boolean isDir ( String path ) { if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; if ( path . startsWith ( "" ) ) { path = path . substring ( ) ; } IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; try { IFolder folder = root . getFolder ( new Path ( path ) ) ; return folder . exists ( ) ; } catch ( IllegalArgumentException e ) { } try { IProject project = root . getProject ( path ) ; return project . exists ( ) ; } catch ( IllegalArgumentException e ) { } return false ; } else { return new File ( path ) . isDirectory ( ) ; } } public List < String > getFiles ( String path ) { List < String > ret = new ArrayList < String > ( ) ; if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; if ( path . startsWith ( "" ) ) { path = path . substring ( ) ; } IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IContainer c = null ; try { c = root . getFolder ( new Path ( path ) ) ; } catch ( IllegalArgumentException e ) { } if ( c == null ) { try { c = root . getProject ( path ) ; } catch ( IllegalArgumentException e ) { } } if ( c != null ) { try { for ( IResource m : c . members ( ) ) { IPath p = m . getFullPath ( ) ; ret . add ( "" + p . toString ( ) ) ; } } catch ( CoreException e ) { } } } else { File p = new File ( path ) ; if ( p . isDirectory ( ) ) { File f_l [ ] = p . listFiles ( ) ; if ( f_l != null ) { for ( File f : p . listFiles ( ) ) { if ( ! f . getName ( ) . equals ( "" ) && ! f . getName ( ) . equals ( "" ) ) { ret . add ( f . getAbsolutePath ( ) ) ; } } } } } return ret ; } public void closeStream ( InputStream in ) { try { if ( in != null ) { in . close ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } public InputStream openStream ( String path ) { InputStream ret = null ; if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IFile file = root . getFile ( new Path ( path ) ) ; if ( ! file . exists ( ) ) { return null ; } for ( int i = ; i < ; i ++ ) { try { ret = file . getContents ( ) ; break ; } catch ( CoreException e ) { if ( i == && e . getMessage ( ) . contains ( "" ) ) { try { file . getParent ( ) . refreshLocal ( IResource . DEPTH_INFINITE , null ) ; } catch ( CoreException e2 ) { } } else { e . printStackTrace ( ) ; } } } } else { try { ret = new FileInputStream ( path ) ; } catch ( IOException e ) { } } return ret ; } public String resolvePath ( String path , String fmt ) { boolean ws_path = path . startsWith ( "" ) ; if ( ws_path ) { path = path . substring ( "" . length ( ) ) ; StringBuilder ret = new StringBuilder ( ) ; int i = path . length ( ) - ; int end ; int skipCnt = ; while ( i >= ) { end = ret . length ( ) ; while ( i >= && path . charAt ( i ) != '' && path . charAt ( i ) != '' ) { ret . append ( path . charAt ( i ) ) ; i -- ; } if ( i != - ) { ret . append ( "" ) ; i -- ; } if ( ( ret . length ( ) - end ) > ) { String str = ret . substring ( end , ret . length ( ) - ) ; if ( str . equals ( "" ) ) { skipCnt ++ ; ret . setLength ( end ) ; } else if ( skipCnt > ) { ret . setLength ( end ) ; skipCnt -- ; } } } if ( skipCnt > ) { throw new RuntimeException ( "" ) ; } path = ret . reverse ( ) . toString ( ) ; } if ( fmt != null ) { if ( fmt . equals ( ISVDBFileSystemProvider . PATHFMT_FILESYSTEM ) ) { if ( ws_path ) { if ( isDir ( "" + path ) ) { IContainer c = SVFileUtils . getWorkspaceFolder ( path ) ; if ( c != null ) { path = c . getLocation ( ) . toOSString ( ) ; } } else { IFile f = SVFileUtils . getWorkspaceFile ( path ) ; if ( f != null ) { path = f . getLocation ( ) . toOSString ( ) ; } } } } else if ( fmt . equals ( ISVDBFileSystemProvider . PATHFMT_WORKSPACE ) ) { if ( ! ws_path ) { if ( isDir ( path ) ) { IContainer c = SVFileUtils . findWorkspaceFolder ( path ) ; if ( c != null ) { path = "" + c . getFullPath ( ) ; } } else { IFile f = SVFileUtils . findWorkspaceFile ( path ) ; if ( f != null ) { path = "" + f . getFullPath ( ) ; } } } } } else { if ( ws_path ) { path = "" + path ; } } return path ; } protected String normalizePath ( String path ) { StringBuilder ret = new StringBuilder ( ) ; int i = path . length ( ) - ; int end ; int skipCnt = ; while ( i >= ) { end = ret . length ( ) ; while ( i >= && path . charAt ( i ) != '' && path . charAt ( i ) != '' ) { ret . append ( path . charAt ( i ) ) ; i -- ; } if ( i != - ) { ret . append ( "" ) ; i -- ; } if ( ( ret . length ( ) - end ) > ) { String str = ret . substring ( end , ret . length ( ) - ) ; if ( str . equals ( "" ) ) { skipCnt ++ ; ret . setLength ( end ) ; } else if ( skipCnt > ) { ret . setLength ( end ) ; skipCnt -- ; } } } if ( skipCnt > ) { throw new RuntimeException ( "" ) ; } return ret . reverse ( ) . toString ( ) ; } public long getLastModifiedTime ( String path ) { if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IFile file = root . getFile ( new Path ( path ) ) ; if ( file != null && file . getLocation ( ) != null && file . getLocation ( ) . toFile ( ) != null ) { return file . getLocation ( ) . toFile ( ) . lastModified ( ) ; } else { return ; } } else { return new File ( path ) . lastModified ( ) ; } } public void addFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { synchronized ( fChangeListeners ) { fChangeListeners . add ( new WeakReference < ISVDBFileSystemChangeListener > ( l ) ) ; } } public void removeFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { synchronized ( fChangeListeners ) { for ( int i = ; i < fChangeListeners . size ( ) ; i ++ ) { ISVDBFileSystemChangeListener ll = fChangeListeners . get ( i ) . get ( ) ; if ( ll == null || ll == l ) { fChangeListeners . remove ( i ) ; i -- ; } } } } public synchronized boolean visit ( IResourceDelta delta ) throws CoreException { if ( delta . getResource ( ) instanceof IFile ) { String file = "" ; file += SVFileUtils . normalize ( ( ( IFile ) delta . getResource ( ) ) . getFullPath ( ) . toOSString ( ) ) ; if ( delta . getKind ( ) == IResourceDelta . REMOVED ) { synchronized ( fChangeListeners ) { for ( int i = ; i < fChangeListeners . size ( ) ; i ++ ) { ISVDBFileSystemChangeListener l = fChangeListeners . get ( i ) . get ( ) ; if ( l == null ) { fChangeListeners . remove ( i ) ; i -- ; } else { l . fileRemoved ( file ) ; } } } } else if ( delta . getKind ( ) == IResourceDelta . ADDED ) { synchronized ( fChangeListeners ) { for ( int i = ; i < fChangeListeners . size ( ) ; i ++ ) { ISVDBFileSystemChangeListener l = fChangeListeners . get ( i ) . get ( ) ; if ( l == null ) { fChangeListeners . remove ( i ) ; i -- ; } else { l . fileAdded ( file ) ; } } } } else if ( delta . getKind ( ) == IResourceDelta . CHANGED ) { if ( ( delta . getFlags ( ) & IResourceDelta . CONTENT ) != ) { synchronized ( fChangeListeners ) { for ( int i = ; i < fChangeListeners . size ( ) ; i ++ ) { ISVDBFileSystemChangeListener l = fChangeListeners . get ( i ) . get ( ) ; if ( l == null ) { fChangeListeners . remove ( i ) ; i -- ; } else { l . fileChanged ( file ) ; } } } } } } return true ; } public void resourceChanged ( IResourceChangeEvent event ) { try { if ( event . getDelta ( ) != null ) { event . getDelta ( ) . accept ( this ) ; } } catch ( CoreException e ) { e . printStackTrace ( ) ; } } } package net . sf . sveditor . core . db . index . plugin_lib ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexConfig ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; public class SVDBPluginLibIndexFactory implements ISVDBIndexFactory { public static final String TYPE = "" ; public ISVDBIndex createSVDBIndex ( String project , String base_location , ISVDBIndexCache cache , SVDBIndexConfig config ) { for ( SVDBPluginLibDescriptor d : SVCorePlugin . getDefault ( ) . getPluginLibList ( ) ) { if ( d . getId ( ) . equals ( base_location ) ) { return new SVDBPluginLibIndex ( project , d . getNamespace ( ) , d . getPath ( ) , cache ) ; } } return null ; } } package net . sf . sveditor . core . db . index . plugin_lib ; import java . net . URI ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . filesystem . provider . FileSystem ; public class PluginFilesystem extends FileSystem { public PluginFilesystem ( ) { } @ Override public IFileStore getStore ( URI uri ) { return new PluginFileStore ( uri ) ; } } package net . sf . sveditor . core . db . index . plugin_lib ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBFileSystemChangeListener ; import net . sf . sveditor . core . db . index . ISVDBFileSystemProvider ; import net . sf . sveditor . core . db . index . SVDBLibIndex ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . log . LogFactory ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . osgi . framework . Bundle ; import org . osgi . framework . Version ; public class SVDBPluginLibIndex extends SVDBLibIndex implements ISVDBFileSystemProvider { private Bundle fBundle ; private String fPluginNS ; private String fRootFile ; private long fBundleVersion = - ; public SVDBPluginLibIndex ( String project , String plugin_ns , String root , ISVDBIndexCache cache ) { super ( project , "" + plugin_ns + "" + root , null , cache , null ) ; fLog = LogFactory . getLogHandle ( "" ) ; fRootFile = root ; fPluginNS = plugin_ns ; fBundle = Platform . getBundle ( fPluginNS ) ; fLog . debug ( "" + fRootFile + "" + getBaseLocation ( ) ) ; setFileSystemProvider ( this ) ; } public String getTypeID ( ) { return SVDBPluginLibIndexFactory . TYPE ; } @ Override protected void discoverRootFiles ( IProgressMonitor monitor ) { clearFilesList ( ) ; clearIncludePaths ( ) ; addFile ( getBaseLocation ( ) ) ; addIncludePath ( getResolvedBaseLocationDir ( ) ) ; } public boolean isDir ( String path ) { if ( path . startsWith ( "" ) ) { URL entry ; String leaf = path . substring ( ( "" + fPluginNS ) . length ( ) ) ; return ( ( entry = fBundle . getEntry ( leaf ) ) != null && entry . getPath ( ) . endsWith ( "" ) ) ; } else { return false ; } } public List < String > getFiles ( String path ) { return new ArrayList < String > ( ) ; } public void addMarker ( String path , String type , int lineno , String msg ) { } public void clearMarkers ( String path ) { } public void closeStream ( InputStream in ) { try { in . close ( ) ; } catch ( IOException e ) { } } public boolean fileExists ( String path ) { if ( path . startsWith ( "" ) ) { String leaf = path . substring ( ( "" + fPluginNS ) . length ( ) ) ; return ( fBundle . getEntry ( leaf ) != null ) ; } else { return false ; } } public String resolvePath ( String path , String fmt ) { return path ; } public void init ( String root ) { } public InputStream openStream ( String path ) { InputStream ret = null ; if ( path . startsWith ( "" ) ) { String leaf = path . substring ( ( "" + fPluginNS ) . length ( ) ) ; URL url = fBundle . getEntry ( leaf ) ; if ( url != null ) { try { ret = url . openStream ( ) ; } catch ( IOException e ) { fLog . error ( "" + path + "" , e ) ; } } } return ret ; } public long getLastModifiedTime ( String file ) { if ( fBundleVersion == - ) { Version v = SVCorePlugin . getDefault ( ) . getBundle ( ) . getVersion ( ) ; fBundleVersion = v . getMicro ( ) ; fBundleVersion |= v . getMinor ( ) << ; fBundleVersion |= v . getMajor ( ) << ; fBundleVersion |= ( << ) ; } if ( fBundleVersion < fBundle . getLastModified ( ) ) { System . out . println ( "" + fBundleVersion + "" + fBundle . getLastModified ( ) ) ; } return fBundleVersion ; } @ Override public void dispose ( ) { if ( getCache ( ) != null ) { getCache ( ) . sync ( ) ; } } public void addFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { } public void removeFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { } } package net . sf . sveditor . core . db . index . plugin_lib ; public class SVDBPluginLibDescriptor { private String fName ; private String fId ; private String fNamespace ; private String fPath ; private boolean fIsDefault ; private String fDescription ; public SVDBPluginLibDescriptor ( String name , String id , String namespace , String path , boolean is_default , String description ) { fName = name ; fId = id ; fNamespace = namespace ; fPath = path ; fIsDefault = is_default ; fDescription = description ; } public String getName ( ) { return fName ; } public String getId ( ) { return fId ; } public String getPath ( ) { return fPath ; } public String getNamespace ( ) { return fNamespace ; } public boolean isDefault ( ) { return fIsDefault ; } public String getDescription ( ) { return fDescription ; } } package net . sf . sveditor . core . db . index . plugin_lib ; import java . io . InputStream ; import java . net . URI ; import java . net . URL ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileInfo ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . filesystem . provider . FileInfo ; import org . eclipse . core . filesystem . provider . FileStore ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . osgi . framework . Bundle ; public class PluginFileStore extends FileStore { private URI fURI ; public PluginFileStore ( URI uri ) { fURI = uri ; } public String getPluginPath ( ) { return fURI . toString ( ) ; } @ Override public String [ ] childNames ( int options , IProgressMonitor monitor ) throws CoreException { return new String [ ] ; } @ Override public IFileInfo fetchInfo ( int options , IProgressMonitor monitor ) throws CoreException { FileInfo info = new FileInfo ( getName ( ) ) ; info . setExists ( true ) ; info . setLength ( ) ; info . setDirectory ( false ) ; info . setAttribute ( EFS . ATTRIBUTE_READ_ONLY , true ) ; info . setAttribute ( EFS . ATTRIBUTE_HIDDEN , false ) ; return info ; } @ Override public IFileStore getChild ( String name ) { return null ; } @ Override public String getName ( ) { return fURI . getPath ( ) . substring ( fURI . getPath ( ) . lastIndexOf ( '' ) + ) ; } @ Override public IFileStore getParent ( ) { return null ; } @ Override public InputStream openInputStream ( int options , IProgressMonitor monitor ) throws CoreException { String host = fURI . getHost ( ) ; String path = fURI . getPath ( ) ; if ( host == null ) { host = path . substring ( , path . indexOf ( '' , ) ) ; path = path . substring ( path . indexOf ( '' , ) + ) ; } Bundle bundle = Platform . getBundle ( host ) ; URL url = bundle . getEntry ( path ) ; try { return url . openStream ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } } @ Override public URI toURI ( ) { return fURI ; } } package net . sf . sveditor . core . db . index ; public interface ISVDBProjectRefProvider { SVDBIndexCollection resolveProjectRef ( String path ) ; } package net . sf . sveditor . core . db . index ; import java . util . Map ; public class SVDBIndexFactoryUtils { @ SuppressWarnings ( "" ) public static void setBaseProperties ( Map < String , Object > config , ISVDBIndex index ) { if ( config != null ) { if ( config . containsKey ( ISVDBIndexFactory . KEY_GlobalDefineMap ) ) { Map < String , String > define_map = ( Map < String , String > ) config . get ( ISVDBIndexFactory . KEY_GlobalDefineMap ) ; for ( String key : define_map . keySet ( ) ) { index . setGlobalDefine ( key , define_map . get ( key ) ) ; } } } } } package net . sf . sveditor . core . db . index ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import java . util . regex . Pattern ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerKind ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . SVDBPreProcCond ; import net . sf . sveditor . core . db . SVDBPreProcObserver ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . refs . ISVDBRefMatcher ; import net . sf . sveditor . core . db . refs . SVDBRefCacheEntry ; import net . sf . sveditor . core . db . refs . SVDBRefCacheItem ; import net . sf . sveditor . core . db . search . ISVDBFindNameMatcher ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import net . sf . sveditor . core . job_mgr . IJob ; import net . sf . sveditor . core . job_mgr . IJobMgr ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . ILogLevelListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcDirectiveScanner ; import net . sf . sveditor . core . scanner . FileContextSearchMacroProvider ; import net . sf . sveditor . core . scanner . IPreProcMacroProvider ; import net . sf . sveditor . core . scanner . SVFileTreeMacroProvider ; import net . sf . sveditor . core . scanner . SVPreProcDefineProvider ; import org . eclipse . core . filesystem . provider . FileTree ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . SubProgressMonitor ; public abstract class AbstractThreadedSVDBIndex implements ISVDBIndex , ISVDBFileSystemChangeListener , ILogLevelListener , ILogLevel { private static final int IndexState_AllInvalid = ; private static final int IndexState_RootFilesDiscovered = ( IndexState_AllInvalid + ) ; private static final int IndexState_FilesPreProcessed = ( IndexState_RootFilesDiscovered + ) ; private static final int IndexState_FileTreeValid = ( IndexState_FilesPreProcessed + ) ; private static final int IndexState_AllFilesParsed = ( IndexState_FileTreeValid + ) ; public String fProjectName ; private String fBaseLocation ; private String fResolvedBaseLocation ; private String fBaseLocationDir ; private SVDBBaseIndexCacheData fIndexCacheData ; private boolean fCacheDataValid ; protected Set < String > fMissingIncludes ; private ISVDBIncludeFileProvider fIncludeFileProvider ; private List < ISVDBIndexChangeListener > fIndexChangeListeners ; protected static Pattern fWinPathPattern ; protected LogHandle fLog ; private ISVDBFileSystemProvider fFileSystemProvider ; protected boolean fLoadUpToDate ; private ISVDBIndexCache fCache ; private SVDBIndexConfig fConfig ; private Set < String > fFileDirs ; protected boolean fDebugEn ; protected boolean fInWorkspaceOk ; private int fIndexState ; protected boolean fAutoRebuildEn ; protected boolean fIsDirty ; protected boolean fEnableThreads = false ; static { fWinPathPattern = Pattern . compile ( "" ) ; } protected AbstractThreadedSVDBIndex ( String project ) { fIndexChangeListeners = new ArrayList < ISVDBIndexChangeListener > ( ) ; fProjectName = project ; fLog = LogFactory . getLogHandle ( getLogName ( ) ) ; fLog . addLogLevelListener ( this ) ; fDebugEn = fLog . isEnabled ( ) ; fMissingIncludes = new HashSet < String > ( ) ; fAutoRebuildEn = true ; fFileDirs = new HashSet < String > ( ) ; } public AbstractThreadedSVDBIndex ( String project , String base_location , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { this ( project ) ; fBaseLocation = base_location ; fCache = cache ; fConfig = config ; setFileSystemProvider ( fs_provider ) ; fInWorkspaceOk = ( base_location . startsWith ( "" ) ) ; fAutoRebuildEn = true ; } public void logLevelChanged ( ILogHandle handle ) { fDebugEn = handle . isEnabled ( ) ; } public void setEnableAutoRebuild ( boolean en ) { fAutoRebuildEn = en ; } public boolean isDirty ( ) { return fIsDirty ; } protected abstract String getLogName ( ) ; protected boolean checkCacheValid ( ) { boolean valid = true ; String version = SVCorePlugin . getVersion ( ) ; if ( fDebugEn ) { fLog . debug ( "" + fIndexCacheData . getVersion ( ) + "" + version ) ; } if ( fIndexCacheData . getVersion ( ) == null || ! fIndexCacheData . getVersion ( ) . equals ( version ) ) { valid = false ; return valid ; } if ( fConfig != null ) { } if ( fCache . getFileList ( ) . size ( ) > ) { for ( String path : fCache . getFileList ( ) ) { long fs_timestamp = fFileSystemProvider . getLastModifiedTime ( path ) ; long cache_timestamp = fCache . getLastModified ( path ) ; if ( fs_timestamp != cache_timestamp ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path + "" + fs_timestamp + "" + cache_timestamp ) ; } valid = false ; break ; } } } else { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + getBaseLocation ( ) + "" ) ; } SVDBIndexFactoryUtils . setBaseProperties ( fConfig , this ) ; valid = false ; } if ( getCacheData ( ) . getMissingIncludeFiles ( ) . size ( ) > && valid ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } for ( String path : getCacheData ( ) . getMissingIncludeFiles ( ) ) { SVDBSearchResult < SVDBFile > res = findIncludedFile ( path ) ; if ( res != null ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + getBaseLocation ( ) + "" + path ) ; } valid = false ; break ; } } } if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + getBaseLocation ( ) + "" + ( ( valid ) ? "" : "" ) ) ; } return valid ; } @ SuppressWarnings ( "" ) public void init ( IProgressMonitor monitor ) { SubProgressMonitor m ; monitor . beginTask ( "" + getBaseLocation ( ) , ) ; m = new SubProgressMonitor ( monitor , ) ; fIndexCacheData = createIndexCacheData ( ) ; fCacheDataValid = fCache . init ( m , fIndexCacheData ) ; if ( fCacheDataValid ) { fCacheDataValid = checkCacheValid ( ) ; } if ( fCacheDataValid ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } fIndexState = IndexState_FileTreeValid ; if ( fIndexCacheData . getDeclCacheMap ( ) != null ) { for ( Entry < String , List < SVDBDeclCacheItem > > e : fIndexCacheData . getDeclCacheMap ( ) . entrySet ( ) ) { for ( SVDBDeclCacheItem i : e . getValue ( ) ) { i . init ( this ) ; } } } if ( fIndexCacheData . getPackageCacheMap ( ) != null ) { for ( Entry < String , List < SVDBDeclCacheItem > > e : fIndexCacheData . getPackageCacheMap ( ) . entrySet ( ) ) { for ( SVDBDeclCacheItem i : e . getValue ( ) ) { i . init ( this ) ; } } } for ( String f : fCache . getFileList ( ) ) { addFileDir ( f ) ; } } else { if ( fDebugEn ) { fLog . debug ( "" + getBaseLocation ( ) + "" ) ; } invalidateIndex ( "" , true ) ; } fIndexCacheData . setVersion ( SVCorePlugin . getVersion ( ) ) ; if ( fConfig != null && fConfig . containsKey ( ISVDBIndexFactory . KEY_GlobalDefineMap ) ) { Map < String , String > define_map = ( Map < String , String > ) fConfig . get ( ISVDBIndexFactory . KEY_GlobalDefineMap ) ; fIndexCacheData . clearGlobalDefines ( ) ; for ( String key : define_map . keySet ( ) ) { fIndexCacheData . setGlobalDefine ( key , define_map . get ( key ) ) ; } } monitor . done ( ) ; } public void loadIndex ( IProgressMonitor monitor ) { ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; } public synchronized void ensureIndexState ( IProgressMonitor monitor , int state ) { List < IJob > jobs = new ArrayList < IJob > ( ) ; IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; monitor . beginTask ( "" + getBaseLocation ( ) , ) ; if ( fIndexState < IndexState_RootFilesDiscovered && state >= IndexState_RootFilesDiscovered ) { if ( fDebugEn ) { fLog . debug ( "" + fIndexState ) ; } SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; discoverRootFiles ( jobs ) ; fCache . sync ( ) ; fIsDirty = false ; join ( m , jobs ) ; jobs . clear ( ) ; fIndexState = IndexState_RootFilesDiscovered ; } if ( fIndexState < IndexState_FilesPreProcessed && state >= IndexState_FilesPreProcessed ) { if ( fDebugEn ) { fLog . debug ( "" + fIndexState ) ; } SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; preProcessFiles ( jobs ) ; fIsDirty = false ; join ( m , jobs ) ; jobs . clear ( ) ; fIndexState = IndexState_FilesPreProcessed ; } if ( fIndexState < IndexState_FileTreeValid && state >= IndexState_FileTreeValid ) { if ( fDebugEn ) { fLog . debug ( "" + fIndexState ) ; } SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; List < String > missing_includes = new ArrayList < String > ( ) ; buildFileTree ( jobs , missing_includes ) ; join ( m , jobs ) ; jobs . clear ( ) ; getCacheData ( ) . clearMissingIncludeFiles ( ) ; for ( String path : missing_includes ) { getCacheData ( ) . addMissingIncludeFile ( path ) ; } propagateAllMarkers ( ) ; notifyIndexRebuilt ( ) ; fIsDirty = false ; fIndexState = IndexState_FileTreeValid ; } if ( fIndexState < IndexState_AllFilesParsed && state >= IndexState_AllFilesParsed ) { if ( fCacheDataValid ) { SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; fCache . initLoad ( m ) ; m . done ( ) ; } else { parseFiles ( jobs ) ; } fIndexState = IndexState_AllFilesParsed ; fIsDirty = false ; join ( new NullProgressMonitor ( ) , jobs ) ; jobs . clear ( ) ; } monitor . done ( ) ; } protected void parseFiles ( List < IJob > jobs ) { final List < String > paths = new ArrayList < String > ( ) ; fLog . debug ( LEVEL_MAX , "" ) ; synchronized ( fCache ) { paths . addAll ( fCache . getFileList ( ) ) ; } IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; for ( String path : paths ) { ParseFilesRunnable r = new ParseFilesRunnable ( path ) ; IJob j = job_mgr . createJob ( ) ; j . init ( path , r ) ; synchronized ( jobs ) { jobs . add ( j ) ; } if ( fEnableThreads ) { job_mgr . queueJob ( j ) ; } } } private class ParseFilesRunnable implements Runnable { private String fPath ; public ParseFilesRunnable ( String path ) { fPath = path ; } public void run ( ) { SVDBFile file ; SVDBFileTree ft_root ; synchronized ( fCache ) { ft_root = fCache . getFileTree ( new NullProgressMonitor ( ) , fPath ) ; } if ( ft_root == null ) { try { throw new Exception ( ) ; } catch ( Exception e ) { fLog . error ( "" + fPath + "" + getBaseLocation ( ) , e ) ; for ( String p : getFileList ( new NullProgressMonitor ( ) ) ) { fLog . error ( "" + p ) ; } } } long start = System . currentTimeMillis ( ) ; IPreProcMacroProvider mp = createMacroProvider ( ft_root ) ; processFile ( ft_root , mp ) ; long end = System . currentTimeMillis ( ) ; synchronized ( fCache ) { file = fCache . getFile ( new NullProgressMonitor ( ) , fPath ) ; } } } protected void invalidateIndex ( String reason , boolean force ) { if ( fDebugEn ) { if ( fAutoRebuildEn || force ) { fLog . debug ( LEVEL_MIN , "" + ( ( reason == null ) ? "" : reason ) ) ; } else { fLog . debug ( LEVEL_MIN , "" + ( ( reason == null ) ? "" : reason ) + "" ) ; } } if ( fAutoRebuildEn || force ) { fIndexState = IndexState_AllInvalid ; fCacheDataValid = false ; fIndexCacheData . clear ( ) ; fCache . clear ( new NullProgressMonitor ( ) ) ; fMissingIncludes . clear ( ) ; } else { fIsDirty = true ; } } public void rebuildIndex ( IProgressMonitor monitor ) { invalidateIndex ( "" , true ) ; } public ISVDBIndexCache getCache ( ) { return fCache ; } public SVDBIndexConfig getConfig ( ) { return fConfig ; } protected SVDBBaseIndexCacheData getCacheData ( ) { return fIndexCacheData ; } public void setFileSystemProvider ( ISVDBFileSystemProvider fs_provider ) { if ( fFileSystemProvider != null && fs_provider != fFileSystemProvider ) { fFileSystemProvider . removeFileSystemChangeListener ( this ) ; } fFileSystemProvider = fs_provider ; if ( fFileSystemProvider != null ) { fFileSystemProvider . init ( getResolvedBaseLocationDir ( ) ) ; fFileSystemProvider . addFileSystemChangeListener ( this ) ; } } public ISVDBFileSystemProvider getFileSystemProvider ( ) { return fFileSystemProvider ; } public void fileChanged ( String path ) { synchronized ( fCache ) { if ( fCache . getFileList ( ) . contains ( path ) ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path ) ; } fCache . setFile ( path , null ) ; fCache . setLastModified ( path , getFileSystemProvider ( ) . getLastModifiedTime ( path ) ) ; } } } public void fileRemoved ( String path ) { synchronized ( fCache ) { if ( fCache . getFileList ( ) . contains ( path ) ) { invalidateIndex ( "" , false ) ; } } } public void fileAdded ( String path ) { File f = new File ( path ) ; File p = f . getParentFile ( ) ; if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path ) ; } if ( fFileDirs . contains ( p . getPath ( ) ) ) { invalidateIndex ( "" , false ) ; } } public String getBaseLocation ( ) { return fBaseLocation ; } public String getProject ( ) { return fProjectName ; } public String getResolvedBaseLocation ( ) { if ( fResolvedBaseLocation == null ) { fResolvedBaseLocation = SVDBIndexUtil . expandVars ( fBaseLocation , fProjectName , fInWorkspaceOk ) ; } return fResolvedBaseLocation ; } public String getResolvedBaseLocationDir ( ) { if ( fBaseLocationDir == null ) { String base_location = getResolvedBaseLocation ( ) ; if ( fDebugEn ) { fLog . debug ( "" + base_location ) ; } if ( fFileSystemProvider . isDir ( base_location ) ) { if ( fDebugEn ) { fLog . debug ( "" + base_location + "" ) ; } fBaseLocationDir = base_location ; } else { if ( fDebugEn ) { fLog . debug ( "" + base_location + "" ) ; } fBaseLocationDir = SVFileUtils . getPathParent ( base_location ) ; if ( fDebugEn ) { fLog . debug ( "" + base_location + "" + fBaseLocationDir ) ; } } } return fBaseLocationDir ; } public void setGlobalDefine ( String key , String val ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" + key + "" + val + "" ) ; } fIndexCacheData . setGlobalDefine ( key , val ) ; if ( ! fIndexCacheData . getGlobalDefines ( ) . containsKey ( key ) || ! fIndexCacheData . getGlobalDefines ( ) . get ( key ) . equals ( val ) ) { rebuildIndex ( new NullProgressMonitor ( ) ) ; } } public void clearGlobalDefines ( ) { fIndexCacheData . clearGlobalDefines ( ) ; } protected void clearDefines ( ) { fIndexCacheData . clearDefines ( ) ; } protected void addDefine ( String key , String val ) { fIndexCacheData . addDefine ( key , val ) ; } protected void clearIncludePaths ( ) { fIndexCacheData . clearIncludePaths ( ) ; } protected void addIncludePath ( String path ) { fIndexCacheData . addIncludePath ( path ) ; } public Set < String > getFileList ( IProgressMonitor monitor ) { ensureIndexState ( monitor , IndexState_FileTreeValid ) ; return fCache . getFileList ( ) ; } public SVDBFile findFile ( IProgressMonitor monitor , String path ) { return findFile ( path ) ; } public SVDBFile findPreProcFile ( IProgressMonitor monitor , String path ) { return findPreProcFile ( path ) ; } public synchronized List < SVDBMarker > getMarkers ( String path ) { findFile ( path ) ; return fCache . getMarkers ( path ) ; } protected void addFile ( String path ) { synchronized ( fCache ) { fCache . addFile ( path ) ; fCache . setLastModified ( path , getFileSystemProvider ( ) . getLastModifiedTime ( path ) ) ; } addFileDir ( path ) ; } protected void addFileDir ( String file_path ) { File f = new File ( file_path ) ; File p = f . getParentFile ( ) ; if ( p != null && ! fFileDirs . contains ( p . getPath ( ) ) ) { fFileDirs . add ( p . getPath ( ) ) ; } } protected void clearFilesList ( ) { fCache . clear ( new NullProgressMonitor ( ) ) ; fFileDirs . clear ( ) ; } protected void propagateAllMarkers ( ) { Set < String > file_list = fCache . getFileList ( ) ; for ( String path : file_list ) { if ( path != null ) { propagateMarkers ( path ) ; } } } protected void propagateMarkers ( String path ) { List < SVDBMarker > ml = fCache . getMarkers ( path ) ; getFileSystemProvider ( ) . clearMarkers ( path ) ; if ( ml != null ) { for ( SVDBMarker m : ml ) { String type = null ; switch ( m . getMarkerType ( ) ) { case Info : type = ISVDBFileSystemProvider . MARKER_TYPE_INFO ; break ; case Warning : type = ISVDBFileSystemProvider . MARKER_TYPE_WARNING ; break ; case Error : type = ISVDBFileSystemProvider . MARKER_TYPE_ERROR ; break ; } getFileSystemProvider ( ) . addMarker ( path , type , m . getLocation ( ) . getLine ( ) , m . getMessage ( ) ) ; } } } protected SVDBBaseIndexCacheData createIndexCacheData ( ) { return new SVDBBaseIndexCacheData ( getBaseLocation ( ) ) ; } protected abstract void discoverRootFiles ( List < IJob > jobs ) ; protected void preProcessFiles ( List < IJob > jobs ) { IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; final List < String > paths = new ArrayList < String > ( ) ; synchronized ( fCache ) { paths . addAll ( fCache . getFileList ( ) ) ; } for ( String path : paths ) { IJob job = job_mgr . createJob ( ) ; job . init ( path , new PreProcessFilesRunnable ( path ) ) ; synchronized ( jobs ) { jobs . add ( job ) ; } if ( fEnableThreads ) { job_mgr . queueJob ( job ) ; } } } private class PreProcessFilesRunnable implements Runnable { private String fPath ; public PreProcessFilesRunnable ( String path ) { fPath = path ; } public void run ( ) { long start = System . currentTimeMillis ( ) ; SVDBFile file = processPreProcFile ( fPath ) ; long end = System . currentTimeMillis ( ) ; synchronized ( fCache ) { fCache . setPreProcFile ( fPath , file ) ; fCache . setLastModified ( fPath , fFileSystemProvider . getLastModifiedTime ( fPath ) ) ; } } } protected void buildFileTree ( List < IJob > jobs , List < String > missing_includes ) { final List < String > paths = new ArrayList < String > ( ) ; IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; synchronized ( fCache ) { paths . addAll ( getCache ( ) . getFileList ( ) ) ; } fLog . debug ( LEVEL_MAX , "" ) ; for ( String path : paths ) { IJob job = job_mgr . createJob ( ) ; job . init ( path , new BuildFileTreeRunnable ( path , missing_includes ) ) ; synchronized ( jobs ) { jobs . add ( job ) ; } if ( fEnableThreads ) { job_mgr . queueJob ( job ) ; } } } private class BuildFileTreeRunnable implements Runnable { private String fPath ; private List < String > fMissingIncludes ; public BuildFileTreeRunnable ( String path , List < String > missing_inc ) { fPath = path ; fMissingIncludes = missing_inc ; } public void run ( ) { SVDBFileTree ft_root ; synchronized ( fCache ) { ft_root = fCache . getFileTree ( new NullProgressMonitor ( ) , fPath ) ; } if ( ft_root == null ) { SVDBFile pp_file ; synchronized ( fCache ) { pp_file = fCache . getPreProcFile ( new NullProgressMonitor ( ) , fPath ) ; } if ( pp_file == null ) { fLog . error ( "" + fPath + "" ) ; } else { long start = System . currentTimeMillis ( ) ; ft_root = new SVDBFileTree ( ( SVDBFile ) pp_file . duplicate ( ) ) ; Set < String > included_files = new HashSet < String > ( ) ; Map < String , SVDBFileTree > working_set = new HashMap < String , SVDBFileTree > ( ) ; buildPreProcFileMap ( null , ft_root , fMissingIncludes , included_files , working_set ) ; long end = System . currentTimeMillis ( ) ; } } } } private void buildPreProcFileMap ( SVDBFileTree parent , SVDBFileTree root , List < String > missing_includes , Set < String > included_files , Map < String , SVDBFileTree > working_set ) { SVDBFileTreeUtils ft_utils = new SVDBFileTreeUtils ( ) ; if ( fDebugEn ) { fLog . debug ( "" + root . getFilePath ( ) ) ; } if ( ! working_set . containsKey ( root . getFilePath ( ) ) ) { working_set . put ( root . getFilePath ( ) , root ) ; } synchronized ( fCache ) { if ( ! working_set . containsKey ( root . getFilePath ( ) ) ) { System . out . println ( "" + root . getFilePath ( ) + "" ) ; } fCache . setFileTree ( root . getFilePath ( ) , root ) ; } if ( parent != null ) { root . getIncludedByFiles ( ) . add ( parent . getFilePath ( ) ) ; } synchronized ( root ) { ft_utils . resolveConditionals ( root , new SVPreProcDefineProvider ( createPreProcMacroProvider ( root , working_set ) ) ) ; } List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; included_files . add ( root . getFilePath ( ) ) ; addPreProcFileIncludeFiles ( root , root . getSVDBFile ( ) , markers , missing_includes , included_files , working_set ) ; synchronized ( fCache ) { fCache . setFileTree ( root . getFilePath ( ) , root ) ; fCache . setMarkers ( root . getFilePath ( ) , markers ) ; } } private void addPreProcFileIncludeFiles ( SVDBFileTree root , ISVDBScopeItem scope , List < SVDBMarker > markers , List < String > missing_includes , Set < String > included_files , Map < String , SVDBFileTree > working_set ) { for ( int i = ; i < scope . getItems ( ) . size ( ) ; i ++ ) { ISVDBItemBase it = scope . getItems ( ) . get ( i ) ; if ( it . getType ( ) == SVDBItemType . Include ) { if ( fDebugEn ) { fLog . debug ( "" + ( ( ISVDBNamedItem ) it ) . getName ( ) ) ; } SVDBSearchResult < SVDBFile > f = findIncludedFileGlobal ( ( ( ISVDBNamedItem ) it ) . getName ( ) ) ; if ( f != null ) { if ( fDebugEn ) { fLog . debug ( "" + ( ( ISVDBNamedItem ) it ) . getName ( ) + "" + f . getIndex ( ) . getBaseLocation ( ) + "" ) ; } String file_path = f . getItem ( ) . getFilePath ( ) ; if ( fDebugEn ) { fLog . debug ( "" + file_path + "" + root . getFilePath ( ) + "" ) ; } SVDBFileTree ft = new SVDBFileTree ( ( SVDBFile ) f . getItem ( ) . duplicate ( ) ) ; root . addIncludedFile ( ft . getFilePath ( ) ) ; if ( fDebugEn ) { fLog . debug ( "" + ft . getIncludedFiles ( ) . size ( ) + "" ) ; } if ( ! included_files . contains ( f . getItem ( ) . getFilePath ( ) ) ) { buildPreProcFileMap ( root , ft , missing_includes , included_files , working_set ) ; } } else { String missing_path = ( ( ISVDBNamedItem ) it ) . getName ( ) ; if ( fDebugEn ) { fLog . debug ( "" + missing_path + "" + root . getFilePath ( ) + "" ) ; } synchronized ( missing_includes ) { if ( ! missing_includes . contains ( missing_path ) ) { missing_includes . add ( missing_path ) ; } } SVDBFileTree ft = new SVDBFileTree ( SVDBItem . getName ( it ) ) ; root . addIncludedFile ( ft . getFilePath ( ) ) ; ft . getIncludedByFiles ( ) . add ( root . getFilePath ( ) ) ; SVDBMarker err = new SVDBMarker ( MarkerType . Error , MarkerKind . MissingInclude , "" + ( ( ISVDBNamedItem ) it ) . getName ( ) + "" ) ; err . setLocation ( it . getLocation ( ) ) ; markers . add ( err ) ; } } else if ( it instanceof ISVDBScopeItem ) { addPreProcFileIncludeFiles ( root , ( ISVDBScopeItem ) it , markers , missing_includes , included_files , working_set ) ; } } } public SVDBSearchResult < SVDBFile > findIncludedFile ( String path ) { if ( fDebugEn ) { fLog . debug ( "" + path ) ; } for ( String inc_dir : fIndexCacheData . getIncludePaths ( ) ) { String inc_path = resolvePath ( inc_dir + "" + path , fInWorkspaceOk ) ; SVDBFile file = null ; if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" ) ; } if ( ( file = fCache . getPreProcFile ( new NullProgressMonitor ( ) , inc_path ) ) != null ) { if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" ) ; } } else { if ( fFileSystemProvider . fileExists ( inc_path ) ) { if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" ) ; } file = processPreProcFile ( inc_path ) ; addFile ( inc_path ) ; fCache . setPreProcFile ( inc_path , file ) ; fCache . setLastModified ( inc_path , fFileSystemProvider . getLastModifiedTime ( inc_path ) ) ; } else { if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" ) ; } } } if ( file != null ) { return new SVDBSearchResult < SVDBFile > ( file , this ) ; } } String res_path = resolvePath ( path , fInWorkspaceOk ) ; if ( fFileSystemProvider . fileExists ( res_path ) ) { SVDBFile pp_file = null ; if ( ( pp_file = processPreProcFile ( res_path ) ) != null ) { if ( fDebugEn ) { fLog . debug ( "" + path + "" ) ; } addFile ( res_path ) ; return new SVDBSearchResult < SVDBFile > ( pp_file , this ) ; } } return null ; } protected String resolvePath ( String path_orig , boolean in_workspace_ok ) { String path = path_orig ; String norm_path = null ; if ( fDebugEn ) { fLog . debug ( "" + path_orig ) ; } if ( path . startsWith ( "" ) ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } if ( ( norm_path = resolveRelativePath ( getResolvedBaseLocationDir ( ) , path ) ) == null ) { for ( String inc_path : fIndexCacheData . getIncludePaths ( ) ) { if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" + path ) ; } if ( ( norm_path = resolveRelativePath ( inc_path , path ) ) != null ) { break ; } } } else { if ( fDebugEn ) { fLog . debug ( "" + norm_path ) ; } } } else { if ( path . equals ( "" ) ) { path = getResolvedBaseLocationDir ( ) ; } else if ( path . startsWith ( "" ) ) { path = getResolvedBaseLocationDir ( ) + "" + path . substring ( ) ; } else { if ( ! fFileSystemProvider . fileExists ( path ) ) { String imp_path = getResolvedBaseLocationDir ( ) + "" + path ; if ( fFileSystemProvider . fileExists ( imp_path ) ) { path = imp_path ; } } } norm_path = normalizePath ( path ) ; } if ( norm_path != null && ! norm_path . startsWith ( "" ) && in_workspace_ok ) { IWorkspaceRoot ws_root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IFile file = ws_root . getFileForLocation ( new Path ( norm_path ) ) ; if ( file != null && file . exists ( ) ) { norm_path = "" + file . getFullPath ( ) . toOSString ( ) ; } } return ( norm_path != null ) ? norm_path : path_orig ; } private String resolveRelativePath ( String base , String path ) { String norm_path = normalizePath ( base + "" + path ) ; if ( fDebugEn ) { fLog . debug ( "" + norm_path + "" + getResolvedBaseLocationDir ( ) ) ; } if ( fFileSystemProvider . fileExists ( norm_path ) ) { return norm_path ; } else if ( getBaseLocation ( ) . startsWith ( "" ) ) { String base_loc = getResolvedBaseLocationDir ( ) ; if ( fDebugEn ) { fLog . debug ( "" + base_loc ) ; } base_loc = base_loc . substring ( "" . length ( ) ) ; if ( fDebugEn ) { fLog . debug ( "" + base_loc ) ; } IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IContainer base_dir = null ; try { base_dir = root . getFolder ( new Path ( base_loc ) ) ; } catch ( IllegalArgumentException e ) { } if ( base_dir == null ) { if ( base_loc . length ( ) > ) { base_dir = root . getProject ( base_loc . substring ( ) ) ; } } if ( fDebugEn ) { fLog . debug ( "" + base_dir ) ; } if ( base_dir != null && base_dir . exists ( ) ) { IPath base_dir_p = base_dir . getLocation ( ) ; if ( base_dir_p != null ) { File path_f_t = new File ( base_dir_p . toFile ( ) , path ) ; try { if ( path_f_t . exists ( ) ) { if ( fDebugEn ) { fLog . debug ( "" + path_f_t . getCanonicalPath ( ) ) ; } norm_path = SVFileUtils . normalize ( path_f_t . getCanonicalPath ( ) ) ; return norm_path ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } return null ; } protected String normalizePath ( String path ) { StringBuilder ret = new StringBuilder ( ) ; int i = path . length ( ) - ; int end ; int skipCnt = ; while ( i >= && ( path . charAt ( i ) == '' || path . charAt ( i ) == '' ) ) { i -- ; } while ( i >= ) { end = ret . length ( ) ; while ( i >= && path . charAt ( i ) != '' && path . charAt ( i ) != '' ) { ret . append ( path . charAt ( i ) ) ; i -- ; } if ( i != - ) { ret . append ( "" ) ; i -- ; } if ( ( ret . length ( ) - end ) > ) { String str = ret . substring ( end , ret . length ( ) - ) ; if ( str . equals ( "" ) ) { skipCnt ++ ; ret . setLength ( end ) ; } else if ( skipCnt > ) { ret . setLength ( end ) ; skipCnt -- ; } } } return ret . reverse ( ) . toString ( ) ; } public void setIncludeFileProvider ( ISVDBIncludeFileProvider provider ) { fIncludeFileProvider = provider ; } public void addChangeListener ( ISVDBIndexChangeListener l ) { synchronized ( fIndexChangeListeners ) { fIndexChangeListeners . add ( l ) ; } } public void removeChangeListener ( ISVDBIndexChangeListener l ) { synchronized ( fIndexChangeListeners ) { fIndexChangeListeners . remove ( l ) ; } } protected void notifyIndexRebuilt ( ) { synchronized ( fIndexChangeListeners ) { for ( ISVDBIndexChangeListener l : fIndexChangeListeners ) { l . index_rebuilt ( ) ; } } } public boolean isLoaded ( ) { return true ; } public boolean isFileListLoaded ( ) { return ( fIndexState >= IndexState_FileTreeValid ) ; } protected IPreProcMacroProvider createMacroProvider ( SVDBFileTree file_tree ) { SVFileTreeMacroProvider mp = new SVFileTreeMacroProvider ( fCache , file_tree , fMissingIncludes ) ; for ( Entry < String , String > entry : fIndexCacheData . getGlobalDefines ( ) . entrySet ( ) ) { mp . setMacro ( entry . getKey ( ) , entry . getValue ( ) ) ; } for ( Entry < String , String > entry : fIndexCacheData . getDefines ( ) . entrySet ( ) ) { mp . setMacro ( entry . getKey ( ) , entry . getValue ( ) ) ; } return mp ; } protected IPreProcMacroProvider createPreProcMacroProvider ( SVDBFileTree file , Map < String , SVDBFileTree > working_set ) { FileContextSearchMacroProvider mp = new FileContextSearchMacroProvider ( fCache , working_set ) ; mp . setFileContext ( file ) ; for ( Entry < String , String > entry : fIndexCacheData . getGlobalDefines ( ) . entrySet ( ) ) { mp . setMacro ( entry . getKey ( ) , entry . getValue ( ) ) ; } for ( Entry < String , String > entry : fIndexCacheData . getDefines ( ) . entrySet ( ) ) { mp . setMacro ( entry . getKey ( ) , entry . getValue ( ) ) ; } return mp ; } public SVDBSearchResult < SVDBFile > findIncludedFileGlobal ( String leaf ) { SVDBSearchResult < SVDBFile > ret = findIncludedFile ( leaf ) ; if ( ret == null ) { if ( fIncludeFileProvider != null ) { ret = fIncludeFileProvider . findIncludedFile ( leaf ) ; if ( fDebugEn ) { fLog . debug ( "" + leaf + "" + ret + "" ) ; } } else { if ( fDebugEn ) { fLog . debug ( "" ) ; } } } return ret ; } public Tuple < SVDBFile , SVDBFile > parse ( IProgressMonitor monitor , InputStream in , String path , List < SVDBMarker > markers ) { if ( markers == null ) { markers = new ArrayList < SVDBMarker > ( ) ; } SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( null ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( dp ) ; path = SVFileUtils . normalize ( path ) ; SVDBFileTree file_tree = findFileTree ( path ) ; if ( file_tree == null ) { if ( getFileSystemProvider ( ) . fileExists ( path ) ) { invalidateIndex ( "" + path , false ) ; addFile ( path ) ; file_tree = findFileTree ( path ) ; if ( file_tree == null && ! fAutoRebuildEn ) { file_tree = incrCreateFileTree ( path ) ; } } else { return null ; } } markers . clear ( ) ; List < SVDBMarker > markers_e = fCache . getMarkers ( path ) ; if ( markers_e != null ) { for ( SVDBMarker m : markers_e ) { if ( m . getKind ( ) == MarkerKind . MissingInclude ) { markers . add ( m ) ; } } } InputStreamCopier copier = new InputStreamCopier ( in ) ; in = null ; SVPreProcDirectiveScanner sc = new SVPreProcDirectiveScanner ( ) ; SVDBPreProcObserver ob = new SVDBPreProcObserver ( ) ; sc . setObserver ( ob ) ; file_tree = file_tree . duplicate ( ) ; sc . init ( copier . copy ( ) , path ) ; sc . process ( ) ; SVDBFile svdb_pp = ob . getFiles ( ) . get ( ) ; if ( fDebugEn ) { fLog . debug ( "" ) ; } file_tree . setSVDBFile ( svdb_pp ) ; if ( file_tree . getFilePath ( ) == null ) { System . out . println ( "" + path + "" ) ; } dp . setMacroProvider ( createMacroProvider ( file_tree ) ) ; SVDBFile svdb_f = factory . parse ( copier . copy ( ) , file_tree . getFilePath ( ) , markers ) ; if ( svdb_f . getFilePath ( ) == null ) { System . out . println ( "" + path + "" ) ; } return new Tuple < SVDBFile , SVDBFile > ( svdb_pp , svdb_f ) ; } public ISVDBItemIterator getItemIterator ( IProgressMonitor monitor ) { return new SVDBIndexItemIterator ( getFileList ( new NullProgressMonitor ( ) ) , this ) ; } public SVDBFile findFile ( String path ) { ensureIndexState ( new NullProgressMonitor ( ) , IndexState_FileTreeValid ) ; SVDBFile ret ; synchronized ( fCache ) { ret = fCache . getFile ( new NullProgressMonitor ( ) , path ) ; } if ( ret == null ) { SVDBFileTree ft_root ; synchronized ( fCache ) { ft_root = fCache . getFileTree ( new NullProgressMonitor ( ) , path ) ; } if ( ft_root != null ) { IPreProcMacroProvider mp = createMacroProvider ( ft_root ) ; processFile ( ft_root , mp ) ; synchronized ( fCache ) { ret = fCache . getFile ( new NullProgressMonitor ( ) , path ) ; } } else { try { throw new Exception ( ) ; } catch ( Exception e ) { fLog . error ( "" + path + "" , e ) ; for ( String p : getFileList ( new NullProgressMonitor ( ) ) ) { System . out . println ( "" + p ) ; } } } } if ( ret == null ) { try { throw new Exception ( "" + path + "" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return ret ; } protected void processFile ( SVDBFileTree path , IPreProcMacroProvider mp ) { SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( mp ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( dp ) ; fLog . debug ( LEVEL_MAX , "" + path . getFilePath ( ) ) ; String path_s = path . getFilePath ( ) ; InputStream in = fFileSystemProvider . openStream ( path_s ) ; if ( in == null ) { fLog . error ( "" + path_s + "" ) ; } BufferedInputStream in_b = new BufferedInputStream ( in ) ; List < SVDBMarker > markers = fCache . getMarkers ( path . getFilePath ( ) ) ; if ( markers == null ) { markers = new ArrayList < SVDBMarker > ( ) ; } for ( int i = ; i < markers . size ( ) ; i ++ ) { if ( markers . get ( i ) . getKind ( ) == MarkerKind . UndefinedMacro || markers . get ( i ) . getKind ( ) == MarkerKind . ParseError ) { markers . remove ( i ) ; i -- ; } } SVDBFile svdb_f = factory . parse ( in_b , path . getFilePath ( ) , markers ) ; if ( svdb_f == null ) { return ; } cacheDeclarations ( svdb_f ) ; fFileSystemProvider . clearMarkers ( path_s ) ; fCache . setFile ( path . getFilePath ( ) , svdb_f ) ; fCache . setLastModified ( path . getFilePath ( ) , fFileSystemProvider . getLastModifiedTime ( path . getFilePath ( ) ) ) ; fCache . setMarkers ( path . getFilePath ( ) , markers ) ; fFileSystemProvider . closeStream ( in ) ; propagateMarkers ( path . getFilePath ( ) ) ; } public synchronized SVDBFile findPreProcFile ( String path ) { ensureIndexState ( new NullProgressMonitor ( ) , IndexState_FileTreeValid ) ; return fCache . getPreProcFile ( new NullProgressMonitor ( ) , path ) ; } protected SVDBFile processPreProcFile ( String path ) { SVPreProcDirectiveScanner sc = new SVPreProcDirectiveScanner ( ) ; SVDBPreProcObserver ob = new SVDBPreProcObserver ( ) ; sc . setObserver ( ob ) ; fLog . debug ( "" + path ) ; InputStream in = fFileSystemProvider . openStream ( path ) ; if ( in == null ) { fLog . error ( getClass ( ) . getName ( ) + "" + path + "" ) ; return null ; } sc . init ( in , path ) ; sc . process ( ) ; getFileSystemProvider ( ) . closeStream ( in ) ; SVDBFile file = ob . getFiles ( ) . get ( ) ; return file ; } public synchronized SVDBFileTree findFileTree ( String path ) { ensureIndexState ( new NullProgressMonitor ( ) , IndexState_FileTreeValid ) ; SVDBFileTree ft = fCache . getFileTree ( new NullProgressMonitor ( ) , path ) ; return ft ; } protected SVDBFileTree incrCreateFileTree ( String path ) { SVDBFileTree ft = new SVDBFileTree ( path ) ; synchronized ( fCache ) { fCache . setFileTree ( path , ft ) ; } return ft ; } public void dispose ( ) { fLog . debug ( "" + getBaseLocation ( ) ) ; if ( fCache != null ) { fCache . sync ( ) ; } if ( fFileSystemProvider != null ) { fFileSystemProvider . dispose ( ) ; } } public List < SVDBDeclCacheItem > findGlobalScopeDecl ( IProgressMonitor monitor , String name , ISVDBFindNameMatcher matcher ) { List < SVDBDeclCacheItem > ret = new ArrayList < SVDBDeclCacheItem > ( ) ; Map < String , List < SVDBDeclCacheItem > > decl_cache = fIndexCacheData . getDeclCacheMap ( ) ; ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; for ( Entry < String , List < SVDBDeclCacheItem > > e : decl_cache . entrySet ( ) ) { for ( SVDBDeclCacheItem item : e . getValue ( ) ) { if ( matcher . match ( item , name ) ) { ret . add ( item ) ; } } } return ret ; } public List < SVDBRefCacheItem > findReferences ( IProgressMonitor monitor , String name , ISVDBRefMatcher matcher ) { List < SVDBRefCacheItem > ret = new ArrayList < SVDBRefCacheItem > ( ) ; Map < String , SVDBRefCacheEntry > ref_cache = fIndexCacheData . getReferenceCacheMap ( ) ; for ( Entry < String , SVDBRefCacheEntry > e : ref_cache . entrySet ( ) ) { matcher . find_matches ( ret , e . getValue ( ) , name ) ; } return ret ; } public Iterable < String > getFileNames ( IProgressMonitor monitor ) { return new Iterable < String > ( ) { public Iterator < String > iterator ( ) { return fCache . getFileList ( ) . iterator ( ) ; } } ; } protected void cacheDeclarations ( SVDBFile file ) { Map < String , List < SVDBDeclCacheItem > > decl_cache = fIndexCacheData . getDeclCacheMap ( ) ; if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" + file . getFilePath ( ) ) ; } if ( ! decl_cache . containsKey ( file . getFilePath ( ) ) ) { decl_cache . put ( file . getFilePath ( ) , new ArrayList < SVDBDeclCacheItem > ( ) ) ; } else { decl_cache . get ( file . getFilePath ( ) ) . clear ( ) ; } cacheDeclarations ( file . getFilePath ( ) , file , false ) ; } private void cacheDeclarations ( String filename , ISVDBChildParent scope , boolean is_ft ) { Map < String , List < SVDBDeclCacheItem > > decl_cache = fIndexCacheData . getDeclCacheMap ( ) ; List < SVDBDeclCacheItem > decl_list = decl_cache . get ( filename ) ; for ( ISVDBChildItem item : scope . getChildren ( ) ) { if ( item . getType ( ) . isElemOf ( SVDBItemType . PackageDecl ) ) { decl_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( SVDBPackageDecl ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; cacheDeclarations ( filename , ( SVDBPackageDecl ) item , is_ft ) ; } else if ( item . getType ( ) . isElemOf ( SVDBItemType . Function , SVDBItemType . Task , SVDBItemType . ClassDecl , SVDBItemType . ModuleDecl , SVDBItemType . InterfaceDecl , SVDBItemType . ProgramDecl , SVDBItemType . TypedefStmt ) ) { fLog . debug ( "" + item . getType ( ) + "" + ( ( ISVDBNamedItem ) item ) . getName ( ) + "" ) ; decl_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; } else if ( item . getType ( ) == SVDBItemType . PreProcCond ) { cacheDeclarations ( filename , ( SVDBPreProcCond ) item , is_ft ) ; } else if ( item . getType ( ) == SVDBItemType . MacroDef ) { decl_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; } } } public List < SVDBDeclCacheItem > findPackageDecl ( IProgressMonitor monitor , SVDBDeclCacheItem pkg_item ) { return null ; } public SVDBFile getDeclFile ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; return findFile ( item . getFilename ( ) ) ; } public SVDBFile getDeclFilePP ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; return findPreProcFile ( item . getFilename ( ) ) ; } public SVPreProcDirectiveScanner createPreProcScanner ( String path ) { path = SVFileUtils . normalize ( path ) ; InputStream in = getFileSystemProvider ( ) . openStream ( path ) ; SVDBFileTree ft = findFileTree ( path ) ; if ( ft == null ) { fLog . error ( "" + path + "" ) ; return null ; } IPreProcMacroProvider mp = createMacroProvider ( ft ) ; SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( mp ) ; SVPreProcDirectiveScanner pp = new SVPreProcDirectiveScanner ( ) ; pp . setDefineProvider ( dp ) ; pp . init ( in , path ) ; return pp ; } private void join ( IProgressMonitor m , List < IJob > jobs ) { synchronized ( jobs ) { for ( IJob j : jobs ) { if ( fEnableThreads ) { j . join ( ) ; } else { j . run ( new NullProgressMonitor ( ) ) ; } } } } } package net . sf . sveditor . core . db . index ; import java . util . List ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; public interface ISVDBChangeListener { void SVDBFileChanged ( SVDBFile file , List < SVDBItem > adds , List < SVDBItem > removes , List < SVDBItem > changes ) ; } package net . sf . sveditor . core . db . index ; import java . io . File ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBInclude ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBPreProcCond ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . scanner . IDefineProvider ; public class SVDBFileTreeUtils { private boolean fDebugEn = false ; private ISVDBIndex fIndex ; public SVDBFileTreeUtils ( ) { } public void setIndex ( ISVDBIndex index ) { fIndex = index ; } public void resolveConditionals ( SVDBFileTree file , IDefineProvider dp ) { processScope ( file . getSVDBFile ( ) , dp , file , null ) ; } private static SVDBFileTree findBestIncParent ( SVDBFileTree file , SVDBFileTree p1 , SVDBFileTree p2 ) { File file_dir = new File ( file . getFilePath ( ) ) . getParentFile ( ) ; File p1_dir = new File ( p1 . getFilePath ( ) ) . getParentFile ( ) ; File p2_dir = new File ( p2 . getFilePath ( ) ) . getParentFile ( ) ; if ( file_dir . equals ( p1_dir ) && ! file_dir . equals ( p2_dir ) ) { return p1 ; } else if ( file_dir . equals ( p2_dir ) && ! file_dir . equals ( p1_dir ) ) { return p2 ; } else { return p1 ; } } private void processFile ( IDefineProvider dp , SVDBFileTree file , List < SVDBFileTree > file_l ) { debug ( "" + file . getFilePath ( ) + "" ) ; file . setFileProcessed ( true ) ; processScope ( file . getSVDBFile ( ) , dp , file , file_l ) ; if ( fDebugEn ) { debug ( "" + file . getFilePath ( ) + "" ) ; for ( String f : file . getIncludedFiles ( ) ) { debug ( "" + f ) ; } for ( String f : file . getIncludedByFiles ( ) ) { debug ( "" + f ) ; } } debug ( "" + file . getFilePath ( ) + "" ) ; } private void processScope ( SVDBScopeItem scope , IDefineProvider dp , SVDBFileTree file , List < SVDBFileTree > file_l ) { List < ISVDBItemBase > it_l = scope . getItems ( ) ; debug ( "" + scope . getName ( ) ) ; for ( int i = ; i < it_l . size ( ) ; i ++ ) { ISVDBItemBase it = it_l . get ( i ) ; if ( it . getType ( ) == SVDBItemType . PreProcCond ) { SVDBPreProcCond c = ( SVDBPreProcCond ) it ; debug ( "" + c . getConditional ( ) ) ; debug ( "" + c . getName ( ) + "" + c . getConditional ( ) ) ; String cond = c . getConditional ( ) ; boolean defined = dp . isDefined ( cond , it . getLocation ( ) . getLine ( ) ) ; if ( ( defined && c . getName ( ) . equals ( "" ) ) || ( ! defined && c . getName ( ) . equals ( "" ) ) ) { while ( i + < it_l . size ( ) && it_l . get ( i + ) . getType ( ) == SVDBItemType . PreProcCond && ( ( ( ISVDBNamedItem ) it_l . get ( i + ) ) . getName ( ) . equals ( "" ) || ( ( ISVDBNamedItem ) it_l . get ( i + ) ) . getName ( ) . equals ( "" ) ) ) { debug ( "" ) ; it_l . remove ( i + ) ; } it_l . remove ( i ) ; if ( fDebugEn ) { debug ( "" + c . getName ( ) + "" ) ; for ( ISVDBItemBase it_t : c . getChildren ( ) ) { debug ( "" + it_t . getType ( ) + "" + ( ( ( it_t instanceof ISVDBNamedItem ) ) ? ( ( ISVDBNamedItem ) it_t ) . getName ( ) : "" ) ) ; } } it_l . addAll ( i , c . getItems ( ) ) ; i -- ; } else { boolean taken = false ; it_l . remove ( i ) ; while ( i < it_l . size ( ) && it_l . get ( i ) . getType ( ) == SVDBItemType . PreProcCond && ( ( ISVDBNamedItem ) it_l . get ( i ) ) . getName ( ) . equals ( "" ) ) { String elsif_cond = ( ( SVDBPreProcCond ) it_l . get ( i ) ) . getConditional ( ) ; taken = dp . isDefined ( elsif_cond , it . getLocation ( ) . getLine ( ) ) ; if ( taken ) { break ; } it_l . remove ( i ) ; } if ( taken ) { ISVDBItemBase it_t = it_l . get ( i ) ; it_l . remove ( i ) ; it_l . addAll ( i , ( ( SVDBPreProcCond ) it_t ) . getItems ( ) ) ; while ( i < it_l . size ( ) && it_l . get ( i + ) . getType ( ) == SVDBItemType . PreProcCond && ( ( ( ISVDBNamedItem ) it_l . get ( i ) ) . getName ( ) . equals ( "" ) || ( ( ISVDBNamedItem ) it_l . get ( i ) ) . getName ( ) . equals ( "" ) ) ) { it_l . remove ( i ) ; } } else { if ( i < it_l . size ( ) ) { ISVDBItemBase it_t = it_l . get ( i ) ; debug ( "" + SVDBItem . getName ( it_t ) ) ; if ( it_t . getType ( ) == SVDBItemType . PreProcCond && ( ( ISVDBNamedItem ) it_t ) . getName ( ) . equals ( "" ) ) { it_l . remove ( i ) ; if ( fDebugEn ) { debug ( "" ) ; for ( ISVDBItemBase it_tt : ( ( SVDBPreProcCond ) it_t ) . getChildren ( ) ) { debug ( "" + it_tt . getType ( ) + "" + ( ( it_tt instanceof ISVDBNamedItem ) ? ( ( ISVDBNamedItem ) it_tt ) . getName ( ) : "" ) ) ; } } it_l . addAll ( i , ( ( SVDBPreProcCond ) it_t ) . getItems ( ) ) ; } } } i -- ; } } else if ( it . getType ( ) == SVDBItemType . Include ) { SVDBInclude inc = ( SVDBInclude ) it ; debug ( "" + inc . getName ( ) ) ; if ( file_l == null ) { debug ( "" ) ; } if ( file_l != null ) { SVDBFileTree inc_file = findIncludedFile ( file , inc . getName ( ) , file_l ) ; if ( inc_file == null && fIndex != null ) { SVDBFile f = new SVDBIncludeSearch ( fIndex ) . findIncludedFile ( inc . getName ( ) ) ; if ( f != null ) { inc_file = new SVDBFileTree ( ( SVDBFile ) f . duplicate ( ) ) ; } } if ( inc_file == null ) { System . out . println ( "" + inc . getName ( ) + "" ) ; try { throw new Exception ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } else if ( ! file . getIncludedFiles ( ) . contains ( inc_file . getFilePath ( ) ) ) { debug ( "" + inc . getName ( ) + "" ) ; file . addIncludedFile ( inc_file . getFilePath ( ) ) ; if ( ! inc_file . getFileProcessed ( ) ) { processFile ( dp , inc_file , file_l ) ; } } else { debug ( "" + inc_file . getFilePath ( ) + "" ) ; } } } else if ( it . getType ( ) == SVDBItemType . PackageDecl ) { processScope ( ( SVDBScopeItem ) it , dp , file , file_l ) ; } } } private SVDBFileTree findIncludedFile ( SVDBFileTree file_t , String name , List < SVDBFileTree > file_l ) { SVDBFileTree inc_file = null ; boolean multi_inc = false ; for ( SVDBFileTree f : file_l ) { if ( f . getFilePath ( ) . endsWith ( name ) ) { if ( inc_file != null ) { System . out . println ( "" + "" + name + "" ) ; inc_file = findBestIncParent ( file_t , inc_file , f ) ; multi_inc = true ; } else { inc_file = f ; } } } if ( multi_inc ) { System . out . println ( "" + name + "" + file_t . getFilePath ( ) + "" + inc_file . getFilePath ( ) + "" ) ; } return inc_file ; } private void debug ( String msg ) { if ( fDebugEn ) { System . out . println ( msg ) ; } } } package net . sf . sveditor . core . db . index . cache ; import java . io . File ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ISVDBIndexCache { long numFilesRead ( ) ; void removeStoragePath ( List < File > db_path_list ) ; void setIndexData ( Object data ) ; Object getIndexData ( ) ; boolean init ( IProgressMonitor monitor , Object index_data ) ; void initLoad ( IProgressMonitor monitor ) ; void clear ( IProgressMonitor monitor ) ; Set < String > getFileList ( ) ; long getLastModified ( String path ) ; void setLastModified ( String path , long timestamp ) ; void addFile ( String path ) ; List < SVDBMarker > getMarkers ( String path ) ; void setMarkers ( String path , List < SVDBMarker > markers ) ; SVDBFile getPreProcFile ( IProgressMonitor monitor , String path ) ; void setPreProcFile ( String path , SVDBFile file ) ; SVDBFileTree getFileTree ( IProgressMonitor monitor , String path ) ; void setFileTree ( String path , SVDBFileTree file ) ; SVDBFile getFile ( IProgressMonitor monitor , String path ) ; void setFile ( String path , SVDBFile file ) ; void removeFile ( String path ) ; void sync ( ) ; } package net . sf . sveditor . core . db . index . cache ; import java . io . BufferedInputStream ; import java . io . BufferedOutputStream ; import java . io . DataInput ; import java . io . DataInputStream ; import java . io . DataOutput ; import java . io . DataOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . RandomAccessFile ; import java . util . List ; import java . util . Random ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . job_mgr . IJob ; import net . sf . sveditor . core . job_mgr . IJobMgr ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevelListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVDBDirFS implements ISVDBFS , ILogLevelListener { private File fDBDir ; private boolean fAsyncClear = false ; private boolean fDebugEn ; private LogHandle fLog ; public SVDBDirFS ( File root ) { fDBDir = root ; fLog = LogFactory . getLogHandle ( "" ) ; fLog . addLogLevelListener ( this ) ; fDebugEn = fLog . isEnabled ( ) ; } public void setEnableAsyncClear ( boolean en ) { fAsyncClear = en ; } public void logLevelChanged ( ILogHandle handle ) { fDebugEn = handle . isEnabled ( ) ; } public String getRoot ( ) { return fDBDir . getAbsolutePath ( ) ; } public void removeStoragePath ( List < File > db_file_list ) { db_file_list . remove ( fDBDir ) ; } public InputStream openFileRead ( String path ) { InputStream ret = null ; try { ret = new FileInputStream ( new File ( fDBDir , path ) ) ; } catch ( IOException e ) { } return ret ; } public RandomAccessFile openChannelRead ( String path ) { RandomAccessFile ret = null ; File target = new File ( fDBDir , path ) ; try { ret = new RandomAccessFile ( target , "" ) ; } catch ( IOException e ) { } return ret ; } public DataInput openDataInput ( String path ) { InputStream in = openFileRead ( path ) ; if ( in != null ) { BufferedInputStream bin = new BufferedInputStream ( in , * ) ; DataInputStream din = new DataInputStream ( bin ) ; return din ; } else { return null ; } } public void closeInput ( DataInput in ) { try { if ( in instanceof DataInputStream ) { ( ( DataInputStream ) in ) . close ( ) ; } } catch ( IOException e ) { } } public void closeChannel ( RandomAccessFile ch ) { try { ch . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } public OutputStream openFileWrite ( String path ) { OutputStream ret = null ; if ( ! fDBDir . exists ( ) ) { fDBDir . mkdirs ( ) ; } try { ret = new FileOutputStream ( new File ( fDBDir , path ) ) ; } catch ( IOException e ) { } return ret ; } public RandomAccessFile openChannelWrite ( String path ) { RandomAccessFile ret = null ; File target = new File ( fDBDir , path ) ; File target_p = target . getParentFile ( ) ; if ( ! target_p . exists ( ) ) { target_p . mkdirs ( ) ; } try { ret = new RandomAccessFile ( new File ( fDBDir , path ) , "" ) ; ret . setLength ( ) ; } catch ( IOException e ) { } return ret ; } public DataOutput openDataOutput ( String path ) { OutputStream out = openFileWrite ( path ) ; if ( out != null ) { BufferedOutputStream bos = new BufferedOutputStream ( out , * ) ; DataOutputStream dos = new DataOutputStream ( bos ) ; return dos ; } else { return null ; } } public void closeOutput ( DataOutput out ) { try { if ( out instanceof DataOutputStream ) { ( ( DataOutputStream ) out ) . close ( ) ; } } catch ( IOException e ) { } } public void close ( InputStream in ) { try { in . close ( ) ; } catch ( IOException e ) { } } public boolean fileExists ( String path ) { File file = new File ( fDBDir , path ) ; if ( file . exists ( ) ) { return true ; } else { return false ; } } public long lastModified ( String path ) { File file = new File ( fDBDir , path ) ; return file . lastModified ( ) ; } public void delete ( IProgressMonitor monitor , String path ) { if ( path . equals ( "" ) ) { if ( fDBDir . exists ( ) ) { if ( fAsyncClear ) { async_clear ( fDBDir ) ; } else { delete_tree ( monitor , fDBDir ) ; } } } else { File file = new File ( fDBDir , path ) ; debug ( "" + file . getAbsolutePath ( ) + "" ) ; if ( file . isDirectory ( ) ) { delete_tree ( new SubProgressMonitor ( monitor , ) , file ) ; } else if ( file . isFile ( ) ) { file . delete ( ) ; } } } public void mkdirs ( String path ) { File file = new File ( fDBDir , path ) ; if ( ! file . isDirectory ( ) ) { file . mkdirs ( ) ; } } private void async_clear ( File root ) { Random r = new Random ( System . currentTimeMillis ( ) ) ; final File newname = new File ( root . getParentFile ( ) , root . getName ( ) + "" + Math . abs ( r . nextInt ( ) ) ) ; if ( ! root . renameTo ( newname ) ) { fLog . debug ( LEVEL_MIN , "" ) ; delete_tree ( null , root ) ; return ; } if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" + newname . getAbsolutePath ( ) ) ; } IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; IJob job = job_mgr . createJob ( ) ; job . setPriority ( ) ; job . init ( "" , new Runnable ( ) { public void run ( ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" ) ; } delete_tree ( null , newname ) ; } } ) ; job_mgr . queueJob ( job ) ; } private void delete_tree ( IProgressMonitor monitor , File p ) { if ( p . isFile ( ) ) { p . delete ( ) ; } else { if ( p . exists ( ) ) { File file_l [ ] = p . listFiles ( ) ; if ( file_l != null ) { if ( monitor != null ) { monitor . beginTask ( "" , ) ; } for ( File f : file_l ) { if ( f . getName ( ) . equals ( "" ) || f . getName ( ) . equals ( "" ) ) { debug ( "" + f . getName ( ) ) ; continue ; } if ( f . isDirectory ( ) ) { delete_tree ( null , f ) ; } } if ( monitor != null ) { monitor . done ( ) ; } } file_l = p . listFiles ( ) ; if ( file_l != null ) { for ( File f : file_l ) { if ( f . getName ( ) . equals ( "" ) || f . getName ( ) . equals ( "" ) ) { debug ( "" + f . getName ( ) ) ; continue ; } if ( f . isFile ( ) ) { f . delete ( ) ; } } } p . delete ( ) ; } } } public void sync ( ) throws IOException { } private void debug ( String msg ) { } } package net . sf . sveditor . core . db . index . cache ; import java . util . List ; public interface ISVDBIndexCacheFactory { ISVDBIndexCache createIndexCache ( String project_name , String base_location ) ; void compactCache ( List < ISVDBIndexCache > cache_list ) ; } package net . sf . sveditor . core . db . index . cache ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . RandomAccessFile ; public class BufferedRandomAccessFileWriter extends RandomAccessFile { public BufferedRandomAccessFileWriter ( File path ) throws FileNotFoundException { super ( path , "" ) ; } } package net . sf . sveditor . core . db . index . cache ; import java . io . File ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import org . eclipse . core . runtime . IProgressMonitor ; public class InMemoryIndexCache implements ISVDBIndexCache { private Object fData ; private Set < String > fFileList ; private Map < String , Long > fLastModifiedMap ; private Map < String , SVDBFile > fPreProcFileMap ; private Map < String , SVDBFile > fFileMap ; private Map < String , SVDBFileTree > fFileTreeMap ; private Map < String , List < SVDBMarker > > fMarkerMap ; public InMemoryIndexCache ( ) { fFileList = new HashSet < String > ( ) ; fLastModifiedMap = new HashMap < String , Long > ( ) ; fPreProcFileMap = new HashMap < String , SVDBFile > ( ) ; fFileMap = new HashMap < String , SVDBFile > ( ) ; fFileTreeMap = new HashMap < String , SVDBFileTree > ( ) ; fMarkerMap = new HashMap < String , List < SVDBMarker > > ( ) ; } public long numFilesRead ( ) { return ; } public void removeStoragePath ( List < File > db_path_list ) { } public void setIndexData ( Object data ) { fData = data ; } public Object getIndexData ( ) { return fData ; } public boolean init ( IProgressMonitor monitor , Object index_data ) { fData = index_data ; return true ; } public void initLoad ( IProgressMonitor monitor ) { } public void clear ( IProgressMonitor monitor ) { monitor . beginTask ( "" , ) ; fFileList . clear ( ) ; fFileMap . clear ( ) ; fFileTreeMap . clear ( ) ; fLastModifiedMap . clear ( ) ; fPreProcFileMap . clear ( ) ; fMarkerMap . clear ( ) ; monitor . done ( ) ; } public Set < String > getFileList ( ) { return fFileList ; } public List < SVDBMarker > getMarkers ( String path ) { return fMarkerMap . get ( path ) ; } public void setMarkers ( String path , List < SVDBMarker > markers ) { if ( fMarkerMap . containsKey ( path ) ) { fMarkerMap . remove ( path ) ; } fMarkerMap . put ( path , markers ) ; } public long getLastModified ( String path ) { if ( fLastModifiedMap . containsKey ( path ) ) { return fLastModifiedMap . get ( path ) ; } else { return - ; } } public void setLastModified ( String path , long timestamp ) { if ( fLastModifiedMap . containsKey ( path ) ) { fLastModifiedMap . remove ( path ) ; } fLastModifiedMap . put ( path , timestamp ) ; } public void addFile ( String path ) { if ( ! fFileList . contains ( path ) ) { fFileList . add ( path ) ; } } public SVDBFile getPreProcFile ( IProgressMonitor monitor , String path ) { return fPreProcFileMap . get ( path ) ; } public void setPreProcFile ( String path , SVDBFile file ) { if ( fPreProcFileMap . containsKey ( path ) ) { fPreProcFileMap . remove ( path ) ; } fPreProcFileMap . put ( path , file ) ; } public SVDBFileTree getFileTree ( IProgressMonitor monitor , String path ) { return fFileTreeMap . get ( path ) ; } public void setFileTree ( String path , SVDBFileTree file ) { if ( fFileTreeMap . containsKey ( path ) ) { fFileTreeMap . remove ( path ) ; } fFileTreeMap . put ( path , file ) ; } public SVDBFile getFile ( IProgressMonitor monitor , String path ) { return fFileMap . get ( path ) ; } public void setFile ( String path , SVDBFile file ) { if ( fFileMap . containsKey ( path ) ) { fFileMap . remove ( path ) ; } fFileMap . put ( path , file ) ; } public void removeFile ( String path ) { fFileList . remove ( path ) ; fPreProcFileMap . remove ( path ) ; fFileMap . remove ( path ) ; fFileTreeMap . remove ( path ) ; } public void sync ( ) { } } package net . sf . sveditor . core . db . index . cache ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; public class SVDBFileFSRootBlock { private long fBlockSize ; private long fDirentPtr ; private long fBitmapPtr ; public SVDBFileFSRootBlock ( DataInput in ) throws IOException { fBlockSize = in . readLong ( ) ; fDirentPtr = in . readLong ( ) ; fBitmapPtr = in . readLong ( ) ; } public void sync ( DataOutput out ) throws IOException { out . writeLong ( fBlockSize ) ; out . writeLong ( fDirentPtr ) ; out . writeLong ( fBitmapPtr ) ; } } package net . sf . sveditor . core . db . index . cache ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . File ; import java . lang . ref . Reference ; import java . lang . ref . SoftReference ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . SVDBBaseIndexCacheData ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import net . sf . sveditor . core . db . persistence . DBFormatException ; import net . sf . sveditor . core . db . persistence . DBWriteException ; import net . sf . sveditor . core . db . persistence . IDBReader ; import net . sf . sveditor . core . db . persistence . IDBWriter ; import net . sf . sveditor . core . db . persistence . SVDBPersistenceRW ; import net . sf . sveditor . core . job_mgr . IJob ; import net . sf . sveditor . core . job_mgr . IJobMgr ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevelListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IProgressMonitor ; @ SuppressWarnings ( { "" , "" } ) public class SVDBThreadedFileIndexCache implements ISVDBIndexCache , ILogLevelListener { private String fBaseLocation ; private Map < String , CacheFileInfo > fFileCache ; private ISVDBFS fSVDBFS ; private Object fIndexData ; private LogHandle fLog ; private List < IDBReader > fPersistenceRdrSet ; private List < IDBWriter > fPersistenceWriterSet ; private long fNumFilesRead = ; private boolean fDebugEn = false ; private List < IJob > fWritebackJobs ; private int fMaxCacheSize = ; private static CacheFileInfo fCacheHead ; private static CacheFileInfo fCacheTail ; private static int fCacheSize ; private boolean fUseSoftRef = true ; final class CacheFileInfo { public boolean fCached ; public String fPath ; public CacheFileInfo fPrev ; public CacheFileInfo fNext ; public Reference < SVDBFile > fSVDBPreProcFile ; public SVDBFile fSVDBPreProcFileRef ; public Reference < SVDBFileTree > fSVDBFileTree ; public SVDBFileTree fSVDBFileTreeRef ; public Reference < SVDBFile > fSVDBFile ; public SVDBFile fSVDBFileRef ; public Reference < List < SVDBMarker > > fMarkers ; public List < SVDBMarker > fMarkersRef ; public long fLastModified ; public CacheFileInfo ( String path ) { fPath = path ; fSVDBPreProcFile = ( Reference < SVDBFile > ) createRef ( null ) ; fSVDBFileTree = ( Reference < SVDBFileTree > ) createRef ( null ) ; fSVDBFile = ( Reference < SVDBFile > ) createRef ( null ) ; fMarkers = ( Reference < List < SVDBMarker > > ) createRef ( null ) ; fLastModified = - ; } } public SVDBThreadedFileIndexCache ( ISVDBFS fs ) { fSVDBFS = fs ; fFileCache = new HashMap < String , SVDBThreadedFileIndexCache . CacheFileInfo > ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; fDebugEn = fLog . isEnabled ( ) ; fLog . addLogLevelListener ( this ) ; fPersistenceRdrSet = new ArrayList < IDBReader > ( ) ; fPersistenceWriterSet = new ArrayList < IDBWriter > ( ) ; fWritebackJobs = new ArrayList < IJob > ( ) ; } public void logLevelChanged ( ILogHandle handle ) { fDebugEn = handle . isEnabled ( ) ; } public long numFilesRead ( ) { return fNumFilesRead ; } public void removeStoragePath ( List < File > db_path_list ) { fSVDBFS . removeStoragePath ( db_path_list ) ; } public void setIndexData ( Object data ) { fIndexData = data ; } public Object getIndexData ( ) { return fIndexData ; } public boolean isValid ( ) { return true ; } public void clear ( IProgressMonitor monitor ) { monitor . beginTask ( "" , ) ; if ( fDebugEn ) { fLog . debug ( "" ) ; } fFileCache . clear ( ) ; fSVDBFS . delete ( monitor , "" ) ; monitor . done ( ) ; } public void addFile ( String path ) { getCacheFileInfo ( path , true ) ; } private CacheFileInfo getCacheFileInfo ( String path , boolean create ) { synchronized ( fFileCache ) { CacheFileInfo file = null ; if ( ! fFileCache . containsKey ( path ) ) { if ( create ) { file = new CacheFileInfo ( path ) ; fFileCache . put ( path , file ) ; } } else { file = fFileCache . get ( path ) ; } if ( file != null ) { if ( file . fCached ) { moveElementToTail ( file ) ; } else { addElementToTail ( file ) ; } } return file ; } } public void setMarkers ( String path , List < SVDBMarker > markers ) { CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fMarkers = ( Reference < List < SVDBMarker > > ) createRef ( markers ) ; cfi . fMarkersRef = markers ; } public List < SVDBMarker > getMarkers ( String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; List < SVDBMarker > m = ( cfi != null ) ? cfi . fMarkers . get ( ) : null ; if ( m == null ) { String parent_dir = computePathDir ( path ) ; String target_file = parent_dir + "" ; if ( fSVDBFS . fileExists ( target_file ) ) { cfi = getCacheFileInfo ( path , true ) ; m = readMarkerList ( target_file ) ; cfi . fMarkers = ( Reference < List < SVDBMarker > > ) createRef ( m ) ; cfi . fMarkersRef = m ; } } if ( m == null ) { m = new ArrayList < SVDBMarker > ( ) ; } return m ; } public boolean init ( IProgressMonitor monitor , Object index_data ) { boolean valid = false ; fFileCache . clear ( ) ; fBaseLocation = "" ; fIndexData = index_data ; IDBReader rdr = allocReader ( ) ; try { DataInput in = fSVDBFS . openDataInput ( "" ) ; if ( in != null ) { rdr . init ( in ) ; fBaseLocation = rdr . readString ( ) ; List < String > file_list = rdr . readStringList ( ) ; List < Long > timestamp_list = rdr . readLongList ( ) ; for ( int i = ; i < file_list . size ( ) ; i ++ ) { String path = file_list . get ( i ) ; CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fLastModified = timestamp_list . get ( i ) ; } fSVDBFS . closeInput ( in ) ; } in = fSVDBFS . openDataInput ( "" ) ; if ( in != null ) { rdr . init ( in ) ; rdr . readObject ( null , index_data . getClass ( ) , index_data ) ; debug ( "" + fSVDBFS . getRoot ( ) + "" + ( ( SVDBBaseIndexCacheData ) index_data ) . getBaseLocation ( ) ) ; fSVDBFS . closeInput ( in ) ; valid = true ; } else { debug ( "" ) ; } } catch ( DBFormatException e ) { e . printStackTrace ( ) ; } finally { freeReader ( rdr ) ; } return valid ; } public void initLoad ( IProgressMonitor monitor ) { } public Set < String > getFileList ( ) { return fFileCache . keySet ( ) ; } public long getLastModified ( String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; if ( cfi != null ) { return cfi . fLastModified ; } else { System . out . println ( "" + path + "" ) ; } return - ; } public void setLastModified ( String path , long timestamp ) { if ( timestamp == - ) { try { throw new Exception ( ) ; } catch ( Exception e ) { System . out . println ( "" ) ; e . printStackTrace ( ) ; } } CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fLastModified = timestamp ; } public SVDBFile getPreProcFile ( IProgressMonitor monitor , String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; SVDBFile pp_file = ( cfi != null ) ? cfi . fSVDBPreProcFile . get ( ) : null ; if ( pp_file == null ) { String target_dir = computePathDir ( path ) ; if ( fSVDBFS . fileExists ( target_dir + "" ) ) { cfi = getCacheFileInfo ( path , true ) ; DataInput in = fSVDBFS . openDataInput ( target_dir + "" ) ; pp_file = readFile ( in , path ) ; fSVDBFS . closeInput ( in ) ; cfi . fSVDBPreProcFile = ( Reference < SVDBFile > ) createRef ( pp_file ) ; cfi . fSVDBPreProcFileRef = pp_file ; } } return pp_file ; } public SVDBFile getFile ( IProgressMonitor monitor , String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; SVDBFile file = ( cfi != null ) ? cfi . fSVDBFile . get ( ) : null ; if ( file == null ) { String target_dir = computePathDir ( path ) ; if ( fSVDBFS . fileExists ( target_dir + "" ) ) { cfi = getCacheFileInfo ( path , true ) ; DataInput in = fSVDBFS . openDataInput ( target_dir + "" ) ; file = readFile ( in , path ) ; fSVDBFS . closeInput ( in ) ; cfi . fSVDBFile = ( Reference < SVDBFile > ) createRef ( file ) ; cfi . fSVDBFileRef = file ; fNumFilesRead ++ ; } else { debug ( "" + target_dir ) ; } } return file ; } public void setPreProcFile ( String path , SVDBFile file ) { if ( file == null ) { try { throw new Exception ( "" + path + "" ) ; } catch ( Exception e ) { fLog . error ( "" + path + "" , e ) ; } } CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fSVDBPreProcFile = ( Reference < SVDBFile > ) createRef ( file ) ; cfi . fSVDBPreProcFileRef = file ; } public void setFile ( String path , SVDBFile file ) { CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; if ( file == null ) { debug ( "" + path + "" ) ; cfi . fSVDBFile = new WeakReference < SVDBFile > ( null ) ; String target_dir = computePathDir ( path ) ; fSVDBFS . delete ( null , target_dir + "" ) ; } else { cfi . fSVDBFile = ( Reference < SVDBFile > ) createRef ( file ) ; cfi . fSVDBFileRef = file ; } } public void setFileTree ( String path , SVDBFileTree file_tree ) { CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fSVDBFileTree = ( Reference < SVDBFileTree > ) createRef ( file_tree ) ; cfi . fSVDBFileTreeRef = file_tree ; if ( path == null ) { System . out . println ( "" ) ; } } public SVDBFileTree getFileTree ( IProgressMonitor monitor , String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; SVDBFileTree ft = ( cfi != null ) ? cfi . fSVDBFileTree . get ( ) : null ; if ( ft == null ) { String target_dir = computePathDir ( path ) ; if ( fSVDBFS . fileExists ( target_dir + "" ) ) { cfi = getCacheFileInfo ( path , true ) ; DataInput in = fSVDBFS . openDataInput ( target_dir + "" ) ; ft = readFileTree ( in ) ; fSVDBFS . closeInput ( in ) ; cfi . fSVDBFileTree = ( Reference < SVDBFileTree > ) createRef ( ft ) ; cfi . fSVDBFileTreeRef = ft ; } else { fLog . debug ( "" + path + "" ) ; } } return ft ; } public void removeFile ( String path ) { CacheFileInfo file = fFileCache . get ( path ) ; fFileCache . remove ( path ) ; removeElement ( file ) ; String target_dir = computePathDir ( path ) ; fSVDBFS . delete ( null , target_dir ) ; } private String computePathDir ( String path ) { return SVFileUtils . computeMD5 ( path ) ; } private SVDBFile readFile ( DataInput in , String path ) { IDBReader reader = allocReader ( ) ; reader . init ( in ) ; SVDBFile ret = new SVDBFile ( ) ; try { reader . readObject ( null , ret . getClass ( ) , ret ) ; } catch ( DBFormatException e ) { e . printStackTrace ( ) ; } finally { freeReader ( reader ) ; } return ret ; } private SVDBFileTree readFileTree ( DataInput in ) { IDBReader reader = allocReader ( ) ; reader . init ( in ) ; SVDBFileTree ret = new SVDBFileTree ( ) ; try { reader . readObject ( null , ret . getClass ( ) , ret ) ; } catch ( DBFormatException e ) { e . printStackTrace ( ) ; } finally { freeReader ( reader ) ; } return ret ; } private List < SVDBMarker > readMarkerList ( String path ) { DataInput in = fSVDBFS . openDataInput ( path ) ; IDBReader reader = allocReader ( ) ; reader . init ( in ) ; List < SVDBMarker > ret = null ; try { ret = ( List < SVDBMarker > ) reader . readItemList ( null ) ; } catch ( DBFormatException e ) { e . printStackTrace ( ) ; } finally { freeReader ( reader ) ; } fSVDBFS . closeInput ( in ) ; return ret ; } public void sync ( ) { IDBWriter writer = allocWriter ( ) ; while ( fCacheHead != null ) { removeElement ( fCacheHead ) ; } while ( true ) { IJob j = null ; synchronized ( fWritebackJobs ) { if ( fWritebackJobs . size ( ) > ) { j = fWritebackJobs . remove ( ) ; } } if ( j == null ) { break ; } else { j . join ( ) ; } } try { DataOutput out = fSVDBFS . openDataOutput ( "" ) ; if ( out == null ) { throw new DBWriteException ( "" ) ; } writer . init ( out ) ; writer . writeString ( fBaseLocation ) ; List < String > tmp = new ArrayList < String > ( ) ; tmp . addAll ( fFileCache . keySet ( ) ) ; writer . writeStringList ( tmp ) ; List < Long > timestamp_list = new ArrayList < Long > ( ) ; for ( String path : fFileCache . keySet ( ) ) { CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; timestamp_list . add ( cfi . fLastModified ) ; } writer . writeLongList ( timestamp_list ) ; writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; out = fSVDBFS . openDataOutput ( "" ) ; writer . init ( out ) ; writer . writeObject ( fIndexData . getClass ( ) , fIndexData ) ; writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; } catch ( DBWriteException e ) { e . printStackTrace ( ) ; } finally { freeWriter ( writer ) ; } } private IDBReader allocReader ( ) { IDBReader reader = null ; synchronized ( fPersistenceRdrSet ) { if ( fPersistenceRdrSet . size ( ) > ) { reader = fPersistenceRdrSet . remove ( fPersistenceRdrSet . size ( ) - ) ; } } if ( reader == null ) { reader = new SVDBPersistenceRW ( ) ; } return reader ; } private void freeReader ( IDBReader reader ) { synchronized ( fPersistenceRdrSet ) { fPersistenceRdrSet . add ( reader ) ; } } private IDBWriter allocWriter ( ) { IDBWriter writer = null ; synchronized ( fPersistenceWriterSet ) { if ( fPersistenceWriterSet . size ( ) > ) { writer = fPersistenceWriterSet . remove ( fPersistenceWriterSet . size ( ) - ) ; } } if ( writer == null ) { writer = new SVDBPersistenceRW ( ) ; } return writer ; } private void freeWriter ( IDBWriter writer ) { synchronized ( fPersistenceWriterSet ) { fPersistenceWriterSet . add ( writer ) ; } } private void writeBackPreProcFile ( CacheFileInfo info , String path , SVDBFile file ) { String target_dir = computePathDir ( path ) ; String file_path = target_dir + "" ; IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; IJob job = job_mgr . createJob ( ) ; job . init ( "" , new WriteBackFileRunnable ( job , info , target_dir , file_path , file ) ) ; job . setPriority ( ) ; synchronized ( fWritebackJobs ) { fWritebackJobs . add ( job ) ; } job_mgr . queueJob ( job ) ; } private void writeBackFile ( CacheFileInfo info , String path , SVDBFile file ) { String target_dir = computePathDir ( path ) ; String file_path = target_dir + "" ; IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; IJob job = job_mgr . createJob ( ) ; job . init ( "" , new WriteBackFileRunnable ( job , info , target_dir , file_path , file ) ) ; job . setPriority ( ) ; synchronized ( fWritebackJobs ) { fWritebackJobs . add ( job ) ; } job_mgr . queueJob ( job ) ; } private void writeBackFileTree ( CacheFileInfo info , String path , SVDBFileTree file_tree ) { String target_dir = computePathDir ( path ) ; String file_path = target_dir + "" ; IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; IJob job = job_mgr . createJob ( ) ; job . init ( "" , new WriteBackFileTreeRunnable ( job , info , target_dir , file_path , file_tree ) ) ; job . setPriority ( ) ; synchronized ( fWritebackJobs ) { fWritebackJobs . add ( job ) ; } job_mgr . queueJob ( job ) ; } private void writeBackMarkerList ( CacheFileInfo info , String path , List < SVDBMarker > markers ) { String target_dir = computePathDir ( path ) ; String file_path = target_dir + "" ; IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; IJob job = job_mgr . createJob ( ) ; job . init ( "" , new WriteBackMarkerListRunnable ( job , info , target_dir , file_path , markers ) ) ; job . setPriority ( ) ; synchronized ( fWritebackJobs ) { fWritebackJobs . add ( job ) ; } job_mgr . queueJob ( job ) ; } private class WriteBackFileRunnable implements Runnable { private IJob fJob ; private CacheFileInfo fInfo ; private String fTargetDir ; private String fFilePath ; private SVDBFile fFile ; public WriteBackFileRunnable ( IJob job , CacheFileInfo info , String target_dir , String file_path , SVDBFile file ) { fJob = job ; fInfo = info ; fTargetDir = target_dir ; fFilePath = file_path ; fFile = file ; } public void run ( ) { IDBWriter writer = allocWriter ( ) ; fSVDBFS . mkdirs ( fTargetDir ) ; try { DataOutput out = fSVDBFS . openDataOutput ( fFilePath ) ; writer . init ( out ) ; writer . writeObject ( fFile . getClass ( ) , fFile ) ; writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; } catch ( DBWriteException e ) { e . printStackTrace ( ) ; } finally { freeWriter ( writer ) ; fInfo . fSVDBFileRef = null ; synchronized ( fWritebackJobs ) { fWritebackJobs . remove ( fJob ) ; } } } } private class WriteBackFileTreeRunnable implements Runnable { private IJob fJob ; private CacheFileInfo fInfo ; private String fTargetDir ; private String fFilePath ; private SVDBFileTree fFileTree ; public WriteBackFileTreeRunnable ( IJob job , CacheFileInfo info , String target_dir , String file_path , SVDBFileTree ft ) { fJob = job ; fInfo = info ; fTargetDir = target_dir ; fFilePath = file_path ; fFileTree = ft ; } public void run ( ) { fSVDBFS . mkdirs ( fTargetDir ) ; IDBWriter writer = allocWriter ( ) ; try { DataOutput out = fSVDBFS . openDataOutput ( fFilePath ) ; writer . init ( out ) ; synchronized ( fFileTree ) { writer . writeObject ( fFileTree . getClass ( ) , fFileTree ) ; } writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { freeWriter ( writer ) ; fInfo . fSVDBFileTreeRef = null ; synchronized ( fWritebackJobs ) { fWritebackJobs . remove ( fJob ) ; } } } } private class WriteBackMarkerListRunnable implements Runnable { private IJob fJob ; private CacheFileInfo fInfo ; private String fTargetDir ; private String fFilePath ; private List < SVDBMarker > fMarkers ; public WriteBackMarkerListRunnable ( IJob job , CacheFileInfo info , String target_dir , String file_path , List < SVDBMarker > markers ) { fJob = job ; fInfo = info ; fTargetDir = target_dir ; fFilePath = file_path ; fMarkers = markers ; } public void run ( ) { fSVDBFS . mkdirs ( fTargetDir ) ; IDBWriter writer = allocWriter ( ) ; try { DataOutput out = fSVDBFS . openDataOutput ( fFilePath ) ; writer . init ( out ) ; writer . writeItemList ( fMarkers ) ; writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; } catch ( DBWriteException e ) { e . printStackTrace ( ) ; } finally { freeWriter ( writer ) ; fInfo . fMarkersRef = null ; synchronized ( fWritebackJobs ) { fWritebackJobs . remove ( fJob ) ; } } } } private Reference createRef ( Object obj ) { if ( fUseSoftRef ) { return new SoftReference ( obj ) ; } else { return new WeakReference ( obj ) ; } } private void debug ( String msg ) { } private void addElementToTail ( CacheFileInfo info ) { synchronized ( SVDBThreadedFileIndexCache . class ) { info . fCached = true ; info . fSVDBFileRef = info . fSVDBFile . get ( ) ; info . fSVDBFileTreeRef = info . fSVDBFileTree . get ( ) ; info . fSVDBPreProcFileRef = info . fSVDBPreProcFile . get ( ) ; if ( fCacheHead == null ) { fCacheHead = info ; fCacheTail = info ; info . fPrev = null ; info . fNext = null ; } else { fCacheTail . fNext = info ; info . fPrev = fCacheTail ; fCacheTail = info ; info . fNext = null ; } fCacheSize ++ ; while ( fCacheSize > fMaxCacheSize ) { removeElement ( fCacheHead ) ; } } } private void moveElementToTail ( CacheFileInfo info ) { synchronized ( SVDBThreadedFileIndexCache . class ) { if ( fCacheTail != info ) { if ( info . fPrev == null ) { fCacheHead = info . fNext ; } else { info . fPrev . fNext = info . fNext ; } if ( info . fNext == null ) { fCacheTail = info . fPrev ; } else { info . fNext . fPrev = info . fPrev ; } if ( fCacheHead == null ) { fCacheHead = info ; fCacheTail = info ; info . fPrev = null ; info . fNext = null ; } else { fCacheTail . fNext = info ; info . fPrev = fCacheTail ; fCacheTail = info ; info . fNext = null ; } } } } private void removeElement ( CacheFileInfo info ) { synchronized ( SVDBThreadedFileIndexCache . class ) { if ( info . fPrev == null ) { fCacheHead = info . fNext ; } else { info . fPrev . fNext = info . fNext ; } if ( info . fNext == null ) { fCacheTail = info . fPrev ; } else { info . fNext . fPrev = info . fPrev ; } if ( info . fSVDBFileRef != null ) { writeBackFile ( info , info . fPath , info . fSVDBFileRef ) ; } if ( info . fSVDBFileTreeRef != null ) { writeBackFileTree ( info , info . fPath , info . fSVDBFileTreeRef ) ; } if ( info . fSVDBPreProcFileRef != null ) { writeBackPreProcFile ( info , info . fPath , info . fSVDBPreProcFileRef ) ; } if ( info . fMarkers != null ) { writeBackMarkerList ( info , info . fPath , info . fMarkersRef ) ; } info . fCached = false ; fCacheSize -- ; } } } package net . sf . sveditor . core . db . index . cache ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . RandomAccessFile ; import java . nio . ByteBuffer ; import java . nio . channels . FileChannel ; import java . nio . channels . FileChannel . MapMode ; public class MappedByteBufferInputStream extends InputStream { private RandomAccessFile fIn ; private ByteBuffer fByteBuffer ; private int fBufferIdx ; private byte fTmp [ ] = new byte [ ] ; public MappedByteBufferInputStream ( File path ) throws IOException { fIn = new RandomAccessFile ( path , "" ) ; FileChannel channel = fIn . getChannel ( ) ; fByteBuffer = channel . map ( MapMode . READ_ONLY , , channel . size ( ) ) ; fBufferIdx = ; } @ Override public int available ( ) throws IOException { return ( fByteBuffer . limit ( ) - fBufferIdx ) ; } @ Override public void close ( ) throws IOException { fIn . close ( ) ; } @ Override public boolean markSupported ( ) { return false ; } @ Override public int read ( ) throws IOException { int ret = read ( fTmp , , ) ; if ( ret <= ) { return - ; } else { return fTmp [ ] ; } } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { int ret = - ; if ( fByteBuffer . remaining ( ) > ) { ret = ( fByteBuffer . remaining ( ) >= len ) ? len : fByteBuffer . remaining ( ) ; fByteBuffer . get ( b , off , ret ) ; System . out . println ( "" + ret + "" ) ; } return ret ; } @ Override public int read ( byte [ ] b ) throws IOException { return read ( b , , b . length ) ; } } package net . sf . sveditor . core . db . index . cache ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . File ; import java . lang . ref . Reference ; import java . lang . ref . SoftReference ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . SVDBBaseIndexCacheData ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import net . sf . sveditor . core . db . persistence . DBFormatException ; import net . sf . sveditor . core . db . persistence . DBWriteException ; import net . sf . sveditor . core . db . persistence . IDBReader ; import net . sf . sveditor . core . db . persistence . IDBWriter ; import net . sf . sveditor . core . db . persistence . SVDBPersistenceRW ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevelListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IProgressMonitor ; @ SuppressWarnings ( { "" , "" } ) public class SVDBFileIndexCache implements ISVDBIndexCache , ILogLevelListener { private String fBaseLocation ; private Map < String , CacheFileInfo > fFileCache ; private ISVDBFS fSVDBFS ; private Object fIndexData ; private LogHandle fLog ; private List < IDBReader > fPersistenceRdrSet ; private List < IDBWriter > fPersistenceWriterSet ; private long fNumFilesRead = ; private boolean fDebugEn = false ; private int fMaxCacheSize = ; private static CacheFileInfo fCacheHead ; private static CacheFileInfo fCacheTail ; private static int fCacheSize ; private boolean fUseSoftRef = true ; final class CacheFileInfo { public boolean fCached ; public CacheFileInfo fPrev ; public CacheFileInfo fNext ; public Reference < SVDBFile > fSVDBPreProcFile ; public SVDBFile fSVDBPreProcFileRef ; public Reference < SVDBFileTree > fSVDBFileTree ; public SVDBFileTree fSVDBFileTreeRef ; public Reference < SVDBFile > fSVDBFile ; public SVDBFile fSVDBFileRef ; public Reference < List < SVDBMarker > > fMarkers ; public List < SVDBMarker > fMarkersRef ; public long fLastModified ; public CacheFileInfo ( ) { fSVDBPreProcFile = ( Reference < SVDBFile > ) createRef ( null ) ; fSVDBFileTree = ( Reference < SVDBFileTree > ) createRef ( null ) ; fSVDBFile = ( Reference < SVDBFile > ) createRef ( null ) ; fMarkers = ( Reference < List < SVDBMarker > > ) createRef ( null ) ; fLastModified = - ; } } final class WriteBackInfo { public static final int SVDB_FILE = , SVDB_FILE_TREE = , MARKERS = ; public int fType ; public SVDBFile fFile ; public SVDBFileTree fFileTree ; public List < SVDBMarker > fMarkers ; public String fFilePath ; public String fTargetDir ; public WriteBackInfo ( String target_dir , String file_path , SVDBFile file ) { fTargetDir = target_dir ; fFilePath = file_path ; fFile = file ; fType = SVDB_FILE ; } public WriteBackInfo ( String target_dir , String file_path , SVDBFileTree file ) { fTargetDir = target_dir ; fFilePath = file_path ; fFileTree = file ; fType = SVDB_FILE_TREE ; } public WriteBackInfo ( String target_dir , String file_path , List < SVDBMarker > markers ) { fTargetDir = target_dir ; fFilePath = file_path ; fMarkers = markers ; fType = MARKERS ; } } public SVDBFileIndexCache ( ISVDBFS fs ) { fSVDBFS = fs ; fFileCache = new HashMap < String , SVDBFileIndexCache . CacheFileInfo > ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; fDebugEn = fLog . isEnabled ( ) ; fLog . addLogLevelListener ( this ) ; fPersistenceRdrSet = new ArrayList < IDBReader > ( ) ; fPersistenceWriterSet = new ArrayList < IDBWriter > ( ) ; } public void logLevelChanged ( ILogHandle handle ) { fDebugEn = handle . isEnabled ( ) ; } public long numFilesRead ( ) { return fNumFilesRead ; } public void removeStoragePath ( List < File > db_path_list ) { fSVDBFS . removeStoragePath ( db_path_list ) ; } public void setIndexData ( Object data ) { fIndexData = data ; } public Object getIndexData ( ) { return fIndexData ; } public boolean isValid ( ) { return true ; } public void clear ( IProgressMonitor monitor ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" ) ; } monitor . beginTask ( "" , ) ; fFileCache . clear ( ) ; fSVDBFS . delete ( monitor , "" ) ; monitor . done ( ) ; } public void addFile ( String path ) { getCacheFileInfo ( path , true ) ; } private CacheFileInfo getCacheFileInfo ( String path , boolean create ) { synchronized ( fFileCache ) { CacheFileInfo file = null ; if ( ! fFileCache . containsKey ( path ) ) { if ( create ) { file = new CacheFileInfo ( ) ; fFileCache . put ( path , file ) ; } } else { file = fFileCache . get ( path ) ; } if ( file != null ) { if ( file . fCached ) { moveElementToTail ( file ) ; } else { addElementToTail ( file ) ; } } return file ; } } public void setMarkers ( String path , List < SVDBMarker > markers ) { CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fMarkers = ( Reference < List < SVDBMarker > > ) createRef ( markers ) ; cfi . fMarkersRef = markers ; writeBackMarkerList ( path , markers ) ; } public List < SVDBMarker > getMarkers ( String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; List < SVDBMarker > m = ( cfi != null ) ? cfi . fMarkers . get ( ) : null ; if ( m == null ) { String parent_dir = computePathDir ( path ) ; String target_file = parent_dir + "" ; if ( fSVDBFS . fileExists ( target_file ) ) { cfi = getCacheFileInfo ( path , true ) ; m = readMarkerList ( target_file ) ; cfi . fMarkers = ( Reference < List < SVDBMarker > > ) createRef ( m ) ; cfi . fMarkersRef = m ; } } if ( m == null ) { m = new ArrayList < SVDBMarker > ( ) ; } return m ; } public boolean init ( IProgressMonitor monitor , Object index_data ) { boolean valid = false ; fFileCache . clear ( ) ; fBaseLocation = "" ; fIndexData = index_data ; IDBReader rdr = allocReader ( ) ; try { DataInput in = fSVDBFS . openDataInput ( "" ) ; if ( in != null ) { rdr . init ( in ) ; fBaseLocation = rdr . readString ( ) ; List < String > file_list = rdr . readStringList ( ) ; List < Long > timestamp_list = rdr . readLongList ( ) ; for ( int i = ; i < file_list . size ( ) ; i ++ ) { String path = file_list . get ( i ) ; CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fLastModified = timestamp_list . get ( i ) ; } fSVDBFS . closeInput ( in ) ; } in = fSVDBFS . openDataInput ( "" ) ; if ( in != null ) { rdr . init ( in ) ; rdr . readObject ( null , index_data . getClass ( ) , index_data ) ; if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + fSVDBFS . getRoot ( ) + "" + ( ( SVDBBaseIndexCacheData ) index_data ) . getBaseLocation ( ) ) ; } fSVDBFS . closeInput ( in ) ; valid = true ; } else { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" ) ; } } } catch ( DBFormatException e ) { e . printStackTrace ( ) ; } finally { freeReader ( rdr ) ; } return valid ; } public void initLoad ( IProgressMonitor monitor ) { } public Set < String > getFileList ( ) { return fFileCache . keySet ( ) ; } public long getLastModified ( String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; if ( cfi != null ) { return cfi . fLastModified ; } else { System . out . println ( "" + path + "" ) ; } return - ; } public void setLastModified ( String path , long timestamp ) { if ( timestamp == - ) { try { throw new Exception ( ) ; } catch ( Exception e ) { System . out . println ( "" ) ; e . printStackTrace ( ) ; } } CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fLastModified = timestamp ; } public SVDBFile getPreProcFile ( IProgressMonitor monitor , String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; SVDBFile pp_file = ( cfi != null ) ? cfi . fSVDBPreProcFile . get ( ) : null ; if ( pp_file == null ) { String target_dir = computePathDir ( path ) ; if ( fSVDBFS . fileExists ( target_dir + "" ) ) { cfi = getCacheFileInfo ( path , true ) ; DataInput in = fSVDBFS . openDataInput ( target_dir + "" ) ; pp_file = readFile ( in , path ) ; fSVDBFS . closeInput ( in ) ; cfi . fSVDBPreProcFile = ( Reference < SVDBFile > ) createRef ( pp_file ) ; cfi . fSVDBPreProcFileRef = pp_file ; } } return pp_file ; } public SVDBFile getFile ( IProgressMonitor monitor , String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; SVDBFile file = ( cfi != null ) ? cfi . fSVDBFile . get ( ) : null ; if ( file == null ) { String target_dir = computePathDir ( path ) ; if ( fSVDBFS . fileExists ( target_dir + "" ) ) { cfi = getCacheFileInfo ( path , true ) ; DataInput in = fSVDBFS . openDataInput ( target_dir + "" ) ; file = readFile ( in , path ) ; fSVDBFS . closeInput ( in ) ; cfi . fSVDBFile = ( Reference < SVDBFile > ) createRef ( file ) ; cfi . fSVDBFileRef = file ; fNumFilesRead ++ ; } } return file ; } public void setPreProcFile ( String path , SVDBFile file ) { if ( file == null ) { try { throw new Exception ( "" + path + "" ) ; } catch ( Exception e ) { fLog . error ( "" + path + "" , e ) ; } } CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fSVDBPreProcFile = ( Reference < SVDBFile > ) createRef ( file ) ; cfi . fSVDBPreProcFileRef = file ; writeBackPreProcFile ( path , file ) ; } public void setFile ( String path , SVDBFile file ) { CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; if ( file == null ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MAX , "" + path + "" ) ; } cfi . fSVDBFile = new WeakReference < SVDBFile > ( null ) ; String target_dir = computePathDir ( path ) ; fSVDBFS . delete ( null , target_dir + "" ) ; } else { cfi . fSVDBFile = ( Reference < SVDBFile > ) createRef ( file ) ; cfi . fSVDBFileRef = file ; writeBackFile ( path , file ) ; } } public void setFileTree ( String path , SVDBFileTree file_tree ) { CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; cfi . fSVDBFileTree = ( Reference < SVDBFileTree > ) createRef ( file_tree ) ; cfi . fSVDBFileTreeRef = file_tree ; if ( path == null ) { System . out . println ( "" ) ; } writeBackFileTree ( path , file_tree ) ; } public SVDBFileTree getFileTree ( IProgressMonitor monitor , String path ) { CacheFileInfo cfi = getCacheFileInfo ( path , false ) ; SVDBFileTree ft = ( cfi != null ) ? cfi . fSVDBFileTree . get ( ) : null ; if ( ft == null ) { String target_dir = computePathDir ( path ) ; if ( fSVDBFS . fileExists ( target_dir + "" ) ) { cfi = getCacheFileInfo ( path , true ) ; DataInput in = fSVDBFS . openDataInput ( target_dir + "" ) ; ft = readFileTree ( in ) ; fSVDBFS . closeInput ( in ) ; cfi . fSVDBFileTree = ( Reference < SVDBFileTree > ) createRef ( ft ) ; cfi . fSVDBFileTreeRef = ft ; } } return ft ; } public void removeFile ( String path ) { CacheFileInfo file = fFileCache . get ( path ) ; fFileCache . remove ( path ) ; removeElement ( file ) ; String target_dir = computePathDir ( path ) ; fSVDBFS . delete ( null , target_dir ) ; } private String computePathDir ( String path ) { return SVFileUtils . computeMD5 ( path ) ; } private SVDBFile readFile ( DataInput in , String path ) { IDBReader reader = allocReader ( ) ; reader . init ( in ) ; SVDBFile ret = new SVDBFile ( ) ; try { reader . readObject ( null , ret . getClass ( ) , ret ) ; } catch ( DBFormatException e ) { e . printStackTrace ( ) ; } finally { freeReader ( reader ) ; } return ret ; } private SVDBFileTree readFileTree ( DataInput in ) { IDBReader reader = allocReader ( ) ; reader . init ( in ) ; SVDBFileTree ret = new SVDBFileTree ( ) ; try { reader . readObject ( null , ret . getClass ( ) , ret ) ; } catch ( DBFormatException e ) { e . printStackTrace ( ) ; } finally { freeReader ( reader ) ; } return ret ; } private List < SVDBMarker > readMarkerList ( String path ) { DataInput in = fSVDBFS . openDataInput ( path ) ; IDBReader reader = allocReader ( ) ; reader . init ( in ) ; List < SVDBMarker > ret = null ; try { ret = ( List < SVDBMarker > ) reader . readItemList ( null ) ; } catch ( DBFormatException e ) { e . printStackTrace ( ) ; } finally { freeReader ( reader ) ; } fSVDBFS . closeInput ( in ) ; return ret ; } public void sync ( ) { IDBWriter writer = allocWriter ( ) ; try { DataOutput out = fSVDBFS . openDataOutput ( "" ) ; if ( out == null ) { throw new DBWriteException ( "" ) ; } writer . init ( out ) ; writer . writeString ( fBaseLocation ) ; List < String > tmp = new ArrayList < String > ( ) ; tmp . addAll ( fFileCache . keySet ( ) ) ; writer . writeStringList ( tmp ) ; List < Long > timestamp_list = new ArrayList < Long > ( ) ; for ( String path : fFileCache . keySet ( ) ) { CacheFileInfo cfi = getCacheFileInfo ( path , true ) ; timestamp_list . add ( cfi . fLastModified ) ; } writer . writeLongList ( timestamp_list ) ; writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; out = fSVDBFS . openDataOutput ( "" ) ; writer . init ( out ) ; writer . writeObject ( fIndexData . getClass ( ) , fIndexData ) ; writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; } catch ( DBWriteException e ) { e . printStackTrace ( ) ; } finally { freeWriter ( writer ) ; } } private IDBReader allocReader ( ) { IDBReader reader = null ; synchronized ( fPersistenceRdrSet ) { if ( fPersistenceRdrSet . size ( ) > ) { reader = fPersistenceRdrSet . remove ( fPersistenceRdrSet . size ( ) - ) ; } } if ( reader == null ) { reader = new SVDBPersistenceRW ( ) ; } return reader ; } private void freeReader ( IDBReader reader ) { synchronized ( fPersistenceRdrSet ) { fPersistenceRdrSet . add ( reader ) ; } } private IDBWriter allocWriter ( ) { IDBWriter writer = null ; synchronized ( fPersistenceWriterSet ) { if ( fPersistenceWriterSet . size ( ) > ) { writer = fPersistenceWriterSet . remove ( fPersistenceWriterSet . size ( ) - ) ; } } if ( writer == null ) { writer = new SVDBPersistenceRW ( ) ; } return writer ; } private void freeWriter ( IDBWriter writer ) { synchronized ( fPersistenceWriterSet ) { fPersistenceWriterSet . add ( writer ) ; } } private void writeBackPreProcFile ( String path , SVDBFile file ) { String target_dir = computePathDir ( path ) ; String file_path = target_dir + "" ; writeBackFileWorker ( target_dir , file_path , file ) ; } private void writeBackFile ( String path , SVDBFile file ) { String target_dir = computePathDir ( path ) ; String file_path = target_dir + "" ; writeBackFileWorker ( target_dir , file_path , file ) ; } private void writeBackFileTree ( String path , SVDBFileTree file_tree ) { String target_dir = computePathDir ( path ) ; String file_path = target_dir + "" ; writeBackFileTreeWorker ( target_dir , file_path , file_tree ) ; } private void writeBackMarkerList ( String path , List < SVDBMarker > markers ) { String target_dir = computePathDir ( path ) ; String file_path = target_dir + "" ; writeBackMarkerListWorker ( target_dir , file_path , markers ) ; } private void writeBackFileWorker ( String target_dir , String file_path , SVDBFile file ) { IDBWriter writer = allocWriter ( ) ; fSVDBFS . mkdirs ( target_dir ) ; try { DataOutput out = fSVDBFS . openDataOutput ( file_path ) ; writer . init ( out ) ; writer . writeObject ( file . getClass ( ) , file ) ; writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; } catch ( DBWriteException e ) { e . printStackTrace ( ) ; } finally { freeWriter ( writer ) ; } } private void writeBackFileTreeWorker ( String target_dir , String file_path , SVDBFileTree file_tree ) { fSVDBFS . mkdirs ( target_dir ) ; IDBWriter writer = allocWriter ( ) ; try { DataOutput out = fSVDBFS . openDataOutput ( file_path ) ; writer . init ( out ) ; synchronized ( file_tree ) { writer . writeObject ( file_tree . getClass ( ) , file_tree ) ; } writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { freeWriter ( writer ) ; } } private void writeBackMarkerListWorker ( String target_dir , String file_path , List < SVDBMarker > markers ) { fSVDBFS . mkdirs ( target_dir ) ; IDBWriter writer = allocWriter ( ) ; try { DataOutput out = fSVDBFS . openDataOutput ( file_path ) ; writer . init ( out ) ; writer . writeItemList ( markers ) ; writer . close ( ) ; fSVDBFS . closeOutput ( out ) ; } catch ( DBWriteException e ) { e . printStackTrace ( ) ; } finally { freeWriter ( writer ) ; } } private Reference createRef ( Object obj ) { if ( fUseSoftRef ) { return new SoftReference ( obj ) ; } else { return new WeakReference ( obj ) ; } } private void addElementToTail ( CacheFileInfo info ) { synchronized ( SVDBFileIndexCache . class ) { info . fCached = true ; info . fSVDBFileRef = info . fSVDBFile . get ( ) ; info . fSVDBFileTreeRef = info . fSVDBFileTree . get ( ) ; info . fSVDBPreProcFileRef = info . fSVDBPreProcFile . get ( ) ; if ( fCacheHead == null ) { fCacheHead = info ; fCacheTail = info ; info . fPrev = null ; info . fNext = null ; } else { fCacheTail . fNext = info ; info . fPrev = fCacheTail ; fCacheTail = info ; info . fNext = null ; } fCacheSize ++ ; while ( fCacheSize > fMaxCacheSize ) { removeElement ( fCacheHead ) ; } } } private void moveElementToTail ( CacheFileInfo info ) { synchronized ( SVDBFileIndexCache . class ) { if ( fCacheTail != info ) { if ( info . fPrev == null ) { fCacheHead = info . fNext ; } else { info . fPrev . fNext = info . fNext ; } if ( info . fNext == null ) { fCacheTail = info . fPrev ; } else { info . fNext . fPrev = info . fPrev ; } if ( fCacheHead == null ) { fCacheHead = info ; fCacheTail = info ; info . fPrev = null ; info . fNext = null ; } else { fCacheTail . fNext = info ; info . fPrev = fCacheTail ; fCacheTail = info ; info . fNext = null ; } } } } private void removeElement ( CacheFileInfo info ) { synchronized ( SVDBFileIndexCache . class ) { if ( info . fPrev == null ) { fCacheHead = info . fNext ; } else { info . fPrev . fNext = info . fNext ; } if ( info . fNext == null ) { fCacheTail = info . fPrev ; } else { info . fNext . fPrev = info . fPrev ; } info . fSVDBFileRef = null ; info . fSVDBFileTreeRef = null ; info . fSVDBPreProcFileRef = null ; info . fCached = false ; fCacheSize -- ; } } } package net . sf . sveditor . core . db . index . cache ; import java . io . IOException ; import java . io . OutputStream ; public class MappedByteBufferOutputStream extends OutputStream { @ Override public void write ( int b ) throws IOException { } } package net . sf . sveditor . core . db . index . cache ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . RandomAccessFile ; import java . nio . MappedByteBuffer ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBFileFS implements ISVDBFS { private RandomAccessFile fStorage ; private class Block { protected long fBlockPtr ; private long fNextBlockPtr ; public Block ( long ptr ) { fBlockPtr = ptr ; } public long getNextBlock ( ) { return fNextBlockPtr ; } public void setNextBlock ( long next ) { fNextBlockPtr = next ; } Block ( DataInput in ) throws IOException { fNextBlockPtr = in . readLong ( ) ; } } private class RootBlock { private long fDirentPtr ; private long fBitmapPtr ; } private class Dirent extends Block { Dirent ( DataInput in ) throws IOException { super ( in ) ; } } private class FileEntry { } private class BlockBitmap { private MappedByteBuffer fBlock ; BlockBitmap ( MappedByteBuffer block ) { fBlock = block ; } } private List < BlockBitmap > fBlockBitmapList ; public SVDBFileFS ( ) { RandomAccessFile f ; } public String getRoot ( ) { return "" ; } public void removeStoragePath ( List < File > db_file_list ) { } public InputStream openFileRead ( String path ) throws IOException { return null ; } public RandomAccessFile openChannelRead ( String path ) { return null ; } public RandomAccessFile openChannelWrite ( String path ) { return null ; } public void closeChannel ( RandomAccessFile ch ) { } public void close ( InputStream in ) { } public long lastModified ( String path ) { return ; } public OutputStream openFileWrite ( String path ) { return null ; } public boolean fileExists ( String path ) { return false ; } public void sync ( ) throws IOException { } public void delete ( IProgressMonitor monitor , String path ) { } public void mkdirs ( String path ) { } public DataInput openDataInput ( String path ) { return null ; } public void closeInput ( DataInput in ) { } public DataOutput openDataOutput ( String path ) { return null ; } public void closeOutput ( DataOutput out ) { } } package net . sf . sveditor . core . db . index . cache ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . RandomAccessFile ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ISVDBFS { String getRoot ( ) ; void removeStoragePath ( List < File > db_file_list ) ; InputStream openFileRead ( String path ) throws IOException ; RandomAccessFile openChannelRead ( String path ) ; DataInput openDataInput ( String path ) ; void closeChannel ( RandomAccessFile ch ) ; void close ( InputStream in ) ; void closeInput ( DataInput in ) ; OutputStream openFileWrite ( String path ) ; RandomAccessFile openChannelWrite ( String path ) ; DataOutput openDataOutput ( String path ) ; void closeOutput ( DataOutput out ) ; boolean fileExists ( String path ) ; long lastModified ( String path ) ; void delete ( IProgressMonitor monitor , String path ) ; void mkdirs ( String path ) ; void sync ( ) throws IOException ; } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; public interface ISVDBIndexFactory { String KEY_GlobalDefineMap = "" ; ISVDBIndex createSVDBIndex ( String project_name , String base_location , ISVDBIndexCache cache , SVDBIndexConfig config ) ; } package net . sf . sveditor . core . db . index ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . fileset . AbstractSVFileMatcher ; import net . sf . sveditor . core . log . LogFactory ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBSourceCollectionIndex extends AbstractSVDBIndex { private List < AbstractSVFileMatcher > fFileMatcherList ; static { LogFactory . getLogHandle ( "" ) ; } SVDBSourceCollectionIndex ( String project , String root , List < AbstractSVFileMatcher > matcher_list , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { super ( project , root , fs_provider , cache , config ) ; fFileMatcherList = matcher_list ; } @ Override protected String getLogName ( ) { return "" ; } @ Override protected boolean checkCacheValid ( ) { boolean valid = super . checkCacheValid ( ) ; if ( valid ) { for ( int i = ; i < fFileMatcherList . size ( ) ; i ++ ) { AbstractSVFileMatcher matcher = fFileMatcherList . get ( i ) ; List < String > file_paths = matcher . findIncludedPaths ( ) ; Set < String > cache_files = getCache ( ) . getFileList ( ) ; List < String > tmp_cache_files = new ArrayList < String > ( ) ; tmp_cache_files . addAll ( cache_files ) ; for ( String path : file_paths ) { if ( cache_files . contains ( path ) ) { long fs_timestamp = getFileSystemProvider ( ) . getLastModifiedTime ( path ) ; long cache_timestamp = getCache ( ) . getLastModified ( path ) ; if ( cache_timestamp < fs_timestamp ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path + "" + fs_timestamp + "" + cache_timestamp ) ; } valid = false ; break ; } tmp_cache_files . remove ( path ) ; } else { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path ) ; } valid = false ; break ; } } if ( valid ) { for ( String path : tmp_cache_files ) { if ( getFileSystemProvider ( ) . fileExists ( path ) ) { long fs_timestamp = getFileSystemProvider ( ) . getLastModifiedTime ( path ) ; long cache_timestamp = getCache ( ) . getLastModified ( path ) ; if ( cache_timestamp < fs_timestamp ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path + "" + fs_timestamp + "" + cache_timestamp ) ; } valid = false ; break ; } } else { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path ) ; } valid = false ; break ; } } } } } if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + ( ( valid ) ? "" : "" ) ) ; } return valid ; } @ Override protected void discoverRootFiles ( IProgressMonitor monitor ) { for ( int i = ; i < fFileMatcherList . size ( ) ; i ++ ) { AbstractSVFileMatcher matcher = fFileMatcherList . get ( i ) ; List < String > file_paths = matcher . findIncludedPaths ( ) ; fLog . debug ( LEVEL_MIN , "" ) ; for ( String path : file_paths ) { String rp = resolvePath ( path , fInWorkspaceOk ) ; fLog . debug ( LEVEL_MID , "" + rp + "" ) ; addFile ( rp ) ; addIncludePath ( SVFileUtils . getPathParent ( rp ) ) ; } } } public String getTypeID ( ) { return SVDBSourceCollectionIndexFactory . TYPE ; } } package net . sf . sveditor . core . db . index ; import java . util . HashMap ; import java . util . Map ; public class SVDBIndexConfig extends HashMap < String , Object > { private static final long serialVersionUID = ; public static boolean equals ( SVDBIndexConfig c1 , SVDBIndexConfig c2 ) { if ( c1 == null || c2 == null ) { return ( c1 == c2 ) ; } else { boolean equals = c1 . size ( ) == c2 . size ( ) ; if ( equals ) { for ( Map . Entry < String , Object > c1_e : c1 . entrySet ( ) ) { if ( c2 . containsKey ( c1_e . getKey ( ) ) ) { Object o1 = c1 . get ( c1_e . getKey ( ) ) ; Object o2 = c2 . get ( c1_e . getKey ( ) ) ; if ( o1 == null || o2 == null ) { equals &= ( o1 == o2 ) ; } else { equals &= o1 . equals ( o2 ) ; } } else { equals = false ; } if ( ! equals ) { break ; } } } return equals ; } } } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public interface ISVDBItemIterator { boolean hasNext ( SVDBItemType ... type_list ) ; ISVDBItemBase nextItem ( SVDBItemType ... type_list ) ; } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; public interface ISVDBIncludeFileProvider { SVDBSearchResult < SVDBFile > findIncludedFile ( String leaf ) ; } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; public class SVDBArgFileIndexFactory implements ISVDBIndexFactory { public static final String TYPE = "" ; public ISVDBIndex createSVDBIndex ( String projectName , String base_location , ISVDBIndexCache cache , SVDBIndexConfig config ) { ISVDBFileSystemProvider fs_provider ; fs_provider = new SVDBWSFileSystemProvider ( ) ; SVDBArgFileIndex index = new SVDBArgFileIndex ( projectName , base_location , fs_provider , cache , config ) ; return index ; } public ISVDBIndex createSVDBIndex ( String projectName , String base_location , StringBuilder arguments , ISVDBIndexCache cache , SVDBIndexConfig config ) { ISVDBFileSystemProvider fs_provider ; fs_provider = new SVDBWSFileSystemProvider ( ) ; SVDBArgFileIndex index = new SVDBArgFileIndex ( projectName , base_location , arguments , fs_provider , cache , config ) ; return index ; } } package net . sf . sveditor . core . db . index ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ISVDBIndexIterator extends ISVDBDeclCache { ISVDBItemIterator getItemIterator ( IProgressMonitor monitor ) ; } package net . sf . sveditor . core . db . index ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . StringIterableIterator ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . refs . ISVDBRefMatcher ; import net . sf . sveditor . core . db . refs . SVDBRefCacheItem ; import net . sf . sveditor . core . db . search . ISVDBFindNameMatcher ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBIndexListIterator implements ISVDBIndexIterator { private List < ISVDBIndexIterator > fIndexIteratorList ; public SVDBIndexListIterator ( ) { fIndexIteratorList = new ArrayList < ISVDBIndexIterator > ( ) ; } public void addIndexIterator ( ISVDBIndexIterator it ) { fIndexIteratorList . add ( it ) ; } public ISVDBItemIterator getItemIterator ( IProgressMonitor monitor ) { return new SVDBIndexItemItIterator ( fIndexIteratorList . iterator ( ) , monitor ) ; } public List < SVDBDeclCacheItem > findGlobalScopeDecl ( IProgressMonitor monitor , String name , ISVDBFindNameMatcher matcher ) { List < SVDBDeclCacheItem > ret = new ArrayList < SVDBDeclCacheItem > ( ) ; for ( ISVDBIndexIterator index_it : fIndexIteratorList ) { List < SVDBDeclCacheItem > tmp = index_it . findGlobalScopeDecl ( monitor , name , matcher ) ; ret . addAll ( tmp ) ; } return ret ; } public List < SVDBRefCacheItem > findReferences ( IProgressMonitor monitor , String name , ISVDBRefMatcher matcher ) { List < SVDBRefCacheItem > ret = new ArrayList < SVDBRefCacheItem > ( ) ; for ( ISVDBIndexIterator index_it : fIndexIteratorList ) { List < SVDBRefCacheItem > r = index_it . findReferences ( monitor , name , matcher ) ; ret . addAll ( r ) ; } return ret ; } public Iterable < String > getFileList ( IProgressMonitor monitor ) { StringIterableIterator ret = new StringIterableIterator ( ) ; for ( ISVDBIndexIterator index_it : fIndexIteratorList ) { ret . addIterable ( index_it . getFileList ( new NullProgressMonitor ( ) ) ) ; } return ret ; } public SVDBFile findFile ( IProgressMonitor monitor , String path ) { SVDBFile ret = null ; synchronized ( fIndexIteratorList ) { for ( ISVDBIndexIterator index_it : fIndexIteratorList ) { ret = index_it . findFile ( monitor , path ) ; if ( ret != null ) { break ; } } } return ret ; } public SVDBFile findPreProcFile ( IProgressMonitor monitor , String path ) { SVDBFile ret = null ; synchronized ( fIndexIteratorList ) { for ( ISVDBIndexIterator index_it : fIndexIteratorList ) { ret = index_it . findPreProcFile ( monitor , path ) ; if ( ret != null ) { break ; } } } return ret ; } public List < SVDBDeclCacheItem > findPackageDecl ( IProgressMonitor monitor , SVDBDeclCacheItem pkg_item ) { List < SVDBDeclCacheItem > ret = new ArrayList < SVDBDeclCacheItem > ( ) ; for ( ISVDBIndexIterator index_it : fIndexIteratorList ) { List < SVDBDeclCacheItem > tmp = index_it . findPackageDecl ( monitor , pkg_item ) ; ret . addAll ( tmp ) ; } return ret ; } public SVDBFile getDeclFile ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { for ( ISVDBIndexIterator index_it : fIndexIteratorList ) { SVDBFile tmp = index_it . getDeclFile ( monitor , item ) ; if ( tmp != null ) { return tmp ; } } return null ; } public SVDBFile getDeclFilePP ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { for ( ISVDBIndexIterator index_it : fIndexIteratorList ) { SVDBFile tmp = index_it . getDeclFilePP ( monitor , item ) ; if ( tmp != null ) { return tmp ; } } return null ; } } package net . sf . sveditor . core . db . index ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . refs . ISVDBRefMatcher ; import net . sf . sveditor . core . db . refs . SVDBRefCacheEntry ; import net . sf . sveditor . core . db . refs . SVDBRefCacheItem ; import net . sf . sveditor . core . db . refs . SVDBRefItem ; import net . sf . sveditor . core . db . search . ISVDBFindNameMatcher ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ISVDBDeclCache { List < SVDBDeclCacheItem > findGlobalScopeDecl ( IProgressMonitor monitor , String name , ISVDBFindNameMatcher matcher ) ; Iterable < String > getFileList ( IProgressMonitor monitor ) ; SVDBFile findFile ( IProgressMonitor monitor , String filename ) ; SVDBFile findPreProcFile ( IProgressMonitor monitor , String filename ) ; List < SVDBDeclCacheItem > findPackageDecl ( IProgressMonitor monitor , SVDBDeclCacheItem pkg_item ) ; SVDBFile getDeclFile ( IProgressMonitor monitor , SVDBDeclCacheItem item ) ; SVDBFile getDeclFilePP ( IProgressMonitor monitor , SVDBDeclCacheItem item ) ; List < SVDBRefCacheItem > findReferences ( IProgressMonitor monitor , String name , ISVDBRefMatcher matcher ) ; } package net . sf . sveditor . core . db . index ; import java . util . ArrayList ; import java . util . List ; public class SVDBArgFileIndexCacheData extends SVDBBaseIndexCacheData { public List < String > fArgFilePaths ; public List < Long > fArgFileTimestamps ; public SVDBArgFileIndexCacheData ( String base_location ) { super ( base_location ) ; fArgFileTimestamps = new ArrayList < Long > ( ) ; fArgFilePaths = new ArrayList < String > ( ) ; } public List < Long > getArgFileTimestamps ( ) { return fArgFileTimestamps ; } public List < String > getArgFilePaths ( ) { return fArgFilePaths ; } } package net . sf . sveditor . core . db . index ; import java . io . InputStream ; import java . util . List ; import java . util . Map . Entry ; import java . util . Set ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . scanutils . ITextScanner ; import net . sf . sveditor . core . scanutils . InputStreamTextScanner ; import net . sf . sveditor . core . svf_scanner . SVFScanner ; import org . apache . tools . ant . filters . StringInputStream ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; public class SVDBArgFileIndex extends AbstractSVDBIndex { private StringBuilder fArguments ; public SVDBArgFileIndex ( String project , String root , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { super ( project , root , fs_provider , cache , config ) ; fInWorkspaceOk = ( root . startsWith ( "" ) ) ; } public SVDBArgFileIndex ( String project , String root , StringBuilder arguments , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { super ( project , root , fs_provider , cache , config ) ; fArguments = arguments ; fInWorkspaceOk = ( root . startsWith ( "" ) ) ; } @ Override protected String getLogName ( ) { return "" ; } public String getTypeID ( ) { return SVDBArgFileIndexFactory . TYPE ; } @ Override protected SVDBBaseIndexCacheData createIndexCacheData ( ) { return new SVDBArgFileIndexCacheData ( getBaseLocation ( ) ) ; } @ Override protected boolean checkCacheValid ( ) { SVDBArgFileIndexCacheData cd = ( SVDBArgFileIndexCacheData ) getCacheData ( ) ; int i = ; for ( String arg_file : cd . getArgFilePaths ( ) ) { long ts = getFileSystemProvider ( ) . getLastModifiedTime ( arg_file ) ; long ts_c = cd . getArgFileTimestamps ( ) . get ( i ) ; if ( ts > ts_c ) { fLog . debug ( "" + arg_file + "" + ts + "" + ts_c ) ; return false ; } i ++ ; } return super . checkCacheValid ( ) ; } @ Override protected void discoverRootFiles ( IProgressMonitor monitor ) { fLog . debug ( "" + getBaseLocation ( ) ) ; clearFilesList ( ) ; clearIncludePaths ( ) ; clearDefines ( ) ; monitor . beginTask ( "" , ) ; SVDBArgFileIndexCacheData cd = ( SVDBArgFileIndexCacheData ) getCacheData ( ) ; cd . getArgFileTimestamps ( ) . clear ( ) ; cd . getArgFilePaths ( ) . clear ( ) ; addIncludePath ( getResolvedBaseLocationDir ( ) ) ; processArgFile ( new SubProgressMonitor ( monitor , ) , getResolvedBaseLocation ( ) ) ; monitor . done ( ) ; } private void processArgFile ( IProgressMonitor monitor , String path ) { InputStream in = null ; if ( fArguments != null ) { in = new StringInputStream ( fArguments . toString ( ) ) ; } else if ( getFileSystemProvider ( ) . fileExists ( path ) ) { in = getFileSystemProvider ( ) . openStream ( path ) ; } else if ( getFileSystemProvider ( ) . fileExists ( getResolvedBaseLocationDir ( ) + "" + path ) ) { in = getFileSystemProvider ( ) . openStream ( getResolvedBaseLocationDir ( ) + "" + path ) ; } monitor . beginTask ( "" + path , ) ; if ( in != null ) { SVDBArgFileIndexCacheData cd = ( SVDBArgFileIndexCacheData ) getCacheData ( ) ; cd . getArgFilePaths ( ) . add ( path ) ; cd . getArgFileTimestamps ( ) . add ( getFileSystemProvider ( ) . getLastModifiedTime ( path ) ) ; ITextScanner sc = new InputStreamTextScanner ( in , path ) ; SVFScanner scanner = new SVFScanner ( ) ; monitor . worked ( ) ; try { scanner . scan ( sc ) ; } catch ( Exception e ) { fLog . error ( "" + getResolvedBaseLocation ( ) + "" , e ) ; } monitor . worked ( ) ; for ( String f : scanner . getFilePaths ( ) ) { String exp_f = SVDBIndexUtil . expandVars ( f , fProjectName , fInWorkspaceOk ) ; fLog . debug ( "" + f + "" + exp_f + "" ) ; String res_f = resolvePath ( exp_f , fInWorkspaceOk ) ; if ( getFileSystemProvider ( ) . fileExists ( res_f ) ) { addFile ( res_f ) ; } else { fLog . error ( "" + exp_f + "" ) ; } } for ( String lib_p : scanner . getLibPaths ( ) ) { String exp_p = SVDBIndexUtil . expandVars ( lib_p , fProjectName , fInWorkspaceOk ) ; fLog . debug ( "" + lib_p + "" + exp_p + "" ) ; String res_p = resolvePath ( exp_p , fInWorkspaceOk ) ; if ( getFileSystemProvider ( ) . isDir ( res_p ) ) { List < String > paths = getFileSystemProvider ( ) . getFiles ( res_p ) ; Set < String > exts = scanner . getSrcExts ( ) ; for ( String file_p : paths ) { int last_dot = file_p . lastIndexOf ( '' ) ; if ( last_dot != - ) { String ext = file_p . substring ( last_dot ) ; if ( exts . contains ( ext ) ) { addFile ( file_p ) ; } } } } else { fLog . error ( "" + exp_p + "" ) ; } } monitor . worked ( ) ; for ( String inc : scanner . getIncludePaths ( ) ) { String inc_path = SVDBIndexUtil . expandVars ( inc , fProjectName , fInWorkspaceOk ) ; fLog . debug ( "" + inc + "" + inc_path + "" ) ; addIncludePath ( inc_path ) ; } monitor . worked ( ) ; for ( Entry < String , String > entry : scanner . getDefineMap ( ) . entrySet ( ) ) { fLog . debug ( "" + entry . getKey ( ) + "" + entry . getValue ( ) ) ; addDefine ( entry . getKey ( ) , entry . getValue ( ) ) ; } getFileSystemProvider ( ) . closeStream ( in ) ; for ( String arg_file : scanner . getArgFilePaths ( ) ) { arg_file = SVDBIndexUtil . expandVars ( arg_file , fProjectName , fInWorkspaceOk ) ; if ( ! cd . getArgFilePaths ( ) . contains ( arg_file ) ) { processArgFile ( new SubProgressMonitor ( monitor , ) , arg_file ) ; } } monitor . done ( ) ; } else { monitor . done ( ) ; fLog . error ( "" + path + "" ) ; } } @ Override public void dispose ( ) { SVDBArgFileIndexCacheData cd = ( SVDBArgFileIndexCacheData ) getCacheData ( ) ; cd . getArgFileTimestamps ( ) . clear ( ) ; for ( String arg_file : cd . getArgFilePaths ( ) ) { long ts = getFileSystemProvider ( ) . getLastModifiedTime ( arg_file ) ; fLog . debug ( "" + arg_file + "" + ts ) ; cd . getArgFileTimestamps ( ) . add ( ts ) ; } super . dispose ( ) ; } @ Override public void fileChanged ( String path ) { fLog . debug ( "" + path ) ; if ( path . equals ( getResolvedBaseLocation ( ) ) ) { invalidateIndex ( new NullProgressMonitor ( ) , "" + path , false ) ; } super . fileChanged ( path ) ; } } package net . sf . sveditor . core . db . index ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . fileset . AbstractSVFileMatcher ; import net . sf . sveditor . core . job_mgr . IJob ; import net . sf . sveditor . core . job_mgr . IJobMgr ; import net . sf . sveditor . core . log . LogFactory ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBThreadedSourceCollectionIndex extends AbstractThreadedSVDBIndex { private List < AbstractSVFileMatcher > fFileMatcherList ; static { LogFactory . getLogHandle ( "" ) ; } public SVDBThreadedSourceCollectionIndex ( String project , String root , List < AbstractSVFileMatcher > matcher_list , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { super ( project , root , fs_provider , cache , config ) ; fFileMatcherList = matcher_list ; } @ Override protected String getLogName ( ) { return "" ; } @ Override protected boolean checkCacheValid ( ) { boolean valid = super . checkCacheValid ( ) ; if ( valid ) { for ( int i = ; i < fFileMatcherList . size ( ) ; i ++ ) { AbstractSVFileMatcher matcher = fFileMatcherList . get ( i ) ; List < String > file_paths = matcher . findIncludedPaths ( ) ; Set < String > cache_files = getCache ( ) . getFileList ( ) ; List < String > tmp_cache_files = new ArrayList < String > ( ) ; tmp_cache_files . addAll ( cache_files ) ; for ( String path : file_paths ) { if ( cache_files . contains ( path ) ) { long fs_timestamp = getFileSystemProvider ( ) . getLastModifiedTime ( path ) ; long cache_timestamp = getCache ( ) . getLastModified ( path ) ; if ( cache_timestamp < fs_timestamp ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path + "" + fs_timestamp + "" + cache_timestamp ) ; } valid = false ; break ; } tmp_cache_files . remove ( path ) ; } else { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path ) ; } valid = false ; break ; } } if ( valid ) { for ( String path : tmp_cache_files ) { if ( getFileSystemProvider ( ) . fileExists ( path ) ) { long fs_timestamp = getFileSystemProvider ( ) . getLastModifiedTime ( path ) ; long cache_timestamp = getCache ( ) . getLastModified ( path ) ; if ( cache_timestamp < fs_timestamp ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path + "" + fs_timestamp + "" + cache_timestamp ) ; } valid = false ; break ; } } else { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path ) ; } valid = false ; break ; } } } } } if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + ( ( valid ) ? "" : "" ) ) ; } return valid ; } @ Override protected void discoverRootFiles ( List < IJob > jobs ) { IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; for ( int i = ; i < fFileMatcherList . size ( ) ; i ++ ) { AbstractSVFileMatcher matcher = fFileMatcherList . get ( i ) ; List < String > file_paths = matcher . findIncludedPaths ( ) ; fLog . debug ( LEVEL_MIN , "" ) ; for ( String path : file_paths ) { IJob job = job_mgr . createJob ( ) ; job . init ( path , new DiscoverFilesJob ( path ) ) ; jobs . add ( job ) ; job_mgr . queueJob ( job ) ; } } } private class DiscoverFilesJob implements Runnable { private String fPath ; public DiscoverFilesJob ( String path ) { fPath = path ; } public void run ( ) { String rp = resolvePath ( fPath , fInWorkspaceOk ) ; fLog . debug ( LEVEL_MID , "" + rp + "" ) ; addFile ( rp ) ; addIncludePath ( SVFileUtils . getPathParent ( rp ) ) ; } } public String getTypeID ( ) { return SVDBSourceCollectionIndexFactory . TYPE ; } } package net . sf . sveditor . core . db . index ; import java . io . File ; public class SVDBPersistenceDescriptor { private File fDBFile ; private String fBaseLocation ; public SVDBPersistenceDescriptor ( File file , String base_location ) { fDBFile = file ; fBaseLocation = base_location ; } public File getDBFile ( ) { return fDBFile ; } public String getBaseLocation ( ) { return fBaseLocation ; } } package net . sf . sveditor . core . db . index ; import java . io . InputStream ; import java . util . List ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . refs . ISVDBRefMatcher ; import net . sf . sveditor . core . db . refs . SVDBRefCacheItem ; import net . sf . sveditor . core . db . search . ISVDBFindNameMatcher ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBFileOverrideIndex implements ISVDBIndex , ISVDBIndexIterator , ILogLevel { private SVDBFile fFile ; private SVDBFile fFilePP ; private ISVDBIndex fIndex ; private ISVDBIndexIterator fSuperIterator ; private List < SVDBMarker > fMarkers ; private LogHandle fLog ; public SVDBFileOverrideIndex ( SVDBFile file , SVDBFile file_pp , ISVDBIndex index , ISVDBIndexIterator item_it , List < SVDBMarker > markers ) { fFile = file ; fFilePP = file_pp ; fIndex = index ; fSuperIterator = item_it ; fMarkers = markers ; fLog = LogFactory . getLogHandle ( getClass ( ) . getName ( ) ) ; } public void setFile ( SVDBFile file ) { fFile = file ; } public void setFilePP ( SVDBFile file ) { fFilePP = file ; } public ISVDBItemIterator getItemIterator ( IProgressMonitor monitor ) { if ( fSuperIterator != null ) { ISVDBItemIterator super_it = fSuperIterator . getItemIterator ( monitor ) ; if ( super_it instanceof SVDBIndexCollectionItemIterator ) { SVDBIndexCollectionItemIterator it = ( SVDBIndexCollectionItemIterator ) super_it ; it . setOverride ( fIndex , fFile ) ; return it ; } else { return super_it ; } } else { return SVEmptyItemIterator ; } } private ISVDBItemIterator SVEmptyItemIterator = new ISVDBItemIterator ( ) { public ISVDBItemBase nextItem ( SVDBItemType ... type_list ) { return null ; } public boolean hasNext ( SVDBItemType ... type_list ) { return false ; } } ; public List < SVDBDeclCacheItem > findGlobalScopeDecl ( IProgressMonitor monitor , String name , ISVDBFindNameMatcher matcher ) { List < SVDBDeclCacheItem > ret = fSuperIterator . findGlobalScopeDecl ( monitor , name , matcher ) ; for ( int i = ; i < ret . size ( ) ; i ++ ) { if ( ret . get ( i ) == null ) { System . out . println ( "" + i + "" ) ; } if ( ret . get ( i ) . getFile ( ) == null ) { System . out . println ( "" + i + "" ) ; continue ; } else if ( ret . get ( i ) . getFile ( ) . getFilePath ( ) == null ) { System . out . println ( "" + i + "" ) ; continue ; } if ( fFile == null ) { System . out . println ( "" ) ; } if ( fFile . getFilePath ( ) == null ) { System . out . println ( "" ) ; } String filepath = ret . get ( i ) . getFile ( ) . getFilePath ( ) ; String filepath_f = fFile . getFilePath ( ) ; if ( filepath != null && filepath . equals ( filepath_f ) ) { fLog . debug ( LEVEL_MID , "" + ret . get ( i ) . getName ( ) + "" ) ; ret . remove ( i ) ; i -- ; } } findDecl ( ret , fFile , name , matcher ) ; return ret ; } private void findDecl ( List < SVDBDeclCacheItem > result , ISVDBChildParent scope , String name , ISVDBFindNameMatcher matcher ) { for ( ISVDBChildItem item : scope . getChildren ( ) ) { if ( item . getType ( ) . isElemOf ( SVDBItemType . PackageDecl , SVDBItemType . Function , SVDBItemType . Task , SVDBItemType . ClassDecl , SVDBItemType . ModuleDecl , SVDBItemType . InterfaceDecl , SVDBItemType . ProgramDecl , SVDBItemType . TypedefStmt , SVDBItemType . MacroDef ) ) { if ( item instanceof ISVDBNamedItem ) { boolean is_ft = item . getType ( ) . isElemOf ( SVDBItemType . MacroDef ) ; ISVDBNamedItem ni = ( ISVDBNamedItem ) item ; if ( matcher . match ( ni , name ) ) { fLog . debug ( LEVEL_MID , "" + ni . getName ( ) + "" ) ; result . add ( new SVDBDeclCacheItem ( this , fFile . getFilePath ( ) , ni . getName ( ) , ni . getType ( ) , is_ft ) ) ; } } if ( item . getType ( ) == SVDBItemType . PackageDecl ) { findDecl ( result , ( ISVDBChildParent ) item , name , matcher ) ; } } else if ( item . getType ( ) == SVDBItemType . PreProcCond ) { findDecl ( result , ( ISVDBChildParent ) item , name , matcher ) ; } } } public List < SVDBDeclCacheItem > findPackageDecl ( IProgressMonitor monitor , SVDBDeclCacheItem pkg_item ) { return fSuperIterator . findPackageDecl ( monitor , pkg_item ) ; } public SVDBFile getDeclFile ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { if ( item . getFilename ( ) . equals ( fFile . getFilePath ( ) ) ) { return fFile ; } else { return fSuperIterator . getDeclFile ( monitor , item ) ; } } public SVDBFile getDeclFilePP ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { if ( item . getFilename ( ) . equals ( fFile . getFilePath ( ) ) ) { return fFile ; } else { return fSuperIterator . getDeclFilePP ( monitor , item ) ; } } public List < SVDBRefCacheItem > findReferences ( IProgressMonitor monitor , String name , ISVDBRefMatcher matcher ) { return fSuperIterator . findReferences ( monitor , name , matcher ) ; } public SVDBSearchResult < SVDBFile > findIncludedFile ( String leaf ) { return fIndex . findIncludedFile ( leaf ) ; } public void init ( IProgressMonitor monitor ) { fIndex . init ( monitor ) ; } public Tuple < SVDBFile , SVDBFile > parse ( IProgressMonitor monitor , InputStream in , String path , List < SVDBMarker > markers ) { return fIndex . parse ( monitor , in , path , markers ) ; } public void setEnableAutoRebuild ( boolean en ) { fIndex . setEnableAutoRebuild ( en ) ; } public boolean isDirty ( ) { return fIndex . isDirty ( ) ; } public void dispose ( ) { fIndex . dispose ( ) ; } public String getBaseLocation ( ) { return fIndex . getBaseLocation ( ) ; } public String getProject ( ) { return fIndex . getProject ( ) ; } public void setGlobalDefine ( String key , String val ) { fIndex . setGlobalDefine ( key , val ) ; } public void clearGlobalDefines ( ) { fIndex . clearGlobalDefines ( ) ; } public String getTypeID ( ) { return fIndex . getTypeID ( ) ; } public void setIncludeFileProvider ( ISVDBIncludeFileProvider inc_provider ) { fIndex . setIncludeFileProvider ( inc_provider ) ; } public Iterable < String > getFileList ( IProgressMonitor monitor ) { return fSuperIterator . getFileList ( monitor ) ; } public SVDBFile findFile ( IProgressMonitor monitor , String path ) { return findFile ( path ) ; } public SVDBFile findPreProcFile ( IProgressMonitor monitor , String path ) { return findPreProcFile ( path ) ; } public List < SVDBMarker > getMarkers ( String path ) { if ( fFile . getFilePath ( ) . equals ( path ) ) { return fMarkers ; } else { return fIndex . getMarkers ( path ) ; } } public SVDBFile findFile ( String path ) { if ( fFile . getFilePath ( ) . equals ( path ) ) { return fFile ; } else { return fSuperIterator . findFile ( new NullProgressMonitor ( ) , path ) ; } } public SVDBFile findPreProcFile ( String path ) { if ( fFile . getFilePath ( ) . equals ( path ) ) { return fFilePP ; } else { return fSuperIterator . findPreProcFile ( new NullProgressMonitor ( ) , path ) ; } } public void rebuildIndex ( IProgressMonitor monitor ) { fIndex . rebuildIndex ( monitor ) ; } public void addChangeListener ( ISVDBIndexChangeListener l ) { fIndex . addChangeListener ( l ) ; } public void removeChangeListener ( ISVDBIndexChangeListener l ) { fIndex . removeChangeListener ( l ) ; } public ISVDBIndexCache getCache ( ) { return fIndex . getCache ( ) ; } public void loadIndex ( IProgressMonitor monitor ) { fIndex . loadIndex ( monitor ) ; } public boolean isLoaded ( ) { return fIndex . isLoaded ( ) ; } public boolean isFileListLoaded ( ) { return fIndex . isFileListLoaded ( ) ; } public SVDBIndexConfig getConfig ( ) { return fIndex . getConfig ( ) ; } } package net . sf . sveditor . core . db . index ; import java . lang . ref . Reference ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; public class SVDBIndexCollectionMgr { private List < Reference < SVDBIndexCollection > > fIndexCollectionList ; private boolean fCreateShadowIndexes ; public SVDBIndexCollectionMgr ( ) { fIndexCollectionList = new ArrayList < Reference < SVDBIndexCollection > > ( ) ; } public void addIndexCollection ( SVDBIndexCollection c ) { fIndexCollectionList . add ( new WeakReference < SVDBIndexCollection > ( c ) ) ; } public void setCreateShadowIndexes ( boolean create ) { boolean fire = ( fCreateShadowIndexes != create ) ; if ( fire ) { for ( int i = ; i < fIndexCollectionList . size ( ) ; i ++ ) { if ( fIndexCollectionList . get ( i ) . get ( ) != null ) { fIndexCollectionList . get ( i ) . get ( ) . settingsChanged ( ) ; } else { fIndexCollectionList . remove ( i ) ; i -- ; } } } fCreateShadowIndexes = create ; } public boolean getCreateShadowIndexes ( ) { return fCreateShadowIndexes ; } public void loadIndex ( IProgressMonitor monitor ) { SubProgressMonitor sm = new SubProgressMonitor ( monitor , ) ; synchronized ( fIndexCollectionList ) { sm . beginTask ( "" , fIndexCollectionList . size ( ) ) ; for ( int i = ; i < fIndexCollectionList . size ( ) ; i ++ ) { if ( fIndexCollectionList . get ( i ) . get ( ) == null ) { fIndexCollectionList . remove ( i ) ; i -- ; } else { fIndexCollectionList . get ( i ) . get ( ) . loadIndex ( new SubProgressMonitor ( sm , ) ) ; } } } sm . done ( ) ; } } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; public class SVDBLibPathIndexFactory implements ISVDBIndexFactory { public static final String TYPE = "" ; public ISVDBIndex createSVDBIndex ( String project_name , String base_location , ISVDBIndexCache cache , SVDBIndexConfig config ) { ISVDBFileSystemProvider fs_provider ; fs_provider = new SVDBWSFileSystemProvider ( ) ; ISVDBIndex index = new SVDBLibIndex ( project_name , base_location , fs_provider , cache , config ) ; return index ; } } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . SVDBFile ; public class SVDBIncludeSearch { public SVDBIncludeSearch ( ISVDBIndex index ) { } public SVDBFile findIncludedFile ( String name ) { SVDBFile ret = null ; try { throw new Exception ( ) ; } catch ( Exception e ) { System . out . println ( "" ) ; e . printStackTrace ( ) ; } return ret ; } } package net . sf . sveditor . core . db . index ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . sf . sveditor . core . db . refs . SVDBRefCacheEntry ; public class SVDBBaseIndexCacheData { public String fVersion ; public String fBaseLocation ; public List < String > fIncludePathList ; public List < String > fMissingIncludeFiles ; public Map < String , String > fGlobalDefines ; public Map < String , String > fDefineMap ; public Map < String , List < SVDBDeclCacheItem > > fDeclCacheMap ; public Map < String , List < SVDBDeclCacheItem > > fPackageCacheMap ; public Map < String , SVDBRefCacheEntry > fReferenceCacheMap ; public SVDBBaseIndexCacheData ( String base ) { fBaseLocation = base ; fIncludePathList = new ArrayList < String > ( ) ; fMissingIncludeFiles = new ArrayList < String > ( ) ; fGlobalDefines = new HashMap < String , String > ( ) ; fDefineMap = new HashMap < String , String > ( ) ; fDeclCacheMap = new HashMap < String , List < SVDBDeclCacheItem > > ( ) ; fPackageCacheMap = new HashMap < String , List < SVDBDeclCacheItem > > ( ) ; fReferenceCacheMap = new HashMap < String , SVDBRefCacheEntry > ( ) ; } public String getVersion ( ) { return fVersion ; } public void setVersion ( String version ) { fVersion = version ; } public String getBaseLocation ( ) { return fBaseLocation ; } public void addMissingIncludeFile ( String path ) { if ( ! fMissingIncludeFiles . contains ( path ) ) { fMissingIncludeFiles . add ( path ) ; } } public void clearMissingIncludeFiles ( ) { fMissingIncludeFiles . clear ( ) ; } public List < String > getMissingIncludeFiles ( ) { return fMissingIncludeFiles ; } public void setGlobalDefine ( String key , String val ) { if ( fGlobalDefines . containsKey ( key ) ) { fGlobalDefines . remove ( key ) ; } fGlobalDefines . put ( key , val ) ; } public Map < String , String > getGlobalDefines ( ) { return fGlobalDefines ; } public void clearGlobalDefines ( ) { fGlobalDefines . clear ( ) ; } public void clearDefines ( ) { fDefineMap . clear ( ) ; fDefineMap . putAll ( fGlobalDefines ) ; } public void addDefine ( String key , String val ) { if ( fDefineMap . containsKey ( key ) ) { fDefineMap . remove ( key ) ; } fDefineMap . put ( key , val ) ; } public Map < String , String > getDefines ( ) { return fDefineMap ; } public void clearIncludePaths ( ) { fIncludePathList . clear ( ) ; } public void addIncludePath ( String path ) { if ( ! fIncludePathList . contains ( path ) ) { fIncludePathList . add ( path ) ; } } public List < String > getIncludePaths ( ) { return fIncludePathList ; } public Map < String , List < SVDBDeclCacheItem > > getDeclCacheMap ( ) { return fDeclCacheMap ; } public Map < String , List < SVDBDeclCacheItem > > getPackageCacheMap ( ) { return fPackageCacheMap ; } public Map < String , SVDBRefCacheEntry > getReferenceCacheMap ( ) { return fReferenceCacheMap ; } public void clear ( ) { fDeclCacheMap . clear ( ) ; } } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBShadowIndex extends AbstractSVDBIndex { public SVDBShadowIndex ( String project , String base_location , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { super ( project , base_location , fs_provider , cache , config ) ; } public String getTypeID ( ) { return SVDBShadowIndexFactory . TYPE ; } @ Override protected String getLogName ( ) { return "" ; } @ Override protected void discoverRootFiles ( IProgressMonitor monitor ) { fLog . debug ( LEVEL_MIN , "" ) ; addFile ( getResolvedBaseLocation ( ) ) ; addIncludePath ( SVFileUtils . getPathParent ( getResolvedBaseLocation ( ) ) ) ; } } package net . sf . sveditor . core . db . index ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; public class InputStreamCopier { private InputStream fIn ; private ByteArrayOutputStream fOut ; public InputStreamCopier ( InputStream in ) { fIn = in ; } public InputStream copy ( ) { if ( fOut == null ) { byte data [ ] = new byte [ * ] ; int size ; fOut = new ByteArrayOutputStream ( ) ; try { while ( ( size = fIn . read ( data , , data . length ) ) > ) { fOut . write ( data , , size ) ; } fIn . close ( ) ; } catch ( IOException e ) { } } return new ByteArrayInputStream ( fOut . toByteArray ( ) ) ; } } package net . sf . sveditor . core . db . index ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; public class SVDBFSFileSystemProvider implements ISVDBFileSystemProvider { public void init ( String path ) { } public void dispose ( ) { } public void addMarker ( String path , String type , int lineno , String msg ) { } public void clearMarkers ( String path ) { } public void closeStream ( InputStream in ) { try { in . close ( ) ; } catch ( IOException e ) { } } public boolean fileExists ( String path ) { File f = new File ( path ) ; return f . isFile ( ) ; } public boolean isDir ( String path ) { File f = new File ( path ) ; return f . isDirectory ( ) ; } public List < String > getFiles ( String path ) { File p = new File ( path ) ; List < String > ret = new ArrayList < String > ( ) ; if ( p . isDirectory ( ) ) { File f_l [ ] = p . listFiles ( ) ; if ( f_l != null ) { for ( File f : p . listFiles ( ) ) { if ( ! f . getName ( ) . equals ( "" ) && ! f . getName ( ) . equals ( "" ) ) { ret . add ( f . getAbsolutePath ( ) ) ; } } } } return ret ; } public long getLastModifiedTime ( String path ) { File f = new File ( path ) ; return f . lastModified ( ) ; } public String resolvePath ( String path , String fmt ) { return path ; } public InputStream openStream ( String path ) { InputStream in = null ; try { in = new FileInputStream ( path ) ; } catch ( IOException e ) { } return in ; } public void addFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { } public void removeFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { } } package net . sf . sveditor . core . db . index ; import java . util . Iterator ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import org . eclipse . core . runtime . IProgressMonitor ; class SVDBIndexItemItIterator implements ISVDBItemIterator { private Iterator < ISVDBIndexIterator > fIterator ; private ISVDBItemIterator fCurrent ; private IProgressMonitor fMonitor ; public SVDBIndexItemItIterator ( Iterator < ISVDBIndexIterator > it , IProgressMonitor monitor ) { fIterator = it ; fMonitor = monitor ; } public boolean hasNext ( SVDBItemType ... type_list ) { while ( fCurrent != null || fIterator . hasNext ( ) ) { if ( fCurrent == null ) { fCurrent = fIterator . next ( ) . getItemIterator ( fMonitor ) ; } if ( ! fCurrent . hasNext ( type_list ) ) { fCurrent = null ; continue ; } else { break ; } } return ( fCurrent != null && fCurrent . hasNext ( type_list ) ) ; } public ISVDBItemBase nextItem ( SVDBItemType ... type_list ) { ISVDBItemBase ret = null ; while ( fCurrent != null || fIterator . hasNext ( ) ) { if ( fCurrent == null ) { fCurrent = fIterator . next ( ) . getItemIterator ( fMonitor ) ; } if ( ( ret = fCurrent . nextItem ( type_list ) ) == null ) { fCurrent = null ; continue ; } else { break ; } } return ret ; } } package net . sf . sveditor . core . db . index ; import java . io . InputStream ; import java . lang . ref . Reference ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . StringIterableIterator ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . refs . ISVDBRefMatcher ; import net . sf . sveditor . core . db . refs . SVDBRefCacheItem ; import net . sf . sveditor . core . db . search . ISVDBFindNameMatcher ; import net . sf . sveditor . core . db . search . ISVDBPreProcIndexSearcher ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; public class SVDBIndexCollection implements ISVDBPreProcIndexSearcher , ISVDBIndexIterator , ILogLevel { private SVDBIndexCollectionMgr fMgr ; private String fProject ; private List < ISVDBIndex > fSourceCollectionList ; private List < ISVDBIndex > fIncludePathList ; private List < ISVDBIndex > fLibraryPathList ; private List < ISVDBIndex > fPluginLibraryList ; private List < Reference < ISVDBIndex > > fShadowIndexList ; private List < List < ISVDBIndex > > fFileSearchOrder ; private Set < String > fProjectRefs ; private ISVDBProjectRefProvider fProjectRefProvider ; private List < ISVDBIndexChangeListener > fIndexChangeListeners ; private LogHandle fLog ; public SVDBIndexCollection ( String project ) { this ( null , project ) ; } public SVDBIndexCollection ( SVDBIndexCollectionMgr mgr , String project ) { fMgr = mgr ; fProject = project ; fSourceCollectionList = new ArrayList < ISVDBIndex > ( ) ; fIncludePathList = new ArrayList < ISVDBIndex > ( ) ; fLibraryPathList = new ArrayList < ISVDBIndex > ( ) ; fPluginLibraryList = new ArrayList < ISVDBIndex > ( ) ; fShadowIndexList = new ArrayList < Reference < ISVDBIndex > > ( ) ; fProjectRefs = new HashSet < String > ( ) ; fFileSearchOrder = new ArrayList < List < ISVDBIndex > > ( ) ; fFileSearchOrder . add ( fLibraryPathList ) ; fFileSearchOrder . add ( fSourceCollectionList ) ; fFileSearchOrder . add ( fIncludePathList ) ; fFileSearchOrder . add ( fPluginLibraryList ) ; fIndexChangeListeners = new ArrayList < ISVDBIndexChangeListener > ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; if ( fMgr != null ) { fMgr . addIndexCollection ( this ) ; } } public void loadIndex ( IProgressMonitor monitor ) { SubProgressMonitor sm = new SubProgressMonitor ( monitor , ) ; sm . beginTask ( "" , fSourceCollectionList . size ( ) + fIncludePathList . size ( ) + fLibraryPathList . size ( ) + fPluginLibraryList . size ( ) + fShadowIndexList . size ( ) ) ; synchronized ( fSourceCollectionList ) { for ( ISVDBIndex index : fSourceCollectionList ) { index . loadIndex ( new SubProgressMonitor ( sm , ) ) ; } } synchronized ( fIncludePathList ) { for ( ISVDBIndex index : fIncludePathList ) { index . loadIndex ( new SubProgressMonitor ( sm , ) ) ; } } synchronized ( fLibraryPathList ) { for ( ISVDBIndex index : fLibraryPathList ) { index . loadIndex ( new SubProgressMonitor ( sm , ) ) ; } } synchronized ( fPluginLibraryList ) { for ( ISVDBIndex index : fPluginLibraryList ) { index . loadIndex ( new SubProgressMonitor ( sm , ) ) ; } } synchronized ( fShadowIndexList ) { for ( Reference < ISVDBIndex > iref : fShadowIndexList ) { if ( iref . get ( ) != null ) { iref . get ( ) . loadIndex ( new SubProgressMonitor ( sm , ) ) ; } } } sm . done ( ) ; } public boolean isLoaded ( ) { boolean loaded = true ; synchronized ( fSourceCollectionList ) { for ( ISVDBIndex index : fSourceCollectionList ) { loaded &= index . isLoaded ( ) ; } } synchronized ( fIncludePathList ) { for ( ISVDBIndex index : fIncludePathList ) { loaded &= index . isLoaded ( ) ; } } synchronized ( fLibraryPathList ) { for ( ISVDBIndex index : fLibraryPathList ) { loaded &= index . isLoaded ( ) ; } } synchronized ( fPluginLibraryList ) { for ( ISVDBIndex index : fPluginLibraryList ) { loaded &= index . isLoaded ( ) ; } } return loaded ; } public boolean isFileListLoaded ( ) { boolean loaded = true ; synchronized ( fSourceCollectionList ) { for ( ISVDBIndex index : fSourceCollectionList ) { loaded &= index . isFileListLoaded ( ) ; } } synchronized ( fIncludePathList ) { for ( ISVDBIndex index : fIncludePathList ) { loaded &= index . isFileListLoaded ( ) ; } } synchronized ( fLibraryPathList ) { for ( ISVDBIndex index : fLibraryPathList ) { loaded &= index . isFileListLoaded ( ) ; } } synchronized ( fPluginLibraryList ) { for ( ISVDBIndex index : fPluginLibraryList ) { loaded &= index . isFileListLoaded ( ) ; loaded &= index . isLoaded ( ) ; } } return loaded ; } public void settingsChanged ( ) { } public boolean getCreateShadowIndex ( ) { return ( fMgr != null ) ? fMgr . getCreateShadowIndexes ( ) : true ; } public void addIndexChangeListener ( ISVDBIndexChangeListener l ) { if ( ! fIndexChangeListeners . contains ( l ) ) { fIndexChangeListeners . add ( l ) ; } for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { index . addChangeListener ( l ) ; } } clearStaleShadowIndexes ( ) ; for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { index . addChangeListener ( l ) ; } } } public void removeIndexChangeListener ( ISVDBIndexChangeListener l ) { fIndexChangeListeners . remove ( l ) ; for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { index . removeChangeListener ( l ) ; } } clearStaleShadowIndexes ( ) ; for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { index . removeChangeListener ( l ) ; } } } public void dispose ( ) { for ( ISVDBIndex i : getIndexList ( ) ) { i . dispose ( ) ; } } public String getProject ( ) { return fProject ; } public void rebuildIndex ( IProgressMonitor monitor ) { for ( ISVDBIndex i : getIndexList ( ) ) { i . rebuildIndex ( monitor ) ; } clearStaleShadowIndexes ( ) ; for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { index . rebuildIndex ( monitor ) ; } } } public void clear ( ) { fLog . debug ( "" ) ; for ( ISVDBIndex index : fSourceCollectionList ) { index . setIncludeFileProvider ( null ) ; } fSourceCollectionList . clear ( ) ; for ( ISVDBIndex index : fIncludePathList ) { index . setIncludeFileProvider ( null ) ; } fIncludePathList . clear ( ) ; for ( ISVDBIndex index : fLibraryPathList ) { index . setIncludeFileProvider ( null ) ; } fLibraryPathList . clear ( ) ; for ( ISVDBIndex index : fPluginLibraryList ) { index . setIncludeFileProvider ( null ) ; } fPluginLibraryList . clear ( ) ; fProjectRefs . clear ( ) ; } public List < ISVDBIndex > getIndexList ( ) { List < ISVDBIndex > ret = new ArrayList < ISVDBIndex > ( ) ; for ( List < ISVDBIndex > i_l : fFileSearchOrder ) { ret . addAll ( i_l ) ; } return ret ; } public ISVDBItemIterator getItemIterator ( IProgressMonitor monitor ) { List < String > referenced_projects = new ArrayList < String > ( ) ; List < ISVDBIndexIterator > iterator_list = new ArrayList < ISVDBIndexIterator > ( ) ; getItemIterators ( referenced_projects , iterator_list ) ; return new SVDBIndexItemItIterator ( iterator_list . iterator ( ) , monitor ) ; } private void getItemIterators ( List < String > referenced_projects , List < ISVDBIndexIterator > iterator_list ) { if ( referenced_projects . contains ( fProject ) ) { return ; } referenced_projects . add ( fProject ) ; for ( List < ISVDBIndex > i_l : fFileSearchOrder ) { for ( ISVDBIndex index : i_l ) { iterator_list . add ( index ) ; } } clearStaleShadowIndexes ( ) ; for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { iterator_list . add ( index ) ; } } if ( fProjectRefProvider != null ) { for ( String proj : fProjectRefs ) { if ( ! referenced_projects . contains ( proj ) ) { SVDBIndexCollection mgr_t = fProjectRefProvider . resolveProjectRef ( proj ) ; mgr_t . getItemIterators ( referenced_projects , iterator_list ) ; } } } } public void addProjectRef ( String ref ) { if ( ! fProjectRefs . contains ( ref ) ) { fProjectRefs . add ( ref ) ; } } public Set < String > getProjectRefs ( ) { return fProjectRefs ; } public void setProjectRefProvider ( ISVDBProjectRefProvider p ) { fProjectRefProvider = p ; } public ISVDBProjectRefProvider getProjectRefProvider ( ) { return fProjectRefProvider ; } public void addSourceCollection ( ISVDBIndex index ) { fLog . debug ( "" + index . getBaseLocation ( ) ) ; IncludeProvider p = new IncludeProvider ( index ) ; p . addSearchPath ( fSourceCollectionList ) ; p . addSearchPath ( fIncludePathList ) ; p . addSearchPath ( fLibraryPathList ) ; p . addSearchPath ( fPluginLibraryList ) ; index . setIncludeFileProvider ( p ) ; fSourceCollectionList . add ( index ) ; for ( ISVDBIndexChangeListener l : fIndexChangeListeners ) { index . addChangeListener ( l ) ; } } public List < ISVDBIndex > getSourceCollectionList ( ) { return fSourceCollectionList ; } public void addShadowIndex ( String dir , ISVDBIndex index ) { if ( index == null ) { fLog . error ( "" + dir + "" ) ; return ; } fLog . debug ( "" + dir + "" + index . getBaseLocation ( ) + "" ) ; IncludeProvider p = new IncludeProvider ( index ) ; p . addSearchPath ( fSourceCollectionList ) ; p . addSearchPath ( fIncludePathList ) ; p . addSearchPath ( fLibraryPathList ) ; p . addSearchPath ( fPluginLibraryList ) ; index . setIncludeFileProvider ( p ) ; fShadowIndexList . add ( new WeakReference < ISVDBIndex > ( index ) ) ; for ( ISVDBIndexChangeListener l : fIndexChangeListeners ) { index . addChangeListener ( l ) ; } } public void addIncludePath ( ISVDBIndex index ) { IncludeProvider p = new IncludeProvider ( index ) ; p . addSearchPath ( fIncludePathList ) ; p . addSearchPath ( fLibraryPathList ) ; p . addSearchPath ( fSourceCollectionList ) ; p . addSearchPath ( fPluginLibraryList ) ; index . setIncludeFileProvider ( p ) ; fIncludePathList . add ( index ) ; } public void addLibraryPath ( ISVDBIndex index ) { IncludeProvider p = new IncludeProvider ( index ) ; p . addSearchPath ( fLibraryPathList ) ; p . addSearchPath ( fIncludePathList ) ; p . addSearchPath ( fSourceCollectionList ) ; p . addSearchPath ( fPluginLibraryList ) ; index . setIncludeFileProvider ( p ) ; fLibraryPathList . add ( index ) ; for ( ISVDBIndexChangeListener l : fIndexChangeListeners ) { index . addChangeListener ( l ) ; } } public List < ISVDBIndex > getLibraryPathList ( ) { return fLibraryPathList ; } public List < ISVDBIndex > getPluginPathList ( ) { return fPluginLibraryList ; } public void addPluginLibrary ( ISVDBIndex index ) { IncludeProvider p = new IncludeProvider ( index ) ; p . addSearchPath ( fPluginLibraryList ) ; index . setIncludeFileProvider ( p ) ; fPluginLibraryList . add ( index ) ; for ( ISVDBIndexChangeListener l : fIndexChangeListeners ) { index . addChangeListener ( l ) ; } } public List < SVDBSearchResult < SVDBFile > > findPreProcFile ( String path , boolean search_shadow ) { List < SVDBSearchResult < SVDBFile > > ret = new ArrayList < SVDBSearchResult < SVDBFile > > ( ) ; SVDBFile result ; synchronized ( fFileSearchOrder ) { for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { if ( ( result = index . findPreProcFile ( path ) ) != null ) { ret . add ( new SVDBSearchResult < SVDBFile > ( result , index ) ) ; } } } } if ( ret . size ( ) == && search_shadow ) { clearStaleShadowIndexes ( ) ; synchronized ( fShadowIndexList ) { for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { if ( ( result = index . findPreProcFile ( path ) ) != null ) { ret . add ( new SVDBSearchResult < SVDBFile > ( result , index ) ) ; } } } } } return ret ; } public List < SVDBSearchResult < SVDBFile > > findFile ( String path ) { return findFile ( path , true ) ; } public List < SVDBSearchResult < SVDBFile > > findFile ( String path , boolean search_shadow ) { List < SVDBSearchResult < SVDBFile > > ret = new ArrayList < SVDBSearchResult < SVDBFile > > ( ) ; SVDBFile result ; synchronized ( fFileSearchOrder ) { for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { if ( ( result = index . findFile ( path ) ) != null ) { ret . add ( new SVDBSearchResult < SVDBFile > ( result , index ) ) ; } } } } if ( ret . size ( ) == && search_shadow ) { clearStaleShadowIndexes ( ) ; for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { if ( ( result = index . findFile ( path ) ) != null ) { ret . add ( new SVDBSearchResult < SVDBFile > ( result , index ) ) ; } } } } return ret ; } public Tuple < SVDBFile , SVDBFile > parse ( IProgressMonitor monitor , InputStream in , String path , List < SVDBMarker > markers ) { Tuple < SVDBFile , SVDBFile > ret = null ; path = SVFileUtils . normalize ( path ) ; List < SVDBSearchResult < SVDBFile > > result = findPreProcFile ( path , true ) ; fLog . debug ( "" + path + "" ) ; for ( SVDBSearchResult < SVDBFile > r : result ) { fLog . debug ( "" + r . getIndex ( ) . getBaseLocation ( ) + "" + r . getItem ( ) . getFilePath ( ) ) ; } if ( result . size ( ) > ) { SVDBFile file = result . get ( ) . getItem ( ) ; ret = result . get ( ) . getIndex ( ) . parse ( monitor , in , file . getFilePath ( ) , markers ) ; } else { ISVDBIndex index = null ; clearStaleShadowIndexes ( ) ; for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null && index . getBaseLocation ( ) . equals ( path ) ) { break ; } } if ( index == null ) { fLog . debug ( LEVEL_MID , "" + path + "" ) ; if ( fProject != null ) { synchronized ( fShadowIndexList ) { for ( Reference < ISVDBIndex > r : fShadowIndexList ) { if ( r . get ( ) != null ) { if ( r . get ( ) . getBaseLocation ( ) . equals ( path ) ) { index = r . get ( ) ; break ; } } } } if ( index != null ) { index = SVDBShadowIndexFactory . create ( fProject , path ) ; } } else { System . out . println ( "" + "" ) ; } addShadowIndex ( path , index ) ; } ret = index . parse ( monitor , in , path , markers ) ; } return ret ; } public List < SVDBSearchResult < SVDBFile > > findIncParent ( SVDBFile file ) { System . out . println ( "" ) ; return null ; } public List < SVDBDeclCacheItem > findGlobalScopeDecl ( IProgressMonitor monitor , String name , ISVDBFindNameMatcher matcher ) { List < SVDBDeclCacheItem > ret = new ArrayList < SVDBDeclCacheItem > ( ) ; for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { List < SVDBDeclCacheItem > tmp = index . findGlobalScopeDecl ( monitor , name , matcher ) ; ret . addAll ( tmp ) ; } } Set < SVDBIndexCollection > already_searched = new HashSet < SVDBIndexCollection > ( ) ; findGlobalScopeDeclProjRef ( ret , name , matcher , already_searched , false ) ; return ret ; } public List < SVDBRefCacheItem > findReferences ( IProgressMonitor monitor , String name , ISVDBRefMatcher matcher ) { List < SVDBRefCacheItem > ret = new ArrayList < SVDBRefCacheItem > ( ) ; for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { List < SVDBRefCacheItem > r = index . findReferences ( monitor , name , matcher ) ; ret . addAll ( r ) ; } } return ret ; } public Iterable < String > getFileList ( IProgressMonitor monitor ) { StringIterableIterator ret = new StringIterableIterator ( ) ; for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { ret . addIterable ( index . getFileList ( new NullProgressMonitor ( ) ) ) ; } } Set < SVDBIndexCollection > already_searched = new HashSet < SVDBIndexCollection > ( ) ; getFileList ( ret , already_searched , false ) ; clearStaleShadowIndexes ( ) ; for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { ret . addIterable ( index . getFileList ( new NullProgressMonitor ( ) ) ) ; } } return ret ; } public SVDBFile findFile ( IProgressMonitor monitor , String path ) { SVDBFile ret = null ; for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { if ( ( ret = index . findFile ( monitor , path ) ) != null ) { break ; } } if ( ret != null ) { break ; } } if ( ret == null ) { clearStaleShadowIndexes ( ) ; synchronized ( fShadowIndexList ) { for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { if ( ( ret = index . findFile ( monitor , path ) ) != null ) { break ; } } } } } return ret ; } public SVDBFile findPreProcFile ( IProgressMonitor monitor , String path ) { SVDBFile ret = null ; for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { if ( ( ret = index . findPreProcFile ( monitor , path ) ) != null ) { break ; } } if ( ret != null ) { break ; } } if ( ret == null ) { clearStaleShadowIndexes ( ) ; synchronized ( fShadowIndexList ) { for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { if ( ( ret = index . findPreProcFile ( monitor , path ) ) != null ) { break ; } } } } } return ret ; } private void findGlobalScopeDeclProjRef ( List < SVDBDeclCacheItem > ret , String name , ISVDBFindNameMatcher matcher , Set < SVDBIndexCollection > already_searched , boolean search_local ) { if ( ! already_searched . contains ( this ) ) { already_searched . add ( this ) ; } if ( search_local ) { for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { List < SVDBDeclCacheItem > tmp = index . findGlobalScopeDecl ( new NullProgressMonitor ( ) , name , matcher ) ; ret . addAll ( tmp ) ; } } } if ( fProjectRefProvider != null ) { for ( String ref : fProjectRefs ) { SVDBIndexCollection mgr_t = fProjectRefProvider . resolveProjectRef ( ref ) ; if ( mgr_t != null && ! already_searched . contains ( mgr_t ) ) { mgr_t . findGlobalScopeDeclProjRef ( ret , name , matcher , already_searched , true ) ; } } } } private void clearStaleShadowIndexes ( ) { synchronized ( fShadowIndexList ) { for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { if ( fShadowIndexList . get ( i ) . get ( ) == null ) { System . out . println ( "" + i ) ; fShadowIndexList . remove ( i ) ; i -- ; } } } } private void getFileList ( StringIterableIterator ret , Set < SVDBIndexCollection > already_searched , boolean search_local ) { if ( ! already_searched . contains ( this ) ) { already_searched . add ( this ) ; } if ( search_local ) { for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { ret . addIterable ( index . getFileList ( new NullProgressMonitor ( ) ) ) ; } } } if ( fProjectRefProvider != null ) { for ( String ref : fProjectRefs ) { SVDBIndexCollection mgr_t = fProjectRefProvider . resolveProjectRef ( ref ) ; if ( mgr_t != null && ! already_searched . contains ( mgr_t ) ) { ret . addIterable ( mgr_t . getFileList ( new NullProgressMonitor ( ) ) ) ; } } } } public List < SVDBDeclCacheItem > findPackageDecl ( IProgressMonitor monitor , SVDBDeclCacheItem pkg_item ) { List < SVDBDeclCacheItem > ret = new ArrayList < SVDBDeclCacheItem > ( ) ; for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { List < SVDBDeclCacheItem > tmp = index . findPackageDecl ( monitor , pkg_item ) ; ret . addAll ( tmp ) ; } } clearStaleShadowIndexes ( ) ; for ( int i = ; i < fShadowIndexList . size ( ) ; i ++ ) { ISVDBIndex index = fShadowIndexList . get ( i ) . get ( ) ; if ( index != null ) { List < SVDBDeclCacheItem > tmp = index . findPackageDecl ( monitor , pkg_item ) ; ret . addAll ( tmp ) ; } } return ret ; } public SVDBFile getDeclFile ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { SVDBFile tmp = index . getDeclFile ( monitor , item ) ; if ( tmp != null ) { return tmp ; } } } return null ; } public SVDBFile getDeclFilePP ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { for ( List < ISVDBIndex > index_l : fFileSearchOrder ) { for ( ISVDBIndex index : index_l ) { SVDBFile tmp = index . getDeclFilePP ( monitor , item ) ; if ( tmp != null ) { return tmp ; } } } return null ; } private class IncludeProvider implements ISVDBIncludeFileProvider { ISVDBIndex fIndex ; List < List < ISVDBIndex > > fSearchPath ; public IncludeProvider ( ISVDBIndex self ) { fIndex = self ; fSearchPath = new ArrayList < List < ISVDBIndex > > ( ) ; } public void addSearchPath ( List < ISVDBIndex > path ) { fSearchPath . add ( path ) ; } public SVDBSearchResult < SVDBFile > findIncludedFile ( String leaf ) { SVDBSearchResult < SVDBFile > ret = null ; for ( List < ISVDBIndex > index_l : fSearchPath ) { for ( ISVDBIndex index : index_l ) { if ( index != fIndex ) { ret = index . findIncludedFile ( leaf ) ; fLog . debug ( "" + index . getBaseLocation ( ) + "" + leaf + "" + ret + "" ) ; if ( ret != null ) { break ; } } } if ( ret != null ) { break ; } } if ( ret == null ) { Set < SVDBIndexCollection > searched_projects = new HashSet < SVDBIndexCollection > ( ) ; ret = findIncludedFileProjRefs ( SVDBIndexCollection . this , leaf , searched_projects ) ; } return ret ; } private SVDBSearchResult < SVDBFile > findIncludedFileProjRefs ( SVDBIndexCollection mgr , String leaf , Set < SVDBIndexCollection > searched_projects ) { ISVDBProjectRefProvider p = mgr . getProjectRefProvider ( ) ; SVDBSearchResult < SVDBFile > ret = null ; searched_projects . add ( mgr ) ; if ( mgr != SVDBIndexCollection . this ) { for ( ISVDBIndex index : mgr . getIndexList ( ) ) { ret = index . findIncludedFile ( leaf ) ; fLog . debug ( "" + index . getBaseLocation ( ) + "" + leaf + "" + ret + "" ) ; if ( ret != null ) { break ; } } } if ( ret == null && p != null ) { for ( String ref : mgr . getProjectRefs ( ) ) { SVDBIndexCollection mgr_t = p . resolveProjectRef ( ref ) ; if ( mgr_t != null && ! searched_projects . contains ( mgr_t ) ) { ret = findIncludedFileProjRefs ( mgr_t , leaf , searched_projects ) ; if ( ret != null ) { break ; } } } } return ret ; } } ; } package net . sf . sveditor . core . db . index ; import java . io . InputStream ; import java . util . List ; public interface ISVDBFileSystemProvider { String MARKER_TYPE_ERROR = "" ; String MARKER_TYPE_WARNING = "" ; String MARKER_TYPE_INFO = "" ; String PATHFMT_FILESYSTEM = "" ; String PATHFMT_WORKSPACE = "" ; void init ( String root ) ; void dispose ( ) ; void addMarker ( String path , String type , int lineno , String msg ) ; void clearMarkers ( String path ) ; String resolvePath ( String path , String fmt ) ; boolean fileExists ( String path ) ; boolean isDir ( String path ) ; List < String > getFiles ( String path ) ; InputStream openStream ( String path ) ; void closeStream ( InputStream in ) ; long getLastModifiedTime ( String path ) ; void addFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) ; void removeFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) ; } package net . sf . sveditor . core . db . index ; public interface ISVDBFileSystemChangeListener { void fileChanged ( String path ) ; void fileRemoved ( String path ) ; void fileAdded ( String path ) ; } package net . sf . sveditor . core . db . index ; import java . io . InputStream ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ISVDBIndex extends ISVDBIndexIterator , ISVDBIncludeFileProvider , ISVDBDeclCache { public void init ( IProgressMonitor monitor ) ; Tuple < SVDBFile , SVDBFile > parse ( IProgressMonitor monitor , InputStream in , String path , List < SVDBMarker > markers ) ; void setEnableAutoRebuild ( boolean en ) ; boolean isDirty ( ) ; void dispose ( ) ; String getBaseLocation ( ) ; String getProject ( ) ; void setGlobalDefine ( String key , String val ) ; void clearGlobalDefines ( ) ; String getTypeID ( ) ; void setIncludeFileProvider ( ISVDBIncludeFileProvider inc_provider ) ; Iterable < String > getFileList ( IProgressMonitor monitor ) ; List < SVDBMarker > getMarkers ( String path ) ; SVDBFile findFile ( String path ) ; SVDBFile findPreProcFile ( String path ) ; void rebuildIndex ( IProgressMonitor monitor ) ; void addChangeListener ( ISVDBIndexChangeListener l ) ; void removeChangeListener ( ISVDBIndexChangeListener l ) ; ISVDBIndexCache getCache ( ) ; void loadIndex ( IProgressMonitor monitor ) ; boolean isLoaded ( ) ; boolean isFileListLoaded ( ) ; SVDBIndexConfig getConfig ( ) ; } package net . sf . sveditor . core . db . index ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import java . util . regex . Pattern ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBInclude ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerKind ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . SVDBPreProcCond ; import net . sf . sveditor . core . db . SVDBPreProcObserver ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . SVDBTypeInfoEnumerator ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . refs . ISVDBRefFinder ; import net . sf . sveditor . core . db . refs . ISVDBRefMatcher ; import net . sf . sveditor . core . db . refs . SVDBFileRefCollector ; import net . sf . sveditor . core . db . refs . SVDBRefCacheEntry ; import net . sf . sveditor . core . db . refs . SVDBRefCacheItem ; import net . sf . sveditor . core . db . refs . SVDBRefFinder ; import net . sf . sveditor . core . db . refs . SVDBRefItem ; import net . sf . sveditor . core . db . search . ISVDBFindNameMatcher ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . ILogLevelListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcDirectiveScanner ; import net . sf . sveditor . core . preproc . SVPreProcessor ; import net . sf . sveditor . core . scanner . FileContextSearchMacroProvider ; import net . sf . sveditor . core . scanner . IPreProcMacroProvider ; import net . sf . sveditor . core . scanner . SVFileTreeMacroProvider ; import net . sf . sveditor . core . scanner . SVPreProcDefineProvider ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . SubProgressMonitor ; public abstract class AbstractSVDBIndex implements ISVDBIndex , ISVDBRefFinder , ISVDBFileSystemChangeListener , ILogLevelListener , ILogLevel { private static final int IndexState_AllInvalid = ; private static final int IndexState_RootFilesDiscovered = ( IndexState_AllInvalid + ) ; private static final int IndexState_FilesPreProcessed = ( IndexState_RootFilesDiscovered + ) ; private static final int IndexState_FileTreeValid = ( IndexState_FilesPreProcessed + ) ; private static final int IndexState_AllFilesParsed = ( IndexState_FileTreeValid + ) ; public String fProjectName ; private String fBaseLocation ; private String fResolvedBaseLocation ; private String fBaseLocationDir ; private SVDBBaseIndexCacheData fIndexCacheData ; private boolean fCacheDataValid ; protected Set < String > fMissingIncludes ; protected List < Tuple < String , List < String > > > fDeferredPkgCacheFiles ; private ISVDBIncludeFileProvider fIncludeFileProvider ; private List < ISVDBIndexChangeListener > fIndexChangeListeners ; protected static Pattern fWinPathPattern ; protected LogHandle fLog ; private ISVDBFileSystemProvider fFileSystemProvider ; protected boolean fLoadUpToDate ; private ISVDBIndexCache fCache ; private SVDBIndexConfig fConfig ; private Set < String > fFileDirs ; private int fMaxIndexThreads = ; protected boolean fDebugEn ; protected boolean fInWorkspaceOk ; private int fIndexState ; protected boolean fAutoRebuildEn ; protected boolean fIsDirty ; static { fWinPathPattern = Pattern . compile ( "" ) ; } protected AbstractSVDBIndex ( String project ) { fIndexChangeListeners = new ArrayList < ISVDBIndexChangeListener > ( ) ; fProjectName = project ; fLog = LogFactory . getLogHandle ( getLogName ( ) ) ; fLog . addLogLevelListener ( this ) ; fDebugEn = fLog . isEnabled ( ) ; fMissingIncludes = new HashSet < String > ( ) ; fMaxIndexThreads = SVCorePlugin . getMaxIndexThreads ( ) ; fAutoRebuildEn = true ; fFileDirs = new HashSet < String > ( ) ; fDeferredPkgCacheFiles = new ArrayList < Tuple < String , List < String > > > ( ) ; } public AbstractSVDBIndex ( String project , String base_location , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { this ( project ) ; fBaseLocation = base_location ; fCache = cache ; fConfig = config ; setFileSystemProvider ( fs_provider ) ; fInWorkspaceOk = ( base_location . startsWith ( "" ) ) ; fAutoRebuildEn = true ; } public void logLevelChanged ( ILogHandle handle ) { fDebugEn = handle . isEnabled ( ) ; } public void setEnableAutoRebuild ( boolean en ) { fAutoRebuildEn = en ; } public boolean isDirty ( ) { return fIsDirty ; } protected abstract String getLogName ( ) ; @ SuppressWarnings ( "" ) protected boolean checkCacheValid ( ) { boolean valid = true ; String version = SVCorePlugin . getVersion ( ) ; if ( fDebugEn ) { fLog . debug ( "" + fIndexCacheData . getVersion ( ) + "" + version ) ; } if ( fIndexCacheData . getVersion ( ) == null || ! fIndexCacheData . getVersion ( ) . equals ( version ) ) { valid = false ; return valid ; } if ( fConfig != null ) { if ( fConfig . containsKey ( ISVDBIndexFactory . KEY_GlobalDefineMap ) ) { Map < String , String > define_map = ( Map < String , String > ) fConfig . get ( ISVDBIndexFactory . KEY_GlobalDefineMap ) ; if ( define_map . size ( ) != fIndexCacheData . getGlobalDefines ( ) . size ( ) ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" ) ; } valid = false ; } else { for ( Entry < String , String > e : define_map . entrySet ( ) ) { if ( fIndexCacheData . getGlobalDefines ( ) . containsKey ( e . getKey ( ) ) ) { if ( ! fIndexCacheData . getGlobalDefines ( ) . get ( e . getKey ( ) ) . equals ( e . getValue ( ) ) ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" + e . getKey ( ) + "" ) ; } valid = false ; break ; } } else { if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" + e . getKey ( ) + "" ) ; } valid = false ; break ; } } } } else if ( fIndexCacheData . getGlobalDefines ( ) . size ( ) > ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" ) ; } valid = false ; } } if ( fCache . getFileList ( ) . size ( ) > ) { for ( String path : fCache . getFileList ( ) ) { long fs_timestamp = fFileSystemProvider . getLastModifiedTime ( path ) ; long cache_timestamp = fCache . getLastModified ( path ) ; if ( fs_timestamp != cache_timestamp ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path + "" + fs_timestamp + "" + cache_timestamp ) ; } valid = false ; break ; } } } else { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + getBaseLocation ( ) + "" ) ; } SVDBIndexFactoryUtils . setBaseProperties ( fConfig , this ) ; valid = false ; } if ( getCacheData ( ) . getMissingIncludeFiles ( ) . size ( ) > && valid ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } for ( String path : getCacheData ( ) . getMissingIncludeFiles ( ) ) { SVDBSearchResult < SVDBFile > res = findIncludedFile ( path ) ; if ( res != null ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + getBaseLocation ( ) + "" + path ) ; } valid = false ; break ; } } } if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + getBaseLocation ( ) + "" + ( ( valid ) ? "" : "" ) ) ; } return valid ; } @ SuppressWarnings ( "" ) public void init ( IProgressMonitor monitor ) { SubProgressMonitor m ; monitor . beginTask ( "" + getBaseLocation ( ) , ) ; m = new SubProgressMonitor ( monitor , ) ; fIndexCacheData = createIndexCacheData ( ) ; fCacheDataValid = fCache . init ( m , fIndexCacheData ) ; if ( fCacheDataValid ) { fCacheDataValid = checkCacheValid ( ) ; } if ( fCacheDataValid ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } fIndexState = IndexState_FileTreeValid ; if ( fIndexCacheData . getDeclCacheMap ( ) != null ) { for ( Entry < String , List < SVDBDeclCacheItem > > e : fIndexCacheData . getDeclCacheMap ( ) . entrySet ( ) ) { for ( SVDBDeclCacheItem i : e . getValue ( ) ) { i . init ( this ) ; } } } if ( fIndexCacheData . getPackageCacheMap ( ) != null ) { for ( Entry < String , List < SVDBDeclCacheItem > > e : fIndexCacheData . getPackageCacheMap ( ) . entrySet ( ) ) { for ( SVDBDeclCacheItem i : e . getValue ( ) ) { i . init ( this ) ; } } } if ( fIndexCacheData . getReferenceCacheMap ( ) != null ) { for ( Entry < String , SVDBRefCacheEntry > e : fIndexCacheData . getReferenceCacheMap ( ) . entrySet ( ) ) { e . getValue ( ) . setFilename ( e . getKey ( ) ) ; } } for ( String f : fCache . getFileList ( ) ) { addFileDir ( f ) ; } } else { if ( fDebugEn ) { fLog . debug ( "" + getBaseLocation ( ) + "" ) ; } invalidateIndex ( m , "" , true ) ; } fIndexCacheData . setVersion ( SVCorePlugin . getVersion ( ) ) ; if ( fConfig != null && fConfig . containsKey ( ISVDBIndexFactory . KEY_GlobalDefineMap ) ) { Map < String , String > define_map = ( Map < String , String > ) fConfig . get ( ISVDBIndexFactory . KEY_GlobalDefineMap ) ; fIndexCacheData . clearGlobalDefines ( ) ; for ( String key : define_map . keySet ( ) ) { fIndexCacheData . setGlobalDefine ( key , define_map . get ( key ) ) ; } } monitor . done ( ) ; } public synchronized void loadIndex ( IProgressMonitor monitor ) { ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; } public synchronized boolean isLoaded ( ) { return ( fIndexState >= IndexState_AllFilesParsed ) ; } public synchronized boolean isFileListLoaded ( ) { return ( fIndexState >= IndexState_FileTreeValid ) ; } public synchronized void ensureIndexState ( IProgressMonitor super_monitor , int state ) { SubProgressMonitor monitor = new SubProgressMonitor ( super_monitor , ) ; monitor . beginTask ( "" + getBaseLocation ( ) , ) ; if ( fIndexState < IndexState_RootFilesDiscovered && state >= IndexState_RootFilesDiscovered ) { if ( fDebugEn ) { fLog . debug ( "" + fIndexState ) ; } SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; discoverRootFiles ( m ) ; fCache . sync ( ) ; fIndexState = IndexState_RootFilesDiscovered ; fIsDirty = false ; } if ( fIndexState < IndexState_FilesPreProcessed && state >= IndexState_FilesPreProcessed ) { if ( fDebugEn ) { fLog . debug ( "" + fIndexState ) ; } SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; preProcessFiles ( m ) ; fIndexState = IndexState_FilesPreProcessed ; fIsDirty = false ; } if ( fIndexState < IndexState_FileTreeValid && state >= IndexState_FileTreeValid ) { if ( fDebugEn ) { fLog . debug ( "" + fIndexState ) ; } SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; buildFileTree ( m ) ; fIndexState = IndexState_FileTreeValid ; propagateAllMarkers ( ) ; notifyIndexRebuilt ( ) ; fIsDirty = false ; } if ( fIndexState < IndexState_AllFilesParsed && state >= IndexState_AllFilesParsed ) { if ( fCacheDataValid ) { SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; fCache . initLoad ( m ) ; m . done ( ) ; } else { parseFiles ( monitor ) ; } fIndexState = IndexState_AllFilesParsed ; fIsDirty = false ; synchronized ( fDeferredPkgCacheFiles ) { for ( Tuple < String , List < String > > e : fDeferredPkgCacheFiles ) { if ( e . second ( ) . size ( ) > ) { fLog . debug ( "" + e . first ( ) + "" ) ; for ( String pkg : e . second ( ) ) { fLog . debug ( "" + pkg ) ; } } } } } monitor . done ( ) ; } protected void parseFiles ( IProgressMonitor monitor ) { final List < String > paths = new ArrayList < String > ( ) ; fLog . debug ( LEVEL_MAX , "" ) ; synchronized ( fCache ) { paths . addAll ( fCache . getFileList ( ) ) ; } final SubProgressMonitor m = new SubProgressMonitor ( monitor , ) ; m . beginTask ( "" , paths . size ( ) ) ; int num_threads = Math . min ( fMaxIndexThreads , paths . size ( ) / ) ; if ( fMaxIndexThreads <= || num_threads <= ) { parseFilesJob ( paths , m ) ; } else { Thread threads [ ] = new Thread [ num_threads ] ; for ( int i = ; i < threads . length ; i ++ ) { threads [ i ] = new Thread ( new Runnable ( ) { public void run ( ) { parseFilesJob ( paths , m ) ; } } , "" + getBaseLocation ( ) + "" + i ) ; threads [ i ] . setPriority ( Thread . MAX_PRIORITY ) ; threads [ i ] . start ( ) ; } join_threads ( threads ) ; } m . done ( ) ; } protected void parseFilesJob ( List < String > paths , IProgressMonitor monitor ) { while ( true ) { String path = null ; synchronized ( paths ) { if ( paths . size ( ) > ) { path = paths . remove ( ) ; } } if ( path == null ) { break ; } SVDBFile ret ; synchronized ( fCache ) { ret = fCache . getFile ( new NullProgressMonitor ( ) , path ) ; } if ( ret == null ) { SVDBFileTree ft_root ; synchronized ( fCache ) { ft_root = fCache . getFileTree ( new NullProgressMonitor ( ) , path ) ; } if ( ft_root == null ) { try { throw new Exception ( ) ; } catch ( Exception e ) { fLog . error ( "" + path + "" + getBaseLocation ( ) , e ) ; for ( String p : getFileList ( new NullProgressMonitor ( ) ) ) { fLog . error ( "" + p ) ; } } } if ( ft_root != null ) { IPreProcMacroProvider mp = createMacroProvider ( ft_root ) ; processFile ( ft_root , mp ) ; } synchronized ( fCache ) { ret = fCache . getFile ( new NullProgressMonitor ( ) , path ) ; } } synchronized ( monitor ) { monitor . worked ( ) ; } } } protected void invalidateIndex ( IProgressMonitor monitor , String reason , boolean force ) { if ( fDebugEn ) { if ( fAutoRebuildEn || force ) { fLog . debug ( LEVEL_MIN , "" + ( ( reason == null ) ? "" : reason ) ) ; } else { fLog . debug ( LEVEL_MIN , "" + ( ( reason == null ) ? "" : reason ) + "" ) ; } } if ( fAutoRebuildEn || force ) { fIndexState = IndexState_AllInvalid ; fCacheDataValid = false ; fIndexCacheData . clear ( ) ; fCache . clear ( monitor ) ; fMissingIncludes . clear ( ) ; fDeferredPkgCacheFiles . clear ( ) ; } else { fIsDirty = true ; } } public void rebuildIndex ( IProgressMonitor monitor ) { invalidateIndex ( monitor , "" , true ) ; } public ISVDBIndexCache getCache ( ) { return fCache ; } public SVDBIndexConfig getConfig ( ) { return fConfig ; } protected SVDBBaseIndexCacheData getCacheData ( ) { return fIndexCacheData ; } public void setFileSystemProvider ( ISVDBFileSystemProvider fs_provider ) { if ( fFileSystemProvider != null && fs_provider != fFileSystemProvider ) { fFileSystemProvider . removeFileSystemChangeListener ( this ) ; } fFileSystemProvider = fs_provider ; if ( fFileSystemProvider != null ) { fFileSystemProvider . init ( getResolvedBaseLocationDir ( ) ) ; fFileSystemProvider . addFileSystemChangeListener ( this ) ; } } public ISVDBFileSystemProvider getFileSystemProvider ( ) { return fFileSystemProvider ; } public void fileChanged ( String path ) { synchronized ( fCache ) { if ( fCache . getFileList ( ) . contains ( path ) ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path ) ; } fCache . setFile ( path , null ) ; fCache . setLastModified ( path , getFileSystemProvider ( ) . getLastModifiedTime ( path ) ) ; } } } public void fileRemoved ( String path ) { synchronized ( fCache ) { if ( fCache . getFileList ( ) . contains ( path ) ) { invalidateIndex ( new NullProgressMonitor ( ) , "" , false ) ; } } } public void fileAdded ( String path ) { File f = new File ( path ) ; File p = f . getParentFile ( ) ; if ( fDebugEn ) { fLog . debug ( LEVEL_MIN , "" + path ) ; } if ( fFileDirs . contains ( p . getPath ( ) ) ) { invalidateIndex ( new NullProgressMonitor ( ) , "" , false ) ; } } public String getBaseLocation ( ) { return fBaseLocation ; } public String getProject ( ) { return fProjectName ; } public String getResolvedBaseLocation ( ) { if ( fResolvedBaseLocation == null ) { fResolvedBaseLocation = SVDBIndexUtil . expandVars ( fBaseLocation , fProjectName , fInWorkspaceOk ) ; } return fResolvedBaseLocation ; } public String getResolvedBaseLocationDir ( ) { if ( fBaseLocationDir == null ) { String base_location = getResolvedBaseLocation ( ) ; if ( fDebugEn ) { fLog . debug ( "" + base_location ) ; } if ( fFileSystemProvider . isDir ( base_location ) ) { if ( fDebugEn ) { fLog . debug ( "" + base_location + "" ) ; } fBaseLocationDir = base_location ; } else { if ( fDebugEn ) { fLog . debug ( "" + base_location + "" ) ; } fBaseLocationDir = SVFileUtils . getPathParent ( base_location ) ; if ( fDebugEn ) { fLog . debug ( "" + base_location + "" + fBaseLocationDir ) ; } } } return fBaseLocationDir ; } public void setGlobalDefine ( String key , String val ) { if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" + key + "" + val + "" ) ; } fIndexCacheData . setGlobalDefine ( key , val ) ; if ( ! fIndexCacheData . getGlobalDefines ( ) . containsKey ( key ) || ! fIndexCacheData . getGlobalDefines ( ) . get ( key ) . equals ( val ) ) { rebuildIndex ( new NullProgressMonitor ( ) ) ; } } public void clearGlobalDefines ( ) { fIndexCacheData . clearGlobalDefines ( ) ; } protected void clearDefines ( ) { fIndexCacheData . clearDefines ( ) ; } protected void addDefine ( String key , String val ) { fIndexCacheData . addDefine ( key , val ) ; } protected void clearIncludePaths ( ) { fIndexCacheData . clearIncludePaths ( ) ; } protected void addIncludePath ( String path ) { fIndexCacheData . addIncludePath ( path ) ; } public Iterable < String > getFileList ( IProgressMonitor monitor ) { ensureIndexState ( monitor , IndexState_FileTreeValid ) ; return fCache . getFileList ( ) ; } public SVDBFile findFile ( IProgressMonitor monitor , String path ) { String r_path = path ; SVDBFile ret = null ; ensureIndexState ( monitor , IndexState_FileTreeValid ) ; for ( String fmt : new String [ ] { null , ISVDBFileSystemProvider . PATHFMT_WORKSPACE , ISVDBFileSystemProvider . PATHFMT_FILESYSTEM } ) { if ( fmt != null ) { r_path = fFileSystemProvider . resolvePath ( path , fmt ) ; } synchronized ( fCache ) { ret = fCache . getFile ( monitor , r_path ) ; } if ( ret != null ) { break ; } } if ( ret == null ) { SVDBFileTree ft_root ; synchronized ( fCache ) { ft_root = fCache . getFileTree ( monitor , path ) ; } if ( ft_root != null ) { IPreProcMacroProvider mp = createMacroProvider ( ft_root ) ; processFile ( ft_root , mp ) ; synchronized ( fCache ) { ret = fCache . getFile ( monitor , path ) ; } } else { } } return ret ; } public SVDBFile findPreProcFile ( IProgressMonitor monitor , String path ) { String r_path = path ; SVDBFile file = null ; ensureIndexState ( monitor , IndexState_FileTreeValid ) ; for ( String fmt : new String [ ] { null , ISVDBFileSystemProvider . PATHFMT_WORKSPACE , ISVDBFileSystemProvider . PATHFMT_FILESYSTEM } ) { if ( fmt != null ) { r_path = fFileSystemProvider . resolvePath ( path , fmt ) ; } file = fCache . getPreProcFile ( new NullProgressMonitor ( ) , r_path ) ; if ( file != null ) { break ; } } return file ; } public synchronized List < SVDBMarker > getMarkers ( String path ) { findFile ( path ) ; return fCache . getMarkers ( path ) ; } protected void addFile ( String path ) { synchronized ( fCache ) { fCache . addFile ( path ) ; fCache . setLastModified ( path , getFileSystemProvider ( ) . getLastModifiedTime ( path ) ) ; } addFileDir ( path ) ; } protected void addFileDir ( String file_path ) { File f = new File ( file_path ) ; File p = f . getParentFile ( ) ; if ( p != null && ! fFileDirs . contains ( p . getPath ( ) ) ) { fFileDirs . add ( p . getPath ( ) ) ; } } protected void clearFilesList ( ) { fCache . clear ( new NullProgressMonitor ( ) ) ; fFileDirs . clear ( ) ; } protected void propagateAllMarkers ( ) { Set < String > file_list = fCache . getFileList ( ) ; for ( String path : file_list ) { if ( path != null ) { propagateMarkers ( path ) ; } } } protected void propagateMarkers ( String path ) { List < SVDBMarker > ml = fCache . getMarkers ( path ) ; getFileSystemProvider ( ) . clearMarkers ( path ) ; if ( ml != null ) { for ( SVDBMarker m : ml ) { String type = null ; switch ( m . getMarkerType ( ) ) { case Info : type = ISVDBFileSystemProvider . MARKER_TYPE_INFO ; break ; case Warning : type = ISVDBFileSystemProvider . MARKER_TYPE_WARNING ; break ; case Error : type = ISVDBFileSystemProvider . MARKER_TYPE_ERROR ; break ; } getFileSystemProvider ( ) . addMarker ( path , type , m . getLocation ( ) . getLine ( ) , m . getMessage ( ) ) ; } } } protected SVDBBaseIndexCacheData createIndexCacheData ( ) { return new SVDBBaseIndexCacheData ( getBaseLocation ( ) ) ; } protected abstract void discoverRootFiles ( IProgressMonitor monitor ) ; protected void preProcessFiles ( final IProgressMonitor monitor ) { final List < String > paths = new ArrayList < String > ( ) ; synchronized ( fCache ) { paths . addAll ( fCache . getFileList ( ) ) ; } monitor . beginTask ( "" , paths . size ( ) ) ; int num_threads = Math . min ( fMaxIndexThreads , paths . size ( ) / ) ; if ( fMaxIndexThreads <= || num_threads <= ) { preProcessFilesJob ( paths , monitor ) ; } else { Thread threads [ ] = new Thread [ num_threads ] ; for ( int i = ; i < threads . length ; i ++ ) { threads [ i ] = new Thread ( new Runnable ( ) { public void run ( ) { preProcessFilesJob ( paths , monitor ) ; } } ) ; threads [ i ] . start ( ) ; } join_threads ( threads ) ; } monitor . done ( ) ; } private void join_threads ( Thread threads [ ] ) { for ( int i = ; i < threads . length ; i ++ ) { if ( threads [ i ] . isAlive ( ) ) { try { threads [ i ] . join ( ) ; } catch ( InterruptedException e ) { } } } } protected void preProcessFilesJob ( List < String > paths , IProgressMonitor monitor ) { while ( true ) { String path = null ; synchronized ( paths ) { if ( paths . size ( ) > ) { path = paths . remove ( ) ; } } if ( path == null ) { break ; } SubProgressMonitor m = null ; synchronized ( monitor ) { m = new SubProgressMonitor ( monitor , ) ; m . beginTask ( "" + path , ) ; } SVDBFile file = processPreProcFile ( path ) ; synchronized ( fCache ) { fCache . setPreProcFile ( path , file ) ; fCache . setLastModified ( path , fFileSystemProvider . getLastModifiedTime ( path ) ) ; } synchronized ( monitor ) { m . done ( ) ; } } } protected void buildFileTree ( final IProgressMonitor monitor ) { final List < String > paths = new ArrayList < String > ( ) ; paths . addAll ( getCache ( ) . getFileList ( ) ) ; final List < String > missing_includes = new ArrayList < String > ( ) ; fLog . debug ( LEVEL_MAX , "" ) ; monitor . beginTask ( "" , paths . size ( ) ) ; int num_threads = Math . min ( fMaxIndexThreads , paths . size ( ) / ) ; if ( fMaxIndexThreads <= || num_threads <= ) { buildFileTreeJob ( paths , missing_includes , monitor ) ; } else { Thread threads [ ] = new Thread [ num_threads ] ; for ( int i = ; i < threads . length ; i ++ ) { threads [ i ] = new Thread ( new Runnable ( ) { public void run ( ) { buildFileTreeJob ( paths , missing_includes , monitor ) ; } } , "" + getBaseLocation ( ) + "" + i ) ; threads [ i ] . start ( ) ; } boolean threads_alive = true ; while ( threads_alive ) { threads_alive = false ; for ( int i = ; i < threads . length ; i ++ ) { if ( threads [ i ] . isAlive ( ) ) { try { threads [ i ] . join ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; threads_alive = true ; } } } } } getCacheData ( ) . clearMissingIncludeFiles ( ) ; for ( String path : missing_includes ) { getCacheData ( ) . addMissingIncludeFile ( path ) ; } monitor . done ( ) ; } protected void buildFileTreeJob ( List < String > paths , List < String > missing_includes , IProgressMonitor monitor ) { while ( true ) { String path = null ; synchronized ( paths ) { if ( paths . size ( ) > ) { path = paths . remove ( ) ; } } if ( path == null ) { break ; } synchronized ( fCache ) { if ( fCache . getFileTree ( new NullProgressMonitor ( ) , path ) != null ) { continue ; } } SVDBFile pp_file ; synchronized ( fCache ) { pp_file = fCache . getPreProcFile ( new NullProgressMonitor ( ) , path ) ; } if ( pp_file == null ) { fLog . error ( "" + path + "" ) ; } else { SVDBFileTree ft_root = new SVDBFileTree ( ( SVDBFile ) pp_file . duplicate ( ) ) ; Set < String > included_files = new HashSet < String > ( ) ; Map < String , SVDBFileTree > working_set = new HashMap < String , SVDBFileTree > ( ) ; buildPreProcFileMap ( null , ft_root , missing_includes , included_files , working_set ) ; } } } protected void buildPreProcFileMap ( SVDBFileTree parent , SVDBFileTree root , List < String > missing_includes , Set < String > included_files , Map < String , SVDBFileTree > working_set ) { SVDBFileTreeUtils ft_utils = new SVDBFileTreeUtils ( ) ; if ( fDebugEn ) { fLog . debug ( "" + root . getFilePath ( ) ) ; } if ( ! working_set . containsKey ( root . getFilePath ( ) ) ) { working_set . put ( root . getFilePath ( ) , root ) ; } synchronized ( fCache ) { if ( ! working_set . containsKey ( root . getFilePath ( ) ) ) { System . out . println ( "" + root . getFilePath ( ) + "" ) ; } fCache . setFileTree ( root . getFilePath ( ) , root ) ; } if ( parent != null ) { root . getIncludedByFiles ( ) . add ( parent . getFilePath ( ) ) ; } synchronized ( root ) { ft_utils . resolveConditionals ( root , new SVPreProcDefineProvider ( createPreProcMacroProvider ( root , working_set ) ) ) ; } List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; included_files . add ( root . getFilePath ( ) ) ; addPreProcFileIncludeFiles ( root , root . getSVDBFile ( ) , markers , missing_includes , included_files , working_set ) ; synchronized ( fCache ) { fCache . setFileTree ( root . getFilePath ( ) , root ) ; fCache . setMarkers ( root . getFilePath ( ) , markers ) ; } } private void addPreProcFileIncludeFiles ( SVDBFileTree root , ISVDBScopeItem scope , List < SVDBMarker > markers , List < String > missing_includes , Set < String > included_files , Map < String , SVDBFileTree > working_set ) { for ( int i = ; i < scope . getItems ( ) . size ( ) ; i ++ ) { ISVDBItemBase it = scope . getItems ( ) . get ( i ) ; if ( it . getType ( ) == SVDBItemType . Include ) { if ( fDebugEn ) { fLog . debug ( "" + ( ( ISVDBNamedItem ) it ) . getName ( ) ) ; } SVDBSearchResult < SVDBFile > f = findIncludedFileGlobal ( ( ( ISVDBNamedItem ) it ) . getName ( ) ) ; if ( f != null ) { if ( fDebugEn ) { fLog . debug ( "" + ( ( ISVDBNamedItem ) it ) . getName ( ) + "" + f . getIndex ( ) . getBaseLocation ( ) + "" ) ; } String file_path = f . getItem ( ) . getFilePath ( ) ; if ( fDebugEn ) { fLog . debug ( "" + file_path + "" + root . getFilePath ( ) + "" ) ; } SVDBFileTree ft = new SVDBFileTree ( ( SVDBFile ) f . getItem ( ) . duplicate ( ) ) ; root . addIncludedFile ( ft . getFilePath ( ) ) ; if ( fDebugEn ) { fLog . debug ( "" + ft . getIncludedFiles ( ) . size ( ) + "" ) ; } if ( ! included_files . contains ( f . getItem ( ) . getFilePath ( ) ) ) { buildPreProcFileMap ( root , ft , missing_includes , included_files , working_set ) ; } } else { String missing_path = ( ( ISVDBNamedItem ) it ) . getName ( ) ; if ( fDebugEn ) { fLog . debug ( "" + missing_path + "" + root . getFilePath ( ) + "" ) ; } synchronized ( missing_includes ) { if ( ! missing_includes . contains ( missing_path ) ) { missing_includes . add ( missing_path ) ; } } SVDBFileTree ft = new SVDBFileTree ( SVDBItem . getName ( it ) ) ; root . addIncludedFile ( ft . getFilePath ( ) ) ; ft . getIncludedByFiles ( ) . add ( root . getFilePath ( ) ) ; SVDBMarker err = new SVDBMarker ( MarkerType . Error , MarkerKind . MissingInclude , "" + ( ( ISVDBNamedItem ) it ) . getName ( ) + "" ) ; err . setLocation ( it . getLocation ( ) ) ; markers . add ( err ) ; } } else if ( it instanceof ISVDBScopeItem ) { addPreProcFileIncludeFiles ( root , ( ISVDBScopeItem ) it , markers , missing_includes , included_files , working_set ) ; } } } public SVDBSearchResult < SVDBFile > findIncludedFile ( String path ) { SVDBFile file = null ; if ( fDebugEn ) { fLog . debug ( "" + path ) ; } if ( fDebugEn ) { fLog . debug ( "" ) ; } for ( String inc_dir : fIndexCacheData . getIncludePaths ( ) ) { String inc_path = resolvePath ( inc_dir + "" + path , fInWorkspaceOk ) ; if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" ) ; } if ( ( file = fCache . getPreProcFile ( new NullProgressMonitor ( ) , inc_path ) ) != null ) { if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" ) ; } break ; } } if ( file != null ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } return new SVDBSearchResult < SVDBFile > ( file , this ) ; } for ( String inc_dir : fIndexCacheData . getIncludePaths ( ) ) { String inc_path = resolvePath ( inc_dir + "" + path , fInWorkspaceOk ) ; if ( fFileSystemProvider . fileExists ( inc_path ) ) { if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" ) ; } file = processPreProcFile ( inc_path ) ; addFile ( inc_path ) ; fCache . setPreProcFile ( inc_path , file ) ; fCache . setLastModified ( inc_path , fFileSystemProvider . getLastModifiedTime ( inc_path ) ) ; break ; } else { if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" ) ; } } } if ( file != null ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } return new SVDBSearchResult < SVDBFile > ( file , this ) ; } String res_path = resolvePath ( path , fInWorkspaceOk ) ; if ( fFileSystemProvider . fileExists ( res_path ) ) { SVDBFile pp_file = null ; if ( ( pp_file = processPreProcFile ( res_path ) ) != null ) { if ( fDebugEn ) { fLog . debug ( "" + path + "" ) ; } addFile ( res_path ) ; return new SVDBSearchResult < SVDBFile > ( pp_file , this ) ; } } return null ; } protected String resolvePath ( String path_orig , boolean in_workspace_ok ) { String path = path_orig ; String norm_path = null ; if ( fDebugEn ) { fLog . debug ( "" + path_orig ) ; } if ( path . startsWith ( "" ) ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } if ( ( norm_path = resolveRelativePath ( getResolvedBaseLocationDir ( ) , path ) ) == null ) { for ( String inc_path : fIndexCacheData . getIncludePaths ( ) ) { if ( fDebugEn ) { fLog . debug ( "" + inc_path + "" + path ) ; } if ( ( norm_path = resolveRelativePath ( inc_path , path ) ) != null ) { break ; } } } else { if ( fDebugEn ) { fLog . debug ( "" + norm_path ) ; } } } else { if ( path . equals ( "" ) ) { path = getResolvedBaseLocationDir ( ) ; } else if ( path . startsWith ( "" ) ) { path = getResolvedBaseLocationDir ( ) + "" + path . substring ( ) ; } else { if ( ! fFileSystemProvider . fileExists ( path ) ) { String imp_path = getResolvedBaseLocationDir ( ) + "" + path ; if ( fFileSystemProvider . fileExists ( imp_path ) ) { path = imp_path ; } } } norm_path = normalizePath ( path ) ; } if ( norm_path != null && ! norm_path . startsWith ( "" ) && in_workspace_ok ) { IWorkspaceRoot ws_root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IFile file = ws_root . getFileForLocation ( new Path ( norm_path ) ) ; if ( file != null && file . exists ( ) ) { norm_path = "" + file . getFullPath ( ) . toOSString ( ) ; } } return ( norm_path != null ) ? norm_path : path_orig ; } private String resolveRelativePath ( String base , String path ) { String norm_path = normalizePath ( base + "" + path ) ; if ( fDebugEn ) { fLog . debug ( "" + norm_path + "" + getResolvedBaseLocationDir ( ) ) ; } if ( fFileSystemProvider . fileExists ( norm_path ) ) { return norm_path ; } else if ( getBaseLocation ( ) . startsWith ( "" ) ) { String base_loc = getResolvedBaseLocationDir ( ) ; if ( fDebugEn ) { fLog . debug ( "" + base_loc ) ; } base_loc = base_loc . substring ( "" . length ( ) ) ; if ( fDebugEn ) { fLog . debug ( "" + base_loc ) ; } IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IContainer base_dir = null ; try { base_dir = root . getFolder ( new Path ( base_loc ) ) ; } catch ( IllegalArgumentException e ) { } if ( base_dir == null ) { if ( base_loc . length ( ) > ) { base_dir = root . getProject ( base_loc . substring ( ) ) ; } } if ( fDebugEn ) { fLog . debug ( "" + base_dir ) ; } if ( base_dir != null && base_dir . exists ( ) ) { IPath base_dir_p = base_dir . getLocation ( ) ; if ( base_dir_p != null ) { File path_f_t = new File ( base_dir_p . toFile ( ) , path ) ; try { if ( path_f_t . exists ( ) ) { if ( fDebugEn ) { fLog . debug ( "" + path_f_t . getCanonicalPath ( ) ) ; } norm_path = SVFileUtils . normalize ( path_f_t . getCanonicalPath ( ) ) ; return norm_path ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } return null ; } protected String normalizePath ( String path ) { StringBuilder ret = new StringBuilder ( ) ; int i = path . length ( ) - ; int end ; int skipCnt = ; while ( i >= && ( path . charAt ( i ) == '' || path . charAt ( i ) == '' ) ) { i -- ; } while ( i >= ) { end = ret . length ( ) ; while ( i >= && path . charAt ( i ) != '' && path . charAt ( i ) != '' ) { ret . append ( path . charAt ( i ) ) ; i -- ; } if ( i != - ) { ret . append ( "" ) ; i -- ; } if ( ( ret . length ( ) - end ) > ) { String str = ret . substring ( end , ret . length ( ) - ) ; if ( str . equals ( "" ) ) { skipCnt ++ ; ret . setLength ( end ) ; } else if ( skipCnt > ) { ret . setLength ( end ) ; skipCnt -- ; } } } return ret . reverse ( ) . toString ( ) ; } public void setIncludeFileProvider ( ISVDBIncludeFileProvider provider ) { fIncludeFileProvider = provider ; } public void addChangeListener ( ISVDBIndexChangeListener l ) { synchronized ( fIndexChangeListeners ) { fIndexChangeListeners . add ( l ) ; } } public void removeChangeListener ( ISVDBIndexChangeListener l ) { synchronized ( fIndexChangeListeners ) { fIndexChangeListeners . remove ( l ) ; } } protected void notifyIndexRebuilt ( ) { synchronized ( fIndexChangeListeners ) { for ( ISVDBIndexChangeListener l : fIndexChangeListeners ) { l . index_rebuilt ( ) ; } } } protected IPreProcMacroProvider createMacroProvider ( SVDBFileTree file_tree ) { SVFileTreeMacroProvider mp = new SVFileTreeMacroProvider ( fCache , file_tree , fMissingIncludes ) ; for ( Entry < String , String > entry : fIndexCacheData . getGlobalDefines ( ) . entrySet ( ) ) { mp . setMacro ( entry . getKey ( ) , entry . getValue ( ) ) ; } for ( Entry < String , String > entry : fIndexCacheData . getDefines ( ) . entrySet ( ) ) { mp . setMacro ( entry . getKey ( ) , entry . getValue ( ) ) ; } return mp ; } protected IPreProcMacroProvider createPreProcMacroProvider ( SVDBFileTree file , Map < String , SVDBFileTree > working_set ) { FileContextSearchMacroProvider mp = new FileContextSearchMacroProvider ( fCache , working_set ) ; mp . setFileContext ( file ) ; for ( Entry < String , String > entry : fIndexCacheData . getGlobalDefines ( ) . entrySet ( ) ) { mp . setMacro ( entry . getKey ( ) , entry . getValue ( ) ) ; } for ( Entry < String , String > entry : fIndexCacheData . getDefines ( ) . entrySet ( ) ) { mp . setMacro ( entry . getKey ( ) , entry . getValue ( ) ) ; } return mp ; } public SVDBSearchResult < SVDBFile > findIncludedFileGlobal ( String leaf ) { SVDBSearchResult < SVDBFile > ret = findIncludedFile ( leaf ) ; if ( ret == null ) { if ( fIncludeFileProvider != null ) { ret = fIncludeFileProvider . findIncludedFile ( leaf ) ; if ( fDebugEn ) { fLog . debug ( "" + leaf + "" + ret + "" ) ; } } else { if ( fDebugEn ) { fLog . debug ( "" ) ; } } } return ret ; } public Tuple < SVDBFile , SVDBFile > parse ( IProgressMonitor monitor , InputStream in , String path , List < SVDBMarker > markers ) { if ( markers == null ) { markers = new ArrayList < SVDBMarker > ( ) ; } SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( null ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( dp ) ; path = SVFileUtils . normalize ( path ) ; SVDBFileTree file_tree = findFileTree ( path ) ; if ( file_tree == null ) { if ( getFileSystemProvider ( ) . fileExists ( path ) ) { invalidateIndex ( new NullProgressMonitor ( ) , "" + path , false ) ; addFile ( path ) ; file_tree = findFileTree ( path ) ; if ( file_tree == null && ! fAutoRebuildEn ) { file_tree = incrCreateFileTree ( path ) ; } } else { return null ; } } markers . clear ( ) ; List < SVDBMarker > markers_e = fCache . getMarkers ( path ) ; if ( markers_e != null ) { for ( SVDBMarker m : markers_e ) { if ( m . getKind ( ) == MarkerKind . MissingInclude ) { markers . add ( m ) ; } } } InputStreamCopier copier = new InputStreamCopier ( in ) ; in = null ; SVPreProcDirectiveScanner sc = new SVPreProcDirectiveScanner ( ) ; SVDBPreProcObserver ob = new SVDBPreProcObserver ( ) ; sc . setObserver ( ob ) ; file_tree = file_tree . duplicate ( ) ; sc . init ( copier . copy ( ) , path ) ; sc . process ( ) ; SVDBFile svdb_pp = ob . getFiles ( ) . get ( ) ; if ( fDebugEn ) { fLog . debug ( "" ) ; } file_tree . setSVDBFile ( svdb_pp ) ; if ( file_tree . getFilePath ( ) == null ) { System . out . println ( "" + path + "" ) ; } dp . setMacroProvider ( createMacroProvider ( file_tree ) ) ; SVDBFile svdb_f = factory . parse ( copier . copy ( ) , file_tree . getFilePath ( ) , markers ) ; if ( svdb_f . getFilePath ( ) == null ) { System . out . println ( "" + path + "" ) ; } return new Tuple < SVDBFile , SVDBFile > ( svdb_pp , svdb_f ) ; } public ISVDBItemIterator getItemIterator ( IProgressMonitor monitor ) { return new SVDBIndexItemIterator ( getFileList ( new NullProgressMonitor ( ) ) , this ) ; } public SVDBFile findFile ( String path ) { return findFile ( new NullProgressMonitor ( ) , path ) ; } protected void processFile ( SVDBFileTree path , IPreProcMacroProvider mp ) { SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( mp ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( dp ) ; fLog . debug ( LEVEL_MAX , "" + path . getFilePath ( ) ) ; String path_s = path . getFilePath ( ) ; InputStream in = fFileSystemProvider . openStream ( path_s ) ; if ( in == null ) { fLog . error ( "" + path_s + "" ) ; } List < SVDBMarker > markers = fCache . getMarkers ( path . getFilePath ( ) ) ; if ( markers == null ) { markers = new ArrayList < SVDBMarker > ( ) ; } for ( int i = ; i < markers . size ( ) ; i ++ ) { if ( markers . get ( i ) . getKind ( ) == MarkerKind . UndefinedMacro || markers . get ( i ) . getKind ( ) == MarkerKind . ParseError ) { markers . remove ( i ) ; i -- ; } } SVDBFile svdb_f = factory . parse ( in , path . getFilePath ( ) , markers ) ; if ( svdb_f == null ) { return ; } fFileSystemProvider . clearMarkers ( path_s ) ; fCache . setFile ( path . getFilePath ( ) , svdb_f ) ; fCache . setLastModified ( path . getFilePath ( ) , fFileSystemProvider . getLastModifiedTime ( path . getFilePath ( ) ) ) ; fCache . setMarkers ( path . getFilePath ( ) , markers ) ; fFileSystemProvider . closeStream ( in ) ; propagateMarkers ( path . getFilePath ( ) ) ; cacheDeclarations ( svdb_f ) ; cacheReferences ( svdb_f ) ; } public synchronized SVDBFile findPreProcFile ( String path ) { return findPreProcFile ( new NullProgressMonitor ( ) , path ) ; } protected SVDBFile processPreProcFile ( String path ) { SVPreProcDirectiveScanner sc = new SVPreProcDirectiveScanner ( ) ; SVDBPreProcObserver ob = new SVDBPreProcObserver ( ) ; sc . setObserver ( ob ) ; fLog . debug ( "" + path ) ; InputStream in = fFileSystemProvider . openStream ( path ) ; if ( in == null ) { fLog . error ( getClass ( ) . getName ( ) + "" + path + "" ) ; return null ; } sc . init ( in , path ) ; sc . process ( ) ; getFileSystemProvider ( ) . closeStream ( in ) ; SVDBFile file = ob . getFiles ( ) . get ( ) ; return file ; } public synchronized SVDBFileTree findFileTree ( String path ) { ensureIndexState ( new NullProgressMonitor ( ) , IndexState_FileTreeValid ) ; SVDBFileTree ft = fCache . getFileTree ( new NullProgressMonitor ( ) , path ) ; return ft ; } protected SVDBFileTree incrCreateFileTree ( String path ) { SVDBFileTree ft = new SVDBFileTree ( path ) ; synchronized ( fCache ) { fCache . setFileTree ( path , ft ) ; } return ft ; } public void dispose ( ) { fLog . debug ( "" + getBaseLocation ( ) ) ; if ( fCache != null ) { fCache . sync ( ) ; } if ( fFileSystemProvider != null ) { fFileSystemProvider . dispose ( ) ; } } public Iterable < String > getFileNames ( IProgressMonitor monitor ) { return new Iterable < String > ( ) { public Iterator < String > iterator ( ) { return fCache . getFileList ( ) . iterator ( ) ; } } ; } protected void cacheDeclarations ( SVDBFile file ) { Map < String , List < SVDBDeclCacheItem > > decl_cache = fIndexCacheData . getDeclCacheMap ( ) ; if ( fDebugEn ) { fLog . debug ( LEVEL_MID , "" + file . getFilePath ( ) ) ; } if ( ! decl_cache . containsKey ( file . getFilePath ( ) ) ) { decl_cache . put ( file . getFilePath ( ) , new ArrayList < SVDBDeclCacheItem > ( ) ) ; } else { decl_cache . get ( file . getFilePath ( ) ) . clear ( ) ; } Tuple < String , List < String > > t = null ; synchronized ( fDeferredPkgCacheFiles ) { for ( Tuple < String , List < String > > tp : fDeferredPkgCacheFiles ) { if ( tp . first ( ) . equals ( file . getFilePath ( ) ) ) { t = tp ; break ; } } } if ( t != null ) { synchronized ( fDeferredPkgCacheFiles ) { fDeferredPkgCacheFiles . remove ( t ) ; } for ( String pkgname : t . second ( ) ) { Map < String , List < SVDBDeclCacheItem > > pkg_map = fIndexCacheData . getPackageCacheMap ( ) ; List < SVDBDeclCacheItem > pkgitem_list = pkg_map . get ( pkgname ) ; Set < String > processed_files = new HashSet < String > ( ) ; if ( fDebugEn ) { fLog . debug ( "" + pkgname + "" + file . getFilePath ( ) + "" ) ; } cachePkgDeclIncFile ( processed_files , pkgname , pkgitem_list , file . getFilePath ( ) ) ; } } Set < String > processed_files = new HashSet < String > ( ) ; processed_files . add ( file . getFilePath ( ) ) ; cacheDeclarations ( processed_files , file . getFilePath ( ) , decl_cache . get ( file . getFilePath ( ) ) , null , null , file , false ) ; SVDBFileTree ft = findFileTree ( file . getFilePath ( ) ) ; if ( ft != null ) { cacheDeclarations ( processed_files , file . getFilePath ( ) , decl_cache . get ( file . getFilePath ( ) ) , null , null , ft . getSVDBFile ( ) , true ) ; } } private void cachePkgDeclFileTree ( ISVDBChildParent scope , List < SVDBDeclCacheItem > pkgitem_list , SVDBPackageDecl pkg ) { int pkg_start = ( pkg . getLocation ( ) != null ) ? pkg . getLocation ( ) . getLine ( ) : ; int pkg_end = ( pkg . getEndLocation ( ) != null ) ? pkg . getEndLocation ( ) . getLine ( ) : - ; Set < String > processed_files = new HashSet < String > ( ) ; fLog . debug ( "" + pkg . getName ( ) + "" + pkg_start + "" + pkg_end ) ; for ( ISVDBChildItem item : scope . getChildren ( ) ) { int line = ( item . getLocation ( ) != null ) ? ( item . getLocation ( ) . getLine ( ) ) : - ; if ( fDebugEn ) { fLog . debug ( "" + item . getType ( ) + "" + line + "" + pkg_start + "" + pkg_end + "" ) ; } if ( item . getType ( ) . equals ( SVDBItemType . Include ) && line >= pkg_start && line <= pkg_end ) { cachePkgDeclIncFile ( processed_files , pkg . getName ( ) , pkgitem_list , ( ( SVDBInclude ) item ) . getName ( ) ) ; } else if ( item instanceof ISVDBChildParent ) { cachePkgDeclFileTree ( ( ISVDBChildParent ) item , pkgitem_list , pkg ) ; } } fLog . debug ( "" + pkg . getName ( ) + "" + pkg_start + "" + pkg_end ) ; } private void cachePkgDeclIncFile ( Set < String > processed_files , String pkgname , List < SVDBDeclCacheItem > pkgitem_list , String inc ) { if ( fDebugEn ) { fLog . debug ( "" + inc + "" ) ; } SVDBFile abs_pp_file = fCache . getPreProcFile ( new NullProgressMonitor ( ) , inc ) ; if ( abs_pp_file != null ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } } else { if ( fDebugEn ) { fLog . debug ( "" ) ; } SVDBSearchResult < SVDBFile > r = findIncludedFile ( inc ) ; if ( r != null ) { abs_pp_file = r . getItem ( ) ; } } if ( abs_pp_file != null ) { if ( fDebugEn ) { fLog . debug ( "" + abs_pp_file . getFilePath ( ) ) ; } SVDBFile file = fCache . getFile ( new NullProgressMonitor ( ) , abs_pp_file . getFilePath ( ) ) ; if ( file != null ) { fLog . debug ( "" + pkgname ) ; if ( ! processed_files . contains ( file . getFilePath ( ) ) ) { processed_files . add ( file . getFilePath ( ) ) ; cacheDeclarations ( processed_files , file . getFilePath ( ) , null , pkgname , pkgitem_list , file , false ) ; SVDBFileTree ft = fCache . getFileTree ( new NullProgressMonitor ( ) , abs_pp_file . getFilePath ( ) ) ; SVDBFile pp_file = ft . getSVDBFile ( ) ; synchronized ( pp_file ) { for ( ISVDBChildItem item : pp_file . getChildren ( ) ) { if ( item . getType ( ) == SVDBItemType . Include ) { cachePkgDeclIncFile ( processed_files , pkgname , pkgitem_list , ( ( SVDBInclude ) item ) . getName ( ) ) ; } } } } else { if ( fDebugEn ) { fLog . debug ( "" + file . getFilePath ( ) + "" ) ; } } } else { fLog . debug ( "" + abs_pp_file . getFilePath ( ) + "" ) ; Tuple < String , List < String > > t = null ; synchronized ( fDeferredPkgCacheFiles ) { for ( Tuple < String , List < String > > tp : fDeferredPkgCacheFiles ) { if ( tp . first ( ) . equals ( abs_pp_file . getFilePath ( ) ) ) { t = tp ; break ; } } } if ( t == null ) { t = new Tuple < String , List < String > > ( abs_pp_file . getFilePath ( ) , new ArrayList < String > ( ) ) ; fDeferredPkgCacheFiles . add ( t ) ; } if ( ! t . second ( ) . contains ( pkgname ) ) { t . second ( ) . add ( pkgname ) ; } } } else { fLog . debug ( "" + inc + "" ) ; } } private void cacheDeclarations ( Set < String > processed_files , String filename , List < SVDBDeclCacheItem > decl_list , String pkgname , List < SVDBDeclCacheItem > pkgitem_list , ISVDBChildParent scope , boolean is_ft ) { if ( fDebugEn ) { fLog . debug ( "" + filename + "" + pkgname + "" + scope ) ; } for ( ISVDBChildItem item : scope . getChildren ( ) ) { if ( fDebugEn ) { fLog . debug ( "" + item . getType ( ) + "" + SVDBItem . getName ( item ) ) ; } if ( item . getType ( ) . isElemOf ( SVDBItemType . PackageDecl ) ) { SVDBPackageDecl pkg = ( SVDBPackageDecl ) item ; if ( decl_list != null ) { decl_list . add ( new SVDBDeclCacheItem ( this , filename , pkg . getName ( ) , item . getType ( ) , is_ft ) ) ; } Map < String , List < SVDBDeclCacheItem > > pkg_map = fIndexCacheData . getPackageCacheMap ( ) ; if ( pkg_map . containsKey ( pkg . getName ( ) ) ) { pkg_map . get ( pkg . getName ( ) ) . clear ( ) ; } else { pkg_map . put ( pkg . getName ( ) , new ArrayList < SVDBDeclCacheItem > ( ) ) ; } if ( ! is_ft ) { SVDBFileTree ft = fCache . getFileTree ( new NullProgressMonitor ( ) , filename ) ; if ( ft != null ) { cachePkgDeclFileTree ( ft . getSVDBFile ( ) , pkg_map . get ( pkg . getName ( ) ) , pkg ) ; } else { fLog . error ( "" + filename + "" ) ; } } cacheDeclarations ( processed_files , filename , decl_list , pkg . getName ( ) , pkg_map . get ( pkg . getName ( ) ) , pkg , false ) ; } else if ( item . getType ( ) . isElemOf ( SVDBItemType . Function , SVDBItemType . Task , SVDBItemType . ClassDecl , SVDBItemType . ModuleDecl , SVDBItemType . InterfaceDecl , SVDBItemType . ProgramDecl ) ) { fLog . debug ( LEVEL_MID , "" + item . getType ( ) + "" + ( ( ISVDBNamedItem ) item ) . getName ( ) + "" ) ; if ( decl_list != null ) { decl_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; } if ( pkgname != null ) { if ( fDebugEn ) { fLog . debug ( "" + SVDBItem . getName ( item ) + "" + pkgname + "" ) ; } pkgitem_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; } else { fLog . debug ( "" ) ; } } else if ( item . getType ( ) == SVDBItemType . TypedefStmt ) { if ( decl_list != null ) { decl_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; } if ( pkgname != null ) { pkgitem_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; } SVDBTypedefStmt td = ( SVDBTypedefStmt ) item ; if ( td . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoEnum ) { SVDBTypeInfoEnum e = ( SVDBTypeInfoEnum ) td . getTypeInfo ( ) ; fLog . debug ( "" + e . getName ( ) + "" ) ; for ( SVDBTypeInfoEnumerator en : e . getEnumerators ( ) ) { fLog . debug ( "" + en . getName ( ) + "" ) ; if ( decl_list != null ) { decl_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) en ) . getName ( ) , en . getType ( ) , is_ft ) ) ; } if ( pkgname != null ) { pkgitem_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; } } } } else if ( item . getType ( ) == SVDBItemType . PreProcCond ) { cacheDeclarations ( processed_files , filename , decl_list , pkgname , pkgitem_list , ( SVDBPreProcCond ) item , is_ft ) ; } else if ( item . getType ( ) == SVDBItemType . MacroDef ) { if ( decl_list != null ) { fLog . debug ( LEVEL_MID , "" + SVDBItem . getName ( item ) + "" ) ; decl_list . add ( new SVDBDeclCacheItem ( this , filename , ( ( ISVDBNamedItem ) item ) . getName ( ) , item . getType ( ) , is_ft ) ) ; } } } if ( fDebugEn ) { fLog . debug ( "" + filename + "" + pkgname + "" + scope ) ; } } protected void cacheReferences ( SVDBFile file ) { SVDBFileRefCollector collector = new SVDBFileRefCollector ( ) ; collector . visitFile ( file ) ; Map < String , SVDBRefCacheEntry > ref_map = getCacheData ( ) . getReferenceCacheMap ( ) ; if ( ref_map . containsKey ( file . getFilePath ( ) ) ) { ref_map . remove ( file . getFilePath ( ) ) ; } SVDBRefCacheEntry ref = collector . getReferences ( ) ; ref . setFilename ( file . getFilePath ( ) ) ; ref_map . put ( file . getFilePath ( ) , ref ) ; } public List < SVDBDeclCacheItem > findPackageDecl ( IProgressMonitor monitor , SVDBDeclCacheItem pkg_item ) { List < SVDBDeclCacheItem > ret = new ArrayList < SVDBDeclCacheItem > ( ) ; Map < String , List < SVDBDeclCacheItem > > pkg_cache = fIndexCacheData . getPackageCacheMap ( ) ; ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; List < SVDBDeclCacheItem > pkg_content = pkg_cache . get ( pkg_item . getName ( ) ) ; if ( pkg_content != null ) { ret . addAll ( pkg_content ) ; } return ret ; } public List < SVDBDeclCacheItem > findGlobalScopeDecl ( IProgressMonitor monitor , String name , ISVDBFindNameMatcher matcher ) { List < SVDBDeclCacheItem > ret = new ArrayList < SVDBDeclCacheItem > ( ) ; Map < String , List < SVDBDeclCacheItem > > decl_cache = fIndexCacheData . getDeclCacheMap ( ) ; ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; for ( Entry < String , List < SVDBDeclCacheItem > > e : decl_cache . entrySet ( ) ) { for ( SVDBDeclCacheItem item : e . getValue ( ) ) { if ( matcher . match ( item , name ) ) { ret . add ( item ) ; } } } return ret ; } public List < SVDBRefCacheItem > findReferences ( IProgressMonitor monitor , String name , ISVDBRefMatcher matcher ) { List < SVDBRefCacheItem > ret = new ArrayList < SVDBRefCacheItem > ( ) ; ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; Map < String , SVDBRefCacheEntry > ref_cache = fIndexCacheData . getReferenceCacheMap ( ) ; for ( Entry < String , SVDBRefCacheEntry > e : ref_cache . entrySet ( ) ) { matcher . find_matches ( ret , e . getValue ( ) , name ) ; } for ( SVDBRefCacheItem item : ret ) { item . setRefFinder ( this ) ; } return ret ; } public List < SVDBRefItem > findReferences ( IProgressMonitor monitor , SVDBRefCacheItem item ) { ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; SVDBRefFinder finder = new SVDBRefFinder ( item . getRefType ( ) , item . getRefName ( ) ) ; SVDBFile file = findFile ( item . getFilename ( ) ) ; return finder . find_refs ( file ) ; } public SVDBFile getDeclFile ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; SVDBFile file = null ; if ( item . isFileTreeItem ( ) ) { SVDBFileTree ft = findFileTree ( item . getFilename ( ) ) ; if ( ft != null ) { file = ft . getSVDBFile ( ) ; } } else { file = findFile ( item . getFilename ( ) ) ; } return file ; } public SVDBFile getDeclFilePP ( IProgressMonitor monitor , SVDBDeclCacheItem item ) { ensureIndexState ( monitor , IndexState_AllFilesParsed ) ; SVDBFile file = null ; if ( item . isFileTreeItem ( ) ) { SVDBFileTree ft = findFileTree ( item . getFilename ( ) ) ; if ( ft != null ) { file = ft . getSVDBFile ( ) ; } } else { file = findFile ( item . getFilename ( ) ) ; } return file ; } public SVPreProcessor createPreProcScanner ( String path ) { path = SVFileUtils . normalize ( path ) ; InputStream in = getFileSystemProvider ( ) . openStream ( path ) ; SVDBFileTree ft = findFileTree ( path ) ; if ( ft == null ) { fLog . error ( "" + path + "" ) ; return null ; } IPreProcMacroProvider mp = createMacroProvider ( ft ) ; SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( mp ) ; SVPreProcessor pp = new SVPreProcessor ( in , path , dp ) ; return pp ; } } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . SVDBFile ; public interface ISVDBIndexChangeListener { int FILE_ADDED = ; int FILE_REMOVED = ; int FILE_CHANGED = ; void index_changed ( int reason , SVDBFile file ) ; void index_rebuilt ( ) ; } package net . sf . sveditor . core . db . index ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; public class SVDBFileTree { @ SVDBDoNotSaveAttr private boolean fProcessed ; public String fFilePath ; public SVDBFile fSVDBFile ; public List < String > fIncludedFiles ; public List < String > fIncludedByFiles ; public SVDBFileTree ( ) { fFilePath = null ; fIncludedFiles = new ArrayList < String > ( ) ; fIncludedByFiles = new ArrayList < String > ( ) ; } public SVDBFileTree ( String path ) { fFilePath = path ; fIncludedFiles = new ArrayList < String > ( ) ; fIncludedByFiles = new ArrayList < String > ( ) ; } public SVDBFileTree ( SVDBFile file ) { fFilePath = file . getFilePath ( ) ; fSVDBFile = file ; fIncludedFiles = new ArrayList < String > ( ) ; fIncludedByFiles = new ArrayList < String > ( ) ; } public boolean getFileProcessed ( ) { return fProcessed ; } public void setFileProcessed ( boolean is_processed ) { fProcessed = is_processed ; } public String getFilePath ( ) { return fFilePath ; } public void setFileName ( String path ) { fFilePath = path ; } public SVDBFile getSVDBFile ( ) { return fSVDBFile ; } public void setSVDBFile ( SVDBFile file ) { fSVDBFile = file ; } public List < String > getIncludedFiles ( ) { return fIncludedFiles ; } public void addIncludedFile ( String path ) { if ( ! fIncludedFiles . contains ( path ) ) { fIncludedFiles . add ( path ) ; } } public List < String > getIncludedByFiles ( ) { return fIncludedByFiles ; } public boolean equals ( Object other ) { if ( other != null && other instanceof SVDBFileTree ) { SVDBFileTree other_t = ( SVDBFileTree ) other ; boolean ret = true ; if ( other_t . fFilePath == null || fFilePath == null ) { ret &= ( other_t . fFilePath == fFilePath ) ; } else { ret &= ( other_t . fFilePath . equals ( fFilePath ) ) ; } return ret ; } else { return false ; } } public SVDBFileTree duplicate ( ) { SVDBFileTree ret = new SVDBFileTree ( fFilePath ) ; ret . fSVDBFile = fSVDBFile ; ret . fIncludedByFiles . addAll ( fIncludedByFiles ) ; ret . fIncludedFiles . addAll ( fIncludedFiles ) ; return ret ; } } package net . sf . sveditor . core . db . index ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBIndexCollectionItemIterator implements ISVDBItemIterator { List < ISVDBIndex > fIndexList ; int fIndexListIdx = ; ISVDBItemIterator fIndexIterator ; ISVDBIndex fOverrideIndex ; SVDBFile fOverrideFile ; IProgressMonitor fProgressMonitor ; public SVDBIndexCollectionItemIterator ( IProgressMonitor monitor ) { fIndexList = new ArrayList < ISVDBIndex > ( ) ; fProgressMonitor = monitor ; } public void setOverride ( ISVDBIndex index , SVDBFile file ) { fOverrideIndex = index ; fOverrideFile = file ; } public void addIndex ( ISVDBIndex index ) { fIndexList . add ( index ) ; } public boolean hasNext ( SVDBItemType ... type_list ) { if ( fIndexIterator != null && ! fIndexIterator . hasNext ( ) ) { fIndexIterator = null ; } while ( ( fIndexIterator == null || ! fIndexIterator . hasNext ( type_list ) ) && fIndexListIdx < fIndexList . size ( ) ) { fIndexIterator = fIndexList . get ( fIndexListIdx ) . getItemIterator ( fProgressMonitor ) ; fIndexListIdx ++ ; } return ( ( fIndexIterator != null && fIndexIterator . hasNext ( type_list ) ) || fIndexListIdx < fIndexList . size ( ) ) ; } public ISVDBItemBase nextItem ( SVDBItemType ... type_list ) { boolean had_next = hasNext ( ) ; if ( fIndexIterator != null && ! fIndexIterator . hasNext ( type_list ) ) { fIndexIterator = null ; } if ( fIndexIterator == null && fIndexListIdx < fIndexList . size ( ) ) { fIndexIterator = fIndexList . get ( fIndexListIdx ) . getItemIterator ( fProgressMonitor ) ; fIndexListIdx ++ ; } if ( fIndexList . get ( fIndexListIdx - ) == fOverrideIndex ) { ( ( SVDBIndexItemIterator ) fIndexIterator ) . setOverride ( fOverrideFile ) ; } ISVDBItemBase ret = null ; if ( fIndexIterator != null ) { ret = fIndexIterator . nextItem ( type_list ) ; } if ( ret == null && had_next ) { System . out . println ( "" ) ; try { throw new Exception ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return ret ; } } package net . sf . sveditor . core . db . index ; import java . io . File ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import net . sf . sveditor . core . fileset . SVFileSet ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IPathVariableManager ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . variables . IStringVariableManager ; import org . eclipse . core . variables . IValueVariable ; import org . eclipse . core . variables . VariablesPlugin ; public class SVDBIndexUtil { private static LogHandle fLog = LogFactory . getLogHandle ( "" ) ; public static Tuple < ISVDBIndex , SVDBIndexCollection > findIndexFile ( String path , String project , boolean create_shadow ) { ISVDBIndex index = null ; SVDBIndexCollection index_mgr = null ; IWorkspaceRoot ws_root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; List < IProject > projects = new ArrayList < IProject > ( ) ; for ( IProject p : ws_root . getProjects ( ) ) { if ( project != null && p . getName ( ) . equals ( project ) ) { projects . add ( , p ) ; } else { projects . add ( p ) ; } } SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; for ( IProject p : projects ) { if ( ! p . isOpen ( ) ) { continue ; } SVDBProjectData pdata = p_mgr . getProjectData ( p ) ; List < SVDBSearchResult < SVDBFile > > result = pdata . getProjectIndexMgr ( ) . findPreProcFile ( path , false ) ; if ( result . size ( ) > ) { index = result . get ( ) . getIndex ( ) ; fLog . debug ( "" + path + "" + index . getBaseLocation ( ) + "" + pdata . getName ( ) ) ; index_mgr = pdata . getProjectIndexMgr ( ) ; break ; } else if ( path . startsWith ( "" ) ) { String ws_path = path . substring ( "" . length ( ) ) ; IFile f = ws_root . getFile ( new Path ( ws_path ) ) ; if ( f != null && f . exists ( ) ) { File fs_file = f . getLocation ( ) . toFile ( ) ; result = pdata . getProjectIndexMgr ( ) . findPreProcFile ( fs_file . getAbsolutePath ( ) , false ) ; if ( result . size ( ) > ) { index = result . get ( ) . getIndex ( ) ; fLog . debug ( "" + path + "" + index . getBaseLocation ( ) + "" + pdata . getName ( ) ) ; index_mgr = pdata . getProjectIndexMgr ( ) ; break ; } } } } if ( index == null ) { for ( IProject p : projects ) { if ( ! p . isOpen ( ) ) { continue ; } SVDBProjectData pdata = p_mgr . getProjectData ( p ) ; List < SVDBSearchResult < SVDBFile > > result = pdata . getProjectIndexMgr ( ) . findPreProcFile ( path , true ) ; if ( result . size ( ) > ) { index = result . get ( ) . getIndex ( ) ; index_mgr = pdata . getProjectIndexMgr ( ) ; fLog . debug ( "" + path + "" + index . getBaseLocation ( ) + "" + pdata . getName ( ) ) ; break ; } } } if ( index == null ) { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; for ( ISVDBIndex idx_t : rgy . getProjectIndexList ( SVDBIndexRegistry . GLOBAL_PROJECT ) ) { if ( idx_t . findPreProcFile ( path ) != null ) { index = idx_t ; index_mgr = rgy . getGlobalIndexMgr ( ) ; } } } if ( index == null && create_shadow ) { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; fLog . debug ( "" + path + "" ) ; if ( project != null ) { SVDBProjectData pdata = p_mgr . getProjectData ( projects . get ( ) ) ; index_mgr = pdata . getProjectIndexMgr ( ) ; } else { index_mgr = rgy . getGlobalIndexMgr ( ) ; project = SVDBIndexRegistry . GLOBAL_PROJECT ; } SVFileSet fs = new SVFileSet ( SVFileUtils . getPathParent ( path ) ) ; fs . getIncludes ( ) . add ( SVFileUtils . getPathLeaf ( path ) ) ; index = SVDBShadowIndexFactory . create ( project , path ) ; index_mgr . addShadowIndex ( index . getBaseLocation ( ) , index ) ; } if ( index != null ) { return new Tuple < ISVDBIndex , SVDBIndexCollection > ( index , index_mgr ) ; } else { return null ; } } public static String expandVars ( String path , String projectname , boolean in_workspace_ok ) { boolean workspace_prefix = path . startsWith ( "" ) ; String exp_path = path ; if ( workspace_prefix ) { exp_path = exp_path . substring ( "" . length ( ) ) ; } IWorkspace workspace = null ; try { workspace = ResourcesPlugin . getWorkspace ( ) ; } catch ( IllegalStateException e ) { } IPathVariableManager pvm = null ; IProject project = null ; IStringVariableManager svm = null ; if ( workspace != null ) { pvm = ResourcesPlugin . getWorkspace ( ) . getPathVariableManager ( ) ; if ( projectname != null ) { project = workspace . getRoot ( ) . getProject ( projectname ) ; } svm = ( VariablesPlugin . getDefault ( ) != null ) ? VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) : null ; } StringBuilder sb = new StringBuilder ( exp_path ) ; StringBuilder tmp = new StringBuilder ( ) ; int found_var = ; while ( found_var == ) { int idx = ; found_var = ; while ( idx < sb . length ( ) ) { if ( sb . charAt ( idx ) == '' ) { tmp . setLength ( ) ; int start = idx , end ; String key , val = null ; idx ++ ; if ( sb . charAt ( idx ) == '' ) { idx ++ ; while ( idx < sb . length ( ) && sb . charAt ( idx ) != '' ) { tmp . append ( sb . charAt ( idx ) ) ; idx ++ ; } if ( idx < sb . length ( ) ) { end = ++ idx ; } else { end = idx ; } } else { while ( idx < sb . length ( ) && sb . charAt ( idx ) != '' && ! Character . isWhitespace ( sb . charAt ( idx ) ) ) { tmp . append ( sb . charAt ( idx ) ) ; idx ++ ; } end = idx ; } key = tmp . toString ( ) ; val = null ; if ( val == null && project != null ) { IPath p = null ; try { Class < ? extends IProject > c = project . getClass ( ) ; Method get_path_variable_manager = c . getMethod ( "" ) ; if ( get_path_variable_manager != null ) { pvm = ( IPathVariableManager ) get_path_variable_manager . invoke ( project ) ; p = pvm . getValue ( key ) ; } } catch ( Exception e ) { } if ( p != null ) { val = p . toString ( ) ; if ( val . matches ( "" ) ) { val = val . replaceFirst ( "" , "" ) ; } } } if ( val == null && pvm != null ) { IPath p = pvm . getValue ( key ) ; if ( p != null ) { val = p . toString ( ) ; } } if ( val == null ) { val = SVCorePlugin . getenv ( key ) ; } if ( val == null && svm != null ) { IValueVariable v = svm . getValueVariable ( key ) ; if ( v != null ) { val = v . getValue ( ) ; } } if ( val != null ) { found_var = ; sb . replace ( start , end , val ) ; break ; } } else { idx ++ ; } } } exp_path = sb . toString ( ) ; if ( VariablesPlugin . getDefault ( ) != null ) { IStringVariableManager mgr = VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) ; try { exp_path = mgr . performStringSubstitution ( exp_path ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } } if ( ! workspace_prefix && in_workspace_ok ) { IWorkspaceRoot ws_root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IFile file = ws_root . getFileForLocation ( new Path ( exp_path ) ) ; if ( file != null && file . exists ( ) ) { workspace_prefix = true ; exp_path = file . getFullPath ( ) . toOSString ( ) ; } } if ( workspace_prefix ) { exp_path = "" + exp_path ; } return exp_path ; } } package net . sf . sveditor . core . db . index ; import java . io . InputStream ; import java . util . List ; import java . util . Map . Entry ; import java . util . Set ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . job_mgr . IJob ; import net . sf . sveditor . core . scanutils . ITextScanner ; import net . sf . sveditor . core . scanutils . InputStreamTextScanner ; import net . sf . sveditor . core . svf_scanner . SVFScanner ; import org . apache . tools . ant . filters . StringInputStream ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; public class SVDBThreadedArgFileIndex extends AbstractThreadedSVDBIndex { private StringBuilder fArguments ; public SVDBThreadedArgFileIndex ( String project , String root , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { super ( project , root , fs_provider , cache , config ) ; fInWorkspaceOk = ( root . startsWith ( "" ) ) ; } public SVDBThreadedArgFileIndex ( String project , String root , StringBuilder arguments , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { super ( project , root , fs_provider , cache , config ) ; fArguments = arguments ; fInWorkspaceOk = ( root . startsWith ( "" ) ) ; } @ Override protected String getLogName ( ) { return "" ; } public String getTypeID ( ) { return SVDBArgFileIndexFactory . TYPE ; } @ Override protected SVDBBaseIndexCacheData createIndexCacheData ( ) { return new SVDBArgFileIndexCacheData ( getBaseLocation ( ) ) ; } @ Override protected boolean checkCacheValid ( ) { SVDBArgFileIndexCacheData cd = ( SVDBArgFileIndexCacheData ) getCacheData ( ) ; int i = ; for ( String arg_file : cd . getArgFilePaths ( ) ) { long ts = getFileSystemProvider ( ) . getLastModifiedTime ( arg_file ) ; long ts_c = cd . getArgFileTimestamps ( ) . get ( i ) ; if ( ts > ts_c ) { fLog . debug ( "" + arg_file + "" + ts + "" + ts_c ) ; return false ; } i ++ ; } return super . checkCacheValid ( ) ; } @ Override protected void discoverRootFiles ( List < IJob > jobs ) { fLog . debug ( "" + getBaseLocation ( ) ) ; clearFilesList ( ) ; clearIncludePaths ( ) ; clearDefines ( ) ; SVDBArgFileIndexCacheData cd = ( SVDBArgFileIndexCacheData ) getCacheData ( ) ; cd . getArgFileTimestamps ( ) . clear ( ) ; cd . getArgFilePaths ( ) . clear ( ) ; addIncludePath ( getResolvedBaseLocationDir ( ) ) ; processArgFile ( new NullProgressMonitor ( ) , getResolvedBaseLocation ( ) ) ; } private void processArgFile ( IProgressMonitor monitor , String path ) { InputStream in = null ; if ( fArguments != null ) { in = new StringInputStream ( fArguments . toString ( ) ) ; } else if ( getFileSystemProvider ( ) . fileExists ( path ) ) { in = getFileSystemProvider ( ) . openStream ( path ) ; } else if ( getFileSystemProvider ( ) . fileExists ( getResolvedBaseLocationDir ( ) + "" + path ) ) { in = getFileSystemProvider ( ) . openStream ( getResolvedBaseLocationDir ( ) + "" + path ) ; } monitor . beginTask ( "" + path , ) ; if ( in != null ) { SVDBArgFileIndexCacheData cd = ( SVDBArgFileIndexCacheData ) getCacheData ( ) ; cd . getArgFilePaths ( ) . add ( path ) ; cd . getArgFileTimestamps ( ) . add ( getFileSystemProvider ( ) . getLastModifiedTime ( path ) ) ; ITextScanner sc = new InputStreamTextScanner ( in , path ) ; SVFScanner scanner = new SVFScanner ( ) ; monitor . worked ( ) ; try { scanner . scan ( sc ) ; } catch ( Exception e ) { fLog . error ( "" + getResolvedBaseLocation ( ) + "" , e ) ; } monitor . worked ( ) ; for ( String f : scanner . getFilePaths ( ) ) { String exp_f = SVDBIndexUtil . expandVars ( f , fProjectName , fInWorkspaceOk ) ; fLog . debug ( "" + f + "" + exp_f + "" ) ; String res_f = resolvePath ( exp_f , fInWorkspaceOk ) ; if ( getFileSystemProvider ( ) . fileExists ( res_f ) ) { addFile ( res_f ) ; } else { fLog . error ( "" + exp_f + "" ) ; } } for ( String lib_p : scanner . getLibPaths ( ) ) { String exp_p = SVDBIndexUtil . expandVars ( lib_p , fProjectName , fInWorkspaceOk ) ; fLog . debug ( "" + lib_p + "" + exp_p + "" ) ; String res_p = resolvePath ( exp_p , fInWorkspaceOk ) ; if ( getFileSystemProvider ( ) . isDir ( res_p ) ) { List < String > paths = getFileSystemProvider ( ) . getFiles ( res_p ) ; Set < String > exts = scanner . getSrcExts ( ) ; for ( String file_p : paths ) { int last_dot = file_p . lastIndexOf ( '' ) ; if ( last_dot != - ) { String ext = file_p . substring ( last_dot ) ; if ( exts . contains ( ext ) ) { addFile ( file_p ) ; } } } } else { fLog . error ( "" + exp_p + "" ) ; } } monitor . worked ( ) ; for ( String inc : scanner . getIncludePaths ( ) ) { String inc_path = SVDBIndexUtil . expandVars ( inc , fProjectName , fInWorkspaceOk ) ; fLog . debug ( "" + inc + "" + inc_path + "" ) ; addIncludePath ( inc_path ) ; } monitor . worked ( ) ; for ( Entry < String , String > entry : scanner . getDefineMap ( ) . entrySet ( ) ) { fLog . debug ( "" + entry . getKey ( ) + "" + entry . getValue ( ) ) ; addDefine ( entry . getKey ( ) , entry . getValue ( ) ) ; } getFileSystemProvider ( ) . closeStream ( in ) ; for ( String arg_file : scanner . getArgFilePaths ( ) ) { arg_file = SVDBIndexUtil . expandVars ( arg_file , fProjectName , fInWorkspaceOk ) ; if ( ! cd . getArgFilePaths ( ) . contains ( arg_file ) ) { processArgFile ( new SubProgressMonitor ( monitor , ) , arg_file ) ; } } monitor . done ( ) ; } else { monitor . done ( ) ; fLog . error ( "" + path + "" ) ; } } @ Override public void dispose ( ) { SVDBArgFileIndexCacheData cd = ( SVDBArgFileIndexCacheData ) getCacheData ( ) ; cd . getArgFileTimestamps ( ) . clear ( ) ; for ( String arg_file : cd . getArgFilePaths ( ) ) { long ts = getFileSystemProvider ( ) . getLastModifiedTime ( arg_file ) ; fLog . debug ( "" + arg_file + "" + ts ) ; cd . getArgFileTimestamps ( ) . add ( ts ) ; } super . dispose ( ) ; } @ Override public void fileChanged ( String path ) { fLog . debug ( "" + path ) ; if ( path . equals ( getResolvedBaseLocation ( ) ) ) { invalidateIndex ( "" + path , false ) ; } super . fileChanged ( path ) ; } } package net . sf . sveditor . core . db . index ; import java . util . Iterator ; import java . util . Stack ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBIndexItemIterator implements ISVDBItemIterator { private ISVDBIndex fIndex ; private Stack < Iterator < ISVDBChildItem > > fScopeStack ; private Iterator < String > fFilePathIterator ; private Iterator < ISVDBChildItem > fScopeIterator ; private SVDBFile fOverrideFile ; private ISVDBItemBase fCurrent ; public SVDBIndexItemIterator ( Iterable < String > file_list , ISVDBIndex index ) { fFilePathIterator = file_list . iterator ( ) ; fScopeStack = new Stack < Iterator < ISVDBChildItem > > ( ) ; fIndex = index ; } public void setOverride ( SVDBFile file ) { fOverrideFile = file ; } public ISVDBItemBase peekNext ( SVDBItemType ... type_list ) { while ( true ) { if ( fCurrent == null ) { fCurrent = nextItem_int ( ) ; } if ( fCurrent != null ) { if ( fCurrent . getType ( ) . isElemOf ( type_list ) ) { break ; } else { fCurrent = null ; } } else { break ; } } return fCurrent ; } public boolean hasNext ( SVDBItemType ... type_list ) { return ( peekNext ( type_list ) != null ) ; } private ISVDBItemBase nextItem_int ( ) { ISVDBItemBase ret = null ; for ( int i = ; i < && ret == null ; i ++ ) { if ( fScopeIterator != null && fScopeIterator . hasNext ( ) ) { ret = fScopeIterator . next ( ) ; if ( ret instanceof ISVDBChildParent ) { ISVDBChildParent it = ( ISVDBChildParent ) ret ; Iterator < ISVDBChildItem > c_it = it . getChildren ( ) . iterator ( ) ; if ( c_it . hasNext ( ) ) { if ( fScopeIterator . hasNext ( ) ) { fScopeStack . push ( fScopeIterator ) ; } fScopeIterator = c_it ; } } } else if ( ! fScopeStack . empty ( ) ) { fScopeIterator = fScopeStack . pop ( ) ; } else if ( fFilePathIterator . hasNext ( ) ) { String path = fFilePathIterator . next ( ) ; SVDBFile file = fIndex . findFile ( path ) ; if ( fOverrideFile != null && file . getFilePath ( ) . equals ( fOverrideFile . getFilePath ( ) ) ) { file = fOverrideFile ; } if ( file == null ) { continue ; } ret = file ; Iterator < ISVDBChildItem > tmp = file . getChildren ( ) . iterator ( ) ; if ( tmp . hasNext ( ) ) { fScopeIterator = tmp ; } } } return ret ; } public ISVDBItemBase nextItem ( SVDBItemType ... type_list ) { ISVDBItemBase ret = peekNext ( type_list ) ; fCurrent = null ; return ret ; } } package net . sf . sveditor . core . db . index ; import java . util . Map ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . log . LogFactory ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBLibIndex extends AbstractSVDBIndex { public SVDBLibIndex ( String project , String root , ISVDBFileSystemProvider fs_provider , ISVDBIndexCache cache , SVDBIndexConfig config ) { super ( project , root , fs_provider , cache , config ) ; } @ Override protected String getLogName ( ) { return "" ; } public String getTypeID ( ) { return SVDBLibPathIndexFactory . TYPE ; } @ Override protected void discoverRootFiles ( IProgressMonitor monitor ) { fLog . debug ( "" + getBaseLocation ( ) ) ; clearFilesList ( ) ; clearIncludePaths ( ) ; clearDefines ( ) ; monitor . beginTask ( "" , ) ; addIncludePath ( getResolvedBaseLocationDir ( ) ) ; addFile ( getResolvedBaseLocation ( ) ) ; monitor . done ( ) ; } protected void signalIndexRebuilt ( ) { } } package net . sf . sveditor . core . db . index ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . index . cache . InMemoryIndexCache ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBShadowIndexFactory implements ISVDBIndexFactory { public static final String TYPE = "" ; private LogHandle fLog ; public SVDBShadowIndexFactory ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } public ISVDBIndex createSVDBIndex ( String project_name , String base_location , ISVDBIndexCache cache , SVDBIndexConfig config ) { ISVDBIndex ret ; ISVDBFileSystemProvider fs_provider = null ; fLog . debug ( "" + project_name + "" + base_location ) ; fs_provider = new SVDBWSFileSystemProvider ( ) ; ret = new SVDBShadowIndex ( project_name , base_location , fs_provider , cache , config ) ; return ret ; } public static ISVDBIndex create ( String project , String path ) { SVDBShadowIndexFactory f = new SVDBShadowIndexFactory ( ) ; ISVDBIndex ret = f . createSVDBIndex ( project , path , new InMemoryIndexCache ( ) , null ) ; ret . init ( new NullProgressMonitor ( ) ) ; return ret ; } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBModportSimplePort extends SVDBChildItem implements ISVDBNamedItem { public boolean fIsMapped ; public String fPortId ; public SVDBExpr fExpr ; public SVDBModportSimplePort ( ) { super ( SVDBItemType . ModportSimplePort ) ; } public void setIsMapped ( boolean m ) { fIsMapped = m ; } public boolean isMapped ( ) { return fIsMapped ; } public void setPortId ( String id ) { fPortId = id ; } public String getPortId ( ) { return fPortId ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public String getName ( ) { return fPortId ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; public class SVDBCoverpointCross extends SVDBScopeItem { public List < SVDBIdentifierExpr > fCoverpointList ; public SVDBExpr fIFF ; public SVDBCoverpointCross ( ) { super ( "" , SVDBItemType . CoverpointCross ) ; } public SVDBCoverpointCross ( String name ) { super ( name , SVDBItemType . CoverpointCross ) ; fCoverpointList = new ArrayList < SVDBIdentifierExpr > ( ) ; } public SVDBExpr getIFF ( ) { return fIFF ; } public void setIFF ( SVDBExpr expr ) { fIFF = expr ; } public List < SVDBIdentifierExpr > getCoverpointList ( ) { return fCoverpointList ; } @ Override public SVDBItemBase duplicate ( ) { return ( SVDBCoverpointCross ) SVDBItemUtils . duplicate ( this ) ; } @ Override public void init ( SVDBItemBase other ) { SVDBCoverpointCross other_i = ( SVDBCoverpointCross ) other ; super . init ( other ) ; fCoverpointList . clear ( ) ; fCoverpointList . addAll ( other_i . fCoverpointList ) ; } } package net . sf . sveditor . core . db ; import java . util . HashMap ; import java . util . Map ; @ SuppressWarnings ( "" ) public enum SVDBItemType { File , ModuleDecl , ClassDecl , ConfigDecl , InterfaceDecl , ProgramDecl , Bind , Task , Function , ModIfcInst , ModIfcInstItem , ModportDecl , ModportItem , ModportSimplePortsDecl , ModportSimplePort , ModportClockingPortDecl , ModportTFPortsDecl , ModportTFPort , MacroDef , MacroDefParam , PreProcCond , Include , PackageDecl , Covergroup , Coverpoint , CoverpointBins , CoverpointCross , CoverCrossBinsSel , Sequence , Property , ModIfcClassParam , Constraint , Assign , Marker , ParamValueAssign , ParamValueAssignList , GenerateBlock , GenerateFor , GenerateIf , GenerateRegion , ClockingBlock , TypeInfoBuiltin , TypeInfoBuiltinNet , TypeInfoClassItem , TypeInfoClassType , TypeInfoEnum , TypeInfoEnumerator , TypeInfoFwdDecl , TypeInfoStruct , TypeInfoUnion , TypeInfoUserDef , TypeInfoModuleIfc , ActionBlockStmt , AlwaysStmt , AssertStmt , AssignStmt , AssumeStmt , LabeledStmt , BlockStmt , BreakStmt , CaseItem , CaseStmt , ConfigCellClauseStmt , ConfigDefaultClauseStmt , ConfigDesignStmt , ConfigInstClauseStmt , ConstraintDistListStmt , ConstraintDistListItem , ConstraintForeachStmt , ConstraintIfStmt , ConstraintImplStmt , ConstraintSetStmt , ConstraintSolveBeforeStmt , ContinueStmt , CoverStmt , DisableStmt , DisableForkStmt , DefParamStmt , DefParamItem , DelayControlStmt , DoWhileStmt , EventControlStmt , EventTriggerStmt , ExportStmt , ExportItem , ExprStmt , FinalStmt , ForeachStmt , ForeverStmt , ForkStmt , ForStmt , IfStmt , ImportItem , ImportStmt , InitialStmt , NullStmt , ProceduralContAssignStmt , RepeatStmt , ReturnStmt , VarDeclItem , VarDeclStmt , WaitForkStmt , WaitOrderStmt , WaitStmt , WhileStmt , VarDimItem , ParamPortDecl , TypedefStmt , CoverageOptionStmt , CoverageCrossBinsSelectStmt , TimePrecisionStmt , TimeUnitsStmt , ArrayAccessExpr , AssignExpr , AssignmentPatternExpr , AssignmentPatternRepeatExpr , AssociativeArrayElemAssignExpr , BinaryExpr , CastExpr , ClockingEventExpr , ConcatenationExpr , CondExpr , CrossBinsSelectConditionExpr , CtorExpr , CycleDelayExpr , FieldAccessExpr , FirstMatchExpr , IdentifierExpr , IncDecExpr , InsideExpr , LiteralExpr , MinTypMaxExpr , NamedArgExpr , NameMappedExpr , NullExpr , ParamIdExpr , ParenExpr , PropertyWeakStrongExpr , RandomizeCallExpr , RangeDollarBoundExpr , RangeExpr , TFCallExpr , UnaryExpr , TypeExpr , PropertySpecExpr , PropertyIfStmt , PropertyCaseStmt , PropertyCaseItem , SequenceCycleDelayExpr , SequenceClockingExpr , SequenceMatchItemExpr , SequenceDistExpr , SequenceRepetitionExpr , StringExpr , CoverpointExpr , CoverBinsExpr , DocComment ; public boolean isElemOf ( SVDBItemType ... type_list ) { switch ( type_list . length ) { case : return true ; case : return ( type_list [ ] == this ) ; case : return ( type_list [ ] == this || type_list [ ] == this ) ; case : return ( type_list [ ] == this || type_list [ ] == this || type_list [ ] == this ) ; case : return ( type_list [ ] == this || type_list [ ] == this || type_list [ ] == this || type_list [ ] == this ) ; default : for ( SVDBItemType t : type_list ) { if ( this == t ) { return true ; } } } return false ; } public static final Map < SVDBItemType , Class > fObjectMap ; static { fObjectMap = new HashMap < SVDBItemType , Class > ( ) ; fObjectMap . put ( File , SVDBFile . class ) ; fObjectMap . put ( ModuleDecl , SVDBModIfcDecl . class ) ; } } package net . sf . sveditor . core . db ; public interface ISVDBAddChildItem { void addChildItem ( ISVDBChildItem item ) ; } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBTypeInfoEnumerator extends SVDBTypeInfo { public SVDBExpr fExpr ; public SVDBTypeInfoEnumerator ( ) { this ( "" ) ; } public SVDBTypeInfoEnumerator ( String name ) { super ( name , SVDBItemType . TypeInfoEnumerator ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db ; public class SVDBProgramDecl extends SVDBModIfcDecl { public SVDBProgramDecl ( ) { super ( "" , SVDBItemType . ProgramDecl ) ; } public SVDBProgramDecl ( String name ) { super ( name , SVDBItemType . ProgramDecl ) ; } } package net . sf . sveditor . core . db ; import java . io . InputStream ; import java . util . List ; public interface ISVDBFileFactory { void init ( InputStream in , String filename ) ; SVDBFile parse ( InputStream in , String filename , List < SVDBMarker > markers ) ; } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . SVDBCovergroup . BinsKW ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBCoverpointBins extends SVDBItem { public enum BinsType { OpenRangeList , TransList , Default , DefaultSeq } ; public boolean fWildcard ; public BinsKW fBinsKW ; public BinsType fBinsType ; public boolean fIsArray ; public SVDBExpr fArrayExpr ; public SVDBExpr fIFF ; public SVDBCoverpointBins ( ) { super ( "" , SVDBItemType . CoverpointBins ) ; } public SVDBCoverpointBins ( boolean wildcard , String name , BinsKW kw ) { super ( name , SVDBItemType . CoverpointBins ) ; fWildcard = wildcard ; fBinsKW = kw ; } public void setIsWildcard ( boolean wildcard ) { fWildcard = wildcard ; } public boolean isWildcard ( ) { return fWildcard ; } public BinsKW getBinsKW ( ) { return fBinsKW ; } public void setBinsKW ( BinsKW kw ) { fBinsKW = kw ; } public void setIsArray ( boolean is_array ) { fIsArray = is_array ; } public boolean isArray ( ) { return fIsArray ; } public SVDBExpr getArrayExpr ( ) { return fArrayExpr ; } public void setArrayExpr ( SVDBExpr expr ) { fArrayExpr = expr ; } public void setBinsType ( BinsType type ) { fBinsType = type ; } public BinsType getBinsType ( ) { return fBinsType ; } public SVDBExpr getIFF ( ) { return fIFF ; } public void setIFF ( SVDBExpr expr ) { fIFF = expr ; } } package net . sf . sveditor . core . db ; import java . lang . reflect . Field ; import java . lang . reflect . Modifier ; import java . lang . reflect . ParameterizedType ; import java . lang . reflect . Type ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; import net . sf . sveditor . core . db . attr . SVDBParentAttr ; @ SuppressWarnings ( "" ) public class SVDBItemUtils { private static Map < SVDBItemType , Class > fClassMap ; public static synchronized ISVDBItemBase duplicate ( ISVDBItemBase item ) { ISVDBItemBase ret = null ; if ( fClassMap == null ) { init ( ) ; } if ( item == null ) { return null ; } if ( fClassMap . containsKey ( item . getType ( ) ) ) { Class cls = fClassMap . get ( item . getType ( ) ) ; Object obj = null ; try { obj = cls . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "" + item . getType ( ) + "" + e . getMessage ( ) ) ; } ret = ( ISVDBItemBase ) obj ; } else { throw new RuntimeException ( "" + item . getType ( ) ) ; } duplicate ( item . getClass ( ) , ret , item ) ; if ( item instanceof ISVDBChildItem ) { ( ( ISVDBChildItem ) ret ) . setParent ( ( ( ISVDBChildItem ) item ) . getParent ( ) ) ; } return ret ; } private static void duplicate ( Class cls , Object target , Object source ) { if ( cls . getSuperclass ( ) != null && cls . getSuperclass ( ) != Object . class ) { duplicate ( cls . getSuperclass ( ) , target , source ) ; } Field fields [ ] = cls . getDeclaredFields ( ) ; for ( Field f : fields ) { f . setAccessible ( true ) ; if ( ! Modifier . isStatic ( f . getModifiers ( ) ) ) { if ( f . getAnnotation ( SVDBParentAttr . class ) != null || f . getAnnotation ( SVDBDoNotSaveAttr . class ) != null ) { try { f . set ( target , f . get ( source ) ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } continue ; } try { Class field_class = f . getType ( ) ; if ( Enum . class . isAssignableFrom ( field_class ) ) { f . set ( target , f . get ( source ) ) ; } else if ( List . class . isAssignableFrom ( field_class ) ) { Type t = f . getGenericType ( ) ; if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; Type args [ ] = pt . getActualTypeArguments ( ) ; if ( args . length != ) { throw new RuntimeException ( "" + args . length + "" ) ; } Class c = ( Class ) args [ ] ; if ( c == String . class ) { Object o = duplicateStringList ( f . get ( source ) ) ; f . set ( target , o ) ; } else if ( c == Integer . class ) { f . set ( target , duplicateIntList ( f . get ( source ) ) ) ; } else if ( ISVDBItemBase . class . isAssignableFrom ( c ) ) { if ( target instanceof ISVDBChildItem ) { f . set ( target , duplicateItemList ( f . get ( source ) ) ) ; } else { f . set ( target , duplicateItemList ( f . get ( source ) ) ) ; } } else { throw new RuntimeException ( "" + ( ( Class ) args [ ] ) . getName ( ) ) ; } } else { throw new RuntimeException ( "" ) ; } } else if ( Map . class . isAssignableFrom ( field_class ) ) { Type t = f . getGenericType ( ) ; if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; Type args [ ] = pt . getActualTypeArguments ( ) ; Class key_c = ( Class ) args [ ] ; Class val_c = ( Class ) args [ ] ; if ( key_c == String . class && val_c == String . class ) { f . set ( target , duplicateMapStringString ( f . get ( source ) ) ) ; } else { throw new RuntimeException ( "" + key_c . getName ( ) + "" + val_c . getName ( ) + "" + cls . getName ( ) ) ; } } else { throw new RuntimeException ( "" ) ; } } else if ( field_class == String . class ) { f . set ( target , f . get ( source ) ) ; } else if ( field_class == int . class ) { f . setInt ( target , f . getInt ( source ) ) ; } else if ( field_class == long . class ) { f . setLong ( target , f . getLong ( source ) ) ; } else if ( field_class == boolean . class ) { f . setBoolean ( target , f . getBoolean ( source ) ) ; } else if ( SVDBLocation . class == field_class ) { f . set ( target , duplicateSVDBLocation ( f . get ( source ) ) ) ; } else if ( ISVDBItemBase . class . isAssignableFrom ( field_class ) ) { f . set ( target , duplicate ( ( ISVDBItemBase ) f . get ( source ) ) ) ; } else { throw new RuntimeException ( "" + field_class . getName ( ) ) ; } } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "" + e . getMessage ( ) ) ; } } } } @ SuppressWarnings ( { "" } ) private static Object duplicateStringList ( Object src_obj ) { List < String > ret = null ; if ( src_obj != null ) { ret = new ArrayList < String > ( ) ; List < String > src = ( List < String > ) src_obj ; ret . addAll ( src ) ; } return ret ; } @ SuppressWarnings ( "" ) private static Object duplicateIntList ( Object src_obj ) { List < Integer > ret = null ; if ( src_obj != null ) { ret = new ArrayList < Integer > ( ) ; List < Integer > src = ( List < Integer > ) src_obj ; ret . addAll ( src ) ; } return ret ; } @ SuppressWarnings ( "" ) private static Object duplicateItemList ( Object src_obj ) { List < ISVDBItemBase > ret = null ; if ( src_obj != null ) { ret = new ArrayList < ISVDBItemBase > ( ) ; List < ISVDBItemBase > src = ( List < ISVDBItemBase > ) src_obj ; for ( ISVDBItemBase it : src ) { ret . add ( duplicate ( it ) ) ; } } return ret ; } @ SuppressWarnings ( "" ) private static Object duplicateMapStringString ( Object src_obj ) { Map < String , String > ret = null ; if ( src_obj != null ) { ret = new HashMap < String , String > ( ) ; Map < String , String > src = ( Map < String , String > ) src_obj ; for ( Entry < String , String > e : src . entrySet ( ) ) { ret . put ( e . getKey ( ) , e . getValue ( ) ) ; } } return ret ; } private static Object duplicateSVDBLocation ( Object src_obj ) { SVDBLocation ret = null ; if ( src_obj != null ) { SVDBLocation src = ( SVDBLocation ) src_obj ; ret = new SVDBLocation ( src ) ; } return ret ; } private static void init ( ) { fClassMap = new HashMap < SVDBItemType , Class > ( ) ; ClassLoader cl = SVDBItemUtils . class . getClassLoader ( ) ; for ( SVDBItemType v : SVDBItemType . values ( ) ) { String key = "" + v . name ( ) ; Class cls = null ; for ( String pref : new String [ ] { "" , "" , "" } ) { try { cls = cl . loadClass ( pref + key ) ; } catch ( Exception e ) { } } if ( cls == null ) { System . out . println ( "" + key ) ; } else { fClassMap . put ( v , cls ) ; } } } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; public class SVDBItemBase implements ISVDBItemBase { @ SVDBDoNotSaveAttr public SVDBItemType fType ; public SVDBLocation fLocation ; public SVDBItemBase ( SVDBItemType type ) { fType = type ; fLocation = null ; } public SVDBItemType getType ( ) { return fType ; } public void setType ( SVDBItemType type ) { fType = type ; } public SVDBLocation getLocation ( ) { return fLocation ; } public void setLocation ( SVDBLocation location ) { fLocation = location ; } public ISVDBItemBase duplicate ( ) { return SVDBItemUtils . duplicate ( this ) ; } public void init ( ISVDBItemBase other ) { if ( other . getLocation ( ) != null ) { fLocation = other . getLocation ( ) . duplicate ( ) ; } else { fLocation = null ; } } public boolean equals ( Object obj ) { if ( obj instanceof SVDBItemBase ) { SVDBItemBase o = ( SVDBItemBase ) obj ; return ( o . fType == fType ) ; } else { return false ; } } public boolean equals ( ISVDBItemBase obj , boolean full ) { boolean ret = false ; if ( obj instanceof SVDBItemBase ) { ret = true ; SVDBItemBase other = ( SVDBItemBase ) obj ; if ( other . fType == null || fType == null ) { ret &= other . fType == fType ; } else { ret &= other . fType . equals ( fType ) ; } if ( full ) { if ( fLocation == null || other . fLocation == null ) { ret &= ( fLocation == other . fLocation ) ; } else { ret &= other . fLocation . equals ( fLocation ) ; } } } return ret ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; public class SVDBParamValueAssignList extends SVDBItem implements ISVDBEndLocation { public boolean fNamedMapping ; public List < SVDBParamValueAssign > fParameters ; public SVDBLocation fEndLocation ; public SVDBParamValueAssignList ( ) { super ( "" , SVDBItemType . ParamValueAssignList ) ; fNamedMapping = false ; fParameters = new ArrayList < SVDBParamValueAssign > ( ) ; } public void setEndLocation ( SVDBLocation l ) { fEndLocation = l ; } public SVDBLocation getEndLocation ( ) { return fEndLocation ; } public List < SVDBParamValueAssign > getParameters ( ) { return fParameters ; } public void addParameter ( SVDBParamValueAssign assign ) { fParameters . add ( assign ) ; } public void addParameter ( String name , String val ) { SVDBParamValueAssign assign = new SVDBParamValueAssign ( name , new SVDBIdentifierExpr ( val ) ) ; fParameters . add ( assign ) ; } public boolean getIsNamedMapping ( ) { return fNamedMapping ; } public void setIsNamedMapping ( boolean m ) { fNamedMapping = m ; } @ Override public SVDBParamValueAssignList duplicate ( ) { return ( SVDBParamValueAssignList ) super . duplicate ( ) ; } @ Override public void init ( SVDBItemBase other ) { super . init ( other ) ; fNamedMapping = ( ( SVDBParamValueAssignList ) other ) . fNamedMapping ; fParameters . clear ( ) ; fParameters . addAll ( ( ( SVDBParamValueAssignList ) other ) . fParameters ) ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBParamValueAssignList ) { SVDBParamValueAssignList o = ( SVDBParamValueAssignList ) obj ; if ( o . fNamedMapping != fNamedMapping ) { return false ; } if ( o . fParameters . size ( ) == fParameters . size ( ) ) { for ( int i = ; i < fParameters . size ( ) ; i ++ ) { if ( ! fParameters . get ( i ) . equals ( o . fParameters . get ( i ) ) ) { return false ; } } } else { return false ; } return super . equals ( obj ) ; } return false ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; import java . util . Stack ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . scanner . ISVPreProcScannerObserver ; import net . sf . sveditor . core . scanner . ISVScanner ; import net . sf . sveditor . core . scanutils . ScanLocation ; public class SVDBPreProcObserver implements ISVPreProcScannerObserver { private List < SVDBFile > fFileList ; private Stack < SVDBScopeItem > fScopeStack ; private ISVScanner fScanner ; public SVDBPreProcObserver ( ) { fFileList = new ArrayList < SVDBFile > ( ) ; fScopeStack = new Stack < SVDBScopeItem > ( ) ; } public List < SVDBFile > getFiles ( ) { return fFileList ; } public void init ( ISVScanner scanner ) { fScanner = scanner ; } public void enter_file ( String filename ) { SVDBFile file = new SVDBFile ( filename ) ; fFileList . add ( file ) ; fScopeStack . push ( file ) ; } public void enter_package ( String name ) { SVDBPackageDecl pd = new SVDBPackageDecl ( name ) ; setLocation ( pd ) ; fScopeStack . peek ( ) . addItem ( pd ) ; fScopeStack . push ( pd ) ; } public void leave_package ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . PackageDecl ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } public void preproc_define ( String key , List < Tuple < String , String > > params , String value ) { SVDBMacroDef def = new SVDBMacroDef ( key , value ) ; setLocation ( def ) ; for ( Tuple < String , String > p : params ) { SVDBMacroDefParam mp = new SVDBMacroDefParam ( p . first ( ) , p . second ( ) ) ; def . addParameter ( mp ) ; } fScopeStack . peek ( ) . addItem ( def ) ; } public void enter_preproc_conditional ( String type , String conditional ) { SVDBPreProcCond c = new SVDBPreProcCond ( type , conditional ) ; setLocation ( c ) ; fScopeStack . peek ( ) . addItem ( c ) ; fScopeStack . push ( c ) ; } public void leave_preproc_conditional ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) instanceof SVDBPreProcCond ) { fScopeStack . pop ( ) ; } } public void preproc_include ( String path ) { SVDBInclude inc = new SVDBInclude ( path ) ; setLocation ( inc ) ; fScopeStack . peek ( ) . addItem ( inc ) ; } public void leave_file ( ) { fScopeStack . clear ( ) ; } private void setLocation ( SVDBItem it ) { ScanLocation loc = fScanner . getStmtLocation ( ) ; it . setLocation ( new SVDBLocation ( loc . getLineNo ( ) , loc . getLinePos ( ) ) ) ; } private void setEndLocation ( SVDBScopeItem item ) { ScanLocation loc = fScanner . getStmtLocation ( ) ; item . setEndLocation ( new SVDBLocation ( loc . getLineNo ( ) , loc . getLinePos ( ) ) ) ; } public void error ( String msg , String filename , int lineno , int linepos ) { } public void comment ( String name , String comment ) { SVDBDocComment docCom = new SVDBDocComment ( name , comment ) ; fScopeStack . peek ( ) . addItem ( docCom ) ; } public void enter_interface_decl ( String name , String ports ) { SVDBModIfcDecl id = new SVDBModIfcDecl ( name , SVDBItemType . InterfaceDecl ) ; fScopeStack . peek ( ) . addItem ( id ) ; fScopeStack . push ( id ) ; setLocation ( id ) ; } public void leave_interface_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . InterfaceDecl ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } public void enter_module_decl ( String name , String ports ) { SVDBModIfcDecl md = new SVDBModIfcDecl ( name , SVDBItemType . ModuleDecl ) ; fScopeStack . peek ( ) . addItem ( md ) ; fScopeStack . push ( md ) ; setLocation ( md ) ; } public void leave_module_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . ModuleDecl ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } public void enter_program_decl ( String name ) { SVDBModIfcDecl p = new SVDBModIfcDecl ( name , SVDBItemType . ProgramDecl ) ; fScopeStack . peek ( ) . addItem ( p ) ; fScopeStack . push ( p ) ; setLocation ( p ) ; } public void leave_program_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . ProgramDecl ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } } package net . sf . sveditor . core . db ; public class SVDBInclude extends SVDBItem { public SVDBInclude ( ) { super ( "" , SVDBItemType . Include ) ; } public SVDBInclude ( String name ) { super ( name , SVDBItemType . Include ) ; } @ Override public SVDBInclude duplicate ( ) { return ( SVDBInclude ) super . duplicate ( ) ; } @ Override public void init ( SVDBItemBase other ) { super . init ( other ) ; } } package net . sf . sveditor . core . db ; public class SVDBDocComment extends SVDBItem { public String fRawComment ; public SVDBDocComment ( ) { super ( "" , SVDBItemType . DocComment ) ; } public SVDBDocComment ( String title , String comment ) { super ( title , SVDBItemType . DocComment ) ; fRawComment = comment ; } public String getRawComment ( ) { return fRawComment ; } } package net . sf . sveditor . core . db ; import java . util . List ; public interface ISVDBScopeItem extends ISVDBChildParent , ISVDBEndLocation { List < ISVDBItemBase > getItems ( ) ; @ Deprecated void addItem ( ISVDBItemBase item ) ; } package net . sf . sveditor . core . db ; public class SVDBTypeInfoFwdDecl extends SVDBTypeInfo { public String fTypeClass ; public SVDBTypeInfoFwdDecl ( ) { this ( "" , "" ) ; } public SVDBTypeInfoFwdDecl ( String type_class , String typename ) { super ( typename , SVDBItemType . TypeInfoFwdDecl ) ; fTypeClass = type_class ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBTypeInfoFwdDecl ) { SVDBTypeInfoFwdDecl o = ( SVDBTypeInfoFwdDecl ) obj ; return ( fTypeClass . equals ( o . fTypeClass ) && super . equals ( obj ) ) ; } return false ; } @ Override public SVDBTypeInfoFwdDecl duplicate ( ) { return ( SVDBTypeInfoFwdDecl ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBGenerateRegion extends SVDBChildItem implements ISVDBScopeItem { public List < ISVDBChildItem > fGenerateItems ; public SVDBLocation fEndLocation ; public SVDBGenerateRegion ( ) { super ( SVDBItemType . GenerateRegion ) ; fGenerateItems = new ArrayList < ISVDBChildItem > ( ) ; } public Iterable < ISVDBChildItem > getChildren ( ) { return fGenerateItems ; } public SVDBLocation getEndLocation ( ) { return fEndLocation ; } public void setEndLocation ( SVDBLocation loc ) { fEndLocation = loc ; } @ SuppressWarnings ( { "" , "" } ) public List < ISVDBItemBase > getItems ( ) { return ( List < ISVDBItemBase > ) ( ( List ) fGenerateItems ) ; } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fGenerateItems . add ( item ) ; } public void addItem ( ISVDBItemBase item ) { if ( item instanceof ISVDBChildItem ) { ( ( ISVDBChildItem ) item ) . setParent ( this ) ; fGenerateItems . add ( ( ISVDBChildItem ) item ) ; } } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . attr . SVDBParentAttr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; public class SVDBItem extends SVDBItemBase implements ISVDBNamedItem , ISVDBChildItem { @ SVDBParentAttr public ISVDBChildItem fParent ; public String fName ; public SVDBItem ( String name , SVDBItemType type ) { super ( type ) ; if ( name == null ) { fName = "" ; } else { fName = name ; } } public SVDBItem ( SVDBIdentifierExpr name , SVDBItemType type ) { super ( type ) ; if ( name == null ) { fName = "" ; } else { fName = name . getId ( ) ; } } public void setParent ( ISVDBChildItem parent ) { fParent = parent ; } public ISVDBChildItem getParent ( ) { return fParent ; } public String getName ( ) { return fName ; } public void setName ( String name ) { fName = name ; } public void setType ( SVDBItemType type ) { fType = type ; } public SVDBItemType getType ( ) { return fType ; } public void init ( SVDBItemBase other ) { SVDBItem o = ( SVDBItem ) other ; fName = o . fName ; fParent = o . fParent ; super . init ( o ) ; } @ Override public boolean equals ( ISVDBItemBase obj , boolean full ) { boolean ret = false ; if ( obj instanceof SVDBItem ) { ret = true ; SVDBItem other = ( SVDBItem ) obj ; if ( other . fName == null || fName == null ) { ret &= other . fName == fName ; } else { ret &= other . fName . equals ( fName ) ; } ret &= super . equals ( obj , full ) ; } return ret ; } public static String getName ( ISVDBItemBase item ) { if ( item == null ) { return "" ; } else if ( item instanceof ISVDBNamedItem ) { return ( ( ISVDBNamedItem ) item ) . getName ( ) ; } else { return "" + item . getType ( ) ; } } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBClockingBlock extends SVDBScopeItem { public SVDBExpr fExpr ; public SVDBClockingBlock ( ) { super ( "" , SVDBItemType . ClockingBlock ) ; } public SVDBClockingBlock ( String name ) { super ( name , SVDBItemType . ClockingBlock ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } @ Override public SVDBClockingBlock duplicate ( ) { return ( SVDBClockingBlock ) SVDBItemUtils . duplicate ( this ) ; } @ Override public void init ( SVDBItemBase other ) { super . init ( other ) ; } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBSearchEngine { private ISVDBIndexIterator fSearchContext ; private SVDBSearchSpecification fSearchSpec ; private IProgressMonitor fProgressMonitor ; public SVDBSearchEngine ( ISVDBIndexIterator search_ctxt ) { fSearchContext = search_ctxt ; } public synchronized List < ISVDBItemBase > find ( SVDBSearchSpecification spec , IProgressMonitor monitor ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; fProgressMonitor = monitor ; fSearchSpec = spec ; switch ( spec . getSearchType ( ) ) { case Package : if ( spec . getSearchUsage ( ) == SVDBSearchUsage . Declaration || spec . getSearchUsage ( ) == SVDBSearchUsage . All ) { find_package_decl ( ret ) ; } if ( spec . getSearchUsage ( ) == SVDBSearchUsage . Reference || spec . getSearchUsage ( ) == SVDBSearchUsage . All ) { find_package_refs ( ret ) ; } break ; case Method : if ( spec . getSearchUsage ( ) == SVDBSearchUsage . Declaration || spec . getSearchUsage ( ) == SVDBSearchUsage . All ) { find_method_decl ( ret ) ; } if ( spec . getSearchUsage ( ) == SVDBSearchUsage . Reference || spec . getSearchUsage ( ) == SVDBSearchUsage . All ) { find_method_refs ( ret ) ; } break ; case Type : if ( spec . getSearchUsage ( ) == SVDBSearchUsage . Declaration || spec . getSearchUsage ( ) == SVDBSearchUsage . All ) { find_type_decl ( ret ) ; } if ( spec . getSearchUsage ( ) == SVDBSearchUsage . Reference || spec . getSearchUsage ( ) == SVDBSearchUsage . All ) { find_type_refs ( ret ) ; } break ; case Field : if ( spec . getSearchUsage ( ) == SVDBSearchUsage . Declaration || spec . getSearchUsage ( ) == SVDBSearchUsage . All ) { find_field_decl ( ret ) ; } if ( spec . getSearchUsage ( ) == SVDBSearchUsage . Reference || spec . getSearchUsage ( ) == SVDBSearchUsage . All ) { find_field_refs ( ret ) ; } break ; } return ret ; } private void find_package_decl ( List < ISVDBItemBase > items ) { ISVDBItemIterator iterator = fSearchContext . getItemIterator ( fProgressMonitor ) ; while ( iterator . hasNext ( SVDBItemType . PackageDecl ) ) { SVDBItem pkg = ( SVDBPackageDecl ) iterator . nextItem ( SVDBItemType . PackageDecl ) ; if ( fSearchSpec . match ( pkg . getName ( ) ) ) { items . add ( pkg ) ; } } } private void find_package_refs ( List < ISVDBItemBase > items ) { System . out . println ( "" ) ; } private void find_type_decl ( List < ISVDBItemBase > items ) { ISVDBItemIterator iterator = fSearchContext . getItemIterator ( fProgressMonitor ) ; SVDBItemType types [ ] = new SVDBItemType [ ] { SVDBItemType . ClassDecl , SVDBItemType . TypedefStmt , SVDBItemType . ModuleDecl } ; while ( iterator . hasNext ( types ) ) { ISVDBItemBase item = iterator . nextItem ( types ) ; if ( item . getType ( ) == SVDBItemType . TypedefStmt ) { SVDBTypedefStmt td = ( SVDBTypedefStmt ) item ; if ( td . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoStruct ) { continue ; } } if ( fSearchSpec . match ( SVDBItem . getName ( item ) ) ) { items . add ( item ) ; } } } private void find_type_refs ( List < ISVDBItemBase > items ) { ISVDBItemIterator iterator = fSearchContext . getItemIterator ( fProgressMonitor ) ; SVDBItemType types [ ] = new SVDBItemType [ ] { SVDBItemType . VarDeclStmt , SVDBItemType . ModIfcInst } ; while ( iterator . hasNext ( types ) ) { ISVDBItemBase item = iterator . nextItem ( types ) ; String match_name = "" ; if ( item . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt decl = ( SVDBVarDeclStmt ) item ; match_name = decl . getTypeInfo ( ) . getName ( ) ; } else if ( item . getType ( ) == SVDBItemType . ModIfcInst ) { SVDBModIfcInst inst = ( SVDBModIfcInst ) item ; match_name = inst . getTypeName ( ) ; } if ( fSearchSpec . match ( match_name ) ) { items . add ( item ) ; } } } private void find_method_decl ( List < ISVDBItemBase > items ) { ISVDBItemIterator iterator = fSearchContext . getItemIterator ( fProgressMonitor ) ; SVDBItemType types [ ] = new SVDBItemType [ ] { SVDBItemType . Function , SVDBItemType . Task } ; while ( iterator . hasNext ( types ) ) { ISVDBItemBase item = iterator . nextItem ( ) ; String name = SVDBItem . getName ( item ) ; if ( name . indexOf ( "" ) != - ) { name = name . substring ( name . lastIndexOf ( "" ) + ) ; } if ( fSearchSpec . match ( name ) ) { items . add ( item ) ; } } } private void find_method_refs ( List < ISVDBItemBase > items ) { } private void find_field_decl ( List < ISVDBItemBase > items ) { ISVDBItemIterator iterator = fSearchContext . getItemIterator ( fProgressMonitor ) ; SVDBItemType types [ ] = new SVDBItemType [ ] { SVDBItemType . VarDeclStmt , SVDBItemType . ModIfcInst } ; while ( iterator . hasNext ( types ) ) { ISVDBItemBase item = iterator . nextItem ( ) ; String name = SVDBItem . getName ( item ) ; if ( fSearchSpec . match ( name ) ) { items . add ( item ) ; } } } private void find_field_refs ( List < ISVDBItemBase > items ) { } } package net . sf . sveditor . core . db . search ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class SVDBSearchSpecification { private String fExpr ; private boolean fCaseSensitive ; private boolean fRegExp ; private SVDBSearchType fType ; private SVDBSearchUsage fUsage ; private Pattern fPattern ; public SVDBSearchSpecification ( String expr , boolean case_sensitive , boolean reg_exp , SVDBSearchType type , SVDBSearchUsage usage ) { fExpr = expr ; fCaseSensitive = case_sensitive ; fRegExp = reg_exp ; fType = type ; fUsage = usage ; int flags = ; if ( ! fCaseSensitive ) { flags |= Pattern . CASE_INSENSITIVE ; } if ( ! fRegExp ) { flags |= Pattern . LITERAL ; } fPattern = Pattern . compile ( expr , flags ) ; } public SVDBSearchSpecification ( String expr , boolean case_sensitive , boolean reg_exp ) { this ( expr , case_sensitive , reg_exp , SVDBSearchType . Type , SVDBSearchUsage . All ) ; } public void setSearchType ( SVDBSearchType type ) { fType = type ; } public SVDBSearchType getSearchType ( ) { return fType ; } public void setSearchUsage ( SVDBSearchUsage usage ) { fUsage = usage ; } public SVDBSearchUsage getSearchUsage ( ) { return fUsage ; } public String getExpr ( ) { return fExpr ; } public boolean isRegExp ( ) { return fRegExp ; } public boolean isCaseSensitive ( ) { return fCaseSensitive ; } public boolean match ( String name ) { Matcher m = fPattern . matcher ( name ) ; if ( fRegExp ) { return m . matches ( ) ; } else { return ( m . find ( ) && m . start ( ) == ) ; } } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBFindNamedModIfcClassIfc { private ISVDBIndexIterator fIndexIt ; private ISVDBFindNameMatcher fMatcher ; public SVDBFindNamedModIfcClassIfc ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIt = index_it ; fMatcher = matcher ; } public SVDBFindNamedModIfcClassIfc ( ISVDBIndexIterator index_it ) { this ( index_it , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; } public List < ISVDBChildItem > find ( String type_name ) { List < ISVDBChildItem > ret = new ArrayList < ISVDBChildItem > ( ) ; List < SVDBDeclCacheItem > found = fIndexIt . findGlobalScopeDecl ( new NullProgressMonitor ( ) , type_name , fMatcher ) ; for ( SVDBDeclCacheItem ci : found ) { if ( ci . getType ( ) . isElemOf ( SVDBItemType . ClassDecl , SVDBItemType . ModuleDecl , SVDBItemType . InterfaceDecl ) ) { ret . add ( ( ISVDBChildItem ) ci . getSVDBItem ( ) ) ; } } return ret ; } } package net . sf . sveditor . core . db . search ; public enum SVDBSearchUsage { All , Reference , Declaration } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFindPackageDefaultNameMatcher implements ISVDBFindNameMatcher { static SVDBFindPackageDefaultNameMatcher fDefault ; public boolean match ( ISVDBNamedItem it , String name ) { return ( it . getType ( ) == SVDBItemType . PackageDecl && it . getName ( ) != null && it . getName ( ) . equals ( name ) ) ; } public static SVDBFindPackageDefaultNameMatcher getDefault ( ) { if ( fDefault == null ) { fDefault = new SVDBFindPackageDefaultNameMatcher ( ) ; } return fDefault ; } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBFindNamedClass { private ISVDBIndexIterator fIndexIt ; private ISVDBFindNameMatcher fMatcher ; public SVDBFindNamedClass ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIt = index_it ; fMatcher = matcher ; } public SVDBFindNamedClass ( ISVDBIndexIterator index_it ) { this ( index_it , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; } public List < SVDBClassDecl > find ( String type_name ) { List < SVDBClassDecl > ret = new ArrayList < SVDBClassDecl > ( ) ; List < SVDBDeclCacheItem > found = fIndexIt . findGlobalScopeDecl ( new NullProgressMonitor ( ) , type_name , fMatcher ) ; for ( SVDBDeclCacheItem ci : found ) { if ( ci . getType ( ) == SVDBItemType . ClassDecl ) { ret . add ( ( SVDBClassDecl ) ci . getSVDBItem ( ) ) ; } } return ret ; } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . SVDBScopeItem ; public interface ISVDBFileContextIndexSearcher extends ISVDBIndexSearcher { SVDBScopeItem findActiveScope ( int lineno ) ; } package net . sf . sveditor . core . db . search ; import java . util . List ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBTypeInfoClassType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; public class SVDBFindSuperClass { ISVDBIndexIterator fIndexIterator ; private ISVDBFindNameMatcher fMatcher ; public SVDBFindSuperClass ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIterator = index_it ; fMatcher = matcher ; } public SVDBFindSuperClass ( ISVDBIndexIterator index_it ) { this ( index_it , SVDBFindClassDefaultNameMatcher . getDefault ( ) ) ; } public SVDBClassDecl find ( SVDBClassDecl cls ) { if ( cls . getSuperClass ( ) != null ) { SVDBFindNamedClass finder = new SVDBFindNamedClass ( fIndexIterator , fMatcher ) ; SVDBTypeInfoClassType cls_type = cls . getSuperClass ( ) ; List < SVDBClassDecl > ret = finder . find ( cls_type . getName ( ) ) ; return ( ret . size ( ) > ) ? ret . get ( ) : null ; } else { return null ; } } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFindContentAssistNameMatcher implements ISVDBFindNameMatcher { private SVDBItemType fItemTypes [ ] ; public SVDBFindContentAssistNameMatcher ( SVDBItemType ... types ) { fItemTypes = types ; } public boolean match ( ISVDBNamedItem it , String name ) { if ( ( fItemTypes . length == || it . getType ( ) . isElemOf ( fItemTypes ) ) && it . getName ( ) != null ) { String it_lower = it . getName ( ) . toLowerCase ( ) ; String n_lower = name . toLowerCase ( ) ; if ( name . equals ( "" ) || it_lower . startsWith ( n_lower ) ) { return true ; } } return false ; } } package net . sf . sveditor . core . db . search ; public class BuiltinClassFactory { } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcClassParam ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . SVDBTypeInfoEnumerator ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVDBFindByNameInScopes { private ISVDBFindNameMatcher fMatcher ; private LogHandle fLog ; public SVDBFindByNameInScopes ( ISVDBIndexIterator index_it ) { fMatcher = SVDBFindDefaultNameMatcher . getDefault ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public SVDBFindByNameInScopes ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fMatcher = matcher ; fLog = LogFactory . getLogHandle ( "" ) ; } public List < ISVDBItemBase > find ( ISVDBChildItem context , String name , boolean stop_on_first_match , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; fLog . debug ( "" + ( ( context != null ) ? SVDBItem . getName ( context ) : "" ) + "" + ( ( context != null ) ? context . getType ( ) : "" ) + "" + name ) ; while ( context != null && context instanceof ISVDBChildParent ) { if ( context . getType ( ) == SVDBItemType . ClassDecl ) { SVDBClassDecl cls = ( SVDBClassDecl ) context ; if ( cls . getParameters ( ) != null ) { for ( SVDBModIfcClassParam p : cls . getParameters ( ) ) { if ( fMatcher . match ( p , name ) ) { ret . add ( p ) ; } } } } for ( ISVDBItemBase it : ( ( ISVDBChildParent ) context ) . getChildren ( ) ) { fLog . debug ( "" + SVDBItem . getName ( context ) + "" + SVDBItem . getName ( it ) ) ; if ( it instanceof SVDBVarDeclStmt ) { for ( ISVDBItemBase it_t : ( ( SVDBVarDeclStmt ) it ) . getChildren ( ) ) { fLog . debug ( "" + SVDBItem . getName ( it_t ) + "" + name + "" ) ; if ( it_t instanceof ISVDBNamedItem && fMatcher . match ( ( ISVDBNamedItem ) it_t , name ) ) { boolean match = ( types . length == || it_t . getType ( ) . isElemOf ( types ) ) ; if ( match ) { fLog . debug ( "" + SVDBItem . getName ( it_t ) ) ; ret . add ( it_t ) ; if ( stop_on_first_match ) { break ; } } } } } else if ( it instanceof SVDBModIfcInst ) { for ( ISVDBItemBase it_t : ( ( SVDBModIfcInst ) it ) . getChildren ( ) ) { if ( it_t instanceof ISVDBNamedItem && fMatcher . match ( ( ISVDBNamedItem ) it_t , name ) ) { boolean match = ( types . length == ) ; for ( SVDBItemType t : types ) { if ( it_t . getType ( ) == t ) { match = true ; break ; } } if ( match ) { ret . add ( it_t ) ; if ( stop_on_first_match ) { break ; } } } } } else if ( it . getType ( ) == SVDBItemType . TypedefStmt && ( ( SVDBTypedefStmt ) it ) . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoEnum ) { SVDBTypeInfoEnum e = ( SVDBTypeInfoEnum ) ( ( SVDBTypedefStmt ) it ) . getTypeInfo ( ) ; for ( SVDBTypeInfoEnumerator en : e . getEnumerators ( ) ) { if ( fMatcher . match ( en , name ) ) { ret . add ( en ) ; if ( stop_on_first_match ) { break ; } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } } else { if ( it instanceof ISVDBNamedItem && fMatcher . match ( ( ISVDBNamedItem ) it , name ) ) { boolean match = ( types . length == ) ; for ( SVDBItemType t : types ) { if ( it . getType ( ) == t ) { match = true ; break ; } } if ( match ) { ret . add ( it ) ; if ( stop_on_first_match ) { break ; } } } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } if ( context . getType ( ) . isElemOf ( SVDBItemType . Function , SVDBItemType . Task ) ) { for ( SVDBParamPortDecl p : ( ( SVDBTask ) context ) . getParams ( ) ) { for ( ISVDBChildItem pi : p . getChildren ( ) ) { fLog . debug ( "" + SVDBItem . getName ( pi ) + "" ) ; if ( fMatcher . match ( ( ISVDBNamedItem ) pi , name ) ) { ret . add ( pi ) ; if ( stop_on_first_match ) { break ; } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } fLog . debug ( "" + context . getType ( ) ) ; if ( context . getType ( ) == SVDBItemType . ClassDecl ) { } else if ( context . getType ( ) == SVDBItemType . ModuleDecl || context . getType ( ) == SVDBItemType . InterfaceDecl ) { List < SVDBParamPortDecl > p_list = ( ( SVDBModIfcDecl ) context ) . getPorts ( ) ; for ( SVDBParamPortDecl p : p_list ) { for ( ISVDBChildItem c : p . getChildren ( ) ) { SVDBVarDeclItem pi = ( SVDBVarDeclItem ) c ; fLog . debug ( "" + pi . getName ( ) + "" + name ) ; if ( fMatcher . match ( ( ISVDBNamedItem ) pi , name ) ) { ret . add ( pi ) ; if ( ret . size ( ) > && stop_on_first_match ) { break ; } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } while ( ( context = context . getParent ( ) ) != null && ! ( context instanceof ISVDBChildParent ) ) { } fLog . debug ( "" + ( ( context != null ) ? context . getType ( ) : "" ) ) ; } fLog . debug ( "" + ( ( context != null ) ? SVDBItem . getName ( context ) : "" ) + "" + name ) ; return ret ; } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; public class SVDBFindReferences extends SVDBElemIterator { public List < ISVDBItemBase > find_class_refs ( String name ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; return ret ; } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFindModuleMatcher implements ISVDBFindNameMatcher { public boolean match ( ISVDBNamedItem it , String name ) { return ( it . getType ( ) == SVDBItemType . ModuleDecl ) ; } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFindPackageMatcher implements ISVDBFindNameMatcher { public boolean match ( ISVDBNamedItem it , String name ) { return ( it . getType ( ) == SVDBItemType . PackageDecl ) ; } } package net . sf . sveditor . core . db . search ; import java . util . List ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBScopeItem ; public interface ISVDBIndexSearcher { SVDBModIfcDecl findNamedModClassIfc ( String name ) ; void visitItems ( ISVDBItemVisitor visitor , SVDBItemType type ) ; void visitItemsInTypeHierarchy ( SVDBScopeItem scope , ISVDBItemVisitor visitor ) ; List < SVDBItem > findByNameInScopes ( String name , SVDBScopeItem scope , boolean stop_on_first_match , SVDBItemType ... type_filter ) ; List < SVDBItem > findVarsByNameInScopes ( String name , SVDBScopeItem scope , boolean stop_on_first_match ) ; List < SVDBItem > findByName ( String name , SVDBItemType ... type_filter ) ; List < SVDBItem > findByNameInClassHierarchy ( String name , SVDBScopeItem scope , SVDBItemType ... type_filter ) ; SVDBModIfcDecl findSuperClass ( SVDBModIfcDecl cls ) ; SVDBFile findIncludedFile ( String path ) ; } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFindInterfaceMatcher implements ISVDBFindNameMatcher { public boolean match ( ISVDBNamedItem it , String name ) { return ( it . getType ( ) == SVDBItemType . InterfaceDecl ) ; } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; public class SVDBFindVarsByNameInScopes { private ISVDBIndexIterator fIndexIterator ; private ISVDBFindNameMatcher fMatcher ; private SVDBFindDefaultNameMatcher fDefaultMatcher ; public SVDBFindVarsByNameInScopes ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIterator = index_it ; fMatcher = matcher ; fDefaultMatcher = new SVDBFindDefaultNameMatcher ( ) ; } public List < ISVDBItemBase > find ( ISVDBChildItem context , String name , boolean stop_on_first_match ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; ISVDBChildItem context_save = context ; while ( context != null && context instanceof ISVDBChildParent ) { for ( ISVDBItemBase it : ( ( ISVDBChildParent ) context ) . getChildren ( ) ) { if ( SVDBStmt . isType ( it , SVDBItemType . VarDeclStmt ) ) { boolean stop = false ; for ( ISVDBChildItem c : ( ( SVDBVarDeclStmt ) it ) . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; if ( vi . getName ( ) . equals ( name ) ) { ret . add ( vi ) ; if ( stop_on_first_match ) { stop = true ; break ; } } if ( stop ) { break ; } } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } if ( context . getType ( ) == SVDBItemType . Function || context . getType ( ) == SVDBItemType . Task ) { for ( SVDBParamPortDecl it : ( ( SVDBTask ) context ) . getParams ( ) ) { boolean stop = false ; for ( ISVDBChildItem c : it . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; if ( fMatcher . match ( vi , name ) ) { ret . add ( vi ) ; if ( stop_on_first_match ) { stop = true ; break ; } } } if ( stop ) { break ; } } } else if ( context . getType ( ) == SVDBItemType . ModuleDecl ) { SVDBModIfcDecl m = ( SVDBModIfcDecl ) context ; for ( SVDBParamPortDecl p : m . getPorts ( ) ) { boolean stop = false ; for ( ISVDBChildItem c : p . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; if ( fMatcher . match ( vi , name ) ) { ret . add ( vi ) ; if ( stop_on_first_match ) { stop = true ; break ; } } } if ( stop ) { break ; } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } context = context . getParent ( ) ; } if ( ret . size ( ) == || ! stop_on_first_match ) { context = context_save ; while ( context != null && context . getType ( ) != SVDBItemType . ClassDecl ) { context = context . getParent ( ) ; } if ( context != null ) { SVDBClassDecl cls = ( SVDBClassDecl ) context ; while ( cls != null ) { for ( ISVDBItemBase it : cls . getChildren ( ) ) { if ( SVDBStmt . isType ( it , SVDBItemType . VarDeclStmt ) || it . getType ( ) == SVDBItemType . Covergroup || it . getType ( ) == SVDBItemType . Coverpoint ) { if ( fMatcher . match ( ( ISVDBNamedItem ) it , name ) ) { ret . add ( it ) ; if ( stop_on_first_match ) { break ; } } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } SVDBFindSuperClass finder = new SVDBFindSuperClass ( fIndexIterator , fDefaultMatcher ) ; cls = finder . find ( cls ) ; } } } return ret ; } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; public class SVDBFindDefaultNameMatcher implements ISVDBFindNameMatcher { static SVDBFindDefaultNameMatcher fDefault ; public boolean match ( ISVDBNamedItem it , String name ) { return ( it . getName ( ) != null && it . getName ( ) . equals ( name ) ) ; } public static SVDBFindDefaultNameMatcher getDefault ( ) { if ( fDefault == null ) { fDefault = new SVDBFindDefaultNameMatcher ( ) ; } return fDefault ; } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBFindNamedPackage { private ISVDBIndexIterator fIndexIt ; private ISVDBFindNameMatcher fMatcher ; public SVDBFindNamedPackage ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIt = index_it ; fMatcher = matcher ; } public SVDBFindNamedPackage ( ISVDBIndexIterator index_it ) { this ( index_it , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; } public List < ISVDBChildItem > find ( String type_name ) { List < ISVDBChildItem > ret = new ArrayList < ISVDBChildItem > ( ) ; List < SVDBDeclCacheItem > found = fIndexIt . findGlobalScopeDecl ( new NullProgressMonitor ( ) , type_name , fMatcher ) ; for ( SVDBDeclCacheItem ci : found ) { if ( ci . getType ( ) == SVDBItemType . PackageDecl ) { ret . add ( ( ISVDBChildItem ) ci . getSVDBItem ( ) ) ; } } return ret ; } } package net . sf . sveditor . core . db . search ; import java . util . regex . Pattern ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBContentAssistIncludeNameMatcher extends SVDBFindContentAssistNameMatcher { private static Pattern fWinPathPattern ; static { fWinPathPattern = Pattern . compile ( "" ) ; } @ Override public boolean match ( ISVDBNamedItem it , String name ) { if ( it . getType ( ) == SVDBItemType . File ) { String norm_path = fWinPathPattern . matcher ( it . getName ( ) ) . replaceAll ( "" ) ; String last_elem = norm_path ; if ( norm_path . indexOf ( '' ) != - ) { last_elem = norm_path . substring ( norm_path . lastIndexOf ( '' ) + ) ; } last_elem = last_elem . toLowerCase ( ) ; name = name . toLowerCase ( ) ; return last_elem . startsWith ( name ) ; } else { return super . match ( it , name ) ; } } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; public interface ISVDBFindNameMatcher { boolean match ( ISVDBNamedItem it , String name ) ; } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBFindByName { private ISVDBIndexIterator fIndexIterator ; private ISVDBFindNameMatcher fMatcher ; private LogHandle fLog ; public SVDBFindByName ( ISVDBIndexIterator index_it ) { this ( index_it , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; } public SVDBFindByName ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIterator = index_it ; fMatcher = matcher ; fLog = LogFactory . getLogHandle ( "" ) ; } public List < ISVDBItemBase > find ( String name , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; List < SVDBDeclCacheItem > found = fIndexIterator . findGlobalScopeDecl ( new NullProgressMonitor ( ) , name , fMatcher ) ; for ( SVDBDeclCacheItem item : found ) { if ( item . getType ( ) . isElemOf ( types ) ) { if ( item . getSVDBItem ( ) != null ) { ret . add ( item . getSVDBItem ( ) ) ; } else { try { throw new Exception ( ) ; } catch ( Exception e ) { fLog . error ( "" + item . getType ( ) + "" + item . getName ( ) + "" , e ) ; } } } } return ret ; } } package net . sf . sveditor . core . db . search ; import java . util . List ; import net . sf . sveditor . core . db . SVDBFile ; public interface ISVDBPreProcIndexSearcher { List < SVDBSearchResult < SVDBFile > > findPreProcFile ( String path , boolean search_shadow ) ; List < SVDBSearchResult < SVDBFile > > findIncParent ( SVDBFile file ) ; } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFindClassDefaultNameMatcher implements ISVDBFindNameMatcher { static SVDBFindClassDefaultNameMatcher fDefault ; public boolean match ( ISVDBNamedItem it , String name ) { return ( it . getType ( ) == SVDBItemType . ClassDecl && it . getName ( ) != null && it . getName ( ) . equals ( name ) ) ; } public static SVDBFindClassDefaultNameMatcher getDefault ( ) { if ( fDefault == null ) { fDefault = new SVDBFindClassDefaultNameMatcher ( ) ; } return fDefault ; } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBTypeInfoStruct ; public class SVDBStructFieldFinder { private ISVDBFindNameMatcher fMatcher ; public SVDBStructFieldFinder ( ISVDBFindNameMatcher matcher ) { fMatcher = matcher ; } public List < ISVDBItemBase > find ( SVDBTypeInfoStruct struct , String name ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; for ( ISVDBItemBase it : struct . getFields ( ) ) { if ( it instanceof ISVDBNamedItem ) { if ( fMatcher . match ( ( ISVDBNamedItem ) it , name ) ) { ret . add ( it ) ; } } } return ret ; } } package net . sf . sveditor . core . db . search ; public enum SVDBSearchType { Type , Method , Package , Field } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; public interface ISVDBItemVisitor { int CONTINUE = ; int DONT_RECURSE = ; int CANCEL = ; int accept ( ISVDBIndex index , SVDBItem item ) ; } package net . sf . sveditor . core . db . search ; import java . util . List ; import java . util . Stack ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBAssign ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBClockingBlock ; import net . sf . sveditor . core . db . SVDBConstraint ; import net . sf . sveditor . core . db . SVDBCoverCrossBinsSel ; import net . sf . sveditor . core . db . SVDBCovergroup ; import net . sf . sveditor . core . db . SVDBCoverpoint ; import net . sf . sveditor . core . db . SVDBCoverpointBins ; import net . sf . sveditor . core . db . SVDBCoverpointCross ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBGenerateBlock ; import net . sf . sveditor . core . db . SVDBGenerateFor ; import net . sf . sveditor . core . db . SVDBGenerateIf ; import net . sf . sveditor . core . db . SVDBGenerateRegion ; import net . sf . sveditor . core . db . SVDBInclude ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMacroDef ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBModIfcClassParam ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . SVDBModportClockingPortDecl ; import net . sf . sveditor . core . db . SVDBModportDecl ; import net . sf . sveditor . core . db . SVDBModportItem ; import net . sf . sveditor . core . db . SVDBModportPortsDecl ; import net . sf . sveditor . core . db . SVDBModportSimplePort ; import net . sf . sveditor . core . db . SVDBModportSimplePortsDecl ; import net . sf . sveditor . core . db . SVDBModportTFPort ; import net . sf . sveditor . core . db . SVDBModportTFPortsDecl ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . SVDBParamValueAssign ; import net . sf . sveditor . core . db . SVDBParamValueAssignList ; import net . sf . sveditor . core . db . SVDBPreProcCond ; import net . sf . sveditor . core . db . SVDBProgramDecl ; import net . sf . sveditor . core . db . SVDBProperty ; import net . sf . sveditor . core . db . SVDBSequence ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltinNet ; import net . sf . sveditor . core . db . SVDBTypeInfoClassItem ; import net . sf . sveditor . core . db . SVDBTypeInfoClassType ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . SVDBTypeInfoFwdDecl ; import net . sf . sveditor . core . db . SVDBTypeInfoModuleIfc ; import net . sf . sveditor . core . db . SVDBTypeInfoStruct ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . stmt . SVDBActionBlockStmt ; import net . sf . sveditor . core . db . stmt . SVDBAlwaysStmt ; import net . sf . sveditor . core . db . stmt . SVDBAssertStmt ; import net . sf . sveditor . core . db . stmt . SVDBAssignStmt ; import net . sf . sveditor . core . db . stmt . SVDBAssumeStmt ; import net . sf . sveditor . core . db . stmt . SVDBBlockStmt ; import net . sf . sveditor . core . db . stmt . SVDBLabeledStmt ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; public class SVDBElemIterator { private Stack < ISVDBItemBase > fStack ; public SVDBElemIterator ( ) { fStack = new Stack < ISVDBItemBase > ( ) ; } public void visit ( ISVDBItemBase item ) { fStack . clear ( ) ; visit_int ( item ) ; } protected void visit_int ( ISVDBItemBase item ) { switch ( item . getType ( ) ) { case File : file ( ( SVDBFile ) item ) ; break ; case ModuleDecl : module_decl ( ( SVDBModIfcDecl ) item ) ; break ; case ClassDecl : class_decl ( ( SVDBClassDecl ) item ) ; break ; case InterfaceDecl : interface_decl ( ( SVDBModIfcDecl ) item ) ; break ; case ProgramDecl : program_decl ( ( SVDBProgramDecl ) item ) ; break ; case Task : case Function : tf_decl ( ( SVDBTask ) item ) ; break ; case ModIfcInst : mod_ifc_inst ( ( SVDBModIfcInst ) item ) ; break ; case ModIfcInstItem : mod_ifc_inst_item ( ( SVDBModIfcInstItem ) item ) ; break ; case ModportDecl : modport_decl ( ( SVDBModportDecl ) item ) ; break ; case ModportItem : modport_item ( ( SVDBModportItem ) item ) ; break ; case ModportSimplePortsDecl : modport_simple_ports_decl ( ( SVDBModportSimplePortsDecl ) item ) ; break ; case ModportSimplePort : modport_simple_port ( ( SVDBModportSimplePort ) item ) ; break ; case ModportClockingPortDecl : modport_clocking_port_decl ( ( SVDBModportClockingPortDecl ) item ) ; break ; case ModportTFPortsDecl : modport_tf_ports_decl ( ( SVDBModportTFPortsDecl ) item ) ; break ; case ModportTFPort : modport_tf_port ( ( SVDBModportTFPort ) item ) ; break ; case MacroDef : macro_def ( ( SVDBMacroDef ) item ) ; break ; case PreProcCond : pre_proc_cond ( ( SVDBPreProcCond ) item ) ; break ; case Include : include ( ( SVDBInclude ) item ) ; break ; case PackageDecl : package_decl ( ( SVDBPackageDecl ) item ) ; break ; case Covergroup : covergroup ( ( SVDBCovergroup ) item ) ; break ; case Coverpoint : coverpoint ( ( SVDBCoverpoint ) item ) ; break ; case CoverpointBins : coverpoint_bins ( ( SVDBCoverpointBins ) item ) ; break ; case CoverpointCross : coverpoint_cross ( ( SVDBCoverpointCross ) item ) ; break ; case CoverCrossBinsSel : cover_cross_bins_sel ( ( SVDBCoverCrossBinsSel ) item ) ; break ; case Sequence : sequence ( ( SVDBSequence ) item ) ; break ; case Property : property ( ( SVDBProperty ) item ) ; break ; case ModIfcClassParam : mod_ifc_class_param ( ( SVDBModIfcClassParam ) item ) ; break ; case Constraint : constraint ( ( SVDBConstraint ) item ) ; break ; case Assign : assign ( ( SVDBAssign ) item ) ; break ; case Marker : marker ( ( SVDBMarker ) item ) ; break ; case ParamValueAssign : param_value_assign ( ( SVDBParamValueAssign ) item ) ; break ; case ParamValueAssignList : param_value_assign_list ( ( SVDBParamValueAssignList ) item ) ; break ; case GenerateBlock : generate_block ( ( SVDBGenerateBlock ) item ) ; break ; case GenerateFor : generate_for ( ( SVDBGenerateFor ) item ) ; break ; case GenerateIf : generate_if ( ( SVDBGenerateIf ) item ) ; break ; case GenerateRegion : generate_region ( ( SVDBGenerateRegion ) item ) ; break ; case ClockingBlock : clocking_block ( ( SVDBClockingBlock ) item ) ; break ; case TypeInfoBuiltin : type_info_builtin ( ( SVDBTypeInfoBuiltin ) item ) ; break ; case TypeInfoBuiltinNet : type_info_builtin_net ( ( SVDBTypeInfoBuiltinNet ) item ) ; break ; case TypeInfoClassItem : type_info_class_item ( ( SVDBTypeInfoClassItem ) item ) ; break ; case TypeInfoClassType : type_info_class_type ( ( SVDBTypeInfoClassType ) item ) ; break ; case TypeInfoEnum : type_info_enum ( ( SVDBTypeInfoEnum ) item ) ; break ; case TypeInfoFwdDecl : type_info_fwd_decl ( ( SVDBTypeInfoFwdDecl ) item ) ; break ; case TypeInfoStruct : type_info_struct ( ( SVDBTypeInfoStruct ) item ) ; break ; case TypeInfoUserDef : type_info_user_def ( ( SVDBTypeInfoUserDef ) item ) ; break ; case TypeInfoModuleIfc : type_info_module_ifc ( ( SVDBTypeInfoModuleIfc ) item ) ; break ; case ActionBlockStmt : action_block_stmt ( ( SVDBActionBlockStmt ) item ) ; break ; case AlwaysStmt : always_stmt ( ( SVDBAlwaysStmt ) item ) ; break ; case AssertStmt : assert_stmt ( ( SVDBAssertStmt ) item ) ; break ; case AssignStmt : assign_stmt ( ( SVDBAssignStmt ) item ) ; break ; case AssumeStmt : assume_stmt ( ( SVDBAssumeStmt ) item ) ; break ; case LabeledStmt : labeled_stmt ( ( SVDBLabeledStmt ) item ) ; break ; case BlockStmt : block_stmt ( ( SVDBBlockStmt ) item ) ; break ; case VarDeclStmt : var_decl_stmt ( ( SVDBVarDeclStmt ) item ) ; break ; case VarDeclItem : var_decl_item ( ( SVDBVarDeclItem ) item ) ; break ; } } protected void file ( SVDBFile file ) { fStack . push ( file ) ; for ( ISVDBChildItem item : file . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void module_decl ( SVDBModIfcDecl module ) { fStack . push ( module ) ; for ( ISVDBChildItem item : module . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void class_decl ( SVDBClassDecl cls ) { fStack . push ( cls ) ; for ( ISVDBChildItem item : cls . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void interface_decl ( SVDBModIfcDecl ifc ) { fStack . push ( ifc ) ; for ( ISVDBChildItem item : ifc . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void program_decl ( SVDBProgramDecl prog ) { fStack . push ( prog ) ; for ( ISVDBChildItem item : prog . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void tf_decl ( SVDBTask tf ) { fStack . push ( tf ) ; if ( tf . getType ( ) == SVDBItemType . Function ) { visit ( ( ( SVDBFunction ) tf ) . getReturnType ( ) ) ; } tf_param_port_list ( tf . getParams ( ) ) ; fStack . pop ( ) ; } protected void tf_param_port_list ( List < SVDBParamPortDecl > ports ) { for ( SVDBParamPortDecl p : ports ) { visit ( p ) ; } } protected void mod_ifc_inst ( SVDBModIfcInst inst ) { fStack . push ( inst ) ; for ( ISVDBChildItem item : inst . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void mod_ifc_inst_item ( SVDBModIfcInstItem item ) { fStack . push ( item ) ; visit ( item . getPortMap ( ) ) ; fStack . pop ( ) ; } protected void modport_decl ( SVDBModportDecl decl ) { fStack . push ( decl ) ; for ( ISVDBChildItem pi : decl . getChildren ( ) ) { visit ( pi ) ; } fStack . pop ( ) ; } protected void modport_item ( SVDBModportItem item ) { for ( SVDBModportPortsDecl p : item . getPortsList ( ) ) { visit ( p ) ; } } protected void modport_simple_ports_decl ( SVDBModportSimplePortsDecl decl ) { fStack . push ( decl ) ; for ( SVDBModportSimplePort p : decl . getPortList ( ) ) { visit ( p ) ; } fStack . pop ( ) ; } protected void modport_simple_port ( SVDBModportSimplePort port ) { fStack . push ( port ) ; visit ( port . getExpr ( ) ) ; fStack . pop ( ) ; } protected void modport_clocking_port_decl ( SVDBModportClockingPortDecl port ) { } protected void modport_tf_ports_decl ( SVDBModportTFPortsDecl port ) { for ( ISVDBChildItem p : port . getPorts ( ) ) { visit ( p ) ; } } protected void modport_tf_port ( SVDBModportTFPort port ) { } protected void macro_def ( SVDBMacroDef macro ) { } protected void pre_proc_cond ( SVDBPreProcCond cond ) { fStack . push ( cond ) ; for ( ISVDBChildItem item : cond . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void include ( SVDBInclude inc ) { } protected void package_decl ( SVDBPackageDecl pkg ) { fStack . push ( pkg ) ; for ( ISVDBChildItem item : pkg . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void covergroup ( SVDBCovergroup cg ) { fStack . push ( cg ) ; for ( ISVDBChildItem item : cg . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void coverpoint ( SVDBCoverpoint cp ) { fStack . push ( cp ) ; if ( cp . getIFF ( ) != null ) { visit ( cp . getIFF ( ) ) ; } for ( ISVDBChildItem item : cp . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void coverpoint_bins ( SVDBCoverpointBins bins ) { } protected void coverpoint_cross ( SVDBCoverpointCross cross ) { fStack . push ( cross ) ; for ( ISVDBChildItem item : cross . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void cover_cross_bins_sel ( SVDBCoverCrossBinsSel sel ) { } protected void sequence ( SVDBSequence seq ) { fStack . push ( seq ) ; for ( ISVDBChildItem item : seq . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void property ( SVDBProperty prop ) { fStack . push ( prop ) ; for ( ISVDBChildItem item : prop . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void mod_ifc_class_param ( SVDBModIfcClassParam param ) { fStack . push ( param ) ; visit ( param . getDefault ( ) ) ; fStack . pop ( ) ; } protected void constraint ( SVDBConstraint c ) { fStack . push ( c ) ; for ( ISVDBChildItem item : c . getChildren ( ) ) { visit ( item ) ; } fStack . pop ( ) ; } protected void assign ( SVDBAssign assign ) { fStack . push ( assign ) ; visit ( assign . getLHS ( ) ) ; visit ( assign . getRHS ( ) ) ; fStack . pop ( ) ; } protected void marker ( SVDBMarker marker ) { } protected void param_value_assign ( SVDBParamValueAssign assign ) { visit ( assign . getValue ( ) ) ; } protected void param_value_assign_list ( SVDBParamValueAssignList assign_list ) { fStack . push ( assign_list ) ; for ( SVDBParamValueAssign a : assign_list . getParameters ( ) ) { visit ( a ) ; } fStack . pop ( ) ; } protected void generate_block ( SVDBGenerateBlock block ) { fStack . push ( block ) ; for ( ISVDBChildItem c : block . getChildren ( ) ) { visit ( c ) ; } fStack . pop ( ) ; } protected void generate_for ( SVDBGenerateFor gen_for ) { } protected void generate_if ( SVDBGenerateIf gen_if ) { } protected void generate_region ( SVDBGenerateRegion region ) { } protected void clocking_block ( SVDBClockingBlock block ) { } protected void type_info_builtin ( SVDBTypeInfoBuiltin type ) { } protected void type_info_builtin_net ( SVDBTypeInfoBuiltinNet type ) { } protected void type_info_class_type ( SVDBTypeInfoClassType type ) { } protected void type_info_class_item ( SVDBTypeInfoClassItem type_item ) { } protected void type_info_enum ( SVDBTypeInfoEnum type ) { } protected void type_info_fwd_decl ( SVDBTypeInfoFwdDecl type ) { } protected void type_info_struct ( SVDBTypeInfoStruct type ) { } protected void type_info_module_ifc ( SVDBTypeInfoModuleIfc type ) { } protected void type_info_user_def ( SVDBTypeInfoUserDef type ) { } protected void action_block_stmt ( SVDBActionBlockStmt stmt ) { fStack . push ( stmt ) ; fStack . pop ( ) ; } protected void always_stmt ( SVDBAlwaysStmt stmt ) { fStack . push ( stmt ) ; visit ( stmt . getBody ( ) ) ; fStack . pop ( ) ; } protected void assert_stmt ( SVDBAssertStmt stmt ) { fStack . push ( stmt ) ; fStack . pop ( ) ; } protected void assign_stmt ( SVDBAssignStmt stmt ) { fStack . push ( stmt ) ; visit ( stmt . getLHS ( ) ) ; visit ( stmt . getRHS ( ) ) ; fStack . pop ( ) ; } protected void assume_stmt ( SVDBAssumeStmt stmt ) { } protected void labeled_stmt ( SVDBLabeledStmt stmt ) { visit ( stmt . getBody ( ) ) ; } protected void block_stmt ( SVDBBlockStmt block ) { fStack . push ( block ) ; for ( ISVDBChildItem c : block . getChildren ( ) ) { visit ( c ) ; } fStack . pop ( ) ; } protected void var_decl_stmt ( SVDBVarDeclStmt stmt ) { visit ( stmt . getTypeInfo ( ) ) ; for ( ISVDBChildItem c : stmt . getChildren ( ) ) { visit ( c ) ; } } protected void var_decl_item ( SVDBVarDeclItem item ) { if ( item . getInitExpr ( ) != null ) { visit ( item . getInitExpr ( ) ) ; } } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBDocComment ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBFindDocComment { private ISVDBIndexIterator fIndexIt ; private LogHandle fLog ; public SVDBFindDocComment ( ISVDBIndexIterator index_it ) { fIndexIt = index_it ; fLog = LogFactory . getLogHandle ( "" ) ; } public SVDBDocComment find ( IProgressMonitor monitor , ISVDBItemBase item ) { SVDBDocComment comment = null ; ISVDBItemBase p = item ; while ( p != null && p . getType ( ) != SVDBItemType . File ) { if ( p instanceof ISVDBChildItem ) { p = ( ( ISVDBChildItem ) p ) . getParent ( ) ; } else { p = null ; break ; } } if ( p == null ) { fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , SVDBItem . getName ( item ) ) ) ; return null ; } SVDBFile pp_file = fIndexIt . findPreProcFile ( monitor , ( ( SVDBFile ) p ) . getFilePath ( ) ) ; if ( pp_file != null ) { comment = find_comment ( pp_file , item ) ; } else { fLog . debug ( ILogLevel . LEVEL_MID , "" + ( ( SVDBFile ) p ) . getFilePath ( ) ) ; } return comment ; } private String cleanCommentNameForMatch ( String commentName ) { String cleaned = commentName . replaceAll ( "" , "" ) ; return cleaned ; } private SVDBDocComment find_comment ( ISVDBChildParent p , ISVDBItemBase item ) { SVDBDocComment comment = null ; for ( ISVDBChildItem child : p . getChildren ( ) ) { fLog . debug ( "" + SVDBItem . getName ( item ) + "" + SVDBItem . getName ( child ) ) ; if ( child . getType ( ) == SVDBItemType . DocComment ) { SVDBDocComment tryDocCom = ( SVDBDocComment ) child ; String nameCleaned = cleanCommentNameForMatch ( tryDocCom . getName ( ) ) ; if ( nameCleaned . equals ( SVDBItem . getName ( item ) ) ) { fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , SVDBItem . getName ( item ) ) ) ; comment = tryDocCom ; break ; } } else if ( child instanceof ISVDBChildParent ) { if ( ( comment = find_comment ( ( ISVDBChildParent ) child , item ) ) != null ) { break ; } } } return comment ; } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBAllTypeMatcher implements ISVDBFindNameMatcher { public boolean match ( ISVDBNamedItem it , String name ) { return it . getType ( ) . isElemOf ( SVDBItemType . ClassDecl , SVDBItemType . ModuleDecl , SVDBItemType . InterfaceDecl ) ; } } package net . sf . sveditor . core . db . search ; import java . io . File ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBOpenDeclarationIncludeNameMatcher extends SVDBFindDefaultNameMatcher { @ Override public boolean match ( ISVDBNamedItem it , String name ) { if ( it . getType ( ) == SVDBItemType . File ) { String norm_path = SVFileUtils . normalize ( it . getName ( ) ) ; String basename = new File ( name ) . getName ( ) ; return ( norm_path . endsWith ( name ) || norm_path . endsWith ( basename ) ) ; } else { return super . match ( it , name ) ; } } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBFindIncludedFile { private ISVDBIndexIterator fIndexIterator ; private ISVDBFindNameMatcher fMatcher ; public SVDBFindIncludedFile ( ISVDBIndexIterator index_it ) { this ( index_it , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; } public SVDBFindIncludedFile ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIterator = index_it ; fMatcher = matcher ; } public List < SVDBFile > find ( String name ) { ISVDBItemIterator item_it = fIndexIterator . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBFile > ret = new ArrayList < SVDBFile > ( ) ; while ( item_it . hasNext ( ) ) { ISVDBItemBase it = item_it . nextItem ( ) ; if ( it . getType ( ) == SVDBItemType . File ) { if ( fMatcher . match ( ( SVDBFile ) it , name ) ) { ret . add ( ( SVDBFile ) it ) ; } } } return ret ; } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . index . ISVDBIndex ; public class SVDBSearchResult < T > { private T fItem ; private ISVDBIndex fIndex ; public SVDBSearchResult ( T item , ISVDBIndex index ) { fItem = item ; fIndex = index ; } public T getItem ( ) { return fItem ; } public ISVDBIndex getIndex ( ) { return fIndex ; } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFindClassMatcher implements ISVDBFindNameMatcher { public boolean match ( ISVDBNamedItem it , String name ) { return ( it . getType ( ) == SVDBItemType . ClassDecl ) ; } } package net . sf . sveditor . core . db . search ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBParamValueAssign ; import net . sf . sveditor . core . db . SVDBParamValueAssignList ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVDBFindParameterizedClass { private ISVDBIndexIterator fIndexIt ; private Set < Tuple < SVDBClassDecl , SVDBTypeInfoUserDef > > fParamClassCache ; private SVDBFindNamedClass fFindNamedClass ; public SVDBFindParameterizedClass ( ISVDBIndexIterator it ) { fIndexIt = it ; fParamClassCache = new HashSet < Tuple < SVDBClassDecl , SVDBTypeInfoUserDef > > ( ) ; fFindNamedClass = new SVDBFindNamedClass ( fIndexIt ) ; } public SVDBClassDecl find ( SVDBTypeInfoUserDef type_info ) { SVDBClassDecl ret = null ; for ( Tuple < SVDBClassDecl , SVDBTypeInfoUserDef > cls_t : fParamClassCache ) { if ( cls_t . first ( ) . getName ( ) . equals ( type_info . getName ( ) ) ) { SVDBTypeInfoUserDef ti_t = cls_t . second ( ) ; SVDBParamValueAssignList type_params = type_info . getParameters ( ) ; SVDBParamValueAssignList ti_params = ti_t . getParameters ( ) ; if ( type_params == null && ti_params == null ) { ret = cls_t . first ( ) ; break ; } else if ( type_params != null && ti_params != null ) { if ( type_params . getParameters ( ) . size ( ) == ti_params . getParameters ( ) . size ( ) ) { boolean match = true ; for ( int i = ; i < type_params . getParameters ( ) . size ( ) ; i ++ ) { SVDBParamValueAssign p1 = type_params . getParameters ( ) . get ( i ) ; SVDBParamValueAssign p2 = ti_params . getParameters ( ) . get ( i ) ; if ( ! p1 . getName ( ) . equals ( p2 . getName ( ) ) ) { match = false ; break ; } } if ( match ) { ret = cls_t . first ( ) ; break ; } } } } } if ( ret == null ) { List < SVDBClassDecl > result = fFindNamedClass . find ( type_info . getName ( ) ) ; if ( result . size ( ) > ) { ret = specialize ( result . get ( ) , type_info ) ; fParamClassCache . add ( new Tuple < SVDBClassDecl , SVDBTypeInfoUserDef > ( ret , type_info ) ) ; } } return ret ; } private SVDBClassDecl specialize ( SVDBClassDecl decl , SVDBTypeInfoUserDef type_info ) { Map < String , String > param_map = new HashMap < String , String > ( ) ; SVDBClassDecl s_decl = ( SVDBClassDecl ) decl . duplicate ( ) ; SVDBParamValueAssignList param_list = type_info . getParameters ( ) ; for ( int i = ; i < decl . getParameters ( ) . size ( ) ; i ++ ) { String p_name = decl . getParameters ( ) . get ( i ) . getName ( ) ; SVDBParamValueAssign assign = param_list . getParameters ( ) . get ( i ) ; String p_val = "" ; if ( assign . getValue ( ) == null ) { System . out . println ( "" + assign . getName ( ) + "" ) ; } else { p_val = assign . getValue ( ) . toString ( ) ; } param_map . put ( p_name , p_val ) ; } specialize_int ( s_decl , param_map ) ; return s_decl ; } private void specialize_int ( ISVDBItemBase item , Map < String , String > param_map ) { switch ( item . getType ( ) ) { case ClassDecl : specialize_cls ( ( SVDBClassDecl ) item , param_map ) ; break ; case Task : case Function : specialize_tf ( ( SVDBTask ) item , param_map ) ; break ; case VarDeclStmt : { specialize_var_decl ( ( SVDBVarDeclStmt ) item , param_map ) ; } break ; default : if ( item instanceof ISVDBScopeItem ) { ISVDBScopeItem scope = ( ISVDBScopeItem ) item ; for ( ISVDBItemBase it : scope . getItems ( ) ) { specialize_int ( it , param_map ) ; } } break ; } } private void specialize_tf ( SVDBTask tf , Map < String , String > param_map ) { if ( tf . getType ( ) == SVDBItemType . Function ) { SVDBFunction func = ( SVDBFunction ) tf ; if ( param_map . containsKey ( ( ( SVDBFunction ) tf ) . getReturnType ( ) ) ) { String type = param_map . get ( func . getReturnType ( ) . getName ( ) ) ; if ( SVKeywords . isBuiltInType ( type ) ) { SVDBTypeInfoBuiltin ret_type = new SVDBTypeInfoBuiltin ( type ) ; func . setReturnType ( ret_type ) ; } else { SVDBTypeInfoUserDef ret_type = new SVDBTypeInfoUserDef ( type ) ; func . setReturnType ( ret_type ) ; } } } for ( SVDBParamPortDecl p : tf . getParams ( ) ) { if ( param_map . containsKey ( p . getTypeInfo ( ) . getName ( ) ) ) { p . getTypeInfo ( ) . setName ( param_map . get ( p . getTypeInfo ( ) . getName ( ) ) ) ; } } } private void specialize_cls ( SVDBClassDecl cls , Map < String , String > param_map ) { if ( cls . getSuperClass ( ) != null && cls . getSuperClass ( ) . getParamAssignList ( ) != null ) { for ( SVDBParamValueAssign p : cls . getSuperClass ( ) . getParamAssignList ( ) . getParameters ( ) ) { if ( param_map . containsKey ( p . getName ( ) ) ) { p . setName ( param_map . get ( p . getName ( ) ) ) ; } } } for ( ISVDBItemBase it : cls . getChildren ( ) ) { specialize_int ( it , param_map ) ; } } private void specialize_var_decl ( SVDBVarDeclStmt var_decl , Map < String , String > param_map ) { if ( var_decl . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoUserDef ) { SVDBTypeInfoUserDef cls = ( SVDBTypeInfoUserDef ) var_decl . getTypeInfo ( ) ; if ( cls . getParameters ( ) == null || cls . getParameters ( ) . getParameters ( ) . size ( ) == ) { if ( param_map . containsKey ( var_decl . getTypeInfo ( ) . getName ( ) ) ) { var_decl . getTypeInfo ( ) . setName ( param_map . get ( var_decl . getTypeInfo ( ) . getName ( ) ) ) ; } } } } } package net . sf . sveditor . core . db . search ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFindByNameMatcher implements ISVDBFindNameMatcher { private SVDBItemType fTypes [ ] ; public SVDBFindByNameMatcher ( SVDBItemType ... types ) { fTypes = types ; } public boolean match ( ISVDBNamedItem it , String name ) { if ( fTypes . length == ) { return ( it . getName ( ) . equals ( name ) ) ; } else { return ( it . getType ( ) . isElemOf ( fTypes ) && it . getName ( ) . equals ( name ) ) ; } } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; public class SVDBIndexSearcher implements ISVDBIndexSearcher { protected boolean fDebugEn ; protected List < SVDBIndexCollection > fIndexCollection ; public SVDBIndexSearcher ( ) { fIndexCollection = new ArrayList < SVDBIndexCollection > ( ) ; } public void addIndexCollection ( SVDBIndexCollection mgr ) { fIndexCollection . add ( mgr ) ; } public List < SVDBItem > findByName ( String name , SVDBItemType ... type_filter ) { return null ; } public List < SVDBItem > findByNameInClassHierarchy ( String name , SVDBScopeItem scope , SVDBItemType ... type_filter ) { return null ; } public List < SVDBItem > findByNameInScopes ( String name , SVDBScopeItem scope , boolean stop_on_first_match , SVDBItemType ... type_filter ) { return null ; } public SVDBModIfcDecl findNamedModClassIfc ( String name ) { System . out . println ( "" + name + "" ) ; return null ; } public SVDBModIfcDecl findSuperClass ( SVDBModIfcDecl cls ) { return null ; } public List < SVDBItem > findVarsByNameInScopes ( String name , SVDBScopeItem scope , boolean stop_on_first_match ) { return null ; } public void visitItems ( ISVDBItemVisitor visitor , SVDBItemType type ) { } public void visitItemsInTypeHierarchy ( SVDBScopeItem scope , ISVDBItemVisitor visitor ) { } public SVDBFile findIncludedFile ( String path ) { return null ; } protected void debug ( String msg ) { if ( fDebugEn ) { System . out . println ( msg ) ; } } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVDBFindByNameInClassHierarchy { private ISVDBIndexIterator fIndexIterator ; private LogHandle fLog ; private ISVDBFindNameMatcher fMatcher ; private SVDBFindDefaultNameMatcher fDefaultMatcher ; public SVDBFindByNameInClassHierarchy ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIterator = index_it ; fMatcher = matcher ; fDefaultMatcher = new SVDBFindDefaultNameMatcher ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public List < ISVDBItemBase > find ( ISVDBChildItem scope , String id , SVDBItemType ... types ) { return find ( scope , id , false , false , types ) ; } public List < ISVDBItemBase > find ( ISVDBChildItem scope , String id , boolean exclude_nonstatic , boolean exclude_static , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; fLog . debug ( "" + ( ( scope != null ) ? SVDBItem . getName ( scope ) : null ) + "" + id + "" ) ; for ( SVDBItemType t : types ) { fLog . debug ( "" + t ) ; } if ( scope != null && SVDBScopeItem . getName ( scope ) != null && SVDBScopeItem . getName ( scope ) . indexOf ( "" ) != - ) { String clsname = ( ( ISVDBNamedItem ) scope ) . getName ( ) . substring ( , ( ( ISVDBNamedItem ) scope ) . getName ( ) . indexOf ( "" ) ) ; SVDBFindNamedModIfcClassIfc finder = new SVDBFindNamedModIfcClassIfc ( fIndexIterator ) ; List < ISVDBChildItem > result = finder . find ( clsname ) ; if ( result . size ( ) > ) { scope = result . get ( ) ; } } else { while ( scope != null && scope . getType ( ) != SVDBItemType . ClassDecl && scope . getType ( ) != SVDBItemType . InterfaceDecl && scope . getType ( ) != SVDBItemType . ModuleDecl && scope . getType ( ) != SVDBItemType . Covergroup && scope . getType ( ) != SVDBItemType . Coverpoint ) { fLog . debug ( "" + scope . getType ( ) + "" + SVDBItem . getName ( scope ) + "" ) ; if ( scope . getType ( ) == SVDBItemType . Task || scope . getType ( ) == SVDBItemType . Function ) { findTFParamsLocals ( ret , ( SVDBTask ) scope , id , types ) ; } scope = scope . getParent ( ) ; } } if ( scope == null ) { fLog . debug ( "" ) ; fLog . debug ( "" + id + "" + ret . size ( ) + "" ) ; return ret ; } while ( scope != null && scope instanceof ISVDBChildParent ) { fLog . debug ( "" + ( ( ISVDBNamedItem ) scope ) . getName ( ) + "" ) ; for ( ISVDBItemBase it : ( ( ISVDBChildParent ) scope ) . getChildren ( ) ) { boolean matches = ( types . length == ) ; for ( SVDBItemType type : types ) { if ( it . getType ( ) == type ) { matches = true ; break ; } } if ( matches ) { if ( it . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt var = ( SVDBVarDeclStmt ) it ; boolean is_static = ( var . getAttr ( ) & SVDBVarDeclStmt . FieldAttr_Static ) != ; if ( ( is_static && ! exclude_static ) || ( ! is_static && ! exclude_nonstatic ) ) { for ( ISVDBChildItem it_t : ( ( SVDBVarDeclStmt ) it ) . getChildren ( ) ) { if ( fMatcher . match ( ( ISVDBNamedItem ) it_t , id ) ) { ret . add ( it_t ) ; } } } } else if ( it instanceof ISVDBNamedItem ) { if ( fMatcher . match ( ( ISVDBNamedItem ) it , id ) ) { ret . add ( it ) ; } } } } if ( scope instanceof SVDBClassDecl ) { SVDBFindSuperClass finder = new SVDBFindSuperClass ( fIndexIterator , fDefaultMatcher ) ; if ( ( ( SVDBClassDecl ) scope ) . getSuperClass ( ) != null ) { String super_name = ( ( SVDBClassDecl ) scope ) . getSuperClass ( ) . getName ( ) ; fLog . debug ( "" + super_name + "" ) ; scope = finder . find ( ( SVDBClassDecl ) scope ) ; if ( scope != null ) { fLog . debug ( "" + ( ( SVDBClassDecl ) scope ) . getSuperClass ( ) + "" + scope ) ; } else { fLog . debug ( "" + super_name + "" ) ; } } else { fLog . debug ( "" ) ; scope = null ; } } else { scope = null ; } } fLog . debug ( "" + id + "" + ret . size ( ) + "" ) ; return ret ; } private void findTFParamsLocals ( List < ISVDBItemBase > items , SVDBTask scope , String id , SVDBItemType ... types ) { boolean matches = ( types . length == ) ; for ( SVDBParamPortDecl it : scope . getParams ( ) ) { for ( SVDBItemType type : types ) { if ( it . getType ( ) == type ) { matches = true ; break ; } } if ( matches ) { for ( ISVDBChildItem c : it . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; if ( fMatcher . match ( vi , id ) ) { items . add ( vi ) ; } } } } for ( ISVDBItemBase it : scope . getChildren ( ) ) { for ( SVDBItemType type : types ) { if ( it . getType ( ) == type ) { matches = true ; break ; } } if ( matches && it instanceof ISVDBNamedItem ) { if ( fMatcher . match ( ( ISVDBNamedItem ) it , id ) ) { items . add ( it ) ; } } } } } package net . sf . sveditor . core . db . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBInclude ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; public class SVDBPackageItemFinder { private ISVDBIndexIterator fIndexIt ; private ISVDBFindNameMatcher fMatcher ; public SVDBPackageItemFinder ( ISVDBIndexIterator index_it , ISVDBFindNameMatcher matcher ) { fIndexIt = index_it ; fMatcher = matcher ; } public List < SVDBItem > find ( SVDBPackageDecl pkg , String name ) { SVDBFindIncludedFile inc_finder = new SVDBFindIncludedFile ( fIndexIt ) ; List < SVDBItem > ret = new ArrayList < SVDBItem > ( ) ; for ( ISVDBItemBase it : pkg . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . Include ) { List < SVDBFile > file = inc_finder . find ( ( ( SVDBInclude ) it ) . getName ( ) ) ; if ( file . size ( ) > ) { find ( file . get ( ) , ret , name ) ; } } else if ( it . getType ( ) == SVDBItemType . ClassDecl ) { if ( fMatcher . match ( ( SVDBModIfcDecl ) it , name ) ) { ret . add ( ( SVDBModIfcDecl ) it ) ; } } } return ret ; } private void find ( SVDBFile file , List < SVDBItem > items , String name ) { for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . ClassDecl ) { if ( fMatcher . match ( ( SVDBModIfcDecl ) it , name ) ) { items . add ( ( SVDBModIfcDecl ) it ) ; } } } } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; public class SVDBChildParent extends SVDBChildItem implements ISVDBChildParent { public List < ISVDBChildItem > fItems ; public SVDBChildParent ( SVDBItemType type ) { super ( type ) ; fItems = new ArrayList < ISVDBChildItem > ( ) ; } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fItems . add ( item ) ; } public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return fItems . iterator ( ) ; } } ; } } package net . sf . sveditor . core . db . refs ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBDeclCache ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBSubClassRefFinder { public static List < SVDBClassDecl > find ( ISVDBDeclCache decl_cache , String clsname ) { List < SVDBClassDecl > ret = new ArrayList < SVDBClassDecl > ( ) ; List < SVDBRefCacheItem > cache_items = decl_cache . findReferences ( new NullProgressMonitor ( ) , clsname , new SVDBTypeRefMatcher ( ) ) ; for ( SVDBRefCacheItem item : cache_items ) { List < SVDBRefItem > ref_items = item . findReferences ( new NullProgressMonitor ( ) ) ; for ( SVDBRefItem ref_item : ref_items ) { if ( ref_item . getLeaf ( ) . getType ( ) == SVDBItemType . ClassDecl ) { SVDBClassDecl cls = ( SVDBClassDecl ) ref_item . getLeaf ( ) ; if ( cls . getSuperClass ( ) . getName ( ) . equals ( clsname ) ) { ret . add ( cls ) ; } } } } return ret ; } } package net . sf . sveditor . core . db . refs ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; public class SVDBRefItem { private List < ISVDBItemBase > fRefPath ; private String fRefName ; private SVDBRefType fRefType ; public SVDBRefItem ( List < ISVDBItemBase > ref_path , String ref_name , SVDBRefType ref_type ) { fRefPath = ref_path ; fRefName = ref_name ; fRefType = ref_type ; } public SVDBFile getRoot ( ) { return ( SVDBFile ) fRefPath . get ( ) ; } public ISVDBItemBase getLeaf ( ) { return fRefPath . get ( fRefPath . size ( ) - ) ; } } package net . sf . sveditor . core . db . refs ; public enum SVDBRefType { TypeReference , FieldReference , ImportReference , IncludeReference } package net . sf . sveditor . core . db . refs ; import java . util . Stack ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBInclude ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBTypeInfoClassType ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . expr . SVDBAssignExpr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBFieldAccessExpr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; import net . sf . sveditor . core . db . stmt . ISVDBBodyStmt ; import net . sf . sveditor . core . db . stmt . SVDBActionBlockStmt ; import net . sf . sveditor . core . db . stmt . SVDBBlockStmt ; import net . sf . sveditor . core . db . stmt . SVDBCaseItem ; import net . sf . sveditor . core . db . stmt . SVDBCaseStmt ; import net . sf . sveditor . core . db . stmt . SVDBDoWhileStmt ; import net . sf . sveditor . core . db . stmt . SVDBExprStmt ; import net . sf . sveditor . core . db . stmt . SVDBForStmt ; import net . sf . sveditor . core . db . stmt . SVDBIfStmt ; import net . sf . sveditor . core . db . stmt . SVDBImportItem ; import net . sf . sveditor . core . db . stmt . SVDBImportStmt ; import net . sf . sveditor . core . db . stmt . SVDBRepeatStmt ; import net . sf . sveditor . core . db . stmt . SVDBReturnStmt ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . db . stmt . SVDBWaitStmt ; import net . sf . sveditor . core . db . stmt . SVDBWhileStmt ; public abstract class AbstractSVDBFileRefFinder { protected SVDBFile fFile ; protected Stack < ISVDBChildItem > fScopeStack ; public AbstractSVDBFileRefFinder ( ) { fScopeStack = new Stack < ISVDBChildItem > ( ) ; } public void visitFile ( SVDBFile file ) { fFile = file ; fScopeStack . push ( fFile ) ; visitChildParent ( fFile ) ; fScopeStack . pop ( ) ; } protected void visitChildParent ( ISVDBChildParent parent ) { for ( ISVDBChildItem c : parent . getChildren ( ) ) { visitChild ( c ) ; } } protected void visitChild ( ISVDBChildItem c ) { fScopeStack . push ( c ) ; if ( c instanceof SVDBStmt ) { visitStmt ( ( SVDBStmt ) c ) ; } else if ( c instanceof SVDBExpr ) { visitExpr ( ( SVDBExpr ) c ) ; } else { switch ( c . getType ( ) ) { case ModuleDecl : case InterfaceDecl : case ProgramDecl : case Task : case Function : break ; case Include : { SVDBInclude inc = ( SVDBInclude ) c ; visitRef ( inc . getLocation ( ) , SVDBRefType . IncludeReference , inc . getName ( ) ) ; } break ; case ClassDecl : { SVDBClassDecl cls = ( SVDBClassDecl ) c ; if ( cls . getSuperClass ( ) != null ) { SVDBTypeInfoClassType cls_t = cls . getSuperClass ( ) ; visitRef ( null , SVDBRefType . TypeReference , cls_t . getName ( ) ) ; } } break ; } if ( c instanceof ISVDBChildParent ) { visitChildParent ( ( ISVDBChildParent ) c ) ; } } fScopeStack . pop ( ) ; } protected void visitStmt ( SVDBStmt stmt ) { if ( stmt == null ) { return ; } switch ( stmt . getType ( ) ) { case ActionBlockStmt : { SVDBActionBlockStmt action_blk = ( SVDBActionBlockStmt ) stmt ; if ( action_blk . getStmt ( ) != null ) { fScopeStack . push ( action_blk . getStmt ( ) ) ; visitStmt ( action_blk . getStmt ( ) ) ; fScopeStack . pop ( ) ; } if ( action_blk . getElseStmt ( ) != null ) { fScopeStack . push ( action_blk . getElseStmt ( ) ) ; visitStmt ( action_blk . getElseStmt ( ) ) ; fScopeStack . pop ( ) ; } } break ; case AlwaysStmt : { } break ; case AssignStmt : { } break ; case BlockStmt : { SVDBBlockStmt block = ( SVDBBlockStmt ) stmt ; for ( ISVDBChildItem ci : block . getChildren ( ) ) { visitStmt ( ( SVDBStmt ) ci ) ; } } break ; case CaseItem : { SVDBCaseItem ci = ( SVDBCaseItem ) stmt ; for ( SVDBExpr expr : ci . getExprList ( ) ) { visitExpr ( expr ) ; } } break ; case CaseStmt : { SVDBCaseStmt case_stmt = ( SVDBCaseStmt ) stmt ; visitExpr ( case_stmt . getExpr ( ) ) ; for ( SVDBCaseItem ci : case_stmt . getCaseItemList ( ) ) { visitStmt ( ci ) ; } } break ; case DoWhileStmt : { SVDBDoWhileStmt dw_stmt = ( SVDBDoWhileStmt ) stmt ; visitExpr ( dw_stmt . getCond ( ) ) ; } break ; case ExprStmt : { SVDBExprStmt expr_stmt = ( SVDBExprStmt ) stmt ; fScopeStack . push ( expr_stmt ) ; visitExpr ( expr_stmt . getExpr ( ) ) ; fScopeStack . pop ( ) ; } break ; case ForStmt : { SVDBForStmt f_stmt = ( SVDBForStmt ) stmt ; if ( f_stmt . getInitExpr ( ) != null ) { visitStmt ( f_stmt . getInitExpr ( ) ) ; } if ( f_stmt . getTestExpr ( ) != null ) { visitStmt ( f_stmt . getTestExpr ( ) ) ; } if ( f_stmt . getIncrStmt ( ) != null ) { visitStmt ( f_stmt . getIncrStmt ( ) ) ; } } break ; case IfStmt : { SVDBIfStmt if_stmt = ( SVDBIfStmt ) stmt ; visitExpr ( if_stmt . getCond ( ) ) ; visitStmt ( if_stmt . getIfStmt ( ) ) ; if ( if_stmt . getElseStmt ( ) != null ) { visitStmt ( if_stmt . getElseStmt ( ) ) ; } } break ; case ImportItem : { SVDBImportItem i_stmt = ( SVDBImportItem ) stmt ; visitRef ( i_stmt . getLocation ( ) , SVDBRefType . ImportReference , i_stmt . getImport ( ) ) ; } break ; case ImportStmt : { SVDBImportStmt i_stmt = ( SVDBImportStmt ) stmt ; for ( ISVDBChildItem ci : i_stmt . getChildren ( ) ) { visitStmt ( ( SVDBStmt ) ci ) ; } } break ; case RepeatStmt : { SVDBRepeatStmt r_stmt = ( SVDBRepeatStmt ) stmt ; visitExpr ( r_stmt . getExpr ( ) ) ; } break ; case ReturnStmt : { SVDBReturnStmt r_stmt = ( SVDBReturnStmt ) stmt ; if ( r_stmt . getExpr ( ) != null ) { visitExpr ( r_stmt . getExpr ( ) ) ; } } break ; case VarDeclStmt : { SVDBVarDeclStmt var_decl = ( SVDBVarDeclStmt ) stmt ; if ( var_decl . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoUserDef ) { SVDBTypeInfoUserDef ut = ( SVDBTypeInfoUserDef ) var_decl . getTypeInfo ( ) ; visitRef ( null , SVDBRefType . TypeReference , ut . getName ( ) ) ; for ( ISVDBChildItem var_item_c : var_decl . getChildren ( ) ) { SVDBVarDeclItem var_item = ( SVDBVarDeclItem ) var_item_c ; if ( var_item . getInitExpr ( ) != null ) { } } } } break ; case WaitStmt : { SVDBWaitStmt w_stmt = ( SVDBWaitStmt ) stmt ; visitExpr ( w_stmt . getExpr ( ) ) ; } break ; case WhileStmt : { SVDBWhileStmt w_stmt = ( SVDBWhileStmt ) stmt ; visitExpr ( w_stmt . getExpr ( ) ) ; } break ; } if ( stmt instanceof ISVDBBodyStmt ) { ISVDBBodyStmt b_stmt = ( ISVDBBodyStmt ) stmt ; if ( b_stmt . getBody ( ) != null ) { visitStmt ( b_stmt . getBody ( ) ) ; } } } protected void visitExpr ( SVDBExpr expr ) { if ( expr == null ) { return ; } switch ( expr . getType ( ) ) { case AssignExpr : { SVDBAssignExpr a_expr = ( SVDBAssignExpr ) expr ; visitExpr ( a_expr . getLhs ( ) ) ; visitExpr ( a_expr . getRhs ( ) ) ; } break ; case FieldAccessExpr : { SVDBFieldAccessExpr f_expr = ( SVDBFieldAccessExpr ) expr ; visitExpr ( f_expr . getExpr ( ) ) ; visitExpr ( f_expr . getLeaf ( ) ) ; } break ; case IdentifierExpr : { SVDBIdentifierExpr id_expr = ( SVDBIdentifierExpr ) expr ; visitRef ( id_expr . getLocation ( ) , SVDBRefType . FieldReference , id_expr . getId ( ) ) ; } break ; } } protected void visitRef ( SVDBLocation loc , SVDBRefType type , String name ) { System . out . println ( "" + type + "" + name ) ; } } package net . sf . sveditor . core . db . refs ; import java . util . List ; public class SVDBTypeRefMatcher implements ISVDBRefMatcher { public void find_matches ( List < SVDBRefCacheItem > matches , SVDBRefCacheEntry item , String name ) { if ( item . getRefSet ( SVDBRefType . TypeReference ) . contains ( name ) ) { matches . add ( new SVDBRefCacheItem ( item , null , SVDBRefType . TypeReference , name ) ) ; } } } package net . sf . sveditor . core . db . refs ; import net . sf . sveditor . core . db . SVDBLocation ; public class SVDBFileRefCollector extends AbstractSVDBFileRefFinder { private SVDBRefCacheEntry fReferences ; public SVDBFileRefCollector ( ) { fReferences = new SVDBRefCacheEntry ( ) ; } public SVDBRefCacheEntry getReferences ( ) { return fReferences ; } @ Override protected void visitRef ( SVDBLocation loc , SVDBRefType type , String name ) { switch ( type ) { case FieldReference : { fReferences . addFieldRef ( name ) ; } break ; case ImportReference : { fReferences . addImportRef ( name ) ; } break ; case IncludeReference : { fReferences . addIncludeRef ( name ) ; } break ; case TypeReference : { fReferences . addTypeRef ( name ) ; } break ; } } } package net . sf . sveditor . core . db . refs ; import java . util . List ; public interface ISVDBRefMatcher { void find_matches ( List < SVDBRefCacheItem > matches , SVDBRefCacheEntry item , String name ) ; } package net . sf . sveditor . core . db . refs ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; public class SVDBRefCacheItem { private SVDBRefCacheEntry fCacheEntry ; private ISVDBRefFinder fRefFinder ; private SVDBRefType fRefType ; private String fRefName ; public SVDBRefCacheItem ( SVDBRefCacheEntry entry , ISVDBRefFinder finder , SVDBRefType type , String name ) { fCacheEntry = entry ; fRefFinder = finder ; fRefType = type ; fRefName = name ; } public void setRefFinder ( ISVDBRefFinder finder ) { fRefFinder = finder ; } public String getFilename ( ) { return fCacheEntry . getFilename ( ) ; } public SVDBRefType getRefType ( ) { return fRefType ; } public String getRefName ( ) { return fRefName ; } public List < SVDBRefItem > findReferences ( IProgressMonitor monitor ) { return fRefFinder . findReferences ( monitor , this ) ; } } package net . sf . sveditor . core . db . refs ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ISVDBRefFinder { List < SVDBRefItem > findReferences ( IProgressMonitor monitor , SVDBRefCacheItem item ) ; } package net . sf . sveditor . core . db . refs ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBLocation ; public class SVDBRefFinder extends AbstractSVDBFileRefFinder { private SVDBRefType fRefType ; private String fRefName ; private List < SVDBRefItem > fRefList ; public SVDBRefFinder ( SVDBRefType ref_type , String ref_name ) { fRefList = new ArrayList < SVDBRefItem > ( ) ; fRefType = ref_type ; fRefName = ref_name ; } public List < SVDBRefItem > find_refs ( SVDBFile file ) { visitFile ( file ) ; return fRefList ; } @ Override protected void visitRef ( SVDBLocation loc , SVDBRefType type , String name ) { if ( type == fRefType && name . equals ( fRefName ) ) { List < ISVDBItemBase > ref_path = new ArrayList < ISVDBItemBase > ( ) ; ref_path . addAll ( fScopeStack ) ; fRefList . add ( new SVDBRefItem ( ref_path , fRefName , fRefType ) ) ; } } } package net . sf . sveditor . core . db . refs ; import java . util . HashSet ; import java . util . Set ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; public class SVDBRefCacheEntry { @ SVDBDoNotSaveAttr private String fFileName ; public Set < String > fTypeReferences ; public Set < String > fFieldReferences ; public Set < String > fImportReferences ; public Set < String > fIncludeReferences ; public SVDBRefCacheEntry ( ) { fTypeReferences = new HashSet < String > ( ) ; fFieldReferences = new HashSet < String > ( ) ; fImportReferences = new HashSet < String > ( ) ; fIncludeReferences = new HashSet < String > ( ) ; } public Set < String > getRefSet ( SVDBRefType t ) { switch ( t ) { case FieldReference : return fFieldReferences ; case ImportReference : return fImportReferences ; case IncludeReference : return fIncludeReferences ; case TypeReference : return fTypeReferences ; } return null ; } public void addFieldRef ( String name ) { if ( ! fFieldReferences . contains ( name ) ) { fFieldReferences . add ( name ) ; } } public void addImportRef ( String name ) { if ( ! fImportReferences . contains ( name ) ) { fImportReferences . add ( name ) ; } } public void addIncludeRef ( String name ) { if ( ! fIncludeReferences . contains ( name ) ) { fIncludeReferences . add ( name ) ; } } public void addTypeRef ( String name ) { if ( ! fTypeReferences . contains ( name ) ) { fTypeReferences . add ( name ) ; } } public void setFilename ( String filename ) { fFileName = filename ; } public String getFilename ( ) { return fFileName ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; public class SVDBProperty extends SVDBScopeItem { public SVDBExpr fExpr ; public List < SVDBParamPortDecl > fPortList ; public SVDBProperty ( ) { this ( "" ) ; } public SVDBProperty ( String name ) { super ( name , SVDBItemType . Property ) ; fPortList = new ArrayList < SVDBParamPortDecl > ( ) ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public void addPropertyPort ( SVDBParamPortDecl p ) { fPortList . add ( p ) ; } public List < SVDBParamPortDecl > getPropertyPortList ( ) { return fPortList ; } } package net . sf . sveditor . core . db ; public class SVDBTypeInfoBuiltinNet extends SVDBTypeInfo { public String fWireType ; public SVDBTypeInfo fType ; public SVDBTypeInfoBuiltinNet ( ) { this ( "" , null ) ; } public SVDBTypeInfoBuiltinNet ( String wire_type , SVDBTypeInfo type ) { super ( wire_type , SVDBItemType . TypeInfoBuiltinNet ) ; fWireType = wire_type ; fType = type ; } public String getWireType ( ) { return fWireType ; } public SVDBTypeInfo getTypeInfo ( ) { return fType ; } } package net . sf . sveditor . core . db ; public class SVDBModportTFPort extends SVDBChildItem { public String fId ; public SVDBTask fTFPrototype ; public SVDBModportTFPort ( ) { super ( SVDBItemType . ModportTFPort ) ; } public void setId ( String id ) { fId = id ; } public String getId ( ) { return fId ; } public void setPrototype ( SVDBTask p ) { fTFPrototype = p ; } public SVDBTask getPrototype ( ) { return fTFPrototype ; } } package net . sf . sveditor . core . db ; public class SVDB { private static boolean fInit ; public static void init ( ) { if ( fInit ) { return ; } fInit = true ; } } package net . sf . sveditor . core . db ; import java . util . List ; public class SVDBTypeInfoUserDef extends SVDBTypeInfo { public SVDBParamValueAssignList fParamAssignList ; public SVDBLocation fEndLocation ; public List < ISVDBItemBase > fItems ; public SVDBTypeInfoUserDef ( ) { this ( "" ) ; } public SVDBTypeInfoUserDef ( String typename ) { this ( typename , SVDBItemType . TypeInfoUserDef ) ; } public SVDBTypeInfoUserDef ( String typename , SVDBItemType type ) { super ( typename , type ) ; } public SVDBLocation getEndLocation ( ) { return fEndLocation ; } public List < ISVDBItemBase > getItems ( ) { return fItems ; } public void setEndLocation ( SVDBLocation loc ) { } public SVDBParamValueAssignList getParameters ( ) { return fParamAssignList ; } public void setParameters ( SVDBParamValueAssignList params ) { fParamAssignList = params ; } public String toString ( ) { StringBuilder ret = new StringBuilder ( ) ; ret . append ( getName ( ) ) ; if ( fParamAssignList != null && fParamAssignList . getParameters ( ) . size ( ) > ) { ret . append ( "" ) ; for ( SVDBParamValueAssign p : fParamAssignList . getParameters ( ) ) { if ( fParamAssignList . getIsNamedMapping ( ) ) { ret . append ( "" + p . getName ( ) + "" + p . getValue ( ) + "" ) ; } else { ret . append ( p . getValue ( ) + "" ) ; } } ret . setLength ( ret . length ( ) - ) ; ret . append ( "" ) ; } return ret . toString ( ) ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBTypeInfoUserDef ) { SVDBTypeInfoUserDef o = ( SVDBTypeInfoUserDef ) obj ; if ( fParamAssignList == null || o . fParamAssignList == null ) { if ( fParamAssignList != o . fParamAssignList ) { return false ; } } else if ( fParamAssignList . equals ( o . fParamAssignList ) ) { return false ; } return super . equals ( obj ) ; } return false ; } @ Override public SVDBTypeInfoUserDef duplicate ( ) { return ( SVDBTypeInfoUserDef ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . attr . SVDBParentAttr ; public class SVDBChildItem extends SVDBItemBase implements ISVDBChildItem { @ SVDBParentAttr public ISVDBChildItem fParent ; public SVDBChildItem ( SVDBItemType type ) { super ( type ) ; } public ISVDBChildItem getParent ( ) { return fParent ; } public void setParent ( ISVDBChildItem parent ) { fParent = parent ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; public class SVDBConstraint extends SVDBScopeItem { public List < SVDBStmt > fConstraintList ; public SVDBConstraint ( ) { super ( "" , SVDBItemType . Constraint ) ; fConstraintList = new ArrayList < SVDBStmt > ( ) ; } public void addChildItem ( ISVDBChildItem stmt ) { stmt . setParent ( this ) ; fConstraintList . add ( ( SVDBStmt ) stmt ) ; } @ Override @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fConstraintList . iterator ( ) ; } } ; } } package net . sf . sveditor . core . db . utils ; import java . util . Iterator ; public class SVDBSingleItemIterable < T > implements Iterable < T > { private T fItem ; private class SVDBSingleItemIterator implements Iterator < T > { T fItem ; int fIdx = ; public SVDBSingleItemIterator ( T item ) { fItem = item ; } public boolean hasNext ( ) { return ( fItem != null && fIdx == ) ; } public T next ( ) { if ( fIdx == ) { fIdx ++ ; return fItem ; } else { return null ; } } public void remove ( ) { } } public SVDBSingleItemIterable ( T item ) { fItem = item ; } public Iterator < T > iterator ( ) { return new SVDBSingleItemIterator ( fItem ) ; } } package net . sf . sveditor . core . db . utils ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBPreProcCond ; public class SVDBItemPrint { public static void printItem ( ISVDBItemBase item ) { printItem ( , item ) ; } private static void printItem ( int indent , ISVDBItemBase item ) { for ( int i = ; i < indent ; i ++ ) { System . out . print ( "" ) ; } System . out . print ( "" + item . getType ( ) ) ; if ( item instanceof ISVDBNamedItem ) { System . out . print ( "" + ( ( ISVDBNamedItem ) item ) . getName ( ) ) ; } if ( item instanceof SVDBPreProcCond ) { System . out . print ( "" + ( ( SVDBPreProcCond ) item ) . getConditional ( ) ) ; } System . out . println ( ) ; if ( item instanceof ISVDBScopeItem ) { for ( ISVDBItemBase it : ( ( ISVDBScopeItem ) item ) . getItems ( ) ) { printItem ( indent + , it ) ; } } } } package net . sf . sveditor . core . db . utils ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . stmt . ISVDBBodyStmt ; import net . sf . sveditor . core . db . stmt . SVDBIfStmt ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVDBSearchUtils implements ILogLevel { private static final LogHandle fLog ; static { fLog = LogFactory . getLogHandle ( "" ) ; } public static List < ISVDBItemBase > findItemsByType ( SVDBScopeItem scope , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; for ( ISVDBItemBase it : scope . getChildren ( ) ) { boolean match = ( types . length == ) ; for ( SVDBItemType t : types ) { if ( it . getType ( ) == t ) { match = true ; break ; } } if ( match ) { ret . add ( it ) ; } } return ret ; } public static SVDBModIfcDecl findClassScope ( ISVDBChildItem scope ) { while ( scope != null && scope . getType ( ) != SVDBItemType . ClassDecl ) { scope = scope . getParent ( ) ; } return ( SVDBModIfcDecl ) scope ; } public static List < ISVDBItemBase > findItemsByName ( ISVDBScopeItem scope , String name , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; for ( ISVDBItemBase it : scope . getItems ( ) ) { boolean type_match = ( types . length == ) ; for ( SVDBItemType t : types ) { if ( it . getType ( ) == t ) { type_match = true ; break ; } } if ( type_match && ( it instanceof ISVDBNamedItem ) && ( ( ISVDBNamedItem ) it ) . getName ( ) != null && ( ( ISVDBNamedItem ) it ) . getName ( ) . equals ( name ) ) { ret . add ( it ) ; } else if ( it instanceof ISVDBScopeItem ) { ret . addAll ( findItemsByName ( ( ISVDBScopeItem ) it , name , types ) ) ; } } return ret ; } public static ISVDBScopeItem findActiveScope ( ISVDBChildParent scope , int lineno ) { ISVDBScopeItem ret = null ; debug ( "" + SVDBItem . getName ( scope ) + "" + lineno ) ; for ( ISVDBItemBase it : scope . getChildren ( ) ) { debug ( "" + SVDBItem . getName ( it ) + "" + ( it instanceof ISVDBScopeItem ) ) ; if ( it instanceof ISVDBBodyStmt && ( ( ISVDBBodyStmt ) it ) . getBody ( ) != null && ( ( ISVDBBodyStmt ) it ) . getBody ( ) instanceof ISVDBScopeItem ) { it = ( ( ISVDBBodyStmt ) it ) . getBody ( ) ; debug ( "" + SVDBItem . getName ( it ) ) ; if ( ( ret = findActiveScope_i ( it , lineno ) ) != null ) { break ; } } else if ( it . getType ( ) == SVDBItemType . IfStmt ) { SVDBIfStmt if_stmt = ( SVDBIfStmt ) it ; if ( if_stmt . getIfStmt ( ) != null ) { if ( ( ret = findActiveScope_i ( if_stmt . getIfStmt ( ) , lineno ) ) != null ) { break ; } } if ( if_stmt . getElseStmt ( ) != null ) { if ( ( ret = findActiveScope_i ( if_stmt . getElseStmt ( ) , lineno ) ) != null ) { break ; } } } else { if ( ( ret = findActiveScope_i ( it , lineno ) ) != null ) { break ; } } } return ret ; } private static ISVDBScopeItem findActiveScope_i ( ISVDBItemBase it , int lineno ) { if ( it instanceof ISVDBScopeItem ) { SVDBLocation end_loc = ( ( ISVDBScopeItem ) it ) . getEndLocation ( ) ; ISVDBScopeItem s_it = ( ISVDBScopeItem ) it ; debug ( "" + s_it . getLocation ( ) + "" + end_loc ) ; if ( s_it . getLocation ( ) != null && end_loc != null ) { debug ( "" + SVDBItem . getName ( it ) + "" + it . getLocation ( ) . getLine ( ) + "" + ( ( end_loc != null ) ? end_loc . getLine ( ) : - ) ) ; if ( lineno >= s_it . getLocation ( ) . getLine ( ) && lineno <= end_loc . getLine ( ) ) { ISVDBScopeItem s_it_p = findActiveScope ( s_it , lineno ) ; if ( s_it_p != null ) { return s_it_p ; } else { return ( ISVDBScopeItem ) s_it ; } } } } return null ; } private static void debug ( String msg ) { fLog . debug ( LEVEL_MAX , msg ) ; } } package net . sf . sveditor . core . db . utils ; import java . util . ArrayList ; import java . util . Comparator ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBIndexSearcher { private Map < ISVDBIndex , Set < String > > fIndexMap ; public SVDBIndexSearcher ( ) { } public SVDBIndexSearcher ( ISVDBIndex index ) { Set < String > filelist = new HashSet < String > ( ) ; for ( String path : index . getFileList ( new NullProgressMonitor ( ) ) ) { filelist . add ( path ) ; } fIndexMap . put ( index , filelist ) ; } public void addIndex ( ISVDBIndex index ) { Set < String > filelist = new HashSet < String > ( ) ; for ( String path : index . getFileList ( new NullProgressMonitor ( ) ) ) { filelist . add ( path ) ; } fIndexMap . put ( index , filelist ) ; } public SVDBClassDecl findNamedClass ( String name ) { SVDBClassDecl c ; for ( Entry < ISVDBIndex , Set < String > > e : fIndexMap . entrySet ( ) ) { for ( String fname : e . getValue ( ) ) { SVDBFile f = e . getKey ( ) . findFile ( fname ) ; if ( ( c = findNamedClass ( name , f ) ) != null ) { return c ; } } } return null ; } private SVDBClassDecl findNamedClass ( String name , SVDBScopeItem parent ) { for ( ISVDBItemBase it : parent . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . ClassDecl && ( ( ISVDBNamedItem ) it ) . getName ( ) != null && ( ( ISVDBNamedItem ) it ) . getName ( ) . equals ( name ) ) { return ( SVDBClassDecl ) it ; } else if ( it . getType ( ) == SVDBItemType . PackageDecl ) { SVDBClassDecl c ; if ( ( c = findNamedClass ( name , ( SVDBScopeItem ) it ) ) != null ) { return c ; } } } return null ; } public SVDBClassDecl findSuperClass ( SVDBClassDecl cls ) { if ( cls . getSuperClass ( ) != null ) { return findNamedClass ( cls . getSuperClass ( ) . getName ( ) ) ; } else { return null ; } } public List < ISVDBItemBase > findVarsByNameInScopes ( String name , ISVDBChildItem context , boolean stop_on_first_match ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; while ( context != null ) { if ( context instanceof ISVDBScopeItem ) { for ( ISVDBItemBase it : ( ( ISVDBScopeItem ) context ) . getItems ( ) ) { if ( SVDBStmt . isType ( it , SVDBItemType . VarDeclStmt ) ) { if ( ( ( ISVDBNamedItem ) it ) . getName ( ) . equals ( name ) ) { ret . add ( it ) ; if ( stop_on_first_match ) { break ; } } } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } if ( context . getType ( ) == SVDBItemType . Function || context . getType ( ) == SVDBItemType . Task ) { for ( ISVDBItemBase it : ( ( SVDBTask ) context ) . getParams ( ) ) { if ( SVDBItem . getName ( it ) . equals ( name ) ) { ret . add ( it ) ; if ( stop_on_first_match ) { break ; } } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } context = context . getParent ( ) ; } return ret ; } public List < ISVDBItemBase > findByNameInScopes ( String name , ISVDBChildItem context , boolean stop_on_first_match , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; while ( context != null ) { if ( context instanceof ISVDBScopeItem ) { for ( ISVDBItemBase it : ( ( ISVDBScopeItem ) context ) . getItems ( ) ) { if ( it instanceof ISVDBNamedItem && ( ( ISVDBNamedItem ) it ) . getName ( ) . equals ( name ) ) { boolean match = ( types . length == ) ; for ( SVDBItemType t : types ) { if ( it . getType ( ) == t ) { match = true ; break ; } } if ( match ) { ret . add ( it ) ; if ( stop_on_first_match ) { break ; } } } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } if ( context . getType ( ) == SVDBItemType . Function || context . getType ( ) == SVDBItemType . Task ) { for ( ISVDBItemBase it : ( ( SVDBTask ) context ) . getParams ( ) ) { if ( SVDBItem . getName ( it ) . equals ( name ) ) { ret . add ( it ) ; if ( stop_on_first_match ) { break ; } } } } if ( ret . size ( ) > && stop_on_first_match ) { break ; } context = context . getParent ( ) ; } return ret ; } public List < ISVDBItemBase > findByName ( String name , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; for ( Entry < ISVDBIndex , Set < String > > e : fIndexMap . entrySet ( ) ) { for ( String fname : e . getValue ( ) ) { SVDBFile f = e . getKey ( ) . findFile ( fname ) ; List < ISVDBItemBase > r = SVDBSearchUtils . findItemsByName ( f , name , types ) ; ret . addAll ( r ) ; } } return ret ; } public List < ISVDBItemBase > findByPrefixInTypeHierarchy ( String prefix , SVDBScopeItem ref_type , Comparator < String > comparator , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; while ( ref_type != null ) { for ( ISVDBItemBase it : ref_type . getChildren ( ) ) { boolean type_match = ( types . length == ) ; for ( SVDBItemType type : types ) { if ( it . getType ( ) == type ) { type_match = true ; break ; } } if ( type_match && ( it instanceof ISVDBNamedItem ) && ( ( ISVDBNamedItem ) it ) . getName ( ) . toLowerCase ( ) . startsWith ( prefix ) ) { ret . add ( it ) ; } } if ( ref_type . getType ( ) == SVDBItemType . ClassDecl && ( ( SVDBClassDecl ) ref_type ) . getSuperClass ( ) != null ) { ref_type = findNamedClass ( ( ( SVDBClassDecl ) ref_type ) . getSuperClass ( ) . getName ( ) ) ; } else { ref_type = null ; } } return ret ; } public List < ISVDBItemBase > findByNameInClassHierarchy ( String name , ISVDBChildItem scope , SVDBItemType ... types ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; while ( scope != null && scope . getType ( ) != SVDBItemType . ClassDecl ) { scope = scope . getParent ( ) ; } if ( scope == null ) { return ret ; } while ( scope != null ) { if ( scope instanceof ISVDBScopeItem ) { for ( ISVDBItemBase it : ( ( ISVDBScopeItem ) scope ) . getItems ( ) ) { boolean match_type = ( types . length == ) ; for ( SVDBItemType t : types ) { if ( it . getType ( ) == t ) { match_type = true ; break ; } } if ( match_type && it instanceof ISVDBNamedItem && ( ( ISVDBNamedItem ) it ) . getName ( ) . equals ( name ) ) { ret . add ( it ) ; } } } scope = findNamedClass ( ( ( SVDBClassDecl ) scope ) . getSuperClass ( ) . getName ( ) ) ; } return ret ; } } package net . sf . sveditor . core . db ; public class SVDBModuleDecl extends SVDBModIfcDecl { public SVDBModuleDecl ( ) { super ( "" , SVDBItemType . ModuleDecl ) ; } public SVDBModuleDecl ( String name ) { super ( name , SVDBItemType . ModuleDecl ) ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; public class SVDBSequence extends SVDBScopeItem { public SVDBExpr fExpr ; public List < SVDBParamPortDecl > fPortList ; public List < SVDBVarDeclStmt > fVarDeclList ; public SVDBSequence ( ) { this ( "" ) ; } public SVDBSequence ( String name ) { super ( name , SVDBItemType . Sequence ) ; fPortList = new ArrayList < SVDBParamPortDecl > ( ) ; fVarDeclList = new ArrayList < SVDBVarDeclStmt > ( ) ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public void addPort ( SVDBParamPortDecl port ) { fPortList . add ( port ) ; } public List < SVDBParamPortDecl > getPortList ( ) { return fPortList ; } public void addVarDecl ( SVDBVarDeclStmt decl ) { fVarDeclList . add ( decl ) ; } public List < SVDBVarDeclStmt > getVarDeclList ( ) { return fVarDeclList ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBModportItem extends SVDBItem { public List < SVDBModportPortsDecl > fPorts ; public SVDBModportItem ( ) { this ( "" ) ; } public SVDBModportItem ( String name ) { super ( name , SVDBItemType . ModportItem ) ; fPorts = new ArrayList < SVDBModportPortsDecl > ( ) ; } public List < SVDBModportPortsDecl > getPortsList ( ) { return fPorts ; } public void addPorts ( SVDBModportPortsDecl p ) { fPorts . add ( p ) ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBMacroDef extends SVDBItem implements ISVDBChildItem { public List < SVDBMacroDefParam > fParams ; public String fDef ; public SVDBMacroDef ( ) { super ( "" , SVDBItemType . MacroDef ) ; } public SVDBMacroDef ( String name , String def ) { super ( name , SVDBItemType . MacroDef ) ; fParams = new ArrayList < SVDBMacroDefParam > ( ) ; fDef = def ; } public String getDef ( ) { return fDef ; } public void setDef ( String def ) { fDef = def ; } public List < SVDBMacroDefParam > getParameters ( ) { return fParams ; } public void addParameter ( SVDBMacroDefParam p ) { fParams . add ( p ) ; p . setParent ( this ) ; } @ Override public void init ( SVDBItemBase other ) { super . init ( other ) ; SVDBMacroDef m = ( SVDBMacroDef ) other ; fParams . clear ( ) ; fParams . addAll ( m . fParams ) ; fDef = m . fDef ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBLiteralExpr extends SVDBExpr { public String fLiteral ; public SVDBLiteralExpr ( ) { this ( null ) ; } public SVDBLiteralExpr ( String literal ) { super ( SVDBItemType . LiteralExpr ) ; fLiteral = literal ; } public String getValue ( ) { return fLiteral ; } public SVDBLiteralExpr duplicate ( ) { return ( SVDBLiteralExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; public class SVDBRandomizeCallExpr extends SVDBTFCallExpr { public SVDBStmt fWithBlock ; public SVDBRandomizeCallExpr ( ) { this ( null , null , null ) ; } public SVDBRandomizeCallExpr ( SVDBExpr target , String name , List < SVDBExpr > args ) { super ( SVDBItemType . RandomizeCallExpr , target , name , args ) ; } public void setWithBlock ( SVDBStmt with ) { fWithBlock = with ; } public SVDBStmt getWithBlock ( ) { return fWithBlock ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFirstMatchExpr extends SVDBExpr { public SVDBExpr fExpr ; public List < SVDBExpr > fSequenceMatchItems ; public SVDBFirstMatchExpr ( ) { super ( SVDBItemType . FirstMatchExpr ) ; fSequenceMatchItems = new ArrayList < SVDBExpr > ( ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void addSequenceMatchItem ( SVDBExpr expr ) { fSequenceMatchItems . add ( expr ) ; } public List < SVDBExpr > getSequenceMatchItems ( ) { return fSequenceMatchItems ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBConcatenationExpr extends SVDBExpr { public List < SVDBExpr > fElems ; public SVDBConcatenationExpr ( ) { super ( SVDBItemType . ConcatenationExpr ) ; fElems = new ArrayList < SVDBExpr > ( ) ; } public List < SVDBExpr > getElements ( ) { return fElems ; } public SVDBConcatenationExpr duplicate ( ) { return ( SVDBConcatenationExpr ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { SVDBConcatenationExpr ce = ( SVDBConcatenationExpr ) other ; super . init ( other ) ; fElems . clear ( ) ; for ( SVDBExpr e : ce . fElems ) { fElems . add ( ( SVDBExpr ) e . duplicate ( ) ) ; } } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBPropertyIfStmt extends SVDBExpr { public SVDBExpr fExpr ; public SVDBExpr fIfExpr ; public SVDBExpr fElseExpr ; public SVDBPropertyIfStmt ( ) { super ( SVDBItemType . PropertyIfStmt ) ; } public void setIfExpr ( SVDBExpr expr ) { fIfExpr = expr ; } public SVDBExpr getIfExpr ( ) { return fIfExpr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setElseExpr ( SVDBExpr expr ) { fElseExpr = expr ; } public SVDBExpr getElseExpr ( ) { return fElseExpr ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . stmt . SVDBBodyStmt ; public class SVDBPropertyCaseItem extends SVDBBodyStmt { public List < SVDBExpr > fExprList ; public SVDBExpr fStmt ; public SVDBPropertyCaseItem ( ) { super ( SVDBItemType . PropertyCaseItem ) ; fExprList = new ArrayList < SVDBExpr > ( ) ; } public void addExpr ( SVDBExpr expr ) { fExprList . add ( expr ) ; } public void setStmt ( SVDBExpr stmt ) { fStmt = stmt ; } public SVDBExpr getStmt ( ) { return fStmt ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBAssignmentPatternRepeatExpr extends SVDBAssignmentPatternExpr { public SVDBExpr fRepeatExpr ; public SVDBAssignmentPatternRepeatExpr ( ) { this ( null ) ; } public SVDBAssignmentPatternRepeatExpr ( SVDBExpr repeat_expr ) { super ( SVDBItemType . AssignmentPatternRepeatExpr ) ; fRepeatExpr = repeat_expr ; } public void setRepeatExpr ( SVDBExpr e ) { fRepeatExpr = e ; } public SVDBExpr getRepeatExpr ( ) { return fRepeatExpr ; } } package net . sf . sveditor . core . db . expr ; import java . io . ByteArrayOutputStream ; import java . io . OutputStream ; import java . io . PrintStream ; import java . util . Stack ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVExprUtils { private static SVExprUtils fDefault ; private Stack < String > fIndentStack ; private LogHandle fLog ; public SVExprUtils ( ) { fIndentStack = new Stack < String > ( ) ; fIndentStack . push ( "" ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public void setBaseIndent ( String base ) { fIndentStack . clear ( ) ; fIndentStack . push ( base ) ; } public static SVExprUtils getDefault ( ) { if ( fDefault == null ) { fDefault = new SVExprUtils ( ) ; } return fDefault ; } public String exprToString ( SVDBExpr expr ) { PrintStream ps ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; ps = new PrintStream ( bos ) ; expr_to_string ( ps , expr ) ; ps . flush ( ) ; return bos . toString ( ) ; } public void exprToStream ( SVDBExpr expr , OutputStream out ) { PrintStream ps ; ps = new PrintStream ( out ) ; expr_to_string ( ps , expr ) ; ps . flush ( ) ; } protected String getAccess ( String id ) { return id ; } protected void push_indent ( ) { fIndentStack . push ( fIndentStack . peek ( ) + "" ) ; } protected void pop_indent ( ) { if ( fIndentStack . size ( ) > ) { fIndentStack . pop ( ) ; } } protected String get_indent ( ) { return fIndentStack . peek ( ) ; } protected boolean binary ( PrintStream ps , SVDBBinaryExpr expr ) { expr_to_string ( ps , expr . getLhs ( ) ) ; ps . print ( expr . getOp ( ) ) ; expr_to_string ( ps , expr . getRhs ( ) ) ; return true ; } protected boolean paren ( PrintStream ps , SVDBParenExpr expr ) { ps . print ( "" ) ; expr_to_string ( ps , expr . getExpr ( ) ) ; ps . print ( "" ) ; return true ; } protected boolean range ( PrintStream ps , SVDBRangeExpr expr ) { expr_to_string ( ps , expr . getLeft ( ) ) ; ps . print ( "" ) ; expr_to_string ( ps , expr . getRight ( ) ) ; return true ; } protected boolean identifier ( PrintStream ps , SVDBIdentifierExpr expr ) { String id_path = getAccess ( expr . getId ( ) ) ; ps . print ( id_path ) ; return true ; } protected boolean literal ( PrintStream ps , SVDBLiteralExpr expr ) { SVDBLiteralExpr lit = ( SVDBLiteralExpr ) expr ; ps . print ( lit . getValue ( ) ) ; return true ; } protected boolean array_access ( PrintStream ps , SVDBArrayAccessExpr expr ) { expr_to_string ( ps , expr . getLhs ( ) ) ; ps . print ( "" ) ; expr_to_string ( ps , expr . getLow ( ) ) ; if ( expr . getHigh ( ) != null ) { ps . print ( "" ) ; expr_to_string ( ps , expr . getHigh ( ) ) ; } ps . print ( "" ) ; return true ; } protected boolean unary ( PrintStream ps , SVDBUnaryExpr expr ) { ps . print ( expr . getOp ( ) ) ; expr_to_string ( ps , expr . getExpr ( ) ) ; return true ; } protected boolean inside ( PrintStream ps , SVDBInsideExpr expr ) { expr_to_string ( ps , expr . getLhs ( ) ) ; ps . print ( "" ) ; for ( int i = ; i < expr . getValueRangeList ( ) . size ( ) ; i ++ ) { SVDBExpr r_i = expr . getValueRangeList ( ) . get ( i ) ; if ( r_i . getType ( ) == SVDBItemType . LiteralExpr ) { literal ( ps , ( SVDBLiteralExpr ) r_i ) ; } else if ( r_i . getType ( ) == SVDBItemType . RangeExpr ) { SVDBRangeExpr r = ( SVDBRangeExpr ) r_i ; ps . print ( "" ) ; expr_to_string ( ps , r . getLeft ( ) ) ; ps . print ( "" ) ; expr_to_string ( ps , r . getRight ( ) ) ; ps . print ( "" ) ; } else if ( r_i . getType ( ) == SVDBItemType . IdentifierExpr ) { identifier ( ps , ( SVDBIdentifierExpr ) r_i ) ; } if ( i + < expr . getValueRangeList ( ) . size ( ) ) { ps . print ( "" ) ; } } ps . print ( "" ) ; return true ; } protected boolean concatenation ( PrintStream ps , SVDBConcatenationExpr expr ) { ps . print ( "" ) ; for ( int i = ; i < expr . getElements ( ) . size ( ) ; i ++ ) { expr_to_string ( ps , expr . getElements ( ) . get ( i ) ) ; if ( i + < expr . getElements ( ) . size ( ) ) { ps . print ( "" ) ; } } ps . print ( "" ) ; return true ; } protected boolean assign ( PrintStream ps , SVDBAssignExpr expr ) { expr_to_string ( ps , expr . getLhs ( ) ) ; ps . print ( "" + expr . getOp ( ) + "" ) ; expr_to_string ( ps , expr . getRhs ( ) ) ; return true ; } protected boolean cast ( PrintStream ps , SVDBCastExpr expr ) { expr_to_string ( ps , expr . getCastType ( ) ) ; ps . print ( "" ) ; expr_to_string ( ps , expr . getExpr ( ) ) ; ps . print ( "" ) ; return true ; } protected boolean cond ( PrintStream ps , SVDBCondExpr expr ) { ps . print ( "" ) ; expr_to_string ( ps , expr . getLhs ( ) ) ; ps . print ( "" ) ; ps . print ( "" ) ; expr_to_string ( ps , expr . getMhs ( ) ) ; ps . print ( "" ) ; expr_to_string ( ps , expr . getRhs ( ) ) ; return true ; } protected boolean tf_call ( PrintStream ps , SVDBTFCallExpr expr ) { if ( expr . getTarget ( ) != null ) { expr_to_string ( ps , expr . getTarget ( ) ) ; ps . print ( "" ) ; } ps . print ( expr . getName ( ) ) ; ps . print ( "" ) ; if ( expr . getArgs ( ) != null ) { for ( int i = ; i < expr . getArgs ( ) . size ( ) ; i ++ ) { expr_to_string ( ps , expr . getArgs ( ) . get ( i ) ) ; if ( i + < expr . getArgs ( ) . size ( ) ) { ps . print ( "" ) ; } } } ps . print ( "" ) ; return true ; } protected boolean field_access ( PrintStream ps , SVDBFieldAccessExpr expr ) { expr_to_string ( ps , expr . getExpr ( ) ) ; ps . print ( "" ) ; expr_to_string ( ps , expr . getLeaf ( ) ) ; return true ; } protected boolean randomize_call ( PrintStream ps , SVDBRandomizeCallExpr expr ) { tf_call ( ps , expr ) ; return true ; } protected boolean assignment_pattern ( PrintStream ps , SVDBAssignmentPatternExpr expr ) { ps . print ( "" ) ; for ( int i = ; i < expr . getPatternList ( ) . size ( ) ; i ++ ) { expr_to_string ( ps , expr . getPatternList ( ) . get ( i ) ) ; if ( i + < expr . getPatternList ( ) . size ( ) ) { ps . print ( "" ) ; } } ps . print ( "" ) ; return true ; } protected boolean incdec ( PrintStream ps , SVDBIncDecExpr expr ) { expr_to_string ( ps , expr . getExpr ( ) ) ; ps . print ( expr . getOp ( ) ) ; return true ; } protected boolean expr_to_string ( PrintStream ps , SVDBExpr expr ) { boolean ret = false ; switch ( expr . getType ( ) ) { case ArrayAccessExpr : ret = array_access ( ps , ( SVDBArrayAccessExpr ) expr ) ; break ; case AssignExpr : ret = assign ( ps , ( SVDBAssignExpr ) expr ) ; break ; case AssignmentPatternExpr : ret = assignment_pattern ( ps , ( SVDBAssignmentPatternExpr ) expr ) ; break ; case AssignmentPatternRepeatExpr : break ; case AssociativeArrayElemAssignExpr : break ; case BinaryExpr : ret = binary ( ps , ( SVDBBinaryExpr ) expr ) ; break ; case CastExpr : ret = cast ( ps , ( SVDBCastExpr ) expr ) ; break ; case ClockingEventExpr : break ; case ConcatenationExpr : ret = concatenation ( ps , ( SVDBConcatenationExpr ) expr ) ; break ; case CondExpr : ret = cond ( ps , ( SVDBCondExpr ) expr ) ; break ; case FieldAccessExpr : ret = field_access ( ps , ( SVDBFieldAccessExpr ) expr ) ; break ; case IdentifierExpr : ret = identifier ( ps , ( SVDBIdentifierExpr ) expr ) ; break ; case IncDecExpr : ret = incdec ( ps , ( SVDBIncDecExpr ) expr ) ; break ; case InsideExpr : ret = inside ( ps , ( SVDBInsideExpr ) expr ) ; break ; case LiteralExpr : ret = literal ( ps , ( SVDBLiteralExpr ) expr ) ; break ; case NullExpr : ret = true ; ps . print ( "" ) ; break ; case ParenExpr : ret = paren ( ps , ( SVDBParenExpr ) expr ) ; break ; case RandomizeCallExpr : ret = randomize_call ( ps , ( SVDBRandomizeCallExpr ) expr ) ; break ; case RangeExpr : ret = range ( ps , ( SVDBRangeExpr ) expr ) ; break ; case TFCallExpr : ret = tf_call ( ps , ( SVDBTFCallExpr ) expr ) ; break ; case UnaryExpr : ret = unary ( ps , ( SVDBUnaryExpr ) expr ) ; break ; case TypeExpr : { SVDBTypeExpr type = ( SVDBTypeExpr ) expr ; ps . print ( "" + type . getTypeInfo ( ) ) ; } break ; case StringExpr : ret = true ; ps . print ( "" + ( ( SVDBStringExpr ) expr ) . getContent ( ) + "" ) ; break ; default : try { throw new Exception ( ) ; } catch ( Exception e ) { fLog . error ( "" + expr . getType ( ) , e ) ; } break ; } return ret ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . stmt . SVDBConstraintDistListItem ; import net . sf . sveditor . core . db . stmt . SVDBConstraintDistListStmt ; import net . sf . sveditor . core . db . stmt . SVDBConstraintSolveBeforeStmt ; public class SVExprIterator { public void visit ( SVDBExpr expr ) { switch ( expr . getType ( ) ) { case ArrayAccessExpr : array_access ( ( SVDBArrayAccessExpr ) expr ) ; break ; case AssignExpr : assign ( ( SVDBAssignExpr ) expr ) ; break ; case CastExpr : cast ( ( SVDBCastExpr ) expr ) ; break ; case BinaryExpr : binary_expr ( ( SVDBBinaryExpr ) expr ) ; break ; case CondExpr : cond ( ( SVDBCondExpr ) expr ) ; break ; case FieldAccessExpr : field_access ( ( SVDBFieldAccessExpr ) expr ) ; break ; case IdentifierExpr : identifier ( ( SVDBIdentifierExpr ) expr ) ; break ; case IncDecExpr : inc_dec ( ( SVDBIncDecExpr ) expr ) ; break ; case InsideExpr : inside ( ( SVDBInsideExpr ) expr ) ; break ; case LiteralExpr : literal ( ( SVDBLiteralExpr ) expr ) ; break ; case ParenExpr : paren ( ( SVDBParenExpr ) expr ) ; break ; case TFCallExpr : tf_call ( ( SVDBTFCallExpr ) expr ) ; break ; case UnaryExpr : unary ( ( SVDBUnaryExpr ) expr ) ; break ; case RangeExpr : range ( ( SVDBRangeExpr ) expr ) ; break ; default : System . out . println ( "" + expr . getType ( ) ) ; break ; } } protected void array_access ( SVDBArrayAccessExpr expr ) { visit ( expr . getLhs ( ) ) ; } protected void assign ( SVDBAssignExpr expr ) { visit ( expr . getLhs ( ) ) ; visit ( expr . getRhs ( ) ) ; } protected void binary_expr ( SVDBBinaryExpr expr ) { visit ( expr . getLhs ( ) ) ; visit ( expr . getRhs ( ) ) ; } protected void cast ( SVDBCastExpr expr ) { visit ( expr . getExpr ( ) ) ; } protected void cond ( SVDBCondExpr expr ) { visit ( expr . getLhs ( ) ) ; visit ( expr . getMhs ( ) ) ; visit ( expr . getRhs ( ) ) ; } protected void dist_item ( SVDBConstraintDistListItem expr ) { } protected void dist_list ( SVDBConstraintDistListStmt expr ) { } protected void field_access ( SVDBFieldAccessExpr expr ) { visit ( expr . getExpr ( ) ) ; } protected void identifier ( SVDBIdentifierExpr expr ) { } protected void inc_dec ( SVDBIncDecExpr expr ) { visit ( expr . getExpr ( ) ) ; } protected void inside ( SVDBInsideExpr expr ) { visit ( expr . getLhs ( ) ) ; for ( SVDBExpr e : expr . getValueRangeList ( ) ) { visit ( e ) ; } } protected void literal ( SVDBLiteralExpr expr ) { } protected void paren ( SVDBParenExpr expr ) { visit ( expr . getExpr ( ) ) ; } protected void solve_before ( SVDBConstraintSolveBeforeStmt expr ) { } protected void tf_call ( SVDBTFCallExpr expr ) { if ( expr . getTarget ( ) != null ) { visit ( expr . getTarget ( ) ) ; } } protected void unary ( SVDBUnaryExpr expr ) { visit ( expr . getExpr ( ) ) ; } protected void range ( SVDBRangeExpr expr ) { visit ( expr . getLeft ( ) ) ; visit ( expr . getRight ( ) ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBNullExpr extends SVDBExpr { public SVDBNullExpr ( ) { super ( SVDBItemType . NullExpr ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBRangeExpr extends SVDBExpr { public SVDBExpr fLeft ; public SVDBExpr fRight ; public SVDBRangeExpr ( ) { this ( null , null ) ; } public SVDBRangeExpr ( SVDBExpr left , SVDBExpr right ) { super ( SVDBItemType . RangeExpr ) ; fLeft = left ; fRight = right ; } public SVDBExpr getLeft ( ) { return fLeft ; } public SVDBExpr getRight ( ) { return fRight ; } public SVDBRangeExpr duplicate ( ) { return ( SVDBRangeExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBFieldAccessExpr extends SVDBExpr { public SVDBExpr fExpr ; public boolean fStaticRef ; public SVDBExpr fLeaf ; public SVDBFieldAccessExpr ( ) { this ( null , false , null ) ; } public SVDBFieldAccessExpr ( SVDBExpr expr , boolean static_ref , SVDBExpr leaf ) { super ( SVDBItemType . FieldAccessExpr ) ; fExpr = expr ; fStaticRef = static_ref ; fLeaf = leaf ; } public SVDBExpr getExpr ( ) { return fExpr ; } public boolean isStaticRef ( ) { return fStaticRef ; } public SVDBExpr getLeaf ( ) { return fLeaf ; } public SVDBFieldAccessExpr duplicate ( ) { return ( SVDBFieldAccessExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBPropertySpecExpr extends SVDBExpr { public SVDBClockingEventExpr fClockingEventExpr ; public SVDBExpr fDisableExpr ; public SVDBExpr fExpr ; public SVDBPropertySpecExpr ( ) { super ( SVDBItemType . PropertySpecExpr ) ; } public SVDBClockingEventExpr getClockingEvent ( ) { return fClockingEventExpr ; } public void setClockingEvent ( SVDBClockingEventExpr expr ) { fClockingEventExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getDisableExpr ( ) { return fDisableExpr ; } public void setDisableExpr ( SVDBExpr expr ) { fDisableExpr = expr ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBArrayAccessExpr extends SVDBExpr { public SVDBExpr fLhs ; public SVDBExpr fLow ; public SVDBExpr fHigh ; public SVDBArrayAccessExpr ( ) { this ( null , null , null ) ; } public SVDBArrayAccessExpr ( SVDBExpr lhs , SVDBExpr low , SVDBExpr high ) { super ( SVDBItemType . ArrayAccessExpr ) ; fLhs = lhs ; fLow = low ; fHigh = high ; } public SVDBExpr getLhs ( ) { return fLhs ; } public SVDBExpr getLow ( ) { return fLow ; } public SVDBExpr getHigh ( ) { return fHigh ; } public SVDBArrayAccessExpr duplicate ( ) { return ( SVDBArrayAccessExpr ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { SVDBArrayAccessExpr aa = ( SVDBArrayAccessExpr ) other ; super . init ( other ) ; fLhs = aa . fLhs ; fLow = aa . fLow ; fHigh = aa . fHigh ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBAssignmentPatternExpr extends SVDBExpr { public List < SVDBExpr > fPatternList ; public SVDBAssignmentPatternExpr ( ) { this ( SVDBItemType . AssignmentPatternExpr ) ; } public SVDBAssignmentPatternExpr ( SVDBItemType type ) { super ( type ) ; fPatternList = new ArrayList < SVDBExpr > ( ) ; } public List < SVDBExpr > getPatternList ( ) { return fPatternList ; } public SVDBAssignmentPatternExpr duplicate ( ) { return ( SVDBAssignmentPatternExpr ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBStringExpr extends SVDBExpr { public String fStr ; public SVDBStringExpr ( ) { this ( "" ) ; } public SVDBStringExpr ( String str ) { super ( SVDBItemType . StringExpr ) ; fStr = str ; } public String getContent ( ) { return fStr ; } public SVDBStringExpr duplicate ( ) { return ( SVDBStringExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBAssignExpr extends SVDBExpr { public SVDBExpr fLhs ; public String fOp ; public SVDBExpr fRhs ; public SVDBAssignExpr ( ) { this ( null , null , null ) ; } public SVDBAssignExpr ( SVDBExpr lhs , String op , SVDBExpr rhs ) { super ( SVDBItemType . AssignExpr ) ; fLhs = lhs ; fOp = op ; fRhs = rhs ; } public SVDBExpr getLhs ( ) { return fLhs ; } public void setLhs ( SVDBExpr lhs ) { fLhs = lhs ; } public String getOp ( ) { return fOp ; } public void setOp ( String op ) { fOp = op ; } public SVDBExpr getRhs ( ) { return fRhs ; } public void setRhs ( SVDBExpr rhs ) { fRhs = rhs ; } public SVDBAssignExpr duplicate ( ) { return ( SVDBAssignExpr ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { SVDBAssignExpr ae = ( SVDBAssignExpr ) other ; super . init ( other ) ; fLhs = ae . fLhs ; fOp = ae . fOp ; fRhs = ae . fRhs ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBNamedArgExpr extends SVDBExpr { public String fArgName ; public SVDBExpr fExpr ; public SVDBNamedArgExpr ( ) { super ( SVDBItemType . NamedArgExpr ) ; } public void setArgName ( String name ) { fArgName = name ; } public String getArgName ( ) { return fArgName ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVCoverageExpr extends SVDBExpr { public SVCoverageExpr ( SVDBItemType type ) { super ( type ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBSequenceRepetitionExpr extends SVDBExpr { public String fRepType ; public SVDBExpr fExpr ; public SVDBSequenceRepetitionExpr ( ) { super ( SVDBItemType . SequenceRepetitionExpr ) ; } public void setRepType ( String t ) { fRepType = t ; } public String getRepType ( ) { return fRepType ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBPropertyCaseStmt extends SVDBExpr { public SVDBExpr fExpr ; public List < SVDBPropertyCaseItem > fItemList ; public SVDBPropertyCaseStmt ( ) { super ( SVDBItemType . PropertyCaseStmt ) ; fItemList = new ArrayList < SVDBPropertyCaseItem > ( ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void addItem ( SVDBPropertyCaseItem item ) { fItemList . add ( item ) ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBCtorExpr extends SVDBExpr { public enum CtorType { CtorType_Args , CtorType_Dim , CtorType_Expr , CtorType_Void } public CtorType fCtorType = CtorType . CtorType_Void ; public List < SVDBExpr > fArgs ; public SVDBCtorExpr ( ) { super ( SVDBItemType . CtorExpr ) ; } public void setCtorType ( CtorType type ) { fCtorType = type ; } public CtorType getCtorType ( ) { return fCtorType ; } public void setArg ( SVDBExpr expr ) { if ( fArgs == null ) { fArgs = new ArrayList < SVDBExpr > ( ) ; } fArgs . clear ( ) ; fArgs . add ( expr ) ; } public SVDBExpr getArg ( ) { if ( fArgs == null || fArgs . size ( ) == ) { return null ; } else { return fArgs . get ( ) ; } } public void setArgs ( List < SVDBExpr > args ) { fArgs = args ; } public List < SVDBExpr > getArgs ( ) { return fArgs ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBBinaryExpr extends SVDBExpr { public SVDBExpr fLhs ; public String fOp ; public SVDBExpr fRhs ; public SVDBBinaryExpr ( ) { this ( null , null , null ) ; } public SVDBBinaryExpr ( SVDBExpr lhs , String op , SVDBExpr rhs ) { super ( SVDBItemType . BinaryExpr ) ; fLhs = lhs ; fOp = op ; fRhs = rhs ; } public SVDBExpr getLhs ( ) { return fLhs ; } public String getOp ( ) { return fOp ; } public SVDBExpr getRhs ( ) { return fRhs ; } public SVDBBinaryExpr duplicate ( ) { return ( SVDBBinaryExpr ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; SVDBBinaryExpr be = ( SVDBBinaryExpr ) other ; fLhs = ( SVDBExpr ) be . fLhs . duplicate ( ) ; fOp = be . fOp ; fRhs = ( SVDBExpr ) be . fRhs . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBCycleDelayExpr extends SVDBExpr { public SVDBExpr fExpr ; public SVDBCycleDelayExpr ( SVDBItemType type ) { super ( type ) ; } public SVDBCycleDelayExpr ( ) { this ( SVDBItemType . CycleDelayExpr ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBClockingEventExpr extends SVDBExpr { public enum ClockingEventType { None , Any , Expr } public SVDBExpr fExpr ; public ClockingEventType fEventType ; public SVDBClockingEventExpr ( ) { super ( SVDBItemType . ClockingEventExpr ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setClockingEventType ( ClockingEventType type ) { fEventType = type ; } public ClockingEventType getClockingEventType ( ) { return fEventType ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBItemUtils ; public class SVDBExpr extends SVDBItemBase { protected SVDBExpr ( SVDBItemType type ) { super ( type ) ; } public String toString ( ) { return SVExprUtils . getDefault ( ) . exprToString ( this ) ; } public SVDBExpr duplicate ( ) { return ( SVDBExpr ) SVDBItemUtils . duplicate ( this ) ; } public void init ( SVDBItemBase other ) { SVDBExpr o = ( SVDBExpr ) other ; super . init ( o ) ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBInsideExpr extends SVDBExpr { public SVDBExpr fLhs ; public List < SVDBExpr > fValueRangeList ; public SVDBInsideExpr ( ) { this ( null ) ; } public SVDBInsideExpr ( SVDBExpr lhs ) { super ( SVDBItemType . InsideExpr ) ; fLhs = lhs ; fValueRangeList = new ArrayList < SVDBExpr > ( ) ; } public SVDBExpr getLhs ( ) { return fLhs ; } public List < SVDBExpr > getValueRangeList ( ) { return fValueRangeList ; } public SVDBInsideExpr duplicate ( ) { return ( SVDBInsideExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBParenExpr extends SVDBExpr { public SVDBExpr fExpr ; public SVDBParenExpr ( ) { this ( null ) ; } public SVDBParenExpr ( SVDBExpr expr ) { super ( SVDBItemType . ParenExpr ) ; fExpr = expr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public SVDBParenExpr duplicate ( ) { return ( SVDBParenExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBSequenceClockingExpr extends SVDBExpr { public SVDBExpr fClockingExpr ; public SVDBExpr fSequenceExpr ; public SVDBSequenceClockingExpr ( ) { super ( SVDBItemType . SequenceClockingExpr ) ; } public void setClockingExpr ( SVDBExpr expr ) { fClockingExpr = expr ; } public SVDBExpr getClockingExpr ( ) { return fClockingExpr ; } public void setSequenceExpr ( SVDBExpr expr ) { fSequenceExpr = expr ; } public SVDBExpr getSequenceExpr ( ) { return fSequenceExpr ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBSequenceCycleDelayExpr extends SVDBExpr { public SVDBExpr fLhs ; public SVDBCycleDelayExpr fDelay ; public SVDBExpr fRhs ; public SVDBSequenceCycleDelayExpr ( ) { super ( SVDBItemType . SequenceCycleDelayExpr ) ; } public void setDelay ( SVDBCycleDelayExpr expr ) { fDelay = expr ; } public SVDBCycleDelayExpr getDelay ( ) { return fDelay ; } public void setLhs ( SVDBExpr expr ) { fLhs = expr ; } public SVDBExpr getLhs ( ) { return fLhs ; } public void setRhs ( SVDBExpr expr ) { fRhs = expr ; } public SVDBExpr getRhs ( ) { return fRhs ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBMinTypMaxExpr extends SVDBExpr { public SVDBExpr fMin ; public SVDBExpr fTyp ; public SVDBExpr fMax ; public SVDBMinTypMaxExpr ( ) { super ( SVDBItemType . MinTypMaxExpr ) ; } public SVDBMinTypMaxExpr ( SVDBExpr min , SVDBExpr typ , SVDBExpr max ) { this ( ) ; fMin = min ; fTyp = typ ; fMax = max ; } } package net . sf . sveditor . core . db . expr ; public class SVExprParseException extends Exception { private static final long serialVersionUID = ; public SVExprParseException ( String msg ) { super ( msg ) ; } public SVExprParseException ( Exception e ) { super ( e ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBAssociativeArrayElemAssignExpr extends SVDBExpr { public SVDBExpr fKey ; public SVDBExpr fValue ; public SVDBAssociativeArrayElemAssignExpr ( ) { super ( SVDBItemType . AssociativeArrayElemAssignExpr ) ; } public void setKey ( SVDBExpr key ) { fKey = key ; } public SVDBExpr getKey ( ) { return fKey ; } public void setValue ( SVDBExpr val ) { fValue = val ; } public SVDBExpr getValue ( ) { return fValue ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . persistence . DBFormatException ; import net . sf . sveditor . core . db . persistence . IDBReader ; public interface ISVExprPersistenceFactory { SVDBExpr readSVExpr ( SVDBItemType type , IDBReader reader ) throws DBFormatException ; } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBCrossBinsSelectConditionExpr extends SVDBExpr { public SVDBExpr fBinsExpr ; public List < SVDBExpr > fIntersectList ; public SVDBCrossBinsSelectConditionExpr ( ) { super ( SVDBItemType . CrossBinsSelectConditionExpr ) ; fIntersectList = new ArrayList < SVDBExpr > ( ) ; } public void setBinsExpr ( SVDBExpr expr ) { fBinsExpr = expr ; } public SVDBExpr getBinsExpr ( ) { return fBinsExpr ; } public List < SVDBExpr > getIntersectList ( ) { return fIntersectList ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBIncDecExpr extends SVDBExpr { public SVDBExpr fExpr ; public String fOp ; public SVDBIncDecExpr ( ) { this ( null , null ) ; } public SVDBIncDecExpr ( String op , SVDBExpr expr ) { super ( SVDBItemType . IncDecExpr ) ; fExpr = expr ; fOp = op ; } public SVDBExpr getExpr ( ) { return fExpr ; } public String getOp ( ) { return fOp ; } public SVDBIncDecExpr duplicate ( ) { return ( SVDBIncDecExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBSequenceMatchItemExpr extends SVDBExpr { public SVDBExpr fExpr ; public List < SVDBExpr > fMatchItemList ; public SVDBExpr fSequenceAbbrev ; public SVDBSequenceMatchItemExpr ( ) { super ( SVDBItemType . SequenceMatchItemExpr ) ; fMatchItemList = new ArrayList < SVDBExpr > ( ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void addMatchItemExpr ( SVDBExpr expr ) { fMatchItemList . add ( expr ) ; } public List < SVDBExpr > getMatchItemExprList ( ) { return fMatchItemList ; } public void setSequenceAbbrev ( SVDBExpr expr ) { fSequenceAbbrev = expr ; } public SVDBExpr getSequenceAbbrev ( ) { return fSequenceAbbrev ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBRangeDollarBoundExpr extends SVDBExpr { public SVDBRangeDollarBoundExpr ( ) { super ( SVDBItemType . RangeDollarBoundExpr ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBNameMappedExpr extends SVDBExpr { public String fName ; public SVDBExpr fExpr ; public SVDBNameMappedExpr ( ) { super ( SVDBItemType . NameMappedExpr ) ; } public SVDBNameMappedExpr ( String name , SVDBExpr expr ) { this ( ) ; fName = name ; fExpr = expr ; } public String getName ( ) { return fName ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBParamIdExpr extends SVDBIdentifierExpr { public List < SVDBExpr > fParamExpr ; public SVDBParamIdExpr ( ) { this ( null ) ; } public SVDBParamIdExpr ( String id ) { super ( SVDBItemType . ParamIdExpr , id ) ; fParamExpr = new ArrayList < SVDBExpr > ( ) ; } public List < SVDBExpr > getParamExpr ( ) { return fParamExpr ; } public void addParamExpr ( SVDBExpr expr ) { fParamExpr . add ( expr ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBUnaryExpr extends SVDBExpr { public SVDBExpr fExpr ; public String fOp ; public SVDBUnaryExpr ( ) { this ( null , null ) ; } public SVDBUnaryExpr ( String op , SVDBExpr expr ) { super ( SVDBItemType . UnaryExpr ) ; fOp = op ; fExpr = expr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setOp ( String op ) { fOp = op ; } public String getOp ( ) { return fOp ; } public SVDBUnaryExpr duplicate ( ) { return ( SVDBUnaryExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBCoverpointExpr extends SVCoverageExpr { public Map < String , String > fOptionMap ; public Map < String , String > fTypeOptionMap ; public List < SVDBCoverBinsExpr > fCoverBins ; public SVDBExpr fIffExpr ; public SVDBExpr fTarget ; public SVDBCoverpointExpr ( ) { super ( SVDBItemType . CoverpointExpr ) ; fOptionMap = new HashMap < String , String > ( ) ; fTypeOptionMap = new HashMap < String , String > ( ) ; fCoverBins = new ArrayList < SVDBCoverBinsExpr > ( ) ; } public List < SVDBCoverBinsExpr > getCoverBins ( ) { return fCoverBins ; } public SVDBExpr getTarget ( ) { return fTarget ; } public void setTarget ( SVDBExpr target ) { fTarget = target ; } public SVDBExpr getIFFExpr ( ) { return fIffExpr ; } public void setIFFExpr ( SVDBExpr iff_expr ) { fIffExpr = iff_expr ; } public void addOption ( String key , String value ) { if ( fOptionMap . containsKey ( key ) ) { fOptionMap . remove ( key ) ; } fOptionMap . put ( key , value ) ; } public void addTypeOption ( String key , String value ) { if ( fTypeOptionMap . containsKey ( key ) ) { fTypeOptionMap . remove ( key ) ; } fTypeOptionMap . put ( key , value ) ; } public Map < String , String > getOptionMap ( ) { return fOptionMap ; } public Map < String , String > getTypeOptionMap ( ) { return fTypeOptionMap ; } public SVDBCoverpointExpr duplicate ( ) { return ( SVDBCoverpointExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBCoverBinsExpr extends SVCoverageExpr { public String fName ; public String fBinsType ; public boolean fIsArray ; public SVDBExpr fArrayExpr ; public List < SVDBExpr > fRangeList ; public boolean fIsDefault ; public SVDBCoverBinsExpr ( ) { this ( null , null ) ; } public SVDBCoverBinsExpr ( String name , String bins_type ) { super ( SVDBItemType . CoverBinsExpr ) ; fName = name ; fBinsType = bins_type ; fRangeList = new ArrayList < SVDBExpr > ( ) ; } public String getName ( ) { return fName ; } public void setIsDefault ( boolean dflt ) { fIsDefault = dflt ; } public boolean isDefault ( ) { return fIsDefault ; } public String getBinsType ( ) { return fBinsType ; } public boolean isArray ( ) { return fIsArray ; } public void setIsArray ( boolean is_array ) { fIsArray = is_array ; } public SVDBExpr getArrayExpr ( ) { return fArrayExpr ; } public void setArrayExpr ( SVDBExpr expr ) { fArrayExpr = expr ; } public List < SVDBExpr > getRangeList ( ) { return fRangeList ; } public SVDBCoverBinsExpr duplicate ( ) { return ( SVDBCoverBinsExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBCastExpr extends SVDBExpr { public SVDBExpr fCastType ; public SVDBExpr fExpr ; public SVDBCastExpr ( ) { this ( null , null ) ; } public SVDBCastExpr ( SVDBExpr cast_type , SVDBExpr expr ) { super ( SVDBItemType . CastExpr ) ; fCastType = cast_type ; fExpr = expr ; } public SVDBExpr getCastType ( ) { return fCastType ; } public SVDBExpr getExpr ( ) { return fExpr ; } public SVDBCastExpr duplicate ( ) { return ( SVDBCastExpr ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; SVDBCastExpr ce = ( SVDBCastExpr ) other ; fCastType = ( SVDBExpr ) ce . fCastType . duplicate ( ) ; fExpr = ( SVDBExpr ) ce . fExpr . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBIdentifierExpr extends SVDBExpr { public String fId ; public SVDBIdentifierExpr ( ) { this ( ( String ) null ) ; } public SVDBIdentifierExpr ( String id ) { super ( SVDBItemType . IdentifierExpr ) ; fId = id ; } public SVDBIdentifierExpr ( SVDBItemType type , String id ) { super ( type ) ; fId = id ; } public String getId ( ) { return fId ; } public SVDBIdentifierExpr duplicate ( ) { return ( SVDBIdentifierExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBCondExpr extends SVDBExpr { public SVDBExpr fLhs ; public SVDBExpr fMhs ; public SVDBExpr fRhs ; public SVDBCondExpr ( ) { this ( null , null , null ) ; } public SVDBCondExpr ( SVDBExpr lhs , SVDBExpr mhs , SVDBExpr rhs ) { super ( SVDBItemType . CondExpr ) ; fLhs = lhs ; fMhs = mhs ; fRhs = rhs ; } public SVDBExpr getLhs ( ) { return fLhs ; } public SVDBExpr getMhs ( ) { return fMhs ; } public SVDBExpr getRhs ( ) { return fRhs ; } public SVDBCondExpr duplicate ( ) { return ( SVDBCondExpr ) super . duplicate ( ) ; } public void init ( SVDBItemBase other ) { SVDBCondExpr ce = ( SVDBCondExpr ) other ; fLhs = ( SVDBExpr ) ce . fLhs . duplicate ( ) ; fMhs = ( SVDBExpr ) ce . fMhs . duplicate ( ) ; fRhs = ( SVDBExpr ) ce . fRhs . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfo ; public class SVDBTypeExpr extends SVDBExpr { public SVDBTypeInfo fTypeInfo ; public SVDBTypeExpr ( ) { super ( SVDBItemType . TypeExpr ) ; } public SVDBTypeExpr ( SVDBTypeInfo type ) { this ( ) ; fTypeInfo = type ; } public void setTypeInfo ( SVDBTypeInfo type ) { fTypeInfo = type ; } public SVDBTypeInfo getTypeInfo ( ) { return fTypeInfo ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . stmt . SVDBConstraintDistListStmt ; public class SVDBSequenceDistExpr extends SVDBExpr { public SVDBExpr fExpr ; public SVDBConstraintDistListStmt fDistExpr ; public SVDBSequenceDistExpr ( ) { super ( SVDBItemType . SequenceDistExpr ) ; } public SVDBExpr getExpr ( ) { return fExpr ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBConstraintDistListStmt getDistExpr ( ) { return fDistExpr ; } public void setDistExpr ( SVDBConstraintDistListStmt dist ) { fDistExpr = dist ; } } package net . sf . sveditor . core . db . expr ; import java . util . List ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBTFCallExpr extends SVDBExpr { public SVDBExpr fTarget ; public String fName ; public List < SVDBExpr > fArgs ; public SVDBExpr fWithExpr ; public SVDBTFCallExpr ( ) { this ( null , null , null ) ; } public SVDBTFCallExpr ( SVDBExpr target , String name , List < SVDBExpr > args ) { this ( SVDBItemType . TFCallExpr , target , name , args ) ; } public SVDBTFCallExpr ( SVDBItemType type , SVDBExpr target , String name , List < SVDBExpr > args ) { super ( type ) ; fTarget = target ; fName = name ; fArgs = args ; } public SVDBExpr getTarget ( ) { return fTarget ; } public String getName ( ) { return fName ; } public List < SVDBExpr > getArgs ( ) { return fArgs ; } public SVDBExpr getWithExpr ( ) { return fWithExpr ; } public void setWithExpr ( SVDBExpr with ) { fWithExpr = with ; } public SVDBTFCallExpr duplicate ( ) { return ( SVDBTFCallExpr ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . expr ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBPropertyWeakStrongExpr extends SVDBExpr { public boolean fIsWeak ; public SVDBExpr fExpr ; public SVDBPropertyWeakStrongExpr ( ) { super ( SVDBItemType . PropertyWeakStrongExpr ) ; } public void setIsWeak ( boolean is_weak ) { fIsWeak = is_weak ; } public boolean getIsWeak ( ) { return fIsWeak ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } } package net . sf . sveditor . core . db . project ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; public class SVDBSourceCollection { private String fBaseLocation ; private List < String > fIncludes ; private List < String > fExcludes ; private boolean fDefaultIncExcl ; public SVDBSourceCollection ( String base_location , boolean dflt_inc_excl ) { fBaseLocation = base_location ; fIncludes = new ArrayList < String > ( ) ; fExcludes = new ArrayList < String > ( ) ; setDefaultIncExcl ( dflt_inc_excl ) ; } public String getBaseLocation ( ) { return fBaseLocation ; } public boolean getDefaultIncExcl ( ) { return fDefaultIncExcl ; } public void setDefaultIncExcl ( boolean dflt_inc_excl ) { if ( fDefaultIncExcl != dflt_inc_excl ) { if ( dflt_inc_excl ) { fIncludes . clear ( ) ; fExcludes . clear ( ) ; fIncludes . addAll ( SVDBSourceCollection . parsePatternList ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionIncludes ( ) ) ) ; fExcludes . addAll ( SVDBSourceCollection . parsePatternList ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionExcludes ( ) ) ) ; } } fDefaultIncExcl = dflt_inc_excl ; } public void setBaseLocation ( String base ) { fBaseLocation = base ; } public List < String > getIncludes ( ) { return fIncludes ; } public String getIncludesStr ( ) { String ret = "" ; for ( int i = ; i < fIncludes . size ( ) ; i ++ ) { ret += fIncludes . get ( i ) ; if ( i + < fIncludes . size ( ) ) { ret += "" ; } } return ret ; } public List < String > getExcludes ( ) { return fExcludes ; } public String getExcludesStr ( ) { String ret = "" ; for ( int i = ; i < fExcludes . size ( ) ; i ++ ) { ret += fExcludes . get ( i ) ; if ( i + < fExcludes . size ( ) ) { ret += "" ; } } return ret ; } public SVDBSourceCollection duplicate ( ) { SVDBSourceCollection ret = new SVDBSourceCollection ( fBaseLocation , getDefaultIncExcl ( ) ) ; if ( ! getDefaultIncExcl ( ) ) { ret . getIncludes ( ) . addAll ( fIncludes ) ; ret . getExcludes ( ) . addAll ( fExcludes ) ; } return ret ; } public static List < String > parsePatternList ( String pattern ) { String arr [ ] = pattern . split ( "" ) ; List < String > ret = new ArrayList < String > ( ) ; for ( String p : arr ) { ret . add ( p . trim ( ) ) ; } return ret ; } } package net . sf . sveditor . core . db . project ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . WeakHashMap ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibDescriptor ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IResourceDeltaVisitor ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; public class SVDBProjectManager implements IResourceChangeListener { private WeakHashMap < IPath , SVDBProjectData > fProjectMap ; private List < ISVDBProjectSettingsListener > fListeners ; public SVDBProjectManager ( ) { fProjectMap = new WeakHashMap < IPath , SVDBProjectData > ( ) ; fListeners = new ArrayList < ISVDBProjectSettingsListener > ( ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( this ) ; } public void init ( ) { fProjectMap . clear ( ) ; } public void addProjectSettingsListener ( ISVDBProjectSettingsListener l ) { synchronized ( fListeners ) { fListeners . add ( l ) ; } } public void removeProjectSettingsListener ( ISVDBProjectSettingsListener l ) { synchronized ( fListeners ) { fListeners . remove ( l ) ; } } void projectSettingsChanged ( SVDBProjectData data ) { synchronized ( fListeners ) { for ( int i = ; i < fListeners . size ( ) ; i ++ ) { fListeners . get ( i ) . projectSettingsChanged ( data ) ; } } } public List < SVDBProjectData > getProjectList ( ) { List < SVDBProjectData > ret = new ArrayList < SVDBProjectData > ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( IProject p : root . getProjects ( ) ) { if ( p . isOpen ( ) && p . getFile ( "" ) . exists ( ) ) { SVDBProjectData pd = getProjectData ( p ) ; if ( pd != null ) { ret . add ( pd ) ; } } } return ret ; } public SVDBProjectData getProjectData ( IProject proj ) { SVDBProjectData ret = null ; if ( fProjectMap . containsKey ( proj . getFullPath ( ) ) ) { ret = fProjectMap . get ( proj . getFullPath ( ) ) ; } else { IFile svproject ; SVProjectFileWrapper f_wrapper = null ; if ( ( svproject = proj . getFile ( "" ) ) . exists ( ) ) { InputStream in = null ; try { svproject . refreshLocal ( IResource . DEPTH_ZERO , null ) ; in = svproject . getContents ( ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } try { f_wrapper = new SVProjectFileWrapper ( in ) ; } catch ( Exception e ) { f_wrapper = null ; } } if ( f_wrapper == null ) { f_wrapper = new SVProjectFileWrapper ( ) ; setupDefaultProjectFile ( f_wrapper ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; f_wrapper . toStream ( bos ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; try { if ( svproject . exists ( ) ) { svproject . setContents ( bis , true , true , null ) ; } else { svproject . create ( bis , true , null ) ; } } catch ( CoreException e ) { e . printStackTrace ( ) ; } } ret = new SVDBProjectData ( proj , f_wrapper , svproject . getFullPath ( ) ) ; fProjectMap . put ( proj . getFullPath ( ) , ret ) ; } return ret ; } private static void setupDefaultProjectFile ( SVProjectFileWrapper file_wrapper ) { List < SVDBPluginLibDescriptor > lib_d = SVCorePlugin . getDefault ( ) . getPluginLibList ( ) ; for ( SVDBPluginLibDescriptor d : lib_d ) { if ( d . isDefault ( ) ) { file_wrapper . getPluginPaths ( ) . add ( new SVDBPath ( d . getId ( ) ) ) ; } } } public void resourceChanged ( IResourceChangeEvent event ) { final Set < IProject > changed_project = new HashSet < IProject > ( ) ; if ( event . getDelta ( ) != null ) { try { event . getDelta ( ) . accept ( new IResourceDeltaVisitor ( ) { public boolean visit ( IResourceDelta delta ) throws CoreException { IProject p = delta . getResource ( ) . getProject ( ) ; if ( p != null && fProjectMap . containsKey ( p . getFullPath ( ) ) ) { if ( delta . getResource ( ) . equals ( "" ) && delta . getKind ( ) == IResourceDelta . CHANGED ) { if ( ! changed_project . contains ( p ) ) { changed_project . add ( p ) ; } } } return true ; } } ) ; } catch ( CoreException e ) { } } for ( IProject p : changed_project ) { SVDBProjectData pd = fProjectMap . get ( p . getFullPath ( ) ) ; pd . setProjectFileWrapper ( pd . getProjectFileWrapper ( ) , false ) ; } } public void dispose ( ) { ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( this ) ; } } package net . sf . sveditor . core . db . project ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexFactory ; import net . sf . sveditor . core . db . index . ISVDBProjectRefProvider ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexConfig ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . fileset . SVFileSet ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBProjectData implements ISVDBProjectRefProvider { private IProject fProject ; private IPath fSVProjFilePath ; private SVProjectFileWrapper fFileWrapper ; private SVDBIndexCollection fIndexCollection ; private String fProjectName ; private LogHandle fLog ; private List < ISVDBProjectSettingsListener > fListeners ; public SVDBProjectData ( IProject project , SVProjectFileWrapper wrapper , IPath projfile_path ) { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; fProject = project ; fLog = LogFactory . getLogHandle ( "" ) ; fListeners = new ArrayList < ISVDBProjectSettingsListener > ( ) ; fProjectName = project . getName ( ) ; fSVProjFilePath = projfile_path ; fIndexCollection = new SVDBIndexCollection ( rgy . getIndexCollectionMgr ( ) , fProjectName ) ; fFileWrapper = null ; setProjectFileWrapper ( wrapper , false ) ; } public SVDBIndexCollection resolveProjectRef ( String path ) { IWorkspace ws = ResourcesPlugin . getWorkspace ( ) ; IWorkspaceRoot root = ws . getRoot ( ) ; SVDBIndexCollection mgr = null ; SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; IProject p = root . getProject ( path ) ; if ( p != null ) { SVDBProjectData p_data = p_mgr . getProjectData ( p ) ; if ( p_data != null ) { mgr = p_data . getProjectIndexMgr ( ) ; } } return mgr ; } public String getName ( ) { return fProjectName ; } public void addProjectSettingsListener ( ISVDBProjectSettingsListener l ) { synchronized ( fListeners ) { fListeners . add ( l ) ; } } public void removeProjectSettingsListener ( ISVDBProjectSettingsListener l ) { synchronized ( fListeners ) { fListeners . remove ( l ) ; } } public synchronized SVDBIndexCollection getProjectIndexMgr ( ) { if ( fIndexCollection == null ) { fIndexCollection = createProjectIndex ( ) ; } return fIndexCollection ; } public void refreshProjectFile ( ) { try { IFile file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( fSVProjFilePath ) ; InputStream in = file . getContents ( ) ; fFileWrapper = new SVProjectFileWrapper ( in ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } public SVProjectFileWrapper getProjectFileWrapper ( ) { return fFileWrapper ; } public synchronized void setProjectFileWrapper ( SVProjectFileWrapper w ) { setProjectFileWrapper ( w , true ) ; } public synchronized void setProjectFileWrapper ( SVProjectFileWrapper w , boolean set_contents ) { boolean refresh = set_contents ; if ( fFileWrapper == null || ! fFileWrapper . equals ( w ) ) { fLog . debug ( "" ) ; refresh = true ; } else { fLog . debug ( "" ) ; } fFileWrapper = w ; if ( set_contents ) { try { IFile file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( fSVProjFilePath ) ; file . refreshLocal ( IResource . DEPTH_ONE , null ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; fFileWrapper . toStream ( out ) ; if ( file . exists ( ) ) { file . setContents ( new ByteArrayInputStream ( out . toByteArray ( ) ) , true , true , null ) ; } else { file . create ( new ByteArrayInputStream ( out . toByteArray ( ) ) , true , null ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( fProject != null ) { IProject refs [ ] = null ; try { refs = fProject . getReferencedProjects ( ) ; } catch ( CoreException e ) { } if ( refs == null ) { refs = new IProject [ ] ; } boolean set_paths = false ; if ( refs . length != w . getProjectRefs ( ) . size ( ) ) { set_paths = true ; } else { for ( int i = ; i < refs . length ; i ++ ) { SVDBPath p = new SVDBPath ( refs [ i ] . getName ( ) ) ; if ( ! w . getProjectRefs ( ) . contains ( p ) ) { set_paths = true ; break ; } } } if ( set_paths ) { refresh = true ; w . getProjectRefs ( ) . clear ( ) ; for ( int i = ; i < refs . length ; i ++ ) { w . addProjectRef ( refs [ i ] . getName ( ) ) ; } } } if ( refresh && fIndexCollection != null ) { setProjectPaths ( fIndexCollection , fFileWrapper , refresh ) ; } } private SVDBIndexCollection createProjectIndex ( ) { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; SVDBIndexCollection ret = new SVDBIndexCollection ( rgy . getIndexCollectionMgr ( ) , fProjectName ) ; SVProjectFileWrapper fw = getProjectFileWrapper ( ) ; setProjectPaths ( ret , fw , false ) ; return ret ; } private void setProjectPaths ( SVDBIndexCollection sc , SVProjectFileWrapper fw , boolean refresh ) { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; Map < String , String > define_map = new HashMap < String , String > ( ) ; SVDBIndexConfig args = new SVDBIndexConfig ( ) ; for ( Tuple < String , String > def : fw . getGlobalDefines ( ) ) { if ( define_map . containsKey ( def . first ( ) ) ) { define_map . remove ( def . first ( ) ) ; } define_map . put ( def . first ( ) , def . second ( ) ) ; } sc . clear ( ) ; sc . setProjectRefProvider ( this ) ; for ( SVDBPath pr : fw . getProjectRefs ( ) ) { sc . addProjectRef ( pr . getPath ( ) ) ; } for ( SVDBPath path : fw . getPluginPaths ( ) ) { ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , SVDBIndexRegistry . GLOBAL_PROJECT , path . getPath ( ) , SVDBPluginLibIndexFactory . TYPE , null ) ; if ( index != null ) { sc . addPluginLibrary ( index ) ; } else { fLog . error ( "" + path . getPath ( ) + "" ) ; } } args . clear ( ) ; args . put ( ISVDBIndexFactory . KEY_GlobalDefineMap , define_map ) ; for ( SVDBPath path : fw . getLibraryPaths ( ) ) { ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , fProjectName , path . getPath ( ) , SVDBLibPathIndexFactory . TYPE , args ) ; if ( index != null ) { sc . addLibraryPath ( index ) ; } else { fLog . error ( "" + path . getPath ( ) + "" ) ; } } args . clear ( ) ; args . put ( ISVDBIndexFactory . KEY_GlobalDefineMap , define_map ) ; for ( SVDBPath path : fw . getArgFilePaths ( ) ) { ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , fProjectName , path . getPath ( ) , SVDBArgFileIndexFactory . TYPE , args ) ; if ( index != null ) { sc . addLibraryPath ( index ) ; } else { fLog . error ( "" + path . getPath ( ) + "" ) ; } } for ( SVDBSourceCollection srcc : fw . getSourceCollections ( ) ) { SVDBIndexConfig params = new SVDBIndexConfig ( ) ; SVFileSet fs = new SVFileSet ( srcc . getBaseLocation ( ) ) ; for ( String incl : srcc . getIncludes ( ) ) { fs . addInclude ( incl ) ; } for ( String excl : srcc . getExcludes ( ) ) { fs . addExclude ( excl ) ; } params . put ( SVDBSourceCollectionIndexFactory . FILESET , fs ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , fProjectName , srcc . getBaseLocation ( ) , SVDBSourceCollectionIndexFactory . TYPE , params ) ; if ( index != null ) { sc . addSourceCollection ( index ) ; } else { fLog . error ( "" + "" + srcc . getBaseLocation ( ) + "" ) ; } } List < ISVDBIndex > active_indexes = sc . getIndexList ( ) ; List < ISVDBIndex > project_indexes = rgy . getProjectIndexList ( fProjectName ) ; for ( ISVDBIndex i : active_indexes ) { project_indexes . remove ( i ) ; } for ( ISVDBIndex i : project_indexes ) { rgy . disposeIndex ( i ) ; } for ( ISVDBIndex index : rgy . getProjectIndexList ( fProjectName ) ) { for ( Tuple < String , String > def : fw . getGlobalDefines ( ) ) { index . setGlobalDefine ( def . first ( ) , def . second ( ) ) ; } } synchronized ( fListeners ) { for ( ISVDBProjectSettingsListener l : fListeners ) { l . projectSettingsChanged ( this ) ; } } if ( refresh ) { SVCorePlugin . getDefault ( ) . getProjMgr ( ) . projectSettingsChanged ( this ) ; } } public boolean equals ( Object other ) { if ( other instanceof SVDBProjectData ) { SVDBProjectData o = ( SVDBProjectData ) other ; boolean eq = true ; System . out . println ( "" + fProjectName + "" + o . fProjectName ) ; eq &= o . fProjectName . equals ( fProjectName ) ; eq &= o . fFileWrapper . equals ( fFileWrapper ) ; return eq ; } else { return false ; } } } package net . sf . sveditor . core . db . project ; public class SVDBPath { private String fPath ; private boolean fPhantom ; public SVDBPath ( String path ) { fPath = path ; fPhantom = false ; } public SVDBPath ( String path , boolean is_phantom ) { fPath = path ; fPhantom = is_phantom ; } public boolean getIsPhantom ( ) { return fPhantom ; } public void setIsPhantom ( boolean is_phantom ) { fPhantom = is_phantom ; } public String getPath ( ) { return fPath ; } public void setPath ( String path ) { fPath = path ; } public SVDBPath duplicate ( ) { return new SVDBPath ( fPath , fPhantom ) ; } public boolean equals ( Object other ) { if ( other instanceof SVDBPath ) { SVDBPath other_p = ( SVDBPath ) other ; if ( other_p . fPath . equals ( fPath ) ) { return true ; } } return false ; } } package net . sf . sveditor . core . db . project ; public interface ISVDBProjectSettingsListener { void projectSettingsChanged ( SVDBProjectData data ) ; } package net . sf . sveditor . core . db . project ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . List ; import java . util . Properties ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . sax . SAXTransformerFactory ; import javax . xml . transform . sax . TransformerHandler ; import javax . xml . transform . stream . StreamResult ; import net . sf . sveditor . core . Tuple ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; import org . xml . sax . ErrorHandler ; import org . xml . sax . SAXException ; import org . xml . sax . SAXParseException ; public class SVProjectFileWrapper { private Document fDocument ; private List < Tuple < String , String > > fGlobalDefines ; private List < SVDBPath > fIncludePaths ; private List < SVDBPath > fLibraryPaths ; private List < SVDBPath > fBuildPaths ; private List < SVDBPath > fPluginPaths ; private List < SVDBPath > fArgFilePaths ; private List < SVDBSourceCollection > fSourceCollections ; private List < SVDBPath > fProjectReferences ; public SVProjectFileWrapper ( ) { fGlobalDefines = new ArrayList < Tuple < String , String > > ( ) ; fIncludePaths = new ArrayList < SVDBPath > ( ) ; fLibraryPaths = new ArrayList < SVDBPath > ( ) ; fBuildPaths = new ArrayList < SVDBPath > ( ) ; fPluginPaths = new ArrayList < SVDBPath > ( ) ; fArgFilePaths = new ArrayList < SVDBPath > ( ) ; fSourceCollections = new ArrayList < SVDBSourceCollection > ( ) ; fProjectReferences = new ArrayList < SVDBPath > ( ) ; DocumentBuilderFactory f = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder b = null ; try { b = f . newDocumentBuilder ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) ) ; } fDocument = b . newDocument ( ) ; init ( ) ; } public SVProjectFileWrapper ( InputStream in ) throws Exception { fGlobalDefines = new ArrayList < Tuple < String , String > > ( ) ; fIncludePaths = new ArrayList < SVDBPath > ( ) ; fLibraryPaths = new ArrayList < SVDBPath > ( ) ; fBuildPaths = new ArrayList < SVDBPath > ( ) ; fPluginPaths = new ArrayList < SVDBPath > ( ) ; fArgFilePaths = new ArrayList < SVDBPath > ( ) ; fSourceCollections = new ArrayList < SVDBSourceCollection > ( ) ; fProjectReferences = new ArrayList < SVDBPath > ( ) ; DocumentBuilderFactory f = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder b = f . newDocumentBuilder ( ) ; b . setErrorHandler ( fErrorHandler ) ; fDocument = b . parse ( in ) ; init ( ) ; } private boolean init ( ) { NodeList svprojectList = fDocument . getElementsByTagName ( "" ) ; Element svproject ; boolean change = false ; if ( svprojectList . getLength ( ) == ) { svproject = fDocument . createElement ( "" ) ; fDocument . appendChild ( svproject ) ; } else { svproject = ( Element ) svprojectList . item ( ) ; } change |= init_defines ( svproject ) ; change |= init_paths ( svproject , "" , "" , fIncludePaths ) ; change |= init_paths ( svproject , "" , "" , fBuildPaths ) ; change |= init_paths ( svproject , "" , "" , fPluginPaths ) ; change |= init_paths ( svproject , "" , "" , fLibraryPaths ) ; change |= init_paths ( svproject , "" , "" , fArgFilePaths ) ; change |= init_source_collections ( svproject , "" , "" , fSourceCollections ) ; change |= init_paths ( svproject , "" , "" , fProjectReferences ) ; return change ; } private boolean init_paths ( Element svproject , String containerName , String elementName , List < SVDBPath > element_list ) { boolean change = false ; NodeList pathsList = svproject . getElementsByTagName ( containerName ) ; Element paths = null ; if ( pathsList . getLength ( ) > ) { paths = ( Element ) pathsList . item ( ) ; } else { paths = fDocument . createElement ( containerName ) ; svproject . appendChild ( paths ) ; change = true ; } NodeList includePathList = paths . getElementsByTagName ( elementName ) ; for ( int i = ; i < includePathList . getLength ( ) ; i ++ ) { Element includePath = ( Element ) includePathList . item ( i ) ; String path = includePath . getAttribute ( "" ) ; if ( path == null ) { path = "" ; } element_list . add ( new SVDBPath ( path , false ) ) ; } return change ; } private boolean init_defines ( Element svproject ) { boolean change = false ; NodeList definesList = svproject . getElementsByTagName ( "" ) ; Element paths = null ; if ( definesList . getLength ( ) > ) { paths = ( Element ) definesList . item ( ) ; } else { paths = fDocument . createElement ( "" ) ; svproject . appendChild ( paths ) ; change = true ; } NodeList defineList = paths . getElementsByTagName ( "" ) ; for ( int i = ; i < defineList . getLength ( ) ; i ++ ) { Element define = ( Element ) defineList . item ( i ) ; String key = define . getAttribute ( "" ) ; String val = define . getAttribute ( "" ) ; if ( key == null ) { key = "" ; } fGlobalDefines . add ( new Tuple < String , String > ( key , val ) ) ; } return change ; } private boolean init_source_collections ( Element svproject , String containerName , String elementName , List < SVDBSourceCollection > element_list ) { boolean change = false ; NodeList pathsList = svproject . getElementsByTagName ( containerName ) ; Element paths = null ; if ( pathsList . getLength ( ) > ) { paths = ( Element ) pathsList . item ( ) ; } else { paths = fDocument . createElement ( containerName ) ; svproject . appendChild ( paths ) ; change = true ; } NodeList sourceCollectionList = paths . getElementsByTagName ( elementName ) ; for ( int i = ; i < sourceCollectionList . getLength ( ) ; i ++ ) { Element sourceCollection = ( Element ) sourceCollectionList . item ( i ) ; String baseLocation = sourceCollection . getAttribute ( "" ) ; if ( baseLocation == null ) { continue ; } SVDBSourceCollection c ; if ( sourceCollection . hasAttribute ( "" ) ) { boolean dflt_inc_excl = ( sourceCollection . getAttribute ( "" ) . equals ( "" ) ) ; c = new SVDBSourceCollection ( baseLocation , dflt_inc_excl ) ; if ( ! dflt_inc_excl ) { NodeList includeList = sourceCollection . getElementsByTagName ( "" ) ; for ( int j = ; j < includeList . getLength ( ) ; j ++ ) { Element inc = ( Element ) includeList . item ( j ) ; String expr = inc . getAttribute ( "" ) ; if ( expr != null && ! expr . equals ( "" ) ) { c . getIncludes ( ) . add ( expr ) ; } } NodeList excludeList = sourceCollection . getElementsByTagName ( "" ) ; for ( int j = ; j < excludeList . getLength ( ) ; j ++ ) { Element excl = ( Element ) excludeList . item ( j ) ; String expr = excl . getAttribute ( "" ) ; if ( expr != null && ! expr . equals ( "" ) ) { c . getExcludes ( ) . add ( expr ) ; } } } } else { c = new SVDBSourceCollection ( baseLocation , false ) ; NodeList includeList = sourceCollection . getElementsByTagName ( "" ) ; for ( int j = ; j < includeList . getLength ( ) ; j ++ ) { Element inc = ( Element ) includeList . item ( j ) ; String expr = inc . getAttribute ( "" ) ; if ( expr != null && ! expr . equals ( "" ) ) { c . getIncludes ( ) . add ( expr ) ; } } NodeList excludeList = sourceCollection . getElementsByTagName ( "" ) ; for ( int j = ; j < excludeList . getLength ( ) ; j ++ ) { Element excl = ( Element ) excludeList . item ( j ) ; String expr = excl . getAttribute ( "" ) ; if ( expr != null && ! expr . equals ( "" ) ) { c . getExcludes ( ) . add ( expr ) ; } } } element_list . add ( c ) ; } return change ; } private void marshall ( ) { NodeList svprojectList = fDocument . getElementsByTagName ( "" ) ; Element svproject ; if ( svprojectList . getLength ( ) == ) { svproject = fDocument . createElement ( "" ) ; fDocument . appendChild ( svproject ) ; } else { svproject = ( Element ) svprojectList . item ( ) ; } marshall_defines ( svproject ) ; marshall_paths ( svproject , "" , "" , fIncludePaths ) ; marshall_paths ( svproject , "" , "" , fBuildPaths ) ; marshall_paths ( svproject , "" , "" , fLibraryPaths ) ; marshall_paths ( svproject , "" , "" , fPluginPaths ) ; marshall_paths ( svproject , "" , "" , fArgFilePaths ) ; marshall_source_collections ( svproject , fSourceCollections ) ; marshall_paths ( svproject , "" , "" , fProjectReferences ) ; } private void marshall_paths ( Element svproject , String containerName , String elementName , List < SVDBPath > element_list ) { NodeList pathsList = svproject . getElementsByTagName ( containerName ) ; Element paths = null ; if ( pathsList . getLength ( ) > ) { paths = ( Element ) pathsList . item ( ) ; } else { paths = fDocument . createElement ( containerName ) ; svproject . appendChild ( paths ) ; } NodeList includePathList = paths . getElementsByTagName ( elementName ) ; for ( int i = ; i < includePathList . getLength ( ) ; i ++ ) { paths . removeChild ( ( Element ) includePathList . item ( i ) ) ; } for ( SVDBPath ip : element_list ) { Element path = fDocument . createElement ( elementName ) ; path . setAttribute ( "" , ip . getPath ( ) ) ; paths . appendChild ( path ) ; } } private void marshall_defines ( Element svproject ) { NodeList definesList = svproject . getElementsByTagName ( "" ) ; Element defines = null ; if ( definesList . getLength ( ) > ) { defines = ( Element ) definesList . item ( ) ; } else { defines = fDocument . createElement ( "" ) ; svproject . appendChild ( defines ) ; } NodeList defineList = defines . getElementsByTagName ( "" ) ; for ( int i = ; i < defineList . getLength ( ) ; i ++ ) { defines . removeChild ( ( Element ) defineList . item ( i ) ) ; } for ( Tuple < String , String > def : fGlobalDefines ) { Element def_e = fDocument . createElement ( "" ) ; def_e . setAttribute ( "" , def . first ( ) ) ; def_e . setAttribute ( "" , def . second ( ) ) ; defines . appendChild ( def_e ) ; } } private void marshall_source_collections ( Element svproject , List < SVDBSourceCollection > source_collections ) { NodeList collectionsList = svproject . getElementsByTagName ( "" ) ; Element paths = null ; if ( collectionsList . getLength ( ) > ) { paths = ( Element ) collectionsList . item ( ) ; } else { paths = fDocument . createElement ( "" ) ; svproject . appendChild ( paths ) ; } NodeList sourceCollections = paths . getElementsByTagName ( "" ) ; for ( int i = ; i < sourceCollections . getLength ( ) ; i ++ ) { paths . removeChild ( ( Element ) sourceCollections . item ( i ) ) ; } for ( SVDBSourceCollection c : source_collections ) { Element path = fDocument . createElement ( "" ) ; path . setAttribute ( "" , c . getBaseLocation ( ) ) ; path . setAttribute ( "" , ( c . getDefaultIncExcl ( ) ) ? "" : "" ) ; if ( ! c . getDefaultIncExcl ( ) ) { for ( String inc : c . getIncludes ( ) ) { Element inc_e = fDocument . createElement ( "" ) ; inc_e . setAttribute ( "" , inc ) ; path . appendChild ( inc_e ) ; } for ( String excl : c . getExcludes ( ) ) { Element excl_e = fDocument . createElement ( "" ) ; excl_e . setAttribute ( "" , excl ) ; path . appendChild ( excl_e ) ; } } paths . appendChild ( path ) ; } } public List < SVDBPath > getIncludePaths ( ) { return fIncludePaths ; } public List < SVDBPath > getLibraryPaths ( ) { return fLibraryPaths ; } public List < SVDBPath > getBuildPaths ( ) { return fBuildPaths ; } public List < SVDBPath > getPluginPaths ( ) { return fPluginPaths ; } public List < SVDBPath > getArgFilePaths ( ) { return fArgFilePaths ; } public void addArgFilePath ( String path ) { SVDBPath arg_path = new SVDBPath ( path ) ; if ( ! fArgFilePaths . contains ( arg_path ) ) { fArgFilePaths . add ( arg_path ) ; } } public List < Tuple < String , String > > getGlobalDefines ( ) { return fGlobalDefines ; } public void addGlobalDefine ( String key , String val ) { synchronized ( fGlobalDefines ) { boolean found = false ; for ( int i = ; i < fGlobalDefines . size ( ) ; i ++ ) { if ( fGlobalDefines . get ( i ) . first ( ) . equals ( key ) ) { fGlobalDefines . set ( i , new Tuple < String , String > ( key , val ) ) ; found = true ; break ; } } if ( ! found ) { fGlobalDefines . add ( new Tuple < String , String > ( key , val ) ) ; } } } public List < SVDBSourceCollection > getSourceCollections ( ) { return fSourceCollections ; } public List < SVDBPath > getProjectRefs ( ) { return fProjectReferences ; } public void addProjectRef ( String ref ) { SVDBPath p = new SVDBPath ( ref ) ; fProjectReferences . add ( p ) ; } public void toStream ( OutputStream out ) { SAXTransformerFactory tf = ( SAXTransformerFactory ) SAXTransformerFactory . newInstance ( ) ; try { marshall ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } try { DOMSource ds = new DOMSource ( fDocument ) ; StreamResult sr = new StreamResult ( out ) ; tf . setAttribute ( "" , new Integer ( ) ) ; TransformerHandler th = tf . newTransformerHandler ( ) ; Properties format = new Properties ( ) ; format . put ( OutputKeys . METHOD , "" ) ; format . put ( OutputKeys . ENCODING , "" ) ; format . put ( OutputKeys . INDENT , "" ) ; th . getTransformer ( ) . setOutputProperties ( format ) ; th . setResult ( sr ) ; th . getTransformer ( ) . transform ( ds , sr ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } public SVProjectFileWrapper duplicate ( ) { SVProjectFileWrapper ret = new SVProjectFileWrapper ( ) ; ret . init ( this ) ; return ret ; } public void init ( SVProjectFileWrapper fw ) { fIncludePaths . clear ( ) ; fPluginPaths . clear ( ) ; fLibraryPaths . clear ( ) ; fArgFilePaths . clear ( ) ; fProjectReferences . clear ( ) ; fSourceCollections . clear ( ) ; fBuildPaths . clear ( ) ; fGlobalDefines . clear ( ) ; for ( SVDBPath p : fw . fIncludePaths ) { fIncludePaths . add ( p . duplicate ( ) ) ; } for ( SVDBPath p : fw . getLibraryPaths ( ) ) { fLibraryPaths . add ( p . duplicate ( ) ) ; } for ( SVDBPath p : fw . getPluginPaths ( ) ) { fPluginPaths . add ( p . duplicate ( ) ) ; } for ( SVDBSourceCollection c : fw . fSourceCollections ) { fSourceCollections . add ( c . duplicate ( ) ) ; } for ( SVDBPath p : fw . getArgFilePaths ( ) ) { fArgFilePaths . add ( p . duplicate ( ) ) ; } for ( SVDBPath p : fw . getProjectRefs ( ) ) { fProjectReferences . add ( p . duplicate ( ) ) ; } for ( SVDBPath p : fw . fBuildPaths ) { fBuildPaths . add ( p . duplicate ( ) ) ; } for ( Tuple < String , String > def : fw . fGlobalDefines ) { Tuple < String , String > dup = new Tuple < String , String > ( def . first ( ) , def . second ( ) ) ; fGlobalDefines . add ( dup ) ; } } public boolean equals ( Object other ) { if ( other instanceof SVProjectFileWrapper ) { SVProjectFileWrapper p = ( SVProjectFileWrapper ) other ; if ( p . fIncludePaths . size ( ) != fIncludePaths . size ( ) ) { return false ; } for ( int i = ; i < fIncludePaths . size ( ) ; i ++ ) { if ( ! p . fIncludePaths . get ( i ) . getPath ( ) . equals ( fIncludePaths . get ( i ) . getPath ( ) ) ) { return false ; } } if ( p . fLibraryPaths . size ( ) != fLibraryPaths . size ( ) ) { return false ; } for ( int i = ; i < fLibraryPaths . size ( ) ; i ++ ) { if ( ! p . fLibraryPaths . get ( i ) . equals ( fLibraryPaths . get ( i ) ) ) { return false ; } } if ( p . getArgFilePaths ( ) . size ( ) != fArgFilePaths . size ( ) ) { return false ; } for ( int i = ; i < fArgFilePaths . size ( ) ; i ++ ) { if ( ! p . fArgFilePaths . get ( i ) . equals ( fArgFilePaths . get ( i ) ) ) { return false ; } } if ( p . fProjectReferences . size ( ) != fProjectReferences . size ( ) ) { return false ; } for ( int i = ; i < fProjectReferences . size ( ) ; i ++ ) { if ( ! p . fProjectReferences . get ( i ) . equals ( fProjectReferences . get ( i ) ) ) { return false ; } } if ( fSourceCollections . size ( ) != p . fSourceCollections . size ( ) ) { return false ; } for ( int i = ; i < fSourceCollections . size ( ) ; i ++ ) { if ( ! p . fSourceCollections . get ( i ) . equals ( fSourceCollections . get ( i ) ) ) { return false ; } } if ( fPluginPaths . size ( ) != p . fPluginPaths . size ( ) ) { return false ; } for ( int i = ; i < fPluginPaths . size ( ) ; i ++ ) { if ( ! p . fPluginPaths . get ( i ) . equals ( fPluginPaths . get ( i ) ) ) { return false ; } } if ( fGlobalDefines . size ( ) != p . fGlobalDefines . size ( ) ) { return false ; } for ( int i = ; i < fGlobalDefines . size ( ) ; i ++ ) { if ( ! p . fGlobalDefines . get ( i ) . first ( ) . equals ( fGlobalDefines . get ( i ) . first ( ) ) || ! p . fGlobalDefines . get ( i ) . second ( ) . equals ( fGlobalDefines . get ( i ) . second ( ) ) ) { return false ; } } return true ; } return false ; } private ErrorHandler fErrorHandler = new ErrorHandler ( ) { public void error ( SAXParseException arg0 ) throws SAXException { throw arg0 ; } public void fatalError ( SAXParseException arg0 ) throws SAXException { throw arg0 ; } public void warning ( SAXParseException arg0 ) throws SAXException { } } ; } package net . sf . sveditor . core . db ; import java . io . File ; public class SVDBFile extends SVDBScopeItem { public String fFile ; public SVDBFile ( ) { super ( "" , SVDBItemType . File ) ; fFile = "" ; } public SVDBFile ( String file ) { super ( file , SVDBItemType . File ) ; if ( file != null ) { setName ( new File ( file ) . getName ( ) ) ; } else { try { throw new Exception ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } fFile = file ; setLocation ( new SVDBLocation ( - , - ) ) ; } public String getFilePath ( ) { return fFile ; } public void setFilePath ( String file ) { if ( file == null ) { try { throw new Exception ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } fFile = file ; } public void clearChildren ( ) { fItems . clear ( ) ; } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBParamValueAssign extends SVDBItem { public SVDBExpr fValue ; public SVDBTypeInfo fType ; public SVDBParamValueAssign ( ) { super ( "" , SVDBItemType . ParamValueAssign ) ; } public SVDBParamValueAssign ( String name , SVDBExpr value ) { super ( name , SVDBItemType . ParamValueAssign ) ; fValue = value ; } public SVDBParamValueAssign ( String name , SVDBTypeInfo type ) { super ( name , SVDBItemType . ParamValueAssign ) ; fType = type ; } public SVDBExpr getValue ( ) { return fValue ; } public SVDBTypeInfo getTypeInfo ( ) { return fType ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; public class SVDBTypeInfoStruct extends SVDBTypeInfo implements ISVDBScopeItem { public SVDBLocation fEndLocation ; public List < SVDBVarDeclStmt > fFields ; public SVDBTypeInfoStruct ( ) { super ( "" , SVDBItemType . TypeInfoStruct ) ; fFields = new ArrayList < SVDBVarDeclStmt > ( ) ; } public SVDBLocation getEndLocation ( ) { return fEndLocation ; } public void setEndLocation ( SVDBLocation loc ) { fEndLocation = loc ; } @ SuppressWarnings ( { "" , "" } ) public List < ISVDBItemBase > getItems ( ) { return ( List ) fFields ; } @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fFields . iterator ( ) ; } } ; } public void addItem ( ISVDBItemBase item ) { } public List < SVDBVarDeclStmt > getFields ( ) { return fFields ; } public void addChildItem ( ISVDBChildItem f ) { fFields . add ( ( SVDBVarDeclStmt ) f ) ; f . setParent ( this ) ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBTypeInfoStruct ) { SVDBTypeInfoStruct o = ( SVDBTypeInfoStruct ) obj ; if ( fFields . size ( ) == o . fFields . size ( ) ) { for ( int i = ; i < fFields . size ( ) ; i ++ ) { if ( ! fFields . get ( i ) . equals ( o . fFields . get ( i ) ) ) { return false ; } } } else { return false ; } return super . equals ( obj ) ; } return false ; } @ Override public SVDBTypeInfoStruct duplicate ( ) { return ( SVDBTypeInfoStruct ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db . persistence ; public class SVDBPersistenceRW extends SVDBDelegatingPersistenceRW { public SVDBPersistenceRW ( ) { addDelegate ( JITPersistenceDelegateFactory . instance ( ) . newDelegate ( ) ) ; } } package net . sf . sveditor . core . db . persistence ; import java . io . DataOutput ; import java . util . Collection ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; @ SuppressWarnings ( "" ) public interface IDBWriter { void init ( DataOutput out ) ; void setDebugEn ( boolean en ) ; void close ( ) ; void writeInt ( int val ) throws DBWriteException ; void writeLong ( long val ) throws DBWriteException ; void writeObject ( Class cls , Object obj ) throws DBWriteException ; void writeByteArray ( byte data [ ] ) throws DBWriteException ; void writeString ( String val ) throws DBWriteException ; void writeItemType ( SVDBItemType type ) throws DBWriteException ; void writeEnumType ( Class enum_type , Enum value ) throws DBWriteException ; void writeItemList ( List items ) throws DBWriteException ; void writeSVDBItem ( ISVDBItemBase item ) throws DBWriteException ; void writeStringList ( List < String > items ) throws DBWriteException ; void writeIntList ( List < Integer > items ) throws DBWriteException ; void writeLongList ( List < Long > items ) throws DBWriteException ; } package net . sf . sveditor . core . db . persistence ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . db . SVDBItemType ; @ SuppressWarnings ( "" ) public abstract class JITPersistenceDelegateBase extends SVDBPersistenceRWDelegateBase { protected List < Class > fObjectTypeList ; public JITPersistenceDelegateBase ( ) { fObjectTypeList = new ArrayList < Class > ( ) ; } public void setSupportedClasses ( List < Class > s ) { fObjectTypeList = s ; } @ Override public void init ( Set < SVDBItemType > supported_items , Set < Class > supported_objects ) { super . init ( supported_items , supported_objects ) ; } public void writeEnumType ( Class cls , Enum value ) throws DBWriteException { } public Enum readEnumType ( Class enum_type ) throws DBFormatException { return null ; } protected void writeObjectErr ( Object obj ) throws DBWriteException { System . out . println ( "" + obj . getClass ( ) . getName ( ) ) ; } protected void readObjectErr ( Object obj ) throws DBFormatException { System . out . println ( "" + obj . getClass ( ) . getName ( ) ) ; } } package net . sf . sveditor . core . db . persistence ; import java . io . DataInput ; import java . io . DataOutput ; import java . util . HashSet ; import java . util . Set ; import net . sf . sveditor . core . db . SVDBItemType ; @ SuppressWarnings ( "" ) public abstract class SVDBPersistenceRWDelegateBase extends SVDBPersistenceRWBase implements ISVDBPersistenceRWDelegate { protected Set < SVDBItemType > fSupportedItems ; protected Set < Class > fSupportedObjects ; protected ISVDBPersistenceRWDelegateParent fParent ; public SVDBPersistenceRWDelegateBase ( ) { fSupportedItems = new HashSet < SVDBItemType > ( ) ; fSupportedObjects = new HashSet < Class > ( ) ; } public void init ( ISVDBPersistenceRWDelegateParent parent , DataInput in , DataOutput out ) { fParent = parent ; fIn = in ; fOut = out ; } public void init ( Set < SVDBItemType > supported_items , Set < Class > supported_objects ) { fSupportedItems . addAll ( supported_items ) ; fSupportedObjects . addAll ( supported_objects ) ; } public void addSupportedType ( SVDBItemType t ) { fSupportedItems . add ( t ) ; } public Set < Class > getSupportedObjects ( ) { return fSupportedObjects ; } public Set < Class > getSupportedEnumTypes ( ) { return null ; } public Set < SVDBItemType > getSupportedItemTypes ( ) { return fSupportedItems ; } } package net . sf . sveditor . core . db . persistence ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import net . sf . sveditor . core . db . SVDBLocation ; public abstract class SVDBPersistenceRWBase implements IDBPersistenceTypes { private byte fTmp [ ] ; protected DataInput fIn ; protected DataOutput fOut ; public void init ( DataInput in ) { fIn = in ; fOut = null ; } public void init ( DataOutput out ) { fOut = out ; fIn = null ; } public void close ( ) { } public SVDBLocation readSVDBLocation ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_SVDB_LOCATION ) { throw new DBFormatException ( "" + type ) ; } int line = readInt ( ) ; int pos = readInt ( ) ; return new SVDBLocation ( line , pos ) ; } public String readString ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_STRING ) { throw new DBFormatException ( "" + type ) ; } int len = readInt ( ) ; if ( len < ) { throw new DBFormatException ( "" + len ) ; } if ( fTmp == null || fTmp . length < len ) { fTmp = new byte [ len ] ; } try { fIn . readFully ( fTmp , , len ) ; } catch ( IOException e ) { throw new DBFormatException ( "" + e . getMessage ( ) ) ; } String ret = new String ( fTmp , , len ) ; return ret ; } public int readRawType ( ) throws DBFormatException { int ret = - ; if ( fIn == null ) { throw new DBFormatException ( "" + fOut ) ; } try { ret = fIn . readByte ( ) ; } catch ( IOException e ) { throw new DBFormatException ( "" + e . getMessage ( ) ) ; } if ( ret < TYPE_INT_8 || ret >= TYPE_MAX ) { throw new DBFormatException ( "" + ret ) ; } return ret ; } public Map < String , String > readMapStringString ( ) throws DBFormatException { Map < String , String > ret = new HashMap < String , String > ( ) ; int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_MAP ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; for ( int i = ; i < size ; i ++ ) { String key = readString ( ) ; String val = readString ( ) ; ret . put ( key , val ) ; } return ret ; } public List < Long > readLongList ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_LONG_LIST ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; List < Long > ret = new ArrayList < Long > ( ) ; for ( int i = ; i < size ; i ++ ) { ret . add ( readLong ( ) ) ; } return ret ; } public Set < Long > readLongSet ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_LONG_SET ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; Set < Long > ret = new HashSet < Long > ( ) ; for ( int i = ; i < size ; i ++ ) { ret . add ( readLong ( ) ) ; } return ret ; } public List < Integer > readIntList ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_INT_LIST ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; List < Integer > ret = new ArrayList < Integer > ( ) ; for ( int i = ; i < size ; i ++ ) { ret . add ( readInt ( ) ) ; } return ret ; } public Set < Integer > readIntSet ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_INT_SET ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; Set < Integer > ret = new HashSet < Integer > ( ) ; for ( int i = ; i < size ; i ++ ) { ret . add ( readInt ( ) ) ; } return ret ; } public List < String > readStringList ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_STRING_LIST ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; List < String > ret = new ArrayList < String > ( ) ; for ( int i = ; i < size ; i ++ ) { ret . add ( readString ( ) ) ; } return ret ; } public Set < String > readStringSet ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_STRING_SET ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; Set < String > ret = new HashSet < String > ( ) ; for ( int i = ; i < size ; i ++ ) { ret . add ( readString ( ) ) ; } return ret ; } public byte [ ] readByteArray ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_BYTE_ARRAY ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; byte ret [ ] = new byte [ size ] ; try { fIn . readFully ( ret ) ; } catch ( IOException e ) { throw new DBFormatException ( "" + e . getMessage ( ) ) ; } return ret ; } public boolean readBoolean ( ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_BOOL_TRUE ) { return true ; } else if ( type == TYPE_BOOL_FALSE ) { return false ; } else { throw new DBFormatException ( "" + type ) ; } } public long readLong ( ) throws DBFormatException { int type = readRawType ( ) ; long ret = - ; if ( type < TYPE_INT_8 || type > TYPE_INT_64 ) { throw new DBFormatException ( "" + type ) ; } try { switch ( type ) { case TYPE_INT_8 : ret = fIn . readByte ( ) ; break ; case TYPE_INT_16 : ret = fIn . readShort ( ) ; break ; case TYPE_INT_32 : ret = fIn . readInt ( ) ; break ; case TYPE_INT_64 : ret = fIn . readLong ( ) ; break ; } } catch ( IOException e ) { throw new DBFormatException ( "" + e . getMessage ( ) ) ; } return ret ; } public int readInt ( ) throws DBFormatException { int type = readRawType ( ) ; int ret = - ; if ( type < TYPE_INT_8 || type > TYPE_INT_32 ) { throw new DBFormatException ( "" + type ) ; } try { switch ( type ) { case TYPE_INT_8 : ret = fIn . readByte ( ) ; break ; case TYPE_INT_16 : ret = fIn . readShort ( ) ; break ; case TYPE_INT_32 : ret = fIn . readInt ( ) ; break ; } } catch ( IOException e ) { throw new DBFormatException ( "" + e . getMessage ( ) ) ; } return ret ; } public void writeBoolean ( boolean v ) throws DBWriteException { writeRawType ( ( v ) ? TYPE_BOOL_TRUE : TYPE_BOOL_FALSE ) ; } public void writeRawType ( int type ) throws DBWriteException { try { fOut . write ( ( byte ) type ) ; } catch ( IOException e ) { throw new DBWriteException ( "" + e . getMessage ( ) ) ; } } public void writeIntList ( List < Integer > items ) throws DBWriteException { if ( items == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_INT_LIST ) ; writeInt ( items . size ( ) ) ; for ( Integer i : items ) { writeInt ( i . intValue ( ) ) ; } } } public void writeIntSet ( Set < Integer > items ) throws DBWriteException { if ( items == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_INT_SET ) ; writeInt ( items . size ( ) ) ; for ( Integer i : items ) { writeInt ( i . intValue ( ) ) ; } } } public void writeMapStringString ( Map < String , String > map ) throws DBWriteException { if ( map == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_MAP ) ; writeInt ( map . size ( ) ) ; for ( Entry < String , String > e : map . entrySet ( ) ) { writeString ( e . getKey ( ) ) ; writeString ( e . getValue ( ) ) ; } } } public void writeStringList ( List < String > items ) throws DBWriteException { if ( items == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_STRING_LIST ) ; writeInt ( items . size ( ) ) ; for ( int i = ; i < items . size ( ) ; i ++ ) { writeString ( items . get ( i ) ) ; } } } public void writeStringSet ( Set < String > items ) throws DBWriteException { if ( items == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_STRING_SET ) ; writeInt ( items . size ( ) ) ; for ( String s : items ) { writeString ( s ) ; } } } public void writeLongList ( List < Long > items ) throws DBWriteException { if ( items == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_LONG_LIST ) ; writeInt ( items . size ( ) ) ; for ( Long v : items ) { writeLong ( v . longValue ( ) ) ; } } } public void writeLongSet ( Set < Long > items ) throws DBWriteException { if ( items == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_LONG_SET ) ; writeInt ( items . size ( ) ) ; for ( Long v : items ) { writeLong ( v . longValue ( ) ) ; } } } public void writeSVDBLocation ( SVDBLocation loc ) throws DBWriteException { if ( loc == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_SVDB_LOCATION ) ; writeInt ( loc . getLine ( ) ) ; writeInt ( loc . getPos ( ) ) ; } } public void writeString ( String val ) throws DBWriteException { if ( val == null ) { writeRawType ( TYPE_NULL ) ; } else { try { writeRawType ( TYPE_STRING ) ; writeInt ( val . length ( ) ) ; fOut . writeBytes ( val ) ; } catch ( IOException e ) { throw new DBWriteException ( "" + e . getMessage ( ) ) ; } } } public void writeInt ( int val ) throws DBWriteException { try { if ( val < ) { if ( val >= - ) { fOut . write ( ( byte ) TYPE_INT_8 ) ; fOut . write ( ( byte ) val ) ; } else if ( val >= - ) { fOut . write ( ( byte ) TYPE_INT_16 ) ; fOut . writeShort ( ( short ) val ) ; } else { fOut . write ( ( byte ) TYPE_INT_32 ) ; fOut . writeInt ( val ) ; } } else { if ( val <= ) { fOut . write ( ( byte ) TYPE_INT_8 ) ; fOut . write ( ( byte ) val ) ; } else if ( val <= ) { fOut . write ( ( byte ) TYPE_INT_16 ) ; fOut . writeShort ( ( short ) val ) ; } else { fOut . write ( ( byte ) TYPE_INT_32 ) ; fOut . writeInt ( val ) ; } } } catch ( IOException e ) { throw new DBWriteException ( "" + e . getMessage ( ) ) ; } } public void writeLong ( long val ) throws DBWriteException { try { if ( val < ) { if ( val >= - ) { fOut . write ( TYPE_INT_8 ) ; fOut . writeByte ( ( byte ) val ) ; } else if ( val >= - ) { fOut . write ( TYPE_INT_16 ) ; fOut . writeShort ( ( short ) val ) ; } else if ( val >= - ) { fOut . write ( TYPE_INT_32 ) ; fOut . writeInt ( ( int ) val ) ; } else { fOut . write ( TYPE_INT_64 ) ; fOut . writeLong ( val ) ; } } else { if ( val <= ) { fOut . write ( TYPE_INT_8 ) ; fOut . writeByte ( ( byte ) val ) ; } else if ( val <= ) { fOut . write ( TYPE_INT_16 ) ; fOut . writeShort ( ( short ) val ) ; } else if ( val <= ) { fOut . write ( TYPE_INT_32 ) ; fOut . writeInt ( ( int ) val ) ; } else { fOut . write ( TYPE_INT_64 ) ; fOut . writeLong ( val ) ; } } } catch ( IOException e ) { throw new DBWriteException ( "" + e . getMessage ( ) ) ; } } public void writeByteArray ( byte [ ] data ) throws DBWriteException { if ( data == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_BYTE_ARRAY ) ; writeInt ( data . length ) ; try { fOut . write ( data ) ; } catch ( IOException e ) { throw new DBWriteException ( "" + e . getMessage ( ) ) ; } } } } package net . sf . sveditor . core . db . persistence ; import java . lang . reflect . Field ; import java . lang . reflect . Modifier ; import java . lang . reflect . ParameterizedType ; import java . lang . reflect . Type ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; import net . sf . sveditor . core . db . attr . SVDBParentAttr ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexCacheData ; import net . sf . sveditor . core . db . index . SVDBBaseIndexCacheData ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import net . sf . sveditor . core . db . refs . SVDBRefCacheEntry ; import org . objectweb . asm . ClassWriter ; import org . objectweb . asm . Label ; import org . objectweb . asm . MethodVisitor ; import org . objectweb . asm . Opcodes ; @ SuppressWarnings ( { "" , "" } ) public class JITPersistenceDelegateFactory implements Opcodes { private static JITPersistenceDelegateFactory fInstance ; private Class < JITPersistenceDelegateBase > fDelegateCls ; private String fTargetPkg ; private List < String > fTargetPkgList ; private Map < SVDBItemType , Class > fTypeClassMap ; private List < Class > fClassList ; private Set < Class > fClassSet ; private static final String fBaseClass = getClassName ( JITPersistenceDelegateBase . class ) ; private static final String fPersistenceDelegateParentClass = getClassName ( ISVDBPersistenceRWDelegateParent . class ) ; private static final String fChildItem = "" ; private static final String fDBFormatException = "" ; private static final String fDBWriteException = "" ; private static final String WRITE_ENUM_TYPE_SIG = "" ; private static final String READ_ENUM_TYPE_SIG = "" ; private static final String WRITE_STRING_SIG = "" ; private static final String READ_STRING_SIG = "" ; private static final String WRITE_LOCATION_SIG = "" ; private static final String READ_LOCATION_SIG = "" ; private static final String READ_LIST_SIG = "" ; private static final String WRITE_LIST_SIG = "" ; private static final String READ_SET_SIG = "" ; private static final String WRITE_SET_SIG = "" ; private static final String READ_ITEM_LIST_SIG = "" + fChildItem + "" ; private static final String WRITE_INT_SIG = "" ; private static final String READ_INT_SIG = "" ; private static final String WRITE_LONG_SIG = "" ; private static final String READ_LONG_SIG = "" ; private static final String WRITE_BOOL_SIG = "" ; private static final String READ_BOOL_SIG = "" ; private static final String WRITE_ITEM_SIG = "" ; private static final String READ_ITEM_SIG = "" + getClassName ( ISVDBChildItem . class ) + "" ; private static final String WRITE_MAP_SIG = "" ; private static final String READ_MAP_SIG = "" ; private boolean fDebugEn = false ; private int fLevel ; private static final int THIS_VAR = ; private static final int READ_PARENT_VAR = ; private static final int READ_OBJ_VAR = ; private static final int WRITE_OBJ_VAR = ; private class JITClassLoader extends ClassLoader { private byte fClassBytes [ ] ; private Class < JITPersistenceDelegateBase > fCls ; JITClassLoader ( ClassLoader parent , byte class_bytes [ ] ) { super ( parent ) ; fClassBytes = class_bytes ; } @ Override protected Class < ? > findClass ( String name ) throws ClassNotFoundException { if ( name . equals ( fTargetPkg + "" ) ) { if ( fCls == null ) { fCls = ( Class < JITPersistenceDelegateBase > ) defineClass ( name , fClassBytes , , fClassBytes . length ) ; } return fCls ; } return super . findClass ( name ) ; } } private JITPersistenceDelegateFactory ( ) { fTypeClassMap = new HashMap < SVDBItemType , Class > ( ) ; fClassList = new ArrayList < Class > ( ) ; fClassSet = new HashSet < Class > ( ) ; fTargetPkg = "" ; fTargetPkgList = new ArrayList < String > ( ) ; fTargetPkgList . add ( "" ) ; fTargetPkgList . add ( "" ) ; fTargetPkgList . add ( "" ) ; fClassList . add ( SVDBFile . class ) ; fClassList . add ( SVDBFileTree . class ) ; fClassList . add ( SVDBBaseIndexCacheData . class ) ; fClassList . add ( SVDBArgFileIndexCacheData . class ) ; fClassList . add ( SVDBDeclCacheItem . class ) ; fClassList . add ( SVDBRefCacheEntry . class ) ; fClassSet . addAll ( fClassList ) ; } private void build ( ) { ClassWriter cw = new ClassWriter ( ) ; final ClassLoader cl = getClass ( ) . getClassLoader ( ) ; for ( SVDBItemType t : SVDBItemType . values ( ) ) { Class cls = null ; for ( String pkg : fTargetPkgList ) { try { cls = cl . loadClass ( pkg + "" + t . name ( ) ) ; } catch ( Exception e ) { } if ( cls != null ) { break ; } } if ( cls != null ) { fTypeClassMap . put ( t , cls ) ; } else { System . out . println ( "" + t . name ( ) ) ; } } long start = System . currentTimeMillis ( ) ; build_boilerplate ( cw ) ; for ( SVDBItemType t : fTypeClassMap . keySet ( ) ) { Class cls = fTypeClassMap . get ( t ) ; buildItemAccessor ( cw , t , cls ) ; } for ( Class c : fClassList ) { buildObjectAccessor ( cw , c ) ; } cw . visitEnd ( ) ; JITClassLoader jit_cl = new JITClassLoader ( cl , cw . toByteArray ( ) ) ; try { fDelegateCls = ( Class < JITPersistenceDelegateBase > ) jit_cl . loadClass ( fTargetPkg + "" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } long end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( end - start ) ) ; System . out . println ( "" + cw . toByteArray ( ) . length ) ; } private void build_boilerplate ( ClassWriter cw ) { String classname = "" ; String full_classname = transform_cls ( fTargetPkg ) + "" + classname ; cw . visit ( Opcodes . V1_5 , ACC_PROTECTED + ACC_PUBLIC + ACC_SUPER , full_classname , null , fBaseClass , null ) ; cw . visitSource ( classname + "" , null ) ; MethodVisitor mv ; mv = cw . visitMethod ( ACC_PUBLIC , "" , "" , null , null ) ; mv . visitCode ( ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , "" ) ; mv . visitInsn ( RETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; buildItemDispatchMethods ( cw ) ; buildObjectDispatchMethods ( cw ) ; } private void buildItemDispatchMethods ( ClassWriter cw ) { String classname = "" ; String full_classname = transform_cls ( fTargetPkg ) + "" + classname ; Label labels [ ] = new Label [ SVDBItemType . values ( ) . length ] ; int indexes [ ] = new int [ SVDBItemType . values ( ) . length ] ; Label dflt , endcase ; for ( int i = ; i < SVDBItemType . values ( ) . length ; i ++ ) { indexes [ i ] = i ; } MethodVisitor mv = cw . visitMethod ( ACC_PUBLIC , "" , "" + getClassName ( ISVDBItemBase . class ) + "" , null , new String [ ] { fDBWriteException } ) ; for ( int i = ; i < SVDBItemType . values ( ) . length ; i ++ ) { labels [ i ] = new Label ( ) ; } dflt = new Label ( ) ; endcase = new Label ( ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitMethodInsn ( INVOKEINTERFACE , getClassName ( ISVDBItemBase . class ) , "" , "" + getClassName ( SVDBItemType . class ) + "" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , getClassName ( SVDBItemType . class ) , "" , "" ) ; mv . visitLookupSwitchInsn ( dflt , indexes , labels ) ; for ( SVDBItemType t : SVDBItemType . values ( ) ) { Class c = fTypeClassMap . get ( t ) ; mv . visitLabel ( labels [ t . ordinal ( ) ] ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitTypeInsn ( CHECKCAST , getClassName ( c ) ) ; mv . visitMethodInsn ( INVOKESPECIAL , full_classname , "" + t . name ( ) , "" + getClassName ( c ) + "" ) ; mv . visitJumpInsn ( GOTO , endcase ) ; } mv . visitLabel ( dflt ) ; mv . visitLabel ( endcase ) ; mv . visitInsn ( RETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; mv = cw . visitMethod ( ACC_PUBLIC , "" , "" + getClassName ( SVDBItemType . class ) + "" + getClassName ( ISVDBChildItem . class ) + "" + getClassName ( ISVDBItemBase . class ) + "" , null , new String [ ] { fDBWriteException } ) ; for ( int i = ; i < SVDBItemType . values ( ) . length ; i ++ ) { labels [ i ] = new Label ( ) ; } dflt = new Label ( ) ; endcase = new Label ( ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , getClassName ( SVDBItemType . class ) , "" , "" ) ; mv . visitLookupSwitchInsn ( dflt , indexes , labels ) ; for ( SVDBItemType t : SVDBItemType . values ( ) ) { Class c = fTypeClassMap . get ( t ) ; mv . visitLabel ( labels [ t . ordinal ( ) ] ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitMethodInsn ( INVOKESPECIAL , full_classname , "" + t . name ( ) , "" + getClassName ( ISVDBChildItem . class ) + "" + "" + getClassName ( c ) + "" ) ; mv . visitJumpInsn ( GOTO , endcase ) ; } mv . visitLabel ( dflt ) ; mv . visitInsn ( ACONST_NULL ) ; mv . visitLabel ( endcase ) ; mv . visitInsn ( ARETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; } private void buildObjectDispatchMethods ( ClassWriter cw ) { String classname = "" ; String full_classname = transform_cls ( fTargetPkg ) + "" + classname ; int idx ; Label labels [ ] = new Label [ fClassList . size ( ) ] ; int indexes [ ] = new int [ fClassList . size ( ) ] ; Label dflt , endcase ; for ( int i = ; i < fClassList . size ( ) ; i ++ ) { indexes [ i ] = i ; } MethodVisitor mv = cw . visitMethod ( ACC_PUBLIC , "" , "" + getClassName ( Class . class ) + "" + "" + getClassName ( Object . class ) + "" , null , new String [ ] { fDBWriteException } ) ; for ( int i = ; i < fClassList . size ( ) ; i ++ ) { labels [ i ] = new Label ( ) ; } dflt = new Label ( ) ; endcase = new Label ( ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + getClassName ( List . class ) + "" ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitMethodInsn ( INVOKEINTERFACE , getClassName ( List . class ) , "" , "" + getClassName ( Object . class ) + "" ) ; mv . visitLookupSwitchInsn ( dflt , indexes , labels ) ; idx = ; for ( Class c : fClassList ) { mv . visitLabel ( labels [ idx ] ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitTypeInsn ( CHECKCAST , getClassName ( c ) ) ; mv . visitMethodInsn ( INVOKESPECIAL , full_classname , "" + getClassLeafName ( c ) , "" + getClassName ( c ) + "" ) ; mv . visitJumpInsn ( GOTO , endcase ) ; idx ++ ; } mv . visitLabel ( dflt ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitMethodInsn ( INVOKESPECIAL , full_classname , "" , "" + getClassName ( Object . class ) + "" ) ; mv . visitLabel ( endcase ) ; mv . visitInsn ( RETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; mv = cw . visitMethod ( ACC_PUBLIC , "" , "" + getClassName ( ISVDBChildItem . class ) + "" + "" + getClassName ( Class . class ) + "" + "" + getClassName ( Object . class ) + "" , null , new String [ ] { fDBWriteException } ) ; for ( int i = ; i < fClassList . size ( ) ; i ++ ) { labels [ i ] = new Label ( ) ; } dflt = new Label ( ) ; endcase = new Label ( ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + getClassName ( List . class ) + "" ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitMethodInsn ( INVOKEINTERFACE , getClassName ( List . class ) , "" , "" + getClassName ( Object . class ) + "" ) ; mv . visitLookupSwitchInsn ( dflt , indexes , labels ) ; idx = ; for ( Class c : fClassList ) { mv . visitLabel ( labels [ idx ] ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitTypeInsn ( CHECKCAST , getClassName ( c ) ) ; mv . visitMethodInsn ( INVOKESPECIAL , full_classname , "" + getClassLeafName ( c ) , "" + getClassName ( ISVDBChildItem . class ) + "" + "" + getClassName ( c ) + "" ) ; mv . visitJumpInsn ( GOTO , endcase ) ; idx ++ ; } mv . visitLabel ( dflt ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , ) ; mv . visitMethodInsn ( INVOKESPECIAL , full_classname , "" , "" + getClassName ( Object . class ) + "" ) ; mv . visitLabel ( endcase ) ; mv . visitInsn ( RETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; } private void buildObjectAccessor ( ClassWriter cw , Class cls ) { MethodVisitor mv ; if ( fDebugEn ) { debug ( "" + cls . getName ( ) ) ; } String tgt_clsname = getClassName ( cls ) ; String cls_name = getClassLeafName ( cls ) ; mv = cw . visitMethod ( ACC_PRIVATE , "" + cls_name , "" + fChildItem + "" + "" + tgt_clsname + "" , null , new String [ ] { fDBFormatException } ) ; mv . visitCode ( ) ; visit ( false , tgt_clsname , mv , cls ) ; mv . visitInsn ( RETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; mv = cw . visitMethod ( ACC_PRIVATE , "" + cls_name , "" + tgt_clsname + "" , null , new String [ ] { fDBWriteException } ) ; mv . visitCode ( ) ; visit ( true , tgt_clsname , mv , cls ) ; mv . visitInsn ( RETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; if ( fDebugEn ) { debug ( "" + cls . getName ( ) ) ; } } private void buildItemAccessor ( ClassWriter cw , SVDBItemType t , Class cls ) { MethodVisitor mv ; if ( fDebugEn ) { debug ( "" + t . name ( ) + "" + cls . getName ( ) ) ; } String item_name = t . name ( ) ; String tgt_clsname = getClassName ( cls ) ; mv = cw . visitMethod ( ACC_PRIVATE , "" + item_name , "" + fChildItem + "" + tgt_clsname + "" , null , new String [ ] { fDBFormatException } ) ; mv . visitCode ( ) ; mv . visitTypeInsn ( NEW , tgt_clsname ) ; mv . visitInsn ( DUP ) ; mv . visitMethodInsn ( INVOKESPECIAL , tgt_clsname , "" , "" ) ; mv . visitVarInsn ( ASTORE , READ_OBJ_VAR ) ; visit ( false , tgt_clsname , mv , cls ) ; mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitInsn ( ARETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; mv = cw . visitMethod ( ACC_PRIVATE , "" + item_name , "" + tgt_clsname + "" , null , new String [ ] { fDBWriteException } ) ; mv . visitCode ( ) ; visit ( true , tgt_clsname , mv , cls ) ; mv . visitInsn ( RETURN ) ; mv . visitMaxs ( , ) ; mv . visitEnd ( ) ; if ( fDebugEn ) { debug ( "" + t + "" + cls . getName ( ) ) ; } } protected void visit ( boolean write , String tgt_classname , MethodVisitor mv , Class cls ) { if ( fDebugEn ) { debug ( "" + ( ++ fLevel ) + "" + cls . getName ( ) ) ; } if ( cls . getSuperclass ( ) != null && cls . getSuperclass ( ) != Object . class ) { String tgt_super_classname = getClassName ( cls . getSuperclass ( ) ) ; visit ( write , tgt_super_classname , mv , cls . getSuperclass ( ) ) ; } Field fields [ ] = cls . getDeclaredFields ( ) ; for ( Field f : fields ) { Class field_class = f . getType ( ) ; String field_classname = getClassName ( field_class ) ; if ( ! Modifier . isStatic ( f . getModifiers ( ) ) ) { if ( f . getAnnotation ( SVDBParentAttr . class ) != null ) { if ( ! write ) { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , READ_PARENT_VAR ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } continue ; } if ( f . getAnnotation ( SVDBDoNotSaveAttr . class ) != null ) { continue ; } if ( ( f . getModifiers ( ) & Modifier . PUBLIC ) == ) { throw new RuntimeException ( "" + tgt_classname + "" + f . getName ( ) ) ; } try { if ( Enum . class . isAssignableFrom ( field_class ) ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" + field_class . getName ( ) ) ; } if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + fPersistenceDelegateParentClass + "" ) ; mv . visitLdcInsn ( org . objectweb . asm . Type . getType ( field_class ) ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; mv . visitMethodInsn ( INVOKEINTERFACE , fPersistenceDelegateParentClass , "" , WRITE_ENUM_TYPE_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + fPersistenceDelegateParentClass + "" ) ; mv . visitLdcInsn ( org . objectweb . asm . Type . getType ( field_class ) ) ; mv . visitMethodInsn ( INVOKEINTERFACE , fPersistenceDelegateParentClass , "" , READ_ENUM_TYPE_SIG ) ; mv . visitTypeInsn ( CHECKCAST , field_classname ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } } else if ( List . class . isAssignableFrom ( field_class ) ) { Type t = f . getGenericType ( ) ; if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; Type args [ ] = pt . getActualTypeArguments ( ) ; String readMethod = null , writeMethod = null ; boolean useStdRW = true ; if ( args . length != ) { throw new DBFormatException ( "" + args . length + "" ) ; } Class c = ( Class ) args [ ] ; if ( c == String . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } writeMethod = "" ; readMethod = "" ; } else if ( c == Integer . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } writeMethod = "" ; readMethod = "" ; } else if ( c == Long . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } writeMethod = "" ; readMethod = "" ; } else if ( ISVDBItemBase . class . isAssignableFrom ( c ) ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } useStdRW = false ; if ( ! write ) { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + fPersistenceDelegateParentClass + "" ) ; mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitMethodInsn ( INVOKEINTERFACE , fPersistenceDelegateParentClass , "" , READ_ITEM_LIST_SIG ) ; mv . visitTypeInsn ( CHECKCAST , field_classname ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } else { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + fPersistenceDelegateParentClass + "" ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; mv . visitMethodInsn ( INVOKEINTERFACE , fPersistenceDelegateParentClass , "" , WRITE_LIST_SIG ) ; } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" + ( ( Class ) args [ ] ) . getName ( ) ) ; } if ( useStdRW ) { if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , writeMethod , WRITE_LIST_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , readMethod , READ_LIST_SIG ) ; mv . visitTypeInsn ( CHECKCAST , field_classname ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" ) ; } } else if ( Set . class . isAssignableFrom ( field_class ) ) { Type t = f . getGenericType ( ) ; if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; Type args [ ] = pt . getActualTypeArguments ( ) ; String readMethod = null , writeMethod = null ; boolean useStdRW = true ; if ( args . length != ) { throw new DBFormatException ( "" + args . length + "" ) ; } Class c = ( Class ) args [ ] ; if ( c == String . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } writeMethod = "" ; readMethod = "" ; } else if ( c == Integer . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } writeMethod = "" ; readMethod = "" ; } else if ( c == Long . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } writeMethod = "" ; readMethod = "" ; } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" + ( ( Class ) args [ ] ) . getName ( ) ) ; } if ( useStdRW ) { if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , writeMethod , WRITE_SET_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , readMethod , READ_SET_SIG ) ; mv . visitTypeInsn ( CHECKCAST , field_classname ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" ) ; } } else if ( Map . class . isAssignableFrom ( field_class ) ) { boolean local_access = true ; Type t = f . getGenericType ( ) ; if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; Type args [ ] = pt . getActualTypeArguments ( ) ; Class key_c = null ; Class val_c = null ; Class elem_c = null ; String readMethod = null , writeMethod = null ; String readSig = READ_MAP_SIG , writeSig = WRITE_MAP_SIG ; if ( args [ ] instanceof Class ) { key_c = ( Class ) args [ ] ; } else { throw new DBFormatException ( "" + "" + f . getName ( ) ) ; } if ( args [ ] instanceof Class ) { val_c = ( Class ) args [ ] ; } else if ( args [ ] instanceof ParameterizedType ) { val_c = ( Class ) ( ( ParameterizedType ) args [ ] ) . getRawType ( ) ; } else { throw new DBFormatException ( "" + "" + f . getName ( ) ) ; } if ( key_c == String . class && val_c == String . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } writeMethod = "" ; readMethod = "" ; } else if ( key_c == String . class && val_c . isAssignableFrom ( List . class ) ) { elem_c = ( Class ) ( ( ParameterizedType ) args [ ] ) . getActualTypeArguments ( ) [ ] ; if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } local_access = false ; writeMethod = "" ; writeSig = "" + getClassName ( Map . class ) + "" + "" + getClassName ( Class . class ) + "" ; writeSig = "" + getClassName ( Map . class ) + "" + "" + getClassName ( Class . class ) + "" ; readMethod = "" ; readSig = "" + getClassName ( Class . class ) + "" + "" + getClassName ( Map . class ) + "" ; } else if ( key_c == String . class ) { elem_c = val_c ; if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } local_access = false ; writeMethod = "" ; writeSig = "" + getClassName ( Map . class ) + "" + "" + getClassName ( Class . class ) + "" ; writeSig = "" + getClassName ( Map . class ) + "" + "" + getClassName ( Class . class ) + "" ; readMethod = "" ; readSig = "" + getClassName ( Class . class ) + "" + "" + getClassName ( Map . class ) + "" ; } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" + key_c . getName ( ) + "" + val_c . getName ( ) + "" + cls . getName ( ) ) ; } if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; if ( ! local_access ) { mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + fPersistenceDelegateParentClass + "" ) ; } mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; if ( elem_c != null ) { mv . visitLdcInsn ( org . objectweb . asm . Type . getType ( elem_c ) ) ; } if ( local_access ) { mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , writeMethod , writeSig ) ; } else { mv . visitMethodInsn ( INVOKEINTERFACE , fPersistenceDelegateParentClass , writeMethod , writeSig ) ; } } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; if ( ! local_access ) { mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + fPersistenceDelegateParentClass + "" ) ; } if ( elem_c != null ) { mv . visitLdcInsn ( org . objectweb . asm . Type . getType ( elem_c ) ) ; } if ( local_access ) { mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , readMethod , readSig ) ; } else { mv . visitMethodInsn ( INVOKEINTERFACE , fPersistenceDelegateParentClass , readMethod , readSig ) ; } mv . visitTypeInsn ( CHECKCAST , field_classname ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" ) ; } } else if ( field_class == String . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , WRITE_STRING_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , READ_STRING_SIG ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } } else if ( field_class == int . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , WRITE_INT_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , READ_INT_SIG ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" ) ; } } else if ( field_class == long . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , WRITE_LONG_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , READ_LONG_SIG ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" ) ; } } else if ( field_class == boolean . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , WRITE_BOOL_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , READ_BOOL_SIG ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" ) ; } } else if ( SVDBLocation . class == field_class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , WRITE_LOCATION_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitMethodInsn ( INVOKESPECIAL , fBaseClass , "" , READ_LOCATION_SIG ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } } else if ( ISVDBItemBase . class . isAssignableFrom ( field_class ) ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + fPersistenceDelegateParentClass + "" ) ; mv . visitVarInsn ( ALOAD , WRITE_OBJ_VAR ) ; mv . visitFieldInsn ( GETFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; mv . visitMethodInsn ( INVOKEINTERFACE , fPersistenceDelegateParentClass , "" , WRITE_ITEM_SIG ) ; } else { mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitVarInsn ( ALOAD , THIS_VAR ) ; mv . visitFieldInsn ( GETFIELD , fBaseClass , "" , "" + fPersistenceDelegateParentClass + "" ) ; mv . visitVarInsn ( ALOAD , READ_OBJ_VAR ) ; mv . visitMethodInsn ( INVOKEINTERFACE , fPersistenceDelegateParentClass , "" , READ_ITEM_SIG ) ; mv . visitTypeInsn ( CHECKCAST , field_classname ) ; mv . visitFieldInsn ( PUTFIELD , tgt_classname , f . getName ( ) , "" + field_classname + "" ) ; } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" + field_class . getName ( ) ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } if ( fDebugEn ) { debug ( "" + ( fLevel -- ) + "" + cls . getName ( ) ) ; } } private static String getClassName ( Class cls ) { return transform_cls ( cls . getName ( ) ) ; } private static String getClassLeafName ( Class cls ) { String ret = cls . getName ( ) ; int idx = ret . lastIndexOf ( '' ) ; if ( idx != - ) { ret = ret . substring ( idx + ) ; } return ret ; } private static String transform_cls ( String clsname ) { return clsname . replace ( '' , '' ) ; } public ISVDBPersistenceRWDelegate newDelegate ( ) { try { JITPersistenceDelegateBase ret = fDelegateCls . newInstance ( ) ; ret . setSupportedClasses ( fClassList ) ; ret . init ( fTypeClassMap . keySet ( ) , fClassSet ) ; return ret ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; } return null ; } public static synchronized JITPersistenceDelegateFactory instance ( ) { if ( fInstance == null ) { fInstance = new JITPersistenceDelegateFactory ( ) ; fInstance . build ( ) ; } return fInstance ; } private void debug ( String msg ) { if ( fDebugEn ) { System . out . println ( msg ) ; } } } package net . sf . sveditor . core . db . persistence ; import java . io . DataInput ; import java . io . DataOutput ; import java . lang . reflect . Field ; import java . lang . reflect . Method ; import java . lang . reflect . Modifier ; import java . lang . reflect . ParameterizedType ; import java . lang . reflect . Type ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; import net . sf . sveditor . core . db . attr . SVDBParentAttr ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; @ SuppressWarnings ( { "" , "" } ) public class SVDBDefaultPersistenceRW extends SVDBPersistenceRWDelegateBase { private LogHandle fLog ; private boolean fDebugEn = false ; private int fLevel ; private static Map < Class , Map < Integer , Enum > > fIntToEnumMap ; private static Map < Class , Map < Enum , Integer > > fEnumToIntMap ; private static Map < SVDBItemType , Class > fClassMap ; static { fIntToEnumMap = new HashMap < Class , Map < Integer , Enum > > ( ) ; fEnumToIntMap = new HashMap < Class , Map < Enum , Integer > > ( ) ; } public SVDBDefaultPersistenceRW ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } public Set < Class > getSupportedObjects ( ) { return null ; } public Set < Class > getSupportedEnumTypes ( ) { return null ; } public Set < SVDBItemType > getSupportedItemTypes ( ) { return null ; } public void setDebugEn ( boolean en ) { fDebugEn = en ; } public void init ( ISVDBPersistenceRWDelegateParent parent , DataInput in , DataOutput out ) { super . init ( parent , in , out ) ; fLevel = ; synchronized ( getClass ( ) ) { if ( fClassMap == null ) { fClassMap = new HashMap < SVDBItemType , Class > ( ) ; ClassLoader cl = getClass ( ) . getClassLoader ( ) ; for ( SVDBItemType v : SVDBItemType . values ( ) ) { String key = "" + v . name ( ) ; Class cls = null ; for ( String pref : new String [ ] { "" , "" , "" } ) { try { cls = cl . loadClass ( pref + key ) ; } catch ( Exception e ) { } } if ( cls == null ) { System . out . println ( "" + key ) ; } else { fClassMap . put ( v , cls ) ; } } } } } public void writeObject ( Class cls , Object target ) throws DBWriteException { try { accessObject ( true , null , cls , target ) ; } catch ( DBFormatException e ) { } } public void readObject ( ISVDBChildItem parent , Class cls , Object target ) throws DBFormatException { try { accessObject ( false , parent , cls , target ) ; } catch ( DBWriteException e ) { } } protected void accessObject ( boolean write , ISVDBChildItem parent , Class cls , Object target ) throws DBWriteException , DBFormatException { if ( fDebugEn ) { debug ( "" + ( ++ fLevel ) + "" + cls . getName ( ) ) ; } if ( cls . getSuperclass ( ) != null && cls . getSuperclass ( ) != Object . class ) { accessObject ( write , parent , cls . getSuperclass ( ) , target ) ; } Field fields [ ] = cls . getDeclaredFields ( ) ; for ( Field f : fields ) { f . setAccessible ( true ) ; if ( ! Modifier . isStatic ( f . getModifiers ( ) ) ) { if ( f . getAnnotation ( SVDBParentAttr . class ) != null ) { if ( ! write ) { try { f . set ( target , parent ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } } continue ; } if ( f . getAnnotation ( SVDBDoNotSaveAttr . class ) != null ) { continue ; } try { Class field_class = f . getType ( ) ; Object field_value = null ; if ( write ) { field_value = f . get ( target ) ; } if ( Enum . class . isAssignableFrom ( field_class ) ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" + field_class . getName ( ) ) ; } if ( write ) { fParent . writeEnumType ( field_class , ( Enum ) field_value ) ; } else { f . set ( target , fParent . readEnumType ( field_class ) ) ; } } else if ( List . class . isAssignableFrom ( field_class ) ) { Type t = f . getGenericType ( ) ; if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; Type args [ ] = pt . getActualTypeArguments ( ) ; if ( args . length != ) { throw new DBFormatException ( "" + args . length + "" ) ; } Class c = ( Class ) args [ ] ; if ( c == String . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeStringList ( ( List < String > ) field_value ) ; } else { Object o = readStringList ( ) ; f . set ( target , o ) ; } } else if ( c == Integer . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeIntList ( ( List < Integer > ) field_value ) ; } else { f . set ( target , readIntList ( ) ) ; } } else if ( c == Long . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeLongList ( ( List < Long > ) field_value ) ; } else { f . set ( target , readLongList ( ) ) ; } } else if ( ISVDBItemBase . class . isAssignableFrom ( c ) ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { fParent . writeItemList ( ( List < ISVDBItemBase > ) field_value ) ; } else { if ( target instanceof ISVDBChildItem ) { f . set ( target , fParent . readItemList ( ( ISVDBChildItem ) target ) ) ; } else { f . set ( target , fParent . readItemList ( null ) ) ; } } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" + ( ( Class ) args [ ] ) . getName ( ) ) ; } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" ) ; } } else if ( Map . class . isAssignableFrom ( field_class ) ) { Type t = f . getGenericType ( ) ; if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; Type args [ ] = pt . getActualTypeArguments ( ) ; Class key_c = null ; Class val_c = null ; if ( args [ ] instanceof Class ) { key_c = ( Class ) args [ ] ; } else { throw new DBFormatException ( "" + "" + f . getName ( ) ) ; } if ( args [ ] instanceof Class ) { val_c = ( Class ) args [ ] ; } else if ( args [ ] instanceof ParameterizedType ) { val_c = ( Class ) ( ( ParameterizedType ) args [ ] ) . getRawType ( ) ; } else { throw new DBFormatException ( "" + "" + f . getName ( ) ) ; } if ( key_c == String . class && val_c == String . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeMapStringString ( ( Map < String , String > ) field_value ) ; } else { f . set ( target , readMapStringString ( ) ) ; } } else if ( key_c == String . class && val_c . isAssignableFrom ( List . class ) ) { Class c = ( Class ) ( ( ParameterizedType ) args [ ] ) . getActualTypeArguments ( ) [ ] ; if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { fParent . writeMapStringList ( ( Map < String , List > ) field_value , c ) ; } else { f . set ( target , fParent . readMapStringList ( c ) ) ; } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" + key_c . getName ( ) + "" + val_c . getName ( ) + "" + cls . getName ( ) ) ; } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } throw new DBFormatException ( "" ) ; } } else if ( field_class == String . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeString ( ( String ) field_value ) ; } else { f . set ( target , readString ( ) ) ; } } else if ( field_class == int . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeInt ( ( Integer ) field_value ) ; } else { f . setInt ( target , readInt ( ) ) ; } } else if ( field_class == long . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeLong ( ( Long ) field_value ) ; } else { f . setLong ( target , readLong ( ) ) ; } } else if ( field_class == boolean . class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeBoolean ( ( Boolean ) field_value ) ; } else { f . setBoolean ( target , readBoolean ( ) ) ; } } else if ( SVDBLocation . class == field_class ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { writeSVDBLocation ( ( SVDBLocation ) field_value ) ; } else { f . set ( target , readSVDBLocation ( ) ) ; } } else if ( ISVDBItemBase . class . isAssignableFrom ( field_class ) ) { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" ) ; } if ( write ) { fParent . writeSVDBItem ( ( ISVDBItemBase ) field_value ) ; } else { f . set ( target , fParent . readSVDBItem ( parent ) ) ; } } else { if ( fDebugEn ) { debug ( "" + fLevel + "" + f . getName ( ) + "" + field_class . getName ( ) ) ; } throw new DBFormatException ( "" + field_class . getName ( ) ) ; } } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; throw new DBFormatException ( "" + e . getMessage ( ) ) ; } } } if ( fDebugEn ) { debug ( "" + ( fLevel -- ) + "" + cls . getName ( ) ) ; } } public void writeEnumType ( Class enum_type , Enum value ) throws DBWriteException { writeRawType ( TYPE_ENUM ) ; writeInt ( value . ordinal ( ) ) ; } public void writeSVDBItem ( ISVDBItemBase item ) throws DBWriteException { try { accessObject ( true , null , item . getClass ( ) , item ) ; } catch ( DBFormatException e ) { } } public Enum readEnumType ( Class enum_type ) throws DBFormatException { Enum ret ; int val ; synchronized ( fIntToEnumMap ) { if ( ! fIntToEnumMap . containsKey ( enum_type ) ) { Enum vals [ ] = null ; try { Method m = null ; m = enum_type . getMethod ( "" ) ; vals = ( Enum [ ] ) m . invoke ( null ) ; } catch ( Exception ex ) { throw new DBFormatException ( "" + enum_type . getName ( ) + "" ) ; } Map < Integer , Enum > em = new HashMap < Integer , Enum > ( ) ; for ( int i = ; i < vals . length ; i ++ ) { em . put ( i , vals [ i ] ) ; } fIntToEnumMap . put ( enum_type , em ) ; } Map < Integer , Enum > enum_vals = fIntToEnumMap . get ( enum_type ) ; val = readInt ( ) ; ret = enum_vals . get ( val ) ; } if ( ret == null ) { throw new DBFormatException ( "" + val + "" + enum_type . getName ( ) ) ; } return ret ; } public ISVDBItemBase readSVDBItem ( SVDBItemType item_type , ISVDBChildItem parent ) throws DBFormatException { ISVDBItemBase ret = null ; if ( fClassMap . containsKey ( item_type ) ) { Class cls = fClassMap . get ( item_type ) ; Object obj = null ; try { obj = cls . newInstance ( ) ; } catch ( Exception e ) { throw new DBFormatException ( "" + item_type + "" + e . getMessage ( ) ) ; } try { accessObject ( false , parent , cls , obj ) ; } catch ( DBWriteException e ) { } ret = ( ISVDBItemBase ) obj ; } else { throw new DBFormatException ( "" + item_type ) ; } return ret ; } private void debug ( String msg ) { if ( fDebugEn ) { fLog . debug ( msg ) ; } } } package net . sf . sveditor . core . db . persistence ; public class DBWriteException extends Exception { private static final long serialVersionUID = ; public DBWriteException ( String msg ) { super ( msg ) ; } } package net . sf . sveditor . core . db . persistence ; public interface IDBPersistenceTypes { int TYPE_INT_8 = ; int TYPE_INT_16 = ; int TYPE_INT_32 = ; int TYPE_INT_64 = ; int TYPE_INT_LIST = ; int TYPE_STRING = ; int TYPE_STRING_LIST = ; int TYPE_NULL = ; int TYPE_ITEM = ; int TYPE_ITEM_LIST = ; int TYPE_BOOL_FALSE = ; int TYPE_BOOL_TRUE = ; int TYPE_ENUM = ; int TYPE_BYTE_ARRAY = ; int TYPE_SVDB_LOCATION = ; int TYPE_MAP = ; int TYPE_LONG_LIST = ; int TYPE_OBJECT_LIST = ; int TYPE_STRING_SET = ; int TYPE_INT_SET = ; int TYPE_LONG_SET = ; int TYPE_MAX = ; } package net . sf . sveditor . core . db . persistence ; import java . io . DataInput ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public interface IDBReader { void init ( DataInput in ) ; void setDebugEn ( boolean en ) ; int readInt ( ) throws DBFormatException ; long readLong ( ) throws DBFormatException ; void readObject ( ISVDBChildItem parent , Class cls , Object obj ) throws DBFormatException ; byte [ ] readByteArray ( ) throws DBFormatException ; String readString ( ) throws DBFormatException ; SVDBItemType readItemType ( ) throws DBFormatException ; @ SuppressWarnings ( "" ) Enum readEnumType ( Class enum_type ) throws DBFormatException ; @ SuppressWarnings ( "" ) List readItemList ( ISVDBChildItem parent ) throws DBFormatException ; ISVDBItemBase readSVDBItem ( ISVDBChildItem parent ) throws DBFormatException ; List < String > readStringList ( ) throws DBFormatException ; List < Integer > readIntList ( ) throws DBFormatException ; List < Long > readLongList ( ) throws DBFormatException ; } package net . sf . sveditor . core . db . persistence ; import java . io . DataInput ; import java . io . DataOutput ; 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 net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; @ SuppressWarnings ( { "" , "" } ) public class SVDBDelegatingPersistenceRW extends SVDBPersistenceRWBase implements IDBReader , IDBWriter , ISVDBPersistenceRWDelegateParent { private Map < Class , ISVDBPersistenceRWDelegate > fObjectDelegateMap ; private Map < SVDBItemType , ISVDBPersistenceRWDelegate > fSVDBItemDelegateMap ; private Map < Class , ISVDBPersistenceRWDelegate > fEnumDelegateMap ; private List < ISVDBPersistenceRWDelegate > fDelegateList ; private ISVDBPersistenceRWDelegate fDefaultDelegate ; public SVDBDelegatingPersistenceRW ( ) { fObjectDelegateMap = new HashMap < Class , ISVDBPersistenceRWDelegate > ( ) ; fEnumDelegateMap = new HashMap < Class , ISVDBPersistenceRWDelegate > ( ) ; fSVDBItemDelegateMap = new HashMap < SVDBItemType , ISVDBPersistenceRWDelegate > ( ) ; fDelegateList = new ArrayList < ISVDBPersistenceRWDelegate > ( ) ; fDefaultDelegate = new SVDBDefaultPersistenceRW ( ) ; fDefaultDelegate . init ( this , fIn , fOut ) ; } @ Override public void init ( DataInput in ) { super . init ( in ) ; for ( ISVDBPersistenceRWDelegate d : fDelegateList ) { d . init ( this , in , null ) ; } fDefaultDelegate . init ( this , in , null ) ; } @ Override public void init ( DataOutput out ) { super . init ( out ) ; for ( ISVDBPersistenceRWDelegate d : fDelegateList ) { d . init ( this , null , out ) ; } fDefaultDelegate . init ( this , null , out ) ; } public void addDelegate ( ISVDBPersistenceRWDelegate d ) { fDelegateList . add ( d ) ; d . init ( this , fIn , fOut ) ; Set < Class > supported_classes = d . getSupportedObjects ( ) ; if ( supported_classes != null ) { for ( Class cls : supported_classes ) { fObjectDelegateMap . put ( cls , d ) ; } } Set < Class > supported_enums = d . getSupportedEnumTypes ( ) ; if ( supported_enums != null ) { for ( Class cls : supported_enums ) { fEnumDelegateMap . put ( cls , d ) ; } } Set < SVDBItemType > supported_types = d . getSupportedItemTypes ( ) ; if ( supported_types != null ) { for ( SVDBItemType type : supported_types ) { fSVDBItemDelegateMap . put ( type , d ) ; } } } public Map < String , List > readMapStringList ( Class val_c ) throws DBFormatException { Map < String , List > ret = new HashMap < String , List > ( ) ; int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_MAP ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; for ( int i = ; i < size ; i ++ ) { String key = readString ( ) ; ret . put ( key , readObjectList ( null , val_c ) ) ; } return ret ; } public Map < String , Object > readMapStringObject ( Class val_c ) throws DBFormatException { Map < String , Object > ret = new HashMap < String , Object > ( ) ; int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_MAP ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; for ( int i = ; i < size ; i ++ ) { String key = readString ( ) ; Object val = null ; try { val = val_c . newInstance ( ) ; } catch ( InstantiationException e ) { throw new DBFormatException ( "" + val_c . getName ( ) ) ; } catch ( IllegalAccessException e ) { throw new DBFormatException ( "" + val_c . getName ( ) ) ; } readObject ( null , val_c , val ) ; ret . put ( key , val ) ; } return ret ; } public void writeMapStringList ( Map < String , List > map , Class list_c ) throws DBWriteException , DBFormatException { if ( map == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_MAP ) ; writeInt ( map . size ( ) ) ; for ( Entry < String , List > e : map . entrySet ( ) ) { writeString ( e . getKey ( ) ) ; writeObjectList ( e . getValue ( ) , list_c ) ; } } } public void writeMapStringObject ( Map < String , Object > map , Class obj_c ) throws DBWriteException , DBFormatException { if ( map == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_MAP ) ; writeInt ( map . size ( ) ) ; for ( Entry < String , Object > e : map . entrySet ( ) ) { writeString ( e . getKey ( ) ) ; writeObject ( obj_c , e . getValue ( ) ) ; } } } public void writeObject ( Class cls , Object obj ) throws DBWriteException { ISVDBPersistenceRWDelegate d = fObjectDelegateMap . get ( cls ) ; if ( d != null ) { d . writeObject ( cls , obj ) ; } else { fDefaultDelegate . writeObject ( cls , obj ) ; } } public void writeObjectList ( List items , Class obj_c ) throws DBWriteException { if ( items == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_OBJECT_LIST ) ; writeInt ( items . size ( ) ) ; for ( Object v : items ) { writeObject ( obj_c , v ) ; } } } public List readObjectList ( ISVDBChildParent parent , Class val_c ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } else if ( type != TYPE_OBJECT_LIST ) { throw new DBFormatException ( "" + type + "" + val_c . getName ( ) ) ; } int size = readInt ( ) ; List ret = new ArrayList ( ) ; for ( int i = ; i < size ; i ++ ) { Object val = null ; try { val = val_c . newInstance ( ) ; } catch ( InstantiationException e ) { throw new DBFormatException ( "" + val_c . getName ( ) ) ; } catch ( IllegalAccessException e ) { throw new DBFormatException ( "" + val_c . getName ( ) ) ; } readObject ( parent , val_c , val ) ; ret . add ( val ) ; } return ret ; } public void writeItemType ( SVDBItemType type ) throws DBWriteException { writeEnumType ( SVDBItemType . class , type ) ; } public void writeEnumType ( Class enum_type , Enum value ) throws DBWriteException { if ( value == null ) { writeRawType ( TYPE_NULL ) ; } else { ISVDBPersistenceRWDelegate d = fEnumDelegateMap . get ( enum_type ) ; if ( d != null ) { d . writeEnumType ( enum_type , value ) ; } else { fDefaultDelegate . writeEnumType ( enum_type , value ) ; } } } public void writeItemList ( List items ) throws DBWriteException { if ( items == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_ITEM_LIST ) ; writeInt ( items . size ( ) ) ; for ( Object it : items ) { writeSVDBItem ( ( ISVDBItemBase ) it ) ; } } } public void writeSVDBItem ( ISVDBItemBase item ) throws DBWriteException { if ( item == null ) { writeRawType ( TYPE_NULL ) ; } else { writeRawType ( TYPE_ITEM ) ; writeItemType ( item . getType ( ) ) ; ISVDBPersistenceRWDelegate d = fSVDBItemDelegateMap . get ( item . getType ( ) ) ; if ( d != null ) { d . writeSVDBItem ( item ) ; } else { fDefaultDelegate . writeSVDBItem ( item ) ; } } } public void setDebugEn ( boolean en ) { } public void readObject ( ISVDBChildItem parent , Class cls , Object obj ) throws DBFormatException { ISVDBPersistenceRWDelegate d = fObjectDelegateMap . get ( cls ) ; if ( d != null ) { d . readObject ( parent , cls , obj ) ; } else { fDefaultDelegate . readObject ( parent , cls , obj ) ; } } public SVDBItemType readItemType ( ) throws DBFormatException { return ( SVDBItemType ) readEnumType ( SVDBItemType . class ) ; } public Enum readEnumType ( Class enum_type ) throws DBFormatException { ISVDBPersistenceRWDelegate d = fEnumDelegateMap . get ( enum_type ) ; int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_ENUM ) { throw new DBFormatException ( "" + type ) ; } if ( d != null ) { return d . readEnumType ( enum_type ) ; } else { return fDefaultDelegate . readEnumType ( enum_type ) ; } } public List readItemList ( ISVDBChildItem parent ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } if ( type != TYPE_ITEM_LIST ) { throw new DBFormatException ( "" + type ) ; } int size = readInt ( ) ; List ret = new ArrayList ( ) ; for ( int i = ; i < size ; i ++ ) { ret . add ( readSVDBItem ( parent ) ) ; } return ret ; } public ISVDBItemBase readSVDBItem ( ISVDBChildItem parent ) throws DBFormatException { int type = readRawType ( ) ; if ( type == TYPE_NULL ) { return null ; } else if ( type != TYPE_ITEM ) { throw new DBFormatException ( "" + type ) ; } SVDBItemType item_type = readItemType ( ) ; ISVDBPersistenceRWDelegate d = fSVDBItemDelegateMap . get ( item_type ) ; if ( d != null ) { return d . readSVDBItem ( item_type , parent ) ; } else { return fDefaultDelegate . readSVDBItem ( item_type , parent ) ; } } } package net . sf . sveditor . core . db . persistence ; import java . io . DataInput ; import java . io . DataOutput ; import java . util . List ; import java . util . Map ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; @ SuppressWarnings ( "" ) public interface ISVDBPersistenceRWDelegateParent { void init ( DataInput in ) ; void init ( DataOutput out ) ; void writeObject ( Class cls , Object obj ) throws DBWriteException ; void readObject ( ISVDBChildItem parent , Class cls , Object obj ) throws DBFormatException ; SVDBLocation readSVDBLocation ( ) throws DBFormatException ; String readString ( ) throws DBFormatException ; int readRawType ( ) throws DBFormatException ; Map < String , String > readMapStringString ( ) throws DBFormatException ; Map < String , List > readMapStringList ( Class val_c ) throws DBFormatException ; Map < String , Object > readMapStringObject ( Class val_c ) throws DBFormatException ; List < Long > readLongList ( ) throws DBFormatException ; List < Integer > readIntList ( ) throws DBFormatException ; List < String > readStringList ( ) throws DBFormatException ; List readObjectList ( ISVDBChildParent parent , Class val_c ) throws DBWriteException , DBFormatException ; byte [ ] readByteArray ( ) throws DBFormatException ; boolean readBoolean ( ) throws DBFormatException ; long readLong ( ) throws DBFormatException ; SVDBItemType readItemType ( ) throws DBFormatException ; ISVDBItemBase readSVDBItem ( ISVDBChildItem parent ) throws DBFormatException ; List readItemList ( ISVDBChildItem parent ) throws DBFormatException ; Enum readEnumType ( Class enum_type ) throws DBFormatException ; int readInt ( ) throws DBFormatException ; void writeBoolean ( boolean v ) throws DBWriteException ; void writeRawType ( int type ) throws DBWriteException ; void writeIntList ( List < Integer > items ) throws DBWriteException ; void writeMapStringString ( Map < String , String > map ) throws DBWriteException ; void writeMapStringList ( Map < String , List > map , Class list_c ) throws DBWriteException , DBFormatException ; void writeMapStringObject ( Map < String , Object > map , Class list_c ) throws DBWriteException , DBFormatException ; void writeStringList ( List < String > items ) throws DBWriteException ; void writeSVDBItem ( ISVDBItemBase item ) throws DBWriteException ; void writeItemList ( List items ) throws DBWriteException ; void writeObjectList ( List items , Class obj_c ) throws DBWriteException ; void writeLongList ( List < Long > items ) throws DBWriteException ; void writeSVDBLocation ( SVDBLocation loc ) throws DBWriteException ; void writeString ( String val ) throws DBWriteException ; void writeInt ( int val ) throws DBWriteException ; void writeLong ( long val ) throws DBWriteException ; void writeEnumType ( Class enum_type , Enum enum_val ) throws DBWriteException ; void writeItemType ( SVDBItemType type ) throws DBWriteException ; void writeByteArray ( byte [ ] data ) throws DBWriteException ; } package net . sf . sveditor . core . db . persistence ; public class DBFormatException extends Exception { private static final long serialVersionUID = ; public DBFormatException ( String msg ) { super ( msg ) ; } } package net . sf . sveditor . core . db . persistence ; import java . io . DataInput ; import java . io . DataOutput ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; public interface ISVDBPersistenceRWDelegate { void init ( ISVDBPersistenceRWDelegateParent parent , DataInput in , DataOutput out ) ; Set < Class > getSupportedObjects ( ) ; Set < Class > getSupportedEnumTypes ( ) ; Set < SVDBItemType > getSupportedItemTypes ( ) ; void writeObject ( Class cls , Object obj ) throws DBWriteException ; void writeSVDBItem ( ISVDBItemBase item ) throws DBWriteException ; void writeEnumType ( Class cls , Enum value ) throws DBWriteException ; void readObject ( ISVDBChildItem parent , Class cls , Object obj ) throws DBFormatException ; ISVDBItemBase readSVDBItem ( SVDBItemType type , ISVDBChildItem parent ) throws DBFormatException ; Enum readEnumType ( Class enum_type ) throws DBFormatException ; } package net . sf . sveditor . core . db ; public class SVDBPackageDecl extends SVDBScopeItem { public SVDBPackageDecl ( ) { super ( "" , SVDBItemType . PackageDecl ) ; } public SVDBPackageDecl ( String name ) { super ( name , SVDBItemType . PackageDecl ) ; } } package net . sf . sveditor . core . db ; public class SVDBTypeInfoClassItem extends SVDBTypeInfo { public SVDBParamValueAssignList fParamAssign ; public SVDBTypeInfoClassItem ( ) { this ( "" ) ; } public SVDBTypeInfoClassItem ( String name ) { super ( name , SVDBItemType . TypeInfoClassItem ) ; } public SVDBTypeInfoClassItem ( String name , SVDBItemType type ) { super ( name , type ) ; } public boolean hasParameters ( ) { return ( fParamAssign != null && fParamAssign . getParameters ( ) . size ( ) > ) ; } public void setParamAssignList ( SVDBParamValueAssignList assign ) { fParamAssign = assign ; } public SVDBParamValueAssignList getParamAssignList ( ) { return fParamAssign ; } public void init_class_item ( SVDBTypeInfoClassItem item ) { setName ( item . getName ( ) ) ; if ( item . fParamAssign == null ) { fParamAssign = null ; } else { fParamAssign = item . fParamAssign . duplicate ( ) ; } } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; public class SVDBModIfcInst extends SVDBFieldItem implements ISVDBChildParent { public SVDBTypeInfo fTypeInfo ; public List < SVDBModIfcInstItem > fInstList ; public SVDBModIfcInst ( ) { super ( "" , SVDBItemType . ModIfcInst ) ; fInstList = new ArrayList < SVDBModIfcInstItem > ( ) ; } public SVDBModIfcInst ( SVDBTypeInfo type ) { super ( "" , SVDBItemType . ModIfcInst ) ; fTypeInfo = type ; fInstList = new ArrayList < SVDBModIfcInstItem > ( ) ; } public List < SVDBModIfcInstItem > getInstList ( ) { return fInstList ; } @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fInstList . iterator ( ) ; } } ; } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fInstList . add ( ( SVDBModIfcInstItem ) item ) ; } public void addInst ( SVDBModIfcInstItem item ) { item . setParent ( this ) ; fInstList . add ( item ) ; } public SVDBTypeInfo getTypeInfo ( ) { return fTypeInfo ; } public String getTypeName ( ) { if ( fTypeInfo == null ) { return "" ; } else { return fTypeInfo . getName ( ) ; } } public SVDBModIfcInst duplicate ( ) { return ( SVDBModIfcInst ) super . duplicate ( ) ; } } package net . sf . sveditor . core . db ; import java . util . List ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; public class SVDBCovergroup extends SVDBModIfcDecl { public enum BinsKW { Bins , IllegalBins , IgnoreBins } ; public SVDBExpr fCoverageEventExpr ; public List < SVDBParamPortDecl > fParamPort ; public SVDBCovergroup ( ) { super ( "" , SVDBItemType . Covergroup ) ; } public SVDBCovergroup ( String name ) { super ( name , SVDBItemType . Covergroup ) ; } public void setParamPort ( List < SVDBParamPortDecl > params ) { fParamPort = params ; } public List < SVDBParamPortDecl > getParamPort ( ) { return fParamPort ; } public void setCoverageEvent ( SVDBExpr expr ) { fCoverageEventExpr = expr ; } public SVDBExpr getCoverageEvent ( ) { return fCoverageEventExpr ; } public SVDBCovergroup duplicate ( ) { return ( SVDBCovergroup ) SVDBItemUtils . duplicate ( this ) ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; } } package net . sf . sveditor . core . db . attr ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; @ Retention ( RetentionPolicy . RUNTIME ) public @ interface SVDBDoNotSaveAttr { } package net . sf . sveditor . core . db . attr ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; @ Retention ( RetentionPolicy . RUNTIME ) public @ interface SVDBParentAttr { } package net . sf . sveditor . core . db ; public class SVDBFieldItem extends SVDBItem implements IFieldItemAttr { public int fFieldAttr ; public SVDBFieldItem ( String name , SVDBItemType type ) { super ( name , type ) ; SVDBInclude inc = new SVDBInclude ( ) ; inc . fName = "" ; } public int getAttr ( ) { return fFieldAttr ; } public void setAttr ( int attr ) { fFieldAttr = attr ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; fFieldAttr = ( ( SVDBFieldItem ) other ) . fFieldAttr ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; public class SVDBTypeInfoUnion extends SVDBTypeInfo implements ISVDBScopeItem { public SVDBLocation fEndLocation ; public List < SVDBVarDeclStmt > fFields ; public SVDBTypeInfoUnion ( ) { super ( "" , SVDBItemType . TypeInfoUnion ) ; fFields = new ArrayList < SVDBVarDeclStmt > ( ) ; } @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fFields . iterator ( ) ; } } ; } public void addChildItem ( ISVDBChildItem f ) { fFields . add ( ( SVDBVarDeclStmt ) f ) ; f . setParent ( this ) ; } public SVDBLocation getEndLocation ( ) { return fEndLocation ; } public void setEndLocation ( SVDBLocation loc ) { fEndLocation = loc ; } @ SuppressWarnings ( { "" , "" } ) public List < ISVDBItemBase > getItems ( ) { return ( List ) fFields ; } public void addItem ( ISVDBItemBase item ) { } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBModportPortsDecl extends SVDBChildItem implements ISVDBAddChildItem { public List < ISVDBChildItem > fPorts ; protected SVDBModportPortsDecl ( SVDBItemType type ) { super ( type ) ; fPorts = new ArrayList < ISVDBChildItem > ( ) ; } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fPorts . add ( item ) ; } public List < ISVDBChildItem > getPorts ( ) { return fPorts ; } } package net . sf . sveditor . core . db ; public class SVDBModportTFPortsDecl extends SVDBModportPortsDecl { public enum ImpExpType { Import , Export } ; public ImpExpType fImpExpType ; public SVDBModportTFPortsDecl ( ) { super ( SVDBItemType . ModportTFPortsDecl ) ; } public void setImpExpType ( String type ) { if ( type . equals ( "" ) ) { setImpExpType ( ImpExpType . Import ) ; } else { setImpExpType ( ImpExpType . Export ) ; } } public void setImpExpType ( ImpExpType type ) { fImpExpType = type ; } public ImpExpType getImpExpType ( ) { return fImpExpType ; } } package net . sf . sveditor . core . db ; public class SVDBMarker extends SVDBItemBase { public enum MarkerType { Info , Warning , Error } ; public enum MarkerKind { MissingInclude , UndefinedMacro , ParseError } ; public String fMessage ; public MarkerKind fKind ; public MarkerType fMarkerType ; public SVDBMarker ( ) { super ( SVDBItemType . Marker ) ; } public SVDBMarker ( MarkerType type , MarkerKind kind , String message ) { super ( SVDBItemType . Marker ) ; fMarkerType = type ; fKind = kind ; fMessage = message ; } public MarkerType getMarkerType ( ) { return fMarkerType ; } public void setMarkerType ( MarkerType type ) { fMarkerType = type ; } public void setMessage ( String msg ) { fMessage = msg ; } public String getMessage ( ) { return fMessage ; } public void setKind ( MarkerKind kind ) { fKind = kind ; } public MarkerKind getKind ( ) { return fKind ; } @ Override public SVDBMarker duplicate ( ) { return ( SVDBMarker ) SVDBItemUtils . duplicate ( this ) ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBMarker ) { SVDBMarker o = ( SVDBMarker ) obj ; boolean ret = super . equals ( obj ) ; ret &= ( o . fKind == fKind ) ; return ret ; } return false ; } } package net . sf . sveditor . core . db ; public interface ISVDBChildItem extends ISVDBItemBase { ISVDBChildItem getParent ( ) ; void setParent ( ISVDBChildItem parent ) ; } package net . sf . sveditor . core . db ; public class SVDBMacroDefParam extends SVDBChildItem implements ISVDBNamedItem { public String fName ; public String fValue ; public SVDBMacroDefParam ( ) { super ( SVDBItemType . MacroDefParam ) ; } public SVDBMacroDefParam ( String name , String value ) { this ( ) ; fName = name ; fValue = value ; } public String getName ( ) { return fName ; } public String getValue ( ) { return fValue ; } } package net . sf . sveditor . core . db ; public class SVDBTypeInfoModuleIfc extends SVDBTypeInfoUserDef { public SVDBTypeInfoModuleIfc ( ) { super ( "" , SVDBItemType . TypeInfoModuleIfc ) ; } public SVDBTypeInfoModuleIfc ( String name ) { super ( name , SVDBItemType . TypeInfoModuleIfc ) ; } } package net . sf . sveditor . core . db ; public interface IFieldItemAttr { int FieldAttr_Local = ( << ) ; int FieldAttr_Protected = ( << ) ; int FieldAttr_Rand = ( << ) ; int FieldAttr_Randc = ( << ) ; int FieldAttr_Static = ( << ) ; int FieldAttr_Virtual = ( << ) ; int FieldAttr_Automatic = ( << ) ; int FieldAttr_Extern = ( << ) ; int FieldAttr_Const = ( << ) ; int FieldAttr_DPI = ( << ) ; int FieldAttr_Pure = ( << ) ; int FieldAttr_Context = ( << ) ; int FieldAttr_SvBuiltin = ( << ) ; void setAttr ( int attr ) ; int getAttr ( ) ; } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . attr . SVDBDoNotSaveAttr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBGenerateIf extends SVDBChildItem implements ISVDBAddChildItem { @ SVDBDoNotSaveAttr int fAddIdx ; public SVDBExpr fExpr ; public ISVDBChildItem fIfBody ; public ISVDBChildItem fElseBody ; public SVDBGenerateIf ( ) { super ( SVDBItemType . GenerateIf ) ; } public void setExpr ( SVDBExpr expr ) { fExpr = expr ; } public SVDBExpr getExpr ( ) { return fExpr ; } public ISVDBChildItem getIfBody ( ) { return fIfBody ; } public ISVDBChildItem getElseBody ( ) { return fElseBody ; } public void addChildItem ( ISVDBChildItem item ) { if ( fAddIdx == ) { fIfBody = item ; } else if ( fAddIdx == ) { fElseBody = item ; } fAddIdx ++ ; } } package net . sf . sveditor . core . db ; public class SVDBFunction extends SVDBTask { public SVDBTypeInfo fRetType ; public SVDBFunction ( ) { super ( "" , SVDBItemType . Function ) ; } public SVDBFunction ( String name , SVDBTypeInfo ret_type ) { super ( name , SVDBItemType . Function ) ; fRetType = ret_type ; } public SVDBTypeInfo getReturnType ( ) { return fRetType ; } public void setReturnType ( SVDBTypeInfo ret ) { fRetType = ret ; } @ Override public SVDBFunction duplicate ( ) { return ( SVDBFunction ) super . duplicate ( ) ; } @ Override public void init ( SVDBItemBase other ) { super . init ( other ) ; SVDBFunction o = ( SVDBFunction ) other ; fRetType = o . fRetType . duplicate ( ) ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; public class SVDBModportDecl extends SVDBChildItem implements ISVDBChildParent { public List < SVDBModportItem > fModportItemList ; public SVDBModportDecl ( ) { super ( SVDBItemType . ModportDecl ) ; fModportItemList = new ArrayList < SVDBModportItem > ( ) ; } public List < SVDBModportItem > getModportItemList ( ) { return fModportItemList ; } @ SuppressWarnings ( { "" , "" } ) public Iterable < ISVDBChildItem > getChildren ( ) { return new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return ( Iterator ) fModportItemList . iterator ( ) ; } } ; } public void addChildItem ( ISVDBChildItem item ) { item . setParent ( this ) ; fModportItemList . add ( ( SVDBModportItem ) item ) ; } public void addModportItem ( SVDBModportItem item ) { item . setParent ( this ) ; fModportItemList . add ( item ) ; } } package net . sf . sveditor . core . db ; import java . util . List ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; public class SVDBTypeInfo extends SVDBItem implements ISVDBNamedItem { public static final int TypeAttr_Vectored = ( << ) ; public List < SVDBVarDimItem > fArrayDim ; public SVDBTypeInfo ( String typename , SVDBItemType data_type ) { super ( typename , data_type ) ; fLocation = null ; } @ Deprecated public SVDBItemType getDataType ( ) { return getType ( ) ; } @ Deprecated public void setDataType ( SVDBItemType type ) { setType ( type ) ; } public List < SVDBVarDimItem > getArrayDim ( ) { return fArrayDim ; } public void setArrayDim ( List < SVDBVarDimItem > dim ) { fArrayDim = dim ; } @ Override public SVDBTypeInfo duplicate ( ) { return ( SVDBTypeInfo ) super . duplicate ( ) ; } public static boolean isDataType ( SVDBItemType type ) { return false ; } } package net . sf . sveditor . core . db ; import java . util . List ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; public class SVDBModIfcInstItem extends SVDBItem implements ISVDBChildItem { public SVDBParamValueAssignList fPortMap ; public List < SVDBVarDimItem > fArrayDim ; public SVDBModIfcInstItem ( ) { super ( "" , SVDBItemType . ModIfcInstItem ) ; } public SVDBModIfcInstItem ( String name ) { super ( name , SVDBItemType . ModIfcInstItem ) ; } public SVDBParamValueAssignList getPortMap ( ) { return fPortMap ; } public void setPortMap ( SVDBParamValueAssignList map ) { fPortMap = map ; } public void setArrayDim ( List < SVDBVarDimItem > dim ) { fArrayDim = dim ; } public List < SVDBVarDimItem > getArrayDim ( ) { return fArrayDim ; } } package net . sf . sveditor . core . db ; public interface ISVDBNamedItem { SVDBItemType getType ( ) ; String getName ( ) ; } package net . sf . sveditor . core . db ; import java . util . Iterator ; public class EmptySVDBChildItemIterable { private static final Iterator < ISVDBChildItem > EmptyIterator = new Iterator < ISVDBChildItem > ( ) { public boolean hasNext ( ) { return false ; } public ISVDBChildItem next ( ) { return null ; } public void remove ( ) { } } ; public static final Iterable < ISVDBChildItem > iterable = new Iterable < ISVDBChildItem > ( ) { public Iterator < ISVDBChildItem > iterator ( ) { return EmptyIterator ; } } ; } package net . sf . sveditor . core . db ; public class SVDBConfigDecl extends SVDBScopeItem { public SVDBConfigDecl ( ) { super ( null , SVDBItemType . ConfigDecl ) ; } public SVDBConfigDecl ( String name ) { super ( name , SVDBItemType . ConfigDecl ) ; } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVDBCoverpoint extends SVDBScopeItem { public SVDBExpr fTarget ; public SVDBExpr fIFF ; public SVDBCoverpoint ( ) { super ( "" , SVDBItemType . Coverpoint ) ; } public SVDBCoverpoint ( String name ) { super ( name , SVDBItemType . Coverpoint ) ; } public SVDBExpr getTarget ( ) { return fTarget ; } public void setTarget ( SVDBExpr expr ) { fTarget = expr ; } public SVDBExpr getIFF ( ) { return fIFF ; } public void setIFF ( SVDBExpr expr ) { fIFF = expr ; } @ Override public SVDBCoverpoint duplicate ( ) { return ( SVDBCoverpoint ) SVDBItemUtils . duplicate ( this ) ; } @ Override public void init ( SVDBItemBase other ) { SVDBCoverpoint other_i = ( SVDBCoverpoint ) other ; super . init ( other ) ; fTarget = other_i . fTarget ; } } package net . sf . sveditor . core . db ; public class SVDBModportClockingPortDecl extends SVDBModportPortsDecl { public String fClockingId ; public SVDBModportClockingPortDecl ( ) { super ( SVDBItemType . ModportClockingPortDecl ) ; } public void setClockingId ( String id ) { fClockingId = id ; } public String getClockingId ( ) { return fClockingId ; } } package net . sf . sveditor . core . db ; import java . util . List ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; public class SVDBTypeInfoBuiltin extends SVDBTypeInfo { public static final int TypeAttr_Signed = ( << ) ; public static final int TypeAttr_Unsigned = ( << ) ; public int fAttr ; public List < SVDBVarDimItem > fVectorDim ; public SVDBTypeInfoBuiltin ( ) { this ( "" ) ; } public SVDBTypeInfoBuiltin ( String typename ) { super ( typename , SVDBItemType . TypeInfoBuiltin ) ; } public SVDBTypeInfoBuiltin ( String typename , SVDBItemType type ) { super ( typename , type ) ; } public int getAttr ( ) { return fAttr ; } public void setAttr ( int attr ) { fAttr = attr ; } public List < SVDBVarDimItem > getVectorDim ( ) { return fVectorDim ; } public void setVectorDim ( List < SVDBVarDimItem > dim ) { fVectorDim = dim ; } public String toString ( ) { String ret = getName ( ) ; if ( ( getAttr ( ) & TypeAttr_Unsigned ) != ) { ret += "" ; } if ( getVectorDim ( ) != null && getVectorDim ( ) . size ( ) > ) { for ( SVDBVarDimItem dim : getVectorDim ( ) ) { ret += dim . toString ( ) ; } } if ( getArrayDim ( ) != null && getArrayDim ( ) . size ( ) > ) { for ( SVDBVarDimItem dim : getArrayDim ( ) ) { ret += dim . toString ( ) ; } } return ret ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof SVDBTypeInfoBuiltin ) { SVDBTypeInfoBuiltin o = ( SVDBTypeInfoBuiltin ) obj ; if ( fAttr != o . fAttr ) { return false ; } if ( fVectorDim == null || o . fVectorDim == null ) { if ( fVectorDim != o . fVectorDim ) { return false ; } } else if ( ! fVectorDim . equals ( o . fVectorDim ) ) { return false ; } return super . equals ( obj ) ; } return false ; } @ Override public SVDBTypeInfoBuiltin duplicate ( ) { SVDBTypeInfoBuiltin ret = new SVDBTypeInfoBuiltin ( getName ( ) ) ; ret . init ( this ) ; return ret ; } @ Override public void init ( SVDBItemBase other ) { super . init ( other ) ; SVDBTypeInfoBuiltin o = ( SVDBTypeInfoBuiltin ) other ; setAttr ( o . getAttr ( ) ) ; setVectorDim ( o . getVectorDim ( ) ) ; } } package net . sf . sveditor . core . db ; public class SVDBPreProcCond extends SVDBScopeItem { public String fConditional ; public SVDBPreProcCond ( ) { super ( "" , SVDBItemType . PreProcCond ) ; } public SVDBPreProcCond ( String name , String conditional ) { super ( name , SVDBItemType . PreProcCond ) ; fConditional = conditional ; } public String getConditional ( ) { return fConditional ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; } public boolean equals ( Object obj ) { if ( super . equals ( obj ) && obj instanceof SVDBPreProcCond ) { return fConditional . equals ( ( ( SVDBPreProcCond ) obj ) . fConditional ) && super . equals ( obj ) ; } return false ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBTypeInfoClassType extends SVDBTypeInfoClassItem { public List < SVDBTypeInfoClassItem > fTypeInfo ; public SVDBTypeInfoClassType ( ) { this ( "" ) ; } public SVDBTypeInfoClassType ( String name ) { super ( name , SVDBItemType . TypeInfoClassType ) ; } public boolean isScoped ( ) { return ( fTypeInfo != null && fTypeInfo . size ( ) > ) ; } public void addClassItem ( SVDBTypeInfoClassItem item ) { SVDBTypeInfoClassItem this_i = new SVDBTypeInfoClassItem ( getName ( ) ) ; this_i . init ( this ) ; if ( fTypeInfo == null ) { fTypeInfo = new ArrayList < SVDBTypeInfoClassItem > ( ) ; } fTypeInfo . add ( this_i ) ; init_class_item ( item ) ; } } package net . sf . sveditor . core . db ; public class SVDBGenerateFor extends SVDBChildItem { public SVDBGenerateFor ( ) { super ( SVDBItemType . GenerateFor ) ; } } package net . sf . sveditor . core . db ; import java . util . ArrayList ; import java . util . List ; public class SVDBModportSimplePortsDecl extends SVDBModportPortsDecl { public enum PortDir { input , output , inout } ; public PortDir fPortDir ; public List < SVDBModportSimplePort > fPortList ; public SVDBModportSimplePortsDecl ( ) { super ( SVDBItemType . ModportSimplePortsDecl ) ; fPortList = new ArrayList < SVDBModportSimplePort > ( ) ; } public void setPortDir ( PortDir dir ) { fPortDir = dir ; } public void setPortDir ( String dir ) { if ( dir . equals ( "" ) ) { setPortDir ( PortDir . input ) ; } else if ( dir . equals ( "" ) ) { setPortDir ( PortDir . output ) ; } else { setPortDir ( PortDir . inout ) ; } } public PortDir getPortDir ( ) { return fPortDir ; } public List < SVDBModportSimplePort > getPortList ( ) { return fPortList ; } public void addPort ( SVDBModportSimplePort port ) { fPortList . add ( port ) ; } } package net . sf . sveditor . core . db ; public class SVDBInterfaceDecl extends SVDBModIfcDecl { public SVDBInterfaceDecl ( ) { super ( "" , SVDBItemType . InterfaceDecl ) ; } public SVDBInterfaceDecl ( String name ) { super ( name , SVDBItemType . InterfaceDecl ) ; } } package net . sf . sveditor . core . db ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; public class SVDBAssign extends SVDBStmt { public SVDBExpr fLHS ; public SVDBExpr fDelay ; public SVDBExpr fRHS ; public SVDBAssign ( ) { super ( SVDBItemType . Assign ) ; } public void setLHS ( SVDBExpr lhs ) { fLHS = lhs ; } public SVDBExpr getLHS ( ) { return fLHS ; } public void setDelay ( SVDBExpr delay ) { fDelay = delay ; } public SVDBExpr getDelay ( ) { return fDelay ; } public void setRHS ( SVDBExpr rhs ) { fRHS = rhs ; } public SVDBExpr getRHS ( ) { return fRHS ; } public SVDBAssign duplicate ( ) { return ( SVDBAssign ) SVDBItemUtils . duplicate ( this ) ; } public void init ( SVDBItemBase other ) { super . init ( other ) ; SVDBAssign o = ( SVDBAssign ) other ; if ( o . fDelay == null ) { fDelay = null ; } else { fDelay = o . fDelay . duplicate ( ) ; } } public boolean equals ( Object other ) { boolean ret = super . equals ( other ) ; return ret ; } } package net . sf . sveditor . core . preproc ; import java . util . List ; import net . sf . sveditor . core . scanutils . AbstractTextScanner ; import net . sf . sveditor . core . scanutils . ScanLocation ; public class SVPreProcOutput extends AbstractTextScanner { private StringBuilder fText ; private List < Integer > fLineMap ; private int fLineIdx ; private int fNextLinePos ; private int fIdx ; private int fUngetCh1 , fUngetCh2 ; public SVPreProcOutput ( StringBuilder text , List < Integer > line_map ) { fText = text ; fIdx = ; fLineIdx = ; fLineMap = line_map ; if ( line_map . size ( ) > ) { fNextLinePos = line_map . get ( ) ; } else { fNextLinePos = Integer . MAX_VALUE ; } fLineno = ; int length = fText . length ( ) ; for ( int i = ; i < length ; i ++ ) { if ( fText . charAt ( i ) == '' ) { fText . setCharAt ( i , '' ) ; } } fUngetCh1 = - ; fUngetCh2 = - ; } public int get_ch ( ) { int ch = - ; if ( fUngetCh1 != - ) { ch = fUngetCh1 ; fUngetCh1 = fUngetCh2 ; fUngetCh2 = - ; } else if ( fIdx < fText . length ( ) ) { ch = fText . charAt ( fIdx ++ ) ; } return ch ; } public void unget_ch ( int ch ) { fUngetCh2 = fUngetCh1 ; fUngetCh1 = ch ; } public ScanLocation getLocation ( ) { if ( fIdx >= fNextLinePos ) { while ( fLineIdx < fLineMap . size ( ) && fLineMap . get ( fLineIdx ) < fIdx ) { fLineIdx ++ ; fLineno ++ ; } if ( fLineIdx >= fLineMap . size ( ) ) { fNextLinePos = Integer . MAX_VALUE ; } } return new ScanLocation ( "" , fLineno , ) ; } public long getPos ( ) { return fIdx ; } public String toString ( ) { return fText . toString ( ) ; } } package net . sf . sveditor . core . preproc ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . Stack ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . scanner . IDefineProvider ; import net . sf . sveditor . core . scanutils . AbstractTextScanner ; import net . sf . sveditor . core . scanutils . ScanLocation ; public class SVPreProcessor extends AbstractTextScanner { private IDefineProvider fDefineProvider ; private String fFileName ; private InputStream fInput ; private StringBuilder fOutput ; private List < Integer > fLineMap ; private StringBuilder fTmpBuffer ; private List < Tuple < String , String > > fParamList ; private Stack < Integer > fPreProcEn ; private int fLineno = ; private int fLastCh ; private int fUngetCh [ ] = { - , - } ; private byte fInBuffer [ ] ; private int fInBufferIdx ; private int fInBufferMax ; private boolean fInPreProcess ; private static final int PP_DISABLED = ; private static final int PP_ENABLED = ; private static final int PP_CARRY = ; private static final int PP_THIS_LEVEL_EN_BLOCK = ; public static final Set < String > fIgnoredDirectives ; static { fIgnoredDirectives = new HashSet < String > ( ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; } public SVPreProcessor ( InputStream input , String filename , IDefineProvider define_provider ) { fOutput = new StringBuilder ( ) ; fTmpBuffer = new StringBuilder ( ) ; fInput = input ; fDefineProvider = define_provider ; fParamList = new ArrayList < Tuple < String , String > > ( ) ; fFileName = filename ; fPreProcEn = new Stack < Integer > ( ) ; fLineMap = new ArrayList < Integer > ( ) ; fInBuffer = new byte [ * ] ; fInBufferIdx = ; fInBufferMax = ; } public SVPreProcOutput preprocess ( ) { int ch , last_ch = - ; int end_comment [ ] = { - , - } ; boolean in_string = false ; boolean ifdef_enabled = true ; fInPreProcess = true ; while ( ( ch = get_ch ( ) ) != - ) { if ( ! in_string ) { if ( ch == '' ) { int ch2 = get_ch ( ) ; if ( ch2 == '' ) { fOutput . append ( '' ) ; while ( ( ch = get_ch ( ) ) != - && ch != '' && ch != '' ) { } if ( ch == '' ) { ch = get_ch ( ) ; if ( ch != '' ) { unget_ch ( ch ) ; } } ch = '' ; last_ch = '' ; } else if ( ch2 == '' ) { end_comment [ ] = - ; end_comment [ ] = - ; fOutput . append ( '' ) ; while ( ( ch = get_ch ( ) ) != - ) { end_comment [ ] = end_comment [ ] ; end_comment [ ] = ch ; if ( end_comment [ ] == '' && end_comment [ ] == '' ) { break ; } } ch = '' ; last_ch = '' ; } else { unget_ch ( ch2 ) ; } } if ( ch == '' ) { handle_preproc_directive ( ) ; ifdef_enabled = ifdef_enabled ( ) ; if ( ! ifdef_enabled ) { fOutput . append ( '' ) ; } } else { if ( ch == '' && last_ch != '' ) { in_string = true ; } if ( ifdef_enabled ) { fOutput . append ( ( char ) ch ) ; } } } else { if ( ch == '' && last_ch != '' ) { in_string = false ; } if ( ifdef_enabled ) { fOutput . append ( ( char ) ch ) ; } } if ( last_ch == '' && ch == '' ) { last_ch = '' ; } else { last_ch = ch ; } } fInPreProcess = false ; return new SVPreProcOutput ( fOutput , fLineMap ) ; } private void handle_preproc_directive ( ) { int ch = - ; while ( ( ch = get_ch ( ) ) != - && Character . isWhitespace ( ch ) ) { } String type ; if ( ch == - ) { type = "" ; } else { type = readIdentifier ( ch ) ; if ( type == null ) { type = "" ; } } if ( type . equals ( "" ) || type . equals ( "" ) || type . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; String remainder = readIdentifier ( ch ) ; if ( remainder != null ) { remainder = remainder . trim ( ) ; } else { remainder = "" ; } if ( type . equals ( "" ) ) { if ( fDefineProvider != null ) { enter_ifdef ( fDefineProvider . isDefined ( remainder , fLineno ) ) ; } else { enter_ifdef ( false ) ; } } else if ( type . equals ( "" ) ) { if ( fDefineProvider != null ) { enter_ifdef ( ! fDefineProvider . isDefined ( remainder , fLineno ) ) ; } else { enter_ifdef ( true ) ; } } else { if ( fDefineProvider != null ) { enter_elsif ( fDefineProvider . isDefined ( remainder , fLineno ) ) ; } else { enter_elsif ( false ) ; } } } else if ( type . equals ( "" ) ) { enter_else ( ) ; } else if ( type . equals ( "" ) ) { leave_ifdef ( ) ; } else if ( fIgnoredDirectives . contains ( type ) ) { readLine ( get_ch ( ) ) ; } else if ( type . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; readIdentifier ( ch ) ; fParamList . clear ( ) ; ch = get_ch ( ) ; if ( ch == '' ) { do { ch = skipWhite ( get_ch ( ) ) ; if ( ! ( Character . isJavaIdentifierPart ( ch ) ) ) { break ; } else { String p = readIdentifier ( ch ) ; String dflt = null ; ch = skipWhite ( get_ch ( ) ) ; if ( ch == '' ) { ch = skipWhite ( get_ch ( ) ) ; if ( ch == '' ) { dflt = readString ( ch ) ; dflt = "" + dflt + "" ; } else { startCapture ( ch ) ; while ( ( ch = get_ch ( ) ) != - && ch != '' && ch != '' ) { } unget_ch ( ch ) ; dflt = endCapture ( ) ; } } else { unget_ch ( ch ) ; } fParamList . add ( new Tuple < String , String > ( p , dflt ) ) ; } ch = skipWhite ( get_ch ( ) ) ; } while ( ch == '' ) ; if ( ch == '' ) { ch = get_ch ( ) ; } } String define = readLine ( ch ) ; if ( define == null ) { define = "" ; } int last_comment ; if ( ( last_comment = define . lastIndexOf ( "" ) ) != - ) { int lr = define . indexOf ( '' , last_comment ) ; if ( lr == - ) { define = define . substring ( , define . indexOf ( "" ) ) ; } } } else if ( type . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; if ( ch == '' ) { String inc = readString ( ch ) ; if ( inc . length ( ) > ) { inc = inc . substring ( , inc . length ( ) - ) ; } else { inc = "" ; } } } else if ( type . equals ( "" ) ) { fOutput . append ( "" + fLineno ) ; } else if ( type . equals ( "" ) ) { fOutput . append ( "" + fFileName + "" ) ; } else if ( type . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; String id = readIdentifier ( ch ) ; if ( id != null ) { if ( id . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; id = readIdentifier ( ch ) ; if ( id != null ) { if ( id . equals ( "" ) ) { enter_ifdef ( false ) ; } else if ( id . equals ( "" ) ) { leave_ifdef ( ) ; } } } } } else if ( type . equals ( "" ) ) { enter_ifdef ( false ) ; } else if ( type . equals ( "" ) ) { leave_ifdef ( ) ; } else if ( ! type . equals ( "" ) ) { fTmpBuffer . setLength ( ) ; fTmpBuffer . append ( '' ) ; fTmpBuffer . append ( type ) ; if ( ifdef_enabled ( ) ) { boolean is_defined = ( fDefineProvider != null ) ? fDefineProvider . isDefined ( type , fLineno ) : false ; if ( fDefineProvider != null && ( fDefineProvider . hasParameters ( type , fLineno ) || ! is_defined ) ) { ch = get_ch ( ) ; while ( ch != - && Character . isWhitespace ( ch ) && ch != '' ) { ch = get_ch ( ) ; } if ( ch == '' ) { fTmpBuffer . append ( ( char ) ch ) ; int matchLevel = ; do { ch = get_ch ( ) ; if ( ch == '' ) { matchLevel ++ ; } else if ( ch == '' ) { matchLevel -- ; } if ( ch != - ) { fTmpBuffer . append ( ( char ) ch ) ; } } while ( ch != - && matchLevel > ) ; } else if ( is_defined ) { unget_ch ( ch ) ; } else { unget_ch ( ch ) ; } } if ( fDefineProvider != null ) { try { fOutput . append ( fDefineProvider . expandMacro ( fTmpBuffer . toString ( ) , fFileName , fLineno ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } } private void enter_ifdef ( boolean enabled ) { int e = ( enabled ) ? PP_ENABLED : PP_DISABLED ; if ( fPreProcEn . size ( ) > ) { int e_t = fPreProcEn . peek ( ) ; if ( ( e_t & PP_ENABLED ) == ) { e = PP_DISABLED ; e |= PP_CARRY ; } } if ( ( e & PP_ENABLED ) == ) { e |= PP_THIS_LEVEL_EN_BLOCK ; } fPreProcEn . push ( e ) ; } private void leave_ifdef ( ) { if ( fPreProcEn . size ( ) > ) { fPreProcEn . pop ( ) ; } } private void enter_elsif ( boolean enabled ) { if ( fPreProcEn . size ( ) > ) { int e = fPreProcEn . pop ( ) ; if ( enabled ) { if ( ( e & PP_CARRY ) != PP_CARRY && ( e & PP_THIS_LEVEL_EN_BLOCK ) != PP_THIS_LEVEL_EN_BLOCK ) { e |= ( PP_ENABLED | PP_THIS_LEVEL_EN_BLOCK ) ; } } else { e &= ~ PP_ENABLED ; } fPreProcEn . push ( e ) ; } } private void enter_else ( ) { if ( fPreProcEn . size ( ) > ) { int e = fPreProcEn . pop ( ) ; if ( ( e & PP_CARRY ) == ) { if ( ( e & PP_THIS_LEVEL_EN_BLOCK ) != ) { e &= ~ PP_ENABLED ; } else { e |= PP_ENABLED ; } } fPreProcEn . push ( e ) ; } } private boolean ifdef_enabled ( ) { if ( fPreProcEn . size ( ) == ) { return true ; } else { int e = fPreProcEn . peek ( ) ; return ( ( e & PP_ENABLED ) == PP_ENABLED ) ; } } private String readLine ( int ci ) { int last_ch = - ; fTmpBuffer . setLength ( ) ; while ( ci != - && ci != '' || last_ch == '' ) { if ( last_ch == '' && ci == '' ) { if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setLength ( fTmpBuffer . length ( ) - ) ; } if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setCharAt ( fTmpBuffer . length ( ) - , '' ) ; } } else { fTmpBuffer . append ( ( char ) ci ) ; } if ( ci != '' ) { last_ch = ci ; } ci = get_ch ( ) ; } unget_ch ( ci ) ; if ( fTmpBuffer . length ( ) == ) { return null ; } else { return fTmpBuffer . toString ( ) ; } } public int get_ch ( ) { int ch = - ; if ( ! fInPreProcess ) { throw new RuntimeException ( "" ) ; } if ( fUngetCh [ ] != - ) { ch = fUngetCh [ ] ; fUngetCh [ ] = fUngetCh [ ] ; fUngetCh [ ] = - ; } else { if ( fInBufferIdx >= fInBufferMax ) { try { fInBufferMax = fInput . read ( fInBuffer , , fInBuffer . length ) ; fInBufferIdx = ; } catch ( IOException e ) { } } if ( fInBufferIdx < fInBufferMax ) { ch = fInBuffer [ fInBufferIdx ++ ] ; } else { ch = - ; } if ( fLastCh == '' ) { fLineMap . add ( fOutput . length ( ) - ) ; fLineno ++ ; } fLastCh = ch ; } if ( ch != - && fCaptureEnabled ) { fCaptureBuffer . append ( ( char ) ch ) ; } return ch ; } public void unget_ch ( int ch ) { if ( fUngetCh [ ] == - ) { fUngetCh [ ] = ch ; } else { fUngetCh [ ] = fUngetCh [ ] ; fUngetCh [ ] = ch ; } if ( ch != - && fCaptureEnabled && fCaptureBuffer . length ( ) > ) { fCaptureBuffer . deleteCharAt ( fCaptureBuffer . length ( ) - ) ; } } public ScanLocation getLocation ( ) { return new ScanLocation ( fFileName , fLineno , ) ; } public long getPos ( ) { return - ; } } package net . sf . sveditor . core . preproc ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . docs . DocCommentParser ; import net . sf . sveditor . core . docs . IDocCommentParser ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanner . IDefineProvider ; import net . sf . sveditor . core . scanner . ISVPreProcScannerObserver ; import net . sf . sveditor . core . scanner . ISVScanner ; import net . sf . sveditor . core . scanutils . AbstractTextScanner ; import net . sf . sveditor . core . scanutils . ScanLocation ; public class SVPreProcDirectiveScanner extends AbstractTextScanner implements ISVScanner { private InputStream fInput ; private String fFileName ; private boolean fInProcess ; private int fUngetCh = - ; private int fLastCh = - ; private int fLineno ; private StringBuffer fTmpBuffer ; private StringBuilder fCommentBuffer ; private boolean fInComment ; private List < Tuple < String , String > > fParamList ; private ISVPreProcScannerObserver fObserver ; private ISVScanner fScanner ; private IDefineProvider fDefineProvider ; private ScanLocation fScanLocation ; private IDocCommentParser fDocCommentParser ; private byte fInBuffer [ ] ; private int fInBufferIdx ; private int fInBufferMax ; public static final Set < String > fIgnoredDirectives ; private static LogHandle fLog = LogFactory . getLogHandle ( "" ) ; static { fIgnoredDirectives = new HashSet < String > ( ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; fIgnoredDirectives . add ( "" ) ; } public SVPreProcDirectiveScanner ( ) { fTmpBuffer = new StringBuffer ( ) ; fParamList = new ArrayList < Tuple < String , String > > ( ) ; fScanLocation = new ScanLocation ( "" , , ) ; fCommentBuffer = new StringBuilder ( ) ; fDocCommentParser = new DocCommentParser ( ) ; fInComment = false ; fInBuffer = new byte [ * ] ; fInBufferIdx = ; fInBufferMax = ; } public void setObserver ( ISVPreProcScannerObserver observer ) { fObserver = observer ; fObserver . init ( this ) ; } public void setDefineProvider ( IDefineProvider def_provider ) { fDefineProvider = def_provider ; } public void setScanner ( ISVScanner scanner ) { fScanner = scanner ; } public ScanLocation getStmtLocation ( ) { return fScanLocation ; } public ScanLocation getStartLocation ( ) { return fScanLocation ; } public ScanLocation getLocation ( ) { return new ScanLocation ( fFileName , fLineno , ) ; } public void setStmtLocation ( ScanLocation location ) { } public void init ( InputStream in , String name ) { fLineno = ; fScanLocation . setLineNo ( ) ; fTmpBuffer . setLength ( ) ; fInput = in ; fFileName = name ; fScanLocation . setFileName ( name ) ; } public void close ( ) { try { if ( fInput != null ) { fInput . close ( ) ; } } catch ( IOException e ) { } } public void process ( ) { int ch , last_ch = - ; int end_comment [ ] = { - , - } ; boolean in_string = false ; boolean foundSingleLineComment = false ; fInProcess = true ; if ( fObserver != null ) { fObserver . enter_file ( fFileName ) ; } while ( ( ch = get_ch ( ) ) != - ) { foundSingleLineComment = false ; if ( ! in_string ) { if ( ch == '' ) { int ch2 = get_ch ( ) ; if ( ch2 == '' ) { foundSingleLineComment = true ; beginComment ( ) ; while ( ( ch = get_ch ( ) ) != - && ch != '' ) { fCommentBuffer . append ( ( char ) ch ) ; } fCommentBuffer . append ( '' ) ; ch = '' ; last_ch = '' ; } else if ( ch2 == '' ) { end_comment [ ] = - ; end_comment [ ] = - ; beginComment ( ) ; while ( ( ch = get_ch ( ) ) != - ) { end_comment [ ] = end_comment [ ] ; end_comment [ ] = ch ; if ( end_comment [ ] == '' && end_comment [ ] == '' ) { endComment ( ) ; break ; } else { fCommentBuffer . append ( ( char ) ch ) ; } } ch = '' ; last_ch = '' ; } else { unget_ch ( ch2 ) ; } } if ( ! Character . isWhitespace ( ch ) && fInComment ) { endComment ( ) ; } if ( ch == '' ) { handle_preproc_directive ( ) ; } else { if ( ch == '' && last_ch != '' ) { in_string = true ; } } } else { if ( ch == '' && last_ch != '' ) { in_string = false ; } } last_ch = ch ; if ( fInComment && ! foundSingleLineComment && ( ( char ) ch ) == '' ) { endComment ( ) ; } } if ( fObserver != null ) { fObserver . leave_file ( ) ; } fInProcess = false ; } private void beginComment ( ) { if ( ! fInComment ) { fCommentBuffer . setLength ( ) ; } fInComment = true ; } private void endComment ( ) { if ( ! fInComment ) { return ; } fInComment = false ; String comment = fCommentBuffer . toString ( ) ; String title = fDocCommentParser . isDocComment ( comment ) ; if ( title != null ) { if ( fObserver != null ) { fLog . debug ( "" + title + "" + comment ) ; fObserver . comment ( title , comment ) ; } } } private String readLine ( int ci ) { int last_ch = - ; fTmpBuffer . setLength ( ) ; while ( ci != - && ci != '' || last_ch == '' ) { if ( last_ch == '' && ci == '' ) { if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setLength ( fTmpBuffer . length ( ) - ) ; } if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setCharAt ( fTmpBuffer . length ( ) - , '' ) ; } } else { fTmpBuffer . append ( ( char ) ci ) ; } if ( ci != '' ) { last_ch = ci ; } ci = get_ch ( ) ; } unget_ch ( ci ) ; if ( fTmpBuffer . length ( ) == ) { return null ; } else { return fTmpBuffer . toString ( ) ; } } private String readString_ll ( int ci ) { fTmpBuffer . setLength ( ) ; int last_ch = - ; if ( ci != '' ) { return null ; } fTmpBuffer . append ( ( char ) ci ) ; ci = get_ch ( ) ; while ( ( ci != '' && ci != '' && ci != - ) || last_ch == '' ) { if ( last_ch == '' && ci == '' ) { if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setCharAt ( fTmpBuffer . length ( ) - , '' ) ; } } else if ( last_ch == '' && ci == '' ) { if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setLength ( fTmpBuffer . length ( ) - ) ; } if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setCharAt ( fTmpBuffer . length ( ) - , '' ) ; } } else { fTmpBuffer . append ( ( char ) ci ) ; } if ( ci != '' ) { last_ch = ci ; } ci = get_ch ( ) ; } if ( ci != - ) { fTmpBuffer . append ( ( char ) ci ) ; } return fTmpBuffer . toString ( ) ; } private void handle_preproc_directive ( ) { int ch = - ; while ( ( ch = get_ch ( ) ) != - && Character . isWhitespace ( ch ) ) { } if ( ch == - ) { return ; } String type = readIdentifier ( ch ) ; if ( type == null ) { type = "" ; } fScanLocation . setLineNo ( fLineno ) ; if ( type . equals ( "" ) || type . equals ( "" ) || type . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; String remainder = readIdentifier ( ch ) ; if ( remainder != null ) { remainder = remainder . trim ( ) ; } else { remainder = "" ; } if ( fObserver != null ) { if ( type . equals ( "" ) ) { fObserver . leave_preproc_conditional ( ) ; } fObserver . enter_preproc_conditional ( type , remainder ) ; } } else if ( type . equals ( "" ) ) { if ( fObserver != null ) { fObserver . leave_preproc_conditional ( ) ; fObserver . enter_preproc_conditional ( "" , "" ) ; } } else if ( type . equals ( "" ) ) { if ( fObserver != null ) { fObserver . leave_preproc_conditional ( ) ; } } else if ( fIgnoredDirectives . contains ( type ) ) { readLine ( get_ch ( ) ) ; } else if ( type . equals ( "" ) ) { String def_id = null ; if ( fScanner != null ) { fScanner . setStmtLocation ( getStmtLocation ( ) ) ; } ch = skipWhite ( get_ch ( ) ) ; def_id = readIdentifier ( ch ) ; fParamList . clear ( ) ; ch = get_ch ( ) ; if ( ch == '' ) { do { ch = skipWhite ( get_ch ( ) ) ; if ( ! ( Character . isJavaIdentifierPart ( ch ) ) ) { break ; } else { String p = readIdentifier ( ch ) ; String dflt = null ; ch = skipWhite ( get_ch ( ) ) ; if ( ch == '' ) { ch = skipWhite ( get_ch ( ) ) ; if ( ch == '' ) { dflt = readString ( ch ) ; dflt = "" + dflt + "" ; } else { startCapture ( ch ) ; while ( ( ch = get_ch ( ) ) != - && ch != '' && ch != '' ) { } unget_ch ( ch ) ; dflt = endCapture ( ) ; } } else { unget_ch ( ch ) ; } fParamList . add ( new Tuple < String , String > ( p , dflt ) ) ; } ch = skipWhite ( get_ch ( ) ) ; } while ( ch == '' ) ; if ( ch == '' ) { ch = get_ch ( ) ; } } String define = readLine ( ch ) ; if ( define == null ) { define = "" ; } int last_comment ; if ( ( last_comment = define . lastIndexOf ( "" ) ) != - ) { int lr = define . indexOf ( '' , last_comment ) ; if ( lr == - ) { define = define . substring ( , define . indexOf ( "" ) ) ; } } if ( fObserver != null ) { fObserver . preproc_define ( def_id , fParamList , define ) ; } } else if ( type . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; if ( ch == '' ) { String inc = readString_ll ( ch ) ; inc = inc . substring ( , inc . length ( ) - ) ; if ( fObserver != null ) { fObserver . preproc_include ( inc ) ; } } } else if ( type . equals ( "" ) ) { } else if ( type . equals ( "" ) ) { } else if ( type . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; String id = readIdentifier ( ch ) ; if ( id != null ) { if ( id . equals ( "" ) ) { ch = skipWhite ( get_ch ( ) ) ; id = readIdentifier ( ch ) ; } } } else if ( type . equals ( "" ) ) { } else if ( type . equals ( "" ) ) { } else { fTmpBuffer . setLength ( ) ; fTmpBuffer . append ( '' ) ; fTmpBuffer . append ( type ) ; boolean is_defined = ( fDefineProvider != null ) ? fDefineProvider . isDefined ( type , fLineno ) : false ; if ( fDefineProvider != null && ( fDefineProvider . hasParameters ( type , fLineno ) || ! is_defined ) ) { ch = get_ch ( ) ; while ( ch != - && Character . isWhitespace ( ch ) && ch != '' ) { ch = get_ch ( ) ; } if ( ch == '' ) { fTmpBuffer . append ( ( char ) ch ) ; int matchLevel = ; do { ch = get_ch ( ) ; if ( ch == '' ) { matchLevel ++ ; } else if ( ch == '' ) { matchLevel -- ; } if ( ch != - ) { fTmpBuffer . append ( ( char ) ch ) ; } } while ( ch != - && matchLevel > ) ; } else if ( is_defined ) { fDefineProvider . error ( "" + type + "" , fScanLocation . getFileName ( ) , fScanLocation . getLineNo ( ) ) ; fLog . debug ( "" + type + "" + fScanLocation . getFileName ( ) + "" + fScanLocation . getLineNo ( ) ) ; unget_ch ( ch ) ; } else { unget_ch ( ch ) ; } } } } public int get_ch ( ) { int ch = - ; if ( ! fInProcess ) { throw new RuntimeException ( "" ) ; } if ( fUngetCh != - ) { ch = fUngetCh ; fUngetCh = - ; } else { if ( fInBufferIdx >= fInBufferMax ) { try { fInBufferMax = fInput . read ( fInBuffer , , fInBuffer . length ) ; fInBufferIdx = ; } catch ( IOException e ) { } } if ( fInBufferIdx < fInBufferMax ) { ch = fInBuffer [ fInBufferIdx ++ ] ; } else { ch = - ; } if ( fLastCh == '' ) { fLineno ++ ; } fLastCh = ch ; } if ( ch != - && fCaptureEnabled ) { fCaptureBuffer . append ( ( char ) ch ) ; } return ch ; } public void unget_ch ( int ch ) { fUngetCh = ch ; if ( ch != - && fCaptureEnabled && fCaptureBuffer . length ( ) > ) { fCaptureBuffer . deleteCharAt ( fCaptureBuffer . length ( ) - ) ; } } public long getPos ( ) { return - ; } } package net . sf . sveditor . core ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdapterFactory ; public class SVProjectDataAdapter implements IAdapterFactory { @ SuppressWarnings ( "" ) public Object getAdapter ( Object adaptableObject , Class adapterType ) { if ( adaptableObject instanceof IProject ) { IProject p = ( IProject ) adaptableObject ; if ( p . getFile ( "" ) . exists ( ) ) { SVDBProjectData pd = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( p ) ; return pd ; } } return null ; } @ SuppressWarnings ( { "" } ) public Class [ ] getAdapterList ( ) { return new Class [ ] { IProject . class } ; } } package net . sf . sveditor . core ; import java . io . IOException ; import java . io . InputStream ; import java . io . StringReader ; public class StringInputStream extends InputStream { private StringReader fReader ; private int fLastC ; public StringInputStream ( String content ) { fReader = new StringReader ( content ) ; fLastC = ; } @ Override public int read ( ) throws IOException { int ret = - ; try { ret = fReader . read ( ) ; } catch ( IOException e ) { } fLastC = ret ; return ret ; } public void close ( ) throws IOException { fReader . close ( ) ; } public synchronized void mark ( int readLimit ) { try { fReader . mark ( readLimit ) ; } catch ( IOException e ) { } } public boolean markSupported ( ) { return fReader . markSupported ( ) ; } public synchronized void reset ( ) throws IOException { fReader . reset ( ) ; } @ Override public int available ( ) throws IOException { return ( fLastC != - ) ? : ; } } package net . sf . sveditor . core . text ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . templates . ITemplateParameterProvider ; public class TagProcessor { private List < ITemplateParameterProvider > fProviders ; public TagProcessor ( ) { fProviders = new ArrayList < ITemplateParameterProvider > ( ) ; } public void addParameterProvider ( ITemplateParameterProvider p ) { fProviders . add ( p ) ; } public void removeParameterProvider ( ITemplateParameterProvider p ) { fProviders . remove ( p ) ; } public String process ( String in ) { StringInputStream in_str = new StringInputStream ( in ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; try { process ( in_str , out ) ; } catch ( IOException e ) { } return out . toString ( ) ; } public int process ( InputStream in , OutputStream out ) throws IOException { int ch ; int n_replacements = ; StringBuilder sb = new StringBuilder ( ) ; while ( ( ch = in . read ( ) ) != - ) { if ( ch == '' ) { int ch2 = in . read ( ) ; if ( ch2 == '' ) { sb . setLength ( ) ; for ( int i = ; i < ; i ++ ) { if ( ( ch = in . read ( ) ) == '' || ch == - ) { break ; } sb . append ( ( char ) ch ) ; } String val = sb . toString ( ) ; if ( ch == '' ) { String key = val ; String args = null ; if ( key . indexOf ( '' ) != - ) { args = key . substring ( key . indexOf ( '' ) + ) ; key = key . substring ( , key . indexOf ( '' ) ) ; } if ( containsKey ( key ) ) { out . write ( getParameterValue ( key , args ) . getBytes ( ) ) ; n_replacements ++ ; } else { out . write ( '' ) ; out . write ( '' ) ; out . write ( val . getBytes ( ) ) ; out . write ( '' ) ; } } else { out . write ( '' ) ; out . write ( '' ) ; out . write ( val . getBytes ( ) ) ; if ( ch != - ) { out . write ( ( char ) ch ) ; } } } else { out . write ( ( char ) ch ) ; if ( ch2 != - ) { out . write ( ( char ) ch2 ) ; } } } else { out . write ( ( char ) ch ) ; } } return n_replacements ; } private boolean containsKey ( String key ) { for ( ITemplateParameterProvider p : fProviders ) { if ( p . providesParameter ( key ) ) { return true ; } } return false ; } private String getParameterValue ( String key , String args ) { for ( ITemplateParameterProvider p : fProviders ) { if ( p . providesParameter ( key ) ) { return p . getParameterValue ( key , args ) ; } } return null ; } } package net . sf . sveditor . core ; import java . io . ByteArrayOutputStream ; import java . io . InputStream ; import java . util . HashMap ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Properties ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . sax . SAXTransformerFactory ; import javax . xml . transform . sax . TransformerHandler ; import javax . xml . transform . stream . StreamResult ; import org . w3c . dom . CDATASection ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; import org . xml . sax . ErrorHandler ; import org . xml . sax . SAXException ; import org . xml . sax . SAXParseException ; public class XMLTransformUtils { public static Map < String , String > xml2Map ( String content , String root_elem_id , String item_elem_id ) throws Exception { return xml2Map ( new StringInputStream ( content ) , root_elem_id , item_elem_id ) ; } public static Map < String , String > xml2Map ( InputStream content , String root_elem_id , String item_elem_id ) throws Exception { Map < String , String > ret = new HashMap < String , String > ( ) ; DocumentBuilder b = documentBuilder ( ) ; Document doc = b . parse ( content ) ; NodeList root_list = doc . getElementsByTagName ( root_elem_id ) ; if ( root_list . getLength ( ) > ) { Element root = ( Element ) root_list . item ( ) ; NodeList item_list = root . getElementsByTagName ( item_elem_id ) ; for ( int i = ; i < item_list . getLength ( ) ; i ++ ) { Element item = ( Element ) item_list . item ( i ) ; String id = item . getAttribute ( "" ) ; String value = item . getTextContent ( ) ; ret . put ( id , value ) ; } } return ret ; } public static String map2Xml ( Map < String , String > content , String root_elem_id , String item_elem_id ) throws Exception { DocumentBuilder b = documentBuilder ( ) ; Document doc = b . newDocument ( ) ; String str = null ; SAXTransformerFactory tf = ( SAXTransformerFactory ) SAXTransformerFactory . newInstance ( ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Element root = doc . createElement ( root_elem_id ) ; doc . appendChild ( root ) ; for ( Entry < String , String > e : content . entrySet ( ) ) { Element item = doc . createElement ( item_elem_id ) ; item . setAttribute ( "" , e . getKey ( ) ) ; CDATASection data = doc . createCDATASection ( e . getValue ( ) ) ; item . appendChild ( data ) ; root . appendChild ( item ) ; } try { DOMSource ds = new DOMSource ( doc ) ; StreamResult sr = new StreamResult ( out ) ; tf . setAttribute ( "" , new Integer ( ) ) ; TransformerHandler th = tf . newTransformerHandler ( ) ; Properties format = new Properties ( ) ; format . put ( OutputKeys . METHOD , "" ) ; format . put ( OutputKeys . ENCODING , "" ) ; format . put ( OutputKeys . INDENT , "" ) ; th . getTransformer ( ) . setOutputProperties ( format ) ; th . setResult ( sr ) ; th . getTransformer ( ) . transform ( ds , sr ) ; str = out . toString ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return str ; } private static DocumentBuilder documentBuilder ( ) throws Exception { DocumentBuilder b = null ; try { DocumentBuilderFactory f = DocumentBuilderFactory . newInstance ( ) ; b = f . newDocumentBuilder ( ) ; b . setErrorHandler ( fErrorHandler ) ; } catch ( ParserConfigurationException e ) { throw e ; } return b ; } private static ErrorHandler fErrorHandler = new ErrorHandler ( ) { public void error ( SAXParseException arg0 ) throws SAXException { throw arg0 ; } public void fatalError ( SAXParseException arg0 ) throws SAXException { throw arg0 ; } public void warning ( SAXParseException arg0 ) throws SAXException { } } ; } package net . sf . sveditor . core . svf_scanner ; import java . util . HashMap ; import java . util . Map ; public class SVFCmdLineProcessor { public static int SWITCH_NO_ARGS = ; public static int SWITCH_HAS_ARG = ; public static int SWITCH_MAY_HAVE_ARG = ; private Map < String , Integer > fIgnoreSwitches ; public SVFCmdLineProcessor ( ) { fIgnoreSwitches = new HashMap < String , Integer > ( ) ; } public void addIgnoreSwitch ( String spec , int arg ) { fIgnoreSwitches . put ( spec , arg ) ; } public StringBuilder process ( String args [ ] ) { StringBuilder cmdline = new StringBuilder ( ) ; for ( int i = ; i < args . length ; i ++ ) { String arg = args [ i ] ; if ( arg . startsWith ( "" ) ) { for ( String key : fIgnoreSwitches . keySet ( ) ) { if ( arg . startsWith ( key ) ) { } } } } return cmdline ; } } package net . sf . sveditor . core . svf_scanner ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . ITextScanner ; public class SVFScanner { private LogHandle fLog ; private ITextScanner fScanner ; private List < String > fIncludePaths ; private Map < String , String > fDefineMap ; private List < String > fFilePaths ; private List < String > fLibPaths ; private Set < String > fSrcExtensions ; private List < String > fIncludedArgFiles ; public static final Map < String , Integer > fIgnoredSwitches ; public static final Set < String > fSupportedSwitches ; public static final Set < String > fRecognizedSwitches ; static { fIgnoredSwitches = new HashMap < String , Integer > ( ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fIgnoredSwitches . put ( "" , ) ; fSupportedSwitches = new HashSet < String > ( ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fSupportedSwitches . add ( "" ) ; fRecognizedSwitches = new HashSet < String > ( ) ; fRecognizedSwitches . addAll ( fIgnoredSwitches . keySet ( ) ) ; fRecognizedSwitches . addAll ( fSupportedSwitches ) ; } public SVFScanner ( ) { fIncludePaths = new ArrayList < String > ( ) ; fDefineMap = new HashMap < String , String > ( ) ; fFilePaths = new ArrayList < String > ( ) ; fLibPaths = new ArrayList < String > ( ) ; fIncludedArgFiles = new ArrayList < String > ( ) ; fSrcExtensions = new HashSet < String > ( ) ; fSrcExtensions . add ( "" ) ; fSrcExtensions . add ( "" ) ; fSrcExtensions . add ( "" ) ; fSrcExtensions . add ( "" ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public List < String > getIncludePaths ( ) { return fIncludePaths ; } public List < String > getFilePaths ( ) { return fFilePaths ; } public List < String > getLibPaths ( ) { return fLibPaths ; } public Set < String > getSrcExts ( ) { return fSrcExtensions ; } public List < String > getArgFilePaths ( ) { return fIncludedArgFiles ; } public Map < String , String > getDefineMap ( ) { return fDefineMap ; } public void scan ( ITextScanner scanner ) throws Exception { fScanner = scanner ; StringBuilder tmp = new StringBuilder ( ) ; int ch ; while ( ( ch = fScanner . skipWhite ( fScanner . get_ch ( ) ) ) != - ) { if ( ch == '' ) { tmp . setLength ( ) ; tmp . append ( ( char ) ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ch != '' && ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; if ( ch == '' ) { break ; } } fLog . debug ( "" + tmp . toString ( ) ) ; if ( tmp . toString ( ) . equals ( "" ) ) { String key , val ; tmp . setLength ( ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) && ch != '' ) { tmp . append ( ( char ) ch ) ; } key = tmp . toString ( ) ; if ( ch == '' ) { tmp . setLength ( ) ; ch = fScanner . get_ch ( ) ; if ( ch == '' ) { val = fScanner . readString ( ch ) ; } else { tmp . append ( ( char ) ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; } val = tmp . toString ( ) ; } } else { val = "" ; } if ( fDefineMap . containsKey ( key ) ) { fDefineMap . remove ( key ) ; } fDefineMap . put ( key , val ) ; } else if ( tmp . toString ( ) . equals ( "" ) ) { ch = fScanner . skipWhite ( fScanner . get_ch ( ) ) ; tmp . setLength ( ) ; tmp . append ( ( char ) ch ) ; do { while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; } fIncludePaths . add ( tmp . toString ( ) ) ; } while ( ch == '' ) ; fScanner . unget_ch ( ch ) ; } else { fLog . debug ( "" + tmp . toString ( ) ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { } fScanner . unget_ch ( ch ) ; } } else if ( ch == '' ) { String key = null , val = null ; tmp . setLength ( ) ; tmp . append ( ( char ) ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; } key = tmp . toString ( ) ; if ( fIgnoredSwitches . containsKey ( key ) ) { int ignore_arg_count = fIgnoredSwitches . get ( key ) ; for ( int i = ; i < ignore_arg_count ; i ++ ) { while ( ( ch = fScanner . get_ch ( ) ) != - && Character . isWhitespace ( ch ) ) { } fScanner . unget_ch ( ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { } fScanner . unget_ch ( ch ) ; } } else if ( key . equals ( "" ) || key . toLowerCase ( ) . equals ( "" ) ) { ch = fScanner . skipWhite ( ch ) ; key = fScanner . readIdentifier ( ch ) ; ch = fScanner . get_ch ( ) ; if ( ch == '' ) { ch = fScanner . get_ch ( ) ; if ( ch == '' ) { val = fScanner . readString ( ch ) ; } else { val = fScanner . readIdentifier ( ch ) ; } } else { val = "" ; fScanner . unget_ch ( ch ) ; } if ( fDefineMap . containsKey ( key ) ) { fDefineMap . remove ( key ) ; } fDefineMap . put ( key , val ) ; } else if ( key . equals ( "" ) || key . toLowerCase ( ) . equals ( "" ) ) { ch = fScanner . skipWhite ( fScanner . get_ch ( ) ) ; tmp . setLength ( ) ; tmp . append ( ( char ) ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; } fIncludePaths . add ( tmp . toString ( ) ) ; } else if ( key . equals ( "" ) || key . equals ( "" ) ) { ch = fScanner . skipWhite ( ch ) ; tmp . setLength ( ) ; while ( ch != - && ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; ch = fScanner . get_ch ( ) ; } fScanner . unget_ch ( ch ) ; fIncludedArgFiles . add ( tmp . toString ( ) ) ; } else if ( key . equals ( "" ) ) { ch = fScanner . skipWhite ( ch ) ; tmp . setLength ( ) ; while ( ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; ch = fScanner . get_ch ( ) ; } fScanner . unget_ch ( ch ) ; fFilePaths . add ( tmp . toString ( ) ) ; } else if ( key . equals ( "" ) ) { ch = fScanner . skipWhite ( ch ) ; tmp . setLength ( ) ; tmp . append ( ( char ) ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; } fLibPaths . add ( tmp . toString ( ) ) ; } } else if ( ch == '' ) { while ( ( ch = fScanner . get_ch ( ) ) != - && ch != '' ) { } fScanner . unget_ch ( ch ) ; continue ; } else { if ( ch == '' ) { int ch2 = fScanner . get_ch ( ) ; if ( ch2 == '' ) { while ( ( ch = fScanner . get_ch ( ) ) != - && ch != '' ) { } fScanner . unget_ch ( ch ) ; continue ; } else if ( ch2 == '' ) { int match [ ] = { - , - } ; do { match [ ] = match [ ] ; match [ ] = fScanner . get_ch ( ) ; } while ( ( match [ ] != - || match [ ] != - ) && match [ ] != '' || match [ ] != '' ) ; continue ; } else { fScanner . unget_ch ( ch2 ) ; } } tmp . setLength ( ) ; tmp . append ( ( char ) ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { tmp . append ( ( char ) ch ) ; } if ( ! tmp . toString ( ) . matches ( "" ) ) { fFilePaths . add ( tmp . toString ( ) ) ; } } } } } package net . sf . sveditor . core ; public class Tuple < T1 , T2 > { private T1 first ; private T2 second ; public Tuple ( T1 it1 , T2 it2 ) { first = it1 ; second = it2 ; } public T1 first ( ) { return first ; } public void setFirst ( T1 f ) { first = f ; } public T2 second ( ) { return second ; } public void setSecond ( T2 s ) { second = s ; } } package net . sf . sveditor . core ; import java . util . ArrayList ; import java . util . Comparator ; import java . util . List ; public class SortUtils { public static List < String > sortStringList ( List < String > l , boolean ascending ) { List < String > ret = new ArrayList < String > ( ) ; ret . addAll ( l ) ; return ret ; } @ SuppressWarnings ( { "" , "" } ) public static void sort ( List l , Comparator c , boolean ascending ) { for ( int i = ; i < l . size ( ) ; i ++ ) { for ( int j = i + ; j < l . size ( ) ; j ++ ) { Object o_i = l . get ( i ) ; Object o_j = l . get ( j ) ; int r ; if ( ( r = c . compare ( o_i , o_j ) ) != ) { if ( r > && ascending ) { l . set ( i , o_j ) ; l . set ( j , o_i ) ; } } } } } } package net . sf . sveditor . core . srcgen ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcClassParam ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . search . SVDBFindByName ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . core . scanutils . StringTextScanner ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class NewClassGenerator { public void generate ( ISVDBIndexIterator index_it , final IFile file_path , String clsname , String superclass , boolean implement_new , IProgressMonitor monitor ) { String subst_filename = "" ; if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( "" , ) ; subst_filename = SVCharacter . toSVIdentifier ( file_path . getName ( ) ) ; String template = "" + "" + file_path . getName ( ) + "" + "" + "" + subst_filename + "" + "" + subst_filename + "" + "" ; template += "" ; template += "" + clsname + "" ; template += "" ; template += "" ; template += "" ; template += "" + clsname ; SVDBClassDecl superclass_decl = null ; if ( superclass != null && ! superclass . trim ( ) . equals ( "" ) ) { monitor . subTask ( "" ) ; template += "" + superclass ; if ( index_it != null ) { SVDBFindByName finder = new SVDBFindByName ( index_it ) ; List < ISVDBItemBase > result = finder . find ( superclass , SVDBItemType . ClassDecl ) ; if ( result . size ( ) > && result . get ( ) . getType ( ) == SVDBItemType . ClassDecl ) { superclass_decl = ( SVDBClassDecl ) result . get ( ) ; } } } monitor . worked ( ) ; if ( superclass_decl != null ) { if ( superclass_decl . getParameters ( ) != null && superclass_decl . getParameters ( ) . size ( ) > ) { template += "" ; List < SVDBModIfcClassParam > params = superclass_decl . getParameters ( ) ; for ( int i = ; i < params . size ( ) ; i ++ ) { template += params . get ( i ) . getName ( ) ; if ( i + < params . size ( ) ) { template += "" ; } } template += "" ; } } template += "" ; if ( implement_new ) { monitor . subTask ( "" ) ; SVDBTask new_func = null ; if ( superclass_decl != null ) { for ( ISVDBChildItem it : superclass_decl . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . Function && it instanceof ISVDBNamedItem && ( ( ISVDBNamedItem ) it ) . getName ( ) . equals ( "" ) ) { new_func = ( SVDBTask ) it ; break ; } } } if ( new_func != null ) { if ( new_func . getParams ( ) != null && new_func . getParams ( ) . size ( ) > ) { List < SVDBParamPortDecl > params = new_func . getParams ( ) ; template += "" ; template += "" ; for ( int i = ; i < params . size ( ) ; i ++ ) { SVDBParamPortDecl p = params . get ( i ) ; template += p . getTypeName ( ) + "" ; for ( ISVDBChildItem c : p . getChildren ( ) ) { template += ( ( SVDBVarDeclItem ) c ) . getName ( ) ; template += "" ; } } if ( template . endsWith ( "" ) ) { template = template . substring ( , template . length ( ) - ) ; } template += "" ; template += "" ; for ( int i = ; i < params . size ( ) ; i ++ ) { SVDBParamPortDecl p = params . get ( i ) ; for ( ISVDBChildItem c : p . getChildren ( ) ) { template += ( ( SVDBVarDeclItem ) c ) . getName ( ) ; template += "" ; } } if ( template . endsWith ( "" ) ) { template = template . substring ( , template . length ( ) - ) ; } template += "" ; } else { template += "" ; template += "" ; } } else { template += "" ; template += "" ; } template += "" ; template += "" ; } monitor . worked ( ) ; template += "" ; template += "" ; template += "" + "" + subst_filename + "" ; monitor . subTask ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( new StringBuilder ( template ) ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; final StringInputStream in = new StringInputStream ( indenter . indent ( ) ) ; monitor . worked ( ) ; try { if ( file_path . exists ( ) ) { file_path . setContents ( in , true , true , new NullProgressMonitor ( ) ) ; } else { file_path . create ( in , true , new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { } monitor . done ( ) ; } } package net . sf . sveditor . core . srcgen ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBFieldItem ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; public class MethodGenerator { public String generate ( SVDBTask tf ) { StringBuilder new_tf = new StringBuilder ( ) ; String classname = "" ; String tf_type = ( tf . getType ( ) == SVDBItemType . Task ) ? "" : "" ; if ( tf . getParent ( ) != null && tf . getParent ( ) . getType ( ) == SVDBItemType . ClassDecl ) { classname = ( ( ISVDBNamedItem ) tf . getParent ( ) ) . getName ( ) ; } new_tf . append ( "" + "" + tf_type + "" + tf . getName ( ) + "" + "" + "" + classname + "" + "" ) ; new_tf . append ( "" ) ; if ( ( tf . getAttr ( ) & SVDBFieldItem . FieldAttr_Virtual ) != ) { new_tf . append ( "" ) ; } if ( tf . getType ( ) == SVDBItemType . Function ) { SVDBTypeInfo ti = ( ( SVDBFunction ) tf ) . getReturnType ( ) ; new_tf . append ( "" ) ; if ( ti != null ) { new_tf . append ( ti . toString ( ) ) ; new_tf . append ( "" ) ; } } else { new_tf . append ( "" ) ; } new_tf . append ( tf . getName ( ) ) ; new_tf . append ( "" ) ; for ( int i = ; i < tf . getParams ( ) . size ( ) ; i ++ ) { SVDBParamPortDecl p = tf . getParams ( ) . get ( i ) ; SVDBTypeInfo ti = p . getTypeInfo ( ) ; if ( ( p . getDir ( ) & SVDBParamPortDecl . Direction_Const ) != ) { new_tf . append ( "" ) ; } if ( ( p . getDir ( ) & SVDBParamPortDecl . Direction_Ref ) != ) { new_tf . append ( "" ) ; } else if ( ( p . getDir ( ) & SVDBParamPortDecl . Direction_Var ) != ) { new_tf . append ( "" ) ; } else if ( ( p . getDir ( ) & SVDBParamPortDecl . Direction_Input ) != ) { new_tf . append ( "" ) ; } else if ( ( p . getDir ( ) & SVDBParamPortDecl . Direction_Output ) != ) { new_tf . append ( "" ) ; } else if ( ( p . getDir ( ) & SVDBParamPortDecl . Direction_Inout ) != ) { new_tf . append ( "" ) ; } new_tf . append ( ti . toString ( ) ) ; new_tf . append ( "" ) ; for ( ISVDBChildItem c : p . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; new_tf . append ( vi . getName ( ) ) ; if ( vi . getArrayDim ( ) != null ) { for ( SVDBVarDimItem di : vi . getArrayDim ( ) ) { switch ( di . getDimType ( ) ) { case Associative : new_tf . append ( "" ) ; new_tf . append ( di . getTypeInfo ( ) . toString ( ) ) ; new_tf . append ( "" ) ; break ; case Queue : new_tf . append ( "" ) ; break ; case Sized : new_tf . append ( "" ) ; new_tf . append ( di . getExpr ( ) . toString ( ) ) ; new_tf . append ( "" ) ; break ; case Unsized : new_tf . append ( "" ) ; break ; } } } new_tf . append ( "" ) ; } } if ( tf . getParams ( ) . size ( ) > ) { new_tf . setLength ( new_tf . length ( ) - ) ; } new_tf . append ( "" ) ; new_tf . append ( "" ) ; if ( tf . getType ( ) == SVDBItemType . Function ) { new_tf . append ( "" ) ; } else { new_tf . append ( "" ) ; } new_tf . append ( "" ) ; return new_tf . toString ( ) ; } } package net . sf . sveditor . core . srcgen ; import java . util . ArrayList ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . search . SVDBFindDefaultNameMatcher ; import net . sf . sveditor . core . db . search . SVDBFindSuperClass ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class OverrideMethodsFinder implements ILogLevel { private SVDBClassDecl fLeafClass ; private Map < SVDBClassDecl , List < SVDBTask > > fClassMap ; private ISVDBIndexIterator fIndexIt ; private LogHandle fLog ; public OverrideMethodsFinder ( SVDBClassDecl leaf_class , ISVDBIndexIterator index_it ) { fLog = LogFactory . getLogHandle ( "" ) ; fLeafClass = leaf_class ; fClassMap = new LinkedHashMap < SVDBClassDecl , List < SVDBTask > > ( ) ; fIndexIt = index_it ; findClasses ( ) ; } public Set < SVDBClassDecl > getClassSet ( ) { return fClassMap . keySet ( ) ; } public List < SVDBTask > getMethods ( SVDBClassDecl cls ) { return fClassMap . get ( cls ) ; } private void findClasses ( ) { fClassMap . clear ( ) ; SVDBClassDecl cl = fLeafClass ; SVDBFindSuperClass finder_super = new SVDBFindSuperClass ( fIndexIt , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; fLog . debug ( LEVEL_MID , "" + SVDBItem . getName ( cl ) ) ; while ( cl != null ) { cl = finder_super . find ( cl ) ; if ( cl != null ) { fLog . debug ( LEVEL_MID , "" + SVDBItem . getName ( cl ) ) ; List < SVDBTask > overrides = getClassOverrideTargets ( cl ) ; if ( overrides . size ( ) > ) { fClassMap . put ( cl , getClassOverrideTargets ( cl ) ) ; } } } } private List < SVDBTask > getClassOverrideTargets ( SVDBClassDecl cls ) { List < SVDBTask > ret = new ArrayList < SVDBTask > ( ) ; for ( ISVDBItemBase it : cls . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . Function || it . getType ( ) == SVDBItemType . Task ) { SVDBTask tf = ( SVDBTask ) it ; if ( ( tf . getAttr ( ) & SVDBTask . FieldAttr_Local ) == ) { if ( ! existsInClass ( it , fLeafClass ) ) { ret . add ( tf ) ; } } } } return ret ; } private boolean existsInClass ( ISVDBItemBase it , SVDBClassDecl cls ) { for ( ISVDBItemBase it_t : cls . getChildren ( ) ) { if ( it instanceof ISVDBNamedItem && it_t instanceof ISVDBNamedItem && ( ( ISVDBNamedItem ) it_t ) . getName ( ) . equals ( ( ( ISVDBNamedItem ) it ) . getName ( ) ) ) { return true ; } } return false ; } } package net . sf . sveditor . core . srcgen ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . core . scanutils . StringTextScanner ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class NewInterfaceGenerator { public void generate ( ISVDBIndexIterator index_it , final IFile file_path , String interfacename , IProgressMonitor monitor ) { String subst_filename = "" ; if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( "" , ) ; subst_filename = SVCharacter . toSVIdentifier ( file_path . getName ( ) ) ; String template = "" + "" + file_path . getName ( ) + "" + "" + "" + subst_filename + "" + "" + subst_filename + "" + "" ; template += "" ; template += "" + interfacename + "" ; template += "" ; template += "" ; template += "" ; template += "" + interfacename ; monitor . worked ( ) ; template += "" ; monitor . worked ( ) ; template += "" ; template += "" ; template += "" + "" + subst_filename + "" ; monitor . subTask ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( new StringBuilder ( template ) ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; final StringInputStream in = new StringInputStream ( indenter . indent ( ) ) ; monitor . worked ( ) ; try { if ( file_path . exists ( ) ) { file_path . setContents ( in , true , true , new NullProgressMonitor ( ) ) ; } else { file_path . create ( in , true , new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { } monitor . done ( ) ; } } package net . sf . sveditor . core . srcgen ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . core . scanutils . StringTextScanner ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class NewPackageGenerator { public void generate ( ISVDBIndexIterator index_it , final IFile file_path , String pkg_name , IProgressMonitor monitor ) { String subst_filename = "" ; if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( "" , ) ; subst_filename = SVCharacter . toSVIdentifier ( file_path . getName ( ) ) ; String template = "" + "" + file_path . getName ( ) + "" + "" + "" + subst_filename + "" + "" + subst_filename + "" + "" ; template += "" ; template += "" + pkg_name + "" ; template += "" ; template += "" ; template += "" ; template += "" + pkg_name ; monitor . worked ( ) ; template += "" ; monitor . worked ( ) ; template += "" ; template += "" ; template += "" + "" + subst_filename + "" ; monitor . subTask ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( new StringBuilder ( template ) ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; final StringInputStream in = new StringInputStream ( indenter . indent ( ) ) ; monitor . worked ( ) ; try { if ( file_path . exists ( ) ) { file_path . setContents ( in , true , true , new NullProgressMonitor ( ) ) ; } else { file_path . create ( in , true , new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { } monitor . done ( ) ; } } package net . sf . sveditor . core . srcgen ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . core . scanutils . StringTextScanner ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class NewModuleGenerator { public void generate ( ISVDBIndexIterator index_it , final IFile file_path , String modulename , IProgressMonitor monitor ) { String subst_filename = "" ; if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( "" , ) ; subst_filename = SVCharacter . toSVIdentifier ( file_path . getName ( ) ) ; String template = "" + "" + file_path . getName ( ) + "" + "" + "" + subst_filename + "" + "" + subst_filename + "" + "" ; template += "" ; template += "" + modulename + "" ; template += "" ; template += "" ; template += "" ; template += "" + modulename ; monitor . worked ( ) ; template += "" ; monitor . worked ( ) ; template += "" ; template += "" ; template += "" + "" + subst_filename + "" ; monitor . subTask ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( new StringBuilder ( template ) ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; final StringInputStream in = new StringInputStream ( indenter . indent ( ) ) ; monitor . worked ( ) ; try { if ( file_path . exists ( ) ) { file_path . setContents ( in , true , true , new NullProgressMonitor ( ) ) ; } else { file_path . create ( in , true , new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { } monitor . done ( ) ; } } package net . sf . sveditor . core ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IResourceDeltaVisitor ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; public class SVTodoScanner implements IResourceChangeListener , IResourceDeltaVisitor { public SVTodoScanner ( ) { ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( this ) ; } public void dispose ( ) { ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( this ) ; } public void resourceChanged ( IResourceChangeEvent event ) { if ( event . getDelta ( ) != null ) { try { event . getDelta ( ) . accept ( this ) ; } catch ( CoreException e ) { } } } public boolean visit ( IResourceDelta delta ) throws CoreException { if ( delta . getResource ( ) instanceof IFile ) { IFile file = ( IFile ) delta . getResource ( ) ; if ( isSVFile ( file ) ) { file . deleteMarkers ( IMarker . TASK , true , IResource . DEPTH_ONE ) ; } } return true ; } private static final String suffixes [ ] = { "" , "" , "" , "" , "" , "" } ; private boolean isSVFile ( IFile f ) { for ( String s : suffixes ) { if ( f . getName ( ) . endsWith ( s ) ) { return true ; } } return false ; } } package net . sf . sveditor . core ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectNature ; import org . eclipse . core . runtime . CoreException ; public class SVProjectNature implements IProjectNature { private IProject fProject ; public void configure ( ) throws CoreException { } public void deconfigure ( ) throws CoreException { } public IProject getProject ( ) { return fProject ; } public void setProject ( IProject project ) { fProject = project ; } } package net . sf . sveditor . core . scanutils ; public class StringTextScanner extends AbstractTextScanner implements IRandomAccessTextScanner { private StringBuilder fStr ; private int fIdx ; private int fLimit ; private int fUngetCh ; public StringTextScanner ( StringTextScanner scanner , int idx ) { fStr = scanner . getStorage ( ) ; fIdx = idx ; fLimit = - ; fUngetCh = - ; } public StringTextScanner ( StringTextScanner scanner ) { fStr = scanner . getStorage ( ) ; fIdx = scanner . getOffset ( ) ; fLimit = - ; fUngetCh = - ; } public StringTextScanner ( StringTextScanner scanner , int idx , int limit ) { fStr = scanner . getStorage ( ) ; fIdx = idx ; fLimit = limit ; fUngetCh = - ; } public StringTextScanner ( StringBuilder str ) { init ( str ) ; fUngetCh = - ; } public StringTextScanner ( String str ) { this ( new StringBuilder ( str ) ) ; } public StringTextScanner ( String str , int idx ) { this ( new StringBuilder ( str ) , idx ) ; } public StringTextScanner ( StringBuilder str , int idx ) { init ( str , idx ) ; } public void init ( StringBuilder str ) { init ( str , ) ; } public void init ( StringBuilder str , int idx ) { fStr = str ; fIdx = idx ; fLimit = - ; fUngetCh = - ; } public String get_str ( long start , int length ) { if ( length == ) { return "" ; } else { return fStr . substring ( ( int ) start , ( int ) ( start + length - ) ) ; } } public int charAt ( int pos ) { return fStr . charAt ( pos ) ; } public long getPos ( ) { return fIdx ; } public void seek ( long pos ) { fIdx = ( int ) pos ; } public int get_ch ( ) { int ch = - ; if ( fUngetCh != - ) { ch = fUngetCh ; fUngetCh = - ; return ch ; } else if ( fIdx < fStr . length ( ) && ( fLimit == - || fIdx < fLimit ) ) { ch = fStr . charAt ( fIdx ) ; fIdx ++ ; } if ( ch != - && fCaptureEnabled ) { fCaptureBuffer . append ( ( char ) ch ) ; } fLinepos ++ ; if ( fLastCh == '' ) { fLineno ++ ; fLinepos = ; } fLastCh = ch ; return ch ; } public void unget_ch ( int ch ) { fUngetCh = ch ; } public int getOffset ( ) { return fIdx ; } public void seek ( int idx ) { fIdx = idx ; } public StringBuilder getStorage ( ) { return fStr ; } public int getLimit ( ) { return ( fLimit != - ) ? fLimit : fStr . length ( ) ; } private void update_idx_replace ( int start , int end , int len ) { if ( start < fIdx ) { fIdx += ( len - ( end - start ) ) ; } if ( fLimit != - ) { fLimit += ( len - ( end - start ) ) ; } } public void replace ( int start , int end , String replace ) { try { fStr . replace ( start , end , replace ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; System . out . println ( "" + start + "" + end + "" + replace + "" ) ; } update_idx_replace ( start , end , replace . length ( ) ) ; } private void update_idx_delete ( int start , int end ) { if ( start < fIdx ) { if ( end > fIdx ) { fIdx -= ( fIdx - start ) ; } else { fIdx -= ( end - start ) ; } } if ( fLimit != - ) { fLimit -= ( end - start ) ; } } public void delete ( int start , int end ) { fStr . delete ( start , end ) ; update_idx_delete ( start , end ) ; } public String substring ( int start , int end ) { if ( end > fStr . length ( ) ) { System . out . println ( "" + end + "" + fStr . length ( ) ) ; } return fStr . substring ( start , end ) ; } public String substring ( int start ) { return fStr . substring ( start ) ; } public ScanLocation getLocation ( ) { return new ScanLocation ( "" , fLineno , fLinepos ) ; } } package net . sf . sveditor . core . scanutils ; public interface ITextScanner { int get_ch ( ) ; void unget_ch ( int ch ) ; int skipWhite ( int ch ) ; String readIdentifier ( int ch ) ; void startCapture ( int ch ) ; String endCapture ( ) ; int skipPastMatch ( String pair ) ; String readString ( int ch ) ; ScanLocation getLocation ( ) ; long getPos ( ) ; } package net . sf . sveditor . core . scanutils ; public interface IBIDITextScanner extends IRandomAccessTextScanner { void setScanFwd ( boolean scan_fwd ) ; boolean getScanFwd ( ) ; } package net . sf . sveditor . core . scanutils ; import java . io . IOException ; import java . io . InputStream ; public class InputStreamTextScanner extends AbstractTextScanner { private InputStream fInput ; private String fFilename ; private int fUngetCh ; private byte fBuffer [ ] ; private int fBufferIdx ; private int fBufferMax ; private long fPos ; public InputStreamTextScanner ( InputStream in , String filename ) { super ( ) ; fInput = in ; fFilename = filename ; fUngetCh = - ; fBuffer = new byte [ * ] ; fBufferIdx = ; fBufferMax = ; fPos = ; } public ScanLocation getLocation ( ) { return new ScanLocation ( fFilename , fLineno , fLinepos ) ; } public int get_ch ( ) { int ch = - ; if ( fUngetCh != - ) { ch = fUngetCh ; fUngetCh = - ; fPos ++ ; return ch ; } if ( fBufferIdx >= fBufferMax ) { fBufferIdx = ; fBufferMax = ; try { fBufferMax = fInput . read ( fBuffer , , fBuffer . length ) ; } catch ( IOException e ) { } } if ( fBufferIdx < fBufferMax ) { ch = fBuffer [ fBufferIdx ++ ] ; } fLinepos ++ ; if ( fLastCh == '' ) { fLineno ++ ; fLinepos = ; } fLastCh = ch ; fPos ++ ; return ch ; } public void unget_ch ( int ch ) { fUngetCh = ch ; if ( fUngetCh != - ) { fPos -- ; } } public long getPos ( ) { return fPos ; } } package net . sf . sveditor . core . scanutils ; public class ScanLocation implements IScanLocation { private String fFile ; private int fLineno ; private int fLinepos ; public ScanLocation ( String file , int lineno , int linepos ) { fFile = file ; fLineno = lineno ; fLinepos = linepos ; } public String getFileName ( ) { return fFile ; } public void setFileName ( String name ) { fFile = name ; } public int getLineNo ( ) { return fLineno ; } public void setLineNo ( int num ) { fLineno = num ; } public int getLinePos ( ) { return fLinepos ; } public void setLinePos ( int pos ) { fLinepos = pos ; } } package net . sf . sveditor . core . scanutils ; import java . util . ArrayList ; import java . util . List ; public class StringBIDITextScanner extends AbstractTextScanner implements IBIDITextScanner { private String fData ; private int fIdx ; private int fUngetCh ; List < Integer > fLineOffsets ; public StringBIDITextScanner ( String data ) { fData = data ; fIdx = ; fUngetCh = - ; fLineOffsets = new ArrayList < Integer > ( ) ; fLineOffsets . add ( ) ; for ( int i = ; i < fData . length ( ) ; i ++ ) { if ( fData . charAt ( i ) == '' ) { fLineOffsets . add ( i + ) ; } } } public void setScanFwd ( boolean scanFwd ) { if ( fScanFwd != scanFwd ) { fUngetCh = - ; } fScanFwd = scanFwd ; } public int get_ch ( ) { int ret = - ; if ( fUngetCh != - ) { ret = fUngetCh ; fUngetCh = - ; } else { if ( fScanFwd ) { if ( fIdx < fData . length ( ) ) { ret = fData . charAt ( fIdx ) ; fIdx ++ ; } } else { if ( ( fIdx - ) >= && fData . length ( ) > ) { if ( fIdx >= fData . length ( ) ) { fIdx = fData . length ( ) - ; } ret = fData . charAt ( fIdx ) ; fIdx -- ; } } } return ret ; } public ScanLocation getLocation ( ) { int lineno = - ; int linepos = - ; for ( int i = ; i < fLineOffsets . size ( ) ; i ++ ) { int pos = fLineOffsets . get ( i ) ; if ( fIdx <= pos ) { lineno = i ; linepos = pos ; break ; } } return new ScanLocation ( "" , lineno , linepos ) ; } public void unget_ch ( int ch ) { if ( fScanFwd ) { fIdx -- ; } else { fIdx ++ ; } } public String get_str ( long start , int length ) { return fData . substring ( ( int ) start , ( int ) start + length ) ; } public long getPos ( ) { return fIdx ; } public void seek ( long pos ) { fIdx = ( int ) pos ; } public String getContent ( ) { return fData ; } } package net . sf . sveditor . core . scanutils ; public interface IScanLocation { } package net . sf . sveditor . core . scanutils ; public interface IRandomAccessTextScanner extends ITextScanner { void seek ( long pos ) ; String get_str ( long start , int length ) ; } package net . sf . sveditor . core . scanutils ; import net . sf . sveditor . core . scanner . SVCharacter ; public abstract class AbstractTextScanner implements ITextScanner { protected StringBuilder fTmpBuffer ; protected StringBuilder fCaptureBuffer ; protected boolean fCaptureEnabled ; protected int fLineno ; protected int fLinepos ; protected int fLastCh ; protected boolean fScanFwd ; public AbstractTextScanner ( ) { fTmpBuffer = new StringBuilder ( ) ; fCaptureBuffer = new StringBuilder ( ) ; fCaptureEnabled = false ; fScanFwd = true ; fLastCh = - ; fLineno = ; fLinepos = ; } public void init ( ) { fCaptureEnabled = false ; } public boolean getScanFwd ( ) { return fScanFwd ; } public void setScanFwd ( boolean scanFwd ) { fScanFwd = scanFwd ; } public int skipWhite ( int ch ) { while ( Character . isWhitespace ( ch ) || ch == '' ) { int tmp = get_ch ( ) ; if ( ch == '' && ( tmp != '' && tmp != '' ) ) { unget_ch ( tmp ) ; return ch ; } ch = tmp ; } return ch ; } public String readIdentifier ( int ci ) { fTmpBuffer . setLength ( ) ; if ( fScanFwd ) { if ( ! SVCharacter . isSVIdentifierStart ( ci ) ) { unget_ch ( ci ) ; return null ; } boolean in_ref = false ; int last_ci = ci ; fTmpBuffer . append ( ( char ) ci ) ; while ( ( ci = get_ch ( ) ) != - && ( SVCharacter . isSVIdentifierPart ( ci ) || ci == '' || ( last_ci == '' && ci == '' ) || ( in_ref && ci == '' ) ) ) { if ( ci == '' ) { int c2 = get_ch ( ) ; if ( c2 == '' ) { fTmpBuffer . append ( "" ) ; } else { unget_ch ( c2 ) ; break ; } } else { fTmpBuffer . append ( ( char ) ci ) ; } in_ref |= ( ci == '' && last_ci == '' ) ; in_ref &= ! ( in_ref && ci == '' ) ; last_ci = ci ; } unget_ch ( ci ) ; while ( fTmpBuffer . length ( ) > && fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { unget_ch ( '' ) ; fTmpBuffer . setLength ( fTmpBuffer . length ( ) - ) ; } } else { if ( ! SVCharacter . isSVIdentifierPart ( ci ) ) { unget_ch ( ci ) ; return null ; } fTmpBuffer . append ( ( char ) ci ) ; while ( ( ci = get_ch ( ) ) != - && ( SVCharacter . isSVIdentifierPart ( ci ) || ci == '' ) ) { fTmpBuffer . append ( ( char ) ci ) ; } unget_ch ( ci ) ; } return ( fTmpBuffer . length ( ) > ) ? fTmpBuffer . toString ( ) : null ; } public String readPreProcIdentifier ( int ci ) { fTmpBuffer . setLength ( ) ; if ( ! SVCharacter . isSVIdentifierStart ( ci ) ) { unget_ch ( ci ) ; return null ; } fTmpBuffer . append ( ( char ) ci ) ; while ( ( ci = get_ch ( ) ) != - && SVCharacter . isSVIdentifierPart ( ci ) ) { fTmpBuffer . append ( ( char ) ci ) ; } unget_ch ( ci ) ; return ( fTmpBuffer . length ( ) > ) ? fTmpBuffer . toString ( ) : null ; } public String readString ( int ch ) { fTmpBuffer . setLength ( ) ; int last_ch = - ; if ( ch != '' ) { return null ; } ch = get_ch ( ) ; while ( ( ( ch != '' && ch != '' ) || last_ch == '' ) && ch != - ) { if ( last_ch == '' && ch == '' ) { if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setCharAt ( fTmpBuffer . length ( ) - , '' ) ; } } else if ( last_ch == '' && ch == '' ) { if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setLength ( fTmpBuffer . length ( ) - ) ; } if ( fTmpBuffer . charAt ( fTmpBuffer . length ( ) - ) == '' ) { fTmpBuffer . setCharAt ( fTmpBuffer . length ( ) - , '' ) ; } } else { fTmpBuffer . append ( ( char ) ch ) ; } if ( ch != '' ) { last_ch = ch ; } ch = get_ch ( ) ; } return fTmpBuffer . toString ( ) ; } public void startCapture ( int ch ) { fCaptureEnabled = true ; fCaptureBuffer . setLength ( ) ; if ( ch != - ) { fCaptureBuffer . append ( ( char ) ch ) ; } } public String endCapture ( ) { fCaptureEnabled = false ; return fCaptureBuffer . toString ( ) ; } public int skipPastMatch ( String pair ) { int begin = pair . charAt ( ) ; int end = pair . charAt ( ) ; int matchLevel = ; int ch ; do { ch = get_ch ( ) ; if ( ch == begin ) { matchLevel ++ ; } else if ( ch == end ) { matchLevel -- ; } } while ( matchLevel > && ch != - ) ; return get_ch ( ) ; } } package net . sf . sveditor . core . expr . eval ; import java . math . BigInteger ; import net . sf . sveditor . core . db . expr . SVDBBinaryExpr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; import net . sf . sveditor . core . db . expr . SVDBLiteralExpr ; public class SVIntegerExprEvaluator { private IValueProvider fValueProvider ; public SVIntegerExprEvaluator ( IValueProvider provider ) { fValueProvider = provider ; } public BigInteger evaluate ( SVDBExpr expr ) throws Exception { switch ( expr . getType ( ) ) { case LiteralExpr : { SVDBLiteralExpr literal = ( SVDBLiteralExpr ) expr ; return parse_literal ( literal ) ; } case BinaryExpr : { SVDBBinaryExpr binary = ( SVDBBinaryExpr ) expr ; return evaluate_binary ( evaluate ( binary . getLhs ( ) ) , binary . getOp ( ) , evaluate ( binary . getRhs ( ) ) ) ; } case IdentifierExpr : { SVDBIdentifierExpr id = ( SVDBIdentifierExpr ) expr ; if ( fValueProvider != null ) { return fValueProvider . get_value ( id . getId ( ) ) ; } else { throw new Exception ( "" + id . getId ( ) + "" ) ; } } default : throw new Exception ( "" + expr . getType ( ) ) ; } } public BigInteger parse_literal ( SVDBLiteralExpr literal ) throws Exception { int radix = ; String value = literal . getValue ( ) ; if ( value . indexOf ( '' ) != - ) { int ind = value . indexOf ( '' ) ; int radix_c = Character . toLowerCase ( value . charAt ( ind - ) ) ; value = value . substring ( ind + ) ; if ( radix_c == '' ) { radix = ; } else if ( radix_c == '' ) { radix = ; } else if ( radix_c == '' ) { radix = ; } else if ( radix_c == '' ) { radix = ; } else { throw new Exception ( "" + ( char ) radix_c + "" + literal . getValue ( ) + "" ) ; } } return new BigInteger ( value , radix ) ; } public BigInteger evaluate_binary ( BigInteger lhs , String op , BigInteger rhs ) throws Exception { if ( op . equals ( "" ) ) { return lhs . add ( rhs ) ; } else if ( op . equals ( "" ) ) { return lhs . subtract ( rhs ) ; } else if ( op . equals ( "" ) ) { return lhs . multiply ( rhs ) ; } else { throw new Exception ( "" + op + "" ) ; } } } package net . sf . sveditor . core . expr . eval ; import java . math . BigInteger ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVDBIndexValueProvider implements IValueProvider { private ISVDBIndexIterator fIndexIt ; public SVDBIndexValueProvider ( ISVDBIndexIterator index_it ) { fIndexIt = index_it ; } public BigInteger get_value ( String name ) throws Exception { ISVDBItemIterator item_it = fIndexIt . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( item_it . hasNext ( ) ) { ISVDBItemBase it = item_it . nextItem ( ) ; if ( it . getType ( ) == SVDBItemType . TypedefStmt ) { SVDBTypedefStmt typedef = ( SVDBTypedefStmt ) it ; if ( typedef . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoEnum ) { SVDBTypeInfoEnum enum_t = ( SVDBTypeInfoEnum ) typedef . getTypeInfo ( ) ; } } } throw new Exception ( "" + name + "" ) ; } } package net . sf . sveditor . core . expr . eval ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVExprComparator { public synchronized boolean is_equal ( SVDBExpr expr_1 , SVDBExpr expr_2 ) { return false ; } } package net . sf . sveditor . core . expr . eval ; import java . math . BigInteger ; public interface IValueProvider { BigInteger get_value ( String name ) throws Exception ; } package net . sf . sveditor . core . diagrams ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModuleDecl ; import net . sf . sveditor . core . db . index . ISVDBIndex ; public class ModuleDiagModelFactory extends AbstractDiagModelFactory { private SVDBModuleDecl fModuleDecl ; public ModuleDiagModelFactory ( ISVDBIndex index , SVDBModuleDecl moduleDecl ) { super ( index ) ; fModuleDecl = moduleDecl ; } public DiagModel build ( ) { DiagModel model = new DiagModel ( ) ; if ( fModuleDecl != null ) { DiagNode moduleNode = createNodeForModule ( model , fModuleDecl ) ; createNodesAndConnectionsForContainedModules ( model , moduleNode ) ; } return model ; } } package net . sf . sveditor . core . diagrams ; import java . util . HashMap ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . SVDBModuleDecl ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . search . SVDBFindClassDefaultNameMatcher ; import net . sf . sveditor . core . db . search . SVDBFindNamedClass ; import net . sf . sveditor . core . db . search . SVDBFindNamedModIfcClassIfc ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; public abstract class AbstractDiagModelFactory implements IDiagModelFactory { protected ISVDBIndex fIndex ; public AbstractDiagModelFactory ( ISVDBIndex index ) { fIndex = index ; } public DiagNode createNodeForClass ( DiagModel model , SVDBClassDecl classDecl ) { DiagNode node = model . getVisitedClass ( classDecl . getName ( ) ) ; if ( node != null ) { return node ; } node = new DiagNode ( classDecl . getName ( ) , classDecl ) ; model . addNode ( node ) ; for ( ISVDBChildItem child : classDecl . getChildren ( ) ) { if ( child . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt childVarDecl = ( SVDBVarDeclStmt ) child ; for ( ISVDBChildItem var : childVarDecl . getChildren ( ) ) { if ( var instanceof SVDBVarDeclItem ) { SVDBVarDeclItem declItem = ( SVDBVarDeclItem ) var ; node . addMember ( declItem ) ; } } } else if ( child . getType ( ) == SVDBItemType . Function ) { SVDBFunction funcItem = ( SVDBFunction ) child ; node . addFunction ( funcItem ) ; } else if ( child . getType ( ) == SVDBItemType . Task ) { SVDBTask taskItem = ( SVDBTask ) child ; node . addTask ( taskItem ) ; } } return node ; } public DiagNode createNodeForModule ( DiagModel model , SVDBModIfcDecl moduleDecl ) { DiagNode node = model . getVisitedClass ( moduleDecl . getName ( ) ) ; if ( node != null ) { return node ; } node = new DiagNode ( moduleDecl . getName ( ) , moduleDecl ) ; model . addNode ( node ) ; if ( moduleDecl . getPorts ( ) != null ) { } for ( ISVDBChildItem child : moduleDecl . getChildren ( ) ) { if ( child . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt childVarDecl = ( SVDBVarDeclStmt ) child ; for ( ISVDBChildItem var : childVarDecl . getChildren ( ) ) { if ( var instanceof SVDBVarDeclItem ) { SVDBVarDeclItem declItem = ( SVDBVarDeclItem ) var ; node . addMember ( declItem ) ; } } } else if ( child . getType ( ) == SVDBItemType . Function ) { SVDBFunction funcItem = ( SVDBFunction ) child ; node . addFunction ( funcItem ) ; } else if ( child . getType ( ) == SVDBItemType . Task ) { SVDBTask taskItem = ( SVDBTask ) child ; node . addTask ( taskItem ) ; } } return node ; } public void createNodesAndConnectionsForContainedClasses ( DiagModel model , DiagNode node ) { if ( node . getSVDBItem ( ) == null || node . getSVDBItem ( ) . getType ( ) != SVDBItemType . ClassDecl ) { return ; } SVDBClassDecl classDecl = ( SVDBClassDecl ) node . getSVDBItem ( ) ; for ( ISVDBChildItem child : classDecl . getChildren ( ) ) { if ( child . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt childVarDecl = ( SVDBVarDeclStmt ) child ; if ( childVarDecl . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoUserDef ) { SVDBFindNamedClass finder = new SVDBFindNamedClass ( fIndex , SVDBFindClassDefaultNameMatcher . getDefault ( ) ) ; List < SVDBClassDecl > classDecls = finder . find ( childVarDecl . getTypeName ( ) ) ; if ( classDecls . size ( ) != ) { DiagNode kidNode = createNodeForClass ( model , ( SVDBClassDecl ) classDecls . toArray ( ) [ ] ) ; DiagConnection con = new DiagConnection ( "" , DiagConnectionType . Contains , node , kidNode ) ; model . addConnection ( con ) ; node . addContainedClass ( kidNode ) ; } } } } } public void createNodesAndConnectionsForContainedModules ( DiagModel model , DiagNode node ) { if ( node . getSVDBItem ( ) == null || node . getSVDBItem ( ) . getType ( ) != SVDBItemType . ModuleDecl ) { return ; } SVDBModuleDecl moduleDecl = ( SVDBModuleDecl ) node . getSVDBItem ( ) ; for ( ISVDBChildItem child : moduleDecl . getChildren ( ) ) { if ( child . getType ( ) == SVDBItemType . ModIfcInst ) { SVDBModIfcInst modInst = ( SVDBModIfcInst ) child ; SVDBFindNamedModIfcClassIfc finder = new SVDBFindNamedModIfcClassIfc ( fIndex ) ; List < ISVDBChildItem > result = finder . find ( modInst . getTypeName ( ) ) ; if ( result . size ( ) > && result . get ( ) . getType ( ) == SVDBItemType . ModuleDecl ) { DiagNode kidNode = createNodeForModule ( model , ( SVDBModuleDecl ) result . get ( ) ) ; DiagConnection con = new DiagConnection ( "" , DiagConnectionType . Contains , node , kidNode ) ; model . addConnection ( con ) ; node . addContainedClass ( kidNode ) ; } } } } public void createConnectionsForNodes ( DiagModel model , List < DiagNode > nodes ) { HashMap < String , DiagNode > nodeHash = new HashMap < String , DiagNode > ( ) ; for ( DiagNode node : nodes ) { nodeHash . put ( node . getName ( ) , node ) ; } for ( DiagNode node : nodes ) { SVDBClassDecl classDecl = ( SVDBClassDecl ) node . getSVDBItem ( ) ; for ( ISVDBChildItem child : classDecl . getChildren ( ) ) { if ( child . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt childVarDecl = ( SVDBVarDeclStmt ) child ; if ( childVarDecl . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoUserDef ) { String typeName = childVarDecl . getTypeName ( ) ; if ( nodeHash . containsKey ( typeName ) ) { DiagConnection con = new DiagConnection ( "" , DiagConnectionType . Contains , node , nodeHash . get ( typeName ) ) ; model . addConnection ( con ) ; node . addContainedClass ( nodeHash . get ( typeName ) ) ; } } } } } } } package net . sf . sveditor . core . diagrams ; public interface IDiagModelFactory { public DiagModel build ( ) ; } package net . sf . sveditor . core . diagrams ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; public class DiagModel { private List < DiagConnection > connections ; private List < DiagNode > nodes ; private HashMap < String , DiagNode > fClassNodeMap ; public DiagNode getVisitedClass ( String className ) { if ( fClassNodeMap . containsKey ( className ) ) { return fClassNodeMap . get ( className ) ; } else { return null ; } } public void addNode ( DiagNode node ) { fClassNodeMap . put ( node . getName ( ) , node ) ; nodes . add ( node ) ; } public void addConnection ( DiagConnection con ) { connections . add ( con ) ; } public DiagModel ( ) { nodes = new ArrayList < DiagNode > ( ) ; connections = new ArrayList < DiagConnection > ( ) ; fClassNodeMap = new HashMap < String , DiagNode > ( ) ; } public List < DiagNode > getNodes ( ) { return nodes ; } } package net . sf . sveditor . core . diagrams ; import java . util . List ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . search . SVDBFindPackageDefaultNameMatcher ; import org . eclipse . core . runtime . NullProgressMonitor ; public class PackageClassDiagModelFactory extends AbstractDiagModelFactory { private SVDBPackageDecl fPackageDecl ; public PackageClassDiagModelFactory ( ISVDBIndex index , SVDBPackageDecl pkgDecl ) { super ( index ) ; fPackageDecl = pkgDecl ; } public DiagModel build ( ) { DiagModel model = new DiagModel ( ) ; List < SVDBDeclCacheItem > pkgDeclItems = fIndex . findGlobalScopeDecl ( new NullProgressMonitor ( ) , fPackageDecl . getName ( ) , new SVDBFindPackageDefaultNameMatcher ( ) ) ; if ( pkgDeclItems . size ( ) == ) { return null ; } SVDBDeclCacheItem pkgDeclItem = pkgDeclItems . get ( ) ; List < SVDBDeclCacheItem > pkgDecls = fIndex . findPackageDecl ( new NullProgressMonitor ( ) , pkgDeclItem ) ; if ( pkgDecls != null ) { for ( SVDBDeclCacheItem pkgDecl : pkgDecls ) { if ( pkgDecl . getType ( ) == SVDBItemType . ClassDecl ) { createNodeForClass ( model , ( SVDBClassDecl ) pkgDecl . getSVDBItem ( ) ) ; } } } createConnectionsForNodes ( model , model . getNodes ( ) ) ; return model ; } } package net . sf . sveditor . core . diagrams ; public class DiagConnection { final String fLabel ; final DiagNode fSrcNode ; final DiagNode fDstNode ; final DiagConnectionType fConType ; public DiagConnection ( String label , DiagConnectionType conType , DiagNode srcNode , DiagNode dstNode ) { this . fLabel = label ; this . fSrcNode = srcNode ; this . fDstNode = dstNode ; this . fConType = conType ; } public DiagConnectionType getConType ( ) { return fConType ; } public String getLabel ( ) { return fLabel ; } public DiagNode getSource ( ) { return fSrcNode ; } public DiagNode getDestination ( ) { return fDstNode ; } } package net . sf . sveditor . core . diagrams ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . search . SVDBFindSuperClass ; public class ClassDiagModelFactory extends AbstractDiagModelFactory { private SVDBClassDecl fClassDecl ; public ClassDiagModelFactory ( ISVDBIndex index , SVDBClassDecl classDecl ) { super ( index ) ; fClassDecl = classDecl ; } public DiagModel build ( ) { DiagModel model = new DiagModel ( ) ; if ( fClassDecl != null ) { DiagNode classNode = createNodeForClass ( model , fClassDecl ) ; if ( fClassDecl . getSuperClass ( ) != null ) { DiagNode superNode = null ; String superName = fClassDecl . getSuperClass ( ) . getName ( ) ; superNode = model . getVisitedClass ( superName ) ; if ( superNode == null ) { SVDBFindSuperClass super_finder = new SVDBFindSuperClass ( fIndex ) ; ISVDBChildParent si = super_finder . find ( fClassDecl ) ; if ( si != null && si . getType ( ) == SVDBItemType . ClassDecl ) { superNode = createNodeForClass ( model , ( SVDBClassDecl ) si ) ; } } if ( superNode != null ) { DiagConnection con = new DiagConnection ( "" , DiagConnectionType . Inherits , classNode , superNode ) ; model . addConnection ( con ) ; classNode . addSuperClass ( superNode ) ; } } createNodesAndConnectionsForContainedClasses ( model , classNode ) ; } return model ; } } package net . sf . sveditor . core . diagrams ; public enum DiagConnectionType { Inherits , Contains } ; package net . sf . sveditor . core . diagrams ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; public class DiagNode { private final String fName ; private HashSet < DiagNode > fSuperClasses ; private HashSet < DiagNode > fContainedClasses ; private ISVDBItemBase fISVDBItem ; private List < SVDBVarDeclItem > fMemberDecls ; private List < SVDBFunction > fFuncDecls ; private List < SVDBTask > fTaskDecls ; private boolean fSelected ; public DiagNode ( String name , ISVDBItemBase item ) { this . fName = name ; this . fSelected = false ; this . fMemberDecls = new ArrayList < SVDBVarDeclItem > ( ) ; this . fFuncDecls = new ArrayList < SVDBFunction > ( ) ; this . fTaskDecls = new ArrayList < SVDBTask > ( ) ; this . fISVDBItem = item ; this . fSuperClasses = new HashSet < DiagNode > ( ) ; this . fContainedClasses = new HashSet < DiagNode > ( ) ; } public String getName ( ) { return fName ; } public void addMember ( SVDBVarDeclItem declItem ) { fMemberDecls . add ( declItem ) ; } public void addSuperClass ( DiagNode node ) { fSuperClasses . add ( node ) ; } public void addContainedClass ( DiagNode node ) { fContainedClasses . add ( node ) ; } public Collection < DiagNode > getSuperClasses ( ) { return fSuperClasses ; } public Collection < DiagNode > getContainedClasses ( ) { return fContainedClasses ; } public List < SVDBVarDeclItem > getMemberDecls ( ) { return fMemberDecls ; } public ISVDBItemBase getSVDBItem ( ) { return fISVDBItem ; } public List < DiagNode > getConnectedTo ( ) { List < DiagNode > connections = new ArrayList < DiagNode > ( fSuperClasses ) ; connections . addAll ( new ArrayList < DiagNode > ( fContainedClasses ) ) ; return connections ; } public void addFunction ( SVDBFunction funcItem ) { this . fFuncDecls . add ( funcItem ) ; } public List < SVDBFunction > getFuncDecls ( ) { return fFuncDecls ; } public void addTask ( SVDBTask taskItem ) { this . fTaskDecls . add ( taskItem ) ; } public List < SVDBTask > getTaskDecls ( ) { return fTaskDecls ; } public void setSelected ( boolean selected ) { fSelected = selected ; } public boolean getSelected ( ) { return fSelected ; } } package net . sf . sveditor . core ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . PrintStream ; import java . net . URL ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . SVDB ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCacheFactory ; import net . sf . sveditor . core . db . index . cache . SVDBDirFS ; import net . sf . sveditor . core . db . index . cache . SVDBFileIndexCache ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibDescriptor ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . project . SVDBSourceCollection ; import net . sf . sveditor . core . fileset . SVFileSet ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVDefaultIndenter2 ; import net . sf . sveditor . core . job_mgr . IJobMgr ; import net . sf . sveditor . core . job_mgr . JobMgr ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . ILogListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . parser . ParserSVDBFileFactory ; import net . sf . sveditor . core . scanner . IDefineProvider ; import net . sf . sveditor . core . templates . TemplateRegistry ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . core . runtime . content . IContentType ; import org . eclipse . core . runtime . content . IContentTypeManager ; import org . osgi . framework . Bundle ; import org . osgi . framework . BundleContext ; import org . osgi . framework . Version ; public class SVCorePlugin extends Plugin implements ILogListener , ISVDBIndexCacheFactory { public static final String PLUGIN_ID = "" ; public static final String SV_BUILTIN_LIBRARY = "" ; private static SVCorePlugin fPlugin ; private SVTodoScanner fTodoScanner ; private SVDBProjectManager fProjManager ; private SVDBIndexRegistry fIndexRegistry ; private int fDebugLevel = ; private OutputStream fLogStream ; private PrintStream fLogPS ; private static Map < String , String > fLocalEnvMap = new HashMap < String , String > ( ) ; private SVMarkerPropagationJob fMarkerPropagationJob ; private static IJobMgr fJobMgr ; private int fNumIndexCacheThreads = ; private int fMaxIndexThreads = ; private TemplateRegistry fTemplateRgy ; private boolean fEnableAsyncCacheClear ; public SVCorePlugin ( ) { } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; fPlugin = this ; if ( context . getProperty ( "" ) . toLowerCase ( ) . startsWith ( "" ) ) { SVFileUtils . fIsWinPlatform = true ; } SVDB . init ( ) ; fTodoScanner = new SVTodoScanner ( ) ; File state_location = getStateLocation ( ) . toFile ( ) ; try { fLogStream = new FileOutputStream ( new File ( state_location , "" ) ) ; fLogPS = new PrintStream ( fLogStream ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } fEnableAsyncCacheClear = true ; LogFactory . getDefault ( ) . addLogListener ( this ) ; } public void setTestMode ( ) { fEnableAsyncCacheClear = false ; } public boolean getEnableAsyncCacheClear ( ) { return fEnableAsyncCacheClear ; } public void enableDebug ( boolean en ) { fDebugLevel = ( en ) ? ILogLevel . LEVEL_MAX : ; LogFactory . getDefault ( ) . setLogLevel ( null , fDebugLevel ) ; } public void setDebugLevel ( int level ) { fDebugLevel = level ; LogFactory . getDefault ( ) . setLogLevel ( null , fDebugLevel ) ; } public int getDebugLevel ( ) { return fDebugLevel ; } public static ISVDBFileFactory createFileFactory ( IDefineProvider dp ) { return new ParserSVDBFileFactory ( dp ) ; } public ISVIndenter createIndenter ( ) { return new SVDefaultIndenter2 ( ) ; } public synchronized static IJobMgr getJobMgr ( ) { if ( fJobMgr == null ) { fJobMgr = new JobMgr ( ) ; } return fJobMgr ; } public TemplateRegistry getTemplateRgy ( ) { if ( fTemplateRgy == null ) { fTemplateRgy = new TemplateRegistry ( true ) ; } return fTemplateRgy ; } public void stop ( BundleContext context ) throws Exception { if ( fTodoScanner != null ) { fTodoScanner . dispose ( ) ; } if ( fProjManager != null ) { fProjManager . dispose ( ) ; } if ( fIndexRegistry != null ) { fIndexRegistry . save_state ( ) ; } LogFactory . getDefault ( ) . removeLogListener ( this ) ; if ( fLogStream != null ) { fLogPS . flush ( ) ; try { fLogStream . close ( ) ; } catch ( IOException e ) { } } if ( fJobMgr != null ) { fJobMgr . dispose ( ) ; } fPlugin = null ; super . stop ( context ) ; } public static SVCorePlugin getDefault ( ) { return fPlugin ; } public static void testInit ( ) { fPlugin = new SVCorePlugin ( ) ; } public SVDBProjectManager getProjMgr ( ) { if ( fProjManager == null ) { fProjManager = new SVDBProjectManager ( ) ; } return fProjManager ; } public List < SVDBPluginLibDescriptor > getPluginLibList ( ) { List < SVDBPluginLibDescriptor > ret = new ArrayList < SVDBPluginLibDescriptor > ( ) ; IExtensionRegistry rgy = Platform . getExtensionRegistry ( ) ; IExtensionPoint pt = rgy . getExtensionPoint ( PLUGIN_ID , "" ) ; for ( IExtension ext : pt . getExtensions ( ) ) { for ( IConfigurationElement cel : ext . getConfigurationElements ( ) ) { String name = cel . getAttribute ( "" ) ; String path = cel . getAttribute ( "" ) ; String id = cel . getAttribute ( "" ) ; String is_dflt_s = cel . getAttribute ( "" ) ; String desc = "" ; boolean is_default = ( is_dflt_s != null && is_dflt_s . equals ( "" ) ) ; for ( IConfigurationElement cel_i : cel . getChildren ( ) ) { if ( cel_i . getName ( ) . equals ( "" ) ) { desc = cel_i . getValue ( ) ; } } SVDBPluginLibDescriptor lib_desc = new SVDBPluginLibDescriptor ( name , id , ext . getNamespaceIdentifier ( ) , path , is_default , desc ) ; ret . add ( lib_desc ) ; } } super . getStateLocation ( ) ; return ret ; } public void setSVDBIndexRegistry ( SVDBIndexRegistry rgy ) { fIndexRegistry = rgy ; } public SVDBIndexRegistry getSVDBIndexRegistry ( ) { if ( fIndexRegistry == null ) { fIndexRegistry = new SVDBIndexRegistry ( ) ; fIndexRegistry . init ( this ) ; } return fIndexRegistry ; } public ISVDBIndexCache createIndexCache ( String project_name , String base_location ) { File file = getStateLocation ( ) . toFile ( ) ; File cache = new File ( file , "" ) ; File cache_dir = new File ( cache , project_name + "" + SVFileUtils . computeMD5 ( base_location ) ) ; if ( ! cache_dir . exists ( ) ) { if ( ! cache_dir . mkdirs ( ) ) { System . out . println ( "" ) ; } } SVDBDirFS fs = new SVDBDirFS ( cache_dir ) ; fs . setEnableAsyncClear ( fEnableAsyncCacheClear ) ; ISVDBIndexCache ret = new SVDBFileIndexCache ( fs ) ; return ret ; } public void compactCache ( List < ISVDBIndexCache > cache_list ) { File file = getStateLocation ( ) . toFile ( ) ; File cache = new File ( file , "" ) ; if ( cache . isDirectory ( ) ) { List < File > file_list = new ArrayList < File > ( ) ; for ( File f : cache . listFiles ( ) ) { if ( ! f . getName ( ) . equals ( "" ) && ! f . getName ( ) . equals ( "" ) ) { file_list . add ( f ) ; } } for ( ISVDBIndexCache index_c : cache_list ) { index_c . removeStoragePath ( file_list ) ; } for ( File f : file_list ) { System . out . println ( "" + f . getAbsolutePath ( ) ) ; SVFileUtils . delete ( f ) ; } } } public List < String > getDefaultSVExts ( ) { IContentTypeManager mgr = Platform . getContentTypeManager ( ) ; IContentType type = mgr . getContentType ( PLUGIN_ID + "" ) ; String exts [ ] = type . getFileSpecs ( IContentType . FILE_EXTENSION_SPEC ) ; List < String > ret = new ArrayList < String > ( ) ; for ( String e : exts ) { ret . add ( e ) ; } return ret ; } public String getDefaultSourceCollectionIncludes ( ) { IContentTypeManager mgr = Platform . getContentTypeManager ( ) ; IContentType type = mgr . getContentType ( PLUGIN_ID + "" ) ; String exts [ ] = type . getFileSpecs ( IContentType . FILE_EXTENSION_SPEC ) ; StringBuilder ret = new StringBuilder ( ) ; for ( int i = ; i < exts . length ; i ++ ) { ret . append ( "" ) ; ret . append ( exts [ i ] ) ; if ( i + < exts . length ) { ret . append ( "" ) ; } } return ret . toString ( ) ; } public String getDefaultSourceCollectionExcludes ( ) { return "" ; } public SVFileSet getDefaultFileSet ( String base ) { SVFileSet ret = new SVFileSet ( base ) ; for ( String inc : SVDBSourceCollection . parsePatternList ( getDefaultSourceCollectionIncludes ( ) ) ) { ret . addInclude ( inc ) ; } for ( String exc : SVDBSourceCollection . parsePatternList ( getDefaultSourceCollectionExcludes ( ) ) ) { ret . addExclude ( exc ) ; } return ret ; } public void propagateMarker ( IFile file , int severity , int lineno , String msg ) { if ( fMarkerPropagationJob == null ) { fMarkerPropagationJob = new SVMarkerPropagationJob ( ) ; } fMarkerPropagationJob . addMarker ( file , severity , lineno , msg ) ; } public void message ( ILogHandle handle , int type , int level , String message ) { if ( type == ILogListener . Type_Error ) { System . err . println ( "" + handle . getName ( ) + "" + message ) ; if ( fLogPS != null ) { fLogPS . println ( "" + handle . getName ( ) + "" + message ) ; } } else { if ( fDebugLevel >= level ) { System . out . println ( "" + handle . getName ( ) + "" + message ) ; if ( fLogPS != null ) { fLogPS . println ( "" + handle . getName ( ) + "" + message ) ; } } } } public static String getVersion ( ) { if ( fPlugin != null ) { Version v = fPlugin . getBundle ( ) . getVersion ( ) ; return v . getMajor ( ) + "" + v . getMinor ( ) + "" + v . getMicro ( ) ; } else { return "" ; } } public static StringBuilder readResourceFile ( IConfigurationElement element , String attr ) { Bundle bundle = Platform . getBundle ( element . getContributor ( ) . getName ( ) ) ; String filePath = element . getAttribute ( attr ) ; if ( filePath != null ) { URL fileURL = FileLocator . find ( bundle , new Path ( filePath ) , null ) ; if ( fileURL != null ) { try { StringBuilder sb = new StringBuilder ( ) ; InputStream in = fileURL . openStream ( ) ; byte tmp [ ] = new byte [ * ] ; int sz ; while ( ( sz = in . read ( tmp , , tmp . length ) ) > ) { for ( int i = ; i < sz ; i ++ ) { sb . append ( tmp [ i ] ) ; } } in . close ( ) ; return sb ; } catch ( IOException e ) { } } } return null ; } public static void setenv ( String key , String val ) { if ( fLocalEnvMap . containsKey ( key ) ) { fLocalEnvMap . remove ( key ) ; } fLocalEnvMap . put ( key , val ) ; } public static String getenv ( String key ) { if ( fLocalEnvMap . containsKey ( key ) ) { return fLocalEnvMap . get ( key ) ; } else { return System . getenv ( key ) ; } } public static int getNumIndexCacheThreads ( ) { SVCorePlugin plugin = getDefault ( ) ; if ( plugin != null ) { return plugin . fNumIndexCacheThreads ; } else { return ; } } public static int getMaxIndexThreads ( ) { SVCorePlugin plugin = getDefault ( ) ; if ( plugin != null ) { return plugin . fMaxIndexThreads ; } else { return ; } } } package net . sf . sveditor . core ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; public class StringIterableIterator implements Iterable < String > , Iterator < String > { private List < Iterable < String > > fIterables ; private int fIterableIdx ; private Iterator < String > fIterator ; public StringIterableIterator ( ) { fIterables = new ArrayList < Iterable < String > > ( ) ; } private StringIterableIterator ( List < Iterable < String > > it ) { fIterables = new ArrayList < Iterable < String > > ( ) ; fIterables . addAll ( it ) ; } public void addIterable ( Iterable < String > it ) { fIterables . add ( it ) ; } public boolean hasNext ( ) { if ( fIterator == null || ! fIterator . hasNext ( ) ) { fIterator = null ; while ( fIterableIdx < fIterables . size ( ) ) { fIterator = fIterables . get ( fIterableIdx ) . iterator ( ) ; fIterableIdx ++ ; if ( fIterator . hasNext ( ) ) { break ; } fIterator = null ; } } return ( fIterator != null && fIterator . hasNext ( ) ) ; } public String next ( ) { if ( hasNext ( ) ) { return fIterator . next ( ) ; } else { return null ; } } public void remove ( ) { throw new RuntimeException ( "" ) ; } public Iterator < String > iterator ( ) { return new StringIterableIterator ( fIterables ) ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevelListener ; public class SVParserBase implements ISVParser , ILogLevelListener { protected boolean fDebugEn = false ; protected ISVParser fParser ; protected SVLexer fLexer ; protected SVParsers fParsers ; protected SVParserBase ( ISVParser parser ) { fParser = parser ; fLexer = parser . lexer ( ) ; fParsers = parser . parsers ( ) ; fDebugEn = getLogHandle ( ) . isEnabled ( ) ; getLogHandle ( ) . addLogLevelListener ( this ) ; } public void logLevelChanged ( ILogHandle handle ) { fDebugEn = getLogHandle ( ) . isEnabled ( ) ; } public ILogHandle getLogHandle ( ) { return fParser . getLogHandle ( ) ; } public boolean error_limit_reached ( ) { return fParser . error_limit_reached ( ) ; } public void disableErrors ( boolean dis ) { fParser . disableErrors ( dis ) ; } public void error ( SVParseException e ) throws SVParseException { fParser . error ( e ) ; } public void error ( String msg ) throws SVParseException { fParser . error ( msg ) ; } public SVLexer lexer ( ) { return fParser . lexer ( ) ; } protected SVDBIdentifierExpr readId ( ) throws SVParseException { return fParsers . exprParser ( ) . idExpr ( ) ; } public void warning ( String msg , int lineno ) { fParser . warning ( msg , lineno ) ; } public SVParsers parsers ( ) { return fParser . parsers ( ) ; } public SVDBLocation getLocation ( ) { return fLexer . getStartLocation ( ) ; } public void debug ( String msg ) { fParser . debug ( msg , null ) ; } public void debug ( String msg , Exception e ) { fParser . debug ( msg , e ) ; } protected void setStartLocation ( SVDBItem item ) { item . setLocation ( getLocation ( ) ) ; } protected void setEndLocation ( SVDBScopeItem item ) { item . setEndLocation ( getLocation ( ) ) ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . IFieldItemAttr ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBTypeInfoClassType ; public class SVClassDeclParser extends SVParserBase { public SVClassDeclParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent , int qualifiers ) throws SVParseException { SVDBClassDecl cls = null ; SVDBTypeInfoClassType cls_type ; String cls_type_name = null ; if ( fDebugEn ) { debug ( "" ) ; } SVDBLocation start_loc = fLexer . getStartLocation ( ) ; fLexer . readKeyword ( "" ) ; if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; } cls_type_name = parsers ( ) . SVParser ( ) . scopedIdentifier ( ( ( qualifiers & IFieldItemAttr . FieldAttr_SvBuiltin ) != ) ) ; cls = new SVDBClassDecl ( cls_type_name ) ; cls . setLocation ( start_loc ) ; cls_type = new SVDBTypeInfoClassType ( cls_type_name ) ; cls . setClassType ( cls_type ) ; if ( fLexer . peekOperator ( "" ) ) { cls . addParameters ( parsers ( ) . paramPortListParser ( ) . parse ( ) ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; cls . setSuperClass ( parsers ( ) . dataTypeParser ( ) . class_type ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . skipPastMatch ( "" , "" ) ; } else { fLexer . eatToken ( ) ; } } } fLexer . readOperator ( "" ) ; parent . addChildItem ( cls ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { try { fParsers . modIfcBodyItemParser ( ) . parse ( cls , "" ) ; } catch ( SVParseException e ) { while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) && ! fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } } } cls . setEndLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . expr . SVDBAssignExpr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBLiteralExpr ; import net . sf . sveditor . core . db . stmt . SVDBActionBlockStmt ; import net . sf . sveditor . core . db . stmt . SVDBAssignStmt ; import net . sf . sveditor . core . db . stmt . SVDBBlockStmt ; import net . sf . sveditor . core . db . stmt . SVDBBreakStmt ; import net . sf . sveditor . core . db . stmt . SVDBCaseItem ; import net . sf . sveditor . core . db . stmt . SVDBCaseStmt ; import net . sf . sveditor . core . db . stmt . SVDBCaseStmt . CaseType ; import net . sf . sveditor . core . db . stmt . SVDBContinueStmt ; import net . sf . sveditor . core . db . stmt . SVDBDelayControlStmt ; import net . sf . sveditor . core . db . stmt . SVDBDisableForkStmt ; import net . sf . sveditor . core . db . stmt . SVDBDisableStmt ; import net . sf . sveditor . core . db . stmt . SVDBDoWhileStmt ; import net . sf . sveditor . core . db . stmt . SVDBEventControlStmt ; import net . sf . sveditor . core . db . stmt . SVDBEventTriggerStmt ; import net . sf . sveditor . core . db . stmt . SVDBExprStmt ; import net . sf . sveditor . core . db . stmt . SVDBForStmt ; import net . sf . sveditor . core . db . stmt . SVDBForeachStmt ; import net . sf . sveditor . core . db . stmt . SVDBForeverStmt ; import net . sf . sveditor . core . db . stmt . SVDBForkStmt ; import net . sf . sveditor . core . db . stmt . SVDBForkStmt . JoinType ; import net . sf . sveditor . core . db . stmt . SVDBIfStmt ; import net . sf . sveditor . core . db . stmt . SVDBLabeledStmt ; import net . sf . sveditor . core . db . stmt . SVDBNullStmt ; import net . sf . sveditor . core . db . stmt . SVDBProceduralContAssignStmt ; import net . sf . sveditor . core . db . stmt . SVDBProceduralContAssignStmt . AssignType ; import net . sf . sveditor . core . db . stmt . SVDBRepeatStmt ; import net . sf . sveditor . core . db . stmt . SVDBReturnStmt ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBWaitForkStmt ; import net . sf . sveditor . core . db . stmt . SVDBWaitStmt ; import net . sf . sveditor . core . db . stmt . SVDBWhileStmt ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVBehavioralBlockParser extends SVParserBase { public static boolean isDeclAllowed ( SVDBStmt stmt ) { return ( stmt . getType ( ) == SVDBItemType . VarDeclStmt || stmt . getType ( ) == SVDBItemType . TypedefStmt ) ; } public SVBehavioralBlockParser ( ISVParser parser ) { super ( parser ) ; } public boolean statement ( ISVDBAddChildItem parent ) throws SVParseException { return statement ( parent , false , true ) ; } public boolean statement ( ISVDBAddChildItem parent , boolean decl_allowed , boolean ansi_decl ) throws SVParseException { return statement_int ( parent , decl_allowed , ansi_decl , true ) ; } private static final Set < String > fDeclKeywordsANSI ; private static final Set < String > fDeclKeywordsNonANSI ; static { fDeclKeywordsANSI = new HashSet < String > ( ) ; fDeclKeywordsNonANSI = new HashSet < String > ( ) ; fDeclKeywordsANSI . add ( "" ) ; fDeclKeywordsANSI . add ( "" ) ; fDeclKeywordsANSI . add ( "" ) ; fDeclKeywordsANSI . add ( "" ) ; fDeclKeywordsANSI . add ( "" ) ; fDeclKeywordsNonANSI . addAll ( fDeclKeywordsANSI ) ; fDeclKeywordsNonANSI . add ( "" ) ; fDeclKeywordsNonANSI . add ( "" ) ; fDeclKeywordsNonANSI . add ( "" ) ; fDeclKeywordsNonANSI . add ( "" ) ; } private boolean statement_int ( ISVDBAddChildItem parent , boolean decl_allowed , boolean ansi_decl , boolean consume_terminator ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) + "" + fLexer . getStartLocation ( ) . getLine ( ) + "" + decl_allowed ) ; } Set < String > decl_keywords = ( ansi_decl ) ? fDeclKeywordsANSI : fDeclKeywordsNonANSI ; SVDBLocation start = fLexer . getStartLocation ( ) ; if ( fLexer . peekKeyword ( decl_keywords ) || fLexer . peekKeyword ( SVKeywords . fBuiltinDeclTypes ) || fLexer . isIdentifier ( ) || fLexer . peekKeyword ( "" , "" , "" , "" ) ) { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekKeyword ( decl_keywords ) || fLexer . peekKeyword ( SVKeywords . fBuiltinDeclTypes ) || fLexer . peekKeyword ( "" , "" , "" , "" ) ) { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( ! decl_allowed ) { error ( "" ) ; } parsers ( ) . blockItemDeclParser ( ) . parse ( parent , null , start , consume_terminator ) ; return decl_allowed ; } else { SVToken tok = fLexer . consumeToken ( ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekOperator ( "" , "" ) || fLexer . peekId ( ) ) { boolean retry_as_statement = false ; fLexer . ungetToken ( tok ) ; final List < SVToken > tok_l = new ArrayList < SVToken > ( ) ; ISVTokenListener l = new ISVTokenListener ( ) { public void tokenConsumed ( SVToken tok ) { tok_l . add ( tok ) ; } public void ungetToken ( SVToken tok ) { tok_l . remove ( tok_l . size ( ) - ) ; } } ; SVDBTypeInfo type = null ; try { fLexer . addTokenListener ( l ) ; disableErrors ( true ) ; type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; } catch ( SVParseException e ) { if ( fDebugEn ) { debug ( "" , e ) ; } fLexer . ungetToken ( tok_l ) ; retry_as_statement = true ; } finally { disableErrors ( false ) ; fLexer . removeTokenListener ( l ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( ! retry_as_statement ) { if ( fLexer . peekId ( ) ) { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( ! decl_allowed ) { error ( "" ) ; } parsers ( ) . blockItemDeclParser ( ) . parse ( parent , type , start , consume_terminator ) ; return decl_allowed ; } else { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } fLexer . ungetToken ( tok_l ) ; } } } else { if ( fDebugEn ) { debug ( "" ) ; } fLexer . ungetToken ( tok ) ; } } } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } decl_allowed = false ; if ( fLexer . peekKeyword ( "" ) ) { block_stmt ( parent ) ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { parsers ( ) . modIfcBodyItemParser ( ) . parse_parameter_decl ( parent ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" ) ) { fLexer . eatToken ( ) ; statement ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { parse_if_stmt ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBWhileStmt while_stmt = new SVDBWhileStmt ( ) ; while_stmt . setLocation ( start ) ; fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; while_stmt . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( while_stmt ) ; statement ( while_stmt , false , false ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBDoWhileStmt do_while = new SVDBDoWhileStmt ( ) ; do_while . setLocation ( start ) ; fLexer . eatToken ( ) ; parent . addChildItem ( do_while ) ; statement ( do_while , false , false ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; do_while . setCond ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; fLexer . readOperator ( "" ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBRepeatStmt repeat = new SVDBRepeatStmt ( ) ; repeat . setLocation ( start ) ; fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; repeat . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( repeat ) ; statement_int ( repeat , false , false , consume_terminator ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBForeverStmt forever = new SVDBForeverStmt ( ) ; forever . setLocation ( start ) ; fLexer . eatToken ( ) ; parent . addChildItem ( forever ) ; statement_int ( forever , false , false , consume_terminator ) ; } else if ( fLexer . peekKeyword ( "" ) ) { for_stmt ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBForeachStmt foreach = new SVDBForeachStmt ( ) ; foreach . setLocation ( start ) ; fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; foreach . setCond ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( foreach ) ; statement_int ( foreach , false , false , consume_terminator ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBForkStmt fork = new SVDBForkStmt ( ) ; fork . setLocation ( start ) ; parent . addChildItem ( fork ) ; decl_allowed = true ; fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" , "" , "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } decl_allowed = statement_int ( fork , decl_allowed , true , true ) ; if ( fDebugEn ) { debug ( "" ) ; } } fork . setEndLocation ( fLexer . getStartLocation ( ) ) ; String join_type = fLexer . readKeyword ( "" , "" , "" ) ; if ( join_type . equals ( "" ) ) { fork . setJoinType ( JoinType . Join ) ; } else if ( join_type . equals ( "" ) ) { fork . setJoinType ( JoinType . JoinNone ) ; } else if ( join_type . equals ( "" ) ) { fork . setJoinType ( JoinType . JoinAny ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } else if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { parse_case_stmt ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBWaitStmt wait_stmt ; fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" ) ) { wait_stmt = new SVDBWaitForkStmt ( ) ; fLexer . eatToken ( ) ; if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } parent . addChildItem ( wait_stmt ) ; } else { wait_stmt = new SVDBWaitStmt ( ) ; fLexer . readOperator ( "" ) ; wait_stmt . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( wait_stmt ) ; if ( ! fLexer . peekOperator ( "" ) ) { statement_int ( wait_stmt , false , false , consume_terminator ) ; } else if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } } } else if ( fLexer . peekOperator ( "" , "" , "" ) ) { SVDBEventTriggerStmt event_trigger = new SVDBEventTriggerStmt ( ) ; String tt = fLexer . eatToken ( ) ; if ( tt . equals ( "" ) ) { if ( fLexer . peekKeyword ( "" ) ) { SVDBRepeatStmt repeat = new SVDBRepeatStmt ( ) ; repeat . setLocation ( start ) ; fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; repeat . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { SVDBEventControlStmt event_stmt = new SVDBEventControlStmt ( ) ; fLexer . eatToken ( ) ; event_stmt . setExpr ( parsers ( ) . exprParser ( ) . event_expression ( ) ) ; event_trigger . setDelayOrEventControl ( event_stmt ) ; } else if ( fLexer . peekOperator ( "" ) ) { SVDBDelayControlStmt delay_stmt = new SVDBDelayControlStmt ( ) ; delay_stmt . setExpr ( fParsers . exprParser ( ) . delay_expr ( ) ) ; event_trigger . setDelayOrEventControl ( delay_stmt ) ; } } event_trigger . setHierarchicalEventIdentifier ( parsers ( ) . exprParser ( ) . expression ( ) ) ; if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } parent . addChildItem ( event_trigger ) ; } else if ( fLexer . peekOperator ( "" ) ) { SVDBEventControlStmt event_stmt = new SVDBEventControlStmt ( ) ; fLexer . eatToken ( ) ; event_stmt . setExpr ( parsers ( ) . exprParser ( ) . event_expression ( ) ) ; parent . addChildItem ( event_stmt ) ; statement_int ( event_stmt , decl_allowed , ansi_decl , consume_terminator ) ; } else if ( fLexer . peekOperator ( "" ) ) { SVDBDelayControlStmt delay_stmt = new SVDBDelayControlStmt ( ) ; delay_stmt . setExpr ( fParsers . exprParser ( ) . delay_expr ( ) ) ; statement_int ( delay_stmt , false , true , consume_terminator ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBDisableStmt disable_stmt ; fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; disable_stmt = new SVDBDisableForkStmt ( ) ; } else { disable_stmt = new SVDBDisableStmt ( ) ; disable_stmt . setHierarchicalId ( parsers ( ) . exprParser ( ) . expression ( ) ) ; } if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } parent . addChildItem ( disable_stmt ) ; } else if ( fLexer . peekKeyword ( "" ) ) { error ( "" ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" ) ) { parsers ( ) . assertionParser ( ) . parse ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } SVDBReturnStmt return_stmt = new SVDBReturnStmt ( ) ; return_stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; if ( ! fLexer . peekOperator ( "" ) ) { return_stmt . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; } if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } parent . addChildItem ( return_stmt ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBBreakStmt break_stmt = new SVDBBreakStmt ( ) ; break_stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } parent . addChildItem ( break_stmt ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBContinueStmt continue_stmt = new SVDBContinueStmt ( ) ; continue_stmt . setLocation ( start ) ; fLexer . eatToken ( ) ; if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } parent . addChildItem ( continue_stmt ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { procedural_cont_assign ( parent ) ; } else if ( ParserSVDBFileFactory . isFirstLevelScope ( fLexer . peek ( ) , ) || ParserSVDBFileFactory . isSecondLevelScope ( fLexer . peek ( ) ) ) { error ( "" + fLexer . peek ( ) ) ; } else if ( fLexer . peekOperator ( "" ) ) { SVDBNullStmt null_stmt = new SVDBNullStmt ( ) ; null_stmt . setLocation ( start ) ; fLexer . eatToken ( ) ; parent . addChildItem ( null_stmt ) ; } else if ( fLexer . peekId ( ) || fLexer . peekKeyword ( SVKeywords . fBuiltinTypes ) || fLexer . peekKeyword ( "" , "" ) || fLexer . peekOperator ( ) ) { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } SVToken id = fLexer . consumeToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { String label = id . getImage ( ) ; fLexer . eatToken ( ) ; SVDBLabeledStmt l_stmt = new SVDBLabeledStmt ( ) ; l_stmt . setLocation ( start ) ; l_stmt . setLabel ( label ) ; parent . addChildItem ( l_stmt ) ; statement ( l_stmt , decl_allowed , ansi_decl ) ; } else { fLexer . ungetToken ( id ) ; expression_stmt ( start , parent , null , consume_terminator ) ; } } else { error ( "" + fLexer . peek ( ) ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) + "" + fLexer . getStartLocation ( ) . getLine ( ) + "" + decl_allowed ) ; } return decl_allowed ; } private void expression_stmt ( SVDBLocation start , ISVDBAddChildItem parent , SVDBExpr lvalue , boolean consume_terminator ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( lvalue == null ) { lvalue = fParsers . exprParser ( ) . variable_lvalue ( ) ; } if ( fLexer . peekOperator ( SVKeywords . fAssignmentOps ) ) { String op = fLexer . eatToken ( ) ; SVDBAssignStmt assign_stmt = new SVDBAssignStmt ( ) ; assign_stmt . setLocation ( start ) ; assign_stmt . setLHS ( lvalue ) ; assign_stmt . setOp ( op ) ; if ( fLexer . peekOperator ( "" ) ) { assign_stmt . setDelayExpr ( fParsers . exprParser ( ) . delay_expr ( ) ) ; } else if ( fLexer . peekOperator ( "" ) ) { assign_stmt . setDelayExpr ( fParsers . exprParser ( ) . clocking_event ( ) ) ; } else if ( fLexer . peekOperator ( "" ) ) { assign_stmt . setDelayExpr ( fParsers . exprParser ( ) . expression ( ) ) ; } assign_stmt . setRHS ( parsers ( ) . exprParser ( ) . expression ( ) ) ; parent . addChildItem ( assign_stmt ) ; } else { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) + "" ) ; } SVDBExprStmt expr_stmt = new SVDBExprStmt ( lvalue ) ; expr_stmt . setLocation ( start ) ; parent . addChildItem ( expr_stmt ) ; } if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } } public void action_block ( SVDBActionBlockStmt parent ) throws SVParseException { if ( fLexer . peekOperator ( "" ) ) { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . eatToken ( ) ; SVDBStmt stmt = new SVDBNullStmt ( ) ; stmt . setLocation ( start ) ; parent . addChildItem ( stmt ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; statement_int ( parent , false , true , true ) ; } else { statement_int ( parent , false , true , true ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; statement_int ( parent , false , true , true ) ; } else { fLexer . readOperator ( "" ) ; } } } public void action_block_stmt ( SVDBActionBlockStmt parent ) throws SVParseException { if ( fLexer . peekOperator ( "" ) ) { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . eatToken ( ) ; SVDBStmt stmt = new SVDBNullStmt ( ) ; stmt . setLocation ( start ) ; parent . addChildItem ( stmt ) ; } else { fLexer . eatToken ( ) ; statement_int ( parent , false , true , true ) ; } } private SVDBForStmt for_stmt ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; SVDBForStmt for_stmt = new SVDBForStmt ( ) ; for_stmt . setLocation ( start ) ; if ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) { SVDBBlockStmt init_stmt = new SVDBBlockStmt ( ) ; statement_int ( init_stmt , true , true , false ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; statement_int ( init_stmt , true , true , false ) ; } } fLexer . readOperator ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { SVDBBlockStmt cond_stmt = new SVDBBlockStmt ( ) ; for_stmt . setTestStmt ( cond_stmt ) ; while ( fLexer . peek ( ) != null ) { SVDBExprStmt expr_stmt = new SVDBExprStmt ( ) ; expr_stmt . setLocation ( fLexer . getStartLocation ( ) ) ; SVDBExpr expr = fParsers . exprParser ( ) . expression ( ) ; expr_stmt . setExpr ( expr ) ; cond_stmt . addChildItem ( expr_stmt ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } fLexer . readOperator ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { SVDBBlockStmt incr_stmt = new SVDBBlockStmt ( ) ; for_stmt . setIncrstmt ( incr_stmt ) ; while ( fLexer . peek ( ) != null ) { SVDBExprStmt expr_stmt = new SVDBExprStmt ( ) ; expr_stmt . setLocation ( fLexer . getStartLocation ( ) ) ; SVDBExpr expr = fParsers . exprParser ( ) . expression ( ) ; expr_stmt . setExpr ( expr ) ; incr_stmt . addChildItem ( expr_stmt ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } fLexer . readOperator ( "" ) ; parent . addChildItem ( for_stmt ) ; statement ( for_stmt , false , false ) ; return for_stmt ; } private void procedural_cont_assign ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; String type_s = fLexer . readKeyword ( "" , "" , "" , "" ) ; AssignType type = null ; if ( type_s . equals ( "" ) ) { type = AssignType . Assign ; } else if ( type_s . equals ( "" ) ) { type = AssignType . Deassign ; } else if ( type_s . equals ( "" ) ) { type = AssignType . Force ; } else if ( type_s . equals ( "" ) ) { type = AssignType . Release ; } SVDBProceduralContAssignStmt assign = new SVDBProceduralContAssignStmt ( type ) ; assign . setLocation ( start ) ; parent . addChildItem ( assign ) ; SVDBExpr expr = fParsers . exprParser ( ) . variable_lvalue ( ) ; if ( type == AssignType . Assign || type == AssignType . Force ) { fLexer . readOperator ( "" ) ; expr = new SVDBAssignExpr ( expr , "" , fParsers . exprParser ( ) . expression ( ) ) ; } assign . setExpr ( expr ) ; fLexer . readOperator ( "" ) ; } private void block_stmt ( ISVDBAddChildItem parent ) throws SVParseException { boolean decl_allowed = true ; SVDBBlockStmt block = new SVDBBlockStmt ( ) ; block . setLocation ( fLexer . getStartLocation ( ) ) ; parent . addChildItem ( block ) ; fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } try { while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { decl_allowed = statement_int ( block , decl_allowed , true , true ) ; } } finally { if ( fDebugEn ) { debug ( "" + fLexer . getStartLocation ( ) ) ; } block . setEndLocation ( fLexer . getStartLocation ( ) ) ; } fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } private void parse_if_stmt ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; String if_stem = fLexer . eatToken ( ) ; if ( fDebugEn ) { debug ( "" + if_stem ) ; } if ( ! if_stem . equals ( "" ) ) { fLexer . readKeyword ( "" ) ; } fLexer . readOperator ( "" ) ; SVDBIfStmt if_stmt = new SVDBIfStmt ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; if_stmt . setLocation ( start ) ; parent . addChildItem ( if_stmt ) ; if ( fDebugEn ) { debug ( "" ) ; } statement ( if_stmt ) ; if ( fDebugEn ) { debug ( "" ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; statement ( if_stmt ) ; } } private void parse_case_stmt ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; String type_s = fLexer . eatToken ( ) ; CaseType type = null ; if ( type_s . equals ( "" ) ) { type = CaseType . Case ; } else if ( type_s . equals ( "" ) ) { type = CaseType . Casex ; } else if ( type_s . equals ( "" ) ) { type = CaseType . Casez ; } else if ( type_s . equals ( "" ) ) { type = CaseType . Randcase ; } SVDBCaseStmt case_stmt = new SVDBCaseStmt ( type ) ; case_stmt . setLocation ( start ) ; if ( ! type_s . equals ( "" ) ) { fLexer . readOperator ( "" ) ; case_stmt . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } parent . addChildItem ( case_stmt ) ; if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; } while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { SVDBCaseItem item = new SVDBCaseItem ( ) ; if ( type != CaseType . Randcase && fLexer . peekKeyword ( "" ) ) { item . addExpr ( new SVDBLiteralExpr ( "" ) ) ; fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; } } else { while ( fLexer . peek ( ) != null ) { item . addExpr ( fParsers . exprParser ( ) . expression ( ) ) ; if ( type != CaseType . Randcase && fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } statement ( item ) ; case_stmt . addCaseItem ( item ) ; } fLexer . readKeyword ( "" ) ; } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBModIfcClassParam ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVParameterPortListParser extends SVParserBase { public SVParameterPortListParser ( ISVParser parser ) { super ( parser ) ; } public List < SVDBModIfcClassParam > parse ( ) throws SVParseException { List < SVDBModIfcClassParam > params = new ArrayList < SVDBModIfcClassParam > ( ) ; fLexer . readOperator ( "" ) ; fLexer . readOperator ( "" ) ; while ( ! fLexer . peekOperator ( "" ) ) { String id = null ; SVDBModIfcClassParam p ; SVDBLocation it_start = fLexer . getStartLocation ( ) ; boolean is_type = false ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; id = fLexer . readIdOrKeyword ( ) ; is_type = true ; } else { SVDBTypeInfo type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; if ( fLexer . peekOperator ( "" , "" , "" ) ) { id = type . getName ( ) ; } else { id = fLexer . readIdOrKeyword ( ) ; } } if ( fLexer . peekOperator ( "" ) ) { fLexer . skipPastMatch ( "" , "" ) ; } p = new SVDBModIfcClassParam ( id ) ; p . setLocation ( it_start ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( is_type ) { SVDBTypeInfo type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; p . setDefaultType ( type ) ; } else { SVDBExpr dflt = parsers ( ) . exprParser ( ) . expression ( ) ; if ( fDebugEn ) { debug ( "" + id ) ; } p . setDefault ( dflt ) ; } } params . add ( p ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; return params ; } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBFieldItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBParamValueAssignList ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . SVDBTypeInfoClassItem ; import net . sf . sveditor . core . db . SVDBTypeInfoClassType ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . SVDBTypeInfoEnumerator ; import net . sf . sveditor . core . db . SVDBTypeInfoFwdDecl ; import net . sf . sveditor . core . db . SVDBTypeInfoStruct ; import net . sf . sveditor . core . db . SVDBTypeInfoUnion ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBRangeExpr ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem . DimType ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVDataTypeParser extends SVParserBase { public static final Set < String > IntegerAtomType ; public static final Set < String > IntegerVectorType ; public static final Set < String > IntegerTypes ; public static final Set < String > NonIntegerType ; public static final Set < String > NetType ; public static final Set < String > BuiltInTypes ; static { IntegerAtomType = new HashSet < String > ( ) ; IntegerAtomType . add ( "" ) ; IntegerAtomType . add ( "" ) ; IntegerAtomType . add ( "" ) ; IntegerAtomType . add ( "" ) ; IntegerAtomType . add ( "" ) ; IntegerAtomType . add ( "" ) ; IntegerAtomType . add ( "" ) ; IntegerVectorType = new HashSet < String > ( ) ; IntegerVectorType . add ( "" ) ; IntegerVectorType . add ( "" ) ; IntegerVectorType . add ( "" ) ; IntegerTypes = new HashSet < String > ( ) ; IntegerTypes . addAll ( IntegerAtomType ) ; IntegerTypes . addAll ( IntegerVectorType ) ; NonIntegerType = new HashSet < String > ( ) ; NonIntegerType . add ( "" ) ; NonIntegerType . add ( "" ) ; NonIntegerType . add ( "" ) ; NetType = new HashSet < String > ( ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; NetType . add ( "" ) ; BuiltInTypes = new HashSet < String > ( ) ; BuiltInTypes . add ( "" ) ; BuiltInTypes . add ( "" ) ; BuiltInTypes . add ( "" ) ; } public SVDataTypeParser ( ISVParser parser ) { super ( parser ) ; } public SVDBTypeInfo data_type ( int qualifiers ) throws SVParseException { SVDBTypeInfo type = null ; SVToken tok ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } qualifiers |= parsers ( ) . SVParser ( ) . scan_qualifiers ( false ) ; tok = fLexer . consumeToken ( ) ; fLexer . ungetToken ( tok ) ; if ( fLexer . peekKeyword ( IntegerVectorType ) ) { SVDBTypeInfoBuiltin builtin_type = new SVDBTypeInfoBuiltin ( fLexer . eatToken ( ) ) ; if ( fLexer . peekKeyword ( "" , "" ) ) { builtin_type . setAttr ( fLexer . peekKeyword ( "" ) ? SVDBTypeInfoBuiltin . TypeAttr_Signed : SVDBTypeInfoBuiltin . TypeAttr_Unsigned ) ; fLexer . eatToken ( ) ; } while ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } builtin_type . setArrayDim ( vector_dim ( ) ) ; } type = builtin_type ; } else if ( fLexer . peekKeyword ( NetType ) ) { debug ( "" ) ; SVDBTypeInfoBuiltin builtin_type = new SVDBTypeInfoBuiltin ( fLexer . eatToken ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { tok = fLexer . consumeToken ( ) ; if ( fLexer . peekOperator ( SVKeywords . fStrength ) ) { String strength1 = fLexer . readKeyword ( SVKeywords . fStrength ) ; fLexer . readOperator ( "" ) ; String strength2 = fLexer . readKeyword ( SVKeywords . fStrength ) ; fLexer . readOperator ( "" ) ; } else { fLexer . ungetToken ( tok ) ; } } if ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } builtin_type . setVectorDim ( vector_dim ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fParsers . exprParser ( ) . delay_expr ( ) ; } type = builtin_type ; } else if ( fLexer . peekKeyword ( IntegerAtomType ) ) { SVDBTypeInfoBuiltin builtin_type = new SVDBTypeInfoBuiltin ( fLexer . eatToken ( ) ) ; if ( fLexer . peekKeyword ( "" , "" ) ) { builtin_type . setAttr ( fLexer . peekKeyword ( "" ) ? SVDBTypeInfoBuiltin . TypeAttr_Signed : SVDBTypeInfoBuiltin . TypeAttr_Unsigned ) ; fLexer . eatToken ( ) ; } type = builtin_type ; } else if ( fLexer . peekKeyword ( NonIntegerType ) ) { type = new SVDBTypeInfoBuiltin ( fLexer . eatToken ( ) ) ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { tok = fLexer . readKeywordTok ( "" , "" ) ; if ( tok . getImage ( ) . equals ( "" ) ) { if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; } type = ( tok . getImage ( ) . equals ( "" ) ) ? new SVDBTypeInfoUnion ( ) : new SVDBTypeInfoStruct ( ) ; struct_union_body ( ( ISVDBAddChildItem ) type ) ; } else if ( fLexer . peekKeyword ( "" ) ) { type = enum_type ( ) ; type . setName ( "" ) ; } else if ( fLexer . peekKeyword ( BuiltInTypes ) ) { type = new SVDBTypeInfoBuiltin ( fLexer . eatToken ( ) ) ; } else if ( fLexer . peekKeyword ( "" ) || ( qualifiers & SVDBFieldItem . FieldAttr_Virtual ) != ) { if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } tok = fLexer . readIdTok ( ) ; SVDBTypeInfoUserDef ud_type = new SVDBTypeInfoUserDef ( tok . getImage ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { SVDBParamValueAssignList plist = parsers ( ) . paramValueAssignParser ( ) . parse ( true ) ; ud_type . setParameters ( plist ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; String id = fLexer . readId ( ) ; ud_type . setName ( ud_type . getName ( ) + "" + id ) ; } type = ud_type ; } else if ( fLexer . peekKeyword ( "" ) ) { type = new SVDBTypeInfoBuiltin ( fLexer . eatToken ( ) ) ; error ( "" ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; SVDBTypeInfoFwdDecl type_fwd = new SVDBTypeInfoFwdDecl ( "" , fLexer . readId ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . skipPastMatch ( "" , "" ) ; } else { fLexer . eatToken ( ) ; } } } type = type_fwd ; } else if ( fLexer . peekOperator ( "" ) || fLexer . peekKeyword ( "" , "" ) ) { SVToken id = fLexer . consumeToken ( ) ; SVDBTypeInfoBuiltin builtin_type = new SVDBTypeInfoBuiltin ( ( id . getImage ( ) . equals ( "" ) ) ? "" : id . getImage ( ) ) ; debug ( "" + id . getImage ( ) ) ; if ( id . getImage ( ) . equals ( "" ) ) { fLexer . ungetToken ( id ) ; builtin_type . setVectorDim ( vector_dim ( ) ) ; } else if ( fLexer . peekOperator ( "" ) ) { builtin_type . setVectorDim ( vector_dim ( ) ) ; } type = builtin_type ; } else if ( SVKeywords . isVKeyword ( fLexer . peek ( ) ) && ! fLexer . peekKeyword ( "" ) && ! fLexer . peekKeyword ( SVKeywords . fBuiltinGates ) ) { error ( "" + fLexer . peek ( ) + "" ) ; } else { String id = fLexer . eatToken ( ) ; SVDBParamValueAssignList p_list = null ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; p_list = parsers ( ) . paramValueAssignParser ( ) . parse ( false ) ; } if ( fLexer . peekOperator ( "" ) ) { StringBuilder type_id = new StringBuilder ( ) ; type_id . append ( id ) ; while ( fLexer . peekOperator ( "" ) ) { type_id . append ( fLexer . eatToken ( ) ) ; type_id . append ( fLexer . readId ( ) ) ; } type = new SVDBTypeInfoUserDef ( type_id . toString ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { type . setArrayDim ( packed_dim ( ) ) ; } } else if ( fLexer . peekOperator ( "" ) ) { StringBuilder type_id = new StringBuilder ( ) ; type_id . append ( id ) ; while ( fLexer . peekOperator ( "" ) ) { type_id . append ( fLexer . eatToken ( ) ) ; type_id . append ( fLexer . readId ( ) ) ; } type = new SVDBTypeInfoUserDef ( type_id . toString ( ) ) ; } else { type = new SVDBTypeInfoUserDef ( id ) ; } ( ( SVDBTypeInfoUserDef ) type ) . setParameters ( p_list ) ; if ( fLexer . peekOperator ( "" ) ) { SVDBParamValueAssignList plist = parsers ( ) . paramValueAssignParser ( ) . parse ( true ) ; ( ( SVDBTypeInfoUserDef ) type ) . setParameters ( plist ) ; } if ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } type . setArrayDim ( var_dim ( ) ) ; } } if ( type == null ) { error ( "" + fLexer . peek ( ) + "" ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return type ; } public SVDBTypeInfo data_type_or_void ( int qualifiers ) throws SVParseException { if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; return new SVDBTypeInfoBuiltin ( "" ) ; } else { return data_type ( qualifiers ) ; } } public SVDBTypeInfo net_port_type ( int qualifiers ) throws SVParseException { if ( fLexer . peekKeyword ( NetType ) ) { fLexer . eatToken ( ) ; } return data_type ( qualifiers ) ; } public SVDBTypeInfo enum_type ( ) throws SVParseException { fLexer . readKeyword ( "" ) ; SVDBTypeInfoEnum type = null ; if ( ! fLexer . peekOperator ( "" ) ) { data_type ( ) ; if ( fLexer . peekOperator ( "" ) ) { return new SVDBTypeInfoFwdDecl ( ) ; } else { type = new SVDBTypeInfoEnum ( ) ; } } else { type = new SVDBTypeInfoEnum ( ) ; } fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null ) { SVDBLocation loc = fLexer . getStartLocation ( ) ; SVDBTypeInfoEnumerator enum_v = new SVDBTypeInfoEnumerator ( fLexer . readId ( ) ) ; enum_v . setLocation ( loc ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . skipPastMatch ( "" , "" ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; enum_v . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; } type . addEnumerator ( enum_v ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; return type ; } public void typedef ( ISVDBAddChildItem parent ) throws SVParseException { SVDBTypedefStmt typedef = null ; SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . readKeyword ( "" ) ; SVDBTypeInfo type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; if ( type . getType ( ) != SVDBItemType . TypeInfoFwdDecl ) { String id = fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" ) ) { type . setArrayDim ( var_dim ( ) ) ; } typedef = new SVDBTypedefStmt ( type , id ) ; typedef . setLocation ( start ) ; } else { typedef = new SVDBTypedefStmt ( type , type . getName ( ) ) ; typedef . setLocation ( start ) ; } fLexer . readOperator ( "" ) ; parent . addChildItem ( typedef ) ; } public List < SVDBVarDimItem > var_dim ( ) throws SVParseException { List < SVDBVarDimItem > ret = new ArrayList < SVDBVarDimItem > ( ) ; while ( fLexer . peek ( ) != null ) { fLexer . readOperator ( "" ) ; SVDBVarDimItem dim = new SVDBVarDimItem ( ) ; if ( fLexer . peekOperator ( "" ) ) { dim . setDimType ( DimType . Unsized ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; dim . setDimType ( DimType . Queue ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; dim . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; } } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; dim . setDimType ( DimType . Associative ) ; } else { SVToken first = fLexer . consumeToken ( ) ; if ( first . isNumber ( ) || first . isOperator ( ) || ( fLexer . peekOperator ( ) && ! fLexer . peekOperator ( "" ) ) ) { fLexer . ungetToken ( first ) ; dim . setDimType ( DimType . Sized ) ; SVDBExpr expr = parsers ( ) . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; dim . setExpr ( new SVDBRangeExpr ( expr , fParsers . exprParser ( ) . expression ( ) ) ) ; } else { dim . setExpr ( expr ) ; } } else { fLexer . ungetToken ( first ) ; dim . setDimType ( DimType . Associative ) ; dim . setTypeInfo ( parsers ( ) . dataTypeParser ( ) . data_type ( ) ) ; } } ret . add ( dim ) ; fLexer . readOperator ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { break ; } } return ret ; } public List < SVDBVarDimItem > vector_dim ( ) throws SVParseException { List < SVDBVarDimItem > ret = new ArrayList < SVDBVarDimItem > ( ) ; while ( fLexer . peek ( ) != null ) { fLexer . readOperator ( "" ) ; SVDBVarDimItem dim = new SVDBVarDimItem ( ) ; dim . setDimType ( DimType . Sized ) ; debug ( "" ) ; SVDBExpr expr = parsers ( ) . exprParser ( ) . expression ( ) ; debug ( "" + fLexer . peek ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; dim . setExpr ( new SVDBRangeExpr ( expr , fParsers . exprParser ( ) . expression ( ) ) ) ; } else { dim . setExpr ( expr ) ; } ret . add ( dim ) ; fLexer . readOperator ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { break ; } } return ret ; } public List < SVDBVarDimItem > packed_dim ( ) throws SVParseException { List < SVDBVarDimItem > ret = new ArrayList < SVDBVarDimItem > ( ) ; while ( fLexer . peek ( ) != null ) { fLexer . readOperator ( "" ) ; SVDBVarDimItem dim = new SVDBVarDimItem ( ) ; if ( fLexer . peekOperator ( "" ) ) { dim . setDimType ( DimType . Unsized ) ; } else if ( fLexer . peekOperator ( "" ) ) { error ( "" ) ; fLexer . eatToken ( ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; error ( "" ) ; } else { dim . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; } ret . add ( dim ) ; fLexer . readOperator ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { break ; } } return ret ; } private void struct_union_body ( ISVDBAddChildItem parent ) throws SVParseException { if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } fLexer . readOperator ( "" ) ; do { SVDBLocation it_start = fLexer . getStartLocation ( ) ; SVDBTypeInfo type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; SVDBVarDeclStmt var = new SVDBVarDeclStmt ( type , ) ; var . setLocation ( it_start ) ; while ( fLexer . peek ( ) != null ) { it_start = fLexer . getStartLocation ( ) ; String name = fLexer . readId ( ) ; SVDBVarDeclItem vi = new SVDBVarDeclItem ( name ) ; vi . setLocation ( it_start ) ; if ( fLexer . peekOperator ( "" ) ) { vi . setArrayDim ( var_dim ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; vi . setInitExpr ( fParsers . exprParser ( ) . expression ( ) ) ; } var . addChildItem ( vi ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } parent . addChildItem ( var ) ; fLexer . readOperator ( "" ) ; } while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) ; fLexer . readOperator ( "" ) ; } public SVDBTypeInfoClassType class_type ( ) throws SVParseException { SVDBTypeInfoClassType class_type = new SVDBTypeInfoClassType ( "" ) ; while ( fLexer . peek ( ) != null ) { String id = fLexer . readId ( ) ; SVDBTypeInfoClassItem class_item = new SVDBTypeInfoClassItem ( id ) ; class_type . addClassItem ( class_item ) ; if ( fLexer . peekOperator ( "" ) ) { SVDBParamValueAssignList param_assign = parsers ( ) . paramValueAssignParser ( ) . parse ( true ) ; class_item . setParamAssignList ( param_assign ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } return class_type ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . scanutils . ITextScanner ; public class SVProceduralBlockParser { public SVProceduralBlockParser ( ) { } public Object parse ( ITextScanner scanner ) { return null ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVBlockItemDeclParser extends SVParserBase { public SVBlockItemDeclParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent , SVDBTypeInfo type , SVDBLocation start ) throws SVParseException { parse ( parent , type , start , true ) ; } public void parse ( ISVDBAddChildItem parent , SVDBTypeInfo type , SVDBLocation start , boolean consume_terminator ) throws SVParseException { if ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . dataTypeParser ( ) . typedef ( parent ) ; } else { String dir = null ; if ( start == null ) { start = fLexer . getStartLocation ( ) ; } if ( fLexer . peekKeyword ( "" , "" , "" ) ) { dir = fLexer . eatToken ( ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; } if ( ( ( fLexer . peekKeyword ( SVKeywords . fBuiltinTypes ) ) && ! fLexer . peekKeyword ( "" ) ) || ! SVKeywords . isSVKeyword ( fLexer . peek ( ) ) || fLexer . peekKeyword ( "" , "" , "" ) ) { String name = null ; if ( type == null ) { type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; } if ( fDebugEn ) { debug ( "" + type + "" + fLexer . peek ( ) ) ; } if ( dir != null && fLexer . peekOperator ( ) ) { name = type . getName ( ) ; type = new SVDBTypeInfoBuiltin ( dir ) ; } SVDBVarDeclStmt var_decl = new SVDBVarDeclStmt ( type , ) ; var_decl . setLocation ( start ) ; parent . addChildItem ( var_decl ) ; if ( ! fLexer . peekOperator ( "" ) ) { while ( fLexer . peek ( ) != null ) { SVDBLocation it_start = fLexer . getStartLocation ( ) ; if ( name == null ) { name = fLexer . readId ( ) ; } SVDBVarDeclItem var = new SVDBVarDeclItem ( name ) ; var . setLocation ( it_start ) ; var_decl . addChildItem ( var ) ; if ( fLexer . peekOperator ( "" ) ) { var . setArrayDim ( parsers ( ) . dataTypeParser ( ) . var_dim ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; var . setInitExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { SVToken comma_tok = fLexer . consumeToken ( ) ; SVToken post_var = fLexer . consumeToken ( ) ; SVToken post_post_var = fLexer . consumeToken ( ) ; if ( post_var != null && post_var . isIdentifier ( ) && post_post_var != null && ! post_post_var . isIdentifier ( ) ) { fLexer . ungetToken ( post_post_var ) ; fLexer . ungetToken ( post_var ) ; } else { fLexer . ungetToken ( post_post_var ) ; fLexer . ungetToken ( post_var ) ; fLexer . ungetToken ( comma_tok ) ; break ; } } else { break ; } name = null ; } if ( consume_terminator ) { fLexer . readOperator ( "" ) ; } } } else { error ( "" + fLexer . peek ( ) + "" ) ; } } } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . log . ILogHandle ; public interface ISVParser { SVLexer lexer ( ) ; void error ( String msg ) throws SVParseException ; void error ( SVParseException e ) throws SVParseException ; void warning ( String msg , int lineno ) ; boolean error_limit_reached ( ) ; void disableErrors ( boolean dis ) ; SVParsers parsers ( ) ; void debug ( String msg , Exception e ) ; ILogHandle getLogHandle ( ) ; } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; public class SVPortListParser extends SVParserBase { public SVPortListParser ( ISVParser parser ) { super ( parser ) ; } public List < SVDBParamPortDecl > parse ( ) throws SVParseException { List < SVDBParamPortDecl > ports = new ArrayList < SVDBParamPortDecl > ( ) ; int dir = SVDBParamPortDecl . Direction_Input ; SVDBTypeInfo last_type = null ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; return ports ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; return ports ; } while ( true ) { SVDBLocation it_start = fLexer . getStartLocation ( ) ; if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { String dir_s = fLexer . eatToken ( ) ; if ( dir_s . equals ( "" ) ) { dir = SVDBParamPortDecl . Direction_Input ; } else if ( dir_s . equals ( "" ) ) { dir = SVDBParamPortDecl . Direction_Output ; } else if ( dir_s . equals ( "" ) ) { dir = SVDBParamPortDecl . Direction_Inout ; } else if ( dir_s . equals ( "" ) ) { dir = SVDBParamPortDecl . Direction_Ref ; } } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readKeyword ( "" ) ; dir = ( SVDBParamPortDecl . Direction_Ref | SVDBParamPortDecl . Direction_Const ) ; } SVDBTypeInfo type = null ; String id = null ; if ( fLexer . peekOperator ( "" ) ) { SVDBTypeInfoBuiltin bi_type = new SVDBTypeInfoBuiltin ( "" ) ; bi_type . setVectorDim ( fParsers . dataTypeParser ( ) . vector_dim ( ) ) ; type = bi_type ; id = fLexer . readId ( ) ; } else { type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; if ( fLexer . peekOperator ( "" , "" , "" , "" ) ) { id = type . getName ( ) ; if ( last_type == null ) { } type = last_type ; } else { id = fLexer . readIdOrKeyword ( ) ; last_type = type ; } } SVDBParamPortDecl param_r = new SVDBParamPortDecl ( type ) ; param_r . setDir ( dir ) ; param_r . setLocation ( it_start ) ; SVDBVarDeclItem param = new SVDBVarDeclItem ( id ) ; param_r . addChildItem ( param ) ; if ( fLexer . peekOperator ( "" ) ) { param . setArrayDim ( parsers ( ) . dataTypeParser ( ) . var_dim ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; param . setInitExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; if ( fDebugEn ) { debug ( "" + param . getInitExpr ( ) ) ; } } ports . add ( param_r ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; return ports ; } } package net . sf . sveditor . core . parser ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . Stack ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . expr . SVCoverageExpr ; import net . sf . sveditor . core . db . expr . SVDBArrayAccessExpr ; import net . sf . sveditor . core . db . expr . SVDBAssignExpr ; import net . sf . sveditor . core . db . expr . SVDBAssignmentPatternExpr ; import net . sf . sveditor . core . db . expr . SVDBAssignmentPatternRepeatExpr ; import net . sf . sveditor . core . db . expr . SVDBBinaryExpr ; import net . sf . sveditor . core . db . expr . SVDBCastExpr ; import net . sf . sveditor . core . db . expr . SVDBClockingEventExpr ; import net . sf . sveditor . core . db . expr . SVDBClockingEventExpr . ClockingEventType ; import net . sf . sveditor . core . db . expr . SVDBConcatenationExpr ; import net . sf . sveditor . core . db . expr . SVDBCondExpr ; import net . sf . sveditor . core . db . expr . SVDBCoverBinsExpr ; import net . sf . sveditor . core . db . expr . SVDBCoverpointExpr ; import net . sf . sveditor . core . db . expr . SVDBCtorExpr ; import net . sf . sveditor . core . db . expr . SVDBCtorExpr . CtorType ; import net . sf . sveditor . core . db . expr . SVDBCycleDelayExpr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBFieldAccessExpr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; import net . sf . sveditor . core . db . expr . SVDBIncDecExpr ; import net . sf . sveditor . core . db . expr . SVDBInsideExpr ; import net . sf . sveditor . core . db . expr . SVDBLiteralExpr ; import net . sf . sveditor . core . db . expr . SVDBMinTypMaxExpr ; import net . sf . sveditor . core . db . expr . SVDBNameMappedExpr ; import net . sf . sveditor . core . db . expr . SVDBNamedArgExpr ; import net . sf . sveditor . core . db . expr . SVDBNullExpr ; import net . sf . sveditor . core . db . expr . SVDBParamIdExpr ; import net . sf . sveditor . core . db . expr . SVDBParenExpr ; import net . sf . sveditor . core . db . expr . SVDBRandomizeCallExpr ; import net . sf . sveditor . core . db . expr . SVDBRangeDollarBoundExpr ; import net . sf . sveditor . core . db . expr . SVDBRangeExpr ; import net . sf . sveditor . core . db . expr . SVDBStringExpr ; import net . sf . sveditor . core . db . expr . SVDBTFCallExpr ; import net . sf . sveditor . core . db . expr . SVDBTypeExpr ; import net . sf . sveditor . core . db . expr . SVDBUnaryExpr ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVExprParser extends SVParserBase { public static boolean fUseFullExprParser = true ; private Stack < Boolean > fEventExpr ; private Stack < Boolean > fAssertionExpr ; private boolean fEnableNameMappedPrimary = false ; public SVExprParser ( ISVParser parser ) { super ( parser ) ; fAssertionExpr = new Stack < Boolean > ( ) ; fAssertionExpr . push ( false ) ; fEventExpr = new Stack < Boolean > ( ) ; fEventExpr . push ( false ) ; } public SVDBClockingEventExpr clocking_event ( ) throws SVParseException { SVDBClockingEventExpr expr = new SVDBClockingEventExpr ( ) ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { SVDBParenExpr p = new SVDBParenExpr ( ) ; p . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; expr . setClockingEventType ( ClockingEventType . Any ) ; } else { expr . setClockingEventType ( ClockingEventType . Expr ) ; p . setExpr ( event_expression ( ) ) ; expr . setExpr ( p ) ; } fLexer . readOperator ( "" ) ; } else if ( fLexer . peekOperator ( "" ) ) { expr . setClockingEventType ( ClockingEventType . Any ) ; fLexer . readOperator ( "" ) ; } else { expr . setClockingEventType ( ClockingEventType . Expr ) ; expr . setExpr ( idExpr ( ) ) ; } return expr ; } private final static Set < String > fUnaryModulePathOperators ; private final static Set < String > fBinaryModulePathOperators ; static { fUnaryModulePathOperators = new HashSet < String > ( ) ; fUnaryModulePathOperators . add ( "" ) ; fUnaryModulePathOperators . add ( "" ) ; fUnaryModulePathOperators . add ( "" ) ; fUnaryModulePathOperators . add ( "" ) ; fUnaryModulePathOperators . add ( "" ) ; fUnaryModulePathOperators . add ( "" ) ; fUnaryModulePathOperators . add ( "" ) ; fUnaryModulePathOperators . add ( "" ) ; fUnaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators = new HashSet < String > ( ) ; fBinaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators . add ( "" ) ; fBinaryModulePathOperators . add ( "" ) ; } public SVDBExpr module_path_expression ( ) throws SVParseException { SVDBExpr ret = null ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekOperator ( fUnaryModulePathOperators ) ) { fLexer . eatToken ( ) ; module_path_primary ( ) ; } if ( fLexer . peekOperator ( fBinaryModulePathOperators ) ) { String op = fLexer . eatToken ( ) ; module_path_expression ( ) ; } module_path_primary ( ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return ret ; } private SVDBExpr module_path_primary ( ) throws SVParseException { SVDBExpr ret = null ; if ( fLexer . peekNumber ( ) ) { ret = literalExpr ( ) ; } else if ( fLexer . peekId ( ) ) { ret = idExpr ( ) ; if ( fLexer . peekOperator ( "" ) ) { error ( "" ) ; } } else if ( fLexer . peekOperator ( "" ) ) { error ( "" ) ; fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { } else { } } else if ( fLexer . peekOperator ( "" ) ) { error ( "" ) ; } return ret ; } public SVDBExpr cycle_delay ( ) throws SVParseException { SVDBCycleDelayExpr expr = new SVDBCycleDelayExpr ( ) ; expr . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readOperator ( "" ) ; if ( fLexer . peekNumber ( ) ) { expr . setExpr ( literalExpr ( ) ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; expr . setExpr ( expression ( ) ) ; fLexer . readOperator ( "" ) ; } else { expr . setExpr ( idExpr ( ) ) ; } return expr ; } public SVDBExpr delay_expr ( int max_delays ) throws SVParseException { SVDBExpr expr = null ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( ( max_delays != ) && ( max_delays != ) ) { error ( "" ) ; } fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; expr = fParsers . exprParser ( ) . expression ( ) ; fLexer . readOperator ( "" ) ; expr = fParsers . exprParser ( ) . expression ( ) ; } for ( int i = ; i <= max_delays ; i ++ ) { if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; expr = fParsers . exprParser ( ) . expression ( ) ; fLexer . readOperator ( "" ) ; expr = fParsers . exprParser ( ) . expression ( ) ; } } } fLexer . readOperator ( "" ) ; } else { expr = delay_value ( ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return expr ; } private SVDBExpr delay_value ( ) throws SVParseException { SVDBExpr ret = null ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekNumber ( ) ) { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } ret = new SVDBLiteralExpr ( fLexer . eatToken ( ) ) ; } else if ( fLexer . peekKeyword ( "" ) ) { ret = new SVDBLiteralExpr ( fLexer . eatToken ( ) ) ; } else if ( fLexer . peekId ( ) ) { if ( fDebugEn ) { debug ( "" ) ; } ret = idExpr ( ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } while ( fLexer . peekOperator ( "" , "" , "" ) ) { SVToken t = fLexer . consumeToken ( ) ; if ( fAssertionExpr . peek ( ) ) { if ( ! fLexer . peekOperator ( ) ) { fLexer . ungetToken ( t ) ; ret = selector ( ret ) ; } else { fLexer . ungetToken ( t ) ; break ; } } else { fLexer . ungetToken ( t ) ; ret = selector ( ret ) ; } } } else { error ( "" + fLexer . peek ( ) ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return ret ; } public SVDBExpr datatype_or_expression ( ) throws SVParseException { if ( fLexer . peekKeyword ( "" , "" ) || fLexer . peekKeyword ( SVKeywords . fBuiltinTypes ) ) { SVDBTypeExpr expr = new SVDBTypeExpr ( ) ; expr . setLocation ( fLexer . getStartLocation ( ) ) ; SVDBTypeInfo info = fParsers . dataTypeParser ( ) . data_type ( ) ; expr . setTypeInfo ( info ) ; return expr ; } else { return expression ( ) ; } } public SVDBExpr assert_expression ( ) throws SVParseException { fAssertionExpr . push ( true ) ; fEventExpr . push ( true ) ; try { return expression ( ) ; } finally { fAssertionExpr . pop ( ) ; fEventExpr . pop ( ) ; } } public SVDBExpr event_expression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } fEventExpr . push ( true ) ; try { return expression ( ) ; } finally { fEventExpr . pop ( ) ; } } public SVDBExpr variable_lvalue ( ) throws SVParseException { SVDBExpr lvalue ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { lvalue = concatenation_or_repetition ( ) ; } else { lvalue = unaryExpression ( ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return lvalue ; } public SVDBExpr const_or_range_expression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } SVDBExpr expr = expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = new SVDBRangeExpr ( expr , expression ( ) ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return expr ; } public SVDBExpr constant_mintypmax_expression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } SVDBExpr expr = expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; SVDBExpr typ = expression ( ) ; fLexer . readOperator ( "" ) ; SVDBExpr max = expression ( ) ; expr = new SVDBMinTypMaxExpr ( expr , typ , max ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return expr ; } public SVDBExpr expression ( ) throws SVParseException { SVDBExpr expr = null ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } expr = assignmentExpression ( ) ; if ( fEventExpr . peek ( ) && fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; expr = new SVDBBinaryExpr ( expr , "" , expression ( ) ) ; } if ( fEventExpr . peek ( ) && fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = new SVDBBinaryExpr ( expr , "" , expression ( ) ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return expr ; } public SVDBExpr hierarchical_identifier ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } SVDBExpr ret ; String id = fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" , "" ) ) { ret = new SVDBFieldAccessExpr ( new SVDBIdentifierExpr ( id ) , false , hierarchical_identifier_int ( ) ) ; } else { ret = new SVDBIdentifierExpr ( id ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return ret ; } private SVDBExpr hierarchical_identifier_int ( ) throws SVParseException { fLexer . readOperator ( "" , "" ) ; String id = fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" , "" ) ) { return new SVDBFieldAccessExpr ( new SVDBIdentifierExpr ( id ) , false , hierarchical_identifier_int ( ) ) ; } else { return new SVDBIdentifierExpr ( id ) ; } } public void coverpoint_target ( SVDBCoverpointExpr coverpoint ) throws SVParseException { try { SVDBExpr target = expression ( ) ; coverpoint . setTarget ( target ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; SVDBExpr iff_expr = expression ( ) ; fLexer . readOperator ( "" ) ; coverpoint . setIFFExpr ( iff_expr ) ; } } catch ( EOFException e ) { e . printStackTrace ( ) ; } } private static final Set < String > cp_body_items ; static { cp_body_items = new HashSet < String > ( ) ; cp_body_items . add ( "" ) ; cp_body_items . add ( "" ) ; cp_body_items . add ( "" ) ; cp_body_items . add ( "" ) ; cp_body_items . add ( "" ) ; cp_body_items . add ( "" ) ; } public void coverpoint_body ( SVDBCoverpointExpr coverpoint ) throws SVParseException { try { while ( fLexer . peekKeyword ( cp_body_items ) ) { if ( fLexer . peekKeyword ( "" , "" ) ) { String kw = fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; String option = fLexer . readId ( ) ; if ( ! fLexer . peekString ( ) && ! fLexer . peekNumber ( ) ) { error ( "" + fLexer . peek ( ) + "" ) ; } if ( kw . equals ( "" ) ) { coverpoint . addOption ( option , fLexer . eatToken ( ) ) ; } else { coverpoint . addTypeOption ( option , fLexer . eatToken ( ) ) ; } } else { if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } String bins_kw = fLexer . readKeyword ( "" , "" , "" ) ; String bins_id = fLexer . readId ( ) ; SVDBCoverBinsExpr bins = new SVDBCoverBinsExpr ( bins_id , bins_kw ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; bins . setIsArray ( true ) ; if ( ! fLexer . peekOperator ( "" ) ) { bins . setArrayExpr ( expression ( ) ) ; } fLexer . readOperator ( "" ) ; } fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { open_range_list ( bins . getRangeList ( ) ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; bins . setIsDefault ( true ) ; } else { error ( "" + fLexer . peek ( ) ) ; } coverpoint . getCoverBins ( ) . add ( bins ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } } } } catch ( EOFException e ) { } } public List < SVCoverageExpr > parse_covercross ( InputStream in ) throws SVParseException { return null ; } public SVDBExpr assignmentExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = conditionalExpression ( ) ; if ( fLexer . peekOperator ( SVKeywords . fAssignmentOps ) ) { String op = fLexer . readOperator ( ) ; SVDBExpr rhs = assignmentExpression ( ) ; a = new SVDBAssignExpr ( a , op , rhs ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; SVDBInsideExpr inside = new SVDBInsideExpr ( a ) ; open_range_list ( inside . getValueRangeList ( ) ) ; a = inside ; if ( fLexer . peekOperator ( SVKeywords . fBinaryOps ) ) { a = new SVDBBinaryExpr ( a , fLexer . eatToken ( ) , expression ( ) ) ; } } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return a ; } public void open_range_list ( List < SVDBExpr > list ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } fLexer . readOperator ( "" ) ; do { if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } if ( fLexer . peekOperator ( "" ) ) { list . add ( parse_range ( ) ) ; } else { list . add ( expression ( ) ) ; } } while ( fLexer . peekOperator ( "" ) ) ; fLexer . readOperator ( "" ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } } public SVDBRangeExpr parse_range ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } fLexer . readOperator ( "" ) ; SVDBExpr left = expression ( ) ; SVDBExpr right ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; right = new SVDBRangeDollarBoundExpr ( ) ; } else { right = expression ( ) ; } fLexer . readOperator ( "" ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return new SVDBRangeExpr ( left , right ) ; } public SVDBExpr conditionalExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = conditionalOrExpression ( ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; SVDBExpr lhs = a ; SVDBExpr mhs = expression ( ) ; fLexer . readOperator ( "" ) ; SVDBExpr rhs = conditionalExpression ( ) ; a = new SVDBCondExpr ( lhs , mhs , rhs ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr conditionalOrExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = conditionalAndExpression ( ) ; while ( fLexer . peekOperator ( "" ) || ( fEventExpr . peek ( ) && fLexer . peekKeyword ( "" ) ) ) { String op = fLexer . eatToken ( ) ; a = new SVDBBinaryExpr ( a , op , conditionalAndExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr conditionalAndExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = inclusiveOrExpression ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; a = new SVDBBinaryExpr ( a , "" , inclusiveOrExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr inclusiveOrExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = exclusiveOrExpression ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; a = new SVDBBinaryExpr ( a , "" , exclusiveOrExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr exclusiveOrExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = exclusiveNorExpression1 ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; a = new SVDBBinaryExpr ( a , "" , exclusiveNorExpression1 ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr exclusiveNorExpression1 ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = exclusiveNorExpression2 ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; a = new SVDBBinaryExpr ( a , "" , exclusiveNorExpression2 ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr exclusiveNorExpression2 ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = andExpression ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; a = new SVDBBinaryExpr ( a , "" , andExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr andExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = equalityExpression ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; a = new SVDBBinaryExpr ( a , "" , equalityExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr equalityExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = relationalExpression ( ) ; while ( fLexer . peekOperator ( "" , "" , "" , "" , "" , "" ) ) { a = new SVDBBinaryExpr ( a , fLexer . readOperator ( ) , relationalExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr relationalExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = shiftExpression ( ) ; while ( fLexer . peekOperator ( "" , ">" , "" , "" ) ) { a = new SVDBBinaryExpr ( a , fLexer . readOperator ( ) , shiftExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr shiftExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = additiveExpression ( ) ; while ( fLexer . peekOperator ( "" , "" , "" , "" ) ) { a = new SVDBBinaryExpr ( a , fLexer . readOperator ( ) , additiveExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr additiveExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBExpr a = multiplicativeExpression ( ) ; while ( fLexer . peekOperator ( "" , "" ) ) { a = new SVDBBinaryExpr ( a , fLexer . readOperator ( ) , multiplicativeExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr multiplicativeExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } SVDBExpr a = unaryExpression ( ) ; while ( fLexer . peekOperator ( "" , "" , "" , "" ) ) { a = new SVDBBinaryExpr ( a , fLexer . readOperator ( ) , unaryExpression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return a ; } public SVDBExpr unaryExpression ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekOperator ( "" , "" ) ) { return new SVDBIncDecExpr ( fLexer . readOperator ( ) , unaryExpression ( ) ) ; } else if ( fEventExpr . peek ( ) && fLexer . peekKeyword ( "" , "" , "" ) ) { SVDBExpr ret = new SVDBUnaryExpr ( fLexer . eatToken ( ) , expression ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBBinaryExpr ( ret , "" , expression ( ) ) ; } return ret ; } if ( fLexer . peekOperator ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) || ( fAssertionExpr . peek ( ) && fLexer . peekOperator ( "" ) ) ) { String op = fLexer . readOperator ( ) ; SVDBUnaryExpr ret = new SVDBUnaryExpr ( op , unaryExpression ( ) ) ; if ( fDebugEn ) { debug ( "" + op ) ; } return ret ; } else if ( fLexer . peekOperator ( "" ) ) { return assignment_pattern_expr ( ) ; } SVDBExpr a = primary ( ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } while ( fLexer . peekOperator ( "" , "" , "" ) ) { SVToken t = fLexer . consumeToken ( ) ; if ( fAssertionExpr . peek ( ) ) { if ( ! fLexer . peekOperator ( ) ) { fLexer . ungetToken ( t ) ; a = selector ( a ) ; } else { fLexer . ungetToken ( t ) ; break ; } } else { fLexer . ungetToken ( t ) ; a = selector ( a ) ; } } if ( fLexer . peekOperator ( "" ) ) { SVToken tok = fLexer . consumeToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . ungetToken ( tok ) ; a = assignment_pattern_expr ( ) ; } else { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } a = new SVDBCastExpr ( a , expression ( ) ) ; } } while ( fLexer . peekOperator ( "" , "" ) ) { a = new SVDBIncDecExpr ( fLexer . readOperator ( ) , a ) ; } return a ; } private SVDBExpr assignment_pattern_expr ( ) throws SVParseException { SVDBExpr ret_top ; fLexer . readOperator ( "" ) ; fLexer . readOperator ( "" ) ; if ( fDebugEn ) { debug ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret_top = new SVDBConcatenationExpr ( ) ; } else { try { fEnableNameMappedPrimary = true ; SVDBExpr expr1 = expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { SVDBAssignmentPatternRepeatExpr ret = new SVDBAssignmentPatternRepeatExpr ( expr1 ) ; fLexer . eatToken ( ) ; while ( true ) { SVDBExpr expr = expression ( ) ; ret . getPatternList ( ) . add ( expr ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; ret_top = ret ; } else { SVDBAssignmentPatternExpr ret = new SVDBAssignmentPatternExpr ( ) ; ret . getPatternList ( ) . add ( expr1 ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; SVDBExpr expr = expression ( ) ; ret . getPatternList ( ) . add ( expr ) ; } ret_top = ret ; } fLexer . readOperator ( "" ) ; } finally { fEnableNameMappedPrimary = false ; } } return ret_top ; } public SVDBExpr primary ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } SVDBExpr ret = null ; if ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } fLexer . eatToken ( ) ; SVDBExpr a = expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; SVDBExpr expr = fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = fParsers . exprParser ( ) . expression ( ) ; } } fLexer . readOperator ( "" ) ; fLexer . peek ( ) ; if ( fLexer . isNumber ( ) || fLexer . isIdentifier ( ) || fLexer . peekOperator ( "" , "" , "" ) || fLexer . peekKeyword ( "" , "" , "" ) ) { ret = new SVDBCastExpr ( a , unaryExpression ( ) ) ; } else { ret = new SVDBParenExpr ( a ) ; } } else { fLexer . peek ( ) ; if ( fLexer . isNumber ( ) ) { if ( fDebugEn ) { debug ( "" ) ; } SVToken tmp = fLexer . consumeToken ( ) ; if ( fEnableNameMappedPrimary && fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBNameMappedExpr ( tmp . getImage ( ) , expression ( ) ) ; } else { ret = new SVDBLiteralExpr ( tmp . getImage ( ) ) ; } } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBRangeDollarBoundExpr ( ) ; } else if ( fLexer . peekString ( ) ) { if ( fDebugEn ) { debug ( "" ) ; } SVToken tmp = fLexer . consumeToken ( ) ; if ( fEnableNameMappedPrimary && fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBNameMappedExpr ( tmp . getImage ( ) , expression ( ) ) ; } else { ret = new SVDBStringExpr ( tmp . getImage ( ) ) ; } } else if ( fLexer . peekKeyword ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } fLexer . eatToken ( ) ; ret = new SVDBNullExpr ( ) ; } else if ( fLexer . isIdentifier ( ) || SVKeywords . isBuiltInType ( fLexer . peek ( ) ) || fLexer . peekKeyword ( "" , "" , "" , "" ) ) { if ( fDebugEn ) { debug ( "" + fLexer . getImage ( ) + "" ) ; } String id = fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fParsers . attrParser ( ) . parse ( null ) ; } if ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } ret = new SVDBParamIdExpr ( id ) ; fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) { ( ( SVDBParamIdExpr ) ret ) . addParamExpr ( datatype_or_expression ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } else if ( fLexer . peekOperator ( "" ) || fLexer . peekKeyword ( "" ) ) { if ( id . equals ( "" ) ) { ret = randomize_call ( null ) ; } else if ( fLexer . peekOperator ( "" ) ) { ret = tf_args_call ( null , id ) ; } else { ret = tf_noargs_with_call ( null , id ) ; } } else if ( id . equals ( "" ) ) { ret = ctor_call ( ) ; } else if ( fLexer . peekKeyword ( SVKeywords . fBuiltinDeclTypes ) || fLexer . peekKeyword ( "" ) ) { fLexer . startCapture ( ) ; fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; } ret = new SVDBIdentifierExpr ( fLexer . endCapture ( ) ) ; } else { if ( fEnableNameMappedPrimary && fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( fDebugEn ) { debug ( "" ) ; } ret = new SVDBNameMappedExpr ( id , expression ( ) ) ; } else { ret = new SVDBIdentifierExpr ( id ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } } } else if ( fLexer . peekOperator ( "" ) ) { ret = concatenation_or_repetition ( ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBIdentifierExpr ( "" ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBIdentifierExpr ( "" ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBIdentifierExpr ( "" ) ; } else if ( fEventExpr . peek ( ) && fLexer . peekOperator ( "" ) ) { ret = clocking_event ( ) ; } else if ( fEventExpr . peek ( ) && fLexer . peekOperator ( "" ) ) { ret = cycle_delay ( ) ; } else { error ( "" + fLexer . getImage ( ) + "" ) ; } } if ( fDebugEn ) { debug ( "" ) ; } return ret ; } private SVDBExpr concatenation_or_repetition ( ) throws SVParseException { SVDBExpr expr = null ; if ( fDebugEn ) { debug ( "" ) ; } fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = new SVDBConcatenationExpr ( ) ; } else if ( fLexer . peekOperator ( "" , "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( SVKeywords . fBuiltinTypes ) ) { expr = new SVDBTypeExpr ( fParsers . dataTypeParser ( ) . data_type ( ) ) ; } else if ( ! fLexer . peekOperator ( "" ) ) { expr = new SVDBLiteralExpr ( fLexer . eatToken ( ) ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null ) { expression ( ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; expression ( ) ; if ( fLexer . peekOperator ( "" , "" , "" ) ) { fLexer . eatToken ( ) ; expression ( ) ; } fLexer . readOperator ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; fLexer . readOperator ( "" ) ; expr = new SVDBConcatenationExpr ( ) ; } else { try { SVDBExpr expr0 = expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } fLexer . eatToken ( ) ; SVDBAssignmentPatternRepeatExpr ret = new SVDBAssignmentPatternRepeatExpr ( expr ) ; ret . setRepeatExpr ( expr0 ) ; while ( fLexer . peek ( ) != null ) { ret . getPatternList ( ) . add ( expression ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; fLexer . readOperator ( "" ) ; expr = ret ; } else { if ( fDebugEn ) { debug ( "" ) ; } SVDBConcatenationExpr ret = new SVDBConcatenationExpr ( ) ; ret . getElements ( ) . add ( expr0 ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret . getElements ( ) . add ( expression ( ) ) ; } fLexer . readOperator ( "" ) ; expr = ret ; } } finally { } } if ( fDebugEn ) { debug ( "" ) ; } return expr ; } public List < SVDBExpr > arguments ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; return new ArrayList < SVDBExpr > ( ) ; } List < SVDBExpr > arguments = argumentList ( ) ; fLexer . readOperator ( "" ) ; if ( fDebugEn ) { debug ( "" ) ; } return arguments ; } private List < SVDBExpr > argumentList ( ) throws SVParseException { List < SVDBExpr > arguments = new ArrayList < SVDBExpr > ( ) ; if ( fDebugEn ) { debug ( "" ) ; } for ( ; ; ) { if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; SVDBNamedArgExpr arg_expr = new SVDBNamedArgExpr ( ) ; String name = fLexer . readId ( ) ; arg_expr . setArgName ( name ) ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { arg_expr . setExpr ( new SVDBLiteralExpr ( "" ) ) ; } else { arg_expr . setExpr ( expression ( ) ) ; } fLexer . readOperator ( "" ) ; arguments . add ( arg_expr ) ; } else if ( fLexer . peekOperator ( "" , "" ) ) { arguments . add ( new SVDBLiteralExpr ( "" ) ) ; } else { arguments . add ( expression ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } if ( fDebugEn ) { debug ( "" ) ; } return arguments ; } public SVDBExpr selector ( SVDBExpr expr ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } if ( fLexer . peekOperator ( "" , "" ) ) { String q = fLexer . eatToken ( ) ; fLexer . peek ( ) ; if ( fLexer . isIdentifier ( ) || fLexer . peekKeyword ( "" , "" , "" ) ) { String id = fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fParsers . attrParser ( ) . parse ( null ) ; } if ( fLexer . peekOperator ( "" ) || fLexer . peekKeyword ( "" ) ) { if ( id . equals ( "" ) ) { return randomize_call ( expr ) ; } else if ( fLexer . peekOperator ( "" ) ) { return tf_args_call ( expr , id ) ; } else { return tf_noargs_with_call ( expr , id ) ; } } if ( fDebugEn ) { debug ( "" ) ; } return new SVDBFieldAccessExpr ( expr , ( q . equals ( "" ) ) , new SVDBIdentifierExpr ( id ) ) ; } } if ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } fLexer . eatToken ( ) ; SVDBExpr low = expression ( ) ; SVDBExpr high = null ; if ( fLexer . peekOperator ( "" , "" , "" ) ) { fLexer . eatToken ( ) ; high = expression ( ) ; } fLexer . readOperator ( "" ) ; if ( expr == null ) { error ( "" ) ; } if ( fDebugEn ) { debug ( "" ) ; } return new SVDBArrayAccessExpr ( expr , low , high ) ; } error ( "" + fLexer . getImage ( ) + "" ) ; return null ; } private SVDBRandomizeCallExpr randomize_call ( SVDBExpr target ) throws SVParseException { List < SVDBExpr > arguments = null ; SVDBRandomizeCallExpr rand_call = null ; fAssertionExpr . push ( false ) ; fEventExpr . push ( false ) ; try { if ( fLexer . peekOperator ( "" ) ) { arguments = arguments ( ) ; } rand_call = new SVDBRandomizeCallExpr ( target , "" , arguments ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; rand_call . setWithBlock ( fParsers . constraintParser ( ) . constraint_set ( true ) ) ; } } finally { fAssertionExpr . pop ( ) ; fEventExpr . pop ( ) ; } return rand_call ; } private SVDBTFCallExpr tf_args_call ( SVDBExpr target , String id ) throws SVParseException { SVDBTFCallExpr tf = new SVDBTFCallExpr ( target , id , arguments ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; tf . setWithExpr ( expression ( ) ) ; fLexer . readOperator ( "" ) ; } return tf ; } private SVDBTFCallExpr tf_noargs_with_call ( SVDBExpr target , String id ) throws SVParseException { SVDBTFCallExpr tf = new SVDBTFCallExpr ( target , id , null ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; tf . setWithExpr ( expression ( ) ) ; if ( fLexer . peekOperator ( "" , "" , "" ) ) { fLexer . eatToken ( ) ; expression ( ) ; } fLexer . readOperator ( "" ) ; } else { fLexer . readOperator ( "" ) ; tf . setWithExpr ( expression ( ) ) ; fLexer . readOperator ( "" ) ; } } return tf ; } private SVDBCtorExpr ctor_call ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } SVDBCtorExpr ctor = new SVDBCtorExpr ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; ctor . setCtorType ( CtorType . CtorType_Dim ) ; ctor . setArg ( expression ( ) ) ; fLexer . readOperator ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { ctor . setCtorType ( CtorType . CtorType_Args ) ; ctor . setArgs ( arguments ( ) ) ; } else if ( fLexer . peekKeyword ( ) || fLexer . peekId ( ) ) { ctor . setCtorType ( CtorType . CtorType_Expr ) ; ctor . setArg ( expression ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } return ctor ; } public SVDBIdentifierExpr idExpr ( ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; SVDBIdentifierExpr ret = new SVDBIdentifierExpr ( fLexer . readId ( ) ) ; ret . setLocation ( start ) ; return ret ; } public SVDBLiteralExpr literalExpr ( ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; SVDBLiteralExpr ret = new SVDBLiteralExpr ( fLexer . readNumber ( ) ) ; ret . setLocation ( start ) ; return ret ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBConstraint ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBLiteralExpr ; import net . sf . sveditor . core . db . stmt . SVDBConstraintDistListItem ; import net . sf . sveditor . core . db . stmt . SVDBConstraintDistListStmt ; import net . sf . sveditor . core . db . stmt . SVDBConstraintForeachStmt ; import net . sf . sveditor . core . db . stmt . SVDBConstraintIfStmt ; import net . sf . sveditor . core . db . stmt . SVDBConstraintImplStmt ; import net . sf . sveditor . core . db . stmt . SVDBConstraintSetStmt ; import net . sf . sveditor . core . db . stmt . SVDBConstraintSolveBeforeStmt ; import net . sf . sveditor . core . db . stmt . SVDBExprStmt ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; public class SVConstraintParser extends SVParserBase { public SVConstraintParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent , int qualifiers ) throws SVParseException { SVDBConstraint c = new SVDBConstraint ( ) ; c . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; c . setName ( fParsers . SVParser ( ) . scopedIdentifier ( false ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { fLexer . readOperator ( "" ) ; parent . addChildItem ( c ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) { c . addChildItem ( constraint_set_item ( ) ) ; } fLexer . readOperator ( "" ) ; } } public SVDBStmt constraint_set ( boolean force_braces ) throws SVParseException { if ( fDebugEn ) { debug ( "" ) ; } if ( force_braces || fLexer . peekOperator ( "" ) ) { SVDBConstraintSetStmt ret = new SVDBConstraintSetStmt ( ) ; fLexer . readOperator ( "" ) ; while ( lexer ( ) . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) { SVDBStmt c_stmt = constraint_set_item ( ) ; ret . addConstraintStmt ( c_stmt ) ; } fLexer . readOperator ( "" ) ; if ( fDebugEn ) { debug ( "" ) ; } return ret ; } else { if ( fDebugEn ) { debug ( "" ) ; } return constraint_set_item ( ) ; } } private SVDBStmt constraint_set_item ( ) throws SVParseException { SVDBStmt ret = null ; if ( fLexer . peekKeyword ( "" ) ) { ret = solve_expression ( ) ; } else if ( fLexer . peekKeyword ( "" ) ) { ret = constraint_if_expression ( ) ; } else if ( fLexer . peekKeyword ( "" ) ) { ret = constraint_foreach ( ) ; } else { if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } SVDBExpr expr = fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekKeyword ( "" ) ) { ret = dist_expr ( ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBExprStmt ( expr ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret = new SVDBConstraintImplStmt ( expr , constraint_set ( false ) ) ; } else { error ( "" + fLexer . getImage ( ) ) ; } } return ret ; } public SVDBConstraintDistListStmt dist_expr ( ) throws SVParseException { SVDBConstraintDistListStmt dist_stmt = new SVDBConstraintDistListStmt ( ) ; fLexer . readKeyword ( "" ) ; dist_list ( dist_stmt ) ; fLexer . readOperator ( "" ) ; return dist_stmt ; } private void dist_list ( SVDBConstraintDistListStmt dist_stmt ) throws SVParseException { fLexer . readOperator ( "" ) ; SVDBConstraintDistListItem item = dist_item ( ) ; dist_stmt . addDistItem ( item ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; item = dist_item ( ) ; } fLexer . readOperator ( "" ) ; } private SVDBConstraintDistListItem dist_item ( ) throws SVParseException { SVDBConstraintDistListItem ret = new SVDBConstraintDistListItem ( ) ; if ( fLexer . peekOperator ( "" ) ) { ret . setLHS ( fParsers . exprParser ( ) . parse_range ( ) ) ; } else { ret . setLHS ( fParsers . exprParser ( ) . expression ( ) ) ; } if ( fLexer . peekOperator ( "" , "" ) ) { ret . setIsDist ( false ) ; ret . setRHS ( new SVDBLiteralExpr ( "" ) ) ; } else { String type = fLexer . readOperator ( "" , "" ) ; ret . setIsDist ( type . equals ( "" ) ) ; ret . setRHS ( fParsers . exprParser ( ) . expression ( ) ) ; } return ret ; } private SVDBConstraintIfStmt constraint_if_expression ( ) throws SVParseException { SVDBConstraintIfStmt ret ; if ( fDebugEn ) { debug ( "" ) ; } fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; SVDBExpr if_expr = fParsers . exprParser ( ) . expression ( ) ; fLexer . readOperator ( "" ) ; SVDBStmt constraint = constraint_set ( false ) ; if ( fLexer . peekKeyword ( "" ) ) { SVDBStmt else_stmt ; fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" ) ) { else_stmt = constraint_if_expression ( ) ; } else { else_stmt = constraint_set ( false ) ; } ret = new SVDBConstraintIfStmt ( if_expr , constraint , else_stmt , true ) ; } else { ret = new SVDBConstraintIfStmt ( if_expr , constraint , null , false ) ; } if ( fDebugEn ) { debug ( "" ) ; } return ret ; } private SVDBStmt constraint_foreach ( ) throws SVParseException { SVDBConstraintForeachStmt stmt = new SVDBConstraintForeachStmt ( ) ; stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; stmt . setExpr ( fParsers . exprParser ( ) . variable_lvalue ( ) ) ; fLexer . readOperator ( "" ) ; stmt . setStmt ( constraint_set ( false ) ) ; return stmt ; } private SVDBConstraintSolveBeforeStmt solve_expression ( ) throws SVParseException { SVDBConstraintSolveBeforeStmt ret = new SVDBConstraintSolveBeforeStmt ( ) ; fLexer . eatToken ( ) ; SVDBExpr expr = fParsers . exprParser ( ) . variable_lvalue ( ) ; ret . addSolveBefore ( expr ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret . addSolveBefore ( fParsers . exprParser ( ) . variable_lvalue ( ) ) ; } fLexer . readKeyword ( "" ) ; ret . addSolveAfter ( fParsers . exprParser ( ) . variable_lvalue ( ) ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret . addSolveAfter ( fParsers . exprParser ( ) . variable_lvalue ( ) ) ; } fLexer . readOperator ( "" ) ; return ret ; } } package net . sf . sveditor . core . parser ; import java . util . List ; import net . sf . sveditor . core . db . SVDBParamValueAssign ; import net . sf . sveditor . core . db . SVDBParamValueAssignList ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBNullExpr ; public class SVParameterValueAssignmentParser extends SVParserBase { public SVParameterValueAssignmentParser ( ISVParser parser ) { super ( parser ) ; } public SVDBParamValueAssignList parse ( boolean is_parameter ) throws SVParseException { SVDBParamValueAssignList ret = new SVDBParamValueAssignList ( ) ; if ( is_parameter ) { fLexer . readOperator ( "" ) ; } fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) { boolean is_mapped = false ; boolean is_wildcard = false ; boolean is_implicit_connection = false ; String name = null ; if ( ! is_parameter && fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; ret . addParameter ( new SVDBParamValueAssign ( "" , ( SVDBExpr ) null ) ) ; is_wildcard = true ; is_mapped = true ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; name = fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; is_mapped = true ; } else if ( fLexer . peekOperator ( "" ) ) { is_implicit_connection = true ; is_mapped = true ; ret . addParameter ( new SVDBParamValueAssign ( name , ( SVDBExpr ) null ) ) ; } } if ( ! is_wildcard && ! is_implicit_connection ) { if ( fLexer . peekOperator ( "" ) ) { ret . addParameter ( new SVDBParamValueAssign ( name , new SVDBNullExpr ( ) ) ) ; } else if ( ! fLexer . peekOperator ( "" ) ) { List < SVToken > id_list = parsers ( ) . SVParser ( ) . peekScopedStaticIdentifier_l ( false ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . ungetToken ( id_list ) ; SVDBTypeInfo type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; ret . addParameter ( new SVDBParamValueAssign ( name , type ) ) ; } else { fLexer . ungetToken ( id_list ) ; SVDBExpr val = parsers ( ) . exprParser ( ) . datatype_or_expression ( ) ; ret . addParameter ( new SVDBParamValueAssign ( name , val ) ) ; } } if ( is_mapped ) { fLexer . readOperator ( "" ) ; } } ret . setIsNamedMapping ( is_mapped ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; return ret ; } } package net . sf . sveditor . core . parser ; public class SVAbortParseException extends RuntimeException { private static final long serialVersionUID = ; } package net . sf . sveditor . core . parser ; public class SVParseException extends Exception { private String fFilename ; private int fLineno ; private int fLinepos ; private static final long serialVersionUID = ; private SVParseException ( String msg , String filename , int lineno , int linepos ) { super ( filename + "" + lineno + "" + msg ) ; fFilename = filename ; fLineno = lineno ; fLinepos = linepos ; } public String getFilename ( ) { return fFilename ; } public int getLineno ( ) { return fLineno ; } public int getLinepos ( ) { return fLinepos ; } public static SVParseException createParseException ( String msg , String filename , int lineno , int linepos ) { return new SVParseException ( msg , filename , lineno , linepos ) ; } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBProperty ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . stmt . SVDBExprStmt ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVPropertyParser extends SVParserBase { public SVPropertyParser ( ISVParser parser ) { super ( parser ) ; } public void property ( ISVDBAddChildItem parent ) throws SVParseException { SVDBProperty prop = new SVDBProperty ( ) ; fLexer . readKeyword ( "" ) ; prop . setName ( fLexer . readId ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( ! fLexer . peekOperator ( "" ) ) { while ( fLexer . peek ( ) != null ) { prop . addPropertyPort ( property_port_item ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } fLexer . readOperator ( "" ) ; } fLexer . readOperator ( "" ) ; parent . addChildItem ( prop ) ; while ( fLexer . peekKeyword ( SVKeywords . fBuiltinDeclTypes ) || fLexer . peekKeyword ( "" ) || fLexer . isIdentifier ( ) ) { SVDBLocation start = fLexer . getStartLocation ( ) ; if ( fLexer . peekKeyword ( "" ) || fLexer . peekKeyword ( SVKeywords . fBuiltinDeclTypes ) ) { parsers ( ) . blockItemDeclParser ( ) . parse ( prop , null , start ) ; } else { SVToken tok = fLexer . consumeToken ( ) ; if ( fLexer . peekOperator ( "" , "" ) || fLexer . peekId ( ) ) { fLexer . ungetToken ( tok ) ; final List < SVToken > tok_l = new ArrayList < SVToken > ( ) ; ISVTokenListener l = new ISVTokenListener ( ) { public void tokenConsumed ( SVToken tok ) { tok_l . add ( tok ) ; } public void ungetToken ( SVToken tok ) { tok_l . remove ( tok_l . size ( ) - ) ; } } ; SVDBTypeInfo type = null ; try { fLexer . addTokenListener ( l ) ; type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; } finally { fLexer . removeTokenListener ( l ) ; } if ( fLexer . peekId ( ) ) { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } parsers ( ) . blockItemDeclParser ( ) . parse ( prop , type , start ) ; } else { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } fLexer . ungetToken ( tok_l ) ; break ; } } else { fLexer . ungetToken ( tok ) ; break ; } } } if ( lexer ( ) . peekOperator ( "" ) ) { parsers ( ) . exprParser ( ) . clocking_event ( ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . readKeyword ( "" ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; SVDBExprStmt stmt = new SVDBExprStmt ( ) ; stmt . setLocation ( fLexer . getStartLocation ( ) ) ; stmt . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } try { property_statement_spec ( prop ) ; } finally { prop . setEndLocation ( fLexer . getStartLocation ( ) ) ; } fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } private void property_statement_spec ( SVDBProperty prop ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } SVDBExprStmt stmt = new SVDBExprStmt ( ) ; stmt . setLocation ( fLexer . getStartLocation ( ) ) ; stmt . setExpr ( fParsers . propertyExprParser ( ) . property_statement ( ) ) ; prop . addChildItem ( stmt ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } } private SVDBParamPortDecl property_port_item ( ) throws SVParseException { int attr = ; SVDBParamPortDecl port = new SVDBParamPortDecl ( ) ; port . setLocation ( fLexer . getStartLocation ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; attr |= SVDBParamPortDecl . Direction_Input ; } } port . setAttr ( attr ) ; if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { port . setTypeInfo ( new SVDBTypeInfoBuiltin ( fLexer . eatToken ( ) ) ) ; } else { if ( fLexer . peekId ( ) ) { SVToken t = fLexer . consumeToken ( ) ; if ( fLexer . peekId ( ) ) { fLexer . ungetToken ( t ) ; port . setTypeInfo ( fParsers . dataTypeParser ( ) . data_type ( ) ) ; } else { fLexer . ungetToken ( t ) ; } } else { port . setTypeInfo ( fParsers . dataTypeParser ( ) . data_type ( ) ) ; } } SVDBVarDeclItem vi = new SVDBVarDeclItem ( ) ; vi . setLocation ( fLexer . getStartLocation ( ) ) ; vi . setName ( fLexer . readId ( ) ) ; port . addChildItem ( vi ) ; if ( fLexer . peekOperator ( "" ) ) { vi . setArrayDim ( fParsers . dataTypeParser ( ) . var_dim ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; vi . setInitExpr ( fParsers . exprParser ( ) . expression ( ) ) ; } return port ; } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBModIfcClassParam ; public class SVParameterDeclParser extends SVParserBase { public SVParameterDeclParser ( ISVParser parser ) { super ( parser ) ; } public List < SVDBModIfcClassParam > parse ( ) throws SVParseException { List < SVDBModIfcClassParam > param_l = new ArrayList < SVDBModIfcClassParam > ( ) ; fLexer . readOperator ( "" ) ; while ( fLexer . peekKeyword ( "" ) || fLexer . peekId ( ) ) { if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } fLexer . readOperator ( "" ) ; } return param_l ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . IFieldItemAttr ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . stmt . SVDBExportItem ; import net . sf . sveditor . core . db . stmt . SVDBExportStmt ; import net . sf . sveditor . core . db . stmt . SVDBImportItem ; import net . sf . sveditor . core . db . stmt . SVDBImportStmt ; public class SVImpExpStmtParser extends SVParserBase { public SVImpExpStmtParser ( ISVParser parser ) { super ( parser ) ; } public void parse_export ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . readKeyword ( "" ) ; if ( fLexer . peekString ( ) && ( fLexer . peek ( ) . equals ( "" ) || fLexer . peek ( ) . equals ( "" ) ) ) { fLexer . eatToken ( ) ; parse_dpi_tf ( parent , start ) ; } else { SVDBExportStmt exp = new SVDBExportStmt ( ) ; exp . setLocation ( start ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . startCapture ( ) ; fLexer . readOperator ( "" ) ; fLexer . readOperator ( "" ) ; fLexer . readOperator ( "" ) ; SVDBExportItem ei = new SVDBExportItem ( ) ; ei . setExport ( fLexer . endCapture ( ) ) ; exp . addChildItem ( ei ) ; } else { while ( fLexer . peek ( ) != null ) { exp . addChildItem ( package_export_item ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } fLexer . readOperator ( "" ) ; parent . addChildItem ( exp ) ; } } private void parse_dpi_tf ( ISVDBAddChildItem parent , SVDBLocation start ) throws SVParseException { int modifiers = IFieldItemAttr . FieldAttr_DPI ; modifiers |= parsers ( ) . SVParser ( ) . scan_qualifiers ( false ) ; if ( fLexer . peekId ( ) ) { fLexer . readId ( ) ; fLexer . readOperator ( "" ) ; } parsers ( ) . taskFuncParser ( ) . parse ( parent , start , modifiers ) ; } public void parse_import ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . readKeyword ( "" ) ; if ( fLexer . peekString ( ) ) { String qualifier = fLexer . readString ( ) ; if ( qualifier != null && qualifier . equals ( "" ) || qualifier . equals ( "" ) ) { parse_dpi_tf ( parent , start ) ; } else { error ( "" + qualifier + "" ) ; } } else { SVDBImportStmt imp = new SVDBImportStmt ( ) ; imp . setLocation ( start ) ; while ( fLexer . peek ( ) != null ) { imp . addChildItem ( package_import_item ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; parent . addChildItem ( imp ) ; } } private SVDBImportItem package_import_item ( ) throws SVParseException { SVDBImportItem imp = new SVDBImportItem ( ) ; imp . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . startCapture ( ) ; fLexer . readId ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { fLexer . readId ( ) ; } } imp . setImport ( fLexer . endCapture ( ) ) ; return imp ; } private SVDBExportItem package_export_item ( ) throws SVParseException { SVDBExportItem exp = new SVDBExportItem ( ) ; exp . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . startCapture ( ) ; fLexer . readId ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { fLexer . readId ( ) ; } } exp . setExport ( fLexer . endCapture ( ) ) ; return exp ; } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFieldItem ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . SVDBUtil ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVTaskFunctionParser extends SVParserBase { public SVTaskFunctionParser ( ISVParser parser ) { super ( parser ) ; } public void parse_method_decl ( ISVDBScopeItem parent ) throws SVParseException { parse ( parent , null , true , ) ; } public SVDBTask parse_method_decl ( ) throws SVParseException { SVDBScopeItem scope = new SVDBScopeItem ( ) ; parse ( scope , null , true , ) ; return ( SVDBTask ) SVDBUtil . getFirstChildItem ( scope ) ; } public void parse ( ISVDBAddChildItem parent , SVDBLocation start , int qualifiers ) throws SVParseException { parse ( parent , start , false , qualifiers ) ; } private void parse ( ISVDBAddChildItem parent , SVDBLocation start , boolean is_decl , int qualifiers ) throws SVParseException { SVDBTask func = null ; SVDBLocation end = null ; String tf_name ; if ( start == null ) { start = fLexer . getStartLocation ( ) ; } String type = fLexer . readKeyword ( "" , "" ) ; SVDBTypeInfo return_type = null ; if ( type . equals ( "" ) ) { if ( fLexer . peekKeyword ( "" ) ) { tf_name = fLexer . eatToken ( ) ; return_type = new SVDBTypeInfoBuiltin ( "" ) ; } else { if ( fLexer . peekKeyword ( "" , "" ) ) { if ( fLexer . eatToken ( ) . equals ( "" ) ) { qualifiers |= SVDBFieldItem . FieldAttr_Static ; } } List < SVToken > data_type_or_implicit = null ; if ( fLexer . peekKeyword ( "" ) || SVKeywords . isBuiltInType ( fLexer . peek ( ) ) ) { data_type_or_implicit = new ArrayList < SVToken > ( ) ; data_type_or_implicit . add ( fLexer . consumeToken ( ) ) ; } else if ( fLexer . peekId ( ) ) { data_type_or_implicit = parsers ( ) . SVParser ( ) . scopedIdentifier_l ( true ) ; } if ( ! fLexer . peekOperator ( "" , "" ) || fLexer . peekOperator ( "" ) ) { if ( data_type_or_implicit != null ) { fLexer . ungetToken ( data_type_or_implicit ) ; } return_type = parsers ( ) . dataTypeParser ( ) . data_type_or_void ( ) ; tf_name = parsers ( ) . SVParser ( ) . scopedIdentifier ( false ) ; } else { tf_name = parsers ( ) . SVParser ( ) . scopedIdentifierList2Str ( data_type_or_implicit ) ; } } } else { if ( fLexer . peekKeyword ( "" , "" ) ) { if ( fLexer . eatToken ( ) . equals ( "" ) ) { qualifiers |= SVDBFieldItem . FieldAttr_Static ; } } tf_name = parsers ( ) . SVParser ( ) . scopedIdentifier ( false ) ; } List < SVDBParamPortDecl > params = null ; boolean is_ansi = true ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( is_decl || fLexer . peekOperator ( "" ) ) { params = parsers ( ) . tfPortListParser ( ) . parse ( ) ; is_ansi = true ; } else if ( fLexer . peekOperator ( "" ) ) { params = new ArrayList < SVDBParamPortDecl > ( ) ; is_ansi = false ; } if ( ! is_decl ) { fLexer . readOperator ( "" ) ; } if ( fDebugEn ) { debug ( "" + type + "" + tf_name ) ; } if ( type . equals ( "" ) ) { func = new SVDBFunction ( tf_name , return_type ) ; } else { func = new SVDBTask ( tf_name , SVDBItemType . Task ) ; } func . setParams ( params ) ; func . setAttr ( qualifiers ) ; func . setLocation ( start ) ; parent . addChildItem ( func ) ; if ( ! is_decl && ( qualifiers & SVDBFieldItem . FieldAttr_Extern ) == && ( qualifiers & ( SVDBFieldItem . FieldAttr_Pure | SVDBFieldItem . FieldAttr_Virtual ) ) != ( SVDBFieldItem . FieldAttr_Pure | SVDBFieldItem . FieldAttr_Virtual ) && ( ( qualifiers & SVDBFieldItem . FieldAttr_DPI ) == ) ) { try { parsers ( ) . tfBodyParser ( ) . parse ( func , is_ansi ) ; } catch ( SVParseException e ) { if ( fDebugEn ) { debug ( "" , e ) ; } } finally { func . setEndLocation ( fLexer . getStartLocation ( ) ) ; } end = fLexer . getStartLocation ( ) ; if ( type . equals ( "" ) ) { fLexer . readKeyword ( "" ) ; } else { fLexer . readKeyword ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; String id = fLexer . readIdOrKeyword ( ) ; if ( ! id . equals ( func . getName ( ) ) ) { } } } if ( end == null ) { end = fLexer . getStartLocation ( ) ; } func . setEndLocation ( end ) ; } } package net . sf . sveditor . core . parser ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVFieldVarDeclParser extends SVParserBase { public SVFieldVarDeclParser ( ISVParser parser ) { super ( parser ) ; } public boolean try_parse ( ISVDBAddChildItem parent , boolean decl_allowed ) throws SVParseException { if ( ( fLexer . peekKeyword ( SVKeywords . fBuiltinTypes ) && ! fLexer . peekKeyword ( "" ) ) || fLexer . isIdentifier ( ) || fLexer . peekKeyword ( "" ) ) { boolean builtin_type = ( fLexer . peekKeyword ( SVKeywords . fBuiltinTypes ) && ! fLexer . peekKeyword ( "" ) ) ; if ( ( fLexer . peekKeyword ( SVKeywords . fBuiltinTypes ) && ! fLexer . peekKeyword ( "" ) ) || fLexer . peekKeyword ( "" ) ) { if ( ! decl_allowed ) { error ( "" ) ; } parsers ( ) . blockItemDeclParser ( ) . parse ( parent , null , null ) ; return true ; } else { List < SVToken > id_list = parsers ( ) . SVParser ( ) . scopedStaticIdentifier_l ( true ) ; if ( ! builtin_type && ( fLexer . peekOperator ( ) && ! fLexer . peekOperator ( "" ) ) ) { for ( int i = id_list . size ( ) - ; i >= ; i -- ) { fLexer . ungetToken ( id_list . get ( i ) ) ; } debug ( "" + fLexer . peek ( ) ) ; } else { for ( int i = id_list . size ( ) - ; i >= ; i -- ) { fLexer . ungetToken ( id_list . get ( i ) ) ; } debug ( "" + fLexer . peek ( ) ) ; if ( ! decl_allowed ) { error ( "" ) ; } parsers ( ) . blockItemDeclParser ( ) . parse ( parent , null , null ) ; return true ; } } } else { debug ( "" + fLexer . peek ( ) ) ; } return false ; } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltinNet ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; public class SVTaskFunctionPortListParser extends SVParserBase { public SVTaskFunctionPortListParser ( ISVParser parser ) { super ( parser ) ; } public List < SVDBParamPortDecl > parse ( ) throws SVParseException { List < SVDBParamPortDecl > params = new ArrayList < SVDBParamPortDecl > ( ) ; int dir = SVDBParamPortDecl . Direction_Input ; SVDBTypeInfo last_type = null ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; return params ; } while ( true ) { SVDBLocation it_start = fLexer . getStartLocation ( ) ; if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { String dir_s = fLexer . eatToken ( ) ; if ( dir_s . equals ( "" ) ) { dir = SVDBParamPortDecl . Direction_Input ; } else if ( dir_s . equals ( "" ) ) { dir = SVDBParamPortDecl . Direction_Output ; } else if ( dir_s . equals ( "" ) ) { dir = SVDBParamPortDecl . Direction_Inout ; } else if ( dir_s . equals ( "" ) ) { dir = SVDBParamPortDecl . Direction_Ref ; } } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readKeyword ( "" ) ; dir = ( SVDBParamPortDecl . Direction_Ref | SVDBParamPortDecl . Direction_Const ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; dir |= SVDBParamPortDecl . Direction_Var ; } SVDBTypeInfo type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; if ( fLexer . peekOperator ( "" ) ) { List < SVDBVarDimItem > dim = fParsers . dataTypeParser ( ) . vector_dim ( ) ; if ( type instanceof SVDBTypeInfoBuiltin ) { ( ( SVDBTypeInfoBuiltin ) type ) . setVectorDim ( dim ) ; } else { } } String id ; if ( fLexer . peekOperator ( "" , "" , "" , "" ) ) { id = type . getName ( ) ; type = last_type ; } else { id = fLexer . readId ( ) ; last_type = type ; } SVDBParamPortDecl param_r = new SVDBParamPortDecl ( type ) ; param_r . setDir ( dir ) ; param_r . setLocation ( it_start ) ; SVDBVarDeclItem param = new SVDBVarDeclItem ( id ) ; param_r . addChildItem ( param ) ; if ( fLexer . peekOperator ( "" ) ) { param . setArrayDim ( parsers ( ) . dataTypeParser ( ) . var_dim ( ) ) ; } params . add ( param_r ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; param . setInitExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; return params ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; public class SVTaskFuncBodyParser extends SVParserBase { public SVTaskFuncBodyParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( SVDBTask tf , boolean is_ansi ) throws SVParseException { String end_keyword = ( tf . getType ( ) == SVDBItemType . Function ) ? "" : "" ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; debug ( "" + is_ansi ) ; } boolean decl_allowed = true ; while ( fLexer . peek ( ) != null ) { if ( fLexer . peekKeyword ( end_keyword ) ) { break ; } else if ( fLexer . peekKeyword ( "" ) || fLexer . peekKeyword ( "" ) ) { parsers ( ) . modIfcBodyItemParser ( ) . parse_parameter_decl ( tf ) ; } else if ( ParserSVDBFileFactory . isFirstLevelScope ( fLexer . peek ( ) , ) ) { error ( "" + ( ( tf . getType ( ) == SVDBItemType . Function ) ? "" : "" ) + "" ) ; } else { decl_allowed = parsers ( ) . behavioralBlockParser ( ) . statement ( tf , decl_allowed , is_ansi ) ; } } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } } } package net . sf . sveditor . core . parser ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBFieldItem ; import net . sf . sveditor . core . db . SVDBInterfaceDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModuleDecl ; import net . sf . sveditor . core . db . SVDBProgramDecl ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; public class SVModIfcProgDeclParser extends SVParserBase { public SVModIfcProgDeclParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent , int qualifiers ) throws SVParseException { String id ; String module_type_name = null ; SVDBModIfcDecl module = null ; if ( fDebugEn ) { debug ( "" ) ; } SVDBLocation start = fLexer . getStartLocation ( ) ; String type_name = fLexer . readKeyword ( "" , "" , "" , "" ) ; SVDBItemType type = null ; if ( type_name . equals ( "" ) || type_name . equals ( "" ) ) { type = SVDBItemType . ModuleDecl ; } else if ( type_name . equals ( "" ) ) { type = SVDBItemType . InterfaceDecl ; } else if ( type_name . equals ( "" ) ) { type = SVDBItemType . ProgramDecl ; } else { error ( "" + type_name ) ; } if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; } if ( type == SVDBItemType . ProgramDecl && fLexer . peekOperator ( "" ) ) { module_type_name = "" ; } else { module_type_name = fLexer . readId ( ) ; } switch ( type ) { case ModuleDecl : module = new SVDBModuleDecl ( module_type_name ) ; break ; case InterfaceDecl : module = new SVDBInterfaceDecl ( module_type_name ) ; break ; case ProgramDecl : module = new SVDBProgramDecl ( module_type_name ) ; break ; } module . setLocation ( start ) ; parent . addChildItem ( module ) ; if ( type != SVDBItemType . ProgramDecl ) { while ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . impExpParser ( ) . parse_import ( module ) ; } } if ( fLexer . peekOperator ( "" ) ) { module . getParameters ( ) . addAll ( parsers ( ) . paramPortListParser ( ) . parse ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { List < SVDBParamPortDecl > ports = parsers ( ) . portListParser ( ) . parse ( ) ; for ( SVDBParamPortDecl p : ports ) { p . setParent ( module ) ; } module . getPorts ( ) . addAll ( ports ) ; } fLexer . readOperator ( "" ) ; if ( ( qualifiers & SVDBFieldItem . FieldAttr_Extern ) == ) { while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" + type_name ) ) { try { fParsers . modIfcBodyItemParser ( ) . parse ( module , type_name ) ; } catch ( SVParseException e ) { if ( fDebugEn ) { debug ( "" , e ) ; } while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) && ! fLexer . peekKeyword ( "" + type_name ) ) { fLexer . eatToken ( ) ; } } } SVDBLocation end = fLexer . getStartLocation ( ) ; module . setEndLocation ( end ) ; fLexer . readKeyword ( "" + type_name ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } else { SVDBLocation end = fLexer . getStartLocation ( ) ; module . setEndLocation ( end ) ; } if ( fDebugEn ) { debug ( "" ) ; } } } package net . sf . sveditor . core . parser ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBAssign ; import net . sf . sveditor . core . db . SVDBBind ; import net . sf . sveditor . core . db . SVDBFieldItem ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . SVDBModportClockingPortDecl ; import net . sf . sveditor . core . db . SVDBModportDecl ; import net . sf . sveditor . core . db . SVDBModportItem ; import net . sf . sveditor . core . db . SVDBModportPortsDecl ; import net . sf . sveditor . core . db . SVDBModportSimplePort ; import net . sf . sveditor . core . db . SVDBModportSimplePortsDecl ; import net . sf . sveditor . core . db . SVDBModportTFPort ; import net . sf . sveditor . core . db . SVDBModportTFPortsDecl ; import net . sf . sveditor . core . db . SVDBParamValueAssignList ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltinNet ; import net . sf . sveditor . core . db . SVDBTypeInfoModuleIfc ; import net . sf . sveditor . core . db . expr . SVDBClockingEventExpr . ClockingEventType ; import net . sf . sveditor . core . db . stmt . SVDBAlwaysStmt ; import net . sf . sveditor . core . db . stmt . SVDBAlwaysStmt . AlwaysType ; import net . sf . sveditor . core . db . stmt . SVDBBodyStmt ; import net . sf . sveditor . core . db . stmt . SVDBDefParamItem ; import net . sf . sveditor . core . db . stmt . SVDBDefParamStmt ; import net . sf . sveditor . core . db . stmt . SVDBFinalStmt ; import net . sf . sveditor . core . db . stmt . SVDBInitialStmt ; import net . sf . sveditor . core . db . stmt . SVDBNullStmt ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBTimePrecisionStmt ; import net . sf . sveditor . core . db . stmt . SVDBTimeUnitsStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVModIfcBodyItemParser extends SVParserBase { public SVModIfcBodyItemParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent , String typename ) throws SVParseException { int modifiers = ; if ( fLexer . peekOperator ( "" ) ) { fParsers . attrParser ( ) . parse ( parent ) ; } String id = fLexer . peek ( ) ; if ( fDebugEn ) { debug ( "" + id + "" + fLexer . getStartLocation ( ) . getLine ( ) ) ; } SVDBLocation start = fLexer . getStartLocation ( ) ; modifiers = parsers ( ) . SVParser ( ) . scan_qualifiers ( false ) ; id = fLexer . peek ( ) ; if ( fDebugEn ) { debug ( "" + id ) ; } if ( id . equals ( "" ) || id . equals ( "" ) ) { parsers ( ) . taskFuncParser ( ) . parse ( parent , start , modifiers ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { parsers ( ) . assertionParser ( ) . parse ( parent ) ; } else if ( id . equals ( "" ) ) { fParsers . propertyParser ( ) . property ( parent ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { parsers ( ) . generateBlockParser ( ) . parse ( parent ) ; } else if ( id . equals ( "" ) ) { parsers ( ) . specifyBlockParser ( ) . parse ( parent ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" ) ) { parsers ( ) . clockingBlockParser ( ) . parse ( parent ) ; } else if ( id . equals ( "" ) ) { SVDBNullStmt stmt = new SVDBNullStmt ( ) ; stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; parent . addChildItem ( stmt ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" , "" , "" ) ) { parse_initial_always ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { parse_final ( parent ) ; } else if ( id . equals ( "" ) ) { modport_decl ( parent ) ; } else if ( id . equals ( "" ) ) { parse_continuous_assign ( parent ) ; } else if ( id . equals ( "" ) ) { parse_bind ( parent ) ; } else if ( id . equals ( "" ) ) { parsers ( ) . covergroupParser ( ) . parse ( parent ) ; } else if ( id . equals ( "" ) ) { fParsers . constraintParser ( ) . parse ( parent , modifiers ) ; } else if ( id . equals ( "" ) ) { fParsers . sequenceParser ( ) . sequence ( parent ) ; } else if ( id . equals ( "" ) ) { parsers ( ) . impExpParser ( ) . parse_import ( parent ) ; } else if ( id . equals ( "" ) ) { parsers ( ) . impExpParser ( ) . parse_export ( parent ) ; } else if ( id . equals ( "" ) ) { fParsers . clockingBlockParser ( ) . parse ( parent ) ; } else if ( id . equals ( "" ) ) { parsers ( ) . dataTypeParser ( ) . typedef ( parent ) ; } else if ( id . equals ( "" ) ) { parsers ( ) . classParser ( ) . parse ( parent , modifiers ) ; } else if ( id . equals ( "" ) || id . equals ( "" ) || ( id . equals ( "" ) && ( modifiers & SVDBFieldItem . FieldAttr_Virtual ) == ) ) { parsers ( ) . modIfcProgParser ( ) . parse ( parent , modifiers ) ; } else if ( id . equals ( "" ) || id . equals ( "" ) ) { parse_parameter_decl ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBDefParamStmt defparam = new SVDBDefParamStmt ( ) ; defparam . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; parent . addChildItem ( defparam ) ; while ( fLexer . peek ( ) != null ) { SVDBLocation is = fLexer . getStartLocation ( ) ; SVDBDefParamItem item = new SVDBDefParamItem ( ) ; item . setLocation ( is ) ; item . setTarget ( fParsers . exprParser ( ) . hierarchical_identifier ( ) ) ; fLexer . readOperator ( "" ) ; item . setExpr ( fParsers . exprParser ( ) . expression ( ) ) ; defparam . addParamAssign ( item ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } else if ( SVDataTypeParser . NetType . contains ( id ) ) { parse_var_decl_net_type ( parent ) ; } else if ( fLexer . peekKeyword ( SVKeywords . fBuiltinGates ) ) { parsers ( ) . gateInstanceParser ( ) . parse ( parent ) ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) { parsers ( ) . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { parse_time_units_precision ( parent ) ; } else if ( ! fLexer . peekOperator ( ) ) { if ( fLexer . peekId ( ) ) { SVToken tok = fLexer . consumeToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; parsers ( ) . assertionParser ( ) . parse ( parent ) ; } else { fLexer . ungetToken ( tok ) ; if ( fDebugEn ) { debug ( "" + id ) ; } parse_var_decl_module_inst ( parent , modifiers ) ; } } else { if ( fDebugEn ) { debug ( "" + id ) ; } parse_var_decl_module_inst ( parent , modifiers ) ; } } else { error ( "" + fLexer . eatToken ( ) ) ; } if ( fDebugEn ) { debug ( "" ) ; } } public void parse_parameter_decl ( ISVDBAddChildItem parent ) throws SVParseException { fLexer . readKeyword ( "" , "" ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } SVDBTypeInfo data_type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; String param_name ; SVDBLocation it_start = fLexer . getStartLocation ( ) ; if ( fLexer . peekId ( ) ) { param_name = fLexer . readId ( ) ; } else { param_name = data_type . getName ( ) ; data_type = null ; } SVDBParamPortDecl p = new SVDBParamPortDecl ( data_type ) ; SVDBVarDeclItem pi ; parent . addChildItem ( p ) ; while ( true ) { pi = new SVDBVarDeclItem ( param_name ) ; if ( fLexer . peekOperator ( "" ) ) { pi . setArrayDim ( fParsers . dataTypeParser ( ) . var_dim ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; parsers ( ) . exprParser ( ) . expression ( ) ; } pi . setLocation ( it_start ) ; p . addChildItem ( pi ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; it_start = fLexer . getStartLocation ( ) ; param_name = fLexer . readId ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } public void parse_time_units_precision ( ISVDBAddChildItem parent ) throws SVParseException { String type = fLexer . readKeyword ( "" , "" ) ; String num = fLexer . readNumber ( ) ; if ( type . equals ( "" ) ) { SVDBTimePrecisionStmt precision = new SVDBTimePrecisionStmt ( ) ; precision . setArg1 ( num ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; precision . setArg2 ( fLexer . readNumber ( ) ) ; } parent . addChildItem ( precision ) ; } else { SVDBTimeUnitsStmt units = new SVDBTimeUnitsStmt ( ) ; units . setUnits ( num ) ; parent . addChildItem ( units ) ; } fLexer . readOperator ( "" ) ; } public void parse_continuous_assign ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . readKeyword ( "" ) ; SVDBAssign assign = new SVDBAssign ( ) ; assign . setLocation ( start ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; String s1 = null , s2 = null ; if ( fLexer . peekKeyword ( "" , "" ) ) { s1 = fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; s2 = fLexer . readKeyword ( SVKeywords . fStrength ) ; } else { s1 = fLexer . readKeyword ( SVKeywords . fStrength ) ; fLexer . readOperator ( "" ) ; if ( fLexer . peekKeyword ( "" , "" ) ) { s2 = fLexer . eatToken ( ) ; } else { s2 = fLexer . readKeyword ( SVKeywords . fStrength ) ; } } fLexer . readOperator ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { assign . setDelay ( fParsers . exprParser ( ) . delay_expr ( ) ) ; } assign . setLHS ( fParsers . exprParser ( ) . variable_lvalue ( ) ) ; fLexer . readOperator ( "" ) ; assign . setRHS ( fParsers . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( assign ) ; } private void parse_var_decl_net_type ( ISVDBAddChildItem parent ) throws SVParseException { String net_type = fLexer . eatToken ( ) ; String vector_dim = null ; SVDBVarDeclStmt var = null ; String net_name = null ; SVDBLocation start = null ; SVDBTypeInfoBuiltinNet type_info = null ; SVDBTypeInfo data_type = null ; if ( fDebugEn ) { debug ( "" + net_type + "" + fLexer . getStartLocation ( ) . getLine ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { SVToken tok = new SVToken ( ) ; tok = fLexer . consumeToken ( ) ; if ( fLexer . peekKeyword ( SVKeywords . fStrength ) ) { String strength1 = fLexer . readKeyword ( SVKeywords . fStrength ) ; fLexer . readOperator ( "" ) ; String strength2 = fLexer . readKeyword ( SVKeywords . fStrength ) ; fLexer . readOperator ( "" ) ; } else { fLexer . ungetToken ( tok ) ; } } if ( fLexer . peekOperator ( "" ) ) { fParsers . exprParser ( ) . delay_expr ( ) ; } if ( fLexer . peekOperator ( "" ) ) { data_type = new SVDBTypeInfoBuiltin ( net_type ) ; ( ( SVDBTypeInfoBuiltin ) data_type ) . setVectorDim ( fParsers . dataTypeParser ( ) . vector_dim ( ) ) ; } else { data_type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; } if ( fLexer . peekOperator ( "" ) ) { fParsers . exprParser ( ) . delay_expr ( ) ; } if ( fLexer . peekOperator ( "" , "" , "" ) ) { net_name = data_type . getName ( ) ; data_type = new SVDBTypeInfoBuiltin ( net_type ) ; } else { net_name = fLexer . readId ( ) ; } start = fLexer . getStartLocation ( ) ; type_info = new SVDBTypeInfoBuiltinNet ( net_type , data_type ) ; var = new SVDBVarDeclStmt ( type_info , ) ; parent . addChildItem ( var ) ; while ( true ) { SVDBVarDeclItem vi = new SVDBVarDeclItem ( net_name ) ; vi . setLocation ( start ) ; var . addChildItem ( vi ) ; if ( fLexer . peekOperator ( "" ) ) { vi . setArrayDim ( parsers ( ) . dataTypeParser ( ) . var_dim ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; start = fLexer . getStartLocation ( ) ; net_name = fLexer . readId ( ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; parsers ( ) . exprParser ( ) . expression ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } public void parse_bind ( ISVDBAddChildItem parent ) throws SVParseException { SVDBBind bind = new SVDBBind ( ) ; bind . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; bind . setTargetTypeName ( fParsers . exprParser ( ) . hierarchical_identifier ( ) ) ; parent . addChildItem ( bind ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; while ( fLexer . peek ( ) != null ) { bind . addTargetInstName ( fParsers . exprParser ( ) . hierarchical_identifier ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } fParsers . modIfcBodyItemParser ( ) . parse_var_decl_module_inst ( bind , ) ; } public void parse_var_decl_module_inst ( ISVDBAddChildItem parent , int modifiers ) throws SVParseException { SVDBTypeInfo type ; SVDBLocation start = fLexer . getStartLocation ( ) , item_start ; type = parsers ( ) . dataTypeParser ( ) . data_type ( modifiers ) ; item_start = fLexer . getStartLocation ( ) ; String inst_name_or_var = fLexer . readIdOrKeyword ( ) ; if ( fDebugEn ) { debug ( "" + inst_name_or_var ) ; } List < SVDBVarDimItem > arraydims = null ; if ( fLexer . peekOperator ( "" ) ) { arraydims = parsers ( ) . dataTypeParser ( ) . var_dim ( ) ; } if ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" + type . getClass ( ) . getName ( ) ) ; } type = new SVDBTypeInfoModuleIfc ( type . getName ( ) ) ; SVDBModIfcInst inst = new SVDBModIfcInst ( type ) ; inst . setLocation ( start ) ; parent . addChildItem ( inst ) ; while ( fLexer . peek ( ) != null ) { if ( fDebugEn ) { debug ( "" + inst_name_or_var ) ; } SVDBModIfcInstItem item = new SVDBModIfcInstItem ( inst_name_or_var ) ; if ( arraydims != null ) { item . setArrayDim ( arraydims ) ; arraydims = null ; } item . setLocation ( fLexer . getStartLocation ( ) ) ; inst . addChildItem ( item ) ; SVDBParamValueAssignList port_map = fParsers . paramValueAssignParser ( ) . parse ( false ) ; item . setPortMap ( port_map ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; start = fLexer . getStartLocation ( ) ; inst_name_or_var = fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" ) ) { arraydims = fParsers . dataTypeParser ( ) . var_dim ( ) ; } } else { break ; } } fLexer . readOperator ( "" ) ; } else { SVDBVarDeclStmt item = new SVDBVarDeclStmt ( type , ) ; item . setAttr ( modifiers ) ; item . setLocation ( start ) ; parent . addChildItem ( item ) ; while ( fLexer . peek ( ) != null ) { SVDBVarDeclItem vi = new SVDBVarDeclItem ( inst_name_or_var ) ; vi . setLocation ( item_start ) ; if ( arraydims != null ) { vi . setArrayDim ( arraydims ) ; arraydims = null ; } item . addChildItem ( vi ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; vi . setInitExpr ( fParsers . exprParser ( ) . expression ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; start = fLexer . getStartLocation ( ) ; inst_name_or_var = fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" ) ) { arraydims = fParsers . dataTypeParser ( ) . var_dim ( ) ; } } else { break ; } } fLexer . readOperator ( "" ) ; } } private void parse_final ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . readKeyword ( "" ) ; SVDBBodyStmt ret = new SVDBFinalStmt ( ) ; ret . setLocation ( start ) ; parent . addChildItem ( ret ) ; fParsers . behavioralBlockParser ( ) . statement ( ret ) ; } private void modport_decl ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . readKeyword ( "" ) ; SVDBModportDecl modport = new SVDBModportDecl ( ) ; modport . setLocation ( start ) ; parent . addChildItem ( modport ) ; while ( fLexer . peek ( ) != null ) { start = fLexer . getStartLocation ( ) ; String id = fLexer . readId ( ) ; SVDBModportItem item = new SVDBModportItem ( id ) ; item . setLocation ( start ) ; fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null ) { String type = fLexer . readKeyword ( "" , "" , "" , "" , "" , "" ) ; SVDBModportPortsDecl ports_decl = null ; if ( type . equals ( "" ) ) { ports_decl = modport_clocking_declaration ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } } else if ( type . equals ( "" ) || type . equals ( "" ) ) { ports_decl = modport_tf_ports_declaration ( type ) ; } else { ports_decl = modport_simple_ports_declaration ( type ) ; } item . addPorts ( ports_decl ) ; if ( fLexer . peekOperator ( "" ) ) { break ; } } fLexer . readOperator ( "" ) ; modport . addModportItem ( item ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } private SVDBModportClockingPortDecl modport_clocking_declaration ( ) throws SVParseException { SVDBModportClockingPortDecl ret = new SVDBModportClockingPortDecl ( ) ; ret . setClockingId ( fLexer . readId ( ) ) ; return ret ; } private SVDBModportTFPortsDecl modport_tf_ports_declaration ( String type ) throws SVParseException { SVDBModportTFPortsDecl ret = new SVDBModportTFPortsDecl ( ) ; ret . setImpExpType ( type ) ; while ( fLexer . peek ( ) != null ) { SVDBModportTFPort port = new SVDBModportTFPort ( ) ; port . setLocation ( fLexer . getStartLocation ( ) ) ; if ( fLexer . peekKeyword ( "" , "" ) ) { port . setPrototype ( fParsers . taskFuncParser ( ) . parse_method_decl ( ) ) ; } else { port . setId ( fLexer . readId ( ) ) ; } ret . addChildItem ( port ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } if ( fLexer . peekKeyword ( ) ) { break ; } } return ret ; } private SVDBModportSimplePortsDecl modport_simple_ports_declaration ( String dir ) throws SVParseException { SVDBModportSimplePortsDecl ret = new SVDBModportSimplePortsDecl ( ) ; if ( fDebugEn ) { debug ( "" + dir ) ; } ret . setPortDir ( dir ) ; while ( fLexer . peek ( ) != null ) { SVDBModportSimplePort port = new SVDBModportSimplePort ( ) ; port . setLocation ( fLexer . getStartLocation ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { port . setIsMapped ( true ) ; fLexer . eatToken ( ) ; } port . setPortId ( fLexer . readId ( ) ) ; if ( port . isMapped ( ) ) { fLexer . readOperator ( "" ) ; port . setExpr ( fParsers . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } if ( fDebugEn ) { debug ( "" + port . getPortId ( ) ) ; } ret . addPort ( port ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } if ( fLexer . peekKeyword ( ) ) { break ; } } if ( fDebugEn ) { debug ( "" + dir ) ; } return ret ; } private void parse_initial_always ( ISVDBAddChildItem parent ) throws SVParseException { ISVDBChildItem ret = null ; SVDBLocation start = fLexer . getStartLocation ( ) ; String type = fLexer . readKeyword ( "" , "" , "" , "" , "" ) ; if ( ! type . equals ( "" ) ) { AlwaysType always_type = null ; if ( type . equals ( "" ) ) { always_type = AlwaysType . Always ; } else if ( type . equals ( "" ) ) { always_type = AlwaysType . AlwaysComb ; } else if ( type . equals ( "" ) ) { always_type = AlwaysType . AlwaysLatch ; } else if ( type . equals ( "" ) ) { always_type = AlwaysType . AlwaysFF ; } SVDBAlwaysStmt always_stmt = new SVDBAlwaysStmt ( always_type ) ; if ( ( always_type == AlwaysType . AlwaysFF ) || ( always_type == AlwaysType . Always ) ) { if ( lexer ( ) . peekOperator ( "" ) ) { always_stmt . setCBEventExpr ( parsers ( ) . exprParser ( ) . clocking_event ( ) ) ; } else { always_stmt . setAlwaysEventType ( ClockingEventType . None ) ; } } else { always_stmt . setAlwaysEventType ( ClockingEventType . None ) ; } ret = always_stmt ; } else { ret = new SVDBInitialStmt ( ) ; } ret . setLocation ( start ) ; parent . addChildItem ( ret ) ; fParsers . behavioralBlockParser ( ) . statement ( ( SVDBBodyStmt ) ret ) ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBClockingBlock ; import net . sf . sveditor . core . db . expr . SVDBExpr ; public class SVClockingBlockParser extends SVParserBase { public SVClockingBlockParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent ) throws SVParseException { SVDBClockingBlock clk_blk = new SVDBClockingBlock ( "" ) ; String name = "" ; clk_blk . setLocation ( fLexer . getStartLocation ( ) ) ; parent . addChildItem ( clk_blk ) ; try { String type = null ; if ( fLexer . peekKeyword ( "" , "" ) ) { type = fLexer . eatToken ( ) ; } fLexer . readKeyword ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { name = fLexer . readId ( ) ; } clk_blk . setName ( name ) ; clk_blk . setExpr ( fParsers . exprParser ( ) . clocking_event ( ) ) ; fLexer . readOperator ( "" ) ; if ( type == null || ! type . equals ( "" ) ) { while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { clocking_item ( clk_blk ) ; } } clk_blk . setEndLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } finally { } } private void clocking_item ( SVDBClockingBlock clk_blk ) throws SVParseException { if ( fLexer . peekKeyword ( "" ) ) { default_skew ( ) ; fLexer . readOperator ( "" ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" ) ) { String dir = fLexer . eatToken ( ) ; if ( ! dir . equals ( "" ) ) { if ( fLexer . peekKeyword ( "" , "" ) || fLexer . peekOperator ( "" ) ) { clocking_skew ( ) ; if ( dir . equals ( "" ) && fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" , "" ) || fLexer . peekOperator ( "" ) ) { clocking_skew ( ) ; } } } } } else { fParsers . attrParser ( ) . parse ( null ) ; assertion_item_declaration ( clk_blk ) ; fLexer . eatToken ( ) ; } } private void assertion_item_declaration ( ISVDBAddChildItem parent ) throws SVParseException { String type = fLexer . readKeyword ( "" , "" , "" ) ; if ( type . equals ( "" ) ) { fParsers . propertyParser ( ) . property ( parent ) ; } else if ( type . equals ( "" ) ) { fParsers . sequenceParser ( ) . sequence ( parent ) ; } else { error ( "" ) ; } } private void default_skew ( ) throws SVParseException { fLexer . readKeyword ( "" ) ; String type = fLexer . readKeyword ( "" , "" ) ; clocking_skew ( ) ; if ( type . equals ( "" ) && fLexer . peekKeyword ( "" ) ) { fLexer . readKeyword ( "" ) ; clocking_skew ( ) ; } } private void clocking_skew ( ) throws SVParseException { if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fParsers . exprParser ( ) . delay_expr ( ) ; } } else { fParsers . exprParser ( ) . delay_expr ( ) ; } } private String event_expr ( ) throws SVParseException { String ret = null ; try { while ( fLexer . peek ( ) != null ) { if ( fLexer . peekOperator ( "" ) ) { fLexer . skipPastMatch ( "" , "" ) ; } else { if ( fLexer . peekKeyword ( "" , "" , "" ) ) { fLexer . eatToken ( ) ; } fLexer . readId ( ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } finally { ret = fLexer . endCapture ( ) ; } return ret ; } } package net . sf . sveditor . core . parser ; public class EOFException extends RuntimeException { private static final long serialVersionUID = ; } package net . sf . sveditor . core . parser ; public class SVFatalParseException extends RuntimeException { private static final long serialVersionUID = ; public SVFatalParseException ( String msg ) { super ( msg ) ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . stmt . SVDBActionBlockStmt ; import net . sf . sveditor . core . db . stmt . SVDBAssertStmt ; import net . sf . sveditor . core . db . stmt . SVDBAssumeStmt ; import net . sf . sveditor . core . db . stmt . SVDBCoverStmt ; public class SVAssertionParser extends SVParserBase { public SVAssertionParser ( ISVParser parser ) { super ( parser ) ; } public SVDBAssertStmt parse ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; String assert_type = fLexer . readKeyword ( "" , "" , "" ) ; SVDBAssertStmt assert_stmt ; if ( assert_type . equals ( "" ) ) { assert_stmt = new SVDBAssertStmt ( ) ; } else if ( assert_type . equals ( "" ) ) { assert_stmt = new SVDBAssumeStmt ( ) ; } else { assert_stmt = new SVDBCoverStmt ( ) ; } assert_stmt . setLocation ( start ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; assert_stmt . setExpr ( fParsers . propertyExprParser ( ) . property_spec ( ) ) ; fLexer . readOperator ( "" ) ; } else { if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readNumber ( ) ; } fLexer . readOperator ( "" ) ; assert_stmt . setExpr ( parsers ( ) . exprParser ( ) . event_expression ( ) ) ; fLexer . readOperator ( "" ) ; } parent . addChildItem ( assert_stmt ) ; assert_stmt . setActionBlock ( new SVDBActionBlockStmt ( ) ) ; if ( assert_type . equals ( "" ) ) { parsers ( ) . behavioralBlockParser ( ) . action_block_stmt ( assert_stmt . getActionBlock ( ) ) ; } else { parsers ( ) . behavioralBlockParser ( ) . action_block ( assert_stmt . getActionBlock ( ) ) ; } return assert_stmt ; } } package net . sf . sveditor . core . parser ; public class SVParsers { private ISVParser fSVParser ; private ParserSVDBFileFactory fSVDBFileFactory ; private SVClassDeclParser fClassParser ; private SVCovergroupParser fCovergroupParser ; private SVParameterDeclParser fParamDeclParser ; private SVParameterPortListParser fParamPortParser ; private SVDataTypeParser fDataTypeParser ; private SVTaskFunctionParser fFunctionParser ; private SVTaskFunctionPortListParser fTFPortListParser ; private SVTaskFuncBodyParser fTFBodyParser ; private SVBlockItemDeclParser fBlockItemDeclParser ; private SVParameterValueAssignmentParser fParamValueAssignParser ; private SVBehavioralBlockParser fBehavioralBlockParser ; private SVModIfcProgDeclParser fModIfcProgParser ; private SVPortListParser fPortListParser ; private SVGenerateBlockParser fGenBlockParser ; private SVClockingBlockParser fClkBlockParser ; private SVSpecifyBlockParser fSpecifyBlockParser ; private SVImpExpStmtParser fImportParser ; private SVExprParser fExprParser ; private SVGateInstantiationParser fGateInstanceParser ; private SVAssertionParser fAssertionParser ; private SVModIfcBodyItemParser fModIfcBodyItemParser ; private SVConstraintParser fConstraintParser ; private SVAttributeParser fAttrParser ; private SVPropertyExprParser fPropertyExprParser ; private SVSequenceParser fSequenceParser ; private SVPropertyParser fPropertyParser ; private SVConfigParser fConfigParser ; public SVParsers ( ) { } public SVParsers ( ISVParser parser ) { fSVParser = parser ; } public void init ( ParserSVDBFileFactory sv_parser ) { fSVDBFileFactory = sv_parser ; init ( ( ISVParser ) sv_parser ) ; } public void init ( ISVParser parser ) { fSVParser = parser ; fClassParser = new SVClassDeclParser ( fSVParser ) ; fParamDeclParser = new SVParameterDeclParser ( fSVParser ) ; fParamPortParser = new SVParameterPortListParser ( fSVParser ) ; fDataTypeParser = new SVDataTypeParser ( fSVParser ) ; fFunctionParser = new SVTaskFunctionParser ( fSVParser ) ; fTFPortListParser = new SVTaskFunctionPortListParser ( fSVParser ) ; fTFBodyParser = new SVTaskFuncBodyParser ( fSVParser ) ; fBlockItemDeclParser = new SVBlockItemDeclParser ( fSVParser ) ; fParamValueAssignParser = new SVParameterValueAssignmentParser ( fSVParser ) ; fBehavioralBlockParser = new SVBehavioralBlockParser ( fSVParser ) ; fModIfcProgParser = new SVModIfcProgDeclParser ( fSVParser ) ; fPortListParser = new SVPortListParser ( fSVParser ) ; fGenBlockParser = new SVGenerateBlockParser ( fSVParser ) ; fClkBlockParser = new SVClockingBlockParser ( fSVParser ) ; fSpecifyBlockParser = new SVSpecifyBlockParser ( fSVParser ) ; fImportParser = new SVImpExpStmtParser ( fSVParser ) ; fExprParser = new SVExprParser ( fSVParser ) ; fGateInstanceParser = new SVGateInstantiationParser ( fSVParser ) ; fAssertionParser = new SVAssertionParser ( fSVParser ) ; fCovergroupParser = new SVCovergroupParser ( fSVParser ) ; fModIfcBodyItemParser = new SVModIfcBodyItemParser ( fSVParser ) ; fConstraintParser = new SVConstraintParser ( fSVParser ) ; fAttrParser = new SVAttributeParser ( fSVParser ) ; fPropertyExprParser = new SVPropertyExprParser ( fSVParser ) ; fSequenceParser = new SVSequenceParser ( fSVParser ) ; fPropertyParser = new SVPropertyParser ( fSVParser ) ; fConfigParser = new SVConfigParser ( fSVParser ) ; } public ParserSVDBFileFactory SVParser ( ) { return fSVDBFileFactory ; } public final SVClassDeclParser classParser ( ) { return fClassParser ; } public SVParameterDeclParser paramDeclParser ( ) { return fParamDeclParser ; } public SVParameterPortListParser paramPortListParser ( ) { return fParamPortParser ; } public SVDataTypeParser dataTypeParser ( ) { return fDataTypeParser ; } public SVTaskFunctionParser taskFuncParser ( ) { return fFunctionParser ; } public SVTaskFunctionPortListParser tfPortListParser ( ) { return fTFPortListParser ; } public SVTaskFuncBodyParser tfBodyParser ( ) { return fTFBodyParser ; } public SVBlockItemDeclParser blockItemDeclParser ( ) { return fBlockItemDeclParser ; } public SVParameterValueAssignmentParser paramValueAssignParser ( ) { return fParamValueAssignParser ; } public SVBehavioralBlockParser behavioralBlockParser ( ) { return fBehavioralBlockParser ; } public SVModIfcProgDeclParser modIfcProgParser ( ) { return fModIfcProgParser ; } public SVPortListParser portListParser ( ) { return fPortListParser ; } public SVGenerateBlockParser generateBlockParser ( ) { return fGenBlockParser ; } public SVClockingBlockParser clockingBlockParser ( ) { return fClkBlockParser ; } public SVSpecifyBlockParser specifyBlockParser ( ) { return fSpecifyBlockParser ; } public SVImpExpStmtParser impExpParser ( ) { return fImportParser ; } public SVExprParser exprParser ( ) { return fExprParser ; } public SVGateInstantiationParser gateInstanceParser ( ) { return fGateInstanceParser ; } public SVAssertionParser assertionParser ( ) { return fAssertionParser ; } public SVCovergroupParser covergroupParser ( ) { return fCovergroupParser ; } public SVModIfcBodyItemParser modIfcBodyItemParser ( ) { return fModIfcBodyItemParser ; } public SVConstraintParser constraintParser ( ) { return fConstraintParser ; } public SVAttributeParser attrParser ( ) { return fAttrParser ; } public SVPropertyExprParser propertyExprParser ( ) { return fPropertyExprParser ; } public SVSequenceParser sequenceParser ( ) { return fSequenceParser ; } public SVPropertyParser propertyParser ( ) { return fPropertyParser ; } public SVConfigParser configParser ( ) { return fConfigParser ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; public class SVAttributeParser extends SVParserBase { public SVAttributeParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent ) throws SVParseException { try { while ( fLexer . peekOperator ( "" ) ) { fLexer . setInAttr ( true ) ; fLexer . eatToken ( ) ; while ( fLexer . peek ( ) != null ) { fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fParsers . exprParser ( ) . expression ( ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } } finally { fLexer . setInAttr ( false ) ; } } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBSequence ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVSequenceParser extends SVParserBase { public SVSequenceParser ( ISVParser parser ) { super ( parser ) ; } public void sequence ( ISVDBAddChildItem parent ) throws SVParseException { SVDBSequence seq = new SVDBSequence ( ) ; seq . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; seq . setName ( fLexer . readId ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( ! fLexer . peekOperator ( "" ) ) { while ( fLexer . peek ( ) != null ) { seq . addPort ( sequence_port_item ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } fLexer . readOperator ( "" ) ; } fLexer . readOperator ( "" ) ; parent . addChildItem ( seq ) ; while ( fLexer . peekKeyword ( SVKeywords . fBuiltinDeclTypes ) || fLexer . peekKeyword ( "" ) || fLexer . isIdentifier ( ) ) { SVDBLocation start = fLexer . getStartLocation ( ) ; if ( fLexer . peekKeyword ( "" ) || fLexer . peekKeyword ( SVKeywords . fBuiltinDeclTypes ) ) { parsers ( ) . blockItemDeclParser ( ) . parse ( seq , null , start ) ; } else { SVToken tok = fLexer . consumeToken ( ) ; if ( fLexer . peekOperator ( "" , "" ) || fLexer . peekId ( ) ) { fLexer . ungetToken ( tok ) ; final List < SVToken > tok_l = new ArrayList < SVToken > ( ) ; ISVTokenListener l = new ISVTokenListener ( ) { public void tokenConsumed ( SVToken tok ) { tok_l . add ( tok ) ; } public void ungetToken ( SVToken tok ) { tok_l . remove ( tok_l . size ( ) - ) ; } } ; SVDBTypeInfo type = null ; try { fLexer . addTokenListener ( l ) ; type = parsers ( ) . dataTypeParser ( ) . data_type ( ) ; } finally { fLexer . removeTokenListener ( l ) ; } if ( fLexer . peekId ( ) ) { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } parsers ( ) . blockItemDeclParser ( ) . parse ( seq , type , start ) ; } else { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } fLexer . ungetToken ( tok_l ) ; break ; } } else { fLexer . ungetToken ( tok ) ; break ; } } } seq . setExpr ( fParsers . propertyExprParser ( ) . sequence_expr ( ) ) ; fLexer . readOperator ( "" ) ; fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } private SVDBParamPortDecl sequence_port_item ( ) throws SVParseException { int attr = ; SVDBParamPortDecl port = new SVDBParamPortDecl ( ) ; port . setLocation ( fLexer . getStartLocation ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" , "" , "" ) ) { String dir = fLexer . eatToken ( ) ; if ( dir . equals ( "" ) ) { attr |= SVDBParamPortDecl . Direction_Input ; } else if ( dir . equals ( "" ) ) { attr |= SVDBParamPortDecl . Direction_Inout ; } else { attr |= SVDBParamPortDecl . Direction_Output ; } } } port . setAttr ( attr ) ; if ( fLexer . peekKeyword ( "" , "" , "" ) ) { port . setTypeInfo ( new SVDBTypeInfoBuiltin ( fLexer . eatToken ( ) ) ) ; } else { if ( fLexer . peekId ( ) ) { SVToken t = fLexer . consumeToken ( ) ; if ( fLexer . peekId ( ) ) { fLexer . ungetToken ( t ) ; port . setTypeInfo ( fParsers . dataTypeParser ( ) . data_type ( ) ) ; } else { fLexer . ungetToken ( t ) ; } } else { port . setTypeInfo ( fParsers . dataTypeParser ( ) . data_type ( ) ) ; } } SVDBVarDeclItem vi = new SVDBVarDeclItem ( ) ; vi . setLocation ( fLexer . getStartLocation ( ) ) ; vi . setName ( fLexer . readId ( ) ) ; port . addChildItem ( vi ) ; if ( fLexer . peekOperator ( "" ) ) { vi . setArrayDim ( fParsers . dataTypeParser ( ) . var_dim ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; vi . setInitExpr ( fParsers . exprParser ( ) . expression ( ) ) ; } return port ; } } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . Stack ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . core . scanner . SVKeywords ; import net . sf . sveditor . core . scanutils . ITextScanner ; import net . sf . sveditor . core . scanutils . ScanLocation ; public class SVLexer extends SVToken { private ITextScanner fScanner ; private Set < String > fSeqPrefixes [ ] ; private Set < String > fOperatorSet ; private Set < String > fKeywordSet ; private List < ISVTokenListener > fTokenListeners ; private boolean fTokenConsumed ; private boolean fNewlineAsOperator ; private boolean fIsDelayControl ; private StringBuilder fStringBuffer ; private static final boolean fDebugEn = false ; private boolean fEOF ; private StringBuilder fCaptureBuffer ; private boolean fCapture ; private SVToken fCaptureLastToken ; private ISVParser fParser ; private Stack < SVToken > fUngetStack ; private boolean fInAttr ; private LogHandle fLog ; public static final String RelationalOps [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , ">" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; public static final String GroupingOps [ ] = { "" , "" , "" , "" , "" , "" , } ; public static final String MiscOps [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private static final String AllOperators [ ] ; static { AllOperators = new String [ RelationalOps . length + GroupingOps . length + MiscOps . length ] ; int idx = ; for ( String o : RelationalOps ) { AllOperators [ idx ++ ] = o ; } for ( String o : GroupingOps ) { AllOperators [ idx ++ ] = o ; } for ( String o : MiscOps ) { AllOperators [ idx ++ ] = o ; } } @ SuppressWarnings ( "" ) public SVLexer ( ) { fLog = LogFactory . getLogHandle ( "" ) ; fOperatorSet = new HashSet < String > ( ) ; fSeqPrefixes = new Set [ ] { fOperatorSet , new HashSet < String > ( ) , new HashSet < String > ( ) } ; fKeywordSet = new HashSet < String > ( ) ; fStringBuffer = new StringBuilder ( ) ; fCaptureBuffer = new StringBuilder ( ) ; fCapture = false ; fUngetStack = new Stack < SVToken > ( ) ; fTokenListeners = new ArrayList < ISVTokenListener > ( ) ; for ( String op : AllOperators ) { if ( op . length ( ) == ) { fSeqPrefixes [ ] . add ( op . substring ( , ) ) ; fSeqPrefixes [ ] . add ( op . substring ( , ) ) ; } else if ( op . length ( ) == ) { fSeqPrefixes [ ] . add ( op . substring ( , ) ) ; } fOperatorSet . add ( op ) ; } for ( String kw : SVKeywords . getKeywords ( ) ) { if ( kw . endsWith ( "" ) ) { kw = kw . substring ( , kw . length ( ) - ) ; } fKeywordSet . add ( kw ) ; } fEOF = false ; } public void addTokenListener ( ISVTokenListener l ) { fTokenListeners . add ( l ) ; } public void removeTokenListener ( ISVTokenListener l ) { fTokenListeners . remove ( l ) ; } public void setNewlineAsOperator ( boolean en ) { fNewlineAsOperator = en ; } public void setInAttr ( boolean in ) { fInAttr = in ; } public void init ( ISVParser parser , ITextScanner scanner ) { fTokenConsumed = true ; fScanner = scanner ; fEOF = false ; fParser = parser ; } public void init ( SVToken tok ) { fImage = tok . fImage ; fIsIdentifier = tok . fIsIdentifier ; fIsKeyword = tok . fIsKeyword ; fIsNumber = tok . fIsNumber ; fIsOperator = tok . fIsOperator ; fIsString = tok . fIsString ; fIsTime = tok . fIsTime ; fStartLocation = tok . fStartLocation . duplicate ( ) ; } public SVToken peekToken ( ) { peek ( ) ; return this . duplicate ( ) ; } public SVToken consumeToken ( ) { peek ( ) ; SVToken tok = this . duplicate ( ) ; eatToken ( ) ; return tok ; } public void ungetToken ( SVToken tok ) { if ( fDebugEn ) { debug ( "" + tok . getImage ( ) + "" ) ; } if ( ! fTokenConsumed ) { fUngetStack . push ( this . duplicate ( ) ) ; } fTokenConsumed = true ; if ( fCapture ) { if ( fCaptureBuffer . length ( ) >= tok . getImage ( ) . length ( ) ) { fCaptureBuffer . setLength ( fCaptureBuffer . length ( ) - tok . getImage ( ) . length ( ) ) ; } if ( fCaptureBuffer . length ( ) > && fCaptureBuffer . charAt ( fCaptureBuffer . length ( ) - ) == '' ) { fCaptureBuffer . setLength ( fCaptureBuffer . length ( ) - ) ; } fCaptureLastToken = tok . duplicate ( ) ; } if ( fTokenListeners . size ( ) > ) { for ( ISVTokenListener l : fTokenListeners ) { l . ungetToken ( tok ) ; } } fUngetStack . push ( tok ) ; peek ( ) ; if ( fDebugEn ) { debug ( "" + tok . getImage ( ) + "" + peek ( ) + "" ) ; } } public void ungetToken ( List < SVToken > tok_l ) { for ( int i = tok_l . size ( ) - ; i >= ; i -- ) { ungetToken ( tok_l . get ( i ) ) ; } } public String peek ( ) { if ( fTokenConsumed ) { if ( fEOF || ! next_token ( ) ) { fImage = null ; } if ( fDebugEn ) { debug ( "" + fImage + "" + fEOF ) ; } } return fImage ; } public boolean isIdentifier ( ) { peek ( ) ; return fIsIdentifier ; } public boolean isNumber ( ) { peek ( ) ; return fIsNumber ; } public boolean isTime ( ) { peek ( ) ; return fIsTime ; } public boolean isKeyword ( ) { peek ( ) ; return fIsKeyword ; } public boolean isOperator ( ) { peek ( ) ; return fIsOperator ; } public boolean peekOperator ( String ... ops ) throws SVParseException { peek ( ) ; if ( fIsOperator ) { switch ( ops . length ) { case : return true ; case : return ( fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; case : return ( fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ) ; default : for ( String op : ops ) { if ( fImage . equals ( op ) ) { return true ; } } return false ; } } else { return false ; } } public boolean peekOperator ( Set < String > ops ) throws SVParseException { peek ( ) ; if ( fIsOperator ) { return ops . contains ( fImage ) ; } return false ; } public boolean peekId ( ) throws SVParseException { peek ( ) ; return fIsIdentifier ; } public boolean peekNumber ( ) throws SVParseException { peek ( ) ; return fIsNumber ; } public String read ( ) throws SVParseException { peek ( ) ; return eatToken ( ) ; } public String readOperator ( String ... ops ) throws SVParseException { peek ( ) ; boolean found = false ; if ( fIsOperator ) { if ( ops . length == ) { found = true ; } else if ( ops . length == ) { found = fImage . equals ( ops [ ] ) ; } else if ( ops . length == ) { found = fImage . equals ( ops [ ] ) || fImage . equals ( ops [ ] ) ; } else { for ( String op : ops ) { if ( fImage . equals ( op ) ) { found = true ; break ; } } } } if ( ! found ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = ; i < ops . length ; i ++ ) { sb . append ( ops [ i ] ) ; if ( i + < ops . length ) { sb . append ( "" ) ; } } error ( "" + sb . toString ( ) + "" + fImage + "" ) ; } return eatToken ( ) ; } public boolean peekKeyword ( String ... kw ) throws SVParseException { peek ( ) ; if ( fIsKeyword ) { switch ( kw . length ) { case : return true ; case : return fImage . equals ( kw [ ] ) ; case : return ( fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) ) ; case : return ( fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) ) ; case : return ( fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) ) ; case : return ( fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) || fImage . equals ( kw [ ] ) ) ; default : for ( String k : kw ) { if ( fImage . equals ( k ) ) { return true ; } } return false ; } } return false ; } public boolean peekKeyword ( Set < String > kw ) throws SVParseException { peek ( ) ; boolean found = false ; if ( fIsKeyword ) { found = kw . contains ( fImage ) ; } return found ; } public String readKeyword ( Set < String > kw ) throws SVParseException { if ( ! peekKeyword ( kw ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( String k : kw ) { sb . append ( k ) ; } if ( sb . length ( ) > ) { sb . setLength ( sb . length ( ) - ) ; } error ( "" + sb . toString ( ) + "" + fImage + "" ) ; } return eatToken ( ) ; } public String readKeyword ( String ... kw ) throws SVParseException { if ( ! peekKeyword ( kw ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = ; i < kw . length ; i ++ ) { sb . append ( kw [ i ] ) ; if ( i + < kw . length ) { sb . append ( "" ) ; } } error ( "" + sb . toString ( ) + "" + fImage + "" ) ; } return eatToken ( ) ; } public SVToken readKeywordTok ( String ... kw ) throws SVParseException { if ( ! peekKeyword ( kw ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = ; i < kw . length ; i ++ ) { sb . append ( kw [ i ] ) ; if ( i + < kw . length ) { sb . append ( "" ) ; } } error ( "" + sb . toString ( ) + "" + fImage + "" ) ; } return consumeToken ( ) ; } public String eatToken ( ) { peek ( ) ; if ( fCapture ) { if ( fCaptureBuffer . length ( ) > && ( ( isIdentifier ( ) && fCaptureLastToken . isIdentifier ( ) ) || ( isNumber ( ) && fCaptureLastToken . isNumber ( ) ) ) ) { fCaptureBuffer . append ( "" ) ; } fCaptureBuffer . append ( fImage ) ; fCaptureLastToken = duplicate ( ) ; } if ( fTokenListeners . size ( ) > ) { SVToken tok = this . duplicate ( ) ; for ( ISVTokenListener l : fTokenListeners ) { l . tokenConsumed ( tok ) ; } } fTokenConsumed = true ; return fImage ; } public String readString ( ) throws SVParseException { peek ( ) ; if ( ! fIsString ) { error ( "" + fImage + "" ) ; } return eatToken ( ) ; } public boolean peekString ( ) throws SVParseException { peek ( ) ; return fIsString ; } public String readId ( ) throws SVParseException { peek ( ) ; if ( ! fIsIdentifier ) { error ( "" + fImage + "" ) ; } return eatToken ( ) ; } public SVToken readIdTok ( ) throws SVParseException { peek ( ) ; if ( ! fIsIdentifier ) { error ( "" + fImage + "" ) ; } return consumeToken ( ) ; } public String readIdOrKeyword ( ) throws SVParseException { peek ( ) ; if ( ! fIsIdentifier && ! fIsKeyword ) { error ( "" + fImage + "" ) ; } return eatToken ( ) ; } public String readNumber ( ) throws SVParseException { peek ( ) ; if ( ! fIsNumber ) { error ( "" + fImage + "" ) ; } return eatToken ( ) ; } private boolean next_token ( ) { if ( fEOF && fUngetStack . size ( ) == ) { return false ; } try { if ( fUngetStack . size ( ) > ) { if ( fDebugEn ) { debug ( "" + fUngetStack . peek ( ) . getImage ( ) ) ; } init ( fUngetStack . pop ( ) ) ; fTokenConsumed = false ; return true ; } else { return next_token_int ( ) ; } } catch ( SVParseException e ) { return false ; } } public void skipPastMatch ( String start , String end , String ... escape ) { int start_c = , end_c = ; if ( peek ( ) . equals ( start ) ) { eatToken ( ) ; } while ( peek ( ) != null && start_c != end_c ) { if ( peek ( ) . equals ( start ) ) { start_c ++ ; } else if ( peek ( ) . equals ( end ) ) { end_c ++ ; } else if ( escape . length > ) { for ( String e : escape ) { if ( peek ( ) . equals ( e ) ) { return ; } } } eatToken ( ) ; } } public void startCapture ( ) { fCaptureBuffer . setLength ( ) ; fCapture = true ; } public String endCapture ( ) { fCapture = false ; fCaptureLastToken = null ; return fCaptureBuffer . toString ( ) ; } private boolean next_token_int ( ) throws SVParseException { int ch = fScanner . get_ch ( ) ; int ch2 = - ; if ( fDebugEn ) { fLog . debug ( "" ) ; } fIsOperator = false ; fIsNumber = false ; fIsTime = false ; fIsIdentifier = false ; fIsKeyword = false ; fIsString = false ; boolean local_is_delay_ctrl = fIsDelayControl ; fIsDelayControl = false ; while ( true ) { if ( ch == '' ) { ch2 = fScanner . get_ch ( ) ; if ( ch2 == '' ) { while ( ( ch = fScanner . get_ch ( ) ) != - && ch != '' ) { } } else if ( ch2 == '' ) { int end_comment [ ] = { - , - } ; while ( ( ch = fScanner . get_ch ( ) ) != - ) { end_comment [ ] = end_comment [ ] ; end_comment [ ] = ch ; if ( end_comment [ ] == '' && end_comment [ ] == '' ) { break ; } } ch = '' ; } else { fScanner . unget_ch ( ch2 ) ; break ; } } else { if ( ! Character . isWhitespace ( ch ) || ( ch == '' && fNewlineAsOperator ) ) { break ; } } ch = fScanner . get_ch ( ) ; } fStringBuffer . setLength ( ) ; if ( ch != - && ch != ) { append_ch ( ch ) ; } ScanLocation loc = fScanner . getLocation ( ) ; fStartLocation = new SVDBLocation ( loc . getLineNo ( ) , loc . getLinePos ( ) ) ; if ( ch == - ) { fEOF = true ; } else if ( fNewlineAsOperator && ch == '' ) { fIsOperator = true ; } else if ( ch == '' ) { int last_ch = - ; fStringBuffer . setLength ( ) ; while ( ( ch = fScanner . get_ch ( ) ) != - ) { if ( ch == '' && last_ch != '' ) { break ; } append_ch ( ch ) ; if ( last_ch == '' && ch == '' ) { last_ch = - ; } else { last_ch = ch ; } } if ( ch != '' ) { error ( "" ) ; } fIsString = true ; } else if ( ch == '' || ( ch >= '' && ch <= '' ) ) { fIsNumber = true ; if ( ch == '' ) { ch2 = fScanner . get_ch ( ) ; if ( isUnbasedUnsizedLiteralChar ( ch2 ) ) { append_ch ( ch2 ) ; } else if ( isBaseChar ( ch2 ) ) { ch = readBasedNumber ( ch2 ) ; fScanner . unget_ch ( ch ) ; } else { fScanner . unget_ch ( ch2 ) ; fIsOperator = true ; } } else { readNumber ( ch , local_is_delay_ctrl ) ; ch = fScanner . get_ch ( ) ; if ( ch == '' ) { fIsNumber = false ; fIsKeyword = true ; fStringBuffer . append ( ( char ) ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && SVCharacter . isSVIdentifierPart ( ch ) ) { fStringBuffer . append ( ( char ) ch ) ; } fScanner . unget_ch ( ch ) ; } else { fScanner . unget_ch ( ch ) ; } } fImage = fStringBuffer . toString ( ) ; } else if ( ch == '' ) { ch2 = fScanner . get_ch ( ) ; if ( ch2 == '' ) { int ch3 = fScanner . get_ch ( ) ; if ( ch3 != '' ) { append_ch ( '' ) ; fScanner . unget_ch ( ch3 ) ; } else { fScanner . unget_ch ( ch3 ) ; fScanner . unget_ch ( ch2 ) ; } } else { fScanner . unget_ch ( ch2 ) ; } fIsOperator = true ; } else if ( ch == '' ) { ch2 = fScanner . get_ch ( ) ; if ( ch2 == '' && fInAttr ) { append_ch ( '' ) ; } else if ( ch2 == '' || ch2 == '' ) { append_ch ( ch2 ) ; } else { fScanner . unget_ch ( ch2 ) ; } fIsOperator = true ; } else if ( fOperatorSet . contains ( fStringBuffer . toString ( ) ) || fSeqPrefixes [ ] . contains ( fStringBuffer . toString ( ) ) || fSeqPrefixes [ ] . contains ( fStringBuffer . toString ( ) ) ) { operator ( ) ; } else if ( SVCharacter . isSVIdentifierStart ( ch ) ) { int last_ch = ch ; boolean in_ref = false ; while ( ( ch = fScanner . get_ch ( ) ) != - && ( SVCharacter . isSVIdentifierPart ( ch ) || ( ch == '' && last_ch == '' ) || ( ch == '' && in_ref ) ) ) { append_ch ( ch ) ; in_ref |= ( last_ch == '' && ch == '' ) ; in_ref &= ! ( in_ref && ch == '' ) ; last_ch = ch ; } fScanner . unget_ch ( ch ) ; if ( fStringBuffer . length ( ) == && fStringBuffer . charAt ( ) == '' ) { fIsOperator = true ; } else { fIsIdentifier = true ; } } else if ( ch == '' ) { while ( ( ch = fScanner . get_ch ( ) ) != - && ! Character . isWhitespace ( ch ) ) { append_ch ( ch ) ; } fScanner . unget_ch ( ch ) ; } if ( fStringBuffer . length ( ) == && ! fIsString ) { fEOF = true ; if ( fDebugEn ) { debug ( "" + getStartLocation ( ) . toString ( ) ) ; } if ( fDebugEn ) { fLog . debug ( "" ) ; } return false ; } else { fImage = fStringBuffer . toString ( ) ; if ( fIsIdentifier ) { if ( ( fIsKeyword = fKeywordSet . contains ( fImage ) ) ) { if ( SVKeywords . isSVKeyword ( fImage ) ) { fIsIdentifier = false ; } } } fTokenConsumed = false ; if ( fDebugEn ) { debug ( "" + fImage + "" ) ; } if ( fDebugEn ) { fLog . debug ( "" ) ; } return true ; } } private void append_ch ( int ch ) { fStringBuffer . append ( ( char ) ch ) ; if ( fDebugEn ) { debug ( "" + ( char ) ch + "" + fStringBuffer . toString ( ) ) ; if ( ch == - || ch == ) { try { throw new Exception ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } private void operator ( ) throws SVParseException { int ch ; int op_idx = ; if ( fDebugEn ) { debug ( "" + fStringBuffer . toString ( ) ) ; } while ( op_idx < ) { if ( ( ch = fScanner . get_ch ( ) ) != - ) { append_ch ( ch ) ; if ( fDebugEn ) { debug ( "" + ( char ) ch + "" + fStringBuffer . toString ( ) ) ; } if ( ! fSeqPrefixes [ op_idx + ] . contains ( fStringBuffer . toString ( ) ) && ! fOperatorSet . contains ( fStringBuffer . toString ( ) ) ) { fScanner . unget_ch ( ch ) ; fStringBuffer . setLength ( fStringBuffer . length ( ) - ) ; if ( fDebugEn ) { debug ( "" + ( char ) ch + "" ) ; } break ; } else { if ( fDebugEn ) { debug ( "" + ( char ) ch + "" + fStringBuffer . toString ( ) ) ; } } } else { break ; } op_idx ++ ; } if ( fDebugEn ) { debug ( "" + fStringBuffer . toString ( ) ) ; } fIsOperator = true ; String val = fStringBuffer . toString ( ) ; if ( ! fOperatorSet . contains ( val ) ) { error ( "" + fStringBuffer . toString ( ) ) ; } if ( val . equals ( "" ) ) { while ( ( ch = fScanner . get_ch ( ) ) != - && Character . isWhitespace ( ch ) ) { } if ( ch >= '' && ch <= '' ) { fIsDelayControl = true ; } fScanner . unget_ch ( ch ) ; } } private static boolean isBaseChar ( int ch ) { return ( ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' ) ; } private static boolean isUnbasedUnsizedLiteralChar ( int ch ) { return ( ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' ) ; } private static boolean isTimeUnitChar ( int ch ) { return ( ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' ) ; } private int readBasedNumber ( int ch ) throws SVParseException { int base ; append_ch ( ch ) ; if ( ch == '' || ch == '' ) { ch = fScanner . get_ch ( ) ; append_ch ( ch ) ; } if ( ! isBaseChar ( ch ) ) { error ( "" + ( char ) ch ) ; } base = Character . toLowerCase ( ch ) ; while ( ( ch = fScanner . get_ch ( ) ) != - && Character . isWhitespace ( ch ) ) { } if ( base == '' ) { ch = readDecNumber ( ch ) ; } else if ( base == '' ) { ch = readHexNumber ( ch ) ; } else if ( base == '' ) { ch = readOctNumber ( ch ) ; } else if ( base == '' ) { ch = readBinNumber ( ch ) ; } return ch ; } private void readNumber ( int ch , boolean is_delay_ctrl ) throws SVParseException { fStringBuffer . setLength ( fStringBuffer . length ( ) - ) ; ch = readDecNumber ( ch ) ; if ( isTimeUnitChar ( ch ) ) { if ( ch == '' ) { int ch2 = fScanner . get_ch ( ) ; if ( SVCharacter . isSVIdentifierPart ( ch2 ) ) { fScanner . unget_ch ( ch2 ) ; } else { append_ch ( ch ) ; ch = ch2 ; } } else { ch = readTimeUnit ( ch ) ; } } else if ( ch == '' || ch == '' || ch == '' ) { ch = readRealNumber ( ch ) ; } else if ( is_delay_ctrl ) { } else { boolean found_ws = false ; while ( ch != - && Character . isWhitespace ( ch ) ) { ch = fScanner . get_ch ( ) ; found_ws = true ; } if ( ch == '' ) { int ch2 = fScanner . get_ch ( ) ; int ch2_l ; if ( ( ch2_l = Character . toLowerCase ( ch2 ) ) == '' || ch2_l == '' || ch2_l == '' || ch2_l == '' ) { append_ch ( ch ) ; ch = readBasedNumber ( ch2 ) ; } else { fScanner . unget_ch ( ch2 ) ; } } else { if ( found_ws ) { fScanner . unget_ch ( ch ) ; ch = '' ; } } } fScanner . unget_ch ( ch ) ; } private static boolean isDecDigit ( int ch ) { return ( ch >= '' && ch <= '' ) ; } private int readDecNumber ( int ch ) throws SVParseException { while ( ch >= '' && ch <= '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' ) { append_ch ( ch ) ; ch = fScanner . get_ch ( ) ; } return ch ; } private int readRealNumber ( int ch ) throws SVParseException { if ( ch == '' ) { append_ch ( ch ) ; ch = readDecNumber ( fScanner . get_ch ( ) ) ; } if ( ch == '' || ch == '' ) { append_ch ( ch ) ; ch = fScanner . get_ch ( ) ; if ( ch == '' || ch == '' ) { append_ch ( ch ) ; ch = fScanner . get_ch ( ) ; } if ( ! isDecDigit ( ch ) ) { error ( "" + ( char ) ch ) ; } ch = readDecNumber ( ch ) ; } if ( isTimeUnitChar ( ch ) ) { ch = readTimeUnit ( ch ) ; } return ch ; } private int readTimeUnit ( int ch ) throws SVParseException { append_ch ( ch ) ; if ( ch != '' ) { ch = fScanner . get_ch ( ) ; if ( ch != '' ) { error ( "" + ( char ) ch ) ; } append_ch ( ch ) ; } fIsTime = true ; return fScanner . get_ch ( ) ; } private int readHexNumber ( int ch ) throws SVParseException { while ( ch != - && ( ( ch >= '' && ch <= '' ) || ( ch >= '' && ch <= '' ) || ( ch >= '' && ch <= '' ) || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' ) ) { append_ch ( ch ) ; ch = fScanner . get_ch ( ) ; } return ch ; } private int readOctNumber ( int ch ) throws SVParseException { while ( ch != - && ( ( ch >= '' && ch <= '' ) || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' ) ) { append_ch ( ch ) ; ch = fScanner . get_ch ( ) ; } return ch ; } private int readBinNumber ( int ch ) throws SVParseException { while ( ch != - && ( ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' || ch == '' ) ) { append_ch ( ch ) ; ch = fScanner . get_ch ( ) ; } return ch ; } private void debug ( String msg ) { if ( fDebugEn ) { fLog . debug ( msg ) ; } } private void error ( String msg ) throws SVParseException { endCapture ( ) ; setInAttr ( false ) ; fParser . error ( msg ) ; } } package net . sf . sveditor . core . parser ; public interface ISVTokenListener { void tokenConsumed ( SVToken tok ) ; void ungetToken ( SVToken tok ) ; } package net . sf . sveditor . core . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBCovergroup ; import net . sf . sveditor . core . db . SVDBCovergroup . BinsKW ; import net . sf . sveditor . core . db . SVDBCoverpoint ; import net . sf . sveditor . core . db . SVDBCoverpointBins ; import net . sf . sveditor . core . db . SVDBCoverpointBins . BinsType ; import net . sf . sveditor . core . db . SVDBCoverpointCross ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . expr . SVDBBinaryExpr ; import net . sf . sveditor . core . db . expr . SVDBCrossBinsSelectConditionExpr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBFieldAccessExpr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; import net . sf . sveditor . core . db . expr . SVDBParenExpr ; import net . sf . sveditor . core . db . expr . SVDBUnaryExpr ; import net . sf . sveditor . core . db . stmt . SVDBCoverageCrossBinsSelectStmt ; import net . sf . sveditor . core . db . stmt . SVDBCoverageOptionStmt ; public class SVCovergroupParser extends SVParserBase { public SVCovergroupParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; fLexer . readKeyword ( "" ) ; String cg_name = fLexer . readId ( ) ; SVDBCovergroup cg = new SVDBCovergroup ( cg_name ) ; cg . setLocation ( start ) ; while ( fLexer . peekOperator ( "" ) ) { cg . setParamPort ( parsers ( ) . tfPortListParser ( ) . parse ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { error ( "" ) ; } else if ( fLexer . peekOperator ( "" ) ) { cg . setCoverageEvent ( parsers ( ) . exprParser ( ) . clocking_event ( ) ) ; } else if ( fLexer . peekKeyword ( "" ) ) { error ( "" ) ; } fLexer . readOperator ( "" ) ; parent . addChildItem ( cg ) ; try { while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { ISVDBChildItem cov_item ; if ( isOption ( ) ) { cov_item = coverage_option ( ) ; } else { cov_item = coverage_spec ( ) ; } cg . addItem ( cov_item ) ; } cg . setEndLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } catch ( SVParseException e ) { while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" , "" , "" , "" , "" , "" , "" ) ) { fLexer . eatToken ( ) ; } cg . setEndLocation ( fLexer . getStartLocation ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } } } private SVDBCoverageOptionStmt coverage_option ( ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; String type = fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; String name = fLexer . readId ( ) ; SVDBCoverageOptionStmt opt = new SVDBCoverageOptionStmt ( name , type . equals ( "" ) ) ; opt . setLocation ( start ) ; fLexer . readOperator ( "" ) ; opt . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; return opt ; } private ISVDBChildItem coverage_spec ( ) throws SVParseException { ISVDBChildItem ret = null ; String name = "" ; SVDBLocation start = fLexer . getStartLocation ( ) ; if ( fLexer . peekId ( ) ) { name = fLexer . readId ( ) ; fLexer . readOperator ( "" ) ; } String type = fLexer . readKeyword ( "" , "" ) ; if ( type . equals ( "" ) ) { SVDBCoverpoint cp = new SVDBCoverpoint ( name ) ; cp . setLocation ( start ) ; cover_point ( cp ) ; ret = cp ; } else { SVDBCoverpointCross cp = new SVDBCoverpointCross ( name ) ; cp . setLocation ( start ) ; cover_cross ( cp ) ; ret = cp ; } return ret ; } private void cover_point ( SVDBCoverpoint cp ) throws SVParseException { cp . setTarget ( parsers ( ) . exprParser ( ) . expression ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; cp . setIFF ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) { if ( isOption ( ) ) { cp . addItem ( coverage_option ( ) ) ; } else { boolean wildcard = fLexer . peekKeyword ( "" ) ; if ( wildcard ) { fLexer . eatToken ( ) ; } String type = fLexer . readKeyword ( "" , "" , "" ) ; BinsKW kw = ( type . equals ( "" ) ) ? BinsKW . Bins : ( type . equals ( "" ) ) ? BinsKW . IllegalBins : BinsKW . IgnoreBins ; String id = fLexer . readId ( ) ; SVDBCoverpointBins bins = new SVDBCoverpointBins ( wildcard , id , kw ) ; boolean is_array = fLexer . peekOperator ( "" ) ; bins . setIsArray ( is_array ) ; if ( is_array ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { bins . setArrayExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } } fLexer . readOperator ( "" ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; boolean is_sequence = fLexer . peekKeyword ( "" ) ; if ( is_sequence ) { fLexer . eatToken ( ) ; bins . setBinsType ( BinsType . DefaultSeq ) ; } else { bins . setBinsType ( BinsType . Default ) ; } } else { if ( fLexer . peekOperator ( "" ) ) { List < SVDBExpr > l = new ArrayList < SVDBExpr > ( ) ; bins . setBinsType ( BinsType . OpenRangeList ) ; parsers ( ) . exprParser ( ) . open_range_list ( l ) ; } else if ( fLexer . peekOperator ( "" ) ) { bins . setBinsType ( BinsType . TransList ) ; trans_list ( ) ; } else { fLexer . readOperator ( "" , "" ) ; } } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; bins . setIFF ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } cp . addItem ( bins ) ; fLexer . readOperator ( "" ) ; } } fLexer . readOperator ( "" ) ; } else { fLexer . readOperator ( "" ) ; } } private void trans_list ( ) throws SVParseException { while ( fLexer . peek ( ) != null ) { fLexer . readOperator ( "" ) ; trans_set ( ) ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } private void trans_set ( ) throws SVParseException { trans_range_list ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; trans_range_list ( ) ; } } private void trans_range_list ( ) throws SVParseException { range_list ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" , "" , "" ) ; repeat_range ( ) ; fLexer . readOperator ( "" ) ; } } private void range_list ( ) throws SVParseException { while ( fLexer . peek ( ) != null ) { if ( fLexer . peekOperator ( "" ) ) { fParsers . exprParser ( ) . parse_range ( ) ; } else { fParsers . exprParser ( ) . expression ( ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } } private void repeat_range ( ) throws SVParseException { fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fParsers . exprParser ( ) . expression ( ) ; } } private void cover_cross ( SVDBCoverpointCross cp ) throws SVParseException { while ( fLexer . peek ( ) != null ) { SVDBIdentifierExpr id = fParsers . exprParser ( ) . idExpr ( ) ; cp . getCoverpointList ( ) . add ( id ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; cp . setIFF ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekOperator ( "" ) ) { if ( isOption ( ) ) { cp . addItem ( coverage_option ( ) ) ; } else { SVDBCoverageCrossBinsSelectStmt select_stmt = new SVDBCoverageCrossBinsSelectStmt ( ) ; String type = fLexer . readKeyword ( "" , "" , "" ) ; select_stmt . setBinsType ( type ) ; select_stmt . setBinsName ( fParsers . exprParser ( ) . idExpr ( ) ) ; fLexer . readOperator ( "" ) ; select_stmt . setSelectCondition ( select_expression ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; select_stmt . setIffExpr ( fParsers . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; } fLexer . readOperator ( "" ) ; cp . addItem ( select_stmt ) ; } } fLexer . readOperator ( "" ) ; } else { fLexer . readOperator ( "" ) ; } } private SVDBExpr select_expression ( ) throws SVParseException { SVDBExpr expr = or_select_expression ( ) ; return expr ; } private SVDBExpr or_select_expression ( ) throws SVParseException { SVDBExpr expr = and_select_expression ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = new SVDBBinaryExpr ( expr , "" , and_select_expression ( ) ) ; } return expr ; } private SVDBExpr and_select_expression ( ) throws SVParseException { SVDBExpr expr = unary_select_condition ( ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = new SVDBBinaryExpr ( expr , "" , unary_select_condition ( ) ) ; } return expr ; } private SVDBExpr unary_select_condition ( ) throws SVParseException { if ( fLexer . peekOperator ( "" ) ) { return new SVDBUnaryExpr ( "" , select_condition ( ) ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; SVDBParenExpr ret = new SVDBParenExpr ( select_expression ( ) ) ; fLexer . readOperator ( "" ) ; return ret ; } else { return select_condition ( ) ; } } private SVDBExpr select_condition ( ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; SVDBCrossBinsSelectConditionExpr select_c = new SVDBCrossBinsSelectConditionExpr ( ) ; SVDBUnaryExpr not_expr = null ; SVDBExpr bins_expr = null ; select_c . setLocation ( start ) ; if ( fLexer . peekOperator ( "" ) ) { not_expr = new SVDBUnaryExpr ( "" , null ) ; not_expr . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; } fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; bins_expr = fParsers . exprParser ( ) . idExpr ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; bins_expr = new SVDBFieldAccessExpr ( bins_expr , false , fParsers . exprParser ( ) . idExpr ( ) ) ; } if ( not_expr != null ) { not_expr . setExpr ( bins_expr ) ; select_c . setBinsExpr ( not_expr ) ; } else { select_c . setBinsExpr ( bins_expr ) ; } fLexer . readOperator ( "" ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fParsers . exprParser ( ) . open_range_list ( select_c . getIntersectList ( ) ) ; } return select_c ; } private boolean isOption ( ) throws SVParseException { if ( fLexer . peekId ( ) ) { String id = fLexer . peek ( ) ; return ( id . equals ( "" ) || id . equals ( "" ) ) ; } else { return false ; } } } package net . sf . sveditor . core . parser ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Stack ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . IFieldItemAttr ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFieldItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBInclude ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . SVDBMacroDef ; import net . sf . sveditor . core . db . SVDBMacroDefParam ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerKind ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevelListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcessor ; import net . sf . sveditor . core . scanner . IDefineProvider ; import net . sf . sveditor . core . scanner . IPreProcErrorListener ; import net . sf . sveditor . core . scanner . ISVPreProcScannerObserver ; import net . sf . sveditor . core . scanner . ISVScanner ; import net . sf . sveditor . core . scanner . SVKeywords ; import net . sf . sveditor . core . scanutils . ITextScanner ; import net . sf . sveditor . core . scanutils . ScanLocation ; public class ParserSVDBFileFactory implements ISVScanner , IPreProcErrorListener , ISVDBFileFactory , ISVPreProcScannerObserver , ISVParser , ILogLevelListener { private ITextScanner fInput ; private SVLexer fLexer ; private ScanLocation fStmtLocation ; private ScanLocation fStartLocation ; private IDefineProvider fDefineProvider ; private SVDBFile fFile ; private Stack < SVDBScopeItem > fScopeStack ; private SVParsers fSVParsers ; private int fParseErrorCount ; private int fParseErrorMax ; private LogHandle fLog ; private boolean fDebugEn ; private List < SVDBMarker > fMarkers ; private boolean fDisableErrors ; public ParserSVDBFileFactory ( IDefineProvider dp ) { fLog = LogFactory . getLogHandle ( "" , ILogHandle . LOG_CAT_PARSER ) ; fLog . addLogLevelListener ( this ) ; logLevelChanged ( fLog ) ; setDefineProvider ( dp ) ; fScopeStack = new Stack < SVDBScopeItem > ( ) ; if ( dp != null ) { setDefineProvider ( dp ) ; } fParseErrorCount = ; fParseErrorMax = ; } public void setDefineProvider ( IDefineProvider p ) { fDefineProvider = p ; } public void setEvalConditionals ( boolean eval ) { } public ScanLocation getStmtLocation ( ) { if ( fStmtLocation == null ) { return getLocation ( ) ; } return fStmtLocation ; } public ScanLocation getStartLocation ( ) { return fStartLocation ; } public void setStmtLocation ( ScanLocation loc ) { fStmtLocation = loc ; } public void preProcError ( String msg , String filename , int lineno ) { if ( fMarkers != null && ! fDisableErrors ) { SVDBMarker marker = new SVDBMarker ( MarkerType . Error , MarkerKind . UndefinedMacro , msg ) ; marker . setLocation ( new SVDBLocation ( lineno , ) ) ; fMarkers . add ( marker ) ; } } private void top_level_item ( ISVDBScopeItem parent ) throws SVParseException { SVDBLocation start = fLexer . getStartLocation ( ) ; int modifiers = scan_qualifiers ( false ) ; try { if ( fLexer . peekOperator ( "" ) ) { fSVParsers . attrParser ( ) . parse ( parent ) ; } } catch ( SVParseException e ) { } if ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . modIfcBodyItemParser ( ) . parse_bind ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . configParser ( ) . parse_config ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . classParser ( ) . parse ( parent , modifiers ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { parsers ( ) . modIfcProgParser ( ) . parse ( parent , modifiers ) ; } else if ( fLexer . peekKeyword ( "" ) ) { package_decl ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . impExpParser ( ) . parse_import ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . impExpParser ( ) . parse_export ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . dataTypeParser ( ) . typedef ( parent ) ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { parsers ( ) . taskFuncParser ( ) . parse ( parent , start , modifiers ) ; } else if ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . constraintParser ( ) . parse ( parent , modifiers ) ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { parsers ( ) . modIfcBodyItemParser ( ) . parse_parameter_decl ( parent ) ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { parsers ( ) . modIfcBodyItemParser ( ) . parse_time_units_precision ( parent ) ; } else if ( fLexer . peekId ( ) && fLexer . peek ( ) . equals ( "" ) ) { fLexer . eatToken ( ) ; } else if ( ! fLexer . peekOperator ( ) ) { parsers ( ) . modIfcBodyItemParser ( ) . parse_var_decl_module_inst ( parent , modifiers ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { error ( "" + fLexer . peek ( ) + "" ) ; } } public int scan_qualifiers ( boolean param ) throws EOFException { int modifiers = ; Map < String , Integer > qmap = ( param ) ? fTaskFuncParamQualifiers : fFieldQualifers ; String id ; while ( ( id = fLexer . peek ( ) ) != null && qmap . containsKey ( id ) ) { if ( fDebugEn ) { debug ( "" + id + "" ) ; } modifiers |= qmap . get ( id ) ; fLexer . eatToken ( ) ; } return modifiers ; } public String scopedIdentifier ( boolean allow_keywords ) throws SVParseException { StringBuilder id = new StringBuilder ( ) ; if ( ! allow_keywords ) { id . append ( fLexer . readId ( ) ) ; } else if ( fLexer . peekKeyword ( ) || fLexer . peekId ( ) ) { id . append ( fLexer . eatToken ( ) ) ; } else { error ( "" + fLexer . peek ( ) ) ; } while ( fLexer . peekOperator ( "" ) ) { id . append ( "" ) ; fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" ) || ( allow_keywords && fLexer . peekKeyword ( ) ) ) { id . append ( fLexer . readKeyword ( ) ) ; } else { id . append ( fLexer . readId ( ) ) ; } } return id . toString ( ) ; } public List < SVToken > scopedIdentifier_l ( boolean allow_keywords ) throws SVParseException { List < SVToken > ret = new ArrayList < SVToken > ( ) ; if ( ! allow_keywords ) { ret . add ( fLexer . readIdTok ( ) ) ; } else if ( fLexer . peekKeyword ( ) || fLexer . peekId ( ) ) { ret . add ( fLexer . consumeToken ( ) ) ; } else { error ( "" + fLexer . peek ( ) ) ; } while ( fLexer . peekOperator ( "" , "" ) ) { ret . add ( fLexer . consumeToken ( ) ) ; if ( fLexer . peekKeyword ( "" ) || ( allow_keywords && fLexer . peekKeyword ( ) ) ) { ret . add ( fLexer . consumeToken ( ) ) ; } else { ret . add ( fLexer . readIdTok ( ) ) ; } } return ret ; } public List < SVToken > scopedStaticIdentifier_l ( boolean allow_keywords ) throws SVParseException { List < SVToken > ret = new ArrayList < SVToken > ( ) ; if ( ! allow_keywords ) { ret . add ( fLexer . readIdTok ( ) ) ; } else if ( fLexer . peekKeyword ( ) || fLexer . peekId ( ) ) { ret . add ( fLexer . consumeToken ( ) ) ; } else { error ( "" + fLexer . peek ( ) ) ; } while ( fLexer . peekOperator ( "" ) ) { ret . add ( fLexer . consumeToken ( ) ) ; if ( allow_keywords && fLexer . peekKeyword ( ) ) { ret . add ( fLexer . consumeToken ( ) ) ; } else { ret . add ( fLexer . readIdTok ( ) ) ; } } return ret ; } public List < SVToken > peekScopedStaticIdentifier_l ( boolean allow_keywords ) throws SVParseException { List < SVToken > ret = new ArrayList < SVToken > ( ) ; if ( ! allow_keywords ) { if ( fLexer . peekId ( ) ) { ret . add ( fLexer . readIdTok ( ) ) ; } else { return ret ; } } else if ( fLexer . peekKeyword ( ) || fLexer . peekId ( ) ) { ret . add ( fLexer . consumeToken ( ) ) ; } else { return ret ; } while ( fLexer . peekOperator ( "" ) ) { ret . add ( fLexer . consumeToken ( ) ) ; if ( allow_keywords && fLexer . peekKeyword ( ) ) { ret . add ( fLexer . consumeToken ( ) ) ; } else { ret . add ( fLexer . readIdTok ( ) ) ; } } return ret ; } public String scopedIdentifierList2Str ( List < SVToken > scoped_id ) { StringBuilder sb = new StringBuilder ( ) ; for ( SVToken tok : scoped_id ) { sb . append ( tok . getImage ( ) ) ; } return sb . toString ( ) ; } private void package_decl ( ISVDBScopeItem parent ) throws SVParseException { if ( fLexer . peekOperator ( "" ) ) { fSVParsers . attrParser ( ) . parse ( parent ) ; } SVDBPackageDecl pkg = new SVDBPackageDecl ( ) ; pkg . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; fScopeStack . push ( pkg ) ; try { if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; } String pkg_name = readQualifiedIdentifier ( ) ; pkg . setName ( pkg_name ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( pkg ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { top_level_item ( pkg ) ; if ( fLexer . peekKeyword ( "" ) ) { break ; } } pkg . setEndLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } finally { fScopeStack . pop ( ) ; } } static private final Map < String , Integer > fFieldQualifers ; static private final Map < String , Integer > fTaskFuncParamQualifiers ; static { fFieldQualifers = new HashMap < String , Integer > ( ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Local ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Static ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Protected ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Virtual ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Automatic ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Rand ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Randc ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Extern ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Const ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Pure ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_Context ) ; fFieldQualifers . put ( "" , IFieldItemAttr . FieldAttr_SvBuiltin ) ; fTaskFuncParamQualifiers = new HashMap < String , Integer > ( ) ; fTaskFuncParamQualifiers . put ( "" , ) ; fTaskFuncParamQualifiers . put ( "" , SVDBParamPortDecl . FieldAttr_Virtual ) ; fTaskFuncParamQualifiers . put ( "" , SVDBParamPortDecl . Direction_Input ) ; fTaskFuncParamQualifiers . put ( "" , SVDBParamPortDecl . Direction_Output ) ; fTaskFuncParamQualifiers . put ( "" , SVDBParamPortDecl . Direction_Inout ) ; fTaskFuncParamQualifiers . put ( "" , SVDBParamPortDecl . Direction_Ref ) ; fTaskFuncParamQualifiers . put ( "" , SVDBParamPortDecl . Direction_Var ) ; } public static boolean isFirstLevelScope ( String id , int modifiers ) { return ( ( id == null ) || id . equals ( "" ) || ( id . equals ( "" ) && ( modifiers & SVDBFieldItem . FieldAttr_Virtual ) == ) || id . equals ( "" ) ) ; } public static boolean isSecondLevelScope ( String id ) { return ( id . equals ( "" ) || id . equals ( "" ) || id . equals ( "" ) || id . equals ( "" ) || id . equals ( "" ) || id . equals ( "" ) || id . equals ( "" ) ) ; } private String readQualifiedIdentifier ( ) throws SVParseException { if ( ! fLexer . peekId ( ) && ! fLexer . peekKeyword ( ) ) { return null ; } StringBuffer ret = new StringBuffer ( ) ; ret . append ( fLexer . eatToken ( ) ) ; while ( fLexer . peekOperator ( "" ) ) { ret . append ( fLexer . eatToken ( ) ) ; ret . append ( fLexer . eatToken ( ) ) ; } return ret . toString ( ) ; } public ScanLocation getLocation ( ) { return fInput . getLocation ( ) ; } public void debug ( String msg ) { debug ( msg , null ) ; } public void debug ( String msg , Exception e ) { if ( e != null ) { fLog . debug ( msg , e ) ; } else { fLog . debug ( msg ) ; } } public ILogHandle getLogHandle ( ) { return fLog ; } public void logLevelChanged ( ILogHandle handle ) { fDebugEn = fLog . isEnabled ( ) ; } public String strengths ( int max_strengths ) throws SVParseException { boolean done = false ; int num_strengths = ; while ( done == false ) { if ( fLexer . peekKeyword ( SVKeywords . fStrength ) ) { fLexer . readKeyword ( SVKeywords . fStrength ) ; num_strengths ++ ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; done = true ; } else { fLexer . readOperator ( "" ) ; } } if ( max_strengths < num_strengths ) { error ( "" + num_strengths + "" + max_strengths + "" ) ; } return fLexer . endCapture ( ) ; } public String delay_n ( int max_delays ) throws SVParseException { fLexer . readOperator ( "" ) ; boolean has_min_max_typ = false ; boolean done_with_params = false ; int num_delays = ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; while ( done_with_params == false ) { num_delays ++ ; parsers ( ) . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { has_min_max_typ = true ; fLexer . eatToken ( ) ; parsers ( ) . exprParser ( ) . expression ( ) ; fLexer . readOperator ( "" ) ; parsers ( ) . exprParser ( ) . expression ( ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; done_with_params = true ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; } } } else { parsers ( ) . exprParser ( ) . expression ( ) ; } if ( num_delays > max_delays ) { error ( "" + num_delays + "" + max_delays + "" ) ; } return fLexer . endCapture ( ) ; } public void error ( String msg , String filename , int lineno , int linepos ) { if ( fMarkers != null && ! fDisableErrors ) { SVDBMarker marker = new SVDBMarker ( MarkerType . Error , MarkerKind . ParseError , msg ) ; marker . setLocation ( new SVDBLocation ( lineno , linepos ) ) ; fMarkers . add ( marker ) ; } } public SVDBFile parse ( InputStream in , String filename , List < SVDBMarker > markers ) { fScopeStack . clear ( ) ; fFile = new SVDBFile ( filename ) ; fScopeStack . clear ( ) ; fScopeStack . push ( fFile ) ; fMarkers = markers ; if ( fMarkers == null ) { fMarkers = new ArrayList < SVDBMarker > ( ) ; } if ( fDefineProvider != null ) { fDefineProvider . addErrorListener ( this ) ; } SVPreProcessor preproc = new SVPreProcessor ( in , filename , fDefineProvider ) ; fInput = preproc . preprocess ( ) ; fLexer = new SVLexer ( ) ; fLexer . init ( this , fInput ) ; fSVParsers = new SVParsers ( ) ; fSVParsers . init ( this ) ; try { while ( fLexer . peek ( ) != null ) { top_level_item ( fFile ) ; } } catch ( SVParseException e ) { if ( fDebugEn ) { debug ( "" , e ) ; } } catch ( EOFException e ) { e . printStackTrace ( ) ; } catch ( SVAbortParseException e ) { } if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . File ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } if ( fDefineProvider != null ) { fDefineProvider . removeErrorListener ( this ) ; } return fFile ; } public void init ( InputStream in , String name ) { fScopeStack . clear ( ) ; fFile = new SVDBFile ( name ) ; fScopeStack . push ( fFile ) ; if ( fDefineProvider != null ) { fDefineProvider . addErrorListener ( this ) ; } SVPreProcessor preproc = new SVPreProcessor ( in , name , fDefineProvider ) ; fInput = preproc . preprocess ( ) ; fLexer = new SVLexer ( ) ; fLexer . init ( this , fInput ) ; fSVParsers = new SVParsers ( ) ; fSVParsers . init ( this ) ; } public void enter_package ( String name ) { } public void leave_package ( ) { } public void leave_interface_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . InterfaceDecl ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } public void leave_class_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . ClassDecl ) { fScopeStack . pop ( ) ; } } public void leave_task_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . Task ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } public void leave_func_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . Function ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } public void init ( ISVScanner scanner ) { } public void leave_module_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . ModuleDecl ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } public void leave_program_decl ( ) { if ( fScopeStack . size ( ) > && fScopeStack . peek ( ) . getType ( ) == SVDBItemType . ProgramDecl ) { setEndLocation ( fScopeStack . peek ( ) ) ; fScopeStack . pop ( ) ; } } private void setLocation ( ISVDBItemBase item ) { ScanLocation loc = getStmtLocation ( ) ; item . setLocation ( new SVDBLocation ( loc . getLineNo ( ) , loc . getLinePos ( ) ) ) ; } private void setEndLocation ( SVDBScopeItem item ) { ScanLocation loc = getStmtLocation ( ) ; item . setEndLocation ( new SVDBLocation ( loc . getLineNo ( ) , loc . getLinePos ( ) ) ) ; } public void preproc_define ( String key , List < Tuple < String , String > > params , String value ) { SVDBMacroDef def = new SVDBMacroDef ( key , value ) ; setLocation ( def ) ; for ( Tuple < String , String > p : params ) { SVDBMacroDefParam mp = new SVDBMacroDefParam ( p . first ( ) , p . second ( ) ) ; def . addParameter ( mp ) ; } if ( def . getName ( ) == null || def . getName ( ) . equals ( "" ) ) { System . out . println ( "" + "" + def . getLocation ( ) . getLine ( ) ) ; } fScopeStack . peek ( ) . addItem ( def ) ; } public void preproc_include ( String path ) { SVDBInclude inc = new SVDBInclude ( path ) ; setLocation ( inc ) ; fScopeStack . peek ( ) . addItem ( inc ) ; } public void enter_preproc_conditional ( String type , String conditional ) { } public void leave_preproc_conditional ( ) { } public void comment ( String comment , String name ) { } public boolean error_limit_reached ( ) { return ( fParseErrorMax > && fParseErrorCount >= fParseErrorMax ) ; } public SVLexer lexer ( ) { return fLexer ; } public void warning ( String msg , int lineno ) { System . out . println ( "" + msg + "" + lineno ) ; } public void error ( SVParseException e ) throws SVParseException { fParseErrorCount ++ ; error ( e . getMessage ( ) , e . getFilename ( ) , e . getLineno ( ) , e . getLinepos ( ) ) ; String msg = e . getMessage ( ) + "" + e . getFilename ( ) + "" + e . getLineno ( ) ; if ( fDebugEn ) { fLog . debug ( "" + msg , e ) ; } if ( error_limit_reached ( ) ) { throw new SVAbortParseException ( ) ; } throw e ; } public void disableErrors ( boolean dis ) { fDisableErrors = dis ; } public void error ( String msg ) throws SVParseException { error ( SVParseException . createParseException ( msg , fFile . getFilePath ( ) , getLocation ( ) . getLineNo ( ) , getLocation ( ) . getLinePos ( ) ) ) ; } public SVParsers parsers ( ) { return fSVParsers ; } public void enter_file ( String filename ) { } public void leave_file ( ) { } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . SVDBLocation ; public class SVToken { protected String fImage ; protected boolean fIsString ; protected boolean fIsOperator ; protected boolean fIsNumber ; protected boolean fIsTime ; protected boolean fIsIdentifier ; protected boolean fIsKeyword ; protected SVDBLocation fStartLocation ; public SVToken duplicate ( ) { SVToken ret = new SVToken ( ) ; ret . fImage = fImage ; ret . fIsString = fIsString ; ret . fIsOperator = fIsOperator ; ret . fIsNumber = fIsNumber ; ret . fIsTime = fIsTime ; ret . fIsIdentifier = fIsIdentifier ; ret . fIsKeyword = fIsKeyword ; ret . fStartLocation = fStartLocation . duplicate ( ) ; return ret ; } public boolean isIdentifier ( ) { return fIsIdentifier ; } public boolean isNumber ( ) { return fIsNumber ; } public boolean isOperator ( ) { return fIsOperator ; } public boolean isTime ( ) { return fIsTime ; } public boolean isKeyword ( ) { return fIsKeyword ; } public String getImage ( ) { return fImage ; } public SVDBLocation getStartLocation ( ) { return fStartLocation ; } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBConfigDecl ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . stmt . SVDBConfigCellClauseStmt ; import net . sf . sveditor . core . db . stmt . SVDBConfigDefaultClauseStmt ; import net . sf . sveditor . core . db . stmt . SVDBConfigDesignStmt ; import net . sf . sveditor . core . db . stmt . SVDBConfigInstClauseStmt ; import net . sf . sveditor . core . db . stmt . SVDBConfigRuleStmtBase ; public class SVConfigParser extends SVParserBase { public SVConfigParser ( ISVParser parser ) { super ( parser ) ; } public void parse_config ( ISVDBAddChildItem parent ) throws SVParseException { SVDBConfigDecl cfg = new SVDBConfigDecl ( ) ; cfg . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; cfg . setName ( fLexer . readId ( ) ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( cfg ) ; try { while ( fLexer . peekKeyword ( "" ) ) { parsers ( ) . modIfcBodyItemParser ( ) . parse_parameter_decl ( cfg ) ; } SVDBConfigDesignStmt design_stmt = new SVDBConfigDesignStmt ( ) ; design_stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; cfg . addChildItem ( design_stmt ) ; do { SVDBExpr id = fParsers . exprParser ( ) . hierarchical_identifier ( ) ; design_stmt . addCellIdentifier ( id ) ; } while ( fLexer . peekId ( ) ) ; fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null ) { if ( fLexer . peekKeyword ( "" ) ) { default_clause ( cfg ) ; } else if ( fLexer . peekKeyword ( "" ) ) { instance_clause ( cfg ) ; } else if ( fLexer . peekKeyword ( "" ) ) { cell_clause ( cfg ) ; } else { break ; } } fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } catch ( SVParseException e ) { cfg . setEndLocation ( fLexer . getStartLocation ( ) ) ; throw e ; } } private void default_clause ( ISVDBAddChildItem parent ) throws SVParseException { SVDBConfigDefaultClauseStmt dflt_stmt = new SVDBConfigDefaultClauseStmt ( ) ; dflt_stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; parent . addChildItem ( dflt_stmt ) ; fLexer . readKeyword ( "" ) ; liblist_clause ( dflt_stmt ) ; fLexer . readOperator ( "" ) ; } private void instance_clause ( ISVDBAddChildItem parent ) throws SVParseException { SVDBConfigInstClauseStmt inst_stmt = new SVDBConfigInstClauseStmt ( ) ; inst_stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; inst_stmt . setInstName ( fParsers . exprParser ( ) . hierarchical_identifier ( ) ) ; String type = fLexer . readKeyword ( "" , "" ) ; if ( type . equals ( "" ) ) { liblist_clause ( inst_stmt ) ; } else { use_clause ( inst_stmt ) ; } fLexer . readOperator ( "" ) ; } private void cell_clause ( ISVDBAddChildItem parent ) throws SVParseException { SVDBConfigCellClauseStmt inst_stmt = new SVDBConfigCellClauseStmt ( ) ; inst_stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; inst_stmt . setCellId ( fParsers . exprParser ( ) . hierarchical_identifier ( ) ) ; String type = fLexer . readKeyword ( "" , "" ) ; if ( type . equals ( "" ) ) { liblist_clause ( inst_stmt ) ; } else { use_clause ( inst_stmt ) ; } fLexer . readOperator ( "" ) ; } private void liblist_clause ( SVDBConfigRuleStmtBase stmt ) throws SVParseException { while ( fLexer . peekId ( ) ) { stmt . addLib ( fParsers . exprParser ( ) . idExpr ( ) ) ; } } private void use_clause ( SVDBConfigRuleStmtBase stmt ) throws SVParseException { if ( fLexer . peekId ( ) ) { stmt . setLibCellId ( fParsers . exprParser ( ) . hierarchical_identifier ( ) ) ; } if ( fLexer . peekOperator ( "" ) ) { stmt . setParamAssign ( fParsers . paramValueAssignParser ( ) . parse ( true ) ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readKeyword ( "" ) ; } } } package net . sf . sveditor . core . parser ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBGenerateBlock ; import net . sf . sveditor . core . db . SVDBGenerateIf ; public class SVGenerateBlockParser extends SVParserBase { public SVGenerateBlockParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent ) throws SVParseException { if ( fLexer . peekKeyword ( "" ) ) { generate_block ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { if_block ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { for_block ( parent ) ; } else if ( fLexer . peekKeyword ( "" ) ) { case_block ( parent ) ; } else { fLexer . readKeyword ( "" , "" , "" , "" ) ; } } public void generate_block ( ISVDBAddChildItem parent ) throws SVParseException { SVDBGenerateBlock gen_blk = new SVDBGenerateBlock ( "" ) ; gen_blk . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; parent . addChildItem ( gen_blk ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) && ! fLexer . peekKeyword ( "" ) ) { if ( fLexer . peekKeyword ( "" ) ) { begin_end_block ( gen_blk ) ; } else { fParsers . modIfcBodyItemParser ( ) . parse ( gen_blk , "" ) ; } } gen_blk . setEndLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; } private void begin_end_block ( ISVDBAddChildItem parent ) throws SVParseException { fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { fParsers . modIfcBodyItemParser ( ) . parse ( parent , "" ) ; } fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } public void if_block ( ISVDBAddChildItem parent ) throws SVParseException { SVDBGenerateIf if_blk = new SVDBGenerateIf ( ) ; if_blk . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; if_blk . setExpr ( parsers ( ) . exprParser ( ) . expression ( ) ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( if_blk ) ; if ( fLexer . peekKeyword ( "" ) ) { begin_end_block ( if_blk ) ; } else { fParsers . modIfcBodyItemParser ( ) . parse ( if_blk , "" ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { fParsers . modIfcBodyItemParser ( ) . parse ( if_blk , "" ) ; } fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } else { fParsers . modIfcBodyItemParser ( ) . parse ( if_blk , "" ) ; } } } public void for_block ( ISVDBAddChildItem parent ) throws SVParseException { SVDBGenerateBlock gen_blk = new SVDBGenerateBlock ( "" ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } if ( ! fLexer . peekOperator ( "" ) ) { parsers ( ) . exprParser ( ) . expression ( ) ; } fLexer . readOperator ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { parsers ( ) . exprParser ( ) . expression ( ) ; } fLexer . readOperator ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { parsers ( ) . exprParser ( ) . expression ( ) ; } fLexer . readOperator ( "" ) ; parent . addChildItem ( gen_blk ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { fParsers . modIfcBodyItemParser ( ) . parse ( gen_blk , "" ) ; } fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } else { fParsers . modIfcBodyItemParser ( ) . parse ( gen_blk , "" ) ; } } public void case_block ( ISVDBAddChildItem parent ) throws SVParseException { SVDBGenerateBlock case_blk = new SVDBGenerateBlock ( "" ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; parsers ( ) . exprParser ( ) . expression ( ) ; fLexer . readOperator ( "" ) ; parent . addChildItem ( case_blk ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; } else { do { if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } parsers ( ) . exprParser ( ) . expression ( ) ; } while ( fLexer . peekOperator ( "" ) ) ; } fLexer . readOperator ( "" ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { fParsers . modIfcBodyItemParser ( ) . parse ( case_blk , "" ) ; } fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } else { fParsers . modIfcBodyItemParser ( ) . parse ( case_blk , "" ) ; } } fLexer . readKeyword ( "" ) ; } } package net . sf . sveditor . core . parser ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; import net . sf . sveditor . core . scanner . SVKeywords ; public class SVGateInstantiationParser extends SVParserBase { public SVGateInstantiationParser ( ISVParser parser ) { super ( parser ) ; } public void parse ( ISVDBAddChildItem parent ) throws SVParseException { SVDBModIfcInst item = null ; int max_ports = ; int min_ports = ; int max_strengths = ; int max_delays = ; SVDBTypeInfoUserDef type = new SVDBTypeInfoUserDef ( fLexer . eatToken ( ) ) ; String primitive_name = type . getName ( ) ; if ( ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) ) { min_ports = ; max_ports = ; max_delays = ; } else if ( ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) ) { min_ports = ; max_ports = ; max_delays = ; } else if ( ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) ) { min_ports = ; max_ports = - ; max_strengths = ; max_delays = ; } else if ( ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) ) { min_ports = ; max_ports = - ; max_strengths = ; max_delays = ; } else if ( ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) ) { min_ports = ; max_ports = ; max_strengths = ; max_delays = ; } else if ( ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) ) { min_ports = ; max_ports = ; max_delays = ; } else if ( ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) ) { min_ports = ; max_ports = ; max_delays = ; } else if ( ( primitive_name . equals ( "" ) ) || ( primitive_name . equals ( "" ) ) ) { min_ports = ; max_ports = ; max_strengths = ; max_delays = ; } else { error ( "" + primitive_name + "" ) ; } if ( ( max_strengths != ) && ( fLexer . peekOperator ( "" ) ) ) { SVToken tok = fLexer . consumeToken ( ) ; if ( fLexer . peekKeyword ( SVKeywords . fStrength ) ) { String strengths = parsers ( ) . SVParser ( ) . strengths ( max_strengths ) ; } else { fLexer . ungetToken ( tok ) ; } } if ( fLexer . peekOperator ( "" ) ) { parsers ( ) . SVParser ( ) . delay_n ( max_delays ) ; } item = new SVDBModIfcInst ( type ) ; while ( fLexer . peek ( ) != null ) { String name = "" ; if ( fLexer . peekId ( ) ) { name = fLexer . eatToken ( ) ; } SVDBModIfcInstItem inst = new SVDBModIfcInstItem ( name ) ; List < SVDBVarDimItem > arraydims = null ; if ( fLexer . peekOperator ( "" ) ) { arraydims = parsers ( ) . dataTypeParser ( ) . var_dim ( ) ; } item . addInst ( inst ) ; fLexer . readOperator ( "" ) ; boolean terminals_read = false ; int num_ports = ; while ( terminals_read == false ) { parsers ( ) . exprParser ( ) . expression ( ) ; num_ports ++ ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; } else { terminals_read = true ; } } if ( max_ports == - ) { max_ports = num_ports ; } if ( ( num_ports > max_ports ) || ( num_ports < min_ports ) ) { error ( "" + primitive_name + "" + num_ports + "" + min_ports + "" + max_ports + "" ) ; } fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; parent . addChildItem ( item ) ; } } package net . sf . sveditor . core . parser ; import java . util . HashSet ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBAddChildItem ; import net . sf . sveditor . core . db . SVDBItem ; public class SVSpecifyBlockParser extends SVParserBase { public SVSpecifyBlockParser ( ISVParser parser ) { super ( parser ) ; } private static final Set < String > system_timing_checks_kw ; static { system_timing_checks_kw = new HashSet < String > ( ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; system_timing_checks_kw . add ( "" ) ; } public SVDBItem parse ( ISVDBAddChildItem parent ) throws SVParseException { fLexer . readKeyword ( "" ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { if ( fLexer . peekKeyword ( "" ) ) { specparam_declaration ( null ) ; } else if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { error ( "" ) ; } else if ( fLexer . peekOperator ( "" ) ) { path_declaration ( ) ; fLexer . readOperator ( "" ) ; list_of_path_delay_expressions ( ) ; fLexer . readOperator ( "" ) ; } else if ( fLexer . peekId ( ) && system_timing_checks_kw . contains ( fLexer . peek ( ) ) ) { system_timing_checks ( null ) ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { state_dependent_path_declaration ( null ) ; } else { error ( "" + fLexer . peek ( ) ) ; } } fLexer . readKeyword ( "" ) ; return null ; } public void specparam_declaration ( ISVDBAddChildItem parent ) throws SVParseException { fLexer . readKeyword ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fParsers . dataTypeParser ( ) . packed_dim ( ) ; } while ( fLexer . peek ( ) != null ) { fLexer . readId ( ) ; fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . constant_mintypmax_expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } private void system_timing_checks ( ISVDBAddChildItem parent ) throws SVParseException { String type = fLexer . readId ( ) ; fLexer . readOperator ( "" ) ; if ( type . equals ( "" ) || type . equals ( "" ) || type . equals ( "" ) || type . equals ( "" ) || type . equals ( "" ) ) { timing_check_event ( false ) ; fLexer . readOperator ( "" ) ; timing_check_event ( false ) ; fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } else if ( type . equals ( "" ) ) { timing_check_event ( true ) ; fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } else if ( type . equals ( "" ) ) { timing_check_event ( true ) ; fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } } else if ( type . equals ( "" ) ) { timing_check_event ( false ) ; fLexer . readOperator ( "" ) ; timing_check_event ( false ) ; fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . expression ( ) ; fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } } else { error ( "" + type ) ; } fLexer . readOperator ( "" ) ; fLexer . readOperator ( "" ) ; } private void timing_check_event ( boolean is_controlled ) throws SVParseException { if ( fLexer . peekKeyword ( "" , "" ) ) { fLexer . eatToken ( ) ; } else if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } } else if ( is_controlled ) { error ( "" ) ; } fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readId ( ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . const_or_range_expression ( ) ; fLexer . readOperator ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fParsers . exprParser ( ) . expression ( ) ; } } private void path_declaration ( ) throws SVParseException { int count = ; fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null ) { specify_inout_terminal_descriptor ( ) ; count ++ ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } if ( count > ) { fLexer . readOperator ( "" ) ; } else { fLexer . readOperator ( "" ) ; } while ( fLexer . peek ( ) != null ) { specify_inout_terminal_descriptor ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } private void specify_inout_terminal_descriptor ( ) throws SVParseException { fLexer . readId ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; fParsers . exprParser ( ) . const_or_range_expression ( ) ; fLexer . readOperator ( "" ) ; } } private void list_of_path_delay_expressions ( ) throws SVParseException { boolean has_paren = fLexer . peekOperator ( "" ) ; int path_delay_count = ; if ( has_paren ) { fLexer . readOperator ( "" ) ; } while ( fLexer . peek ( ) != null ) { fLexer . readNumber ( ) ; path_delay_count ++ ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } if ( has_paren ) { fLexer . readOperator ( "" ) ; } } private void state_dependent_path_declaration ( ISVDBAddChildItem parent ) throws SVParseException { if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; fParsers . exprParser ( ) . module_path_expression ( ) ; fLexer . readOperator ( "" ) ; } else { error ( "" ) ; } } } package net . sf . sveditor . core . parser ; import java . util . HashSet ; import java . util . Set ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . expr . SVDBBinaryExpr ; import net . sf . sveditor . core . db . expr . SVDBCycleDelayExpr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBFirstMatchExpr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; import net . sf . sveditor . core . db . expr . SVDBLiteralExpr ; import net . sf . sveditor . core . db . expr . SVDBParenExpr ; import net . sf . sveditor . core . db . expr . SVDBPropertyCaseItem ; import net . sf . sveditor . core . db . expr . SVDBPropertyCaseStmt ; import net . sf . sveditor . core . db . expr . SVDBPropertyIfStmt ; import net . sf . sveditor . core . db . expr . SVDBPropertySpecExpr ; import net . sf . sveditor . core . db . expr . SVDBPropertyWeakStrongExpr ; import net . sf . sveditor . core . db . expr . SVDBRangeExpr ; import net . sf . sveditor . core . db . expr . SVDBSequenceClockingExpr ; import net . sf . sveditor . core . db . expr . SVDBSequenceCycleDelayExpr ; import net . sf . sveditor . core . db . expr . SVDBSequenceDistExpr ; import net . sf . sveditor . core . db . expr . SVDBSequenceMatchItemExpr ; import net . sf . sveditor . core . db . expr . SVDBSequenceRepetitionExpr ; import net . sf . sveditor . core . db . expr . SVDBUnaryExpr ; public class SVPropertyExprParser extends SVParserBase { public SVPropertyExprParser ( ISVParser parser ) { super ( parser ) ; } private static final Set < String > BinaryOpKW ; private static final Set < String > BinaryOp ; static { BinaryOpKW = new HashSet < String > ( ) ; BinaryOpKW . add ( "" ) ; BinaryOpKW . add ( "" ) ; BinaryOpKW . add ( "" ) ; BinaryOpKW . add ( "" ) ; BinaryOpKW . add ( "" ) ; BinaryOpKW . add ( "" ) ; BinaryOpKW . add ( "" ) ; BinaryOpKW . add ( "" ) ; BinaryOpKW . add ( "" ) ; BinaryOp = new HashSet < String > ( ) ; BinaryOp . add ( "" ) ; BinaryOp . add ( "" ) ; BinaryOp . add ( "" ) ; BinaryOp . add ( "" ) ; for ( String op : SVLexer . RelationalOps ) { BinaryOp . add ( op ) ; } } public SVDBExpr property_statement ( ) throws SVParseException { SVDBExpr ret ; if ( fLexer . peekKeyword ( "" ) ) { ret = property_statement_if ( ) ; } else if ( fLexer . peekKeyword ( "" ) ) { ret = property_stmt_case ( ) ; } else { SVDBExpr stmt = property_expr ( ) ; fLexer . readOperator ( "" ) ; ret = stmt ; } return ret ; } public SVDBExpr property_expr ( ) throws SVParseException { SVDBExpr ret = null ; if ( fDebugEn ) { debug ( "" ) ; } if ( fLexer . peekKeyword ( "" , "" ) ) { SVDBPropertyWeakStrongExpr ws_expr = new SVDBPropertyWeakStrongExpr ( ) ; ws_expr . setLocation ( fLexer . getStartLocation ( ) ) ; String ws = fLexer . eatToken ( ) ; ws_expr . setIsWeak ( ws . equals ( "" ) ) ; fLexer . readOperator ( "" ) ; ws_expr . setExpr ( fParsers . propertyExprParser ( ) . sequence_expr ( ) ) ; fLexer . readOperator ( "" ) ; ret = ws_expr ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; SVDBExpr p_expr = property_expr ( ) ; fLexer . readOperator ( "" ) ; debug ( "" + p_expr . getClass ( ) . getName ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { SVDBSequenceMatchItemExpr match_expr = new SVDBSequenceMatchItemExpr ( ) ; match_expr . setExpr ( p_expr ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; match_expr . addMatchItemExpr ( sequence_match_item ( ) ) ; } ret = match_expr ; } else { ret = new SVDBParenExpr ( p_expr ) ; } } else if ( fLexer . peekKeyword ( "" ) ) { SVDBUnaryExpr unary_expr = new SVDBUnaryExpr ( ) ; unary_expr . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; unary_expr . setOp ( "" ) ; unary_expr . setExpr ( fParsers . propertyExprParser ( ) . property_expr ( ) ) ; ret = unary_expr ; } else if ( fLexer . peekKeyword ( "" , "" ) ) { } else if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { } else if ( fLexer . peekKeyword ( "" , "" , "" , "" ) ) { } else if ( fLexer . peekKeyword ( "" , "" ) ) { ret = property_statement ( ) ; } else { ret = sequence_expr ( ) ; } if ( fLexer . peekKeyword ( BinaryOpKW ) || fLexer . peekOperator ( BinaryOp ) ) { String op = fLexer . eatToken ( ) ; if ( fDebugEn ) { debug ( "" + op ) ; } ret = new SVDBBinaryExpr ( ret , op , property_expr ( ) ) ; } else if ( fLexer . peekOperator ( "" ) ) { String op = fLexer . eatToken ( ) ; ret = new SVDBBinaryExpr ( ret , op , sequence_expr ( ) ) ; if ( fLexer . peekKeyword ( BinaryOpKW ) || fLexer . peekOperator ( BinaryOp ) ) { op = fLexer . eatToken ( ) ; if ( fDebugEn ) { debug ( "" + op ) ; } ret = new SVDBBinaryExpr ( ret , op , property_expr ( ) ) ; } } if ( fDebugEn ) { debug ( "" ) ; } return ret ; } private SVDBExpr property_statement_if ( ) throws SVParseException { SVDBPropertyIfStmt stmt = new SVDBPropertyIfStmt ( ) ; stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; stmt . setExpr ( expression_or_dist ( ) ) ; fLexer . readOperator ( "" ) ; stmt . setIfExpr ( property_expr ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; stmt . setElseExpr ( property_expr ( ) ) ; } return stmt ; } private SVDBExpr property_stmt_case ( ) throws SVParseException { SVDBPropertyCaseStmt stmt = new SVDBPropertyCaseStmt ( ) ; stmt . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; stmt . setExpr ( expression_or_dist ( ) ) ; fLexer . readOperator ( "" ) ; while ( fLexer . peek ( ) != null && ! fLexer . peekKeyword ( "" ) ) { SVDBPropertyCaseItem case_item = property_stmt_case_item ( ) ; stmt . addItem ( case_item ) ; } fLexer . readKeyword ( "" ) ; return stmt ; } private SVDBPropertyCaseItem property_stmt_case_item ( ) throws SVParseException { if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } SVDBPropertyCaseItem item = new SVDBPropertyCaseItem ( ) ; item . setLocation ( fLexer . getStartLocation ( ) ) ; if ( fLexer . peekKeyword ( "" ) ) { fLexer . eatToken ( ) ; item . addExpr ( new SVDBIdentifierExpr ( "" ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } } else { while ( fLexer . peek ( ) != null ) { item . addExpr ( expression_or_dist ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; } else { break ; } } fLexer . readOperator ( "" ) ; } item . setStmt ( property_statement ( ) ) ; if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return item ; } public SVDBExpr sequence_expr ( ) throws SVParseException { SVDBExpr expr = null ; if ( fDebugEn ) { debug ( "" ) ; } if ( fLexer . peekOperator ( "" ) ) { while ( fLexer . peekOperator ( "" ) ) { SVDBSequenceCycleDelayExpr delay_expr = new SVDBSequenceCycleDelayExpr ( ) ; delay_expr . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; delay_expr . setLhs ( expr ) ; delay_expr . setDelay ( cycle_delay_range ( ) ) ; delay_expr . setRhs ( sequence_expr ( ) ) ; expr = delay_expr ; } } else if ( fLexer . peekOperator ( "" ) ) { SVDBSequenceClockingExpr clk_expr = new SVDBSequenceClockingExpr ( ) ; clk_expr . setLocation ( fLexer . getStartLocation ( ) ) ; clk_expr . setClockingExpr ( fParsers . exprParser ( ) . clocking_event ( ) ) ; clk_expr . setSequenceExpr ( sequence_expr ( ) ) ; expr = clk_expr ; } else if ( fLexer . peekOperator ( "" ) ) { if ( fDebugEn ) { debug ( "" ) ; } SVDBSequenceMatchItemExpr match_expr = new SVDBSequenceMatchItemExpr ( ) ; fLexer . readOperator ( "" ) ; match_expr . setExpr ( sequence_expr ( ) ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; match_expr . addMatchItemExpr ( sequence_match_item ( ) ) ; } fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { match_expr . setSequenceAbbrev ( sequence_abbrev ( ) ) ; } expr = match_expr ; } else if ( fLexer . peekKeyword ( "" ) ) { SVDBFirstMatchExpr first_match = new SVDBFirstMatchExpr ( ) ; first_match . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; fLexer . readOperator ( "" ) ; first_match . setExpr ( sequence_expr ( ) ) ; while ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; first_match . addSequenceMatchItem ( sequence_match_item ( ) ) ; } fLexer . readOperator ( "" ) ; expr = first_match ; } else { expr = expression_or_dist ( ) ; if ( fLexer . peekOperator ( "" ) ) { SVDBExpr bool_abbrev = boolean_abbrev ( ) ; } } if ( fLexer . peekOperator ( "" ) ) { while ( fLexer . peekOperator ( "" ) ) { SVDBSequenceCycleDelayExpr delay_expr = new SVDBSequenceCycleDelayExpr ( ) ; delay_expr . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . eatToken ( ) ; delay_expr . setLhs ( expr ) ; delay_expr . setDelay ( cycle_delay_range ( ) ) ; delay_expr . setRhs ( sequence_expr ( ) ) ; expr = delay_expr ; } } else if ( fLexer . peekKeyword ( "" , "" , "" , "" , "" ) || fLexer . peekOperator ( BinaryOp ) ) { SVDBLocation start = fLexer . getStartLocation ( ) ; expr = new SVDBBinaryExpr ( expr , fLexer . eatToken ( ) , sequence_expr ( ) ) ; expr . setLocation ( start ) ; } if ( fDebugEn ) { debug ( "" + fLexer . peek ( ) ) ; } return expr ; } private SVDBExpr sequence_match_item ( ) throws SVParseException { return fParsers . exprParser ( ) . expression ( ) ; } private SVDBExpr boolean_abbrev ( ) throws SVParseException { SVDBSequenceRepetitionExpr expr = new SVDBSequenceRepetitionExpr ( ) ; expr . setLocation ( fLexer . getStartLocation ( ) ) ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr . setRepType ( "" ) ; if ( ! fLexer . peekOperator ( "" ) ) { expr . setExpr ( fParsers . exprParser ( ) . const_or_range_expression ( ) ) ; } } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr . setRepType ( "" ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr . setRepType ( "" ) ; expr . setExpr ( fParsers . exprParser ( ) . const_or_range_expression ( ) ) ; } else if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr . setRepType ( "" ) ; expr . setExpr ( fParsers . exprParser ( ) . const_or_range_expression ( ) ) ; } fLexer . readOperator ( "" ) ; return expr ; } private SVDBExpr expression_or_dist ( ) throws SVParseException { SVDBExpr expr = fParsers . exprParser ( ) . assert_expression ( ) ; if ( fLexer . peekKeyword ( "" ) ) { SVDBSequenceDistExpr dist = new SVDBSequenceDistExpr ( ) ; dist . setLocation ( fLexer . getStartLocation ( ) ) ; dist . setDistExpr ( fParsers . constraintParser ( ) . dist_expr ( ) ) ; dist . setExpr ( expr ) ; expr = dist ; } return expr ; } private SVDBExpr sequence_abbrev ( ) throws SVParseException { SVDBExpr expr ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" ) ) { expr = new SVDBLiteralExpr ( "" ) ; } else { expr = fParsers . exprParser ( ) . expression ( ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr = new SVDBRangeExpr ( expr , fParsers . exprParser ( ) . expression ( ) ) ; } } } else { fLexer . readOperator ( "" ) ; expr = new SVDBLiteralExpr ( "" ) ; } fLexer . readOperator ( "" ) ; return expr ; } private SVDBCycleDelayExpr cycle_delay_range ( ) throws SVParseException { SVDBCycleDelayExpr expr = new SVDBCycleDelayExpr ( ) ; expr . setLocation ( fLexer . getStartLocation ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; if ( fLexer . peekOperator ( "" , "" ) ) { String op = fLexer . eatToken ( ) ; expr . setExpr ( new SVDBRangeExpr ( new SVDBLiteralExpr ( op ) , new SVDBLiteralExpr ( op ) ) ) ; } else { SVDBExpr expr1 = fParsers . exprParser ( ) . expression ( ) ; fLexer . readOperator ( "" ) ; if ( fLexer . peekOperator ( "" ) ) { fLexer . eatToken ( ) ; expr . setExpr ( new SVDBRangeExpr ( expr1 , new SVDBLiteralExpr ( "" ) ) ) ; } else { expr . setExpr ( new SVDBRangeExpr ( expr1 , fParsers . exprParser ( ) . expression ( ) ) ) ; } } fLexer . readOperator ( "" ) ; } else { expr . setExpr ( fParsers . exprParser ( ) . assert_expression ( ) ) ; } return expr ; } public SVDBPropertySpecExpr property_spec ( ) throws SVParseException { SVDBPropertySpecExpr expr = new SVDBPropertySpecExpr ( ) ; expr . setLocation ( fLexer . getStartLocation ( ) ) ; if ( fLexer . peekOperator ( "" ) ) { expr . setClockingEvent ( fParsers . exprParser ( ) . clocking_event ( ) ) ; } if ( fLexer . peekKeyword ( "" ) ) { fLexer . readKeyword ( "" ) ; fLexer . readKeyword ( "" ) ; fLexer . readOperator ( "" ) ; expr . setDisableExpr ( fParsers . exprParser ( ) . assert_expression ( ) ) ; fLexer . readOperator ( "" ) ; } expr . setExpr ( fParsers . propertyExprParser ( ) . property_expr ( ) ) ; return expr ; } } package net . sf . sveditor . core . docs . model ; public class DocModelStats { } package net . sf . sveditor . core . docs . model ; import java . io . IOException ; import java . io . Writer ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . docs . DocTopicManager ; import net . sf . sveditor . core . docs . IDocTopicManager ; public class DocModel { private Map < String , DocFile > docFiles ; private SymbolTable fSymbolTable ; private Map < String , DocIndex > indexMap ; private IDocTopicManager docTopicManager ; public DocModel ( ) { docFiles = new HashMap < String , DocFile > ( ) ; docTopicManager = new DocTopicManager ( ) ; indexMap = new HashMap < String , DocIndex > ( ) ; fSymbolTable = new SymbolTable ( ) ; } public void addDocFile ( DocFile docFile ) { docFiles . put ( docFile . getTitle ( ) , docFile ) ; } public DocFile getDocFile ( String filePath ) { return docFiles . get ( filePath ) ; } public List < String > getDocFileKeysSorted ( ) { List < String > sortedDocFileKeys = new ArrayList < String > ( docFiles . keySet ( ) ) ; Collections . sort ( sortedDocFileKeys ) ; return sortedDocFileKeys ; } public Set < String > getFileSet ( ) { return docFiles . keySet ( ) ; } public Collection < DocFile > getDocFiles ( ) { return new HashSet < DocFile > ( docFiles . values ( ) ) ; } public SymbolTable getSymbolTable ( ) { return fSymbolTable ; } public DocIndex getTopicIndexMap ( String topic ) { if ( indexMap . containsKey ( topic ) ) { return indexMap . get ( topic ) ; } else { return null ; } } public DocIndex getCreateTopicIndexMap ( String topic ) { DocIndex index ; index = getTopicIndexMap ( topic ) ; if ( index == null ) { index = new DocIndex ( topic ) ; indexMap . put ( topic , index ) ; } return index ; } public IDocTopicManager getDocTopics ( ) { return docTopicManager ; } public void dumpToFile ( Writer writer ) throws IOException { fSymbolTable . dumpSymbolsToFile ( writer ) ; List < DocFile > docFilesByName = new ArrayList < DocFile > ( docFiles . values ( ) ) ; Collections . sort ( docFilesByName , new Comparator < DocFile > ( ) { public int compare ( DocFile o1 , DocFile o2 ) { return o1 . getSrcFileName ( ) . compareToIgnoreCase ( o2 . getSrcFileName ( ) ) ; } } ) ; writer . write ( String . format ( "" ) ) ; writer . write ( String . format ( "" ) ) ; writer . write ( String . format ( "" ) ) ; for ( DocFile docFile : docFilesByName ) { writer . write ( String . format ( "" ) ) ; writer . write ( String . format ( "" , docFile . getSrcFileName ( ) ) ) ; writer . write ( String . format ( "" ) ) ; writer . write ( String . format ( "" , docFile . getChildren ( ) . size ( ) ) ) ; writer . write ( String . format ( "" , docFile . getSummary ( ) ) ) ; writer . write ( String . format ( "" ) ) ; } writer . write ( String . format ( "" ) ) ; for ( DocFile docFile : docFilesByName ) { String srcFileName = docFile . getSrcFileName ( ) ; writer . write ( String . format ( "" ) ) ; writer . write ( String . format ( "" , srcFileName ) ) ; writer . write ( String . format ( "" ) ) ; for ( DocTopic childTopic : docFile . getChildren ( ) ) { dumpTopic ( writer , childTopic , String . format ( "" , srcFileName ) ) ; } } } private void dumpTopic ( Writer writer , DocTopic topic , String preFix ) throws IOException { writer . write ( String . format ( "" , preFix ) ) ; writer . write ( String . format ( "" , preFix , topic . getTitle ( ) ) ) ; writer . write ( String . format ( "" , preFix ) ) ; writer . write ( String . format ( "" , preFix , topic . getQualifiedName ( ) ) ) ; writer . write ( String . format ( "" , preFix , topic . getTopic ( ) ) ) ; writer . write ( String . format ( "" , preFix , topic . getKeyword ( ) ) ) ; writer . write ( String . format ( "" , preFix , topic . getChildren ( ) . size ( ) ) ) ; writer . write ( String . format ( "" , preFix , topic . getSummary ( ) ) ) ; writer . write ( String . format ( "" , preFix , topic . getBody ( ) ) ) ; if ( topic . getChildren ( ) . size ( ) != ) { writer . write ( String . format ( "" , preFix ) ) ; writer . write ( String . format ( "" , preFix ) ) ; writer . write ( String . format ( "" , preFix ) ) ; for ( DocTopic childTopic : topic . getChildren ( ) ) { dumpTopic ( writer , childTopic , String . format ( "" , preFix , topic . getTitle ( ) ) ) ; } } writer . write ( String . format ( "" , preFix ) ) ; } } package net . sf . sveditor . core . docs . model ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; public class DocIndex { public static final String IndexKeyWierd = "" ; public static final String IndexKeyNum = "" ; public static final String indexKeys [ ] = { IndexKeyWierd , IndexKeyNum , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private Map < String , Collection < DocTopic > > fMap ; private String fTopicName ; public DocIndex ( String topicName ) { setTopicName ( topicName ) ; fMap = new HashMap < String , Collection < DocTopic > > ( ) ; for ( String key : indexKeys ) { fMap . put ( key , new HashSet < DocTopic > ( ) ) ; } } public String getTopicName ( ) { return fTopicName ; } public void setTopicName ( String topicName ) { this . fTopicName = topicName ; } public Map < String , Collection < DocTopic > > getMap ( ) { return fMap ; } public void indexTopic ( DocTopic docTopic ) { String name = docTopic . getTitle ( ) ; String firstChar = name . substring ( , ) . toUpperCase ( ) ; if ( fMap . containsKey ( firstChar ) ) { fMap . get ( firstChar ) . add ( docTopic ) ; } else if ( firstChar . matches ( "" ) ) { fMap . get ( IndexKeyNum ) . add ( docTopic ) ; } else { fMap . get ( IndexKeyWierd ) . add ( docTopic ) ; } } } package net . sf . sveditor . core . docs . model ; import java . util . ArrayList ; import java . util . List ; public class DocTopic implements IDocTopic { private String fTitle ; private String fSummary ; private String fKeyword ; private String fTopic ; private String fBody ; private List < DocTopic > fChildren ; private String fEnclosingPkg ; private String fEnclosingClass ; private DocFile fDocFile ; public DocTopic ( ) { fTitle = "" ; fChildren = new ArrayList < DocTopic > ( ) ; fSummary = "" ; fBody = "" ; fEnclosingPkg = "" ; fEnclosingClass = "" ; fDocFile = null ; } public DocTopic ( String topicTitle , String topicTypeName , String keyword ) { this ( ) ; setTitle ( topicTitle ) ; setTopic ( topicTypeName ) ; setKeyword ( keyword ) ; } public String getQualifiedName ( ) { String ret = fTitle ; if ( ! fEnclosingClass . isEmpty ( ) ) { ret = fEnclosingClass + "" + ret ; } if ( ! fEnclosingPkg . isEmpty ( ) ) { ret = fEnclosingPkg + "" + ret ; } return ret ; } public String getTitle ( ) { return fTitle ; } public void setTitle ( String title ) { fTitle = title ; } public void addChild ( DocTopic child ) { fChildren . add ( child ) ; child . setDocFile ( getDocFile ( ) ) ; } public List < DocTopic > getChildren ( ) { return fChildren ; } public String getSummary ( ) { return fSummary ; } public void setSummary ( String summary ) { this . fSummary = summary ; } public void setBody ( String body ) { this . fBody = body ; } public String getBody ( ) { return fBody ; } public String getEnclosingPkg ( ) { return fEnclosingPkg ; } public void setEnclosingPkg ( String pkg ) { this . fEnclosingPkg = pkg ; } public String getEnclosingClass ( ) { return fEnclosingClass ; } public void setEnclosingClass ( String c ) { this . fEnclosingClass = c ; } public DocFile getDocFile ( ) { return fDocFile ; } public void setDocFile ( DocFile docFile ) { this . fDocFile = docFile ; } public String getKeyword ( ) { return fKeyword ; } public void setKeyword ( String keyword ) { this . fKeyword = keyword ; } public String getTopic ( ) { return fTopic ; } public void setTopic ( String topic ) { this . fTopic = topic ; } private int fFieldAttr ; public void setAttr ( int attr ) { fFieldAttr = attr ; } public int getAttr ( ) { return fFieldAttr ; } } package net . sf . sveditor . core . docs . model ; import java . io . File ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBDocComment ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . docs . DocCommentCleaner ; import net . sf . sveditor . core . docs . DocCommentParser ; import net . sf . sveditor . core . docs . DocGenConfig ; import net . sf . sveditor . core . docs . DocKeywordInfo ; import net . sf . sveditor . core . docs . DocTopicType ; import net . sf . sveditor . core . docs . IDocCommentParser ; import net . sf . sveditor . core . docs . IDocTopicManager ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . NullProgressMonitor ; public class DocModelFactory { private LogHandle fLog ; private class DocModelFactoryException extends Exception { private static final long serialVersionUID = - ; public DocModelFactoryException ( String msg ) { super ( msg ) ; } } public DocModelFactory ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } public DocModel build ( DocGenConfig cfg ) { DocModel model = new DocModel ( ) ; IDocCommentParser docCommentParser = new DocCommentParser ( model . getDocTopics ( ) ) ; try { gatherSymbols ( cfg , model ) ; gatherDocTopicsFromPreProcFiles ( cfg , model , docCommentParser ) ; gatherPackageContentFromDeclCache ( cfg , model ) ; assignSymbolsTheirDocFiles ( cfg , model ) ; setPageTitles ( cfg , model ) ; indexTopics ( cfg , model ) ; } catch ( Exception e ) { fLog . error ( "" + e . toString ( ) ) ; } return model ; } private void assignSymbolsTheirDocFiles ( DocGenConfig cfg , DocModel model ) { for ( String symbol : model . getSymbolTable ( ) . getSymbolSet ( ) ) { SymbolTableEntry entry = model . getSymbolTable ( ) . getSymbol ( symbol ) ; String file = entry . getFile ( ) ; DocFile docFile = model . getDocFile ( file ) ; if ( docFile == null ) { fLog . debug ( ILogLevel . LEVEL_MIN , String . format ( "" , symbol ) ) ; } else { fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , symbol , file ) ) ; entry . setDocFile ( docFile ) ; } } } private void setPageTitles ( DocGenConfig cfg , DocModel model ) { IDocTopicManager topicMgr = model . getDocTopics ( ) ; for ( DocFile docFile : model . getDocFiles ( ) ) { boolean setFromTopic = false ; for ( DocTopic childTopic : docFile . getChildren ( ) ) { DocKeywordInfo kwi = topicMgr . getTopicType ( childTopic . getKeyword ( ) ) ; if ( kwi . getTopicType ( ) . isPageTitleIfFirst ( ) ) { docFile . setPageTitle ( childTopic . getTitle ( ) ) ; setFromTopic = true ; } break ; } if ( ! setFromTopic ) { File file = new File ( docFile . getTitle ( ) ) ; docFile . setPageTitle ( file . getName ( ) ) ; } } } private void gatherDocTopicsFromPreProcFiles ( DocGenConfig cfg , DocModel model , IDocCommentParser docCommentParser ) { HashSet < ISVDBIndex > visitedIndex = new HashSet < ISVDBIndex > ( ) ; fLog . debug ( ILogLevel . LEVEL_MIN , "" ) ; for ( Tuple < SVDBDeclCacheItem , ISVDBIndex > pkgTuple : cfg . getSelectedPackages ( ) ) { ISVDBIndex index = pkgTuple . second ( ) ; if ( ! visitedIndex . contains ( index ) ) { visitedIndex . add ( index ) ; for ( String file : index . getFileList ( new NullProgressMonitor ( ) ) ) { DocTopic parent = null ; SVDBFile ppFile = index . getCache ( ) . getPreProcFile ( new NullProgressMonitor ( ) , file ) ; if ( ppFile == null ) { fLog . error ( "" + file ) ; } else { fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" + file + "" ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; String path = file ; String shortFileName = new File ( path ) . getName ( ) ; if ( path . startsWith ( "" ) ) { path = path . substring ( "" . length ( ) ) ; } DocFile docFile = new DocFile ( file ) ; parent = docFile ; docFile . setDocPath ( path ) ; boolean fileHasDocs = false ; for ( ISVDBChildItem child : ppFile . getChildren ( ) ) { if ( child instanceof SVDBDocComment ) { List < DocTopic > docTopics = new ArrayList < DocTopic > ( ) ; SVDBDocComment docCom = ( SVDBDocComment ) child ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName , docCom . getName ( ) ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName ) ) ; String lines [ ] = DocCommentCleaner . splitCommentIntoLines ( docCom . getRawComment ( ) ) ; int lin_num = ; for ( String line : lines ) { fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName , lin_num , line ) ) ; lin_num ++ ; } fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName ) ) ; docCommentParser . parse ( docCom . getRawComment ( ) , docTopics ) ; for ( DocTopic topic : docTopics ) { IDocTopicManager topicMgr = model . getDocTopics ( ) ; DocKeywordInfo kwi = topicMgr . getTopicType ( topic . getKeyword ( ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName , topic . getTitle ( ) ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName , topic . getSummary ( ) ) ) ; fileHasDocs = true ; switch ( kwi . getTopicType ( ) . getScopeType ( ) ) { case START : docFile . addChild ( topic ) ; parent = topic ; break ; case NORMAL : parent . addChild ( topic ) ; break ; case END : parent = docFile ; parent . addChild ( topic ) ; break ; default : break ; } } fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , shortFileName ) ) ; } } fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" + file + "" ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; if ( fileHasDocs ) { model . addDocFile ( docFile ) ; } } } } } } private void gatherSymbols ( DocGenConfig cfg , DocModel model ) { fLog . debug ( ILogLevel . LEVEL_MIN , "" ) ; for ( Tuple < SVDBDeclCacheItem , ISVDBIndex > pkgTuple : cfg . getSelectedPackages ( ) ) { SVDBDeclCacheItem pkgDeclCacheItem = pkgTuple . first ( ) ; ISVDBIndex pkgSvdbIndex = pkgTuple . second ( ) ; SymbolTableEntry pkgSTE = SymbolTableEntry . createPkgEntry ( pkgDeclCacheItem . getName ( ) , pkgSvdbIndex , pkgDeclCacheItem . getFilename ( ) , pkgDeclCacheItem ) ; model . getSymbolTable ( ) . addSymbol ( pkgSTE ) ; gatherSymbolsFromPackage ( cfg , model , pkgDeclCacheItem , pkgSvdbIndex ) ; } model . getSymbolTable ( ) . dumpSymbols ( ) ; } private void gatherSymbolsFromPackage ( DocGenConfig cfg , DocModel model , SVDBDeclCacheItem pkgDeclCacheItem , ISVDBIndex pkgSvdbIndex ) { List < SVDBDeclCacheItem > pkgDecls = pkgDeclCacheItem . getParent ( ) . findPackageDecl ( new NullProgressMonitor ( ) , pkgDeclCacheItem ) ; if ( pkgDecls != null ) { for ( SVDBDeclCacheItem pkgDecl : pkgDecls ) { if ( pkgDecl . getType ( ) == SVDBItemType . ClassDecl ) { SymbolTableEntry classSTE = SymbolTableEntry . createClassEntry ( pkgDeclCacheItem . getName ( ) , pkgDecl . getName ( ) , pkgSvdbIndex , pkgDecl . getFilename ( ) , pkgDecl ) ; model . getSymbolTable ( ) . addSymbol ( classSTE ) ; gatherSymbolsFromClass ( cfg , model , pkgSvdbIndex , pkgDeclCacheItem , pkgDecl ) ; } } } else { fLog . debug ( ILogLevel . LEVEL_MID , "" + pkgDeclCacheItem . getName ( ) + "" ) ; } } private void gatherSymbolsFromClass ( DocGenConfig cfg , DocModel model , ISVDBIndex pkgSvdbIndex , SVDBDeclCacheItem pkgDeclCacheItem , SVDBDeclCacheItem classDeclCacheItem ) { SVDBClassDecl svdbClassDecl = ( SVDBClassDecl ) classDeclCacheItem . getSVDBItem ( ) ; for ( ISVDBChildItem ci : svdbClassDecl . getChildren ( ) ) { if ( ci . getType ( ) == SVDBItemType . Task ) { SVDBTask svdbTask = ( SVDBTask ) ci ; SymbolTableEntry taskSTE = SymbolTableEntry . createClassMemberEntry ( pkgDeclCacheItem . getName ( ) , classDeclCacheItem . getName ( ) , svdbTask . getName ( ) , pkgSvdbIndex , classDeclCacheItem . getFilename ( ) ) ; model . getSymbolTable ( ) . addSymbol ( taskSTE ) ; } else if ( ci . getType ( ) == SVDBItemType . Function ) { SVDBFunction svdbFunction = ( SVDBFunction ) ci ; SymbolTableEntry funcSTE = SymbolTableEntry . createClassMemberEntry ( pkgDeclCacheItem . getName ( ) , classDeclCacheItem . getName ( ) , svdbFunction . getName ( ) , pkgSvdbIndex , classDeclCacheItem . getFilename ( ) ) ; model . getSymbolTable ( ) . addSymbol ( funcSTE ) ; } else if ( ci . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt varDecl = ( SVDBVarDeclStmt ) ci ; for ( ISVDBChildItem varItem : varDecl . getChildren ( ) ) { if ( varItem instanceof SVDBVarDeclItem ) { SVDBVarDeclItem varDeclItem = ( SVDBVarDeclItem ) varItem ; SymbolTableEntry varSTE = SymbolTableEntry . createClassMemberEntry ( pkgDeclCacheItem . getName ( ) , classDeclCacheItem . getName ( ) , varDeclItem . getName ( ) , pkgSvdbIndex , classDeclCacheItem . getFilename ( ) ) ; model . getSymbolTable ( ) . addSymbol ( varSTE ) ; } } } } } private void gatherPackageContentFromDeclCache ( DocGenConfig cfg , DocModel model ) throws DocModelFactoryException { fLog . debug ( ILogLevel . LEVEL_MIN , "" ) ; for ( Tuple < SVDBDeclCacheItem , ISVDBIndex > pkgTuple : cfg . getSelectedPackages ( ) ) { SVDBDeclCacheItem pkg = pkgTuple . first ( ) ; if ( pkg . getParent ( ) == null ) { throw new DocModelFactoryException ( "" + pkg . getName ( ) ) ; } gatherPackageClasses ( model , pkg , pkgTuple . second ( ) ) ; } } private void gatherPackageClasses ( DocModel model , SVDBDeclCacheItem pkg , ISVDBIndex isvdbIndex ) throws DocModelFactoryException { String pkgName = pkg . getName ( ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" + pkgName ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; List < SVDBDeclCacheItem > pkgDecls = pkg . getParent ( ) . findPackageDecl ( new NullProgressMonitor ( ) , pkg ) ; if ( pkgDecls != null ) { for ( SVDBDeclCacheItem pkgDecl : pkgDecls ) { SVDBFile ppFile = isvdbIndex . getCache ( ) . getPreProcFile ( new NullProgressMonitor ( ) , pkgDecl . getFile ( ) . getFilePath ( ) ) ; if ( ppFile != null ) { String symbol = String . format ( "" , pkg . getName ( ) , pkgDecl . getName ( ) ) ; DocFile docFile = model . getDocFile ( pkgDecl . getFile ( ) . getFilePath ( ) ) ; if ( docFile != null ) { for ( DocTopic docItem : docFile . getChildren ( ) ) { if ( docItem . getTitle ( ) . equals ( pkgDecl . getName ( ) ) ) { fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , pkgName , symbol ) ) ; SymbolTableEntry symbolEntry = model . getSymbolTable ( ) . getSymbol ( symbol ) ; if ( symbolEntry == null ) { fLog . debug ( ILogLevel . LEVEL_MIN , "" + symbol + "" ) ; } else { symbolEntry . setDocFile ( docFile ) ; symbolEntry . setDocumented ( true ) ; docItem . setEnclosingPkg ( pkg . getName ( ) ) ; if ( pkgDecl . getType ( ) == SVDBItemType . ClassDecl && docItem . getTopic ( ) . equals ( "" ) ) { gatherClassMembers ( docItem , pkg , pkgDecl , model , isvdbIndex , docFile , ppFile ) ; } } break ; } } } else { } } } } else { fLog . debug ( "" + pkg . getName ( ) + "" ) ; } } private void gatherClassMembers ( DocTopic classDocItem , SVDBDeclCacheItem pkgDeclCacheItem , SVDBDeclCacheItem classDeclCacheItem , DocModel model , ISVDBIndex isvdbIndex , DocFile docFile , SVDBFile ppFile ) { SVDBClassDecl svdbClassDecl = ( SVDBClassDecl ) classDeclCacheItem . getSVDBItem ( ) ; String pkgName = pkgDeclCacheItem . getName ( ) ; String className = svdbClassDecl . getName ( ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , pkgName ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , pkgName , className ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , pkgName ) ) ; for ( ISVDBChildItem ci : svdbClassDecl . getChildren ( ) ) { if ( ci . getType ( ) == SVDBItemType . Task ) { SVDBTask svdbTask = ( SVDBTask ) ci ; for ( DocTopic docItem : classDocItem . getChildren ( ) ) { if ( docItem . getTitle ( ) . equals ( svdbTask . getName ( ) ) ) { docItem . setEnclosingClass ( classDeclCacheItem . getName ( ) ) ; docItem . setEnclosingPkg ( pkgDeclCacheItem . getName ( ) ) ; String symbol = docItem . getQualifiedName ( ) ; SymbolTableEntry symbolEntry = model . getSymbolTable ( ) . getSymbol ( symbol ) ; if ( symbolEntry == null ) { fLog . debug ( ILogLevel . LEVEL_MIN , "" + symbol + "" ) ; } else { fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , pkgName , className , symbol ) ) ; symbolEntry . setDocFile ( docFile ) ; symbolEntry . setDocumented ( true ) ; } break ; } } } if ( ci . getType ( ) == SVDBItemType . Function ) { SVDBFunction svdbFunc = ( SVDBFunction ) ci ; for ( DocTopic docItem : classDocItem . getChildren ( ) ) { if ( docItem . getTitle ( ) . equals ( svdbFunc . getName ( ) ) ) { docItem . setEnclosingClass ( classDeclCacheItem . getName ( ) ) ; docItem . setEnclosingPkg ( pkgDeclCacheItem . getName ( ) ) ; String symbol = docItem . getQualifiedName ( ) ; SymbolTableEntry symbolEntry = model . getSymbolTable ( ) . getSymbol ( symbol ) ; if ( symbolEntry == null ) { fLog . debug ( ILogLevel . LEVEL_MIN , "" + symbol + "" ) ; } else { fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , pkgName , className , symbol ) ) ; symbolEntry . setDocFile ( docFile ) ; symbolEntry . setDocumented ( true ) ; } break ; } } } if ( ci . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt svdbVarDeclStmt = ( SVDBVarDeclStmt ) ci ; for ( ISVDBChildItem child : svdbVarDeclStmt . getChildren ( ) ) { SVDBVarDeclItem varDeclItem = ( SVDBVarDeclItem ) child ; for ( DocTopic docItem : classDocItem . getChildren ( ) ) { if ( docItem . getTitle ( ) . equals ( varDeclItem . getName ( ) ) ) { docItem . setEnclosingClass ( classDeclCacheItem . getName ( ) ) ; docItem . setEnclosingPkg ( pkgDeclCacheItem . getName ( ) ) ; String symbol = docItem . getQualifiedName ( ) ; SymbolTableEntry symbolEntry = model . getSymbolTable ( ) . getSymbol ( symbol ) ; if ( symbolEntry == null ) { fLog . debug ( ILogLevel . LEVEL_MIN , "" + symbol + "" ) ; } else { fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , pkgName , className , symbol ) ) ; symbolEntry . setDocFile ( docFile ) ; symbolEntry . setDocumented ( true ) ; } break ; } } } } } fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , pkgName ) ) ; } private void indexTopics ( DocGenConfig cfg , DocModel model ) { IDocTopicManager dtMan = model . getDocTopics ( ) ; for ( DocTopicType docTopicType : dtMan . getAllTopicTypes ( ) ) { if ( docTopicType . isIndex ( ) ) { model . getCreateTopicIndexMap ( docTopicType . getName ( ) ) ; } } for ( DocTopic item : model . getDocFiles ( ) ) { indexTopic ( model , item ) ; } } private void indexTopic ( DocModel model , DocTopic item ) { DocIndex docIndex = model . getTopicIndexMap ( item . getTopic ( ) . toLowerCase ( ) ) ; if ( docIndex != null ) { docIndex . indexTopic ( item ) ; } for ( DocTopic child : item . getChildren ( ) ) { indexTopic ( model , child ) ; } } } package net . sf . sveditor . core . docs . model ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; enum SymbolType { CLASS , PKG , CLASS_MEMBER } ; public class SymbolTableEntry { private String symbol ; private String pkgName ; private String className ; private String memberName ; private String topicType ; private String file ; private SymbolType symbolType ; private boolean isDocumented ; private ISVDBIndex svdbIndex ; private SVDBDeclCacheItem declCacheItem ; private DocFile docFile ; public static SymbolTableEntry createPkgEntry ( String pkgName , ISVDBIndex svdbIndex , String file , SVDBDeclCacheItem declCacheItem ) { String symbolName = pkgName ; SymbolTableEntry result = new SymbolTableEntry ( symbolName , SymbolType . PKG ) ; result . setPkgName ( pkgName ) ; result . setSvdbIndex ( svdbIndex ) ; result . setFile ( file ) ; result . setDeclCacheItem ( declCacheItem ) ; return result ; } public static SymbolTableEntry createClassEntry ( String pkgName , String className , ISVDBIndex svdbIndex , String file , SVDBDeclCacheItem declCacheItem ) { String symbolName = String . format ( "" , pkgName , className ) ; SymbolTableEntry result = new SymbolTableEntry ( symbolName , SymbolType . CLASS ) ; result . setPkgName ( pkgName ) ; result . setClassName ( className ) ; result . setSvdbIndex ( svdbIndex ) ; result . setFile ( file ) ; result . setDeclCacheItem ( declCacheItem ) ; return result ; } public static SymbolTableEntry createClassMemberEntry ( String pkgName , String className , String memberName , ISVDBIndex svdbIndex , String file ) { String symbolName = String . format ( "" , pkgName , className , memberName ) ; SymbolTableEntry result = new SymbolTableEntry ( symbolName , SymbolType . CLASS_MEMBER ) ; result . setPkgName ( pkgName ) ; result . setClassName ( className ) ; result . setMemberName ( memberName ) ; result . setSvdbIndex ( svdbIndex ) ; result . setFile ( file ) ; return result ; } public SymbolTableEntry ( String symbol , SymbolType symbolType ) { this . symbol = symbol ; this . symbolType = symbolType ; this . pkgName = null ; this . memberName = null ; this . svdbIndex = null ; this . topicType = "" ; this . declCacheItem = null ; this . isDocumented = false ; } public String getMemberName ( ) { return memberName ; } public void setMemberName ( String memberName ) { this . memberName = memberName ; } public String getSymbol ( ) { return symbol ; } public void setSymbol ( String symbol ) { this . symbol = symbol ; } public String getPkgName ( ) { return pkgName ; } public void setPkgName ( String pkgName ) { this . pkgName = pkgName ; } public String getClassName ( ) { return className ; } public void setClassName ( String className ) { this . className = className ; } public SymbolType getSymbolType ( ) { return symbolType ; } public void setSymbolType ( SymbolType symbolType ) { this . symbolType = symbolType ; } public ISVDBIndex getSvdbIndex ( ) { return svdbIndex ; } public void setSvdbIndex ( ISVDBIndex svdbIndex ) { this . svdbIndex = svdbIndex ; } public SVDBDeclCacheItem getDeclCacheItem ( ) { return declCacheItem ; } public void setDeclCacheItem ( SVDBDeclCacheItem declCacheItem ) { this . declCacheItem = declCacheItem ; } public boolean isDocumented ( ) { return isDocumented ; } public void setDocumented ( boolean isDocumented ) { this . isDocumented = isDocumented ; } public String getDocPath ( ) { if ( this . docFile != null ) { return docFile . getDocPath ( ) ; } else { return "" + getSymbol ( ) ; } } public void setDocFile ( DocFile docFile ) { this . docFile = docFile ; } public DocFile getDocFile ( ) { return this . docFile ; } public String getTopicType ( ) { return topicType ; } public void setTopicType ( String topicType ) { this . topicType = topicType ; } public static String cleanSymbol ( String symbol ) { String result = symbol ; result = result . replaceAll ( "" , "" ) ; result = result . replaceAll ( "" , "" ) ; result = result . replaceAll ( "" , "" ) ; return result ; } public String getFile ( ) { return file ; } public void setFile ( String file ) { this . file = file ; } } package net . sf . sveditor . core . docs . model ; public enum DocItemType { PACKAGE , CLASS , TASK , FUNC , VARDECL , TOPIC , PACKAGESECTION , FILE , GENERAL } package net . sf . sveditor . core . docs . model ; import java . io . IOException ; import java . io . Writer ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SymbolTable { private LogHandle fLog ; private Map < String , SymbolTableEntry > fSymbolTable ; public SymbolTable ( ) { fLog = LogFactory . getLogHandle ( "" ) ; fSymbolTable = new HashMap < String , SymbolTableEntry > ( ) ; } public void addSymbol ( SymbolTableEntry symbol ) { if ( fSymbolTable . containsKey ( symbol . getSymbol ( ) ) ) { fLog . error ( String . format ( "" , symbol . getSymbol ( ) ) ) ; } else { fSymbolTable . put ( symbol . getSymbol ( ) , symbol ) ; } } public Set < String > getSymbolSet ( ) { return fSymbolTable . keySet ( ) ; } public void dumpSymbols ( ) { fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; List < String > sortedSymbols = new ArrayList < String > ( getSymbolSet ( ) ) ; Collections . sort ( sortedSymbols , String . CASE_INSENSITIVE_ORDER ) ; for ( String symbol : sortedSymbols ) { fLog . debug ( ILogLevel . LEVEL_MID , "" + symbol ) ; } fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; } public void dumpSymbolsToFile ( Writer writer ) throws IOException { writer . write ( "" ) ; writer . write ( "" ) ; writer . write ( "" ) ; List < String > sortedSymbols = new ArrayList < String > ( getSymbolSet ( ) ) ; Collections . sort ( sortedSymbols , String . CASE_INSENSITIVE_ORDER ) ; for ( String symbol : sortedSymbols ) { writer . write ( String . format ( "" , symbol ) ) ; writer . write ( String . format ( "" , fSymbolTable . get ( symbol ) . isDocumented ( ) ) ) ; writer . write ( String . format ( "" , fSymbolTable . get ( symbol ) . getTopicType ( ) ) ) ; writer . write ( String . format ( "" , fSymbolTable . get ( symbol ) . getSymbolType ( ) ) ) ; } writer . write ( "" ) ; } public SymbolTableEntry getSymbol ( String symbol ) { return fSymbolTable . get ( symbol ) ; } public boolean symbolIsValid ( String symbol ) { return fSymbolTable . containsKey ( symbol ) ; } public SymbolTableEntry resolveSymbol ( DocTopic docTopic , String symbol ) { fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , symbol , docTopic . getQualifiedName ( ) ) ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; String enclosingScope = docTopic . getQualifiedName ( ) ; SymbolTableEntry entry = null ; int safetyCount = ; while ( true ) { if ( enclosingScope == null ) { fLog . debug ( ILogLevel . LEVEL_MID , "" + symbol ) ; if ( fSymbolTable . containsKey ( symbol ) ) { entry = fSymbolTable . get ( symbol ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , symbol ) ) ; break ; } else { fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; break ; } } else { String trySymbol = enclosingScope + "" + symbol ; fLog . debug ( ILogLevel . LEVEL_MID , "" + trySymbol ) ; if ( fSymbolTable . containsKey ( trySymbol ) ) { entry = fSymbolTable . get ( trySymbol ) ; fLog . debug ( ILogLevel . LEVEL_MID , String . format ( "" , trySymbol ) ) ; break ; } int index = enclosingScope . lastIndexOf ( "" ) ; if ( index != - ) { enclosingScope = enclosingScope . substring ( , index ) ; } else { enclosingScope = null ; } } safetyCount ++ ; if ( safetyCount >= ) { fLog . error ( String . format ( "" , symbol , docTopic . getQualifiedName ( ) ) ) ; break ; } } fLog . debug ( ILogLevel . LEVEL_MID , "" ) ; return entry ; } } package net . sf . sveditor . core . docs . model ; public interface IDocTopic { } package net . sf . sveditor . core . docs . model ; import java . io . File ; public class DocFile extends DocTopic { String fDocPath ; String fPageTitle ; String fOutPath ; public DocFile ( String name ) { super ( name , "" , "" ) ; setDocFile ( this ) ; } public void setOutPath ( String path ) { fOutPath = path ; } public String getOutPath ( ) { return fOutPath ; } public String getSrcFileName ( ) { File file = new File ( fDocPath ) ; return file . getName ( ) ; } public void setDocPath ( String path ) { fDocPath = path ; } public String getDocPath ( ) { return fDocPath ; } public String getPageTitle ( ) { return fPageTitle ; } public void setPageTitle ( String pageTitle ) { fPageTitle = pageTitle ; } } package net . sf . sveditor . core . docs ; public class DocKeywordInfo { private String keyword ; private boolean isPlural ; private DocTopicType topicType ; public DocKeywordInfo ( String keyword , DocTopicType topicType , boolean isPlural ) { this . keyword = keyword ; this . topicType = topicType ; this . isPlural = isPlural ; } public String getKeyword ( ) { return keyword ; } public void setKeyword ( String keyword ) { this . keyword = keyword ; } public boolean isPlural ( ) { return isPlural ; } public void setPlural ( boolean isPlural ) { this . isPlural = isPlural ; } public DocTopicType getTopicType ( ) { return topicType ; } public void setTopicType ( DocTopicType topicType ) { this . topicType = topicType ; } } package net . sf . sveditor . core . docs ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class DocCommentCleaner { public static String TAB_EXPANSION = "" ; private enum Uniformity { DONT_KNOW , IS_UNIFORM , IS_UNIFORM_IF_AT_END , IS_NOT_UNIFORM } ; private static LogHandle fLog ; private static boolean fDebugEn = false ; private static Pattern fLeftVerticalLineStripPattern ; private static Pattern fRightVerticalLineStripPattern ; static { fLog = LogFactory . getLogHandle ( "" ) ; fLeftVerticalLineStripPattern = Pattern . compile ( "" ) ; fRightVerticalLineStripPattern = Pattern . compile ( "" ) ; } public static void clean ( String [ ] lines ) { Uniformity leftSide = Uniformity . DONT_KNOW ; Uniformity rightSide = Uniformity . DONT_KNOW ; int leftSideChar = - ; int rightSideChar = - ; int index = ; boolean inCodeSection = false ; while ( index < lines . length ) { lines [ index ] = lines [ index ] . replaceAll ( "" , "" ) ; lines [ index ] = lines [ index ] . replaceAll ( "" , TAB_EXPANSION ) ; String line = lines [ index ] ; line = line . trim ( ) ; if ( fDebugEn ) { fLog . debug ( "" + line ) ; fLog . debug ( "" + leftSide + "" + rightSide ) ; fLog . debug ( "" + ( ( leftSideChar != - ) ? ( char ) leftSideChar : "" ) + "" + ( ( rightSideChar != - ) ? ( char ) rightSideChar : "" ) ) ; } if ( line . length ( ) == ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } if ( leftSide == Uniformity . IS_UNIFORM ) { leftSide = Uniformity . IS_UNIFORM_IF_AT_END ; if ( fDebugEn ) { fLog . debug ( "" + leftSide ) ; } } if ( rightSide == Uniformity . IS_UNIFORM ) { rightSide = Uniformity . IS_UNIFORM_IF_AT_END ; if ( fDebugEn ) { fLog . debug ( "" + rightSide ) ; } } } else if ( line . matches ( "" ) || ( ( line . length ( ) < ) && line . matches ( "" ) ) ) { if ( fDebugEn ) { fLog . debug ( "" ) ; } } else { if ( fDebugEn ) { fLog . debug ( "" ) ; } if ( leftSide == Uniformity . IS_UNIFORM_IF_AT_END ) { leftSide = Uniformity . IS_NOT_UNIFORM ; if ( fDebugEn ) { fLog . debug ( "" + leftSide ) ; } } if ( rightSide == Uniformity . IS_UNIFORM_IF_AT_END ) { rightSide = Uniformity . IS_NOT_UNIFORM ; if ( fDebugEn ) { fLog . debug ( "" + rightSide ) ; } } if ( leftSide != Uniformity . IS_NOT_UNIFORM ) { Pattern p = Pattern . compile ( "" ) ; Matcher m = p . matcher ( line ) ; if ( m . matches ( ) ) { int g1_char = m . group ( ) . charAt ( ) ; if ( leftSide == Uniformity . DONT_KNOW ) { leftSide = Uniformity . IS_UNIFORM ; leftSideChar = g1_char ; } else { if ( leftSideChar != g1_char ) { leftSide = Uniformity . IS_NOT_UNIFORM ; } } } else if ( index != ) { leftSide = Uniformity . IS_NOT_UNIFORM ; } } if ( rightSide != Uniformity . IS_NOT_UNIFORM ) { Pattern p = Pattern . compile ( "" ) ; Matcher m = p . matcher ( line ) ; if ( m . matches ( ) ) { int g1_char = m . group ( ) . charAt ( ) ; if ( rightSide == Uniformity . DONT_KNOW ) { rightSide = Uniformity . IS_UNIFORM ; rightSideChar = g1_char ; } else { if ( rightSideChar != g1_char ) { rightSide = Uniformity . IS_NOT_UNIFORM ; } } } else { rightSide = Uniformity . IS_NOT_UNIFORM ; } } } index ++ ; } if ( leftSide == Uniformity . IS_UNIFORM_IF_AT_END ) { leftSide = Uniformity . IS_UNIFORM ; } if ( rightSide == Uniformity . IS_UNIFORM_IF_AT_END ) { rightSide = Uniformity . IS_UNIFORM ; } index = ; inCodeSection = false ; while ( index < lines . length ) { if ( lines [ index ] . matches ( "" ) || ( lines [ index ] . length ( ) < && lines [ index ] . matches ( "" ) ) ) { if ( ! inCodeSection ) { lines [ index ] = "" ; } } else { if ( leftSide == Uniformity . IS_UNIFORM ) { if ( fDebugEn ) { fLog . debug ( "" + lines [ index ] ) ; } Matcher m = fLeftVerticalLineStripPattern . matcher ( lines [ index ] ) ; if ( fDebugEn ) { if ( m . matches ( ) ) { fLog . debug ( "" + m . matches ( ) + "" + m . group ( ) ) ; } else { fLog . debug ( "" + m . matches ( ) ) ; } } lines [ index ] = m . replaceFirst ( "" ) ; if ( fDebugEn ) { fLog . debug ( "" + lines [ index ] ) ; } } if ( rightSide == Uniformity . IS_UNIFORM ) { Matcher m = fRightVerticalLineStripPattern . matcher ( lines [ index ] ) ; lines [ index ] = m . replaceFirst ( "" ) ; } if ( ( leftSide == Uniformity . IS_UNIFORM || rightSide == Uniformity . IS_UNIFORM ) && ! inCodeSection ) { lines [ index ] . replace ( "" , "" ) ; lines [ index ] . replace ( "" , "" ) ; } Pattern patternCodeStart = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE ) ; Pattern patternCodeEnd = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE ) ; if ( ! inCodeSection && patternCodeStart . matcher ( lines [ index ] ) . matches ( ) ) { inCodeSection = true ; } else if ( inCodeSection && patternCodeEnd . matcher ( lines [ index ] ) . matches ( ) ) { inCodeSection = false ; } } index ++ ; } } public static String [ ] splitCommentIntoLines ( String comment ) { String lines [ ] = comment . split ( "" ) ; return lines ; } } package net . sf . sveditor . core . docs ; public class DocTopicType { public enum ScopeType { NORMAL , START , END , ALWAYS_GLOBAL } ; private String name ; private String pluralName ; private boolean index ; private boolean pageTitleIfFirst ; private boolean breakLists ; private ScopeType scopeType ; public DocTopicType ( String name , String pluralName , ScopeType scopeType , boolean index , boolean pageTitleIfFirst , boolean breakLists ) { this . name = name ; this . pluralName = pluralName ; this . scopeType = scopeType ; this . index = index ; this . pageTitleIfFirst = pageTitleIfFirst ; this . breakLists = breakLists ; } public String getName ( ) { return name ; } public String getNameCapitalized ( ) { return name . substring ( , ) . toUpperCase ( ) + name . substring ( ) . toLowerCase ( ) ; } public void setName ( String name ) { this . name = name ; } public String getPluralName ( ) { return pluralName ; } public String getPluralNameCapitalized ( ) { return pluralName . substring ( , ) . toUpperCase ( ) + pluralName . substring ( ) . toLowerCase ( ) ; } public ScopeType getScopeType ( ) { return scopeType ; } public void setPluralName ( String pluralName ) { this . pluralName = pluralName ; } public boolean isIndex ( ) { return index ; } public void setIndex ( boolean index ) { this . index = index ; } public boolean isPageTitleIfFirst ( ) { return pageTitleIfFirst ; } public void setPageTitleIfFirst ( boolean pageTitleIfFirst ) { this . pageTitleIfFirst = pageTitleIfFirst ; } public boolean isBreakLists ( ) { return breakLists ; } public void setBreakLists ( boolean breakLists ) { this . breakLists = breakLists ; } } package net . sf . sveditor . core . docs . html ; import java . io . File ; import net . sf . sveditor . core . docs . DocGenConfig ; import net . sf . sveditor . core . docs . model . DocFile ; import net . sf . sveditor . core . docs . model . DocModel ; import net . sf . sveditor . core . docs . model . DocTopic ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class HTMLFileFactory { private DocGenConfig cfg ; private DocModel model ; @ SuppressWarnings ( "" ) private LogHandle fLog ; private HTMLFromNDMarkup fMarkupToHTML ; public HTMLFileFactory ( DocGenConfig cfg , DocModel model ) { this . cfg = cfg ; this . model = model ; fLog = LogFactory . getLogHandle ( "" ) ; fMarkupToHTML = new HTMLFromNDMarkup ( this . model ) ; } public static String getRelPathToHTML ( String path ) { String res = "" ; File filePath = new File ( path ) ; int numParents = ; while ( filePath . getParentFile ( ) != null ) { numParents ++ ; filePath = filePath . getParentFile ( ) ; } for ( int i = ; i < numParents ; i ++ ) { res += "" ; } return res ; } public String build ( DocFile docFile ) { String res = HTMLUtils . STR_DOCTYPE ; res += HTMLUtils . genHTMLHeadStart ( getRelPathToHTML ( docFile . getTitle ( ) ) , docFile . getPageTitle ( ) ) ; res += HTMLUtils . genBodyBegin ( "" ) ; res += HTMLUtils . genContentBegin ( ) ; res += genContent ( docFile ) ; res += HTMLUtils . genContentEnd ( ) ; res += HTMLUtils . genFooter ( ) ; res += HTMLUtils . genMenu ( cfg , getRelPathToHTML ( docFile . getTitle ( ) ) , docFile . getPageTitle ( ) , model . getDocTopics ( ) . getAllTopicTypes ( ) ) ; res += HTMLUtils . genBodyHTMLEnd ( ) ; return res ; } private String genSummaryStart ( DocFile docFile , DocTopic docItem ) { String result = "" ; result += fMarkupToHTML . convertNDMarkupToHTML ( docFile , docItem , docItem . getBody ( ) , HTMLFromNDMarkup . NDMarkupToHTMLStyle . General ) ; return result ; } private String genMemberDetail ( DocFile docFile , DocTopic docTopic ) { String res = "" ; for ( DocTopic child : docTopic . getChildren ( ) ) { res += genDetails ( docFile , docTopic , child ) ; } return res ; } private String genSTRMain ( DocFile docFile , DocTopic topic ) { String res = "" ; if ( topic . getTopic ( ) . equals ( "" ) ) { res += "" + "" + topic . getQualifiedName ( ) + "" + topic . getTitle ( ) + "" + "" + "" ; } else { res += "" + "" + "" + getRelPathToHTML ( topic . getDocFile ( ) . getTitle ( ) ) + HTMLIconUtils . getImagePath ( topic ) + ">" + "" + "" + topic . getTitle ( ) + "" + topic . getTitle ( ) + "" + "" ; res += topic . getSummary ( ) ; res += "" ; } return res ; } private String genTopicStart ( DocTopic contentItem ) { String res = "" + HTMLUtils . genCSSClassForTopic ( contentItem . getTopic ( ) ) + "" ; return res ; } private String genClassEnd ( ) { String res = "" ; return res ; } private String genContent ( DocFile docFile ) { String res = "" ; if ( docFile . getChildren ( ) . size ( ) > ) { res += genFileSummary ( docFile ) ; } for ( DocTopic contentItem : docFile . getChildren ( ) ) { if ( ! contentItem . getTopic ( ) . equals ( "" ) ) { res += genContent ( docFile , contentItem ) ; } } return res ; } private String genContent ( DocFile docFile , DocTopic contentItem ) { String res = "" ; res += genTopicStart ( contentItem ) ; res += HTMLUtils . genCTopicBegin ( "" ) ; res += HTMLUtils . genCTitle ( contentItem . getTitle ( ) ) ; res += HTMLUtils . genCBodyBegin ( ) ; res += genSummaryStart ( docFile , contentItem ) ; res += HTMLUtils . genSummaryBegin ( ) ; res += HTMLUtils . genSTitle ( ) ; res += HTMLUtils . genSBorderBegin ( ) ; res += HTMLUtils . genSTableBegin ( ) ; res += genSTRMain ( docFile , contentItem ) ; res += genSummaryMembers ( docFile , contentItem ) ; res += HTMLUtils . genSTableEnd ( ) ; res += HTMLUtils . genSBorderEnd ( ) ; res += HTMLUtils . genSummaryEnd ( ) ; res += HTMLUtils . genCBodyEnd ( ) ; res += HTMLUtils . genCTopicEnd ( ) ; res += genClassEnd ( ) ; res += genMemberDetail ( docFile , contentItem ) ; return res ; } private String genFileSummary ( DocFile docFile ) { String res = "" ; res += genSummaryStart ( docFile , docFile ) ; res += HTMLUtils . genCTopicBegin ( "" ) ; res += HTMLUtils . genCTitle ( docFile . getPageTitle ( ) ) ; res += HTMLUtils . genCBodyBegin ( ) ; res += HTMLUtils . genSummaryBegin ( ) ; res += HTMLUtils . genSTitle ( ) ; res += HTMLUtils . genSBorderBegin ( ) ; res += HTMLUtils . genSTableBegin ( ) ; for ( DocTopic docItem : docFile . getChildren ( ) ) { res += genSTRMain ( docFile , docItem ) ; res += genSummaryMembers ( docFile , docItem ) ; } res += HTMLUtils . genSTableEnd ( ) ; res += HTMLUtils . genSBorderEnd ( ) ; res += HTMLUtils . genSummaryEnd ( ) ; res += HTMLUtils . genCBodyEnd ( ) ; res += HTMLUtils . genCTopicEnd ( ) ; return res ; } private String genSummaryMembers ( DocFile docFile , DocTopic docTopic ) { String res = "" ; boolean marked = false ; for ( DocTopic child : docTopic . getChildren ( ) ) { res += genSummaryForMemember ( docFile , docTopic , child , marked ) ; marked = ! marked ; } return res ; } private String genSummaryForMemember ( DocFile docFile , DocTopic parent , DocTopic topic , boolean marked ) { String res = "" ; if ( topic . getTopic ( ) . equals ( "" ) ) { res += "" + HTMLUtils . genCSSClassForTopicInSummary ( topic . getTopic ( ) ) ; if ( marked ) { res += "" ; } res += "" + "" + "" + "" + topic . getQualifiedName ( ) + "" + topic . getTitle ( ) + "" + "" + "" ; } else { res += "" + HTMLUtils . genCSSClassForTopicInSummary ( topic . getTopic ( ) ) ; if ( marked ) { res += "" ; } res += "" + "" + "" + getRelPathToHTML ( docFile . getTitle ( ) ) + HTMLIconUtils . getImagePath ( topic ) + ">" + "" + "" + "" + topic . getQualifiedName ( ) + "" + topic . getTitle ( ) + "" + "" + "" + topic . getSummary ( ) + "" + "" ; } return res ; } private String genDetails ( DocFile docFile , DocTopic parent , DocTopic child ) { String res = "" + HTMLUtils . genCSSClassForTopic ( child . getTopic ( ) ) + ">" + "" + "" + "" + child . getQualifiedName ( ) + "" + child . getTitle ( ) + "" + "" ; res += fMarkupToHTML . convertNDMarkupToHTML ( docFile , child , child . getBody ( ) , HTMLFromNDMarkup . NDMarkupToHTMLStyle . General ) ; res += "" + "" + "" ; return res ; } } package net . sf . sveditor . core . docs . html ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . util . Enumeration ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . docs . DocGenConfig ; import net . sf . sveditor . core . docs . DocTopicType ; import net . sf . sveditor . core . docs . IDocWriter ; import net . sf . sveditor . core . docs . model . DocFile ; import net . sf . sveditor . core . docs . model . DocModel ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . osgi . framework . Bundle ; public class HTMLDocWriter implements IDocWriter { private File indexHtmFile ; private class HTMLDocWriterException extends Exception { private static final long serialVersionUID = ; public HTMLDocWriterException ( String msg ) { super ( msg ) ; } @ SuppressWarnings ( "" ) public HTMLDocWriterException ( Exception e ) { super ( e ) ; } } LogHandle fLog ; public HTMLDocWriter ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } public void write ( DocGenConfig cfg , DocModel model ) { try { sanityCheck ( cfg , model ) ; fLog . debug ( ILogLevel . LEVEL_MIN , "" + cfg . getOutputDir ( ) ) ; buildDirTree ( cfg , model ) ; assignOutPaths ( cfg , model ) ; writeFiles ( cfg , model ) ; writeIndices ( cfg , model ) ; } catch ( Exception e ) { fLog . error ( "" , e ) ; } } private void assignOutPaths ( DocGenConfig cfg , DocModel model ) { for ( String file : model . getFileSet ( ) ) { DocFile docFile = model . getDocFile ( file ) ; String srcPath = docFile . getDocPath ( ) ; File outPath = HTMLUtils . getHTMLFileForSrcPath ( cfg , srcPath ) ; docFile . setOutPath ( outPath . toString ( ) ) ; } } private void writeFiles ( DocGenConfig cfg , DocModel model ) throws IOException { for ( String file : model . getFileSet ( ) ) { DocFile docFile = model . getDocFile ( file ) ; writeFile ( cfg , model , docFile ) ; } } private void writeFile ( DocGenConfig cfg , DocModel model , DocFile docFile ) { HTMLFileFactory fileFactory = new HTMLFileFactory ( cfg , model ) ; File outPath = new File ( docFile . getOutPath ( ) ) ; if ( ! outPath . getParentFile ( ) . exists ( ) ) outPath . getParentFile ( ) . mkdirs ( ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" + outPath ) ; FileOutputStream os ; try { os = new FileOutputStream ( outPath ) ; String fileContent = fileFactory . build ( docFile ) ; if ( fileContent == null || fileContent . isEmpty ( ) ) { fLog . error ( "" + docFile . getTitle ( ) ) ; } os . write ( fileContent . getBytes ( ) ) ; os . close ( ) ; } catch ( Exception e ) { fLog . error ( "" + outPath , e ) ; } } private void writeIndices ( DocGenConfig cfg , DocModel model ) throws IOException { for ( DocTopicType docTopicType : model . getDocTopics ( ) . getAllTopicTypes ( ) ) { if ( docTopicType . isIndex ( ) ) { writeIndex ( cfg , model , docTopicType ) ; } } } private void writeIndex ( DocGenConfig cfg , DocModel model , DocTopicType docTopicType ) throws IOException { HTMLIndexFactory indexFactory = new HTMLIndexFactory ( cfg , docTopicType ) ; String topicName = docTopicType . getName ( ) ; File indexFile = HTMLUtils . getHTMLFileForIndexOfTopic ( cfg , docTopicType . getPluralName ( ) ) ; fLog . debug ( ILogLevel . LEVEL_MIN , String . format ( "" , topicName , indexFile . toString ( ) ) ) ; indexHtmFile = indexFile ; if ( ! indexFile . getParentFile ( ) . exists ( ) ) indexFile . getParentFile ( ) . mkdirs ( ) ; FileOutputStream os ; os = new FileOutputStream ( indexFile ) ; os . write ( indexFactory . build ( model ) . getBytes ( ) ) ; os . close ( ) ; } private void sanityCheck ( DocGenConfig cfg , DocModel model ) throws HTMLDocWriterException { if ( cfg == null ) throw new HTMLDocWriterException ( "" ) ; if ( model == null ) throw new HTMLDocWriterException ( "" ) ; File outputDir = cfg . getOutputDir ( ) ; if ( outputDir . toString ( ) . isEmpty ( ) ) throw new HTMLDocWriterException ( "" ) ; } private void buildDirTree ( DocGenConfig cfg , DocModel model ) throws Exception { fLog . debug ( ILogLevel . LEVEL_MIN , "" ) ; copyBundleDirToFS ( "" , cfg . getOutputDir ( ) ) ; } public void copyBundleDirToFS ( String srcBundlePath , File dstFSPathRoot ) throws HTMLDocWriterException { Bundle bundle = SVCorePlugin . getDefault ( ) . getBundle ( ) ; byte buffer [ ] = new byte [ * ] ; Enumeration < URL > entries = bundle . findEntries ( srcBundlePath , "" , true ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" + srcBundlePath ) ; while ( entries . hasMoreElements ( ) ) { URL url = ( URL ) entries . nextElement ( ) ; if ( url . getPath ( ) . endsWith ( "" ) ) { continue ; } String fileSubPath = url . getPath ( ) ; File target = new File ( dstFSPathRoot , fileSubPath ) ; fLog . debug ( ILogLevel . LEVEL_MID , "" + fileSubPath ) ; if ( ! target . getParentFile ( ) . exists ( ) ) { if ( ! target . getParentFile ( ) . mkdirs ( ) ) { throw new HTMLDocWriterException ( "" + target . getParent ( ) + "" ) ; } } try { FileOutputStream out = new FileOutputStream ( target ) ; InputStream in = url . openStream ( ) ; int len ; do { len = in . read ( buffer , , buffer . length ) ; if ( len > ) { out . write ( buffer , , len ) ; } } while ( len > ) ; out . close ( ) ; in . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "" + target ) ; } } } public File getIndexHTML ( DocGenConfig cfg , DocModel model ) { return indexHtmFile ; } } package net . sf . sveditor . core . docs . html ; public interface IHTMLIcons { String OBJ_ICONS = "" ; String MODULE_OBJ = OBJ_ICONS + "" ; String INT_OBJ = OBJ_ICONS + "" ; String CLASS_OBJ = OBJ_ICONS + "" ; String DEFINE_OBJ = OBJ_ICONS + "" ; String INCLUDE_OBJ = OBJ_ICONS + "" ; String PACKAGE_OBJ = OBJ_ICONS + "" ; String STRUCT_OBJ = OBJ_ICONS + "" ; String MOD_IFC_INST_OBJ = OBJ_ICONS + "" ; String LOCAL_OBJ = OBJ_ICONS + "" ; String ENUM_TYPE_OBJ = OBJ_ICONS + "" ; String TYPEDEF_TYPE_OBJ = OBJ_ICONS + "" ; String DECL_ICONS = "" ; String FIELD_PRIV_OBJ = DECL_ICONS + "" ; String FIELD_PROT_OBJ = DECL_ICONS + "" ; String FIELD_PUB_OBJ = DECL_ICONS + "" ; String TASK_PRIV_OBJ = DECL_ICONS + "" ; String TASK_PROT_OBJ = DECL_ICONS + "" ; String TASK_PUB_OBJ = DECL_ICONS + "" ; } package net . sf . sveditor . core . docs . html ; import java . io . File ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . List ; import net . sf . sveditor . core . docs . DocGenConfig ; import net . sf . sveditor . core . docs . DocTopicType ; public class HTMLUtils { static final String STR_DOCTYPE = "" + "" + "" ; static String genHTMLHeadStart ( String relPathToHTML , String title ) { String result = "" + "" + "" + title + "" + "" + "" + relPathToHTML + "" + "" + relPathToHTML + "" + "" + relPathToHTML + "" + "" + relPathToHTML + "" + "" ; return result ; } static String genBodyBegin ( String bodyClass ) { String result = "" + bodyClass + "" + "" + "" + "" + "" + "" + "" ; return result ; } static String genFooter ( ) { String result = "" ; return result ; } static String genBodyHTMLEnd ( ) { String result = "" + "" + "" ; return result ; } static String genContentBegin ( ) { String result = "" ; return result ; } static String genContentEnd ( ) { return genDivEnd ( ) ; } static String genCTopicBegin ( String topicID ) { String result = "" + topicID + ">" ; return result ; } static String genCTopicEnd ( ) { return genDivEnd ( ) ; } static String genCTitle ( String name ) { String result = "" + name + "" + name + "" ; return result ; } static String genCBodyBegin ( ) { String result = "" ; return result ; } static String genCBodyEnd ( ) { return genDivEnd ( ) ; } static String genSummaryBegin ( ) { String result = "" ; return result ; } static String genSummaryEnd ( ) { return genDivEnd ( ) ; } static String genSTitle ( ) { String result = "" ; return result ; } static String genSBorderBegin ( ) { String result = "" ; return result ; } static String genSBorderEnd ( ) { return genDivEnd ( ) ; } static String genSTableBegin ( ) { String result = "" ; return result ; } static String genSTableEnd ( ) { return genTableEnd ( ) ; } static String genDivEnd ( ) { String result = "" ; return result ; } static String genTableEnd ( ) { String result = "" ; return result ; } static String genCSSClassForTopic ( String topicName ) { String c = "" ; if ( topicName == null || topicName . length ( ) < ) { return "" ; } c += capitalize ( topicName ) ; return c ; } static String capitalize ( String in ) { String out = "" ; out = out + in . substring ( , ) . toUpperCase ( ) ; out = out + in . substring ( ) . toLowerCase ( ) ; return out ; } static String genCSSClassForTopicInSummary ( String topicName ) { String c = "" ; if ( topicName == null || topicName . length ( ) < ) { return "" ; } c += capitalize ( topicName ) ; return c ; } static String genMenu ( DocGenConfig cfg , String relPathToHTML , String title , Collection < DocTopicType > docTopicTypes ) { String res = "" + "" + "" + title + "" + "" + "" + "" + "" ; for ( DocTopicType docTopicType : docTopicTypes ) { if ( ! docTopicType . isIndex ( ) ) continue ; res += "" + "" + relPathToHTML + "" + getHTMLRelPathForIndexOfTopic ( cfg , docTopicType . getPluralName ( ) ) + "" + docTopicType . getPluralNameCapitalized ( ) + "" + "" ; } res += "" + "" + "" + "" + "" + "" + "" ; return res ; } public static File getHTMLFileForIndexOfTopic ( DocGenConfig cfg , String topicName ) { return new File ( HTMLUtils . getHTMLDir ( cfg ) , getHTMLRelPathForIndexOfTopic ( cfg , topicName ) . toString ( ) ) ; } public static File getHTMLRelPathForIndexOfTopic ( DocGenConfig cfg , String topicNamePlural ) { String topicFileName = topicNamePlural . substring ( , ) . toUpperCase ( ) + topicNamePlural . substring ( ) . toLowerCase ( ) + "" ; File htmlRelIndexFile = new File ( new File ( "" ) , topicFileName ) ; return htmlRelIndexFile ; } public static File getHTMLFileForClass ( DocGenConfig cfg , String pkgName , String className ) { return new File ( getPkgClassDir ( cfg , pkgName ) , className + "" ) ; } public static File getHTMLDir ( DocGenConfig cfg ) { return new File ( cfg . getOutputDir ( ) , "" ) ; } public static File getFilesDir ( DocGenConfig cfg ) { return new File ( getHTMLDir ( cfg ) , "" ) ; } public static File getPkgClassDir ( DocGenConfig cfg , String pkgName ) { return new File ( getClassesDir ( cfg ) , pkgName ) ; } public static File getClassesDir ( DocGenConfig cfg ) { return new File ( getHTMLDir ( cfg ) , "" ) ; } public static File getStylesDir ( DocGenConfig cfg ) { return new File ( getHTMLDir ( cfg ) , "" ) ; } public static File getScriptsDir ( DocGenConfig cfg ) { return new File ( getHTMLDir ( cfg ) , "" ) ; } public static File getHTMLFileForSrcPath ( DocGenConfig cfg , String srcPath ) { return new File ( getFilesDir ( cfg ) , srcPath + "" ) ; } public static String restoreAmpChars ( String text ) { text = text . replaceAll ( "" , "" ) ; text = text . replaceAll ( "" , ">" ) ; text = text . replaceAll ( "" , "" ) ; text = text . replaceAll ( "" , "" ) ; return text ; } public static String makeRelativeURL ( String basePath , String targetPath , boolean baseHasFileName ) { String ret = "" ; File baseFile = new File ( basePath ) ; File targetFile = new File ( targetPath ) ; if ( baseHasFileName ) { baseFile = baseFile . getParentFile ( ) ; } List < String > baseDirs = new ArrayList < String > ( Arrays . asList ( baseFile . toString ( ) . split ( "" ) ) ) ; List < String > targetDirs = new ArrayList < String > ( Arrays . asList ( targetFile . toString ( ) . split ( "" ) ) ) ; int idx = ; while ( idx < baseDirs . size ( ) && idx < targetDirs . size ( ) && baseDirs . get ( idx ) . equals ( targetDirs . get ( idx ) ) ) { idx ++ ; } ; baseDirs = baseDirs . subList ( idx , baseDirs . size ( ) ) ; targetDirs = targetDirs . subList ( idx , targetDirs . size ( ) ) ; for ( idx = ; idx < baseDirs . size ( ) ; idx ++ ) { targetDirs . add ( , "" ) ; } ; for ( idx = ; idx < targetDirs . size ( ) ; idx ++ ) { ret += targetDirs . get ( idx ) ; if ( targetDirs . size ( ) > && idx < ( targetDirs . size ( ) - ) ) { ret += "" ; } } return ret ; } } package net . sf . sveditor . core . docs . html ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . docs . DocGenConfig ; import net . sf . sveditor . core . docs . DocTopicType ; import net . sf . sveditor . core . docs . model . DocIndex ; import net . sf . sveditor . core . docs . model . DocTopic ; import net . sf . sveditor . core . docs . model . DocModel ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; @ SuppressWarnings ( "" ) public class HTMLIndexFactory { private DocGenConfig cfg ; private DocTopicType docTopicType ; private LogHandle fLog ; String fIndexNameCapitalized ; private int ttID = ; private int linkID = ; private HashMap < String , String > ttDescriptions ; public HTMLIndexFactory ( DocGenConfig cfg , DocTopicType docTopicType ) { this . cfg = cfg ; this . docTopicType = docTopicType ; fLog = LogFactory . getLogHandle ( "" ) ; fIndexNameCapitalized = docTopicType . getNameCapitalized ( ) + "" ; ttDescriptions = new HashMap < String , String > ( ) ; } public String build ( DocModel model ) { fLog . debug ( ILogLevel . LEVEL_MIN , String . format ( "" , docTopicType . getName ( ) ) ) ; String res = HTMLUtils . STR_DOCTYPE ; res += HTMLUtils . genHTMLHeadStart ( "" , fIndexNameCapitalized ) ; res += HTMLUtils . genBodyBegin ( "" ) ; res += genIndex ( "" , model ) ; res += HTMLUtils . genFooter ( ) ; res += HTMLUtils . genMenu ( cfg , "" , fIndexNameCapitalized , model . getDocTopics ( ) . getAllTopicTypes ( ) ) ; res += HTMLUtils . genBodyHTMLEnd ( ) ; return res ; } private String genIndex ( String relPathToHTML , DocModel model ) { DocIndex idxMap = model . getTopicIndexMap ( docTopicType . getName ( ) . toLowerCase ( ) ) ; if ( idxMap == null ) { return "" ; } String res = "" + "" + fIndexNameCapitalized + "" + "" ; boolean first = true ; ArrayList < String > sortedIdxKeys = new ArrayList < String > ( idxMap . getMap ( ) . keySet ( ) ) ; Collections . sort ( sortedIdxKeys ) ; for ( String idxKey : sortedIdxKeys ) { if ( ! first ) { res += "" ; } else { first = false ; } if ( idxMap . getMap ( ) . get ( idxKey ) . size ( ) == ) { res += idxKey ; } else { res += "" + idxKey . toUpperCase ( ) + "" + idxKey . toUpperCase ( ) + "" ; } } res += "" + "" ; for ( String idxKey : sortedIdxKeys ) { if ( idxMap . getMap ( ) . get ( idxKey ) . size ( ) == ) { continue ; } res += "" + "" + "" + idxKey + "" + idxKey + "" + "" ; ArrayList < DocTopic > entries = new ArrayList < DocTopic > ( idxMap . getMap ( ) . get ( idxKey ) ) ; Collections . sort ( entries , new Comparator < DocTopic > ( ) { public int compare ( DocTopic o1 , DocTopic o2 ) { return ( o1 . getTitle ( ) + "" + o1 . getQualifiedName ( ) ) . compareToIgnoreCase ( ( o2 . getTitle ( ) + "" + o2 . getQualifiedName ( ) ) ) ; } } ) ; for ( DocTopic entry : entries ) { String linkID = getNextLinkID ( ) ; String ttID = getNextTTID ( ) ; res += "" + "" + "" + relPathToHTML + "" + entry . getDocFile ( ) . getDocPath ( ) + "" + "" + entry . getQualifiedName ( ) + "" + "" + linkID + "" + ttID + "" + linkID + "" + "" + ttID + "" + "" + entry . getTitle ( ) + "" + "" + "" + entry . getQualifiedName ( ) + "" + "" ; ttDescriptions . put ( ttID , entry . getSummary ( ) ) ; } } res += "" ; res += genToolTips ( ) ; res += "" ; return res ; } private String genToolTips ( ) { String res = "" ; for ( String ttid : ttDescriptions . keySet ( ) ) { res += "" + ttid + "" + "" + ttDescriptions . get ( ttid ) + "" + "" ; } return res ; } private String getNextTTID ( ) { ttID += ; return "" + ttID ; } private String getNextLinkID ( ) { linkID += ; return "" + linkID ; } } package net . sf . sveditor . core . docs . html ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . db . IFieldItemAttr ; import net . sf . sveditor . core . docs . DocTopicManager ; import net . sf . sveditor . core . docs . model . DocTopic ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class HTMLIconUtils implements IHTMLIcons { private static final Map < String , String > fImgDescMap ; static { fImgDescMap = new HashMap < String , String > ( ) ; fImgDescMap . put ( DocTopicManager . TOPIC_CLASS , CLASS_OBJ ) ; fImgDescMap . put ( DocTopicManager . TOPIC_PACKAGE , PACKAGE_OBJ ) ; fImgDescMap . put ( DocTopicManager . TOPIC_TASK , TASK_PUB_OBJ ) ; fImgDescMap . put ( DocTopicManager . TOPIC_FUNCTION , TASK_PUB_OBJ ) ; } private static LogHandle log ; public static LogHandle getLog ( ) { if ( log == null ) { log = LogFactory . getLogHandle ( "" ) ; } return log ; } public static String getImagePath ( DocTopic docItem ) { if ( docItem . getTopic ( ) == DocTopicManager . TOPIC_VARIABLE ) { int attr = docItem . getAttr ( ) ; if ( ( attr & IFieldItemAttr . FieldAttr_Local ) != ) { return FIELD_PRIV_OBJ ; } else if ( ( attr & IFieldItemAttr . FieldAttr_Protected ) != ) { return FIELD_PROT_OBJ ; } else { return FIELD_PUB_OBJ ; } } else if ( docItem . getTopic ( ) == DocTopicManager . TOPIC_TASK ) { int attr = docItem . getAttr ( ) ; if ( ( attr & IFieldItemAttr . FieldAttr_Local ) != ) { return TASK_PRIV_OBJ ; } else if ( ( attr & IFieldItemAttr . FieldAttr_Protected ) != ) { return TASK_PROT_OBJ ; } else { return TASK_PUB_OBJ ; } } else { String topic = docItem . getTopic ( ) ; if ( fImgDescMap . containsKey ( topic ) ) { return fImgDescMap . get ( topic ) ; } } return null ; } } package net . sf . sveditor . core . docs . html ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import net . sf . sveditor . core . docs . model . DocFile ; import net . sf . sveditor . core . docs . model . DocModel ; import net . sf . sveditor . core . docs . model . DocTopic ; import net . sf . sveditor . core . docs . model . SymbolTableEntry ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class HTMLFromNDMarkup { private final static Pattern patternLink = Pattern . compile ( "" ) ; public enum NDMarkupToHTMLStyle { Tooltip , General } ; private DocModel fModel ; private LogHandle fLog ; public HTMLFromNDMarkup ( ) { this ( null ) ; } public HTMLFromNDMarkup ( DocModel model ) { fModel = model ; fLog = LogFactory . getLogHandle ( "" ) ; } @ SuppressWarnings ( "" ) public String convertNDMarkupToHTML ( DocFile docFile , DocTopic docTopic , String markup , NDMarkupToHTMLStyle style ) { String output = "" ; String splitText [ ] = markup . split ( "" ) ; int index = ; while ( index < splitText . length ) { String text = splitText [ index ] ; if ( false ) { } else if ( false ) { } else if ( false ) { } else { if ( false ) { } if ( style != NDMarkupToHTMLStyle . Tooltip ) { while ( true ) { Matcher matcher = patternLink . matcher ( text ) ; if ( matcher . find ( ) ) { String newText = "" ; if ( matcher . start ( ) != ) { newText += text . substring ( , matcher . start ( ) ) ; } newText += buildTextLink ( docFile , docTopic , matcher . group ( ) , matcher . group ( ) , matcher . group ( ) ) ; if ( ! matcher . hitEnd ( ) ) { newText += text . substring ( matcher . end ( ) ) ; } text = newText ; } else { break ; } } } else { Matcher matcher = patternLink . matcher ( text ) ; text = matcher . replaceAll ( "" ) ; } text = text . replaceAll ( "" , "" ) ; text = text . replaceAll ( "" , "" ) ; output += text ; } index ++ ; } return output ; } private String buildTextLink ( DocFile docFile , DocTopic docTopic , String target , String name , String original ) { String plainTarget = HTMLUtils . restoreAmpChars ( target ) ; String symbol = SymbolTableEntry . cleanSymbol ( plainTarget ) ; if ( fModel == null ) { fLog . error ( String . format ( "" ) ) ; return "" ; } SymbolTableEntry symbolTableEntry = fModel . getSymbolTable ( ) . resolveSymbol ( docTopic , symbol ) ; if ( symbolTableEntry == null ) { fLog . debug ( ILogLevel . LEVEL_MIN , String . format ( "" , symbol , docFile . getTitle ( ) ) ) ; return original ; } else if ( symbolTableEntry . getDocFile ( ) == null ) { fLog . debug ( ILogLevel . LEVEL_MIN , String . format ( "" , symbol , docFile . getTitle ( ) ) ) ; return original ; } else { String link ; String targetFile = null ; if ( symbolTableEntry . getDocFile ( ) != docFile ) { targetFile = HTMLUtils . makeRelativeURL ( docFile . getOutPath ( ) , symbolTableEntry . getDocFile ( ) . getOutPath ( ) , true ) ; } link = "" ; if ( targetFile != null ) { link += targetFile ; } link += "" + symbolTableEntry . getSymbol ( ) + "" ; link += "" + HTMLUtils . capitalize ( symbolTableEntry . getTopicType ( ) ) ; link += "" + name ; link += "" ; return link ; } } } package net . sf . sveditor . core . docs ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . docs . DocTopicType . ScopeType ; public class DocTopicManager implements IDocTopicManager { public static String TOPIC_GENERAL = "" ; public static String TOPIC_GROUP = "" ; public static String TOPIC_MODULE = "" ; public static String TOPIC_CLASS = "" ; public static String TOPIC_INTERFACE = "" ; public static String TOPIC_PACKAGE = "" ; public static String TOPIC_SECTION = "" ; public static String TOPIC_TASK = "" ; public static String TOPIC_FUNCTION = "" ; public static String TOPIC_VARIABLE = "" ; Map < String , DocTopicType > topicTypeMap ; Map < String , DocTopicType > singularKeywordMap ; Map < String , DocTopicType > pluralKeywordMap ; public DocTopicManager ( ) { topicTypeMap = new HashMap < String , DocTopicType > ( ) ; singularKeywordMap = new HashMap < String , DocTopicType > ( ) ; pluralKeywordMap = new HashMap < String , DocTopicType > ( ) ; topicTypeMap . put ( TOPIC_GENERAL , new DocTopicType ( TOPIC_GENERAL , "" , ScopeType . NORMAL , false , true , false ) ) ; topicTypeMap . put ( TOPIC_CLASS , new DocTopicType ( TOPIC_CLASS , "" , ScopeType . START , true , true , false ) ) ; topicTypeMap . put ( TOPIC_MODULE , new DocTopicType ( TOPIC_MODULE , "" , ScopeType . START , true , true , false ) ) ; topicTypeMap . put ( TOPIC_INTERFACE , new DocTopicType ( TOPIC_INTERFACE , "" , ScopeType . START , true , true , false ) ) ; topicTypeMap . put ( TOPIC_PACKAGE , new DocTopicType ( TOPIC_PACKAGE , "" , ScopeType . START , true , true , false ) ) ; topicTypeMap . put ( TOPIC_SECTION , new DocTopicType ( TOPIC_SECTION , "" , ScopeType . END , false , true , false ) ) ; topicTypeMap . put ( TOPIC_GROUP , new DocTopicType ( TOPIC_GROUP , "" , ScopeType . NORMAL , false , false , false ) ) ; topicTypeMap . put ( TOPIC_TASK , new DocTopicType ( TOPIC_TASK , "" , ScopeType . NORMAL , true , false , false ) ) ; topicTypeMap . put ( TOPIC_FUNCTION , new DocTopicType ( TOPIC_FUNCTION , "" , ScopeType . NORMAL , true , false , false ) ) ; topicTypeMap . put ( TOPIC_VARIABLE , new DocTopicType ( TOPIC_VARIABLE , "" , ScopeType . NORMAL , true , false , false ) ) ; registerKeywordForTopicType ( TOPIC_GENERAL , "" , "" ) ; registerKeywordForTopicType ( TOPIC_CLASS , "" , "" ) ; registerKeywordForTopicType ( TOPIC_CLASS , "" , "" ) ; registerKeywordForTopicType ( TOPIC_CLASS , "" , "" ) ; registerKeywordForTopicType ( TOPIC_PACKAGE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_MODULE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_INTERFACE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_SECTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_SECTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_GROUP , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_TASK , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_FUNCTION , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; registerKeywordForTopicType ( TOPIC_VARIABLE , "" , "" ) ; } private void registerKeywordForTopicType ( String topicTypeName , String singularKeyword , String pluralKeyword ) { DocTopicType topicType = topicTypeMap . get ( topicTypeName ) ; if ( topicType != null ) { singularKeywordMap . put ( singularKeyword , topicType ) ; pluralKeywordMap . put ( pluralKeyword , topicType ) ; } } public DocKeywordInfo getTopicType ( String keyword ) { String kwLower = keyword . toLowerCase ( ) ; if ( singularKeywordMap . containsKey ( kwLower ) ) return new DocKeywordInfo ( kwLower , singularKeywordMap . get ( kwLower ) , false ) ; if ( pluralKeywordMap . containsKey ( kwLower . toLowerCase ( ) ) ) return new DocKeywordInfo ( kwLower , pluralKeywordMap . get ( kwLower ) , false ) ; return null ; } public Collection < DocTopicType > getAllTopicTypes ( ) { return new ArrayList < DocTopicType > ( topicTypeMap . values ( ) ) ; } } package net . sf . sveditor . core . docs ; import java . io . File ; import java . util . Set ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; public class DocGenConfig { private Set < Tuple < SVDBDeclCacheItem , ISVDBIndex > > fPackages ; private File outputDir ; private boolean includeUndocumentedPkgsInPkgIndex = true ; public Set < Tuple < SVDBDeclCacheItem , ISVDBIndex > > getSelectedPackages ( ) { return fPackages ; } public void setSelectedPackages ( Set < Tuple < SVDBDeclCacheItem , ISVDBIndex > > fPackages ) { this . fPackages = fPackages ; } public void setOutputDir ( File outputDir ) { this . outputDir = outputDir ; } public File getOutputDir ( ) { return outputDir ; } public boolean getIncludeUndocumentedPkgsInPkgIndex ( ) { return includeUndocumentedPkgsInPkgIndex ; } public void setIncludeUndocumentedPkgsInPkgIndex ( boolean includeUndocumentedPkgsInPkgIndex ) { this . includeUndocumentedPkgsInPkgIndex = includeUndocumentedPkgsInPkgIndex ; } } package net . sf . sveditor . core . docs ; import java . util . List ; import net . sf . sveditor . core . docs . model . DocTopic ; public interface IDocCommentParser { public String isDocComment ( String comment ) ; public void parse ( String comment , List < DocTopic > docTopics ) ; public int parseComment ( String lines [ ] , List < DocTopic > parsedTopics ) ; } package net . sf . sveditor . core . docs ; import java . io . File ; import net . sf . sveditor . core . docs . model . DocModel ; public interface IDocWriter { public void write ( DocGenConfig cfg , DocModel model ) ; public File getIndexHTML ( DocGenConfig cfg , DocModel model ) ; } package net . sf . sveditor . core . docs ; import java . util . Collection ; public interface IDocTopicManager { DocKeywordInfo getTopicType ( String keyword ) ; Collection < DocTopicType > getAllTopicTypes ( ) ; } package net . sf . sveditor . core . docs ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . docs . model . DocTopic ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class DocCommentParser implements IDocCommentParser { private LogHandle fLog ; private IDocTopicManager fDocTopics ; public DocCommentParser ( ) { this ( null ) ; } public DocCommentParser ( IDocTopicManager docTopics ) { fLog = LogFactory . getLogHandle ( "" ) ; fDocTopics = docTopics ; } private static Pattern fPatternHeaderLine = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE ) ; private static Pattern fPatternIsDocComment = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE | Pattern . DOTALL ) ; private static Pattern fPatternCodeSectionEnd = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE ) ; private static Pattern fPatternDefinition = Pattern . compile ( "" ) ; private static Pattern fPatternCodeSectionStart = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE ) ; private static Pattern headerLinePattern = Pattern . compile ( "" ) ; private static Pattern fSummaryPattern = Pattern . compile ( "" , Pattern . DOTALL ) ; public String isDocComment ( String comment ) { String lines [ ] = DocCommentCleaner . splitCommentIntoLines ( comment ) ; for ( String line : lines ) { Matcher matcher = fPatternIsDocComment . matcher ( line ) ; if ( matcher . matches ( ) ) { if ( fDocTopics == null ) { return matcher . group ( ) ; } String keyword = matcher . group ( ) . toLowerCase ( ) ; if ( fDocTopics . getTopicType ( keyword ) != null ) { return matcher . group ( ) ; } } } return null ; } public DocTopic createDocItemForKeyword ( String keyword , String topicTitle ) { DocKeywordInfo kwi = fDocTopics . getTopicType ( keyword . toLowerCase ( ) ) ; if ( kwi == null ) { return null ; } DocTopic docItem ; String topicTypeName = kwi . getTopicType ( ) . getName ( ) ; docItem = new DocTopic ( topicTitle , topicTypeName , keyword ) ; return docItem ; } public void parse ( String comment , List < DocTopic > docTopics ) { String lines [ ] = DocCommentCleaner . splitCommentIntoLines ( comment ) ; try { DocCommentCleaner . clean ( lines ) ; parseComment ( lines , docTopics ) ; } catch ( Exception e ) { fLog . error ( "" , e ) ; } } enum TagType { POSSIBLE_OPENING_TAG , POSSIBLE_CLOSING_TAG , NOT_A_TAG } ; public int parseComment ( String lines [ ] , List < DocTopic > docTopics ) { int topicCount = ; boolean prevLineBlank = true ; boolean inCodeSection = false ; int index = ; String title = null ; String keyword = null ; int bodyStart = ; int bodyEnd = ; Tuple < String , String > tupleKeywordTitle = new Tuple < String , String > ( null , null ) ; while ( index < lines . length ) { if ( inCodeSection ) { if ( fPatternCodeSectionEnd . matcher ( lines [ index ] ) . matches ( ) ) { inCodeSection = false ; } prevLineBlank = false ; bodyEnd ++ ; } else if ( lines [ index ] . length ( ) == ) { prevLineBlank = true ; if ( topicCount != ) { bodyEnd ++ ; } } else if ( prevLineBlank && parseHeaderLine ( tupleKeywordTitle , lines [ index ] ) ) { if ( topicCount != ) { String body = formatBody ( lines , bodyStart , bodyEnd ) ; String summary = "" ; if ( body != null ) { summary = getSummaryFromBody ( body ) ; } DocTopic newDocItem = createDocItemForKeyword ( keyword , title ) ; newDocItem . setBody ( body ) ; newDocItem . setSummary ( summary ) ; docTopics . add ( newDocItem ) ; } keyword = tupleKeywordTitle . first ( ) ; title = tupleKeywordTitle . second ( ) ; bodyStart = index + ; bodyEnd = index + ; topicCount ++ ; prevLineBlank = false ; } else if ( topicCount != ) { prevLineBlank = false ; bodyEnd ++ ; if ( fPatternCodeSectionStart . matcher ( lines [ index ] ) . matches ( ) ) { inCodeSection = true ; } } index ++ ; } if ( topicCount != ) { String body = formatBody ( lines , bodyStart , bodyEnd ) ; String summary = "" ; if ( body != null ) { summary = getSummaryFromBody ( body ) ; } DocTopic newTopic = createDocItemForKeyword ( keyword , title ) ; newTopic . setBody ( body ) ; newTopic . setSummary ( summary ) ; docTopics . add ( newTopic ) ; topicCount ++ ; } return topicCount ; } private boolean parseHeaderLine ( Tuple < String , String > tupleKeywordTitle , String line ) { Matcher matcher = fPatternHeaderLine . matcher ( line ) ; if ( matcher . matches ( ) ) { String keyWord = matcher . group ( ) ; String title = matcher . group ( ) ; if ( fDocTopics . getTopicType ( keyWord . toLowerCase ( ) ) != null ) { tupleKeywordTitle . setFirst ( keyWord ) ; tupleKeywordTitle . setSecond ( title ) ; return true ; } else { return false ; } } else { return false ; } } enum Tag { NONE , PARAGRAPH , BULLETLIST , DESCRIPTIONLIST , HEADING , PREFIXCODE , TAGCODE } ; private static final Map < Tag , String > fTagEnders ; static { fTagEnders = new HashMap < Tag , String > ( ) ; fTagEnders . put ( Tag . NONE , "" ) ; fTagEnders . put ( Tag . PARAGRAPH , "" ) ; fTagEnders . put ( Tag . BULLETLIST , "" ) ; fTagEnders . put ( Tag . DESCRIPTIONLIST , "" ) ; fTagEnders . put ( Tag . HEADING , "" ) ; fTagEnders . put ( Tag . PREFIXCODE , "" ) ; fTagEnders . put ( Tag . TAGCODE , "" ) ; } @ SuppressWarnings ( "" ) private String formatBody ( String [ ] lines , int startIndex , int endIndex ) { Tag topLevelTag = Tag . NONE ; String output = "" ; String textBlock = null ; boolean prevLineBlank = true ; Tuple < String , Integer > codeBlockTuple = new Tuple < String , Integer > ( "" , ) ; boolean ignoreListSymbols ; int index = startIndex ; while ( index < endIndex ) { Pattern codeDesignatorPattern = Pattern . compile ( "" ) ; Matcher codeDesignatorMatcher = codeDesignatorPattern . matcher ( lines [ index ] ) ; Matcher headerLineMatcher = headerLinePattern . matcher ( lines [ index ] ) ; Matcher definitionMatcher = fPatternDefinition . matcher ( lines [ index ] ) ; if ( topLevelTag == Tag . TAGCODE ) { if ( false ) { } else { AddToCodeBlock ( lines [ index ] , codeBlockTuple ) ; } ; } else if ( codeDesignatorMatcher . matches ( ) ) { String code = codeDesignatorMatcher . group ( ) ; if ( topLevelTag == Tag . PREFIXCODE ) { AddToCodeBlock ( code , codeBlockTuple ) ; } else { if ( textBlock != null ) { output += richFormatTextBlock ( textBlock ) + fTagEnders . get ( topLevelTag ) ; textBlock = null ; } topLevelTag = Tag . PREFIXCODE ; output += "" ; AddToCodeBlock ( code , codeBlockTuple ) ; } } else { lines [ index ] = lines [ index ] . replaceFirst ( "" , "" ) ; Pattern bulletLinePatter = Pattern . compile ( "" ) ; Matcher bulletLineMatcher = bulletLinePatter . matcher ( lines [ index ] ) ; if ( topLevelTag == Tag . PREFIXCODE ) { output += convertAmpChars ( codeBlockTuple . first ( ) ) + "" ; codeBlockTuple . setFirst ( "" ) ; codeBlockTuple . setSecond ( ) ; topLevelTag = Tag . NONE ; prevLineBlank = false ; } if ( lines [ index ] . length ( ) == ) { if ( topLevelTag == Tag . PARAGRAPH ) { output += richFormatTextBlock ( textBlock ) + "" ; textBlock = null ; topLevelTag = Tag . NONE ; } prevLineBlank = true ; } else if ( bulletLineMatcher . matches ( ) && ! bulletLineMatcher . group ( ) . substring ( , ) . matches ( "" ) ) { String bulletedText = bulletLineMatcher . group ( ) ; if ( textBlock != null ) { output += richFormatTextBlock ( textBlock ) ; } ; if ( topLevelTag == Tag . BULLETLIST ) { output += "" ; } else { output += fTagEnders . get ( topLevelTag ) + "" ; topLevelTag = Tag . BULLETLIST ; } textBlock = bulletedText ; prevLineBlank = false ; } else if ( definitionMatcher . matches ( ) && topLevelTag != Tag . PARAGRAPH ) { String entry = definitionMatcher . group ( ) ; String description = definitionMatcher . group ( ) ; if ( textBlock != null ) { output += richFormatTextBlock ( textBlock ) ; } if ( topLevelTag == Tag . DESCRIPTIONLIST ) { output += "" ; } else { output += fTagEnders . get ( topLevelTag ) + "" ; topLevelTag = Tag . DESCRIPTIONLIST ; } if ( false ) { } else { output += "" + convertAmpChars ( entry ) + "" ; } ; textBlock = description ; prevLineBlank = false ; } else if ( prevLineBlank && headerLineMatcher . matches ( ) ) { String headerText = headerLineMatcher . group ( ) + headerLineMatcher . group ( ) ; if ( textBlock != null ) { output += richFormatTextBlock ( textBlock ) ; textBlock = null ; } output += fTagEnders . get ( topLevelTag ) ; topLevelTag = Tag . NONE ; output += "" + richFormatTextBlock ( headerText ) + "" ; prevLineBlank = false ; } else { if ( prevLineBlank && ( topLevelTag == Tag . BULLETLIST || topLevelTag == Tag . DESCRIPTIONLIST ) ) { output += richFormatTextBlock ( textBlock ) + fTagEnders . get ( topLevelTag ) + "" ; topLevelTag = Tag . PARAGRAPH ; textBlock = null ; } else if ( topLevelTag == Tag . NONE ) { output += "" ; topLevelTag = Tag . PARAGRAPH ; } if ( textBlock != null ) { textBlock += "" ; } else { textBlock = new String ( ) ; } textBlock += lines [ index ] ; prevLineBlank = false ; } } index ++ ; } if ( textBlock != null ) { output += richFormatTextBlock ( textBlock ) + fTagEnders . get ( topLevelTag ) ; } else if ( codeBlockTuple . first ( ) . length ( ) != ) { codeBlockTuple . setFirst ( codeBlockTuple . first ( ) . replaceFirst ( "" , "" ) ) ; output += convertAmpChars ( codeBlockTuple . first ( ) ) + "" ; } return output ; } private void AddToCodeBlock ( String line , Tuple < String , Integer > codeBlockTuple ) { Pattern patternLeadingWhiteSpaces = Pattern . compile ( "" ) ; Matcher matcherLeadingWhiteSpace = patternLeadingWhiteSpaces . matcher ( line ) ; String spaces = null ; String code = null ; if ( ! matcherLeadingWhiteSpace . matches ( ) ) { } else { spaces = matcherLeadingWhiteSpace . group ( ) ; code = matcherLeadingWhiteSpace . group ( ) ; } if ( codeBlockTuple . first ( ) . length ( ) == ) { if ( code . length ( ) != ) { codeBlockTuple . setFirst ( codeBlockTuple . first ( ) + code + "" ) ; codeBlockTuple . setSecond ( spaces . length ( ) ) ; } } else if ( code . length ( ) != ) { if ( spaces . length ( ) != codeBlockTuple . second ( ) ) { int spaceDifference = ; if ( spaces . length ( ) >= codeBlockTuple . second ( ) ) { spaceDifference = spaces . length ( ) - codeBlockTuple . second ( ) ; } String spacesToAdd = "" ; for ( int i = ; i < spaceDifference ; i ++ ) { spacesToAdd += "" ; } if ( spaces . length ( ) > codeBlockTuple . second ( ) ) { codeBlockTuple . setFirst ( codeBlockTuple . first ( ) + spacesToAdd ) ; } else { codeBlockTuple . setFirst ( spacesToAdd + codeBlockTuple . first ( ) ) ; codeBlockTuple . setSecond ( spaces . length ( ) ) ; } } codeBlockTuple . setFirst ( codeBlockTuple . first ( ) + code + "" ) ; } else { codeBlockTuple . setFirst ( codeBlockTuple . first ( ) + "" ) ; } } private String richFormatTextBlock ( String text ) { String output = "" ; String [ ] tempTextBlocks = text . split ( "" ) ; ArrayList < String > textBlocks = new ArrayList < String > ( ) ; for ( String block : tempTextBlocks ) { if ( block . length ( ) != ) { textBlocks . add ( block ) ; } } boolean bold = false ; boolean underline = false ; boolean underlineHasWhitespace = false ; int index = ; while ( index < textBlocks . size ( ) ) { if ( textBlocks . get ( index ) . matches ( "" ) ) { output += '' ; index ++ ; while ( ! textBlocks . get ( index ) . matches ( "" ) ) { output += textBlocks . get ( index ) ; index ++ ; } ; output += ">" ; } else if ( textBlocks . get ( index ) . matches ( "" ) && tagType ( textBlocks , index ) == TagType . POSSIBLE_OPENING_TAG ) { Tuple < Integer , Boolean > closingTagTuple = closingTag ( textBlocks , index ) ; if ( closingTagTuple . first ( ) != - ) { String linkText = "" ; index ++ ; while ( index < closingTagTuple . first ( ) ) { linkText += textBlocks . get ( index ) ; index ++ ; } linkText = convertAmpChars ( linkText ) ; { output += String . format ( "" , linkText , linkText , linkText ) ; } } else { output += "" ; } } else if ( textBlocks . get ( index ) . matches ( "" ) ) { TagType tagType = tagType ( textBlocks , index ) ; Tuple < Integer , Boolean > closingTagTuple = closingTag ( textBlocks , index ) ; if ( tagType == TagType . POSSIBLE_OPENING_TAG && closingTagTuple . first ( ) != - ) { bold = true ; output += "" ; } else if ( bold && tagType == TagType . POSSIBLE_CLOSING_TAG ) { bold = false ; output += "" ; } else { output += "" ; } ; } else if ( textBlocks . get ( index ) . matches ( "" ) ) { TagType tagType = tagType ( textBlocks , index ) ; Tuple < Integer , Boolean > closingTagTuple = closingTag ( textBlocks , index ) ; if ( tagType == TagType . POSSIBLE_OPENING_TAG && closingTagTuple . first ( ) != - ) { bold = true ; output += "" ; } else if ( bold && tagType == TagType . POSSIBLE_CLOSING_TAG ) { bold = false ; output += "" ; } else { output += "" ; } ; } else if ( textBlocks . get ( index ) . matches ( "" ) ) { TagType tagType = tagType ( textBlocks , index ) ; Tuple < Integer , Boolean > closingTagTuple = closingTag ( textBlocks , index ) ; if ( tagType == TagType . POSSIBLE_OPENING_TAG && closingTagTuple . first ( ) != - ) { underline = true ; output += "" ; } else if ( underline && tagType == TagType . POSSIBLE_CLOSING_TAG ) { underline = false ; output += "" ; } else if ( underline && ! underlineHasWhitespace ) { output += "" ; } else { output += "" ; } ; } else { output += convertAmpChars ( textBlocks . get ( index ) ) ; } ; index ++ ; } return output ; } private TagType tagType ( ArrayList < String > textBlocks , int index ) { if ( textBlocks . get ( index ) . matches ( "" ) && ( index == || textBlocks . get ( index - ) . matches ( "" ) ) && ( ( index + < textBlocks . size ( ) ) && ! textBlocks . get ( index + ) . matches ( "" ) ) && ( ! textBlocks . get ( index ) . matches ( "" ) || ! textBlocks . get ( index + ) . matches ( "" ) ) && ( ! textBlocks . get ( index ) . matches ( "" ) || ! textBlocks . get ( index + ) . matches ( "" ) ) && ( textBlocks . get ( index ) . matches ( "" ) || index == || ! textBlocks . get ( index - ) . matches ( "" ) ) ) { return TagType . POSSIBLE_OPENING_TAG ; } else if ( ( textBlocks . get ( index ) . matches ( "" ) ) && ( index + == textBlocks . size ( ) || textBlocks . get ( index + ) . matches ( "" ) ) && ( index != && ! textBlocks . get ( index - ) . matches ( "" ) ) && ( ! textBlocks . get ( index ) . matches ( "" ) || ! textBlocks . get ( index ) . matches ( "" ) ) ) { return TagType . POSSIBLE_CLOSING_TAG ; } else { return TagType . NOT_A_TAG ; } } ; Tuple < Integer , Boolean > closingTag ( ArrayList < String > textBlocks , int index ) { Tuple < Integer , Boolean > result = new Tuple < Integer , Boolean > ( - , false ) ; try { boolean hasWhitespace = false ; String closingTag = null ; if ( textBlocks . get ( index ) . matches ( "" ) ) { closingTag = ( "" ) ; } else if ( textBlocks . get ( index ) . matches ( "" ) ) { closingTag = textBlocks . get ( index ) ; } else if ( textBlocks . get ( index ) . matches ( "" ) ) { closingTag = textBlocks . get ( index ) ; } else if ( textBlocks . get ( index ) . matches ( "" ) ) { closingTag = "" ; } else { return result ; } ; int beginningIndex = index ; index ++ ; while ( index < textBlocks . size ( ) ) { if ( textBlocks . get ( index ) . matches ( "" ) && tagType ( textBlocks , index ) == TagType . POSSIBLE_OPENING_TAG ) { if ( closingTag . equals ( "" ) ) { return result ; } else { Tuple < Integer , Boolean > closingTagTuple = closingTag ( textBlocks , index ) ; int endIndex = closingTagTuple . first ( ) ; boolean linkHasWhitespace = closingTagTuple . second ( ) ; if ( endIndex != - ) { if ( linkHasWhitespace ) { hasWhitespace = true ; } ; index = endIndex ; } } } else if ( textBlocks . get ( index ) . matches ( closingTag ) ) { TagType tagType = tagType ( textBlocks , index ) ; if ( tagType == TagType . POSSIBLE_CLOSING_TAG ) { if ( index == beginningIndex + ) { return result ; } else { result . setFirst ( index ) ; result . setSecond ( hasWhitespace ) ; } } else if ( tagType == TagType . POSSIBLE_OPENING_TAG ) { return result ; } } else if ( ! result . second ( ) ) { if ( textBlocks . get ( index ) . matches ( "" ) ) { result . setSecond ( true ) ; } } index ++ ; } ; } catch ( Exception e ) { fLog . error ( "" , e ) ; } return result ; } private String convertAmpChars ( String text ) { text = text . replaceAll ( "" , "" ) ; text = text . replaceAll ( "" , "" ) ; text = text . replaceAll ( ">" , "" ) ; text = text . replaceAll ( "" , "" ) ; return text ; } private String getSummaryFromBody ( String body ) { String summary = "" ; Matcher matcher = fSummaryPattern . matcher ( body ) ; if ( matcher . matches ( ) ) { summary = matcher . group ( ) ; if ( ( matcher . group ( ) != null ) && ! ( matcher . group ( ) . equals ( "" ) ) ) { summary += matcher . group ( ) ; } ; } return summary ; } } package net . sf . sveditor . core ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . ui . actions . WorkspaceModifyOperation ; public class SVMarkerPropagationJob extends Job { private class MarkerInfo { IFile fFile ; int fSeverity ; int fLineno ; String fMsg ; } private List < MarkerInfo > fMarkerList ; public SVMarkerPropagationJob ( ) { super ( "" ) ; fMarkerList = new ArrayList < SVMarkerPropagationJob . MarkerInfo > ( ) ; } @ Override protected IStatus run ( IProgressMonitor monitor ) { final List < MarkerInfo > markers = new ArrayList < SVMarkerPropagationJob . MarkerInfo > ( ) ; synchronized ( fMarkerList ) { markers . addAll ( fMarkerList ) ; fMarkerList . clear ( ) ; } WorkspaceModifyOperation op = new WorkspaceModifyOperation ( ) { @ Override protected void execute ( IProgressMonitor monitor ) throws CoreException , InvocationTargetException , InterruptedException { IMarker marker = null ; for ( MarkerInfo info : markers ) { try { marker = info . fFile . createMarker ( IMarker . PROBLEM ) ; marker . setAttribute ( IMarker . SEVERITY , info . fSeverity ) ; marker . setAttribute ( IMarker . LINE_NUMBER , info . fLineno ) ; marker . setAttribute ( IMarker . MESSAGE , info . fMsg ) ; } catch ( CoreException e ) { if ( marker != null ) { marker . delete ( ) ; } } } } } ; try { op . run ( monitor ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return Status . OK_STATUS ; } public void addMarker ( IFile file , int severity , int lineno , String msg ) { MarkerInfo info = new MarkerInfo ( ) ; info . fFile = file ; info . fSeverity = severity ; info . fLineno = lineno ; info . fMsg = msg ; synchronized ( fMarkerList ) { fMarkerList . add ( info ) ; } synchronized ( this ) { if ( getState ( ) == Job . NONE ) { schedule ( ) ; } } } } package net . sf . sveditor . core . scanner ; import java . util . List ; import net . sf . sveditor . core . Tuple ; public interface ISVPreProcScannerObserver { void init ( ISVScanner scanner ) ; void enter_file ( String filename ) ; void leave_file ( ) ; void preproc_define ( String key , List < Tuple < String , String > > params , String value ) ; void preproc_include ( String path ) ; void enter_preproc_conditional ( String type , String conditional ) ; void leave_preproc_conditional ( ) ; void comment ( String title , String comment ) ; void enter_package ( String name ) ; void leave_package ( ) ; } package net . sf . sveditor . core . scanner ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; public class SVKeywords { private static final String fKeywords [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private static final String fSystemCalls [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private static final String fTypeStrings [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , } ; public static final Set < String > fBuiltinTypes ; public static final Set < String > fTypePrefixes ; public static final Set < String > fBuiltinDeclTypes ; private static final Map < String , Boolean > fKeywordMap ; public static final Set < String > fBuiltinGates_with_Strength ; public static final Set < String > fBuiltinGates_no_Strength ; public static final Set < String > fBuiltinGates ; public static final Set < String > fStrength0 ; public static final Set < String > fStrength1 ; public static final Set < String > fStrengthC ; public static final Set < String > fStrength ; public static final Set < String > fAssignmentOps ; public static final Set < String > fBinaryOps ; static { fKeywordMap = new HashMap < String , Boolean > ( ) ; for ( String str : fKeywords ) { boolean is_sv = str . endsWith ( "" ) ; if ( is_sv ) { str = str . substring ( , str . length ( ) - ) ; } fKeywordMap . put ( str , is_sv ) ; } fBuiltinTypes = new HashSet < String > ( ) ; fBuiltinDeclTypes = new HashSet < String > ( ) ; for ( String n : fTypeStrings ) { fBuiltinTypes . add ( n ) ; if ( ! n . equals ( "" ) ) { fBuiltinDeclTypes . add ( n ) ; } } fBuiltinGates_with_Strength = new HashSet < String > ( ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_with_Strength . add ( "" ) ; fBuiltinGates_no_Strength = new HashSet < String > ( ) ; fBuiltinGates_no_Strength . add ( "" ) ; fBuiltinGates_no_Strength . add ( "" ) ; fBuiltinGates_no_Strength . add ( "" ) ; fBuiltinGates_no_Strength . add ( "" ) ; fBuiltinGates_no_Strength . add ( "" ) ; fBuiltinGates_no_Strength . add ( "" ) ; fBuiltinGates = new HashSet < String > ( ) ; fBuiltinGates . addAll ( fBuiltinGates_with_Strength ) ; fBuiltinGates . addAll ( fBuiltinGates_no_Strength ) ; fTypePrefixes = new HashSet < String > ( ) ; fTypePrefixes . add ( "" ) ; fTypePrefixes . add ( "" ) ; fStrength0 = new HashSet < String > ( ) ; fStrength0 . add ( "" ) ; fStrength0 . add ( "" ) ; fStrength0 . add ( "" ) ; fStrength0 . add ( "" ) ; fStrength0 . add ( "" ) ; fStrength1 = new HashSet < String > ( ) ; fStrength1 . add ( "" ) ; fStrength1 . add ( "" ) ; fStrength1 . add ( "" ) ; fStrength1 . add ( "" ) ; fStrength1 . add ( "" ) ; fStrengthC = new HashSet < String > ( ) ; fStrengthC . add ( "" ) ; fStrengthC . add ( "" ) ; fStrengthC . add ( "" ) ; fStrength = new HashSet < String > ( ) ; fStrength . addAll ( fStrength0 ) ; fStrength . addAll ( fStrength1 ) ; fStrength . addAll ( fStrengthC ) ; fAssignmentOps = new HashSet < String > ( ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fAssignmentOps . add ( "" ) ; fBinaryOps = new HashSet < String > ( ) ; for ( String op : new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , ">" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ) { fBinaryOps . add ( op ) ; } } ; public static boolean isSVKeyword ( String kw ) { Boolean is_sv = fKeywordMap . get ( kw ) ; return ( is_sv != null ) ; } public static boolean isBuiltinGate ( String kw ) { return fBuiltinGates . contains ( kw ) ; } public static boolean isVKeyword ( String kw ) { Boolean is_sv = fKeywordMap . get ( kw ) ; return ( is_sv != null && ! is_sv . booleanValue ( ) ) ; } public static boolean isBuiltInType ( String type ) { return fBuiltinTypes . contains ( type ) ; } public static boolean isDir ( String dir ) { return ( dir . equals ( "" ) || dir . equals ( "" ) || dir . equals ( "" ) ) ; } public static Set < String > getKeywords ( ) { return fKeywordMap . keySet ( ) ; } public static String [ ] getSystemCalls ( ) { return fSystemCalls ; } } package net . sf . sveditor . core . scanner ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . NullProgressMonitor ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMacroDef ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class FileContextSearchMacroProvider implements IPreProcMacroProvider { private Map < String , SVDBMacroDef > fMacroCache ; private ISVDBIndexCache fIndexCache ; private Map < String , SVDBFileTree > fWorkingSet ; private SVDBFileTree fContext ; private boolean fDebugEnS = false ; private int fIndent = ; private LogHandle fLog ; public FileContextSearchMacroProvider ( ISVDBIndexCache cache , Map < String , SVDBFileTree > working_set ) { fIndexCache = cache ; fWorkingSet = working_set ; fMacroCache = new HashMap < String , SVDBMacroDef > ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public void setFileContext ( SVDBFileTree context ) { fContext = context ; } public void addMacro ( SVDBMacroDef macro ) { if ( fMacroCache . containsKey ( macro . getName ( ) ) ) { fMacroCache . remove ( macro . getName ( ) ) ; } fMacroCache . put ( macro . getName ( ) , macro ) ; } public SVDBMacroDef findMacro ( String name , int lineno ) { if ( fMacroCache . containsKey ( name ) ) { return fMacroCache . get ( name ) ; } else { return searchContext ( fContext , name ) ; } } public void setMacro ( String key , String value ) { if ( fMacroCache . containsKey ( key ) ) { fMacroCache . get ( key ) . setDef ( value ) ; } else { SVDBMacroDef def = new SVDBMacroDef ( key , value ) ; fMacroCache . put ( key , def ) ; } } protected SVDBMacroDef searchContext ( SVDBFileTree context , String key ) { SVDBMacroDef ret ; debug_s ( indent ( fIndent ++ ) + "" + context . getFilePath ( ) + "" + key + "" ) ; if ( ( ret = fMacroCache . get ( key ) ) == null ) { if ( ( ret = searchDown ( context , context , key ) ) == null ) { for ( String ib_s : context . getIncludedByFiles ( ) ) { SVDBFileTree ib ; if ( fWorkingSet . containsKey ( ib_s ) ) { ib = fWorkingSet . get ( ib_s ) ; } else { ib = fIndexCache . getFileTree ( new NullProgressMonitor ( ) , ib_s ) ; } if ( ib == null ) { fLog . error ( "" + ib_s + "" ) ; fLog . error ( "" + fContext . getFilePath ( ) ) ; continue ; } ret = searchUp ( context , ib , context , key ) ; } } if ( ret != null ) { if ( fMacroCache . containsKey ( key ) ) { fMacroCache . remove ( key ) ; } fMacroCache . put ( key , ret ) ; } } debug_s ( indent ( -- fIndent ) + "" + context . getFilePath ( ) + "" + key + "" ) ; return ret ; } private SVDBMacroDef searchLocal ( SVDBFileTree file , ISVDBScopeItem context , String key ) { SVDBMacroDef m = null ; debug_s ( indent ( fIndent ++ ) + "" + file . getFilePath ( ) + "" + key + "" ) ; for ( ISVDBItemBase it : context . getItems ( ) ) { debug_s ( "" + ( ( ISVDBNamedItem ) it ) . getName ( ) ) ; if ( it . getType ( ) == SVDBItemType . MacroDef && ( ( ISVDBNamedItem ) it ) . getName ( ) . equals ( key ) ) { m = ( SVDBMacroDef ) it ; } else if ( it instanceof ISVDBScopeItem ) { m = searchLocal ( file , ( ISVDBScopeItem ) it , key ) ; } if ( m != null ) { break ; } } debug_s ( indent ( -- fIndent ) + "" + file . getFilePath ( ) + "" + key + "" ) ; return m ; } private SVDBMacroDef searchDown ( SVDBFileTree boundary , SVDBFileTree context , String key ) { SVDBMacroDef m = null ; debug_s ( indent ( fIndent ++ ) + "" + context . getFilePath ( ) + "" + key + "" ) ; if ( context . getSVDBFile ( ) != null ) { if ( ( m = searchLocal ( context , context . getSVDBFile ( ) , key ) ) == null ) { for ( String inc_s : context . getIncludedFiles ( ) ) { SVDBFileTree inc ; if ( fWorkingSet . containsKey ( inc_s ) ) { inc = fWorkingSet . get ( inc_s ) ; } else { inc = fIndexCache . getFileTree ( new NullProgressMonitor ( ) , inc_s ) ; } debug_s ( indent ( fIndent ) + "" + ( ( inc != null ) ? inc . getFilePath ( ) : "" ) + "" ) ; if ( inc != null && inc . getSVDBFile ( ) != null ) { if ( ( m = searchDown ( boundary , inc , key ) ) != null ) { break ; } } } } } debug_s ( indent ( -- fIndent ) + "" + context . getFilePath ( ) + "" + key + "" ) ; return m ; } private SVDBMacroDef searchUp ( SVDBFileTree boundary , SVDBFileTree context , SVDBFileTree child , String key ) { SVDBMacroDef m = null ; debug_s ( indent ( fIndent ++ ) + "" + context . getFilePath ( ) + "" + key + "" ) ; if ( ( m = searchLocal ( context , context . getSVDBFile ( ) , key ) ) == null ) { List < String > inc_files = context . getIncludedFiles ( ) ; synchronized ( inc_files ) { for ( String is_s : inc_files ) { SVDBFileTree is ; if ( fWorkingSet . containsKey ( is_s ) ) { is = fWorkingSet . get ( is_s ) ; } else { is = fIndexCache . getFileTree ( new NullProgressMonitor ( ) , is_s ) ; } if ( is == null ) { continue ; } if ( ! is . getFilePath ( ) . equals ( child . getFilePath ( ) ) && ( is != boundary ) ) { debug_s ( indent ( fIndent ) + "" + is . getFilePath ( ) ) ; if ( ( m = searchDown ( boundary , is , key ) ) == null ) { for ( String ib_s : context . getIncludedByFiles ( ) ) { SVDBFileTree ib ; if ( fWorkingSet . containsKey ( ib_s ) ) { ib = fWorkingSet . get ( ib_s ) ; } else { ib = fIndexCache . getFileTree ( new NullProgressMonitor ( ) , ib_s ) ; } if ( ( m = searchUp ( boundary , ib , context , key ) ) != null ) { break ; } } } } else { debug_s ( indent ( fIndent ) + "" + is . getFilePath ( ) + "" + ( is == boundary ) ) ; } if ( m != null ) { break ; } } } } debug_s ( indent ( -- fIndent ) + "" + context . getFilePath ( ) + "" + key + "" ) ; return m ; } private void debug_s ( String str ) { if ( fDebugEnS ) { fLog . debug ( str ) ; } } private String indent ( int ind ) { String ret = "" ; while ( ind -- > ) { ret += "" ; } return ret ; } } package net . sf . sveditor . core . scanner ; public interface IDefineProvider { String expandMacro ( String string , String filename , int lineno ) ; boolean isDefined ( String name , int lineno ) ; boolean hasParameters ( String key , int lineno ) ; void addErrorListener ( IPreProcErrorListener l ) ; void removeErrorListener ( IPreProcErrorListener l ) ; void error ( String msg , String filename , int lineno ) ; } package net . sf . sveditor . core . scanner ; public interface IPreProcErrorListener { void preProcError ( String msg , String filename , int lineno ) ; } package net . sf . sveditor . core . scanner ; import net . sf . sveditor . core . scanutils . ScanLocation ; public interface ISVScanner { void setStmtLocation ( ScanLocation location ) ; ScanLocation getStmtLocation ( ) ; ScanLocation getStartLocation ( ) ; } package net . sf . sveditor . core . scanner ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . Stack ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBMacroDef ; import net . sf . sveditor . core . db . SVDBMacroDefParam ; import net . sf . sveditor . core . db . utils . SVDBItemPrint ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . ITextScanner ; import net . sf . sveditor . core . scanutils . StringTextScanner ; public class SVPreProcDefineProvider implements IDefineProvider { private static final boolean fDebugEn = false ; private static final boolean fDebugChEn = false ; private boolean fDebugUndefinedMacros = false ; private String fFilename ; private int fLineno ; private Stack < String > fExpandStack ; private Stack < Boolean > fEnableOutputStack ; private LogHandle fLog ; private IPreProcMacroProvider fMacroProvider ; private List < IPreProcErrorListener > fErrorListeners ; public SVPreProcDefineProvider ( IPreProcMacroProvider macro_provider ) { fExpandStack = new Stack < String > ( ) ; fEnableOutputStack = new Stack < Boolean > ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; fMacroProvider = macro_provider ; fErrorListeners = new ArrayList < IPreProcErrorListener > ( ) ; } public void addErrorListener ( IPreProcErrorListener l ) { fErrorListeners . add ( l ) ; } public void removeErrorListener ( IPreProcErrorListener l ) { fErrorListeners . remove ( l ) ; } public void error ( String msg , String filename , int lineno ) { for ( IPreProcErrorListener l : fErrorListeners ) { l . preProcError ( msg , filename , lineno ) ; } } public void setMacroProvider ( IPreProcMacroProvider provider ) { fMacroProvider = provider ; } public IPreProcMacroProvider getMacroProvider ( ) { return fMacroProvider ; } public void addDefines ( Map < String , String > defs ) { for ( String key : defs . keySet ( ) ) { fMacroProvider . setMacro ( key , defs . get ( key ) ) ; } } public boolean isDefined ( String name , int lineno ) { SVDBMacroDef m = fMacroProvider . findMacro ( name , lineno ) ; if ( m != null ) { return ( m . getLocation ( ) == null || m . getLocation ( ) . getLine ( ) <= lineno ) ; } else { return false ; } } public synchronized String expandMacro ( String str , String filename , int lineno ) { StringTextScanner scanner = new StringTextScanner ( new StringBuilder ( str ) ) ; fFilename = filename ; fLineno = lineno ; if ( fDebugEn ) { debug ( "" + str ) ; } if ( fMacroProvider == null ) { fLog . error ( "" ) ; if ( fDebugEn ) { debug ( "" + str ) ; debug ( "" ) ; } return "" ; } fMacroProvider . setMacro ( "" , "" + fFilename + "" ) ; fMacroProvider . setMacro ( "" , "" + fLineno ) ; fExpandStack . clear ( ) ; fEnableOutputStack . clear ( ) ; fEnableOutputStack . push ( true ) ; expandMacro ( scanner ) ; if ( fDebugEn ) { debug ( "" + str ) ; debug ( "" + scanner . getStorage ( ) . toString ( ) ) ; } return scanner . getStorage ( ) . toString ( ) ; } private int expandMacro ( StringTextScanner scanner ) { if ( fDebugEn ) { debug ( "" ) ; } int macro_start = scanner . getOffset ( ) ; int ch = scanner . get_ch ( ) ; if ( ch != '' ) { System . out . println ( "" + "" + ( char ) ch + "" + fFilename + "" + fLineno ) ; try { throw new Exception ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } String key = scanner . readPreProcIdentifier ( scanner . get_ch ( ) ) ; if ( key == null ) { ch = scanner . get_ch ( ) ; fLog . error ( "" + ( char ) ch ) ; scanner . unget_ch ( ch ) ; } else if ( key . equals ( "" ) || key . equals ( "" ) || key . equals ( "" ) || key . equals ( "" ) ) { } else { fExpandStack . push ( key ) ; ch = scanner . skipWhite ( scanner . get_ch ( ) ) ; SVDBMacroDef m = fMacroProvider . findMacro ( key , fLineno ) ; Set < String > referenced_macros = new HashSet < String > ( ) ; if ( m == null ) { error ( "" + key + "" ) ; if ( fDebugUndefinedMacros ) { fLog . error ( "" + key + "" + fFilename + "" + fLineno ) ; } if ( ch == '' ) { ch = skipPastMatchSkipStrings ( scanner , '' , '' ) ; scanner . unget_ch ( ch ) ; } int newline_count = ; for ( int i = macro_start ; i < scanner . getOffset ( ) ; i ++ ) { if ( scanner . charAt ( i ) == '' ) { newline_count ++ ; } } if ( newline_count > ) { StringBuilder replace = new StringBuilder ( ) ; while ( newline_count > ) { replace . append ( "" ) ; newline_count -- ; } scanner . replace ( macro_start , scanner . getOffset ( ) , replace . toString ( ) ) ; } else { scanner . replace ( macro_start , scanner . getOffset ( ) , "" ) ; } return ; } List < String > params = null ; if ( ch == '' ) { StringTextScanner scanner_s ; if ( fDebugEn ) { debug ( "" + scanner . getStorage ( ) ) ; } expandMacroRefs ( new StringTextScanner ( scanner , scanner . getOffset ( ) ) , referenced_macros ) ; if ( fDebugEn ) { debug ( "" + scanner . getStorage ( ) ) ; } params = parse_params ( m , scanner ) ; scanner_s = new StringTextScanner ( scanner , macro_start , scanner . getOffset ( ) ) ; expandMacro ( scanner_s , m , params , referenced_macros ) ; if ( fDebugEn ) { debug ( "" + m . getName ( ) + "" + scanner . getStorage ( ) . toString ( ) ) ; } ch = scanner . get_ch ( ) ; } else { StringTextScanner scanner_s = new StringTextScanner ( scanner , macro_start , scanner . getOffset ( ) ) ; expandMacro ( scanner_s , m , null , referenced_macros ) ; scanner . seek ( scanner_s . getOffset ( ) - ) ; if ( fDebugEn ) { debug ( "" + scanner_s . getStorage ( ) . toString ( ) ) ; } } fExpandStack . pop ( ) ; if ( fDebugEn ) { debug ( "" ) ; } } return ; } private int skipPastMatchSkipStrings ( ITextScanner scanner , int ch1 , int ch2 ) { int ch ; int lcnt = , rcnt = ; while ( ( ch = scanner . get_ch ( ) ) != - ) { if ( ch == ch1 ) { lcnt ++ ; } else if ( ch == ch2 ) { rcnt ++ ; } else if ( ch == '' ) { skipPastString ( scanner ) ; } if ( lcnt == rcnt ) { break ; } } return scanner . get_ch ( ) ; } private void skipPastString ( ITextScanner scanner ) { int ch ; int last_ch = - ; while ( ( ch = scanner . get_ch ( ) ) != - ) { if ( ch == '' && last_ch != '' ) { break ; } if ( last_ch == '' && ch == '' ) { last_ch = - ; } else { last_ch = ch ; } } } private void expandMacro ( StringTextScanner scanner , SVDBMacroDef m , List < String > params_vals , Set < String > referenced_params ) { boolean expand_params = ( params_vals != null ) ; List < String > param_names = new ArrayList < String > ( ) ; for ( int i = ; i < m . getParameters ( ) . size ( ) ; i ++ ) { SVDBMacroDefParam mp = m . getParameters ( ) . get ( i ) ; param_names . add ( mp . getName ( ) ) ; if ( i >= params_vals . size ( ) && mp . getValue ( ) != null ) { if ( fDebugEn ) { debug ( "" + mp . getValue ( ) + "" + mp . getName ( ) ) ; } params_vals . add ( mp . getValue ( ) ) ; } } if ( fDebugEn ) { debug ( "" + m . getName ( ) + "" ) ; debug ( "" + scanner . substring ( scanner . getOffset ( ) , scanner . getLimit ( ) ) ) ; } if ( expand_params ) { expand_params = ( params_vals . size ( ) == param_names . size ( ) ) ; if ( params_vals . size ( ) != param_names . size ( ) ) { fLog . error ( "" + m . getName ( ) + "" + params_vals . size ( ) + "" + m . getParameters ( ) . size ( ) ) ; fLog . error ( "" + fFilename + "" + fLineno ) ; if ( fDebugEn ) { try { throw new Exception ( ) ; } catch ( Exception e ) { fLog . debug ( "" , e ) ; } } } } if ( m . getDef ( ) == null ) { System . out . println ( "" + m . getName ( ) + "" ) ; ISVDBChildItem top = m ; while ( top . getParent ( ) != null ) { top = top . getParent ( ) ; } System . out . println ( "" ) ; SVDBItemPrint . printItem ( top ) ; walkStack ( ) ; } if ( fDebugEn ) { debug ( "" + m . getDef ( ) ) ; } if ( m . getDef ( ) == null ) { System . out . println ( "" + m . getName ( ) + "" + m . getLocation ( ) . getLine ( ) + "" ) ; scanner . replace ( scanner . getOffset ( ) , scanner . getLimit ( ) , "" ) ; } else { scanner . replace ( scanner . getOffset ( ) , scanner . getLimit ( ) , m . getDef ( ) ) ; } if ( expand_params ) { expandParameterRefs ( new StringTextScanner ( scanner ) , param_names , params_vals ) ; } if ( ! referenced_params . contains ( m . getName ( ) ) ) { referenced_params . add ( m . getName ( ) ) ; expandMacroRefs ( new StringTextScanner ( scanner ) , referenced_params ) ; referenced_params . remove ( m . getName ( ) ) ; } else { } if ( fDebugEn ) { debug ( "" + scanner . getStorage ( ) . toString ( ) ) ; debug ( "" + m . getName ( ) + "" ) ; } } private List < String > parse_params ( SVDBMacroDef m , StringTextScanner scanner ) { if ( fDebugEn ) { debug ( "" + m . getName ( ) + "" ) ; debug ( "" + scanner . getStorage ( ) . substring ( scanner . getOffset ( ) ) ) ; } List < String > params = new ArrayList < String > ( ) ; int ch = scanner . get_ch ( ) ; for ( int i = ; i < m . getParameters ( ) . size ( ) ; i ++ ) { ch = scanner . skipWhite ( ch ) ; int p_start = scanner . getOffset ( ) - ; if ( ch == - ) { break ; } scanner . unget_ch ( ch ) ; do { ch = scanner . get_ch ( ) ; if ( ch == '' ) { ch = skipPastMatchSkipStrings ( scanner , '' , '' ) ; if ( fDebugEn ) { debug ( "" + ( char ) ch ) ; } } else if ( ch == '' ) { ch = skipPastMatchSkipStrings ( scanner , '' , '' ) ; if ( fDebugEn ) { debug ( "" + ( char ) ch ) ; } } else if ( ch == '' ) { while ( ( ch = scanner . get_ch ( ) ) != - && ch != '' && ch != '' ) { } if ( ch == '' ) { ch = scanner . get_ch ( ) ; } } } while ( ch != - && ch != '' && ch != '' ) ; int p_end = scanner . getOffset ( ) ; String param ; if ( scanner . getStorage ( ) . charAt ( p_start ) == '' ) { StringTextScanner scanner_s = new StringTextScanner ( new StringBuilder ( scanner . substring ( p_start , p_end - ) ) ) ; if ( fDebugEn ) { debug ( "" + scanner . substring ( p_start , p_end - ) + "" ) ; } if ( Character . isJavaIdentifierStart ( scanner . getStorage ( ) . charAt ( p_start + ) ) ) { expandMacro ( scanner_s ) ; } else { while ( ( ch = scanner_s . get_ch ( ) ) != - ) { if ( ch == '' ) { int ch2 = scanner_s . get_ch ( ) ; if ( ch2 == '' ) { scanner_s . delete ( scanner_s . getOffset ( ) - , scanner_s . getOffset ( ) ) ; } else { scanner_s . delete ( scanner_s . getOffset ( ) - , scanner_s . getOffset ( ) - ) ; } } } } param = scanner_s . getStorage ( ) . toString ( ) ; if ( fDebugEn ) { debug ( "" + param ) ; } } else { param = scanner . getStorage ( ) . substring ( p_start , p_end - ) ; if ( fDebugEn ) { debug ( "" + param ) ; } } params . add ( param . trim ( ) ) ; debug ( "" + ( char ) ch ) ; if ( ch == '' || ch == '' ) { if ( ch == '' ) { ch = scanner . get_ch ( ) ; break ; } ch = scanner . get_ch ( ) ; } } scanner . unget_ch ( ch ) ; if ( fDebugEn ) { for ( String s : params ) { debug ( "" + s + "" ) ; } debug ( "" + m . getName ( ) + "" + params . size ( ) + "" + ( char ) ch ) ; } return params ; } private void expandParameterRefs ( StringTextScanner scanner , List < String > param_names , List < String > param_vals ) { int ch ; if ( fDebugEn ) { for ( int i = ; i < param_names . size ( ) ; i ++ ) { debug ( "" + i + "" + param_names . get ( i ) + "" + param_vals . get ( i ) ) ; } debug ( "" ) ; debug ( "" + scanner . getStorage ( ) ) ; } int last_ch = - ; while ( ( ch = scanner . get_ch ( ) ) != - ) { if ( ch == '' && last_ch != '' ) { while ( ( ch = scanner . get_ch ( ) ) != - && ch != '' ) { } } else if ( ch == '' && last_ch == '' ) { scanner . replace ( scanner . getOffset ( ) - , scanner . getOffset ( ) , "" ) ; } else if ( Character . isJavaIdentifierStart ( ch ) ) { int p_start = scanner . getOffset ( ) - ; int p_end ; String key = scanner . readPreProcIdentifier ( ch ) ; debug ( "" + scanner . getOffset ( ) + "" + scanner . getLimit ( ) ) ; if ( scanner . getOffset ( ) >= scanner . getLimit ( ) && key . length ( ) == ) { debug ( "" ) ; p_end = scanner . getOffset ( ) ; } else { p_end = scanner . getOffset ( ) - ; } int index = param_names . indexOf ( key ) ; if ( index != - && index < param_vals . size ( ) ) { if ( fDebugEn ) { debug ( "" + key + "" + param_vals . get ( index ) + "" ) ; debug ( "" + p_start + "" + p_end + "" + ( scanner . getOffset ( ) - ) ) ; } scanner . replace ( p_start , p_end , param_vals . get ( index ) ) ; } } last_ch = ch ; } if ( fDebugEn ) { debug ( "" ) ; debug ( "" + scanner . getStorage ( ) ) ; } } private void expandMacroRefs ( StringTextScanner scanner , Set < String > referenced_params ) { int ch ; int iteration = ; int marker = - ; if ( fDebugEn ) { debug ( "" ) ; debug ( "" + scanner . getStorage ( ) . substring ( scanner . getOffset ( ) , scanner . getLimit ( ) ) ) ; } while ( ( ch = scanner . get_ch ( ) ) != - ) { iteration ++ ; if ( fDebugChEn ) { debug ( "" + ( char ) ch + "" ) ; } if ( ch == '' ) { int macro_start = scanner . getOffset ( ) - ; int ch2 = scanner . get_ch ( ) ; if ( fDebugChEn ) { debug ( "" + ( char ) ch2 + "" ) ; } if ( ch2 == '' ) { scanner . delete ( scanner . getOffset ( ) - , scanner . getOffset ( ) ) ; debug ( "" ) ; } else if ( ch2 == '' || ch2 == '' ) { scanner . delete ( scanner . getOffset ( ) - , scanner . getOffset ( ) - ) ; } else { int m_start = scanner . getOffset ( ) - ; ch = scanner . skipWhite ( ch2 ) ; if ( ! SVCharacter . isSVIdentifierStart ( ch ) ) { continue ; } String key = scanner . readPreProcIdentifier ( ch ) ; if ( key == null ) { fLog . error ( "" + ( char ) ch ) ; } if ( key . equals ( "" ) || key . equals ( "" ) ) { ch = scanner . skipWhite ( scanner . get_ch ( ) ) ; String condition = scanner . readPreProcIdentifier ( ch ) ; SVDBMacroDef cond_m = fMacroProvider . findMacro ( condition , fLineno ) ; scanner . delete ( macro_start , scanner . getOffset ( ) ) ; boolean en = ( fEnableOutputStack . peek ( ) && ( ( key . equals ( "" ) && cond_m != null ) || ( key . equals ( "" ) && cond_m == null ) ) ) ; if ( fEnableOutputStack . peek ( ) && ! en ) { marker = scanner . getOffset ( ) ; } fEnableOutputStack . push ( en ) ; } else if ( key . equals ( "" ) ) { ch = scanner . skipWhite ( scanner . get_ch ( ) ) ; scanner . readPreProcIdentifier ( ch ) ; scanner . delete ( macro_start , scanner . getOffset ( ) ) ; } else if ( key . equals ( "" ) ) { scanner . delete ( macro_start , scanner . getOffset ( ) ) ; if ( fEnableOutputStack . size ( ) > ) { boolean en = fEnableOutputStack . pop ( ) ; if ( marker != - && ! en && fEnableOutputStack . peek ( ) ) { scanner . delete ( marker , scanner . getOffset ( ) ) ; marker = - ; } else if ( marker == - && en && fEnableOutputStack . peek ( ) ) { marker = scanner . getOffset ( ) ; } fEnableOutputStack . push ( ! en ) ; } } else if ( key . equals ( "" ) ) { scanner . delete ( macro_start , scanner . getOffset ( ) ) ; if ( fEnableOutputStack . size ( ) > ) { boolean en = fEnableOutputStack . pop ( ) ; if ( marker != - && ! en && fEnableOutputStack . peek ( ) ) { scanner . delete ( marker , scanner . getOffset ( ) ) ; marker = - ; } } } else { SVDBMacroDef sub_m = fMacroProvider . findMacro ( key , fLineno ) ; List < String > sub_p = null ; ch = scanner . get_ch ( ) ; if ( fDebugEn ) { debug ( "" + key + "" ) ; } int m_end = scanner . getOffset ( ) ; if ( hasParameters ( key , fLineno ) ) { if ( fDebugEn ) { debug ( "" + key + "" ) ; } ch = scanner . skipWhite ( ch ) ; if ( ch == '' ) { if ( fDebugEn ) { debug ( "" + scanner . getStorage ( ) . substring ( scanner . getOffset ( ) ) + "" ) ; } expandMacroRefs ( new StringTextScanner ( scanner , scanner . getOffset ( ) ) , referenced_params ) ; sub_p = parse_params ( sub_m , scanner ) ; ch = scanner . get_ch ( ) ; } m_end = scanner . getOffset ( ) ; } else { debug ( "" + key + "" ) ; } if ( fDebugEn ) { debug ( "" + ( char ) ch ) ; } if ( ch != - ) { scanner . unget_ch ( ch ) ; m_end -- ; } if ( ( m_end - ) >= scanner . getStorage ( ) . length ( ) ) { System . out . println ( "" + m_end + "" + scanner . getStorage ( ) . length ( ) + "" + scanner . getOffset ( ) + "" + scanner . getLimit ( ) ) ; System . out . println ( "" + scanner . getStorage ( ) . toString ( ) ) ; System . out . println ( "" + iteration ) ; } if ( fDebugEn ) { debug ( "" + scanner . getStorage ( ) . charAt ( m_end - ) + "" ) ; } StringTextScanner scanner_s = new StringTextScanner ( scanner , m_start , m_end ) ; if ( sub_m != null ) { if ( ! referenced_params . contains ( key ) ) { referenced_params . add ( key ) ; if ( scanner . getOffset ( ) > scanner . getLimit ( ) ) { System . out . println ( "" + iteration ) ; System . out . println ( "" + sub_m . getName ( ) ) ; } expandMacro ( scanner_s , sub_m , sub_p , referenced_params ) ; referenced_params . remove ( key ) ; scanner . seek ( scanner_s . getOffset ( ) - ) ; if ( scanner . getOffset ( ) > scanner . getLimit ( ) ) { System . out . println ( "" + iteration ) ; System . out . println ( "" + sub_m . getName ( ) ) ; } } else { if ( fDebugEn ) { debug ( "" + key + "" ) ; } } } else { if ( fDebugEn ) { debug ( "" + key + "" + fFilename + "" + fLineno ) ; } scanner . delete ( m_start , m_end - ) ; walkStack ( ) ; } } } } } if ( fDebugEn ) { debug ( "" + scanner . getStorage ( ) ) ; debug ( "" ) ; } } public boolean hasParameters ( String key , int lineno ) { SVDBMacroDef m = fMacroProvider . findMacro ( key , lineno ) ; if ( m != null ) { return ( m . getParameters ( ) . size ( ) != ) ; } else { return false ; } } private void error ( String msg ) { for ( IPreProcErrorListener l : fErrorListeners ) { l . preProcError ( msg , fFilename , fLineno ) ; } } private void walkStack ( ) { String key ; Stack < String > tmp = new Stack < String > ( ) ; tmp . addAll ( fExpandStack ) ; fLog . debug ( "" ) ; while ( tmp . size ( ) > ) { key = tmp . pop ( ) ; fLog . debug ( "" + key ) ; } } private void debug ( String str ) { if ( fDebugEn ) { fLog . debug ( str ) ; } } } package net . sf . sveditor . core . scanner ; public class VerilogNumberParser { public static long parseLong ( String number ) throws NumberFormatException { int tick_index ; String p_number = number ; if ( ( tick_index = number . indexOf ( '' ) ) != - ) { p_number = number . substring ( tick_index ) ; } int radix = ; if ( p_number . startsWith ( "" ) ) { int radix_c = Character . toLowerCase ( p_number . charAt ( ) ) ; if ( radix_c == '' ) { radix = ; } else if ( radix_c == '' ) { radix = ; } else if ( radix_c == '' ) { radix = ; } else if ( radix_c == '' ) { radix = ; } else { System . out . println ( "" + ( char ) radix_c + "" ) ; } p_number = p_number . substring ( ) ; } if ( p_number . indexOf ( '' ) != - ) { p_number = p_number . replace ( "" , "" ) ; } return Long . parseLong ( p_number , radix ) ; } } package net . sf . sveditor . core . scanner ; public class SVCharacter { public static boolean isSVIdentifierStart ( int c ) { return ( Character . isJavaIdentifierStart ( c ) || c == '' ) ; } public static boolean isSVIdentifierPart ( int c ) { return ( Character . isJavaIdentifierPart ( c ) || c == '' ) ; } public static boolean isSVIdentifier ( String id ) { if ( id . length ( ) == ) { return false ; } if ( ! isSVIdentifierStart ( id . charAt ( ) ) ) { return false ; } for ( int i = ; i < id . length ( ) ; i ++ ) { if ( ! isSVIdentifierPart ( id . charAt ( i ) ) ) { return false ; } } return true ; } public static String toSVIdentifier ( String str ) { String id ; if ( SVCharacter . isSVIdentifierStart ( str . charAt ( ) ) ) { id = "" + str . charAt ( ) ; } else { id = "" ; } for ( int i = ; i < str . length ( ) ; i ++ ) { if ( SVCharacter . isSVIdentifierPart ( str . charAt ( i ) ) ) { id += str . charAt ( i ) ; } else { id += "" ; } } return id ; } } package net . sf . sveditor . core . scanner ; import net . sf . sveditor . core . db . SVDBMacroDef ; public interface IPreProcMacroProvider { SVDBMacroDef findMacro ( String name , int lineno ) ; void addMacro ( SVDBMacroDef macro ) ; void setMacro ( String key , String value ) ; } package net . sf . sveditor . core . scanner ; import java . io . File ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMacroDef ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SVFileTreeMacroProvider implements IPreProcMacroProvider { private ISVDBIndexCache fIndexCache ; private Map < String , SVDBMacroDef > fMacroCache ; private Set < String > fMissingIncludes ; private SVDBFileTree fContext ; private boolean fFirstSearch ; private int fLastLineno ; private LogHandle fLog ; private static final boolean fDebugEn = false ; public SVFileTreeMacroProvider ( ISVDBIndexCache cache , SVDBFileTree context , Set < String > missing_includes ) { fLog = LogFactory . getLogHandle ( "" ) ; fContext = context ; fIndexCache = cache ; fMacroCache = new HashMap < String , SVDBMacroDef > ( ) ; if ( missing_includes != null ) { fMissingIncludes = missing_includes ; } else { fMissingIncludes = new HashSet < String > ( ) ; } fFirstSearch = true ; fLastLineno = ; } public void addMacro ( SVDBMacroDef macro ) { if ( fMacroCache . containsKey ( macro . getName ( ) ) ) { fMacroCache . remove ( macro . getName ( ) ) ; } fMacroCache . put ( macro . getName ( ) , macro ) ; } public void setMacro ( String key , String value ) { if ( fMacroCache . containsKey ( key ) ) { fMacroCache . get ( key ) . setDef ( value ) ; } else { fMacroCache . put ( key , new SVDBMacroDef ( key , value ) ) ; } } public SVDBMacroDef findMacro ( String name , int lineno ) { if ( fFirstSearch ) { collectParentFileMacros ( ) ; fFirstSearch = false ; } if ( fLastLineno < lineno ) { collectThisFileMacros ( lineno ) ; fLastLineno = lineno ; } SVDBMacroDef m = fMacroCache . get ( name ) ; return m ; } private void collectParentFileMacros ( ) { List < SVDBFileTree > file_list = new ArrayList < SVDBFileTree > ( ) ; if ( fDebugEn ) { fLog . debug ( "" ) ; } if ( fContext == null ) { return ; } SVDBFileTree ib = fContext ; file_list . add ( ib ) ; while ( ib . getIncludedByFiles ( ) . size ( ) > ) { String ib_s = ib . getIncludedByFiles ( ) . get ( ) ; ib = fIndexCache . getFileTree ( new NullProgressMonitor ( ) , ib_s ) ; file_list . add ( ib ) ; } for ( int i = file_list . size ( ) - ; i > ; i -- ) { SVDBFile this_file = file_list . get ( i ) . getSVDBFile ( ) ; SVDBFile next_file = file_list . get ( i - ) . getSVDBFile ( ) ; if ( fDebugEn ) { fLog . enter ( "" + this_file . getName ( ) + "" + next_file . getName ( ) + "" ) ; } if ( this_file != null ) { collectMacroDefs ( file_list . get ( i ) , this_file , next_file ) ; } if ( fDebugEn ) { fLog . leave ( "" + this_file . getName ( ) + "" + next_file . getName ( ) + "" ) ; } } } private boolean collectMacroDefs ( SVDBFileTree file , ISVDBScopeItem scope , SVDBFile stop_pt ) { for ( ISVDBItemBase it : scope . getItems ( ) ) { if ( it . getType ( ) == SVDBItemType . MacroDef ) { addMacro ( ( SVDBMacroDef ) it ) ; } else if ( it . getType ( ) == SVDBItemType . Include ) { String leaf = ( ( ISVDBNamedItem ) it ) . getName ( ) ; if ( stop_pt != null && stop_pt . getName ( ) . endsWith ( ( ( ISVDBNamedItem ) it ) . getName ( ) ) ) { return true ; } else if ( ! fMissingIncludes . contains ( leaf ) ) { SVDBFileTree inc = null ; if ( fDebugEn ) { fLog . debug ( "" + file . getFilePath ( ) + "" + leaf ) ; } for ( String inc_s : file . getIncludedFiles ( ) ) { SVDBFileTree inc_t = fIndexCache . getFileTree ( new NullProgressMonitor ( ) , inc_s ) ; if ( inc_t != null ) { if ( fDebugEn ) { fLog . debug ( "" + inc_t . getFilePath ( ) ) ; } if ( inc_t . getFilePath ( ) . endsWith ( leaf ) ) { inc = inc_t ; break ; } } else { fLog . debug ( "" + inc_s + "" ) ; } } if ( inc != null ) { if ( inc . getSVDBFile ( ) != null ) { collectMacroDefs ( inc , inc . getSVDBFile ( ) , null ) ; } } else { fMissingIncludes . add ( leaf ) ; fLog . debug ( "" + leaf + "" ) ; if ( fDebugEn ) { for ( String inc_s : file . getIncludedFiles ( ) ) { fLog . debug ( "" + inc_s ) ; } } } } } else if ( it instanceof ISVDBScopeItem ) { if ( collectMacroDefs ( file , ( ISVDBScopeItem ) it , stop_pt ) ) { return true ; } } } return false ; } private void collectThisFileMacros ( int lineno ) { collectThisFileMacros ( fContext , fContext . getSVDBFile ( ) , lineno ) ; } private boolean collectThisFileMacros ( SVDBFileTree context , ISVDBScopeItem scope , int lineno ) { for ( ISVDBItemBase it : scope . getItems ( ) ) { if ( it . getLocation ( ) != null && it . getLocation ( ) . getLine ( ) > lineno && lineno != - ) { return false ; } else if ( it instanceof ISVDBScopeItem ) { if ( ! collectThisFileMacros ( context , ( ISVDBScopeItem ) it , lineno ) ) { return false ; } } else if ( it . getType ( ) == SVDBItemType . MacroDef ) { if ( fDebugEn ) { fLog . debug ( "" + ( ( ISVDBNamedItem ) it ) . getName ( ) + "" + ( ( ISVDBNamedItem ) scope ) . getName ( ) + "" + fContext . getFilePath ( ) ) ; } addMacro ( ( SVDBMacroDef ) it ) ; } else if ( it . getType ( ) == SVDBItemType . Include ) { if ( fDebugEn ) { fLog . debug ( "" + ( ( ISVDBNamedItem ) it ) . getName ( ) + "" + context . getFilePath ( ) ) ; } SVDBFileTree inc = null ; String it_leaf = new File ( ( ( ISVDBNamedItem ) it ) . getName ( ) ) . getName ( ) ; if ( ! fMissingIncludes . contains ( it_leaf ) ) { for ( String inc_s : context . getIncludedFiles ( ) ) { SVDBFileTree inc_t = fIndexCache . getFileTree ( new NullProgressMonitor ( ) , inc_s ) ; if ( inc_t != null ) { if ( fDebugEn ) { fLog . debug ( "" + inc_t . getFilePath ( ) + "" ) ; } String inc_t_leaf = new File ( inc_t . getFilePath ( ) ) . getName ( ) ; if ( inc_t_leaf . equals ( it_leaf ) ) { inc = inc_t ; break ; } } } if ( inc != null ) { if ( inc . getSVDBFile ( ) != null ) { collectThisFileMacros ( inc , inc . getSVDBFile ( ) , - ) ; } else { if ( fDebugEn ) { fLog . debug ( "" + inc . getFilePath ( ) + "" ) ; } } } else { fLog . error ( "" + ( ( ISVDBNamedItem ) it ) . getName ( ) + "" ) ; fMissingIncludes . add ( it_leaf ) ; if ( fDebugEn ) { for ( String inc_s : context . getIncludedFiles ( ) ) { fLog . debug ( "" + inc_s ) ; } } } } } } return true ; } } package net . sf . sveditor . core . evaluator ; public class SVEvalTFContext { } package net . sf . sveditor . core . evaluator ; public interface ISVEvalContext { ISVEvalContext getParent ( ) ; void setParent ( ISVEvalContext parent ) ; } package net . sf . sveditor . core . evaluator ; public class SVEvalGlobalContext { } package net . sf . sveditor . core . evaluator ; public class SVBehavioralBlockEvaluator { } package net . sf . sveditor . core . evaluator ; public class SVEvalVariable { } package net . sf . sveditor . core . objects ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . search . SVDBFindClassMatcher ; import net . sf . sveditor . core . db . search . SVDBFindInterfaceMatcher ; import net . sf . sveditor . core . db . search . SVDBFindModuleMatcher ; import net . sf . sveditor . core . db . search . SVDBFindPackageMatcher ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . NullProgressMonitor ; public class ObjectsTreeFactory { List < ISVDBIndex > fProjectIndexList ; private LogHandle fLog ; public ObjectsTreeFactory ( List < ISVDBIndex > projectIndexList ) { fProjectIndexList = projectIndexList ; fLog = LogFactory . getLogHandle ( "" ) ; } public ObjectsTreeNode build ( ) { if ( fProjectIndexList == null ) { return null ; } Map < String , SVDBDeclCacheItem > pkgMap = new HashMap < String , SVDBDeclCacheItem > ( ) ; Map < String , SVDBDeclCacheItem > globalPkgMap = new HashMap < String , SVDBDeclCacheItem > ( ) ; Map < String , SVDBDeclCacheItem > ifaceMap = new HashMap < String , SVDBDeclCacheItem > ( ) ; Map < String , SVDBDeclCacheItem > moduleMap = new HashMap < String , SVDBDeclCacheItem > ( ) ; ObjectsTreeNode topNode = new ObjectsTreeNode ( null , "" ) ; ObjectsTreeNode packagesNode = new ObjectsTreeNode ( topNode , ObjectsTreeNode . PACKAGES_NODE ) ; topNode . addChild ( packagesNode ) ; packagesNode . setItemDecl ( new SVDBDeclCacheItem ( null , null , ObjectsTreeNode . PACKAGES_NODE , SVDBItemType . PackageDecl , false ) ) ; ObjectsTreeNode rootPkgNode = new ObjectsTreeNode ( packagesNode , "" ) ; packagesNode . addChild ( rootPkgNode ) ; rootPkgNode . setItemDecl ( new SVDBDeclCacheItem ( null , null , "" , SVDBItemType . PackageDecl , false ) ) ; for ( ISVDBIndex svdbIndex : fProjectIndexList ) { List < SVDBDeclCacheItem > rootClasses = svdbIndex . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindClassMatcher ( ) ) ; if ( rootClasses != null ) { for ( SVDBDeclCacheItem rootClass : rootClasses ) { if ( rootClass . getName ( ) . matches ( "" ) ) { continue ; } if ( ! globalPkgMap . containsKey ( rootClass . getName ( ) ) ) { ObjectsTreeNode rootClassNode = new ObjectsTreeNode ( rootPkgNode , rootClass . getName ( ) , rootClass ) ; rootPkgNode . addChild ( rootClassNode ) ; globalPkgMap . put ( rootClass . getName ( ) , rootClass ) ; } } } } for ( ISVDBIndex svdbIndex : fProjectIndexList ) { List < SVDBDeclCacheItem > packages = svdbIndex . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindPackageMatcher ( ) ) ; if ( packages != null ) { for ( SVDBDeclCacheItem pkg : packages ) { if ( ! pkgMap . containsKey ( pkg . getName ( ) ) ) { ObjectsTreeNode pkgNode = new ObjectsTreeNode ( packagesNode , pkg . getName ( ) , pkg ) ; packagesNode . addChild ( pkgNode ) ; pkgMap . put ( pkg . getName ( ) , pkg ) ; List < SVDBDeclCacheItem > pkgDecls = svdbIndex . findPackageDecl ( new NullProgressMonitor ( ) , pkg ) ; if ( pkgDecls != null ) { fLog . debug ( "" + pkg . getName ( ) + "" ) ; for ( SVDBDeclCacheItem pkgDecl : pkgDecls ) { if ( pkgDecl . getType ( ) == SVDBItemType . ClassDecl ) { fLog . debug ( "" + pkgDecl . getName ( ) + "" ) ; ObjectsTreeNode pkgClassNode = new ObjectsTreeNode ( pkgNode , pkgDecl . getName ( ) , pkgDecl ) ; pkgNode . addChild ( pkgClassNode ) ; } } } else { fLog . debug ( "" + pkg . getName ( ) + "" ) ; } } } } } ObjectsTreeNode modulesNode = new ObjectsTreeNode ( topNode , ObjectsTreeNode . MODULES_NODE ) ; topNode . addChild ( modulesNode ) ; modulesNode . setItemDecl ( new SVDBDeclCacheItem ( null , null , ObjectsTreeNode . MODULES_NODE , SVDBItemType . ModuleDecl , false ) ) ; for ( ISVDBIndex svdbIndex : fProjectIndexList ) { List < SVDBDeclCacheItem > modules = svdbIndex . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindModuleMatcher ( ) ) ; if ( modules != null ) { for ( SVDBDeclCacheItem module : modules ) { if ( ! moduleMap . containsKey ( module . getName ( ) ) ) { ObjectsTreeNode moduleNode = new ObjectsTreeNode ( modulesNode , module . getName ( ) , module ) ; modulesNode . addChild ( moduleNode ) ; moduleMap . put ( module . getName ( ) , module ) ; } } } } ObjectsTreeNode interfacesNode = new ObjectsTreeNode ( topNode , ObjectsTreeNode . INTERFACES_NODE ) ; topNode . addChild ( interfacesNode ) ; interfacesNode . setItemDecl ( new SVDBDeclCacheItem ( null , null , ObjectsTreeNode . INTERFACES_NODE , SVDBItemType . InterfaceDecl , false ) ) ; for ( ISVDBIndex svdbIndex : fProjectIndexList ) { List < SVDBDeclCacheItem > interfaces = svdbIndex . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindInterfaceMatcher ( ) ) ; if ( interfaces != null ) { for ( SVDBDeclCacheItem iface : interfaces ) { if ( ! ifaceMap . containsKey ( iface . getName ( ) ) ) { ObjectsTreeNode ifaceNode = new ObjectsTreeNode ( interfacesNode , iface . getName ( ) , iface ) ; interfacesNode . addChild ( ifaceNode ) ; ifaceMap . put ( iface . getName ( ) , iface ) ; } } } } return topNode ; } } package net . sf . sveditor . core . objects ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; public class ObjectsTreeNode { private String fName ; private ObjectsTreeNode fParent ; private SVDBDeclCacheItem fItemDecl ; private List < ObjectsTreeNode > fChildren ; public static String MODULES_NODE = "" ; public static String INTERFACES_NODE = "" ; public static String PACKAGES_NODE = "" ; public static String ROOT_PKG = "" ; public ObjectsTreeNode ( ObjectsTreeNode parent , String name ) { fName = name ; fParent = parent ; fChildren = new ArrayList < ObjectsTreeNode > ( ) ; } public ObjectsTreeNode ( ObjectsTreeNode parent , String name , SVDBDeclCacheItem item ) { this ( parent , name ) ; fItemDecl = item ; } public String getName ( ) { return fName ; } public void setName ( String name ) { fName = name ; } public void addChild ( ObjectsTreeNode child ) { if ( ! fChildren . contains ( child ) ) { fChildren . add ( child ) ; } } public ObjectsTreeNode getChildByName ( String name ) { for ( ObjectsTreeNode child : getChildren ( ) ) { if ( child . getName ( ) . matches ( name ) ) { return child ; } } return null ; } public ObjectsTreeNode getParent ( ) { return fParent ; } public void setParent ( ObjectsTreeNode parent ) { fParent = parent ; } public List < ObjectsTreeNode > getChildren ( ) { return fChildren ; } public SVDBDeclCacheItem getItemDecl ( ) { return fItemDecl ; } public void setItemDecl ( SVDBDeclCacheItem cls ) { fItemDecl = cls ; } } package net . sf . sveditor . core . expr_utils ; import net . sf . sveditor . core . expr_utils . SVExprContext . ContextType ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . core . scanutils . IBIDITextScanner ; public class SVExprScanner { private boolean fDebugEn = true ; private LogHandle fLog ; public SVExprScanner ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } public SVExprContext extractExprContext ( IBIDITextScanner scanner , boolean leaf_scan_fwd ) { SVExprContext ret = new SVExprContext ( ) ; debug ( "" ) ; int c = - ; boolean scan_fwd = scanner . getScanFwd ( ) ; scanner . setScanFwd ( false ) ; c = scanner . get_ch ( ) ; debug ( "" + ( char ) c + "" ) ; scanner . unget_ch ( c ) ; scanner . setScanFwd ( scan_fwd ) ; if ( scanner . getScanFwd ( ) && scanner . getPos ( ) > ) { debug ( "" ) ; long pos = scanner . getPos ( ) ; scanner . seek ( pos - ) ; int prev_ch = scanner . get_ch ( ) ; if ( Character . isWhitespace ( prev_ch ) || prev_ch == '' || ( SVCharacter . isSVIdentifierPart ( c ) && ! SVCharacter . isSVIdentifierPart ( prev_ch ) ) ) { scanner . seek ( pos ) ; } else { scanner . seek ( pos - ) ; } } scanner . setScanFwd ( false ) ; c = scanner . get_ch ( ) ; debug ( "" + ( char ) c + "" ) ; scanner . unget_ch ( c ) ; if ( isInString ( scanner ) ) { debug ( "" ) ; ret . fType = ContextType . String ; ret . fLeaf = readString ( scanner , leaf_scan_fwd ) ; long seek = scanner . getPos ( ) ; scanner . setScanFwd ( true ) ; while ( ( c = scanner . get_ch ( ) ) != - && c != '' ) { } if ( c == '' ) { ret . fStart = ( int ) scanner . getPos ( ) ; } else { ret . fStart = ( int ) seek ; } scanner . seek ( seek ) ; if ( ret . fLeaf == null ) { ret . fLeaf = "" ; } scanner . setScanFwd ( false ) ; c = scanner . skipWhite ( scanner . get_ch ( ) ) ; debug ( "" + ret . fLeaf + "" + ( char ) c + "" ) ; if ( SVCharacter . isSVIdentifierPart ( c ) ) { String id = new StringBuilder ( scanner . readIdentifier ( c ) ) . reverse ( ) . toString ( ) ; debug ( "" + id + "" ) ; c = scanner . skipWhite ( scanner . get_ch ( ) ) ; debug ( "" + ( char ) c + "" ) ; if ( c == '' && id . equals ( "" ) ) { ret . fTrigger = "" ; ret . fRoot = "" ; } } } else { if ( SVCharacter . isSVIdentifierPart ( ( c = scanner . get_ch ( ) ) ) ) { debug ( "" + ( char ) c + "" ) ; scanner . unget_ch ( c ) ; String id = readIdentifier ( scanner , leaf_scan_fwd ) ; ret . fStart = ( int ) scanner . getPos ( ) + ; ret . fLeaf = id ; debug ( "" + id + "" ) ; ret . fTrigger = readTriggerStr ( scanner , true ) ; debug ( "" + ret . fTrigger + "" ) ; if ( ret . fTrigger != null && ! ret . fTrigger . equals ( "" ) ) { ret . fType = ContextType . Triggered ; ret . fRoot = readExpression ( scanner ) ; if ( ret . fRoot != null && ret . fRoot . trim ( ) . equals ( "" ) ) { ret . fRoot = null ; } } else if ( ret . fTrigger == null ) { ret . fType = ContextType . Untriggered ; c = scanner . skipWhite ( scanner . get_ch ( ) ) ; if ( c == '' ) { int c2 = scanner . get_ch ( ) ; if ( c2 != '' && c2 != '>' && c2 != '' && c2 != '' && c2 != '' && c2 != '' && c2 != '' ) { c = scanner . skipWhite ( c2 ) ; ret . fTrigger = "" ; } } if ( SVCharacter . isSVIdentifierPart ( c ) ) { scanner . unget_ch ( c ) ; ret . fRoot = readIdentifier ( scanner , false ) ; } } } else { debug ( "" + ( char ) c + "" ) ; scanner . unget_ch ( c ) ; ret . fStart = ( int ) scanner . getPos ( ) + ; if ( ( ret . fTrigger = readTriggerStr ( scanner , true ) ) != null ) { ret . fType = ContextType . Triggered ; if ( scan_fwd ) { scanner . setScanFwd ( true ) ; c = scanner . get_ch ( ) ; fLog . debug ( "" + ( char ) c + "" ) ; ret . fLeaf = readIdentifier ( scanner , true ) ; scanner . setScanFwd ( false ) ; c = scanner . get_ch ( ) ; fLog . debug ( "" + ( char ) c + "" ) ; } else { ret . fLeaf = "" ; } ret . fRoot = readExpression ( scanner ) ; } } } if ( ret . fType != ContextType . String ) { if ( ret . fRoot != null && ret . fRoot . equals ( "" ) ) { ret . fType = ContextType . Import ; } else { c = scanner . skipWhite ( scanner . get_ch ( ) ) ; if ( SVCharacter . isSVIdentifierPart ( c ) ) { scanner . unget_ch ( c ) ; String tmp = readIdentifier ( scanner , false ) ; fLog . debug ( "" + tmp . toString ( ) ) ; if ( tmp . equals ( "" ) ) { ret . fType = ContextType . Import ; } else if ( tmp . equals ( "" ) ) { ret . fType = ContextType . Extends ; } } } } debug ( "" ) ; if ( ret . fRoot != null && ret . fRoot . trim ( ) . equals ( "" ) ) { ret . fRoot = null ; } if ( ret . fRoot == null && ret . fTrigger == null && ret . fLeaf == null ) { ret . fLeaf = "" ; } return ret ; } private boolean isInString ( IBIDITextScanner scanner ) { boolean ret = false ; long sav_pos = scanner . getPos ( ) ; boolean scan_fwd = scanner . getScanFwd ( ) ; int ch ; scanner . setScanFwd ( false ) ; while ( ( ch = scanner . get_ch ( ) ) != - && ch != '' && ch != '' ) { } if ( ch == '' ) { ret = true ; while ( ( ch = scanner . get_ch ( ) ) != - && ch != '' && ch != '' ) { } if ( ch == '' ) { ret = false ; } } scanner . seek ( sav_pos ) ; scanner . setScanFwd ( scan_fwd ) ; return ret ; } private String readExpression ( IBIDITextScanner scanner ) { int ch ; String trigger = null ; fLog . debug ( "" ) ; scanner . setScanFwd ( false ) ; ch = scanner . skipWhite ( scanner . get_ch ( ) ) ; scanner . unget_ch ( ch ) ; long end_pos = scanner . getPos ( ) , start_pos ; do { ch = scanner . skipWhite ( scanner . get_ch ( ) ) ; fLog . debug ( "" + trigger + "" + ( char ) ch + "" ) ; if ( ch == '' ) { scanner . skipPastMatch ( "" ) ; fLog . debug ( "" + ( char ) ch ) ; ch = scanner . skipWhite ( scanner . get_ch ( ) ) ; if ( SVCharacter . isSVIdentifierPart ( ch ) ) { scanner . readIdentifier ( ch ) ; } else { scanner . unget_ch ( ch ) ; } } else if ( ch == '' ) { ch = scanner . skipPastMatch ( "" ) ; ch = scanner . skipWhite ( scanner . get_ch ( ) ) ; if ( SVCharacter . isSVIdentifierPart ( ch ) ) { scanner . readIdentifier ( ch ) ; } else { scanner . unget_ch ( ch ) ; } } else if ( SVCharacter . isSVIdentifierPart ( ch ) ) { scanner . readIdentifier ( ch ) ; } else { fLog . debug ( "" + ( char ) ch + "" ) ; start_pos = ( scanner . getPos ( ) + ) ; break ; } start_pos = ( scanner . getPos ( ) + ) ; } while ( ( trigger = readTriggerStr ( scanner , false ) ) != null ) ; fLog . debug ( "" ) ; return scanner . get_str ( start_pos , ( int ) ( end_pos - start_pos + ) ) . trim ( ) ; } private String readTriggerStr ( IBIDITextScanner scanner , boolean allow_colon ) { long start_pos = scanner . getPos ( ) ; scanner . setScanFwd ( false ) ; int ch = scanner . skipWhite ( scanner . get_ch ( ) ) ; if ( ch == '' || ch == '' ) { return "" + ( char ) ch ; } else if ( ch == '' ) { int ch2 = scanner . get_ch ( ) ; if ( ch2 == '' ) { return "" ; } else if ( allow_colon ) { return "" ; } } scanner . seek ( start_pos ) ; return null ; } private String readString ( IBIDITextScanner scanner , boolean scan_fwd ) { int ch ; long end_pos = scanner . getPos ( ) ; long start_pos = - , seek ; scanner . setScanFwd ( false ) ; while ( ( ch = scanner . get_ch ( ) ) != - && ch != '' && ch != '' ) { debug ( "" + ( char ) ch + "" ) ; } start_pos = scanner . getPos ( ) ; if ( ch == '' ) { seek = start_pos - ; start_pos += ; } else { seek = start_pos ; } if ( scan_fwd ) { scanner . setScanFwd ( true ) ; scanner . seek ( start_pos ) ; while ( ( ch = scanner . get_ch ( ) ) != - && ch != '' && ch != '' ) { } end_pos = ( scanner . getPos ( ) - ) ; if ( ch == '' ) { end_pos -- ; } } scanner . seek ( seek ) ; if ( start_pos >= && ( end_pos - start_pos ) > ) { return scanner . get_str ( start_pos , ( int ) ( end_pos - start_pos + ) ) ; } else { return "" ; } } private String readIdentifier ( IBIDITextScanner scanner , boolean scan_fwd ) { int ch ; fLog . debug ( "" + scan_fwd + "" ) ; long end_pos = ( scanner . getScanFwd ( ) ) ? scanner . getPos ( ) : ( scanner . getPos ( ) + ) ; long start_pos = - , seek ; scanner . setScanFwd ( false ) ; while ( ( ch = scanner . get_ch ( ) ) != - && SVCharacter . isSVIdentifierPart ( ch ) ) { } start_pos = scanner . getPos ( ) + ; seek = scanner . getPos ( ) + ; if ( scan_fwd ) { scanner . setScanFwd ( true ) ; scanner . seek ( start_pos ) ; while ( ( ch = scanner . get_ch ( ) ) != - && SVCharacter . isSVIdentifierPart ( ch ) ) { } end_pos = scanner . getPos ( ) - ; } scanner . seek ( seek ) ; fLog . debug ( "" + scan_fwd + "" ) ; return scanner . get_str ( start_pos , ( int ) ( end_pos - start_pos ) ) ; } private void debug ( String msg ) { if ( fDebugEn ) { fLog . debug ( msg ) ; } } } package net . sf . sveditor . core . expr_utils ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . ISVParser ; import net . sf . sveditor . core . parser . SVLexer ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . parser . SVParsers ; import net . sf . sveditor . core . scanutils . StringTextScanner ; public class SVExprUtilsParser implements ISVParser { private SVLexer fLexer ; private SVParsers fParsers ; private LogHandle fLog ; public SVExprUtilsParser ( SVExprContext context ) { this ( context , false ) ; } public SVExprUtilsParser ( SVExprContext context , boolean parse_full ) { StringBuilder content = new StringBuilder ( ) ; fLog = LogFactory . getLogHandle ( "" , ILogHandle . LOG_CAT_PARSER ) ; if ( context . fTrigger == null ) { content . append ( context . fLeaf ) ; } else { content . append ( context . fRoot ) ; if ( parse_full ) { content . append ( context . fTrigger ) ; content . append ( context . fLeaf ) ; } } fLexer = new SVLexer ( ) ; fLexer . init ( this , new StringTextScanner ( content ) ) ; fParsers = new SVParsers ( this ) ; fParsers . init ( this ) ; } public SVLexer lexer ( ) { return fLexer ; } public ILogHandle getLogHandle ( ) { return fLog ; } public void disableErrors ( boolean dis ) { } public void error ( String msg ) throws SVParseException { } public void error ( SVParseException e ) throws SVParseException { } public void warning ( String msg , int lineno ) { } public boolean error_limit_reached ( ) { return false ; } public SVParsers parsers ( ) { return fParsers ; } public void debug ( String msg , Exception e ) { } } package net . sf . sveditor . core . expr_utils ; public class SVExprItemInfo { private SVExprItemType fType ; private String fName ; public SVExprItemInfo ( SVExprItemType type , String name ) { fType = type ; fName = name ; } public SVExprItemType getType ( ) { return fType ; } public String getName ( ) { return fName ; } } package net . sf . sveditor . core . expr_utils ; public enum SVExprItemType { SubExpr , TypeId , TaskFunc , Id } package net . sf . sveditor . core . expr_utils ; public class SVExprContext { public enum ContextType { String , Untriggered , Triggered , Import , Extends } ; public int fStart ; public ContextType fType ; public String fRoot ; public String fLeaf ; public String fTrigger ; } package net . sf . sveditor . core . expr_utils ; import net . sf . sveditor . core . db . ISVDBItemBase ; public interface ISVItemResolver { ISVDBItemBase resolveItemScopeRelative ( String name ) ; ISVDBItemBase resolveItemBaseRelative ( ISVDBItemBase base , String name ) ; } package net . sf . sveditor . core . expr_utils ; import java . util . List ; import java . util . Stack ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . SVDBModportDecl ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . db . SVDBParamValueAssignList ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . expr . SVDBArrayAccessExpr ; import net . sf . sveditor . core . db . expr . SVDBAssignExpr ; import net . sf . sveditor . core . db . expr . SVDBCastExpr ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . expr . SVDBFieldAccessExpr ; import net . sf . sveditor . core . db . expr . SVDBIdentifierExpr ; import net . sf . sveditor . core . db . expr . SVDBParenExpr ; import net . sf . sveditor . core . db . expr . SVDBTFCallExpr ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . search . ISVDBFindNameMatcher ; import net . sf . sveditor . core . db . search . SVDBFindByName ; import net . sf . sveditor . core . db . search . SVDBFindByNameInClassHierarchy ; import net . sf . sveditor . core . db . search . SVDBFindByNameInScopes ; import net . sf . sveditor . core . db . search . SVDBFindNamedClass ; import net . sf . sveditor . core . db . search . SVDBFindParameterizedClass ; import net . sf . sveditor . core . db . search . SVDBFindSuperClass ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDimItem ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVContentAssistExprVisitor implements ILogLevel { private LogHandle fLog ; private ISVDBIndexIterator fIndexIt ; private ISVDBScopeItem fScope ; private ISVDBChildItem fClassScope ; private ISVDBFindNameMatcher fNameMatcher ; private Stack < ISVDBItemBase > fResolveStack ; private SVDBFindNamedClass fFindNamedClass ; private SVDBFindParameterizedClass fFindParameterizedClass ; private boolean fStaticAccess ; private class SVAbortException extends RuntimeException { private static final long serialVersionUID = ; public SVAbortException ( String msg ) { super ( msg ) ; } } public SVContentAssistExprVisitor ( ISVDBScopeItem scope , ISVDBFindNameMatcher name_matcher , ISVDBIndexIterator index_it ) { fLog = LogFactory . getLogHandle ( "" ) ; fResolveStack = new Stack < ISVDBItemBase > ( ) ; fScope = scope ; fNameMatcher = name_matcher ; fIndexIt = index_it ; fFindNamedClass = new SVDBFindNamedClass ( fIndexIt ) ; fFindParameterizedClass = new SVDBFindParameterizedClass ( fIndexIt ) ; classifyScope ( ) ; } private void classifyScope ( ) { ISVDBChildItem parent = fScope ; fClassScope = null ; if ( fScope == null ) { return ; } while ( parent != null && ! parent . getType ( ) . isElemOf ( SVDBItemType . ClassDecl , SVDBItemType . Covergroup ) ) { parent = parent . getParent ( ) ; } if ( parent != null ) { fClassScope = parent ; } else { if ( fScope . getType ( ) == SVDBItemType . Function || fScope . getType ( ) == SVDBItemType . Task ) { String name = ( ( SVDBTask ) fScope ) . getName ( ) ; int idx ; if ( ( idx = name . indexOf ( "" ) ) != - ) { String class_name = name . substring ( , idx ) ; fLog . debug ( "" + class_name ) ; List < SVDBClassDecl > result = fFindNamedClass . find ( class_name ) ; if ( result . size ( ) > ) { fClassScope = result . get ( ) ; } } } } } public ISVDBItemBase findItem ( SVDBExpr expr ) { fLog . debug ( "" ) ; fResolveStack . clear ( ) ; try { visit ( expr ) ; if ( fResolveStack . size ( ) > ) { return fResolveStack . pop ( ) ; } } catch ( SVAbortException e ) { e . printStackTrace ( ) ; } return null ; } public ISVDBItemBase findTypeItem ( SVDBExpr expr ) { fLog . debug ( "" + SVDBItem . getName ( fScope ) ) ; fResolveStack . clear ( ) ; try { visit ( expr ) ; if ( fResolveStack . size ( ) > ) { return findType ( fResolveStack . peek ( ) ) ; } } catch ( SVAbortException e ) { fLog . debug ( "" , e ) ; } return null ; } protected void visit ( SVDBExpr expr ) { fLog . debug ( "" + expr . getType ( ) ) ; switch ( expr . getType ( ) ) { case CastExpr : cast_expr ( ( SVDBCastExpr ) expr ) ; break ; case FieldAccessExpr : field_access_expr ( ( SVDBFieldAccessExpr ) expr ) ; break ; case ParamIdExpr : case IdentifierExpr : identifier_expr ( ( SVDBIdentifierExpr ) expr ) ; break ; case TFCallExpr : tf_call ( ( SVDBTFCallExpr ) expr ) ; break ; case ParenExpr : visit ( ( ( SVDBParenExpr ) expr ) . getExpr ( ) ) ; break ; case AssignExpr : assign_expr ( ( SVDBAssignExpr ) expr ) ; break ; case ArrayAccessExpr : array_access_expr ( ( SVDBArrayAccessExpr ) expr ) ; break ; case ClockingEventExpr : case ConcatenationExpr : case CondExpr : case CrossBinsSelectConditionExpr : case CtorExpr : case AssignmentPatternExpr : case AssignmentPatternRepeatExpr : case BinaryExpr : case RandomizeCallExpr : case RangeDollarBoundExpr : case RangeExpr : case UnaryExpr : case IncDecExpr : case InsideExpr : case LiteralExpr : case NamedArgExpr : case NullExpr : throw new SVAbortException ( "" + expr . getType ( ) ) ; default : throw new SVAbortException ( "" + expr . getType ( ) ) ; } } protected void cast_expr ( SVDBCastExpr expr ) { fLog . debug ( "" + expr . getCastType ( ) . toString ( ) ) ; } protected void field_access_expr ( SVDBFieldAccessExpr expr ) { fLog . debug ( "" + ( expr . isStaticRef ( ) ? "" : "" ) + "" ) ; visit ( expr . getExpr ( ) ) ; fStaticAccess = expr . isStaticRef ( ) ; visit ( expr . getLeaf ( ) ) ; fStaticAccess = false ; } private ISVDBItemBase findInScopeHierarchy ( String name ) { SVDBFindByNameInScopes finder = new SVDBFindByNameInScopes ( fIndexIt ) ; fLog . debug ( "" + ( ( fScope != null ) ? ( fScope . getType ( ) + "" + SVDBItem . getName ( fScope ) ) : "" ) ) ; List < ISVDBItemBase > items = finder . find ( fScope , name , false ) ; filterFwdDecls ( items ) ; if ( items . size ( ) > ) { return items . get ( ) ; } else { return null ; } } private ISVDBItemBase findInClassHierarchy ( ISVDBChildItem root , String name ) { fLog . debug ( "" + root . getType ( ) + "" + SVDBItem . getName ( root ) + "" + name ) ; if ( root . getType ( ) == SVDBItemType . Covergroup ) { fLog . debug ( "" ) ; List < SVDBClassDecl > l = fFindNamedClass . find ( "" ) ; if ( l . size ( ) > ) { root = l . get ( ) ; } else { return null ; } } SVDBFindByNameInClassHierarchy finder_h = new SVDBFindByNameInClassHierarchy ( fIndexIt , fNameMatcher ) ; List < ISVDBItemBase > items = finder_h . find ( root , name , fStaticAccess , ! fStaticAccess ) ; filterFwdDecls ( items ) ; if ( items . size ( ) > ) { return items . get ( ) ; } else { return null ; } } private ISVDBItemBase findInModuleInterface ( SVDBModIfcDecl root , String name ) { ISVDBItemBase ret = null ; fLog . debug ( "" + root . getType ( ) + "" + SVDBItem . getName ( root ) + "" + name ) ; for ( ISVDBChildItem c : root . getChildren ( ) ) { if ( c . getType ( ) == SVDBItemType . VarDeclStmt ) { for ( ISVDBChildItem i : ( ( SVDBVarDeclStmt ) c ) . getChildren ( ) ) { if ( fNameMatcher . match ( ( ISVDBNamedItem ) i , name ) ) { ret = i ; break ; } } } else if ( c . getType ( ) == SVDBItemType . ModIfcInst ) { for ( ISVDBChildItem i : ( ( SVDBModIfcInst ) c ) . getChildren ( ) ) { if ( fNameMatcher . match ( ( ISVDBNamedItem ) i , name ) ) { ret = i ; break ; } } } else if ( c . getType ( ) == SVDBItemType . ModportDecl ) { for ( ISVDBChildItem i : ( ( SVDBModportDecl ) c ) . getChildren ( ) ) { if ( fNameMatcher . match ( ( ISVDBNamedItem ) i , name ) ) { ret = i ; break ; } } } else if ( c instanceof ISVDBNamedItem ) { if ( fNameMatcher . match ( ( ISVDBNamedItem ) c , name ) ) { ret = c ; break ; } } } if ( ret == null ) { for ( SVDBParamPortDecl p : root . getPorts ( ) ) { for ( ISVDBChildItem i : p . getChildren ( ) ) { if ( fNameMatcher . match ( ( ISVDBNamedItem ) i , name ) ) { ret = i ; break ; } } } } return ret ; } private ISVDBItemBase findInTypeInfo ( SVDBTypeInfo root , String name ) { fLog . debug ( "" + root . getType ( ) + "" + SVDBItem . getName ( root ) + "" + name ) ; if ( root . getType ( ) . isElemOf ( SVDBItemType . TypeInfoStruct , SVDBItemType . TypeInfoUnion ) ) { ISVDBChildParent p = ( ISVDBChildParent ) root ; for ( ISVDBChildItem c : p . getChildren ( ) ) { if ( c . getType ( ) == SVDBItemType . VarDeclStmt ) { for ( ISVDBChildItem i : ( ( SVDBVarDeclStmt ) c ) . getChildren ( ) ) { if ( fNameMatcher . match ( ( ISVDBNamedItem ) i , name ) ) { return i ; } } } else if ( c instanceof ISVDBNamedItem ) { if ( fNameMatcher . match ( ( ISVDBNamedItem ) c , name ) ) { return c ; } } } } return null ; } private ISVDBItemBase findInPackage ( SVDBPackageDecl pkg , String name ) { ISVDBItemBase ret = null ; ISVDBChildItem c = pkg ; while ( c != null && c . getType ( ) != SVDBItemType . PackageDecl ) { c = c . getParent ( ) ; } for ( ISVDBChildItem pkg_item : pkg . getChildren ( ) ) { if ( pkg_item . getType ( ) == SVDBItemType . Include ) { } else if ( SVDBItem . getName ( pkg_item ) . equals ( name ) ) { ret = pkg_item ; break ; } } return ret ; } private ISVDBItemBase findType ( ISVDBItemBase item ) { SVDBTypeInfo type = null ; List < SVDBVarDimItem > var_dim = null ; fLog . debug ( "" + item . getType ( ) + "" + SVDBItem . getName ( item ) ) ; if ( item . getType ( ) == SVDBItemType . VarDeclItem ) { SVDBVarDeclItem var = ( SVDBVarDeclItem ) item ; SVDBVarDeclStmt stmt = var . getParent ( ) ; var_dim = var . getArrayDim ( ) ; type = stmt . getTypeInfo ( ) ; } else if ( item . getType ( ) == SVDBItemType . ClassDecl ) { fLog . debug ( "" + SVDBItem . getName ( item ) + "" ) ; return item ; } else if ( item . getType ( ) == SVDBItemType . PackageDecl ) { fLog . debug ( "" + SVDBItem . getName ( item ) + "" ) ; return item ; } else if ( item . getType ( ) == SVDBItemType . ModIfcInstItem ) { SVDBModIfcInstItem mod_ifc = ( SVDBModIfcInstItem ) item ; SVDBModIfcInst mod_ifc_p = ( SVDBModIfcInst ) mod_ifc . getParent ( ) ; type = mod_ifc_p . getTypeInfo ( ) ; } else if ( item . getType ( ) == SVDBItemType . TypedefStmt ) { type = ( ( SVDBTypedefStmt ) item ) . getTypeInfo ( ) ; } if ( type != null ) { fLog . debug ( "" + type . getType ( ) ) ; if ( type . getType ( ) == SVDBItemType . TypeInfoUserDef ) { item = findTypedef ( null , type . getName ( ) ) ; } else if ( type . getType ( ) == SVDBItemType . TypeInfoModuleIfc ) { item = findTypedef ( null , type . getName ( ) ) ; } else if ( type . getType ( ) . isElemOf ( SVDBItemType . TypeInfoStruct , SVDBItemType . TypeInfoUnion ) ) { item = type ; } while ( item != null && item . getType ( ) == SVDBItemType . TypedefStmt ) { fLog . debug ( "" + SVDBItem . getName ( item ) + "" ) ; SVDBTypedefStmt td = ( SVDBTypedefStmt ) item ; type = td . getTypeInfo ( ) ; if ( type . getType ( ) . isElemOf ( SVDBItemType . TypeInfoStruct , SVDBItemType . TypeInfoUnion ) ) { item = type ; } else if ( type . getType ( ) == SVDBItemType . TypeInfoUserDef ) { item = findTypedef ( null , type . getName ( ) ) ; } else { break ; } } if ( var_dim != null ) { if ( item != null ) { item = resolveArrayType ( item , SVDBItem . getName ( item ) , var_dim . get ( ) ) ; } } } else { fLog . debug ( "" ) ; } fLog . debug ( "" + ( ( item != null ) ? SVDBItem . getName ( item ) : "" ) ) ; return item ; } private ISVDBItemBase findTypedef ( ISVDBItemBase root , String name ) { ISVDBItemBase ret = null ; fLog . debug ( "" + name ) ; if ( name . indexOf ( '' ) != - ) { String type_elems [ ] = name . split ( "" ) ; ISVDBItemBase type_root = findRoot ( type_elems [ ] ) ; fLog . debug ( "" + type_root ) ; if ( type_root != null ) { int start_size = fResolveStack . size ( ) ; fResolveStack . push ( type_root ) ; identifier_expr ( new SVDBIdentifierExpr ( type_elems [ ] ) ) ; int end_size = fResolveStack . size ( ) ; fLog . debug ( "" + start_size + "" + end_size ) ; if ( end_size > ( start_size + ) ) { ret = fResolveStack . peek ( ) ; fResolveStack . setSize ( start_size ) ; } } fLog . debug ( "" + name + "" ) ; } else { if ( ( ret = findLocalTypedef ( name ) ) == null ) { SVDBFindByName finder_n = new SVDBFindByName ( fIndexIt ) ; List < ISVDBItemBase > item_l = finder_n . find ( name ) ; filterFwdDecls ( item_l ) ; if ( item_l . size ( ) > ) { ret = item_l . get ( ) ; } } } fLog . debug ( "" + ( ( ret != null ) ? SVDBItem . getName ( ret ) : "" ) ) ; return ret ; } private ISVDBItemBase findLocalTypedef ( String name ) { ISVDBItemBase ret = null ; fLog . debug ( "" + name ) ; ISVDBChildParent scope = fScope ; while ( scope != null && scope . getType ( ) != SVDBItemType . File ) { fLog . debug ( "" + SVDBItem . getName ( scope ) ) ; for ( ISVDBChildItem c : scope . getChildren ( ) ) { if ( c . getType ( ) == SVDBItemType . TypedefStmt && SVDBItem . getName ( c ) . equals ( name ) ) { ret = c ; } } ISVDBChildItem c = scope ; while ( ( c = c . getParent ( ) ) != null && ! ( c instanceof ISVDBChildParent ) ) { } if ( c != null ) { scope = ( ISVDBChildParent ) c ; } else { scope = null ; } } fLog . debug ( "" + SVDBItem . getName ( ret ) ) ; return ret ; } private ISVDBItemBase resolveArrayType ( ISVDBItemBase base , String base_type , SVDBVarDimItem var_dim ) { ISVDBItemBase ret = null ; SVDBTypeInfoUserDef target_type_info = null ; SVDBParamValueAssignList param_l = new SVDBParamValueAssignList ( ) ; fLog . debug ( "" + base + "" + base_type ) ; switch ( var_dim . getDimType ( ) ) { case Associative : fLog . debug ( "" ) ; target_type_info = new SVDBTypeInfoUserDef ( "" ) ; param_l . addParameter ( "" , base_type ) ; param_l . addParameter ( "" , var_dim . getExpr ( ) . toString ( ) ) ; break ; case Queue : fLog . debug ( "" ) ; target_type_info = new SVDBTypeInfoUserDef ( "" ) ; param_l . addParameter ( "" , base_type ) ; break ; case Sized : case Unsized : fLog . debug ( "" ) ; target_type_info = new SVDBTypeInfoUserDef ( "" ) ; param_l . addParameter ( "" , base_type ) ; break ; default : fLog . debug ( "" ) ; } target_type_info . setParameters ( param_l ) ; ret = fFindParameterizedClass . find ( target_type_info ) ; if ( ret == null ) { fLog . debug ( "" + target_type_info . getName ( ) ) ; } return ret ; } private ISVDBItemBase findRoot ( String id ) { ISVDBItemBase ret = null ; fLog . debug ( "" + id ) ; if ( id . equals ( "" ) || id . equals ( "" ) ) { if ( fClassScope != null ) { if ( id . equals ( "" ) ) { return fClassScope ; } else if ( fClassScope . getType ( ) == SVDBItemType . ClassDecl ) { SVDBFindSuperClass finder = new SVDBFindSuperClass ( fIndexIt ) ; return finder . find ( ( SVDBClassDecl ) fClassScope ) ; } } else { return null ; } } if ( ( ret = findInScopeHierarchy ( id ) ) != null ) { return ret ; } if ( fClassScope != null && ( ret = findInClassHierarchy ( fClassScope , id ) ) != null ) { return ret ; } List < SVDBClassDecl > cls_l = fFindNamedClass . find ( id ) ; if ( cls_l . size ( ) > ) { return cls_l . get ( ) ; } SVDBFindByName name_finder = new SVDBFindByName ( fIndexIt ) ; List < ISVDBItemBase > item_l = name_finder . find ( id ) ; filterFwdDecls ( item_l ) ; if ( item_l . size ( ) > ) { return item_l . get ( ) ; } return ret ; } protected void identifier_expr ( SVDBIdentifierExpr expr ) { fLog . debug ( "" + expr . getId ( ) ) ; if ( fResolveStack . size ( ) == ) { ISVDBItemBase item = findRoot ( expr . getId ( ) ) ; if ( item == null ) { String msg = "" + expr . getId ( ) + "" ; fLog . debug ( msg ) ; throw new SVAbortException ( msg ) ; } fResolveStack . push ( item ) ; } else { fLog . debug ( "" + expr . getId ( ) + "" + fResolveStack . peek ( ) + "" + SVDBItem . getName ( fResolveStack . peek ( ) ) ) ; ISVDBItemBase item = findType ( fResolveStack . peek ( ) ) ; if ( item == null ) { throw new SVAbortException ( "" + fResolveStack . peek ( ) . getType ( ) + "" ) ; } fLog . debug ( "" + SVDBItem . getName ( item ) ) ; if ( item . getType ( ) == SVDBItemType . PackageDecl ) { item = findInPackage ( ( SVDBPackageDecl ) item , expr . getId ( ) ) ; } else if ( item . getType ( ) . isElemOf ( SVDBItemType . TypeInfoStruct , SVDBItemType . TypeInfoUnion ) ) { item = findInTypeInfo ( ( SVDBTypeInfo ) item , expr . getId ( ) ) ; } else if ( item . getType ( ) == SVDBItemType . ModuleDecl || item . getType ( ) == SVDBItemType . InterfaceDecl ) { item = findInModuleInterface ( ( SVDBModIfcDecl ) item , expr . getId ( ) ) ; } else if ( item . getType ( ) == SVDBItemType . ModportItem ) { } else { item = findInClassHierarchy ( ( ISVDBChildItem ) item , expr . getId ( ) ) ; } if ( item == null ) { throw new SVAbortException ( "" + expr . getId ( ) + "" ) ; } fResolveStack . push ( item ) ; } } protected void tf_call ( SVDBTFCallExpr expr ) { fLog . debug ( "" ) ; if ( fResolveStack . size ( ) == ) { } else { } } protected void assign_expr ( SVDBAssignExpr expr ) { fLog . debug ( "" ) ; visit ( expr . getLhs ( ) ) ; visit ( expr . getRhs ( ) ) ; } protected void array_access_expr ( SVDBArrayAccessExpr expr ) { fLog . debug ( "" ) ; visit ( expr . getLhs ( ) ) ; if ( fResolveStack . size ( ) == ) { throw new SVAbortException ( "" ) ; } ISVDBItemBase item = fResolveStack . peek ( ) ; fLog . debug ( "" + item . getType ( ) ) ; if ( item . getType ( ) == SVDBItemType . VarDeclItem ) { SVDBVarDeclItem vi = ( ( SVDBVarDeclItem ) item ) . duplicate ( ) ; vi . setArrayDim ( null ) ; fResolveStack . push ( vi ) ; } } protected void filterFwdDecls ( List < ISVDBItemBase > items ) { for ( int i = ; i < items . size ( ) ; i ++ ) { if ( items . get ( i ) . getType ( ) == SVDBItemType . TypedefStmt ) { SVDBTypedefStmt td = ( SVDBTypedefStmt ) items . get ( i ) ; if ( td . getTypeInfo ( ) . getType ( ) != null && td . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoFwdDecl ) { items . remove ( i ) ; i -- ; } } } } } package net . sf . sveditor . core . open_decl ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . expr . SVDBExpr ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . search . SVDBFindDefaultNameMatcher ; import net . sf . sveditor . core . db . utils . SVDBSearchUtils ; import net . sf . sveditor . core . expr_utils . SVContentAssistExprVisitor ; import net . sf . sveditor . core . expr_utils . SVExprContext ; import net . sf . sveditor . core . expr_utils . SVExprScanner ; import net . sf . sveditor . core . expr_utils . SVExprUtilsParser ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . scanutils . IBIDITextScanner ; import org . eclipse . core . runtime . NullProgressMonitor ; public class OpenDeclUtils { public static List < Tuple < ISVDBItemBase , SVDBFile > > openDecl_2 ( SVDBFile file , int line , IBIDITextScanner scanner , ISVDBIndexIterator index_it ) { List < OpenDeclResult > result = openDecl ( file , line , scanner , index_it ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = new ArrayList < Tuple < ISVDBItemBase , SVDBFile > > ( ) ; for ( OpenDeclResult r : result ) { ret . add ( new Tuple < ISVDBItemBase , SVDBFile > ( r . getItem ( ) , r . getFile ( ) ) ) ; } return ret ; } public static List < OpenDeclResult > openDecl ( SVDBFile file , int line , IBIDITextScanner scanner , ISVDBIndexIterator index_it ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVExprScanner expr_scanner = new SVExprScanner ( ) ; SVDBFile inc_file = null ; log . debug ( ILogLevel . LEVEL_MID , "" + file . getFilePath ( ) + "" + line ) ; SVExprContext expr_ctxt = expr_scanner . extractExprContext ( scanner , true ) ; log . debug ( "" + expr_ctxt . fRoot + "" + expr_ctxt . fTrigger + "" + expr_ctxt . fLeaf ) ; ISVDBScopeItem active_scope = SVDBSearchUtils . findActiveScope ( file , line ) ; if ( active_scope != null ) { log . debug ( ILogLevel . LEVEL_MID , "" ) ; ISVDBChildItem i = active_scope ; String ind = "" ; while ( i != null ) { log . debug ( ILogLevel . LEVEL_MID , ind + SVDBItem . getName ( i ) + "" + i + "" + i . getParent ( ) ) ; if ( i . getType ( ) == SVDBItemType . File ) { log . debug ( ILogLevel . LEVEL_MID , "" + ( SVDBFile ) i + "" + file ) ; } ind += "" ; i = i . getParent ( ) ; } } else { log . debug ( ILogLevel . LEVEL_MID , "" ) ; } List < OpenDeclResult > ret = new ArrayList < OpenDeclResult > ( ) ; if ( expr_ctxt . fTrigger != null && expr_ctxt . fTrigger . equals ( "" ) ) { if ( expr_ctxt . fRoot != null && expr_ctxt . fRoot . equals ( "" ) ) { findMatchingIncludeFiles ( ret , expr_ctxt , index_it ) ; } else if ( expr_ctxt . fRoot == null ) { for ( SVDBDeclCacheItem it : index_it . findGlobalScopeDecl ( new NullProgressMonitor ( ) , expr_ctxt . fLeaf , SVDBFindDefaultNameMatcher . getDefault ( ) ) ) { if ( it . getType ( ) == SVDBItemType . MacroDef ) { ret . add ( new OpenDeclResult ( it . getFile ( ) , it . getFilePP ( ) , it . getSVDBItem ( ) ) ) ; } } } } else { SVExprUtilsParser expr_parser = new SVExprUtilsParser ( expr_ctxt , true ) ; SVDBExpr expr = null ; try { expr = expr_parser . parsers ( ) . exprParser ( ) . expression ( ) ; } catch ( SVParseException e ) { log . debug ( "" + e . getMessage ( ) , e ) ; } if ( expr != null ) { SVContentAssistExprVisitor v = new SVContentAssistExprVisitor ( active_scope , SVDBFindDefaultNameMatcher . getDefault ( ) , index_it ) ; ISVDBItemBase item = v . findItem ( expr ) ; if ( item != null ) { ret . add ( new OpenDeclResult ( inc_file , null , item ) ) ; } } } log . debug ( ILogLevel . LEVEL_MID , "" ) ; for ( OpenDeclResult r : ret ) { String ind = "" ; ISVDBItemBase i = r . getItem ( ) ; while ( i != null ) { log . debug ( ILogLevel . LEVEL_MID , ind + SVDBItem . getName ( i ) ) ; ind += "" ; if ( i instanceof ISVDBChildItem ) { i = ( ( ISVDBChildItem ) i ) . getParent ( ) ; } else { i = null ; } } } return ret ; } private static void findMatchingIncludeFiles ( List < OpenDeclResult > ret , SVExprContext expr_ctxt , ISVDBIndexIterator index_it ) { String target = expr_ctxt . fLeaf ; String leaf = target ; int idx = - ; if ( ( idx = leaf . lastIndexOf ( '' ) ) != - ) { leaf = leaf . substring ( idx + ) ; } while ( target . startsWith ( "" ) ) { target = target . substring ( ) ; } for ( String filename : index_it . getFileList ( new NullProgressMonitor ( ) ) ) { int f_idx = filename . lastIndexOf ( '' ) ; if ( f_idx == - ) { if ( filename . equals ( leaf ) ) { SVDBFile item = new SVDBFile ( filename ) ; ret . add ( new OpenDeclResult ( item , item , item ) ) ; } } else { if ( filename . endsWith ( target ) ) { SVDBFile item = new SVDBFile ( filename ) ; ret . add ( new OpenDeclResult ( item , item , item ) ) ; } } } } } package net . sf . sveditor . core . open_decl ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; public class OpenDeclResult { private SVDBFile fFile ; private SVDBFile fFilePP ; private ISVDBItemBase fItem ; public OpenDeclResult ( SVDBFile file , SVDBFile pp_file , ISVDBItemBase item ) { fFile = file ; fFilePP = pp_file ; fItem = item ; } public SVDBFile getFile ( ) { return fFile ; } public SVDBFile getFilePP ( ) { return fFilePP ; } public ISVDBItemBase getItem ( ) { return fItem ; } } package net . sf . sveditor . core ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfoClassType ; public class BuiltinClassConstants { public static final String Covergroup = "" ; public static final String Coverpoint = "" ; public static final String CoverpointCross = "" ; private static final Map < SVDBItemType , SVDBTypeInfoClassType > fBaseClassMap ; static { fBaseClassMap = new HashMap < SVDBItemType , SVDBTypeInfoClassType > ( ) ; fBaseClassMap . put ( SVDBItemType . Covergroup , new SVDBTypeInfoClassType ( Covergroup ) ) ; fBaseClassMap . put ( SVDBItemType . Coverpoint , new SVDBTypeInfoClassType ( Coverpoint ) ) ; } public static boolean hasBuiltin ( SVDBItemType type ) { return fBaseClassMap . containsKey ( type ) ; } public static SVDBTypeInfoClassType getBuiltinClass ( SVDBItemType type ) { return fBaseClassMap . get ( type ) ; } } package net . sf . sveditor . core . fileset ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . log . LogFactory ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; public class SVWorkspaceFileMatcher extends AbstractSVFileMatcher { public SVWorkspaceFileMatcher ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } @ Override public List < String > findIncludedPaths ( ) { final List < String > ret = new ArrayList < String > ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( SVFileSet fs : fFileSets ) { String base_location = fs . getBase ( ) ; if ( base_location . startsWith ( "" ) ) { base_location = base_location . substring ( "" . length ( ) ) ; } try { IResource base = root . findMember ( base_location ) ; if ( base == null ) { fLog . error ( "" + base_location + "" ) ; continue ; } if ( ! ( base instanceof IContainer ) ) { fLog . error ( "" + base_location + "" ) ; continue ; } base . refreshLocal ( IResource . DEPTH_INFINITE , null ) ; IContainer c = ( IContainer ) base ; recurse ( c , ret ) ; } catch ( CoreException e ) { } } return ret ; } private void recurse ( IContainer parent , List < String > paths ) throws CoreException { IResource member_l [ ] = parent . members ( ) ; if ( member_l != null ) { for ( IResource m : member_l ) { String full_path = m . getFullPath ( ) . toPortableString ( ) ; if ( m instanceof IContainer ) { if ( include_dir ( full_path ) ) { recurse ( ( IContainer ) m , paths ) ; } } else { if ( include_file ( full_path ) ) { String path = "" + full_path ; if ( ! paths . contains ( path ) ) { paths . add ( path ) ; } } } } } } } package net . sf . sveditor . core . fileset ; import java . util . ArrayList ; import java . util . List ; public class SVFileSet { protected String fBaseLocation ; protected List < String > fIncludes ; protected List < String > fExcludes ; public SVFileSet ( String base_location ) { fBaseLocation = base_location ; fIncludes = new ArrayList < String > ( ) ; fExcludes = new ArrayList < String > ( ) ; } public String getBase ( ) { return fBaseLocation ; } public void addInclude ( String inc ) { fIncludes . add ( inc ) ; } public void addExclude ( String exc ) { fExcludes . add ( exc ) ; } public List < String > getIncludes ( ) { return fIncludes ; } public List < String > getExcludes ( ) { return fExcludes ; } } package net . sf . sveditor . core . fileset ; import java . util . ArrayList ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import java . util . regex . PatternSyntaxException ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . log . LogHandle ; public abstract class AbstractSVFileMatcher { protected static Pattern fNormalizePathPattern ; protected boolean fPatternsValid ; protected List < FilePattern > fIncludePatterns ; protected List < FilePattern > fExcludePatterns ; protected List < SVFileSet > fFileSets ; protected LogHandle fLog ; private class FilePattern { public Pattern fDirMatchPattern ; public Pattern fFileMatchPattern ; } static { fNormalizePathPattern = Pattern . compile ( "" ) ; } public AbstractSVFileMatcher ( ) { fIncludePatterns = new ArrayList < FilePattern > ( ) ; fExcludePatterns = new ArrayList < FilePattern > ( ) ; fFileSets = new ArrayList < SVFileSet > ( ) ; fPatternsValid = false ; } public void addFileSet ( SVFileSet fs ) { fFileSets . add ( fs ) ; fPatternsValid = false ; } public abstract List < String > findIncludedPaths ( ) ; protected boolean include_dir ( String path ) { path = fNormalizePathPattern . matcher ( path ) . replaceAll ( "" ) ; if ( ! fPatternsValid ) { update_patterns ( ) ; fPatternsValid = true ; } boolean include = ( fIncludePatterns . size ( ) == ) ; for ( FilePattern p : fIncludePatterns ) { Matcher m = p . fDirMatchPattern . matcher ( path ) ; if ( m . matches ( ) ) { include = true ; break ; } } if ( include ) { boolean exclude = false ; for ( FilePattern p : fExcludePatterns ) { Matcher m = p . fDirMatchPattern . matcher ( path ) ; if ( m . matches ( ) ) { exclude = true ; break ; } } fLog . debug ( "" + path + "" + ( ( exclude ) ? "" : "" ) + "" ) ; return ! exclude ; } else { fLog . debug ( "" + path + "" ) ; return false ; } } protected boolean include_file ( String path ) { path = fNormalizePathPattern . matcher ( path ) . replaceAll ( "" ) ; if ( ! fPatternsValid ) { update_patterns ( ) ; fPatternsValid = true ; } boolean include = ( fIncludePatterns . size ( ) == ) ; for ( FilePattern p : fIncludePatterns ) { fLog . debug ( "" + path + "" + p . fFileMatchPattern . pattern ( ) ) ; Matcher m = p . fFileMatchPattern . matcher ( path ) ; if ( m . matches ( ) ) { include = true ; break ; } } if ( include ) { boolean exclude = false ; for ( FilePattern p : fExcludePatterns ) { Matcher m = p . fFileMatchPattern . matcher ( path ) ; if ( m . matches ( ) ) { exclude = true ; break ; } } fLog . debug ( "" + path + "" + ( ( exclude ) ? "" : "" ) + "" ) ; return ! exclude ; } else { fLog . debug ( "" + path + "" ) ; return false ; } } protected void update_patterns ( ) { fIncludePatterns . clear ( ) ; fExcludePatterns . clear ( ) ; for ( SVFileSet fs : fFileSets ) { for ( String inc : fs . getIncludes ( ) ) { try { fIncludePatterns . add ( create_pattern ( fs . getBase ( ) , inc ) ) ; } catch ( PatternSyntaxException e ) { fLog . error ( "" + fs . getBase ( ) + "" + inc , e ) ; } } for ( String exc : fs . getExcludes ( ) ) { try { FilePattern p = create_pattern ( fs . getBase ( ) , exc ) ; fExcludePatterns . add ( p ) ; } catch ( PatternSyntaxException e ) { fLog . error ( "" + fs . getBase ( ) + "" + exc , e ) ; } } } } private FilePattern create_pattern ( String base , String pattern ) { FilePattern p = new FilePattern ( ) ; if ( base . startsWith ( "" ) ) { base = base . substring ( "" . length ( ) ) ; } base = SVFileUtils . normalize ( base ) ; int last_slash = pattern . lastIndexOf ( "" ) ; if ( last_slash != - ) { String leaf = pattern . substring ( last_slash + ) ; String ext_dir_path = pattern . substring ( , last_slash ) ; p . fDirMatchPattern = Pattern . compile ( create_regexp ( base + "" + ext_dir_path ) , Pattern . CASE_INSENSITIVE ) ; p . fFileMatchPattern = Pattern . compile ( create_regexp ( base + "" + ext_dir_path + leaf ) , Pattern . CASE_INSENSITIVE ) ; } else { p . fDirMatchPattern = Pattern . compile ( create_regexp ( base ) , Pattern . CASE_INSENSITIVE ) ; p . fFileMatchPattern = Pattern . compile ( create_regexp ( base + "" + pattern ) , Pattern . CASE_INSENSITIVE ) ; } return p ; } private static String create_regexp ( String pattern ) { StringBuilder regexp = new StringBuilder ( ) ; regexp . setLength ( ) ; for ( int i = ; i < pattern . length ( ) ; i ++ ) { char ch = pattern . charAt ( i ) ; if ( ch == '' ) { regexp . append ( "" ) ; } else if ( ch == '' ) { if ( i + >= pattern . length ( ) || pattern . charAt ( i + ) != '' ) { regexp . append ( "" ) ; } else { regexp . append ( "" ) ; } } else { regexp . append ( ch ) ; } } return regexp . toString ( ) ; } } package net . sf . sveditor . core . fileset ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . log . LogFactory ; public class SVFilesystemFileMatcher extends AbstractSVFileMatcher { public SVFilesystemFileMatcher ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } @ Override public List < String > findIncludedPaths ( ) { List < String > ret = new ArrayList < String > ( ) ; for ( SVFileSet fs : fFileSets ) { File base = new File ( fs . getBase ( ) ) ; findIncludedPaths ( fs . getBase ( ) , ret , base ) ; } return ret ; } private void findIncludedPaths ( String base , List < String > paths , File parent ) { if ( parent . isFile ( ) ) { if ( include_file ( parent . getAbsolutePath ( ) ) ) { if ( ! paths . contains ( parent . getAbsolutePath ( ) ) ) { paths . add ( parent . getAbsolutePath ( ) ) ; } } } else { for ( File file : parent . listFiles ( ) ) { if ( file . isDirectory ( ) ) { if ( include_dir ( file . getAbsolutePath ( ) ) ) { findIncludedPaths ( base , paths , file ) ; } } else { if ( include_file ( file . getAbsolutePath ( ) ) ) { if ( ! paths . contains ( file . getAbsolutePath ( ) ) ) { paths . add ( file . getAbsolutePath ( ) ) ; } } } } } } } package net . sf . sveditor . core . hierarchy ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . search . SVDBFindByName ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class ModuleHierarchyTreeFactory { private ISVDBIndexIterator fIndexIt ; private SVDBFindByName fFinder ; private LogHandle fLog ; public ModuleHierarchyTreeFactory ( ISVDBIndexIterator index_it ) { fIndexIt = index_it ; fFinder = new SVDBFindByName ( fIndexIt ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public HierarchyTreeNode build ( SVDBModIfcDecl mod ) { return build_s ( null , mod , null ) ; } private HierarchyTreeNode build_s ( HierarchyTreeNode parent , SVDBModIfcDecl mod , SVDBModIfcInstItem inst_item ) { HierarchyTreeNode ret ; if ( inst_item != null ) { ret = new HierarchyTreeNode ( parent , inst_item . getName ( ) , inst_item , mod ) ; } else { ret = new HierarchyTreeNode ( parent , mod . getName ( ) , mod ) ; } for ( ISVDBItemBase it : mod . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . ModIfcInst ) { SVDBModIfcInst inst = ( SVDBModIfcInst ) it ; if ( inst . getTypeInfo ( ) == null ) { fLog . error ( "" + inst . getName ( ) + "" ) ; } List < ISVDBItemBase > it_l = fFinder . find ( inst . getTypeInfo ( ) . getName ( ) , SVDBItemType . ModuleDecl , SVDBItemType . InterfaceDecl ) ; for ( SVDBModIfcInstItem inst_i : inst . getInstList ( ) ) { if ( it_l . size ( ) > ) { HierarchyTreeNode n = build_s ( ret , ( SVDBModIfcDecl ) it_l . get ( ) , inst_i ) ; n . setItemDecl ( inst_i ) ; ret . addChild ( n ) ; } else if ( it instanceof ISVDBNamedItem ) { fLog . error ( "" + SVDBItem . getName ( it ) ) ; ret . addChild ( new HierarchyTreeNode ( ret , ( ( ISVDBNamedItem ) it ) . getName ( ) ) ) ; } } } } return ret ; } } package net . sf . sveditor . core . hierarchy ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; public class HierarchyTreeNode { private String fName ; private HierarchyTreeNode fParent ; private SVDBItem fItemDecl ; private ISVDBItemBase fItemType ; private List < HierarchyTreeNode > fChildren ; public HierarchyTreeNode ( HierarchyTreeNode parent , String name ) { fName = name ; fParent = parent ; fChildren = new ArrayList < HierarchyTreeNode > ( ) ; } public HierarchyTreeNode ( HierarchyTreeNode parent , String name , SVDBItem item ) { this ( parent , name ) ; fItemDecl = item ; } public HierarchyTreeNode ( HierarchyTreeNode parent , String name , SVDBItem item , ISVDBItemBase type ) { this ( parent , name ) ; fItemDecl = item ; fItemType = type ; } public String getName ( ) { return fName ; } public void setName ( String name ) { fName = name ; } public void addChild ( HierarchyTreeNode child ) { if ( ! fChildren . contains ( child ) ) { fChildren . add ( child ) ; } } public HierarchyTreeNode getParent ( ) { return fParent ; } public void setParent ( HierarchyTreeNode parent ) { fParent = parent ; } public List < HierarchyTreeNode > getChildren ( ) { return fChildren ; } public SVDBItem getItemDecl ( ) { return fItemDecl ; } public ISVDBItemBase getItemType ( ) { return fItemType ; } public void setItemDecl ( SVDBItem cls ) { fItemDecl = cls ; } } package net . sf . sveditor . core . hierarchy ; import java . util . List ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . refs . SVDBSubClassRefFinder ; import net . sf . sveditor . core . db . search . SVDBFindSuperClass ; public class ClassHierarchyTreeFactory { private ISVDBIndexIterator fIndexIt ; public ClassHierarchyTreeFactory ( ISVDBIndexIterator index_it ) { fIndexIt = index_it ; } public HierarchyTreeNode build ( SVDBClassDecl cls ) { HierarchyTreeNode target = new HierarchyTreeNode ( null , cls . getName ( ) , cls ) ; HierarchyTreeNode root = target ; SVDBFindSuperClass super_finder = new SVDBFindSuperClass ( fIndexIt ) ; SVDBClassDecl cls_t = cls , super_c ; while ( ( super_c = super_finder . find ( cls_t ) ) != null ) { HierarchyTreeNode old_root = root ; root = new HierarchyTreeNode ( null , super_c . getName ( ) , super_c ) ; old_root . setParent ( root ) ; root . addChild ( old_root ) ; cls_t = super_c ; } build_sub ( target ) ; return target ; } private void build_sub ( HierarchyTreeNode parent ) { List < SVDBClassDecl > sub_classes = SVDBSubClassRefFinder . find ( fIndexIt , parent . getName ( ) ) ; for ( SVDBClassDecl s : sub_classes ) { HierarchyTreeNode sn = new HierarchyTreeNode ( parent , s . getName ( ) , s ) ; parent . addChild ( sn ) ; build_sub ( sn ) ; } } } package net . sf . sveditor . doc . dev ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import java . util . Properties ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . sax . SAXTransformerFactory ; import javax . xml . transform . sax . TransformerHandler ; import javax . xml . transform . stream . StreamResult ; import org . apache . tools . ant . BuildException ; import org . apache . tools . ant . taskdefs . MatchingTask ; import org . apache . tools . ant . types . FileSet ; import org . apache . tools . ant . types . resources . FileResource ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; public class BuildJavaDocTocTask extends MatchingTask { private String fOutput ; private String fBase ; private String fLabel ; private List < FileSet > fFileSetList = new ArrayList < FileSet > ( ) ; private class PackageFileRef { public File fFile ; public String fPackage ; public PackageFileRef ( File file , String pkg ) { fFile = file ; fPackage = pkg ; } } private List < PackageFileRef > fPackageList = new ArrayList < PackageFileRef > ( ) ; public void setLabel ( String label ) { fLabel = label ; } public void setBase ( String base ) { fBase = base ; } public void setOutput ( String output ) { fOutput = output ; } public void addFileSet ( FileSet fs ) { fFileSetList . add ( fs ) ; } @ Override @ SuppressWarnings ( "" ) public void execute ( ) throws BuildException { for ( FileSet fs : fFileSetList ) { Iterator < FileResource > fr_i = ( Iterator < FileResource > ) fs . iterator ( ) ; while ( fr_i . hasNext ( ) ) { FileResource fr = fr_i . next ( ) ; String pkg_name = getPackageName ( fr . getFile ( ) ) ; fPackageList . add ( new PackageFileRef ( fr . getFile ( ) , pkg_name ) ) ; } } for ( int i = ; i < fPackageList . size ( ) ; i ++ ) { for ( int j = i + ; j < fPackageList . size ( ) ; j ++ ) { PackageFileRef r_i = fPackageList . get ( i ) ; PackageFileRef r_j = fPackageList . get ( j ) ; if ( r_i . fPackage . compareTo ( r_j . fPackage ) > ) { fPackageList . set ( i , r_j ) ; fPackageList . set ( j , r_i ) ; } } } try { DocumentBuilderFactory f = DocumentBuilderFactory . newInstance ( ) ; Document doc_o = f . newDocumentBuilder ( ) . newDocument ( ) ; FileOutputStream fos = new FileOutputStream ( fOutput ) ; Element toc = doc_o . createElement ( "" ) ; toc . setAttribute ( "" , fLabel ) ; doc_o . appendChild ( toc ) ; Element api_topic = doc_o . createElement ( "" ) ; api_topic . setAttribute ( "" , fLabel ) ; toc . appendChild ( api_topic ) ; for ( PackageFileRef r : fPackageList ) { Element package_topic = doc_o . createElement ( "" ) ; package_topic . setAttribute ( "" , r . fPackage ) ; package_topic . setAttribute ( "" , r . fFile . getAbsolutePath ( ) . substring ( fBase . length ( ) ) ) ; api_topic . appendChild ( package_topic ) ; } SAXTransformerFactory tf = ( SAXTransformerFactory ) SAXTransformerFactory . newInstance ( ) ; DOMSource ds = new DOMSource ( doc_o ) ; StreamResult sr = new StreamResult ( fos ) ; tf . setAttribute ( "" , new Integer ( ) ) ; TransformerHandler th = tf . newTransformerHandler ( ) ; Properties format = new Properties ( ) ; format . put ( OutputKeys . METHOD , "" ) ; format . put ( OutputKeys . ENCODING , "" ) ; format . put ( OutputKeys . INDENT , "" ) ; th . getTransformer ( ) . setOutputProperties ( format ) ; th . setResult ( sr ) ; th . getTransformer ( ) . transform ( ds , sr ) ; fos . close ( ) ; } catch ( Exception e ) { throw new BuildException ( e ) ; } } private String getPackageName ( File package_file ) throws BuildException { String pkg = null ; try { FileInputStream in = new FileInputStream ( package_file ) ; StringBuilder sb = new StringBuilder ( ) ; int ch = '' ; do { sb . setLength ( ) ; while ( ( ch = in . read ( ) ) != - && ch != '' ) { sb . append ( ( char ) ch ) ; } if ( sb . toString ( ) . startsWith ( "" ) ) { pkg = sb . toString ( ) . substring ( "" . length ( ) ) . trim ( ) ; break ; } } while ( ch != - ) ; in . close ( ) ; } catch ( Exception e ) { throw new BuildException ( e ) ; } return pkg ; } } package net . sf . sveditor . doc . dev ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Properties ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . TransformerConfigurationException ; import javax . xml . transform . TransformerException ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . sax . SAXTransformerFactory ; import javax . xml . transform . sax . TransformerHandler ; import javax . xml . transform . stream . StreamResult ; import org . apache . tools . ant . BuildException ; import org . apache . tools . ant . taskdefs . MatchingTask ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . ErrorHandler ; import org . xml . sax . SAXException ; import org . xml . sax . SAXParseException ; public class AssembleTocTask extends MatchingTask { private String [ ] fFiles ; private String fOutput = "" ; private String fLabel = "" ; public void setOutput ( String output ) { fOutput = output ; } public void setLabel ( String label ) { fLabel = label ; } public void setFiles ( String files ) { fFiles = files . split ( "" ) ; for ( int i = ; i < fFiles . length ; i ++ ) { fFiles [ i ] = fFiles [ i ] . trim ( ) ; } } @ Override public void execute ( ) throws BuildException { System . out . println ( "" ) ; try { run ( ) ; } catch ( Exception e ) { throw new BuildException ( e ) ; } } private void run ( ) throws IOException , ParserConfigurationException , SAXException , TransformerConfigurationException , TransformerException { DocumentBuilderFactory f = DocumentBuilderFactory . newInstance ( ) ; Document doc_o = f . newDocumentBuilder ( ) . newDocument ( ) ; FileOutputStream fos = new FileOutputStream ( fOutput ) ; Element toc = doc_o . createElement ( "" ) ; toc . setAttribute ( "" , fLabel ) ; doc_o . appendChild ( toc ) ; for ( String file : fFiles ) { InputStream in = new FileInputStream ( file ) ; DocumentBuilder b = f . newDocumentBuilder ( ) ; b . setErrorHandler ( fErrorHandler ) ; Document d = b . parse ( in ) ; Node toc_n = d . getFirstChild ( ) ; NodeList nl = toc_n . getChildNodes ( ) ; for ( int i = ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; System . out . println ( "" + n . getNodeName ( ) ) ; Node n_p = doc_o . importNode ( n , true ) ; toc . appendChild ( n_p ) ; } } SAXTransformerFactory tf = ( SAXTransformerFactory ) SAXTransformerFactory . newInstance ( ) ; DOMSource ds = new DOMSource ( doc_o ) ; StreamResult sr = new StreamResult ( fos ) ; tf . setAttribute ( "" , new Integer ( ) ) ; TransformerHandler th = tf . newTransformerHandler ( ) ; Properties format = new Properties ( ) ; format . put ( OutputKeys . METHOD , "" ) ; format . put ( OutputKeys . ENCODING , "" ) ; format . put ( OutputKeys . INDENT , "" ) ; th . getTransformer ( ) . setOutputProperties ( format ) ; th . setResult ( sr ) ; th . getTransformer ( ) . transform ( ds , sr ) ; fos . close ( ) ; } private ErrorHandler fErrorHandler = new ErrorHandler ( ) { public void warning ( SAXParseException arg0 ) throws SAXException { } public void fatalError ( SAXParseException arg0 ) throws SAXException { } public void error ( SAXParseException arg0 ) throws SAXException { } } ; } package net . sf . sveditor . core . uvm . templates ; import org . osgi . framework . BundleActivator ; import org . osgi . framework . BundleContext ; public class Activator implements BundleActivator { private static BundleContext context ; static BundleContext getContext ( ) { return context ; } public void start ( BundleContext bundleContext ) throws Exception { Activator . context = bundleContext ; } public void stop ( BundleContext bundleContext ) throws Exception { Activator . context = null ; } } package net . sf . sveditor . ui . tests ; import junit . framework . Test ; import junit . framework . TestSuite ; import net . sf . sveditor . core . tests . CoreReleaseTests ; public class AllReleaseTests extends TestSuite { public AllReleaseTests ( ) { addTest ( CoreReleaseTests . suite ( ) ) ; } public static Test suite ( ) { return new AllReleaseTests ( ) ; } } package net . sf . sveditor . ui . tests . editor ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . ui . editor . ISVEditor ; import net . sf . sveditor . ui . tests . UiReleaseTests ; import net . sf . sveditor . ui . tests . editor . utils . AutoEditTester ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; public class SVEditorTester implements ISVEditor { private IDocument fDoc ; private AutoEditTester fAutoEditTester ; private ISVDBIndexIterator fIndexIt ; private SVDBFile fSVDBFile ; private ITextSelection fTextSel ; public SVEditorTester ( AutoEditTester auto_ed , ISVDBIndexIterator index_it , SVDBFile file ) { fAutoEditTester = auto_ed ; fIndexIt = index_it ; fSVDBFile = file ; fTextSel = null ; } public SVEditorTester ( String doc , String filename ) throws BadLocationException { fAutoEditTester = UiReleaseTests . createAutoEditTester ( ) ; fAutoEditTester . setContent ( doc ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; fSVDBFile = factory . parse ( new StringInputStream ( doc ) , filename , markers ) ; fIndexIt = new FileIndexIterator ( fSVDBFile ) ; } public IDocument getDocument ( ) { if ( fAutoEditTester != null ) { return fAutoEditTester . getDocument ( ) ; } else { return fDoc ; } } public AutoEditTester getAutoEdit ( ) { return fAutoEditTester ; } public void setSelection ( ITextSelection sel ) { fTextSel = sel ; } public ISVDBIndexIterator getIndexIterator ( ) { return fIndexIt ; } public SVDBFile getSVDBFile ( ) { return fSVDBFile ; } public ITextSelection getTextSel ( ) { return fTextSel ; } } package net . sf . sveditor . ui . tests . editor ; import java . io . File ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBPath ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import net . sf . sveditor . ui . SVEditorUtil ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . editor . actions . OpenDeclarationAction ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IEditorReference ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PlatformUI ; public class TestUserLevelOperations extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testOpenClassDeclaration ( ) throws CoreException , InterruptedException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; cleanupWorkspace ( ) ; CoreReleaseTests . clearErrors ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File test_dir = new File ( fTmpDir , "" ) ; File db_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { assertTrue ( test_dir . delete ( ) ) ; } assertTrue ( test_dir . mkdirs ( ) ) ; if ( db_dir . exists ( ) ) { assertTrue ( db_dir . delete ( ) ) ; } assertTrue ( db_dir . mkdirs ( ) ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File xbus = new File ( test_dir , "" ) ; IProject project_dir = TestUtils . createProject ( "" , xbus ) ; SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData p_data = p_mgr . getProjectData ( project_dir ) ; SVProjectFileWrapper p_wrapper = p_data . getProjectFileWrapper ( ) . duplicate ( ) ; p_wrapper . getArgFilePaths ( ) . add ( new SVDBPath ( "" ) ) ; p_data . setProjectFileWrapper ( p_wrapper ) ; SVDBIndexCollection project_index = p_data . getProjectIndexMgr ( ) ; ISVDBItemIterator it = project_index . getItemIterator ( new NullProgressMonitor ( ) ) ; it . nextItem ( ) ; IEditorPart xbus_demo_tb = SVEditorUtil . openEditor ( "" ) ; assertNotNull ( xbus_demo_tb ) ; assertTrue ( ( xbus_demo_tb instanceof SVEditor ) ) ; SVEditor sveditor = ( SVEditor ) xbus_demo_tb ; while ( Display . getDefault ( ) . readAndDispatch ( ) ) { } OpenDeclarationAction od_action = ( OpenDeclarationAction ) sveditor . getAction ( SVUiPlugin . PLUGIN_ID + "" ) ; IDocument doc = sveditor . getDocument ( ) ; int idx = doc . get ( ) . indexOf ( "" ) ; sveditor . getSelectionProvider ( ) . setSelection ( new TextSelection ( idx , "" . length ( ) ) ) ; ISVDBIndexIterator index_it = sveditor . getIndexIterator ( ) ; System . out . println ( "" ) ; ISVDBItemIterator item_it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( item_it . hasNext ( ) ) { item_it . nextItem ( ) ; } System . out . println ( "" ) ; while ( Display . getDefault ( ) . readAndDispatch ( ) ) { } od_action . run ( ) ; while ( Display . getDefault ( ) . readAndDispatch ( ) ) { } SVEditor ovm_env = findEditor ( "" ) ; assertNotNull ( ovm_env ) ; SVDBFile ovm_env_f = ovm_env . getSVDBFile ( ) ; SVDBTestUtils . assertNoErrWarn ( ovm_env_f ) ; SVDBTestUtils . assertFileHasElements ( ovm_env_f , "" ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; } private void cleanupWorkspace ( ) throws CoreException { IWorkbenchWindow w = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; for ( IWorkbenchPage p : w . getPages ( ) ) { p . closeAllEditors ( true ) ; } IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( IProject p : root . getProjects ( ) ) { p . delete ( true , new NullProgressMonitor ( ) ) ; } } private SVEditor findEditor ( String path ) { SVEditor ret = null ; IWorkbenchWindow w = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; for ( IWorkbenchPage p : w . getPages ( ) ) { for ( IEditorReference ed : p . getEditorReferences ( ) ) { if ( ed . getName ( ) . endsWith ( path ) ) { IEditorPart ed_p = ed . getEditor ( true ) ; if ( ed_p instanceof SVEditor ) { ret = ( SVEditor ) ed_p ; break ; } } } } return ret ; } } package net . sf . sveditor . ui . tests . editor ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . tests . indent . IndentComparator ; import net . sf . sveditor . ui . tests . UiReleaseTests ; import net . sf . sveditor . ui . tests . editor . utils . AutoEditTester ; import org . eclipse . jface . text . BadLocationException ; public class TestAutoIndent extends TestCase { public void testBasicIndent ( ) throws BadLocationException { AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( "" ) ; tester . type ( "" ) ; tester . type ( "" ) ; tester . type ( "" ) ; tester . type ( "" ) ; tester . type ( "" ) ; String content = tester . getContent ( ) ; String expected = "" + "" + "" + "" + "" + "" + "" + "" ; System . out . println ( "" + content ) ; IndentComparator . compare ( "" , expected , content ) ; } public void testAutoIndentAlways ( ) throws BadLocationException { AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; String content = "" + "" + "" + "" + "" + "" ; tester . type ( content ) ; String result = tester . getContent ( ) ; String expected = "" + "" + "" + "" + "" + "" ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testAutoPostSingleComment ( ) throws BadLocationException { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( content ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testPaste ( ) throws BadLocationException { String first = "" + "" + "" ; String text = "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( first ) ; tester . paste ( text ) ; String content = tester . getContent ( ) ; System . out . println ( "" + content ) ; IndentComparator . compare ( "" , expected , content ) ; } public void testPasteModule ( ) throws BadLocationException { String first = "" + "" + "" ; String text = "" + "" ; String expected = "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( first ) ; tester . setCaretOffset ( first . length ( ) ) ; tester . paste ( text ) ; String content = tester . getContent ( ) ; System . out . println ( "" + content + "" ) ; IndentComparator . compare ( "" , expected , content ) ; } public void testPasteAlwaysComb ( ) throws BadLocationException { String content = "" + "" + "" + "" + "" + "" + "" ; String paste = "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( content ) ; String result ; result = tester . getContent ( ) ; IndentComparator . compare ( "" , "" + "" + "" + "" + "" + "" + "" , result ) ; tester . setCaretOffset ( ( "" + "" ) . length ( ) + ) ; tester . paste ( paste ) ; result = tester . getContent ( ) ; System . out . println ( "" + result + "" ) ; IndentComparator . compare ( "" , "" + "" + "" + "" + "" + "" + "" + "" + "" , result ) ; } public void testModuleWires ( ) throws BadLocationException { String content = "" + "" + "" + "" ; String expected = "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( content ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testModuleWiresPastePost ( ) throws BadLocationException { String content = "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( content ) ; tester . paste ( "" + "" + "" + "" ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testPasteInModule ( ) throws BadLocationException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String first = "" + "" + "" ; String text = "" ; String expected = "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . setContent ( first ) ; tester . setCaretOffset ( ( "" + "" ) . length ( ) ) ; tester . paste ( text ) ; String content = tester . getContent ( ) ; System . out . println ( "" + content ) ; IndentComparator . compare ( "" , expected , content ) ; } public void testPasteModuleNoCR ( ) throws BadLocationException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String first = "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . paste ( first ) ; first += "" ; String content = tester . getContent ( ) ; System . out . println ( "" + content ) ; System . out . println ( "" + first ) ; IndentComparator . compare ( "" , first , content ) ; } public void testAutoIndentIfThenElse ( ) throws BadLocationException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( content ) ; String result = tester . getContent ( ) ; System . out . println ( "" + content ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testCovergroup ( ) throws BadLocationException { String input = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testVirtualFunction ( ) throws BadLocationException { String input1 = "" + "" + "" + "" + "" ; String input2 = "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input1 ) ; tester . type ( input2 ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testPastePostStringAdaptiveIndent ( ) throws BadLocationException { AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; String content = "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" ; tester . setContent ( content ) ; tester . paste ( "" + "" + "" ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testPasteAdaptiveIndent ( ) throws BadLocationException { AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; String content = "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" ; tester . setContent ( content ) ; tester . paste ( "" + "" + "" ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testPasteInsertOpeningComment ( ) throws BadLocationException { String input = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . setContent ( input ) ; tester . setCaretOffset ( ) ; while ( true ) { String line = tester . readLine ( ) ; System . out . println ( "" + line + "" ) ; if ( line . trim ( ) . startsWith ( "" ) ) { break ; } } tester . paste ( "" ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } public void disabled_testCaseStatement ( ) throws BadLocationException { String input = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input ) ; String result = tester . getContent ( ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testBasedEmptyEnumIndent ( ) throws BadLocationException { String input = "" + "" + "" ; String expected = "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input ) ; String result = tester . getContent ( ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testEnumForwardDeclIndent ( ) throws BadLocationException { String input = "" + "" + "" ; String expected = "" + "" + "" ; ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input ) ; String result = tester . getContent ( ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testBasedEnumIndent ( ) throws BadLocationException { String input = "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input ) ; String result = tester . getContent ( ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testBasicEnumDecl ( ) throws BadLocationException { String input = "" + "" + "" + "" ; String expected = "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input ) ; String result = tester . getContent ( ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testProperIndentEndPackage ( ) throws BadLocationException { String input = "" + "" + "" + "" + "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; } public void disabled_testModifyIndent ( ) throws BadLocationException { int offset1 , offset2 ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( "" ) ; tester . type ( "" ) ; tester . type ( "" ) ; offset1 = tester . getCaretOffset ( ) ; tester . type ( "" ) ; offset2 = tester . getCaretOffset ( ) ; tester . setCaretOffset ( offset1 ) ; tester . type ( "" ) ; tester . setCaretOffset ( offset2 + ) ; System . out . println ( "" + ( offset2 + ) + "" + tester . getChar ( ) + "" ) ; tester . type ( "" ) ; tester . type ( "" ) ; tester . type ( "" ) ; String content = tester . getContent ( ) ; String expected = "" + "" + "" + "" + "" + "" + "" + "" ; System . out . println ( "" + content ) ; assertEquals ( "" , expected , content ) ; } public void testMoveLineDown ( ) throws BadLocationException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String input = "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" ; AutoEditTester tester = UiReleaseTests . createAutoEditTester ( ) ; tester . type ( input ) ; String content = tester . getContent ( ) ; int idx = content . indexOf ( "" ) ; while ( content . indexOf ( idx ) != '' ) { idx -- ; } tester . setCaretOffset ( idx + ) ; System . out . println ( "" ) ; tester . type ( '' ) ; System . out . println ( "" ) ; String result = tester . getContent ( ) ; System . out . println ( "" + result ) ; IndentComparator . compare ( "" , expected , result ) ; } } package net . sf . sveditor . ui . tests . editor . utils ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . IDocument ; class TestDocumentCommand extends DocumentCommand { public TestDocumentCommand ( int offset , int length , String text ) { super ( ) ; doit = true ; this . text = text ; this . offset = offset ; this . length = length ; owner = null ; caretOffset = - ; } public int exec ( IDocument doc ) throws BadLocationException { doc . replace ( offset , length , text ) ; return caretOffset != - ? caretOffset : offset + ( text == null ? : text . length ( ) ) ; } } package net . sf . sveditor . ui . tests . editor . utils ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IAutoEditStrategy ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextUtilities ; public class AutoEditTester { private Map < String , IAutoEditStrategy > fStrategyMap = new HashMap < String , IAutoEditStrategy > ( ) ; private IDocument fDoc ; private String fPartitioning ; private int fCaretOffset ; public AutoEditTester ( IDocument doc , String partitioning ) { super ( ) ; fDoc = doc ; fPartitioning = partitioning ; } public IDocument getDocument ( ) { return fDoc ; } public void setAutoEditStrategy ( String contentType , IAutoEditStrategy aes ) { fStrategyMap . put ( contentType , aes ) ; } public IAutoEditStrategy getAutoEditStrategy ( String contentType ) { return ( IAutoEditStrategy ) fStrategyMap . get ( contentType ) ; } public void reset ( ) { try { goTo ( , ) ; fDoc . set ( "" ) ; } catch ( BadLocationException ble ) { TestCase . fail ( ble . getMessage ( ) ) ; } } public void type ( String text ) throws BadLocationException { for ( int i = ; i < text . length ( ) ; ++ i ) { type ( text . charAt ( i ) ) ; } } public void type ( char c ) throws BadLocationException { TestDocumentCommand command = new TestDocumentCommand ( fCaretOffset , , new String ( new char [ ] { c } ) ) ; customizeDocumentCommand ( command ) ; fCaretOffset = command . exec ( fDoc ) ; } private void customizeDocumentCommand ( TestDocumentCommand command ) throws BadLocationException { IAutoEditStrategy aes = getAutoEditStrategy ( getContentType ( ) ) ; if ( aes != null ) { aes . customizeDocumentCommand ( fDoc , command ) ; } } public void type ( int offset , String text ) throws BadLocationException { fCaretOffset = offset ; type ( text ) ; } public void type ( int offset , char c ) throws BadLocationException { fCaretOffset = offset ; type ( c ) ; } public void paste ( String text ) throws BadLocationException { TestDocumentCommand command = new TestDocumentCommand ( fCaretOffset , , text ) ; customizeDocumentCommand ( command ) ; fCaretOffset = command . exec ( fDoc ) ; } public void paste ( int offset , String text ) throws BadLocationException { fCaretOffset = offset ; paste ( text ) ; } public void backspace ( int n ) throws BadLocationException { for ( int i = ; i < n ; ++ i ) { backspace ( ) ; } } public void backspace ( ) throws BadLocationException { TestDocumentCommand command = new TestDocumentCommand ( fCaretOffset - , , "" ) ; customizeDocumentCommand ( command ) ; fCaretOffset = command . exec ( fDoc ) ; } public int getCaretOffset ( ) { return fCaretOffset ; } public int setCaretOffset ( int offset ) { fCaretOffset = offset ; if ( fCaretOffset < ) fCaretOffset = ; else if ( fCaretOffset > fDoc . getLength ( ) ) fCaretOffset = fDoc . getLength ( ) ; return fCaretOffset ; } public int moveCaret ( int shift ) { return setCaretOffset ( fCaretOffset + shift ) ; } public int goTo ( int line ) throws BadLocationException { fCaretOffset = fDoc . getLineOffset ( line ) ; return fCaretOffset ; } public int goTo ( int line , int column ) throws BadLocationException { if ( column < || column > fDoc . getLineLength ( line ) ) { throw new BadLocationException ( "" + column + "" + line ) ; } fCaretOffset = fDoc . getLineOffset ( line ) + column ; return fCaretOffset ; } public int getCaretLine ( ) throws BadLocationException { return fDoc . getLineOfOffset ( fCaretOffset ) ; } public int getCaretColumn ( ) throws BadLocationException { IRegion region = fDoc . getLineInformationOfOffset ( fCaretOffset ) ; return fCaretOffset - region . getOffset ( ) ; } public char getChar ( ) throws BadLocationException { return getChar ( ) ; } public char getChar ( int i ) throws BadLocationException { return fDoc . getChar ( fCaretOffset + i ) ; } public String getLine ( ) throws BadLocationException { return getLine ( ) ; } public String readLine ( ) throws BadLocationException { IRegion region = fDoc . getLineInformation ( getCaretLine ( ) ) ; String ret = fDoc . get ( region . getOffset ( ) , region . getLength ( ) ) ; fCaretOffset = region . getOffset ( ) + region . getLength ( ) + ; return ret ; } public String getLine ( int i ) throws BadLocationException { IRegion region = fDoc . getLineInformation ( getCaretLine ( ) + i ) ; return fDoc . get ( region . getOffset ( ) , region . getLength ( ) ) ; } public void setContent ( String content ) throws BadLocationException { fDoc . set ( content ) ; fCaretOffset = fDoc . getLength ( ) - ; } public String getContent ( ) throws BadLocationException { return fDoc . get ( ) ; } public String getContentType ( ) throws BadLocationException { return getContentType ( ) ; } public String getContentType ( int i ) throws BadLocationException { return TextUtilities . getContentType ( fDoc , fPartitioning , fCaretOffset + i , false ) ; } } package net . sf . sveditor . ui . tests . editor ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . srcgen . OverrideMethodsFinder ; import net . sf . sveditor . core . tests . TextTagPosUtils ; import net . sf . sveditor . core . tests . indent . IndentComparator ; import net . sf . sveditor . ui . editor . actions . IOverrideMethodsTargetProvider ; import net . sf . sveditor . ui . editor . actions . OverrideTaskFuncImpl ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . TextSelection ; public class TestOverrideMethods extends TestCase { public void testOverrideFunction ( ) throws BadLocationException { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; core_testOverrideAll ( "" , doc , expected , "" ) ; } public void testVirtualFunction ( ) throws BadLocationException { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; core_testOverrideAll ( "" , doc , expected , "" ) ; } public void testOverrideRefArgTask ( ) throws BadLocationException { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; core_testOverrideAll ( "" , doc , expected , "" ) ; } public void testOverrideInOutTask ( ) throws BadLocationException { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; core_testOverrideAll ( "" , doc , expected , "" ) ; } public void core_testOverrideAll ( String test_name , String doc , String expected , String extension_class_name ) throws BadLocationException { TextTagPosUtils tag_utils = new TextTagPosUtils ( doc ) ; SVEditorTester sve_tester = new SVEditorTester ( tag_utils . getStrippedData ( ) , "" ) ; ITextSelection sel = new TextSelection ( sve_tester . getDocument ( ) , tag_utils . getTagPos ( "" ) , ) ; sve_tester . getAutoEdit ( ) . setCaretOffset ( tag_utils . getTagPos ( "" ) ) ; sve_tester . setSelection ( sel ) ; SVDBClassDecl extension = null ; SVDBClassDecl base = null ; for ( ISVDBItemBase it : sve_tester . getSVDBFile ( ) . getItems ( ) ) { if ( SVDBItem . getName ( it ) . equals ( extension_class_name ) ) { extension = ( SVDBClassDecl ) it ; } } assertNotNull ( extension ) ; for ( ISVDBItemBase it : sve_tester . getSVDBFile ( ) . getItems ( ) ) { if ( SVDBItem . getName ( it ) . equals ( extension . getSuperClass ( ) ) ) { base = ( SVDBClassDecl ) it ; } } assertNotNull ( base ) ; OverrideMethodsFinder finder = new OverrideMethodsFinder ( extension , sve_tester . getIndexIterator ( ) ) ; final List < SVDBTask > targets = finder . getMethods ( base ) ; OverrideTaskFuncImpl override = new OverrideTaskFuncImpl ( sve_tester , new IOverrideMethodsTargetProvider ( ) { @ Override public List < SVDBTask > getTargets ( ISVDBScopeItem activeScope ) { return targets ; } } ) ; override . run ( ) ; String result = sve_tester . getDocument ( ) . get ( ) ; IndentComparator . compare ( test_name , expected , result ) ; } } package net . sf . sveditor . ui . tests . explorer ; import java . io . File ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestExplorer extends TestCase { private File fTmpDir ; private SVDBIndexCollection fIndexCollectionOVMMgr ; @ Override public void setUp ( ) { fTmpDir = TestUtils . createTempDir ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; String pname = "" ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; fIndexCollectionOVMMgr = new SVDBIndexCollection ( rgy . getIndexCollectionMgr ( ) , pname ) ; fIndexCollectionOVMMgr . addPluginLibrary ( rgy . findCreateIndex ( new NullProgressMonitor ( ) , pname , SVCoreTestsPlugin . OVM_LIBRARY_ID , SVDBPluginLibIndexFactory . TYPE , null ) ) ; fIndexCollectionOVMMgr . getItemIterator ( new NullProgressMonitor ( ) ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; TestUtils . delete ( fTmpDir ) ; } } package net . sf . sveditor . ui . tests ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class UiTestsPlugin extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static UiTestsPlugin plugin ; public UiTestsPlugin ( ) { } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static UiTestsPlugin getDefault ( ) { return plugin ; } } package net . sf . sveditor . ui . tests ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import junit . framework . Test ; import junit . framework . TestResult ; import junit . framework . TestSuite ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . ui . editor . SVAutoIndentStrategy ; import net . sf . sveditor . ui . editor . SVDocumentPartitions ; import net . sf . sveditor . ui . tests . editor . TestAutoIndent ; import net . sf . sveditor . ui . tests . editor . TestOverrideMethods ; import net . sf . sveditor . ui . tests . editor . TestUserLevelOperations ; import net . sf . sveditor . ui . tests . editor . utils . AutoEditTester ; public class UiReleaseTests extends TestSuite { public UiReleaseTests ( ) { addTest ( new TestSuite ( TestAutoIndent . class ) ) ; addTest ( new TestSuite ( TestOverrideMethods . class ) ) ; addTest ( new TestSuite ( TestUserLevelOperations . class ) ) ; } @ Override public void run ( TestResult result ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; super . run ( result ) ; } @ Override public void runTest ( Test test , TestResult result ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; super . runTest ( test , result ) ; } public static Test suite ( ) { return new UiReleaseTests ( ) ; } public static AutoEditTester createAutoEditTester ( ) { IDocument doc = new Document ( ) ; AutoEditTester tester = new AutoEditTester ( doc , SVDocumentPartitions . SV_PARTITIONING ) ; tester . setAutoEditStrategy ( IDocument . DEFAULT_CONTENT_TYPE , new SVAutoIndentStrategy ( null , SVDocumentPartitions . SV_PARTITIONING ) ) ; return tester ; } } package net . sf . sveditor . core . tests . hierarchy ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; public class TestModuleHierarchy extends TestCase { public void testModuleSubHierarchy ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String testname = "" ; HierarchyTests . runModuleHierarchyTest ( testname , doc , "" , "" ) ; } } package net . sf . sveditor . core . tests . hierarchy ; import java . util . List ; import junit . framework . Test ; import junit . framework . TestCase ; import junit . framework . TestSuite ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . search . SVDBFindNamedClass ; import net . sf . sveditor . core . db . search . SVDBFindNamedModIfcClassIfc ; import net . sf . sveditor . core . hierarchy . ClassHierarchyTreeFactory ; import net . sf . sveditor . core . hierarchy . HierarchyTreeNode ; import net . sf . sveditor . core . hierarchy . ModuleHierarchyTreeFactory ; import net . sf . sveditor . core . tests . IndexTestUtils ; public class HierarchyTests extends TestCase { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( HierarchyTests . class ) ) ; suite . addTest ( new TestSuite ( TestModuleHierarchy . class ) ) ; return suite ; } public void testClassHierarchy ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; String testname = "" ; ISVDBIndexIterator index_it = IndexTestUtils . buildIndex ( doc , testname ) ; ClassHierarchyTreeFactory tf = new ClassHierarchyTreeFactory ( index_it ) ; SVDBFindNamedClass cls_finder = new SVDBFindNamedClass ( index_it ) ; List < SVDBClassDecl > cls_l = cls_finder . find ( "" ) ; assertEquals ( , cls_l . size ( ) ) ; HierarchyTreeNode h = tf . build ( cls_l . get ( ) ) ; assertEquals ( "" , h . getName ( ) ) ; h = h . getParent ( ) ; assertNotNull ( h ) ; assertEquals ( "" , h . getName ( ) ) ; } public void testClassSubHierarchy ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String testname = "" ; ISVDBIndexIterator index_it = IndexTestUtils . buildIndex ( doc , testname ) ; ClassHierarchyTreeFactory tf = new ClassHierarchyTreeFactory ( index_it ) ; SVDBFindNamedClass cls_finder = new SVDBFindNamedClass ( index_it ) ; List < SVDBClassDecl > cls_l = cls_finder . find ( "" ) ; assertEquals ( , cls_l . size ( ) ) ; HierarchyTreeNode h = tf . build ( cls_l . get ( ) ) ; assertEquals ( "" , h . getName ( ) ) ; HierarchyTreeNode c2_2_1 = null ; HierarchyTreeNode c2_2_2 = null ; for ( HierarchyTreeNode c : h . getChildren ( ) ) { if ( c . getName ( ) . equals ( "" ) ) { c2_2_1 = c ; } else if ( c . getName ( ) . equals ( "" ) ) { c2_2_2 = c ; } } assertNotNull ( c2_2_1 ) ; assertEquals ( "" , c2_2_1 . getName ( ) ) ; assertNotNull ( c2_2_2 ) ; assertEquals ( "" , c2_2_2 . getName ( ) ) ; } public static void runModuleHierarchyTest ( String testname , String doc , String top , String ... paths ) { ISVDBIndexIterator index_it = IndexTestUtils . buildIndex ( doc , testname ) ; ModuleHierarchyTreeFactory tf = new ModuleHierarchyTreeFactory ( index_it ) ; SVDBFindNamedModIfcClassIfc mod_finder = new SVDBFindNamedModIfcClassIfc ( index_it ) ; List < ISVDBChildItem > mod_l = mod_finder . find ( top ) ; assertEquals ( , mod_l . size ( ) ) ; HierarchyTreeNode h = tf . build ( ( SVDBModIfcDecl ) mod_l . get ( ) ) ; assertEquals ( top , h . getName ( ) ) ; for ( String path : paths ) { String path_split [ ] = path . split ( "" ) ; for ( int i = ; i < path_split . length ; i ++ ) { path_split [ i ] = path_split [ i ] . trim ( ) ; } HierarchyTreeNode n = find ( h , path_split , ) ; assertNotNull ( n ) ; } } public static HierarchyTreeNode find ( HierarchyTreeNode parent , String path [ ] , int idx ) { HierarchyTreeNode target = null ; for ( HierarchyTreeNode c : parent . getChildren ( ) ) { if ( c . getName ( ) . equals ( path [ idx ] ) ) { target = c ; break ; } } if ( target == null ) { StringBuilder path_str = new StringBuilder ( ) ; StringBuilder avail_elems = new StringBuilder ( ) ; for ( HierarchyTreeNode c : parent . getChildren ( ) ) { avail_elems . append ( c . getName ( ) ) ; avail_elems . append ( "" ) ; } for ( int i = ; i <= idx ; i ++ ) { path_str . append ( path [ i ] ) ; if ( i + <= idx ) { path_str . append ( "" ) ; } } TestCase . fail ( "" + path_str . toString ( ) + "" + avail_elems . toString ( ) ) ; } if ( idx + < path . length ) { find ( target , path , idx + ) ; } return target ; } } package net . sf . sveditor . core . tests . lexer ; import junit . framework . TestSuite ; public class LexerTests extends TestSuite { } package net . sf . sveditor . core . tests . lexer ; import junit . framework . TestCase ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . ISVParser ; import net . sf . sveditor . core . parser . SVLexer ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . parser . SVParsers ; import net . sf . sveditor . core . scanutils . StringTextScanner ; public class TestClassItems extends TestCase { public void testClassFields ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; final LogHandle log = LogFactory . getLogHandle ( "" ) ; final SVLexer lexer = new SVLexer ( ) ; ISVParser parser = new ISVParser ( ) { public void warning ( String msg , int lineno ) { } public SVParsers parsers ( ) { return null ; } public SVLexer lexer ( ) { return lexer ; } public ILogHandle getLogHandle ( ) { return log ; } public boolean error_limit_reached ( ) { return false ; } public void disableErrors ( boolean dis ) { } public void error ( SVParseException e ) { } public void error ( String msg ) { } public void debug ( String msg , Exception e ) { } } ; lexer . init ( parser , new StringTextScanner ( content ) ) ; while ( lexer . peek ( ) != null ) { log . debug ( "" + lexer . getImage ( ) + "" ) ; lexer . eatToken ( ) ; } LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . constraint_parser ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBConstraint ; import net . sf . sveditor . core . db . SVDBItemType ; public class SmokeTest extends TestCase { public static void find_constraints ( ISVDBScopeItem scope , List < SVDBConstraint > constraints ) { for ( ISVDBItemBase it : scope . getItems ( ) ) { if ( it . getType ( ) == SVDBItemType . Constraint ) { constraints . add ( ( SVDBConstraint ) it ) ; } else if ( it instanceof ISVDBScopeItem ) { find_constraints ( ( ISVDBScopeItem ) it , constraints ) ; } } } } package net . sf . sveditor . core . tests . templates ; import java . io . File ; import java . io . IOException ; import java . io . PrintStream ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . templates . TemplateFSFileCreator ; import net . sf . sveditor . core . templates . TemplateInfo ; import net . sf . sveditor . core . templates . TemplateParameterProvider ; import net . sf . sveditor . core . templates . TemplateProcessor ; import net . sf . sveditor . core . templates . TemplateRegistry ; import net . sf . sveditor . core . tests . IndexTestUtils ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestNullIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import net . sf . sveditor . core . text . TagProcessor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestMethodologyTemplates extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { TestUtils . delete ( fTmpDir ) ; } public void testUvmAgent ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TemplateRegistry rgy = new TemplateRegistry ( true ) ; TemplateInfo tmpl = rgy . findTemplate ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; assertNotNull ( tmpl ) ; TagProcessor proc = new TagProcessor ( ) ; TemplateParameterProvider p = new TemplateParameterProvider ( ) ; p . setTag ( "" , "" ) ; proc . addParameterProvider ( p ) ; List < String > files = TemplateProcessor . getOutputFiles ( tmpl , proc ) ; assertContainsAll ( files , "" , "" , "" , "" , "" , "" , "" ) ; TemplateFSFileCreator out_sp = new TemplateFSFileCreator ( fTmpDir ) ; TemplateProcessor tp = new TemplateProcessor ( out_sp ) ; tp . process ( tmpl , proc ) ; utils . unpackBundleZipToFS ( "" , fTmpDir ) ; SVDBIndexRegistry i_rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; i_rgy . init ( new TestNullIndexCacheFactory ( ) ) ; try { PrintStream ps = new PrintStream ( new File ( fTmpDir , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . close ( ) ; } catch ( IOException e ) { fail ( "" + e . getMessage ( ) ) ; } ISVDBIndex index = i_rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , new File ( fTmpDir , "" ) . getAbsolutePath ( ) , SVDBArgFileIndexFactory . TYPE , null ) ; IndexTestUtils . assertNoErrWarn ( log , index ) ; LogFactory . removeLogHandle ( log ) ; } private static void assertContainsAll ( List < String > target , String ... expected ) { assertEquals ( expected . length , target . size ( ) ) ; for ( String exp : expected ) { if ( ! target . contains ( exp ) ) { fail ( "" + exp + "" ) ; } } } } package net . sf . sveditor . core . tests . templates ; import junit . framework . TestSuite ; public class TemplateTests extends TestSuite { public static TestSuite suite ( ) { TestSuite s = new TestSuite ( ) ; s . addTest ( new TestSuite ( TestMethodologyTemplates . class ) ) ; s . addTest ( new TestSuite ( TestExternalTemplates . class ) ) ; return s ; } } package net . sf . sveditor . core . tests . templates ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . templates . IExternalTemplatePathProvider ; import net . sf . sveditor . core . templates . TemplateFSFileCreator ; import net . sf . sveditor . core . templates . TemplateInfo ; import net . sf . sveditor . core . templates . TemplateParameter ; import net . sf . sveditor . core . templates . TemplateParameterProvider ; import net . sf . sveditor . core . templates . TemplateProcessor ; import net . sf . sveditor . core . templates . TemplateRegistry ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import net . sf . sveditor . core . text . TagProcessor ; import junit . framework . TestCase ; public class TestExternalTemplates extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { TestUtils . delete ( fTmpDir ) ; } public void testDiscoverTemplatesFS ( ) throws IOException { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; final File tmpl_dir = new File ( fTmpDir , "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; utils . copyBundleDirToFS ( "" , tmpl_dir ) ; TemplateRegistry rgy = new TemplateRegistry ( false ) ; rgy . addPathProvider ( new IExternalTemplatePathProvider ( ) { public List < String > getExternalTemplatePath ( ) { List < String > ret = new ArrayList < String > ( ) ; ret . add ( tmpl_dir . getAbsolutePath ( ) ) ; return ret ; } } ) ; rgy . load_extensions ( ) ; List < String > categories = rgy . getCategoryIDs ( ) ; for ( String category : categories ) { log . debug ( "" + category ) ; } TestUtils . assertContains ( categories , "" ) ; LogFactory . removeLogHandle ( log ) ; TemplateInfo t1_1 = null ; List < TemplateInfo > ti_l = rgy . getTemplates ( "" ) ; List < String > templates = new ArrayList < String > ( ) ; for ( TemplateInfo t : ti_l ) { log . debug ( "" + t . getId ( ) ) ; templates . add ( t . getId ( ) ) ; if ( t . getId ( ) . equals ( "" ) ) { t1_1 = t ; } } assertNotNull ( t1_1 ) ; List < String > param_names = new ArrayList < String > ( ) ; for ( TemplateParameter p : t1_1 . getParameters ( ) ) { param_names . add ( p . getName ( ) ) ; } TestUtils . assertContains ( param_names , "" , "" ) ; TestUtils . assertContains ( templates , "" , "" , "" , "" ) ; TemplateInfo ti = rgy . findTemplate ( "" ) ; assertNotNull ( ti ) ; Iterable < Tuple < String , String > > tf_it = ti . getTemplates ( ) ; List < String > tfn_list = new ArrayList < String > ( ) ; for ( Tuple < String , String > tf : tf_it ) { File file = new File ( tf . first ( ) ) ; log . debug ( "" + file . getName ( ) ) ; tfn_list . add ( file . getName ( ) ) ; } TestUtils . assertContains ( tfn_list , "" , "" ) ; for ( String category : rgy . getCategoryIDs ( ) ) { for ( TemplateInfo t : rgy . getTemplates ( category ) ) { for ( Tuple < String , String > tf : t . getTemplates ( ) ) { File file = new File ( tf . first ( ) ) ; assertTrue ( "" + tf . first ( ) + "" , file . isFile ( ) ) ; } } } } public void testSubdirHierarchy ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; TemplateRegistry rgy = new TemplateRegistry ( false ) ; rgy . addPathProvider ( new IExternalTemplatePathProvider ( ) { public List < String > getExternalTemplatePath ( ) { List < String > ret = new ArrayList < String > ( ) ; ret . add ( new File ( fTmpDir , "" ) . getAbsolutePath ( ) ) ; return ret ; } } ) ; rgy . load_extensions ( ) ; TemplateInfo tmpl = rgy . findTemplate ( "" ) ; assertNotNull ( tmpl ) ; TagProcessor proc = new TagProcessor ( ) ; TemplateParameterProvider p = new TemplateParameterProvider ( ) ; p . setTag ( "" , "" ) ; proc . addParameterProvider ( p ) ; List < String > files = TemplateProcessor . getOutputFiles ( tmpl , proc ) ; assertContainsAll ( files , "" , "" ) ; TemplateFSFileCreator out_sp = new TemplateFSFileCreator ( fTmpDir ) ; TemplateProcessor tp = new TemplateProcessor ( out_sp ) ; tp . process ( tmpl , proc ) ; assertFilesExist ( fTmpDir , "" , "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testSpaceContainingFilenames ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; TemplateRegistry rgy = new TemplateRegistry ( false ) ; rgy . addPathProvider ( new IExternalTemplatePathProvider ( ) { public List < String > getExternalTemplatePath ( ) { List < String > ret = new ArrayList < String > ( ) ; ret . add ( new File ( fTmpDir , "" ) . getAbsolutePath ( ) ) ; return ret ; } } ) ; rgy . load_extensions ( ) ; TemplateInfo tmpl = rgy . findTemplate ( "" ) ; assertNotNull ( tmpl ) ; TagProcessor proc = new TagProcessor ( ) ; TemplateParameterProvider p = new TemplateParameterProvider ( ) ; p . setTag ( "" , "" ) ; proc . addParameterProvider ( p ) ; List < String > files = TemplateProcessor . getOutputFiles ( tmpl , proc ) ; assertContainsAll ( files , "" , "" ) ; TemplateFSFileCreator out_sp = new TemplateFSFileCreator ( fTmpDir ) ; TemplateProcessor tp = new TemplateProcessor ( out_sp ) ; tp . process ( tmpl , proc ) ; assertFilesExist ( fTmpDir , "" , "" ) ; LogFactory . removeLogHandle ( log ) ; } private static void assertFilesExist ( File dir , String ... paths ) { for ( String path : paths ) { File t = new File ( dir , path ) ; TestCase . assertTrue ( "" + t . getPath ( ) + "" , t . isFile ( ) ) ; } } private static void assertContainsAll ( List < String > target , String ... expected ) { assertEquals ( expected . length , target . size ( ) ) ; for ( String exp : expected ) { if ( ! target . contains ( exp ) ) { fail ( "" + exp + "" ) ; } } } } package net . sf . sveditor . core . tests . job_mgr ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . job_mgr . IJob ; import net . sf . sveditor . core . job_mgr . JobMgr ; import junit . framework . TestCase ; import junit . framework . TestSuite ; public class JobMgrTests extends TestCase { public static TestSuite suite ( ) { TestSuite s = new TestSuite ( "" ) ; s . addTest ( new TestSuite ( JobMgrTests . class ) ) ; return s ; } public void testBasics ( ) { JobMgr mgr = new JobMgr ( ) ; List < IJob > jobs = new ArrayList < IJob > ( ) ; final List < String > finished = new ArrayList < String > ( ) ; for ( int i = ; i < ; i ++ ) { IJob job = mgr . createJob ( ) ; job . init ( "" + i , new Runnable ( ) { public void run ( ) { synchronized ( finished ) { System . out . println ( "" ) ; finished . add ( "" ) ; } } } ) ; mgr . queueJob ( job ) ; } mgr . dispose ( ) ; System . out . println ( "" ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBUtil ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . SVDBIndexValidator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestParamClassContentAssist extends TestCase { private ContentAssistIndex fIndex ; @ Override protected void setUp ( ) throws Exception { fIndex = new ContentAssistIndex ( ) ; fIndex . init ( new NullProgressMonitor ( ) ) ; } public void testNullTest ( ) { } public void EXP_FAIL_testParameterizedField ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , fIndex ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBClassDecl my_class1 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; if ( SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } } assertNotNull ( my_class1 ) ; System . out . println ( "" + SVDBUtil . getChildrenSize ( my_class1 ) + "" ) ; for ( ISVDBItemBase it_t : my_class1 . getChildren ( ) ) { System . out . println ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; } public void EXP_FAIL_testParameterizedFunction ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , fIndex ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBClassDecl my_class1 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; if ( SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } } assertNotNull ( my_class1 ) ; System . out . println ( "" + SVDBUtil . getChildrenSize ( my_class1 ) + "" ) ; for ( ISVDBItemBase it_t : my_class1 . getChildren ( ) ) { System . out . println ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; } private Tuple < SVDBFile , TextTagPosUtils > contentAssistSetup ( String doc ) { TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; fIndex . setFile ( file ) ; return new Tuple < SVDBFile , TextTagPosUtils > ( file , tt_utils ) ; } private void validateResults ( String expected [ ] , List < SVCompletionProposal > proposals ) { for ( String exp : expected ) { boolean found = false ; for ( int i = ; i < proposals . size ( ) ; i ++ ) { if ( proposals . get ( i ) . getReplacement ( ) . equals ( exp ) ) { found = true ; proposals . remove ( i ) ; break ; } } assertTrue ( "" + exp , found ) ; } for ( SVCompletionProposal p : proposals ) { System . out . println ( "" + p . getReplacement ( ) ) ; } assertEquals ( "" , , proposals . size ( ) ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; public class TestContentAssistStruct extends TestCase { public void testContentAssistStructTypedef ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistStructModuleInput ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistStructModuleInputModuleScope ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistStructInClassTypedef ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistStructInClassTypedefRedirect ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistStructField ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . NullProgressMonitor ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . TestNullIndexCacheFactory ; import net . sf . sveditor . core . tests . TextTagPosUtils ; public class TestModuleContentAssist extends TestCase { private ContentAssistIndex fIndex ; public void setUp ( ) { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( new TestNullIndexCacheFactory ( ) ) ; fIndex = new ContentAssistIndex ( ) ; fIndex . init ( new NullProgressMonitor ( ) ) ; } public void testModulePortAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testModulePortAssistNoPrefix ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testInitialBlockVariableAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedBlockVariableAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedIfVariableAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedWhileVariableAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedDoWhileVariableAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedRepeatVariableAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedForeverVariableAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testInitialBlockVarFieldAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testModuleHierarchyAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testModuleHierarchyAssist_2 ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testModuleHierarchyAssist_3 ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndex ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } private Tuple < SVDBFile , TextTagPosUtils > contentAssistSetup ( String doc ) { TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; fIndex . setFile ( file ) ; return new Tuple < SVDBFile , TextTagPosUtils > ( file , tt_utils ) ; } private static void validateResults ( String expected [ ] , List < SVCompletionProposal > proposals ) { for ( String exp : expected ) { boolean found = false ; for ( int i = ; i < proposals . size ( ) ; i ++ ) { if ( proposals . get ( i ) . getReplacement ( ) . equals ( exp ) ) { found = true ; proposals . remove ( i ) ; break ; } } assertTrue ( "" + exp , found ) ; } for ( SVCompletionProposal p : proposals ) { System . out . println ( "" + p . getReplacement ( ) ) ; } assertEquals ( "" , , proposals . size ( ) ) ; } } package net . sf . sveditor . core . tests . content_assist ; import net . sf . sveditor . core . content_assist . AbstractCompletionProcessor ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class TestCompletionProcessor extends AbstractCompletionProcessor { private SVDBFile fSVDBFile ; private ISVDBIndexIterator fIndexIterator ; public TestCompletionProcessor ( LogHandle log , SVDBFile file , ISVDBIndexIterator iterator ) { fSVDBFile = file ; fIndexIterator = iterator ; fLog = LogFactory . getLogHandle ( log . getName ( ) + "" ) ; } public TestCompletionProcessor ( String name , SVDBFile file , ISVDBIndexIterator iterator ) { fSVDBFile = file ; fIndexIterator = iterator ; fLog = LogFactory . getLogHandle ( name + "" ) ; } public TestCompletionProcessor ( SVDBFile file , ISVDBIndexIterator iterator ) { fSVDBFile = file ; fIndexIterator = iterator ; fLog = LogFactory . getLogHandle ( "" ) ; } @ Override protected ISVDBIndexIterator getIndexIterator ( ) { return fIndexIterator ; } @ Override protected SVDBFile getSVDBFile ( ) { return fSVDBFile ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBUtil ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . SVDBIndexValidator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestArrayContentAssist extends TestCase { private static ContentAssistIndex fIndex ; private static SVDBIndexCollection fIndexMgr ; @ Override protected void setUp ( ) throws Exception { if ( fIndexMgr == null ) { System . out . println ( "" ) ; fIndex = new ContentAssistIndex ( ) ; fIndex . init ( new NullProgressMonitor ( ) ) ; fIndexMgr = new SVDBIndexCollection ( "" ) ; fIndexMgr . addLibraryPath ( fIndex ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , SVDBIndexRegistry . GLOBAL_PROJECT , SVCorePlugin . SV_BUILTIN_LIBRARY , SVDBPluginLibIndexFactory . TYPE , null ) ; fIndexMgr . addPluginLibrary ( index ) ; } } public void testMultiple ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc_arr [ ] = { "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" , "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" , "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" , "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" } ; String [ ] exp_arr [ ] = { new String [ ] { "" , "" , "" , "" , "" , "" , "" } , new String [ ] { "" } , new String [ ] { "" } , new String [ ] { "" } } ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; for ( int i = ; i < doc_arr . length ; i ++ ) { Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc_arr [ i ] ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , ini . first ( ) , fIndexMgr ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBClassDecl my_class1 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; if ( SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } else if ( SVDBItem . getName ( it_t ) . startsWith ( "" ) ) { log . debug ( "" + SVDBItem . getName ( it_t ) ) ; } } assertNotNull ( my_class1 ) ; log . debug ( "" + SVDBUtil . getChildrenSize ( my_class1 ) + "" ) ; for ( ISVDBItemBase it_t : my_class1 . getChildren ( ) ) { log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( exp_arr [ i ] , proposals ) ; } LogFactory . removeLogHandle ( log ) ; } public void testQueueFunctions ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , ini . first ( ) , fIndexMgr ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBClassDecl my_class1 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; if ( SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } else if ( SVDBItem . getName ( it_t ) . startsWith ( "" ) ) { log . debug ( "" + SVDBItem . getName ( it_t ) ) ; } } assertNotNull ( my_class1 ) ; log . debug ( "" + my_class1 . getItems ( ) . size ( ) + "" ) ; for ( ISVDBItemBase it_t : my_class1 . getItems ( ) ) { log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testQueueElemItems ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , ini . first ( ) , fIndexMgr ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBClassDecl my_class1 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; if ( SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } } assertNotNull ( my_class1 ) ; log . debug ( "" + my_class1 . getItems ( ) . size ( ) + "" ) ; for ( ISVDBItemBase it_t : my_class1 . getItems ( ) ) { log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testArrayFunctions ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , ini . first ( ) , fIndexMgr ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBClassDecl my_class1 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; if ( SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } } assertNotNull ( my_class1 ) ; log . debug ( "" + my_class1 . getItems ( ) . size ( ) + "" ) ; for ( ISVDBItemBase it_t : my_class1 . getItems ( ) ) { log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testArrayElemItems ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , ini . first ( ) , fIndexMgr ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBClassDecl my_class1 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; if ( SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } } assertNotNull ( my_class1 ) ; log . debug ( "" + my_class1 . getItems ( ) . size ( ) + "" ) ; for ( ISVDBItemBase it_t : my_class1 . getItems ( ) ) { log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } private Tuple < SVDBFile , TextTagPosUtils > contentAssistSetup ( String doc ) { TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; fIndex . setFile ( file ) ; return new Tuple < SVDBFile , TextTagPosUtils > ( file , tt_utils ) ; } private void validateResults ( String expected [ ] , List < SVCompletionProposal > proposals ) { for ( String exp : expected ) { boolean found = false ; for ( int i = ; i < proposals . size ( ) ; i ++ ) { if ( proposals . get ( i ) . getReplacement ( ) . equals ( exp ) ) { found = true ; proposals . remove ( i ) ; break ; } } assertTrue ( "" + exp , found ) ; } for ( SVCompletionProposal p : proposals ) { System . out . println ( "" + p . getReplacement ( ) ) ; } assertEquals ( "" , , proposals . size ( ) ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; public class TestContentAssistClass extends TestCase { public void testContentAssistExternTaskClass ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testIgnoreForwardDecl ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testIgnoreNullStmt ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistExternTaskClassField ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistSuperSuperClass ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" , "" , "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistSuperClass_1 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistBaseClass ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistBaseClassEOF ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; log . debug ( "" + tt_utils . getLineMap ( ) . get ( "" ) ) ; log . debug ( "" + tt_utils . getPosMap ( ) . get ( "" ) ) ; log . debug ( "" + scanner . getContent ( ) + "" ) ; log . debug ( "" + scanner . getContent ( ) . length ( ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistOnlyTopNew_1 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistOnlyTopNew_2 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testStaticTypeAssist_1 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testStaticTypeAssist_2 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testStaticTypeAssist_3 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testStaticTypeAssist_4 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testStaticTypeAssist_5 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testStaticTypeAssist_6 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testParameterizedTypeAssist_1 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testParameterizedTypeAssist_2 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistIgnoreBaseClassTF ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistOnlyTopTF_1 ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ContentAssistTests . runTest ( testname , doc , "" , "" ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBCovergroup ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . SVDBIndexValidator ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . TextTagPosUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestContentAssistBuiltins extends TestCase { private ContentAssistIndex fIndex ; private SVDBIndexCollection fIndexMgr ; private File fTmpDir ; private SVDBIndexRegistry fIndexRgy ; @ Override public void setUp ( ) { fTmpDir = TestUtils . createTempDir ( ) ; fIndexMgr = new SVDBIndexCollection ( "" ) ; fIndexRgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; fIndexRgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; fIndexMgr . addPluginLibrary ( fIndexRgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , SVCorePlugin . SV_BUILTIN_LIBRARY , SVDBPluginLibIndexFactory . TYPE , null ) ) ; fIndex = new ContentAssistIndex ( ) ; fIndex . init ( new NullProgressMonitor ( ) ) ; fIndexMgr . addLibraryPath ( fIndex ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; fIndexRgy . save_state ( ) ; TestUtils . delete ( fTmpDir ) ; } public void testCovergroupOption ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , fIndexMgr ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBCovergroup cg = null ; SVDBClassDecl my_class1 = null ; it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; if ( it_t . getType ( ) == SVDBItemType . Covergroup && SVDBItem . getName ( it_t ) . equals ( "" ) ) { cg = ( SVDBCovergroup ) it_t ; } else if ( it_t . getType ( ) == SVDBItemType . ClassDecl && SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } } assertNotNull ( cg ) ; assertNotNull ( my_class1 ) ; log . debug ( "" ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testCovergroupTypeOptionMergeInstances ( ) { String doc = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , fIndexMgr ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBCovergroup cg = null ; SVDBClassDecl my_class1 = null ; it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; if ( it_t . getType ( ) == SVDBItemType . Covergroup && SVDBItem . getName ( it_t ) . equals ( "" ) ) { cg = ( SVDBCovergroup ) it_t ; } else if ( it_t . getType ( ) == SVDBItemType . ClassDecl && SVDBItem . getName ( it_t ) . equals ( "" ) ) { my_class1 = ( SVDBClassDecl ) it_t ; } } assertNotNull ( cg ) ; assertNotNull ( my_class1 ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; assertEquals ( , proposals . size ( ) ) ; validateResults ( new String [ ] { "" } , proposals ) ; } private Tuple < SVDBFile , TextTagPosUtils > contentAssistSetup ( String doc ) { TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; fIndex . setFile ( file ) ; return new Tuple < SVDBFile , TextTagPosUtils > ( file , tt_utils ) ; } private void validateResults ( String expected [ ] , List < SVCompletionProposal > proposals ) { for ( String exp : expected ) { boolean found = false ; for ( int i = ; i < proposals . size ( ) ; i ++ ) { if ( proposals . get ( i ) . getReplacement ( ) . equals ( exp ) ) { found = true ; proposals . remove ( i ) ; break ; } } assertTrue ( "" + exp , found ) ; } for ( SVCompletionProposal p : proposals ) { System . out . println ( "" + p . getReplacement ( ) ) ; } assertEquals ( "" , , proposals . size ( ) ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; public class TestContentAssistEnum extends TestCase { public void testContentAssistEnumeratorAssign ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testContentAssistInClassEnumDecl ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . io . InputStream ; import java . util . HashSet ; import java . util . Set ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . AbstractSVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexChangeListener ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . cache . InMemoryIndexCache ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import org . eclipse . core . runtime . IProgressMonitor ; public class ContentAssistIndex extends AbstractSVDBIndex { private SVDBFile fFile ; public ContentAssistIndex ( ) { super ( "" , "" , null , new InMemoryIndexCache ( ) , null ) ; } @ Override protected String getLogName ( ) { return "" ; } @ Override protected void discoverRootFiles ( IProgressMonitor monitor ) { } public void setFile ( SVDBFile file ) { fFile = file ; cacheDeclarations ( fFile ) ; } @ Override public Set < String > getFileList ( IProgressMonitor monitor ) { Set < String > ret = new HashSet < String > ( ) ; synchronized ( fFile ) { ret . add ( fFile . getFilePath ( ) ) ; } return ret ; } @ Override public synchronized SVDBFile findFile ( String path ) { return fFile ; } @ Override public ISVDBItemIterator getItemIterator ( IProgressMonitor monitor ) { return super . getItemIterator ( monitor ) ; } public void addChangeListener ( ISVDBIndexChangeListener l ) { } public String getBaseLocation ( ) { return "" ; } public String getTypeID ( ) { return "" ; } public void removeChangeListener ( ISVDBIndexChangeListener l ) { } public SVDBFile parse ( InputStream in , String path , IProgressMonitor monitor ) { return null ; } public SVDBSearchResult < SVDBFile > findIncludedFile ( String leaf ) { return null ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; public class TestContentAssistTaskFunction extends TestCase { public void testClassTFParam ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testClassTFLocal ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testClassTFSameClassLocal ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; public class TestContentAssistInterface extends TestCase { public void testContentAssistInterfaceBasics ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testInterfaceTaskVarAssist ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( testname , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testInterfaceModuleFieldAssist ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( testname , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testInterfaceModulePortAssist ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( testname , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testInterfaceModportModuleField ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( testname , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testInterfaceModportModulePort ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( testname , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testInterfaceModportModulePort_1 ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( testname , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . content_assist ; import net . sf . sveditor . core . SVCorePlugin ; import junit . framework . TestCase ; public class TestContentAssistTypes extends TestCase { public void testTypeAssistPackageScope ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( true ) ; String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" ; ContentAssistTests . runTest ( testname , doc , "" , "" ) ; } public void testEnumAssistPackageScope ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( true ) ; String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ContentAssistTests . runTest ( testname , doc , "" , "" , "" ) ; } public void testTypeAssistClassScope ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" ; ContentAssistTests . runTest ( testname , doc , "" , "" ) ; } public void testEnumAssistClassScope ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ContentAssistTests . runTest ( testname , doc , "" , "" , "" ) ; } public void testClassParam ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( true ) ; String testname = "" ; String doc = "" + "" + "" + "" + "" + "" ; ContentAssistTests . runTest ( testname , doc , "" ) ; } } package net . sf . sveditor . core . tests . content_assist ; import junit . framework . TestCase ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . expr_utils . SVExprContext ; import net . sf . sveditor . core . expr_utils . SVExprScanner ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . TextTagPosUtils ; public class ExpressionUtils extends TestCase { public void testExtractPreTriggerPortionUntriggered ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( content ) ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; SVExprScanner expr_scan = new SVExprScanner ( ) ; scanner . seek ( tt_utils . getTagPos ( "" ) ) ; SVExprContext ctxt = expr_scan . extractExprContext ( scanner , false ) ; System . out . println ( "" + ctxt . fLeaf + "" + ctxt . fStart + "" ) ; } public void testExtractExprContext ( ) { SVExprScanner expr_scan = new SVExprScanner ( ) ; String doc1 = "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; System . out . println ( "" + tt_utils . getStrippedData ( ) ) ; SVExprContext ctxt ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; ctxt = expr_scan . extractExprContext ( scanner , false ) ; System . out . println ( "" + ctxt . fLeaf + "" + ctxt . fStart + "" + ctxt . fTrigger + "" ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; ctxt = expr_scan . extractExprContext ( scanner , false ) ; System . out . println ( "" + ctxt . fLeaf + "" + ctxt . fStart + "" + ctxt . fTrigger + "" ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; ctxt = expr_scan . extractExprContext ( scanner , true ) ; System . out . println ( "" + ctxt . fLeaf + "" + ctxt . fStart + "" + ctxt . fTrigger + "" ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; ctxt = expr_scan . extractExprContext ( scanner , false ) ; System . out . println ( "" + ctxt . fLeaf + "" + ctxt . fRoot + "" + ctxt . fStart + "" + ctxt . fTrigger + "" ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; public class TestContentAssistBehavioralBlock extends TestCase { public void testAssignRHS ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testBlockLocalVariable ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testFieldRefBlockLocalVariable ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testLessEqualAssist ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc1 ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( new String [ ] { "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testStructFieldAssistInForIfScope ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ContentAssistTests . runTest ( testname , doc , "" , "" , "" , "" ) ; } public void testStructFieldAssistInForScope ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ContentAssistTests . runTest ( testname , doc , "" , "" , "" , "" ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBUtil ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . db . search . SVDBFindDefaultNameMatcher ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanner . SVKeywords ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBIndexValidator ; import net . sf . sveditor . core . tests . TestNullIndexCacheFactory ; import net . sf . sveditor . core . tests . TextTagPosUtils ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestContentAssistBasics extends TestCase { private SVDBIndexCollection fIndexCollectionOVMMgr ; private SVDBIndexCollection fIndexCollectionVMMMgr ; private SVDBIndexCollection fIndexCollectionStandalone ; private ContentAssistIndex fIndex ; private File fTmpDir ; @ Override public void setUp ( ) { fTmpDir = TestUtils . createTempDir ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; String pname = "" ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( new TestNullIndexCacheFactory ( ) ) ; fIndex = new ContentAssistIndex ( ) ; fIndex . init ( new NullProgressMonitor ( ) ) ; fIndexCollectionVMMMgr = new SVDBIndexCollection ( pname ) ; fIndexCollectionVMMMgr . addLibraryPath ( fIndex ) ; fIndexCollectionVMMMgr . addPluginLibrary ( rgy . findCreateIndex ( new NullProgressMonitor ( ) , pname , SVCoreTestsPlugin . VMM_LIBRARY_ID , SVDBPluginLibIndexFactory . TYPE , null ) ) ; } private SVDBIndexCollection createStandaloneIndexMgr ( ) { if ( fIndexCollectionStandalone == null ) { fIndexCollectionStandalone = new SVDBIndexCollection ( "" ) ; fIndexCollectionStandalone . addLibraryPath ( fIndex ) ; } return fIndexCollectionStandalone ; } private SVDBIndexCollection createOVMIndexMgr ( ) { if ( fIndexCollectionOVMMgr == null ) { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; fIndexCollectionOVMMgr = new SVDBIndexCollection ( "" ) ; fIndexCollectionOVMMgr . addLibraryPath ( fIndex ) ; fIndexCollectionOVMMgr . addPluginLibrary ( rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , SVCoreTestsPlugin . OVM_LIBRARY_ID , SVDBPluginLibIndexFactory . TYPE , null ) ) ; } return fIndexCollectionOVMMgr ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; TestUtils . delete ( fTmpDir ) ; } public void testOVMMacroContentAssist ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . setDebugLevel ( ILogLevel . LEVEL_OFF ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc1 = "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( testname , file , createOVMIndexMgr ( ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; log . debug ( ILogLevel . LEVEL_MIN , "" ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; log . debug ( ILogLevel . LEVEL_MIN , "" ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testVMMMacroContentAssist ( ) { String doc1 = "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc1 ) ; TextTagPosUtils tt_utils = ini . second ( ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( "" , file , fIndexCollectionVMMMgr ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" } , proposals ) ; } public void testScopedNonInheritanceAssist ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; ISVDBIndexIterator index_it = cp . getIndexIterator ( ) ; ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBIndexValidator v = new SVDBIndexValidator ( ) ; v . validateIndex ( index_it . getItemIterator ( new NullProgressMonitor ( ) ) , SVDBIndexValidator . ExpectErrors ) ; SVDBClassDecl my_class2 = null ; List < SVDBDeclCacheItem > found = index_it . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; assertEquals ( , found . size ( ) ) ; my_class2 = ( SVDBClassDecl ) found . get ( ) . getSVDBItem ( ) ; assertNotNull ( my_class2 ) ; log . debug ( "" + SVDBUtil . getChildrenSize ( my_class2 ) + "" ) ; for ( ISVDBItemBase it_t : my_class2 . getChildren ( ) ) { log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testScopedFieldContentAssist ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createStandaloneIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" } , proposals ) ; } public void testScopedFieldDerefContentAssist ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" } , proposals ) ; } public void testExternScopedFieldContentAssist ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" } , proposals ) ; } public void testScopedTypedefFieldContentAssist ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" } , proposals ) ; } public void testScopedInheritanceAssist ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" , "" , "" , "" } , proposals ) ; } public void testConstructorCompletion ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) + "" ) ; } assertEquals ( "" , , proposals . size ( ) ) ; SVDBTask new_f ; SVDBVarDeclItem new_field ; if ( proposals . get ( ) . getItem ( ) . getType ( ) == SVDBItemType . Function ) { new_f = ( SVDBTask ) proposals . get ( ) . getItem ( ) ; new_field = ( SVDBVarDeclItem ) proposals . get ( ) . getItem ( ) ; } else { new_f = ( SVDBTask ) proposals . get ( ) . getItem ( ) ; new_field = ( SVDBVarDeclItem ) proposals . get ( ) . getItem ( ) ; } log . debug ( "" + new_f . getParent ( ) . getType ( ) + "" + SVDBItem . getName ( new_f . getParent ( ) ) ) ; assertEquals ( "" , "" , new_f . getName ( ) ) ; assertEquals ( "" , "" , SVDBItem . getName ( new_field ) ) ; assertEquals ( "" , "" , SVDBItem . getName ( new_f . getParent ( ) ) ) ; assertEquals ( "" , "" , SVDBItem . getName ( new_field . getParent ( ) . getParent ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testUntriggeredClassAssist ( ) { String doc = "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , fIndex ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( int i = ; i < proposals . size ( ) ; i ++ ) { if ( SVKeywords . isSVKeyword ( proposals . get ( i ) . getReplacement ( ) ) ) { proposals . remove ( i ) ; i -- ; } } validateResults ( new String [ ] { "" , "" } , proposals ) ; } public void testEmptyFileAssist ( ) { String doc = "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , fIndex ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( int i = ; i < proposals . size ( ) ; i ++ ) { if ( SVKeywords . isSVKeyword ( proposals . get ( i ) . getReplacement ( ) ) ) { proposals . remove ( i ) ; i -- ; } } validateResults ( new String [ ] { } , proposals ) ; } public void testUntriggeredPrefixClassAssist ( ) { String doc = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" } , proposals ) ; } public void testMacroCompletion ( ) { String doc = "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; validateResults ( new String [ ] { "" , "" , "" } , proposals ) ; } public void testFunctionNonVoidReturn ( ) { String doc = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } public void testEndFunctionLabel ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , TextTagPosUtils > ini = contentAssistSetup ( doc ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( ini . second ( ) . getStrippedData ( ) ) ; TestCompletionProcessor cp = new TestCompletionProcessor ( ini . first ( ) , createOVMIndexMgr ( ) ) ; scanner . seek ( ini . second ( ) . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , ini . first ( ) , ini . second ( ) . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; for ( SVCompletionProposal p : proposals ) { log . debug ( "" + p . getReplacement ( ) ) ; } validateResults ( new String [ ] { "" } , proposals ) ; LogFactory . removeLogHandle ( log ) ; } private Tuple < SVDBFile , TextTagPosUtils > contentAssistSetup ( String doc ) { TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , "" , markers ) ; fIndex . setFile ( file ) ; return new Tuple < SVDBFile , TextTagPosUtils > ( file , tt_utils ) ; } private void validateResults ( String expected [ ] , List < SVCompletionProposal > proposals ) { for ( String exp : expected ) { boolean found = false ; for ( int i = ; i < proposals . size ( ) ; i ++ ) { if ( proposals . get ( i ) . getReplacement ( ) . equals ( exp ) ) { found = true ; proposals . remove ( i ) ; break ; } } assertTrue ( "" + exp , found ) ; } for ( SVCompletionProposal p : proposals ) { System . out . println ( "" + p . getReplacement ( ) ) ; } assertEquals ( "" , , proposals . size ( ) ) ; } } package net . sf . sveditor . core . tests . content_assist ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . TextTagPosUtils ; import junit . framework . Test ; import junit . framework . TestCase ; import junit . framework . TestSuite ; public class ContentAssistTests extends TestCase { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( TestArrayContentAssist . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistBasics . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistBehavioralBlock . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistBuiltins . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistClass . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistEnum . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistInterface . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistStruct . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistTaskFunction . class ) ) ; suite . addTest ( new TestSuite ( TestContentAssistTypes . class ) ) ; suite . addTest ( new TestSuite ( TestModuleContentAssist . class ) ) ; suite . addTest ( new TestSuite ( TestParamClassContentAssist . class ) ) ; return suite ; } public static void validateResults ( String expected [ ] , List < SVCompletionProposal > proposals ) { for ( String exp : expected ) { boolean found = false ; for ( int i = ; i < proposals . size ( ) ; i ++ ) { if ( proposals . get ( i ) . getReplacement ( ) . equals ( exp ) ) { found = true ; proposals . remove ( i ) ; break ; } } assertTrue ( "" + exp , found ) ; } for ( SVCompletionProposal p : proposals ) { System . out . println ( "" + p . getReplacement ( ) ) ; } assertEquals ( "" , , proposals . size ( ) ) ; } public static void runTest ( String testname , String doc , String ... expected ) { LogHandle log = LogFactory . getLogHandle ( testname ) ; TextTagPosUtils tt_utils = new TextTagPosUtils ( new StringInputStream ( doc ) ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( tt_utils . openStream ( ) , testname , markers ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( tt_utils . getStrippedData ( ) ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } TestCompletionProcessor cp = new TestCompletionProcessor ( log , file , new FileIndexIterator ( file ) ) ; scanner . seek ( tt_utils . getPosMap ( ) . get ( "" ) ) ; cp . computeProposals ( scanner , file , tt_utils . getLineMap ( ) . get ( "" ) ) ; List < SVCompletionProposal > proposals = cp . getCompletionProposals ( ) ; ContentAssistTests . validateResults ( expected , proposals ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCacheFactory ; import net . sf . sveditor . core . db . index . cache . InMemoryIndexCache ; public class TestNullIndexCacheFactory implements ISVDBIndexCacheFactory { private List < InMemoryIndexCache > fCacheList ; public TestNullIndexCacheFactory ( ) { fCacheList = new ArrayList < InMemoryIndexCache > ( ) ; } public ISVDBIndexCache createIndexCache ( String project_name , String base_location ) { InMemoryIndexCache ret = new InMemoryIndexCache ( ) ; fCacheList . add ( ret ) ; return ret ; } public void compactCache ( List < ISVDBIndexCache > cache_list ) { } public List < InMemoryIndexCache > getCacheList ( ) { return fCacheList ; } } package net . sf . sveditor . core . tests . indent ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . util . Enumeration ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import org . osgi . framework . Bundle ; public class NoHangIndentTests extends TestCase { @ SuppressWarnings ( "" ) public void testIndentNoHang ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; Bundle bundle = SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ; Enumeration < URL > sv_entries = ( Enumeration < URL > ) bundle . findEntries ( "" , "" , true ) ; Enumeration < URL > svh_entries = ( Enumeration < URL > ) bundle . findEntries ( "" , "" , true ) ; int passes = , failures = ; while ( sv_entries != null && sv_entries . hasMoreElements ( ) ) { URL url = sv_entries . nextElement ( ) ; if ( noHangTestInt ( url ) ) { passes ++ ; } else { failures ++ ; } } while ( svh_entries != null && svh_entries . hasMoreElements ( ) ) { URL url = svh_entries . nextElement ( ) ; if ( noHangTestInt ( url ) ) { passes ++ ; } else { failures ++ ; } } log . note ( "" + passes + "" + failures + "" ) ; assertEquals ( "" , failures , ) ; LogFactory . removeLogHandle ( log ) ; } private boolean noHangTestInt ( final URL url ) { boolean ret = true ; InputStream in_t = null ; final Object monitor = new Object ( ) ; try { in_t = url . openStream ( ) ; } catch ( Exception e ) { System . out . println ( "" + url . getPath ( ) + "" ) ; return false ; } final InputStream in = in_t ; Thread t = new Thread ( new Runnable ( ) { public void run ( ) { StringBuilder sb = new StringBuilder ( ) ; byte data [ ] = new byte [ ] ; int sz ; try { sz = in . read ( data , , data . length ) ; for ( int i = ; i < sz ; i ++ ) { sb . append ( ( char ) data [ i ] ) ; } } catch ( IOException e ) { } SVIndentScanner scanner = new SVIndentScanner ( new StringBIDITextScanner ( sb . toString ( ) ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . indent ( ) ; synchronized ( monitor ) { monitor . notify ( ) ; } } } ) ; t . start ( ) ; try { t . join ( ) ; if ( t . isAlive ( ) ) { System . out . println ( "" + url . getPath ( ) + "" ) ; ret = false ; t . interrupt ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } return ret ; } } package net . sf . sveditor . core . tests . indent ; import junit . framework . TestCase ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . indent . SVIndentToken ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringTextScanner ; public class TestIndentScanner extends TestCase { public void testIsStartLine ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; boolean start_line [ ] = { true , true , false , true , false , true , true , false , false , false , false , } ; boolean end_line [ ] = { true , false , true , false , true , true , false , false , false , false , true , } ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( new StringBuilder ( content ) ) ) ; for ( int i = ; i < start_line . length ; i ++ ) { SVIndentToken tok = scanner . next ( ) ; log . debug ( "" + tok . isStartLine ( ) + "" + tok . isEndLine ( ) + "" + tok . getImage ( ) ) ; assertEquals ( "" + tok . getImage ( ) + "" , start_line [ i ] , tok . isStartLine ( ) ) ; assertEquals ( "" + tok . getImage ( ) + "" , end_line [ i ] , tok . isEndLine ( ) ) ; } LogFactory . removeLogHandle ( log ) ; } public void testLeadingWhitespace ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( new StringBuilder ( content ) ) ) ; SVIndentToken tok ; while ( ( tok = scanner . next ( ) ) != null ) { if ( tok . getImage ( ) . equals ( "" ) ) { log . debug ( "" + tok . getLeadingWS ( ) + "" ) ; } } LogFactory . removeLogHandle ( log ) ; } public void testMultiEmptyLines ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; SVIndentToken tok ; while ( ( tok = scanner . next ( ) ) != null && ! tok . getImage ( ) . equals ( "" ) ) { } tok = scanner . next ( ) ; tok = scanner . next ( ) ; assertEquals ( "" , "" , tok . getLeadingWS ( ) ) ; tok = scanner . next ( ) ; assertEquals ( "" , "" , tok . getLeadingWS ( ) ) ; } public void testStringWithEmbeddedCtrl ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; SVIndentToken tok ; while ( ( tok = scanner . next ( ) ) != null && ! tok . getImage ( ) . equals ( "" ) ) { } tok = scanner . next ( ) ; tok = scanner . next ( ) ; assertEquals ( "" , "" , tok . getImage ( ) ) ; } } package net . sf . sveditor . core . tests . indent ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringTextScanner ; public class TestAdaptiveIndent extends TestCase { public void testAdaptiveSecondLevel ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testPostComment ( ) { String content = "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; coreAutoIndentTest ( "" , content , , expected ) ; } public void testBasicModule ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( log , "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testModuleContainingClass ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( log , "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testAdaptiveIf ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( log , "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testPostSysTfIfPartial ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( , ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( log , "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testPostSysTfIfFull ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( log , "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testAdaptiveFirstLevelScope ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( log , "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } private void coreAutoIndentTest ( String testname , String content , int adaptive_end , String expected ) { LogHandle log = LogFactory . getLogHandle ( testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndentEnd ( adaptive_end ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( testname , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . indent ; import java . io . ByteArrayOutputStream ; import junit . framework . Test ; import junit . framework . TestCase ; import junit . framework . TestSuite ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringTextScanner ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . utils . BundleUtils ; public class IndentTests extends TestCase { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( IndentTests . class ) ) ; suite . addTest ( new TestSuite ( NoHangIndentTests . class ) ) ; suite . addTest ( new TestSuite ( TestIndentScanner . class ) ) ; suite . addTest ( new TestSuite ( TestAdaptiveIndent . class ) ) ; return suite ; } public void testClass ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; ByteArrayOutputStream bos ; bos = utils . readBundleFile ( "" ) ; String ref = bos . toString ( ) ; StringBuilder sb = removeLeadingWS ( ref ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( sb ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; StringBuilder result = new StringBuilder ( indenter . indent ( - , - ) ) ; IndentComparator . compare ( "" , ref , result . toString ( ) ) ; } public void testBasicClass ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testEmptyCaseStmt ( ) throws Exception { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" ) ; try { SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw e ; } finally { log . debug ( "" ) ; } LogFactory . removeLogHandle ( log ) ; } public void testInitialBlock ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" ; log . debug ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; log . debug ( "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testInitialStmt ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" ; log . debug ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; log . debug ( "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testStructVar ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" ; log . debug ( "" + testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( testname , expected , result ) ; log . debug ( "" + testname ) ; LogFactory . removeLogHandle ( log ) ; } public void testTypedefStruct ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" ; log . debug ( "" + testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( testname , expected , result ) ; log . debug ( "" + testname ) ; LogFactory . removeLogHandle ( log ) ; } public void testTypedefNonStructUnion ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" ; log . debug ( "" + testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( testname , expected , result ) ; log . debug ( "" + testname ) ; LogFactory . removeLogHandle ( log ) ; } public void testUnionVar ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" ; log . debug ( "" + testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( testname , expected , result ) ; log . debug ( "" + testname ) ; LogFactory . removeLogHandle ( log ) ; } public void testTypedefUnion ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" ; log . debug ( "" + testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( testname , expected , result ) ; log . debug ( "" + testname ) ; LogFactory . removeLogHandle ( log ) ; } public void testEnumVar ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" ; log . debug ( "" + testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( testname , expected , result ) ; log . debug ( "" + testname ) ; LogFactory . removeLogHandle ( log ) ; } public void testTypedefEnum ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" ; log . debug ( "" + testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( testname , expected , result ) ; log . debug ( "" + testname ) ; LogFactory . removeLogHandle ( log ) ; } public void testBasicModuleComment ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedModule ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testIndentPostSingleComment ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testBasicModuleWire ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" ; String expected = "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testNewLineIf ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( content ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; log . debug ( "" ) ; log . debug ( result ) ; IndentComparator . compare ( "" , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testModule ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; ByteArrayOutputStream bos ; bos = utils . readBundleFile ( "" ) ; String expected = bos . toString ( ) ; StringBuilder sb = removeLeadingWS ( expected ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( sb ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( ) ; IndentComparator . compare ( "" , expected , result ) ; } public void testMultiBlankLine ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String ref = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" ) ; log . debug ( result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , "" , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testFunctionComment ( ) { String ref = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" ) ; log . debug ( result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , "" , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testModuleFirstItemComment ( ) { String ref = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" + result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , "" , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testInitialFirstItemComment ( ) { String ref = "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" + result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , "" , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testFunctionFirstItemComment ( ) { String ref = "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" + result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , "" , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testIfInFunction ( ) { String ref = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" + result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , "" , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testForkJoin ( ) { String testname = "" ; String ref = "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" + result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , testname , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testEmptyForkJoin ( ) { String testname = "" ; String ref = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" + result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , testname , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testForkJoinBlock ( ) { String testname = "" ; String ref = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" + result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , testname , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } public void testPreProcIndent ( ) { String testname = "" ; String ref = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVIndentScanner scanner = new SVIndentScanner ( new StringTextScanner ( ref ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; indenter . init ( scanner ) ; indenter . setTestMode ( true ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( ) ; String result = indenter . indent ( - , - ) ; log . debug ( "" + ref ) ; log . debug ( "" ) ; log . debug ( "" + result ) ; log . debug ( "" ) ; IndentComparator . compare ( log , testname , ref , result ) ; LogFactory . removeLogHandle ( log ) ; } private StringBuilder removeLeadingWS ( String ref ) { StringBuilder sb = new StringBuilder ( ) ; int i = ; while ( i < ref . length ( ) ) { while ( i < ref . length ( ) && Character . isWhitespace ( ref . charAt ( i ) ) && ref . charAt ( i ) != '' ) { i ++ ; } if ( i >= ref . length ( ) ) { break ; } if ( ref . charAt ( i ) == '' ) { sb . append ( '' ) ; i ++ ; continue ; } else { while ( i < ref . length ( ) && ref . charAt ( i ) != '' ) { sb . append ( ref . charAt ( i ) ) ; i ++ ; } if ( i < ref . charAt ( i ) ) { sb . append ( '' ) ; } } } return sb ; } } package net . sf . sveditor . core . tests . indent ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import junit . framework . TestCase ; public class IndentComparator { public static void compare ( String msg , String expected , String result ) { LogHandle log = LogFactory . getLogHandle ( msg ) ; compare ( log , msg , expected , result ) ; LogFactory . removeLogHandle ( log ) ; } public static void compare ( LogHandle log , String msg , String expected , String result ) { List < String > lines_expected = split ( expected ) ; List < String > lines_result = split ( result ) ; int lineno = ; StringBuilder exp_sb = new StringBuilder ( ) ; StringBuilder res_sb = new StringBuilder ( ) ; int failures = ; int i ; for ( i = ; i < lines_expected . size ( ) || i < lines_result . size ( ) ; i ++ ) { String e = ( i < lines_expected . size ( ) ) ? lines_expected . get ( i ) : null ; String r = ( i < lines_result . size ( ) ) ? lines_result . get ( i ) : null ; if ( e != null && r != null ) { if ( e . equals ( r ) ) { log . debug ( lineno + "" + r + "" ) ; } else { log . error ( lineno + "" + e + "" ) ; log . error ( lineno + "" + r + "" ) ; failures ++ ; } } else { if ( e == null && r . equals ( "" ) ) { log . debug ( lineno + "" + r + "" ) ; } else if ( r == null && e . equals ( "" ) ) { log . debug ( lineno + "" + e + "" ) ; } else { log . error ( lineno + "" + e + "" ) ; log . error ( lineno + "" + r + "" ) ; failures ++ ; } } lineno ++ ; } for ( String e : lines_expected ) { exp_sb . append ( e ) ; exp_sb . append ( "" ) ; } for ( String r : lines_result ) { res_sb . append ( r ) ; res_sb . append ( "" ) ; } TestCase . assertEquals ( msg , , failures ) ; } private static List < String > split ( String input ) { List < String > ret = new ArrayList < String > ( ) ; StringBuilder sb = new StringBuilder ( ) ; boolean all_ws ; int idx = ; while ( idx < input . length ( ) ) { sb . setLength ( ) ; all_ws = true ; while ( idx < input . length ( ) && input . charAt ( idx ) != '' ) { if ( ! Character . isWhitespace ( input . charAt ( idx ) ) ) { all_ws = false ; } sb . append ( input . charAt ( idx ) ) ; idx ++ ; } if ( sb . length ( ) > || input . charAt ( idx ) == '' ) { if ( all_ws ) { ret . add ( "" ) ; } else { ret . add ( sb . toString ( ) ) ; } } if ( idx >= input . length ( ) ) { break ; } else { idx ++ ; } } return ret ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . io . InputStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . AbstractSVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SaveMarkersFileSystemProvider ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestIndexMissingIncludeDefine extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testWSLibMissingIncludeDefine ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; int_TestMissingIncludeDefine ( index , "" , ) ; } public void testWSArgFileMissingIncludeDefine ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; int_TestMissingIncludeDefine ( index , "" , ) ; } public void testWSSourceCollectionMissingIncludeDefine ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; int_TestMissingIncludeDefine ( index , "" , ) ; } public void int_TestMissingIncludeDefine ( ISVDBIndex index , String path , int expected_errors ) { SaveMarkersFileSystemProvider fs_provider_m = new SaveMarkersFileSystemProvider ( ( ( AbstractSVDBIndex ) index ) . getFileSystemProvider ( ) ) ; ( ( AbstractSVDBIndex ) index ) . setFileSystemProvider ( fs_provider_m ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( it . hasNext ( ) ) { it . nextItem ( ) ; } assertEquals ( "" , , fs_provider_m . getMarkers ( ) . size ( ) ) ; fs_provider_m . getMarkers ( ) . clear ( ) ; InputStream in = fs_provider_m . openStream ( path ) ; SVDBFile file = index . parse ( new NullProgressMonitor ( ) , in , path , null ) . second ( ) ; assertNotNull ( "" , file ) ; } } package net . sf . sveditor . core . tests . index ; import junit . framework . TestCase ; public class TestWorkspaceIndexProviders extends TestCase { } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . io . InputStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . AbstractSVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; public class TestIndexParse extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testWSLibIndexParse ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; String path = "" + project_dir . getFile ( new Path ( "" ) ) . getFullPath ( ) . toOSString ( ) ; try { int_testIndexParse ( index , path ) ; } finally { TestUtils . deleteProject ( project_dir ) ; } } public void testWSArgFileIndexParse ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; String path = "" + project_dir . getFile ( new Path ( "" ) ) . getFullPath ( ) . toOSString ( ) ; try { int_testIndexParse ( index , path ) ; } finally { TestUtils . deleteProject ( project_dir ) ; } } public void testWSSourceCollectionIndexParse ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; String path = "" + project_dir . getFile ( new Path ( "" ) ) . getFullPath ( ) . toOSString ( ) ; try { int_testIndexParse ( index , path ) ; } finally { TestUtils . deleteProject ( project_dir ) ; } } private void int_testIndexParse ( ISVDBIndex index , String path ) { String path_n = SVFileUtils . normalize ( path ) ; InputStream in = ( ( AbstractSVDBIndex ) index ) . getFileSystemProvider ( ) . openStream ( path ) ; assertNotNull ( "" + path + "" , in ) ; SVDBFile file = index . parse ( new NullProgressMonitor ( ) , in , path , null ) . second ( ) ; assertNotNull ( "" + path + "" , file ) ; ( ( AbstractSVDBIndex ) index ) . getFileSystemProvider ( ) . closeStream ( in ) ; if ( ! path_n . equals ( path ) ) { in = ( ( AbstractSVDBIndex ) index ) . getFileSystemProvider ( ) . openStream ( path_n ) ; assertNotNull ( "" + path_n + "" , in ) ; file = index . parse ( new NullProgressMonitor ( ) , in , path_n , null ) . second ( ) ; assertNotNull ( "" + path_n + "" , file ) ; ( ( AbstractSVDBIndex ) index ) . getFileSystemProvider ( ) . closeStream ( in ) ; } } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . db . refs . SVDBFileRefCollector ; import net . sf . sveditor . core . db . refs . SVDBRefCacheEntry ; import net . sf . sveditor . core . db . refs . SVDBRefCacheItem ; import net . sf . sveditor . core . db . refs . SVDBRefItem ; import net . sf . sveditor . core . db . refs . SVDBRefType ; import net . sf . sveditor . core . db . refs . SVDBTypeRefMatcher ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . IndexTestUtils ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestIndexFileRefs extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testUVMIncludeRefs ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { TestUtils . delete ( test_dir ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File uvm_src = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , uvm_src ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; IndexTestUtils . assertNoErrWarn ( log , index ) ; for ( String filename : index . getFileList ( new NullProgressMonitor ( ) ) ) { SVDBFileRefCollector finder = new SVDBFileRefCollector ( ) ; SVDBFile file = index . findFile ( filename ) ; System . out . println ( "" + filename ) ; finder . visitFile ( file ) ; SVDBRefCacheEntry ref = finder . getReferences ( ) ; for ( SVDBRefType t : SVDBRefType . values ( ) ) { System . out . println ( "" + t ) ; for ( String n : ref . getRefSet ( t ) ) { System . out . println ( "" + n ) ; } } } LogFactory . removeLogHandle ( log ) ; } public void testUVMComponentRefs ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { TestUtils . delete ( test_dir ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File uvm_src = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , uvm_src ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; long index_build_start = System . currentTimeMillis ( ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; long index_build_end = System . currentTimeMillis ( ) ; IndexTestUtils . assertNoErrWarn ( log , index ) ; long ref_find_start = System . currentTimeMillis ( ) ; List < SVDBRefCacheItem > refs = index . findReferences ( new NullProgressMonitor ( ) , "" , new SVDBTypeRefMatcher ( ) ) ; for ( SVDBRefCacheItem item : refs ) { log . debug ( "" + item . getFilename ( ) ) ; List < SVDBRefItem > ref_items = item . findReferences ( new NullProgressMonitor ( ) ) ; for ( SVDBRefItem ref_item : ref_items ) { System . out . println ( "" + ref_item . getLeaf ( ) . getType ( ) + "" + SVDBItem . getName ( ref_item . getLeaf ( ) ) + "" + ref_item . getRoot ( ) . getFilePath ( ) ) ; } } long ref_find_end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( index_build_end - index_build_start ) ) ; System . out . println ( "" + ( ref_find_end - ref_find_start ) ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestBuiltinIndex extends TestCase { File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; } } public void testBuiltinIndexNoErrors ( ) { File tmpdir = new File ( fTmpDir , "" ) ; if ( tmpdir . exists ( ) ) { tmpdir . delete ( ) ; } tmpdir . mkdirs ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( tmpdir ) ) ; SVDBIndexCollection index_mgr = new SVDBIndexCollection ( "" ) ; index_mgr . addPluginLibrary ( rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , SVCorePlugin . SV_BUILTIN_LIBRARY , SVDBPluginLibIndexFactory . TYPE , null ) ) ; ISVDBItemIterator index_it = index_mgr . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; ISVDBItemBase string_cls = null , process_cls = null , covergrp_cls = null ; ISVDBItemBase finish_task = null ; while ( index_it . hasNext ( ) ) { ISVDBItemBase it = index_it . nextItem ( ) ; if ( it . getType ( ) != SVDBItemType . File ) { assertNotNull ( "" + SVDBItem . getName ( it ) + "" , it . getLocation ( ) ) ; if ( it instanceof ISVDBScopeItem ) { assertNotNull ( "" + SVDBItem . getName ( it ) + "" , ( ( ISVDBScopeItem ) it ) . getEndLocation ( ) ) ; } } if ( SVDBStmt . isType ( it , SVDBItemType . VarDeclStmt ) ) { assertNotNull ( "" + SVDBItem . getName ( it ) + "" + SVDBItem . getName ( ( ( SVDBVarDeclStmt ) it ) . getParent ( ) ) + "" , ( ( SVDBVarDeclStmt ) it ) . getTypeInfo ( ) ) ; } if ( it . getType ( ) == SVDBItemType . Marker ) { markers . add ( ( SVDBMarker ) it ) ; } else if ( it . getType ( ) == SVDBItemType . ClassDecl ) { String name = ( ( SVDBClassDecl ) it ) . getName ( ) ; if ( name . equals ( "" ) ) { string_cls = it ; } else if ( name . equals ( "" ) ) { process_cls = it ; } else if ( name . equals ( "" ) ) { covergrp_cls = it ; } } else if ( it . getType ( ) == SVDBItemType . Task ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { finish_task = it ; } } } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , string_cls ) ; assertNotNull ( "" , process_cls ) ; assertNotNull ( "" , covergrp_cls ) ; assertNotNull ( "" , finish_task ) ; } } package net . sf . sveditor . core . tests . index . src_collection ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexChangeListener ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestSrcCollectionWSChanges extends TestCase implements ISVDBIndexChangeListener { private int fIndexRebuilt ; private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testFileAdded ( ) { fIndexRebuilt = ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData p_data = p_mgr . getProjectData ( project_dir ) ; p_data . getProjectIndexMgr ( ) . getItemIterator ( new NullProgressMonitor ( ) ) ; String class_str = "" + "" + "" + "" ; IFile class_1_2_file = project_dir . getFile ( "" ) ; try { class_1_2_file . create ( new StringInputStream ( class_str ) , true , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; fail ( "" + e . getMessage ( ) ) ; } try { index . parse ( new NullProgressMonitor ( ) , class_1_2_file . getContents ( ) , "" + class_1_2_file . getFullPath ( ) , null ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( "" + e . getMessage ( ) ) ; } assertEquals ( "" , , fIndexRebuilt ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null ; ISVDBItemBase class2 = null ; ISVDBItemBase class3 = null ; ISVDBItemBase class_1_2 = null ; ISVDBItemBase def_function = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class2 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class3 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { def_function = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class_1_2 = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { System . out . println ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertNotNull ( "" , class_1_2 ) ; assertNotNull ( "" , def_function ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; } public void testFileRemoved ( ) { fIndexRebuilt = ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } String class_str = "" + "" + "" + "" ; IFile class_1_2_file = project_dir . getFile ( "" ) ; try { class_1_2_file . create ( new StringInputStream ( class_str ) , true , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; fail ( "" + e . getMessage ( ) ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData p_data = p_mgr . getProjectData ( project_dir ) ; p_data . getProjectIndexMgr ( ) . getItemIterator ( new NullProgressMonitor ( ) ) ; try { index . parse ( new NullProgressMonitor ( ) , class_1_2_file . getContents ( ) , "" + class_1_2_file . getFullPath ( ) , null ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( "" + e . getMessage ( ) ) ; } ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null ; ISVDBItemBase class2 = null ; ISVDBItemBase class3 = null ; ISVDBItemBase class_1_2 = null ; ISVDBItemBase def_function = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class2 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class3 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { def_function = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class_1_2 = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { System . out . println ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertNotNull ( "" , class_1_2 ) ; assertNotNull ( "" , def_function ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; try { class_1_2_file . delete ( true , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; fail ( "" + e . getMessage ( ) ) ; } SVDBFile class_1_2_db = null ; try { class_1_2_db = index . parse ( new NullProgressMonitor ( ) , new StringInputStream ( class_str ) , "" + class_1_2_file . getFullPath ( ) , null ) . second ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( "" + e . getMessage ( ) ) ; } assertEquals ( "" , , fIndexRebuilt ) ; assertNull ( "" , class_1_2_db ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; class1 = null ; class2 = null ; class3 = null ; class_1_2 = null ; def_function = null ; markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class2 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class3 = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { def_function = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class_1_2 = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { System . out . println ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertNull ( "" , class_1_2 ) ; assertNotNull ( "" , def_function ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; } public void index_changed ( int reason , SVDBFile file ) { } public void index_rebuilt ( ) { fIndexRebuilt ++ ; } } package net . sf . sveditor . core . tests . index . src_collection ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . PrintStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . AbstractSVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBFileSystemProvider ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . IndexTestUtils ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class SrcCollectionBasics extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) . save_state ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testFindSourceRecursePkg ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null ; ISVDBItemBase class2 = null ; ISVDBItemBase class3 = null ; ISVDBItemBase def_function = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { class2 = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( name . equals ( "" ) ) { def_function = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { log . debug ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertNotNull ( "" , def_function ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testFindSourceRecurseNoPkg ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , project_dir . getName ( ) , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null ; ISVDBItemBase class2 = null ; ISVDBItemBase class3 = null ; ISVDBItemBase def_function = null ; ISVDBItemBase def_task = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { class2 = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( name . equals ( "" ) ) { def_function = tmp_it ; } else if ( name . equals ( "" ) ) { def_task = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { log . debug ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertNotNull ( "" , def_function ) ; assertNotNull ( "" , def_task ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testFindSourceRecurseModule ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { TestUtils . delete ( project_dir ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , project_dir . getName ( ) , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase top = null , top_t = null , sub = null ; ISVDBItemBase class1 = null ; ISVDBItemBase class3 = null ; ISVDBItemBase def_function = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; log . debug ( "" + tmp_it . getType ( ) + "" + name ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { top = tmp_it ; } else if ( name . equals ( "" ) ) { top_t = tmp_it ; } else if ( name . equals ( "" ) ) { sub = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( name . equals ( "" ) ) { def_function = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { log . debug ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class3 ) ; assertNotNull ( "" , top ) ; assertNotNull ( "" , top_t ) ; assertNotNull ( "" , sub ) ; assertNotNull ( "" , def_function ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testMissingIncludeRecurseModule ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { TestUtils . delete ( project_dir ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , project_dir . getName ( ) , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase top = null , top_t = null , sub = null ; ISVDBItemBase class1 = null ; ISVDBItemBase class3 = null ; ISVDBItemBase def_function = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; log . debug ( "" + tmp_it . getType ( ) + "" + name ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { top = tmp_it ; } else if ( name . equals ( "" ) ) { top_t = tmp_it ; } else if ( name . equals ( "" ) ) { sub = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( name . equals ( "" ) ) { def_function = tmp_it ; } } ISVDBFileSystemProvider fs = ( ( AbstractSVDBIndex ) index ) . getFileSystemProvider ( ) ; String file_path = new File ( path , "" ) . getAbsolutePath ( ) ; index . parse ( new NullProgressMonitor ( ) , fs . openStream ( file_path ) , file_path , null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; for ( String file : index . getFileList ( new NullProgressMonitor ( ) ) ) { List < SVDBMarker > tmp_m = index . getMarkers ( file ) ; markers . addAll ( tmp_m ) ; } for ( ISVDBItemBase warn : markers ) { log . debug ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class3 ) ; assertNotNull ( "" , top ) ; assertNotNull ( "" , top_t ) ; assertNotNull ( "" , sub ) ; assertNotNull ( "" , def_function ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; assertEquals ( "" , , markers . size ( ) ) ; log . debug ( "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testBasicClassIncludingModule ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { TestUtils . delete ( project_dir ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , path . getName ( ) , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null ; ISVDBItemBase class2 = null ; ISVDBItemBase class3 = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { class2 = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { log . debug ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testBasicClassIncludingInterface ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { TestUtils . delete ( project_dir ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , path . getName ( ) , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null ; ISVDBItemBase class2 = null ; ISVDBItemBase class3 = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { class2 = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { log . debug ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testBasicClassIncludingProgram ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , path . getName ( ) , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null ; ISVDBItemBase class2 = null ; ISVDBItemBase class3 = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { class2 = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { log . debug ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testFSNewFileAdded ( ) throws IOException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { TestUtils . delete ( project_dir ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , project_dir . getName ( ) , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase top = null , top_t = null , sub = null ; ISVDBItemBase class1 = null ; ISVDBItemBase class3 = null ; ISVDBItemBase def_function = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; log . debug ( "" + tmp_it . getType ( ) + "" + name ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { top = tmp_it ; } else if ( name . equals ( "" ) ) { top_t = tmp_it ; } else if ( name . equals ( "" ) ) { sub = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( name . equals ( "" ) ) { def_function = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { log . debug ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class3 ) ; assertNotNull ( "" , top ) ; assertNotNull ( "" , top_t ) ; assertNotNull ( "" , sub ) ; assertNotNull ( "" , def_function ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; PrintStream out = new PrintStream ( new File ( project_dir , "" ) ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . close ( ) ; String new_class_path = new File ( project_dir , "" ) . getAbsolutePath ( ) ; FileInputStream in = new FileInputStream ( new File ( project_dir , "" ) ) ; SVDBFile new_class_file = index . parse ( new NullProgressMonitor ( ) , in , new_class_path , null ) . second ( ) ; assertNotNull ( new_class_file ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testOutsideWsRelativeIncPaths ( ) throws IOException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; log . debug ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File testdir = new File ( fTmpDir , "" ) ; File sub1 = new File ( testdir , "" ) ; File sub2 = new File ( sub1 , "" ) ; File sub3 = new File ( sub2 , "" ) ; if ( sub2 . exists ( ) ) { sub2 . delete ( ) ; } fProject = TestUtils . createProject ( "" , new File ( sub3 , "" ) ) ; String data_dir = "" ; utils . copyBundleFileToWS ( data_dir + "" , fProject ) ; utils . copyBundleFileToFS ( data_dir + "" , sub3 ) ; utils . copyBundleFileToFS ( data_dir + "" , sub2 ) ; utils . copyBundleFileToFS ( data_dir + "" , sub1 ) ; utils . copyBundleFileToFS ( data_dir + "" , testdir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( null ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , fProject . getName ( ) , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; index . setGlobalDefine ( "" , "" ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; log . debug ( "" + it_t . getType ( ) + "" + SVDBItem . getName ( it_t ) ) ; } IndexTestUtils . assertNoErrWarn ( log , index ) ; IndexTestUtils . assertFileHasElements ( index , "" , "" , "" , "" , "" ) ; ISVDBFileSystemProvider fs = ( ( AbstractSVDBIndex ) index ) . getFileSystemProvider ( ) ; String file_path = "" ; SVDBFile file = index . parse ( new NullProgressMonitor ( ) , fs . openStream ( file_path ) , file_path , null ) . second ( ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; ISVDBItemBase top = SVDBTestUtils . findInFile ( file , "" ) ; assertNotNull ( "" , top ) ; log . debug ( "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testCapsExtensionFiles ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( new TestIndexCacheFactory ( project_dir ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , path . getName ( ) , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null ; ISVDBItemBase class2 = null ; ISVDBItemBase class3 = null ; List < ISVDBItemBase > markers = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { class2 = tmp_it ; } else if ( name . equals ( "" ) ) { class3 = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { markers . add ( tmp_it ) ; } } for ( ISVDBItemBase warn : markers ) { System . out . println ( "" + ( ( SVDBMarker ) warn ) . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , class1 ) ; assertNotNull ( "" , class2 ) ; assertNotNull ( "" , class3 ) ; assertEquals ( "" , SVDBItem . getName ( class1 ) ) ; index . dispose ( ) ; } public void testSrcCollectWinPathsNormalize ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { TestUtils . delete ( project_dir ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; fProject = TestUtils . createProject ( "" , project_dir ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , project_dir . getName ( ) , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; IndexTestUtils . assertFileHasElements ( index , "" , "" , "" ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndex ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBWSFileSystemProvider ; import net . sf . sveditor . core . db . index . cache . InMemoryIndexCache ; import net . sf . sveditor . core . db . search . SVDBFindByNameMatcher ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import junit . framework . TestCase ; public class TestDeclCache extends TestCase { private IProject fProject ; private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testPackageCacheNonInclude ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; fProject = TestUtils . createProject ( "" , fTmpDir ) ; utils . copyBundleDirToWS ( "" , fProject ) ; ISVDBIndex index = new SVDBArgFileIndex ( "" , "" , new SVDBWSFileSystemProvider ( ) , new InMemoryIndexCache ( ) , null ) ; index . init ( new NullProgressMonitor ( ) ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; List < SVDBDeclCacheItem > pkg_list = index . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindByNameMatcher ( ) ) ; assertNotNull ( pkg_list ) ; assertEquals ( , pkg_list . size ( ) ) ; List < SVDBDeclCacheItem > pkg_content = index . findPackageDecl ( new NullProgressMonitor ( ) , pkg_list . get ( ) ) ; assertNotNull ( pkg_content ) ; SVDBDeclCacheItem cls1 = null , cls2 = null ; for ( SVDBDeclCacheItem item : pkg_content ) { if ( item . getName ( ) . equals ( "" ) ) { cls1 = item ; } else if ( item . getName ( ) . equals ( "" ) ) { cls2 = item ; } } assertNotNull ( cls1 ) ; assertNotNull ( cls2 ) ; } public void testPackageCacheInclude ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; fProject = TestUtils . createProject ( "" , fTmpDir ) ; utils . copyBundleDirToWS ( "" , fProject ) ; ISVDBIndex index = new SVDBArgFileIndex ( "" , "" , new SVDBWSFileSystemProvider ( ) , new InMemoryIndexCache ( ) , null ) ; index . init ( new NullProgressMonitor ( ) ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; List < SVDBDeclCacheItem > pkg_list = index . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindByNameMatcher ( ) ) ; assertNotNull ( pkg_list ) ; assertEquals ( , pkg_list . size ( ) ) ; assertEquals ( "" , pkg_list . get ( ) . getName ( ) ) ; List < SVDBDeclCacheItem > pkg_content = index . findPackageDecl ( new NullProgressMonitor ( ) , pkg_list . get ( ) ) ; assertNotNull ( pkg_content ) ; SVDBDeclCacheItem cls1 = null , cls2 = null ; for ( SVDBDeclCacheItem item : pkg_content ) { log . debug ( "" + item . getName ( ) ) ; if ( item . getName ( ) . equals ( "" ) ) { cls1 = item ; } else if ( item . getName ( ) . equals ( "" ) ) { cls2 = item ; } } assertNotNull ( cls1 ) ; assertNotNull ( cls2 ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . io . IOException ; import java . io . PrintStream ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . search . SVDBFindDefaultNameMatcher ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . IndexTestUtils ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestArgFileIndex extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; super . tearDown ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testIncludePathPriority ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; fProject = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , fProject ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1_dir1 = null , class1_dir2 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; log . debug ( "" + tmp_it . getType ( ) + "" + name ) ; if ( name . equals ( "" ) ) { class1_dir1 = tmp_it ; } else if ( name . equals ( "" ) ) { class1_dir2 = tmp_it ; } } assertNull ( "" , class1_dir2 ) ; assertNotNull ( "" , class1_dir1 ) ; LogFactory . removeLogHandle ( log ) ; } public void testWSLibPath ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; final IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; String names [ ] = { "" , "" , "" , "" } ; for ( String n : names ) { List < SVDBDeclCacheItem > res = index . findGlobalScopeDecl ( new NullProgressMonitor ( ) , n , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; assertEquals ( "" + n + "" , , res . size ( ) ) ; } LogFactory . removeLogHandle ( log ) ; } public void testArgFileIncludePath ( ) throws IOException { CoreReleaseTests . clearErrors ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; File project_dir_f = new File ( fTmpDir , "" ) ; if ( project_dir_f . exists ( ) ) { TestUtils . delete ( project_dir_f ) ; } final IProject project_dir = TestUtils . createProject ( "" , project_dir_f ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; SVCorePlugin . setenv ( "" , fTmpDir . getAbsolutePath ( ) + "" ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null , class2 = null ; ISVDBItemBase arg_file_multi_include = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; log . debug ( "" + tmp_it . getType ( ) + "" + name ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { class2 = tmp_it ; } else if ( name . equals ( "" ) ) { arg_file_multi_include = tmp_it ; } } assertNotNull ( class1 ) ; assertNotNull ( class2 ) ; assertNotNull ( arg_file_multi_include ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testEnvVarExpansion ( ) throws IOException { CoreReleaseTests . clearErrors ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; final IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; SVCorePlugin . setenv ( "" , fTmpDir . getAbsolutePath ( ) + "" ) ; File ext_lib = new File ( fTmpDir , "" ) ; ext_lib . mkdirs ( ) ; PrintStream ps ; ps = new PrintStream ( new File ( ext_lib , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . close ( ) ; ps = new PrintStream ( new File ( ext_lib , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . close ( ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1 = null , class2 = null ; ISVDBItemBase ext_pkg_1 = null , ext_pkg_2 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; String name = SVDBItem . getName ( tmp_it ) ; log . debug ( "" + tmp_it . getType ( ) + "" + name ) ; if ( name . equals ( "" ) ) { class1 = tmp_it ; } else if ( name . equals ( "" ) ) { class2 = tmp_it ; } else if ( name . equals ( "" ) ) { ext_pkg_1 = tmp_it ; } else if ( name . equals ( "" ) ) { ext_pkg_2 = tmp_it ; } } assertNotNull ( class1 ) ; assertNotNull ( class2 ) ; assertNotNull ( ext_pkg_1 ) ; assertNotNull ( ext_pkg_2 ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testMultiArgFile ( ) throws IOException { String testname = "" ; CoreReleaseTests . clearErrors ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; final IProject project_dir = TestUtils . createProject ( testname + "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" + testname + "" , SVDBArgFileIndexFactory . TYPE , null ) ; IndexTestUtils . assertFileHasElements ( index , "" , "" , "" ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testMultiArgFileEnvVar ( ) throws IOException { String testname = "" ; CoreReleaseTests . clearErrors ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; final IProject project_dir = TestUtils . createProject ( testname + "" ) ; File proj_subdir = new File ( fTmpDir , "" ) ; assertTrue ( proj_subdir . mkdirs ( ) ) ; SVCorePlugin . setenv ( "" , proj_subdir . getAbsolutePath ( ) ) ; String data_root = "" ; utils . copyBundleDirToWS ( data_root , project_dir ) ; for ( String f : new String [ ] { "" , "" , "" , "" } ) { utils . copyBundleFileToFS ( data_root + f , proj_subdir ) ; assertTrue ( utils . deleteWSFile ( project_dir , "" ) ) ; } File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" + testname + "" , SVDBArgFileIndexFactory . TYPE , null ) ; IndexTestUtils . assertFileHasElements ( index , "" , "" , "" ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; public class TestFileSystemIndexProviders { } package net . sf . sveditor . core . tests . index . cache ; import junit . framework . Test ; import junit . framework . TestSuite ; public class IndexCacheTests extends TestSuite { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( TestIndexCache . class ) ) ; return suite ; } } package net . sf . sveditor . core . tests . index . cache ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInputStream ; import java . io . DataOutputStream ; import java . io . File ; import java . io . IOException ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCacheFactory ; import net . sf . sveditor . core . db . index . cache . SVDBDirFS ; import net . sf . sveditor . core . db . index . cache . SVDBFileIndexCache ; import net . sf . sveditor . core . db . persistence . DBFormatException ; import net . sf . sveditor . core . db . persistence . DBWriteException ; import net . sf . sveditor . core . db . persistence . IDBReader ; import net . sf . sveditor . core . db . persistence . IDBWriter ; import net . sf . sveditor . core . db . persistence . SVDBPersistenceRW ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestNullIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestIndexCache extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { SVCorePlugin . getJobMgr ( ) . dispose ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testFileCacheBasics ( ) { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File test_dir = new File ( fTmpDir , "" ) ; final File db_dir = new File ( fTmpDir , "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; CoreReleaseTests . clearErrors ( ) ; assertTrue ( db_dir . mkdirs ( ) ) ; assertTrue ( test_dir . mkdirs ( ) ) ; utils . unpackBundleZipToFS ( "" , fTmpDir ) ; File xbus = new File ( fTmpDir , "" ) ; fProject = TestUtils . createProject ( "" , xbus ) ; SVDBIndexRegistry rgy = new SVDBIndexRegistry ( ) ; SVCorePlugin . getDefault ( ) . setSVDBIndexRegistry ( rgy ) ; ISVDBIndexCacheFactory f = new ISVDBIndexCacheFactory ( ) { public ISVDBIndexCache createIndexCache ( String project_name , String base_location ) { SVDBDirFS fs = new SVDBDirFS ( db_dir ) ; fs . setEnableAsyncClear ( false ) ; ISVDBIndexCache cache = new SVDBFileIndexCache ( fs ) ; return cache ; } public void compactCache ( List < ISVDBIndexCache > cache_list ) { } } ; rgy . init ( f ) ; long start , end ; ISVDBIndex index ; ISVDBItemIterator it ; start = System . currentTimeMillis ( ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; Iterable < String > l_1 = index . getFileList ( new NullProgressMonitor ( ) ) ; index . findFile ( l_1 . iterator ( ) . next ( ) ) ; end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( it . hasNext ( ) ) { it . nextItem ( ) ; } index . dispose ( ) ; end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; rgy . init ( f ) ; start = System . currentTimeMillis ( ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; Iterable < String > l = index . getFileList ( new NullProgressMonitor ( ) ) ; for ( String file : l ) { index . findFile ( file ) ; } end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testFileCacheBasicsUVM ( ) { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; final File db_dir = new File ( fTmpDir , "" ) ; File test_dir = new File ( fTmpDir , "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; CoreReleaseTests . clearErrors ( ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; assertTrue ( db_dir . mkdirs ( ) ) ; assertTrue ( test_dir . mkdirs ( ) ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File uvm = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , uvm ) ; SVDBIndexRegistry rgy = new SVDBIndexRegistry ( ) ; SVCorePlugin . getDefault ( ) . setSVDBIndexRegistry ( rgy ) ; ISVDBIndexCacheFactory f = new ISVDBIndexCacheFactory ( ) { public ISVDBIndexCache createIndexCache ( String project_name , String base_location ) { SVDBDirFS fs = new SVDBDirFS ( db_dir ) ; fs . setEnableAsyncClear ( false ) ; ISVDBIndexCache cache = new SVDBFileIndexCache ( fs ) ; return cache ; } public void compactCache ( List < ISVDBIndexCache > cache_list ) { } } ; rgy . init ( f ) ; long start , end ; ISVDBIndex index ; ISVDBItemIterator it ; start = System . currentTimeMillis ( ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; Iterable < String > l_1 = index . getFileList ( new NullProgressMonitor ( ) ) ; index . findFile ( l_1 . iterator ( ) . next ( ) ) ; end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( it . hasNext ( ) ) { it . nextItem ( ) ; } index . dispose ( ) ; end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; rgy . init ( f ) ; start = System . currentTimeMillis ( ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; index . findFile ( "" ) ; end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testFileCacheUVMDumpLoadBug ( ) throws IOException , DBFormatException , DBWriteException { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; final File db_dir = new File ( fTmpDir , "" ) ; File test_dir = new File ( fTmpDir , "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; CoreReleaseTests . clearErrors ( ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; assertTrue ( db_dir . mkdirs ( ) ) ; assertTrue ( test_dir . mkdirs ( ) ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File uvm = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , uvm ) ; SVDBIndexRegistry rgy = new SVDBIndexRegistry ( ) ; SVCorePlugin . getDefault ( ) . setSVDBIndexRegistry ( rgy ) ; TestNullIndexCacheFactory test_cache_f = new TestNullIndexCacheFactory ( ) ; rgy . init ( test_cache_f ) ; long start , end ; ISVDBIndex index ; ISVDBItemIterator it ; start = System . currentTimeMillis ( ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; Iterable < String > l_1 = index . getFileList ( new NullProgressMonitor ( ) ) ; index . findFile ( l_1 . iterator ( ) . next ( ) ) ; end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( it . hasNext ( ) ) { it . nextItem ( ) ; } index . dispose ( ) ; end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; SVDBFile file = index . findFile ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutputStream dos = new DataOutputStream ( bos ) ; IDBWriter writer = null ; try { writer = new SVDBPersistenceRW ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } writer . setDebugEn ( true ) ; IDBReader reader = new SVDBPersistenceRW ( ) ; reader . setDebugEn ( true ) ; writer . init ( dos ) ; writer . writeObject ( file . getClass ( ) , file ) ; dos . flush ( ) ; bos . flush ( ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; DataInputStream din = new DataInputStream ( bis ) ; reader . init ( din ) ; SVDBFile file_2 = new SVDBFile ( ) ; reader . readObject ( null , file_2 . getClass ( ) , file_2 ) ; end = System . currentTimeMillis ( ) ; log . debug ( "" + ( end - start ) + "" ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; import java . util . ArrayList ; import java . util . List ; import junit . framework . Test ; import junit . framework . TestCase ; import junit . framework . TestSuite ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . search . SVDBFindDefaultNameMatcher ; import net . sf . sveditor . core . tests . index . libIndex . WSArgFileIndexChanges ; import net . sf . sveditor . core . tests . index . libIndex . WSLibIndexFileChanges ; import net . sf . sveditor . core . tests . index . src_collection . SrcCollectionBasics ; import net . sf . sveditor . core . tests . objects . ObjectsTests ; import org . eclipse . core . runtime . NullProgressMonitor ; public class IndexTests extends TestSuite { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( WSLibIndexFileChanges . class ) ) ; suite . addTest ( new TestSuite ( WSArgFileIndexChanges . class ) ) ; suite . addTest ( new TestSuite ( SrcCollectionBasics . class ) ) ; suite . addTest ( new TestSuite ( TestBuiltinIndex . class ) ) ; suite . addTest ( new TestSuite ( TestDeclCache . class ) ) ; suite . addTest ( new TestSuite ( SrcCollectionBasics . class ) ) ; suite . addTest ( new TestSuite ( TestIndexMissingIncludeDefine . class ) ) ; suite . addTest ( new TestSuite ( TestGlobalDefine . class ) ) ; suite . addTest ( new TestSuite ( TestVmmBasics . class ) ) ; suite . addTest ( new TestSuite ( TestOvmBasics . class ) ) ; suite . addTest ( new TestSuite ( TestUvmBasics . class ) ) ; suite . addTest ( new TestSuite ( TestIndexParse . class ) ) ; suite . addTest ( new TestSuite ( TestArgFileIndex . class ) ) ; suite . addTest ( new TestSuite ( TestIndexPersistance . class ) ) ; suite . addTest ( new TestSuite ( TestOpencoresProjects . class ) ) ; suite . addTest ( new TestSuite ( TestCrossIndexReferences . class ) ) ; suite . addTest ( new TestSuite ( TestIndexFileRefs . class ) ) ; suite . addTest ( new TestSuite ( ObjectsTests . class ) ) ; return suite ; } public static List < SVDBMarker > getErrorsWarnings ( ISVDBIndexIterator index_it ) { ISVDBItemIterator it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > ret = new ArrayList < SVDBMarker > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; if ( it_t . getType ( ) == SVDBItemType . Marker ) { ret . add ( ( SVDBMarker ) it_t ) ; } } return ret ; } public static void assertContains ( ISVDBIndexIterator index_it , String name , SVDBItemType type ) { List < SVDBDeclCacheItem > result = index_it . findGlobalScopeDecl ( new NullProgressMonitor ( ) , name , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; TestCase . assertEquals ( "" + name , , result . size ( ) ) ; SVDBDeclCacheItem item_c = result . get ( ) ; TestCase . assertNotNull ( item_c . getSVDBItem ( ) ) ; TestCase . assertEquals ( "" + type , item_c . getSVDBItem ( ) . getType ( ) ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestGlobalDefine extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testLibIndexGlobalDefine ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; CoreReleaseTests . clearErrors ( ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData p_data = p_mgr . getProjectData ( project_dir ) ; try { int_testGlobalDefine ( "" , p_data , index ) ; } finally { TestUtils . deleteProject ( project_dir ) ; } assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; } public void testArgFileIndexGlobalDefine ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; CoreReleaseTests . clearErrors ( ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData p_data = p_mgr . getProjectData ( project_dir ) ; try { int_testGlobalDefine ( "" , p_data , index ) ; } finally { TestUtils . deleteProject ( project_dir ) ; } assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; } public void testSourceCollectionIndexGlobalDefine ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; CoreReleaseTests . clearErrors ( ) ; String pname = "" ; IProject project_dir = TestUtils . createProject ( pname ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVCorePlugin . getDefault ( ) . getProjMgr ( ) . init ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , pname , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData p_data = p_mgr . getProjectData ( project_dir ) ; try { int_testGlobalDefine ( "" , p_data , index ) ; } finally { TestUtils . deleteProject ( project_dir ) ; } assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; } private void int_testGlobalDefine ( String testname , SVDBProjectData project_data , ISVDBIndex index ) { LogHandle log = LogFactory . getLogHandle ( testname ) ; CoreReleaseTests . clearErrors ( ) ; SVProjectFileWrapper p_wrap = project_data . getProjectFileWrapper ( ) . duplicate ( ) ; p_wrap . getGlobalDefines ( ) . add ( new Tuple < String , String > ( "" , "" ) ) ; project_data . setProjectFileWrapper ( p_wrap ) ; p_wrap = project_data . getProjectFileWrapper ( ) ; assertEquals ( "" , , p_wrap . getGlobalDefines ( ) . size ( ) ) ; ISVDBItemIterator index_it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1_it = null ; while ( index_it . hasNext ( ) ) { ISVDBItemBase it_tmp = index_it . nextItem ( ) ; log . debug ( "" + it_tmp . getType ( ) + "" + SVDBItem . getName ( it_tmp ) ) ; if ( SVDBItem . getName ( it_tmp ) . equals ( "" ) ) { class1_it = it_tmp ; } } assertNotNull ( "" , class1_it ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . core . db . search . SVDBFindDefaultNameMatcher ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestCrossIndexReferences extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; CoreReleaseTests . clearErrors ( ) ; } @ Override protected void tearDown ( ) throws Exception { assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; } public void testBasicArgFileIndexCrossRef ( ) throws CoreException { String testname = "" ; SVDBProjectManager pmgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; IProject p1 = TestUtils . setupIndexWSProject ( null , fTmpDir , "" , "" ) ; IProject p2 = TestUtils . setupIndexWSProject ( null , fTmpDir , "" , "" ) ; IProjectDescription p2_desc = p2 . getDescription ( ) ; p2_desc . setReferencedProjects ( new IProject [ ] { p1 } ) ; p2 . setDescription ( p2_desc , new NullProgressMonitor ( ) ) ; SVDBProjectData p1_pdata = pmgr . getProjectData ( p1 ) ; SVProjectFileWrapper p1_fwrapper = p1_pdata . getProjectFileWrapper ( ) ; SVDBProjectData p2_pdata = pmgr . getProjectData ( p2 ) ; SVProjectFileWrapper p2_fwrapper = p2_pdata . getProjectFileWrapper ( ) ; p1_fwrapper . addArgFilePath ( "" ) ; p2_fwrapper . addArgFilePath ( "" ) ; p1_pdata . setProjectFileWrapper ( p1_fwrapper ) ; p2_pdata . setProjectFileWrapper ( p2_fwrapper ) ; SVDBIndexCollection p1_index = p1_pdata . getProjectIndexMgr ( ) ; SVDBIndexCollection p2_index = p2_pdata . getProjectIndexMgr ( ) ; List < SVDBDeclCacheItem > result = p2_index . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; assertEquals ( , result . size ( ) ) ; SVDBDeclCacheItem p1_c = result . get ( ) ; assertEquals ( "" , p1_c . getName ( ) ) ; assertEquals ( SVDBItemType . ClassDecl , p1_c . getType ( ) ) ; assertNotNull ( p1_c . getSVDBItem ( ) ) ; } public void testCircularArgFileIndexCrossRef ( ) throws CoreException { String testname = "" ; SVDBProjectManager pmgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; IProject p1 = TestUtils . setupIndexWSProject ( null , fTmpDir , "" , "" ) ; IProject p2 = TestUtils . setupIndexWSProject ( null , fTmpDir , "" , "" ) ; IProjectDescription p2_desc = p2 . getDescription ( ) ; p2_desc . setReferencedProjects ( new IProject [ ] { p1 } ) ; p2 . setDescription ( p2_desc , new NullProgressMonitor ( ) ) ; IProjectDescription p1_desc = p1 . getDescription ( ) ; p1_desc . setReferencedProjects ( new IProject [ ] { p2 } ) ; p1 . setDescription ( p1_desc , new NullProgressMonitor ( ) ) ; SVDBProjectData p1_pdata = pmgr . getProjectData ( p1 ) ; SVProjectFileWrapper p1_fwrapper = p1_pdata . getProjectFileWrapper ( ) ; SVDBProjectData p2_pdata = pmgr . getProjectData ( p2 ) ; SVProjectFileWrapper p2_fwrapper = p2_pdata . getProjectFileWrapper ( ) ; p1_fwrapper . addArgFilePath ( "" ) ; p2_fwrapper . addArgFilePath ( "" ) ; p1_pdata . setProjectFileWrapper ( p1_fwrapper ) ; p2_pdata . setProjectFileWrapper ( p2_fwrapper ) ; SVDBIndexCollection p1_index = p1_pdata . getProjectIndexMgr ( ) ; SVDBIndexCollection p2_index = p2_pdata . getProjectIndexMgr ( ) ; List < SVDBDeclCacheItem > result = p2_index . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , SVDBFindDefaultNameMatcher . getDefault ( ) ) ; assertEquals ( , result . size ( ) ) ; SVDBDeclCacheItem p1_c = result . get ( ) ; assertEquals ( "" , p1_c . getName ( ) ) ; assertEquals ( SVDBItemType . ClassDecl , p1_c . getType ( ) ) ; assertNotNull ( p1_c . getSVDBItem ( ) ) ; } public void testIteratorCircularArgFileIndexCrossRef ( ) throws CoreException { String testname = "" ; SVDBProjectManager pmgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; IProject p1 = TestUtils . setupIndexWSProject ( null , fTmpDir , "" , "" ) ; IProject p2 = TestUtils . setupIndexWSProject ( null , fTmpDir , "" , "" ) ; IProjectDescription p2_desc = p2 . getDescription ( ) ; p2_desc . setReferencedProjects ( new IProject [ ] { p1 } ) ; p2 . setDescription ( p2_desc , new NullProgressMonitor ( ) ) ; IProjectDescription p1_desc = p1 . getDescription ( ) ; p1_desc . setReferencedProjects ( new IProject [ ] { p2 } ) ; p1 . setDescription ( p1_desc , new NullProgressMonitor ( ) ) ; SVDBProjectData p1_pdata = pmgr . getProjectData ( p1 ) ; SVProjectFileWrapper p1_fwrapper = p1_pdata . getProjectFileWrapper ( ) ; SVDBProjectData p2_pdata = pmgr . getProjectData ( p2 ) ; SVProjectFileWrapper p2_fwrapper = p2_pdata . getProjectFileWrapper ( ) ; p1_fwrapper . addArgFilePath ( "" ) ; p2_fwrapper . addArgFilePath ( "" ) ; p1_pdata . setProjectFileWrapper ( p1_fwrapper ) ; p2_pdata . setProjectFileWrapper ( p2_fwrapper ) ; SVDBIndexCollection p1_index = p1_pdata . getProjectIndexMgr ( ) ; SVDBIndexCollection p2_index = p2_pdata . getProjectIndexMgr ( ) ; ISVDBItemIterator it = p2_index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase p1_c = null , p2_c = null ; while ( it . hasNext ( ) ) { ISVDBItemBase item = it . nextItem ( ) ; if ( SVDBItem . getName ( item ) . equals ( "" ) ) { p1_c = item ; } else if ( SVDBItem . getName ( item ) . equals ( "" ) ) { p2_c = item ; } } assertNotNull ( p1_c ) ; assertNotNull ( p2_c ) ; assertEquals ( SVDBItemType . ClassDecl , p1_c . getType ( ) ) ; assertEquals ( SVDBItemType . ClassDecl , p2_c . getType ( ) ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcDirectiveScanner ; import net . sf . sveditor . core . preproc . SVPreProcOutput ; import net . sf . sveditor . core . preproc . SVPreProcessor ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestVmmBasics extends TestCase { private IProject fProject ; private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testBasicProcessing ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; File tmpdir = new File ( fTmpDir , "" ) ; if ( tmpdir . exists ( ) ) { TestUtils . delete ( tmpdir ) ; } assertTrue ( tmpdir . mkdirs ( ) ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( tmpdir ) ) ; SVDBIndexCollection index_mgr = new SVDBIndexCollection ( "" ) ; index_mgr . addPluginLibrary ( rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBPluginLibIndexFactory . TYPE , null ) ) ; ISVDBItemIterator index_it = index_mgr . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; ISVDBItemBase vmm_xtor = null ; while ( index_it . hasNext ( ) ) { ISVDBItemBase it = index_it . nextItem ( ) ; String name = SVDBItem . getName ( it ) ; log . debug ( "" + it . getType ( ) + "" + name ) ; if ( it . getType ( ) == SVDBItemType . Marker ) { markers . add ( ( SVDBMarker ) it ) ; } else if ( it . getType ( ) == SVDBItemType . ClassDecl ) { if ( name . equals ( "" ) ) { vmm_xtor = it ; } } else if ( SVDBStmt . isType ( it , SVDBItemType . VarDeclStmt ) ) { SVDBVarDeclStmt v = ( SVDBVarDeclStmt ) it ; SVDBVarDeclItem vi = ( SVDBVarDeclItem ) v . getChildren ( ) . iterator ( ) . next ( ) ; assertNotNull ( "" + SVDBItem . getName ( v . getParent ( ) ) + "" + vi . getName ( ) + "" , v . getTypeInfo ( ) ) ; } } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , vmm_xtor ) ; LogFactory . removeLogHandle ( log ) ; } public void testEthernetExample ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { TestUtils . delete ( test_dir ) ; } test_dir . mkdirs ( ) ; utils . copyBundleDirToFS ( "" , test_dir ) ; File ethernet = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , ethernet ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) tmp_it ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; } for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testWishboneExample ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { TestUtils . delete ( test_dir ) ; } test_dir . mkdirs ( ) ; utils . copyBundleDirToFS ( "" , test_dir ) ; File wishbone = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , wishbone ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) tmp_it ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; } for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testScenariosExample ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { TestUtils . delete ( test_dir ) ; } test_dir . mkdirs ( ) ; utils . copyBundleDirToFS ( "" , test_dir ) ; File scenarios = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , scenarios ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; SVDBArgFileIndex af_index = ( SVDBArgFileIndex ) index ; SVPreProcessor pp = af_index . createPreProcScanner ( "" ) ; SVPreProcOutput pp_out = pp . preprocess ( ) ; int ch , lineno = ; StringBuilder sb_dbg = new StringBuilder ( ) ; sb_dbg . append ( lineno + "" ) ; StringBuilder sb = new StringBuilder ( ) ; while ( ( ch = pp_out . get_ch ( ) ) != - ) { sb_dbg . append ( ( char ) ch ) ; sb . append ( ( char ) ch ) ; if ( ch == '' ) { lineno ++ ; sb_dbg . append ( lineno + "" ) ; } } log . debug ( "" + sb_dbg . toString ( ) ) ; SVDBTestUtils . parse ( log , sb . toString ( ) , "" , false ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) tmp_it ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } } for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . search . SVDBFindPackageMatcher ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestUvmBasics extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testBasicExamplePkg ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String test_name = "" ; File test_dir = new File ( fTmpDir , test_name ) ; File proj_dir = new File ( test_dir , "" ) ; File uvm_dir = new File ( test_dir , "" ) ; File uvm_pkg = new File ( test_dir , "" ) ; StringBuilder list_file_conent = new StringBuilder ( ) ; list_file_conent . append ( "" + uvm_dir . toString ( ) + "" + uvm_pkg . toString ( ) + "" + "" ) ; HashSet < String > requiredClasses = TestUtils . newHashSet ( "" , "" , "" , "" ) ; doTestUVMExample ( test_name , test_dir , proj_dir , list_file_conent . toString ( ) , requiredClasses , null ) ; } public void testBasicExampleEventPool ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String test_name = "" ; File test_dir = new File ( fTmpDir , test_name ) ; File proj_dir = new File ( test_dir , "" ) ; File uvm_dir = new File ( test_dir , "" ) ; File uvm_pkg = new File ( test_dir , "" ) ; StringBuilder list_file_conent = new StringBuilder ( ) ; list_file_conent . append ( "" + uvm_dir . toString ( ) + "" + uvm_pkg . toString ( ) + "" + "" ) ; HashSet < String > requiredClasses = TestUtils . newHashSet ( ) ; doTestUVMExample ( test_name , test_dir , proj_dir , list_file_conent . toString ( ) , requiredClasses , null ) ; } public void testBasicExampleModule ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String test_name = "" ; File test_dir = new File ( fTmpDir , test_name ) ; File proj_dir = new File ( test_dir , "" ) ; File uvm_dir = new File ( test_dir , "" ) ; File uvm_pkg = new File ( test_dir , "" ) ; StringBuilder list_file_conent = new StringBuilder ( ) ; list_file_conent . append ( "" + uvm_dir . toString ( ) + "" + uvm_pkg . toString ( ) + "" + "" ) ; HashSet < String > requiredClasses = TestUtils . newHashSet ( "" , "" ) ; doTestUVMExample ( test_name , test_dir , proj_dir , list_file_conent . toString ( ) , requiredClasses , null ) ; } public void testTrivial ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String test_name = "" ; File test_dir = new File ( fTmpDir , test_name ) ; File proj_dir = new File ( test_dir , "" ) ; File uvm_dir = new File ( test_dir , "" ) ; File uvm_pkg = new File ( test_dir , "" ) ; StringBuilder list_file_conent = new StringBuilder ( ) ; list_file_conent . append ( "" + uvm_dir . toString ( ) + "" + uvm_pkg . toString ( ) + "" + "" ) ; HashSet < String > requiredClasses = TestUtils . newHashSet ( "" ) ; doTestUVMExample ( test_name , test_dir , proj_dir , list_file_conent . toString ( ) , requiredClasses , null ) ; } public void testSequenceBasicReadWrite ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String test_name = "" ; File test_dir = new File ( fTmpDir , test_name ) ; File proj_dir = new File ( test_dir , "" ) ; File uvm_dir = new File ( test_dir , "" ) ; File uvm_pkg = new File ( test_dir , "" ) ; StringBuilder list_file_conent = new StringBuilder ( ) ; list_file_conent . append ( "" + uvm_dir . toString ( ) + "" + uvm_pkg . toString ( ) + "" + "" ) ; HashSet < String > requiredClasses = TestUtils . newHashSet ( "" , "" , "" , "" , "" , "" ) ; doTestUVMExample ( test_name , test_dir , proj_dir , list_file_conent . toString ( ) , requiredClasses , null ) ; } public void testSequenceBasicReadWriteWithDeclCache ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String test_name = "" ; File test_dir = new File ( fTmpDir , test_name ) ; File proj_dir = new File ( test_dir , "" ) ; File uvm_dir = new File ( test_dir , "" ) ; File uvm_pkg = new File ( test_dir , "" ) ; StringBuilder list_file_conent = new StringBuilder ( ) ; list_file_conent . append ( "" + uvm_dir . toString ( ) + "" + uvm_pkg . toString ( ) + "" + "" ) ; HashMap < String , HashSet < String > > requiredPkgDecls = new HashMap < String , HashSet < String > > ( ) ; requiredPkgDecls . put ( "" , TestUtils . newHashSet ( "" , "" , "" , "" , "" , "" ) ) ; requiredPkgDecls . put ( "" , TestUtils . newHashSet ( "" , "" , "" , "" , "" , "" ) ) ; doTestUVMExample ( test_name , test_dir , proj_dir , list_file_conent . toString ( ) , null , requiredPkgDecls ) ; } public void testInterfaces ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String test_name = "" ; File test_dir = new File ( fTmpDir , test_name ) ; File proj_dir = new File ( test_dir , "" ) ; File uvm_dir = new File ( test_dir , "" ) ; File uvm_pkg = new File ( test_dir , "" ) ; StringBuilder list_file_conent = new StringBuilder ( ) ; list_file_conent . append ( "" + uvm_dir . toString ( ) + "" + uvm_pkg . toString ( ) + "" + "" ) ; HashSet < String > requiredClasses = TestUtils . newHashSet ( "" , "" ) ; doTestUVMExample ( test_name , test_dir , proj_dir , list_file_conent . toString ( ) , requiredClasses , null ) ; } public void doTestUVMExample ( String testName , File testDir , File projDir , String listFileContent , HashSet < String > requiredClasses , HashMap < String , HashSet < String > > requiredPkgDecls ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testName ) ; if ( requiredClasses != null ) { requiredClasses . add ( "" ) ; requiredClasses . add ( "" ) ; requiredClasses . add ( "" ) ; requiredClasses . add ( "" ) ; requiredClasses . add ( "" ) ; requiredClasses . add ( "" ) ; } testDir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , testDir ) ; File listFile = new File ( projDir , "" ) ; fProject = TestUtils . createProject ( testName , projDir ) ; SVFileUtils . writeToFile ( listFile , listFileContent ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , listFile . toString ( ) , SVDBArgFileIndexFactory . TYPE , null ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase item = it . nextItem ( ) ; if ( item . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) item ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } else if ( item . getType ( ) == SVDBItemType . ClassDecl ) { String itemName = SVDBItem . getName ( item ) ; if ( requiredClasses != null && requiredClasses . contains ( itemName ) ) { requiredClasses . remove ( itemName ) ; } } else if ( SVDBStmt . isType ( item , SVDBItemType . VarDeclStmt ) ) { SVDBVarDeclStmt v = ( SVDBVarDeclStmt ) item ; SVDBVarDeclItem vi = ( SVDBVarDeclItem ) v . getChildren ( ) . iterator ( ) . next ( ) ; assertNotNull ( "" + SVDBItem . getName ( v . getParent ( ) ) + "" + vi . getName ( ) + "" , v . getTypeInfo ( ) ) ; } } if ( requiredPkgDecls != null ) { for ( String requiredPkgName : requiredPkgDecls . keySet ( ) ) { log . debug ( "" + requiredPkgName ) ; List < SVDBDeclCacheItem > packages = index . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindPackageMatcher ( ) ) ; HashMap < String , SVDBDeclCacheItem > pkgMap = new HashMap < String , SVDBDeclCacheItem > ( ) ; log . debug ( "" ) ; for ( SVDBDeclCacheItem pkg : packages ) { log . debug ( "" + pkg . getName ( ) ) ; pkgMap . put ( pkg . getName ( ) , pkg ) ; } log . debug ( "" ) ; assertTrue ( "" + requiredPkgName + "" , pkgMap . containsKey ( requiredPkgName ) ) ; if ( pkgMap . containsKey ( requiredPkgName ) ) { List < SVDBDeclCacheItem > pkgDecls = index . findPackageDecl ( new NullProgressMonitor ( ) , pkgMap . get ( requiredPkgName ) ) ; assertNotNull ( "" , pkgDecls ) ; if ( pkgDecls != null ) { HashMap < String , SVDBDeclCacheItem > pkgDeclMap = new HashMap < String , SVDBDeclCacheItem > ( ) ; log . debug ( "" + requiredPkgName ) ; for ( SVDBDeclCacheItem decl : pkgDecls ) { log . debug ( "" + decl . getType ( ) + "" + decl . getName ( ) ) ; pkgDeclMap . put ( decl . getName ( ) , decl ) ; } log . debug ( "" + requiredPkgName ) ; HashSet < String > requiredPkgDeclsCopy = new HashSet < String > ( requiredPkgDecls . get ( requiredPkgName ) ) ; for ( String requiredPkgDecl : requiredPkgDeclsCopy ) { if ( pkgDeclMap . containsKey ( requiredPkgDecl ) ) { requiredPkgDecls . get ( requiredPkgName ) . remove ( requiredPkgDecl ) ; } } } } } } for ( SVDBMarker m : errors ) { log . error ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; if ( requiredClasses != null ) { for ( String className : requiredClasses ) { log . error ( "" + "" + className + "" ) ; } assertTrue ( "" , requiredClasses . size ( ) == ) ; } int unfoundDecls = ; if ( requiredPkgDecls != null ) { for ( String pkgName : requiredPkgDecls . keySet ( ) ) { for ( String declName : requiredPkgDecls . get ( pkgName ) ) { log . error ( "" + "" + pkgName + "" + declName + "" ) ; unfoundDecls ++ ; } } } assertEquals ( "" , , unfoundDecls ) ; for ( SVDBMarker m : errors ) { log . error ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexChangeListener ; import net . sf . sveditor . core . db . index . SVDBArgFileIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibIndex ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestIndexPersistance extends TestCase implements ISVDBIndexChangeListener { private File fTmpDir ; private int fRebuildCount ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void index_changed ( int reason , SVDBFile file ) { } public void index_rebuilt ( ) { fRebuildCount ++ ; } public void testWSArgFileIndex ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; CoreReleaseTests . clearErrors ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File test_dir = new File ( fTmpDir , "" ) ; File db_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { assertTrue ( test_dir . delete ( ) ) ; } assertTrue ( test_dir . mkdirs ( ) ) ; if ( db_dir . exists ( ) ) { assertTrue ( db_dir . delete ( ) ) ; } assertTrue ( db_dir . mkdirs ( ) ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File xbus = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , xbus ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db_dir ) ) ; ISVDBIndex index ; SVDBFile file ; InputStream in ; String path = "" ; log . debug ( "" ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; fRebuildCount = ; in = ( ( SVDBArgFileIndex ) index ) . getFileSystemProvider ( ) . openStream ( path ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; file = index . parse ( new NullProgressMonitor ( ) , in , path , errors ) . second ( ) ; assertNotNull ( file ) ; assertEquals ( , fRebuildCount ) ; for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; log . debug ( "" ) ; rgy . save_state ( ) ; log . debug ( "" ) ; rgy . init ( TestIndexCacheFactory . instance ( db_dir ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; fRebuildCount = ; in = ( ( SVDBArgFileIndex ) index ) . getFileSystemProvider ( ) . openStream ( path ) ; file = index . parse ( new NullProgressMonitor ( ) , in , path , null ) . second ( ) ; assertNotNull ( file ) ; assertEquals ( , fRebuildCount ) ; log . debug ( "" ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testWSLibIndex ( ) { CoreReleaseTests . clearErrors ( ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File test_dir = new File ( fTmpDir , "" ) ; File db_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { TestUtils . delete ( test_dir ) ; } assertTrue ( test_dir . mkdirs ( ) ) ; if ( db_dir . exists ( ) ) { TestUtils . delete ( db_dir ) ; } assertTrue ( db_dir . mkdirs ( ) ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File ovm = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , ovm ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db_dir ) ) ; ISVDBIndex index ; SVDBFile file ; InputStream in ; String path = "" ; log . debug ( "" ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; fRebuildCount = ; in = ( ( SVDBLibIndex ) index ) . getFileSystemProvider ( ) . openStream ( path ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; file = index . parse ( new NullProgressMonitor ( ) , in , path , errors ) . second ( ) ; assertNotNull ( file ) ; assertEquals ( , fRebuildCount ) ; for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; log . debug ( "" ) ; rgy . save_state ( ) ; log . debug ( "" ) ; rgy . init ( TestIndexCacheFactory . instance ( db_dir ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; fRebuildCount = ; in = ( ( SVDBLibIndex ) index ) . getFileSystemProvider ( ) . openStream ( path ) ; file = index . parse ( new NullProgressMonitor ( ) , in , path , null ) . second ( ) ; assertNotNull ( file ) ; assertEquals ( , fRebuildCount ) ; log . debug ( "" ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; TestUtils . deleteProject ( fProject ) ; } } package net . sf . sveditor . core . tests . index . persistence ; import junit . framework . Test ; import junit . framework . TestSuite ; public class PersistenceTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( TestFilesystemLibPersistence . class ) ) ; suite . addTest ( new TestSuite ( TestWorkspaceLibPersistence . class ) ) ; suite . addTest ( new TestSuite ( ArgFilePersistence . class ) ) ; suite . addTest ( new TestSuite ( SrcCollectionPersistence . class ) ) ; suite . addTest ( new TestSuite ( TestPersistenceUnit . class ) ) ; return suite ; } } package net . sf . sveditor . core . tests . index . persistence ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . PrintStream ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestFilesystemLibPersistence extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testTimestampChangeDetected ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { TestUtils . delete ( project_dir ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBLibPathIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; rgy . save_state ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; log . debug ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } ByteArrayOutputStream out = utils . readBundleFile ( "" ) ; PrintStream ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , new File ( project_dir , "" ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBLibPathIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } log . debug ( "" + target_it ) ; assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testFSLibIndexFilelistChangeDetected ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBLibPathIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; SVDBMarker missing_inc = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; } else if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { missing_inc = ( SVDBMarker ) tmp_it ; } } for ( String file : index . getFileList ( new NullProgressMonitor ( ) ) ) { List < SVDBMarker > markers = index . getMarkers ( file ) ; for ( SVDBMarker m : markers ) { missing_inc = m ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; assertNotNull ( "" , missing_inc ) ; rgy . save_state ( ) ; log . debug ( "" ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; PrintStream ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; log . debug ( "" ) ; TestUtils . copy ( out , new File ( project_dir , "" ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBLibPathIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; index . dispose ( ) ; } } package net . sf . sveditor . core . tests . index . persistence ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInput ; import java . io . DataInputStream ; import java . io . DataOutput ; import java . io . DataOutputStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . SVDBBaseIndexCacheData ; import net . sf . sveditor . core . db . persistence . DBFormatException ; import net . sf . sveditor . core . db . persistence . DBWriteException ; import net . sf . sveditor . core . db . persistence . IDBReader ; import net . sf . sveditor . core . db . persistence . IDBWriter ; import net . sf . sveditor . core . db . persistence . SVDBPersistenceRW ; import net . sf . sveditor . core . db . refs . SVDBRefCacheEntry ; import net . sf . sveditor . core . db . refs . SVDBRefType ; public class TestPersistenceUnit extends TestCase { public void testRWRefCacheEntry ( ) throws DBFormatException , DBWriteException { IDBWriter writer = new SVDBPersistenceRW ( ) ; IDBReader reader = new SVDBPersistenceRW ( ) ; SVDBRefCacheEntry entry = new SVDBRefCacheEntry ( ) ; entry . setFilename ( "" ) ; entry . addTypeRef ( "" ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutput out = new DataOutputStream ( bos ) ; writer . init ( out ) ; writer . writeObject ( SVDBRefCacheEntry . class , entry ) ; ByteArrayInputStream bin = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; DataInput in = new DataInputStream ( bin ) ; reader . init ( in ) ; SVDBRefCacheEntry entry_i = new SVDBRefCacheEntry ( ) ; reader . readObject ( null , SVDBRefCacheEntry . class , entry_i ) ; assertTrue ( entry_i . getRefSet ( SVDBRefType . TypeReference ) . contains ( "" ) ) ; } public void testRWRefCacheEntryMap ( ) throws DBFormatException , DBWriteException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; IDBWriter writer = new SVDBPersistenceRW ( ) ; IDBReader reader = new SVDBPersistenceRW ( ) ; SVDBBaseIndexCacheData index_data = new SVDBBaseIndexCacheData ( "" ) ; SVDBRefCacheEntry entry = new SVDBRefCacheEntry ( ) ; entry . setFilename ( "" ) ; entry . addTypeRef ( "" ) ; index_data . fReferenceCacheMap . put ( "" , entry ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutput out = new DataOutputStream ( bos ) ; writer . init ( out ) ; writer . writeObject ( SVDBBaseIndexCacheData . class , index_data ) ; ByteArrayInputStream bin = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; DataInput in = new DataInputStream ( bin ) ; reader . init ( in ) ; SVDBBaseIndexCacheData index_data_i = new SVDBBaseIndexCacheData ( "" ) ; reader . readObject ( null , SVDBBaseIndexCacheData . class , index_data_i ) ; } } package net . sf . sveditor . core . tests . index . persistence ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInput ; import java . io . DataInputStream ; import java . io . DataOutput ; import java . io . DataOutputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . PrintStream ; import java . net . URL ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBInclude ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBLocation ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexCacheData ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBBaseIndexCacheData ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . persistence . DBFormatException ; import net . sf . sveditor . core . db . persistence . DBWriteException ; import net . sf . sveditor . core . db . persistence . IDBReader ; import net . sf . sveditor . core . db . persistence . IDBWriter ; import net . sf . sveditor . core . db . persistence . ISVDBPersistenceRWDelegate ; import net . sf . sveditor . core . db . persistence . JITPersistenceDelegateFactory ; import net . sf . sveditor . core . db . persistence . SVDBDelegatingPersistenceRW ; import net . sf . sveditor . core . db . persistence . SVDBPersistenceRW ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . TestNullIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . osgi . framework . Bundle ; public class TestPersistencePerformance extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testJITPersistence ( ) throws Exception { SVDBInclude inc = new SVDBInclude ( "" ) ; inc . setLocation ( new SVDBLocation ( , ) ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutputStream out = new DataOutputStream ( bos ) ; DataInputStream in ; long start , end ; SVDBDelegatingPersistenceRW dflt1 = new SVDBDelegatingPersistenceRW ( ) { @ Override public void writeEnumType ( Class enum_type , Enum value ) throws DBWriteException { System . out . println ( "" ) ; super . writeEnumType ( enum_type , value ) ; } @ Override public void writeString ( String val ) throws DBWriteException { System . out . println ( "" + val ) ; super . writeString ( val ) ; } @ Override public SVDBLocation readSVDBLocation ( ) throws DBFormatException { System . out . println ( "" ) ; return super . readSVDBLocation ( ) ; } @ Override public void writeSVDBLocation ( SVDBLocation loc ) throws DBWriteException { super . writeSVDBLocation ( loc ) ; } } ; SVDBDelegatingPersistenceRW dflt = new SVDBDelegatingPersistenceRW ( ) ; ISVDBPersistenceRWDelegate delegate = JITPersistenceDelegateFactory . instance ( ) . newDelegate ( ) ; int n_iter = ; dflt . init ( out ) ; delegate . init ( dflt , null , null ) ; start = System . currentTimeMillis ( ) ; for ( int i = ; i < n_iter ; i ++ ) { delegate . writeSVDBItem ( inc ) ; } in = new DataInputStream ( new ByteArrayInputStream ( bos . toByteArray ( ) ) ) ; dflt . init ( in ) ; for ( int i = ; i < n_iter ; i ++ ) { SVDBInclude inc_1 = ( SVDBInclude ) delegate . readSVDBItem ( SVDBItemType . Include , null ) ; } end = System . currentTimeMillis ( ) ; System . out . println ( "" + n_iter + "" + ( end - start ) ) ; } public void testInMemPersistence ( ) throws IOException , CoreException , DBFormatException , DBWriteException { IDBWriter writer = new SVDBPersistenceRW ( ) ; IDBReader reader = new SVDBPersistenceRW ( ) ; ByteArrayOutputStream bos = null ; Bundle bundle = SVCorePlugin . getDefault ( ) . getBundle ( ) ; URL cls_url = bundle . getEntry ( "" ) ; InputStream cls_in = cls_url . openStream ( ) ; String content = TestUtils . readInput ( cls_in ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; try { cls_in . close ( ) ; } catch ( IOException e ) { } bos = new ByteArrayOutputStream ( ) ; DataOutput out = new DataOutputStream ( bos ) ; writer . init ( out ) ; writer . writeSVDBItem ( file ) ; long start = System . currentTimeMillis ( ) ; for ( int i = ; i < ; i ++ ) { ByteArrayInputStream ba_in = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; DataInput in = new DataInputStream ( ba_in ) ; reader . init ( in ) ; reader . readSVDBItem ( null ) ; } long end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( end - start ) + "" ) ; } public void testFSPerf ( ) throws IOException , CoreException , DBFormatException , DBWriteException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { TestUtils . delete ( test_dir ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File ubus = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , ubus ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } db . mkdirs ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( new TestNullIndexCacheFactory ( ) ) ; PrintStream ps = new PrintStream ( new File ( ubus , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; ps . close ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; Iterable < String > files = index . getFileList ( new NullProgressMonitor ( ) ) ; SVDBPersistenceRW delegate = new SVDBPersistenceRW ( ) ; IDBWriter writer = delegate ; IDBReader reader = delegate ; long start = System . currentTimeMillis ( ) , end , total_time ; int iter = ; int total = ; total = ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutput dout = new DataOutputStream ( bos ) ; DataInput din = null ; start = System . currentTimeMillis ( ) ; for ( int i = ; i < iter ; i ++ ) { writer . init ( dout ) ; for ( String file : files ) { SVDBFile svdb_file = index . findFile ( file ) ; writer . writeSVDBItem ( svdb_file ) ; total ++ ; } } total = ; din = new DataInputStream ( new ByteArrayInputStream ( bos . toByteArray ( ) ) ) ; for ( int i = ; i < iter ; i ++ ) { reader . init ( din ) ; for ( String file : files ) { ISVDBItemBase item = reader . readSVDBItem ( null ) ; total ++ ; } } end = System . currentTimeMillis ( ) ; total_time = ( end - start ) ; if ( total_time == ) { total_time = ; } System . out . println ( "" + total + "" + total_time + "" ) ; System . out . println ( "" + ( total_time / total ) + "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testCacheDataPerf ( ) throws IOException , CoreException , DBFormatException , DBWriteException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; File test_dir = new File ( fTmpDir , testname ) ; if ( test_dir . exists ( ) ) { TestUtils . delete ( test_dir ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File ubus = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , ubus ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } db . mkdirs ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( new TestNullIndexCacheFactory ( ) ) ; PrintStream ps = new PrintStream ( new File ( ubus , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; ps . close ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; Iterable < String > files = index . getFileList ( new NullProgressMonitor ( ) ) ; SVDBPersistenceRW delegate = new SVDBPersistenceRW ( ) ; IDBWriter writer = delegate ; IDBReader reader = delegate ; long start = System . currentTimeMillis ( ) , end , total_time ; int iter = ; int total = ; total = ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutput dout = new DataOutputStream ( bos ) ; DataInput din = null ; SVDBBaseIndexCacheData cd = new SVDBBaseIndexCacheData ( "" ) ; SVDBBaseIndexCacheData cd2 = new SVDBBaseIndexCacheData ( "" ) ; SVDBArgFileIndexCacheData acd = new SVDBArgFileIndexCacheData ( "" ) ; SVDBArgFileIndexCacheData acd2 = new SVDBArgFileIndexCacheData ( "" ) ; SVDBFile f = new SVDBFile ( "" ) ; SVDBFile f2 = new SVDBFile ( ) ; List < SVDBDeclCacheItem > items = new ArrayList < SVDBDeclCacheItem > ( ) ; items . add ( new SVDBDeclCacheItem ( null , "" , "" , SVDBItemType . ActionBlockStmt , false ) ) ; cd . getDeclCacheMap ( ) . put ( "" , items ) ; start = System . currentTimeMillis ( ) ; for ( int i = ; i < iter ; i ++ ) { writer . init ( dout ) ; writer . writeObject ( SVDBBaseIndexCacheData . class , cd ) ; writer . writeObject ( SVDBArgFileIndexCacheData . class , acd ) ; writer . writeObject ( SVDBFile . class , f ) ; total ++ ; } total = ; din = new DataInputStream ( new ByteArrayInputStream ( bos . toByteArray ( ) ) ) ; for ( int i = ; i < iter ; i ++ ) { reader . init ( din ) ; reader . readObject ( null , SVDBBaseIndexCacheData . class , cd2 ) ; reader . readObject ( null , SVDBArgFileIndexCacheData . class , acd2 ) ; reader . readObject ( null , SVDBFile . class , f2 ) ; total ++ ; } end = System . currentTimeMillis ( ) ; total_time = ( end - start ) ; System . out . println ( "" + f2 . getFilePath ( ) ) ; if ( total_time == ) { total_time = ; } System . out . println ( "" + total + "" + total_time + "" ) ; System . out . println ( "" + ( total_time / total ) + "" ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index . persistence ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . PrintStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; public class TestWorkspaceLibPersistence extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testTimestampChangeDetected ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; rgy . save_state ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } ByteArrayOutputStream out = utils . readBundleFile ( "" ) ; PrintStream ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , project_dir . getFile ( new Path ( "" ) ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } log . debug ( "" + target_it ) ; assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testFilelistChangeDetected ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; rgy . save_state ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; log . debug ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } log . debug ( "" ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; PrintStream ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , project_dir . getFile ( new Path ( "" ) ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; } } package net . sf . sveditor . core . tests . index . persistence ; import java . util . Stack ; import junit . framework . TestCase ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; public class SVDBItemTestComparator { private Stack < ISVDBScopeItem > fScopeStack ; public SVDBItemTestComparator ( ) { fScopeStack = new Stack < ISVDBScopeItem > ( ) ; } public void compare ( ISVDBScopeItem i1 , ISVDBScopeItem i2 ) { TestCase . assertEquals ( "" + getScope ( i1 ) , i1 . getType ( ) , i2 . getType ( ) ) ; TestCase . assertEquals ( "" + getScope ( i1 ) , SVDBItem . getName ( i1 ) , SVDBItem . getName ( i2 ) ) ; TestCase . assertEquals ( "" + getScope ( i1 ) , i1 . getItems ( ) . size ( ) , i2 . getItems ( ) . size ( ) ) ; for ( int i = ; i < i1 . getItems ( ) . size ( ) ; i ++ ) { if ( ( i1 . getItems ( ) . get ( i ) instanceof ISVDBScopeItem ) || ( i2 . getItems ( ) . get ( i ) instanceof ISVDBScopeItem ) ) { TestCase . assertEquals ( true , ( i1 . getItems ( ) . get ( i ) instanceof ISVDBScopeItem ) ) ; TestCase . assertEquals ( true , ( i2 . getItems ( ) . get ( i ) instanceof ISVDBScopeItem ) ) ; fScopeStack . push ( i1 ) ; compare ( ( ISVDBScopeItem ) i1 . getItems ( ) . get ( i ) , ( ISVDBScopeItem ) i2 . getItems ( ) . get ( i ) ) ; fScopeStack . pop ( ) ; } } for ( int i = ; i < i1 . getItems ( ) . size ( ) ; i ++ ) { if ( ! ( i1 . getItems ( ) . get ( i ) instanceof ISVDBScopeItem ) ) { ISVDBItemBase i1_t = i1 . getItems ( ) . get ( i ) ; ISVDBItemBase i2_t = i2 . getItems ( ) . get ( i ) ; if ( ! i1_t . equals ( i2_t ) ) { i1_t . equals ( i2_t ) ; System . out . println ( "" + i1_t . getType ( ) + "" + SVDBItem . getName ( i1_t ) + "" + i2_t . getType ( ) + "" + SVDBItem . getName ( i2_t ) ) ; System . out . println ( "" + i1_t . getLocation ( ) + "" + i2_t . getLocation ( ) ) ; SVDBItemType it = i1 . getItems ( ) . get ( i ) . getType ( ) ; String type_name ; type_name = "" + it ; type_name += "" + SVDBItem . getName ( i1 . getItems ( ) . get ( i ) ) ; TestCase . assertTrue ( "" + type_name + "" + getScope ( i1 . getItems ( ) . get ( i ) ) , i1_t . equals ( i2_t ) ) ; } } } for ( int i = ; i < i1 . getItems ( ) . size ( ) ; i ++ ) { if ( ( i1 . getItems ( ) . get ( i ) instanceof ISVDBScopeItem ) ) { ISVDBItemBase i1_t = i1 . getItems ( ) . get ( i ) ; ISVDBItemBase i2_t = i2 . getItems ( ) . get ( i ) ; if ( ! i1_t . equals ( i2_t ) ) { i1_t . equals ( i2_t ) ; TestCase . assertTrue ( "" + ( i1 . getItems ( ) . get ( i ) . getType ( ) ) + "" + getScope ( i1 . getItems ( ) . get ( i ) ) , i1_t . equals ( i2_t ) ) ; } } } } private String getScope ( ISVDBItemBase leaf ) { StringBuilder ret = new StringBuilder ( ) ; for ( ISVDBScopeItem it : fScopeStack ) { ret . append ( SVDBItem . getName ( it ) ) ; ret . append ( "" ) ; } ret . append ( SVDBItem . getName ( leaf ) ) ; return ret . toString ( ) ; } } package net . sf . sveditor . core . tests . index . persistence ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . PrintStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexChangeListener ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; public class SrcCollectionPersistence extends TestCase implements ISVDBIndexChangeListener { private File fTmpDir ; private int fIndexRebuildCnt ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testWSTimestampChanged ( ) { ByteArrayOutputStream out ; PrintStream ps ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; fIndexRebuildCnt = ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; rgy . save_state ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; log . debug ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } log . debug ( "" ) ; out = new ByteArrayOutputStream ( ) ; ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , project_dir . getFile ( new Path ( "" ) ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; index . addChangeListener ( this ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertEquals ( "" , , fIndexRebuildCnt ) ; assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; TestUtils . deleteProject ( project_dir ) ; LogFactory . removeLogHandle ( log ) ; } public void testWSNoChange ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; rgy . save_state ( ) ; log . debug ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } log . debug ( "" ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; fIndexRebuildCnt = ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; index . addChangeListener ( this ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertEquals ( "" , , fIndexRebuildCnt ) ; assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; TestUtils . deleteProject ( project_dir ) ; LogFactory . removeLogHandle ( log ) ; } public void testFSTimestampChanged ( ) { ByteArrayOutputStream out ; PrintStream ps ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; fIndexRebuildCnt = ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; ISVDBItemBase class1_2 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_2 = tmp_it ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; assertNull ( "" , class1_2 ) ; rgy . save_state ( ) ; log . debug ( "" ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } out = new ByteArrayOutputStream ( ) ; ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; log . debug ( "" ) ; TestUtils . copy ( out , new File ( project_dir , "" ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; index . addChangeListener ( this ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertEquals ( "" + target_it + "" , , fIndexRebuildCnt ) ; assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testFSNoChange ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; fIndexRebuildCnt = ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; ISVDBItemBase class1_2 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_2 = tmp_it ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; assertNull ( "" , class1_2 ) ; rgy . save_state ( ) ; log . debug ( "" ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } fIndexRebuildCnt = ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBSourceCollectionIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; index . addChangeListener ( this ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertEquals ( "" , , fIndexRebuildCnt ) ; assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; LogFactory . removeLogHandle ( log ) ; } public void index_changed ( int reason , SVDBFile file ) { } public void index_rebuilt ( ) { fIndexRebuildCnt ++ ; } } package net . sf . sveditor . core . tests . index . persistence ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInputStream ; import java . io . DataOutputStream ; import java . io . IOException ; import java . util . ArrayList ; import junit . framework . TestCase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . SVDBBaseIndexCacheData ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . persistence . DBFormatException ; import net . sf . sveditor . core . db . persistence . DBWriteException ; import net . sf . sveditor . core . db . persistence . IDBReader ; import net . sf . sveditor . core . db . persistence . IDBWriter ; import net . sf . sveditor . core . db . persistence . SVDBPersistenceRW ; public class TestIndexCacheDataPersistence extends TestCase { private void dump_load ( SVDBBaseIndexCacheData data , SVDBBaseIndexCacheData data_n ) throws DBFormatException , DBWriteException , IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutputStream dos = new DataOutputStream ( bos ) ; IDBWriter writer = new SVDBPersistenceRW ( ) ; IDBReader reader = new SVDBPersistenceRW ( ) ; writer . init ( dos ) ; writer . writeObject ( data . getClass ( ) , data ) ; dos . flush ( ) ; DataInputStream dis = new DataInputStream ( new ByteArrayInputStream ( bos . toByteArray ( ) ) ) ; reader . init ( dis ) ; reader . readObject ( null , data_n . getClass ( ) , data_n ) ; } public void testBasics ( ) throws DBFormatException , DBWriteException , IOException { SVDBBaseIndexCacheData data = new SVDBBaseIndexCacheData ( "" ) ; SVDBBaseIndexCacheData data_n = new SVDBBaseIndexCacheData ( "" ) ; dump_load ( data , data_n ) ; assertEquals ( data . getBaseLocation ( ) , data_n . getBaseLocation ( ) ) ; } public void testDeclCache ( ) throws DBFormatException , DBWriteException , IOException { SVDBBaseIndexCacheData data = new SVDBBaseIndexCacheData ( "" ) ; SVDBBaseIndexCacheData data_n = new SVDBBaseIndexCacheData ( "" ) ; data . getDeclCacheMap ( ) . put ( "" , new ArrayList < SVDBDeclCacheItem > ( ) ) ; data . getDeclCacheMap ( ) . get ( "" ) . add ( new SVDBDeclCacheItem ( null , "" , "" , SVDBItemType . ClassDecl , false ) ) ; dump_load ( data , data_n ) ; assertEquals ( data . getBaseLocation ( ) , data_n . getBaseLocation ( ) ) ; assertEquals ( , data_n . getDeclCacheMap ( ) . size ( ) ) ; assertEquals ( "" , data_n . getDeclCacheMap ( ) . get ( "" ) . get ( ) . getName ( ) ) ; } } package net . sf . sveditor . core . tests . index . persistence ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . InputStream ; import java . io . PrintStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBCovergroup ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBFileSystemProvider ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexChangeListener ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . persistence . DBFormatException ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcDirectiveScanner ; import net . sf . sveditor . core . preproc . SVPreProcOutput ; import net . sf . sveditor . core . preproc . SVPreProcessor ; import net . sf . sveditor . core . tests . IndexTestUtils ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; public class ArgFilePersistence extends TestCase implements ISVDBIndexChangeListener { private File fTmpDir ; private int fIndexRebuilt ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testXbusTransferFileParse ( ) throws DBFormatException { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; File test_dir = new File ( fTmpDir , testname ) ; if ( test_dir . exists ( ) ) { test_dir . delete ( ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File xbus = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , xbus ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex target_index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; IndexTestUtils . assertNoErrWarn ( log , target_index ) ; String path = "" ; ISVDBFileSystemProvider fs = ( ( SVDBArgFileIndex ) target_index ) . getFileSystemProvider ( ) ; SVPreProcessor pp = ( ( SVDBArgFileIndex ) target_index ) . createPreProcScanner ( path ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; InputStream in = fs . openStream ( path ) ; log . debug ( "" ) ; SVDBFile file = target_index . parse ( new NullProgressMonitor ( ) , in , path , null ) . second ( ) ; log . debug ( "" ) ; SVPreProcOutput pp_out = pp . preprocess ( ) ; StringBuilder tmp = new StringBuilder ( ) ; int line = , ch ; tmp . append ( "" + line + "" ) ; while ( ( ch = pp_out . get_ch ( ) ) != - ) { tmp . append ( ( char ) ch ) ; bos . write ( ( char ) ch ) ; if ( ch == '' ) { line ++ ; tmp . append ( "" + line + "" ) ; } } log . debug ( tmp . toString ( ) ) ; in = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; log . debug ( "" ) ; file = target_index . parse ( new NullProgressMonitor ( ) , in , path , null ) . second ( ) ; log . debug ( "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; LogFactory . removeLogHandle ( log ) ; } public void testOvmWarningUnbalancedParen ( ) throws DBFormatException { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; File test_dir = new File ( fTmpDir , testname ) ; if ( test_dir . exists ( ) ) { test_dir . delete ( ) ; } test_dir . mkdirs ( ) ; log . debug ( "" + test_dir . getAbsolutePath ( ) ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; utils . copyBundleDirToFS ( "" , test_dir ) ; File test_proj = new File ( test_dir , "" ) ; assertTrue ( test_proj . isDirectory ( ) ) ; fProject = TestUtils . createProject ( test_proj . getName ( ) , test_proj ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex target_index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; String path = "" ; ISVDBFileSystemProvider fs = ( ( SVDBArgFileIndex ) target_index ) . getFileSystemProvider ( ) ; SVPreProcessor pp = ( ( SVDBArgFileIndex ) target_index ) . createPreProcScanner ( path ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; InputStream in = fs . openStream ( path ) ; log . debug ( "" ) ; SVDBFile file = target_index . parse ( new NullProgressMonitor ( ) , in , path , null ) . second ( ) ; log . debug ( "" ) ; SVPreProcOutput pp_out = pp . preprocess ( ) ; StringBuilder tmp = new StringBuilder ( ) ; int line = , ch ; tmp . append ( "" + line + "" ) ; while ( ( ch = pp_out . get_ch ( ) ) != - ) { tmp . append ( ( char ) ch ) ; bos . write ( ( char ) ch ) ; if ( ch == '' ) { line ++ ; tmp . append ( "" + line + "" ) ; } } log . debug ( tmp . toString ( ) ) ; in = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; log . debug ( "" ) ; file = target_index . parse ( new NullProgressMonitor ( ) , in , path , null ) . second ( ) ; log . debug ( "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; IndexTestUtils . assertNoErrWarn ( log , target_index ) ; LogFactory . removeLogHandle ( log ) ; } public void testWSArgFileTimestampChanged ( ) { ByteArrayOutputStream out ; PrintStream ps ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; fProject = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , fProject ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; IndexTestUtils . assertNoErrWarn ( log , index ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; rgy . save_state ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; log . debug ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } log . debug ( "" ) ; out = new ByteArrayOutputStream ( ) ; ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , fProject . getFile ( new Path ( "" ) ) ) ; out = new ByteArrayOutputStream ( ) ; ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , fProject . getFile ( new Path ( "" ) ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testWSArgFileTimestampUnchanged ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; fProject = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , fProject ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; fIndexRebuilt = ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; SVDBClassDecl target_it = null , target_orig = null ; List < ISVDBItemBase > orig_list = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = ( SVDBClassDecl ) tmp_it ; target_orig = ( SVDBClassDecl ) tmp_it . duplicate ( ) ; } orig_list . add ( tmp_it . duplicate ( ) ) ; if ( tmp_it . getType ( ) == SVDBItemType . Covergroup ) { SVDBCovergroup cg = ( SVDBCovergroup ) tmp_it ; SVDBCovergroup cg2 = ( SVDBCovergroup ) cg . duplicate ( ) ; assertEquals ( cg , cg2 ) ; } } for ( int i = ; i < orig_list . size ( ) ; i ++ ) { if ( ( orig_list . get ( i ) instanceof ISVDBScopeItem ) && orig_list . get ( i ) . getType ( ) != SVDBItemType . File ) { assertTrue ( "" + orig_list . get ( i ) . getType ( ) + "" + SVDBItem . getName ( orig_list . get ( i ) ) + "" + orig_list . get ( i ) . getType ( ) + "" + SVDBItem . getName ( orig_list . get ( i ) ) , orig_list . get ( i ) . equals ( orig_list . get ( i ) ) ) ; } } assertEquals ( "" , , fIndexRebuilt ) ; assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; rgy . save_state ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; log . debug ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } log . debug ( "" ) ; fIndexRebuilt = ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; index . addChangeListener ( this ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; target_it = null ; List < ISVDBItemBase > new_list = new ArrayList < ISVDBItemBase > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; new_list . add ( tmp_it ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = ( SVDBClassDecl ) tmp_it ; } } target_it . equals ( target_orig ) ; assertEquals ( "" , orig_list . size ( ) , new_list . size ( ) ) ; for ( int i = ; i < orig_list . size ( ) ; i ++ ) { if ( ! ( orig_list . get ( i ) instanceof ISVDBScopeItem ) ) { assertTrue ( "" + orig_list . get ( i ) . getType ( ) + "" + SVDBItem . getName ( orig_list . get ( i ) ) + "" + new_list . get ( i ) . getType ( ) + "" + SVDBItem . getName ( new_list . get ( i ) ) , orig_list . get ( i ) . equals ( new_list . get ( i ) ) ) ; } } for ( int i = ; i < orig_list . size ( ) ; i ++ ) { if ( ( orig_list . get ( i ) instanceof ISVDBScopeItem ) && orig_list . get ( i ) . getType ( ) != SVDBItemType . File && orig_list . get ( i ) . getType ( ) != SVDBItemType . ClassDecl ) { if ( orig_list . get ( i ) . getType ( ) == SVDBItemType . Function && SVDBItem . getName ( orig_list . get ( i ) ) . equals ( "" ) ) { SVDBTask f1 = ( SVDBTask ) orig_list . get ( i ) ; SVDBTask f2 = ( SVDBTask ) new_list . get ( i ) ; f1 . equals ( f2 ) ; } else { assertTrue ( "" + orig_list . get ( i ) . getType ( ) + "" + SVDBItem . getName ( orig_list . get ( i ) ) + "" + new_list . get ( i ) . getType ( ) + "" + SVDBItem . getName ( new_list . get ( i ) ) , orig_list . get ( i ) . equals ( new_list . get ( i ) ) ) ; } } } for ( int i = ; i < orig_list . size ( ) ; i ++ ) { if ( orig_list . get ( i ) . getType ( ) == SVDBItemType . File && SVDBItem . getName ( orig_list . get ( i ) ) . equals ( "" ) ) { SVDBFile c1 = ( SVDBFile ) orig_list . get ( i ) ; SVDBFile c2 = ( SVDBFile ) new_list . get ( i ) ; c1 . equals ( c2 ) ; } assertTrue ( "" + orig_list . get ( i ) . getType ( ) + "" + SVDBItem . getName ( orig_list . get ( i ) ) + "" + new_list . get ( i ) . getType ( ) + "" + SVDBItem . getName ( new_list . get ( i ) ) , orig_list . get ( i ) . equals ( new_list . get ( i ) ) ) ; } assertEquals ( "" , , fIndexRebuilt ) ; assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; } public void testFSArgFileTimestampChanged ( ) { ByteArrayOutputStream out ; PrintStream ps ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; File path = new File ( project_dir , "" ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase target_it = null ; ISVDBItemBase class1_2 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_2 = tmp_it ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; assertNull ( "" , class1_2 ) ; rgy . save_state ( ) ; log . debug ( "" ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } out = new ByteArrayOutputStream ( ) ; ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; log . debug ( "" ) ; TestUtils . copy ( out , new File ( project_dir , "" ) ) ; out = new ByteArrayOutputStream ( ) ; ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , new File ( project_dir , "" ) ) ; index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , path . getAbsolutePath ( ) , SVDBArgFileIndexFactory . TYPE , null ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; target_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { target_it = tmp_it ; break ; } } assertNotNull ( "" , target_it ) ; assertEquals ( "" , SVDBItem . getName ( target_it ) ) ; LogFactory . removeLogHandle ( log ) ; } public void index_changed ( int reason , SVDBFile file ) { } public void index_rebuilt ( ) { fIndexRebuilt ++ ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . io . IOException ; import java . io . PrintStream ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . SVDBFSFileSystemProvider ; import net . sf . sveditor . core . db . index . SVDBThreadedArgFileIndex ; import net . sf . sveditor . core . db . index . SVDBThreadedSourceCollectionIndex ; import net . sf . sveditor . core . db . index . SVDBWSFileSystemProvider ; import net . sf . sveditor . core . db . index . cache . InMemoryIndexCache ; import net . sf . sveditor . core . fileset . AbstractSVFileMatcher ; import net . sf . sveditor . core . fileset . SVFileSet ; import net . sf . sveditor . core . fileset . SVWorkspaceFileMatcher ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import junit . framework . TestCase ; public class TestThreadedSourceCollectionIndex extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testParseUVM ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVDBWSFileSystemProvider fs_provider = new SVDBWSFileSystemProvider ( ) ; File project = new File ( fTmpDir , "" ) ; project . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , project ) ; fProject = TestUtils . createProject ( "" , project ) ; String base = "" ; List < AbstractSVFileMatcher > matcher_list = new ArrayList < AbstractSVFileMatcher > ( ) ; SVWorkspaceFileMatcher matcher = new SVWorkspaceFileMatcher ( ) ; SVFileSet fs = new SVFileSet ( base ) ; fs . addInclude ( "" ) ; fs . addInclude ( "" ) ; matcher_list . add ( matcher ) ; matcher . addFileSet ( fs ) ; SVDBThreadedSourceCollectionIndex index = new SVDBThreadedSourceCollectionIndex ( "" , "" , matcher_list , fs_provider , new InMemoryIndexCache ( ) , null ) ; index . init ( new NullProgressMonitor ( ) ) ; long start = System . currentTimeMillis ( ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; long end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( end - start ) ) ; } public void testParseUVMArgFile ( ) throws IOException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVDBWSFileSystemProvider fs_provider = new SVDBWSFileSystemProvider ( ) ; File project = new File ( fTmpDir , "" ) ; project . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , project ) ; fProject = TestUtils . createProject ( "" , project ) ; PrintStream ps = new PrintStream ( new File ( project , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; SVDBThreadedArgFileIndex index = new SVDBThreadedArgFileIndex ( "" , "" , fs_provider , new InMemoryIndexCache ( ) , null ) ; index . init ( new NullProgressMonitor ( ) ) ; long start = System . currentTimeMillis ( ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; long end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( end - start ) ) ; } public void testParseOpenSparcArgFile ( ) throws IOException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVDBFSFileSystemProvider fs_provider = new SVDBFSFileSystemProvider ( ) ; TestIndexCacheFactory cf = new TestIndexCacheFactory ( fTmpDir ) ; SVDBThreadedArgFileIndex index = new SVDBThreadedArgFileIndex ( "" , "" , fs_provider , cf . createIndexCache ( "" , "" ) , null ) ; index . init ( new NullProgressMonitor ( ) ) ; long start = System . currentTimeMillis ( ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; index . dispose ( ) ; long end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( end - start ) ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestOvmBasics extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testBasicProcessing ( ) { File tmpdir = new File ( fTmpDir , "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; if ( tmpdir . exists ( ) ) { tmpdir . delete ( ) ; } tmpdir . mkdirs ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( tmpdir ) ) ; SVDBIndexCollection index_mgr = new SVDBIndexCollection ( "" ) ; index_mgr . addPluginLibrary ( rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBPluginLibIndexFactory . TYPE , null ) ) ; ISVDBItemIterator index_it = index_mgr . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; ISVDBItemBase ovm_component = null , ovm_sequence = null ; SVDBFile current_file = null ; while ( index_it . hasNext ( ) ) { ISVDBItemBase it = index_it . nextItem ( ) ; String name = SVDBItem . getName ( it ) ; log . debug ( "" + it . getType ( ) + "" + name ) ; if ( it . getType ( ) == SVDBItemType . File ) { current_file = ( SVDBFile ) it ; } else if ( it . getType ( ) == SVDBItemType . Marker ) { markers . add ( ( SVDBMarker ) it ) ; } else if ( it . getType ( ) == SVDBItemType . ClassDecl ) { if ( name . equals ( "" ) ) { ovm_component = it ; } else if ( name . equals ( "" ) ) { ovm_sequence = it ; } } else if ( it . getType ( ) == SVDBItemType . MacroDef ) { } else if ( SVDBStmt . isType ( it , SVDBItemType . VarDeclStmt ) ) { SVDBVarDeclStmt v = ( SVDBVarDeclStmt ) it ; if ( v . getParent ( ) == null ) { log . debug ( "" + current_file . getFilePath ( ) ) ; log . debug ( "" + v . getLocation ( ) . getLine ( ) ) ; } SVDBVarDeclItem vi = ( SVDBVarDeclItem ) v . getChildren ( ) . iterator ( ) . next ( ) ; assertNotNull ( "" + vi . getName ( ) + "" , v . getParent ( ) ) ; assertNotNull ( "" + SVDBItem . getName ( v . getParent ( ) ) + "" + name + "" , v . getTypeInfo ( ) ) ; } } for ( SVDBMarker m : markers ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , markers . size ( ) ) ; assertNotNull ( "" , ovm_sequence ) ; assertNotNull ( "" , ovm_component ) ; index_mgr . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testXbusExample ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { test_dir . delete ( ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File xbus = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , xbus ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) tmp_it ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } } for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; index . dispose ( ) ; TestUtils . deleteProject ( fProject ) ; LogFactory . removeLogHandle ( log ) ; } public void testTrivialExample ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { test_dir . delete ( ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File trivial = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , trivial ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) tmp_it ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } } for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } public void testSequenceBasicReadWriteExample ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { test_dir . delete ( ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File basic_read_write_sequence = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , basic_read_write_sequence ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; SVDBClassDecl my_driver = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) tmp_it ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } else if ( tmp_it . getType ( ) == SVDBItemType . ClassDecl && SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { my_driver = ( SVDBClassDecl ) tmp_it ; } } for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; assertNotNull ( my_driver ) ; LogFactory . removeLogHandle ( log ) ; } public void testSequenceSimpleExample ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; File test_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { test_dir . delete ( ) ; } test_dir . mkdirs ( ) ; utils . unpackBundleZipToFS ( "" , test_dir ) ; File simple = new File ( test_dir , "" ) ; fProject = TestUtils . createProject ( "" , simple ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; SVDBClassDecl simple_driver = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( tmp_it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) tmp_it ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } else if ( tmp_it . getType ( ) == SVDBItemType . ClassDecl && SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { simple_driver = ( SVDBClassDecl ) tmp_it ; } } for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( "" , , errors . size ( ) ) ; assertNotNull ( simple_driver ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index . libIndex ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . PrintStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; public class WSArgFileIndexChanges extends TestCase { @ Override protected void tearDown ( ) throws Exception { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; } public void testArgFileChange ( ) { File tmpdir = TestUtils . createTempDir ( ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; try { int_testArgFileChange ( tmpdir ) ; } catch ( RuntimeException e ) { throw e ; } finally { TestUtils . delete ( tmpdir ) ; } } private void int_testArgFileChange ( File tmpdir ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; final IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( tmpdir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( tmpdir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBArgFileIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1_it = null , class1_2_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_it = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_2_it = tmp_it ; } } assertNotNull ( "" , class1_it ) ; assertNull ( "" , class1_2_it ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; PrintStream ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , project_dir . getFile ( new Path ( "" ) ) ) ; out = new ByteArrayOutputStream ( ) ; ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , project_dir . getFile ( new Path ( "" ) ) ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; class1_it = null ; class1_2_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_it = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_2_it = tmp_it ; } } assertNotNull ( "" , class1_it ) ; assertNotNull ( "" , class1_2_it ) ; index . dispose ( ) ; } } package net . sf . sveditor . core . tests . index . libIndex ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . PrintStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; public class WSLibIndexFileChanges extends TestCase { @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; } @ Override protected void tearDown ( ) throws Exception { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; } public void testMissingIncludeAdded ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; File tmpdir = TestUtils . createTempDir ( ) ; try { int_testMissingIncludeAdded ( "" , tmpdir ) ; } catch ( RuntimeException e ) { throw e ; } finally { TestUtils . delete ( tmpdir ) ; } } private void int_testMissingIncludeAdded ( String testname , File tmpdir ) throws RuntimeException { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; IProject project_dir = TestUtils . createProject ( "" ) ; utils . copyBundleDirToWS ( "" , project_dir ) ; File db = new File ( tmpdir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( tmpdir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class1_it = null , class1_2_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_it = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_2_it = tmp_it ; } } assertNotNull ( "" , class1_it ) ; assertNull ( "" , class1_2_it ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; PrintStream ps = new PrintStream ( out ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; TestUtils . copy ( out , project_dir . getFile ( new Path ( "" ) ) ) ; log . debug ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } log . debug ( "" ) ; it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; class1_it = null ; class1_2_it = null ; while ( it . hasNext ( ) ) { ISVDBItemBase tmp_it = it . nextItem ( ) ; log . debug ( "" + SVDBItem . getName ( tmp_it ) ) ; if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_it = tmp_it ; } else if ( SVDBItem . getName ( tmp_it ) . equals ( "" ) ) { class1_2_it = tmp_it ; } } assertNotNull ( "" , class1_it ) ; assertNotNull ( "" , class1_2_it ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . index ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBPath ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . IndexTestUtils ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestOpencoresProjects extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testEthernetMac ( ) throws CoreException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , "" , new String [ ] { "" , "" } ) ; } public void testI2C ( ) throws CoreException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , "" , new String [ ] { "" , "" } ) ; } public void testDMA ( ) throws CoreException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , "" , new String [ ] { "" , "" } ) ; } public void testUSBHostSlave ( ) throws CoreException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , "" , new String [ ] { "" } ) ; } private void runTest ( String testname , String zipfile_path , String proj_path , String arg_file_paths [ ] ) throws CoreException { LogHandle log = LogFactory . getLogHandle ( testname ) ; CoreReleaseTests . clearErrors ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; cleanupWorkspace ( ) ; File test_dir = new File ( fTmpDir , testname ) ; File db_dir = new File ( fTmpDir , "" ) ; if ( test_dir . exists ( ) ) { assertTrue ( test_dir . delete ( ) ) ; } assertTrue ( test_dir . mkdirs ( ) ) ; if ( db_dir . exists ( ) ) { assertTrue ( db_dir . delete ( ) ) ; } assertTrue ( db_dir . mkdirs ( ) ) ; utils . unpackBundleZipToFS ( zipfile_path , test_dir ) ; File project_path = new File ( test_dir , proj_path ) ; fProject = TestUtils . createProject ( project_path . getName ( ) , project_path ) ; SVDBProjectManager p_mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData p_data = p_mgr . getProjectData ( fProject ) ; SVProjectFileWrapper p_wrapper = p_data . getProjectFileWrapper ( ) . duplicate ( ) ; if ( arg_file_paths != null ) { for ( String arg_file : arg_file_paths ) { p_wrapper . getArgFilePaths ( ) . add ( new SVDBPath ( arg_file ) ) ; p_wrapper . getArgFilePaths ( ) . add ( new SVDBPath ( arg_file ) ) ; } } p_data . setProjectFileWrapper ( p_wrapper ) ; SVDBIndexCollection project_index = p_data . getProjectIndexMgr ( ) ; assertNoErrors ( log , project_index ) ; ISVDBItemIterator it = project_index . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( it . hasNext ( ) ) { it . nextItem ( ) ; } IndexTestUtils . assertNoErrWarn ( log , project_index ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; project_index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } private void assertNoErrors ( LogHandle log , ISVDBIndexIterator index_it ) { ISVDBItemIterator it_i = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; while ( it_i . hasNext ( ) ) { ISVDBItemBase it = it_i . nextItem ( ) ; if ( it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker marker = ( SVDBMarker ) it ; if ( marker . getMarkerType ( ) == MarkerType . Error ) { errors . add ( marker ) ; } } } for ( SVDBMarker m : errors ) { log . debug ( "" + m . getMessage ( ) + "" + "" + m . getLocation ( ) . getLine ( ) ) ; } assertEquals ( , errors . size ( ) ) ; } private void cleanupWorkspace ( ) throws CoreException { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( IProject p : root . getProjects ( ) ) { p . delete ( true , new NullProgressMonitor ( ) ) ; } } } package net . sf . sveditor . core . tests . preproc ; import junit . framework . Test ; import junit . framework . TestCase ; import junit . framework . TestSuite ; public class PreProcTests extends TestCase { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( TestPreProc . class ) ) ; return suite ; } } package net . sf . sveditor . core . tests . preproc ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestConditionalEval extends TestCase { public void testIfTakenNoElse ( ) throws SVParseException { String testname = "" ; String content = "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testIfTakenElse ( ) throws SVParseException { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testIfNotTakenElseTaken ( ) throws SVParseException { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testIfTakenElsifNoElse ( ) throws SVParseException { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } , new String [ ] { "" } ) ; } public void testIfTakenElsifElse ( ) throws SVParseException { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } , new String [ ] { "" , "" } ) ; } public void testIfNotTakenElsifTakenElse ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testIfNotTakenElsifNotTakenElseTaken ( ) throws SVParseException { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testIfNotTakenElsifTakenPostDefine ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" , "" } ) ; } private void runTest ( String testname , String data , String exp_items [ ] ) throws SVParseException { runTest ( testname , data , exp_items , null ) ; } private void runTest ( String testname , String data , String exp_items [ ] , String unexp_items [ ] ) throws SVParseException { LogHandle log = LogFactory . getLogHandle ( testname ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; StringInputStream in = new StringInputStream ( data ) ; SVDBFile file = SVDBTestUtils . parse ( log , in , data , markers ) . second ( ) ; assertEquals ( , markers . size ( ) ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; if ( unexp_items != null ) { SVDBTestUtils . assertFileDoesNotHaveElements ( file , unexp_items ) ; } LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . preproc ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . PrintStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBPreProcObserver ; import net . sf . sveditor . core . db . index . SVDBArgFileIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcDirectiveScanner ; import net . sf . sveditor . core . preproc . SVPreProcOutput ; import net . sf . sveditor . core . preproc . SVPreProcessor ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestPreProc extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testUnbalancedConditionals_GreaterEndifs ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; InputStream in = new StringInputStream ( content ) ; SVPreProcDirectiveScanner pp_scanner = new SVPreProcDirectiveScanner ( ) ; pp_scanner . init ( in , "" ) ; SVDBPreProcObserver observer = new SVDBPreProcObserver ( ) ; pp_scanner . setObserver ( observer ) ; pp_scanner . process ( ) ; } public void testCommaContainingStringMacroParam ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String result = SVDBTestUtils . preprocess ( doc , "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testMacroArgExpansion ( ) { String doc = "" + "" ; String expected = "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String result = SVDBTestUtils . preprocess ( doc , "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testMacroArgMacroExpansion ( ) { String doc = "" + "" + "" + "" ; String expected = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String result = SVDBTestUtils . preprocess ( doc , "" ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testMacroArgDefaultValue ( ) { CoreReleaseTests . clearErrors ( ) ; String doc = "" + "" + "" ; String expected = "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String result = SVDBTestUtils . preprocess ( doc , "" ) ; assertEquals ( "" , , CoreReleaseTests . getErrors ( ) . size ( ) ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testMacroArgDefaultValue_2 ( ) { String testname = "" ; CoreReleaseTests . clearErrors ( ) ; String doc = "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String result = SVDBTestUtils . preprocess ( doc , testname ) ; assertEquals ( "" , , CoreReleaseTests . getErrors ( ) . size ( ) ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testFileLine ( ) { CoreReleaseTests . clearErrors ( ) ; String doc = "" + "" ; String expected = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String result = SVDBTestUtils . preprocess ( doc , "" ) ; assertEquals ( "" , , CoreReleaseTests . getErrors ( ) . size ( ) ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testUndefExcluded ( ) { CoreReleaseTests . clearErrors ( ) ; String doc = "" + "" + "" + "" + "" ; String expected = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String result = SVDBTestUtils . preprocess ( doc , "" ) ; assertEquals ( "" , , CoreReleaseTests . getErrors ( ) . size ( ) ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void disabled_testPreProcVMM ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File project_dir = new File ( fTmpDir , "" ) ; if ( project_dir . exists ( ) ) { project_dir . delete ( ) ; } utils . copyBundleDirToFS ( "" , project_dir ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( project_dir ) ) ; rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBPluginLibIndexFactory . TYPE , null ) ; } public void disabled_testNestedMacro ( ) { File tmpdir = new File ( fTmpDir , "" ) ; if ( tmpdir . exists ( ) ) { tmpdir . delete ( ) ; } tmpdir . mkdirs ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( tmpdir ) ) ; rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBPluginLibIndexFactory . TYPE , null ) ; } public void testVmmErrorMacro ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String result = SVDBTestUtils . preprocess ( doc , "" ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testOvmSequenceUtilsExpansion ( ) throws IOException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } assertTrue ( fTmpDir . mkdirs ( ) ) ; File db = new File ( fTmpDir , "" ) ; utils . unpackBundleZipToFS ( "" , fTmpDir ) ; utils . copyBundleFileToFS ( "" , fTmpDir ) ; PrintStream ps = new PrintStream ( new File ( fTmpDir , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; ps . close ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVDBArgFileIndex index = ( SVDBArgFileIndex ) rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , new File ( fTmpDir , "" ) . getAbsolutePath ( ) , SVDBArgFileIndexFactory . TYPE , null ) ; File target = new File ( fTmpDir , "" ) ; SVPreProcessor pp = index . createPreProcScanner ( target . getAbsolutePath ( ) ) ; assertNotNull ( pp ) ; StringBuilder sb = new StringBuilder ( ) ; int ch ; SVPreProcOutput pp_out = pp . preprocess ( ) ; while ( ( ch = pp_out . get_ch ( ) ) != - ) { sb . append ( ( char ) ch ) ; } log . debug ( sb . toString ( ) ) ; assertTrue ( ( sb . indexOf ( "" ) == - ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testUvmTlm2DoRecordMacroExpansion ( ) throws IOException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } assertTrue ( fTmpDir . mkdirs ( ) ) ; File db = new File ( fTmpDir , "" ) ; utils . unpackBundleZipToFS ( "" , fTmpDir ) ; utils . copyBundleFileToFS ( "" , fTmpDir ) ; PrintStream ps = new PrintStream ( new File ( fTmpDir , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; ps . close ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVDBArgFileIndex index = ( SVDBArgFileIndex ) rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , new File ( fTmpDir , "" ) . getAbsolutePath ( ) , SVDBArgFileIndexFactory . TYPE , null ) ; File target = new File ( fTmpDir , "" ) ; SVPreProcessor pp = index . createPreProcScanner ( target . getAbsolutePath ( ) ) ; assertNotNull ( pp ) ; StringBuilder sb = new StringBuilder ( ) ; int ch ; SVPreProcOutput pp_out = pp . preprocess ( ) ; while ( ( ch = pp_out . get_ch ( ) ) != - ) { sb . append ( ( char ) ch ) ; } log . debug ( sb . toString ( ) ) ; assertTrue ( ( sb . indexOf ( "" ) == - ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testSingleLineCommentMacro ( ) { String doc = "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String result = SVDBTestUtils . preprocess ( doc , "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testSpaceSeparatedMacroRef ( ) { String testname = "" ; String doc = "" + "" + "" + "" + "" ; String expected = "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String result = SVDBTestUtils . preprocess ( doc , testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testIncompleteMacroRef ( ) { String testname = "" ; String doc = "" + "" + "" + "" ; String expected = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String result = SVDBTestUtils . preprocess ( doc , testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testMangledMacroRef ( ) { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" ; String expected = "" + "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String result = SVDBTestUtils . preprocess ( doc , testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testRecursiveMacroRef ( ) { String testname = "" ; String doc = "" + "" + "" + "" + "" ; String expected = "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String result = SVDBTestUtils . preprocess ( doc , testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; log . debug ( "" + result . trim ( ) ) ; log . debug ( "" ) ; log . debug ( "" + expected . trim ( ) ) ; log . debug ( "" ) ; assertEquals ( expected . trim ( ) , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testUVMFieldArrayIntExpansion ( ) throws IOException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } assertTrue ( fTmpDir . mkdirs ( ) ) ; File db = new File ( fTmpDir , "" ) ; utils . unpackBundleZipToFS ( "" , fTmpDir ) ; PrintStream ps ; ps = new PrintStream ( new File ( fTmpDir , "" ) ) ; ps . println ( "" ) ; ps . println ( ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . close ( ) ; ps = new PrintStream ( new File ( fTmpDir , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . flush ( ) ; ps . close ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; SVDBArgFileIndex index = ( SVDBArgFileIndex ) rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , new File ( fTmpDir , "" ) . getAbsolutePath ( ) , SVDBArgFileIndexFactory . TYPE , null ) ; File target = new File ( fTmpDir , "" ) ; SVPreProcessor pp = index . createPreProcScanner ( target . getAbsolutePath ( ) ) ; assertNotNull ( pp ) ; StringBuilder sb = new StringBuilder ( ) ; int ch ; SVPreProcOutput pp_out = pp . preprocess ( ) ; while ( ( ch = pp_out . get_ch ( ) ) != - ) { sb . append ( ( char ) ch ) ; } int lineno = ; StringBuilder line = new StringBuilder ( ) ; for ( int i = ; i < sb . length ( ) ; i ++ ) { while ( i < sb . length ( ) && sb . charAt ( i ) != '' ) { if ( sb . charAt ( i ) != '' ) { line . append ( sb . charAt ( i ) ) ; } i ++ ; } if ( sb . charAt ( i ) == '' ) { i ++ ; } log . debug ( lineno + "" + line . toString ( ) ) ; line . setLength ( ) ; lineno ++ ; } List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = SVDBTestUtils . parse ( log , sb . toString ( ) , "" , markers ) ; assertEquals ( "" , , markers . size ( ) ) ; index . dispose ( ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOError ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBBind ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMacroDef ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . SVDBPreProcObserver ; import net . sf . sveditor . core . db . index . InputStreamCopier ; import net . sf . sveditor . core . db . stmt . SVDBImportItem ; import net . sf . sveditor . core . db . stmt . SVDBImportStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcDirectiveScanner ; import net . sf . sveditor . core . preproc . SVPreProcOutput ; import net . sf . sveditor . core . preproc . SVPreProcessor ; import net . sf . sveditor . core . scanner . IPreProcMacroProvider ; import net . sf . sveditor . core . scanner . SVPreProcDefineProvider ; import net . sf . sveditor . core . tests . utils . TestUtils ; public class SVDBTestUtils { public static void assertNoErrWarn ( SVDBFile file ) { for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . Marker ) { SVDBMarker m = ( SVDBMarker ) it ; if ( m . getMarkerType ( ) == MarkerType . Error || m . getMarkerType ( ) == MarkerType . Warning ) { System . out . println ( "" + m . getMessage ( ) + "" + file . getName ( ) + "" + m . getLocation ( ) . getLine ( ) ) ; TestCase . fail ( "" + m . getMarkerType ( ) + "" + file . getName ( ) + "" + m . getLocation ( ) . getLine ( ) ) ; } } } } public static void assertFileHasElements ( SVDBFile file , String ... elems ) { for ( String e : elems ) { if ( findElement ( file , e ) == null ) { TestCase . fail ( "" + e + "" + file . getName ( ) ) ; } } } public static void assertFileDoesNotHaveElements ( SVDBFile file , String ... elems ) { for ( String e : elems ) { if ( findElement ( file , e ) != null ) { TestCase . fail ( "" + e + "" + file . getName ( ) ) ; } } } public static ISVDBItemBase findInFile ( SVDBFile file , String name ) { return findElement ( file , name ) ; } private static ISVDBItemBase findElement ( ISVDBScopeItem scope , String e ) { for ( ISVDBItemBase it : scope . getItems ( ) ) { ISVDBItemBase ret = findElement ( it , e ) ; if ( ret != null ) { return ret ; } } return null ; } private static ISVDBItemBase findElement ( ISVDBItemBase it , String e ) { if ( SVDBItem . getName ( it ) . equals ( e ) ) { return it ; } else if ( it instanceof SVDBVarDeclStmt ) { for ( ISVDBChildItem c : ( ( SVDBVarDeclStmt ) it ) . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; if ( vi . getName ( ) . equals ( e ) ) { return vi ; } } } else if ( it instanceof SVDBModIfcInst ) { for ( ISVDBChildItem c : ( ( SVDBModIfcInst ) it ) . getChildren ( ) ) { SVDBModIfcInstItem mi = ( SVDBModIfcInstItem ) c ; if ( mi . getName ( ) . equals ( e ) ) { return mi ; } } } else if ( it . getType ( ) == SVDBItemType . ImportStmt ) { for ( ISVDBChildItem c : ( ( SVDBImportStmt ) it ) . getChildren ( ) ) { SVDBImportItem ii = ( SVDBImportItem ) c ; if ( ii . getImport ( ) . equals ( e ) ) { return ii ; } } } else if ( it instanceof ISVDBScopeItem ) { ISVDBItemBase t ; if ( ( t = findElement ( ( ISVDBScopeItem ) it , e ) ) != null ) { return t ; } } else { switch ( it . getType ( ) ) { case Bind : { SVDBModIfcInst inst = ( ( SVDBBind ) it ) . getBindInst ( ) ; if ( inst != null ) { return findElement ( inst , e ) ; } } break ; } } return null ; } public static SVDBFile parse ( String content , String filename ) { return parse ( content , filename , false ) ; } public static Tuple < SVDBFile , SVDBFile > parsePreProc ( String content , String filename , boolean exp_err ) { List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; Tuple < SVDBFile , SVDBFile > file = parse ( null , new StringInputStream ( content ) , filename , markers ) ; if ( ! exp_err ) { TestCase . assertEquals ( "" , , markers . size ( ) ) ; } return file ; } public static SVDBFile parse ( String content , String filename , boolean exp_err ) { List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = parse ( null , content , filename , markers ) ; if ( ! exp_err ) { TestCase . assertEquals ( "" , , markers . size ( ) ) ; } return file ; } public static Tuple < SVDBFile , SVDBFile > parse ( LogHandle log , File file , List < SVDBMarker > markers ) { InputStream in = null ; try { in = new FileInputStream ( file ) ; } catch ( IOException e ) { TestCase . fail ( "" + file . getAbsolutePath ( ) + "" + e . getMessage ( ) ) ; } Tuple < SVDBFile , SVDBFile > ret = parse ( log , in , file . getName ( ) , markers ) ; return ret ; } public static SVDBFile parse ( LogHandle log , String content , String filename , boolean exp_err ) { List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = parse ( log , content , filename , markers ) ; if ( ! exp_err ) { TestCase . assertEquals ( "" , , markers . size ( ) ) ; } return file ; } public static SVDBFile parse ( LogHandle log , String content , String filename , List < SVDBMarker > markers ) { return parse ( log , new StringInputStream ( content ) , filename , markers ) . second ( ) ; } public static Tuple < SVDBFile , SVDBFile > parse ( LogHandle log , InputStream content_i , String filename , List < SVDBMarker > markers ) { SVDBFile file = null ; InputStreamCopier copier = new InputStreamCopier ( content_i ) ; InputStream content = copier . copy ( ) ; SVPreProcDirectiveScanner pp_dir_scanner = new SVPreProcDirectiveScanner ( ) ; pp_dir_scanner . init ( content , filename ) ; SVDBPreProcObserver pp_observer = new SVDBPreProcObserver ( ) ; pp_dir_scanner . setObserver ( pp_observer ) ; pp_dir_scanner . process ( ) ; final SVDBFile pp_file = pp_observer . getFiles ( ) . get ( ) ; IPreProcMacroProvider macro_provider = new IPreProcMacroProvider ( ) { public void setMacro ( String key , String value ) { } public void addMacro ( SVDBMacroDef macro ) { } public SVDBMacroDef findMacro ( String name , int lineno ) { for ( ISVDBItemBase it : pp_file . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . MacroDef && SVDBItem . getName ( it ) . equals ( name ) ) { return ( SVDBMacroDef ) it ; } } return null ; } } ; SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( macro_provider ) ; if ( log != null ) { InputStream in = copier . copy ( ) ; SVPreProcessor preproc = new SVPreProcessor ( in , filename , dp ) ; log . debug ( "" ) ; log . debug ( preproc . preprocess ( ) . toString ( ) ) ; } ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( dp ) ; content = copier . copy ( ) ; file = factory . parse ( content , filename , markers ) ; for ( SVDBMarker m : markers ) { if ( log != null ) { log . debug ( "" + m . getMessage ( ) ) ; } } return new Tuple < SVDBFile , SVDBFile > ( pp_file , file ) ; } public static String preprocess ( String content , final String filename ) { SVPreProcDirectiveScanner pp_scanner = new SVPreProcDirectiveScanner ( ) ; pp_scanner . init ( new StringInputStream ( content ) , filename ) ; SVDBPreProcObserver pp_observer = new SVDBPreProcObserver ( ) ; pp_scanner . setObserver ( pp_observer ) ; pp_scanner . process ( ) ; final SVDBFile pp_file = pp_observer . getFiles ( ) . get ( ) ; IPreProcMacroProvider macro_provider = new IPreProcMacroProvider ( ) { public void setMacro ( String key , String value ) { } public void addMacro ( SVDBMacroDef macro ) { } public SVDBMacroDef findMacro ( String name , int lineno ) { if ( name . equals ( "" ) ) { return new SVDBMacroDef ( "" , "" + filename + "" ) ; } else if ( name . equals ( "" ) ) { return new SVDBMacroDef ( "" , "" ) ; } else { for ( ISVDBItemBase it : pp_file . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . MacroDef && SVDBItem . getName ( it ) . equals ( name ) ) { return ( SVDBMacroDef ) it ; } } } return null ; } } ; SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( macro_provider ) ; SVPreProcessor pp = new SVPreProcessor ( new StringInputStream ( content ) , filename , dp ) ; SVPreProcOutput out = pp . preprocess ( ) ; return out . toString ( ) ; } } package net . sf . sveditor . core . tests ; import java . util . ArrayList ; import java . util . List ; import junit . framework . Test ; import junit . framework . TestResult ; import junit . framework . TestSuite ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . tests . content_assist . ContentAssistTests ; import net . sf . sveditor . core . tests . docs . DocsTests ; import net . sf . sveditor . core . tests . fileset . FileSetTests ; import net . sf . sveditor . core . tests . hierarchy . HierarchyTests ; import net . sf . sveditor . core . tests . indent . IndentTests ; import net . sf . sveditor . core . tests . index . IndexTests ; import net . sf . sveditor . core . tests . index . cache . IndexCacheTests ; import net . sf . sveditor . core . tests . index . persistence . PersistenceTests ; import net . sf . sveditor . core . tests . job_mgr . JobMgrTests ; import net . sf . sveditor . core . tests . open_decl . OpenDeclTests ; import net . sf . sveditor . core . tests . parser . ParserTests ; import net . sf . sveditor . core . tests . preproc . PreProcTests ; import net . sf . sveditor . core . tests . project_settings . ProjectSettingsTests ; import net . sf . sveditor . core . tests . scanner . PreProcMacroTests ; import net . sf . sveditor . core . tests . srcgen . SrcGenTests ; import net . sf . sveditor . core . tests . templates . TemplateTests ; public class CoreReleaseTests extends TestSuite { private static List < Exception > fErrors = new ArrayList < Exception > ( ) ; private static ILogListener fErrorLogListener ; static { fErrorLogListener = new ILogListener ( ) { public void message ( ILogHandle handle , int type , int level , String message ) { if ( type == ILogListener . Type_Error ) { System . out . println ( "" + message ) ; try { throw new Exception ( "" + handle . getName ( ) + "" + message ) ; } catch ( Exception e ) { fErrors . add ( e ) ; } } } } ; LogFactory . getDefault ( ) . addLogListener ( fErrorLogListener ) ; } public CoreReleaseTests ( ) { addTest ( new TestSuite ( SVScannerTests . class ) ) ; addTest ( ParserTests . suite ( ) ) ; addTest ( new TestSuite ( PreProcMacroTests . class ) ) ; addTest ( PreProcTests . suite ( ) ) ; addTest ( IndentTests . suite ( ) ) ; addTest ( JobMgrTests . suite ( ) ) ; addTest ( ContentAssistTests . suite ( ) ) ; addTest ( PersistenceTests . suite ( ) ) ; addTest ( ProjectSettingsTests . suite ( ) ) ; addTest ( IndexTests . suite ( ) ) ; addTest ( IndexCacheTests . suite ( ) ) ; addTest ( SrcGenTests . suite ( ) ) ; addTest ( OpenDeclTests . suite ( ) ) ; addTest ( new TestSuite ( FileSetTests . class ) ) ; addTest ( TemplateTests . suite ( ) ) ; addTest ( HierarchyTests . suite ( ) ) ; addTest ( DocsTests . suite ( ) ) ; } public static List < Exception > getErrors ( ) { return fErrors ; } public static void clearErrors ( ) { fErrors . clear ( ) ; } @ Override public void run ( TestResult result ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; super . run ( result ) ; } @ Override public void runTest ( Test test , TestResult result ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; super . runTest ( test , result ) ; } public static Test suite ( ) { return new CoreReleaseTests ( ) ; } } package net . sf . sveditor . core . tests ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import net . sf . sveditor . core . db . index . ISVDBFileSystemChangeListener ; import net . sf . sveditor . core . db . index . ISVDBFileSystemProvider ; public class SaveMarkersFileSystemProvider implements ISVDBFileSystemProvider { private ISVDBFileSystemProvider fFSProvider ; private Map < String , List < String > > fMarkersMap ; public SaveMarkersFileSystemProvider ( ISVDBFileSystemProvider fs_provider ) { fFSProvider = fs_provider ; fMarkersMap = new HashMap < String , List < String > > ( ) ; } public List < String > getMarkers ( ) { List < String > ret = new ArrayList < String > ( ) ; for ( Entry < String , List < String > > e : fMarkersMap . entrySet ( ) ) { ret . addAll ( e . getValue ( ) ) ; } return ret ; } public void addFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { fFSProvider . addFileSystemChangeListener ( l ) ; } public synchronized void addMarker ( String path , String type , int lineno , String msg ) { if ( ! fMarkersMap . containsKey ( path ) ) { fMarkersMap . put ( path , new ArrayList < String > ( ) ) ; } fMarkersMap . get ( path ) . add ( msg ) ; fFSProvider . addMarker ( path , type , lineno , msg ) ; } public void clearMarkers ( String path ) { fFSProvider . clearMarkers ( path ) ; if ( fMarkersMap . containsKey ( path ) ) { fMarkersMap . get ( path ) . clear ( ) ; } } public void closeStream ( InputStream in ) { fFSProvider . closeStream ( in ) ; } public void dispose ( ) { fFSProvider . dispose ( ) ; } public boolean fileExists ( String path ) { return fFSProvider . fileExists ( path ) ; } public boolean isDir ( String path ) { return fFSProvider . isDir ( path ) ; } public List < String > getFiles ( String path ) { return fFSProvider . getFiles ( path ) ; } public long getLastModifiedTime ( String path ) { return fFSProvider . getLastModifiedTime ( path ) ; } public void init ( String root ) { fFSProvider . init ( root ) ; } public InputStream openStream ( String path ) { return fFSProvider . openStream ( path ) ; } public void removeFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { fFSProvider . removeFileSystemChangeListener ( l ) ; } public String resolvePath ( String path , String fmt ) { return fFSProvider . resolvePath ( path , fmt ) ; } } package net . sf . sveditor . core . tests . srcgen ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . srcgen . NewClassGenerator ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . indent . IndentComparator ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestNewClassGen extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) . save_state ( ) ; if ( fTmpDir != null ) { TestUtils . delete ( fTmpDir ) ; fTmpDir = null ; } } public void testNewClassBasics ( ) { String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; NewClassGenerator gen = new NewClassGenerator ( ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; try { IProject project_dir = TestUtils . createProject ( "" ) ; IFile file = project_dir . getFile ( "" ) ; assertEquals ( "" , false , file . exists ( ) ) ; File tmpdir = new File ( fTmpDir , "" ) ; if ( tmpdir . exists ( ) ) { TestUtils . delete ( tmpdir ) ; } tmpdir . mkdirs ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( tmpdir ) ) ; SVDBIndexCollection index_mgr = new SVDBIndexCollection ( "" ) ; index_mgr . addPluginLibrary ( rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , SVCorePlugin . SV_BUILTIN_LIBRARY , SVDBPluginLibIndexFactory . TYPE , null ) ) ; gen . generate ( index_mgr , file , "" , null , true , new NullProgressMonitor ( ) ) ; try { InputStream in = file . getContents ( ) ; String content = SVCoreTestsPlugin . readStream ( in ) ; log . debug ( "" + content ) ; IndentComparator . compare ( log , "" , expected . trim ( ) , content . trim ( ) ) ; in . close ( ) ; } catch ( CoreException e ) { fail ( "" + e . getMessage ( ) ) ; } catch ( IOException e ) { fail ( "" + e . getMessage ( ) ) ; } } finally { } LogFactory . removeLogHandle ( log ) ; } public void testNewClassSuperCtor ( ) { String doc = "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; NewClassGenerator gen = new NewClassGenerator ( ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; try { IProject project_dir = TestUtils . createProject ( "" ) ; IFile file = project_dir . getFile ( "" ) ; assertEquals ( "" , false , file . exists ( ) ) ; File tmpdir = new File ( fTmpDir , "" ) ; if ( tmpdir . exists ( ) ) { TestUtils . delete ( tmpdir ) ; } assertTrue ( tmpdir . mkdirs ( ) ) ; SVDBIndexCollection index_it = SrcGenTests . createIndex ( doc ) ; gen . generate ( index_it , file , "" , "" , true , new NullProgressMonitor ( ) ) ; try { InputStream in = file . getContents ( ) ; String content = SVCoreTestsPlugin . readStream ( in ) ; log . debug ( "" + content ) ; IndentComparator . compare ( log , "" , expected . trim ( ) , content . trim ( ) ) ; in . close ( ) ; } catch ( CoreException e ) { fail ( "" + e . getMessage ( ) ) ; } catch ( IOException e ) { fail ( "" + e . getMessage ( ) ) ; } } finally { } LogFactory . removeLogHandle ( log ) ; } public void testNewClassTemplateSuper ( ) { String doc = "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; NewClassGenerator gen = new NewClassGenerator ( ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; try { IProject project_dir = TestUtils . createProject ( "" ) ; IFile file = project_dir . getFile ( "" ) ; assertEquals ( "" , false , file . exists ( ) ) ; File tmpdir = new File ( fTmpDir , "" ) ; if ( tmpdir . exists ( ) ) { tmpdir . delete ( ) ; } tmpdir . mkdirs ( ) ; SVDBIndexCollection index_it = SrcGenTests . createIndex ( doc ) ; gen . generate ( index_it , file , "" , "" , true , new NullProgressMonitor ( ) ) ; try { InputStream in = file . getContents ( ) ; String content = SVCoreTestsPlugin . readStream ( in ) ; log . debug ( "" + content ) ; IndentComparator . compare ( log , "" , expected . trim ( ) , content . trim ( ) ) ; in . close ( ) ; } catch ( CoreException e ) { fail ( "" + e . getMessage ( ) ) ; } catch ( IOException e ) { fail ( "" + e . getMessage ( ) ) ; } } finally { } LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . srcgen ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . ParserSVDBFileFactory ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . srcgen . MethodGenerator ; import net . sf . sveditor . core . tests . indent . IndentComparator ; public class TestMethodGenerator extends TestCase { private SVDBTask parse_tf ( String content , String name ) throws SVParseException { SVDBScopeItem scope = new SVDBScopeItem ( ) ; ParserSVDBFileFactory parser = new ParserSVDBFileFactory ( null ) ; parser . init ( new StringInputStream ( content ) , name ) ; parser . parsers ( ) . taskFuncParser ( ) . parse ( scope , null , ) ; return ( SVDBTask ) scope . getChildren ( ) . iterator ( ) . next ( ) ; } public void testVoidFunction ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , "" ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , "" , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testBuiltinRetFunction ( ) throws SVParseException { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , "" ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , "" , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testParamClassRetFunction ( ) throws SVParseException { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , "" ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( "" , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testParamClassParamFunction ( ) throws SVParseException { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , "" ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , "" , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testRefParamFunction ( ) throws SVParseException { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , "" ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , "" , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testRefVarListParamFunction ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , "" ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , "" , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testBitVecParamFunction ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , testname ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , testname , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testVectoredParam_1 ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , testname ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , testname , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testVectoredParam_2 ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , testname ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , testname , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testVectoredParam_3 ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , testname ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , testname , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } public void testVectoredParam_4 ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String content = "" + "" + "" ; String exp = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBTask tf = parse_tf ( content , testname ) ; MethodGenerator gen = new MethodGenerator ( ) ; String src = gen . generate ( tf ) ; log . debug ( "" + src ) ; IndentComparator . compare ( log , testname , exp , src ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . srcgen ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . tests . SVDBStringDocumentIndex ; import junit . framework . Test ; import junit . framework . TestSuite ; public class SrcGenTests extends TestSuite { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( TestNewClassGen . class ) ) ; suite . addTest ( new TestSuite ( TestMethodGenerator . class ) ) ; return suite ; } public static SVDBIndexCollection createIndex ( String doc ) { SVDBIndexCollection index_mgr = new SVDBIndexCollection ( "" ) ; index_mgr . addPluginLibrary ( new SVDBStringDocumentIndex ( doc ) ) ; return index_mgr ; } } package net . sf . sveditor . core . tests . project_settings ; import java . io . File ; import org . eclipse . core . resources . IProject ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBSourceCollection ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . core . tests . IndexTestUtils ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import junit . framework . TestCase ; import junit . framework . TestSuite ; public class ProjectSettingsTests extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public static TestSuite suite ( ) { TestSuite s = new TestSuite ( "" ) ; s . addTest ( new TestSuite ( ProjectSettingsTests . class ) ) ; s . addTest ( new TestSuite ( TestProjectSettingsVarRefs . class ) ) ; return s ; } public void testSourceCollectionChange ( ) { fProject = TestUtils . createProject ( "" , fTmpDir ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; utils . copyBundleDirToWS ( "" , fProject ) ; SVDBProjectData pd = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVProjectFileWrapper fw ; SVDBSourceCollection sc ; SVDBIndexCollection index ; fw = pd . getProjectFileWrapper ( ) ; sc = new SVDBSourceCollection ( "" , true ) ; fw . getSourceCollections ( ) . clear ( ) ; fw . getSourceCollections ( ) . add ( sc ) ; pd . setProjectFileWrapper ( fw , true ) ; index = pd . getProjectIndexMgr ( ) ; IndexTestUtils . assertFileHasElements ( index , "" ) ; IndexTestUtils . assertDoesNotContain ( index , "" ) ; fw = pd . getProjectFileWrapper ( ) ; sc = new SVDBSourceCollection ( "" , true ) ; fw . getSourceCollections ( ) . clear ( ) ; fw . getSourceCollections ( ) . add ( sc ) ; pd . setProjectFileWrapper ( fw , true ) ; index = pd . getProjectIndexMgr ( ) ; IndexTestUtils . assertFileHasElements ( index , "" ) ; IndexTestUtils . assertDoesNotContain ( index , "" ) ; } public void testSourceCollectionChangeIncExclExts ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; fProject = TestUtils . createProject ( "" , fTmpDir ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; utils . copyBundleDirToWS ( "" , fProject ) ; SVDBProjectData pd = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVProjectFileWrapper fw ; SVDBSourceCollection sc ; SVDBIndexCollection index ; fw = pd . getProjectFileWrapper ( ) ; sc = new SVDBSourceCollection ( "" , false ) ; sc . getIncludes ( ) . add ( "" ) ; fw . getSourceCollections ( ) . clear ( ) ; fw . getSourceCollections ( ) . add ( sc ) ; pd . setProjectFileWrapper ( fw , true ) ; index = pd . getProjectIndexMgr ( ) ; IndexTestUtils . assertFileHasElements ( index , "" ) ; IndexTestUtils . assertDoesNotContain ( index , "" ) ; fw = pd . getProjectFileWrapper ( ) ; sc = new SVDBSourceCollection ( "" , false ) ; sc . getIncludes ( ) . add ( "" ) ; fw . getSourceCollections ( ) . clear ( ) ; fw . getSourceCollections ( ) . add ( sc ) ; pd . setProjectFileWrapper ( fw , true ) ; index = pd . getProjectIndexMgr ( ) ; IndexTestUtils . assertFileHasElements ( index , "" ) ; IndexTestUtils . assertDoesNotContain ( index , "" ) ; } } package net . sf . sveditor . core . tests . project_settings ; import java . io . File ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBIndexUtil ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . IndexTestUtils ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; public class TestProjectSettingsVarRefs extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; File db = new File ( fTmpDir , "" ) ; assertTrue ( db . mkdirs ( ) ) ; rgy . init ( new TestIndexCacheFactory ( db ) ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testArgFileWorkspaceRelRef ( ) throws CoreException { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; CoreReleaseTests . clearErrors ( ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; fProject = TestUtils . importProject ( new File ( fTmpDir , "" ) ) ; SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVDBIndexCollection index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; InputStream in = null ; IFile parameters_sv = root . getFile ( new Path ( "" + fProject . getName ( ) + "" ) ) ; in = parameters_sv . getContents ( ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = index_collection . parse ( new NullProgressMonitor ( ) , in , "" + fProject . getName ( ) + "" , markers ) . second ( ) ; assertNotNull ( file ) ; assertEquals ( , markers . size ( ) ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; } public void testResourceVarProjVarRef ( ) throws CoreException { String testname = "" ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; CoreReleaseTests . clearErrors ( ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; fProject = TestUtils . importProject ( new File ( fTmpDir , "" ) ) ; SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVDBIndexCollection index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; InputStream in = null ; IFile parameters_sv = root . getFile ( new Path ( "" + fProject . getName ( ) + "" ) ) ; in = parameters_sv . getContents ( ) ; String target_file = "" + fProject . getName ( ) + "" ; Tuple < ISVDBIndex , SVDBIndexCollection > result = SVDBIndexUtil . findIndexFile ( target_file , fProject . getName ( ) , false ) ; assertNotNull ( result ) ; log . debug ( "" + result . first ( ) . getBaseLocation ( ) ) ; log . debug ( "" ) ; for ( String file : result . first ( ) . getFileList ( new NullProgressMonitor ( ) ) ) { log . debug ( "" + file ) ; } List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = result . second ( ) . parse ( new NullProgressMonitor ( ) , in , target_file , markers ) . second ( ) ; assertNotNull ( file ) ; assertEquals ( , markers . size ( ) ) ; assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; } public void testProjectDefine ( ) throws CoreException { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( true ) ; CoreReleaseTests . clearErrors ( ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; fProject = TestUtils . createProject ( testname , new File ( fTmpDir , "" ) ) ; SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVProjectFileWrapper wrapper = pdata . getProjectFileWrapper ( ) ; wrapper . addGlobalDefine ( "" , "" ) ; wrapper . addArgFilePath ( "" + testname + "" ) ; pdata . setProjectFileWrapper ( wrapper ) ; SVDBIndexCollection index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; IndexTestUtils . assertFileHasElements ( index_collection , "" ) ; } public void testProjectDefineChange ( ) throws CoreException { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( true ) ; CoreReleaseTests . clearErrors ( ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; fProject = TestUtils . createProject ( testname , new File ( fTmpDir , "" ) ) ; SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVProjectFileWrapper wrapper = pdata . getProjectFileWrapper ( ) ; wrapper . addArgFilePath ( "" + testname + "" ) ; pdata . setProjectFileWrapper ( wrapper ) ; SVDBIndexCollection index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; IndexTestUtils . assertDoesNotContain ( index_collection , "" ) ; wrapper = pdata . getProjectFileWrapper ( ) ; wrapper . addGlobalDefine ( "" , "" ) ; pdata . setProjectFileWrapper ( wrapper ) ; index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; IndexTestUtils . assertFileHasElements ( index_collection , "" ) ; } public void testProjectUndefined ( ) throws CoreException { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; CoreReleaseTests . clearErrors ( ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; fProject = TestUtils . createProject ( "" , new File ( fTmpDir , "" ) ) ; SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVDBIndexCollection index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; IndexTestUtils . assertDoesNotContain ( index_collection , "" ) ; } public void testProjectDefine_1 ( ) throws CoreException { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; CoreReleaseTests . clearErrors ( ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; fProject = TestUtils . createProject ( "" , new File ( fTmpDir , "" ) ) ; SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVProjectFileWrapper wrapper = pdata . getProjectFileWrapper ( ) ; wrapper . addArgFilePath ( "" ) ; wrapper . addGlobalDefine ( "" , "" ) ; pdata . setProjectFileWrapper ( wrapper ) ; SVDBIndexCollection index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; IndexTestUtils . assertFileHasElements ( index_collection , "" ) ; IndexTestUtils . assertDoesNotContain ( index_collection , "" ) ; } public void testArgFilePathChange ( ) throws CoreException { String testname = "" ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; CoreReleaseTests . clearErrors ( ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; fProject = TestUtils . importProject ( new File ( fTmpDir , "" ) ) ; SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( fProject ) ; SVDBIndexCollection index_collection = null ; SVProjectFileWrapper fw ; CoreReleaseTests . clearErrors ( ) ; fw = pdata . getProjectFileWrapper ( ) ; fw . addArgFilePath ( "" ) ; pdata . setProjectFileWrapper ( fw , true ) ; index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; assertTrue ( CoreReleaseTests . getErrors ( ) . size ( ) > ) ; CoreReleaseTests . clearErrors ( ) ; fw = pdata . getProjectFileWrapper ( ) ; fw . getArgFilePaths ( ) . clear ( ) ; fw . addArgFilePath ( "" ) ; pdata . setProjectFileWrapper ( fw , true ) ; index_collection = pdata . getProjectIndexMgr ( ) ; index_collection . loadIndex ( new NullProgressMonitor ( ) ) ; assertTrue ( CoreReleaseTests . getErrors ( ) . size ( ) == ) ; } } package net . sf . sveditor . core . tests . parser ; import junit . framework . TestCase ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBUtil ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestParseLineNumbers extends TestCase { public void testClassLineNumbers ( ) { String content = "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBClassDecl cls = null ; assertEquals ( "" , , SVDBUtil . getChildrenSize ( file ) ) ; cls = ( SVDBClassDecl ) SVDBUtil . getFirstChildItem ( file ) ; assertNotNull ( "" , cls . getLocation ( ) ) ; assertNotNull ( "" , cls . getEndLocation ( ) ) ; assertEquals ( "" , , cls . getLocation ( ) . getLine ( ) ) ; assertEquals ( "" , , cls . getEndLocation ( ) . getLine ( ) ) ; } public void testClassFunctionLineNumbers ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBClassDecl cls = null ; assertEquals ( "" , , SVDBUtil . getChildrenSize ( file ) ) ; cls = ( SVDBClassDecl ) SVDBUtil . getFirstChildItem ( file ) ; assertNotNull ( "" , cls . getLocation ( ) ) ; assertNotNull ( "" , cls . getEndLocation ( ) ) ; assertEquals ( "" , , cls . getLocation ( ) . getLine ( ) ) ; assertEquals ( "" , , cls . getEndLocation ( ) . getLine ( ) ) ; SVDBTask f1 = null , f2 = null ; for ( ISVDBItemBase it : cls . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { f1 = ( SVDBTask ) it ; } if ( SVDBItem . getName ( it ) . equals ( "" ) ) { f2 = ( SVDBTask ) it ; } } assertNotNull ( f1 ) ; assertNotNull ( f2 ) ; assertEquals ( "" , , f1 . getLocation ( ) . getLine ( ) ) ; assertEquals ( "" , , f1 . getEndLocation ( ) . getLine ( ) ) ; assertEquals ( "" , , f2 . getLocation ( ) . getLine ( ) ) ; assertEquals ( "" , , f2 . getEndLocation ( ) . getLine ( ) ) ; } } package net . sf . sveditor . core . tests . parser ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltin ; import net . sf . sveditor . core . db . SVDBTypeInfoBuiltinNet ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestParseModuleBodyItems extends TestCase { public void testPackageModule ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( log , content , "" , false ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testDefineCaseItems ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( log , content , "" , false ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testRandCase ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; LogFactory . removeLogHandle ( log ) ; } public void testDelayedAssign ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testDelayedExprAssign ( ) { String content = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testDelayedExprAssignRiseFall ( ) { String content = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testModuleSizedParameter ( ) { String content = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testModuleGenvarDecl ( ) { String content = "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testModuleInterfacePort ( ) { String content = "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testModuleBitArrayPort ( ) { String content = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testModuleSignedPort ( ) { String content = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testModuleSizedSignedPort ( ) { String content = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testAssignInvert ( ) { String doc = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testAssignSystemTask ( ) { String doc = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testInitialBlock ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBModIfcDecl top = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { top = ( SVDBModIfcDecl ) it ; break ; } } assertNotNull ( "" , top ) ; ISVDBItemBase initial = null ; for ( ISVDBItemBase it : top . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . InitialStmt ) { initial = it ; break ; } } assertNotNull ( "" , initial ) ; } public void testPortList ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . Marker ) { log . debug ( "" + ( ( SVDBMarker ) it ) . getMessage ( ) ) ; } } SVDBModIfcDecl top = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { top = ( SVDBModIfcDecl ) it ; break ; } } assertNotNull ( "" , top ) ; for ( SVDBParamPortDecl p : top . getPorts ( ) ) { for ( ISVDBChildItem c : p . getChildren ( ) ) { log . debug ( "" + SVDBItem . getName ( c ) ) ; } } SVDBVarDeclItem a = null , b = null , c = null , d = null , bus = null ; for ( ISVDBItemBase it : top . getChildren ( ) ) { String name = SVDBItem . getName ( it ) ; log . debug ( "" + it . getType ( ) + "" + name ) ; if ( it . getType ( ) == SVDBItemType . VarDeclStmt ) { for ( ISVDBChildItem ci : ( ( SVDBVarDeclStmt ) it ) . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) ci ; log . debug ( "" + vi . getName ( ) ) ; if ( vi . getName ( ) . equals ( "" ) ) { a = vi ; } else if ( vi . getName ( ) . equals ( "" ) ) { b = vi ; } else if ( vi . getName ( ) . equals ( "" ) ) { c = vi ; } else if ( vi . getName ( ) . equals ( "" ) ) { d = vi ; } else if ( vi . getName ( ) . equals ( "" ) ) { bus = vi ; } } } } assertNotNull ( a ) ; assertNotNull ( b ) ; assertNotNull ( c ) ; assertNotNull ( d ) ; assertNotNull ( bus ) ; assertEquals ( "" , a . getParent ( ) . getTypeName ( ) ) ; assertEquals ( "" , a . getParent ( ) . getTypeName ( ) ) ; assertTrue ( bus . getParent ( ) . getTypeInfo ( ) instanceof SVDBTypeInfoBuiltinNet ) ; SVDBTypeInfoBuiltinNet net_type = ( SVDBTypeInfoBuiltinNet ) bus . getParent ( ) . getTypeInfo ( ) ; log . debug ( "" + ( ( SVDBTypeInfoBuiltin ) net_type . getTypeInfo ( ) ) . getVectorDim ( ) ) ; assertEquals ( , ( ( SVDBTypeInfoBuiltin ) net_type . getTypeInfo ( ) ) . getVectorDim ( ) . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testTypedPortList ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . Marker ) { log . debug ( "" + ( ( SVDBMarker ) it ) . getMessage ( ) ) ; } } SVDBModIfcDecl top = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { top = ( SVDBModIfcDecl ) it ; break ; } } assertNotNull ( "" , top ) ; SVDBVarDeclItem a = null , b = null , bar = null ; for ( SVDBParamPortDecl p : top . getPorts ( ) ) { for ( ISVDBChildItem c : p . getChildren ( ) ) { SVDBVarDeclItem pi = ( SVDBVarDeclItem ) c ; log . debug ( "" + pi . getName ( ) ) ; if ( pi . getName ( ) . equals ( "" ) ) { a = pi ; } else if ( pi . getName ( ) . equals ( "" ) ) { b = pi ; } else if ( pi . getName ( ) . equals ( "" ) ) { bar = pi ; } } } assertNotNull ( a ) ; assertNotNull ( b ) ; assertNotNull ( bar ) ; assertEquals ( SVDBItemType . TypeInfoUserDef , b . getParent ( ) . getTypeInfo ( ) . getType ( ) ) ; assertEquals ( "" , ( ( SVDBTypeInfoUserDef ) b . getParent ( ) . getTypeInfo ( ) ) . getName ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testAlwaysBlock ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; List < SVDBMarker > errors = new ArrayList < SVDBMarker > ( ) ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . Marker ) { log . debug ( "" + ( ( SVDBMarker ) it ) . getMessage ( ) ) ; SVDBMarker m = ( SVDBMarker ) it ; if ( m . getMarkerType ( ) == MarkerType . Error ) { errors . add ( m ) ; } } } SVDBTestUtils . assertFileHasElements ( file , "" ) ; assertEquals ( "" , , errors . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedModule ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBModIfcDecl top = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { top = ( SVDBModIfcDecl ) it ; } } assertNotNull ( "" , top ) ; SVDBModIfcDecl inner = null ; for ( ISVDBItemBase it : top . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { inner = ( SVDBModIfcDecl ) it ; } } assertNotNull ( "" , inner ) ; LogFactory . removeLogHandle ( log ) ; } public void testEmptyParamList ( ) { String doc = "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testParameterDeclaration ( ) { String doc = "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBModIfcDecl t1 = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { t1 = ( SVDBModIfcDecl ) it ; } } assertNotNull ( "" , t1 ) ; SVDBVarDeclItem c = null ; for ( ISVDBItemBase it : t1 . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . ParamPortDecl ) { for ( ISVDBChildItem ci : ( ( SVDBParamPortDecl ) it ) . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) ci ; if ( vi . getName ( ) . equals ( "" ) ) { c = vi ; } } } } assertNotNull ( c ) ; } public void testParameterExprInit ( ) { String doc = "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBModIfcDecl t = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { t = ( SVDBModIfcDecl ) it ; } } assertNotNull ( "" , t ) ; SVDBVarDeclItem a = null , b = null ; for ( ISVDBItemBase it : t . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . ParamPortDecl ) { for ( ISVDBChildItem c : ( ( SVDBParamPortDecl ) it ) . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; if ( vi . getName ( ) . equals ( "" ) ) { a = vi ; } else if ( vi . getName ( ) . equals ( "" ) ) { b = vi ; } } } } assertNotNull ( a ) ; assertNotNull ( b ) ; } public void testAlwaysVariants ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBModIfcDecl t3 = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { t3 = ( SVDBModIfcDecl ) it ; } } assertNotNull ( "" , t3 ) ; for ( ISVDBItemBase it : t3 . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } LogFactory . removeLogHandle ( log ) ; } public void testGenVars ( ) { String doc = "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex1 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex1_a ( ) { String doc = "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex1_b ( ) { String doc = "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex1_c ( ) { String doc = "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex2 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex3 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex4 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex5 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex_Cond_1 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGen_LRM_Ex_Cond_2 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testClocking_LRM_Ex1 ( ) { String doc = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGenBeginEnd ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testClocking_DR ( ) { String doc = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testClockingSameLine_DR ( ) { String testname = "" ; String doc = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testOutputPort ( ) { String doc = "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testUntypedInputPort ( ) { String doc = "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBModIfcDecl t = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { t = ( SVDBModIfcDecl ) it ; } } assertNotNull ( "" , t ) ; SVDBVarDeclItem out = null , in = null , in2 = null ; for ( SVDBParamPortDecl p : ( ( SVDBModIfcDecl ) t ) . getPorts ( ) ) { for ( ISVDBChildItem c : p . getChildren ( ) ) { SVDBVarDeclItem pi = ( SVDBVarDeclItem ) c ; if ( pi . getName ( ) . equals ( "" ) ) { out = pi ; } else if ( pi . getName ( ) . equals ( "" ) ) { in = pi ; } else if ( pi . getName ( ) . equals ( "" ) ) { in2 = pi ; } } } assertNotNull ( "" , out ) ; assertNotNull ( "" , in ) ; assertNotNull ( "" , in2 ) ; } public void testModportPort ( ) { String doc = "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBModIfcDecl t2 = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { t2 = ( SVDBModIfcDecl ) it ; } } assertNotNull ( "" , t2 ) ; SVDBVarDeclItem mp = null ; for ( SVDBParamPortDecl p : ( ( SVDBModIfcDecl ) t2 ) . getPorts ( ) ) { for ( ISVDBChildItem c : p . getChildren ( ) ) { SVDBVarDeclItem pi = ( SVDBVarDeclItem ) c ; if ( pi . getName ( ) . equals ( "" ) ) { mp = pi ; } } } assertNotNull ( "" , mp ) ; } public void testTypedInitializedParameterDecl ( ) { String doc = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testParameterArrayRefExpr ( ) { String doc = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testMappedParameterizedModule ( ) { String doc = "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testGlobalParamRef ( ) { String doc = "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testVarCompare ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testAlwaysIfElse ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" + "" + "" + "" + "" , new String [ ] { "" } ) ; } public void testAlwaysMultiLevelIf ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" , new String [ ] { "" } ) ; } public void testAlwaysCase ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testAlwaysCaseDefaultNoColon ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testTaskNonAnsiInputParam ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testPreIncDec ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testPostIncDec ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testMultiModuleInstantiation ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testVmmErrorBehaveBlock ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testModulePreBodyImport ( ) { String doc = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" , "" } ) ; } public void testModulePreBodyImport2 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" , "" } ) ; } public void testModulePreBodyImport3 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" , "" } ) ; } public void testGatePrimitives1 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testGatePrimitives2 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testCovergroup ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" , "" } ) ; } public void testModuleInst ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" , "" } ) ; } public void testAssignStrength ( ) { String doc = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testTimeUnitPrecision ( ) { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( testname , doc , new String [ ] { "" } ) ; } public void testLocalParamAssign ( ) { String testname = "" ; String doc = "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( testname , doc , new String [ ] { "" , "" } ) ; } public void testModInstArray ( ) { String testname = "" ; String doc = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( testname , doc , new String [ ] { "" , "" , "" , "" } ) ; } public void testDPIExportImport ( ) { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( testname , doc , new String [ ] { "" , "" } ) ; } public void testNonBlockingDelayAssign ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" ; } public void testSpecifyBlock_2 ( ) throws SVParseException { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( testname , doc , new String [ ] { "" } ) ; } public void testParseEvent ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } private void runTest ( String testname , String doc , String exp_items [ ] ) { LogHandle log = LogFactory . getLogHandle ( testname ) ; SVDBFile file = SVDBTestUtils . parse ( log , doc , testname , false ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import junit . framework . TestCase ; public class TestParseConfigurations extends TestCase { public void testConfig_33_2_1 ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , content , new String [ ] { "" } ) ; } public void testConfig_33_2_2 ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , content , new String [ ] { "" } ) ; } } package net . sf . sveditor . core . tests . parser ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . IOException ; import java . io . PrintStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBFSFileSystemProvider ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . TestNullIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestSystemParse extends TestCase { public void testParseOvmSequenceUtils ( ) { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; ByteArrayOutputStream bos = utils . readBundleFile ( "" ) ; SVDBFile file = SVDBTestUtils . parse ( bos . toString ( ) , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; } public void testRecursiveInclude ( ) throws IOException { File tmpdir = TestUtils . createTempDir ( ) ; try { PrintStream ps = new PrintStream ( new File ( tmpdir , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . close ( ) ; ps = new PrintStream ( new File ( tmpdir , "" ) ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . println ( "" ) ; ps . close ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( new TestNullIndexCacheFactory ( ) ) ; SVDBFSFileSystemProvider fs = new SVDBFSFileSystemProvider ( ) ; fs . init ( tmpdir . getAbsolutePath ( ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , new File ( tmpdir , "" ) . getAbsolutePath ( ) , SVDBLibPathIndexFactory . TYPE , null ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; ISVDBItemIterator it = index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBItemBase class_1 = null ; while ( it . hasNext ( ) ) { ISVDBItemBase i = it . nextItem ( ) ; if ( SVDBItem . getName ( i ) . equals ( "" ) ) { class_1 = i ; } } assertNotNull ( class_1 ) ; } finally { TestUtils . delete ( tmpdir ) ; } } } package net . sf . sveditor . core . tests . parser ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBScopeItem ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBUtil ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . parser . ParserSVDBFileFactory ; import net . sf . sveditor . core . parser . SVParseException ; public class TestParseFunction extends TestCase { private SVDBTask parse_tf ( String content , String name ) throws SVParseException { SVDBScopeItem scope = new SVDBScopeItem ( ) ; ParserSVDBFileFactory parser = new ParserSVDBFileFactory ( null ) ; parser . init ( new StringInputStream ( content ) , name ) ; parser . parsers ( ) . taskFuncParser ( ) . parse ( scope , null , ) ; return ( SVDBTask ) scope . getChildren ( ) . iterator ( ) . next ( ) ; } private SVDBClassDecl parse_class ( String content , String name ) throws SVParseException { SVDBScopeItem scope = new SVDBScopeItem ( ) ; ParserSVDBFileFactory parser = new ParserSVDBFileFactory ( null ) ; parser . init ( new StringInputStream ( content ) , name ) ; parser . parsers ( ) . classParser ( ) . parse ( scope , ) ; return ( SVDBClassDecl ) scope . getChildren ( ) . iterator ( ) . next ( ) ; } public void testBasicFunction ( ) throws SVParseException { String content = "" + "" + "" ; parse_tf ( content , "" ) ; } public void testReturnOnlyFunction ( ) throws SVParseException { String content = "" + "" + "" + "" + "" ; parse_class ( content , "" ) ; } public void testKRParameters ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" ; parse_tf ( content , testname ) ; } public void testKRParameters2 ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; parse_tf ( content , testname ) ; } public void testTaskWithParam ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" ; parse_tf ( content , testname ) ; } public void testLocalVarsWithCast ( ) throws SVParseException { String content = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBTask func = parse_tf ( content , "" ) ; assertEquals ( , SVDBUtil . getChildrenSize ( func ) ) ; SVDBVarDeclItem a = null , b = null ; for ( ISVDBItemBase it_t : func . getChildren ( ) ) { if ( it_t . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt v = ( SVDBVarDeclStmt ) it_t ; for ( ISVDBChildItem vi : v . getChildren ( ) ) { if ( SVDBItem . getName ( vi ) . equals ( "" ) ) { a = ( SVDBVarDeclItem ) vi ; } else if ( SVDBItem . getName ( vi ) . equals ( "" ) ) { b = ( SVDBVarDeclItem ) vi ; } } } } assertNotNull ( a ) ; assertNotNull ( b ) ; } public void testLocalTimeVar ( ) throws SVParseException { String content = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBTask func = parse_tf ( content , "" ) ; assertEquals ( , SVDBUtil . getChildrenSize ( func ) ) ; assertTrue ( SVDBUtil . getFirstChildItem ( func ) . getType ( ) == SVDBItemType . VarDeclStmt ) ; SVDBVarDeclStmt stmt = ( SVDBVarDeclStmt ) SVDBUtil . getFirstChildItem ( func ) ; SVDBVarDeclItem vi = ( SVDBVarDeclItem ) stmt . getChildren ( ) . iterator ( ) . next ( ) ; assertEquals ( "" , vi . getName ( ) ) ; } public void testLocalTypedef ( ) throws SVParseException { String content = "" + "" + "" + "" + "" ; SVDBTask func = parse_tf ( content , "" ) ; SVDBVarDeclItem a = null ; for ( ISVDBItemBase it : func . getChildren ( ) ) { if ( it . getType ( ) == SVDBItemType . VarDeclStmt ) { for ( ISVDBChildItem vi : ( ( SVDBVarDeclStmt ) it ) . getChildren ( ) ) { if ( SVDBItem . getName ( vi ) . equals ( "" ) ) { a = ( SVDBVarDeclItem ) vi ; } } } } assertEquals ( , SVDBUtil . getChildrenSize ( func ) ) ; assertEquals ( "" , SVDBItem . getName ( SVDBUtil . getFirstChildItem ( func ) ) ) ; assertNotNull ( a ) ; } public void testStaticFunction ( ) throws SVParseException { String content = "" + "" + "" ; parse_tf ( content , "" ) ; } public void testIfElseBody ( ) throws SVParseException { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; parse_tf ( content , "" ) ; } public void testAutomaticFunction ( ) throws SVParseException { String content = "" + "" + "" ; parse_tf ( content , "" ) ; } public void testParamListFunction ( ) throws SVParseException { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBTask func = parse_tf ( content , "" ) ; ISVDBChildItem c = func . getParams ( ) . get ( ) . getChildren ( ) . iterator ( ) . next ( ) ; assertEquals ( "" , SVDBItem . getName ( c ) ) ; assertEquals ( SVDBParamPortDecl . Direction_Ref , func . getParams ( ) . get ( ) . getDir ( ) ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import junit . framework . TestCase ; public class TestParseBehavioralStmts extends TestCase { public void testModulePreBodyImport3 ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" , "" , "" , "" , "" } ) ; } public void testVarDeclForStmt ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testMultiVarDeclForStmt ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testNonBlockingEventTrigger ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testEventDelayedNonBlockingAssign ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testVirtualInterfaceParameterizedStaticCall ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testConstIntParameterizedStaticCall ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testStringParameterizedStaticCall ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testEmptyParameterizedStaticCall ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testVarDeclListForStmt ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testVarDeclListForStmt2 ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" } ) ; } public void testOmittedTFCallParams ( ) throws SVParseException { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , doc , new String [ ] { "" , "" , "" } ) ; } private void runTest ( String testname , String doc , String exp_items [ ] ) { SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; } } package net . sf . sveditor . core . tests . parser ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestParseProgramBlocks extends TestCase { public void testNamedProgramBlock ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; for ( ISVDBItemBase it : file . getItems ( ) ) { if ( it . getType ( ) == SVDBItemType . Marker ) { System . out . println ( "" + ( ( SVDBMarker ) it ) . getMessage ( ) ) ; } } SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testAnonProgramBlock ( ) { String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; for ( ISVDBItemBase it : file . getItems ( ) ) { if ( it . getType ( ) == SVDBItemType . Marker ) { System . out . println ( "" + ( ( SVDBMarker ) it ) . getMessage ( ) ) ; } } SVDBTestUtils . assertFileHasElements ( file , "" ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import junit . framework . TestCase ; public class TestLexer extends TestCase { public void testSpaceContainingNumber ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" } ) ; } public void testParenContainingString ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testDefinedMacroCallWithStatement ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void EXP_FAIL_testUnDefinedMacroCallWithStatement ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } private void runTest ( String testname , String doc , String exp_items [ ] ) { LogHandle log = LogFactory . getLogHandle ( testname ) ; SVDBFile file = SVDBTestUtils . parse ( log , doc , testname , false ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . parser ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestParserSVStdExamples extends TestCase { public void test_7_2_0_struct_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" , "" , "" } ) ; } public void test_7_2_0_struct_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" , "" , "" } ) ; } public void test_7_2_1_struct_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" , "" , "" } ) ; } public void test_7_2_1_struct_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" , "" } ) ; } public void test_7_2_2_struct_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" , "" , "" , "" } ) ; } public void test_7_3_0_union_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" , "" , "" , "" } ) ; } public void test_13_5_3_tf_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" , "" , "" } ) ; } public void test_13_5_3_tf_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" , "" } ) ; } public void test_13_5_4_tf_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_3_0_assert_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_3_0_assert_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_3_0_assert_3 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_4_2_assert_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_4_2_assert_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_4_2_assert_3 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_4_3_assert_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_4_3_assert_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_4_4_assert_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_4_4_assert_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_4_5_assert_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_6_0_assert_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_0_sequence_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_0_sequence_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_0_sequence_3 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_0_sequence_4 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_0_sequence_5 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void EXP_FAIL_test_16_8_1_sequence_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_1_sequence_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_1_sequence_3 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_1_sequence_4 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_8_1_sequence_5 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_property_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_property_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_sequence_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_sequence_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_sequence_3 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_sequence_4 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_sequence_5 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_sequence_6 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_10_0_sequence_7 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_11_0_sequence_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_11_0_throughout_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_13_0_property_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_13_6_property_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_13_6_property_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void test_16_13_6_property_3 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void EXP_FAIL_test_16_13_6_property_4 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void EXP_FAIL_test_16_13_6_property_5 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void EXP_FAIL_test_16_13_7_property_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void EXP_FAIL_test_16_13_7_property_2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void EXP_FAIL_test_16_13_10_property_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void EXP_FAIL_test_16_13_11_property_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } public void EXP_FAIL_test_16_13_12_property_1 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , "" , new String [ ] { "" } ) ; } private void runTest ( String testname , String data , String exp_items [ ] ) throws SVParseException { LogHandle log = LogFactory . getLogHandle ( testname ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; InputStream in = null ; try { URL url = SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) . getEntry ( data ) ; in = url . openStream ( ) ; } catch ( IOException e ) { fail ( "" + data + "" + e . getMessage ( ) ) ; } SVDBFile file = SVDBTestUtils . parse ( log , in , data , markers ) . second ( ) ; try { in . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } assertEquals ( , markers . size ( ) ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . parser ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBConstraint ; import net . sf . sveditor . core . db . SVDBCovergroup ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestParseClassBodyItems extends TestCase { public void testTaskFunction ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" } ) ; } public void testImplicitVectoredReturnFunction ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testEmptyClass ( ) { String content = "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , content , new String [ ] { "" } ) ; } public void testSingleParameterClass ( ) { String content = "" + "" ; runTest ( "" , content , new String [ ] { "" } ) ; } public void testSimpleExtensionClass ( ) { String content = "" + "" ; runTest ( "" , content , new String [ ] { "" } ) ; } public void testCovergroupSizedArrayBins ( ) { String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testTypedClassParameters ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" } ) ; } public void testMultiParamClass ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; runTest ( "" , content , new String [ ] { "" } ) ; } public void testAttrInstance ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" } ) ; } public void testIncompleteAttrInstance ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTestExpErr ( "" , content , new String [ ] { "" , "" , "" , "" } ) ; } public void testAttrTaggedRandomize ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" } ) ; } public void testAttrTaggedRandomize2 ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" } ) ; } public void testAttrTaggedTF ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" } ) ; } public void testFunctionVirtualIfcParam ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" } ) ; } public void testClassFields ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; } public void testBuiltinExternTasks ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" } ) ; } public void testClassStringFields ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; LogHandle log = LogFactory . getLogHandle ( "" ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBClassDecl cg_options = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { cg_options = ( SVDBClassDecl ) it ; } log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; } assertNotNull ( "" , cg_options ) ; for ( ISVDBItemBase it : cg_options . getChildren ( ) ) { log . debug ( "" + it . getType ( ) + "" + SVDBItem . getName ( it ) ) ; assertNotNull ( "" + SVDBItem . getName ( it ) + "" , it . getLocation ( ) ) ; if ( SVDBStmt . isType ( it , SVDBItemType . VarDeclStmt ) ) { assertNotNull ( "" + SVDBItem . getName ( it ) + "" , ( ( SVDBVarDeclStmt ) it ) . getTypeInfo ( ) ) ; } } } public void testTypedef ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBClassDecl foobar = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { foobar = ( SVDBClassDecl ) it ; break ; } } SVDBTypedefStmt foobar_td = null ; ISVDBItemBase foobar_i = null ; for ( ISVDBItemBase it : foobar . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { foobar_i = it ; } } assertNotNull ( "" , foobar_i ) ; assertEquals ( "" , foobar_i . getType ( ) , SVDBItemType . TypedefStmt ) ; foobar_td = ( SVDBTypedefStmt ) foobar_i ; assertEquals ( "" , SVDBItemType . TypeInfoEnum , foobar_td . getTypeInfo ( ) . getType ( ) ) ; SVDBTypeInfoEnum enum_t = ( SVDBTypeInfoEnum ) foobar_td . getTypeInfo ( ) ; assertEquals ( "" , , enum_t . getEnumerators ( ) . size ( ) ) ; } public void testBeginBlockVirtualInterfaceVar ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , content , new String [ ] { "" , "" } ) ; } public void testTypedefClass ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBClassDecl foobar = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { foobar = ( SVDBClassDecl ) it ; break ; } } SVDBTypedefStmt foobar_td = null ; ISVDBItemBase foobar_i = null ; ISVDBItemBase foobar_i1 = null ; for ( ISVDBItemBase it : foobar . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { foobar_i = it ; } else if ( SVDBItem . getName ( it ) . equals ( "" ) ) { foobar_i1 = it ; } } assertNotNull ( "" , foobar_i ) ; assertNotNull ( "" , foobar_i1 ) ; assertEquals ( "" , foobar_i . getType ( ) , SVDBItemType . TypedefStmt ) ; foobar_td = ( SVDBTypedefStmt ) foobar_i ; assertEquals ( "" , SVDBItemType . TypeInfoFwdDecl , foobar_td . getTypeInfo ( ) . getType ( ) ) ; } public void testCovergroup ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBClassDecl foobar = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { foobar = ( SVDBClassDecl ) it ; break ; } } assertNotNull ( foobar ) ; SVDBCovergroup cg = null , cg2 = null ; for ( ISVDBItemBase it : foobar . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { cg = ( SVDBCovergroup ) it ; } else if ( SVDBItem . getName ( it ) . equals ( "" ) ) { cg2 = ( SVDBCovergroup ) it ; } } assertNotNull ( cg ) ; assertNotNull ( cg2 ) ; } public void testEmptyConstraint ( ) { String content = "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBClassDecl foobar = null ; for ( ISVDBItemBase it : file . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { foobar = ( SVDBClassDecl ) it ; break ; } } assertNotNull ( foobar ) ; SVDBConstraint empty_c = null ; for ( ISVDBItemBase it : foobar . getChildren ( ) ) { if ( SVDBItem . getName ( it ) . equals ( "" ) ) { empty_c = ( SVDBConstraint ) it ; } } assertNotNull ( empty_c ) ; } public void testExternConstraint ( ) { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testImplicationConstraint ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testComplexImplicationConstraint ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testSoftConstraint ( ) { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testRandomizeWithNoArgList ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testRandomizeWithArgList ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testFindWithNoArgList ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testFindWithArgList ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testRandomizeLocalVarRef ( ) { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } private void runTest ( String testname , String doc , String exp_items [ ] ) { LogHandle log = LogFactory . getLogHandle ( testname ) ; SVDBFile file = SVDBTestUtils . parse ( log , doc , testname , false ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; LogFactory . removeLogHandle ( log ) ; } private void runTestExpErr ( String testname , String doc , String exp_items [ ] ) { SVDBFile file = SVDBTestUtils . parse ( doc , testname , true ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . parser . SVParseException ; import junit . framework . TestCase ; public class TestParseCovergroups extends TestCase { public void testCovergroup ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" , "" } ) ; } public void testTransitionBins ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" , "" } ) ; } } package net . sf . sveditor . core . tests . parser ; import junit . framework . TestCase ; public class TestParseStruct extends TestCase { public void testParseTypedefStruct ( ) { } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . parser . SVParseException ; import junit . framework . TestCase ; public class TestParseSpecify extends TestCase { public void testSpecifyIf ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } public void testSpecifyBlock ( ) throws SVParseException { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } public void testSpecifyBlock_2 ( ) throws SVParseException { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } } package net . sf . sveditor . core . tests . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import junit . framework . TestCase ; public class TestParserErrorRecovery extends TestCase { public void testModuleScopeError ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = SVDBTestUtils . parse ( log , content , "" , markers ) ; assertEquals ( , markers . size ( ) ) ; SVDBTestUtils . assertFileHasElements ( file , new String [ ] { "" , "" , "" , "" } ) ; LogFactory . removeLogHandle ( log ) ; } public void testClassScopeError ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = SVDBTestUtils . parse ( log , content , "" , markers ) ; assertEquals ( , markers . size ( ) ) ; SVDBTestUtils . assertFileHasElements ( file , new String [ ] { "" , "" , "" , "" } ) ; LogFactory . removeLogHandle ( log ) ; } public void EXP_FAIL_testTFScopeError ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = SVDBTestUtils . parse ( log , content , "" , markers ) ; assertEquals ( , markers . size ( ) ) ; SVDBTestUtils . assertFileHasElements ( file , new String [ ] { "" , "" , "" , "" } ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import junit . framework . TestCase ; public class TestParseInterfaceBodyItems extends TestCase { public void testModportBasic ( ) throws SVParseException { String doc = "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testModportMethod ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testInterfaceWithParam ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testInterfaceModportTypeField ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , content , new String [ ] { "" , "" } ) ; } public void testTypeParameters ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , content , new String [ ] { "" } ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . parser . SVParseException ; import junit . framework . TestCase ; public class TestParseAssertions extends TestCase { public void testOvmXbusAssertions ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; ParserTests . runTest ( "" , "" , new String [ ] { "" } ) ; } public void testOvmXbusAssertions_repetition ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; ParserTests . runTest ( "" , "" , new String [ ] { "" } ) ; } public void testBasicProperties ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; ParserTests . runTest ( "" , "" , new String [ ] { "" } ) ; } public void testSavedValueProperty ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; ParserTests . runTest ( "" , "" , new String [ ] { "" , "" } ) ; } public void testPropertyDisableIffIf ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } public void testPropertyCaseStmt ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } } package net . sf . sveditor . core . tests . parser ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestParseDataTypes extends TestCase { public void testTypedefVirtual ( ) throws SVParseException { LogHandle log = LogFactory . getLogHandle ( "" ) ; String testname = "" ; String content = "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , content , new String [ ] { "" , "" } ) ; LogFactory . removeLogHandle ( log ) ; } public void testScopedTypeCast ( ) throws SVParseException { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" ; ParserTests . runTestStrDoc ( testname , content , new String [ ] { "" , "" } ) ; LogFactory . removeLogHandle ( log ) ; } public void testTypedefEnumFwdDecl ( ) throws SVParseException { String content = "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testEnumVarTFScope ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testStructVarTFScope ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testMultiDimArrayDecl ( ) throws SVParseException { String content = "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testMultiDimWireArrayDecl ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" , "" , "" } ) ; } public void testPackedEnumArrayDecl ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" , "" , "" } ) ; } public void testVirtualInterfaceParameterizedClass ( ) throws SVParseException { String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" } ) ; } public void testVirtualInterfaceClassParam ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" ; runTest ( "" , content , new String [ ] { "" } ) ; } public void testStructPackedSignedUnsigned ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" } ) ; } public void testUnionTaggedUntagged ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" } ) ; } public void testIntAssignPackedStruct ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" } ) ; } public void testIntAssignPackedStructFieldQualified ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" } ) ; } public void testTimeUnits ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; } public void testAssocArrayInit ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" , "" } ) ; } public void testBeginBlockVirtualIfcDecl ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" , "" } ) ; } private void runTest ( String testname , String doc , String exp_items [ ] ) { SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; } } package net . sf . sveditor . core . tests . parser ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import junit . framework . TestCase ; public class TestParseExpr extends TestCase { public void testTimeUnits ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; } public void testStreamOperators ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" } ) ; } public void testStreamOperators2 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" , "" } ) ; } public void testStreamOperators3 ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testStringEmbeddedBackslashes ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testStringEmbeddedComment ( ) throws SVParseException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" } ) ; } public void testTFCallWithUnspecifiedParams ( ) throws SVParseException { String testname = "" ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" , "" } ) ; } public void testDelayExpressionTrailingAND ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testDelayArrayRefExpr ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testWireAssignMacroExpr ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testWireAssignMiscOperators ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testConcatTernaryStringExpr ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testAssignTLeftShift ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testAssignTRightShift ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testAssignBitSelect ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testDelayControlAdjacentBasedNumber ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" } ) ; } public void testInlineDistConstraint ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } public void testNewExprCall ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( testname , content , new String [ ] { "" , "" } ) ; } private void runTest ( String testname , String doc , String exp_items [ ] ) { List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVDBFile file = SVDBTestUtils . parse ( log , doc , testname , markers ) ; for ( SVDBMarker m : markers ) { log . debug ( "" + m . getMessage ( ) ) ; } assertEquals ( , markers . size ( ) ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . parser . SVParseException ; import junit . framework . TestCase ; public class TestParseBind extends TestCase { public void testBasicBind ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } public void testHierarchicalBind ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } public void testTypedHierarchicalBind ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } public void testLRMEx1 ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } public void testLRMEx2 ( ) throws SVParseException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" ; ParserTests . runTestStrDoc ( testname , doc , new String [ ] { "" } ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import junit . framework . TestCase ; public class TestParseTopLevelItems extends TestCase { public void testTimePrecisionUnits ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" , "" , "" } ) ; } public void testOvmPrinter ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; runTest ( "" , content , new String [ ] { "" } ) ; } private void runTest ( String testname , String doc , String exp_items [ ] ) { SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; } } package net . sf . sveditor . core . tests . parser ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import junit . framework . TestCase ; public class TestTypeDeclarations extends TestCase { public void testParameterizedFieldType ( ) { String content = "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; } public void testParameterizedFieldTypeInit ( ) { String content = "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; } public void testParameterizedFieldTypeStaticInit ( ) { String content = "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; } public void testTypeParameterizedClass ( ) { testTypeCastInFunction ( "" ) ; } public void testBuiltinTypeCast ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; testTypeCastInFunction ( "" ) ; } public void testIntegralTypeCast ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; testTypeCastInFunction ( "" ) ; } public void testVoidCast ( ) { testTypeCastInFunction ( "" ) ; } public void testConstTypeCast ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; testTypeCastInFunction ( "" ) ; } public void testParameterizedFieldInit ( ) { String content = "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; } public void testAssociativeArrayInit ( ) { String content = "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" , "" ) ; } protected void testTypeCastInFunction ( String castExpresson ) { String content = "" + "" + castExpresson + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( content , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; } } package net . sf . sveditor . core . tests . parser . perf ; import java . io . File ; import java . net . URL ; import junit . framework . TestCase ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestParserPerf extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; } public void testXBusExample ( ) { String cls_path = "" ; URL plugin_class = getClass ( ) . getClassLoader ( ) . getResource ( cls_path ) ; System . out . println ( "" + plugin_class . toExternalForm ( ) ) ; String path = plugin_class . toExternalForm ( ) ; path = path . substring ( "" . length ( ) ) ; path = path . substring ( , path . length ( ) - ( cls_path . length ( ) + "" . length ( ) ) ) ; String ovm_dir = path + "" ; String xbus = ovm_dir + "" ; SVDBIndexRegistry rgy = new SVDBIndexRegistry ( true ) ; SVDBArgFileIndexFactory factory = new SVDBArgFileIndexFactory ( ) ; rgy . test_init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; String compile_questa_sv = xbus + "" ; System . out . println ( "" + compile_questa_sv ) ; ISVDBIndex index = rgy . findCreateIndex ( "" , compile_questa_sv , SVDBArgFileIndexFactory . TYPE , factory , null ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; } public void testUVMPreProc ( ) { String cls_path = "" ; URL plugin_class = getClass ( ) . getClassLoader ( ) . getResource ( cls_path ) ; System . out . println ( "" + plugin_class . toExternalForm ( ) ) ; String path = plugin_class . toExternalForm ( ) ; path = path . substring ( "" . length ( ) ) ; path = path . substring ( , path . length ( ) - ( cls_path . length ( ) + "" . length ( ) ) ) ; File uvm_zip = new File ( new File ( path ) , "" ) ; TestUtils . unpackZipToFS ( uvm_zip , fTmpDir ) ; SVDBIndexRegistry rgy = new SVDBIndexRegistry ( true ) ; SVDBLibPathIndexFactory factory = new SVDBLibPathIndexFactory ( ) ; rgy . test_init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; File uvm = new File ( fTmpDir , "" ) ; File uvm_pkg = new File ( uvm , "" ) ; System . out . println ( "" + uvm_pkg . getAbsolutePath ( ) ) ; ISVDBIndex index = rgy . findCreateIndex ( "" , uvm_pkg . getAbsolutePath ( ) , SVDBLibPathIndexFactory . TYPE , factory , null ) ; long fullparse_start = System . currentTimeMillis ( ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; long fullparse_end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( fullparse_end - fullparse_start ) ) ; } public void testOpenSparc ( ) { File opensparc_design = new File ( "" ) ; SVDBIndexRegistry rgy = new SVDBIndexRegistry ( true ) ; SVDBArgFileIndexFactory factory = new SVDBArgFileIndexFactory ( ) ; rgy . test_init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; ISVDBIndex index = rgy . findCreateIndex ( "" , opensparc_design . getAbsolutePath ( ) , SVDBArgFileIndexFactory . TYPE , factory , null ) ; long fullparse_start = System . currentTimeMillis ( ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; long fullparse_end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( fullparse_end - fullparse_start ) ) ; } } package net . sf . sveditor . core . tests . parser ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import junit . framework . TestSuite ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . parser . SVParseException ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class ParserTests extends TestSuite { public static TestSuite suite ( ) { TestSuite s = new TestSuite ( "" ) ; s . addTest ( new TestSuite ( TestLexer . class ) ) ; s . addTest ( new TestSuite ( TestParseBehavioralStmts . class ) ) ; s . addTest ( new TestSuite ( TestParseClassBodyItems . class ) ) ; s . addTest ( new TestSuite ( TestParseConfigurations . class ) ) ; s . addTest ( new TestSuite ( TestParseDataTypes . class ) ) ; s . addTest ( new TestSuite ( TestParseExpr . class ) ) ; s . addTest ( new TestSuite ( TestParseFunction . class ) ) ; s . addTest ( new TestSuite ( TestParseInterfaceBodyItems . class ) ) ; s . addTest ( new TestSuite ( TestParseLineNumbers . class ) ) ; s . addTest ( new TestSuite ( TestParseModuleBodyItems . class ) ) ; s . addTest ( new TestSuite ( TestParseSpecify . class ) ) ; s . addTest ( new TestSuite ( TestParseProgramBlocks . class ) ) ; s . addTest ( new TestSuite ( TestParserErrorRecovery . class ) ) ; s . addTest ( new TestSuite ( TestParseStruct . class ) ) ; s . addTest ( new TestSuite ( TestParseTopLevelItems . class ) ) ; s . addTest ( new TestSuite ( TestSystemParse . class ) ) ; s . addTest ( new TestSuite ( TestTypeDeclarations . class ) ) ; s . addTest ( new TestSuite ( TestParserSVStdExamples . class ) ) ; s . addTest ( new TestSuite ( TestParseAssertions . class ) ) ; s . addTest ( new TestSuite ( TestParseBind . class ) ) ; s . addTest ( new TestSuite ( TestParseCovergroups . class ) ) ; return s ; } public static void runTest ( String testname , String data , String exp_items [ ] ) throws SVParseException { LogHandle log = LogFactory . getLogHandle ( testname ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; InputStream in = null ; try { URL url = SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) . getEntry ( data ) ; in = url . openStream ( ) ; } catch ( IOException e ) { TestCase . fail ( "" + data + "" + e . getMessage ( ) ) ; } SVDBFile file = SVDBTestUtils . parse ( log , in , data , markers ) . second ( ) ; try { in . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } TestCase . assertEquals ( , markers . size ( ) ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; LogFactory . removeLogHandle ( log ) ; } public static void runTestStrDoc ( String testname , String doc , String exp_items [ ] ) { List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVDBFile file = SVDBTestUtils . parse ( log , doc , testname , markers ) ; for ( SVDBMarker m : markers ) { log . debug ( "" + m . getMessage ( ) ) ; } TestCase . assertEquals ( , markers . size ( ) ) ; SVDBTestUtils . assertFileHasElements ( file , exp_items ) ; } } package net . sf . sveditor . core . tests ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import net . sf . sveditor . core . StringInputStream ; public class TextTagPosUtils { private ByteArrayOutputStream fStrippedData ; private Map < String , Integer > fPosMap ; private Map < String , Integer > fLineMap ; private int fUngetCh ; private int fLastCh ; private int fLineno ; private int fPos ; private InputStream fInputStream ; public TextTagPosUtils ( InputStream in ) { fInputStream = in ; fPosMap = new HashMap < String , Integer > ( ) ; fLineMap = new HashMap < String , Integer > ( ) ; fStrippedData = new ByteArrayOutputStream ( ) ; process ( ) ; } public TextTagPosUtils ( String in ) { this ( new StringInputStream ( in ) ) ; } public Map < String , Integer > getPosMap ( ) { return fPosMap ; } public int getTagPos ( String tag ) { if ( ! fPosMap . containsKey ( tag ) ) { return - ; } else { return fPosMap . get ( tag ) ; } } public Map < String , Integer > getLineMap ( ) { return fLineMap ; } public InputStream openStream ( ) { return new ByteArrayInputStream ( fStrippedData . toByteArray ( ) ) ; } public String getStrippedData ( ) { return fStrippedData . toString ( ) ; } private void process ( ) { fUngetCh = - ; fLastCh = - ; fLineno = ; fPos = ; int ch , ch2 ; StringBuilder tmp = new StringBuilder ( ) ; do { while ( ( ch = get_ch ( ) ) != - && ch != '' ) { fStrippedData . write ( ( char ) ch ) ; } ch2 = - ; if ( ch == '' && ( ch2 = get_ch ( ) ) == '' ) { tmp . setLength ( ) ; tmp . append ( ( char ) ch ) ; tmp . append ( ( char ) ch2 ) ; while ( ( ch = get_ch ( ) ) != - && Character . isJavaIdentifierPart ( ch ) ) { tmp . append ( ( char ) ch ) ; } ch2 = - ; if ( ch == '>' && ( ch2 = get_ch ( ) ) == '>' ) { String tag = tmp . substring ( ) ; fPos -= ( tmp . length ( ) + ) ; fPosMap . put ( tag , fPos ) ; fLineMap . put ( tag , fLineno ) ; } else { for ( int i = ; i < tmp . length ( ) ; i ++ ) { fStrippedData . write ( tmp . charAt ( i ) ) ; } fStrippedData . write ( ( char ) ch ) ; unget_ch ( ch2 ) ; } } else { unget_ch ( ch2 ) ; if ( ch != - ) { fStrippedData . write ( ( char ) ch ) ; } } } while ( ch != - ) ; } private int get_ch ( ) { int ret = - ; if ( fUngetCh != - ) { ret = fUngetCh ; fUngetCh = - ; fLastCh = - ; } else { try { ret = fInputStream . read ( ) ; } catch ( IOException e ) { } if ( fLastCh == '' ) { fLineno ++ ; } fLastCh = ret ; fPos ++ ; } return ret ; } private void unget_ch ( int ch ) { fUngetCh = ch ; } } package net . sf . sveditor . core . tests . docs ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import junit . framework . TestCase ; import net . sf . sveditor . core . docs . DocCommentParser ; import net . sf . sveditor . core . docs . DocTopicManager ; import net . sf . sveditor . core . docs . IDocCommentParser ; import net . sf . sveditor . core . docs . IDocTopicManager ; import net . sf . sveditor . core . docs . model . DocTopic ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class TestParser extends TestCase { boolean fDebug = false ; private LogHandle fLog ; public TestParser ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } public void testEmptyClassTopic ( ) throws Exception { String commentLines [ ] = { "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testSimplClassTopic ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testSimplClassTopicWithHeaderLine ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" + "" + "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testClassTopicWithMultiParagraphs ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testClassTopicWithList ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testDefinitionList ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testBold ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testItalics ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testBoldMultiWord ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testUnderline ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testUnderlineMultiWord ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testUnderlineMultiWordWithWS ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testClassTopicWithCodeBlock ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" + "" + "" + "" + "" + "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testClassTopicWithCodeBlockCarrot ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classDocTopic = new DocTopic ( "" , "" , "" ) ; classDocTopic . setBody ( "" + "" + "" + "" + "" + "" ) ; classDocTopic . setSummary ( "" ) ; expTopics . add ( classDocTopic ) ; runTest ( commentLines , expTopics ) ; } public void testTitleAndClasses ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic titleTopic = new DocTopic ( "" , "" , "" ) ; titleTopic . setBody ( "" ) ; titleTopic . setSummary ( "" ) ; expTopics . add ( titleTopic ) ; expTopics . add ( new DocTopic ( "" , "" , "" ) ) ; expTopics . add ( new DocTopic ( "" , "" , "" ) ) ; runTest ( commentLines , expTopics ) ; } public void testBasicLink ( ) throws Exception { String commentLines [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; Set < DocTopic > expTopics = new HashSet < DocTopic > ( ) ; DocTopic classA = new DocTopic ( "" , "" , "" ) ; classA . setBody ( "" + "" + "" ) ; classA . setSummary ( "" ) ; expTopics . add ( classA ) ; expTopics . add ( new DocTopic ( "" , "" , "" ) ) ; runTest ( commentLines , expTopics ) ; } private void runTest ( String commentLines [ ] , Set < DocTopic > expTopics ) throws Exception { if ( fDebug ) { logComment ( "" , commentLines ) ; } IDocTopicManager docTopicMgr = new DocTopicManager ( ) ; IDocCommentParser parser = new DocCommentParser ( docTopicMgr ) ; List < DocTopic > actDocTopics = new ArrayList < DocTopic > ( ) ; parser . parseComment ( commentLines , actDocTopics ) ; for ( DocTopic expTopic : expTopics ) { DocTopic actTopic = null ; for ( DocTopic topic : actDocTopics ) { if ( topic . getTitle ( ) . equals ( expTopic . getTitle ( ) ) ) { actTopic = topic ; actDocTopics . remove ( topic ) ; if ( fDebug ) { logBody ( "" , expTopic . getBody ( ) ) ; logBody ( "" , actTopic . getBody ( ) ) ; logBody ( "" , expTopic . getSummary ( ) ) ; logBody ( "" , actTopic . getSummary ( ) ) ; } assertEquals ( "" + expTopic . getTitle ( ) + "" , expTopic . getBody ( ) , actTopic . getBody ( ) ) ; assertEquals ( "" + expTopic . getTitle ( ) + "" , expTopic . getSummary ( ) , actTopic . getSummary ( ) ) ; break ; } } assertNotNull ( "" + expTopic . getTitle ( ) + "" , actTopic ) ; } assertTrue ( "" , actDocTopics . size ( ) == ) ; } private void logBody ( String msg , String body ) { fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + msg ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , body ) ; } private void logComment ( String msg , String [ ] lines ) { fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + msg ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; for ( int lineNum = ; lineNum < lines . length ; lineNum ++ ) { fLog . debug ( ILogLevel . LEVEL_OFF , String . format ( "" , lineNum ) + lines [ lineNum ] + "" ) ; } } } package net . sf . sveditor . core . tests . docs ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . search . SVDBFindPackageMatcher ; import net . sf . sveditor . core . docs . DocGenConfig ; import net . sf . sveditor . core . docs . model . DocModel ; import net . sf . sveditor . core . docs . model . DocModelFactory ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import difflib . * ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestModelFactory extends TestCase { boolean fDebug = false ; private LogHandle fLog ; private File fTmpDir ; private IProject fProject ; public TestModelFactory ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTmpDir = TestUtils . createTempDir ( ) ; fProject = null ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . save_state ( ) ; if ( fProject != null && ! fDebug ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) && ! fDebug ) { TestUtils . delete ( fTmpDir ) ; } } public void testUVM ( ) throws IOException { String test_name = "" ; String bundle_dir_name = "" ; String test_bundle_dir = "" + bundle_dir_name ; doTestUVMExample ( test_name , bundle_dir_name , test_bundle_dir ) ; } public void doTestUVMExample ( String testName , String bundleDirName , String testBundleDir ) throws IOException { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; LogHandle log = LogFactory . getLogHandle ( testName ) ; File testDir = new File ( fTmpDir , testName ) ; File projDir = testDir ; File cpBundleDir = new File ( testDir , bundleDirName ) ; File listFile = new File ( cpBundleDir , "" ) ; testDir . mkdirs ( ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + testName ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + testBundleDir ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + testDir . getPath ( ) ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + cpBundleDir . getPath ( ) ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + projDir . getPath ( ) ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + listFile . getPath ( ) ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fProject = TestUtils . createProject ( testName , projDir ) ; utils . unpackBundleZipToFS ( "" , testDir ) ; utils . copyBundleDirToWS ( testBundleDir , fProject ) ; File db = new File ( fTmpDir , "" ) ; if ( db . exists ( ) ) { db . delete ( ) ; } SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , listFile . toString ( ) , SVDBArgFileIndexFactory . TYPE , null ) ; index . loadIndex ( new NullProgressMonitor ( ) ) ; DocGenConfig cfg = new DocGenConfig ( ) ; Map < String , Tuple < SVDBDeclCacheItem , ISVDBIndex > > pkgMap = new HashMap < String , Tuple < SVDBDeclCacheItem , ISVDBIndex > > ( ) ; List < ISVDBIndex > projIndexList = rgy . getAllProjectLists ( ) ; for ( ISVDBIndex svdbIndex : projIndexList ) { List < SVDBDeclCacheItem > foundPkgs = svdbIndex . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindPackageMatcher ( ) ) ; for ( SVDBDeclCacheItem pkg : foundPkgs ) { if ( ! pkgMap . containsKey ( pkg . getName ( ) ) ) { pkgMap . put ( pkg . getName ( ) , new Tuple < SVDBDeclCacheItem , ISVDBIndex > ( pkg , svdbIndex ) ) ; } } } Set < Tuple < SVDBDeclCacheItem , ISVDBIndex > > pkgs = new HashSet < Tuple < SVDBDeclCacheItem , ISVDBIndex > > ( pkgMap . values ( ) ) ; cfg . setSelectedPackages ( pkgs ) ; if ( fDebug ) SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; DocModelFactory factory = new DocModelFactory ( ) ; DocModel model = factory . build ( cfg ) ; File modelDumpPathAct = new File ( testDir , "" ) ; File modelDumpPathExp = new File ( cpBundleDir , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + modelDumpPathAct ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + modelDumpPathExp ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + modelDumpPathExp + "" + modelDumpPathAct ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + modelDumpPathExp + "" + modelDumpPathAct ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + modelDumpPathAct + "" + "" + testBundleDir + "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; FileWriter fw = new FileWriter ( modelDumpPathAct . getPath ( ) ) ; BufferedWriter bw = new BufferedWriter ( fw ) ; model . dumpToFile ( bw ) ; bw . close ( ) ; fw . close ( ) ; List < String > expLines = TestUtils . fileToLines ( modelDumpPathExp . getPath ( ) ) ; List < String > actLines = TestUtils . fileToLines ( modelDumpPathAct . getPath ( ) ) ; Patch patch = DiffUtils . diff ( expLines , actLines ) ; List < Delta > deltas = patch . getDeltas ( ) ; assertTrue ( String . format ( "" , deltas . size ( ) , modelDumpPathExp . toString ( ) , modelDumpPathAct . toString ( ) ) , deltas . size ( ) == ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . docs ; import junit . framework . TestSuite ; public class DocsTests extends TestSuite { public static TestSuite suite ( ) { TestSuite s = new TestSuite ( "" ) ; s . addTest ( new TestSuite ( TestCleaner . class ) ) ; s . addTest ( new TestSuite ( TestParser . class ) ) ; s . addTest ( new TestSuite ( TestModelFactory . class ) ) ; s . addTest ( new TestSuite ( TestFindDocComments . class ) ) ; return s ; } } package net . sf . sveditor . core . tests . docs ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBDocComment ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . search . SVDBFindDocComment ; import net . sf . sveditor . core . db . search . SVDBFindNamedClass ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestFindDocComments extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; File db = new File ( fTmpDir , "" ) ; assertTrue ( db . mkdirs ( ) ) ; rgy . init ( new TestIndexCacheFactory ( db ) ) ; } @ Override protected void tearDown ( ) throws Exception { if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir != null && fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testFindUvmReportObject ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; utils . unpackBundleZipToFS ( "" , fTmpDir ) ; File uvm = new File ( fTmpDir , "" ) ; File uvm_report_object_svh = new File ( uvm , "" ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; Tuple < SVDBFile , SVDBFile > file = SVDBTestUtils . parse ( log , uvm_report_object_svh , markers ) ; assertNotNull ( file ) ; FileIndexIterator index_it = new FileIndexIterator ( file ) ; SVDBFindNamedClass finder = new SVDBFindNamedClass ( index_it ) ; List < SVDBClassDecl > result = finder . find ( "" ) ; assertTrue ( result . size ( ) == ) ; SVDBClassDecl uvm_report_object = result . get ( ) ; SVDBFindDocComment comment_finder = new SVDBFindDocComment ( index_it ) ; SVDBDocComment comment = comment_finder . find ( new NullProgressMonitor ( ) , uvm_report_object ) ; assertNotNull ( comment ) ; } } package net . sf . sveditor . core . tests . docs ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBDocComment ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . docs . DocCommentCleaner ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestCleaner extends TestCase { boolean fDebug = false ; private LogHandle fLog ; public TestCleaner ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } public void testBoxRemoval ( ) throws Exception { String comment [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; String cleanedContent [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; runTest ( "" , comment , cleanedContent ) ; } public void testLeadingCommentMarkRemoval ( ) throws Exception { String comment [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; String cleanedContent [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; runTest ( "" , comment , cleanedContent ) ; } public void testLeadingCommentMarkRemovalButNotCodeBlock ( ) throws Exception { String comment [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; String cleanedContent [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; runTest ( "" , comment , cleanedContent ) ; } public void testCodeBlockNotRemoved ( ) throws Exception { String comment [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; String cleanedContent [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; runTest ( "" , comment , cleanedContent ) ; } public void testSVPreProc_1 ( ) throws Exception { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , SVDBFile > r = SVDBTestUtils . parsePreProc ( doc , testname , false ) ; SVDBFile pp_file = r . first ( ) ; SVDBDocComment dc = null ; for ( ISVDBChildItem c : pp_file . getChildren ( ) ) { if ( c . getType ( ) == SVDBItemType . DocComment ) { dc = ( SVDBDocComment ) c ; } } assertNotNull ( dc ) ; assertTrue ( dc . getRawComment ( ) . contains ( "" ) ) ; } public void testSVPreProc_2 ( ) throws Exception { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , SVDBFile > r = SVDBTestUtils . parsePreProc ( doc , testname , false ) ; SVDBFile pp_file = r . first ( ) ; SVDBDocComment dc = null ; for ( ISVDBChildItem c : pp_file . getChildren ( ) ) { if ( c . getType ( ) == SVDBItemType . DocComment ) { dc = ( SVDBDocComment ) c ; } } assertNotNull ( dc ) ; assertTrue ( dc . getRawComment ( ) . contains ( "" ) ) ; } public void testSVPreProc_3 ( ) throws Exception { String testname = "" ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Tuple < SVDBFile , SVDBFile > r = SVDBTestUtils . parsePreProc ( doc , testname , false ) ; SVDBFile pp_file = r . first ( ) ; SVDBDocComment dc = null ; for ( ISVDBChildItem c : pp_file . getChildren ( ) ) { if ( c . getType ( ) == SVDBItemType . DocComment ) { dc = ( SVDBDocComment ) c ; } } assertNotNull ( dc ) ; assertTrue ( dc . getRawComment ( ) . contains ( "" ) ) ; assertTrue ( dc . getRawComment ( ) . contains ( "" ) ) ; assertTrue ( dc . getRawComment ( ) . contains ( "" ) ) ; assertTrue ( dc . getRawComment ( ) . contains ( "" ) ) ; } private void runTest ( String string , String comment [ ] , String expCleanedComment [ ] ) throws Exception { SVCorePlugin . getDefault ( ) . enableDebug ( fDebug ) ; if ( comment . length != expCleanedComment . length ) { throw ( new Exception ( "" + comment . length + "" + "" + expCleanedComment . length + "" ) ) ; } if ( fDebug ) { logComment ( "" , comment ) ; logComment ( "" , expCleanedComment ) ; } DocCommentCleaner . clean ( comment ) ; if ( fDebug ) { logComment ( "" , comment ) ; } for ( int lineNum = ; lineNum < comment . length ; lineNum ++ ) { assertEquals ( String . format ( "" , lineNum ) , expCleanedComment [ lineNum ] , comment [ lineNum ] ) ; } } private void logComment ( String msg , String [ ] lines ) { fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" + msg ) ; fLog . debug ( ILogLevel . LEVEL_OFF , "" ) ; for ( int lineNum = ; lineNum < lines . length ; lineNum ++ ) { fLog . debug ( ILogLevel . LEVEL_OFF , String . format ( "" , lineNum ) + lines [ lineNum ] + "" ) ; } } } package net . sf . sveditor . core . tests . utils ; import java . io . BufferedOutputStream ; import java . io . BufferedReader ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . FileReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . URI ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . LinkedList ; import java . util . List ; import java . util . zip . ZipEntry ; import java . util . zip . ZipInputStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . osgi . framework . Bundle ; public class TestUtils { private static byte [ ] fTmp ; static { fTmp = new byte [ * ] ; } public static File createTempDir ( ) { File tmpdir = new File ( System . getProperty ( "" ) ) ; File ret = null ; for ( int i = ; i < ; i ++ ) { File try_dir = new File ( tmpdir , "" + i ) ; if ( ! try_dir . exists ( ) ) { ret = try_dir ; if ( ! ret . mkdirs ( ) ) { System . out . println ( "" ) ; } break ; } } return ret ; } public static void unpackZipToFS ( File zipfile_path , File fs_path ) { if ( ! fs_path . isDirectory ( ) ) { TestCase . assertTrue ( fs_path . mkdirs ( ) ) ; } try { InputStream in = new FileInputStream ( zipfile_path ) ; TestCase . assertNotNull ( in ) ; byte tmp [ ] = new byte [ * ] ; int cnt ; ZipInputStream zin = new ZipInputStream ( in ) ; ZipEntry ze ; while ( ( ze = zin . getNextEntry ( ) ) != null ) { File entry_f = new File ( fs_path , ze . getName ( ) ) ; if ( ze . getName ( ) . endsWith ( "" ) ) { continue ; } if ( ! entry_f . getParentFile ( ) . exists ( ) ) { TestCase . assertTrue ( entry_f . getParentFile ( ) . mkdirs ( ) ) ; } FileOutputStream fos = new FileOutputStream ( entry_f ) ; BufferedOutputStream bos = new BufferedOutputStream ( fos , tmp . length ) ; while ( ( cnt = zin . read ( tmp , , tmp . length ) ) > ) { bos . write ( tmp , , cnt ) ; } bos . flush ( ) ; bos . close ( ) ; fos . close ( ) ; zin . closeEntry ( ) ; } zin . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; TestCase . fail ( "" + e . getMessage ( ) ) ; } } public static String readInput ( InputStream in ) { StringBuilder sb = new StringBuilder ( ) ; byte tmp [ ] = new byte [ ] ; int len ; try { while ( ( len = in . read ( tmp , , tmp . length ) ) > ) { sb . append ( new String ( tmp , , len ) ) ; } } catch ( IOException e ) { } return sb . toString ( ) ; } public static void delete ( File item ) { if ( item . isDirectory ( ) ) { for ( File i : item . listFiles ( ) ) { delete ( i ) ; } } if ( item . exists ( ) && ! item . delete ( ) ) { if ( item . isDirectory ( ) ) { TestCase . fail ( "" + item . getAbsolutePath ( ) + "" ) ; } else { TestCase . fail ( "" + item . getAbsolutePath ( ) + "" ) ; } } } public static void copy ( ByteArrayOutputStream in , File out ) { try { OutputStream out_s = new FileOutputStream ( out ) ; InputStream in_s = new ByteArrayInputStream ( in . toByteArray ( ) ) ; int len ; do { len = in_s . read ( fTmp , , fTmp . length ) ; if ( len > ) { out_s . write ( fTmp , , len ) ; } } while ( len > ) ; out_s . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( "" + out + "" ) ; } } public static void copy ( ByteArrayOutputStream in , IFile out ) { try { InputStream in_s = new ByteArrayInputStream ( in . toByteArray ( ) ) ; if ( out . exists ( ) ) { out . setContents ( in_s , true , false , new NullProgressMonitor ( ) ) ; } else { out . create ( in_s , true , new NullProgressMonitor ( ) ) ; } } catch ( Exception e ) { throw new RuntimeException ( "" + out + "" ) ; } } public static IProject createProject ( String name ) { return createProject ( name , null ) ; } public static IProject setupIndexWSProject ( Bundle bundle , File tmpdir , String name , String data_file ) { if ( bundle == null ) { bundle = SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ; } BundleUtils utils = new BundleUtils ( bundle ) ; IProject project = TestUtils . createProject ( name , new File ( tmpdir , name ) ) ; if ( data_file . endsWith ( "" ) ) { TestCase . fail ( "" ) ; utils . copyBundleDirToWS ( data_file , project ) ; } else { utils . copyBundleDirToWS ( data_file , project ) ; } File db = new File ( tmpdir , "" ) ; if ( db . exists ( ) ) { TestUtils . delete ( db ) ; } TestCase . assertTrue ( db . mkdirs ( ) ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( db ) ) ; return project ; } public static IProject createProject ( String name , File path ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; URI location = null ; if ( path != null ) { location = path . toURI ( ) ; } IProject project = root . getProject ( name ) ; try { if ( project . exists ( ) ) { project . close ( new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { e . printStackTrace ( ) ; } try { if ( project . exists ( ) ) { project . delete ( true , true , new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "" + e . getMessage ( ) ) ; } try { IProjectDescription desc = project . getWorkspace ( ) . newProjectDescription ( name ) ; desc . setLocationURI ( location ) ; project . create ( desc , new NullProgressMonitor ( ) ) ; if ( ! project . isOpen ( ) ) { project . open ( new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "" + e . getMessage ( ) ) ; } return project ; } public static void deleteProject ( IProject project_dir ) { try { project_dir . close ( new NullProgressMonitor ( ) ) ; project_dir . delete ( true , true , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } } public static void assertContains ( List < String > list , String ... expected ) { List < String > temp = new ArrayList < String > ( ) ; temp . addAll ( list ) ; for ( String exp : expected ) { if ( temp . contains ( exp ) ) { temp . remove ( exp ) ; } else { TestCase . fail ( "" + exp + "" ) ; } } if ( temp . size ( ) > ) { StringBuilder leftovers = new StringBuilder ( ) ; for ( String l : temp ) { leftovers . append ( l ) ; leftovers . append ( "" ) ; } TestCase . fail ( "" + leftovers + "" ) ; } } public static < T > HashSet < T > newHashSet ( T ... objs ) { HashSet < T > set = new HashSet < T > ( ) ; for ( T o : objs ) { set . add ( o ) ; } return set ; } public static List < String > fileToLines ( String filename ) throws IOException { List < String > lines = new LinkedList < String > ( ) ; String line = "" ; @ SuppressWarnings ( "" ) BufferedReader in = new BufferedReader ( new FileReader ( filename ) ) ; while ( ( line = in . readLine ( ) ) != null ) { lines . add ( line ) ; } return lines ; } public static IProject importProject ( File project ) { IProjectDescription pd = null ; IWorkspace ws = ResourcesPlugin . getWorkspace ( ) ; IWorkspaceRoot root = ws . getRoot ( ) ; try { pd = ws . loadProjectDescription ( new Path ( new File ( project , "" ) . getAbsolutePath ( ) ) ) ; } catch ( CoreException e ) { TestCase . fail ( "" + project . getAbsolutePath ( ) + "" + e . getMessage ( ) ) ; } IProject p = root . getProject ( pd . getName ( ) ) ; try { p . create ( pd , null ) ; p . open ( null ) ; } catch ( CoreException e ) { TestCase . fail ( "" + project . getAbsolutePath ( ) + "" + e . getMessage ( ) ) ; } return p ; } } package net . sf . sveditor . core . tests . utils ; import java . io . BufferedOutputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . util . Enumeration ; import java . util . zip . ZipEntry ; import java . util . zip . ZipInputStream ; import junit . framework . TestCase ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . osgi . framework . Bundle ; public class BundleUtils { private Bundle fBundle ; public BundleUtils ( Bundle bundle ) { fBundle = bundle ; } public void copyBundleFileToFS ( String bundle_file , File fs_path ) throws IOException { URL url = fBundle . getEntry ( bundle_file ) ; byte tmp [ ] = new byte [ * ] ; if ( ! fs_path . exists ( ) ) { fs_path . mkdirs ( ) ; } FileOutputStream out = new FileOutputStream ( new File ( fs_path , new File ( bundle_file ) . getName ( ) ) ) ; InputStream in = url . openStream ( ) ; int len ; do { len = in . read ( tmp , , tmp . length ) ; if ( len > ) { out . write ( tmp , , len ) ; } } while ( len > ) ; out . close ( ) ; in . close ( ) ; } @ SuppressWarnings ( "" ) public void copyBundleDirToFS ( String bundle_dir , File fs_path ) { Enumeration entries = fBundle . findEntries ( bundle_dir , "" , true ) ; byte tmp [ ] = new byte [ * ] ; String dirname = new File ( bundle_dir ) . getName ( ) ; fs_path = new File ( fs_path , dirname ) ; while ( entries . hasMoreElements ( ) ) { URL url = ( URL ) entries . nextElement ( ) ; if ( url . getPath ( ) . endsWith ( "" ) ) { continue ; } String file_subpath = url . getPath ( ) . substring ( bundle_dir . length ( ) ) ; File target = new File ( fs_path , file_subpath ) ; if ( ! target . getParentFile ( ) . exists ( ) ) { if ( ! target . getParentFile ( ) . mkdirs ( ) ) { System . out . println ( "" + target . getParent ( ) + "" ) ; throw new RuntimeException ( "" + target . getParent ( ) + "" ) ; } } try { FileOutputStream out = new FileOutputStream ( target ) ; InputStream in = url . openStream ( ) ; int len ; do { len = in . read ( tmp , , tmp . length ) ; if ( len > ) { out . write ( tmp , , len ) ; } } while ( len > ) ; out . close ( ) ; in . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "" + target ) ; } } } public void unpackBundleZipToFS ( String bundle_path , File fs_path ) { URL zip_url = fBundle . getEntry ( bundle_path ) ; TestCase . assertNotNull ( zip_url ) ; if ( ! fs_path . isDirectory ( ) ) { TestCase . assertTrue ( fs_path . mkdirs ( ) ) ; } try { InputStream in = zip_url . openStream ( ) ; TestCase . assertNotNull ( in ) ; byte tmp [ ] = new byte [ * ] ; int cnt ; ZipInputStream zin = new ZipInputStream ( in ) ; ZipEntry ze ; while ( ( ze = zin . getNextEntry ( ) ) != null ) { File entry_f = new File ( fs_path , ze . getName ( ) ) ; if ( ze . getName ( ) . endsWith ( "" ) ) { continue ; } if ( ! entry_f . getParentFile ( ) . exists ( ) ) { TestCase . assertTrue ( entry_f . getParentFile ( ) . mkdirs ( ) ) ; } FileOutputStream fos = new FileOutputStream ( entry_f ) ; BufferedOutputStream bos = new BufferedOutputStream ( fos , tmp . length ) ; while ( ( cnt = zin . read ( tmp , , tmp . length ) ) > ) { bos . write ( tmp , , cnt ) ; } bos . flush ( ) ; bos . close ( ) ; fos . close ( ) ; zin . closeEntry ( ) ; } zin . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; TestCase . fail ( "" + e . getMessage ( ) ) ; } } public void copyBundleFileToWS ( String bundle_path , IContainer ws_path ) { URL url = fBundle . getEntry ( bundle_path ) ; String bundle_filename = new File ( bundle_path ) . getName ( ) ; IFile target = ws_path . getFile ( new Path ( bundle_filename ) ) ; IContainer parent = target . getParent ( ) ; try { if ( ! parent . exists ( ) ) { createDirTree ( parent ) ; } InputStream in = url . openStream ( ) ; if ( target . exists ( ) ) { target . setContents ( in , true , false , new NullProgressMonitor ( ) ) ; } else { target . create ( in , true , new NullProgressMonitor ( ) ) ; } in . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } @ SuppressWarnings ( "" ) public void copyBundleDirToWS ( String bundle_dir , IContainer ws_path ) { Enumeration entries = fBundle . findEntries ( bundle_dir , "" , true ) ; String dirname = new File ( bundle_dir ) . getName ( ) ; ws_path = ws_path . getFolder ( new Path ( dirname ) ) ; while ( entries . hasMoreElements ( ) ) { URL url = ( URL ) entries . nextElement ( ) ; if ( url . getPath ( ) . endsWith ( "" ) ) { continue ; } String file_subpath = url . getPath ( ) . substring ( bundle_dir . length ( ) ) ; IFile target = ws_path . getFile ( new Path ( file_subpath ) ) ; IFolder parent = ( IFolder ) target . getParent ( ) ; try { if ( ! parent . exists ( ) ) { createDirTree ( parent ) ; } InputStream in = url . openStream ( ) ; if ( target . exists ( ) ) { target . setContents ( in , true , false , new NullProgressMonitor ( ) ) ; } else { target . create ( in , true , new NullProgressMonitor ( ) ) ; } in . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } private void createDirTree ( IContainer dir ) throws CoreException { if ( dir . getParent ( ) != null ) { if ( ! dir . getParent ( ) . exists ( ) ) { createDirTree ( dir . getParent ( ) ) ; } } ( ( IFolder ) dir ) . create ( true , false , new NullProgressMonitor ( ) ) ; } public ByteArrayOutputStream readBundleFile ( String bundle_path ) { URL url = fBundle . getEntry ( bundle_path ) ; ByteArrayOutputStream ret = new ByteArrayOutputStream ( ) ; try { InputStream in = url . openStream ( ) ; byte tmp [ ] = new byte [ * ] ; int len ; do { if ( ( len = in . read ( tmp , , tmp . length ) ) > ) { ret . write ( tmp , , len ) ; } if ( len > ) ; } while ( len > ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } return ret ; } public boolean deleteWSFile ( IContainer parent , String path ) { IFile file = parent . getFile ( new Path ( path ) ) ; try { file . delete ( true , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { return false ; } return true ; } } package net . sf . sveditor . core . tests ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBUtil ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; public class SVScannerTests extends TestCase { public SVScannerTests ( ) { } public void testVariableLists ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String in_data = "" + "" + "" + "" ; String exp [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; int idx = ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = factory . parse ( new StringInputStream ( in_data ) , "" , markers ) ; for ( SVDBMarker m : markers ) { System . out . println ( "" + m . getMessage ( ) ) ; } assertEquals ( , SVDBUtil . getChildrenSize ( file ) ) ; assertTrue ( SVDBUtil . getFirstChildItem ( file ) instanceof SVDBModIfcDecl ) ; SVDBModIfcDecl m = ( SVDBModIfcDecl ) SVDBUtil . getFirstChildItem ( file ) ; assertEquals ( "" , m . getName ( ) ) ; for ( ISVDBChildItem it : m . getChildren ( ) ) { assertTrue ( it instanceof SVDBVarDeclStmt ) ; SVDBVarDeclStmt v = ( SVDBVarDeclStmt ) it ; for ( ISVDBChildItem c : v . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; log . debug ( "" + v . getTypeName ( ) + "" + vi . getName ( ) ) ; assertEquals ( exp [ idx ++ ] , v . getTypeName ( ) ) ; assertEquals ( exp [ idx ++ ] , vi . getName ( ) ) ; } } LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . search ; import junit . framework . TestCase ; public class TestFindReferences extends TestCase { public void testFindExtensionRef ( ) { String content = "" + "" + "" + "" + "" ; } } package net . sf . sveditor . core . tests ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import org . eclipse . core . runtime . Plugin ; import org . osgi . framework . BundleContext ; public class SVCoreTestsPlugin extends Plugin { public static final String PLUGIN_ID = "" ; public static final String OVM_LIBRARY_ID = "" ; public static final String VMM_LIBRARY_ID = "" ; private static SVCoreTestsPlugin plugin ; public SVCoreTestsPlugin ( ) { } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static InputStream openFile ( String path ) { SVCoreTestsPlugin p = getDefault ( ) ; URL url = p . getBundle ( ) . getEntry ( path ) ; InputStream in = null ; if ( url != null ) { try { in = url . openStream ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return in ; } public static String readStream ( InputStream in ) throws IOException { StringBuilder ret = new StringBuilder ( ) ; int ch ; while ( ( ch = in . read ( ) ) != - ) { ret . append ( ( char ) ch ) ; } return ret . toString ( ) ; } public static SVCoreTestsPlugin getDefault ( ) { return plugin ; } } package net . sf . sveditor . core . tests . profile ; import java . io . File ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; public class ProfileIndexLoad { File fTmpDir ; public void testLoadOVM ( String ovm_home ) { String pname = "" ; SVDBIndexCollection mgr = new SVDBIndexCollection ( pname ) ; SVDBIndexRegistry rgy = new SVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( fTmpDir ) ) ; String lib_path = ovm_home + "" ; System . out . println ( "" + lib_path ) ; SVDBLibPathIndexFactory f = new SVDBLibPathIndexFactory ( ) ; ISVDBIndex index = f . createSVDBIndex ( pname , lib_path , null , null ) ; mgr . addLibraryPath ( index ) ; ISVDBItemIterator item_it = mgr . getItemIterator ( new NullProgressMonitor ( ) ) ; int count = ; while ( item_it . hasNext ( ) ) { item_it . nextItem ( ) ; count ++ ; } System . out . println ( "" + count + "" ) ; } public static final void main ( String args [ ] ) { ProfileIndexLoad t = new ProfileIndexLoad ( ) ; t . fTmpDir = TestUtils . createTempDir ( ) ; long start_time = System . currentTimeMillis ( ) ; try { t . testLoadOVM ( args [ ] ) ; } finally { long end_time = System . currentTimeMillis ( ) ; System . out . println ( "" + ( end_time - start_time ) ) ; TestUtils . delete ( t . fTmpDir ) ; } } } package net . sf . sveditor . core . tests ; import java . io . File ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCache ; import net . sf . sveditor . core . db . index . cache . ISVDBIndexCacheFactory ; import net . sf . sveditor . core . db . index . cache . InMemoryIndexCache ; import net . sf . sveditor . core . db . index . cache . SVDBDirFS ; import net . sf . sveditor . core . db . index . cache . SVDBFileIndexCache ; public class TestIndexCacheFactory implements ISVDBIndexCacheFactory { private File fRoot ; public TestIndexCacheFactory ( File dir ) { fRoot = dir ; } public ISVDBIndexCache createIndexCache ( String project_name , String base_location ) { if ( fRoot == null ) { return new InMemoryIndexCache ( ) ; } else { if ( ! fRoot . isDirectory ( ) ) { TestCase . assertTrue ( fRoot . mkdirs ( ) ) ; } String hash = SVFileUtils . computeMD5 ( base_location ) ; File target = new File ( fRoot , project_name + "" + hash ) ; if ( ! target . isDirectory ( ) ) { TestCase . assertTrue ( target . mkdirs ( ) ) ; } SVDBDirFS fs = new SVDBDirFS ( target ) ; fs . setEnableAsyncClear ( false ) ; SVDBFileIndexCache cache = new SVDBFileIndexCache ( fs ) ; return cache ; } } public void compactCache ( List < ISVDBIndexCache > cache_list ) { } public static TestIndexCacheFactory instance ( File dir ) { return new TestIndexCacheFactory ( dir ) ; } } package net . sf . sveditor . core . tests ; import junit . framework . TestCase ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; public class SVDBIndexValidator extends TestCase { public static final int ExpectErrors = ( << ) ; public void validateIndex ( ISVDBItemIterator i_it , int flags ) { while ( i_it . hasNext ( ) ) { ISVDBItemBase it = i_it . nextItem ( ) ; assertNotNull ( it ) ; if ( it . getType ( ) == SVDBItemType . VarDeclStmt ) { SVDBVarDeclStmt v = ( SVDBVarDeclStmt ) it ; for ( ISVDBChildItem c : v . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; assertNotNull ( "" + vi . getName ( ) + "" , vi . getParent ( ) ) ; assertNotNull ( "" + vi . getName ( ) + "" , v . getTypeInfo ( ) ) ; } } } } } package net . sf . sveditor . core . tests ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import junit . framework . TestCase ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . NullProgressMonitor ; public class IndexTestUtils { public static void assertNoErrWarn ( LogHandle log , ISVDBIndex index ) { for ( String file : index . getFileList ( new NullProgressMonitor ( ) ) ) { List < SVDBMarker > markers = index . getMarkers ( file ) ; for ( SVDBMarker m : markers ) { log . debug ( "" + m . getKind ( ) + m . getMessage ( ) ) ; } } for ( String file : index . getFileList ( new NullProgressMonitor ( ) ) ) { List < SVDBMarker > markers = index . getMarkers ( file ) ; TestCase . assertEquals ( "" + file , , markers . size ( ) ) ; } } public static void assertNoErrWarn ( LogHandle log , SVDBIndexCollection index_mgr ) { for ( ISVDBIndex index : index_mgr . getIndexList ( ) ) { for ( String file : index . getFileList ( new NullProgressMonitor ( ) ) ) { List < SVDBMarker > markers = index . getMarkers ( file ) ; for ( SVDBMarker m : markers ) { log . debug ( "" + m . getKind ( ) + m . getMessage ( ) ) ; } } for ( String file : index . getFileList ( new NullProgressMonitor ( ) ) ) { List < SVDBMarker > markers = index . getMarkers ( file ) ; TestCase . assertEquals ( "" + file , , markers . size ( ) ) ; } } } public static void assertFileHasElements ( ISVDBIndexIterator index_it , String ... elems ) { Set < String > exp = new HashSet < String > ( ) ; for ( String e : elems ) { exp . add ( e ) ; } ISVDBItemIterator item_it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( item_it . hasNext ( ) ) { ISVDBItemBase it = item_it . nextItem ( ) ; String name = SVDBItem . getName ( it ) ; if ( exp . contains ( name ) ) { exp . remove ( name ) ; } } for ( String e : exp ) { TestCase . fail ( "" + e + "" ) ; } } public static void assertDoesNotContain ( ISVDBIndexIterator index_it , String ... elems ) { Set < String > exp = new HashSet < String > ( ) ; for ( String e : elems ) { exp . add ( e ) ; } ISVDBItemIterator item_it = index_it . getItemIterator ( new NullProgressMonitor ( ) ) ; while ( item_it . hasNext ( ) ) { ISVDBItemBase it = item_it . nextItem ( ) ; String name = SVDBItem . getName ( it ) ; if ( exp . contains ( name ) ) { TestCase . fail ( "" + name + "" ) ; } } } public static ISVDBIndexIterator buildIndex ( String doc , String filename ) { SVDBFile file = SVDBTestUtils . parse ( doc , filename ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; return target_index ; } } package net . sf . sveditor . core . tests ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcDirectiveScanner ; import net . sf . sveditor . core . scanner . FileContextSearchMacroProvider ; import net . sf . sveditor . core . scanner . SVPreProcDefineProvider ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . equinox . app . IApplication ; import org . eclipse . equinox . app . IApplicationContext ; public class testPreProcessor implements IApplication { public Object start ( IApplicationContext context ) throws Exception { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; ISVDBIndex index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBSourceCollectionIndexFactory . TYPE , null ) ; String filename = "" ; FileContextSearchMacroProvider mp = new FileContextSearchMacroProvider ( null , null ) ; SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( mp ) ; index . findPreProcFile ( filename ) ; log . debug ( "" ) ; SVDBFileTree scen_gen_ctxt = null ; log . debug ( "" ) ; mp . setFileContext ( scen_gen_ctxt ) ; SVPreProcDirectiveScanner sc = new SVPreProcDirectiveScanner ( ) ; long start = System . currentTimeMillis ( ) ; log . debug ( "" ) ; StringBuilder tmp = new StringBuilder ( ) ; try { InputStream in = new FileInputStream ( filename ) ; sc . init ( in , filename ) ; int ch ; do { if ( ( ch = sc . get_ch ( ) ) != - ) { tmp . append ( ( char ) ch ) ; } } while ( ch != - ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } log . debug ( tmp . toString ( ) ) ; log . debug ( "" ) ; long end = System . currentTimeMillis ( ) ; System . out . println ( "" + ( end - start ) ) ; return ; } public void stop ( ) { } } package net . sf . sveditor . core . tests ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBMarker ; import org . eclipse . equinox . app . IApplication ; import org . eclipse . equinox . app . IApplicationContext ; public class testSVScannerLineNumbers implements IApplication { public Object start ( IApplicationContext context ) throws Exception { InputStream in = SVCoreTestsPlugin . openFile ( "" ) ; ISVDBFileFactory factory = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile f = factory . parse ( in , "" , markers ) ; for ( ISVDBItemBase it : f . getChildren ( ) ) { System . out . println ( "" + SVDBItem . getName ( it ) + "" + it . getLocation ( ) . getLine ( ) ) ; } return ; } public void stop ( ) { } } package net . sf . sveditor . core . tests . open_decl ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . open_decl . OpenDeclUtils ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class TestOpenClass extends TestCase { public void testOpenVariableRef ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testOpenVariableRefTaskScope ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . Task , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testOpenVariableDottedRef ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } public void testOpenVariableExplicitThisDottedRef ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } public void testOpenVariableDottedSuperRef ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } public void testOpenVariableExplicitDottedSuperRef ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } public void testOpenScopedClassReference ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testOpenClassTypeRef ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . ClassDecl , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } public void testOpenIfcTypeRef ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . InterfaceDecl , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } public void testOpenClassTypeRefIgnoreTypedefs ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; ISVDBItemBase item = ret . get ( ) . first ( ) ; assertEquals ( SVDBItemType . ClassDecl , item . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( item ) ) ; } public void testOpenMethodrefAtBeginning ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . Function , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } } package net . sf . sveditor . core . tests . open_decl ; import junit . framework . TestSuite ; public class OpenDeclTests extends TestSuite { public static TestSuite suite ( ) { TestSuite s = new TestSuite ( "" ) ; s . addTest ( new TestSuite ( TestOpenFile . class ) ) ; s . addTest ( new TestSuite ( TestOpenClass . class ) ) ; s . addTest ( new TestSuite ( TestOpenModIfc . class ) ) ; return s ; } } package net . sf . sveditor . core . tests . open_decl ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBFileSystemProvider ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . ISVDBItemIterator ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBLibIndex ; import net . sf . sveditor . core . db . index . SVDBLibPathIndexFactory ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . open_decl . OpenDeclUtils ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import net . sf . sveditor . core . tests . TestIndexCacheFactory ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; public class TestOpenFile extends TestCase { private File fTmpDir ; private IProject fProject ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) . save_state ( ) ; if ( fProject != null ) { TestUtils . deleteProject ( fProject ) ; } if ( fTmpDir . exists ( ) ) { TestUtils . delete ( fTmpDir ) ; } } public void testRelPathOpenDecl ( ) throws IOException { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; try { BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; utils . copyBundleDirToFS ( "" , fTmpDir ) ; File subdir2 = new File ( fTmpDir , "" ) ; fProject = TestUtils . createProject ( "" , subdir2 ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . init ( TestIndexCacheFactory . instance ( null ) ) ; ISVDBIndex target_index = rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , "" , SVDBLibPathIndexFactory . TYPE , null ) ; ISVDBItemIterator it = target_index . getItemIterator ( new NullProgressMonitor ( ) ) ; ISVDBFileSystemProvider fs_provider = ( ( SVDBLibIndex ) target_index ) . getFileSystemProvider ( ) ; SVDBFile file = null ; while ( it . hasNext ( ) ) { ISVDBItemBase it_t = it . nextItem ( ) ; if ( SVDBItem . getName ( it_t ) . endsWith ( "" ) ) { file = ( SVDBFile ) it_t ; } } InputStream in = fs_provider . openStream ( "" ) ; String content = SVCoreTestsPlugin . readStream ( in ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( content ) ; scanner . seek ( content . indexOf ( "" ) + ) ; fs_provider . closeStream ( in ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; assertEquals ( , ret . size ( ) ) ; log . debug ( "" + ret . size ( ) ) ; log . debug ( "" + SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } finally { } LogFactory . removeLogHandle ( log ) ; } public void testOpenMacroDef ( ) { String testname = "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( testname ) ; String doc = "" + "" + "" + "" + "" ; Tuple < SVDBFile , SVDBFile > file = SVDBTestUtils . parsePreProc ( doc , testname , false ) ; SVDBTestUtils . assertFileHasElements ( file . second ( ) , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; int lineno = ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file . second ( ) , lineno , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . MacroDef , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; } } package net . sf . sveditor . core . tests . open_decl ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . open_decl . OpenDeclUtils ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . core . tests . FileIndexIterator ; import net . sf . sveditor . core . tests . SVDBTestUtils ; import junit . framework . TestCase ; public class TestOpenModIfc extends TestCase { public void testOpenModuleDecl ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . ModuleDecl , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testOpenInterfaceDecl ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String doc = "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , "" ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . InterfaceDecl , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void disabled_testOpenModuleDeclwPreComment ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; scanner . seek ( idx + ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . ModuleDecl , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testStructFieldModuleScope ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; int lineno = ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , lineno , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testUnionFieldModuleScope ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; int lineno = ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , lineno , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testStructUnionFieldModuleScope ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; int lineno = ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , lineno , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testClassFieldModuleScope ( ) { String testname = "" ; LogHandle log = LogFactory . getLogHandle ( testname ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String doc = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVDBFile file = SVDBTestUtils . parse ( doc , testname ) ; SVDBTestUtils . assertNoErrWarn ( file ) ; SVDBTestUtils . assertFileHasElements ( file , "" ) ; StringBIDITextScanner scanner = new StringBIDITextScanner ( doc ) ; int idx = doc . indexOf ( "" ) ; log . debug ( "" + idx ) ; scanner . seek ( idx + "" . length ( ) ) ; ISVDBIndexIterator target_index = new FileIndexIterator ( file ) ; int lineno = ; List < Tuple < ISVDBItemBase , SVDBFile > > ret = OpenDeclUtils . openDecl_2 ( file , lineno , scanner , target_index ) ; log . debug ( ret . size ( ) + "" ) ; assertEquals ( , ret . size ( ) ) ; assertEquals ( SVDBItemType . VarDeclItem , ret . get ( ) . first ( ) . getType ( ) ) ; assertEquals ( "" , SVDBItem . getName ( ret . get ( ) . first ( ) ) ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . fileset ; import java . io . File ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . project . SVDBSourceCollection ; import net . sf . sveditor . core . fileset . AbstractSVFileMatcher ; import net . sf . sveditor . core . fileset . SVFileSet ; import net . sf . sveditor . core . fileset . SVFilesystemFileMatcher ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . tests . SVCoreTestsPlugin ; import net . sf . sveditor . core . tests . utils . BundleUtils ; import net . sf . sveditor . core . tests . utils . TestUtils ; public class FileSetTests extends TestCase { private File fTmpDir ; @ Override protected void setUp ( ) throws Exception { fTmpDir = TestUtils . createTempDir ( ) ; } @ Override protected void tearDown ( ) throws Exception { TestUtils . delete ( fTmpDir ) ; } public void testDefaultRecurse ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File t_dir = new File ( fTmpDir , "" ) ; utils . copyBundleDirToFS ( "" , t_dir ) ; File base = new File ( t_dir , "" ) ; SVFileSet fs = new SVFileSet ( base . getAbsolutePath ( ) ) ; String dflt_include = SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionIncludes ( ) ; String dflt_exclude = SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionExcludes ( ) ; fs . getIncludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( dflt_include ) ) ; fs . getExcludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( dflt_exclude ) ) ; SVFilesystemFileMatcher matcher = new SVFilesystemFileMatcher ( ) ; matcher . addFileSet ( fs ) ; List < String > matches = matcher . findIncludedPaths ( ) ; Set < String > match_set = new HashSet < String > ( ) ; match_set . add ( "" ) ; match_set . add ( "" ) ; match_set . add ( "" ) ; match_set . add ( "" ) ; match_set . add ( "" ) ; for ( String m : matches ) { log . debug ( "" + m ) ; File f = new File ( m ) ; assertTrue ( match_set . contains ( f . getName ( ) ) ) ; match_set . remove ( f . getName ( ) ) ; } assertEquals ( , match_set . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testExcludeRecurse ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File t_dir = new File ( fTmpDir , "" ) ; utils . copyBundleDirToFS ( "" , t_dir ) ; File base = new File ( t_dir , "" ) ; SVFileSet fs = new SVFileSet ( base . getAbsolutePath ( ) ) ; String dflt_include = SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionIncludes ( ) ; String dflt_exclude = SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionExcludes ( ) ; fs . getIncludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( dflt_include ) ) ; fs . getExcludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( dflt_exclude ) ) ; fs . addExclude ( "" ) ; SVFilesystemFileMatcher matcher = new SVFilesystemFileMatcher ( ) ; matcher . addFileSet ( fs ) ; List < String > matches = matcher . findIncludedPaths ( ) ; Set < String > match_set = new HashSet < String > ( ) ; match_set . add ( "" ) ; match_set . add ( "" ) ; match_set . add ( "" ) ; match_set . add ( "" ) ; for ( String m : matches ) { log . debug ( "" + m ) ; File f = new File ( m ) ; assertTrue ( match_set . contains ( f . getName ( ) ) ) ; match_set . remove ( f . getName ( ) ) ; } assertEquals ( , match_set . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testNonRecurseVlog ( ) { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; LogHandle log = LogFactory . getLogHandle ( "" ) ; BundleUtils utils = new BundleUtils ( SVCoreTestsPlugin . getDefault ( ) . getBundle ( ) ) ; File t_dir = new File ( fTmpDir , "" ) ; utils . copyBundleDirToFS ( "" , t_dir ) ; File base = new File ( t_dir , "" ) ; SVFileSet fs = new SVFileSet ( base . getAbsolutePath ( ) ) ; fs . addInclude ( "" ) ; SVFilesystemFileMatcher matcher = new SVFilesystemFileMatcher ( ) ; matcher . addFileSet ( fs ) ; List < String > matches = matcher . findIncludedPaths ( ) ; Set < String > match_set = new HashSet < String > ( ) ; match_set . add ( "" ) ; match_set . add ( "" ) ; for ( String m : matches ) { log . debug ( "" + m ) ; File f = new File ( m ) ; assertTrue ( match_set . contains ( f . getName ( ) ) ) ; match_set . remove ( f . getName ( ) ) ; } assertEquals ( , match_set . size ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testWindowsPathPattern ( ) { String root = "" ; final String input [ ] = { root + "" , root + "" } ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; SVFileSet fs = SVCorePlugin . getDefault ( ) . getDefaultFileSet ( root ) ; fs . addInclude ( "" ) ; fs . addInclude ( "" ) ; AbstractSVFileMatcher matcher = new AbstractSVFileMatcher ( ) { @ Override public List < String > findIncludedPaths ( ) { fLog = LogFactory . getLogHandle ( "" ) ; List < String > ret = new ArrayList < String > ( ) ; for ( String in : input ) { if ( include_file ( in ) ) { ret . add ( SVFileUtils . normalize ( in ) ) ; } } return ret ; } } ; matcher . addFileSet ( fs ) ; List < String > result = matcher . findIncludedPaths ( ) ; for ( String exp : input ) { exp = SVFileUtils . normalize ( exp ) ; assertTrue ( result . contains ( exp ) ) ; } } } package net . sf . sveditor . core . tests ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . AbstractSVDBIndex ; import net . sf . sveditor . core . db . index . SVDBFSFileSystemProvider ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import net . sf . sveditor . core . db . index . SVDBFileTreeUtils ; import net . sf . sveditor . core . db . index . cache . InMemoryIndexCache ; import net . sf . sveditor . core . scanner . IPreProcMacroProvider ; import net . sf . sveditor . core . scanner . SVPreProcDefineProvider ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class FileIndexIterator extends AbstractSVDBIndex { private SVDBFile fFile ; private SVDBFile fPPFile ; Map < String , SVDBFile > fFileMap ; public FileIndexIterator ( SVDBFile file ) { super ( "" , "" , new SVDBFSFileSystemProvider ( ) , new InMemoryIndexCache ( ) , null ) ; fFile = file ; fFileMap = new HashMap < String , SVDBFile > ( ) ; fFileMap . put ( file . getName ( ) , file ) ; init ( new NullProgressMonitor ( ) ) ; loadIndex ( new NullProgressMonitor ( ) ) ; } public FileIndexIterator ( Tuple < SVDBFile , SVDBFile > file ) { super ( "" , "" , new SVDBFSFileSystemProvider ( ) , new InMemoryIndexCache ( ) , null ) ; fPPFile = file . first ( ) ; fFile = file . second ( ) ; fFileMap = new HashMap < String , SVDBFile > ( ) ; fFileMap . put ( fFile . getName ( ) , fFile ) ; init ( new NullProgressMonitor ( ) ) ; loadIndex ( new NullProgressMonitor ( ) ) ; } public String getTypeID ( ) { return "" ; } @ Override protected String getLogName ( ) { return "" ; } @ Override protected void discoverRootFiles ( IProgressMonitor monitor ) { addFile ( fFile . getFilePath ( ) ) ; } @ Override protected void processFile ( SVDBFileTree path , IPreProcMacroProvider mp ) { } @ Override protected SVDBFile processPreProcFile ( String path ) { cacheDeclarations ( fFile ) ; cacheReferences ( fFile ) ; getCache ( ) . setFile ( fFile . getFilePath ( ) , fFile ) ; return null ; } @ Override public SVDBFile findFile ( IProgressMonitor monitor , String path ) { if ( fFile . getFilePath ( ) . equals ( path ) ) { return fFile ; } else { return super . findFile ( monitor , path ) ; } } @ Override public SVDBFile findPreProcFile ( IProgressMonitor monitor , String path ) { if ( fPPFile != null && fPPFile . getFilePath ( ) . equals ( path ) ) { return fPPFile ; } else { return super . findPreProcFile ( monitor , path ) ; } } @ Override protected void parseFiles ( IProgressMonitor monitor ) { } @ Override protected void buildFileTree ( IProgressMonitor monitor ) { } @ Override public synchronized SVDBFileTree findFileTree ( String path ) { if ( fPPFile != null ) { SVDBFileTree ft = new SVDBFileTree ( ( SVDBFile ) fPPFile . duplicate ( ) ) ; SVDBFileTreeUtils ft_utils = new SVDBFileTreeUtils ( ) ; Map < String , SVDBFileTree > working_set = new HashMap < String , SVDBFileTree > ( ) ; ft_utils . resolveConditionals ( ft , new SVPreProcDefineProvider ( createPreProcMacroProvider ( ft , working_set ) ) ) ; return ft ; } else { return null ; } } } package net . sf . sveditor . core . tests ; import org . eclipse . core . runtime . NullProgressMonitor ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBSourceCollectionIndexFactory ; public class SVDBIndexProfiler { public static final void main ( String args [ ] ) { SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; rgy . findCreateIndex ( new NullProgressMonitor ( ) , "" , args [ ] , SVDBSourceCollectionIndexFactory . TYPE , null ) ; try { Thread . sleep ( ) ; } catch ( Exception e ) { } } } package net . sf . sveditor . core . tests . scanner ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . tests . SVDBTestUtils ; public class ProgramBlockTests extends TestCase { protected void setUp ( ) throws Exception { super . setUp ( ) ; } public void testBasicProgramBlock ( ) { StringInputStream in = new StringInputStream ( "" + "" + "" + "" + "" + "" + "" + "" ) ; ISVDBFileFactory f = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; SVDBFile file = f . parse ( in , "" , markers ) ; SVDBTestUtils . assertFileHasElements ( file , "" , "" , "" ) ; } protected void tearDown ( ) throws Exception { super . tearDown ( ) ; } } package net . sf . sveditor . core . tests . scanner ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . ISVDBFileFactory ; import net . sf . sveditor . core . db . SVDBMarker ; public class EnumTypes extends TestCase { public void testEnumTypedef ( ) { String enum_defs = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; StringInputStream in = new StringInputStream ( enum_defs ) ; ISVDBFileFactory f = SVCorePlugin . createFileFactory ( null ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; f . parse ( in , "" , markers ) ; } } package net . sf . sveditor . core . tests . scanner ; import junit . framework . TestSuite ; public class ScannerTests extends TestSuite { } package net . sf . sveditor . core . tests . scanner ; import java . io . InputStream ; import junit . framework . TestCase ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBPreProcObserver ; import net . sf . sveditor . core . db . index . SVDBFileTree ; import net . sf . sveditor . core . db . index . SVDBFileTreeUtils ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . preproc . SVPreProcDirectiveScanner ; import net . sf . sveditor . core . scanner . FileContextSearchMacroProvider ; import net . sf . sveditor . core . scanner . SVPreProcDefineProvider ; import org . apache . tools . ant . filters . StringInputStream ; public class PreProcMacroTests extends TestCase { public void testMultiTokenGlue ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; String text = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; InputStream in = new StringInputStream ( text ) ; SVPreProcDirectiveScanner sc = new SVPreProcDirectiveScanner ( ) ; SVDBPreProcObserver ob = new SVDBPreProcObserver ( ) ; sc . init ( in , "" ) ; sc . setObserver ( ob ) ; sc . process ( ) ; SVDBFile pp_file = ob . getFiles ( ) . get ( ) ; SVDBFileTree ft_root = new SVDBFileTree ( ( SVDBFile ) pp_file . duplicate ( ) ) ; SVDBFileTreeUtils ft_utils = new SVDBFileTreeUtils ( ) ; FileContextSearchMacroProvider mp = new FileContextSearchMacroProvider ( null , null ) ; SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( mp ) ; mp . setFileContext ( ft_root ) ; ft_utils . resolveConditionals ( ft_root , dp ) ; String result = dp . expandMacro ( "" , "" , ) ; log . debug ( "" + expected . trim ( ) + "" ) ; log . debug ( "" ) ; log . debug ( "" + result . trim ( ) + "" ) ; assertEquals ( expected , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testNestedExpansion ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String text = "" + "" + "" + "" ; InputStream in = new StringInputStream ( text ) ; SVPreProcDirectiveScanner sc = new SVPreProcDirectiveScanner ( ) ; SVDBPreProcObserver ob = new SVDBPreProcObserver ( ) ; sc . init ( in , "" ) ; sc . setObserver ( ob ) ; sc . process ( ) ; SVDBFile pp_file = ob . getFiles ( ) . get ( ) ; SVDBFileTree ft_root = new SVDBFileTree ( ( SVDBFile ) pp_file . duplicate ( ) ) ; SVDBFileTreeUtils ft_utils = new SVDBFileTreeUtils ( ) ; FileContextSearchMacroProvider mp = new FileContextSearchMacroProvider ( null , null ) ; SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( mp ) ; mp . setFileContext ( ft_root ) ; ft_utils . resolveConditionals ( ft_root , dp ) ; String result = dp . expandMacro ( "" , "" , ) ; log . debug ( "" + result + "" ) ; assertEquals ( "" , result . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } public void testMacroContainingIfdef ( ) { LogHandle log = LogFactory . getLogHandle ( "" ) ; String content = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; InputStream in = new StringInputStream ( content ) ; SVPreProcDirectiveScanner pp_scanner = new SVPreProcDirectiveScanner ( ) ; pp_scanner . init ( in , "" ) ; SVDBPreProcObserver observer = new SVDBPreProcObserver ( ) ; pp_scanner . setObserver ( observer ) ; pp_scanner . process ( ) ; SVDBFileTree ft = new SVDBFileTree ( observer . getFiles ( ) . get ( ) ) ; FileContextSearchMacroProvider mp = new FileContextSearchMacroProvider ( null , null ) ; mp . setFileContext ( ft ) ; SVPreProcDefineProvider dp = new SVPreProcDefineProvider ( mp ) ; String out = dp . expandMacro ( "" , "" , ) ; log . debug ( "" + out ) ; assertEquals ( "" , out . trim ( ) ) ; LogFactory . removeLogHandle ( log ) ; } } package net . sf . sveditor . core . tests . objects ; import java . io . File ; import java . util . List ; import junit . framework . Test ; import junit . framework . TestCase ; import junit . framework . TestSuite ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . core . objects . ObjectsTreeFactory ; import net . sf . sveditor . core . objects . ObjectsTreeNode ; import net . sf . sveditor . core . tests . CoreReleaseTests ; import net . sf . sveditor . core . tests . utils . TestUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; public class ObjectsTests extends TestCase { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( new TestSuite ( ObjectsTests . class ) ) ; return suite ; } private File fTmpDir ; private IProject fp1 , fp2 ; private SVDBProjectData fp1_pdata , fp2_pdata ; private SVProjectFileWrapper fp1_fwrapper , fp2_fwrapper ; private ObjectsTreeNode fTopNode ; private ObjectsTreeNode fpkgsNode = null , fmodulesNode = null , finterfacesNode = null ; private ObjectsTreeNode fpkgA = null , fpkgB = null , fpkgRoot = null ; @ Override protected void setUp ( ) throws Exception { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; fTmpDir = TestUtils . createTempDir ( ) ; CoreReleaseTests . clearErrors ( ) ; SVDBProjectManager pmgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; fp1 = TestUtils . setupIndexWSProject ( null , fTmpDir , "" , "" ) ; fp2 = TestUtils . setupIndexWSProject ( null , fTmpDir , "" , "" ) ; fp1_pdata = pmgr . getProjectData ( fp1 ) ; fp1_fwrapper = fp1_pdata . getProjectFileWrapper ( ) ; fp1_fwrapper . addArgFilePath ( "" ) ; fp1_pdata . setProjectFileWrapper ( fp1_fwrapper ) ; SVDBIndexCollection p1_index = fp1_pdata . getProjectIndexMgr ( ) ; for ( ISVDBIndex index : p1_index . getIndexList ( ) ) { index . loadIndex ( new NullProgressMonitor ( ) ) ; } fp2_pdata = pmgr . getProjectData ( fp2 ) ; fp2_fwrapper = fp2_pdata . getProjectFileWrapper ( ) ; fp2_fwrapper . addArgFilePath ( "" ) ; fp2_pdata . setProjectFileWrapper ( fp2_fwrapper ) ; SVDBIndexCollection p2_index = fp2_pdata . getProjectIndexMgr ( ) ; for ( ISVDBIndex index : p2_index . getIndexList ( ) ) { index . loadIndex ( new NullProgressMonitor ( ) ) ; } List < ISVDBIndex > allProjIndexList = p1_index . getIndexList ( ) ; allProjIndexList . addAll ( p2_index . getIndexList ( ) ) ; ObjectsTreeFactory of = new ObjectsTreeFactory ( allProjIndexList ) ; fTopNode = of . build ( ) ; if ( fTopNode != null ) { for ( ObjectsTreeNode topChild : fTopNode . getChildren ( ) ) { if ( topChild . getName ( ) == ObjectsTreeNode . PACKAGES_NODE ) { fpkgsNode = topChild ; continue ; } if ( topChild . getName ( ) == ObjectsTreeNode . MODULES_NODE ) { fmodulesNode = topChild ; continue ; } if ( topChild . getName ( ) == ObjectsTreeNode . INTERFACES_NODE ) { finterfacesNode = topChild ; continue ; } } } if ( fpkgsNode != null ) { for ( ObjectsTreeNode pkgNode : fpkgsNode . getChildren ( ) ) { if ( pkgNode . getName ( ) . matches ( "" ) ) { fpkgA = pkgNode ; continue ; } if ( pkgNode . getName ( ) . matches ( "" ) ) { fpkgB = pkgNode ; continue ; } if ( pkgNode . getName ( ) . matches ( ObjectsTreeNode . ROOT_PKG ) ) { fpkgRoot = pkgNode ; continue ; } } } } @ Override protected void tearDown ( ) throws Exception { assertEquals ( , CoreReleaseTests . getErrors ( ) . size ( ) ) ; } public void testTopNodeFound ( ) throws CoreException { assertNotNull ( fTopNode ) ; } public void testTopNodesFound ( ) throws CoreException { assertNotNull ( "" , fpkgsNode ) ; assertNotNull ( "" , fmodulesNode ) ; assertNotNull ( "" , finterfacesNode ) ; } public void testPackagesFound ( ) throws CoreException { assertNotNull ( "" , fpkgA ) ; assertNotNull ( "" , fpkgB ) ; assertNotNull ( "" , fpkgRoot ) ; } public void testClassesNotWithinPackages ( ) throws CoreException { assertNotNull ( "" , fpkgRoot ) ; ObjectsTreeNode cR = null , cS = null ; if ( fpkgRoot != null ) { cR = fpkgRoot . getChildByName ( "" ) ; cS = fpkgRoot . getChildByName ( "" ) ; } assertNotNull ( "" , cR ) ; assertNotNull ( "" , cS ) ; } public void testClassesWithinPackages ( ) throws CoreException { SVCorePlugin . getDefault ( ) . enableDebug ( false ) ; assertNotNull ( "" , fpkgA ) ; assertNotNull ( "" , fpkgB ) ; assertNotNull ( "" , fpkgB ) ; ObjectsTreeNode cA = null , cB = null , cL = null ; cA = fpkgA . getChildByName ( "" ) ; cB = fpkgA . getChildByName ( "" ) ; cL = fpkgB . getChildByName ( "" ) ; assertNotNull ( "" , cA ) ; assertNotNull ( "" , cB ) ; assertNotNull ( "" , cL ) ; } } package net . sf . sveditor . core . tests ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . NullProgressMonitor ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . db . index . ISVDBFileSystemChangeListener ; import net . sf . sveditor . core . db . index . ISVDBFileSystemProvider ; import net . sf . sveditor . core . db . index . SVDBLibIndex ; public class SVDBStringDocumentIndex extends SVDBLibIndex { public SVDBStringDocumentIndex ( final String input ) { super ( "" , "" , new ISVDBFileSystemProvider ( ) { public InputStream openStream ( String path ) { if ( path . equals ( "" ) ) { return new StringInputStream ( input ) ; } else { return null ; } } public boolean fileExists ( String path ) { return path . equals ( "" ) ; } public boolean isDir ( String path ) { return false ; } public List < String > getFiles ( String path ) { return new ArrayList < String > ( ) ; } public void init ( String root ) { } public long getLastModifiedTime ( String path ) { return ; } public String resolvePath ( String path , String fmt ) { return path ; } public void removeFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { } public void dispose ( ) { } public void closeStream ( InputStream in ) { } public void clearMarkers ( String path ) { } public void addMarker ( String path , String type , int lineno , String msg ) { } public void addFileSystemChangeListener ( ISVDBFileSystemChangeListener l ) { } } , TestIndexCacheFactory . instance ( null ) . createIndexCache ( "" , "" ) , null ) ; init ( new NullProgressMonitor ( ) ) ; } } package net . sf . sveditor . doc . user . tasks ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Properties ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . TransformerConfigurationException ; import javax . xml . transform . TransformerException ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . sax . SAXTransformerFactory ; import javax . xml . transform . sax . TransformerHandler ; import javax . xml . transform . stream . StreamResult ; import org . apache . tools . ant . BuildException ; import org . apache . tools . ant . taskdefs . MatchingTask ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . ErrorHandler ; import org . xml . sax . SAXException ; import org . xml . sax . SAXParseException ; public class AssembleTocTask extends MatchingTask { private String [ ] fFiles ; private String fOutput = "" ; private String fLabel = "" ; public void setOutput ( String output ) { fOutput = output ; } public void setLabel ( String label ) { fLabel = label ; } public void setFiles ( String files ) { fFiles = files . split ( "" ) ; for ( int i = ; i < fFiles . length ; i ++ ) { fFiles [ i ] = fFiles [ i ] . trim ( ) ; } } @ Override public void execute ( ) throws BuildException { System . out . println ( "" ) ; try { run ( ) ; } catch ( Exception e ) { throw new BuildException ( e ) ; } } private void run ( ) throws IOException , ParserConfigurationException , SAXException , TransformerConfigurationException , TransformerException { DocumentBuilderFactory f = DocumentBuilderFactory . newInstance ( ) ; Document doc_o = f . newDocumentBuilder ( ) . newDocument ( ) ; System . out . println ( "" + fOutput ) ; FileOutputStream fos = new FileOutputStream ( fOutput ) ; Element toc = doc_o . createElement ( "" ) ; toc . setAttribute ( "" , fLabel ) ; doc_o . appendChild ( toc ) ; for ( String file : fFiles ) { InputStream in = new FileInputStream ( file ) ; DocumentBuilder b = f . newDocumentBuilder ( ) ; b . setErrorHandler ( fErrorHandler ) ; Document d = b . parse ( in ) ; Node toc_n = d . getFirstChild ( ) ; NodeList nl = toc_n . getChildNodes ( ) ; for ( int i = ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; System . out . println ( "" + n . getNodeName ( ) ) ; Node n_p = doc_o . importNode ( n , true ) ; toc . appendChild ( n_p ) ; } } SAXTransformerFactory tf = ( SAXTransformerFactory ) SAXTransformerFactory . newInstance ( ) ; DOMSource ds = new DOMSource ( doc_o ) ; StreamResult sr = new StreamResult ( fos ) ; tf . setAttribute ( "" , new Integer ( ) ) ; TransformerHandler th = tf . newTransformerHandler ( ) ; Properties format = new Properties ( ) ; format . put ( OutputKeys . METHOD , "" ) ; format . put ( OutputKeys . ENCODING , "" ) ; format . put ( OutputKeys . INDENT , "" ) ; th . getTransformer ( ) . setOutputProperties ( format ) ; th . setResult ( sr ) ; th . getTransformer ( ) . transform ( ds , sr ) ; fos . close ( ) ; } private ErrorHandler fErrorHandler = new ErrorHandler ( ) { public void warning ( SAXParseException arg0 ) throws SAXException { } public void fatalError ( SAXParseException arg0 ) throws SAXException { } public void error ( SAXParseException arg0 ) throws SAXException { } } ; } package net . sf . sveditor . doc . user ; import org . eclipse . core . runtime . Plugin ; import org . osgi . framework . BundleContext ; public class Activator extends Plugin { private static Activator fPlugin ; @ Override public void start ( BundleContext context ) throws Exception { super . start ( context ) ; fPlugin = this ; } @ Override public void stop ( BundleContext context ) throws Exception { fPlugin = null ; super . stop ( context ) ; } public static Activator getDefault ( ) { return fPlugin ; } } package net . sf . sveditor . ui . pref ; public class SVEditorPrefsConstants { public static final String P_DEFAULT_C = "" ; public static final String P_SL_COMMENT_C = "" ; public static final String P_ML_COMMENT_C = "" ; public static final String P_KEYWORD_C = "" ; public static final String P_STRING_C = "" ; public static final String P_DEFAULT_S = "" ; public static final String P_KEYWORD_S = "" ; public static final String P_SL_COMMENT_S = "" ; public static final String P_ML_COMMENT_S = "" ; public static final String P_STRING_S = "" ; } package net . sf . sveditor . ui . views . diagram ; import java . util . HashSet ; import java . util . Set ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . diagrams . DiagModel ; import net . sf . sveditor . core . diagrams . DiagNode ; import net . sf . sveditor . core . diagrams . IDiagModelFactory ; import net . sf . sveditor . ui . SVDBIconUtils ; import net . sf . sveditor . ui . SVEditorUtil ; import net . sf . sveditor . ui . views . diagram . contributions . NewDiagramForClassContributionItem ; import net . sf . sveditor . ui . views . diagram . contributions . NewDiagramForClassHandler ; import org . eclipse . draw2d . FanRouter ; import org . eclipse . draw2d . Graphics ; import org . eclipse . draw2d . IFigure ; import org . eclipse . draw2d . ManhattanConnectionRouter ; import org . eclipse . draw2d . SWTGraphics ; import org . eclipse . draw2d . ScalableFigure ; import org . eclipse . draw2d . geometry . Rectangle ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CTabFolder ; import org . eclipse . swt . custom . CTabItem ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . events . MouseListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . ImageLoader ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . layout . RowLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . zest . core . viewers . AbstractZoomableViewer ; import org . eclipse . zest . core . viewers . GraphViewer ; import org . eclipse . zest . core . viewers . IZoomableWorkbenchPart ; import org . eclipse . zest . core . viewers . ZoomContributionViewItem ; import org . eclipse . zest . core . widgets . CGraphNode ; import org . eclipse . zest . core . widgets . Graph ; import org . eclipse . zest . layouts . LayoutStyles ; import org . eclipse . zest . layouts . algorithms . GridLayoutAlgorithm ; import org . eclipse . zest . layouts . algorithms . RadialLayoutAlgorithm ; import org . eclipse . zest . layouts . algorithms . TreeLayoutAlgorithm ; public class SVDiagramView extends ViewPart implements SelectionListener , IZoomableWorkbenchPart { private GraphViewer fGraphViewer ; private DiagModel fModel ; @ SuppressWarnings ( "" ) private IDiagModelFactory fModelFactory ; private CTabItem fConfigTab ; private CTabFolder fTabFolder ; private IDiagLabelProviderConfig fDiagLabelProvider ; private NewDiagramForClassHandler fNewDiagramForClassHandler ; private NewDiagramForClassContributionItem fNewDiagramForClassContributionItem ; @ SuppressWarnings ( "" ) private double [ ] fZoomLevels = { , , } ; public GraphViewer getGraphViewer ( ) { return fGraphViewer ; } @ Override public void createPartControl ( Composite parent ) { GridLayout gl = new GridLayout ( ) ; gl . numColumns = ; parent . setLayout ( gl ) ; createGraphViewer ( parent ) ; createTabFolder ( parent ) ; createContextMenu ( ) ; createContributions ( ) ; ZoomContributionViewItem toolbarZoomContributionViewItem = new ZoomContributionViewItem ( this ) ; IActionBars bars = getViewSite ( ) . getActionBars ( ) ; bars . getMenuManager ( ) . add ( toolbarZoomContributionViewItem ) ; fGraphViewer . setLayoutAlgorithm ( new RadialLayoutAlgorithm ( LayoutStyles . NO_LAYOUT_NODE_RESIZING ) , false ) ; fTabFolder . setSelection ( fConfigTab ) ; } private void createContextMenu ( ) { MenuManager menuMgr = new MenuManager ( "" ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager mgr ) { SVDiagramView . this . fillContextMenu ( mgr ) ; } } ) ; Menu menu = menuMgr . createContextMenu ( fGraphViewer . getControl ( ) ) ; fGraphViewer . getControl ( ) . setMenu ( menu ) ; } protected void fillContextMenu ( IMenuManager mgr ) { mgr . add ( fNewDiagramForClassContributionItem ) ; mgr . add ( new Separator ( IWorkbenchActionConstants . MB_ADDITIONS ) ) ; } private void createContributions ( ) { fNewDiagramForClassHandler = new NewDiagramForClassHandler ( ) ; fNewDiagramForClassContributionItem = new NewDiagramForClassContributionItem ( this , fNewDiagramForClassHandler ) ; } private void createGraphViewer ( Composite parent ) { GridData gd ; fGraphViewer = new GraphViewer ( parent , SWT . BORDER ) ; fDiagLabelProvider = new DiagLabelProvider ( ) ; fGraphViewer . setContentProvider ( new DiagContentProvider ( ) ) ; fGraphViewer . setLabelProvider ( ( IBaseLabelProvider ) fDiagLabelProvider ) ; fGraphViewer . setInput ( fModel == null ? null : fModel . getNodes ( ) ) ; gd = new GridData ( ) ; gd . grabExcessVerticalSpace = true ; gd . grabExcessHorizontalSpace = true ; gd . horizontalAlignment = GridData . FILL ; gd . verticalAlignment = GridData . FILL ; fGraphViewer . getControl ( ) . setLayoutData ( gd ) ; } private void createTabFolder ( Composite parent ) { GridData gd ; fTabFolder = new CTabFolder ( parent , SWT . NONE ) ; fTabFolder . setSimple ( false ) ; gd = new GridData ( ) ; gd . grabExcessVerticalSpace = true ; gd . verticalAlignment = GridData . FILL ; gd . horizontalAlignment = GridData . FILL ; fTabFolder . setLayoutData ( gd ) ; fConfigTab = new CTabItem ( fTabFolder , SWT . NONE ) ; fConfigTab . setText ( "" ) ; fConfigTab . setImage ( SVDBIconUtils . getIcon ( SVDBIconUtils . CONFIG_OBJ ) ) ; fConfigTab . setControl ( new Composite ( fTabFolder , SWT . NONE ) ) ; ( ( Composite ) fConfigTab . getControl ( ) ) . setLayout ( new GridLayout ( ) ) ; createLayoutGroup ( ) ; createClassDetailsGroup ( ) ; createToolBarItems ( parent ) ; createListeners ( ) ; } private void createListeners ( ) { fGraphViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { if ( event . getSelection ( ) . isEmpty ( ) ) return ; IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; if ( sel . getFirstElement ( ) instanceof DiagNode ) { DiagNode dn = ( DiagNode ) sel . getFirstElement ( ) ; try { SVEditorUtil . openEditor ( dn . getSVDBItem ( ) ) ; } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } } } ) ; fGraphViewer . getGraphControl ( ) . addMouseListener ( new MouseListener ( ) { public void mouseUp ( MouseEvent e ) { } public void mouseDown ( MouseEvent e ) { IFigure figure = fGraphViewer . getGraphControl ( ) . getFigureAt ( e . x , e . y ) ; if ( figure == null ) { Set < DiagNode > nodesChanged = new HashSet < DiagNode > ( ) ; for ( Object item : fGraphViewer . getGraphControl ( ) . getGraph ( ) . getSelection ( ) ) { if ( ! ( item instanceof CGraphNode ) ) { continue ; } CGraphNode graphNode = ( CGraphNode ) item ; if ( ! ( graphNode . getData ( ) instanceof DiagNode ) ) { continue ; } DiagNode dNode = ( DiagNode ) graphNode . getData ( ) ; dNode . setSelected ( false ) ; nodesChanged . add ( dNode ) ; } if ( nodesChanged . size ( ) != ) { fGraphViewer . refresh ( ) ; } fGraphViewer . getGraphControl ( ) . getGraph ( ) . setSelection ( null ) ; } } public void mouseDoubleClick ( MouseEvent e ) { } } ) ; fGraphViewer . getGraphControl ( ) . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { if ( ! ( e . widget instanceof Graph ) ) { return ; } Graph graph = ( Graph ) e . widget ; Set < DiagNode > nodesChanged = new HashSet < DiagNode > ( ) ; for ( Object obj : graph . getNodes ( ) ) { if ( ! ( obj instanceof CGraphNode ) ) { continue ; } CGraphNode graphNode = ( CGraphNode ) obj ; if ( ! ( graphNode . getData ( ) instanceof DiagNode ) ) { continue ; } DiagNode dNode = ( DiagNode ) graphNode . getData ( ) ; if ( dNode . getSelected ( ) ) { dNode . setSelected ( false ) ; nodesChanged . add ( dNode ) ; } } for ( Object item : fGraphViewer . getGraphControl ( ) . getGraph ( ) . getSelection ( ) ) { if ( ! ( item instanceof CGraphNode ) ) { continue ; } CGraphNode graphNode = ( CGraphNode ) item ; if ( ! ( graphNode . getData ( ) instanceof DiagNode ) ) { continue ; } DiagNode dNode = ( DiagNode ) graphNode . getData ( ) ; dNode . setSelected ( true ) ; nodesChanged . add ( dNode ) ; } if ( nodesChanged . size ( ) != ) { fGraphViewer . refresh ( ) ; } } } ) ; } private void createToolBarItems ( Composite parent ) { IToolBarManager tbm = getViewSite ( ) . getActionBars ( ) . getToolBarManager ( ) ; final Shell shell = parent . getShell ( ) ; tbm . add ( new Action ( "" , Action . AS_PUSH_BUTTON ) { { setImageDescriptor ( PlatformUI . getWorkbench ( ) . getSharedImages ( ) . getImageDescriptor ( ISharedImages . IMG_ETOOL_SAVEAS_EDIT ) ) ; } public void run ( ) { FileDialog fileDialog = new FileDialog ( shell , SWT . SAVE ) ; fileDialog . setText ( "" ) ; fileDialog . setFilterExtensions ( new String [ ] { "" } ) ; fileDialog . setFilterNames ( new String [ ] { "" } ) ; String selected = fileDialog . open ( ) ; if ( selected != null ) { ScalableFigure figure = fGraphViewer . getGraphControl ( ) . getRootLayer ( ) ; Rectangle bounds = figure . getBounds ( ) ; Control srcCanvas = fGraphViewer . getGraphControl ( ) ; GC srcGC = new GC ( srcCanvas ) ; Image destImg = new Image ( null , bounds . width , bounds . height ) ; GC destImgGC = new GC ( destImg ) ; destImgGC . setBackground ( srcGC . getBackground ( ) ) ; destImgGC . setForeground ( srcGC . getForeground ( ) ) ; destImgGC . setFont ( srcGC . getFont ( ) ) ; destImgGC . setLineStyle ( srcGC . getLineStyle ( ) ) ; destImgGC . setLineWidth ( srcGC . getLineWidth ( ) ) ; Graphics dstImgGraphics = new SWTGraphics ( destImgGC ) ; figure . paint ( dstImgGraphics ) ; ImageLoader imgLoader = new ImageLoader ( ) ; imgLoader . data = new ImageData [ ] { destImg . getImageData ( ) } ; imgLoader . save ( selected , SWT . IMAGE_PNG ) ; destImg . dispose ( ) ; destImgGC . dispose ( ) ; } } } ) ; } private void createClassDetailsGroup ( ) { Group group ; Button button = null ; group = new Group ( ( Composite ) fConfigTab . getControl ( ) , SWT . NONE ) ; group . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; group . setLayout ( new RowLayout ( SWT . VERTICAL ) ) ; group . setText ( "" ) ; button = new Button ( group , SWT . CHECK ) ; button . setText ( "" ) ; button . setSelection ( true ) ; fDiagLabelProvider . setIncludePrivateTasksFunctions ( true ) ; button . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fDiagLabelProvider . setIncludePublicTasksFunctions ( ( ( Button ) ( e . widget ) ) . getSelection ( ) ) ; fDiagLabelProvider . setIncludePrivateTasksFunctions ( ( ( Button ) ( e . widget ) ) . getSelection ( ) ) ; updateInputNoLayout ( ) ; } } ) ; button = new Button ( group , SWT . CHECK ) ; button . setText ( "" ) ; button . setSelection ( true ) ; fDiagLabelProvider . setIncludePrivateClassFields ( true ) ; button . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fDiagLabelProvider . setIncludePublicClassFields ( ( ( Button ) ( e . widget ) ) . getSelection ( ) ) ; fDiagLabelProvider . setIncludePrivateClassFields ( ( ( Button ) ( e . widget ) ) . getSelection ( ) ) ; updateInputNoLayout ( ) ; } } ) ; button = new Button ( group , SWT . CHECK ) ; button . setText ( "" ) ; button . setSelection ( false ) ; fDiagLabelProvider . setShowFieldTypes ( false ) ; button . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fDiagLabelProvider . setShowFieldTypes ( ( ( Button ) ( e . widget ) ) . getSelection ( ) ) ; updateInputNoLayout ( ) ; } } ) ; } @ SuppressWarnings ( "" ) private void createRoutingGroup ( ) { Group group ; group = new Group ( ( Composite ) fConfigTab . getControl ( ) , SWT . NONE ) ; group . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; group . setLayout ( new RowLayout ( SWT . VERTICAL ) ) ; group . setText ( "" ) ; Button routingButtons [ ] = new Button [ ] ; routingButtons [ ] = new Button ( group , SWT . RADIO ) ; routingButtons [ ] . setText ( "" ) ; routingButtons [ ] . setSelection ( true ) ; fDiagLabelProvider . setSVDiagRouter ( new ManhattanConnectionRouter ( ) ) ; routingButtons [ ] . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fDiagLabelProvider . setSVDiagRouter ( new ManhattanConnectionRouter ( ) ) ; fGraphViewer . setInput ( fModel . getNodes ( ) ) ; } } ) ; routingButtons [ ] = new Button ( group , SWT . RADIO ) ; routingButtons [ ] . setText ( "" ) ; routingButtons [ ] . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fDiagLabelProvider . setSVDiagRouter ( new FanRouter ( ) ) ; fGraphViewer . setInput ( fModel . getNodes ( ) ) ; } } ) ; } private void createLayoutGroup ( ) { Group group ; group = new Group ( ( Composite ) fConfigTab . getControl ( ) , SWT . NONE ) ; group . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; group . setLayout ( new RowLayout ( SWT . VERTICAL ) ) ; group . setText ( "" ) ; Button layoutRadios [ ] = new Button [ ] ; layoutRadios [ ] = new Button ( group , SWT . RADIO ) ; layoutRadios [ ] . setText ( "" ) ; layoutRadios [ ] . setSelection ( true ) ; layoutRadios [ ] . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fGraphViewer . setLayoutAlgorithm ( new GridLayoutAlgorithm ( LayoutStyles . NO_LAYOUT_NODE_RESIZING ) ) ; fGraphViewer . applyLayout ( ) ; } } ) ; layoutRadios [ ] = new Button ( group , SWT . RADIO ) ; layoutRadios [ ] . setText ( "" ) ; layoutRadios [ ] . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fGraphViewer . setLayoutAlgorithm ( new RadialLayoutAlgorithm ( LayoutStyles . NO_LAYOUT_NODE_RESIZING ) ) ; fGraphViewer . applyLayout ( ) ; } } ) ; layoutRadios [ ] = new Button ( group , SWT . RADIO ) ; layoutRadios [ ] . setText ( "" ) ; layoutRadios [ ] . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fGraphViewer . setLayoutAlgorithm ( new TreeLayoutAlgorithm ( LayoutStyles . NO_LAYOUT_NODE_RESIZING ) ) ; fGraphViewer . applyLayout ( ) ; } } ) ; } private void updateInputNoLayout ( ) { fGraphViewer . setLayoutAlgorithm ( new LeaveEmBeLayoutAlgoritm ( SWT . NONE ) ) ; fGraphViewer . setInput ( fModel . getNodes ( ) ) ; } @ Override public void init ( IViewSite site ) throws PartInitException { super . init ( site ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { fTabFolder . setSelection ( fConfigTab ) ; } public void widgetSelected ( SelectionEvent e ) { fTabFolder . setSelection ( fConfigTab ) ; } public void setFocus ( ) { fTabFolder . setSelection ( fConfigTab ) ; } public AbstractZoomableViewer getZoomableViewer ( ) { return fGraphViewer ; } public void setTarget ( DiagModel model , IDiagModelFactory factory , ISVDBIndex index ) { if ( model == null || factory == null || index == null ) { return ; } fModel = model ; fModelFactory = factory ; fNewDiagramForClassHandler . setSVDBIndex ( index ) ; fGraphViewer . setInput ( fModel . getNodes ( ) ) ; fGraphViewer . setLayoutAlgorithm ( new GridLayoutAlgorithm ( LayoutStyles . NO_LAYOUT_NODE_RESIZING ) ) ; } public void setViewState ( int state ) { IWorkbenchPage page = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) ; int currentState = page . getPartState ( page . getReference ( this ) ) ; if ( currentState != state ) { page . activate ( this ) ; page . setPartState ( page . getReference ( this ) , state ) ; } } } package net . sf . sveditor . ui . views . diagram ; import org . eclipse . draw2d . AbstractRouter ; public interface IDiagLabelProviderConfig { boolean getIncludePrivateClassFields ( ) ; boolean getIncludePublicClassFields ( ) ; boolean getIncludePrivateTasksFunctions ( ) ; boolean getIncludePublicTasksFunctions ( ) ; boolean getShowFieldTypes ( ) ; void setIncludePrivateClassFields ( boolean include ) ; void setIncludePublicClassFields ( boolean include ) ; void setIncludePrivateTasksFunctions ( boolean include ) ; void setIncludePublicTasksFunctions ( boolean include ) ; void setShowFieldTypes ( boolean show ) ; void setSVDiagRouter ( AbstractRouter router ) ; } package net . sf . sveditor . ui . views . diagram . contributions ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . diagrams . ClassDiagModelFactory ; import net . sf . sveditor . core . diagrams . DiagModel ; import net . sf . sveditor . core . diagrams . IDiagModelFactory ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . views . diagram . SVDiagramView ; import org . eclipse . core . commands . AbstractHandler ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . core . commands . IHandler ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; public class NewDiagramForClassHandler extends AbstractHandler implements IHandler { private ISVDBIndex fSVDBIndex ; public NewDiagramForClassHandler ( ) { } public void setSVDBIndex ( ISVDBIndex index ) { fSVDBIndex = index ; } public Object execute ( ExecutionEvent event ) throws ExecutionException { if ( event . getApplicationContext ( ) instanceof SVDBClassDecl && fSVDBIndex != null ) { SVDBClassDecl classDecl = ( SVDBClassDecl ) event . getApplicationContext ( ) ; IDiagModelFactory factory = new ClassDiagModelFactory ( fSVDBIndex , classDecl ) ; IWorkbench workbench = PlatformUI . getWorkbench ( ) ; IWorkbenchPage page = workbench . getActiveWorkbenchWindow ( ) . getActivePage ( ) ; IViewPart view ; try { if ( ( view = page . findView ( SVUiPlugin . PLUGIN_ID + "" ) ) == null ) { view = page . showView ( SVUiPlugin . PLUGIN_ID + "" ) ; } DiagModel model = factory . build ( ) ; if ( model == null ) { return null ; } page . activate ( view ) ; ( ( SVDiagramView ) view ) . setViewState ( IWorkbenchPage . STATE_MAXIMIZED ) ; ( ( SVDiagramView ) view ) . setTarget ( model , factory , fSVDBIndex ) ; } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } return null ; } } package net . sf . sveditor . ui . views . diagram . contributions ; import java . util . Collections ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . diagrams . DiagNode ; import net . sf . sveditor . ui . SVDBIconUtils ; import net . sf . sveditor . ui . views . diagram . SVDiagramView ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . core . commands . IHandler ; import org . eclipse . jface . action . ContributionItem ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; public class NewDiagramForClassContributionItem extends ContributionItem { protected final SVDiagramView fDiagramView ; protected final IHandler fHandler ; boolean fEnabled = false ; private MenuItem fMenuItem ; private SVDBClassDecl fClassDecl ; public NewDiagramForClassContributionItem ( SVDiagramView diagramView , IHandler handler ) { fDiagramView = diagramView ; fHandler = handler ; fDiagramView . getGraphViewer ( ) . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { ISelection selection = event . getSelection ( ) ; fEnabled = false ; fClassDecl = null ; if ( ! selection . isEmpty ( ) && selection instanceof IStructuredSelection ) { IStructuredSelection structuredSel = ( IStructuredSelection ) selection ; if ( structuredSel . size ( ) == ) { if ( structuredSel . getFirstElement ( ) instanceof DiagNode ) { DiagNode node = ( DiagNode ) structuredSel . getFirstElement ( ) ; if ( node . getSVDBItem ( ) instanceof SVDBClassDecl ) { fEnabled = true ; fClassDecl = ( SVDBClassDecl ) node . getSVDBItem ( ) ; } } } } updateEnablement ( ) ; } } ) ; } @ Override public boolean isDynamic ( ) { return true ; } protected void updateEnablement ( ) { if ( fMenuItem != null ) { fMenuItem . setEnabled ( fEnabled ) ; } } @ Override public void fill ( Menu menu , int index ) { if ( fClassDecl == null ) { return ; } fMenuItem = new MenuItem ( menu , SWT . NONE , index ) ; fMenuItem . setText ( "" + fClassDecl . getName ( ) + "" ) ; fMenuItem . setImage ( SVDBIconUtils . getIcon ( fClassDecl ) ) ; fMenuItem . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { run ( ) ; } } ) ; updateEnablement ( ) ; } protected void run ( ) { ExecutionEvent event = new ExecutionEvent ( null , Collections . EMPTY_MAP , null , fClassDecl ) ; try { fHandler . execute ( event ) ; } catch ( ExecutionException e ) { } } } package net . sf . sveditor . ui . views . diagram . figures ; import org . eclipse . draw2d . ColorConstants ; import org . eclipse . draw2d . Figure ; import org . eclipse . draw2d . Label ; import org . eclipse . draw2d . LineBorder ; import org . eclipse . draw2d . ToolbarLayout ; import org . eclipse . swt . graphics . Color ; public class UMLClassFigure extends Figure { public static Color classColor = null ; private CompartmentFigure attributeFigure = new CompartmentFigure ( ) ; private CompartmentFigure methodFigure = new CompartmentFigure ( ) ; public UMLClassFigure ( Label name , boolean isSelected ) { ToolbarLayout layout = new ToolbarLayout ( ) ; setLayoutManager ( layout ) ; setBorder ( new LineBorder ( ColorConstants . black , isSelected ? : ) ) ; if ( UMLClassFigure . classColor == null ) { UMLClassFigure . classColor = new Color ( null , , , ) ; } setBackgroundColor ( UMLClassFigure . classColor ) ; setOpaque ( true ) ; add ( name ) ; add ( attributeFigure ) ; add ( methodFigure ) ; } public CompartmentFigure getAttributesCompartment ( ) { return attributeFigure ; } public CompartmentFigure getMethodsCompartment ( ) { return methodFigure ; } } package net . sf . sveditor . ui . views . diagram . figures ; import org . eclipse . draw2d . AbstractBorder ; import org . eclipse . draw2d . Figure ; import org . eclipse . draw2d . Graphics ; import org . eclipse . draw2d . IFigure ; import org . eclipse . draw2d . ToolbarLayout ; import org . eclipse . draw2d . geometry . Insets ; public class CompartmentFigure extends Figure { public CompartmentFigure ( ) { ToolbarLayout layout = new ToolbarLayout ( ) ; layout . setMinorAlignment ( ToolbarLayout . ALIGN_TOPLEFT ) ; layout . setStretchMinorAxis ( false ) ; layout . setSpacing ( ) ; setLayoutManager ( layout ) ; setBorder ( new CompartmentFigureBorder ( ) ) ; } class CompartmentFigureBorder extends AbstractBorder { public Insets getInsets ( IFigure figure ) { return new Insets ( , , , ) ; } public void paint ( IFigure figure , Graphics graphics , Insets insets ) { graphics . drawLine ( getPaintRectangle ( figure , insets ) . getTopLeft ( ) , tempRect . getTopRight ( ) ) ; } } } package net . sf . sveditor . ui . views . diagram ; import org . eclipse . zest . layouts . algorithms . AbstractLayoutAlgorithm ; import org . eclipse . zest . layouts . dataStructures . InternalNode ; import org . eclipse . zest . layouts . dataStructures . InternalRelationship ; public class LeaveEmBeLayoutAlgoritm extends AbstractLayoutAlgorithm { public LeaveEmBeLayoutAlgoritm ( int styles ) { super ( styles ) ; } @ Override public void setLayoutArea ( double x , double y , double width , double height ) { } @ Override protected boolean isValidConfiguration ( boolean asynchronous , boolean continuous ) { return true ; } @ Override protected void applyLayoutInternal ( InternalNode [ ] entitiesToLayout , InternalRelationship [ ] relationshipsToConsider , double boundsX , double boundsY , double boundsWidth , double boundsHeight ) { } @ Override protected void preLayoutAlgorithm ( InternalNode [ ] entitiesToLayout , InternalRelationship [ ] relationshipsToConsider , double x , double y , double width , double height ) { } @ Override protected void postLayoutAlgorithm ( InternalNode [ ] entitiesToLayout , InternalRelationship [ ] relationshipsToConsider ) { } @ Override protected int getTotalNumberOfLayoutSteps ( ) { return ; } @ Override protected int getCurrentLayoutStep ( ) { return ; } } package net . sf . sveditor . ui . views . diagram ; import java . util . HashSet ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . diagrams . DiagConnection ; import net . sf . sveditor . core . diagrams . DiagNode ; import net . sf . sveditor . ui . SVDBIconUtils ; import net . sf . sveditor . ui . views . diagram . figures . UMLClassFigure ; import org . eclipse . draw2d . ConnectionRouter ; import org . eclipse . draw2d . IFigure ; import org . eclipse . draw2d . Label ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . eclipse . zest . core . viewers . EntityConnectionData ; import org . eclipse . zest . core . viewers . IConnectionStyleProvider ; import org . eclipse . zest . core . viewers . IFigureProvider ; import org . eclipse . zest . core . widgets . ZestStyles ; public class DiagLabelProvider extends AbstractDiagLabelProvider implements IFigureProvider , IConnectionStyleProvider { final HashSet < String > fExcludedUVMMembers ; public DiagLabelProvider ( ) { fExcludedUVMMembers = new HashSet < String > ( ) ; createExcludeLists ( ) ; } private void createExcludeLists ( ) { fExcludedUVMMembers . add ( "" ) ; fExcludedUVMMembers . add ( "" ) ; fExcludedUVMMembers . add ( "" ) ; fExcludedUVMMembers . add ( "" ) ; fExcludedUVMMembers . add ( "" ) ; fExcludedUVMMembers . add ( "" ) ; fExcludedUVMMembers . add ( "" ) ; } @ Override public String getText ( Object element ) { if ( element instanceof DiagNode ) { DiagNode myNode = ( DiagNode ) element ; return myNode . getName ( ) ; } if ( element instanceof DiagConnection ) { DiagConnection myConnection = ( DiagConnection ) element ; return myConnection . getLabel ( ) ; } if ( element instanceof EntityConnectionData ) { return "" ; } throw new RuntimeException ( "" + element . getClass ( ) . toString ( ) ) ; } @ Override public Image getImage ( Object element ) { if ( element instanceof DiagNode ) { DiagNode myNode = ( DiagNode ) element ; if ( myNode . getSVDBItem ( ) . getType ( ) == SVDBItemType . ClassDecl ) { return SVDBIconUtils . getIcon ( myNode . getSVDBItem ( ) ) ; } } return null ; } public IFigure getFigure ( Object element ) { if ( element instanceof DiagNode ) { DiagNode myNode = ( DiagNode ) element ; if ( myNode . getSVDBItem ( ) . getType ( ) == SVDBItemType . ClassDecl ) { return createClassFigure ( myNode ) ; } } return null ; } public IFigure createClassFigure ( DiagNode node ) { if ( node . getSVDBItem ( ) . getType ( ) != SVDBItemType . ClassDecl ) { return null ; } SVDBClassDecl classDecl = ( SVDBClassDecl ) node . getSVDBItem ( ) ; Label classLabel1 = new Label ( classDecl . getName ( ) , SVDBIconUtils . getIcon ( classDecl ) ) ; UMLClassFigure classFigure = new UMLClassFigure ( classLabel1 , node . getSelected ( ) ) ; if ( getIncludePrivateClassFields ( ) ) { for ( SVDBVarDeclItem declItem : node . getMemberDecls ( ) ) { String typeName = "" ; if ( declItem . getParent ( ) != null ) { typeName = declItem . getParent ( ) . getTypeName ( ) ; } else { continue ; } if ( fExcludedUVMMembers . contains ( declItem . getName ( ) ) ) { continue ; } String labelString = getShowFieldTypes ( ) ? typeName + "" + declItem . getName ( ) : declItem . getName ( ) + "" ; classFigure . getAttributesCompartment ( ) . add ( new Label ( labelString , SVDBIconUtils . getIcon ( declItem ) ) ) ; } } if ( getIncludePrivateTasksFunctions ( ) ) { for ( SVDBFunction funcItem : node . getFuncDecls ( ) ) { if ( fExcludedUVMMembers . contains ( funcItem . getName ( ) ) ) { continue ; } classFigure . getMethodsCompartment ( ) . add ( new Label ( funcItem . getName ( ) + "" , SVDBIconUtils . getIcon ( funcItem ) ) ) ; } for ( SVDBTask taskItem : node . getTaskDecls ( ) ) { if ( fExcludedUVMMembers . contains ( taskItem . getName ( ) ) ) { continue ; } classFigure . getMethodsCompartment ( ) . add ( new Label ( taskItem . getName ( ) + "" , SVDBIconUtils . getIcon ( taskItem ) ) ) ; } } classFigure . setSize ( - , - ) ; return classFigure ; } public int getConnectionStyle ( Object rel ) { int res = ; if ( rel instanceof EntityConnectionData ) { EntityConnectionData ecd = ( EntityConnectionData ) rel ; if ( ecd . source instanceof DiagNode && ecd . dest instanceof DiagNode ) { DiagNode srcNode = ( DiagNode ) ecd . source ; DiagNode dstNode = ( DiagNode ) ecd . dest ; if ( srcNode . getSuperClasses ( ) . contains ( dstNode ) ) { res |= ZestStyles . CONNECTIONS_SOLID ; } else { res |= ZestStyles . CONNECTIONS_DASH ; } } } res |= ZestStyles . CONNECTIONS_DIRECTED ; return res ; } public Color getColor ( Object rel ) { return null ; } public Color getHighlightColor ( Object rel ) { return null ; } public int getLineWidth ( Object rel ) { return ; } public IFigure getTooltip ( Object entity ) { return null ; } public ConnectionRouter getRouter ( Object rel ) { if ( rel instanceof EntityConnectionData ) { return getSVDiagRouter ( ) ; } else { return null ; } } } package net . sf . sveditor . ui . views . diagram ; import net . sf . sveditor . core . diagrams . DiagNode ; import org . eclipse . jface . viewers . ArrayContentProvider ; import org . eclipse . zest . core . viewers . IGraphEntityContentProvider ; public class DiagContentProvider extends ArrayContentProvider implements IGraphEntityContentProvider { public Object [ ] getConnectedTo ( Object entity ) { if ( entity instanceof DiagNode ) { DiagNode node = ( DiagNode ) entity ; return node . getConnectedTo ( ) . toArray ( ) ; } throw new RuntimeException ( "" ) ; } } package net . sf . sveditor . ui . views . diagram ; import org . eclipse . draw2d . AbstractRouter ; import org . eclipse . jface . viewers . LabelProvider ; public class AbstractDiagLabelProvider extends LabelProvider implements IDiagLabelProviderConfig { private boolean fIncludePrivateClassFields ; private boolean fIncludePublicClassFields ; private boolean fIncludePrivateClassTasksFunctions ; private boolean fIncludePublicClassTasksFunctions ; private boolean fShowFieldTypes ; private AbstractRouter fRouter ; public boolean getIncludePrivateClassFields ( ) { return fIncludePrivateClassFields ; } public boolean getIncludePublicClassFields ( ) { return fIncludePublicClassFields ; } public boolean getIncludePrivateTasksFunctions ( ) { return fIncludePrivateClassTasksFunctions ; } public boolean getIncludePublicTasksFunctions ( ) { return fIncludePublicClassTasksFunctions ; } public void setIncludePrivateClassFields ( boolean include ) { fIncludePrivateClassFields = include ; } public void setIncludePublicClassFields ( boolean include ) { fIncludePublicClassFields = include ; } public void setIncludePrivateTasksFunctions ( boolean include ) { fIncludePrivateClassTasksFunctions = include ; } public void setIncludePublicTasksFunctions ( boolean include ) { fIncludePublicClassTasksFunctions = include ; } public boolean getShowFieldTypes ( ) { return fShowFieldTypes ; } public void setShowFieldTypes ( boolean show ) { fShowFieldTypes = show ; } public void setSVDiagRouter ( AbstractRouter router ) { fRouter = router ; } public AbstractRouter getSVDiagRouter ( ) { return fRouter ; } } package net . sf . sveditor . ui . views . objects ; import net . sf . sveditor . core . objects . ObjectsTreeNode ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; public class SVObjectsViewerFilter extends ViewerFilter { private ObjectsTreeNode fTarget ; public void setTarget ( ObjectsTreeNode on ) { fTarget = on ; } @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( fTarget == null ) { return true ; } return true ; } } package net . sf . sveditor . ui . views . objects ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; public class SVObjectsViewerSorter extends ViewerSorter { @ Override public int compare ( Viewer viewer , Object e1 , Object e2 ) { return super . compare ( viewer , e1 , e2 ) ; } } package net . sf . sveditor . ui . views . objects ; import net . sf . sveditor . core . objects . ObjectsTreeNode ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . StyledString ; import org . eclipse . swt . graphics . Image ; public class ObjectsLabelProvider extends SVTreeLabelProvider { @ Override public Image getImage ( Object element ) { if ( element instanceof ObjectsTreeNode ) { ObjectsTreeNode n = ( ObjectsTreeNode ) element ; if ( n . getItemDecl ( ) != null ) { return super . getImage ( n . getItemDecl ( ) ) ; } else { return null ; } } return super . getImage ( element ) ; } @ Override public StyledString getStyledText ( Object element ) { if ( element instanceof ObjectsTreeNode ) { ObjectsTreeNode n = ( ObjectsTreeNode ) element ; if ( n . getItemDecl ( ) != null ) { return super . getStyledText ( n . getItemDecl ( ) ) ; } else { return new StyledString ( n . getName ( ) ) ; } } return super . getStyledText ( element ) ; } } package net . sf . sveditor . ui . views . objects ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . objects . ObjectsTreeNode ; import net . sf . sveditor . ui . SVDBIconUtils ; import net . sf . sveditor . ui . SVEditorUtil ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . ViewerComparator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . FilteredTree ; import org . eclipse . ui . dialogs . PatternFilter ; import org . eclipse . ui . part . ViewPart ; public class SVObjectsView extends ViewPart implements SelectionListener { private FilteredTree fObjectTree ; private TreeViewer fTreeViewer ; private PatternFilter fPatternFilter ; private ObjectsViewContentProvider fContentProvider ; @ Override public void createPartControl ( Composite parent ) { GridLayout gl ; gl = new GridLayout ( ) ; gl . marginHeight = ; gl . marginWidth = ; Composite class_c = new Composite ( parent , SWT . NONE ) ; class_c . setLayout ( gl ) ; class_c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fPatternFilter = new PatternFilter ( ) ; fObjectTree = new FilteredTree ( class_c , SWT . H_SCROLL | SWT . V_SCROLL , fPatternFilter , true ) ; fTreeViewer = fObjectTree . getViewer ( ) ; fTreeViewer . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fTreeViewer . setContentProvider ( fContentProvider = new ObjectsViewContentProvider ( ) ) ; fTreeViewer . setLabelProvider ( new ObjectsLabelProvider ( ) ) ; fTreeViewer . setInput ( SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ) ; fTreeViewer . setComparator ( new ViewerComparator ( ) ) ; fTreeViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; if ( sel . getFirstElement ( ) instanceof ObjectsTreeNode ) { ObjectsTreeNode n = ( ObjectsTreeNode ) sel . getFirstElement ( ) ; if ( n == fContentProvider . getModulesNode ( ) || n == fContentProvider . getInterfacesNode ( ) || n == fContentProvider . getPackagesNode ( ) ) { fTreeViewer . setExpandedState ( n , ! fTreeViewer . getExpandedState ( n ) ) ; } else if ( n . getItemDecl ( ) . getType ( ) == SVDBItemType . PackageDecl ) { fTreeViewer . setExpandedState ( n , ! fTreeViewer . getExpandedState ( n ) ) ; } else { if ( n . getItemDecl ( ) != null ) { try { if ( n . getItemDecl ( ) != null && n . getItemDecl ( ) . getFile ( ) != null ) { SVEditorUtil . openEditor ( n . getItemDecl ( ) . getFile ( ) ) ; } } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } } } } } ) ; } @ Override public void init ( IViewSite site ) throws PartInitException { super . init ( site ) ; IToolBarManager tbm = site . getActionBars ( ) . getToolBarManager ( ) ; tbm . add ( new Action ( "" , Action . AS_PUSH_BUTTON ) { { setImageDescriptor ( PlatformUI . getWorkbench ( ) . getSharedImages ( ) . getImageDescriptor ( ISharedImages . IMG_ELCL_COLLAPSEALL ) ) ; } public void run ( ) { fTreeViewer . collapseAll ( ) ; } } ) ; tbm . add ( new Action ( "" , Action . AS_PUSH_BUTTON ) { { setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . InterfaceDecl ) ) ; } public void run ( ) { if ( fContentProvider . getInterfacesNode ( ) != null ) { fTreeViewer . collapseAll ( ) ; fTreeViewer . expandToLevel ( fContentProvider . getInterfacesNode ( ) , TreeViewer . ALL_LEVELS ) ; } } } ) ; tbm . add ( new Action ( "" , Action . AS_PUSH_BUTTON ) { { setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . ModuleDecl ) ) ; } public void run ( ) { if ( fContentProvider . getModulesNode ( ) != null ) { fTreeViewer . collapseAll ( ) ; fTreeViewer . expandToLevel ( fContentProvider . getModulesNode ( ) , TreeViewer . ALL_LEVELS ) ; } } } ) ; tbm . add ( new Action ( "" , Action . AS_PUSH_BUTTON ) { { setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . PackageDecl ) ) ; } public void run ( ) { if ( fContentProvider . getPackagesNode ( ) != null ) { fTreeViewer . collapseAll ( ) ; fTreeViewer . expandToLevel ( fContentProvider . getPackagesNode ( ) , ) ; } } } ) ; tbm . add ( new Action ( "" , Action . AS_PUSH_BUTTON ) { { setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . ClassDecl ) ) ; } public void run ( ) { if ( fContentProvider . getPackagesNode ( ) != null ) { fTreeViewer . collapseAll ( ) ; fTreeViewer . expandToLevel ( fContentProvider . getPackagesNode ( ) , TreeViewer . ALL_LEVELS ) ; } } } ) ; tbm . add ( new Action ( "" , Action . AS_PUSH_BUTTON ) { { setImageDescriptor ( PlatformUI . getWorkbench ( ) . getSharedImages ( ) . getImageDescriptor ( ISharedImages . IMG_TOOL_REDO ) ) ; } public void run ( ) { fTreeViewer . setInput ( SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ) ; } } ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { } public void setFocus ( ) { } } package net . sf . sveditor . ui . views . objects ; import java . util . List ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . objects . ObjectsTreeFactory ; import net . sf . sveditor . core . objects . ObjectsTreeNode ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class ObjectsViewContentProvider implements ITreeContentProvider { private static final Object fEmptyArray [ ] = new Object [ ] ; private SVDBIndexRegistry fIndexRegistry ; private ObjectsTreeNode fNodeModules ; private ObjectsTreeNode fNodeInterface ; private ObjectsTreeNode fNodePackages ; public ObjectsTreeNode getModulesNode ( ) { return fNodeModules ; } public ObjectsTreeNode getInterfacesNode ( ) { return fNodeInterface ; } public ObjectsTreeNode getPackagesNode ( ) { return fNodePackages ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof ObjectsTreeNode ) { return ( ( ObjectsTreeNode ) parentElement ) . getChildren ( ) . toArray ( ) ; } else { return fEmptyArray ; } } public Object getParent ( Object element ) { if ( element instanceof ObjectsTreeNode ) { return ( ( ObjectsTreeNode ) element ) . getParent ( ) ; } else { return null ; } } public boolean hasChildren ( Object element ) { if ( element instanceof ObjectsTreeNode ) { return ( ( ( ObjectsTreeNode ) element ) . getChildren ( ) . size ( ) > ) ; } else { return false ; } } public Object [ ] getElements ( Object inputElement ) { List < ISVDBIndex > projectIndexList = fIndexRegistry . getAllProjectLists ( ) ; ObjectsTreeFactory factory = new ObjectsTreeFactory ( projectIndexList ) ; ObjectsTreeNode topNode = factory . build ( ) ; if ( topNode == null ) { return fEmptyArray ; } else { fNodeInterface = topNode . getChildByName ( ObjectsTreeNode . INTERFACES_NODE ) ; fNodeModules = topNode . getChildByName ( ObjectsTreeNode . MODULES_NODE ) ; fNodePackages = topNode . getChildByName ( ObjectsTreeNode . PACKAGES_NODE ) ; return topNode . getChildren ( ) . toArray ( ) ; } } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fIndexRegistry = ( SVDBIndexRegistry ) newInput ; } } package net . sf . sveditor . ui . views . hierarchy ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; public class SVHierarchyViewerSorter extends ViewerSorter { @ Override public int compare ( Viewer viewer , Object e1 , Object e2 ) { return super . compare ( viewer , e1 , e2 ) ; } } package net . sf . sveditor . ui . views . hierarchy ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . hierarchy . HierarchyTreeNode ; import net . sf . sveditor . ui . SVEditorUtil ; import net . sf . sveditor . ui . svcp . SVDBDecoratingLabelProvider ; import net . sf . sveditor . ui . svcp . SVTreeContentProvider ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . IElementComparer ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . part . ViewPart ; public class SVHierarchyView extends ViewPart implements SelectionListener { private TreeViewer fClassTree ; private TableViewer fMemberList ; private HierarchyTreeNode fTarget ; private HierarchyTreeNode fRoot ; private SVTreeContentProvider fMemberContentProvider ; private Composite fMemberComposite ; private Label fSelectedClass ; private SVHierarchyViewerFilter fViewerFilter ; private Button fShowInheritedMembers ; @ Override public void createPartControl ( Composite parent ) { SashForm sash = new SashForm ( parent , SWT . VERTICAL ) ; GridLayout gl ; gl = new GridLayout ( ) ; gl . marginHeight = ; gl . marginWidth = ; Composite class_c = new Composite ( sash , SWT . NONE ) ; class_c . setLayout ( gl ) ; class_c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fClassTree = new TreeViewer ( class_c ) ; fClassTree . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fClassTree . setContentProvider ( new HierarchyTreeContentProvider ( ) ) ; fClassTree . setLabelProvider ( new HierarchyTreeLabelProvider ( ) ) ; fClassTree . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; Object elem = sel . getFirstElement ( ) ; if ( elem instanceof HierarchyTreeNode ) { HierarchyTreeNode hn = ( HierarchyTreeNode ) elem ; fViewerFilter . setTarget ( hn ) ; fSelectedClass . setText ( hn . getName ( ) ) ; if ( hn . getItemDecl ( ) != null ) { ISVDBChildItem it = hn . getItemDecl ( ) ; if ( it . getType ( ) == SVDBItemType . ClassDecl ) { fMemberList . setInput ( it ) ; } else if ( it . getType ( ) . isElemOf ( SVDBItemType . ModIfcInstItem , SVDBItemType . VarDeclItem ) ) { ISVDBItemBase type = hn . getItemType ( ) ; fMemberList . setInput ( type ) ; } else { fMemberList . setInput ( it ) ; } } else { fMemberList . setInput ( hn . getItemDecl ( ) ) ; } } else { fMemberList . setInput ( null ) ; fSelectedClass . setText ( "" ) ; fViewerFilter . setTarget ( null ) ; } fMemberComposite . layout ( true , true ) ; } } ) ; fClassTree . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; if ( sel . getFirstElement ( ) instanceof HierarchyTreeNode ) { HierarchyTreeNode n = ( HierarchyTreeNode ) sel . getFirstElement ( ) ; if ( n . getItemDecl ( ) != null ) { try { SVEditorUtil . openEditor ( n . getItemDecl ( ) ) ; } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } } } } ) ; sash . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fMemberComposite = new Composite ( sash , SWT . NO_TRIM ) ; fMemberComposite . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; gl = new GridLayout ( ) ; gl . marginHeight = ; gl . marginWidth = ; fMemberComposite . setLayout ( gl ) ; Composite member_action_bar = new Composite ( fMemberComposite , SWT . NONE ) ; gl = new GridLayout ( , true ) ; gl . marginHeight = ; member_action_bar . setLayout ( gl ) ; member_action_bar . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; fSelectedClass = new Label ( member_action_bar , SWT . NONE ) ; Composite member_button_bar = new Composite ( member_action_bar , SWT . NONE ) ; GridData gd = new GridData ( SWT . FILL , SWT . FILL , false , false ) ; gd . heightHint = ; member_button_bar . setLayoutData ( gd ) ; gl = new GridLayout ( , true ) ; gl . marginHeight = ; gl . marginWidth = ; member_button_bar . setLayout ( gl ) ; fMemberContentProvider = new SVTreeContentProvider ( ) ; fMemberList = new TableViewer ( fMemberComposite ) ; fMemberList . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fMemberList . setContentProvider ( fMemberContentProvider ) ; fMemberList . setLabelProvider ( new SVDBDecoratingLabelProvider ( new SVTreeLabelProvider ( ) ) ) ; fMemberList . setComparer ( new IElementComparer ( ) { public int hashCode ( Object element ) { return element . hashCode ( ) ; } public boolean equals ( Object a , Object b ) { return ( a == b ) ; } } ) ; fMemberList . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; if ( sel . getFirstElement ( ) instanceof SVDBItem ) { try { SVEditorUtil . openEditor ( ( ISVDBItemBase ) sel . getFirstElement ( ) ) ; } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } } } ) ; fViewerFilter = new SVHierarchyViewerFilter ( ) ; fMemberList . addFilter ( fViewerFilter ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { if ( e . item == fShowInheritedMembers ) { } } public void setTarget ( HierarchyTreeNode target ) { fTarget = target ; fRoot = target ; fViewerFilter . setTarget ( fTarget ) ; while ( fRoot . getParent ( ) != null ) { fRoot = fRoot . getParent ( ) ; } target = new HierarchyTreeNode ( null , "" ) ; fRoot . setParent ( target ) ; target . addChild ( fRoot ) ; fRoot = target ; Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { fClassTree . setInput ( fRoot ) ; fClassTree . setSelection ( new StructuredSelection ( fTarget ) , true ) ; fClassTree . expandToLevel ( fTarget , ) ; } } ) ; } @ Override public void setFocus ( ) { } } package net . sf . sveditor . ui . views . hierarchy ; import net . sf . sveditor . core . db . IFieldItemAttr ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFieldItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . hierarchy . HierarchyTreeNode ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; public class SVHierarchyViewerFilter extends ViewerFilter { private HierarchyTreeNode fTarget ; private boolean fShowInheritedMembers ; private boolean fHideFields ; private boolean fHideStatic ; private boolean fHideNonPublic ; public void setTarget ( HierarchyTreeNode target ) { fTarget = target ; } public void setShowInheritedMembers ( boolean show ) { fShowInheritedMembers = show ; } public void setHideFields ( boolean hide ) { fHideFields = hide ; } public void setHideStatic ( boolean hide ) { fHideStatic = hide ; } public void setHideNonPublic ( boolean hide ) { fHideNonPublic = hide ; } @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( fTarget == null ) { return true ; } if ( element instanceof ISVDBItemBase ) { ISVDBItemBase it = ( ISVDBItemBase ) element ; if ( ! fShowInheritedMembers ) { if ( fTarget . getItemDecl ( ) . getType ( ) == SVDBItemType . ClassDecl ) { if ( ! isInScope ( ( SVDBClassDecl ) fTarget . getItemDecl ( ) , it ) ) { return false ; } } } if ( fHideFields && SVDBStmt . isType ( it , SVDBItemType . VarDeclStmt ) ) { return false ; } if ( fHideStatic ) { if ( it instanceof SVDBFieldItem && ( ( ( SVDBFieldItem ) it ) . getAttr ( ) & IFieldItemAttr . FieldAttr_Static ) != ) { return false ; } else if ( it instanceof SVDBTask && ( ( ( SVDBTask ) it ) . getAttr ( ) & IFieldItemAttr . FieldAttr_Static ) != ) { return false ; } } if ( fHideNonPublic ) { if ( it instanceof SVDBFieldItem && ( ( ( ( SVDBFieldItem ) it ) . getAttr ( ) & IFieldItemAttr . FieldAttr_Local ) != || ( ( ( SVDBFieldItem ) it ) . getAttr ( ) & IFieldItemAttr . FieldAttr_Protected ) != ) ) { return false ; } else if ( it instanceof SVDBTask && ( ( ( ( SVDBTask ) it ) . getAttr ( ) & IFieldItemAttr . FieldAttr_Local ) != || ( ( ( SVDBTask ) it ) . getAttr ( ) & IFieldItemAttr . FieldAttr_Protected ) != ) ) { return false ; } } } return true ; } private boolean isInScope ( ISVDBScopeItem scope , ISVDBItemBase it ) { for ( ISVDBItemBase it_t : scope . getItems ( ) ) { if ( it_t == it ) { return true ; } else if ( it_t instanceof ISVDBScopeItem ) { if ( isInScope ( ( ISVDBScopeItem ) it_t , it ) ) { return true ; } } } return false ; } } package net . sf . sveditor . ui . views . hierarchy ; import net . sf . sveditor . core . hierarchy . HierarchyTreeNode ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class HierarchyTreeContentProvider implements ITreeContentProvider { private static final Object fEmptyArray [ ] = new Object [ ] ; public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof HierarchyTreeNode ) { return ( ( HierarchyTreeNode ) parentElement ) . getChildren ( ) . toArray ( ) ; } else { return fEmptyArray ; } } public Object getParent ( Object element ) { if ( element instanceof HierarchyTreeNode ) { return ( ( HierarchyTreeNode ) element ) . getParent ( ) ; } else { return null ; } } public boolean hasChildren ( Object element ) { if ( element instanceof HierarchyTreeNode ) { return ( ( ( HierarchyTreeNode ) element ) . getChildren ( ) . size ( ) > ) ; } else { return false ; } } public Object [ ] getElements ( Object inputElement ) { if ( inputElement instanceof HierarchyTreeNode ) { return ( ( HierarchyTreeNode ) inputElement ) . getChildren ( ) . toArray ( ) ; } else { return fEmptyArray ; } } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } } package net . sf . sveditor . ui . views . hierarchy ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class SVHierarchyContentProvider implements ITreeContentProvider { public Object [ ] getChildren ( Object parentElement ) { return null ; } public Object getParent ( Object element ) { return null ; } public boolean hasChildren ( Object element ) { return false ; } public Object [ ] getElements ( Object inputElement ) { return null ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } } package net . sf . sveditor . ui . views . hierarchy ; import net . sf . sveditor . core . hierarchy . HierarchyTreeNode ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . StyledString ; import org . eclipse . swt . graphics . Image ; public class HierarchyTreeLabelProvider extends SVTreeLabelProvider { @ Override public Image getImage ( Object element ) { if ( element instanceof HierarchyTreeNode ) { HierarchyTreeNode n = ( HierarchyTreeNode ) element ; if ( n . getItemDecl ( ) != null ) { return super . getImage ( n . getItemDecl ( ) ) ; } else { return null ; } } return super . getImage ( element ) ; } @ Override public StyledString getStyledText ( Object element ) { if ( element instanceof HierarchyTreeNode ) { HierarchyTreeNode n = ( HierarchyTreeNode ) element ; if ( n . getItemDecl ( ) != null ) { return super . getStyledText ( n . getItemDecl ( ) ) ; } else { return new StyledString ( n . getName ( ) ) ; } } return super . getStyledText ( element ) ; } } package net . sf . sveditor . ui ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . Job ; public class RefreshIndexJob extends Job { private List < ISVDBIndex > fIndexRebuildList ; private SVUiPlugin fParent ; private LogHandle fLog ; public RefreshIndexJob ( SVUiPlugin parent ) { super ( "" ) ; fIndexRebuildList = new ArrayList < ISVDBIndex > ( ) ; fParent = parent ; fLog = LogFactory . getLogHandle ( "" ) ; } public void addIndex ( ISVDBIndex index ) { synchronized ( fIndexRebuildList ) { fIndexRebuildList . add ( index ) ; } } public void addIndexList ( List < ISVDBIndex > list ) { synchronized ( fIndexRebuildList ) { fIndexRebuildList . addAll ( list ) ; } } @ Override protected IStatus run ( IProgressMonitor monitor ) { synchronized ( fIndexRebuildList ) { monitor . beginTask ( "" , * fIndexRebuildList . size ( ) ) ; } while ( true ) { ISVDBIndex index = null ; synchronized ( fIndexRebuildList ) { if ( fIndexRebuildList . size ( ) == ) { break ; } else { index = fIndexRebuildList . remove ( ) ; } } try { SubProgressMonitor sub ; sub = new SubProgressMonitor ( monitor , ) ; index . rebuildIndex ( sub ) ; index . loadIndex ( sub ) ; } catch ( Exception e ) { fLog . error ( "" + e . getMessage ( ) , e ) ; } } monitor . done ( ) ; fParent . refreshJobComplete ( ) ; return Status . OK_STATUS ; } } package net . sf . sveditor . ui ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . URI ; import net . sf . sveditor . core . Tuple ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . IURIEditorInput ; public class EditorInputUtils { public static Tuple < File , IFile > getFileLocation ( IEditorInput input ) { File file = null ; IFile ifile = null ; if ( input instanceof IFileEditorInput ) { ifile = ( ( IFileEditorInput ) input ) . getFile ( ) ; } else if ( input instanceof IURIEditorInput ) { URI uri = ( ( IURIEditorInput ) input ) . getURI ( ) ; file = new File ( uri . getPath ( ) ) ; } return new Tuple < File , IFile > ( file , ifile ) ; } public static InputStream openInputStream ( IEditorInput input ) { InputStream in = null ; if ( input instanceof IFileEditorInput ) { IFile file = ( ( IFileEditorInput ) input ) . getFile ( ) ; for ( int i = ; i < ; i ++ ) { try { in = file . getContents ( ) ; break ; } catch ( CoreException e ) { if ( e . getMessage ( ) . contains ( "" ) ) { try { file . getParent ( ) . refreshLocal ( IResource . DEPTH_INFINITE , new NullProgressMonitor ( ) ) ; } catch ( CoreException e2 ) { } } } } } else if ( input instanceof IURIEditorInput ) { URI uri = ( ( IURIEditorInput ) input ) . getURI ( ) ; try { in = new FileInputStream ( uri . getPath ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return in ; } public static void setContents ( IEditorInput input , InputStream in ) throws Exception { if ( input instanceof IFileEditorInput ) { IFile file = ( ( IFileEditorInput ) input ) . getFile ( ) ; file . setContents ( in , true , true , new NullProgressMonitor ( ) ) ; } else if ( input instanceof IURIEditorInput ) { OutputStream out = null ; URI uri = ( ( IURIEditorInput ) input ) . getURI ( ) ; byte tmp [ ] = new byte [ ] ; int len ; out = new FileOutputStream ( uri . getPath ( ) ) ; while ( ( len = in . read ( tmp , , tmp . length ) ) > ) { out . write ( tmp , , len ) ; } out . close ( ) ; } } } package net . sf . sveditor . ui ; public interface ISVIcons { String OBJ_ICONS = "" ; String FILE_OBJ = "" ; String MODULE_OBJ = OBJ_ICONS + "" ; String CONFIG_OBJ = OBJ_ICONS + "" ; String INT_OBJ = OBJ_ICONS + "" ; String CLASS_OBJ = OBJ_ICONS + "" ; String DEFINE_OBJ = OBJ_ICONS + "" ; String INCLUDE_OBJ = OBJ_ICONS + "" ; String PACKAGE_OBJ = OBJ_ICONS + "" ; String STRUCT_OBJ = OBJ_ICONS + "" ; String COVERGROUP_OBJ = OBJ_ICONS + "" ; String COVERPOINT_OBJ = OBJ_ICONS + "" ; String COVERPOINT_CROSS_OBJ = OBJ_ICONS + "" ; String SEQUENCE_OBJ = OBJ_ICONS + "" ; String PROPERTY_OBJ = OBJ_ICONS + "" ; String MOD_IFC_INST_OBJ = OBJ_ICONS + "" ; String LOCAL_OBJ = OBJ_ICONS + "" ; String ENUM_TYPE_OBJ = OBJ_ICONS + "" ; String TYPEDEF_TYPE_OBJ = OBJ_ICONS + "" ; String DECL_ICONS = "" ; String FIELD_PRIV_OBJ = DECL_ICONS + "" ; String FIELD_PROT_OBJ = DECL_ICONS + "" ; String FIELD_PUB_OBJ = DECL_ICONS + "" ; String CONSTRAINT_OBJ = OBJ_ICONS + "" ; String ALWAYS_BLOCK_OBJ = OBJ_ICONS + "" ; String INITIAL_OBJ = OBJ_ICONS + "" ; String ASSIGN_OBJ = OBJ_ICONS + "" ; String GENERATE_OBJ = OBJ_ICONS + "" ; String CLOCKING_OBJ = OBJ_ICONS + "" ; String TASK_PRIV_OBJ = DECL_ICONS + "" ; String TASK_PROT_OBJ = DECL_ICONS + "" ; String TASK_PUB_OBJ = DECL_ICONS + "" ; String IMPORT_OBJ = DECL_ICONS + "" ; } package net . sf . sveditor . ui . wizards ; import net . sf . sveditor . core . srcgen . NewPackageGenerator ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . IProgressMonitor ; public class NewSVPackageWizard extends AbstractNewSVItemFileWizard { public static final String ID = SVUiPlugin . PLUGIN_ID + "" ; public NewSVPackageWizard ( ) { super ( ) ; } @ Override protected AbstractNewSVItemFileWizardPage createPage ( ) { return new NewSVPackageWizardPage ( ) ; } @ Override protected void generate ( IProgressMonitor monitor , IFile file_path ) { NewPackageGenerator gen = new NewPackageGenerator ( ) ; gen . generate ( getIndexIterator ( monitor ) , file_path , fPage . getOption ( AbstractNewSVItemFileWizardPage . NAME , null ) , monitor ) ; } } package net . sf . sveditor . ui . wizards ; import java . lang . reflect . InvocationTargetException ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . ui . SVEditorUtil ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . wizards . newresource . BasicNewResourceWizard ; abstract public class AbstractNewSVItemFileWizard extends BasicNewResourceWizard { protected AbstractNewSVItemFileWizardPage fPage ; public AbstractNewSVItemFileWizard ( ) { super ( ) ; } abstract protected AbstractNewSVItemFileWizardPage createPage ( ) ; abstract protected void generate ( IProgressMonitor monitor , IFile file_path ) ; public void addPages ( ) { super . addPages ( ) ; fPage = createPage ( ) ; Object sel = getSelection ( ) . getFirstElement ( ) ; if ( sel != null && sel instanceof IResource ) { IResource r = ( IResource ) sel ; if ( ! ( r instanceof IContainer ) ) { r = r . getParent ( ) ; } fPage . setOption ( AbstractNewSVItemFileWizardPage . SOURCE_FOLDER , r . getFullPath ( ) . toOSString ( ) ) ; } addPage ( fPage ) ; } public void init ( IWorkbench workbench , IStructuredSelection selection ) { super . init ( workbench , selection ) ; setNeedsProgressMonitor ( true ) ; } protected ISVDBIndexIterator getIndexIterator ( IProgressMonitor monitor ) { ISVDBIndexIterator index_it = null ; if ( fPage . getProjectData ( ) != null ) { index_it = fPage . getProjectData ( ) . getProjectIndexMgr ( ) ; } return index_it ; } @ Override public boolean performFinish ( ) { IContainer c = SVFileUtils . getWorkspaceFolder ( fPage . getOption ( AbstractNewSVItemFileWizardPage . SOURCE_FOLDER , null ) ) ; final IFile file_path = c . getFile ( new Path ( fPage . getOption ( AbstractNewSVItemFileWizardPage . FILE_NAME , null ) ) ) ; IRunnableWithProgress op = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { generate ( monitor , file_path ) ; } } ; try { getContainer ( ) . run ( false , false , op ) ; } catch ( Exception e ) { return false ; } try { SVEditorUtil . openEditor ( "" + file_path . getFullPath ( ) ) ; } catch ( PartInitException e ) { e . printStackTrace ( ) ; } return true ; } } package net . sf . sveditor . ui . wizards ; import net . sf . sveditor . core . srcgen . NewClassGenerator ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . IProgressMonitor ; public class NewSVClassWizard extends AbstractNewSVItemFileWizard { public static final String ID = SVUiPlugin . PLUGIN_ID + "" ; public NewSVClassWizard ( ) { super ( ) ; } @ Override protected AbstractNewSVItemFileWizardPage createPage ( ) { return new NewSVClassWizardPage ( ) ; } @ Override protected void generate ( IProgressMonitor monitor , IFile file_path ) { NewClassGenerator gen = new NewClassGenerator ( ) ; gen . generate ( getIndexIterator ( monitor ) , file_path , fPage . getOption ( AbstractNewSVItemFileWizardPage . NAME , null ) , fPage . getOption ( NewSVClassWizardPage . SUPER_CLASS , null ) , fPage . getOption ( NewSVClassWizardPage . OVERRIDE_NEW , "" ) . equals ( "" ) , monitor ) ; } } package net . sf . sveditor . ui . wizards ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . search . SVDBFindPackageMatcher ; import net . sf . sveditor . ui . SVDBIconUtils ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . layout . RowLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . dialogs . FilteredTree ; import org . eclipse . ui . dialogs . PatternFilter ; public class DocGenSelectPkgsWizardPage extends WizardPage { private FilteredTree fLeftList ; private FilteredTree fRightList ; private Set < SVDBDeclCacheItem > fSelectedPackages ; Map < String , Tuple < SVDBDeclCacheItem , ISVDBIndex > > fPkgMap ; public Map < String , Tuple < SVDBDeclCacheItem , ISVDBIndex > > getPkgMap ( ) { return fPkgMap ; } public Set < SVDBDeclCacheItem > getSelectedPackages ( ) { return fSelectedPackages ; } public void setfSelectedPackages ( Set < SVDBDeclCacheItem > fSelectedPackages ) { this . fSelectedPackages = fSelectedPackages ; } protected DocGenSelectPkgsWizardPage ( ) { super ( "" ) ; fSelectedPackages = new HashSet < SVDBDeclCacheItem > ( ) ; fPkgMap = new HashMap < String , Tuple < SVDBDeclCacheItem , ISVDBIndex > > ( ) ; } public void createControl ( Composite parent ) { Composite container = new Composite ( parent , SWT . NULL ) ; final GridLayout gridLayout = new GridLayout ( ) ; gridLayout . numColumns = ; container . setLayout ( gridLayout ) ; setControl ( container ) ; createLabel ( container ) ; createLeftTable ( container ) ; createSelectionControls ( container ) ; createRightTable ( container ) ; List < ISVDBIndex > projIndexList = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) . getAllProjectLists ( ) ; for ( ISVDBIndex svdbIndex : projIndexList ) { List < SVDBDeclCacheItem > pkgs = svdbIndex . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new SVDBFindPackageMatcher ( ) ) ; for ( SVDBDeclCacheItem pkg : pkgs ) { if ( ! fPkgMap . containsKey ( pkg . getName ( ) ) ) { fPkgMap . put ( pkg . getName ( ) , new Tuple < SVDBDeclCacheItem , ISVDBIndex > ( pkg , svdbIndex ) ) ; } } } Set < SVDBDeclCacheItem > allPkgs = new HashSet < SVDBDeclCacheItem > ( ) ; for ( Tuple < SVDBDeclCacheItem , ISVDBIndex > tuple : fPkgMap . values ( ) ) { allPkgs . add ( tuple . first ( ) ) ; } fLeftList . getViewer ( ) . setInput ( allPkgs ) ; fRightList . getViewer ( ) . setInput ( fSelectedPackages ) ; } private void createSelectionControls ( Composite parent ) { Composite container = new Composite ( parent , SWT . NULL ) ; Button button ; container . setLayoutData ( new GridData ( GridData . FILL_VERTICAL ) ) ; container . setLayout ( new RowLayout ( SWT . VERTICAL ) ) ; button = new Button ( container , SWT . PUSH ) ; button . setText ( "" ) ; button . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fSelectedPackages . clear ( ) ; for ( Tuple < SVDBDeclCacheItem , ISVDBIndex > tuple : fPkgMap . values ( ) ) { fSelectedPackages . add ( tuple . first ( ) ) ; } fRightList . getViewer ( ) . setInput ( fSelectedPackages ) ; updatePageComplete ( ) ; } } ) ; button = new Button ( container , SWT . PUSH ) ; button . setText ( "" ) ; button . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fSelectedPackages . clear ( ) ; fRightList . getViewer ( ) . setInput ( fSelectedPackages ) ; updatePageComplete ( ) ; } } ) ; } private void createLabel ( Composite container ) { final Label label = new Label ( container , SWT . NONE ) ; final GridData gridData = new GridData ( ) ; gridData . horizontalSpan = ; label . setLayoutData ( gridData ) ; label . setText ( "" ) ; } private void createLeftTable ( Composite parent ) { fLeftList = new FilteredTree ( parent , SWT . H_SCROLL | SWT . V_SCROLL , new PatternFilter ( ) , true ) ; fLeftList . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; TreeViewer viewer = fLeftList . getViewer ( ) ; viewer . setContentProvider ( new ITreeContentProvider ( ) { Object fInput ; public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fInput = newInput ; } public void dispose ( ) { } public boolean hasChildren ( Object element ) { return false ; } public Object getParent ( Object element ) { return null ; } public Object [ ] getElements ( Object inputElement ) { if ( fInput instanceof Collection < ? > ) { return ( ( Collection < ? > ) fInput ) . toArray ( ) ; } else { return new Object [ ] ; } } public Object [ ] getChildren ( Object parentElement ) { return null ; } } ) ; viewer . setLabelProvider ( new LabelProvider ( ) { @ Override public String getText ( Object element ) { if ( element instanceof SVDBDeclCacheItem ) { return ( ( SVDBDeclCacheItem ) element ) . getName ( ) ; } else { return "" ; } } @ Override public Image getImage ( Object element ) { if ( element instanceof SVDBDeclCacheItem ) { return SVDBIconUtils . getIcon ( ( ( SVDBDeclCacheItem ) element ) . getType ( ) ) ; } return super . getImage ( element ) ; } } ) ; } private void createRightTable ( Composite parent ) { fRightList = new FilteredTree ( parent , SWT . H_SCROLL | SWT . V_SCROLL , new PatternFilter ( ) , true ) ; fRightList . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; TreeViewer viewer = fRightList . getViewer ( ) ; viewer . setContentProvider ( new ITreeContentProvider ( ) { Object fInput ; public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fInput = newInput ; } public void dispose ( ) { } public boolean hasChildren ( Object element ) { return false ; } public Object getParent ( Object element ) { return null ; } public Object [ ] getElements ( Object inputElement ) { if ( fInput instanceof Collection < ? > ) { return ( ( Collection < ? > ) fInput ) . toArray ( ) ; } else { return new Object [ ] ; } } public Object [ ] getChildren ( Object parentElement ) { return null ; } } ) ; viewer . setLabelProvider ( new LabelProvider ( ) { @ Override public String getText ( Object element ) { if ( element instanceof SVDBDeclCacheItem ) { return ( ( SVDBDeclCacheItem ) element ) . getName ( ) ; } else { return "" ; } } @ Override public Image getImage ( Object element ) { if ( element instanceof SVDBDeclCacheItem ) { return SVDBIconUtils . getIcon ( ( ( SVDBDeclCacheItem ) element ) . getType ( ) ) ; } return super . getImage ( element ) ; } } ) ; } public boolean hasSelection ( ) { return fSelectedPackages . size ( ) != ; } protected void updatePageComplete ( ) { setPageComplete ( hasSelection ( ) ) ; } } package net . sf . sveditor . ui . wizards ; import org . eclipse . swt . widgets . Composite ; public class NewSVModuleWizardPage extends AbstractNewSVItemFileWizardPage { public NewSVModuleWizardPage ( ) { super ( "" , "" , "" ) ; fFileExt = "" ; } @ Override protected void createCustomContent ( Composite src_c ) { } } package net . sf . sveditor . ui . wizards ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . search . SVDBFindByName ; import net . sf . sveditor . core . db . search . SVDBFindContentAssistNameMatcher ; import net . sf . sveditor . core . db . search . SVDBFindSuperClass ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . svcp . SVDBDecoratingLabelProvider ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . dialogs . SelectionStatusDialog ; public class BrowseClasses extends SelectionStatusDialog implements IStructuredContentProvider { private String fSuperClass ; private Text fClassName ; private String fClassNameStr ; private boolean fModifyInProgress ; private TableViewer fClassList ; private SVDBClassDecl fSelectedClass ; private ISVDBIndexIterator fIndexIt ; private List < SVDBItem > fProposals ; public BrowseClasses ( Shell shell , ISVDBIndexIterator index_it ) { super ( shell ) ; fIndexIt = index_it ; fProposals = new ArrayList < SVDBItem > ( ) ; setTitle ( "" ) ; setStatusLineAboveButtons ( true ) ; } public void setSuperClass ( String superclass ) { fSuperClass = superclass ; } public void setClassName ( String classname ) { fClassNameStr = classname ; if ( fClassName != null ) { fClassName . setText ( fClassNameStr ) ; } } public SVDBClassDecl getSelectedClass ( ) { return fSelectedClass ; } @ Override protected Control createDialogArea ( Composite parent ) { Label l ; GridData gd ; Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new GridLayout ( , false ) ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . widthHint = ; gd . heightHint = ; c . setLayoutData ( gd ) ; l = new Label ( c , SWT . NONE ) ; l . setText ( "" ) ; fClassName = new Text ( c , SWT . BORDER ) ; fClassName . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; fClassName . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fClassNameStr = fClassName . getText ( ) ; if ( ! fModifyInProgress ) { updateProposals ( ) ; } } } ) ; fClassList = new TableViewer ( c , SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = ; fClassList . getControl ( ) . setLayoutData ( gd ) ; fClassList . setContentProvider ( this ) ; fClassList . setLabelProvider ( new SVDBDecoratingLabelProvider ( new SVTreeLabelProvider ( ) ) ) ; fClassList . setInput ( fProposals ) ; fClassList . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) fClassList . getSelection ( ) ; if ( sel . getFirstElement ( ) == null ) { fSelectedClass = null ; updateStatus ( new Status ( IStatus . ERROR , SVUiPlugin . PLUGIN_ID , "" ) ) ; } else { fSelectedClass = ( SVDBClassDecl ) sel . getFirstElement ( ) ; updateStatus ( new Status ( IStatus . OK , SVUiPlugin . PLUGIN_ID , "" + fSelectedClass . getName ( ) + "" ) ) ; } } } ) ; fClassList . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { okPressed ( ) ; } } ) ; if ( fClassNameStr != null ) { fClassName . setText ( fClassNameStr ) ; } else { fClassName . setText ( "" ) ; } updateProposals ( ) ; return c ; } private void updateProposals ( ) { SVDBFindByName finder = new SVDBFindByName ( fIndexIt , new SVDBFindContentAssistNameMatcher ( ) { @ Override public boolean match ( ISVDBNamedItem it , String name ) { return ( ! it . getName ( ) . startsWith ( "" ) && super . match ( it , name ) ) ; } } ) ; List < ISVDBItemBase > proposals = null ; fProposals . clear ( ) ; IStructuredSelection sel = ( IStructuredSelection ) fClassList . getSelection ( ) ; if ( fClassNameStr == null ) { fClassNameStr = "" ; } proposals = finder . find ( fClassNameStr , SVDBItemType . ClassDecl ) ; for ( ISVDBItemBase p : proposals ) { fProposals . add ( ( SVDBItem ) p ) ; } if ( fSuperClass != null ) { filter_by_superclass ( ) ; } for ( SVDBItem cls : fProposals ) { if ( cls . getName ( ) . equals ( fClassNameStr ) ) { sel = new StructuredSelection ( cls ) ; } } fClassList . setSelection ( sel ) ; fClassList . refresh ( ) ; sel = ( IStructuredSelection ) fClassList . getSelection ( ) ; if ( sel != null && sel . getFirstElement ( ) != null ) { fSelectedClass = ( SVDBClassDecl ) sel . getFirstElement ( ) ; updateStatus ( new Status ( IStatus . OK , SVUiPlugin . PLUGIN_ID , "" + fSelectedClass . getName ( ) + "" ) ) ; } else { updateStatus ( new Status ( IStatus . ERROR , SVUiPlugin . PLUGIN_ID , "" ) ) ; } } private void filter_by_superclass ( ) { SVDBFindSuperClass finder = new SVDBFindSuperClass ( fIndexIt ) ; for ( int i = ; i < fProposals . size ( ) ; i ++ ) { SVDBClassDecl cls = ( SVDBClassDecl ) fProposals . get ( i ) ; boolean found = false ; while ( cls != null ) { SVDBClassDecl super_cls = finder . find ( cls ) ; if ( super_cls != null && super_cls . getName ( ) . equals ( fSuperClass ) ) { found = true ; break ; } cls = super_cls ; } if ( ! found ) { fProposals . remove ( i ) ; i -- ; } } } @ Override protected void computeResult ( ) { } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public Object [ ] getElements ( Object inputElement ) { return fProposals . toArray ( ) ; } } package net . sf . sveditor . ui . wizards . templates ; import java . io . InputStream ; import java . lang . reflect . InvocationTargetException ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . templates . DefaultTemplateParameterProvider ; import net . sf . sveditor . core . templates . DynamicTemplateParameterProvider ; import net . sf . sveditor . core . templates . ITemplateFileCreator ; import net . sf . sveditor . core . templates . TemplateProcessor ; import net . sf . sveditor . core . text . TagProcessor ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . wizards . ISVSubWizard ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . wizards . newresource . BasicNewResourceWizard ; public class SVTemplateWizard extends BasicNewResourceWizard { public static final String ID = SVUiPlugin . PLUGIN_ID + "" ; private SVTemplateSelectionPage fBasicsPage ; private SVTemplateParameterPage fParamsPage ; private ISVSubWizard fSubWizard ; private Map < String , Object > fOptions ; public SVTemplateWizard ( ) { super ( ) ; fOptions = new HashMap < String , Object > ( ) ; } public void addPages ( ) { super . addPages ( ) ; fBasicsPage = new SVTemplateSelectionPage ( ) ; fParamsPage = new SVTemplateParameterPage ( ) ; Object sel = getSelection ( ) . getFirstElement ( ) ; if ( sel != null && sel instanceof IResource ) { IResource r = ( IResource ) sel ; if ( ! ( r instanceof IContainer ) ) { r = r . getParent ( ) ; } fParamsPage . setSourceFolder ( r . getFullPath ( ) . toOSString ( ) ) ; } addPage ( fBasicsPage ) ; addPage ( fParamsPage ) ; } @ Override public boolean canFinish ( ) { if ( fSubWizard != null ) { return fSubWizard . canFinish ( ) ; } else { return super . canFinish ( ) ; } } @ Override public IWizardPage getNextPage ( IWizardPage page ) { IWizardPage next ; if ( fSubWizard != null ) { next = fSubWizard . getNextPage ( page ) ; } else { next = super . getNextPage ( page ) ; } if ( next == fParamsPage ) { fParamsPage . setTemplate ( fBasicsPage . getTemplate ( ) ) ; } return next ; } @ Override public IWizardPage getPreviousPage ( IWizardPage page ) { if ( fSubWizard != null ) { return fSubWizard . getPreviousPage ( page ) ; } else { return super . getPreviousPage ( page ) ; } } public void setSubWizard ( ISVSubWizard sub ) { fSubWizard = sub ; if ( fSubWizard != null ) { fSubWizard . init ( this , fOptions ) ; } } public void init ( IWorkbench workbench , IStructuredSelection selection ) { super . init ( workbench , selection ) ; setNeedsProgressMonitor ( true ) ; SVCorePlugin . getDefault ( ) . getTemplateRgy ( ) . load_extensions ( ) ; } @ Override public boolean performFinish ( ) { final IContainer folder = SVFileUtils . getWorkspaceFolder ( fParamsPage . getSourceFolder ( ) ) ; final TagProcessor tp = new TagProcessor ( ) ; tp . addParameterProvider ( new DynamicTemplateParameterProvider ( ) ) ; tp . addParameterProvider ( fParamsPage . getTagProcessor ( false ) ) ; tp . addParameterProvider ( new DefaultTemplateParameterProvider ( SVUiPlugin . getDefault ( ) . getGlobalTemplateParameters ( ) ) ) ; tp . addParameterProvider ( SVUiPlugin . getDefault ( ) . getGlobalTemplateParameters ( ) ) ; try { getContainer ( ) . run ( true , true , new IRunnableWithProgress ( ) { public void run ( final IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { monitor . beginTask ( "" , ) ; TemplateProcessor templ_proc = new TemplateProcessor ( new ITemplateFileCreator ( ) { public void createFile ( String path , InputStream content ) { IFile file = folder . getFile ( new Path ( path ) ) ; monitor . worked ( ) ; try { if ( ! file . getParent ( ) . exists ( ) ) { ( ( IFolder ) file . getParent ( ) ) . create ( true , true , new NullProgressMonitor ( ) ) ; } if ( file . exists ( ) ) { file . setContents ( content , true , true , new NullProgressMonitor ( ) ) ; } else { file . create ( content , true , new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { e . printStackTrace ( ) ; } } } ) ; templ_proc . process ( fBasicsPage . getTemplate ( ) , tp ) ; monitor . done ( ) ; } } ) ; } catch ( InterruptedException e ) { } catch ( InvocationTargetException e ) { } return true ; } } package net . sf . sveditor . ui . wizards . templates ; import net . sf . sveditor . core . templates . TemplateCategory ; import net . sf . sveditor . core . templates . TemplateInfo ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; public class TemplateCategoriesLabelProvider extends LabelProvider { @ Override public Image getImage ( Object element ) { return null ; } @ Override public String getText ( Object element ) { if ( element instanceof TemplateCategory ) { return ( ( TemplateCategory ) element ) . getName ( ) ; } else if ( element instanceof TemplateInfo ) { return ( ( TemplateInfo ) element ) . getName ( ) ; } else { return "" ; } } } package net . sf . sveditor . ui . wizards . templates ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; public class WorkspaceDirectoryDialog extends Dialog { private TreeViewer fTreeViewer ; private IContainer fContainer ; public WorkspaceDirectoryDialog ( Shell shell , IContainer container ) { super ( shell ) ; fContainer = container ; } public IContainer getContainer ( ) { return fContainer ; } @ Override protected Control createDialogArea ( Composite p ) { Composite parent = new Composite ( p , SWT . NONE ) ; parent . setLayout ( new GridLayout ( , true ) ) ; fTreeViewer = new TreeViewer ( parent ) ; GridData gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . widthHint = ; gd . heightHint = ; fTreeViewer . getControl ( ) . setLayoutData ( gd ) ; fTreeViewer . setAutoExpandLevel ( ) ; fTreeViewer . setContentProvider ( new WorkbenchContentProvider ( ) ) ; fTreeViewer . addFilter ( new ViewerFilter ( ) { @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { return ( element instanceof IContainer ) ; } } ) ; fTreeViewer . setLabelProvider ( new WorkbenchLabelProvider ( ) ) ; fTreeViewer . setInput ( ResourcesPlugin . getWorkspace ( ) ) ; fTreeViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) fTreeViewer . getSelection ( ) ; if ( sel . getFirstElement ( ) != null ) { fContainer = ( IContainer ) sel . getFirstElement ( ) ; } } } ) ; if ( fContainer != null ) { fTreeViewer . setSelection ( new StructuredSelection ( fContainer ) , true ) ; } return fTreeViewer . getControl ( ) ; } } package net . sf . sveditor . ui . wizards . templates ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . templates . TemplateCategory ; import net . sf . sveditor . core . templates . TemplateInfo ; import net . sf . sveditor . core . templates . TemplateRegistry ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerComparator ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Text ; public class SVTemplateSelectionPage extends WizardPage { private TreeViewer fTemplateTree ; private TemplateInfo fTemplate ; private TemplateCategory fCategory ; private Text fDescription ; public SVTemplateSelectionPage ( ) { super ( "" , "" , null ) ; setDescription ( "" ) ; } public TemplateInfo getTemplate ( ) { return fTemplate ; } public void createControl ( Composite parent ) { parent . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; final Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new GridLayout ( ) ) ; c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Composite src_c = new Composite ( c , SWT . NONE ) ; src_c . setLayout ( new GridLayout ( , false ) ) ; src_c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; GridData gd ; Group g ; g = new Group ( src_c , SWT . NONE ) ; g . setText ( "" ) ; g . setLayout ( new GridLayout ( ) ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = ; g . setLayoutData ( gd ) ; fTemplateTree = new TreeViewer ( g ) ; fTemplateTree . setContentProvider ( new TemplateCategoriesContentProvider ( ) ) ; fTemplateTree . setLabelProvider ( new TemplateCategoriesLabelProvider ( ) ) ; fTemplateTree . getTree ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fTemplateTree . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { templateSelectionChanged ( event ) ; } } ) ; TemplateRegistry rgy = SVCorePlugin . getDefault ( ) . getTemplateRgy ( ) ; fTemplateTree . setInput ( TemplateCategoriesNode . create ( rgy ) ) ; fTemplateTree . setSorter ( SorterA ) ; g = new Group ( c , SWT . None ) ; g . setText ( "" ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = ; g . setLayout ( new GridLayout ( ) ) ; g . setLayoutData ( gd ) ; fDescription = new Text ( g , SWT . READ_ONLY ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; fDescription . setLayoutData ( gd ) ; setPageComplete ( false ) ; setControl ( c ) ; } private void templateSelectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; fTemplate = null ; fCategory = null ; if ( sel . getFirstElement ( ) instanceof TemplateInfo ) { fTemplate = ( TemplateInfo ) sel . getFirstElement ( ) ; } else if ( sel . getFirstElement ( ) instanceof TemplateCategory ) { fCategory = ( TemplateCategory ) sel . getFirstElement ( ) ; } validate ( ) ; } private void validate ( ) { setErrorMessage ( null ) ; if ( fCategory != null ) { fDescription . setText ( fCategory . getDescription ( ) ) ; } else if ( fTemplate != null ) { fDescription . setText ( fTemplate . getDescription ( ) ) ; } else { fDescription . setText ( "" ) ; } if ( getErrorMessage ( ) == null ) { if ( fTemplate == null ) { setErrorMessage ( "" ) ; } } setPageComplete ( ( getErrorMessage ( ) == null ) ) ; } private ViewerSorter SorterA = new ViewerSorter ( ) { @ Override public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( e1 instanceof TemplateCategory && e2 instanceof TemplateCategory ) { TemplateCategory c1 = ( TemplateCategory ) e1 ; TemplateCategory c2 = ( TemplateCategory ) e2 ; return c1 . getName ( ) . compareTo ( c2 . getName ( ) ) ; } else if ( e1 instanceof TemplateInfo && e2 instanceof TemplateInfo ) { TemplateInfo c1 = ( TemplateInfo ) e1 ; TemplateInfo c2 = ( TemplateInfo ) e2 ; return c1 . getName ( ) . compareTo ( c2 . getName ( ) ) ; } else { return super . compare ( viewer , e1 , e2 ) ; } } } ; } package net . sf . sveditor . ui . wizards . templates ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . templates . TemplateInfo ; import net . sf . sveditor . core . templates . TemplateParameterProvider ; import net . sf . sveditor . core . text . TagProcessor ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . TableColumn ; public class TemplateFilesTableViewer extends TableViewer { private TemplateInfo fTemplate ; private String fSourceFolderStr = "" ; private List < String > fFilenames ; private TemplateParameterProvider fParameters ; private boolean fOverwriteFiles ; public TemplateFilesTableViewer ( Composite parent , TemplateParameterProvider p ) { super ( parent ) ; getTable ( ) . setHeaderVisible ( true ) ; TableColumn err = new TableColumn ( getTable ( ) , SWT . LEFT , ) ; err . setText ( "" ) ; err . setWidth ( ) ; TableColumn file = new TableColumn ( getTable ( ) , SWT . LEFT , ) ; file . setText ( "" ) ; file . setWidth ( ) ; setContentProvider ( contentProvider ) ; setLabelProvider ( labelProvider ) ; fParameters = p ; updateFilenames ( ) ; } public void setOverwriteFiles ( boolean overwrite ) { fOverwriteFiles = overwrite ; updateFilenames ( ) ; } public String validate ( ) { String ret = null ; updateFilenames ( ) ; if ( ! fParameters . hasTag ( "" ) || fParameters . getTag ( "" ) . trim ( ) . equals ( "" ) ) { ret = "" ; } IContainer c = SVFileUtils . getWorkspaceFolder ( fSourceFolderStr ) ; if ( c != null && c . exists ( ) ) { fTemplate . getTemplates ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( String filename : fFilenames ) { IFile file = root . getFile ( new Path ( filename ) ) ; if ( ( file . exists ( ) && ! fOverwriteFiles ) && ret == null ) { ret = "" + filename + "" ; } } } else { ret = "" + fSourceFolderStr + "" ; } return ret ; } public void setSourceFolder ( String src_folder ) { fSourceFolderStr = src_folder ; updateFilenames ( ) ; } public void setTemplate ( TemplateInfo template ) { fTemplate = template ; updateFilenames ( ) ; } private void updateFilenames ( ) { fFilenames = new ArrayList < String > ( ) ; TemplateParameterProvider pp = new TemplateParameterProvider ( fParameters ) ; TagProcessor tp = new TagProcessor ( ) ; tp . addParameterProvider ( pp ) ; if ( pp . hasTag ( "" ) && pp . getTag ( "" ) . trim ( ) . equals ( "" ) ) { pp . removeTag ( "" ) ; } if ( fTemplate != null ) { for ( Tuple < String , String > n : fTemplate . getTemplates ( ) ) { fFilenames . add ( "" + fSourceFolderStr + "" + n . second ( ) ) ; } } for ( int i = ; i < fFilenames . size ( ) ; i ++ ) { String pn = tp . process ( fFilenames . get ( i ) ) ; fFilenames . set ( i , pn ) ; } if ( getTable ( ) != null && ! getTable ( ) . isDisposed ( ) ) { setInput ( fFilenames ) ; } } private IStructuredContentProvider contentProvider = new IStructuredContentProvider ( ) { public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void dispose ( ) { } @ SuppressWarnings ( "" ) public Object [ ] getElements ( Object inputElement ) { return ( ( List ) inputElement ) . toArray ( ) ; } } ; private ITableLabelProvider labelProvider = new ITableLabelProvider ( ) { public void removeListener ( ILabelProviderListener listener ) { } public void addListener ( ILabelProviderListener listener ) { } public void dispose ( ) { } public boolean isLabelProperty ( Object element , String property ) { return false ; } public String getColumnText ( Object element , int columnIndex ) { if ( columnIndex == ) { return element . toString ( ) ; } else { return null ; } } public Image getColumnImage ( Object element , int columnIndex ) { if ( columnIndex == ) { IContainer c = SVFileUtils . getWorkspaceFolder ( fSourceFolderStr ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; if ( c != null ) { String filename = element . toString ( ) ; IFile file = root . getFile ( new Path ( filename ) ) ; if ( ! fParameters . hasTag ( "" ) || fParameters . getTag ( "" ) . trim ( ) . equals ( "" ) || ( file . exists ( ) && ! fOverwriteFiles ) ) { return SVUiPlugin . getImage ( "" ) ; } else { return SVUiPlugin . getImage ( "" ) ; } } else { return SVUiPlugin . getImage ( "" ) ; } } else { return null ; } } } ; } package net . sf . sveditor . ui . wizards . templates ; import net . sf . sveditor . core . templates . TemplateCategory ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class TemplateCategoriesContentProvider implements ITreeContentProvider { private TemplateCategoriesNode fRoot ; public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fRoot = ( TemplateCategoriesNode ) newInput ; } public Object [ ] getElements ( Object inputElement ) { return fRoot . getCategories ( ) . toArray ( ) ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof TemplateCategory ) { return fRoot . getTemplates ( ( TemplateCategory ) parentElement ) . toArray ( ) ; } else { return new Object [ ] ; } } public Object getParent ( Object element ) { return null ; } public boolean hasChildren ( Object element ) { return ( getChildren ( element ) . length > ) ; } } package net . sf . sveditor . ui . wizards . templates ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . StringInputStream ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . wizard . Wizard ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . internal . ide . DialogUtil ; import org . eclipse . ui . internal . wizards . newresource . ResourceMessages ; import org . eclipse . ui . part . ISetSelectionTarget ; public class NewSVTDescriptorWizard extends Wizard implements INewWizard { private IWorkbench fWorkbench ; private IStructuredSelection fSelection ; private NewSVTDescriptorPage fPage ; public NewSVTDescriptorWizard ( ) { } public void init ( IWorkbench workbench , IStructuredSelection selection ) { fWorkbench = workbench ; fSelection = selection ; } @ Override public void addPages ( ) { IContainer container = null ; if ( fSelection != null ) { if ( fSelection . getFirstElement ( ) instanceof IContainer ) { container = ( IContainer ) fSelection . getFirstElement ( ) ; } else if ( fSelection . getFirstElement ( ) instanceof IResource ) { container = ( ( IResource ) fSelection . getFirstElement ( ) ) . getParent ( ) ; } } fPage = new NewSVTDescriptorPage ( container ) ; addPage ( fPage ) ; } protected void selectAndReveal ( IResource newResource ) { selectAndReveal ( newResource , fWorkbench . getActiveWorkbenchWindow ( ) ) ; } public static void selectAndReveal ( IResource resource , IWorkbenchWindow window ) { if ( window == null || resource == null ) { return ; } IWorkbenchPage page = window . getActivePage ( ) ; if ( page == null ) { return ; } List < IWorkbenchPart > parts = new ArrayList < IWorkbenchPart > ( ) ; IWorkbenchPartReference refs [ ] = page . getViewReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { IWorkbenchPart part = refs [ i ] . getPart ( false ) ; if ( part != null ) { parts . add ( part ) ; } } refs = page . getEditorReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { if ( refs [ i ] . getPart ( false ) != null ) { parts . add ( refs [ i ] . getPart ( false ) ) ; } } final ISelection selection = new StructuredSelection ( resource ) ; Iterator < IWorkbenchPart > itr = parts . iterator ( ) ; while ( itr . hasNext ( ) ) { IWorkbenchPart part = itr . next ( ) ; ISetSelectionTarget target = null ; if ( part instanceof ISetSelectionTarget ) { target = ( ISetSelectionTarget ) part ; } else { target = ( ISetSelectionTarget ) part . getAdapter ( ISetSelectionTarget . class ) ; } if ( target != null ) { final ISetSelectionTarget finalTarget = target ; window . getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { finalTarget . selectReveal ( selection ) ; } } ) ; } } } @ Override public boolean performFinish ( ) { IContainer folder = fPage . getFolder ( ) ; String filename = fPage . getFilename ( ) + "" ; if ( folder == null ) { return false ; } IFile file = folder . getFile ( new Path ( filename ) ) ; try { StringInputStream in = new StringInputStream ( "" + "" ) ; file . create ( in , true , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { return false ; } selectAndReveal ( file ) ; IWorkbenchWindow dw = fWorkbench . getActiveWorkbenchWindow ( ) ; try { if ( dw != null ) { IWorkbenchPage page = dw . getActivePage ( ) ; if ( page != null ) { IDE . openEditor ( page , file , true ) ; } } } catch ( PartInitException e ) { } return true ; } } package net . sf . sveditor . ui . wizards . templates ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . templates . ITemplateParameterProvider ; import net . sf . sveditor . core . templates . TemplateInfo ; import net . sf . sveditor . core . templates . TemplateParameter ; import net . sf . sveditor . core . templates . TemplateParameterProvider ; import net . sf . sveditor . core . text . TagProcessor ; import net . sf . sveditor . ui . WorkspaceDirectoryDialog ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . window . Window ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; public class SVTemplateParameterPage extends WizardPage { private Text fSourceFolder ; private String fSourceFolderStr ; private Button fBrowse ; private Text fName ; private Button fOverwrite ; private TemplateFilesTableViewer fFileTable ; private TemplateParametersTableViewer fParamsTable ; private TemplateInfo fTemplate ; private TemplateParameterProvider fParameters ; public SVTemplateParameterPage ( ) { super ( "" , "" , null ) ; setDescription ( "" ) ; fParameters = new TemplateParameterProvider ( ) ; } public void setSourceFolder ( String folder ) { fSourceFolderStr = folder ; if ( fSourceFolder != null && ! fSourceFolder . isDisposed ( ) ) { fSourceFolder . setText ( fSourceFolderStr ) ; } updateFilenamesDescription ( ) ; } public String getSourceFolder ( ) { return fSourceFolderStr ; } public void setTemplate ( TemplateInfo template ) { fTemplate = template ; updateFilenamesDescription ( ) ; updateParameters ( ) ; } public ITemplateParameterProvider getTagProcessor ( boolean dont_expand_null_name ) { TemplateParameterProvider tp = new TemplateParameterProvider ( fParameters ) ; if ( ! dont_expand_null_name ) { if ( ! tp . hasTag ( "" ) ) { tp . setTag ( "" , "" ) ; } } for ( TemplateParameter p : fParamsTable . getParameters ( ) ) { tp . setTag ( p . getName ( ) , p . getValue ( ) ) ; } return tp ; } public void createControl ( Composite parent ) { Label l ; GridData gd ; Group g ; final Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new GridLayout ( ) ) ; Composite src_c = new Composite ( c , SWT . NONE ) ; src_c . setLayout ( new GridLayout ( , false ) ) ; src_c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; l = new Label ( src_c , SWT . NONE ) ; l . setText ( "" ) ; fSourceFolder = new Text ( src_c , SWT . BORDER ) ; if ( fSourceFolderStr != null ) { fSourceFolder . setText ( fSourceFolderStr ) ; } fSourceFolder . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; fSourceFolder . addModifyListener ( modifyListener ) ; fBrowse = new Button ( src_c , SWT . PUSH ) ; fBrowse . setText ( "" ) ; fBrowse . addSelectionListener ( selectionListener ) ; l = new Label ( src_c , SWT . NONE ) ; l . setText ( "" ) ; fName = new Text ( src_c , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; gd . horizontalSpan = ; fName . setLayoutData ( gd ) ; fName . addModifyListener ( modifyListener ) ; l = new Label ( src_c , SWT . NONE ) ; l . setText ( "" ) ; fOverwrite = new Button ( src_c , SWT . CHECK ) ; fOverwrite . addSelectionListener ( selectionListener ) ; g = new Group ( src_c , SWT . NONE ) ; g . setText ( "" ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = ; g . setLayoutData ( gd ) ; g . setLayout ( new GridLayout ( ) ) ; fParamsTable = new TemplateParametersTableViewer ( g ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . heightHint = ; fParamsTable . getTable ( ) . setLayoutData ( gd ) ; fParamsTable . addModifyListener ( modifyListener ) ; g = new Group ( src_c , SWT . NONE ) ; g . setText ( "" ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . heightHint = ; gd . horizontalSpan = ; g . setLayoutData ( gd ) ; g . setLayout ( new GridLayout ( ) ) ; fFileTable = new TemplateFilesTableViewer ( g , fParameters ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; fFileTable . getTable ( ) . setLayoutData ( gd ) ; setPageComplete ( false ) ; setControl ( c ) ; updateFilenamesDescription ( ) ; fName . setFocus ( ) ; } private void validate ( ) { String err ; setErrorMessage ( null ) ; if ( fTemplate == null ) { return ; } if ( ( err = fFileTable . validate ( ) ) != null ) { if ( getErrorMessage ( ) == null ) { setErrorMessage ( err ) ; } } setPageComplete ( ( getErrorMessage ( ) == null ) ) ; } private void updateFilenamesDescription ( ) { if ( fFileTable != null && ! fFileTable . getTable ( ) . isDisposed ( ) ) { fFileTable . setSourceFolder ( fSourceFolderStr ) ; fFileTable . setTemplate ( fTemplate ) ; } if ( fParamsTable != null && ! fParamsTable . getTable ( ) . isDisposed ( ) ) { fParamsTable . setSourceFolder ( fSourceFolderStr ) ; } validate ( ) ; } private void updateParameters ( ) { if ( fParamsTable != null && ! fParamsTable . getTable ( ) . isDisposed ( ) ) { if ( fTemplate != null ) { fParamsTable . setParameters ( fTemplate . getParameters ( ) ) ; } else { fParamsTable . setParameters ( null ) ; } } } private IProject findDestProject ( ) { IContainer c = SVFileUtils . getWorkspaceFolder ( fSourceFolderStr ) ; if ( c == null ) { return null ; } else if ( c instanceof IProject ) { return ( IProject ) c ; } else { return c . getProject ( ) ; } } public SVDBProjectData getProjectData ( ) { IProject p = findDestProject ( ) ; if ( p == null ) { return null ; } SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( p ) ; return pdata ; } private ModifyListener modifyListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { if ( e . widget == fSourceFolder ) { fSourceFolderStr = fSourceFolder . getText ( ) ; fFileTable . setSourceFolder ( fSourceFolderStr ) ; } else if ( e . widget == fName ) { fParameters . setTag ( "" , fName . getText ( ) ) ; } else if ( e . widget == fFileTable . getTable ( ) ) { } updateFilenamesDescription ( ) ; } } ; private SelectionListener selectionListener = new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { if ( e . widget == fBrowse ) { WorkspaceDirectoryDialog dlg = new WorkspaceDirectoryDialog ( getShell ( ) ) ; if ( dlg . open ( ) == Window . OK ) { fSourceFolder . setText ( dlg . getPath ( ) ) ; } } else if ( e . widget == fOverwrite ) { boolean overwrite = fOverwrite . getSelection ( ) ; if ( fFileTable . getTable ( ) != null && ! fFileTable . getTable ( ) . isDisposed ( ) ) { fFileTable . setOverwriteFiles ( overwrite ) ; } } validate ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ; } package net . sf . sveditor . ui . wizards . templates ; import net . sf . sveditor . core . SVFileUtils ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . window . Window ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; public class NewSVTDescriptorPage extends WizardPage { private Text fFolderPath ; private Button fFolderBrowse ; private Text fFilePath ; private IContainer fContainer ; private String fFilename ; public NewSVTDescriptorPage ( IContainer container ) { super ( "" ) ; setTitle ( "" ) ; fContainer = container ; fFilename = "" ; } public IContainer getFolder ( ) { return fContainer ; } public String getFilename ( ) { return fFilename ; } public void createControl ( Composite parent ) { Composite c = new Composite ( parent , SWT . NONE ) ; Label l ; c . setLayout ( new GridLayout ( , false ) ) ; l = new Label ( c , SWT . NONE ) ; l . setText ( "" ) ; fFolderPath = new Text ( c , SWT . SINGLE + SWT . BORDER ) ; fFolderPath . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fFolderPath . addModifyListener ( modifyListener ) ; if ( fContainer != null ) { fFolderPath . setText ( fContainer . getFullPath ( ) . toOSString ( ) ) ; } fFolderBrowse = new Button ( c , SWT . PUSH ) ; fFolderBrowse . setText ( "" ) ; fFolderBrowse . addSelectionListener ( selectionListener ) ; l = new Label ( c , SWT . NONE ) ; l . setText ( "" ) ; fFilePath = new Text ( c , SWT . SINGLE + SWT . BORDER ) ; fFilePath . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fFilePath . addModifyListener ( modifyListener ) ; l = new Label ( c , SWT . NONE ) ; l . setText ( "" ) ; setControl ( c ) ; validate ( ) ; } private void validate ( ) { String err = null ; if ( fFilename . trim ( ) . equals ( "" ) ) { err = setErr ( err , "" ) ; } if ( fContainer == null || ! fContainer . exists ( ) ) { err = setErr ( err , "" ) ; } if ( fContainer != null && ! fFilename . trim ( ) . equals ( "" ) ) { IFile file = fContainer . getFile ( new Path ( fFilename + "" ) ) ; if ( file . exists ( ) ) { err = setErr ( err , "" + fFilename + "" ) ; } } setErrorMessage ( err ) ; } private static String setErr ( String err , String msg ) { return ( err == null ) ? msg : err ; } private ModifyListener modifyListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { if ( e . widget == fFilePath ) { fFilename = fFilePath . getText ( ) ; } else if ( e . widget == fFolderPath ) { fContainer = SVFileUtils . getWorkspaceFolder ( fFolderPath . getText ( ) ) ; } validate ( ) ; } } ; private SelectionListener selectionListener = new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { WorkspaceDirectoryDialog dlg = new WorkspaceDirectoryDialog ( getShell ( ) , fContainer ) ; if ( dlg . open ( ) == Window . OK ) { fContainer = dlg . getContainer ( ) ; if ( fContainer == null ) { fFolderPath . setText ( "" ) ; } else { fFolderPath . setText ( fContainer . getFullPath ( ) . toOSString ( ) ) ; } } } public void widgetDefaultSelected ( SelectionEvent e ) { } } ; } package net . sf . sveditor . ui . wizards . templates ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . sf . sveditor . core . templates . TemplateCategory ; import net . sf . sveditor . core . templates . TemplateInfo ; import net . sf . sveditor . core . templates . TemplateRegistry ; public class TemplateCategoriesNode { private Map < TemplateCategory , List < TemplateInfo > > fCategoryMap ; public TemplateCategoriesNode ( ) { fCategoryMap = new HashMap < TemplateCategory , List < TemplateInfo > > ( ) ; } public List < TemplateInfo > getTemplates ( TemplateCategory category ) { return fCategoryMap . get ( category ) ; } public List < TemplateCategory > getCategories ( ) { List < TemplateCategory > ret = new ArrayList < TemplateCategory > ( ) ; for ( TemplateCategory c : fCategoryMap . keySet ( ) ) { ret . add ( c ) ; } return ret ; } public static TemplateCategoriesNode create ( TemplateRegistry rgy ) { TemplateCategoriesNode ret = new TemplateCategoriesNode ( ) ; for ( TemplateCategory c : rgy . getCategories ( ) ) { List < TemplateInfo > ti = rgy . getTemplates ( c . getId ( ) ) ; ret . fCategoryMap . put ( c , ti ) ; } return ret ; } } package net . sf . sveditor . ui . wizards . templates ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . search . ISVDBFindNameMatcher ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class ClassBrowseDialog extends Dialog { private String fSelectedClassStr = "" ; private String fSourceFolder ; private String fClassParent ; private Text fFilterText ; private String fFilterStr ; private TableViewer fTable ; private List < SVDBDeclCacheItem > fAllClasses ; public ClassBrowseDialog ( Shell parent , String src_folder , String class_parent ) { super ( parent ) ; fSourceFolder = src_folder ; fClassParent = class_parent ; fFilterStr = "" ; } @ Override protected Control createDialogArea ( Composite parent ) { Composite c = new Composite ( parent , SWT . NONE ) ; GridData gd ; SVDBProjectData pdata = getProjectData ( ) ; c . setLayout ( new GridLayout ( ) ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; c . setLayoutData ( gd ) ; if ( pdata != null ) { fFilterText = new Text ( c , SWT . ICON_CANCEL + SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; fFilterText . setLayoutData ( gd ) ; fFilterText . addModifyListener ( modifyListener ) ; fTable = new TableViewer ( c ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . heightHint = ; gd . widthHint = ; fTable . getTable ( ) . setLayoutData ( gd ) ; fTable . addSelectionChangedListener ( selectionChangedListener ) ; fTable . addFilter ( viewerFilter ) ; fTable . setContentProvider ( contentProvider ) ; fTable . setLabelProvider ( new SVTreeLabelProvider ( ) ) ; SVDBIndexCollection mgr = pdata . getProjectIndexMgr ( ) ; fAllClasses = mgr . findGlobalScopeDecl ( new NullProgressMonitor ( ) , "" , new ISVDBFindNameMatcher ( ) { public boolean match ( ISVDBNamedItem it , String name ) { return ( it . getType ( ) == SVDBItemType . ClassDecl ) ; } } ) ; fTable . setInput ( fAllClasses ) ; } else { Label l = new Label ( c , SWT . NONE ) ; l . setText ( "" ) ; } return c ; } public String getSelectedClass ( ) { return fSelectedClassStr ; } private IProject findDestProject ( ) { IContainer c = SVFileUtils . getWorkspaceFolder ( fSourceFolder ) ; if ( c == null ) { return null ; } else if ( c instanceof IProject ) { return ( IProject ) c ; } else { return c . getProject ( ) ; } } public SVDBProjectData getProjectData ( ) { IProject p = findDestProject ( ) ; if ( p == null ) { return null ; } SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( p ) ; return pdata ; } private ModifyListener modifyListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fFilterStr = fFilterText . getText ( ) ; fTable . refresh ( ) ; } } ; private ISelectionChangedListener selectionChangedListener = new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; SVDBDeclCacheItem item = ( SVDBDeclCacheItem ) sel . getFirstElement ( ) ; fSelectedClassStr = item . getName ( ) ; } } ; private ViewerFilter viewerFilter = new ViewerFilter ( ) { @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { SVDBDeclCacheItem item = ( SVDBDeclCacheItem ) element ; return item . getName ( ) . toLowerCase ( ) . startsWith ( fFilterStr . toLowerCase ( ) ) ; } } ; private IStructuredContentProvider contentProvider = new IStructuredContentProvider ( ) { public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void dispose ( ) { } public Object [ ] getElements ( Object inputElement ) { return fAllClasses . toArray ( ) ; } } ; } package net . sf . sveditor . ui . wizards . templates ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . templates . ITemplateParameterProvider ; import net . sf . sveditor . core . templates . TemplateParameter ; import net . sf . sveditor . core . templates . TemplateParameterType ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . viewers . CellEditor ; import org . eclipse . jface . viewers . ColumnViewer ; import org . eclipse . jface . viewers . ComboBoxCellEditor ; import org . eclipse . jface . viewers . EditingSupport ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . TableViewerColumn ; import org . eclipse . jface . viewers . TextCellEditor ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CCombo ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Text ; public class TemplateParametersTableViewer extends TableViewer { private List < TemplateParameter > fParameters ; private List < ModifyListener > fModifyListeners ; private String fSourceFolderStr = "" ; private TemplateParameter fActiveParameter ; public TemplateParametersTableViewer ( Composite parent ) { super ( parent ) ; fParameters = new ArrayList < TemplateParameter > ( ) ; fModifyListeners = new ArrayList < ModifyListener > ( ) ; getTable ( ) . setHeaderVisible ( true ) ; TableViewerColumn err = new TableViewerColumn ( this , SWT . LEFT , ) ; err . getColumn ( ) . setText ( "" ) ; err . getColumn ( ) . setWidth ( ) ; TableViewerColumn name = new TableViewerColumn ( this , SWT . LEFT , ) ; name . getColumn ( ) . setText ( "" ) ; name . getColumn ( ) . setWidth ( ) ; TableViewerColumn value = new TableViewerColumn ( this , SWT . LEFT , ) ; value . getColumn ( ) . setText ( "" ) ; value . getColumn ( ) . setWidth ( ) ; value . setEditingSupport ( new ValueEditingSupport ( getTable ( ) , this ) ) ; setColumnProperties ( new String [ ] { "" , "" , "" } ) ; setContentProvider ( contentProvider ) ; setLabelProvider ( labelProvider ) ; } public void setParameters ( List < TemplateParameter > params ) { fParameters = new ArrayList < TemplateParameter > ( ) ; if ( params != null ) { ITemplateParameterProvider pp = SVUiPlugin . getDefault ( ) . getGlobalTemplateParameters ( ) ; for ( TemplateParameter p : params ) { TemplateParameter p_d = p . duplicate ( ) ; if ( pp . providesParameter ( p . getName ( ) ) ) { p_d . setValue ( pp . getParameterValue ( p . getName ( ) , null ) ) ; } fParameters . add ( p_d ) ; } } setInput ( fParameters ) ; } public List < TemplateParameter > getParameters ( ) { return fParameters ; } public void setSourceFolder ( String src_folder ) { fSourceFolderStr = src_folder ; } public void addModifyListener ( ModifyListener l ) { fModifyListeners . add ( l ) ; } private void triggerListeners ( ) { Event ev = new Event ( ) ; ev . widget = getTable ( ) ; ModifyEvent e = new ModifyEvent ( ev ) ; e . widget = this . getTable ( ) ; for ( ModifyListener l : fModifyListeners ) { l . modifyText ( e ) ; } } IStructuredContentProvider contentProvider = new IStructuredContentProvider ( ) { public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void dispose ( ) { } public Object [ ] getElements ( Object inputElement ) { return fParameters . toArray ( ) ; } } ; private class ParamLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage ( Object element , int columnIndex ) { Image ret = null ; switch ( columnIndex ) { } return ret ; } public String getColumnText ( Object element , int columnIndex ) { String ret = "" + columnIndex ; TemplateParameter p = ( TemplateParameter ) element ; switch ( columnIndex ) { case : ret = p . getName ( ) ; break ; case : ret = p . getTypeName ( ) ; break ; case : ret = p . getValue ( ) ; break ; } return ret ; } } ; private ITableLabelProvider labelProvider = new ParamLabelProvider ( ) ; private class ValueEditingSupport extends EditingSupport { private ComboBoxCellEditor fRestrictedIdEditor ; private TextCellEditor fIdEditor ; private TextCellEditor fClassEditor ; public ValueEditingSupport ( Composite parent , ColumnViewer viewer ) { super ( viewer ) ; fRestrictedIdEditor = new ComboBoxCellEditor ( parent , new String [ ] { } , SWT . READ_ONLY ) ; fIdEditor = new TextCellEditor ( parent , SWT . NONE ) ; fClassEditor = new TextCellEditor ( parent , SWT . SEARCH + SWT . ICON_SEARCH + SWT . CANCEL + SWT . ICON_CANCEL ) ; final Text t = ( Text ) fClassEditor . getControl ( ) ; t . addListener ( SWT . DefaultSelection , new Listener ( ) { public void handleEvent ( Event event ) { ClassBrowseDialog d = new ClassBrowseDialog ( t . getShell ( ) , fSourceFolderStr , fActiveParameter . getExtFrom ( ) ) ; if ( d . open ( ) == Dialog . OK ) { t . setText ( d . getSelectedClass ( ) ) ; } } } ) ; } @ Override protected CellEditor getCellEditor ( Object element ) { CellEditor ret = null ; TemplateParameter p = ( TemplateParameter ) element ; fActiveParameter = p ; if ( p . getType ( ) == TemplateParameterType . ParameterType_Id ) { if ( p . getValues ( ) . size ( ) > ) { ret = fRestrictedIdEditor ; ( ( CCombo ) ret . getControl ( ) ) . setItems ( p . getValues ( ) . toArray ( new String [ p . getValues ( ) . size ( ) ] ) ) ; } else { ret = fIdEditor ; } } else if ( p . getType ( ) == TemplateParameterType . ParameterType_Class ) { ret = fClassEditor ; } return ret ; } @ Override protected boolean canEdit ( Object element ) { return true ; } @ Override protected Object getValue ( Object element ) { TemplateParameter p = ( TemplateParameter ) element ; if ( p . getType ( ) == TemplateParameterType . ParameterType_Id ) { if ( p . getValues ( ) . size ( ) > ) { return p . getValues ( ) . indexOf ( p . getValue ( ) ) ; } else { return p . getValue ( ) ; } } else if ( p . getType ( ) == TemplateParameterType . ParameterType_Class ) { return p . getValue ( ) ; } return "" ; } @ Override protected void setValue ( Object element , Object value ) { TemplateParameter p = ( TemplateParameter ) element ; if ( p . getType ( ) == TemplateParameterType . ParameterType_Class ) { p . setValue ( value . toString ( ) ) ; } else { if ( p . getValues ( ) . size ( ) > ) { CCombo c = ( CCombo ) fRestrictedIdEditor . getControl ( ) ; p . setValue ( c . getText ( ) ) ; } else { p . setValue ( value . toString ( ) ) ; } } refresh ( ) ; triggerListeners ( ) ; } } } package net . sf . sveditor . ui . wizards ; import net . sf . sveditor . core . srcgen . NewInterfaceGenerator ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . IProgressMonitor ; public class NewSVInterfaceWizard extends AbstractNewSVItemFileWizard { public static final String ID = SVUiPlugin . PLUGIN_ID + "" ; public NewSVInterfaceWizard ( ) { super ( ) ; } @ Override protected AbstractNewSVItemFileWizardPage createPage ( ) { return new NewSVInterfaceWizardPage ( ) ; } @ Override protected void generate ( IProgressMonitor monitor , IFile file_path ) { NewInterfaceGenerator gen = new NewInterfaceGenerator ( ) ; gen . generate ( getIndexIterator ( monitor ) , file_path , fPage . getOption ( AbstractNewSVItemFileWizardPage . NAME , null ) , monitor ) ; } } package net . sf . sveditor . ui . wizards ; import org . eclipse . swt . widgets . Composite ; public class NewSVInterfaceWizardPage extends AbstractNewSVItemFileWizardPage { public NewSVInterfaceWizardPage ( ) { super ( "" , "" , "" ) ; fFileExt = "" ; } @ Override protected void createCustomContent ( Composite src_c ) { } } package net . sf . sveditor . ui . wizards ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import org . eclipse . jface . wizard . IWizard ; import org . eclipse . jface . wizard . IWizardPage ; public abstract class AbstractSVSubWizard implements ISVSubWizard { protected IWizard fWizard ; protected Map < String , Object > fOptions ; protected List < IWizardPage > fWizardPages ; public AbstractSVSubWizard ( ) { fWizardPages = new ArrayList < IWizardPage > ( ) ; } public void init ( IWizard wizard , Map < String , Object > options ) { fWizard = wizard ; fOptions = options ; addPages ( ) ; } public abstract void addPages ( ) ; public void addPage ( IWizardPage page ) { fWizardPages . add ( page ) ; page . setWizard ( fWizard ) ; } public Map < String , Object > getOptions ( ) { return fOptions ; } public IWizardPage getNextPage ( IWizardPage page ) { IWizardPage ret = null ; int idx = fWizardPages . indexOf ( page ) ; if ( idx == - ) { ret = fWizardPages . get ( ) ; } else { if ( idx + < fWizardPages . size ( ) ) { ret = fWizardPages . get ( idx + ) ; } } return ret ; } public IWizardPage getPreviousPage ( IWizardPage page ) { int idx = fWizardPages . indexOf ( page ) ; IWizardPage ret = null ; if ( idx > ) { ret = fWizardPages . get ( idx - ) ; } return ret ; } public boolean canFinish ( ) { boolean can_finish = true ; for ( IWizardPage p : fWizardPages ) { if ( ! p . isPageComplete ( ) ) { can_finish = false ; } } return can_finish ; } } package net . sf . sveditor . ui . wizards ; import net . sf . sveditor . core . srcgen . NewModuleGenerator ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . IProgressMonitor ; public class NewSVModuleWizard extends AbstractNewSVItemFileWizard { public static final String ID = SVUiPlugin . PLUGIN_ID + "" ; public NewSVModuleWizard ( ) { super ( ) ; } @ Override protected AbstractNewSVItemFileWizardPage createPage ( ) { return new NewSVModuleWizardPage ( ) ; } @ Override protected void generate ( IProgressMonitor monitor , IFile file_path ) { NewModuleGenerator gen = new NewModuleGenerator ( ) ; gen . generate ( getIndexIterator ( monitor ) , file_path , fPage . getOption ( AbstractNewSVItemFileWizardPage . NAME , null ) , monitor ) ; } } package net . sf . sveditor . ui . wizards ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; public class DocGenBasicOptionsWizardPage extends WizardPage { private DirectoryDialog fDirDialog ; private Text fDirText ; public String getOutputDir ( ) { return fDirText . getText ( ) ; } protected DocGenBasicOptionsWizardPage ( ) { super ( "" ) ; } public void createControl ( Composite parent ) { Composite container = new Composite ( parent , SWT . NULL ) ; final GridLayout gridLayout = new GridLayout ( ) ; gridLayout . numColumns = ; container . setLayout ( gridLayout ) ; setControl ( container ) ; createLabel ( container ) ; createDirectoryField ( container ) ; } private void createLabel ( Composite container ) { final Label label = new Label ( container , SWT . NONE ) ; final GridData gridData = new GridData ( ) ; gridData . horizontalSpan = ; label . setLayoutData ( gridData ) ; label . setText ( "" ) ; } private void createDirectoryField ( Composite parent ) { Group group = new Group ( parent , SWT . NONE ) ; group . setText ( "" ) ; group . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; GridLayout gl = new GridLayout ( ) ; gl . numColumns = ; group . setLayout ( gl ) ; fDirText = new Text ( group , SWT . NONE ) ; fDirText . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fDirText . setEditable ( false ) ; fDirDialog = new DirectoryDialog ( parent . getShell ( ) , SWT . OPEN | SWT . MULTI ) ; Button button = new Button ( group , SWT . PUSH ) ; button . setText ( "" ) ; button . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { String dir = fDirDialog . open ( ) ; if ( dir != null && ! dir . isEmpty ( ) ) { fDirText . setText ( dir ) ; setPageComplete ( ! dir . isEmpty ( ) ) ; } } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; } } package net . sf . sveditor . ui . wizards ; import java . io . File ; import java . lang . reflect . InvocationTargetException ; import java . net . URL ; import java . util . HashSet ; import java . util . Set ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . docs . DocGenConfig ; import net . sf . sveditor . core . docs . IDocWriter ; import net . sf . sveditor . core . docs . html . HTMLDocWriter ; import net . sf . sveditor . core . docs . model . DocModelFactory ; import net . sf . sveditor . core . docs . model . DocModel ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . wizard . Wizard ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . browser . IWebBrowser ; import org . eclipse . ui . browser . IWorkbenchBrowserSupport ; public class DocGenWizard extends Wizard { DocGenSelectPkgsWizardPage fSelectPkgsPage ; DocGenBasicOptionsWizardPage fBasicOptionsPage ; IWorkbench workbench ; LogHandle log ; public DocGenWizard ( ) { log = LogFactory . getLogHandle ( "" ) ; } @ Override public boolean performFinish ( ) { final DocGenConfig cfg = new DocGenConfig ( ) ; Set < Tuple < SVDBDeclCacheItem , ISVDBIndex > > pkgs = new HashSet < Tuple < SVDBDeclCacheItem , ISVDBIndex > > ( ) ; for ( SVDBDeclCacheItem pkg : fSelectPkgsPage . getSelectedPackages ( ) ) { pkgs . add ( fSelectPkgsPage . getPkgMap ( ) . get ( pkg . getName ( ) ) ) ; } cfg . setSelectedPackages ( pkgs ) ; cfg . setOutputDir ( new File ( fBasicOptionsPage . getOutputDir ( ) ) ) ; try { getContainer ( ) . run ( true , true , new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { performOperation ( cfg , monitor ) ; } } ) ; } catch ( InvocationTargetException e ) { log . error ( "" , e ) ; } catch ( InterruptedException e ) { log . debug ( ILogLevel . LEVEL_MIN , "" , e ) ; } return true ; } public void init ( IWorkbench workbench ) { this . workbench = workbench ; } @ Override public void addPages ( ) { super . addPages ( ) ; setWindowTitle ( "" ) ; fSelectPkgsPage = new DocGenSelectPkgsWizardPage ( ) ; addPage ( fSelectPkgsPage ) ; fBasicOptionsPage = new DocGenBasicOptionsWizardPage ( ) ; addPage ( fBasicOptionsPage ) ; } @ Override public boolean canFinish ( ) { return fSelectPkgsPage . hasSelection ( ) && ! ( fBasicOptionsPage . getOutputDir ( ) . isEmpty ( ) ) ; } @ Override public boolean performCancel ( ) { return super . performCancel ( ) ; } private void performOperation ( DocGenConfig cfg , IProgressMonitor monitor ) { class DocGenJob extends Job { private final DocGenConfig cfg ; public DocGenJob ( String jobTitle , DocGenConfig cfg ) { super ( jobTitle ) ; this . cfg = cfg ; } @ Override protected IStatus run ( IProgressMonitor monitor ) { DocModelFactory factory = new DocModelFactory ( ) ; DocModel model = factory . build ( cfg ) ; monitor . worked ( ) ; IDocWriter writer = new HTMLDocWriter ( ) ; writer . write ( cfg , model ) ; monitor . worked ( ) ; final File file = writer . getIndexHTML ( cfg , model ) ; Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { openIndexHTML ( file ) ; } } ) ; monitor . done ( ) ; return Status . OK_STATUS ; } private void openIndexHTML ( File indexHTML ) { try { URL url = new URL ( "" + indexHTML ) ; IWorkbenchBrowserSupport browserSupport = workbench . getBrowserSupport ( ) ; IWebBrowser browser ; int style = IWorkbenchBrowserSupport . AS_EDITOR ; browser = browserSupport . createBrowser ( style , "" , "" , "" ) ; browser . openURL ( url ) ; } catch ( Exception e ) { log . error ( "" , e ) ; return ; } } } DocGenJob job = new DocGenJob ( "" , cfg ) ; job . schedule ( ) ; } } package net . sf . sveditor . ui . wizards ; import java . util . Map ; import org . eclipse . jface . wizard . IWizard ; import org . eclipse . jface . wizard . IWizardPage ; public interface ISVSubWizard { void init ( IWizard wizard , Map < String , Object > options ) ; IWizardPage getNextPage ( IWizardPage page ) ; IWizardPage getPreviousPage ( IWizardPage page ) ; boolean canFinish ( ) ; } package net . sf . sveditor . ui . wizards ; import org . eclipse . swt . widgets . Composite ; public class NewSVPackageWizardPage extends AbstractNewSVItemFileWizardPage { public NewSVPackageWizardPage ( ) { super ( "" , "" , "" ) ; fFileExt = "" ; } @ Override protected void createCustomContent ( Composite src_c ) { } } package net . sf . sveditor . ui . wizards ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; public class NewSVClassWizardPage extends AbstractNewSVItemFileWizardPage { public static final String SUPER_CLASS = "" ; public static final String OVERRIDE_NEW = "" ; private Text fSuperClass ; private Button fSuperClassBrowse ; private Button fOverrideNew ; public NewSVClassWizardPage ( ) { super ( "" , "" , "" ) ; setOption ( OVERRIDE_NEW , "" ) ; } @ Override protected void createCustomContent ( Composite src_c ) { Label l ; GridData gd ; l = new Label ( src_c , SWT . NONE ) ; l . setText ( "" ) ; fSuperClass = new Text ( src_c , SWT . BORDER ) ; fSuperClass . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; fSuperClass . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { setOption ( SUPER_CLASS , fSuperClass . getText ( ) ) ; validate ( ) ; } } ) ; fSuperClassBrowse = new Button ( src_c , SWT . NONE ) ; fSuperClassBrowse . setText ( "" ) ; fSuperClassBrowse . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { browseClass ( ) ; validate ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; Group group = new Group ( src_c , SWT . BORDER ) ; group . setText ( "" ) ; group . setLayout ( new GridLayout ( ) ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = ; group . setLayoutData ( gd ) ; fOverrideNew = new Button ( group , SWT . CHECK ) ; fOverrideNew . setText ( "" ) ; fOverrideNew . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { setOption ( OVERRIDE_NEW , ( fOverrideNew . getSelection ( ) ) ? "" : "" ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; fOverrideNew . setSelection ( true ) ; } @ Override protected void sourceFolderChanged ( ) { updateClassBrowseState ( ) ; } private void updateClassBrowseState ( ) { fSuperClassBrowse . setEnabled ( ( findDestProject ( ) != null ) ) ; } private void browseClass ( ) { SVDBProjectData pdata = getProjectData ( ) ; BrowseClasses dlg = new BrowseClasses ( fSuperClass . getShell ( ) , pdata . getProjectIndexMgr ( ) ) ; dlg . setClassName ( getOption ( SUPER_CLASS , "" ) ) ; if ( dlg . open ( ) == Window . OK ) { SVDBClassDecl cls = dlg . getSelectedClass ( ) ; if ( cls != null ) { fSuperClass . setText ( cls . getName ( ) ) ; } } } } package net . sf . sveditor . ui . wizards ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . ui . WorkspaceDirectoryDialog ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . window . Window ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; abstract public class AbstractNewSVItemFileWizardPage extends WizardPage { public static final String SOURCE_FOLDER = "" ; public static final String NAME = "" ; public static final String FILE_NAME = "" ; protected Map < String , String > fOptions ; protected String fFileExt ; private Text fSourceFolder ; private Text fName ; private Text fFileName ; private Button fFileNameDefault ; public AbstractNewSVItemFileWizardPage ( String title , String type , String description ) { super ( title , type , null ) ; setDescription ( description ) ; fFileExt = "" ; fOptions = new HashMap < String , String > ( ) ; setOption ( NAME , "" ) ; } public String getOption ( String key , String dflt ) { if ( fOptions . containsKey ( key ) ) { return fOptions . get ( key ) ; } else { return dflt ; } } public void setOption ( String key , String val ) { if ( fOptions . containsKey ( key ) ) { fOptions . remove ( key ) ; } fOptions . put ( key , val ) ; } abstract protected void createCustomContent ( Composite c ) ; protected void sourceFolderChanged ( ) { } public void createControl ( Composite parent ) { Label l ; final Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new GridLayout ( ) ) ; Composite src_c = new Composite ( c , SWT . NONE ) ; src_c . setLayout ( new GridLayout ( , false ) ) ; src_c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; l = new Label ( src_c , SWT . NONE ) ; l . setText ( "" ) ; fSourceFolder = new Text ( src_c , SWT . BORDER ) ; fSourceFolder . setText ( getOption ( SOURCE_FOLDER , "" ) ) ; fSourceFolder . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; fSourceFolder . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { setOption ( SOURCE_FOLDER , fSourceFolder . getText ( ) ) ; sourceFolderChanged ( ) ; validate ( ) ; } } ) ; final Button sf_browse = new Button ( src_c , SWT . PUSH ) ; sf_browse . setText ( "" ) ; sf_browse . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { WorkspaceDirectoryDialog dlg = new WorkspaceDirectoryDialog ( sf_browse . getShell ( ) ) ; if ( dlg . open ( ) == Window . OK ) { fSourceFolder . setText ( dlg . getPath ( ) ) ; } validate ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; Composite s = new Composite ( src_c , SWT . BORDER ) ; GridData gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; gd . heightHint = ; s . setLayoutData ( gd ) ; l = new Label ( src_c , SWT . NONE ) ; l . setText ( "" ) ; fName = new Text ( src_c , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; gd . horizontalSpan = ; fName . setLayoutData ( gd ) ; fName . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { setOption ( NAME , fName . getText ( ) ) ; if ( fFileNameDefault . getSelection ( ) ) { fFileName . setEnabled ( true ) ; if ( ! getOption ( NAME , "" ) . equals ( "" ) ) { fFileName . setText ( getOption ( NAME , "" ) + fFileExt ) ; } else { fFileName . setText ( "" ) ; } fFileName . setEnabled ( false ) ; } validate ( ) ; } } ) ; l = new Label ( src_c , SWT . NONE ) ; l . setText ( "" ) ; fFileName = new Text ( src_c , SWT . BORDER ) ; fFileName . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; fFileName . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { setOption ( FILE_NAME , fFileName . getText ( ) ) ; validate ( ) ; } } ) ; fFileNameDefault = new Button ( src_c , SWT . CHECK ) ; fFileNameDefault . setText ( "" ) ; fFileNameDefault . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { if ( ! fFileNameDefault . getSelection ( ) ) { fFileName . setEditable ( true ) ; fFileName . setEnabled ( true ) ; } else { fFileName . setEnabled ( true ) ; if ( ! getOption ( NAME , "" ) . equals ( "" ) ) { fFileName . setText ( getOption ( NAME , "" ) + fFileExt ) ; } else { fFileName . setText ( "" ) ; } fFileName . setEnabled ( false ) ; fFileName . setEditable ( false ) ; } validate ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; fFileNameDefault . setSelection ( true ) ; fFileName . setEnabled ( false ) ; fFileName . setEditable ( false ) ; createCustomContent ( src_c ) ; fName . setFocus ( ) ; setPageComplete ( false ) ; setControl ( c ) ; } protected void validate ( ) { setErrorMessage ( null ) ; if ( ! SVCharacter . isSVIdentifier ( getOption ( NAME , "" ) ) ) { setErrorMessage ( "" ) ; } IContainer c = SVFileUtils . getWorkspaceFolder ( getOption ( SOURCE_FOLDER , "" ) ) ; if ( c != null ) { String filename_str = getOption ( FILE_NAME , null ) ; if ( filename_str != null && ! filename_str . equals ( "" ) ) { IFile f = c . getFile ( new Path ( filename_str ) ) ; if ( f . exists ( ) ) { setErrorMessage ( "" + filename_str + "" ) ; } } } else { setErrorMessage ( "" + getOption ( SOURCE_FOLDER , "" ) + "" ) ; } setPageComplete ( ( getErrorMessage ( ) == null ) ) ; } protected IProject findDestProject ( ) { IContainer c = SVFileUtils . getWorkspaceFolder ( getOption ( SOURCE_FOLDER , "" ) ) ; if ( c == null ) { return null ; } else if ( c instanceof IProject ) { return ( IProject ) c ; } else { return c . getProject ( ) ; } } public SVDBProjectData getProjectData ( ) { IProject p = findDestProject ( ) ; if ( p == null ) { return null ; } SVDBProjectData pdata = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( p ) ; return pdata ; } } package net . sf . sveditor . ui ; import java . net . URI ; import net . sf . sveditor . core . db . index . plugin_lib . PluginFileStore ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPersistableElement ; import org . eclipse . ui . editors . text . ILocationProvider ; import org . eclipse . ui . editors . text . ILocationProviderExtension ; import org . eclipse . ui . ide . FileStoreEditorInput ; public class PluginPathEditorInput extends FileStoreEditorInput { PluginFileStore fFileStore ; public PluginPathEditorInput ( PluginFileStore file ) throws CoreException { super ( file ) ; fFileStore = file ; } public PluginFileStore getFileStore ( ) { return fFileStore ; } public IPersistableElement getPersistable ( ) { return this ; } @ SuppressWarnings ( "" ) public Object getAdapter ( Class adapter ) { if ( IFile . class . equals ( adapter ) || IResource . class . equals ( adapter ) ) { return null ; } else if ( ILocationProvider . class . equals ( adapter ) ) { return new LocationProvider ( ( PluginFileStore ) fFileStore ) ; } else { return super . getAdapter ( adapter ) ; } } public boolean equals ( Object o ) { if ( o == this ) { return true ; } if ( o instanceof PluginPathEditorInput ) { PluginPathEditorInput in = ( PluginPathEditorInput ) o ; return fFileStore . equals ( in . fFileStore ) ; } return false ; } public String getFactoryId ( ) { return PluginFileEditorInputFactory . ID ; } public void saveState ( IMemento memento ) { PluginFileEditorInputFactory . saveState ( memento , this ) ; } private class LocationProvider implements ILocationProvider , ILocationProviderExtension { PluginFileStore fFileStore ; public LocationProvider ( PluginFileStore fs ) { fFileStore = fs ; } public URI getURI ( Object element ) { String path = ( ( PluginFileStore ) fFileStore ) . getPluginPath ( ) ; try { return new URI ( path ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; } public IPath getPath ( Object element ) { String path = ( ( PluginFileStore ) fFileStore ) . getPluginPath ( ) ; return new Path ( path ) ; } } ; } package net . sf . sveditor . ui . argfile . editor ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . svf_scanner . SVFScanner ; import net . sf . sveditor . ui . editor . SVEditorColors ; import org . eclipse . jface . text . TextAttribute ; import org . eclipse . jface . text . rules . EndOfLineRule ; import org . eclipse . jface . text . rules . IRule ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . IWordDetector ; import org . eclipse . jface . text . rules . MultiLineRule ; import org . eclipse . jface . text . rules . RuleBasedScanner ; import org . eclipse . jface . text . rules . SingleLineRule ; import org . eclipse . jface . text . rules . Token ; import org . eclipse . jface . text . rules . WordRule ; public class SVArgFileCodeScanner extends RuleBasedScanner { public SVArgFileCodeScanner ( ) { updateRules ( ) ; } public void updateRules ( ) { IToken keyword = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . KEYWORD ) , null , SVEditorColors . getStyle ( SVEditorColors . KEYWORD ) ) ) ; final IToken str = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . STRING ) , null , SVEditorColors . getStyle ( SVEditorColors . STRING ) ) ) ; final IToken slc = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . SINGLE_LINE_COMMENT ) , null , SVEditorColors . getStyle ( SVEditorColors . SINGLE_LINE_COMMENT ) ) ) ; final IToken mlc = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . MULTI_LINE_COMMENT ) , null , SVEditorColors . getStyle ( SVEditorColors . MULTI_LINE_COMMENT ) ) ) ; IToken default_t = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . DEFAULT ) , null , SVEditorColors . getStyle ( SVEditorColors . DEFAULT ) ) ) ; setDefaultReturnToken ( default_t ) ; List < IRule > rules = new ArrayList < IRule > ( ) ; rules . add ( new EndOfLineRule ( "" , slc ) ) ; rules . add ( new MultiLineRule ( "" , "" , mlc , ( char ) , true ) ) ; rules . add ( new SingleLineRule ( "" , "" , str , '' ) ) ; WordRule wordRule = new WordRule ( new SVArgFileWordDetector ( ) , default_t ) ; for ( String kw : SVFScanner . fRecognizedSwitches ) { wordRule . addWord ( kw , keyword ) ; } rules . add ( wordRule ) ; IRule [ ] ruleArray = rules . toArray ( new IRule [ rules . size ( ) ] ) ; setRules ( ruleArray ) ; } } package net . sf . sveditor . ui . argfile . editor ; import net . sf . sveditor . ui . editor . SVCodeScanner ; import net . sf . sveditor . ui . editor . SVDocumentPartitions ; import net . sf . sveditor . ui . editor . SVEditorColors ; import net . sf . sveditor . ui . editor . SVPresentationReconciler ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextAttribute ; import org . eclipse . jface . text . presentation . IPresentationReconciler ; import org . eclipse . jface . text . presentation . PresentationReconciler ; import org . eclipse . jface . text . rules . BufferedRuleBasedScanner ; import org . eclipse . jface . text . rules . DefaultDamagerRepairer ; import org . eclipse . jface . text . rules . Token ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; public class SVArgFileSourceViewerConfiguration extends SourceViewerConfiguration { private SVArgFileEditor fEditor ; public SVArgFileSourceViewerConfiguration ( SVArgFileEditor editor ) { fEditor = editor ; } @ Override public IPresentationReconciler getPresentationReconciler ( ISourceViewer viewer ) { PresentationReconciler r = new SVPresentationReconciler ( ) ; r . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( viewer ) ) ; DefaultDamagerRepairer dr ; if ( fEditor != null ) { dr = new DefaultDamagerRepairer ( fEditor . getCodeScanner ( ) ) ; } else { dr = new DefaultDamagerRepairer ( new SVCodeScanner ( ) ) ; } r . setDamager ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; r . setRepairer ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; BufferedRuleBasedScanner scanner ; scanner = new BufferedRuleBasedScanner ( ) ; scanner . setDefaultReturnToken ( new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . MULTI_LINE_COMMENT ) , null , SVEditorColors . getStyle ( SVEditorColors . MULTI_LINE_COMMENT ) ) ) ) ; dr = new DefaultDamagerRepairer ( scanner ) ; r . setDamager ( dr , SVArgFileDocumentPartitions . SV_ARGFILE_MULTILINE_COMMENT ) ; r . setRepairer ( dr , SVArgFileDocumentPartitions . SV_ARGFILE_MULTILINE_COMMENT ) ; scanner = new BufferedRuleBasedScanner ( ) ; scanner . setDefaultReturnToken ( new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . SINGLE_LINE_COMMENT ) , null , SVEditorColors . getStyle ( SVEditorColors . SINGLE_LINE_COMMENT ) ) ) ) ; dr = new DefaultDamagerRepairer ( scanner ) ; r . setDamager ( dr , SVArgFileDocumentPartitions . SV_ARGFILE_SINGLELINE_COMMENT ) ; r . setRepairer ( dr , SVArgFileDocumentPartitions . SV_ARGFILE_SINGLELINE_COMMENT ) ; return r ; } @ Override public String [ ] getConfiguredContentTypes ( ISourceViewer sourceViewer ) { return new String [ ] { IDocument . DEFAULT_CONTENT_TYPE , SVArgFileDocumentPartitions . SV_ARGFILE_MULTILINE_COMMENT , SVArgFileDocumentPartitions . SV_ARGFILE_SINGLELINE_COMMENT , SVArgFileDocumentPartitions . SV_ARGFILE_KEYWORD } ; } @ Override public String getConfiguredDocumentPartitioning ( ISourceViewer sourceViewer ) { return SVArgFileDocumentPartitions . SV_ARGFILE_PARTITIONING ; } } package net . sf . sveditor . ui . argfile . editor ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . ui . editor . CCommentRule ; import org . eclipse . core . filebuffers . IDocumentSetupParticipant ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . IDocumentPartitioner ; import org . eclipse . jface . text . rules . EndOfLineRule ; import org . eclipse . jface . text . rules . FastPartitioner ; import org . eclipse . jface . text . rules . IPartitionTokenScanner ; import org . eclipse . jface . text . rules . IPredicateRule ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . RuleBasedPartitionScanner ; import org . eclipse . jface . text . rules . Token ; public class SVArgFileDocSetupParticipant implements IDocumentSetupParticipant { public void setup ( IDocument doc ) { if ( doc instanceof IDocumentExtension3 ) { IDocumentExtension3 docExt = ( IDocumentExtension3 ) doc ; IDocumentPartitioner p = createPartitioner ( ) ; docExt . setDocumentPartitioner ( SVArgFileDocumentPartitions . SV_ARGFILE_PARTITIONING , p ) ; p . connect ( doc ) ; } } public static IDocumentPartitioner createPartitioner ( ) { IDocumentPartitioner p = new FastPartitioner ( createScanner ( ) , SVArgFileDocumentPartitions . SV_ARGFILE_PARTITION_TYPES ) ; return p ; } private static IPartitionTokenScanner createScanner ( ) { RuleBasedPartitionScanner scanner = new RuleBasedPartitionScanner ( ) ; IToken mlc = new Token ( SVArgFileDocumentPartitions . SV_ARGFILE_MULTILINE_COMMENT ) ; IToken slc = new Token ( SVArgFileDocumentPartitions . SV_ARGFILE_SINGLELINE_COMMENT ) ; List < IPredicateRule > rules = new ArrayList < IPredicateRule > ( ) ; rules . add ( new EndOfLineRule ( "" , slc ) ) ; rules . add ( new CCommentRule ( mlc ) ) ; IPredicateRule rulesArr [ ] = rules . toArray ( new IPredicateRule [ rules . size ( ) ] ) ; scanner . setDefaultReturnToken ( new Token ( IDocument . DEFAULT_CONTENT_TYPE ) ) ; scanner . setPredicateRules ( rulesArr ) ; return scanner ; } } package net . sf . sveditor . ui . argfile . editor ; import java . util . ResourceBundle ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . argfile . editor . actions . OpenDeclarationAction ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . editors . text . TextEditor ; public class SVArgFileEditor extends TextEditor implements ILogLevel { private SVArgFileCodeScanner fCodeScanner ; public SVArgFileEditor ( ) { fCodeScanner = new SVArgFileCodeScanner ( ) ; } public SVArgFileCodeScanner getCodeScanner ( ) { return fCodeScanner ; } @ Override protected void createActions ( ) { super . createActions ( ) ; ResourceBundle bundle = SVUiPlugin . getDefault ( ) . getResources ( ) ; OpenDeclarationAction od_action = new OpenDeclarationAction ( bundle , this ) ; od_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , od_action ) ; markAsStateDependentAction ( SVUiPlugin . PLUGIN_ID + "" , false ) ; markAsSelectionDependentAction ( SVUiPlugin . PLUGIN_ID + "" , false ) ; } @ Override protected void initializeKeyBindingScopes ( ) { super . initializeKeyBindingScopes ( ) ; } @ Override public void createPartControl ( Composite parent ) { setSourceViewerConfiguration ( new SVArgFileSourceViewerConfiguration ( this ) ) ; super . createPartControl ( parent ) ; } } package net . sf . sveditor . ui . argfile . editor ; public interface SVArgFileDocumentPartitions { String SV_ARGFILE_MULTILINE_COMMENT = "" ; String SV_ARGFILE_SINGLELINE_COMMENT = "" ; String SV_ARGFILE_KEYWORD = "" ; String [ ] SV_ARGFILE_PARTITION_TYPES = { SV_ARGFILE_MULTILINE_COMMENT , SV_ARGFILE_SINGLELINE_COMMENT , SV_ARGFILE_KEYWORD } ; String SV_ARGFILE_PARTITIONING = "" ; } package net . sf . sveditor . ui . argfile . editor ; import org . eclipse . jface . text . rules . IWordDetector ; public class SVArgFileWordDetector implements IWordDetector { private boolean fStartsWithPlus ; private char fLastCh = '' ; public boolean isWordStart ( char c ) { fStartsWithPlus = ( c == '' ) ; fLastCh = '' ; return ( Character . isJavaIdentifierStart ( c ) || c == '' || c == '' ) ; } public boolean isWordPart ( char c ) { if ( fLastCh == '' && fStartsWithPlus ) { return false ; } else { fLastCh = c ; return ( Character . isJavaIdentifierPart ( c ) || c == '' ) ; } } } package net . sf . sveditor . ui . argfile . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . ui . argfile . editor . SVArgFileEditor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OpenDeclarationAction extends TextEditorAction { private SVArgFileEditor fEditor ; private LogHandle fLog ; private boolean fDebugEn = true ; public OpenDeclarationAction ( ResourceBundle bundle , SVArgFileEditor editor ) { super ( bundle , "" , editor ) ; fLog = LogFactory . getLogHandle ( "" ) ; fEditor = editor ; update ( ) ; } protected ITextSelection getTextSel ( ) { ITextSelection sel = null ; if ( getTextEditor ( ) != null ) { ISelection sel_o = getTextEditor ( ) . getSelectionProvider ( ) . getSelection ( ) ; if ( sel_o != null && sel_o instanceof ITextSelection ) { sel = ( ITextSelection ) sel_o ; } } return sel ; } @ Override public void run ( ) { debug ( "" ) ; } protected IDocument getDocument ( ) { return fEditor . getDocumentProvider ( ) . getDocument ( fEditor . getEditorInput ( ) ) ; } private void debug ( String msg ) { if ( fDebugEn ) { fLog . debug ( msg ) ; } } } package net . sf . sveditor . ui . prop_pages ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . project . SVDBSourceCollection ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public class SourceCollectionsPage implements ISVProjectPropsPage , ITreeContentProvider , ILabelProvider { private TreeViewer fSourceCollectionsTree ; private SVProjectFileWrapper fFileWrapper ; private Button fAddButton ; private Button fEditButton ; private Button fRemoveButton ; private List < SVDBSourceCollection > fSourceCollections ; private IProject fProject ; public SourceCollectionsPage ( IProject p ) { fSourceCollections = new ArrayList < SVDBSourceCollection > ( ) ; fProject = p ; } public void init ( SVProjectFileWrapper project_wrapper ) { fFileWrapper = project_wrapper ; fSourceCollections . clear ( ) ; fSourceCollections . addAll ( fFileWrapper . getSourceCollections ( ) ) ; } public Control createContents ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; fSourceCollectionsTree = new TreeViewer ( frame , SWT . BORDER ) ; fSourceCollectionsTree . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fSourceCollectionsTree . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { updateSelection ( ) ; } } ) ; fSourceCollectionsTree . setContentProvider ( this ) ; fSourceCollectionsTree . setLabelProvider ( this ) ; fSourceCollectionsTree . setInput ( fSourceCollections ) ; Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; fAddButton = new Button ( button_bar , SWT . PUSH ) ; fAddButton . setText ( "" ) ; fAddButton . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { add ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; fEditButton = new Button ( button_bar , SWT . PUSH ) ; fEditButton . setText ( "" ) ; fEditButton . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { edit ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; fRemoveButton = new Button ( button_bar , SWT . PUSH ) ; fRemoveButton . setText ( "" ) ; fRemoveButton . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { remove ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; updateSelection ( ) ; return frame ; } private void updateSelection ( ) { IStructuredSelection sel = ( IStructuredSelection ) fSourceCollectionsTree . getSelection ( ) ; if ( sel != null && sel . size ( ) != ) { if ( sel . size ( ) == && sel . getFirstElement ( ) instanceof SVDBSourceCollection ) { fEditButton . setEnabled ( true ) ; } else { fEditButton . setEnabled ( false ) ; } fRemoveButton . setEnabled ( true ) ; } else { fRemoveButton . setEnabled ( false ) ; } } private void add ( ) { AddSourceCollectionDialog dlg = new AddSourceCollectionDialog ( fAddButton . getShell ( ) , fProject ) ; dlg . setIncludes ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionIncludes ( ) ) ; dlg . setExcludes ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionExcludes ( ) ) ; if ( dlg . open ( ) == Window . OK ) { SVDBSourceCollection sc = new SVDBSourceCollection ( dlg . getBase ( ) , dlg . getUseDefaultPattern ( ) ) ; if ( ! dlg . getUseDefaultPattern ( ) ) { sc . getIncludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( dlg . getIncludes ( ) ) ) ; sc . getExcludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( dlg . getExcludes ( ) ) ) ; } fSourceCollections . add ( sc ) ; fSourceCollectionsTree . refresh ( ) ; } } private void edit ( ) { IStructuredSelection sel = ( IStructuredSelection ) fSourceCollectionsTree . getSelection ( ) ; if ( sel != null && sel . size ( ) == ) { AddSourceCollectionDialog dlg = new AddSourceCollectionDialog ( fEditButton . getShell ( ) , fProject ) ; SVDBSourceCollection sc = ( SVDBSourceCollection ) sel . getFirstElement ( ) ; dlg . setBase ( sc . getBaseLocation ( ) ) ; dlg . setUseDefaultPattern ( sc . getDefaultIncExcl ( ) ) ; dlg . setIncludes ( sc . getIncludesStr ( ) ) ; dlg . setExcludes ( sc . getExcludesStr ( ) ) ; if ( dlg . open ( ) == Window . OK ) { int sc_idx = fSourceCollections . indexOf ( sc ) ; sc = new SVDBSourceCollection ( dlg . getBase ( ) , dlg . getUseDefaultPattern ( ) ) ; if ( ! dlg . getUseDefaultPattern ( ) ) { sc . getIncludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( dlg . getIncludes ( ) ) ) ; sc . getExcludes ( ) . addAll ( SVDBSourceCollection . parsePatternList ( dlg . getExcludes ( ) ) ) ; } else { } fSourceCollections . set ( sc_idx , sc ) ; fSourceCollectionsTree . refresh ( ) ; } } } private void remove ( ) { IStructuredSelection sel = ( IStructuredSelection ) fSourceCollectionsTree . getSelection ( ) ; if ( sel != null && sel . size ( ) > ) { for ( Object s_o : sel . toList ( ) ) { fSourceCollections . remove ( s_o ) ; } } fSourceCollectionsTree . refresh ( ) ; } public Image getIcon ( ) { return SVUiPlugin . getImage ( "" ) ; } public String getName ( ) { return "" ; } public void perfomOk ( ) { fFileWrapper . getSourceCollections ( ) . clear ( ) ; fFileWrapper . getSourceCollections ( ) . addAll ( fSourceCollections ) ; } public Object [ ] getElements ( Object inputElement ) { return fSourceCollections . toArray ( ) ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { if ( element instanceof SVDBSourceCollection ) { return ( ( SVDBSourceCollection ) element ) . getBaseLocation ( ) ; } else if ( element instanceof IncExclWrapper ) { return ( ( IncExclWrapper ) element ) . fLabel ; } return null ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof SVDBSourceCollection ) { SVDBSourceCollection sc = ( SVDBSourceCollection ) parentElement ; IncExclWrapper inc = new IncExclWrapper ( ) ; inc . fParent = sc ; if ( sc . getDefaultIncExcl ( ) ) { inc . fLabel = "" + sc . getIncludesStr ( ) ; } else { inc . fLabel = "" + sc . getIncludesStr ( ) ; } IncExclWrapper exc = new IncExclWrapper ( ) ; exc . fParent = sc ; if ( sc . getDefaultIncExcl ( ) ) { exc . fLabel = "" + sc . getExcludesStr ( ) ; } else { exc . fLabel = "" + sc . getExcludesStr ( ) ; } return new Object [ ] { inc , exc } ; } else { return new Object [ ] ; } } public Object getParent ( Object element ) { if ( element instanceof IncExclWrapper ) { return ( ( IncExclWrapper ) element ) . fParent ; } return null ; } public boolean hasChildren ( Object element ) { return ( element instanceof SVDBSourceCollection ) ; } public void addListener ( ILabelProviderListener listener ) { } public boolean isLabelProperty ( Object element , String property ) { return false ; } public void removeListener ( ILabelProviderListener listener ) { } private class IncExclWrapper { public String fLabel ; public SVDBSourceCollection fParent ; } } package net . sf . sveditor . ui . prop_pages ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class AddDefineDialog extends Dialog { private Text fName ; private String fNameStr ; private Text fValue ; private String fValueStr ; public AddDefineDialog ( Shell shell ) { super ( shell ) ; } public void setInitialName ( String path ) { fNameStr = path ; } public void setInitialValue ( String value ) { fValueStr = value ; } public String getName ( ) { return fNameStr ; } public String getValue ( ) { return fValueStr ; } @ Override protected Control createDialogArea ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; Label l ; GridData gd ; l = new Label ( frame , SWT . NONE ) ; l . setText ( "" ) ; fName = new Text ( frame , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . widthHint = ; fName . setLayoutData ( gd ) ; fName . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fNameStr = fName . getText ( ) ; } } ) ; if ( fNameStr != null ) { fName . setText ( fNameStr ) ; } l = new Label ( frame , SWT . NONE ) ; l . setText ( "" ) ; fValue = new Text ( frame , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . widthHint = ; fValue . setLayoutData ( gd ) ; fValue . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fValueStr = fValue . getText ( ) ; } } ) ; if ( fValueStr != null ) { fValue . setText ( fValueStr ) ; } else { fValueStr = "" ; } return frame ; } } package net . sf . sveditor . ui . prop_pages ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public interface ISVProjectPropsPage { String getName ( ) ; Image getIcon ( ) ; void init ( SVProjectFileWrapper project_wrapper ) ; Control createContents ( Composite parent ) ; void perfomOk ( ) ; } package net . sf . sveditor . ui . prop_pages ; import net . sf . sveditor . ui . WorkspaceFileDialog ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class AddFilePathDialog extends Dialog { private Text fPath ; private String fPathStr ; private IProject fProject ; public AddFilePathDialog ( Shell shell , IProject p ) { super ( shell ) ; fProject = p ; } public void setInitialPath ( String path ) { fPathStr = path ; } public String getPath ( ) { return fPathStr ; } @ Override protected Control createDialogArea ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; GridData gd ; fPath = new Text ( frame , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . widthHint = ; fPath . setLayoutData ( gd ) ; fPath . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fPathStr = fPath . getText ( ) ; } } ) ; if ( fPathStr != null ) { fPath . setText ( fPathStr ) ; } Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; button_bar . setLayoutData ( new GridData ( SWT . CENTER , SWT . FILL , false , true ) ) ; Button add_proj_path = new Button ( button_bar , SWT . PUSH ) ; add_proj_path . setText ( "" ) ; add_proj_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; add_proj_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { ProjectFileDialog dlg = new ProjectFileDialog ( getShell ( ) , fProject ) ; if ( dlg . open ( ) == Window . OK ) { if ( dlg . getPath ( ) != null ) { fPath . setText ( "" + dlg . getPath ( ) ) ; } } } } ) ; Button add_ws_path = new Button ( button_bar , SWT . PUSH ) ; add_ws_path . setText ( "" ) ; add_ws_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; add_ws_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { WorkspaceFileDialog dlg = new WorkspaceFileDialog ( getShell ( ) ) ; if ( dlg . open ( ) == Window . OK ) { if ( dlg . getPath ( ) != null ) { fPath . setText ( "" + dlg . getPath ( ) ) ; } } } } ) ; Button add_fs_path = new Button ( button_bar , SWT . PUSH ) ; add_fs_path . setText ( "" ) ; add_fs_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; add_fs_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { FileDialog dlg = new FileDialog ( getShell ( ) ) ; dlg . setText ( "" ) ; String result = dlg . open ( ) ; if ( result != null && ! result . trim ( ) . equals ( "" ) ) { fPath . setText ( result ) ; } } } ) ; return frame ; } } package net . sf . sveditor . ui . prop_pages ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . ui . WorkspaceFileDialog ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class AddSourceCollectionDialog extends Dialog { private Text fPath ; private boolean fUseDefaults = true ; private Text fIncludes ; private String fIncludeStr ; private Text fExcludes ; private String fExcludeStr ; private String fPathStr ; private IProject fProject ; public AddSourceCollectionDialog ( Shell shell , IProject p ) { super ( shell ) ; fProject = p ; } public void setBase ( String path ) { fPathStr = path ; } public String getBase ( ) { return fPathStr ; } public void setUseDefaultPattern ( boolean use ) { fUseDefaults = use ; } public boolean getUseDefaultPattern ( ) { return fUseDefaults ; } public void setIncludes ( String inc ) { fIncludeStr = inc ; } public String getIncludes ( ) { return fIncludeStr ; } public void setExcludes ( String exc ) { fExcludeStr = exc ; } public String getExcludes ( ) { return fExcludeStr ; } @ Override protected Control createDialogArea ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; Composite entry_c = new Composite ( frame , SWT . NONE ) ; entry_c . setLayout ( new GridLayout ( , true ) ) ; entry_c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; GridData gd ; Group g ; g = new Group ( entry_c , SWT . BORDER ) ; g . setText ( "" ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . widthHint = ; g . setLayout ( new GridLayout ( , true ) ) ; g . setLayoutData ( gd ) ; fPath = new Text ( g , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . widthHint = ; fPath . setLayoutData ( gd ) ; fPath . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fPathStr = fPath . getText ( ) ; } } ) ; if ( fPathStr != null ) { fPath . setText ( fPathStr ) ; } Composite pattern_group = new Composite ( entry_c , SWT . NONE ) ; pattern_group . setLayout ( new GridLayout ( , false ) ) ; pattern_group . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Button use_default = new Button ( pattern_group , SWT . CHECK ) ; use_default . setSelection ( fUseDefaults ) ; use_default . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { fUseDefaults = ( ( Button ) e . getSource ( ) ) . getSelection ( ) ; if ( fUseDefaults ) { fIncludes . setEnabled ( true ) ; fExcludes . setEnabled ( true ) ; fIncludes . setText ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionIncludes ( ) ) ; fExcludes . setText ( SVCorePlugin . getDefault ( ) . getDefaultSourceCollectionExcludes ( ) ) ; } fIncludes . setEditable ( ! fUseDefaults ) ; fIncludes . setEnabled ( ! fUseDefaults ) ; fExcludes . setEditable ( ! fUseDefaults ) ; fExcludes . setEnabled ( ! fUseDefaults ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; use_default . setLayoutData ( new GridData ( SWT . CENTER , SWT . CENTER , false , false , , ) ) ; g = new Group ( pattern_group , SWT . NONE ) ; g . setText ( "" ) ; g . setLayout ( new GridLayout ( , true ) ) ; g . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fIncludes = new Text ( g , SWT . NONE ) ; fIncludes . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; if ( fIncludeStr != null ) { fIncludes . setText ( fIncludeStr ) ; } fIncludes . setEditable ( ! fUseDefaults ) ; fIncludes . setEnabled ( ! fUseDefaults ) ; fIncludes . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fIncludeStr = fIncludes . getText ( ) ; } } ) ; g = new Group ( pattern_group , SWT . NONE ) ; g . setText ( "" ) ; g . setLayout ( new GridLayout ( , true ) ) ; g . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fExcludes = new Text ( g , SWT . NONE ) ; fExcludes . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; if ( fExcludeStr != null ) { fExcludes . setText ( fExcludeStr ) ; } fExcludes . setEditable ( ! fUseDefaults ) ; fExcludes . setEnabled ( ! fUseDefaults ) ; fExcludes . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fExcludeStr = fExcludes . getText ( ) ; } } ) ; Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; button_bar . setLayoutData ( new GridData ( SWT . CENTER , SWT . FILL , false , true ) ) ; Button add_proj_path = new Button ( button_bar , SWT . PUSH ) ; add_proj_path . setText ( "" ) ; add_proj_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; add_proj_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { ProjectDirectoryDialog dlg = new ProjectDirectoryDialog ( getShell ( ) , fProject ) ; if ( dlg . open ( ) == Window . OK ) { if ( dlg . getPath ( ) != null ) { fPath . setText ( "" + dlg . getPath ( ) ) ; } } } } ) ; Button add_ws_path = new Button ( button_bar , SWT . PUSH ) ; add_ws_path . setText ( "" ) ; add_ws_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; add_ws_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { WorkspaceFileDialog dlg = new WorkspaceFileDialog ( getShell ( ) ) ; dlg . setSelectFiles ( false ) ; if ( dlg . open ( ) == Window . OK ) { if ( dlg . getPath ( ) != null ) { fPath . setText ( "" + dlg . getPath ( ) ) ; } } } } ) ; Button add_fs_path = new Button ( button_bar , SWT . PUSH ) ; add_fs_path . setText ( "" ) ; add_fs_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; add_fs_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { DirectoryDialog dlg = new DirectoryDialog ( getShell ( ) ) ; dlg . setText ( "" ) ; String result = dlg . open ( ) ; if ( result != null && ! result . trim ( ) . equals ( "" ) ) { fPath . setText ( result ) ; } } } ) ; return frame ; } } package net . sf . sveditor . ui . prop_pages ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibDescriptor ; import net . sf . sveditor . core . db . project . SVDBPath ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public class PluginLibPrefsPage implements ISVProjectPropsPage , IStructuredContentProvider , ILabelProvider { private CheckboxTableViewer fPluginLibViewer ; private List < SVDBPluginLibDescriptor > fPluginLibs ; private SVProjectFileWrapper fProjectWrapper ; public void init ( SVProjectFileWrapper project_wrapper ) { fProjectWrapper = project_wrapper ; } public PluginLibPrefsPage ( ) { fPluginLibs = SVCorePlugin . getDefault ( ) . getPluginLibList ( ) ; } public Control createContents ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , true ) ) ; fPluginLibViewer = CheckboxTableViewer . newCheckList ( frame , SWT . NONE ) ; fPluginLibViewer . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fPluginLibViewer . setContentProvider ( this ) ; fPluginLibViewer . setLabelProvider ( this ) ; fPluginLibViewer . setInput ( fPluginLibs ) ; for ( SVDBPluginLibDescriptor lib : fPluginLibs ) { int sel = - ; for ( int i = ; i < fProjectWrapper . getPluginPaths ( ) . size ( ) ; i ++ ) { SVDBPath p = fProjectWrapper . getPluginPaths ( ) . get ( i ) ; if ( p . getPath ( ) . equals ( lib . getId ( ) ) ) { sel = i ; break ; } } if ( ! fPluginLibViewer . setChecked ( lib , ( sel != - ) ) ) { System . out . println ( "" ) ; } } return frame ; } public Image getIcon ( ) { return SVUiPlugin . getImage ( "" ) ; } public String getName ( ) { return "" ; } public void perfomOk ( ) { fProjectWrapper . getPluginPaths ( ) . clear ( ) ; for ( int i = ; i < fPluginLibs . size ( ) ; i ++ ) { if ( fPluginLibViewer . getChecked ( fPluginLibs . get ( i ) ) ) { SVDBPath p = new SVDBPath ( fPluginLibs . get ( i ) . getId ( ) , false ) ; fProjectWrapper . getPluginPaths ( ) . add ( p ) ; } } } public Object [ ] getElements ( Object inputElement ) { return fPluginLibs . toArray ( ) ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { if ( element instanceof SVDBPluginLibDescriptor ) { return ( ( SVDBPluginLibDescriptor ) element ) . getName ( ) ; } return null ; } public void addListener ( ILabelProviderListener listener ) { } public boolean isLabelProperty ( Object element , String property ) { return false ; } public void removeListener ( ILabelProviderListener listener ) { } } package net . sf . sveditor . ui . prop_pages ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; public class ProjectFileDialog extends Dialog { private String fPathStr ; private TreeViewer fTreeViewer ; private IProject fProject ; public ProjectFileDialog ( Shell shell , IProject project ) { super ( shell ) ; fProject = project ; } public String getPath ( ) { return fPathStr ; } @ Override protected Control createDialogArea ( Composite p ) { Composite parent = new Composite ( p , SWT . NONE ) ; parent . setLayout ( new GridLayout ( , true ) ) ; fTreeViewer = new TreeViewer ( parent ) ; GridData gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . widthHint = ; gd . heightHint = ; fTreeViewer . getControl ( ) . setLayoutData ( gd ) ; fTreeViewer . setAutoExpandLevel ( ) ; fTreeViewer . setContentProvider ( new WorkbenchContentProvider ( ) ) ; fTreeViewer . addFilter ( new ViewerFilter ( ) { @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { return ( element instanceof IResource && ( ( IResource ) element ) . getProject ( ) . equals ( fProject ) ) ; } } ) ; fTreeViewer . setLabelProvider ( new WorkbenchLabelProvider ( ) ) ; fTreeViewer . setInput ( ResourcesPlugin . getWorkspace ( ) ) ; fTreeViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) fTreeViewer . getSelection ( ) ; if ( sel . getFirstElement ( ) != null ) { fPathStr = ( ( IResource ) sel . getFirstElement ( ) ) . getFullPath ( ) . toOSString ( ) ; } } } ) ; fTreeViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { buttonPressed ( IDialogConstants . OK_ID ) ; } } ) ; return fTreeViewer . getControl ( ) ; } } package net . sf . sveditor . ui . prop_pages ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . TabFolder ; import org . eclipse . swt . widgets . TabItem ; public class DeprecatedPropertiesPage implements ISVProjectPropsPage { private List < ISVProjectPropsPage > fSubPages ; private IProject fProject ; private SVProjectFileWrapper fProjectWrapper ; public DeprecatedPropertiesPage ( IProject p ) { fSubPages = new ArrayList < ISVProjectPropsPage > ( ) ; fProject = p ; } public String getName ( ) { return "" ; } public Image getIcon ( ) { return null ; } public void init ( SVProjectFileWrapper project_wrapper ) { fProjectWrapper = project_wrapper ; } public Control createContents ( Composite parent ) { fSubPages . add ( new GlobalDefinesPage ( fProject ) ) ; fSubPages . add ( new SourceCollectionsPage ( fProject ) ) ; fSubPages . add ( new LibraryPathsPage ( fProject ) ) ; TabFolder folder = new TabFolder ( parent , SWT . NONE ) ; TabItem item ; for ( ISVProjectPropsPage p : fSubPages ) { p . init ( fProjectWrapper ) ; item = new TabItem ( folder , SWT . NONE ) ; item . setText ( p . getName ( ) ) ; if ( p . getIcon ( ) != null ) { item . setImage ( p . getIcon ( ) ) ; } item . setControl ( p . createContents ( folder ) ) ; } Dialog . applyDialogFont ( folder ) ; return folder ; } public void perfomOk ( ) { for ( ISVProjectPropsPage p : fSubPages ) { p . perfomOk ( ) ; } } } package net . sf . sveditor . ui . prop_pages ; import net . sf . sveditor . ui . WorkspaceDirectoryDialog ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class AddDirectoryPathDialog extends Dialog { private Text fPath ; private String fPathStr ; private IProject fProject ; public AddDirectoryPathDialog ( Shell shell , IProject project ) { super ( shell ) ; fProject = project ; } public void setInitialPath ( String path ) { fPathStr = path ; } public String getPath ( ) { return fPathStr ; } @ Override protected Control createDialogArea ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; GridData gd ; fPath = new Text ( frame , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . widthHint = ; fPath . setLayoutData ( gd ) ; fPath . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fPathStr = fPath . getText ( ) ; } } ) ; if ( fPathStr != null ) { fPath . setText ( fPathStr ) ; } Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; button_bar . setLayoutData ( new GridData ( SWT . CENTER , SWT . FILL , false , true ) ) ; Button add_proj_path = new Button ( button_bar , SWT . PUSH ) ; add_proj_path . setText ( "" ) ; add_proj_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; add_proj_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { ProjectDirectoryDialog dlg = new ProjectDirectoryDialog ( getShell ( ) , fProject ) ; if ( dlg . open ( ) == Window . OK ) { if ( dlg . getPath ( ) != null ) { fPath . setText ( "" + dlg . getPath ( ) ) ; } } } } ) ; Button add_ws_path = new Button ( button_bar , SWT . PUSH ) ; add_ws_path . setText ( "" ) ; add_ws_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; add_ws_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { WorkspaceDirectoryDialog dlg = new WorkspaceDirectoryDialog ( getShell ( ) ) ; if ( dlg . open ( ) == Window . OK ) { if ( dlg . getPath ( ) != null ) { fPath . setText ( "" + dlg . getPath ( ) ) ; } } } } ) ; Button add_fs_path = new Button ( button_bar , SWT . PUSH ) ; add_fs_path . setText ( "" ) ; add_fs_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; add_fs_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { DirectoryDialog dlg = new DirectoryDialog ( getShell ( ) ) ; dlg . setText ( "" ) ; String result = dlg . open ( ) ; if ( result != null && ! result . trim ( ) . equals ( "" ) ) { fPath . setText ( result ) ; } } } ) ; return frame ; } } package net . sf . sveditor . ui . prop_pages ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . TabFolder ; import org . eclipse . swt . widgets . TabItem ; import org . eclipse . ui . IWorkbenchPropertyPage ; import org . eclipse . ui . dialogs . PropertyPage ; public class SVProjectProps extends PropertyPage implements IWorkbenchPropertyPage { private List < ISVProjectPropsPage > fPropertyPages ; private SVDBProjectData fProjectData ; private SVProjectFileWrapper fProjectFileWrapper ; public SVProjectProps ( ) { fPropertyPages = new ArrayList < ISVProjectPropsPage > ( ) ; noDefaultAndApplyButton ( ) ; } @ Override protected Control createContents ( Composite parent ) { IProject p = getProject ( ) ; SVDBProjectManager mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; fProjectData = mgr . getProjectData ( p ) ; fProjectFileWrapper = fProjectData . getProjectFileWrapper ( ) . duplicate ( ) ; fPropertyPages . add ( new GlobalDefinesPage ( p ) ) ; fPropertyPages . add ( new SourceCollectionsPage ( p ) ) ; fPropertyPages . add ( new LibraryPathsPage ( p ) ) ; fPropertyPages . add ( new ArgumentFilePathsPage ( p ) ) ; fPropertyPages . add ( new PluginLibPrefsPage ( ) ) ; TabFolder folder = new TabFolder ( parent , SWT . NONE ) ; TabItem item ; for ( ISVProjectPropsPage page : fPropertyPages ) { page . init ( fProjectFileWrapper ) ; item = new TabItem ( folder , SWT . NONE ) ; item . setText ( page . getName ( ) ) ; if ( page . getIcon ( ) != null ) { item . setImage ( page . getIcon ( ) ) ; } item . setControl ( page . createContents ( folder ) ) ; } Dialog . applyDialogFont ( folder ) ; return folder ; } @ Override public boolean performOk ( ) { for ( ISVProjectPropsPage page : fPropertyPages ) { page . perfomOk ( ) ; } fProjectData . setProjectFileWrapper ( fProjectFileWrapper ) ; fProjectData . getProjectIndexMgr ( ) . rebuildIndex ( new NullProgressMonitor ( ) ) ; return true ; } private IProject getProject ( ) { IAdaptable adaptable = getElement ( ) ; if ( adaptable != null ) { IProject proj = ( IProject ) adaptable . getAdapter ( IProject . class ) ; return proj ; } return null ; } } package net . sf . sveditor . ui . prop_pages ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; public class ProjectDirectoryDialog extends Dialog { private String fPathStr ; private TreeViewer fTreeViewer ; private IProject fProject ; public ProjectDirectoryDialog ( Shell shell , IProject project ) { super ( shell ) ; fProject = project ; } public String getPath ( ) { return fPathStr ; } @ Override protected Control createDialogArea ( Composite p ) { Composite parent = new Composite ( p , SWT . NONE ) ; parent . setLayout ( new GridLayout ( , true ) ) ; fTreeViewer = new TreeViewer ( parent ) ; GridData gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . widthHint = ; gd . heightHint = ; fTreeViewer . getControl ( ) . setLayoutData ( gd ) ; fTreeViewer . setAutoExpandLevel ( ) ; fTreeViewer . setContentProvider ( new WorkbenchContentProvider ( ) ) ; fTreeViewer . addFilter ( new ViewerFilter ( ) { @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { return ( element instanceof IContainer && ( ( IResource ) element ) . getProject ( ) . equals ( fProject ) ) ; } } ) ; fTreeViewer . setLabelProvider ( new WorkbenchLabelProvider ( ) ) ; fTreeViewer . setInput ( ResourcesPlugin . getWorkspace ( ) ) ; fTreeViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) fTreeViewer . getSelection ( ) ; if ( sel . getFirstElement ( ) != null ) { fPathStr = ( ( IContainer ) sel . getFirstElement ( ) ) . getFullPath ( ) . toOSString ( ) ; } } } ) ; fTreeViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { buttonPressed ( IDialogConstants . OK_ID ) ; } } ) ; return fTreeViewer . getControl ( ) ; } } package net . sf . sveditor . ui . prop_pages ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . project . SVDBPath ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ListViewer ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public class LibraryPathsPage implements ISVProjectPropsPage , IStructuredContentProvider , ILabelProvider { private ListViewer fLibraryPathViewer ; private SVProjectFileWrapper fProjectWrapper ; private List < SVDBPath > fLibraryPaths ; private Button fAdd ; private Button fRemove ; private Button fEdit ; private IProject fProject ; public LibraryPathsPage ( IProject p ) { fLibraryPaths = new ArrayList < SVDBPath > ( ) ; fProject = p ; } public void init ( SVProjectFileWrapper project_wrapper ) { fProjectWrapper = project_wrapper ; fLibraryPaths . clear ( ) ; for ( SVDBPath p : fProjectWrapper . getLibraryPaths ( ) ) { fLibraryPaths . add ( p . duplicate ( ) ) ; } } public Control createContents ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; fLibraryPathViewer = new ListViewer ( frame , SWT . BORDER ) ; fLibraryPathViewer . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fLibraryPathViewer . setContentProvider ( this ) ; fLibraryPathViewer . setLabelProvider ( this ) ; fLibraryPathViewer . setInput ( fLibraryPaths ) ; fLibraryPathViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { updateSelection ( ) ; } } ) ; Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , true ) ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; fAdd = new Button ( button_bar , SWT . PUSH ) ; fAdd . setText ( "" ) ; fAdd . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fAdd . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { add ( ) ; } } ) ; fEdit = new Button ( button_bar , SWT . PUSH ) ; fEdit . setText ( "" ) ; fEdit . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fEdit . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { edit ( ) ; } } ) ; fRemove = new Button ( button_bar , SWT . PUSH ) ; fRemove . setText ( "" ) ; fRemove . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fRemove . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { remove ( ) ; } } ) ; updateSelection ( ) ; return frame ; } public Image getIcon ( ) { return SVUiPlugin . getImage ( "" ) ; } public String getName ( ) { return "" ; } public void perfomOk ( ) { fProjectWrapper . getLibraryPaths ( ) . clear ( ) ; for ( SVDBPath p : fLibraryPaths ) { fProjectWrapper . getLibraryPaths ( ) . add ( p . duplicate ( ) ) ; } } public Object [ ] getElements ( Object inputElement ) { return fLibraryPaths . toArray ( ) ; } public boolean isLabelProperty ( Object element , String property ) { return false ; } public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { if ( element instanceof SVDBPath ) { return ( ( SVDBPath ) element ) . getPath ( ) ; } return null ; } private void add ( ) { AddFilePathDialog dlg = new AddFilePathDialog ( fAdd . getShell ( ) , fProject ) ; if ( dlg . open ( ) == Window . OK ) { SVDBPath path = new SVDBPath ( dlg . getPath ( ) , false ) ; fLibraryPaths . add ( path ) ; fLibraryPathViewer . refresh ( ) ; } } private void edit ( ) { IStructuredSelection sel = ( IStructuredSelection ) fLibraryPathViewer . getSelection ( ) ; SVDBPath elem = ( SVDBPath ) sel . getFirstElement ( ) ; AddFilePathDialog dlg = new AddFilePathDialog ( fAdd . getShell ( ) , fProject ) ; dlg . setInitialPath ( elem . getPath ( ) ) ; if ( dlg . open ( ) == Window . OK ) { elem . setPath ( dlg . getPath ( ) ) ; fLibraryPathViewer . refresh ( ) ; } } private void remove ( ) { IStructuredSelection sel = ( IStructuredSelection ) fLibraryPathViewer . getSelection ( ) ; for ( Object sel_o : sel . toList ( ) ) { fLibraryPaths . remove ( sel_o ) ; } fLibraryPathViewer . refresh ( ) ; } private void updateSelection ( ) { IStructuredSelection sel = ( IStructuredSelection ) fLibraryPathViewer . getSelection ( ) ; fAdd . setEnabled ( true ) ; if ( sel . getFirstElement ( ) == null ) { fRemove . setEnabled ( false ) ; fEdit . setEnabled ( false ) ; } else { if ( sel . size ( ) == ) { fEdit . setEnabled ( true ) ; } else { fEdit . setEnabled ( false ) ; } fRemove . setEnabled ( true ) ; } } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void addListener ( ILabelProviderListener listener ) { } public void removeListener ( ILabelProviderListener listener ) { } } package net . sf . sveditor . ui . prop_pages ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . TableViewerColumn ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public class GlobalDefinesPage implements ISVProjectPropsPage , IStructuredContentProvider , ITableLabelProvider { private TableViewer fGlobalDefines ; private SVProjectFileWrapper fProjectWrapper ; private List < Tuple < String , String > > fDefineList ; private Button fAdd ; private Button fRemove ; private Button fEdit ; public GlobalDefinesPage ( IProject p ) { fDefineList = new ArrayList < Tuple < String , String > > ( ) ; } public void init ( SVProjectFileWrapper project_wrapper ) { fProjectWrapper = project_wrapper ; fDefineList . clear ( ) ; for ( Tuple < String , String > p : fProjectWrapper . getGlobalDefines ( ) ) { Tuple < String , String > dup = new Tuple < String , String > ( p . first ( ) , p . second ( ) ) ; fDefineList . add ( dup ) ; } } public Control createContents ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; fGlobalDefines = new TableViewer ( frame , SWT . MULTI + SWT . BORDER ) ; fGlobalDefines . getTable ( ) . setHeaderVisible ( true ) ; fGlobalDefines . getTable ( ) . setLinesVisible ( true ) ; TableViewerColumn tc = new TableViewerColumn ( fGlobalDefines , SWT . NONE ) ; tc . getColumn ( ) . setText ( "" ) ; tc . getColumn ( ) . setWidth ( ) ; tc = new TableViewerColumn ( fGlobalDefines , SWT . NONE ) ; tc . getColumn ( ) . setText ( "" ) ; tc . getColumn ( ) . setWidth ( ) ; fGlobalDefines . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fGlobalDefines . setContentProvider ( this ) ; fGlobalDefines . setLabelProvider ( this ) ; fGlobalDefines . setInput ( fDefineList ) ; fGlobalDefines . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { updateSelection ( ) ; } } ) ; Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , true ) ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; fAdd = new Button ( button_bar , SWT . PUSH ) ; fAdd . setText ( "" ) ; fAdd . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fAdd . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { add ( ) ; } } ) ; fEdit = new Button ( button_bar , SWT . PUSH ) ; fEdit . setText ( "" ) ; fEdit . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fEdit . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { edit ( ) ; } } ) ; fRemove = new Button ( button_bar , SWT . PUSH ) ; fRemove . setText ( "" ) ; fRemove . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fRemove . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { remove ( ) ; } } ) ; updateSelection ( ) ; return frame ; } public Image getIcon ( ) { return SVUiPlugin . getImage ( "" ) ; } public String getName ( ) { return "" ; } public void perfomOk ( ) { fProjectWrapper . getGlobalDefines ( ) . clear ( ) ; for ( Tuple < String , String > p : fDefineList ) { Tuple < String , String > dup = new Tuple < String , String > ( p . first ( ) , p . second ( ) ) ; fProjectWrapper . getGlobalDefines ( ) . add ( dup ) ; } } public Object [ ] getElements ( Object inputElement ) { return fDefineList . toArray ( ) ; } public boolean isLabelProperty ( Object element , String property ) { return false ; } public Image getColumnImage ( Object element , int columnIndex ) { return null ; } @ SuppressWarnings ( "" ) public String getColumnText ( Object element , int columnIndex ) { Tuple < String , String > def = ( Tuple < String , String > ) element ; return ( columnIndex == ) ? def . first ( ) : def . second ( ) ; } private void add ( ) { AddDefineDialog dlg = new AddDefineDialog ( fAdd . getShell ( ) ) ; if ( dlg . open ( ) == Window . OK ) { Tuple < String , String > path = new Tuple < String , String > ( dlg . getName ( ) , dlg . getValue ( ) ) ; fDefineList . add ( path ) ; fGlobalDefines . refresh ( ) ; } } @ SuppressWarnings ( "" ) private void edit ( ) { IStructuredSelection sel = ( IStructuredSelection ) fGlobalDefines . getSelection ( ) ; Tuple < String , String > elem = ( Tuple < String , String > ) sel . getFirstElement ( ) ; AddDefineDialog dlg = new AddDefineDialog ( fAdd . getShell ( ) ) ; dlg . setInitialName ( elem . first ( ) ) ; dlg . setInitialValue ( elem . second ( ) ) ; if ( dlg . open ( ) == Window . OK ) { elem . setFirst ( dlg . getName ( ) ) ; elem . setSecond ( dlg . getValue ( ) ) ; fGlobalDefines . refresh ( ) ; } } private void remove ( ) { IStructuredSelection sel = ( IStructuredSelection ) fGlobalDefines . getSelection ( ) ; for ( Object sel_o : sel . toList ( ) ) { fDefineList . remove ( sel_o ) ; } fGlobalDefines . refresh ( ) ; } private void updateSelection ( ) { IStructuredSelection sel = ( IStructuredSelection ) fGlobalDefines . getSelection ( ) ; fAdd . setEnabled ( true ) ; if ( sel . getFirstElement ( ) == null ) { fRemove . setEnabled ( false ) ; fEdit . setEnabled ( false ) ; } else { if ( sel . size ( ) == ) { fEdit . setEnabled ( true ) ; } else { fEdit . setEnabled ( false ) ; } fRemove . setEnabled ( true ) ; } } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void addListener ( ILabelProviderListener listener ) { } public void removeListener ( ILabelProviderListener listener ) { } } package net . sf . sveditor . ui . prop_pages ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . TextViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . IWorkbenchPropertyPage ; import org . eclipse . ui . dialogs . PropertyPage ; public class SVFilePropertyPage extends PropertyPage implements IWorkbenchPropertyPage { public SVFilePropertyPage ( ) { } @ Override protected Control createContents ( Composite parent ) { StringBuilder index_info = new StringBuilder ( ) ; IAdaptable adaptable = getElement ( ) ; IFile file ; Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new GridLayout ( ) ) ; file = ( IFile ) adaptable . getAdapter ( IFile . class ) ; Label l = new Label ( c , SWT . NONE ) ; l . setText ( "" + file . getFullPath ( ) . toOSString ( ) ) ; Group index_details_g = new Group ( c , SWT . SHADOW_ETCHED_IN ) ; index_details_g . setText ( "" ) ; index_details_g . setLayout ( new GridLayout ( ) ) ; index_details_g . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; TextViewer index_details = new TextViewer ( index_details_g , SWT . READ_ONLY ) ; index_details . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; String file_path = "" + file . getFullPath ( ) . toOSString ( ) ; SVDBProjectManager mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; boolean found = false ; for ( IProject project : root . getProjects ( ) ) { SVDBProjectData proj_data = mgr . getProjectData ( project ) ; SVDBIndexCollection index_mgr = proj_data . getProjectIndexMgr ( ) ; List < SVDBSearchResult < SVDBFile > > result = index_mgr . findPreProcFile ( file_path , true ) ; if ( result . size ( ) > ) { ISVDBIndex index = result . get ( ) . getIndex ( ) ; index_info . append ( "" + file_path + "" + index . getBaseLocation ( ) + "" ) ; index_info . append ( "" + index . getClass ( ) . getName ( ) + "" ) ; found = true ; } } if ( ! found ) { index_info . append ( "" + file_path + "" ) ; } Document doc = new Document ( index_info . toString ( ) ) ; index_details . setDocument ( doc ) ; Dialog . applyDialogFont ( c ) ; return c ; } } package net . sf . sveditor . ui . prop_pages ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . project . SVDBPath ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ListViewer ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public class IncludePathsPage implements ISVProjectPropsPage , IStructuredContentProvider , ILabelProvider { private ListViewer fIncludePathViewer ; private SVProjectFileWrapper fProjectWrapper ; private List < SVDBPath > fIncludePaths ; private Button fAdd ; private Button fRemove ; private Button fEdit ; private IProject fProject ; public IncludePathsPage ( IProject p ) { fIncludePaths = new ArrayList < SVDBPath > ( ) ; fProject = p ; } public void init ( SVProjectFileWrapper project_wrapper ) { fProjectWrapper = project_wrapper ; fIncludePaths . clear ( ) ; for ( SVDBPath p : fProjectWrapper . getIncludePaths ( ) ) { fIncludePaths . add ( p . duplicate ( ) ) ; } } public Control createContents ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; fIncludePathViewer = new ListViewer ( frame , SWT . BORDER ) ; fIncludePathViewer . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fIncludePathViewer . setContentProvider ( this ) ; fIncludePathViewer . setLabelProvider ( this ) ; fIncludePathViewer . setInput ( fIncludePaths ) ; fIncludePathViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { updateSelection ( ) ; } } ) ; Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , true ) ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; fAdd = new Button ( button_bar , SWT . PUSH ) ; fAdd . setText ( "" ) ; fAdd . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fAdd . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { add ( ) ; } } ) ; fEdit = new Button ( button_bar , SWT . PUSH ) ; fEdit . setText ( "" ) ; fEdit . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fEdit . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { edit ( ) ; } } ) ; fRemove = new Button ( button_bar , SWT . PUSH ) ; fRemove . setText ( "" ) ; fRemove . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fRemove . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { remove ( ) ; } } ) ; updateSelection ( ) ; return frame ; } private void add ( ) { AddDirectoryPathDialog dlg = new AddDirectoryPathDialog ( fAdd . getShell ( ) , fProject ) ; if ( dlg . open ( ) == Window . OK ) { SVDBPath path = new SVDBPath ( dlg . getPath ( ) , false ) ; fIncludePaths . add ( path ) ; fIncludePathViewer . refresh ( ) ; } } private void edit ( ) { IStructuredSelection sel = ( IStructuredSelection ) fIncludePathViewer . getSelection ( ) ; SVDBPath elem = ( SVDBPath ) sel . getFirstElement ( ) ; AddDirectoryPathDialog dlg = new AddDirectoryPathDialog ( fAdd . getShell ( ) , fProject ) ; dlg . setInitialPath ( elem . getPath ( ) ) ; if ( dlg . open ( ) == Window . OK ) { elem . setPath ( dlg . getPath ( ) ) ; fIncludePathViewer . refresh ( ) ; } } private void remove ( ) { IStructuredSelection sel = ( IStructuredSelection ) fIncludePathViewer . getSelection ( ) ; for ( Object sel_o : sel . toList ( ) ) { fIncludePaths . remove ( sel_o ) ; } fIncludePathViewer . refresh ( ) ; } private void updateSelection ( ) { IStructuredSelection sel = ( IStructuredSelection ) fIncludePathViewer . getSelection ( ) ; fAdd . setEnabled ( true ) ; if ( sel . getFirstElement ( ) == null ) { fRemove . setEnabled ( false ) ; fEdit . setEnabled ( false ) ; } else { if ( sel . size ( ) == ) { fEdit . setEnabled ( true ) ; } else { fEdit . setEnabled ( false ) ; } fRemove . setEnabled ( true ) ; } } public Image getIcon ( ) { return SVUiPlugin . getImage ( "" ) ; } public String getName ( ) { return "" ; } public void perfomOk ( ) { fProjectWrapper . getIncludePaths ( ) . clear ( ) ; for ( SVDBPath p : fIncludePaths ) { fProjectWrapper . getIncludePaths ( ) . add ( p . duplicate ( ) ) ; } } public Object [ ] getElements ( Object inputElement ) { return fIncludePaths . toArray ( ) ; } public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { if ( element instanceof SVDBPath ) { return ( ( SVDBPath ) element ) . getPath ( ) ; } return null ; } public boolean isLabelProperty ( Object element , String property ) { return false ; } public void removeListener ( ILabelProviderListener listener ) { } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void addListener ( ILabelProviderListener listener ) { } } package net . sf . sveditor . ui . prop_pages ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . project . SVDBPath ; import net . sf . sveditor . core . db . project . SVProjectFileWrapper ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ListViewer ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public class ArgumentFilePathsPage implements ISVProjectPropsPage , IStructuredContentProvider , ILabelProvider { private ListViewer fArgFilePathViewer ; private SVProjectFileWrapper fProjectWrapper ; private List < SVDBPath > fArgFilePaths ; private Button fAdd ; private Button fRemove ; private Button fEdit ; private IProject fProject ; public ArgumentFilePathsPage ( IProject p ) { fArgFilePaths = new ArrayList < SVDBPath > ( ) ; fProject = p ; } public void init ( SVProjectFileWrapper project_wrapper ) { fProjectWrapper = project_wrapper ; fArgFilePaths . clear ( ) ; for ( SVDBPath p : fProjectWrapper . getArgFilePaths ( ) ) { fArgFilePaths . add ( p . duplicate ( ) ) ; } } public Control createContents ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; fArgFilePathViewer = new ListViewer ( frame , SWT . BORDER ) ; fArgFilePathViewer . getControl ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fArgFilePathViewer . setContentProvider ( this ) ; fArgFilePathViewer . setLabelProvider ( this ) ; fArgFilePathViewer . setInput ( fArgFilePaths ) ; fArgFilePathViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { updateSelection ( ) ; } } ) ; Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , true ) ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; fAdd = new Button ( button_bar , SWT . PUSH ) ; fAdd . setText ( "" ) ; fAdd . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fAdd . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { add ( ) ; } } ) ; fEdit = new Button ( button_bar , SWT . PUSH ) ; fEdit . setText ( "" ) ; fEdit . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fEdit . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { edit ( ) ; } } ) ; fRemove = new Button ( button_bar , SWT . PUSH ) ; fRemove . setText ( "" ) ; fRemove . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fRemove . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { remove ( ) ; } } ) ; updateSelection ( ) ; return frame ; } public Image getIcon ( ) { return SVUiPlugin . getImage ( "" ) ; } public String getName ( ) { return "" ; } public void perfomOk ( ) { fProjectWrapper . getArgFilePaths ( ) . clear ( ) ; for ( SVDBPath p : fArgFilePaths ) { fProjectWrapper . getArgFilePaths ( ) . add ( p . duplicate ( ) ) ; } } public Object [ ] getElements ( Object inputElement ) { return fArgFilePaths . toArray ( ) ; } public boolean isLabelProperty ( Object element , String property ) { return false ; } public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { if ( element instanceof SVDBPath ) { return ( ( SVDBPath ) element ) . getPath ( ) ; } return null ; } private void add ( ) { AddFilePathDialog dlg = new AddFilePathDialog ( fAdd . getShell ( ) , fProject ) ; if ( dlg . open ( ) == Window . OK ) { SVDBPath path = new SVDBPath ( dlg . getPath ( ) , false ) ; fArgFilePaths . add ( path ) ; fArgFilePathViewer . refresh ( ) ; } } private void edit ( ) { IStructuredSelection sel = ( IStructuredSelection ) fArgFilePathViewer . getSelection ( ) ; SVDBPath elem = ( SVDBPath ) sel . getFirstElement ( ) ; AddFilePathDialog dlg = new AddFilePathDialog ( fAdd . getShell ( ) , fProject ) ; dlg . setInitialPath ( elem . getPath ( ) ) ; if ( dlg . open ( ) == Window . OK ) { elem . setPath ( dlg . getPath ( ) ) ; fArgFilePathViewer . refresh ( ) ; } } private void remove ( ) { IStructuredSelection sel = ( IStructuredSelection ) fArgFilePathViewer . getSelection ( ) ; for ( Object sel_o : sel . toList ( ) ) { fArgFilePaths . remove ( sel_o ) ; } fArgFilePathViewer . refresh ( ) ; } private void updateSelection ( ) { IStructuredSelection sel = ( IStructuredSelection ) fArgFilePathViewer . getSelection ( ) ; fAdd . setEnabled ( true ) ; if ( sel . getFirstElement ( ) == null ) { fRemove . setEnabled ( false ) ; fEdit . setEnabled ( false ) ; } else { if ( sel . size ( ) == ) { fEdit . setEnabled ( true ) ; } else { fEdit . setEnabled ( false ) ; } fRemove . setEnabled ( true ) ; } } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void addListener ( ILabelProviderListener listener ) { } public void removeListener ( ILabelProviderListener listener ) { } } package net . sf . sveditor . ui . dialog . types ; import java . util . Comparator ; import java . util . List ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . search . SVDBAllTypeMatcher ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . FilteredItemsSelectionDialog ; public class SVOpenTypeDialog extends FilteredItemsSelectionDialog { private ISVDBIndexIterator fIndexIt ; public SVOpenTypeDialog ( ISVDBIndexIterator index_it , Shell shell ) { super ( shell , false ) ; fIndexIt = index_it ; setListLabelProvider ( new SVTreeLabelProvider ( ) ) ; setDetailsLabelProvider ( new SVTreeLabelProvider ( ) ) ; } @ Override protected Control createExtendedContentArea ( Composite parent ) { return null ; } private static final String DIALOG_SETTINGS = "" ; @ Override protected IDialogSettings getDialogSettings ( ) { IDialogSettings settings = SVUiPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( DIALOG_SETTINGS ) ; if ( settings == null ) { settings = SVUiPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( DIALOG_SETTINGS ) ; } return settings ; } @ Override protected IStatus validateItem ( Object item ) { return Status . OK_STATUS ; } @ Override protected ItemsFilter createFilter ( ) { return new ItemsFilter ( ) { @ Override public boolean matchItem ( Object item ) { if ( item instanceof SVDBDeclCacheItem ) { return matches ( ( ( SVDBDeclCacheItem ) item ) . getName ( ) ) ; } else { return matches ( item . toString ( ) ) ; } } @ Override public boolean isConsistentItem ( Object item ) { return true ; } } ; } @ Override @ SuppressWarnings ( "" ) protected Comparator getItemsComparator ( ) { return new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { if ( o1 instanceof SVDBDeclCacheItem && o2 instanceof SVDBDeclCacheItem ) { SVDBDeclCacheItem i1 = ( SVDBDeclCacheItem ) o1 ; SVDBDeclCacheItem i2 = ( SVDBDeclCacheItem ) o2 ; return i1 . getName ( ) . compareTo ( i2 . getName ( ) ) ; } else { return ; } } } ; } @ Override protected void fillContentProvider ( AbstractContentProvider content_provider , ItemsFilter filter , IProgressMonitor monitor ) throws CoreException { int count = ; ISVDBIndexIterator index_it = fIndexIt ; SubProgressMonitor find_monitor = new SubProgressMonitor ( monitor , ) ; List < SVDBDeclCacheItem > items = index_it . findGlobalScopeDecl ( find_monitor , "" , new SVDBAllTypeMatcher ( ) ) ; synchronized ( items ) { for ( SVDBDeclCacheItem i : items ) { content_provider . add ( i , filter ) ; count ++ ; } } System . out . println ( "" + count + "" ) ; monitor . done ( ) ; } @ Override public String getElementName ( Object item ) { if ( item instanceof SVDBDeclCacheItem ) { SVDBDeclCacheItem ci = ( SVDBDeclCacheItem ) item ; return ci . getName ( ) ; } else { return item . toString ( ) ; } } } package net . sf . sveditor . ui ; import java . io . File ; import java . net . URI ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . index . plugin_lib . PluginFileStore ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . filesystem . IFileSystem ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Path ; import org . eclipse . ui . IEditorDescriptor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IEditorReference ; import org . eclipse . ui . IEditorRegistry ; import org . eclipse . ui . IURIEditorInput ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . ide . FileStoreEditorInput ; import org . eclipse . ui . part . FileEditorInput ; public class SVEditorUtil { private static LogHandle fLog = LogFactory . getLogHandle ( "" ) ; public static IEditorPart openEditor ( ISVDBItemBase it ) throws PartInitException { ISVDBItemBase p = it ; String typeName = p . getType ( ) . toString ( ) ; while ( p != null && p . getType ( ) != SVDBItemType . File ) { if ( p instanceof ISVDBChildItem ) { p = ( ( ISVDBChildItem ) p ) . getParent ( ) ; } else { p = null ; break ; } } if ( p == null ) { fLog . debug ( "" + typeName + "" ) ; return null ; } String file = ( ( SVDBFile ) p ) . getFilePath ( ) ; fLog . debug ( "" + file + "" ) ; IEditorPart ed = openEditor ( file ) ; if ( ed instanceof SVEditor && it . getType ( ) != SVDBItemType . File ) { ( ( SVEditor ) ed ) . setSelection ( it , true ) ; } return ed ; } public static IEditorPart openEditor ( String file ) throws PartInitException { IFile f = null ; String name = "" ; IEditorPart ret = null ; if ( file != null ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; if ( file . startsWith ( "" ) ) { file = file . substring ( "" . length ( ) ) ; f = root . getFile ( new Path ( file ) ) ; if ( f != null ) { name = f . getFullPath ( ) . toOSString ( ) ; } } else { f = root . getFileForLocation ( new Path ( file ) ) ; if ( f != null ) { name = f . getLocation ( ) . toString ( ) ; } else { name = file ; } } IWorkbench wb = PlatformUI . getWorkbench ( ) ; IWorkbenchWindow w = wb . getActiveWorkbenchWindow ( ) ; for ( IWorkbenchPage page : w . getPages ( ) ) { for ( IEditorReference ed_r : page . getEditorReferences ( ) ) { String id = ed_r . getId ( ) ; if ( ! id . equals ( SVUiPlugin . PLUGIN_ID + "" ) ) { continue ; } IEditorInput in = null ; in = ed_r . getEditorInput ( ) ; if ( in == null ) { debug ( "" ) ; } if ( in instanceof IURIEditorInput ) { IURIEditorInput in_uri = ( IURIEditorInput ) in ; if ( in_uri . getURI ( ) == null ) { debug ( "" + ed_r . getName ( ) + "" ) ; } else { debug ( "" + in_uri . getURI ( ) . getPath ( ) ) ; if ( in_uri . getURI ( ) . getPath ( ) . equals ( name ) ) { ret = ed_r . getEditor ( true ) ; break ; } } } } if ( ret != null ) { break ; } } } if ( ret == null ) { IWorkbenchWindow w = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; IEditorRegistry rgy = PlatformUI . getWorkbench ( ) . getEditorRegistry ( ) ; String leaf_name = new File ( file ) . getName ( ) ; IEditorDescriptor desc = rgy . getDefaultEditor ( leaf_name ) ; IEditorInput ed_in = null ; debug ( "" + file ) ; if ( f != null ) { ed_in = new FileEditorInput ( f ) ; } else if ( file . startsWith ( "" ) ) { debug ( "" + file ) ; IFileSystem fs = null ; IFileStore store = null ; try { fs = EFS . getFileSystem ( "" ) ; store = fs . getStore ( new URI ( file ) ) ; } catch ( Exception e ) { fLog . error ( "" + file , e ) ; e . printStackTrace ( ) ; } try { ed_in = new PluginPathEditorInput ( ( PluginFileStore ) store ) ; } catch ( CoreException e ) { fLog . error ( "" , e ) ; e . printStackTrace ( ) ; } } else { File file_path = new File ( file ) ; IFileStore fs = EFS . getLocalFileSystem ( ) . getStore ( file_path . toURI ( ) ) ; ed_in = new FileStoreEditorInput ( fs ) ; } ret = w . getActivePage ( ) . openEditor ( ed_in , desc . getId ( ) ) ; } else { IWorkbenchWindow w = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; w . getActivePage ( ) . activate ( ret ) ; } return ret ; } private static void debug ( String msg ) { fLog . debug ( msg ) ; } } package net . sf . sveditor . ui . svt . editor ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; public class SVTContentProvider implements ITreeContentProvider { private Document fDocument ; private Element fRoot ; public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fDocument = ( Document ) newInput ; if ( fDocument != null ) { NodeList nl = fDocument . getElementsByTagName ( "" ) ; if ( nl . getLength ( ) > ) { fRoot = ( Element ) nl . item ( ) ; } else { fRoot = null ; } } } public Object [ ] getElements ( Object inputElement ) { return new Object [ ] { "" , "" } ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof String ) { NodeList nl = fDocument . getElementsByTagName ( "" ) ; List < Node > ret = new ArrayList < Node > ( ) ; String s = ( String ) parentElement ; if ( nl . getLength ( ) > ) { Element sv_template = ( Element ) nl . item ( ) ; if ( s . equals ( "" ) ) { if ( sv_template != null ) { nl = sv_template . getElementsByTagName ( "" ) ; } } else if ( s . equals ( "" ) ) { if ( sv_template != null ) { nl = sv_template . getElementsByTagName ( "" ) ; } } for ( int i = ; i < nl . getLength ( ) ; i ++ ) { ret . add ( nl . item ( i ) ) ; } } return ret . toArray ( ) ; } else { Element e = ( Element ) parentElement ; if ( e . getNodeName ( ) . equals ( "" ) ) { ArrayList < Element > ret = new ArrayList < Element > ( ) ; NodeList nl = e . getChildNodes ( ) ; for ( int i = ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n instanceof Element ) { Element el = ( Element ) n ; if ( el . getNodeName ( ) . equals ( "" ) ) { ret . add ( el ) ; } } } return ret . toArray ( ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { ArrayList < Element > ret = new ArrayList < Element > ( ) ; NodeList nl = e . getChildNodes ( ) ; for ( int i = ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n instanceof Element ) { Element el = ( Element ) n ; if ( el . getNodeName ( ) . equals ( "" ) || el . getNodeName ( ) . equals ( "" ) ) { ret . add ( el ) ; } } } return ret . toArray ( ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { ArrayList < Element > ret = new ArrayList < Element > ( ) ; NodeList nl = e . getChildNodes ( ) ; for ( int i = ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n instanceof Element ) { Element el = ( Element ) n ; if ( el . getNodeName ( ) . equals ( "" ) ) { ret . add ( el ) ; } } } return ret . toArray ( ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { ArrayList < Element > ret = new ArrayList < Element > ( ) ; NodeList nl = e . getChildNodes ( ) ; for ( int i = ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n instanceof Element ) { Element el = ( Element ) n ; if ( el . getNodeName ( ) . equals ( "" ) ) { ret . add ( el ) ; } } } return ret . toArray ( ) ; } else { return new Object [ ] ; } } } public Object getParent ( Object element ) { Object ret = null ; if ( element instanceof String ) { ret = fRoot ; } else if ( element != fRoot ) { Element e = ( Element ) element ; if ( e . getNodeName ( ) . equals ( "" ) ) { ret = "" ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { ret = "" ; } else { ret = e . getParentNode ( ) ; } } return ret ; } public boolean hasChildren ( Object element ) { return ( getChildren ( element ) . length > ) ; } } package net . sf . sveditor . ui . svt . editor ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . w3c . dom . Element ; public class SVTLabelProvider extends LabelProvider { @ Override public Image getImage ( Object element ) { return super . getImage ( element ) ; } @ Override public String getText ( Object element ) { if ( element instanceof Element ) { Element e = ( Element ) element ; if ( e . getNodeName ( ) . equals ( "" ) ) { return getAttr ( e , "" , "" ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { return "" ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { return getAttr ( e , "" , "" ) + "" + getAttr ( e , "" , "" ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { return "" ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { return getAttr ( e , "" , "" ) + "" + getAttr ( e , "" , "" ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { return getAttr ( e , "" , "" ) ; } else { return super . getText ( element ) ; } } else if ( element instanceof String ) { return ( ( String ) element ) ; } else { return super . getText ( element ) ; } } private String getAttr ( Element e , String attr , String dflt ) { String ret = e . getAttribute ( attr ) ; if ( ret == null ) { ret = dflt ; } return ret ; } } package net . sf . sveditor . ui . svt . editor ; import java . io . File ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; public class FileBrowseDialog extends Dialog { private TreeViewer fTreeViewer ; private IContainer fContainer ; private File fContainerFile ; private String fSelectedFile ; public FileBrowseDialog ( Shell shell , IContainer container ) { super ( shell ) ; fContainer = container ; fContainerFile = null ; } public FileBrowseDialog ( Shell shell , File container ) { super ( shell ) ; fContainer = null ; fContainerFile = container ; } public String getSelectedFile ( ) { return fSelectedFile ; } @ Override protected Control createDialogArea ( Composite p ) { Composite parent = new Composite ( p , SWT . NONE ) ; parent . setLayout ( new GridLayout ( , true ) ) ; fTreeViewer = new TreeViewer ( parent ) ; GridData gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . widthHint = ; gd . heightHint = ; fTreeViewer . getControl ( ) . setLayoutData ( gd ) ; fTreeViewer . setAutoExpandLevel ( ) ; if ( fContainer != null ) { fTreeViewer . setContentProvider ( new WorkbenchContentProvider ( ) ) ; fTreeViewer . addFilter ( new ViewerFilter ( ) { @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { boolean ret = true ; return ret ; } } ) ; fTreeViewer . setLabelProvider ( WSLabelProvider ) ; fTreeViewer . setInput ( ResourcesPlugin . getWorkspace ( ) ) ; fTreeViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) fTreeViewer . getSelection ( ) ; if ( sel . getFirstElement ( ) != null ) { IResource r = ( IResource ) sel . getFirstElement ( ) ; StringBuilder sb = new StringBuilder ( ) ; while ( r != null && ! fContainer . equals ( r ) ) { if ( sb . length ( ) > ) { sb . insert ( , r . getName ( ) + "" ) ; } else { sb . insert ( , r . getName ( ) ) ; } r = r . getParent ( ) ; } fSelectedFile = sb . toString ( ) ; } } } ) ; } else { fTreeViewer . setContentProvider ( FSContentProvider ) ; fTreeViewer . setLabelProvider ( FSLabelProvider ) ; fTreeViewer . setInput ( new Object ( ) ) ; fTreeViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) fTreeViewer . getSelection ( ) ; if ( sel . getFirstElement ( ) != null ) { File r = ( File ) sel . getFirstElement ( ) ; StringBuilder sb = new StringBuilder ( ) ; while ( r != null && ! fContainerFile . equals ( r ) ) { if ( sb . length ( ) > ) { sb . insert ( , r . getName ( ) + "" ) ; } else { sb . insert ( , r . getName ( ) ) ; } r = r . getParentFile ( ) ; } fSelectedFile = sb . toString ( ) ; } } } ) ; } if ( fContainer != null ) { fTreeViewer . setSelection ( new StructuredSelection ( fContainer ) , true ) ; } return fTreeViewer . getControl ( ) ; } private ITreeContentProvider FSContentProvider = new ITreeContentProvider ( ) { public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void dispose ( ) { } public boolean hasChildren ( Object element ) { File f = ( File ) element ; return ( f . listFiles ( ) != null && f . listFiles ( ) . length > ) ; } public Object getParent ( Object element ) { return ( ( File ) element ) . getParentFile ( ) ; } public Object [ ] getElements ( Object inputElement ) { return new Object [ ] { fContainerFile } ; } public Object [ ] getChildren ( Object parentElement ) { File files [ ] = ( ( File ) parentElement ) . listFiles ( ) ; if ( files == null ) { return new Object [ ] ; } else { return files ; } } } ; private WorkbenchLabelProvider WSLabelProvider = new WorkbenchLabelProvider ( ) ; private static final Image IMG_FOLDER = PlatformUI . getWorkbench ( ) . getSharedImages ( ) . getImage ( ISharedImages . IMG_OBJ_FOLDER ) ; private static final Image IMG_FILE = PlatformUI . getWorkbench ( ) . getSharedImages ( ) . getImage ( ISharedImages . IMG_OBJ_FILE ) ; private LabelProvider FSLabelProvider = new LabelProvider ( ) { @ Override public Image getImage ( Object element ) { File f = ( File ) element ; if ( f . isDirectory ( ) ) { return IMG_FOLDER ; } else { return IMG_FILE ; } } @ Override public String getText ( Object element ) { File f = ( File ) element ; return f . getName ( ) ; } } ; } package net . sf . sveditor . ui . svt . editor ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Properties ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . sax . SAXTransformerFactory ; import javax . xml . transform . sax . TransformerHandler ; import javax . xml . transform . stream . StreamResult ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . templates . SVTUtils ; import net . sf . sveditor . ui . EditorInputUtils ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorSite ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . forms . editor . FormEditor ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . xml . sax . ErrorHandler ; import org . xml . sax . SAXException ; import org . xml . sax . SAXParseException ; public class SVTEditor extends FormEditor { private TemplatePage fTemplatePage ; private TextEditorPage fTextEditorPage ; private LogHandle fLog ; private Document fDocument ; private Element fRootElement ; private boolean fIsDirty ; public SVTEditor ( ) { fLog = LogFactory . getLogHandle ( "" ) ; } @ Override public void init ( IEditorSite site , IEditorInput input ) throws PartInitException { DocumentBuilder b = null ; try { DocumentBuilderFactory f = DocumentBuilderFactory . newInstance ( ) ; b = f . newDocumentBuilder ( ) ; b . setErrorHandler ( fErrorHandler ) ; InputStream in = EditorInputUtils . openInputStream ( input ) ; fDocument = b . parse ( in ) ; in . close ( ) ; } catch ( ParserConfigurationException e ) { } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( SAXException e ) { e . printStackTrace ( ) ; } if ( fDocument == null ) { fDocument = b . newDocument ( ) ; fRootElement = fDocument . createElement ( "" ) ; fDocument . appendChild ( fRootElement ) ; } else if ( fDocument . getElementsByTagName ( "" ) . getLength ( ) == ) { fRootElement = fDocument . createElement ( "" ) ; fDocument . appendChild ( fRootElement ) ; } else { fRootElement = ( Element ) fDocument . getElementsByTagName ( "" ) . item ( ) ; } super . init ( site , input ) ; if ( SVTUtils . ensureExpectedSections ( fDocument , fRootElement ) ) { fIsDirty = true ; editorDirtyStateChanged ( ) ; } setPartName ( input . getName ( ) ) ; } @ Override public boolean isDirty ( ) { return ( super . isDirty ( ) || fIsDirty ) ; } @ Override protected void commitPages ( boolean onSave ) { super . commitPages ( onSave ) ; } @ Override protected void pageChange ( int newPageIndex ) { super . pageChange ( newPageIndex ) ; } @ Override protected void addPages ( ) { fTemplatePage = new TemplatePage ( this ) ; try { addPage ( fTemplatePage ) ; } catch ( PartInitException e ) { fLog . error ( "" , e ) ; } fTemplatePage . setRoot ( fDocument , fRootElement ) ; } @ Override public void doSave ( IProgressMonitor monitor ) { SAXTransformerFactory tf = ( SAXTransformerFactory ) SAXTransformerFactory . newInstance ( ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; if ( getActivePage ( ) == ) { fTemplatePage . doSave ( monitor ) ; } else if ( getActivePage ( ) == ) { fTextEditorPage . doSave ( monitor ) ; } try { DOMSource ds = new DOMSource ( fDocument ) ; StreamResult sr = new StreamResult ( out ) ; tf . setAttribute ( "" , new Integer ( ) ) ; TransformerHandler th = tf . newTransformerHandler ( ) ; Properties format = new Properties ( ) ; format . put ( OutputKeys . METHOD , "" ) ; format . put ( OutputKeys . ENCODING , "" ) ; format . put ( OutputKeys . INDENT , "" ) ; th . getTransformer ( ) . setOutputProperties ( format ) ; th . setResult ( sr ) ; th . getTransformer ( ) . transform ( ds , sr ) ; EditorInputUtils . setContents ( getEditorInput ( ) , new ByteArrayInputStream ( out . toByteArray ( ) ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } fIsDirty = false ; } @ Override public void doSaveAs ( ) { } @ Override public boolean isSaveAsAllowed ( ) { return true ; } private void dump ( ) { SAXTransformerFactory tf = ( SAXTransformerFactory ) SAXTransformerFactory . newInstance ( ) ; try { DOMSource ds = new DOMSource ( fDocument ) ; StreamResult sr = new StreamResult ( System . out ) ; tf . setAttribute ( "" , new Integer ( ) ) ; TransformerHandler th = tf . newTransformerHandler ( ) ; Properties format = new Properties ( ) ; format . put ( OutputKeys . METHOD , "" ) ; format . put ( OutputKeys . ENCODING , "" ) ; format . put ( OutputKeys . INDENT , "" ) ; th . getTransformer ( ) . setOutputProperties ( format ) ; th . setResult ( sr ) ; th . getTransformer ( ) . transform ( ds , sr ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } private ErrorHandler fErrorHandler = new ErrorHandler ( ) { public void error ( SAXParseException arg0 ) throws SAXException { throw arg0 ; } public void fatalError ( SAXParseException arg0 ) throws SAXException { throw arg0 ; } public void warning ( SAXParseException arg0 ) throws SAXException { } } ; } package net . sf . sveditor . ui . svt . editor ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocumentListener ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorSite ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . editors . text . TextEditor ; import org . eclipse . ui . forms . IManagedForm ; import org . eclipse . ui . forms . editor . FormEditor ; import org . eclipse . ui . forms . editor . IFormPage ; public class TextEditorPage extends TextEditor implements IFormPage { private SVTEditor fEditor ; private Control fPartControl ; private int fIndex ; private boolean fIsActive ; private boolean fIsDirty ; public TextEditorPage ( ) { setPartName ( "" ) ; } @ Override public void init ( IEditorSite site , IEditorInput input ) throws PartInitException { super . init ( site , input ) ; getDocumentProvider ( ) . getDocument ( input ) . addDocumentListener ( documentListener ) ; } @ Override public void doSave ( IProgressMonitor progressMonitor ) { System . out . println ( "" ) ; super . doSave ( progressMonitor ) ; } public void initialize ( FormEditor editor ) { fEditor = ( SVTEditor ) editor ; } public FormEditor getEditor ( ) { return fEditor ; } public IManagedForm getManagedForm ( ) { return null ; } public void setActive ( boolean active ) { fIsActive = active ; } public boolean isActive ( ) { return fIsActive ; } @ Override public boolean isDirty ( ) { return fIsDirty ; } public boolean canLeaveThePage ( ) { return true ; } public void createPartControl ( Composite parent ) { super . createPartControl ( parent ) ; Control children [ ] = parent . getChildren ( ) ; fPartControl = children [ children . length - ] ; } public Control getPartControl ( ) { return fPartControl ; } public String getId ( ) { return null ; } public int getIndex ( ) { return fIndex ; } public void setIndex ( int index ) { fIndex = index ; } public boolean isEditor ( ) { return true ; } public boolean selectReveal ( Object object ) { return false ; } private IDocumentListener documentListener = new IDocumentListener ( ) { public void documentChanged ( DocumentEvent event ) { fIsDirty = true ; getEditor ( ) . editorDirtyStateChanged ( ) ; } public void documentAboutToBeChanged ( DocumentEvent event ) { } } ; } package net . sf . sveditor . ui . svt . editor ; import java . io . File ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . ui . EditorInputUtils ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . custom . StackLayout ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . forms . IManagedForm ; import org . eclipse . ui . forms . editor . FormPage ; import org . eclipse . ui . forms . widgets . ExpandableComposite ; import org . eclipse . ui . forms . widgets . FormToolkit ; import org . eclipse . ui . forms . widgets . ScrolledForm ; import org . eclipse . ui . forms . widgets . Section ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; public class TemplatePage extends FormPage { private TreeViewer fTreeViewer ; private Document fDocument ; private Element fRoot ; private Button fAddButton ; private Button fRemoveButton ; private StackLayout fStackLayout ; private Composite fDetailsPaneParent ; private Element fActiveElement ; private Composite fNoDetailsPane ; private Composite fTemplateDetailsPane ; private Text fTemplateName ; private Text fTemplateId ; private Text fTemplateCategoryId ; private Button fTemplateCategoryBrowse ; private Text fTemplateDescription ; private Composite fParameterDetailsPane ; private Text fParameterName ; private Combo fParameterType ; private Text fParameterRestrictions ; private Text fParameterExtFromClass ; private Button fParameterExtFromClassBrowse ; private Text fParameterDefault ; private Composite fFileDetailsPane ; private Text fFileName ; private Text fTemplatePath ; private Button fFilePathBrowse ; private Composite fCategoryDetailsPane ; private Text fCategoryId ; private Text fCategoryName ; private Text fCategoryDescription ; private boolean fControlModify ; private boolean fIsDirty ; private Map < Object , String > fAttrMap ; private Map < Object , String > fElemMap ; private static List < String > fTypeNames ; static { fTypeNames = new ArrayList < String > ( ) ; fTypeNames . add ( "" ) ; fTypeNames . add ( "" ) ; fTypeNames . add ( "" ) ; fTypeNames . add ( "" ) ; } public TemplatePage ( SVTEditor editor ) { super ( editor , "" , "" ) ; fAttrMap = new HashMap < Object , String > ( ) ; fElemMap = new HashMap < Object , String > ( ) ; } @ Override protected void createFormContent ( IManagedForm managedForm ) { FormToolkit tk = managedForm . getToolkit ( ) ; ScrolledForm form = managedForm . getForm ( ) ; form . setText ( "" ) ; managedForm . dirtyStateChanged ( ) ; Composite pane = form . getBody ( ) ; pane . setLayout ( new GridLayout ( , false ) ) ; SashForm sash = new SashForm ( pane , SWT . HORIZONTAL ) ; sash . setSashWidth ( ) ; sash . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Section s = tk . createSection ( sash , ExpandableComposite . TITLE_BAR ) ; s . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; s . setText ( "" ) ; Composite left = tk . createComposite ( s , SWT . NONE ) ; left . setLayout ( new GridLayout ( , false ) ) ; left . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; s . setClient ( left ) ; fTreeViewer = new TreeViewer ( left ) ; fTreeViewer . getTree ( ) . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; fTreeViewer . setContentProvider ( new SVTContentProvider ( ) ) ; fTreeViewer . setLabelProvider ( new SVTLabelProvider ( ) ) ; fTreeViewer . setInput ( fDocument ) ; fTreeViewer . addSelectionChangedListener ( selectionChangedListener ) ; Composite bb = tk . createComposite ( left ) ; bb . setLayout ( new GridLayout ( ) ) ; bb . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , true ) ) ; fAddButton = tk . createButton ( bb , "" , SWT . PUSH ) ; fAddButton . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fAddButton . addSelectionListener ( selectionListener ) ; fRemoveButton = tk . createButton ( bb , "" , SWT . PUSH ) ; fRemoveButton . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; fRemoveButton . addSelectionListener ( selectionListener ) ; s = tk . createSection ( sash , ExpandableComposite . TITLE_BAR ) ; s . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; s . setText ( "" ) ; fDetailsPaneParent = tk . createComposite ( s , SWT . NONE ) ; fStackLayout = new StackLayout ( ) ; fDetailsPaneParent . setLayout ( fStackLayout ) ; fDetailsPaneParent . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; s . setClient ( fDetailsPaneParent ) ; fNoDetailsPane = tk . createComposite ( fDetailsPaneParent , SWT . NONE ) ; fTemplateDetailsPane = createTemplateDetailsPane ( tk , fDetailsPaneParent ) ; fParameterDetailsPane = createParameterDetailsPane ( tk , fDetailsPaneParent ) ; fFileDetailsPane = createFileDetailsPane ( tk , fDetailsPaneParent ) ; fCategoryDetailsPane = createCategoryDetailsPane ( tk , fDetailsPaneParent ) ; fTreeViewer . setSelection ( new StructuredSelection ( "" ) ) ; setDetailsPane ( fNoDetailsPane ) ; } private void setDetailsPane ( Composite p ) { fStackLayout . topControl = p ; fDetailsPaneParent . layout ( ) ; } private Composite createTemplateDetailsPane ( FormToolkit tk , Composite parent ) { GridData gd ; Composite c = tk . createComposite ( parent ) ; c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; c . setLayout ( new GridLayout ( , false ) ) ; tk . createLabel ( c , "" ) ; fTemplateName = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; fTemplateName . setLayoutData ( gd ) ; fTemplateName . addModifyListener ( modifyListener ) ; fAttrMap . put ( fTemplateName , "" ) ; tk . createLabel ( c , "" ) ; fTemplateId = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; fTemplateId . setLayoutData ( gd ) ; fTemplateId . addModifyListener ( modifyListener ) ; fAttrMap . put ( fTemplateId , "" ) ; tk . createLabel ( c , "" ) ; fTemplateCategoryId = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; fTemplateCategoryId . setLayoutData ( gd ) ; fTemplateCategoryId . addModifyListener ( modifyListener ) ; fAttrMap . put ( fTemplateCategoryId , "" ) ; Group g = new Group ( c , SWT . NONE ) ; g . setText ( "" ) ; tk . adapt ( g ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = ; g . setLayoutData ( gd ) ; g . setLayout ( new GridLayout ( ) ) ; fTemplateDescription = tk . createText ( g , "" , SWT . BORDER + SWT . MULTI + SWT . WRAP ) ; fTemplateDescription . addModifyListener ( modifyListener ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; fTemplateDescription . setLayoutData ( gd ) ; fElemMap . put ( fTemplateDescription , "" ) ; return c ; } private Composite createParameterDetailsPane ( FormToolkit tk , Composite parent ) { GridData gd ; Composite c = tk . createComposite ( parent ) ; c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; c . setLayout ( new GridLayout ( , false ) ) ; tk . createLabel ( c , "" ) ; fParameterName = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; fParameterName . setLayoutData ( gd ) ; fParameterName . addModifyListener ( modifyListener ) ; fAttrMap . put ( fParameterName , "" ) ; tk . createLabel ( c , "" ) ; fParameterType = new Combo ( c , SWT . READ_ONLY ) ; fParameterType . setItems ( fTypeNames . toArray ( new String [ fTypeNames . size ( ) ] ) ) ; tk . adapt ( fParameterType ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; fParameterType . setLayoutData ( gd ) ; fParameterType . addSelectionListener ( selectionListener ) ; tk . createLabel ( c , "" ) ; fParameterRestrictions = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; fParameterRestrictions . setLayoutData ( gd ) ; fParameterRestrictions . addModifyListener ( modifyListener ) ; fAttrMap . put ( fParameterRestrictions , "" ) ; tk . createLabel ( c , "" ) ; fParameterExtFromClass = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; fParameterExtFromClass . setLayoutData ( gd ) ; fParameterExtFromClass . addModifyListener ( modifyListener ) ; fAttrMap . put ( fParameterExtFromClass , "" ) ; tk . createLabel ( c , "" ) ; fParameterDefault = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; fParameterDefault . setLayoutData ( gd ) ; fParameterDefault . addModifyListener ( modifyListener ) ; fAttrMap . put ( fParameterDefault , "" ) ; return c ; } private Composite createFileDetailsPane ( FormToolkit tk , Composite parent ) { GridData gd ; Composite c = tk . createComposite ( parent ) ; c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; c . setLayout ( new GridLayout ( , false ) ) ; tk . createLabel ( c , "" ) ; fFileName = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . horizontalSpan = ; fFileName . setLayoutData ( gd ) ; fFileName . addModifyListener ( modifyListener ) ; fAttrMap . put ( fFileName , "" ) ; tk . createLabel ( c , "" ) ; fTemplatePath = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; fTemplatePath . setLayoutData ( gd ) ; fTemplatePath . addModifyListener ( modifyListener ) ; fAttrMap . put ( fTemplatePath , "" ) ; fFilePathBrowse = tk . createButton ( c , "" , SWT . PUSH ) ; fFilePathBrowse . addSelectionListener ( selectionListener ) ; return c ; } private Composite createCategoryDetailsPane ( FormToolkit tk , Composite parent ) { GridData gd ; Composite c = tk . createComposite ( parent ) ; c . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; c . setLayout ( new GridLayout ( , false ) ) ; tk . createLabel ( c , "" ) ; fCategoryId = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; fCategoryId . setLayoutData ( gd ) ; fCategoryId . addModifyListener ( modifyListener ) ; fAttrMap . put ( fCategoryId , "" ) ; tk . createLabel ( c , "" ) ; fCategoryName = tk . createText ( c , "" , SWT . BORDER + SWT . SINGLE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; fCategoryName . setLayoutData ( gd ) ; fCategoryName . addModifyListener ( modifyListener ) ; fAttrMap . put ( fCategoryName , "" ) ; Group g = new Group ( c , SWT . NONE ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = ; g . setLayoutData ( gd ) ; g . setLayout ( new GridLayout ( ) ) ; g . setText ( "" ) ; fCategoryDescription = tk . createText ( g , "" , SWT . BORDER + SWT . MULTI + SWT . WRAP ) ; fCategoryDescription . addModifyListener ( modifyListener ) ; fElemMap . put ( fCategoryDescription , "" ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; fCategoryDescription . setLayoutData ( gd ) ; return c ; } private void setTemplateContext ( Element template ) { fAddButton . setEnabled ( true ) ; fRemoveButton . setEnabled ( true ) ; fActiveElement = template ; fControlModify = true ; fTemplateName . setText ( getAttribute ( template , "" ) ) ; fTemplateId . setText ( getAttribute ( template , "" ) ) ; fTemplateCategoryId . setText ( getAttribute ( template , "" ) ) ; fTemplateDescription . setText ( getElementText ( template , "" ) ) ; fControlModify = false ; setDetailsPane ( fTemplateDetailsPane ) ; } private void setFileContext ( Element file ) { fAddButton . setEnabled ( true ) ; fRemoveButton . setEnabled ( true ) ; fActiveElement = file ; fControlModify = true ; fFileName . setText ( getAttribute ( fActiveElement , "" ) ) ; fTemplatePath . setText ( getAttribute ( fActiveElement , "" ) ) ; fControlModify = false ; setDetailsPane ( fFileDetailsPane ) ; } private void setParameterContext ( Element file ) { fAddButton . setEnabled ( true ) ; fRemoveButton . setEnabled ( true ) ; fActiveElement = file ; fControlModify = true ; fParameterName . setText ( getAttribute ( fActiveElement , "" ) ) ; fParameterType . select ( getTypeIndex ( getAttribute ( fActiveElement , "" ) ) ) ; fParameterDefault . setText ( getAttribute ( fActiveElement , "" ) ) ; fParameterExtFromClass . setText ( getAttribute ( fActiveElement , "" ) ) ; fParameterRestrictions . setText ( getAttribute ( fActiveElement , "" ) ) ; updateParameterFields ( ) ; fControlModify = false ; setDetailsPane ( fParameterDetailsPane ) ; } private void updateParameterFields ( ) { String type = fParameterType . getText ( ) ; fControlModify = true ; if ( type . equals ( "" ) || type . equals ( "" ) ) { fParameterExtFromClass . setText ( "" ) ; fParameterExtFromClass . setEnabled ( false ) ; fParameterRestrictions . setText ( "" ) ; fParameterRestrictions . setEnabled ( false ) ; } else if ( type . equals ( "" ) ) { fParameterExtFromClass . setText ( "" ) ; fParameterExtFromClass . setEnabled ( false ) ; fParameterRestrictions . setText ( getAttribute ( fActiveElement , "" ) ) ; fParameterRestrictions . setEnabled ( true ) ; } else if ( type . equals ( "" ) ) { fParameterExtFromClass . setText ( getAttribute ( fActiveElement , "" ) ) ; fParameterExtFromClass . setEnabled ( true ) ; fParameterRestrictions . setText ( "" ) ; fParameterRestrictions . setEnabled ( false ) ; } else { } fControlModify = false ; } private void setCategoryContext ( Element category ) { fAddButton . setEnabled ( true ) ; fRemoveButton . setEnabled ( true ) ; fActiveElement = category ; fControlModify = true ; fCategoryId . setText ( getAttribute ( fActiveElement , "" ) ) ; fCategoryName . setText ( getAttribute ( fActiveElement , "" ) ) ; fCategoryDescription . setText ( getElementText ( fActiveElement , "" ) ) ; fControlModify = false ; setDetailsPane ( fCategoryDetailsPane ) ; } public void setRoot ( Document doc , Element root ) { fRoot = root ; fDocument = doc ; if ( fTreeViewer != null && ! fTreeViewer . getTree ( ) . isDisposed ( ) ) { fTreeViewer . setInput ( fDocument ) ; } } @ Override public void doSave ( IProgressMonitor monitor ) { fIsDirty = false ; getEditor ( ) . editorDirtyStateChanged ( ) ; } @ Override public boolean isDirty ( ) { return fIsDirty ; } private Element createTemplate ( ) { Element ret = fDocument . createElement ( "" ) ; Element doc = fDocument . createElement ( "" ) ; ret . appendChild ( doc ) ; ret . setAttribute ( "" , "" ) ; ret . setAttribute ( "" , "" ) ; ret . setAttribute ( "" , "" ) ; Element parameters = fDocument . createElement ( "" ) ; ret . appendChild ( parameters ) ; Element files = fDocument . createElement ( "" ) ; ret . appendChild ( files ) ; return ret ; } private Element createCategory ( ) { Element ret = fDocument . createElement ( "" ) ; Element doc = fDocument . createElement ( "" ) ; ret . appendChild ( doc ) ; ret . setAttribute ( "" , "" ) ; ret . setAttribute ( "" , "" ) ; return ret ; } private Element createParameter ( ) { Element ret = fDocument . createElement ( "" ) ; ret . setAttribute ( "" , "" ) ; ret . setAttribute ( "" , "" ) ; ret . setAttribute ( "" , "" ) ; return ret ; } private Element createFile ( ) { Element ret = fDocument . createElement ( "" ) ; return ret ; } private void addElement ( ) { Element new_elem = null ; Element target = null ; System . out . println ( "" + fActiveElement . getNodeName ( ) ) ; if ( fActiveElement . getNodeName ( ) . equals ( "" ) || fActiveElement . getNodeName ( ) . equals ( "" ) ) { if ( fActiveElement . getNodeName ( ) . equals ( "" ) ) { target = fRoot ; } else { target = ( Element ) fActiveElement . getParentNode ( ) ; } new_elem = createTemplate ( ) ; } else if ( fActiveElement . getNodeName ( ) . equals ( "" ) || fActiveElement . getNodeName ( ) . equals ( "" ) ) { if ( fActiveElement . getNodeName ( ) . equals ( "" ) ) { target = fRoot ; } else { target = ( Element ) fActiveElement . getParentNode ( ) ; } new_elem = createCategory ( ) ; } else if ( fActiveElement . getNodeName ( ) . equals ( "" ) || fActiveElement . getNodeName ( ) . equals ( "" ) ) { if ( fActiveElement . getNodeName ( ) . equals ( "" ) ) { target = fActiveElement ; } else { target = ( Element ) fActiveElement . getParentNode ( ) ; } new_elem = createParameter ( ) ; } else if ( fActiveElement . getNodeName ( ) . equals ( "" ) || fActiveElement . getNodeName ( ) . equals ( "" ) ) { if ( fActiveElement . getNodeName ( ) . equals ( "" ) ) { target = fActiveElement ; } else { target = ( Element ) fActiveElement . getParentNode ( ) ; } new_elem = createFile ( ) ; } if ( new_elem != null ) { target . appendChild ( new_elem ) ; fActiveElement = new_elem ; fTreeViewer . refresh ( ) ; fTreeViewer . getTree ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { fTreeViewer . expandToLevel ( fActiveElement , ) ; fTreeViewer . setSelection ( new StructuredSelection ( fActiveElement ) , true ) ; } } ) ; fIsDirty = true ; getEditor ( ) . editorDirtyStateChanged ( ) ; } } private void removeElement ( ) { fActiveElement . getParentNode ( ) . removeChild ( fActiveElement ) ; fTreeViewer . refresh ( ) ; fIsDirty = true ; getEditor ( ) . editorDirtyStateChanged ( ) ; } private SelectionListener selectionListener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { if ( e . widget == fAddButton ) { addElement ( ) ; } else if ( e . widget == fRemoveButton ) { removeElement ( ) ; } else if ( e . widget == fParameterType ) { if ( ! fControlModify ) { setAttr ( fActiveElement , "" , fParameterType . getText ( ) ) ; updateParameterFields ( ) ; fIsDirty = true ; getEditor ( ) . editorDirtyStateChanged ( ) ; } } else if ( e . widget == fFilePathBrowse ) { Tuple < File , IFile > ret = EditorInputUtils . getFileLocation ( getEditorInput ( ) ) ; FileBrowseDialog dlg ; if ( ret . first ( ) != null ) { dlg = new FileBrowseDialog ( fDetailsPaneParent . getShell ( ) , ret . first ( ) . getParentFile ( ) ) ; } else { dlg = new FileBrowseDialog ( fDetailsPaneParent . getShell ( ) , ret . second ( ) . getParent ( ) ) ; } if ( dlg . open ( ) == Window . OK ) { fTemplatePath . setText ( dlg . getSelectedFile ( ) ) ; } } } } ; private ISelectionChangedListener selectionChangedListener = new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection ss = ( IStructuredSelection ) event . getSelection ( ) ; if ( ss . getFirstElement ( ) == null ) { } else if ( ss . getFirstElement ( ) instanceof String ) { String e = ( String ) ss . getFirstElement ( ) ; fAddButton . setEnabled ( true ) ; fRemoveButton . setEnabled ( false ) ; setDetailsPane ( fNoDetailsPane ) ; fActiveElement = fDocument . createElement ( e ) ; } else { Element e = ( Element ) ss . getFirstElement ( ) ; fActiveElement = e ; if ( e . getNodeName ( ) . equals ( "" ) || e . getNodeName ( ) . equals ( "" ) || e . getNodeName ( ) . equals ( "" ) ) { fAddButton . setEnabled ( true ) ; fRemoveButton . setEnabled ( false ) ; setDetailsPane ( fNoDetailsPane ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { setTemplateContext ( e ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { setFileContext ( e ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { setParameterContext ( e ) ; } else if ( e . getNodeName ( ) . equals ( "" ) ) { setCategoryContext ( e ) ; } else { } } } } ; private ModifyListener modifyListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { if ( fControlModify ) { return ; } if ( fAttrMap . containsKey ( e . widget ) ) { setAttr ( fActiveElement , fAttrMap . get ( e . widget ) , ( ( Text ) e . widget ) . getText ( ) ) ; } else if ( fElemMap . containsKey ( e . widget ) ) { setElem ( fActiveElement , fElemMap . get ( e . widget ) , ( ( Text ) e . widget ) . getText ( ) ) ; } fIsDirty = true ; getEditor ( ) . editorDirtyStateChanged ( ) ; fTreeViewer . refresh ( ) ; } } ; private void setAttr ( Element elem , String attr , String value ) { elem . setAttribute ( attr , value ) ; } private void setElem ( Element elem , String e_name , String value ) { NodeList nl = elem . getElementsByTagName ( e_name ) ; Element e ; if ( nl . getLength ( ) > ) { e = ( Element ) nl . item ( ) ; } else { e = fDocument . createElement ( e_name ) ; elem . appendChild ( e ) ; } e . setTextContent ( value ) ; } private int getTypeIndex ( String type ) { int ret = fTypeNames . indexOf ( type ) ; if ( ret == - ) { ret = ; } return ret ; } private String getAttribute ( Element elem , String attr ) { return getAttribute ( elem , attr , "" ) ; } private String getAttribute ( Element elem , String attr , String dflt ) { String ret = elem . getAttribute ( attr ) ; if ( ret == null ) { ret = dflt ; } return ret ; } private String getElementText ( Element elem , String c_elem ) { NodeList nl = elem . getElementsByTagName ( c_elem ) ; String ret = "" ; if ( nl . getLength ( ) != ) { ret = nl . item ( ) . getTextContent ( ) ; } return ret ; } } package net . sf . sveditor . ui ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; public class WorkspaceDirectoryDialog extends Dialog { private String fPathStr ; private TreeViewer fTreeViewer ; public WorkspaceDirectoryDialog ( Shell shell ) { super ( shell ) ; } public String getPath ( ) { return fPathStr ; } @ Override protected Control createDialogArea ( Composite p ) { Composite parent = new Composite ( p , SWT . NONE ) ; parent . setLayout ( new GridLayout ( , true ) ) ; fTreeViewer = new TreeViewer ( parent ) ; GridData gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . widthHint = ; gd . heightHint = ; fTreeViewer . getControl ( ) . setLayoutData ( gd ) ; fTreeViewer . setContentProvider ( new WorkbenchContentProvider ( ) ) ; fTreeViewer . addFilter ( new ViewerFilter ( ) { @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { return ( element instanceof IContainer ) ; } } ) ; fTreeViewer . setLabelProvider ( new WorkbenchLabelProvider ( ) ) ; fTreeViewer . setInput ( ResourcesPlugin . getWorkspace ( ) ) ; fTreeViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) fTreeViewer . getSelection ( ) ; if ( sel . getFirstElement ( ) != null ) { fPathStr = ( ( IContainer ) sel . getFirstElement ( ) ) . getFullPath ( ) . toOSString ( ) ; } } } ) ; return fTreeViewer . getControl ( ) ; } } package net . sf . sveditor . ui ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . db . IFieldItemAttr ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . stmt . SVDBStmt ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . graphics . Image ; public class SVDBIconUtils implements ISVIcons { private static final Map < SVDBItemType , String > fImgDescMap ; static { fImgDescMap = new HashMap < SVDBItemType , String > ( ) ; fImgDescMap . put ( SVDBItemType . File , FILE_OBJ ) ; fImgDescMap . put ( SVDBItemType . ModuleDecl , MODULE_OBJ ) ; fImgDescMap . put ( SVDBItemType . InterfaceDecl , INT_OBJ ) ; fImgDescMap . put ( SVDBItemType . ConfigDecl , CONFIG_OBJ ) ; fImgDescMap . put ( SVDBItemType . ClassDecl , CLASS_OBJ ) ; fImgDescMap . put ( SVDBItemType . MacroDef , DEFINE_OBJ ) ; fImgDescMap . put ( SVDBItemType . Include , INCLUDE_OBJ ) ; fImgDescMap . put ( SVDBItemType . PackageDecl , PACKAGE_OBJ ) ; fImgDescMap . put ( SVDBItemType . TypeInfoStruct , STRUCT_OBJ ) ; fImgDescMap . put ( SVDBItemType . Covergroup , COVERGROUP_OBJ ) ; fImgDescMap . put ( SVDBItemType . Coverpoint , COVERPOINT_OBJ ) ; fImgDescMap . put ( SVDBItemType . CoverpointCross , COVERPOINT_CROSS_OBJ ) ; fImgDescMap . put ( SVDBItemType . Sequence , SEQUENCE_OBJ ) ; fImgDescMap . put ( SVDBItemType . Property , PROPERTY_OBJ ) ; fImgDescMap . put ( SVDBItemType . Constraint , CONSTRAINT_OBJ ) ; fImgDescMap . put ( SVDBItemType . AlwaysStmt , ALWAYS_BLOCK_OBJ ) ; fImgDescMap . put ( SVDBItemType . InitialStmt , INITIAL_OBJ ) ; fImgDescMap . put ( SVDBItemType . Assign , ASSIGN_OBJ ) ; fImgDescMap . put ( SVDBItemType . GenerateBlock , GENERATE_OBJ ) ; fImgDescMap . put ( SVDBItemType . ClockingBlock , CLOCKING_OBJ ) ; fImgDescMap . put ( SVDBItemType . ImportItem , IMPORT_OBJ ) ; fImgDescMap . put ( SVDBItemType . ModIfcInst , MOD_IFC_INST_OBJ ) ; fImgDescMap . put ( SVDBItemType . ModIfcInstItem , MOD_IFC_INST_OBJ ) ; fImgDescMap . put ( SVDBItemType . VarDeclItem , FIELD_PUB_OBJ ) ; fImgDescMap . put ( SVDBItemType . Task , TASK_PUB_OBJ ) ; fImgDescMap . put ( SVDBItemType . TypedefStmt , ENUM_TYPE_OBJ ) ; } public static Image getIcon ( String key ) { return SVUiPlugin . getImage ( key ) ; } public static Image getIcon ( SVDBItemType type ) { if ( fImgDescMap . containsKey ( type ) ) { return SVUiPlugin . getImage ( fImgDescMap . get ( type ) ) ; } return null ; } public static Image getIcon ( ISVDBItemBase it ) { if ( it . getType ( ) == SVDBItemType . VarDeclItem ) { SVDBVarDeclItem decl = ( SVDBVarDeclItem ) it ; SVDBVarDeclStmt decl_p = decl . getParent ( ) ; if ( decl_p == null ) { System . out . println ( "" + decl . getName ( ) + "" + decl . getLocation ( ) . getLine ( ) + "" ) ; } int attr = decl_p . getAttr ( ) ; if ( decl_p . getParent ( ) != null && ( decl_p . getParent ( ) . getType ( ) == SVDBItemType . Task || decl_p . getParent ( ) . getType ( ) == SVDBItemType . Function ) ) { return SVUiPlugin . getImage ( LOCAL_OBJ ) ; } else { if ( ( attr & IFieldItemAttr . FieldAttr_Local ) != ) { return SVUiPlugin . getImage ( FIELD_PRIV_OBJ ) ; } else if ( ( attr & IFieldItemAttr . FieldAttr_Protected ) != ) { return SVUiPlugin . getImage ( FIELD_PROT_OBJ ) ; } else { return SVUiPlugin . getImage ( FIELD_PUB_OBJ ) ; } } } else if ( it instanceof IFieldItemAttr ) { int attr = ( ( IFieldItemAttr ) it ) . getAttr ( ) ; SVDBItemType type = it . getType ( ) ; if ( type == SVDBItemType . ModIfcInstItem ) { return SVUiPlugin . getImage ( MOD_IFC_INST_OBJ ) ; } else if ( type == SVDBItemType . Task || type == SVDBItemType . Function ) { if ( ( attr & IFieldItemAttr . FieldAttr_Local ) != ) { return SVUiPlugin . getImage ( TASK_PRIV_OBJ ) ; } else if ( ( attr & IFieldItemAttr . FieldAttr_Protected ) != ) { return SVUiPlugin . getImage ( TASK_PROT_OBJ ) ; } else { return SVUiPlugin . getImage ( TASK_PUB_OBJ ) ; } } else if ( SVDBStmt . isType ( it , SVDBItemType . ParamPortDecl ) ) { return SVUiPlugin . getImage ( LOCAL_OBJ ) ; } } else if ( it instanceof ISVDBItemBase ) { SVDBItemType type = ( ( ISVDBItemBase ) it ) . getType ( ) ; if ( fImgDescMap . containsKey ( type ) ) { return SVUiPlugin . getImage ( fImgDescMap . get ( type ) ) ; } else if ( it . getType ( ) == SVDBItemType . TypedefStmt ) { SVDBTypedefStmt td = ( SVDBTypedefStmt ) it ; if ( td . getTypeInfo ( ) . getType ( ) == SVDBItemType . TypeInfoEnum ) { return SVUiPlugin . getImage ( ENUM_TYPE_OBJ ) ; } else { return SVUiPlugin . getImage ( TYPEDEF_TYPE_OBJ ) ; } } } return null ; } public static ImageDescriptor getImageDescriptor ( SVDBItemType it ) { if ( fImgDescMap . containsKey ( it ) ) { return SVUiPlugin . getImageDescriptor ( fImgDescMap . get ( it ) ) ; } return null ; } } package net . sf . sveditor . ui . handlers ; import net . sf . sveditor . ui . wizards . DocGenWizard ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . core . commands . IHandler ; import org . eclipse . core . commands . IHandlerListener ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . handlers . HandlerUtil ; public class DocsGenerateHandler implements IHandler { public void addHandlerListener ( IHandlerListener handlerListener ) { } public void dispose ( ) { } public Object execute ( ExecutionEvent event ) throws ExecutionException { IWorkbenchWindow window = HandlerUtil . getActiveWorkbenchWindow ( event ) ; DocGenWizard wizard = new DocGenWizard ( ) ; wizard . init ( window . getWorkbench ( ) ) ; WizardDialog dialog = new WizardDialog ( window . getShell ( ) , wizard ) ; dialog . open ( ) ; return null ; } public boolean isEnabled ( ) { return true ; } public boolean isHandled ( ) { return true ; } public void removeHandlerListener ( IHandlerListener handlerListener ) { } } package net . sf . sveditor . ui . pref ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; public class SVEditorTemplatePropertiesPrefsPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public SVEditorTemplatePropertiesPrefsPage ( ) { super ( GRID ) ; setPreferenceStore ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; } public void init ( IWorkbench workbench ) { } @ Override protected void createFieldEditors ( ) { TemplatePropertiesEditor ed = new TemplatePropertiesEditor ( SVEditorPrefsConstants . P_SV_TEMPLATE_PROPERTIES , getFieldEditorParent ( ) ) ; addField ( ed ) ; } } package net . sf . sveditor . ui . pref ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . ui . texteditor . templates . TemplatePreferencePage ; public class SVTemplatePrefsPage extends TemplatePreferencePage { public SVTemplatePrefsPage ( ) { setPreferenceStore ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setTemplateStore ( SVUiPlugin . getDefault ( ) . getTemplateStore ( ) ) ; setContextTypeRegistry ( SVUiPlugin . getDefault ( ) . getContextTypeRegistry ( ) ) ; } protected boolean isShowFormatterSetting ( ) { return false ; } @ SuppressWarnings ( "" ) public boolean performOk ( ) { boolean ok = super . performOk ( ) ; SVUiPlugin . getDefault ( ) . savePluginPreferences ( ) ; return ok ; } } package net . sf . sveditor . ui . pref ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . preference . BooleanFieldEditor ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . jface . preference . IntegerFieldEditor ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Group ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; public class SVContentAssistPrefsPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public SVContentAssistPrefsPage ( ) { super ( GRID ) ; setPreferenceStore ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( "" ) ; } public void init ( IWorkbench workbench ) { } @ Override protected void createFieldEditors ( ) { GridData gd ; Group general_group = new Group ( getFieldEditorParent ( ) , SWT . NONE ) ; gd = new GridData ( GridData . FILL , GridData . CENTER , true , false ) ; gd . horizontalSpan = ; general_group . setLayout ( new GridLayout ( , false ) ) ; general_group . setLayoutData ( gd ) ; general_group . setText ( "" ) ; addField ( new IntegerFieldEditor ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TIMEOUT , "" , general_group ) ) ; addField ( new BooleanFieldEditor ( SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_USES_BROWSER , "" , general_group ) ) ; Group tf_group = new Group ( getFieldEditorParent ( ) , SWT . NONE ) ; gd = new GridData ( GridData . FILL , GridData . CENTER , true , false ) ; gd . horizontalSpan = ; tf_group . setLayout ( new GridLayout ( , false ) ) ; tf_group . setText ( "" ) ; tf_group . setLayoutData ( gd ) ; addField ( new BooleanFieldEditor ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_NAMED_PORTS_EN , "" , tf_group ) ) ; addField ( new IntegerFieldEditor ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_LINE_WRAP_LIMIT , "" , tf_group ) ) ; addField ( new IntegerFieldEditor ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_MAX_PARAMS_PER_LINE , "" , tf_group ) ) ; Group mod_ifc_group = new Group ( getFieldEditorParent ( ) , SWT . NONE ) ; gd = new GridData ( GridData . FILL , GridData . CENTER , true , false ) ; gd . horizontalSpan = ; mod_ifc_group . setLayout ( new GridLayout ( , false ) ) ; mod_ifc_group . setText ( "" ) ; mod_ifc_group . setLayoutData ( gd ) ; addField ( new BooleanFieldEditor ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_NAMED_PORTS_EN , "" , mod_ifc_group ) ) ; addField ( new IntegerFieldEditor ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_LINE_WRAP_LIMIT , "" , mod_ifc_group ) ) ; addField ( new IntegerFieldEditor ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_MAX_PORTS_PER_LINE , "" , mod_ifc_group ) ) ; } } package net . sf . sveditor . ui . pref ; import org . eclipse . jface . preference . ColorFieldEditor ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; public class ColorStyleFieldEditor extends ColorFieldEditor { protected Button [ ] checkButton ; static private String [ ] styleText = new String [ ] { "" , "" } ; static private String labelText = "" ; private String stylePreference ; private Label styleLabel ; public ColorStyleFieldEditor ( ) { super ( ) ; } public ColorStyleFieldEditor ( String name , String labelText , String stylePref , Composite parent ) { super ( name , labelText , parent ) ; this . stylePreference = stylePref ; } protected void doFillIntoGrid ( Composite parent , int numColumns ) { Control control = getLabelControl ( parent ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = numColumns - ; control . setLayoutData ( gd ) ; Button colorButton = getChangeControl ( parent ) ; colorButton . setLayoutData ( new GridData ( ) ) ; Label lb = getStyleLabel ( parent ) ; lb . setLayoutData ( new GridData ( ) ) ; for ( int i = ; i < ; i ++ ) { Button checkButton = getCheckButton ( parent , i ) ; checkButton . setLayoutData ( new GridData ( ) ) ; } } protected void adjustForNumColumns ( int numColumns ) { ( ( GridData ) styleLabel . getLayoutData ( ) ) . horizontalSpan = ; for ( int i = ; i < ; i ++ ) { ( ( GridData ) checkButton [ i ] . getLayoutData ( ) ) . horizontalSpan = ; } } protected Button getCheckButton ( Composite parent , int i ) { if ( checkButton == null ) checkButton = new Button [ ] ; if ( checkButton [ i ] != null ) return ( checkButton [ i ] ) ; else { checkButton [ i ] = new Button ( parent , SWT . CHECK ) ; if ( checkButton [ i ] != null ) checkButton [ i ] . setText ( styleText [ i ] ) ; return ( checkButton [ i ] ) ; } } protected Label getStyleLabel ( Composite parent ) { if ( styleLabel != null ) return ( styleLabel ) ; else { styleLabel = new Label ( parent , SWT . LEFT ) ; if ( styleLabel != null ) styleLabel . setText ( labelText ) ; return ( styleLabel ) ; } } protected void doLoad ( ) { super . doLoad ( ) ; if ( checkButton [ ] == null ) return ; checkButton [ ] . setSelection ( ( getPreferenceStore ( ) . getInt ( stylePreference ) == SWT . BOLD ) | ( getPreferenceStore ( ) . getInt ( stylePreference ) == ( SWT . BOLD | SWT . ITALIC ) ) ? true : false ) ; if ( checkButton [ ] == null ) return ; checkButton [ ] . setSelection ( ( getPreferenceStore ( ) . getInt ( stylePreference ) == SWT . ITALIC ) | ( getPreferenceStore ( ) . getInt ( stylePreference ) == ( SWT . BOLD | SWT . ITALIC ) ) ? true : false ) ; } protected void doLoadDefault ( ) { super . doLoadDefault ( ) ; if ( checkButton [ ] == null ) return ; checkButton [ ] . setSelection ( ( getPreferenceStore ( ) . getDefaultInt ( stylePreference ) == SWT . BOLD ) | ( getPreferenceStore ( ) . getDefaultInt ( stylePreference ) == ( SWT . BOLD | SWT . ITALIC ) ) ? true : false ) ; if ( checkButton [ ] == null ) return ; checkButton [ ] . setSelection ( ( getPreferenceStore ( ) . getDefaultInt ( stylePreference ) == SWT . ITALIC ) | ( getPreferenceStore ( ) . getDefaultInt ( stylePreference ) == ( SWT . BOLD | SWT . ITALIC ) ) ? true : false ) ; } protected void doStore ( ) { super . doStore ( ) ; getPreferenceStore ( ) . setValue ( stylePreference , ( checkButton [ ] . getSelection ( ) ? SWT . BOLD : SWT . NORMAL ) | ( checkButton [ ] . getSelection ( ) ? SWT . ITALIC : SWT . NORMAL ) ) ; } public int getNumberOfControls ( ) { return super . getNumberOfControls ( ) + ; } public void setEnabled ( boolean enabled , Composite parent ) { super . setEnabled ( enabled , parent ) ; for ( int i = ; i < ; i ++ ) checkButton [ i ] . setEnabled ( enabled ) ; } } package net . sf . sveditor . ui . pref ; import net . sf . sveditor . ui . WorkspaceDirectoryDialog ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class AddDirectoryPathDialog extends Dialog { private Text fPath ; private String fPathStr ; public AddDirectoryPathDialog ( Shell shell , int style ) { super ( shell ) ; } public void setInitialPath ( String path ) { fPathStr = path ; } public String getPath ( ) { return fPathStr ; } @ Override protected Control createDialogArea ( Composite parent ) { Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; GridData gd ; fPath = new Text ( frame , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . widthHint = ; fPath . setLayoutData ( gd ) ; fPath . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fPathStr = fPath . getText ( ) ; } } ) ; if ( fPathStr != null ) { fPath . setText ( fPathStr ) ; } Composite button_bar = new Composite ( frame , SWT . NONE ) ; button_bar . setLayout ( new GridLayout ( , true ) ) ; button_bar . setLayoutData ( new GridData ( SWT . CENTER , SWT . FILL , false , true ) ) ; Button add_ws_path = new Button ( button_bar , SWT . PUSH ) ; add_ws_path . setText ( "" ) ; add_ws_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; add_ws_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { WorkspaceDirectoryDialog dlg = new WorkspaceDirectoryDialog ( getShell ( ) ) ; if ( dlg . open ( ) == Window . OK ) { if ( dlg . getPath ( ) != null ) { fPath . setText ( "" + dlg . getPath ( ) ) ; } } } } ) ; Button add_fs_path = new Button ( button_bar , SWT . PUSH ) ; add_fs_path . setText ( "" ) ; add_fs_path . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; add_fs_path . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { DirectoryDialog dlg = new DirectoryDialog ( getShell ( ) ) ; dlg . setText ( "" ) ; String result = dlg . open ( ) ; if ( result != null && ! result . trim ( ) . equals ( "" ) ) { fPath . setText ( result ) ; } } } ) ; return frame ; } } package net . sf . sveditor . ui . pref ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . core . XMLTransformUtils ; import net . sf . sveditor . core . templates . DefaultTemplateParameterProvider ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . RGB ; public class SVEditorPrefsInitialize extends AbstractPreferenceInitializer { public void initializeDefaultPreferences ( ) { IPreferenceStore store = SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ; PreferenceConverter . setDefault ( store , SVEditorPrefsConstants . P_DEFAULT_C , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , SVEditorPrefsConstants . P_COMMENT_C , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , SVEditorPrefsConstants . P_STRING_C , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , SVEditorPrefsConstants . P_KEYWORD_C , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_BG_COLOR , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_FG_COLOR , new RGB ( , , ) ) ; store . setDefault ( SVEditorPrefsConstants . P_DEFAULT_S , SWT . NORMAL ) ; store . setDefault ( SVEditorPrefsConstants . P_COMMENT_S , SWT . NORMAL ) ; store . setDefault ( SVEditorPrefsConstants . P_STRING_S , SWT . NORMAL ) ; store . setDefault ( SVEditorPrefsConstants . P_KEYWORD_S , SWT . BOLD ) ; store . setDefault ( SVEditorPrefsConstants . P_DEBUG_LEVEL_S , "" ) ; store . setDefault ( SVEditorPrefsConstants . P_DEBUG_CONSOLE_S , false ) ; store . setDefault ( SVEditorPrefsConstants . P_AUTO_INDENT_ENABLED_S , true ) ; store . setDefault ( SVEditorPrefsConstants . P_AUTO_REBUILD_INDEX , true ) ; store . setDefault ( SVEditorPrefsConstants . P_ENABLE_SHADOW_INDEX , false ) ; store . setDefault ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TIMEOUT , ) ; store . setDefault ( SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_USES_BROWSER , false ) ; store . setDefault ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_NAMED_PORTS_EN , false ) ; store . setDefault ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_LINE_WRAP_LIMIT , ) ; store . setDefault ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_MAX_PARAMS_PER_LINE , ) ; store . setDefault ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_NAMED_PORTS_EN , true ) ; store . setDefault ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_LINE_WRAP_LIMIT , ) ; store . setDefault ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_MAX_PORTS_PER_LINE , ) ; { Map < String , String > p = new HashMap < String , String > ( ) ; p . put ( "" , DefaultTemplateParameterProvider . FILE_HEADER_DFLT ) ; p . put ( "" , DefaultTemplateParameterProvider . FILE_FOOTER_DFLT ) ; try { store . setDefault ( SVEditorPrefsConstants . P_SV_TEMPLATE_PROPERTIES , XMLTransformUtils . map2Xml ( p , "" , "" ) ) ; } catch ( Exception e ) { } } } } package net . sf . sveditor . ui . pref ; public class SVEditorPrefsConstants { private static final String EDIT_SETTINGS = "" ; private static final String OUTLINE_SETTINGS = "" ; private static final String TEMPLATE_SETTINGS = "" ; private static final String INDEX_SETTINGS = "" ; public static final String P_DEFAULT_C = EDIT_SETTINGS + "" ; public static final String P_COMMENT_C = EDIT_SETTINGS + "" ; public static final String P_KEYWORD_C = EDIT_SETTINGS + "" ; public static final String P_STRING_C = EDIT_SETTINGS + "" ; public static final String P_DEFAULT_S = EDIT_SETTINGS + "" ; public static final String P_KEYWORD_S = EDIT_SETTINGS + "" ; public static final String P_COMMENT_S = EDIT_SETTINGS + "" ; public static final String P_STRING_S = EDIT_SETTINGS + "" ; public static final String P_SV_FILE_EXTENSIONS_S = "" ; public static final String P_AUTO_INDENT_ENABLED_S = EDIT_SETTINGS + "" ; public static final String P_AUTO_REBUILD_INDEX = "" ; public static final String P_ENABLE_SHADOW_INDEX = "" ; public static final String P_DEBUG_LEVEL_S = "" ; public static final String P_DEBUG_CONSOLE_S = "" ; public static final String P_CONTENT_ASSIST_TIMEOUT = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_TF_NAMED_PORTS_EN = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_TF_LINE_WRAP_LIMIT = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_TF_MAX_PARAMS_PER_LINE = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_MODIFCINST_NAMED_PORTS_EN = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_MODIFCINST_LINE_WRAP_LIMIT = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_MODIFCINST_MAX_PORTS_PER_LINE = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_HOVER_USES_BROWSER = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_HOVER_BG_COLOR = EDIT_SETTINGS + "" ; public static final String P_CONTENT_ASSIST_HOVER_FG_COLOR = EDIT_SETTINGS + "" ; public static final String P_SV_TEMPLATE_PATHS = TEMPLATE_SETTINGS + "" ; public static final String P_SV_TEMPLATE_PROPERTIES = TEMPLATE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_ALWAYS_BLOCKS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_ASSIGN_STATEMENTS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_DEFINE_STATEMENTS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_INITIAL_BLOCKS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_INCLUDE_FILES = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_GENERATE_BLOCKS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_MODULE_INSTANCES = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_SIGNAL_DECLARATIONS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_TASK_FUNCTION_DECLARATIONS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_ENUM_TYPEDEFS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_ASSERTION_PROPERTIES = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_COVER_POINT_GROUP_CROSS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SHOW_CONSTRAINTS = OUTLINE_SETTINGS + "" ; public static final String P_OUTLINE_SORT = OUTLINE_SETTINGS + "" ; } package net . sf . sveditor . ui . pref ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . preference . BooleanFieldEditor ; import org . eclipse . jface . preference . ComboFieldEditor ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; public class SVEditorPrefsPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public SVEditorPrefsPage ( ) { super ( GRID ) ; setPreferenceStore ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( "" ) ; } public void createFieldEditors ( ) { addField ( new ColorStyleFieldEditor ( SVEditorPrefsConstants . P_DEFAULT_C , "" , SVEditorPrefsConstants . P_DEFAULT_S , getFieldEditorParent ( ) ) ) ; addField ( new ColorStyleFieldEditor ( SVEditorPrefsConstants . P_COMMENT_C , "" , SVEditorPrefsConstants . P_COMMENT_S , getFieldEditorParent ( ) ) ) ; addField ( new ColorStyleFieldEditor ( SVEditorPrefsConstants . P_STRING_C , "" , SVEditorPrefsConstants . P_STRING_S , getFieldEditorParent ( ) ) ) ; addField ( new ColorStyleFieldEditor ( SVEditorPrefsConstants . P_KEYWORD_C , "" , SVEditorPrefsConstants . P_KEYWORD_S , getFieldEditorParent ( ) ) ) ; addField ( new BooleanFieldEditor ( SVEditorPrefsConstants . P_AUTO_INDENT_ENABLED_S , "" , getFieldEditorParent ( ) ) ) ; addField ( new ComboFieldEditor ( SVEditorPrefsConstants . P_DEBUG_LEVEL_S , "" , new String [ ] [ ] { { "" , "" } , { "" , "" } , { "" , "" } , { "" , "" } } , getFieldEditorParent ( ) ) ) ; addField ( new BooleanFieldEditor ( SVEditorPrefsConstants . P_DEBUG_CONSOLE_S , "" , getFieldEditorParent ( ) ) ) ; } public void init ( IWorkbench workbench ) { } } package net . sf . sveditor . ui . pref ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . preference . BooleanFieldEditor ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . texteditor . templates . TemplatePreferencePage ; public class SVEditorIndexPrefsPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public SVEditorIndexPrefsPage ( ) { super ( GRID ) ; setPreferenceStore ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( "" ) ; } public void init ( IWorkbench workbench ) { } @ Override protected void createFieldEditors ( ) { addField ( new BooleanFieldEditor ( SVEditorPrefsConstants . P_AUTO_REBUILD_INDEX , "" , getFieldEditorParent ( ) ) ) ; addField ( new BooleanFieldEditor ( SVEditorPrefsConstants . P_ENABLE_SHADOW_INDEX , "" , getFieldEditorParent ( ) ) ) ; } } package net . sf . sveditor . ui . pref ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; public class SVEditorTemplatePathsPrefsPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public SVEditorTemplatePathsPrefsPage ( ) { super ( GRID ) ; setPreferenceStore ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; } public void init ( IWorkbench workbench ) { } @ Override protected void createFieldEditors ( ) { addField ( new TemplatePathsEditor ( SVEditorPrefsConstants . P_SV_TEMPLATE_PATHS , getFieldEditorParent ( ) ) ) ; } } package net . sf . sveditor . ui . pref ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . XMLTransformUtils ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . preference . ListEditor ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . List ; import org . eclipse . swt . widgets . Text ; public class TemplatePropertiesEditor extends ListEditor { private Text fPreview ; private Button fModify ; private List fList ; private Map < String , String > fParamValMap ; public TemplatePropertiesEditor ( String name , Composite parent ) { super ( name , "" , parent ) ; fParamValMap = new HashMap < String , String > ( ) ; } @ Override protected String createList ( String [ ] items ) { Map < String , String > content = new HashMap < String , String > ( ) ; for ( String item : items ) { content . put ( item , fParamValMap . get ( item ) ) ; } String str = "" ; try { str = XMLTransformUtils . map2Xml ( content , "" , "" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return str ; } @ Override protected String [ ] parseString ( String stringList ) { Map < String , String > content = null ; fParamValMap . clear ( ) ; if ( ! stringList . trim ( ) . equals ( "" ) ) { try { content = XMLTransformUtils . xml2Map ( new StringInputStream ( stringList ) , "" , "" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( content != null ) { Set < String > keys = content . keySet ( ) ; for ( Entry < String , String > e : content . entrySet ( ) ) { fParamValMap . put ( e . getKey ( ) , e . getValue ( ) ) ; } return keys . toArray ( new String [ keys . size ( ) ] ) ; } else { return new String [ ] ; } } @ Override protected void doLoad ( ) { super . doLoad ( ) ; if ( fList . getSelectionIndex ( ) == - && fList . getItemCount ( ) > ) { fList . select ( ) ; listSelected ( ) ; } } @ Override protected void doFillIntoGrid ( Composite parent , int numColumns ) { super . doFillIntoGrid ( parent , numColumns ) ; GridData gd ; Group g = new Group ( parent , SWT . NONE ) ; g . setText ( "" ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = numColumns - ; g . setLayoutData ( gd ) ; g . setLayout ( new GridLayout ( ) ) ; fPreview = new Text ( g , SWT . READ_ONLY + SWT . MULTI + SWT . BORDER ) ; fPreview . setFont ( JFaceResources . getTextFont ( ) ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; fPreview . setLayoutData ( gd ) ; fModify = new Button ( parent , SWT . PUSH ) ; fModify . setText ( "" ) ; fModify . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , false , false ) ) ; fModify . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { modifyPressed ( ) ; } } ) ; fList = getListControl ( parent ) ; fList . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { listSelected ( ) ; } } ) ; } private void listSelected ( ) { String val = fParamValMap . get ( fList . getItem ( fList . getSelectionIndex ( ) ) ) ; if ( val != null ) { fPreview . setText ( val ) ; fModify . setEnabled ( true ) ; } else { fPreview . setText ( "" ) ; fModify . setEnabled ( false ) ; } } private void modifyPressed ( ) { String id = fList . getItem ( fList . getSelectionIndex ( ) ) ; String val = fParamValMap . get ( id ) ; TemplatePropertyDialog prefs = new TemplatePropertyDialog ( getShell ( ) , SWT . SHEET , new HashSet < String > ( ) , false ) ; prefs . setParameterId ( id ) ; prefs . setValue ( val ) ; if ( prefs . open ( ) == Dialog . OK ) { id = prefs . getParameterId ( ) ; val = prefs . getValue ( ) ; fParamValMap . put ( id , val ) ; fPreview . setText ( val ) ; } } @ Override protected String getNewInputObject ( ) { Set < String > taken_ids = new HashSet < String > ( ) ; taken_ids . addAll ( fParamValMap . keySet ( ) ) ; String id = null ; TemplatePropertyDialog prefs = new TemplatePropertyDialog ( getShell ( ) , SWT . SHEET , taken_ids , true ) ; if ( prefs . open ( ) == Dialog . OK ) { id = prefs . getParameterId ( ) ; String val = prefs . getValue ( ) ; fParamValMap . put ( id , val ) ; } return id ; } } package net . sf . sveditor . ui . pref ; import java . util . Set ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class TemplatePropertyDialog extends Dialog { private Text fParameterId ; private String fParameterIdStr ; private Text fValue ; private String fValueStr ; private Set < String > fTakenIds ; private boolean fCanModifyId ; public TemplatePropertyDialog ( Shell shell , int style , Set < String > taken_ids , boolean modify_id ) { super ( shell ) ; fTakenIds = taken_ids ; fCanModifyId = modify_id ; } @ Override protected boolean isResizable ( ) { return true ; } public void setParameterId ( String path ) { fParameterIdStr = path ; if ( fParameterId != null && ! fParameterId . isDisposed ( ) ) { fParameterId . setText ( fParameterIdStr ) ; } } public String getParameterId ( ) { return fParameterIdStr ; } public void setValue ( String value ) { fValueStr = value ; if ( fValue != null && ! fValue . isDisposed ( ) ) { fValue . setText ( fValueStr ) ; } } public String getValue ( ) { return fValueStr ; } private void validate ( ) { boolean ok = true ; ok &= ( ! fParameterId . getText ( ) . trim ( ) . equals ( "" ) ) ; if ( getButton ( IDialogConstants . OK_ID ) != null ) { getButton ( IDialogConstants . OK_ID ) . setEnabled ( ok ) ; } } @ Override protected Control createButtonBar ( Composite parent ) { Control c = super . createButtonBar ( parent ) ; validate ( ) ; return c ; } @ Override protected Control createContents ( Composite parent ) { Composite c = ( Composite ) super . createContents ( parent ) ; GridData gd ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . heightHint = ; gd . widthHint = ; c . setLayoutData ( gd ) ; c . layout ( ) ; Composite da = ( Composite ) getDialogArea ( ) ; gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; da . setLayoutData ( gd ) ; return c ; } @ Override protected Control createDialogArea ( Composite parent ) { Label l ; Composite frame = new Composite ( parent , SWT . NONE ) ; frame . setLayout ( new GridLayout ( , false ) ) ; GridData gd ; l = new Label ( frame , SWT . NONE ) ; l . setText ( "" ) ; fParameterId = new Text ( frame , SWT . BORDER ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; gd . widthHint = ; fParameterId . setLayoutData ( gd ) ; fParameterId . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fParameterIdStr = fParameterId . getText ( ) ; validate ( ) ; } } ) ; if ( fParameterIdStr != null ) { fParameterId . setText ( fParameterIdStr ) ; } if ( ! fCanModifyId ) { fParameterId . setEditable ( false ) ; fParameterId . setEnabled ( false ) ; } fValue = new Text ( frame , SWT . MULTI + SWT . BORDER + SWT . V_SCROLL ) ; fValue . setFont ( JFaceResources . getTextFont ( ) ) ; fValue . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fValueStr = fValue . getText ( ) ; validate ( ) ; } } ) ; if ( fValueStr != null ) { fValue . setText ( fValueStr ) ; } gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . horizontalSpan = ; gd . heightHint = ; fValue . setLayoutData ( gd ) ; return frame ; } } package net . sf . sveditor . ui . pref ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . preference . PathEditor ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; public class TemplatePathsEditor extends PathEditor { public TemplatePathsEditor ( String name , Composite parent ) { super ( name , "" , "" , parent ) ; } @ Override protected String getNewInputObject ( ) { AddDirectoryPathDialog prefs = new AddDirectoryPathDialog ( getShell ( ) , SWT . SHEET ) ; String dir = null ; if ( prefs . open ( ) == Dialog . OK ) { dir = prefs . getPath ( ) ; } return dir ; } } package net . sf . sveditor . ui . text ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . svcp . SVDBDecoratingLabelProvider ; import net . sf . sveditor . ui . svcp . SVTreeContentProvider ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . IElementComparer ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . ViewerComparator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . ui . dialogs . FilteredTree ; import org . eclipse . ui . dialogs . PatternFilter ; public class OutlineInformationControl extends AbstractInformationControl { public OutlineInformationControl ( Shell parent , int shellStyle , int treeStyle , String commandId ) { super ( parent , shellStyle , treeStyle , commandId , true ) ; } protected FilteredTree fObjectTree ; protected PatternFilter fPatternFilter ; protected TreeViewer fTreeViewer ; protected SVTreeContentProvider fContentProvider ; protected SVDBFile fSVDBFile ; protected SVEditor fEditor ; @ Override public void setFocus ( ) { fObjectTree . getFilterControl ( ) . setFocus ( ) ; } ; @ Override protected TreeViewer createTreeViewer ( Composite parent , int style ) { fPatternFilter = new PatternFilter ( ) ; fObjectTree = new FilteredTree ( parent , SWT . H_SCROLL , fPatternFilter , true ) ; fTreeViewer = fObjectTree . getViewer ( ) ; fContentProvider = new SVTreeContentProvider ( ) ; final Tree tree = fTreeViewer . getTree ( ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; gd . heightHint = tree . getItemHeight ( ) * ; gd . widthHint = ; tree . setLayoutData ( gd ) ; fTreeViewer . setContentProvider ( fContentProvider ) ; fTreeViewer . setLabelProvider ( new SVDBDecoratingLabelProvider ( new SVTreeLabelProvider ( ) ) ) ; fTreeViewer . setComparator ( new ViewerComparator ( ) ) ; fTreeViewer . setComparer ( new IElementComparer ( ) { public int hashCode ( Object element ) { return element . hashCode ( ) ; } public boolean equals ( Object a , Object b ) { return ( a == b ) ; } } ) ; fTreeViewer . setInput ( fSVDBFile ) ; fTreeViewer . expandAll ( ) ; fTreeViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; if ( sel . getFirstElement ( ) instanceof ISVDBItemBase ) { ISVDBItemBase n = ( ISVDBItemBase ) sel . getFirstElement ( ) ; fEditor . setSelection ( n , false ) ; close ( ) ; } } } ) ; return fTreeViewer ; } @ Override protected String getId ( ) { return "" ; } @ Override public void setInput ( Object information ) { if ( information == null ) { fEditor = null ; fSVDBFile = null ; } else if ( information instanceof SVEditor ) { fEditor = ( SVEditor ) information ; fSVDBFile = fEditor . getSVDBFile ( ) ; fTreeViewer . setInput ( fSVDBFile ) ; fTreeViewer . expandAll ( ) ; } } } package net . sf . sveditor . ui . text ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . objects . ObjectsTreeNode ; import net . sf . sveditor . ui . SVEditorUtil ; import net . sf . sveditor . ui . views . objects . ObjectsLabelProvider ; import net . sf . sveditor . ui . views . objects . ObjectsViewContentProvider ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . ViewerComparator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . dialogs . FilteredTree ; import org . eclipse . ui . dialogs . PatternFilter ; public class ObjectsInformationControl extends AbstractInformationControl { public ObjectsInformationControl ( Shell parent , int shellStyle , int treeStyle , String commandId ) { super ( parent , shellStyle , treeStyle , commandId , true ) ; } protected FilteredTree fObjectTree ; protected PatternFilter fPatternFilter ; protected TreeViewer fTreeViewer ; protected ObjectsViewContentProvider fContentProvider ; @ Override public void setFocus ( ) { fObjectTree . getFilterControl ( ) . setFocus ( ) ; } ; @ Override protected TreeViewer createTreeViewer ( Composite parent , int style ) { fPatternFilter = new PatternFilter ( ) ; fObjectTree = new FilteredTree ( parent , SWT . H_SCROLL , fPatternFilter , true ) ; fTreeViewer = fObjectTree . getViewer ( ) ; fContentProvider = new ObjectsViewContentProvider ( ) ; final Tree tree = fTreeViewer . getTree ( ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; gd . heightHint = tree . getItemHeight ( ) * ; gd . widthHint = ; tree . setLayoutData ( gd ) ; fTreeViewer . setContentProvider ( fContentProvider ) ; fTreeViewer . setLabelProvider ( new ObjectsLabelProvider ( ) ) ; fTreeViewer . setInput ( SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ) ; fTreeViewer . setComparator ( new ViewerComparator ( ) ) ; addKeyListeners ( ) ; fTreeViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; if ( sel . getFirstElement ( ) instanceof ObjectsTreeNode ) { ObjectsTreeNode n = ( ObjectsTreeNode ) sel . getFirstElement ( ) ; if ( n == fContentProvider . getModulesNode ( ) || n == fContentProvider . getInterfacesNode ( ) || n == fContentProvider . getPackagesNode ( ) ) { fTreeViewer . setExpandedState ( n , ! fTreeViewer . getExpandedState ( n ) ) ; } else if ( n . getItemDecl ( ) . getType ( ) == SVDBItemType . PackageDecl ) { fTreeViewer . setExpandedState ( n , ! fTreeViewer . getExpandedState ( n ) ) ; } else { if ( n . getItemDecl ( ) != null ) { try { if ( n . getItemDecl ( ) != null && n . getItemDecl ( ) . getSVDBItem ( ) != null ) { SVEditorUtil . openEditor ( n . getItemDecl ( ) . getSVDBItem ( ) ) ; } } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } } } } } ) ; return fTreeViewer ; } private void addKeyListeners ( ) { final Tree tree = fTreeViewer . getTree ( ) ; tree . addKeyListener ( new KeyListener ( ) { public void keyReleased ( KeyEvent e ) { } public void keyPressed ( KeyEvent e ) { if ( tree . getSelectionCount ( ) == && ( tree . getSelection ( ) [ ] . getData ( ) instanceof ObjectsTreeNode ) ) { ObjectsTreeNode n = ( ObjectsTreeNode ) tree . getSelection ( ) [ ] . getData ( ) ; if ( e . keyCode == SWT . CR ) { if ( n == fContentProvider . getModulesNode ( ) || n == fContentProvider . getInterfacesNode ( ) || n == fContentProvider . getPackagesNode ( ) ) { fTreeViewer . setExpandedState ( n , ! fTreeViewer . getExpandedState ( n ) ) ; } else if ( n . getItemDecl ( ) . getType ( ) == SVDBItemType . PackageDecl ) { fTreeViewer . setExpandedState ( n , ! fTreeViewer . getExpandedState ( n ) ) ; } else if ( n . getItemDecl ( ) != null && n . getItemDecl ( ) . getFile ( ) != null ) { try { SVEditorUtil . openEditor ( n . getItemDecl ( ) . getFile ( ) ) ; } catch ( PartInitException e1 ) { e1 . printStackTrace ( ) ; } } } else if ( e . keyCode == SWT . ARROW_RIGHT ) { if ( n == fContentProvider . getModulesNode ( ) || n == fContentProvider . getInterfacesNode ( ) || n == fContentProvider . getPackagesNode ( ) ) { fTreeViewer . setExpandedState ( n , true ) ; } else if ( n . getItemDecl ( ) . getType ( ) == SVDBItemType . PackageDecl ) { fTreeViewer . setExpandedState ( n , true ) ; } } else if ( e . keyCode == SWT . ARROW_LEFT ) { if ( n == fContentProvider . getModulesNode ( ) || n == fContentProvider . getInterfacesNode ( ) || n == fContentProvider . getPackagesNode ( ) ) { if ( fTreeViewer . getExpandedState ( fContentProvider . getModulesNode ( ) ) ) { fTreeViewer . setExpandedState ( fContentProvider . getModulesNode ( ) , false ) ; } else { fObjectTree . getFilterControl ( ) . setFocus ( ) ; } } else if ( n . getItemDecl ( ) . getType ( ) == SVDBItemType . PackageDecl ) { if ( fTreeViewer . getExpandedState ( n ) ) { fTreeViewer . setExpandedState ( n , false ) ; } else { if ( fTreeViewer . getExpandedState ( fContentProvider . getPackagesNode ( ) ) ) { fTreeViewer . setExpandedState ( fContentProvider . getPackagesNode ( ) , false ) ; fTreeViewer . setSelection ( new StructuredSelection ( fContentProvider . getPackagesNode ( ) ) ) ; } else { fObjectTree . getFilterControl ( ) . setFocus ( ) ; } } } else if ( n . getItemDecl ( ) != null && n . getParent ( ) != null ) { fTreeViewer . setExpandedState ( n . getParent ( ) , false ) ; fTreeViewer . setSelection ( new StructuredSelection ( n . getParent ( ) ) ) ; } } else if ( e . keyCode == SWT . HOME ) { fObjectTree . getFilterControl ( ) . setFocus ( ) ; } } } } ) ; } @ Override protected String getId ( ) { return "" ; } @ Override public void setInput ( Object information ) { } } package net . sf . sveditor . ui . text ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . information . IInformationProvider ; import org . eclipse . jface . text . information . IInformationProviderExtension ; import org . eclipse . ui . IEditorPart ; public class SVEditorProvider implements IInformationProvider , IInformationProviderExtension { private SVEditor fEditor ; public SVEditorProvider ( IEditorPart editor ) { if ( editor instanceof SVEditor ) fEditor = ( SVEditor ) editor ; } public SVEditorProvider ( IEditorPart editor , boolean useCodeResolve ) { this ( editor ) ; } public String getInformation ( ITextViewer textViewer , IRegion subject ) { return getInformation2 ( textViewer , subject ) . toString ( ) ; } public Object getInformation2 ( ITextViewer textViewer , IRegion subject ) { return fEditor ; } public IRegion getSubject ( ITextViewer textViewer , int offset ) { if ( textViewer != null && fEditor != null ) { return new Region ( offset , ) ; } return null ; } } package net . sf . sveditor . ui . text ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . hierarchy . ClassHierarchyTreeFactory ; import net . sf . sveditor . core . hierarchy . HierarchyTreeNode ; import net . sf . sveditor . ui . SVEditorUtil ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . views . hierarchy . HierarchyTreeContentProvider ; import net . sf . sveditor . ui . views . hierarchy . HierarchyTreeLabelProvider ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . IElementComparer ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . ViewerComparator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . FilteredTree ; import org . eclipse . ui . dialogs . PatternFilter ; public class HierarchyInformationControl extends AbstractInformationControl { public HierarchyInformationControl ( Shell parent , int shellStyle , int treeStyle , String commandId ) { super ( parent , shellStyle , treeStyle , commandId , true ) ; } protected FilteredTree fObjectTree ; protected PatternFilter fPatternFilter ; protected TreeViewer fTreeViewer ; protected SVDBClassDecl fClassDecl ; protected SVEditor fEditor ; @ Override public void setFocus ( ) { fObjectTree . getFilterControl ( ) . setFocus ( ) ; } ; @ Override protected TreeViewer createTreeViewer ( Composite parent , int style ) { fPatternFilter = new PatternFilter ( ) ; fObjectTree = new FilteredTree ( parent , SWT . H_SCROLL , fPatternFilter , true ) ; fTreeViewer = fObjectTree . getViewer ( ) ; final Tree tree = fTreeViewer . getTree ( ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; gd . heightHint = tree . getItemHeight ( ) * ; gd . widthHint = ; tree . setLayoutData ( gd ) ; fTreeViewer . setContentProvider ( new HierarchyTreeContentProvider ( ) ) ; fTreeViewer . setLabelProvider ( new HierarchyTreeLabelProvider ( ) ) ; fTreeViewer . setComparator ( new ViewerComparator ( ) ) ; fTreeViewer . setComparer ( new IElementComparer ( ) { public int hashCode ( Object element ) { return element . hashCode ( ) ; } public boolean equals ( Object a , Object b ) { return ( a == b ) ; } } ) ; fTreeViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; if ( sel . getFirstElement ( ) instanceof HierarchyTreeNode ) { HierarchyTreeNode n = ( HierarchyTreeNode ) sel . getFirstElement ( ) ; SVDBItem item = n . getItemDecl ( ) ; if ( item != null ) { try { SVEditorUtil . openEditor ( item ) ; } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } close ( ) ; } } } ) ; fTreeViewer . getTree ( ) . addKeyListener ( new KeyListener ( ) { public void keyPressed ( KeyEvent e ) { if ( tree . getSelectionCount ( ) == && ( tree . getSelection ( ) [ ] . getData ( ) instanceof HierarchyTreeNode ) ) { HierarchyTreeNode n = ( HierarchyTreeNode ) tree . getSelection ( ) [ ] . getData ( ) ; SVDBItem item = n . getItemDecl ( ) ; if ( e . keyCode == SWT . CR ) { if ( item != null ) { try { SVEditorUtil . openEditor ( item ) ; } catch ( PartInitException ex ) { ex . printStackTrace ( ) ; } } close ( ) ; } } } public void keyReleased ( KeyEvent e ) { } } ) ; return fTreeViewer ; } @ Override protected String getId ( ) { return "" ; } @ Override public void setInput ( Object information ) { fEditor = null ; fClassDecl = null ; if ( information != null && information instanceof ISVDBItemBase ) { ISVDBItemBase itemBase = ( ISVDBItemBase ) information ; if ( itemBase . getType ( ) == SVDBItemType . ClassDecl ) { fClassDecl = ( SVDBClassDecl ) itemBase ; IEditorPart editorPart = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . getActiveEditor ( ) ; if ( editorPart != null && editorPart instanceof SVEditor ) { fEditor = ( SVEditor ) editorPart ; ClassHierarchyTreeFactory factory = new ClassHierarchyTreeFactory ( fEditor . getIndexIterator ( ) ) ; HierarchyTreeNode root = factory . build ( fClassDecl ) ; while ( root . getParent ( ) != null ) { root = root . getParent ( ) ; } HierarchyTreeNode top = new HierarchyTreeNode ( null , "" ) ; root . setParent ( top ) ; top . addChild ( root ) ; fTreeViewer . setInput ( top ) ; fTreeViewer . expandAll ( ) ; } } } } } package net . sf . sveditor . ui . text ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . information . IInformationProvider ; import org . eclipse . jface . text . information . IInformationProviderExtension ; import org . eclipse . ui . IEditorPart ; public class SVEditorFileProvider implements IInformationProvider , IInformationProviderExtension { private SVEditor fEditor ; public SVEditorFileProvider ( IEditorPart editor ) { if ( editor instanceof SVEditor ) fEditor = ( SVEditor ) editor ; } public SVEditorFileProvider ( IEditorPart editor , boolean useCodeResolve ) { this ( editor ) ; } public String getInformation ( ITextViewer textViewer , IRegion subject ) { return getInformation2 ( textViewer , subject ) . toString ( ) ; } public Object getInformation2 ( ITextViewer textViewer , IRegion subject ) { if ( fEditor == null ) return null ; return fEditor . getSVDBFile ( ) ; } public IRegion getSubject ( ITextViewer textViewer , int offset ) { if ( textViewer != null && fEditor != null ) { return new Region ( offset , ) ; } return null ; } } package net . sf . sveditor . ui . text ; import com . ibm . icu . text . UTF16 ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; public class SVWordFinder { public static IRegion findWord ( IDocument document , int offset ) { int start = - ; int end = - ; try { int pos = offset ; char c ; while ( pos >= ) { c = document . getChar ( pos ) ; if ( ! Character . isJavaIdentifierPart ( c ) ) { if ( UTF16 . isSurrogate ( c ) ) { } else { break ; } } -- pos ; } start = pos ; pos = offset ; int length = document . getLength ( ) ; while ( pos < length ) { c = document . getChar ( pos ) ; if ( ! Character . isJavaIdentifierPart ( c ) ) { if ( UTF16 . isSurrogate ( c ) ) { } else { break ; } } ++ pos ; } end = pos ; } catch ( BadLocationException x ) { } if ( start >= - && end > - ) { if ( start == offset && end == offset ) return new Region ( offset , ) ; else if ( start == offset ) return new Region ( start , end - start ) ; else return new Region ( start + , end - start - ) ; } return null ; } } package net . sf . sveditor . ui . text ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . editor . actions . SelectionConverter ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . information . IInformationProvider ; import org . eclipse . jface . text . information . IInformationProviderExtension ; import org . eclipse . ui . IEditorPart ; public class SVElementProvider implements IInformationProvider , IInformationProviderExtension { private SVEditor fEditor ; public SVElementProvider ( IEditorPart editor ) { if ( editor instanceof SVEditor ) fEditor = ( SVEditor ) editor ; } public IRegion getSubject ( ITextViewer textViewer , int offset ) { if ( textViewer != null && fEditor != null ) { return new Region ( offset , ) ; } return null ; } public String getInformation ( ITextViewer textViewer , IRegion subject ) { return getInformation2 ( textViewer , subject ) . toString ( ) ; } public Object getInformation2 ( ITextViewer textViewer , IRegion subject ) { if ( fEditor == null ) return null ; ISVDBItemBase element = SelectionConverter . getElementAtOffset ( fEditor ) ; return element ; } } package net . sf . sveditor . ui . text . hover ; import org . eclipse . osgi . util . NLS ; final class SVHoverMessages extends NLS { private static final String BUNDLE_NAME = SVHoverMessages . class . getName ( ) ; private SVHoverMessages ( ) { } public static String AbstractAnnotationHover_action_configureAnnotationPreferences ; public static String AbstractAnnotationHover_message_singleQuickFix ; public static String AbstractAnnotationHover_message_multipleQuickFix ; public static String AbstractAnnotationHover_multifix_variable_description ; public static String JavadocHover_back ; public static String JavadocHover_back_toElement_toolTip ; public static String JavadocHover_noAttachments ; public static String JavadocHover_noAttachedJavadoc ; public static String JavadocHover_noAttachedSource ; public static String JavadocHover_noInformation ; public static String JavadocHover_constantValue_hexValue ; public static String JavadocHover_error_gettingJavadoc ; public static String JavadocHover_forward ; public static String JavadocHover_forward_toElement_toolTip ; public static String JavadocHover_forward_toolTip ; public static String JavadocHover_openDeclaration ; public static String JavadocHover_showInJavadoc ; public static String JavaSourceHover_skippedLines ; public static String JavaTextHover_createTextHover ; public static String NoBreakpointAnnotation_addBreakpoint ; public static String NLSStringHover_NLSStringHover_missingKeyWarning ; public static String NLSStringHover_NLSStringHover_PropertiesFileCouldNotBeReadWarning ; public static String NLSStringHover_NLSStringHover_PropertiesFileNotDetectedWarning ; public static String NLSStringHover_open_in_properties_file ; public static String ProblemHover_action_configureProblemSeverity ; public static String ProblemHover_chooseSettingsTypeDialog_button_cancel ; public static String ProblemHover_chooseSettingsTypeDialog_button_project ; public static String ProblemHover_chooseSettingsTypeDialog_button_workspace ; public static String ProblemHover_chooseSettingsTypeDialog_checkBox_dontShowAgain ; public static String ProblemHover_chooseSettingsTypeDialog_message ; public static String ProblemHover_chooseSettingsTypeDialog_title ; static { NLS . initializeMessages ( BUNDLE_NAME , SVHoverMessages . class ) ; } } package net . sf . sveditor . ui . text . hover ; package net . sf . sveditor . ui . text . hover ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . editor . actions . SelectionConverter ; import net . sf . sveditor . ui . text . SVWordFinder ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextHoverExtension ; import org . eclipse . jface . text . ITextHoverExtension2 ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . editors . text . EditorsUI ; public abstract class AbstractSVEditorTextHover implements ISVEditorTextHover , ITextHoverExtension , ITextHoverExtension2 { private IEditorPart fEditor ; public void setEditor ( IEditorPart editor ) { fEditor = editor ; } protected IEditorPart getEditor ( ) { return fEditor ; } public Object getHoverInfo2 ( ITextViewer textViewer , IRegion hoverRegion ) { return getHoverInfo ( textViewer , hoverRegion ) ; } public IRegion getHoverRegion ( ITextViewer textViewer , int offset ) { return SVWordFinder . findWord ( textViewer . getDocument ( ) , offset ) ; } protected ISVDBItemBase getSVElementAt ( ITextViewer textViewer , IRegion hoverRegion ) { if ( hoverRegion . getLength ( ) == ) return null ; return SelectionConverter . getElementAt ( ( SVEditor ) fEditor , hoverRegion . getOffset ( ) ) ; } public IInformationControlCreator getHoverControlCreator ( ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { return new DefaultInformationControl ( parent , EditorsUI . getTooltipAffordanceString ( ) ) ; } } ; } public IInformationControlCreator getInformationPresenterControlCreator ( ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell shell ) { return new DefaultInformationControl ( shell , true ) ; } } ; } } package net . sf . sveditor . ui . text . hover ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . internal . text . html . BrowserInformationControlInput ; public class SVDocBrowserInformationControlInput extends BrowserInformationControlInput { private final ISVDBItemBase fElement ; private final String fHtml ; private final int fLeadingImageWidth ; public SVDocBrowserInformationControlInput ( SVDocBrowserInformationControlInput previous , Tuple < ISVDBItemBase , SVDBFile > target , String html , int leadingImageWidth ) { super ( previous ) ; Assert . isNotNull ( html ) ; fElement = target . first ( ) ; fHtml = html ; fLeadingImageWidth = leadingImageWidth ; } @ Override public int getLeadingImageWidth ( ) { return fLeadingImageWidth ; } public ISVDBItemBase getElement ( ) { return fElement ; } @ Override public String getHtml ( ) { return fHtml ; } @ Override public Object getInputElement ( ) { return fElement == null ? ( Object ) fHtml : fElement ; } @ Override public String getInputName ( ) { return fElement == null ? "" : "" ; } } package net . sf . sveditor . ui . text . hover ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . net . URL ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBDocComment ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . search . SVDBFindDocComment ; import net . sf . sveditor . core . docs . DocCommentParser ; import net . sf . sveditor . core . docs . DocTopicManager ; import net . sf . sveditor . core . docs . IDocCommentParser ; import net . sf . sveditor . core . docs . IDocTopicManager ; import net . sf . sveditor . core . docs . html . HTMLFromNDMarkup ; import net . sf . sveditor . core . docs . model . DocTopic ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . open_decl . OpenDeclUtils ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . SVColorManager ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . pref . SVEditorPrefsConstants ; import net . sf . sveditor . ui . scanutils . SVDocumentTextScanner ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . action . ToolBarManager ; import org . eclipse . jface . internal . text . html . BrowserInformationControl ; import org . eclipse . jface . internal . text . html . HTMLPrinter ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . AbstractReusableInformationControlCreator ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IInformationControlExtension4 ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchSite ; import org . osgi . framework . Bundle ; public class SVDocHover extends AbstractSVEditorTextHover { private LogHandle log ; public SVDocHover ( ) { log = LogFactory . getLogHandle ( "" ) ; } public static final class PresenterControlCreator extends AbstractReusableInformationControlCreator { private IWorkbenchSite fSite ; public PresenterControlCreator ( IWorkbenchSite site ) { fSite = site ; } @ Override public IInformationControl doCreateInformationControl ( Shell parent ) { IPreferenceStore prefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; if ( BrowserInformationControl . isAvailable ( parent ) && prefs . getBoolean ( SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_USES_BROWSER ) ) { ToolBarManager tbm = new ToolBarManager ( SWT . FLAT ) ; BrowserInformationControl iControl = new BrowserInformationControl ( parent , JFaceResources . getTextFont ( ) . toString ( ) , tbm ) ; tbm . update ( true ) ; return iControl ; } else { return new DefaultInformationControl ( parent , true ) ; } } } public static final class HoverControlCreator extends AbstractReusableInformationControlCreator { private final IInformationControlCreator fInformationPresenterControlCreator ; private final boolean fAdditionalInfoAffordance ; public HoverControlCreator ( IInformationControlCreator informationPresenterControlCreator ) { this ( informationPresenterControlCreator , false ) ; } public HoverControlCreator ( IInformationControlCreator informationPresenterControlCreator , boolean additionalInfoAffordance ) { fInformationPresenterControlCreator = informationPresenterControlCreator ; fAdditionalInfoAffordance = additionalInfoAffordance ; } @ Override public IInformationControl doCreateInformationControl ( Shell parent ) { IPreferenceStore prefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; Color bg_color = SVColorManager . getColor ( PreferenceConverter . getColor ( prefs , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_BG_COLOR ) ) ; Color fg_color = SVColorManager . getColor ( PreferenceConverter . getColor ( prefs , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_FG_COLOR ) ) ; if ( BrowserInformationControl . isAvailable ( parent ) && prefs . getBoolean ( SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_USES_BROWSER ) ) { BrowserInformationControl iControl = new BrowserInformationControl ( parent , "" , "" ) { @ Override public IInformationControlCreator getInformationPresenterControlCreator ( ) { return fInformationPresenterControlCreator ; } } ; iControl . setBackgroundColor ( bg_color ) ; iControl . setForegroundColor ( fg_color ) ; return iControl ; } else { DefaultInformationControl hover = new SVDefaultInformationControl ( parent , "" , bg_color , fg_color ) ; return hover ; } } private final class SVDefaultInformationControl extends DefaultInformationControl implements IInformationControlCreator { IInformationControlCreator fCreator ; Color fBgColor ; Color fFgColor ; public SVDefaultInformationControl ( Shell parent , String msg , Color bg_color , Color fg_color ) { super ( parent , msg ) ; setBackgroundColor ( bg_color ) ; setForegroundColor ( fg_color ) ; fBgColor = bg_color ; fFgColor = fg_color ; } @ Override public IInformationControlCreator getInformationPresenterControlCreator ( ) { fCreator = super . getInformationPresenterControlCreator ( ) ; return this ; } public IInformationControl createInformationControl ( Shell parent ) { IInformationControl c = fCreator . createInformationControl ( parent ) ; if ( c instanceof DefaultInformationControl ) { ( ( DefaultInformationControl ) c ) . setBackgroundColor ( fBgColor ) ; ( ( DefaultInformationControl ) c ) . setForegroundColor ( fFgColor ) ; } return c ; } } @ Override public boolean canReuse ( IInformationControl control ) { if ( ! super . canReuse ( control ) ) return false ; if ( control instanceof IInformationControlExtension4 ) { String tooltipAffordanceString = "" ; ( ( IInformationControlExtension4 ) control ) . setStatusText ( tooltipAffordanceString ) ; } return true ; } } private static String fgStyleSheet ; private IInformationControlCreator fHoverControlCreator ; private IInformationControlCreator fPresenterControlCreator ; @ Override public IInformationControlCreator getInformationPresenterControlCreator ( ) { if ( fPresenterControlCreator == null ) fPresenterControlCreator = new PresenterControlCreator ( getSite ( ) ) ; return fPresenterControlCreator ; } private IWorkbenchSite getSite ( ) { IEditorPart editor = getEditor ( ) ; if ( editor == null ) { IWorkbenchPage page = SVUiPlugin . getActivePage ( ) ; if ( page != null ) editor = page . getActiveEditor ( ) ; } if ( editor != null ) return editor . getSite ( ) ; return null ; } @ Override public IInformationControlCreator getHoverControlCreator ( ) { if ( fHoverControlCreator == null ) fHoverControlCreator = new HoverControlCreator ( getInformationPresenterControlCreator ( ) ) ; return fHoverControlCreator ; } public String getHoverInfo ( ITextViewer textViewer , IRegion hoverRegion ) { SVDocBrowserInformationControlInput info = ( SVDocBrowserInformationControlInput ) getHoverInfo2 ( textViewer , hoverRegion ) ; return info != null ? info . getHtml ( ) : null ; } @ Override public Object getHoverInfo2 ( ITextViewer textViewer , IRegion hoverRegion ) { return internalGetHoverInfo ( textViewer , hoverRegion ) ; } private SVDocBrowserInformationControlInput internalGetHoverInfo ( ITextViewer textViewer , IRegion hoverRegion ) { Tuple < ISVDBItemBase , SVDBFile > target = findTarget ( hoverRegion ) ; if ( target == null ) return null ; return getHoverInfo ( target , hoverRegion , null ) ; } private String genContent ( List < DocTopic > topics ) { String res = "" ; HTMLFromNDMarkup markupConverter = new HTMLFromNDMarkup ( ) ; for ( DocTopic topic : topics ) { String html = "" ; html = genContentForTopic ( topic ) ; html = markupConverter . convertNDMarkupToHTML ( null , topic , html , HTMLFromNDMarkup . NDMarkupToHTMLStyle . Tooltip ) ; res += html ; } return res ; } private String genContentForTopic ( DocTopic topic ) { String res = "" ; res += "" ; res += topic . getTitle ( ) ; res += "" ; res += topic . getBody ( ) ; for ( DocTopic childTopic : topic . getChildren ( ) ) { res += genContentForTopic ( childTopic ) ; } return res ; } private SVDocBrowserInformationControlInput getHoverInfo ( Tuple < ISVDBItemBase , SVDBFile > target , IRegion hoverRegion , SVDocBrowserInformationControlInput previousInput ) { StringBuffer buffer = new StringBuffer ( ) ; ISVDBItemBase element = target . first ( ) ; if ( ! ( element instanceof ISVDBNamedItem ) ) { return null ; } ISVDBIndexIterator index_it = ( ( SVEditor ) getEditor ( ) ) . getSVDBIndex ( ) ; SVDBFindDocComment finder = new SVDBFindDocComment ( index_it ) ; SVDBDocComment docCom = finder . find ( new NullProgressMonitor ( ) , element ) ; if ( docCom == null ) { log . debug ( ILogLevel . LEVEL_MID , String . format ( "" , SVDBItem . getName ( element ) ) ) ; return null ; } List < DocTopic > docTopics = new ArrayList < DocTopic > ( ) ; IDocTopicManager topicMgr = new DocTopicManager ( ) ; IDocCommentParser docCommentParser = new DocCommentParser ( topicMgr ) ; log . debug ( ILogLevel . LEVEL_MID , "" ) ; log . debug ( ILogLevel . LEVEL_MID , "" ) ; log . debug ( ILogLevel . LEVEL_MID , "" + docCom . getRawComment ( ) ) ; log . debug ( ILogLevel . LEVEL_MID , "" ) ; docCommentParser . parse ( docCom . getRawComment ( ) , docTopics ) ; buffer . append ( genContent ( docTopics ) ) ; if ( buffer . length ( ) > ) { HTMLPrinter . insertPageProlog ( buffer , , getStyleSheet ( ) ) ; HTMLPrinter . addPageEpilog ( buffer ) ; log . debug ( ILogLevel . LEVEL_MID , "" ) ; log . debug ( ILogLevel . LEVEL_MID , "" ) ; log . debug ( ILogLevel . LEVEL_MID , buffer . toString ( ) ) ; log . debug ( ILogLevel . LEVEL_MID , "" ) ; log . debug ( ILogLevel . LEVEL_MID , "" ) ; return new SVDocBrowserInformationControlInput ( previousInput , target , buffer . toString ( ) , ) ; } return null ; } protected Tuple < ISVDBItemBase , SVDBFile > findTarget ( IRegion hoverRegion ) { SVEditor editor = ( ( SVEditor ) getEditor ( ) ) ; IDocument doc = editor . getDocument ( ) ; int offset = hoverRegion . getOffset ( ) ; SVDocumentTextScanner scanner = new SVDocumentTextScanner ( doc , offset ) ; scanner . setSkipComments ( true ) ; List < Tuple < ISVDBItemBase , SVDBFile > > items = null ; try { items = OpenDeclUtils . openDecl_2 ( editor . getSVDBFile ( ) , doc . getLineOfOffset ( hoverRegion . getOffset ( ) ) , scanner , editor . getIndexIterator ( ) ) ; } catch ( BadLocationException e ) { log . error ( "" , e ) ; } if ( items != null && items . size ( ) > ) { return items . get ( ) ; } else { return new Tuple < ISVDBItemBase , SVDBFile > ( null , null ) ; } } private String getStyleSheet ( ) { if ( fgStyleSheet == null ) fgStyleSheet = loadStyleSheet ( ) ; String css = fgStyleSheet ; return css ; } private String loadStyleSheet ( ) { Bundle bundle = Platform . getBundle ( SVUiPlugin . PLUGIN_ID ) ; URL styleSheetURL = bundle . getEntry ( "" ) ; if ( styleSheetURL != null ) { BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( styleSheetURL . openStream ( ) ) ) ; StringBuffer buffer = new StringBuffer ( ) ; String line = reader . readLine ( ) ; while ( line != null ) { buffer . append ( line ) ; buffer . append ( '' ) ; line = reader . readLine ( ) ; } return buffer . toString ( ) ; } catch ( IOException ex ) { log . error ( "" , ex ) ; return "" ; } finally { try { if ( reader != null ) reader . close ( ) ; } catch ( IOException e ) { } } } return null ; } } package net . sf . sveditor . ui . text . hover ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . ui . IEditorPart ; public interface ISVEditorTextHover extends ITextHover { void setEditor ( IEditorPart editor ) ; } package net . sf . sveditor . ui . text ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . dialogs . PopupDialog ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlExtension ; import org . eclipse . jface . text . IInformationControlExtension2 ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; public abstract class AbstractInformationControl extends PopupDialog implements IInformationControl , IInformationControlExtension , IInformationControlExtension2 , DisposeListener { private TreeViewer fTreeViewer ; protected StringMatcher fStringMatcher ; private int fTreeStyle ; public AbstractInformationControl ( Shell parent , int shellStyle , int treeStyle , String invokingCommandId , boolean showStatusField ) { super ( parent , shellStyle , true , true , true , false , false , null , null ) ; fTreeStyle = treeStyle ; create ( ) ; } @ Override protected Control createDialogArea ( Composite parent ) { fTreeViewer = createTreeViewer ( parent , fTreeStyle ) ; addDisposeListener ( this ) ; return fTreeViewer . getControl ( ) ; } public AbstractInformationControl ( Shell parent , int shellStyle , int treeStyle ) { this ( parent , shellStyle , treeStyle , null , false ) ; } protected abstract TreeViewer createTreeViewer ( Composite parent , int style ) ; protected abstract String getId ( ) ; protected TreeViewer getTreeViewer ( ) { return fTreeViewer ; } protected boolean hasHeader ( ) { return false ; } protected void createHorizontalSeparator ( Composite parent ) { Label separator = new Label ( parent , SWT . SEPARATOR | SWT . HORIZONTAL | SWT . LINE_DOT ) ; separator . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; } protected Object getSelectedElement ( ) { if ( fTreeViewer == null ) return null ; return ( ( IStructuredSelection ) fTreeViewer . getSelection ( ) ) . getFirstElement ( ) ; } public void setInformation ( String information ) { } public abstract void setInput ( Object information ) ; protected void fillViewMenu ( IMenuManager viewMenu ) { } @ Override protected void fillDialogMenu ( IMenuManager dialogMenu ) { super . fillDialogMenu ( dialogMenu ) ; fillViewMenu ( dialogMenu ) ; } public void setVisible ( boolean visible ) { if ( visible ) { open ( ) ; } else { saveDialogBounds ( getShell ( ) ) ; getShell ( ) . setVisible ( false ) ; } } @ Override public int open ( ) { return super . open ( ) ; } public final void dispose ( ) { close ( ) ; } public void widgetDisposed ( DisposeEvent event ) { fTreeViewer = null ; } public boolean hasContents ( ) { return fTreeViewer != null && fTreeViewer . getInput ( ) != null ; } public void setSizeConstraints ( int maxWidth , int maxHeight ) { } public Point computeSizeHint ( ) { return getShell ( ) . getSize ( ) ; } public void setLocation ( Point location ) { if ( ! getPersistLocation ( ) || getDialogSettings ( ) == null ) getShell ( ) . setLocation ( location ) ; } public void setSize ( int width , int height ) { getShell ( ) . setSize ( width , height ) ; } public void addDisposeListener ( DisposeListener listener ) { getShell ( ) . addDisposeListener ( listener ) ; } public void removeDisposeListener ( DisposeListener listener ) { getShell ( ) . removeDisposeListener ( listener ) ; } public void setForegroundColor ( Color foreground ) { applyForegroundColor ( foreground , getContents ( ) ) ; } public void setBackgroundColor ( Color background ) { applyBackgroundColor ( background , getContents ( ) ) ; } public boolean isFocusControl ( ) { return getShell ( ) . getDisplay ( ) . getActiveShell ( ) == getShell ( ) ; } public void setFocus ( ) { getShell ( ) . forceFocus ( ) ; } public void addFocusListener ( FocusListener listener ) { getShell ( ) . addFocusListener ( listener ) ; } public void removeFocusListener ( FocusListener listener ) { getShell ( ) . removeFocusListener ( listener ) ; } @ Override protected void setTabOrder ( Composite composite ) { } } package net . sf . sveditor . ui . text ; import java . util . Vector ; public class StringMatcher { protected String fPattern ; protected int fLength ; protected boolean fIgnoreWildCards ; protected boolean fIgnoreCase ; protected boolean fHasLeadingStar ; protected boolean fHasTrailingStar ; protected String fSegments [ ] ; protected int fBound = ; protected static final char fSingleWildCard = '' ; public static class Position { int start ; int end ; public Position ( int start , int end ) { this . start = start ; this . end = end ; } public int getStart ( ) { return start ; } public int getEnd ( ) { return end ; } } public StringMatcher ( String pattern , boolean ignoreCase , boolean ignoreWildCards ) { if ( pattern == null ) throw new IllegalArgumentException ( ) ; fIgnoreCase = ignoreCase ; fIgnoreWildCards = ignoreWildCards ; fPattern = pattern ; fLength = pattern . length ( ) ; if ( fIgnoreWildCards ) { parseNoWildCards ( ) ; } else { parseWildCards ( ) ; } } public StringMatcher . Position find ( String text , int start , int end ) { if ( text == null ) throw new IllegalArgumentException ( ) ; int tlen = text . length ( ) ; if ( start < ) start = ; if ( end > tlen ) end = tlen ; if ( end < || start >= end ) return null ; if ( fLength == ) return new Position ( start , start ) ; if ( fIgnoreWildCards ) { int x = posIn ( text , start , end ) ; if ( x < ) return null ; return new Position ( x , x + fLength ) ; } int segCount = fSegments . length ; if ( segCount == ) return new Position ( start , end ) ; int curPos = start ; int matchStart = - ; int i ; for ( i = ; i < segCount && curPos < end ; ++ i ) { String current = fSegments [ i ] ; int nextMatch = regExpPosIn ( text , curPos , end , current ) ; if ( nextMatch < ) return null ; if ( i == ) matchStart = nextMatch ; curPos = nextMatch + current . length ( ) ; } if ( i < segCount ) return null ; return new Position ( matchStart , curPos ) ; } public boolean match ( String text ) { return match ( text , , text . length ( ) ) ; } public boolean match ( String text , int start , int end ) { if ( null == text ) throw new IllegalArgumentException ( ) ; if ( start > end ) return false ; if ( fIgnoreWildCards ) return ( end - start == fLength ) && fPattern . regionMatches ( fIgnoreCase , , text , start , fLength ) ; int segCount = fSegments . length ; if ( segCount == && ( fHasLeadingStar || fHasTrailingStar ) ) return true ; if ( start == end ) return fLength == ; if ( fLength == ) return start == end ; int tlen = text . length ( ) ; if ( start < ) start = ; if ( end > tlen ) end = tlen ; int tCurPos = start ; int bound = end - fBound ; if ( bound < ) return false ; int i = ; String current = fSegments [ i ] ; int segLength = current . length ( ) ; if ( ! fHasLeadingStar ) { if ( ! regExpRegionMatches ( text , start , current , , segLength ) ) { return false ; } else { ++ i ; tCurPos = tCurPos + segLength ; } } if ( ( fSegments . length == ) && ( ! fHasLeadingStar ) && ( ! fHasTrailingStar ) ) { return tCurPos == end ; } while ( i < segCount ) { current = fSegments [ i ] ; int currentMatch ; int k = current . indexOf ( fSingleWildCard ) ; if ( k < ) { currentMatch = textPosIn ( text , tCurPos , end , current ) ; if ( currentMatch < ) return false ; } else { currentMatch = regExpPosIn ( text , tCurPos , end , current ) ; if ( currentMatch < ) return false ; } tCurPos = currentMatch + current . length ( ) ; i ++ ; } if ( ! fHasTrailingStar && tCurPos != end ) { int clen = current . length ( ) ; return regExpRegionMatches ( text , end - clen , current , , clen ) ; } return i == segCount ; } private void parseNoWildCards ( ) { fSegments = new String [ ] ; fSegments [ ] = fPattern ; fBound = fLength ; } private void parseWildCards ( ) { if ( fPattern . startsWith ( "" ) ) fHasLeadingStar = true ; if ( fPattern . endsWith ( "" ) ) { if ( fLength > && fPattern . charAt ( fLength - ) != '' ) { fHasTrailingStar = true ; } } Vector < String > temp = new Vector < String > ( ) ; int pos = ; StringBuffer buf = new StringBuffer ( ) ; while ( pos < fLength ) { char c = fPattern . charAt ( pos ++ ) ; switch ( c ) { case '' : if ( pos >= fLength ) { buf . append ( c ) ; } else { char next = fPattern . charAt ( pos ++ ) ; if ( next == '' || next == '' || next == '' ) { buf . append ( next ) ; } else { buf . append ( c ) ; buf . append ( next ) ; } } break ; case '' : if ( buf . length ( ) > ) { temp . addElement ( buf . toString ( ) ) ; fBound += buf . length ( ) ; buf . setLength ( ) ; } break ; case '' : buf . append ( fSingleWildCard ) ; break ; default : buf . append ( c ) ; } } if ( buf . length ( ) > ) { temp . addElement ( buf . toString ( ) ) ; fBound += buf . length ( ) ; } fSegments = new String [ temp . size ( ) ] ; temp . copyInto ( fSegments ) ; } protected int posIn ( String text , int start , int end ) { int max = end - fLength ; if ( ! fIgnoreCase ) { int i = text . indexOf ( fPattern , start ) ; if ( i == - || i > max ) return - ; return i ; } for ( int i = start ; i <= max ; ++ i ) { if ( text . regionMatches ( true , i , fPattern , , fLength ) ) return i ; } return - ; } protected int regExpPosIn ( String text , int start , int end , String p ) { int plen = p . length ( ) ; int max = end - plen ; for ( int i = start ; i <= max ; ++ i ) { if ( regExpRegionMatches ( text , i , p , , plen ) ) return i ; } return - ; } protected boolean regExpRegionMatches ( String text , int tStart , String p , int pStart , int plen ) { while ( plen -- > ) { char tchar = text . charAt ( tStart ++ ) ; char pchar = p . charAt ( pStart ++ ) ; if ( ! fIgnoreWildCards ) { if ( pchar == fSingleWildCard ) { continue ; } } if ( pchar == tchar ) continue ; if ( fIgnoreCase ) { if ( Character . toUpperCase ( tchar ) == Character . toUpperCase ( pchar ) ) continue ; if ( Character . toLowerCase ( tchar ) == Character . toLowerCase ( pchar ) ) continue ; } return false ; } return true ; } protected int textPosIn ( String text , int start , int end , String p ) { int plen = p . length ( ) ; int max = end - plen ; if ( ! fIgnoreCase ) { int i = text . indexOf ( p , start ) ; if ( i == - || i > max ) return - ; return i ; } for ( int i = start ; i <= max ; ++ i ) { if ( text . regionMatches ( true , i , p , , plen ) ) return i ; } return - ; } } package net . sf . sveditor . ui ; import net . sf . sveditor . ui . wizards . NewSVClassWizard ; import net . sf . sveditor . ui . wizards . NewSVInterfaceWizard ; import net . sf . sveditor . ui . wizards . NewSVModuleWizard ; import net . sf . sveditor . ui . wizards . NewSVPackageWizard ; import net . sf . sveditor . ui . wizards . templates . SVTemplateWizard ; import org . eclipse . ui . IFolderLayout ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IPerspectiveFactory ; import org . eclipse . ui . navigator . resources . ProjectExplorer ; import org . eclipse . ui . wizards . newresource . BasicNewFileResourceWizard ; import org . eclipse . ui . wizards . newresource . BasicNewFolderResourceWizard ; public class SVPerspectiveFactory implements IPerspectiveFactory { public void createInitialLayout ( IPageLayout layout ) { defineActions ( layout ) ; defineLayout ( layout ) ; } public void defineActions ( IPageLayout layout ) { layout . addNewWizardShortcut ( BasicNewFolderResourceWizard . WIZARD_ID ) ; layout . addNewWizardShortcut ( BasicNewFileResourceWizard . WIZARD_ID ) ; layout . addNewWizardShortcut ( NewSVClassWizard . ID ) ; layout . addNewWizardShortcut ( NewSVInterfaceWizard . ID ) ; layout . addNewWizardShortcut ( NewSVModuleWizard . ID ) ; layout . addNewWizardShortcut ( NewSVPackageWizard . ID ) ; layout . addNewWizardShortcut ( SVTemplateWizard . ID ) ; layout . addShowViewShortcut ( ProjectExplorer . VIEW_ID ) ; layout . addShowViewShortcut ( IPageLayout . ID_BOOKMARKS ) ; layout . addShowViewShortcut ( IPageLayout . ID_OUTLINE ) ; layout . addShowViewShortcut ( IPageLayout . ID_PROP_SHEET ) ; layout . addShowViewShortcut ( IPageLayout . ID_PROBLEM_VIEW ) ; layout . addShowViewShortcut ( IPageLayout . ID_PROGRESS_VIEW ) ; layout . addShowViewShortcut ( IPageLayout . ID_TASK_LIST ) ; layout . addActionSet ( IPageLayout . ID_NAVIGATE_ACTION_SET ) ; } public void defineLayout ( IPageLayout layout ) { String editorArea = layout . getEditorArea ( ) ; IFolderLayout topLeft = layout . createFolder ( "" , IPageLayout . LEFT , ( float ) , editorArea ) ; topLeft . addView ( ProjectExplorer . VIEW_ID ) ; topLeft . addPlaceholder ( IPageLayout . ID_BOOKMARKS ) ; topLeft . addPlaceholder ( "" ) ; IFolderLayout bottomLeft = layout . createFolder ( "" , IPageLayout . BOTTOM , ( float ) , "" ) ; bottomLeft . addView ( IPageLayout . ID_OUTLINE ) ; IFolderLayout bottomRight = layout . createFolder ( "" , IPageLayout . BOTTOM , ( float ) , editorArea ) ; bottomRight . addView ( IPageLayout . ID_TASK_LIST ) ; } } package net . sf . sveditor . ui . compare ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . IViewerCreator ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . widgets . Composite ; public class SVCompareViewerCreator implements IViewerCreator { public SVCompareViewerCreator ( ) { } public Viewer createViewer ( Composite parent , CompareConfiguration config ) { return new SVCompareViewer ( parent , config ) ; } } package net . sf . sveditor . ui . compare ; import net . sf . sveditor . ui . editor . SVDocumentPartitions ; import net . sf . sveditor . ui . editor . SVDocumentSetupParticipant ; import net . sf . sveditor . ui . editor . SVSourceViewerConfiguration ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . contentmergeviewer . TextMergeViewer ; import org . eclipse . jface . text . IDocumentPartitioner ; import org . eclipse . jface . text . TextViewer ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; public class SVCompareViewer extends TextMergeViewer { public SVCompareViewer ( Composite parent , CompareConfiguration configuration ) { super ( parent , SWT . LEFT_TO_RIGHT , configuration ) ; } @ Override protected void configureTextViewer ( TextViewer textViewer ) { if ( textViewer instanceof SourceViewer ) { SourceViewer viewer = ( SourceViewer ) textViewer ; SVSourceViewerConfiguration configuration = new SVSourceViewerConfiguration ( null ) ; viewer . configure ( configuration ) ; } } @ Override protected IDocumentPartitioner getDocumentPartitioner ( ) { return SVDocumentSetupParticipant . createPartitioner ( ) ; } @ Override protected String getDocumentPartitioning ( ) { return SVDocumentPartitions . SV_PARTITIONING ; } } package net . sf . sveditor . ui . svcp ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBItemType ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class SVTreeContentProvider implements ITreeContentProvider { private static final Set < SVDBItemType > fDoNotRecurseScopes ; private static final Set < SVDBItemType > fExpandInLineItems ; private static final Set < SVDBItemType > fIgnoreItems ; static { fDoNotRecurseScopes = new HashSet < SVDBItemType > ( ) ; fDoNotRecurseScopes . add ( SVDBItemType . Function ) ; fDoNotRecurseScopes . add ( SVDBItemType . Task ) ; fDoNotRecurseScopes . add ( SVDBItemType . Coverpoint ) ; fDoNotRecurseScopes . add ( SVDBItemType . CoverpointCross ) ; fDoNotRecurseScopes . add ( SVDBItemType . ConfigDecl ) ; fExpandInLineItems = new HashSet < SVDBItemType > ( ) ; fExpandInLineItems . add ( SVDBItemType . VarDeclStmt ) ; fExpandInLineItems . add ( SVDBItemType . ParamPortDecl ) ; fExpandInLineItems . add ( SVDBItemType . ModIfcInst ) ; fExpandInLineItems . add ( SVDBItemType . ImportStmt ) ; fExpandInLineItems . add ( SVDBItemType . ExportStmt ) ; fIgnoreItems = new HashSet < SVDBItemType > ( ) ; fIgnoreItems . add ( SVDBItemType . NullStmt ) ; } public Object [ ] getChildren ( Object elem ) { if ( elem instanceof ISVDBItemBase ) { List < ISVDBItemBase > c = new ArrayList < ISVDBItemBase > ( ) ; ISVDBItemBase it = ( ISVDBItemBase ) elem ; if ( it instanceof ISVDBChildParent && ! fDoNotRecurseScopes . contains ( it . getType ( ) ) ) { for ( ISVDBChildItem ci : ( ( ISVDBChildParent ) it ) . getChildren ( ) ) { if ( fExpandInLineItems . contains ( ci . getType ( ) ) ) { for ( ISVDBChildItem ci_p : ( ( ISVDBChildParent ) ci ) . getChildren ( ) ) { c . add ( ci_p ) ; } } else if ( ! fIgnoreItems . contains ( ci . getType ( ) ) ) { c . add ( ci ) ; } } } return c . toArray ( ) ; } return new Object [ ] ; } public Object getParent ( Object element ) { if ( element instanceof ISVDBChildItem ) { return ( ( ISVDBChildItem ) element ) . getParent ( ) ; } else { return null ; } } public boolean hasChildren ( Object element ) { if ( element instanceof ISVDBChildParent ) { ISVDBChildParent p = ( ISVDBChildParent ) element ; if ( ! fDoNotRecurseScopes . contains ( p . getType ( ) ) ) { return p . getChildren ( ) . iterator ( ) . hasNext ( ) ; } } return false ; } public Object [ ] getElements ( Object element ) { return getChildren ( element ) ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } } package net . sf . sveditor . ui . svcp ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . WeakHashMap ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . ISVDBIndexChangeListener ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . IDecoration ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ILightweightLabelDecorator ; import org . eclipse . jface . viewers . LabelProviderChangedEvent ; import org . eclipse . swt . widgets . Display ; public class SVDBFileDecorator implements ILightweightLabelDecorator { private List < ILabelProviderListener > fListeners ; private Thread fLookupThread ; private Map < String , Map < String , Boolean > > fManagedByIndex ; private Map < SVDBIndexCollection , IndexChangeListener > fProjectListeners ; private List < Object > fWorkQueue ; private boolean fFireChangeRunnableQueued ; private Runnable lookupRunnable = new Runnable ( ) { public void run ( ) { while ( true ) { Object work = null ; synchronized ( fWorkQueue ) { for ( int i = ; i < ; i ++ ) { if ( fWorkQueue . size ( ) > ) { work = fWorkQueue . remove ( ) ; } else if ( i == ) { try { fWorkQueue . wait ( ) ; } catch ( InterruptedException e ) { } } } if ( work == null ) { fLookupThread = null ; break ; } } if ( work instanceof IFile ) { IFile elem = ( IFile ) work ; IProject p = elem . getProject ( ) ; String pname = p . getName ( ) ; SVDBProjectManager pmgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData pdata = pmgr . getProjectData ( p ) ; SVDBIndexCollection index = pdata . getProjectIndexMgr ( ) ; List < SVDBSearchResult < SVDBFile > > res = index . findFile ( "" + elem . getFullPath ( ) . toOSString ( ) , false ) ; synchronized ( fManagedByIndex ) { Map < String , Boolean > proj_map = fManagedByIndex . get ( p . getName ( ) ) ; if ( proj_map == null ) { proj_map = new HashMap < String , Boolean > ( ) ; fManagedByIndex . put ( p . getName ( ) , proj_map ) ; if ( ! fProjectListeners . containsKey ( index ) ) { IndexChangeListener l = new IndexChangeListener ( pname ) ; fProjectListeners . put ( index , l ) ; index . addIndexChangeListener ( l ) ; } } proj_map . remove ( elem ) ; proj_map . put ( elem . getFullPath ( ) . toOSString ( ) , ( res != null && res . size ( ) > ) ) ; } } else if ( work instanceof IndexChangeListener ) { IndexChangeListener l = ( IndexChangeListener ) work ; String project = l . getProject ( ) ; synchronized ( fManagedByIndex ) { fManagedByIndex . remove ( project ) ; } } } Display . getDefault ( ) . asyncExec ( fireChangeRunnable ) ; } } ; private Runnable fireChangeRunnable = new Runnable ( ) { public void run ( ) { synchronized ( SVDBFileDecorator . this ) { fFireChangeRunnableQueued = false ; } LabelProviderChangedEvent ev = new LabelProviderChangedEvent ( SVDBFileDecorator . this ) ; for ( ILabelProviderListener l : fListeners ) { l . labelProviderChanged ( ev ) ; } } } ; private class IndexChangeListener implements ISVDBIndexChangeListener { private String fProject ; public IndexChangeListener ( String project ) { fProject = project ; } public String getProject ( ) { return fProject ; } public void index_changed ( int reason , SVDBFile file ) { switch ( reason ) { case FILE_ADDED : case FILE_REMOVED : queueWork ( this ) ; break ; } } public void index_rebuilt ( ) { queueWork ( this ) ; } } ; public SVDBFileDecorator ( ) { fListeners = new ArrayList < ILabelProviderListener > ( ) ; fWorkQueue = new ArrayList < Object > ( ) ; fManagedByIndex = new HashMap < String , Map < String , Boolean > > ( ) ; fProjectListeners = new WeakHashMap < SVDBIndexCollection , SVDBFileDecorator . IndexChangeListener > ( ) ; } public void addListener ( ILabelProviderListener listener ) { synchronized ( fListeners ) { fListeners . add ( listener ) ; } } public void removeListener ( ILabelProviderListener listener ) { synchronized ( fListeners ) { fListeners . remove ( listener ) ; } } public void dispose ( ) { synchronized ( fListeners ) { fListeners . clear ( ) ; } } public boolean isLabelProperty ( Object element , String property ) { return false ; } private void queueWork ( Object work ) { synchronized ( fWorkQueue ) { if ( ! fWorkQueue . contains ( work ) ) { fWorkQueue . add ( work ) ; if ( fLookupThread == null ) { fLookupThread = new Thread ( lookupRunnable ) ; fLookupThread . start ( ) ; } fWorkQueue . notifyAll ( ) ; } } } public void decorate ( Object element , IDecoration decoration ) { ImageDescriptor image = null ; if ( element instanceof IFile ) { IFile file = ( IFile ) element ; String path = ( ( IFile ) element ) . getFullPath ( ) . toOSString ( ) ; synchronized ( fManagedByIndex ) { Map < String , Boolean > proj_map = fManagedByIndex . get ( file . getProject ( ) . getName ( ) ) ; if ( proj_map != null && proj_map . containsKey ( path ) ) { if ( proj_map . get ( path ) ) { image = SVUiPlugin . getImageDescriptor ( "" ) ; if ( image != null ) { decoration . addOverlay ( image ) ; } } } else { SVDBProjectManager pmgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBProjectData pdata = pmgr . getProjectData ( file . getProject ( ) ) ; SVDBIndexCollection index = pdata . getProjectIndexMgr ( ) ; String pname = file . getProject ( ) . getName ( ) ; if ( index . isFileListLoaded ( ) ) { if ( proj_map == null ) { proj_map = new HashMap < String , Boolean > ( ) ; fManagedByIndex . put ( pname , proj_map ) ; if ( fProjectListeners . containsKey ( index ) ) { IndexChangeListener l = new IndexChangeListener ( pname ) ; fProjectListeners . put ( index , l ) ; index . addIndexChangeListener ( l ) ; } } List < SVDBSearchResult < SVDBFile > > res = index . findFile ( "" + path , false ) ; proj_map . put ( path , ( res != null && res . size ( ) > ) ) ; if ( proj_map . get ( path ) ) { image = SVUiPlugin . getImageDescriptor ( "" ) ; if ( image != null ) { decoration . addOverlay ( image ) ; } } } else { queueWork ( element ) ; } } } } } } package net . sf . sveditor . ui . svcp ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcClassParam ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . SVDBParamValueAssign ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfo ; import net . sf . sveditor . core . db . SVDBTypeInfoUserDef ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . core . db . stmt . SVDBAlwaysStmt ; import net . sf . sveditor . core . db . stmt . SVDBEventControlStmt ; import net . sf . sveditor . core . db . stmt . SVDBExportItem ; import net . sf . sveditor . core . db . stmt . SVDBImportItem ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . ui . SVDBIconUtils ; import org . eclipse . jface . viewers . DelegatingStyledCellLabelProvider . IStyledLabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . StyledString ; import org . eclipse . swt . graphics . Image ; import org . eclipse . ui . model . WorkbenchLabelProvider ; public class SVTreeLabelProvider extends LabelProvider implements IStyledLabelProvider { protected boolean fShowFunctionRetType ; private WorkbenchLabelProvider fLabelProvider ; public SVTreeLabelProvider ( ) { fLabelProvider = new WorkbenchLabelProvider ( ) ; fShowFunctionRetType = true ; } @ Override public Image getImage ( Object element ) { if ( element instanceof ISVDBItemBase ) { return SVDBIconUtils . getIcon ( ( ISVDBItemBase ) element ) ; } else if ( element instanceof SVDBDeclCacheItem ) { SVDBDeclCacheItem item = ( SVDBDeclCacheItem ) element ; return SVDBIconUtils . getIcon ( item . getType ( ) ) ; } else { return super . getImage ( element ) ; } } public StyledString getStyledText ( Object element ) { if ( element == null ) { return new StyledString ( "" ) ; } if ( element instanceof SVDBDeclCacheItem ) { SVDBDeclCacheItem item = ( SVDBDeclCacheItem ) element ; return new StyledString ( item . getName ( ) ) ; } else if ( element instanceof SVDBVarDeclItem ) { SVDBVarDeclItem var = ( SVDBVarDeclItem ) element ; SVDBVarDeclStmt var_r = var . getParent ( ) ; StyledString ret = new StyledString ( var . getName ( ) ) ; if ( var_r . getTypeInfo ( ) != null ) { ret . append ( "" + var_r . getTypeName ( ) , StyledString . QUALIFIER_STYLER ) ; SVDBTypeInfo type = var_r . getTypeInfo ( ) ; if ( type . getType ( ) == SVDBItemType . TypeInfoUserDef ) { SVDBTypeInfoUserDef cls = ( SVDBTypeInfoUserDef ) type ; if ( cls . getParameters ( ) != null && cls . getParameters ( ) . getParameters ( ) . size ( ) > ) { ret . append ( "" , StyledString . QUALIFIER_STYLER ) ; for ( int i = ; i < cls . getParameters ( ) . getParameters ( ) . size ( ) ; i ++ ) { SVDBParamValueAssign p = cls . getParameters ( ) . getParameters ( ) . get ( i ) ; ret . append ( p . getName ( ) , StyledString . QUALIFIER_STYLER ) ; if ( i + < cls . getParameters ( ) . getParameters ( ) . size ( ) ) { ret . append ( "" , StyledString . QUALIFIER_STYLER ) ; } } ret . append ( ">" , StyledString . QUALIFIER_STYLER ) ; } } } return ret ; } else if ( element instanceof ISVDBNamedItem ) { StyledString ret = new StyledString ( ( ( ISVDBNamedItem ) element ) . getName ( ) ) ; ISVDBNamedItem ni = ( ISVDBNamedItem ) element ; if ( ni . getType ( ) . isElemOf ( SVDBItemType . Task , SVDBItemType . Function ) ) { SVDBTask tf = ( SVDBTask ) element ; ret . append ( "" ) ; for ( int i = ; i < tf . getParams ( ) . size ( ) ; i ++ ) { SVDBParamPortDecl p = tf . getParams ( ) . get ( i ) ; if ( p . getTypeInfo ( ) != null ) { ret . append ( p . getTypeInfo ( ) . toString ( ) ) ; } if ( i + < tf . getParams ( ) . size ( ) ) { ret . append ( "" ) ; } } ret . append ( "" ) ; if ( tf . getType ( ) == SVDBItemType . Function ) { SVDBFunction f = ( SVDBFunction ) tf ; if ( f . getReturnType ( ) != null && ! f . getReturnType ( ) . equals ( "" ) && fShowFunctionRetType ) { ret . append ( "" + f . getReturnType ( ) , StyledString . QUALIFIER_STYLER ) ; } } } else if ( element instanceof SVDBModIfcDecl ) { SVDBModIfcDecl decl = ( SVDBModIfcDecl ) element ; if ( decl . getParameters ( ) . size ( ) > ) { ret . append ( "" , StyledString . QUALIFIER_STYLER ) ; for ( int i = ; i < decl . getParameters ( ) . size ( ) ; i ++ ) { SVDBModIfcClassParam p = decl . getParameters ( ) . get ( i ) ; ret . append ( p . getName ( ) , StyledString . QUALIFIER_STYLER ) ; if ( i + < decl . getParameters ( ) . size ( ) ) { ret . append ( "" , StyledString . QUALIFIER_STYLER ) ; } } ret . append ( ">" , StyledString . QUALIFIER_STYLER ) ; } } else if ( element instanceof SVDBClassDecl ) { SVDBClassDecl decl = ( SVDBClassDecl ) element ; if ( decl . getParameters ( ) != null && decl . getParameters ( ) . size ( ) > ) { ret . append ( "" , StyledString . QUALIFIER_STYLER ) ; for ( int i = ; i < decl . getParameters ( ) . size ( ) ; i ++ ) { SVDBModIfcClassParam p = decl . getParameters ( ) . get ( i ) ; ret . append ( p . getName ( ) , StyledString . QUALIFIER_STYLER ) ; if ( i + < decl . getParameters ( ) . size ( ) ) { ret . append ( "" , StyledString . QUALIFIER_STYLER ) ; } } ret . append ( ">" , StyledString . QUALIFIER_STYLER ) ; } } else if ( ni . getType ( ) == SVDBItemType . ModIfcInstItem ) { SVDBModIfcInstItem mod_item = ( SVDBModIfcInstItem ) ni ; SVDBModIfcInst mod_inst = ( SVDBModIfcInst ) mod_item . getParent ( ) ; ret . append ( "" + mod_inst . getTypeName ( ) , StyledString . QUALIFIER_STYLER ) ; } else if ( ni . getType ( ) == SVDBItemType . CoverageOptionStmt ) { ret . append ( "" , StyledString . QUALIFIER_STYLER ) ; } else { } return ret ; } else if ( element instanceof ISVDBItemBase ) { ISVDBItemBase it = ( ISVDBItemBase ) element ; StyledString ret = null ; if ( it . getType ( ) == SVDBItemType . AlwaysStmt ) { SVDBAlwaysStmt always = ( SVDBAlwaysStmt ) it ; if ( always . getBody ( ) != null && always . getBody ( ) . getType ( ) == SVDBItemType . EventControlStmt ) { SVDBEventControlStmt stmt = ( SVDBEventControlStmt ) always . getBody ( ) ; ret = new StyledString ( stmt . getExpr ( ) . toString ( ) . trim ( ) ) ; } else { ret = new StyledString ( "" ) ; } } else if ( it . getType ( ) == SVDBItemType . InitialStmt ) { ret = new StyledString ( "" ) ; } else if ( it . getType ( ) == SVDBItemType . FinalStmt ) { ret = new StyledString ( "" ) ; } else if ( it . getType ( ) == SVDBItemType . ImportItem ) { SVDBImportItem imp = ( SVDBImportItem ) it ; ret = new StyledString ( "" + imp . getImport ( ) ) ; } else if ( it . getType ( ) == SVDBItemType . ExportItem ) { SVDBExportItem exp = ( SVDBExportItem ) it ; ret = new StyledString ( "" + exp . getExport ( ) ) ; } if ( ret == null ) { ret = new StyledString ( element . toString ( ) ) ; } return ret ; } else { return new StyledString ( element . toString ( ) ) ; } } @ Override public String getText ( Object element ) { return getStyledText ( element ) . toString ( ) ; } @ Override public void addListener ( ILabelProviderListener listener ) { fLabelProvider . addListener ( listener ) ; } @ Override public void removeListener ( ILabelProviderListener listener ) { fLabelProvider . removeListener ( listener ) ; } @ Override public boolean isLabelProperty ( Object element , String property ) { return fLabelProvider . isLabelProperty ( element , property ) ; } @ Override public void dispose ( ) { super . dispose ( ) ; fLabelProvider . dispose ( ) ; } } package net . sf . sveditor . ui . svcp ; import org . eclipse . jface . preference . JFacePreferences ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ColumnViewer ; import org . eclipse . jface . viewers . DecoratingStyledCellLabelProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . StyledString ; import org . eclipse . jface . viewers . StyledString . Styler ; import org . eclipse . jface . viewers . ViewerColumn ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IWorkbenchPreferenceConstants ; import org . eclipse . ui . PlatformUI ; public class SVDBDecoratingLabelProvider extends DecoratingStyledCellLabelProvider implements ILabelProvider , IPropertyChangeListener { private static final String HIGHLIGHT_BG_COLOR_NAME = "" ; public static final Styler HIGHLIGHT_STYLE = StyledString . createColorRegistryStyler ( null , HIGHLIGHT_BG_COLOR_NAME ) ; public SVDBDecoratingLabelProvider ( SVTreeLabelProvider provider ) { super ( provider , PlatformUI . getWorkbench ( ) . getDecoratorManager ( ) . getLabelDecorator ( ) , null ) ; } public void initialize ( ColumnViewer viewer , ViewerColumn column ) { PlatformUI . getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; JFaceResources . getColorRegistry ( ) . addListener ( this ) ; setOwnerDrawEnabled ( showColoredLabels ( ) ) ; super . initialize ( viewer , column ) ; } public void dispose ( ) { super . dispose ( ) ; PlatformUI . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; JFaceResources . getColorRegistry ( ) . removeListener ( this ) ; } private void refresh ( ) { ColumnViewer viewer = getViewer ( ) ; if ( viewer == null ) { return ; } boolean showColoredLabels = showColoredLabels ( ) ; if ( showColoredLabels != isOwnerDrawEnabled ( ) ) { setOwnerDrawEnabled ( showColoredLabels ) ; viewer . refresh ( ) ; } else if ( showColoredLabels ) { viewer . refresh ( ) ; } } protected StyleRange prepareStyleRange ( StyleRange styleRange , boolean applyColors ) { if ( ! applyColors && styleRange . background != null ) { styleRange = super . prepareStyleRange ( styleRange , applyColors ) ; styleRange . borderStyle = SWT . BORDER_DOT ; return styleRange ; } return super . prepareStyleRange ( styleRange , applyColors ) ; } public static boolean showColoredLabels ( ) { return PlatformUI . getPreferenceStore ( ) . getBoolean ( IWorkbenchPreferenceConstants . USE_COLORED_LABELS ) ; } public void propertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( property . equals ( JFacePreferences . QUALIFIER_COLOR ) || property . equals ( JFacePreferences . COUNTER_COLOR ) || property . equals ( JFacePreferences . DECORATIONS_COLOR ) || property . equals ( HIGHLIGHT_BG_COLOR_NAME ) || property . equals ( IWorkbenchPreferenceConstants . USE_COLORED_LABELS ) ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { refresh ( ) ; } } ) ; } } public String getText ( Object element ) { return getStyledText ( element ) . getString ( ) ; } } package net . sf . sveditor . ui . svcp ; import net . sf . sveditor . core . db . SVDBAssign ; import net . sf . sveditor . core . db . SVDBConstraint ; import net . sf . sveditor . core . db . SVDBCovergroup ; import net . sf . sveditor . core . db . SVDBCoverpoint ; import net . sf . sveditor . core . db . SVDBCoverpointBins ; import net . sf . sveditor . core . db . SVDBCoverpointCross ; import net . sf . sveditor . core . db . SVDBGenerateBlock ; import net . sf . sveditor . core . db . SVDBInclude ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMacroDef ; import net . sf . sveditor . core . db . SVDBModIfcInstItem ; import net . sf . sveditor . core . db . SVDBProperty ; import net . sf . sveditor . core . db . SVDBSequence ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . SVDBTypeInfoEnum ; import net . sf . sveditor . core . db . stmt . SVDBAlwaysStmt ; import net . sf . sveditor . core . db . stmt . SVDBAssertStmt ; import net . sf . sveditor . core . db . stmt . SVDBImportItem ; import net . sf . sveditor . core . db . stmt . SVDBInitialStmt ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; public class SVDBDefaultContentFilter extends ViewerFilter { private boolean hide_assign_statements = true ; private boolean hide_always_statements = true ; private boolean hide_initial_blocks = true ; private boolean hide_generate_blocks = true ; private boolean hide_define_statements = true ; private boolean hide_variable_declarations = true ; private boolean hide_constraints = true ; private boolean hide_enum_typedefs = true ; private boolean hide_assertion_properties = true ; private boolean hide_cover_point_group_cross = true ; private boolean hide_task_functions = false ; private boolean hide_module_instances = false ; private boolean hide_include_files = false ; @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( element instanceof SVDBItem && ( ( ( SVDBItem ) element ) . getType ( ) == SVDBItemType . Marker ) ) { return false ; } else if ( ( hide_variable_declarations == true ) && ( ( element instanceof SVDBVarDeclItem ) ) ) { return false ; } else if ( ( hide_assign_statements == true ) && ( element instanceof SVDBAssign ) ) { return false ; } else if ( ( hide_always_statements == true ) && ( element instanceof SVDBAlwaysStmt ) ) { return false ; } else if ( ( hide_generate_blocks == true ) && ( element instanceof SVDBGenerateBlock ) ) { return false ; } else if ( ( hide_module_instances == true ) && ( element instanceof SVDBModIfcInstItem ) ) { return false ; } else if ( ( hide_initial_blocks == true ) && ( element instanceof SVDBInitialStmt ) ) { return false ; } else if ( ( hide_define_statements == true ) && ( element instanceof SVDBMacroDef ) ) { return false ; } else if ( ( hide_task_functions == true ) && ( ( element instanceof SVDBTask ) ) ) { return false ; } else if ( ( hide_assertion_properties == true ) && ( ( element instanceof SVDBSequence ) || ( element instanceof SVDBProperty ) || ( element instanceof SVDBAssertStmt ) ) ) { return false ; } else if ( ( hide_cover_point_group_cross == true ) && ( ( element instanceof SVDBCoverpoint ) || ( element instanceof SVDBCovergroup ) || ( element instanceof SVDBCoverpointCross ) || ( element instanceof SVDBCoverpointBins ) ) ) { return false ; } else if ( ( hide_enum_typedefs == true ) && ( ( element instanceof SVDBTypedefStmt ) || ( element instanceof SVDBTypeInfoEnum ) ) ) { return false ; } else if ( ( hide_constraints == true ) && ( element instanceof SVDBConstraint ) ) { return false ; } else if ( ( hide_include_files == true ) && ( ( element instanceof SVDBInclude ) || ( element instanceof SVDBImportItem ) ) ) { return false ; } return true ; } public boolean ToggleTaskFunctions ( ) { hide_task_functions = ! hide_task_functions ; return ( hide_task_functions ) ; } public boolean ToggleConstraints ( ) { hide_constraints = ! hide_constraints ; return ( hide_constraints ) ; } public boolean ToggleAssertionProperties ( ) { hide_assertion_properties = ! hide_assertion_properties ; return ( hide_assertion_properties ) ; } public boolean ToggleCoverPointGroupCross ( ) { hide_cover_point_group_cross = ! hide_cover_point_group_cross ; return ( hide_cover_point_group_cross ) ; } public boolean ToggleEnumTypedefs ( ) { hide_enum_typedefs = ! hide_enum_typedefs ; return ( hide_enum_typedefs ) ; } public boolean ToggleVariableDeclarations ( ) { hide_variable_declarations = ! hide_variable_declarations ; return ( hide_variable_declarations ) ; } public boolean ToggleAssignStatements ( ) { hide_assign_statements = ! hide_assign_statements ; return ( hide_assign_statements ) ; } public boolean ToggleAlwaysStatements ( ) { hide_always_statements = ! hide_always_statements ; return ( hide_always_statements ) ; } public boolean ToggleGenerateBlocks ( ) { hide_generate_blocks = ! hide_generate_blocks ; return ( hide_generate_blocks ) ; } public boolean ToggleModuleInstances ( ) { hide_module_instances = ! hide_module_instances ; return ( hide_module_instances ) ; } public boolean ToggleInitialBlocks ( ) { hide_initial_blocks = ! hide_initial_blocks ; return ( hide_initial_blocks ) ; } public boolean ToggleIncludeFiles ( ) { hide_include_files = ! hide_include_files ; return ( hide_include_files ) ; } public boolean ToggleDefineStatements ( ) { hide_define_statements = ! hide_define_statements ; return ( hide_define_statements ) ; } public void HideTaskFunctions ( boolean hide ) { hide_task_functions = hide ; } public void HideConstraints ( boolean hide ) { hide_constraints = hide ; } public void HideAssertionProperties ( boolean hide ) { hide_assertion_properties = hide ; } public void HideCoverPointGroupCross ( boolean hide ) { hide_cover_point_group_cross = hide ; } public void HideEnumTypedefs ( boolean hide ) { hide_enum_typedefs = hide ; } public void HideVariableDeclarations ( boolean hide ) { hide_variable_declarations = hide ; } public void HideAssignStatements ( boolean hide ) { hide_assign_statements = hide ; } public void HideAlwaysStatements ( boolean hide ) { hide_always_statements = hide ; } public void HideGenerateBlocks ( boolean hide ) { hide_generate_blocks = hide ; } public void HideModuleInstances ( boolean hide ) { hide_module_instances = hide ; } public void HideInitialBlocks ( boolean hide ) { hide_initial_blocks = hide ; } public void HideIncludeFiles ( boolean hide ) { hide_include_files = hide ; } public void HideDefineStatements ( boolean hide ) { hide_define_statements = hide ; } } package net . sf . sveditor . ui . editor ; public class SVIdentifierDetector { } package net . sf . sveditor . ui . editor ; import java . util . ResourceBundle ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . editors . text . TextEditorActionContributor ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . eclipse . ui . texteditor . RetargetTextEditorAction ; public class SVActionContributor extends TextEditorActionContributor { protected RetargetTextEditorAction fContentAssistProposal ; protected RetargetTextEditorAction fIndentAction ; protected RetargetTextEditorAction fOpenDeclarationAction ; protected RetargetTextEditorAction fOpenTypeAction ; protected RetargetTextEditorAction fFindReferencesAction ; protected RetargetTextEditorAction fOpenTypeHierarchyAction ; protected RetargetTextEditorAction fOpenObjectsAction ; protected RetargetTextEditorAction fOpenQuickObjectsAction ; protected RetargetTextEditorAction fAddBlockCommentAction ; protected RetargetTextEditorAction fRemoveBlockCommentAction ; protected RetargetTextEditorAction fToggleCommentAction ; protected RetargetTextEditorAction fNextWordAction ; protected RetargetTextEditorAction fPrevWordAction ; protected RetargetTextEditorAction fSelNextWordAction ; protected RetargetTextEditorAction fSelPrevWordAction ; protected MenuManager fSourceMenu ; public SVActionContributor ( ) { super ( ) ; ResourceBundle bundle = SVUiPlugin . getDefault ( ) . getResources ( ) ; fContentAssistProposal = new RetargetTextEditorAction ( bundle , "" ) ; fContentAssistProposal . setActionDefinitionId ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS ) ; fOpenDeclarationAction = new RetargetTextEditorAction ( bundle , "" ) ; fOpenDeclarationAction . setActionDefinitionId ( "" ) ; fFindReferencesAction = new RetargetTextEditorAction ( bundle , "" ) ; fFindReferencesAction . setActionDefinitionId ( "" ) ; fOpenTypeAction = new RetargetTextEditorAction ( bundle , "" ) ; fOpenTypeAction . setActionDefinitionId ( "" ) ; fOpenTypeHierarchyAction = new RetargetTextEditorAction ( bundle , "" ) ; fOpenTypeHierarchyAction . setActionDefinitionId ( "" ) ; fOpenObjectsAction = new RetargetTextEditorAction ( bundle , "" ) ; fOpenObjectsAction . setActionDefinitionId ( "" ) ; fOpenQuickObjectsAction = new RetargetTextEditorAction ( bundle , "" ) ; fOpenQuickObjectsAction . setActionDefinitionId ( "" ) ; fIndentAction = new RetargetTextEditorAction ( bundle , "" ) ; fIndentAction . setActionDefinitionId ( "" ) ; fAddBlockCommentAction = new RetargetTextEditorAction ( bundle , "" ) ; fAddBlockCommentAction . setActionDefinitionId ( "" ) ; fRemoveBlockCommentAction = new RetargetTextEditorAction ( bundle , "" ) ; fRemoveBlockCommentAction . setActionDefinitionId ( "" ) ; fToggleCommentAction = new RetargetTextEditorAction ( bundle , "" ) ; fToggleCommentAction . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; fNextWordAction = new RetargetTextEditorAction ( bundle , "" ) ; fNextWordAction . setActionDefinitionId ( ITextEditorActionDefinitionIds . WORD_NEXT ) ; fPrevWordAction = new RetargetTextEditorAction ( bundle , "" ) ; fPrevWordAction . setActionDefinitionId ( ITextEditorActionDefinitionIds . WORD_PREVIOUS ) ; fSelNextWordAction = new RetargetTextEditorAction ( bundle , "" ) ; fSelNextWordAction . setActionDefinitionId ( ITextEditorActionDefinitionIds . SELECT_WORD_NEXT ) ; fSelPrevWordAction = new RetargetTextEditorAction ( bundle , "" ) ; fSelPrevWordAction . setActionDefinitionId ( ITextEditorActionDefinitionIds . SELECT_WORD_PREVIOUS ) ; } public void contributeToMenu ( IMenuManager mm ) { IMenuManager editMenu = mm . findMenuUsingPath ( IWorkbenchActionConstants . M_EDIT ) ; if ( editMenu != null ) { editMenu . add ( new Separator ( ) ) ; editMenu . add ( fContentAssistProposal ) ; editMenu . add ( fOpenDeclarationAction ) ; editMenu . add ( fOpenTypeHierarchyAction ) ; editMenu . add ( fOpenTypeAction ) ; editMenu . add ( fOpenObjectsAction ) ; editMenu . add ( fOpenQuickObjectsAction ) ; editMenu . add ( fFindReferencesAction ) ; editMenu . add ( fIndentAction ) ; } } public void init ( IActionBars bars ) { super . init ( bars ) ; IMenuManager menuManager = bars . getMenuManager ( ) ; IMenuManager editMenu = menuManager . findMenuUsingPath ( IWorkbenchActionConstants . M_EDIT ) ; if ( editMenu != null ) { editMenu . add ( new Separator ( ) ) ; editMenu . add ( fContentAssistProposal ) ; editMenu . add ( fOpenDeclarationAction ) ; editMenu . add ( fOpenTypeAction ) ; editMenu . add ( fOpenTypeHierarchyAction ) ; editMenu . add ( fOpenQuickObjectsAction ) ; editMenu . add ( fOpenObjectsAction ) ; editMenu . add ( fFindReferencesAction ) ; editMenu . add ( fIndentAction ) ; } } private void doSetActiveEditor ( IEditorPart part ) { super . setActiveEditor ( part ) ; ITextEditor editor = null ; if ( part instanceof ITextEditor ) editor = ( ITextEditor ) part ; fContentAssistProposal . setAction ( getAction ( editor , "" ) ) ; fOpenDeclarationAction . setAction ( getAction ( editor , "" ) ) ; fOpenTypeAction . setAction ( getAction ( editor , "" ) ) ; fOpenTypeHierarchyAction . setAction ( getAction ( editor , "" ) ) ; fOpenObjectsAction . setAction ( getAction ( editor , "" ) ) ; fOpenQuickObjectsAction . setAction ( getAction ( editor , "" ) ) ; fFindReferencesAction . setAction ( getAction ( editor , "" ) ) ; fIndentAction . setAction ( getAction ( editor , "" ) ) ; fAddBlockCommentAction . setAction ( getAction ( editor , "" ) ) ; fRemoveBlockCommentAction . setAction ( getAction ( editor , "" ) ) ; fToggleCommentAction . setAction ( getAction ( editor , "" ) ) ; fNextWordAction . setAction ( getAction ( editor , "" ) ) ; fPrevWordAction . setAction ( getAction ( editor , "" ) ) ; fSelNextWordAction . setAction ( getAction ( editor , "" ) ) ; fSelPrevWordAction . setAction ( getAction ( editor , "" ) ) ; } public void setActiveEditor ( IEditorPart part ) { super . setActiveEditor ( part ) ; doSetActiveEditor ( part ) ; } public void dispose ( ) { doSetActiveEditor ( null ) ; super . dispose ( ) ; } } package net . sf . sveditor . ui . editor ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . filebuffers . IDocumentSetupParticipant ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . IDocumentPartitioner ; import org . eclipse . jface . text . rules . EndOfLineRule ; import org . eclipse . jface . text . rules . FastPartitioner ; import org . eclipse . jface . text . rules . IPartitionTokenScanner ; import org . eclipse . jface . text . rules . IPredicateRule ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . RuleBasedPartitionScanner ; import org . eclipse . jface . text . rules . Token ; public class SVDocumentSetupParticipant implements IDocumentSetupParticipant { public void setup ( IDocument doc ) { if ( doc instanceof IDocumentExtension3 ) { IDocumentExtension3 docExt = ( IDocumentExtension3 ) doc ; IDocumentPartitioner p = createPartitioner ( ) ; docExt . setDocumentPartitioner ( SVDocumentPartitions . SV_PARTITIONING , p ) ; p . connect ( doc ) ; } } public static IDocumentPartitioner createPartitioner ( ) { IDocumentPartitioner p = new FastPartitioner ( createScanner ( ) , SVDocumentPartitions . SV_PARTITION_TYPES ) ; return p ; } private static IPartitionTokenScanner createScanner ( ) { RuleBasedPartitionScanner scanner = new RuleBasedPartitionScanner ( ) ; IToken mlc = new Token ( SVDocumentPartitions . SV_MULTILINE_COMMENT ) ; IToken slc = new Token ( SVDocumentPartitions . SV_SINGLELINE_COMMENT ) ; List < IPredicateRule > rules = new ArrayList < IPredicateRule > ( ) ; rules . add ( new EndOfLineRule ( "" , slc ) ) ; rules . add ( new CCommentRule ( mlc ) ) ; IPredicateRule rulesArr [ ] = rules . toArray ( new IPredicateRule [ rules . size ( ) ] ) ; scanner . setDefaultReturnToken ( new Token ( IDocument . DEFAULT_CONTENT_TYPE ) ) ; scanner . setPredicateRules ( rulesArr ) ; return scanner ; } } package net . sf . sveditor . ui . editor ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . pref . SVEditorPrefsConstants ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultIndentLineAutoEditStrategy ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; public class SVAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy implements IPropertyChangeListener { private LogHandle fLog ; private boolean fAutoIndentEnabled ; public SVAutoIndentStrategy ( SVEditor editor , String p ) { fLog = LogFactory . getLogHandle ( "" ) ; fAutoIndentEnabled = SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_AUTO_INDENT_ENABLED_S ) ; } public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( SVEditorPrefsConstants . P_AUTO_INDENT_ENABLED_S ) ) { fAutoIndentEnabled = event . getNewValue ( ) . toString ( ) . equals ( "" ) ; } } private void indentPastedContent ( IDocument doc , DocumentCommand cmd ) { fLog . debug ( "" + cmd . offset + "" ) ; fLog . debug ( "" + cmd . text + "" ) ; try { int lineno = doc . getLineOfOffset ( cmd . offset ) ; int target_lineno = lineno ; if ( doc . getLineOffset ( lineno ) != cmd . offset ) { return ; } int line_cnt = , result_line_cnt = ; for ( int i = ; i < cmd . text . length ( ) ; i ++ ) { if ( cmd . text . charAt ( i ) == '' ) { line_cnt ++ ; } } if ( line_cnt == ) { return ; } if ( cmd . text . charAt ( cmd . text . length ( ) - ) != '' ) { line_cnt ++ ; } fLog . debug ( "" + lineno ) ; StringBuilder doc_str = new StringBuilder ( ) ; doc_str . append ( doc . get ( , cmd . offset ) ) ; doc_str . append ( cmd . text ) ; int start = cmd . offset + cmd . length ; int len = ( doc . getLength ( ) - ( cmd . offset + cmd . length ) - ) ; try { if ( len > ) { doc_str . append ( doc . get ( start , len ) ) ; } } catch ( BadLocationException e ) { System . out . println ( "" + start + "" + len + "" + doc . getLength ( ) ) ; throw e ; } StringBIDITextScanner text_scanner = new StringBIDITextScanner ( doc_str . toString ( ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; SVIndentScanner scanner = new SVIndentScanner ( text_scanner ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( target_lineno ) ; try { String result = indenter . indent ( lineno + , ( lineno + line_cnt ) ) ; for ( int i = ; i < result . length ( ) ; i ++ ) { if ( result . charAt ( i ) == '' ) { result_line_cnt ++ ; } } if ( result_line_cnt == line_cnt ) { cmd . text = result ; } } catch ( Exception e ) { } fLog . debug ( "" + lineno ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } } private void indentOnKeypress ( IDocument doc , DocumentCommand cmd ) { StringBuilder doc_str = new StringBuilder ( ) ; boolean indent_newline ; if ( cmd . text != null && isLineDelimiter ( doc , cmd . text ) ) { indent_newline = true ; } else if ( cmd . text . length ( ) == ) { indent_newline = false ; } else { if ( cmd . text . length ( ) > && cmd . text . trim ( ) . equals ( "" ) ) { String incr = SVUiPlugin . getDefault ( ) . getIndentIncr ( ) ; if ( ! incr . equals ( "" ) ) { int indent_len = incr . length ( ) ; if ( ( cmd . text . length ( ) % indent_len ) != ) { int new_mul = ( cmd . text . length ( ) / indent_len ) + ; String new_text = "" ; for ( int i = ; i < new_mul ; i ++ ) { new_text += incr ; } cmd . text = new_text ; } } } return ; } try { int target_lineno = doc . getLineOfOffset ( cmd . offset ) ; doc_str . append ( doc . get ( , cmd . offset ) ) ; doc_str . append ( cmd . text ) ; if ( indent_newline ) { doc_str . append ( "" ) ; } if ( doc . getLength ( ) > ( cmd . offset + cmd . length ) ) { doc_str . append ( doc . get ( cmd . offset + cmd . length , ( doc . getLength ( ) - ( cmd . offset + cmd . length ) - ) ) ) ; } StringBIDITextScanner text_scanner = new StringBIDITextScanner ( doc_str . toString ( ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; SVIndentScanner scanner = new SVIndentScanner ( text_scanner ) ; indenter . setIndentIncr ( SVUiPlugin . getDefault ( ) . getIndentIncr ( ) ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndent ( true ) ; if ( cmd . text . equals ( "" ) ) { target_lineno ++ ; } indenter . setAdaptiveIndentEnd ( target_lineno ) ; indenter . indent ( ) ; IRegion cmd_line = doc . getLineInformationOfOffset ( cmd . offset ) ; String indent = null ; if ( indent_newline ) { indent = indenter . getLineIndent ( doc . getLineOfOffset ( cmd . offset ) + ) ; } else { indent = indenter . getLineIndent ( doc . getLineOfOffset ( cmd . offset ) + ) ; } if ( indent != null ) { if ( indent_newline ) { cmd . text += indent ; int idx = cmd . offset ; while ( idx < doc . getLength ( ) && ( doc . getChar ( idx ) != '' && doc . getChar ( idx ) != '' ) && Character . isWhitespace ( doc . getChar ( idx ) ) ) { cmd . length ++ ; idx ++ ; } } else { int n_ws_chars = ; while ( ( cmd_line . getOffset ( ) + n_ws_chars ) < doc . getLength ( ) && Character . isWhitespace ( doc . getChar ( cmd_line . getOffset ( ) + n_ws_chars ) ) && doc . getChar ( cmd_line . getOffset ( ) + n_ws_chars ) != '' ) { n_ws_chars ++ ; } if ( cmd . text . equals ( "" ) && ( indent . length ( ) < n_ws_chars ) ) { doc . replace ( cmd_line . getOffset ( ) , n_ws_chars , indent ) ; cmd . offset += ( indent . length ( ) - n_ws_chars ) ; } else { int idx = cmd . offset - , c ; doc_str . setLength ( ) ; doc_str . append ( cmd . text ) ; while ( idx >= ) { c = doc . getChar ( idx ) ; if ( ! Character . isWhitespace ( c ) ) { doc_str . append ( ( char ) c ) ; idx -- ; } else { break ; } } doc_str . reverse ( ) ; if ( ( doc_str . toString ( ) . startsWith ( "" ) || doc_str . toString ( ) . equals ( "" ) || doc_str . toString ( ) . equals ( "" ) || doc_str . toString ( ) . equals ( "" ) || doc_str . toString ( ) . equals ( "" ) ) && ( indent . length ( ) < n_ws_chars ) ) { doc . replace ( cmd_line . getOffset ( ) , n_ws_chars , indent ) ; cmd . offset += ( indent . length ( ) - n_ws_chars ) ; } } } } } catch ( BadLocationException e ) { fLog . error ( "" , e ) ; } } public void customizeDocumentCommand ( IDocument doc , DocumentCommand cmd ) { if ( ! fAutoIndentEnabled ) { return ; } if ( cmd . length == && cmd . text . trim ( ) . length ( ) <= ) { indentOnKeypress ( doc , cmd ) ; } else if ( cmd . text . length ( ) > ) { indentPastedContent ( doc , cmd ) ; } } private boolean isLineDelimiter ( IDocument document , String text ) { String [ ] delimiters = document . getLegalLineDelimiters ( ) ; if ( delimiters != null ) { return TextUtilities . equals ( delimiters , text ) > - ; } return false ; } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultIndentLineAutoEditStrategy ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextUtilities ; public class SVMultiLineCommentAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { private final String fPartitioning ; public SVMultiLineCommentAutoIndentStrategy ( String partitioning ) { fPartitioning = partitioning ; } private IRegion findPrefixRange ( IDocument doc , IRegion line ) throws BadLocationException { int lineOffset = line . getOffset ( ) ; int lineEnd = lineOffset + line . getLength ( ) ; int indentEnd = findEndOfWhiteSpace ( doc , lineOffset , lineEnd ) ; if ( ( indentEnd < lineEnd ) && ( doc . getChar ( indentEnd ) == '' ) ) { indentEnd ++ ; while ( ( indentEnd < lineEnd ) && Character . isWhitespace ( doc . getChar ( indentEnd ) ) ) { indentEnd ++ ; } } return new Region ( lineOffset , indentEnd - lineOffset ) ; } private boolean isCommentClosed ( IDocument doc , int offset ) { try { if ( ( doc . getLineOfOffset ( offset ) + ) >= doc . getNumberOfLines ( ) ) { return false ; } IRegion line = doc . getLineInformation ( doc . getLineOfOffset ( offset ) + ) ; ITypedRegion partition = TextUtilities . getPartition ( doc , fPartitioning , offset , false ) ; int partitionEnd = partition . getOffset ( ) + partition . getLength ( ) ; if ( line . getOffset ( ) >= partitionEnd ) { return true ; } if ( doc . getLength ( ) == partitionEnd ) { return false ; } String comment = doc . get ( partition . getOffset ( ) , partition . getLength ( ) ) ; if ( comment . indexOf ( "" , ) != - ) { return false ; } return true ; } catch ( BadLocationException e ) { return true ; } } private void addIndentAndContinueComment ( IDocument doc , DocumentCommand cmd ) { int offset = cmd . offset ; if ( ( offset == - ) || ( doc . getLength ( ) == ) ) { return ; } try { IRegion line = doc . getLineInformationOfOffset ( ( offset == doc . getLength ( ) ) ? ( offset - ) : offset ) ; int lineOffset = line . getOffset ( ) ; int firstNonWS = findEndOfWhiteSpace ( doc , lineOffset , offset ) ; StringBuilder buf = new StringBuilder ( cmd . text ) ; IRegion prefix = findPrefixRange ( doc , line ) ; String indent = doc . get ( prefix . getOffset ( ) , prefix . getLength ( ) ) ; int lenToAdd = Math . min ( offset - prefix . getOffset ( ) , prefix . getLength ( ) ) ; buf . append ( indent . substring ( , lenToAdd ) ) ; if ( firstNonWS < offset ) { if ( doc . getChar ( firstNonWS ) == '' ) { buf . append ( "" ) ; } } if ( ! isCommentClosed ( doc , offset ) ) { cmd . shiftsCaret = false ; cmd . caretOffset = cmd . offset + buf . length ( ) ; String lineDelimiter = TextUtilities . getDefaultLineDelimiter ( doc ) ; String endTag = lineDelimiter + indent + "" ; buf . append ( endTag ) ; } if ( lenToAdd < prefix . getLength ( ) ) { cmd . caretOffset = offset + prefix . getLength ( ) - lenToAdd ; } cmd . text = buf . toString ( ) ; } catch ( BadLocationException e ) { } } public void customizeDocumentCommand ( IDocument doc , DocumentCommand cmd ) { if ( cmd . text != null ) { if ( cmd . length == && cmd . text . length ( ) == ) { String [ ] lineDelimiters = doc . getLegalLineDelimiters ( ) ; int index = TextUtilities . endsWith ( lineDelimiters , cmd . text ) ; if ( ( index >= ) && lineDelimiters [ index ] . equals ( cmd . text ) ) { addIndentAndContinueComment ( doc , cmd ) ; } } } } } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OpenQuickHierarchyAction extends TextEditorAction { private SVEditor fEditor ; public OpenQuickHierarchyAction ( ResourceBundle bundle , SVEditor editor ) { super ( bundle , "" , editor ) ; fEditor = editor ; } @ Override public void run ( ) { fEditor . getQuickHierarchyPresenter ( ) . showInformation ( ) ; } ; } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . index . SVDBDeclCacheItem ; import net . sf . sveditor . ui . SVEditorUtil ; import net . sf . sveditor . ui . dialog . types . SVOpenTypeDialog ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OpenTypeAction extends TextEditorAction { private SVEditor fEditor ; public OpenTypeAction ( ResourceBundle bundle , SVEditor editor ) { super ( bundle , "" , editor ) ; fEditor = editor ; } @ Override public void run ( ) { Shell shell = fEditor . getSite ( ) . getWorkbenchWindow ( ) . getShell ( ) ; SVOpenTypeDialog dlg = new SVOpenTypeDialog ( fEditor . getIndexIterator ( ) , shell ) ; if ( dlg . open ( ) == Window . OK ) { Object sel = dlg . getFirstResult ( ) ; if ( sel instanceof SVDBDeclCacheItem ) { SVDBDeclCacheItem ci = ( SVDBDeclCacheItem ) sel ; ISVDBItemBase item = ci . getSVDBItem ( ) ; try { SVEditorUtil . openEditor ( item ) ; } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } } } } package net . sf . sveditor . ui . editor . actions ; import java . util . List ; import java . util . Set ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemBase ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . srcgen . OverrideMethodsFinder ; import net . sf . sveditor . ui . svcp . SVDBDecoratingLabelProvider ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTreeViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . CheckedTreeSelectionDialog ; public class OverrideMethodsDialog extends CheckedTreeSelectionDialog { private SVDBClassDecl fLeafClass ; private CheckboxTreeViewer fCheckboxTree ; public OverrideMethodsDialog ( Shell parent , SVDBClassDecl leaf_class , ISVDBIndexIterator index_it ) { super ( parent , new SVDBDecoratingLabelProvider ( new SVTreeLabelProvider ( ) ) , new OverrideMethodsContentProvider ( leaf_class , index_it ) ) ; fLeafClass = leaf_class ; setInput ( fLeafClass ) ; updateOKStatus ( ) ; } @ Override protected CheckboxTreeViewer createTreeViewer ( Composite parent ) { fCheckboxTree = super . createTreeViewer ( parent ) ; fCheckboxTree . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { Object elem = event . getElement ( ) ; if ( elem instanceof SVDBClassDecl ) { ITreeContentProvider cp = ( ITreeContentProvider ) fCheckboxTree . getContentProvider ( ) ; boolean any_checked = false ; for ( Object c : cp . getChildren ( event . getElement ( ) ) ) { if ( fCheckboxTree . getChecked ( c ) ) { any_checked = true ; break ; } } if ( any_checked ) { for ( Object c : cp . getChildren ( event . getElement ( ) ) ) { fCheckboxTree . setChecked ( c , false ) ; } fCheckboxTree . setChecked ( event . getElement ( ) , false ) ; } else { for ( Object c : cp . getChildren ( event . getElement ( ) ) ) { fCheckboxTree . setChecked ( c , true ) ; } fCheckboxTree . setChecked ( event . getElement ( ) , true ) ; } } else { ITreeContentProvider cp = ( ITreeContentProvider ) fCheckboxTree . getContentProvider ( ) ; Object parent_o = cp . getParent ( elem ) ; if ( parent_o != null && parent_o instanceof SVDBClassDecl ) { } } } } ) ; fCheckboxTree . setSorter ( new OverrideMethodsSorter ( ) ) ; return fCheckboxTree ; } private static class OverrideMethodsContentProvider implements ITreeContentProvider { private Object fEmptyList [ ] = new Object [ ] ; OverrideMethodsFinder fMethodsFinder ; private SVDBClassDecl fLeafClass ; public OverrideMethodsContentProvider ( SVDBClassDecl leaf_class , ISVDBIndexIterator index_it ) { fLeafClass = leaf_class ; fMethodsFinder = new OverrideMethodsFinder ( leaf_class , index_it ) ; } public Object [ ] getElements ( Object inputElement ) { Set < SVDBClassDecl > cls_set = fMethodsFinder . getClassSet ( ) ; return cls_set . toArray ( ) ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof SVDBClassDecl ) { List < SVDBTask > methods = fMethodsFinder . getMethods ( ( SVDBClassDecl ) parentElement ) ; if ( methods == null ) { if ( parentElement == fLeafClass ) { return fMethodsFinder . getClassSet ( ) . toArray ( ) ; } System . out . println ( "" + SVDBItem . getName ( ( SVDBItemBase ) parentElement ) + "" ) ; System . out . println ( "" + SVDBItem . getName ( fLeafClass ) ) ; return fEmptyList ; } else { return methods . toArray ( ) ; } } else { return fEmptyList ; } } public Object getParent ( Object element ) { return ( ( SVDBItem ) element ) . getParent ( ) ; } public boolean hasChildren ( Object element ) { return ( getChildren ( element ) . length > ) ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } } private static class OverrideMethodsSorter extends ViewerSorter { @ Override public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( e1 instanceof SVDBClassDecl ) { SVDBClassDecl c1 = ( SVDBClassDecl ) e1 ; SVDBClassDecl c2 = ( SVDBClassDecl ) e2 ; if ( c1 . getSuperClass ( ) != null && c1 . getSuperClass ( ) . equals ( c2 . getSuperClass ( ) ) ) { return ; } else { return - ; } } else if ( e1 instanceof SVDBTask ) { SVDBTask f1 = ( SVDBTask ) e1 ; SVDBTask f2 = ( SVDBTask ) e2 ; int a1 = , a2 = , ret ; if ( ( f1 . getAttr ( ) & SVDBTask . FieldAttr_Protected ) != ) { a1 += ; } else { a1 -= ; } if ( ( f2 . getAttr ( ) & SVDBTask . FieldAttr_Protected ) != ) { a2 += ; } else { a2 -= ; } ret = f1 . getName ( ) . compareTo ( f2 . getName ( ) ) ; ret += ( a1 - a2 ) ; return ret ; } else { return super . compare ( viewer , e1 , e2 ) ; } } } } package net . sf . sveditor . ui . editor . actions ; import java . lang . reflect . InvocationTargetException ; import java . util . ResourceBundle ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModuleDecl ; import net . sf . sveditor . core . db . SVDBPackageDecl ; import net . sf . sveditor . core . diagrams . ClassDiagModelFactory ; import net . sf . sveditor . core . diagrams . DiagModel ; import net . sf . sveditor . core . diagrams . IDiagModelFactory ; import net . sf . sveditor . core . diagrams . ModuleDiagModelFactory ; import net . sf . sveditor . core . diagrams . PackageClassDiagModelFactory ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . views . diagram . SVDiagramView ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OpenDiagForSelectionAction extends TextEditorAction { private IWorkbench fWorkbench ; private SVEditor fEditor ; public OpenDiagForSelectionAction ( ResourceBundle bundle , SVEditor editor ) { super ( bundle , "" , editor ) ; fEditor = editor ; fWorkbench = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getWorkbench ( ) ; } @ Override public void run ( ) { try { fWorkbench . getProgressService ( ) . run ( false , false , fOpenDiagForSelection ) ; } catch ( InvocationTargetException e ) { } catch ( InterruptedException e ) { } } private IRunnableWithProgress fOpenDiagForSelection = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { monitor . beginTask ( "" , ) ; monitor . worked ( ) ; ISVDBItemBase itemBase = SelectionConverter . getElementAtOffset ( fEditor ) ; if ( itemBase != null && ( itemBase . getType ( ) == SVDBItemType . ClassDecl || itemBase . getType ( ) == SVDBItemType . PackageDecl || itemBase . getType ( ) == SVDBItemType . ModuleDecl ) ) { try { IWorkbench workbench = PlatformUI . getWorkbench ( ) ; IWorkbenchPage page = workbench . getActiveWorkbenchWindow ( ) . getActivePage ( ) ; IViewPart view ; if ( ( view = page . findView ( SVUiPlugin . PLUGIN_ID + "" ) ) == null ) { view = page . showView ( SVUiPlugin . PLUGIN_ID + "" ) ; } IDiagModelFactory factory = null ; if ( itemBase . getType ( ) == SVDBItemType . ClassDecl ) { factory = new ClassDiagModelFactory ( fEditor . getSVDBIndex ( ) , ( SVDBClassDecl ) itemBase ) ; } else if ( itemBase . getType ( ) == SVDBItemType . PackageDecl ) { factory = new PackageClassDiagModelFactory ( fEditor . getSVDBIndex ( ) , ( SVDBPackageDecl ) itemBase ) ; } else if ( itemBase . getType ( ) == SVDBItemType . ModuleDecl ) { factory = new ModuleDiagModelFactory ( fEditor . getSVDBIndex ( ) , ( SVDBModuleDecl ) itemBase ) ; } if ( factory != null ) { DiagModel model = factory . build ( ) ; page . activate ( view ) ; ( ( SVDiagramView ) view ) . setViewState ( IWorkbenchPage . STATE_MAXIMIZED ) ; ( ( SVDiagramView ) view ) . setTarget ( model , factory , fEditor . getSVDBIndex ( ) ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } monitor . done ( ) ; } } ; } package net . sf . sveditor . ui . editor . actions ; import java . lang . reflect . InvocationTargetException ; import java . util . ResourceBundle ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . ResourceAction ; public class OpenObjectsViewAction extends ResourceAction { private IWorkbench fWorkbench ; public OpenObjectsViewAction ( ResourceBundle bundle ) { super ( bundle , "" ) ; fWorkbench = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getWorkbench ( ) ; } @ Override public void run ( ) { try { fWorkbench . getProgressService ( ) . run ( false , false , fOpenObjects ) ; } catch ( InvocationTargetException e ) { } catch ( InterruptedException e ) { } } private IRunnableWithProgress fOpenObjects = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { monitor . beginTask ( "" , ) ; monitor . worked ( ) ; try { IWorkbench workbench = PlatformUI . getWorkbench ( ) ; IWorkbenchPage page = workbench . getActiveWorkbenchWindow ( ) . getActivePage ( ) ; IViewPart view ; if ( ( view = page . findView ( SVUiPlugin . PLUGIN_ID + "" ) ) == null ) { view = page . showView ( SVUiPlugin . PLUGIN_ID + "" ) ; } page . activate ( view ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } monitor . done ( ) ; } } ; } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; public class FindReferencesAction extends TextEditorAction { private SVEditor fEditor ; private LogHandle fLog ; private boolean fDebugEn = true ; public FindReferencesAction ( ResourceBundle bundle , SVEditor editor ) { super ( bundle , "" , editor ) ; fLog = LogFactory . getLogHandle ( "" ) ; fEditor = editor ; update ( ) ; } @ Override public void run ( ) { System . out . println ( "" ) ; super . run ( ) ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . search . SVDBFindNamedModIfcClassIfc ; import net . sf . sveditor . core . db . search . SVDBFindNamedPackage ; import net . sf . sveditor . core . expr_utils . SVExprContext ; import net . sf . sveditor . core . expr_utils . SVExprScanner ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . scanutils . SVDocumentTextScanner ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelection ; public class SelectionConverter { private SelectionConverter ( ) { } public static ISVDBItemBase getElementAtOffset ( SVEditor editor ) { ITextSelection sel = null ; ISelection sel_o = editor . getSelectionProvider ( ) . getSelection ( ) ; if ( sel_o != null && sel_o instanceof ITextSelection ) { sel = ( ITextSelection ) sel_o ; } if ( sel == null ) { return null ; } int offset = sel . getOffset ( ) + sel . getLength ( ) ; return getElementAt ( editor , offset ) ; } public static ISVDBItemBase getElementAt ( SVEditor editor , int offset ) { IDocument doc = editor . getDocumentProvider ( ) . getDocument ( editor . getEditorInput ( ) ) ; SVDocumentTextScanner scanner = new SVDocumentTextScanner ( doc , offset ) ; SVExprScanner expr_scanner = new SVExprScanner ( ) ; SVExprContext expr_ctxt = expr_scanner . extractExprContext ( scanner , true ) ; if ( expr_ctxt . fLeaf != null && ( expr_ctxt . fTrigger == null || expr_ctxt . fTrigger . equals ( "" ) ) ) { List < ISVDBChildItem > found ; SVDBFindNamedPackage findNamedPkg = new SVDBFindNamedPackage ( editor . getIndexIterator ( ) ) ; found = findNamedPkg . find ( expr_ctxt . fLeaf ) ; ISVDBItemBase pkg = ( found != null && found . size ( ) > ) ? found . get ( ) : null ; if ( pkg != null ) { return pkg ; } SVDBFindNamedModIfcClassIfc finder_c = new SVDBFindNamedModIfcClassIfc ( editor . getIndexIterator ( ) ) ; found = finder_c . find ( expr_ctxt . fLeaf ) ; ISVDBItemBase cls = ( found != null && found . size ( ) > ) ? found . get ( ) : null ; if ( cls == null ) { return null ; } else { return cls ; } } return null ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OpenQuickOutlineAction extends TextEditorAction { private SVEditor fEditor ; public OpenQuickOutlineAction ( ResourceBundle bundle , SVEditor editor ) { super ( bundle , "" , editor ) ; fEditor = editor ; } public void run ( ) { fEditor . getQuickOutlinePresenter ( ) . showInformation ( ) ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . HashMap ; import java . util . Map ; import java . util . ResourceBundle ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . ResourceAction ; import org . eclipse . ui . texteditor . TextEditorAction ; public class ToggleCommentAction extends TextEditorAction { private ITextOperationTarget fOperationTarget ; private String fDocumentPartitioning ; private Map < String , String [ ] > fPrefixesMap ; public ToggleCommentAction ( ResourceBundle bundle , String prefix , ITextEditor editor ) { super ( bundle , prefix , editor ) ; } public void run ( ) { if ( fOperationTarget == null || fDocumentPartitioning == null || fPrefixesMap == null ) return ; ITextEditor editor = getTextEditor ( ) ; if ( editor == null ) return ; if ( ! validateEditorInputState ( ) ) return ; final int operationCode ; if ( isSelectionCommented ( editor . getSelectionProvider ( ) . getSelection ( ) ) ) operationCode = ITextOperationTarget . STRIP_PREFIX ; else operationCode = ITextOperationTarget . PREFIX ; Shell shell = editor . getSite ( ) . getShell ( ) ; if ( ! fOperationTarget . canDoOperation ( operationCode ) ) { if ( shell != null ) MessageDialog . openError ( shell , "" , "" ) ; return ; } Display display = null ; if ( shell != null && ! shell . isDisposed ( ) ) display = shell . getDisplay ( ) ; BusyIndicator . showWhile ( display , new Runnable ( ) { public void run ( ) { fOperationTarget . doOperation ( operationCode ) ; } } ) ; } private boolean isSelectionCommented ( ISelection selection ) { if ( ! ( selection instanceof ITextSelection ) ) return false ; ITextSelection textSelection = ( ITextSelection ) selection ; if ( textSelection . getStartLine ( ) < || textSelection . getEndLine ( ) < ) return false ; IDocument document = getTextEditor ( ) . getDocumentProvider ( ) . getDocument ( getTextEditor ( ) . getEditorInput ( ) ) ; try { IRegion block = getTextBlockFromSelection ( textSelection , document ) ; ITypedRegion [ ] regions = TextUtilities . computePartitioning ( document , fDocumentPartitioning , block . getOffset ( ) , block . getLength ( ) , false ) ; int [ ] lines = new int [ regions . length * ] ; for ( int i = , j = ; i < regions . length ; i ++ , j += ) { lines [ j ] = getFirstCompleteLineOfRegion ( regions [ i ] , document ) ; int length = regions [ i ] . getLength ( ) ; int offset = regions [ i ] . getOffset ( ) + length ; if ( length > ) offset -- ; lines [ j + ] = ( lines [ j ] == - ? - : document . getLineOfOffset ( offset ) ) ; assert i < regions . length ; assert j < regions . length * ; } for ( int i = , j = ; i < regions . length ; i ++ , j += ) { String [ ] prefixes = ( String [ ] ) fPrefixesMap . get ( regions [ i ] . getType ( ) ) ; if ( prefixes != null && prefixes . length > && lines [ j ] >= && lines [ j + ] >= ) if ( ! isBlockCommented ( lines [ j ] , lines [ j + ] , prefixes , document ) ) return false ; } return true ; } catch ( BadLocationException x ) { x . printStackTrace ( ) ; } return false ; } private IRegion getTextBlockFromSelection ( ITextSelection selection , IDocument document ) { try { IRegion line = document . getLineInformationOfOffset ( selection . getOffset ( ) ) ; int length = selection . getLength ( ) == ? line . getLength ( ) : selection . getLength ( ) + ( selection . getOffset ( ) - line . getOffset ( ) ) ; return new Region ( line . getOffset ( ) , length ) ; } catch ( BadLocationException x ) { x . printStackTrace ( ) ; } return null ; } private int getFirstCompleteLineOfRegion ( IRegion region , IDocument document ) { try { int startLine = document . getLineOfOffset ( region . getOffset ( ) ) ; int offset = document . getLineOffset ( startLine ) ; if ( offset >= region . getOffset ( ) ) return startLine ; offset = document . getLineOffset ( startLine + ) ; return ( offset > region . getOffset ( ) + region . getLength ( ) ? - : startLine + ) ; } catch ( BadLocationException x ) { x . printStackTrace ( ) ; } return - ; } private boolean isBlockCommented ( int startLine , int endLine , String [ ] prefixes , IDocument document ) { try { for ( int i = startLine ; i <= endLine ; i ++ ) { IRegion line = document . getLineInformation ( i ) ; String text = document . get ( line . getOffset ( ) , line . getLength ( ) ) ; int [ ] found = TextUtilities . indexOf ( prefixes , text , ) ; if ( found [ ] == - ) return false ; String s = document . get ( line . getOffset ( ) , found [ ] ) ; s = s . trim ( ) ; if ( s . length ( ) != ) return false ; } return true ; } catch ( BadLocationException x ) { x . printStackTrace ( ) ; } return false ; } public void update ( ) { super . update ( ) ; if ( ! canModifyEditor ( ) ) { setEnabled ( false ) ; return ; } ITextEditor editor = getTextEditor ( ) ; if ( fOperationTarget == null && editor != null ) fOperationTarget = ( ITextOperationTarget ) editor . getAdapter ( ITextOperationTarget . class ) ; boolean isEnabled = ( fOperationTarget != null && fOperationTarget . canDoOperation ( ITextOperationTarget . PREFIX ) && fOperationTarget . canDoOperation ( ITextOperationTarget . STRIP_PREFIX ) ) ; setEnabled ( isEnabled ) ; } public void setEditor ( ITextEditor editor ) { super . setEditor ( editor ) ; fOperationTarget = null ; } public void configure ( ISourceViewer sourceViewer , SourceViewerConfiguration configuration ) { fPrefixesMap = null ; String [ ] types = configuration . getConfiguredContentTypes ( sourceViewer ) ; Map < String , String [ ] > prefixesMap = new HashMap < String , String [ ] > ( types . length ) ; for ( int i = ; i < types . length ; i ++ ) { String type = types [ i ] ; String [ ] prefixes = configuration . getDefaultPrefixes ( sourceViewer , type ) ; if ( prefixes != null && prefixes . length > ) { int emptyPrefixes = ; for ( int j = ; j < prefixes . length ; j ++ ) if ( prefixes [ j ] . length ( ) == ) emptyPrefixes ++ ; if ( emptyPrefixes > ) { String [ ] nonemptyPrefixes = new String [ prefixes . length - emptyPrefixes ] ; for ( int j = , k = ; j < prefixes . length ; j ++ ) { String prefix = prefixes [ j ] ; if ( prefix . length ( ) != ) { nonemptyPrefixes [ k ] = prefix ; k ++ ; } } prefixes = nonemptyPrefixes ; } prefixesMap . put ( type , prefixes ) ; } } fDocumentPartitioning = configuration . getConfiguredDocumentPartitioning ( sourceViewer ) ; fPrefixesMap = prefixesMap ; } } package net . sf . sveditor . ui . editor . actions ; import java . lang . reflect . InvocationTargetException ; import java . util . List ; import java . util . ResourceBundle ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . search . SVDBFindNamedModIfcClassIfc ; import net . sf . sveditor . core . expr_utils . SVExprContext ; import net . sf . sveditor . core . expr_utils . SVExprScanner ; import net . sf . sveditor . core . hierarchy . ClassHierarchyTreeFactory ; import net . sf . sveditor . core . hierarchy . HierarchyTreeNode ; import net . sf . sveditor . core . hierarchy . ModuleHierarchyTreeFactory ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . scanutils . SVDocumentTextScanner ; import net . sf . sveditor . ui . views . hierarchy . SVHierarchyView ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OpenTypeHierarchyAction extends TextEditorAction { private IWorkbench fWorkbench ; private SVDocumentTextScanner fScanner ; public OpenTypeHierarchyAction ( ResourceBundle bundle , SVEditor editor ) { super ( bundle , "" , editor ) ; fWorkbench = editor . getEditorSite ( ) . getWorkbenchWindow ( ) . getWorkbench ( ) ; } @ Override public void run ( ) { IDocument doc = getTextEditor ( ) . getDocumentProvider ( ) . getDocument ( getTextEditor ( ) . getEditorInput ( ) ) ; ITextSelection sel = getTextSel ( ) ; int offset = sel . getOffset ( ) + sel . getLength ( ) ; fScanner = new SVDocumentTextScanner ( doc , offset ) ; try { fWorkbench . getProgressService ( ) . run ( false , false , fOpenHierarchy ) ; } catch ( InvocationTargetException e ) { } catch ( InterruptedException e ) { } } private IRunnableWithProgress fOpenHierarchy = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { monitor . beginTask ( "" , ) ; SVExprScanner expr_scanner = new SVExprScanner ( ) ; SVExprContext expr_ctxt = expr_scanner . extractExprContext ( fScanner , true ) ; monitor . worked ( ) ; if ( expr_ctxt . fLeaf != null && ( expr_ctxt . fTrigger == null || expr_ctxt . fTrigger . equals ( "" ) ) ) { SVDBFindNamedModIfcClassIfc finder_c = new SVDBFindNamedModIfcClassIfc ( ( ( SVEditor ) getTextEditor ( ) ) . getIndexIterator ( ) ) ; List < ISVDBChildItem > result = finder_c . find ( expr_ctxt . fLeaf ) ; ISVDBItemBase cls = ( result != null && result . size ( ) > ) ? result . get ( ) : null ; monitor . worked ( ) ; if ( cls != null ) { HierarchyTreeNode target = null ; if ( cls . getType ( ) == SVDBItemType . ClassDecl ) { ClassHierarchyTreeFactory factory = new ClassHierarchyTreeFactory ( ( ( SVEditor ) getTextEditor ( ) ) . getIndexIterator ( ) ) ; target = factory . build ( ( SVDBClassDecl ) cls ) ; } else if ( cls . getType ( ) == SVDBItemType . ModuleDecl ) { ModuleHierarchyTreeFactory factory = new ModuleHierarchyTreeFactory ( ( ( SVEditor ) getTextEditor ( ) ) . getIndexIterator ( ) ) ; target = factory . build ( ( SVDBModIfcDecl ) cls ) ; } monitor . worked ( ) ; if ( target != null ) { try { IWorkbench workbench = PlatformUI . getWorkbench ( ) ; IWorkbenchPage page = workbench . getActiveWorkbenchWindow ( ) . getActivePage ( ) ; IViewPart view ; if ( ( view = page . findView ( SVUiPlugin . PLUGIN_ID + "" ) ) == null ) { view = page . showView ( SVUiPlugin . PLUGIN_ID + "" ) ; } page . activate ( view ) ; ( ( SVHierarchyView ) view ) . setTarget ( target ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } monitor . done ( ) ; } } ; private ITextSelection getTextSel ( ) { ITextSelection sel = null ; if ( getTextEditor ( ) != null ) { ISelection sel_o = getTextEditor ( ) . getSelectionProvider ( ) . getSelection ( ) ; if ( sel_o != null && sel_o instanceof ITextSelection ) { sel = ( ITextSelection ) sel_o ; } } return sel ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . graphics . Point ; import org . eclipse . ui . texteditor . TextEditorAction ; public class SelPrevWordAction extends TextEditorAction { private SVEditor fEditor ; public SelPrevWordAction ( ResourceBundle bundle , String prefix , SVEditor editor ) { super ( bundle , prefix , editor ) ; fEditor = editor ; } @ Override public void run ( ) { ISourceViewer sv = fEditor . sourceViewer ( ) ; StyledText text = fEditor . sourceViewer ( ) . getTextWidget ( ) ; int offset = text . getCaretOffset ( ) ; int start_offset = offset ; if ( text . getSelection ( ) != null ) { Point sel = text . getSelection ( ) ; if ( sel . x == offset ) { start_offset = sel . y ; } else if ( sel . y == offset ) { start_offset = sel . x ; } } String str = text . getText ( ) ; offset -- ; if ( offset < ) { return ; } int ch = str . charAt ( offset ) ; if ( SVCharacter . isSVIdentifierPart ( ch ) ) { while ( offset >= ) { ch = str . charAt ( offset ) ; if ( ! SVCharacter . isSVIdentifierPart ( ch ) ) { break ; } offset -- ; } } else if ( Character . isWhitespace ( ch ) ) { while ( offset >= ) { ch = str . charAt ( offset ) ; if ( ! Character . isWhitespace ( ch ) ) { break ; } offset -- ; } } else { offset -- ; } if ( offset < ) { offset = ; } offset ++ ; sv . setSelectedRange ( start_offset , offset - start_offset ) ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . ui . texteditor . TextEditorAction ; public class NextWordAction extends TextEditorAction { private SVEditor fEditor ; public NextWordAction ( ResourceBundle bundle , String prefix , SVEditor editor ) { super ( bundle , prefix , editor ) ; fEditor = editor ; } @ Override public void run ( ) { StyledText text = fEditor . sourceViewer ( ) . getTextWidget ( ) ; int offset = text . getCaretOffset ( ) ; String str = text . getText ( ) ; int len = str . length ( ) ; int ch = str . charAt ( offset ) ; if ( SVCharacter . isSVIdentifierPart ( ch ) ) { while ( offset < len ) { ch = str . charAt ( offset ) ; if ( ! SVCharacter . isSVIdentifierPart ( ch ) ) { break ; } offset ++ ; } } else { while ( offset < len ) { ch = str . charAt ( offset ) ; if ( SVCharacter . isSVIdentifierPart ( ch ) ) { break ; } offset ++ ; } } if ( offset >= len ) { offset = len - ; } text . setCaretOffset ( offset ) ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . ArrayList ; import java . util . List ; import java . util . ResourceBundle ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OverrideTaskFuncAction extends TextEditorAction implements IOverrideMethodsTargetProvider { private OverrideTaskFuncImpl fImpl ; private SVEditor fEditor ; public OverrideTaskFuncAction ( ResourceBundle bundle , String prefix , SVEditor editor ) { super ( bundle , prefix , editor ) ; fImpl = new OverrideTaskFuncImpl ( editor , this ) ; fEditor = editor ; update ( ) ; } @ Override public void run ( ) { super . run ( ) ; fImpl . run ( ) ; } public List < SVDBTask > getTargets ( ISVDBScopeItem active_scope ) { OverrideMethodsDialog dlg = null ; try { dlg = new OverrideMethodsDialog ( fEditor . getSite ( ) . getShell ( ) , ( SVDBClassDecl ) active_scope , fEditor . getIndexIterator ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } dlg . setBlockOnOpen ( true ) ; dlg . open ( ) ; if ( dlg . getResult ( ) == null ) { return null ; } List < SVDBTask > ret = new ArrayList < SVDBTask > ( ) ; for ( Object o : dlg . getResult ( ) ) { if ( o instanceof SVDBTask ) { ret . add ( ( SVDBTask ) o ) ; } } return ret ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OpenQuickObjectsViewAction extends TextEditorAction { private SVEditor fEditor ; public OpenQuickObjectsViewAction ( ResourceBundle bundle , SVEditor editor ) { super ( bundle , "" , editor ) ; fEditor = editor ; } @ Override public void run ( ) { fEditor . getQuickObjectsPresenter ( ) . showInformation ( ) ; } ; } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . scanutils . SVDocumentTextScanner ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; public class IndentAction extends TextEditorAction { public IndentAction ( ResourceBundle bundle , String prefix , SVEditor editor ) { super ( bundle , prefix , editor ) ; update ( ) ; } @ Override public boolean isEnabled ( ) { return true ; } @ Override public void run ( ) { ITextSelection sel = getSelection ( ) ; IDocument doc = getTextEditor ( ) . getDocumentProvider ( ) . getDocument ( getTextEditor ( ) . getEditorInput ( ) ) ; int start_line , end_line ; boolean full_file = false ; if ( sel . getLength ( ) == ) { full_file = true ; } try { if ( full_file ) { start_line = doc . getLineOfOffset ( ) ; end_line = doc . getLineOfOffset ( doc . getLength ( ) - ) ; } else { start_line = doc . getLineOfOffset ( sel . getOffset ( ) ) ; end_line = doc . getLineOfOffset ( sel . getOffset ( ) + sel . getLength ( ) ) ; } SVDocumentTextScanner text_scanner = new SVDocumentTextScanner ( doc , ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; SVIndentScanner scanner = new SVIndentScanner ( text_scanner ) ; indenter . init ( scanner ) ; indenter . setIndentIncr ( SVUiPlugin . getDefault ( ) . getIndentIncr ( ) ) ; if ( ! full_file ) { indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( start_line - ) ; } String str = null ; int length = ; for ( int i = start_line ; i < end_line ; i ++ ) { length += doc . getLineLength ( i ) ; } try { str = indenter . indent ( start_line + , end_line ) ; doc . replace ( doc . getLineOffset ( start_line ) , length , str ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } catch ( BadLocationException e ) { } } private ITextSelection getSelection ( ) { ISelectionProvider provider = getSelectionProvider ( ) ; if ( provider != null ) { ISelection selection = provider . getSelection ( ) ; if ( selection instanceof ITextSelection ) return ( ITextSelection ) selection ; } return TextSelection . emptySelection ( ) ; } private ISelectionProvider getSelectionProvider ( ) { ITextEditor editor = getTextEditor ( ) ; if ( editor != null ) { return editor . getSelectionProvider ( ) ; } return null ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . utils . SVDBIndexSearcher ; import net . sf . sveditor . core . db . utils . SVDBSearchUtils ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class SVClassHierarchyCP implements ITreeContentProvider { private SVDBIndexSearcher fIndexSearcher ; private SVDBClassDecl fLeafClass ; private Object fEmptyList [ ] = new Object [ ] ; public SVClassHierarchyCP ( SVDBClassDecl leaf_class , SVDBIndexSearcher index_searcher ) { fLeafClass = leaf_class ; fIndexSearcher = index_searcher ; } public Object [ ] getElements ( Object inputElement ) { List < SVDBClassDecl > ret = new ArrayList < SVDBClassDecl > ( ) ; SVDBClassDecl cl = fLeafClass ; while ( cl != null ) { cl = fIndexSearcher . findSuperClass ( cl ) ; if ( cl != null ) { ret . add ( cl ) ; } } return ret . toArray ( ) ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof SVDBClassDecl ) { List < ISVDBItemBase > ret = SVDBSearchUtils . findItemsByType ( ( SVDBModIfcDecl ) parentElement , SVDBItemType . Function , SVDBItemType . Task ) ; return ret . toArray ( ) ; } else { return fEmptyList ; } } public Object getParent ( Object element ) { return ( ( ISVDBChildItem ) element ) . getParent ( ) ; } public boolean hasChildren ( Object element ) { return ( getChildren ( element ) . length > ) ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } } package net . sf . sveditor . ui . editor . actions ; import java . util . Iterator ; import java . util . List ; import java . util . ResourceBundle ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPartitioningException ; import org . eclipse . jface . text . BadPositionCategoryException ; import org . eclipse . jface . text . DefaultPositionUpdater ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . IPositionUpdater ; import org . eclipse . jface . text . IRewriteTarget ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . ITextEditorExtension2 ; import org . eclipse . ui . texteditor . TextEditorAction ; public abstract class BlockCommentAction extends TextEditorAction { public BlockCommentAction ( ResourceBundle bundle , String prefix , ITextEditor editor ) { super ( bundle , prefix , editor ) ; } static class Edit extends DocumentEvent { public static class EditFactory { private static final String CATEGORY = "" ; private static int fgCount = ; private final String fCategory ; private IDocument fDocument ; private IPositionUpdater fUpdater ; public EditFactory ( IDocument document ) { fCategory = CATEGORY + fgCount ++ ; fDocument = document ; } public Edit createEdit ( int offset , int length , String text ) throws BadLocationException { if ( ! fDocument . containsPositionCategory ( fCategory ) ) { fDocument . addPositionCategory ( fCategory ) ; fUpdater = new DefaultPositionUpdater ( fCategory ) ; fDocument . addPositionUpdater ( fUpdater ) ; } Position position = new Position ( offset ) ; try { fDocument . addPosition ( fCategory , position ) ; } catch ( BadPositionCategoryException e ) { Assert . isTrue ( false ) ; } return new Edit ( fDocument , length , text , position ) ; } public void release ( ) { if ( fDocument != null && fDocument . containsPositionCategory ( fCategory ) ) { fDocument . removePositionUpdater ( fUpdater ) ; try { fDocument . removePositionCategory ( fCategory ) ; } catch ( BadPositionCategoryException e ) { Assert . isTrue ( false ) ; } fDocument = null ; fUpdater = null ; } } } private Position fPosition ; protected Edit ( IDocument document , int length , String text , Position position ) { super ( document , , length , text ) ; fPosition = position ; } public int getOffset ( ) { return fPosition . getOffset ( ) ; } public void perform ( ) throws BadLocationException { getDocument ( ) . replace ( getOffset ( ) , getLength ( ) , getText ( ) ) ; } } public void run ( ) { if ( ! isEnabled ( ) ) return ; ITextEditor editor = getTextEditor ( ) ; if ( editor == null || ! ensureEditable ( editor ) ) return ; ITextSelection selection = getCurrentSelection ( ) ; if ( ! isValidSelection ( selection ) ) return ; if ( ! validateEditorInputState ( ) ) return ; IDocumentProvider docProvider = editor . getDocumentProvider ( ) ; IEditorInput input = editor . getEditorInput ( ) ; if ( docProvider == null || input == null ) return ; IDocument document = docProvider . getDocument ( input ) ; if ( document == null ) return ; IDocumentExtension3 docExtension ; if ( document instanceof IDocumentExtension3 ) docExtension = ( IDocumentExtension3 ) document ; else return ; IRewriteTarget target = ( IRewriteTarget ) editor . getAdapter ( IRewriteTarget . class ) ; if ( target != null ) { target . beginCompoundChange ( ) ; } Edit . EditFactory factory = new Edit . EditFactory ( document ) ; try { runInternal ( selection , docExtension , factory ) ; } catch ( BadLocationException e ) { } catch ( BadPartitioningException e ) { Assert . isTrue ( false , "" ) ; } finally { factory . release ( ) ; if ( target != null ) { target . endCompoundChange ( ) ; } } } protected void executeEdits ( List < Edit > edits ) throws BadLocationException { for ( Iterator < Edit > it = edits . iterator ( ) ; it . hasNext ( ) ; ) { Edit edit = it . next ( ) ; edit . perform ( ) ; } } protected boolean ensureEditable ( ITextEditor editor ) { Assert . isNotNull ( editor ) ; if ( editor instanceof ITextEditorExtension2 ) { ITextEditorExtension2 ext = ( ITextEditorExtension2 ) editor ; return ext . validateEditorInputState ( ) ; } return editor . isEditable ( ) ; } public void update ( ) { super . update ( ) ; if ( isEnabled ( ) ) { if ( ! canModifyEditor ( ) || ! isValidSelection ( getCurrentSelection ( ) ) ) setEnabled ( false ) ; } } protected ITextSelection getCurrentSelection ( ) { ITextEditor editor = getTextEditor ( ) ; if ( editor != null ) { ISelectionProvider provider = editor . getSelectionProvider ( ) ; if ( provider != null ) { ISelection selection = provider . getSelection ( ) ; if ( selection instanceof ITextSelection ) return ( ITextSelection ) selection ; } } return null ; } protected abstract void runInternal ( ITextSelection selection , IDocumentExtension3 docExtension , Edit . EditFactory factory ) throws BadLocationException , BadPartitioningException ; protected abstract boolean isValidSelection ( ITextSelection selection ) ; protected String getCommentStart ( ) { return "" ; } protected String getCommentEnd ( ) { return "" ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . utils . SVDBSearchUtils ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . scanutils . IRandomAccessTextScanner ; import net . sf . sveditor . core . srcgen . MethodGenerator ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . ISVEditor ; import net . sf . sveditor . ui . pref . SVEditorPrefsConstants ; import net . sf . sveditor . ui . scanutils . SVDocumentTextScanner ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; public class OverrideTaskFuncImpl { private ISVEditor fEditor ; private IOverrideMethodsTargetProvider fTargetProvider ; public OverrideTaskFuncImpl ( ISVEditor editor , IOverrideMethodsTargetProvider target_provider ) { fEditor = editor ; fTargetProvider = target_provider ; } public void run ( ) { IDocument doc = fEditor . getDocument ( ) ; ITextSelection sel = fEditor . getTextSel ( ) ; int offset = sel . getOffset ( ) + sel . getLength ( ) ; SVDBFile file = fEditor . getSVDBFile ( ) ; ISVDBChildItem active_scope = SVDBSearchUtils . findActiveScope ( file , fEditor . getTextSel ( ) . getStartLine ( ) ) ; ISVDBChildItem insert_point = active_scope ; int insert_point_line = fEditor . getTextSel ( ) . getStartLine ( ) ; if ( insert_point . getType ( ) != SVDBItemType . ClassDecl ) { while ( insert_point != null && insert_point . getType ( ) != SVDBItemType . ClassDecl && insert_point . getParent ( ) != null && insert_point . getParent ( ) . getType ( ) != SVDBItemType . ClassDecl ) { insert_point = insert_point . getParent ( ) ; } if ( insert_point . getParent ( ) != null && insert_point . getParent ( ) . getType ( ) == SVDBItemType . ClassDecl ) { ISVDBScopeItem scope = ( ISVDBScopeItem ) insert_point ; insert_point_line = scope . getEndLocation ( ) . getLine ( ) ; } else { System . out . println ( "" ) ; return ; } } while ( active_scope != null && active_scope . getType ( ) != SVDBItemType . ClassDecl ) { active_scope = active_scope . getParent ( ) ; } if ( active_scope == null ) { return ; } List < SVDBTask > targets = null ; if ( active_scope instanceof ISVDBScopeItem ) { targets = fTargetProvider . getTargets ( ( ISVDBScopeItem ) active_scope ) ; } if ( targets == null ) { return ; } try { StringBuilder new_tf = new StringBuilder ( ) ; MethodGenerator gen = new MethodGenerator ( ) ; new_tf . append ( "" ) ; for ( SVDBTask tf : targets ) { new_tf . append ( gen . generate ( tf ) ) ; } offset = doc . getLineOffset ( insert_point_line ) ; doc . replace ( offset , , new_tf . toString ( ) ) ; boolean indent_en = SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_AUTO_INDENT_ENABLED_S ) ; if ( indent_en ) { int line_cnt = ; for ( int i = ; i < new_tf . length ( ) ; i ++ ) { if ( new_tf . charAt ( i ) == '' ) { line_cnt ++ ; } } doc . computePartitioning ( , doc . getLength ( ) ) ; IRandomAccessTextScanner text_scanner = new SVDocumentTextScanner ( doc , ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; SVIndentScanner scanner = new SVIndentScanner ( text_scanner ) ; indenter . init ( scanner ) ; try { String str = indenter . indent ( insert_point_line + , ( insert_point_line + line_cnt ) ) ; doc . replace ( offset , new_tf . length ( ) , str ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } } } package net . sf . sveditor . ui . editor . actions ; import java . util . LinkedList ; import java . util . List ; import java . util . ResourceBundle ; import net . sf . sveditor . ui . editor . SVDocumentPartitions ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPartitioningException ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITypedRegion ; public class RemoveBlockCommentAction extends BlockCommentAction { public RemoveBlockCommentAction ( ResourceBundle bundle , String prefix , SVEditor editor ) { super ( bundle , prefix , editor ) ; } protected void runInternal ( ITextSelection selection , IDocumentExtension3 docExtension , Edit . EditFactory factory ) throws BadPartitioningException , BadLocationException { List < Edit > edits = new LinkedList < Edit > ( ) ; int tokenLength = getCommentStart ( ) . length ( ) ; int offset = selection . getOffset ( ) ; int endOffset = offset + selection . getLength ( ) ; ITypedRegion partition = docExtension . getPartition ( SVDocumentPartitions . SV_PARTITIONING , offset , false ) ; int partOffset = partition . getOffset ( ) ; int partEndOffset = partOffset + partition . getLength ( ) ; while ( partEndOffset < endOffset ) { if ( partition . getType ( ) == SVDocumentPartitions . SV_MULTILINE_COMMENT ) { edits . add ( factory . createEdit ( partOffset , tokenLength , "" ) ) ; edits . add ( factory . createEdit ( partEndOffset - tokenLength , tokenLength , "" ) ) ; } partition = docExtension . getPartition ( SVDocumentPartitions . SV_PARTITIONING , partEndOffset , false ) ; partOffset = partition . getOffset ( ) ; partEndOffset = partOffset + partition . getLength ( ) ; } if ( partition . getType ( ) == SVDocumentPartitions . SV_MULTILINE_COMMENT ) { edits . add ( factory . createEdit ( partOffset , tokenLength , "" ) ) ; edits . add ( factory . createEdit ( partEndOffset - tokenLength , tokenLength , "" ) ) ; } executeEdits ( edits ) ; } protected boolean isValidSelection ( ITextSelection selection ) { return selection != null && ! selection . isEmpty ( ) && selection . getLength ( ) > ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . List ; import java . util . ResourceBundle ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . core . open_decl . OpenDeclUtils ; import net . sf . sveditor . ui . SVEditorUtil ; import net . sf . sveditor . ui . editor . SVEditor ; import net . sf . sveditor . ui . scanutils . SVDocumentTextScanner ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . texteditor . TextEditorAction ; public class OpenDeclarationAction extends TextEditorAction { private SVEditor fEditor ; private LogHandle fLog ; private boolean fDebugEn = true ; public OpenDeclarationAction ( ResourceBundle bundle , SVEditor editor ) { super ( bundle , "" , editor ) ; fLog = LogFactory . getLogHandle ( "" ) ; fEditor = editor ; update ( ) ; } protected ITextSelection getTextSel ( ) { ITextSelection sel = null ; if ( getTextEditor ( ) != null ) { ISelection sel_o = getTextEditor ( ) . getSelectionProvider ( ) . getSelection ( ) ; if ( sel_o != null && sel_o instanceof ITextSelection ) { sel = ( ITextSelection ) sel_o ; } } return sel ; } @ Override public void run ( ) { debug ( "" ) ; Tuple < ISVDBItemBase , SVDBFile > target = findTarget ( ) ; try { if ( target . first ( ) != null ) { fLog . debug ( "" + SVDBItem . getName ( target . first ( ) ) ) ; SVEditorUtil . openEditor ( target . first ( ) ) ; } else if ( target . second ( ) != null ) { SVEditorUtil . openEditor ( target . second ( ) . getFilePath ( ) ) ; } } catch ( PartInitException e ) { fLog . error ( "" , e ) ; } } protected SVDBFile getTargetFile ( ) { return fEditor . getSVDBFile ( ) ; } protected ISVDBIndexIterator getIndexIt ( ) { return fEditor . getIndexIterator ( ) ; } protected IDocument getDocument ( ) { return fEditor . getDocumentProvider ( ) . getDocument ( fEditor . getEditorInput ( ) ) ; } protected Tuple < ISVDBItemBase , SVDBFile > findTarget ( ) { IDocument doc = getDocument ( ) ; ITextSelection sel = getTextSel ( ) ; int offset = sel . getOffset ( ) + sel . getLength ( ) ; SVDocumentTextScanner scanner = new SVDocumentTextScanner ( doc , offset ) ; scanner . setSkipComments ( true ) ; List < Tuple < ISVDBItemBase , SVDBFile > > items = OpenDeclUtils . openDecl_2 ( getTargetFile ( ) , getTextSel ( ) . getStartLine ( ) , scanner , getIndexIt ( ) ) ; if ( items . size ( ) > ) { return items . get ( ) ; } else { return new Tuple < ISVDBItemBase , SVDBFile > ( null , null ) ; } } private void debug ( String msg ) { if ( fDebugEn ) { fLog . debug ( msg ) ; } } } package net . sf . sveditor . ui . editor . actions ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBTask ; public interface IOverrideMethodsTargetProvider { List < SVDBTask > getTargets ( ISVDBScopeItem active_scope ) ; } package net . sf . sveditor . ui . editor . actions ; import java . util . LinkedList ; import java . util . List ; import java . util . ResourceBundle ; import net . sf . sveditor . ui . editor . SVDocumentPartitions ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPartitioningException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITypedRegion ; public class AddBlockCommentAction extends BlockCommentAction { public AddBlockCommentAction ( ResourceBundle bundle , String prefix , SVEditor editor ) { super ( bundle , prefix , editor ) ; } protected void runInternal ( ITextSelection selection , IDocumentExtension3 docExtension , Edit . EditFactory factory ) throws BadLocationException , BadPartitioningException { int selectionOffset = selection . getOffset ( ) ; int selectionEndOffset = selectionOffset + selection . getLength ( ) ; List < Edit > edits = new LinkedList < Edit > ( ) ; ITypedRegion partition = docExtension . getPartition ( SVDocumentPartitions . SV_PARTITIONING , selectionOffset , false ) ; handleFirstPartition ( partition , edits , factory , selectionOffset ) ; while ( partition . getOffset ( ) + partition . getLength ( ) < selectionEndOffset ) { partition = handleInteriorPartition ( partition , edits , factory , docExtension ) ; } handleLastPartition ( partition , edits , factory , selectionEndOffset ) ; executeEdits ( edits ) ; } private void handleFirstPartition ( ITypedRegion partition , List < Edit > edits , Edit . EditFactory factory , int offset ) throws BadLocationException { int partOffset = partition . getOffset ( ) ; String partType = partition . getType ( ) ; Assert . isTrue ( partOffset <= offset , "" ) ; if ( partType == IDocument . DEFAULT_CONTENT_TYPE ) { edits . add ( factory . createEdit ( offset , , getCommentStart ( ) ) ) ; } else if ( isSpecialPartition ( partType ) ) { edits . add ( factory . createEdit ( partOffset , , getCommentStart ( ) ) ) ; } } private ITypedRegion handleInteriorPartition ( ITypedRegion partition , List < Edit > edits , Edit . EditFactory factory , IDocumentExtension3 docExtension ) throws BadPartitioningException , BadLocationException { String partType = partition . getType ( ) ; int partEndOffset = partition . getOffset ( ) + partition . getLength ( ) ; int tokenLength = getCommentStart ( ) . length ( ) ; if ( partType == SVDocumentPartitions . SV_MULTILINE_COMMENT ) { edits . add ( factory . createEdit ( partEndOffset - tokenLength , tokenLength , "" ) ) ; } partition = docExtension . getPartition ( SVDocumentPartitions . SV_PARTITIONING , partEndOffset , false ) ; partType = partition . getType ( ) ; if ( partType == SVDocumentPartitions . SV_MULTILINE_COMMENT ) { edits . add ( factory . createEdit ( partition . getOffset ( ) , getCommentStart ( ) . length ( ) , "" ) ) ; } return partition ; } private void handleLastPartition ( ITypedRegion partition , List < Edit > edits , Edit . EditFactory factory , int endOffset ) throws BadLocationException { String partType = partition . getType ( ) ; if ( partType == IDocument . DEFAULT_CONTENT_TYPE ) { edits . add ( factory . createEdit ( endOffset , , getCommentEnd ( ) ) ) ; } else if ( isSpecialPartition ( partType ) ) { edits . add ( factory . createEdit ( partition . getOffset ( ) + partition . getLength ( ) , , getCommentEnd ( ) ) ) ; } } private boolean isSpecialPartition ( String partType ) { return partType == SVDocumentPartitions . SV_STRING || partType == SVDocumentPartitions . SV_SINGLELINE_COMMENT || partType == SVDocumentPartitions . SV_MULTILINE_COMMENT ; } protected boolean isValidSelection ( ITextSelection selection ) { return ( selection != null && ! selection . isEmpty ( ) && selection . getLength ( ) > ) ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . ui . texteditor . TextEditorAction ; public class PrevWordAction extends TextEditorAction { private SVEditor fEditor ; public PrevWordAction ( ResourceBundle bundle , String prefix , SVEditor editor ) { super ( bundle , prefix , editor ) ; fEditor = editor ; } @ Override public void run ( ) { StyledText text = fEditor . sourceViewer ( ) . getTextWidget ( ) ; int offset = text . getCaretOffset ( ) ; String str = text . getText ( ) ; offset -- ; if ( offset < ) { return ; } int ch = str . charAt ( offset ) ; if ( SVCharacter . isSVIdentifierPart ( ch ) ) { while ( offset >= ) { ch = str . charAt ( offset ) ; if ( ! SVCharacter . isSVIdentifierPart ( ch ) ) { break ; } offset -- ; } } else { while ( offset >= ) { ch = str . charAt ( offset ) ; if ( SVCharacter . isSVIdentifierPart ( ch ) ) { break ; } offset -- ; } } if ( offset < ) { offset = ; } text . setCaretOffset ( ++ offset ) ; } } package net . sf . sveditor . ui . editor . actions ; import java . util . ResourceBundle ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . graphics . Point ; import org . eclipse . ui . texteditor . TextEditorAction ; public class SelNextWordAction extends TextEditorAction { private SVEditor fEditor ; public SelNextWordAction ( ResourceBundle bundle , String prefix , SVEditor editor ) { super ( bundle , prefix , editor ) ; fEditor = editor ; } @ Override public void run ( ) { ISourceViewer sv = fEditor . sourceViewer ( ) ; StyledText text = fEditor . sourceViewer ( ) . getTextWidget ( ) ; int offset = text . getCaretOffset ( ) ; int start_offset = offset ; if ( text . getSelection ( ) != null ) { Point sel = text . getSelection ( ) ; if ( sel . x == offset ) { start_offset = sel . y ; } else if ( sel . y == offset ) { start_offset = sel . x ; } } String str = text . getText ( ) ; int len = str . length ( ) ; int ch = str . charAt ( offset ) ; if ( SVCharacter . isSVIdentifierPart ( ch ) ) { while ( offset < len ) { ch = str . charAt ( offset ) ; if ( ! SVCharacter . isSVIdentifierPart ( ch ) ) { break ; } offset ++ ; } } else if ( Character . isWhitespace ( ch ) ) { while ( offset < len ) { ch = str . charAt ( offset ) ; if ( ! Character . isWhitespace ( ch ) ) { break ; } offset ++ ; } } else { if ( offset + < len ) { offset ++ ; } } if ( offset >= len ) { offset = len - ; } sv . setSelectedRange ( start_offset , Math . abs ( offset - start_offset ) ) ; } } package net . sf . sveditor . ui . editor ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . text . rules . EndOfLineRule ; import org . eclipse . jface . text . rules . IPredicateRule ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . RuleBasedPartitionScanner ; import org . eclipse . jface . text . rules . SingleLineRule ; import org . eclipse . jface . text . rules . Token ; public class SVPartitionScanner extends RuleBasedPartitionScanner { public SVPartitionScanner ( ) { super ( ) ; IToken mlc = new Token ( SVDocumentPartitions . SV_MULTILINE_COMMENT ) ; IToken slc = new Token ( SVDocumentPartitions . SV_SINGLELINE_COMMENT ) ; List < IPredicateRule > rules = new ArrayList < IPredicateRule > ( ) ; rules . add ( new CCommentRule ( mlc ) ) ; rules . add ( new EndOfLineRule ( "" , slc ) ) ; rules . add ( new SingleLineRule ( "" , "" , Token . UNDEFINED , '' ) ) ; IPredicateRule rulesArr [ ] = rules . toArray ( new IPredicateRule [ rules . size ( ) ] ) ; setPredicateRules ( rulesArr ) ; } } package net . sf . sveditor . ui . editor ; import java . util . HashMap ; import java . util . Map ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . pref . SVEditorPrefsConstants ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; public enum SVEditorColors { DEFAULT , KEYWORD , STRING , SINGLE_LINE_COMMENT , MULTI_LINE_COMMENT ; private static Map < SVEditorColors , String > fColorMap ; private static Map < SVEditorColors , String > fStyleMap ; static { fColorMap = new HashMap < SVEditorColors , String > ( ) ; fStyleMap = new HashMap < SVEditorColors , String > ( ) ; fColorMap . put ( DEFAULT , SVEditorPrefsConstants . P_DEFAULT_C ) ; fColorMap . put ( STRING , SVEditorPrefsConstants . P_STRING_C ) ; fColorMap . put ( SINGLE_LINE_COMMENT , SVEditorPrefsConstants . P_COMMENT_C ) ; fColorMap . put ( MULTI_LINE_COMMENT , SVEditorPrefsConstants . P_COMMENT_C ) ; fColorMap . put ( KEYWORD , SVEditorPrefsConstants . P_KEYWORD_C ) ; fStyleMap . put ( DEFAULT , SVEditorPrefsConstants . P_DEFAULT_S ) ; fStyleMap . put ( STRING , SVEditorPrefsConstants . P_STRING_S ) ; fStyleMap . put ( SINGLE_LINE_COMMENT , SVEditorPrefsConstants . P_COMMENT_S ) ; fStyleMap . put ( MULTI_LINE_COMMENT , SVEditorPrefsConstants . P_COMMENT_S ) ; fStyleMap . put ( KEYWORD , SVEditorPrefsConstants . P_KEYWORD_S ) ; } static IPreferenceStore fPrefStore = SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ; public static Color getColor ( SVEditorColors color ) { if ( fColorMap . containsKey ( color ) ) { return SVColorManager . getColor ( PreferenceConverter . getColor ( fPrefStore , fColorMap . get ( color ) ) ) ; } else { return SVColorManager . getColor ( PreferenceConverter . getColor ( fPrefStore , fColorMap . get ( DEFAULT ) ) ) ; } } public static int getStyle ( SVEditorColors color ) { if ( fStyleMap . containsKey ( color ) ) { return fPrefStore . getInt ( fStyleMap . get ( color ) ) ; } else { return SWT . NORMAL ; } } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultTextDoubleClickStrategy ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; public class SVDoubleClickStrategy extends DefaultTextDoubleClickStrategy { @ Override protected IRegion findExtendedDoubleClickSelection ( IDocument document , int offset ) { return findWord ( document , offset ) ; } @ Override protected IRegion findWord ( IDocument document , int offset ) { return getWordSelection ( document , offset ) ; } private static final int UNKNOWN = - ; private static final int WS = ; private static final int ID = ; private static final int IDS = ; private static final int AT = ; private static final int FORWARD = ; private static final int BACKWARD = ; private int fState ; private int fAnchorState ; private int fDirection ; private int fStart ; private int fEnd ; private void setAnchor ( int anchor ) { fState = UNKNOWN ; fAnchorState = UNKNOWN ; fDirection = UNKNOWN ; fStart = anchor ; fEnd = anchor - ; } private boolean isIdentifierStart ( char c ) { return Character . isJavaIdentifierStart ( c ) ; } private boolean isIdentifierPart ( char c ) { return Character . isJavaIdentifierPart ( c ) ; } private boolean isWhitespace ( char c ) { return Character . isWhitespace ( c ) ; } private boolean backward ( char c , int offset ) { checkDirection ( BACKWARD ) ; switch ( fState ) { case AT : return false ; case IDS : if ( isWhitespace ( c ) ) { fState = WS ; return true ; } if ( isIdentifierStart ( c ) ) { fStart = offset ; fState = IDS ; return true ; } if ( isIdentifierPart ( c ) ) { fStart = offset ; fState = ID ; return true ; } return false ; case ID : if ( isIdentifierStart ( c ) ) { fStart = offset ; fState = IDS ; return true ; } if ( isIdentifierPart ( c ) ) { fStart = offset ; fState = ID ; return true ; } return false ; case WS : if ( isWhitespace ( c ) ) { return true ; } return false ; default : return false ; } } private boolean forward ( char c , int offset ) { checkDirection ( FORWARD ) ; switch ( fState ) { case WS : case AT : if ( isWhitespace ( c ) ) { fState = WS ; return true ; } if ( isIdentifierStart ( c ) ) { fEnd = offset ; fState = IDS ; return true ; } return false ; case IDS : case ID : if ( isIdentifierStart ( c ) ) { fEnd = offset ; fState = IDS ; return true ; } if ( isIdentifierPart ( c ) ) { fEnd = offset ; fState = ID ; return true ; } return false ; case UNKNOWN : if ( isIdentifierStart ( c ) ) { fEnd = offset ; fState = IDS ; fAnchorState = fState ; return true ; } if ( isIdentifierPart ( c ) ) { fEnd = offset ; fState = ID ; fAnchorState = fState ; return true ; } if ( isWhitespace ( c ) ) { fState = WS ; fAnchorState = fState ; return true ; } return false ; default : return false ; } } private void checkDirection ( int direction ) { if ( fDirection == direction ) return ; if ( direction == FORWARD ) { if ( fStart <= fEnd ) fState = fAnchorState ; else fState = UNKNOWN ; } else if ( direction == BACKWARD ) { if ( fEnd >= fStart ) fState = fAnchorState ; else fState = UNKNOWN ; } fDirection = direction ; } public IRegion getWordSelection ( IDocument document , int anchor ) { try { final int min = ; final int max = document . getLength ( ) ; setAnchor ( anchor ) ; char c ; int offset = anchor ; while ( offset < max ) { c = document . getChar ( offset ) ; if ( ! forward ( c , offset ) ) break ; ++ offset ; } offset = anchor ; while ( offset >= min ) { c = document . getChar ( offset ) ; if ( ! backward ( c , offset ) ) break ; -- offset ; } return new Region ( fStart , fEnd - fStart + ) ; } catch ( BadLocationException x ) { return new Region ( anchor , ) ; } } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentListener ; import org . eclipse . jface . text . ITextInputListener ; import org . eclipse . jface . text . ITextPresentationListener ; import org . eclipse . jface . text . TextPresentation ; public class SVHightingPresenter implements ITextPresentationListener , ITextInputListener , IDocumentListener { public void applyTextPresentation ( TextPresentation textPresentation ) { } public void inputDocumentAboutToBeChanged ( IDocument oldInput , IDocument newInput ) { System . out . println ( "" ) ; } public void inputDocumentChanged ( IDocument oldInput , IDocument newInput ) { System . out . println ( "" ) ; } public void documentAboutToBeChanged ( DocumentEvent event ) { } public void documentChanged ( DocumentEvent event ) { System . out . println ( "" ) ; } } package net . sf . sveditor . ui . editor ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . utils . SVDBSearchUtils ; import net . sf . sveditor . core . expr_utils . SVExprScanner ; import net . sf . sveditor . ui . scanutils . SVDocumentTextScanner ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; public class SVEditorTextHover implements ITextHover { private SVEditor fEditor ; public SVEditorTextHover ( SVEditor editor , ITextViewer viewer ) { fEditor = editor ; } public String getHoverInfo ( ITextViewer textViewer , IRegion hoverRegion ) { SVDocumentTextScanner scanner = new SVDocumentTextScanner ( textViewer . getDocument ( ) , hoverRegion . getOffset ( ) + ) ; SVExprScanner expr_scanner = new SVExprScanner ( ) ; expr_scanner . extractExprContext ( scanner , true ) ; int lineno = - ; try { lineno = textViewer . getDocument ( ) . getLineOfOffset ( hoverRegion . getOffset ( ) ) ; } catch ( BadLocationException e ) { } ISVDBScopeItem src_scope = null ; if ( lineno != - ) { src_scope = SVDBSearchUtils . findActiveScope ( fEditor . getSVDBFile ( ) , lineno ) ; } String str = null ; if ( src_scope != null ) { } return str ; } public IRegion getHoverRegion ( ITextViewer textViewer , int offset ) { return findWord ( textViewer . getDocument ( ) , offset ) ; } public IInformationControlCreator getHoverControlCreator ( ) { return null ; } private IRegion findWord ( IDocument document , int offset ) { int start = - ; int end = - ; try { int pos = offset ; char c ; while ( pos >= ) { c = document . getChar ( pos ) ; if ( ! Character . isUnicodeIdentifierPart ( c ) ) break ; -- pos ; } start = pos ; pos = offset ; int length = document . getLength ( ) ; while ( pos < length ) { c = document . getChar ( pos ) ; if ( ! Character . isUnicodeIdentifierPart ( c ) ) break ; ++ pos ; } end = pos ; } catch ( BadLocationException x ) { } if ( start >= - && end > - ) { if ( start == offset && end == offset ) return new Region ( offset , ) ; else if ( start == offset ) return new Region ( start , end - start ) ; else return new Region ( start + , end - start - ) ; } return null ; } } package net . sf . sveditor . ui . editor ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . content_assist . AbstractCompletionProcessor ; import net . sf . sveditor . core . content_assist . SVCompletionProposal ; import net . sf . sveditor . core . content_assist . SVCompletionProposalType ; import net . sf . sveditor . core . content_assist . SVCompletionProposalUtils ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBClassDecl ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBFunction ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBMacroDef ; import net . sf . sveditor . core . db . SVDBModIfcClassParam ; import net . sf . sveditor . core . db . SVDBModIfcDecl ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . stmt . SVDBParamPortDecl ; import net . sf . sveditor . core . db . stmt . SVDBTypedefStmt ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclItem ; import net . sf . sveditor . core . job_mgr . IJob ; import net . sf . sveditor . core . job_mgr . IJobMgr ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . ui . SVDBIconUtils ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . pref . SVEditorPrefsConstants ; import net . sf . sveditor . ui . scanutils . SVDocumentTextScanner ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . contentassist . CompletionProposal ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . IContentAssistProcessor ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . contentassist . IContextInformationValidator ; import org . eclipse . jface . text . templates . DocumentTemplateContext ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . TemplateContext ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . eclipse . jface . text . templates . TemplateProposal ; import org . eclipse . swt . widgets . Display ; public class SVCompletionProcessor extends AbstractCompletionProcessor implements IContentAssistProcessor { private SVEditor fEditor ; private SVCompletionProposalUtils fProposalUtils ; private static final boolean fShowModulePorts = false ; private static final char [ ] PROPOSAL_ACTIVATION_CHARS = { '' , '' } ; private final IContextInformation NO_CONTEXTS [ ] = new IContextInformation [ ] ; private List < ICompletionProposal > fProposals = new ArrayList < ICompletionProposal > ( ) ; public SVCompletionProcessor ( SVEditor editor ) { fLog = LogFactory . getLogHandle ( "" ) ; fEditor = editor ; fProposalUtils = new SVCompletionProposalUtils ( ) ; } public ICompletionProposal [ ] computeCompletionProposals ( ITextViewer viewer , int offset ) { fProposalUtils . setTFMaxCharsPerLine ( SVUiPlugin . getDefault ( ) . getIntegerPref ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_LINE_WRAP_LIMIT ) ) ; fProposalUtils . setTFNamedPorts ( SVUiPlugin . getDefault ( ) . getBooleanPref ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_NAMED_PORTS_EN ) ) ; fProposalUtils . setTFPortsPerLine ( SVUiPlugin . getDefault ( ) . getIntegerPref ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TF_MAX_PARAMS_PER_LINE ) ) ; fProposalUtils . setModIfcInstMaxCharsPerLine ( SVUiPlugin . getDefault ( ) . getIntegerPref ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_LINE_WRAP_LIMIT ) ) ; fProposalUtils . setModIfcInstNamedPorts ( SVUiPlugin . getDefault ( ) . getBooleanPref ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_NAMED_PORTS_EN ) ) ; fProposalUtils . setModIfcInstPortsPerLine ( SVUiPlugin . getDefault ( ) . getIntegerPref ( SVEditorPrefsConstants . P_CONTENT_ASSIST_MODIFCINST_MAX_PORTS_PER_LINE ) ) ; fProposals . clear ( ) ; final SVDocumentTextScanner scanner = new SVDocumentTextScanner ( viewer . getDocument ( ) , offset ) ; scanner . setSkipComments ( true ) ; int lineno = - , linepos = - ; try { lineno = viewer . getDocument ( ) . getLineOfOffset ( offset ) ; linepos = ( offset - viewer . getDocument ( ) . getLineOffset ( lineno ) ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; return new ICompletionProposal [ ] ; } IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; IJob job = job_mgr . createJob ( ) ; final int lineno_f = lineno , linepos_f = linepos ; job . init ( "" , new Runnable ( ) { public void run ( ) { computeProposals ( scanner , fEditor . getSVDBFile ( ) , lineno_f , linepos_f ) ; } } ) ; job_mgr . queueJob ( job ) ; Display d = Display . getCurrent ( ) ; int wait_time_ms = ; IPreferenceStore p_store = SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ; int timeout_ms = p_store . getInt ( SVEditorPrefsConstants . P_CONTENT_ASSIST_TIMEOUT ) ; int timeout_remain = timeout_ms ; while ( true ) { if ( job . join ( wait_time_ms ) ) { break ; } if ( timeout_ms != ) { timeout_remain -= wait_time_ms ; if ( timeout_remain < ) { break ; } } while ( d . readAndDispatch ( ) ) { } } List < SVCompletionProposal > temp_p = new ArrayList < SVCompletionProposal > ( ) ; synchronized ( fCompletionProposals ) { temp_p . addAll ( fCompletionProposals ) ; } for ( SVCompletionProposal p : temp_p ) { List < ICompletionProposal > cp = convertToProposal ( p , viewer . getDocument ( ) ) ; fProposals . addAll ( cp ) ; } return fProposals . toArray ( new ICompletionProposal [ fProposals . size ( ) ] ) ; } private static int getIndentStringSize ( String indent ) { int size = ; for ( int i = ; i < indent . length ( ) ; i ++ ) { if ( indent . charAt ( i ) == '' ) { size += SVUiPlugin . getDefault ( ) . getTabWidth ( ) ; } else { size ++ ; } } return size ; } protected List < ICompletionProposal > convertToProposal ( SVCompletionProposal p , IDocument doc ) { List < ICompletionProposal > ret = new ArrayList < ICompletionProposal > ( ) ; ICompletionProposal cp = null ; String prefix = p . getPrefix ( ) ; int replacementOffset = p . getReplacementOffset ( ) ; int replacementLength = p . getReplacementLength ( ) ; if ( replacementOffset > doc . getLength ( ) ) { replacementOffset = doc . getLength ( ) ; } String doc_str = "" ; try { doc_str = doc . get ( , replacementOffset ) ; } catch ( BadLocationException e ) { } String next_line_indent = SVCompletionProposalUtils . getLineIndent ( doc_str , SVUiPlugin . getDefault ( ) . getIndentIncr ( ) ) ; int first_line_pos = getIndentStringSize ( next_line_indent ) ; next_line_indent += SVUiPlugin . getDefault ( ) . getIndentIncr ( ) ; int subseq_line_pos = getIndentStringSize ( next_line_indent ) ; if ( p . getItem ( ) != null ) { ISVDBItemBase it = p . getItem ( ) ; switch ( p . getItem ( ) . getType ( ) ) { case Function : case Task : cp = createTaskFuncProposal ( it , doc , replacementOffset , replacementLength , next_line_indent , first_line_pos , subseq_line_pos ) ; break ; case ModuleDecl : cp = createModuleProposal ( it , doc , replacementOffset , replacementLength , next_line_indent , first_line_pos , subseq_line_pos ) ; break ; case MacroDef : cp = createMacroProposal ( it , doc , replacementOffset , replacementLength ) ; break ; case ClassDecl : cp = createClassProposal ( it , doc , replacementOffset , replacementLength ) ; break ; case TypedefStmt : { SVDBTypedefStmt tds = ( SVDBTypedefStmt ) it ; String td_name_lc = tds . getName ( ) . toLowerCase ( ) ; String prefix_lc = prefix . toLowerCase ( ) ; if ( prefix . equals ( "" ) || td_name_lc . startsWith ( prefix_lc ) ) { cp = new CompletionProposal ( SVDBItem . getName ( it ) , replacementOffset , replacementLength , SVDBItem . getName ( it ) . length ( ) , SVDBIconUtils . getIcon ( it ) , null , null , null ) ; ret . add ( cp ) ; } cp = null ; } break ; case PackageDecl : { String import_all = SVDBItem . getName ( it ) + "" ; cp = new CompletionProposal ( SVDBItem . getName ( it ) , replacementOffset , replacementLength , SVDBItem . getName ( it ) . length ( ) , SVDBIconUtils . getIcon ( it ) , null , null , null ) ; ret . add ( cp ) ; cp = new CompletionProposal ( import_all , replacementOffset , replacementLength , import_all . length ( ) , SVDBIconUtils . getIcon ( it ) , null , null , null ) ; } break ; default : cp = new CompletionProposal ( SVDBItem . getName ( it ) , replacementOffset , replacementLength , SVDBItem . getName ( it ) . length ( ) , SVDBIconUtils . getIcon ( it ) , null , null , null ) ; break ; } } else if ( p . getType ( ) == SVCompletionProposalType . Keyword ) { cp = new CompletionProposal ( p . getReplacement ( ) , p . getReplacementOffset ( ) , p . getReplacementLength ( ) , p . getReplacement ( ) . length ( ) , SVUiPlugin . getImage ( "" ) , null , null , null ) ; } else { cp = new CompletionProposal ( p . getReplacement ( ) , p . getReplacementOffset ( ) , p . getReplacementLength ( ) , p . getReplacement ( ) . length ( ) ) ; } if ( cp != null ) { ret . add ( cp ) ; } return ret ; } private ICompletionProposal createTaskFuncProposal ( ISVDBItemBase it , IDocument doc , int replacementOffset , int replacementLength , String next_line_indent , int first_line_pos , int subseq_line_pos ) { TemplateContext ctxt = new DocumentTemplateContext ( new TemplateContextType ( "" ) , doc , replacementOffset , replacementLength ) ; StringBuilder d = new StringBuilder ( ) ; SVDBTask tf = ( SVDBTask ) it ; d . append ( SVDBItem . getName ( it ) + "" ) ; ArrayList < String > all_types = new ArrayList < String > ( ) ; ArrayList < String > all_ports = new ArrayList < String > ( ) ; for ( int i = ; i < tf . getParams ( ) . size ( ) ; i ++ ) { SVDBParamPortDecl param = tf . getParams ( ) . get ( i ) ; for ( ISVDBChildItem c : param . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; all_ports . add ( vi . getName ( ) ) ; all_types . add ( param . getTypeName ( ) ) ; } } for ( int i = ; i < all_ports . size ( ) ; i ++ ) { d . append ( all_types . get ( i ) + "" + all_ports . get ( i ) ) ; if ( i + < all_ports . size ( ) ) { d . append ( "" ) ; } } d . append ( "" ) ; if ( it . getType ( ) == SVDBItemType . Function ) { SVDBFunction f = ( SVDBFunction ) tf ; if ( f . getReturnType ( ) != null && ! f . getReturnType ( ) . equals ( "" ) && ! SVDBItem . getName ( it ) . equals ( "" ) ) { d . append ( "" ) ; d . append ( f . getReturnType ( ) ) ; } } ISVDBChildItem class_it = ( ISVDBChildItem ) it ; while ( class_it != null && class_it . getType ( ) != SVDBItemType . ClassDecl ) { class_it = class_it . getParent ( ) ; } String cls_name = null ; if ( class_it != null && class_it instanceof ISVDBNamedItem ) { cls_name = ( ( ISVDBNamedItem ) class_it ) . getName ( ) ; if ( cls_name . equals ( "" ) ) { cls_name = "" ; } else if ( cls_name . equals ( "" ) ) { cls_name = "" ; } else if ( cls_name . equals ( "" ) ) { cls_name = "" ; } else if ( cls_name . startsWith ( "" ) ) { cls_name = cls_name . substring ( "" . length ( ) ) ; } } String template_str = fProposalUtils . createTFTemplate ( tf , next_line_indent , first_line_pos , subseq_line_pos ) ; Template t = new Template ( d . toString ( ) , ( cls_name != null ) ? cls_name : "" , "" , template_str , ( tf . getParams ( ) . size ( ) == ) ) ; return new TemplateProposal ( t , ctxt , new Region ( replacementOffset , replacementLength ) , SVDBIconUtils . getIcon ( it ) ) ; } private ICompletionProposal createModuleProposal ( ISVDBItemBase it , IDocument doc , int replacementOffset , int replacementLength , String next_line_indent , int first_line_pos , int subseq_line_pos ) { TemplateContext ctxt = new DocumentTemplateContext ( new TemplateContextType ( "" ) , doc , replacementOffset , replacementLength ) ; StringBuilder d = new StringBuilder ( ) ; SVDBModIfcDecl tf = ( SVDBModIfcDecl ) it ; d . append ( SVDBItem . getName ( it ) ) ; if ( fShowModulePorts ) { d . append ( "" ) ; ArrayList < String > all_types = new ArrayList < String > ( ) ; ArrayList < String > all_ports = new ArrayList < String > ( ) ; for ( int i = ; i < tf . getPorts ( ) . size ( ) ; i ++ ) { SVDBParamPortDecl param = tf . getPorts ( ) . get ( i ) ; for ( ISVDBChildItem c : param . getChildren ( ) ) { SVDBVarDeclItem vi = ( SVDBVarDeclItem ) c ; all_ports . add ( vi . getName ( ) ) ; if ( param . getTypeInfo ( ) == null ) { all_types . add ( null ) ; } else { all_types . add ( param . getTypeName ( ) ) ; } } } for ( int i = ; i < all_ports . size ( ) ; i ++ ) { if ( all_types . get ( i ) == null ) { d . append ( all_ports . get ( i ) ) ; } else { d . append ( all_types . get ( i ) + "" + all_ports . get ( i ) ) ; } if ( i + < all_ports . size ( ) ) { d . append ( "" ) ; } } d . append ( "" ) ; } String template_str = fProposalUtils . createModuleTemplate ( tf , next_line_indent , first_line_pos , subseq_line_pos ) ; Template t = new Template ( d . toString ( ) , "" , "" , template_str , ( tf . getPorts ( ) . size ( ) == ) ) ; return new TemplateProposal ( t , ctxt , new Region ( replacementOffset , replacementLength ) , SVDBIconUtils . getIcon ( it ) ) ; } private ICompletionProposal createMacroProposal ( ISVDBItemBase it , IDocument doc , int replacementOffset , int replacementLength ) { TemplateContext ctxt = new DocumentTemplateContext ( new TemplateContextType ( "" ) , doc , replacementOffset , replacementLength ) ; fLog . debug ( "" + SVDBItem . getName ( it ) ) ; StringBuilder d = new StringBuilder ( ) ; StringBuilder r = new StringBuilder ( ) ; SVDBMacroDef md = ( SVDBMacroDef ) it ; d . append ( SVDBItem . getName ( it ) ) ; r . append ( SVDBItem . getName ( it ) ) ; if ( md . getParameters ( ) . size ( ) > ) { d . append ( "" ) ; r . append ( "" ) ; } for ( int i = ; i < md . getParameters ( ) . size ( ) ; i ++ ) { String param = md . getParameters ( ) . get ( i ) . getName ( ) ; d . append ( param ) ; r . append ( "" ) ; r . append ( param ) ; r . append ( "" ) ; if ( i + < md . getParameters ( ) . size ( ) ) { d . append ( "" ) ; r . append ( "" ) ; } } if ( md . getParameters ( ) . size ( ) > ) { d . append ( "" ) ; r . append ( "" ) ; } Template t = new Template ( d . toString ( ) , "" , "" , r . toString ( ) , true ) ; return new TemplateProposal ( t , ctxt , new Region ( replacementOffset , replacementLength ) , SVDBIconUtils . getIcon ( it ) ) ; } private ICompletionProposal createClassProposal ( ISVDBItemBase it , IDocument doc , int replacementOffset , int replacementLength ) { TemplateContext ctxt = new DocumentTemplateContext ( new TemplateContextType ( "" ) , doc , replacementOffset , replacementLength ) ; StringBuilder d = new StringBuilder ( ) ; StringBuilder r = new StringBuilder ( ) ; SVDBClassDecl cl = ( SVDBClassDecl ) it ; r . append ( SVDBItem . getName ( it ) ) ; d . append ( SVDBItem . getName ( it ) ) ; if ( cl . getParameters ( ) != null && cl . getParameters ( ) . size ( ) > ) { r . append ( "" ) ; for ( int i = ; i < cl . getParameters ( ) . size ( ) ; i ++ ) { SVDBModIfcClassParam pm = cl . getParameters ( ) . get ( i ) ; r . append ( "" ) ; r . append ( pm . getName ( ) ) ; r . append ( "" ) ; if ( i + < cl . getParameters ( ) . size ( ) ) { r . append ( "" ) ; } } r . append ( "" ) ; } Template t = new Template ( d . toString ( ) , "" , "" , r . toString ( ) , true ) ; return new TemplateProposal ( t , ctxt , new Region ( replacementOffset , replacementLength ) , SVDBIconUtils . getIcon ( it ) ) ; } @ Override protected ISVDBIndexIterator getIndexIterator ( ) { return fEditor . getIndexIterator ( ) ; } @ Override protected SVDBFile getSVDBFile ( ) { return fEditor . getSVDBFile ( ) ; } public IContextInformation [ ] computeContextInformation ( ITextViewer viewer , int offset ) { return NO_CONTEXTS ; } public char [ ] getCompletionProposalAutoActivationCharacters ( ) { return PROPOSAL_ACTIVATION_CHARS ; } public char [ ] getContextInformationAutoActivationCharacters ( ) { return PROPOSAL_ACTIVATION_CHARS ; } public IContextInformationValidator getContextInformationValidator ( ) { System . out . println ( "" ) ; return null ; } public String getErrorMessage ( ) { return null ; } } package net . sf . sveditor . ui . editor ; public interface SVDocumentPartitions { String SV_MULTILINE_COMMENT = "" ; String SV_SINGLELINE_COMMENT = "" ; String SV_KEYWORD = "" ; String SV_STRING = "" ; String SV_CODE = "" ; String [ ] SV_PARTITION_TYPES = { SV_MULTILINE_COMMENT , SV_SINGLELINE_COMMENT , SV_CODE } ; String SV_PARTITIONING = "" ; } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextPresentation ; import org . eclipse . jface . text . presentation . PresentationReconciler ; public class SVPresentationReconciler extends PresentationReconciler { private IDocument fLastDocument ; public TextPresentation createRepairDescription ( IRegion damage , IDocument doc ) { if ( doc != fLastDocument ) { setDocumentToDamagers ( doc ) ; setDocumentToRepairers ( doc ) ; fLastDocument = doc ; } return createPresentation ( damage , doc ) ; } } package net . sf . sveditor . ui . editor ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension4 ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ISynchronizable ; import org . eclipse . jface . text . reconciler . DirtyRegion ; import org . eclipse . jface . text . reconciler . IReconcilingStrategy ; import org . eclipse . jface . text . reconciler . IReconcilingStrategyExtension ; public class SVReconcilingStrategy implements IReconcilingStrategy , IReconcilingStrategyExtension { private IDocument fDocument ; private SVEditor fEditor ; public SVReconcilingStrategy ( SVEditor editor ) { fEditor = editor ; } public void reconcile ( IRegion partition ) { reconcileSource ( ) ; if ( fEditor != null ) { fEditor . updateSVDBFile ( ) ; } } public void reconcile ( DirtyRegion dirtyRegion , IRegion subRegion ) { reconcileSource ( ) ; if ( fEditor != null ) { fEditor . updateSVDBFile ( ) ; } } public void setDocument ( IDocument document ) { fDocument = document ; } public void initialReconcile ( ) { reconcileSource ( ) ; if ( fEditor != null ) { fEditor . updateSVDBFile ( ) ; } } public void setProgressMonitor ( IProgressMonitor monitor ) { } private Object getLockObject ( ) { if ( fDocument instanceof ISynchronizable ) { Object lock = ( ( ISynchronizable ) fDocument ) . getLockObject ( ) ; if ( lock != null ) { return lock ; } } return fDocument ; } private void reconcileSource ( ) { if ( fDocument != null ) { synchronized ( getLockObject ( ) ) { fDocument . get ( ) ; ( ( IDocumentExtension4 ) fDocument ) . getModificationStamp ( ) ; } } } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . source . ICharacterPairMatcher ; public class SVCharacterPairMatcher implements ICharacterPairMatcher { private final static char fPairs [ ] = { '' , '' , '' , '>' , '' , '' , '' , '' } ; private IDocument fDocument ; private int fOffset ; private int fStartPos ; private int fEndPos ; private int fAnchor ; public void clear ( ) { } public void dispose ( ) { clear ( ) ; fDocument = null ; } public int getAnchor ( ) { return fAnchor ; } public IRegion match ( IDocument document , int offset ) { fOffset = offset ; if ( fOffset < ) { return null ; } fDocument = document ; if ( fDocument != null && matchPairsAt ( ) && fStartPos != fEndPos ) { return new Region ( fStartPos , fEndPos - fStartPos + ) ; } return null ; } private boolean matchPairsAt ( ) { int i ; int pairIndex1 = fPairs . length ; int pairIndex2 = fPairs . length ; fStartPos = - ; fEndPos = - ; try { char prevChar = fDocument . getChar ( Math . max ( fOffset - , ) ) ; for ( i = ; i < fPairs . length ; i = i + ) { if ( prevChar == fPairs [ i ] ) { fStartPos = fOffset - ; pairIndex1 = i ; } } for ( i = ; i < fPairs . length ; i = i + ) { if ( prevChar == fPairs [ i ] ) { fEndPos = fOffset - ; pairIndex2 = i ; } } if ( fEndPos > - ) { fAnchor = RIGHT ; fStartPos = searchForOpeningPeer ( fEndPos , fPairs [ pairIndex2 - ] , fPairs [ pairIndex2 ] ) ; if ( fStartPos > - ) return true ; else fEndPos = - ; } else if ( fStartPos > - ) { fAnchor = LEFT ; fEndPos = searchForClosingPeer ( fStartPos , fPairs [ pairIndex1 ] , fPairs [ pairIndex1 + ] ) ; if ( fEndPos > - ) return true ; else fStartPos = - ; } } catch ( BadLocationException x ) { } return false ; } private int searchForClosingPeer ( int start , char opening , char closing ) { try { int depth = ; int fPos = start + ; char fChar = ; while ( true ) { while ( fPos < fDocument . getLength ( ) ) { fChar = fDocument . getChar ( fPos ) ; if ( fChar == '' ) while ( fDocument . getChar ( ++ fPos ) != '' ) ; if ( fChar == opening || fChar == closing ) break ; fPos ++ ; } if ( fPos == fDocument . getLength ( ) ) return - ; if ( fChar == opening ) depth ++ ; else depth -- ; if ( depth == ) return fPos ; fPos ++ ; } } catch ( BadLocationException e ) { return - ; } } private int searchForOpeningPeer ( int start , char opening , char closing ) { try { int depth = ; int fPos = start - ; char fChar = ; while ( true ) { while ( fPos > - ) { fChar = fDocument . getChar ( fPos ) ; if ( fChar == '' ) while ( fDocument . getChar ( -- fPos ) != '' ) ; if ( fChar == opening || fChar == closing ) break ; fPos -- ; } if ( fPos == - ) return - ; if ( fChar == closing ) depth ++ ; else depth -- ; if ( depth == ) return fPos ; fPos -- ; } } catch ( BadLocationException e ) { return - ; } } } package net . sf . sveditor . ui . editor ; public interface ILiveSVDBChangeListener { void liveSVDBChanged ( ) ; } package net . sf . sveditor . ui . editor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . ui . editors . text . TextFileDocumentProvider ; public class SVEditorDocumentProvider extends TextFileDocumentProvider { private static SVEditorDocumentProvider fDefault ; protected FileInfo createFileInfo ( Object elem ) throws CoreException { FileInfo result = super . createFileInfo ( elem ) ; setUpSynchronization ( result ) ; return result ; } public static synchronized SVEditorDocumentProvider getDefault ( ) { if ( fDefault == null ) { fDefault = new SVEditorDocumentProvider ( ) ; } return fDefault ; } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . templates . GlobalTemplateVariables ; import org . eclipse . jface . text . templates . TemplateContextType ; public class SVTemplateContextType extends TemplateContextType { public SVTemplateContextType ( ) { addResolver ( new GlobalTemplateVariables . Cursor ( ) ) ; addResolver ( new GlobalTemplateVariables . WordSelection ( ) ) ; addResolver ( new GlobalTemplateVariables . LineSelection ( ) ) ; addResolver ( new GlobalTemplateVariables . Dollar ( ) ) ; addResolver ( new GlobalTemplateVariables . Date ( ) ) ; addResolver ( new GlobalTemplateVariables . Year ( ) ) ; addResolver ( new GlobalTemplateVariables . Time ( ) ) ; addResolver ( new GlobalTemplateVariables . User ( ) ) ; } public SVTemplateContextType ( String id ) { super ( id ) ; } public SVTemplateContextType ( String id , String name ) { super ( id , name ) ; } } package net . sf . sveditor . ui . editor ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension2 ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; final class PositionBasedCompletionProposal implements ICompletionProposal , ICompletionProposalExtension2 { private String fDisplayString ; private String fReplacementString ; private Position fReplacementPosition ; private int fCursorPosition ; private Image fImage ; private IContextInformation fContextInformation ; private String fAdditionalProposalInfo ; public PositionBasedCompletionProposal ( String replacementString , Position replacementPosition , int cursorPosition ) { this ( replacementString , replacementPosition , cursorPosition , null , null , null , null ) ; } public PositionBasedCompletionProposal ( String replacementString , Position replacementPosition , int cursorPosition , Image image , String displayString , IContextInformation contextInformation , String additionalProposalInfo ) { Assert . isNotNull ( replacementString ) ; Assert . isTrue ( replacementPosition != null ) ; fReplacementString = replacementString ; fReplacementPosition = replacementPosition ; fCursorPosition = cursorPosition ; fImage = image ; fDisplayString = displayString ; fContextInformation = contextInformation ; fAdditionalProposalInfo = additionalProposalInfo ; } public void apply ( IDocument document ) { try { document . replace ( fReplacementPosition . getOffset ( ) , fReplacementPosition . getLength ( ) , fReplacementString ) ; } catch ( BadLocationException x ) { } } public Point getSelection ( IDocument document ) { return new Point ( fReplacementPosition . getOffset ( ) + fCursorPosition , ) ; } public IContextInformation getContextInformation ( ) { return fContextInformation ; } public Image getImage ( ) { return fImage ; } public String getDisplayString ( ) { if ( fDisplayString != null ) return fDisplayString ; return fReplacementString ; } public String getAdditionalProposalInfo ( ) { return fAdditionalProposalInfo ; } public void apply ( ITextViewer viewer , char trigger , int stateMask , int offset ) { apply ( viewer . getDocument ( ) ) ; } public void selected ( ITextViewer viewer , boolean smartToggle ) { } public void unselected ( ITextViewer viewer ) { } public boolean validate ( IDocument document , int offset , DocumentEvent event ) { try { String content = document . get ( fReplacementPosition . getOffset ( ) , offset - fReplacementPosition . getOffset ( ) ) ; if ( fReplacementString . startsWith ( content ) ) return true ; } catch ( BadLocationException e ) { } return false ; } } package net . sf . sveditor . ui . editor ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Display ; public class SVColorManager { private static Map < RGB , Color > fColorMap = new HashMap < RGB , Color > ( ) ; public static synchronized Color getColor ( RGB color ) { Color ret = fColorMap . get ( color ) ; if ( ret == null ) { ret = new Color ( Display . getDefault ( ) , color ) ; fColorMap . put ( color , ret ) ; } return ret ; } public static synchronized void clear ( ) { fColorMap . clear ( ) ; } public static synchronized void dispose ( ) { for ( Color color : fColorMap . values ( ) ) { color . dispose ( ) ; } fColorMap . clear ( ) ; } } package net . sf . sveditor . ui . editor ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; public interface ISVEditor { ISVDBIndexIterator getIndexIterator ( ) ; IDocument getDocument ( ) ; ITextSelection getTextSel ( ) ; SVDBFile getSVDBFile ( ) ; } package net . sf . sveditor . ui . editor ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexUtil ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; public class UpdateProjectSettingsJob extends Job implements ILogLevel { private SVEditor fEditor ; private String fProjectName ; private LogHandle fLog ; public UpdateProjectSettingsJob ( SVEditor editor , String project_name ) { super ( editor . getTitle ( ) + "" ) ; fEditor = editor ; fProjectName = project_name ; fLog = LogFactory . getLogHandle ( "" ) ; } @ Override protected IStatus run ( IProgressMonitor monitor ) { fLog . debug ( LEVEL_MIN , "" + fEditor . getFilePath ( ) + "" ) ; Tuple < ISVDBIndex , SVDBIndexCollection > result ; String file_path = fEditor . getFilePath ( ) ; result = SVDBIndexUtil . findIndexFile ( file_path , fProjectName , true ) ; if ( result == null ) { fLog . error ( "" + fEditor . getFilePath ( ) + "" ) ; fEditor . int_projectSettingsUpdated ( null , null ) ; } else { fEditor . int_projectSettingsUpdated ( result . first ( ) , result . second ( ) ) ; } return Status . OK_STATUS ; } } package net . sf . sveditor . ui . editor ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . jface . resource . ImageRegistry ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . templates . ContextTypeRegistry ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . TemplateCompletionProcessor ; import org . eclipse . jface . text . templates . TemplateContext ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . eclipse . jface . text . templates . TemplateException ; import org . eclipse . swt . graphics . Image ; public class SVTemplateCompletionProcessor extends TemplateCompletionProcessor { private SVEditor fEditor ; private SVCompletionProcessor fSubProcessor ; @ SuppressWarnings ( "" ) private static final class ProposalComparator implements Comparator { public int compare ( Object o1 , Object o2 ) { return ( ( SVIndentingTemplateProposal ) o2 ) . getRelevance ( ) - ( ( SVIndentingTemplateProposal ) o1 ) . getRelevance ( ) ; } } @ SuppressWarnings ( "" ) private static final Comparator fgProposalComparator = new ProposalComparator ( ) ; public SVTemplateCompletionProcessor ( SVEditor editor ) { fEditor = editor ; fSubProcessor = new SVCompletionProcessor ( fEditor ) ; } @ Override public ICompletionProposal [ ] computeCompletionProposals ( ITextViewer viewer , int offset ) { List < ICompletionProposal > proposals = new ArrayList < ICompletionProposal > ( ) ; for ( ICompletionProposal p : computeTemplateCompletionProposals ( viewer , offset ) ) { proposals . add ( p ) ; } for ( ICompletionProposal p : fSubProcessor . computeCompletionProposals ( viewer , offset ) ) { proposals . add ( p ) ; } return proposals . toArray ( new ICompletionProposal [ proposals . size ( ) ] ) ; } @ SuppressWarnings ( "" ) private ICompletionProposal [ ] computeTemplateCompletionProposals ( ITextViewer viewer , int offset ) { ITextSelection selection = ( ITextSelection ) viewer . getSelectionProvider ( ) . getSelection ( ) ; if ( selection . getOffset ( ) == offset ) offset = selection . getOffset ( ) + selection . getLength ( ) ; String prefix = extractPrefix ( viewer , offset ) ; Region region = new Region ( offset - prefix . length ( ) , prefix . length ( ) ) ; TemplateContext context = createContext ( viewer , region ) ; if ( context == null ) return new ICompletionProposal [ ] ; context . setVariable ( "" , selection . getText ( ) ) ; Template [ ] templates = getTemplates ( context . getContextType ( ) . getId ( ) ) ; List < Object > matches = new ArrayList < Object > ( ) ; for ( int i = ; i < templates . length ; i ++ ) { Template template = templates [ i ] ; try { context . getContextType ( ) . validate ( template . getPattern ( ) ) ; } catch ( TemplateException e ) { continue ; } if ( context . getContextType ( ) . getId ( ) . equals ( template . getContextTypeId ( ) ) && ! prefix . trim ( ) . equals ( "" ) && template . getPattern ( ) . toLowerCase ( ) . startsWith ( prefix . toLowerCase ( ) ) ) { matches . add ( createProposal ( template , context , ( IRegion ) region , getRelevance ( template , prefix ) ) ) ; } } Collections . sort ( matches , fgProposalComparator ) ; return ( ICompletionProposal [ ] ) matches . toArray ( new ICompletionProposal [ matches . size ( ) ] ) ; } @ Override protected ICompletionProposal createProposal ( Template template , TemplateContext context , IRegion region , int relevance ) { return new SVIndentingTemplateProposal ( template , context , region , getImage ( template ) , relevance ) ; } @ Override protected TemplateContextType getContextType ( ITextViewer viewer , IRegion region ) { ContextTypeRegistry rgy = SVUiPlugin . getDefault ( ) . getContextTypeRegistry ( ) ; return rgy . getContextType ( SVUiPlugin . SV_TEMPLATE_CONTEXT ) ; } @ Override protected Image getImage ( Template template ) { ImageRegistry rgy = SVUiPlugin . getDefault ( ) . getImageRegistry ( ) ; return rgy . get ( "" ) ; } public Template [ ] getTemplates ( String contextId ) { return SVUiPlugin . getDefault ( ) . getTemplateStore ( ) . getTemplates ( ) ; } } package net . sf . sveditor . ui . editor ; import java . util . EnumMap ; import org . eclipse . jface . text . TextAttribute ; import org . eclipse . jface . text . source . SourceViewer ; public class SVHighlightingManager { private static EnumMap < SVEditorColors , TextAttribute > fHighlightAttr ; static { if ( fHighlightAttr == null ) { EnumMap < SVEditorColors , TextAttribute > tmp = new EnumMap < SVEditorColors , TextAttribute > ( SVEditorColors . class ) ; for ( SVEditorColors c : new SVEditorColors [ ] { SVEditorColors . KEYWORD , SVEditorColors . STRING } ) { tmp . put ( c , new TextAttribute ( SVEditorColors . getColor ( c ) , null , SVEditorColors . getStyle ( c ) ) ) ; } fHighlightAttr = tmp ; } } public void install ( SourceViewer viewer , SVPresentationReconciler rec , SVEditor editor ) { } public TextAttribute getHighlight ( SVEditorColors key ) { System . out . println ( "" + key ) ; return fHighlightAttr . get ( key ) ; } } package net . sf . sveditor . ui . editor ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBChildParent ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBNamedItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBModIfcInst ; import net . sf . sveditor . core . db . index . ISVDBChangeListener ; import net . sf . sveditor . core . db . stmt . SVDBVarDeclStmt ; import net . sf . sveditor . ui . SVDBIconUtils ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . actions . ToggleCommentAction ; import net . sf . sveditor . ui . pref . SVEditorPrefsConstants ; import net . sf . sveditor . ui . svcp . SVDBDecoratingLabelProvider ; import net . sf . sveditor . ui . svcp . SVDBDefaultContentFilter ; import net . sf . sveditor . ui . svcp . SVTreeContentProvider ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . viewers . IElementComparer ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreePath ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . ViewerComparator ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . part . IPageSite ; import org . eclipse . ui . part . IShowInTarget ; import org . eclipse . ui . part . ShowInContext ; import org . eclipse . ui . views . contentoutline . ContentOutlinePage ; public class SVOutlinePage extends ContentOutlinePage implements IShowInTarget , IAdaptable , Runnable , ISVDBChangeListener { private SVDBFile fSVDBFile ; private SVTreeContentProvider fContentProvider ; private SVEditor fEditor ; private boolean fIgnoreSelectionChange = false ; private ISVDBItemBase fLastSelection ; private Action ToggleAssign ; private Action ToggleAlways ; private Action ToggleDefines ; private Action ToggleInitial ; private Action ToggleGenerate ; private Action ToggleVariables ; private Action ToggleModuleInstances ; private Action ToggleInclude ; private Action ToggleTaskFunction ; private Action ToggleEnumTypedefs ; private Action ToggleAssertionProperties ; private Action ToggleCoverPointGroupCross ; private Action ToggleConstraints ; private Action ToggleSort ; private SVDBDefaultContentFilter DefaultContentFilter ; private ViewerComparator ViewerComapartor ; public SVOutlinePage ( SVEditor editor ) { fEditor = editor ; fContentProvider = new SVTreeContentProvider ( ) ; fSVDBFile = new SVDBFile ( "" ) ; } public void createControl ( Composite parent ) { super . createControl ( parent ) ; fContentProvider = new SVTreeContentProvider ( ) ; DefaultContentFilter = new SVDBDefaultContentFilter ( ) ; ViewerComapartor = new ViewerComparator ( ) ; DefaultContentFilter . HideAlwaysStatements ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ALWAYS_BLOCKS ) ) ; DefaultContentFilter . HideAssignStatements ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ASSIGN_STATEMENTS ) ) ; DefaultContentFilter . HideDefineStatements ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_DEFINE_STATEMENTS ) ) ; DefaultContentFilter . HideGenerateBlocks ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_GENERATE_BLOCKS ) ) ; DefaultContentFilter . HideIncludeFiles ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_INCLUDE_FILES ) ) ; DefaultContentFilter . HideInitialBlocks ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_INITIAL_BLOCKS ) ) ; DefaultContentFilter . HideModuleInstances ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_MODULE_INSTANCES ) ) ; DefaultContentFilter . HideTaskFunctions ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_TASK_FUNCTION_DECLARATIONS ) ) ; DefaultContentFilter . HideVariableDeclarations ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_SIGNAL_DECLARATIONS ) ) ; getTreeViewer ( ) . setContentProvider ( fContentProvider ) ; getTreeViewer ( ) . addFilter ( DefaultContentFilter ) ; if ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SORT ) ) { getTreeViewer ( ) . setComparator ( ViewerComapartor ) ; } else { getTreeViewer ( ) . setComparator ( null ) ; } getTreeViewer ( ) . setLabelProvider ( new SVDBDecoratingLabelProvider ( new SVTreeLabelProvider ( ) ) ) ; getTreeViewer ( ) . setComparer ( new IElementComparer ( ) { public int hashCode ( Object element ) { return element . hashCode ( ) ; } public boolean equals ( Object a , Object b ) { return ( a == b ) ; } } ) ; getTreeViewer ( ) . setInput ( fSVDBFile ) ; getTreeViewer ( ) . addSelectionChangedListener ( fSelectionListener ) ; getTreeViewer ( ) . setAutoExpandLevel ( TreeViewer . ALL_LEVELS ) ; refresh ( ) ; } public void SVDBFileChanged ( SVDBFile file , List < SVDBItem > adds , List < SVDBItem > removes , List < SVDBItem > changes ) { if ( file . getFilePath ( ) . equals ( fEditor . getFilePath ( ) ) ) { if ( getTreeViewer ( ) != null && ! getTreeViewer ( ) . getControl ( ) . isDisposed ( ) ) { Display . getDefault ( ) . asyncExec ( this ) ; } } } public void refresh ( ) { if ( getTreeViewer ( ) != null && ! getTreeViewer ( ) . getControl ( ) . isDisposed ( ) ) { Display . getDefault ( ) . asyncExec ( this ) ; } } public void run ( ) { if ( getTreeViewer ( ) != null && ! getTreeViewer ( ) . getControl ( ) . isDisposed ( ) ) { fSVDBFile = fEditor . getSVDBFile ( ) ; List < ISVDBItemBase > exp_path_list = getExpansionPaths ( ) ; ISelection sel = getTreeViewer ( ) . getSelection ( ) ; getTreeViewer ( ) . setInput ( fSVDBFile ) ; setExpansionPaths ( exp_path_list ) ; setSavedSelection ( sel ) ; } } private List < ISVDBItemBase > getExpansionPaths ( ) { List < ISVDBItemBase > ret = new ArrayList < ISVDBItemBase > ( ) ; for ( TreePath p : getTreeViewer ( ) . getExpandedTreePaths ( ) ) { Object last_seg_o = p . getLastSegment ( ) ; if ( last_seg_o instanceof ISVDBItemBase ) { ret . add ( ( ISVDBItemBase ) last_seg_o ) ; } } return ret ; } private void setExpansionPaths ( List < ISVDBItemBase > exp_paths ) { List < ISVDBItemBase > path = new ArrayList < ISVDBItemBase > ( ) ; List < ISVDBItemBase > target_path = new ArrayList < ISVDBItemBase > ( ) ; List < TreePath > exp_tree_paths = new ArrayList < TreePath > ( ) ; for ( ISVDBItemBase item : exp_paths ) { path . clear ( ) ; target_path . clear ( ) ; buildFullPath ( path , item ) ; lookupPath ( fSVDBFile , path . iterator ( ) , target_path ) ; if ( target_path . size ( ) > ) { exp_tree_paths . add ( new TreePath ( target_path . toArray ( ) ) ) ; } } if ( exp_tree_paths . size ( ) > ) { getTreeViewer ( ) . setExpandedTreePaths ( exp_tree_paths . toArray ( new TreePath [ exp_tree_paths . size ( ) ] ) ) ; } } private void buildFullPath ( List < ISVDBItemBase > path , ISVDBItemBase leaf ) { ISVDBItemBase item_tmp = leaf ; while ( item_tmp != null && item_tmp . getType ( ) != SVDBItemType . File ) { if ( ! ( item_tmp instanceof SVDBVarDeclStmt ) && ! ( item_tmp instanceof SVDBModIfcInst ) ) { path . add ( , item_tmp ) ; } if ( item_tmp instanceof ISVDBChildItem ) { item_tmp = ( ( ISVDBChildItem ) item_tmp ) . getParent ( ) ; } else { item_tmp = null ; } } } private void setSavedSelection ( ISelection sel ) { fIgnoreSelectionChange = true ; if ( ! sel . isEmpty ( ) && sel instanceof IStructuredSelection ) { List < ISVDBItemBase > path = new ArrayList < ISVDBItemBase > ( ) ; IStructuredSelection ss = ( IStructuredSelection ) sel ; List < ISVDBItemBase > new_sel_l = new ArrayList < ISVDBItemBase > ( ) ; List < ISVDBItemBase > target_path = new ArrayList < ISVDBItemBase > ( ) ; for ( Object sel_it : ss . toList ( ) ) { if ( sel_it instanceof ISVDBItemBase ) { path . clear ( ) ; target_path . clear ( ) ; buildFullPath ( path , ( ISVDBItemBase ) sel_it ) ; if ( lookupPath ( fSVDBFile , path . iterator ( ) , target_path ) ) { ISVDBItemBase sel_t = target_path . get ( target_path . size ( ) - ) ; new_sel_l . add ( sel_t ) ; } } } StructuredSelection new_sel = new StructuredSelection ( new_sel_l ) ; getTreeViewer ( ) . setSelection ( new_sel ) ; } } private boolean lookupPath ( ISVDBChildParent scope , Iterator < ISVDBItemBase > path_it , List < ISVDBItemBase > target_path ) { ISVDBItemBase path_item = path_it . next ( ) ; ISVDBItemBase target_item = null ; boolean ret = false ; if ( ! ( path_item instanceof ISVDBNamedItem ) ) { return ret ; } ISVDBNamedItem ni = ( ISVDBNamedItem ) path_item ; for ( ISVDBChildItem ci : scope . getChildren ( ) ) { if ( ci instanceof ISVDBNamedItem ) { ISVDBNamedItem ci_ni = ( ISVDBNamedItem ) ci ; if ( ni . getName ( ) . equals ( ci_ni . getName ( ) ) && ni . getType ( ) == ci_ni . getType ( ) ) { target_item = ci ; break ; } } else if ( ci instanceof SVDBVarDeclStmt || ci instanceof SVDBModIfcInst ) { ISVDBChildParent inst_list = ( ISVDBChildParent ) ci ; for ( ISVDBChildItem ci_inst : inst_list . getChildren ( ) ) { ISVDBNamedItem ci_inst_ni = ( ISVDBNamedItem ) ci_inst ; if ( ni . getName ( ) . equals ( ci_inst_ni . getName ( ) ) && ni . getType ( ) == ci_inst_ni . getType ( ) ) { target_item = ci_inst ; break ; } } if ( target_item != null ) { break ; } } else { } } if ( target_item != null ) { target_path . add ( target_item ) ; } if ( path_it . hasNext ( ) && target_item != null && target_item instanceof ISVDBChildParent ) { ret = lookupPath ( ( ISVDBChildParent ) target_item , path_it , target_path ) ; } else if ( ! path_it . hasNext ( ) && target_item != null ) { ret = true ; } return ret ; } public void dispose ( ) { if ( getTreeViewer ( ) != null ) { getTreeViewer ( ) . removeSelectionChangedListener ( fSelectionListener ) ; } } @ SuppressWarnings ( "" ) public Object getAdapter ( Class adapter ) { if ( IShowInTarget . class . equals ( adapter ) ) { return this ; } return null ; } public boolean show ( ShowInContext context ) { return true ; } private ISelectionChangedListener fSelectionListener = new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { if ( fIgnoreSelectionChange ) { fIgnoreSelectionChange = false ; return ; } removeSelectionChangedListener ( this ) ; if ( event . getSelection ( ) instanceof StructuredSelection ) { StructuredSelection sel = ( StructuredSelection ) event . getSelection ( ) ; if ( sel . getFirstElement ( ) instanceof ISVDBItemBase ) { ISVDBItemBase it = ( ISVDBItemBase ) sel . getFirstElement ( ) ; if ( fLastSelection == null || ! fLastSelection . equals ( it , true ) ) { fEditor . setSelection ( it , false ) ; fLastSelection = it ; } } } addSelectionChangedListener ( this ) ; } } ; public void createActions ( ) { } private class SortAction extends Action { public SortAction ( ) { super ( "" , Action . AS_CHECK_BOX ) ; setImageDescriptor ( SVUiPlugin . getImageDescriptor ( "" ) ) ; } public void run ( ) { boolean new_value = true ; if ( SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SORT ) ) { new_value = false ; } SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SORT , new_value ) ; ToggleSort . setChecked ( new_value ) ; if ( new_value ) { getTreeViewer ( ) . setComparator ( ViewerComapartor ) ; } else { getTreeViewer ( ) . setComparator ( null ) ; } refresh ( ) ; } } @ Override public void init ( IPageSite pageSite ) { super . init ( pageSite ) ; ToggleSort = new SortAction ( ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleSort ) ; ToggleAssign = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleAssign . setChecked ( DefaultContentFilter . ToggleAssignStatements ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ASSIGN_STATEMENTS , ToggleAssign . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleAssign . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . Assign ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleAssign ) ; ToggleAlways = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleAlways . setChecked ( DefaultContentFilter . ToggleAlwaysStatements ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ALWAYS_BLOCKS , ToggleAlways . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleAlways . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . AlwaysStmt ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleAlways ) ; ToggleDefines = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleDefines . setChecked ( DefaultContentFilter . ToggleDefineStatements ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_DEFINE_STATEMENTS , ToggleDefines . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleDefines . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . MacroDef ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleDefines ) ; ToggleInitial = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleInitial . setChecked ( DefaultContentFilter . ToggleInitialBlocks ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_INITIAL_BLOCKS , ToggleInitial . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleInitial . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . InitialStmt ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleInitial ) ; ToggleGenerate = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleGenerate . setChecked ( DefaultContentFilter . ToggleGenerateBlocks ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_GENERATE_BLOCKS , ToggleGenerate . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleGenerate . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . GenerateBlock ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleGenerate ) ; ToggleVariables = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleVariables . setChecked ( DefaultContentFilter . ToggleVariableDeclarations ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_SIGNAL_DECLARATIONS , ToggleVariables . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleVariables . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . VarDeclItem ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleVariables ) ; ToggleModuleInstances = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleModuleInstances . setChecked ( DefaultContentFilter . ToggleModuleInstances ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_MODULE_INSTANCES , ToggleModuleInstances . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleModuleInstances . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . ModIfcInst ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleModuleInstances ) ; ToggleInclude = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleInclude . setChecked ( DefaultContentFilter . ToggleIncludeFiles ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_INCLUDE_FILES , ToggleInclude . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleInclude . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . Include ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleInclude ) ; ToggleTaskFunction = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleTaskFunction . setChecked ( DefaultContentFilter . ToggleTaskFunctions ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_TASK_FUNCTION_DECLARATIONS , ToggleTaskFunction . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleTaskFunction . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . Task ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleTaskFunction ) ; ToggleEnumTypedefs = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleEnumTypedefs . setChecked ( DefaultContentFilter . ToggleEnumTypedefs ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ENUM_TYPEDEFS , ToggleEnumTypedefs . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleEnumTypedefs . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . TypedefStmt ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleEnumTypedefs ) ; ToggleConstraints = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleConstraints . setChecked ( DefaultContentFilter . ToggleConstraints ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_CONSTRAINTS , ToggleConstraints . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleConstraints . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . Constraint ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleConstraints ) ; ToggleAssertionProperties = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleAssertionProperties . setChecked ( DefaultContentFilter . ToggleAssertionProperties ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ASSERTION_PROPERTIES , ToggleAssertionProperties . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleAssertionProperties . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . Property ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleAssertionProperties ) ; ToggleCoverPointGroupCross = new Action ( "" , Action . AS_CHECK_BOX ) { public void run ( ) { ToggleCoverPointGroupCross . setChecked ( DefaultContentFilter . ToggleCoverPointGroupCross ( ) ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( SVEditorPrefsConstants . P_OUTLINE_SHOW_COVER_POINT_GROUP_CROSS , ToggleCoverPointGroupCross . isChecked ( ) ) ; refresh ( ) ; } } ; ToggleCoverPointGroupCross . setImageDescriptor ( SVDBIconUtils . getImageDescriptor ( SVDBItemType . Coverpoint ) ) ; pageSite . getActionBars ( ) . getToolBarManager ( ) . add ( ToggleCoverPointGroupCross ) ; IPreferenceStore ps = SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) ; ToggleSort . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SORT ) ) ; ToggleAlways . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ALWAYS_BLOCKS ) ) ; ToggleAssign . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ASSIGN_STATEMENTS ) ) ; ToggleDefines . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_DEFINE_STATEMENTS ) ) ; ToggleGenerate . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_GENERATE_BLOCKS ) ) ; ToggleInclude . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_INCLUDE_FILES ) ) ; ToggleInitial . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_INITIAL_BLOCKS ) ) ; ToggleModuleInstances . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_MODULE_INSTANCES ) ) ; ToggleTaskFunction . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_TASK_FUNCTION_DECLARATIONS ) ) ; ToggleEnumTypedefs . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ENUM_TYPEDEFS ) ) ; ToggleAssertionProperties . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_ASSERTION_PROPERTIES ) ) ; ToggleCoverPointGroupCross . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_COVER_POINT_GROUP_CROSS ) ) ; ToggleConstraints . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_CONSTRAINTS ) ) ; ToggleVariables . setChecked ( ps . getBoolean ( SVEditorPrefsConstants . P_OUTLINE_SHOW_SIGNAL_DECLARATIONS ) ) ; } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . formatter . ContextBasedFormattingStrategy ; public class SVFormattingStrategy extends ContextBasedFormattingStrategy { @ Override public void format ( ) { super . format ( ) ; System . out . println ( "" ) ; } @ Override public String format ( String content , boolean start , String indentation , int [ ] positions ) { System . out . println ( "" + content + "" + start + "" + indentation + "" ) ; return super . format ( content , start , indentation , positions ) ; } } package net . sf . sveditor . ui . editor ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . indent . ISVIndenter ; import net . sf . sveditor . core . indent . SVIndentScanner ; import net . sf . sveditor . core . scanutils . StringBIDITextScanner ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPositionCategoryException ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension2 ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension3 ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . link . ILinkedModeListener ; import org . eclipse . jface . text . link . InclusivePositionUpdater ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . jface . text . link . LinkedModeUI ; import org . eclipse . jface . text . link . LinkedPosition ; import org . eclipse . jface . text . link . LinkedPositionGroup ; import org . eclipse . jface . text . link . ProposalPosition ; import org . eclipse . jface . text . templates . DocumentTemplateContext ; import org . eclipse . jface . text . templates . GlobalTemplateVariables ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . TemplateBuffer ; import org . eclipse . jface . text . templates . TemplateContext ; import org . eclipse . jface . text . templates . TemplateException ; import org . eclipse . jface . text . templates . TemplateVariable ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Shell ; public class SVIndentingTemplateProposal implements ICompletionProposal , ICompletionProposalExtension , ICompletionProposalExtension2 , ICompletionProposalExtension3 { private final Template fTemplate ; private final TemplateContext fContext ; private final Image fImage ; private final IRegion fRegion ; private int fRelevance ; private IRegion fSelectedRegion ; private String fDisplayString ; private InclusivePositionUpdater fUpdater ; private IInformationControlCreator fInformationControlCreator ; public SVIndentingTemplateProposal ( Template template , TemplateContext context , IRegion region , Image image , int relevance ) { Assert . isNotNull ( template ) ; Assert . isNotNull ( context ) ; Assert . isNotNull ( region ) ; fTemplate = template ; fContext = context ; fImage = image ; fRegion = region ; fDisplayString = null ; fRelevance = relevance ; } public final void setInformationControlCreator ( IInformationControlCreator informationControlCreator ) { fInformationControlCreator = informationControlCreator ; } protected final Template getTemplate ( ) { return fTemplate ; } protected final TemplateContext getContext ( ) { return fContext ; } public final void apply ( IDocument document ) { } public void apply ( ITextViewer viewer , char trigger , int stateMask , int offset ) { IDocument document = viewer . getDocument ( ) ; try { fContext . setReadOnly ( false ) ; int start ; TemplateBuffer templateBuffer ; { int oldReplaceOffset = getReplaceOffset ( ) ; start = getReplaceOffset ( ) ; int shift = start - oldReplaceOffset ; int end = Math . max ( getReplaceEndOffset ( ) , offset + shift ) ; try { String pattern = indent_proposal ( document , offset , fTemplate . getPattern ( ) . substring ( end - start ) ) ; Template template_t = new Template ( fTemplate . getName ( ) , fTemplate . getDescription ( ) , fTemplate . getContextTypeId ( ) , pattern , fTemplate . isAutoInsertable ( ) ) ; templateBuffer = fContext . evaluate ( template_t ) ; } catch ( TemplateException e1 ) { fSelectedRegion = fRegion ; return ; } String templateString = templateBuffer . getString ( ) ; document . replace ( start , end - start , templateString ) ; } LinkedModeModel model = new LinkedModeModel ( ) ; TemplateVariable [ ] variables = templateBuffer . getVariables ( ) ; boolean hasPositions = false ; for ( int i = ; i != variables . length ; i ++ ) { TemplateVariable variable = variables [ i ] ; if ( variable . isUnambiguous ( ) ) continue ; LinkedPositionGroup group = new LinkedPositionGroup ( ) ; int [ ] offsets = variable . getOffsets ( ) ; int length = variable . getLength ( ) ; LinkedPosition first ; { String [ ] values = variable . getValues ( ) ; ICompletionProposal [ ] proposals = new ICompletionProposal [ values . length ] ; for ( int j = ; j < values . length ; j ++ ) { ensurePositionCategoryInstalled ( document , model ) ; Position pos = new Position ( offsets [ ] + start , length ) ; document . addPosition ( getCategory ( ) , pos ) ; proposals [ j ] = new PositionBasedCompletionProposal ( values [ j ] , pos , length ) ; } if ( proposals . length > ) first = new ProposalPosition ( document , offsets [ ] + start , length , proposals ) ; else first = new LinkedPosition ( document , offsets [ ] + start , length ) ; } for ( int j = ; j != offsets . length ; j ++ ) if ( j == ) group . addPosition ( first ) ; else group . addPosition ( new LinkedPosition ( document , offsets [ j ] + start , length ) ) ; model . addGroup ( group ) ; hasPositions = true ; } if ( hasPositions ) { model . forceInstall ( ) ; LinkedModeUI ui = new LinkedModeUI ( model , viewer ) ; ui . setExitPosition ( viewer , getCaretOffset ( templateBuffer ) + start , , Integer . MAX_VALUE ) ; ui . enter ( ) ; fSelectedRegion = ui . getSelectedRegion ( ) ; } else { ensurePositionCategoryRemoved ( document ) ; fSelectedRegion = new Region ( getCaretOffset ( templateBuffer ) + start , ) ; } } catch ( BadLocationException e ) { openErrorDialog ( viewer . getTextWidget ( ) . getShell ( ) , e ) ; ensurePositionCategoryRemoved ( document ) ; fSelectedRegion = fRegion ; } catch ( BadPositionCategoryException e ) { openErrorDialog ( viewer . getTextWidget ( ) . getShell ( ) , e ) ; fSelectedRegion = fRegion ; } } private void ensurePositionCategoryInstalled ( final IDocument document , LinkedModeModel model ) { if ( ! document . containsPositionCategory ( getCategory ( ) ) ) { document . addPositionCategory ( getCategory ( ) ) ; fUpdater = new InclusivePositionUpdater ( getCategory ( ) ) ; document . addPositionUpdater ( fUpdater ) ; model . addLinkingListener ( new ILinkedModeListener ( ) { public void left ( LinkedModeModel environment , int flags ) { ensurePositionCategoryRemoved ( document ) ; } public void suspend ( LinkedModeModel environment ) { } public void resume ( LinkedModeModel environment , int flags ) { } } ) ; } } private void ensurePositionCategoryRemoved ( IDocument document ) { if ( document . containsPositionCategory ( getCategory ( ) ) ) { try { document . removePositionCategory ( getCategory ( ) ) ; } catch ( BadPositionCategoryException e ) { } document . removePositionUpdater ( fUpdater ) ; } } private String getCategory ( ) { return "" + toString ( ) ; } private int getCaretOffset ( TemplateBuffer buffer ) { TemplateVariable [ ] variables = buffer . getVariables ( ) ; for ( int i = ; i != variables . length ; i ++ ) { TemplateVariable variable = variables [ i ] ; if ( variable . getType ( ) . equals ( GlobalTemplateVariables . Cursor . NAME ) ) return variable . getOffsets ( ) [ ] ; } return buffer . getString ( ) . length ( ) ; } protected final int getReplaceOffset ( ) { int start ; if ( fContext instanceof DocumentTemplateContext ) { DocumentTemplateContext docContext = ( DocumentTemplateContext ) fContext ; start = docContext . getStart ( ) ; } else { start = fRegion . getOffset ( ) ; } return start ; } protected final int getReplaceEndOffset ( ) { int end ; if ( fContext instanceof DocumentTemplateContext ) { DocumentTemplateContext docContext = ( DocumentTemplateContext ) fContext ; end = docContext . getEnd ( ) ; } else { end = fRegion . getOffset ( ) + fRegion . getLength ( ) ; } return end ; } public Point getSelection ( IDocument document ) { return new Point ( fSelectedRegion . getOffset ( ) , fSelectedRegion . getLength ( ) ) ; } public String getAdditionalProposalInfo ( ) { try { fContext . setReadOnly ( true ) ; TemplateBuffer templateBuffer ; try { templateBuffer = fContext . evaluate ( fTemplate ) ; } catch ( TemplateException e ) { return null ; } return templateBuffer . getString ( ) ; } catch ( BadLocationException e ) { return null ; } } public String getDisplayString ( ) { if ( fDisplayString == null ) { fDisplayString = fTemplate . getName ( ) + "" + fTemplate . getDescription ( ) ; } return fDisplayString ; } public Image getImage ( ) { return fImage ; } public IContextInformation getContextInformation ( ) { return null ; } private void openErrorDialog ( Shell shell , Exception e ) { MessageDialog . openError ( shell , "" , e . getMessage ( ) ) ; } public int getRelevance ( ) { return fRelevance ; } public IInformationControlCreator getInformationControlCreator ( ) { return fInformationControlCreator ; } public void selected ( ITextViewer viewer , boolean smartToggle ) { } public void unselected ( ITextViewer viewer ) { } public boolean validate ( IDocument document , int offset , DocumentEvent event ) { try { int replaceOffset = getReplaceOffset ( ) ; if ( offset >= replaceOffset ) { String content = document . get ( replaceOffset , offset - replaceOffset ) ; return fTemplate . getName ( ) . toLowerCase ( ) . startsWith ( content . toLowerCase ( ) ) ; } } catch ( BadLocationException e ) { } return false ; } public CharSequence getPrefixCompletionText ( IDocument document , int completionOffset ) { return fTemplate . getName ( ) ; } public int getPrefixCompletionStart ( IDocument document , int completionOffset ) { return getReplaceOffset ( ) ; } public void apply ( IDocument document , char trigger , int offset ) { } public boolean isValidFor ( IDocument document , int offset ) { return false ; } public char [ ] getTriggerCharacters ( ) { return new char [ ] ; } public int getContextInformationPosition ( ) { return fRegion . getOffset ( ) ; } public String indent_proposal ( IDocument doc , int offset , String text ) { try { int lineno = doc . getLineOfOffset ( offset ) ; int length = ; int target_lineno = lineno ; int line_cnt = ; for ( int i = ; i < text . length ( ) ; i ++ ) { if ( text . charAt ( i ) == '' ) { line_cnt ++ ; } } StringBuilder doc_str = new StringBuilder ( ) ; doc_str . append ( doc . get ( , offset ) ) ; doc_str . append ( text ) ; int start = offset + length ; int len = ( doc . getLength ( ) - ( offset + length ) - ) ; try { if ( len > ) { doc_str . append ( doc . get ( start , len ) ) ; } } catch ( BadLocationException e ) { System . out . println ( "" + start + "" + len + "" + doc . getLength ( ) ) ; throw e ; } StringBIDITextScanner text_scanner = new StringBIDITextScanner ( doc_str . toString ( ) ) ; ISVIndenter indenter = SVCorePlugin . getDefault ( ) . createIndenter ( ) ; SVIndentScanner scanner = new SVIndentScanner ( text_scanner ) ; indenter . init ( scanner ) ; indenter . setAdaptiveIndent ( true ) ; indenter . setAdaptiveIndentEnd ( target_lineno + ) ; try { text = indenter . indent ( lineno + , ( lineno + line_cnt + ) ) ; while ( text . length ( ) > && Character . isWhitespace ( text . charAt ( ) ) && text . charAt ( ) != '' ) { text = text . substring ( ) ; } if ( text . charAt ( text . length ( ) - ) == '' ) { text = text . substring ( , text . length ( ) - ) ; } } catch ( Exception e ) { } } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } return text ; } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . templates . TemplateVariableResolver ; public class SVContextTemplateVariableResolver extends TemplateVariableResolver { public SVContextTemplateVariableResolver ( ) { super ( ) ; } } package net . sf . sveditor . ui . editor ; import java . io . File ; import java . net . URI ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import java . util . ResourceBundle ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . SVFileUtils ; import net . sf . sveditor . core . StringInputStream ; import net . sf . sveditor . core . Tuple ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBMarker ; import net . sf . sveditor . core . db . SVDBMarker . MarkerType ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBFileOverrideIndex ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . index . SVDBIndexUtil ; import net . sf . sveditor . core . db . index . SVDBShadowIndexFactory ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibDescriptor ; import net . sf . sveditor . core . db . index . plugin_lib . SVDBPluginLibIndexFactory ; import net . sf . sveditor . core . db . project . ISVDBProjectSettingsListener ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . actions . AddBlockCommentAction ; import net . sf . sveditor . ui . editor . actions . FindReferencesAction ; import net . sf . sveditor . ui . editor . actions . IndentAction ; import net . sf . sveditor . ui . editor . actions . NextWordAction ; import net . sf . sveditor . ui . editor . actions . OpenDeclarationAction ; import net . sf . sveditor . ui . editor . actions . OpenDiagForSelectionAction ; import net . sf . sveditor . ui . editor . actions . OpenObjectsViewAction ; import net . sf . sveditor . ui . editor . actions . OpenQuickHierarchyAction ; import net . sf . sveditor . ui . editor . actions . OpenQuickObjectsViewAction ; import net . sf . sveditor . ui . editor . actions . OpenQuickOutlineAction ; import net . sf . sveditor . ui . editor . actions . OpenTypeAction ; import net . sf . sveditor . ui . editor . actions . OpenTypeHierarchyAction ; import net . sf . sveditor . ui . editor . actions . OverrideTaskFuncAction ; import net . sf . sveditor . ui . editor . actions . PrevWordAction ; import net . sf . sveditor . ui . editor . actions . RemoveBlockCommentAction ; import net . sf . sveditor . ui . editor . actions . SelNextWordAction ; import net . sf . sveditor . ui . editor . actions . SelPrevWordAction ; import net . sf . sveditor . ui . editor . actions . ToggleCommentAction ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewerExtension2 ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . information . IInformationPresenter ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . ISourceViewerExtension2 ; import org . eclipse . jface . text . source . MatchingCharacterPainter ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorSite ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . IURIEditorInput ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . editors . text . ITextEditorHelpContextIds ; import org . eclipse . ui . editors . text . TextEditor ; import org . eclipse . ui . ide . IDEActionFactory ; import org . eclipse . ui . part . FileEditorInput ; import org . eclipse . ui . texteditor . AddTaskAction ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . eclipse . ui . texteditor . ResourceAction ; import org . eclipse . ui . texteditor . TextOperationAction ; import org . eclipse . ui . views . contentoutline . IContentOutlinePage ; public class SVEditor extends TextEditor implements ISVDBProjectSettingsListener , ISVEditor , ILogLevel { private SVOutlinePage fOutline ; private SVHighlightingManager fHighlightManager ; private SVCodeScanner fCodeScanner ; private MatchingCharacterPainter fMatchingCharacterPainter ; private SVCharacterPairMatcher fCharacterMatcher ; private SVDBFile fSVDBFile ; private SVDBFile fSVDBFilePP ; private SVDBFileOverrideIndex fSVDBIndex ; private List < SVDBMarker > fMarkers ; private String fFile ; private SVDBIndexCollection fIndexMgr ; private LogHandle fLog ; private String fSVDBFilePath ; private UpdateProjectSettingsJob fProjectSettingsJob ; private SVDBProjectData fPendingProjectSettingsUpdate ; private UpdateSVDBFileJob fUpdateSVDBFileJob ; private boolean fPendingUpdateSVDBFile ; IInformationPresenter fQuickObjectsPresenter ; IInformationPresenter fQuickOutlinePresenter ; IInformationPresenter fQuickHierarchyPresenter ; public ISVDBIndex getSVDBIndex ( ) { return fSVDBIndex ; } public IInformationPresenter getQuickObjectsPresenter ( ) { if ( fQuickObjectsPresenter == null ) { fQuickObjectsPresenter = ( ( SVSourceViewerConfiguration ) getSourceViewerConfiguration ( ) ) . getObjectsPresenter ( getSourceViewer ( ) , false ) ; if ( fQuickObjectsPresenter != null ) { fQuickObjectsPresenter . install ( getSourceViewer ( ) ) ; } } return fQuickObjectsPresenter ; } public IInformationPresenter getQuickOutlinePresenter ( ) { if ( fQuickOutlinePresenter == null ) { fQuickOutlinePresenter = ( ( SVSourceViewerConfiguration ) getSourceViewerConfiguration ( ) ) . getOutlinePresenter ( getSourceViewer ( ) , false ) ; if ( fQuickOutlinePresenter != null ) { fQuickOutlinePresenter . install ( getSourceViewer ( ) ) ; } } return fQuickOutlinePresenter ; } public IInformationPresenter getQuickHierarchyPresenter ( ) { if ( fQuickHierarchyPresenter == null ) { fQuickHierarchyPresenter = ( ( SVSourceViewerConfiguration ) getSourceViewerConfiguration ( ) ) . getHierarchyPresenter ( getSourceViewer ( ) , false ) ; if ( fQuickHierarchyPresenter != null ) { fQuickHierarchyPresenter . install ( getSourceViewer ( ) ) ; } } return fQuickHierarchyPresenter ; } private class UpdateSVDBFileJob extends Job { public UpdateSVDBFileJob ( ) { super ( "" ) ; } @ Override protected IStatus run ( IProgressMonitor monitor ) { IEditorInput ed_in = getEditorInput ( ) ; IDocument doc = getDocumentProvider ( ) . getDocument ( ed_in ) ; StringInputStream sin = new StringInputStream ( doc . get ( ) ) ; List < SVDBMarker > markers = new ArrayList < SVDBMarker > ( ) ; Tuple < SVDBFile , SVDBFile > new_in = fIndexMgr . parse ( getProgressMonitor ( ) , sin , fSVDBFilePath , markers ) ; fSVDBFile . clearChildren ( ) ; if ( new_in != null ) { fSVDBFile = new_in . second ( ) ; fSVDBFilePP = new_in . first ( ) ; fSVDBIndex . setFile ( fSVDBFile ) ; fSVDBIndex . setFilePP ( fSVDBFilePP ) ; addErrorMarkers ( markers ) ; } if ( fOutline != null ) { fOutline . refresh ( ) ; } synchronized ( SVEditor . this ) { fUpdateSVDBFileJob = null ; if ( fPendingUpdateSVDBFile ) { updateSVDBFile ( ) ; } } return Status . OK_STATUS ; } } public SVEditor ( ) { super ( ) ; fMarkers = new ArrayList < SVDBMarker > ( ) ; setDocumentProvider ( SVEditorDocumentProvider . getDefault ( ) ) ; fCodeScanner = new SVCodeScanner ( ) ; fCharacterMatcher = new SVCharacterPairMatcher ( ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . addPropertyChangeListener ( fPropertyChangeListener ) ; fLog = LogFactory . getLogHandle ( "" ) ; SVUiPlugin . getDefault ( ) . startRefreshJob ( ) ; } @ Override public void init ( IEditorSite site , IEditorInput input ) throws PartInitException { super . init ( site , input ) ; if ( input instanceof IURIEditorInput ) { URI uri = ( ( IURIEditorInput ) input ) . getURI ( ) ; if ( uri . getScheme ( ) . equals ( "" ) ) { fFile = "" + uri . getPath ( ) ; } else { fFile = uri . getPath ( ) ; } } else if ( input instanceof IFileEditorInput ) { fFile = ( ( IFileEditorInput ) input ) . getFile ( ) . getFullPath ( ) . toOSString ( ) ; } fSVDBFile = new SVDBFile ( fFile ) ; fSVDBFilePP = new SVDBFile ( fFile ) ; IDocument doc = getDocument ( ) ; int idx = ; int replacements = ; try { while ( idx < doc . getLength ( ) ) { int ch = doc . getChar ( idx ) ; if ( ch == '' ) { if ( idx + < doc . getLength ( ) && doc . getChar ( idx + ) != '' ) { doc . replace ( idx , , "" ) ; replacements ++ ; } else if ( idx + >= doc . getLength ( ) ) { doc . replace ( idx , , "" ) ; replacements ++ ; } } idx ++ ; } } catch ( BadLocationException e ) { } if ( replacements > ) { fLog . note ( "" + replacements + "" + fFile ) ; } initSVDBMgr ( ) ; } @ Override public void doSave ( IProgressMonitor progressMonitor ) { super . doSave ( progressMonitor ) ; } @ Override public void doSaveAs ( ) { super . doSaveAs ( ) ; } public void projectSettingsChanged ( SVDBProjectData data ) { fLog . debug ( LEVEL_MID , "" + fSVDBFilePath ) ; synchronized ( this ) { if ( fProjectSettingsJob == null ) { fProjectSettingsJob = new UpdateProjectSettingsJob ( this , data . getName ( ) ) ; fProjectSettingsJob . schedule ( ) ; fPendingProjectSettingsUpdate = null ; } else { fPendingProjectSettingsUpdate = data ; } } } public void int_projectSettingsUpdated ( final ISVDBIndex index , final SVDBIndexCollection index_mgr ) { fLog . debug ( LEVEL_MIN , "" + fSVDBFilePath + "" + ( ( index != null ) ? ( index . getTypeID ( ) + "" + index . getBaseLocation ( ) ) : "" ) + "" + ( ( index_mgr != null ) ? ( index_mgr . getProject ( ) ) : "" ) ) ; final SVActionContributor ac = ( SVActionContributor ) getEditorSite ( ) . getActionBarContributor ( ) ; getEditorSite ( ) . getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { String msg = "" ; if ( index != null ) { if ( index . getTypeID ( ) . equals ( SVDBShadowIndexFactory . TYPE ) ) { msg = "" ; } else { msg = "" + index . getBaseLocation ( ) ; } } else { msg = "" ; } ac . getActionBars ( ) . getStatusLineManager ( ) . setMessage ( msg ) ; } } ) ; synchronized ( this ) { fProjectSettingsJob = null ; fIndexMgr = index_mgr ; fSVDBIndex = new SVDBFileOverrideIndex ( fSVDBFile , fSVDBFilePP , index , fIndexMgr , fMarkers ) ; } if ( fPendingProjectSettingsUpdate != null ) { projectSettingsChanged ( fPendingProjectSettingsUpdate ) ; } else { updateSVDBFile ( ) ; } } private void initSVDBMgr ( ) { IEditorInput ed_in = getEditorInput ( ) ; SVActionContributor ac = ( SVActionContributor ) getEditorSite ( ) . getActionBarContributor ( ) ; ac . getActionBars ( ) . getStatusLineManager ( ) . setMessage ( "" ) ; if ( ed_in instanceof IURIEditorInput ) { IURIEditorInput uri_in = ( IURIEditorInput ) ed_in ; SVDBProjectManager mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; if ( uri_in . getURI ( ) . getScheme ( ) . equals ( "" ) ) { fLog . debug ( LEVEL_MIN , "" + uri_in . getURI ( ) ) ; fSVDBFilePath = "" + uri_in . getURI ( ) . getPath ( ) ; fSVDBFilePath = SVFileUtils . normalize ( fSVDBFilePath ) ; SVDBPluginLibDescriptor target = null ; String uri_path = uri_in . getURI ( ) . getPath ( ) ; String plugin = uri_path . substring ( , uri_path . indexOf ( '' , ) ) ; String root_file = uri_path . substring ( uri_path . indexOf ( '' , ) ) ; for ( SVDBPluginLibDescriptor d : SVCorePlugin . getDefault ( ) . getPluginLibList ( ) ) { if ( d . getNamespace ( ) . equals ( plugin ) ) { String root_dir = new File ( d . getPath ( ) ) . getParent ( ) ; if ( ! root_dir . startsWith ( "" ) ) { root_dir = "" + root_dir ; } if ( root_file . startsWith ( root_dir ) ) { target = d ; break ; } } } fIndexMgr = new SVDBIndexCollection ( rgy . getIndexCollectionMgr ( ) , plugin ) ; if ( target != null ) { fLog . debug ( LEVEL_MIN , "" ) ; fIndexMgr . addPluginLibrary ( rgy . findCreateIndex ( new NullProgressMonitor ( ) , SVDBIndexRegistry . GLOBAL_PROJECT , target . getId ( ) , SVDBPluginLibIndexFactory . TYPE , null ) ) ; } else { fLog . debug ( LEVEL_MIN , "" ) ; } } else { if ( ed_in instanceof FileEditorInput ) { FileEditorInput fi = ( FileEditorInput ) ed_in ; fLog . debug ( LEVEL_MIN , "" + fi . getFile ( ) . getFullPath ( ) + "" + fi . getFile ( ) . getProject ( ) . getName ( ) ) ; fSVDBFilePath = "" + fi . getFile ( ) . getFullPath ( ) . toOSString ( ) ; fSVDBFilePath = SVFileUtils . normalize ( fSVDBFilePath ) ; fLog . debug ( LEVEL_MIN , "" + fSVDBFilePath ) ; projectSettingsChanged ( mgr . getProjectData ( fi . getFile ( ) . getProject ( ) ) ) ; mgr . addProjectSettingsListener ( this ) ; } else { fLog . debug ( LEVEL_MIN , "" + uri_in . getClass ( ) . getName ( ) ) ; fSVDBFilePath = SVFileUtils . normalize ( uri_in . getURI ( ) . getPath ( ) ) ; fLog . debug ( LEVEL_MIN , "" + uri_in . getURI ( ) . getPath ( ) + "" + fSVDBFilePath + "" ) ; fLog . debug ( LEVEL_MIN , "" + fSVDBFilePath + "" ) ; fIndexMgr = null ; Tuple < ISVDBIndex , SVDBIndexCollection > result = SVDBIndexUtil . findIndexFile ( fSVDBFilePath , null , true ) ; fIndexMgr = result . second ( ) ; fSVDBIndex = new SVDBFileOverrideIndex ( fSVDBFile , fSVDBFilePP , result . first ( ) , fIndexMgr , fMarkers ) ; fLog . debug ( LEVEL_MIN , "" + fSVDBIndex . getBaseLocation ( ) + "" ) ; } } } else { fLog . error ( "" + ed_in . getClass ( ) . getName ( ) ) ; } } void updateSVDBFile ( ) { fLog . debug ( LEVEL_MAX , "" + fIndexMgr ) ; if ( fIndexMgr != null ) { if ( fUpdateSVDBFileJob == null ) { synchronized ( this ) { fPendingUpdateSVDBFile = false ; fUpdateSVDBFileJob = new UpdateSVDBFileJob ( ) ; fUpdateSVDBFileJob . schedule ( ) ; } } else { fPendingUpdateSVDBFile = true ; } } } public SVCodeScanner getCodeScanner ( ) { return fCodeScanner ; } @ Override protected void initializeKeyBindingScopes ( ) { setKeyBindingScopes ( new String [ ] { SVUiPlugin . PLUGIN_ID + "" } ) ; } @ SuppressWarnings ( "" ) @ Override protected void createActions ( ) { super . createActions ( ) ; ResourceBundle bundle = SVUiPlugin . getDefault ( ) . getResources ( ) ; IAction a = new TextOperationAction ( bundle , "" , this , ISourceViewer . CONTENTASSIST_PROPOSALS ) ; a . setActionDefinitionId ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS ) ; setAction ( "" , a ) ; a = new TextOperationAction ( bundle , "" , this , ISourceViewer . CONTENTASSIST_CONTEXT_INFORMATION ) ; a . setActionDefinitionId ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_CONTEXT_INFORMATION ) ; setAction ( "" , a ) ; ResourceAction ra = new AddTaskAction ( bundle , "" , this ) ; ra . setHelpContextId ( ITextEditorHelpContextIds . ADD_TASK_ACTION ) ; ra . setActionDefinitionId ( ITextEditorActionDefinitionIds . ADD_TASK ) ; setAction ( IDEActionFactory . ADD_TASK . getId ( ) , ra ) ; OpenDeclarationAction od_action = new OpenDeclarationAction ( bundle , this ) ; od_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , od_action ) ; markAsStateDependentAction ( SVUiPlugin . PLUGIN_ID + "" , false ) ; markAsSelectionDependentAction ( SVUiPlugin . PLUGIN_ID + "" , false ) ; FindReferencesAction fr_action = new FindReferencesAction ( bundle , this ) ; fr_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , fr_action ) ; markAsStateDependentAction ( SVUiPlugin . PLUGIN_ID + "" , false ) ; markAsSelectionDependentAction ( SVUiPlugin . PLUGIN_ID + "" , false ) ; OpenTypeAction ot_action = new OpenTypeAction ( bundle , this ) ; ot_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , ot_action ) ; OpenTypeHierarchyAction th_action = new OpenTypeHierarchyAction ( bundle , this ) ; th_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , th_action ) ; OpenObjectsViewAction ov_action = new OpenObjectsViewAction ( bundle ) ; ov_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , ov_action ) ; OpenQuickObjectsViewAction qov_action = new OpenQuickObjectsViewAction ( bundle , this ) ; qov_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , qov_action ) ; OpenQuickOutlineAction qoutv_action = new OpenQuickOutlineAction ( bundle , this ) ; qoutv_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , qoutv_action ) ; OpenQuickHierarchyAction qh_action = new OpenQuickHierarchyAction ( bundle , this ) ; qh_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , qh_action ) ; OpenDiagForSelectionAction ods_action = new OpenDiagForSelectionAction ( bundle , this ) ; ods_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , ods_action ) ; IndentAction ind_action = new IndentAction ( bundle , "" , this ) ; ind_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , ind_action ) ; AddBlockCommentAction add_block_comment = new AddBlockCommentAction ( bundle , "" , this ) ; add_block_comment . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; add_block_comment . setEnabled ( true ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , add_block_comment ) ; RemoveBlockCommentAction remove_block_comment = new RemoveBlockCommentAction ( bundle , "" , this ) ; remove_block_comment . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; remove_block_comment . setEnabled ( true ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , remove_block_comment ) ; ToggleCommentAction toggle_comment = new ToggleCommentAction ( bundle , "" , this ) ; toggle_comment . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; toggle_comment . setEnabled ( true ) ; toggle_comment . configure ( getSourceViewer ( ) , getSourceViewerConfiguration ( ) ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , toggle_comment ) ; OverrideTaskFuncAction ov_tf_action = new OverrideTaskFuncAction ( bundle , "" , this ) ; ov_tf_action . setActionDefinitionId ( SVUiPlugin . PLUGIN_ID + "" ) ; setAction ( SVUiPlugin . PLUGIN_ID + "" , ov_tf_action ) ; NextWordAction nw_action = new NextWordAction ( bundle , "" , this ) ; nw_action . setActionDefinitionId ( ITextEditorActionDefinitionIds . WORD_NEXT ) ; setAction ( ITextEditorActionDefinitionIds . WORD_NEXT , nw_action ) ; PrevWordAction pw_action = new PrevWordAction ( bundle , "" , this ) ; pw_action . setActionDefinitionId ( ITextEditorActionDefinitionIds . WORD_PREVIOUS ) ; setAction ( ITextEditorActionDefinitionIds . WORD_PREVIOUS , pw_action ) ; SelNextWordAction sel_nw_action = new SelNextWordAction ( bundle , "" , this ) ; sel_nw_action . setActionDefinitionId ( ITextEditorActionDefinitionIds . SELECT_WORD_NEXT ) ; setAction ( ITextEditorActionDefinitionIds . SELECT_WORD_NEXT , sel_nw_action ) ; SelPrevWordAction sel_pw_action = new SelPrevWordAction ( bundle , "" , this ) ; sel_pw_action . setActionDefinitionId ( ITextEditorActionDefinitionIds . SELECT_WORD_PREVIOUS ) ; setAction ( ITextEditorActionDefinitionIds . SELECT_WORD_PREVIOUS , sel_pw_action ) ; } public ISVDBIndexIterator getIndexIterator ( ) { return fSVDBIndex ; } public IDocument getDocument ( ) { return getDocumentProvider ( ) . getDocument ( getEditorInput ( ) ) ; } public ITextSelection getTextSel ( ) { ITextSelection sel = null ; ISelection sel_o = getSelectionProvider ( ) . getSelection ( ) ; if ( sel_o != null && sel_o instanceof ITextSelection ) { sel = ( ITextSelection ) sel_o ; } return sel ; } protected void editorContextMenuAboutToShow ( IMenuManager menu ) { super . editorContextMenuAboutToShow ( menu ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , SVUiPlugin . PLUGIN_ID + "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , SVUiPlugin . PLUGIN_ID + "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , SVUiPlugin . PLUGIN_ID + "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , SVUiPlugin . PLUGIN_ID + "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , SVUiPlugin . PLUGIN_ID + "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , SVUiPlugin . PLUGIN_ID + "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , SVUiPlugin . PLUGIN_ID + "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_EDIT , SVUiPlugin . PLUGIN_ID + "" ) ; addAction ( menu , ITextEditorActionConstants . GROUP_FIND , SVUiPlugin . PLUGIN_ID + "" ) ; addGroup ( menu , ITextEditorActionConstants . GROUP_EDIT , "" ) ; } @ Override public void dispose ( ) { super . dispose ( ) ; if ( fOutline != null ) { fOutline . dispose ( ) ; fOutline = null ; } if ( fCharacterMatcher != null ) { fCharacterMatcher . dispose ( ) ; fCharacterMatcher = null ; } SVCorePlugin . getDefault ( ) . getProjMgr ( ) . removeProjectSettingsListener ( this ) ; SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) . removePropertyChangeListener ( fPropertyChangeListener ) ; fSVDBIndex = null ; fIndexMgr = null ; } public void createPartControl ( Composite parent ) { setSourceViewerConfiguration ( new SVSourceViewerConfiguration ( this ) ) ; super . createPartControl ( parent ) ; if ( fHighlightManager == null ) { fHighlightManager = new SVHighlightingManager ( ) ; fHighlightManager . install ( ( SourceViewer ) getSourceViewer ( ) , ( SVPresentationReconciler ) getSourceViewerConfiguration ( ) . getPresentationReconciler ( getSourceViewer ( ) ) , this ) ; } if ( fMatchingCharacterPainter == null ) { if ( getSourceViewer ( ) instanceof ISourceViewerExtension2 ) { fMatchingCharacterPainter = new MatchingCharacterPainter ( getSourceViewer ( ) , fCharacterMatcher ) ; Display display = Display . getCurrent ( ) ; fMatchingCharacterPainter . setColor ( display . getSystemColor ( SWT . COLOR_GRAY ) ) ; ( ( ITextViewerExtension2 ) getSourceViewer ( ) ) . addPainter ( fMatchingCharacterPainter ) ; } } } public SVDBFile getSVDBFile ( ) { return fSVDBFile ; } public String getFilePath ( ) { return fSVDBFilePath ; } public void setSelection ( ISVDBItemBase it , boolean set_cursor ) { int start = - ; int end = - ; if ( it . getLocation ( ) != null ) { start = it . getLocation ( ) . getLine ( ) ; if ( it instanceof ISVDBScopeItem && ( ( ISVDBScopeItem ) it ) . getEndLocation ( ) != null ) { end = ( ( ISVDBScopeItem ) it ) . getEndLocation ( ) . getLine ( ) ; } setSelection ( start , end , set_cursor ) ; } } public void setSelection ( int start , int end , boolean set_cursor ) { IDocument doc = getDocumentProvider ( ) . getDocument ( getEditorInput ( ) ) ; if ( start > ) { start -- ; } if ( end == - ) { end = start ; } try { int offset = doc . getLineOffset ( start ) ; int last_line = doc . getLineOfOffset ( doc . getLength ( ) - ) ; if ( end > last_line ) { end = last_line ; } int offset_e = doc . getLineOffset ( end ) ; setHighlightRange ( offset , ( offset_e - offset ) , false ) ; if ( set_cursor ) { getSourceViewer ( ) . getTextWidget ( ) . setCaretOffset ( offset ) ; } selectAndReveal ( offset , , offset , ( offset_e - offset ) ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } } public ISourceViewer sourceViewer ( ) { return getSourceViewer ( ) ; } @ SuppressWarnings ( "" ) private void clearErrors ( ) { if ( getDocumentProvider ( ) == null || getEditorInput ( ) == null || getDocumentProvider ( ) . getAnnotationModel ( getEditorInput ( ) ) == null ) { return ; } IAnnotationModel ann_model = getDocumentProvider ( ) . getAnnotationModel ( getEditorInput ( ) ) ; Iterator < Annotation > ann_it = ann_model . getAnnotationIterator ( ) ; while ( ann_it . hasNext ( ) ) { Annotation ann = ann_it . next ( ) ; if ( ann . getType ( ) . equals ( "" ) ) { ann_model . removeAnnotation ( ann ) ; } } } private void addErrorMarkers ( List < SVDBMarker > markers ) { if ( getDocumentProvider ( ) == null || getEditorInput ( ) == null || getDocumentProvider ( ) . getAnnotationModel ( getEditorInput ( ) ) == null ) { return ; } clearErrors ( ) ; IAnnotationModel ann_model = getDocumentProvider ( ) . getAnnotationModel ( getEditorInput ( ) ) ; for ( SVDBMarker marker : markers ) { Annotation ann = null ; int line = - ; if ( marker . getMarkerType ( ) == MarkerType . Error ) { ann = new Annotation ( "" , false , marker . getMessage ( ) ) ; line = marker . getLocation ( ) . getLine ( ) ; } if ( ann != null ) { IDocument doc = getDocumentProvider ( ) . getDocument ( getEditorInput ( ) ) ; try { Position pos = new Position ( doc . getLineOffset ( line - ) ) ; ann_model . addAnnotation ( ann , pos ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } } } } @ Override @ SuppressWarnings ( "" ) public Object getAdapter ( Class adapter ) { if ( adapter . equals ( IContentOutlinePage . class ) ) { if ( fOutline == null ) { fOutline = new SVOutlinePage ( this ) ; } return fOutline ; } return super . getAdapter ( adapter ) ; } private IPropertyChangeListener fPropertyChangeListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { SVColorManager . clear ( ) ; getCodeScanner ( ) . updateRules ( ) ; getSourceViewer ( ) . getTextWidget ( ) . redraw ( ) ; getSourceViewer ( ) . getTextWidget ( ) . update ( ) ; } } ; } package net . sf . sveditor . ui . editor ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . pref . SVEditorPrefsConstants ; import net . sf . sveditor . ui . text . HierarchyInformationControl ; import net . sf . sveditor . ui . text . ObjectsInformationControl ; import net . sf . sveditor . ui . text . OutlineInformationControl ; import net . sf . sveditor . ui . text . SVEditorProvider ; import net . sf . sveditor . ui . text . SVElementProvider ; import net . sf . sveditor . ui . text . hover . ISVEditorTextHover ; import net . sf . sveditor . ui . text . hover . SVDocHover ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . text . AbstractInformationControlManager ; import org . eclipse . jface . text . IAutoEditStrategy ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . jface . text . TextAttribute ; import org . eclipse . jface . text . contentassist . ContentAssistant ; import org . eclipse . jface . text . contentassist . IContentAssistProcessor ; import org . eclipse . jface . text . contentassist . IContentAssistant ; import org . eclipse . jface . text . information . IInformationPresenter ; import org . eclipse . jface . text . information . IInformationProvider ; import org . eclipse . jface . text . information . InformationPresenter ; import org . eclipse . jface . text . presentation . IPresentationReconciler ; import org . eclipse . jface . text . presentation . PresentationReconciler ; import org . eclipse . jface . text . reconciler . IReconciler ; import org . eclipse . jface . text . reconciler . MonoReconciler ; import org . eclipse . jface . text . rules . BufferedRuleBasedScanner ; import org . eclipse . jface . text . rules . DefaultDamagerRepairer ; import org . eclipse . jface . text . rules . Token ; import org . eclipse . jface . text . source . DefaultAnnotationHover ; import org . eclipse . jface . text . source . IAnnotationHover ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . texteditor . AbstractDecoratedTextEditorPreferenceConstants ; public class SVSourceViewerConfiguration extends SourceViewerConfiguration { private SVEditor fEditor ; private ContentAssistant fContentAssist ; public SVSourceViewerConfiguration ( SVEditor editor ) { fEditor = editor ; } @ Override public String [ ] getIndentPrefixes ( ISourceViewer sourceViewer , String contentType ) { String prefix = SVUiPlugin . getDefault ( ) . getIndentIncr ( ) ; return new String [ ] { prefix , "" } ; } @ Override public int getTabWidth ( ISourceViewer sourceViewer ) { IPreferenceStore chainedPrefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; chainedPrefs . getBoolean ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SPACES_FOR_TABS ) ; int tab_width = chainedPrefs . getInt ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_TAB_WIDTH ) ; return tab_width ; } @ Override public IContentAssistant getContentAssistant ( ISourceViewer sourceViewer ) { if ( fContentAssist == null ) { fContentAssist = new ContentAssistant ( ) ; IContentAssistProcessor p = new SVTemplateCompletionProcessor ( fEditor ) ; fContentAssist . setContentAssistProcessor ( p , IDocument . DEFAULT_CONTENT_TYPE ) ; fContentAssist . setInformationControlCreator ( getInformationControlCreator ( sourceViewer ) ) ; fContentAssist . enableAutoActivation ( true ) ; fContentAssist . enableAutoInsert ( true ) ; fContentAssist . enablePrefixCompletion ( true ) ; } return fContentAssist ; } @ Override public IAutoEditStrategy [ ] getAutoEditStrategies ( ISourceViewer sourceViewer , String contentType ) { String partitioning = getConfiguredDocumentPartitioning ( sourceViewer ) ; if ( contentType . equals ( SVDocumentPartitions . SV_MULTILINE_COMMENT ) ) { return new IAutoEditStrategy [ ] { new SVMultiLineCommentAutoIndentStrategy ( partitioning ) } ; } else { List < IAutoEditStrategy > ret = new ArrayList < IAutoEditStrategy > ( ) ; IAutoEditStrategy ss [ ] = super . getAutoEditStrategies ( sourceViewer , contentType ) ; ret . add ( new SVAutoIndentStrategy ( fEditor , partitioning ) ) ; for ( IAutoEditStrategy si : ss ) { ret . add ( si ) ; } return ret . toArray ( new IAutoEditStrategy [ ret . size ( ) ] ) ; } } @ Override public String [ ] getConfiguredContentTypes ( ISourceViewer viewer ) { return new String [ ] { IDocument . DEFAULT_CONTENT_TYPE , SVDocumentPartitions . SV_MULTILINE_COMMENT , SVDocumentPartitions . SV_SINGLELINE_COMMENT , SVDocumentPartitions . SV_STRING , SVDocumentPartitions . SV_KEYWORD } ; } @ Override public IPresentationReconciler getPresentationReconciler ( ISourceViewer viewer ) { PresentationReconciler r = new SVPresentationReconciler ( ) ; r . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( viewer ) ) ; DefaultDamagerRepairer dr ; if ( fEditor != null ) { dr = new DefaultDamagerRepairer ( fEditor . getCodeScanner ( ) ) ; } else { dr = new DefaultDamagerRepairer ( new SVCodeScanner ( ) ) ; } r . setDamager ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; r . setRepairer ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; BufferedRuleBasedScanner scanner ; scanner = new BufferedRuleBasedScanner ( ) ; scanner . setDefaultReturnToken ( new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . MULTI_LINE_COMMENT ) , null , SVEditorColors . getStyle ( SVEditorColors . MULTI_LINE_COMMENT ) ) ) ) ; dr = new DefaultDamagerRepairer ( scanner ) ; r . setDamager ( dr , SVDocumentPartitions . SV_MULTILINE_COMMENT ) ; r . setRepairer ( dr , SVDocumentPartitions . SV_MULTILINE_COMMENT ) ; scanner = new BufferedRuleBasedScanner ( ) ; scanner . setDefaultReturnToken ( new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . SINGLE_LINE_COMMENT ) , null , SVEditorColors . getStyle ( SVEditorColors . SINGLE_LINE_COMMENT ) ) ) ) ; dr = new DefaultDamagerRepairer ( scanner ) ; r . setDamager ( dr , SVDocumentPartitions . SV_SINGLELINE_COMMENT ) ; r . setRepairer ( dr , SVDocumentPartitions . SV_SINGLELINE_COMMENT ) ; return r ; } @ Override public String getConfiguredDocumentPartitioning ( ISourceViewer viewer ) { return SVDocumentPartitions . SV_PARTITIONING ; } @ Override public IReconciler getReconciler ( ISourceViewer viewer ) { return new MonoReconciler ( new SVReconcilingStrategy ( fEditor ) , false ) ; } @ Override public IAnnotationHover getAnnotationHover ( ISourceViewer viewer ) { return new DefaultAnnotationHover ( ) ; } @ Override public String [ ] getDefaultPrefixes ( ISourceViewer sourceViewer , String contentType ) { return new String [ ] { "" , "" } ; } public ITextHover getTextHover ( ISourceViewer viewer , String contentType ) { if ( ! contentType . equals ( SVDocumentPartitions . SV_STRING ) && ! contentType . equals ( SVDocumentPartitions . SV_MULTILINE_COMMENT ) && ! contentType . equals ( SVDocumentPartitions . SV_SINGLELINE_COMMENT ) ) { ISVEditorTextHover hover = new SVDocHover ( ) ; hover . setEditor ( fEditor ) ; return hover ; } return null ; } private IInformationControlCreator getObjectsPresenterControlCreator ( ISourceViewer sourceViewer , final String commandId ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { IPreferenceStore prefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; Color bg_color = SVColorManager . getColor ( PreferenceConverter . getColor ( prefs , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_BG_COLOR ) ) ; Color fg_color = SVColorManager . getColor ( PreferenceConverter . getColor ( prefs , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_FG_COLOR ) ) ; int shellStyle = SWT . RESIZE ; int treeStyle = SWT . V_SCROLL | SWT . H_SCROLL ; ObjectsInformationControl obj = new ObjectsInformationControl ( parent , shellStyle , treeStyle , commandId ) ; obj . setBackgroundColor ( bg_color ) ; obj . setForegroundColor ( fg_color ) ; return obj ; } } ; } private IInformationControlCreator getOutlinePresenterControlCreator ( ISourceViewer sourceViewer , final String commandId ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { IPreferenceStore prefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; Color bg_color = SVColorManager . getColor ( PreferenceConverter . getColor ( prefs , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_BG_COLOR ) ) ; Color fg_color = SVColorManager . getColor ( PreferenceConverter . getColor ( prefs , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_FG_COLOR ) ) ; int shellStyle = SWT . RESIZE ; int treeStyle = SWT . V_SCROLL | SWT . H_SCROLL ; OutlineInformationControl outline = new OutlineInformationControl ( parent , shellStyle , treeStyle , commandId ) ; outline . setBackgroundColor ( bg_color ) ; outline . setForegroundColor ( fg_color ) ; return outline ; } } ; } private IInformationControlCreator getHierarchyPresenterControlCreator ( ISourceViewer sourceViewer , final String commandId ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { IPreferenceStore prefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; Color bg_color = SVColorManager . getColor ( PreferenceConverter . getColor ( prefs , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_BG_COLOR ) ) ; Color fg_color = SVColorManager . getColor ( PreferenceConverter . getColor ( prefs , SVEditorPrefsConstants . P_CONTENT_ASSIST_HOVER_FG_COLOR ) ) ; int shellStyle = SWT . RESIZE ; int treeStyle = SWT . V_SCROLL | SWT . H_SCROLL ; HierarchyInformationControl h = new HierarchyInformationControl ( parent , shellStyle , treeStyle , commandId ) ; h . setBackgroundColor ( bg_color ) ; h . setForegroundColor ( fg_color ) ; return h ; } } ; } public IInformationPresenter getObjectsPresenter ( ISourceViewer sourceViewer , boolean doCodeResolve ) { InformationPresenter presenter ; presenter = new InformationPresenter ( getObjectsPresenterControlCreator ( sourceViewer , SVUiPlugin . PLUGIN_ID + "" ) ) ; presenter . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( sourceViewer ) ) ; presenter . setAnchor ( AbstractInformationControlManager . ANCHOR_GLOBAL ) ; IInformationProvider provider = new SVEditorProvider ( fEditor ) ; presenter . setInformationProvider ( provider , IDocument . DEFAULT_CONTENT_TYPE ) ; presenter . setSizeConstraints ( , , true , false ) ; return presenter ; } public IInformationPresenter getOutlinePresenter ( ISourceViewer sourceViewer , boolean doCodeResolve ) { InformationPresenter presenter ; presenter = new InformationPresenter ( getOutlinePresenterControlCreator ( sourceViewer , SVUiPlugin . PLUGIN_ID + "" ) ) ; presenter . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( sourceViewer ) ) ; presenter . setAnchor ( AbstractInformationControlManager . ANCHOR_GLOBAL ) ; IInformationProvider provider = new SVEditorProvider ( fEditor ) ; presenter . setInformationProvider ( provider , IDocument . DEFAULT_CONTENT_TYPE ) ; presenter . setSizeConstraints ( , , true , false ) ; return presenter ; } public IInformationPresenter getHierarchyPresenter ( ISourceViewer sourceViewer , boolean doCodeResolve ) { InformationPresenter presenter ; presenter = new InformationPresenter ( getHierarchyPresenterControlCreator ( sourceViewer , SVUiPlugin . PLUGIN_ID + "" ) ) ; presenter . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( sourceViewer ) ) ; presenter . setAnchor ( AbstractInformationControlManager . ANCHOR_GLOBAL ) ; IInformationProvider provider = new SVElementProvider ( fEditor ) ; presenter . setInformationProvider ( provider , IDocument . DEFAULT_CONTENT_TYPE ) ; presenter . setSizeConstraints ( , , true , false ) ; return presenter ; } } package net . sf . sveditor . ui . editor ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . scanner . SVCharacter ; import net . sf . sveditor . core . scanner . SVKeywords ; import org . eclipse . jface . text . TextAttribute ; import org . eclipse . jface . text . rules . EndOfLineRule ; import org . eclipse . jface . text . rules . IRule ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . IWordDetector ; import org . eclipse . jface . text . rules . MultiLineRule ; import org . eclipse . jface . text . rules . RuleBasedScanner ; import org . eclipse . jface . text . rules . SingleLineRule ; import org . eclipse . jface . text . rules . Token ; import org . eclipse . jface . text . rules . WordRule ; public class SVCodeScanner extends RuleBasedScanner { public SVCodeScanner ( ) { updateRules ( ) ; } public void updateRules ( ) { IToken keyword = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . KEYWORD ) , null , SVEditorColors . getStyle ( SVEditorColors . KEYWORD ) ) ) ; final IToken str = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . STRING ) , null , SVEditorColors . getStyle ( SVEditorColors . STRING ) ) ) ; final IToken slc = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . SINGLE_LINE_COMMENT ) , null , SVEditorColors . getStyle ( SVEditorColors . SINGLE_LINE_COMMENT ) ) ) ; final IToken mlc = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . MULTI_LINE_COMMENT ) , null , SVEditorColors . getStyle ( SVEditorColors . MULTI_LINE_COMMENT ) ) ) ; IToken default_t = new Token ( new TextAttribute ( SVEditorColors . getColor ( SVEditorColors . DEFAULT ) , null , SVEditorColors . getStyle ( SVEditorColors . DEFAULT ) ) ) ; setDefaultReturnToken ( default_t ) ; List < IRule > rules = new ArrayList < IRule > ( ) ; rules . add ( new EndOfLineRule ( "" , slc ) ) ; rules . add ( new MultiLineRule ( "" , "" , mlc , ( char ) , true ) ) ; rules . add ( new SingleLineRule ( "" , "" , str , '' ) ) ; WordRule wordRule = new WordRule ( new IWordDetector ( ) { public boolean isWordPart ( char c ) { return SVCharacter . isSVIdentifierPart ( c ) ; } public boolean isWordStart ( char c ) { return SVCharacter . isSVIdentifierStart ( c ) ; } } , default_t ) ; for ( String kw : SVKeywords . getKeywords ( ) ) { String kw_p = kw ; if ( kw . endsWith ( "" ) ) { kw_p = kw . substring ( , kw . length ( ) - ) ; } wordRule . addWord ( kw_p , keyword ) ; } for ( String kw : SVKeywords . getSystemCalls ( ) ) { String kw_p = kw ; if ( kw . endsWith ( "" ) ) { kw_p = kw . substring ( , kw . length ( ) - ) ; } wordRule . addWord ( kw_p , keyword ) ; } rules . add ( wordRule ) ; rules . add ( new WordRule ( new IWordDetector ( ) { public boolean isWordPart ( char c ) { return SVCharacter . isSVIdentifierPart ( c ) ; } public boolean isWordStart ( char c ) { return ( c == '' ) ; } } , keyword ) ) ; IRule [ ] ruleArray = rules . toArray ( new IRule [ rules . size ( ) ] ) ; setRules ( ruleArray ) ; } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . source . DefaultCharacterPairMatcher ; public class SVPairMatcher extends DefaultCharacterPairMatcher { public SVPairMatcher ( char pairs [ ] ) { super ( pairs , SVDocumentPartitions . SV_PARTITIONING ) ; } } package net . sf . sveditor . ui . editor ; import org . eclipse . jface . text . rules . ICharacterScanner ; import org . eclipse . jface . text . rules . IPredicateRule ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . Token ; public class CCommentRule implements IPredicateRule { private IToken fToken ; public CCommentRule ( IToken tok ) { fToken = tok ; } public IToken evaluate ( ICharacterScanner scanner , boolean resume ) { boolean in_comment = resume ; if ( ! resume ) { if ( scanner . read ( ) == '' ) { if ( scanner . read ( ) == '' ) { in_comment = true ; } scanner . unread ( ) ; } else { scanner . unread ( ) ; } } if ( in_comment ) { scanToEnd ( scanner ) ; return fToken ; } return Token . UNDEFINED ; } private void scanToEnd ( ICharacterScanner scanner ) { int ch_a [ ] = { - , - } ; int ch ; while ( ( ch = scanner . read ( ) ) != ICharacterScanner . EOF ) { ch_a [ ] = ch_a [ ] ; ch_a [ ] = ch ; if ( ch_a [ ] == '' && ch_a [ ] == '' ) { break ; } } } public IToken evaluate ( ICharacterScanner scanner ) { return evaluate ( scanner , false ) ; } public IToken getSuccessToken ( ) { return fToken ; } } package net . sf . sveditor . ui . editor ; public class GenerateGroupActions { public GenerateGroupActions ( SVEditor editor , String group ) { } } package net . sf . sveditor . ui . scanutils ; import net . sf . sveditor . core . scanutils . AbstractTextScanner ; import net . sf . sveditor . core . scanutils . IBIDITextScanner ; import net . sf . sveditor . core . scanutils . ScanLocation ; import net . sf . sveditor . ui . editor . SVDocumentPartitions ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPartitioningException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . ITypedRegion ; public class SVDocumentTextScanner extends AbstractTextScanner implements IBIDITextScanner { private IDocument fDoc ; private int fIdx ; private int fOffset ; private int fLimit ; private String fName ; private int fUngetCh ; private boolean fSkipComments ; public SVDocumentTextScanner ( IDocument doc , String name , int offset , boolean scan_fwd , boolean skip_comments ) { fDoc = doc ; fName = name ; fOffset = - ; fIdx = offset ; fScanFwd = scan_fwd ; fUngetCh = - ; fLimit = - ; fSkipComments = skip_comments ; } public SVDocumentTextScanner ( IDocument doc , int offset ) { this ( doc , "" , offset , true , false ) ; } public SVDocumentTextScanner ( IDocument doc , int offset , int limit ) { this ( doc , "" , offset , true , false ) ; fOffset = offset ; fLimit = limit ; } public void setSkipComments ( boolean skip_comments ) { fSkipComments = skip_comments ; } public void setScanFwd ( boolean scan_fwd ) { if ( fScanFwd != scan_fwd ) { fUngetCh = - ; } super . setScanFwd ( scan_fwd ) ; } public long getPos ( ) { return ( long ) fIdx ; } public void seek ( long pos ) { fIdx = ( int ) pos ; fUngetCh = - ; } public String get_str ( long start , int length ) { try { return fDoc . get ( ( int ) start , length ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; return null ; } } public ScanLocation getLocation ( ) { int lineno = - ; int linepos = - ; try { int off = fIdx < ( fDoc . getLength ( ) ) ? fIdx : fDoc . getLength ( ) - ; lineno = fDoc . getLineOfOffset ( off ) ; linepos = off - fDoc . getLineOffset ( off ) ; } catch ( BadLocationException e ) { } return new ScanLocation ( fName , lineno , linepos ) ; } public int get_ch ( ) { int ch = - ; if ( fUngetCh != - ) { ch = fUngetCh ; fUngetCh = - ; } else { try { IDocumentExtension3 ext3 = ( IDocumentExtension3 ) fDoc ; if ( fScanFwd ) { while ( ( fLimit == - && ( fIdx < fDoc . getLength ( ) ) ) || ( fLimit != - && ( fIdx <= fLimit ) ) ) { ITypedRegion r = null ; try { r = ext3 . getPartition ( SVDocumentPartitions . SV_PARTITIONING , fIdx , false ) ; } catch ( BadPartitioningException e ) { } if ( ! fSkipComments || ( r != null && ! r . getType ( ) . equals ( SVDocumentPartitions . SV_MULTILINE_COMMENT ) && ! r . getType ( ) . equals ( SVDocumentPartitions . SV_SINGLELINE_COMMENT ) ) ) { ch = fDoc . getChar ( fIdx ) ; fIdx ++ ; break ; } else { if ( fIdx == r . getOffset ( ) ) { ch = '' ; fIdx ++ ; break ; } else { fIdx ++ ; } } } } else { while ( fIdx >= fOffset ) { ITypedRegion r = null ; try { r = ext3 . getPartition ( SVDocumentPartitions . SV_PARTITIONING , fIdx , false ) ; } catch ( BadPartitioningException e ) { } if ( ! fSkipComments || ( r != null && ! r . getType ( ) . equals ( SVDocumentPartitions . SV_MULTILINE_COMMENT ) && ! r . getType ( ) . equals ( SVDocumentPartitions . SV_SINGLELINE_COMMENT ) ) ) { if ( fIdx >= fDoc . getLength ( ) ) { fIdx = fDoc . getLength ( ) - ; } ch = fDoc . getChar ( fIdx ) ; fIdx -- ; break ; } else { if ( fIdx == ( r . getOffset ( ) + r . getLength ( ) - ) ) { ch = '' ; fIdx -- ; break ; } else { fIdx -- ; } } } } } catch ( BadLocationException e ) { } } return ch ; } public void unget_ch ( int ch ) { if ( fScanFwd ) { fIdx -- ; } else { fIdx ++ ; } } } package net . sf . sveditor . ui ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; import java . util . StringTokenizer ; import java . util . WeakHashMap ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . XMLTransformUtils ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . log . ILogHandle ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . ILogListener ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . templates . IExternalTemplatePathProvider ; import net . sf . sveditor . core . templates . ITemplateParameterProvider ; import net . sf . sveditor . core . templates . TemplateParameterProvider ; import net . sf . sveditor . core . templates . TemplateRegistry ; import net . sf . sveditor . ui . pref . SVEditorPrefsConstants ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . templates . ContextTypeRegistry ; import org . eclipse . jface . text . templates . persistence . TemplateStore ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . console . ConsolePlugin ; import org . eclipse . ui . console . IConsole ; import org . eclipse . ui . console . MessageConsole ; import org . eclipse . ui . console . MessageConsoleStream ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . editors . text . templates . ContributionContextTypeRegistry ; import org . eclipse . ui . editors . text . templates . ContributionTemplateStore ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . eclipse . ui . texteditor . AbstractDecoratedTextEditorPreferenceConstants ; import org . eclipse . ui . texteditor . ChainedPreferenceStore ; import org . osgi . framework . BundleContext ; public class SVUiPlugin extends AbstractUIPlugin implements IPropertyChangeListener , ILogListener , IExternalTemplatePathProvider { private class LogMessage { ILogHandle handle ; int type ; int level ; String message ; } public static final String PLUGIN_ID = "" ; private static SVUiPlugin fPlugin ; private ResourceBundle fResources ; private WeakHashMap < String , Image > fImageMap ; private MessageConsole fConsole ; private MessageConsoleStream fStdoutStream ; private MessageConsoleStream fStderrStream ; private ContributionContextTypeRegistry fContextRegistry ; private TemplateStore fTemplateStore ; private boolean fDebugConsole ; public static final String CUSTOM_TEMPLATES_KEY = "" ; public static final String SV_TEMPLATE_CONTEXT = "" ; private String fInsertSpaceTestOverride ; private boolean fStartRefreshJob = false ; private RefreshIndexJob fRefreshIndexJob ; private List < String > fTemplatePaths ; private TemplateParameterProvider fGlobalPrefsProvider ; private List < LogMessage > fLogMessageQueue ; private boolean fLogMessageScheduled ; public SVUiPlugin ( ) { fImageMap = new WeakHashMap < String , Image > ( ) ; fGlobalPrefsProvider = new TemplateParameterProvider ( ) ; fLogMessageQueue = new ArrayList < SVUiPlugin . LogMessage > ( ) ; } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; fPlugin = this ; LogFactory . getDefault ( ) . addLogListener ( this ) ; getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; SVCorePlugin . getDefault ( ) . setDebugLevel ( getDebugLevel ( getPreferenceStore ( ) . getString ( SVEditorPrefsConstants . P_DEBUG_LEVEL_S ) ) ) ; SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) . setEnableAutoRebuild ( getPreferenceStore ( ) . getBoolean ( SVEditorPrefsConstants . P_AUTO_REBUILD_INDEX ) ) ; TemplateRegistry rgy = SVCorePlugin . getDefault ( ) . getTemplateRgy ( ) ; rgy . addPathProvider ( this ) ; update_template_paths ( ) ; update_global_parameters ( ) ; } public static IWorkbenchPage getActivePage ( ) { return getDefault ( ) . getActivePage ( ) ; } private void update_template_paths ( ) { fTemplatePaths = parse_paths ( getPreferenceStore ( ) . getString ( SVEditorPrefsConstants . P_SV_TEMPLATE_PATHS ) ) ; } private void update_global_parameters ( ) { Map < String , String > params = null ; try { params = XMLTransformUtils . xml2Map ( getPreferenceStore ( ) . getString ( SVEditorPrefsConstants . P_SV_TEMPLATE_PROPERTIES ) , "" , "" ) ; } catch ( Exception e ) { } if ( params != null ) { fGlobalPrefsProvider = new TemplateParameterProvider ( params ) ; } } public List < String > getExternalTemplatePath ( ) { return fTemplatePaths ; } public ITemplateParameterProvider getGlobalTemplateParameters ( ) { return fGlobalPrefsProvider ; } private static List < String > parse_paths ( String stringList ) { StringTokenizer st = new StringTokenizer ( stringList , File . pathSeparator + "" ) ; ArrayList < String > v = new ArrayList < String > ( ) ; while ( st . hasMoreElements ( ) ) { v . add ( ( String ) st . nextElement ( ) ) ; } return v ; } private int getDebugLevel ( String level_s ) { if ( level_s . equals ( "" ) ) { return ILogLevel . LEVEL_MIN ; } else if ( level_s . equals ( "" ) ) { return ILogLevel . LEVEL_MID ; } else if ( level_s . equals ( "" ) ) { return ILogLevel . LEVEL_MAX ; } else { return ILogLevel . LEVEL_OFF ; } } public synchronized void startRefreshJob ( ) { if ( ! fStartRefreshJob ) { RefreshProjectIndexesJob rj = new RefreshProjectIndexesJob ( ) ; rj . setPriority ( Job . LONG ) ; rj . schedule ( ) ; fStartRefreshJob = true ; } } public synchronized void refreshIndex ( ISVDBIndex index ) { if ( fRefreshIndexJob == null ) { fRefreshIndexJob = new RefreshIndexJob ( this ) ; fRefreshIndexJob . setPriority ( Job . LONG ) ; fRefreshIndexJob . schedule ( ) ; } fRefreshIndexJob . addIndex ( index ) ; } public synchronized void refreshIndexList ( List < ISVDBIndex > list ) { if ( fRefreshIndexJob == null ) { fRefreshIndexJob = new RefreshIndexJob ( this ) ; fRefreshIndexJob . setPriority ( Job . LONG ) ; fRefreshIndexJob . schedule ( ) ; } fRefreshIndexJob . addIndexList ( list ) ; } public synchronized void refreshJobComplete ( ) { fRefreshIndexJob = null ; } public void stop ( BundleContext context ) throws Exception { fPlugin = null ; getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; LogFactory . getDefault ( ) . removeLogListener ( this ) ; super . stop ( context ) ; } public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( SVEditorPrefsConstants . P_DEBUG_LEVEL_S ) ) { SVCorePlugin . getDefault ( ) . setDebugLevel ( getDebugLevel ( ( String ) event . getNewValue ( ) ) ) ; } else if ( event . getProperty ( ) . equals ( SVEditorPrefsConstants . P_DEBUG_CONSOLE_S ) ) { synchronized ( fLogMessageQueue ) { fDebugConsole = ( Boolean ) event . getNewValue ( ) ; } } else if ( event . getProperty ( ) . equals ( SVEditorPrefsConstants . P_SV_TEMPLATE_PATHS ) ) { update_template_paths ( ) ; } else if ( event . getProperty ( ) . equals ( SVEditorPrefsConstants . P_AUTO_REBUILD_INDEX ) ) { SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) . setEnableAutoRebuild ( ( Boolean ) event . getNewValue ( ) ) ; } else if ( event . getProperty ( ) . equals ( SVEditorPrefsConstants . P_SV_TEMPLATE_PROPERTIES ) ) { update_global_parameters ( ) ; } } private Runnable logMessageRunnable = new Runnable ( ) { public void run ( ) { synchronized ( fLogMessageQueue ) { for ( LogMessage msg : fLogMessageQueue ) { ILogHandle handle = msg . handle ; int type = msg . type ; int level = msg . level ; String message = msg . message ; MessageConsoleStream out = null ; if ( type == ILogListener . Type_Error ) { out = getStderrStream ( ) ; } else if ( type == ILogListener . Type_Info ) { out = getStdoutStream ( ) ; } else if ( SVCorePlugin . getDefault ( ) . getDebugLevel ( ) >= level ) { if ( ( type & ILogListener . Type_Error ) != ) { out = getStderrStream ( ) ; } else { out = getStdoutStream ( ) ; } } if ( out != null ) { out . println ( "" + handle . getName ( ) + "" + message ) ; } } fLogMessageQueue . clear ( ) ; fLogMessageScheduled = false ; } } } ; public void message ( ILogHandle handle , int type , int level , String message ) { synchronized ( fLogMessageQueue ) { if ( ! fDebugConsole && type != ILogListener . Type_Error ) { return ; } LogMessage msg = new LogMessage ( ) ; msg . handle = handle ; msg . type = type ; msg . level = level ; msg . message = message ; fLogMessageQueue . add ( msg ) ; if ( ! fLogMessageScheduled ) { Display . getDefault ( ) . asyncExec ( logMessageRunnable ) ; fLogMessageScheduled = true ; } } } public ResourceBundle getResources ( ) { if ( fResources == null ) { try { fResources = ResourceBundle . getBundle ( PLUGIN_ID + "" ) ; } catch ( MissingResourceException e ) { e . printStackTrace ( ) ; } } return fResources ; } public static Image getImage ( String resource ) { SVUiPlugin p = getDefault ( ) ; Image ret = null ; if ( ! p . fImageMap . containsKey ( resource ) ) { ret = SVUiPlugin . imageDescriptorFromPlugin ( SVUiPlugin . PLUGIN_ID , resource ) . createImage ( ) ; p . fImageMap . put ( resource , ret ) ; } return p . fImageMap . get ( resource ) ; } public static ImageDescriptor getImageDescriptor ( String resource ) { return SVUiPlugin . imageDescriptorFromPlugin ( SVUiPlugin . PLUGIN_ID , resource ) ; } public MessageConsole getConsole ( ) { if ( fConsole == null ) { fConsole = new MessageConsole ( "" , null ) ; ConsolePlugin . getDefault ( ) . getConsoleManager ( ) . addConsoles ( new IConsole [ ] { fConsole } ) ; } return fConsole ; } public ContextTypeRegistry getContextTypeRegistry ( ) { if ( fContextRegistry == null ) { fContextRegistry = new ContributionContextTypeRegistry ( ) ; fContextRegistry . addContextType ( SV_TEMPLATE_CONTEXT ) ; } return fContextRegistry ; } public TemplateStore getTemplateStore ( ) { if ( fTemplateStore == null ) { fTemplateStore = new ContributionTemplateStore ( SVUiPlugin . getDefault ( ) . getContextTypeRegistry ( ) , SVUiPlugin . getDefault ( ) . getPreferenceStore ( ) , SVUiPlugin . CUSTOM_TEMPLATES_KEY ) ; try { fTemplateStore . load ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return fTemplateStore ; } public MessageConsoleStream getStdoutStream ( ) { if ( fStdoutStream == null ) { fStdoutStream = getConsole ( ) . newMessageStream ( ) ; fStdoutStream . setActivateOnWrite ( false ) ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { fStdoutStream . setColor ( Display . getDefault ( ) . getSystemColor ( SWT . COLOR_BLACK ) ) ; } } ) ; } return fStdoutStream ; } public MessageConsoleStream getStderrStream ( ) { if ( fStderrStream == null ) { fStderrStream = getConsole ( ) . newMessageStream ( ) ; fStderrStream . setActivateOnWrite ( false ) ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { fStderrStream . setColor ( Display . getDefault ( ) . getSystemColor ( SWT . COLOR_RED ) ) ; } } ) ; } return fStderrStream ; } public static SVUiPlugin getDefault ( ) { return fPlugin ; } public IDialogSettings getDialogSettingsSection ( String name ) { IDialogSettings dialogSettings = getDialogSettings ( ) ; IDialogSettings section = dialogSettings . getSection ( name ) ; if ( section == null ) { section = dialogSettings . addNewSection ( name ) ; } return section ; } public IPreferenceStore getChainedPrefs ( ) { ChainedPreferenceStore ret = new ChainedPreferenceStore ( new IPreferenceStore [ ] { getPreferenceStore ( ) , EditorsUI . getPreferenceStore ( ) } ) ; return ret ; } public String getIndentIncr ( ) { IPreferenceStore chainedPrefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; boolean spaces_for_tabs = chainedPrefs . getBoolean ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SPACES_FOR_TABS ) ; int tab_width = chainedPrefs . getInt ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_TAB_WIDTH ) ; if ( fInsertSpaceTestOverride != null ) { return fInsertSpaceTestOverride ; } else { if ( spaces_for_tabs ) { String ret = "" ; for ( int i = ; i < tab_width ; i ++ ) { ret += "" ; } return ret ; } else { return "" ; } } } public int getTabWidth ( ) { IPreferenceStore chainedPrefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; int tab_width = chainedPrefs . getInt ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_TAB_WIDTH ) ; return tab_width ; } public boolean getBooleanPref ( String id ) { IPreferenceStore chainedPrefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; boolean val = chainedPrefs . getBoolean ( id ) ; return val ; } public int getIntegerPref ( String id ) { IPreferenceStore chainedPrefs = SVUiPlugin . getDefault ( ) . getChainedPrefs ( ) ; int val = chainedPrefs . getInt ( id ) ; return val ; } } package net . sf . sveditor . ui ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; public class RefreshProjectIndexesJob extends Job { public RefreshProjectIndexesJob ( ) { super ( "" ) ; } @ Override protected IStatus run ( IProgressMonitor monitor ) { SVDBProjectManager mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; for ( SVDBProjectData p : mgr . getProjectList ( ) ) { List < ISVDBIndex > index_list = rgy . getProjectIndexList ( p . getName ( ) ) ; SVUiPlugin . getDefault ( ) . refreshIndexList ( index_list ) ; } return Status . OK_STATUS ; } } package net . sf . sveditor . ui ; import java . net . URI ; import net . sf . sveditor . core . db . index . plugin_lib . PluginFileStore ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . filesystem . IFileSystem ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . ui . IElementFactory ; import org . eclipse . ui . IMemento ; public class PluginFileEditorInputFactory implements IElementFactory { public static final String ID = "" ; static void saveState ( IMemento memento , PluginPathEditorInput input ) { memento . putString ( "" , input . getURI ( ) . toString ( ) ) ; } public IAdaptable createElement ( IMemento memento ) { String plugin_path = memento . getString ( "" ) ; System . out . println ( "" + plugin_path ) ; if ( plugin_path == null ) { return null ; } URI uri = null ; try { uri = new URI ( plugin_path ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } IFileSystem fs = null ; IFileStore store = null ; try { fs = EFS . getFileSystem ( "" ) ; store = fs . getStore ( uri ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } try { return new PluginPathEditorInput ( ( PluginFileStore ) store ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; return null ; } } } package net . sf . sveditor . ui . explorer ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . dirtree . SVDBDirTreeNode ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . StyledString ; import org . eclipse . swt . graphics . Image ; public class ProjectPathsLabelProvider extends SVTreeLabelProvider { @ Override public Image getImage ( Object element ) { if ( element instanceof ProjectPathsData ) { return SVUiPlugin . getImage ( "" ) ; } else if ( element instanceof SVDBDirTreeNode ) { SVDBDirTreeNode n = ( SVDBDirTreeNode ) element ; if ( n . isDir ( ) ) { return SVUiPlugin . getImage ( "" ) ; } else { return SVUiPlugin . getImage ( "" ) ; } } else if ( element instanceof LibIndexPath || element instanceof ProjectPathsIndexEntry ) { String type ; if ( element instanceof LibIndexPath ) { type = ( ( LibIndexPath ) element ) . getType ( ) ; } else { type = ( ( ProjectPathsIndexEntry ) element ) . getType ( ) ; } if ( type . equals ( LibIndexPath . TYPE_SRC_COLLECTION ) ) { return SVUiPlugin . getImage ( "" ) ; } else if ( type . equals ( LibIndexPath . TYPE_ARG_FILE ) || type . equals ( LibIndexPath . TYPE_LIB_PATH ) ) { return SVUiPlugin . getImage ( "" ) ; } } return super . getImage ( element ) ; } @ Override public StyledString getStyledText ( Object element ) { if ( element instanceof IProjectPathsData ) { return new StyledString ( ( ( IProjectPathsData ) element ) . getName ( ) ) ; } else if ( element instanceof SVDBFile ) { return new StyledString ( ( ( SVDBFile ) element ) . getName ( ) ) ; } else if ( element instanceof SVDBDirTreeNode ) { SVDBDirTreeNode n = ( SVDBDirTreeNode ) element ; return new StyledString ( n . getName ( ) ) ; } else { return super . getStyledText ( element ) ; } } } package net . sf . sveditor . ui . explorer ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . index . ISVDBIndex ; public class LibIndexPath implements IProjectPathsData { public static final String TYPE_LIB_PATH = "" ; public static final String TYPE_SRC_COLLECTION = "" ; public static final String TYPE_ARG_FILE = "" ; private IProjectPathsData fParent ; private String fName ; private String fType ; private List < ProjectPathsIndexEntry > fIndexList ; public LibIndexPath ( String type , IProjectPathsData parent , String name , List < ISVDBIndex > index_list ) { fType = type ; fParent = parent ; fName = name ; fIndexList = new ArrayList < ProjectPathsIndexEntry > ( ) ; for ( ISVDBIndex index : index_list ) { ProjectPathsIndexEntry e = new ProjectPathsIndexEntry ( type , index ) ; fIndexList . add ( e ) ; } } public String getType ( ) { return fType ; } public Object [ ] getChildren ( Object parent ) { return fIndexList . toArray ( ) ; } public String getName ( ) { return fName ; } public Object getParent ( Object element ) { if ( element == this ) { return fParent ; } return null ; } @ Override public int hashCode ( ) { int hash = fName . hashCode ( ) ; hash += fType . hashCode ( ) ; hash += fParent . hashCode ( ) ; return hash ; } public boolean equals ( Object obj ) { if ( obj instanceof LibIndexPath ) { LibIndexPath lip = ( LibIndexPath ) obj ; return ( fName . equals ( lip . fName ) && fType . equals ( lip . fType ) && fParent . equals ( lip . fParent ) ) ; } else { return super . equals ( obj ) ; } } } package net . sf . sveditor . ui . explorer ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . IDecoration ; import org . eclipse . jface . viewers . ILightweightLabelDecorator ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PlatformUI ; public class ProblemLabelDecorator extends LabelProvider implements ILightweightLabelDecorator { public void decorate ( Object element , IDecoration decoration ) { if ( ! ( element instanceof IResource ) ) { return ; } IWorkbench workbench = PlatformUI . getWorkbench ( ) ; if ( workbench . isClosing ( ) ) { return ; } IResource res = ( IResource ) element ; try { if ( res . findMaxProblemSeverity ( IMarker . PROBLEM , true , IResource . DEPTH_INFINITE ) >= IMarker . SEVERITY_ERROR ) { ImageDescriptor image = SVUiPlugin . getImageDescriptor ( "" ) ; if ( image != null ) { decoration . addOverlay ( image ) ; } } } catch ( CoreException e ) { e . printStackTrace ( ) ; } } } package net . sf . sveditor . ui . explorer ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . core . db . SVDBTask ; import net . sf . sveditor . core . db . index . ISVDBChangeListener ; import net . sf . sveditor . core . db . project . ISVDBProjectSettingsListener ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . search . SVDBSearchResult ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . widgets . Display ; public class SVFileNavigatorContentProvider implements ITreeContentProvider , Runnable , ISVDBChangeListener , ISVDBProjectSettingsListener { private Viewer fViewer ; private LogHandle fLog ; public SVFileNavigatorContentProvider ( ) { SVCorePlugin . getDefault ( ) . getProjMgr ( ) . addProjectSettingsListener ( this ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public void SVDBFileChanged ( SVDBFile file , List < SVDBItem > adds , List < SVDBItem > removes , List < SVDBItem > changes ) { Display . getDefault ( ) . asyncExec ( this ) ; } public void projectSettingsChanged ( SVDBProjectData data ) { fLog . debug ( "" ) ; Display . getDefault ( ) . asyncExec ( this ) ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof IFile ) { List < SVDBSearchResult < SVDBFile > > res = new ArrayList < SVDBSearchResult < SVDBFile > > ( ) ; SVDBFile svdb_file = null ; if ( res . size ( ) == ) { } else { svdb_file = res . get ( ) . getItem ( ) ; } if ( svdb_file != null ) { List < SVDBItem > ret = new ArrayList < SVDBItem > ( ) ; for ( ISVDBItemBase it : svdb_file . getChildren ( ) ) { if ( it . getType ( ) != SVDBItemType . Marker ) { ret . add ( ( SVDBItem ) it ) ; } } return ret . toArray ( ) ; } else { return new Object [ ] ; } } else if ( parentElement instanceof ISVDBScopeItem && ! ( parentElement instanceof SVDBTask ) ) { return ( ( ISVDBScopeItem ) parentElement ) . getItems ( ) . toArray ( ) ; } return new Object [ ] ; } public Object getParent ( Object element ) { if ( element instanceof IResource ) { return ( ( IResource ) element ) . getParent ( ) ; } else if ( element instanceof SVDBItem ) { return ( ( SVDBItem ) element ) . getParent ( ) ; } else { return null ; } } public boolean hasChildren ( Object element ) { return ( getChildren ( element ) . length > ) ; } public Object [ ] getElements ( Object inputElement ) { return new Object [ ] ; } public void dispose ( ) { SVCorePlugin . getDefault ( ) . getProjMgr ( ) . removeProjectSettingsListener ( this ) ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fViewer = viewer ; } public void run ( ) { if ( ! fViewer . getControl ( ) . isDisposed ( ) ) { fLog . debug ( "" ) ; fViewer . refresh ( ) ; } } } package net . sf . sveditor . ui . explorer ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItem ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . ui . SVUiPlugin ; import net . sf . sveditor . ui . editor . SVEditor ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorDescriptor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IEditorReference ; import org . eclipse . ui . IEditorRegistry ; import org . eclipse . ui . IURIEditorInput ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . SelectionListenerAction ; import org . eclipse . ui . ide . FileStoreEditorInput ; import org . eclipse . ui . navigator . CommonActionProvider ; import org . eclipse . ui . navigator . ICommonActionConstants ; import org . eclipse . ui . navigator . ICommonActionExtensionSite ; import org . eclipse . ui . part . FileEditorInput ; public class OpenSVDBItem extends CommonActionProvider { private OpenItemAction fOpenItem ; private static LogHandle fLog ; static { fLog = LogFactory . getLogHandle ( "" ) ; } @ Override public void init ( ICommonActionExtensionSite site ) { super . init ( site ) ; fOpenItem = new OpenItemAction ( ) ; } @ Override public void fillContextMenu ( IMenuManager menu ) { menu . add ( fOpenItem ) ; fOpenItem . selectionChanged ( ( IStructuredSelection ) getContext ( ) . getSelection ( ) ) ; super . fillContextMenu ( menu ) ; } @ Override public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; actionBars . setGlobalActionHandler ( ICommonActionConstants . OPEN , fOpenItem ) ; fOpenItem . selectionChanged ( ( IStructuredSelection ) getContext ( ) . getSelection ( ) ) ; } private class OpenItemAction extends SelectionListenerAction { public OpenItemAction ( ) { super ( "" ) ; } @ Override @ SuppressWarnings ( "" ) public void run ( ) { super . run ( ) ; for ( SVDBItem it : ( List < SVDBItem > ) getSelectedNonResources ( ) ) { IEditorPart ed_f = openEditor ( it ) ; if ( ed_f != null ) { if ( ed_f instanceof SVEditor ) { ( ( SVEditor ) ed_f ) . setSelection ( it , true ) ; } else { fLog . enter ( "" + it . getName ( ) + "" + ed_f . getClass ( ) . getName ( ) ) ; } } } } private IEditorPart openEditor ( SVDBItem it ) { IEditorPart ret = null ; ISVDBChildItem p = ( ISVDBChildItem ) it ; IFile f = null ; while ( p != null && ! ( p instanceof SVDBFile ) ) { p = p . getParent ( ) ; } if ( p != null ) { String file = ( ( SVDBFile ) p ) . getFilePath ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; if ( file . startsWith ( "" ) ) { file = file . substring ( "" . length ( ) ) ; } String leaf = ( ( SVDBFile ) p ) . getName ( ) ; Path path = new Path ( file ) ; f = root . getFile ( new Path ( file ) ) ; getActionSite ( ) . getViewSite ( ) . getShell ( ) ; IWorkbench wb = PlatformUI . getWorkbench ( ) ; IWorkbenchWindow w = wb . getActiveWorkbenchWindow ( ) ; for ( IWorkbenchPage page : w . getPages ( ) ) { for ( IEditorReference ed_r : page . getEditorReferences ( ) ) { String id = ed_r . getId ( ) ; if ( ! id . equals ( SVUiPlugin . PLUGIN_ID + "" ) ) { continue ; } IEditorInput in = null ; try { in = ed_r . getEditorInput ( ) ; } catch ( PartInitException e ) { e . printStackTrace ( ) ; } if ( in instanceof FileEditorInput ) { FileEditorInput in_f = ( FileEditorInput ) in ; if ( in_f . getPath ( ) . equals ( path ) ) { ret = ed_r . getEditor ( true ) ; break ; } } else if ( in instanceof IURIEditorInput ) { IURIEditorInput in_u = ( IURIEditorInput ) in ; if ( in_u . getURI ( ) . equals ( path ) ) { ret = ed_r . getEditor ( true ) ; break ; } } } if ( ret != null ) { break ; } } if ( ret == null ) { w = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; IEditorRegistry rgy = PlatformUI . getWorkbench ( ) . getEditorRegistry ( ) ; IEditorDescriptor desc = rgy . getDefaultEditor ( leaf ) ; try { if ( f != null && f . exists ( ) ) { ret = w . getActivePage ( ) . openEditor ( new FileEditorInput ( f ) , desc . getId ( ) ) ; } else if ( file . startsWith ( "" ) ) { } else { IFileStore fs = EFS . getLocalFileSystem ( ) . getStore ( new Path ( file ) ) ; ret = w . getActivePage ( ) . openEditor ( new FileStoreEditorInput ( fs ) , desc . getId ( ) ) ; } } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } } return ret ; } } } package net . sf . sveditor . ui . explorer ; import java . text . Collator ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBScopeItem ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; public class SVFileSorter extends ViewerSorter { public SVFileSorter ( ) { } public SVFileSorter ( Collator collator ) { super ( collator ) ; } @ Override public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( e1 instanceof ISVDBChildItem && e2 instanceof ISVDBChildItem ) { ISVDBChildItem p1 = ( ( ISVDBChildItem ) e1 ) . getParent ( ) ; ISVDBChildItem p2 = ( ( ISVDBChildItem ) e2 ) . getParent ( ) ; if ( p1 != p2 ) { System . out . println ( "" ) ; } int i1 = ( ( ISVDBScopeItem ) p1 ) . getItems ( ) . indexOf ( e1 ) ; int i2 = ( ( ISVDBScopeItem ) p2 ) . getItems ( ) . indexOf ( e2 ) ; return ( i1 - i2 ) ; } return super . compare ( viewer , e1 , e2 ) ; } @ Override public void sort ( Viewer viewer , Object [ ] elements ) { System . out . println ( "" ) ; } } package net . sf . sveditor . ui . explorer ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . dirtree . SVDBDirTreeFactory ; import net . sf . sveditor . core . dirtree . SVDBDirTreeNode ; import org . eclipse . core . runtime . NullProgressMonitor ; public class ProjectPathsIndexEntry implements IProjectPathsData { private String fType ; private ISVDBIndex fIndex ; private List < SVDBDirTreeNode > fRoots ; public ProjectPathsIndexEntry ( String type , ISVDBIndex index ) { fType = type ; fIndex = index ; fRoots = new ArrayList < SVDBDirTreeNode > ( ) ; Iterable < String > filelist = fIndex . getFileList ( new NullProgressMonitor ( ) ) ; SVDBDirTreeFactory tree_factory = new SVDBDirTreeFactory ( ) ; for ( String f : filelist ) { tree_factory . addPath ( f , false ) ; } fRoots . addAll ( tree_factory . buildTree ( ) . getChildren ( ) ) ; } public String getType ( ) { return fType ; } public Object [ ] getChildren ( Object parent ) { return fRoots . toArray ( ) ; } public String getName ( ) { return fIndex . getBaseLocation ( ) ; } public Object getParent ( Object element ) { return null ; } } package net . sf . sveditor . ui . explorer ; import net . sf . sveditor . core . db . SVDBFile ; import org . eclipse . core . runtime . IAdaptable ; public class ProjectPathsFileWrapper implements IAdaptable { private SVDBFile fFile ; public ProjectPathsFileWrapper ( SVDBFile f ) { fFile = f ; } public SVDBFile getFile ( ) { return fFile ; } @ SuppressWarnings ( "" ) public Object getAdapter ( Class adapter ) { if ( adapter . equals ( SVDBFile . class ) ) { return fFile ; } return null ; } } package net . sf . sveditor . ui . explorer ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . DecoratingLabelProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . swt . graphics . Image ; import org . eclipse . ui . PlatformUI ; public class SVExplorerDecoratingLabelProvider extends DecoratingLabelProvider { public SVExplorerDecoratingLabelProvider ( ) { super ( new SVTreeLabelProvider ( ) , PlatformUI . getWorkbench ( ) . getDecoratorManager ( ) . getLabelDecorator ( ) ) ; } @ Override public Image getImage ( Object element ) { return super . getImage ( element ) ; } @ Override public ILabelProvider getLabelProvider ( ) { return super . getLabelProvider ( ) ; } } package net . sf . sveditor . ui . explorer ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IProjectNature ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . actions . SelectionListenerAction ; import org . eclipse . ui . navigator . CommonActionProvider ; import org . eclipse . ui . navigator . ICommonActionExtensionSite ; import org . eclipse . ui . navigator . ICommonMenuConstants ; public class AddSystemVerilogNatureAction extends CommonActionProvider { public AddSystemVerilogNatureAction ( ) { } @ Override public void init ( ICommonActionExtensionSite site ) { super . init ( site ) ; fAddSVNature = new AddSVNatureAction ( ) ; } @ Override public void fillContextMenu ( IMenuManager menu ) { menu . insertAfter ( ICommonMenuConstants . GROUP_ADDITIONS , fAddSVNature ) ; fAddSVNature . selectionChanged ( ( IStructuredSelection ) getContext ( ) . getSelection ( ) ) ; } private AddSVNatureAction fAddSVNature ; private class AddSVNatureAction extends SelectionListenerAction { public AddSVNatureAction ( ) { super ( "" ) ; } @ Override @ SuppressWarnings ( "" ) public void run ( ) { List < IResource > sel = ( List < IResource > ) getSelectedResources ( ) ; for ( IResource r : sel ) { if ( r instanceof IProject ) { IProject p = ( IProject ) r ; IProjectNature n = null ; try { p . refreshLocal ( IResource . DEPTH_ONE , null ) ; n = p . getNature ( SVCorePlugin . PLUGIN_ID + "" ) ; } catch ( CoreException e ) { } if ( n == null ) { try { IProjectDescription d = p . getDescription ( ) ; String old_ids [ ] = d . getNatureIds ( ) ; String new_ids [ ] = new String [ old_ids . length + ] ; System . arraycopy ( old_ids , , new_ids , , old_ids . length ) ; new_ids [ old_ids . length ] = SVCorePlugin . PLUGIN_ID + "" ; d . setNatureIds ( new_ids ) ; p . setDescription ( d , IResource . NONE , null ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } } } } super . run ( ) ; } } } package net . sf . sveditor . ui . explorer ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexCollection ; import net . sf . sveditor . core . db . project . SVDBProjectData ; public class ProjectPathsData implements IProjectPathsData { private SVDBProjectData fProjectData ; private List < IProjectPathsData > fPaths ; public ProjectPathsData ( SVDBProjectData pd ) { this ( pd , true ) ; } public ProjectPathsData ( SVDBProjectData pd , boolean setup ) { fProjectData = pd ; fPaths = new ArrayList < IProjectPathsData > ( ) ; if ( setup ) { SVDBIndexCollection mgr = fProjectData . getProjectIndexMgr ( ) ; List < ISVDBIndex > allLibIndexes = mgr . getLibraryPathList ( ) ; List < ISVDBIndex > srcCollectionIndexes = mgr . getSourceCollectionList ( ) ; List < ISVDBIndex > libIndexList = new ArrayList < ISVDBIndex > ( ) ; List < ISVDBIndex > argFileIndexList = new ArrayList < ISVDBIndex > ( ) ; for ( ISVDBIndex i : allLibIndexes ) { if ( i . getTypeID ( ) . equals ( SVDBArgFileIndexFactory . TYPE ) ) { argFileIndexList . add ( i ) ; } else { libIndexList . add ( i ) ; } } fPaths . add ( new LibIndexPath ( LibIndexPath . TYPE_SRC_COLLECTION , this , "" , srcCollectionIndexes ) ) ; fPaths . add ( new LibIndexPath ( LibIndexPath . TYPE_LIB_PATH , this , "" , libIndexList ) ) ; fPaths . add ( new LibIndexPath ( LibIndexPath . TYPE_ARG_FILE , this , "" , argFileIndexList ) ) ; } } public Object [ ] getChildren ( Object parent ) { return fPaths . toArray ( ) ; } public String getName ( ) { return "" ; } public Object getParent ( Object element ) { return null ; } public SVDBProjectData getProjectData ( ) { return fProjectData ; } @ Override public int hashCode ( ) { int hash = fProjectData . getName ( ) . hashCode ( ) ; return hash ; } public boolean equals ( Object obj ) { if ( obj instanceof SVDBProjectData ) { return ( obj == fProjectData ) ; } else if ( obj instanceof ProjectPathsData ) { ProjectPathsData p_obj = ( ProjectPathsData ) obj ; return p_obj . getProjectData ( ) . getName ( ) . equals ( fProjectData . getName ( ) ) ; } else { return super . equals ( obj ) ; } } } package net . sf . sveditor . ui . explorer ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBIndexRegistry ; import net . sf . sveditor . core . log . ILogLevel ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . actions . SelectionListenerAction ; import org . eclipse . ui . navigator . CommonActionProvider ; import org . eclipse . ui . navigator . ICommonMenuConstants ; public class RebuildSvIndexAction extends CommonActionProvider implements ILogLevel { public RebuildSvIndexAction ( ) { fRebuildAction = new RebuildIndexAction ( ) ; } public void fillContextMenu ( IMenuManager menu ) { menu . insertAfter ( ICommonMenuConstants . GROUP_ADDITIONS , fRebuildAction ) ; } private RebuildIndexAction fRebuildAction ; private class RebuildIndexAction extends SelectionListenerAction { private LogHandle fLog ; public RebuildIndexAction ( ) { super ( "" ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public void run ( ) { IStructuredSelection sel_s = ( IStructuredSelection ) getActionSite ( ) . getViewSite ( ) . getSelectionProvider ( ) . getSelection ( ) ; updateSelection ( sel_s ) ; List < IProject > projects = new ArrayList < IProject > ( ) ; SVDBIndexRegistry rgy = SVCorePlugin . getDefault ( ) . getSVDBIndexRegistry ( ) ; for ( Object sel_o : sel_s . toList ( ) ) { IProject p = null ; if ( sel_o instanceof IProject ) { p = ( IProject ) sel_o ; } else if ( sel_o instanceof IResource ) { p = ( ( IResource ) sel_o ) . getProject ( ) ; } if ( p != null && ! projects . contains ( p ) ) { projects . add ( p ) ; } } for ( IProject p : projects ) { fLog . debug ( LEVEL_MIN , "" + p . getName ( ) + "" ) ; try { p . deleteMarkers ( IMarker . PROBLEM , true , IResource . DEPTH_INFINITE ) ; } catch ( CoreException e ) { } List < ISVDBIndex > index_list = rgy . getProjectIndexList ( p . getName ( ) ) ; SVUiPlugin . getDefault ( ) . refreshIndexList ( index_list ) ; } rgy . rebuildIndex ( new NullProgressMonitor ( ) , SVDBIndexRegistry . GLOBAL_PROJECT ) ; } } } package net . sf . sveditor . ui . explorer ; public interface IProjectPathsData { String getName ( ) ; Object getParent ( Object element ) ; Object [ ] getChildren ( Object parent ) ; } package net . sf . sveditor . ui . explorer ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . index . ISVDBIndexChangeListener ; import net . sf . sveditor . core . db . project . ISVDBProjectSettingsListener ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . dirtree . SVDBDirTreeNode ; import net . sf . sveditor . core . job_mgr . IJob ; import net . sf . sveditor . core . job_mgr . IJobMgr ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . jobs . ILock ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . viewers . IElementComparer ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . widgets . Display ; public class ProjectPathsContentProvider implements ITreeContentProvider , ISVDBProjectSettingsListener , ISVDBIndexChangeListener { private List < ProjectPathsData > fProjectDataMap ; private static Object NO_ELEMENTS [ ] = new Object [ ] ; private Viewer fViewer ; private boolean fRefreshQueued ; private IElementComparer fDefaultComparer ; public ProjectPathsContentProvider ( ) { fProjectDataMap = new ArrayList < ProjectPathsData > ( ) ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof IProject && ( ( IProject ) parentElement ) . getFile ( "" ) . exists ( ) ) { SVDBProjectData pd = SVCorePlugin . getDefault ( ) . getProjMgr ( ) . getProjectData ( ( IProject ) parentElement ) ; ProjectPathsData paths_d = getProjectPathsData ( pd ) ; if ( paths_d == null ) { return new Object [ ] ; } else { return new Object [ ] { paths_d } ; } } else if ( parentElement instanceof IProjectPathsData ) { return ( ( IProjectPathsData ) parentElement ) . getChildren ( parentElement ) ; } else if ( parentElement instanceof SVDBDirTreeNode ) { return ( ( SVDBDirTreeNode ) parentElement ) . getChildren ( ) . toArray ( ) ; } return NO_ELEMENTS ; } private ProjectPathsData getProjectPathsData ( final SVDBProjectData pd ) { int idx ; synchronized ( fProjectDataMap ) { ProjectPathsData tmp = new ProjectPathsData ( pd , false ) ; idx = fProjectDataMap . indexOf ( tmp ) ; } if ( idx == ) { return fProjectDataMap . get ( idx ) ; } else if ( idx == - ) { synchronized ( fProjectDataMap ) { while ( fProjectDataMap . size ( ) >= ) { ProjectPathsData paths_d = fProjectDataMap . remove ( ) ; removeListeners ( paths_d . getProjectData ( ) ) ; } } IJobMgr job_mgr = SVCorePlugin . getJobMgr ( ) ; IJob job = job_mgr . createJob ( ) ; job . init ( "" , new Runnable ( ) { public void run ( ) { ProjectPathsData paths_d = new ProjectPathsData ( pd ) ; addListeners ( pd ) ; synchronized ( fProjectDataMap ) { fProjectDataMap . add ( paths_d ) ; } Display d = fViewer . getControl ( ) . getDisplay ( ) ; if ( d != null && ! d . isDisposed ( ) && ! fViewer . getControl ( ) . isDisposed ( ) ) { fViewer . getControl ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { fViewer . refresh ( ) ; } } ) ; } } } ) ; job_mgr . queueJob ( job ) ; return null ; } else { ProjectPathsData paths_d = fProjectDataMap . remove ( idx ) ; fProjectDataMap . add ( paths_d ) ; return paths_d ; } } private void addListeners ( SVDBProjectData pd ) { pd . addProjectSettingsListener ( this ) ; pd . getProjectIndexMgr ( ) . addIndexChangeListener ( this ) ; } private void removeListeners ( SVDBProjectData pd ) { pd . removeProjectSettingsListener ( this ) ; pd . getProjectIndexMgr ( ) . removeIndexChangeListener ( this ) ; } public Object getParent ( Object element ) { if ( element instanceof LibIndexPath ) { LibIndexPath lip = ( LibIndexPath ) element ; return lip . getParent ( element ) ; } else if ( element instanceof SVDBDirTreeNode ) { return ( ( SVDBDirTreeNode ) element ) . getParent ( ) ; } else { return null ; } } public boolean hasChildren ( Object element ) { return ( getChildren ( element ) . length > ) ; } public Object [ ] getElements ( Object inputElement ) { return NO_ELEMENTS ; } public void dispose ( ) { if ( fViewer != null && ! fViewer . getControl ( ) . isDisposed ( ) ) { ( ( TreeViewer ) fViewer ) . setComparer ( fDefaultComparer ) ; } } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fViewer = viewer ; } public void index_changed ( int reason , SVDBFile file ) { doRefresh ( ) ; } public void index_rebuilt ( ) { doRefresh ( ) ; } public void projectSettingsChanged ( SVDBProjectData data ) { doRefresh ( ) ; } private void doRefresh ( ) { if ( ! fRefreshQueued && fViewer != null && ! fViewer . getControl ( ) . isDisposed ( ) ) { fRefreshQueued = true ; fViewer . getControl ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { fViewer . refresh ( ) ; fRefreshQueued = false ; } } ) ; } } } package net . sf . sveditor . ui . search ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . ui . SVEditorUtil ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . search . ui . text . AbstractTextSearchViewPage ; import org . eclipse . search . ui . text . Match ; import org . eclipse . ui . PartInitException ; public class SVSearchResultsPage extends AbstractTextSearchViewPage implements IAdaptable { private SVSearchTreeContentProvider fTreeContentProvider ; private SVSearchTableContentProvider fTableContentProvider ; @ Override protected void elementsChanged ( Object [ ] objects ) { if ( fTreeContentProvider != null ) { fTreeContentProvider . elementsChanged ( objects ) ; } if ( fTableContentProvider != null ) { fTableContentProvider . elementsChanged ( objects ) ; } } @ Override protected void clear ( ) { if ( fTreeContentProvider != null ) { fTreeContentProvider . clear ( ) ; } if ( fTableContentProvider != null ) { fTableContentProvider . clear ( ) ; } } @ Override protected void configureTreeViewer ( TreeViewer viewer ) { fTreeContentProvider = new SVSearchTreeContentProvider ( this , viewer ) ; viewer . setLabelProvider ( new SVSearchTreeLabelProvider ( ) ) ; viewer . setContentProvider ( fTreeContentProvider ) ; } @ Override protected void configureTableViewer ( TableViewer viewer ) { fTableContentProvider = new SVSearchTableContentProvider ( this , viewer ) ; SVSearchTableLabelProvider provider = new SVSearchTableLabelProvider ( ) ; viewer . setContentProvider ( fTableContentProvider ) ; viewer . setLabelProvider ( new SVDecoratingSearchTableLabelProvider ( provider ) ) ; } @ Override protected void showMatch ( Match match , int currentOffset , int currentLength , boolean activate ) throws PartInitException { if ( match . getElement ( ) instanceof ISVDBItemBase ) { SVEditorUtil . openEditor ( ( ISVDBItemBase ) match . getElement ( ) ) ; } } @ SuppressWarnings ( "" ) public Object getAdapter ( Class adapter ) { return null ; } } package net . sf . sveditor . ui . search ; import java . util . List ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . search . SVDBSearchEngine ; import net . sf . sveditor . core . db . search . SVDBSearchSpecification ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Status ; import org . eclipse . search . ui . ISearchQuery ; import org . eclipse . search . ui . ISearchResult ; import org . eclipse . search . ui . text . AbstractTextSearchResult ; public class SVSearchQuery implements ISearchQuery { private SVSearchResult fSearchResult ; private SVDBSearchSpecification fSearchSpec ; private ISVDBIndexIterator fSearchContext ; private String fLabel ; public SVSearchQuery ( ISVDBIndexIterator search_ctxt , SVDBSearchSpecification search_spec ) { fSearchContext = search_ctxt ; fSearchSpec = search_spec ; updateLabel ( ) ; } public IStatus run ( IProgressMonitor monitor ) throws OperationCanceledException { AbstractTextSearchResult textResult = ( AbstractTextSearchResult ) getSearchResult ( ) ; textResult . removeAll ( ) ; search ( monitor ) ; return Status . OK_STATUS ; } private void updateLabel ( ) { String type = "" ; switch ( fSearchSpec . getSearchType ( ) ) { case Field : type = "" ; break ; case Method : type = "" ; break ; case Package : type = "" ; break ; case Type : type = "" ; break ; } fLabel = type + fSearchSpec . getExpr ( ) ; if ( fSearchResult != null ) { fLabel += "" + fSearchResult . getMatchCount ( ) + "" ; } } private void search ( IProgressMonitor monitor ) throws OperationCanceledException { AbstractTextSearchResult result = ( AbstractTextSearchResult ) getSearchResult ( ) ; SVDBSearchEngine engine = new SVDBSearchEngine ( fSearchContext ) ; List < ISVDBItemBase > results = engine . find ( fSearchSpec , monitor ) ; for ( ISVDBItemBase it : results ) { result . addMatch ( new SVSearchMatch ( it ) ) ; } } public String getLabel ( ) { return fLabel ; } public boolean canRerun ( ) { return false ; } public boolean canRunInBackground ( ) { return true ; } public ISearchResult getSearchResult ( ) { if ( fSearchResult == null ) { fSearchResult = new SVSearchResult ( this ) ; } return fSearchResult ; } } package net . sf . sveditor . ui . search ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . StyledString ; public class SVSearchTreeLabelProvider extends SVTreeLabelProvider { public SVSearchTreeLabelProvider ( ) { fShowFunctionRetType = false ; } public StyledString getStyledText ( Object element ) { return super . getStyledText ( element ) ; } } package net . sf . sveditor . ui . search ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . search . ui . text . AbstractTextSearchResult ; public class SVSearchTreeContentProvider implements ITreeContentProvider { private static final Object EMPTY [ ] = new Object [ ] ; private Map < Object , Set < Object > > fChildrenMap ; private AbstractTextSearchResult fResult ; private TreeViewer fTreeViewer ; public SVSearchTreeContentProvider ( SVSearchResultsPage page , TreeViewer viewer ) { fTreeViewer = viewer ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { initialize ( ( AbstractTextSearchResult ) newInput ) ; } private void initialize ( AbstractTextSearchResult result ) { fResult = result ; fChildrenMap = new HashMap < Object , Set < Object > > ( ) ; if ( result != null ) { Object [ ] elements = result . getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { insert ( elements [ i ] , false ) ; } } } private void insert ( Object child , boolean refreshViewer ) { Object parent = getParent ( child ) ; while ( parent != null ) { if ( insertChild ( parent , child ) ) { if ( refreshViewer && ! fTreeViewer . getControl ( ) . isDisposed ( ) ) { fTreeViewer . add ( parent , child ) ; } } else { if ( refreshViewer && ! fTreeViewer . getControl ( ) . isDisposed ( ) ) { fTreeViewer . refresh ( parent ) ; } return ; } child = parent ; parent = getParent ( child ) ; } if ( insertChild ( fResult , child ) ) { if ( refreshViewer && ! fTreeViewer . getControl ( ) . isDisposed ( ) ) { fTreeViewer . add ( fResult , child ) ; } } } private void remove ( Object element , boolean refreshViewer ) { if ( hasChildren ( element ) ) { if ( refreshViewer && ! fTreeViewer . getControl ( ) . isDisposed ( ) ) { fTreeViewer . refresh ( element ) ; } } else { if ( ! hasMatches ( element ) ) { fChildrenMap . remove ( element ) ; Object parent = getParent ( element ) ; if ( parent != null ) { removeFromSiblings ( element , parent ) ; remove ( parent , refreshViewer ) ; } else { removeFromSiblings ( element , fResult ) ; if ( refreshViewer && ! fTreeViewer . getControl ( ) . isDisposed ( ) ) { fTreeViewer . refresh ( ) ; } } } else { if ( refreshViewer && ! fTreeViewer . getControl ( ) . isDisposed ( ) ) { fTreeViewer . refresh ( element ) ; } } } } private boolean hasMatches ( Object element ) { return fResult . getMatchCount ( element ) > ; } private void removeFromSiblings ( Object element , Object parent ) { Set < Object > siblings = fChildrenMap . get ( parent ) ; if ( siblings != null ) { siblings . remove ( element ) ; } } private boolean insertChild ( Object parent , Object child ) { Set < Object > children = fChildrenMap . get ( parent ) ; if ( children == null ) { children = new HashSet < Object > ( ) ; fChildrenMap . put ( parent , children ) ; } return children . add ( child ) ; } public Object [ ] getElements ( Object inputElement ) { Object [ ] children = getChildren ( inputElement ) ; System . out . println ( "" + children . length ) ; return children ; } public Object [ ] getChildren ( Object parentElement ) { Set < Object > children = fChildrenMap . get ( parentElement ) ; if ( children == null ) { return EMPTY ; } else { return children . toArray ( ) ; } } public Object getParent ( Object element ) { if ( element instanceof IProject ) { return null ; } if ( element instanceof IResource ) { IResource resource = ( IResource ) element ; return resource . getParent ( ) ; } return null ; } public boolean hasChildren ( Object element ) { return getChildren ( element ) . length > ; } public synchronized void elementsChanged ( Object [ ] updatedElements ) { for ( int i = ; i < updatedElements . length ; i ++ ) { if ( fResult . getMatchCount ( updatedElements [ i ] ) > ) insert ( updatedElements [ i ] , true ) ; else remove ( updatedElements [ i ] , true ) ; } } public void clear ( ) { initialize ( fResult ) ; if ( ! fTreeViewer . getControl ( ) . isDisposed ( ) ) { fTreeViewer . refresh ( ) ; } } } package net . sf . sveditor . ui . search ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import org . eclipse . search . ui . text . Match ; public class SVSearchMatch extends Match { private SVDBFile fFile ; public SVSearchMatch ( ISVDBItemBase item ) { super ( item , , ) ; } public SVDBFile getFile ( ) { if ( fFile == null ) { if ( getElement ( ) instanceof ISVDBChildItem ) { ISVDBChildItem it = ( ISVDBChildItem ) getElement ( ) ; while ( it != null ) { if ( it . getType ( ) == SVDBItemType . File ) { fFile = ( SVDBFile ) it ; break ; } it = it . getParent ( ) ; } } } return fFile ; } } package net . sf . sveditor . ui . search ; import org . eclipse . jface . preference . JFacePreferences ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ColumnViewer ; import org . eclipse . jface . viewers . DecoratingStyledCellLabelProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . StyledString ; import org . eclipse . jface . viewers . StyledString . Styler ; import org . eclipse . jface . viewers . ViewerColumn ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IWorkbenchPreferenceConstants ; import org . eclipse . ui . PlatformUI ; public class SVDecoratingSearchTableLabelProvider extends DecoratingStyledCellLabelProvider implements ILabelProvider , IPropertyChangeListener { private static final String HIGHLIGHT_BG_COLOR_NAME = "" ; public static final Styler HIGHLIGHT_STYLE = StyledString . createColorRegistryStyler ( null , HIGHLIGHT_BG_COLOR_NAME ) ; public SVDecoratingSearchTableLabelProvider ( SVSearchTableLabelProvider provider ) { super ( provider , PlatformUI . getWorkbench ( ) . getDecoratorManager ( ) . getLabelDecorator ( ) , null ) ; } public void initialize ( ColumnViewer viewer , ViewerColumn column ) { PlatformUI . getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; JFaceResources . getColorRegistry ( ) . addListener ( this ) ; setOwnerDrawEnabled ( showColoredLabels ( ) ) ; super . initialize ( viewer , column ) ; } public void dispose ( ) { super . dispose ( ) ; PlatformUI . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; JFaceResources . getColorRegistry ( ) . removeListener ( this ) ; } private void refresh ( ) { ColumnViewer viewer = getViewer ( ) ; if ( viewer == null ) { return ; } boolean showColoredLabels = showColoredLabels ( ) ; if ( showColoredLabels != isOwnerDrawEnabled ( ) ) { setOwnerDrawEnabled ( showColoredLabels ) ; viewer . refresh ( ) ; } else if ( showColoredLabels ) { viewer . refresh ( ) ; } } protected StyleRange prepareStyleRange ( StyleRange styleRange , boolean applyColors ) { if ( ! applyColors && styleRange . background != null ) { styleRange = super . prepareStyleRange ( styleRange , applyColors ) ; styleRange . borderStyle = SWT . BORDER_DOT ; return styleRange ; } return super . prepareStyleRange ( styleRange , applyColors ) ; } public static boolean showColoredLabels ( ) { return PlatformUI . getPreferenceStore ( ) . getBoolean ( IWorkbenchPreferenceConstants . USE_COLORED_LABELS ) ; } public void propertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( property . equals ( JFacePreferences . QUALIFIER_COLOR ) || property . equals ( JFacePreferences . COUNTER_COLOR ) || property . equals ( JFacePreferences . DECORATIONS_COLOR ) || property . equals ( HIGHLIGHT_BG_COLOR_NAME ) || property . equals ( IWorkbenchPreferenceConstants . USE_COLORED_LABELS ) ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { refresh ( ) ; } } ) ; } } public String getText ( Object element ) { return getStyledText ( element ) . getString ( ) ; } } package net . sf . sveditor . ui . search ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . SVCorePlugin ; import net . sf . sveditor . core . db . index . ISVDBIndexIterator ; import net . sf . sveditor . core . db . index . SVDBIndexListIterator ; import net . sf . sveditor . core . db . project . SVDBProjectData ; import net . sf . sveditor . core . db . project . SVDBProjectManager ; import net . sf . sveditor . core . db . search . SVDBSearchSpecification ; import net . sf . sveditor . core . db . search . SVDBSearchType ; import net . sf . sveditor . core . db . search . SVDBSearchUsage ; import net . sf . sveditor . core . log . LogFactory ; import net . sf . sveditor . core . log . LogHandle ; import net . sf . sveditor . ui . SVUiPlugin ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . DialogPage ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . search . ui . ISearchPage ; import org . eclipse . search . ui . ISearchPageContainer ; import org . eclipse . search . ui . ISearchQuery ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . ui . IWorkingSet ; public class SVSearchPage extends DialogPage implements ISearchPage { private Combo fSearchExprCombo ; private Button fCaseSensitiveButton ; private Button fSearchForTypeButton ; private Button fSearchForMethodButton ; private Button fSearchForPackageButton ; private Button fSearchForFieldButton ; private ISearchPageContainer fContainer ; private Button fLimitToDeclarationsButton ; private Button fLimitToReferencesButton ; private Button fLimitToAllButton ; private LogHandle fLog ; private List < SearchSettings > fSearchHistory ; private SearchSettings fCurrentSearch ; private static final String PAGE_NAME = "" ; private class SearchSettings { public String fSearchExpr ; public SVDBSearchType fSearchFor ; public SVDBSearchUsage fLimitTo ; public boolean fCaseSensitive ; public SearchSettings ( ) { fSearchExpr = "" ; fSearchFor = SVDBSearchType . Type ; fLimitTo = SVDBSearchUsage . Declaration ; fCaseSensitive = false ; } public void store ( IDialogSettings s ) { s . put ( PREF_CASE_SENSITIVE , fCaseSensitive ) ; s . put ( PREF_SEARCH_FOR , fSearchFor . name ( ) ) ; s . put ( PREF_LIMIT_TO , fLimitTo . name ( ) ) ; s . put ( PREF_PATTERN , fSearchExpr ) ; } public void load ( IDialogSettings s ) { fCaseSensitive = s . getBoolean ( PREF_CASE_SENSITIVE ) ; String search_for = s . get ( PREF_SEARCH_FOR ) ; if ( search_for == null ) { search_for = "" ; } if ( search_for . equals ( SVDBSearchType . Type . name ( ) ) ) { fSearchFor = SVDBSearchType . Type ; } else if ( search_for . equals ( SVDBSearchType . Method . name ( ) ) ) { fSearchFor = SVDBSearchType . Method ; } else if ( search_for . equals ( SVDBSearchType . Package . name ( ) ) ) { fSearchFor = SVDBSearchType . Package ; } else if ( search_for . equals ( SVDBSearchType . Field . name ( ) ) ) { fSearchFor = SVDBSearchType . Field ; } else { fSearchFor = SVDBSearchType . Type ; } String limit_to = s . get ( PREF_LIMIT_TO ) ; if ( limit_to == null ) { limit_to = "" ; } if ( limit_to . equals ( SVDBSearchUsage . Declaration . name ( ) ) ) { fLimitTo = SVDBSearchUsage . Declaration ; } else if ( limit_to . equals ( SVDBSearchUsage . Reference . name ( ) ) ) { fLimitTo = SVDBSearchUsage . Reference ; } else if ( limit_to . equals ( SVDBSearchUsage . All . name ( ) ) ) { fLimitTo = SVDBSearchUsage . All ; } else { fLimitTo = SVDBSearchUsage . Declaration ; } fSearchExpr = s . get ( PREF_PATTERN ) ; } public void apply ( ) { fCaseSensitiveButton . setSelection ( fCaseSensitive ) ; fSearchExprCombo . setText ( fSearchExpr ) ; fSearchForTypeButton . setSelection ( false ) ; fSearchForMethodButton . setSelection ( false ) ; fSearchForPackageButton . setSelection ( false ) ; fSearchForFieldButton . setSelection ( false ) ; switch ( fSearchFor ) { case Type : fSearchForTypeButton . setSelection ( true ) ; break ; case Field : fSearchForFieldButton . setSelection ( true ) ; break ; case Method : fSearchForMethodButton . setSelection ( true ) ; break ; case Package : fSearchForPackageButton . setSelection ( true ) ; break ; } fLimitToDeclarationsButton . setSelection ( false ) ; fLimitToReferencesButton . setSelection ( false ) ; fLimitToAllButton . setSelection ( false ) ; switch ( fLimitTo ) { case Declaration : fLimitToDeclarationsButton . setSelection ( true ) ; break ; case Reference : fLimitToReferencesButton . setSelection ( true ) ; break ; case All : fLimitToAllButton . setSelection ( true ) ; break ; } } public SearchSettings duplicate ( ) { SearchSettings ret = new SearchSettings ( ) ; ret . fCaseSensitive = fCaseSensitive ; ret . fLimitTo = fLimitTo ; ret . fSearchExpr = fSearchExpr ; ret . fSearchFor = fSearchFor ; return ret ; } public boolean equals ( Object other ) { if ( other instanceof SearchSettings ) { SearchSettings s = ( SearchSettings ) other ; return ( s . fCaseSensitive == fCaseSensitive ) && ( s . fLimitTo == fLimitTo ) && ( s . fSearchExpr . equals ( fSearchExpr ) ) && ( s . fSearchFor == fSearchFor ) ; } else { return false ; } } } public SVSearchPage ( ) { super ( ) ; fSearchHistory = new ArrayList < SVSearchPage . SearchSettings > ( ) ; fCurrentSearch = new SearchSettings ( ) ; fLog = LogFactory . getLogHandle ( "" ) ; } public SVSearchPage ( String title ) { super ( title ) ; } public SVSearchPage ( String title , ImageDescriptor image ) { super ( title , image ) ; } private ISearchQuery createQuery ( ) { SVDBSearchSpecification spec = new SVDBSearchSpecification ( fCurrentSearch . fSearchExpr . trim ( ) , fCurrentSearch . fCaseSensitive , false ) ; spec . setSearchType ( fCurrentSearch . fSearchFor ) ; spec . setSearchUsage ( fCurrentSearch . fLimitTo ) ; SVDBIndexListIterator search_ctxt = new SVDBIndexListIterator ( ) ; switch ( fContainer . getSelectedScope ( ) ) { case ISearchPageContainer . SELECTED_PROJECTS_SCOPE : { IWorkspace ws = ResourcesPlugin . getWorkspace ( ) ; SVDBProjectManager mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; for ( String pn : fContainer . getSelectedProjectNames ( ) ) { IProject p = ws . getRoot ( ) . getProject ( pn ) ; SVDBProjectData p_data = mgr . getProjectData ( p ) ; if ( p_data != null ) { ISVDBIndexIterator it = p_data . getProjectIndexMgr ( ) ; search_ctxt . addIndexIterator ( it ) ; } } } break ; case ISearchPageContainer . WORKSPACE_SCOPE : { IWorkspace ws = ResourcesPlugin . getWorkspace ( ) ; SVDBProjectManager mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; for ( IProject p : ws . getRoot ( ) . getProjects ( ) ) { SVDBProjectData p_data = mgr . getProjectData ( p ) ; if ( p_data != null ) { ISVDBIndexIterator it = p_data . getProjectIndexMgr ( ) ; search_ctxt . addIndexIterator ( it ) ; } } } break ; case ISearchPageContainer . WORKING_SET_SCOPE : { for ( IWorkingSet set : fContainer . getSelectedWorkingSets ( ) ) { SVDBProjectManager mgr = SVCorePlugin . getDefault ( ) . getProjMgr ( ) ; for ( IAdaptable adapter : set . getElements ( ) ) { Object project_o = adapter . getAdapter ( IProject . class ) ; if ( project_o != null ) { IProject project = ( IProject ) project_o ; SVDBProjectData p_data = mgr . getProjectData ( project ) ; if ( p_data != null ) { ISVDBIndexIterator it = p_data . getProjectIndexMgr ( ) ; search_ctxt . addIndexIterator ( it ) ; } } } } } break ; case ISearchPageContainer . SELECTION_SCOPE : { fLog . error ( "" ) ; ISelection sel = fContainer . getSelection ( ) ; if ( sel instanceof IStructuredSelection ) { IStructuredSelection ss = ( IStructuredSelection ) sel ; for ( Object sel_o : ss . toList ( ) ) { if ( sel_o instanceof IProject ) { } else if ( sel_o instanceof IFile ) { } } } } break ; } return new SVSearchQuery ( search_ctxt , spec ) ; } public boolean performAction ( ) { saveSettings ( true ) ; try { NewSearchUI . runQueryInBackground ( createQuery ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; ErrorDialog . openError ( getShell ( ) , "" , "" , Status . CANCEL_STATUS ) ; return false ; } return true ; } @ Override public void dispose ( ) { super . dispose ( ) ; } public void setContainer ( ISearchPageContainer container ) { fContainer = container ; fContainer . setPerformActionEnabled ( true ) ; } public void createControl ( Composite parent ) { Composite c = new Composite ( parent , SWT . NONE ) ; setControl ( c ) ; c . setLayout ( new GridLayout ( , false ) ) ; Composite composite = new Composite ( c , SWT . NONE ) ; composite . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false , , ) ) ; composite . setLayout ( new GridLayout ( , false ) ) ; fSearchExprCombo = new Combo ( composite , SWT . NONE ) ; fSearchExprCombo . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false , , ) ) ; fSearchExprCombo . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fCurrentSearch . fSearchExpr = fSearchExprCombo . getText ( ) ; } } ) ; fSearchExprCombo . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { fCurrentSearch = fSearchHistory . get ( fSearchExprCombo . getSelectionIndex ( ) ) . duplicate ( ) ; fCurrentSearch . apply ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; fCaseSensitiveButton = new Button ( composite , SWT . CHECK ) ; fCaseSensitiveButton . setText ( "" ) ; fCaseSensitiveButton . addSelectionListener ( prvButtonSelectionListener ) ; Composite composite_1 = new Composite ( c , SWT . NONE ) ; composite_1 . setLayout ( new GridLayout ( , true ) ) ; composite_1 . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false , , ) ) ; Group grpSearchFor = new Group ( composite_1 , SWT . NONE ) ; grpSearchFor . setText ( "" ) ; grpSearchFor . setLayout ( new GridLayout ( , true ) ) ; GridData gd_grpSearchFor = new GridData ( SWT . FILL , SWT . CENTER , true , false , , ) ; gd_grpSearchFor . widthHint = ; grpSearchFor . setLayoutData ( gd_grpSearchFor ) ; fSearchForTypeButton = new Button ( grpSearchFor , SWT . RADIO ) ; fSearchForTypeButton . setLayoutData ( new GridData ( SWT . LEFT , SWT . CENTER , true , false , , ) ) ; fSearchForTypeButton . setText ( "" ) ; fSearchForTypeButton . addSelectionListener ( prvButtonSelectionListener ) ; fSearchForMethodButton = new Button ( grpSearchFor , SWT . RADIO ) ; fSearchForMethodButton . setLayoutData ( new GridData ( SWT . LEFT , SWT . CENTER , true , false , , ) ) ; fSearchForMethodButton . setText ( "" ) ; fSearchForMethodButton . addSelectionListener ( prvButtonSelectionListener ) ; fSearchForPackageButton = new Button ( grpSearchFor , SWT . RADIO ) ; fSearchForPackageButton . setLayoutData ( new GridData ( SWT . LEFT , SWT . CENTER , true , false , , ) ) ; fSearchForPackageButton . setText ( "" ) ; fSearchForPackageButton . addSelectionListener ( prvButtonSelectionListener ) ; fSearchForFieldButton = new Button ( grpSearchFor , SWT . RADIO ) ; fSearchForFieldButton . setLayoutData ( new GridData ( SWT . LEFT , SWT . FILL , true , true , , ) ) ; fSearchForFieldButton . setText ( "" ) ; fSearchForFieldButton . addSelectionListener ( prvButtonSelectionListener ) ; Group grpLimitTo = new Group ( composite_1 , SWT . NONE ) ; grpLimitTo . setText ( "" ) ; grpLimitTo . setLayout ( new GridLayout ( , false ) ) ; GridData gd_grpLimitTo = new GridData ( SWT . FILL , SWT . FILL , true , true , , ) ; gd_grpLimitTo . widthHint = ; grpLimitTo . setLayoutData ( gd_grpLimitTo ) ; fLimitToDeclarationsButton = new Button ( grpLimitTo , SWT . RADIO ) ; fLimitToDeclarationsButton . setText ( "" ) ; fLimitToDeclarationsButton . addSelectionListener ( prvButtonSelectionListener ) ; fLimitToReferencesButton = new Button ( grpLimitTo , SWT . RADIO ) ; fLimitToReferencesButton . setText ( "" ) ; fLimitToReferencesButton . addSelectionListener ( prvButtonSelectionListener ) ; fLimitToReferencesButton . setEnabled ( false ) ; fLimitToAllButton = new Button ( grpLimitTo , SWT . RADIO ) ; fLimitToAllButton . setText ( "" ) ; fLimitToAllButton . addSelectionListener ( prvButtonSelectionListener ) ; fLimitToAllButton . setEnabled ( false ) ; setControl ( c ) ; loadSettings ( ) ; } private SelectionListener prvButtonSelectionListener = new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { if ( e . getSource ( ) == fCaseSensitiveButton ) { fCurrentSearch . fCaseSensitive = fCaseSensitiveButton . getSelection ( ) ; } if ( e . getSource ( ) == fSearchForTypeButton ) { fCurrentSearch . fSearchFor = SVDBSearchType . Type ; } if ( e . getSource ( ) == fSearchForMethodButton ) { fCurrentSearch . fSearchFor = SVDBSearchType . Method ; } if ( e . getSource ( ) == fSearchForPackageButton ) { fCurrentSearch . fSearchFor = SVDBSearchType . Package ; } if ( e . getSource ( ) == fSearchForFieldButton ) { fCurrentSearch . fSearchFor = SVDBSearchType . Field ; } if ( e . getSource ( ) == fLimitToDeclarationsButton ) { fCurrentSearch . fLimitTo = SVDBSearchUsage . Declaration ; } if ( e . getSource ( ) == fLimitToReferencesButton ) { fCurrentSearch . fLimitTo = SVDBSearchUsage . Reference ; } if ( e . getSource ( ) == fLimitToAllButton ) { fCurrentSearch . fLimitTo = SVDBSearchUsage . All ; } } public void widgetDefaultSelected ( SelectionEvent e ) { } } ; private static final String PREF_CASE_SENSITIVE = "" ; private static final String PREF_SEARCH_FOR = "" ; private static final String PREF_LIMIT_TO = "" ; private static final int HISTORY_MAX_SIZE = ; private static final String PREF_HISTORY_SIZE = "" ; private static final String PREF_HISTORY = "" ; private static final String PREF_PATTERN = "" ; private void saveSettings ( boolean on_search ) { IDialogSettings s = SVUiPlugin . getDefault ( ) . getDialogSettingsSection ( PAGE_NAME ) ; List < SearchSettings > items = new ArrayList < SVSearchPage . SearchSettings > ( ) ; items . addAll ( fSearchHistory ) ; int current_idx = - ; for ( int i = ; i < items . size ( ) ; i ++ ) { SearchSettings setting = items . get ( i ) ; if ( setting . fSearchExpr . equals ( fCurrentSearch . fSearchExpr ) ) { current_idx = i ; } } if ( current_idx == - ) { if ( on_search ) { items . add ( , fCurrentSearch ) ; } } else { if ( on_search ) { items . remove ( current_idx ) ; items . add ( , fCurrentSearch ) ; } } int history_size = Math . min ( HISTORY_MAX_SIZE , items . size ( ) ) ; s . put ( PREF_HISTORY_SIZE , history_size ) ; for ( int i = ; i < history_size ; i ++ ) { IDialogSettings hist_setting = s . addNewSection ( PREF_HISTORY + i ) ; items . get ( i ) . store ( hist_setting ) ; } } private void loadSettings ( ) { IDialogSettings s = SVUiPlugin . getDefault ( ) . getDialogSettingsSection ( PAGE_NAME ) ; fSearchExprCombo . removeAll ( ) ; if ( s . get ( PREF_HISTORY_SIZE ) != null ) { int history_size = s . getInt ( PREF_HISTORY_SIZE ) ; if ( history_size > ) { fSearchHistory . clear ( ) ; for ( int i = ; i < history_size ; i ++ ) { IDialogSettings history_setting = s . getSection ( PREF_HISTORY + i ) ; SearchSettings setting = new SearchSettings ( ) ; setting . load ( history_setting ) ; fSearchHistory . add ( setting ) ; fSearchExprCombo . add ( setting . fSearchExpr ) ; } fSearchExprCombo . select ( ) ; fCurrentSearch = fSearchHistory . get ( ) . duplicate ( ) ; } } fCurrentSearch . apply ( ) ; } } package net . sf . sveditor . ui . search ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; public class OpenSVSearchAction implements IWorkbenchWindowActionDelegate { private static final String SV_SEARCH_PAGE_ID = "" ; private IWorkbenchWindow fWindow ; public void run ( IAction action ) { if ( fWindow == null || fWindow . getActivePage ( ) == null ) { return ; } NewSearchUI . openSearchDialog ( fWindow , SV_SEARCH_PAGE_ID ) ; } public void selectionChanged ( IAction action , ISelection selection ) { } public void dispose ( ) { fWindow = null ; } public void init ( IWorkbenchWindow window ) { fWindow = window ; } } package net . sf . sveditor . ui . search ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; public class SVSearchTableContentProvider implements IStructuredContentProvider { private SVSearchResult fResult ; private TableViewer fTableViewer ; public SVSearchTableContentProvider ( SVSearchResultsPage page , TableViewer viewer ) { fTableViewer = viewer ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fResult = ( SVSearchResult ) newInput ; } public Object [ ] getElements ( Object inputElement ) { return fResult . getElements ( ) ; } public synchronized void elementsChanged ( Object [ ] updatedElements ) { if ( ! fTableViewer . getControl ( ) . isDisposed ( ) ) { fTableViewer . refresh ( ) ; } } public void clear ( ) { fTableViewer . refresh ( ) ; } } package net . sf . sveditor . ui . search ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . search . ui . ISearchQuery ; import org . eclipse . search . ui . text . AbstractTextSearchResult ; import org . eclipse . search . ui . text . IEditorMatchAdapter ; import org . eclipse . search . ui . text . IFileMatchAdapter ; import org . eclipse . search . ui . text . Match ; import org . eclipse . ui . IEditorPart ; public class SVSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter { private SVSearchQuery fQuery ; public SVSearchResult ( SVSearchQuery query ) { fQuery = query ; } public String getLabel ( ) { return fQuery . getLabel ( ) ; } public String getTooltip ( ) { return "" ; } public ImageDescriptor getImageDescriptor ( ) { return null ; } public ISearchQuery getQuery ( ) { return fQuery ; } @ Override public IEditorMatchAdapter getEditorMatchAdapter ( ) { return null ; } @ Override public IFileMatchAdapter getFileMatchAdapter ( ) { return null ; } public boolean isShownInEditor ( Match match , IEditorPart editor ) { System . out . println ( "" + match . getElement ( ) + "" + editor . getTitle ( ) ) ; return false ; } public Match [ ] computeContainedMatches ( AbstractTextSearchResult result , IEditorPart editor ) { System . out . println ( "" + editor . getTitle ( ) ) ; return null ; } } package net . sf . sveditor . ui . search ; import java . io . File ; import net . sf . sveditor . core . db . ISVDBChildItem ; import net . sf . sveditor . core . db . ISVDBItemBase ; import net . sf . sveditor . core . db . SVDBFile ; import net . sf . sveditor . core . db . SVDBItemType ; import net . sf . sveditor . ui . svcp . SVTreeLabelProvider ; import org . eclipse . jface . viewers . DelegatingStyledCellLabelProvider . IStyledLabelProvider ; import org . eclipse . jface . viewers . StyledString ; public class SVSearchTableLabelProvider extends SVTreeLabelProvider implements IStyledLabelProvider { public SVSearchTableLabelProvider ( ) { fShowFunctionRetType = false ; } public StyledString getStyledText ( Object element ) { if ( element instanceof ISVDBItemBase ) { StyledString ret = super . getStyledText ( element ) ; ISVDBItemBase item = ( ISVDBItemBase ) element ; SVDBFile file = getFile ( item ) ; if ( file != null ) { String filename = new File ( file . getFilePath ( ) ) . getName ( ) ; ret . append ( "" ) ; ret . append ( filename , StyledString . QUALIFIER_STYLER ) ; } return ret ; } else { return new StyledString ( super . getText ( element ) ) ; } } private static SVDBFile getFile ( ISVDBItemBase item ) { SVDBFile ret = null ; if ( item instanceof ISVDBChildItem ) { ISVDBChildItem it = ( ISVDBChildItem ) item ; while ( it != null ) { if ( it . getType ( ) == SVDBItemType . File ) { ret = ( SVDBFile ) it ; break ; } else { it = it . getParent ( ) ; } } } return ret ; } } package net . sf . sveditor . ui ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; public class WorkspaceFileDialog extends Dialog { private String fPathStr ; private TreeViewer fTreeViewer ; private boolean fSelectFiles = true ; public WorkspaceFileDialog ( Shell shell ) { super ( shell ) ; } public String getPath ( ) { return fPathStr ; } public void setSelectFiles ( boolean sel_files ) { fSelectFiles = sel_files ; } @ Override protected Control createDialogArea ( Composite p ) { Composite parent = new Composite ( p , SWT . NONE ) ; parent . setLayout ( new GridLayout ( , true ) ) ; fTreeViewer = new TreeViewer ( parent ) ; GridData gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gd . widthHint = ; gd . heightHint = ; fTreeViewer . getControl ( ) . setLayoutData ( gd ) ; fTreeViewer . setContentProvider ( new WorkbenchContentProvider ( ) ) ; fTreeViewer . setLabelProvider ( new WorkbenchLabelProvider ( ) ) ; fTreeViewer . setInput ( ResourcesPlugin . getWorkspace ( ) ) ; fTreeViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) fTreeViewer . getSelection ( ) ; if ( fSelectFiles ) { if ( sel . getFirstElement ( ) != null && sel . getFirstElement ( ) instanceof IFile ) { fPathStr = ( ( IFile ) sel . getFirstElement ( ) ) . getFullPath ( ) . toOSString ( ) ; getButton ( IDialogConstants . OK_ID ) . setEnabled ( true ) ; } else { getButton ( IDialogConstants . OK_ID ) . setEnabled ( false ) ; } } else { if ( sel . getFirstElement ( ) != null && sel . getFirstElement ( ) instanceof IContainer ) { fPathStr = ( ( IContainer ) sel . getFirstElement ( ) ) . getFullPath ( ) . toOSString ( ) ; getButton ( IDialogConstants . OK_ID ) . setEnabled ( true ) ; } else { getButton ( IDialogConstants . OK_ID ) . setEnabled ( false ) ; } } } } ) ; return fTreeViewer . getControl ( ) ; } } package net . sf . sveditor . core . batch . python ; import java . util . Properties ; import org . eclipse . core . runtime . Status ; import org . eclipse . equinox . app . IApplication ; import org . eclipse . equinox . app . IApplicationContext ; import org . python . core . PyDictionary ; import org . python . core . PyString ; import org . python . core . PySystemState ; import org . python . util . PythonInterpreter ; public class SVEditorPythonApplication implements IApplication { static boolean fInitialized ; public Object start ( IApplicationContext context ) throws Exception { String args [ ] = ( String [ ] ) context . getArguments ( ) . get ( IApplicationContext . APPLICATION_ARGS ) ; if ( args . length < ) { throw new Exception ( "" ) ; } if ( ! fInitialized ) { Properties p = new Properties ( ) ; PythonInterpreter . initialize ( System . getProperties ( ) , p , new String [ ] { } ) ; fInitialized = true ; } PySystemState ss = new PySystemState ( ) ; for ( int i = ; i < args . length ; i ++ ) { ss . argv . add ( new PyString ( args [ i ] ) ) ; } PyDictionary ls = new PyDictionary ( ) ; PythonInterpreter interp = new PythonInterpreter ( ls , ss ) ; interp . execfile ( args [ ] ) ; return Status . OK_STATUS ; } public void stop ( ) { } } package net . sf . sveditor . core . batch ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import org . osgi . framework . BundleActivator ; import org . osgi . framework . BundleContext ; public class SVBatchPlugin implements BundleActivator { private static BundleContext context ; private static SVBatchPlugin fDefault ; private List < File > fTempDirs ; private List < ISVDBIndex > fLocalIndexes ; static BundleContext getContext ( ) { return context ; } public void start ( BundleContext bundleContext ) throws Exception { SVBatchPlugin . context = bundleContext ; fTempDirs = new ArrayList < File > ( ) ; fLocalIndexes = new ArrayList < ISVDBIndex > ( ) ; fDefault = this ; } public void stop ( BundleContext bundleContext ) throws Exception { for ( ISVDBIndex index : fLocalIndexes ) { index . dispose ( ) ; } for ( File tmpdir : fTempDirs ) { deleteTree ( tmpdir ) ; } SVBatchPlugin . context = null ; fDefault = null ; } private static void deleteTree ( File dir ) { if ( dir . isFile ( ) ) { dir . delete ( ) ; } else { File e [ ] = dir . listFiles ( ) ; if ( e != null ) { for ( File t : e ) { if ( t . getName ( ) . equals ( "" ) || t . getName ( ) . equals ( "" ) ) { System . out . println ( "" ) ; continue ; } if ( t . isDirectory ( ) ) { deleteTree ( t ) ; } else { t . delete ( ) ; } } } dir . delete ( ) ; } } public static synchronized File createTempDir ( ) { File tmpdir = new File ( System . getProperty ( "" ) ) ; File ret = null ; for ( int i = ; i < ; i ++ ) { File tmp = new File ( tmpdir , "" + i ) ; if ( ! tmp . isDirectory ( ) ) { tmp . mkdirs ( ) ; ret = tmp ; break ; } } if ( ret != null ) { fDefault . fTempDirs . add ( ret ) ; } else { System . out . println ( "" ) ; } return ret ; } public static synchronized void addIndex ( ISVDBIndex index ) { fDefault . fLocalIndexes . add ( index ) ; } } package net . sf . sveditor . core . batch ; import java . io . File ; import org . eclipse . core . runtime . NullProgressMonitor ; import net . sf . sveditor . core . db . index . ISVDBIndex ; import net . sf . sveditor . core . db . index . SVDBArgFileIndexFactory ; import net . sf . sveditor . core . db . index . SVDBIndexUtil ; import net . sf . sveditor . core . db . index . cache . SVDBDirFS ; import net . sf . sveditor . core . db . index . cache . SVDBFileIndexCache ; public class SVEditorVlogIndexFactory { public static ISVDBIndex vlog ( String args [ ] ) { return vlog_loc ( System . getProperty ( "" ) , args ) ; } public static ISVDBIndex vlog_loc ( String location , String args [ ] ) { ISVDBIndex index = null ; StringBuilder sb = new StringBuilder ( ) ; for ( String arg : args ) { arg = SVDBIndexUtil . expandVars ( arg , null , false ) ; if ( arg . indexOf ( '' ) != - || arg . indexOf ( '' ) != - ) { sb . append ( "" + arg + "" ) ; } else { sb . append ( arg + "" ) ; } } SVDBArgFileIndexFactory f = new SVDBArgFileIndexFactory ( ) ; File tmpdir = SVBatchPlugin . createTempDir ( ) ; SVDBDirFS dir_fs = new SVDBDirFS ( tmpdir ) ; SVDBFileIndexCache index_c = new SVDBFileIndexCache ( dir_fs ) ; index = f . createSVDBIndex ( null , location , sb , index_c , null ) ; index . init ( new NullProgressMonitor ( ) ) ; return index ; } } package com . postmark . java ; import java . util . * ; public class TestClient { public static void main ( String [ ] args ) { List < NameValuePair > headers = new ArrayList < NameValuePair > ( ) ; headers . add ( new NameValuePair ( "" , "" ) ) ; PostmarkMessage message = new PostmarkMessage ( args [ ] , args [ ] , args [ ] , args [ ] , args [ ] , args [ ] , false , args [ ] , headers ) ; String apiKey = "" ; if ( args [ ] != null ) apiKey = args [ ] ; PostmarkClient client = new PostmarkClient ( apiKey ) ; try { client . sendMessage ( message ) ; } catch ( PostmarkException pe ) { System . out . println ( "" + pe . getMessage ( ) ) ; } } } package com . postmark . java ; import com . google . gson . * ; import org . joda . time . DateTime ; import java . lang . reflect . Type ; public class DateTimeTypeAdapter implements JsonSerializer < DateTime > , JsonDeserializer < DateTime > { public JsonElement serialize ( DateTime src , Type typeOfSrc , JsonSerializationContext context ) { return new JsonPrimitive ( src . toString ( ) ) ; } public DateTime deserialize ( JsonElement json , Type typeOfT , JsonDeserializationContext context ) throws JsonParseException { return new DateTime ( json . getAsJsonPrimitive ( ) . getAsString ( ) ) ; } } package com . postmark . java ; public class NameValuePair { private String name ; private String value ; public NameValuePair ( String name , String value ) { this . name = name ; this . value = value ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getValue ( ) { return value ; } public void setValue ( String value ) { this . value = value ; } public String toString ( ) { return name + "" + value ; } @ Override public boolean equals ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) != o . getClass ( ) ) return false ; NameValuePair that = ( NameValuePair ) o ; if ( name != null ? ! name . equals ( that . name ) : that . name != null ) return false ; if ( value != null ? ! value . equals ( that . value ) : that . value != null ) return false ; return true ; } @ Override public int hashCode ( ) { int result = name != null ? name . hashCode ( ) : ; result = * result + ( value != null ? value . hashCode ( ) : ) ; return result ; } } package com . postmark . java ; public class Attachment { private String name ; private String contentType ; private String content ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getContentType ( ) { return contentType ; } public void setContentType ( String contentType ) { this . contentType = contentType ; } public String getContent ( ) { return content ; } public void setContent ( String content ) { this . content = content ; } @ Override public String toString ( ) { return "" + name + "" + contentType + "" + content + "" ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( content == null ) ? : content . hashCode ( ) ) ; result = prime * result + ( ( contentType == null ) ? : contentType . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Attachment other = ( Attachment ) obj ; if ( content == null ) { if ( other . content != null ) return false ; } else if ( ! content . equals ( other . content ) ) return false ; if ( contentType == null ) { if ( other . contentType != null ) return false ; } else if ( ! contentType . equals ( other . contentType ) ) return false ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; return true ; } } package com . postmark . java ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( { ElementType . FIELD } ) public @ interface SkipMe { } package com . postmark . java ; import com . google . gson . annotations . SerializedName ; import org . joda . time . DateTime ; enum PostmarkStatus { UNKNOWN , SUCCESS , USERERROR , SERVERERROR } public class PostmarkResponse { @ SerializedName ( "" ) public PostmarkStatus status ; @ SerializedName ( "" ) public String message ; @ SerializedName ( "" ) public DateTime submittedAt ; @ SerializedName ( "" ) public String to ; @ SerializedName ( "" ) public int errorCode ; public PostmarkStatus getStatus ( ) { return status ; } public void setStatus ( PostmarkStatus status ) { this . status = status ; } public String getMessage ( ) { return message ; } public void setMessage ( String message ) { this . message = message ; } public DateTime getSubmittedAt ( ) { return submittedAt ; } public void setSubmittedAt ( DateTime submittedAt ) { this . submittedAt = submittedAt ; } public String getTo ( ) { return to ; } public void setTo ( String to ) { this . to = to ; } public int getErrorCode ( ) { return errorCode ; } public void setErrorCode ( int errorCode ) { this . errorCode = errorCode ; } } package com . postmark . java ; import com . google . gson . annotations . SerializedName ; import java . util . ArrayList ; import java . util . List ; public class PostmarkMessage { @ SerializedName ( "" ) private String fromAddress ; @ SerializedName ( "" ) private String toAddress ; @ SerializedName ( "" ) private String replyToAddress ; @ SerializedName ( "" ) private String ccAddress ; @ SerializedName ( "" ) private String subject ; @ SerializedName ( "" ) private String htmlBody ; @ SerializedName ( "" ) private String textBody ; @ SerializedName ( "" ) private String tag ; @ SerializedName ( "" ) private List < NameValuePair > headers ; @ SerializedName ( "" ) private List < Attachment > attachments ; @ SkipMe private boolean isHTML ; public PostmarkMessage ( String fromAddress , String toAddress , String replyToAddress , String ccAddress , String subject , String body , boolean isHTML , String tag , List < NameValuePair > headers ) { this . isHTML = isHTML ; this . fromAddress = fromAddress ; this . toAddress = toAddress ; this . replyToAddress = replyToAddress ; this . ccAddress = ccAddress ; this . subject = subject ; if ( isHTML ) this . htmlBody = body ; else this . textBody = body ; this . tag = tag ; this . headers = ( headers == null ) ? new ArrayList < NameValuePair > ( ) : headers ; } public PostmarkMessage ( String fromAddress , String toAddress , String replyToAddress , String ccAddress , String subject , String body , boolean isHTML , String tag ) { this ( fromAddress , toAddress , replyToAddress , ccAddress , subject , body , isHTML , tag , null ) ; } public PostmarkMessage ( PostmarkMessage message ) { this . fromAddress = message . fromAddress ; this . toAddress = message . toAddress ; this . replyToAddress = message . replyToAddress ; this . ccAddress = message . ccAddress ; this . subject = message . subject ; this . htmlBody = message . htmlBody ; this . textBody = message . textBody ; this . headers = message . headers ; this . isHTML = message . isHTML ; } public void clean ( ) { this . fromAddress = this . fromAddress . trim ( ) ; this . toAddress = this . toAddress . trim ( ) ; this . subject = ( this . subject == null ) ? "" : this . subject . trim ( ) ; } public void validate ( ) throws PostmarkException { if ( ( this . fromAddress == null ) || ( this . fromAddress . equals ( "" ) ) ) { throw new PostmarkException ( "" ) ; } if ( ( this . toAddress == null ) || ( this . toAddress . equals ( "" ) ) ) { throw new PostmarkException ( "" ) ; } } public String getFromAddress ( ) { return fromAddress ; } public void setFromAddress ( String fromAddress ) { this . fromAddress = fromAddress ; } public String getToAddress ( ) { return toAddress ; } public void setToAddress ( String toAddress ) { this . toAddress = toAddress ; } public String getCcAddress ( ) { return ccAddress ; } public void setCcAddress ( String ccAddress ) { this . ccAddress = ccAddress ; } public String getReplyToAddress ( ) { return replyToAddress ; } public void setReplyToAddress ( String replyToAddress ) { this . replyToAddress = replyToAddress ; } public String getSubject ( ) { return subject ; } public void setSubject ( String subject ) { this . subject = subject ; } public String getHtmlBody ( ) { return htmlBody ; } public void setHtmlBody ( String htmlBody ) { this . htmlBody = htmlBody ; } public String getTextBody ( ) { return textBody ; } public void setTextBody ( String textBody ) { this . textBody = textBody ; } public String getTag ( ) { return tag ; } public void setTag ( String tag ) { this . tag = tag ; } public List < NameValuePair > getHeaders ( ) { return headers ; } public void setHeaders ( List < NameValuePair > headers ) { this . headers = headers ; } public List < Attachment > getAttachments ( ) { return attachments ; } public void setAttachments ( List < Attachment > attachments ) { this . attachments = attachments ; } @ Override public boolean equals ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) != o . getClass ( ) ) return false ; PostmarkMessage that = ( PostmarkMessage ) o ; if ( ccAddress != null ? ! ccAddress . equals ( that . ccAddress ) : that . ccAddress != null ) return false ; if ( fromAddress != null ? ! fromAddress . equals ( that . fromAddress ) : that . fromAddress != null ) return false ; if ( headers != null ? ! headers . equals ( that . headers ) : that . headers != null ) return false ; if ( htmlBody != null ? ! htmlBody . equals ( that . htmlBody ) : that . htmlBody != null ) return false ; if ( replyToAddress != null ? ! replyToAddress . equals ( that . replyToAddress ) : that . replyToAddress != null ) return false ; if ( subject != null ? ! subject . equals ( that . subject ) : that . subject != null ) return false ; if ( textBody != null ? ! textBody . equals ( that . textBody ) : that . textBody != null ) return false ; if ( toAddress != null ? ! toAddress . equals ( that . toAddress ) : that . toAddress != null ) return false ; if ( tag != null ? ! tag . equals ( that . toAddress ) : that . tag != null ) return false ; if ( isHTML != that . isHTML ) return false ; return true ; } @ Override public int hashCode ( ) { int result = fromAddress != null ? fromAddress . hashCode ( ) : ; result = * result + ( toAddress != null ? toAddress . hashCode ( ) : ) ; result = * result + ( ccAddress != null ? ccAddress . hashCode ( ) : ) ; result = * result + ( replyToAddress != null ? replyToAddress . hashCode ( ) : ) ; result = * result + ( subject != null ? subject . hashCode ( ) : ) ; result = * result + ( htmlBody != null ? htmlBody . hashCode ( ) : ) ; result = * result + ( textBody != null ? textBody . hashCode ( ) : ) ; result = * result + ( tag != null ? tag . hashCode ( ) : ) ; result = * result + ( headers != null ? headers . hashCode ( ) : ) ; return result ; } @ Override public String toString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "" ) ; sb . append ( "" ) . append ( fromAddress ) . append ( '' ) ; sb . append ( "" ) . append ( toAddress ) . append ( '' ) ; sb . append ( "" ) . append ( ccAddress ) . append ( '' ) ; sb . append ( "" ) . append ( replyToAddress ) . append ( '' ) ; sb . append ( "" ) . append ( subject ) . append ( '' ) ; sb . append ( "" ) . append ( htmlBody ) . append ( '' ) ; sb . append ( "" ) . append ( textBody ) . append ( '' ) ; sb . append ( "" ) . append ( tag ) . append ( '' ) ; sb . append ( "" ) . append ( headers ) ; sb . append ( '' ) ; return sb . toString ( ) ; } } package com . postmark . java ; import com . google . gson . ExclusionStrategy ; import com . google . gson . FieldAttributes ; public class SkipMeExclusionStrategy implements ExclusionStrategy { private final Class < ? > typeToSkip ; public SkipMeExclusionStrategy ( Class < ? > typeToSkip ) { this . typeToSkip = typeToSkip ; } public boolean shouldSkipClass ( Class < ? > clazz ) { return ( clazz == typeToSkip ) ; } public boolean shouldSkipField ( FieldAttributes f ) { return f . getAnnotation ( SkipMe . class ) != null ; } } package com . postmark . java ; import com . google . gson . Gson ; import com . google . gson . GsonBuilder ; import org . apache . http . client . HttpClient ; import org . apache . http . client . HttpResponseException ; import org . apache . http . client . ResponseHandler ; import org . apache . http . client . methods . HttpPost ; import org . apache . http . entity . StringEntity ; import org . apache . http . impl . client . BasicResponseHandler ; import org . apache . http . impl . client . DefaultHttpClient ; import org . joda . time . DateTime ; import java . util . List ; import java . util . logging . ConsoleHandler ; import java . util . logging . Level ; import java . util . logging . Logger ; public class PostmarkClient { private static Logger logger = Logger . getLogger ( "" ) ; private String serverToken ; private static GsonBuilder gsonBuilder = new GsonBuilder ( ) ; static { gsonBuilder . registerTypeAdapter ( DateTime . class , new DateTimeTypeAdapter ( ) ) ; gsonBuilder . setPrettyPrinting ( ) ; gsonBuilder . setExclusionStrategies ( new SkipMeExclusionStrategy ( Boolean . class ) ) ; logger . addHandler ( new ConsoleHandler ( ) ) ; logger . setLevel ( Level . ALL ) ; } public PostmarkClient ( String serverToken ) { this . serverToken = serverToken ; } public PostmarkResponse sendMessage ( String from , String to , String replyTo , String cc , String subject , String body , boolean isHTML , String tag ) throws PostmarkException { return sendMessage ( from , to , replyTo , cc , subject , body , isHTML , tag , null ) ; } public PostmarkResponse sendMessage ( String from , String to , String replyTo , String cc , String subject , String body , boolean isHTML , String tag , List < NameValuePair > headers ) throws PostmarkException { PostmarkMessage message = new PostmarkMessage ( from , to , replyTo , subject , cc , body , isHTML , tag , headers ) ; return sendMessage ( message ) ; } public PostmarkResponse sendMessage ( PostmarkMessage message ) throws PostmarkException { HttpClient httpClient = new DefaultHttpClient ( ) ; PostmarkResponse theResponse = new PostmarkResponse ( ) ; try { HttpPost method = new HttpPost ( "" ) ; method . addHeader ( "" , "" ) ; method . addHeader ( "" , "" ) ; method . addHeader ( "" , serverToken ) ; method . addHeader ( "" , "" ) ; message . validate ( ) ; message . clean ( ) ; Gson gson = gsonBuilder . create ( ) ; String messageContents = gson . toJson ( message ) ; logger . info ( "" + messageContents ) ; StringEntity payload = new StringEntity ( messageContents , "" ) ; method . setEntity ( payload ) ; ResponseHandler < String > responseHandler = new BasicResponseHandler ( ) ; try { String response = httpClient . execute ( method , responseHandler ) ; logger . info ( "" + response ) ; theResponse = gsonBuilder . create ( ) . fromJson ( response , PostmarkResponse . class ) ; theResponse . status = PostmarkStatus . SUCCESS ; } catch ( HttpResponseException hre ) { switch ( hre . getStatusCode ( ) ) { case : case : logger . log ( Level . SEVERE , "" + hre . getMessage ( ) ) ; theResponse . setMessage ( hre . getMessage ( ) ) ; theResponse . status = PostmarkStatus . USERERROR ; throw new PostmarkException ( hre . getMessage ( ) , theResponse ) ; case : logger . log ( Level . SEVERE , "" + hre . getMessage ( ) ) ; theResponse . setMessage ( hre . getMessage ( ) ) ; theResponse . status = PostmarkStatus . SERVERERROR ; throw new PostmarkException ( hre . getMessage ( ) , theResponse ) ; default : logger . log ( Level . SEVERE , "" + hre . getMessage ( ) ) ; theResponse . status = PostmarkStatus . UNKNOWN ; theResponse . setMessage ( hre . getMessage ( ) ) ; throw new PostmarkException ( hre . getMessage ( ) , theResponse ) ; } } } catch ( Exception e ) { logger . log ( Level . SEVERE , "" + e . getMessage ( ) ) ; throw new PostmarkException ( e ) ; } finally { httpClient . getConnectionManager ( ) . shutdown ( ) ; } return theResponse ; } } package com . postmark . java ; public class PostmarkException extends Exception { private static final long serialVersionUID = ; private PostmarkResponse response ; public PostmarkException ( Throwable cause ) { super ( cause ) ; } public PostmarkException ( String message ) { super ( message ) ; } public PostmarkException ( String message , PostmarkResponse response ) { super ( message ) ; this . response = response ; } public PostmarkResponse getResponse ( ) { return response ; } } package org . apache . camel . example . reportincident . model ; import org . apache . camel . dataformat . bindy . annotation . CsvRecord ; import org . apache . camel . dataformat . bindy . annotation . DataField ; import javax . persistence . * ; import java . io . Serializable ; import java . util . Date ; @ CsvRecord ( separator = "" ) @ Entity public class Incident extends org . apache . camel . example . reportincident . model . Abstract implements Serializable { private static final long serialVersionUID = ; @ Column ( name = "" ) @ DataField ( pos = ) private String incidentRef ; @ Column ( name = "" ) @ DataField ( pos = , pattern = "" ) private Date incidentDate ; @ Column ( name = "" ) @ DataField ( pos = ) private String givenName ; @ Column ( name = "" ) @ DataField ( pos = ) private String familyName ; @ Column ( name = "" ) @ DataField ( pos = ) private String summary ; @ Column ( name = "" ) @ DataField ( pos = ) private String details ; @ Column ( name = "" ) @ DataField ( pos = ) private String email ; @ Column ( name = "" ) @ DataField ( pos = ) private String phone ; @ Id @ GeneratedValue ( strategy = GenerationType . AUTO ) private long incidentId ; @ Column ( name = "" ) private String creationUser ; @ Column ( name = "" ) private Date creationDate ; public long getIncidentId ( ) { return incidentId ; } public void setIncidentId ( long incidentId ) { this . incidentId = incidentId ; } public String getIncidentRef ( ) { return incidentRef ; } public void setIncidentRef ( String incidentRef ) { this . incidentRef = incidentRef ; } public Date getIncidentDate ( ) { return incidentDate ; } public void setIncidentDate ( Date incidentDate ) { this . incidentDate = incidentDate ; } public String getGivenName ( ) { return givenName ; } public void setGivenName ( String givenName ) { this . givenName = givenName ; } public String getFamilyName ( ) { return familyName ; } public void setFamilyName ( String familyName ) { this . familyName = familyName ; } public String getSummary ( ) { return summary ; } public void setSummary ( String summary ) { this . summary = summary ; } public String getDetails ( ) { return details ; } public void setDetails ( String details ) { this . details = details ; } public String getEmail ( ) { return email ; } public void setEmail ( String email ) { this . email = email ; } public String getPhone ( ) { return phone ; } public void setPhone ( String phone ) { this . phone = phone ; } public String getCreationUser ( ) { return creationUser ; } public void setCreationUser ( String creationUser ) { this . creationUser = creationUser ; } public Date getCreationDate ( ) { return creationDate ; } public void setCreationDate ( Date creationDate ) { this . creationDate = creationDate ; } } package org . apache . camel . example . reportincident . model ; import org . apache . commons . lang . builder . ToStringBuilder ; import org . apache . commons . lang . builder . ToStringStyle ; public abstract class Abstract { @ Override public String toString ( ) { return ToStringBuilder . reflectionToString ( this , ToStringStyle . MULTI_LINE_STYLE ) ; } } package org . apache . camel . example . reportincident . dao . impl ; import org . apache . camel . example . reportincident . dao . IncidentDAO ; import org . apache . camel . example . reportincident . model . Incident ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import javax . persistence . EntityManager ; import javax . persistence . Query ; import java . util . List ; public class IncidentDAOImpl implements IncidentDAO { private static final transient Log LOG = LogFactory . getLog ( IncidentDAOImpl . class ) ; private EntityManager em ; private static final String findIncidentByReference = "" ; private static final String findIncident = "" ; public void setEntityManager ( EntityManager e ) { em = e ; } public List < Incident > findIncident ( ) { Query q = this . em . createQuery ( "" ) ; List list = q . getResultList ( ) ; return list ; } public List < Incident > findIncident ( String key ) { Query q = this . em . createQuery ( "" ) ; q . setParameter ( "" , key ) ; List list = q . getResultList ( ) ; return list ; } public Incident getIncident ( long id ) { return ( Incident ) this . em . find ( Incident . class , Long . valueOf ( id ) ) ; } public void removeIncident ( long id ) { Object record = this . em . find ( Incident . class , Long . valueOf ( id ) ) ; this . em . remove ( record ) ; this . em . flush ( ) ; } public void saveIncident ( Incident incident ) { this . em . persist ( incident ) ; this . em . flush ( ) ; } } package org . apache . camel . example . reportincident . dao ; import org . apache . camel . example . reportincident . model . Incident ; import java . util . List ; public interface IncidentDAO { public abstract Incident getIncident ( long paramLong ) ; public abstract List < Incident > findIncident ( ) ; public abstract List < Incident > findIncident ( String paramString ) ; public abstract void saveIncident ( Incident paramIncident ) ; public abstract void removeIncident ( long paramLong ) ; } package org . apache . camel . example . reportincident ; import org . apache . camel . builder . RouteBuilder ; public class ReportIncidentRoutes extends RouteBuilder { public void configure ( ) throws Exception { OutputReportIncident OK = new OutputReportIncident ( ) ; OK . setCode ( "" ) ; String cxfEndpoint = "" + "" + "" ; from ( cxfEndpoint ) . convertBodyTo ( InputReportIncident . class ) . transform ( constant ( OK ) ) ; } } package org . apache . camel . example . reportincident ; import org . apache . camel . CamelContext ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . cxf . jaxws . JaxWsProxyFactoryBean ; import org . junit . Test ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . test . context . ContextConfiguration ; import org . springframework . test . context . junit4 . AbstractJUnit4SpringContextTests ; import static org . junit . Assert . assertNotNull ; import static org . junit . Assert . assertEquals ; @ ContextConfiguration public class ReportIncidentRoutesTest extends AbstractJUnit4SpringContextTests { private static final transient Log LOG = LogFactory . getLog ( ReportIncidentRoutesTest . class ) ; @ Autowired protected CamelContext camelContext ; private final static String ADDRESS = "" ; protected static ReportIncidentEndpoint createCXFClient ( ) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean ( ) ; factory . setServiceClass ( ReportIncidentEndpoint . class ) ; factory . setAddress ( ADDRESS ) ; return ( ReportIncidentEndpoint ) factory . create ( ) ; } @ Test public void testRendportIncident ( ) throws Exception { assertNotNull ( camelContext ) ; InputReportIncident input = new InputReportIncident ( ) ; input . setIncidentId ( "" ) ; input . setIncidentDate ( "" ) ; input . setGivenName ( "" ) ; input . setFamilyName ( "" ) ; input . setSummary ( "" ) ; input . setDetails ( "" ) ; input . setEmail ( "" ) ; input . setPhone ( "" ) ; ReportIncidentEndpoint client = createCXFClient ( ) ; OutputReportIncident out = client . reportIncident ( input ) ; assertEquals ( "" , out . getCode ( ) ) ; } } package org . apache . camel . example . reportincident ; import junit . framework . TestCase ; import org . apache . camel . CamelContext ; import org . apache . camel . impl . DefaultCamelContext ; import org . apache . cxf . jaxws . JaxWsProxyFactoryBean ; public class ReportIncidentNoSpringRoutesTest extends TestCase { private CamelContext camel ; private static String ADDRESS = "" ; protected void startCamel ( ) throws Exception { camel = new DefaultCamelContext ( ) ; camel . addRoutes ( new ReportIncidentRoutes ( ) ) ; camel . start ( ) ; } protected static ReportIncidentEndpoint createCXFClient ( ) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean ( ) ; factory . setServiceClass ( ReportIncidentEndpoint . class ) ; factory . setAddress ( ADDRESS ) ; return ( ReportIncidentEndpoint ) factory . create ( ) ; } public void testRendportIncident ( ) throws Exception { startCamel ( ) ; InputReportIncident input = new InputReportIncident ( ) ; input . setIncidentId ( "" ) ; input . setIncidentDate ( "" ) ; input . setGivenName ( "" ) ; input . setFamilyName ( "" ) ; input . setSummary ( "" ) ; input . setDetails ( "" ) ; input . setEmail ( "" ) ; input . setPhone ( "" ) ; ReportIncidentEndpoint client = createCXFClient ( ) ; OutputReportIncident out = client . reportIncident ( input ) ; assertEquals ( "" , out . getCode ( ) ) ; camel . stop ( ) ; } } package org . apache . camel . example . reportincident . internal ; import org . apache . camel . Exchange ; import org . apache . camel . example . reportincident . model . Incident ; import org . apache . camel . example . reportincident . service . IncidentService ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import java . text . DateFormat ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . * ; public class IncidentSaver { private static final transient Log LOG = LogFactory . getLog ( IncidentSaver . class ) ; private IncidentService incidentService = null ; public void process ( Exchange exchange ) throws ParseException { int count = ; List < Map < String , Object > > models = new ArrayList < Map < String , Object > > ( ) ; Map < String , Object > model = new HashMap < String , Object > ( ) ; models = ( List < Map < String , Object > > ) exchange . getIn ( ) . getBody ( ) ; String origin = ( String ) exchange . getIn ( ) . getHeader ( "" ) ; LOG . debug ( "" + origin ) ; Iterator < Map < String , Object > > it = models . iterator ( ) ; DateFormat format = new SimpleDateFormat ( "" ) ; String currentDate = format . format ( new Date ( ) ) ; Date creationDate = format . parse ( currentDate ) ; while ( it . hasNext ( ) ) { model = it . next ( ) ; LOG . debug ( "" ) ; for ( String key : model . keySet ( ) ) { LOG . debug ( "" + model . get ( key ) . toString ( ) ) ; Incident incident = ( Incident ) model . get ( key ) ; incident . setCreationDate ( creationDate ) ; incident . setCreationUser ( origin ) ; LOG . debug ( "" + count + "" + incident . toString ( ) ) ; incidentService . saveIncident ( incident ) ; LOG . debug ( "" ) ; } count ++ ; } LOG . debug ( "" + count ) ; } public void setIncidentService ( IncidentService incidentService ) { this . incidentService = incidentService ; } } package org . apache . camel . example . reportincident . internal ; import org . apache . camel . Exchange ; import org . apache . camel . example . reportincident . InputReportIncident ; import org . apache . camel . example . reportincident . model . Incident ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import java . text . DateFormat ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . * ; public class WebService { private static final transient Log LOG = LogFactory . getLog ( WebService . class ) ; public void process ( Exchange exchange ) throws ParseException { InputReportIncident webincident = ( InputReportIncident ) exchange . getIn ( ) . getBody ( ) ; LOG . debug ( "" + webincident . getFamilyName ( ) + "" + webincident . getGivenName ( ) ) ; LOG . debug ( "" + webincident . getIncidentId ( ) + "" + webincident . getIncidentDate ( ) ) ; LOG . debug ( "" + webincident . getDetails ( ) + "" + webincident . getSummary ( ) ) ; List < Map < String , Incident > > models = new ArrayList < Map < String , Incident > > ( ) ; Map < String , Incident > model = new HashMap < String , Incident > ( ) ; Incident incident = new Incident ( ) ; DateFormat format = new SimpleDateFormat ( "" ) ; incident . setIncidentDate ( format . parse ( webincident . getIncidentDate ( ) ) ) ; incident . setDetails ( webincident . getDetails ( ) ) ; incident . setEmail ( webincident . getEmail ( ) ) ; incident . setFamilyName ( webincident . getFamilyName ( ) ) ; incident . setGivenName ( webincident . getGivenName ( ) ) ; incident . setIncidentRef ( webincident . getIncidentId ( ) ) ; incident . setPhone ( webincident . getPhone ( ) ) ; incident . setSummary ( webincident . getSummary ( ) ) ; String origin = ( String ) exchange . getIn ( ) . getHeader ( "" ) ; format = new SimpleDateFormat ( "" ) ; String currentDate = format . format ( new Date ( ) ) ; Date creationDate = format . parse ( currentDate ) ; incident . setCreationDate ( creationDate ) ; incident . setCreationUser ( origin ) ; LOG . debug ( "" + incident . toString ( ) ) ; model . put ( Incident . class . getName ( ) , incident ) ; models . add ( model ) ; exchange . getOut ( ) . setBody ( models ) ; exchange . getOut ( ) . setHeader ( "" , origin ) ; } } package org . apache . camel . example . reportincident . internal ; import org . apache . camel . example . reportincident . OutputReportIncident ; public class Feedback { public OutputReportIncident setOk ( ) { OutputReportIncident outputReportIncident = new OutputReportIncident ( ) ; outputReportIncident . setCode ( "" ) ; return outputReportIncident ; } } package org . apache . camel . example . reportincident ; import org . apache . wicket . protocol . http . WebApplication ; import org . apache . wicket . spring . injection . annot . SpringComponentInjector ; public class WicketApplication extends WebApplication { public void init ( ) { super . init ( ) ; addComponentInstantiationListener ( new SpringComponentInjector ( this ) ) ; } public WicketApplication ( ) { } public Class < HomePage > getHomePage ( ) { return HomePage . class ; } } package org . apache . camel . example . reportincident ; import org . apache . camel . example . reportincident . model . Incident ; import org . apache . camel . example . reportincident . service . IncidentService ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . wicket . AttributeModifier ; import org . apache . wicket . PageParameters ; import org . apache . wicket . markup . html . WebPage ; import org . apache . wicket . markup . html . basic . Label ; import org . apache . wicket . markup . html . navigation . paging . PagingNavigator ; import org . apache . wicket . markup . repeater . Item ; import org . apache . wicket . markup . repeater . data . DataView ; import org . apache . wicket . markup . repeater . data . IDataProvider ; import org . apache . wicket . model . AbstractReadOnlyModel ; import org . apache . wicket . model . IModel ; import org . apache . wicket . model . LoadableDetachableModel ; import org . apache . wicket . model . Model ; import org . apache . wicket . spring . injection . annot . SpringBean ; import java . util . Iterator ; public class HomePage extends WebPage { private static final long serialVersionUID = ; private static final transient Log LOG = LogFactory . getLog ( HomePage . class ) ; @ SpringBean private IncidentService incidentService ; public HomePage ( final PageParameters parameters ) { LOG . debug ( "" + incidentService . toString ( ) ) ; add ( new Label ( "" , "" ) ) ; final DataView dataView = new DataView ( "" , new IncidentProvider ( ) ) { public void populateItem ( final Item item ) { final Incident incident = ( Incident ) item . getModelObject ( ) ; item . add ( new Label ( "" , String . valueOf ( incident . getIncidentId ( ) ) ) ) ; item . add ( new Label ( "" , String . valueOf ( incident . getIncidentDate ( ) ) ) ) ; item . add ( new Label ( "" , incident . getIncidentRef ( ) ) ) ; item . add ( new Label ( "" , incident . getGivenName ( ) ) ) ; item . add ( new Label ( "" , incident . getFamilyName ( ) ) ) ; item . add ( new Label ( "" , incident . getSummary ( ) ) ) ; item . add ( new Label ( "" , incident . getDetails ( ) ) ) ; item . add ( new Label ( "" , incident . getEmail ( ) ) ) ; item . add ( new Label ( "" , incident . getPhone ( ) ) ) ; item . add ( new Label ( "" , incident . getCreationUser ( ) ) ) ; item . add ( new Label ( "" , String . valueOf ( incident . getCreationDate ( ) ) ) ) ; item . add ( new AttributeModifier ( "" , true , new AbstractReadOnlyModel ( ) { @ Override public Object getObject ( ) { return ( item . getIndex ( ) % == ) ? "" : "" ; } } ) ) ; } } ; dataView . setItemsPerPage ( ) ; add ( dataView ) ; add ( new PagingNavigator ( "" , dataView ) ) ; } private class IncidentProvider implements IDataProvider { public Iterator iterator ( int first , int count ) { return incidentService . findIncident ( ) . iterator ( ) ; } public int size ( ) { return incidentService . findIncident ( ) . size ( ) ; } public IModel model ( Object object ) { return new Model ( ( Incident ) object ) ; } public void detach ( ) { } } private class IncidentDetachModel extends LoadableDetachableModel { private long id ; @ Override protected Object load ( ) { return incidentService . findIncident ( String . valueOf ( id ) ) ; } public IncidentDetachModel ( Incident i ) { this ( i . getIncidentId ( ) ) ; } public IncidentDetachModel ( long id ) { if ( id == ) { throw new IllegalArgumentException ( ) ; } this . id = id ; } } } package org . apache . camel . example . reportincident . service . impl ; import org . apache . camel . example . reportincident . dao . IncidentDAO ; import org . apache . camel . example . reportincident . model . Incident ; import org . apache . camel . example . reportincident . service . IncidentService ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import java . util . List ; public class IncidentServiceImpl implements IncidentService { private static final transient Log LOG = LogFactory . getLog ( IncidentServiceImpl . class ) ; private IncidentDAO incidentDAO ; public void saveIncident ( Incident incident ) { try { getIncidentDAO ( ) . saveIncident ( incident ) ; throw new RuntimeException ( "" ) ; } catch ( RuntimeException e ) { e . printStackTrace ( ) ; } } public void removeIncident ( long id ) { getIncidentDAO ( ) . removeIncident ( id ) ; } public Incident getIncident ( long id ) { return getIncidentDAO ( ) . getIncident ( id ) ; } public List < Incident > findIncident ( ) { return getIncidentDAO ( ) . findIncident ( ) ; } public List < Incident > findIncident ( String key ) { return getIncidentDAO ( ) . findIncident ( key ) ; } public IncidentDAO getIncidentDAO ( ) { return incidentDAO ; } public void setIncidentDAO ( IncidentDAO incidentDAO ) { this . incidentDAO = incidentDAO ; } } package org . apache . camel . example . reportincident . service ; import org . apache . camel . example . reportincident . model . Incident ; import java . util . List ; public interface IncidentService { public Incident getIncident ( long id ) ; public List < Incident > findIncident ( ) ; public List < Incident > findIncident ( String key ) ; public void saveIncident ( Incident incident ) ; public void removeIncident ( long id ) ; } package com . team1160 . scouting . frontend ; import javax . swing . UIManager ; import javax . swing . UnsupportedLookAndFeelException ; public class Main { public static void main ( String [ ] args ) throws Exception { try { UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; } catch ( UnsupportedLookAndFeelException e ) { } catch ( ClassNotFoundException e ) { } catch ( InstantiationException e ) { } catch ( IllegalAccessException e ) { } @ SuppressWarnings ( "" ) ScoutingAppWindow window = new ScoutingAppWindow ( ) ; } } package com . team1160 . scouting . frontend . resourcePackets ; import java . awt . CardLayout ; import java . awt . Container ; public class CardLayoutPacket { protected CardLayout layout ; protected Container parent ; public CardLayoutPacket ( Container parent ) { layout = new CardLayout ( ) ; this . parent = parent ; } public CardLayout getLayout ( ) { return layout ; } public void setLayout ( CardLayout layout ) { this . layout = layout ; } public Container getParent ( ) { return parent ; } public void setParent ( Container parent ) { this . parent = parent ; } } package com . team1160 . scouting . frontend ; import com . team1160 . scouting . frontend . panels . CommentPanel ; import com . team1160 . scouting . frontend . panels . GraphPanel ; import java . awt . HeadlessException ; import javax . swing . JFrame ; import javax . swing . JPanel ; import com . team1160 . scouting . frontend . panels . InitialPanel ; import com . team1160 . scouting . frontend . panels . MatchScoutingPanel ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; import com . team1160 . scouting . h2 . CommentTable ; import com . team1160 . scouting . h2 . DictTable ; import com . team1160 . scouting . h2 . MatchScoutingTable ; import com . team1160 . scouting . h2 . WeightingTable ; import java . io . File ; public class ScoutingAppWindow extends JFrame { private static final long serialVersionUID = ; private InitialPanel splash ; private MatchScoutingPanel match ; private CardLayoutPacket layout ; private JPanel cards ; private GraphPanel graph ; private CommentPanel comment ; private MatchScoutingTable scoutingTable ; private WeightingTable weightingTable ; private DictTable dictTable ; private CommentTable commentTable ; public ScoutingAppWindow ( String title ) throws Exception { super ( title ) ; this . scoutingTable = new MatchScoutingTable ( "" + File . separator + "" + File . separator + "" ) ; this . weightingTable = new WeightingTable ( "" + File . separator + "" + File . separator + "" ) ; this . dictTable = new DictTable ( "" + File . separator + "" + File . separator + "" ) ; this . commentTable = new CommentTable ( "" + File . separator + "" + File . separator + "" ) ; this . cards = new JPanel ( ) ; layout = new CardLayoutPacket ( cards ) ; cards . setLayout ( this . layout . getLayout ( ) ) ; splash = new InitialPanel ( layout ) ; splash . setOpaque ( true ) ; match = new MatchScoutingPanel ( layout , this . scoutingTable , this . weightingTable , this . dictTable , this . commentTable ) ; graph = new GraphPanel ( layout , this . scoutingTable , this . weightingTable , this . dictTable ) ; comment = new CommentPanel ( layout , this . commentTable ) ; cards . add ( splash , "" ) ; cards . add ( match , "" ) ; cards . add ( graph , "" ) ; cards . add ( comment , "" ) ; this . add ( cards ) ; this . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; this . setSize ( , ) ; this . setVisible ( true ) ; } public ScoutingAppWindow ( ) throws Exception { this ( "" ) ; } } package com . team1160 . scouting . frontend . panels ; import com . team1160 . scouting . frontend . elements . JumpMenuItem ; import com . team1160 . scouting . frontend . elements . MultiLineTableCellRenderer ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; import com . team1160 . scouting . h2 . CommentTable ; import java . awt . BorderLayout ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . awt . event . KeyEvent ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import java . util . logging . Level ; import java . util . logging . Logger ; import javax . swing . JButton ; import javax . swing . JMenu ; import javax . swing . JMenuBar ; import javax . swing . JOptionPane ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JTable ; import javax . swing . JToolBar ; import javax . swing . table . AbstractTableModel ; public class CommentPanel extends JPanel { private static final long serialVersionUID = ; JMenuBar menubar ; JToolBar toolbar ; JMenu go ; private final JButton refresh ; private final JButton deleteData ; CommentTable commentTable ; JTable table ; JScrollPane scroll ; CardLayoutPacket layout ; public CommentPanel ( CardLayoutPacket layout , CommentTable commentTable ) throws SQLException { this . commentTable = commentTable ; this . layout = layout ; this . menubar = new JMenuBar ( ) ; this . go = new JMenu ( "" ) ; this . go . setMnemonic ( KeyEvent . VK_G ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; this . toolbar = new JToolBar ( ) ; this . toolbar . setFloatable ( false ) ; this . deleteData = new JButton ( "" ) ; this . deleteData . setMnemonic ( KeyEvent . VK_D ) ; this . deleteData . addActionListener ( this . new DeleteData ( ) ) ; this . deleteData . setSize ( , this . menubar . getHeight ( ) ) ; this . toolbar . add ( this . deleteData ) ; this . refresh = new JButton ( "" ) ; this . refresh . setMnemonic ( KeyEvent . VK_R ) ; this . refresh . addActionListener ( this . new Refresh ( ) ) ; this . refresh . setSize ( , this . menubar . getHeight ( ) ) ; this . toolbar . add ( this . refresh ) ; this . table = new JTable ( new CommentTableModel ( this . getData ( ) ) ) ; table . getColumnModel ( ) . getColumn ( ) . setCellRenderer ( new MultiLineTableCellRenderer ( ) ) ; this . scroll = new JScrollPane ( this . table ) ; this . setLayout ( new BorderLayout ( ) ) ; JPanel top = new JPanel ( new BorderLayout ( ) ) ; top . add ( this . menubar ) ; this . menubar . add ( this . go , BorderLayout . NORTH ) ; top . add ( this . toolbar , BorderLayout . SOUTH ) ; this . add ( top , BorderLayout . NORTH ) ; this . add ( this . scroll , BorderLayout . CENTER ) ; } public void refresh ( ) throws SQLException { this . remove ( this . scroll ) ; this . table = null ; this . scroll = null ; this . table = new JTable ( new CommentTableModel ( this . getData ( ) ) ) ; table . getColumnModel ( ) . getColumn ( ) . setCellRenderer ( new MultiLineTableCellRenderer ( ) ) ; this . scroll = new JScrollPane ( this . table ) ; this . add ( this . scroll , BorderLayout . CENTER ) ; this . validate ( ) ; } protected ArrayList < ArrayList < String > > getData ( ) throws SQLException { List < Integer > teams = this . commentTable . getTeams ( ) ; ArrayList < ArrayList < String > > data = new ArrayList < ArrayList < String > > ( ) ; for ( Integer t : teams ) { Map < Integer , String > comments = this . commentTable . getComments ( t ) ; for ( Integer m : comments . keySet ( ) ) { ArrayList < String > row = new ArrayList < String > ( ) ; row . add ( t . toString ( ) ) ; row . add ( m . toString ( ) ) ; row . add ( comments . get ( m ) ) ; data . add ( row ) ; } } return data ; } class Refresh implements ActionListener { public void actionPerformed ( ActionEvent e ) { try { CommentPanel . this . refresh ( ) ; } catch ( SQLException ex ) { Logger . getLogger ( GraphPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } class DeleteData implements ActionListener { public void actionPerformed ( ActionEvent e ) { Object [ ] options = { "" , "" } ; boolean contin = JOptionPane . showOptionDialog ( CommentPanel . this , "" , "" , JOptionPane . YES_NO_OPTION , JOptionPane . ERROR_MESSAGE , null , options , options [ ] ) == ; if ( contin ) { try { CommentPanel . this . commentTable . reset ( ) ; } catch ( SQLException ex ) { Logger . getLogger ( GraphPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } } class CommentTableModel extends AbstractTableModel { private static final long serialVersionUID = - ; String columnNames [ ] = { "" , "" , "" } ; ArrayList < ArrayList < String > > data ; public CommentTableModel ( ArrayList < ArrayList < String > > data ) { this . data = data ; } public int getRowCount ( ) { return this . data . size ( ) ; } public int getColumnCount ( ) { return this . columnNames . length ; } public Object getValueAt ( int rowIndex , int columnIndex ) { return this . data . get ( rowIndex ) . get ( columnIndex ) ; } @ Override public boolean isCellEditable ( int row , int col ) { return false ; } @ Override public String getColumnName ( int col ) { return this . columnNames [ col ] ; } } } package com . team1160 . scouting . frontend . panels ; import com . team1160 . scouting . frontend . elements . JumpMenuItem ; import java . awt . BorderLayout ; import java . awt . Dimension ; import javax . swing . ImageIcon ; import javax . swing . JLabel ; import javax . swing . JPanel ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; import java . awt . event . KeyEvent ; import javax . swing . JMenu ; import javax . swing . JMenuBar ; public class InitialPanel extends JPanel { private static final long serialVersionUID = ; JMenuBar toolbar ; JPanel picturepanel ; CardLayoutPacket layout ; JMenu go ; public InitialPanel ( CardLayoutPacket layout ) { this . layout = layout ; this . setLayout ( new BorderLayout ( ) ) ; toolbar = new JMenuBar ( ) ; toolbar . setLayout ( new BorderLayout ( ) ) ; this . go = new JMenu ( "" ) ; this . go . setMnemonic ( KeyEvent . VK_G ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; toolbar . add ( this . go , BorderLayout . WEST ) ; this . add ( toolbar , BorderLayout . NORTH ) ; picturepanel = new JPanel ( ) ; ImageIcon image = new ImageIcon ( "" ) ; picturepanel . add ( new JLabel ( image ) ) ; picturepanel . setOpaque ( true ) ; this . add ( picturepanel , BorderLayout . CENTER ) ; this . setPreferredSize ( new Dimension ( , ) ) ; } } package com . team1160 . scouting . frontend . panels ; import com . team1160 . scouting . frontend . elements . JumpMenuItem ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; import com . team1160 . scouting . h2 . DictTable ; import com . team1160 . scouting . h2 . MatchScoutingTable ; import com . team1160 . scouting . h2 . WeightingTable ; import java . awt . BorderLayout ; import java . awt . Dimension ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . awt . event . KeyEvent ; import java . sql . SQLException ; import java . util . Comparator ; import java . util . HashMap ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import java . util . logging . Level ; import java . util . logging . Logger ; import javax . swing . JButton ; import javax . swing . JMenu ; import javax . swing . JMenuBar ; import javax . swing . JOptionPane ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JToolBar ; import org . jfree . chart . ChartFactory ; import org . jfree . chart . ChartPanel ; import org . jfree . chart . JFreeChart ; import org . jfree . chart . plot . PlotOrientation ; import org . jfree . chart . renderer . category . GroupedStackedBarRenderer ; import org . jfree . data . category . CategoryDataset ; import org . jfree . data . category . DefaultCategoryDataset ; public class GraphPanel extends JPanel { private static final long serialVersionUID = ; CardLayoutPacket layout ; JMenuBar menubar ; JToolBar toolbar ; JMenu go ; private final JButton refresh ; private final JButton deleteData ; MatchScoutingTable matchTable ; WeightingTable weightingTable ; DictTable dictTable ; JFreeChart chart ; ChartPanel chartPanel ; JScrollPane scroll ; @ SuppressWarnings ( "" ) private final GroupedStackedBarRenderer renderer ; final int preferredHeight = ; Dimension preferredSize ; public GraphPanel ( CardLayoutPacket layout , MatchScoutingTable match , WeightingTable weight , DictTable dict ) throws SQLException { this . matchTable = match ; this . weightingTable = weight ; this . dictTable = dict ; this . menubar = new JMenuBar ( ) ; this . go = new JMenu ( "" ) ; this . go . setMnemonic ( KeyEvent . VK_G ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; this . toolbar = new JToolBar ( ) ; this . toolbar . setFloatable ( false ) ; this . deleteData = new JButton ( "" ) ; this . deleteData . setMnemonic ( KeyEvent . VK_D ) ; this . deleteData . addActionListener ( this . new DeleteData ( ) ) ; this . deleteData . setSize ( , this . menubar . getHeight ( ) ) ; this . toolbar . add ( this . deleteData ) ; this . refresh = new JButton ( "" ) ; this . refresh . setMnemonic ( KeyEvent . VK_R ) ; this . refresh . addActionListener ( this . new Refresh ( ) ) ; this . refresh . setSize ( , this . menubar . getHeight ( ) ) ; this . toolbar . add ( this . refresh ) ; JPanel top = new JPanel ( ) ; top . setLayout ( new BorderLayout ( ) ) ; top . add ( this . menubar ) ; this . menubar . add ( this . go , BorderLayout . NORTH ) ; top . add ( this . toolbar , BorderLayout . SOUTH ) ; this . chart = ChartFactory . createStackedBarChart ( "" , "" , "" , this . createDataSet ( ) , PlotOrientation . VERTICAL , true , true , false ) ; this . renderer = new GroupedStackedBarRenderer ( ) ; this . chartPanel = new ChartPanel ( this . chart , this . preferredSize . width , this . preferredSize . height , , , , , true , true , true , false , false , true ) ; this . scroll = new JScrollPane ( this . chartPanel ) ; this . setLayout ( new BorderLayout ( ) ) ; this . add ( top , BorderLayout . NORTH ) ; this . add ( this . scroll , BorderLayout . CENTER ) ; } protected CategoryDataset createDataSet ( ) throws SQLException { DefaultCategoryDataset data = new DefaultCategoryDataset ( ) ; Map < String , Integer > dict ; Map < Integer , String > reverseDict ; List < Integer > teams ; Map < Integer , Integer > weights ; teams = this . matchTable . getTeams ( ) ; dict = this . dictTable . getValuesName ( ) ; reverseDict = this . dictTable . getValuesID ( ) ; weights = this . weightingTable . getValues ( ) ; if ( weights . keySet ( ) . isEmpty ( ) ) { weights = new LinkedHashMap < Integer , Integer > ( ) ; for ( Integer i : reverseDict . keySet ( ) ) { weights . put ( i , ) ; } } Map < Integer , Double > teamToOverallScore = new HashMap < Integer , Double > ( ) ; Map < Integer , LinkedHashMap < String , Double > > teamToValues = new HashMap < Integer , LinkedHashMap < String , Double > > ( ) ; ValueComparator vc = new ValueComparator ( teamToOverallScore ) ; @ SuppressWarnings ( "" ) TreeMap < Integer , Double > teamSorted = new TreeMap < Integer , Double > ( vc ) ; for ( Integer t : teams ) { LinkedHashMap < String , Double > values = new LinkedHashMap < String , Double > ( ) ; for ( String n : dict . keySet ( ) ) { int value = this . matchTable . getAverageValue ( t , dict . get ( n ) ) ; double weight = ( weights . get ( dict . get ( n ) ) ) ; weight /= ; double weightedValue = value * weight ; values . put ( n , weightedValue ) ; } double overallScore = ; for ( String s : values . keySet ( ) ) { overallScore += values . get ( s ) ; } teamToOverallScore . put ( t , overallScore ) ; teamToValues . put ( t , values ) ; } teamSorted . putAll ( teamToOverallScore ) ; for ( Integer t : teamSorted . keySet ( ) ) { for ( String s : teamToValues . get ( t ) . keySet ( ) ) { data . addValue ( teamToValues . get ( t ) . get ( s ) , s . substring ( , s . length ( ) - ) , t . toString ( ) ) ; } } this . preferredSize = new Dimension ( this . getPreferredWidth ( teams . size ( ) ) , this . preferredHeight ) ; return data ; } public void refresh ( ) throws SQLException { this . remove ( this . scroll ) ; this . chart = null ; this . chartPanel = null ; this . scroll = null ; this . chart = ChartFactory . createStackedBarChart ( "" , "" , "" , this . createDataSet ( ) , PlotOrientation . VERTICAL , true , true , false ) ; this . chartPanel = new ChartPanel ( this . chart , this . preferredSize . width , this . preferredSize . height , , , , , true , true , true , false , false , true ) ; this . scroll = new JScrollPane ( this . chartPanel ) ; this . add ( this . scroll , BorderLayout . CENTER ) ; this . validate ( ) ; this . scroll . validate ( ) ; } @ SuppressWarnings ( "" ) class ValueComparator implements Comparator { Map < Integer , Double > base ; public ValueComparator ( Map < Integer , Double > base ) { this . base = base ; } public int compare ( Object a , Object b ) { if ( base . get ( a ) < base . get ( b ) ) { return ; } else if ( base . get ( a ) == base . get ( b ) ) { return ; } else { return - ; } } } private int getPreferredWidth ( int n ) { if ( ( n <= ) && ( n > ) ) { return ; } else { return + * n + ; } } class Refresh implements ActionListener { public void actionPerformed ( ActionEvent e ) { try { GraphPanel . this . refresh ( ) ; } catch ( SQLException ex ) { Logger . getLogger ( GraphPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } class DeleteData implements ActionListener { public void actionPerformed ( ActionEvent e ) { Object [ ] options = { "" , "" } ; boolean contin = JOptionPane . showOptionDialog ( GraphPanel . this , "" , "" , JOptionPane . YES_NO_OPTION , JOptionPane . ERROR_MESSAGE , null , options , options [ ] ) == ; if ( contin ) { try { GraphPanel . this . matchTable . reset ( ) ; GraphPanel . this . weightingTable . reset ( ) ; } catch ( SQLException ex ) { Logger . getLogger ( GraphPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } } } package com . team1160 . scouting . frontend . panels ; import com . team1160 . scouting . frontend . elements . JumpMenuItem ; import com . team1160 . scouting . frontend . elements . MultiLineInputElement ; import com . team1160 . scouting . frontend . elements . NumberDropDownElement ; import com . team1160 . scouting . frontend . elements . ScoutingElement ; import com . team1160 . scouting . frontend . elements . SingleLineInputElement ; import com . team1160 . scouting . frontend . elements . WeightingSliderElement ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; import com . team1160 . scouting . h2 . CommentTable ; import com . team1160 . scouting . h2 . DictTable ; import com . team1160 . scouting . h2 . MatchScoutingTable ; import com . team1160 . scouting . h2 . WeightingTable ; import com . team1160 . scouting . xml . XMLParser ; import java . awt . BorderLayout ; import java . awt . Component ; import java . awt . GridLayout ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . awt . event . KeyEvent ; import java . io . IOException ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . logging . Level ; import java . util . logging . Logger ; import javax . swing . BorderFactory ; import javax . swing . JButton ; import javax . swing . JMenu ; import javax . swing . JMenuBar ; import javax . swing . JOptionPane ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . border . Border ; import javax . xml . parsers . ParserConfigurationException ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; import org . xml . sax . SAXException ; public class MatchScoutingPanel extends JPanel { private static final long serialVersionUID = - ; protected JPanel bottomPanel ; protected ArrayList < ScoutingElement > elements ; protected JPanel elementPanel ; protected JPanel elementInputPanel ; protected JPanel elementButtonPanel ; protected Border elementBorder ; protected ArrayList < WeightingSliderElement > weightingElements ; protected JPanel weightingPanel ; protected JPanel weightingInputPanel ; protected JPanel weightingButtonPanel ; protected Border weightingBorder ; protected JMenuBar menubar ; protected JMenu go ; protected CardLayoutPacket layout ; protected MatchScoutingTable scoutingTable ; protected WeightingTable weightingTable ; protected DictTable dictTable ; protected CommentTable commentTable ; public MatchScoutingPanel ( CardLayoutPacket layout , MatchScoutingTable scouting , WeightingTable weighting , DictTable dict , CommentTable comment ) throws ParserConfigurationException , SAXException , IOException , Exception { this . layout = layout ; this . elements = new ArrayList < ScoutingElement > ( ) ; this . weightingElements = new ArrayList < WeightingSliderElement > ( ) ; this . setLayout ( new BorderLayout ( ) ) ; XML xml = this . new XML ( ) ; this . scoutingTable = scouting ; this . weightingTable = weighting ; this . dictTable = dict ; this . commentTable = comment ; this . menubar = new JMenuBar ( ) ; this . menubar . setLayout ( new BorderLayout ( ) ) ; this . go = new JMenu ( "" ) ; this . go . setMnemonic ( KeyEvent . VK_G ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; this . go . add ( new JumpMenuItem ( layout , "" , "" ) ) ; this . menubar . add ( this . go , BorderLayout . WEST ) ; this . bottomPanel = new JPanel ( ) ; this . bottomPanel . setLayout ( new GridLayout ( , , , ) ) ; xml . parse ( ) ; this . elementPanel = new JPanel ( ) ; this . elementInputPanel = new JPanel ( ) ; this . elementBorder = BorderFactory . createTitledBorder ( "" ) ; this . elementInputPanel . setLayout ( new GridLayout ( this . elements . size ( ) , , , ) ) ; this . elementPanel . setBorder ( this . elementBorder ) ; this . elementPanel . setLayout ( new BorderLayout ( ) ) ; this . weightingPanel = new JPanel ( ) ; this . weightingInputPanel = new JPanel ( ) ; this . weightingBorder = BorderFactory . createTitledBorder ( "" ) ; this . weightingPanel . setBorder ( this . weightingBorder ) ; this . weightingInputPanel . setLayout ( new GridLayout ( this . weightingElements . size ( ) , , , ) ) ; this . weightingPanel . setLayout ( new BorderLayout ( ) ) ; for ( ScoutingElement se : this . elements ) { this . elementInputPanel . add ( se ) ; } for ( WeightingSliderElement w : this . weightingElements ) { this . weightingInputPanel . add ( w ) ; } JButton elementSubmit = new JButton ( "" ) , elementClear = new JButton ( "" ) ; elementSubmit . addActionListener ( this . new ElementSubmit ( ) ) ; elementClear . addActionListener ( this . new ElementClear ( ) ) ; JButton weightingSubmit = new JButton ( "" ) , weightingClear = new JButton ( "" ) ; weightingSubmit . addActionListener ( this . new WeightingSubmit ( ) ) ; weightingClear . addActionListener ( this . new WeightingClear ( ) ) ; this . elementButtonPanel = new JPanel ( ) ; this . weightingButtonPanel = new JPanel ( ) ; this . elementButtonPanel . add ( elementSubmit ) ; this . elementButtonPanel . add ( elementClear ) ; this . weightingButtonPanel . add ( weightingSubmit ) ; this . weightingButtonPanel . add ( weightingClear ) ; this . elementPanel . add ( new JScrollPane ( this . elementInputPanel ) , BorderLayout . CENTER ) ; this . elementPanel . add ( this . elementButtonPanel , BorderLayout . SOUTH ) ; this . weightingPanel . add ( new JScrollPane ( this . weightingInputPanel ) , BorderLayout . CENTER ) ; this . weightingPanel . add ( this . weightingButtonPanel , BorderLayout . SOUTH ) ; this . bottomPanel . add ( this . elementPanel ) ; this . bottomPanel . add ( this . weightingPanel ) ; this . add ( this . menubar , BorderLayout . NORTH ) ; this . add ( this . bottomPanel , BorderLayout . CENTER ) ; } class XML { XMLParser xml ; protected XML ( ) throws ParserConfigurationException , SAXException , IOException { xml = new XMLParser ( "" ) ; } protected void parse ( ) throws Exception { Element e = xml . getMatch ( ) ; elements . add ( new SingleLineInputElement ( "" , SingleLineInputElement . INTEGER ) ) ; SingleLineInputElement match = new SingleLineInputElement ( "" , SingleLineInputElement . INTEGER ) ; match . setInComments ( true ) ; elements . add ( match ) ; NodeList element = e . getElementsByTagName ( "" ) ; MatchScoutingPanel . this . dictTable . reset ( ) ; for ( int i = ; i < element . getLength ( ) ; i ++ ) { Element el = ( Element ) element . item ( i ) ; String type = el . getAttribute ( "" ) ; String name = el . getAttribute ( "" ) ; @ SuppressWarnings ( "" ) String inWeight = el . getAttribute ( "" ) ; if ( type . equalsIgnoreCase ( "" ) ) { SingleLineInputElement se ; if ( ( el . hasAttribute ( "" ) ) && el . getAttribute ( "" ) . equals ( "" ) ) { se = new SingleLineInputElement ( name , SingleLineInputElement . INTEGER , true ) ; } else if ( ( ( el . hasAttribute ( "" ) ) ) && el . getAttribute ( "" ) . equals ( "" ) ) { int maxTime = Integer . parseInt ( el . getAttribute ( "" ) ) ; se = new SingleLineInputElement ( name , SingleLineInputElement . INTEGER , false , true , maxTime ) ; } else { se = new SingleLineInputElement ( name , SingleLineInputElement . INTEGER ) ; } if ( ( ! ( el . hasAttribute ( "" ) ) ) || ( el . getAttribute ( "" ) ) . equalsIgnoreCase ( "" ) ) { weightingElements . add ( new WeightingSliderElement ( name , se . hashCode ( ) ) ) ; weightingElements . get ( weightingElements . size ( ) - ) . setValue ( MatchScoutingPanel . this . weightingTable . getValue ( weightingElements . get ( weightingElements . size ( ) - ) . hashCode ( ) ) ) ; MatchScoutingPanel . this . dictTable . insert ( se . hashCode ( ) , se . getText ( ) ) ; } se . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; elements . add ( se ) ; } else if ( type . equalsIgnoreCase ( "" ) ) { NumberDropDownElement ne = new NumberDropDownElement ( name , Integer . parseInt ( el . getAttribute ( "" ) ) , Integer . parseInt ( el . getAttribute ( "" ) ) ) ; if ( ( ! ( el . hasAttribute ( "" ) ) ) || ( el . getAttribute ( "" ) ) . equalsIgnoreCase ( "" ) ) { weightingElements . add ( new WeightingSliderElement ( name , ne . hashCode ( ) ) ) ; weightingElements . get ( weightingElements . size ( ) - ) . setValue ( MatchScoutingPanel . this . weightingTable . getValue ( weightingElements . get ( weightingElements . size ( ) - ) . hashCode ( ) ) ) ; MatchScoutingPanel . this . dictTable . insert ( ne . hashCode ( ) , ne . getText ( ) ) ; } ne . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; elements . add ( ne ) ; } else { throw new Exception ( "" ) ; } } MultiLineInputElement comments = new MultiLineInputElement ( "" ) ; comments . setInComments ( true ) ; elements . add ( comments ) ; } } class ElementSubmit implements ActionListener { public void actionPerformed ( ActionEvent ae ) { ArrayList < String > values = new ArrayList < String > ( ) ; boolean error = false ; for ( ScoutingElement e : MatchScoutingPanel . this . elements ) { if ( e . getClass ( ) == SingleLineInputElement . class ) { SingleLineInputElement slie = ( SingleLineInputElement ) e ; if ( ! slie . isNegative ( ) ) { error = slie . getInput ( ) . startsWith ( "" ) ; } if ( slie . isTime ( ) ) { try { int i = Integer . parseInt ( slie . getInput ( ) ) ; error = ( i > slie . getMaxTime ( ) ) || ( i <= ) ; } catch ( NumberFormatException nfe ) { error = true ; } } } values . add ( e . getInput ( ) ) ; } for ( String s : values ) { if ( ! s . contains ( "" ) ) { try { Integer . parseInt ( s ) ; } catch ( NumberFormatException nfe ) { error = true ; } } } if ( error ) { JOptionPane . showMessageDialog ( MatchScoutingPanel . this , "" , "" , JOptionPane . ERROR_MESSAGE ) ; } else { for ( int i = ; i < ( MatchScoutingPanel . this . elements . size ( ) - ) ; i ++ ) { try { MatchScoutingPanel . this . scoutingTable . insert ( Integer . parseInt ( values . get ( ) ) , MatchScoutingPanel . this . elements . get ( i ) . hashCode ( ) , Integer . parseInt ( values . get ( i ) ) ) ; } catch ( SQLException ex ) { Logger . getLogger ( MatchScoutingPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } try { if ( values . get ( values . size ( ) - ) . matches ( "" ) ) MatchScoutingPanel . this . commentTable . insert ( Integer . parseInt ( values . get ( ) ) , Integer . parseInt ( values . get ( ) ) , values . get ( values . size ( ) - ) ) ; } catch ( SQLException ex ) { Logger . getLogger ( MatchScoutingPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } for ( ScoutingElement s : MatchScoutingPanel . this . elements ) { s . clear ( ) ; } } } } class ElementClear implements ActionListener { public void actionPerformed ( ActionEvent ae ) { for ( ScoutingElement s : MatchScoutingPanel . this . elements ) { s . clear ( ) ; } } } class WeightingSubmit implements ActionListener { public void actionPerformed ( ActionEvent ae ) { try { MatchScoutingPanel . this . weightingTable . reset ( ) ; } catch ( SQLException ex ) { Logger . getLogger ( MatchScoutingPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } for ( WeightingSliderElement e : MatchScoutingPanel . this . weightingElements ) { try { MatchScoutingPanel . this . weightingTable . insert ( e . hashCode ( ) , Integer . parseInt ( e . getInput ( ) ) ) ; } catch ( SQLException ex ) { Logger . getLogger ( MatchScoutingPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } } class WeightingClear implements ActionListener { public void actionPerformed ( ActionEvent ae ) { for ( WeightingSliderElement e : MatchScoutingPanel . this . weightingElements ) { try { e . setValue ( MatchScoutingPanel . this . weightingTable . getValue ( e . hashCode ( ) ) ) ; } catch ( SQLException ex ) { Logger . getLogger ( MatchScoutingPanel . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } } } package com . team1160 . scouting . frontend . elements ; import java . awt . Component ; import javax . swing . JPanel ; public abstract class ScoutingElement extends JPanel { private static final long serialVersionUID = - ; public boolean isWeighted ; public ScoutingElement ( ) { this . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; } public abstract String getInput ( ) ; public abstract String getText ( ) ; public abstract void clear ( ) ; } package com . team1160 . scouting . frontend . elements ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import javax . swing . JButton ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; public class JumpButton extends JButton implements ActionListener { private static final long serialVersionUID = ; CardLayoutPacket layout ; String slideName ; public JumpButton ( CardLayoutPacket layout , String text , String slideName ) { super ( text ) ; this . layout = layout ; this . slideName = slideName ; this . addActionListener ( this ) ; } public void actionPerformed ( ActionEvent e ) { this . layout . getLayout ( ) . show ( this . layout . getParent ( ) , slideName ) ; } } package com . team1160 . scouting . frontend . elements ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import javax . swing . JButton ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; public class NextButton extends JButton implements ActionListener { private static final long serialVersionUID = ; CardLayoutPacket layout ; public NextButton ( CardLayoutPacket layout , String name ) { super ( name ) ; this . layout = layout ; this . addActionListener ( this ) ; } public NextButton ( CardLayoutPacket layout ) { super ( "" ) ; this . layout = layout ; this . addActionListener ( this ) ; } public void actionPerformed ( ActionEvent e ) { this . layout . getLayout ( ) . next ( this . layout . getParent ( ) ) ; } } package com . team1160 . scouting . frontend . elements ; import java . awt . Component ; import java . awt . Dimension ; import javax . swing . JTable ; import javax . swing . JTextArea ; import javax . swing . UIManager ; import javax . swing . border . EmptyBorder ; import javax . swing . table . TableCellRenderer ; public class MultiLineTableCellRenderer extends JTextArea implements TableCellRenderer { private static final long serialVersionUID = ; public MultiLineTableCellRenderer ( ) { setLineWrap ( true ) ; setWrapStyleWord ( true ) ; setOpaque ( true ) ; } public Component getTableCellRendererComponent ( JTable table , Object value , boolean isSelected , boolean hasFocus , int row , int column ) { if ( isSelected ) { setForeground ( table . getSelectionForeground ( ) ) ; setBackground ( table . getSelectionBackground ( ) ) ; } else { setForeground ( table . getForeground ( ) ) ; setBackground ( table . getBackground ( ) ) ; } setFont ( table . getFont ( ) ) ; if ( hasFocus ) { setBorder ( UIManager . getBorder ( "" ) ) ; if ( table . isCellEditable ( row , column ) ) { setForeground ( UIManager . getColor ( "" ) ) ; setBackground ( UIManager . getColor ( "" ) ) ; } } else { setBorder ( new EmptyBorder ( , , , ) ) ; } setText ( ( value == null ) ? "" : value . toString ( ) ) ; int count = ( ( String ) value ) . split ( "" ) . length ; this . setPreferredSize ( new Dimension ( , * count ) ) ; int height_wanted = ( int ) getPreferredSize ( ) . getHeight ( ) ; if ( height_wanted != table . getRowHeight ( row ) ) table . setRowHeight ( row , height_wanted ) ; return this ; } } package com . team1160 . scouting . frontend . elements ; import java . awt . Component ; import javax . swing . JLabel ; import javax . swing . JTextField ; public class SingleLineInputElement extends ScoutingElement { private static final long serialVersionUID = ; private JLabel label ; private JTextField input ; private int type ; private String name ; public static final int INTEGER = , STRING = , DOUBLE = ; protected boolean inComments ; protected boolean isNegative ; protected boolean isTime ; protected int maxTime ; public SingleLineInputElement ( String name , int type , boolean isNegative , boolean isTime , int maxTime ) { super ( ) ; this . isNegative = isNegative ; this . isTime = isTime ; this . maxTime = maxTime ; this . inComments = false ; if ( ! ( name . endsWith ( "" ) ) ) { label = new JLabel ( name + "" ) ; this . name = name + "" ; } else { label = new JLabel ( name ) ; this . name = name ; } this . input = new JTextField ( ) ; this . input . setColumns ( ) ; this . label . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; this . input . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; this . add ( label ) ; this . add ( input ) ; } public SingleLineInputElement ( String name , int type , boolean isNegative ) { this ( name , type , isNegative , false , ) ; } public SingleLineInputElement ( String name , int type ) { this ( name , type , false , false , ) ; } public String getText ( ) { return this . label . getText ( ) . substring ( , this . label . getText ( ) . length ( ) ) ; } public String getInput ( ) { String text = this . input . getText ( ) ; if ( this . isNegative ) { if ( text . startsWith ( "" ) ) { return text ; } else { return "" + text ; } } else if ( this . isTime ) { int value = Math . abs ( Integer . parseInt ( text ) ) ; return Integer . toString ( this . maxTime - value ) ; } else { return text ; } } public int getType ( ) { return type ; } public boolean isNegative ( ) { return this . isNegative ; } public boolean isTime ( ) { return this . isTime ; } public int getMaxTime ( ) { return this . maxTime ; } public void setInComments ( boolean b ) { this . inComments = b ; } public boolean isInComments ( ) { return this . inComments ; } @ Override public boolean equals ( Object obj ) { if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final SingleLineInputElement other = ( SingleLineInputElement ) obj ; if ( ( this . name == null ) ? ( other . name != null ) : ! this . name . equals ( other . name ) ) { return false ; } return true ; } @ Override public int hashCode ( ) { int hash = ; hash = * hash + ( this . name != null ? this . name . hashCode ( ) : ) ; return hash ; } @ Override public void clear ( ) { this . input . setText ( "" ) ; } } package com . team1160 . scouting . frontend . elements ; import java . awt . BorderLayout ; import java . awt . Component ; import javax . swing . JLabel ; import javax . swing . JScrollPane ; import javax . swing . JTextArea ; public class MultiLineInputElement extends ScoutingElement { private static final long serialVersionUID = - ; private JLabel label ; private JScrollPane scrolling ; private JTextArea input ; String name ; protected boolean inComments ; public MultiLineInputElement ( String name ) { super ( ) ; this . inComments = false ; if ( ! ( name . endsWith ( "" ) ) ) { label = new JLabel ( name + "" ) ; this . name = name + "" ; } else { label = new JLabel ( name ) ; this . name = name ; } this . input = new JTextArea ( ) ; this . scrolling = new JScrollPane ( this . input ) ; this . setLayout ( new BorderLayout ( ) ) ; this . label . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; this . input . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; this . add ( label , BorderLayout . WEST ) ; this . add ( scrolling , BorderLayout . CENTER ) ; } public String getText ( ) { return this . label . getText ( ) ; } public String getInput ( ) { return this . input . getText ( ) + "" ; } public boolean isInComments ( ) { return inComments ; } public void setInComments ( boolean inComments ) { this . inComments = inComments ; } @ Override public boolean equals ( Object obj ) { if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final MultiLineInputElement other = ( MultiLineInputElement ) obj ; if ( ( this . name == null ) ? ( other . name != null ) : ! this . name . equals ( other . name ) ) { return false ; } return true ; } @ Override public int hashCode ( ) { int hash = ; hash = * hash + ( this . name != null ? this . name . hashCode ( ) : ) ; return hash ; } @ Override public void clear ( ) { this . input . setText ( "" ) ; } } package com . team1160 . scouting . frontend . elements ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import javax . swing . JButton ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; public class PrevButton extends JButton implements ActionListener { private static final long serialVersionUID = ; CardLayoutPacket layout ; public PrevButton ( CardLayoutPacket layout , String name ) { super ( name ) ; this . layout = layout ; this . addActionListener ( this ) ; } public PrevButton ( CardLayoutPacket layout ) { super ( "" ) ; this . layout = layout ; this . addActionListener ( this ) ; } public void actionPerformed ( ActionEvent e ) { this . layout . getLayout ( ) . previous ( this . layout . getParent ( ) ) ; } } package com . team1160 . scouting . frontend . elements ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; import javax . swing . JMenuItem ; public class PrevMenuItem extends JMenuItem implements ActionListener { private static final long serialVersionUID = - ; CardLayoutPacket layout ; public PrevMenuItem ( CardLayoutPacket layout , String name ) { super ( name ) ; this . layout = layout ; this . addActionListener ( this ) ; } public PrevMenuItem ( CardLayoutPacket layout ) { super ( "" ) ; this . layout = layout ; this . addActionListener ( this ) ; } public void actionPerformed ( ActionEvent e ) { this . layout . getLayout ( ) . previous ( this . layout . getParent ( ) ) ; } } package com . team1160 . scouting . frontend . elements ; import javax . swing . JLabel ; import javax . swing . JSlider ; public class WeightingSliderElement extends ScoutingElement { private static final long serialVersionUID = - ; private JLabel label ; private JSlider slider ; private String name ; private int hashCode ; public WeightingSliderElement ( String name , int hashCode ) { super ( ) ; if ( ! ( name . endsWith ( "" ) ) ) { label = new JLabel ( name + "" ) ; this . name = name + "" ; } else { label = new JLabel ( name ) ; this . name = name ; } this . slider = new JSlider ( ) ; this . slider . setMaximum ( ) ; this . slider . setMinimum ( ) ; this . slider . setMajorTickSpacing ( ) ; this . slider . setMinorTickSpacing ( ) ; this . slider . setPaintTicks ( true ) ; this . slider . setSnapToTicks ( true ) ; this . slider . setPaintLabels ( true ) ; this . add ( label ) ; this . add ( slider ) ; this . hashCode = hashCode ; } @ Override public String getInput ( ) { int value = this . slider . getValue ( ) ; return Integer . toString ( value ) ; } @ Override public String getText ( ) { return this . label . getText ( ) ; } @ Override public void clear ( ) { this . slider . setValue ( ) ; } public void setValue ( int n ) { slider . setValue ( n ) ; } @ Override public boolean equals ( Object obj ) { if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final WeightingSliderElement other = ( WeightingSliderElement ) obj ; if ( ( this . name == null ) ? ( other . name != null ) : ! this . name . equals ( other . name ) ) { return false ; } return true ; } @ Override public int hashCode ( ) { return this . hashCode ; } } package com . team1160 . scouting . frontend . elements ; import java . util . Vector ; import javax . swing . JComboBox ; import javax . swing . JLabel ; public class NumberDropDownElement extends ScoutingElement { private static final long serialVersionUID = ; private JLabel label ; private JComboBox dropDown ; private int bottom , top ; private String name ; public NumberDropDownElement ( String name , int bottom , int top ) { super ( ) ; if ( ! ( name . endsWith ( "" ) ) ) { label = new JLabel ( name + "" ) ; this . name = name + "" ; } else { label = new JLabel ( name ) ; this . name = name ; } this . bottom = bottom ; this . top = top ; Vector < Integer > items = new Vector < Integer > ( ) ; for ( int i = bottom ; i <= top ; i ++ ) { items . add ( i ) ; } this . dropDown = new JComboBox ( items ) ; this . add ( this . label ) ; this . add ( this . dropDown ) ; } public String getText ( ) { return this . label . getText ( ) . substring ( , this . label . getText ( ) . length ( ) ) ; } public String getInput ( ) { return this . dropDown . getSelectedItem ( ) . toString ( ) ; } @ Override public boolean equals ( Object obj ) { if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final NumberDropDownElement other = ( NumberDropDownElement ) obj ; if ( this . bottom != other . bottom ) { return false ; } if ( this . top != other . top ) { return false ; } if ( ( this . name == null ) ? ( other . name != null ) : ! this . name . equals ( other . name ) ) { return false ; } return true ; } @ Override public int hashCode ( ) { int hash = ; hash = * hash + this . bottom ; hash = * hash + this . top ; hash = * hash + ( this . name != null ? this . name . hashCode ( ) : ) ; return hash ; } @ Override public void clear ( ) { this . dropDown . setSelectedItem ( new Integer ( ) ) ; } } package com . team1160 . scouting . frontend . elements ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; import javax . swing . JMenuItem ; public class JumpMenuItem extends JMenuItem implements ActionListener { private static final long serialVersionUID = ; CardLayoutPacket layout ; String slideName ; public JumpMenuItem ( CardLayoutPacket layout , String text , String slideName ) { super ( text ) ; this . layout = layout ; this . slideName = slideName ; this . addActionListener ( this ) ; } public void actionPerformed ( ActionEvent e ) { this . layout . getLayout ( ) . show ( this . layout . getParent ( ) , slideName ) ; } } package com . team1160 . scouting . frontend . elements ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import com . team1160 . scouting . frontend . resourcePackets . CardLayoutPacket ; import javax . swing . JMenuItem ; public class NextMenuItem extends JMenuItem implements ActionListener { private static final long serialVersionUID = ; CardLayoutPacket layout ; public NextMenuItem ( CardLayoutPacket layout , String name ) { super ( name ) ; this . layout = layout ; this . addActionListener ( this ) ; } public NextMenuItem ( CardLayoutPacket layout ) { super ( "" ) ; this . layout = layout ; this . addActionListener ( this ) ; } public void actionPerformed ( ActionEvent e ) { this . layout . getLayout ( ) . next ( this . layout . getParent ( ) ) ; } } package com . team1160 . scouting . xml ; import java . io . File ; import java . io . IOException ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . SAXException ; public class XMLParser { String documentName ; File documentFile ; Document document ; public XMLParser ( String documentName ) throws ParserConfigurationException , SAXException , IOException { this . documentName = documentName ; documentFile = new File ( documentName ) ; DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; document = db . parse ( documentFile ) ; document . getDocumentElement ( ) . normalize ( ) ; } public Element getMatch ( ) { NodeList nodes = document . getDocumentElement ( ) . getChildNodes ( ) ; for ( int i = ; i < nodes . getLength ( ) ; i ++ ) { if ( nodes . item ( i ) . getNodeType ( ) == Node . ELEMENT_NODE ) { Element e = ( Element ) nodes . item ( i ) ; if ( e . getTagName ( ) . equals ( "" ) ) { return e ; } } } throw new NullPointerException ( "" ) ; } public Element getPit ( ) { NodeList nodes = document . getDocumentElement ( ) . getChildNodes ( ) ; for ( int i = ; i < nodes . getLength ( ) ; i ++ ) { if ( nodes . item ( i ) . getNodeType ( ) == Node . ELEMENT_NODE ) { Element e = ( Element ) nodes . item ( i ) ; if ( e . getTagName ( ) . equals ( "" ) ) { return e ; } } } throw new NullPointerException ( "" ) ; } } package com . team1160 . scouting . h2 ; import java . sql . * ; import org . h2 . Driver ; @ SuppressWarnings ( "" ) public abstract class H2Table { protected String database ; protected Connection connection ; protected Statement statement ; public H2Table ( String database ) throws ClassNotFoundException , SQLException { this . database = database ; Class . forName ( "" ) ; connection = DriverManager . getConnection ( "" + database ) ; statement = connection . createStatement ( ) ; } } package com . team1160 . scouting . h2 ; import java . sql . * ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; public class MatchScoutingTable extends H2Table { public MatchScoutingTable ( String database ) throws ClassNotFoundException , SQLException { super ( database ) ; statement . executeUpdate ( "" ) ; } public void insert ( int team , int ID , int value ) throws SQLException { PreparedStatement prep = connection . prepareStatement ( "" ) ; prep . setInt ( , team ) ; prep . setInt ( , ID ) ; prep . setInt ( , value ) ; prep . addBatch ( ) ; connection . setAutoCommit ( false ) ; prep . executeBatch ( ) ; connection . setAutoCommit ( true ) ; } public Map < Integer , Integer > getValues ( int team ) throws SQLException { ResultSet rs = statement . executeQuery ( "" + Integer . toString ( team ) ) ; Map < Integer , Integer > values = new HashMap < Integer , Integer > ( ) ; while ( rs . next ( ) ) { Integer key , value ; key = rs . getInt ( "" ) ; value = rs . getInt ( "" ) ; values . put ( key , value ) ; } return values ; } public List < Integer > getValues ( int team , int ID ) throws SQLException { ResultSet rs = statement . executeQuery ( "" + Integer . toString ( team ) + "" + Integer . toString ( ID ) ) ; List < Integer > values = new ArrayList < Integer > ( ) ; while ( rs . next ( ) ) { Integer value ; value = rs . getInt ( "" ) ; values . add ( value ) ; } return values ; } public int getAverageValue ( int team , int ID ) throws SQLException { List < Integer > values = this . getValues ( team , ID ) ; int sum = ; for ( Integer i : values ) { sum += i ; } int average = ( values . size ( ) == ) ? : sum / ( values . size ( ) ) ; return average ; } public List < Integer > getTeams ( ) throws SQLException { ResultSet rs = statement . executeQuery ( "" ) ; List < Integer > teams = new ArrayList < Integer > ( ) ; while ( rs . next ( ) ) { Integer team ; team = rs . getInt ( "" ) ; teams . add ( team ) ; } Collections . sort ( teams ) ; return teams ; } public void reset ( ) throws SQLException { statement . executeUpdate ( "" ) ; statement . executeUpdate ( "" ) ; } } package com . team1160 . scouting . h2 ; import java . sql . * ; import java . util . LinkedHashMap ; import java . util . Map ; public class DictTable extends H2Table { public DictTable ( String database ) throws SQLException , ClassNotFoundException { super ( database ) ; statement . executeUpdate ( "" ) ; } public void insert ( int ID , String value ) throws SQLException { PreparedStatement prep = connection . prepareStatement ( "" ) ; prep . setInt ( , ID ) ; prep . setString ( , value ) ; prep . addBatch ( ) ; connection . setAutoCommit ( false ) ; prep . executeBatch ( ) ; connection . setAutoCommit ( true ) ; } public String getString ( int ID ) throws SQLException { ResultSet rs = statement . executeQuery ( "" + Integer . toString ( ID ) ) ; return rs . getString ( "" ) ; } public String getID ( String value ) throws SQLException { ResultSet rs = statement . executeQuery ( "" + value ) ; return rs . getString ( "" ) ; } public Map < Integer , String > getValuesID ( ) throws SQLException { ResultSet rs = statement . executeQuery ( "" ) ; Map < Integer , String > values = new LinkedHashMap < Integer , String > ( ) ; while ( rs . next ( ) ) { Integer key ; String value ; key = rs . getInt ( "" ) ; value = rs . getString ( "" ) ; values . put ( key , value ) ; } return values ; } public Map < String , Integer > getValuesName ( ) throws SQLException { ResultSet rs = statement . executeQuery ( "" ) ; Map < String , Integer > values = new LinkedHashMap < String , Integer > ( ) ; while ( rs . next ( ) ) { Integer key ; String value ; key = rs . getInt ( "" ) ; value = rs . getString ( "" ) ; values . put ( value , key ) ; } return values ; } public void reset ( ) throws SQLException { statement . executeUpdate ( "" ) ; statement . executeUpdate ( "" ) ; } } package com . team1160 . scouting . h2 ; import java . sql . * ; import java . util . HashMap ; import java . util . Map ; public class WeightingTable extends H2Table { public WeightingTable ( String database ) throws ClassNotFoundException , SQLException { super ( database ) ; statement . executeUpdate ( "" ) ; } public void insert ( int ID , int value ) throws SQLException { PreparedStatement prep = connection . prepareStatement ( "" ) ; prep . setInt ( , ID ) ; prep . setInt ( , value ) ; prep . addBatch ( ) ; connection . setAutoCommit ( false ) ; prep . executeBatch ( ) ; connection . setAutoCommit ( true ) ; } public int getValue ( int ID ) throws SQLException { ResultSet rs ; try { rs = statement . executeQuery ( "" + Integer . toString ( ID ) ) ; rs . next ( ) ; return rs . getInt ( "" ) ; } catch ( SQLException ex ) { this . insert ( ID , ) ; return ; } } public Map < Integer , Integer > getValues ( ) throws SQLException { ResultSet rs = statement . executeQuery ( "" ) ; Map < Integer , Integer > values = new HashMap < Integer , Integer > ( ) ; while ( rs . next ( ) ) { Integer key ; Integer value ; key = rs . getInt ( "" ) ; value = rs . getInt ( "" ) ; values . put ( key , value ) ; } return values ; } public void reset ( ) throws SQLException { statement . executeUpdate ( "" ) ; statement . executeUpdate ( "" ) ; } } package com . team1160 . scouting . h2 ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; public class CommentTable extends H2Table { public CommentTable ( String database ) throws ClassNotFoundException , SQLException { super ( database ) ; statement . executeUpdate ( "" ) ; } public void insert ( int team , int match , String comment ) throws SQLException { PreparedStatement prep = connection . prepareStatement ( "" ) ; prep . setInt ( , team ) ; prep . setInt ( , match ) ; prep . setString ( , comment ) ; prep . addBatch ( ) ; connection . setAutoCommit ( false ) ; prep . executeBatch ( ) ; connection . setAutoCommit ( true ) ; } public String getComment ( int team , int match ) throws SQLException { ResultSet rs ; rs = statement . executeQuery ( "" + Integer . toString ( team ) + "" + Integer . toString ( match ) ) ; rs . next ( ) ; return rs . getString ( "" ) ; } public Map < Integer , String > getComments ( int team ) throws SQLException { ResultSet rs ; rs = statement . executeQuery ( "" + Integer . toString ( team ) ) ; Map < Integer , String > comments = new LinkedHashMap < Integer , String > ( ) ; while ( rs . next ( ) ) { Integer key ; String value ; key = rs . getInt ( "" ) ; value = rs . getString ( "" ) ; comments . put ( key , value ) ; } return comments ; } public List < Integer > getTeams ( ) throws SQLException { ResultSet rs = statement . executeQuery ( "" ) ; List < Integer > teams = new ArrayList < Integer > ( ) ; while ( rs . next ( ) ) { Integer team ; team = rs . getInt ( "" ) ; teams . add ( team ) ; } Collections . sort ( teams ) ; return teams ; } public void reset ( ) throws SQLException { statement . executeUpdate ( "" ) ; statement . executeUpdate ( "" ) ; } } package de . fuberlin . wiwiss . d2rq . dbschema ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( ISWCSchemaTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . dbschema ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class ISWCSchemaTest extends TestCase { private final static String driverClass = "" ; private final static String jdbcURL = "" ; private ConnectedDB db ; public void setUp ( ) throws Exception { Class . forName ( driverClass ) ; db = new ConnectedDB ( jdbcURL , null , null ) ; } public void tearDown ( ) { db . close ( ) ; } public void testRecognizeNullableColumn ( ) { Attribute personEmail = new Attribute ( null , "" , "" ) ; assertTrue ( db . isNullable ( personEmail ) ) ; } public void testRecognizeNonNullableColumn ( ) { Attribute personID = new Attribute ( null , "" , "" ) ; assertFalse ( db . isNullable ( personID ) ) ; } } package de . fuberlin . wiwiss . d2rq . examples ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . sparql . vocabulary . FOAF ; import com . hp . hpl . jena . vocabulary . DC ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; import de . fuberlin . wiwiss . d2rq . vocab . ISWC ; public class JenaModelExample { public static void main ( String [ ] args ) { ModelD2RQ m = new ModelD2RQ ( "" ) ; StmtIterator paperIt = m . listStatements ( null , RDF . type , ISWC . InProceedings ) ; while ( paperIt . hasNext ( ) ) { Resource paper = paperIt . nextStatement ( ) . getSubject ( ) ; System . out . println ( "" + paper . getProperty ( DC . title ) . getString ( ) ) ; StmtIterator authorIt = paper . listProperties ( DC . creator ) ; while ( authorIt . hasNext ( ) ) { Resource author = authorIt . nextStatement ( ) . getResource ( ) ; System . out . println ( "" + author . getProperty ( FOAF . name ) . getString ( ) ) ; } System . out . println ( ) ; } m . close ( ) ; } } package de . fuberlin . wiwiss . d2rq . examples ; import com . hp . hpl . jena . query . Query ; import com . hp . hpl . jena . query . QueryExecutionFactory ; import com . hp . hpl . jena . query . QueryFactory ; import com . hp . hpl . jena . query . QuerySolution ; import com . hp . hpl . jena . query . ResultSet ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; public class SPARQLExample { public static void main ( String [ ] args ) { ModelD2RQ m = new ModelD2RQ ( "" ) ; String sparql = "" + "" + "" + "" + "" + "" + "" ; Query q = QueryFactory . create ( sparql ) ; ResultSet rs = QueryExecutionFactory . create ( q , m ) . execSelect ( ) ; while ( rs . hasNext ( ) ) { QuerySolution row = rs . nextSolution ( ) ; System . out . println ( "" + row . getLiteral ( "" ) . getString ( ) ) ; System . out . println ( "" + row . getLiteral ( "" ) . getString ( ) ) ; } m . close ( ) ; } } package de . fuberlin . wiwiss . d2rq . examples ; import com . hp . hpl . jena . assembler . Assembler ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . util . FileManager ; public class AssemblerExample { public static void main ( String [ ] args ) { Model assemblerSpec = FileManager . get ( ) . loadModel ( "" ) ; Resource modelSpec = assemblerSpec . createResource ( assemblerSpec . expandPrefix ( "" ) ) ; Model m = Assembler . general . openModel ( modelSpec ) ; m . write ( System . out ) ; m . close ( ) ; } } package de . fuberlin . wiwiss . d2rq . examples ; import com . hp . hpl . jena . query . QueryExecutionFactory ; import com . hp . hpl . jena . query . ResultSet ; import com . hp . hpl . jena . rdf . model . Model ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; public class SystemLoaderExample { public static void main ( String [ ] args ) { SystemLoader loader = new SystemLoader ( ) ; loader . setJdbcURL ( "" ) ; loader . setStartupSQLScript ( "" ) ; loader . setGenerateW3CDirectMapping ( true ) ; Mapping mapping = loader . getMapping ( ) ; for ( TripleRelation internal : mapping . compiledPropertyBridges ( ) ) { System . out . println ( internal ) ; } Model model = loader . getModelD2RQ ( ) ; model . write ( System . out , "" ) ; model . close ( ) ; loader = new SystemLoader ( ) ; loader . setMappingFileOrJdbcURL ( "" ) ; loader . setFastMode ( true ) ; loader . setSystemBaseURI ( "" ) ; model = loader . getModelD2RQ ( ) ; ResultSet rs = QueryExecutionFactory . create ( "" , model ) . execSelect ( ) ; while ( rs . hasNext ( ) ) { System . out . println ( rs . next ( ) ) ; } model . close ( ) ; } } package de . fuberlin . wiwiss . d2rq . examples ; import java . util . Iterator ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . util . FileManager ; import com . hp . hpl . jena . vocabulary . DC ; import de . fuberlin . wiwiss . d2rq . jena . GraphD2RQ ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; public class JenaGraphExample { public static void main ( String [ ] args ) { Model mapModel = FileManager . get ( ) . loadModel ( "" ) ; MapParser parser = new MapParser ( mapModel , "" ) ; Mapping mapping = parser . parse ( ) ; GraphD2RQ g = new GraphD2RQ ( mapping ) ; Node subject = Node . ANY ; Node predicate = DC . date . asNode ( ) ; Node object = Node . createLiteral ( "" , null , XSDDatatype . XSDgYear ) ; Triple pattern = new Triple ( subject , predicate , object ) ; Iterator < Triple > it = g . find ( pattern ) ; while ( it . hasNext ( ) ) { Triple t = it . next ( ) ; System . out . println ( "" + t . getSubject ( ) ) ; } g . close ( ) ; } } package de . fuberlin . wiwiss . d2rq . download ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . ResourceFactory ; import de . fuberlin . wiwiss . d2rq . helpers . HSQLDatabase ; import de . fuberlin . wiwiss . d2rq . helpers . MappingHelper ; import de . fuberlin . wiwiss . d2rq . map . DownloadMap ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; public class DownloadContentQueryTest extends TestCase { private HSQLDatabase db ; private DownloadMap downloadCLOB ; private DownloadMap downloadBLOB ; private DownloadContentQuery q ; public void setUp ( ) { db = new HSQLDatabase ( "" ) ; db . executeSQL ( "" ) ; db . executeSQL ( "" ) ; db . executeSQL ( "" ) ; Mapping m = MappingHelper . readFromTestFile ( "" ) ; downloadCLOB = m . downloadMap ( ResourceFactory . createResource ( "" ) ) ; downloadBLOB = m . downloadMap ( ResourceFactory . createResource ( "" ) ) ; } public void tearDown ( ) { db . close ( true ) ; if ( q != null ) q . close ( ) ; } public void testFixture ( ) { assertNotNull ( downloadCLOB ) ; assertNotNull ( downloadBLOB ) ; } public void testNullForNonDownloadURI ( ) { q = new DownloadContentQuery ( downloadCLOB , "" ) ; assertFalse ( q . hasContent ( ) ) ; assertNull ( q . getContentStream ( ) ) ; } public void testNullForNonExistingRecord ( ) { q = new DownloadContentQuery ( downloadCLOB , "" ) ; assertFalse ( q . hasContent ( ) ) ; assertNull ( q . getContentStream ( ) ) ; } public void testReturnCLOBContentForExistingRecord ( ) throws IOException { q = new DownloadContentQuery ( downloadCLOB , "" ) ; assertTrue ( q . hasContent ( ) ) ; assertEquals ( "" , inputStreamToString ( q . getContentStream ( ) ) ) ; } public void testNULLContent ( ) { q = new DownloadContentQuery ( downloadCLOB , "" ) ; assertFalse ( q . hasContent ( ) ) ; assertNull ( q . getContentStream ( ) ) ; } public void testReturnBLOBContentForExistingRecord ( ) throws IOException { q = new DownloadContentQuery ( downloadBLOB , "" ) ; assertTrue ( q . hasContent ( ) ) ; assertEquals ( "" , inputStreamToString ( q . getContentStream ( ) ) ) ; } private String inputStreamToString ( InputStream is ) throws IOException { final char [ ] buffer = new char [ ] ; StringBuilder out = new StringBuilder ( ) ; Reader in = new InputStreamReader ( is , "" ) ; int read ; do { read = in . read ( buffer , , buffer . length ) ; if ( read > ) { out . append ( buffer , , read ) ; } } while ( read >= ) ; return out . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . download ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( AllTests . class . getName ( ) ) ; suite . addTestSuite ( DownloadContentQueryTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Arrays ; import java . util . Collections ; import junit . framework . TestCase ; public class ConjunctionTest extends TestCase { private final static String sql1 = "" ; private final static String sql2 = "" ; private final static String sql3 = "" ; private final static Expression expr1 = SQLExpression . create ( sql1 ) ; private final static Expression expr2 = SQLExpression . create ( sql2 ) ; private final static Expression expr3 = SQLExpression . create ( sql3 ) ; private final static Expression conjunction12 = Conjunction . create ( Arrays . asList ( new Expression [ ] { expr1 , expr2 } ) ) ; private final static Expression conjunction123 = Conjunction . create ( Arrays . asList ( new Expression [ ] { expr1 , expr2 , expr3 } ) ) ; private final static Expression conjunction21 = Conjunction . create ( Arrays . asList ( new Expression [ ] { expr2 , expr1 } ) ) ; public void testEmptyConjunctionIsTrue ( ) { assertEquals ( Expression . TRUE , Conjunction . create ( Collections . < Expression > emptySet ( ) ) ) ; } public void testSingletonConjunctionIsSelf ( ) { Expression e = SQLExpression . create ( "" ) ; assertEquals ( e , Conjunction . create ( Collections . singleton ( e ) ) ) ; } public void testCreateConjunction ( ) { assertFalse ( conjunction12 . isTrue ( ) ) ; assertFalse ( conjunction12 . isFalse ( ) ) ; } public void testToString ( ) { assertEquals ( "" , conjunction12 . toString ( ) ) ; } public void testTrueExpressionsAreSkipped ( ) { assertEquals ( Expression . TRUE , Conjunction . create ( Arrays . asList ( new Expression [ ] { Expression . TRUE , Expression . TRUE } ) ) ) ; assertEquals ( expr1 , Conjunction . create ( Arrays . asList ( new Expression [ ] { Expression . TRUE , expr1 , Expression . TRUE } ) ) ) ; assertEquals ( conjunction12 , Conjunction . create ( Arrays . asList ( new Expression [ ] { Expression . TRUE , expr1 , Expression . TRUE , expr2 } ) ) ) ; } public void testFalseCausesFailure ( ) { assertEquals ( Expression . FALSE , Conjunction . create ( Collections . singleton ( Expression . FALSE ) ) ) ; assertEquals ( Expression . FALSE , Conjunction . create ( Arrays . asList ( new Expression [ ] { expr1 , Expression . FALSE } ) ) ) ; } public void testRemoveDuplicates ( ) { assertEquals ( expr1 , Conjunction . create ( Arrays . asList ( new Expression [ ] { expr1 , expr1 } ) ) ) ; } public void testFlatten ( ) { assertEquals ( conjunction123 , Conjunction . create ( Arrays . asList ( new Expression [ ] { conjunction12 , expr3 } ) ) ) ; } public void testOrderDoesNotAffectEquality ( ) { assertEquals ( conjunction12 , conjunction21 ) ; assertEquals ( conjunction12 . hashCode ( ) , conjunction21 . hashCode ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Collections ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . sql . DummyDB ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType . GenericType ; public class ExpressionTest extends TestCase { private AliasMap aliases ; public void setUp ( ) { aliases = AliasMap . create1 ( new RelationName ( null , "" ) , new RelationName ( null , "" ) ) ; } public void testTrue ( ) { assertEquals ( "" , Expression . TRUE . toString ( ) ) ; assertEquals ( Expression . TRUE , Expression . TRUE ) ; assertTrue ( Expression . TRUE . isTrue ( ) ) ; assertFalse ( Expression . TRUE . isFalse ( ) ) ; } public void testFalse ( ) { assertEquals ( "" , Expression . FALSE . toString ( ) ) ; assertEquals ( Expression . FALSE , Expression . FALSE ) ; assertFalse ( Expression . FALSE . isTrue ( ) ) ; assertTrue ( Expression . FALSE . isFalse ( ) ) ; } public void testTrueNotEqualFalse ( ) { assertFalse ( Expression . TRUE . equals ( Expression . FALSE ) ) ; } public void testConstant ( ) { Expression expr = new Constant ( "" ) ; assertTrue ( expr . attributes ( ) . isEmpty ( ) ) ; assertFalse ( expr . isFalse ( ) ) ; assertFalse ( expr . isTrue ( ) ) ; assertEquals ( expr , expr . renameAttributes ( aliases ) ) ; } public void testConstantEquals ( ) { assertTrue ( new Constant ( "" ) . equals ( new Constant ( "" ) ) ) ; assertFalse ( new Constant ( "" ) . equals ( new Constant ( "" ) ) ) ; assertFalse ( new Constant ( "" ) . equals ( Expression . TRUE ) ) ; } public void testConstantHashCode ( ) { assertEquals ( new Constant ( "" ) . hashCode ( ) , new Constant ( "" ) . hashCode ( ) ) ; assertFalse ( new Constant ( "" ) . hashCode ( ) == new Constant ( "" ) . hashCode ( ) ) ; } public void testConstantToString ( ) { assertEquals ( "" , new Constant ( "" ) . toString ( ) ) ; } public void testConstantToSQL ( ) { assertEquals ( "" , new Constant ( "" ) . toSQL ( new DummyDB ( ) , AliasMap . NO_ALIASES ) ) ; } public void testConstantToSQLWithType ( ) { Attribute attribute = SQL . parseAttribute ( "" ) ; DummyDB db = new DummyDB ( Collections . singletonMap ( "" , GenericType . NUMERIC ) ) ; assertEquals ( "" , new Constant ( "" , attribute ) . toSQL ( db , AliasMap . NO_ALIASES ) ) ; } public void testConstantToSQLWithTypeAndAlias ( ) { Attribute aliasedAttribute = SQL . parseAttribute ( "" ) ; DummyDB db = new DummyDB ( Collections . singletonMap ( "" , GenericType . NUMERIC ) ) ; assertEquals ( "" , new Constant ( "" , aliasedAttribute ) . toSQL ( db , aliases ) ) ; } public void testConstantTypeAttributeIsRenamed ( ) { Attribute attribute = SQL . parseAttribute ( "" ) ; assertEquals ( "" , new Constant ( "" , attribute ) . renameAttributes ( aliases ) . toString ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( ConjunctionTest . class ) ; suite . addTestSuite ( SQLExpressionTest . class ) ; suite . addTestSuite ( ConcatenationTest . class ) ; suite . addTestSuite ( ExpressionTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Arrays ; import java . util . Collections ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; public class ConcatenationTest extends TestCase { public void testCreateEmpty ( ) { assertEquals ( new Constant ( "" ) , Concatenation . create ( Collections . < Expression > emptyList ( ) ) ) ; } public void testCreateOnePart ( ) { Expression expr = new AttributeExpr ( new Attribute ( null , "" , "" ) ) ; assertEquals ( expr , Concatenation . create ( Collections . singletonList ( expr ) ) ) ; } public void testTwoParts ( ) { Expression expr1 = new Constant ( "" ) ; Expression expr2 = new AttributeExpr ( new Attribute ( null , "" , "" ) ) ; Expression concat = Concatenation . create ( Arrays . asList ( new Expression [ ] { expr1 , expr2 } ) ) ; assertEquals ( "" , concat . toString ( ) ) ; } public void testFilterEmptyParts ( ) { Expression empty = new Constant ( "" ) ; Expression expr1 = new Constant ( "" ) ; assertEquals ( expr1 , Concatenation . create ( Arrays . asList ( new Expression [ ] { empty , empty , expr1 , empty } ) ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamerMap ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; public class SQLExpressionTest extends TestCase { public void testCreate ( ) { Expression e = SQLExpression . create ( "" ) ; assertEquals ( "" , e . toString ( ) ) ; assertFalse ( e . isTrue ( ) ) ; assertFalse ( e . isFalse ( ) ) ; } public void testFindsColumns ( ) { Expression e = SQLExpression . create ( "" ) ; Set < Attribute > expectedColumns = new HashSet < Attribute > ( Arrays . asList ( new Attribute [ ] { new Attribute ( null , "" , "" ) , new Attribute ( null , "" , "" ) , new Attribute ( null , "" , "" ) , new Attribute ( null , "" , "" ) } ) ) ; assertEquals ( expectedColumns , e . attributes ( ) ) ; } public void testToString ( ) { Expression e = SQLExpression . create ( "" ) ; assertEquals ( "" , e . toString ( ) ) ; } public void testTwoExpressionsAreEqual ( ) { assertEquals ( SQLExpression . create ( "" ) , SQLExpression . create ( "" ) ) ; assertEquals ( SQLExpression . create ( "" ) . hashCode ( ) , SQLExpression . create ( "" ) . hashCode ( ) ) ; } public void testTwoExpressionsAreNotEqual ( ) { assertFalse ( SQLExpression . create ( "" ) . equals ( SQLExpression . create ( "" ) ) ) ; assertFalse ( SQLExpression . create ( "" ) . hashCode ( ) == SQLExpression . create ( "" ) . hashCode ( ) ) ; } public void testRenameColumnsWithAliasMap ( ) { Alias a = new Alias ( new RelationName ( null , "" ) , new RelationName ( null , "" ) ) ; assertEquals ( SQLExpression . create ( "" ) , SQLExpression . create ( "" ) . renameAttributes ( new AliasMap ( Collections . singleton ( a ) ) ) ) ; } public void testRenameColumnsWithColumnReplacer ( ) { Map < Attribute , Attribute > map = new HashMap < Attribute , Attribute > ( ) ; map . put ( new Attribute ( null , "" , "" ) , new Attribute ( null , "" , "" ) ) ; assertEquals ( SQLExpression . create ( "" ) , SQLExpression . create ( "" ) . renameAttributes ( new ColumnRenamerMap ( map ) ) ) ; } } package de . fuberlin . wiwiss . d2rq . functional_tests ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static void main ( String [ ] args ) { junit . textui . TestRunner . run ( AllTests . suite ( ) ) ; } public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( FindTest . class ) ; suite . addTestSuite ( SPARQLTest . class ) ; suite . addTestSuite ( ModelAPITest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . functional_tests ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . vocabulary . DC ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; import de . fuberlin . wiwiss . d2rq . helpers . QueryLanguageTestFramework ; import de . fuberlin . wiwiss . d2rq . vocab . ISWC ; import de . fuberlin . wiwiss . d2rq . vocab . SKOS ; public class SPARQLTest extends QueryLanguageTestFramework { protected String mapURL ( ) { return D2RQTestSuite . ISWC_MAP ; } public void testSPARQLFetch ( ) { sparql ( "" ) ; expectVariable ( "" , ISWC . conference ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; expectVariable ( "" , SKOS . primarySubject ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; expectVariable ( "" , SKOS . subject ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; expectVariable ( "" , DC . date ) ; expectVariable ( "" , this . model . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertSolution ( ) ; expectVariable ( "" , DC . title ) ; expectVariable ( "" , this . model . createLiteral ( "" , "" ) ) ; assertSolution ( ) ; expectVariable ( "" , RDF . type ) ; expectVariable ( "" , ISWC . InProceedings ) ; assertSolution ( ) ; assertResultCount ( ) ; } public void testSPARQLGetAuthorsAndEmails ( ) { sparql ( "" + "" ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; assertResultCount ( ) ; } public void testSPARQLGetAuthorsAndEmailsWithCondition ( ) { sparql ( "" + "" + "" ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; assertResultCount ( ) ; } public void testSPARQLGetTopics ( ) { sparql ( "" ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createTypedLiteral ( "" , XSDDatatype . XSDstring ) ) ; assertSolution ( ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createTypedLiteral ( "" , XSDDatatype . XSDstring ) ) ; assertSolution ( ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createTypedLiteral ( "" , XSDDatatype . XSDstring ) ) ; assertSolution ( ) ; assertResultCount ( ) ; } public void testSPARQLGetAuthorsOfPaperByTitle ( ) { sparql ( "" ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; assertResultCount ( ) ; } public void testSPARQLGetAuthorsNameAndEmail ( ) { sparql ( "" ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; expectVariable ( "" , this . model . createResource ( "" ) ) ; assertSolution ( ) ; assertResultCount ( ) ; } public void testGetTitleAndYearOfAllPapers ( ) { sparql ( "" ) ; expectVariable ( "" , this . model . createLiteral ( "" , "" ) ) ; expectVariable ( "" , this . model . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertSolution ( ) ; assertResultCount ( ) ; } public void testRDFType ( ) { sparql ( "" ) ; } } package de . fuberlin . wiwiss . d2rq . functional_tests ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . rdf . model . AnonId ; import com . hp . hpl . jena . sparql . vocabulary . FOAF ; import com . hp . hpl . jena . vocabulary . DC ; import com . hp . hpl . jena . vocabulary . RDF ; import com . hp . hpl . jena . vocabulary . RDFS ; import com . hp . hpl . jena . vocabulary . VCARD ; import de . fuberlin . wiwiss . d2rq . helpers . FindTestFramework ; import de . fuberlin . wiwiss . d2rq . vocab . ISWC ; import de . fuberlin . wiwiss . d2rq . vocab . SKOS ; public class FindTest extends FindTestFramework { public void testListTypeStatements ( ) { find ( null , RDF . type , null ) ; assertStatement ( resource ( "" ) , RDF . type , ISWC . InProceedings ) ; assertNoStatement ( resource ( "" ) , RDF . type , ISWC . InProceedings ) ; assertStatement ( resource ( "" ) , RDF . type , ISWC . Conference ) ; assertStatement ( resource ( "" ) , RDF . type , SKOS . Concept ) ; assertStatementCount ( ) ; } public void testListTopicInstances ( ) { find ( null , RDF . type , SKOS . Concept ) ; assertStatement ( resource ( "" ) , RDF . type , SKOS . Concept ) ; assertStatement ( resource ( "" ) , RDF . type , SKOS . Concept ) ; assertStatementCount ( ) ; } public void testListTopicNames ( ) { find ( null , SKOS . prefLabel , null ) ; assertStatement ( resource ( "" ) , SKOS . prefLabel , m . createTypedLiteral ( "" ) ) ; assertStatement ( resource ( "" ) , SKOS . prefLabel , m . createTypedLiteral ( "" ) ) ; assertStatementCount ( ) ; } public void testListAuthors ( ) { find ( null , DC . creator , null ) ; assertStatement ( resource ( "" ) , DC . creator , resource ( "" ) ) ; assertStatement ( resource ( "" ) , DC . creator , resource ( "" ) ) ; assertStatementCount ( ) ; } public void testDatatypeFindByYear ( ) { find ( null , DC . date , m . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertStatement ( resource ( "" ) , DC . date , m . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertStatementCount ( ) ; } public void testDatatypeFindByString ( ) { find ( null , SKOS . prefLabel , m . createTypedLiteral ( "" , XSDDatatype . XSDstring ) ) ; assertStatement ( resource ( "" ) , SKOS . prefLabel , m . createTypedLiteral ( "" , XSDDatatype . XSDstring ) ) ; assertStatementCount ( ) ; } public void testXSDStringDoesntMatchPlainLiteral ( ) { find ( null , SKOS . prefLabel , m . createLiteral ( "" ) ) ; assertStatementCount ( ) ; } public void testDatatypeFindYear ( ) { find ( resource ( "" ) , DC . date , null ) ; assertStatement ( resource ( "" ) , DC . date , m . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertStatementCount ( ) ; } public void testDatatypeYearContains ( ) { find ( resource ( "" ) , DC . date , m . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertStatement ( resource ( "" ) , DC . date , m . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertStatementCount ( ) ; assertStatementCount ( ) ; } public void testLiteralLanguage ( ) { find ( null , DC . title , m . createLiteral ( "" , "" ) ) ; assertStatement ( resource ( "" ) , DC . title , m . createLiteral ( "" , "" ) ) ; assertStatementCount ( ) ; } public void testFindSubjectWhereObjectURIColumn ( ) { find ( null , DC . creator , resource ( "" ) ) ; assertStatement ( resource ( "" ) , DC . creator , resource ( "" ) ) ; assertStatementCount ( ) ; } public void testFindSubjectWithConditionalObject ( ) { find ( null , DC . creator , resource ( "" ) ) ; assertStatementCount ( ) ; } public void testFindSubjectWhereObjectURIPattern ( ) { find ( null , FOAF . mbox , m . createResource ( "" ) ) ; assertStatement ( resource ( "" ) , FOAF . mbox , m . createResource ( "" ) ) ; assertStatementCount ( ) ; } public void testFindAnonymousNode ( ) { find ( null , VCARD . Pcode , m . createLiteral ( "" ) ) ; assertStatement ( m . createResource ( new AnonId ( "" ) ) , VCARD . Pcode , m . createLiteral ( "" ) ) ; assertStatementCount ( ) ; } public void testMatchAnonymousSubject ( ) { find ( m . createResource ( new AnonId ( "" ) ) , VCARD . Pcode , null ) ; assertStatement ( m . createResource ( new AnonId ( "" ) ) , VCARD . Pcode , m . createLiteral ( "" ) ) ; assertStatementCount ( ) ; } public void testMatchAnonymousObject ( ) { find ( null , VCARD . ADR , m . createResource ( new AnonId ( "" ) ) ) ; assertStatement ( resource ( "" ) , VCARD . ADR , m . createResource ( new AnonId ( "" ) ) ) ; assertStatementCount ( ) ; } public void testDump ( ) { find ( null , null , null ) ; assertStatementCount ( ) ; } public void testFindPredicate ( ) { find ( resource ( "" ) , null , m . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertStatement ( resource ( "" ) , DC . date , m . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertStatementCount ( ) ; } public void testReverseFetchWithDatatype ( ) { find ( null , null , m . createTypedLiteral ( "" , XSDDatatype . XSDgYear ) ) ; assertStatementCount ( ) ; } public void testReverseFetchWithURI ( ) { find ( null , null , resource ( "" ) ) ; assertStatementCount ( ) ; } public void testFindAliasedPropertyBridge ( ) { find ( null , SKOS . broader , null ) ; assertStatement ( resource ( "" ) , SKOS . broader , resource ( "" ) ) ; assertStatementCount ( ) ; } public void testDefinitions ( ) { find ( ISWC . Conference , null , null ) ; assertStatement ( ISWC . Conference , RDF . type , RDFS . Class ) ; assertStatement ( ISWC . Conference , RDFS . label , m . createLiteral ( "" ) ) ; assertStatement ( ISWC . Conference , RDFS . comment , m . createLiteral ( "" ) ) ; assertStatement ( ISWC . Conference , RDFS . subClassOf , ISWC . Event ) ; find ( RDFS . label , null , null ) ; assertStatement ( RDFS . label , RDF . type , RDF . Property ) ; assertStatement ( RDFS . label , RDFS . label , m . createLiteral ( "" ) ) ; assertStatement ( RDFS . label , RDFS . comment , m . createLiteral ( "" ) ) ; assertStatement ( RDFS . label , RDFS . domain , RDFS . Resource ) ; } } package de . fuberlin . wiwiss . d2rq . functional_tests ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . RDFNode ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . vocabulary . DC ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; public class ModelAPITest extends TestCase { private ModelD2RQ model ; protected void setUp ( ) throws Exception { this . model = new ModelD2RQ ( D2RQTestSuite . ISWC_MAP , "" , "" ) ; } protected void tearDown ( ) throws Exception { this . model . close ( ) ; } public void testListStatements ( ) { StmtIterator iter = this . model . listStatements ( ) ; int count = ; while ( iter . hasNext ( ) ) { Statement stmt = iter . nextStatement ( ) ; stmt . toString ( ) ; count ++ ; } assertEquals ( , count ) ; } public void testHasProperty ( ) { assertTrue ( this . model . getResource ( "" ) . hasProperty ( DC . creator ) ) ; } void dumpStatement ( Statement stmt ) { Resource subject = stmt . getSubject ( ) ; Property predicate = stmt . getPredicate ( ) ; RDFNode object = stmt . getObject ( ) ; System . out . print ( subject + "" + predicate + "" ) ; if ( object instanceof Resource ) { System . out . print ( object ) ; } else { System . out . print ( "" + object + "" ) ; } System . out . println ( "" ) ; } } package de . fuberlin . wiwiss . d2rq . sql ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; public class ResultRowTest extends TestCase { private static final Attribute col1 = new Attribute ( null , "" , "" ) ; private static final Attribute col2 = new Attribute ( null , "" , "" ) ; public void testGetUndefinedReturnsNull ( ) { ResultRow r = new ResultRowMap ( Collections . < ProjectionSpec , String > emptyMap ( ) ) ; assertNull ( r . get ( col1 ) ) ; assertNull ( r . get ( col2 ) ) ; } public void testGetColumnReturnsValue ( ) { Map < ProjectionSpec , String > m = new HashMap < ProjectionSpec , String > ( ) ; m . put ( col1 , "" ) ; ResultRow r = new ResultRowMap ( m ) ; assertEquals ( "" , r . get ( col1 ) ) ; assertNull ( r . get ( col2 ) ) ; } public void testEmptyRowToString ( ) { assertEquals ( "" , new ResultRowMap ( Collections . < ProjectionSpec , String > emptyMap ( ) ) . toString ( ) ) ; } public void testTwoItemsToString ( ) { Map < ProjectionSpec , String > m = new HashMap < ProjectionSpec , String > ( ) ; m . put ( col1 , "" ) ; m . put ( col2 , "" ) ; assertEquals ( "" , new ResultRowMap ( m ) . toString ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . sql ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import junit . framework . TestCase ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . ResourceFactory ; import com . hp . hpl . jena . util . iterator . ExtendedIterator ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . dbschema . DatabaseSchemaInspector ; import de . fuberlin . wiwiss . d2rq . jena . GraphD2RQ ; import de . fuberlin . wiwiss . d2rq . map . ClassMap ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . map . PropertyBridge ; public abstract class DatatypeTestBase extends TestCase { private final static String EX = "" ; private final static Resource dbURI = ResourceFactory . createResource ( EX + "" ) ; private final static Resource classMapURI = ResourceFactory . createResource ( EX + "" ) ; private final static Resource propertyBridgeURI = ResourceFactory . createResource ( EX + "" ) ; private final static Resource valueProperty = ResourceFactory . createProperty ( EX + "" ) ; private String jdbcURL ; private String driver ; private String user ; private String password ; private String schema ; private String script ; private String datatype ; private GraphD2RQ graph ; private DatabaseSchemaInspector inspector ; public void tearDown ( ) { if ( graph != null ) graph . close ( ) ; } protected void initDB ( String jdbcURL , String driver , String user , String password , String script , String schema ) { this . jdbcURL = jdbcURL ; this . driver = driver ; this . user = user ; this . password = password ; this . script = script ; this . schema = null ; dropAllTables ( ) ; } private void dropAllTables ( ) { ConnectedDB . registerJDBCDriver ( driver ) ; ConnectedDB db = new ConnectedDB ( jdbcURL , user , password ) ; try { Statement stmt = db . connection ( ) . createStatement ( ) ; try { for ( String table : allTables ( ) ) { stmt . execute ( "" + table ) ; } } finally { stmt . close ( ) ; } } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } finally { db . close ( ) ; } } protected void createMapping ( String datatype ) { this . datatype = datatype ; Mapping mapping = generateMapping ( ) ; mapping . configuration ( ) . setServeVocabulary ( false ) ; mapping . configuration ( ) . setUseAllOptimizations ( true ) ; mapping . connect ( ) ; graph = getGraph ( mapping ) ; inspector = mapping . databases ( ) . iterator ( ) . next ( ) . connectedDB ( ) . schemaInspector ( ) ; } protected void assertMappedType ( String rdfType ) { assertEquals ( rdfType , inspector . columnType ( SQL . parseAttribute ( "" + datatype + "" ) ) . rdfType ( ) ) ; } protected void assertValues ( String [ ] expectedValues ) { assertValues ( expectedValues , true ) ; } protected void assertValues ( String [ ] expectedValues , boolean searchValues ) { ExtendedIterator < Triple > it = graph . find ( Node . ANY , Node . ANY , Node . ANY ) ; List < String > listedValues = new ArrayList < String > ( ) ; while ( it . hasNext ( ) ) { listedValues . add ( it . next ( ) . getObject ( ) . getLiteralLexicalForm ( ) ) ; } assertEquals ( Arrays . asList ( expectedValues ) , listedValues ) ; if ( ! searchValues ) return ; for ( String value : expectedValues ) { assertTrue ( "" + value + "" , graph . contains ( Node . ANY , Node . ANY , Node . createLiteral ( value ) ) ) ; } } protected void assertValuesNotFindable ( String [ ] expectedValues ) { for ( String value : expectedValues ) { assertFalse ( "" + value + "" , graph . contains ( Node . ANY , Node . ANY , Node . createLiteral ( value ) ) ) ; } } private Set < String > allTables ( ) { ConnectedDB . registerJDBCDriver ( driver ) ; ConnectedDB db = new ConnectedDB ( jdbcURL , user , password ) ; try { Set < String > result = new HashSet < String > ( ) ; inspector = db . schemaInspector ( ) ; for ( RelationName name : inspector . listTableNames ( schema ) ) { result . add ( name . toString ( ) ) ; } return result ; } finally { db . close ( ) ; } } private GraphD2RQ getGraph ( Mapping mapping ) { return new GraphD2RQ ( mapping ) ; } private Mapping generateMapping ( ) { Mapping mapping = new Mapping ( ) ; Database database = new Database ( dbURI ) ; database . setJDBCDSN ( jdbcURL ) ; database . setJDBCDriver ( driver ) ; database . setUsername ( user ) ; database . setPassword ( password ) ; database . setStartupSQLScript ( ResourceFactory . createResource ( "" + script ) ) ; mapping . addDatabase ( database ) ; ClassMap classMap = new ClassMap ( classMapURI ) ; classMap . setDatabase ( database ) ; classMap . setURIPattern ( "" + datatype + "" ) ; mapping . addClassMap ( classMap ) ; PropertyBridge propertyBridge = new PropertyBridge ( propertyBridgeURI ) ; propertyBridge . setBelongsToClassMap ( classMap ) ; propertyBridge . addProperty ( valueProperty ) ; propertyBridge . setColumn ( "" + datatype + "" ) ; classMap . addPropertyBridge ( propertyBridge ) ; return mapping ; } } package de . fuberlin . wiwiss . d2rq . sql ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLBuildingTest extends TestCase { private final static Attribute foo = new Attribute ( null , "" , "" ) ; public void testSingleQuoteEscapeMySQL ( ) { Vendor vendor = Vendor . MySQL ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; } public void testSingleQuoteEscape ( ) { Vendor vendor = Vendor . SQL92 ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; assertEquals ( "" , vendor . quoteStringLiteral ( "" ) ) ; } public void testQuoteIdentifierEscape ( ) { Vendor db = Vendor . SQL92 ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; } public void testQuoteIdentifierEscapeMySQL ( ) { Vendor db = Vendor . MySQL ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; assertEquals ( "" , db . quoteIdentifier ( "" ) ) ; } public void testAttributeQuoting ( ) { Vendor db = Vendor . SQL92 ; assertEquals ( "" , db . quoteAttribute ( new Attribute ( "" , "" , "" ) ) ) ; assertEquals ( "" , db . quoteAttribute ( new Attribute ( null , "" , "" ) ) ) ; } public void testDoubleQuotesInAttributesAreEscaped ( ) { Vendor db = Vendor . SQL92 ; assertEquals ( "" , db . quoteAttribute ( new Attribute ( "" , "" , "" ) ) ) ; } public void testAttributeQuotingMySQL ( ) { Vendor db = Vendor . MySQL ; assertEquals ( "" , db . quoteAttribute ( new Attribute ( null , "" , "" ) ) ) ; } public void testRelationNameQuoting ( ) { Vendor db = new DummyDB ( ) . vendor ( ) ; assertEquals ( "" , db . quoteRelationName ( new RelationName ( "" , "" ) ) ) ; assertEquals ( "" , db . quoteRelationName ( new RelationName ( null , "" ) ) ) ; } public void testBackticksInRelationsAreEscapedMySQL ( ) { Vendor db = Vendor . MySQL ; assertEquals ( "" , db . quoteRelationName ( new RelationName ( null , "" ) ) ) ; } public void testRelationNameQuotingMySQL ( ) { Vendor db = Vendor . MySQL ; assertEquals ( "" , db . quoteRelationName ( new RelationName ( null , "" ) ) ) ; } public void testNoLimit ( ) { ConnectedDB db = new DummyDB ( ) ; Relation r = Relation . createSimpleRelation ( db , new Attribute [ ] { foo } ) ; assertEquals ( "" , new SelectStatementBuilder ( r ) . getSQLStatement ( ) ) ; } public void testLimitStandard ( ) { DummyDB db = new DummyDB ( ) ; db . setLimit ( ) ; Relation r = Relation . createSimpleRelation ( db , new Attribute [ ] { foo } ) ; assertEquals ( "" , new SelectStatementBuilder ( r ) . getSQLStatement ( ) ) ; } public void testNoLimitMSSQL ( ) { DummyDB db = new DummyDB ( Vendor . SQLServer ) ; db . setLimit ( ) ; Relation r = Relation . createSimpleRelation ( db , new Attribute [ ] { foo } ) ; assertEquals ( "" , new SelectStatementBuilder ( r ) . getSQLStatement ( ) ) ; } public void testNoLimitOracle ( ) { DummyDB db = new DummyDB ( Vendor . Oracle ) ; db . setLimit ( ) ; Relation r = Relation . createSimpleRelation ( db , new Attribute [ ] { foo } ) ; assertEquals ( "" , new SelectStatementBuilder ( r ) . getSQLStatement ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . sql ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; public class HSQLDBDatatypeTest extends DatatypeTestBase { public void setUp ( ) throws Exception { initDB ( "" , "" , null , null , D2RQTestSuite . DIRECTORY + "" , null ) ; } public void testTinyInt ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testSmallInt ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testInteger ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testBigInt ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } private final static String [ ] NUMERIC_VALUES = { "" , "" , "" , "" } ; public void testNumeric ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( NUMERIC_VALUES ) ; } public void testDecimal ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( NUMERIC_VALUES ) ; } public void testDecimal_4_2 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" } ) ; } private final static String [ ] DOUBLE_VALUES = { "" , "" , "" , "" , "" , "" , "" } ; public void testDouble ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( DOUBLE_VALUES ) ; } public void testReal ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( DOUBLE_VALUES ) ; } public void testFloat ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( DOUBLE_VALUES ) ; } public void testBoolean ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" } ) ; } public void testChar_3 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testChar ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } private final static String [ ] VARCHAR_VALUES = { "" , "" , "" , "" } ; public void testVarchar ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testLongvarchar ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testCLOB ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testBinary_4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testBinary ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } private final static String [ ] VARBINARY_VALUES = { "" , "" , "" , "" } ; public void testVarBinary ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARBINARY_VALUES ) ; } public void testLongVarBinary ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARBINARY_VALUES ) ; } public void testBLOB ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testBit_4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testBit ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" } ) ; } public void testBitVarying ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testDate ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testTime ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testTime_4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testTimeTZ ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" , "" } ) ; } public void testTimeTZ_4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" , "" } ) ; } public void testTimestamp ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testTimestamp_4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testTimestampTZ ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" , "" } ) ; } public void testTimestampTZ_4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" , "" } ) ; } public void testIntervalDay ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } , false ) ; assertValuesNotFindable ( new String [ ] { "" , "" , "" , "" } ) ; } public void testIntervalHourMinute ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" } , false ) ; assertValuesNotFindable ( new String [ ] { "" , "" , "" , "" , "" } ) ; } public void testOther ( ) { try { createMapping ( "" ) ; fail ( "" ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . DATATYPE_UNMAPPABLE , ex . errorCode ( ) ) ; } } public void testArrayInteger ( ) { try { createMapping ( "" ) ; fail ( "" ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . DATATYPE_UNMAPPABLE , ex . errorCode ( ) ) ; } } } package de . fuberlin . wiwiss . d2rq . sql ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; public class MySQLDatatypeTest extends DatatypeTestBase { public void setUp ( ) throws Exception { initDB ( "" , "" , "" , null , D2RQTestSuite . DIRECTORY + "" , null ) ; } public void testSerial ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testBit_4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testBit ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" } ) ; } public void testTinyInt ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testTinyInt1 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testTinyIntUnsigned ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testSmallInt ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testSmallIntUnsigned ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testMediumInt ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testMediumIntUnsigned ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testInteger ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testIntegerUnsigned ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testInt ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testIntUnsigned ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testBigInt ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" } ) ; } public void testBigIntUnsigned ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } private final static String [ ] DECIMAL_VALUE = { "" , "" , "" , "" } ; public void testDecimal ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( DECIMAL_VALUE ) ; } public void testDecimal_4_2 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" } ) ; } public void testDec ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( DECIMAL_VALUE ) ; } public void testDec_4_2 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" } ) ; } private final static String [ ] FLOAT_VALUES = { "" , "" , "" , "" , "" , "" , "" } ; public void testFloat ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( FLOAT_VALUES , false ) ; } private final static String [ ] DOUBLE_VALUES = { "" , "" , "" , "" , "" , "" , "" } ; public void testDouble ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( DOUBLE_VALUES , false ) ; } public void testReal ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( DOUBLE_VALUES , false ) ; } public void testDoublePrecision ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( DOUBLE_VALUES , false ) ; } public void testChar_3 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } private final static String [ ] CHAR_VALUES = { "" , "" , "" } ; public void testChar ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( CHAR_VALUES ) ; } public void testCharacter ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( CHAR_VALUES ) ; } public void testNationalCharacter ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( CHAR_VALUES ) ; } public void testNChar ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( CHAR_VALUES ) ; } private final static String [ ] VARCHAR_VALUES = { "" , "" , "" , "" } ; public void testVarchar ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testNVarchar ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testNationalVarchar ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testTinyText ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testMediumText ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testText ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testLongText ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARCHAR_VALUES ) ; } public void testBinary_4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testBinary ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } private final static String [ ] VARBINARY_VALUES = { "" , "" , "" , "" } ; public void testVarBinary ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARBINARY_VALUES ) ; } public void testTinyBLOB ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARBINARY_VALUES ) ; } public void testMediumBLOB ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARBINARY_VALUES ) ; } public void testBLOB ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARBINARY_VALUES ) ; } public void testLongBLOB ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( VARBINARY_VALUES ) ; } public void testDate ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" } ) ; } public void testDateTime ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" } ) ; } public void testTimestamp ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testTime ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testYear ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testYear4 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testYear2 ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" } ) ; } public void testEnum ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" } ) ; } public void testSet ( ) { createMapping ( "" ) ; assertMappedType ( "" ) ; assertValues ( new String [ ] { "" , "" , "" , "" , "" } ) ; } } package de . fuberlin . wiwiss . d2rq . sql ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( SQLBuildingTest . class ) ; suite . addTestSuite ( ResultRowTest . class ) ; suite . addTestSuite ( SQLSyntaxTest . class ) ; suite . addTestSuite ( HSQLDBDatatypeTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . sql ; import java . util . HashMap ; import java . util . Map ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType . GenericType ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class DummyDB extends ConnectedDB { private final Vendor vendor ; private int limit = Database . NO_LIMIT ; private Map < Attribute , Boolean > nullability = new HashMap < Attribute , Boolean > ( ) ; public DummyDB ( ) { this ( Vendor . SQL92 ) ; } public DummyDB ( final Vendor vendor ) { super ( null , null , null ) ; this . vendor = vendor ; } public DummyDB ( Map < String , GenericType > overrideColumnTypes ) { super ( null , null , null , overrideColumnTypes , Database . NO_LIMIT , Database . NO_FETCH_SIZE , null ) ; this . vendor = Vendor . SQL92 ; } public void setLimit ( int newLimit ) { limit = newLimit ; } public void setNullable ( Attribute column , boolean flag ) { nullability . put ( column , flag ) ; } @ Override public Vendor vendor ( ) { return vendor ; } @ Override public int limit ( ) { return limit ; } @ Override public boolean isNullable ( Attribute column ) { if ( ! nullability . containsKey ( column ) ) return true ; return nullability . get ( column ) ; } public boolean equals ( Object other ) { return other instanceof DummyDB ; } } package de . fuberlin . wiwiss . d2rq . sql ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamerMap ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; public class SQLSyntaxTest extends TestCase { private final static Attribute foo_col1 = new Attribute ( null , "" , "" ) ; private final static Attribute foo_col2 = new Attribute ( null , "" , "" ) ; private final static Attribute bar_col1 = new Attribute ( null , "" , "" ) ; private final static Attribute bar_col2 = new Attribute ( null , "" , "" ) ; private final static Attribute baz_col1 = new Attribute ( null , "" , "" ) ; private final static Alias fooAsBar = new Alias ( new RelationName ( null , "" ) , new RelationName ( null , "" ) ) ; public void testParseRelationNameNoSchema ( ) { RelationName r = SQL . parseRelationName ( "" ) ; assertEquals ( "" , r . tableName ( ) ) ; assertNull ( r . schemaName ( ) ) ; } public void testParseRelationNameWithSchema ( ) { RelationName r = SQL . parseRelationName ( "" ) ; assertEquals ( "" , r . tableName ( ) ) ; assertEquals ( "" , r . schemaName ( ) ) ; } public void testParseInvalidRelationName ( ) { try { SQL . parseRelationName ( "" ) ; fail ( ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . SQL_INVALID_RELATIONNAME , ex . errorCode ( ) ) ; } } public void testParseInvalidAttributeName ( ) { try { SQL . parseAttribute ( "" ) ; fail ( "" ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . SQL_INVALID_ATTRIBUTENAME , ex . errorCode ( ) ) ; } } public void testFindColumnInEmptyExpression ( ) { assertEquals ( Collections . EMPTY_SET , SQL . findColumnsInExpression ( "" ) ) ; } public void testNumbersInExpressionsAreNotColumns ( ) { assertEquals ( Collections . EMPTY_SET , SQL . findColumnsInExpression ( "" ) ) ; } public void testFindColumnInColumnName ( ) { assertEquals ( Collections . singleton ( foo_col1 ) , SQL . findColumnsInExpression ( "" ) ) ; } public void testFindColumnsInExpression ( ) { assertEquals ( new HashSet < Attribute > ( Arrays . asList ( new Attribute [ ] { foo_col1 , bar_col2 } ) ) , SQL . findColumnsInExpression ( "" ) ) ; } public void testFindColumnsInExpression2 ( ) { assertEquals ( new HashSet < Attribute > ( Arrays . asList ( new Attribute [ ] { foo_col1 , foo_col2 } ) ) , SQL . findColumnsInExpression ( "" ) ) ; } public void testFindColumnsInExpressionWithSchema ( ) { assertEquals ( new HashSet < Attribute > ( Arrays . asList ( new Attribute [ ] { new Attribute ( "" , "" , "" ) , new Attribute ( "" , "" , "" ) } ) ) , SQL . findColumnsInExpression ( "" ) ) ; } public void testFindColumnsInExpressionWithStrings ( ) { assertEquals ( new HashSet < Attribute > ( Arrays . asList ( new Attribute [ ] { foo_col1 , foo_col2 , bar_col1 } ) ) , SQL . findColumnsInExpression ( "" ) ) ; } public void testFindColumnsInExpressionWithStrings2 ( ) { assertEquals ( new HashSet < Attribute > ( Arrays . asList ( new Attribute [ ] { foo_col1 } ) ) , SQL . findColumnsInExpression ( "" ) ) ; } public void testReplaceColumnsInExpressionWithAliasMap ( ) { Alias alias = new Alias ( new RelationName ( null , "" ) , new RelationName ( null , "" ) ) ; AliasMap fooAsBar = new AliasMap ( Collections . singleton ( alias ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , fooAsBar ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , fooAsBar ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , fooAsBar ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , fooAsBar ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , fooAsBar ) ) ; } public void testReplaceColumnsWithSchemaInExpressionWithAliasMap ( ) { Alias alias = new Alias ( new RelationName ( "" , "" ) , new RelationName ( "" , "" ) ) ; AliasMap fooAsBar = new AliasMap ( Collections . singleton ( alias ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , fooAsBar ) ) ; } public void testReplaceColumnsInExpressionWithColumnReplacer ( ) { Map < Attribute , Attribute > map = new HashMap < Attribute , Attribute > ( ) ; map . put ( foo_col1 , bar_col2 ) ; ColumnRenamerMap col1ToCol2 = new ColumnRenamerMap ( map ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , col1ToCol2 ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , col1ToCol2 ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , col1ToCol2 ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , col1ToCol2 ) ) ; assertEquals ( "" , SQL . replaceColumnsInExpression ( "" , col1ToCol2 ) ) ; } public void testParseAliasIsCaseInsensitive ( ) { assertEquals ( fooAsBar , SQL . parseAlias ( "" ) ) ; assertEquals ( fooAsBar , SQL . parseAlias ( "" ) ) ; } public void testParseAlias ( ) { assertEquals ( new Alias ( new RelationName ( null , "" ) , new RelationName ( "" , "" ) ) , SQL . parseAlias ( "" ) ) ; } public void testParseInvalidAlias ( ) { try { SQL . parseAlias ( "" ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . SQL_INVALID_ALIAS , ex . errorCode ( ) ) ; } } public void testParseInvalidJoin ( ) { try { SQL . parseJoins ( Collections . singleton ( "" ) ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . SQL_INVALID_JOIN , ex . errorCode ( ) ) ; } } public void testParseJoinOneCondition ( ) { Set < Join > joins = SQL . parseJoins ( Collections . singleton ( "" ) ) ; assertEquals ( , joins . size ( ) ) ; Join join = ( Join ) joins . iterator ( ) . next ( ) ; assertEquals ( Collections . singletonList ( bar_col2 ) , join . attributes1 ( ) ) ; assertEquals ( Collections . singletonList ( foo_col1 ) , join . attributes2 ( ) ) ; } public void testParseJoinTwoConditionsOnSameTables ( ) { Set < Join > joins = SQL . parseJoins ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; assertEquals ( , joins . size ( ) ) ; Join join = ( Join ) joins . iterator ( ) . next ( ) ; assertEquals ( Arrays . asList ( new Attribute [ ] { bar_col1 , bar_col2 } ) , join . attributes1 ( ) ) ; assertEquals ( Arrays . asList ( new Attribute [ ] { foo_col1 , foo_col2 } ) , join . attributes2 ( ) ) ; assertEquals ( foo_col1 , join . equalAttribute ( bar_col1 ) ) ; } public void testParseJoinTwoConditionsOnDifferentTables ( ) { Set < Join > joins = SQL . parseJoins ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; assertEquals ( , joins . size ( ) ) ; assertEquals ( new HashSet < Join > ( Arrays . asList ( new Join [ ] { new Join ( bar_col1 , foo_col1 , Join . DIRECTION_LEFT ) , new Join ( baz_col1 , foo_col2 , Join . DIRECTION_RIGHT ) , new Join ( foo_col2 , bar_col1 , Join . DIRECTION_UNDIRECTED ) } ) ) , joins ) ; } } package de . fuberlin . wiwiss . d2rq . parser ; import java . util . Collections ; import java . util . HashSet ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . ResourceFactory ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . helpers . MappingHelper ; import de . fuberlin . wiwiss . d2rq . map . DownloadMap ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . map . TranslationTable ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . values . Translator ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class ParserTest extends TestCase { private final static String TABLE_URI = "" ; private Model model ; protected void setUp ( ) throws Exception { this . model = ModelFactory . createDefaultModel ( ) ; } public void testEmptyTranslationTable ( ) { Resource r = addTranslationTableResource ( ) ; Mapping mapping = new MapParser ( this . model , null ) . parse ( ) ; TranslationTable table = mapping . translationTable ( r ) ; assertNotNull ( table ) ; assertEquals ( , table . size ( ) ) ; } public void testGetSameTranslationTable ( ) { Resource r = addTranslationTableResource ( ) ; addTranslationResource ( r , "" , "" ) ; Mapping mapping = new MapParser ( this . model , null ) . parse ( ) ; TranslationTable table1 = mapping . translationTable ( r ) ; TranslationTable table2 = mapping . translationTable ( r ) ; assertSame ( table1 , table2 ) ; } public void testParseTranslationTable ( ) { Resource r = addTranslationTableResource ( ) ; addTranslationResource ( r , "" , "" ) ; Mapping mapping = new MapParser ( this . model , null ) . parse ( ) ; TranslationTable table = mapping . translationTable ( r ) ; assertEquals ( , table . size ( ) ) ; Translator translator = table . translator ( ) ; assertEquals ( "" , translator . toRDFValue ( "" ) ) ; } public void testParseAlias ( ) { Mapping mapping = MappingHelper . readFromTestFile ( "" ) ; MappingHelper . connectToDummyDBs ( mapping ) ; assertEquals ( , mapping . compiledPropertyBridges ( ) . size ( ) ) ; TripleRelation bridge = ( TripleRelation ) mapping . compiledPropertyBridges ( ) . iterator ( ) . next ( ) ; assertTrue ( bridge . baseRelation ( ) . condition ( ) . isTrue ( ) ) ; AliasMap aliases = bridge . baseRelation ( ) . aliases ( ) ; AliasMap expected = new AliasMap ( Collections . singleton ( SQL . parseAlias ( "" ) ) ) ; assertEquals ( expected , aliases ) ; } public void testParseResourceInsteadOfLiteral ( ) { try { MappingHelper . readFromTestFile ( "" ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . MAPPING_RESOURCE_INSTEADOF_LITERAL , ex . errorCode ( ) ) ; } } public void testParseLiteralInsteadOfResource ( ) { try { MappingHelper . readFromTestFile ( "" ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . MAPPING_LITERAL_INSTEADOF_RESOURCE , ex . errorCode ( ) ) ; } } public void testTranslationTableRDFValueCanBeLiteral ( ) { Mapping m = MappingHelper . readFromTestFile ( "" ) ; TranslationTable tt = m . translationTable ( ResourceFactory . createResource ( "" ) ) ; assertEquals ( "" , tt . translator ( ) . toRDFValue ( "" ) ) ; } public void testTranslationTableRDFValueCanBeURI ( ) { Mapping m = MappingHelper . readFromTestFile ( "" ) ; TranslationTable tt = m . translationTable ( ResourceFactory . createResource ( "" ) ) ; assertEquals ( "" , tt . translator ( ) . toRDFValue ( "" ) ) ; } public void testTypeConflictClassMapAndBridgeIsDetected ( ) { try { MappingHelper . readFromTestFile ( "" ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . MAPPING_TYPECONFLICT , ex . errorCode ( ) ) ; } } public void testGenerateDownloadMap ( ) { Mapping m = MappingHelper . readFromTestFile ( "" ) ; MappingHelper . connectToDummyDBs ( m ) ; Resource name = ResourceFactory . createResource ( "" ) ; assertTrue ( m . downloadMapResources ( ) . contains ( name ) ) ; DownloadMap d = m . downloadMap ( name ) ; assertNotNull ( d ) ; assertEquals ( "" , d . getMediaTypeValueMaker ( ) . makeValue ( new ResultRow ( ) { public String get ( ProjectionSpec column ) { return null ; } } ) ) ; assertEquals ( "" , d . getContentDownloadColumn ( ) . qualifiedName ( ) ) ; assertEquals ( "" , d . nodeMaker ( ) . toString ( ) ) ; assertEquals ( new HashSet < ProjectionSpec > ( ) { { add ( SQL . parseAttribute ( "" ) ) ; add ( SQL . parseAttribute ( "" ) ) ; } } , d . getRelation ( ) . projections ( ) ) ; assertTrue ( d . getRelation ( ) . isUnique ( ) ) ; assertTrue ( d . getRelation ( ) . condition ( ) . isTrue ( ) ) ; assertTrue ( d . getRelation ( ) . joinConditions ( ) . isEmpty ( ) ) ; } private Resource addTranslationTableResource ( ) { return this . model . createResource ( TABLE_URI , D2RQ . TranslationTable ) ; } private Resource addTranslationResource ( Resource table , String dbValue , String rdfValue ) { Resource translation = this . model . createResource ( ) ; translation . addProperty ( D2RQ . databaseValue , dbValue ) ; translation . addProperty ( D2RQ . rdfValue , rdfValue ) ; table . addProperty ( D2RQ . translation , translation ) ; return translation ; } } package de . fuberlin . wiwiss . d2rq . parser ; import junit . framework . TestCase ; public class URITest extends TestCase { public void testAbsoluteHTTPURIIsNotChanged ( ) { assertEquals ( "" , MapParser . absolutizeURI ( "" ) ) ; } public void testAbsoluteFileURIIsNotChanged ( ) { assertEquals ( "" , MapParser . absolutizeURI ( "" ) ) ; } public void testRelativeFileURIIsAbsolutized ( ) { String uri = MapParser . absolutizeURI ( "" ) ; assertTrue ( uri . startsWith ( "" ) ) ; assertTrue ( uri . endsWith ( "" ) ) ; } public void testRootlessFileURIIsAbsolutized ( ) { String uri = MapParser . absolutizeURI ( "" ) ; assertTrue ( uri . startsWith ( "" ) ) ; assertTrue ( uri . endsWith ( "" ) ) ; } } package de . fuberlin . wiwiss . d2rq . parser ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( ParserTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . find ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import junit . framework . TestCase ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . sparql . vocabulary . FOAF ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . RelationImpl ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . find . URIMakerRule . URIMakerRuleChecker ; import de . fuberlin . wiwiss . d2rq . nodes . FixedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . TypedNodeMaker ; import de . fuberlin . wiwiss . d2rq . values . Column ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; public class URIMakerRuleTest extends TestCase { private TripleRelation withURIPatternSubject ; private TripleRelation withURIPatternSubjectAndObject ; private TripleRelation withURIColumnSubject ; private TripleRelation withURIPatternSubjectAndURIColumnObject ; private URIMakerRuleChecker employeeChecker ; private URIMakerRuleChecker foobarChecker ; public void setUp ( ) { Relation base = new RelationImpl ( null , AliasMap . NO_ALIASES , Expression . TRUE , Expression . TRUE , Collections . < Join > emptySet ( ) , Collections . < ProjectionSpec > emptySet ( ) , false , OrderSpec . NONE , Relation . NO_LIMIT , Relation . NO_LIMIT ) ; this . withURIPatternSubject = new TripleRelation ( base , new TypedNodeMaker ( TypedNodeMaker . URI , new Pattern ( "" ) , true ) , new FixedNodeMaker ( RDF . type . asNode ( ) , false ) , new FixedNodeMaker ( FOAF . Person . asNode ( ) , false ) ) ; this . withURIPatternSubjectAndObject = new TripleRelation ( base , new TypedNodeMaker ( TypedNodeMaker . URI , new Pattern ( "" ) , true ) , new FixedNodeMaker ( FOAF . knows . asNode ( ) , false ) , new TypedNodeMaker ( TypedNodeMaker . URI , new Pattern ( "" ) , true ) ) ; this . withURIColumnSubject = new TripleRelation ( base , new TypedNodeMaker ( TypedNodeMaker . URI , new Column ( new Attribute ( null , "" , "" ) ) , false ) , new FixedNodeMaker ( RDF . type . asNode ( ) , false ) , new FixedNodeMaker ( FOAF . Document . asNode ( ) , false ) ) ; this . withURIPatternSubjectAndURIColumnObject = new TripleRelation ( base , new TypedNodeMaker ( TypedNodeMaker . URI , new Pattern ( "" ) , true ) , new FixedNodeMaker ( FOAF . homepage . asNode ( ) , false ) , new TypedNodeMaker ( TypedNodeMaker . URI , new Column ( new Attribute ( null , "" , "" ) ) , false ) ) ; this . employeeChecker = new URIMakerRule ( ) . createRuleChecker ( Node . createURI ( "" ) ) ; this . foobarChecker = new URIMakerRule ( ) . createRuleChecker ( Node . createURI ( "" ) ) ; } public void testComparator ( ) { URIMakerRule u = new URIMakerRule ( ) ; assertEquals ( , u . compare ( this . withURIPatternSubject , this . withURIPatternSubject ) ) ; assertEquals ( , u . compare ( this . withURIPatternSubject , this . withURIPatternSubjectAndObject ) ) ; assertEquals ( - , u . compare ( this . withURIPatternSubject , this . withURIColumnSubject ) ) ; assertEquals ( - , u . compare ( this . withURIPatternSubject , this . withURIPatternSubjectAndURIColumnObject ) ) ; assertEquals ( - , u . compare ( this . withURIPatternSubjectAndObject , this . withURIPatternSubject ) ) ; assertEquals ( , u . compare ( this . withURIPatternSubjectAndObject , this . withURIPatternSubjectAndObject ) ) ; assertEquals ( - , u . compare ( this . withURIPatternSubjectAndObject , this . withURIColumnSubject ) ) ; assertEquals ( - , u . compare ( this . withURIPatternSubjectAndObject , this . withURIPatternSubjectAndURIColumnObject ) ) ; assertEquals ( , u . compare ( this . withURIColumnSubject , this . withURIPatternSubject ) ) ; assertEquals ( , u . compare ( this . withURIColumnSubject , this . withURIPatternSubjectAndObject ) ) ; assertEquals ( , u . compare ( this . withURIColumnSubject , this . withURIColumnSubject ) ) ; assertEquals ( , u . compare ( this . withURIColumnSubject , this . withURIPatternSubjectAndURIColumnObject ) ) ; assertEquals ( , u . compare ( this . withURIPatternSubjectAndURIColumnObject , this . withURIPatternSubject ) ) ; assertEquals ( , u . compare ( this . withURIPatternSubjectAndURIColumnObject , this . withURIPatternSubjectAndObject ) ) ; assertEquals ( - , u . compare ( this . withURIPatternSubjectAndURIColumnObject , this . withURIColumnSubject ) ) ; assertEquals ( , u . compare ( this . withURIPatternSubjectAndURIColumnObject , this . withURIPatternSubjectAndURIColumnObject ) ) ; } public void testSort ( ) { Collection < TripleRelation > unsorted = new ArrayList < TripleRelation > ( Arrays . asList ( new TripleRelation [ ] { this . withURIColumnSubject , this . withURIPatternSubject , this . withURIPatternSubjectAndObject , this . withURIPatternSubjectAndURIColumnObject } ) ) ; Collection < TripleRelation > sorted = new ArrayList < TripleRelation > ( Arrays . asList ( new TripleRelation [ ] { this . withURIPatternSubjectAndObject , this . withURIPatternSubject , this . withURIPatternSubjectAndURIColumnObject , this . withURIColumnSubject } ) ) ; assertEquals ( sorted , new URIMakerRule ( ) . sortRDFRelations ( unsorted ) ) ; } public void testRuleCheckerStartsAccepting ( ) { assertTrue ( this . employeeChecker . canMatch ( this . withURIColumnSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ) ; assertTrue ( this . employeeChecker . canMatch ( this . withURIPatternSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ) ; } public void testRuleCheckerUnaffectedByNonURIPattern ( ) { this . employeeChecker . addPotentialMatch ( this . withURIColumnSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ; assertTrue ( this . employeeChecker . canMatch ( this . withURIColumnSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ) ; assertTrue ( this . employeeChecker . canMatch ( this . withURIPatternSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ) ; } public void testRuleCheckerRejectsAfterMatch ( ) { this . employeeChecker . addPotentialMatch ( this . withURIPatternSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ; assertFalse ( this . employeeChecker . canMatch ( this . withURIColumnSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ) ; assertTrue ( this . employeeChecker . canMatch ( this . withURIPatternSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ) ; } public void testRuleCheckerDoesNotRejectAfterNonMatch ( ) { this . foobarChecker . addPotentialMatch ( this . withURIPatternSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ; assertTrue ( this . foobarChecker . canMatch ( this . withURIColumnSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ) ; assertTrue ( this . foobarChecker . canMatch ( this . withURIPatternSubject . nodeMaker ( TripleRelation . SUBJECT ) ) ) ; } } package de . fuberlin . wiwiss . d2rq . find ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( URIMakerRuleTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . csv ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TranslationTableParserTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . csv ; import java . io . StringReader ; import java . util . Collection ; import java . util . HashSet ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; import de . fuberlin . wiwiss . d2rq . map . TranslationTable . Translation ; public class TranslationTableParserTest extends TestCase { private Collection < Translation > simpleTranslations ; public void setUp ( ) { this . simpleTranslations = new HashSet < Translation > ( ) ; this . simpleTranslations . add ( new Translation ( "" , "" ) ) ; this . simpleTranslations . add ( new Translation ( "" , "" ) ) ; } public void testEmpty ( ) { Collection < Translation > translations = new TranslationTableParser ( new StringReader ( "" ) ) . parseTranslations ( ) ; assertTrue ( translations . isEmpty ( ) ) ; } public void testSimple ( ) { String csv = "" ; Collection < Translation > translations = new TranslationTableParser ( new StringReader ( csv ) ) . parseTranslations ( ) ; assertEquals ( , translations . size ( ) ) ; Translation t = ( Translation ) translations . iterator ( ) . next ( ) ; assertEquals ( "" , t . dbValue ( ) ) ; assertEquals ( "" , t . rdfValue ( ) ) ; } public void testTwoRows ( ) { String csv = "" ; Collection < Translation > translations = new TranslationTableParser ( new StringReader ( csv ) ) . parseTranslations ( ) ; assertEquals ( , translations . size ( ) ) ; assertEquals ( this . simpleTranslations , new HashSet < Translation > ( translations ) ) ; } public void testParseFromFile ( ) { Collection < Translation > translations = new TranslationTableParser ( D2RQTestSuite . DIRECTORY + "" ) . parseTranslations ( ) ; assertEquals ( this . simpleTranslations , new HashSet < Translation > ( translations ) ) ; } public void testParseFromFileWithProtocol ( ) { Collection < Translation > translations = new TranslationTableParser ( D2RQTestSuite . DIRECTORY_URL + "" ) . parseTranslations ( ) ; assertEquals ( this . simpleTranslations , new HashSet < Translation > ( translations ) ) ; } } package de . fuberlin . wiwiss . d2rq ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( JenaAPITest . class ) ; suite . addTestSuite ( DBConnectionTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . helpers ; import java . util . ArrayList ; import junit . framework . TestCase ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . dbschema . DatabaseSchemaInspector ; import de . fuberlin . wiwiss . d2rq . jena . GraphD2RQ ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . mapgen . MappingGenerator ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class HSQLSimpleTest extends TestCase { private final static String EX = "" ; { ConnectedDB . registerJDBCDriver ( "" ) ; } private HSQLDatabase db ; public void setUp ( ) { db = new HSQLDatabase ( "" ) ; db . executeSQL ( "" ) ; } public void tearDown ( ) { db . close ( true ) ; } public void testFindTableWithSchemaInspector ( ) { DatabaseSchemaInspector schema = new DatabaseSchemaInspector ( new ConnectedDB ( db . getJdbcURL ( ) , db . getUser ( ) , db . getPassword ( ) ) ) ; assertEquals ( new ArrayList < RelationName > ( ) { { add ( new RelationName ( null , "" ) ) ; } } , schema . listTableNames ( null ) ) ; } public void testGenerateDefaultMappingModel ( ) { Model model = generateDefaultMappingModel ( ) ; assertFalse ( model . isEmpty ( ) ) ; } public void testGenerateSomeClassMapsInDefaultMapping ( ) { Mapping mapping = generateDefaultMapping ( ) ; assertEquals ( , mapping . classMapResources ( ) . size ( ) ) ; } public void testDefaultMappingWithHelloWorld ( ) { db . executeSQL ( "" ) ; GraphD2RQ g = generateDefaultGraphD2RQ ( ) ; assertTrue ( g . contains ( Node . ANY , Node . ANY , Node . createLiteral ( "" ) ) ) ; } public void testGenerateEmptyGraphFromSimpleD2RQMapping ( ) { Mapping m = MappingHelper . readFromTestFile ( "" ) ; m . configuration ( ) . setServeVocabulary ( false ) ; GraphD2RQ g = new GraphD2RQ ( m ) ; assertTrue ( g . isEmpty ( ) ) ; } public void testGenerateTripleFromSimpleD2RQMapping ( ) { Mapping m = MappingHelper . readFromTestFile ( "" ) ; m . configuration ( ) . setServeVocabulary ( false ) ; db . executeSQL ( "" ) ; GraphD2RQ g = new GraphD2RQ ( m ) ; assertTrue ( g . contains ( Node . createURI ( EX + "" ) , RDF . Nodes . type , Node . createURI ( EX + "" ) ) ) ; assertEquals ( , g . size ( ) ) ; } private Model generateDefaultMappingModel ( ) { ConnectedDB cdb = new ConnectedDB ( db . getJdbcURL ( ) , db . getUser ( ) , null ) ; MappingGenerator generator = new MappingGenerator ( cdb ) ; return generator . mappingModel ( EX ) ; } private Mapping generateDefaultMapping ( ) { return new MapParser ( generateDefaultMappingModel ( ) , EX ) . parse ( ) ; } private GraphD2RQ generateDefaultGraphD2RQ ( ) { return new GraphD2RQ ( generateDefaultMapping ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . helpers ; import java . util . Arrays ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import junit . framework . TestCase ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import com . hp . hpl . jena . query . Query ; import com . hp . hpl . jena . query . QueryExecution ; import com . hp . hpl . jena . query . QueryExecutionFactory ; import com . hp . hpl . jena . query . QueryFactory ; import com . hp . hpl . jena . query . QuerySolution ; import com . hp . hpl . jena . query . ResultSet ; import com . hp . hpl . jena . rdf . model . RDFNode ; import com . hp . hpl . jena . sparql . vocabulary . FOAF ; import com . hp . hpl . jena . vocabulary . DC ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; import de . fuberlin . wiwiss . d2rq . sql . BeanCounter ; import de . fuberlin . wiwiss . d2rq . vocab . ISWC ; import de . fuberlin . wiwiss . d2rq . vocab . SKOS ; public abstract class QueryLanguageTestFramework extends TestCase { protected ModelD2RQ model ; protected Set < Map < String , RDFNode > > results ; protected String queryString ; protected Map < String , RDFNode > currentSolution = new HashMap < String , RDFNode > ( ) ; int nTimes = ; BeanCounter startInst ; boolean compareQueryHandlers = false ; int configs ; BeanCounter diffInfo [ ] ; Set < Map < String , RDFNode > > resultMaps [ ] ; String printed [ ] ; String handlerDescription [ ] ; boolean usingD2RQ [ ] ; boolean verbatim [ ] ; @ SuppressWarnings ( "" ) protected void setUpHandlers ( ) { configs = ; diffInfo = new BeanCounter [ configs ] ; resultMaps = new HashSet [ configs ] ; printed = new String [ configs ] ; handlerDescription = new String [ ] { "" , "" } ; usingD2RQ = new boolean [ ] { false , true } ; verbatim = new boolean [ ] { false , true } ; } private final static String pckg = "" ; protected static Logger bigStringInResultLogger = Logger . getLogger ( pckg + "" ) ; protected Logger dumpLogger = Logger . getLogger ( pckg + "" ) ; protected Logger usingLogger = Logger . getLogger ( pckg + "" ) ; protected Logger testCaseSeparatorLogger = Logger . getLogger ( pckg + "" ) ; protected Logger performanceLogger = Logger . getLogger ( pckg + "" ) ; protected Logger queryLogger = Logger . getLogger ( pckg + "" ) ; protected Logger differentLogger = Logger . getLogger ( pckg + "" ) ; protected Logger differenceLogger = Logger . getLogger ( pckg + "" ) ; protected Logger sqlResultSetLogger = Logger . getLogger ( pckg + "" ) ; protected Logger oldSQLResultSetLogger ; protected Logger oldSQLResultSetSeparatorLogger ; public QueryLanguageTestFramework ( ) { super ( ) ; setUpHandlers ( ) ; } protected void setUpShowPerformance ( ) { nTimes = ; compareQueryHandlers = true ; queryLogger . setLevel ( Level . DEBUG ) ; queryLogger . setLevel ( Level . DEBUG ) ; performanceLogger . setLevel ( Level . DEBUG ) ; } protected void setUpMixOutputs ( boolean v ) { compareQueryHandlers = v ; usingLogger . setLevel ( v ? Level . DEBUG : Level . INFO ) ; testCaseSeparatorLogger . setLevel ( v ? Level . DEBUG : Level . INFO ) ; } protected void setUpShowStatements ( ) { queryLogger . setLevel ( Level . DEBUG ) ; sqlResultSetLogger . setLevel ( Level . DEBUG ) ; } protected void setUpShowErrors ( ) { differentLogger . setLevel ( Level . DEBUG ) ; differenceLogger . setLevel ( Level . DEBUG ) ; } protected void setUpShowWarnings ( ) { bigStringInResultLogger . setLevel ( Level . DEBUG ) ; } protected void setUpShowAll ( ) { setUpMixOutputs ( true ) ; verbatim [ ] = true ; setUpShowPerformance ( ) ; setUpShowStatements ( ) ; setUpShowErrors ( ) ; setUpShowWarnings ( ) ; } protected abstract String mapURL ( ) ; protected void setUp ( ) throws Exception { this . model = new ModelD2RQ ( mapURL ( ) , "" , "" ) ; setUpShowErrors ( ) ; } protected void tearDown ( ) throws Exception { this . model . close ( ) ; this . results = null ; super . tearDown ( ) ; } public void runTest ( ) throws Throwable { testCaseSeparatorLogger . debug ( "" ) ; if ( ! compareQueryHandlers ) { super . runTest ( ) ; return ; } Level oldQueryLoggerState = queryLogger . getLevel ( ) ; Level oldSqlResultSetLoggerState = sqlResultSetLogger . getLevel ( ) ; try { for ( int i = ; i < configs ; i ++ ) { queryLogger . setLevel ( verbatim [ i ] ? oldQueryLoggerState : Level . INFO ) ; sqlResultSetLogger . setLevel ( verbatim [ i ] ? oldSqlResultSetLoggerState : Level . INFO ) ; usingLogger . debug ( "" + handlerDescription [ i ] + "" ) ; startInst = BeanCounter . instance ( ) ; for ( int j = ; j < nTimes ; j ++ ) { if ( j > ) { queryLogger . setLevel ( Level . INFO ) ; sqlResultSetLogger . setLevel ( Level . INFO ) ; } super . runTest ( ) ; } diffInfo [ i ] = BeanCounter . instanceMinus ( startInst ) ; diffInfo [ i ] . div ( nTimes ) ; resultMaps [ i ] = results ; } performanceLogger . debug ( handlerDescription [ ] + "" + handlerDescription [ ] + "" + diffInfo [ ] . sqlPerformanceString ( ) + "" + diffInfo [ ] . sqlPerformanceString ( ) + "" ) ; if ( ! resultMaps [ ] . equals ( resultMaps [ ] ) ) { differentLogger . debug ( handlerDescription [ ] + "" + handlerDescription [ ] + "" + resultMaps [ ] . size ( ) + "" + resultMaps [ ] . size ( ) + "" ) ; differenceLogger . debug ( "" + queryString ) ; printed [ ] = printObject ( resultMaps [ ] ) ; printed [ ] = printObject ( resultMaps [ ] ) ; if ( printed [ ] . equals ( printed [ ] ) ) { differentLogger . debug ( "" ) ; } else { differenceLogger . debug ( "" ) ; differenceLogger . debug ( printed [ ] ) ; differenceLogger . debug ( "" ) ; differenceLogger . debug ( "" ) ; differenceLogger . debug ( printed [ ] ) ; } } assertEquals ( resultMaps [ ] , resultMaps [ ] ) ; } catch ( Exception e ) { throw e ; } finally { queryLogger . setLevel ( oldQueryLoggerState ) ; sqlResultSetLogger . setLevel ( oldSqlResultSetLoggerState ) ; } } private String printObject ( Object obj ) { if ( obj instanceof Collection ) { return printCollection ( ( Collection < ? > ) obj ) ; } if ( obj instanceof Map ) { return printMap ( ( Map < ? , ? > ) obj ) ; } else { return obj . toString ( ) ; } } private String printArray ( String [ ] a ) { StringBuffer b = new StringBuffer ( "" ) ; for ( int i = ; i < a . length ; i ++ ) { if ( i > ) b . append ( "" ) ; b . append ( a [ i ] ) ; } b . append ( "" ) ; return b . toString ( ) ; } private String printCollection ( Collection < ? > c ) { String a [ ] = new String [ c . size ( ) ] ; Iterator < ? > it = c . iterator ( ) ; int i = ; while ( it . hasNext ( ) ) { Object obj = it . next ( ) ; a [ i ] = printObject ( obj ) ; i ++ ; } Arrays . sort ( a ) ; return printArray ( a ) ; } private String printMap ( Map < ? , ? > m ) { String a [ ] = new String [ m . size ( ) ] ; Iterator < ? > it = m . entrySet ( ) . iterator ( ) ; int i = ; while ( it . hasNext ( ) ) { Map . Entry < ? , ? > e = ( Map . Entry < ? , ? > ) it . next ( ) ; a [ i ] = printObject ( e . getKey ( ) ) + "" + printObject ( e . getValue ( ) ) ; i ++ ; } Arrays . sort ( a ) ; return printArray ( a ) ; } protected void sparql ( String sparql ) { queryString = sparql ; sparql = "" + DC . NS + "" + "" + FOAF . NS + "" + "" + SKOS . NS + "" + "" + ISWC . NS + "" + sparql ; Query query = QueryFactory . create ( sparql ) ; QueryExecution qe = QueryExecutionFactory . create ( query , this . model ) ; this . results = new HashSet < Map < String , RDFNode > > ( ) ; ResultSet resultSet = qe . execSelect ( ) ; while ( resultSet . hasNext ( ) ) { QuerySolution solution = resultSet . nextSolution ( ) ; addSolution ( solution ) ; } } private void addSolution ( QuerySolution solution ) { Map < String , RDFNode > map = new HashMap < String , RDFNode > ( ) ; Iterator < String > it = solution . varNames ( ) ; while ( it . hasNext ( ) ) { String variable = it . next ( ) ; RDFNode value = solution . get ( variable ) ; map . put ( variable , value ) ; } this . results . add ( map ) ; } protected void assertResultCount ( int count ) { assertEquals ( count , this . results . size ( ) ) ; } protected void expectVariable ( String variableName , RDFNode value ) { this . currentSolution . put ( variableName , value ) ; } protected void assertSolution ( ) { if ( ! this . results . contains ( this . currentSolution ) ) { fail ( ) ; } this . currentSolution . clear ( ) ; } public static Map < String , RDFNode > solutionToMap ( QuerySolution solution , List < String > variables ) { Map < String , RDFNode > result = new HashMap < String , RDFNode > ( ) ; Iterator < String > it = solution . varNames ( ) ; while ( it . hasNext ( ) ) { String variableName = it . next ( ) ; if ( ! variables . contains ( variableName ) ) { continue ; } RDFNode value = solution . get ( variableName ) ; int size = value . toString ( ) . length ( ) ; if ( size > ) { bigStringInResultLogger . debug ( "" + size + "" + value ) ; } result . put ( variableName , value ) ; } return result ; } protected void dump ( ) { System . out . println ( "" + results . size ( ) + "" ) ; int count = ; for ( Map < String , RDFNode > binding : results ) { System . out . println ( "" + count + "" ) ; for ( String varName : binding . keySet ( ) ) { RDFNode val = binding . get ( varName ) ; System . out . println ( "" + varName + "" + val ) ; } count ++ ; } } } package de . fuberlin . wiwiss . d2rq . helpers ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; import de . fuberlin . wiwiss . d2rq . sql . DummyDB ; public class MappingHelper { public static Mapping readFromTestFile ( String testFileName ) { return new MapParser ( D2RQTestSuite . loadTurtle ( testFileName ) , "" ) . parse ( ) ; } public static void connectToDummyDBs ( Mapping m ) { for ( Database db : m . databases ( ) ) { connectToDummyDB ( db ) ; } } public static void connectToDummyDB ( Database db ) { db . useConnectedDB ( new DummyDB ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . helpers ; import java . io . File ; import java . io . FileNotFoundException ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import de . fuberlin . wiwiss . d2rq . sql . SQLScriptLoader ; public class HSQLDatabase { public final static String HSQL_DRIVER_CLASS = org . hsqldb . jdbcDriver . class . getName ( ) ; private final static String HSQL_USER = "" ; private final static String HSQL_PASS = "" ; private final String jdbcURL ; private final Connection conn ; public HSQLDatabase ( String databaseName ) { jdbcURL = "" + databaseName ; try { Class . forName ( HSQL_DRIVER_CLASS ) ; conn = DriverManager . getConnection ( jdbcURL + "" , HSQL_USER , HSQL_PASS ) ; } catch ( ClassNotFoundException ex ) { throw new RuntimeException ( ex ) ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } } public String getJdbcURL ( ) { return jdbcURL ; } public String getUser ( ) { return HSQL_USER ; } public String getPassword ( ) { return HSQL_PASS ; } public Connection getConnection ( ) { return conn ; } public void executeSQL ( String sql ) { try { Statement stmt = conn . createStatement ( ) ; stmt . execute ( sql ) ; stmt . close ( ) ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } } public void executeScript ( String filename ) { try { SQLScriptLoader . loadFile ( new File ( filename ) , conn ) ; } catch ( FileNotFoundException ex ) { throw new RuntimeException ( ex ) ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } } public PreparedStatement prepareSQL ( String sql ) throws SQLException { return conn . prepareStatement ( sql ) ; } public String selectString ( String sql ) { try { Statement stmt = conn . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( sql ) ; if ( ! rs . next ( ) ) return null ; String result = rs . getString ( ) ; rs . close ( ) ; stmt . close ( ) ; return result ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } } public Object selectObject ( String sql ) { try { Statement stmt = conn . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( sql ) ; if ( ! rs . next ( ) ) return null ; Object result = rs . getObject ( ) ; rs . close ( ) ; stmt . close ( ) ; return result ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } } public byte [ ] selectBytes ( String sql ) { try { Statement stmt = conn . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( sql ) ; if ( ! rs . next ( ) ) return null ; byte [ ] result = rs . getBytes ( ) ; rs . close ( ) ; stmt . close ( ) ; return result ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } } public String selectClassName ( String sql ) { try { Statement stmt = conn . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( sql ) ; if ( ! rs . next ( ) ) return null ; String result = rs . getMetaData ( ) . getColumnClassName ( ) ; rs . close ( ) ; stmt . close ( ) ; return result ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } } public void clear ( ) { executeSQL ( "" ) ; } public void close ( ) { try { conn . close ( ) ; } catch ( SQLException ex ) { } } public void close ( boolean dropAll ) { if ( dropAll ) { clear ( ) ; } close ( ) ; } } package de . fuberlin . wiwiss . d2rq . helpers ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . RDFNode ; import com . hp . hpl . jena . util . iterator . ExtendedIterator ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; import de . fuberlin . wiwiss . d2rq . jena . GraphD2RQ ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; public class FindTestFramework extends TestCase { protected static final Model m = ModelFactory . createDefaultModel ( ) ; private GraphD2RQ graph ; private Set < Triple > resultTriples ; protected void setUp ( ) throws Exception { this . graph = ( GraphD2RQ ) new ModelD2RQ ( D2RQTestSuite . ISWC_MAP , "" , "" ) . getGraph ( ) ; } protected void tearDown ( ) throws Exception { this . graph . close ( ) ; } protected void find ( RDFNode s , RDFNode p , RDFNode o ) { this . resultTriples = new HashSet < Triple > ( ) ; ExtendedIterator < Triple > it = this . graph . find ( toNode ( s ) , toNode ( p ) , toNode ( o ) ) ; while ( it . hasNext ( ) ) { this . resultTriples . add ( it . next ( ) ) ; } } protected RDFNode resource ( String relativeURI ) { return m . createResource ( "" + relativeURI ) ; } protected void dump ( ) { int count = ; for ( Triple t : resultTriples ) { count ++ ; System . out . println ( "" + count + "" + PrettyPrinter . toString ( t , this . graph . getPrefixMapping ( ) ) ) ; } System . out . println ( count + "" ) ; System . out . println ( ) ; } protected void assertStatementCount ( int count ) { assertEquals ( count , this . resultTriples . size ( ) ) ; } protected void assertStatement ( RDFNode s , RDFNode p , RDFNode o ) { assertTrue ( this . resultTriples . contains ( new Triple ( toNode ( s ) , toNode ( p ) , toNode ( o ) ) ) ) ; } protected void assertNoStatement ( RDFNode s , RDFNode p , RDFNode o ) { assertFalse ( this . resultTriples . contains ( new Triple ( toNode ( s ) , toNode ( p ) , toNode ( o ) ) ) ) ; } private Node toNode ( RDFNode n ) { if ( n == null ) { return Node . ANY ; } return n . asNode ( ) ; } } package de . fuberlin . wiwiss . d2rq . helpers ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( AllTests . class . getName ( ) ) ; suite . addTestSuite ( HSQLSimpleTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . pp ; import junit . framework . TestCase ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . datatypes . TypeMapper ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . rdf . model . AnonId ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . shared . PrefixMapping ; import com . hp . hpl . jena . shared . impl . PrefixMappingImpl ; import com . hp . hpl . jena . vocabulary . RDF ; import com . hp . hpl . jena . vocabulary . RDFS ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class PrettyPrinterTest extends TestCase { public void testNodePrettyPrinting ( ) { assertEquals ( "" , PrettyPrinter . toString ( Node . createLiteral ( "" ) ) ) ; assertEquals ( "" , PrettyPrinter . toString ( Node . createLiteral ( "" , "" , null ) ) ) ; assertEquals ( "" + XSDDatatype . XSDint . getURI ( ) + ">" , PrettyPrinter . toString ( Node . createLiteral ( "" , null , XSDDatatype . XSDint ) ) ) ; assertEquals ( "" , PrettyPrinter . toString ( Node . createLiteral ( "" , null , XSDDatatype . XSDint ) , PrefixMapping . Standard ) ) ; assertEquals ( "" , PrettyPrinter . toString ( Node . createAnon ( new AnonId ( "" ) ) ) ) ; assertEquals ( "" , PrettyPrinter . toString ( Node . createURI ( "" ) ) ) ; assertEquals ( "" + RDF . type . getURI ( ) + ">" , PrettyPrinter . toString ( RDF . type . asNode ( ) , new PrefixMappingImpl ( ) ) ) ; assertEquals ( "" , PrettyPrinter . toString ( RDF . type . asNode ( ) , PrefixMapping . Standard ) ) ; assertEquals ( "" , PrettyPrinter . toString ( Node . createVariable ( "" ) ) ) ; assertEquals ( "" , PrettyPrinter . toString ( Node . ANY ) ) ; } public void testTriplePrettyPrinting ( ) { assertEquals ( "" + RDFS . label . getURI ( ) + "" , PrettyPrinter . toString ( new Triple ( Node . createURI ( "" ) , RDFS . label . asNode ( ) , Node . createLiteral ( "" , null , null ) ) ) ) ; } public void testTriplePrettyPrintingWithNodeANY ( ) { assertEquals ( "" , PrettyPrinter . toString ( Triple . ANY ) ) ; } public void testTriplePrettyPrintingWithPrefixMapping ( ) { PrefixMappingImpl prefixes = new PrefixMappingImpl ( ) ; prefixes . setNsPrefixes ( PrefixMapping . Standard ) ; prefixes . setNsPrefix ( "" , "" ) ; assertEquals ( "" , PrettyPrinter . toString ( new Triple ( Node . createURI ( "" ) , RDFS . label . asNode ( ) , Node . createLiteral ( "" , null , null ) ) , prefixes ) ) ; } public void testResourcePrettyPrinting ( ) { Model m = ModelFactory . createDefaultModel ( ) ; assertEquals ( "" , PrettyPrinter . toString ( m . createLiteral ( "" ) ) ) ; assertEquals ( "" , PrettyPrinter . toString ( m . createResource ( "" ) ) ) ; } public void testUsePrefixMappingWhenPrintingURIResources ( ) { Model m = ModelFactory . createDefaultModel ( ) ; m . setNsPrefix ( "" , "" ) ; assertEquals ( "" , PrettyPrinter . toString ( m . createResource ( "" ) ) ) ; } public void testD2RQTermsHaveD2RQPrefix ( ) { assertEquals ( "" , PrettyPrinter . toString ( D2RQ . ClassMap ) ) ; } public void testSomeRDFDatatypeToString ( ) { RDFDatatype someDatatype = TypeMapper . getInstance ( ) . getSafeTypeByName ( "" ) ; assertEquals ( "" , PrettyPrinter . toString ( someDatatype ) ) ; } public void testXSDTypeToString ( ) { assertEquals ( "" , PrettyPrinter . toString ( XSDDatatype . XSDstring ) ) ; } } package de . fuberlin . wiwiss . d2rq . pp ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( PrettyPrinterTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . d2rq_sdb ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import com . hp . hpl . jena . query . Query ; import com . hp . hpl . jena . query . QueryExecution ; import com . hp . hpl . jena . query . QueryExecutionFactory ; import com . hp . hpl . jena . query . QueryFactory ; import com . hp . hpl . jena . query . ResultSet ; import com . hp . hpl . jena . query . SortCondition ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . sparql . core . Var ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import com . hp . hpl . jena . sparql . engine . binding . BindingComparator ; public class SdbSqlEqualityTest extends LoadDataTest { private static final String QUERY_DIR = "" ; private static final String QUERY_FILE_SUFFIX = "" ; private String [ ] excludedQueriesFileNames = { "" , "" , "" , "" , "" , "" , "" , "" , } ; public SdbSqlEqualityTest ( ) { super ( ) ; } public void testSdbSqlEquality ( ) { ResultSet resultSet ; QueryExecution sdbQueryExecution , d2rqQueryExecution ; List < ? extends Object > sdbDataResult ; List < ? extends Object > hsqlDataResult ; List < SortCondition > sortingConditions ; SortCondition sortCondition ; Var var ; List < Query > queries ; int hsqlResultSize , sdbResultSize ; Object sdbResultEntry , hsqlResultEntry ; boolean entriesEqual ; Model sdbModel , d2rqModel ; try { System . out . println ( "" ) ; queries = loadAllQueries ( ) ; System . out . println ( "" + queries . size ( ) + "" + CURR_DIR + "" + QUERY_DIR ) ; for ( Query query : queries ) { System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( query ) ; System . out . println ( "" ) ; sdbQueryExecution = QueryExecutionFactory . create ( query , this . sdbDataModel ) ; System . out . println ( "" ) ; d2rqQueryExecution = QueryExecutionFactory . create ( query , this . hsqlDataModel ) ; if ( query . isSelectType ( ) ) { resultSet = sdbQueryExecution . execSelect ( ) ; sortingConditions = new ArrayList < SortCondition > ( ) ; for ( String varName : resultSet . getResultVars ( ) ) { var = Var . alloc ( varName ) ; sortCondition = new SortCondition ( var , Query . ORDER_DEFAULT ) ; sortingConditions . add ( sortCondition ) ; } List < Binding > sdbSelectResult = new ArrayList < Binding > ( ) ; List < Binding > hsqlSelectResult = new ArrayList < Binding > ( ) ; while ( resultSet . hasNext ( ) ) { sdbSelectResult . add ( resultSet . nextBinding ( ) ) ; } Collections . sort ( sdbSelectResult , new BindingComparator ( sortingConditions ) ) ; resultSet = d2rqQueryExecution . execSelect ( ) ; while ( resultSet . hasNext ( ) ) { hsqlSelectResult . add ( resultSet . nextBinding ( ) ) ; } Collections . sort ( hsqlSelectResult , new BindingComparator ( sortingConditions ) ) ; sdbDataResult = sdbSelectResult ; hsqlDataResult = hsqlSelectResult ; } else if ( query . isConstructType ( ) || query . isDescribeType ( ) ) { if ( query . isConstructType ( ) ) { sdbModel = sdbQueryExecution . execConstruct ( ) ; d2rqModel = d2rqQueryExecution . execConstruct ( ) ; } else { sdbModel = sdbQueryExecution . execDescribe ( ) ; d2rqModel = d2rqQueryExecution . execDescribe ( ) ; } List < Statement > sdbGraphResult = new ArrayList < Statement > ( ) ; List < Statement > hsqlGraphResult = new ArrayList < Statement > ( ) ; for ( StmtIterator iterator = sdbModel . listStatements ( ) ; iterator . hasNext ( ) ; ) { sdbGraphResult . add ( iterator . nextStatement ( ) ) ; } Collections . sort ( sdbGraphResult , new StatementsComparator ( ) ) ; for ( StmtIterator iterator = d2rqModel . listStatements ( ) ; iterator . hasNext ( ) ; ) { hsqlGraphResult . add ( iterator . nextStatement ( ) ) ; } Collections . sort ( hsqlGraphResult , new StatementsComparator ( ) ) ; sdbDataResult = sdbGraphResult ; hsqlDataResult = hsqlGraphResult ; } else if ( query . isAskType ( ) ) { continue ; } else { fail ( "" ) ; continue ; } System . out . println ( "" ) ; sdbResultSize = sdbDataResult . size ( ) ; hsqlResultSize = hsqlDataResult . size ( ) ; System . out . println ( "" + sdbResultSize ) ; System . out . println ( "" + hsqlResultSize ) ; if ( sdbResultSize == hsqlResultSize ) { System . out . println ( "" ) ; } else { fail ( ) ; } System . out . println ( "" ) ; for ( int i = ; i < sdbDataResult . size ( ) ; i ++ ) { sdbResultEntry = sdbDataResult . get ( i ) ; hsqlResultEntry = hsqlDataResult . get ( i ) ; entriesEqual = sdbResultEntry . equals ( hsqlResultEntry ) ; System . out . println ( "" + sdbResultEntry ) ; System . out . println ( "" + hsqlResultEntry ) ; if ( entriesEqual ) { System . out . println ( "" + entriesEqual ) ; } else { fail ( ) ; } } System . out . println ( "" ) ; } System . out . println ( queries . size ( ) + "" ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; fail ( ) ; } } private List < Query > loadAllQueries ( ) throws IOException { File queryDir ; File [ ] files ; List < Query > queries ; queries = new ArrayList < Query > ( ) ; queryDir = new File ( CURR_DIR + "" + QUERY_DIR ) ; files = queryDir . listFiles ( ) ; Arrays . sort ( files ) ; for ( int i = ; i < files . length ; i ++ ) { readRecursiveAndCreateQuery ( files [ i ] , queries ) ; } return queries ; } private void readRecursiveAndCreateQuery ( File file , List < Query > queries ) throws IOException { File [ ] files ; Query query ; BufferedReader queryReader = null ; String fileName ; fileName = file . getName ( ) ; if ( file . isDirectory ( ) ) { files = file . listFiles ( ) ; System . out . println ( "" + fileName + "" + files . length + "" ) ; Arrays . sort ( files ) ; for ( int i = ; i < files . length ; i ++ ) { if ( ! excludeFile ( files [ i ] ) ) { readRecursiveAndCreateQuery ( files [ i ] , queries ) ; } } } else { System . out . println ( "" + fileName ) ; try { if ( ! excludeFile ( file ) ) { queryReader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) ) ) ; query = createQuery ( queryReader ) ; queries . add ( query ) ; } } finally { if ( queryReader != null ) { queryReader . close ( ) ; } } } } private boolean excludeFile ( File file ) { String fileName ; boolean exclude = false ; fileName = file . getName ( ) ; for ( int j = ; j < excludedQueriesFileNames . length ; j ++ ) { if ( fileName . equals ( excludedQueriesFileNames [ j ] ) || ( file . isFile ( ) && ! fileName . toLowerCase ( ) . endsWith ( QUERY_FILE_SUFFIX ) ) ) { exclude = true ; break ; } } return exclude ; } private Query createQuery ( BufferedReader queryReader ) throws IOException { StringBuffer stringBuffer ; String line ; stringBuffer = new StringBuffer ( ) ; while ( ( line = queryReader . readLine ( ) ) != null ) { stringBuffer . append ( line ) ; stringBuffer . append ( "" ) ; } return QueryFactory . create ( stringBuffer . toString ( ) ) ; } private static class StatementsComparator implements Comparator < Statement > { public int compare ( Statement arg0 , Statement arg1 ) { return arg0 . toString ( ) . compareTo ( arg1 . toString ( ) ) ; } } } package de . fuberlin . wiwiss . d2rq . d2rq_sdb ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . zip . ZipEntry ; import java . util . zip . ZipInputStream ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . sdb . SDBFactory ; import com . hp . hpl . jena . sdb . Store ; import com . hp . hpl . jena . sdb . StoreDesc ; import com . hp . hpl . jena . sdb . layout2 . index . StoreTriplesNodesIndexHSQL ; import com . hp . hpl . jena . sdb . sql . JDBC ; import com . hp . hpl . jena . sdb . sql . SDBConnection ; import com . hp . hpl . jena . sdb . store . DatabaseType ; import com . hp . hpl . jena . sdb . store . LayoutType ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; import junit . framework . TestCase ; public abstract class LoadDataTest extends TestCase { private static boolean loadHsqlData = true ; private static boolean loadSDBData = true ; protected static final String CURR_DIR = "" ; private static final String DATA_DIR = "" ; private static final String CONFIG_DIR = "" ; private static final String FILENAME_TTL_DATA = "" ; private static final String FILENAME_SQL_DATA = "" ; private static final String MAPPING_FILE_HSQL = "" ; private static final String SDB_URL = "" ; private static final String SDB_USER = "" ; private static final String SDB_PASS = "" ; protected Model sdbDataModel ; private static final String HSQL_DRIVER_NAME = "" ; private static final String HSQL_URL = "" ; private static final String HSQL_USER = "" ; private static final String HSQL_PASS = "" ; protected Model hsqlDataModel ; public LoadDataTest ( ) { initDatabases ( ) ; } private void initDatabases ( ) { try { if ( loadHsqlData ) { createHsqlDatabase ( ) ; assertNotNull ( "" , hsqlDataModel ) ; } if ( loadSDBData ) { createSemanticDatabase ( ) ; assertNotNull ( "" , sdbDataModel ) ; assertTrue ( "" , sdbDataModel . size ( ) > ) ; } System . out . println ( "" ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; fail ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; fail ( ) ; } } private void createHsqlDatabase ( ) throws IOException , SQLException { Connection hsqlConnection ; File zipFile ; ZipEntry entry ; ZipInputStream zipInputStream = null ; String sqlData ; Statement statement ; try { Class . forName ( HSQL_DRIVER_NAME ) ; } catch ( ClassNotFoundException e ) { throw new SQLException ( e . getMessage ( ) ) ; } hsqlConnection = DriverManager . getConnection ( HSQL_URL , HSQL_USER , HSQL_PASS ) ; zipFile = new File ( CURR_DIR + "" + DATA_DIR + "" + FILENAME_SQL_DATA ) ; zipInputStream = new ZipInputStream ( new FileInputStream ( zipFile ) ) ; if ( zipInputStream != null ) { try { while ( ( entry = zipInputStream . getNextEntry ( ) ) != null ) { System . out . println ( "" + entry . getName ( ) ) ; sqlData = convertStreamToString ( zipInputStream ) ; statement = hsqlConnection . createStatement ( ) ; statement . execute ( sqlData ) ; statement . close ( ) ; } } finally { zipInputStream . close ( ) ; } } hsqlDataModel = new ModelD2RQ ( CURR_DIR + "" + CONFIG_DIR + "" + MAPPING_FILE_HSQL , "" , "" ) ; System . out . println ( "" ) ; } private void createSemanticDatabase ( ) throws IOException { File zipFile ; ZipEntry entry ; ZipInputStream zipInputStream = null ; SDBConnection sdbConnection ; StoreDesc sdbStoreDesc ; Store sdbStore ; JDBC . loadDriverHSQL ( ) ; sdbConnection = SDBFactory . createConnection ( SDB_URL , SDB_USER , SDB_PASS ) ; sdbStoreDesc = new StoreDesc ( LayoutType . LayoutTripleNodesIndex , DatabaseType . HSQLDB ) ; sdbStore = new StoreTriplesNodesIndexHSQL ( sdbConnection , sdbStoreDesc ) ; sdbStore . getTableFormatter ( ) . create ( ) ; sdbDataModel = SDBFactory . connectDefaultModel ( sdbStore ) ; zipFile = new File ( CURR_DIR + "" + DATA_DIR + "" + FILENAME_TTL_DATA ) ; zipInputStream = new ZipInputStream ( new FileInputStream ( zipFile ) ) ; if ( zipInputStream != null ) { entry = zipInputStream . getNextEntry ( ) ; if ( entry != null ) { assertFalse ( "" , "" . equals ( entry . getName ( ) ) ) ; sdbDataModel = sdbDataModel . read ( zipInputStream , null , "" ) ; assertTrue ( "" , sdbDataModel . size ( ) > ) ; } zipInputStream . close ( ) ; } System . out . println ( "" + sdbDataModel . size ( ) + "" ) ; } private String convertStreamToString ( InputStream inputStream ) throws IOException { BufferedReader bufferedReader ; StringBuilder stringBuilder ; String line = null ; bufferedReader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; stringBuilder = new StringBuilder ( ) ; while ( ( line = bufferedReader . readLine ( ) ) != null ) { stringBuilder . append ( line ) ; stringBuilder . append ( "" ) ; } return stringBuilder . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . d2rq_sdb ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static void main ( String [ ] args ) { junit . textui . TestRunner . run ( AllTests . suite ( ) ) ; } public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import junit . framework . Test ; import junit . framework . TestSuite ; public class D2RQTestSuite { public static final String DIRECTORY = "" ; public static final String DIRECTORY_URL = "" + DIRECTORY ; public static final String ISWC_MAP = "" ; public static void main ( String [ ] args ) { Log4jHelper . turnLoggingOff ( ) ; junit . textui . TestRunner . run ( D2RQTestSuite . suite ( ) ) ; } public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . algebra . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . csv . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . dbschema . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . download . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . expr . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . find . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . functional_tests . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . helpers . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . map . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . mapgen . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . nodes . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . parser . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . pp . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . sql . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . values . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . engine . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . d2rq_sdb . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . optimizer . AllTests . suite ( ) ) ; suite . addTest ( de . fuberlin . wiwiss . d2rq . vocab . AllTests . suite ( ) ) ; return suite ; } public static Model loadTurtle ( String fileName ) { Model m = ModelFactory . createDefaultModel ( ) ; m . read ( D2RQTestSuite . DIRECTORY_URL + fileName , "" ) ; return m ; } } package de . fuberlin . wiwiss . d2rq . vocab ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( AllTests . class . getName ( ) ) ; suite . addTestSuite ( VocabularySummarizerTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . vocab ; import java . util . Collection ; import java . util . HashSet ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; public class VocabularySummarizerTest extends TestCase { public void testAllPropertiesEmpty ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( Object . class ) ; assertTrue ( vocab . getAllProperties ( ) . isEmpty ( ) ) ; } public void testAllClassesEmpty ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( Object . class ) ; assertTrue ( vocab . getAllClasses ( ) . isEmpty ( ) ) ; } public void testAllPropertiesContainsProperty ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getAllProperties ( ) . contains ( D2RQ . column ) ) ; assertTrue ( vocab . getAllProperties ( ) . contains ( D2RQ . belongsToClassMap ) ) ; } public void testAllPropertiesDoesNotContainClass ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertFalse ( vocab . getAllProperties ( ) . contains ( D2RQ . Database ) ) ; } public void testAllPropertiesDoesNotContainTermFromOtherNamespace ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertFalse ( vocab . getAllProperties ( ) . contains ( RDF . type ) ) ; } public void testAllClassesContainsClass ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getAllClasses ( ) . contains ( D2RQ . Database ) ) ; } public void testAllClassesDoesNotContainProperty ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertFalse ( vocab . getAllClasses ( ) . contains ( D2RQ . column ) ) ; } public void testAllClassesDoesNotContainTermFromOtherNamespace ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertFalse ( vocab . getAllClasses ( ) . contains ( D2RConfig . Server ) ) ; } public void testGetNamespaceEmpty ( ) { assertNull ( new VocabularySummarizer ( Object . class ) . getNamespace ( ) ) ; } public void testGetNamespaceD2RQ ( ) { assertEquals ( D2RQ . NS , new VocabularySummarizer ( D2RQ . class ) . getNamespace ( ) ) ; } public void testGetNamespaceD2RConfig ( ) { assertEquals ( D2RConfig . NS , new VocabularySummarizer ( D2RConfig . class ) . getNamespace ( ) ) ; } public void testNoUndefinedClassesForEmptyModel ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getUndefinedClasses ( ModelFactory . createDefaultModel ( ) ) . isEmpty ( ) ) ; } public void testNoUndefinedClassesWithoutTypeStatement ( ) { Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getUndefinedClasses ( m ) . isEmpty ( ) ) ; } public void testNoUndefinedClassesIfAllClassesDefined ( ) { Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getUndefinedClasses ( m ) . isEmpty ( ) ) ; } public void testNoUndefinedClassesIfAllInOtherNamespace ( ) { Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getUndefinedClasses ( m ) . isEmpty ( ) ) ; } public void testFindOneUndefinedClass ( ) { final Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; Collection < Resource > expected = new HashSet < Resource > ( ) { { this . add ( m . createResource ( D2RQ . NS + "" ) ) ; } } ; assertEquals ( expected , vocab . getUndefinedClasses ( m ) ) ; } public void testFindTwoUndefinedClasses ( ) { final Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; Collection < Resource > expected = new HashSet < Resource > ( ) { { this . add ( m . createResource ( D2RQ . NS + "" ) ) ; this . add ( m . createResource ( D2RQ . NS + "" ) ) ; } } ; assertEquals ( expected , vocab . getUndefinedClasses ( m ) ) ; } public void testNoUndefinedPropertiesForEmptyModel ( ) { VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getUndefinedProperties ( ModelFactory . createDefaultModel ( ) ) . isEmpty ( ) ) ; } public void testNoUndefinedPropertiesIfAllPropertiesDefined ( ) { Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getUndefinedProperties ( m ) . isEmpty ( ) ) ; } public void testNoUndefinedPropertiesIfAllInOtherNamespace ( ) { Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; assertTrue ( vocab . getUndefinedProperties ( m ) . isEmpty ( ) ) ; } public void testFindOneUndefinedProperty ( ) { final Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; Collection < Property > expected = new HashSet < Property > ( ) { { this . add ( m . createProperty ( D2RQ . NS + "" ) ) ; } } ; assertEquals ( expected , vocab . getUndefinedProperties ( m ) ) ; } public void testFindTwoUndefinedProperties ( ) { final Model m = D2RQTestSuite . loadTurtle ( "" ) ; VocabularySummarizer vocab = new VocabularySummarizer ( D2RQ . class ) ; Collection < Property > expected = new HashSet < Property > ( ) { { this . add ( m . createProperty ( D2RQ . NS + "" ) ) ; this . add ( m . createProperty ( D2RQ . NS + "" ) ) ; } } ; assertEquals ( expected , vocab . getUndefinedProperties ( m ) ) ; } } package de . fuberlin . wiwiss . d2rq . vocab ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . ResourceFactory ; public class Test { public static final String NS = "" ; public static final Resource DummyDatabase = ResourceFactory . createResource ( NS + "" ) ; } package de . fuberlin . wiwiss . d2rq ; import com . hp . hpl . jena . util . FileManager ; import de . fuberlin . wiwiss . d2rq . jena . GraphD2RQ ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; import junit . framework . TestCase ; public class JenaAPITest extends TestCase { public void testCopyPrefixesFromMapModelToD2RQModel ( ) { ModelD2RQ m = new ModelD2RQ ( D2RQTestSuite . DIRECTORY_URL + "" ) ; assertEquals ( "" , m . getNsPrefixURI ( "" ) ) ; } public void testCopyPrefixesFromMapModelToD2RQGraph ( ) { GraphD2RQ g = new ModelD2RQ ( FileManager . get ( ) . loadModel ( D2RQTestSuite . DIRECTORY_URL + "" ) , null ) . getGraph ( ) ; assertEquals ( "" , g . getPrefixMapping ( ) . getNsPrefixURI ( "" ) ) ; } public void testDontCopyD2RQPrefixFromMapModel ( ) { ModelD2RQ m = new ModelD2RQ ( D2RQTestSuite . DIRECTORY_URL + "" ) ; assertNull ( m . getNsPrefixURI ( "" ) ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( FilterParserTest . class ) ; suite . addTestSuite ( IRIEncoderTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; import java . util . List ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . mapgen . Filter . IdentifierMatcher ; import de . fuberlin . wiwiss . d2rq . mapgen . FilterParser . ParseException ; public class FilterParserTest extends TestCase { public void testEmpty ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testSimple ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testMultipleStrings ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testMultipleFilters ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testMultipleFiltersNewline ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testRegex ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testRegexWithFlag ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testMutlipleRegexes ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testMutlipleRegexFilters ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testDotInRegex ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testEscapedDotInRegex ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testCommaInRegex ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testIncompleteRegex ( ) { try { new FilterParser ( "" ) . parse ( ) ; fail ( "" ) ; } catch ( ParseException ex ) { } } public void testIncompleteRegexNewline ( ) { try { new FilterParser ( "" ) . parse ( ) ; fail ( "" ) ; } catch ( ParseException ex ) { } } public void testComplex ( ) throws ParseException { assertEquals ( "" , toString ( new FilterParser ( "" ) . parse ( ) ) ) ; } public void testParseAsSchemaFilter ( ) throws ParseException { Filter result = new FilterParser ( "" ) . parseSchemaFilter ( ) ; assertTrue ( result . matchesSchema ( "" ) ) ; assertTrue ( result . matchesSchema ( "" ) ) ; assertFalse ( result . matchesSchema ( "" ) ) ; assertFalse ( result . matchesSchema ( null ) ) ; } public void testParseAsSchemaFilterWithRegex ( ) throws ParseException { Filter result = new FilterParser ( "" ) . parseSchemaFilter ( ) ; assertTrue ( result . matchesSchema ( "" ) ) ; assertTrue ( result . matchesSchema ( "" ) ) ; assertFalse ( result . matchesSchema ( "" ) ) ; assertFalse ( result . matchesSchema ( null ) ) ; } public void testParseAsSchemaFilterFail ( ) { try { new FilterParser ( "" ) . parseSchemaFilter ( ) ; fail ( "" ) ; } catch ( ParseException ex ) { } } public void testParseAsTableFilter ( ) throws ParseException { Filter result = new FilterParser ( "" ) . parseTableFilter ( false ) ; assertTrue ( result . matchesTable ( "" , "" ) ) ; assertTrue ( result . matchesTable ( "" , "" ) ) ; assertTrue ( result . matchesTable ( null , "" ) ) ; assertFalse ( result . matchesTable ( "" , "" ) ) ; assertFalse ( result . matchesTable ( "" , "" ) ) ; assertFalse ( result . matchesTable ( "" , "" ) ) ; assertFalse ( result . matchesTable ( null , "" ) ) ; assertFalse ( result . matchesTable ( null , "" ) ) ; } public void testTableFilterTooMany ( ) { try { new FilterParser ( "" ) . parseTableFilter ( true ) ; fail ( "" ) ; } catch ( ParseException ex ) { } } public void testParseAsColumnFilter ( ) throws ParseException { Filter result = new FilterParser ( "" ) . parseColumnFilter ( false ) ; assertTrue ( result . matchesColumn ( "" , "" , "" ) ) ; assertTrue ( result . matchesColumn ( null , "" , "" ) ) ; assertTrue ( result . matchesColumn ( null , "" , "" ) ) ; assertFalse ( result . matchesColumn ( null , "" , "" ) ) ; assertFalse ( result . matchesColumn ( "" , "" , "" ) ) ; assertFalse ( result . matchesColumn ( null , "" , "" ) ) ; } private String toString ( List < List < IdentifierMatcher > > filters ) { StringBuilder result = new StringBuilder ( ) ; for ( List < IdentifierMatcher > l : filters ) { for ( IdentifierMatcher m : l ) { result . append ( m . toString ( ) ) ; result . append ( '' ) ; } if ( ! l . isEmpty ( ) ) { result . deleteCharAt ( result . length ( ) - ) ; } result . append ( '' ) ; } if ( ! filters . isEmpty ( ) ) { result . deleteCharAt ( result . length ( ) - ) ; } return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; import junit . framework . TestCase ; public class IRIEncoderTest extends TestCase { public void testDontEncodeAlphanumeric ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } public void testDontEncodeSafePunctuation ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } public void testDontEncodeUnicodeChars ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } public void testEncodeGenDelims ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } public void testEncodeSubDelims ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } public void testEncodePercentSign ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } public void testEncodeOtherASCIIChars ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } public void testEncodeASCIIControlChars ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } public void testEncodeUnicodeControlChars ( ) { assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; assertEquals ( "" , IRIEncoder . encode ( "" ) ) ; } } package de . fuberlin . wiwiss . d2rq . optimizer ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import junit . framework . TestCase ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . sparql . core . Var ; import com . hp . hpl . jena . sparql . expr . E_Datatype ; import com . hp . hpl . jena . sparql . expr . E_Equals ; import com . hp . hpl . jena . sparql . expr . E_IsBlank ; import com . hp . hpl . jena . sparql . expr . E_IsIRI ; import com . hp . hpl . jena . sparql . expr . E_IsLiteral ; import com . hp . hpl . jena . sparql . expr . E_Lang ; import com . hp . hpl . jena . sparql . expr . E_LangMatches ; import com . hp . hpl . jena . sparql . expr . E_LogicalOr ; import com . hp . hpl . jena . sparql . expr . E_SameTerm ; import com . hp . hpl . jena . sparql . expr . Expr ; import com . hp . hpl . jena . sparql . expr . ExprVar ; import com . hp . hpl . jena . sparql . expr . NodeValue ; import com . hp . hpl . jena . sparql . expr . nodevalue . NodeValueNode ; import com . hp . hpl . jena . vocabulary . RDFS ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . engine . GraphPatternTranslator ; import de . fuberlin . wiwiss . d2rq . engine . MapFixture ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . TypedNodeMaker ; import de . fuberlin . wiwiss . d2rq . optimizer . expr . TransformExprToSQLApplyer ; public class ExprTransformTest2 extends TestCase { NodeRelation search ( String tableName , String attributeName , NodeRelation [ ] relation ) { for ( int i = ; i < relation . length ; i ++ ) { NodeRelation rel = relation [ i ] ; for ( ProjectionSpec p : rel . baseRelation ( ) . projections ( ) ) { Attribute attribute = ( Attribute ) p ; if ( attribute . tableName ( ) . equals ( tableName ) && attribute . attributeName ( ) . equals ( attributeName ) ) return rel ; } } return null ; } public void testLang ( ) { List < Triple > pattern = new ArrayList < Triple > ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , RDFS . label . asNode ( ) , Node . createVariable ( "" ) ) ) ; NodeRelation [ ] rels = translate ( pattern , "" ) ; NodeRelation label_fr_be = search ( "" , "" , rels ) ; NodeRelation label_en = search ( "" , "" , rels ) ; NodeRelation label_noLang = search ( "" , "" , rels ) ; Expr filterFR = new E_Equals ( new E_Lang ( new ExprVar ( "" ) ) , NodeValue . makeString ( "" ) ) ; Expr filterEN_TAG_EN = new E_Equals ( new E_Lang ( new ExprVar ( "" ) ) , NodeValue . makeNode ( "" , "" , ( String ) null ) ) ; Expr filterFR_BE = new E_Equals ( new E_Lang ( new ExprVar ( "" ) ) , NodeValue . makeString ( "" ) ) ; Expr filter = new E_Equals ( new E_Lang ( new ExprVar ( "" ) ) , NodeValue . makeString ( "" ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( filterFR , label_fr_be ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( filterFR , label_en ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterFR_BE , label_fr_be ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( filterEN_TAG_EN , label_en ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filter , label_noLang ) ) ; } public void testLangMatches ( ) { List < Triple > pattern = new ArrayList < Triple > ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , RDFS . label . asNode ( ) , Node . createVariable ( "" ) ) ) ; NodeRelation [ ] rels = translate ( pattern , "" ) ; NodeRelation label_fr_be = search ( "" , "" , rels ) ; NodeRelation label_en = search ( "" , "" , rels ) ; NodeRelation label = search ( "" , "" , rels ) ; Expr filterFR = new E_LangMatches ( new E_Lang ( new ExprVar ( "" ) ) , NodeValue . makeString ( "" ) ) ; Expr filterEN = new E_LangMatches ( new E_Lang ( new ExprVar ( "" ) ) , NodeValue . makeString ( "" ) ) ; Expr filterFR_BE = new E_LangMatches ( new E_Lang ( new ExprVar ( "" ) ) , NodeValue . makeString ( "" ) ) ; Expr filterALL = new E_LangMatches ( new E_Lang ( new ExprVar ( "" ) ) , NodeValue . makeString ( "" ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterFR , label_fr_be ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( filterFR , label_en ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterEN , label_en ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterFR_BE , label_fr_be ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( filterEN , label ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterALL , label_fr_be ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterALL , label_en ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( filterALL , label ) ) ; } public void testIsLiteral ( ) { List < Triple > pattern = new ArrayList < Triple > ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , RDFS . label . asNode ( ) , Node . createVariable ( "" ) ) ) ; NodeRelation [ ] rels = translate ( pattern , "" ) ; NodeRelation label = search ( "" , "" , rels ) ; NodeRelation label_en = search ( "" , "" , rels ) ; pattern . clear ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , Node . createURI ( "" ) , Node . createVariable ( "" ) ) ) ; rels = translate ( pattern , "" ) ; NodeRelation intvalue = search ( "" , "" , rels ) ; Expr subject = new E_IsLiteral ( new ExprVar ( "" ) ) ; Expr object = new E_IsLiteral ( new ExprVar ( "" ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( object , label ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( object , label_en ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( subject , label ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( object , intvalue ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( subject , intvalue ) ) ; } public void testIsIRI ( ) { List < Triple > pattern = new ArrayList < Triple > ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , RDFS . label . asNode ( ) , Node . createVariable ( "" ) ) ) ; NodeRelation [ ] rels = translate ( pattern , "" ) ; NodeRelation label = search ( "" , "" , rels ) ; NodeRelation label_en = search ( "" , "" , rels ) ; pattern . clear ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , Node . createURI ( "" ) , Node . createVariable ( "" ) ) ) ; rels = translate ( pattern , "" ) ; NodeRelation intvalue = search ( "" , "" , rels ) ; Expr subject = new E_IsIRI ( new ExprVar ( "" ) ) ; Expr object = new E_IsIRI ( new ExprVar ( "" ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( object , label ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( object , label_en ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( subject , label ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( object , intvalue ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( subject , intvalue ) ) ; } public void testIsBlank ( ) { List < Triple > pattern = new ArrayList < Triple > ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , RDFS . label . asNode ( ) , Node . createVariable ( "" ) ) ) ; NodeRelation [ ] rels = translate ( pattern , "" ) ; NodeRelation label = search ( "" , "" , rels ) ; NodeRelation label_en = search ( "" , "" , rels ) ; pattern . clear ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , Node . createURI ( "" ) , Node . createVariable ( "" ) ) ) ; rels = translate ( pattern , "" ) ; NodeRelation intvalue = search ( "" , "" , rels ) ; Expr subject = new E_IsBlank ( new ExprVar ( "" ) ) ; Expr object = new E_IsBlank ( new ExprVar ( "" ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( object , label ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( object , label_en ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( subject , label ) ) ; assertEquals ( "" , Expression . FALSE , TransformExprToSQLApplyer . convert ( object , intvalue ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( subject , intvalue ) ) ; } public void testDataType ( ) { List < Triple > pattern = new ArrayList < Triple > ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , Node . createURI ( "" ) , Node . createVariable ( "" ) ) ) ; NodeRelation [ ] rels = translate ( pattern , "" ) ; NodeRelation intvalue = search ( "" , "" , rels ) ; NodeRelation value = search ( "" , "" , rels ) ; pattern . clear ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , RDFS . label . asNode ( ) , Node . createVariable ( "" ) ) ) ; rels = translate ( pattern , "" ) ; NodeRelation langliteral = search ( "" , "" , rels ) ; Expr filterint = new E_Equals ( new E_Datatype ( new ExprVar ( "" ) ) , NodeValueNode . makeNode ( Node . createURI ( XSDDatatype . XSDint . getURI ( ) ) ) ) ; Expr filterstring = new E_Equals ( new E_Datatype ( new ExprVar ( "" ) ) , NodeValueNode . makeNode ( Node . createURI ( XSDDatatype . XSDstring . getURI ( ) ) ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterint , intvalue ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterstring , value ) ) ; assertEquals ( "" , Expression . TRUE , TransformExprToSQLApplyer . convert ( filterstring , langliteral ) ) ; } public void testDisjunction ( ) { List < Triple > pattern = new ArrayList < Triple > ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , Node . createURI ( "" ) , Node . createVariable ( "" ) ) ) ; NodeRelation [ ] rels = translate ( pattern , "" ) ; NodeRelation intvalue = search ( "" , "" , rels ) ; Expr disjunction = new E_LogicalOr ( new E_Equals ( new ExprVar ( "" ) , NodeValue . makeNode ( "" , XSDDatatype . XSDint ) ) , new E_Equals ( new ExprVar ( "" ) , NodeValue . makeNode ( "" , XSDDatatype . XSDint ) ) ) ; Expression result = TransformExprToSQLApplyer . convert ( disjunction , intvalue ) ; TypedNodeMaker nm = ( TypedNodeMaker ) intvalue . nodeMaker ( Var . alloc ( "" ) ) ; Expression e1 = nm . valueMaker ( ) . valueExpression ( "" ) ; Expression e2 = nm . valueMaker ( ) . valueExpression ( "" ) ; Expression expected = e1 . or ( e2 ) ; assertEquals ( "" , expected , result ) ; } public void testSameTerm ( ) { List < Triple > pattern = new ArrayList < Triple > ( ) ; pattern . add ( Triple . create ( Node . createVariable ( "" ) , Node . createURI ( "" ) , Node . createVariable ( "" ) ) ) ; NodeRelation [ ] rels = translate ( pattern , "" ) ; NodeRelation intvalue = search ( "" , "" , rels ) ; Expr sameTerm = new E_SameTerm ( new ExprVar ( "" ) , NodeValue . makeNode ( "" , XSDDatatype . XSDint ) ) ; Expression result = TransformExprToSQLApplyer . convert ( sameTerm , intvalue ) ; TypedNodeMaker nm = ( TypedNodeMaker ) intvalue . nodeMaker ( Var . alloc ( "" ) ) ; Expression expected = nm . valueMaker ( ) . valueExpression ( "" ) ; assertEquals ( "" , expected , result ) ; sameTerm = new E_SameTerm ( new ExprVar ( "" ) , NodeValue . makeNode ( "" , XSDDatatype . XSDdecimal ) ) ; result = TransformExprToSQLApplyer . convert ( sameTerm , intvalue ) ; assertEquals ( "" , Expression . FALSE , result ) ; } private NodeRelation [ ] translate ( List < Triple > pattern , String mappingFile ) { Collection < NodeRelation > rels = new GraphPatternTranslator ( pattern , MapFixture . loadPropertyBridges ( mappingFile ) , true ) . translate ( ) ; return ( NodeRelation [ ] ) rels . toArray ( new NodeRelation [ rels . size ( ) ] ) ; } } package de . fuberlin . wiwiss . d2rq . optimizer ; import junit . framework . TestCase ; import com . hp . hpl . jena . sparql . expr . Expr ; import com . hp . hpl . jena . sparql . util . ExprUtils ; import de . fuberlin . wiwiss . d2rq . engine . TransformFilterCNF . DeMorganLawApplyer ; import de . fuberlin . wiwiss . d2rq . engine . TransformFilterCNF . DistributiveLawApplyer ; public class ExprTransformTest extends TestCase { public void testExprDeMorganDoubleNotA ( ) { Expr expr = ExprUtils . parse ( "" ) ; DeMorganLawApplyer apply = new DeMorganLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDeMorganDoubleNotAB ( ) { Expr expr = ExprUtils . parse ( "" ) ; DeMorganLawApplyer apply = new DeMorganLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDeMorganOr ( ) { Expr expr = ExprUtils . parse ( "" ) ; DeMorganLawApplyer apply = new DeMorganLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDeMorganAndDontChange ( ) { Expr expr = ExprUtils . parse ( "" ) ; DeMorganLawApplyer apply = new DeMorganLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDistributiveABOrC ( ) { Expr expr = ExprUtils . parse ( "" ) ; DistributiveLawApplyer apply = new DistributiveLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDistributiveCOrAB ( ) { Expr expr = ExprUtils . parse ( "" ) ; DistributiveLawApplyer apply = new DistributiveLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDistributiveAndDontChange ( ) { Expr expr = ExprUtils . parse ( "" ) ; DistributiveLawApplyer apply = new DistributiveLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDistributiveOrComplex ( ) { Expr expr = ExprUtils . parse ( "" ) ; DistributiveLawApplyer apply = new DistributiveLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDistributiveABC ( ) { Expr expr = ExprUtils . parse ( "" ) ; DistributiveLawApplyer apply = new DistributiveLawApplyer ( ) ; expr . visit ( apply ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testExprDistributiveUsingFunctions ( ) { Expr expr = ExprUtils . parse ( "" ) ; DistributiveLawApplyer apply = new DistributiveLawApplyer ( ) ; expr . visit ( apply ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } public void testDeMorganNotEqual ( ) { Expr expr = ExprUtils . parse ( "" ) ; DeMorganLawApplyer apply = new DeMorganLawApplyer ( ) ; expr . visit ( apply ) ; assertNotNull ( apply . result ( ) ) ; assertEquals ( "" , apply . result ( ) . toString ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . optimizer ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( AllTests . class . getName ( ) ) ; suite . addTestSuite ( ExprTransformTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Set ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; import de . fuberlin . wiwiss . d2rq . expr . SQLExpression ; public class AliasMapTest extends TestCase { private final static RelationName foo = new RelationName ( null , "" ) ; private final static RelationName bar = new RelationName ( null , "" ) ; private final static RelationName baz = new RelationName ( null , "" ) ; private final static Attribute foo_col1 = new Attribute ( null , "" , "" ) ; private final static Attribute bar_col1 = new Attribute ( null , "" , "" ) ; private final static Attribute baz_col1 = new Attribute ( null , "" , "" ) ; private final static Attribute abc_col1 = new Attribute ( null , "" , "" ) ; private final static Attribute xyz_col1 = new Attribute ( null , "" , "" ) ; private Alias fooAsBar = new Alias ( foo , bar ) ; private Alias fooAsBaz = new Alias ( foo , baz ) ; private Alias bazAsBar = new Alias ( baz , bar ) ; private AliasMap fooAsBarMap = new AliasMap ( Collections . singleton ( new Alias ( foo , bar ) ) ) ; public void testEmptyMapDoesIdentityTranslation ( ) { AliasMap aliases = AliasMap . NO_ALIASES ; assertFalse ( aliases . isAlias ( foo ) ) ; assertFalse ( aliases . hasAlias ( foo ) ) ; assertEquals ( foo , aliases . applyTo ( foo ) ) ; assertEquals ( foo , aliases . originalOf ( foo ) ) ; } public void testAliasIsTranslated ( ) { assertFalse ( this . fooAsBarMap . isAlias ( foo ) ) ; assertTrue ( this . fooAsBarMap . isAlias ( bar ) ) ; assertFalse ( this . fooAsBarMap . isAlias ( baz ) ) ; assertTrue ( this . fooAsBarMap . hasAlias ( foo ) ) ; assertFalse ( this . fooAsBarMap . hasAlias ( bar ) ) ; assertFalse ( this . fooAsBarMap . hasAlias ( baz ) ) ; assertEquals ( bar , this . fooAsBarMap . applyTo ( foo ) ) ; assertEquals ( baz , this . fooAsBarMap . applyTo ( baz ) ) ; assertEquals ( foo , this . fooAsBarMap . originalOf ( bar ) ) ; assertEquals ( baz , this . fooAsBarMap . originalOf ( baz ) ) ; } public void testApplyToColumn ( ) { assertEquals ( baz_col1 , this . fooAsBarMap . applyTo ( baz_col1 ) ) ; assertEquals ( bar_col1 , this . fooAsBarMap . applyTo ( foo_col1 ) ) ; assertEquals ( bar_col1 , this . fooAsBarMap . applyTo ( bar_col1 ) ) ; } public void testOriginalOfColumn ( ) { assertEquals ( baz_col1 , this . fooAsBarMap . originalOf ( baz_col1 ) ) ; assertEquals ( foo_col1 , this . fooAsBarMap . originalOf ( foo_col1 ) ) ; assertEquals ( foo_col1 , this . fooAsBarMap . originalOf ( bar_col1 ) ) ; } public void testApplyToJoinSetDoesNotModifyUnaliasedJoin ( ) { Join join = new Join ( abc_col1 , xyz_col1 , Join . DIRECTION_RIGHT ) ; Set < Join > joins = Collections . singleton ( join ) ; assertEquals ( joins , this . fooAsBarMap . applyToJoinSet ( joins ) ) ; } public void testApplyToJoinSetDoesModifyAliasedJoin ( ) { Join join = new Join ( foo_col1 , foo_col1 , Join . DIRECTION_RIGHT ) ; Set < Join > aliasedSet = this . fooAsBarMap . applyToJoinSet ( Collections . singleton ( join ) ) ; assertEquals ( , aliasedSet . size ( ) ) ; Join aliased = ( Join ) aliasedSet . iterator ( ) . next ( ) ; assertEquals ( Collections . singletonList ( bar_col1 ) , aliased . attributes1 ( ) ) ; assertEquals ( Collections . singletonList ( bar_col1 ) , aliased . attributes2 ( ) ) ; } public void testApplyToSQLExpression ( ) { assertEquals ( SQLExpression . create ( "" ) , fooAsBarMap . applyTo ( SQLExpression . create ( "" ) ) ) ; } public void testNoAliasesConstantEqualsNewEmptyAliasMap ( ) { AliasMap noAliases = new AliasMap ( Collections . < Alias > emptyList ( ) ) ; assertTrue ( AliasMap . NO_ALIASES . equals ( noAliases ) ) ; assertTrue ( noAliases . equals ( AliasMap . NO_ALIASES ) ) ; } public void testEmptyMapEqualsItself ( ) { assertTrue ( AliasMap . NO_ALIASES . equals ( AliasMap . NO_ALIASES ) ) ; } public void testEmptyMapDoesntEqualPopulatedMap ( ) { assertFalse ( AliasMap . NO_ALIASES . equals ( fooAsBarMap ) ) ; } public void testPopulatedMapDoesntEqualEmptyMap ( ) { assertFalse ( fooAsBarMap . equals ( AliasMap . NO_ALIASES ) ) ; } public void testPopulatedMapEqualsItself ( ) { AliasMap fooAsBar2 = new AliasMap ( Collections . singleton ( new Alias ( foo , bar ) ) ) ; assertTrue ( fooAsBarMap . equals ( fooAsBar2 ) ) ; assertTrue ( fooAsBar2 . equals ( fooAsBarMap ) ) ; } public void testPopulatedMapDoesNotEqualDifferentMap ( ) { AliasMap fooAsBaz = new AliasMap ( Collections . singleton ( new Alias ( foo , baz ) ) ) ; assertFalse ( fooAsBarMap . equals ( fooAsBaz ) ) ; assertFalse ( fooAsBaz . equals ( fooAsBarMap ) ) ; } public void testEqualMapsHaveSameHashCode ( ) { AliasMap m1 = new AliasMap ( new ArrayList < Alias > ( ) ) ; AliasMap m2 = new AliasMap ( new ArrayList < Alias > ( ) ) ; assertEquals ( m1 . hashCode ( ) , m2 . hashCode ( ) ) ; } public void testAliasEquals ( ) { Alias fooAsBar2 = new Alias ( foo , bar ) ; assertEquals ( fooAsBar , fooAsBar2 ) ; assertEquals ( fooAsBar2 , fooAsBar ) ; assertEquals ( fooAsBar . hashCode ( ) , fooAsBar2 . hashCode ( ) ) ; } public void testAliasNotEquals ( ) { assertFalse ( fooAsBar . equals ( fooAsBaz ) ) ; assertFalse ( fooAsBaz . equals ( fooAsBar ) ) ; assertFalse ( fooAsBar . equals ( bazAsBar ) ) ; assertFalse ( bazAsBar . equals ( fooAsBar ) ) ; assertFalse ( fooAsBar . hashCode ( ) == fooAsBaz . hashCode ( ) ) ; assertFalse ( fooAsBar . hashCode ( ) == bazAsBar . hashCode ( ) ) ; } public void testAliasToString ( ) { assertEquals ( "" , fooAsBar . toString ( ) ) ; } public void testApplyToAliasEmpty ( ) { assertEquals ( fooAsBar , AliasMap . NO_ALIASES . applyTo ( fooAsBar ) ) ; } public void testApplyToAlias ( ) { assertEquals ( new Alias ( baz , bar ) , fooAsBarMap . applyTo ( new Alias ( baz , foo ) ) ) ; } public void testOriginalOfAliasEmpty ( ) { assertEquals ( fooAsBar , AliasMap . NO_ALIASES . originalOf ( fooAsBar ) ) ; } public void testOriginalOfAlias ( ) { assertEquals ( fooAsBaz , fooAsBarMap . originalOf ( new Alias ( bar , baz ) ) ) ; } public void testToStringEmpty ( ) { assertEquals ( "" , AliasMap . NO_ALIASES . toString ( ) ) ; } public void testToStringOneAlias ( ) { assertEquals ( "" , fooAsBarMap . toString ( ) ) ; } public void testToStringTwoAliases ( ) { Collection < Alias > aliases = new ArrayList < Alias > ( ) ; aliases . add ( fooAsBar ) ; aliases . add ( new Alias ( new RelationName ( null , "" ) , new RelationName ( null , "" ) ) ) ; assertEquals ( "" , new AliasMap ( aliases ) . toString ( ) ) ; } public void testWithSchema ( ) { RelationName table = new RelationName ( null , "" ) ; RelationName schema_table = new RelationName ( "" , "" ) ; RelationName schema_alias = new RelationName ( "" , "" ) ; AliasMap m = new AliasMap ( Collections . singleton ( new Alias ( schema_table , schema_alias ) ) ) ; assertEquals ( schema_alias , m . applyTo ( schema_table ) ) ; assertEquals ( table , m . applyTo ( table ) ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Arrays ; import java . util . Collections ; import junit . framework . TestCase ; public class JoinTest extends TestCase { private final static Attribute table1foo = new Attribute ( null , "" , "" ) ; private final static Attribute table1bar = new Attribute ( null , "" , "" ) ; private final static Attribute table2foo = new Attribute ( null , "" , "" ) ; private final static Attribute table2bar = new Attribute ( null , "" , "" ) ; private final static RelationName table1 = new RelationName ( null , "" ) ; private final static RelationName table2 = new RelationName ( null , "" ) ; public void testToString ( ) { Join join = new Join ( table1foo , table2foo , Join . DIRECTION_UNDIRECTED ) ; assertEquals ( "" , join . toString ( ) ) ; } public void testToStringRetainsTableOrder ( ) { Join join = new Join ( table2foo , table1foo , Join . DIRECTION_RIGHT ) ; assertEquals ( "" , join . toString ( ) ) ; } public void testToStringRetainsAttributeOrder ( ) { Join join = new Join ( Arrays . asList ( new Attribute [ ] { table1foo , table1bar } ) , Arrays . asList ( new Attribute [ ] { table2bar , table2foo } ) , Join . DIRECTION_RIGHT ) ; assertEquals ( "" , join . toString ( ) ) ; } public void testRenameColumns ( ) { ColumnRenamer renamer = new ColumnRenamerMap ( Collections . singletonMap ( table1foo , table1bar ) ) ; Join join = new Join ( table1foo , table2foo , Join . DIRECTION_RIGHT ) ; assertEquals ( "" , join . renameColumns ( renamer ) . toString ( ) ) ; } public void testTableOrderIsRetained ( ) { assertEquals ( table1 , new Join ( table1foo , table2foo , Join . DIRECTION_RIGHT ) . table1 ( ) ) ; assertEquals ( table2 , new Join ( table2foo , table1foo , Join . DIRECTION_RIGHT ) . table1 ( ) ) ; } public void testJoinOverSameAttributesIsEqual ( ) { Join j1 = new Join ( table1foo , table2foo , Join . DIRECTION_RIGHT ) ; Join j2 = new Join ( table1foo , table2foo , Join . DIRECTION_RIGHT ) ; assertEquals ( j1 , j2 ) ; assertEquals ( j2 , j1 ) ; assertEquals ( j1 . hashCode ( ) , j2 . hashCode ( ) ) ; } public void testSideOrderDoesNotAffectEquality1 ( ) { Join j1 = new Join ( table1foo , table2foo , Join . DIRECTION_RIGHT ) ; Join j2 = new Join ( table2foo , table1foo , Join . DIRECTION_LEFT ) ; assertEquals ( j1 , j2 ) ; assertEquals ( j2 , j1 ) ; assertEquals ( j1 . hashCode ( ) , j2 . hashCode ( ) ) ; } public void testSideOrderDoesNotAffectEquality2 ( ) { Join j1 = new Join ( table1foo , table2foo , Join . DIRECTION_UNDIRECTED ) ; Join j2 = new Join ( table2foo , table1foo , Join . DIRECTION_UNDIRECTED ) ; assertEquals ( j1 , j2 ) ; assertEquals ( j2 , j1 ) ; assertEquals ( j1 . hashCode ( ) , j2 . hashCode ( ) ) ; } public void testDifferentAttributesNotEqual ( ) { Join j1 = new Join ( table1foo , table2foo , Join . DIRECTION_RIGHT ) ; Join j2 = new Join ( table1foo , table2bar , Join . DIRECTION_RIGHT ) ; assertFalse ( j1 . equals ( j2 ) ) ; assertFalse ( j2 . equals ( j1 ) ) ; assertFalse ( j1 . hashCode ( ) == j2 . hashCode ( ) ) ; } public void testDifferentDirectionsNotEqual ( ) { Join j1 = new Join ( table1foo , table2foo , Join . DIRECTION_RIGHT ) ; Join j2 = new Join ( table1foo , table2foo , Join . DIRECTION_UNDIRECTED ) ; assertFalse ( j1 . equals ( j2 ) ) ; assertFalse ( j2 . equals ( j1 ) ) ; assertFalse ( j1 . hashCode ( ) == j2 . hashCode ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; public class AttributeTest extends TestCase { private final static RelationName table1 = new RelationName ( null , "" ) ; private final static RelationName table1b = new RelationName ( null , "" ) ; private final static RelationName table2 = new RelationName ( null , "" ) ; private final static RelationName xTable1 = new RelationName ( "" , "" ) ; private final static RelationName xTable2 = new RelationName ( "" , "" ) ; private final static RelationName yTable1 = new RelationName ( "" , "" ) ; private final static Attribute fooCol1 = new Attribute ( null , "" , "" ) ; private final static Attribute fooCol2 = new Attribute ( null , "" , "" ) ; private final static Attribute barCol1 = new Attribute ( null , "" , "" ) ; private final static Attribute barCol2 = new Attribute ( null , "" , "" ) ; public void testAttributeNames ( ) { Attribute col = new Attribute ( null , "" , "" ) ; assertEquals ( "" , col . qualifiedName ( ) ) ; assertNull ( col . schemaName ( ) ) ; assertEquals ( "" , col . tableName ( ) ) ; assertEquals ( "" , col . attributeName ( ) ) ; assertEquals ( new RelationName ( null , "" ) , col . relationName ( ) ) ; } public void testAttributeNameWithSchema ( ) { Attribute column = new Attribute ( "" , "" , "" ) ; assertEquals ( "" , column . qualifiedName ( ) ) ; assertEquals ( "" , column . schemaName ( ) ) ; assertEquals ( "" , column . tableName ( ) ) ; assertEquals ( "" , column . attributeName ( ) ) ; assertEquals ( new RelationName ( "" , "" ) , column . relationName ( ) ) ; } public void testAttributeEquality ( ) { Attribute col1 = new Attribute ( null , "" , "" ) ; Attribute col1b = new Attribute ( null , "" , "" ) ; Attribute col2 = new Attribute ( null , "" , "" ) ; Attribute col3 = new Attribute ( null , "" , "" ) ; Integer other = new Integer ( ) ; assertFalse ( col1 . equals ( col2 ) ) ; assertFalse ( col1 . equals ( col3 ) ) ; assertFalse ( col1 . equals ( other ) ) ; assertFalse ( col2 . equals ( col1 ) ) ; assertFalse ( col3 . equals ( col1 ) ) ; assertFalse ( other . equals ( col1 ) ) ; assertTrue ( col1 . equals ( col1b ) ) ; assertFalse ( col1 . equals ( null ) ) ; } public void testAttributeEqualityWithSchema ( ) { Attribute schema0 = new Attribute ( null , "" , "" ) ; Attribute schema1 = new Attribute ( "" , "" , "" ) ; Attribute schema2 = new Attribute ( "" , "" , "" ) ; Attribute schema2b = new Attribute ( "" , "" , "" ) ; assertFalse ( schema0 . equals ( schema1 ) ) ; assertFalse ( schema1 . equals ( schema2 ) ) ; assertTrue ( schema2 . equals ( schema2b ) ) ; } public void testAttributeHashCode ( ) { Map < Attribute , String > map = new HashMap < Attribute , String > ( ) ; Attribute col1 = new Attribute ( null , "" , "" ) ; Attribute col1b = new Attribute ( null , "" , "" ) ; Attribute col2 = new Attribute ( null , "" , "" ) ; Attribute col3 = new Attribute ( null , "" , "" ) ; Attribute col1schema = new Attribute ( "" , "" , "" ) ; map . put ( col1 , "" ) ; map . put ( col2 , "" ) ; map . put ( col1schema , "" ) ; assertEquals ( "" , map . get ( col1 ) ) ; assertEquals ( "" , map . get ( col1b ) ) ; assertEquals ( "" , map . get ( col2 ) ) ; assertNull ( map . get ( col3 ) ) ; assertEquals ( "" , map . get ( col1schema ) ) ; } public void testAttributeToString ( ) { assertEquals ( "" , new Attribute ( null , "" , "" ) . toString ( ) ) ; assertEquals ( "" , new Attribute ( "" , "" , "" ) . toString ( ) ) ; } public void testCompareSameAttribute ( ) { assertEquals ( , fooCol1 . compareTo ( fooCol1 ) ) ; } public void testCompareSameTableDifferentAttribute ( ) { assertTrue ( fooCol1 . compareTo ( fooCol2 ) < ) ; assertTrue ( fooCol2 . compareTo ( fooCol1 ) > ) ; } public void testCompareSameAttributeDifferentTable ( ) { assertTrue ( barCol1 . compareTo ( fooCol1 ) < ) ; assertTrue ( fooCol1 . compareTo ( barCol2 ) > ) ; } public void testCompareDifferentAttributeDifferentTable ( ) { assertTrue ( barCol2 . compareTo ( fooCol1 ) < ) ; assertTrue ( fooCol1 . compareTo ( barCol2 ) > ) ; } public void testNoSchemaAttributeSmallerThanSchemaAttribute ( ) { Attribute noSchema = new Attribute ( null , "" , "" ) ; Attribute schema = new Attribute ( "" , "" , "" ) ; assertTrue ( noSchema . compareTo ( schema ) < ) ; assertTrue ( schema . compareTo ( noSchema ) > ) ; } public void testRelationNameWithoutSchema ( ) { RelationName r = new RelationName ( null , "" ) ; assertEquals ( "" , r . tableName ( ) ) ; assertNull ( r . schemaName ( ) ) ; assertEquals ( "" , r . qualifiedName ( ) ) ; } public void testRelationNameWithSchema ( ) { RelationName r = new RelationName ( "" , "" ) ; assertEquals ( "" , r . tableName ( ) ) ; assertEquals ( "" , r . schemaName ( ) ) ; assertEquals ( "" , r . qualifiedName ( ) ) ; } public void testRelationNameToString ( ) { assertEquals ( "" , new RelationName ( null , "" ) . toString ( ) ) ; assertEquals ( "" , new RelationName ( "" , "" ) . toString ( ) ) ; } public void testSameRelationNameIsEqual ( ) { assertEquals ( table1 , table1b ) ; assertEquals ( table1b , table1 ) ; assertEquals ( table1 . hashCode ( ) , table1b . hashCode ( ) ) ; } public void testDifferentRelationNamesAreNotEqual ( ) { assertFalse ( table1 . equals ( table2 ) ) ; assertFalse ( table2 . equals ( table1 ) ) ; assertFalse ( table1 . hashCode ( ) == table2 . hashCode ( ) ) ; } public void testSameRelationAndSchemaNameIsEqual ( ) { assertEquals ( table1 , table1b ) ; assertEquals ( table1b , table1 ) ; assertEquals ( table1 . hashCode ( ) , table1b . hashCode ( ) ) ; } public void testDifferentSchemaNamesAreNotEqual ( ) { assertFalse ( xTable1 . equals ( yTable1 ) ) ; assertFalse ( yTable1 . equals ( xTable1 ) ) ; assertFalse ( xTable1 . hashCode ( ) == yTable1 . hashCode ( ) ) ; } public void testSchemaAndNoSchemaAreNotEqual ( ) { assertFalse ( xTable1 . equals ( table1 ) ) ; assertFalse ( table1 . equals ( xTable1 ) ) ; assertFalse ( table1 . hashCode ( ) == xTable1 . hashCode ( ) ) ; } public void testCompareRelationNamesDifferentSchema ( ) { assertTrue ( xTable1 . compareTo ( yTable1 ) < ) ; assertTrue ( yTable1 . compareTo ( xTable1 ) > ) ; } public void testCompareRelationNamesSameSchema ( ) { assertTrue ( table1 . compareTo ( table2 ) < ) ; assertTrue ( table2 . compareTo ( table1 ) > ) ; assertTrue ( xTable1 . compareTo ( xTable2 ) < ) ; assertTrue ( xTable2 . compareTo ( xTable1 ) > ) ; } public void testNoSchemaRelationNameSmallerSchemaRelationName ( ) { RelationName noSchema = new RelationName ( null , "" ) ; RelationName schema = new RelationName ( "" , "" ) ; assertTrue ( noSchema . compareTo ( schema ) < ) ; assertTrue ( schema . compareTo ( noSchema ) > ) ; } public void testCompareSameRelationName ( ) { assertEquals ( , table1 . compareTo ( table1 ) ) ; assertEquals ( , xTable1 . compareTo ( xTable1 ) ) ; } public void testRelationNameWithPrefixNoSchema ( ) { assertEquals ( "" , table1 . withPrefix ( ) . qualifiedName ( ) ) ; } public void testRelationNameWithPrefixWithSchema ( ) { assertEquals ( "" , xTable1 . withPrefix ( ) . qualifiedName ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . expr . SQLExpression ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . DummyDB ; public class RelationTest extends TestCase { private ConnectedDB db ; private Relation rel1 ; public void setUp ( ) { db = new DummyDB ( ) ; rel1 = Relation . createSimpleRelation ( db , new Attribute [ ] { new Attribute ( null , "" , "" ) } ) ; } public void testSelectFalseIsEmptyRelation ( ) { assertEquals ( Relation . EMPTY , rel1 . select ( Expression . FALSE ) ) ; } public void testTrueRelationIsTrivial ( ) { assertTrue ( Relation . TRUE . isTrivial ( ) ) ; } public void testConditionWithNoSelectColumnsIsNotTrivial ( ) { assertFalse ( Relation . createSimpleRelation ( db , new Attribute [ ] { } ) . select ( SQLExpression . create ( "" ) ) . isTrivial ( ) ) ; } public void testQueryWithSelectColumnsIsNotTrivial ( ) { assertFalse ( rel1 . isTrivial ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Collections ; import java . util . Iterator ; import java . util . Map ; import java . util . Set ; import junit . framework . TestCase ; import com . hp . hpl . jena . sparql . core . Var ; import de . fuberlin . wiwiss . d2rq . engine . BindingMaker ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . TypedNodeMaker ; import de . fuberlin . wiwiss . d2rq . parser . RelationBuilder ; import de . fuberlin . wiwiss . d2rq . sql . DummyDB ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . values . Column ; public class CompatibleRelationGroupTest extends TestCase { Set < ProjectionSpec > projections1 ; Set < ProjectionSpec > projections2 ; RelationImpl unique ; RelationImpl notUnique ; DummyDB db ; public void setUp ( ) { db = new DummyDB ( ) ; projections1 = Collections . < ProjectionSpec > singleton ( new Attribute ( null , "" , "" ) ) ; projections2 = Collections . < ProjectionSpec > singleton ( new Attribute ( null , "" , "" ) ) ; unique = new RelationImpl ( db , AliasMap . NO_ALIASES , Expression . TRUE , Expression . TRUE , Collections . < Join > emptySet ( ) , projections1 , true , OrderSpec . NONE , Relation . NO_LIMIT , Relation . NO_LIMIT ) ; notUnique = new RelationImpl ( db , AliasMap . NO_ALIASES , Expression . TRUE , Expression . TRUE , Collections . < Join > emptySet ( ) , projections2 , false , OrderSpec . NONE , Relation . NO_LIMIT , Relation . NO_LIMIT ) ; } public void testNotUniqueIsNotCompatible ( ) { CompatibleRelationGroup group ; group = new CompatibleRelationGroup ( ) ; group . addRelation ( unique ) ; assertTrue ( group . isCompatible ( unique ) ) ; assertFalse ( group . isCompatible ( notUnique ) ) ; group = new CompatibleRelationGroup ( ) ; group . addRelation ( notUnique ) ; assertFalse ( group . isCompatible ( unique ) ) ; } public void testNotUniqueIsCompatibleIfSameAttributes ( ) { CompatibleRelationGroup group = new CompatibleRelationGroup ( ) ; group . addRelation ( notUnique ) ; assertTrue ( group . isCompatible ( notUnique ) ) ; } public void testCombineDifferentConditions ( ) { Attribute id = SQL . parseAttribute ( "" ) ; db . setNullable ( id , false ) ; NodeMaker x = new TypedNodeMaker ( TypedNodeMaker . PLAIN_LITERAL , new Column ( id ) , true ) ; Map < Var , NodeMaker > map = Collections . singletonMap ( Var . alloc ( "" ) , x ) ; BindingMaker bm = new BindingMaker ( map , null ) ; RelationBuilder b1 = new RelationBuilder ( db ) ; RelationBuilder b2 = new RelationBuilder ( db ) ; b1 . addProjection ( id ) ; b2 . addProjection ( id ) ; b1 . addCondition ( "" ) ; b2 . addCondition ( "" ) ; CompatibleRelationGroup group = new CompatibleRelationGroup ( ) ; Relation r1 = b1 . buildRelation ( ) ; Relation r2 = b2 . buildRelation ( ) ; group . addBindingMaker ( r1 , bm ) ; assertTrue ( group . isCompatible ( r2 ) ) ; group . addBindingMaker ( r2 , bm ) ; assertEquals ( , group . bindingMakers ( ) . size ( ) ) ; assertTrue ( group . baseRelation ( ) . projections ( ) . contains ( new ExpressionProjectionSpec ( r1 . condition ( ) ) ) ) ; assertTrue ( group . baseRelation ( ) . projections ( ) . contains ( new ExpressionProjectionSpec ( r2 . condition ( ) ) ) ) ; assertEquals ( , group . baseRelation ( ) . projections ( ) . size ( ) ) ; assertEquals ( r1 . condition ( ) . or ( r2 . condition ( ) ) , group . baseRelation ( ) . condition ( ) ) ; assertEquals ( group . bindingMakers ( ) . iterator ( ) . next ( ) . nodeMaker ( Var . alloc ( "" ) ) , x ) ; assertNotNull ( group . bindingMakers ( ) . iterator ( ) . next ( ) . condition ( ) ) ; } public void testCombineConditionAndNoCondition ( ) { Attribute id = SQL . parseAttribute ( "" ) ; db . setNullable ( id , false ) ; NodeMaker x = new TypedNodeMaker ( TypedNodeMaker . PLAIN_LITERAL , new Column ( id ) , true ) ; Map < Var , NodeMaker > map = Collections . singletonMap ( Var . alloc ( "" ) , x ) ; BindingMaker bm = new BindingMaker ( map , null ) ; RelationBuilder b1 = new RelationBuilder ( db ) ; RelationBuilder b2 = new RelationBuilder ( db ) ; b1 . addProjection ( id ) ; b2 . addProjection ( id ) ; b1 . addCondition ( "" ) ; CompatibleRelationGroup group = new CompatibleRelationGroup ( ) ; Relation r1 = b1 . buildRelation ( ) ; Relation r2 = b2 . buildRelation ( ) ; group . addBindingMaker ( r1 , bm ) ; assertTrue ( group . isCompatible ( r2 ) ) ; group . addBindingMaker ( r2 , bm ) ; assertEquals ( , group . bindingMakers ( ) . size ( ) ) ; assertTrue ( group . baseRelation ( ) . projections ( ) . contains ( new ExpressionProjectionSpec ( r1 . condition ( ) ) ) ) ; assertEquals ( , group . baseRelation ( ) . projections ( ) . size ( ) ) ; assertEquals ( Expression . TRUE , group . baseRelation ( ) . condition ( ) ) ; Iterator < BindingMaker > it = group . bindingMakers ( ) . iterator ( ) ; BindingMaker bm3 = it . next ( ) ; BindingMaker bm4 = it . next ( ) ; assertTrue ( ( bm3 . condition ( ) == null && bm4 . condition ( ) != null ) || ( bm3 . condition ( ) != null && bm4 . condition ( ) == null ) ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import com . hp . hpl . jena . graph . Node ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . FixedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . TypedNodeMaker ; import de . fuberlin . wiwiss . d2rq . values . Column ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; public class TripleRelationTest extends TestCase { public void testWithPrefix ( ) { RelationName original = new RelationName ( null , "" ) ; RelationName alias = new RelationName ( null , "" ) ; AliasMap aliases = AliasMap . create1 ( original , alias ) ; Set < ProjectionSpec > projections = new HashSet < ProjectionSpec > ( Arrays . asList ( new Attribute [ ] { new Attribute ( original , "" ) , new Attribute ( alias , "" ) } ) ) ; Relation rel = new RelationImpl ( null , aliases , Expression . TRUE , Expression . TRUE , Collections . < Join > emptySet ( ) , projections , false , OrderSpec . NONE , Relation . NO_LIMIT , Relation . NO_LIMIT ) ; TripleRelation t = new TripleRelation ( rel , new TypedNodeMaker ( TypedNodeMaker . URI , new Pattern ( "" ) , true ) , new FixedNodeMaker ( Node . createURI ( "" ) , false ) , new TypedNodeMaker ( TypedNodeMaker . PLAIN_LITERAL , new Column ( new Attribute ( alias , "" ) ) , false ) ) ; assertEquals ( "" , t . nodeMaker ( TripleRelation . SUBJECT ) . toString ( ) ) ; assertEquals ( "" , t . nodeMaker ( TripleRelation . OBJECT ) . toString ( ) ) ; assertEquals ( "" , t . baseRelation ( ) . aliases ( ) . toString ( ) ) ; NodeRelation t4 = t . withPrefix ( ) ; assertEquals ( "" , t4 . nodeMaker ( TripleRelation . SUBJECT ) . toString ( ) ) ; assertEquals ( "" , t4 . nodeMaker ( TripleRelation . OBJECT ) . toString ( ) ) ; assertEquals ( "" , t4 . baseRelation ( ) . aliases ( ) . toString ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( RelationTest . class ) ; suite . addTestSuite ( AliasMapTest . class ) ; suite . addTestSuite ( TripleRelationTest . class ) ; suite . addTestSuite ( AttributeTest . class ) ; suite . addTestSuite ( ColumnRenamerTest . class ) ; suite . addTestSuite ( CompatibleRelationGroupTest . class ) ; suite . addTestSuite ( JoinTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . expr . SQLExpression ; public class ColumnRenamerTest extends TestCase { private final static Attribute col1 = new Attribute ( null , "" , "" ) ; private final static Attribute col2 = new Attribute ( null , "" , "" ) ; private final static Attribute col3 = new Attribute ( null , "" , "" ) ; private ColumnRenamerMap col1ToCol2 ; public void setUp ( ) { Map < Attribute , Attribute > m = new HashMap < Attribute , Attribute > ( ) ; m . put ( col1 , col2 ) ; this . col1ToCol2 = new ColumnRenamerMap ( m ) ; } public void testApplyToUnmappedColumnReturnsSameColumn ( ) { assertEquals ( col3 , this . col1ToCol2 . applyTo ( col3 ) ) ; } public void testApplyToMappedColumnReturnsNewName ( ) { assertEquals ( col2 , this . col1ToCol2 . applyTo ( col1 ) ) ; } public void testApplyToNewNameReturnsNewName ( ) { assertEquals ( col2 , this . col1ToCol2 . applyTo ( col2 ) ) ; } public void testApplyToExpressionReplacesMappedColumns ( ) { Expression e = SQLExpression . create ( "" ) ; assertEquals ( SQLExpression . create ( "" ) , this . col1ToCol2 . applyTo ( e ) ) ; } public void testApplyToAliasMapReturnsOriginal ( ) { AliasMap aliases = new AliasMap ( Collections . singleton ( new Alias ( new RelationName ( null , "" ) , new RelationName ( null , "" ) ) ) ) ; assertEquals ( aliases , this . col1ToCol2 . applyTo ( aliases ) ) ; } public void testNullRenamerToStringEmpty ( ) { assertEquals ( "" , ColumnRenamer . NULL . toString ( ) ) ; } public void testEmptyRenamerToStringEmpty ( ) { assertEquals ( "" , new ColumnRenamerMap ( Collections . < Attribute , Attribute > emptyMap ( ) ) . toString ( ) ) ; } public void testToStringOneAlias ( ) { assertEquals ( "" , col1ToCol2 . toString ( ) ) ; } public void testToStringTwoAliases ( ) { Map < Attribute , Attribute > m = new HashMap < Attribute , Attribute > ( ) ; m . put ( col1 , col3 ) ; m . put ( col2 , col3 ) ; assertEquals ( "" , new ColumnRenamerMap ( m ) . toString ( ) ) ; } public void testRenameWithSchema ( ) { Attribute foo_c1 = new Attribute ( "" , "" , "" ) ; Attribute bar_c2 = new Attribute ( "" , "" , "" ) ; ColumnRenamer renamer = new ColumnRenamerMap ( Collections . singletonMap ( foo_c1 , bar_c2 ) ) ; assertEquals ( bar_c2 , renamer . applyTo ( foo_c1 ) ) ; assertEquals ( col1 , renamer . applyTo ( col1 ) ) ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . Collection ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . shared . PrefixMapping ; import com . hp . hpl . jena . shared . impl . PrefixMappingImpl ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . D2RQTestSuite ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; import de . fuberlin . wiwiss . d2rq . vocab . Test ; public class MapFixture { private final static PrefixMapping prefixes = new PrefixMappingImpl ( ) { { setNsPrefixes ( PrefixMapping . Standard ) ; setNsPrefix ( "" , "" ) ; setNsPrefix ( "" , "" ) ; setNsPrefix ( "" , "" ) ; setNsPrefix ( "" , "" ) ; setNsPrefix ( "" , "" ) ; } } ; public static PrefixMapping prefixes ( ) { return prefixes ; } public static Collection < TripleRelation > loadPropertyBridges ( String mappingFileName ) { Model m = ModelFactory . createDefaultModel ( ) ; Resource dummyDB = m . getResource ( Test . DummyDatabase . getURI ( ) ) ; dummyDB . addProperty ( RDF . type , D2RQ . Database ) ; m . read ( D2RQTestSuite . class . getResourceAsStream ( mappingFileName ) , null , "" ) ; Mapping mapping = new MapParser ( m , null ) . parse ( ) ; return mapping . compiledPropertyBridges ( ) ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import junit . framework . TestCase ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . graph . test . NodeCreateUtils ; import com . hp . hpl . jena . sparql . core . Var ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; public class GraphPatternTranslatorTest extends TestCase { private final static RelationName table1 = SQL . parseRelationName ( "" ) ; private final static Attribute table1id = SQL . parseAttribute ( "" ) ; private final static Attribute t1table1id = SQL . parseAttribute ( "" ) ; private final static Attribute t2table1id = SQL . parseAttribute ( "" ) ; private final static Var foo = Var . alloc ( "" ) ; private final static Var type = Var . alloc ( "" ) ; private final static Var x = Var . alloc ( "" ) ; public void testEmptyGraphAndBGP ( ) { NodeRelation nodeRel = translate1 ( Collections . < Triple > emptyList ( ) , Collections . < TripleRelation > emptyList ( ) ) ; assertEquals ( Relation . TRUE , nodeRel . baseRelation ( ) ) ; assertEquals ( Collections . EMPTY_SET , nodeRel . variables ( ) ) ; } public void testEmptyGraph ( ) { assertNull ( translate1 ( "" , Collections . < TripleRelation > emptyList ( ) ) ) ; } public void testEmptyBGP ( ) { NodeRelation nodeRel = translate1 ( Collections . < Triple > emptyList ( ) , "" ) ; assertEquals ( Relation . TRUE , nodeRel . baseRelation ( ) ) ; assertEquals ( Collections . EMPTY_SET , nodeRel . variables ( ) ) ; } public void testAskNoMatch ( ) { assertNull ( translate1 ( "" , "" ) ) ; } public void testAskMatch ( ) { NodeRelation nodeRel = translate1 ( "" , "" ) ; Relation r = nodeRel . baseRelation ( ) ; assertEquals ( Collections . singleton ( table1 ) , r . tables ( ) ) ; assertEquals ( Collections . EMPTY_SET , r . projections ( ) ) ; assertEquals ( Equality . createAttributeValue ( table1id , "" ) , r . condition ( ) ) ; assertEquals ( AliasMap . NO_ALIASES , r . aliases ( ) ) ; assertEquals ( Collections . EMPTY_SET , nodeRel . variables ( ) ) ; } public void testFindNoMatch ( ) { assertNull ( translate1 ( "" , "" ) ) ; } public void testFindFixedMatch ( ) { NodeRelation nodeRel = translate1 ( "" , "" ) ; Relation r = nodeRel . baseRelation ( ) ; assertEquals ( Collections . singleton ( table1 ) , r . tables ( ) ) ; assertEquals ( Collections . EMPTY_SET , r . projections ( ) ) ; assertEquals ( Equality . createAttributeValue ( table1id , "" ) , r . condition ( ) ) ; assertEquals ( AliasMap . NO_ALIASES , r . aliases ( ) ) ; assertEquals ( Collections . singleton ( type ) , nodeRel . variables ( ) ) ; assertEquals ( "" , nodeRel . nodeMaker ( type ) . toString ( ) ) ; } public void testFindMatch ( ) { NodeRelation nodeRel = translate1 ( "" , "" ) ; Relation r = nodeRel . baseRelation ( ) ; assertEquals ( Collections . singleton ( table1 ) , r . tables ( ) ) ; assertEquals ( Collections . singleton ( table1id ) , r . projections ( ) ) ; assertEquals ( Expression . TRUE , r . condition ( ) ) ; assertEquals ( AliasMap . NO_ALIASES , r . aliases ( ) ) ; assertEquals ( Collections . singleton ( x ) , nodeRel . variables ( ) ) ; assertEquals ( "" , nodeRel . nodeMaker ( x ) . toString ( ) ) ; } public void testConstraintInTripleNoMatch ( ) { assertNull ( translate1 ( "" , "" ) ) ; } public void testConstraintInTripleMatch ( ) { NodeRelation nodeRel = translate1 ( "" , "" ) ; Relation r = nodeRel . baseRelation ( ) ; assertEquals ( Collections . singleton ( table1 ) , r . tables ( ) ) ; assertTrue ( r . condition ( ) instanceof Equality ) ; assertEquals ( AliasMap . NO_ALIASES , r . aliases ( ) ) ; assertEquals ( Collections . singleton ( x ) , nodeRel . variables ( ) ) ; } public void testReturnMultipleMatchesForSingleTriplePattern ( ) { NodeRelation [ ] rels = translate ( "" , "" ) ; assertEquals ( , rels . length ) ; } public void testMatchOneOfTwoPropertyBridges ( ) { NodeRelation nodeRel = translate1 ( "" , "" ) ; Relation r = nodeRel . baseRelation ( ) ; assertEquals ( Collections . EMPTY_SET , r . projections ( ) ) ; assertEquals ( Equality . createAttributeValue ( table1id , "" ) , r . condition ( ) ) ; } public void testAskTwoTriplePatternsNoMatch ( ) { assertNull ( translate1 ( "" , "" ) ) ; } public void testAskTwoTriplePatternsMatch ( ) { NodeRelation nodeRel = translate1 ( "" , "" ) ; assertEquals ( Collections . singleton ( foo ) , nodeRel . variables ( ) ) ; assertEquals ( "" , nodeRel . nodeMaker ( foo ) . toString ( ) ) ; Relation r = nodeRel . baseRelation ( ) ; assertEquals ( "" + "" + "" + "" + "" + "" + "" , r . condition ( ) . toString ( ) ) ; } public void testTwoTriplePatternsWithJoinMatch ( ) { NodeRelation nodeRel = translate1 ( "" , "" ) ; assertEquals ( , nodeRel . variables ( ) . size ( ) ) ; assertEquals ( "" , nodeRel . nodeMaker ( foo ) . toString ( ) ) ; assertEquals ( "" , nodeRel . nodeMaker ( x ) . toString ( ) ) ; Relation r = nodeRel . baseRelation ( ) ; assertEquals ( Equality . createAttributeEquality ( t1table1id , t2table1id ) , r . condition ( ) ) ; } private NodeRelation translate1 ( String pattern , String mappingFile ) { return translate1 ( triplesToList ( pattern ) , mappingFile ) ; } private NodeRelation translate1 ( List < Triple > triplePatterns , String mappingFile ) { return translate1 ( triplePatterns , MapFixture . loadPropertyBridges ( mappingFile ) ) ; } private NodeRelation translate1 ( String pattern , Collection < TripleRelation > tripleRelations ) { return translate1 ( triplesToList ( pattern ) , tripleRelations ) ; } private NodeRelation translate1 ( List < Triple > triplePatterns , Collection < TripleRelation > tripleRelations ) { Collection < NodeRelation > rels = new GraphPatternTranslator ( triplePatterns , tripleRelations , true ) . translate ( ) ; if ( rels . isEmpty ( ) ) return null ; assertEquals ( , rels . size ( ) ) ; return ( NodeRelation ) rels . iterator ( ) . next ( ) ; } private NodeRelation [ ] translate ( String pattern , String mappingFile ) { Collection < NodeRelation > rels = new GraphPatternTranslator ( triplesToList ( pattern ) , MapFixture . loadPropertyBridges ( mappingFile ) , true ) . translate ( ) ; return ( NodeRelation [ ] ) rels . toArray ( new NodeRelation [ rels . size ( ) ] ) ; } private List < Triple > triplesToList ( String pattern ) { List < Triple > results = new ArrayList < Triple > ( ) ; String [ ] parts = pattern . split ( "" ) ; for ( int i = ; i < parts . length ; i ++ ) { results . add ( NodeCreateUtils . createTriple ( MapFixture . prefixes ( ) , parts [ i ] ) ) ; } return results ; } } package de . fuberlin . wiwiss . d2rq . engine ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( GraphPatternTranslatorTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . map ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . ResourceFactory ; import de . fuberlin . wiwiss . d2rq . map . TranslationTable . Translation ; import de . fuberlin . wiwiss . d2rq . values . Translator ; public class TranslationTableTest extends TestCase { Resource table1 = ResourceFactory . createResource ( "" ) ; public void testNewTranslationTableIsEmpty ( ) { TranslationTable table = new TranslationTable ( table1 ) ; assertEquals ( , table . size ( ) ) ; } public void testTranslationTableIsSizeOneAfterAddingOneTranslation ( ) { TranslationTable table = new TranslationTable ( table1 ) ; table . addTranslation ( "" , "" ) ; assertEquals ( , table . size ( ) ) ; } public void testTranslationTableTranslator ( ) { TranslationTable table = new TranslationTable ( table1 ) ; table . addTranslation ( "" , "" ) ; table . addTranslation ( "" , "" ) ; table . addTranslation ( "" , "" ) ; Translator translator = table . translator ( ) ; assertEquals ( "" , translator . toRDFValue ( "" ) ) ; assertEquals ( "" , translator . toRDFValue ( "" ) ) ; assertEquals ( "" , translator . toDBValue ( "" ) ) ; assertEquals ( "" , translator . toDBValue ( "" ) ) ; } public void testUndefinedTranslation ( ) { TranslationTable table = new TranslationTable ( table1 ) ; table . addTranslation ( "" , "" ) ; Translator translator = table . translator ( ) ; assertNull ( translator . toRDFValue ( "" ) ) ; assertNull ( translator . toDBValue ( "" ) ) ; } public void testNullTranslation ( ) { TranslationTable table = new TranslationTable ( table1 ) ; table . addTranslation ( "" , "" ) ; Translator translator = table . translator ( ) ; assertNull ( translator . toRDFValue ( null ) ) ; assertNull ( translator . toDBValue ( null ) ) ; } public void testTranslationsWithSameValuesAreEqual ( ) { Translation t1 = new Translation ( "" , "" ) ; Translation t2 = new Translation ( "" , "" ) ; assertEquals ( t1 , t2 ) ; assertEquals ( t1 . hashCode ( ) , t2 . hashCode ( ) ) ; } public void testTranslationsWithDifferentValuesAreNotEqual ( ) { Translation t1 = new Translation ( "" , "" ) ; Translation t2 = new Translation ( "" , "" ) ; Translation t3 = new Translation ( "" , "" ) ; assertFalse ( t1 . equals ( t2 ) ) ; assertFalse ( t2 . equals ( t1 ) ) ; assertFalse ( t1 . hashCode ( ) == t2 . hashCode ( ) ) ; assertFalse ( t1 . equals ( t3 ) ) ; assertFalse ( t3 . equals ( t1 ) ) ; assertFalse ( t1 . hashCode ( ) == t3 . hashCode ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . map ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . sql . DummyDB ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; public class CompileTest extends TestCase { private Model model ; private Mapping mapping ; private Database database ; private ClassMap employees ; private PropertyBridge managerBridge ; private ClassMap cities ; private PropertyBridge citiesTypeBridge ; private PropertyBridge citiesNameBridge ; private ClassMap countries ; private PropertyBridge countriesTypeBridge ; public void setUp ( ) { this . model = ModelFactory . createDefaultModel ( ) ; this . mapping = new Mapping ( ) ; this . database = new Database ( this . model . createResource ( ) ) ; database . useConnectedDB ( new DummyDB ( ) ) ; this . mapping . addDatabase ( this . database ) ; employees = createClassMap ( "" ) ; employees . addAlias ( "" ) ; employees . addJoin ( "" ) ; employees . addCondition ( "" ) ; managerBridge = createPropertyBridge ( employees , "" ) ; managerBridge . addAlias ( "" ) ; managerBridge . setRefersToClassMap ( this . employees ) ; managerBridge . addJoin ( "" ) ; cities = createClassMap ( "" ) ; citiesTypeBridge = createPropertyBridge ( cities , RDF . type . getURI ( ) ) ; citiesTypeBridge . setConstantValue ( model . createResource ( "" ) ) ; citiesNameBridge = createPropertyBridge ( cities , "" ) ; citiesNameBridge . setColumn ( "" ) ; countries = createClassMap ( "" ) ; countries . setContainsDuplicates ( true ) ; countriesTypeBridge = createPropertyBridge ( countries , RDF . type . getURI ( ) ) ; countriesTypeBridge . setConstantValue ( model . createResource ( "" ) ) ; } private ClassMap createClassMap ( String uriPattern ) { ClassMap result = new ClassMap ( this . model . createResource ( ) ) ; result . setDatabase ( this . database ) ; result . setURIPattern ( uriPattern ) ; this . mapping . addClassMap ( result ) ; return result ; } private PropertyBridge createPropertyBridge ( ClassMap classMap , String propertyURI ) { PropertyBridge result = new PropertyBridge ( this . model . createResource ( ) ) ; result . setBelongsToClassMap ( classMap ) ; result . addProperty ( this . model . createProperty ( propertyURI ) ) ; classMap . addPropertyBridge ( result ) ; return result ; } public void testAttributesInRefersToClassMapAreRenamed ( ) { TripleRelation relation = ( TripleRelation ) this . managerBridge . toTripleRelations ( ) . iterator ( ) . next ( ) ; assertEquals ( "" , relation . nodeMaker ( TripleRelation . SUBJECT ) . toString ( ) ) ; assertEquals ( "" , relation . nodeMaker ( TripleRelation . OBJECT ) . toString ( ) ) ; } public void testJoinConditionsInRefersToClassMapAreRenamed ( ) { TripleRelation relation = ( TripleRelation ) this . managerBridge . toTripleRelations ( ) . iterator ( ) . next ( ) ; Set < String > joinsToString = new HashSet < String > ( ) ; for ( Join join : relation . baseRelation ( ) . joinConditions ( ) ) { joinsToString . add ( join . toString ( ) ) ; } assertEquals ( new HashSet < String > ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) , joinsToString ) ; } public void testConditionInRefersToClassMapIsRenamed ( ) { TripleRelation relation = ( TripleRelation ) this . managerBridge . toTripleRelations ( ) . iterator ( ) . next ( ) ; assertEquals ( "" , relation . baseRelation ( ) . condition ( ) . toString ( ) ) ; } public void testAliasesInRefersToClassMapAreRenamed ( ) { TripleRelation relation = ( TripleRelation ) this . managerBridge . toTripleRelations ( ) . iterator ( ) . next ( ) ; assertEquals ( new AliasMap ( Arrays . asList ( new Alias [ ] { SQL . parseAlias ( "" ) , SQL . parseAlias ( "" ) } ) ) , relation . baseRelation ( ) . aliases ( ) ) ; } public void testSimpleTypeBridgeContainsNoDuplicates ( ) { assertTrue ( this . citiesTypeBridge . buildRelation ( ) . isUnique ( ) ) ; } public void testSimpleColumnBridgeContainsNoDuplicates ( ) { assertTrue ( this . citiesNameBridge . buildRelation ( ) . isUnique ( ) ) ; } public void testBridgeWithDuplicateClassMapContainsDuplicates ( ) { assertFalse ( this . countriesTypeBridge . buildRelation ( ) . isUnique ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . map ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( CompileTest . class ) ; suite . addTestSuite ( ConstantValueClassMapTest . class ) ; suite . addTestSuite ( MappingTest . class ) ; suite . addTestSuite ( TranslationTableTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . map ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . ResourceFactory ; import de . fuberlin . wiwiss . d2rq . D2RQException ; public class MappingTest extends TestCase { private final static Resource database1 = ResourceFactory . createResource ( "" ) ; private final static Resource database2 = ResourceFactory . createResource ( "" ) ; private final static Resource classMap1 = ResourceFactory . createResource ( "" ) ; public void testNewMappingWithResource ( ) { Mapping m = new Mapping ( "" ) ; assertEquals ( ResourceFactory . createResource ( "" ) , m . resource ( ) ) ; } public void testNewMappingWithoutResource ( ) { Mapping m = new Mapping ( ) ; assertTrue ( m . resource ( ) . isAnon ( ) ) ; } public void testNoDatabasesInitially ( ) { Mapping m = new Mapping ( ) ; assertTrue ( m . databases ( ) . isEmpty ( ) ) ; assertNull ( m . database ( database1 ) ) ; } public void testReturnAddedDatabase ( ) { Mapping m = new Mapping ( ) ; Database db = new Database ( database1 ) ; m . addDatabase ( db ) ; assertEquals ( Collections . singletonList ( db ) , new ArrayList < Database > ( m . databases ( ) ) ) ; assertEquals ( db , m . database ( database1 ) ) ; } public void testNoDatabaseCausesValidationError ( ) { Mapping m = new Mapping ( ) ; try { m . validate ( ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . MAPPING_NO_DATABASE , ex . errorCode ( ) ) ; } } public void testReturnResourceFromNewClassMap ( ) { ClassMap c = new ClassMap ( classMap1 ) ; assertEquals ( classMap1 , c . resource ( ) ) ; } public void testNewClassMapHasNoDatabase ( ) { ClassMap c = new ClassMap ( classMap1 ) ; assertNull ( c . database ( ) ) ; } public void testClassMapReturnsAssignedDatabase ( ) { Database db = new Database ( database1 ) ; ClassMap c = new ClassMap ( classMap1 ) ; c . setDatabase ( db ) ; assertEquals ( db , c . database ( ) ) ; } public void testMultipleDatabasesForClassMapCauseValidationError ( ) { Mapping m = new Mapping ( ) ; ClassMap c = new ClassMap ( classMap1 ) ; try { Database db1 = new Database ( database1 ) ; c . setDatabase ( db1 ) ; Database db2 = new Database ( database2 ) ; c . setDatabase ( db2 ) ; m . addClassMap ( c ) ; m . validate ( ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . CLASSMAP_DUPLICATE_DATABASE , ex . errorCode ( ) ) ; } } public void testClassMapWithoutDatabaseCausesValidationError ( ) { Mapping m = new Mapping ( ) ; ClassMap c = new ClassMap ( classMap1 ) ; try { Database db1 = new Database ( database1 ) ; db1 . setJDBCDSN ( "" ) ; db1 . setJDBCDriver ( "" ) ; m . addDatabase ( db1 ) ; m . addClassMap ( c ) ; m . validate ( ) ; } catch ( D2RQException ex ) { assertEquals ( D2RQException . CLASSMAP_NO_DATABASE , ex . errorCode ( ) ) ; } } public void testNewMappingHasNoClassMaps ( ) { Mapping m = new Mapping ( ) ; assertTrue ( m . classMapResources ( ) . isEmpty ( ) ) ; assertNull ( m . classMap ( classMap1 ) ) ; } public void testReturnAddedClassMaps ( ) { Mapping m = new Mapping ( ) ; ClassMap c = new ClassMap ( classMap1 ) ; m . addClassMap ( c ) ; assertEquals ( Collections . singleton ( classMap1 ) , new HashSet < Resource > ( m . classMapResources ( ) ) ) ; assertEquals ( c , m . classMap ( classMap1 ) ) ; } } package de . fuberlin . wiwiss . d2rq . map ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . D2RQException ; public class ConstantValueClassMapTest extends TestCase { private Model model ; private Mapping mapping ; private Database database ; private ClassMap concept ; private PropertyBridge conceptTypeBridge ; private ClassMap collection ; private PropertyBridge collectionTypeBridge ; private PropertyBridge memberBridge ; private ClassMap createClassMap ( String uriPattern ) { ClassMap result = new ClassMap ( this . model . createResource ( ) ) ; result . setDatabase ( this . database ) ; result . setURIPattern ( uriPattern ) ; this . mapping . addClassMap ( result ) ; return result ; } private ClassMap createConstantClassMap ( String uri ) { ClassMap result = new ClassMap ( this . model . createResource ( ) ) ; result . setDatabase ( this . database ) ; result . setConstantValue ( this . model . createResource ( uri ) ) ; this . mapping . addClassMap ( result ) ; return result ; } private PropertyBridge createPropertyBridge ( ClassMap classMap , String propertyURI ) { PropertyBridge result = new PropertyBridge ( this . model . createResource ( ) ) ; result . setBelongsToClassMap ( classMap ) ; result . addProperty ( this . model . createProperty ( propertyURI ) ) ; classMap . addPropertyBridge ( result ) ; return result ; } public void setUp ( ) { this . model = ModelFactory . createDefaultModel ( ) ; this . mapping = new Mapping ( ) ; this . database = new Database ( this . model . createResource ( ) ) ; this . mapping . addDatabase ( this . database ) ; concept = createClassMap ( "" ) ; conceptTypeBridge = createPropertyBridge ( concept , RDF . type . getURI ( ) ) ; conceptTypeBridge . setConstantValue ( model . createResource ( "" ) ) ; collection = createConstantClassMap ( "" ) ; collectionTypeBridge = createPropertyBridge ( collection , RDF . type . getURI ( ) ) ; collectionTypeBridge . setConstantValue ( model . createResource ( "" ) ) ; memberBridge = createPropertyBridge ( collection , "" ) ; memberBridge . setRefersToClassMap ( concept ) ; memberBridge . addCondition ( "" ) ; } public void testValidate ( ) { try { collection . validate ( ) ; } catch ( D2RQException e ) { fail ( "" ) ; } } } package de . fuberlin . wiwiss . d2rq ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . Collection ; import junit . framework . TestCase ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class DBConnectionTest extends TestCase { private Model mapModel ; private Collection < Database > databases ; private Database firstDatabase ; private ConnectedDB cdb ; private String simplestQuery ; private String mediumQuery ; private String complexQuery ; protected void setUp ( ) throws Exception { mapModel = ModelFactory . createDefaultModel ( ) ; mapModel . read ( D2RQTestSuite . ISWC_MAP , "" , "" ) ; MapParser parser = new MapParser ( mapModel , null ) ; databases = parser . parse ( ) . databases ( ) ; firstDatabase = ( Database ) databases . iterator ( ) . next ( ) ; simplestQuery = "" ; mediumQuery = "" ; complexQuery = "" ; } protected void tearDown ( ) throws Exception { mapModel . close ( ) ; if ( cdb != null ) cdb . close ( ) ; } public void testConnections ( ) throws SQLException { for ( Database db : databases ) { cdb = db . connectedDB ( ) ; Connection c = cdb . connection ( ) ; String result = performQuery ( c , simplestQuery ) ; assertEquals ( result , "" ) ; } } private static String performQuery ( Connection c , String theQuery ) throws SQLException { String query_results = "" ; Statement s ; ResultSet rs ; s = c . createStatement ( ) ; rs = s . executeQuery ( theQuery ) ; int col = ( rs . getMetaData ( ) ) . getColumnCount ( ) ; while ( rs . next ( ) ) { for ( int pos = ; pos <= col ; pos ++ ) { if ( pos > ) query_results += "" ; query_results += rs . getString ( pos ) ; } } rs . close ( ) ; s . close ( ) ; return query_results ; } public Connection manuallyConfiguredConnection ( ) { String driverClass ; String url ; String name ; String pass ; driverClass = "" ; url = "" ; name = "" ; pass = "" ; Connection c = null ; try { Class . forName ( driverClass ) ; c = DriverManager . getConnection ( url , name , pass ) ; return c ; } catch ( Exception x ) { x . printStackTrace ( ) ; } return null ; } public void xtestManuallyConfiguredConnection ( ) throws SQLException { Connection c = manuallyConfiguredConnection ( ) ; String query = "" ; String query_results = performQuery ( c , query ) ; c . close ( ) ; assertEquals ( query_results , "" ) ; } public void testDistinct ( ) throws SQLException { cdb = firstDatabase . connectedDB ( ) ; Connection c = cdb . connection ( ) ; String nonDistinct = "" ; String distinct = "" ; String distinctResult = performQuery ( c , distinct ) ; String nonDistinctResult = performQuery ( c , nonDistinct ) ; c . close ( ) ; assertEquals ( distinctResult , nonDistinctResult ) ; } public void testMedium ( ) throws SQLException { cdb = firstDatabase . connectedDB ( ) ; Connection c = cdb . connection ( ) ; String query = mediumQuery ; String query_results = performQuery ( c , query ) ; c . close ( ) ; assertNotNull ( query_results ) ; } public void testLongComplexSQLQuery ( ) throws SQLException { cdb = firstDatabase . connectedDB ( ) ; Connection c = cdb . connection ( ) ; String query = complexQuery ; try { performQuery ( c , query ) ; } catch ( SQLException e ) { fail ( "" ) ; } finally { c . close ( ) ; } } } package de . fuberlin . wiwiss . d2rq . values ; import java . util . Arrays ; import java . util . Collections ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; public class ValueMakerTest extends TestCase { private final static Attribute foo_col1 = new Attribute ( null , "" , "" ) ; private final static Attribute foo_col2 = new Attribute ( null , "" , "" ) ; public void testBlankNodeIDToString ( ) { BlankNodeID b = new BlankNodeID ( "" , Arrays . asList ( new Attribute [ ] { foo_col1 , foo_col2 } ) ) ; assertEquals ( "" , b . toString ( ) ) ; } public void testColumnToString ( ) { assertEquals ( "" , new Column ( foo_col1 ) . toString ( ) ) ; } public void testPatternToString ( ) { assertEquals ( "" , new Pattern ( "" ) . toString ( ) ) ; } public void testValueDecoratorWithoutTranslatorToString ( ) { assertEquals ( "" , new ValueDecorator ( new Column ( foo_col1 ) , Collections . singletonList ( ValueDecorator . maxLengthConstraint ( ) ) ) . toString ( ) ) ; } public void testMaxLengthConstraint ( ) { DummyValueMaker source = new DummyValueMaker ( "" ) ; ValueDecorator values = new ValueDecorator ( source , Collections . singletonList ( ValueDecorator . maxLengthConstraint ( ) ) ) ; assertFalse ( matches ( values , null ) ) ; assertTrue ( matches ( values , "" ) ) ; assertTrue ( matches ( values , "" ) ) ; assertTrue ( matches ( values , "" ) ) ; assertFalse ( matches ( values , "" ) ) ; source . setSelectCondition ( Expression . FALSE ) ; assertFalse ( matches ( values , "" ) ) ; } public void testContainsConstraint ( ) { DummyValueMaker source = new DummyValueMaker ( "" ) ; ValueDecorator values = new ValueDecorator ( source , Collections . singletonList ( ValueDecorator . containsConstraint ( "" ) ) ) ; assertFalse ( matches ( values , null ) ) ; assertTrue ( matches ( values , "" ) ) ; assertTrue ( matches ( values , "" ) ) ; assertFalse ( matches ( values , "" ) ) ; assertFalse ( matches ( values , "" ) ) ; values = new ValueDecorator ( source , Collections . singletonList ( ValueDecorator . containsConstraint ( "" ) ) ) ; assertFalse ( matches ( values , null ) ) ; assertTrue ( matches ( values , "" ) ) ; assertTrue ( matches ( values , "" ) ) ; source . setSelectCondition ( Expression . FALSE ) ; assertFalse ( matches ( values , "" ) ) ; } public void testRegexConstraint ( ) { DummyValueMaker source = new DummyValueMaker ( "" ) ; ValueDecorator values = new ValueDecorator ( source , Collections . singletonList ( ValueDecorator . regexConstraint ( "" ) ) ) ; assertFalse ( matches ( values , null ) ) ; assertTrue ( matches ( values , "" ) ) ; assertFalse ( matches ( values , "" ) ) ; source . setSelectCondition ( Expression . FALSE ) ; assertFalse ( matches ( values , "" ) ) ; } public void testColumnDoesNotMatchNull ( ) { Column column = new Column ( foo_col1 ) ; assertFalse ( matches ( column , null ) ) ; } public void testPatternDoesNotMatchNull ( ) { Pattern pattern = new Pattern ( "" ) ; assertFalse ( matches ( pattern , null ) ) ; } public void testBlankNodeIDDoesNotMatchNull ( ) { BlankNodeID bNodeID = new BlankNodeID ( "" , Collections . singletonList ( foo_col1 ) ) ; assertFalse ( matches ( bNodeID , null ) ) ; } private boolean matches ( ValueMaker valueMaker , String value ) { return ! valueMaker . valueExpression ( value ) . isFalse ( ) ; } } package de . fuberlin . wiwiss . d2rq . values ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( PatternTest . class ) ; suite . addTestSuite ( ValueMakerTest . class ) ; return suite ; } } package de . fuberlin . wiwiss . d2rq . values ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import junit . framework . TestCase ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . expr . Conjunction ; import de . fuberlin . wiwiss . d2rq . expr . Constant ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; import de . fuberlin . wiwiss . d2rq . sql . ResultRowMap ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; public class PatternTest extends TestCase { private final static Attribute col1 = new Attribute ( null , "" , "" ) ; private final static Attribute col2 = new Attribute ( null , "" , "" ) ; private final static Attribute col3 = new Attribute ( null , "" , "" ) ; private final static Attribute col4 = new Attribute ( null , "" , "" ) ; private final static Attribute col5 = new Attribute ( null , "" , "" ) ; private ResultRow row ; public void setUp ( ) { this . row = row ( "" ) ; } public void testSimple ( ) { Pattern pattern = new Pattern ( "" ) ; assertEquals ( "" , pattern . makeValue ( row ( "" ) ) ) ; } public void testNull ( ) { Pattern pattern = new Pattern ( "" ) ; assertNull ( pattern . makeValue ( row ( "" ) ) ) ; } public void testPatternSyntax ( ) { assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; assertPattern ( "" , "" ) ; } public void testMatches ( ) { Pattern p = new Pattern ( "" ) ; assertTrue ( matches ( p , "" ) ) ; } public void testMatchesTrivialPattern ( ) { Pattern p = new Pattern ( "" ) ; assertPatternValues ( p , "" , new HashMap < String , String > ( ) ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , null ) ) ; } public void testMatchesMiniPattern ( ) { Pattern p = new Pattern ( "" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; assertFalse ( matches ( p , null ) ) ; } public void testMatchesPatternContainingNewlines ( ) { Pattern p = new Pattern ( "" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; } public void testMagicRegexCharactersCauseNoProblems ( ) { Pattern p = new Pattern ( "" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; assertFalse ( matches ( p , "" ) ) ; } public void testMatchesOneColumnPattern ( ) { Pattern p = new Pattern ( "" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; } public void testMatchesTwoColumnPattern ( ) { Pattern p = new Pattern ( "" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; } public void testMatchesPatternStartingWithColumn ( ) { Pattern p = new Pattern ( "" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; assertFalse ( matches ( p , "" ) ) ; } public void testMatchesPatternEndingWithColumn ( ) { Pattern p = new Pattern ( "" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; assertPatternValues ( p , "" , map ) ; } public void testPartsIteratorSingleLiteral ( ) { Iterator < Object > it = new Pattern ( "" ) . partsIterator ( ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertFalse ( it . hasNext ( ) ) ; } public void testPartsIteratorFirstLiteralThenColumn ( ) { Iterator < Object > it = new Pattern ( "" ) . partsIterator ( ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( col1 , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertFalse ( it . hasNext ( ) ) ; } public void testPartsIteratorFirstColumnThenLiteral ( ) { Iterator < Object > it = new Pattern ( "" ) . partsIterator ( ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( col1 , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertFalse ( it . hasNext ( ) ) ; } public void testPartsIteratorSeveralColumns ( ) { Iterator < Object > it = new Pattern ( "" ) . partsIterator ( ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( col1 , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( col2 , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertFalse ( it . hasNext ( ) ) ; } public void testPartsIteratorAdjacentColumns ( ) { Iterator < Object > it = new Pattern ( "" ) . partsIterator ( ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( col1 , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( col2 , it . next ( ) ) ; assertTrue ( it . hasNext ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertFalse ( it . hasNext ( ) ) ; } public void testToString ( ) { assertEquals ( "" , new Pattern ( "" ) . toString ( ) ) ; } public void testSamePatternsAreEqual ( ) { Pattern p1 = new Pattern ( "" ) ; Pattern p2 = new Pattern ( "" ) ; assertEquals ( p1 , p2 ) ; assertEquals ( p2 , p1 ) ; assertEquals ( p1 . hashCode ( ) , p2 . hashCode ( ) ) ; } public void testPatternsWithDifferentColumnsAreNotEqual ( ) { Pattern p1 = new Pattern ( "" ) ; Pattern p2 = new Pattern ( "" ) ; assertFalse ( p1 . equals ( p2 ) ) ; assertFalse ( p2 . equals ( p1 ) ) ; assertFalse ( p1 . hashCode ( ) == p2 . hashCode ( ) ) ; } public void testPatternsWithDifferentLiteralPartsAreNotEqual ( ) { Pattern p1 = new Pattern ( "" ) ; Pattern p2 = new Pattern ( "" ) ; assertFalse ( p1 . equals ( p2 ) ) ; assertFalse ( p2 . equals ( p1 ) ) ; assertFalse ( p1 . hashCode ( ) == p2 . hashCode ( ) ) ; } public void testIdenticalPatternsAreCompatible ( ) { Pattern p1 = new Pattern ( "" ) ; Pattern p2 = new Pattern ( "" ) ; assertTrue ( p1 . isEquivalentTo ( p2 ) ) ; assertTrue ( p2 . isEquivalentTo ( p1 ) ) ; } public void testPatternsWithDifferentColumnNamesAreCompatible ( ) { Pattern p1 = new Pattern ( "" ) ; Pattern p2 = new Pattern ( "" ) ; assertTrue ( p1 . isEquivalentTo ( p2 ) ) ; assertTrue ( p2 . isEquivalentTo ( p1 ) ) ; } public void testPatternsWithDifferentLiteralPartsAreNotCompatible ( ) { Pattern p1 = new Pattern ( "" ) ; Pattern p2 = new Pattern ( "" ) ; assertFalse ( p1 . isEquivalentTo ( p2 ) ) ; assertFalse ( p2 . isEquivalentTo ( p1 ) ) ; } public void testMultiColumnPatternsWithDifferentLiteralPartsAreNotCompatible ( ) { Pattern p1 = new Pattern ( "" ) ; Pattern p2 = new Pattern ( "" ) ; assertFalse ( p1 . isEquivalentTo ( p2 ) ) ; assertFalse ( p2 . isEquivalentTo ( p1 ) ) ; } public void testLiteralPatternsMatchTrivialRegex ( ) { assertTrue ( new Pattern ( "" ) . literalPartsMatchRegex ( "" ) ) ; } public void testLiteralPatternsDontMatchTrivialRegex ( ) { assertFalse ( new Pattern ( "" ) . literalPartsMatchRegex ( "" ) ) ; } public void testLiteralPatternRegexIsAnchored ( ) { assertFalse ( new Pattern ( "" ) . literalPartsMatchRegex ( "" ) ) ; } public void testLiteralPatternRegexMultipleParts ( ) { assertTrue ( new Pattern ( "" ) . literalPartsMatchRegex ( "" ) ) ; } public void testLiteralPatternRegexMatchesOnlyLiteralParts ( ) { assertTrue ( new Pattern ( "" ) . literalPartsMatchRegex ( "" ) ) ; } public void testPatternURLEncode ( ) { Pattern p = new Pattern ( "" ) ; assertPattern ( "" , p . makeValue ( row ( "" ) ) ) ; assertPatternValues ( p , "" , Collections . singletonMap ( "" , "" ) ) ; } public void testPatternEncode ( ) { Pattern p = new Pattern ( "" ) ; assertPattern ( "" , p . makeValue ( row ( "" ) ) ) ; assertPattern ( "" , p . makeValue ( row ( "" ) ) ) ; assertPattern ( "" , p . makeValue ( row ( "" ) ) ) ; assertPatternValues ( p , "" , Collections . singletonMap ( "" , "" ) ) ; } public void testPatternURLEncodeIllegal ( ) { Pattern p = new Pattern ( "" ) ; assertFalse ( matches ( p , "" ) ) ; } public void testPatternURLify ( ) { Pattern p = new Pattern ( "" ) ; assertPattern ( "" , p . makeValue ( row ( "" ) ) ) ; assertPatternValues ( p , "" , Collections . singletonMap ( "" , "" ) ) ; } public void testPatternURLifyEscapeUnderscore ( ) { Pattern p = new Pattern ( "" ) ; assertPattern ( "" , p . makeValue ( row ( "" ) ) ) ; assertPatternValues ( p , "" , Collections . singletonMap ( "" , "" ) ) ; } public void testTrivialPatternFirstPart ( ) { assertEquals ( "" , new Pattern ( "" ) . firstLiteralPart ( ) ) ; } public void testTrivialPatternLastPart ( ) { assertEquals ( "" , new Pattern ( "" ) . lastLiteralPart ( ) ) ; } public void testEmptyFirstPart ( ) { assertEquals ( "" , new Pattern ( "" ) . firstLiteralPart ( ) ) ; } public void testEmptyLastPart ( ) { assertEquals ( "" , new Pattern ( "" ) . lastLiteralPart ( ) ) ; } public void testFirstAndLastPart ( ) { assertEquals ( "" , new Pattern ( "" ) . firstLiteralPart ( ) ) ; assertEquals ( "" , new Pattern ( "" ) . lastLiteralPart ( ) ) ; } private void assertPattern ( String expected , String pattern ) { Pattern p = new Pattern ( pattern ) ; assertEquals ( expected , p . makeValue ( this . row ) ) ; } private void assertPatternValues ( Pattern pattern , String value , Map < String , String > expectedValues ) { assertTrue ( matches ( pattern , value ) ) ; Collection < Expression > expressions = new HashSet < Expression > ( ) ; for ( String attributeName : expectedValues . keySet ( ) ) { String attributeValue = ( String ) expectedValues . get ( attributeName ) ; Attribute attribute = SQL . parseAttribute ( attributeName ) ; expressions . add ( Equality . create ( new AttributeExpr ( attribute ) , new Constant ( attributeValue , attribute ) ) ) ; } Expression expr = Conjunction . create ( expressions ) ; assertEquals ( expr , pattern . valueExpression ( value ) ) ; } private boolean matches ( ValueMaker valueMaker , String value ) { return ! valueMaker . valueExpression ( value ) . isFalse ( ) ; } private ResultRow row ( String spec ) { String [ ] parts = spec . split ( "" , - ) ; Attribute [ ] columns = { col1 , col2 , col3 , col4 , col5 } ; Map < ProjectionSpec , String > result = new HashMap < ProjectionSpec , String > ( ) ; for ( int i = ; i < parts . length && i < columns . length ; i ++ ) { result . put ( columns [ i ] , parts [ i ] ) ; } return new ResultRowMap ( result ) ; } } package de . fuberlin . wiwiss . d2rq . values ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public class DummyValueMaker implements ValueMaker { private String returnValue = null ; private Set < ProjectionSpec > projectionSpecs ; private Expression selectCondition = Expression . TRUE ; public DummyValueMaker ( String value ) { this . returnValue = value ; } public void describeSelf ( NodeSetFilter c ) { } public void setValue ( String value ) { this . returnValue = value ; } public void setProjectionSpecs ( Set < ProjectionSpec > columns ) { this . projectionSpecs = columns ; } public void setSelectCondition ( Expression selectCondition ) { this . selectCondition = selectCondition ; } public Set < ProjectionSpec > projectionSpecs ( ) { return this . projectionSpecs ; } public Expression valueExpression ( String value ) { return selectCondition ; } public String makeValue ( ResultRow row ) { return this . returnValue ; } public ValueMaker renameAttributes ( ColumnRenamer renamer ) { return this ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return Collections . emptyList ( ) ; } } package de . fuberlin . wiwiss . d2rq . nodes ; import java . util . Collections ; import junit . framework . TestCase ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . rdf . model . AnonId ; import com . hp . hpl . jena . rdf . model . ResourceFactory ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . expr . SQLExpression ; import de . fuberlin . wiwiss . d2rq . map . TranslationTable ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . values . BlankNodeID ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; import de . fuberlin . wiwiss . d2rq . values . Translator ; public class NodeSetTest extends TestCase { private final static Attribute table1foo = SQL . parseAttribute ( "" ) ; private final static Attribute table1bar = SQL . parseAttribute ( "" ) ; private final static Attribute alias1foo = SQL . parseAttribute ( "" ) ; private final static BlankNodeID fooBlankNodeID = new BlankNodeID ( "" , Collections . singletonList ( table1foo ) ) ; private final static BlankNodeID fooBlankNodeID2 = new BlankNodeID ( "" , Collections . singletonList ( alias1foo ) ) ; private final static BlankNodeID barBlankNodeID = new BlankNodeID ( "" , Collections . singletonList ( table1foo ) ) ; private final static Pattern pattern1 = new Pattern ( "" ) ; private final static Pattern pattern1aliased = new Pattern ( "" ) ; private final static Pattern pattern2 = new Pattern ( "" ) ; private final static Pattern pattern3 = new Pattern ( "" ) ; private final static Expression expression1 = SQLExpression . create ( "" ) ; private final static Expression expression2 = SQLExpression . create ( "" ) ; private NodeSetConstraintBuilder nodes ; public void setUp ( ) { nodes = new NodeSetConstraintBuilder ( ) ; } public void testInitiallyNotEmpty ( ) { assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitToURIsNotEmpty ( ) { nodes . limitToURIs ( ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitToLiteralsNotEmpty ( ) { nodes . limitToLiterals ( null , null ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitToBlankNodes ( ) { nodes . limitToBlankNodes ( ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitToFixedNodeNotEmpty ( ) { nodes . limitTo ( RDF . Nodes . type ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitToEmptySetIsEmpty ( ) { nodes . limitToEmptySet ( ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testLimitValuesToConstantNotEmpty ( ) { nodes . limitValues ( "" ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitValuesToAttributeNotEmpty ( ) { nodes . limitValuesToAttribute ( table1foo ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitValuesToPatternNotEmpty ( ) { nodes . limitValuesToPattern ( pattern1 ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitValuesToBlankNodeIDNotEmpty ( ) { nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testLimitValuesToExpressionNotEmpty ( ) { nodes . limitValuesToExpression ( expression1 ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testURIsAndLiteralsEmpty ( ) { nodes . limitToURIs ( ) ; nodes . limitToLiterals ( null , null ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testURIsAndBlanksEmpty ( ) { nodes . limitToURIs ( ) ; nodes . limitToBlankNodes ( ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testBlanksAndLiteralsEmpty ( ) { nodes . limitToBlankNodes ( ) ; nodes . limitToLiterals ( null , null ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testDifferentFixedBlanksEmpty ( ) { nodes . limitTo ( Node . createAnon ( new AnonId ( "" ) ) ) ; nodes . limitTo ( Node . createAnon ( new AnonId ( "" ) ) ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testDifferentFixedURIsEmpty ( ) { nodes . limitTo ( RDF . Nodes . type ) ; nodes . limitTo ( RDF . Nodes . Property ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testDifferentFixedLiteralsEmpty ( ) { nodes . limitTo ( Node . createLiteral ( "" ) ) ; nodes . limitTo ( Node . createLiteral ( "" ) ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testDifferentTypeFixedLiteralsEmpty ( ) { nodes . limitTo ( Node . createURI ( "" ) ) ; nodes . limitTo ( Node . createLiteral ( "" ) ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testDifferentConstantsEmpty ( ) { nodes . limitValues ( "" ) ; nodes . limitValues ( "" ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testFixedAndConstantEmpty ( ) { nodes . limitTo ( Node . createURI ( "" ) ) ; nodes . limitValues ( "" ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testFixedAndConstantNotEmpty ( ) { nodes . limitTo ( Node . createURI ( "" ) ) ; nodes . limitValues ( "" ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testDifferentLanguagesEmpty ( ) { nodes . limitToLiterals ( "" , null ) ; nodes . limitToLiterals ( "" , null ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testDifferentLanguagesFixedEmpty ( ) { nodes . limitTo ( Node . createLiteral ( "" , "" , null ) ) ; nodes . limitTo ( Node . createLiteral ( "" , "" , null ) ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testDifferentDatatypesEmpty ( ) { nodes . limitToLiterals ( null , XSDDatatype . XSDstring ) ; nodes . limitToLiterals ( null , XSDDatatype . XSDinteger ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testDifferentDatatypesFixedEmpty ( ) { nodes . limitTo ( Node . createLiteral ( "" , null , XSDDatatype . XSDstring ) ) ; nodes . limitTo ( Node . createLiteral ( "" , null , XSDDatatype . XSDinteger ) ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testSameAttributeTwiceNotEmpty ( ) { nodes . limitValuesToAttribute ( table1foo ) ; nodes . limitValuesToAttribute ( table1foo ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testAttributeAndConstantNotEmpty ( ) { nodes . limitValues ( "" ) ; nodes . limitValuesToAttribute ( table1foo ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testSameBlankNodeIDTwiceNotEmpty ( ) { nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testSamePatternTwiceNotEmpty ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValuesToPattern ( pattern1 ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testSameExpressionTwiceNotEmpty ( ) { nodes . limitValuesToExpression ( expression1 ) ; nodes . limitValuesToExpression ( expression1 ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testBlankNodesFromDifferentClassMapsEmpty ( ) { nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; nodes . limitValuesToBlankNodeID ( barBlankNodeID ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testBlankNodeAndConstantMatchNotEmpty ( ) { nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; nodes . limitTo ( Node . createAnon ( new AnonId ( "" ) ) ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testBlankNodeAndConstantNoMatchEmpty ( ) { nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; nodes . limitTo ( Node . createAnon ( new AnonId ( "" ) ) ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testIncompatiblePatternsEmpty ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValuesToPattern ( pattern2 ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testPatternAndConstantMatchNotEmpty ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValues ( "" ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testPatternAndConstantNoMatchEmpty ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValues ( "" ) ; assertTrue ( nodes . isEmpty ( ) ) ; } public void testAliasedPatternsNotEmpty ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValuesToPattern ( pattern1aliased ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testExpressionAndConstantNotEmpty ( ) { nodes . limitValues ( "" ) ; nodes . limitValuesToExpression ( expression1 ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testSameAttributeTwiceExpressionIsTrue ( ) { nodes . limitValuesToAttribute ( table1foo ) ; nodes . limitValuesToAttribute ( table1foo ) ; assertEquals ( Expression . TRUE , nodes . constraint ( ) ) ; } public void testAttributeAndConstantExpressionIsEquality ( ) { nodes . limitValues ( "" ) ; nodes . limitValuesToAttribute ( table1foo ) ; assertEquals ( Equality . createAttributeValue ( table1foo , "" ) , nodes . constraint ( ) ) ; } public void testSameBlankNodeIDTwiceExpressionIsTrue ( ) { nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; assertEquals ( Expression . TRUE , nodes . constraint ( ) ) ; } public void testSamePatternTwiceExpressionIsTrue ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValuesToPattern ( pattern1 ) ; assertEquals ( Expression . TRUE , nodes . constraint ( ) ) ; } public void testSameExpressionTwiceExpressionIsTrue ( ) { nodes . limitValuesToExpression ( expression1 ) ; nodes . limitValuesToExpression ( expression1 ) ; assertEquals ( Expression . TRUE , nodes . constraint ( ) ) ; } public void testBlankNodeAndConstantMatchExpressionIsEquality ( ) { nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; nodes . limitTo ( Node . createAnon ( new AnonId ( "" ) ) ) ; assertEquals ( Equality . createAttributeValue ( table1foo , "" ) , nodes . constraint ( ) ) ; } public void testPatternAndConstantMatchExpressionIsEquality ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValues ( "" ) ; assertEquals ( Equality . createAttributeValue ( table1foo , "" ) , nodes . constraint ( ) ) ; } public void testExpressionAndConstantExpressionIsEquality ( ) { nodes . limitValues ( "" ) ; nodes . limitValuesToExpression ( expression1 ) ; assertEquals ( Equality . createExpressionValue ( expression1 , "" ) , nodes . constraint ( ) ) ; } public void testTwoAttributesExpressionIsEquality ( ) { nodes . limitValuesToAttribute ( table1foo ) ; nodes . limitValuesToAttribute ( table1bar ) ; assertEquals ( Equality . createAttributeEquality ( table1foo , table1bar ) , nodes . constraint ( ) ) ; } public void testEquivalentPatternsExpressionIsEquality ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValuesToPattern ( pattern1aliased ) ; assertEquals ( Equality . createAttributeEquality ( table1foo , alias1foo ) , nodes . constraint ( ) ) ; } public void testTwoPatternsExpressionIsConcatEquality ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValuesToPattern ( pattern3 ) ; assertEquals ( "" + "" + "" + "" + "" + "" + "" + "" + "" , nodes . constraint ( ) . toString ( ) ) ; } public void testTwoExpressionsTranslatesToEquality ( ) { nodes . limitValuesToExpression ( expression1 ) ; nodes . limitValuesToExpression ( expression2 ) ; assertEquals ( Equality . create ( expression1 , expression2 ) , nodes . constraint ( ) ) ; } public void testEquivalentBlankNodeIDsExpressionIsEquality ( ) { nodes . limitValuesToBlankNodeID ( fooBlankNodeID ) ; nodes . limitValuesToBlankNodeID ( fooBlankNodeID2 ) ; assertEquals ( Equality . createAttributeEquality ( table1foo , alias1foo ) , nodes . constraint ( ) ) ; } public void testPatternEqualsAttribute ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValuesToAttribute ( table1bar ) ; assertEquals ( "" + "" + "" + "" + "" , nodes . constraint ( ) . toString ( ) ) ; } public void testExpressionEqualsAttribute ( ) { nodes . limitValuesToExpression ( expression1 ) ; nodes . limitValuesToAttribute ( table1bar ) ; assertEquals ( Equality . create ( expression1 , new AttributeExpr ( table1bar ) ) , nodes . constraint ( ) ) ; } public void testExpressionEqualsPattern ( ) { nodes . limitValuesToPattern ( pattern1 ) ; nodes . limitValuesToExpression ( expression1 ) ; assertEquals ( "" + "" + "" + "" + "" , nodes . constraint ( ) . toString ( ) ) ; } public void testANYNodeDoesNotLimit ( ) { nodes . limitTo ( Node . ANY ) ; nodes . limitTo ( RDF . Nodes . type ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testVariableNodeDoesNotLimit ( ) { nodes . limitTo ( Node . createVariable ( "" ) ) ; nodes . limitTo ( RDF . Nodes . type ) ; assertFalse ( nodes . isEmpty ( ) ) ; } public void testPatternDifferentColumnFunctionsUnsupported ( ) { nodes . limitValuesToPattern ( new Pattern ( "" ) ) ; nodes . limitValuesToPattern ( new Pattern ( "" ) ) ; assertFalse ( nodes . isEmpty ( ) ) ; assertTrue ( nodes . isUnsupported ( ) ) ; } public void testTranslatorUnsupported ( ) { nodes . setUsesTranslator ( Translator . IDENTITY ) ; nodes . setUsesTranslator ( new TranslationTable ( ResourceFactory . createResource ( ) ) . translator ( ) ) ; assertFalse ( nodes . isEmpty ( ) ) ; assertTrue ( nodes . isUnsupported ( ) ) ; } public void testPatternWithColumnFunctionAndColumnUnsupported ( ) { nodes . limitValuesToAttribute ( table1foo ) ; nodes . limitValuesToPattern ( new Pattern ( "" ) ) ; assertEquals ( "" , nodes . constraint ( ) . toString ( ) ) ; assertTrue ( nodes . isUnsupported ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . nodes ; import java . util . Arrays ; import junit . framework . TestCase ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . rdf . model . AnonId ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . values . BlankNodeID ; import de . fuberlin . wiwiss . d2rq . values . Column ; public class NodeMakerTest extends TestCase { private final static Attribute table_col1 = new Attribute ( null , "" , "" ) ; private final static Attribute table_col2 = new Attribute ( null , "" , "" ) ; public void testFixedNodeMakerToString ( ) { assertEquals ( "" , new FixedNodeMaker ( Node . createLiteral ( "" ) , true ) . toString ( ) ) ; assertEquals ( "" , new FixedNodeMaker ( Node . createLiteral ( "" , "" , null ) , true ) . toString ( ) ) ; assertEquals ( "" + XSDDatatype . XSDint . getURI ( ) + "" , new FixedNodeMaker ( Node . createLiteral ( "" , null , XSDDatatype . XSDint ) , true ) . toString ( ) ) ; assertEquals ( "" , new FixedNodeMaker ( Node . createAnon ( new AnonId ( "" ) ) , true ) . toString ( ) ) ; assertEquals ( "" , new FixedNodeMaker ( Node . createURI ( "" ) , true ) . toString ( ) ) ; } public void testBlankNodeMakerToString ( ) { BlankNodeID b = new BlankNodeID ( "" , Arrays . asList ( new Attribute [ ] { table_col1 , table_col2 } ) ) ; NodeMaker maker = new TypedNodeMaker ( TypedNodeMaker . BLANK , b , true ) ; assertEquals ( "" , maker . toString ( ) ) ; } public void testPlainLiteralMakerToString ( ) { TypedNodeMaker l = new TypedNodeMaker ( TypedNodeMaker . PLAIN_LITERAL , new Column ( table_col1 ) , true ) ; assertEquals ( "" , l . toString ( ) ) ; } public void testLanguageLiteralMakerToString ( ) { TypedNodeMaker l = new TypedNodeMaker ( TypedNodeMaker . languageLiteral ( "" ) , new Column ( table_col1 ) , true ) ; assertEquals ( "" , l . toString ( ) ) ; } public void testTypedLiteralMakerToString ( ) { TypedNodeMaker l = new TypedNodeMaker ( TypedNodeMaker . typedLiteral ( XSDDatatype . XSDstring ) , new Column ( table_col1 ) , true ) ; assertEquals ( "" , l . toString ( ) ) ; } public void testURIMakerToString ( ) { NodeMaker u = new TypedNodeMaker ( TypedNodeMaker . URI , new Column ( table_col1 ) , true ) ; assertEquals ( "" , u . toString ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . nodes ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( NodeSetTest . class ) ; suite . addTestSuite ( NodeMakerTest . class ) ; return suite ; } } package d2rq ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . PrintStream ; import jena . cmdline . ArgDecl ; import jena . cmdline . CommandLine ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . rdf . model . Model ; import de . fuberlin . wiwiss . d2rq . CommandLineTool ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; import de . fuberlin . wiwiss . d2rq . mapgen . MappingGenerator ; public class generate_mapping extends CommandLineTool { private final static Log log = LogFactory . getLog ( generate_mapping . class ) ; public static void main ( String [ ] args ) { new generate_mapping ( ) . process ( args ) ; } public void usage ( ) { System . err . println ( "" ) ; System . err . println ( ) ; printStandardArguments ( false ) ; System . err . println ( "" ) ; printConnectionOptions ( ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; System . exit ( ) ; } private ArgDecl outfileArg = new ArgDecl ( true , "" , "" , "" ) ; private ArgDecl vocabAsOutput = new ArgDecl ( false , "" , "" ) ; public void initArgs ( CommandLine cmd ) { cmd . add ( outfileArg ) ; cmd . add ( vocabAsOutput ) ; } public void run ( CommandLine cmd , SystemLoader loader ) throws IOException { if ( cmd . numItems ( ) == ) { loader . setJdbcURL ( cmd . getItem ( ) ) ; } PrintStream out ; if ( cmd . contains ( outfileArg ) ) { File f = new File ( cmd . getArg ( outfileArg ) . getValue ( ) ) ; log . info ( "" + f ) ; out = new PrintStream ( new FileOutputStream ( f ) ) ; } else { log . info ( "" ) ; out = System . out ; } MappingGenerator generator = loader . openMappingGenerator ( ) ; try { if ( cmd . contains ( vocabAsOutput ) ) { Model model = generator . vocabularyModel ( ) ; model . write ( out , "" ) ; } else { generator . writeMapping ( out ) ; } } finally { loader . closeMappingGenerator ( ) ; } } } package d2rq ; import jena . cmdline . ArgDecl ; import jena . cmdline . CommandLine ; import de . fuberlin . wiwiss . d2rq . CommandLineTool ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; import de . fuberlin . wiwiss . d2rq . server . JettyLauncher ; public class server extends CommandLineTool { public static void main ( String [ ] args ) { new server ( ) . process ( args ) ; } public void usage ( ) { System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; printStandardArguments ( true ) ; System . err . println ( ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" + SystemLoader . DEFAULT_BASE_URI + "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; System . err . println ( "" ) ; printConnectionOptions ( ) ; System . err . println ( ) ; } private ArgDecl portArg = new ArgDecl ( true , "" , "" ) ; private ArgDecl baseArg = new ArgDecl ( true , "" , "" ) ; private ArgDecl fastArg = new ArgDecl ( false , "" ) ; public void initArgs ( CommandLine cmd ) { cmd . add ( portArg ) ; cmd . add ( baseArg ) ; cmd . add ( fastArg ) ; } public void run ( CommandLine cmd , SystemLoader loader ) { if ( cmd . numItems ( ) == ) { loader . setMappingFileOrJdbcURL ( cmd . getItem ( ) ) ; } loader . setResourceStem ( "" ) ; if ( cmd . contains ( fastArg ) ) { loader . setFastMode ( true ) ; } if ( cmd . contains ( portArg ) ) { loader . setPort ( Integer . parseInt ( cmd . getArg ( portArg ) . getValue ( ) ) ) ; } if ( cmd . contains ( baseArg ) ) { loader . setSystemBaseURI ( cmd . getArg ( baseArg ) . getValue ( ) ) ; } loader . getModelD2RQ ( ) ; JettyLauncher launcher = loader . getJettyLauncher ( ) ; launcher . start ( ) ; } } package d2rq ; import java . io . IOException ; import jena . cmdline . ArgDecl ; import jena . cmdline . CommandLine ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . query . Query ; import com . hp . hpl . jena . query . QueryCancelledException ; import com . hp . hpl . jena . query . QueryExecution ; import com . hp . hpl . jena . query . QueryExecutionFactory ; import com . hp . hpl . jena . query . QueryFactory ; import com . hp . hpl . jena . sparql . resultset . ResultsFormat ; import com . hp . hpl . jena . sparql . util . QueryExecUtils ; import de . fuberlin . wiwiss . d2rq . CommandLineTool ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; import de . fuberlin . wiwiss . d2rq . engine . QueryEngineD2RQ ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; public class d2r_query extends CommandLineTool { private static final Log log = LogFactory . getLog ( d2r_query . class ) ; public static void main ( String [ ] args ) { new d2r_query ( ) . process ( args ) ; } public void usage ( ) { System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; printStandardArguments ( true ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" + SystemLoader . DEFAULT_BASE_URI + "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; System . err . println ( "" ) ; printConnectionOptions ( ) ; System . err . println ( ) ; System . exit ( ) ; } private ArgDecl baseArg = new ArgDecl ( true , "" , "" ) ; private ArgDecl formatArg = new ArgDecl ( true , "" , "" ) ; private ArgDecl timeoutArg = new ArgDecl ( true , "" , "" ) ; public void initArgs ( CommandLine cmd ) { cmd . add ( baseArg ) ; cmd . add ( formatArg ) ; cmd . add ( timeoutArg ) ; setMinMaxArguments ( , ) ; setSupportImplicitJdbcURL ( true ) ; } public void run ( CommandLine cmd , SystemLoader loader ) throws IOException { String query = null ; if ( cmd . numItems ( ) == ) { query = cmd . getItem ( , true ) ; } else if ( cmd . numItems ( ) == ) { loader . setMappingFileOrJdbcURL ( cmd . getItem ( ) ) ; query = cmd . getItem ( , true ) ; } String format = null ; if ( cmd . hasArg ( formatArg ) ) { format = cmd . getArg ( formatArg ) . getValue ( ) ; } if ( cmd . hasArg ( baseArg ) ) { loader . setSystemBaseURI ( cmd . getArg ( baseArg ) . getValue ( ) ) ; } double timeout = - ; if ( cmd . hasArg ( timeoutArg ) ) { try { timeout = Double . parseDouble ( cmd . getArg ( timeoutArg ) . getValue ( ) ) ; } catch ( NumberFormatException ex ) { throw new D2RQException ( "" + cmd . getArg ( timeoutArg ) . getValue ( ) + "" , D2RQException . MUST_BE_NUMERIC ) ; } } loader . setFastMode ( true ) ; ModelD2RQ d2rqModel = loader . getModelD2RQ ( ) ; String prefixes = "" ; for ( String prefix : d2rqModel . getNsPrefixMap ( ) . keySet ( ) ) { prefixes += "" + prefix + "" + d2rqModel . getNsPrefixURI ( prefix ) + "" ; } query = prefixes + query ; log . info ( "" + query ) ; try { QueryEngineD2RQ . register ( ) ; Query q = QueryFactory . create ( query , loader . getResourceBaseURI ( ) ) ; QueryExecution qe = QueryExecutionFactory . create ( q , d2rqModel ) ; if ( timeout > ) { qe . setTimeout ( Math . round ( timeout * ) ) ; } QueryExecUtils . executeQuery ( q , qe , ResultsFormat . lookup ( format ) ) ; } catch ( QueryCancelledException ex ) { throw new D2RQException ( "" , ex , D2RQException . QUERY_TIMEOUT ) ; } finally { d2rqModel . close ( ) ; } } } package d2rq ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStreamWriter ; import java . io . PrintStream ; import java . io . UnsupportedEncodingException ; import jena . cmdline . ArgDecl ; import jena . cmdline . CommandLine ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . RDFWriter ; import com . hp . hpl . jena . shared . NoWriterForLangException ; import de . fuberlin . wiwiss . d2rq . CommandLineTool ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . mapgen . MappingGenerator ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; public class dump_rdf extends CommandLineTool { private final static Log log = LogFactory . getLog ( dump_rdf . class ) ; private final static int DUMP_DEFAULT_FETCH_SIZE = ; public static void main ( String [ ] args ) { new dump_rdf ( ) . process ( args ) ; } public void usage ( ) { System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; printStandardArguments ( true ) ; System . err . println ( ) ; System . err . println ( "" ) ; System . err . println ( "" + SystemLoader . DEFAULT_BASE_URI + "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; System . err . println ( "" ) ; printConnectionOptions ( ) ; System . err . println ( ) ; System . exit ( ) ; } private ArgDecl baseArg = new ArgDecl ( true , "" , "" ) ; private ArgDecl formatArg = new ArgDecl ( true , "" , "" ) ; private ArgDecl outfileArg = new ArgDecl ( true , "" , "" , "" ) ; public void initArgs ( CommandLine cmd ) { cmd . add ( baseArg ) ; cmd . add ( formatArg ) ; cmd . add ( outfileArg ) ; } public void run ( CommandLine cmd , SystemLoader loader ) throws IOException { if ( cmd . numItems ( ) == ) { loader . setMappingFileOrJdbcURL ( cmd . getItem ( ) ) ; } String format = "" ; if ( cmd . hasArg ( formatArg ) ) { format = cmd . getArg ( formatArg ) . getValue ( ) ; } PrintStream out ; if ( cmd . hasArg ( outfileArg ) ) { File f = new File ( cmd . getArg ( outfileArg ) . getValue ( ) ) ; log . info ( "" + f ) ; out = new PrintStream ( new FileOutputStream ( f ) ) ; loader . setSystemBaseURI ( MapParser . absolutizeURI ( f . toURI ( ) . toString ( ) + "" ) ) ; } else { log . info ( "" ) ; out = System . out ; } if ( cmd . hasArg ( baseArg ) ) { loader . setSystemBaseURI ( cmd . getArg ( baseArg ) . getValue ( ) ) ; } loader . setResultSizeLimit ( Database . NO_LIMIT ) ; Mapping mapping = loader . getMapping ( ) ; try { mapping . compiledPropertyBridges ( ) ; for ( Database db : mapping . databases ( ) ) { db . connectedDB ( ) . setDefaultFetchSize ( DUMP_DEFAULT_FETCH_SIZE ) ; } Model d2rqModel = loader . getModelD2RQ ( ) ; try { RDFWriter writer = d2rqModel . getWriter ( format . toUpperCase ( ) ) ; if ( format . equals ( "" ) || format . equals ( "" ) ) { writer . setProperty ( "" , "" ) ; if ( loader . getResourceBaseURI ( ) != null ) { writer . setProperty ( "" , loader . getResourceBaseURI ( ) ) ; } } writer . write ( d2rqModel , new OutputStreamWriter ( out , "" ) , loader . getResourceBaseURI ( ) ) ; } catch ( NoWriterForLangException ex ) { throw new D2RQException ( "" + format + "" , D2RQException . STARTUP_UNKNOWN_FORMAT ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( "" ) ; } } finally { out . close ( ) ; mapping . close ( ) ; } } } package de . fuberlin . wiwiss . pubby . negotiation ; import java . util . regex . Pattern ; public class PubbyNegotiator { private final static ContentTypeNegotiator pubbyNegotiator ; private final static ContentTypeNegotiator dataNegotiator ; static { pubbyNegotiator = new ContentTypeNegotiator ( ) ; pubbyNegotiator . setDefaultAccept ( "" ) ; pubbyNegotiator . addUserAgentOverride ( null , "" , "" ) ; pubbyNegotiator . addUserAgentOverride ( Pattern . compile ( "" ) , null , "" ) ; pubbyNegotiator . addVariant ( "" ) . addAliasMediaType ( "" ) ; pubbyNegotiator . addVariant ( "" ) . addAliasMediaType ( "" ) . addAliasMediaType ( "" ) ; pubbyNegotiator . addVariant ( "" ) . addAliasMediaType ( "" ) . addAliasMediaType ( "" ) ; pubbyNegotiator . addVariant ( "" ) . addAliasMediaType ( "" ) . addAliasMediaType ( "" ) ; pubbyNegotiator . addVariant ( "" ) ; dataNegotiator = new ContentTypeNegotiator ( ) ; dataNegotiator . addVariant ( "" ) . addAliasMediaType ( "" ) . addAliasMediaType ( "" ) ; dataNegotiator . addVariant ( "" ) . addAliasMediaType ( "" ) . addAliasMediaType ( "" ) ; dataNegotiator . addVariant ( "" ) . addAliasMediaType ( "" ) . addAliasMediaType ( "" ) ; dataNegotiator . addVariant ( "" ) ; } public static ContentTypeNegotiator getPubbyNegotiator ( ) { return pubbyNegotiator ; } public static ContentTypeNegotiator getDataNegotiator ( ) { return dataNegotiator ; } } package de . fuberlin . wiwiss . pubby . negotiation ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . regex . Pattern ; public class ContentTypeNegotiator { private List < VariantSpec > variantSpecs = new ArrayList < VariantSpec > ( ) ; private List < MediaRangeSpec > defaultAcceptRanges = Collections . singletonList ( MediaRangeSpec . parseRange ( "" ) ) ; private Collection < AcceptHeaderOverride > userAgentOverrides = new ArrayList < AcceptHeaderOverride > ( ) ; public VariantSpec addVariant ( String mediaType ) { VariantSpec result = new VariantSpec ( mediaType ) ; variantSpecs . add ( result ) ; return result ; } public void setDefaultAccept ( String accept ) { this . defaultAcceptRanges = MediaRangeSpec . parseAccept ( accept ) ; } public void addUserAgentOverride ( Pattern userAgentString , String originalAcceptHeader , String newAcceptHeader ) { this . userAgentOverrides . add ( new AcceptHeaderOverride ( userAgentString , originalAcceptHeader , newAcceptHeader ) ) ; } public MediaRangeSpec getBestMatch ( String accept ) { return getBestMatch ( accept , null ) ; } public MediaRangeSpec getBestMatch ( String accept , String userAgent ) { if ( userAgent == null ) { userAgent = "" ; } String overriddenAccept = accept ; for ( AcceptHeaderOverride override : userAgentOverrides ) { if ( override . matches ( accept , userAgent ) ) { overriddenAccept = override . getReplacement ( ) ; } } return new Negotiation ( toAcceptRanges ( overriddenAccept ) ) . negotiate ( ) ; } private List < MediaRangeSpec > toAcceptRanges ( String accept ) { if ( accept == null ) { return defaultAcceptRanges ; } List < MediaRangeSpec > result = MediaRangeSpec . parseAccept ( accept ) ; if ( result . isEmpty ( ) ) { return defaultAcceptRanges ; } return result ; } public class VariantSpec { private MediaRangeSpec type ; private List < MediaRangeSpec > aliases = new ArrayList < MediaRangeSpec > ( ) ; private boolean isDefault = false ; public VariantSpec ( String mediaType ) { type = MediaRangeSpec . parseType ( mediaType ) ; } public VariantSpec addAliasMediaType ( String mediaType ) { aliases . add ( MediaRangeSpec . parseType ( mediaType ) ) ; return this ; } public void makeDefault ( ) { isDefault = true ; } public MediaRangeSpec getMediaType ( ) { return type ; } public boolean isDefault ( ) { return isDefault ; } public List < MediaRangeSpec > getAliases ( ) { return aliases ; } } private class Negotiation { private final List < MediaRangeSpec > ranges ; private MediaRangeSpec bestMatchingVariant = null ; private MediaRangeSpec bestDefaultVariant = null ; private double bestMatchingQuality = ; private double bestDefaultQuality = ; Negotiation ( List < MediaRangeSpec > ranges ) { this . ranges = ranges ; } MediaRangeSpec negotiate ( ) { for ( VariantSpec variant : variantSpecs ) { if ( variant . isDefault ) { evaluateDefaultVariant ( variant . getMediaType ( ) ) ; } evaluateVariant ( variant . getMediaType ( ) ) ; for ( MediaRangeSpec alias : variant . getAliases ( ) ) { evaluateVariantAlias ( alias , variant . getMediaType ( ) ) ; } } return ( bestMatchingVariant == null ) ? bestDefaultVariant : bestMatchingVariant ; } private void evaluateVariantAlias ( MediaRangeSpec variant , MediaRangeSpec isAliasFor ) { if ( variant . getBestMatch ( ranges ) == null ) return ; double q = variant . getBestMatch ( ranges ) . getQuality ( ) ; if ( q * variant . getQuality ( ) > bestMatchingQuality ) { bestMatchingVariant = isAliasFor ; bestMatchingQuality = q * variant . getQuality ( ) ; } } private void evaluateVariant ( MediaRangeSpec variant ) { evaluateVariantAlias ( variant , variant ) ; } private void evaluateDefaultVariant ( MediaRangeSpec variant ) { if ( variant . getQuality ( ) > bestDefaultQuality ) { bestDefaultVariant = variant ; bestDefaultQuality = * variant . getQuality ( ) ; } } } private class AcceptHeaderOverride { private Pattern userAgentPattern ; private String original ; private String replacement ; AcceptHeaderOverride ( Pattern userAgentPattern , String original , String replacement ) { this . userAgentPattern = userAgentPattern ; this . original = original ; this . replacement = replacement ; } boolean matches ( String acceptHeader , String userAgentHeader ) { return ( userAgentPattern == null || userAgentPattern . matcher ( userAgentHeader ) . find ( ) ) && ( original == null || original . equals ( acceptHeader ) ) ; } String getReplacement ( ) { return replacement ; } } } package de . fuberlin . wiwiss . pubby . negotiation ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class MediaRangeSpec { private final static Pattern tokenPattern ; private final static Pattern parameterPattern ; private final static Pattern mediaRangePattern ; private final static Pattern qValuePattern ; static { String token = "" ; String quotedString = "" ; String parameter = "" + token + "" + token + "" + quotedString + "" ; String qualityValue = "" ; String quality = "" ; String regex = "" + token + "" + token + "" + "" + parameter + "" + "" + quality + "" + "" + parameter + "" ; tokenPattern = Pattern . compile ( token ) ; parameterPattern = Pattern . compile ( parameter ) ; mediaRangePattern = Pattern . compile ( regex ) ; qValuePattern = Pattern . compile ( qualityValue ) ; } public static MediaRangeSpec parseType ( String mediaType ) { MediaRangeSpec m = parseRange ( mediaType ) ; if ( m == null || m . isWildcardType ( ) || m . isWildcardSubtype ( ) ) { return null ; } return m ; } public static MediaRangeSpec parseRange ( String mediaRange ) { Matcher m = mediaRangePattern . matcher ( mediaRange ) ; if ( ! m . matches ( ) ) { return null ; } String type = m . group ( ) . toLowerCase ( ) ; String subtype = m . group ( ) . toLowerCase ( ) ; String unparsedParameters = m . group ( ) ; String qValue = m . group ( ) ; m = parameterPattern . matcher ( unparsedParameters ) ; if ( "" . equals ( type ) && ! "" . equals ( subtype ) ) { return null ; } List < String > parameterNames = new ArrayList < String > ( ) ; List < String > parameterValues = new ArrayList < String > ( ) ; while ( m . find ( ) ) { String name = m . group ( ) . toLowerCase ( ) ; String value = ( m . group ( ) == null ) ? m . group ( ) : unescape ( m . group ( ) ) ; parameterNames . add ( name ) ; parameterValues . add ( value ) ; } double quality = ; if ( qValue != null && qValuePattern . matcher ( qValue ) . matches ( ) ) { try { quality = Double . parseDouble ( qValue ) ; } catch ( NumberFormatException ex ) { } } return new MediaRangeSpec ( type , subtype , parameterNames , parameterValues , quality ) ; } public static List < MediaRangeSpec > parseAccept ( String s ) { List < MediaRangeSpec > result = new ArrayList < MediaRangeSpec > ( ) ; Matcher m = mediaRangePattern . matcher ( s ) ; while ( m . find ( ) ) { result . add ( parseRange ( m . group ( ) ) ) ; } return result ; } private static String unescape ( String s ) { return s . replaceAll ( "" , "" ) ; } private static String escape ( String s ) { return s . replaceAll ( "" , "" ) ; } private final String type ; private final String subtype ; private final List < String > parameterNames ; private final List < String > parameterValues ; private final String mediaType ; private final double quality ; private MediaRangeSpec ( String type , String subtype , List < String > parameterNames , List < String > parameterValues , double quality ) { this . type = type ; this . subtype = subtype ; this . parameterNames = Collections . unmodifiableList ( parameterNames ) ; this . parameterValues = parameterValues ; this . mediaType = buildMediaType ( ) ; this . quality = quality ; } private String buildMediaType ( ) { StringBuffer result = new StringBuffer ( ) ; result . append ( type ) ; result . append ( "" ) ; result . append ( subtype ) ; for ( int i = ; i < parameterNames . size ( ) ; i ++ ) { result . append ( "" ) ; result . append ( parameterNames . get ( i ) ) ; result . append ( "" ) ; String value = parameterValues . get ( i ) ; if ( tokenPattern . matcher ( value ) . matches ( ) ) { result . append ( value ) ; } else { result . append ( "" ) ; result . append ( escape ( value ) ) ; result . append ( "" ) ; } } return result . toString ( ) ; } public String getType ( ) { return type ; } public String getSubtype ( ) { return subtype ; } public String getMediaType ( ) { return mediaType ; } public List < String > getParameterNames ( ) { return parameterNames ; } public String getParameter ( String parameterName ) { for ( int i = ; i < parameterNames . size ( ) ; i ++ ) { if ( parameterNames . get ( i ) . equals ( parameterName . toLowerCase ( ) ) ) { return parameterValues . get ( i ) ; } } return null ; } public boolean isWildcardType ( ) { return "" . equals ( type ) ; } public boolean isWildcardSubtype ( ) { return ! isWildcardType ( ) && "" . equals ( subtype ) ; } public double getQuality ( ) { return quality ; } public int getPrecedence ( MediaRangeSpec range ) { if ( range . isWildcardType ( ) ) return ; if ( ! range . type . equals ( type ) ) return ; if ( range . isWildcardSubtype ( ) ) return ; if ( ! range . subtype . equals ( subtype ) ) return ; if ( range . getParameterNames ( ) . isEmpty ( ) ) return ; int result = ; for ( int i = ; i < range . getParameterNames ( ) . size ( ) ; i ++ ) { String name = range . getParameterNames ( ) . get ( i ) ; String value = range . getParameter ( name ) ; if ( ! value . equals ( getParameter ( name ) ) ) return ; result ++ ; } return result ; } public MediaRangeSpec getBestMatch ( List < MediaRangeSpec > mediaRanges ) { MediaRangeSpec result = null ; int bestPrecedence = ; for ( MediaRangeSpec range : mediaRanges ) { if ( getPrecedence ( range ) > bestPrecedence ) { bestPrecedence = getPrecedence ( range ) ; result = range ; } } return result ; } public String toString ( ) { return mediaType + "" + quality ; } } package de . fuberlin . wiwiss . d2rq . vocab ; import com . hp . hpl . jena . rdf . model . * ; public class D2RQ { private static Model m_model = ModelFactory . createDefaultModel ( ) ; public static final String NS = "" ; public static String getURI ( ) { return NS ; } public static final Resource NAMESPACE = m_model . createResource ( NS ) ; public static final Property additionalClassDefinitionProperty = m_model . createProperty ( "" ) ; public static final Property additionalProperty = m_model . createProperty ( "" ) ; public static final Property additionalPropertyDefinitionProperty = m_model . createProperty ( "" ) ; public static final Property alias = m_model . createProperty ( "" ) ; public static final Property allowDistinct = m_model . createProperty ( "" ) ; public static final Property bNodeIdColumns = m_model . createProperty ( "" ) ; public static final Property belongsToClassMap = m_model . createProperty ( "" ) ; public static final Property binaryColumn = m_model . createProperty ( "" ) ; public static final Property bitColumn = m_model . createProperty ( "" ) ; public static final Property booleanColumn = m_model . createProperty ( "" ) ; public static final Property class_ = m_model . createProperty ( "" ) ; public static final Property classDefinitionComment = m_model . createProperty ( "" ) ; public static final Property classDefinitionLabel = m_model . createProperty ( "" ) ; public static final Property classMap = m_model . createProperty ( "" ) ; public static final Property column = m_model . createProperty ( "" ) ; public static final Property condition = m_model . createProperty ( "" ) ; public static final Property constantValue = m_model . createProperty ( "" ) ; public static final Property containsDuplicates = m_model . createProperty ( "" ) ; public static final Property contentDownloadColumn = m_model . createProperty ( "" ) ; public static final Property dataStorage = m_model . createProperty ( "" ) ; public static final Property databaseValue = m_model . createProperty ( "" ) ; public static final Property datatype = m_model . createProperty ( "" ) ; public static final Property dateColumn = m_model . createProperty ( "" ) ; public static final Property dynamicProperty = m_model . createProperty ( "" ) ; public static final Property fetchSize = m_model . createProperty ( "" ) ; public static final Property href = m_model . createProperty ( "" ) ; public static final Property intervalColumn = m_model . createProperty ( "" ) ; public static final Property javaClass = m_model . createProperty ( "" ) ; public static final Property jdbcDSN = m_model . createProperty ( "" ) ; public static final Property jdbcDriver = m_model . createProperty ( "" ) ; public static final Property join = m_model . createProperty ( "" ) ; public static final Property lang = m_model . createProperty ( "" ) ; public static final Property limit = m_model . createProperty ( "" ) ; public static final Property limitInverse = m_model . createProperty ( "" ) ; public static final Property mappingFile = m_model . createProperty ( "" ) ; public static final Property mediaType = m_model . createProperty ( "" ) ; public static final Property numericColumn = m_model . createProperty ( "" ) ; public static final Property odbcDSN = m_model . createProperty ( "" ) ; public static final Property orderAsc = m_model . createProperty ( "" ) ; public static final Property orderDesc = m_model . createProperty ( "" ) ; public static final Property password = m_model . createProperty ( "" ) ; public static final Property pattern = m_model . createProperty ( "" ) ; public static final Property property = m_model . createProperty ( "" ) ; public static final Property propertyBridge = m_model . createProperty ( "" ) ; public static final Property propertyDefinitionComment = m_model . createProperty ( "" ) ; public static final Property propertyDefinitionLabel = m_model . createProperty ( "" ) ; public static final Property propertyName = m_model . createProperty ( "" ) ; public static final Property propertyValue = m_model . createProperty ( "" ) ; public static final Property rdfValue = m_model . createProperty ( "" ) ; public static final Property refersToClassMap = m_model . createProperty ( "" ) ; public static final Property resourceBaseURI = m_model . createProperty ( "" ) ; public static final Property resultSizeLimit = m_model . createProperty ( "" ) ; public static final Property serveVocabulary = m_model . createProperty ( "" ) ; public static final Property sqlExpression = m_model . createProperty ( "" ) ; public static final Property startupSQLScript = m_model . createProperty ( "" ) ; public static final Property textColumn = m_model . createProperty ( "" ) ; public static final Property timeColumn = m_model . createProperty ( "" ) ; public static final Property timestampColumn = m_model . createProperty ( "" ) ; public static final Property translateWith = m_model . createProperty ( "" ) ; public static final Property translation = m_model . createProperty ( "" ) ; public static final Property uriColumn = m_model . createProperty ( "" ) ; public static final Property uriPattern = m_model . createProperty ( "" ) ; public static final Property uriSqlExpression = m_model . createProperty ( "" ) ; public static final Property useAllOptimizations = m_model . createProperty ( "" ) ; public static final Property username = m_model . createProperty ( "" ) ; public static final Property valueContains = m_model . createProperty ( "" ) ; public static final Property valueMaxLength = m_model . createProperty ( "" ) ; public static final Property valueRegex = m_model . createProperty ( "" ) ; public static final Resource AdditionalProperty = m_model . createResource ( "" ) ; public static final Resource ClassMap = m_model . createResource ( "" ) ; public static final Resource Configuration = m_model . createResource ( "" ) ; public static final Resource D2RQModel = m_model . createResource ( "" ) ; public static final Resource Database = m_model . createResource ( "" ) ; public static final Resource DatatypePropertyBridge = m_model . createResource ( "" ) ; public static final Resource DownloadMap = m_model . createResource ( "" ) ; public static final Resource ObjectPropertyBridge = m_model . createResource ( "" ) ; public static final Resource PropertyBridge = m_model . createResource ( "" ) ; public static final Resource ResourceMap = m_model . createResource ( "" ) ; public static final Resource Translation = m_model . createResource ( "" ) ; public static final Resource TranslationTable = m_model . createResource ( "" ) ; } package de . fuberlin . wiwiss . d2rq . vocab ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . Resource ; public class VoID { private static Model vocabModel = ModelFactory . createDefaultModel ( ) ; public static final String NS = "" ; public static final Resource NAMESPACE = vocabModel . createResource ( NS ) ; public static final Resource Dataset = vocabModel . createResource ( NS + "" ) ; public static final Property homepage = vocabModel . createProperty ( "" ) ; public static final Property feature = vocabModel . createProperty ( NS + "" ) ; public static final Property rootResource = vocabModel . createProperty ( NS + "" ) ; public static final Property uriSpace = vocabModel . createProperty ( NS + "" ) ; public static final Property class_ = vocabModel . createProperty ( NS + "" ) ; public static final Property property = vocabModel . createProperty ( NS + "" ) ; public static final Property vocabulary = vocabModel . createProperty ( NS + "" ) ; public static final Property classPartition = vocabModel . createProperty ( NS + "" ) ; public static final Property propertyPartition = vocabModel . createProperty ( NS + "" ) ; public static final Property sparqlEndpoint = vocabModel . createProperty ( NS + "" ) ; public static final Property inDataset = vocabModel . createProperty ( NS + "" ) ; } package de . fuberlin . wiwiss . d2rq . vocab ; public class META { public static final String NS = "" ; } package de . fuberlin . wiwiss . d2rq . vocab ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . Resource ; public class SD { private static Model vocabModel = ModelFactory . createDefaultModel ( ) ; public static final String NS = "" ; public static final Resource NAMESPACE = vocabModel . createResource ( NS ) ; public static final Resource Service = vocabModel . createResource ( NS + "" ) ; public static final Resource Dataset = vocabModel . createResource ( NS + "" ) ; public static final Resource Graph = vocabModel . createResource ( NS + "" ) ; public static final Property url = vocabModel . createProperty ( NS + "" ) ; public static final Property defaultDatasetDescription = vocabModel . createProperty ( NS + "" ) ; public static final Property defaultGraph = vocabModel . createProperty ( NS + "" ) ; public static final Property resultFormat = vocabModel . createProperty ( NS + "" ) ; } package de . fuberlin . wiwiss . d2rq . vocab ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Resource ; public class JDBC { private static Model model = ModelFactory . createDefaultModel ( ) ; public static final String NS = "" ; public static String getURI ( ) { return NS ; } public static final Resource NAMESPACE = model . createResource ( NS ) ; } package de . fuberlin . wiwiss . d2rq . vocab ; import com . hp . hpl . jena . rdf . model . * ; public class D2RConfig { private static Model m_model = ModelFactory . createDefaultModel ( ) ; public static final String NS = "" ; public static String getURI ( ) { return NS ; } public static final Resource NAMESPACE = m_model . createResource ( NS ) ; public static final Property autoReloadMapping = m_model . createProperty ( "" ) ; public static final Property baseURI = m_model . createProperty ( "" ) ; public static final Property datasetMetadataTemplate = m_model . createProperty ( "" ) ; public static final Property documentMetadata = m_model . createProperty ( "" ) ; public static final Property enableMetadata = m_model . createProperty ( "" ) ; public static final Property limitPerClassMap = m_model . createProperty ( "" ) ; public static final Property limitPerPropertyBridge = m_model . createProperty ( "" ) ; public static final Property metadataTemplate = m_model . createProperty ( "" ) ; public static final Property pageTimeout = m_model . createProperty ( "" ) ; public static final Property port = m_model . createProperty ( "" ) ; public static final Property publishes = m_model . createProperty ( "" ) ; public static final Property sparqlTimeout = m_model . createProperty ( "" ) ; public static final Property vocabularyIncludeInstances = m_model . createProperty ( "" ) ; public static final Resource Server = m_model . createResource ( "" ) ; } package de . fuberlin . wiwiss . d2rq . vocab ; import com . hp . hpl . jena . rdf . model . * ; public class ISWC { private static Model m_model = ModelFactory . createDefaultModel ( ) ; public static final String NS = "" ; public static String getURI ( ) { return NS ; } public static final Resource NAMESPACE = m_model . createResource ( NS ) ; public static final Property persons_involved = m_model . createProperty ( "" ) ; public static final Property conference = m_model . createProperty ( "" ) ; public static final Property formal_language = m_model . createProperty ( "" ) ; public static final Property application_domain = m_model . createProperty ( "" ) ; public static final Property algorithm = m_model . createProperty ( "" ) ; public static final Property tool = m_model . createProperty ( "" ) ; public static final Property hasSubtopic = m_model . createProperty ( "" ) ; public static final Property has_affiliate = m_model . createProperty ( "" ) ; public static final Property is_about = m_model . createProperty ( "" ) ; public static final Property funding_by = m_model . createProperty ( "" ) ; public static final Property involved_in_project = m_model . createProperty ( "" ) ; public static final Property application = m_model . createProperty ( "" ) ; public static final Property has_affiliation = m_model . createProperty ( "" ) ; public static final Property topic = m_model . createProperty ( "" ) ; public static final Property author = m_model . createProperty ( "" ) ; public static final Property organizations_involved = m_model . createProperty ( "" ) ; public static final Property research_topics = m_model . createProperty ( "" ) ; public static final Property method = m_model . createProperty ( "" ) ; public static final Property name = m_model . createProperty ( "" ) ; public static final Property phone = m_model . createProperty ( "" ) ; public static final Property country = m_model . createProperty ( "" ) ; public static final Property location = m_model . createProperty ( "" ) ; public static final Property email = m_model . createProperty ( "" ) ; public static final Property eventTitle = m_model . createProperty ( "" ) ; public static final Property address = m_model . createProperty ( "" ) ; public static final Property fax = m_model . createProperty ( "" ) ; public static final Property first_Name = m_model . createProperty ( "" ) ; public static final Property title = m_model . createProperty ( "" ) ; public static final Property year = m_model . createProperty ( "" ) ; public static final Property middle_Initial = m_model . createProperty ( "" ) ; public static final Property date = m_model . createProperty ( "" ) ; public static final Property project_title = m_model . createProperty ( "" ) ; public static final Property last_Name = m_model . createProperty ( "" ) ; public static final Property photo = m_model . createProperty ( "" ) ; public static final Property homepage = m_model . createProperty ( "" ) ; public static final Resource Researcher = m_model . createResource ( "" ) ; public static final Resource Research_Funding_Institution = m_model . createResource ( "" ) ; public static final Resource Formal_Language = m_model . createResource ( "" ) ; public static final Resource Event = m_model . createResource ( "" ) ; public static final Resource Algorithm = m_model . createResource ( "" ) ; public static final Resource Application = m_model . createResource ( "" ) ; public static final Resource Faculty_Member = m_model . createResource ( "" ) ; public static final Resource Full_Professor = m_model . createResource ( "" ) ; public static final Resource Organization = m_model . createResource ( "" ) ; public static final Resource Association = m_model . createResource ( "" ) ; public static final Resource Tutorial = m_model . createResource ( "" ) ; public static final Resource Employee = m_model . createResource ( "" ) ; public static final Resource Proceedings = m_model . createResource ( "" ) ; public static final Resource University = m_model . createResource ( "" ) ; public static final Resource PhDStudent = m_model . createResource ( "" ) ; public static final Resource Topic = m_model . createResource ( "" ) ; public static final Resource Application_Domain = m_model . createResource ( "" ) ; public static final Resource Institute = m_model . createResource ( "" ) ; public static final Resource Enterprise = m_model . createResource ( "" ) ; public static final Resource Project = m_model . createResource ( "" ) ; public static final Resource Associate_Professor = m_model . createResource ( "" ) ; public static final Resource Person = m_model . createResource ( "" ) ; public static final Resource Book = m_model . createResource ( "" ) ; public static final Resource Method = m_model . createResource ( "" ) ; public static final Resource Lecturer = m_model . createResource ( "" ) ; public static final Resource Tool = m_model . createResource ( "" ) ; public static final Resource Student = m_model . createResource ( "" ) ; public static final Resource Report = m_model . createResource ( "" ) ; public static final Resource Conference = m_model . createResource ( "" ) ; public static final Resource InProceedings = m_model . createResource ( "" ) ; public static final Resource Department = m_model . createResource ( "" ) ; public static final Resource Workshop = m_model . createResource ( "" ) ; public static final Resource Publication = m_model . createResource ( "" ) ; public static final Resource Development_of_Knowledge_Management_Systems = m_model . createResource ( "" ) ; public static final Resource e_Business = m_model . createResource ( "" ) ; public static final Resource Knowledge_Reasoning = m_model . createResource ( "" ) ; public static final Resource Knowledge_Discovery = m_model . createResource ( "" ) ; public static final Resource Text_Mining = m_model . createResource ( "" ) ; public static final Resource World_Wide_Web = m_model . createResource ( "" ) ; public static final Resource C = m_model . createResource ( "" ) ; public static final Resource OXML = m_model . createResource ( "" ) ; public static final Resource Knowledge_Systems = m_model . createResource ( "" ) ; public static final Resource Web_Services = m_model . createResource ( "" ) ; public static final Resource Information_Systems = m_model . createResource ( "" ) ; public static final Resource Agents = m_model . createResource ( "" ) ; public static final Resource Logic = m_model . createResource ( "" ) ; public static final Resource Information_Extraction = m_model . createResource ( "" ) ; public static final Resource Agent_Systems = m_model . createResource ( "" ) ; public static final Resource Knowledge_Management = m_model . createResource ( "" ) ; public static final Resource DAML_OIL = m_model . createResource ( "" ) ; public static final Resource Artificial_Intelligence = m_model . createResource ( "" ) ; public static final Resource Semantic_Web = m_model . createResource ( "" ) ; public static final Resource KAON = m_model . createResource ( "" ) ; public static final Resource Databases = m_model . createResource ( "" ) ; public static final Resource RDFS = m_model . createResource ( "" ) ; public static final Resource ISWC_2002 = m_model . createResource ( "" ) ; public static final Resource Data_Mining = m_model . createResource ( "" ) ; public static final Resource Knowledge_Portals = m_model . createResource ( "" ) ; public static final Resource TowardsSemanticWebMining = m_model . createResource ( "" ) ; public static final Resource Knowledge_Management_Methodology = m_model . createResource ( "" ) ; public static final Resource Knowledge_Representation_Languages = m_model . createResource ( "" ) ; public static final Resource Ontology_Learning = m_model . createResource ( "" ) ; public static final Resource Ontology_based_Knowledge_Management_Systems = m_model . createResource ( "" ) ; public static final Resource XML = m_model . createResource ( "" ) ; public static final Resource Machine_Learning = m_model . createResource ( "" ) ; public static final Resource Network_Infrastructure = m_model . createResource ( "" ) ; public static final Resource Modeling = m_model . createResource ( "" ) ; public static final Resource SQL = m_model . createResource ( "" ) ; public static final Resource Business_Engineering = m_model . createResource ( "" ) ; public static final Resource Information_Retrieval = m_model . createResource ( "" ) ; public static final Resource Office_Information_Systems = m_model . createResource ( "" ) ; public static final Resource RDF = m_model . createResource ( "" ) ; public static final Resource Semantic_Annotation = m_model . createResource ( "" ) ; public static final Resource Java = m_model . createResource ( "" ) ; public static final Resource Knowledge_Representation_And_Reasoning = m_model . createResource ( "" ) ; public static final Resource Semantic_Web_Iinfrastructure = m_model . createResource ( "" ) ; public static final Resource Query_Languages = m_model . createResource ( "" ) ; public static final Resource Matching = m_model . createResource ( "" ) ; public static final Resource Human_Computer_Interaction = m_model . createResource ( "" ) ; public static final Resource Semantic_Web_Languages = m_model . createResource ( "" ) ; public static final Resource Ontology_Engineering = m_model . createResource ( "" ) ; public static final Resource University_of_Karlsruhe = m_model . createResource ( "" ) ; public static final Resource AIFB = m_model . createResource ( "" ) ; } package de . fuberlin . wiwiss . d2rq . vocab ; import java . lang . reflect . Field ; import java . lang . reflect . Modifier ; import java . util . Collection ; import java . util . HashSet ; import java . util . Set ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . RDFNode ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; public class VocabularySummarizer { private final Class < ? extends Object > vocabularyJavaClass ; private final String namespace ; private final Set < Property > properties ; private final Set < Resource > classes ; public VocabularySummarizer ( Class < ? extends Object > vocabularyJavaClass ) { this . vocabularyJavaClass = vocabularyJavaClass ; namespace = findNamespace ( ) ; properties = findAllProperties ( ) ; classes = findAllClasses ( ) ; } public Set < Property > getAllProperties ( ) { return properties ; } private Set < Property > findAllProperties ( ) { Set < Property > results = new HashSet < Property > ( ) ; for ( int i = ; i < vocabularyJavaClass . getFields ( ) . length ; i ++ ) { Field field = vocabularyJavaClass . getFields ( ) [ i ] ; if ( ! Modifier . isStatic ( field . getModifiers ( ) ) ) continue ; if ( ! Property . class . isAssignableFrom ( field . getType ( ) ) ) continue ; try { results . add ( ( Property ) field . get ( null ) ) ; } catch ( IllegalAccessException ex ) { throw new D2RQException ( ex ) ; } } return results ; } public Set < Resource > getAllClasses ( ) { return classes ; } private Set < Resource > findAllClasses ( ) { Set < Resource > results = new HashSet < Resource > ( ) ; for ( int i = ; i < vocabularyJavaClass . getFields ( ) . length ; i ++ ) { Field field = vocabularyJavaClass . getFields ( ) [ i ] ; if ( ! Modifier . isStatic ( field . getModifiers ( ) ) ) continue ; if ( ! Resource . class . isAssignableFrom ( field . getType ( ) ) ) continue ; if ( Property . class . isAssignableFrom ( field . getType ( ) ) ) continue ; try { results . add ( ( Resource ) field . get ( null ) ) ; } catch ( IllegalAccessException ex ) { throw new D2RQException ( ex ) ; } } return results ; } public String getNamespace ( ) { return namespace ; } private String findNamespace ( ) { try { Object o = vocabularyJavaClass . getField ( "" ) . get ( vocabularyJavaClass ) ; if ( o instanceof String ) { return ( String ) o ; } return null ; } catch ( NoSuchFieldException ex ) { return null ; } catch ( IllegalAccessException ex ) { return null ; } } public Collection < Resource > getUndefinedClasses ( Model model ) { Set < Resource > result = new HashSet < Resource > ( ) ; StmtIterator it = model . listStatements ( null , RDF . type , ( RDFNode ) null ) ; while ( it . hasNext ( ) ) { Statement stmt = it . nextStatement ( ) ; if ( stmt . getObject ( ) . isURIResource ( ) && stmt . getResource ( ) . getURI ( ) . startsWith ( namespace ) && ! classes . contains ( stmt . getObject ( ) ) ) { result . add ( stmt . getResource ( ) ) ; } } return result ; } public Collection < Property > getUndefinedProperties ( Model model ) { Set < Property > result = new HashSet < Property > ( ) ; StmtIterator it = model . listStatements ( ) ; while ( it . hasNext ( ) ) { Statement stmt = it . nextStatement ( ) ; if ( stmt . getPredicate ( ) . getURI ( ) . startsWith ( namespace ) && ! properties . contains ( stmt . getPredicate ( ) ) ) { result . add ( stmt . getPredicate ( ) ) ; } } return result ; } public void assertNoUndefinedTerms ( Model model , int undefinedPropertyErrorCode , int undefinedClassErrorCode ) { Collection < Property > unknownProperties = getUndefinedProperties ( model ) ; if ( ! unknownProperties . isEmpty ( ) ) { throw new D2RQException ( "" + PrettyPrinter . toString ( unknownProperties . iterator ( ) . next ( ) ) + "" , undefinedPropertyErrorCode ) ; } Collection < Resource > unknownClasses = getUndefinedClasses ( model ) ; if ( ! unknownClasses . isEmpty ( ) ) { throw new D2RQException ( "" + PrettyPrinter . toString ( unknownClasses . iterator ( ) . next ( ) ) + "" , undefinedClassErrorCode ) ; } } } package de . fuberlin . wiwiss . d2rq . vocab ; import com . hp . hpl . jena . rdf . model . * ; public class SKOS { private static Model m_model = ModelFactory . createDefaultModel ( ) ; public static final String NS = "" ; public static String getURI ( ) { return NS ; } public static final Resource NAMESPACE = m_model . createResource ( NS ) ; public static final Property altLabel = m_model . createProperty ( "" ) ; public static final Property scopeNote = m_model . createProperty ( "" ) ; public static final Property narrower = m_model . createProperty ( "" ) ; public static final Property note = m_model . createProperty ( "" ) ; public static final Property isSubjectOf = m_model . createProperty ( "" ) ; public static final Property altSymbol = m_model . createProperty ( "" ) ; public static final Property broader = m_model . createProperty ( "" ) ; public static final Property definition = m_model . createProperty ( "" ) ; public static final Property subjectIndicator = m_model . createProperty ( "" ) ; public static final Property subject = m_model . createProperty ( "" ) ; public static final Property inScheme = m_model . createProperty ( "" ) ; public static final Property historyNote = m_model . createProperty ( "" ) ; public static final Property hiddenLabel = m_model . createProperty ( "" ) ; public static final Property prefSymbol = m_model . createProperty ( "" ) ; public static final Property primarySubject = m_model . createProperty ( "" ) ; public static final Property related = m_model . createProperty ( "" ) ; public static final Property member = m_model . createProperty ( "" ) ; public static final Property memberList = m_model . createProperty ( "" ) ; public static final Property example = m_model . createProperty ( "" ) ; public static final Property semanticRelation = m_model . createProperty ( "" ) ; public static final Property changeNote = m_model . createProperty ( "" ) ; public static final Property hasTopConcept = m_model . createProperty ( "" ) ; public static final Property symbol = m_model . createProperty ( "" ) ; public static final Property prefLabel = m_model . createProperty ( "" ) ; public static final Property editorialNote = m_model . createProperty ( "" ) ; public static final Property isPrimarySubjectOf = m_model . createProperty ( "" ) ; public static final Resource CollectableProperty = m_model . createResource ( "" ) ; public static final Resource OrderedCollection = m_model . createResource ( "" ) ; public static final Resource Collection = m_model . createResource ( "" ) ; public static final Resource Concept = m_model . createResource ( "" ) ; public static final Resource ConceptScheme = m_model . createResource ( "" ) ; } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import com . hp . hpl . jena . rdf . model . Resource ; import de . fuberlin . wiwiss . d2rq . download . DownloadContentQuery ; import de . fuberlin . wiwiss . d2rq . map . DownloadMap ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . pubby . negotiation . ContentTypeNegotiator ; import de . fuberlin . wiwiss . pubby . negotiation . MediaRangeSpec ; import de . fuberlin . wiwiss . pubby . negotiation . PubbyNegotiator ; public class ResourceServlet extends HttpServlet { public void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; server . checkMappingFileChanged ( ) ; String relativeResourceURI = request . getRequestURI ( ) . substring ( request . getContextPath ( ) . length ( ) + request . getServletPath ( ) . length ( ) ) ; if ( ! "" . equals ( relativeResourceURI ) && "" . equals ( relativeResourceURI . substring ( , ) ) ) { relativeResourceURI = relativeResourceURI . substring ( ) ; } if ( request . getQueryString ( ) != null ) { relativeResourceURI = relativeResourceURI + "" + request . getQueryString ( ) ; } int servicePos ; if ( - == ( servicePos = request . getServletPath ( ) . indexOf ( "" + D2RServer . getResourceServiceName ( ) ) ) ) throw new ServletException ( "" + D2RServer . getResourceServiceName ( ) ) ; String serviceStem = request . getServletPath ( ) . substring ( , servicePos + ) ; String resourceURI = server . resourceBaseURI ( serviceStem ) + relativeResourceURI ; if ( handleDownload ( resourceURI , response , server ) ) { return ; } response . addHeader ( "" , "" ) ; ContentTypeNegotiator negotiator = PubbyNegotiator . getPubbyNegotiator ( ) ; MediaRangeSpec bestMatch = negotiator . getBestMatch ( request . getHeader ( "" ) , request . getHeader ( "" ) ) ; if ( bestMatch == null ) { response . setStatus ( ) ; response . setContentType ( "" ) ; response . getOutputStream ( ) . println ( "" + "" ) ; return ; } response . setStatus ( ) ; response . setContentType ( "" ) ; String location ; if ( "" . equals ( bestMatch . getMediaType ( ) ) ) { location = server . pageURL ( serviceStem , relativeResourceURI ) ; } else { location = server . dataURL ( serviceStem , relativeResourceURI ) ; } response . addHeader ( "" , location ) ; response . getOutputStream ( ) . println ( "" + location ) ; } private boolean handleDownload ( String resourceURI , HttpServletResponse response , D2RServer server ) throws IOException { Mapping m = D2RServer . retrieveSystemLoader ( getServletContext ( ) ) . getMapping ( ) ; for ( Resource r : m . downloadMapResources ( ) ) { DownloadMap d = m . downloadMap ( r ) ; DownloadContentQuery q = new DownloadContentQuery ( d , resourceURI ) ; if ( q . hasContent ( ) ) { response . setContentType ( q . getMediaType ( ) != null ? q . getMediaType ( ) : "" ) ; InputStream is = q . getContentStream ( ) ; OutputStream os = response . getOutputStream ( ) ; final byte [ ] buffer = new byte [ ] ; int read ; do { read = is . read ( buffer , , buffer . length ) ; if ( read > ) { os . write ( buffer , , read ) ; } } while ( read >= ) ; is . close ( ) ; q . close ( ) ; return true ; } } return false ; } } package de . fuberlin . wiwiss . d2rq . server ; import javax . servlet . ServletContext ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . joseki . RDFServer ; import org . joseki . Registry ; import org . joseki . Service ; import org . joseki . ServiceRegistry ; import org . joseki . processors . SPARQL ; import com . hp . hpl . jena . graph . BulkUpdateHandler ; import com . hp . hpl . jena . query . ARQ ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . shared . PrefixMapping ; import com . hp . hpl . jena . sparql . core . describe . DescribeHandler ; import com . hp . hpl . jena . sparql . core . describe . DescribeHandlerFactory ; import com . hp . hpl . jena . sparql . core . describe . DescribeHandlerRegistry ; import com . hp . hpl . jena . sparql . util . Context ; import de . fuberlin . wiwiss . d2rq . ResourceDescriber ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; public class D2RServer { private final static String SPARQL_SERVICE_NAME = "" ; private final static String RESOURCE_SERVICE_NAME = "" ; private final static String DATASET_SERVICE_NAME = "" ; private final static String DATA_SERVICE_NAME = "" ; private final static String PAGE_SERVICE_NAME = "" ; private final static String VOCABULARY_STEM = "" ; private final static String DEFAULT_SERVER_NAME = "" ; private final static String SYSTEM_LOADER = "" ; private static final Log log = LogFactory . getLog ( D2RServer . class ) ; private final SystemLoader loader ; private final ConfigLoader config ; private String overrideBaseURI = null ; private AutoReloadableDataset dataset ; private boolean startupError = false ; public D2RServer ( SystemLoader loader ) { this . loader = loader ; this . config = loader . getServerConfig ( ) ; } public static D2RServer fromServletContext ( ServletContext context ) { return retrieveSystemLoader ( context ) . getD2RServer ( ) ; } public void overrideBaseURI ( String baseURI ) { if ( ! baseURI . endsWith ( "" ) && ! baseURI . endsWith ( "" ) ) { baseURI += "" ; } if ( baseURI . indexOf ( '' ) != - ) { log . warn ( "" ) ; } this . overrideBaseURI = baseURI ; } public String baseURI ( ) { if ( this . overrideBaseURI != null ) { return this . overrideBaseURI ; } return this . config . baseURI ( ) ; } public String serverName ( ) { if ( this . config . serverName ( ) != null ) { return this . config . serverName ( ) ; } return D2RServer . DEFAULT_SERVER_NAME ; } public boolean hasTruncatedResults ( ) { return dataset . hasTruncatedResults ( ) ; } public String resourceBaseURI ( String serviceStem ) { if ( this . baseURI ( ) . endsWith ( "" ) ) { return this . baseURI ( ) ; } return this . baseURI ( ) + serviceStem + D2RServer . RESOURCE_SERVICE_NAME + "" ; } public String resourceBaseURI ( ) { return resourceBaseURI ( "" ) ; } public static String getResourceServiceName ( ) { return RESOURCE_SERVICE_NAME ; } public static String getDataServiceName ( ) { return DATA_SERVICE_NAME ; } public static String getPageServiceName ( ) { return PAGE_SERVICE_NAME ; } public static String getDatasetServiceName ( ) { return DATASET_SERVICE_NAME ; } public static String getSparqlServiceName ( ) { return SPARQL_SERVICE_NAME ; } public String dataURL ( String serviceStem , String relativeResourceURI ) { return this . baseURI ( ) + serviceStem + DATA_SERVICE_NAME + "" + relativeResourceURI ; } public String pageURL ( String serviceStem , String relativeResourceURI ) { return this . baseURI ( ) + serviceStem + PAGE_SERVICE_NAME + "" + relativeResourceURI ; } public boolean isVocabularyResource ( Resource r ) { return r . getURI ( ) . startsWith ( resourceBaseURI ( VOCABULARY_STEM ) ) ; } public void addDocumentMetadata ( Model document , Resource documentResource ) { this . config . addDocumentMetadata ( document , documentResource ) ; } public AutoReloadableDataset dataset ( ) { return this . dataset ; } public Mapping getMapping ( ) { return loader . getMapping ( ) ; } public void checkMappingFileChanged ( ) { dataset . checkMappingFileChanged ( ) ; } public PrefixMapping getPrefixes ( ) { return dataset . getPrefixMapping ( ) ; } public void start ( ) { startupError = true ; if ( config . isLocalMappingFile ( ) ) { this . dataset = new AutoReloadableDataset ( loader , config . getLocalMappingFilename ( ) , config . getAutoReloadMapping ( ) ) ; } else { this . dataset = new AutoReloadableDataset ( loader , null , false ) ; } if ( loader . getMapping ( ) . configuration ( ) . getUseAllOptimizations ( ) ) { log . info ( "" ) ; } else { log . info ( "" ) ; } DescribeHandlerRegistry . get ( ) . clear ( ) ; DescribeHandlerRegistry . get ( ) . add ( new DescribeHandlerFactory ( ) { public DescribeHandler create ( ) { return new DescribeHandler ( ) { private BulkUpdateHandler adder ; public void start ( Model accumulateResultModel , Context qContext ) { adder = accumulateResultModel . getGraph ( ) . getBulkUpdateHandler ( ) ; } public void describe ( Resource resource ) { log . info ( "" + resource + ">" ) ; boolean outgoingTriplesOnly = isVocabularyResource ( resource ) && ! getConfig ( ) . getVocabularyIncludeInstances ( ) ; adder . add ( new ResourceDescriber ( getMapping ( ) , resource . asNode ( ) , outgoingTriplesOnly , Relation . NO_LIMIT , Math . round ( config . getSPARQLTimeout ( ) ) ) . description ( ) ) ; } public void finish ( ) { } } ; } } ) ; Registry . add ( RDFServer . ServiceRegistryName , createJosekiServiceRegistry ( ) ) ; if ( config . getSPARQLTimeout ( ) > ) { ARQ . getContext ( ) . set ( ARQ . queryTimeout , config . getSPARQLTimeout ( ) * ) ; } startupError = false ; } public boolean errorOnStartup ( ) { return startupError ; } public void shutdown ( ) { log . info ( "" ) ; loader . getMapping ( ) . close ( ) ; } protected ServiceRegistry createJosekiServiceRegistry ( ) { ServiceRegistry services = new ServiceRegistry ( ) ; Service service = new Service ( new SPARQL ( ) , D2RServer . SPARQL_SERVICE_NAME , new D2RQDatasetDesc ( this . dataset ) ) ; services . add ( D2RServer . SPARQL_SERVICE_NAME , service ) ; return services ; } public ConfigLoader getConfig ( ) { return config ; } public static void storeSystemLoader ( SystemLoader loader , ServletContext context ) { context . setAttribute ( SYSTEM_LOADER , loader ) ; } public static SystemLoader retrieveSystemLoader ( ServletContext context ) { return ( SystemLoader ) context . getAttribute ( SYSTEM_LOADER ) ; } private static String getUri ( String base , String service ) { if ( base == null ) { base = "" ; } return base . endsWith ( "" ) ? base + service : base + "" + service ; } public String getDatasetIri ( ) { return getUri ( baseURI ( ) , D2RServer . getDatasetServiceName ( ) ) ; } public String getSparqlUrl ( ) { return getUri ( baseURI ( ) , D2RServer . getSparqlServiceName ( ) ) ; } public static String getVersion ( ) { String version = D2RServer . class . getPackage ( ) . getImplementationVersion ( ) ; if ( version == null ) { version = "" ; } return version ; } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . TreeSet ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . apache . velocity . context . Context ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . query . QueryCancelledException ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . ResourceFactory ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . shared . PrefixMapping ; import com . hp . hpl . jena . sparql . vocabulary . FOAF ; import com . hp . hpl . jena . vocabulary . DC ; import com . hp . hpl . jena . vocabulary . DCTerms ; import com . hp . hpl . jena . vocabulary . RDFS ; import de . fuberlin . wiwiss . d2rq . ClassMapLister ; import de . fuberlin . wiwiss . d2rq . ResourceDescriber ; import de . fuberlin . wiwiss . d2rq . vocab . SKOS ; public class PageServlet extends HttpServlet { private PrefixMapping prefixes ; public void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; server . checkMappingFileChanged ( ) ; String relativeResourceURI = request . getRequestURI ( ) . substring ( request . getContextPath ( ) . length ( ) + request . getServletPath ( ) . length ( ) ) ; if ( ! "" . equals ( relativeResourceURI ) && "" . equals ( relativeResourceURI . substring ( , ) ) ) { relativeResourceURI = relativeResourceURI . substring ( ) ; } if ( request . getQueryString ( ) != null ) { relativeResourceURI = relativeResourceURI + "" + request . getQueryString ( ) ; } int servicePos ; if ( - == ( servicePos = request . getServletPath ( ) . indexOf ( "" + D2RServer . getPageServiceName ( ) ) ) ) throw new ServletException ( "" + D2RServer . getPageServiceName ( ) ) ; String serviceStem = request . getServletPath ( ) . substring ( , servicePos + ) ; String resourceURI = server . resourceBaseURI ( serviceStem ) + relativeResourceURI ; String documentURL = server . dataURL ( serviceStem , relativeResourceURI ) ; String pageURL = server . pageURL ( serviceStem , relativeResourceURI ) ; VelocityWrapper velocity = new VelocityWrapper ( this , request , response ) ; Context context = velocity . getContext ( ) ; context . put ( "" , resourceURI ) ; Resource resource = ResourceFactory . createResource ( resourceURI ) ; boolean outgoingTriplesOnly = server . isVocabularyResource ( resource ) && ! server . getConfig ( ) . getVocabularyIncludeInstances ( ) ; int limit = server . getConfig ( ) . getLimitPerPropertyBridge ( ) ; Model description = null ; try { ResourceDescriber describer = new ResourceDescriber ( server . getMapping ( ) , resource . asNode ( ) , outgoingTriplesOnly , limit , Math . round ( server . getConfig ( ) . getPageTimeout ( ) * ) ) ; description = ModelFactory . createModelForGraph ( describer . description ( ) ) ; } catch ( QueryCancelledException ex ) { velocity . reportError ( , "" , "" ) ; return ; } if ( description . size ( ) == ) { velocity . reportError ( , "" , "" ) ; return ; } resource = description . getResource ( resourceURI ) ; this . prefixes = server . getPrefixes ( ) ; if ( server . getConfig ( ) . serveMetadata ( ) ) { MetadataCreator resourceMetadataCreator = new MetadataCreator ( server , server . getConfig ( ) . getResourceMetadataTemplate ( server , getServletContext ( ) ) ) ; Model metadata = resourceMetadataCreator . addMetadataFromTemplate ( resourceURI , documentURL , pageURL ) ; if ( ! metadata . isEmpty ( ) ) { List < Statement > mList = metadata . getResource ( documentURL ) . listProperties ( ) . toList ( ) ; Collections . sort ( mList , MetadataCreator . subjectSorter ) ; context . put ( "" , mList ) ; context . put ( "" , metadata . getResource ( documentURL ) ) ; Map < String , String > nsSet = metadata . getNsPrefixMap ( ) ; nsSet . putAll ( description . getNsPrefixMap ( ) ) ; context . put ( "" , nsSet . entrySet ( ) ) ; context . put ( "" , new HashMap < Resource , Boolean > ( ) ) ; context . put ( "" , new HashMap < Resource , String > ( ) ) ; } else { context . put ( "" , Boolean . FALSE ) ; } } else { context . put ( "" , Boolean . FALSE ) ; } context . put ( "" , documentURL ) ; context . put ( "" , getBestLabel ( resource ) ) ; context . put ( "" , collectProperties ( description , resource ) ) ; context . put ( "" , classmapLinks ( resource ) ) ; context . put ( "" , limit > ? limit : null ) ; velocity . mergeTemplateXHTML ( "" ) ; } private Collection < Property > collectProperties ( Model m , Resource r ) { Collection < Property > result = new TreeSet < Property > ( ) ; StmtIterator it = r . listProperties ( ) ; while ( it . hasNext ( ) ) { result . add ( new Property ( it . nextStatement ( ) , false ) ) ; } it = m . listStatements ( null , null , r ) ; while ( it . hasNext ( ) ) { result . add ( new Property ( it . nextStatement ( ) , true ) ) ; } return result ; } private Map < String , String > classmapLinks ( Resource resource ) { Map < String , String > result = new HashMap < String , String > ( ) ; D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; for ( String name : getClassMapLister ( ) . classMapNamesForResource ( resource . asNode ( ) ) ) { result . put ( name , server . baseURI ( ) + "" + name ) ; } return result ; } private ClassMapLister getClassMapLister ( ) { return D2RServer . retrieveSystemLoader ( getServletContext ( ) ) . getClassMapLister ( ) ; } private static final long serialVersionUID = ; public class Property implements Comparable < Property > { private Node property ; private Node value ; private boolean isInverse ; Property ( Statement stmt , boolean isInverse ) { this . property = stmt . getPredicate ( ) . asNode ( ) ; if ( isInverse ) { this . value = stmt . getSubject ( ) . asNode ( ) ; } else { this . value = stmt . getObject ( ) . asNode ( ) ; } this . isInverse = isInverse ; } public boolean isInverse ( ) { return this . isInverse ; } public String propertyURI ( ) { return this . property . getURI ( ) ; } public String propertyQName ( ) { String qname = prefixes . shortForm ( this . property . getURI ( ) ) ; if ( qname == null ) { return "" + this . property . getURI ( ) + ">" ; } return qname ; } public String propertyPrefix ( ) { String qname = propertyQName ( ) ; if ( qname . startsWith ( "" ) ) { return null ; } return qname . substring ( , qname . indexOf ( "" ) + ) ; } public String propertyLocalName ( ) { String qname = propertyQName ( ) ; if ( qname . startsWith ( "" ) ) { return this . property . getLocalName ( ) ; } return qname . substring ( qname . indexOf ( "" ) + ) ; } public Node value ( ) { return this . value ; } public String valueQName ( ) { if ( ! this . value . isURI ( ) ) { return null ; } return prefixes . qnameFor ( this . value . getURI ( ) ) ; } public String datatypeQName ( ) { String qname = prefixes . qnameFor ( this . value . getLiteralDatatypeURI ( ) ) ; if ( qname == null ) { return "" + this . value . getLiteralDatatypeURI ( ) + ">" ; } return qname ; } public boolean isImg ( ) { return FOAF . img . asNode ( ) . equals ( property ) || FOAF . depiction . asNode ( ) . equals ( property ) || FOAF . thumbnail . asNode ( ) . equals ( property ) ; } public int compareTo ( Property other ) { String propertyLocalName = this . property . getLocalName ( ) ; String otherLocalName = other . property . getLocalName ( ) ; if ( propertyLocalName . compareTo ( otherLocalName ) != ) { return propertyLocalName . compareTo ( otherLocalName ) ; } if ( propertyPrefix ( ) . compareTo ( other . propertyPrefix ( ) ) != ) { return propertyPrefix ( ) . compareTo ( other . propertyPrefix ( ) ) ; } if ( propertyURI ( ) . compareTo ( other . propertyURI ( ) ) != ) { return propertyURI ( ) . compareTo ( other . propertyURI ( ) ) ; } if ( this . isInverse != other . isInverse ) { return ( this . isInverse ) ? - : ; } if ( this . value . isURI ( ) || other . value . isURI ( ) ) { if ( ! other . value . isURI ( ) ) { return ; } if ( ! this . value . isURI ( ) ) { return - ; } return this . value . getURI ( ) . compareTo ( other . value . getURI ( ) ) ; } if ( this . value . isBlank ( ) || other . value . isBlank ( ) ) { if ( ! other . value . isBlank ( ) ) { return - ; } if ( ! this . value . isBlank ( ) ) { return ; } return this . value . getBlankNodeLabel ( ) . compareTo ( other . value . getBlankNodeLabel ( ) ) ; } return this . value . getLiteralLexicalForm ( ) . compareTo ( other . value . getLiteralLexicalForm ( ) ) ; } } public static Statement getBestLabel ( Resource resource ) { Statement label = resource . getProperty ( RDFS . label ) ; if ( label == null ) label = resource . getProperty ( SKOS . prefLabel ) ; if ( label == null ) label = resource . getProperty ( DC . title ) ; if ( label == null ) label = resource . getProperty ( DCTerms . title ) ; if ( label == null ) label = resource . getProperty ( FOAF . name ) ; return label ; } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; 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 javax . servlet . ServletException ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . apache . velocity . context . Context ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . ResIterator ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . ClassMapLister ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; import de . fuberlin . wiwiss . d2rq . vocab . SD ; import de . fuberlin . wiwiss . d2rq . vocab . VoID ; import de . fuberlin . wiwiss . pubby . negotiation . ContentTypeNegotiator ; import de . fuberlin . wiwiss . pubby . negotiation . MediaRangeSpec ; import de . fuberlin . wiwiss . pubby . negotiation . PubbyNegotiator ; public class DatasetDescriptionServlet extends HttpServlet { protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; if ( ! server . getConfig ( ) . serveMetadata ( ) ) { response . setStatus ( ) ; response . setContentType ( "" ) ; response . getOutputStream ( ) . println ( "" ) ; return ; } Model dDesc = ModelFactory . createDefaultModel ( ) ; dDesc . setNsPrefix ( "" , VoID . NS ) ; Resource sparqlService = dDesc . createResource ( server . getSparqlUrl ( ) ) ; Resource datasetIRI = dDesc . createResource ( server . getDatasetIri ( ) ) ; dDesc . add ( datasetIRI , RDF . type , VoID . Dataset ) ; dDesc . add ( datasetIRI , VoID . sparqlEndpoint , sparqlService ) ; dDesc . add ( datasetIRI , VoID . feature , dDesc . createResource ( "" ) ) ; dDesc . add ( datasetIRI , VoID . feature , dDesc . createResource ( "" ) ) ; dDesc . add ( datasetIRI , VoID . feature , dDesc . createResource ( "" ) ) ; ClassMapLister lister = D2RServer . retrieveSystemLoader ( getServletContext ( ) ) . getClassMapLister ( ) ; for ( String classMapName : lister . classMapNames ( ) ) { dDesc . add ( datasetIRI , VoID . rootResource , dDesc . createResource ( server . baseURI ( ) + "" + classMapName ) ) ; } dDesc . add ( datasetIRI , VoID . uriSpace , dDesc . createLiteral ( server . resourceBaseURI ( ) ) ) ; Model mapping = D2RServer . retrieveSystemLoader ( getServletContext ( ) ) . getMappingModel ( ) ; Set < String > prefixes = new HashSet < String > ( ) ; for ( Resource partClass : generatePartitions ( mapping , D2RQ . ClassMap , D2RQ . class_ ) ) { Resource classPartition = dDesc . createResource ( ) ; dDesc . add ( classPartition , VoID . class_ , partClass ) ; dDesc . add ( datasetIRI , VoID . classPartition , classPartition ) ; prefixes . add ( findPrefix ( partClass . getURI ( ) ) ) ; } for ( Resource partProp : generatePartitions ( mapping , D2RQ . PropertyBridge , D2RQ . property ) ) { Resource propertyPartition = dDesc . createResource ( ) ; dDesc . add ( propertyPartition , VoID . property , partProp ) ; dDesc . add ( datasetIRI , VoID . propertyPartition , propertyPartition ) ; prefixes . add ( findPrefix ( partProp . getURI ( ) ) ) ; } for ( String prefix : prefixes ) { dDesc . add ( datasetIRI , VoID . vocabulary , dDesc . createResource ( prefix ) ) ; } dDesc . setNsPrefix ( "" , SD . NS ) ; dDesc . add ( sparqlService , RDF . type , SD . Service ) ; dDesc . add ( sparqlService , SD . url , sparqlService ) ; dDesc . add ( sparqlService , SD . resultFormat , dDesc . createResource ( "" ) ) ; dDesc . add ( sparqlService , SD . resultFormat , dDesc . createResource ( "" ) ) ; Resource defaultDatasetDesc = dDesc . createResource ( ) ; dDesc . add ( sparqlService , SD . defaultDatasetDescription , defaultDatasetDesc ) ; dDesc . add ( defaultDatasetDesc , RDF . type , SD . Dataset ) ; dDesc . add ( defaultDatasetDesc , SD . defaultGraph , datasetIRI ) ; dDesc . add ( datasetIRI , RDF . type , SD . Graph ) ; Model datasetMetadataTemplate = server . getConfig ( ) . getDatasetMetadataTemplate ( server , getServletContext ( ) ) ; MetadataCreator datasetMetadataCreator = new MetadataCreator ( server , datasetMetadataTemplate ) ; dDesc . add ( datasetMetadataCreator . addMetadataFromTemplate ( server . getDatasetIri ( ) , server . getDatasetIri ( ) , server . getDatasetIri ( ) ) ) ; Map < String , String > dDescPrefixes = dDesc . getNsPrefixMap ( ) ; dDescPrefixes . putAll ( datasetMetadataTemplate . getNsPrefixMap ( ) ) ; dDesc . setNsPrefixes ( dDescPrefixes ) ; ContentTypeNegotiator negotiator = PubbyNegotiator . getPubbyNegotiator ( ) ; MediaRangeSpec bestMatch = negotiator . getBestMatch ( request . getHeader ( "" ) , request . getHeader ( "" ) ) ; if ( bestMatch == null ) { response . setStatus ( ) ; response . setContentType ( "" ) ; response . getOutputStream ( ) . println ( "" + "" ) ; return ; } if ( "" . equals ( bestMatch . getMediaType ( ) ) ) { VelocityWrapper velocity = new VelocityWrapper ( this , request , response ) ; Context context = velocity . getContext ( ) ; List < Statement > mList = datasetIRI . listProperties ( ) . toList ( ) ; Collections . sort ( mList , MetadataCreator . subjectSorter ) ; context . put ( "" , mList ) ; Map < String , String > nsSet = dDesc . getNsPrefixMap ( ) ; context . put ( "" , nsSet . entrySet ( ) ) ; context . put ( "" , datasetIRI ) ; context . put ( "" , new HashMap < Resource , String > ( ) ) ; context . put ( "" , new HashMap < Resource , Boolean > ( ) ) ; velocity . mergeTemplateXHTML ( "" ) ; } else { new ModelResponse ( dDesc , request , response ) . serve ( ) ; } } private static Set < Resource > generatePartitions ( Model m , Resource type , Property p ) { Set < Resource > partitions = new HashSet < Resource > ( ) ; ResIterator classIt = m . listResourcesWithProperty ( RDF . type , type ) ; while ( classIt . hasNext ( ) ) { Resource classMap = classIt . next ( ) ; StmtIterator pIt = classMap . listProperties ( p ) ; while ( pIt . hasNext ( ) ) { partitions . add ( ( Resource ) pIt . next ( ) . getObject ( ) ) ; } } return partitions ; } private static String findPrefix ( String r ) { if ( r == null ) { return "" ; } if ( r . lastIndexOf ( "" ) > - ) { return r . substring ( , r . lastIndexOf ( "" ) + ) ; } if ( r . lastIndexOf ( "" ) > - ) { return r . substring ( , r . lastIndexOf ( "" ) + ) ; } return "" ; } } package de . fuberlin . wiwiss . d2rq . server ; import org . joseki . DatasetDesc ; import org . joseki . Request ; import org . joseki . Response ; import com . hp . hpl . jena . query . Dataset ; public class D2RQDatasetDesc extends DatasetDesc { private AutoReloadableDataset dataset ; public D2RQDatasetDesc ( AutoReloadableDataset dataset ) { super ( null ) ; this . dataset = dataset ; } @ Override public Dataset acquireDataset ( Request request , Response response ) { dataset . checkMappingFileChanged ( ) ; return this . dataset ; } @ Override public void returnDataset ( Dataset ds ) { } public String toString ( ) { return "" + this . dataset + "" ; } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import java . util . Map ; import java . util . TreeMap ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . apache . velocity . context . Context ; import de . fuberlin . wiwiss . d2rq . ClassMapLister ; public class RootServlet extends HttpServlet { public void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; server . checkMappingFileChanged ( ) ; Map < String , String > classMapLinks = new TreeMap < String , String > ( ) ; ClassMapLister lister = D2RServer . retrieveSystemLoader ( getServletContext ( ) ) . getClassMapLister ( ) ; for ( String name : lister . classMapNames ( ) ) { classMapLinks . put ( name , server . baseURI ( ) + "" + name ) ; } VelocityWrapper velocity = new VelocityWrapper ( this , request , response ) ; Context context = velocity . getContext ( ) ; context . put ( "" , server . baseURI ( ) + "" ) ; context . put ( "" , classMapLinks ) ; velocity . mergeTemplateXHTML ( "" ) ; } private static final long serialVersionUID = ; } package de . fuberlin . wiwiss . d2rq . server ; import java . io . File ; import java . io . FileInputStream ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Comparator ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . rdf . model . AnonId ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . RDFNode ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . shared . JenaException ; import de . fuberlin . wiwiss . d2rq . vocab . D2RConfig ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; import de . fuberlin . wiwiss . d2rq . vocab . META ; public class MetadataCreator { private final static String metadataPlaceholderURIPrefix = "" ; private Model model = ModelFactory . createDefaultModel ( ) ; ; private D2RServer server ; private boolean enable = true ; private Model tplModel ; private static final Log log = LogFactory . getLog ( MetadataCreator . class ) ; public MetadataCreator ( D2RServer server , Model template ) { this . server = server ; if ( template != null && template . size ( ) > ) { this . enable = true ; this . tplModel = template ; } } public Model addMetadataFromTemplate ( String resourceURI , String documentURL , String pageUrl ) { if ( ! enable || tplModel == null ) { return ModelFactory . createDefaultModel ( ) ; } Model metadata = ModelFactory . createDefaultModel ( ) ; metadata . setNsPrefixes ( tplModel . getNsPrefixMap ( ) ) ; StmtIterator it = tplModel . listStatements ( ) ; while ( it . hasNext ( ) ) { Statement stmt = it . nextStatement ( ) ; Resource subj = stmt . getSubject ( ) ; Property pred = stmt . getPredicate ( ) ; RDFNode obj = stmt . getObject ( ) ; try { if ( subj . toString ( ) . contains ( metadataPlaceholderURIPrefix ) ) { subj = ( Resource ) parsePlaceholder ( subj , documentURL , resourceURI , pageUrl ) ; if ( subj == null ) { subj = model . createResource ( new AnonId ( String . valueOf ( stmt . getSubject ( ) . hashCode ( ) ) ) ) ; } } if ( obj . toString ( ) . contains ( metadataPlaceholderURIPrefix ) ) { obj = parsePlaceholder ( obj , documentURL , resourceURI , pageUrl ) ; } if ( obj != null ) { stmt = metadata . createStatement ( subj , pred , obj ) ; metadata . add ( stmt ) ; } } catch ( Exception e ) { metadata . remove ( stmt ) ; log . info ( "" + stmt . toString ( ) ) ; e . printStackTrace ( ) ; } } boolean changes = true ; while ( changes ) { changes = false ; StmtIterator stmtIt = metadata . listStatements ( ) ; List < Statement > remList = new ArrayList < Statement > ( ) ; while ( stmtIt . hasNext ( ) ) { Statement s = stmtIt . nextStatement ( ) ; if ( s . getObject ( ) . isAnon ( ) && ! ( ( Resource ) s . getObject ( ) . as ( Resource . class ) ) . listProperties ( ) . hasNext ( ) ) { remList . add ( s ) ; changes = true ; } } metadata . remove ( remList ) ; } return metadata ; } private RDFNode parsePlaceholder ( RDFNode phRes , String documentURL , String resourceURI , String pageURL ) { String phURI = phRes . asNode ( ) . getURI ( ) ; phURI = phURI . replace ( metadataPlaceholderURIPrefix , "" ) ; String phPackage = phURI . substring ( , phURI . indexOf ( "" ) + ) ; String phName = phURI . replace ( phPackage , "" ) ; phPackage = phPackage . replace ( "" , "" ) ; Resource serverConfig = server . getConfig ( ) . findServerResource ( ) ; if ( phPackage . equals ( "" ) ) { if ( phName . equals ( "" ) ) { return model . createTypedLiteral ( Calendar . getInstance ( ) ) ; } if ( phName . equals ( "" ) ) { return model . createResource ( documentURL ) ; } if ( phName . equals ( "" ) ) { return model . createResource ( resourceURI ) ; } if ( phName . equals ( "" ) ) { return model . createResource ( pageURL ) ; } if ( phName . equals ( "" ) ) { return model . createResource ( server . getDatasetIri ( ) ) ; } if ( phName . equals ( "" ) ) { return model . createTypedLiteral ( D2RServer . getVersion ( ) ) ; } } if ( phPackage . equals ( "" ) || phPackage . equals ( "" ) ) { Property p = model . createProperty ( D2RConfig . NS + phName ) ; if ( serverConfig != null && serverConfig . hasProperty ( p ) ) { return serverConfig . getProperty ( p ) . getObject ( ) ; } } Resource mappingConfig = server . getConfig ( ) . findDatabaseResource ( ) ; if ( phPackage . equals ( "" ) ) { Property p = model . createProperty ( D2RQ . NS + phName ) ; if ( mappingConfig != null && mappingConfig . hasProperty ( p ) ) { return mappingConfig . getProperty ( p ) . getObject ( ) ; } } if ( phPackage . equals ( "" ) ) { Property p = model . createProperty ( META . NS + phName ) ; if ( serverConfig != null && serverConfig . hasProperty ( p ) ) return serverConfig . getProperty ( p ) . getObject ( ) ; } return model . createResource ( new AnonId ( String . valueOf ( phRes . hashCode ( ) ) ) ) ; } public static File findTemplateFile ( D2RServer server , Property fileConfigurationProperty ) { Resource config = server . getConfig ( ) . findServerResource ( ) ; if ( config == null || ! config . hasProperty ( fileConfigurationProperty ) ) { return null ; } String metadataTemplate = config . getProperty ( fileConfigurationProperty ) . getString ( ) ; String templatePath ; if ( metadataTemplate . startsWith ( File . separator ) ) { templatePath = metadataTemplate ; } else { File mappingFile = new File ( server . getConfig ( ) . getLocalMappingFilename ( ) ) ; String folder = mappingFile . getParent ( ) ; if ( folder != null ) { templatePath = folder + File . separator + metadataTemplate ; } else { templatePath = metadataTemplate ; } } File f = new File ( templatePath ) ; return f ; } public static Model loadTemplateFile ( File f ) { try { return loadMetadataTemplate ( new FileInputStream ( f ) ) ; } catch ( Exception e ) { return null ; } } public static Model loadMetadataTemplate ( InputStream is ) { try { Model tplModel = ModelFactory . createDefaultModel ( ) ; tplModel . read ( is , "" , "" ) ; return tplModel ; } catch ( JenaException e ) { } return null ; } public static Comparator < Statement > subjectSorter = new Comparator < Statement > ( ) { public int compare ( Statement o1 , Statement o2 ) { return o1 . getPredicate ( ) . toString ( ) . compareTo ( o2 . getPredicate ( ) . toString ( ) ) ; } } ; } package de . fuberlin . wiwiss . d2rq . server ; import java . util . Random ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jetty . server . Server ; import org . eclipse . jetty . server . session . HashSessionIdManager ; import org . eclipse . jetty . webapp . WebAppContext ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; public class JettyLauncher { private final static Log log = LogFactory . getLog ( JettyLauncher . class ) ; private final SystemLoader loader ; private final int port ; public JettyLauncher ( SystemLoader loader , int port ) { this . loader = loader ; this . port = port ; } public boolean start ( ) { Server jetty = new Server ( port ) ; jetty . setSessionIdManager ( new HashSessionIdManager ( new Random ( ) ) ) ; WebAppContext context = new WebAppContext ( jetty , "" , "" ) ; D2RServer . storeSystemLoader ( loader , context . getServletContext ( ) ) ; try { jetty . start ( ) ; D2RServer server = D2RServer . fromServletContext ( context . getServletContext ( ) ) ; if ( server == null || server . errorOnStartup ( ) ) { jetty . stop ( ) ; log . warn ( "" ) ; return false ; } log . info ( "" + loader . getSystemBaseURI ( ) + "" ) ; return true ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import java . util . Map ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import com . hp . hpl . jena . query . QueryExecution ; import com . hp . hpl . jena . query . QueryExecutionFactory ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . sparql . vocabulary . FOAF ; import com . hp . hpl . jena . vocabulary . RDFS ; public class ResourceDescriptionServlet extends HttpServlet { protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; server . checkMappingFileChanged ( ) ; String relativeResourceURI = request . getRequestURI ( ) . substring ( request . getContextPath ( ) . length ( ) + request . getServletPath ( ) . length ( ) ) ; if ( ! "" . equals ( relativeResourceURI ) && "" . equals ( relativeResourceURI . substring ( , ) ) ) { relativeResourceURI = relativeResourceURI . substring ( ) ; } if ( request . getQueryString ( ) != null ) { relativeResourceURI = relativeResourceURI + "" + request . getQueryString ( ) ; } int servicePos ; if ( - == ( servicePos = request . getServletPath ( ) . indexOf ( "" + D2RServer . getDataServiceName ( ) ) ) ) throw new ServletException ( "" + D2RServer . getDataServiceName ( ) ) ; String serviceStem = request . getServletPath ( ) . substring ( , servicePos + ) ; String resourceURI = RequestParamHandler . removeOutputRequestParam ( server . resourceBaseURI ( serviceStem ) + relativeResourceURI ) ; String documentURL = server . dataURL ( serviceStem , relativeResourceURI ) ; String pageURL = server . pageURL ( serviceStem , relativeResourceURI ) ; String sparqlQuery = "" + resourceURI + ">" ; QueryExecution qe = QueryExecutionFactory . create ( sparqlQuery , server . dataset ( ) ) ; if ( server . getConfig ( ) . getPageTimeout ( ) > ) { qe . setTimeout ( Math . round ( server . getConfig ( ) . getPageTimeout ( ) * ) ) ; } Model description = qe . execDescribe ( ) ; qe . close ( ) ; if ( description . size ( ) == ) { response . sendError ( ) ; } if ( description . qnameFor ( FOAF . primaryTopic . getURI ( ) ) == null && description . getNsPrefixURI ( "" ) == null ) { description . setNsPrefix ( "" , FOAF . NS ) ; } Resource resource = description . getResource ( resourceURI ) ; Resource document = description . getResource ( documentURL ) ; document . addProperty ( FOAF . primaryTopic , resource ) ; Statement label = resource . getProperty ( RDFS . label ) ; if ( label != null ) { document . addProperty ( RDFS . label , "" + label . getString ( ) ) ; } server . addDocumentMetadata ( description , document ) ; if ( server . getConfig ( ) . serveMetadata ( ) ) { Model resourceMetadataTemplate = server . getConfig ( ) . getResourceMetadataTemplate ( server , getServletContext ( ) ) ; MetadataCreator resourceMetadataCreator = new MetadataCreator ( server , resourceMetadataTemplate ) ; description . add ( resourceMetadataCreator . addMetadataFromTemplate ( resourceURI , documentURL , pageURL ) ) ; Map < String , String > descPrefixes = description . getNsPrefixMap ( ) ; descPrefixes . putAll ( resourceMetadataTemplate . getNsPrefixMap ( ) ) ; description . setNsPrefixes ( descPrefixes ) ; } new ModelResponse ( description , request , response ) . serve ( ) ; } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import java . util . Map ; import java . util . TreeMap ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . apache . velocity . context . Context ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ResIterator ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import de . fuberlin . wiwiss . d2rq . ClassMapLister ; public class DirectoryServlet extends HttpServlet { protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; server . checkMappingFileChanged ( ) ; if ( request . getPathInfo ( ) == null ) { response . sendError ( ) ; return ; } String classMapName = request . getPathInfo ( ) . substring ( ) ; Model resourceList = getClassMapLister ( ) . classMapInventory ( classMapName , server . getConfig ( ) . getLimitPerClassMap ( ) ) ; if ( resourceList == null ) { response . sendError ( , "" + classMapName + "" ) ; return ; } Map < String , String > resources = new TreeMap < String , String > ( ) ; ResIterator subjects = resourceList . listSubjects ( ) ; while ( subjects . hasNext ( ) ) { Resource resource = subjects . nextResource ( ) ; if ( ! resource . isURIResource ( ) ) { continue ; } String uri = resource . getURI ( ) ; Statement labelStmt = PageServlet . getBestLabel ( resource ) ; String label = ( labelStmt == null ) ? resource . getURI ( ) : labelStmt . getString ( ) ; resources . put ( uri , label ) ; } Map < String , String > classMapLinks = new TreeMap < String , String > ( ) ; for ( String name : getClassMapLister ( ) . classMapNames ( ) ) { classMapLinks . put ( name , server . baseURI ( ) + "" + name ) ; } VelocityWrapper velocity = new VelocityWrapper ( this , request , response ) ; Context context = velocity . getContext ( ) ; context . put ( "" , server . baseURI ( ) + "" + classMapName ) ; context . put ( "" , classMapName ) ; context . put ( "" , classMapLinks ) ; context . put ( "" , resources ) ; context . put ( "" , server . getConfig ( ) . getLimitPerClassMap ( ) ) ; velocity . mergeTemplateXHTML ( "" ) ; } private ClassMapLister getClassMapLister ( ) { return D2RServer . retrieveSystemLoader ( getServletContext ( ) ) . getClassMapLister ( ) ; } private static final long serialVersionUID = ; } package de . fuberlin . wiwiss . d2rq . server ; import java . io . File ; import java . util . Iterator ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . query . Dataset ; import com . hp . hpl . jena . query . LabelExistsException ; import com . hp . hpl . jena . query . ReadWrite ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . shared . Lock ; import com . hp . hpl . jena . shared . PrefixMapping ; import com . hp . hpl . jena . sparql . core . DatasetGraph ; import com . hp . hpl . jena . sparql . core . DatasetGraphFactory ; import com . hp . hpl . jena . util . iterator . NullIterator ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; import de . fuberlin . wiwiss . d2rq . jena . GraphD2RQ ; import de . fuberlin . wiwiss . d2rq . map . Database ; public class AutoReloadableDataset implements Dataset { private static Log log = LogFactory . getLog ( AutoReloadableDataset . class ) ; private static long RELOAD_FREQUENCY_MS = ; private final SystemLoader loader ; private final File watchedFile ; private final boolean autoReload ; private DatasetGraph datasetGraph = null ; private long lastModified = Long . MAX_VALUE ; private long lastReload = Long . MIN_VALUE ; private boolean hasTruncatedResults ; private Model defaultModel ; public AutoReloadableDataset ( SystemLoader loader , String watchedFile , boolean autoReload ) { this . loader = loader ; this . watchedFile = watchedFile == null ? null : new File ( watchedFile ) ; this . autoReload = autoReload ; reload ( ) ; } public void checkMappingFileChanged ( ) { if ( ! autoReload ) return ; long now = System . currentTimeMillis ( ) ; if ( now < this . lastReload + RELOAD_FREQUENCY_MS ) return ; if ( watchedFile . lastModified ( ) == this . lastModified ) return ; log . info ( "" ) ; datasetGraph . close ( ) ; loader . resetMappingFile ( ) ; reload ( ) ; } private void reload ( ) { loader . getMapping ( ) . connect ( ) ; GraphD2RQ graph = loader . getGraphD2RQ ( ) ; datasetGraph = DatasetGraphFactory . createOneGraph ( graph ) ; defaultModel = ModelFactory . createModelForGraph ( datasetGraph . getDefaultGraph ( ) ) ; hasTruncatedResults = false ; for ( Database db : loader . getMapping ( ) . databases ( ) ) { if ( db . getResultSizeLimit ( ) != Database . NO_LIMIT ) { hasTruncatedResults = true ; } } if ( autoReload ) { lastModified = watchedFile . lastModified ( ) ; lastReload = System . currentTimeMillis ( ) ; } } public PrefixMapping getPrefixMapping ( ) { return this . datasetGraph . getDefaultGraph ( ) . getPrefixMapping ( ) ; } public boolean hasTruncatedResults ( ) { return hasTruncatedResults ; } public DatasetGraph asDatasetGraph ( ) { return datasetGraph ; } public Model getDefaultModel ( ) { return defaultModel ; } public boolean containsNamedModel ( String uri ) { return false ; } public Lock getLock ( ) { return datasetGraph . getLock ( ) ; } public Model getNamedModel ( String uri ) { return null ; } public Iterator < String > listNames ( ) { return NullIterator . instance ( ) ; } public void close ( ) { datasetGraph . close ( ) ; } public void setDefaultModel ( Model model ) { throw new UnsupportedOperationException ( "" ) ; } public void addNamedModel ( String uri , Model model ) throws LabelExistsException { throw new UnsupportedOperationException ( "" ) ; } public void removeNamedModel ( String uri ) { throw new UnsupportedOperationException ( "" ) ; } public void replaceNamedModel ( String uri , Model model ) { throw new UnsupportedOperationException ( "" ) ; } public boolean supportsTransactions ( ) { return false ; } public void begin ( ReadWrite readWrite ) { throw new UnsupportedOperationException ( "" ) ; } public void commit ( ) { throw new UnsupportedOperationException ( "" ) ; } public void abort ( ) { throw new UnsupportedOperationException ( "" ) ; } public boolean isInTransaction ( ) { return false ; } public void end ( ) { throw new UnsupportedOperationException ( "" ) ; } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import javax . servlet . ServletException ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . vocabulary . RDFS ; import de . fuberlin . wiwiss . d2rq . ClassMapLister ; public class ClassMapServlet extends HttpServlet { protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; server . checkMappingFileChanged ( ) ; if ( request . getPathInfo ( ) == null ) { new ModelResponse ( classMapListModel ( ) , request , response ) . serve ( ) ; return ; } String classMapName = request . getPathInfo ( ) . substring ( ) ; Model resourceList = getClassMapLister ( ) . classMapInventory ( classMapName ) ; if ( resourceList == null ) { response . sendError ( , "" + classMapName + "" ) ; return ; } Resource classMap = resourceList . getResource ( server . baseURI ( ) + "" + classMapName ) ; Resource directory = resourceList . createResource ( server . baseURI ( ) + "" ) ; classMap . addProperty ( RDFS . seeAlso , directory ) ; classMap . addProperty ( RDFS . label , "" + classMapName ) ; directory . addProperty ( RDFS . label , "" ) ; server . addDocumentMetadata ( resourceList , classMap ) ; new ModelResponse ( resourceList , request , response ) . serve ( ) ; } private ClassMapLister getClassMapLister ( ) { return D2RServer . retrieveSystemLoader ( getServletContext ( ) ) . getClassMapLister ( ) ; } private Model classMapListModel ( ) { D2RServer server = D2RServer . fromServletContext ( getServletContext ( ) ) ; Model result = ModelFactory . createDefaultModel ( ) ; Resource list = result . createResource ( server . baseURI ( ) + "" ) ; list . addProperty ( RDFS . label , "" ) ; for ( String classMapName : getClassMapLister ( ) . classMapNames ( ) ) { Resource instances = result . createResource ( server . baseURI ( ) + "" + classMapName ) ; list . addProperty ( RDFS . seeAlso , instances ) ; instances . addProperty ( RDFS . label , "" + classMapName ) ; } server . addDocumentMetadata ( result , list ) ; return result ; } private static final long serialVersionUID = ; } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import java . io . OutputStreamWriter ; import javax . servlet . ServletOutputStream ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . RDFWriter ; import com . hp . hpl . jena . shared . JenaException ; import de . fuberlin . wiwiss . pubby . negotiation . ContentTypeNegotiator ; import de . fuberlin . wiwiss . pubby . negotiation . MediaRangeSpec ; import de . fuberlin . wiwiss . pubby . negotiation . PubbyNegotiator ; public class ModelResponse { private final Model model ; private final HttpServletRequest request ; private final HttpServletResponse response ; public ModelResponse ( Model model , HttpServletRequest request , HttpServletResponse response ) { RequestParamHandler handler = new RequestParamHandler ( request ) ; if ( handler . isMatchingRequest ( ) ) { request = handler . getModifiedRequest ( ) ; } this . model = model ; this . request = request ; this . response = response ; } public void serve ( ) { try { doResponseModel ( ) ; } catch ( IOException ioEx ) { throw new RuntimeException ( ioEx ) ; } catch ( JenaException jEx ) { try { response . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , "" + jEx . getMessage ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } private void doResponseModel ( ) throws IOException { response . addHeader ( "" , "" ) ; ContentTypeNegotiator negotiator = PubbyNegotiator . getDataNegotiator ( ) ; MediaRangeSpec bestMatch = negotiator . getBestMatch ( request . getHeader ( "" ) , request . getHeader ( "" ) ) ; if ( bestMatch == null ) { response . setStatus ( ) ; response . setContentType ( "" ) ; ServletOutputStream out = response . getOutputStream ( ) ; out . println ( "" ) ; out . println ( "" ) ; return ; } response . setContentType ( bestMatch . getMediaType ( ) ) ; getWriter ( bestMatch . getMediaType ( ) ) . write ( model , response ) ; response . getOutputStream ( ) . flush ( ) ; } private ModelWriter getWriter ( String mediaType ) { if ( "" . equals ( mediaType ) ) { return new RDFXMLWriter ( ) ; } if ( "" . equals ( mediaType ) ) { return new TurtleWriter ( ) ; } if ( "" . equals ( mediaType ) ) { return new N3Writer ( ) ; } return new NTriplesWriter ( ) ; } private interface ModelWriter { void write ( Model model , HttpServletResponse response ) throws IOException ; } private class NTriplesWriter implements ModelWriter { public void write ( Model model , HttpServletResponse response ) throws IOException { model . getWriter ( "" ) . write ( model , response . getOutputStream ( ) , null ) ; } } private class N3Writer implements ModelWriter { public void write ( Model model , HttpServletResponse response ) throws IOException { model . getWriter ( "" ) . write ( model , response . getOutputStream ( ) , null ) ; } } private class TurtleWriter implements ModelWriter { public void write ( Model model , HttpServletResponse response ) throws IOException { model . getWriter ( "" ) . write ( model , response . getOutputStream ( ) , null ) ; } } private class RDFXMLWriter implements ModelWriter { public void write ( Model model , HttpServletResponse response ) throws IOException { RDFWriter writer = model . getWriter ( "" ) ; writer . setProperty ( "" , "" ) ; writer . setProperty ( "" , "" ) ; writer . write ( model , new OutputStreamWriter ( response . getOutputStream ( ) , "" ) , null ) ; } } } package de . fuberlin . wiwiss . d2rq . server ; import javax . servlet . ServletContext ; import javax . servlet . ServletContextEvent ; import javax . servlet . ServletContextListener ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import de . fuberlin . wiwiss . d2rq . SystemLoader ; public class WebappInitListener implements ServletContextListener { private final static Log log = LogFactory . getLog ( WebappInitListener . class ) ; public void contextInitialized ( ServletContextEvent event ) { ServletContext context = event . getServletContext ( ) ; SystemLoader loader = D2RServer . retrieveSystemLoader ( context ) ; if ( loader == null ) { log . info ( "" ) ; loader = new SystemLoader ( ) ; D2RServer . storeSystemLoader ( loader , context ) ; if ( context . getInitParameter ( "" ) == null ) { throw new RuntimeException ( "" ) ; } String configFileName = absolutize ( context . getInitParameter ( "" ) , context ) ; loader . setMappingURL ( configFileName ) ; loader . setResourceStem ( "" ) ; } D2RServer server = loader . getD2RServer ( ) ; server . start ( ) ; VelocityWrapper . initEngine ( server , context ) ; } public void contextDestroyed ( ServletContextEvent event ) { D2RServer server = D2RServer . fromServletContext ( event . getServletContext ( ) ) ; if ( server != null ) server . shutdown ( ) ; } private String absolutize ( String fileName , ServletContext context ) { if ( ! fileName . matches ( "" ) ) { fileName = context . getRealPath ( "" + fileName ) ; } return ConfigLoader . toAbsoluteURI ( fileName ) ; } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import java . util . regex . Pattern ; import javax . servlet . ServletContext ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . apache . velocity . VelocityContext ; import org . apache . velocity . app . VelocityEngine ; import org . apache . velocity . context . Context ; import de . fuberlin . wiwiss . pubby . negotiation . ContentTypeNegotiator ; import de . fuberlin . wiwiss . pubby . negotiation . MediaRangeSpec ; public class VelocityWrapper { private final static String VELOCITY_ENGINE_INSTANCE = "" ; private final static String VELOCITY_DEFAULT_CONTEXT = "" ; private final static String TEXTHTML_CONTENTTYPE = "" ; private final static String APPLICATIONXML_CONTENTTYPE = "" ; private final static ContentTypeNegotiator xhtmlNegotiator ; static { xhtmlNegotiator = new ContentTypeNegotiator ( ) ; xhtmlNegotiator . setDefaultAccept ( TEXTHTML_CONTENTTYPE ) ; xhtmlNegotiator . addUserAgentOverride ( Pattern . compile ( "" ) , null , TEXTHTML_CONTENTTYPE ) ; xhtmlNegotiator . addVariant ( APPLICATIONXML_CONTENTTYPE + "" ) ; xhtmlNegotiator . addVariant ( TEXTHTML_CONTENTTYPE + "" ) ; } public static synchronized void initEngine ( D2RServer d2r , ServletContext servletContext ) { try { VelocityEngine engine = new VelocityEngine ( servletContext . getRealPath ( "" ) ) ; engine . init ( ) ; servletContext . setAttribute ( VELOCITY_ENGINE_INSTANCE , engine ) ; servletContext . setAttribute ( VELOCITY_DEFAULT_CONTEXT , initDefaultContext ( d2r ) ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } private static Context initDefaultContext ( D2RServer server ) { Context context = new VelocityContext ( ) ; context . put ( "" , new Boolean ( server . hasTruncatedResults ( ) ) ) ; context . put ( "" , server . serverName ( ) ) ; context . put ( "" , server . baseURI ( ) ) ; return context ; } private final VelocityEngine engine ; private final Context context ; private final HttpServletRequest request ; private final HttpServletResponse response ; public VelocityWrapper ( HttpServlet servlet , HttpServletRequest request , HttpServletResponse response ) { engine = ( VelocityEngine ) servlet . getServletContext ( ) . getAttribute ( VELOCITY_ENGINE_INSTANCE ) ; Context defaultContext = ( Context ) servlet . getServletContext ( ) . getAttribute ( VELOCITY_DEFAULT_CONTEXT ) ; context = new VelocityContext ( defaultContext ) ; this . request = request ; this . response = response ; } public Context getContext ( ) { return context ; } public VelocityEngine getEngine ( ) { return engine ; } public void mergeTemplateXHTML ( String templateName ) { MediaRangeSpec bestMatch = xhtmlNegotiator . getBestMatch ( request . getHeader ( "" ) , request . getHeader ( "" ) ) ; response . addHeader ( "" , bestMatch != null ? bestMatch . getMediaType ( ) : TEXTHTML_CONTENTTYPE ) ; response . addHeader ( "" , "" ) ; response . addHeader ( "" , "" ) ; response . addHeader ( "" , "" ) ; try { engine . mergeTemplate ( templateName , "" , context , response . getWriter ( ) ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } public void reportError ( int statusCode , String title , String details ) throws IOException { response . setStatus ( statusCode ) ; context . put ( "" , title ) ; context . put ( "" , details ) ; mergeTemplateXHTML ( "" ) ; } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . File ; import java . io . InputStream ; import java . net . URI ; import java . net . URISyntaxException ; import javax . servlet . ServletContext ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . ResIterator ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . shared . JenaException ; import com . hp . hpl . jena . util . FileManager ; import com . hp . hpl . jena . vocabulary . RDF ; import com . hp . hpl . jena . vocabulary . RDFS ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . vocab . D2RConfig ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; import de . fuberlin . wiwiss . d2rq . vocab . VocabularySummarizer ; public class ConfigLoader { public static final int DEFAULT_LIMIT_PER_CLASS_MAP = ; public static final int DEFAULT_LIMIT_PER_PROPERTY_BRIDGE = ; private static final Log log = LogFactory . getLog ( ConfigLoader . class ) ; public static String toAbsoluteURI ( String fileName ) { if ( System . getProperty ( "" ) . toLowerCase ( ) . indexOf ( "" ) != - ) { fileName = fileName . replaceAll ( "" , "" ) ; } try { if ( fileName . matches ( "" ) && new URI ( fileName ) . isAbsolute ( ) ) { return fileName ; } return new File ( fileName ) . getAbsoluteFile ( ) . toURI ( ) . normalize ( ) . toString ( ) ; } catch ( URISyntaxException ex ) { throw new D2RQException ( ex ) ; } } private boolean isLocalMappingFile ; private String configURL ; private String mappingFilename = null ; private Model model = null ; private int port = - ; private String baseURI = null ; private String serverName = null ; private Resource documentMetadata = null ; private boolean vocabularyIncludeInstances = true ; private boolean autoReloadMapping = true ; private int limitPerClassMap = DEFAULT_LIMIT_PER_CLASS_MAP ; private int limitPerPropertyBridge = DEFAULT_LIMIT_PER_PROPERTY_BRIDGE ; private boolean enableMetadata = true ; private double sparqlTimeout = ; private double pageTimeout = ; public ConfigLoader ( String configURL ) { this . configURL = configURL ; if ( configURL == null ) { isLocalMappingFile = false ; } else { if ( configURL . startsWith ( "" ) ) { isLocalMappingFile = true ; mappingFilename = configURL . substring ( ) ; } else if ( configURL . startsWith ( "" ) ) { isLocalMappingFile = true ; mappingFilename = configURL . substring ( ) ; } else if ( configURL . indexOf ( "" ) == - ) { isLocalMappingFile = true ; mappingFilename = configURL ; } } } public void load ( ) { if ( configURL == null ) { model = ModelFactory . createDefaultModel ( ) ; return ; } this . model = FileManager . get ( ) . loadModel ( this . configURL ) ; Resource server = findServerResource ( ) ; if ( server == null ) { return ; } new VocabularySummarizer ( D2RConfig . class ) . assertNoUndefinedTerms ( model , D2RQException . CONFIG_UNKNOWN_PROPERTY , D2RQException . CONFIG_UNKNOWN_CLASS ) ; Statement s = server . getProperty ( D2RConfig . baseURI ) ; if ( s != null ) { this . baseURI = s . getResource ( ) . getURI ( ) ; } s = server . getProperty ( D2RConfig . port ) ; if ( s != null ) { String value = s . getLiteral ( ) . getLexicalForm ( ) ; try { this . port = Integer . parseInt ( value ) ; } catch ( NumberFormatException ex ) { throw new D2RQException ( "" + value + "" , D2RQException . MUST_BE_NUMERIC ) ; } } s = server . getProperty ( RDFS . label ) ; if ( s != null ) { this . serverName = s . getString ( ) ; } s = server . getProperty ( D2RConfig . documentMetadata ) ; if ( s != null ) { this . documentMetadata = s . getResource ( ) ; } s = server . getProperty ( D2RConfig . vocabularyIncludeInstances ) ; if ( s != null ) { this . vocabularyIncludeInstances = s . getBoolean ( ) ; } s = server . getProperty ( D2RConfig . autoReloadMapping ) ; if ( s != null ) { this . autoReloadMapping = s . getBoolean ( ) ; } s = server . getProperty ( D2RConfig . limitPerClassMap ) ; if ( s != null ) { try { limitPerClassMap = s . getInt ( ) ; } catch ( JenaException ex ) { if ( ! s . getBoolean ( ) ) { limitPerClassMap = Relation . NO_LIMIT ; } } } s = server . getProperty ( D2RConfig . limitPerPropertyBridge ) ; if ( s != null ) { try { limitPerPropertyBridge = s . getInt ( ) ; } catch ( JenaException ex ) { if ( ! s . getBoolean ( ) ) { limitPerPropertyBridge = Relation . NO_LIMIT ; } } } s = server . getProperty ( D2RConfig . enableMetadata ) ; if ( s != null ) { this . enableMetadata = s . getBoolean ( ) ; } s = server . getProperty ( D2RConfig . pageTimeout ) ; if ( s != null ) { try { String value = s . getLiteral ( ) . getLexicalForm ( ) ; pageTimeout = Double . parseDouble ( value ) ; } catch ( Exception ex ) { throw new D2RQException ( "" + s . getObject ( ) + "" , D2RQException . MUST_BE_NUMERIC ) ; } } s = server . getProperty ( D2RConfig . sparqlTimeout ) ; if ( s != null ) { try { String value = s . getLiteral ( ) . getLexicalForm ( ) ; sparqlTimeout = Double . parseDouble ( value ) ; } catch ( Exception ex ) { throw new D2RQException ( "" + s . getObject ( ) + "" , D2RQException . MUST_BE_NUMERIC ) ; } } } public boolean isLocalMappingFile ( ) { return this . isLocalMappingFile ; } public String getLocalMappingFilename ( ) { if ( ! this . isLocalMappingFile ) { return null ; } return this . mappingFilename ; } public int port ( ) { if ( this . model == null ) { throw new IllegalStateException ( "" ) ; } return this . port ; } public String baseURI ( ) { if ( this . model == null ) { throw new IllegalStateException ( "" ) ; } return this . baseURI ; } public String serverName ( ) { if ( this . model == null ) { throw new IllegalStateException ( "" ) ; } return this . serverName ; } public boolean getVocabularyIncludeInstances ( ) { return this . vocabularyIncludeInstances ; } public int getLimitPerClassMap ( ) { return limitPerClassMap ; } public int getLimitPerPropertyBridge ( ) { return limitPerPropertyBridge ; } public boolean getAutoReloadMapping ( ) { return this . autoReloadMapping ; } public double getPageTimeout ( ) { return pageTimeout ; } public double getSPARQLTimeout ( ) { return sparqlTimeout ; } public void addDocumentMetadata ( Model document , Resource documentResource ) { if ( this . documentMetadata == null ) { return ; } if ( this . model == null ) { throw new IllegalStateException ( "" ) ; } StmtIterator it = this . documentMetadata . listProperties ( ) ; while ( it . hasNext ( ) ) { Statement stmt = it . nextStatement ( ) ; document . add ( documentResource , stmt . getPredicate ( ) , stmt . getObject ( ) ) ; } it = this . model . listStatements ( null , null , this . documentMetadata ) ; while ( it . hasNext ( ) ) { Statement stmt = it . nextStatement ( ) ; if ( stmt . getPredicate ( ) . equals ( D2RConfig . documentMetadata ) ) { continue ; } document . add ( stmt . getSubject ( ) , stmt . getPredicate ( ) , documentResource ) ; } } protected Resource findServerResource ( ) { ResIterator it = this . model . listSubjectsWithProperty ( RDF . type , D2RConfig . Server ) ; if ( ! it . hasNext ( ) ) { return null ; } return it . nextResource ( ) ; } protected Resource findDatabaseResource ( ) { ResIterator it = this . model . listSubjectsWithProperty ( RDF . type , D2RQ . Database ) ; if ( ! it . hasNext ( ) ) { return null ; } return it . nextResource ( ) ; } private Model resourceMetadataTemplate = null ; protected Model getResourceMetadataTemplate ( D2RServer server , ServletContext context ) { if ( resourceMetadataTemplate == null ) { resourceMetadataTemplate = loadMetadataTemplate ( server , context , D2RConfig . metadataTemplate , "" ) ; } return resourceMetadataTemplate ; } private Model datasetMetadataTemplate = null ; protected Model getDatasetMetadataTemplate ( D2RServer server , ServletContext context ) { if ( datasetMetadataTemplate == null ) { datasetMetadataTemplate = loadMetadataTemplate ( server , context , D2RConfig . datasetMetadataTemplate , "" ) ; } return datasetMetadataTemplate ; } private Model loadMetadataTemplate ( D2RServer server , ServletContext context , Property configurationFlag , String defaultTemplateName ) { Model metadataTemplate ; File userTemplateFile = MetadataCreator . findTemplateFile ( server , configurationFlag ) ; Model userResourceTemplate = MetadataCreator . loadTemplateFile ( userTemplateFile ) ; if ( userResourceTemplate != null && userResourceTemplate . size ( ) > ) { metadataTemplate = userResourceTemplate ; log . info ( "" + userTemplateFile + "" ) ; } else { InputStream drtStream = context . getResourceAsStream ( "" + defaultTemplateName ) ; log . info ( "" ) ; metadataTemplate = MetadataCreator . loadMetadataTemplate ( drtStream ) ; } return metadataTemplate ; } protected boolean serveMetadata ( ) { return enableMetadata ; } } package de . fuberlin . wiwiss . d2rq . server ; import java . io . IOException ; import java . util . Iterator ; import java . util . Map . Entry ; import javax . servlet . ServletException ; import javax . servlet . ServletOutputStream ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; public class NamespaceServlet extends HttpServlet { protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { D2RServer d2r = D2RServer . fromServletContext ( getServletContext ( ) ) ; d2r . checkMappingFileChanged ( ) ; response . setContentType ( "" ) ; ServletOutputStream out = response . getOutputStream ( ) ; d2r . getPrefixes ( ) . getNsPrefixMap ( ) ; out . println ( "" ) ; out . println ( "" ) ; Iterator < Entry < String , String > > it = d2r . getPrefixes ( ) . getNsPrefixMap ( ) . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Entry < String , String > entry = it . next ( ) ; out . print ( "" + entry . getKey ( ) + "" + entry . getValue ( ) + "" ) ; if ( it . hasNext ( ) ) { out . print ( "" ) ; } out . println ( ) ; } out . println ( "" ) ; } private static final long serialVersionUID = - ; } package de . fuberlin . wiwiss . d2rq . server ; import java . util . Enumeration ; import java . util . HashMap ; import java . util . Vector ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletRequestWrapper ; public class RequestParamHandler { private static final String ATTRIBUTE_NAME_IS_HANDLED = "" ; private final static HashMap < String , String > mimeTypes = new HashMap < String , String > ( ) ; static { mimeTypes . put ( "" , "" ) ; mimeTypes . put ( "" , "" ) ; mimeTypes . put ( "" , "" ) ; mimeTypes . put ( "" , "" ) ; mimeTypes . put ( "" , "" ) ; mimeTypes . put ( "" , "" ) ; mimeTypes . put ( "" , "" ) ; } public static String removeOutputRequestParam ( String uri ) { return uri . replaceFirst ( "" , "" ) ; } private final HttpServletRequest request ; private final String requestedType ; public RequestParamHandler ( HttpServletRequest request ) { this . request = request ; requestedType = identifyRequestedType ( request . getParameter ( "" ) ) ; } public boolean isMatchingRequest ( ) { if ( "" . equals ( request . getAttribute ( ATTRIBUTE_NAME_IS_HANDLED ) ) ) { return false ; } return requestedType != null ; } public HttpServletRequest getModifiedRequest ( ) { return new WrappedRequest ( ) ; } private String identifyRequestedType ( String parameterValue ) { if ( mimeTypes . containsKey ( parameterValue ) ) { return parameterValue ; } return null ; } private class WrappedRequest extends HttpServletRequestWrapper { WrappedRequest ( ) { super ( request ) ; setAttribute ( ATTRIBUTE_NAME_IS_HANDLED , "" ) ; } public String getHeader ( String name ) { if ( "" . equals ( name . toLowerCase ( ) ) ) { return ( String ) mimeTypes . get ( requestedType ) ; } return super . getHeader ( name ) ; } public Enumeration < String > getHeaderNames ( ) { final Enumeration < String > realHeaders = super . getHeaderNames ( ) ; return new Enumeration < String > ( ) { private String prefetched = null ; public boolean hasMoreElements ( ) { while ( prefetched == null && realHeaders . hasMoreElements ( ) ) { String next = realHeaders . nextElement ( ) ; if ( ! "" . equals ( next . toLowerCase ( ) ) ) { prefetched = next ; } } return ( prefetched != null ) ; } public String nextElement ( ) { return prefetched ; } } ; } public Enumeration < String > getHeaders ( String name ) { if ( "" . equals ( name . toLowerCase ( ) ) ) { Vector < String > v = new Vector < String > ( ) ; v . add ( getHeader ( name ) ) ; return v . elements ( ) ; } return super . getHeaders ( name ) ; } } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; public class ColumnRenamerMap extends ColumnRenamer { private Map < Attribute , Attribute > originalsToReplacements ; public ColumnRenamerMap ( Map < Attribute , Attribute > originalsToReplacements ) { this . originalsToReplacements = originalsToReplacements ; } public Attribute applyTo ( Attribute original ) { if ( this . originalsToReplacements . containsKey ( original ) ) { return ( Attribute ) this . originalsToReplacements . get ( original ) ; } return original ; } public AliasMap applyTo ( AliasMap aliases ) { return aliases ; } public String toString ( ) { StringBuffer result = new StringBuffer ( ) ; result . append ( "" ) ; List < Attribute > columns = new ArrayList < Attribute > ( this . originalsToReplacements . keySet ( ) ) ; Collections . sort ( columns ) ; Iterator < Attribute > it = columns . iterator ( ) ; while ( it . hasNext ( ) ) { Attribute column = it . next ( ) ; result . append ( column . qualifiedName ( ) ) ; result . append ( "" ) ; result . append ( ( ( Attribute ) this . originalsToReplacements . get ( column ) ) . qualifiedName ( ) ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Arrays ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Set ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . sparql . core . Var ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; public class TripleRelation extends NodeRelation { public static final Var SUBJECT = Var . alloc ( "" ) ; public static final Var PREDICATE = Var . alloc ( "" ) ; public static final Var OBJECT = Var . alloc ( "" ) ; private static final Set < Var > SPO = new HashSet < Var > ( Arrays . asList ( new Var [ ] { SUBJECT , PREDICATE , OBJECT } ) ) ; private static final TripleRelation EMPTY = fromNodeRelation ( NodeRelation . empty ( SPO ) ) ; private static TripleRelation fromNodeRelation ( NodeRelation relation ) { if ( relation instanceof TripleRelation ) return ( TripleRelation ) relation ; if ( ! relation . variables ( ) . equals ( SPO ) ) { throw new IllegalArgumentException ( "" + relation . variables ( ) ) ; } return new TripleRelation ( relation . baseRelation ( ) , relation . nodeMaker ( SUBJECT ) , relation . nodeMaker ( PREDICATE ) , relation . nodeMaker ( OBJECT ) ) ; } public TripleRelation ( Relation baseRelation , final NodeMaker subjectMaker , final NodeMaker predicateMaker , final NodeMaker objectMaker ) { super ( baseRelation , new HashMap < Var , NodeMaker > ( ) { { put ( SUBJECT , subjectMaker ) ; put ( PREDICATE , predicateMaker ) ; put ( OBJECT , objectMaker ) ; } } ) ; } @ Override public TripleRelation orderBy ( Var variable , boolean ascending ) { return fromNodeRelation ( super . orderBy ( variable , ascending ) ) ; } @ Override public TripleRelation limit ( int limit ) { return fromNodeRelation ( super . limit ( limit ) ) ; } public TripleRelation selectTriple ( Triple t ) { MutableRelation newBase = new MutableRelation ( baseRelation ( ) ) ; NodeMaker s = nodeMaker ( SUBJECT ) . selectNode ( t . getSubject ( ) , newBase ) ; if ( s . equals ( NodeMaker . EMPTY ) ) return null ; NodeMaker p = nodeMaker ( PREDICATE ) . selectNode ( t . getPredicate ( ) , newBase ) ; if ( p . equals ( NodeMaker . EMPTY ) ) return null ; NodeMaker o = nodeMaker ( OBJECT ) . selectNode ( t . getObject ( ) , newBase ) ; if ( o . equals ( NodeMaker . EMPTY ) ) return null ; Set < ProjectionSpec > projections = new HashSet < ProjectionSpec > ( ) ; projections . addAll ( s . projectionSpecs ( ) ) ; projections . addAll ( p . projectionSpecs ( ) ) ; projections . addAll ( o . projectionSpecs ( ) ) ; newBase . project ( projections ) ; if ( ! s . projectionSpecs ( ) . isEmpty ( ) && o . projectionSpecs ( ) . isEmpty ( ) ) { newBase . swapLimits ( ) ; } return new TripleRelation ( newBase . immutableSnapshot ( ) , s , p , o ) ; } public TripleRelation selectWithVariables ( Triple t ) { TripleRelation selected = selectTriple ( t ) ; Node s = t . getSubject ( ) == Node . ANY ? SUBJECT : t . getSubject ( ) ; Node p = t . getPredicate ( ) == Node . ANY ? PREDICATE : t . getPredicate ( ) ; Node o = t . getObject ( ) == Node . ANY ? OBJECT : t . getObject ( ) ; VariableConstraints nodeMakers = new VariableConstraints ( ) ; nodeMakers . addIfVariable ( s , nodeMaker ( SUBJECT ) , baseRelation ( ) . aliases ( ) ) ; nodeMakers . addIfVariable ( p , nodeMaker ( PREDICATE ) , baseRelation ( ) . aliases ( ) ) ; nodeMakers . addIfVariable ( o , nodeMaker ( OBJECT ) , baseRelation ( ) . aliases ( ) ) ; if ( ! nodeMakers . satisfiable ( ) ) { return TripleRelation . EMPTY ; } MutableRelation mutator = new MutableRelation ( selected . baseRelation ( ) ) ; Expression constraint = nodeMakers . constraint ( ) ; if ( ! constraint . isTrue ( ) ) { mutator . select ( constraint ) ; } mutator . project ( nodeMakers . allProjections ( ) ) ; return fromNodeRelation ( new NodeRelation ( mutator . immutableSnapshot ( ) , nodeMakers . toMap ( ) ) ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . sparql . core . Var ; import de . fuberlin . wiwiss . d2rq . expr . Conjunction ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetConstraintBuilder ; public class VariableConstraints { private final Map < Var , NodeSetFilter > nodeSets = new HashMap < Var , NodeSetFilter > ( ) ; private final Map < Var , NodeMaker > nodeMakers = new HashMap < Var , NodeMaker > ( ) ; private final Map < Var , AliasMap > nodeRelationAliases = new HashMap < Var , AliasMap > ( ) ; private final Set < ProjectionSpec > projections = new HashSet < ProjectionSpec > ( ) ; public void add ( Var var , NodeMaker nodeMaker , AliasMap aliases ) { if ( ! nodeMakers . containsKey ( var ) ) { nodeMakers . put ( var , nodeMaker ) ; projections . addAll ( nodeMaker . projectionSpecs ( ) ) ; } if ( ! nodeSets . containsKey ( var ) ) { nodeSets . put ( var , new NodeSetConstraintBuilder ( ) ) ; } NodeSetFilter nodeSet = nodeSets . get ( var ) ; nodeMaker . describeSelf ( nodeSet ) ; if ( ! nodeRelationAliases . containsKey ( var ) ) { nodeRelationAliases . put ( var , aliases ) ; } } public void addIfVariable ( Node possibleVariable , NodeMaker nodeMaker , AliasMap aliases ) { if ( ! possibleVariable . isVariable ( ) ) return ; add ( ( Var ) possibleVariable , nodeMaker , aliases ) ; } public void addAll ( NodeRelation nodeRelation ) { for ( Var variable : nodeRelation . variables ( ) ) { add ( variable , nodeRelation . nodeMaker ( variable ) , nodeRelation . baseRelation ( ) . aliases ( ) ) ; } } public boolean satisfiable ( ) { return ! constraint ( ) . isFalse ( ) ; } public Expression constraint ( ) { Collection < Expression > expressions = new ArrayList < Expression > ( ) ; for ( Var var : nodeSets . keySet ( ) ) { NodeSetConstraintBuilder nodeSet = ( NodeSetConstraintBuilder ) nodeSets . get ( var ) ; if ( nodeSet . isEmpty ( ) ) { return Expression . FALSE ; } expressions . add ( nodeSet . constraint ( ) ) ; } return Conjunction . create ( expressions ) ; } public Map < Var , NodeMaker > toMap ( ) { return nodeMakers ; } public Set < Var > allNames ( ) { return nodeMakers . keySet ( ) ; } public Map < Var , AliasMap > relationAliases ( ) { return nodeRelationAliases ; } public Set < ProjectionSpec > allProjections ( ) { return projections ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . sparql . core . Var ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . FixedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; public class NodeRelation { public static final NodeRelation TRUE = new NodeRelation ( Relation . TRUE , Collections . < Var , NodeMaker > emptyMap ( ) ) ; public static NodeRelation empty ( Set < Var > variables ) { Map < Var , NodeMaker > map = new HashMap < Var , NodeMaker > ( ) ; for ( Var variable : variables ) { map . put ( variable , NodeMaker . EMPTY ) ; } return new NodeRelation ( Relation . EMPTY , map ) ; } private final Relation base ; private final Map < Var , NodeMaker > nodeMakers ; public NodeRelation ( Relation base , Map < Var , NodeMaker > nodeMakers ) { this . base = base ; this . nodeMakers = nodeMakers ; } public Relation baseRelation ( ) { return base ; } public Set < Var > variables ( ) { return nodeMakers . keySet ( ) ; } public NodeMaker nodeMaker ( Var variables ) { return ( NodeMaker ) nodeMakers . get ( variables ) ; } public NodeRelation withPrefix ( int index ) { Collection < Alias > newAliases = new ArrayList < Alias > ( ) ; for ( RelationName tableName : baseRelation ( ) . tables ( ) ) { newAliases . add ( new Alias ( tableName , tableName . withPrefix ( index ) ) ) ; } AliasMap renamer = new AliasMap ( newAliases ) ; Map < Var , NodeMaker > renamedNodeMakers = new HashMap < Var , NodeMaker > ( ) ; for ( Var variable : variables ( ) ) { renamedNodeMakers . put ( variable , nodeMaker ( variable ) . renameAttributes ( renamer ) ) ; } return new NodeRelation ( baseRelation ( ) . renameColumns ( renamer ) , renamedNodeMakers ) ; } public NodeRelation renameSingleRelation ( RelationName oldName , RelationName newName ) { AliasMap renamer = AliasMap . create1 ( oldName , newName ) ; Map < Var , NodeMaker > renamedNodeMakers = new HashMap < Var , NodeMaker > ( ) ; for ( Var variable : variables ( ) ) { renamedNodeMakers . put ( variable , nodeMaker ( variable ) . renameAttributes ( renamer ) ) ; } return new NodeRelation ( baseRelation ( ) . renameColumns ( renamer ) , renamedNodeMakers ) ; } public NodeRelation extendWith ( Binding binding ) { if ( binding . isEmpty ( ) ) return this ; MutableRelation mutator = new MutableRelation ( baseRelation ( ) ) ; Map < Var , NodeMaker > columns = new HashMap < Var , NodeMaker > ( ) ; for ( Var variable : variables ( ) ) { columns . put ( variable , nodeMaker ( variable ) ) ; } for ( Iterator < Var > it = binding . vars ( ) ; it . hasNext ( ) ; ) { Var var = it . next ( ) ; Node value = binding . get ( var ) ; if ( columns . containsKey ( var ) ) { columns . put ( var , columns . get ( var ) . selectNode ( value , mutator ) ) ; } else { columns . put ( var , new FixedNodeMaker ( value , false ) ) ; } } return new NodeRelation ( mutator . immutableSnapshot ( ) , columns ) ; } public NodeRelation select ( Expression expression ) { MutableRelation mutator = new MutableRelation ( baseRelation ( ) ) ; mutator . select ( expression ) ; return new NodeRelation ( mutator . immutableSnapshot ( ) , nodeMakers ) ; } public NodeRelation orderBy ( Var variable , boolean ascending ) { if ( ! variables ( ) . contains ( variable ) ) return this ; List < OrderSpec > orderSpecs = nodeMaker ( variable ) . orderSpecs ( ascending ) ; if ( orderSpecs . isEmpty ( ) ) return this ; MutableRelation mutator = new MutableRelation ( baseRelation ( ) ) ; mutator . orderBy ( orderSpecs ) ; return new NodeRelation ( mutator . immutableSnapshot ( ) , nodeMakers ) ; } public NodeRelation limit ( int limit ) { MutableRelation mutator = new MutableRelation ( baseRelation ( ) ) ; mutator . limit ( limit ) ; return new NodeRelation ( mutator . immutableSnapshot ( ) , nodeMakers ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; result . append ( base . toString ( ) ) ; result . append ( "" ) ; for ( Var variable : variables ( ) ) { result . append ( "" ) ; result . append ( variable ) ; result . append ( "" ) ; result . append ( nodeMaker ( variable ) . toString ( ) ) ; result . append ( "" ) ; } result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; public abstract class ColumnRenamer { public final static ColumnRenamer NULL = new ColumnRenamer ( ) { public AliasMap applyTo ( AliasMap aliases ) { return aliases ; } public Attribute applyTo ( Attribute original ) { return original ; } public Expression applyTo ( Expression original ) { return original ; } public Join applyTo ( Join original ) { return original ; } public Set < Join > applyToJoinSet ( Set < Join > joins ) { return joins ; } public String toString ( ) { return "" ; } } ; protected final static < K , V > Map < V , K > invertMap ( Map < K , V > m ) { HashMap < V , K > result = new HashMap < V , K > ( ) ; for ( Entry < K , V > entry : m . entrySet ( ) ) { result . put ( entry . getValue ( ) , entry . getKey ( ) ) ; } return result ; } public abstract Attribute applyTo ( Attribute original ) ; public Join applyTo ( Join original ) { return original . renameColumns ( this ) ; } public Expression applyTo ( Expression original ) { return original . renameAttributes ( this ) ; } public Set < Join > applyToJoinSet ( Set < Join > joins ) { Set < Join > result = new HashSet < Join > ( ) ; for ( Join join : joins ) { result . add ( applyTo ( join ) ) ; } return result ; } public ProjectionSpec applyTo ( ProjectionSpec original ) { return original . renameAttributes ( this ) ; } public Set < ProjectionSpec > applyToProjectionSet ( Set < ProjectionSpec > projections ) { Set < ProjectionSpec > result = new HashSet < ProjectionSpec > ( ) ; for ( ProjectionSpec projection : projections ) { result . add ( applyTo ( projection ) ) ; } return result ; } public List < OrderSpec > applyTo ( List < OrderSpec > orderSpecs ) { List < OrderSpec > result = new ArrayList < OrderSpec > ( orderSpecs . size ( ) ) ; for ( OrderSpec spec : orderSpecs ) { result . add ( new OrderSpec ( applyTo ( spec . expression ( ) ) , spec . isAscending ( ) ) ) ; } return result ; } public abstract AliasMap applyTo ( AliasMap aliases ) ; } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; public interface RelationalOperators { public final static RelationalOperators DUMMY = new RelationalOperators ( ) { public Relation renameColumns ( ColumnRenamer renamer ) { return null ; } public Relation select ( Expression condition ) { return null ; } public Relation project ( Set < ? extends ProjectionSpec > projectionSpecs ) { return null ; } } ; Relation select ( Expression condition ) ; Relation renameColumns ( ColumnRenamer renamer ) ; Relation project ( Set < ? extends ProjectionSpec > projectionSpecs ) ; } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; public class MutableRelation implements RelationalOperators { private Relation relation ; public MutableRelation ( Relation initialState ) { this . relation = initialState ; } public Relation immutableSnapshot ( ) { return this . relation ; } public Relation renameColumns ( ColumnRenamer renamer ) { return this . relation = this . relation . renameColumns ( renamer ) ; } public Relation empty ( ) { return this . relation = Relation . EMPTY ; } public Relation select ( Expression condition ) { if ( condition . isFalse ( ) ) { return empty ( ) ; } return this . relation = this . relation . select ( condition ) ; } public Relation orderBy ( List < OrderSpec > orderSpecs ) { return relation = new RelationImpl ( relation . database ( ) , relation . aliases ( ) , relation . condition ( ) , relation . softCondition ( ) , relation . joinConditions ( ) , relation . projections ( ) , relation . isUnique ( ) , orderSpecs , relation . limit ( ) , relation . limitInverse ( ) ) ; } public Relation swapLimits ( ) { return relation = new RelationImpl ( relation . database ( ) , relation . aliases ( ) , relation . condition ( ) , relation . softCondition ( ) , relation . joinConditions ( ) , relation . projections ( ) , relation . isUnique ( ) , relation . orderSpecs ( ) , relation . limitInverse ( ) , relation . limit ( ) ) ; } public Relation project ( Set < ? extends ProjectionSpec > projectionSpecs ) { return relation = relation . project ( projectionSpecs ) ; } public Relation limit ( int limit ) { return relation = new RelationImpl ( relation . database ( ) , relation . aliases ( ) , relation . condition ( ) , relation . softCondition ( ) , relation . joinConditions ( ) , relation . projections ( ) , relation . isUnique ( ) , relation . orderSpecs ( ) , Relation . combineLimits ( relation . limit ( ) , limit ) , relation . limitInverse ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public interface ProjectionSpec extends Comparable < ProjectionSpec > { public Set < Attribute > requiredAttributes ( ) ; public ProjectionSpec renameAttributes ( ColumnRenamer renamer ) ; public Expression toExpression ( ) ; public String toSQL ( ConnectedDB database , AliasMap aliases ) ; public Expression notNullExpression ( ConnectedDB database , AliasMap aliases ) ; } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; public class JoinOptimizer { private TripleRelation relation ; public JoinOptimizer ( TripleRelation relation ) { this . relation = relation ; } public TripleRelation optimize ( ) { Map < Attribute , Attribute > replacedColumns = new HashMap < Attribute , Attribute > ( ) ; Set < Attribute > allRequiredColumns = relation . baseRelation ( ) . allKnownAttributes ( ) ; Set < Join > requiredJoins = new HashSet < Join > ( this . relation . baseRelation ( ) . joinConditions ( ) ) ; for ( Join join : relation . baseRelation ( ) . joinConditions ( ) ) { if ( ! isRemovableJoin ( join ) ) continue ; boolean isRemovable1 = join . joinDirection ( ) == Join . DIRECTION_RIGHT && isRemovableJoinSide ( join . table1 ( ) , join , allRequiredColumns ) ; boolean isRemovable2 = join . joinDirection ( ) == Join . DIRECTION_LEFT && isRemovableJoinSide ( join . table2 ( ) , join , allRequiredColumns ) ; if ( isRemovable1 ) { requiredJoins . remove ( join ) ; replacedColumns . putAll ( replacementColumns ( join . attributes1 ( ) , join ) ) ; } if ( isRemovable2 ) { requiredJoins . remove ( join ) ; replacedColumns . putAll ( replacementColumns ( join . attributes2 ( ) , join ) ) ; } } if ( replacedColumns . isEmpty ( ) ) { return this . relation ; } ColumnRenamer renamer = new ColumnRenamerMap ( replacedColumns ) ; NodeMaker s = this . relation . nodeMaker ( TripleRelation . SUBJECT ) ; NodeMaker p = this . relation . nodeMaker ( TripleRelation . PREDICATE ) ; NodeMaker o = this . relation . nodeMaker ( TripleRelation . OBJECT ) ; Set < ProjectionSpec > projections = new HashSet < ProjectionSpec > ( ) ; projections . addAll ( s . projectionSpecs ( ) ) ; projections . addAll ( p . projectionSpecs ( ) ) ; projections . addAll ( o . projectionSpecs ( ) ) ; return new TripleRelation ( new RelationImpl ( this . relation . baseRelation ( ) . database ( ) , this . relation . baseRelation ( ) . aliases ( ) , this . relation . baseRelation ( ) . condition ( ) , this . relation . baseRelation ( ) . softCondition ( ) , requiredJoins , projections , this . relation . baseRelation ( ) . isUnique ( ) , this . relation . baseRelation ( ) . orderSpecs ( ) , this . relation . baseRelation ( ) . limit ( ) , this . relation . baseRelation ( ) . limitInverse ( ) ) . renameColumns ( renamer ) , s . renameAttributes ( renamer ) , p . renameAttributes ( renamer ) , o . renameAttributes ( renamer ) ) ; } private boolean isRemovableJoin ( Join join ) { for ( Attribute side1 : join . attributes1 ( ) ) { Attribute side2 = join . equalAttribute ( side1 ) ; if ( ! relation . baseRelation ( ) . database ( ) . areCompatibleFormats ( relation . baseRelation ( ) . aliases ( ) . originalOf ( side1 ) , relation . baseRelation ( ) . aliases ( ) . originalOf ( side2 ) ) ) { return false ; } } return true ; } private boolean isRemovableJoinSide ( RelationName tableName , Join join , Set < Attribute > allRequiredColumns ) { for ( Attribute requiredColumn : allRequiredColumns ) { if ( ! requiredColumn . relationName ( ) . equals ( tableName ) ) { continue ; } if ( ! join . containsColumn ( requiredColumn ) ) { return false ; } } return true ; } private Map < Attribute , Attribute > replacementColumns ( Collection < Attribute > originalColumns , Join removableJoin ) { Map < Attribute , Attribute > result = new HashMap < Attribute , Attribute > ( ) ; for ( Attribute originalColumn : originalColumns ) { result . put ( originalColumn , removableJoin . equalAttribute ( originalColumn ) ) ; } return result ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . engine . BindingMaker ; import de . fuberlin . wiwiss . d2rq . expr . Disjunction ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; public class CompatibleRelationGroup { public static Collection < CompatibleRelationGroup > groupNodeRelations ( Collection < ? extends NodeRelation > nodeRelations ) { Collection < CompatibleRelationGroup > result = new ArrayList < CompatibleRelationGroup > ( ) ; for ( NodeRelation nodeRelation : nodeRelations ) { addNodeRelation ( nodeRelation , result ) ; } return result ; } private static void addNodeRelation ( NodeRelation nodeRelation , Collection < CompatibleRelationGroup > groups ) { for ( CompatibleRelationGroup group : groups ) { if ( group . isCompatible ( nodeRelation . baseRelation ( ) ) ) { group . addBindingMaker ( nodeRelation . baseRelation ( ) , BindingMaker . createFor ( nodeRelation ) ) ; return ; } } CompatibleRelationGroup newGroup = new CompatibleRelationGroup ( ) ; newGroup . addBindingMaker ( nodeRelation . baseRelation ( ) , BindingMaker . createFor ( nodeRelation ) ) ; groups . add ( newGroup ) ; } private final List < BiningMakerAndCondition > makers = new ArrayList < BiningMakerAndCondition > ( ) ; private Relation firstBaseRelation = null ; private boolean differentConditions = false ; private boolean differentSoftConditions = false ; private boolean allUnique = true ; private int relationCounter = ; private Set < ProjectionSpec > projections = new HashSet < ProjectionSpec > ( ) ; private List < OrderSpec > longestOrderSpecs = new ArrayList < OrderSpec > ( ) ; public boolean isCompatible ( Relation otherRelation ) { if ( firstBaseRelation == null ) { throw new IllegalStateException ( ) ; } if ( firstBaseRelation . database ( ) == null || ! firstBaseRelation . database ( ) . equals ( otherRelation . database ( ) ) ) { return false ; } if ( ! firstBaseRelation . joinConditions ( ) . equals ( otherRelation . joinConditions ( ) ) ) { return false ; } Set < RelationName > firstTables = firstBaseRelation . tables ( ) ; Set < RelationName > secondTables = otherRelation . tables ( ) ; if ( ! firstTables . equals ( secondTables ) ) { return false ; } for ( RelationName tableName : firstTables ) { if ( ! firstBaseRelation . aliases ( ) . originalOf ( tableName ) . equals ( otherRelation . aliases ( ) . originalOf ( tableName ) ) ) { return false ; } } if ( ! firstBaseRelation . projections ( ) . equals ( otherRelation . projections ( ) ) ) { if ( ! firstBaseRelation . isUnique ( ) || ! otherRelation . isUnique ( ) ) { return false ; } } for ( int i = ; i < Math . min ( longestOrderSpecs . size ( ) , otherRelation . orderSpecs ( ) . size ( ) ) ; i ++ ) { if ( ! longestOrderSpecs . get ( i ) . equals ( otherRelation . orderSpecs ( ) . get ( i ) ) ) return false ; } for ( int i = longestOrderSpecs . size ( ) ; i < otherRelation . orderSpecs ( ) . size ( ) ; i ++ ) { longestOrderSpecs . add ( otherRelation . orderSpecs ( ) . get ( i ) ) ; } return true ; } public void addRelation ( Relation relation ) { if ( firstBaseRelation == null ) { firstBaseRelation = relation ; longestOrderSpecs . addAll ( firstBaseRelation . orderSpecs ( ) ) ; } if ( ! relation . condition ( ) . equals ( firstBaseRelation . condition ( ) ) ) { differentConditions = true ; } if ( ! relation . softCondition ( ) . equals ( firstBaseRelation . softCondition ( ) ) ) { differentSoftConditions = true ; } projections . addAll ( relation . projections ( ) ) ; allUnique = allUnique && relation . isUnique ( ) ; relationCounter ++ ; } public void addBindingMaker ( Relation relation , BindingMaker bindingMaker ) { addRelation ( relation ) ; makers . add ( new BiningMakerAndCondition ( bindingMaker , relation . condition ( ) , relation . softCondition ( ) ) ) ; } public Relation baseRelation ( ) { if ( relationCounter == ) { return firstBaseRelation ; } if ( differentConditions ) { Set < Expression > allConditions = new HashSet < Expression > ( ) ; Set < ProjectionSpec > projectionsAndConditions = new HashSet < ProjectionSpec > ( projections ) ; for ( BiningMakerAndCondition maker : makers ) { allConditions . add ( maker . conditionWithSoft ( ) ) ; if ( ! maker . condition . isTrue ( ) ) { projectionsAndConditions . add ( maker . conditionProjection ( ) ) ; } } if ( allConditions . isEmpty ( ) ) { allConditions . add ( Expression . TRUE ) ; } Disjunction . create ( allConditions ) ; return new RelationImpl ( firstBaseRelation . database ( ) , firstBaseRelation . aliases ( ) , Disjunction . create ( allConditions ) , Expression . TRUE , firstBaseRelation . joinConditions ( ) , projectionsAndConditions , allUnique , longestOrderSpecs , firstBaseRelation . limit ( ) , firstBaseRelation . limitInverse ( ) ) ; } else { Expression softCondition = firstBaseRelation . softCondition ( ) ; if ( differentSoftConditions ) { Set < Expression > allSoftConditions = new HashSet < Expression > ( ) ; for ( BiningMakerAndCondition maker : makers ) { allSoftConditions . add ( maker . softCondition ) ; } if ( allSoftConditions . isEmpty ( ) ) { allSoftConditions . add ( Expression . TRUE ) ; } softCondition = Disjunction . create ( allSoftConditions ) ; } return new RelationImpl ( firstBaseRelation . database ( ) , firstBaseRelation . aliases ( ) , firstBaseRelation . condition ( ) , softCondition , firstBaseRelation . joinConditions ( ) , projections , allUnique , longestOrderSpecs , firstBaseRelation . limit ( ) , firstBaseRelation . limitInverse ( ) ) ; } } public Collection < BindingMaker > bindingMakers ( ) { Collection < BindingMaker > results = new ArrayList < BindingMaker > ( ) ; if ( relationCounter == || ! differentConditions ) { for ( BiningMakerAndCondition maker : makers ) { if ( maker . bMaker == null ) continue ; results . add ( maker . bMaker ) ; } } else { for ( BiningMakerAndCondition maker : makers ) { if ( maker . bMaker == null ) continue ; if ( maker . condition . isTrue ( ) ) { results . add ( maker . bMaker ) ; } else { results . add ( maker . makeConditional ( ) ) ; } } } return results ; } private class BiningMakerAndCondition { private final BindingMaker bMaker ; private final Expression condition ; private final Expression softCondition ; BiningMakerAndCondition ( BindingMaker maker , Expression condition , Expression softCondition ) { this . bMaker = maker ; this . condition = condition ; this . softCondition = softCondition ; } private ProjectionSpec conditionProjection ( ) { return new ExpressionProjectionSpec ( firstBaseRelation . database ( ) . vendor ( ) . booleanExpressionToSimpleExpression ( condition ) ) ; } private BindingMaker makeConditional ( ) { return bMaker . makeConditional ( conditionProjection ( ) ) ; } private Expression conditionWithSoft ( ) { return condition . and ( softCondition ) ; } } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Collections ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . expr . NotNull ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class Attribute implements ProjectionSpec { private String attributeName ; private RelationName relationName ; private String qualifiedName ; public Attribute ( String schemaName , String tableName , String attributeName ) { this ( new RelationName ( schemaName , tableName ) , attributeName ) ; } public Attribute ( RelationName relationName , String attributeName ) { this . attributeName = attributeName ; this . relationName = relationName ; this . qualifiedName = this . relationName . qualifiedName ( ) + "" + this . attributeName ; } public String qualifiedName ( ) { return this . qualifiedName ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return database . vendor ( ) . quoteAttribute ( this ) ; } public String attributeName ( ) { return this . attributeName ; } public String tableName ( ) { return this . relationName . tableName ( ) ; } public RelationName relationName ( ) { return this . relationName ; } public String schemaName ( ) { return this . relationName . schemaName ( ) ; } public Set < Attribute > requiredAttributes ( ) { return Collections . singleton ( this ) ; } public Expression selectValue ( String value ) { return Equality . createAttributeValue ( this , value ) ; } public ProjectionSpec renameAttributes ( ColumnRenamer renamer ) { return renamer . applyTo ( this ) ; } public Expression toExpression ( ) { return new AttributeExpr ( this ) ; } public Expression notNullExpression ( ConnectedDB db , AliasMap aliases ) { if ( db . isNullable ( aliases . originalOf ( this ) ) ) { return NotNull . create ( new AttributeExpr ( this ) ) ; } return Expression . TRUE ; } public String toString ( ) { return "" + this . qualifiedName + "" ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Attribute ) ) { return false ; } return this . qualifiedName . equals ( ( ( Attribute ) other ) . qualifiedName ( ) ) ; } public int hashCode ( ) { return this . qualifiedName . hashCode ( ) ; } public int compareTo ( ProjectionSpec other ) { if ( ! ( other instanceof Attribute ) ) { return - ; } Attribute otherAttribute = ( Attribute ) other ; int i = this . relationName . compareTo ( otherAttribute . relationName ) ; if ( i != ) { return i ; } return this . attributeName . compareTo ( otherAttribute . attributeName ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; public class AliasMap extends ColumnRenamer { public static final AliasMap NO_ALIASES = new AliasMap ( Collections . < Alias > emptySet ( ) ) ; public static AliasMap create1 ( RelationName original , RelationName alias ) { return new AliasMap ( Collections . singletonList ( new Alias ( original , alias ) ) ) ; } public static class Alias { private RelationName original ; private RelationName alias ; public Alias ( RelationName original , RelationName alias ) { this . original = original ; this . alias = alias ; } public RelationName original ( ) { return this . original ; } public RelationName alias ( ) { return this . alias ; } public int hashCode ( ) { return this . original . hashCode ( ) ^ this . alias . hashCode ( ) ; } public boolean equals ( Object o ) { if ( ! ( o instanceof Alias ) ) return false ; return this . alias . equals ( ( ( Alias ) o ) . alias ) && this . original . equals ( ( ( Alias ) o ) . original ) ; } public String toString ( ) { return this . original + "" + this . alias ; } } private Map < RelationName , Alias > byAlias = new HashMap < RelationName , Alias > ( ) ; private Map < RelationName , Alias > byOriginal = new HashMap < RelationName , Alias > ( ) ; public AliasMap ( Collection < Alias > aliases ) { for ( Alias alias : aliases ) { this . byAlias . put ( alias . alias ( ) , alias ) ; this . byOriginal . put ( alias . original ( ) , alias ) ; } } public boolean isAlias ( RelationName name ) { return this . byAlias . containsKey ( name ) ; } public boolean hasAlias ( RelationName original ) { return this . byOriginal . containsKey ( original ) ; } public RelationName applyTo ( RelationName original ) { if ( ! hasAlias ( original ) ) { return original ; } Alias alias = ( Alias ) this . byOriginal . get ( original ) ; return alias . alias ( ) ; } public RelationName originalOf ( RelationName name ) { if ( ! isAlias ( name ) ) { return name ; } Alias alias = ( Alias ) this . byAlias . get ( name ) ; return alias . original ( ) ; } public Attribute applyTo ( Attribute attribute ) { if ( ! hasAlias ( attribute . relationName ( ) ) ) { return attribute ; } return new Attribute ( applyTo ( attribute . relationName ( ) ) , attribute . attributeName ( ) ) ; } public Attribute originalOf ( Attribute attribute ) { if ( ! isAlias ( attribute . relationName ( ) ) ) { return attribute ; } return new Attribute ( originalOf ( attribute . relationName ( ) ) , attribute . attributeName ( ) ) ; } public Alias applyTo ( Alias alias ) { if ( ! hasAlias ( alias . alias ( ) ) ) { return alias ; } return new Alias ( alias . original ( ) , applyTo ( alias . alias ( ) ) ) ; } public Alias originalOf ( Alias alias ) { if ( ! isAlias ( alias . original ( ) ) ) { return alias ; } return new Alias ( originalOf ( alias . original ( ) ) , alias . alias ( ) ) ; } public Join applyTo ( Join join ) { if ( ! hasAlias ( join . table1 ( ) ) && ! hasAlias ( join . table2 ( ) ) ) { return join ; } return super . applyTo ( join ) ; } public AliasMap applyTo ( AliasMap other ) { if ( this . byAlias . isEmpty ( ) ) { return other ; } if ( other . byAlias . isEmpty ( ) ) { return this ; } Collection < Alias > newAliases = new ArrayList < Alias > ( ) ; for ( Alias alias : other . byAlias . values ( ) ) { newAliases . add ( applyTo ( alias ) ) ; } for ( Alias alias : byAlias . values ( ) ) { if ( other . isAlias ( alias . original ( ) ) ) continue ; newAliases . add ( alias ) ; } return new AliasMap ( newAliases ) ; } public boolean equals ( Object other ) { if ( ! ( other instanceof AliasMap ) ) { return false ; } AliasMap otherAliasMap = ( AliasMap ) other ; return this . byAlias . equals ( otherAliasMap . byAlias ) ; } public int hashCode ( ) { return this . byAlias . hashCode ( ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( ) ; result . append ( "" ) ; List < RelationName > tables = new ArrayList < RelationName > ( this . byAlias . keySet ( ) ) ; Collections . sort ( tables ) ; Iterator < RelationName > it = tables . iterator ( ) ; while ( it . hasNext ( ) ) { result . append ( this . byAlias . get ( it . next ( ) ) ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Collections ; import java . util . List ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class OrderSpec { public final static List < OrderSpec > NONE = Collections . emptyList ( ) ; private Expression expression ; private boolean ascending ; public OrderSpec ( Expression expression ) { this ( expression , true ) ; } public OrderSpec ( Expression expression , boolean ascending ) { this . expression = expression ; this . ascending = ascending ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return expression . toSQL ( database , aliases ) + ( ascending ? "" : "" ) ; } public Expression expression ( ) { return expression ; } public boolean isAscending ( ) { return ascending ; } public String toString ( ) { return ( ascending ? "" : "" ) + expression + "" ; } public boolean equals ( Object other ) { if ( other instanceof OrderSpec ) { return ascending == ( ( OrderSpec ) other ) . ascending && expression . equals ( ( ( OrderSpec ) other ) . expression ) ; } return false ; } public int hashCode ( ) { return Boolean . valueOf ( ascending ) . hashCode ( ) ^ expression . hashCode ( ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; public class RelationName implements Comparable < RelationName > { private String schemaName ; private String tableName ; private String qualifiedName ; private boolean caseUnspecified ; public RelationName ( String schemaName , String tableName , boolean caseUnspecified ) { this . schemaName = schemaName ; this . tableName = tableName ; if ( this . schemaName == null ) { this . qualifiedName = tableName ; } else { this . qualifiedName = schemaName + "" + tableName ; } this . caseUnspecified = caseUnspecified ; } public RelationName ( String schemaName , String tableName ) { this ( schemaName , tableName , false ) ; } public String tableName ( ) { return this . tableName ; } public String schemaName ( ) { return this . schemaName ; } public String qualifiedName ( ) { return this . qualifiedName ; } public boolean caseUnspecified ( ) { return this . caseUnspecified ; } public int hashCode ( ) { return this . qualifiedName . hashCode ( ) ; } public boolean equals ( Object otherObject ) { if ( ! ( otherObject instanceof RelationName ) ) { return false ; } RelationName other = ( RelationName ) otherObject ; if ( this . caseUnspecified || other . caseUnspecified ) return this . qualifiedName . equalsIgnoreCase ( other . qualifiedName ) ; else return this . qualifiedName . equals ( other . qualifiedName ) ; } public String toString ( ) { return this . qualifiedName ; } public int compareTo ( RelationName other ) { if ( this . schemaName == null && other . schemaName == null ) { return this . tableName . compareTo ( other . tableName ) ; } if ( this . schemaName == null ) { return - ; } if ( other . schemaName == null ) { return ; } boolean caseUnspecified = this . caseUnspecified || other . caseUnspecified ; int compareSchemas = caseUnspecified ? this . schemaName . compareToIgnoreCase ( other . schemaName ) : this . schemaName . compareTo ( other . schemaName ) ; if ( compareSchemas != ) { return compareSchemas ; } return ( caseUnspecified ? this . tableName . compareToIgnoreCase ( other . tableName ) : this . tableName . compareTo ( other . tableName ) ) ; } public RelationName withPrefix ( int index ) { String name = "" + index + "" + ( schemaName == null ? "" : schemaName + "" ) + tableName ; if ( name . length ( ) > ) { name = "" + index + "" + name . hashCode ( ) ; } return new RelationName ( null , name ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class RelationImpl extends Relation { private final ConnectedDB database ; private final AliasMap aliases ; private final Expression condition ; private final Expression softCondition ; private final Set < Join > joinConditions ; private final Set < ProjectionSpec > projections ; private final boolean isUnique ; private final List < OrderSpec > orderSpecs ; private int limit ; private int limitInverse ; public RelationImpl ( ConnectedDB database , AliasMap aliases , Expression condition , Expression softCondition , Set < Join > joinConditions , Set < ProjectionSpec > projections , boolean isUnique , List < OrderSpec > orderSpecs , int limit , int limitInverse ) { this . database = database ; this . aliases = aliases ; this . condition = condition ; this . softCondition = softCondition ; this . joinConditions = joinConditions ; this . projections = projections ; this . isUnique = isUnique ; this . orderSpecs = orderSpecs ; this . limit = limit ; this . limitInverse = limitInverse ; } public ConnectedDB database ( ) { return this . database ; } public AliasMap aliases ( ) { return this . aliases ; } public Expression condition ( ) { return this . condition ; } public Expression softCondition ( ) { return softCondition ; } public Set < Join > joinConditions ( ) { return this . joinConditions ; } public Set < ProjectionSpec > projections ( ) { return projections ; } public boolean isUnique ( ) { return isUnique ; } public int limit ( ) { return limit ; } public int limitInverse ( ) { return limitInverse ; } public List < OrderSpec > orderSpecs ( ) { return orderSpecs ; } public Relation select ( Expression selectCondition ) { if ( selectCondition . isTrue ( ) ) { return this ; } if ( selectCondition . isFalse ( ) ) { return Relation . EMPTY ; } return new RelationImpl ( database , aliases , condition . and ( selectCondition ) , softCondition , joinConditions , projections , isUnique , orderSpecs , limit , limitInverse ) ; } public Relation renameColumns ( ColumnRenamer renames ) { return new RelationImpl ( database , renames . applyTo ( aliases ) , renames . applyTo ( condition ) , renames . applyTo ( softCondition ) , renames . applyToJoinSet ( joinConditions ) , renames . applyToProjectionSet ( projections ) , isUnique , renames . applyTo ( orderSpecs ) , limit , limitInverse ) ; } public Relation project ( Set < ? extends ProjectionSpec > projectionSpecs ) { Set < ProjectionSpec > newProjections = new HashSet < ProjectionSpec > ( projectionSpecs ) ; newProjections . retainAll ( projections ) ; return new RelationImpl ( database , aliases , condition , softCondition , joinConditions , newProjections , isUnique , orderSpecs , limit , limitInverse ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; if ( isUnique ) { result . append ( "" ) ; } result . append ( "" ) ; result . append ( "" ) ; result . append ( projections ) ; result . append ( "" ) ; if ( ! joinConditions . isEmpty ( ) ) { result . append ( "" ) ; result . append ( joinConditions ) ; result . append ( "" ) ; } if ( ! condition . isTrue ( ) ) { result . append ( "" ) ; result . append ( condition ) ; result . append ( "" ) ; } if ( ! softCondition . isTrue ( ) ) { result . append ( "" ) ; result . append ( softCondition ) ; result . append ( "" ) ; } if ( ! aliases . equals ( AliasMap . NO_ALIASES ) ) { result . append ( "" ) ; result . append ( aliases ) ; result . append ( "" ) ; } if ( ! orderSpecs . isEmpty ( ) ) { result . append ( "" ) ; result . append ( orderSpecs ) ; result . append ( "" ) ; } if ( limit != - ) { result . append ( "" ) ; result . append ( limit ) ; result . append ( "" ) ; } if ( limitInverse != - ) { result . append ( "" ) ; result . append ( limitInverse ) ; result . append ( "" ) ; } result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . expr . NotNull ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class ExpressionProjectionSpec implements ProjectionSpec { private Expression expression ; private final String name ; public ExpressionProjectionSpec ( Expression expression ) { this . expression = expression ; this . name = "" + Integer . toHexString ( expression . hashCode ( ) ) ; } public ProjectionSpec renameAttributes ( ColumnRenamer renamer ) { return new ExpressionProjectionSpec ( renamer . applyTo ( expression ) ) ; } public Set < Attribute > requiredAttributes ( ) { return expression . attributes ( ) ; } public Expression toExpression ( ) { return expression ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return expression . toSQL ( database , aliases ) + "" + name ; } public Expression notNullExpression ( ConnectedDB database , AliasMap aliases ) { return NotNull . create ( expression ) ; } public boolean equals ( Object other ) { return ( other instanceof ExpressionProjectionSpec ) && expression . equals ( ( ( ExpressionProjectionSpec ) other ) . expression ) ; } public int hashCode ( ) { return expression . hashCode ( ) ^ ; } public String toString ( ) { return "" + expression + "" + name + "" ; } public int compareTo ( ProjectionSpec other ) { if ( ! ( other instanceof ExpressionProjectionSpec ) ) { return ; } ExpressionProjectionSpec otherExpr = ( ExpressionProjectionSpec ) other ; return this . name . compareTo ( otherExpr . name ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public abstract class Relation implements RelationalOperators { public final static int NO_LIMIT = - ; public static Relation createSimpleRelation ( ConnectedDB database , Attribute [ ] attributes ) { return new RelationImpl ( database , AliasMap . NO_ALIASES , Expression . TRUE , Expression . TRUE , Collections . < Join > emptySet ( ) , new HashSet < ProjectionSpec > ( Arrays . asList ( attributes ) ) , false , Collections . < OrderSpec > emptyList ( ) , - , - ) ; } public static Relation EMPTY = new Relation ( ) { public ConnectedDB database ( ) { return null ; } public AliasMap aliases ( ) { return AliasMap . NO_ALIASES ; } public Set < Join > joinConditions ( ) { return Collections . < Join > emptySet ( ) ; } public Expression condition ( ) { return Expression . FALSE ; } public Expression softCondition ( ) { return Expression . FALSE ; } public Set < ProjectionSpec > projections ( ) { return Collections . < ProjectionSpec > emptySet ( ) ; } public Relation select ( Expression condition ) { return this ; } public Relation renameColumns ( ColumnRenamer renamer ) { return this ; } public Relation project ( Set < ? extends ProjectionSpec > projectionSpecs ) { return this ; } public boolean isUnique ( ) { return true ; } public String toString ( ) { return "" ; } public List < OrderSpec > orderSpecs ( ) { return Collections . emptyList ( ) ; } public int limit ( ) { return Relation . NO_LIMIT ; } public int limitInverse ( ) { return Relation . NO_LIMIT ; } } ; public static Relation TRUE = new Relation ( ) { public ConnectedDB database ( ) { return null ; } public AliasMap aliases ( ) { return AliasMap . NO_ALIASES ; } public Set < Join > joinConditions ( ) { return Collections . < Join > emptySet ( ) ; } public Expression condition ( ) { return Expression . TRUE ; } public Expression softCondition ( ) { return Expression . TRUE ; } public Set < ProjectionSpec > projections ( ) { return Collections . < ProjectionSpec > emptySet ( ) ; } public Relation select ( Expression condition ) { if ( condition . isFalse ( ) ) return Relation . EMPTY ; if ( condition . isTrue ( ) ) return Relation . TRUE ; return Relation . TRUE ; } public Relation renameColumns ( ColumnRenamer renamer ) { return this ; } public Relation project ( Set < ? extends ProjectionSpec > projectionSpecs ) { return this ; } public boolean isUnique ( ) { return true ; } public String toString ( ) { return "" ; } public List < OrderSpec > orderSpecs ( ) { return Collections . emptyList ( ) ; } public int limit ( ) { return Relation . NO_LIMIT ; } public int limitInverse ( ) { return Relation . NO_LIMIT ; } } ; public abstract ConnectedDB database ( ) ; public abstract AliasMap aliases ( ) ; public abstract Set < Join > joinConditions ( ) ; public abstract Expression condition ( ) ; public abstract Expression softCondition ( ) ; public abstract Set < ProjectionSpec > projections ( ) ; public abstract boolean isUnique ( ) ; public abstract List < OrderSpec > orderSpecs ( ) ; public abstract int limit ( ) ; public abstract int limitInverse ( ) ; public Set < Attribute > allKnownAttributes ( ) { Set < Attribute > results = new HashSet < Attribute > ( ) ; results . addAll ( condition ( ) . attributes ( ) ) ; results . addAll ( softCondition ( ) . attributes ( ) ) ; for ( Join join : joinConditions ( ) ) { results . addAll ( join . attributes1 ( ) ) ; results . addAll ( join . attributes2 ( ) ) ; } for ( ProjectionSpec projection : projections ( ) ) { results . addAll ( projection . requiredAttributes ( ) ) ; } for ( OrderSpec order : orderSpecs ( ) ) { results . addAll ( order . expression ( ) . attributes ( ) ) ; } return results ; } public Set < RelationName > tables ( ) { Set < RelationName > results = new HashSet < RelationName > ( ) ; for ( Attribute attribute : allKnownAttributes ( ) ) { results . add ( attribute . relationName ( ) ) ; } return results ; } public boolean isTrivial ( ) { return projections ( ) . isEmpty ( ) && condition ( ) . isTrue ( ) && joinConditions ( ) . isEmpty ( ) ; } public static int combineLimits ( int limit1 , int limit2 ) { if ( limit1 == Relation . NO_LIMIT ) { return limit2 ; } else if ( limit2 == Relation . NO_LIMIT ) { return limit1 ; } return Math . min ( limit1 , limit2 ) ; } } package de . fuberlin . wiwiss . d2rq . algebra ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; public class Join { private List < Attribute > attributes1 = new ArrayList < Attribute > ( ) ; private List < Attribute > attributes2 = new ArrayList < Attribute > ( ) ; private RelationName table1 = null ; private RelationName table2 = null ; private Map < Attribute , Attribute > otherSide = new HashMap < Attribute , Attribute > ( ) ; private int joinDirection ; public static final int DIRECTION_UNDIRECTED = ; public static final int DIRECTION_LEFT = ; public static final int DIRECTION_RIGHT = ; public static final String [ ] joinOperators = { "" , "" , "" } ; public Join ( Attribute oneSide , Attribute otherSide , int joinDirection ) { this ( Collections . singletonList ( oneSide ) , Collections . singletonList ( otherSide ) , joinDirection ) ; } public Join ( List < Attribute > oneSideAttributes , List < Attribute > otherSideAttributes , int joinDirection ) { RelationName oneRelation = ( ( Attribute ) oneSideAttributes . get ( ) ) . relationName ( ) ; RelationName otherRelation = ( ( Attribute ) otherSideAttributes . get ( ) ) . relationName ( ) ; this . attributes1 = oneSideAttributes ; this . attributes2 = otherSideAttributes ; this . table1 = oneRelation ; this . table2 = otherRelation ; this . joinDirection = joinDirection ; for ( int i = ; i < this . attributes1 . size ( ) ; i ++ ) { Attribute a1 = ( Attribute ) this . attributes1 . get ( i ) ; Attribute a2 = ( Attribute ) this . attributes2 . get ( i ) ; this . otherSide . put ( a1 , a2 ) ; this . otherSide . put ( a2 , a1 ) ; } } public boolean isSameTable ( ) { return this . table1 . equals ( this . table2 ) ; } public boolean containsColumn ( Attribute column ) { return this . attributes1 . contains ( column ) || this . attributes2 . contains ( column ) ; } public RelationName table1 ( ) { return this . table1 ; } public RelationName table2 ( ) { return this . table2 ; } public List < Attribute > attributes1 ( ) { return this . attributes1 ; } public List < Attribute > attributes2 ( ) { return this . attributes2 ; } public int joinDirection ( ) { return this . joinDirection ; } public Attribute equalAttribute ( Attribute column ) { return ( Attribute ) this . otherSide . get ( column ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; Iterator < Attribute > it = this . attributes1 . iterator ( ) ; while ( it . hasNext ( ) ) { Attribute attribute = it . next ( ) ; result . append ( attribute . qualifiedName ( ) ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( joinDirection == DIRECTION_UNDIRECTED ? "" : ( joinDirection == DIRECTION_RIGHT ? "" : "" ) ) ; it = this . attributes2 . iterator ( ) ; while ( it . hasNext ( ) ) { Attribute attribute = it . next ( ) ; result . append ( attribute . qualifiedName ( ) ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } public int hashCode ( ) { switch ( this . joinDirection ) { case DIRECTION_RIGHT : return * ( this . attributes1 . hashCode ( ) ^ this . attributes2 . hashCode ( ) ) ; case DIRECTION_LEFT : return * ( this . attributes2 . hashCode ( ) ^ this . attributes1 . hashCode ( ) ) ; case DIRECTION_UNDIRECTED : default : return * ( this . attributes1 . hashCode ( ) ^ this . attributes2 . hashCode ( ) ) + ; } } public boolean equals ( Object otherObject ) { if ( ! ( otherObject instanceof Join ) ) { return false ; } Join otherJoin = ( Join ) otherObject ; return ( this . attributes1 . equals ( otherJoin . attributes1 ) && this . attributes2 . equals ( otherJoin . attributes2 ) && this . joinDirection == otherJoin . joinDirection ( ) ) || ( this . attributes1 . equals ( otherJoin . attributes2 ) && this . attributes2 . equals ( otherJoin . attributes1 ) && this . joinDirection == ( otherJoin . joinDirection ( ) == DIRECTION_UNDIRECTED ? DIRECTION_UNDIRECTED : ( otherJoin . joinDirection ( ) == DIRECTION_LEFT ? DIRECTION_RIGHT : DIRECTION_LEFT ) ) ) ; } public Join renameColumns ( ColumnRenamer columnRenamer ) { List < Attribute > oneSide = new ArrayList < Attribute > ( ) ; List < Attribute > otherSide = new ArrayList < Attribute > ( ) ; for ( Attribute column : attributes1 ) { oneSide . add ( columnRenamer . applyTo ( column ) ) ; otherSide . add ( columnRenamer . applyTo ( equalAttribute ( column ) ) ) ; } return new Join ( oneSide , otherSide , joinDirection ) ; } } package de . fuberlin . wiwiss . d2rq . values ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public class ValueDecorator implements ValueMaker { public static ValueConstraint maxLengthConstraint ( final int maxLength ) { return new ValueConstraint ( ) { public boolean matches ( String value ) { return value == null || value . length ( ) <= maxLength ; } public String toString ( ) { return "" + maxLength ; } } ; } public static ValueConstraint containsConstraint ( final String containsSubstring ) { return new ValueConstraint ( ) { public boolean matches ( String value ) { return value == null || value . indexOf ( containsSubstring ) >= ; } public String toString ( ) { return "" + containsSubstring + "" ; } } ; } public static ValueConstraint regexConstraint ( final String regex ) { final Pattern pattern = Pattern . compile ( regex ) ; return new ValueConstraint ( ) { public boolean matches ( String value ) { return value == null || pattern . matcher ( value ) . matches ( ) ; } public String toString ( ) { return "" + regex + "" ; } } ; } private ValueMaker base ; private List < ValueConstraint > constraints ; private Translator translator ; public ValueDecorator ( ValueMaker base , List < ValueConstraint > constraints ) { this ( base , constraints , Translator . IDENTITY ) ; } public ValueDecorator ( ValueMaker base , List < ValueConstraint > constraints , Translator translator ) { this . base = base ; this . constraints = constraints ; this . translator = translator ; } public String makeValue ( ResultRow row ) { return this . translator . toRDFValue ( this . base . makeValue ( row ) ) ; } public void describeSelf ( NodeSetFilter c ) { c . setUsesTranslator ( translator ) ; this . base . describeSelf ( c ) ; } public Expression valueExpression ( String value ) { for ( ValueConstraint constraint : constraints ) { if ( ! constraint . matches ( value ) ) { return Expression . FALSE ; } } String dbValue = this . translator . toDBValue ( value ) ; if ( dbValue == null ) { return Expression . FALSE ; } return base . valueExpression ( dbValue ) ; } public Set < ProjectionSpec > projectionSpecs ( ) { return this . base . projectionSpecs ( ) ; } public ValueMaker renameAttributes ( ColumnRenamer renamer ) { return new ValueDecorator ( this . base . renameAttributes ( renamer ) , this . constraints , this . translator ) ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return base . orderSpecs ( ascending ) ; } public interface ValueConstraint { boolean matches ( String value ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( ) ; if ( ! this . translator . equals ( Translator . IDENTITY ) ) { result . append ( this . translator ) ; result . append ( "" ) ; } result . append ( this . base . toString ( ) ) ; Iterator < ValueConstraint > it = this . constraints . iterator ( ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } while ( it . hasNext ( ) ) { result . append ( it . next ( ) ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } if ( ! this . translator . equals ( Translator . IDENTITY ) ) { result . append ( "" ) ; } return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . values ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . ExpressionProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public class SQLExpressionValueMaker implements ValueMaker { private final Expression expression ; private final ProjectionSpec projection ; public SQLExpressionValueMaker ( Expression expression ) { this . expression = expression ; this . projection = new ExpressionProjectionSpec ( expression ) ; } public void describeSelf ( NodeSetFilter c ) { c . limitValuesToExpression ( expression ) ; } public Set < ProjectionSpec > projectionSpecs ( ) { return Collections . singleton ( projection ) ; } public String makeValue ( ResultRow row ) { return row . get ( projection ) ; } public Expression valueExpression ( String value ) { return Equality . createExpressionValue ( expression , value ) ; } public ValueMaker renameAttributes ( ColumnRenamer renamer ) { return new SQLExpressionValueMaker ( renamer . applyTo ( expression ) ) ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return Collections . singletonList ( new OrderSpec ( expression , ascending ) ) ; } public int hashCode ( ) { return expression . hashCode ( ) ^ ; } public boolean equals ( Object other ) { if ( ! ( other instanceof SQLExpressionValueMaker ) ) { return false ; } return expression . equals ( ( ( SQLExpressionValueMaker ) other ) . expression ) ; } public String toString ( ) { return "" + expression + "" ; } } package de . fuberlin . wiwiss . d2rq . values ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . map . TranslationTable ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public interface ValueMaker { public static final ValueMaker NULL = new ValueMaker ( ) { public Expression valueExpression ( String value ) { return Expression . FALSE ; } public Set < ProjectionSpec > projectionSpecs ( ) { return Collections . emptySet ( ) ; } public String makeValue ( ResultRow row ) { return null ; } public void describeSelf ( NodeSetFilter c ) { c . limitToEmptySet ( ) ; } public ValueMaker renameAttributes ( ColumnRenamer renamer ) { return this ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return Collections . emptyList ( ) ; } } ; Expression valueExpression ( String value ) ; Set < ProjectionSpec > projectionSpecs ( ) ; String makeValue ( ResultRow row ) ; void describeSelf ( NodeSetFilter c ) ; ValueMaker renameAttributes ( ColumnRenamer renamer ) ; List < OrderSpec > orderSpecs ( boolean ascending ) ; } package de . fuberlin . wiwiss . d2rq . values ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public class Column implements ValueMaker { private Attribute attribute ; private Set < ProjectionSpec > attributeAsSet ; public Column ( Attribute attribute ) { this . attribute = attribute ; this . attributeAsSet = Collections . < ProjectionSpec > singleton ( this . attribute ) ; } public String makeValue ( ResultRow row ) { return row . get ( this . attribute ) ; } public void describeSelf ( NodeSetFilter c ) { c . limitValuesToAttribute ( this . attribute ) ; } public Expression valueExpression ( String value ) { if ( value == null ) { return Expression . FALSE ; } return Equality . createAttributeValue ( attribute , value ) ; } public Set < ProjectionSpec > projectionSpecs ( ) { return this . attributeAsSet ; } public ValueMaker renameAttributes ( ColumnRenamer renamer ) { return new Column ( renamer . applyTo ( this . attribute ) ) ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return Collections . singletonList ( new OrderSpec ( new AttributeExpr ( attribute ) , ascending ) ) ; } public String toString ( ) { return "" + this . attribute . qualifiedName ( ) + "" ; } } package de . fuberlin . wiwiss . d2rq . values ; public interface Translator { public static Translator IDENTITY = new Translator ( ) { public String toRDFValue ( String dbValue ) { return dbValue ; } public String toDBValue ( String rdfValue ) { return rdfValue ; } public String toString ( ) { return "" ; } } ; public String toRDFValue ( String dbValue ) ; public String toDBValue ( String rdfValue ) ; } package de . fuberlin . wiwiss . d2rq . values ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . FixedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public class ConstantValueMaker implements ValueMaker { private String value ; public ConstantValueMaker ( String constant ) { this . value = constant ; } public Expression valueExpression ( String value ) { return this . value . equals ( value ) ? Expression . TRUE : Expression . FALSE ; } public Set < ProjectionSpec > projectionSpecs ( ) { return Collections . emptySet ( ) ; } public String makeValue ( ResultRow row ) { return value ; } public void describeSelf ( NodeSetFilter c ) { c . limitValues ( value ) ; } public ValueMaker renameAttributes ( ColumnRenamer renamer ) { return this ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return Collections . emptyList ( ) ; } } package de . fuberlin . wiwiss . d2rq . values ; import java . io . UnsupportedEncodingException ; import java . net . URLDecoder ; import java . net . URLEncoder ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import java . util . regex . Matcher ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . expr . Concatenation ; import de . fuberlin . wiwiss . d2rq . expr . Conjunction ; import de . fuberlin . wiwiss . d2rq . expr . Constant ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . mapgen . IRIEncoder ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; public class Pattern implements ValueMaker { public final static String DELIMITER = "" ; private final static java . util . regex . Pattern embeddedColumnRegex = java . util . regex . Pattern . compile ( "" ) ; private String pattern ; private String firstLiteralPart ; private List < Attribute > columns = new ArrayList < Attribute > ( ) ; private List < ColumnFunction > columnFunctions = new ArrayList < ColumnFunction > ( ) ; private List < String > literalParts = new ArrayList < String > ( ) ; private Set < ProjectionSpec > columnsAsSet ; private java . util . regex . Pattern regex ; public Pattern ( String pattern ) { this . pattern = pattern ; parsePattern ( ) ; this . columnsAsSet = new HashSet < ProjectionSpec > ( this . columns ) ; } public String firstLiteralPart ( ) { return firstLiteralPart ; } public String lastLiteralPart ( ) { if ( literalParts . isEmpty ( ) ) { return firstLiteralPart ; } return literalParts . get ( literalParts . size ( ) - ) ; } public boolean literalPartsMatchRegex ( String regex ) { if ( ! this . firstLiteralPart . matches ( regex ) ) { return false ; } for ( String literalPart : literalParts ) { if ( ! literalPart . matches ( regex ) ) { return false ; } } return true ; } public List < Attribute > attributes ( ) { return this . columns ; } public void describeSelf ( NodeSetFilter c ) { c . limitValuesToPattern ( this ) ; } public boolean matches ( String value ) { return ! valueExpression ( value ) . isFalse ( ) ; } public Expression valueExpression ( String value ) { if ( value == null ) { return Expression . FALSE ; } Matcher match = this . regex . matcher ( value ) ; if ( ! match . matches ( ) ) { return Expression . FALSE ; } Collection < Expression > expressions = new ArrayList < Expression > ( columns . size ( ) ) ; for ( int i = ; i < this . columns . size ( ) ; i ++ ) { Attribute attribute = columns . get ( i ) ; ColumnFunction function = columnFunctions . get ( i ) ; String attributeValue = function . decode ( match . group ( i + ) ) ; if ( attributeValue == null ) { return Expression . FALSE ; } expressions . add ( Equality . createAttributeValue ( attribute , attributeValue ) ) ; } return Conjunction . create ( expressions ) ; } public Set < ProjectionSpec > projectionSpecs ( ) { return this . columnsAsSet ; } public String makeValue ( ResultRow row ) { int index = ; StringBuffer result = new StringBuffer ( this . firstLiteralPart ) ; while ( index < this . columns . size ( ) ) { Attribute column = columns . get ( index ) ; ColumnFunction function = columnFunctions . get ( index ) ; String value = row . get ( column ) ; if ( value == null ) { return null ; } value = function . encode ( value ) ; if ( value == null ) { return null ; } result . append ( value ) ; result . append ( this . literalParts . get ( index ) ) ; index ++ ; } return result . toString ( ) ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { List < OrderSpec > result = new ArrayList < OrderSpec > ( columns . size ( ) ) ; for ( Attribute column : columns ) { result . add ( new OrderSpec ( new AttributeExpr ( column ) , ascending ) ) ; } return result ; } public String toString ( ) { return "" + this . pattern + "" ; } public boolean equals ( Object otherObject ) { if ( ! ( otherObject instanceof Pattern ) ) { return false ; } Pattern other = ( Pattern ) otherObject ; return this . pattern . equals ( other . pattern ) ; } public int hashCode ( ) { return this . pattern . hashCode ( ) ; } public boolean isEquivalentTo ( Pattern p ) { return this . firstLiteralPart . equals ( p . firstLiteralPart ) && this . literalParts . equals ( p . literalParts ) && this . columnFunctions . equals ( p . columnFunctions ) ; } public ValueMaker renameAttributes ( ColumnRenamer renames ) { int index = ; StringBuffer newPattern = new StringBuffer ( this . firstLiteralPart ) ; while ( index < this . columns . size ( ) ) { Attribute column = columns . get ( index ) ; ColumnFunction function = columnFunctions . get ( index ) ; newPattern . append ( DELIMITER ) ; newPattern . append ( renames . applyTo ( column ) . qualifiedName ( ) ) ; if ( function . name ( ) != null ) { newPattern . append ( "" ) ; newPattern . append ( function . name ( ) ) ; } newPattern . append ( DELIMITER ) ; newPattern . append ( this . literalParts . get ( index ) ) ; index ++ ; } return new Pattern ( newPattern . toString ( ) ) ; } private void parsePattern ( ) { Matcher match = embeddedColumnRegex . matcher ( this . pattern ) ; boolean matched = match . find ( ) ; int firstLiteralEnd = matched ? match . start ( ) : this . pattern . length ( ) ; this . firstLiteralPart = this . pattern . substring ( , firstLiteralEnd ) ; String regexPattern = "" + this . firstLiteralPart + "" ; while ( matched ) { this . columns . add ( SQL . parseAttribute ( match . group ( ) ) ) ; this . columnFunctions . add ( getColumnFunction ( match . group ( ) ) ) ; int nextLiteralStart = match . end ( ) ; matched = match . find ( ) ; int nextLiteralEnd = matched ? match . start ( ) : this . pattern . length ( ) ; String nextLiteralPart = this . pattern . substring ( nextLiteralStart , nextLiteralEnd ) ; this . literalParts . add ( nextLiteralPart ) ; regexPattern += "" + nextLiteralPart + "" ; } this . regex = java . util . regex . Pattern . compile ( regexPattern , java . util . regex . Pattern . DOTALL ) ; } public Iterator < Object > partsIterator ( ) { return new Iterator < Object > ( ) { private int i = ; public boolean hasNext ( ) { return i < columns . size ( ) + literalParts . size ( ) + ; } public Object next ( ) { i ++ ; if ( i == ) { return firstLiteralPart ; } else if ( i % == ) { return columns . get ( i / - ) ; } return literalParts . get ( i / - ) ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } public Expression toExpression ( ) { List < Expression > parts = new ArrayList < Expression > ( literalParts . size ( ) * + ) ; parts . add ( new Constant ( firstLiteralPart ) ) ; for ( int i = ; i < columns . size ( ) ; i ++ ) { parts . add ( new AttributeExpr ( columns . get ( i ) ) ) ; parts . add ( new Constant ( literalParts . get ( i ) ) ) ; } return Concatenation . create ( parts ) ; } public boolean usesColumnFunctions ( ) { for ( ColumnFunction f : columnFunctions ) { if ( f != IDENTITY ) return true ; } return false ; } private final static ColumnFunction IDENTITY = new IdentityFunction ( ) ; private final static ColumnFunction URLENCODE = new URLEncodeFunction ( ) ; private final static ColumnFunction ENCODE = new EncodeFunction ( ) ; private final static ColumnFunction URLIFY = new URLifyFunction ( ) ; private ColumnFunction getColumnFunction ( String functionName ) { if ( "" . equals ( functionName ) ) { return URLENCODE ; } if ( "" . equals ( functionName ) ) { return URLIFY ; } if ( "" . equals ( functionName ) ) { return ENCODE ; } if ( "" . equals ( functionName ) || functionName == null ) { return IDENTITY ; } throw new D2RQException ( "" + functionName + "" ) ; } private interface ColumnFunction { String encode ( String s ) ; String decode ( String s ) ; String name ( ) ; } static class IdentityFunction implements ColumnFunction { public String encode ( String s ) { return s ; } public String decode ( String s ) { return s ; } public String name ( ) { return null ; } } static class URLEncodeFunction implements ColumnFunction { public String encode ( String s ) { try { return URLEncoder . encode ( s , "" ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } } public String decode ( String s ) { try { return URLDecoder . decode ( s , "" ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } catch ( IllegalArgumentException ex ) { return null ; } } public String name ( ) { return "" ; } } static class URLifyFunction implements ColumnFunction { public String encode ( String s ) { try { return URLEncoder . encode ( s , "" ) . replaceAll ( "" , "" ) . replace ( '' , '' ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } } public String decode ( String s ) { try { return URLDecoder . decode ( s . replace ( '' , '' ) , "" ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } catch ( IllegalArgumentException ex ) { return null ; } } public String name ( ) { return "" ; } } public static class EncodeFunction implements ColumnFunction { public String encode ( String s ) { return IRIEncoder . encode ( s ) ; } public String decode ( String s ) { try { return URLDecoder . decode ( s . replaceAll ( "" , "" ) , "" ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } catch ( IllegalArgumentException ex ) { return null ; } } public String name ( ) { return "" ; } } } package de . fuberlin . wiwiss . d2rq . values ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . expr . Concatenation ; import de . fuberlin . wiwiss . d2rq . expr . Conjunction ; import de . fuberlin . wiwiss . d2rq . expr . Constant ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public class BlankNodeID implements ValueMaker { private final static String DELIMITER = "" ; private String classMapID ; private List < Attribute > attributes ; public BlankNodeID ( String classMapID , List < Attribute > attributes ) { this . classMapID = classMapID ; this . attributes = attributes ; } public List < Attribute > attributes ( ) { return this . attributes ; } public String classMapID ( ) { return this . classMapID ; } public void describeSelf ( NodeSetFilter c ) { c . limitValuesToBlankNodeID ( this ) ; } public boolean matches ( String value ) { return ! valueExpression ( value ) . isFalse ( ) ; } public Expression valueExpression ( String value ) { if ( value == null ) { return Expression . FALSE ; } String [ ] parts = value . split ( DELIMITER ) ; if ( parts . length != this . attributes . size ( ) + || ! this . classMapID . equals ( parts [ ] ) ) { return Expression . FALSE ; } int i = ; Collection < Expression > expressions = new ArrayList < Expression > ( attributes . size ( ) ) ; for ( Attribute attribute : attributes ) { expressions . add ( Equality . createAttributeValue ( attribute , parts [ i ] ) ) ; i ++ ; } return Conjunction . create ( expressions ) ; } public Set < ProjectionSpec > projectionSpecs ( ) { return new HashSet < ProjectionSpec > ( this . attributes ) ; } public String makeValue ( ResultRow row ) { StringBuffer result = new StringBuffer ( this . classMapID ) ; for ( Attribute attribute : attributes ) { String value = row . get ( attribute ) ; if ( value == null ) { return null ; } result . append ( DELIMITER ) ; result . append ( value ) ; } return result . toString ( ) ; } public ValueMaker renameAttributes ( ColumnRenamer renamer ) { List < Attribute > replacedAttributes = new ArrayList < Attribute > ( ) ; for ( Attribute attribute : attributes ) { replacedAttributes . add ( renamer . applyTo ( attribute ) ) ; } return new BlankNodeID ( this . classMapID , replacedAttributes ) ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { List < OrderSpec > result = new ArrayList < OrderSpec > ( attributes . size ( ) ) ; for ( Attribute column : attributes ) { result . add ( new OrderSpec ( new AttributeExpr ( column ) , ascending ) ) ; } return result ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; Iterator < Attribute > it = attributes . iterator ( ) ; while ( it . hasNext ( ) ) { Attribute attribute = ( Attribute ) it . next ( ) ; result . append ( attribute . qualifiedName ( ) ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } public Expression toExpression ( ) { List < Expression > parts = new ArrayList < Expression > ( ) ; parts . add ( new Constant ( classMapID ) ) ; for ( Attribute attribute : attributes ) { parts . add ( new Constant ( DELIMITER ) ) ; parts . add ( new AttributeExpr ( attribute ) ) ; } return Concatenation . create ( parts ) ; } } package de . fuberlin . wiwiss . d2rq ; import java . io . File ; import java . io . IOException ; import java . nio . charset . MalformedInputException ; import java . sql . SQLException ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . openjena . atlas . AtlasException ; import org . openjena . riot . RiotException ; import com . hp . hpl . jena . n3 . turtle . TurtleParseException ; import com . hp . hpl . jena . query . ARQ ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . shared . JenaException ; import com . hp . hpl . jena . util . FileManager ; import com . hp . hpl . jena . util . FileUtils ; import de . fuberlin . wiwiss . d2rq . jena . GraphD2RQ ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . mapgen . Filter ; import de . fuberlin . wiwiss . d2rq . mapgen . MappingGenerator ; import de . fuberlin . wiwiss . d2rq . mapgen . W3CMappingGenerator ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; import de . fuberlin . wiwiss . d2rq . server . ConfigLoader ; import de . fuberlin . wiwiss . d2rq . server . D2RServer ; import de . fuberlin . wiwiss . d2rq . server . JettyLauncher ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . SQLScriptLoader ; public class SystemLoader { static { ARQ . init ( ) ; } private final static Log log = LogFactory . getLog ( SystemLoader . class ) ; private static final String DEFAULT_PROTOCOL = "" ; private static final String DEFAULT_HOST = "" ; private static final int DEFAULT_PORT = ; public static final String DEFAULT_BASE_URI = DEFAULT_PROTOCOL + "" + DEFAULT_HOST + "" + DEFAULT_PORT + "" ; public static final String DEFAULT_JDBC_URL = "" ; private String username = null ; private String password = null ; private String jdbcDriverClass = null ; private String sqlScript = null ; private boolean generateDirectMapping = false ; private String jdbcURL = null ; private String mappingFile = null ; private String baseURI = null ; private String resourceStem = "" ; private Filter filter = null ; private boolean fastMode = false ; private int port = - ; private int resultSizeLimit = Database . NO_LIMIT ; private ConnectedDB connectedDB = null ; private MappingGenerator generator = null ; private Model mapModel = null ; private Mapping mapping = null ; private ModelD2RQ dataModel = null ; private GraphD2RQ dataGraph = null ; private JettyLauncher jettyLauncher = null ; private ConfigLoader serverConfig = null ; private D2RServer d2rServer = null ; private ClassMapLister classMapLister = null ; public void setUsername ( String username ) { this . username = username ; } public void setPassword ( String password ) { this . password = password ; } public void setFilter ( Filter filter ) { this . filter = filter ; } public void setJDBCDriverClass ( String driver ) { this . jdbcDriverClass = driver ; ConnectedDB . registerJDBCDriver ( driver ) ; } public void setStartupSQLScript ( String sqlFile ) { this . sqlScript = sqlFile ; } public void setGenerateW3CDirectMapping ( boolean flag ) { this . generateDirectMapping = flag ; } public void setJdbcURL ( String jdbcURL ) { this . jdbcURL = jdbcURL ; } public void setMappingFileOrJdbcURL ( String value ) { if ( value . toLowerCase ( ) . startsWith ( "" ) ) { jdbcURL = value ; } else { mappingFile = value ; } } public void setSystemBaseURI ( String baseURI ) { if ( ! java . net . URI . create ( baseURI ) . isAbsolute ( ) ) { throw new D2RQException ( "" + baseURI + "" , D2RQException . STARTUP_BASE_URI_NOT_ABSOLUTE ) ; } this . baseURI = baseURI ; } public void setResourceStem ( String value ) { resourceStem = value ; } public String getSystemBaseURI ( ) { if ( baseURI != null ) { return MapParser . absolutizeURI ( baseURI ) ; } if ( getServerConfig ( ) != null && serverConfig . baseURI ( ) != null ) { return serverConfig . baseURI ( ) ; } if ( getPort ( ) == ) { return DEFAULT_PROTOCOL + "" + DEFAULT_HOST + "" ; } return DEFAULT_PROTOCOL + "" + DEFAULT_HOST + "" + getPort ( ) + "" ; } public String getResourceBaseURI ( ) { return getSystemBaseURI ( ) + resourceStem ; } public void setPort ( int port ) { this . port = port ; } public int getPort ( ) { int effectivePort = port ; if ( effectivePort == - && getServerConfig ( ) != null ) { effectivePort = getServerConfig ( ) . port ( ) ; } if ( effectivePort == - ) { return DEFAULT_PORT ; } return effectivePort ; } public void setFastMode ( boolean flag ) { this . fastMode = flag ; } public void setMappingURL ( String mappingURL ) { this . mappingFile = mappingURL ; } public void setResultSizeLimit ( int value ) { this . resultSizeLimit = value ; } private ConnectedDB getConnectedDB ( ) { if ( connectedDB == null ) { connectedDB = new ConnectedDB ( jdbcURL , username , password ) ; if ( sqlScript != null ) { try { SQLScriptLoader . loadFile ( new File ( sqlScript ) , connectedDB . connection ( ) ) ; } catch ( IOException ex ) { connectedDB . close ( ) ; throw new D2RQException ( "" + sqlScript , D2RQException . STARTUP_SQL_SCRIPT_ACCESS ) ; } catch ( SQLException ex ) { connectedDB . close ( ) ; throw new D2RQException ( "" + sqlScript + "" + ex . getMessage ( ) , D2RQException . STARTUP_SQL_SCRIPT_SYNTAX ) ; } } } return connectedDB ; } public MappingGenerator openMappingGenerator ( ) { if ( generator == null ) { generator = generateDirectMapping ? new W3CMappingGenerator ( getConnectedDB ( ) ) : new MappingGenerator ( getConnectedDB ( ) ) ; if ( jdbcDriverClass != null ) { generator . setJDBCDriverClass ( jdbcDriverClass ) ; } if ( filter != null ) { generator . setFilter ( filter ) ; } if ( sqlScript != null ) { generator . setStartupSQLScript ( new File ( sqlScript ) . toURI ( ) ) ; } } return generator ; } public void closeMappingGenerator ( ) { if ( connectedDB != null ) { connectedDB . close ( ) ; } } public Model getMappingModel ( ) { if ( mapModel == null ) { if ( jdbcURL != null && mappingFile != null ) { throw new D2RQException ( "" + mappingFile + "" + jdbcURL + "" ) ; } if ( jdbcURL == null && mappingFile == null ) { throw new D2RQException ( "" ) ; } if ( jdbcURL != null ) { mapModel = openMappingGenerator ( ) . mappingModel ( getResourceBaseURI ( ) ) ; } else { log . info ( "" + mappingFile ) ; String lang = FileUtils . guessLang ( mappingFile , "" ) ; try { if ( lang . equals ( "" ) ) { mapModel = FileManager . get ( ) . loadModel ( mappingFile , getResourceBaseURI ( ) , "" ) ; } else { mapModel = FileManager . get ( ) . loadModel ( mappingFile , getResourceBaseURI ( ) , null ) ; } } catch ( TurtleParseException ex ) { throw new D2RQException ( "" + mappingFile + "" + ex . getMessage ( ) , ex , ) ; } catch ( JenaException ex ) { if ( ex . getCause ( ) != null && ex . getCause ( ) instanceof RiotException ) { throw new D2RQException ( "" + mappingFile + "" + ex . getCause ( ) . getMessage ( ) , ex , ) ; } throw ex ; } catch ( AtlasException ex ) { if ( FileUtils . langTurtle . equals ( lang ) && ex . getCause ( ) != null && ( ex . getCause ( ) instanceof MalformedInputException ) ) { throw new D2RQException ( "" + mappingFile + "" + "" + ( ( MalformedInputException ) ex . getCause ( ) ) . getInputLength ( ) , ex , ) ; } throw new D2RQException ( "" + mappingFile + "" + ex . getMessage ( ) , ex , ) ; } } } return mapModel ; } public Mapping getMapping ( ) { if ( mapping == null ) { mapping = new MapParser ( getMappingModel ( ) , getResourceBaseURI ( ) ) . parse ( ) ; mapping . configuration ( ) . setUseAllOptimizations ( fastMode ) ; if ( connectedDB != null ) { for ( Database db : mapping . databases ( ) ) { if ( db . getJDBCDSN ( ) . equals ( connectedDB . getJdbcURL ( ) ) ) { if ( resultSizeLimit != Database . NO_LIMIT ) { db . setResultSizeLimit ( resultSizeLimit ) ; } db . useConnectedDB ( connectedDB ) ; } } } } return mapping ; } public ModelD2RQ getModelD2RQ ( ) { if ( dataModel == null ) { dataModel = new ModelD2RQ ( getMapping ( ) ) ; } return dataModel ; } public GraphD2RQ getGraphD2RQ ( ) { if ( dataGraph == null ) { dataGraph = ( GraphD2RQ ) getModelD2RQ ( ) . getGraph ( ) ; } return dataGraph ; } public ClassMapLister getClassMapLister ( ) { if ( classMapLister == null ) { classMapLister = new ClassMapLister ( getMapping ( ) ) ; } return classMapLister ; } public JettyLauncher getJettyLauncher ( ) { if ( jettyLauncher == null ) { jettyLauncher = new JettyLauncher ( this , getPort ( ) ) ; } return jettyLauncher ; } public ConfigLoader getServerConfig ( ) { if ( serverConfig == null ) { serverConfig = new ConfigLoader ( mappingFile == null ? null : ConfigLoader . toAbsoluteURI ( mappingFile ) ) ; serverConfig . load ( ) ; } return serverConfig ; } public D2RServer getD2RServer ( ) { if ( d2rServer == null ) { d2rServer = new D2RServer ( this ) ; if ( baseURI != null || ( getServerConfig ( ) != null && getServerConfig ( ) . baseURI ( ) == null ) ) { d2rServer . overrideBaseURI ( getSystemBaseURI ( ) ) ; } } return d2rServer ; } public void resetMappingFile ( ) { mapModel = null ; mapping = null ; dataModel = null ; if ( dataGraph != null ) dataGraph . close ( ) ; dataGraph = null ; classMapLister = null ; } } package de . fuberlin . wiwiss . d2rq . download ; import java . io . ByteArrayInputStream ; import java . io . InputStream ; import java . sql . Connection ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . sql . Types ; import java . util . HashSet ; import java . util . Set ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . graph . Node ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . MutableRelation ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . map . DownloadMap ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . ResultRowMap ; import de . fuberlin . wiwiss . d2rq . sql . SQLIterator ; import de . fuberlin . wiwiss . d2rq . sql . SelectStatementBuilder ; import de . fuberlin . wiwiss . d2rq . values . ValueMaker ; public class DownloadContentQuery { private static final Log log = LogFactory . getLog ( DownloadContentQuery . class ) ; private final DownloadMap downloadMap ; private final ValueMaker mediaTypeValueMaker ; private final String uri ; private Statement statement = null ; private ResultSet resultSet = null ; private InputStream resultStream = null ; private String mediaType = null ; public DownloadContentQuery ( DownloadMap downloadMap , String uri ) { this . downloadMap = downloadMap ; this . mediaTypeValueMaker = downloadMap . getMediaTypeValueMaker ( ) ; this . uri = uri ; execute ( ) ; } public boolean hasContent ( ) { return resultStream != null ; } public InputStream getContentStream ( ) { return resultStream ; } public String getMediaType ( ) { return mediaType ; } public void close ( ) { try { if ( this . statement != null ) { this . statement . close ( ) ; this . statement = null ; } if ( this . resultSet != null ) { this . resultSet . close ( ) ; this . resultSet = null ; } } catch ( SQLException ex ) { throw new D2RQException ( ex ) ; } } private void execute ( ) { MutableRelation newRelation = new MutableRelation ( downloadMap . getRelation ( ) ) ; NodeMaker x = downloadMap . nodeMaker ( ) . selectNode ( Node . createURI ( uri ) , newRelation ) ; if ( x . equals ( NodeMaker . EMPTY ) ) return ; Set < ProjectionSpec > requiredProjections = new HashSet < ProjectionSpec > ( ) ; requiredProjections . add ( downloadMap . getContentDownloadColumn ( ) ) ; requiredProjections . addAll ( mediaTypeValueMaker . projectionSpecs ( ) ) ; newRelation . project ( requiredProjections ) ; newRelation . limit ( ) ; Relation filteredRelation = newRelation . immutableSnapshot ( ) ; SelectStatementBuilder builder = new SelectStatementBuilder ( filteredRelation ) ; String sql = builder . getSQLStatement ( ) ; int contentColumn = builder . getColumnSpecs ( ) . indexOf ( downloadMap . getContentDownloadColumn ( ) ) + ; ConnectedDB db = filteredRelation . database ( ) ; Connection conn = db . connection ( ) ; try { statement = conn . createStatement ( ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY ) ; log . debug ( sql ) ; resultSet = statement . executeQuery ( sql ) ; if ( ! resultSet . next ( ) ) { close ( ) ; return ; } int type = resultSet . getMetaData ( ) . getColumnType ( contentColumn ) ; if ( type == Types . BINARY || type == Types . VARBINARY || type == Types . LONGVARBINARY || type == Types . BLOB ) { resultStream = resultSet . getBinaryStream ( contentColumn ) ; if ( resultSet . wasNull ( ) ) { resultStream = null ; } } else { String s = resultSet . getString ( contentColumn ) ; if ( ! resultSet . wasNull ( ) ) { resultStream = new ByteArrayInputStream ( s . getBytes ( ) ) ; } } mediaType = mediaTypeValueMaker . makeValue ( ResultRowMap . fromResultSet ( resultSet , builder . getColumnSpecs ( ) , db ) ) ; } catch ( SQLException ex ) { throw new D2RQException ( ex ) ; } } } package de . fuberlin . wiwiss . d2rq . jena ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . graph . TripleMatch ; import com . hp . hpl . jena . util . iterator . ExtendedIterator ; import com . hp . hpl . jena . util . iterator . WrappedIterator ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; public class CachingGraphD2RQ extends GraphD2RQ { private Map < TripleMatch , List < Triple > > queryCache = new LinkedHashMap < TripleMatch , List < Triple > > ( , , true ) { private static final int MAX_ENTRIES = ; @ Override protected boolean removeEldestEntry ( Map . Entry < TripleMatch , List < Triple > > eldest ) { return size ( ) > MAX_ENTRIES ; } } ; public CachingGraphD2RQ ( Mapping mapping ) throws D2RQException { super ( mapping ) ; } public void clearCache ( ) { queryCache . clear ( ) ; } @ Override public ExtendedIterator < Triple > graphBaseFind ( TripleMatch m ) { List < Triple > cached = queryCache . get ( m ) ; if ( cached != null ) { return WrappedIterator . create ( cached . iterator ( ) ) ; } ExtendedIterator < Triple > it = super . graphBaseFind ( m ) ; final List < Triple > list = it . toList ( ) ; queryCache . put ( m , list ) ; return WrappedIterator . create ( list . iterator ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . jena ; import java . util . HashMap ; import java . util . Map ; import com . hp . hpl . jena . graph . Graph ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . graph . query . BindingQueryPlan ; import com . hp . hpl . jena . graph . query . Domain ; import com . hp . hpl . jena . graph . query . Query ; import com . hp . hpl . jena . graph . query . QueryHandler ; import com . hp . hpl . jena . graph . query . SimpleQueryHandler ; import com . hp . hpl . jena . graph . query . TreeQueryPlan ; import com . hp . hpl . jena . sparql . algebra . op . OpBGP ; import com . hp . hpl . jena . sparql . core . BasicPattern ; import com . hp . hpl . jena . sparql . core . DatasetGraph ; import com . hp . hpl . jena . sparql . core . DatasetGraphFactory ; import com . hp . hpl . jena . sparql . core . Var ; import com . hp . hpl . jena . sparql . engine . Plan ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import com . hp . hpl . jena . util . iterator . ExtendedIterator ; import com . hp . hpl . jena . util . iterator . Map1 ; import com . hp . hpl . jena . util . iterator . Map1Iterator ; import de . fuberlin . wiwiss . d2rq . engine . QueryEngineD2RQ ; public class D2RQQueryHandler extends SimpleQueryHandler { private final DatasetGraph dataset ; private Node [ ] variables ; private Map < Node , Integer > indexes ; public D2RQQueryHandler ( GraphD2RQ graph ) { super ( graph ) ; dataset = DatasetGraphFactory . createOneGraph ( graph ) ; } public TreeQueryPlan prepareTree ( Graph pattern ) { throw new RuntimeException ( "" ) ; } public BindingQueryPlan prepareBindings ( Query q , Node [ ] variables ) { this . variables = variables ; this . indexes = new HashMap < Node , Integer > ( ) ; for ( int i = ; i < variables . length ; i ++ ) { indexes . put ( variables [ i ] , new Integer ( i ) ) ; } BasicPattern pattern = new BasicPattern ( ) ; for ( Triple t : q . getPattern ( ) ) { pattern . add ( t ) ; } Plan plan = QueryEngineD2RQ . getFactory ( ) . create ( new OpBGP ( pattern ) , dataset , null , null ) ; final ExtendedIterator < Domain > queryIterator = new Map1Iterator < Binding , Domain > ( new BindingToDomain ( ) , plan . iterator ( ) ) ; return new BindingQueryPlan ( ) { public ExtendedIterator < Domain > executeBindings ( ) { return queryIterator ; } } ; } private class BindingToDomain implements Map1 < Binding , Domain > { public Domain map1 ( Binding binding ) { Domain d = new Domain ( variables . length ) ; for ( int i = ; i < variables . length ; i ++ ) { Var v = Var . alloc ( variables [ i ] ) ; Node value = binding . get ( v ) ; int index = ( ( Integer ) indexes . get ( v ) ) . intValue ( ) ; d . setElement ( index , value ) ; } return d ; } } } package de . fuberlin . wiwiss . d2rq . jena ; import com . hp . hpl . jena . enhanced . BuiltinPersonalities ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . impl . ModelCom ; import com . hp . hpl . jena . util . FileManager ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; public class ModelD2RQ extends ModelCom implements Model { public ModelD2RQ ( String mapURL ) { this ( FileManager . get ( ) . loadModel ( mapURL ) , mapURL + "" ) ; } public ModelD2RQ ( String mapURL , String serializationFormat , String baseURIForData ) { this ( FileManager . get ( ) . loadModel ( mapURL , serializationFormat ) , ( baseURIForData == null ) ? mapURL + "" : baseURIForData ) ; } public ModelD2RQ ( Model mapModel , String baseURIForData ) { super ( new GraphD2RQ ( new MapParser ( mapModel , ( baseURIForData == null ) ? "" : baseURIForData ) . parse ( ) ) , BuiltinPersonalities . model ) ; } public ModelD2RQ ( Mapping mapping ) { super ( new GraphD2RQ ( mapping ) , BuiltinPersonalities . model ) ; } @ Override public GraphD2RQ getGraph ( ) { return ( GraphD2RQ ) super . getGraph ( ) ; } } package de . fuberlin . wiwiss . d2rq . jena ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . graph . Capabilities ; import com . hp . hpl . jena . graph . Graph ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . graph . TripleMatch ; import com . hp . hpl . jena . graph . impl . GraphBase ; import com . hp . hpl . jena . graph . query . QueryHandler ; import com . hp . hpl . jena . util . iterator . ExtendedIterator ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . engine . QueryEngineD2RQ ; import de . fuberlin . wiwiss . d2rq . find . FindQuery ; import de . fuberlin . wiwiss . d2rq . find . TripleQueryIter ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; public class GraphD2RQ extends GraphBase implements Graph { private static final Log log = LogFactory . getLog ( GraphD2RQ . class ) ; private static final Capabilities capabilities = new Capabilities ( ) { public boolean sizeAccurate ( ) { return true ; } public boolean addAllowed ( ) { return addAllowed ( false ) ; } public boolean addAllowed ( boolean every ) { return false ; } public boolean deleteAllowed ( ) { return deleteAllowed ( false ) ; } public boolean deleteAllowed ( boolean every ) { return false ; } public boolean canBeEmpty ( ) { return true ; } public boolean iteratorRemoveAllowed ( ) { return false ; } public boolean findContractSafe ( ) { return false ; } public boolean handlesLiteralTyping ( ) { return true ; } } ; static { QueryEngineD2RQ . register ( ) ; } private final Mapping mapping ; public GraphD2RQ ( Mapping mapping ) throws D2RQException { this . mapping = mapping ; getPrefixMapping ( ) . setNsPrefixes ( mapping . getPrefixMapping ( ) ) ; } @ Override public QueryHandler queryHandler ( ) { checkOpen ( ) ; return new D2RQQueryHandler ( this ) ; } @ Override public void close ( ) { mapping . close ( ) ; } @ Override public Capabilities getCapabilities ( ) { return capabilities ; } @ Override public ExtendedIterator < Triple > graphBaseFind ( TripleMatch m ) { checkOpen ( ) ; Triple t = m . asTriple ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" + PrettyPrinter . toString ( t , getPrefixMapping ( ) ) ) ; } FindQuery query = new FindQuery ( t , mapping . compiledPropertyBridges ( ) , null ) ; ExtendedIterator < Triple > result = TripleQueryIter . create ( query . iterator ( ) ) ; if ( mapping . configuration ( ) . getServeVocabulary ( ) ) { result = result . andThen ( mapping . getVocabularyModel ( ) . getGraph ( ) . find ( t ) ) ; } return result ; } @ Override protected void checkOpen ( ) { mapping . connect ( ) ; } public Mapping getMapping ( ) { return mapping ; } } package de . fuberlin . wiwiss . d2rq ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; public class Log4jHelper { public static void turnLoggingOff ( ) { System . err . println ( "" ) ; Logger . getLogger ( "" ) . setLevel ( Level . OFF ) ; } public static void setVerboseLogging ( ) { Logger . getLogger ( "" ) . setLevel ( Level . INFO ) ; Logger . getLogger ( "" ) . setLevel ( Level . INFO ) ; Logger . getLogger ( "" ) . setLevel ( Level . INFO ) ; Logger . getLogger ( "" ) . setLevel ( Level . INFO ) ; } public static void setDebugLogging ( ) { Logger . getLogger ( "" ) . setLevel ( Level . ALL ) ; Logger . getLogger ( "" ) . setLevel ( Level . ALL ) ; Logger . getLogger ( "" ) . setLevel ( Level . INFO ) ; Logger . getLogger ( "" ) . setLevel ( Level . INFO ) ; } } package de . fuberlin . wiwiss . d2rq ; import java . io . IOException ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . Collection ; import jena . cmdline . ArgDecl ; import jena . cmdline . CmdLineUtils ; import jena . cmdline . CommandLine ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . shared . JenaException ; import de . fuberlin . wiwiss . d2rq . mapgen . Filter ; import de . fuberlin . wiwiss . d2rq . mapgen . FilterIncludeExclude ; import de . fuberlin . wiwiss . d2rq . mapgen . FilterMatchAny ; import de . fuberlin . wiwiss . d2rq . mapgen . FilterParser ; import de . fuberlin . wiwiss . d2rq . mapgen . FilterParser . ParseException ; public abstract class CommandLineTool { private final static Log log = LogFactory . getLog ( CommandLineTool . class ) ; private final CommandLine cmd = new CommandLine ( ) ; private final ArgDecl userArg = new ArgDecl ( true , "" , "" , "" ) ; private final ArgDecl passArg = new ArgDecl ( true , "" , "" , "" ) ; private final ArgDecl driverArg = new ArgDecl ( true , "" , "" ) ; private final ArgDecl sqlFileArg = new ArgDecl ( true , "" , "" ) ; private final ArgDecl w3cArg = new ArgDecl ( false , "" , "" ) ; private final ArgDecl verboseArg = new ArgDecl ( false , "" ) ; private final ArgDecl debugArg = new ArgDecl ( false , "" ) ; private final ArgDecl schemasArg = new ArgDecl ( true , "" , "" ) ; private final ArgDecl tablesArg = new ArgDecl ( true , "" , "" ) ; private final ArgDecl columnsArg = new ArgDecl ( true , "" , "" ) ; private final ArgDecl skipSchemasArg = new ArgDecl ( true , "" , "" ) ; private final ArgDecl skipTablesArg = new ArgDecl ( true , "" , "" ) ; private final ArgDecl skipColumnsArg = new ArgDecl ( true , "" , "" ) ; private final SystemLoader loader = new SystemLoader ( ) ; private boolean supportImplicitJdbcURL = true ; private int minArguments = ; private int maxArguments = ; public abstract void usage ( ) ; public abstract void initArgs ( CommandLine cmd ) ; public abstract void run ( CommandLine cmd , SystemLoader loader ) throws D2RQException , IOException ; public void setMinMaxArguments ( int min , int max ) { minArguments = min ; maxArguments = max ; } public void setSupportImplicitJdbcURL ( boolean flag ) { supportImplicitJdbcURL = flag ; } public void process ( String [ ] args ) { cmd . add ( userArg ) ; cmd . add ( passArg ) ; cmd . add ( driverArg ) ; cmd . add ( sqlFileArg ) ; cmd . add ( w3cArg ) ; cmd . add ( verboseArg ) ; cmd . add ( debugArg ) ; cmd . add ( schemasArg ) ; cmd . add ( tablesArg ) ; cmd . add ( columnsArg ) ; cmd . add ( skipSchemasArg ) ; cmd . add ( skipTablesArg ) ; cmd . add ( skipColumnsArg ) ; initArgs ( cmd ) ; try { cmd . process ( args ) ; } catch ( IllegalArgumentException ex ) { reportException ( ex ) ; } if ( cmd . hasArg ( verboseArg ) ) { Log4jHelper . setVerboseLogging ( ) ; } if ( cmd . hasArg ( debugArg ) ) { Log4jHelper . setDebugLogging ( ) ; } if ( cmd . numItems ( ) == minArguments && supportImplicitJdbcURL && cmd . hasArg ( sqlFileArg ) ) { loader . setJdbcURL ( SystemLoader . DEFAULT_JDBC_URL ) ; } else if ( cmd . numItems ( ) == ) { usage ( ) ; System . exit ( ) ; } if ( cmd . numItems ( ) < minArguments ) { reportException ( new IllegalArgumentException ( "" ) ) ; } else if ( cmd . numItems ( ) > maxArguments ) { reportException ( new IllegalArgumentException ( "" ) ) ; } if ( cmd . contains ( userArg ) ) { loader . setUsername ( cmd . getArg ( userArg ) . getValue ( ) ) ; } if ( cmd . contains ( passArg ) ) { loader . setPassword ( cmd . getArg ( passArg ) . getValue ( ) ) ; } if ( cmd . contains ( driverArg ) ) { loader . setJDBCDriverClass ( cmd . getArg ( driverArg ) . getValue ( ) ) ; } if ( cmd . contains ( sqlFileArg ) ) { loader . setStartupSQLScript ( cmd . getArg ( sqlFileArg ) . getValue ( ) ) ; } if ( cmd . contains ( w3cArg ) ) { loader . setGenerateW3CDirectMapping ( true ) ; } try { Collection < Filter > includes = new ArrayList < Filter > ( ) ; Collection < Filter > excludes = new ArrayList < Filter > ( ) ; if ( cmd . contains ( schemasArg ) ) { String spec = withIndirection ( cmd . getArg ( schemasArg ) . getValue ( ) ) ; includes . add ( new FilterParser ( spec ) . parseSchemaFilter ( ) ) ; } if ( cmd . contains ( tablesArg ) ) { String spec = withIndirection ( cmd . getArg ( tablesArg ) . getValue ( ) ) ; includes . add ( new FilterParser ( spec ) . parseTableFilter ( true ) ) ; } if ( cmd . contains ( columnsArg ) ) { String spec = withIndirection ( cmd . getArg ( columnsArg ) . getValue ( ) ) ; includes . add ( new FilterParser ( spec ) . parseColumnFilter ( true ) ) ; } if ( cmd . contains ( skipSchemasArg ) ) { String spec = withIndirection ( cmd . getArg ( skipSchemasArg ) . getValue ( ) ) ; excludes . add ( new FilterParser ( spec ) . parseSchemaFilter ( ) ) ; } if ( cmd . contains ( skipTablesArg ) ) { String spec = withIndirection ( cmd . getArg ( skipTablesArg ) . getValue ( ) ) ; excludes . add ( new FilterParser ( spec ) . parseTableFilter ( false ) ) ; } if ( cmd . contains ( skipColumnsArg ) ) { String spec = withIndirection ( cmd . getArg ( skipColumnsArg ) . getValue ( ) ) ; excludes . add ( new FilterParser ( spec ) . parseColumnFilter ( false ) ) ; } if ( ! includes . isEmpty ( ) || ! excludes . isEmpty ( ) ) { loader . setFilter ( new FilterIncludeExclude ( includes . isEmpty ( ) ? Filter . ALL : FilterMatchAny . create ( includes ) , FilterMatchAny . create ( excludes ) ) ) ; } run ( cmd , loader ) ; } catch ( IllegalArgumentException ex ) { reportException ( ex ) ; } catch ( IOException ex ) { reportException ( ex ) ; } catch ( D2RQException ex ) { reportException ( ex ) ; } catch ( JenaException ex ) { reportException ( ex ) ; } catch ( ParseException ex ) { reportException ( ex ) ; } } public static void reportException ( D2RQException ex ) { if ( ex . getMessage ( ) == null && ex . getCause ( ) != null && ex . getCause ( ) . getMessage ( ) != null ) { if ( ex . getCause ( ) instanceof SQLException ) { System . err . println ( "" + ex . getCause ( ) . getMessage ( ) ) ; } else { System . err . println ( ex . getCause ( ) . getMessage ( ) ) ; } } else { System . err . println ( ex . getMessage ( ) ) ; } log . info ( "" , ex ) ; System . exit ( ) ; } public void reportException ( Exception ex ) { System . err . println ( ex . getMessage ( ) ) ; log . info ( "" , ex ) ; System . exit ( ) ; } public void printStandardArguments ( boolean withMappingFile ) { System . err . println ( "" ) ; if ( withMappingFile ) { System . err . println ( "" ) ; } System . err . println ( "" ) ; if ( supportImplicitJdbcURL ) { System . err . println ( "" ) ; } } public void printConnectionOptions ( ) { System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; } private static String withIndirection ( String value ) { if ( value . startsWith ( "" ) ) { value = value . substring ( ) ; try { value = CmdLineUtils . readWholeFileAsUTF8 ( value ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "" + value + "" + ex . getMessage ( ) ) ; } } return value ; } } package de . fuberlin . wiwiss . d2rq . nodes ; import java . util . List ; import java . util . Set ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . rdf . model . AnonId ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . RelationalOperators ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; import de . fuberlin . wiwiss . d2rq . values . ValueMaker ; public class TypedNodeMaker implements NodeMaker { public final static NodeType URI = new URINodeType ( ) ; public final static NodeType BLANK = new BlankNodeType ( ) ; public final static NodeType PLAIN_LITERAL = new LiteralNodeType ( "" , null ) ; public final static NodeType XSD_DATE = new DateLiteralNodeType ( ) ; public final static NodeType XSD_TIME = new TimeLiteralNodeType ( ) ; public final static NodeType XSD_DATETIME = new DateTimeLiteralNodeType ( ) ; public final static NodeType XSD_BOOLEAN = new BooleanLiteralNodeType ( ) ; public static NodeType languageLiteral ( String language ) { return new LiteralNodeType ( language , null ) ; } public static NodeType typedLiteral ( RDFDatatype datatype ) { if ( datatype . equals ( XSDDatatype . XSDdate ) ) { return XSD_DATE ; } if ( datatype . equals ( XSDDatatype . XSDtime ) ) { return XSD_TIME ; } if ( datatype . equals ( XSDDatatype . XSDdateTime ) ) { return XSD_DATETIME ; } if ( datatype . equals ( XSDDatatype . XSDboolean ) ) { return XSD_BOOLEAN ; } return new LiteralNodeType ( "" , datatype ) ; } private NodeType nodeType ; private ValueMaker valueMaker ; private boolean isUnique ; public TypedNodeMaker ( NodeType nodeType , ValueMaker valueMaker , boolean isUnique ) { this . nodeType = nodeType ; this . valueMaker = valueMaker ; this . isUnique = isUnique ; } public Set < ProjectionSpec > projectionSpecs ( ) { return this . valueMaker . projectionSpecs ( ) ; } public boolean isUnique ( ) { return this . isUnique ; } public void describeSelf ( NodeSetFilter c ) { this . nodeType . matchConstraint ( c ) ; this . valueMaker . describeSelf ( c ) ; } public ValueMaker valueMaker ( ) { return this . valueMaker ; } public Node makeNode ( ResultRow tuple ) { String value = this . valueMaker . makeValue ( tuple ) ; if ( value == null ) { return null ; } return this . nodeType . makeNode ( value ) ; } public NodeMaker selectNode ( Node node , RelationalOperators sideEffects ) { if ( node . equals ( Node . ANY ) || node . isVariable ( ) ) { return this ; } if ( ! this . nodeType . matches ( node ) ) { return NodeMaker . EMPTY ; } String value = this . nodeType . extractValue ( node ) ; if ( value == null ) { return NodeMaker . EMPTY ; } Expression expr = valueMaker . valueExpression ( value ) ; if ( expr . isFalse ( ) ) { sideEffects . select ( Expression . FALSE ) ; return NodeMaker . EMPTY ; } sideEffects . select ( expr ) ; return new FixedNodeMaker ( node , isUnique ( ) ) ; } public NodeMaker renameAttributes ( ColumnRenamer renamer ) { return new TypedNodeMaker ( this . nodeType , this . valueMaker . renameAttributes ( renamer ) , this . isUnique ) ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return valueMaker . orderSpecs ( ascending ) ; } public String toString ( ) { return this . nodeType . toString ( ) + "" + this . valueMaker + "" ; } public interface NodeType { String extractValue ( Node node ) ; Node makeNode ( String value ) ; void matchConstraint ( NodeSetFilter c ) ; boolean matches ( Node node ) ; } private static class URINodeType implements NodeType { public String extractValue ( Node node ) { return node . getURI ( ) ; } public Node makeNode ( String value ) { return Node . createURI ( value ) ; } public void matchConstraint ( NodeSetFilter c ) { c . limitToURIs ( ) ; } public boolean matches ( Node node ) { return node . isURI ( ) ; } public String toString ( ) { return "" ; } } private static class BlankNodeType implements NodeType { public String extractValue ( Node node ) { return node . getBlankNodeLabel ( ) ; } public Node makeNode ( String value ) { return Node . createAnon ( new AnonId ( value ) ) ; } public void matchConstraint ( NodeSetFilter c ) { c . limitToBlankNodes ( ) ; } public boolean matches ( Node node ) { return node . isBlank ( ) ; } public String toString ( ) { return "" ; } } private static class LiteralNodeType implements NodeType { private String language ; private RDFDatatype datatype ; LiteralNodeType ( String language , RDFDatatype datatype ) { this . language = language ; this . datatype = datatype ; } public String extractValue ( Node node ) { return node . getLiteralLexicalForm ( ) ; } public Node makeNode ( String value ) { return Node . createLiteral ( value , this . language , this . datatype ) ; } public void matchConstraint ( NodeSetFilter c ) { c . limitToLiterals ( this . language , this . datatype ) ; } public boolean matches ( Node node ) { return node . isLiteral ( ) && this . language . equals ( node . getLiteralLanguage ( ) ) && ( ( this . datatype == null && node . getLiteralDatatype ( ) == null ) || ( this . datatype != null && this . datatype . equals ( node . getLiteralDatatype ( ) ) ) ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; if ( ! "" . equals ( this . language ) ) { result . append ( "" + this . language ) ; } if ( this . datatype != null ) { result . append ( "" ) ; result . append ( PrettyPrinter . toString ( this . datatype ) ) ; } return result . toString ( ) ; } } private static class DateLiteralNodeType extends LiteralNodeType { DateLiteralNodeType ( ) { super ( "" , XSDDatatype . XSDdate ) ; } public boolean matches ( Node node ) { return super . matches ( node ) && XSDDatatype . XSDdate . isValid ( node . getLiteralLexicalForm ( ) ) ; } public Node makeNode ( String value ) { if ( ! XSDDatatype . XSDdate . isValid ( value ) ) return null ; return Node . createLiteral ( value , null , XSDDatatype . XSDdate ) ; } } private static class TimeLiteralNodeType extends LiteralNodeType { TimeLiteralNodeType ( ) { super ( "" , XSDDatatype . XSDtime ) ; } public boolean matches ( Node node ) { return super . matches ( node ) && XSDDatatype . XSDtime . isValid ( node . getLiteralLexicalForm ( ) ) ; } public Node makeNode ( String value ) { if ( ! XSDDatatype . XSDtime . isValid ( value ) ) return null ; return Node . createLiteral ( value , null , XSDDatatype . XSDtime ) ; } } private static class DateTimeLiteralNodeType extends LiteralNodeType { DateTimeLiteralNodeType ( ) { super ( "" , XSDDatatype . XSDdateTime ) ; } public boolean matches ( Node node ) { return super . matches ( node ) && XSDDatatype . XSDdateTime . isValid ( node . getLiteralLexicalForm ( ) ) ; } public Node makeNode ( String value ) { if ( ! XSDDatatype . XSDdateTime . isValid ( value ) ) return null ; return Node . createLiteral ( value , null , XSDDatatype . XSDdateTime ) ; } } private static class BooleanLiteralNodeType extends LiteralNodeType { private final static Node TRUE = Node . createLiteral ( "" , null , XSDDatatype . XSDboolean ) ; private final static Node FALSE = Node . createLiteral ( "" , null , XSDDatatype . XSDboolean ) ; BooleanLiteralNodeType ( ) { super ( "" , XSDDatatype . XSDboolean ) ; } public boolean matches ( Node node ) { return super . matches ( node ) && XSDDatatype . XSDboolean . isValid ( node . getLiteralLexicalForm ( ) ) ; } public Node makeNode ( String value ) { if ( "" . equals ( value ) || "" . equals ( value ) ) return FALSE ; if ( "" . equals ( value ) || "" . equals ( value ) ) return TRUE ; return null ; } } } package de . fuberlin . wiwiss . d2rq . nodes ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . graph . Node ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . values . BlankNodeID ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; import de . fuberlin . wiwiss . d2rq . values . Translator ; public interface NodeSetFilter { void limitToEmptySet ( ) ; void limitTo ( Node node ) ; void limitToURIs ( ) ; void limitToBlankNodes ( ) ; public void limitToLiterals ( String language , RDFDatatype datatype ) ; public void limitValues ( String constant ) ; public void limitValuesToAttribute ( Attribute attribute ) ; public void limitValuesToPattern ( Pattern pattern ) ; public void limitValuesToBlankNodeID ( BlankNodeID id ) ; public void limitValuesToExpression ( Expression expression ) ; public void setUsesTranslator ( Translator translator ) ; } package de . fuberlin . wiwiss . d2rq . nodes ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . hp . hpl . jena . graph . Node ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . RelationalOperators ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public class FixedNodeMaker implements NodeMaker { private Node node ; private boolean isUnique ; public FixedNodeMaker ( Node node , boolean isUnique ) { this . node = node ; this . isUnique = isUnique ; } public boolean isUnique ( ) { return this . isUnique ; } public Node makeNode ( ResultRow tuple ) { return this . node ; } public void describeSelf ( NodeSetFilter c ) { c . limitTo ( this . node ) ; } public Set < ProjectionSpec > projectionSpecs ( ) { return Collections . < ProjectionSpec > emptySet ( ) ; } public NodeMaker selectNode ( Node n , RelationalOperators sideEffects ) { if ( n . equals ( this . node ) || n . equals ( Node . ANY ) || n . isVariable ( ) ) { return this ; } sideEffects . select ( Expression . FALSE ) ; return NodeMaker . EMPTY ; } public NodeMaker renameAttributes ( ColumnRenamer renamer ) { return new FixedNodeMaker ( node , this . isUnique ) ; } public String toString ( ) { return "" + PrettyPrinter . toString ( this . node ) + "" ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return Collections . < OrderSpec > emptyList ( ) ; } } package de . fuberlin . wiwiss . d2rq . nodes ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . hp . hpl . jena . graph . Node ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . RelationalOperators ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public interface NodeMaker { static NodeMaker EMPTY = new NodeMaker ( ) { public boolean isUnique ( ) { return true ; } public Node makeNode ( ResultRow tuple ) { return null ; } public void describeSelf ( NodeSetFilter c ) { c . limitToEmptySet ( ) ; } public Set < ProjectionSpec > projectionSpecs ( ) { return Collections . < ProjectionSpec > emptySet ( ) ; } public NodeMaker selectNode ( Node node , RelationalOperators sideEffects ) { return this ; } public NodeMaker renameAttributes ( ColumnRenamer renamer ) { return this ; } public List < OrderSpec > orderSpecs ( boolean ascending ) { return Collections . < OrderSpec > emptyList ( ) ; } } ; Set < ProjectionSpec > projectionSpecs ( ) ; boolean isUnique ( ) ; void describeSelf ( NodeSetFilter c ) ; Node makeNode ( ResultRow tuple ) ; NodeMaker selectNode ( Node node , RelationalOperators sideEffects ) ; NodeMaker renameAttributes ( ColumnRenamer renamer ) ; List < OrderSpec > orderSpecs ( boolean ascending ) ; } package de . fuberlin . wiwiss . d2rq . nodes ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . sparql . core . Var ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . values . BlankNodeID ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; import de . fuberlin . wiwiss . d2rq . values . Translator ; public class DetermineNodeType implements NodeSetFilter { private final Log logger = LogFactory . getLog ( DetermineNodeType . class ) ; private boolean limitedToURIs = false ; private boolean limitedToBlankNodes = false ; private boolean limitedToLiterals = false ; private RDFDatatype datatype = null ; private String language = null ; public boolean isLimittedToURIs ( ) { return limitedToURIs ; } public RDFDatatype getDatatype ( ) { return datatype ; } public String getLanguage ( ) { return language ; } public boolean isLimittedToBlankNodes ( ) { return limitedToBlankNodes ; } public boolean isLimittedToLiterals ( ) { return limitedToLiterals ; } public void limitTo ( Node node ) { logger . debug ( "" + node ) ; if ( node . isURI ( ) ) limitedToURIs = true ; else if ( node . isLiteral ( ) ) limitedToLiterals = true ; else if ( Var . isBlankNodeVar ( node ) ) limitedToBlankNodes = true ; } public void limitToBlankNodes ( ) { logger . debug ( "" ) ; limitedToBlankNodes = true ; } public void limitToEmptySet ( ) { logger . warn ( "" ) ; } public void limitToLiterals ( String language , RDFDatatype datatype ) { logger . debug ( "" ) ; limitedToLiterals = true ; this . datatype = datatype ; this . language = language ; } public void limitToURIs ( ) { logger . debug ( "" ) ; limitedToURIs = true ; } public void limitValues ( String constant ) { logger . warn ( "" + constant ) ; } public void limitValuesToAttribute ( Attribute attribute ) { logger . warn ( "" + attribute ) ; } public void limitValuesToBlankNodeID ( BlankNodeID id ) { logger . warn ( "" + id ) ; } public void limitValuesToExpression ( Expression expression ) { logger . warn ( "" + expression ) ; } public void limitValuesToPattern ( Pattern pattern ) { logger . warn ( "" + pattern ) ; } public void setUsesTranslator ( Translator translator ) { if ( translator != Translator . IDENTITY ) { logger . warn ( "" + translator ) ; } } } package de . fuberlin . wiwiss . d2rq . nodes ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . graph . Node ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . expr . Conjunction ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . values . BlankNodeID ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; import de . fuberlin . wiwiss . d2rq . values . Translator ; public class NodeSetConstraintBuilder implements NodeSetFilter { private final static Log log = LogFactory . getLog ( NodeSetConstraintBuilder . class ) ; private final static int NODE_TYPE_UNKNOWN = ; private final static int NODE_TYPE_URI = ; private final static int NODE_TYPE_LITERAL = ; private final static int NODE_TYPE_BLANK = ; private boolean isEmpty = false ; private boolean unsupported = false ; private int type = NODE_TYPE_UNKNOWN ; private String constantValue = null ; private String constantLanguage = null ; private RDFDatatype constantDatatype = null ; private Node fixedNode = null ; private Collection < Attribute > attributes = new HashSet < Attribute > ( ) ; private Collection < Pattern > patterns = new HashSet < Pattern > ( ) ; private Collection < Expression > expressions = new HashSet < Expression > ( ) ; private Collection < BlankNodeID > blankNodeIDs = new HashSet < BlankNodeID > ( ) ; private Set < Translator > translators = new HashSet < Translator > ( ) ; private String valueStart = "" ; private String valueEnd = "" ; public void limitToEmptySet ( ) { isEmpty = true ; } public void limitToURIs ( ) { limitToNodeType ( NODE_TYPE_URI ) ; } public void limitToBlankNodes ( ) { limitToNodeType ( NODE_TYPE_BLANK ) ; } public void limitToLiterals ( String language , RDFDatatype datatype ) { if ( isEmpty ) return ; limitToNodeType ( NODE_TYPE_LITERAL ) ; if ( constantLanguage == null ) { constantLanguage = language ; } else { if ( ! constantLanguage . equals ( language ) ) { limitToEmptySet ( ) ; } } if ( constantDatatype == null ) { constantDatatype = datatype ; } else { if ( ! constantDatatype . equals ( datatype ) ) { limitToEmptySet ( ) ; } } } private void limitToNodeType ( int limitType ) { if ( isEmpty ) return ; if ( type == NODE_TYPE_UNKNOWN ) { type = limitType ; return ; } if ( type == limitType ) { return ; } limitToEmptySet ( ) ; } public void limitTo ( Node node ) { if ( isEmpty ) return ; if ( Node . ANY . equals ( node ) || node . isVariable ( ) ) { return ; } if ( fixedNode == null ) { fixedNode = node ; } else if ( ! fixedNode . equals ( node ) ) { limitToEmptySet ( ) ; } if ( node . isURI ( ) ) { limitToURIs ( ) ; limitValues ( node . getURI ( ) ) ; } if ( node . isBlank ( ) ) { limitToBlankNodes ( ) ; limitValues ( node . getBlankNodeLabel ( ) ) ; } if ( node . isLiteral ( ) ) { limitToLiterals ( node . getLiteralLanguage ( ) , node . getLiteralDatatype ( ) ) ; limitValues ( node . getLiteralLexicalForm ( ) ) ; } } public void limitValues ( String constant ) { if ( isEmpty ) return ; if ( constantValue == null ) { constantValue = constant ; } else if ( ! constantValue . equals ( constant ) ) { limitToEmptySet ( ) ; return ; } if ( valueStart != null && ! constant . startsWith ( valueStart ) ) { limitToEmptySet ( ) ; return ; } valueStart = constant ; if ( valueEnd != null && ! constant . endsWith ( valueEnd ) ) { limitToEmptySet ( ) ; return ; } valueEnd = constant ; for ( Pattern pattern : patterns ) { if ( ! pattern . matches ( constant ) ) { limitToEmptySet ( ) ; return ; } } for ( BlankNodeID id : blankNodeIDs ) { if ( ! id . matches ( constant ) ) { limitToEmptySet ( ) ; return ; } } } public void limitValuesToAttribute ( Attribute attribute ) { if ( isEmpty ) return ; attributes . add ( attribute ) ; } public void limitValuesToBlankNodeID ( BlankNodeID id ) { if ( isEmpty ) return ; if ( ! blankNodeIDs . isEmpty ( ) ) { BlankNodeID first = ( BlankNodeID ) blankNodeIDs . iterator ( ) . next ( ) ; if ( ! first . classMapID ( ) . equals ( id . classMapID ( ) ) ) { limitToEmptySet ( ) ; } } blankNodeIDs . add ( id ) ; } public void limitValuesToPattern ( Pattern pattern ) { if ( isEmpty ) return ; patterns . add ( pattern ) ; if ( pattern . firstLiteralPart ( ) . startsWith ( valueStart ) ) { valueStart = pattern . firstLiteralPart ( ) ; } else if ( ! valueStart . startsWith ( pattern . firstLiteralPart ( ) ) ) { limitToEmptySet ( ) ; } if ( pattern . lastLiteralPart ( ) . endsWith ( valueEnd ) ) { valueEnd = pattern . lastLiteralPart ( ) ; } else if ( ! valueEnd . endsWith ( pattern . lastLiteralPart ( ) ) ) { limitToEmptySet ( ) ; } if ( constantValue != null ) { if ( ! pattern . matches ( constantValue ) ) { limitToEmptySet ( ) ; } } } public void limitValuesToExpression ( Expression expression ) { if ( isEmpty ) return ; expressions . add ( expression ) ; } public void setUsesTranslator ( Translator translator ) { translators . add ( translator ) ; if ( translators . size ( ) > ) { unsupported = true ; } } public boolean isEmpty ( ) { return isEmpty ; } private List < Expression > matchPatterns ( Pattern p1 , Pattern p2 ) { List < Expression > results = new ArrayList < Expression > ( p1 . attributes ( ) . size ( ) ) ; if ( p1 . isEquivalentTo ( p2 ) ) { for ( int i = ; i < p1 . attributes ( ) . size ( ) ; i ++ ) { Attribute col1 = p1 . attributes ( ) . get ( i ) ; Attribute col2 = p2 . attributes ( ) . get ( i ) ; results . add ( Equality . createAttributeEquality ( col1 , col2 ) ) ; } } else { results . add ( Equality . create ( p1 . toExpression ( ) , p2 . toExpression ( ) ) ) ; if ( p1 . usesColumnFunctions ( ) || p2 . usesColumnFunctions ( ) ) { log . warn ( "" ) ; unsupported = true ; } } return results ; } private List < Expression > matchBlankNodeIDs ( BlankNodeID id1 , BlankNodeID id2 ) { List < Expression > results = new ArrayList < Expression > ( id1 . attributes ( ) . size ( ) ) ; for ( int i = ; i < id1 . attributes ( ) . size ( ) ; i ++ ) { Attribute col1 = id1 . attributes ( ) . get ( i ) ; Attribute col2 = id2 . attributes ( ) . get ( i ) ; results . add ( Equality . createAttributeEquality ( col1 , col2 ) ) ; } return results ; } public Expression constraint ( ) { if ( isEmpty ( ) ) { return Expression . FALSE ; } List < Expression > translated = new ArrayList < Expression > ( ) ; if ( attributes . size ( ) >= ) { Iterator < Attribute > it = attributes . iterator ( ) ; Attribute first = it . next ( ) ; while ( it . hasNext ( ) ) { translated . add ( Equality . createAttributeEquality ( first , it . next ( ) ) ) ; } } if ( patterns . size ( ) >= ) { Iterator < Pattern > it = patterns . iterator ( ) ; Pattern first = it . next ( ) ; while ( it . hasNext ( ) ) { translated . addAll ( matchPatterns ( first , it . next ( ) ) ) ; } } if ( expressions . size ( ) >= ) { Iterator < Expression > it = expressions . iterator ( ) ; Expression first = it . next ( ) ; while ( it . hasNext ( ) ) { translated . add ( Equality . create ( first , it . next ( ) ) ) ; } } if ( blankNodeIDs . size ( ) >= ) { Iterator < BlankNodeID > it = blankNodeIDs . iterator ( ) ; BlankNodeID first = it . next ( ) ; while ( it . hasNext ( ) ) { translated . addAll ( matchBlankNodeIDs ( first , it . next ( ) ) ) ; } } if ( constantValue != null ) { if ( ! attributes . isEmpty ( ) ) { Attribute first = attributes . iterator ( ) . next ( ) ; translated . add ( Equality . createAttributeValue ( first , constantValue ) ) ; } if ( ! blankNodeIDs . isEmpty ( ) ) { BlankNodeID first = blankNodeIDs . iterator ( ) . next ( ) ; translated . add ( first . valueExpression ( constantValue ) ) ; } if ( ! patterns . isEmpty ( ) ) { Pattern first = patterns . iterator ( ) . next ( ) ; translated . add ( first . valueExpression ( constantValue ) ) ; } if ( ! expressions . isEmpty ( ) ) { Expression first = expressions . iterator ( ) . next ( ) ; translated . add ( Equality . createExpressionValue ( first , constantValue ) ) ; } } else if ( ! attributes . isEmpty ( ) ) { AttributeExpr attribute = new AttributeExpr ( attributes . iterator ( ) . next ( ) ) ; if ( ! blankNodeIDs . isEmpty ( ) ) { BlankNodeID first = blankNodeIDs . iterator ( ) . next ( ) ; translated . add ( Equality . create ( attribute , first . toExpression ( ) ) ) ; } if ( ! patterns . isEmpty ( ) ) { Pattern first = patterns . iterator ( ) . next ( ) ; translated . add ( Equality . create ( attribute , first . toExpression ( ) ) ) ; checkUsesColumnFunctions ( first ) ; } if ( ! expressions . isEmpty ( ) ) { Expression first = expressions . iterator ( ) . next ( ) ; translated . add ( Equality . create ( attribute , first ) ) ; } } else if ( ! expressions . isEmpty ( ) ) { Expression expression = expressions . iterator ( ) . next ( ) ; if ( ! blankNodeIDs . isEmpty ( ) ) { BlankNodeID first = blankNodeIDs . iterator ( ) . next ( ) ; translated . add ( Equality . create ( expression , first . toExpression ( ) ) ) ; } if ( ! patterns . isEmpty ( ) ) { Pattern first = patterns . iterator ( ) . next ( ) ; translated . add ( Equality . create ( expression , first . toExpression ( ) ) ) ; checkUsesColumnFunctions ( first ) ; } } else if ( ! patterns . isEmpty ( ) && ! blankNodeIDs . isEmpty ( ) ) { Pattern firstPattern = patterns . iterator ( ) . next ( ) ; BlankNodeID firstBNodeID = blankNodeIDs . iterator ( ) . next ( ) ; translated . add ( Equality . create ( firstPattern . toExpression ( ) , firstBNodeID . toExpression ( ) ) ) ; checkUsesColumnFunctions ( firstPattern ) ; } if ( translators . size ( ) > ) { log . warn ( "" ) ; } return Conjunction . create ( translated ) ; } private void checkUsesColumnFunctions ( Pattern pattern ) { if ( ! pattern . usesColumnFunctions ( ) ) return ; unsupported = true ; log . warn ( "" + "" ) ; } public boolean isUnsupported ( ) { constraint ( ) ; return unsupported ; } } package de . fuberlin . wiwiss . d2rq . sql ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; public class SQL { private static final java . util . regex . Pattern attributeRegexConservative = java . util . regex . Pattern . compile ( "" + "" + "" + "" ) ; private static final java . util . regex . Pattern attributeRegexLax = java . util . regex . Pattern . compile ( "" + "" + "" ) ; public static Attribute parseAttribute ( String qualifiedName ) { Matcher match = attributeRegexLax . matcher ( qualifiedName ) ; if ( ! match . matches ( ) ) { throw new D2RQException ( "" + qualifiedName + "" , D2RQException . SQL_INVALID_ATTRIBUTENAME ) ; } return new Attribute ( match . group ( ) , match . group ( ) , match . group ( ) ) ; } public static Set < Attribute > findColumnsInExpression ( String expression ) { Set < Attribute > results = new HashSet < Attribute > ( ) ; Matcher match = attributeRegexConservative . matcher ( expression ) ; while ( match . find ( ) ) { results . add ( new Attribute ( match . group ( ) , match . group ( ) , match . group ( ) ) ) ; } return results ; } public static String replaceColumnsInExpression ( String expression , ColumnRenamer columnRenamer ) { StringBuffer result = new StringBuffer ( ) ; Matcher match = attributeRegexConservative . matcher ( expression ) ; boolean matched = match . find ( ) ; int firstPartEnd = matched ? ( match . start ( ) != - ? match . start ( ) : match . start ( ) ) : expression . length ( ) ; result . append ( expression . substring ( , firstPartEnd ) ) ; while ( matched ) { Attribute column = new Attribute ( match . group ( ) , match . group ( ) , match . group ( ) ) ; result . append ( columnRenamer . applyTo ( column ) . qualifiedName ( ) ) ; int nextPartStart = match . end ( ) ; matched = match . find ( ) ; int nextPartEnd = matched ? ( match . start ( ) != - ? match . start ( ) : match . start ( ) ) : expression . length ( ) ; result . append ( expression . substring ( nextPartStart , nextPartEnd ) ) ; } return result . toString ( ) ; } public static String quoteColumnsInExpression ( String expression , ConnectedDB database ) { StringBuffer result = new StringBuffer ( ) ; Matcher match = attributeRegexConservative . matcher ( expression ) ; boolean matched = match . find ( ) ; int firstPartEnd = matched ? ( match . start ( ) != - ? match . start ( ) : match . start ( ) ) : expression . length ( ) ; result . append ( expression . substring ( , firstPartEnd ) ) ; while ( matched ) { result . append ( database . vendor ( ) . quoteAttribute ( new Attribute ( match . group ( ) , match . group ( ) , match . group ( ) ) ) ) ; int nextPartStart = match . end ( ) ; matched = match . find ( ) ; int nextPartEnd = matched ? ( match . start ( ) != - ? match . start ( ) : match . start ( ) ) : expression . length ( ) ; result . append ( expression . substring ( nextPartStart , nextPartEnd ) ) ; } return result . toString ( ) ; } private static final java . util . regex . Pattern relationNameRegex = java . util . regex . Pattern . compile ( "" + "" ) ; public static RelationName parseRelationName ( String qualifiedName ) { Matcher match = relationNameRegex . matcher ( qualifiedName ) ; if ( ! match . matches ( ) ) { throw new D2RQException ( "" + qualifiedName + "" , D2RQException . SQL_INVALID_RELATIONNAME ) ; } return new RelationName ( match . group ( ) , match . group ( ) ) ; } private static final Pattern aliasPattern = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE ) ; public static Alias parseAlias ( String aliasExpression ) { Matcher matcher = aliasPattern . matcher ( aliasExpression ) ; if ( ! matcher . matches ( ) ) { throw new D2RQException ( "" + aliasExpression + "" , D2RQException . SQL_INVALID_ALIAS ) ; } return new Alias ( SQL . parseRelationName ( matcher . group ( ) ) , SQL . parseRelationName ( matcher . group ( ) ) ) ; } public static Set < Join > parseJoins ( Collection < String > joinConditions ) { List < AttributeEqualityCondition > parsedConditions = new ArrayList < AttributeEqualityCondition > ( ) ; for ( String joinCondition : joinConditions ) { parsedConditions . add ( AttributeEqualityCondition . parseJoinCondition ( joinCondition ) ) ; } Collections . sort ( parsedConditions ) ; Set < Join > results = new HashSet < Join > ( ) ; List < Attribute > attributes1 = new ArrayList < Attribute > ( ) ; List < Attribute > attributes2 = new ArrayList < Attribute > ( ) ; int joinOperator = Join . DIRECTION_UNDIRECTED ; AttributeEqualityCondition previousCondition = null ; for ( AttributeEqualityCondition condition : parsedConditions ) { if ( previousCondition == null || ! condition . sameRelations ( previousCondition ) ) { if ( previousCondition != null ) { results . add ( new Join ( attributes1 , attributes2 , joinOperator ) ) ; } attributes1 = new ArrayList < Attribute > ( ) ; attributes2 = new ArrayList < Attribute > ( ) ; joinOperator = condition . joinOperator ( ) ; } attributes1 . add ( condition . firstAttribute ( ) ) ; attributes2 . add ( condition . secondAttribute ( ) ) ; previousCondition = condition ; } if ( previousCondition != null ) { results . add ( new Join ( attributes1 , attributes2 , joinOperator ) ) ; } return results ; } private static class AttributeEqualityCondition implements Comparable < AttributeEqualityCondition > { private Attribute firstAttribute ; private Attribute secondAttribute ; private int joinOperator ; AttributeEqualityCondition ( Attribute a1 , Attribute a2 , int joinOperator ) { this . firstAttribute = ( a1 . compareTo ( a2 ) < ) ? a1 : a2 ; this . secondAttribute = ( a1 . compareTo ( a2 ) < ) ? a2 : a1 ; this . joinOperator = joinOperator ; } public Attribute firstAttribute ( ) { return this . firstAttribute ; } public Attribute secondAttribute ( ) { return this . secondAttribute ; } public int joinOperator ( ) { return this . joinOperator ; } boolean sameRelations ( AttributeEqualityCondition otherCondition ) { return otherCondition . firstAttribute ( ) . relationName ( ) . equals ( firstAttribute ( ) . relationName ( ) ) && otherCondition . secondAttribute ( ) . relationName ( ) . equals ( secondAttribute ( ) . relationName ( ) ) && otherCondition . joinOperator ( ) == joinOperator ( ) ; } public int compareTo ( AttributeEqualityCondition other ) { return this . firstAttribute . compareTo ( other . firstAttribute ) ; } public static AttributeEqualityCondition parseJoinCondition ( String joinCondition ) { int joinOperator = - ; int index = - ; for ( joinOperator = Join . joinOperators . length - ; joinOperator >= ; joinOperator -- ) { if ( - != ( index = joinCondition . indexOf ( Join . joinOperators [ joinOperator ] ) ) ) break ; } if ( index == - ) { throw new D2RQException ( "" + joinCondition + "" , D2RQException . SQL_INVALID_JOIN ) ; } Attribute leftSide = SQL . parseAttribute ( joinCondition . substring ( , index ) . trim ( ) ) ; Attribute rightSide = SQL . parseAttribute ( joinCondition . substring ( index + Join . joinOperators [ joinOperator ] . length ( ) ) . trim ( ) ) ; return new AttributeEqualityCondition ( leftSide , rightSide , joinOperator ) ; } } private final static Pattern HEX_STRING_PATTERN = Pattern . compile ( "" ) ; public static boolean isHexString ( String s ) { return HEX_STRING_PATTERN . matcher ( s ) . matches ( ) ; } private SQL ( ) { } } package de . fuberlin . wiwiss . d2rq . sql ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . dbschema . DatabaseSchemaInspector ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType . GenericType ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class ConnectedDB { private static final Log log = LogFactory . getLog ( ConnectedDB . class ) ; public static final String KEEP_ALIVE_PROPERTY = "" ; public static final int DEFAULT_KEEP_ALIVE_INTERVAL = * ; public static final String KEEP_ALIVE_QUERY_PROPERTY = "" ; public static final String DEFAULT_KEEP_ALIVE_QUERY = "" ; { ConnectedDB . registerJDBCDriverIfPresent ( "" ) ; ConnectedDB . registerJDBCDriverIfPresent ( "" ) ; ConnectedDB . registerJDBCDriverIfPresent ( "" ) ; } private String jdbcURL ; private String username ; private String password ; private final Map < Attribute , Boolean > cachedColumnNullability = new HashMap < Attribute , Boolean > ( ) ; private final Map < Attribute , DataType > cachedColumnTypes = new HashMap < Attribute , DataType > ( ) ; private final Map < Attribute , GenericType > overriddenColumnTypes = new HashMap < Attribute , GenericType > ( ) ; private Connection connection = null ; private DatabaseSchemaInspector schemaInspector = null ; private Vendor vendor = null ; private int limit ; private int fetchSize ; private int defaultFetchSize = Database . NO_FETCH_SIZE ; private Map < Attribute , Boolean > zerofillCache = new HashMap < Attribute , Boolean > ( ) ; private Map < RelationName , Map < String , List < String > > > uniqueIndexCache = new HashMap < RelationName , Map < String , List < String > > > ( ) ; private final Properties connectionProperties ; private class KeepAliveAgent extends Thread { private final int interval ; private final String query ; volatile boolean shutdown = false ; public KeepAliveAgent ( int interval , String query ) { super ( "" ) ; this . interval = interval ; this . query = query ; } public void run ( ) { Connection c ; Statement s = null ; while ( ! shutdown ) { try { Thread . sleep ( interval * ) ; } catch ( InterruptedException e ) { if ( shutdown ) break ; } try { if ( log . isDebugEnabled ( ) ) log . debug ( "" + query + "" ) ; c = connection ( ) ; s = c . createStatement ( ) ; s . execute ( query ) ; s . close ( ) ; } catch ( Throwable e ) { log . error ( "" + e . getMessage ( ) ) ; } finally { if ( s != null ) try { s . close ( ) ; } catch ( Exception ignore ) { } } } log . debug ( "" ) ; } public void shutdown ( ) { log . debug ( "" ) ; shutdown = true ; this . interrupt ( ) ; } } ; private final KeepAliveAgent keepAliveAgent ; public ConnectedDB ( String jdbcURL , String username , String password ) { this ( jdbcURL , username , password , Collections . < String , GenericType > emptyMap ( ) , Database . NO_LIMIT , Database . NO_FETCH_SIZE , null ) ; } public ConnectedDB ( String jdbcURL , String username , String password , Map < String , GenericType > columnTypes , int limit , int fetchSize , Properties connectionProperties ) { this . jdbcURL = jdbcURL ; this . username = username ; this . password = password ; this . limit = limit ; this . fetchSize = fetchSize ; this . connectionProperties = connectionProperties ; for ( String columnName : columnTypes . keySet ( ) ) { overriddenColumnTypes . put ( SQL . parseAttribute ( columnName ) , columnTypes . get ( columnName ) ) ; } if ( connectionProperties != null && connectionProperties . containsKey ( KEEP_ALIVE_PROPERTY ) ) { int interval = DEFAULT_KEEP_ALIVE_INTERVAL ; String query = DEFAULT_KEEP_ALIVE_QUERY ; try { interval = new Integer ( ( String ) connectionProperties . get ( KEEP_ALIVE_PROPERTY ) ) . intValue ( ) ; if ( interval <= ) interval = DEFAULT_KEEP_ALIVE_INTERVAL ; } catch ( NumberFormatException ignore ) { } if ( connectionProperties . containsKey ( KEEP_ALIVE_QUERY_PROPERTY ) ) query = connectionProperties . getProperty ( KEEP_ALIVE_QUERY_PROPERTY ) ; this . keepAliveAgent = new KeepAliveAgent ( interval , query ) ; this . keepAliveAgent . start ( ) ; log . debug ( "" + interval + "" + query + "" ) ; } else this . keepAliveAgent = null ; } public String getJdbcURL ( ) { return jdbcURL ; } public String getUsername ( ) { return username ; } public String getPassword ( ) { return password ; } public Connection connection ( ) { if ( this . connection == null ) { connect ( ) ; } return this . connection ; } public int limit ( ) { return this . limit ; } public void setDefaultFetchSize ( int value ) { defaultFetchSize = value ; } public int fetchSize ( ) { if ( fetchSize == Database . NO_FETCH_SIZE ) { if ( vendorIs ( Vendor . MySQL ) ) { return Integer . MIN_VALUE ; } return defaultFetchSize ; } return fetchSize ; } private void connect ( ) { if ( jdbcURL != null && ! jdbcURL . toLowerCase ( ) . startsWith ( "" ) ) { throw new D2RQException ( "" + jdbcURL , D2RQException . D2RQ_DB_CONNECTION_FAILED ) ; } try { log . info ( "" + jdbcURL ) ; this . connection = DriverManager . getConnection ( this . jdbcURL , getConnectionProperties ( ) ) ; } catch ( SQLException ex ) { throw new D2RQException ( "" + jdbcURL + "" + "" + username + "" + ex . getMessage ( ) , D2RQException . D2RQ_DB_CONNECTION_FAILED ) ; } try { vendor ( ) . initializeConnection ( connection ) ; } catch ( SQLException ex ) { throw new D2RQException ( "" + ex . getMessage ( ) , D2RQException . D2RQ_DB_CONNECTION_FAILED ) ; } } private Properties getConnectionProperties ( ) { Properties result = ( connectionProperties == null ) ? new Properties ( ) : ( Properties ) connectionProperties . clone ( ) ; if ( username != null ) { result . setProperty ( "" , username ) ; } if ( password != null ) { result . setProperty ( "" , password ) ; } if ( this . jdbcURL . contains ( "" ) ) { result . setProperty ( "" , "" ) ; result . setProperty ( "" , "" ) ; } return result ; } public DatabaseSchemaInspector schemaInspector ( ) { if ( schemaInspector == null && jdbcURL != null ) { schemaInspector = new DatabaseSchemaInspector ( this ) ; } return this . schemaInspector ; } public DataType columnType ( Attribute column ) { if ( ! cachedColumnTypes . containsKey ( column ) ) { if ( overriddenColumnTypes . containsKey ( column ) ) { cachedColumnTypes . put ( column , overriddenColumnTypes . get ( column ) . dataTypeFor ( vendor ( ) ) ) ; } else if ( schemaInspector ( ) == null ) { cachedColumnTypes . put ( column , GenericType . CHARACTER . dataTypeFor ( vendor ( ) ) ) ; } else { cachedColumnTypes . put ( column , schemaInspector ( ) . columnType ( column ) ) ; } } return cachedColumnTypes . get ( column ) ; } public boolean isNullable ( Attribute column ) { if ( ! cachedColumnNullability . containsKey ( column ) ) { cachedColumnNullability . put ( column , schemaInspector ( ) == null ? true : schemaInspector ( ) . isNullable ( column ) ) ; } return cachedColumnNullability . get ( column ) ; } public boolean vendorIs ( Vendor vendor ) { return this . vendor . equals ( vendor ) ; } public Vendor vendor ( ) { ensureVendorInitialized ( ) ; return vendor ; } protected String getDatabaseProductType ( ) throws SQLException { return connection ( ) . getMetaData ( ) . getDatabaseProductName ( ) ; } private void ensureVendorInitialized ( ) { if ( vendor != null ) return ; try { String productName = getDatabaseProductType ( ) ; log . info ( "" + productName ) ; productName = productName . toLowerCase ( ) ; if ( productName . indexOf ( "" ) >= ) { vendor = Vendor . MySQL ; } else if ( productName . indexOf ( "" ) >= ) { vendor = Vendor . PostgreSQL ; } else if ( productName . indexOf ( "" ) >= ) { vendor = Vendor . InterbaseOrFirebird ; } else if ( productName . indexOf ( "" ) >= ) { this . vendor = Vendor . Oracle ; } else if ( productName . indexOf ( "" ) >= ) { this . vendor = Vendor . SQLServer ; } else if ( productName . indexOf ( "" ) >= ) { this . vendor = Vendor . MSAccess ; } else if ( productName . indexOf ( "" ) >= ) { this . vendor = Vendor . HSQLDB ; } else { this . vendor = Vendor . SQL92 ; } log . info ( "" + vendor . getClass ( ) . getName ( ) ) ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex ) ; } } public boolean areCompatibleFormats ( Attribute column1 , Attribute column2 ) { return ! isZerofillColumn ( column1 ) && ! isZerofillColumn ( column2 ) ; } private boolean isZerofillColumn ( Attribute column ) { if ( ! vendorIs ( Vendor . MySQL ) ) return false ; if ( ! zerofillCache . containsKey ( column ) ) { zerofillCache . put ( column , schemaInspector ( ) . isZerofillColumn ( column ) ) ; } return zerofillCache . get ( column ) ; } public Map < String , List < String > > getUniqueKeyColumns ( RelationName tableName ) { if ( ! uniqueIndexCache . containsKey ( tableName ) && schemaInspector ( ) != null ) uniqueIndexCache . put ( tableName , schemaInspector ( ) . uniqueColumns ( tableName ) ) ; return uniqueIndexCache . get ( tableName ) ; } public boolean lowerCaseTableNames ( ) { Connection c = connection ( ) ; if ( c instanceof com . mysql . jdbc . ConnectionImpl ) return ( ( com . mysql . jdbc . ConnectionImpl ) c ) . lowerCaseTableNames ( ) ; else return false ; } public void close ( ) { if ( keepAliveAgent != null ) keepAliveAgent . shutdown ( ) ; if ( connection != null ) try { log . info ( "" + jdbcURL ) ; this . connection . close ( ) ; } catch ( SQLException ex ) { throw new D2RQException ( ex ) ; } } public boolean equals ( Object otherObject ) { if ( ! ( otherObject instanceof ConnectedDB ) ) { return false ; } ConnectedDB other = ( ConnectedDB ) otherObject ; return this . jdbcURL . equals ( other . jdbcURL ) ; } public int hashCode ( ) { return this . jdbcURL . hashCode ( ) ; } public static void registerJDBCDriverIfPresent ( String driverClassName ) { if ( driverClassName == null ) return ; try { Class . forName ( driverClassName ) ; } catch ( ClassNotFoundException ex ) { } } public static String guessJDBCDriverClass ( String jdbcURL ) { try { return DriverManager . getDriver ( jdbcURL ) . getClass ( ) . getName ( ) ; } catch ( SQLException ex ) { return null ; } } public static void registerJDBCDriver ( String driverClassName ) { if ( driverClassName == null ) return ; try { Class . forName ( driverClassName ) ; } catch ( ClassNotFoundException ex ) { throw new D2RQException ( "" + driverClassName , D2RQException . DATABASE_JDBCDRIVER_CLASS_NOT_FOUND ) ; } } } package de . fuberlin . wiwiss . d2rq . sql ; import java . util . regex . Pattern ; public interface Quoter { public abstract String quote ( String s ) ; public static class PatternDoublingQuoter implements Quoter { private final Pattern pattern ; private final String quote ; public PatternDoublingQuoter ( Pattern pattern , String quote ) { this . pattern = pattern ; this . quote = quote ; } public String quote ( String s ) { return quote + pattern . matcher ( s ) . replaceAll ( "" ) + quote ; } } ; } package de . fuberlin . wiwiss . d2rq . sql ; import java . sql . Connection ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . List ; import java . util . NoSuchElementException ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . query . QueryCancelledException ; import com . hp . hpl . jena . util . iterator . ClosableIterator ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . map . Database ; public class SQLIterator implements ClosableIterator < ResultRow > { private final static Log log = LogFactory . getLog ( SQLIterator . class ) ; private String sql ; private List < ProjectionSpec > columns ; private ConnectedDB database ; private volatile Statement statement = null ; private ResultSet resultSet = null ; private ResultRow prefetchedRow = null ; private int numCols = ; private boolean queryExecuted = false ; private boolean explicitlyClosed = false ; private volatile boolean cancelled = false ; public SQLIterator ( String sql , List < ProjectionSpec > columns , ConnectedDB db ) { this . sql = sql ; this . columns = columns ; this . database = db ; } public boolean hasNext ( ) { if ( cancelled ) { throw new QueryCancelledException ( ) ; } if ( explicitlyClosed ) { return false ; } if ( prefetchedRow == null ) { ensureQueryExecuted ( ) ; tryFetchNextRow ( ) ; } return prefetchedRow != null ; } public ResultRow next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } ResultRow result = this . prefetchedRow ; this . prefetchedRow = null ; return result ; } public ResultRow nextRow ( ) { return next ( ) ; } private synchronized void tryFetchNextRow ( ) { if ( this . resultSet == null ) { this . prefetchedRow = null ; return ; } try { if ( ! this . resultSet . next ( ) ) { this . resultSet . close ( ) ; this . resultSet = null ; this . prefetchedRow = null ; return ; } BeanCounter . totalNumberOfReturnedRows ++ ; BeanCounter . totalNumberOfReturnedFields += this . numCols ; prefetchedRow = ResultRowMap . fromResultSet ( resultSet , columns , database ) ; } catch ( SQLException ex ) { throw new D2RQException ( ex ) ; } } public void close ( ) { if ( explicitlyClosed ) return ; log . debug ( "" ) ; explicitlyClosed = true ; if ( this . resultSet != null ) { try { this . resultSet . close ( ) ; } catch ( SQLException ex ) { throw new D2RQException ( ex . getMessage ( ) + "" + this . sql ) ; } } if ( this . statement != null ) { try { this . statement . close ( ) ; } catch ( SQLException ex ) { throw new D2RQException ( ex . getMessage ( ) + "" + this . sql ) ; } } } public synchronized void cancel ( ) { cancelled = true ; if ( statement != null ) { try { statement . cancel ( ) ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } } } public void remove ( ) { throw new RuntimeException ( "" ) ; } private void ensureQueryExecuted ( ) { if ( this . queryExecuted ) { return ; } this . queryExecuted = true ; log . info ( sql ) ; BeanCounter . totalNumberOfExecutedSQLQueries ++ ; try { Connection con = this . database . connection ( ) ; this . statement = con . createStatement ( ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY ) ; if ( database . fetchSize ( ) != Database . NO_FETCH_SIZE ) { try { this . statement . setFetchSize ( database . fetchSize ( ) ) ; } catch ( SQLException e ) { } } this . resultSet = this . statement . executeQuery ( this . sql ) ; log . debug ( "" ) ; this . numCols = this . resultSet . getMetaData ( ) . getColumnCount ( ) ; } catch ( SQLException ex ) { if ( cancelled ) { log . debug ( "" , ex ) ; throw new QueryCancelledException ( ) ; } throw new D2RQException ( ex . getMessage ( ) + "" + this . sql ) ; } } } package de . fuberlin . wiwiss . d2rq . sql ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import d2rq . d2r_query ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . expr . Conjunction ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; public class SelectStatementBuilder { private static final Log log = LogFactory . getLog ( d2r_query . class ) ; private ConnectedDB database ; private List < ProjectionSpec > selectSpecs = new ArrayList < ProjectionSpec > ( ) ; private List < Expression > conditions = new ArrayList < Expression > ( ) ; private Expression cachedCondition = null ; private boolean eliminateDuplicates = false ; private AliasMap aliases = AliasMap . NO_ALIASES ; private Collection < RelationName > mentionedTables = new HashSet < RelationName > ( ) ; private List < OrderSpec > orderSpecs ; private int limit ; public SelectStatementBuilder ( Relation relation ) { if ( relation . isTrivial ( ) ) { throw new IllegalArgumentException ( "" ) ; } if ( relation . equals ( Relation . EMPTY ) ) { throw new IllegalArgumentException ( "" ) ; } database = relation . database ( ) ; this . limit = Relation . combineLimits ( relation . limit ( ) , database . limit ( ) ) ; this . orderSpecs = relation . orderSpecs ( ) ; this . aliases = this . aliases . applyTo ( relation . aliases ( ) ) ; for ( Join join : relation . joinConditions ( ) ) { for ( Attribute attribute1 : join . attributes1 ( ) ) { Attribute attribute2 = join . equalAttribute ( attribute1 ) ; addCondition ( Equality . createAttributeEquality ( attribute1 , attribute2 ) ) ; } } addCondition ( relation . condition ( ) ) ; addCondition ( relation . softCondition ( ) ) ; for ( ProjectionSpec projection : relation . projections ( ) ) { addSelectSpec ( projection ) ; } eliminateDuplicates = ! relation . isUnique ( ) ; addCondition ( database . vendor ( ) . getRowNumLimitAsExpression ( limit ) ) ; addMentionedTablesFromConditions ( ) ; if ( eliminateDuplicates ) { for ( ProjectionSpec projection : selectSpecs ) { for ( Attribute column : projection . requiredAttributes ( ) ) { if ( ! database . columnType ( aliases . originalOf ( column ) ) . supportsDistinct ( ) ) { log . info ( "" + relation ) ; throw new D2RQException ( "" + "" + database . columnType ( column ) + "" + "" , D2RQException . DATATYPE_DOES_NOT_SUPPORT_DISTINCT ) ; } } } } } private Expression condition ( ) { if ( this . cachedCondition == null ) { this . cachedCondition = Conjunction . create ( this . conditions ) ; } return this . cachedCondition ; } private void addMentionedTablesFromConditions ( ) { for ( Attribute column : condition ( ) . attributes ( ) ) { this . mentionedTables . add ( column . relationName ( ) ) ; } } public String getSQLStatement ( ) { StringBuffer result = new StringBuffer ( "" ) ; if ( this . eliminateDuplicates ) { result . append ( "" ) ; } String s = database . vendor ( ) . getRowNumLimitAsSelectModifier ( limit ) ; if ( ! "" . equals ( s ) ) { result . append ( s ) ; result . append ( "" ) ; } Iterator < ProjectionSpec > it = this . selectSpecs . iterator ( ) ; if ( ! it . hasNext ( ) ) { result . append ( "" ) ; } while ( it . hasNext ( ) ) { ProjectionSpec projection = it . next ( ) ; result . append ( projection . toSQL ( database , aliases ) ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; Iterator < RelationName > tableIt = mentionedTables . iterator ( ) ; while ( tableIt . hasNext ( ) ) { RelationName tableName = tableIt . next ( ) ; if ( this . aliases . isAlias ( tableName ) ) { result . append ( database . vendor ( ) . getRelationNameAliasExpression ( aliases . originalOf ( tableName ) , tableName ) ) ; } else { result . append ( database . vendor ( ) . quoteRelationName ( tableName ) ) ; } if ( tableIt . hasNext ( ) ) { result . append ( "" ) ; } } if ( ! condition ( ) . isTrue ( ) ) { result . append ( "" ) ; result . append ( condition ( ) . toSQL ( this . database , this . aliases ) ) ; } Iterator < OrderSpec > orderIt = orderSpecs . iterator ( ) ; if ( orderIt . hasNext ( ) ) { result . append ( "" ) ; } while ( orderIt . hasNext ( ) ) { result . append ( orderIt . next ( ) . toSQL ( database , aliases ) ) ; if ( orderIt . hasNext ( ) ) { result . append ( "" ) ; } } s = database . vendor ( ) . getRowNumLimitAsQueryAppendage ( limit ) ; if ( ! "" . equals ( s ) ) { result . append ( "" ) ; result . append ( s ) ; } return result . toString ( ) ; } public List < ProjectionSpec > getColumnSpecs ( ) { return this . selectSpecs ; } private void addSelectSpec ( ProjectionSpec projection ) { if ( this . selectSpecs . contains ( projection ) ) { return ; } for ( Attribute attribute : projection . requiredAttributes ( ) ) { this . mentionedTables . add ( attribute . relationName ( ) ) ; } this . selectSpecs . add ( projection ) ; } private void addCondition ( Expression condition ) { this . conditions . add ( condition ) ; this . cachedCondition = null ; } } package de . fuberlin . wiwiss . d2rq . sql ; public class BeanCounter implements Cloneable { public static int totalNumberOfExecutedSQLQueries = ; public static int totalNumberOfReturnedRows = ; public static int totalNumberOfReturnedFields = ; public int numberOfExecutedSQLQueries = ; public int numberOfReturnedRows = ; public int numberOfReturnedFields = ; public long timeMillis ; public void update ( ) { numberOfExecutedSQLQueries = totalNumberOfExecutedSQLQueries ; numberOfReturnedRows = totalNumberOfReturnedRows ; numberOfReturnedFields = totalNumberOfReturnedFields ; timeMillis = System . currentTimeMillis ( ) ; } public void subtract ( BeanCounter minus ) { numberOfExecutedSQLQueries -= minus . numberOfExecutedSQLQueries ; numberOfReturnedRows -= minus . numberOfReturnedRows ; numberOfReturnedFields -= minus . numberOfReturnedFields ; timeMillis -= minus . timeMillis ; } public void div ( int n ) { numberOfExecutedSQLQueries /= n ; numberOfReturnedRows /= n ; numberOfReturnedFields /= n ; timeMillis /= n ; } public BeanCounter ( ) { } public Object clone ( ) { try { return super . clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new RuntimeException ( e ) ; } } public static BeanCounter instance ( ) { BeanCounter inst = new BeanCounter ( ) ; inst . update ( ) ; return inst ; } public static BeanCounter instanceMinus ( BeanCounter minus ) { BeanCounter inst = instance ( ) ; inst . subtract ( minus ) ; return inst ; } public BeanCounter minus ( BeanCounter minus ) { BeanCounter clone = ( BeanCounter ) clone ( ) ; clone . subtract ( minus ) ; return clone ; } public String sqlInfoString ( ) { return "" + numberOfExecutedSQLQueries + "" + numberOfReturnedRows + "" + numberOfReturnedFields ; } public String sqlPerformanceString ( ) { return "" + timeMillis + "" + sqlInfoString ( ) + "" ; } } package de . fuberlin . wiwiss . d2rq . sql ; import java . sql . ResultSet ; import java . sql . ResultSetMetaData ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; public class ResultRowMap implements ResultRow { public static ResultRowMap fromResultSet ( ResultSet resultSet , List < ProjectionSpec > projectionSpecs , ConnectedDB database ) throws SQLException { Map < ProjectionSpec , String > result = new HashMap < ProjectionSpec , String > ( ) ; ResultSetMetaData metaData = resultSet . getMetaData ( ) ; for ( int i = ; i < projectionSpecs . size ( ) ; i ++ ) { ProjectionSpec key = projectionSpecs . get ( i ) ; int jdbcType = metaData == null ? Integer . MIN_VALUE : metaData . getColumnType ( i + ) ; String name = metaData == null ? "" : metaData . getColumnTypeName ( i + ) ; result . put ( key , database . vendor ( ) . getDataType ( jdbcType , name . toUpperCase ( ) , - ) . value ( resultSet , i + ) ) ; } return new ResultRowMap ( result ) ; } private final Map < ProjectionSpec , String > projectionsToValues ; public ResultRowMap ( Map < ProjectionSpec , String > projectionsToValues ) { this . projectionsToValues = projectionsToValues ; } public String get ( ProjectionSpec projection ) { return ( String ) this . projectionsToValues . get ( projection ) ; } public String toString ( ) { List < ProjectionSpec > columns = new ArrayList < ProjectionSpec > ( this . projectionsToValues . keySet ( ) ) ; Collections . sort ( columns ) ; StringBuffer result = new StringBuffer ( "" ) ; Iterator < ProjectionSpec > it = columns . iterator ( ) ; while ( it . hasNext ( ) ) { ProjectionSpec projection = ( ProjectionSpec ) it . next ( ) ; result . append ( projection . toString ( ) ) ; result . append ( "" ) ; result . append ( this . projectionsToValues . get ( projection ) ) ; result . append ( "" ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . math . BigDecimal ; import java . sql . ResultSet ; import java . sql . SQLException ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLApproximateNumeric extends DataType { public SQLApproximateNumeric ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public String rdfType ( ) { return "" ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { double d = resultSet . getDouble ( column ) ; if ( resultSet . wasNull ( ) ) return null ; if ( Double . isNaN ( d ) ) { return "" ; } else if ( Double . isInfinite ( d ) ) { return d > ? "" : "" ; } else if ( d == Double . NEGATIVE_INFINITY ) { return "" ; } else { String dd = Double . toString ( d ) ; if ( ! dd . contains ( "" ) ) { dd += "" ; } return dd ; } } @ Override public String toSQLLiteral ( String value ) { try { return new BigDecimal ( value ) . toString ( ) ; } catch ( NumberFormatException ex ) { try { double d = Double . parseDouble ( value ) ; if ( Double . isNaN ( d ) || Double . isInfinite ( d ) ) { return "" ; } return Double . toString ( d ) ; } catch ( NumberFormatException ex2 ) { log . warn ( "" + value + "" ) ; return "" ; } } } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLTime extends DataType { private final static Pattern TIME_PATTERN = Pattern . compile ( "" ) ; public SQLTime ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public String rdfType ( ) { return "" ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { String time = resultSet . getString ( column ) ; if ( time == null || resultSet . wasNull ( ) ) return null ; Matcher m = TIME_PATTERN . matcher ( time ) ; if ( m . matches ( ) ) { if ( time . substring ( , ) . equals ( "" ) ) { time = '' + time ; } int tzStart = Math . max ( time . indexOf ( '' ) , time . indexOf ( '' ) ) ; if ( tzStart > && time . substring ( tzStart + , tzStart + ) . equals ( "" ) ) { time = time . substring ( , tzStart + ) + '' + time . substring ( tzStart + ) ; } int fractionStart = time . indexOf ( '' ) ; if ( fractionStart > ) { int fractionIndex = fractionStart ; while ( fractionIndex + < time . length ( ) && Character . isDigit ( time . charAt ( fractionIndex + ) ) ) { fractionIndex ++ ; } while ( time . charAt ( fractionIndex ) == '' || time . charAt ( fractionIndex ) == '' ) { time = time . substring ( , fractionIndex ) + time . substring ( fractionIndex + ) ; fractionIndex -- ; if ( fractionIndex < fractionStart ) break ; } } time = time . replace ( "" , "" ) . replace ( "" , "" ) ; return time ; } else { return resultSet . getTime ( column ) . toString ( ) ; } } @ Override public String toSQLLiteral ( String value ) { value = value . replace ( "" , "" ) ; if ( ! TIME_PATTERN . matcher ( value ) . matches ( ) ) { log . warn ( "" + value + "" ) ; return "" ; } return syntax ( ) . quoteTimeLiteral ( value ) ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . sql . ResultSet ; import java . sql . SQLException ; import de . fuberlin . wiwiss . d2rq . D2RQException ; public class UnsupportedDataType extends DataType { private final int jdbcType ; public UnsupportedDataType ( int jdbcType , String name ) { super ( null , name ) ; this . jdbcType = jdbcType ; } @ Override public boolean isUnsupported ( ) { return true ; } @ Override public String rdfType ( ) { return null ; } @ Override public String toSQLLiteral ( String value ) { throw new D2RQException ( "" + value + "" , D2RQException . DATATYPE_UNMAPPABLE ) ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { throw new D2RQException ( "" , D2RQException . DATATYPE_UNMAPPABLE ) ; } @ Override public String toString ( ) { return super . toString ( ) + "" + jdbcType + "" + name ( ) + "" ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Types ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public abstract class DataType { public final static Log log = LogFactory . getLog ( DataType . class ) ; public enum GenericType { CHARACTER ( Types . VARCHAR , "" ) , BINARY ( Types . VARBINARY , "" ) , NUMERIC ( Types . NUMERIC , "" ) , BOOLEAN ( Types . BOOLEAN , "" ) , DATE ( Types . DATE , "" ) , TIME ( Types . TIME , "" ) , TIMESTAMP ( Types . TIMESTAMP , "" ) , INTERVAL ( Types . VARCHAR , "" ) , BIT ( Types . BIT , "" ) ; private final int jdbcType ; private final String name ; GenericType ( int jdbcType , String name ) { this . jdbcType = jdbcType ; this . name = name . toUpperCase ( ) ; } public DataType dataTypeFor ( Vendor vendor ) { return vendor . getDataType ( jdbcType , name , ) ; } } private final Vendor sqlSyntax ; private final String name ; public DataType ( Vendor sqlSyntax , String name ) { this . sqlSyntax = sqlSyntax ; this . name = name ; } public String rdfType ( ) { return "" ; } public boolean isIRISafe ( ) { return false ; } public boolean supportsDistinct ( ) { return true ; } public boolean isUnsupported ( ) { return false ; } public String toSQLLiteral ( String value ) { return sqlSyntax . quoteStringLiteral ( value ) ; } public String value ( ResultSet resultSet , int column ) throws SQLException { return resultSet . getString ( column ) ; } public String valueRegex ( ) { return null ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + name ; } protected Vendor syntax ( ) { return sqlSyntax ; } public String name ( ) { return name ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . math . BigDecimal ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Types ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLExactNumeric extends DataType { private final String rdfType ; public SQLExactNumeric ( Vendor syntax , String name , int jdbcType , boolean unsigned ) { super ( syntax , name ) ; switch ( jdbcType ) { case Types . NUMERIC : rdfType = "" ; break ; case Types . DECIMAL : rdfType = "" ; break ; case Types . TINYINT : rdfType = "" ; break ; case Types . SMALLINT : rdfType = "" ; break ; case Types . INTEGER : rdfType = "" ; break ; case Types . BIGINT : rdfType = "" ; break ; default : rdfType = "" ; } } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public String rdfType ( ) { return rdfType ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { String num = resultSet . getString ( column ) ; if ( resultSet . wasNull ( ) ) return null ; while ( num . contains ( "" ) && ( num . endsWith ( "" ) || num . endsWith ( "" ) ) ) { num = num . substring ( , num . length ( ) - ) ; } return num ; } @ Override public String toSQLLiteral ( String value ) { try { return new BigDecimal ( value ) . toString ( ) ; } catch ( NumberFormatException ex ) { try { double d = Double . parseDouble ( value ) ; if ( Double . isNaN ( d ) || Double . isInfinite ( d ) ) { return "" ; } return Double . toString ( d ) ; } catch ( NumberFormatException ex2 ) { log . warn ( "" + value + "" ) ; return "" ; } } } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . sql . ResultSet ; import java . sql . SQLException ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLBoolean extends DataType { public SQLBoolean ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public String rdfType ( ) { return "" ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { boolean b = resultSet . getBoolean ( column ) ; if ( resultSet . wasNull ( ) ) return null ; return b ? "" : "" ; } @ Override public String toSQLLiteral ( String value ) { if ( "" . equals ( value ) || "" . equals ( value ) ) { return "" ; } if ( "" . equals ( value ) || "" . equals ( value ) ) { return "" ; } log . warn ( "" + value + "" ) ; return "" ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . sql . ResultSet ; import java . sql . SQLException ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLBinary extends DataType { private final boolean supportsDistinct ; public SQLBinary ( Vendor syntax , String name , boolean supportsDistinct ) { super ( syntax , name ) ; this . supportsDistinct = supportsDistinct ; } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public boolean supportsDistinct ( ) { return supportsDistinct ; } @ Override public String rdfType ( ) { return "" ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { byte [ ] bytes = resultSet . getBytes ( column ) ; return resultSet . wasNull ( ) ? null : toHexString ( bytes ) ; } @ Override public String toSQLLiteral ( String value ) { if ( ! SQL . isHexString ( value ) ) { log . warn ( "" + value + "" ) ; return "" ; } return syntax ( ) . quoteBinaryLiteral ( value ) ; } private static final char [ ] HEX_DIGITS = { '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' } ; private static String toHexString ( byte [ ] bytes ) { if ( bytes == null ) return null ; final StringBuilder hex = new StringBuilder ( * bytes . length ) ; for ( final byte b : bytes ) { hex . append ( HEX_DIGITS [ ( b & ) > > ] ) ; hex . append ( HEX_DIGITS [ b & ] ) ; } return hex . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLTimestamp extends DataType { private final static Pattern TIMESTAMP_PATTERN = Pattern . compile ( "" ) ; public SQLTimestamp ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public String rdfType ( ) { return "" ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { String timestamp = resultSet . getString ( column ) ; if ( timestamp == null || resultSet . wasNull ( ) ) return null ; Matcher m = TIMESTAMP_PATTERN . matcher ( timestamp ) ; if ( m . matches ( ) ) { int yearDigits = timestamp . indexOf ( '' ) ; for ( int j = ; j < - yearDigits ; j ++ ) { timestamp = '' + timestamp ; } timestamp = timestamp . replace ( '' , '' ) ; int timeStart = timestamp . indexOf ( '' ) + ; if ( timestamp . substring ( timeStart + , timeStart + ) . equals ( "" ) ) { timestamp = timestamp . substring ( , timeStart ) + '' + timestamp . substring ( timeStart ) ; } int tzStart = Math . max ( timestamp . indexOf ( '' , timeStart ) , timestamp . indexOf ( '' , timeStart ) ) ; if ( tzStart > && timestamp . substring ( tzStart + , tzStart + ) . equals ( "" ) ) { timestamp = timestamp . substring ( , tzStart + ) + '' + timestamp . substring ( tzStart + ) ; } int fractionStart = timestamp . indexOf ( '' ) ; if ( fractionStart > ) { int fractionIndex = fractionStart ; while ( fractionIndex + < timestamp . length ( ) && Character . isDigit ( timestamp . charAt ( fractionIndex + ) ) ) { fractionIndex ++ ; } while ( timestamp . charAt ( fractionIndex ) == '' || timestamp . charAt ( fractionIndex ) == '' ) { timestamp = timestamp . substring ( , fractionIndex ) + timestamp . substring ( fractionIndex + ) ; fractionIndex -- ; if ( fractionIndex < fractionStart ) break ; } } timestamp = timestamp . replace ( "" , "" ) . replace ( "" , "" ) ; return timestamp ; } else { return resultSet . getTimestamp ( column ) . toString ( ) . replace ( '' , '' ) ; } } @ Override public String toSQLLiteral ( String value ) { value = value . replace ( '' , '' ) . replace ( "" , "" ) ; if ( ! TIMESTAMP_PATTERN . matcher ( value ) . matches ( ) ) { log . warn ( "" + value + "" ) ; return "" ; } return syntax ( ) . quoteTimestampLiteral ( value ) ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLInterval extends DataType { public SQLInterval ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public String toSQLLiteral ( String value ) { return "" ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLBit extends DataType { public SQLBit ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public String toSQLLiteral ( String value ) { if ( ! value . matches ( "" ) ) { log . warn ( "" + value + "" ) ; return "" ; } return "" + syntax ( ) . quoteStringLiteral ( value ) ; } @ Override public String valueRegex ( ) { return "" ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import java . sql . Date ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLDate extends DataType { private final static Pattern DATE_PATTERN = Pattern . compile ( "" ) ; public SQLDate ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public boolean isIRISafe ( ) { return true ; } @ Override public String rdfType ( ) { return "" ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { Date date = resultSet . getDate ( column ) ; if ( date == null || resultSet . wasNull ( ) ) return null ; String s = date . toString ( ) ; int yearDigits = s . indexOf ( '' ) ; for ( int j = ; j < - yearDigits ; j ++ ) { s = '' + s ; } return s ; } @ Override public String toSQLLiteral ( String value ) { if ( ! DATE_PATTERN . matcher ( value ) . matches ( ) ) { log . warn ( "" + value + "" ) ; return "" ; } return syntax ( ) . quoteDateLiteral ( value ) ; } } package de . fuberlin . wiwiss . d2rq . sql . types ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class SQLCharacterString extends DataType { private final boolean supportsDistinct ; public SQLCharacterString ( Vendor syntax , String name , boolean supportsDistinct ) { super ( syntax , name ) ; this . supportsDistinct = supportsDistinct ; } @ Override public boolean supportsDistinct ( ) { return supportsDistinct ; } } package de . fuberlin . wiwiss . d2rq . sql ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . Reader ; import java . io . UnsupportedEncodingException ; import java . net . URI ; import java . sql . Connection ; import java . sql . SQLException ; import java . sql . Statement ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class SQLScriptLoader { private final static Log log = LogFactory . getLog ( SQLScriptLoader . class ) ; public static void loadFile ( File file , Connection conn ) throws FileNotFoundException , SQLException { try { log . info ( "" + file ) ; new SQLScriptLoader ( new InputStreamReader ( new FileInputStream ( file ) , "" ) , conn ) . execute ( ) ; } catch ( UnsupportedEncodingException ex ) { } } public static void loadURI ( URI url , Connection conn ) throws IOException , SQLException { try { log . info ( "" + url + ">" ) ; new SQLScriptLoader ( new InputStreamReader ( url . toURL ( ) . openStream ( ) , "" ) , conn ) . execute ( ) ; } catch ( UnsupportedEncodingException ex ) { } } private final BufferedReader in ; private final Connection conn ; public SQLScriptLoader ( Reader in , Connection conn ) { this . in = new BufferedReader ( in ) ; this . conn = conn ; } public void execute ( ) throws SQLException { int lineNumber = ; int statements = ; Statement stmt = conn . createStatement ( ) ; try { String line ; StringBuilder sql = new StringBuilder ( ) ; while ( ( line = in . readLine ( ) ) != null ) { if ( line . trim ( ) . startsWith ( "" ) ) { } else { if ( line . trim ( ) . endsWith ( "" ) ) { sql . append ( line . substring ( , line . length ( ) - ) ) ; String s = sql . toString ( ) . trim ( ) ; if ( ! "" . equals ( s ) ) { stmt . execute ( s ) ; statements ++ ; } sql = new StringBuilder ( ) ; } else { sql . append ( line ) ; sql . append ( '' ) ; } } lineNumber ++ ; } String s = sql . toString ( ) . trim ( ) ; if ( ! "" . equals ( s ) ) { stmt . execute ( s ) ; } log . info ( "" + ( lineNumber - ) + "" + statements + "" ) ; } catch ( SQLException ex ) { throw new SQLException ( "" + lineNumber + "" + ex . getMessage ( ) , ex ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } finally { stmt . close ( ) ; } } } package de . fuberlin . wiwiss . d2rq . sql . vendor ; import java . sql . Connection ; import java . sql . SQLException ; import java . sql . Statement ; import java . sql . Types ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLApproximateNumeric ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBinary ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLCharacterString ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLInterval ; import de . fuberlin . wiwiss . d2rq . sql . types . UnsupportedDataType ; public class HSQLDB extends SQL92 { public HSQLDB ( ) { super ( true ) ; } @ Override public DataType getDataType ( int jdbcType , String name , int size ) { if ( jdbcType == Types . CLOB || "" . equals ( name ) ) { return new SQLCharacterString ( this , name , false ) ; } if ( jdbcType == Types . BLOB ) { return new SQLBinary ( this , name , false ) ; } if ( jdbcType == Types . VARCHAR && name . startsWith ( "" ) ) { return new SQLInterval ( this , name ) ; } if ( jdbcType == Types . DOUBLE || jdbcType == Types . FLOAT || jdbcType == Types . REAL ) { return new HSQLDBCompatibilityDoubleDataType ( this ) ; } if ( jdbcType == Types . OTHER ) { return new UnsupportedDataType ( jdbcType , name ) ; } return super . getDataType ( jdbcType , name , size ) ; } @ Override public void initializeConnection ( Connection connection ) throws SQLException { Statement stmt = connection . createStatement ( ) ; try { stmt . execute ( "" ) ; } finally { stmt . close ( ) ; } } public static class HSQLDBCompatibilityDoubleDataType extends SQLApproximateNumeric { public HSQLDBCompatibilityDoubleDataType ( Vendor syntax ) { super ( syntax , "" ) ; } public String toSQLLiteral ( String value ) { if ( "" . equals ( value ) ) { return "" ; } else if ( "" . equals ( value ) ) { return "" ; } else if ( "" . equals ( value ) ) { return "" ; } return super . toSQLLiteral ( value ) ; } } } package de . fuberlin . wiwiss . d2rq . sql . vendor ; import java . sql . Connection ; import java . sql . SQLException ; import java . util . Properties ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; public interface Vendor { public final static Vendor SQL92 = new SQL92 ( true ) ; public final static Vendor MySQL = new MySQL ( ) ; public final static Vendor PostgreSQL = new PostgreSQL ( ) ; public final static Vendor InterbaseOrFirebird = new SQL92 ( false ) ; public final static Vendor Oracle = new Oracle ( ) ; public final static Vendor SQLServer = new SQLServer ( ) ; public final static Vendor MSAccess = new SQLServer ( ) ; public final static Vendor HSQLDB = new HSQLDB ( ) ; String getConcatenationExpression ( String [ ] sqlFragments ) ; String getRelationNameAliasExpression ( RelationName relationName , RelationName aliasName ) ; String quoteAttribute ( Attribute attribute ) ; String quoteRelationName ( RelationName relationName ) ; String quoteIdentifier ( String identifier ) ; String quoteStringLiteral ( String s ) ; String quoteBinaryLiteral ( String hexString ) ; String quoteDateLiteral ( String date ) ; String quoteTimeLiteral ( String time ) ; String quoteTimestampLiteral ( String timestamp ) ; Expression getRowNumLimitAsExpression ( int limit ) ; String getRowNumLimitAsSelectModifier ( int limit ) ; String getRowNumLimitAsQueryAppendage ( int limit ) ; Properties getDefaultConnectionProperties ( ) ; DataType getDataType ( int jdbcType , String name , int size ) ; Expression booleanExpressionToSimpleExpression ( Expression expression ) ; boolean isIgnoredTable ( String schema , String table ) ; void initializeConnection ( Connection connection ) throws SQLException ; } package de . fuberlin . wiwiss . d2rq . sql . vendor ; import java . math . BigInteger ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Types ; import java . util . Properties ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . sql . Quoter ; import de . fuberlin . wiwiss . d2rq . sql . Quoter . PatternDoublingQuoter ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBit ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBoolean ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLDate ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLExactNumeric ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLTime ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLTimestamp ; public class MySQL extends SQL92 { public MySQL ( ) { super ( true ) ; } @ Override public String getConcatenationExpression ( String [ ] sqlFragments ) { StringBuffer result = new StringBuffer ( "" ) ; for ( int i = ; i < sqlFragments . length ; i ++ ) { if ( i > ) { result . append ( "" ) ; } result . append ( sqlFragments [ i ] ) ; } result . append ( "" ) ; return result . toString ( ) ; } @ Override public String quoteIdentifier ( String identifier ) { return backtickEscaper . quote ( identifier ) ; } private final static Quoter backtickEscaper = new PatternDoublingQuoter ( Pattern . compile ( "" ) , "" ) ; @ Override public String quoteStringLiteral ( String s ) { return singleQuoteEscaperWithBackslash . quote ( s ) ; } private final static Quoter singleQuoteEscaperWithBackslash = new PatternDoublingQuoter ( Pattern . compile ( "" ) , "" ) ; @ Override public Properties getDefaultConnectionProperties ( ) { Properties result = new Properties ( ) ; result . setProperty ( "" , "" ) ; result . setProperty ( "" , "" ) ; return result ; } @ Override public DataType getDataType ( int jdbcType , String name , int size ) { if ( jdbcType == Types . VARBINARY && "" . equals ( name ) ) { return new MySQLCompatibilityBitDataType ( this ) ; } if ( jdbcType == Types . BIT && ( "" . equals ( name ) || size == ) ) { return new SQLBoolean ( this , name ) ; } if ( name . contains ( "" ) ) { return new SQLExactNumeric ( this , name , jdbcType , true ) ; } if ( jdbcType == Types . DATE ) { return new MySQLCompatibilityDateDataType ( this ) ; } if ( jdbcType == Types . TIME ) { return new MySQLCompatibilityTimeDataType ( this ) ; } if ( jdbcType == Types . TIMESTAMP ) { return new MySQLCompatibilityTimestampDataType ( this ) ; } return super . getDataType ( jdbcType , name , size ) ; } public static class MySQLCompatibilityBitDataType extends SQLBit { public MySQLCompatibilityBitDataType ( Vendor syntax ) { super ( syntax , "" ) ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { String value = resultSet . getString ( column ) ; if ( resultSet . wasNull ( ) ) return null ; try { return new BigInteger ( value ) . toString ( ) ; } catch ( NumberFormatException ex ) { log . warn ( "" + value + "" ) ; return null ; } } } public static class MySQLCompatibilityDateDataType extends SQLDate { public MySQLCompatibilityDateDataType ( Vendor syntax ) { super ( syntax , "" ) ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { try { return super . value ( resultSet , column ) ; } catch ( SQLException ex ) { return null ; } } } public static class MySQLCompatibilityTimeDataType extends SQLTime { public MySQLCompatibilityTimeDataType ( Vendor syntax ) { super ( syntax , "" ) ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { try { return super . value ( resultSet , column ) ; } catch ( SQLException ex ) { log . warn ( ex ) ; return null ; } } } public static class MySQLCompatibilityTimestampDataType extends SQLTimestamp { public MySQLCompatibilityTimestampDataType ( Vendor syntax ) { super ( syntax , "" ) ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { try { return super . value ( resultSet , column ) ; } catch ( SQLException ex ) { return null ; } } } } package de . fuberlin . wiwiss . d2rq . sql . vendor ; import java . sql . Connection ; import java . sql . SQLException ; import java . sql . Types ; import java . util . Properties ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . sql . Quoter ; import de . fuberlin . wiwiss . d2rq . sql . Quoter . PatternDoublingQuoter ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLApproximateNumeric ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBinary ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBit ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBoolean ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLCharacterString ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLDate ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLExactNumeric ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLTime ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLTimestamp ; import de . fuberlin . wiwiss . d2rq . sql . types . UnsupportedDataType ; public class SQL92 implements Vendor { private boolean useAS ; public SQL92 ( boolean useAS ) { this . useAS = useAS ; } public String getConcatenationExpression ( String [ ] sqlFragments ) { StringBuffer result = new StringBuffer ( ) ; for ( int i = ; i < sqlFragments . length ; i ++ ) { if ( i > ) { result . append ( "" ) ; } result . append ( sqlFragments [ i ] ) ; } return result . toString ( ) ; } public String getRelationNameAliasExpression ( RelationName relationName , RelationName aliasName ) { return quoteRelationName ( relationName ) + ( useAS ? "" : "" ) + quoteRelationName ( aliasName ) ; } public String quoteAttribute ( Attribute attribute ) { return quoteRelationName ( attribute . relationName ( ) ) + "" + quoteIdentifier ( attribute . attributeName ( ) ) ; } public String quoteRelationName ( RelationName relationName ) { if ( relationName . schemaName ( ) == null ) { return quoteIdentifier ( relationName . tableName ( ) ) ; } return quoteIdentifier ( relationName . schemaName ( ) ) + "" + quoteIdentifier ( relationName . tableName ( ) ) ; } public String quoteIdentifier ( String identifier ) { return doubleQuoteEscaper . quote ( identifier ) ; } private final static Quoter doubleQuoteEscaper = new PatternDoublingQuoter ( Pattern . compile ( "" ) , "" ) ; public String quoteStringLiteral ( String s ) { return singleQuoteEscaper . quote ( s ) ; } private final static Quoter singleQuoteEscaper = new PatternDoublingQuoter ( Pattern . compile ( "" ) , "" ) ; public String quoteBinaryLiteral ( String hexString ) { return "" + quoteStringLiteral ( hexString ) ; } public String quoteDateLiteral ( String date ) { return "" + quoteStringLiteral ( date ) ; } public String quoteTimeLiteral ( String time ) { return "" + quoteStringLiteral ( time ) ; } public String quoteTimestampLiteral ( String timestamp ) { return "" + quoteStringLiteral ( timestamp ) ; } public Expression getRowNumLimitAsExpression ( int limit ) { return Expression . TRUE ; } public String getRowNumLimitAsQueryAppendage ( int limit ) { if ( limit == Database . NO_LIMIT ) return "" ; return "" + limit ; } public String getRowNumLimitAsSelectModifier ( int limit ) { return "" ; } public Properties getDefaultConnectionProperties ( ) { return new Properties ( ) ; } public DataType getDataType ( int jdbcType , String name , int size ) { if ( "" . equals ( name ) || "" . equals ( name ) || "" . equals ( name ) ) { return new SQLCharacterString ( this , name , true ) ; } switch ( jdbcType ) { case Types . CHAR : case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CLOB : return new SQLCharacterString ( this , name , true ) ; case Types . BOOLEAN : return new SQLBoolean ( this , name ) ; case Types . BINARY : case Types . VARBINARY : case Types . LONGVARBINARY : case Types . BLOB : return new SQLBinary ( this , name , true ) ; case Types . BIT : return new SQLBit ( this , name ) ; case Types . NUMERIC : case Types . DECIMAL : case Types . TINYINT : case Types . SMALLINT : case Types . INTEGER : case Types . BIGINT : return new SQLExactNumeric ( this , name , jdbcType , false ) ; case Types . REAL : case Types . FLOAT : case Types . DOUBLE : return new SQLApproximateNumeric ( this , name ) ; case Types . DATE : return new SQLDate ( this , name ) ; case Types . TIME : return new SQLTime ( this , name ) ; case Types . TIMESTAMP : return new SQLTimestamp ( this , name ) ; case Types . ARRAY : case Types . JAVA_OBJECT : return new UnsupportedDataType ( jdbcType , name ) ; case Types . DATALINK : case Types . DISTINCT : case Types . NULL : case Types . OTHER : case Types . REF : } return null ; } public Expression booleanExpressionToSimpleExpression ( Expression expression ) { return expression ; } public boolean isIgnoredTable ( String schema , String table ) { return false ; } public void initializeConnection ( Connection connection ) throws SQLException { } } package de . fuberlin . wiwiss . d2rq . sql . vendor ; import java . sql . Connection ; import java . sql . SQLException ; import java . sql . Types ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLCharacterString ; public class PostgreSQL extends SQL92 { public PostgreSQL ( ) { super ( true ) ; } @ Override public String quoteBinaryLiteral ( String hexString ) { if ( ! SQL . isHexString ( hexString ) ) { throw new IllegalArgumentException ( "" + hexString + "" ) ; } return "" + hexString + "" ; } @ Override public DataType getDataType ( int jdbcType , String name , int size ) { DataType standard = super . getDataType ( jdbcType , name , size ) ; if ( standard != null ) return standard ; if ( "" . equals ( name ) ) { return new SQLCharacterString ( this , name , true ) ; } if ( ( jdbcType == Types . OTHER ) && ( "" . equals ( name ) ) ) { return new SQLCharacterString ( this , name , true ) ; } return null ; } @ Override public boolean isIgnoredTable ( String schema , String table ) { return "" . equals ( schema ) || "" . equals ( schema ) ; } @ Override public void initializeConnection ( Connection connection ) throws SQLException { connection . setAutoCommit ( false ) ; } } package de . fuberlin . wiwiss . d2rq . sql . vendor ; import java . lang . reflect . Method ; import java . sql . Connection ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . sql . Timestamp ; import java . sql . Types ; import java . text . DateFormat ; import java . text . SimpleDateFormat ; import java . util . Arrays ; import java . util . Calendar ; import java . util . GregorianCalendar ; import java . util . TimeZone ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . expr . BooleanToIntegerCaseExpression ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . expr . SQLExpression ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLApproximateNumeric ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBinary ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLCharacterString ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLTimestamp ; import de . fuberlin . wiwiss . d2rq . sql . types . UnsupportedDataType ; public class Oracle extends SQL92 { public Oracle ( ) { super ( false ) ; } @ Override public Expression getRowNumLimitAsExpression ( int limit ) { if ( limit == Database . NO_LIMIT ) return Expression . TRUE ; return SQLExpression . create ( "" + limit ) ; } @ Override public String getRowNumLimitAsQueryAppendage ( int limit ) { return "" ; } @ Override public String quoteBinaryLiteral ( String hexString ) { return quoteStringLiteral ( hexString ) ; } @ Override public DataType getDataType ( int jdbcType , String name , int size ) { if ( jdbcType == Types . CLOB || "" . equals ( name ) ) { return new SQLCharacterString ( this , name , false ) ; } if ( jdbcType == Types . BLOB ) { return new SQLBinary ( this , name , false ) ; } DataType standard = super . getDataType ( jdbcType , name , size ) ; if ( standard != null ) return standard ; if ( name . contains ( "" ) || "" . equals ( name ) ) { return new OracleCompatibilityTimeZoneLocalDataType ( this , name ) ; } if ( name . contains ( "" ) || "" . equals ( name ) ) { return new OracleCompatibilityTimeZoneDataType ( this , name ) ; } if ( "" . equals ( name ) || "" . equals ( name ) ) { return new SQLCharacterString ( this , name , true ) ; } if ( "" . equals ( name ) || "" . equals ( name ) ) { return new SQLApproximateNumeric ( this , name ) ; } if ( "" . equals ( name ) ) { return new UnsupportedDataType ( jdbcType , name ) ; } return null ; } @ Override public void initializeConnection ( Connection connection ) throws SQLException { Statement stmt = connection . createStatement ( ) ; try { stmt . execute ( "" ) ; stmt . execute ( "" ) ; setSessionTimeZone ( connection , getTimeZoneForSession ( ) . getID ( ) ) ; } catch ( Exception ex ) { throw new D2RQException ( ex ) ; } finally { stmt . close ( ) ; } } private void setSessionTimeZone ( Connection connection , String timeZoneID ) throws Exception { Class < ? > c = Class . forName ( "" ) ; Method setSessionTimeZone = c . getMethod ( "" , String . class ) ; setSessionTimeZone . invoke ( connection , timeZoneID ) ; } private static TimeZone getTimeZoneForSession ( ) { return TimeZone . getDefault ( ) ; } public Expression booleanExpressionToSimpleExpression ( Expression expression ) { return new BooleanToIntegerCaseExpression ( expression ) ; } @ Override public boolean isIgnoredTable ( String schema , String table ) { if ( Arrays . binarySearch ( IGNORED_SCHEMAS , schema ) >= ) return true ; if ( IGNORED_SCHEMAS_PATTERN . matcher ( schema ) . matches ( ) ) return true ; if ( table . startsWith ( "" ) ) return true ; if ( table . startsWith ( "" ) ) return true ; return false ; } private static final String [ ] IGNORED_SCHEMAS = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private final static Pattern IGNORED_SCHEMAS_PATTERN = Pattern . compile ( "" ) ; public static class OracleCompatibilityTimeZoneLocalDataType extends SQLTimestamp { public OracleCompatibilityTimeZoneLocalDataType ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { Timestamp timestampValue = resultSet . getTimestamp ( column ) ; return formatForSessionTimeZone ( timestampValue ) ; } private static String formatForSessionTimeZone ( Timestamp timestamp ) { Calendar cal = new GregorianCalendar ( ) ; cal . setTime ( timestamp ) ; DateFormat df = new SimpleDateFormat ( "" ) ; df . setTimeZone ( getTimeZoneForSession ( ) ) ; String dateTime = df . format ( cal . getTime ( ) ) ; return dateTime . substring ( , dateTime . length ( ) - ) + "" + dateTime . substring ( dateTime . length ( ) - ) ; } } public static class OracleCompatibilityTimeZoneDataType extends SQLTimestamp { public OracleCompatibilityTimeZoneDataType ( Vendor syntax , String name ) { super ( syntax , name ) ; } @ Override public String value ( ResultSet resultSet , int column ) throws SQLException { try { return super . value ( resultSet , column ) ; } catch ( SQLException ex ) { return null ; } } } } package de . fuberlin . wiwiss . d2rq . sql . vendor ; import java . sql . Types ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBinary ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLBit ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLCharacterString ; import de . fuberlin . wiwiss . d2rq . sql . types . SQLDate ; public class SQLServer extends SQL92 { public SQLServer ( ) { super ( true ) ; } @ Override public String getRowNumLimitAsSelectModifier ( int limit ) { if ( limit == Database . NO_LIMIT ) return "" ; return "" + limit ; } @ Override public String getRowNumLimitAsQueryAppendage ( int limit ) { return "" ; } @ Override public String quoteBinaryLiteral ( String hexString ) { if ( ! SQL . isHexString ( hexString ) ) { throw new IllegalArgumentException ( "" + hexString + "" ) ; } return "" + hexString ; } @ Override public String quoteDateLiteral ( String date ) { return quoteStringLiteral ( date ) ; } @ Override public String quoteTimeLiteral ( String time ) { return quoteStringLiteral ( time ) ; } @ Override public String quoteTimestampLiteral ( String timestamp ) { return quoteStringLiteral ( timestamp ) ; } @ Override public DataType getDataType ( int jdbcType , String name , int size ) { if ( name . equals ( "" ) ) { return new SQLDate ( this , name ) ; } if ( jdbcType == Types . BIT ) { return new SQLServerCompatibilityBitDataType ( this ) ; } if ( jdbcType == Types . CLOB || "" . equals ( name ) ) { return new SQLCharacterString ( this , name , false ) ; } if ( jdbcType == Types . BLOB ) { return new SQLBinary ( this , name , false ) ; } return super . getDataType ( jdbcType , name , size ) ; } @ Override public boolean isIgnoredTable ( String schema , String table ) { return "" . equals ( schema ) || "" . equals ( schema ) || "" . equals ( table ) ; } private static class SQLServerCompatibilityBitDataType extends SQLBit { public SQLServerCompatibilityBitDataType ( Vendor syntax ) { super ( syntax , "" ) ; } public String toSQLLiteral ( String value ) { try { return Integer . parseInt ( value ) == ? "" : "" ; } catch ( NumberFormatException nfex ) { DataType . log . warn ( "" + value + "" ) ; return "" ; } } public String valueRegex ( ) { return "" ; } } } package de . fuberlin . wiwiss . d2rq . sql ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; public interface ResultRow { public static final ResultRow NO_ATTRIBUTES = new ResultRow ( ) { public String get ( ProjectionSpec attribute ) { return null ; } } ; public String get ( ProjectionSpec column ) ; } package de . fuberlin . wiwiss . d2rq ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . sparql . vocabulary . FOAF ; import com . hp . hpl . jena . vocabulary . DC ; import com . hp . hpl . jena . vocabulary . DCTerms ; import com . hp . hpl . jena . vocabulary . RDF ; import com . hp . hpl . jena . vocabulary . RDFS ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . RelationalOperators ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . find . FindQuery ; import de . fuberlin . wiwiss . d2rq . find . TripleQueryIter ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . nodes . FixedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . vocab . SKOS ; public class ClassMapLister { private static final Log log = LogFactory . getLog ( ClassMapLister . class ) ; private final Mapping mapping ; private Map < String , List < TripleRelation > > classMapInventoryBridges = new HashMap < String , List < TripleRelation > > ( ) ; private Map < String , NodeMaker > classMapNodeMakers = new HashMap < String , NodeMaker > ( ) ; public ClassMapLister ( Mapping mapping ) { this . mapping = mapping ; groupTripleRelationsByClassMap ( ) ; } private void groupTripleRelationsByClassMap ( ) { if ( ! classMapInventoryBridges . isEmpty ( ) || ! classMapNodeMakers . isEmpty ( ) ) return ; for ( Resource classMapResource : mapping . classMapResources ( ) ) { NodeMaker resourceMaker = this . mapping . classMap ( classMapResource ) . nodeMaker ( ) ; Node classMap = classMapResource . asNode ( ) ; this . classMapNodeMakers . put ( toClassMapName ( classMap ) , resourceMaker ) ; List < TripleRelation > inventoryBridges = new ArrayList < TripleRelation > ( ) ; for ( TripleRelation bridge : mapping . classMap ( classMapResource ) . compiledPropertyBridges ( ) ) { bridge = bridge . orderBy ( TripleRelation . SUBJECT , true ) ; if ( bridge . selectTriple ( new Triple ( Node . ANY , RDF . Nodes . type , Node . ANY ) ) != null ) { inventoryBridges . add ( bridge ) ; } if ( bridge . selectTriple ( new Triple ( Node . ANY , RDFS . label . asNode ( ) , Node . ANY ) ) != null ) { inventoryBridges . add ( bridge ) ; } else if ( bridge . selectTriple ( new Triple ( Node . ANY , SKOS . prefLabel . asNode ( ) , Node . ANY ) ) != null ) { inventoryBridges . add ( bridge ) ; } else if ( bridge . selectTriple ( new Triple ( Node . ANY , DC . title . asNode ( ) , Node . ANY ) ) != null ) { inventoryBridges . add ( bridge ) ; } else if ( bridge . selectTriple ( new Triple ( Node . ANY , DCTerms . title . asNode ( ) , Node . ANY ) ) != null ) { inventoryBridges . add ( bridge ) ; } else if ( bridge . selectTriple ( new Triple ( Node . ANY , FOAF . name . asNode ( ) , Node . ANY ) ) != null ) { inventoryBridges . add ( bridge ) ; } } if ( inventoryBridges . isEmpty ( ) ) { Relation relation = ( Relation ) this . mapping . classMap ( classMapResource ) . relation ( ) ; NodeMaker typeNodeMaker = new FixedNodeMaker ( RDF . type . asNode ( ) , false ) ; NodeMaker resourceNodeMaker = new FixedNodeMaker ( RDFS . Resource . asNode ( ) , false ) ; inventoryBridges . add ( new TripleRelation ( relation , resourceMaker , typeNodeMaker , resourceNodeMaker ) ) ; } this . classMapInventoryBridges . put ( toClassMapName ( classMap ) , inventoryBridges ) ; } } private String toClassMapName ( Node classMap ) { return classMap . getLocalName ( ) ; } public Collection < String > classMapNames ( ) { return this . classMapInventoryBridges . keySet ( ) ; } public Model classMapInventory ( String classMapName ) { return classMapInventory ( classMapName , Relation . NO_LIMIT ) ; } public Model classMapInventory ( String classMapName , int limitPerClassMap ) { log . info ( "" + classMapName ) ; List < TripleRelation > inventoryBridges = classMapInventoryBridges . get ( classMapName ) ; if ( inventoryBridges == null ) { return null ; } Model result = ModelFactory . createDefaultModel ( ) ; result . setNsPrefixes ( mapping . getPrefixMapping ( ) ) ; FindQuery query = new FindQuery ( Triple . ANY , inventoryBridges , limitPerClassMap , null ) ; result . getGraph ( ) . getBulkUpdateHandler ( ) . add ( TripleQueryIter . create ( query . iterator ( ) ) ) ; return result ; } public Collection < String > classMapNamesForResource ( Node resource ) { if ( ! resource . isURI ( ) ) { return Collections . < String > emptyList ( ) ; } List < String > results = new ArrayList < String > ( ) ; for ( Entry < String , NodeMaker > entry : classMapNodeMakers . entrySet ( ) ) { String classMapName = entry . getKey ( ) ; NodeMaker nodeMaker = entry . getValue ( ) ; if ( ! nodeMaker . selectNode ( resource , RelationalOperators . DUMMY ) . equals ( NodeMaker . EMPTY ) ) { results . add ( classMapName ) ; } } return results ; } } package de . fuberlin . wiwiss . d2rq . dbschema ; import java . sql . DatabaseMetaData ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import org . apache . log4j . Logger ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . vendor . Vendor ; public class DatabaseSchemaInspector { private final static Logger log = Logger . getLogger ( DatabaseSchemaInspector . class ) ; private final ConnectedDB db ; private final DatabaseMetaData schema ; public static final int KEYS_IMPORTED = ; public static final int KEYS_EXPORTED = ; public DatabaseSchemaInspector ( ConnectedDB db ) { this . db = db ; try { this . schema = db . connection ( ) . getMetaData ( ) ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex , D2RQException . D2RQ_SQLEXCEPTION ) ; } } public DataType columnType ( Attribute column ) { try { ResultSet rs = this . schema . getColumns ( null , column . schemaName ( ) , column . tableName ( ) , column . attributeName ( ) ) ; try { if ( ! rs . next ( ) ) { throw new D2RQException ( "" + column + "" , D2RQException . SQL_COLUMN_NOT_FOUND ) ; } int type = rs . getInt ( "" ) ; String name = rs . getString ( "" ) . toUpperCase ( ) ; int size = rs . getInt ( "" ) ; DataType result = db . vendor ( ) . getDataType ( type , name , size ) ; if ( result == null ) { log . warn ( "" + ( size == ? name : ( name + "" + size + "" ) ) + "" + type + "" ) ; } return result ; } finally { rs . close ( ) ; } } catch ( SQLException ex ) { throw new D2RQException ( "" , ex , D2RQException . D2RQ_SQLEXCEPTION ) ; } } public boolean isNullable ( Attribute column ) { try { ResultSet rs = this . schema . getColumns ( null , column . schemaName ( ) , column . tableName ( ) , column . attributeName ( ) ) ; if ( ! rs . next ( ) ) { throw new D2RQException ( "" + column + "" , D2RQException . SQL_COLUMN_NOT_FOUND ) ; } boolean nullable = ( rs . getInt ( "" ) == DatabaseMetaData . columnNullable ) ; rs . close ( ) ; return nullable ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex , D2RQException . D2RQ_SQLEXCEPTION ) ; } } public boolean isZerofillColumn ( Attribute column ) { boolean isZerofill = false ; boolean foundColumn = false ; try { if ( db . vendor ( ) != Vendor . MySQL ) return false ; Statement stmt = db . connection ( ) . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( "" + db . vendor ( ) . quoteRelationName ( column . relationName ( ) ) ) ; while ( rs . next ( ) ) { if ( column . attributeName ( ) . toLowerCase ( ) . equals ( rs . getString ( "" ) . toLowerCase ( ) ) ) { isZerofill = ( rs . getString ( "" ) . toLowerCase ( ) . indexOf ( "" ) != - ) ; foundColumn = true ; break ; } } rs . close ( ) ; stmt . close ( ) ; if ( foundColumn ) return isZerofill ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex , D2RQException . D2RQ_SQLEXCEPTION ) ; } throw new D2RQException ( "" + column , D2RQException . SQL_COLUMN_NOT_FOUND ) ; } public List < RelationName > listTableNames ( String searchInSchema ) { List < RelationName > result = new ArrayList < RelationName > ( ) ; try { ResultSet rs = this . schema . getTables ( null , searchInSchema , null , new String [ ] { "" , "" } ) ; while ( rs . next ( ) ) { String schema = rs . getString ( "" ) ; String table = rs . getString ( "" ) ; if ( ! this . db . vendor ( ) . isIgnoredTable ( schema , table ) ) { result . add ( toRelationName ( schema , table ) ) ; } } rs . close ( ) ; return result ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex ) ; } } public List < Attribute > listColumns ( RelationName tableName ) { List < Attribute > result = new ArrayList < Attribute > ( ) ; try { ResultSet rs = this . schema . getColumns ( null , schemaName ( tableName ) , tableName ( tableName ) , null ) ; while ( rs . next ( ) ) { result . add ( new Attribute ( tableName , rs . getString ( "" ) ) ) ; } rs . close ( ) ; return result ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex , D2RQException . D2RQ_SQLEXCEPTION ) ; } } public List < Attribute > primaryKeyColumns ( RelationName tableName ) { List < Attribute > result = new ArrayList < Attribute > ( ) ; try { ResultSet rs = this . schema . getPrimaryKeys ( null , schemaName ( tableName ) , tableName ( tableName ) ) ; while ( rs . next ( ) ) { result . add ( new Attribute ( tableName , rs . getString ( "" ) ) ) ; } rs . close ( ) ; return result ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex , D2RQException . D2RQ_SQLEXCEPTION ) ; } } public Map < String , List < String > > uniqueColumns ( RelationName tableName ) { Map < String , List < String > > result = new HashMap < String , List < String > > ( ) ; try { boolean approximate = ( db . vendor ( ) == Vendor . Oracle ) ; ResultSet rs = this . schema . getIndexInfo ( null , schemaName ( tableName ) , tableName ( tableName ) , true , approximate ) ; while ( rs . next ( ) ) { String indexKey = rs . getString ( "" ) ; if ( indexKey != null ) { if ( ! result . containsKey ( indexKey ) ) result . put ( indexKey , new ArrayList < String > ( ) ) ; result . get ( indexKey ) . add ( rs . getString ( "" ) ) ; } } rs . close ( ) ; return result ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex , D2RQException . D2RQ_SQLEXCEPTION ) ; } } public List < Join > foreignKeys ( RelationName tableName , int direction ) { try { Map < String , ForeignKey > fks = new HashMap < String , ForeignKey > ( ) ; ResultSet rs = ( direction == KEYS_IMPORTED ? this . schema . getImportedKeys ( null , schemaName ( tableName ) , tableName ( tableName ) ) : this . schema . getExportedKeys ( null , schemaName ( tableName ) , tableName ( tableName ) ) ) ; while ( rs . next ( ) ) { RelationName pkTable = toRelationName ( rs . getString ( "" ) , rs . getString ( "" ) ) ; Attribute primaryColumn = new Attribute ( pkTable , rs . getString ( "" ) ) ; RelationName fkTable = toRelationName ( rs . getString ( "" ) , rs . getString ( "" ) ) ; Attribute foreignColumn = new Attribute ( fkTable , rs . getString ( "" ) ) ; String fkName = rs . getString ( "" ) ; if ( ! fks . containsKey ( fkName ) ) { fks . put ( fkName , new ForeignKey ( ) ) ; } int keySeq = rs . getInt ( "" ) - ; fks . get ( fkName ) . addColumns ( keySeq , foreignColumn , primaryColumn ) ; } rs . close ( ) ; List < Join > results = new ArrayList < Join > ( ) ; Iterator < ForeignKey > it = fks . values ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { ForeignKey fk = ( ForeignKey ) it . next ( ) ; results . add ( fk . toJoin ( ) ) ; } return results ; } catch ( SQLException ex ) { throw new D2RQException ( "" , ex , D2RQException . D2RQ_SQLEXCEPTION ) ; } } private String schemaName ( RelationName tableName ) { if ( this . db . vendor ( ) == Vendor . PostgreSQL && tableName . schemaName ( ) == null ) { return "" ; } return tableName . schemaName ( ) ; } private String tableName ( RelationName tableName ) { return tableName . tableName ( ) ; } private RelationName toRelationName ( String schema , String table ) { if ( schema == null ) { return new RelationName ( null , table , db . lowerCaseTableNames ( ) ) ; } else if ( ( db . vendor ( ) == Vendor . PostgreSQL || db . vendor ( ) == Vendor . HSQLDB ) && "" . equals ( schema . toLowerCase ( ) ) ) { return new RelationName ( null , table , db . lowerCaseTableNames ( ) ) ; } return new RelationName ( schema , table , db . lowerCaseTableNames ( ) ) ; } private class ForeignKey { private TreeMap < Integer , Attribute > primaryColumns = new TreeMap < Integer , Attribute > ( ) ; private TreeMap < Integer , Attribute > foreignColumns = new TreeMap < Integer , Attribute > ( ) ; private void addColumns ( int keySequence , Attribute foreign , Attribute primary ) { primaryColumns . put ( new Integer ( keySequence ) , primary ) ; foreignColumns . put ( new Integer ( keySequence ) , foreign ) ; } private Join toJoin ( ) { return new Join ( new ArrayList < Attribute > ( foreignColumns . values ( ) ) , new ArrayList < Attribute > ( primaryColumns . values ( ) ) , Join . DIRECTION_RIGHT ) ; } } public RelationName getCorrectCapitalization ( RelationName relationName ) { if ( ! relationName . caseUnspecified ( ) || ! db . lowerCaseTableNames ( ) ) return relationName ; Iterator < RelationName > it = listTableNames ( null ) . iterator ( ) ; while ( it . hasNext ( ) ) { RelationName r = it . next ( ) ; if ( r . equals ( relationName ) ) return r ; } return null ; } } package de . fuberlin . wiwiss . d2rq ; import com . hp . hpl . jena . shared . JenaException ; public class D2RQException extends JenaException { public static final int UNSPECIFIED = ; public static final int MAPPING_NO_DATABASE = ; public static final int CLASSMAP_DUPLICATE_DATABASE = ; public static final int CLASSMAP_NO_DATABASE = ; public static final int CLASSMAP_INVALID_DATABASE = ; public static final int CLASSMAP_NO_PROPERTYBRIDGES = ; public static final int RESOURCEMAP_DUPLICATE_BNODEIDCOLUMNS = ; public static final int RESOURCEMAP_DUPLICATE_URICOLUMN = ; public static final int RESOURCEMAP_DUPLICATE_URIPATTERN = ; public static final int RESOURCEMAP_ILLEGAL_CONTAINSDUPLICATE = ; public static final int RESOURCEMAP_MISSING_PRIMARYSPEC = ; public static final int RESOURCEMAP_DUPLICATE_PRIMARYSPEC = ; public static final int RESOURCEMAP_DUPLICATE_TRANSLATEWITH = ; public static final int RESOURCEMAP_INVALID_TRANSLATEWITH = ; public static final int PROPERTYBRIDGE_DUPLICATE_BELONGSTOCLASSMAP = ; public static final int PROPERTYBRIDGE_INVALID_BELONGSTOCLASSMAP = ; public static final int PROPERTYBRIDGE_DUPLICATE_COLUMN = ; public static final int PROPERTYBRIDGE_DUPLICATE_PATTERN = ; public static final int PROPERTYBRIDGE_DUPLICATE_DATATYPE = ; public static final int PROPERTYBRIDGE_DUPLICATE_LANG = ; public static final int PROPERTYBRIDGE_DUPLICATE_REFERSTOCLASSMAP = ; public static final int PROPERTYBRIDGE_INVALID_REFERSTOCLASSMAP = ; public static final int PROPERTYBRIDGE_DUPLICATE_VALUEMAXLENGTH = ; public static final int PROPERTYBRIDGE_CONFLICTING_DATABASES = ; public static final int PROPERTYBRIDGE_LANG_AND_DATATYPE = ; public static final int PROPERTYBRIDGE_NONLITERAL_WITH_DATATYPE = ; public static final int PROPERTYBRIDGE_NONLITERAL_WITH_LANG = ; public static final int TRANSLATIONTABLE_TRANSLATION_AND_JAVACLASS = ; public static final int TRANSLATIONTABLE_TRANSLATION_AND_HREF = ; public static final int TRANSLATIONTABLE_HREF_AND_JAVACLASS = ; public static final int TRANSLATIONTABLE_DUPLICATE_JAVACLASS = ; public static final int TRANSLATIONTABLE_DUPLICATE_HREF = ; public static final int TRANSLATION_MISSING_DBVALUE = ; public static final int TRANSLATION_MISSING_RDFVALUE = ; public static final int DATABASE_DUPLICATE_JDBCDSN = ; public static final int DATABASE_DUPLICATE_JDBCDRIVER = ; public static final int DATABASE_MISSING_JDBCDRIVER = ; public static final int DATABASE_DUPLICATE_USERNAME = ; public static final int DATABASE_DUPLICATE_PASSWORD = ; public static final int DATABASE_JDBCDRIVER_CLASS_NOT_FOUND = ; public static final int D2RQ_SQLEXCEPTION = ; public static final int SQL_INVALID_RELATIONNAME = ; public static final int SQL_INVALID_ATTRIBUTENAME = ; public static final int SQL_INVALID_ALIAS = ; public static final int SQL_INVALID_JOIN = ; public static final int MAPPING_RESOURCE_INSTEADOF_LITERAL = ; public static final int MAPPING_LITERAL_INSTEADOF_RESOURCE = ; public static final int RESOURCEMAP_ILLEGAL_URIPATTERN = ; public static final int DATABASE_MISSING_DSN = ; public static final int MUST_BE_NUMERIC = ; public static final int RESOURCEMAP_DUPLICATE_CONSTANTVALUE = ; public static final int CLASSMAP_INVALID_CONSTANTVALUE = ; public static final int D2RQ_DB_CONNECTION_FAILED = ; public static final int MAPPING_UNKNOWN_D2RQ_PROPERTY = ; public static final int MAPPING_UNKNOWN_D2RQ_CLASS = ; public static final int PROPERTYBRIDGE_DUPLICATE_SQL_EXPRESSION = ; public static final int MAPPING_TYPECONFLICT = ; public static final int PROPERTYBRIDGE_DUPLICATE_URI_SQL_EXPRESSION = ; public static final int PROPERTYBRIDGE_DUPLICATE_LIMIT = ; public static final int PROPERTYBRIDGE_DUPLICATE_LIMITINVERSE = ; public static final int PROPERTYBRIDGE_DUPLICATE_ORDER = ; public static final int PROPERTYBRIDGE_DUPLICATE_ORDERDESC = ; public static final int DATABASE_ALREADY_CONNECTED = ; public static final int DOWNLOADMAP_DUPLICATE_BELONGSTOCLASSMAP = ; public static final int DOWNLOADMAP_INVALID_BELONGSTOCLASSMAP = ; public static final int DOWNLOADMAP_DUPLICATE_MEDIATYPE = ; public static final int DOWNLOADMAP_DUPLICATE_CONTENTCOLUMN = ; public static final int DOWNLOADMAP_INVALID_CONSTANTVALUE = ; public static final int DOWNLOADMAP_NO_CONTENTCOLUMN = ; public static final int DOWNLOADMAP_DUPLICATE_DATABASE = ; public static final int DOWNLOADMAP_INVALID_DATABASE = ; public static final int DOWNLOADMAP_NO_DATASTORAGE = ; public static final int DATATYPE_UNMAPPABLE = ; public static final int DATATYPE_UNKNOWN = ; public static final int DATABASE_DUPLICATE_STARTUPSCRIPT = ; public static final int MAPPING_TURTLE_SYNTAX = ; public static final int STARTUP_SQL_SCRIPT_ACCESS = ; public static final int STARTUP_SQL_SCRIPT_SYNTAX = ; public static final int DATATYPE_DOES_NOT_SUPPORT_DISTINCT = ; public static final int CONFIG_UNKNOWN_PROPERTY = ; public static final int CONFIG_UNKNOWN_CLASS = ; public static final int STARTUP_BASE_URI_NOT_ABSOLUTE = ; public static final int QUERY_TIMEOUT = ; public static final int PROPERTYBRIDGE_MISSING_PREDICATESPEC = ; public static final int SQL_COLUMN_NOT_FOUND = ; public static final int STARTUP_UNKNOWN_FORMAT = ; private int code ; public D2RQException ( String message ) { this ( message , UNSPECIFIED ) ; } public D2RQException ( Throwable cause ) { this ( cause , UNSPECIFIED ) ; } public D2RQException ( String message , Throwable cause ) { this ( message , cause , UNSPECIFIED ) ; } public D2RQException ( String message , int code ) { super ( message + "" + code + "" ) ; this . code = code ; } public D2RQException ( Throwable cause , int code ) { super ( cause ) ; this . code = code ; } public D2RQException ( String message , Throwable cause , int code ) { super ( message + "" + code + "" , cause ) ; this . code = code ; } public int errorCode ( ) { return this . code ; } } package de . fuberlin . wiwiss . d2rq . expr ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; public class GreaterThanOrEqual extends BinaryOperator { public GreaterThanOrEqual ( Expression expr1 , Expression expr2 ) { super ( expr1 , expr2 , "" ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new GreaterThanOrEqual ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Collections ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class AttributeExpr extends Expression { private final Attribute attribute ; public AttributeExpr ( Attribute attribute ) { this . attribute = attribute ; } public Set < Attribute > attributes ( ) { return Collections . singleton ( attribute ) ; } public boolean isFalse ( ) { return false ; } public boolean isTrue ( ) { return false ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new AttributeExpr ( columnRenamer . applyTo ( attribute ) ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return database . vendor ( ) . quoteAttribute ( attribute ) ; } public String toString ( ) { return "" + attribute + "" ; } public boolean equals ( Object other ) { if ( ! ( other instanceof AttributeExpr ) ) { return false ; } return attribute . equals ( ( ( AttributeExpr ) other ) . attribute ) ; } public int hashCode ( ) { return this . attribute . hashCode ( ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class UnaryMinus extends Expression { private Expression base ; public UnaryMinus ( Expression base ) { this . base = base ; } public Expression getBase ( ) { return base ; } public Set < Attribute > attributes ( ) { return base . attributes ( ) ; } public boolean isFalse ( ) { return false ; } public boolean isTrue ( ) { return false ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new UnaryMinus ( base . renameAttributes ( columnRenamer ) ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return "" + base . toSQL ( database , aliases ) + "" ; } public String toString ( ) { return "" + base + "" ; } } package de . fuberlin . wiwiss . d2rq . expr ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; public class LessThanOrEqual extends BinaryOperator { public LessThanOrEqual ( Expression expr1 , Expression expr2 ) { super ( expr1 , expr2 , "" ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new LessThanOrEqual ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; public class Subtract extends BinaryOperator { public Subtract ( Expression expr1 , Expression expr2 ) { super ( expr1 , expr2 , "" ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new Subtract ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . HashSet ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class Equality extends Expression { public static Expression create ( Expression expr1 , Expression expr2 ) { if ( expr1 . equals ( expr2 ) ) { return Expression . TRUE ; } return new Equality ( expr1 , expr2 ) ; } public static Expression createAttributeEquality ( Attribute attribute1 , Attribute attribute2 ) { return ( attribute1 . compareTo ( attribute2 ) < ) ? create ( new AttributeExpr ( attribute1 ) , new AttributeExpr ( attribute2 ) ) : create ( new AttributeExpr ( attribute2 ) , new AttributeExpr ( attribute1 ) ) ; } public static Expression createAttributeValue ( Attribute attribute , String value ) { return create ( new AttributeExpr ( attribute ) , new Constant ( value , attribute ) ) ; } public static Expression createExpressionValue ( Expression expression , String value ) { return create ( expression , new Constant ( value ) ) ; } private final Expression expr1 ; private final Expression expr2 ; private final Set < Attribute > columns = new HashSet < Attribute > ( ) ; private Equality ( Expression expr1 , Expression expr2 ) { this . expr1 = expr1 ; this . expr2 = expr2 ; columns . addAll ( expr1 . attributes ( ) ) ; columns . addAll ( expr2 . attributes ( ) ) ; } public Set < Attribute > attributes ( ) { return columns ; } public boolean isFalse ( ) { return ( expr1 . isFalse ( ) && expr2 . isTrue ( ) ) || ( expr1 . isTrue ( ) && expr2 . isFalse ( ) ) ; } public boolean isTrue ( ) { return expr1 . equals ( expr2 ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new Equality ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return expr1 . toSQL ( database , aliases ) + "" + expr2 . toSQL ( database , aliases ) ; } public String toString ( ) { return "" + expr1 + "" + expr2 + "" ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Equality ) ) { return false ; } Equality otherEquality = ( Equality ) other ; if ( expr1 . equals ( otherEquality . expr1 ) && expr2 . equals ( otherEquality . expr2 ) ) { return true ; } if ( expr1 . equals ( otherEquality . expr2 ) && expr2 . equals ( otherEquality . expr1 ) ) { return true ; } return false ; } public int hashCode ( ) { return expr1 . hashCode ( ) ^ expr2 . hashCode ( ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; public class GreaterThan extends BinaryOperator { public GreaterThan ( Expression expr1 , Expression expr2 ) { super ( expr1 , expr2 , ">" ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new GreaterThan ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Collections ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType . GenericType ; public class Constant extends Expression { private final String value ; private final Attribute attributeForTrackingType ; public Constant ( String value ) { this ( value , null ) ; } public Constant ( String value , Attribute attributeForTrackingType ) { this . value = value ; this . attributeForTrackingType = attributeForTrackingType ; } public String value ( ) { return value ; } public Set < Attribute > attributes ( ) { return Collections . < Attribute > emptySet ( ) ; } public boolean isFalse ( ) { return false ; } public boolean isTrue ( ) { return false ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { if ( attributeForTrackingType == null ) { return this ; } return new Constant ( value , columnRenamer . applyTo ( attributeForTrackingType ) ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { if ( attributeForTrackingType == null ) { return GenericType . CHARACTER . dataTypeFor ( database . vendor ( ) ) . toSQLLiteral ( value ) ; } return database . columnType ( aliases . originalOf ( attributeForTrackingType ) ) . toSQLLiteral ( value ) ; } public String toString ( ) { if ( attributeForTrackingType == null ) { return "" + value + "" ; } return "" + value + "" + attributeForTrackingType . qualifiedName ( ) + "" ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Constant ) ) return false ; Constant otherConstant = ( Constant ) other ; if ( ! value . equals ( otherConstant . value ) ) return false ; if ( attributeForTrackingType == null ) { return otherConstant . attributeForTrackingType == null ; } return attributeForTrackingType . equals ( otherConstant . attributeForTrackingType ) ; } public int hashCode ( ) { if ( attributeForTrackingType == null ) { return value . hashCode ( ) ; } return value . hashCode ( ) ^ attributeForTrackingType . hashCode ( ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public abstract class Expression { public static final Expression TRUE = new Expression ( ) { public Set < Attribute > attributes ( ) { return Collections . < Attribute > emptySet ( ) ; } public boolean isFalse ( ) { return false ; } public boolean isTrue ( ) { return true ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return this ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return "" ; } public String toString ( ) { return "" ; } } ; public static final Expression FALSE = new Expression ( ) { public Set < Attribute > attributes ( ) { return Collections . < Attribute > emptySet ( ) ; } public boolean isFalse ( ) { return true ; } public boolean isTrue ( ) { return false ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return this ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return "" ; } public String toString ( ) { return "" ; } } ; public abstract boolean isTrue ( ) ; public abstract boolean isFalse ( ) ; public abstract Set < Attribute > attributes ( ) ; public abstract Expression renameAttributes ( ColumnRenamer columnRenamer ) ; public abstract String toSQL ( ConnectedDB database , AliasMap aliases ) ; public Expression and ( Expression other ) { List < Expression > list = new ArrayList < Expression > ( ) ; list . add ( this ) ; list . add ( other ) ; return Conjunction . create ( list ) ; } public Expression or ( Expression other ) { List < Expression > list = new ArrayList < Expression > ( ) ; list . add ( this ) ; list . add ( other ) ; return Disjunction . create ( list ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class NotNull extends Expression { public static Expression create ( Expression expr ) { return new NotNull ( expr ) ; } private Expression expr ; private NotNull ( Expression expr ) { this . expr = expr ; } public Set < Attribute > attributes ( ) { return expr . attributes ( ) ; } public boolean isFalse ( ) { return false ; } public boolean isTrue ( ) { return false ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return NotNull . create ( columnRenamer . applyTo ( expr ) ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return expr . toSQL ( database , aliases ) + "" ; } public String toString ( ) { return "" + this . expr + "" ; } public boolean equals ( Object other ) { if ( ! ( other instanceof NotNull ) ) { return false ; } NotNull otherExpression = ( NotNull ) other ; return expr . equals ( otherExpression . expr ) ; } public int hashCode ( ) { return this . expr . hashCode ( ) ^ ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class Conjunction extends Expression { public static Expression create ( Collection < Expression > expressions ) { Set < Expression > elements = new HashSet < Expression > ( expressions . size ( ) ) ; for ( Expression expression : expressions ) { if ( expression . isFalse ( ) ) { return Expression . FALSE ; } if ( expression . isTrue ( ) ) { continue ; } if ( expression instanceof Conjunction ) { elements . addAll ( ( ( Conjunction ) expression ) . expressions ) ; } else { elements . add ( expression ) ; } } if ( elements . isEmpty ( ) ) { return Expression . TRUE ; } if ( elements . size ( ) == ) { return ( Expression ) elements . iterator ( ) . next ( ) ; } return new Conjunction ( elements ) ; } private Set < Expression > expressions ; private Set < Attribute > attributes = new HashSet < Attribute > ( ) ; private Conjunction ( Set < Expression > expressions ) { this . expressions = expressions ; for ( Expression expression : expressions ) { this . attributes . addAll ( expression . attributes ( ) ) ; } } public boolean isTrue ( ) { return false ; } public boolean isFalse ( ) { return false ; } public Set < Attribute > attributes ( ) { return this . attributes ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { Set < Expression > renamedExpressions = new HashSet < Expression > ( ) ; for ( Expression expression : expressions ) { renamedExpressions . add ( expression . renameAttributes ( columnRenamer ) ) ; } return Conjunction . create ( renamedExpressions ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { List < String > fragments = new ArrayList < String > ( this . expressions . size ( ) ) ; for ( Expression expression : expressions ) { fragments . add ( expression . toSQL ( database , aliases ) ) ; } Collections . sort ( fragments ) ; StringBuffer result = new StringBuffer ( "" ) ; Iterator < String > it = fragments . iterator ( ) ; while ( it . hasNext ( ) ) { String fragment = ( String ) it . next ( ) ; result . append ( fragment ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } public String toString ( ) { List < String > fragments = new ArrayList < String > ( this . expressions . size ( ) ) ; for ( Expression expression : expressions ) { fragments . add ( expression . toString ( ) ) ; } Collections . sort ( fragments ) ; StringBuffer result = new StringBuffer ( "" ) ; Iterator < String > it = fragments . iterator ( ) ; while ( it . hasNext ( ) ) { String fragment = ( String ) it . next ( ) ; result . append ( fragment ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Conjunction ) ) { return false ; } Conjunction otherConjunction = ( Conjunction ) other ; return this . expressions . equals ( otherConjunction . expressions ) ; } public int hashCode ( ) { return this . expressions . hashCode ( ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; public class LessThan extends BinaryOperator { public LessThan ( Expression expr1 , Expression expr2 ) { super ( expr1 , expr2 , "" ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new LessThan ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class Disjunction extends Expression { public static Expression create ( Collection < Expression > expressions ) { Set < Expression > elements = new HashSet < Expression > ( expressions . size ( ) ) ; for ( Expression expression : expressions ) { if ( expression . isTrue ( ) ) { return Expression . TRUE ; } if ( expression . isFalse ( ) ) { continue ; } if ( expression instanceof Disjunction ) { elements . addAll ( ( ( Disjunction ) expression ) . expressions ) ; } else { elements . add ( expression ) ; } } if ( elements . isEmpty ( ) ) { return Expression . FALSE ; } if ( elements . size ( ) == ) { return ( Expression ) elements . iterator ( ) . next ( ) ; } return new Disjunction ( elements ) ; } private Set < Expression > expressions ; private Set < Attribute > attributes = new HashSet < Attribute > ( ) ; private Disjunction ( Set < Expression > expressions ) { this . expressions = expressions ; for ( Expression expression : expressions ) { this . attributes . addAll ( expression . attributes ( ) ) ; } } public boolean isTrue ( ) { return false ; } public boolean isFalse ( ) { return false ; } public Set < Attribute > attributes ( ) { return this . attributes ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { Set < Expression > renamedExpressions = new HashSet < Expression > ( ) ; for ( Expression expression : expressions ) { renamedExpressions . add ( expression . renameAttributes ( columnRenamer ) ) ; } return Disjunction . create ( renamedExpressions ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { List < String > fragments = new ArrayList < String > ( expressions . size ( ) ) ; for ( Expression expression : expressions ) { fragments . add ( expression . toSQL ( database , aliases ) ) ; } Collections . sort ( fragments ) ; StringBuffer result = new StringBuffer ( "" ) ; Iterator < String > it = fragments . iterator ( ) ; while ( it . hasNext ( ) ) { String fragment = it . next ( ) ; result . append ( fragment ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } public String toString ( ) { List < String > fragments = new ArrayList < String > ( expressions . size ( ) ) ; for ( Expression expression : expressions ) { fragments . add ( expression . toString ( ) ) ; } Collections . sort ( fragments ) ; StringBuffer result = new StringBuffer ( "" ) ; Iterator < String > it = fragments . iterator ( ) ; while ( it . hasNext ( ) ) { String fragment = it . next ( ) ; result . append ( fragment ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Disjunction ) ) { return false ; } Disjunction otherConjunction = ( Disjunction ) other ; return this . expressions . equals ( otherConjunction . expressions ) ; } public int hashCode ( ) { return this . expressions . hashCode ( ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class Concatenation extends Expression { public static Expression create ( List < Expression > expressions ) { List < Expression > nonEmpty = new ArrayList < Expression > ( expressions . size ( ) ) ; for ( Expression expression : expressions ) { if ( expression instanceof Constant && "" . equals ( ( ( Constant ) expression ) . value ( ) ) ) { continue ; } nonEmpty . add ( expression ) ; } if ( nonEmpty . isEmpty ( ) ) { return new Constant ( "" ) ; } if ( nonEmpty . size ( ) == ) { return nonEmpty . get ( ) ; } return new Concatenation ( nonEmpty ) ; } private final List < Expression > parts ; private final Set < Attribute > attributes = new HashSet < Attribute > ( ) ; private Concatenation ( List < Expression > parts ) { this . parts = parts ; for ( Expression expression : parts ) { attributes . addAll ( expression . attributes ( ) ) ; } } public Set < Attribute > attributes ( ) { return attributes ; } public boolean isFalse ( ) { return false ; } public boolean isTrue ( ) { return false ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { List < Expression > renamedExpressions = new ArrayList < Expression > ( parts . size ( ) ) ; for ( Expression expression : parts ) { renamedExpressions . add ( columnRenamer . applyTo ( expression ) ) ; } return new Concatenation ( renamedExpressions ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { String [ ] fragments = new String [ parts . size ( ) ] ; for ( int i = ; i < parts . size ( ) ; i ++ ) { Expression part = ( Expression ) parts . get ( i ) ; fragments [ i ] = part . toSQL ( database , aliases ) ; } return database . vendor ( ) . getConcatenationExpression ( fragments ) ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Concatenation ) ) return false ; return parts . equals ( ( ( Concatenation ) other ) . parts ) ; } public int hashCode ( ) { return parts . hashCode ( ) ^ ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; Iterator < Expression > it = parts . iterator ( ) ; while ( it . hasNext ( ) ) { result . append ( it . next ( ) ) ; if ( it . hasNext ( ) ) { result . append ( "" ) ; } } result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . HashSet ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public abstract class BinaryOperator extends Expression { protected final Expression expr1 ; protected final Expression expr2 ; protected final String operator ; private final Set < Attribute > columns = new HashSet < Attribute > ( ) ; protected BinaryOperator ( Expression expr1 , Expression expr2 , String operator ) { this . expr1 = expr1 ; this . expr2 = expr2 ; this . operator = operator ; columns . addAll ( expr1 . attributes ( ) ) ; columns . addAll ( expr2 . attributes ( ) ) ; } public Set < Attribute > attributes ( ) { return columns ; } public boolean isFalse ( ) { return false ; } public boolean isTrue ( ) { return false ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return expr1 . toSQL ( database , aliases ) + "" + operator + "" + expr2 . toSQL ( database , aliases ) ; } public String toString ( ) { return operator + "" + expr1 + "" + expr2 + "" ; } public boolean equals ( Object other ) { if ( ! ( other instanceof BinaryOperator ) ) { return false ; } BinaryOperator otherBinaryOperator = ( BinaryOperator ) other ; return expr1 . equals ( otherBinaryOperator . expr1 ) && expr2 . equals ( otherBinaryOperator . expr2 ) && operator . equals ( otherBinaryOperator . operator ) ; } public int hashCode ( ) { return operator . hashCode ( ) ^ expr1 . hashCode ( ) ^ expr2 . hashCode ( ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . HashSet ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; public class SQLExpression extends Expression { public static Expression create ( String sql ) { sql = sql . trim ( ) ; if ( "" . equals ( sql ) ) { return Expression . TRUE ; } if ( "" . equals ( sql ) ) { return Expression . FALSE ; } return new SQLExpression ( sql ) ; } private String expression ; private Set < Attribute > columns = new HashSet < Attribute > ( ) ; private SQLExpression ( String expression ) { this . expression = expression ; this . columns = SQL . findColumnsInExpression ( this . expression ) ; } public boolean isTrue ( ) { return false ; } public boolean isFalse ( ) { return false ; } public Set < Attribute > attributes ( ) { return this . columns ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new SQLExpression ( SQL . replaceColumnsInExpression ( this . expression , columnRenamer ) ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return "" + SQL . quoteColumnsInExpression ( this . expression , database ) + "" ; } public String toString ( ) { return "" + this . expression + "" ; } public boolean equals ( Object other ) { if ( ! ( other instanceof SQLExpression ) ) { return false ; } SQLExpression otherExpression = ( SQLExpression ) other ; return this . expression . equals ( otherExpression . expression ) ; } public int hashCode ( ) { return this . expression . hashCode ( ) ; } public String getExpression ( ) { return expression ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class BooleanToIntegerCaseExpression extends Expression { private Expression base ; public BooleanToIntegerCaseExpression ( Expression base ) { this . base = base ; } public Expression getBase ( ) { return base ; } public Set < Attribute > attributes ( ) { return base . attributes ( ) ; } public boolean isFalse ( ) { return base . isFalse ( ) ; } public boolean isTrue ( ) { return base . isTrue ( ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new BooleanToIntegerCaseExpression ( base . renameAttributes ( columnRenamer ) ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return "" + base . toSQL ( database , aliases ) + "" ; } public String toString ( ) { return "" + base + "" ; } public boolean equals ( Object other ) { if ( ! ( other instanceof BooleanToIntegerCaseExpression ) ) { return false ; } BooleanToIntegerCaseExpression otherExpression = ( BooleanToIntegerCaseExpression ) other ; return this . base . equals ( otherExpression . base ) ; } public int hashCode ( ) { return base . hashCode ( ) ^ ; } } package de . fuberlin . wiwiss . d2rq . expr ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class Negation extends Expression { private Expression base ; public Negation ( Expression base ) { this . base = base ; } public Expression getBase ( ) { return base ; } public Set < Attribute > attributes ( ) { return base . attributes ( ) ; } public boolean isFalse ( ) { return base . isTrue ( ) ; } public boolean isTrue ( ) { return base . isFalse ( ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new Negation ( base . renameAttributes ( columnRenamer ) ) ; } public String toSQL ( ConnectedDB database , AliasMap aliases ) { return "" + base . toSQL ( database , aliases ) + "" ; } public String toString ( ) { return "" + base + "" ; } } package de . fuberlin . wiwiss . d2rq . expr ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; public class Divide extends BinaryOperator { public Divide ( Expression expr1 , Expression expr2 ) { super ( expr1 , expr2 , "" ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new Divide ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } } package de . fuberlin . wiwiss . d2rq . expr ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; public class Add extends BinaryOperator { public Add ( Expression expr1 , Expression expr2 ) { super ( expr1 , expr2 , "" ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new Add ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Add ) ) { return false ; } Add otherAdd = ( Add ) other ; if ( expr1 . equals ( otherAdd . expr1 ) && expr2 . equals ( otherAdd . expr2 ) ) { return true ; } if ( expr1 . equals ( otherAdd . expr2 ) && expr2 . equals ( otherAdd . expr1 ) ) { return true ; } return false ; } } package de . fuberlin . wiwiss . d2rq . expr ; import de . fuberlin . wiwiss . d2rq . algebra . ColumnRenamer ; public class Multiply extends BinaryOperator { public Multiply ( Expression expr1 , Expression expr2 ) { super ( expr1 , expr2 , "" ) ; } public Expression renameAttributes ( ColumnRenamer columnRenamer ) { return new Multiply ( expr1 . renameAttributes ( columnRenamer ) , expr2 . renameAttributes ( columnRenamer ) ) ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Multiply ) ) { return false ; } Multiply otherMultiply = ( Multiply ) other ; if ( expr1 . equals ( otherMultiply . expr1 ) && expr2 . equals ( otherMultiply . expr2 ) ) { return true ; } if ( expr1 . equals ( otherMultiply . expr2 ) && expr2 . equals ( otherMultiply . expr1 ) ) { return true ; } return false ; } } package de . fuberlin . wiwiss . d2rq . map ; import java . io . IOException ; import java . net . URI ; import java . sql . SQLException ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import com . hp . hpl . jena . rdf . model . Resource ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType . GenericType ; import de . fuberlin . wiwiss . d2rq . sql . SQLScriptLoader ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class Database extends MapObject { public static final int NO_LIMIT = - ; public static final int NO_FETCH_SIZE = - ; private String jdbcDSN ; private String jdbcDriver ; private String username ; private String password ; private final Map < String , GenericType > columnTypes = new HashMap < String , GenericType > ( ) ; private int limit = NO_LIMIT ; private int fetchSize = NO_FETCH_SIZE ; private String startupSQLScript = null ; private ConnectedDB connection = null ; private Properties connectionProperties = new Properties ( ) ; public Database ( Resource resource ) { super ( resource ) ; } public void setJDBCDSN ( String jdbcDSN ) { assertNotYetDefined ( this . jdbcDSN , D2RQ . jdbcDSN , D2RQException . DATABASE_DUPLICATE_JDBCDSN ) ; checkNotConnected ( ) ; this . jdbcDSN = jdbcDSN ; } public String getJDBCDSN ( ) { return this . jdbcDSN ; } public void setJDBCDriver ( String jdbcDriver ) { assertNotYetDefined ( this . jdbcDriver , D2RQ . jdbcDriver , D2RQException . DATABASE_DUPLICATE_JDBCDRIVER ) ; checkNotConnected ( ) ; this . jdbcDriver = jdbcDriver ; } public String getJDBCDriver ( ) { return jdbcDriver ; } public void setUsername ( String username ) { assertNotYetDefined ( this . username , D2RQ . username , D2RQException . DATABASE_DUPLICATE_USERNAME ) ; checkNotConnected ( ) ; this . username = username ; } public String getUsername ( ) { return username ; } public void setPassword ( String password ) { assertNotYetDefined ( this . password , D2RQ . password , D2RQException . DATABASE_DUPLICATE_PASSWORD ) ; checkNotConnected ( ) ; this . password = password ; } public String getPassword ( ) { return password ; } public void addTextColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . CHARACTER ) ; } public void addNumericColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . NUMERIC ) ; } public void addBooleanColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . BOOLEAN ) ; } public void addDateColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . DATE ) ; } public void addTimestampColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . TIMESTAMP ) ; } public void addTimeColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . TIME ) ; } public void addBinaryColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . BINARY ) ; } public void addBitColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . BIT ) ; } public void addIntervalColumn ( String column ) { checkNotConnected ( ) ; columnTypes . put ( column , GenericType . INTERVAL ) ; } public void setResultSizeLimit ( int limit ) { checkNotConnected ( ) ; this . limit = limit ; } public int getResultSizeLimit ( ) { return limit ; } public int getFetchSize ( ) { return this . fetchSize ; } public void setFetchSize ( int fetchSize ) { checkNotConnected ( ) ; this . fetchSize = fetchSize ; } public void setStartupSQLScript ( Resource script ) { checkNotConnected ( ) ; assertNotYetDefined ( startupSQLScript , D2RQ . startupSQLScript , D2RQException . DATABASE_DUPLICATE_STARTUPSCRIPT ) ; startupSQLScript = script . getURI ( ) ; } public void setConnectionProperty ( String key , String value ) { checkNotConnected ( ) ; this . connectionProperties . setProperty ( key , value ) ; } public void useConnectedDB ( ConnectedDB db ) { this . connection = db ; } public ConnectedDB connectedDB ( ) { if ( this . connection == null ) { if ( jdbcDriver != null ) { ConnectedDB . registerJDBCDriver ( jdbcDriver ) ; } connection = new ConnectedDB ( jdbcDSN , username , password , columnTypes , limit , fetchSize , connectionProperties ) ; if ( startupSQLScript != null ) { try { URI url = URI . create ( startupSQLScript ) ; SQLScriptLoader . loadURI ( url , connection . connection ( ) ) ; } catch ( IOException ex ) { connection . close ( ) ; throw new D2RQException ( ex ) ; } catch ( SQLException ex ) { connection . close ( ) ; throw new D2RQException ( ex ) ; } } } return connection ; } public String toString ( ) { return "" + super . toString ( ) ; } public void validate ( ) throws D2RQException { if ( this . jdbcDSN == null ) { throw new D2RQException ( "" , D2RQException . DATABASE_MISSING_DSN ) ; } if ( this . jdbcDSN != null && this . jdbcDriver == null ) { throw new D2RQException ( "" , D2RQException . DATABASE_MISSING_JDBCDRIVER ) ; } } private void checkNotConnected ( ) { if ( this . connection != null ) { throw new D2RQException ( "" , D2RQException . DATABASE_ALREADY_CONNECTED ) ; } } } package de . fuberlin . wiwiss . d2rq . map ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . rdf . model . Literal ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . shared . PrefixMapping ; import com . hp . hpl . jena . shared . impl . PrefixMappingImpl ; import com . hp . hpl . jena . vocabulary . RDF ; import com . hp . hpl . jena . vocabulary . RDFS ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class Mapping { private static final Log log = LogFactory . getLog ( Mapping . class ) ; private final Model model = ModelFactory . createDefaultModel ( ) ; private final Model vocabularyModel = ModelFactory . createDefaultModel ( ) ; private Resource mappingResource ; private final Map < Resource , Database > databases = new HashMap < Resource , Database > ( ) ; private Configuration configuration = new Configuration ( ) ; private final Map < Resource , ClassMap > classMaps = new HashMap < Resource , ClassMap > ( ) ; private final Map < Resource , TranslationTable > translationTables = new HashMap < Resource , TranslationTable > ( ) ; private final Map < Resource , DownloadMap > downloadMaps = new HashMap < Resource , DownloadMap > ( ) ; private final PrefixMapping prefixes = new PrefixMappingImpl ( ) ; private Collection < TripleRelation > compiledPropertyBridges ; public Mapping ( ) { this ( null ) ; } public Mapping ( String mappingURI ) { if ( mappingURI == null ) { this . mappingResource = this . model . createResource ( ) ; } else { this . mappingResource = this . model . createResource ( mappingURI ) ; } } public Resource resource ( ) { return this . mappingResource ; } public Model getVocabularyModel ( ) { return vocabularyModel ; } public void validate ( ) throws D2RQException { if ( this . databases . isEmpty ( ) ) { throw new D2RQException ( "" , D2RQException . MAPPING_NO_DATABASE ) ; } for ( Database db : databases . values ( ) ) { db . validate ( ) ; } for ( TranslationTable table : translationTables . values ( ) ) { table . validate ( ) ; } Collection < ClassMap > classMapsWithoutProperties = new ArrayList < ClassMap > ( classMaps . values ( ) ) ; for ( ClassMap classMap : classMaps . values ( ) ) { classMap . validate ( ) ; if ( classMap . hasProperties ( ) ) { classMapsWithoutProperties . remove ( classMap ) ; } for ( PropertyBridge bridge : classMap . propertyBridges ( ) ) { if ( bridge . refersToClassMap ( ) != null ) { classMapsWithoutProperties . remove ( bridge . refersToClassMap ( ) ) ; } } } if ( ! classMapsWithoutProperties . isEmpty ( ) ) { throw new D2RQException ( classMapsWithoutProperties . iterator ( ) . next ( ) . toString ( ) + "" , D2RQException . CLASSMAP_NO_PROPERTYBRIDGES ) ; } for ( DownloadMap dlm : downloadMaps . values ( ) ) { dlm . validate ( ) ; } for ( TripleRelation bridge : compiledPropertyBridges ( ) ) { new AttributeTypeValidator ( bridge ) . validate ( ) ; } } public void connect ( ) { if ( connected ) return ; connected = true ; for ( Database db : databases ( ) ) { db . connectedDB ( ) . connection ( ) ; } validate ( ) ; } private boolean connected = false ; public void close ( ) { for ( Database db : databases ( ) ) { db . connectedDB ( ) . close ( ) ; } } public void addDatabase ( Database database ) { this . databases . put ( database . resource ( ) , database ) ; } public Collection < Database > databases ( ) { return this . databases . values ( ) ; } public Database database ( Resource name ) { return databases . get ( name ) ; } public Configuration configuration ( ) { return this . configuration ; } public void setConfiguration ( Configuration configuration ) { this . configuration = configuration ; } public void addClassMap ( ClassMap classMap ) { this . classMaps . put ( classMap . resource ( ) , classMap ) ; } public Collection < Resource > classMapResources ( ) { return this . classMaps . keySet ( ) ; } public ClassMap classMap ( Resource name ) { return ( ClassMap ) this . classMaps . get ( name ) ; } public void addTranslationTable ( TranslationTable table ) { this . translationTables . put ( table . resource ( ) , table ) ; } public TranslationTable translationTable ( Resource name ) { return ( TranslationTable ) this . translationTables . get ( name ) ; } public void addDownloadMap ( DownloadMap downloadMap ) { downloadMaps . put ( downloadMap . resource ( ) , downloadMap ) ; } public Collection < Resource > downloadMapResources ( ) { return downloadMaps . keySet ( ) ; } public DownloadMap downloadMap ( Resource name ) { return downloadMaps . get ( name ) ; } public synchronized Collection < TripleRelation > compiledPropertyBridges ( ) { if ( this . compiledPropertyBridges == null ) { compilePropertyBridges ( ) ; } return this . compiledPropertyBridges ; } private void compilePropertyBridges ( ) { compiledPropertyBridges = new ArrayList < TripleRelation > ( ) ; for ( ClassMap classMap : classMaps . values ( ) ) { this . compiledPropertyBridges . addAll ( classMap . compiledPropertyBridges ( ) ) ; } log . info ( "" + compiledPropertyBridges . size ( ) + "" ) ; if ( log . isDebugEnabled ( ) ) { for ( TripleRelation rel : compiledPropertyBridges ) { log . debug ( rel ) ; } } } public PrefixMapping getPrefixMapping ( ) { return prefixes ; } private class AttributeTypeValidator { private final Relation relation ; AttributeTypeValidator ( TripleRelation relation ) { this . relation = relation . baseRelation ( ) ; } void validate ( ) { for ( Attribute attribute : relation . allKnownAttributes ( ) ) { DataType dataType = relation . database ( ) . columnType ( relation . aliases ( ) . originalOf ( attribute ) ) ; if ( dataType == null ) { throw new D2RQException ( "" + relation . aliases ( ) . originalOf ( attribute ) + "" , D2RQException . DATATYPE_UNKNOWN ) ; } if ( dataType . isUnsupported ( ) ) { throw new D2RQException ( "" + relation . aliases ( ) . originalOf ( attribute ) + "" + dataType , D2RQException . DATATYPE_UNMAPPABLE ) ; } } } } private void addDefinitions ( ResourceMap map , Resource targetResource ) { Statement s = vocabularyModel . createStatement ( targetResource , RDF . type , map instanceof ClassMap ? RDFS . Class : RDF . Property ) ; if ( ! this . vocabularyModel . contains ( s ) ) this . vocabularyModel . add ( s ) ; for ( Literal propertyLabel : map . getDefinitionLabels ( ) ) { s = vocabularyModel . createStatement ( targetResource , RDFS . label , propertyLabel ) ; if ( ! this . vocabularyModel . contains ( s ) ) this . vocabularyModel . add ( s ) ; } for ( Literal propertyComment : map . getDefinitionComments ( ) ) { s = vocabularyModel . createStatement ( targetResource , RDFS . comment , propertyComment ) ; if ( ! this . vocabularyModel . contains ( s ) ) this . vocabularyModel . add ( s ) ; } for ( Resource additionalProperty : map . getAdditionalDefinitionProperties ( ) ) { s = vocabularyModel . createStatement ( targetResource , ( Property ) ( additionalProperty . getProperty ( D2RQ . propertyName ) . getResource ( ) . as ( Property . class ) ) , additionalProperty . getProperty ( D2RQ . propertyValue ) . getObject ( ) ) ; if ( ! this . vocabularyModel . contains ( s ) ) this . vocabularyModel . add ( s ) ; } } public void buildVocabularyModel ( ) { for ( ClassMap classMap : classMaps . values ( ) ) { for ( Resource class_ : classMap . getClasses ( ) ) { addDefinitions ( classMap , class_ ) ; } for ( PropertyBridge bridge : classMap . propertyBridges ( ) ) { for ( Resource property : bridge . properties ( ) ) { addDefinitions ( bridge , property ) ; } } } } } package de . fuberlin . wiwiss . d2rq . map ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . datatypes . TypeMapper ; import com . hp . hpl . jena . rdf . model . Literal ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . RDFNode ; import com . hp . hpl . jena . rdf . model . Resource ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . expr . SQLExpression ; import de . fuberlin . wiwiss . d2rq . nodes . FixedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . TypedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . TypedNodeMaker . NodeType ; import de . fuberlin . wiwiss . d2rq . parser . MapParser ; import de . fuberlin . wiwiss . d2rq . parser . RelationBuilder ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . values . BlankNodeID ; import de . fuberlin . wiwiss . d2rq . values . Column ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; import de . fuberlin . wiwiss . d2rq . values . SQLExpressionValueMaker ; import de . fuberlin . wiwiss . d2rq . values . ValueDecorator ; import de . fuberlin . wiwiss . d2rq . values . ValueDecorator . ValueConstraint ; import de . fuberlin . wiwiss . d2rq . values . ValueMaker ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public abstract class ResourceMap extends MapObject { protected String bNodeIdColumns = null ; protected String uriColumn = null ; protected String uriPattern = null ; protected RDFNode constantValue = null ; protected Collection < String > valueRegexes = new ArrayList < String > ( ) ; protected Collection < String > valueContainses = new ArrayList < String > ( ) ; protected int valueMaxLength = Integer . MAX_VALUE ; protected Collection < String > joins = new ArrayList < String > ( ) ; protected Collection < String > conditions = new ArrayList < String > ( ) ; protected Collection < String > aliases = new ArrayList < String > ( ) ; protected boolean containsDuplicates ; protected TranslationTable translateWith = null ; protected String column = null ; protected String pattern = null ; protected String sqlExpression = null ; protected String uriSqlExpression = null ; protected String datatype = null ; protected String lang = null ; protected ClassMap refersToClassMap = null ; protected Integer limit = null ; protected Integer limitInverse = null ; protected String order = null ; protected Boolean orderDesc = null ; private NodeMaker cachedNodeMaker ; private Relation cachedRelation ; Collection < Literal > definitionLabels = new ArrayList < Literal > ( ) ; Collection < Literal > definitionComments = new ArrayList < Literal > ( ) ; Collection < Resource > additionalDefinitionProperties = new ArrayList < Resource > ( ) ; public ResourceMap ( Resource resource , boolean defaultContainsDuplicate ) { super ( resource ) ; this . containsDuplicates = defaultContainsDuplicate ; } public void setBNodeIdColumns ( String columns ) { assertNotYetDefined ( this . bNodeIdColumns , D2RQ . bNodeIdColumns , D2RQException . RESOURCEMAP_DUPLICATE_BNODEIDCOLUMNS ) ; this . bNodeIdColumns = columns ; } public void setURIColumn ( String column ) { assertNotYetDefined ( this . uriColumn , D2RQ . uriColumn , D2RQException . RESOURCEMAP_DUPLICATE_URICOLUMN ) ; this . uriColumn = column ; } public void setURIPattern ( String pattern ) { assertNotYetDefined ( this . uriColumn , D2RQ . uriPattern , D2RQException . RESOURCEMAP_DUPLICATE_URIPATTERN ) ; this . uriPattern = pattern ; } public void setUriSQLExpression ( String uriSqlExpression ) { assertNotYetDefined ( this . column , D2RQ . uriSqlExpression , D2RQException . PROPERTYBRIDGE_DUPLICATE_URI_SQL_EXPRESSION ) ; this . uriSqlExpression = uriSqlExpression ; } public void setConstantValue ( RDFNode constantValue ) { assertNotYetDefined ( this . constantValue , D2RQ . constantValue , D2RQException . RESOURCEMAP_DUPLICATE_CONSTANTVALUE ) ; this . constantValue = constantValue ; } public void addValueRegex ( String regex ) { this . valueRegexes . add ( regex ) ; } public void addValueContains ( String contains ) { this . valueContainses . add ( contains ) ; } public void setValueMaxLength ( int maxLength ) { if ( this . valueMaxLength != Integer . MAX_VALUE ) { assertNotYetDefined ( this , D2RQ . valueMaxLength , D2RQException . PROPERTYBRIDGE_DUPLICATE_VALUEMAXLENGTH ) ; } this . valueMaxLength = maxLength ; } public void setTranslateWith ( TranslationTable table ) { assertNotYetDefined ( this . translateWith , D2RQ . translateWith , D2RQException . RESOURCEMAP_DUPLICATE_TRANSLATEWITH ) ; assertArgumentNotNull ( table , D2RQ . translateWith , D2RQException . RESOURCEMAP_INVALID_TRANSLATEWITH ) ; this . translateWith = table ; } public void addJoin ( String join ) { this . joins . add ( join ) ; } public void addCondition ( String condition ) { this . conditions . add ( condition ) ; } public void addAlias ( String alias ) { this . aliases . add ( alias ) ; } public void setContainsDuplicates ( boolean b ) { this . containsDuplicates = b ; } private Collection < Alias > aliases ( ) { Set < Alias > parsedAliases = new HashSet < Alias > ( ) ; for ( String alias : aliases ) { parsedAliases . add ( SQL . parseAlias ( alias ) ) ; } return parsedAliases ; } public RelationBuilder relationBuilder ( ConnectedDB database ) { RelationBuilder result = new RelationBuilder ( database ) ; for ( Join join : SQL . parseJoins ( joins ) ) { result . addJoinCondition ( join ) ; } for ( String condition : conditions ) { result . addCondition ( condition ) ; } result . addAliases ( aliases ( ) ) ; for ( ProjectionSpec projection : nodeMaker ( ) . projectionSpecs ( ) ) { result . addProjection ( projection ) ; } if ( ! containsDuplicates ) { result . setIsUnique ( true ) ; } return result ; } public Relation relation ( ) { if ( this . cachedRelation == null ) { this . cachedRelation = buildRelation ( ) ; } return this . cachedRelation ; } protected abstract Relation buildRelation ( ) ; public NodeMaker nodeMaker ( ) { if ( this . cachedNodeMaker == null ) { this . cachedNodeMaker = buildNodeMaker ( ) ; } return this . cachedNodeMaker ; } private NodeMaker buildNodeMaker ( ) { if ( this . constantValue != null ) { return new FixedNodeMaker ( this . constantValue . asNode ( ) , ! this . containsDuplicates ) ; } if ( this . refersToClassMap == null ) { return buildNodeMaker ( wrapValueSource ( buildValueSourceBase ( ) ) , ! this . containsDuplicates ) ; } return this . refersToClassMap . buildAliasedNodeMaker ( new AliasMap ( aliases ( ) ) , ! this . containsDuplicates ) ; } public NodeMaker buildAliasedNodeMaker ( AliasMap aliases , boolean unique ) { ValueMaker values = wrapValueSource ( buildValueSourceBase ( ) ) . renameAttributes ( aliases ) ; return buildNodeMaker ( values , unique ) ; } private ValueMaker buildValueSourceBase ( ) { if ( this . bNodeIdColumns != null ) { return new BlankNodeID ( PrettyPrinter . toString ( this . resource ( ) ) , parseColumnList ( this . bNodeIdColumns ) ) ; } if ( this . uriColumn != null ) { return new Column ( SQL . parseAttribute ( this . uriColumn ) ) ; } if ( this . uriPattern != null ) { Pattern p = new Pattern ( this . uriPattern ) ; if ( ! p . literalPartsMatchRegex ( MapParser . IRI_CHAR_REGEX ) ) { throw new D2RQException ( "" + this . uriPattern + "" , D2RQException . RESOURCEMAP_ILLEGAL_URIPATTERN ) ; } return p ; } if ( this . column != null ) { return new Column ( SQL . parseAttribute ( this . column ) ) ; } if ( this . pattern != null ) { return new Pattern ( this . pattern ) ; } if ( this . sqlExpression != null ) { return new SQLExpressionValueMaker ( SQLExpression . create ( sqlExpression ) ) ; } if ( this . uriSqlExpression != null ) { return new SQLExpressionValueMaker ( SQLExpression . create ( uriSqlExpression ) ) ; } throw new D2RQException ( this + "" ) ; } public ValueMaker wrapValueSource ( ValueMaker values ) { List < ValueConstraint > constraints = new ArrayList < ValueConstraint > ( ) ; if ( this . valueMaxLength != Integer . MAX_VALUE ) { constraints . add ( ValueDecorator . maxLengthConstraint ( this . valueMaxLength ) ) ; } for ( String contains : valueContainses ) { constraints . add ( ValueDecorator . containsConstraint ( contains ) ) ; } for ( String regex : valueRegexes ) { constraints . add ( ValueDecorator . regexConstraint ( regex ) ) ; } if ( this . translateWith == null ) { if ( constraints . isEmpty ( ) ) { return values ; } return new ValueDecorator ( values , constraints ) ; } return new ValueDecorator ( values , constraints , this . translateWith . translator ( ) ) ; } private NodeMaker buildNodeMaker ( ValueMaker values , boolean isUnique ) { return new TypedNodeMaker ( nodeType ( ) , values , isUnique ) ; } private NodeType nodeType ( ) { if ( this . bNodeIdColumns != null ) { return TypedNodeMaker . BLANK ; } if ( this . uriColumn != null || this . uriPattern != null ) { return TypedNodeMaker . URI ; } if ( this . uriSqlExpression != null ) { return TypedNodeMaker . URI ; } if ( this . column == null && this . pattern == null && this . sqlExpression == null ) { throw new D2RQException ( this + "" ) ; } if ( this . datatype != null && this . lang != null ) { throw new D2RQException ( this + "" ) ; } if ( this . datatype != null ) { return TypedNodeMaker . typedLiteral ( buildDatatype ( this . datatype ) ) ; } if ( this . lang != null ) { return TypedNodeMaker . languageLiteral ( this . lang ) ; } return TypedNodeMaker . PLAIN_LITERAL ; } private RDFDatatype buildDatatype ( String datatypeURI ) { return TypeMapper . getInstance ( ) . getSafeTypeByName ( datatypeURI ) ; } private List < Attribute > parseColumnList ( String commaSeperated ) { List < Attribute > result = new ArrayList < Attribute > ( ) ; for ( String attr : Arrays . asList ( commaSeperated . split ( "" ) ) ) { result . add ( SQL . parseAttribute ( attr ) ) ; } return result ; } protected void assertHasPrimarySpec ( Property [ ] allowedSpecs ) { List < Property > definedSpecs = new ArrayList < Property > ( ) ; for ( Property allowedProperty : Arrays . asList ( allowedSpecs ) ) { if ( hasPrimarySpec ( allowedProperty ) ) { definedSpecs . add ( allowedProperty ) ; } } if ( definedSpecs . isEmpty ( ) ) { StringBuffer error = new StringBuffer ( toString ( ) ) ; error . append ( "" ) ; for ( int i = ; i < allowedSpecs . length ; i ++ ) { if ( i > ) { error . append ( "" ) ; } error . append ( PrettyPrinter . toString ( allowedSpecs [ i ] ) ) ; } throw new D2RQException ( error . toString ( ) , D2RQException . RESOURCEMAP_MISSING_PRIMARYSPEC ) ; } if ( definedSpecs . size ( ) > ) { throw new D2RQException ( toString ( ) + "" + PrettyPrinter . toString ( ( Property ) definedSpecs . get ( ) ) + "" + PrettyPrinter . toString ( ( Property ) definedSpecs . get ( ) ) ) ; } } private boolean hasPrimarySpec ( Property property ) { if ( property . equals ( D2RQ . bNodeIdColumns ) ) return this . bNodeIdColumns != null ; if ( property . equals ( D2RQ . uriColumn ) ) return this . uriColumn != null ; if ( property . equals ( D2RQ . uriPattern ) ) return this . uriPattern != null ; if ( property . equals ( D2RQ . column ) ) return this . column != null ; if ( property . equals ( D2RQ . pattern ) ) return this . pattern != null ; if ( property . equals ( D2RQ . sqlExpression ) ) return this . sqlExpression != null ; if ( property . equals ( D2RQ . uriSqlExpression ) ) return this . uriSqlExpression != null ; if ( property . equals ( D2RQ . refersToClassMap ) ) return this . refersToClassMap != null ; if ( property . equals ( D2RQ . constantValue ) ) return this . constantValue != null ; throw new D2RQException ( "" + property ) ; } public Collection < Literal > getDefinitionLabels ( ) { return definitionLabels ; } public Collection < Literal > getDefinitionComments ( ) { return definitionComments ; } public Collection < Resource > getAdditionalDefinitionProperties ( ) { return additionalDefinitionProperties ; } public void addDefinitionLabel ( Literal definitionLabel ) { definitionLabels . add ( definitionLabel ) ; } public void addDefinitionComment ( Literal definitionComment ) { definitionComments . add ( definitionComment ) ; } public void addDefinitionProperty ( Resource additionalProperty ) { additionalDefinitionProperties . add ( additionalProperty ) ; } } package de . fuberlin . wiwiss . d2rq . map ; import com . hp . hpl . jena . rdf . model . Resource ; import de . fuberlin . wiwiss . d2rq . D2RQException ; public class Configuration extends MapObject { private boolean serveVocabulary = true ; private boolean useAllOptimizations = false ; public Configuration ( ) { this ( null ) ; } public Configuration ( Resource resource ) { super ( resource ) ; } public boolean getServeVocabulary ( ) { return this . serveVocabulary ; } public void setServeVocabulary ( boolean serveVocabulary ) { this . serveVocabulary = serveVocabulary ; } public boolean getUseAllOptimizations ( ) { return this . useAllOptimizations ; } public void setUseAllOptimizations ( boolean useAllOptimizations ) { this . useAllOptimizations = useAllOptimizations ; } public String toString ( ) { return "" + super . toString ( ) ; } public void validate ( ) throws D2RQException { } } package de . fuberlin . wiwiss . d2rq . map ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; public class PropertyMap extends ResourceMap { private Database database ; public PropertyMap ( String uriPattern , Database database ) { super ( null , true ) ; setURIPattern ( uriPattern ) ; this . database = database ; } @ Override protected Relation buildRelation ( ) { return relationBuilder ( database . connectedDB ( ) ) . buildRelation ( ) ; } @ Override public void validate ( ) throws D2RQException { } public String toString ( ) { return "" + this . uriPattern + "" ; } } package de . fuberlin . wiwiss . d2rq . map ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . Resource ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; public abstract class MapObject { private Resource resource ; public MapObject ( Resource resource ) { this . resource = resource ; } public Resource resource ( ) { return this . resource ; } public abstract void validate ( ) throws D2RQException ; public String toString ( ) { return PrettyPrinter . toString ( this . resource ) ; } protected void assertNotYetDefined ( Object object , Property property , int errorCode ) { if ( object == null ) { return ; } throw new D2RQException ( "" + PrettyPrinter . toString ( property ) + "" + this , errorCode ) ; } protected void assertHasBeenDefined ( Object object , Property property , int errorCode ) { if ( object != null ) { return ; } throw new D2RQException ( "" + PrettyPrinter . toString ( property ) + "" + this , errorCode ) ; } protected void assertArgumentNotNull ( Object object , Property property , int errorCode ) { if ( object != null ) { return ; } throw new D2RQException ( "" + PrettyPrinter . toString ( property ) + "" + this , errorCode ) ; } } package de . fuberlin . wiwiss . d2rq . map ; import java . util . ArrayList ; import java . util . Collection ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class ClassMap extends ResourceMap { private Resource resource ; private Database database = null ; private Collection < Resource > classes = new ArrayList < Resource > ( ) ; private Collection < PropertyBridge > propertyBridges = new ArrayList < PropertyBridge > ( ) ; private Collection < TripleRelation > compiledPropertyBridges = null ; private Log log = LogFactory . getLog ( ClassMap . class ) ; public ClassMap ( Resource classMapResource ) { super ( classMapResource , false ) ; this . resource = classMapResource ; } public Resource resource ( ) { return this . resource ; } public Collection < Resource > getClasses ( ) { return classes ; } public void setDatabase ( Database database ) { assertNotYetDefined ( this . database , D2RQ . dataStorage , D2RQException . CLASSMAP_DUPLICATE_DATABASE ) ; assertArgumentNotNull ( database , D2RQ . dataStorage , D2RQException . CLASSMAP_INVALID_DATABASE ) ; this . database = database ; } public Database database ( ) { return this . database ; } public void addClass ( Resource class_ ) { this . classes . add ( class_ ) ; } public void addPropertyBridge ( PropertyBridge bridge ) { this . propertyBridges . add ( bridge ) ; } public Collection < PropertyBridge > propertyBridges ( ) { return this . propertyBridges ; } public void validate ( ) throws D2RQException { assertHasBeenDefined ( this . database , D2RQ . dataStorage , D2RQException . CLASSMAP_NO_DATABASE ) ; assertHasPrimarySpec ( new Property [ ] { D2RQ . uriColumn , D2RQ . uriPattern , D2RQ . uriSqlExpression , D2RQ . bNodeIdColumns , D2RQ . constantValue } ) ; if ( this . constantValue != null && this . constantValue . isLiteral ( ) ) { throw new D2RQException ( "" + toString ( ) + "" , D2RQException . CLASSMAP_INVALID_CONSTANTVALUE ) ; } if ( this . uriPattern != null && new Pattern ( uriPattern ) . attributes ( ) . size ( ) == ) { this . log . warn ( toString ( ) + "" + "" ) ; } for ( PropertyBridge bridge : propertyBridges ) { bridge . validate ( ) ; } } public boolean hasProperties ( ) { return ( ! this . classes . isEmpty ( ) || ! this . propertyBridges . isEmpty ( ) ) ; } public Collection < TripleRelation > compiledPropertyBridges ( ) { if ( this . compiledPropertyBridges == null ) { compile ( ) ; } return this . compiledPropertyBridges ; } private void compile ( ) { this . compiledPropertyBridges = new ArrayList < TripleRelation > ( ) ; for ( PropertyBridge bridge : propertyBridges ) { this . compiledPropertyBridges . addAll ( bridge . toTripleRelations ( ) ) ; } for ( Resource class_ : classes ) { PropertyBridge bridge = new PropertyBridge ( this . resource ) ; bridge . setBelongsToClassMap ( this ) ; bridge . addProperty ( RDF . type ) ; bridge . setConstantValue ( class_ ) ; this . compiledPropertyBridges . addAll ( bridge . toTripleRelations ( ) ) ; } } protected Relation buildRelation ( ) { return this . relationBuilder ( database . connectedDB ( ) ) . buildRelation ( ) ; } public String toString ( ) { return "" + PrettyPrinter . toString ( this . resource ) ; } } package de . fuberlin . wiwiss . d2rq . map ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . Resource ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . parser . RelationBuilder ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . values . ConstantValueMaker ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; import de . fuberlin . wiwiss . d2rq . values . ValueMaker ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class DownloadMap extends ResourceMap { private final static Log log = LogFactory . getLog ( DownloadMap . class ) ; private ClassMap belongsToClassMap = null ; private Database database = null ; private String mediaType = null ; private Attribute contentDownloadColumn = null ; public DownloadMap ( Resource downloadMapResource ) { super ( downloadMapResource , false ) ; } public void setBelongsToClassMap ( ClassMap classMap ) { assertNotYetDefined ( belongsToClassMap , D2RQ . belongsToClassMap , D2RQException . DOWNLOADMAP_DUPLICATE_BELONGSTOCLASSMAP ) ; assertArgumentNotNull ( classMap , D2RQ . belongsToClassMap , D2RQException . DOWNLOADMAP_INVALID_BELONGSTOCLASSMAP ) ; belongsToClassMap = classMap ; } public void setDatabase ( Database database ) { assertNotYetDefined ( this . database , D2RQ . dataStorage , D2RQException . DOWNLOADMAP_DUPLICATE_DATABASE ) ; assertArgumentNotNull ( database , D2RQ . dataStorage , D2RQException . DOWNLOADMAP_INVALID_DATABASE ) ; this . database = database ; } public void setMediaType ( String mediaType ) { assertNotYetDefined ( this . mediaType , D2RQ . mediaType , D2RQException . DOWNLOADMAP_DUPLICATE_MEDIATYPE ) ; this . mediaType = mediaType ; } public void setContentDownloadColumn ( String contentColumn ) { assertNotYetDefined ( this . contentDownloadColumn , D2RQ . contentDownloadColumn , D2RQException . DOWNLOADMAP_DUPLICATE_CONTENTCOLUMN ) ; this . contentDownloadColumn = SQL . parseAttribute ( contentColumn ) ; } @ Override public void validate ( ) throws D2RQException { assertHasPrimarySpec ( new Property [ ] { D2RQ . uriColumn , D2RQ . uriPattern , D2RQ . constantValue } ) ; if ( database == null && belongsToClassMap == null ) { throw new D2RQException ( "" + toString ( ) + "" , D2RQException . DOWNLOADMAP_NO_DATASTORAGE ) ; } assertHasBeenDefined ( contentDownloadColumn , D2RQ . contentDownloadColumn , D2RQException . DOWNLOADMAP_NO_CONTENTCOLUMN ) ; if ( this . constantValue != null && ! this . constantValue . isURIResource ( ) ) { throw new D2RQException ( "" + toString ( ) + "" , D2RQException . DOWNLOADMAP_INVALID_CONSTANTVALUE ) ; } if ( this . uriPattern != null && new Pattern ( uriPattern ) . attributes ( ) . size ( ) == ) { log . warn ( toString ( ) + "" + "" ) ; } } @ Override protected Relation buildRelation ( ) { Database db = belongsToClassMap == null ? database : belongsToClassMap . database ( ) ; RelationBuilder builder = relationBuilder ( db . connectedDB ( ) ) ; builder . addProjection ( contentDownloadColumn ) ; for ( ProjectionSpec projection : getMediaTypeValueMaker ( ) . projectionSpecs ( ) ) { builder . addProjection ( projection ) ; } if ( belongsToClassMap != null ) { builder . addOther ( belongsToClassMap . relationBuilder ( db . connectedDB ( ) ) ) ; } return builder . buildRelation ( ) ; } public Relation getRelation ( ) { validate ( ) ; return buildRelation ( ) ; } public ValueMaker getMediaTypeValueMaker ( ) { if ( mediaType == null ) return ValueMaker . NULL ; Pattern pattern = new Pattern ( mediaType ) ; if ( pattern . attributes ( ) . isEmpty ( ) ) { return new ConstantValueMaker ( mediaType ) ; } return pattern ; } public Attribute getContentDownloadColumn ( ) { return contentDownloadColumn ; } } package de . fuberlin . wiwiss . d2rq . map ; import java . lang . reflect . Constructor ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import com . hp . hpl . jena . rdf . model . Resource ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . csv . TranslationTableParser ; import de . fuberlin . wiwiss . d2rq . values . Translator ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class TranslationTable extends MapObject { private Collection < Translation > translations = new ArrayList < Translation > ( ) ; private String javaClass = null ; private String href = null ; public TranslationTable ( Resource resource ) { super ( resource ) ; } public int size ( ) { return this . translations . size ( ) ; } public void addTranslation ( String dbValue , String rdfValue ) { assertArgumentNotNull ( dbValue , D2RQ . databaseValue , D2RQException . TRANSLATION_MISSING_DBVALUE ) ; assertArgumentNotNull ( rdfValue , D2RQ . rdfValue , D2RQException . TRANSLATION_MISSING_RDFVALUE ) ; this . translations . add ( new Translation ( dbValue , rdfValue ) ) ; } public void setJavaClass ( String className ) { assertNotYetDefined ( this . javaClass , D2RQ . javaClass , D2RQException . TRANSLATIONTABLE_DUPLICATE_JAVACLASS ) ; this . javaClass = className ; } public void setHref ( String href ) { assertNotYetDefined ( this . href , D2RQ . href , D2RQException . TRANSLATIONTABLE_DUPLICATE_HREF ) ; this . href = href ; } public Translator translator ( ) { validate ( ) ; if ( this . javaClass != null ) { return instantiateJavaClass ( ) ; } if ( this . href != null ) { return new TableTranslator ( new TranslationTableParser ( href ) . parseTranslations ( ) ) ; } return new TableTranslator ( this . translations ) ; } public void validate ( ) throws D2RQException { if ( ! this . translations . isEmpty ( ) && this . javaClass != null ) { throw new D2RQException ( "" + this , D2RQException . TRANSLATIONTABLE_TRANSLATION_AND_JAVACLASS ) ; } if ( ! this . translations . isEmpty ( ) && this . href != null ) { throw new D2RQException ( "" + this , D2RQException . TRANSLATIONTABLE_TRANSLATION_AND_HREF ) ; } if ( this . href != null && this . javaClass != null ) { throw new D2RQException ( "" + this , D2RQException . TRANSLATIONTABLE_HREF_AND_JAVACLASS ) ; } } public String toString ( ) { return "" + super . toString ( ) ; } private Translator instantiateJavaClass ( ) { try { Class < ? > translatorClass = Class . forName ( this . javaClass ) ; if ( ! checkTranslatorClassImplementation ( translatorClass ) ) { throw new D2RQException ( "" + this . javaClass + "" + Translator . class . getName ( ) ) ; } if ( hasConstructorWithArg ( translatorClass ) ) { return invokeConstructorWithArg ( translatorClass , resource ( ) ) ; } if ( hasConstructorWithoutArg ( translatorClass ) ) { return invokeConstructorWithoutArg ( translatorClass ) ; } throw new D2RQException ( "" + this . javaClass ) ; } catch ( ClassNotFoundException e ) { throw new D2RQException ( "" + this . javaClass ) ; } } private boolean checkTranslatorClassImplementation ( Class < ? > translatorClass ) { if ( implementsTranslator ( translatorClass ) ) { return true ; } if ( translatorClass . getSuperclass ( ) == null ) { return false ; } return this . checkTranslatorClassImplementation ( translatorClass . getSuperclass ( ) ) ; } private boolean implementsTranslator ( Class < ? > aClass ) { for ( int i = ; i < aClass . getInterfaces ( ) . length ; i ++ ) { if ( aClass . getInterfaces ( ) [ i ] . equals ( Translator . class ) ) { return true ; } } return false ; } private boolean hasConstructorWithArg ( Class < ? > aClass ) { try { aClass . getConstructor ( new Class [ ] { Resource . class } ) ; return true ; } catch ( NoSuchMethodException nsmex ) { return false ; } } private Translator invokeConstructorWithArg ( Class < ? > aClass , Resource r ) { try { Constructor < ? > c = aClass . getConstructor ( new Class [ ] { Resource . class } ) ; return ( Translator ) c . newInstance ( new Object [ ] { r } ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } private boolean hasConstructorWithoutArg ( Class < ? > aClass ) { try { aClass . getConstructor ( new Class [ ] { } ) ; return true ; } catch ( NoSuchMethodException nsmex ) { return false ; } } private Translator invokeConstructorWithoutArg ( Class < ? > aClass ) { try { Constructor < ? > c = aClass . getConstructor ( new Class [ ] { } ) ; return ( Translator ) c . newInstance ( new Object [ ] { } ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } public static class Translation { private String dbValue ; private String rdfValue ; public Translation ( String dbValue , String rdfValue ) { this . dbValue = dbValue ; this . rdfValue = rdfValue ; } public String dbValue ( ) { return this . dbValue ; } public String rdfValue ( ) { return this . rdfValue ; } public int hashCode ( ) { return this . dbValue . hashCode ( ) ^ this . rdfValue . hashCode ( ) ; } public boolean equals ( Object otherObject ) { if ( ! ( otherObject instanceof Translation ) ) return false ; Translation other = ( Translation ) otherObject ; return this . dbValue . equals ( other . dbValue ) && this . rdfValue . equals ( other . rdfValue ) ; } public String toString ( ) { return "" + this . dbValue + "" + this . rdfValue + "" ; } } private class TableTranslator implements Translator { private Map < String , Translation > translationsByDBValue = new HashMap < String , Translation > ( ) ; private Map < String , Translation > translationsByRDFValue = new HashMap < String , Translation > ( ) ; TableTranslator ( Collection < Translation > translations ) { for ( Translation translation : translations ) { translationsByDBValue . put ( translation . dbValue , translation ) ; translationsByRDFValue . put ( translation . rdfValue , translation ) ; } } public String toDBValue ( String rdfValue ) { Translation translation = translationsByRDFValue . get ( rdfValue ) ; return ( translation == null ) ? null : translation . dbValue ( ) ; } public String toRDFValue ( String dbValue ) { Translation translation = translationsByDBValue . get ( dbValue ) ; return ( translation == null ) ? null : translation . rdfValue ( ) ; } } } package de . fuberlin . wiwiss . d2rq . map ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import com . hp . hpl . jena . rdf . model . Property ; import com . hp . hpl . jena . rdf . model . Resource ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . nodes . FixedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . parser . RelationBuilder ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . SQL ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class PropertyBridge extends ResourceMap { private Resource resource ; private ClassMap belongsToClassMap = null ; private Collection < Resource > properties = new HashSet < Resource > ( ) ; private Collection < String > dynamicPropertyPatterns = new HashSet < String > ( ) ; public PropertyBridge ( Resource resource ) { super ( resource , true ) ; this . resource = resource ; } public Resource resource ( ) { return this . resource ; } public Collection < Resource > properties ( ) { return this . properties ; } public ClassMap getBelongsToClassMap ( ) { return belongsToClassMap ; } public void setBelongsToClassMap ( ClassMap classMap ) { assertNotYetDefined ( this . belongsToClassMap , D2RQ . belongsToClassMap , D2RQException . PROPERTYBRIDGE_DUPLICATE_BELONGSTOCLASSMAP ) ; assertArgumentNotNull ( classMap , D2RQ . belongsToClassMap , D2RQException . PROPERTYBRIDGE_INVALID_BELONGSTOCLASSMAP ) ; this . belongsToClassMap = classMap ; } public String getColumn ( ) { return column ; } public void setColumn ( String column ) { assertNotYetDefined ( this . column , D2RQ . column , D2RQException . PROPERTYBRIDGE_DUPLICATE_COLUMN ) ; this . column = column ; } public String getPattern ( ) { return pattern ; } public void setPattern ( String pattern ) { assertNotYetDefined ( this . pattern , D2RQ . pattern , D2RQException . PROPERTYBRIDGE_DUPLICATE_PATTERN ) ; this . pattern = pattern ; } public String getSQLExpression ( ) { return sqlExpression ; } public void setSQLExpression ( String sqlExpression ) { assertNotYetDefined ( this . column , D2RQ . sqlExpression , D2RQException . PROPERTYBRIDGE_DUPLICATE_SQL_EXPRESSION ) ; this . sqlExpression = sqlExpression ; } public String getUriSQLExpression ( ) { return uriSqlExpression ; } public String getDatatype ( ) { return datatype ; } public void setDatatype ( String datatype ) { assertNotYetDefined ( this . datatype , D2RQ . datatype , D2RQException . PROPERTYBRIDGE_DUPLICATE_DATATYPE ) ; this . datatype = datatype ; } public String getLang ( ) { return lang ; } public void setLang ( String lang ) { assertNotYetDefined ( this . lang , D2RQ . lang , D2RQException . PROPERTYBRIDGE_DUPLICATE_LANG ) ; this . lang = lang ; } public int getLimit ( ) { return limit . intValue ( ) ; } public void setLimit ( int limit ) { assertNotYetDefined ( this . limit , D2RQ . limit , D2RQException . PROPERTYBRIDGE_DUPLICATE_LIMIT ) ; this . limit = new Integer ( limit ) ; } public int getLimitInverse ( ) { return limitInverse . intValue ( ) ; } public void setLimitInverse ( int limit ) { assertNotYetDefined ( this . limitInverse , D2RQ . limitInverse , D2RQException . PROPERTYBRIDGE_DUPLICATE_LIMITINVERSE ) ; this . limitInverse = new Integer ( limit ) ; } public void setOrder ( String column , boolean desc ) { assertNotYetDefined ( this . order , ( desc ? D2RQ . orderDesc : D2RQ . orderAsc ) , D2RQException . PROPERTYBRIDGE_DUPLICATE_ORDER ) ; this . order = column ; this . orderDesc = new Boolean ( desc ) ; } public ClassMap getRefersToClassMap ( ) { return refersToClassMap ; } public void setRefersToClassMap ( ClassMap classMap ) { assertNotYetDefined ( this . refersToClassMap , D2RQ . refersToClassMap , D2RQException . PROPERTYBRIDGE_DUPLICATE_REFERSTOCLASSMAP ) ; assertArgumentNotNull ( classMap , D2RQ . refersToClassMap , D2RQException . PROPERTYBRIDGE_INVALID_REFERSTOCLASSMAP ) ; this . refersToClassMap = classMap ; } public ClassMap refersToClassMap ( ) { return refersToClassMap ; } public void addProperty ( Resource property ) { this . properties . add ( property ) ; } public void addDynamicProperty ( String dynamicPropertyPattern ) { this . dynamicPropertyPatterns . add ( dynamicPropertyPattern ) ; } public void validate ( ) throws D2RQException { if ( this . refersToClassMap != null ) { if ( ! this . refersToClassMap . database ( ) . equals ( this . belongsToClassMap . database ( ) ) ) { throw new D2RQException ( toString ( ) + "" , D2RQException . PROPERTYBRIDGE_CONFLICTING_DATABASES ) ; } } if ( properties . isEmpty ( ) && dynamicPropertyPatterns . isEmpty ( ) ) { throw new D2RQException ( toString ( ) + "" , D2RQException . PROPERTYBRIDGE_MISSING_PREDICATESPEC ) ; } assertHasPrimarySpec ( new Property [ ] { D2RQ . uriColumn , D2RQ . uriPattern , D2RQ . bNodeIdColumns , D2RQ . column , D2RQ . pattern , D2RQ . sqlExpression , D2RQ . uriSqlExpression , D2RQ . constantValue , D2RQ . refersToClassMap } ) ; if ( this . datatype != null && this . lang != null ) { throw new D2RQException ( toString ( ) + "" , D2RQException . PROPERTYBRIDGE_LANG_AND_DATATYPE ) ; } if ( this . datatype != null && this . column == null && this . pattern == null && this . sqlExpression == null ) { throw new D2RQException ( "" + "" + this , D2RQException . PROPERTYBRIDGE_NONLITERAL_WITH_DATATYPE ) ; } if ( this . lang != null && this . column == null && this . pattern == null ) { throw new D2RQException ( "" + "" + this , D2RQException . PROPERTYBRIDGE_NONLITERAL_WITH_LANG ) ; } } protected Relation buildRelation ( ) { ConnectedDB database = belongsToClassMap . database ( ) . connectedDB ( ) ; RelationBuilder builder = belongsToClassMap . relationBuilder ( database ) ; builder . addOther ( relationBuilder ( database ) ) ; if ( this . refersToClassMap != null ) { builder . addAliased ( this . refersToClassMap . relationBuilder ( database ) ) ; } for ( String pattern : dynamicPropertyPatterns ) { builder . addOther ( new PropertyMap ( pattern , belongsToClassMap . database ( ) ) . relationBuilder ( database ) ) ; } if ( this . limit != null ) { builder . setLimit ( this . limit . intValue ( ) ) ; } if ( this . limitInverse != null ) { builder . setLimitInverse ( this . limitInverse . intValue ( ) ) ; } if ( this . order != null ) { builder . setOrderSpecs ( Collections . singletonList ( new OrderSpec ( new AttributeExpr ( SQL . parseAttribute ( this . order ) ) , this . orderDesc . booleanValue ( ) ) ) ) ; } return builder . buildRelation ( ) ; } public Collection < TripleRelation > toTripleRelations ( ) { this . validate ( ) ; Collection < TripleRelation > results = new ArrayList < TripleRelation > ( ) ; for ( Resource property : properties ) { NodeMaker s = this . belongsToClassMap . nodeMaker ( ) ; NodeMaker p = new FixedNodeMaker ( property . asNode ( ) , false ) ; NodeMaker o = nodeMaker ( ) ; results . add ( new TripleRelation ( buildRelation ( ) , s , p , o ) ) ; } for ( String pattern : dynamicPropertyPatterns ) { NodeMaker s = this . belongsToClassMap . nodeMaker ( ) ; NodeMaker p = new PropertyMap ( pattern , belongsToClassMap . database ( ) ) . nodeMaker ( ) ; NodeMaker o = nodeMaker ( ) ; results . add ( new TripleRelation ( buildRelation ( ) , s , p , o ) ) ; } return results ; } public String toString ( ) { return "" + PrettyPrinter . toString ( this . resource ) ; } } package de . fuberlin . wiwiss . d2rq ; import org . openjena . atlas . lib . AlarmClock ; import org . openjena . atlas . lib . Callback ; import org . openjena . atlas . lib . Pingback ; import com . hp . hpl . jena . graph . Graph ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . mem . GraphMem ; import com . hp . hpl . jena . sparql . engine . ExecutionContext ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIterConcat ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . find . FindQuery ; import de . fuberlin . wiwiss . d2rq . find . TripleQueryIter ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; public class ResourceDescriber { private final Mapping mapping ; private final Node node ; private final boolean onlyOutgoing ; private final int limit ; private final long timeout ; private final Graph result = new GraphMem ( ) ; private final ExecutionContext context ; private boolean executed = false ; public ResourceDescriber ( Mapping mapping , Node resource ) { this ( mapping , resource , false , Relation . NO_LIMIT , - ) ; } public ResourceDescriber ( Mapping mapping , Node resource , boolean onlyOutgoing , int limit , long timeout ) { this . mapping = mapping ; this . node = resource ; this . onlyOutgoing = onlyOutgoing ; this . limit = limit ; this . timeout = timeout ; this . context = null ; } public Graph description ( ) { if ( executed ) return result ; executed = true ; final QueryIterConcat qIter = new QueryIterConcat ( context ) ; Pingback < ? > pingback = null ; if ( timeout > ) { pingback = AlarmClock . get ( ) . add ( new Callback < Object > ( ) { public void proc ( Object ignore ) { qIter . cancel ( ) ; } } , timeout ) ; } FindQuery outgoing = new FindQuery ( Triple . create ( node , Node . ANY , Node . ANY ) , mapping . compiledPropertyBridges ( ) , limit , context ) ; qIter . add ( outgoing . iterator ( ) ) ; if ( ! onlyOutgoing ) { FindQuery incoming = new FindQuery ( Triple . create ( Node . ANY , Node . ANY , node ) , mapping . compiledPropertyBridges ( ) , limit , context ) ; qIter . add ( incoming . iterator ( ) ) ; FindQuery triples = new FindQuery ( Triple . create ( Node . ANY , node , Node . ANY ) , mapping . compiledPropertyBridges ( ) , limit , context ) ; qIter . add ( triples . iterator ( ) ) ; } result . getBulkUpdateHandler ( ) . add ( TripleQueryIter . create ( qIter ) ) ; if ( pingback != null ) { AlarmClock . get ( ) . cancel ( pingback ) ; } return result ; } } package de . fuberlin . wiwiss . d2rq . parser ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . RelationImpl ; import de . fuberlin . wiwiss . d2rq . expr . Conjunction ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . expr . SQLExpression ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class RelationBuilder { private final ConnectedDB database ; private Expression condition = Expression . TRUE ; private Set < Join > joinConditions = new HashSet < Join > ( ) ; private Set < Alias > aliases = new HashSet < Alias > ( ) ; private final Set < ProjectionSpec > projections = new HashSet < ProjectionSpec > ( ) ; private boolean isUnique = false ; private List < OrderSpec > orderSpecs = new ArrayList < OrderSpec > ( ) ; private int limit = Relation . NO_LIMIT ; private int limitInverse = Relation . NO_LIMIT ; public RelationBuilder ( ConnectedDB database ) { this . database = database ; } public void setIsUnique ( boolean isUnique ) { this . isUnique = isUnique ; } public void addOther ( RelationBuilder other ) { this . condition = this . condition . and ( other . condition ) ; this . joinConditions . addAll ( other . joinConditions ) ; this . aliases . addAll ( other . aliases ) ; this . projections . addAll ( other . projections ) ; this . isUnique = this . isUnique || other . isUnique ; if ( ! other . orderSpecs . isEmpty ( ) ) { this . orderSpecs = other . orderSpecs ; } this . limit = Relation . combineLimits ( limit , other . limit ) ; this . limitInverse = Relation . combineLimits ( limitInverse , other . limitInverse ) ; } public void addAliased ( RelationBuilder other ) { this . condition = this . condition . and ( aliases ( ) . applyTo ( other . condition ) ) ; this . joinConditions . addAll ( aliases ( ) . applyToJoinSet ( other . joinConditions ) ) ; this . projections . addAll ( aliases ( ) . applyToProjectionSet ( other . projections ) ) ; Collection < Alias > newAliases = new ArrayList < Alias > ( ) ; Collection < Alias > removedAliases = new ArrayList < Alias > ( ) ; for ( Alias alias : ( Collection < Alias > ) this . aliases ) { Alias newAlias = other . aliases ( ) . originalOf ( alias ) ; if ( ! alias . equals ( newAlias ) ) { removedAliases . add ( alias ) ; } newAliases . add ( newAlias ) ; } this . aliases . removeAll ( removedAliases ) ; this . aliases . addAll ( newAliases ) ; if ( ! other . orderSpecs . isEmpty ( ) ) { this . orderSpecs = aliases ( ) . applyTo ( other . orderSpecs ) ; } this . limit = Relation . combineLimits ( limit , other . limit ) ; this . limitInverse = Relation . combineLimits ( limitInverse , other . limitInverse ) ; } public void addCondition ( String condition ) { this . condition = this . condition . and ( SQLExpression . create ( condition ) ) ; } public void addCondition ( Expression condition ) { this . condition = this . condition . and ( condition ) ; } public void addAlias ( Alias alias ) { this . aliases . add ( alias ) ; } public void addAliases ( Collection < Alias > aliases ) { this . aliases . addAll ( aliases ) ; } public void addJoinCondition ( Join joinCondition ) { this . joinConditions . add ( joinCondition ) ; } public void addProjection ( ProjectionSpec projection ) { this . projections . add ( projection ) ; } public void setOrderSpecs ( List < OrderSpec > orderSpecs ) { this . orderSpecs = orderSpecs ; } public void setLimit ( int limit ) { this . limit = limit ; } public void setLimitInverse ( int limitInverse ) { this . limitInverse = limitInverse ; } public Relation buildRelation ( ) { if ( ! isUnique ) { for ( ProjectionSpec projection : projections ) { for ( Attribute column : projection . requiredAttributes ( ) ) { if ( ! database . columnType ( column ) . supportsDistinct ( ) ) { throw new D2RQException ( "" + column + "" + database . columnType ( column ) + "" + "" + "" , D2RQException . DATATYPE_DOES_NOT_SUPPORT_DISTINCT ) ; } } } } AliasMap aliases = aliases ( ) ; Collection < Expression > softConditions = new HashSet < Expression > ( projections . size ( ) ) ; for ( ProjectionSpec projection : projections ) { softConditions . add ( projection . notNullExpression ( database , aliases ) ) ; } return new RelationImpl ( database , aliases , this . condition , Conjunction . create ( softConditions ) , this . joinConditions , this . projections , this . isUnique , this . orderSpecs , this . limit , this . limitInverse ) ; } public AliasMap aliases ( ) { return new AliasMap ( this . aliases ) ; } } package de . fuberlin . wiwiss . d2rq . parser ; import java . util . Arrays ; import java . util . Collection ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . n3 . IRIResolver ; import com . hp . hpl . jena . ontology . Individual ; import com . hp . hpl . jena . ontology . OntModel ; import com . hp . hpl . jena . ontology . OntModelSpec ; import com . hp . hpl . jena . rdf . model . LiteralRequiredException ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . RDFNode ; import com . hp . hpl . jena . rdf . model . ResIterator ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . ResourceRequiredException ; import com . hp . hpl . jena . rdf . model . Statement ; import com . hp . hpl . jena . rdf . model . StmtIterator ; import com . hp . hpl . jena . vocabulary . RDF ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . map . ClassMap ; import de . fuberlin . wiwiss . d2rq . map . Configuration ; import de . fuberlin . wiwiss . d2rq . map . Database ; import de . fuberlin . wiwiss . d2rq . map . DownloadMap ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . map . PropertyBridge ; import de . fuberlin . wiwiss . d2rq . map . ResourceMap ; import de . fuberlin . wiwiss . d2rq . map . TranslationTable ; import de . fuberlin . wiwiss . d2rq . pp . PrettyPrinter ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; import de . fuberlin . wiwiss . d2rq . vocab . JDBC ; import de . fuberlin . wiwiss . d2rq . vocab . VocabularySummarizer ; public class MapParser { private final static Log log = LogFactory . getLog ( MapParser . class ) ; public static final String IRI_CHAR_REGEX = "" ; public static String absolutizeURI ( String uri ) { if ( uri == null ) { return null ; } return resolver . resolve ( uri ) ; } private final static IRIResolver resolver = new IRIResolver ( ) ; private OntModel model ; private String baseURI ; private Mapping mapping ; public MapParser ( Model mapModel , String baseURI ) { this . model = ModelFactory . createOntologyModel ( OntModelSpec . OWL_MEM , mapModel ) ; this . baseURI = absolutizeURI ( baseURI ) ; } public Mapping parse ( ) { if ( this . mapping != null ) { return this . mapping ; } new VocabularySummarizer ( D2RQ . class ) . assertNoUndefinedTerms ( model , D2RQException . MAPPING_UNKNOWN_D2RQ_PROPERTY , D2RQException . MAPPING_UNKNOWN_D2RQ_CLASS ) ; ensureAllDistinct ( new Resource [ ] { D2RQ . Database , D2RQ . ClassMap , D2RQ . PropertyBridge , D2RQ . TranslationTable , D2RQ . Translation } , D2RQException . MAPPING_TYPECONFLICT ) ; this . mapping = new Mapping ( ) ; copyPrefixes ( ) ; try { parseDatabases ( ) ; parseConfiguration ( ) ; parseTranslationTables ( ) ; parseClassMaps ( ) ; parsePropertyBridges ( ) ; parseDownloadMaps ( ) ; this . mapping . buildVocabularyModel ( ) ; log . info ( "" + mapping . databases ( ) . size ( ) + "" + mapping . classMapResources ( ) . size ( ) + "" ) ; return this . mapping ; } catch ( LiteralRequiredException ex ) { throw new D2RQException ( "" + ex . getMessage ( ) , D2RQException . MAPPING_RESOURCE_INSTEADOF_LITERAL ) ; } catch ( ResourceRequiredException ex ) { throw new D2RQException ( "" + ex . getMessage ( ) , D2RQException . MAPPING_LITERAL_INSTEADOF_RESOURCE ) ; } } private void ensureAllDistinct ( Resource [ ] distinctClasses , int errorCode ) { Collection < Resource > classes = Arrays . asList ( distinctClasses ) ; ResIterator it = this . model . listSubjects ( ) ; while ( it . hasNext ( ) ) { Resource resource = it . nextResource ( ) ; Resource matchingType = null ; StmtIterator typeIt = resource . listProperties ( RDF . type ) ; while ( typeIt . hasNext ( ) ) { Resource type = typeIt . nextStatement ( ) . getResource ( ) ; if ( ! classes . contains ( type ) ) continue ; if ( matchingType == null ) { matchingType = type ; } else { throw new D2RQException ( "" + PrettyPrinter . toString ( resource ) + "" + PrettyPrinter . toString ( matchingType ) + "" + PrettyPrinter . toString ( type ) , errorCode ) ; } } } } private void copyPrefixes ( ) { mapping . getPrefixMapping ( ) . setNsPrefixes ( model ) ; Iterator < Map . Entry < String , String > > it = mapping . getPrefixMapping ( ) . getNsPrefixMap ( ) . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Entry < String , String > entry = it . next ( ) ; String namespace = entry . getValue ( ) ; if ( D2RQ . NS . equals ( namespace ) && "" . equals ( entry . getKey ( ) ) ) { mapping . getPrefixMapping ( ) . removeNsPrefix ( entry . getKey ( ) ) ; } if ( JDBC . NS . equals ( namespace ) && "" . equals ( entry . getKey ( ) ) ) { mapping . getPrefixMapping ( ) . removeNsPrefix ( entry . getKey ( ) ) ; } } } private void parseDatabases ( ) { Iterator < Individual > it = this . model . listIndividuals ( D2RQ . Database ) ; while ( it . hasNext ( ) ) { Resource dbResource = it . next ( ) ; Database database = new Database ( dbResource ) ; parseDatabase ( database , dbResource ) ; this . mapping . addDatabase ( database ) ; } } private void parseConfiguration ( ) { Iterator < Individual > it = this . model . listIndividuals ( D2RQ . Configuration ) ; if ( it . hasNext ( ) ) { Resource configResource = it . next ( ) ; Configuration configuration = new Configuration ( configResource ) ; StmtIterator stmts = configResource . listProperties ( D2RQ . serveVocabulary ) ; while ( stmts . hasNext ( ) ) { configuration . setServeVocabulary ( stmts . nextStatement ( ) . getBoolean ( ) ) ; } stmts = configResource . listProperties ( D2RQ . useAllOptimizations ) ; while ( stmts . hasNext ( ) ) { configuration . setUseAllOptimizations ( stmts . nextStatement ( ) . getBoolean ( ) ) ; } this . mapping . setConfiguration ( configuration ) ; if ( it . hasNext ( ) ) throw new D2RQException ( "" ) ; } } private void parseDatabase ( Database database , Resource r ) { StmtIterator stmts ; stmts = r . listProperties ( D2RQ . jdbcDSN ) ; while ( stmts . hasNext ( ) ) { database . setJDBCDSN ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . jdbcDriver ) ; while ( stmts . hasNext ( ) ) { database . setJDBCDriver ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . username ) ; while ( stmts . hasNext ( ) ) { database . setUsername ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . password ) ; while ( stmts . hasNext ( ) ) { database . setPassword ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . resultSizeLimit ) ; while ( stmts . hasNext ( ) ) { try { int limit = Integer . parseInt ( stmts . nextStatement ( ) . getString ( ) ) ; database . setResultSizeLimit ( limit ) ; } catch ( NumberFormatException ex ) { throw new D2RQException ( "" , D2RQException . MUST_BE_NUMERIC ) ; } } stmts = r . listProperties ( D2RQ . textColumn ) ; while ( stmts . hasNext ( ) ) { database . addTextColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . numericColumn ) ; while ( stmts . hasNext ( ) ) { database . addNumericColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . booleanColumn ) ; while ( stmts . hasNext ( ) ) { database . addBooleanColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . dateColumn ) ; while ( stmts . hasNext ( ) ) { database . addDateColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . timestampColumn ) ; while ( stmts . hasNext ( ) ) { database . addTimestampColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . timeColumn ) ; while ( stmts . hasNext ( ) ) { database . addTimeColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . binaryColumn ) ; while ( stmts . hasNext ( ) ) { database . addBinaryColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . bitColumn ) ; while ( stmts . hasNext ( ) ) { database . addBitColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . intervalColumn ) ; while ( stmts . hasNext ( ) ) { database . addIntervalColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . fetchSize ) ; while ( stmts . hasNext ( ) ) { try { int fetchSize = Integer . parseInt ( stmts . nextStatement ( ) . getString ( ) ) ; database . setFetchSize ( fetchSize ) ; } catch ( NumberFormatException ex ) { throw new D2RQException ( "" , D2RQException . MUST_BE_NUMERIC ) ; } } stmts = r . listProperties ( D2RQ . startupSQLScript ) ; while ( stmts . hasNext ( ) ) { database . setStartupSQLScript ( stmts . next ( ) . getResource ( ) ) ; } stmts = r . listProperties ( ) ; while ( stmts . hasNext ( ) ) { Statement stmt = stmts . nextStatement ( ) ; String prop = stmt . getPredicate ( ) . getURI ( ) ; if ( ! prop . startsWith ( JDBC . NS ) ) continue ; database . setConnectionProperty ( prop . substring ( JDBC . NS . length ( ) ) , stmt . getString ( ) ) ; } } private void parseTranslationTables ( ) { Set < Resource > translationTableResources = new HashSet < Resource > ( ) ; Iterator < ? extends Resource > it = this . model . listIndividuals ( D2RQ . TranslationTable ) ; while ( it . hasNext ( ) ) { translationTableResources . add ( it . next ( ) ) ; } StmtIterator stmts ; stmts = this . model . listStatements ( null , D2RQ . translateWith , ( Resource ) null ) ; while ( stmts . hasNext ( ) ) { translationTableResources . add ( stmts . nextStatement ( ) . getResource ( ) ) ; } stmts = this . model . listStatements ( null , D2RQ . translation , ( RDFNode ) null ) ; while ( stmts . hasNext ( ) ) { translationTableResources . add ( stmts . nextStatement ( ) . getSubject ( ) ) ; } stmts = this . model . listStatements ( null , D2RQ . javaClass , ( RDFNode ) null ) ; while ( stmts . hasNext ( ) ) { translationTableResources . add ( stmts . nextStatement ( ) . getSubject ( ) ) ; } stmts = this . model . listStatements ( null , D2RQ . href , ( RDFNode ) null ) ; while ( stmts . hasNext ( ) ) { translationTableResources . add ( stmts . nextStatement ( ) . getSubject ( ) ) ; } it = translationTableResources . iterator ( ) ; while ( it . hasNext ( ) ) { Resource r = it . next ( ) ; TranslationTable table = new TranslationTable ( r ) ; parseTranslationTable ( table , r ) ; this . mapping . addTranslationTable ( table ) ; } } private void parseTranslationTable ( TranslationTable table , Resource r ) { StmtIterator stmts ; stmts = r . listProperties ( D2RQ . href ) ; while ( stmts . hasNext ( ) ) { table . setHref ( stmts . nextStatement ( ) . getResource ( ) . getURI ( ) ) ; } stmts = r . listProperties ( D2RQ . javaClass ) ; while ( stmts . hasNext ( ) ) { table . setJavaClass ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . translation ) ; while ( stmts . hasNext ( ) ) { Resource translation = stmts . nextStatement ( ) . getResource ( ) ; String db = translation . getProperty ( D2RQ . databaseValue ) . getString ( ) ; Statement stmt = translation . getProperty ( D2RQ . rdfValue ) ; String rdf = stmt . getObject ( ) . isLiteral ( ) ? stmt . getString ( ) : stmt . getResource ( ) . getURI ( ) ; table . addTranslation ( db , rdf ) ; } } private void parseClassMaps ( ) { Iterator < Individual > it = this . model . listIndividuals ( D2RQ . ClassMap ) ; while ( it . hasNext ( ) ) { Resource r = it . next ( ) ; ClassMap classMap = new ClassMap ( r ) ; parseClassMap ( classMap , r ) ; parseResourceMap ( classMap , r ) ; this . mapping . addClassMap ( classMap ) ; } } private void parseResourceMap ( ResourceMap resourceMap , Resource r ) { StmtIterator stmts ; stmts = r . listProperties ( D2RQ . bNodeIdColumns ) ; while ( stmts . hasNext ( ) ) { resourceMap . setBNodeIdColumns ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . uriColumn ) ; while ( stmts . hasNext ( ) ) { resourceMap . setURIColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . uriPattern ) ; while ( stmts . hasNext ( ) ) { resourceMap . setURIPattern ( ensureIsAbsolute ( stmts . nextStatement ( ) . getString ( ) ) ) ; } stmts = r . listProperties ( D2RQ . uriSqlExpression ) ; while ( stmts . hasNext ( ) ) { resourceMap . setUriSQLExpression ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . constantValue ) ; while ( stmts . hasNext ( ) ) { resourceMap . setConstantValue ( stmts . nextStatement ( ) . getObject ( ) ) ; } stmts = r . listProperties ( D2RQ . valueRegex ) ; while ( stmts . hasNext ( ) ) { resourceMap . addValueRegex ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . valueContains ) ; while ( stmts . hasNext ( ) ) { resourceMap . addValueContains ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . valueMaxLength ) ; while ( stmts . hasNext ( ) ) { String s = stmts . nextStatement ( ) . getString ( ) ; try { resourceMap . setValueMaxLength ( Integer . parseInt ( s ) ) ; } catch ( NumberFormatException nfex ) { throw new D2RQException ( "" + s + "" + PrettyPrinter . toString ( r ) + "" ) ; } } stmts = r . listProperties ( D2RQ . join ) ; while ( stmts . hasNext ( ) ) { resourceMap . addJoin ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . condition ) ; while ( stmts . hasNext ( ) ) { resourceMap . addCondition ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . alias ) ; while ( stmts . hasNext ( ) ) { resourceMap . addAlias ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . containsDuplicates ) ; while ( stmts . hasNext ( ) ) { String containsDuplicates = stmts . nextStatement ( ) . getString ( ) ; if ( "" . equals ( containsDuplicates ) ) { resourceMap . setContainsDuplicates ( true ) ; } else if ( "" . equals ( containsDuplicates ) ) { resourceMap . setContainsDuplicates ( false ) ; } else if ( containsDuplicates != null ) { throw new D2RQException ( "" + containsDuplicates + "" + PrettyPrinter . toString ( r ) , D2RQException . RESOURCEMAP_ILLEGAL_CONTAINSDUPLICATE ) ; } } stmts = r . listProperties ( D2RQ . translateWith ) ; while ( stmts . hasNext ( ) ) { resourceMap . setTranslateWith ( this . mapping . translationTable ( stmts . nextStatement ( ) . getResource ( ) ) ) ; } } private void parseClassMap ( ClassMap classMap , Resource r ) { StmtIterator stmts ; stmts = r . listProperties ( D2RQ . dataStorage ) ; while ( stmts . hasNext ( ) ) { classMap . setDatabase ( this . mapping . database ( stmts . nextStatement ( ) . getResource ( ) ) ) ; } stmts = r . listProperties ( D2RQ . class_ ) ; while ( stmts . hasNext ( ) ) { classMap . addClass ( stmts . nextStatement ( ) . getResource ( ) ) ; } stmts = this . model . listStatements ( null , D2RQ . classMap , r ) ; while ( stmts . hasNext ( ) ) { classMap . addClass ( stmts . nextStatement ( ) . getSubject ( ) ) ; } stmts = r . listProperties ( D2RQ . additionalProperty ) ; while ( stmts . hasNext ( ) ) { Resource additionalProperty = stmts . nextStatement ( ) . getResource ( ) ; PropertyBridge bridge = new PropertyBridge ( r ) ; bridge . setBelongsToClassMap ( classMap ) ; bridge . addProperty ( additionalProperty . getProperty ( D2RQ . propertyName ) . getResource ( ) ) ; bridge . setConstantValue ( additionalProperty . getProperty ( D2RQ . propertyValue ) . getObject ( ) ) ; classMap . addPropertyBridge ( bridge ) ; } stmts = r . listProperties ( D2RQ . classDefinitionLabel ) ; while ( stmts . hasNext ( ) ) { classMap . addDefinitionLabel ( stmts . nextStatement ( ) . getLiteral ( ) ) ; } stmts = r . listProperties ( D2RQ . classDefinitionComment ) ; while ( stmts . hasNext ( ) ) { classMap . addDefinitionComment ( stmts . nextStatement ( ) . getLiteral ( ) ) ; } stmts = r . listProperties ( D2RQ . additionalClassDefinitionProperty ) ; while ( stmts . hasNext ( ) ) { Resource additionalProperty = stmts . nextStatement ( ) . getResource ( ) ; classMap . addDefinitionProperty ( additionalProperty ) ; } } private void parsePropertyBridges ( ) { StmtIterator stmts = this . model . listStatements ( null , D2RQ . belongsToClassMap , ( RDFNode ) null ) ; while ( stmts . hasNext ( ) ) { Statement stmt = stmts . nextStatement ( ) ; ClassMap classMap = this . mapping . classMap ( stmt . getResource ( ) ) ; Resource r = stmt . getSubject ( ) ; PropertyBridge bridge = new PropertyBridge ( r ) ; bridge . setBelongsToClassMap ( classMap ) ; parseResourceMap ( bridge , r ) ; parsePropertyBridge ( bridge , r ) ; classMap . addPropertyBridge ( bridge ) ; } } private void parsePropertyBridge ( PropertyBridge bridge , Resource r ) { StmtIterator stmts ; stmts = r . listProperties ( D2RQ . column ) ; while ( stmts . hasNext ( ) ) { if ( r . getProperty ( RDF . type ) . equals ( D2RQ . ObjectPropertyBridge ) ) { bridge . setURIColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } else { bridge . setColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } } stmts = r . listProperties ( D2RQ . pattern ) ; while ( stmts . hasNext ( ) ) { if ( r . getProperty ( RDF . type ) . equals ( D2RQ . ObjectPropertyBridge ) ) { bridge . setURIPattern ( stmts . nextStatement ( ) . getString ( ) ) ; } else { bridge . setPattern ( stmts . nextStatement ( ) . getString ( ) ) ; } } stmts = r . listProperties ( D2RQ . sqlExpression ) ; while ( stmts . hasNext ( ) ) { bridge . setSQLExpression ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . lang ) ; while ( stmts . hasNext ( ) ) { bridge . setLang ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . datatype ) ; while ( stmts . hasNext ( ) ) { bridge . setDatatype ( stmts . nextStatement ( ) . getResource ( ) . getURI ( ) ) ; } stmts = r . listProperties ( D2RQ . refersToClassMap ) ; while ( stmts . hasNext ( ) ) { Resource classMapResource = stmts . nextStatement ( ) . getResource ( ) ; bridge . setRefersToClassMap ( this . mapping . classMap ( classMapResource ) ) ; } stmts = r . listProperties ( D2RQ . dynamicProperty ) ; while ( stmts . hasNext ( ) ) { bridge . addDynamicProperty ( stmts . next ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . property ) ; while ( stmts . hasNext ( ) ) { bridge . addProperty ( stmts . nextStatement ( ) . getResource ( ) ) ; } stmts = this . model . listStatements ( null , D2RQ . propertyBridge , r ) ; while ( stmts . hasNext ( ) ) { bridge . addProperty ( stmts . nextStatement ( ) . getSubject ( ) ) ; } stmts = r . listProperties ( D2RQ . propertyDefinitionLabel ) ; while ( stmts . hasNext ( ) ) { bridge . addDefinitionLabel ( stmts . nextStatement ( ) . getLiteral ( ) ) ; } stmts = r . listProperties ( D2RQ . propertyDefinitionComment ) ; while ( stmts . hasNext ( ) ) { bridge . addDefinitionComment ( stmts . nextStatement ( ) . getLiteral ( ) ) ; } stmts = r . listProperties ( D2RQ . additionalPropertyDefinitionProperty ) ; while ( stmts . hasNext ( ) ) { Resource additionalProperty = stmts . nextStatement ( ) . getResource ( ) ; bridge . addDefinitionProperty ( additionalProperty ) ; } stmts = r . listProperties ( D2RQ . limit ) ; while ( stmts . hasNext ( ) ) { bridge . setLimit ( stmts . nextStatement ( ) . getInt ( ) ) ; } stmts = r . listProperties ( D2RQ . limitInverse ) ; while ( stmts . hasNext ( ) ) { bridge . setLimitInverse ( stmts . nextStatement ( ) . getInt ( ) ) ; } stmts = r . listProperties ( D2RQ . orderDesc ) ; while ( stmts . hasNext ( ) ) { bridge . setOrder ( stmts . nextStatement ( ) . getString ( ) , true ) ; } stmts = r . listProperties ( D2RQ . orderAsc ) ; while ( stmts . hasNext ( ) ) { bridge . setOrder ( stmts . nextStatement ( ) . getString ( ) , false ) ; } } private void parseDownloadMaps ( ) { Iterator < Individual > it = this . model . listIndividuals ( D2RQ . DownloadMap ) ; while ( it . hasNext ( ) ) { Resource downloadMapResource = it . next ( ) ; DownloadMap downloadMap = new DownloadMap ( downloadMapResource ) ; parseResourceMap ( downloadMap , downloadMapResource ) ; parseDownloadMap ( downloadMap , downloadMapResource ) ; mapping . addDownloadMap ( downloadMap ) ; } } private void parseDownloadMap ( DownloadMap dm , Resource r ) { StmtIterator stmts ; stmts = r . listProperties ( D2RQ . dataStorage ) ; while ( stmts . hasNext ( ) ) { dm . setDatabase ( mapping . database ( stmts . nextStatement ( ) . getResource ( ) ) ) ; } stmts = r . listProperties ( D2RQ . belongsToClassMap ) ; while ( stmts . hasNext ( ) ) { dm . setBelongsToClassMap ( mapping . classMap ( stmts . nextStatement ( ) . getResource ( ) ) ) ; } stmts = r . listProperties ( D2RQ . contentDownloadColumn ) ; while ( stmts . hasNext ( ) ) { dm . setContentDownloadColumn ( stmts . nextStatement ( ) . getString ( ) ) ; } stmts = r . listProperties ( D2RQ . mediaType ) ; while ( stmts . hasNext ( ) ) { dm . setMediaType ( stmts . nextStatement ( ) . getString ( ) ) ; } } private String ensureIsAbsolute ( String uriPattern ) { if ( uriPattern . indexOf ( "" ) == - ) { return this . baseURI + uriPattern ; } return uriPattern ; } } package de . fuberlin . wiwiss . d2rq . optimizer . expr ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . expr . AttributeExpr ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; public class AttributeExprEx extends AttributeExpr { private final NodeMaker nodeMaker ; public AttributeExprEx ( Attribute attribute , NodeMaker nodeMaker ) { super ( attribute ) ; this . nodeMaker = nodeMaker ; } public NodeMaker getNodeMaker ( ) { return nodeMaker ; } } package de . fuberlin . wiwiss . d2rq . optimizer . expr ; import org . apache . xerces . impl . dv . XSSimpleType ; import org . apache . xerces . xs . XSConstants ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . graph . Node ; public class XSD { private static final XSSimpleType integerType = ( XSSimpleType ) XSDDatatype . XSDinteger . extendedTypeDefinition ( ) ; private static final XSSimpleType decimalType = ( XSSimpleType ) XSDDatatype . XSDdecimal . extendedTypeDefinition ( ) ; private static final XSSimpleType floatType = ( XSSimpleType ) XSDDatatype . XSDfloat . extendedTypeDefinition ( ) ; private static final XSSimpleType doubleType = ( XSSimpleType ) XSDDatatype . XSDdouble . extendedTypeDefinition ( ) ; public static RDFDatatype getNumericType ( RDFDatatype lhs , RDFDatatype rhs ) { int lhsType = getNumericType ( lhs ) ; int rhsType = getNumericType ( rhs ) ; if ( lhsType == XSConstants . INTEGER_DT ) { if ( rhsType == XSConstants . INTEGER_DT ) return XSDDatatype . XSDinteger ; if ( rhsType == XSConstants . DECIMAL_DT ) return XSDDatatype . XSDdecimal ; if ( rhsType == XSConstants . FLOAT_DT ) return XSDDatatype . XSDfloat ; return XSDDatatype . XSDdouble ; } else if ( lhsType == XSConstants . DECIMAL_DT ) { if ( rhsType == XSConstants . INTEGER_DT || rhsType == XSConstants . DECIMAL_DT ) return XSDDatatype . XSDdecimal ; if ( rhsType == XSConstants . FLOAT_DT ) return XSDDatatype . XSDfloat ; return XSDDatatype . XSDdouble ; } else if ( lhsType == XSConstants . FLOAT_DT ) { if ( rhsType == XSConstants . INTEGER_DT || rhsType == XSConstants . DECIMAL_DT || rhsType == XSConstants . FLOAT_DT ) return XSDDatatype . XSDfloat ; return XSDDatatype . XSDdouble ; } else if ( lhsType == XSConstants . DOUBLE_DT ) { return XSDDatatype . XSDdouble ; } throw new IllegalArgumentException ( ) ; } private static int getNumericType ( RDFDatatype numeric ) { XSSimpleType type = ( XSSimpleType ) numeric . extendedTypeDefinition ( ) ; if ( type . derivedFromType ( integerType , XSConstants . DERIVATION_EXTENSION ) ) return integerType . getBuiltInKind ( ) ; if ( type . derivedFromType ( decimalType , XSConstants . DERIVATION_EXTENSION ) ) return decimalType . getBuiltInKind ( ) ; if ( type . derivedFromType ( floatType , XSConstants . DERIVATION_EXTENSION ) ) return floatType . getBuiltInKind ( ) ; if ( type . derivedFromType ( doubleType , XSConstants . DERIVATION_EXTENSION ) ) return doubleType . getBuiltInKind ( ) ; throw new IllegalArgumentException ( ) ; } public static boolean isNumeric ( Node node ) { if ( ! node . isLiteral ( ) ) return false ; RDFDatatype datatype = node . getLiteral ( ) . getDatatype ( ) ; return datatype != null && isNumeric ( datatype ) ; } public static boolean isNumeric ( RDFDatatype datatype ) { XSSimpleType type = ( XSSimpleType ) datatype . extendedTypeDefinition ( ) ; return type != null && type . getNumeric ( ) ; } public static Node cast ( Node numeric , RDFDatatype datatype ) { return Node . createLiteral ( numeric . getLiteralLexicalForm ( ) , null , datatype ) ; } public static boolean isSupported ( RDFDatatype datatype ) { return datatype == null || isNumeric ( datatype ) || datatype . equals ( XSDDatatype . XSDdateTime ) || datatype . equals ( XSDDatatype . XSDstring ) ; } public static boolean isString ( Node node ) { if ( ! node . isLiteral ( ) ) return false ; return XSDDatatype . XSDstring . equals ( node . getLiteralDatatype ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . optimizer . expr ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Stack ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . sparql . core . Var ; import com . hp . hpl . jena . sparql . expr . E_Add ; import com . hp . hpl . jena . sparql . expr . E_Datatype ; import com . hp . hpl . jena . sparql . expr . E_Divide ; import com . hp . hpl . jena . sparql . expr . E_Equals ; import com . hp . hpl . jena . sparql . expr . E_GreaterThan ; import com . hp . hpl . jena . sparql . expr . E_GreaterThanOrEqual ; import com . hp . hpl . jena . sparql . expr . E_IsBlank ; import com . hp . hpl . jena . sparql . expr . E_IsIRI ; import com . hp . hpl . jena . sparql . expr . E_IsLiteral ; import com . hp . hpl . jena . sparql . expr . E_Lang ; import com . hp . hpl . jena . sparql . expr . E_LangMatches ; import com . hp . hpl . jena . sparql . expr . E_LessThan ; import com . hp . hpl . jena . sparql . expr . E_LessThanOrEqual ; import com . hp . hpl . jena . sparql . expr . E_LogicalNot ; import com . hp . hpl . jena . sparql . expr . E_LogicalOr ; import com . hp . hpl . jena . sparql . expr . E_Multiply ; import com . hp . hpl . jena . sparql . expr . E_NotEquals ; import com . hp . hpl . jena . sparql . expr . E_SameTerm ; import com . hp . hpl . jena . sparql . expr . E_Str ; import com . hp . hpl . jena . sparql . expr . E_Subtract ; import com . hp . hpl . jena . sparql . expr . E_UnaryMinus ; import com . hp . hpl . jena . sparql . expr . E_UnaryPlus ; import com . hp . hpl . jena . sparql . expr . Expr ; import com . hp . hpl . jena . sparql . expr . ExprAggregator ; import com . hp . hpl . jena . sparql . expr . ExprEvalException ; import com . hp . hpl . jena . sparql . expr . ExprFunction ; import com . hp . hpl . jena . sparql . expr . ExprFunction0 ; import com . hp . hpl . jena . sparql . expr . ExprFunction1 ; import com . hp . hpl . jena . sparql . expr . ExprFunction2 ; import com . hp . hpl . jena . sparql . expr . ExprFunction3 ; import com . hp . hpl . jena . sparql . expr . ExprFunctionN ; import com . hp . hpl . jena . sparql . expr . ExprFunctionOp ; import com . hp . hpl . jena . sparql . expr . ExprVar ; import com . hp . hpl . jena . sparql . expr . ExprVisitor ; import com . hp . hpl . jena . sparql . expr . NodeValue ; import com . hp . hpl . jena . sparql . expr . nodevalue . NodeFunctions ; import com . hp . hpl . jena . sparql . expr . nodevalue . NodeValueBoolean ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . ExpressionProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . RelationalOperators ; import de . fuberlin . wiwiss . d2rq . expr . Add ; import de . fuberlin . wiwiss . d2rq . expr . Constant ; import de . fuberlin . wiwiss . d2rq . expr . Divide ; import de . fuberlin . wiwiss . d2rq . expr . Equality ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . expr . GreaterThan ; import de . fuberlin . wiwiss . d2rq . expr . GreaterThanOrEqual ; import de . fuberlin . wiwiss . d2rq . expr . LessThan ; import de . fuberlin . wiwiss . d2rq . expr . LessThanOrEqual ; import de . fuberlin . wiwiss . d2rq . expr . Multiply ; import de . fuberlin . wiwiss . d2rq . expr . Negation ; import de . fuberlin . wiwiss . d2rq . expr . SQLExpression ; import de . fuberlin . wiwiss . d2rq . expr . Subtract ; import de . fuberlin . wiwiss . d2rq . expr . UnaryMinus ; import de . fuberlin . wiwiss . d2rq . nodes . DetermineNodeType ; import de . fuberlin . wiwiss . d2rq . nodes . FixedNodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetConstraintBuilder ; import de . fuberlin . wiwiss . d2rq . nodes . TypedNodeMaker ; import de . fuberlin . wiwiss . d2rq . values . ValueMaker ; public final class TransformExprToSQLApplyer implements ExprVisitor { private static final Log logger = LogFactory . getLog ( TransformExprToSQLApplyer . class ) ; public static Expression convert ( final Expr expr , final NodeRelation nodeRelation ) { TransformExprToSQLApplyer transformer = new TransformExprToSQLApplyer ( nodeRelation ) ; expr . visit ( transformer ) ; return transformer . result ( ) ; } private static final Expression CONSTANT_FALSE = new ConstantEx ( "" , NodeValueBoolean . FALSE . asNode ( ) ) ; private static final Expression CONSTANT_TRUE = new ConstantEx ( "" , NodeValueBoolean . TRUE . asNode ( ) ) ; private final NodeRelation nodeRelation ; private final Stack < Expression > expression = new Stack < Expression > ( ) ; private boolean convertable ; private String reason = null ; public TransformExprToSQLApplyer ( NodeRelation nodeRelation ) { this . convertable = true ; this . nodeRelation = nodeRelation ; } public Expression result ( ) { if ( ! convertable ) { logger . debug ( "" + reason ) ; return null ; } if ( expression . size ( ) != ) throw new IllegalStateException ( "" ) ; Expression result = expression . pop ( ) ; logger . debug ( "" + result ) ; return result ; } public void startVisit ( ) { logger . debug ( "" ) ; } public void finishVisit ( ) { logger . debug ( "" ) ; } public void visit ( ExprFunction0 func ) { visitExprFunction ( func ) ; } public void visit ( ExprFunction1 function ) { logger . debug ( "" + function ) ; if ( ! convertable ) { expression . push ( Expression . FALSE ) ; return ; } convertFunction ( function ) ; } public void visit ( ExprFunction2 function ) { logger . debug ( "" + function ) ; if ( ! convertable ) { expression . push ( Expression . FALSE ) ; return ; } convertFunction ( function ) ; } public void visit ( ExprFunction3 func ) { visitExprFunction ( func ) ; } public void visit ( ExprFunctionN func ) { visitExprFunction ( func ) ; } public void visit ( ExprFunctionOp funcOp ) { visitExprFunction ( funcOp ) ; } public void visit ( ExprAggregator eAgg ) { conversionFailed ( eAgg ) ; } public void visit ( ExprVar var ) { logger . debug ( "" + var ) ; if ( ! convertable ) { expression . push ( Expression . FALSE ) ; return ; } String varName = var . getVarName ( ) ; if ( Var . isBlankNodeVarName ( varName ) ) { conversionFailed ( "" , var ) ; return ; } List < Expression > expressions = toExpression ( var ) ; if ( expressions . size ( ) == ) { expression . push ( expressions . get ( ) ) ; } else { conversionFailed ( "" , var ) ; } } public void visit ( NodeValue value ) { logger . debug ( "" + value ) ; if ( ! convertable ) { expression . push ( Expression . FALSE ) ; return ; } if ( value . isDecimal ( ) || value . isDouble ( ) || value . isFloat ( ) || value . isInteger ( ) || value . isNumber ( ) ) { expression . push ( new ConstantEx ( value . asString ( ) , value . asNode ( ) ) ) ; } else if ( value . isDateTime ( ) ) { expression . push ( new ConstantEx ( value . asString ( ) . replace ( "" , "" ) , value . asNode ( ) ) ) ; } else { expression . push ( new ConstantEx ( value . asString ( ) , value . asNode ( ) ) ) ; } } private void visitExprFunction ( ExprFunction function ) { logger . debug ( "" + function ) ; if ( ! convertable ) { expression . push ( Expression . FALSE ) ; return ; } if ( ! extensionSupports ( function ) ) { conversionFailed ( function ) ; return ; } for ( int i = ; i < function . numArgs ( ) ; i ++ ) function . getArg ( i + ) . visit ( this ) ; List < Expression > args = new ArrayList < Expression > ( function . numArgs ( ) ) ; for ( int i = ; i < function . numArgs ( ) ; i ++ ) args . add ( expression . pop ( ) ) ; Collections . reverse ( args ) ; extensionConvert ( function , args ) ; } private List < Expression > toExpression ( ExprVar exprVar ) { ArrayList < Expression > result = new ArrayList < Expression > ( ) ; if ( this . nodeRelation != null && exprVar != null ) { NodeMaker nodeMaker = nodeRelation . nodeMaker ( exprVar . asVar ( ) ) ; if ( nodeMaker instanceof TypedNodeMaker ) { TypedNodeMaker typedNodeMaker = ( TypedNodeMaker ) nodeMaker ; Iterator < ProjectionSpec > it = typedNodeMaker . projectionSpecs ( ) . iterator ( ) ; if ( ! it . hasNext ( ) ) { logger . debug ( "" + exprVar + "" ) ; Node node = typedNodeMaker . makeNode ( null ) ; result . add ( new ConstantEx ( NodeValue . makeNode ( node ) . asString ( ) , node ) ) ; } while ( it . hasNext ( ) ) { ProjectionSpec projectionSpec = it . next ( ) ; if ( projectionSpec == null ) return Collections . emptyList ( ) ; if ( projectionSpec instanceof Attribute ) { result . add ( new AttributeExprEx ( ( Attribute ) projectionSpec , nodeMaker ) ) ; } else { ExpressionProjectionSpec expressionProjectionSpec = ( ExpressionProjectionSpec ) projectionSpec ; Expression expression = expressionProjectionSpec . toExpression ( ) ; if ( expression instanceof SQLExpression ) result . add ( ( ( SQLExpression ) expression ) ) ; else return Collections . emptyList ( ) ; } } } else if ( nodeMaker instanceof FixedNodeMaker ) { FixedNodeMaker fixedNodeMaker = ( FixedNodeMaker ) nodeMaker ; Node node = fixedNodeMaker . makeNode ( null ) ; result . add ( new ConstantEx ( NodeValue . makeNode ( node ) . asString ( ) , node ) ) ; } } return result ; } private void convertFunction ( ExprFunction1 expr ) { logger . debug ( "" + expr . toString ( ) ) ; if ( expr instanceof E_Str ) { convertStr ( ( E_Str ) expr ) ; } else if ( expr instanceof E_IsIRI ) { convertIsIRI ( ( E_IsIRI ) expr ) ; } else if ( expr instanceof E_IsBlank ) { convertIsBlank ( ( E_IsBlank ) expr ) ; } else if ( expr instanceof E_IsLiteral ) { convertIsLiteral ( ( E_IsLiteral ) expr ) ; } else if ( expr instanceof E_Datatype ) { convertDataType ( ( E_Datatype ) expr ) ; } else if ( expr instanceof E_Lang ) { convertLang ( ( E_Lang ) expr ) ; } else if ( expr instanceof E_LogicalNot ) { convertLogicalNot ( ( E_LogicalNot ) expr ) ; } else if ( expr instanceof E_UnaryPlus ) { convert ( ( E_UnaryPlus ) expr ) ; } else if ( expr instanceof E_UnaryMinus ) { convert ( ( E_UnaryMinus ) expr ) ; } else if ( extensionSupports ( expr ) ) { expr . getArg ( ) . visit ( this ) ; Expression e1 = expression . pop ( ) ; List < Expression > args = Collections . singletonList ( e1 ) ; extensionConvert ( expr , args ) ; } else { conversionFailed ( expr ) ; } } private void convertFunction ( ExprFunction2 expr ) { logger . debug ( "" + expr . toString ( ) ) ; if ( expr instanceof E_LogicalOr ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( e1 . or ( e2 ) ) ; } else if ( expr instanceof E_LessThan ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( new LessThan ( e1 , e2 ) ) ; } else if ( expr instanceof E_LessThanOrEqual ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( new LessThanOrEqual ( e1 , e2 ) ) ; } else if ( expr instanceof E_GreaterThan ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( new GreaterThan ( e1 , e2 ) ) ; } else if ( expr instanceof E_GreaterThanOrEqual ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( new GreaterThanOrEqual ( e1 , e2 ) ) ; } else if ( expr instanceof E_Add ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( new Add ( e1 , e2 ) ) ; } else if ( expr instanceof E_Subtract ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( new Subtract ( e1 , e2 ) ) ; } else if ( expr instanceof E_Multiply ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( new Multiply ( e1 , e2 ) ) ; } else if ( expr instanceof E_Divide ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; expression . push ( new Divide ( e1 , e2 ) ) ; } else if ( expr instanceof E_Equals ) { convertEquals ( ( E_Equals ) expr ) ; } else if ( expr instanceof E_NotEquals ) { convertNotEquals ( ( E_NotEquals ) expr ) ; } else if ( expr instanceof E_LangMatches ) { convertLangMatches ( ( E_LangMatches ) expr ) ; } else if ( expr instanceof E_SameTerm ) { convertSameTerm ( ( E_SameTerm ) expr ) ; } else if ( extensionSupports ( expr ) ) { expr . getArg ( ) . visit ( this ) ; expr . getArg ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; List < Expression > args = new ArrayList < Expression > ( ) ; args . add ( e1 ) ; args . add ( e2 ) ; extensionConvert ( expr , args ) ; } else { conversionFailed ( expr ) ; } } private void convertEquals ( E_Equals expr ) { logger . debug ( "" + expr . toString ( ) ) ; convertEquality ( expr ) ; } private void convertEquality ( ExprFunction2 expr ) { expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; if ( e1 . equals ( Expression . FALSE ) ) e1 = CONSTANT_FALSE ; else if ( e1 . equals ( Expression . TRUE ) ) e1 = CONSTANT_TRUE ; if ( e2 . equals ( Expression . FALSE ) ) e2 = CONSTANT_FALSE ; else if ( e2 . equals ( Expression . TRUE ) ) e2 = CONSTANT_TRUE ; if ( e1 instanceof AttributeExprEx && e2 instanceof Constant || e2 instanceof AttributeExprEx && e1 instanceof Constant ) { AttributeExprEx variable ; ConstantEx constant ; if ( e1 instanceof AttributeExprEx ) { variable = ( AttributeExprEx ) e1 ; constant = ( ConstantEx ) e2 ; } else { variable = ( AttributeExprEx ) e2 ; constant = ( ConstantEx ) e1 ; } logger . debug ( "" + variable + "" + constant + "" ) ; NodeMaker nm = variable . getNodeMaker ( ) ; if ( nm instanceof TypedNodeMaker ) { ValueMaker vm = ( ( TypedNodeMaker ) nm ) . valueMaker ( ) ; Node node = constant . getNode ( ) ; logger . debug ( "" + node + "" + nm ) ; if ( XSD . isNumeric ( node ) ) { DetermineNodeType filter = new DetermineNodeType ( ) ; nm . describeSelf ( filter ) ; RDFDatatype datatype = filter . getDatatype ( ) ; if ( datatype != null && XSD . isNumeric ( datatype ) ) { RDFDatatype numericType = XSD . getNumericType ( datatype , node . getLiteralDatatype ( ) ) ; nm = cast ( nm , numericType ) ; node = XSD . cast ( node , numericType ) ; } } boolean empty = nm . selectNode ( node , RelationalOperators . DUMMY ) . equals ( NodeMaker . EMPTY ) ; logger . debug ( "" + new Boolean ( empty ) ) ; if ( ! empty ) { if ( node . isURI ( ) ) expression . push ( vm . valueExpression ( node . getURI ( ) ) ) ; else if ( node . isLiteral ( ) ) { if ( XSD . isSupported ( node . getLiteralDatatype ( ) ) ) expression . push ( vm . valueExpression ( constant . value ( ) ) ) ; else conversionFailed ( "" + node . getLiteralDatatypeURI ( ) , expr ) ; } else conversionFailed ( expr ) ; return ; } else { expression . push ( Expression . FALSE ) ; return ; } } else { logger . warn ( "" ) ; } } else if ( e1 instanceof ConstantEx && e2 instanceof ConstantEx ) { logger . debug ( "" + e1 + "" + e2 + "" ) ; Node c1 = ( ( ConstantEx ) e1 ) . getNode ( ) ; Node c2 = ( ( ConstantEx ) e2 ) . getNode ( ) ; boolean equals ; if ( XSD . isNumeric ( c1 ) && XSD . isNumeric ( c2 ) ) { RDFDatatype datatype = XSD . getNumericType ( c1 . getLiteralDatatype ( ) , c2 . getLiteralDatatype ( ) ) ; equals = XSD . cast ( c1 , datatype ) . equals ( XSD . cast ( c2 , datatype ) ) ; } else if ( isSimpleLiteral ( c1 ) && isSimpleLiteral ( c2 ) ) { equals = c1 . getLiteralValue ( ) . equals ( c2 . getLiteralValue ( ) ) ; } else if ( XSD . isString ( c1 ) && XSD . isString ( c2 ) ) { equals = c1 . getLiteralValue ( ) . equals ( c2 . getLiteralValue ( ) ) ; } else { try { equals = NodeFunctions . rdfTermEquals ( c1 , c2 ) ; } catch ( ExprEvalException e ) { equals = false ; } } logger . debug ( "" + new Boolean ( equals ) ) ; expression . push ( equals ? Expression . TRUE : Expression . FALSE ) ; return ; } else if ( e1 instanceof AttributeExprEx && e2 instanceof AttributeExprEx ) { logger . debug ( "" + e1 + "" + e2 + "" ) ; AttributeExprEx variable1 = ( AttributeExprEx ) e1 ; AttributeExprEx variable2 = ( AttributeExprEx ) e2 ; NodeMaker nm1 = variable1 . getNodeMaker ( ) ; NodeMaker nm2 = variable2 . getNodeMaker ( ) ; DetermineNodeType filter1 = new DetermineNodeType ( ) ; nm1 . describeSelf ( filter1 ) ; RDFDatatype datatype1 = filter1 . getDatatype ( ) ; DetermineNodeType filter2 = new DetermineNodeType ( ) ; nm2 . describeSelf ( filter2 ) ; RDFDatatype datatype2 = filter2 . getDatatype ( ) ; if ( datatype1 != null && XSD . isNumeric ( datatype1 ) && datatype2 != null && XSD . isNumeric ( datatype2 ) ) { RDFDatatype numericType = XSD . getNumericType ( filter1 . getDatatype ( ) , filter2 . getDatatype ( ) ) ; nm1 = cast ( nm1 , numericType ) ; nm2 = cast ( nm2 , numericType ) ; } NodeSetConstraintBuilder nodeSet = new NodeSetConstraintBuilder ( ) ; nm1 . describeSelf ( nodeSet ) ; nm2 . describeSelf ( nodeSet ) ; if ( nodeSet . isEmpty ( ) ) { logger . debug ( "" + nm1 + "" + nm2 + "" ) ; expression . push ( Expression . FALSE ) ; return ; } } expression . push ( Equality . create ( e1 , e2 ) ) ; } private void convertNotEquals ( E_NotEquals expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; if ( e1 . equals ( Expression . FALSE ) ) e1 = CONSTANT_FALSE ; else if ( e1 . equals ( Expression . TRUE ) ) e1 = CONSTANT_TRUE ; if ( e2 . equals ( Expression . FALSE ) ) e2 = CONSTANT_FALSE ; else if ( e2 . equals ( Expression . TRUE ) ) e2 = CONSTANT_TRUE ; if ( e1 instanceof AttributeExprEx && e2 instanceof Constant || e2 instanceof AttributeExprEx && e1 instanceof Constant ) { AttributeExprEx variable ; ConstantEx constant ; if ( e1 instanceof AttributeExprEx ) { variable = ( AttributeExprEx ) e1 ; constant = ( ConstantEx ) e2 ; } else { variable = ( AttributeExprEx ) e2 ; constant = ( ConstantEx ) e1 ; } logger . debug ( "" + variable + "" + constant + "" ) ; NodeMaker nm = variable . getNodeMaker ( ) ; if ( nm instanceof TypedNodeMaker ) { ValueMaker vm = ( ( TypedNodeMaker ) nm ) . valueMaker ( ) ; Node node = constant . getNode ( ) ; logger . debug ( "" + node + "" + nm ) ; if ( XSD . isNumeric ( node ) ) { DetermineNodeType filter = new DetermineNodeType ( ) ; nm . describeSelf ( filter ) ; RDFDatatype datatype = filter . getDatatype ( ) ; if ( datatype != null && XSD . isNumeric ( datatype ) ) { RDFDatatype numericType = XSD . getNumericType ( datatype , node . getLiteralDatatype ( ) ) ; nm = cast ( nm , numericType ) ; node = XSD . cast ( node , numericType ) ; } } boolean empty = nm . selectNode ( node , RelationalOperators . DUMMY ) . equals ( NodeMaker . EMPTY ) ; logger . debug ( "" + new Boolean ( empty ) ) ; if ( ! empty ) { if ( node . isURI ( ) ) expression . push ( new Negation ( vm . valueExpression ( node . getURI ( ) ) ) ) ; else if ( node . isLiteral ( ) ) { if ( XSD . isSupported ( node . getLiteralDatatype ( ) ) ) expression . push ( new Negation ( vm . valueExpression ( constant . value ( ) ) ) ) ; else conversionFailed ( "" + node . getLiteralDatatypeURI ( ) , expr ) ; } else conversionFailed ( expr ) ; return ; } else { expression . push ( Expression . TRUE ) ; return ; } } } else if ( e1 instanceof ConstantEx && e2 instanceof ConstantEx ) { logger . debug ( "" + e1 + "" + e2 + "" ) ; Node c1 = ( ( ConstantEx ) e1 ) . getNode ( ) ; Node c2 = ( ( ConstantEx ) e2 ) . getNode ( ) ; boolean equals ; if ( XSD . isNumeric ( c1 ) && XSD . isNumeric ( c2 ) ) { RDFDatatype datatype = XSD . getNumericType ( c1 . getLiteralDatatype ( ) , c2 . getLiteralDatatype ( ) ) ; equals = XSD . cast ( c1 , datatype ) . equals ( XSD . cast ( c2 , datatype ) ) ; } else if ( isSimpleLiteral ( c1 ) && isSimpleLiteral ( c2 ) ) { equals = c1 . getLiteralValue ( ) . equals ( c2 . getLiteralValue ( ) ) ; } else if ( XSD . isString ( c1 ) && XSD . isString ( c2 ) ) { equals = c1 . getLiteralValue ( ) . equals ( c2 . getLiteralValue ( ) ) ; } else { try { equals = NodeFunctions . rdfTermEquals ( c1 , c2 ) ; } catch ( ExprEvalException e ) { equals = false ; } } logger . debug ( "" + new Boolean ( equals ) ) ; expression . push ( equals ? Expression . FALSE : Expression . TRUE ) ; return ; } else if ( e1 instanceof AttributeExprEx && e2 instanceof AttributeExprEx ) { logger . debug ( "" + e1 + "" + e2 + "" ) ; AttributeExprEx variable1 = ( AttributeExprEx ) e1 ; AttributeExprEx variable2 = ( AttributeExprEx ) e2 ; NodeMaker nm1 = variable1 . getNodeMaker ( ) ; NodeMaker nm2 = variable2 . getNodeMaker ( ) ; DetermineNodeType filter1 = new DetermineNodeType ( ) ; nm1 . describeSelf ( filter1 ) ; RDFDatatype datatype1 = filter1 . getDatatype ( ) ; DetermineNodeType filter2 = new DetermineNodeType ( ) ; nm2 . describeSelf ( filter2 ) ; RDFDatatype datatype2 = filter2 . getDatatype ( ) ; if ( datatype1 != null && XSD . isNumeric ( datatype1 ) && datatype2 != null && XSD . isNumeric ( datatype2 ) ) { RDFDatatype numericType = XSD . getNumericType ( filter1 . getDatatype ( ) , filter2 . getDatatype ( ) ) ; nm1 = cast ( nm1 , numericType ) ; nm2 = cast ( nm2 , numericType ) ; } NodeSetConstraintBuilder nodeSet = new NodeSetConstraintBuilder ( ) ; nm1 . describeSelf ( nodeSet ) ; nm2 . describeSelf ( nodeSet ) ; if ( nodeSet . isEmpty ( ) ) { logger . debug ( "" + nm1 + "" + nm2 + "" ) ; expression . push ( Expression . TRUE ) ; return ; } } expression . push ( new Negation ( Equality . create ( e1 , e2 ) ) ) ; } private void convertLogicalNot ( E_LogicalNot expr ) { expr . getArg ( ) . visit ( this ) ; Expression e1 = expression . pop ( ) ; if ( e1 instanceof Negation ) expression . push ( ( ( Negation ) e1 ) . getBase ( ) ) ; else expression . push ( new Negation ( e1 ) ) ; } private void convert ( E_UnaryPlus expr ) { expr . getArg ( ) . visit ( this ) ; } private void convert ( E_UnaryMinus expr ) { expr . getArg ( ) . visit ( this ) ; Expression e1 = expression . pop ( ) ; if ( e1 instanceof UnaryMinus ) expression . push ( ( ( UnaryMinus ) e1 ) . getBase ( ) ) ; else expression . push ( new UnaryMinus ( e1 ) ) ; } private void convertIsIRI ( E_IsIRI expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg ( ) . visit ( this ) ; Expression arg = expression . pop ( ) ; if ( arg instanceof AttributeExprEx ) { AttributeExprEx variable = ( AttributeExprEx ) arg ; NodeMaker nm = variable . getNodeMaker ( ) ; DetermineNodeType filter = new DetermineNodeType ( ) ; nm . describeSelf ( filter ) ; expression . push ( filter . isLimittedToURIs ( ) ? Expression . TRUE : Expression . FALSE ) ; } else if ( arg instanceof ConstantEx ) { ConstantEx constant = ( ConstantEx ) arg ; Node node = constant . getNode ( ) ; expression . push ( node . isURI ( ) ? Expression . TRUE : Expression . FALSE ) ; } else { conversionFailed ( expr ) ; } } private void convertIsBlank ( E_IsBlank expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg ( ) . visit ( this ) ; Expression arg = expression . pop ( ) ; if ( arg instanceof AttributeExprEx ) { AttributeExprEx variable = ( AttributeExprEx ) arg ; NodeMaker nm = variable . getNodeMaker ( ) ; DetermineNodeType filter = new DetermineNodeType ( ) ; nm . describeSelf ( filter ) ; expression . push ( filter . isLimittedToBlankNodes ( ) ? Expression . TRUE : Expression . FALSE ) ; } else if ( arg instanceof ConstantEx ) { ConstantEx constant = ( ConstantEx ) arg ; Node node = constant . getNode ( ) ; expression . push ( node . isBlank ( ) ? Expression . TRUE : Expression . FALSE ) ; } else { conversionFailed ( expr ) ; } } private void convertIsLiteral ( E_IsLiteral expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg ( ) . visit ( this ) ; Expression arg = expression . pop ( ) ; logger . debug ( "" + arg ) ; if ( arg instanceof AttributeExprEx ) { AttributeExprEx variable = ( AttributeExprEx ) arg ; NodeMaker nm = variable . getNodeMaker ( ) ; DetermineNodeType filter = new DetermineNodeType ( ) ; nm . describeSelf ( filter ) ; expression . push ( filter . isLimittedToLiterals ( ) ? Expression . TRUE : Expression . FALSE ) ; } else if ( arg instanceof ConstantEx ) { ConstantEx constant = ( ConstantEx ) arg ; Node node = constant . getNode ( ) ; expression . push ( node . isLiteral ( ) ? Expression . TRUE : Expression . FALSE ) ; } else { conversionFailed ( expr ) ; } } private void convertStr ( E_Str expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg ( ) . visit ( this ) ; Expression arg = expression . pop ( ) ; if ( arg instanceof AttributeExprEx ) { AttributeExprEx attribute = ( AttributeExprEx ) arg ; TypedNodeMaker nodeMaker = ( TypedNodeMaker ) attribute . getNodeMaker ( ) ; TypedNodeMaker newNodeMaker = new TypedNodeMaker ( TypedNodeMaker . PLAIN_LITERAL , nodeMaker . valueMaker ( ) , nodeMaker . isUnique ( ) ) ; logger . debug ( "" + nodeMaker + "" + newNodeMaker ) ; expression . push ( new AttributeExprEx ( ( Attribute ) attribute . attributes ( ) . iterator ( ) . next ( ) , newNodeMaker ) ) ; } else if ( arg instanceof ConstantEx ) { ConstantEx constant = ( ConstantEx ) arg ; Node node = constant . getNode ( ) ; String lexicalForm = node . getLiteral ( ) . getLexicalForm ( ) ; node = Node . createLiteral ( lexicalForm ) ; ConstantEx constantEx = new ConstantEx ( NodeValue . makeNode ( node ) . asString ( ) , node ) ; logger . debug ( "" + constantEx ) ; expression . push ( constantEx ) ; } else { conversionFailed ( expr ) ; } } private void convertLang ( E_Lang expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg ( ) . visit ( this ) ; Expression arg = expression . pop ( ) ; if ( arg instanceof AttributeExprEx ) { AttributeExprEx variable = ( AttributeExprEx ) arg ; NodeMaker nm = variable . getNodeMaker ( ) ; DetermineNodeType filter = new DetermineNodeType ( ) ; nm . describeSelf ( filter ) ; String lang = filter . getLanguage ( ) ; logger . debug ( "" + lang ) ; if ( lang == null ) lang = "" ; Node node = Node . createLiteral ( lang ) ; ConstantEx constantEx = new ConstantEx ( NodeValue . makeNode ( node ) . asString ( ) , node ) ; logger . debug ( "" + constantEx ) ; expression . push ( constantEx ) ; } else if ( arg instanceof ConstantEx ) { ConstantEx constant = ( ConstantEx ) arg ; Node node = constant . getNode ( ) ; if ( ! node . isLiteral ( ) ) { logger . warn ( "" + node + "" ) ; expression . push ( Expression . FALSE ) ; return ; } String lang = node . getLiteralLanguage ( ) ; logger . debug ( "" + lang ) ; if ( lang == null ) lang = "" ; node = Node . createLiteral ( lang ) ; ConstantEx constantEx = new ConstantEx ( NodeValue . makeNode ( node ) . asString ( ) , node ) ; logger . debug ( "" + constantEx ) ; expression . push ( constantEx ) ; } else { conversionFailed ( expr ) ; } } private void convertDataType ( E_Datatype expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg ( ) . visit ( this ) ; Expression arg = expression . pop ( ) ; if ( arg instanceof AttributeExprEx ) { AttributeExprEx variable = ( AttributeExprEx ) arg ; NodeMaker nm = variable . getNodeMaker ( ) ; DetermineNodeType filter = new DetermineNodeType ( ) ; nm . describeSelf ( filter ) ; if ( ! filter . isLimittedToLiterals ( ) ) { logger . warn ( "" + variable + "" ) ; expression . push ( Expression . FALSE ) ; return ; } RDFDatatype datatype = filter . getDatatype ( ) ; logger . debug ( "" + datatype ) ; Node node = Node . createURI ( ( datatype != null ) ? datatype . getURI ( ) : XSDDatatype . XSDstring . getURI ( ) ) ; ConstantEx constantEx = new ConstantEx ( NodeValue . makeNode ( node ) . asString ( ) , node ) ; logger . debug ( "" + constantEx ) ; expression . push ( constantEx ) ; } else if ( arg instanceof ConstantEx ) { ConstantEx constant = ( ConstantEx ) arg ; Node node = constant . getNode ( ) ; if ( ! node . isLiteral ( ) ) { logger . warn ( "" + node + "" ) ; expression . push ( Expression . FALSE ) ; return ; } RDFDatatype datatype = node . getLiteralDatatype ( ) ; logger . debug ( "" + datatype ) ; node = Node . createURI ( ( datatype != null ) ? datatype . getURI ( ) : XSDDatatype . XSDstring . getURI ( ) ) ; ConstantEx constantEx = new ConstantEx ( NodeValue . makeNode ( node ) . asString ( ) , node ) ; logger . debug ( "" + constantEx ) ; expression . push ( constantEx ) ; } else { conversionFailed ( expr ) ; } } private void convertSameTerm ( E_SameTerm expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; if ( e1 . equals ( Expression . FALSE ) ) e1 = CONSTANT_FALSE ; else if ( e1 . equals ( Expression . TRUE ) ) e1 = CONSTANT_TRUE ; if ( e2 . equals ( Expression . FALSE ) ) e2 = CONSTANT_FALSE ; else if ( e2 . equals ( Expression . TRUE ) ) e2 = CONSTANT_TRUE ; if ( e1 instanceof AttributeExprEx && e2 instanceof Constant || e2 instanceof AttributeExprEx && e1 instanceof Constant ) { AttributeExprEx variable ; ConstantEx constant ; if ( e1 instanceof AttributeExprEx ) { variable = ( AttributeExprEx ) e1 ; constant = ( ConstantEx ) e2 ; } else { variable = ( AttributeExprEx ) e2 ; constant = ( ConstantEx ) e1 ; } logger . debug ( "" + variable + "" + constant + "" ) ; NodeMaker nm = variable . getNodeMaker ( ) ; if ( nm instanceof TypedNodeMaker ) { ValueMaker vm = ( ( TypedNodeMaker ) nm ) . valueMaker ( ) ; Node node = constant . getNode ( ) ; logger . debug ( "" + node + "" + nm ) ; boolean empty = nm . selectNode ( node , RelationalOperators . DUMMY ) . equals ( NodeMaker . EMPTY ) ; logger . debug ( "" + new Boolean ( empty ) ) ; if ( ! empty ) { if ( node . isURI ( ) ) expression . push ( vm . valueExpression ( node . getURI ( ) ) ) ; else if ( node . isLiteral ( ) ) expression . push ( vm . valueExpression ( constant . value ( ) ) ) ; else conversionFailed ( expr ) ; return ; } else { expression . push ( Expression . FALSE ) ; return ; } } else { logger . warn ( "" ) ; } } else if ( e1 instanceof ConstantEx && e2 instanceof ConstantEx ) { logger . debug ( "" + e1 + "" + e2 + "" ) ; ConstantEx constant1 = ( ConstantEx ) e1 ; ConstantEx constant2 = ( ConstantEx ) e2 ; boolean equals = NodeFunctions . sameTerm ( constant1 . getNode ( ) , constant2 . getNode ( ) ) ; logger . debug ( "" + new Boolean ( equals ) ) ; expression . push ( equals ? Expression . TRUE : Expression . FALSE ) ; return ; } else if ( e1 instanceof AttributeExprEx && e2 instanceof AttributeExprEx ) { logger . debug ( "" + e1 + "" + e2 + "" ) ; AttributeExprEx variable1 = ( AttributeExprEx ) e1 ; AttributeExprEx variable2 = ( AttributeExprEx ) e2 ; NodeMaker nm1 = variable1 . getNodeMaker ( ) ; NodeMaker nm2 = variable2 . getNodeMaker ( ) ; NodeSetConstraintBuilder nodeSet = new NodeSetConstraintBuilder ( ) ; nm1 . describeSelf ( nodeSet ) ; nm2 . describeSelf ( nodeSet ) ; if ( nodeSet . isEmpty ( ) ) { logger . debug ( "" + nm1 + "" + nm2 + "" ) ; expression . push ( Expression . FALSE ) ; return ; } } expression . push ( Equality . create ( e1 , e2 ) ) ; } private void convertLangMatches ( E_LangMatches expr ) { logger . debug ( "" + expr . toString ( ) ) ; expr . getArg1 ( ) . visit ( this ) ; expr . getArg2 ( ) . visit ( this ) ; Expression e2 = expression . pop ( ) ; Expression e1 = expression . pop ( ) ; if ( e1 instanceof ConstantEx && e2 instanceof ConstantEx ) { ConstantEx lang1 = ( ConstantEx ) e1 ; ConstantEx lang2 = ( ConstantEx ) e2 ; NodeValue nv1 = NodeValue . makeString ( lang1 . getNode ( ) . getLiteral ( ) . getLexicalForm ( ) ) ; NodeValue nv2 = NodeValue . makeString ( lang2 . getNode ( ) . getLiteral ( ) . getLexicalForm ( ) ) ; NodeValue match = NodeFunctions . langMatches ( nv1 , nv2 ) ; expression . push ( match . equals ( NodeValue . TRUE ) ? Expression . TRUE : Expression . FALSE ) ; } else { expression . push ( Expression . FALSE ) ; } } private void conversionFailed ( Expr unconvertableExpr ) { expression . push ( Expression . FALSE ) ; convertable = false ; if ( reason == null ) reason = "" + unconvertableExpr . toString ( ) ; } private void conversionFailed ( String message , Expr unconvertableExpr ) { expression . push ( Expression . FALSE ) ; convertable = false ; if ( reason == null ) reason = "" + unconvertableExpr . toString ( ) + "" + message ; } static NodeMaker cast ( NodeMaker nodeMaker , RDFDatatype datatype ) { if ( nodeMaker instanceof TypedNodeMaker ) return new TypedNodeMaker ( TypedNodeMaker . typedLiteral ( datatype ) , ( ( TypedNodeMaker ) nodeMaker ) . valueMaker ( ) , nodeMaker . isUnique ( ) ) ; if ( nodeMaker instanceof FixedNodeMaker ) { Node node = nodeMaker . makeNode ( null ) ; return new FixedNodeMaker ( XSD . cast ( node , datatype ) , nodeMaker . isUnique ( ) ) ; } throw new RuntimeException ( "" ) ; } static boolean isSimpleLiteral ( Node node ) { if ( ! node . isLiteral ( ) ) return false ; return node . getLiteralDatatype ( ) == null && "" . equals ( node . getLiteralLanguage ( ) ) ; } protected boolean extensionSupports ( ExprFunction function ) { return false ; } protected void extensionConvert ( ExprFunction function , List < Expression > args ) { } } package de . fuberlin . wiwiss . d2rq . optimizer . expr ; import com . hp . hpl . jena . graph . Node ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . expr . Constant ; public class ConstantEx extends Constant { private final Node node ; public ConstantEx ( String value , Attribute attributeForTrackingType , Node node ) { super ( value , attributeForTrackingType ) ; this . node = node ; } public ConstantEx ( String value , Node node ) { super ( value ) ; this . node = node ; } public Node getNode ( ) { return node ; } } package de . fuberlin . wiwiss . d2rq . csv ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileReader ; import java . io . IOException ; import java . io . Reader ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . n3 . IRIResolver ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . map . TranslationTable . Translation ; public class TranslationTableParser { private Log log = LogFactory . getLog ( TranslationTableParser . class ) ; private BufferedReader reader ; private CSV csvLineParser = new CSV ( ) ; private String url ; public TranslationTableParser ( Reader reader ) { this . reader = new BufferedReader ( reader ) ; } public TranslationTableParser ( String url ) { try { this . url = new IRIResolver ( ) . resolve ( url ) ; ; this . reader = new BufferedReader ( new FileReader ( new File ( new URI ( this . url ) ) ) ) ; } catch ( FileNotFoundException fnfex ) { throw new D2RQException ( "" + this . url ) ; } catch ( URISyntaxException usynex ) { throw new D2RQException ( "" + this . url ) ; } } public Collection < Translation > parseTranslations ( ) { try { List < Translation > result = new ArrayList < Translation > ( ) ; while ( true ) { String line = this . reader . readLine ( ) ; if ( line == null ) { break ; } String [ ] fields = this . csvLineParser . parse ( line ) ; if ( fields . length != ) { this . log . warn ( "" + fields . length + "" + this . url ) ; continue ; } result . add ( new Translation ( fields [ ] , fields [ ] ) ) ; } return result ; } catch ( IOException iex ) { throw new D2RQException ( iex ) ; } } } package de . fuberlin . wiwiss . d2rq . csv ; import java . util . ArrayList ; class CSV { public static final char DEFAULT_SEP = '' ; public CSV ( ) { this ( DEFAULT_SEP ) ; } public CSV ( char sep ) { this . fieldSep = sep ; } private ArrayList < String > list = new ArrayList < String > ( ) ; private char fieldSep ; public String [ ] parse ( String line ) { StringBuffer sb = new StringBuffer ( ) ; this . list . clear ( ) ; int i = ; if ( line . length ( ) == ) { this . list . add ( line ) ; return ( String [ ] ) this . list . toArray ( new String [ ] { } ) ; } do { sb . setLength ( ) ; if ( i < line . length ( ) && line . charAt ( i ) == '' ) i = advQuoted ( line , sb , ++ i ) ; else i = advPlain ( line , sb , i ) ; this . list . add ( sb . toString ( ) ) ; i ++ ; } while ( i < line . length ( ) ) ; return ( String [ ] ) this . list . toArray ( new String [ ] { } ) ; } private int advQuoted ( String s , StringBuffer sb , int i ) { int j ; int len = s . length ( ) ; for ( j = i ; j < len ; j ++ ) { if ( s . charAt ( j ) == '' && j + < len ) { if ( s . charAt ( j + ) == '' ) { j ++ ; } else if ( s . charAt ( j + ) == this . fieldSep ) { j ++ ; break ; } } else if ( s . charAt ( j ) == '' && j + == len ) { break ; } sb . append ( s . charAt ( j ) ) ; } return j ; } private int advPlain ( String s , StringBuffer sb , int i ) { int j ; j = s . indexOf ( this . fieldSep , i ) ; if ( j == - ) { sb . append ( s . substring ( i ) ) ; return s . length ( ) ; } sb . append ( s . substring ( i , j ) ) ; return j ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . ArrayList ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . sparql . algebra . Op ; import com . hp . hpl . jena . sparql . algebra . TransformCopy ; import com . hp . hpl . jena . sparql . algebra . op . OpBGP ; import com . hp . hpl . jena . sparql . algebra . op . OpFilter ; import com . hp . hpl . jena . sparql . expr . Expr ; import com . hp . hpl . jena . sparql . expr . ExprList ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; import de . fuberlin . wiwiss . d2rq . optimizer . expr . TransformExprToSQLApplyer ; public class TransformOpBGP extends TransformCopy { private final static Log log = LogFactory . getLog ( TransformOpBGP . class ) ; private final Mapping mapping ; private final boolean useAllOptimizations ; private final boolean transformFilters ; public TransformOpBGP ( Mapping mapping , boolean transformFilters ) { this . mapping = mapping ; this . transformFilters = transformFilters ; this . useAllOptimizations = mapping . configuration ( ) . getUseAllOptimizations ( ) ; } @ Override public Op transform ( OpBGP opBGP ) { if ( transformFilters ) { return opBGP ; } return createOpD2RQ ( opBGP , new ExprList ( ) ) ; } @ Override public Op transform ( OpFilter opFilter , Op subOp ) { if ( ! transformFilters || ! ( opFilter . getSubOp ( ) instanceof OpBGP ) ) { return super . transform ( opFilter , subOp ) ; } return createOpD2RQ ( ( OpBGP ) subOp , opFilter . getExprs ( ) ) ; } public Op createOpD2RQ ( OpBGP opBGP , ExprList filters ) { List < NodeRelation > tables = new GraphPatternTranslator ( opBGP . getPattern ( ) . getList ( ) , mapping . compiledPropertyBridges ( ) , useAllOptimizations ) . translate ( ) ; if ( useAllOptimizations ) { log . debug ( "" + tables . size ( ) ) ; ExprList copy = new ExprList ( filters ) ; for ( Expr filter : copy ) { tables = applyFilter ( tables , filter , filters ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "" + tables . size ( ) ) ; } } Op op = OpUnionTableSQL . create ( tables ) ; if ( ! filters . isEmpty ( ) ) { op = OpFilter . filter ( filters , op ) ; } return op ; } private List < NodeRelation > applyFilter ( List < NodeRelation > nodeRelations , Expr filter , ExprList allFilters ) { List < NodeRelation > result = new ArrayList < NodeRelation > ( ) ; boolean convertable = true ; for ( NodeRelation nodeRelation : nodeRelations ) { Expression expression = TransformExprToSQLApplyer . convert ( filter , nodeRelation ) ; if ( expression == null ) { convertable = false ; } else if ( expression . isTrue ( ) ) { } else if ( expression . isFalse ( ) ) { continue ; } else { nodeRelation = nodeRelation . select ( expression ) ; if ( nodeRelation . baseRelation ( ) . condition ( ) . isFalse ( ) ) continue ; } result . add ( nodeRelation ) ; } if ( convertable ) { log . debug ( "" + filter ) ; allFilters . getList ( ) . remove ( filter ) ; } else { log . debug ( "" + filter ) ; } return result ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . HashMap ; import java . util . Map ; import java . util . Set ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . sparql . core . Var ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import com . hp . hpl . jena . sparql . engine . binding . BindingHashMap ; import com . hp . hpl . jena . sparql . engine . binding . BindingMap ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; public class BindingMaker { public static BindingMaker createFor ( NodeRelation relation ) { Map < Var , NodeMaker > vars = new HashMap < Var , NodeMaker > ( ) ; for ( Var variable : relation . variables ( ) ) { vars . put ( variable , relation . nodeMaker ( variable ) ) ; } return new BindingMaker ( vars , null ) ; } private final Map < Var , NodeMaker > nodeMakers ; private final ProjectionSpec condition ; public BindingMaker ( Map < Var , NodeMaker > nodeMakers , ProjectionSpec condition ) { this . nodeMakers = nodeMakers ; this . condition = condition ; } public Binding makeBinding ( ResultRow row ) { if ( condition != null ) { String value = row . get ( condition ) ; if ( value == null || "" . equals ( value ) || "" . equals ( value ) || "" . equals ( value ) ) { return null ; } } BindingMap result = new BindingHashMap ( ) ; for ( Var variableName : nodeMakers . keySet ( ) ) { Node node = nodeMakers . get ( variableName ) . makeNode ( row ) ; if ( node == null ) { return null ; } result . add ( Var . alloc ( variableName ) , node ) ; } return result ; } public Set < Var > variableNames ( ) { return nodeMakers . keySet ( ) ; } public NodeMaker nodeMaker ( Var var ) { return nodeMakers . get ( var ) ; } public ProjectionSpec condition ( ) { return condition ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; for ( Var variable : nodeMakers . keySet ( ) ) { result . append ( "" ) ; result . append ( variable ) ; result . append ( "" ) ; result . append ( nodeMakers . get ( variable ) ) ; result . append ( "" ) ; } result . append ( "" ) ; if ( condition != null ) { result . append ( "" ) ; result . append ( condition ) ; } return result . toString ( ) ; } public BindingMaker makeConditional ( ProjectionSpec condition ) { return new BindingMaker ( nodeMakers , condition ) ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import java . util . Stack ; import com . hp . hpl . jena . sparql . algebra . Op ; import com . hp . hpl . jena . sparql . algebra . OpVisitor ; import com . hp . hpl . jena . sparql . algebra . TransformCopy ; import com . hp . hpl . jena . sparql . algebra . op . Op1 ; import com . hp . hpl . jena . sparql . algebra . op . Op2 ; import com . hp . hpl . jena . sparql . algebra . op . OpAssign ; import com . hp . hpl . jena . sparql . algebra . op . OpBGP ; import com . hp . hpl . jena . sparql . algebra . op . OpConditional ; import com . hp . hpl . jena . sparql . algebra . op . OpDatasetNames ; import com . hp . hpl . jena . sparql . algebra . op . OpDiff ; import com . hp . hpl . jena . sparql . algebra . op . OpDisjunction ; import com . hp . hpl . jena . sparql . algebra . op . OpDistinct ; import com . hp . hpl . jena . sparql . algebra . op . OpExt ; import com . hp . hpl . jena . sparql . algebra . op . OpExtend ; import com . hp . hpl . jena . sparql . algebra . op . OpFilter ; import com . hp . hpl . jena . sparql . algebra . op . OpGraph ; import com . hp . hpl . jena . sparql . algebra . op . OpGroup ; import com . hp . hpl . jena . sparql . algebra . op . OpJoin ; import com . hp . hpl . jena . sparql . algebra . op . OpLabel ; import com . hp . hpl . jena . sparql . algebra . op . OpLeftJoin ; import com . hp . hpl . jena . sparql . algebra . op . OpList ; import com . hp . hpl . jena . sparql . algebra . op . OpMinus ; import com . hp . hpl . jena . sparql . algebra . op . OpN ; import com . hp . hpl . jena . sparql . algebra . op . OpNull ; import com . hp . hpl . jena . sparql . algebra . op . OpOrder ; import com . hp . hpl . jena . sparql . algebra . op . OpPath ; import com . hp . hpl . jena . sparql . algebra . op . OpProcedure ; import com . hp . hpl . jena . sparql . algebra . op . OpProject ; import com . hp . hpl . jena . sparql . algebra . op . OpPropFunc ; import com . hp . hpl . jena . sparql . algebra . op . OpQuad ; import com . hp . hpl . jena . sparql . algebra . op . OpQuadPattern ; import com . hp . hpl . jena . sparql . algebra . op . OpReduced ; import com . hp . hpl . jena . sparql . algebra . op . OpSequence ; import com . hp . hpl . jena . sparql . algebra . op . OpService ; import com . hp . hpl . jena . sparql . algebra . op . OpSlice ; import com . hp . hpl . jena . sparql . algebra . op . OpTable ; import com . hp . hpl . jena . sparql . algebra . op . OpTopN ; import com . hp . hpl . jena . sparql . algebra . op . OpTriple ; import com . hp . hpl . jena . sparql . algebra . op . OpUnion ; import com . hp . hpl . jena . sparql . core . Var ; import com . hp . hpl . jena . sparql . expr . Expr ; import com . hp . hpl . jena . sparql . expr . ExprList ; public class PushDownOpFilterVisitor implements OpVisitor { public static Op transform ( Op op ) { PushDownOpFilterVisitor visitor = new PushDownOpFilterVisitor ( ) ; op . visit ( visitor ) ; return visitor . result ( ) ; } private final TransformCopy copy = new TransformCopy ( false ) ; private final Stack < Op > stack = new Stack < Op > ( ) ; private List < Expr > filterExpr = new ArrayList < Expr > ( ) ; public Op result ( ) { if ( stack . size ( ) != ) { throw new IllegalStateException ( "" ) ; } return stack . pop ( ) ; } public void visit ( final OpFilter opFilter ) { filterExpr . addAll ( opFilter . getExprs ( ) . getList ( ) ) ; Op subOp = null ; if ( opFilter . getSubOp ( ) != null ) { opFilter . getSubOp ( ) . visit ( this ) ; subOp = stack . pop ( ) ; } opFilter . getExprs ( ) . getList ( ) . removeAll ( filterExpr ) ; if ( opFilter . getExprs ( ) . isEmpty ( ) ) { stack . push ( subOp ) ; } else { stack . push ( opFilter ) ; } } public void visit ( OpUnion opUnion ) { checkMoveDownFilterExprAndVisitOpUnion ( opUnion ) ; } public void visit ( OpJoin opJoin ) { checkMoveDownFilterExprAndVisitOpJoin ( opJoin ) ; } public void visit ( OpBGP op ) { wrapInCurrentFilter ( op ) ; } public void visit ( OpDiff opDiff ) { checkMoveDownFilterExprAndVisitOpDiff ( opDiff ) ; } public void visit ( OpConditional opCondition ) { wrapInCurrentFilterAndRecurse ( opCondition ) ; } public void visit ( OpProcedure opProc ) { wrapInCurrentFilterAndRecurse ( opProc ) ; } public void visit ( OpPropFunc opPropFunc ) { wrapInCurrentFilterAndRecurse ( opPropFunc ) ; } public void visit ( OpTable opTable ) { wrapInCurrentFilter ( opTable ) ; } public void visit ( OpQuadPattern quadPattern ) { wrapInCurrentFilter ( quadPattern ) ; } public void visit ( OpPath opPath ) { wrapInCurrentFilter ( opPath ) ; } public void visit ( OpTriple opTriple ) { wrapInCurrentFilter ( opTriple ) ; } public void visit ( OpDatasetNames dsNames ) { wrapInCurrentFilter ( dsNames ) ; } public void visit ( OpSequence opSequence ) { wrapInCurrentFilterAndRecurse ( opSequence ) ; } public void visit ( OpLeftJoin opLeftJoin ) { checkMoveDownFilterExprAndVisitOpLeftJoin ( opLeftJoin ) ; } public void visit ( OpGraph opGraph ) { wrapInCurrentFilterAndRecurse ( opGraph ) ; } public void visit ( OpService opService ) { wrapInCurrentFilter ( opService ) ; } public void visit ( OpExt opExt ) { wrapInCurrentFilter ( opExt ) ; } public void visit ( OpNull opNull ) { wrapInCurrentFilter ( opNull ) ; } public void visit ( OpLabel opLabel ) { moveFilterPast ( opLabel ) ; } public void visit ( OpList opList ) { wrapInCurrentFilterAndRecurse ( opList ) ; } public void visit ( OpOrder opOrder ) { wrapInCurrentFilterAndRecurse ( opOrder ) ; } public void visit ( OpProject opProject ) { wrapInCurrentFilterAndRecurse ( opProject ) ; } public void visit ( OpDistinct opDistinct ) { wrapInCurrentFilterAndRecurse ( opDistinct ) ; } public void visit ( OpReduced opReduced ) { wrapInCurrentFilterAndRecurse ( opReduced ) ; } public void visit ( OpAssign opAssign ) { wrapInCurrentFilterAndRecurse ( opAssign ) ; } public void visit ( OpSlice opSlice ) { wrapInCurrentFilterAndRecurse ( opSlice ) ; } public void visit ( OpGroup opGroup ) { wrapInCurrentFilterAndRecurse ( opGroup ) ; } public void visit ( OpExtend opExtend ) { wrapInCurrentFilterAndRecurse ( opExtend ) ; } public void visit ( OpMinus opMinus ) { opMinus . getLeft ( ) . visit ( this ) ; Op leftWithFilter = stack . pop ( ) ; List < Expr > tmp = filterExpr ; filterExpr = new ArrayList < Expr > ( ) ; opMinus . getRight ( ) . visit ( this ) ; Op right = stack . pop ( ) ; filterExpr = tmp ; stack . push ( OpMinus . create ( leftWithFilter , right ) ) ; } public void visit ( OpDisjunction opDisjunction ) { wrapInCurrentFilterAndRecurse ( opDisjunction ) ; } public void visit ( OpTopN opTop ) { wrapInCurrentFilterAndRecurse ( opTop ) ; } public void visit ( OpQuad opQuad ) { wrapInCurrentFilter ( opQuad ) ; } private void wrapInCurrentFilterAndRecurse ( Op1 op1 ) { List < Expr > retainedFilterExpr = new ArrayList < Expr > ( filterExpr ) ; filterExpr . clear ( ) ; Op subOp = null ; if ( op1 . getSubOp ( ) != null ) { op1 . getSubOp ( ) . visit ( this ) ; subOp = stack . pop ( ) ; } wrapInFilter ( op1 . apply ( copy , subOp ) , retainedFilterExpr ) ; filterExpr = retainedFilterExpr ; } private void wrapInCurrentFilterAndRecurse ( Op2 op2 ) { List < Expr > retainedFilterExpr = new ArrayList < Expr > ( filterExpr ) ; filterExpr . clear ( ) ; Op left = null ; if ( op2 . getLeft ( ) != null ) { op2 . getLeft ( ) . visit ( this ) ; left = stack . pop ( ) ; } Op right = null ; if ( op2 . getRight ( ) != null ) { op2 . getRight ( ) . visit ( this ) ; right = stack . pop ( ) ; } wrapInFilter ( op2 . apply ( copy , left , right ) , retainedFilterExpr ) ; filterExpr = retainedFilterExpr ; } private void wrapInCurrentFilterAndRecurse ( OpN opN ) { List < Expr > retainedFilterExpr = new ArrayList < Expr > ( filterExpr ) ; filterExpr . clear ( ) ; List < Op > children = new ArrayList < Op > ( ) ; for ( Op child : opN . getElements ( ) ) { child . visit ( this ) ; children . add ( stack . pop ( ) ) ; } wrapInFilter ( opN . apply ( copy , children ) , retainedFilterExpr ) ; filterExpr = retainedFilterExpr ; } private void wrapInCurrentFilter ( Op op ) { wrapInFilter ( op , filterExpr ) ; } private void wrapInFilter ( Op op , List < Expr > filters ) { if ( filterExpr . isEmpty ( ) ) { stack . push ( op ) ; } else { stack . push ( OpFilter . filter ( new ExprList ( filters ) , op ) ) ; } } private void moveFilterPast ( Op1 op1 ) { op1 . getSubOp ( ) . visit ( this ) ; } private List < Expr > calcValidFilterExpr ( List < Expr > candidates , Op op ) { Set < Var > mentionedVars = VarCollector . mentionedVars ( op ) ; List < Expr > result = new ArrayList < Expr > ( ) ; for ( Expr expr : candidates ) { if ( mentionedVars . containsAll ( expr . getVarsMentioned ( ) ) ) { result . add ( expr ) ; } } return result ; } private void checkMoveDownFilterExprAndVisitOpUnion ( OpUnion opUnion ) { Op left = null ; Op right = null ; Op newOp ; List < Expr > filterExprBeforeOpUnion , filterExprAfterOpUnion , notMoveableFilterExpr ; filterExprBeforeOpUnion = new ArrayList < Expr > ( this . filterExpr ) ; filterExprAfterOpUnion = new ArrayList < Expr > ( ) ; if ( ( left = opUnion . getLeft ( ) ) != null ) { this . filterExpr = calcValidFilterExpr ( filterExprBeforeOpUnion , left ) ; filterExprAfterOpUnion . addAll ( this . filterExpr ) ; opUnion . getLeft ( ) . visit ( this ) ; left = stack . pop ( ) ; } if ( ( right = opUnion . getRight ( ) ) != null ) { this . filterExpr = calcValidFilterExpr ( filterExprBeforeOpUnion , right ) ; filterExprAfterOpUnion . addAll ( this . filterExpr ) ; opUnion . getRight ( ) . visit ( this ) ; right = stack . pop ( ) ; } notMoveableFilterExpr = new ArrayList < Expr > ( filterExprBeforeOpUnion ) ; notMoveableFilterExpr . removeAll ( filterExprAfterOpUnion ) ; if ( ! notMoveableFilterExpr . isEmpty ( ) ) { newOp = OpFilter . filter ( OpUnion . create ( left , right ) ) ; ( ( OpFilter ) newOp ) . getExprs ( ) . getList ( ) . addAll ( notMoveableFilterExpr ) ; } else { newOp = opUnion ; } this . filterExpr = filterExprBeforeOpUnion ; this . stack . push ( newOp ) ; } private void checkMoveDownFilterExprAndVisitOpJoin ( OpJoin opJoin ) { Op left = null ; Op right = null ; Op newOp ; List < Expr > filterExprBeforeOpJoin , filterExprAfterOpJoin , notMoveableFilterExpr ; filterExprBeforeOpJoin = new ArrayList < Expr > ( this . filterExpr ) ; filterExprAfterOpJoin = new ArrayList < Expr > ( ) ; if ( ( left = opJoin . getLeft ( ) ) != null ) { this . filterExpr = calcValidFilterExpr ( filterExprBeforeOpJoin , left ) ; filterExprAfterOpJoin . addAll ( this . filterExpr ) ; opJoin . getLeft ( ) . visit ( this ) ; left = stack . pop ( ) ; } if ( ( right = opJoin . getRight ( ) ) != null ) { this . filterExpr = calcValidFilterExpr ( filterExprBeforeOpJoin , right ) ; filterExprAfterOpJoin . addAll ( this . filterExpr ) ; opJoin . getRight ( ) . visit ( this ) ; right = stack . pop ( ) ; } notMoveableFilterExpr = new ArrayList < Expr > ( filterExprBeforeOpJoin ) ; notMoveableFilterExpr . removeAll ( filterExprAfterOpJoin ) ; if ( ! notMoveableFilterExpr . isEmpty ( ) ) { newOp = OpFilter . filter ( OpJoin . create ( left , right ) ) ; ( ( OpFilter ) newOp ) . getExprs ( ) . getList ( ) . addAll ( notMoveableFilterExpr ) ; } else { newOp = opJoin ; } this . filterExpr = filterExprBeforeOpJoin ; this . stack . push ( newOp ) ; } private void checkMoveDownFilterExprAndVisitOpLeftJoin ( OpLeftJoin opLeftJoin ) { Op left = null ; Op right = null ; Op newOp ; List < Expr > filterExprBeforeOpLeftJoin , filterExprAfterOpLeftJoin , notMoveableFilterExpr , filterExprRightSide , validFilterExprRightSide ; filterExprBeforeOpLeftJoin = new ArrayList < Expr > ( this . filterExpr ) ; filterExprAfterOpLeftJoin = new ArrayList < Expr > ( ) ; if ( ( left = opLeftJoin . getLeft ( ) ) != null ) { this . filterExpr = calcValidFilterExpr ( filterExprBeforeOpLeftJoin , left ) ; filterExprAfterOpLeftJoin . addAll ( this . filterExpr ) ; opLeftJoin . getLeft ( ) . visit ( this ) ; left = stack . pop ( ) ; } if ( ( right = opLeftJoin . getRight ( ) ) != null ) { filterExprRightSide = calcValidFilterExpr ( filterExprBeforeOpLeftJoin , right ) ; validFilterExprRightSide = new ArrayList < Expr > ( ) ; for ( Expr expr : filterExprRightSide ) { if ( this . filterExpr . contains ( expr ) ) { validFilterExprRightSide . add ( expr ) ; } } this . filterExpr = validFilterExprRightSide ; filterExprAfterOpLeftJoin . addAll ( this . filterExpr ) ; opLeftJoin . getRight ( ) . visit ( this ) ; right = stack . pop ( ) ; } notMoveableFilterExpr = new ArrayList < Expr > ( filterExprBeforeOpLeftJoin ) ; notMoveableFilterExpr . removeAll ( filterExprAfterOpLeftJoin ) ; if ( ! notMoveableFilterExpr . isEmpty ( ) ) { newOp = OpFilter . filter ( OpLeftJoin . create ( left , right , opLeftJoin . getExprs ( ) ) ) ; ( ( OpFilter ) newOp ) . getExprs ( ) . getList ( ) . addAll ( notMoveableFilterExpr ) ; } else { newOp = opLeftJoin ; } this . filterExpr = filterExprBeforeOpLeftJoin ; this . stack . push ( newOp ) ; } private void checkMoveDownFilterExprAndVisitOpDiff ( Op2 opDiff ) { Op left = null ; Op right = null ; Op newOp ; List < Expr > filterExprBeforeOpUnionOpJoin , filterExprAfterOpUnionOpJoin , notMoveableFilterExpr ; filterExprBeforeOpUnionOpJoin = new ArrayList < Expr > ( this . filterExpr ) ; filterExprAfterOpUnionOpJoin = new ArrayList < Expr > ( ) ; if ( ( left = opDiff . getLeft ( ) ) != null ) { this . filterExpr = calcValidFilterExpr ( filterExprBeforeOpUnionOpJoin , left ) ; filterExprAfterOpUnionOpJoin . addAll ( this . filterExpr ) ; opDiff . getLeft ( ) . visit ( this ) ; left = stack . pop ( ) ; } if ( ( right = opDiff . getRight ( ) ) != null ) { this . filterExpr = calcValidFilterExpr ( filterExprBeforeOpUnionOpJoin , right ) ; filterExprAfterOpUnionOpJoin . addAll ( this . filterExpr ) ; opDiff . getRight ( ) . visit ( this ) ; right = stack . pop ( ) ; } notMoveableFilterExpr = new ArrayList < Expr > ( filterExprBeforeOpUnionOpJoin ) ; notMoveableFilterExpr . removeAll ( filterExprAfterOpUnionOpJoin ) ; if ( ! notMoveableFilterExpr . isEmpty ( ) ) { newOp = OpFilter . filter ( OpDiff . create ( left , right ) ) ; ( ( OpFilter ) newOp ) . getExprs ( ) . getList ( ) . addAll ( notMoveableFilterExpr ) ; } else { newOp = opDiff ; } this . filterExpr = filterExprBeforeOpUnionOpJoin ; this . stack . push ( newOp ) ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . sparql . core . Var ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap . Alias ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . VariableConstraints ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; import de . fuberlin . wiwiss . d2rq . algebra . OrderSpec ; import de . fuberlin . wiwiss . d2rq . algebra . ProjectionSpec ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . RelationImpl ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . expr . Conjunction ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; class TripleRelationJoiner { public static TripleRelationJoiner create ( boolean allOptimizations ) { return new TripleRelationJoiner ( new VariableConstraints ( ) , Collections . < Triple > emptyList ( ) , Collections . < NodeRelation > emptyList ( ) , allOptimizations ) ; } private final VariableConstraints nodeSets ; private final List < Triple > joinedTriplePatterns ; private final List < NodeRelation > joinedTripleRelations ; private final boolean useAllOptimizations ; private TripleRelationJoiner ( VariableConstraints nodeSets , List < Triple > patterns , List < NodeRelation > relations , boolean useAllOptimizations ) { this . nodeSets = nodeSets ; this . joinedTriplePatterns = patterns ; this . joinedTripleRelations = relations ; this . useAllOptimizations = useAllOptimizations ; } public List < TripleRelationJoiner > joinAll ( Triple pattern , List < NodeRelation > candidates ) { List < TripleRelationJoiner > results = new ArrayList < TripleRelationJoiner > ( ) ; for ( NodeRelation tripleRelation : candidates ) { TripleRelationJoiner nextJoiner = join ( pattern , tripleRelation ) ; if ( nextJoiner != null ) { results . add ( nextJoiner ) ; } } return results ; } private static boolean isUnique ( ConnectedDB database , RelationName originalName , Set < String > attributeNames ) { Map < String , List < String > > uniqueKeys = database . getUniqueKeyColumns ( originalName ) ; if ( uniqueKeys == null ) return false ; for ( List < String > indexColumns : uniqueKeys . values ( ) ) { if ( attributeNames . containsAll ( indexColumns ) ) return true ; } return false ; } private static class AttributeSet { RelationName relationName = null ; Set < String > attributeNames = new TreeSet < String > ( ) ; static AttributeSet createFrom ( NodeMaker nodeMaker ) { AttributeSet attributes = new AttributeSet ( ) ; Set < ProjectionSpec > projectionSpecs = nodeMaker . projectionSpecs ( ) ; boolean err = projectionSpecs . isEmpty ( ) ; Iterator < ProjectionSpec > projectionIterator = projectionSpecs . iterator ( ) ; while ( projectionIterator . hasNext ( ) && ! err ) { ProjectionSpec projection = ( ProjectionSpec ) projectionIterator . next ( ) ; Set < Attribute > reqAttr = projection . requiredAttributes ( ) ; Iterator < Attribute > j = reqAttr . iterator ( ) ; while ( j . hasNext ( ) && ! err ) { Attribute a = ( Attribute ) j . next ( ) ; if ( attributes . relationName == null ) attributes . relationName = a . relationName ( ) ; else if ( ! attributes . relationName . equals ( a . relationName ( ) ) ) err = true ; attributes . attributeNames . add ( a . attributeName ( ) ) ; } } if ( ! err ) return attributes ; return null ; } } private List < RelationName > getRelationNames ( NodeMaker nodeMaker ) { List < RelationName > result = new ArrayList < RelationName > ( ) ; Set < ProjectionSpec > projectionSpecs = nodeMaker . projectionSpecs ( ) ; for ( ProjectionSpec spec : projectionSpecs ) { for ( Attribute a : spec . requiredAttributes ( ) ) { result . add ( a . relationName ( ) ) ; } } return result ; } public TripleRelationJoiner join ( Triple pattern , NodeRelation relation ) { List < Triple > newPatterns = new ArrayList < Triple > ( joinedTriplePatterns ) ; newPatterns . add ( pattern ) ; List < NodeRelation > newRelations = new ArrayList < NodeRelation > ( joinedTripleRelations ) ; newRelations . add ( relation ) ; VariableConstraints nodeSets = new VariableConstraints ( ) ; for ( int i = ; i < newPatterns . size ( ) ; i ++ ) { Triple t = ( Triple ) newPatterns . get ( i ) ; NodeRelation r = newRelations . get ( i ) ; if ( useAllOptimizations ) { List < String > names = new ArrayList < String > ( ) ; if ( t . getSubject ( ) . isVariable ( ) ) names . add ( t . getSubject ( ) . getName ( ) ) ; if ( t . getPredicate ( ) . isVariable ( ) ) names . add ( t . getPredicate ( ) . getName ( ) ) ; if ( t . getObject ( ) . isVariable ( ) ) names . add ( t . getObject ( ) . getName ( ) ) ; for ( String name : names ) { NodeMaker n = ( NodeMaker ) nodeSets . toMap ( ) . get ( name ) ; if ( n != null ) { AttributeSet attributes = AttributeSet . createFrom ( n ) ; if ( attributes != null ) { RelationName originalName = ( ( AliasMap ) nodeSets . relationAliases ( ) . get ( name ) ) . originalOf ( attributes . relationName ) ; if ( r . baseRelation ( ) . aliases ( ) . hasAlias ( originalName ) ) { if ( isUnique ( r . baseRelation ( ) . database ( ) , originalName , attributes . attributeNames ) ) { if ( t . getSubject ( ) . isVariable ( ) && t . getSubject ( ) . getName ( ) . equals ( name ) ) { AttributeSet existing = AttributeSet . createFrom ( r . nodeMaker ( TripleRelation . SUBJECT ) ) ; if ( existing != null && existing . attributeNames . equals ( attributes . attributeNames ) ) { r = r . renameSingleRelation ( existing . relationName , attributes . relationName ) ; newRelations . set ( i , r ) ; } } if ( t . getPredicate ( ) . isVariable ( ) && t . getPredicate ( ) . getName ( ) . equals ( name ) ) { AttributeSet existing = AttributeSet . createFrom ( r . nodeMaker ( TripleRelation . PREDICATE ) ) ; if ( existing != null && existing . attributeNames . equals ( attributes . attributeNames ) ) { r = r . renameSingleRelation ( existing . relationName , attributes . relationName ) ; newRelations . set ( i , r ) ; } } if ( t . getObject ( ) . isVariable ( ) && t . getObject ( ) . getName ( ) . equals ( name ) ) { AttributeSet existing = AttributeSet . createFrom ( r . nodeMaker ( TripleRelation . OBJECT ) ) ; if ( existing != null && existing . attributeNames . equals ( attributes . attributeNames ) ) { r = r . renameSingleRelation ( existing . relationName , attributes . relationName ) ; newRelations . set ( i , r ) ; } } } } } } } } if ( t . getObject ( ) . isVariable ( ) ) { List < RelationName > relationNames = getRelationNames ( r . nodeMaker ( TripleRelation . OBJECT ) ) ; Set < Alias > aliases = new HashSet < Alias > ( ) ; for ( RelationName rname : relationNames ) { if ( r . baseRelation ( ) . aliases ( ) . isAlias ( rname ) ) aliases . add ( new AliasMap . Alias ( r . baseRelation ( ) . aliases ( ) . originalOf ( rname ) , rname ) ) ; } nodeSets . add ( Var . alloc ( t . getObject ( ) ) , r . nodeMaker ( TripleRelation . OBJECT ) , new AliasMap ( aliases ) ) ; } if ( t . getPredicate ( ) . isVariable ( ) ) { List < RelationName > relationNames = getRelationNames ( r . nodeMaker ( TripleRelation . PREDICATE ) ) ; Set < Alias > aliases = new HashSet < Alias > ( ) ; for ( RelationName rname : relationNames ) { if ( r . baseRelation ( ) . aliases ( ) . isAlias ( rname ) ) aliases . add ( new AliasMap . Alias ( r . baseRelation ( ) . aliases ( ) . originalOf ( rname ) , rname ) ) ; } nodeSets . add ( Var . alloc ( t . getPredicate ( ) ) , r . nodeMaker ( TripleRelation . PREDICATE ) , new AliasMap ( aliases ) ) ; } if ( t . getSubject ( ) . isVariable ( ) ) { List < RelationName > relationNames = getRelationNames ( r . nodeMaker ( TripleRelation . SUBJECT ) ) ; Set < Alias > aliases = new HashSet < Alias > ( ) ; for ( RelationName rname : relationNames ) { if ( r . baseRelation ( ) . aliases ( ) . isAlias ( rname ) ) aliases . add ( new AliasMap . Alias ( r . baseRelation ( ) . aliases ( ) . originalOf ( rname ) , rname ) ) ; } nodeSets . add ( Var . alloc ( t . getSubject ( ) ) , r . nodeMaker ( TripleRelation . SUBJECT ) , new AliasMap ( aliases ) ) ; } } if ( ! nodeSets . satisfiable ( ) ) { return null ; } return new TripleRelationJoiner ( nodeSets , newPatterns , newRelations , useAllOptimizations ) ; } public NodeRelation toNodeRelation ( ) { return new NodeRelation ( joinedBaseRelation ( ) . select ( nodeSets . constraint ( ) ) . project ( nodeSets . allProjections ( ) ) , nodeSets . toMap ( ) ) ; } private Relation joinedBaseRelation ( ) { List < Relation > relations = new ArrayList < Relation > ( ) ; for ( NodeRelation tripleRelation : joinedTripleRelations ) { relations . add ( tripleRelation . baseRelation ( ) ) ; } return joinRelations ( relations , Expression . TRUE ) ; } private Relation joinRelations ( Collection < Relation > relations , Expression additionalCondition ) { if ( relations . isEmpty ( ) ) { return Relation . TRUE ; } ConnectedDB connectedDB = ( ( Relation ) relations . iterator ( ) . next ( ) ) . database ( ) ; AliasMap joinedAliases = AliasMap . NO_ALIASES ; Collection < Expression > expressions = new HashSet < Expression > ( ) ; expressions . add ( additionalCondition ) ; Collection < Expression > softConditions = new HashSet < Expression > ( ) ; Set < Join > joins = new HashSet < Join > ( ) ; Set < ProjectionSpec > projections = new HashSet < ProjectionSpec > ( ) ; int limit = Relation . NO_LIMIT ; int limitInverse = Relation . NO_LIMIT ; List < OrderSpec > orderSpecs = null ; for ( Relation relation : relations ) { joinedAliases = joinedAliases . applyTo ( relation . aliases ( ) ) ; expressions . add ( relation . condition ( ) ) ; softConditions . add ( relation . softCondition ( ) ) ; joins . addAll ( relation . joinConditions ( ) ) ; projections . addAll ( relation . projections ( ) ) ; orderSpecs = orderSpecs == null ? relation . orderSpecs ( ) : orderSpecs ; limit = Relation . combineLimits ( limit , relation . limit ( ) ) ; limitInverse = Relation . combineLimits ( limitInverse , relation . limitInverse ( ) ) ; } boolean isUnique = relations . size ( ) == && ( relations . iterator ( ) . next ( ) ) . isUnique ( ) ; return new RelationImpl ( connectedDB , joinedAliases , Conjunction . create ( expressions ) , Conjunction . create ( softConditions ) , joins , projections , isUnique , orderSpecs , limit , limitInverse ) ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . HashSet ; import java . util . Set ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . sparql . algebra . Op ; import com . hp . hpl . jena . sparql . algebra . OpVisitorBase ; import com . hp . hpl . jena . sparql . algebra . OpWalker ; import com . hp . hpl . jena . sparql . algebra . op . OpAssign ; import com . hp . hpl . jena . sparql . algebra . op . OpBGP ; import com . hp . hpl . jena . sparql . algebra . op . OpDatasetNames ; import com . hp . hpl . jena . sparql . algebra . op . OpExtend ; import com . hp . hpl . jena . sparql . algebra . op . OpGraph ; import com . hp . hpl . jena . sparql . algebra . op . OpPath ; import com . hp . hpl . jena . sparql . algebra . op . OpQuad ; import com . hp . hpl . jena . sparql . algebra . op . OpQuadPattern ; import com . hp . hpl . jena . sparql . algebra . op . OpTable ; import com . hp . hpl . jena . sparql . algebra . op . OpTriple ; import com . hp . hpl . jena . sparql . core . Quad ; import com . hp . hpl . jena . sparql . core . Var ; public class VarCollector extends OpVisitorBase { public static Set < Var > mentionedVars ( Op op ) { VarCollector collector = new VarCollector ( ) ; OpWalker . walk ( op , collector ) ; return collector . mentionedVariables ( ) ; } private Set < Var > variables = new HashSet < Var > ( ) ; public Set < Var > mentionedVariables ( ) { return variables ; } @ Override public void visit ( OpBGP opBGP ) { for ( Triple triple : opBGP . getPattern ( ) ) { visit ( triple ) ; } } @ Override public void visit ( OpTriple opTriple ) { visit ( opTriple . getTriple ( ) ) ; } @ Override public void visit ( OpQuadPattern quadPattern ) { for ( Quad quad : quadPattern . getPattern ( ) ) { visit ( quad ) ; } } @ Override public void visit ( OpQuad opQuad ) { visit ( opQuad . getQuad ( ) ) ; } @ Override public void visit ( OpGraph opGraph ) { visit ( opGraph . getNode ( ) ) ; } @ Override public void visit ( OpDatasetNames dsNames ) { visit ( dsNames . getGraphNode ( ) ) ; } @ Override public void visit ( OpAssign opAssign ) { variables . addAll ( opAssign . getVarExprList ( ) . getVars ( ) ) ; } @ Override public void visit ( OpExtend opExtend ) { variables . addAll ( opExtend . getVarExprList ( ) . getVars ( ) ) ; } @ Override public void visit ( OpTable opTable ) { variables . addAll ( opTable . getTable ( ) . getVars ( ) ) ; } private void visit ( Triple triple ) { visit ( triple . getSubject ( ) ) ; visit ( triple . getPredicate ( ) ) ; visit ( triple . getObject ( ) ) ; } private void visit ( Quad quad ) { visit ( quad . asTriple ( ) ) ; visit ( quad . getGraph ( ) ) ; } private void visit ( Node node ) { if ( node == null ) return ; if ( node . isVariable ( ) ) { variables . add ( ( Var ) node ) ; } } public void visit ( OpPath opPath ) { visit ( opPath . getTriplePath ( ) . asTriple ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import com . hp . hpl . jena . graph . Triple ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; public class GraphPatternTranslator { private final List < Triple > triplePatterns ; private final Collection < TripleRelation > tripleRelations ; boolean useAllOptimizations ; public GraphPatternTranslator ( List < Triple > triplePatterns , Collection < TripleRelation > tripleRelations , boolean useAllOptimizations ) { this . triplePatterns = triplePatterns ; this . tripleRelations = tripleRelations ; this . useAllOptimizations = useAllOptimizations ; } public List < NodeRelation > translate ( ) { if ( triplePatterns . isEmpty ( ) ) { return Collections . singletonList ( NodeRelation . TRUE ) ; } Iterator < Triple > it = triplePatterns . iterator ( ) ; List < CandidateList > candidateLists = new ArrayList < CandidateList > ( triplePatterns . size ( ) ) ; int index = ; while ( it . hasNext ( ) ) { Triple triplePattern = ( Triple ) it . next ( ) ; CandidateList candidates = new CandidateList ( triplePattern , triplePatterns . size ( ) > , index ) ; if ( candidates . isEmpty ( ) ) { return Collections . < NodeRelation > emptyList ( ) ; } candidateLists . add ( candidates ) ; index ++ ; } Collections . sort ( candidateLists ) ; List < TripleRelationJoiner > joiners = new ArrayList < TripleRelationJoiner > ( ) ; joiners . add ( TripleRelationJoiner . create ( this . useAllOptimizations ) ) ; for ( CandidateList candidates : candidateLists ) { List < TripleRelationJoiner > nextJoiners = new ArrayList < TripleRelationJoiner > ( ) ; for ( TripleRelationJoiner joiner : joiners ) { nextJoiners . addAll ( joiner . joinAll ( candidates . triplePattern ( ) , candidates . all ( ) ) ) ; } joiners = nextJoiners ; } List < NodeRelation > results = new ArrayList < NodeRelation > ( joiners . size ( ) ) ; for ( TripleRelationJoiner joiner : joiners ) { NodeRelation nodeRelation = joiner . toNodeRelation ( ) ; if ( ! nodeRelation . baseRelation ( ) . equals ( Relation . EMPTY ) || ! useAllOptimizations ) results . add ( nodeRelation ) ; } return results ; } private class CandidateList implements Comparable < CandidateList > { private final Triple triplePattern ; private final List < NodeRelation > candidates ; CandidateList ( Triple triplePattern , boolean useIndex , int index ) { this . triplePattern = triplePattern ; List < NodeRelation > matches = findMatchingTripleRelations ( triplePattern ) ; if ( useIndex ) { candidates = prefixTripleRelations ( matches , index ) ; } else { candidates = matches ; } } boolean isEmpty ( ) { return candidates . isEmpty ( ) ; } Triple triplePattern ( ) { return triplePattern ; } List < NodeRelation > all ( ) { return candidates ; } public int compareTo ( CandidateList other ) { CandidateList otherList = ( CandidateList ) other ; if ( candidates . size ( ) < otherList . candidates . size ( ) ) { return - ; } if ( candidates . size ( ) > otherList . candidates . size ( ) ) { return ; } return ; } private List < NodeRelation > findMatchingTripleRelations ( Triple triplePattern ) { List < NodeRelation > results = new ArrayList < NodeRelation > ( ) ; for ( TripleRelation tripleRelation : tripleRelations ) { TripleRelation selected = tripleRelation . selectTriple ( triplePattern ) ; if ( selected == null ) continue ; results . add ( selected ) ; } return results ; } private List < NodeRelation > prefixTripleRelations ( List < NodeRelation > tripleRelations , int index ) { List < NodeRelation > results = new ArrayList < NodeRelation > ( tripleRelations . size ( ) ) ; for ( NodeRelation tripleRelation : tripleRelations ) { results . add ( tripleRelation . withPrefix ( index ) ) ; } return results ; } public String toString ( ) { return "" + triplePattern + "" + candidates + "" ; } } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . openjena . atlas . io . IndentedWriter ; import com . hp . hpl . jena . sparql . algebra . Op ; import com . hp . hpl . jena . sparql . algebra . op . OpExt ; import com . hp . hpl . jena . sparql . algebra . op . OpNull ; import com . hp . hpl . jena . sparql . algebra . op . OpTable ; import com . hp . hpl . jena . sparql . engine . ExecutionContext ; import com . hp . hpl . jena . sparql . engine . QueryIterator ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIterConcat ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIterRepeatApply ; import com . hp . hpl . jena . sparql . serializer . SerializationContext ; import com . hp . hpl . jena . sparql . sse . writers . WriterOp ; import com . hp . hpl . jena . sparql . util . NodeIsomorphismMap ; import de . fuberlin . wiwiss . d2rq . algebra . CompatibleRelationGroup ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; public class OpUnionTableSQL extends OpExt { public static Op create ( Collection < NodeRelation > tables ) { Collection < OpTableSQL > nonEmpty = new ArrayList < OpTableSQL > ( ) ; for ( NodeRelation table : tables ) { if ( table . baseRelation ( ) . condition ( ) . isFalse ( ) ) continue ; nonEmpty . add ( new OpTableSQL ( table ) ) ; } if ( nonEmpty . isEmpty ( ) ) { return OpNull . create ( ) ; } return new OpUnionTableSQL ( nonEmpty ) ; } private final List < OpTableSQL > tableOps ; private final Op effectiveOp ; public OpUnionTableSQL ( Collection < OpTableSQL > tableOps ) { this ( tableOps , OpTable . unit ( ) ) ; } public OpUnionTableSQL ( Collection < OpTableSQL > tableOps , Op effectiveOp ) { super ( "" ) ; this . tableOps = new ArrayList < OpTableSQL > ( tableOps ) ; this . effectiveOp = effectiveOp ; } @ Override public QueryIterator eval ( QueryIterator input , final ExecutionContext execCxt ) { return new QueryIterRepeatApply ( input , execCxt ) { @ Override protected QueryIterator nextStage ( Binding binding ) { QueryIterConcat resultIt = new QueryIterConcat ( execCxt ) ; Collection < NodeRelation > tables = new ArrayList < NodeRelation > ( ) ; for ( OpTableSQL tableOp : tableOps ) { tables . add ( tableOp . table ( ) . extendWith ( binding ) ) ; } for ( CompatibleRelationGroup group : CompatibleRelationGroup . groupNodeRelations ( tables ) ) { resultIt . add ( QueryIterTableSQL . create ( group . baseRelation ( ) , group . bindingMakers ( ) , execCxt ) ) ; } return resultIt ; } } ; } @ Override public Op effectiveOp ( ) { return effectiveOp ; } @ Override public void outputArgs ( IndentedWriter out , SerializationContext sCxt ) { out . println ( ) ; for ( OpTableSQL table : tableOps ) { WriterOp . output ( out , table , sCxt ) ; } } @ Override public int hashCode ( ) { return ^ tableOps . hashCode ( ) ; } @ Override public boolean equalTo ( Op other , NodeIsomorphismMap labelMap ) { if ( ! ( other instanceof OpUnionTableSQL ) ) return false ; return ( ( OpUnionTableSQL ) other ) . tableOps . equals ( tableOps ) ; } } package de . fuberlin . wiwiss . d2rq . engine ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . LinkedList ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . hp . hpl . jena . sparql . engine . ExecutionContext ; import com . hp . hpl . jena . sparql . engine . QueryIterator ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIter ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIterNullIterator ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIterPlainWrapper ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIterSingleton ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . sql . ResultRow ; import de . fuberlin . wiwiss . d2rq . sql . SQLIterator ; import de . fuberlin . wiwiss . d2rq . sql . SelectStatementBuilder ; public class QueryIterTableSQL extends QueryIter { private final static Log log = LogFactory . getLog ( QueryIterTableSQL . class ) ; public static QueryIterator create ( Relation relation , Collection < BindingMaker > bindingMakers , ExecutionContext execCxt ) { if ( relation . equals ( Relation . EMPTY ) || relation . condition ( ) . isFalse ( ) || bindingMakers . isEmpty ( ) ) { return new QueryIterNullIterator ( execCxt ) ; } if ( relation . isTrivial ( ) ) { ArrayList < Binding > bindingList = new ArrayList < Binding > ( ) ; for ( BindingMaker bindingMaker : bindingMakers ) { Binding t = bindingMaker . makeBinding ( ResultRow . NO_ATTRIBUTES ) ; if ( t == null ) continue ; bindingList . add ( t ) ; } return new QueryIterPlainWrapper ( bindingList . iterator ( ) , execCxt ) ; } return new QueryIterTableSQL ( relation , bindingMakers , execCxt ) ; } public static QueryIterator create ( NodeRelation table , ExecutionContext execCxt ) { if ( table . baseRelation ( ) . condition ( ) . isFalse ( ) ) { return new QueryIterNullIterator ( execCxt ) ; } if ( table . baseRelation ( ) . isTrivial ( ) ) { return QueryIterSingleton . create ( BindingMaker . createFor ( table ) . makeBinding ( ResultRow . NO_ATTRIBUTES ) , execCxt ) ; } return new QueryIterTableSQL ( table . baseRelation ( ) , Collections . singleton ( BindingMaker . createFor ( table ) ) , execCxt ) ; } private final SQLIterator wrapped ; private final Collection < BindingMaker > bindingMakers ; private final LinkedList < Binding > queue = new LinkedList < Binding > ( ) ; private QueryIterTableSQL ( Relation relation , Collection < BindingMaker > bindingMakers , ExecutionContext execCxt ) { super ( execCxt ) ; this . bindingMakers = bindingMakers ; SelectStatementBuilder builder = new SelectStatementBuilder ( relation ) ; wrapped = new SQLIterator ( builder . getSQLStatement ( ) , builder . getColumnSpecs ( ) , relation . database ( ) ) ; } @ Override protected boolean hasNextBinding ( ) { while ( queue . isEmpty ( ) && wrapped . hasNext ( ) ) { enqueueBindings ( wrapped . next ( ) ) ; } return ! queue . isEmpty ( ) ; } @ Override protected Binding moveToNextBinding ( ) { return queue . removeFirst ( ) ; } @ Override protected void closeIterator ( ) { log . debug ( "" ) ; wrapped . close ( ) ; } @ Override protected void requestCancel ( ) { log . info ( "" ) ; wrapped . cancel ( ) ; } private void enqueueBindings ( ResultRow row ) { for ( BindingMaker bindingMaker : bindingMakers ) { Binding binding = bindingMaker . makeBinding ( row ) ; if ( binding == null ) continue ; queue . add ( binding ) ; } } } package de . fuberlin . wiwiss . d2rq . engine ; import com . hp . hpl . jena . sparql . algebra . Op ; import com . hp . hpl . jena . sparql . algebra . TransformCopy ; import com . hp . hpl . jena . sparql . algebra . op . OpFilter ; import com . hp . hpl . jena . sparql . expr . E_LogicalAnd ; import com . hp . hpl . jena . sparql . expr . E_LogicalNot ; import com . hp . hpl . jena . sparql . expr . E_LogicalOr ; import com . hp . hpl . jena . sparql . expr . Expr ; import com . hp . hpl . jena . sparql . expr . ExprAggregator ; import com . hp . hpl . jena . sparql . expr . ExprFunction0 ; import com . hp . hpl . jena . sparql . expr . ExprFunction1 ; import com . hp . hpl . jena . sparql . expr . ExprFunction2 ; import com . hp . hpl . jena . sparql . expr . ExprFunction3 ; import com . hp . hpl . jena . sparql . expr . ExprFunctionN ; import com . hp . hpl . jena . sparql . expr . ExprFunctionOp ; import com . hp . hpl . jena . sparql . expr . ExprList ; import com . hp . hpl . jena . sparql . expr . ExprNode ; import com . hp . hpl . jena . sparql . expr . ExprVar ; import com . hp . hpl . jena . sparql . expr . ExprVisitor ; import com . hp . hpl . jena . sparql . expr . NodeValue ; public class TransformFilterCNF extends TransformCopy { public Op transform ( OpFilter opFilter , Op subOp ) { ExprList exprList = ExprList . splitConjunction ( opFilter . getExprs ( ) ) ; ExprList cnfExprList = ExprList . splitConjunction ( TransformFilterCNF . translateFilterExpressionsToCNF ( opFilter ) ) ; if ( cnfExprList . size ( ) > exprList . size ( ) ) { return OpFilter . filter ( cnfExprList , subOp ) ; } return OpFilter . filter ( exprList , subOp ) ; } public static ExprList translateFilterExpressionsToCNF ( final OpFilter opFilter ) { ExprList exprList , newExprList ; OpFilter copiedOpFilter ; newExprList = new ExprList ( ) ; exprList = opFilter . getExprs ( ) ; copiedOpFilter = ( OpFilter ) OpFilter . filter ( exprList , opFilter . getSubOp ( ) ) ; exprList = copiedOpFilter . getExprs ( ) ; for ( Expr expr : exprList ) { if ( expr instanceof ExprNode ) { expr = applyDeMorganLaw ( expr ) ; expr = applyDistributiveLaw ( expr ) ; } newExprList . add ( expr ) ; } newExprList = ExprList . splitConjunction ( newExprList ) ; return newExprList ; } private static Expr applyDeMorganLaw ( Expr expr ) { DeMorganLawApplyer deMorganLawApplyer = new DeMorganLawApplyer ( ) ; expr . visit ( deMorganLawApplyer ) ; expr = deMorganLawApplyer . result ( ) ; return expr ; } private static Expr applyDistributiveLaw ( Expr expr ) { DistributiveLawApplyer distributiveLawApplyer = new DistributiveLawApplyer ( ) ; expr . visit ( distributiveLawApplyer ) ; expr = distributiveLawApplyer . result ( ) ; return expr ; } public static class DeMorganLawApplyer implements ExprVisitor { private Expr resultExpr ; public DeMorganLawApplyer ( ) { } public void finishVisit ( ) { } public void startVisit ( ) { } public void visit ( NodeValue nv ) { this . resultExpr = nv ; } public void visit ( ExprVar nv ) { this . resultExpr = nv ; } public void visit ( ExprFunction0 func ) { this . resultExpr = func ; } public void visit ( ExprFunction1 curExpr ) { Expr subExpr , leftExpr , rightExpr ; Expr newAndExpr ; subExpr = ( curExpr ) . getArg ( ) ; if ( curExpr instanceof E_LogicalNot ) { if ( subExpr instanceof E_LogicalNot ) { this . resultExpr = ( ( ExprFunction1 ) subExpr ) . getArg ( ) ; } else if ( subExpr instanceof E_LogicalOr ) { leftExpr = ( ( ExprFunction2 ) subExpr ) . getArg1 ( ) ; leftExpr . visit ( this ) ; leftExpr = this . resultExpr ; rightExpr = ( ( ExprFunction2 ) subExpr ) . getArg2 ( ) ; rightExpr . visit ( this ) ; rightExpr = this . resultExpr ; if ( ! ( leftExpr instanceof E_LogicalNot ) ) { leftExpr = new E_LogicalNot ( leftExpr ) ; } else { leftExpr = ( ( E_LogicalNot ) leftExpr ) . getArg ( ) ; } if ( ! ( rightExpr instanceof E_LogicalNot ) ) { rightExpr = new E_LogicalNot ( rightExpr ) ; } else { rightExpr = ( ( E_LogicalNot ) rightExpr ) . getArg ( ) ; } newAndExpr = new E_LogicalAnd ( leftExpr , rightExpr ) ; this . resultExpr = newAndExpr ; } else { this . resultExpr = curExpr ; } } else { subExpr . visit ( this ) ; this . resultExpr = curExpr ; } } public void visit ( ExprFunction2 curExpr ) { Expr leftExpr , rightExpr ; if ( curExpr instanceof E_LogicalOr || curExpr instanceof E_LogicalAnd ) { leftExpr = ( ( ExprFunction2 ) curExpr ) . getArg1 ( ) ; leftExpr . visit ( this ) ; leftExpr = this . resultExpr ; rightExpr = ( ( ExprFunction2 ) curExpr ) . getArg2 ( ) ; rightExpr . visit ( this ) ; rightExpr = this . resultExpr ; if ( curExpr instanceof E_LogicalOr ) { this . resultExpr = new E_LogicalOr ( leftExpr , rightExpr ) ; } else if ( curExpr instanceof E_LogicalAnd ) { this . resultExpr = new E_LogicalAnd ( leftExpr , rightExpr ) ; } } else { this . resultExpr = curExpr ; } } public void visit ( ExprFunction3 func ) { this . resultExpr = func ; } public void visit ( ExprFunctionN func ) { this . resultExpr = func ; } public void visit ( ExprFunctionOp funcOp ) { this . resultExpr = funcOp ; } public void visit ( ExprAggregator eAgg ) { this . resultExpr = eAgg ; } public Expr result ( ) { return resultExpr ; } } public static class DistributiveLawApplyer implements ExprVisitor { private Expr resultExpr ; public DistributiveLawApplyer ( ) { } public void finishVisit ( ) { } public void startVisit ( ) { } public void visit ( NodeValue nv ) { this . resultExpr = nv ; } public void visit ( ExprVar nv ) { this . resultExpr = nv ; } public void visit ( ExprFunction0 func ) { this . resultExpr = func ; } public void visit ( ExprFunction1 curExpr ) { Expr subExpr ; if ( curExpr instanceof E_LogicalNot ) { subExpr = curExpr ; this . resultExpr = curExpr ; ( ( ExprFunction1 ) subExpr ) . getArg ( ) . visit ( this ) ; this . resultExpr = new E_LogicalNot ( this . resultExpr ) ; } else { this . resultExpr = curExpr ; } } public void visit ( ExprFunction2 curExpr ) { Expr leftExpr , rightExpr ; Expr leftLeftExpr , rightLeftExpr , leftRightExpr , rightRightExpr ; Expr newAndExpr , newOrExpr1 , newOrExpr2 ; if ( curExpr instanceof E_LogicalOr || curExpr instanceof E_LogicalAnd ) { leftExpr = curExpr . getArg1 ( ) ; leftExpr . visit ( this ) ; leftExpr = this . resultExpr ; rightExpr = curExpr . getArg2 ( ) ; rightExpr . visit ( this ) ; rightExpr = this . resultExpr ; if ( curExpr instanceof E_LogicalOr ) { if ( ! ( leftExpr instanceof E_LogicalAnd ) && ! ( rightExpr instanceof E_LogicalAnd ) ) { this . resultExpr = new E_LogicalOr ( leftExpr , rightExpr ) ; } else { if ( leftExpr instanceof E_LogicalAnd ) { leftLeftExpr = ( ( E_LogicalAnd ) leftExpr ) . getArg1 ( ) ; rightLeftExpr = ( ( E_LogicalAnd ) leftExpr ) . getArg2 ( ) ; newOrExpr1 = new E_LogicalOr ( leftLeftExpr , rightExpr ) ; newOrExpr2 = new E_LogicalOr ( rightLeftExpr , rightExpr ) ; newAndExpr = new E_LogicalAnd ( newOrExpr1 , newOrExpr2 ) ; this . resultExpr = newAndExpr ; newAndExpr . visit ( this ) ; } if ( rightExpr instanceof E_LogicalAnd ) { leftRightExpr = ( ( E_LogicalAnd ) rightExpr ) . getArg1 ( ) ; rightRightExpr = ( ( E_LogicalAnd ) rightExpr ) . getArg2 ( ) ; newOrExpr1 = new E_LogicalOr ( leftExpr , leftRightExpr ) ; newOrExpr2 = new E_LogicalOr ( leftExpr , rightRightExpr ) ; newAndExpr = new E_LogicalAnd ( newOrExpr1 , newOrExpr2 ) ; this . resultExpr = newAndExpr ; newAndExpr . visit ( this ) ; } } } else { this . resultExpr = new E_LogicalAnd ( leftExpr , rightExpr ) ; } } else { this . resultExpr = curExpr ; } } public void visit ( ExprFunction3 func ) { this . resultExpr = func ; } public void visit ( ExprFunctionN func ) { this . resultExpr = func ; } public void visit ( ExprFunctionOp funcOp ) { this . resultExpr = funcOp ; } public void visit ( ExprAggregator eAgg ) { this . resultExpr = eAgg ; } public Expr result ( ) { return resultExpr ; } } } package de . fuberlin . wiwiss . d2rq . engine ; import org . openjena . atlas . io . IndentedWriter ; import com . hp . hpl . jena . sparql . algebra . Op ; import com . hp . hpl . jena . sparql . algebra . op . OpExt ; import com . hp . hpl . jena . sparql . algebra . op . OpNull ; import com . hp . hpl . jena . sparql . algebra . op . OpTable ; import com . hp . hpl . jena . sparql . engine . ExecutionContext ; import com . hp . hpl . jena . sparql . engine . QueryIterator ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIterRepeatApply ; import com . hp . hpl . jena . sparql . serializer . SerializationContext ; import com . hp . hpl . jena . sparql . util . NodeIsomorphismMap ; import de . fuberlin . wiwiss . d2rq . algebra . NodeRelation ; public class OpTableSQL extends OpExt { public static Op create ( NodeRelation table ) { if ( table . baseRelation ( ) . condition ( ) . isFalse ( ) ) { return OpNull . create ( ) ; } return new OpTableSQL ( table ) ; } private final NodeRelation table ; public OpTableSQL ( NodeRelation table ) { super ( "" ) ; this . table = table ; } public NodeRelation table ( ) { return table ; } @ Override public QueryIterator eval ( QueryIterator input , final ExecutionContext execCxt ) { return new QueryIterRepeatApply ( input , execCxt ) { @ Override protected QueryIterator nextStage ( Binding binding ) { return QueryIterTableSQL . create ( table . extendWith ( binding ) , execCxt ) ; } } ; } @ Override public Op effectiveOp ( ) { return OpTable . unit ( ) ; } @ Override public void outputArgs ( IndentedWriter out , SerializationContext sCxt ) { out . println ( table ) ; } @ Override public int hashCode ( ) { return ^ table . hashCode ( ) ; } @ Override public boolean equalTo ( Op other , NodeIsomorphismMap labelMap ) { if ( ! ( other instanceof OpTableSQL ) ) return false ; return ( ( OpTableSQL ) other ) . table . equals ( table ) ; } } package de . fuberlin . wiwiss . d2rq . engine ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . openjena . atlas . io . PrintUtils ; import com . hp . hpl . jena . query . Query ; import com . hp . hpl . jena . sparql . algebra . Op ; import com . hp . hpl . jena . sparql . algebra . Transformer ; import com . hp . hpl . jena . sparql . algebra . optimize . TransformScopeRename ; import com . hp . hpl . jena . sparql . core . DatasetGraph ; import com . hp . hpl . jena . sparql . core . DatasetGraphFactory ; import com . hp . hpl . jena . sparql . engine . Plan ; import com . hp . hpl . jena . sparql . engine . QueryEngineFactory ; import com . hp . hpl . jena . sparql . engine . QueryEngineRegistry ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import com . hp . hpl . jena . sparql . engine . binding . BindingRoot ; import com . hp . hpl . jena . sparql . engine . main . QueryEngineMain ; import com . hp . hpl . jena . sparql . util . Context ; import de . fuberlin . wiwiss . d2rq . jena . GraphD2RQ ; import de . fuberlin . wiwiss . d2rq . map . Mapping ; public class QueryEngineD2RQ extends QueryEngineMain { private static final Log log = LogFactory . getLog ( QueryEngineD2RQ . class ) ; private final Mapping mapping ; public QueryEngineD2RQ ( GraphD2RQ graph , Query query ) { this ( graph , query , null ) ; } public QueryEngineD2RQ ( GraphD2RQ graph , Query query , Context context ) { super ( query , DatasetGraphFactory . createOneGraph ( graph ) , BindingRoot . create ( ) , context ) ; this . mapping = graph . getMapping ( ) ; } public QueryEngineD2RQ ( GraphD2RQ graph , Op op , Context context ) { super ( op , DatasetGraphFactory . createOneGraph ( graph ) , BindingRoot . create ( ) , context ) ; this . mapping = graph . getMapping ( ) ; } @ Override protected Op modifyOp ( Op op ) { op = TransformScopeRename . transform ( op ) ; return translate ( op ) ; } private Op translate ( Op op ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + PrintUtils . toString ( op ) ) ; } op = Transformer . transform ( new TransformFilterCNF ( ) , op ) ; op = PushDownOpFilterVisitor . transform ( op ) ; op = Transformer . transform ( new TransformOpBGP ( mapping , true ) , op ) ; op = Transformer . transform ( new TransformOpBGP ( mapping , false ) , op ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" + PrintUtils . toString ( op ) ) ; } return op ; } private static QueryEngineFactory factory = new QueryEngineFactoryD2RQ ( ) ; public static QueryEngineFactory getFactory ( ) { return factory ; } public static void register ( ) { QueryEngineRegistry . addFactory ( factory ) ; } public static void unregister ( ) { QueryEngineRegistry . removeFactory ( factory ) ; } private static class QueryEngineFactoryD2RQ implements QueryEngineFactory { public boolean accept ( Query query , DatasetGraph dataset , Context context ) { return dataset . getDefaultGraph ( ) instanceof GraphD2RQ ; } public Plan create ( Query query , DatasetGraph dataset , Binding inputBinding , Context context ) { return new QueryEngineD2RQ ( ( GraphD2RQ ) dataset . getDefaultGraph ( ) , query , context ) . getPlan ( ) ; } public boolean accept ( Op op , DatasetGraph dataset , Context context ) { return dataset . getDefaultGraph ( ) instanceof GraphD2RQ ; } public Plan create ( Op op , DatasetGraph dataset , Binding inputBinding , Context context ) { return new QueryEngineD2RQ ( ( GraphD2RQ ) dataset . getDefaultGraph ( ) , op , context ) . getPlan ( ) ; } } } package de . fuberlin . wiwiss . d2rq . find ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . sparql . engine . ExecutionContext ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIter ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIterConcat ; import de . fuberlin . wiwiss . d2rq . algebra . CompatibleRelationGroup ; import de . fuberlin . wiwiss . d2rq . algebra . JoinOptimizer ; import de . fuberlin . wiwiss . d2rq . algebra . Relation ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . engine . QueryIterTableSQL ; import de . fuberlin . wiwiss . d2rq . find . URIMakerRule . URIMakerRuleChecker ; public class FindQuery { private final Triple triplePattern ; private final Collection < TripleRelation > tripleRelations ; private final int limitPerRelation ; private final ExecutionContext context ; public FindQuery ( Triple triplePattern , Collection < TripleRelation > tripleRelations , ExecutionContext context ) { this ( triplePattern , tripleRelations , Relation . NO_LIMIT , context ) ; } public FindQuery ( Triple triplePattern , Collection < TripleRelation > tripleRelations , int limit , ExecutionContext context ) { this . triplePattern = triplePattern ; this . tripleRelations = tripleRelations ; this . limitPerRelation = limit ; this . context = context ; } private List < TripleRelation > selectedTripleRelations ( ) { URIMakerRule rule = new URIMakerRule ( ) ; List < TripleRelation > sortedTripleRelations = rule . sortRDFRelations ( tripleRelations ) ; URIMakerRuleChecker subjectChecker = rule . createRuleChecker ( triplePattern . getSubject ( ) ) ; URIMakerRuleChecker predicateChecker = rule . createRuleChecker ( triplePattern . getPredicate ( ) ) ; URIMakerRuleChecker objectChecker = rule . createRuleChecker ( triplePattern . getObject ( ) ) ; List < TripleRelation > result = new ArrayList < TripleRelation > ( ) ; for ( TripleRelation tripleRelation : sortedTripleRelations ) { TripleRelation selectedTripleRelation = tripleRelation . selectTriple ( triplePattern ) ; if ( selectedTripleRelation != null && subjectChecker . canMatch ( tripleRelation . nodeMaker ( TripleRelation . SUBJECT ) ) && predicateChecker . canMatch ( tripleRelation . nodeMaker ( TripleRelation . PREDICATE ) ) && objectChecker . canMatch ( tripleRelation . nodeMaker ( TripleRelation . OBJECT ) ) ) { subjectChecker . addPotentialMatch ( tripleRelation . nodeMaker ( TripleRelation . SUBJECT ) ) ; predicateChecker . addPotentialMatch ( tripleRelation . nodeMaker ( TripleRelation . PREDICATE ) ) ; objectChecker . addPotentialMatch ( tripleRelation . nodeMaker ( TripleRelation . OBJECT ) ) ; TripleRelation r = new JoinOptimizer ( selectedTripleRelation ) . optimize ( ) ; if ( limitPerRelation != Relation . NO_LIMIT ) { r = r . limit ( limitPerRelation ) ; } result . add ( r ) ; } } return result ; } public QueryIter iterator ( ) { QueryIterConcat qIter = new QueryIterConcat ( context ) ; for ( CompatibleRelationGroup group : CompatibleRelationGroup . groupNodeRelations ( selectedTripleRelations ( ) ) ) { if ( ! group . baseRelation ( ) . equals ( Relation . EMPTY ) && group . baseRelation ( ) . limit ( ) != ) { qIter . add ( QueryIterTableSQL . create ( group . baseRelation ( ) , group . bindingMakers ( ) , context ) ) ; } } return qIter ; } } package de . fuberlin . wiwiss . d2rq . find ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . sparql . core . Var ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . RelationalOperators ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; import de . fuberlin . wiwiss . d2rq . expr . Expression ; import de . fuberlin . wiwiss . d2rq . nodes . NodeMaker ; import de . fuberlin . wiwiss . d2rq . nodes . NodeSetFilter ; import de . fuberlin . wiwiss . d2rq . values . BlankNodeID ; import de . fuberlin . wiwiss . d2rq . values . Pattern ; import de . fuberlin . wiwiss . d2rq . values . Translator ; public class URIMakerRule implements Comparator < TripleRelation > { private Map < NodeMaker , URIMakerIdentifier > identifierCache = new HashMap < NodeMaker , URIMakerIdentifier > ( ) ; public List < TripleRelation > sortRDFRelations ( Collection < TripleRelation > tripleRelations ) { ArrayList < TripleRelation > results = new ArrayList < TripleRelation > ( tripleRelations ) ; Collections . sort ( results , this ) ; return results ; } public URIMakerRuleChecker createRuleChecker ( Node node ) { return new URIMakerRuleChecker ( node ) ; } public int compare ( TripleRelation o1 , TripleRelation o2 ) { int priority1 = priority ( o1 ) ; int priority2 = priority ( o2 ) ; if ( priority1 > priority2 ) { return - ; } if ( priority1 < priority2 ) { return ; } return ; } private int priority ( TripleRelation relation ) { int result = ; for ( Var var : relation . variables ( ) ) { URIMakerIdentifier id = uriMakerIdentifier ( relation . nodeMaker ( var ) ) ; if ( id . isURIPattern ( ) ) { result += ; } if ( id . isURIColumn ( ) ) { result -= ; } } return result ; } private URIMakerIdentifier uriMakerIdentifier ( NodeMaker nodeMaker ) { URIMakerIdentifier cachedIdentifier = ( URIMakerIdentifier ) this . identifierCache . get ( nodeMaker ) ; if ( cachedIdentifier == null ) { cachedIdentifier = new URIMakerIdentifier ( nodeMaker ) ; this . identifierCache . put ( nodeMaker , cachedIdentifier ) ; } return cachedIdentifier ; } private class URIMakerIdentifier implements NodeSetFilter { private boolean isURIMaker = false ; private boolean isColumn = false ; private boolean isPattern = false ; URIMakerIdentifier ( NodeMaker nodeMaker ) { nodeMaker . describeSelf ( this ) ; } boolean isURIColumn ( ) { return this . isURIMaker && this . isColumn ; } boolean isURIPattern ( ) { return this . isURIMaker && this . isPattern ; } public void limitTo ( Node node ) { } public void limitToBlankNodes ( ) { } public void limitToEmptySet ( ) { } public void limitToLiterals ( String language , RDFDatatype datatype ) { } public void limitToURIs ( ) { this . isURIMaker = true ; } public void limitValues ( String constant ) { } public void limitValuesToAttribute ( Attribute attribute ) { this . isColumn = true ; } public void limitValuesToBlankNodeID ( BlankNodeID id ) { } public void limitValuesToPattern ( Pattern pattern ) { this . isPattern = true ; } public void limitValuesToExpression ( Expression expression ) { } public void setUsesTranslator ( Translator translator ) { } } public class URIMakerRuleChecker { private Node node ; private boolean canMatchURIColumn = true ; public URIMakerRuleChecker ( Node node ) { this . node = node ; } public void addPotentialMatch ( NodeMaker nodeMaker ) { if ( node . isURI ( ) && uriMakerIdentifier ( nodeMaker ) . isURIPattern ( ) && ! nodeMaker . selectNode ( node , RelationalOperators . DUMMY ) . equals ( NodeMaker . EMPTY ) ) { this . canMatchURIColumn = false ; } } public boolean canMatch ( NodeMaker nodeMaker ) { return this . canMatchURIColumn || ! uriMakerIdentifier ( nodeMaker ) . isURIColumn ( ) ; } } } package de . fuberlin . wiwiss . d2rq . find ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . sparql . engine . binding . Binding ; import com . hp . hpl . jena . sparql . engine . iterator . QueryIter ; import com . hp . hpl . jena . util . iterator . ExtendedIterator ; import com . hp . hpl . jena . util . iterator . NiceIterator ; import de . fuberlin . wiwiss . d2rq . algebra . TripleRelation ; public class TripleQueryIter extends NiceIterator < Triple > { public static ExtendedIterator < Triple > create ( QueryIter wrapped ) { return new TripleQueryIter ( wrapped ) ; } private final QueryIter wrapped ; private TripleQueryIter ( QueryIter wrapped ) { this . wrapped = wrapped ; } public boolean hasNext ( ) { return wrapped . hasNext ( ) ; } public Triple next ( ) { Binding b = wrapped . next ( ) ; return new Triple ( b . get ( TripleRelation . SUBJECT ) , b . get ( TripleRelation . PREDICATE ) , b . get ( TripleRelation . OBJECT ) ) ; } public void close ( ) { wrapped . close ( ) ; } public void cancel ( ) { wrapped . cancel ( ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; import java . util . ArrayList ; import java . util . List ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . mapgen . Filter . IdentifierMatcher ; public class FilterParser { private final String s ; private final List < List < IdentifierMatcher > > result = new ArrayList < List < IdentifierMatcher > > ( ) ; private int index = ; public FilterParser ( String filterSpec ) { s = filterSpec ; } public Filter parseSchemaFilter ( ) throws ParseException { List < Filter > result = new ArrayList < Filter > ( ) ; for ( List < IdentifierMatcher > list : parse ( ) ) { if ( list . size ( ) != ) { throw new ParseException ( "" + s + "" ) ; } result . add ( new FilterMatchSchema ( list . get ( ) ) ) ; } return FilterMatchAny . create ( result ) ; } public Filter parseTableFilter ( boolean matchParents ) throws ParseException { List < Filter > result = new ArrayList < Filter > ( ) ; for ( List < IdentifierMatcher > list : parse ( ) ) { if ( list . size ( ) < || list . size ( ) > ) { throw new ParseException ( "" + s + "" ) ; } if ( list . size ( ) == ) { result . add ( new FilterMatchTable ( Filter . NULL_MATCHER , list . get ( ) , matchParents ) ) ; } else { result . add ( new FilterMatchTable ( list . get ( ) , list . get ( ) , matchParents ) ) ; } } return FilterMatchAny . create ( result ) ; } public Filter parseColumnFilter ( boolean matchParents ) throws ParseException { List < Filter > result = new ArrayList < Filter > ( ) ; for ( List < IdentifierMatcher > list : parse ( ) ) { if ( list . size ( ) < || list . size ( ) > ) { throw new ParseException ( "" + s + "" ) ; } if ( list . size ( ) == ) { result . add ( new FilterMatchColumn ( Filter . NULL_MATCHER , list . get ( ) , list . get ( ) , matchParents ) ) ; } else { result . add ( new FilterMatchColumn ( list . get ( ) , list . get ( ) , list . get ( ) , matchParents ) ) ; } } return FilterMatchAny . create ( result ) ; } public List < List < IdentifierMatcher > > parse ( ) throws ParseException { eatSeparators ( ) ; while ( ! atEnd ( ) ) { List < IdentifierMatcher > list = new ArrayList < IdentifierMatcher > ( ) ; while ( ! atEnd ( ) ) { if ( current ( ) == '' ) { list . add ( parseRegex ( ) ) ; } else { list . add ( parseIdentifier ( ) ) ; } if ( ! atEnd ( ) && atFilterTerminator ( ) ) { break ; } index ++ ; } result . add ( list ) ; eatSeparators ( ) ; } return result ; } private void eatSeparators ( ) { while ( ! atEnd ( ) && atSeparator ( ) ) index ++ ; } private char current ( ) { return s . charAt ( index ) ; } private boolean atSeparator ( ) { return current ( ) == '' || current ( ) == '' || current ( ) == '' || current ( ) == '' || current ( ) == '' ; } private boolean atFilterTerminator ( ) { return current ( ) == '' || current ( ) == '' || current ( ) == '' ; } private boolean inIdentifier ( ) { return current ( ) != '' && current ( ) != '' && current ( ) != '' && current ( ) != '' && current ( ) != '' ; } private boolean inRegex ( ) { return current ( ) != '' && current ( ) != '' && current ( ) != '' ; } private boolean inFlags ( ) { return current ( ) == '' || current ( ) == '' || current ( ) == '' ; } private boolean atEnd ( ) { return index >= s . length ( ) ; } private IdentifierMatcher parseIdentifier ( ) { StringBuilder builder = new StringBuilder ( ) ; while ( ! atEnd ( ) && inIdentifier ( ) ) { builder . append ( current ( ) ) ; index ++ ; } return Filter . createStringMatcher ( builder . toString ( ) . trim ( ) ) ; } private IdentifierMatcher parseRegex ( ) throws ParseException { StringBuilder builder = new StringBuilder ( ) ; index ++ ; while ( ! atEnd ( ) && inRegex ( ) ) { builder . append ( current ( ) ) ; index ++ ; } if ( atEnd ( ) || current ( ) != '' ) throw new ParseException ( "" + builder . toString ( ) ) ; index ++ ; int flags = ; while ( ! atEnd ( ) && inFlags ( ) ) { if ( current ( ) == '' ) { flags |= Pattern . CASE_INSENSITIVE ; } index ++ ; } return Filter . createPatternMatcher ( Pattern . compile ( builder . toString ( ) , flags ) ) ; } public class ParseException extends Exception { public ParseException ( String message ) { super ( message ) ; } } } package de . fuberlin . wiwiss . d2rq . mapgen ; import java . io . UnsupportedEncodingException ; public class IRIEncoder { public static String encode ( String s ) { StringBuffer sbuffer = new StringBuffer ( s . length ( ) ) ; for ( int i = ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; int cCode = ( int ) c ; if ( c == '' || c == '' || c == '' || c == '' || isDigit ( cCode ) || isLetter ( cCode ) || cCode >= ) { sbuffer . append ( c ) ; } else { try { for ( byte b : s . substring ( i , i + ) . getBytes ( "" ) ) { sbuffer . append ( '' ) ; sbuffer . append ( hexDigits [ ( b > > ) & ] ) ; sbuffer . append ( hexDigits [ b & ] ) ; } } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( "" ) ; } } } return sbuffer . toString ( ) ; } private static char [ ] hexDigits = { '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' } ; private static boolean isDigit ( int c ) { return ( c >= && c <= ) ; } private static boolean isLetter ( int c ) { return ( c >= && c <= ) || ( c >= && c <= ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; public class FilterMatchColumn extends Filter { private final IdentifierMatcher schema ; private final IdentifierMatcher table ; private final IdentifierMatcher column ; private boolean matchParents ; public FilterMatchColumn ( IdentifierMatcher schema , IdentifierMatcher table , IdentifierMatcher column , boolean matchParents ) { this . schema = schema ; this . table = table ; this . column = column ; this . matchParents = matchParents ; } public boolean matchesSchema ( String schema ) { if ( ! matchParents ) return false ; return this . schema . matches ( schema ) ; } public boolean matchesTable ( String schema , String table ) { if ( ! matchParents ) return false ; return this . schema . matches ( schema ) && this . table . matches ( table ) ; } public boolean matchesColumn ( String schema , String table , String column ) { return this . schema . matches ( schema ) && this . table . matches ( table ) && this . column . matches ( column ) ; } public String getSingleSchema ( ) { return schema . getSingleString ( ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; if ( schema != Filter . NULL_MATCHER ) { result . append ( schema + "" ) ; } if ( table != Filter . NULL_MATCHER ) { result . append ( table + "" ) ; } result . append ( column ) ; result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; public class FilterMatchSchema extends Filter { private final IdentifierMatcher schema ; public FilterMatchSchema ( IdentifierMatcher schema ) { this . schema = schema ; } public boolean matchesSchema ( String schema ) { return this . schema . matches ( schema ) ; } public boolean matchesTable ( String schema , String table ) { return matchesSchema ( schema ) ; } public boolean matchesColumn ( String schema , String table , String column ) { return matchesSchema ( schema ) ; } public String getSingleSchema ( ) { return schema . getSingleString ( ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; result . append ( schema ) ; result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; public class FilterIncludeExclude extends Filter { private final Filter include ; private final Filter exclude ; public FilterIncludeExclude ( Filter include , Filter exclude ) { this . include = include ; this . exclude = exclude ; } public boolean matchesSchema ( String schema ) { return include . matchesSchema ( schema ) && ! exclude . matchesSchema ( schema ) ; } public boolean matchesTable ( String schema , String table ) { return include . matchesTable ( schema , table ) && ! exclude . matchesTable ( schema , table ) ; } public boolean matchesColumn ( String schema , String table , String column ) { return include . matchesColumn ( schema , table , column ) && ! exclude . matchesColumn ( schema , table , column ) ; } public String getSingleSchema ( ) { return include . getSingleSchema ( ) ; } public String toString ( ) { String in = ( include == Filter . ALL ) ? null : "" + include + "" ; String ex = ( exclude == Filter . NOTHING ) ? null : "" + exclude + "" ; if ( in != null ) { if ( ex == null ) { return in ; } return in + "" + ex ; } if ( ex != null ) { return ex ; } return "" ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; import java . util . Collection ; public class FilterMatchAny extends Filter { public static Filter create ( Collection < Filter > elements ) { if ( elements . isEmpty ( ) ) { return Filter . NOTHING ; } if ( elements . size ( ) == ) { return elements . iterator ( ) . next ( ) ; } return new FilterMatchAny ( elements ) ; } private final Collection < Filter > elements ; public FilterMatchAny ( Collection < Filter > elements ) { this . elements = elements ; } public boolean matchesSchema ( String schema ) { for ( Filter filter : elements ) { if ( filter . matchesSchema ( schema ) ) return true ; } return false ; } public boolean matchesTable ( String schema , String table ) { for ( Filter filter : elements ) { if ( filter . matchesTable ( schema , table ) ) return true ; } return false ; } public boolean matchesColumn ( String schema , String table , String column ) { for ( Filter filter : elements ) { if ( filter . matchesColumn ( schema , table , column ) ) return true ; } return false ; } public String getSingleSchema ( ) { String result = null ; for ( Filter filter : elements ) { if ( filter . getSingleSchema ( ) == null ) continue ; if ( result == null ) { result = filter . getSingleSchema ( ) ; } else if ( ! result . equals ( filter . getSingleSchema ( ) ) ) { return null ; } } return null ; } public String toString ( ) { if ( elements . size ( ) == ) { return "" ; } StringBuilder builder = new StringBuilder ( "" ) ; for ( Filter filter : elements ) { builder . append ( filter ) ; builder . append ( "" ) ; } builder . deleteCharAt ( builder . length ( ) - ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . io . StringReader ; import java . io . UnsupportedEncodingException ; import java . io . Writer ; import java . net . URI ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . regex . Pattern ; import org . apache . log4j . Logger ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . datatypes . TypeMapper ; import com . hp . hpl . jena . datatypes . xsd . XSDDatatype ; import com . hp . hpl . jena . rdf . model . Model ; import com . hp . hpl . jena . rdf . model . ModelFactory ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . vocabulary . DC ; import com . hp . hpl . jena . vocabulary . OWL ; import com . hp . hpl . jena . vocabulary . RDF ; import com . hp . hpl . jena . vocabulary . RDFS ; import de . fuberlin . wiwiss . d2rq . algebra . AliasMap ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . Join ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . dbschema . DatabaseSchemaInspector ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; import de . fuberlin . wiwiss . d2rq . sql . types . DataType ; public class MappingGenerator { private final static Logger log = Logger . getLogger ( MappingGenerator . class ) ; private final static String CREATOR = "" ; private final static OutputStream DUMMY_STREAM = new OutputStream ( ) { public void write ( int b ) { } } ; protected final ConnectedDB database ; protected final DatabaseSchemaInspector schema ; private String mapNamespaceURI ; protected String instanceNamespaceURI ; private String vocabNamespaceURI ; private String driverClass = null ; private Filter filter = Filter . ALL ; protected PrintWriter out = null ; private Model vocabModel = ModelFactory . createDefaultModel ( ) ; private boolean finished = false ; private boolean generateClasses = true ; private boolean generateLabelBridges = true ; private boolean generateDefinitionLabels = true ; private boolean handleLinkTables = true ; private boolean serveVocabulary = true ; private boolean skipForeignKeyTargetColumns = true ; private URI startupSQLScript ; private Map < String , Object > assignedNames = new HashMap < String , Object > ( ) ; public MappingGenerator ( ConnectedDB database ) { this . database = database ; schema = database . schemaInspector ( ) ; mapNamespaceURI = "" ; instanceNamespaceURI = "" ; vocabNamespaceURI = "" ; driverClass = ConnectedDB . guessJDBCDriverClass ( database . getJdbcURL ( ) ) ; } public void setMapNamespaceURI ( String uri ) { this . mapNamespaceURI = uri ; } public void setInstanceNamespaceURI ( String uri ) { this . instanceNamespaceURI = uri ; } public void setVocabNamespaceURI ( String uri ) { this . vocabNamespaceURI = uri ; } public void setFilter ( Filter filter ) { this . filter = filter ; } public void setJDBCDriverClass ( String driverClassName ) { this . driverClass = driverClassName ; } public void setStartupSQLScript ( URI uri ) { startupSQLScript = uri ; } public void setGenerateLabelBridges ( boolean flag ) { this . generateLabelBridges = flag ; } public void setGenerateClasses ( boolean flag ) { this . generateClasses = flag ; } public void setHandleLinkTables ( boolean flag ) { this . handleLinkTables = flag ; } public void setGenerateDefinitionLabels ( boolean flag ) { this . generateDefinitionLabels = flag ; } public void setServeVocabulary ( boolean flag ) { this . serveVocabulary = flag ; } public void setSkipForeignKeyTargetColumns ( boolean flag ) { skipForeignKeyTargetColumns = flag ; } public Model vocabularyModel ( ) { if ( ! this . finished ) { writeMapping ( DUMMY_STREAM ) ; } return this . vocabModel ; } public Model mappingModel ( String baseURI ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; writeMapping ( out ) ; try { String mappingAsTurtle = out . toString ( "" ) ; Model result = ModelFactory . createDefaultModel ( ) ; result . read ( new StringReader ( mappingAsTurtle ) , baseURI , "" ) ; return result ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( "" ) ; } } public void writeMapping ( OutputStream out ) { try { Writer w = new OutputStreamWriter ( out , "" ) ; writeMapping ( w ) ; w . flush ( ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } } public void writeMapping ( Writer out ) { this . out = new PrintWriter ( out ) ; this . out . println ( "" + this . mapNamespaceURI + "" ) ; this . out . println ( "" + this . instanceNamespaceURI + "" ) ; this . out . println ( "" + this . vocabNamespaceURI + "" ) ; this . out . println ( "" ) ; this . out . println ( "" ) ; this . out . println ( "" ) ; this . out . println ( "" ) ; this . out . println ( "" ) ; this . out . println ( ) ; if ( ! serveVocabulary ) { writeConfiguration ( ) ; } writeDatabase ( ) ; initVocabularyModel ( ) ; List < RelationName > tableNames = new ArrayList < RelationName > ( ) ; for ( RelationName tableName : schema . listTableNames ( filter . getSingleSchema ( ) ) ) { if ( ! filter . matches ( tableName ) ) { log . info ( "" + tableName ) ; continue ; } tableNames . add ( tableName ) ; } log . info ( "" + filter + "" + tableNames . size ( ) + "" ) ; for ( RelationName tableName : tableNames ) { if ( handleLinkTables && isLinkTable ( tableName ) ) { writeLinkTable ( tableName ) ; } else { writeTable ( tableName ) ; } } log . info ( "" ) ; this . out . flush ( ) ; this . out = null ; this . finished = true ; } private void writeConfiguration ( ) { log . info ( "" ) ; this . out . println ( configIRITurtle ( ) + "" ) ; this . out . println ( "" ) ; this . out . println ( ) ; } private void writeDatabase ( ) { log . info ( "" ) ; this . out . println ( databaseIRITurtle ( ) + "" ) ; this . out . println ( "" + this . driverClass + "" ) ; this . out . println ( "" + database . getJdbcURL ( ) + "" ) ; if ( database . getUsername ( ) != null ) { this . out . println ( "" + database . getUsername ( ) + "" ) ; } if ( database . getPassword ( ) != null ) { this . out . println ( "" + database . getPassword ( ) + "" ) ; } if ( startupSQLScript != null ) { out . println ( "" + startupSQLScript + "" ) ; } Properties props = database . vendor ( ) . getDefaultConnectionProperties ( ) ; for ( Object property : props . keySet ( ) ) { String value = props . getProperty ( ( String ) property ) ; this . out . println ( "" + property + "" + value + "" ) ; } this . out . println ( "" ) ; this . out . println ( ) ; this . out . flush ( ) ; } public void writeTable ( RelationName tableName ) { log . info ( "" + tableName . qualifiedName ( ) ) ; this . out . println ( "" + tableName ) ; List < Attribute > identifierColumns = identifierColumns ( tableName ) ; boolean hasIdentifier = ! identifierColumns . isEmpty ( ) ; this . out . println ( classMapIRITurtle ( tableName ) + "" ) ; this . out . println ( "" + databaseIRITurtle ( ) + "" ) ; if ( hasIdentifier ) { writeEntityIdentifier ( tableName , identifierColumns ) ; } else { writePseudoEntityIdentifier ( tableName ) ; } if ( generateClasses ) { this . out . println ( "" + vocabularyIRITurtle ( tableName ) + "" ) ; if ( generateDefinitionLabels ) { this . out . println ( "" + tableName + "" ) ; } } this . out . println ( "" ) ; if ( generateLabelBridges && hasIdentifier ) { writeLabelBridge ( tableName , identifierColumns ) ; } List < Join > foreignKeys = schema . foreignKeys ( tableName , DatabaseSchemaInspector . KEYS_IMPORTED ) ; for ( Attribute column : filter ( schema . listColumns ( tableName ) , false , "" ) ) { if ( skipForeignKeyTargetColumns && isInForeignKey ( column , foreignKeys ) ) continue ; writeColumn ( column ) ; } for ( Join fk : foreignKeys ) { if ( ! filter . matches ( fk . table1 ( ) ) || ! filter . matches ( fk . table2 ( ) ) || ! filter . matchesAll ( fk . attributes1 ( ) ) || ! filter . matchesAll ( fk . attributes2 ( ) ) ) { log . info ( "" + fk ) ; continue ; } writeForeignKey ( fk ) ; } createVocabularyClass ( tableName ) ; this . out . println ( ) ; this . out . flush ( ) ; } protected void writeEntityIdentifier ( RelationName tableName , List < Attribute > identifierColumns ) { String uriPattern = this . instanceNamespaceURI ; if ( tableName . schemaName ( ) != null ) { uriPattern += IRIEncoder . encode ( tableName . schemaName ( ) ) + "" ; } uriPattern += IRIEncoder . encode ( tableName . tableName ( ) ) ; for ( Attribute column : identifierColumns ) { uriPattern += "" + column . qualifiedName ( ) ; if ( ! schema . columnType ( column ) . isIRISafe ( ) ) { uriPattern += "" ; } uriPattern += "" ; } this . out . println ( "" + uriPattern + "" ) ; } protected void writePseudoEntityIdentifier ( RelationName tableName ) { writeWarning ( new String [ ] { "" , "" + tableName + "" , "" } , "" ) ; writeEntityIdentifier ( tableName , Collections . < Attribute > emptyList ( ) ) ; } public void writeLabelBridge ( RelationName tableName , List < Attribute > labelColumns ) { this . out . println ( propertyBridgeIRITurtle ( tableName , "" ) + "" ) ; this . out . println ( "" + classMapIRITurtle ( tableName ) + "" ) ; this . out . println ( "" ) ; this . out . println ( "" + labelPattern ( tableName . tableName ( ) , labelColumns ) + "" ) ; this . out . println ( "" ) ; } public void writeColumn ( Attribute column ) { this . out . println ( propertyBridgeIRITurtle ( column ) + "" ) ; this . out . println ( "" + classMapIRITurtle ( column . relationName ( ) ) + "" ) ; this . out . println ( "" + vocabularyIRITurtle ( column ) + "" ) ; if ( generateDefinitionLabels ) { this . out . println ( "" + toLabel ( column ) + "" ) ; } this . out . println ( "" + column . qualifiedName ( ) + "" ) ; DataType colType = this . schema . columnType ( column ) ; String xsd = colType . rdfType ( ) ; if ( xsd != null && ! "" . equals ( xsd ) ) { this . out . println ( "" + xsd + "" ) ; } if ( colType . valueRegex ( ) != null ) { this . out . println ( "" + colType . valueRegex ( ) + "" ) ; } if ( xsd == null ) { createDatatypeProperty ( column , null ) ; } else { String datatypeURI = xsd . replaceAll ( "" , XSDDatatype . XSD + "" ) ; createDatatypeProperty ( column , TypeMapper . getInstance ( ) . getSafeTypeByName ( datatypeURI ) ) ; } this . out . println ( "" ) ; } public void writeForeignKey ( Join foreignKey ) { RelationName primaryTable = schema . getCorrectCapitalization ( foreignKey . table1 ( ) ) ; List < Attribute > primaryColumns = foreignKey . attributes1 ( ) ; RelationName foreignTable = schema . getCorrectCapitalization ( foreignKey . table2 ( ) ) ; this . out . println ( propertyBridgeIRITurtle ( primaryColumns , "" ) + "" ) ; this . out . println ( "" + classMapIRITurtle ( primaryTable ) + "" ) ; this . out . println ( "" + vocabularyIRITurtle ( primaryColumns ) + "" ) ; this . out . println ( "" + classMapIRITurtle ( foreignTable ) + "" ) ; AliasMap alias = AliasMap . NO_ALIASES ; if ( foreignKey . isSameTable ( ) ) { String aliasName = foreignTable . qualifiedName ( ) . replace ( '' , '' ) + "" ; this . out . println ( "" + foreignTable . qualifiedName ( ) + "" + aliasName + "" ) ; alias = AliasMap . create1 ( foreignTable , new RelationName ( null , aliasName ) ) ; } for ( Attribute column : primaryColumns ) { this . out . println ( "" + column . qualifiedName ( ) + "" + Join . joinOperators [ foreignKey . joinDirection ( ) ] + "" + alias . applyTo ( foreignKey . equalAttribute ( column ) ) . qualifiedName ( ) + "" ) ; } createObjectProperty ( foreignKey ) ; this . out . println ( "" ) ; } private void writeLinkTable ( RelationName linkTableName ) { List < Join > keys = schema . foreignKeys ( linkTableName , DatabaseSchemaInspector . KEYS_IMPORTED ) ; Join join1 = keys . get ( ) ; Join join2 = keys . get ( ) ; if ( ! filter . matches ( join1 . table1 ( ) ) || ! filter . matches ( join1 . table2 ( ) ) || ! filter . matchesAll ( join1 . attributes1 ( ) ) || ! filter . matchesAll ( join1 . attributes2 ( ) ) || ! filter . matches ( join2 . table1 ( ) ) || ! filter . matches ( join2 . table2 ( ) ) || ! filter . matchesAll ( join2 . attributes1 ( ) ) || ! filter . matchesAll ( join2 . attributes2 ( ) ) ) { log . info ( "" + linkTableName ) ; return ; } log . info ( "" + linkTableName . qualifiedName ( ) ) ; RelationName table1 = this . schema . getCorrectCapitalization ( join1 . table2 ( ) ) ; RelationName table2 = this . schema . getCorrectCapitalization ( join2 . table2 ( ) ) ; boolean isSelfJoin = table1 . equals ( table2 ) ; this . out . println ( "" + linkTableName + ( isSelfJoin ? "" : "" ) ) ; this . out . println ( propertyBridgeIRITurtle ( linkTableName , "" ) + "" ) ; this . out . println ( "" + classMapIRITurtle ( table1 ) + "" ) ; this . out . println ( "" + vocabularyIRITurtle ( linkTableName ) + "" ) ; this . out . println ( "" + classMapIRITurtle ( table2 ) + "" ) ; for ( Attribute column : join1 . attributes1 ( ) ) { Attribute otherColumn = join1 . equalAttribute ( column ) ; this . out . println ( "" + column . qualifiedName ( ) + "" + Join . joinOperators [ join1 . joinDirection ( ) ] + "" + otherColumn . qualifiedName ( ) + "" ) ; } AliasMap alias = AliasMap . NO_ALIASES ; if ( isSelfJoin ) { RelationName aliasName = new RelationName ( null , table2 . tableName ( ) + "" + linkTableName . tableName ( ) + "" ) ; alias = AliasMap . create1 ( table2 , aliasName ) ; this . out . println ( "" + table2 . qualifiedName ( ) + "" + aliasName . qualifiedName ( ) + "" ) ; } for ( Attribute column : join2 . attributes1 ( ) ) { Attribute otherColumn = join2 . equalAttribute ( column ) ; this . out . println ( "" + column . qualifiedName ( ) + "" + Join . joinOperators [ join2 . joinDirection ( ) ] + "" + alias . applyTo ( otherColumn ) . qualifiedName ( ) + "" ) ; } this . out . println ( "" ) ; this . out . println ( ) ; createLinkProperty ( linkTableName , table1 , table2 ) ; this . out . flush ( ) ; } private void writeWarning ( String [ ] warnings , String indent ) { for ( String warning : warnings ) { this . out . println ( indent + "" + warning ) ; log . warn ( warning ) ; } } private String toUniqueString ( RelationName table ) { if ( table . schemaName ( ) == null ) { return table . tableName ( ) ; } String separator = "" ; while ( true ) { String candidate = table . schemaName ( ) + separator + table . tableName ( ) ; if ( ! assignedNames . containsKey ( candidate ) ) { assignedNames . put ( candidate , table ) ; return candidate ; } if ( assignedNames . get ( candidate ) . equals ( table ) ) { return candidate ; } separator += "" ; } } private String toUniqueString ( Attribute column ) { String separator = "" ; while ( true ) { String candidate = toUniqueString ( column . relationName ( ) ) + separator + column . attributeName ( ) ; if ( ! assignedNames . containsKey ( candidate ) ) { assignedNames . put ( candidate , column ) ; return candidate ; } if ( assignedNames . get ( candidate ) . equals ( column ) ) { return candidate ; } separator += "" ; } } private String toUniqueString ( List < Attribute > columns ) { StringBuffer result = new StringBuffer ( ) ; result . append ( toUniqueString ( ( columns . get ( ) ) . relationName ( ) ) ) ; for ( Attribute column : columns ) { result . append ( "" + column . attributeName ( ) ) ; } return result . toString ( ) ; } private String toTurtleIRI ( String namespaceIRI , String prefix , String localName ) { localName = IRIEncoder . encode ( localName ) ; if ( turtleLocalName . matcher ( localName ) . matches ( ) ) { return prefix + "" + localName ; } return "" + namespaceIRI + localName + ">" ; } private final static Pattern turtleLocalName = Pattern . compile ( "" ) ; private String configIRITurtle ( ) { return "" ; } private String databaseIRITurtle ( ) { return "" ; } private String classMapIRITurtle ( RelationName tableName ) { return toTurtleIRI ( mapNamespaceURI , "" , toUniqueString ( tableName ) ) ; } private String propertyBridgeIRITurtle ( RelationName tableName , String suffix ) { return toTurtleIRI ( mapNamespaceURI , "" , toUniqueString ( tableName ) + "" + suffix ) ; } private String propertyBridgeIRITurtle ( Attribute attribute ) { return toTurtleIRI ( mapNamespaceURI , "" , toUniqueString ( attribute ) ) ; } private String propertyBridgeIRITurtle ( List < Attribute > attributes , String suffix ) { return toTurtleIRI ( mapNamespaceURI , "" , toUniqueString ( attributes ) + "" + suffix ) ; } protected String vocabularyIRITurtle ( RelationName tableName ) { return toTurtleIRI ( vocabNamespaceURI , "" , toUniqueString ( tableName ) ) ; } protected String vocabularyIRITurtle ( Attribute attribute ) { return toTurtleIRI ( vocabNamespaceURI , "" , toUniqueString ( attribute ) ) ; } protected String vocabularyIRITurtle ( List < Attribute > attributes ) { return toTurtleIRI ( vocabNamespaceURI , "" , toUniqueString ( attributes ) ) ; } private Resource ontologyResource ( ) { String ontologyURI = dropTrailingHash ( vocabNamespaceURI ) ; return this . vocabModel . createResource ( ontologyURI ) ; } private Resource classResource ( RelationName tableName ) { String classURI = this . vocabNamespaceURI + toUniqueString ( tableName ) ; return this . vocabModel . createResource ( classURI ) ; } private Resource propertyResource ( Attribute column ) { String propertyURI = this . vocabNamespaceURI + toUniqueString ( column ) ; return this . vocabModel . createResource ( propertyURI ) ; } private Resource propertyResource ( List < Attribute > columns ) { String propertyURI = this . vocabNamespaceURI + toUniqueString ( columns ) ; return this . vocabModel . createResource ( propertyURI ) ; } private String toLabel ( Attribute column ) { return column . tableName ( ) + "" + column . attributeName ( ) ; } private String labelPattern ( String name , List < Attribute > labelColumns ) { String result = name + "" ; Iterator < Attribute > it = labelColumns . iterator ( ) ; while ( it . hasNext ( ) ) { result += "" + it . next ( ) . qualifiedName ( ) + "" ; if ( it . hasNext ( ) ) { result += "" ; } } return result ; } private List < Attribute > identifierColumns ( RelationName tableName ) { List < Attribute > columns = schema . primaryKeyColumns ( tableName ) ; if ( filter . matchesAll ( columns ) ) { return filter ( columns , true , "" ) ; } return Collections . < Attribute > emptyList ( ) ; } protected List < Attribute > filter ( List < Attribute > columns , boolean requireDistinct , String reason ) { List < Attribute > result = new ArrayList < Attribute > ( columns . size ( ) ) ; for ( Attribute column : columns ) { if ( ! filter . matches ( column ) ) { log . info ( "" + column + "" + reason ) ; continue ; } DataType type = schema . columnType ( column ) ; if ( type == null ) { writeWarning ( new String [ ] { "" + column + "" + reason + "" , "" , "" , } , "" ) ; continue ; } if ( type . isUnsupported ( ) ) { writeWarning ( new String [ ] { "" + column + "" + reason + "" , "" + schema . columnType ( column ) + "" } , "" ) ; continue ; } if ( requireDistinct && ! type . supportsDistinct ( ) ) { writeWarning ( new String [ ] { "" + column + "" + reason + "" , "" + schema . columnType ( column ) + "" } , "" ) ; } result . add ( column ) ; } return result ; } public boolean isLinkTable ( RelationName tableName ) { List < Join > foreignKeys = schema . foreignKeys ( tableName , DatabaseSchemaInspector . KEYS_IMPORTED ) ; if ( foreignKeys . size ( ) != ) return false ; List < Join > exportedKeys = schema . foreignKeys ( tableName , DatabaseSchemaInspector . KEYS_EXPORTED ) ; if ( ! exportedKeys . isEmpty ( ) ) return false ; List < Attribute > columns = schema . listColumns ( tableName ) ; Iterator < Join > it = foreignKeys . iterator ( ) ; while ( it . hasNext ( ) ) { Join fk = it . next ( ) ; if ( fk . isSameTable ( ) ) return false ; columns . removeAll ( fk . attributes1 ( ) ) ; } return columns . isEmpty ( ) ; } private boolean isInForeignKey ( Attribute column , List < Join > foreignKeys ) { for ( Join fk : foreignKeys ) { if ( fk . containsColumn ( column ) ) return true ; } return false ; } private void initVocabularyModel ( ) { this . vocabModel . setNsPrefix ( "" , RDF . getURI ( ) ) ; this . vocabModel . setNsPrefix ( "" , RDFS . getURI ( ) ) ; this . vocabModel . setNsPrefix ( "" , OWL . getURI ( ) ) ; this . vocabModel . setNsPrefix ( "" , DC . getURI ( ) ) ; this . vocabModel . setNsPrefix ( "" , XSDDatatype . XSD + "" ) ; this . vocabModel . setNsPrefix ( "" , this . vocabNamespaceURI ) ; Resource r = ontologyResource ( ) ; r . addProperty ( RDF . type , OWL . Ontology ) ; r . addProperty ( OWL . imports , this . vocabModel . getResource ( dropTrailingHash ( DC . getURI ( ) ) ) ) ; r . addProperty ( DC . creator , CREATOR ) ; } private void createVocabularyClass ( RelationName tableName ) { Resource r = classResource ( tableName ) ; r . addProperty ( RDF . type , RDFS . Class ) ; r . addProperty ( RDF . type , OWL . Class ) ; r . addProperty ( RDFS . label , tableName . qualifiedName ( ) ) ; r . addProperty ( RDFS . isDefinedBy , ontologyResource ( ) ) ; } private void createDatatypeProperty ( Attribute column , RDFDatatype datatype ) { Resource r = propertyResource ( column ) ; r . addProperty ( RDF . type , RDF . Property ) ; r . addProperty ( RDFS . label , toUniqueString ( column ) ) ; r . addProperty ( RDFS . domain , classResource ( column . relationName ( ) ) ) ; r . addProperty ( RDFS . isDefinedBy , ontologyResource ( ) ) ; r . addProperty ( RDF . type , OWL . DatatypeProperty ) ; if ( datatype != null ) { r . addProperty ( RDFS . range , this . vocabModel . getResource ( datatype . getURI ( ) ) ) ; } } private void createObjectProperty ( Join join ) { Resource r = propertyResource ( join . attributes1 ( ) ) ; r . addProperty ( RDF . type , RDF . Property ) ; r . addProperty ( RDF . type , OWL . ObjectProperty ) ; r . addProperty ( RDFS . label , toUniqueString ( join . attributes1 ( ) ) ) ; r . addProperty ( RDFS . domain , classResource ( schema . getCorrectCapitalization ( join . table1 ( ) ) ) ) ; r . addProperty ( RDFS . range , classResource ( schema . getCorrectCapitalization ( join . table2 ( ) ) ) ) ; r . addProperty ( RDFS . isDefinedBy , ontologyResource ( ) ) ; } private void createLinkProperty ( RelationName linkTableName , RelationName fromTable , RelationName toTable ) { String propertyURI = this . vocabNamespaceURI + linkTableName ; Resource r = this . vocabModel . createResource ( propertyURI ) ; r . addProperty ( RDF . type , RDF . Property ) ; r . addProperty ( RDF . type , OWL . ObjectProperty ) ; r . addProperty ( RDFS . label , linkTableName . qualifiedName ( ) ) ; r . addProperty ( RDFS . domain , classResource ( fromTable ) ) ; r . addProperty ( RDFS . range , classResource ( toTable ) ) ; r . addProperty ( RDFS . isDefinedBy , ontologyResource ( ) ) ; } private String dropTrailingHash ( String uri ) { if ( ! uri . endsWith ( "" ) ) { return uri ; } return uri . substring ( , uri . length ( ) - ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; import java . util . Collection ; import java . util . regex . Pattern ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; public abstract class Filter { public static final Filter ALL = new Filter ( ) { public boolean matchesSchema ( String schema ) { return true ; } public boolean matchesTable ( String schema , String table ) { return true ; } public boolean matchesColumn ( String schema , String table , String column ) { return true ; } public String getSingleSchema ( ) { return null ; } public String toString ( ) { return "" ; } } ; public static final Filter NOTHING = new Filter ( ) { public boolean matchesSchema ( String schema ) { return false ; } public boolean matchesTable ( String schema , String table ) { return false ; } public boolean matchesColumn ( String schema , String table , String column ) { return false ; } public String getSingleSchema ( ) { return null ; } public String toString ( ) { return "" ; } } ; public abstract boolean matchesSchema ( String schema ) ; public abstract boolean matchesTable ( String schema , String table ) ; public abstract boolean matchesColumn ( String schema , String table , String column ) ; public abstract String getSingleSchema ( ) ; public boolean matches ( RelationName table ) { return matchesTable ( table . schemaName ( ) , table . tableName ( ) ) ; } public boolean matches ( Attribute column ) { return matchesColumn ( column . schemaName ( ) , column . tableName ( ) , column . attributeName ( ) ) ; } public boolean matchesAll ( Collection < Attribute > columns ) { for ( Attribute column : columns ) { if ( ! matches ( column ) ) return false ; } return true ; } protected boolean sameSchema ( String schema1 , String schema2 ) { return schema1 == schema2 || ( schema1 != null && schema1 . equals ( schema2 ) ) ; } public static interface IdentifierMatcher { public abstract boolean matches ( String identifier ) ; public abstract String getSingleString ( ) ; } public static final IdentifierMatcher NULL_MATCHER = new IdentifierMatcher ( ) { public boolean matches ( String identifier ) { return identifier == null ; } public String getSingleString ( ) { return null ; } public String toString ( ) { return "" ; } } ; public static IdentifierMatcher createStringMatcher ( final String s ) { return new IdentifierMatcher ( ) { public boolean matches ( String identifier ) { return s . equals ( identifier ) ; } public String getSingleString ( ) { return s ; } public String toString ( ) { return "" + s + "" ; } } ; } public static IdentifierMatcher createPatternMatcher ( final Pattern pattern ) { return new IdentifierMatcher ( ) { public boolean matches ( String identifier ) { if ( identifier == null ) return false ; return pattern . matcher ( identifier ) . matches ( ) ; } public String toString ( ) { return "" + pattern . pattern ( ) + "" + pattern . flags ( ) ; } public String getSingleString ( ) { return null ; } } ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; public class FilterMatchTable extends Filter { private final IdentifierMatcher schema ; private final IdentifierMatcher table ; private final boolean matchParents ; public FilterMatchTable ( IdentifierMatcher schema , IdentifierMatcher table , boolean matchParents ) { this . schema = schema ; this . table = table ; this . matchParents = matchParents ; } public boolean matchesSchema ( String schema ) { if ( ! matchParents ) return false ; return this . schema . matches ( schema ) ; } public boolean matchesTable ( String schema , String table ) { return this . schema . matches ( schema ) && this . table . matches ( table ) ; } public boolean matchesColumn ( String schema , String table , String column ) { return matchesTable ( schema , table ) ; } public String getSingleSchema ( ) { return schema . getSingleString ( ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; if ( schema != Filter . NULL_MATCHER ) { result . append ( schema + "" ) ; } result . append ( table ) ; result . append ( "" ) ; return result . toString ( ) ; } } package de . fuberlin . wiwiss . d2rq . mapgen ; import java . util . Iterator ; import java . util . List ; import de . fuberlin . wiwiss . d2rq . algebra . Attribute ; import de . fuberlin . wiwiss . d2rq . algebra . RelationName ; import de . fuberlin . wiwiss . d2rq . sql . ConnectedDB ; public class W3CMappingGenerator extends MappingGenerator { public W3CMappingGenerator ( ConnectedDB database ) { super ( database ) ; setGenerateLabelBridges ( false ) ; setHandleLinkTables ( false ) ; setGenerateDefinitionLabels ( false ) ; setServeVocabulary ( false ) ; setSkipForeignKeyTargetColumns ( false ) ; } @ Override protected void writeEntityIdentifier ( RelationName tableName , List < Attribute > identifierColumns ) { String uriPattern = this . instanceNamespaceURI + encodeTableName ( tableName ) ; Iterator < Attribute > it = identifierColumns . iterator ( ) ; int i = ; while ( it . hasNext ( ) ) { uriPattern += i == ? "" : "" ; i ++ ; Attribute column = it . next ( ) ; uriPattern += encodeColumnName ( column ) + "" + column . qualifiedName ( ) ; if ( ! database . columnType ( column ) . isIRISafe ( ) ) { uriPattern += "" ; } uriPattern += "" ; } this . out . println ( "" + uriPattern + "" ) ; } @ Override protected void writePseudoEntityIdentifier ( RelationName tableName ) { List < Attribute > usedColumns = filter ( schema . listColumns ( tableName ) , true , "" ) ; out . print ( "" ) ; Iterator < Attribute > it = usedColumns . iterator ( ) ; while ( it . hasNext ( ) ) { Attribute column = it . next ( ) ; out . print ( column . qualifiedName ( ) ) ; if ( it . hasNext ( ) ) { out . print ( "" ) ; } } out . println ( "" ) ; } @ Override protected String vocabularyIRITurtle ( RelationName table ) { return "" + encodeTableName ( table ) + ">" ; } @ Override protected String vocabularyIRITurtle ( Attribute attribute ) { return "" + encodeTableName ( attribute . relationName ( ) ) + "" + encodeColumnName ( attribute ) + ">" ; } @ Override protected String vocabularyIRITurtle ( List < Attribute > attributes ) { StringBuffer result = new StringBuffer ( ) ; result . append ( "" ) ; result . append ( encodeTableName ( attributes . get ( ) . relationName ( ) ) ) ; int i = ; for ( Attribute column : attributes ) { String attributeName = encodeColumnName ( column ) ; if ( i == ) { result . append ( "" ) ; result . append ( attributeName ) ; } else { result . append ( "" + attributeName ) ; } i ++ ; } result . append ( ">" ) ; return result . toString ( ) ; } private String encodeTableName ( RelationName tableName ) { return ( tableName . schemaName ( ) == null ? "" : IRIEncoder . encode ( tableName . schemaName ( ) ) + '' ) + IRIEncoder . encode ( tableName . tableName ( ) ) ; } private String encodeColumnName ( Attribute column ) { return IRIEncoder . encode ( column . attributeName ( ) ) ; } } package de . fuberlin . wiwiss . d2rq . assembler ; import com . hp . hpl . jena . assembler . Assembler ; import com . hp . hpl . jena . assembler . Mode ; import com . hp . hpl . jena . assembler . assemblers . AssemblerBase ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . rdf . model . Statement ; import de . fuberlin . wiwiss . d2rq . D2RQException ; import de . fuberlin . wiwiss . d2rq . jena . ModelD2RQ ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class D2RQAssembler extends AssemblerBase { public Object open ( Assembler ignore , Resource description , Mode ignore2 ) { if ( ! description . hasProperty ( D2RQ . mappingFile ) ) { throw new D2RQException ( "" + description + "" ) ; } if ( ! description . getProperty ( D2RQ . mappingFile ) . getObject ( ) . isURIResource ( ) ) { throw new D2RQException ( "" + description + "" ) ; } String mappingFileURI = ( ( Resource ) description . getProperty ( D2RQ . mappingFile ) . getObject ( ) ) . getURI ( ) ; String resourceBaseURI = null ; Statement stmt = description . getProperty ( D2RQ . resourceBaseURI ) ; if ( stmt != null ) { if ( ! stmt . getObject ( ) . isURIResource ( ) ) { throw new D2RQException ( "" + description + "" ) ; } resourceBaseURI = ( ( Resource ) stmt . getObject ( ) ) . getURI ( ) ; } return new ModelD2RQ ( mappingFileURI , null , resourceBaseURI ) ; } } package de . fuberlin . wiwiss . d2rq . pp ; import com . hp . hpl . jena . datatypes . RDFDatatype ; import com . hp . hpl . jena . graph . Node ; import com . hp . hpl . jena . graph . Triple ; import com . hp . hpl . jena . rdf . model . RDFNode ; import com . hp . hpl . jena . rdf . model . Resource ; import com . hp . hpl . jena . shared . PrefixMapping ; import de . fuberlin . wiwiss . d2rq . vocab . D2RConfig ; import de . fuberlin . wiwiss . d2rq . vocab . D2RQ ; public class PrettyPrinter { static { D2RQ . ClassMap . getModel ( ) . setNsPrefix ( "" , D2RQ . NS ) ; D2RConfig . Server . getModel ( ) . setNsPrefix ( "" , D2RConfig . NS ) ; } public static String toString ( Node n ) { return toString ( n , null ) ; } public static String toString ( Node n , PrefixMapping prefixes ) { if ( n . isURI ( ) ) { return qNameOrURI ( n . getURI ( ) , prefixes ) ; } if ( n . isBlank ( ) ) { return "" + n . getBlankNodeLabel ( ) ; } if ( n . isVariable ( ) ) { return "" + n . getName ( ) ; } if ( Node . ANY . equals ( n ) ) { return "" ; } String s = "" + n . getLiteralLexicalForm ( ) + "" ; if ( ! "" . equals ( n . getLiteralLanguage ( ) ) ) { s += "" + n . getLiteralLanguage ( ) ; } if ( n . getLiteralDatatype ( ) != null ) { s += "" + qNameOrURI ( n . getLiteralDatatypeURI ( ) , prefixes ) ; } return s ; } private static String qNameOrURI ( String uri , PrefixMapping prefixes ) { if ( prefixes == null ) { return "" + uri + ">" ; } String qName = prefixes . qnameFor ( uri ) ; if ( qName != null ) { return qName ; } return "" + uri + ">" ; } public static String toString ( Triple t ) { return toString ( t , null ) ; } public static String toString ( Triple t , PrefixMapping prefixes ) { return toString ( t . getSubject ( ) , prefixes ) + "" + toString ( t . getPredicate ( ) , prefixes ) + "" + toString ( t . getObject ( ) , prefixes ) + "" ; } public static String toString ( RDFDatatype datatype ) { return qNameOrURI ( datatype . getURI ( ) , PrefixMapping . Standard ) ; } public static String toString ( RDFNode n ) { if ( n . isURIResource ( ) ) { Resource r = ( Resource ) n ; return toString ( r . asNode ( ) , r . getModel ( ) ) ; } return toString ( n . asNode ( ) ) ; } } package org . springframework . social . quickstart ; import static org . springframework . util . StringUtils . hasText ; import static org . springframework . web . bind . annotation . RequestMethod . GET ; import static org . springframework . web . bind . annotation . RequestMethod . POST ; import javax . validation . Valid ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . social . ExpiredAuthorizationException ; import org . springframework . social . google . api . Google ; import org . springframework . social . google . api . legacyprofile . LegacyGoogleProfile ; import org . springframework . social . google . api . plus . activity . ActivitiesPage ; import org . springframework . social . google . api . plus . activity . Activity ; import org . springframework . social . google . api . plus . comment . Comment ; import org . springframework . social . google . api . plus . comment . CommentsPage ; import org . springframework . social . google . api . plus . person . PeoplePage ; import org . springframework . social . google . api . plus . person . Person ; import org . springframework . social . google . api . tasks . Task ; import org . springframework . social . google . api . tasks . TaskList ; import org . springframework . social . google . api . tasks . TaskListsPage ; import org . springframework . social . google . api . tasks . TasksPage ; import org . springframework . social . quickstart . tasks . TaskForm ; import org . springframework . social . quickstart . tasks . TaskListForm ; import org . springframework . social . quickstart . tasks . TaskSearchForm ; import org . springframework . stereotype . Controller ; import org . springframework . validation . BindingResult ; import org . springframework . web . bind . annotation . ExceptionHandler ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestParam ; import org . springframework . web . servlet . ModelAndView ; @ Controller public class HomeController { private final Google google ; @ Autowired public HomeController ( Google google ) { this . google = google ; } @ ExceptionHandler ( ExpiredAuthorizationException . class ) public String handleExpiredToken ( ) { return "" ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView home ( ) { LegacyGoogleProfile profile = google . userOperations ( ) . getUserProfile ( ) ; return new ModelAndView ( "" , "" , profile ) ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView person ( String id , String contact ) { if ( hasText ( id ) ) { Person person = google . personOperations ( ) . getPerson ( id ) ; return new ModelAndView ( "" ) . addObject ( "" , new SearchForm ( ) ) . addObject ( "" , person ) ; } else if ( hasText ( contact ) ) { Person person = google . personOperations ( ) . getContact ( contact ) ; return new ModelAndView ( "" , "" , person ) ; } return new ModelAndView ( "" ) ; } @ RequestMapping ( value = "" , method = GET , params = { "" , "" } ) public ModelAndView people ( String text , String group , String pageToken ) { PeoplePage people ; if ( hasText ( text ) ) { people = google . personOperations ( ) . personQuery ( ) . searchFor ( text ) . fromPage ( pageToken ) . getPage ( ) ; } else if ( hasText ( group ) ) { people = google . personOperations ( ) . contactQuery ( ) . fromGroup ( group ) . fromPage ( pageToken ) . getPage ( ) ; } else { people = new PeoplePage ( ) ; } return new ModelAndView ( "" , "" , people ) ; } @ RequestMapping ( value = "" , method = GET , params = "" ) public ModelAndView plusOners ( String plusoners , String pageToken ) { PeoplePage people = google . personOperations ( ) . getActivityPlusOners ( plusoners , pageToken ) ; return new ModelAndView ( "" , "" , people ) ; } @ RequestMapping ( value = "" , method = GET , params = "" ) public ModelAndView resharers ( String resharers , String pageToken ) { PeoplePage people = google . personOperations ( ) . getActivityPlusOners ( resharers , pageToken ) ; return new ModelAndView ( "" , "" , people ) ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView activity ( String id ) { Activity activity = google . activityOperations ( ) . getActivity ( id ) ; return new ModelAndView ( "" , "" , activity ) ; } @ RequestMapping ( value = "" , method = GET , params = "" ) public ModelAndView listActivities ( @ RequestParam ( defaultValue = "" ) String person , String pageToken ) { ActivitiesPage activities = google . activityOperations ( ) . getActivitiesPage ( person , pageToken ) ; return new ModelAndView ( "" , "" , activities ) ; } @ RequestMapping ( value = "" , method = GET , params = "" ) public ModelAndView searchActivities ( String text , String pageToken ) { ActivitiesPage activities = google . activityOperations ( ) . activityQuery ( ) . searchFor ( text ) . fromPage ( pageToken ) . getPage ( ) ; return new ModelAndView ( "" , "" , activities ) ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView comments ( String activity , String pageToken ) { CommentsPage comments = google . commentOperations ( ) . getComments ( activity , pageToken ) ; return new ModelAndView ( "" , "" , comments ) ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView comment ( String id ) { Comment comment = google . commentOperations ( ) . getComment ( id ) ; return new ModelAndView ( "" , "" , comment ) ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView taskLists ( String pageToken ) { TaskListsPage taskLists = google . taskOperations ( ) . taskListQuery ( ) . fromPage ( pageToken ) . getPage ( ) ; return new ModelAndView ( "" , "" , taskLists ) ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView tasklist ( ) { return new ModelAndView ( "" , "" , new TaskListForm ( ) ) ; } @ RequestMapping ( value = "" , method = GET , params = "" ) public ModelAndView taskList ( String id ) { TaskList taskList = google . taskOperations ( ) . getTaskList ( id ) ; TaskListForm command = new TaskListForm ( taskList . getId ( ) , taskList . getTitle ( ) ) ; return new ModelAndView ( "" , "" , command ) ; } @ RequestMapping ( value = "" , method = POST ) public ModelAndView saveTaskList ( @ Valid TaskListForm command , BindingResult result ) { if ( result . hasErrors ( ) ) { return new ModelAndView ( "" , "" , command ) ; } TaskList taskList = new TaskList ( command . getId ( ) , command . getTitle ( ) ) ; google . taskOperations ( ) . saveTaskList ( taskList ) ; return new ModelAndView ( "" ) ; } @ RequestMapping ( value = "" , method = POST , params = "" ) public String deleteTaskList ( TaskListForm command ) { TaskList taskList = new TaskList ( command . getId ( ) , command . getTitle ( ) ) ; google . taskOperations ( ) . deleteTaskList ( taskList ) ; return "" ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView tasks ( TaskSearchForm command ) { TasksPage tasks = google . taskOperations ( ) . taskQuery ( ) . fromTaskList ( command . getList ( ) ) . fromPage ( command . getPageToken ( ) ) . completedFrom ( command . getCompletedMin ( ) ) . completedUntil ( command . getCompletedMax ( ) ) . dueFrom ( command . getDueMin ( ) ) . dueUntil ( command . getDueMax ( ) ) . updatedFrom ( command . getUpdatedMin ( ) ) . includeCompleted ( command . isIncludeCompleted ( ) ) . includeDeleted ( command . isIncludeDeleted ( ) ) . includeHidden ( command . isIncludeHidden ( ) ) . getPage ( ) ; return new ModelAndView ( "" ) . addObject ( "" , command ) . addObject ( "" , tasks ) ; } @ RequestMapping ( value = "" , method = GET ) public ModelAndView task ( ) { return new ModelAndView ( "" , "" , new TaskForm ( ) ) ; } @ RequestMapping ( value = "" , method = GET , params = "" ) public ModelAndView task ( String list , String id ) { if ( ! hasText ( list ) ) { list = "" ; } Task task = google . taskOperations ( ) . getTask ( list , id ) ; TaskForm command = new TaskForm ( task . getId ( ) , task . getTitle ( ) , task . getDue ( ) , task . getNotes ( ) , task . getCompleted ( ) ) ; return new ModelAndView ( "" , "" , command ) ; } @ RequestMapping ( value = "" , method = POST ) public ModelAndView saveTask ( TaskForm command , BindingResult result ) { if ( result . hasErrors ( ) ) { return new ModelAndView ( "" , "" , command ) ; } Task task = new Task ( command . getId ( ) , command . getTitle ( ) , command . getNotes ( ) , command . getDue ( ) , command . getCompleted ( ) ) ; google . taskOperations ( ) . saveTask ( command . getList ( ) , task ) ; return new ModelAndView ( "" , "" , command . getList ( ) ) ; } @ RequestMapping ( value = "" , method = POST , params = "" ) public ModelAndView createTask ( String parent , String previous , TaskForm command , BindingResult result ) { if ( result . hasErrors ( ) ) { return new ModelAndView ( "" , "" , command ) ; } Task task = new Task ( command . getId ( ) , command . getTitle ( ) , command . getNotes ( ) , command . getDue ( ) , command . getCompleted ( ) ) ; google . taskOperations ( ) . createTaskAt ( command . getList ( ) , parent , previous , task ) ; return new ModelAndView ( "" , "" , command . getList ( ) ) ; } @ RequestMapping ( value = "" , method = POST ) public ModelAndView moveTask ( String list , String move , String parent , String previous ) { google . taskOperations ( ) . moveTask ( list , new Task ( move ) , parent , previous ) ; return new ModelAndView ( "" , "" , list ) ; } @ RequestMapping ( value = "" , method = POST , params = "" ) public ModelAndView deleteTask ( @ Valid TaskForm command ) { google . taskOperations ( ) . deleteTask ( command . getList ( ) , new Task ( command . getId ( ) ) ) ; return new ModelAndView ( "" , "" , command . getList ( ) ) ; } @ RequestMapping ( value = "" , method = POST ) public ModelAndView clearTasks ( String list ) { if ( ! hasText ( list ) ) { list = "" ; } google . taskOperations ( ) . clearCompletedTasks ( new TaskList ( list , null ) ) ; return new ModelAndView ( "" , "" , list ) ; } } package org . springframework . social . quickstart . tasks ; import java . util . Date ; import org . hibernate . validator . constraints . NotBlank ; public class TaskListForm { private String id ; @ NotBlank ( message = "" ) private String title ; public TaskListForm ( ) { } public TaskListForm ( String id , String title ) { this . id = id ; this . title = title ; } public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } } package org . springframework . social . quickstart . tasks ; import static org . springframework . util . StringUtils . hasText ; import static org . springframework . format . annotation . DateTimeFormat . ISO . DATE ; import java . util . Date ; import org . hibernate . validator . constraints . NotBlank ; import org . springframework . format . annotation . DateTimeFormat ; public class TaskForm { private String list ; private String id ; @ NotBlank ( message = "" ) private String title ; private String notes ; @ DateTimeFormat ( iso = DATE ) private Date due ; @ DateTimeFormat ( iso = DATE ) private Date completed ; public TaskForm ( ) { } public TaskForm ( String id , String title , Date due , String notes , Date completed ) { this . id = id ; this . title = title ; this . due = due ; this . notes = notes ; this . completed = completed ; } public String getList ( ) { return hasText ( list ) ? list : "" ; } public void setList ( String list ) { this . list = list ; } public String getId ( ) { return hasText ( id ) ? id : null ; } public void setId ( String id ) { this . id = id ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } public String getNotes ( ) { return hasText ( notes ) ? notes : null ; } public void setNotes ( String notes ) { this . notes = notes ; } public Date getDue ( ) { return due ; } public void setDue ( Date due ) { this . due = due ; } public Date getCompleted ( ) { return completed ; } public void setCompleted ( Date completed ) { this . completed = completed ; } } package org . springframework . social . quickstart . tasks ; import static org . springframework . format . annotation . DateTimeFormat . ISO . DATE ; import static org . springframework . util . StringUtils . hasText ; import java . util . Date ; import org . springframework . format . annotation . DateTimeFormat ; public class TaskSearchForm { private String list ; private String pageToken ; @ DateTimeFormat ( iso = DATE ) private Date completedMax ; @ DateTimeFormat ( iso = DATE ) private Date completedMin ; @ DateTimeFormat ( iso = DATE ) private Date dueMax ; @ DateTimeFormat ( iso = DATE ) private Date dueMin ; @ DateTimeFormat ( iso = DATE ) private Date updatedMin ; private boolean includeCompleted ; private boolean includeDeleted ; private boolean includeHidden ; public String getList ( ) { return hasText ( list ) ? list : "" ; } public void setList ( String list ) { this . list = list ; } public String getPageToken ( ) { return pageToken ; } public void setPageToken ( String pageToken ) { this . pageToken = pageToken ; } public Date getCompletedMax ( ) { return completedMax ; } public void setCompletedMax ( Date completedMax ) { this . completedMax = completedMax ; } public Date getCompletedMin ( ) { return completedMin ; } public void setCompletedMin ( Date completedMin ) { this . completedMin = completedMin ; } public Date getDueMax ( ) { return dueMax ; } public void setDueMax ( Date dueMax ) { this . dueMax = dueMax ; } public Date getDueMin ( ) { return dueMin ; } public void setDueMin ( Date dueMin ) { this . dueMin = dueMin ; } public Date getUpdatedMin ( ) { return updatedMin ; } public void setUpdatedMin ( Date updatedMin ) { this . updatedMin = updatedMin ; } public boolean isIncludeCompleted ( ) { return includeCompleted ; } public void setIncludeCompleted ( boolean includeCompleted ) { this . includeCompleted = includeCompleted ; } public boolean isIncludeDeleted ( ) { return includeDeleted ; } public void setIncludeDeleted ( boolean includeDeleted ) { this . includeDeleted = includeDeleted ; } public boolean isIncludeHidden ( ) { return includeHidden ; } public void setIncludeHidden ( boolean includeHidden ) { this . includeHidden = includeHidden ; } } package org . springframework . social . quickstart . user ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . springframework . social . connect . UsersConnectionRepository ; import org . springframework . social . google . api . Google ; import org . springframework . web . servlet . handler . HandlerInterceptorAdapter ; import org . springframework . web . servlet . view . RedirectView ; public final class UserInterceptor extends HandlerInterceptorAdapter { private final UsersConnectionRepository connectionRepository ; private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator ( ) ; public UserInterceptor ( UsersConnectionRepository connectionRepository ) { this . connectionRepository = connectionRepository ; } public boolean preHandle ( HttpServletRequest request , HttpServletResponse response , Object handler ) throws Exception { rememberUser ( request , response ) ; handleSignOut ( request , response ) ; if ( SecurityContext . userSignedIn ( ) || requestForSignIn ( request ) ) { return true ; } else { return requireSignIn ( request , response ) ; } } public void afterCompletion ( HttpServletRequest request , HttpServletResponse response , Object handler , Exception ex ) throws Exception { SecurityContext . remove ( ) ; } private void rememberUser ( HttpServletRequest request , HttpServletResponse response ) { String userId = userCookieGenerator . readCookieValue ( request ) ; if ( userId == null ) { return ; } if ( ! userNotFound ( userId ) ) { userCookieGenerator . removeCookie ( response ) ; return ; } SecurityContext . setCurrentUser ( new User ( userId ) ) ; } private void handleSignOut ( HttpServletRequest request , HttpServletResponse response ) { if ( SecurityContext . userSignedIn ( ) && request . getServletPath ( ) . startsWith ( "" ) ) { connectionRepository . createConnectionRepository ( SecurityContext . getCurrentUser ( ) . getId ( ) ) . removeConnections ( "" ) ; userCookieGenerator . removeCookie ( response ) ; SecurityContext . remove ( ) ; } } private boolean requestForSignIn ( HttpServletRequest request ) { return request . getServletPath ( ) . startsWith ( "" ) ; } private boolean requireSignIn ( HttpServletRequest request , HttpServletResponse response ) throws Exception { new RedirectView ( "" , true ) . render ( null , request , response ) ; return false ; } private boolean userNotFound ( String userId ) { return connectionRepository . createConnectionRepository ( userId ) . findPrimaryConnection ( Google . class ) != null ; } } package org . springframework . social . quickstart . user ; public final class SecurityContext { private static final ThreadLocal < User > currentUser = new ThreadLocal < User > ( ) ; public static User getCurrentUser ( ) { User user = currentUser . get ( ) ; if ( user == null ) { throw new IllegalStateException ( "" ) ; } return user ; } public static void setCurrentUser ( User user ) { currentUser . set ( user ) ; } public static boolean userSignedIn ( ) { return currentUser . get ( ) != null ; } public static void remove ( ) { currentUser . remove ( ) ; } } package org . springframework . social . quickstart . user ; package org . springframework . social . quickstart . user ; import javax . servlet . http . Cookie ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . springframework . web . util . CookieGenerator ; final class UserCookieGenerator { private final CookieGenerator userCookieGenerator = new CookieGenerator ( ) ; public UserCookieGenerator ( ) { userCookieGenerator . setCookieName ( "" ) ; } public void addCookie ( String userId , HttpServletResponse response ) { userCookieGenerator . addCookie ( response , userId ) ; } public void removeCookie ( HttpServletResponse response ) { userCookieGenerator . addCookie ( response , "" ) ; } public String readCookieValue ( HttpServletRequest request ) { Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies == null ) { return null ; } for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( userCookieGenerator . getCookieName ( ) ) ) { return cookie . getValue ( ) ; } } return null ; } } package org . springframework . social . quickstart . user ; import java . util . concurrent . atomic . AtomicLong ; import org . springframework . social . connect . Connection ; import org . springframework . social . connect . ConnectionSignUp ; public final class SimpleConnectionSignUp implements ConnectionSignUp { private final AtomicLong userIdSequence = new AtomicLong ( ) ; public String execute ( Connection < ? > connection ) { return Long . toString ( userIdSequence . incrementAndGet ( ) ) ; } } package org . springframework . social . quickstart . user ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . springframework . social . connect . Connection ; import org . springframework . social . connect . web . SignInAdapter ; import org . springframework . web . context . request . NativeWebRequest ; public final class SimpleSignInAdapter implements SignInAdapter { private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator ( ) ; public String signIn ( String userId , Connection < ? > connection , NativeWebRequest request ) { SecurityContext . setCurrentUser ( new User ( userId ) ) ; userCookieGenerator . addCookie ( userId , request . getNativeResponse ( HttpServletResponse . class ) ) ; return null ; } } package org . springframework . social . quickstart . user ; public final class User { private final String id ; public User ( String id ) { this . id = id ; } public String getId ( ) { return id ; } } package org . springframework . social . quickstart ; package org . springframework . social . quickstart ; import static org . springframework . format . annotation . DateTimeFormat . ISO . DATE ; import java . util . Date ; import org . springframework . format . annotation . DateTimeFormat ; public class SearchForm { private String text ; private int startIndex ; private int maxResults ; @ DateTimeFormat ( iso = DATE ) private Date updatedMin ; @ DateTimeFormat ( iso = DATE ) private Date updatedMax ; @ DateTimeFormat ( iso = DATE ) private Date publishedMin ; @ DateTimeFormat ( iso = DATE ) private Date publishedMax ; public String getText ( ) { return text ; } public void setText ( String text ) { this . text = text ; } public int getStartIndex ( ) { return startIndex ; } public void setStartIndex ( int startIndex ) { this . startIndex = startIndex ; } public int getMaxResults ( ) { return maxResults ; } public void setMaxResults ( int maxResults ) { this . maxResults = maxResults ; } public Date getUpdatedMin ( ) { return updatedMin ; } public void setUpdatedMin ( Date updatedMin ) { this . updatedMin = updatedMin ; } public Date getUpdatedMax ( ) { return updatedMax ; } public void setUpdatedMax ( Date updatedMax ) { this . updatedMax = updatedMax ; } public Date getPublishedMin ( ) { return publishedMin ; } public void setPublishedMin ( Date publishedMin ) { this . publishedMin = publishedMin ; } public Date getPublishedMax ( ) { return publishedMax ; } public void setPublishedMax ( Date publishedMax ) { this . publishedMax = publishedMax ; } } package org . springframework . social . quickstart . plus ; public class PlusSearchForm { private String text ; private String pageToken ; private int maxResults ; private String order ; public String getText ( ) { return text ; } public void setText ( String text ) { this . text = text ; } public String getPageToken ( ) { return pageToken ; } public void setPageToken ( String pageToken ) { this . pageToken = pageToken ; } public int getMaxResults ( ) { return maxResults ; } public void setMaxResults ( int maxResults ) { this . maxResults = maxResults ; } public String getOrder ( ) { return order ; } public void setOrder ( String order ) { this . order = order ; } } package org . springframework . social . quickstart . config ; import org . springframework . context . annotation . Configuration ; import org . springframework . context . annotation . Profile ; import org . springframework . context . annotation . PropertySource ; @ Configuration @ Profile ( "" ) @ PropertySource ( "" ) public class CloudfoundryConfiguration { } package org . springframework . social . quickstart . config ; package org . springframework . social . quickstart . config ; import javax . sql . DataSource ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . context . annotation . Bean ; import org . springframework . context . annotation . Configuration ; import org . springframework . context . annotation . Scope ; import org . springframework . context . annotation . ScopedProxyMode ; import org . springframework . core . env . Environment ; import org . springframework . security . crypto . encrypt . Encryptors ; import org . springframework . social . connect . ConnectionFactory ; import org . springframework . social . connect . ConnectionFactoryLocator ; import org . springframework . social . connect . ConnectionRepository ; import org . springframework . social . connect . NotConnectedException ; import org . springframework . social . connect . UsersConnectionRepository ; import org . springframework . social . connect . jdbc . JdbcUsersConnectionRepository ; import org . springframework . social . connect . support . ConnectionFactoryRegistry ; import org . springframework . social . connect . web . ProviderSignInController ; import org . springframework . social . google . api . Google ; import org . springframework . social . google . connect . GoogleConnectionFactory ; import org . springframework . social . quickstart . user . SecurityContext ; import org . springframework . social . quickstart . user . SimpleConnectionSignUp ; import org . springframework . social . quickstart . user . SimpleSignInAdapter ; import org . springframework . social . quickstart . user . User ; @ Configuration public class SocialConfig { @ Autowired private Environment environment ; @ Autowired private DataSource dataSource ; @ Bean public ConnectionFactoryLocator connectionFactoryLocator ( ) { ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry ( ) ; registry . addConnectionFactory ( new GoogleConnectionFactory ( environment . getProperty ( "" ) , environment . getProperty ( "" ) ) ) ; return registry ; } @ Bean public UsersConnectionRepository usersConnectionRepository ( ) { JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository ( dataSource , connectionFactoryLocator ( ) , Encryptors . noOpText ( ) ) ; repository . setConnectionSignUp ( new SimpleConnectionSignUp ( ) ) ; return repository ; } @ Bean @ Scope ( value = "" , proxyMode = ScopedProxyMode . INTERFACES ) public ConnectionRepository connectionRepository ( ) { User user = SecurityContext . getCurrentUser ( ) ; return usersConnectionRepository ( ) . createConnectionRepository ( user . getId ( ) ) ; } @ Bean @ Scope ( value = "" , proxyMode = ScopedProxyMode . INTERFACES ) public Google google ( ) { return connectionRepository ( ) . getPrimaryConnection ( Google . class ) . getApi ( ) ; } @ Bean public ProviderSignInController providerSignInController ( ) { return new ProviderSignInController ( connectionFactoryLocator ( ) , usersConnectionRepository ( ) , new SimpleSignInAdapter ( ) ) ; } } package org . springframework . social . quickstart . config ; import javax . sql . DataSource ; import org . springframework . context . annotation . Bean ; import org . springframework . context . annotation . ComponentScan ; import org . springframework . context . annotation . ComponentScan . Filter ; import org . springframework . context . annotation . Configuration ; import org . springframework . core . io . ClassPathResource ; import org . springframework . jdbc . datasource . embedded . EmbeddedDatabaseFactory ; import org . springframework . jdbc . datasource . embedded . EmbeddedDatabaseType ; import org . springframework . jdbc . datasource . init . DatabasePopulator ; import org . springframework . jdbc . datasource . init . ResourceDatabasePopulator ; import org . springframework . social . connect . jdbc . JdbcUsersConnectionRepository ; @ Configuration @ ComponentScan ( basePackages = "" , excludeFilters = { @ Filter ( Configuration . class ) } ) public class MainConfig { @ Bean ( destroyMethod = "" ) public DataSource dataSource ( ) { EmbeddedDatabaseFactory factory = new EmbeddedDatabaseFactory ( ) ; factory . setDatabaseName ( "" ) ; factory . setDatabaseType ( EmbeddedDatabaseType . H2 ) ; factory . setDatabasePopulator ( databasePopulator ( ) ) ; return factory . getDatabase ( ) ; } private DatabasePopulator databasePopulator ( ) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator ( ) ; populator . addScript ( new ClassPathResource ( "" , JdbcUsersConnectionRepository . class ) ) ; return populator ; } } package org . springframework . social . quickstart . config ; import javax . inject . Inject ; import org . springframework . context . annotation . Bean ; import org . springframework . context . annotation . Configuration ; import org . springframework . social . connect . UsersConnectionRepository ; import org . springframework . social . quickstart . user . UserInterceptor ; import org . springframework . web . multipart . MultipartResolver ; import org . springframework . web . multipart . commons . CommonsMultipartResolver ; import org . springframework . web . servlet . ViewResolver ; import org . springframework . web . servlet . config . annotation . DefaultServletHandlerConfigurer ; import org . springframework . web . servlet . config . annotation . EnableWebMvc ; import org . springframework . web . servlet . config . annotation . WebMvcConfigurerAdapter ; import org . springframework . web . servlet . view . InternalResourceViewResolver ; @ Configuration @ EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @ Bean public UserInterceptor userInterceptor ( ) { return new UserInterceptor ( usersConnectionRepository ) ; } @ Bean public MultipartResolver multipartResolver ( ) { return new CommonsMultipartResolver ( ) ; } @ Override public void configureDefaultServletHandling ( DefaultServletHandlerConfigurer configurer ) { configurer . enable ( ) ; } @ Bean public ViewResolver viewResolver ( ) { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver ( ) ; viewResolver . setPrefix ( "" ) ; viewResolver . setSuffix ( "" ) ; return viewResolver ; } private @ Inject UsersConnectionRepository usersConnectionRepository ; } package org . springframework . social . quickstart . config ; import org . springframework . context . annotation . Configuration ; import org . springframework . context . annotation . Profile ; import org . springframework . context . annotation . PropertySource ; @ Configuration @ Profile ( "" ) @ PropertySource ( "" ) public class LocalhostConfiguration { } package org . springframework . social . quickstart . config ; import org . cloudfoundry . runtime . env . ApplicationInstanceInfo ; import org . cloudfoundry . runtime . env . CloudEnvironment ; import org . springframework . context . ApplicationContextInitializer ; import org . springframework . context . ConfigurableApplicationContext ; import org . springframework . core . env . ConfigurableEnvironment ; public class EnvironmentInitializer implements ApplicationContextInitializer < ConfigurableApplicationContext > { public void initialize ( ConfigurableApplicationContext ctx ) { ConfigurableEnvironment environment = ctx . getEnvironment ( ) ; ApplicationInstanceInfo instanceInfo = new CloudEnvironment ( ) . getInstanceInfo ( ) ; if ( instanceInfo == null ) { environment . setActiveProfiles ( "" ) ; } else { environment . setActiveProfiles ( "" ) ; } } } package org . springframework . social . google . connect ; import java . util . Map ; import org . springframework . http . HttpEntity ; import org . springframework . http . HttpHeaders ; import org . springframework . http . HttpMethod ; import org . springframework . http . MediaType ; import org . springframework . http . ResponseEntity ; import org . springframework . social . oauth2 . AccessGrant ; import org . springframework . social . oauth2 . OAuth2Template ; import org . springframework . util . MultiValueMap ; public class GoogleOAuth2Template extends OAuth2Template { public GoogleOAuth2Template ( String clientId , String clientSecret ) { super ( clientId , clientSecret , "" , "" ) ; } @ Override @ SuppressWarnings ( { "" , "" } ) protected AccessGrant postForAccessGrant ( String accessTokenUrl , MultiValueMap < String , String > parameters ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . APPLICATION_FORM_URLENCODED ) ; HttpEntity < MultiValueMap < String , String > > requestEntity = new HttpEntity < MultiValueMap < String , String > > ( parameters , headers ) ; ResponseEntity < Map > responseEntity = getRestTemplate ( ) . exchange ( accessTokenUrl , HttpMethod . POST , requestEntity , Map . class ) ; Map < String , Object > responseMap = responseEntity . getBody ( ) ; return extractAccessGrant ( responseMap ) ; } private AccessGrant extractAccessGrant ( Map < String , Object > result ) { String accessToken = ( String ) result . get ( "" ) ; String scope = ( String ) result . get ( "" ) ; String refreshToken = ( String ) result . get ( "" ) ; Integer expiresIn = ( Integer ) result . get ( "" ) ; return createAccessGrant ( accessToken , scope , refreshToken , expiresIn , result ) ; } } package org . springframework . social . google . connect ; import org . springframework . social . connect . UserProfile ; import org . springframework . social . connect . support . OAuth2ConnectionFactory ; import org . springframework . social . google . api . Google ; import org . springframework . social . oauth2 . AccessGrant ; public class GoogleConnectionFactory extends OAuth2ConnectionFactory < Google > { public GoogleConnectionFactory ( String clientId , String clientSecret ) { super ( "" , new GoogleServiceProvider ( clientId , clientSecret ) , new GoogleAdapter ( ) ) ; } @ Override protected String extractProviderUserId ( AccessGrant accessGrant ) { Google api = ( ( GoogleServiceProvider ) getServiceProvider ( ) ) . getApi ( accessGrant . getAccessToken ( ) ) ; UserProfile userProfile = getApiAdapter ( ) . fetchUserProfile ( api ) ; return userProfile . getUsername ( ) ; } } package org . springframework . social . google . connect ; package org . springframework . social . google . connect ; import org . springframework . social . connect . ApiAdapter ; import org . springframework . social . connect . ConnectionValues ; import org . springframework . social . connect . UserProfile ; import org . springframework . social . connect . UserProfileBuilder ; import org . springframework . social . google . api . Google ; import org . springframework . social . google . api . legacyprofile . LegacyGoogleProfile ; public class GoogleAdapter implements ApiAdapter < Google > { public boolean test ( Google google ) { return true ; } public void setConnectionValues ( Google google , ConnectionValues values ) { LegacyGoogleProfile profile = google . userOperations ( ) . getUserProfile ( ) ; values . setProviderUserId ( profile . getId ( ) ) ; values . setDisplayName ( profile . getName ( ) ) ; values . setProfileUrl ( profile . getLink ( ) ) ; values . setImageUrl ( profile . getProfilePictureUrl ( ) ) ; } public UserProfile fetchUserProfile ( Google google ) { LegacyGoogleProfile profile = google . userOperations ( ) . getUserProfile ( ) ; return new UserProfileBuilder ( ) . setUsername ( profile . getEmail ( ) ) . setEmail ( profile . getEmail ( ) ) . setName ( profile . getName ( ) ) . setFirstName ( profile . getFirstName ( ) ) . setLastName ( profile . getLastName ( ) ) . build ( ) ; } public void updateStatus ( Google google , String message ) { throw new UnsupportedOperationException ( ) ; } } package org . springframework . social . google . connect ; import org . springframework . social . google . api . Google ; import org . springframework . social . google . api . impl . GoogleTemplate ; import org . springframework . social . oauth2 . AbstractOAuth2ServiceProvider ; public class GoogleServiceProvider extends AbstractOAuth2ServiceProvider < Google > { public GoogleServiceProvider ( String clientId , String clientSecret ) { super ( new GoogleOAuth2Template ( clientId , clientSecret ) ) ; } @ Override public Google getApi ( String accessToken ) { return new GoogleTemplate ( accessToken ) ; } } package org . springframework . social . google . api . legacyprofile ; public interface LegacyProfileOperations { LegacyGoogleProfile getUserProfile ( ) ; } package org . springframework . social . google . api . legacyprofile ; import java . io . Serializable ; public class LegacyGoogleProfile implements Serializable { private static final long serialVersionUID = - ; private String id ; private String email ; private String name ; private String firstName ; private String lastName ; private String link ; private String profilePictureUrl ; private String gender ; private String locale ; public String getId ( ) { return id ; } public String getEmail ( ) { return email ; } public String getName ( ) { return name ; } public String getFirstName ( ) { return firstName ; } public String getLastName ( ) { return lastName ; } public String getLink ( ) { return link ; } public String getProfilePictureUrl ( ) { return profilePictureUrl ; } public String getGender ( ) { return gender ; } public String getLocale ( ) { return locale ; } } package org . springframework . social . google . api . legacyprofile . impl ; import org . springframework . social . google . api . impl . AbstractGoogleApiOperations ; import org . springframework . social . google . api . legacyprofile . LegacyGoogleProfile ; import org . springframework . social . google . api . legacyprofile . LegacyProfileOperations ; import org . springframework . web . client . RestTemplate ; public class UserTemplate extends AbstractGoogleApiOperations implements LegacyProfileOperations { public UserTemplate ( RestTemplate restTemplate , boolean authorized ) { super ( restTemplate , authorized ) ; } public LegacyGoogleProfile getUserProfile ( ) { requireAuthorization ( ) ; return restTemplate . getForObject ( "" , LegacyGoogleProfile . class ) ; } } package org . springframework . social . google . api . tasks ; import org . springframework . social . google . api . query . ApiPage ; public class TasksPage extends ApiPage < Task > { } package org . springframework . social . google . api . tasks ; import static org . springframework . social . google . api . tasks . TaskStatus . COMPLETED ; import static org . springframework . social . google . api . tasks . TaskStatus . NEEDS_ACTION ; import java . util . Date ; import org . springframework . social . google . api . ApiEntity ; public class Task extends ApiEntity { private String title ; private String notes ; private Date due ; private String parent ; private String position ; private Date updated ; private TaskStatus status ; private Date completed ; public Task ( ) { } public Task ( String id ) { super ( id ) ; } public Task ( String id , String title , String notes , Date due , Date completed ) { super ( id ) ; this . title = title ; this . notes = notes ; this . due = due ; setCompleted ( completed ) ; } public Task ( String title , String notes , Date due , Date completed ) { this ( null , title , notes , due , completed ) ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } public String getNotes ( ) { return notes ; } public void setNotes ( String notes ) { this . notes = notes ; } public Date getDue ( ) { return due ; } public void setDue ( Date due ) { this . due = due ; } public String getParent ( ) { return parent ; } public String getPosition ( ) { return position ; } public Date getUpdated ( ) { return updated ; } public TaskStatus getStatus ( ) { return status ; } public Date getCompleted ( ) { return completed ; } public void setCompleted ( Date completed ) { this . completed = completed ; status = completed == null ? NEEDS_ACTION : COMPLETED ; } } package org . springframework . social . google . api . tasks ; import org . codehaus . jackson . map . annotate . JsonDeserialize ; import org . codehaus . jackson . map . annotate . JsonSerialize ; import org . springframework . social . google . api . impl . ApiEnumSerializer ; import org . springframework . social . google . api . tasks . impl . TaskStatusDeserializer ; @ JsonSerialize ( using = ApiEnumSerializer . class ) @ JsonDeserialize ( using = TaskStatusDeserializer . class ) public enum TaskStatus { NEEDS_ACTION , COMPLETED } package org . springframework . social . google . api . tasks ; import org . springframework . social . google . api . query . ApiQueryBuilder ; import org . springframework . social . google . api . query . QueryBuilder ; public interface TaskListQueryBuilder extends ApiQueryBuilder < TaskListQueryBuilder , TaskListsPage > { } package org . springframework . social . google . api . tasks . impl ; import static org . springframework . social . google . api . tasks . impl . TaskTemplate . TASK_LISTS_URL ; import org . springframework . social . google . api . query . impl . ApiQueryBuilderImpl ; import org . springframework . social . google . api . tasks . TaskListQueryBuilder ; import org . springframework . social . google . api . tasks . TaskListsPage ; import org . springframework . web . client . RestTemplate ; class TaskListQueryBuilderImpl extends ApiQueryBuilderImpl < TaskListQueryBuilder , TaskListsPage > implements TaskListQueryBuilder { public TaskListQueryBuilderImpl ( RestTemplate restTemplate ) { super ( TASK_LISTS_URL , TaskListsPage . class , restTemplate ) ; } } package org . springframework . social . google . api . tasks . impl ; import static org . springframework . util . Assert . isNull ; import static org . springframework . util . Assert . isTrue ; import static org . springframework . util . Assert . notNull ; import static org . springframework . util . StringUtils . hasText ; import org . springframework . social . google . api . impl . AbstractGoogleApiOperations ; import org . springframework . social . google . api . tasks . Task ; import org . springframework . social . google . api . tasks . TaskList ; import org . springframework . social . google . api . tasks . TaskListQueryBuilder ; import org . springframework . social . google . api . tasks . TaskListsPage ; import org . springframework . social . google . api . tasks . TaskOperations ; import org . springframework . social . google . api . tasks . TaskQueryBuilder ; import org . springframework . social . google . api . tasks . TasksPage ; import org . springframework . web . client . RestTemplate ; public class TaskTemplate extends AbstractGoogleApiOperations implements TaskOperations { static final String TASK_LISTS_URL = "" ; static final String TASKS_URL = "" ; static final String DEFAULT = "" ; static final String TASKS = "" ; public TaskTemplate ( RestTemplate restTemplate , boolean isAuthorized ) { super ( restTemplate , isAuthorized ) ; } @ Override public TaskListsPage getTaskLists ( ) { return taskListQuery ( ) . maxResultsNumber ( ) . getPage ( ) ; } @ Override public TaskList getTaskList ( String id ) { return getEntity ( TASK_LISTS_URL + '' + id , TaskList . class ) ; } @ Override public TaskList saveTaskList ( TaskList taskList ) { return saveEntity ( TASK_LISTS_URL , taskList ) ; } @ Override public void deleteTaskList ( TaskList taskList ) { deleteEntity ( TASK_LISTS_URL , taskList ) ; } @ Override public TaskListQueryBuilder taskListQuery ( ) { return new TaskListQueryBuilderImpl ( restTemplate ) ; } @ Override public TasksPage getTasks ( ) { return taskQuery ( ) . maxResultsNumber ( ) . getPage ( ) ; } @ Override public Task getTask ( String id ) { return getTask ( DEFAULT , id ) ; } @ Override public Task getTask ( String taskListId , String id ) { return getEntity ( TASKS_URL + taskListId + TASKS + '' + id , Task . class ) ; } @ Override public Task saveTask ( Task task ) { return saveTask ( DEFAULT , task ) ; } @ Override public Task saveTask ( String taskListId , Task task ) { return saveEntity ( TASKS_URL + taskListId + TASKS , task ) ; } @ Override public Task createTaskAt ( String taskListId , String parent , String previous , Task task ) { isNull ( task . getId ( ) ) ; StringBuilder sb = new StringBuilder ( TASKS_URL ) . append ( defaultIfBlank ( taskListId , DEFAULT ) ) . append ( TASKS ) . append ( '' ) ; if ( hasText ( parent ) ) { sb . append ( "" ) . append ( parent ) . append ( '' ) ; } if ( hasText ( previous ) ) { sb . append ( "" ) . append ( previous ) ; } return saveEntity ( sb . toString ( ) , task ) ; } @ Override public Task moveTask ( String taskListId , Task task , String parent , String previous ) { notNull ( task . getId ( ) ) ; isTrue ( hasText ( parent ) || hasText ( previous ) , "" ) ; StringBuilder sb = new StringBuilder ( TASKS_URL ) . append ( defaultIfBlank ( taskListId , DEFAULT ) ) . append ( TASKS ) . append ( '' ) . append ( task . getId ( ) ) . append ( "" ) ; if ( hasText ( parent ) ) { sb . append ( "" ) . append ( parent ) . append ( '' ) ; } if ( hasText ( previous ) ) { sb . append ( "" ) . append ( previous ) ; } return restTemplate . postForObject ( sb . toString ( ) , null , Task . class ) ; } @ Override public void deleteTask ( Task task ) { deleteTask ( DEFAULT , task ) ; } @ Override public void deleteTask ( String taskListId , Task task ) { deleteEntity ( TASKS_URL + taskListId + TASKS , task ) ; } @ Override public TaskQueryBuilder taskQuery ( ) { return new TaskQueryBuilderImpl ( restTemplate ) ; } private static String defaultIfBlank ( String value , String defaultValue ) { return hasText ( value ) ? value : defaultValue ; } @ Override public void clearCompletedTasks ( TaskList taskList ) { notNull ( taskList . getId ( ) ) ; restTemplate . postForLocation ( TASKS_URL + taskList . getId ( ) + "" , null ) ; } } package org . springframework . social . google . api . tasks . impl ; import org . codehaus . jackson . map . annotate . JsonCachable ; import org . springframework . social . google . api . impl . ApiEnumDeserializer ; import org . springframework . social . google . api . tasks . TaskStatus ; @ JsonCachable public class TaskStatusDeserializer extends ApiEnumDeserializer < TaskStatus > { public TaskStatusDeserializer ( ) { super ( TaskStatus . class ) ; } } package org . springframework . social . google . api . tasks . impl ; import static org . springframework . social . google . api . tasks . impl . TaskTemplate . DEFAULT ; import static org . springframework . social . google . api . tasks . impl . TaskTemplate . TASKS ; import static org . springframework . social . google . api . tasks . impl . TaskTemplate . TASKS_URL ; import java . util . Date ; import org . springframework . social . google . api . query . impl . ApiQueryBuilderImpl ; import org . springframework . social . google . api . tasks . TaskQueryBuilder ; import org . springframework . social . google . api . tasks . TasksPage ; import org . springframework . web . client . RestTemplate ; class TaskQueryBuilderImpl extends ApiQueryBuilderImpl < TaskQueryBuilder , TasksPage > implements TaskQueryBuilder { private String taskListId = DEFAULT ; private Date completedMin ; private Date completedMax ; private Date dueMin ; private Date dueMax ; private Date updatedMin ; private boolean includeCompleted ; private boolean includeDeleted ; private boolean includeHidden ; TaskQueryBuilderImpl ( RestTemplate restTemplate ) { super ( TasksPage . class , restTemplate ) ; } @ Override public TaskQueryBuilder fromTaskList ( String taskListId ) { this . taskListId = taskListId ; return this ; } @ Override public TaskQueryBuilder completedFrom ( Date completedMin ) { this . completedMin = completedMin ; return this ; } @ Override public TaskQueryBuilder completedUntil ( Date completedMax ) { this . completedMax = completedMax ; return this ; } @ Override public TaskQueryBuilder dueFrom ( Date dueMin ) { this . dueMin = dueMin ; return this ; } @ Override public TaskQueryBuilder dueUntil ( Date dueMax ) { this . dueMax = dueMax ; return this ; } @ Override public TaskQueryBuilder updatedFrom ( Date updatedMin ) { this . updatedMin = updatedMin ; return this ; } @ Override public TaskQueryBuilder includeCompleted ( boolean includeCompleted ) { this . includeCompleted = includeCompleted ; return this ; } @ Override public TaskQueryBuilder includeDeleted ( boolean includeDeleted ) { this . includeDeleted = includeDeleted ; return this ; } @ Override public TaskQueryBuilder includeHidden ( boolean includeHidden ) { this . includeHidden = includeHidden ; return this ; } @ Override protected StringBuilder build ( ) { if ( dueMin != null && dueMax == null ) { dueMax = new Date ( ) ; } if ( dueMin == null && dueMax != null ) { dueMin = new Date ( ) ; } feedUrl = TASKS_URL + taskListId + TASKS ; StringBuilder sb = super . build ( ) ; appendQueryParam ( sb , "" , completedMin ) ; appendQueryParam ( sb , "" , completedMax ) ; appendQueryParam ( sb , "" , dueMin ) ; appendQueryParam ( sb , "" , dueMax ) ; appendQueryParam ( sb , "" , includeCompleted ) ; appendQueryParam ( sb , "" , includeDeleted ) ; appendQueryParam ( sb , "" , includeHidden ) ; appendQueryParam ( sb , "" , updatedMin ) ; return sb ; } } package org . springframework . social . google . api . tasks ; import java . util . Date ; import org . springframework . social . google . api . query . ApiQueryBuilder ; import org . springframework . social . google . api . query . QueryBuilder ; public interface TaskQueryBuilder extends ApiQueryBuilder < TaskQueryBuilder , TasksPage > { TaskQueryBuilder fromTaskList ( String taskListId ) ; TaskQueryBuilder completedFrom ( Date completedMin ) ; TaskQueryBuilder completedUntil ( Date completedMax ) ; TaskQueryBuilder dueFrom ( Date dueMin ) ; TaskQueryBuilder dueUntil ( Date dueMax ) ; TaskQueryBuilder updatedFrom ( Date updatedMin ) ; TaskQueryBuilder includeCompleted ( boolean includeCompleted ) ; TaskQueryBuilder includeDeleted ( boolean includeDeleted ) ; TaskQueryBuilder includeHidden ( boolean includeHidden ) ; } package org . springframework . social . google . api . tasks ; public interface TaskOperations { TaskListsPage getTaskLists ( ) ; TaskList getTaskList ( String id ) ; TaskList saveTaskList ( TaskList taskList ) ; void deleteTaskList ( TaskList taskList ) ; TaskListQueryBuilder taskListQuery ( ) ; TasksPage getTasks ( ) ; Task getTask ( String id ) ; Task getTask ( String taskListId , String id ) ; Task saveTask ( Task task ) ; Task saveTask ( String taskListId , Task task ) ; void deleteTask ( Task task ) ; void deleteTask ( String taskListId , Task task ) ; TaskQueryBuilder taskQuery ( ) ; Task createTaskAt ( String taskListId , String parent , String previous , Task task ) ; Task moveTask ( String taskListId , Task task , String parent , String previous ) ; void clearCompletedTasks ( TaskList taskList ) ; } package org . springframework . social . google . api . tasks ; import org . springframework . social . google . api . query . ApiPage ; public class TaskListsPage extends ApiPage < TaskList > { } package org . springframework . social . google . api . tasks ; import org . springframework . social . google . api . ApiEntity ; public class TaskList extends ApiEntity { private String title ; public TaskList ( ) { } public TaskList ( String id , String title ) { super ( id ) ; this . title = title ; } public TaskList ( String title ) { this . title = title ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } } package org . springframework . social . google . api . query ; public interface ApiQueryBuilder < Q extends ApiQueryBuilder < ? , T > , T extends ApiPage < ? > > extends QueryBuilder < Q , T > { Q fromPage ( String pageToken ) ; T getPage ( ) ; } package org . springframework . social . google . api . query ; import java . util . List ; public class ApiPage < T > { private List < ? extends T > items ; private String nextPageToken ; protected ApiPage ( ) { } protected ApiPage ( List < ? extends T > items , String nextPageToken ) { this . items = items ; this . nextPageToken = nextPageToken ; } public List < ? extends T > getItems ( ) { return items ; } public String getNextPageToken ( ) { return nextPageToken ; } } package org . springframework . social . google . api . query ; public interface QueryBuilder < Q extends QueryBuilder < ? , T > , T > { Q maxResultsNumber ( int maxResults ) ; } package org . springframework . social . google . api . query . impl ; import static org . springframework . util . StringUtils . hasText ; import java . text . Format ; import java . text . SimpleDateFormat ; import java . util . Date ; import org . springframework . social . google . api . query . QueryBuilder ; public abstract class QueryBuilderImpl < Q extends QueryBuilder < ? , T > , T > implements QueryBuilder < Q , T > { private static final Format dateFormatter = new SimpleDateFormat ( "" ) ; protected String feedUrl ; protected int maxResults ; protected QueryBuilderImpl ( ) { } protected QueryBuilderImpl ( String feedUrl ) { this . feedUrl = feedUrl ; } @ SuppressWarnings ( "" ) protected Q castThis ( ) { return ( Q ) this ; } @ Override public Q maxResultsNumber ( int maxResults ) { this . maxResults = maxResults ; return castThis ( ) ; } protected void appendQueryParam ( StringBuilder sb , String name , Date value ) { if ( value != null ) { appendQueryParam ( sb , name , dateFormatter . format ( value ) ) ; } } protected void appendQueryParam ( StringBuilder sb , String name , int value ) { if ( value > ) { appendQueryParam ( sb , name , String . valueOf ( value ) ) ; } } protected void appendQueryParam ( StringBuilder sb , String name , Object value ) { if ( value != null ) { appendQueryParam ( sb , name , value . toString ( ) ) ; } } protected void appendQueryParam ( StringBuilder sb , String name , Enum < ? > value ) { if ( value != null ) { appendQueryParam ( sb , name , value . name ( ) . toLowerCase ( ) ) ; } } protected void appendQueryParam ( StringBuilder sb , String name , String value ) { if ( hasText ( value ) ) { sb . append ( name ) . append ( '' ) . append ( value . trim ( ) ) . append ( '' ) ; } } protected StringBuilder build ( ) { StringBuilder sb = new StringBuilder ( feedUrl ) ; if ( feedUrl . indexOf ( '' ) < ) { sb . append ( '' ) ; } else { sb . append ( '' ) ; } return sb ; } } package org . springframework . social . google . api . query . impl ; import org . springframework . social . google . api . query . ApiPage ; import org . springframework . social . google . api . query . ApiQueryBuilder ; import org . springframework . social . google . api . query . QueryBuilder ; import org . springframework . web . client . RestTemplate ; public class ApiQueryBuilderImpl < Q extends ApiQueryBuilder < ? , T > , T extends ApiPage < ? > > extends QueryBuilderImpl < Q , T > implements ApiQueryBuilder < Q , T > { private final Class < T > type ; private final RestTemplate restTemplate ; private String pageToken ; public ApiQueryBuilderImpl ( Class < T > type , RestTemplate restTemplate ) { this . type = type ; this . restTemplate = restTemplate ; } public ApiQueryBuilderImpl ( String feedUrl , Class < T > type , RestTemplate restTemplate ) { super ( feedUrl ) ; this . type = type ; this . restTemplate = restTemplate ; } @ Override public Q fromPage ( String pageToken ) { this . pageToken = pageToken ; return castThis ( ) ; } @ Override protected StringBuilder build ( ) { StringBuilder sb = super . build ( ) ; appendQueryParam ( sb , "" , maxResults ) ; appendQueryParam ( sb , "" , pageToken ) ; return sb ; } @ Override public T getPage ( ) { return restTemplate . getForObject ( build ( ) . toString ( ) , type ) ; } } package org . springframework . social . google . api ; package org . springframework . social . google . api . plus . comment . impl ; import org . springframework . social . google . api . impl . AbstractGoogleApiOperations ; import org . springframework . social . google . api . plus . comment . Comment ; import org . springframework . social . google . api . plus . comment . CommentOperations ; import org . springframework . social . google . api . plus . comment . CommentsPage ; import org . springframework . web . client . RestTemplate ; public class CommentTemplate extends AbstractGoogleApiOperations implements CommentOperations { private static final String COMMENTS_URL = "" ; private static final String ACTIVITIES_URL = "" ; private static final String COMMENTS = "" ; public CommentTemplate ( RestTemplate restTemplate , boolean isAuthorized ) { super ( restTemplate , isAuthorized ) ; } @ Override public Comment getComment ( String id ) { return getEntity ( COMMENTS_URL + id , Comment . class ) ; } @ Override public CommentsPage getComments ( String activityId , String pageToken ) { return getEntity ( ACTIVITIES_URL + activityId + COMMENTS , CommentsPage . class ) ; } } package org . springframework . social . google . api . plus . comment ; import java . util . Date ; import org . codehaus . jackson . annotate . JsonCreator ; import org . codehaus . jackson . annotate . JsonProperty ; import org . springframework . social . google . api . plus . person . Person ; public class Comment { public static class CommentObject { private final String content ; @ JsonCreator public CommentObject ( @ JsonProperty ( "" ) String content ) { this . content = content ; } } private final String id ; private final Date published ; private final Date updated ; private final String content ; private final Person actor ; @ JsonCreator public Comment ( @ JsonProperty ( "" ) String id , @ JsonProperty ( "" ) Date published , @ JsonProperty ( "" ) Date updated , @ JsonProperty ( "" ) CommentObject object , @ JsonProperty ( "" ) Person actor ) { this . id = id ; this . published = published ; this . updated = updated ; this . content = object . content ; this . actor = actor ; } public String getId ( ) { return id ; } public Date getPublished ( ) { return published ; } public Date getUpdated ( ) { return updated ; } public String getContent ( ) { return content ; } public Person getActor ( ) { return actor ; } } package org . springframework . social . google . api . plus . comment ; import org . springframework . social . google . api . query . ApiPage ; public class CommentsPage extends ApiPage < Comment > { } package org . springframework . social . google . api . plus . comment ; public interface CommentOperations { Comment getComment ( String id ) ; CommentsPage getComments ( String activityId , String pageToken ) ; } package org . springframework . social . google . api . plus . person ; public class Phone { private String type ; private String value ; @ Override public String toString ( ) { return value ; } public String getType ( ) { return type ; } public String getValue ( ) { return value ; } } package org . springframework . social . google . api . plus . person ; public class Email { private String type ; private String value ; private boolean primary ; @ Override public String toString ( ) { return value ; } public String getType ( ) { return type ; } public String getValue ( ) { return value ; } public boolean isPrimary ( ) { return primary ; } } package org . springframework . social . google . api . plus . person . impl ; import static org . springframework . social . google . api . plus . person . impl . PersonTemplate . FEED_PREFIX ; import static org . springframework . util . StringUtils . hasText ; import org . springframework . social . google . api . plus . person . ContactQueryBuilder ; import org . springframework . social . google . api . plus . person . PeoplePage ; import org . springframework . social . google . api . query . impl . QueryBuilderImpl ; import org . springframework . web . client . RestTemplate ; public class ContactQueryBuilderImpl extends QueryBuilderImpl < ContactQueryBuilder , PeoplePage > implements ContactQueryBuilder { private static final int DEFAULT_PAGE_SIZE = ; private final RestTemplate restTemplate ; private final OAuth2Draft10RequestInterceptor oauth2Draft10RequestInterceptor = new OAuth2Draft10RequestInterceptor ( ) ; private int index ; private String group = "" ; public ContactQueryBuilderImpl ( RestTemplate restTemplate ) { this . restTemplate = restTemplate ; maxResults = DEFAULT_PAGE_SIZE ; } @ Override public ContactQueryBuilder fromGroup ( String group ) { this . group = group ; return this ; } @ Override protected StringBuilder build ( ) { StringBuilder sb = new StringBuilder ( FEED_PREFIX ) . append ( group ) . append ( "" ) ; appendQueryParam ( sb , "" , index ) ; appendQueryParam ( sb , "" , maxResults ) ; return sb ; } @ Override public ContactQueryBuilder fromPage ( String pageToken ) { index = hasText ( pageToken ) ? index = Integer . parseInt ( pageToken ) : ; return this ; } @ Override public PeoplePage getPage ( ) { restTemplate . getInterceptors ( ) . add ( oauth2Draft10RequestInterceptor ) ; ContactsResponse response = restTemplate . getForObject ( build ( ) . toString ( ) , ContactsResponse . class ) ; restTemplate . getInterceptors ( ) . remove ( oauth2Draft10RequestInterceptor ) ; String nextPageToken = response . getTotal ( ) < index + maxResults ? null : String . valueOf ( index + maxResults ) ; return new PeoplePage ( response . getItems ( ) , nextPageToken ) ; } } package org . springframework . social . google . api . plus . person . impl ; import java . util . List ; import org . codehaus . jackson . annotate . JsonProperty ; import org . springframework . social . google . api . plus . person . Person ; public class ContactsResponse { private int startIndex ; @ JsonProperty ( "" ) private int total ; @ JsonProperty ( "" ) private List < Person > items ; public int getStartIndex ( ) { return startIndex ; } public int getTotal ( ) { return total ; } public List < Person > getItems ( ) { return items ; } } package org . springframework . social . google . api . plus . person . impl ; import org . springframework . social . google . api . plus . person . Person ; public class ContactEntryWrapper { private Person entry ; public Person getEntry ( ) { return entry ; } } package org . springframework . social . google . api . plus . person . impl ; import org . springframework . social . google . api . impl . AbstractGoogleApiOperations ; import org . springframework . social . google . api . plus . person . ContactQueryBuilder ; import org . springframework . social . google . api . plus . person . PeoplePage ; import org . springframework . social . google . api . plus . person . Person ; import org . springframework . social . google . api . plus . person . PersonOperations ; import org . springframework . social . google . api . plus . person . PersonQueryBuilder ; import org . springframework . web . client . RestTemplate ; public class PersonTemplate extends AbstractGoogleApiOperations implements PersonOperations { static final String PEOPLE_SEARCH_URL = "" ; static final String PEOPLE_URL = PEOPLE_SEARCH_URL + '' ; private static final String ACTIVITIES_URL = "" ; private static final String PLUSONERS = "" ; private static final String RESHARERS = "" ; static final String FEED_PREFIX = "" ; static final String CONTACTS_FEED = FEED_PREFIX + "" ; public PersonTemplate ( RestTemplate restTemplate , boolean isAuthorized ) { super ( restTemplate , isAuthorized ) ; } @ Override public Person getPerson ( String id ) { return getEntity ( PEOPLE_URL + id , Person . class ) ; } @ Override public Person getContact ( String id ) { return getEntity ( CONTACTS_FEED + id + "" , ContactEntryWrapper . class ) . getEntry ( ) ; } @ Override public Person getGoogleProfile ( ) { return getPerson ( "" ) ; } @ Override public PersonQueryBuilder personQuery ( ) { return new PersonQueryBuilderImpl ( restTemplate ) ; } @ Override public PeoplePage searchPeople ( String query , String pageToken ) { return personQuery ( ) . searchFor ( query ) . fromPage ( pageToken ) . getPage ( ) ; } @ Override public PeoplePage getActivityPlusOners ( String activityId , String pageToken ) { return getEntity ( ACTIVITIES_URL + activityId + PLUSONERS , PeoplePage . class ) ; } @ Override public PeoplePage getActivityResharers ( String activityId , String pageToken ) { return getEntity ( ACTIVITIES_URL + activityId + RESHARERS , PeoplePage . class ) ; } @ Override public ContactQueryBuilder contactQuery ( ) { return new ContactQueryBuilderImpl ( restTemplate ) ; } } package org . springframework . social . google . api . plus . person . impl ; import java . io . IOException ; import org . springframework . http . HttpHeaders ; import org . springframework . http . HttpRequest ; import org . springframework . http . client . ClientHttpRequestExecution ; import org . springframework . http . client . ClientHttpRequestInterceptor ; import org . springframework . http . client . ClientHttpResponse ; import org . springframework . social . support . HttpRequestDecorator ; class OAuth2Draft10RequestInterceptor implements ClientHttpRequestInterceptor { private static final String AUTHORIZATION = "" ; @ Override public ClientHttpResponse intercept ( HttpRequest request , byte [ ] body , ClientHttpRequestExecution execution ) throws IOException { HttpRequest protectedResourceRequest = new HttpRequestDecorator ( request ) ; HttpHeaders headers = protectedResourceRequest . getHeaders ( ) ; String authorization = headers . getFirst ( AUTHORIZATION ) ; authorization = authorization . replaceFirst ( "" , "" ) ; headers . set ( AUTHORIZATION , authorization ) ; return execution . execute ( protectedResourceRequest , body ) ; } } package org . springframework . social . google . api . plus . person . impl ; import static org . springframework . social . google . api . plus . person . impl . PersonTemplate . PEOPLE_SEARCH_URL ; import org . springframework . social . google . api . plus . person . PeoplePage ; import org . springframework . social . google . api . plus . person . PersonQueryBuilder ; import org . springframework . social . google . api . query . impl . ApiQueryBuilderImpl ; import org . springframework . web . client . RestTemplate ; public class PersonQueryBuilderImpl extends ApiQueryBuilderImpl < PersonQueryBuilder , PeoplePage > implements PersonQueryBuilder { private String text ; public PersonQueryBuilderImpl ( RestTemplate restTemplate ) { super ( PEOPLE_SEARCH_URL , PeoplePage . class , restTemplate ) ; } @ Override public PersonQueryBuilder searchFor ( String text ) { this . text = text ; return this ; } @ Override protected StringBuilder build ( ) { StringBuilder sb = super . build ( ) ; appendQueryParam ( sb , "" , text ) ; return sb ; } } package org . springframework . social . google . api . plus . person ; import org . springframework . social . google . api . query . ApiQueryBuilder ; import org . springframework . social . google . api . query . QueryBuilder ; public interface PersonQueryBuilder extends ApiQueryBuilder < PersonQueryBuilder , PeoplePage > { PersonQueryBuilder searchFor ( String text ) ; } package org . springframework . social . google . api . plus . person ; public class Organization { private String name ; private String title ; private String type ; @ Override public String toString ( ) { StringBuilder sb = new StringBuilder ( name ) ; if ( title != null ) { sb . append ( "" ) . append ( title ) ; } if ( type != null ) { sb . append ( "" ) . append ( type ) . append ( '' ) ; } return sb . toString ( ) ; } public String getName ( ) { return name ; } public String getTitle ( ) { return title ; } public String getType ( ) { return type ; } } package org . springframework . social . google . api . plus . person ; public class ProfileURL { private String value ; private String type ; @ Override public String toString ( ) { if ( type == null ) { return value ; } return new StringBuilder ( value ) . append ( "" ) . append ( type ) . append ( '' ) . toString ( ) ; } public String getValue ( ) { return value ; } public String getType ( ) { return type ; } } package org . springframework . social . google . api . plus . person ; import org . springframework . social . google . api . query . ApiQueryBuilder ; import org . springframework . social . google . api . query . QueryBuilder ; public interface ContactQueryBuilder extends ApiQueryBuilder < ContactQueryBuilder , PeoplePage > { ContactQueryBuilder fromGroup ( String group ) ; } package org . springframework . social . google . api . plus . person ; public interface PersonOperations { Person getPerson ( String id ) ; Person getContact ( String id ) ; Person getGoogleProfile ( ) ; PeoplePage searchPeople ( String query , String pageToken ) ; PeoplePage getActivityPlusOners ( String activityId , String pageToken ) ; PeoplePage getActivityResharers ( String activityId , String pageToken ) ; PersonQueryBuilder personQuery ( ) ; ContactQueryBuilder contactQuery ( ) ; } package org . springframework . social . google . api . plus . person ; public class Address { private String type ; private String streetAddress ; private String locality ; private String region ; private String postalCode ; private String country ; private String formatted ; @ Override public String toString ( ) { return formatted ; } public String getType ( ) { return type ; } public String getStreetAddress ( ) { return streetAddress ; } public String getLocality ( ) { return locality ; } public String getRegion ( ) { return region ; } public String getPostalCode ( ) { return postalCode ; } public String getCountry ( ) { return country ; } public String getFormatted ( ) { return formatted ; } } package org . springframework . social . google . api . plus . person ; public class PlaceLived { private String value ; @ Override public String toString ( ) { return value ; } public String getValue ( ) { return value ; } } package org . springframework . social . google . api . plus . person ; import java . util . Date ; import java . util . List ; import org . codehaus . jackson . annotate . JsonProperty ; public class Person { private static class Name { @ JsonProperty String givenName ; @ JsonProperty String familyName ; } public static class Image { @ JsonProperty private String url ; } @ JsonProperty private String kind ; private String id ; @ JsonProperty private Name name ; private String displayName ; @ JsonProperty private Image image ; @ JsonProperty private String thumbnailUrl ; private Date birthday ; private String gender ; private String aboutMe ; private String relationshipStatus ; private List < ProfileURL > urls ; private List < Organization > organizations ; private List < PlaceLived > placesLived ; private List < Email > emails ; private List < Phone > phoneNumbers ; private List < Address > addresses ; @ Override public String toString ( ) { return displayName ; } public boolean isGooglePlusProfile ( ) { if ( kind != null ) { return true ; } if ( urls != null ) { for ( ProfileURL url : urls ) { if ( "" . equals ( url . getType ( ) ) ) { return true ; } } } return false ; } public boolean isContactWithProfile ( ) { return kind == null && isGooglePlusProfile ( ) ; } public String getId ( ) { return id ; } public String getGivenName ( ) { return name == null ? null : name . givenName ; } public String getFamilyName ( ) { return name == null ? null : name . familyName ; } public String getDisplayName ( ) { return displayName ; } public String getImageUrl ( ) { if ( thumbnailUrl != null ) { return thumbnailUrl ; } if ( image != null ) { return image . url ; } return null ; } public Date getBirthday ( ) { return birthday ; } public String getGender ( ) { return gender ; } public String getAboutMe ( ) { return aboutMe ; } public String getRelationshipStatus ( ) { return relationshipStatus ; } public List < ProfileURL > getUrls ( ) { return urls ; } public List < Organization > getOrganizations ( ) { return organizations ; } public List < PlaceLived > getPlacesLived ( ) { return placesLived ; } public List < Email > getEmails ( ) { return emails ; } public List < Phone > getPhoneNumbers ( ) { return phoneNumbers ; } public List < Address > getAddresses ( ) { return addresses ; } } package org . springframework . social . google . api . plus . person ; package org . springframework . social . google . api . plus . person ; import java . util . List ; import org . springframework . social . google . api . query . ApiPage ; public class PeoplePage extends ApiPage < Person > { public PeoplePage ( ) { } public PeoplePage ( List < ? extends Person > items , String nextPageToken ) { super ( items , nextPageToken ) ; } } package org . springframework . social . google . api . plus ; package org . springframework . social . google . api . plus . activity . impl ; import org . springframework . social . google . api . impl . AbstractGoogleApiOperations ; import org . springframework . social . google . api . plus . activity . ActivitiesPage ; import org . springframework . social . google . api . plus . activity . Activity ; import org . springframework . social . google . api . plus . activity . ActivityOperations ; import org . springframework . social . google . api . plus . activity . ActivityQueryBuilder ; import org . springframework . web . client . RestTemplate ; public class ActivityTemplate extends AbstractGoogleApiOperations implements ActivityOperations { private static final String PEOPLE_URL = "" ; private static final String ACTIVITIES_PUBLIC = "" ; private static final String ACTIVITIES_URL = "" ; public ActivityTemplate ( RestTemplate restTemplate , boolean isAuthorized ) { super ( restTemplate , isAuthorized ) ; } @ Override public Activity getActivity ( String id ) { return getEntity ( ACTIVITIES_URL + id , Activity . class ) ; } @ Override public ActivitiesPage getActivitiesPage ( String userId , String pageToken ) { StringBuilder sb = new StringBuilder ( PEOPLE_URL ) . append ( userId ) . append ( ACTIVITIES_PUBLIC ) ; if ( pageToken != null ) { sb . append ( "" ) . append ( pageToken ) ; } return getEntity ( sb . toString ( ) , ActivitiesPage . class ) ; } @ Override public ActivitiesPage getActivitiesPage ( String userId ) { return getActivitiesPage ( userId , null ) ; } @ Override public ActivityQueryBuilder activityQuery ( ) { return new ActivityQueryBuilderImpl ( restTemplate ) ; } } package org . springframework . social . google . api . plus . activity . impl ; import org . springframework . social . google . api . plus . activity . ActivitiesOrder ; import org . springframework . social . google . api . plus . activity . ActivitiesPage ; import org . springframework . social . google . api . plus . activity . ActivityQueryBuilder ; import org . springframework . social . google . api . query . impl . ApiQueryBuilderImpl ; import org . springframework . web . client . RestTemplate ; public class ActivityQueryBuilderImpl extends ApiQueryBuilderImpl < ActivityQueryBuilder , ActivitiesPage > implements ActivityQueryBuilder { private String text ; private ActivitiesOrder order ; public ActivityQueryBuilderImpl ( RestTemplate restTemplate ) { super ( "" , ActivitiesPage . class , restTemplate ) ; } @ Override public ActivityQueryBuilder searchFor ( String text ) { this . text = text ; return this ; } @ Override public ActivityQueryBuilder orderBy ( ActivitiesOrder order ) { this . order = order ; return this ; } @ Override protected StringBuilder build ( ) { StringBuilder sb = super . build ( ) ; appendQueryParam ( sb , "" , text ) ; appendQueryParam ( sb , "" , order ) ; return sb ; } } package org . springframework . social . google . api . plus . activity ; import org . codehaus . jackson . annotate . JsonProperty ; import org . codehaus . jackson . annotate . JsonTypeName ; @ JsonTypeName ( "" ) public class Photo extends Attachment { @ JsonProperty private PreviewImage fullImage ; public String getFullImageUrl ( ) { return fullImage . url ; } public String getFullImageContentType ( ) { return fullImage . type ; } public int getFullImageHeight ( ) { return fullImage . height ; } public int getFullImageWidth ( ) { return fullImage . width ; } } package org . springframework . social . google . api . plus . activity ; import org . codehaus . jackson . annotate . JsonTypeName ; @ JsonTypeName ( "" ) public class Article extends Attachment { } package org . springframework . social . google . api . plus . activity ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import org . codehaus . jackson . annotate . JsonProperty ; import org . springframework . social . google . api . plus . person . Person ; public class Activity { public static class ActivityObject { public static class TotalItemsWrapper { @ JsonProperty private int totalItems ; } private String content ; @ JsonProperty private List < Attachment > attachments ; @ JsonProperty private TotalItemsWrapper plusoners ; @ JsonProperty private TotalItemsWrapper resharers ; @ JsonProperty private TotalItemsWrapper replies ; } private String id ; private String title ; private Date published ; private Date updated ; private String url ; @ JsonProperty private Person actor ; @ JsonProperty private ActivityObject object ; public String getId ( ) { return id ; } public String getTitle ( ) { return title ; } public Date getPublished ( ) { return published ; } public Date getUpdated ( ) { return updated ; } public String getUrl ( ) { return url ; } public Person getActor ( ) { return actor ; } public String getContent ( ) { return object . content ; } public List < Attachment > getAttachments ( ) { return object . attachments == null ? new ArrayList < Attachment > ( ) : object . attachments ; } public int getPlusOners ( ) { return object . plusoners . totalItems ; } public int getResharers ( ) { return object . resharers . totalItems ; } public int getReplies ( ) { return object . replies . totalItems ; } } package org . springframework . social . google . api . plus . activity ; import org . springframework . social . google . api . query . ApiQueryBuilder ; import org . springframework . social . google . api . query . QueryBuilder ; public interface ActivityQueryBuilder extends ApiQueryBuilder < ActivityQueryBuilder , ActivitiesPage > { ActivityQueryBuilder searchFor ( String text ) ; ActivityQueryBuilder orderBy ( ActivitiesOrder order ) ; } package org . springframework . social . google . api . plus . activity ; public enum ActivitiesOrder { BEST , RECENT } package org . springframework . social . google . api . plus . activity ; import org . codehaus . jackson . annotate . JsonTypeName ; @ JsonTypeName ( "" ) public class Video extends Attachment { } package org . springframework . social . google . api . plus . activity ; import org . springframework . social . google . api . query . ApiPage ; public class ActivitiesPage extends ApiPage < Activity > { } package org . springframework . social . google . api . plus . activity ; package org . springframework . social . google . api . plus . activity ; public interface ActivityOperations { Activity getActivity ( String id ) ; ActivitiesPage getActivitiesPage ( String userId , String pageToken ) ; ActivitiesPage getActivitiesPage ( String userId ) ; ActivityQueryBuilder activityQuery ( ) ; } package org . springframework . social . google . api . plus . activity ; import org . codehaus . jackson . annotate . JsonProperty ; import org . codehaus . jackson . annotate . JsonSubTypes ; import org . codehaus . jackson . annotate . JsonSubTypes . Type ; import org . codehaus . jackson . annotate . JsonTypeInfo ; import org . codehaus . jackson . annotate . JsonTypeInfo . As ; import org . codehaus . jackson . annotate . JsonTypeInfo . Id ; @ JsonTypeInfo ( property = "" , include = As . PROPERTY , use = Id . NAME ) @ JsonSubTypes ( { @ Type ( Article . class ) , @ Type ( Photo . class ) , @ Type ( Video . class ) , @ Type ( Album . class ) } ) public abstract class Attachment { public static class PreviewImage { @ JsonProperty protected String url ; @ JsonProperty protected String type ; @ JsonProperty protected int height ; @ JsonProperty protected int width ; } private String url ; private String displayName ; private String content ; @ JsonProperty private PreviewImage image ; public String getUrl ( ) { return url ; } public String getDisplayName ( ) { return displayName ; } public String getContent ( ) { return content ; } public String getPreviewImageUrl ( ) { return image == null ? null : image . url ; } public String getPreviewImageContentType ( ) { return image == null ? null : image . type ; } } package org . springframework . social . google . api . plus . activity ; import org . codehaus . jackson . annotate . JsonTypeName ; @ JsonTypeName ( "" ) public class Album extends Attachment { } package org . springframework . social . google . api ; import org . springframework . social . ApiBinding ; import org . springframework . social . google . api . impl . GoogleTemplate ; import org . springframework . social . google . api . legacyprofile . LegacyProfileOperations ; import org . springframework . social . google . api . plus . activity . ActivityOperations ; import org . springframework . social . google . api . plus . comment . CommentOperations ; import org . springframework . social . google . api . plus . person . PersonOperations ; import org . springframework . social . google . api . tasks . TaskOperations ; public interface Google extends ApiBinding { LegacyProfileOperations userOperations ( ) ; PersonOperations personOperations ( ) ; ActivityOperations activityOperations ( ) ; CommentOperations commentOperations ( ) ; TaskOperations taskOperations ( ) ; void applyAuthentication ( Object client ) ; } package org . springframework . social . google . api ; import static org . springframework . util . StringUtils . hasText ; public abstract class ApiEntity { private String id ; protected ApiEntity ( ) { } protected ApiEntity ( String id ) { this . id = hasText ( id ) ? id : null ; } public String getId ( ) { return id ; } } package org . springframework . social . google . api . impl ; import static java . util . Collections . singletonList ; import static org . codehaus . jackson . map . DeserializationConfig . Feature . FAIL_ON_UNKNOWN_PROPERTIES ; import static org . codehaus . jackson . map . SerializationConfig . Feature . WRITE_DATES_AS_TIMESTAMPS ; import static org . codehaus . jackson . map . annotate . JsonSerialize . Inclusion . NON_NULL ; import static org . springframework . http . MediaType . APPLICATION_ATOM_XML ; import static org . springframework . util . ReflectionUtils . findMethod ; import static org . springframework . util . ReflectionUtils . invokeMethod ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . List ; import javax . xml . transform . Source ; import org . codehaus . jackson . map . ObjectMapper ; import org . springframework . http . converter . ByteArrayHttpMessageConverter ; import org . springframework . http . converter . HttpMessageConverter ; import org . springframework . http . converter . json . MappingJacksonHttpMessageConverter ; import org . springframework . http . converter . xml . SourceHttpMessageConverter ; import org . springframework . social . google . api . Google ; import org . springframework . social . google . api . legacyprofile . LegacyProfileOperations ; import org . springframework . social . google . api . legacyprofile . impl . UserTemplate ; import org . springframework . social . google . api . plus . activity . ActivityOperations ; import org . springframework . social . google . api . plus . activity . impl . ActivityTemplate ; import org . springframework . social . google . api . plus . comment . CommentOperations ; import org . springframework . social . google . api . plus . comment . impl . CommentTemplate ; import org . springframework . social . google . api . plus . person . PersonOperations ; import org . springframework . social . google . api . plus . person . impl . PersonTemplate ; import org . springframework . social . google . api . tasks . TaskOperations ; import org . springframework . social . google . api . tasks . impl . TaskTemplate ; import org . springframework . social . oauth2 . AbstractOAuth2ApiBinding ; import org . springframework . social . oauth2 . OAuth2Version ; public class GoogleTemplate extends AbstractOAuth2ApiBinding implements Google { private String accessToken ; private LegacyProfileOperations userOperations ; private PersonOperations profileOperations ; private ActivityOperations activityOperations ; private CommentOperations commentOperations ; private TaskOperations taskOperations ; public GoogleTemplate ( ) { initialize ( ) ; } public GoogleTemplate ( String accessToken ) { super ( accessToken ) ; this . accessToken = accessToken ; initialize ( ) ; } private void initialize ( ) { userOperations = new UserTemplate ( getRestTemplate ( ) , isAuthorized ( ) ) ; profileOperations = new PersonTemplate ( getRestTemplate ( ) , isAuthorized ( ) ) ; activityOperations = new ActivityTemplate ( getRestTemplate ( ) , isAuthorized ( ) ) ; commentOperations = new CommentTemplate ( getRestTemplate ( ) , isAuthorized ( ) ) ; taskOperations = new TaskTemplate ( getRestTemplate ( ) , isAuthorized ( ) ) ; } @ Override protected List < HttpMessageConverter < ? > > getMessageConverters ( ) { MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter ( ) ; ObjectMapper objectMapper = new ObjectMapper ( ) ; objectMapper . configure ( FAIL_ON_UNKNOWN_PROPERTIES , false ) ; objectMapper . configure ( WRITE_DATES_AS_TIMESTAMPS , false ) ; objectMapper . setSerializationInclusion ( NON_NULL ) ; jsonConverter . setObjectMapper ( objectMapper ) ; SourceHttpMessageConverter < Source > sourceConverter = new SourceHttpMessageConverter < Source > ( ) ; sourceConverter . setSupportedMediaTypes ( singletonList ( APPLICATION_ATOM_XML ) ) ; List < HttpMessageConverter < ? > > messageConverters = new ArrayList < HttpMessageConverter < ? > > ( ) ; messageConverters . add ( jsonConverter ) ; messageConverters . add ( sourceConverter ) ; messageConverters . add ( new ByteArrayHttpMessageConverter ( ) ) ; return messageConverters ; } @ Override protected OAuth2Version getOAuth2Version ( ) { return OAuth2Version . BEARER ; } @ Override public LegacyProfileOperations userOperations ( ) { return userOperations ; } @ Override public PersonOperations personOperations ( ) { return profileOperations ; } @ Override public ActivityOperations activityOperations ( ) { return activityOperations ; } @ Override public CommentOperations commentOperations ( ) { return commentOperations ; } @ Override public TaskOperations taskOperations ( ) { return taskOperations ; } @ Override public void applyAuthentication ( Object client ) { Method setHeaders = findMethod ( client . getClass ( ) , "" , String . class , String . class ) ; invokeMethod ( setHeaders , client , "" , getOAuth2Version ( ) . getAuthorizationHeaderValue ( accessToken ) ) ; } } package org . springframework . social . google . api . impl ; import static org . springframework . http . HttpMethod . POST ; import static org . springframework . http . HttpMethod . PUT ; import static org . springframework . util . StringUtils . hasText ; import org . springframework . http . HttpEntity ; import org . springframework . http . HttpMethod ; import org . springframework . http . ResponseEntity ; import org . springframework . social . MissingAuthorizationException ; import org . springframework . social . google . api . ApiEntity ; import org . springframework . web . client . RestTemplate ; public abstract class AbstractGoogleApiOperations { protected final RestTemplate restTemplate ; protected final boolean isAuthorized ; protected AbstractGoogleApiOperations ( RestTemplate restTemplate , boolean isAuthorized ) { this . restTemplate = restTemplate ; this . isAuthorized = isAuthorized ; } protected void requireAuthorization ( ) { if ( ! isAuthorized ) { throw new MissingAuthorizationException ( ) ; } } protected < T > T getEntity ( String url , Class < T > type ) { return restTemplate . getForObject ( url , type ) ; } protected < T extends ApiEntity > T saveEntity ( String baseUrl , T entity ) { String url ; HttpMethod method ; if ( hasText ( entity . getId ( ) ) ) { url = baseUrl + '' + entity . getId ( ) ; method = PUT ; } else { url = baseUrl ; method = POST ; } @ SuppressWarnings ( "" ) ResponseEntity < T > response = restTemplate . exchange ( url , method , new HttpEntity < T > ( entity ) , ( Class < T > ) entity . getClass ( ) ) ; return response . getBody ( ) ; } protected void deleteEntity ( String baseUrl , ApiEntity entity ) { restTemplate . delete ( baseUrl + '' + entity . getId ( ) ) ; } } package org . springframework . social . google . api . impl ; import java . io . IOException ; import org . codehaus . jackson . JsonParser ; import org . codehaus . jackson . JsonProcessingException ; import org . codehaus . jackson . map . DeserializationContext ; import org . codehaus . jackson . map . JsonDeserializer ; public abstract class ApiEnumDeserializer < T extends Enum < ? > > extends JsonDeserializer < T > { private final Class < T > type ; public ApiEnumDeserializer ( Class < T > type ) { this . type = type ; } @ Override public T deserialize ( JsonParser jp , DeserializationContext ctxt ) throws IOException , JsonProcessingException { String camelCase = jp . getText ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = ; i < camelCase . length ( ) ; i ++ ) { char c = camelCase . charAt ( i ) ; if ( Character . isUpperCase ( c ) ) { sb . append ( '' ) . append ( c ) ; } else { sb . append ( Character . toUpperCase ( c ) ) ; } } @ SuppressWarnings ( { "" , "" } ) T value = ( T ) Enum . valueOf ( ( Class ) type , sb . toString ( ) ) ; return value ; } } package org . springframework . social . google . api . impl ; import java . io . IOException ; import org . codehaus . jackson . JsonGenerator ; import org . codehaus . jackson . JsonProcessingException ; import org . codehaus . jackson . map . JsonSerializer ; import org . codehaus . jackson . map . SerializerProvider ; public class ApiEnumSerializer extends JsonSerializer < Enum < ? > > { @ Override public void serialize ( Enum < ? > value , JsonGenerator jgen , SerializerProvider provider ) throws IOException , JsonProcessingException { String underscored = value . name ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = ; i < underscored . length ( ) ; i ++ ) { char c = underscored . charAt ( i ) ; if ( c == '' ) { sb . append ( Character . toUpperCase ( underscored . charAt ( ++ i ) ) ) ; } else { sb . append ( Character . toLowerCase ( c ) ) ; } } jgen . writeString ( sb . toString ( ) ) ; } } import java . awt . BorderLayout ; import java . awt . EventQueue ; import javax . swing . JFrame ; import javax . swing . JPanel ; import javax . swing . border . Border ; import javax . swing . border . EmptyBorder ; import javax . swing . text . JTextComponent ; import javax . swing . BoxLayout ; import javax . swing . JTextArea ; import java . awt . datatransfer . DataFlavor ; import java . awt . dnd . DnDConstants ; import java . awt . dnd . DropTarget ; import java . awt . dnd . DropTargetDropEvent ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . io . BufferedReader ; import java . io . File ; import java . util . Arrays ; import java . util . List ; import net . miginfocom . swing . MigLayout ; import javax . swing . BorderFactory ; import javax . swing . ImageIcon ; import javax . swing . JOptionPane ; import javax . swing . JScrollPane ; import javax . swing . JLabel ; import javax . swing . JButton ; import javax . swing . ScrollPaneConstants ; import java . awt . FlowLayout ; import java . awt . GridLayout ; public class MultiUploader extends JFrame { private JPanel contentPane ; private Upload upload ; private JTextArea linkBox ; private JTextArea pathBox ; private MultiUploaderThread mut ; private JButton btnUpload ; private int total_uploads = ; private int current_upload = ; private JTextArea deletionBox ; public MultiUploader ( ) { setTitle ( "" ) ; setDefaultCloseOperation ( JFrame . DISPOSE_ON_CLOSE ) ; setBounds ( , , , ) ; contentPane = new JPanel ( ) ; contentPane . setBorder ( new EmptyBorder ( , , , ) ) ; contentPane . setLayout ( new BorderLayout ( , ) ) ; setContentPane ( contentPane ) ; ImageIcon ii2 = new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ; this . setIconImage ( ii2 . getImage ( ) ) ; JPanel panel = new JPanel ( ) ; contentPane . add ( panel , BorderLayout . CENTER ) ; panel . setLayout ( new MigLayout ( "" , "" , "" ) ) ; JScrollPane scrollPane = new JScrollPane ( ) ; scrollPane . setVerticalScrollBarPolicy ( ScrollPaneConstants . VERTICAL_SCROLLBAR_ALWAYS ) ; scrollPane . setBorder ( BorderFactory . createTitledBorder ( "" ) ) ; panel . add ( scrollPane , "" ) ; pathBox = new JTextArea ( ) ; pathBox . setEditable ( false ) ; scrollPane . setViewportView ( pathBox ) ; pathBox . setDropTarget ( new DropTarget ( ) { public synchronized void drop ( DropTargetDropEvent evt ) { try { evt . acceptDrop ( DnDConstants . ACTION_LINK ) ; List < File > droppedFiles = ( List < File > ) evt . getTransferable ( ) . getTransferData ( DataFlavor . javaFileListFlavor ) ; for ( File file : droppedFiles ) { pathBox . setText ( file . getPath ( ) + "" + pathBox . getText ( ) ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } ) ; JButton btnClearAll = new JButton ( "" ) ; btnClearAll . addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent arg0 ) { pathBox . setText ( "" ) ; deletionBox . setText ( "" ) ; linkBox . setText ( "" ) ; } } ) ; panel . add ( btnClearAll , "" ) ; btnUpload = new JButton ( "" ) ; btnUpload . addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { if ( ! pathBox . getText ( ) . equals ( "" ) ) { uploadFiles ( ) ; } } } ) ; panel . add ( btnUpload , "" ) ; JPanel panel_1 = new JPanel ( ) ; panel . add ( panel_1 , "" ) ; panel_1 . setLayout ( new GridLayout ( , , , ) ) ; JScrollPane scrollPane_1 = new JScrollPane ( ) ; panel_1 . add ( scrollPane_1 ) ; scrollPane_1 . setVerticalScrollBarPolicy ( ScrollPaneConstants . VERTICAL_SCROLLBAR_ALWAYS ) ; scrollPane_1 . setBorder ( BorderFactory . createTitledBorder ( "" ) ) ; linkBox = new JTextArea ( ) ; scrollPane_1 . setViewportView ( linkBox ) ; linkBox . setEditable ( false ) ; JScrollPane scrollPane_2 = new JScrollPane ( ) ; scrollPane_2 . setVerticalScrollBarPolicy ( ScrollPaneConstants . VERTICAL_SCROLLBAR_ALWAYS ) ; scrollPane_2 . setBorder ( BorderFactory . createTitledBorder ( "" ) ) ; panel_1 . add ( scrollPane_2 ) ; deletionBox = new JTextArea ( ) ; deletionBox . setEditable ( false ) ; scrollPane_2 . setViewportView ( deletionBox ) ; JButton btnCopyallTo = new JButton ( "" ) ; btnCopyallTo . addActionListener ( new ActionListener ( ) { String links = "" ; @ Override public void actionPerformed ( ActionEvent e ) { for ( String link : linkBox . getText ( ) . split ( "" ) ) { if ( link . contains ( "" ) ) links += link + "" ; } upload = new Upload ( ) ; upload . setClipboard ( links ) ; } } ) ; panel . add ( btnCopyallTo , "" ) ; setVisible ( true ) ; } private void uploadFiles ( ) { File file ; disableUploadButton ( ) ; total_uploads = pathBox . getText ( ) . split ( "" ) . length ; for ( String path : pathBox . getText ( ) . split ( "" ) ) { file = new File ( path ) ; String [ ] type = file . getPath ( ) . split ( "" ) ; mut = new MultiUploaderThread ( file , type [ type . length - ] , this ) ; } } public void disableUploadButton ( ) { btnUpload . setEnabled ( false ) ; pathBox . setEnabled ( false ) ; btnUpload . setText ( "" ) ; } public void enableUploadButton ( ) { btnUpload . setEnabled ( true ) ; pathBox . setEnabled ( true ) ; btnUpload . setText ( "" ) ; } public void addLink ( String link ) { current_upload ++ ; linkBox . setText ( link + "" + linkBox . getText ( ) ) ; if ( current_upload == total_uploads ) { enableUploadButton ( ) ; } } public void addDeletionLink ( String link ) { deletionBox . setText ( link + "" + deletionBox . getText ( ) ) ; } } import java . awt . EventQueue ; import javax . swing . JFrame ; import javax . swing . JTabbedPane ; import java . awt . BorderLayout ; import java . awt . GridBagLayout ; import java . awt . GridBagConstraints ; import javax . swing . JPanel ; import java . awt . Toolkit ; import net . miginfocom . swing . MigLayout ; import javax . swing . JLabel ; import javax . swing . JTextField ; import java . awt . Dimension ; import javax . swing . JButton ; import javax . swing . JComboBox ; import javax . swing . DefaultComboBoxModel ; import javax . swing . JFileChooser ; import javax . swing . JSeparator ; import javax . swing . JPasswordField ; import java . awt . Insets ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . PrintWriter ; import java . util . Arrays ; import java . awt . Component ; import javax . swing . JCheckBox ; import javax . swing . JEditorPane ; import javax . swing . text . Document ; import javax . swing . text . html . HTMLEditorKit ; import javax . swing . text . html . StyleSheet ; import javax . swing . JScrollPane ; import javax . swing . SwingConstants ; import java . awt . Font ; import java . awt . Color ; public class Preferences { public JFrame frmPreferences ; private JTextField directoryField ; private JTextField titleField ; private JPasswordField passwordField ; private JTextField userField ; private DataUtils dataUtils = new DataUtils ( ) ; private JComboBox typeBox ; private JButton browseButton ; private JComboBox postAsBox ; private JComboBox privacyBox ; private JComboBox expireBox ; private JComboBox formatBox ; String [ ] formatBoxStrings = new String [ ] ; private JCheckBox chckbxEnableMultisnippetSupport ; public Preferences ( ) { populuateFormatBoxStrings ( ) ; DataDirectory . loadPreferences ( ) ; initialize ( ) ; setPreferences ( ) ; frmPreferences . setVisible ( true ) ; frmPreferences . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent we ) { } } ) ; } private void populuateFormatBoxStrings ( ) { InputStream is = this . getClass ( ) . getResourceAsStream ( "" ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( is ) ) ; String line ; try { int index = ; while ( ( line = in . readLine ( ) ) != null ) { String [ ] temp = line . split ( "" ) ; formatBoxStrings [ index ] = temp [ ] . trim ( ) ; index ++ ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } private void setPreferences ( ) { directoryField . setText ( DataDirectory . CAPTURE_PATH ) ; chckbxEnableMultisnippetSupport . setSelected ( DataDirectory . MULTI_SNIPPET ) ; titleField . setText ( DataDirectory . PASTEBIN_TITLE ) ; typeBox . setSelectedItem ( DataDirectory . PASTEBIN_TYPE ) ; formatBox . setSelectedItem ( DataDirectory . PASTEBIN_FORMAT ) ; expireBox . setSelectedItem ( DataDirectory . PASTEBIN_EXPIRATION ) ; if ( DataDirectory . PASTEBIN_GUEST ) postAsBox . setSelectedIndex ( ) ; else postAsBox . setSelectedIndex ( ) ; privacyBox . setSelectedIndex ( DataDirectory . PASTEBIN_PRIVACY ) ; if ( DataDirectory . PASTEBIN_USERNAME == "" ) { userField . setText ( "" ) ; passwordField . setText ( "" ) ; } else { userField . setText ( DataDirectory . PASTEBIN_USERNAME ) ; passwordField . setText ( DataDirectory . PASTEBIN_PASSWORD ) ; } } public void UpdatePreferencesFile ( ) { System . out . println ( "" ) ; try { PrintWriter out = new PrintWriter ( DataDirectory . dirDataPath + "" ) ; out . println ( "" + getDefaultCapturePath ( ) + "" + "" + getMultiSnippetSupport ( ) + "" + "" + getPastebinTitle ( ) + "" + "" + "" + "" + getFormatCode ( ) + "" + "" + getPastebinExpires ( ) + "" + "" + getPastebinPrivacy ( ) + "" + "" + getPastebinPostAsGuest ( ) + "" + "" + getPastebinUsername ( ) + "" + "" + getPastebinPassword ( ) ) ; out . close ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } DataDirectory . loadPreferences ( ) ; } private void initialize ( ) { frmPreferences = new JFrame ( ) ; frmPreferences . setResizable ( false ) ; frmPreferences . setIconImage ( Toolkit . getDefaultToolkit ( ) . getImage ( Preferences . class . getResource ( "" ) ) ) ; frmPreferences . setTitle ( "" ) ; frmPreferences . setBounds ( , , , ) ; frmPreferences . setDefaultCloseOperation ( JFrame . DISPOSE_ON_CLOSE ) ; frmPreferences . getContentPane ( ) . setLayout ( new MigLayout ( "" , "" , "" ) ) ; JTabbedPane tabbedPane = new JTabbedPane ( JTabbedPane . TOP ) ; frmPreferences . getContentPane ( ) . add ( tabbedPane , "" ) ; JPanel panel_2 = new JPanel ( ) ; tabbedPane . addTab ( "" , null , panel_2 , null ) ; panel_2 . setLayout ( new MigLayout ( "" , "" , "" ) ) ; JLabel lblTestLabel = new JLabel ( "" ) ; panel_2 . add ( lblTestLabel , "" ) ; directoryField = new JTextField ( ) ; directoryField . setPreferredSize ( new Dimension ( , ) ) ; panel_2 . add ( directoryField , "" ) ; directoryField . setColumns ( ) ; directoryField . setText ( System . getProperty ( "" ) + "" ) ; browseButton = new JButton ( "" ) ; browseButton . addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { JFileChooser fc = new JFileChooser ( ) ; fc . setFileSelectionMode ( JFileChooser . DIRECTORIES_ONLY ) ; fc . setSelectedFile ( new File ( DataDirectory . CAPTURE_PATH ) ) ; int option = fc . showOpenDialog ( null ) ; if ( option == JFileChooser . APPROVE_OPTION ) { directoryField . setText ( fc . getSelectedFile ( ) . getPath ( ) ) ; } } } ) ; panel_2 . add ( browseButton , "" ) ; JSeparator separator_3 = new JSeparator ( ) ; panel_2 . add ( separator_3 , "" ) ; JPanel panel_3 = new JPanel ( ) ; tabbedPane . addTab ( "" , null , panel_3 , null ) ; panel_3 . setLayout ( new MigLayout ( "" , "" , "" ) ) ; chckbxEnableMultisnippetSupport = new JCheckBox ( "" ) ; panel_3 . add ( chckbxEnableMultisnippetSupport , "" ) ; JCheckBox penBox = new JCheckBox ( "" ) ; panel_3 . add ( penBox , "" ) ; JSeparator separator_1 = new JSeparator ( ) ; panel_3 . add ( separator_1 , "" ) ; JLabel lblSnippetMode = new JLabel ( "" ) ; panel_3 . add ( lblSnippetMode , "" ) ; JComboBox comboBox = new JComboBox ( ) ; comboBox . setModel ( new DefaultComboBoxModel ( new String [ ] { "" , "" } ) ) ; panel_3 . add ( comboBox , "" ) ; JSeparator separator = new JSeparator ( ) ; panel_3 . add ( separator , "" ) ; JPanel panel_1 = new JPanel ( ) ; tabbedPane . addTab ( "" , null , panel_1 , null ) ; panel_1 . setLayout ( new MigLayout ( "" , "" , "" ) ) ; JLabel lblUploadName = new JLabel ( "" ) ; panel_1 . add ( lblUploadName , "" ) ; titleField = new JTextField ( ) ; titleField . setText ( "" ) ; panel_1 . add ( titleField , "" ) ; titleField . setColumns ( ) ; typeBox = new JComboBox ( ) ; typeBox . setModel ( new DefaultComboBoxModel ( new String [ ] { "" } ) ) ; panel_1 . add ( typeBox , "" ) ; JLabel lblFormat = new JLabel ( "" ) ; panel_1 . add ( lblFormat , "" ) ; formatBox = new JComboBox ( formatBoxStrings ) ; formatBox . setSelectedItem ( "" ) ; panel_1 . add ( formatBox , "" ) ; JLabel lblPublic = new JLabel ( "" ) ; panel_1 . add ( lblPublic , "" ) ; JLabel lblType = new JLabel ( "" ) ; panel_1 . add ( lblType , "" ) ; expireBox = new JComboBox ( ) ; expireBox . setModel ( new DefaultComboBoxModel ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; panel_1 . add ( expireBox , "" ) ; JLabel lblPrivate = new JLabel ( "" ) ; panel_1 . add ( lblPrivate , "" ) ; privacyBox = new JComboBox ( ) ; privacyBox . setModel ( new DefaultComboBoxModel ( new String [ ] { "" , "" , "" } ) ) ; privacyBox . addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { if ( privacyBox . getSelectedItem ( ) . equals ( "" ) ) { postAsBox . setSelectedIndex ( ) ; postAsBox . setEnabled ( false ) ; } else postAsBox . setEnabled ( true ) ; } } ) ; panel_1 . add ( privacyBox , "" ) ; JLabel lblPostAs = new JLabel ( "" ) ; panel_1 . add ( lblPostAs , "" ) ; postAsBox = new JComboBox ( ) ; postAsBox . setModel ( new DefaultComboBoxModel ( new String [ ] { "" , "" } ) ) ; postAsBox . addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent arg0 ) { if ( postAsBox . getSelectedIndex ( ) == ) { userField . setEditable ( false ) ; passwordField . setEditable ( false ) ; } else { userField . setEditable ( true ) ; passwordField . setEditable ( true ) ; } } } ) ; panel_1 . add ( postAsBox , "" ) ; JLabel lblUsername = new JLabel ( "" ) ; panel_1 . add ( lblUsername , "" ) ; userField = new JTextField ( ) ; panel_1 . add ( userField , "" ) ; userField . setColumns ( ) ; JLabel lblPassword = new JLabel ( "" ) ; panel_1 . add ( lblPassword , "" ) ; passwordField = new JPasswordField ( ) ; panel_1 . add ( passwordField , "" ) ; JPanel panel_4 = new JPanel ( ) ; tabbedPane . addTab ( "" , null , panel_4 , null ) ; panel_4 . setLayout ( new MigLayout ( "" , "" , "" ) ) ; JLabel lblGeneral = new JLabel ( "" ) ; lblGeneral . setFont ( new Font ( "" , Font . BOLD , ) ) ; lblGeneral . setVerticalAlignment ( SwingConstants . TOP ) ; panel_4 . add ( lblGeneral , "" ) ; JSeparator separator_2 = new JSeparator ( ) ; panel_4 . add ( separator_2 , "" ) ; JLabel lblEscape = new JLabel ( "" ) ; lblEscape . setForeground ( Color . DARK_GRAY ) ; lblEscape . setFont ( new Font ( "" , Font . BOLD , ) ) ; panel_4 . add ( lblEscape , "" ) ; JLabel lblCancelsCurrentSnippet = new JLabel ( "" ) ; lblCancelsCurrentSnippet . setForeground ( Color . GRAY ) ; lblCancelsCurrentSnippet . setFont ( new Font ( "" , Font . ITALIC , ) ) ; panel_4 . add ( lblCancelsCurrentSnippet , "" ) ; JLabel lblTrayIcondouble = new JLabel ( "" ) ; lblTrayIcondouble . setForeground ( Color . DARK_GRAY ) ; lblTrayIcondouble . setFont ( new Font ( "" , Font . BOLD , ) ) ; panel_4 . add ( lblTrayIcondouble , "" ) ; JLabel lblDoubleClickTo = new JLabel ( "" ) ; lblDoubleClickTo . setForeground ( Color . GRAY ) ; lblDoubleClickTo . setFont ( new Font ( "" , Font . ITALIC , ) ) ; panel_4 . add ( lblDoubleClickTo , "" ) ; JLabel lblHotkeys = new JLabel ( "" ) ; lblHotkeys . setFont ( new Font ( "" , Font . BOLD , ) ) ; panel_4 . add ( lblHotkeys , "" ) ; JSeparator separator_4 = new JSeparator ( ) ; panel_4 . add ( separator_4 , "" ) ; JLabel lblUploadSnippet = new JLabel ( "" ) ; lblUploadSnippet . setForeground ( Color . DARK_GRAY ) ; lblUploadSnippet . setFont ( new Font ( "" , Font . BOLD , ) ) ; panel_4 . add ( lblUploadSnippet , "" ) ; JLabel lblUploadScreenshot = new JLabel ( "" ) ; lblUploadScreenshot . setForeground ( Color . DARK_GRAY ) ; lblUploadScreenshot . setFont ( new Font ( "" , Font . BOLD , ) ) ; panel_4 . add ( lblUploadScreenshot , "" ) ; JLabel lblSaveSnippet = new JLabel ( "" ) ; lblSaveSnippet . setForeground ( Color . DARK_GRAY ) ; lblSaveSnippet . setFont ( new Font ( "" , Font . BOLD , ) ) ; panel_4 . add ( lblSaveSnippet , "" ) ; JLabel lblSaveScreenshot = new JLabel ( "" ) ; lblSaveScreenshot . setForeground ( Color . DARK_GRAY ) ; lblSaveScreenshot . setFont ( new Font ( "" , Font . BOLD , ) ) ; panel_4 . add ( lblSaveScreenshot , "" ) ; JLabel lblCtrlShift = new JLabel ( "" ) ; lblCtrlShift . setForeground ( Color . GRAY ) ; lblCtrlShift . setFont ( new Font ( "" , Font . ITALIC , ) ) ; panel_4 . add ( lblCtrlShift , "" ) ; JLabel lblCtrlShift_1 = new JLabel ( "" ) ; lblCtrlShift_1 . setForeground ( Color . GRAY ) ; lblCtrlShift_1 . setFont ( new Font ( "" , Font . ITALIC , ) ) ; panel_4 . add ( lblCtrlShift_1 , "" ) ; JLabel lblCtrlShift_2 = new JLabel ( "" ) ; lblCtrlShift_2 . setForeground ( Color . GRAY ) ; lblCtrlShift_2 . setFont ( new Font ( "" , Font . ITALIC , ) ) ; panel_4 . add ( lblCtrlShift_2 , "" ) ; JLabel lblCtrlShift_3 = new JLabel ( "" ) ; lblCtrlShift_3 . setForeground ( Color . GRAY ) ; lblCtrlShift_3 . setFont ( new Font ( "" , Font . ITALIC , ) ) ; panel_4 . add ( lblCtrlShift_3 , "" ) ; JPanel panel = new JPanel ( ) ; tabbedPane . addTab ( "" , null , panel , null ) ; panel . setLayout ( new MigLayout ( "" , "" , "" ) ) ; JLabel lblImurData = new JLabel ( "" + dataUtils . getRemainingUploads ( ) + "" ) ; panel . add ( lblImurData , "" ) ; JLabel lblTimeUntilRefresh = new JLabel ( "" + dataUtils . getRefreshTimeMins ( ) + "" ) ; panel . add ( lblTimeUntilRefresh , "" ) ; JLabel label_1 = new JLabel ( "" ) ; label_1 . setAlignmentY ( Component . TOP_ALIGNMENT ) ; panel . add ( label_1 , "" ) ; JButton btnOk = new JButton ( "" ) ; frmPreferences . getContentPane ( ) . add ( btnOk , "" ) ; btnOk . addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent arg0 ) { UpdatePreferencesFile ( ) ; frmPreferences . dispose ( ) ; } } ) ; } public String getDefaultCapturePath ( ) { return directoryField . getText ( ) ; } public String getPastebinTitle ( ) { return titleField . getText ( ) ; } public String getPastebinType ( ) { return typeBox . getSelectedItem ( ) . toString ( ) ; } public String getPastebinExpires ( ) { return expireBox . getSelectedItem ( ) . toString ( ) ; } public int getPastebinPrivacy ( ) { return privacyBox . getSelectedIndex ( ) ; } public boolean getPastebinPostAsGuest ( ) { if ( postAsBox . getSelectedIndex ( ) == ) return true ; else return false ; } public String getPastebinUsername ( ) { if ( userField . getText ( ) . equals ( "" ) ) { return "" ; } else return userField . getText ( ) ; } public String getPastebinPassword ( ) { if ( passwordField . getPassword ( ) == null ) return "" ; else return getPasswordFromChars ( ) ; } private String getPasswordFromChars ( ) { String pass = "" ; for ( int i = ; i < passwordField . getPassword ( ) . length ; i ++ ) pass += passwordField . getPassword ( ) [ i ] ; return pass ; } private Boolean getMultiSnippetSupport ( ) { return chckbxEnableMultisnippetSupport . isSelected ( ) ; } public String getFormatCode ( ) { InputStream is = this . getClass ( ) . getResourceAsStream ( "" ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( is ) ) ; String line ; try { int index = ; while ( ( line = in . readLine ( ) ) != null ) { String [ ] temp = line . split ( "" ) ; if ( temp [ ] . trim ( ) . equals ( formatBox . getSelectedItem ( ) ) ) return temp [ ] . trim ( ) ; index ++ ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } return "" ; } } import java . awt . BasicStroke ; import java . awt . Color ; import java . awt . Cursor ; import java . awt . Dimension ; import java . awt . Font ; import java . awt . Graphics ; import java . awt . Graphics2D ; import java . awt . Image ; import java . awt . MouseInfo ; import java . awt . Point ; import java . awt . Rectangle ; import java . awt . Robot ; import java . awt . Toolkit ; import java . awt . TrayIcon ; import java . awt . event . KeyEvent ; import java . awt . event . KeyListener ; import java . awt . event . MouseEvent ; import java . awt . event . MouseListener ; import java . awt . event . MouseMotionListener ; import java . awt . geom . Rectangle2D ; import java . awt . image . BufferedImage ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import javax . imageio . ImageIO ; import javax . swing . ImageIcon ; import javax . swing . JFileChooser ; import javax . swing . JPanel ; class OverlayPanel extends JPanel implements MouseListener , MouseMotionListener , KeyListener { private static final long serialVersionUID = - ; BufferedImage image ; Upload upload ; int scW , scH ; Tray tray ; boolean saveLocally , isSnippet ; Toolkit toolkit ; File savLoc ; Color overlayColor = new Color ( , , , ) , boundingColor = new Color ( , , ) ; Rectangle2D selection ; Point startPoint = new Point ( ) ; Point endPoint = new Point ( ) ; int mx , my ; ArrayList < Point > startPointList = new ArrayList < Point > ( ) ; ArrayList < Point > endPointList = new ArrayList < Point > ( ) ; float divider_width = ; Color divider_color = Color . black ; Font font = new Font ( "" , Font . BOLD , ) ; public OverlayPanel ( int scW , int scH , Tray mainP ) { tray = mainP ; this . scW = scW ; this . scH = scH ; toolkit = Toolkit . getDefaultToolkit ( ) ; selection = new Rectangle2D . Double ( ) ; addMouseListener ( this ) ; addMouseMotionListener ( this ) ; addKeyListener ( this ) ; setMouseCursor ( ) ; setFocusable ( true ) ; } public void setupOverlay ( ) { if ( ! tray . isVisible ( ) ) if ( isSnippet && ! saveLocally ) { tray . setVisible ( true ) ; captureScreen ( ) ; } else if ( ! isSnippet && ! saveLocally ) { captureScreen ( ) ; upload ( true , image ) ; } else if ( isSnippet && saveLocally ) { tray . setVisible ( true ) ; captureScreen ( ) ; } else if ( ! isSnippet && saveLocally ) { captureScreen ( ) ; save ( image ) ; } } public void setMouseCursor ( ) { ImageIcon ii = new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ; Image cursorImage = ii . getImage ( ) ; Point cursorHotSpot = new Point ( , ) ; Cursor customCursor = toolkit . createCustomCursor ( cursorImage , cursorHotSpot , "" ) ; this . setCursor ( customCursor ) ; } public void captureScreen ( ) { try { Dimension screenSize = new Dimension ( scW , scH ) ; Rectangle screenRectangle = new ScreenBounds ( ) . getBounds ( ) ; Robot robot = new Robot ( ) ; image = robot . createScreenCapture ( screenRectangle ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } @ Override public void paintComponent ( Graphics g ) { super . paintComponent ( g ) ; Graphics2D g2d = ( Graphics2D ) g ; g2d . setFont ( font ) ; drawOverlay ( g2d ) ; drawSelection ( g2d ) ; drawTip ( g2d ) ; } private void drawTip ( Graphics2D g2d ) { if ( DataDirectory . MULTI_SNIPPET ) { g2d . setColor ( new Color ( , , , ) ) ; g2d . fillRect ( mx , my , , ) ; g2d . setColor ( Color . lightGray ) ; g2d . drawString ( "" , mx + , my + font . getSize ( ) + ) ; g2d . drawString ( "" , mx + , my + ( font . getSize ( ) * ) + ) ; } } private void drawOverlay ( Graphics2D g2d ) { g2d . drawImage ( image , , , null ) ; g2d . setColor ( overlayColor ) ; g2d . fillRect ( , , scW , scH ) ; } private void drawSelection ( Graphics2D g2d ) { Rectangle select ; if ( DataDirectory . MULTI_SNIPPET ) { for ( int i = ; i < endPointList . size ( ) ; i ++ ) { selection . setFrameFromDiagonal ( startPointList . get ( i ) , endPointList . get ( i ) ) ; select = selection . getBounds ( ) ; if ( getSubimage ( ) != null ) { g2d . drawImage ( getSubimage ( ) , select . x , select . y , null ) ; g2d . setColor ( boundingColor ) ; g2d . drawRect ( select . x , select . y , select . width , select . height ) ; } } } selection . setFrameFromDiagonal ( startPoint , endPoint ) ; select = selection . getBounds ( ) ; if ( getSubimage ( ) != null ) { g2d . drawImage ( getSubimage ( ) , select . x , select . y , null ) ; g2d . setColor ( boundingColor ) ; g2d . drawRect ( select . x , select . y , select . width , select . height ) ; } } private BufferedImage getSubimage ( ) { Rectangle select = selection . getBounds ( ) ; if ( select . width > && select . height > ) { return image . getSubimage ( select . x , select . y , select . width , select . height ) ; } else { return null ; } } private BufferedImage getSubimage ( Point start , Point end ) { Rectangle2D rect2D = new Rectangle2D . Double ( ) ; rect2D . setFrameFromDiagonal ( start , end ) ; Rectangle select = rect2D . getBounds ( ) ; if ( select . width > && select . height > ) return image . getSubimage ( select . x , select . y , select . width , select . height ) ; return null ; } private BufferedImage createMultiImage ( ) { int w = getMultiImageMaxWidth ( ) ; float h = getMultiImageHeight ( ) ; h += ( endPointList . size ( ) * divider_width ) ; BufferedImage multiImage = new BufferedImage ( w , ( int ) h , BufferedImage . TYPE_INT_RGB ) ; Graphics g = multiImage . getGraphics ( ) ; float posY = ; BufferedImage tImage ; g . setColor ( divider_color ) ; for ( int i = ; i < endPointList . size ( ) ; i ++ ) { tImage = getSubimage ( startPointList . get ( i ) , endPointList . get ( i ) ) ; g . drawImage ( tImage , , ( int ) posY , null ) ; posY += tImage . getHeight ( ) ; g . drawLine ( , ( int ) posY , w , ( int ) posY ) ; posY += divider_width ; } return multiImage ; } private int getMultiImageHeight ( ) { Rectangle2D rect2D = new Rectangle2D . Double ( ) ; int height = ; for ( int i = ; i < endPointList . size ( ) ; i ++ ) { rect2D . setFrameFromDiagonal ( startPointList . get ( i ) , endPointList . get ( i ) ) ; height += rect2D . getBounds ( ) . height ; } return height ; } private int getMultiImageMaxWidth ( ) { Rectangle2D rect2D = new Rectangle2D . Double ( ) ; int width = ; for ( int i = ; i < endPointList . size ( ) ; i ++ ) { rect2D . setFrameFromDiagonal ( startPointList . get ( i ) , endPointList . get ( i ) ) ; if ( rect2D . getBounds ( ) . width > width ) width = rect2D . getBounds ( ) . width ; } return width ; } public void upload ( boolean screenshot , BufferedImage imageToUp ) { if ( ! screenshot ) { upload = new Upload ( imageToUp , tray , true ) ; } else upload = new Upload ( imageToUp , tray , true ) ; } public void save ( BufferedImage sav ) { int index = ; savLoc = new File ( DataDirectory . CAPTURE_PATH + "" ) ; do { index ++ ; savLoc = new File ( DataDirectory . CAPTURE_PATH + "" + index + "" ) ; } while ( savLoc . exists ( ) ) ; tray . trayIcon . displayMessage ( "" , "" , TrayIcon . MessageType . INFO ) ; try { ImageIO . write ( sav , "" , savLoc ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } public Boolean isOverlayVisible ( ) { return tray . isVisible ( ) ; } public void setOverlayVisible ( boolean visible ) { tray . setVisible ( visible ) ; } @ Override public void mouseClicked ( MouseEvent e ) { } @ Override public void mouseEntered ( MouseEvent e ) { } @ Override public void mouseExited ( MouseEvent e ) { } @ Override public void mousePressed ( MouseEvent e ) { if ( e . getButton ( ) == MouseEvent . BUTTON1 ) { startPoint = new Point ( mx , my ) ; endPoint = new Point ( mx , my ) ; if ( DataDirectory . MULTI_SNIPPET ) startPointList . add ( startPoint ) ; } } @ Override public void mouseReleased ( MouseEvent e ) { if ( e . getButton ( ) == MouseEvent . BUTTON1 ) { mx = e . getX ( ) ; my = e . getY ( ) ; endPoint = new Point ( mx , my ) ; if ( ! DataDirectory . MULTI_SNIPPET ) { if ( saveLocally ) { tray . setVisible ( false ) ; save ( getSubimage ( ) ) ; } else { tray . setVisible ( false ) ; upload ( false , getSubimage ( ) ) ; } } else { endPointList . add ( endPoint ) ; } } } @ Override public void mouseDragged ( MouseEvent me ) { mx = me . getX ( ) ; my = me . getY ( ) ; endPoint = new Point ( mx , my ) ; repaint ( ) ; } @ Override public void mouseMoved ( MouseEvent me ) { mx = me . getX ( ) ; my = me . getY ( ) ; } public void setUploadSnippet ( ) { reset ( ) ; isSnippet = true ; saveLocally = false ; setupOverlay ( ) ; } public void setUploadScreenshot ( ) { reset ( ) ; isSnippet = false ; saveLocally = false ; setupOverlay ( ) ; } public void setSaveSnippet ( ) { reset ( ) ; isSnippet = true ; saveLocally = true ; setupOverlay ( ) ; } public void setSaveScreenshot ( ) { reset ( ) ; isSnippet = false ; saveLocally = true ; setupOverlay ( ) ; } public void reset ( ) { startPoint = new Point ( , ) ; endPoint = new Point ( , ) ; startPointList . clear ( ) ; endPointList . clear ( ) ; } public void setOverlayColor ( Color col ) { overlayColor = new Color ( col . getRed ( ) , col . getGreen ( ) , col . getBlue ( ) , ) ; System . out . println ( overlayColor . toString ( ) ) ; } public void setBoundingColor ( Color col ) { boundingColor = new Color ( col . getRed ( ) , col . getGreen ( ) , col . getBlue ( ) ) ; } @ Override public void keyPressed ( KeyEvent e ) { if ( ! startPointList . isEmpty ( ) && DataDirectory . MULTI_SNIPPET ) if ( e . getKeyCode ( ) == KeyEvent . VK_ENTER ) { if ( saveLocally ) { tray . setVisible ( false ) ; save ( createMultiImage ( ) ) ; } else { tray . setVisible ( false ) ; upload ( false , createMultiImage ( ) ) ; } } if ( e . getKeyCode ( ) == KeyEvent . VK_ESCAPE ) { setOverlayVisible ( false ) ; reset ( ) ; } } @ Override public void keyReleased ( KeyEvent e ) { } @ Override public void keyTyped ( KeyEvent e ) { } } import java . awt . Dimension ; import java . awt . Frame ; import java . awt . Image ; import java . awt . TrayIcon ; import java . awt . event . MouseAdapter ; import java . awt . event . MouseEvent ; import javax . swing . JDialog ; import javax . swing . JPopupMenu ; import javax . swing . event . PopupMenuEvent ; import javax . swing . event . PopupMenuListener ; public class JXTrayIcon extends TrayIcon { private JPopupMenu menu ; private static JDialog dialog ; static { dialog = new JDialog ( ( Frame ) null , "" ) ; dialog . setUndecorated ( true ) ; dialog . setAlwaysOnTop ( true ) ; } private static PopupMenuListener popupListener = new PopupMenuListener ( ) { @ Override public void popupMenuWillBecomeVisible ( PopupMenuEvent e ) { } @ Override public void popupMenuWillBecomeInvisible ( PopupMenuEvent e ) { dialog . setVisible ( false ) ; } @ Override public void popupMenuCanceled ( PopupMenuEvent e ) { dialog . setVisible ( false ) ; } } ; public JXTrayIcon ( Image image ) { super ( image ) ; addMouseListener ( new MouseAdapter ( ) { @ Override public void mousePressed ( MouseEvent e ) { showJPopupMenu ( e ) ; } @ Override public void mouseReleased ( MouseEvent e ) { showJPopupMenu ( e ) ; } } ) ; } public JXTrayIcon ( Image image , String string ) { super ( image , string ) ; addMouseListener ( new MouseAdapter ( ) { @ Override public void mousePressed ( MouseEvent e ) { showJPopupMenu ( e ) ; } @ Override public void mouseReleased ( MouseEvent e ) { showJPopupMenu ( e ) ; } } ) ; } private void showJPopupMenu ( MouseEvent e ) { if ( e . isPopupTrigger ( ) && menu != null ) { Dimension size = menu . getPreferredSize ( ) ; int adjustedY = e . getY ( ) - size . height ; dialog . setLocation ( e . getX ( ) , adjustedY < ? e . getY ( ) : adjustedY ) ; dialog . setVisible ( true ) ; menu . show ( dialog . getContentPane ( ) , , ) ; dialog . toFront ( ) ; } } public JPopupMenu getJPopupMenu ( ) { return menu ; } public void setJPopupMenu ( JPopupMenu menu ) { if ( this . menu != null ) { this . menu . removePopupMenuListener ( popupListener ) ; } this . menu = menu ; menu . addPopupMenuListener ( popupListener ) ; } } package com . melloware . jintellitype ; import java . util . Properties ; @ SuppressWarnings ( "" ) public final class Main { private Main ( ) { } public static void main ( String [ ] argv ) { System . out . println ( "" + getProjectVersion ( ) + "" ) ; System . out . println ( "" ) ; System . out . println ( "" + System . getProperty ( "" ) + "" + "" + System . getProperty ( "" ) + "" + "" + System . getProperty ( "" ) ) ; System . out . println ( "" + System . getProperty ( "" ) + "" + "" + System . getProperty ( "" ) + "" + System . getProperty ( "" ) ) ; System . out . println ( "" ) ; } private static String getProjectVersion ( ) { String version ; try { final Properties pomProperties = new Properties ( ) ; pomProperties . load ( Main . class . getResourceAsStream ( "" ) ) ; version = pomProperties . getProperty ( "" ) ; } catch ( Exception e ) { version = "" ; } return version ; } } package com . melloware . jintellitype ; public class JIntellitypeException extends RuntimeException { public JIntellitypeException ( ) { super ( ) ; } public JIntellitypeException ( String aMessage , Throwable aCause ) { super ( aMessage , aCause ) ; } public JIntellitypeException ( String aMessage ) { super ( aMessage ) ; } public JIntellitypeException ( Throwable aCause ) { super ( aCause ) ; } } package com . melloware . jintellitype ; public interface HotkeyListener { void onHotKey ( int identifier ) ; } package com . melloware . jintellitype ; public interface JIntellitypeConstants { public static final String ERROR_MESSAGE = "" ; public static final int MOD_ALT = ; public static final int MOD_CONTROL = ; public static final int MOD_SHIFT = ; public static final int MOD_WIN = ; public static final int APPCOMMAND_BROWSER_BACKWARD = ; public static final int APPCOMMAND_BROWSER_FORWARD = ; public static final int APPCOMMAND_BROWSER_REFRESH = ; public static final int APPCOMMAND_BROWSER_STOP = ; public static final int APPCOMMAND_BROWSER_SEARCH = ; public static final int APPCOMMAND_BROWSER_FAVOURITES = ; public static final int APPCOMMAND_BROWSER_HOME = ; public static final int APPCOMMAND_VOLUME_MUTE = ; public static final int APPCOMMAND_VOLUME_DOWN = ; public static final int APPCOMMAND_VOLUME_UP = ; public static final int APPCOMMAND_MEDIA_NEXTTRACK = ; public static final int APPCOMMAND_MEDIA_PREVIOUSTRACK = ; public static final int APPCOMMAND_MEDIA_STOP = ; public static final int APPCOMMAND_MEDIA_PLAY_PAUSE = ; public static final int APPCOMMAND_LAUNCH_MAIL = ; public static final int APPCOMMAND_LAUNCH_MEDIA_SELECT = ; public static final int APPCOMMAND_LAUNCH_APP1 = ; public static final int APPCOMMAND_LAUNCH_APP2 = ; public static final int APPCOMMAND_BASS_DOWN = ; public static final int APPCOMMAND_BASS_BOOST = ; public static final int APPCOMMAND_BASS_UP = ; public static final int APPCOMMAND_TREBLE_DOWN = ; public static final int APPCOMMAND_TREBLE_UP = ; public static final int APPCOMMAND_MICROPHONE_VOLUME_MUTE = ; public static final int APPCOMMAND_MICROPHONE_VOLUME_DOWN = ; public static final int APPCOMMAND_MICROPHONE_VOLUME_UP = ; public static final int APPCOMMAND_HELP = ; public static final int APPCOMMAND_FIND = ; public static final int APPCOMMAND_NEW = ; public static final int APPCOMMAND_OPEN = ; public static final int APPCOMMAND_CLOSE = ; public static final int APPCOMMAND_SAVE = ; public static final int APPCOMMAND_PRINT = ; public static final int APPCOMMAND_UNDO = ; public static final int APPCOMMAND_REDO = ; public static final int APPCOMMAND_COPY = ; public static final int APPCOMMAND_CUT = ; public static final int APPCOMMAND_PASTE = ; public static final int APPCOMMAND_REPLY_TO_MAIL = ; public static final int APPCOMMAND_FORWARD_MAIL = ; public static final int APPCOMMAND_SEND_MAIL = ; public static final int APPCOMMAND_SPELL_CHECK = ; public static final int APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE = ; public static final int APPCOMMAND_MIC_ON_OFF_TOGGLE = ; public static final int APPCOMMAND_CORRECTION_LIST = ; } package com . melloware . jintellitype ; import java . awt . event . InputEvent ; import java . awt . event . KeyEvent ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . concurrent . CopyOnWriteArrayList ; import javax . swing . SwingUtilities ; public final class JIntellitype implements JIntellitypeConstants { private static JIntellitype jintellitype = null ; private static boolean isInitialized = false ; private static String libraryLocation = null ; private final List < HotkeyListener > hotkeyListeners = Collections . synchronizedList ( new CopyOnWriteArrayList < HotkeyListener > ( ) ) ; private final List < IntellitypeListener > intellitypeListeners = Collections . synchronizedList ( new CopyOnWriteArrayList < IntellitypeListener > ( ) ) ; private final int handler = ; private final HashMap < String , Integer > keycodeMap ; private JIntellitype ( ) { try { System . loadLibrary ( "" ) ; } catch ( Throwable ex ) { try { if ( getLibraryLocation ( ) != null ) { System . load ( getLibraryLocation ( ) ) ; } else { String jarPath = "" ; String tmpDir = System . getProperty ( "" ) ; try { String dll = "" ; fromJarToFs ( jarPath + dll , tmpDir + dll ) ; System . load ( tmpDir + dll ) ; } catch ( UnsatisfiedLinkError e ) { String dll = "" ; fromJarToFs ( jarPath + dll , tmpDir + dll ) ; System . load ( tmpDir + dll ) ; } } } catch ( Throwable ex2 ) { throw new JIntellitypeException ( "" , ex2 ) ; } } initializeLibrary ( ) ; this . keycodeMap = getKey2KeycodeMapping ( ) ; } private void fromJarToFs ( String jarPath , String filePath ) throws IOException { File file = new File ( filePath ) ; if ( file . exists ( ) ) { boolean success = file . delete ( ) ; if ( ! success ) { throw new IOException ( "" + filePath ) ; } } InputStream is = null ; OutputStream os = null ; try { is = ClassLoader . getSystemClassLoader ( ) . getResourceAsStream ( jarPath ) ; os = new FileOutputStream ( filePath ) ; byte [ ] buffer = new byte [ ] ; int bytesRead ; while ( ( bytesRead = is . read ( buffer ) ) != - ) { os . write ( buffer , , bytesRead ) ; } } finally { if ( is != null ) { is . close ( ) ; } if ( os != null ) { os . close ( ) ; } } } public static JIntellitype getInstance ( ) { if ( ! isInitialized ) { synchronized ( JIntellitype . class ) { if ( ! isInitialized ) { jintellitype = new JIntellitype ( ) ; isInitialized = true ; } } } return jintellitype ; } public void addHotKeyListener ( HotkeyListener listener ) { hotkeyListeners . add ( listener ) ; } public void addIntellitypeListener ( IntellitypeListener listener ) { intellitypeListeners . add ( listener ) ; } public void cleanUp ( ) { try { terminate ( ) ; } catch ( UnsatisfiedLinkError ex ) { throw new JIntellitypeException ( ERROR_MESSAGE , ex ) ; } catch ( RuntimeException ex ) { throw new JIntellitypeException ( ex ) ; } } public void registerHotKey ( int identifier , int modifier , int keycode ) { try { int modifiers = swingToIntelliType ( modifier ) ; if ( modifiers == ) { modifiers = modifier ; } regHotKey ( identifier , modifier , keycode ) ; } catch ( UnsatisfiedLinkError ex ) { throw new JIntellitypeException ( ERROR_MESSAGE , ex ) ; } catch ( RuntimeException ex ) { throw new JIntellitypeException ( ex ) ; } } public void registerSwingHotKey ( int identifier , int modifier , int keycode ) { try { regHotKey ( identifier , swingToIntelliType ( modifier ) , keycode ) ; } catch ( UnsatisfiedLinkError ex ) { throw new JIntellitypeException ( ERROR_MESSAGE , ex ) ; } catch ( RuntimeException ex ) { throw new JIntellitypeException ( ex ) ; } } public void registerHotKey ( int identifier , String modifierAndKeyCode ) { String [ ] split = modifierAndKeyCode . split ( "" ) ; int mask = ; int keycode = ; for ( int i = ; i < split . length ; i ++ ) { if ( "" . equalsIgnoreCase ( split [ i ] ) ) { mask += JIntellitype . MOD_ALT ; } else if ( "" . equalsIgnoreCase ( split [ i ] ) || "" . equalsIgnoreCase ( split [ i ] ) ) { mask += JIntellitype . MOD_CONTROL ; } else if ( "" . equalsIgnoreCase ( split [ i ] ) ) { mask += JIntellitype . MOD_SHIFT ; } else if ( "" . equalsIgnoreCase ( split [ i ] ) ) { mask += JIntellitype . MOD_WIN ; } else if ( keycodeMap . containsKey ( split [ i ] . toLowerCase ( ) ) ) { keycode = keycodeMap . get ( split [ i ] . toLowerCase ( ) ) ; } } registerHotKey ( identifier , mask , keycode ) ; } public void removeHotKeyListener ( HotkeyListener listener ) { hotkeyListeners . remove ( listener ) ; } public void removeIntellitypeListener ( IntellitypeListener listener ) { intellitypeListeners . remove ( listener ) ; } public void unregisterHotKey ( int identifier ) { try { unregHotKey ( identifier ) ; } catch ( UnsatisfiedLinkError ex ) { throw new JIntellitypeException ( ERROR_MESSAGE , ex ) ; } catch ( RuntimeException ex ) { throw new JIntellitypeException ( ex ) ; } } public static boolean checkInstanceAlreadyRunning ( String appTitle ) { return getInstance ( ) . isRunning ( appTitle ) ; } public static boolean isJIntellitypeSupported ( ) { boolean result = false ; String os = "" ; try { os = System . getProperty ( "" ) . toLowerCase ( ) ; } catch ( SecurityException ex ) { System . err . println ( "" + "" ) ; } if ( os . startsWith ( "" ) ) { try { getInstance ( ) ; result = true ; } catch ( Exception e ) { result = false ; } } return result ; } public static String getLibraryLocation ( ) { return libraryLocation ; } public static void setLibraryLocation ( String libraryLocation ) { final File dll = new File ( libraryLocation ) ; if ( ! dll . isAbsolute ( ) ) { JIntellitype . libraryLocation = dll . getAbsolutePath ( ) ; } else { JIntellitype . libraryLocation = libraryLocation ; } } public static void setLibraryLocation ( File libraryFile ) { if ( ! libraryFile . isAbsolute ( ) ) { JIntellitype . libraryLocation = libraryFile . getAbsolutePath ( ) ; } } protected void onHotKey ( final int identifier ) { for ( final HotkeyListener hotkeyListener : hotkeyListeners ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { hotkeyListener . onHotKey ( identifier ) ; } } ) ; } } protected void onIntellitype ( final int command ) { for ( final IntellitypeListener intellitypeListener : intellitypeListeners ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { intellitypeListener . onIntellitype ( command ) ; } } ) ; } } protected static int swingToIntelliType ( int swingKeystrokeModifier ) { int mask = ; if ( ( swingKeystrokeModifier & InputEvent . SHIFT_MASK ) == InputEvent . SHIFT_MASK || ( swingKeystrokeModifier & InputEvent . SHIFT_DOWN_MASK ) == InputEvent . SHIFT_DOWN_MASK ) { mask |= JIntellitypeConstants . MOD_SHIFT ; } if ( ( swingKeystrokeModifier & InputEvent . ALT_MASK ) == InputEvent . ALT_MASK || ( swingKeystrokeModifier & InputEvent . ALT_DOWN_MASK ) == InputEvent . ALT_DOWN_MASK ) { mask |= JIntellitypeConstants . MOD_ALT ; } if ( ( swingKeystrokeModifier & InputEvent . CTRL_MASK ) == InputEvent . CTRL_MASK || ( swingKeystrokeModifier & InputEvent . CTRL_DOWN_MASK ) == InputEvent . CTRL_DOWN_MASK ) { mask |= JIntellitypeConstants . MOD_CONTROL ; } if ( ( swingKeystrokeModifier & InputEvent . META_MASK ) == InputEvent . META_MASK || ( swingKeystrokeModifier & InputEvent . META_DOWN_MASK ) == InputEvent . META_DOWN_MASK ) { mask |= JIntellitypeConstants . MOD_WIN ; } return mask ; } private HashMap < String , Integer > getKey2KeycodeMapping ( ) { HashMap < String , Integer > map = new HashMap < String , Integer > ( ) ; map . put ( "" , KeyEvent . KEY_FIRST ) ; map . put ( "" , KeyEvent . KEY_LAST ) ; map . put ( "" , KeyEvent . KEY_TYPED ) ; map . put ( "" , KeyEvent . KEY_PRESSED ) ; map . put ( "" , KeyEvent . KEY_RELEASED ) ; map . put ( "" , ) ; map . put ( "" , KeyEvent . VK_BACK_SPACE ) ; map . put ( "" , KeyEvent . VK_TAB ) ; map . put ( "" , KeyEvent . VK_CANCEL ) ; map . put ( "" , KeyEvent . VK_CLEAR ) ; map . put ( "" , KeyEvent . VK_PAUSE ) ; map . put ( "" , KeyEvent . VK_CAPS_LOCK ) ; map . put ( "" , KeyEvent . VK_ESCAPE ) ; map . put ( "" , KeyEvent . VK_SPACE ) ; map . put ( "" , KeyEvent . VK_PAGE_UP ) ; map . put ( "" , KeyEvent . VK_PAGE_DOWN ) ; map . put ( "" , KeyEvent . VK_END ) ; map . put ( "" , KeyEvent . VK_HOME ) ; map . put ( "" , KeyEvent . VK_LEFT ) ; map . put ( "" , KeyEvent . VK_UP ) ; map . put ( "" , KeyEvent . VK_RIGHT ) ; map . put ( "" , KeyEvent . VK_DOWN ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , KeyEvent . VK_0 ) ; map . put ( "" , KeyEvent . VK_1 ) ; map . put ( "" , KeyEvent . VK_2 ) ; map . put ( "" , KeyEvent . VK_3 ) ; map . put ( "" , KeyEvent . VK_4 ) ; map . put ( "" , KeyEvent . VK_5 ) ; map . put ( "" , KeyEvent . VK_6 ) ; map . put ( "" , KeyEvent . VK_7 ) ; map . put ( "" , KeyEvent . VK_8 ) ; map . put ( "" , KeyEvent . VK_9 ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , KeyEvent . VK_A ) ; map . put ( "" , KeyEvent . VK_B ) ; map . put ( "" , KeyEvent . VK_C ) ; map . put ( "" , KeyEvent . VK_D ) ; map . put ( "" , KeyEvent . VK_E ) ; map . put ( "" , KeyEvent . VK_F ) ; map . put ( "" , KeyEvent . VK_G ) ; map . put ( "" , KeyEvent . VK_H ) ; map . put ( "" , KeyEvent . VK_I ) ; map . put ( "" , KeyEvent . VK_J ) ; map . put ( "" , KeyEvent . VK_K ) ; map . put ( "" , KeyEvent . VK_L ) ; map . put ( "" , KeyEvent . VK_M ) ; map . put ( "" , KeyEvent . VK_N ) ; map . put ( "" , KeyEvent . VK_O ) ; map . put ( "" , KeyEvent . VK_P ) ; map . put ( "" , KeyEvent . VK_Q ) ; map . put ( "" , KeyEvent . VK_R ) ; map . put ( "" , KeyEvent . VK_S ) ; map . put ( "" , KeyEvent . VK_T ) ; map . put ( "" , KeyEvent . VK_U ) ; map . put ( "" , KeyEvent . VK_V ) ; map . put ( "" , KeyEvent . VK_W ) ; map . put ( "" , KeyEvent . VK_X ) ; map . put ( "" , KeyEvent . VK_Y ) ; map . put ( "" , KeyEvent . VK_Z ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , KeyEvent . VK_NUMPAD0 ) ; map . put ( "" , KeyEvent . VK_NUMPAD1 ) ; map . put ( "" , KeyEvent . VK_NUMPAD2 ) ; map . put ( "" , KeyEvent . VK_NUMPAD3 ) ; map . put ( "" , KeyEvent . VK_NUMPAD4 ) ; map . put ( "" , KeyEvent . VK_NUMPAD5 ) ; map . put ( "" , KeyEvent . VK_NUMPAD6 ) ; map . put ( "" , KeyEvent . VK_NUMPAD7 ) ; map . put ( "" , KeyEvent . VK_NUMPAD8 ) ; map . put ( "" , KeyEvent . VK_NUMPAD9 ) ; map . put ( "" , KeyEvent . VK_MULTIPLY ) ; map . put ( "" , KeyEvent . VK_ADD ) ; map . put ( "" , KeyEvent . VK_SEPARATOR ) ; map . put ( "" , KeyEvent . VK_SUBTRACT ) ; map . put ( "" , KeyEvent . VK_DECIMAL ) ; map . put ( "" , KeyEvent . VK_DIVIDE ) ; map . put ( "" , ) ; map . put ( "" , KeyEvent . VK_NUM_LOCK ) ; map . put ( "" , KeyEvent . VK_SCROLL_LOCK ) ; map . put ( "" , KeyEvent . VK_F1 ) ; map . put ( "" , KeyEvent . VK_F2 ) ; map . put ( "" , KeyEvent . VK_F3 ) ; map . put ( "" , KeyEvent . VK_F4 ) ; map . put ( "" , KeyEvent . VK_F5 ) ; map . put ( "" , KeyEvent . VK_F6 ) ; map . put ( "" , KeyEvent . VK_F7 ) ; map . put ( "" , KeyEvent . VK_F8 ) ; map . put ( "" , KeyEvent . VK_F9 ) ; map . put ( "" , KeyEvent . VK_F10 ) ; map . put ( "" , KeyEvent . VK_F11 ) ; map . put ( "" , KeyEvent . VK_F12 ) ; map . put ( "" , KeyEvent . VK_F13 ) ; map . put ( "" , KeyEvent . VK_F14 ) ; map . put ( "" , KeyEvent . VK_F15 ) ; map . put ( "" , KeyEvent . VK_F16 ) ; map . put ( "" , KeyEvent . VK_F17 ) ; map . put ( "" , KeyEvent . VK_F18 ) ; map . put ( "" , KeyEvent . VK_F19 ) ; map . put ( "" , KeyEvent . VK_F20 ) ; map . put ( "" , KeyEvent . VK_F21 ) ; map . put ( "" , KeyEvent . VK_F22 ) ; map . put ( "" , KeyEvent . VK_F23 ) ; map . put ( "" , KeyEvent . VK_F24 ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , ) ; map . put ( "" , KeyEvent . VK_META ) ; map . put ( "" , KeyEvent . VK_BACK_QUOTE ) ; map . put ( "" , KeyEvent . VK_QUOTE ) ; map . put ( "" , KeyEvent . VK_KP_UP ) ; map . put ( "" , KeyEvent . VK_KP_DOWN ) ; map . put ( "" , KeyEvent . VK_KP_LEFT ) ; map . put ( "" , KeyEvent . VK_KP_RIGHT ) ; map . put ( "" , KeyEvent . VK_DEAD_GRAVE ) ; map . put ( "" , KeyEvent . VK_DEAD_ACUTE ) ; map . put ( "" , KeyEvent . VK_DEAD_CIRCUMFLEX ) ; map . put ( "" , KeyEvent . VK_DEAD_TILDE ) ; map . put ( "" , KeyEvent . VK_DEAD_MACRON ) ; map . put ( "" , KeyEvent . VK_DEAD_BREVE ) ; map . put ( "" , KeyEvent . VK_DEAD_ABOVEDOT ) ; map . put ( "" , KeyEvent . VK_DEAD_DIAERESIS ) ; map . put ( "" , KeyEvent . VK_DEAD_ABOVERING ) ; map . put ( "" , KeyEvent . VK_DEAD_DOUBLEACUTE ) ; map . put ( "" , KeyEvent . VK_DEAD_CARON ) ; map . put ( "" , KeyEvent . VK_DEAD_CEDILLA ) ; map . put ( "" , KeyEvent . VK_DEAD_OGONEK ) ; map . put ( "" , KeyEvent . VK_DEAD_IOTA ) ; map . put ( "" , KeyEvent . VK_DEAD_VOICED_SOUND ) ; map . put ( "" , KeyEvent . VK_DEAD_SEMIVOICED_SOUND ) ; map . put ( "" , KeyEvent . VK_AMPERSAND ) ; map . put ( "" , KeyEvent . VK_ASTERISK ) ; map . put ( "" , KeyEvent . VK_QUOTEDBL ) ; map . put ( "" , KeyEvent . VK_LESS ) ; map . put ( "" , KeyEvent . VK_GREATER ) ; map . put ( "" , KeyEvent . VK_BRACELEFT ) ; map . put ( "" , KeyEvent . VK_BRACERIGHT ) ; map . put ( "" , KeyEvent . VK_AT ) ; map . put ( "" , KeyEvent . VK_COLON ) ; map . put ( "" , KeyEvent . VK_CIRCUMFLEX ) ; map . put ( "" , KeyEvent . VK_DOLLAR ) ; map . put ( "" , KeyEvent . VK_EURO_SIGN ) ; map . put ( "" , KeyEvent . VK_EXCLAMATION_MARK ) ; map . put ( "" , KeyEvent . VK_INVERTED_EXCLAMATION_MARK ) ; map . put ( "" , KeyEvent . VK_LEFT_PARENTHESIS ) ; map . put ( "" , KeyEvent . VK_NUMBER_SIGN ) ; map . put ( "" , KeyEvent . VK_PLUS ) ; map . put ( "" , KeyEvent . VK_RIGHT_PARENTHESIS ) ; map . put ( "" , KeyEvent . VK_UNDERSCORE ) ; map . put ( "" , KeyEvent . VK_CONTEXT_MENU ) ; map . put ( "" , KeyEvent . VK_FINAL ) ; map . put ( "" , KeyEvent . VK_CONVERT ) ; map . put ( "" , KeyEvent . VK_NONCONVERT ) ; map . put ( "" , KeyEvent . VK_ACCEPT ) ; map . put ( "" , KeyEvent . VK_MODECHANGE ) ; map . put ( "" , KeyEvent . VK_KANA ) ; map . put ( "" , KeyEvent . VK_KANJI ) ; map . put ( "" , KeyEvent . VK_ALPHANUMERIC ) ; map . put ( "" , KeyEvent . VK_KATAKANA ) ; map . put ( "" , KeyEvent . VK_HIRAGANA ) ; map . put ( "" , KeyEvent . VK_FULL_WIDTH ) ; map . put ( "" , KeyEvent . VK_HALF_WIDTH ) ; map . put ( "" , KeyEvent . VK_ROMAN_CHARACTERS ) ; map . put ( "" , KeyEvent . VK_ALL_CANDIDATES ) ; map . put ( "" , KeyEvent . VK_PREVIOUS_CANDIDATE ) ; map . put ( "" , KeyEvent . VK_CODE_INPUT ) ; map . put ( "" , KeyEvent . VK_JAPANESE_KATAKANA ) ; map . put ( "" , KeyEvent . VK_JAPANESE_HIRAGANA ) ; map . put ( "" , KeyEvent . VK_JAPANESE_ROMAN ) ; map . put ( "" , KeyEvent . VK_KANA_LOCK ) ; map . put ( "" , KeyEvent . VK_INPUT_METHOD_ON_OFF ) ; map . put ( "" , KeyEvent . VK_CUT ) ; map . put ( "" , KeyEvent . VK_COPY ) ; map . put ( "" , KeyEvent . VK_PASTE ) ; map . put ( "" , KeyEvent . VK_UNDO ) ; map . put ( "" , KeyEvent . VK_AGAIN ) ; map . put ( "" , KeyEvent . VK_FIND ) ; map . put ( "" , KeyEvent . VK_PROPS ) ; map . put ( "" , KeyEvent . VK_STOP ) ; map . put ( "" , KeyEvent . VK_COMPOSE ) ; map . put ( "" , KeyEvent . VK_ALT_GRAPH ) ; map . put ( "" , KeyEvent . VK_BEGIN ) ; return map ; } private synchronized native void initializeLibrary ( ) throws UnsatisfiedLinkError ; private synchronized native void regHotKey ( int identifier , int modifier , int keycode ) throws UnsatisfiedLinkError ; private synchronized native void terminate ( ) throws UnsatisfiedLinkError ; private synchronized native void unregHotKey ( int identifier ) throws UnsatisfiedLinkError ; private synchronized native boolean isRunning ( String appName ) ; } package com . melloware . jintellitype ; public interface IntellitypeListener { void onIntellitype ( int command ) ; } import java . io . BufferedReader ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileReader ; import java . io . IOException ; import java . io . PrintWriter ; public class DataDirectory { public static String VERSION = "" ; public static String CAPTURE_PATH ; public static boolean MULTI_SNIPPET ; public static String PASTEBIN_TITLE ; public static String PASTEBIN_TYPE ; public static String PASTEBIN_FORMAT ; public static String PASTEBIN_EXPIRATION ; public static int PASTEBIN_PRIVACY ; public static boolean PASTEBIN_GUEST ; public static String PASTEBIN_USERNAME ; public static String PASTEBIN_PASSWORD ; public static String dirPath = System . getProperty ( "" ) + "" ; public static String dirDataPath = System . getProperty ( "" ) + "" ; public static String defaultCapturePath = System . getProperty ( "" ) + "" ; File directory ; File defaultCap ; public DataDirectory ( ) { directory = new File ( dirDataPath ) ; defaultCap = new File ( defaultCapturePath ) ; if ( ! directory . exists ( ) ) { System . out . println ( "" ) ; createDirectories ( ) ; } else { System . out . println ( "" ) ; if ( isCurrentVersion ( ) ) { System . out . println ( "" ) ; File pref = new File ( dirDataPath + "" ) ; if ( pref . exists ( ) ) loadPreferences ( ) ; else createPrefFile ( ) ; } else { System . out . println ( "" ) ; recreateDirectories ( ) ; } } } private boolean isCurrentVersion ( ) { if ( new File ( dirDataPath + "" ) . exists ( ) ) { try { BufferedReader reader = new BufferedReader ( new FileReader ( dirDataPath + "" ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) if ( line . equals ( VERSION ) ) return true ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return false ; } private void recreateDirectories ( ) { deleteDirectory ( new File ( dirPath ) ) ; createDirectories ( ) ; } private void deleteDirectory ( File file ) { if ( file . isDirectory ( ) ) { if ( file . list ( ) . length == ) { file . delete ( ) ; System . out . println ( "" + file . getAbsolutePath ( ) ) ; } else { String files [ ] = file . list ( ) ; for ( String temp : files ) { File fileDelete = new File ( file , temp ) ; deleteDirectory ( fileDelete ) ; } if ( file . list ( ) . length == ) { file . delete ( ) ; System . out . println ( "" + file . getAbsolutePath ( ) ) ; } } } else { file . delete ( ) ; System . out . println ( "" + file . getAbsolutePath ( ) ) ; } } private void createDirectories ( ) { System . out . println ( "" ) ; directory . mkdirs ( ) ; defaultCap . mkdirs ( ) ; createVersionFile ( ) ; createPrefFile ( ) ; loadPreferences ( ) ; } private void createVersionFile ( ) { try { PrintWriter out = new PrintWriter ( dirDataPath + "" ) ; out . println ( VERSION ) ; out . close ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } } public static void loadPreferences ( ) { try { BufferedReader reader = new BufferedReader ( new FileReader ( dirDataPath + "" ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { String [ ] temp = line . split ( "" ) ; if ( temp [ ] . contains ( "" ) ) CAPTURE_PATH = temp [ ] + "" + temp [ ] ; else if ( temp [ ] . contains ( "" ) ) { if ( temp [ ] . equals ( "" ) ) MULTI_SNIPPET = true ; else MULTI_SNIPPET = false ; } else if ( temp [ ] . contains ( "" ) ) PASTEBIN_TITLE = temp [ ] ; else if ( temp [ ] . contains ( "" ) ) PASTEBIN_TYPE = temp [ ] ; else if ( temp [ ] . contains ( "" ) ) PASTEBIN_FORMAT = temp [ ] ; else if ( temp [ ] . contains ( "" ) ) PASTEBIN_EXPIRATION = temp [ ] ; else if ( temp [ ] . contains ( "" ) ) PASTEBIN_PRIVACY = Integer . parseInt ( temp [ ] ) ; else if ( temp [ ] . contains ( "" ) ) if ( temp [ ] . equals ( "" ) ) PASTEBIN_GUEST = true ; else PASTEBIN_GUEST = false ; else if ( temp [ ] . contains ( "" ) ) { if ( temp . length > ) PASTEBIN_USERNAME = temp [ ] ; } else if ( temp [ ] . contains ( "" ) ) { if ( temp . length > ) PASTEBIN_PASSWORD = temp [ ] ; } } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } private void createPrefFile ( ) { System . out . println ( "" ) ; try { PrintWriter out = new PrintWriter ( dirDataPath + "" ) ; out . println ( "" + System . getProperty ( "" ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; out . close ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } } } import java . awt . AWTException ; import java . awt . BorderLayout ; import java . awt . Desktop ; import java . awt . Rectangle ; import java . awt . SystemTray ; import java . awt . TrayIcon ; import java . awt . TrayIcon . MessageType ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . io . File ; import java . io . IOException ; import javax . swing . ImageIcon ; import javax . swing . JColorChooser ; import javax . swing . JFrame ; import javax . swing . JMenu ; import javax . swing . JMenuItem ; import javax . swing . JOptionPane ; import javax . swing . JPopupMenu ; import javax . swing . UIManager ; import javax . swing . UnsupportedLookAndFeelException ; import com . melloware . jintellitype . HotkeyListener ; import com . melloware . jintellitype . JIntellitype ; import com . melloware . jintellitype . JIntellitypeConstants ; public class Tray extends JFrame implements ActionListener { private static final long serialVersionUID = - ; OverlayPanel overlayPanel ; Preferences preferences ; Upload upload ; Upload textUpload ; int x1 = , y1 = , x2 = , y2 = ; int screenW , screenH ; Tray tray ; JXTrayIcon trayIcon ; String os = System . getProperty ( "" ) ; JColorChooser colorChooser ; public Tray ( ) { new DataDirectory ( ) ; tray = this ; this . setAlwaysOnTop ( true ) ; if ( ! SystemTray . isSupported ( ) ) { System . out . println ( "" ) ; return ; } try { if ( os . indexOf ( "" ) >= ) JIntellitype . getInstance ( ) . addHotKeyListener ( new HotkeyListener ( ) { @ Override public void onHotKey ( int identifier ) { if ( identifier == ) { overlayPanel . setUploadSnippet ( ) ; } else if ( identifier == ) { overlayPanel . setUploadScreenshot ( ) ; } else if ( identifier == ) { overlayPanel . setSaveSnippet ( ) ; } else if ( identifier == ) { overlayPanel . setSaveScreenshot ( ) ; } else if ( identifier == ) { textUpload = new Upload ( false , tray ) ; } } } ) ; else JOptionPane . showMessageDialog ( null , "" , "" , JOptionPane . WARNING_MESSAGE ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } initializeTray ( ) ; setUndecorated ( true ) ; if ( os . indexOf ( "" ) >= ) registerHotkeys ( ) ; initializeOverlayPanel ( ) ; } private void initializeTray ( ) { String icon ; if ( os . indexOf ( "" ) >= ) icon = "" ; else icon = "" ; ImageIcon ii = new ImageIcon ( this . getClass ( ) . getResource ( "" + icon ) ) ; final JPopupMenu popup = new JPopupMenu ( ) ; trayIcon = new JXTrayIcon ( ii . getImage ( ) ) ; trayIcon . addActionListener ( this ) ; trayIcon . setActionCommand ( "" ) ; final SystemTray tray = SystemTray . getSystemTray ( ) ; JMenu uploadMenu = new JMenu ( "" ) ; uploadMenu . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; JMenu saveMenu = new JMenu ( "" ) ; saveMenu . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; JMenuItem prefMenu = new JMenuItem ( "" ) ; prefMenu . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; prefMenu . addActionListener ( this ) ; prefMenu . setActionCommand ( "" ) ; JMenuItem uScreenshot = new JMenuItem ( "" ) ; uScreenshot . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; uScreenshot . addActionListener ( this ) ; uScreenshot . setActionCommand ( "" ) ; JMenuItem uSnippet = new JMenuItem ( "" ) ; uSnippet . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; uSnippet . addActionListener ( this ) ; uSnippet . setActionCommand ( "" ) ; JMenuItem uClipboard = new JMenuItem ( "" ) ; uClipboard . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; uClipboard . addActionListener ( this ) ; uClipboard . setActionCommand ( "" ) ; JMenuItem sScreenshot = new JMenuItem ( "" ) ; sScreenshot . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; sScreenshot . addActionListener ( this ) ; sScreenshot . setActionCommand ( "" ) ; JMenuItem sSnippet = new JMenuItem ( "" ) ; sSnippet . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; sSnippet . addActionListener ( this ) ; sSnippet . setActionCommand ( "" ) ; JMenuItem multiUploadItem = new JMenuItem ( "" ) ; multiUploadItem . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; multiUploadItem . addActionListener ( this ) ; multiUploadItem . setActionCommand ( "" ) ; JMenuItem exitItem = new JMenuItem ( "" ) ; exitItem . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; exitItem . addActionListener ( this ) ; exitItem . setActionCommand ( "" ) ; JMenuItem aboutItem = new JMenuItem ( "" ) ; aboutItem . setIcon ( new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ) ; aboutItem . addActionListener ( this ) ; aboutItem . setActionCommand ( "" ) ; uploadMenu . add ( uClipboard ) ; uploadMenu . addSeparator ( ) ; uploadMenu . add ( uSnippet ) ; uploadMenu . add ( uScreenshot ) ; uploadMenu . addSeparator ( ) ; uploadMenu . add ( multiUploadItem ) ; saveMenu . add ( sSnippet ) ; saveMenu . addSeparator ( ) ; saveMenu . add ( sScreenshot ) ; popup . add ( aboutItem ) ; popup . add ( prefMenu ) ; popup . addSeparator ( ) ; popup . add ( uploadMenu ) ; popup . add ( saveMenu ) ; popup . addSeparator ( ) ; popup . add ( exitItem ) ; popup . setLightWeightPopupEnabled ( true ) ; trayIcon . setJPopupMenu ( popup ) ; try { tray . add ( trayIcon ) ; trayIcon . displayMessage ( "" , "" , MessageType . INFO ) ; } catch ( AWTException e ) { System . out . println ( "" ) ; } } private void registerHotkeys ( ) { JIntellitype keyhook = JIntellitype . getInstance ( ) ; keyhook . registerHotKey ( , JIntellitypeConstants . MOD_CONTROL + JIntellitypeConstants . MOD_SHIFT , '' ) ; keyhook . registerHotKey ( , JIntellitypeConstants . MOD_CONTROL + JIntellitypeConstants . MOD_SHIFT , '' ) ; keyhook . registerHotKey ( , JIntellitypeConstants . MOD_CONTROL + JIntellitypeConstants . MOD_SHIFT , '' ) ; keyhook . registerHotKey ( , JIntellitypeConstants . MOD_CONTROL + JIntellitypeConstants . MOD_SHIFT , '' ) ; keyhook . registerHotKey ( , JIntellitypeConstants . MOD_ALT + JIntellitypeConstants . MOD_SHIFT , '' ) ; } public void initializeOverlayPanel ( ) { if ( overlayPanel != null ) this . remove ( overlayPanel ) ; Rectangle bounds = new ScreenBounds ( ) . getBounds ( ) ; setBounds ( bounds ) ; overlayPanel = new OverlayPanel ( bounds . width , bounds . height , this ) ; add ( overlayPanel , BorderLayout . CENTER ) ; } public static void main ( String [ ] args ) throws IOException { try { UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; } catch ( UnsupportedLookAndFeelException e ) { } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } new Tray ( ) ; } @ Override public void actionPerformed ( ActionEvent e ) { Object command = e . getActionCommand ( ) ; if ( command . equals ( "" ) ) { overlayPanel . setUploadSnippet ( ) ; } else if ( command . equals ( "" ) ) { overlayPanel . setUploadScreenshot ( ) ; } else if ( command . equals ( "" ) ) { overlayPanel . setSaveSnippet ( ) ; } else if ( command . equals ( "" ) ) { overlayPanel . setSaveScreenshot ( ) ; } else if ( command . equals ( "" ) ) { textUpload = new Upload ( false , tray ) ; } else if ( command . equals ( "" ) ) { new AboutSplash ( ) ; } else if ( command . equals ( "" ) ) { preferences = new Preferences ( ) ; } else if ( command . equals ( "" ) ) { new MultiUploader ( ) ; } else if ( command . equals ( "" ) ) { try { Desktop . getDesktop ( ) . open ( new File ( DataDirectory . CAPTURE_PATH ) ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } } else if ( command . equals ( "" ) ) { System . exit ( ) ; } } } import java . awt . HeadlessException ; import java . awt . Image ; import java . awt . Toolkit ; import java . awt . TrayIcon ; import java . awt . datatransfer . Clipboard ; import java . awt . datatransfer . DataFlavor ; import java . awt . datatransfer . StringSelection ; import java . awt . datatransfer . Transferable ; import java . awt . datatransfer . UnsupportedFlavorException ; import java . awt . image . BufferedImage ; import java . awt . image . RenderedImage ; import java . io . BufferedReader ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . net . URL ; import java . net . URLConnection ; import java . net . URLEncoder ; import javax . imageio . ImageIO ; import org . apache . commons . codec . binary . Base64 ; public class Upload extends Thread { String IMGUR_POST_URI = "" ; String PASTEBIN_URI = "" ; String PASTEBIN_LOGIN_URI = "" ; String PASTEBIN_API_KEY = "" ; String PASTEBIN_USER_KEY ; String IMGUR_API_KEY = "" ; String pastebinError = "" ; String [ ] imgUrl = null ; Transferable t = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . getContents ( null ) ; Thread uploadThread ; BufferedImage image ; Tray tray ; boolean imageUpload = true ; String uploadText ; ByteArrayOutputStream baos ; public Upload ( BufferedImage image , Tray ol , boolean imageUpload ) { this . imageUpload = imageUpload ; this . image = image ; this . tray = ol ; uploadThread = new Thread ( this ) ; uploadThread . start ( ) ; } public Upload ( boolean imageUpload , Tray ol ) { this . tray = ol ; this . imageUpload = imageUpload ; uploadText = getClipboard ( ) ; uploadThread = new Thread ( this ) ; uploadThread . start ( ) ; } public Upload ( ) { } @ Override public void run ( ) { tray . trayIcon . displayMessage ( "" , "" , TrayIcon . MessageType . INFO ) ; if ( imageUpload ) { boolean uploaded = uploadImage ( image ) ; if ( uploaded ) { tray . trayIcon . displayMessage ( "" , "" , TrayIcon . MessageType . INFO ) ; } else tray . trayIcon . displayMessage ( "" , "" , TrayIcon . MessageType . WARNING ) ; } else { boolean uploaded = uploadText ( uploadText ) ; if ( uploaded ) { tray . trayIcon . displayMessage ( "" , "" , TrayIcon . MessageType . INFO ) ; } else tray . trayIcon . displayMessage ( "" , pastebinError , TrayIcon . MessageType . WARNING ) ; } } private Boolean uploadImage ( BufferedImage img ) { try { baos = new ByteArrayOutputStream ( ) ; ImageIO . write ( img , "" , baos ) ; URL url = new URL ( IMGUR_POST_URI ) ; String data = URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( Base64 . encodeBase64String ( baos . toByteArray ( ) ) . toString ( ) , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( IMGUR_API_KEY , "" ) ; URLConnection conn = url . openConnection ( ) ; conn . setDoOutput ( true ) ; OutputStreamWriter wr = new OutputStreamWriter ( conn . getOutputStream ( ) ) ; wr . write ( data ) ; wr . flush ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; String decodedString ; while ( ( decodedString = in . readLine ( ) ) != null ) { System . out . println ( decodedString ) ; imgUrl = decodedString . split ( "" ) ; } imgUrl = imgUrl [ ] . split ( "" ) ; imgUrl [ ] += "" ; setClipboard ( imgUrl [ ] ) ; in . close ( ) ; return true ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return false ; } public String uploadImage ( File file , String type ) { try { baos = new ByteArrayOutputStream ( ) ; Image image = ImageIO . read ( file ) ; ImageIO . write ( ( RenderedImage ) image , type , baos ) ; image = null ; URL url = new URL ( IMGUR_POST_URI ) ; String data = URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( Base64 . encodeBase64String ( baos . toByteArray ( ) ) . toString ( ) , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( IMGUR_API_KEY , "" ) ; URLConnection conn = url . openConnection ( ) ; conn . setDoOutput ( true ) ; OutputStreamWriter wr = new OutputStreamWriter ( conn . getOutputStream ( ) ) ; wr . write ( data ) ; wr . flush ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; String decodedString ; String response = null ; while ( ( decodedString = in . readLine ( ) ) != null ) { response = decodedString ; } in . close ( ) ; baos . close ( ) ; return response ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return "" + type + "" ; } public boolean uploadText ( String text ) { try { baos = new ByteArrayOutputStream ( ) ; URL url ; if ( ! DataDirectory . PASTEBIN_GUEST ) url = new URL ( PASTEBIN_LOGIN_URI ) ; else url = new URL ( PASTEBIN_URI ) ; String data = URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( Base64 . encodeBase64String ( baos . toByteArray ( ) ) . toString ( ) , "" ) ; if ( ! DataDirectory . PASTEBIN_GUEST ) { data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( PASTEBIN_API_KEY , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_USERNAME , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_PASSWORD , "" ) ; URLConnection conn = url . openConnection ( ) ; conn . setDoOutput ( true ) ; OutputStreamWriter wr = new OutputStreamWriter ( conn . getOutputStream ( ) ) ; wr . write ( data ) ; wr . flush ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; String decodedString ; while ( ( decodedString = in . readLine ( ) ) != null ) if ( decodedString . contains ( "" ) ) { pastebinError = decodedString . split ( "" ) [ ] ; return false ; } else { PASTEBIN_USER_KEY = decodedString ; data = URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( Base64 . encodeBase64String ( baos . toByteArray ( ) ) . toString ( ) , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( PASTEBIN_API_KEY , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( PASTEBIN_USER_KEY , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_FORMAT , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_PRIVACY + "" , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_TITLE , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_EXPIRATION , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( text , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_TYPE , "" ) ; url = new URL ( PASTEBIN_URI ) ; conn = url . openConnection ( ) ; conn . setDoOutput ( true ) ; wr = new OutputStreamWriter ( conn . getOutputStream ( ) ) ; wr . write ( data ) ; wr . flush ( ) ; in = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; while ( ( decodedString = in . readLine ( ) ) != null ) setClipboard ( decodedString ) ; return true ; } in . close ( ) ; } else { data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( PASTEBIN_API_KEY , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_FORMAT , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_PRIVACY + "" , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_TITLE , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_EXPIRATION , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( text , "" ) ; data += "" + URLEncoder . encode ( "" , "" ) + "" + URLEncoder . encode ( DataDirectory . PASTEBIN_TYPE , "" ) ; URLConnection conn = url . openConnection ( ) ; conn . setDoOutput ( true ) ; OutputStreamWriter wr = new OutputStreamWriter ( conn . getOutputStream ( ) ) ; wr . write ( data ) ; wr . flush ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; String decodedString ; while ( ( decodedString = in . readLine ( ) ) != null ) if ( decodedString . contains ( "" ) ) setClipboard ( decodedString ) ; in . close ( ) ; return true ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } return false ; } public void setClipboard ( String str ) { StringSelection ss = new StringSelection ( str ) ; Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . setContents ( ss , null ) ; } public static String getClipboard ( ) { Transferable t = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . getContents ( null ) ; try { if ( t != null && t . isDataFlavorSupported ( DataFlavor . stringFlavor ) ) { String text = ( String ) t . getTransferData ( DataFlavor . stringFlavor ) ; return text ; } } catch ( UnsupportedFlavorException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return null ; } } import java . io . File ; public class MultiUploaderThread extends Thread { Thread thread ; MultiUploader mu ; String type ; Upload upload = new Upload ( ) ; File file ; public MultiUploaderThread ( File file , String type , MultiUploader mu ) { this . mu = mu ; this . type = type ; this . file = file ; thread = new Thread ( this ) ; thread . start ( ) ; } public void run ( ) { String response = upload . uploadImage ( file , type ) ; if ( response != null ) { String upLink [ ] = response . split ( "" ) ; upLink = upLink [ ] . split ( "" ) ; upLink [ ] += "" ; String delLink [ ] = response . split ( "" ) ; delLink = delLink [ ] . split ( "" ) ; mu . addLink ( upLink [ ] ) ; mu . addDeletionLink ( delLink [ ] ) ; } else mu . addLink ( "" ) ; } } import java . awt . Graphics ; import java . awt . Image ; import java . awt . MediaTracker ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import javax . swing . ImageIcon ; import javax . swing . JFrame ; public class AboutSplash extends JFrame { private Image image ; public AboutSplash ( ) { MediaTracker mt = new MediaTracker ( this ) ; ImageIcon ii = new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ; image = ii . getImage ( ) ; mt . addImage ( image , ) ; ImageIcon ii2 = new ImageIcon ( this . getClass ( ) . getResource ( "" ) ) ; this . setIconImage ( ii2 . getImage ( ) ) ; setSize ( , ) ; setLocationRelativeTo ( null ) ; setAlwaysOnTop ( true ) ; setTitle ( "" ) ; setResizable ( false ) ; setVisible ( true ) ; addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent we ) { dispose ( ) ; } } ) ; } public void update ( Graphics g ) { paint ( g ) ; } public void paint ( Graphics g ) { if ( image != null ) { g . drawImage ( image , , , this ) ; } else g . clearRect ( , , getSize ( ) . width , getSize ( ) . height ) ; } } import java . awt . GraphicsConfiguration ; import java . awt . GraphicsDevice ; import java . awt . GraphicsEnvironment ; import java . awt . Rectangle ; public class ScreenBounds { public Rectangle getBounds ( ) { GraphicsEnvironment ge = GraphicsEnvironment . getLocalGraphicsEnvironment ( ) ; GraphicsDevice [ ] gs = ge . getScreenDevices ( ) ; Rectangle virtualBounds = new Rectangle ( ) ; for ( GraphicsDevice device : gs ) { GraphicsConfiguration [ ] gc = device . getConfigurations ( ) ; for ( int i = ; i < gc . length ; i ++ ) { virtualBounds = virtualBounds . union ( gc [ i ] . getBounds ( ) ) ; } } return virtualBounds ; } } import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . net . MalformedURLException ; import java . net . URL ; import java . util . Arrays ; public class DataUtils { private String imgur_credit_url = "" ; private int uploads_remaining ; private int uploads_limit ; String response = "" ; public DataUtils ( ) { getImgurDataResponse ( ) ; } public void getImgurDataResponse ( ) { try { URL url = new URL ( imgur_credit_url ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( url . openStream ( ) ) ) ; String line ; while ( ( line = in . readLine ( ) ) != null ) response += line ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } public int getRemainingUploads ( ) { try { String [ ] temp = response . split ( "" ) ; temp = temp [ ] . split ( "" ) ; return ( int ) ( Integer . parseInt ( temp [ ] ) / ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return ; } } public int getRefreshTimeMins ( ) { try { String [ ] temp = response . split ( "" ) ; temp = temp [ ] . split ( "" ) ; return ( int ) ( Integer . parseInt ( temp [ ] ) / ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return ; } } public String getFormat ( String format ) { InputStream is = this . getClass ( ) . getResourceAsStream ( "" ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( is ) ) ; String line ; try { while ( ( line = in . readLine ( ) ) != null ) { } } catch ( IOException e ) { e . printStackTrace ( ) ; } return "" ; } } package com . devtty . gat . test ; import java . io . File ; public class MavenArtifactResolver { private static final String LOCAL_MAVEN_REPO = System . getProperty ( "" ) != null ? System . getProperty ( "" ) : ( System . getProperty ( "" ) + File . separatorChar + "" + File . separatorChar + "" ) ; public static File resolve ( String groupId , String artifactId , String version ) { return new File ( LOCAL_MAVEN_REPO + File . separatorChar + groupId . replace ( "" , File . separator ) + File . separatorChar + artifactId + File . separatorChar + version + File . separatorChar + artifactId + "" + version + "" ) ; } public static File resolve ( String qualifiedArtifactId ) { String [ ] segments = qualifiedArtifactId . split ( "" ) ; return resolve ( segments [ ] , segments [ ] , segments [ ] ) ; } } package com . devtty . gat . test ; import com . devtty . gat . controller . MemberRegistration ; import com . devtty . gat . data . MemberRepository ; import com . devtty . gat . data . MemberRepositoryProducer ; import com . devtty . gat . model . Member ; import javax . enterprise . inject . Produces ; import javax . enterprise . inject . spi . InjectionPoint ; import static org . junit . Assert . * ; import javax . inject . Inject ; import org . jboss . arquillian . api . Deployment ; import org . jboss . arquillian . junit . Arquillian ; import org . jboss . shrinkwrap . api . ShrinkWrap ; import org . jboss . shrinkwrap . api . Archive ; import org . jboss . shrinkwrap . api . spec . WebArchive ; import org . jboss . shrinkwrap . api . asset . ByteArrayAsset ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; @ RunWith ( Arquillian . class ) public class MemberRegistrationTest { @ Deployment public static Archive < ? > createTestArchive ( ) { return ShrinkWrap . create ( WebArchive . class , "" ) . addClasses ( Member . class , MemberRegistration . class , MemberRepository . class , MemberRepositoryProducer . class ) . addWebResource ( "" , "" ) . addWebResource ( new ByteArrayAsset ( new byte [ ] ) , "" ) ; } @ Inject MemberRegistration memberRegistration ; @ Inject Logger log ; @ Test public void testRegister ( ) throws Exception { Member newMember = memberRegistration . getNewMember ( ) ; newMember . setName ( "" ) ; newMember . setEmail ( "" ) ; newMember . setPhoneNumber ( "" ) ; memberRegistration . register ( ) ; assertNotNull ( newMember . getId ( ) ) ; log . info ( newMember . getName ( ) + "" + newMember . getId ( ) ) ; } @ Produces public Logger produceLog ( InjectionPoint injectionPoint ) { return LoggerFactory . getLogger ( injectionPoint . getMember ( ) . getDeclaringClass ( ) ) ; } } package com . devtty . gat . data ; import com . devtty . gat . model . Member ; import javax . annotation . PostConstruct ; import javax . ejb . Singleton ; import javax . ejb . Startup ; import javax . inject . Inject ; import javax . persistence . EntityManager ; import javax . persistence . TransactionRequiredException ; import javax . transaction . UserTransaction ; import org . slf4j . Logger ; @ Startup @ Singleton public class SeedDataImporter { @ Inject private Logger log ; @ Inject @ MemberRepository private EntityManager em ; @ Inject private UserTransaction tx ; @ PostConstruct public void importData ( ) { Member member1 = new Member ( ) ; member1 . setName ( "" ) ; member1 . setEmail ( "" ) ; member1 . setPhoneNumber ( "" ) ; try { try { em . persist ( member1 ) ; } catch ( TransactionRequiredException e ) { tx . begin ( ) ; em . persist ( member1 ) ; tx . commit ( ) ; } log . info ( "" ) ; } catch ( Exception e ) { log . warn ( "" , e ) ; } } } package com . devtty . gat . data ; import com . devtty . gat . model . Member ; import java . util . List ; import javax . annotation . PostConstruct ; import javax . enterprise . context . RequestScoped ; import javax . enterprise . event . Observes ; import javax . enterprise . event . Reception ; import javax . enterprise . inject . Produces ; import javax . inject . Inject ; import javax . inject . Named ; import javax . persistence . EntityManager ; import javax . persistence . criteria . CriteriaBuilder ; import javax . persistence . criteria . CriteriaQuery ; import javax . persistence . criteria . Root ; @ RequestScoped public class MemberListProducer { @ Inject @ MemberRepository private EntityManager em ; private List < Member > members ; @ Produces @ Named public List < Member > getMembers ( ) { return members ; } public void onMemberListChanged ( @ Observes ( notifyObserver = Reception . IF_EXISTS ) final Member member ) { retrieveAllMembersOrderedByName ( ) ; } @ PostConstruct public void retrieveAllMembersOrderedByName ( ) { CriteriaBuilder cb = em . getCriteriaBuilder ( ) ; CriteriaQuery < Member > criteria = cb . createQuery ( Member . class ) ; Root < Member > member = criteria . from ( Member . class ) ; criteria . select ( member ) . orderBy ( cb . asc ( member . get ( "" ) ) ) ; members = em . createQuery ( criteria ) . getResultList ( ) ; } } package com . devtty . gat . data ; import javax . enterprise . inject . Produces ; import javax . persistence . EntityManager ; import javax . persistence . PersistenceContext ; public class MemberRepositoryProducer { @ SuppressWarnings ( "" ) @ Produces @ MemberRepository @ PersistenceContext private EntityManager em ; } package com . devtty . gat . data ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import javax . inject . Qualifier ; @ Qualifier @ Target ( { ElementType . FIELD , ElementType . METHOD , ElementType . PARAMETER } ) @ Retention ( RetentionPolicy . RUNTIME ) public @ interface MemberRepository { } package com . devtty . gat . model ; import java . io . Serializable ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . validation . constraints . NotNull ; @ Entity public class Configuration implements Serializable { private Long id ; private String name ; @ Id @ GeneratedValue public Long getId ( ) { return id ; } public void setId ( Long id ) { this . id = id ; } @ NotNull public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } } package com . devtty . gat . model ; import java . io . Serializable ; import javax . persistence . Column ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . Table ; import javax . persistence . UniqueConstraint ; import javax . validation . constraints . Digits ; import javax . validation . constraints . NotNull ; import javax . validation . constraints . Pattern ; import javax . validation . constraints . Size ; import javax . xml . bind . annotation . XmlRootElement ; import org . hibernate . validator . constraints . Email ; import org . hibernate . validator . constraints . NotEmpty ; @ Entity @ XmlRootElement @ Table ( uniqueConstraints = @ UniqueConstraint ( columnNames = "" ) ) public class Member implements Serializable { private Long id ; private String name ; private String email ; private String phoneNumber ; @ Id @ GeneratedValue public Long getId ( ) { return id ; } public void setId ( Long id ) { this . id = id ; } @ NotNull @ Size ( min = , max = ) @ Pattern ( regexp = "" , message = "" ) public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } @ NotNull @ NotEmpty @ Email public String getEmail ( ) { return email ; } public void setEmail ( String email ) { this . email = email ; } @ NotNull @ Size ( min = , max = ) @ Digits ( fraction = , integer = ) @ Column ( name = "" ) public String getPhoneNumber ( ) { return phoneNumber ; } public void setPhoneNumber ( String phoneNumber ) { this . phoneNumber = phoneNumber ; } private static final long serialVersionUID = ; } package com . devtty . gat . rest ; import javax . ws . rs . ApplicationPath ; import javax . ws . rs . core . Application ; @ ApplicationPath ( "" ) public class JaxRsActivator extends Application { } package com . devtty . gat . rest ; import com . devtty . gat . model . Member ; import com . devtty . gat . data . MemberRepository ; import java . util . List ; import javax . enterprise . context . RequestScoped ; import javax . inject . Inject ; import javax . persistence . EntityManager ; import javax . ws . rs . GET ; import javax . ws . rs . Path ; import javax . ws . rs . PathParam ; @ Path ( "" ) @ RequestScoped public class MemberResourceRESTService { @ Inject @ MemberRepository private EntityManager em ; @ GET public List < Member > listAllMembers ( ) { @ SuppressWarnings ( "" ) final List < Member > results = em . createQuery ( "" ) . getResultList ( ) ; return results ; } @ GET @ Path ( "" ) public Member lookupMemberById ( @ PathParam ( "" ) long id ) { return em . find ( Member . class , id ) ; } } package com . devtty . gat . controller ; import com . devtty . gat . data . MemberRepository ; import com . devtty . gat . model . Member ; import javax . annotation . PostConstruct ; import javax . enterprise . event . Event ; import javax . enterprise . inject . Model ; import javax . enterprise . inject . Produces ; import javax . inject . Inject ; import javax . inject . Named ; import javax . persistence . EntityManager ; import javax . transaction . UserTransaction ; import org . slf4j . Logger ; @ Model public class MemberRegistration { @ Inject private Logger log ; @ Inject @ MemberRepository private EntityManager em ; @ Inject private UserTransaction utx ; @ Inject private Event < Member > memberEventSrc ; private Member newMember ; @ Produces @ Named public Member getNewMember ( ) { return newMember ; } public void register ( ) throws Exception { log . info ( "" + newMember . getName ( ) ) ; utx . begin ( ) ; em . joinTransaction ( ) ; em . persist ( newMember ) ; utx . commit ( ) ; memberEventSrc . fire ( newMember ) ; initNewMember ( ) ; } @ PostConstruct public void initNewMember ( ) { newMember = new Member ( ) ; } } package hudson . jbpm ; import hudson . Extension ; import hudson . Launcher ; import hudson . jbpm . model . ProcessInstanceAction ; import hudson . model . AbstractBuild ; import hudson . model . AbstractProject ; import hudson . model . BuildListener ; import hudson . tasks . BuildStepDescriptor ; import hudson . tasks . BuildStepMonitor ; import hudson . tasks . Notifier ; import hudson . tasks . Publisher ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import net . sf . json . JSONObject ; import org . jbpm . JbpmConfiguration ; import org . jbpm . JbpmContext ; import org . jbpm . graph . def . ProcessDefinition ; import org . jbpm . graph . exe . ProcessInstance ; import org . kohsuke . stapler . DataBoundConstructor ; import org . kohsuke . stapler . StaplerRequest ; public class ProcessStartPublisher extends Notifier { private String processDefinition ; @ DataBoundConstructor public ProcessStartPublisher ( String processDefinition ) { super ( ) ; this . processDefinition = processDefinition ; } public BuildStepMonitor getRequiredMonitorService ( ) { return BuildStepMonitor . STEP ; } @ Override public boolean perform ( AbstractBuild < ? , ? > build , Launcher launcher , BuildListener listener ) throws InterruptedException , IOException { JbpmContext context = JbpmConfiguration . getInstance ( ) . createJbpmContext ( ) ; try { ProcessInstance instance = context . newProcessInstance ( processDefinition ) ; instance . setKey ( build . getParent ( ) . getName ( ) + "" + build . getNumber ( ) ) ; instance . getContextInstance ( ) . setVariable ( "" , build . getProject ( ) ) ; instance . getContextInstance ( ) . setVariable ( "" , build ) ; build . addAction ( new ProcessInstanceAction ( instance . getId ( ) ) ) ; instance . signal ( ) ; context . save ( instance ) ; } finally { context . close ( ) ; } return true ; } public String getProcessDefinition ( ) { return processDefinition ; } @ Override public DescriptorImpl getDescriptor ( ) { return ( DescriptorImpl ) super . getDescriptor ( ) ; } @ Extension public static class DescriptorImpl extends BuildStepDescriptor < Publisher > { @ Override public ProcessStartPublisher newInstance ( StaplerRequest req , JSONObject formData ) throws FormException { return req . bindJSON ( ProcessStartPublisher . class , formData ) ; } public DescriptorImpl ( ) { super ( ProcessStartPublisher . class ) ; } public List < String > getDefinitions ( ) { ArrayList < String > list = new ArrayList < String > ( ) ; for ( ProcessDefinition pd : PluginImpl . INSTANCE . getLatestProcessDefinitions ( ) ) { list . add ( pd . getName ( ) ) ; } return list ; } @ Override public String getDisplayName ( ) { return "" ; } @ Override public boolean isApplicable ( Class < ? extends AbstractProject > jobType ) { return true ; } } } package hudson . jbpm ; import hudson . model . Hudson ; import java . io . ByteArrayInputStream ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . HashMap ; import java . util . Map ; import org . apache . commons . io . IOUtils ; import org . jbpm . file . def . FileDefinition ; import org . jbpm . graph . def . ProcessDefinition ; public class ProcessClassLoaderCache { public static final ProcessClassLoaderCache INSTANCE = new ProcessClassLoaderCache ( ) ; private Map < Long , ClassLoader > cache = new HashMap < Long , ClassLoader > ( ) ; private File cacheRoot = new File ( Hudson . getInstance ( ) . getRootDir ( ) , "" ) ; private ProcessClassLoaderCache ( ) { } public synchronized ClassLoader getClassLoader ( ProcessDefinition def ) throws IOException { ClassLoader cl = cache . get ( def . getId ( ) ) ; if ( cl == null ) { File pdCache = new File ( cacheRoot , Long . toString ( def . getId ( ) ) ) ; if ( ! pdCache . exists ( ) ) { FileDefinition fd = def . getFileDefinition ( ) ; for ( Map . Entry < String , byte [ ] > entry : ( ( Map < String , byte [ ] > ) fd . getBytesMap ( ) ) . entrySet ( ) ) { File f = new File ( pdCache , entry . getKey ( ) ) ; f . getParentFile ( ) . mkdirs ( ) ; FileOutputStream fos = new FileOutputStream ( f ) ; IOUtils . copy ( new ByteArrayInputStream ( entry . getValue ( ) ) , fos ) ; fos . close ( ) ; } } cl = new URLClassLoader ( new URL [ ] { new URL ( pdCache . toURI ( ) . toURL ( ) , "" ) } , Hudson . getInstance ( ) . getPluginManager ( ) . uberClassLoader ) { @ Override public Class < ? > loadClass ( String name ) throws ClassNotFoundException { System . out . println ( name ) ; return super . loadClass ( name ) ; } } ; cache . put ( def . getId ( ) , cl ) ; } return cl ; } } package hudson . jbpm . rendering ; import java . awt . Image ; import java . awt . Toolkit ; import java . awt . geom . Line2D ; import java . awt . geom . Point2D ; import java . awt . geom . Rectangle2D ; import org . jbpm . graph . def . Node ; public class GraphicsUtil { private static Image endImage ; private static Image startImage ; private static Image joinImage ; private static Image forkImage ; private static Image taskImage ; private static Image mailImage ; private static Image nodeImage ; private static Image decisionImage ; public static boolean getLineRectangleIntersection ( Rectangle2D . Double rect , Line2D . Double line , Point2D . Double intersection ) { Line2D . Double top = new Line2D . Double ( rect . x , rect . y , rect . x + rect . width , rect . y ) ; Line2D . Double bottom = new Line2D . Double ( rect . x , rect . y + rect . height , rect . x + rect . width , rect . y + rect . height ) ; Line2D . Double left = new Line2D . Double ( rect . x , rect . y , rect . x , rect . y + rect . height ) ; Line2D . Double right = new Line2D . Double ( rect . x + rect . width , rect . y , rect . x + rect . width , rect . y + rect . height ) ; return getLineLineIntersection ( line , top , intersection ) || getLineLineIntersection ( line , bottom , intersection ) || getLineLineIntersection ( line , left , intersection ) || getLineLineIntersection ( line , right , intersection ) ; } public static boolean getLineLineIntersection ( Line2D . Double l1 , Line2D . Double l2 , Point2D . Double intersection ) { if ( ! l1 . intersectsLine ( l2 ) ) return false ; double x1 = l1 . getX1 ( ) , y1 = l1 . getY1 ( ) , x2 = l1 . getX2 ( ) , y2 = l1 . getY2 ( ) , x3 = l2 . getX1 ( ) , y3 = l2 . getY1 ( ) , x4 = l2 . getX2 ( ) , y4 = l2 . getY2 ( ) ; intersection . x = det ( det ( x1 , y1 , x2 , y2 ) , x1 - x2 , det ( x3 , y3 , x4 , y4 ) , x3 - x4 ) / det ( x1 - x2 , y1 - y2 , x3 - x4 , y3 - y4 ) ; intersection . y = det ( det ( x1 , y1 , x2 , y2 ) , y1 - y2 , det ( x3 , y3 , x4 , y4 ) , y3 - y4 ) / det ( x1 - x2 , y1 - y2 , x3 - x4 , y3 - y4 ) ; return true ; } public static double det ( double a , double b , double c , double d ) { return a * d - b * c ; } static { Toolkit toolkit = Toolkit . getDefaultToolkit ( ) ; taskImage = toolkit . getImage ( GraphicsUtil . class . getResource ( "" ) ) ; forkImage = toolkit . getImage ( GraphicsUtil . class . getResource ( "" ) ) ; joinImage = toolkit . getImage ( GraphicsUtil . class . getResource ( "" ) ) ; startImage = toolkit . getImage ( GraphicsUtil . class . getResource ( "" ) ) ; mailImage = toolkit . getImage ( GraphicsUtil . class . getResource ( "" ) ) ; nodeImage = toolkit . getImage ( GraphicsUtil . class . getResource ( "" ) ) ; decisionImage = toolkit . getImage ( GraphicsUtil . class . getResource ( "" ) ) ; endImage = toolkit . getImage ( GraphicsUtil . class . getResource ( "" ) ) ; } public static Image getImage ( Node node ) { String s = node . toString ( ) ; if ( s . startsWith ( "" ) ) { return taskImage ; } else if ( s . startsWith ( "" ) ) { return joinImage ; } else if ( s . startsWith ( "" ) ) { return startImage ; } else if ( s . startsWith ( "" ) ) { return endImage ; } else if ( s . startsWith ( "" ) ) { return forkImage ; } else if ( s . startsWith ( "" ) ) { return mailImage ; } else if ( s . startsWith ( "" ) ) { return nodeImage ; } else if ( s . startsWith ( "" ) ) { return decisionImage ; } else if ( s . startsWith ( "" ) ) { return decisionImage ; } else if ( s . startsWith ( "" ) ) { return decisionImage ; } else { return null ; } } } package hudson . jbpm . rendering ; import hudson . jbpm . model . gpd . BendPoint ; import hudson . jbpm . model . gpd . Edge ; import hudson . jbpm . model . gpd . GPD ; import hudson . jbpm . model . gpd . NodeState ; import java . awt . BasicStroke ; import java . awt . Color ; import java . awt . Font ; import java . awt . GradientPaint ; import java . awt . Graphics ; import java . awt . Graphics2D ; import java . awt . Image ; import java . awt . Polygon ; import java . awt . RenderingHints ; import java . awt . geom . Line2D ; import java . awt . geom . Point2D ; import java . awt . geom . Rectangle2D ; import java . util . List ; import java . util . Map ; import javax . swing . JComponent ; import org . dom4j . DocumentException ; import org . jbpm . JbpmConfiguration ; import org . jbpm . graph . def . Node ; import org . jbpm . graph . def . ProcessDefinition ; import org . jbpm . graph . def . Transition ; import org . jbpm . graph . exe . ProcessInstance ; import org . jbpm . graph . exe . Token ; import org . jbpm . graph . log . TokenCreateLog ; import org . jbpm . graph . log . TransitionLog ; import org . jbpm . logging . log . ProcessLog ; import org . jbpm . taskmgmt . log . TaskCreateLog ; public final class ProcessInstanceRenderer extends JComponent { private static Color LINE_COLOR = new Color ( , , ) ; private static final Color TEXT_COLOR = Color . BLACK ; private static final Font FONT = new Font ( "" , Font . BOLD , ) ; private static final Color NODE_COLOR_1 = new Color ( , , ) ; private static final Color NODE_COLOR_2 = Color . WHITE ; private final ProcessDefinition def ; private final GPD gpd ; public ProcessInstanceRenderer ( ProcessInstance processInstance , GPD gpd ) throws DocumentException { def = processInstance . getProcessDefinition ( ) ; this . gpd = gpd ; Map < Token , List < ProcessLog > > logs = JbpmConfiguration . getInstance ( ) . getCurrentJbpmContext ( ) . getLoggingSession ( ) . findLogsByProcessInstance ( processInstance . getId ( ) ) ; handleLog ( logs , processInstance . getRootToken ( ) ) ; setBackground ( Color . WHITE ) ; setOpaque ( true ) ; setSize ( gpd . getWidth ( ) , gpd . getHeight ( ) ) ; } private void handleLog ( Map < Token , List < ProcessLog > > logs , Token token ) { List < ProcessLog > list = logs . get ( token ) ; for ( ProcessLog log : list ) { if ( log instanceof TransitionLog ) { String source = ( ( TransitionLog ) log ) . getSourceNode ( ) . getName ( ) ; String target = ( ( TransitionLog ) log ) . getDestinationNode ( ) . getName ( ) ; gpd . getNode ( source ) . setState ( NodeState . Completed ) ; gpd . getNode ( target ) . setState ( NodeState . Entered ) ; } else if ( log instanceof TokenCreateLog ) { Token subToken = ( ( TokenCreateLog ) log ) . getChild ( ) ; handleLog ( logs , subToken ) ; } else if ( log instanceof TaskCreateLog ) { gpd . getNode ( ( ( TaskCreateLog ) log ) . getTaskInstance ( ) . getTask ( ) . getTaskNode ( ) . getName ( ) ) . setState ( NodeState . TaskCreated ) ; } } } @ Override public void paint ( Graphics g ) { Graphics2D g2 = ( Graphics2D ) g ; g2 . setBackground ( Color . WHITE ) ; g2 . clearRect ( , , getWidth ( ) , getHeight ( ) ) ; Map < String , Node > tasks = def . getNodesMap ( ) ; for ( Map . Entry < String , Node > entry : tasks . entrySet ( ) ) { List < Transition > transitions = entry . getValue ( ) . getLeavingTransitions ( ) ; for ( int i = ; transitions != null && i < transitions . size ( ) ; i ++ ) { Transition transition = transitions . get ( i ) ; String from = transition . getFrom ( ) . getName ( ) ; String to = transition . getTo ( ) . getName ( ) ; Edge edge = gpd . getNode ( from ) . getEdge ( i ) ; paintLine ( g2 , gpd . getNode ( from ) . asRectangle ( ) , gpd . getNode ( to ) . asRectangle ( ) , edge , transition . getName ( ) ) ; } } for ( Map . Entry < String , Node > entry : tasks . entrySet ( ) ) { Node task = tasks . get ( entry . getKey ( ) ) ; Rectangle2D . Double rect = gpd . getNode ( task . getName ( ) ) . asRectangle ( ) ; paintTask ( g2 , task , rect ) ; } } public static void paintLine ( Graphics2D g2 , Rectangle2D . Double from , Rectangle2D . Double to , Edge edge , String label ) { List < BendPoint > bendPoints = edge . getBendPoints ( ) ; Point2D . Double fromRectCenter = new Point2D . Double ( from . getCenterX ( ) , from . getCenterY ( ) ) ; Point2D . Double toRectCenter = new Point2D . Double ( to . getCenterX ( ) , to . getCenterY ( ) ) ; Point2D . Double startPoint = fromRectCenter ; Point2D . Double endPoint ; for ( int i = ; i < bendPoints . size ( ) + ; i ++ ) { endPoint = getPoint ( i , fromRectCenter , bendPoints , toRectCenter ) ; Line2D . Double line = new Line2D . Double ( startPoint , endPoint ) ; Point2D . Double intersection = new Point2D . Double ( ) ; if ( GraphicsUtil . getLineRectangleIntersection ( from , line , intersection ) ) { line . x1 = intersection . x ; line . y1 = intersection . y ; } if ( GraphicsUtil . getLineRectangleIntersection ( to , line , intersection ) ) { line . x2 = intersection . x ; line . y2 = intersection . y ; } drawArrow ( g2 , line , , endPoint == toRectCenter ) ; startPoint = endPoint ; } if ( label != null ) { Point2D . Double labelPoint = new Point2D . Double ( ) ; int count = bendPoints . size ( ) + ; if ( count % == ) { Point2D . Double a = getPoint ( count / - , fromRectCenter , bendPoints , toRectCenter ) ; Point2D . Double b = getPoint ( count / , fromRectCenter , bendPoints , toRectCenter ) ; labelPoint . x = ( a . x + b . x ) / + edge . getLabel ( ) . getX ( ) ; labelPoint . y = ( a . y + b . y ) / + edge . getLabel ( ) . getY ( ) ; } else { Point2D . Double a = getPoint ( count / , fromRectCenter , bendPoints , toRectCenter ) ; labelPoint . x = a . x + edge . getLabel ( ) . getX ( ) ; labelPoint . y = a . y + edge . getLabel ( ) . getY ( ) ; } g2 . setColor ( Color . BLACK ) ; int textHeight = g2 . getFontMetrics ( ) . getAscent ( ) ; g2 . drawString ( label , ( int ) labelPoint . x , ( int ) labelPoint . y + textHeight ) ; } } private static Point2D . Double getPoint ( int i , Point2D . Double start , List < BendPoint > bendPoints , Point2D . Double end ) { if ( i == ) { return start ; } if ( i == bendPoints . size ( ) + ) { return end ; } BendPoint bp = bendPoints . get ( i - ) ; return new Point2D . Double ( start . x + bp . getW1 ( ) , start . y + bp . getH1 ( ) ) ; } public void paintTask ( Graphics2D g2 , Node node , Rectangle2D . Double rect ) { g2 . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; Color nodeColor = getNodeColor ( node ) ; g2 . setPaint ( new GradientPaint ( new Point2D . Double ( rect . x , rect . y ) , nodeColor , new Point2D . Double ( rect . x , rect . y + rect . height ) , NODE_COLOR_2 ) ) ; g2 . fill ( rect ) ; g2 . setPaint ( LINE_COLOR ) ; g2 . draw ( rect ) ; double imageY = rect . y + rect . height / - / ; Image image = GraphicsUtil . getImage ( node ) ; if ( image != null ) { int w = image . getWidth ( null ) ; int h = image . getHeight ( null ) ; g2 . drawImage ( image , ( int ) rect . x + , ( int ) imageY , ( int ) rect . x + + w , ( int ) imageY + h , , , w , h , this ) ; } int textWidth = g2 . getFontMetrics ( ) . stringWidth ( node . getName ( ) ) ; int textHeight = g2 . getFontMetrics ( ) . getAscent ( ) ; g2 . setColor ( TEXT_COLOR ) ; g2 . setFont ( FONT ) ; g2 . drawString ( node . getName ( ) , ( int ) ( rect . x + + ( rect . width - textWidth ) / ) , ( int ) ( rect . y + ( rect . height + textHeight ) / ) ) ; } public static void drawArrow ( Graphics2D g2d , Line2D . Double line , float stroke , boolean arrow ) { int xCenter = ( int ) line . getX1 ( ) ; int yCenter = ( int ) line . getY1 ( ) ; double x = line . getX2 ( ) ; double y = line . getY2 ( ) ; double aDir = Math . atan2 ( xCenter - x , yCenter - y ) ; int i1 = + ( int ) ( stroke * ) ; int i2 = + ( int ) stroke ; Line2D . Double base = new Line2D . Double ( x + xCor ( i1 , aDir + ) , y + yCor ( i1 , aDir + ) , x + xCor ( i1 , aDir - ) , y + yCor ( i1 , aDir - ) ) ; Point2D . Double intersect = new Point2D . Double ( ) ; GraphicsUtil . getLineLineIntersection ( line , base , intersect ) ; g2d . setPaint ( LINE_COLOR ) ; if ( arrow ) { g2d . draw ( new Line2D . Double ( xCenter , yCenter , intersect . x , intersect . y ) ) ; g2d . setStroke ( new BasicStroke ( ) ) ; Polygon tmpPoly = new Polygon ( ) ; tmpPoly . addPoint ( ( int ) x , ( int ) y ) ; tmpPoly . addPoint ( ( int ) x + xCor ( i1 , aDir + ) , ( int ) y + yCor ( i1 , aDir + ) ) ; tmpPoly . addPoint ( ( int ) x + xCor ( i1 , aDir - ) , ( int ) y + yCor ( i1 , aDir - ) ) ; tmpPoly . addPoint ( ( int ) x , ( int ) y ) ; g2d . drawPolygon ( tmpPoly ) ; } else { g2d . draw ( new Line2D . Double ( xCenter , yCenter , x , y ) ) ; } } private static int yCor ( int len , double dir ) { return ( int ) ( len * Math . cos ( dir ) ) ; } private static int xCor ( int len , double dir ) { return ( int ) ( len * Math . sin ( dir ) ) ; } private Color getNodeColor ( Node node ) { NodeState state = gpd . getNode ( node . getName ( ) ) . getState ( ) ; if ( state == NodeState . Entered ) { return new Color ( , , ) ; } else if ( state == NodeState . Started ) { return new Color ( , , ) ; } else if ( state == NodeState . Completed ) { return new Color ( , , ) ; } else if ( state == NodeState . TaskCreated ) { return new Color ( , , ) ; } else { return NODE_COLOR_1 ; } } } package hudson . jbpm ; import hudson . Plugin ; import hudson . jbpm . model . TaskInstanceWrapper ; import hudson . jbpm . rendering . GraphicsUtil ; import hudson . model . Hudson ; import hudson . model . Job ; import hudson . model . TopLevelItem ; import hudson . util . PluginServletFilter ; import java . awt . Graphics2D ; import java . awt . image . BufferedImage ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . logging . Logger ; import java . util . zip . ZipInputStream ; import javax . imageio . ImageIO ; import javax . servlet . ServletException ; import javax . servlet . ServletOutputStream ; import org . acegisecurity . Authentication ; import org . acegisecurity . userdetails . UserDetails ; import org . apache . commons . fileupload . FileItem ; import org . apache . commons . fileupload . FileUploadException ; import org . apache . commons . fileupload . disk . DiskFileItemFactory ; import org . apache . commons . fileupload . servlet . ServletFileUpload ; import org . jbpm . JbpmConfiguration ; import org . jbpm . JbpmContext ; import org . jbpm . context . exe . ContextInstance ; import org . jbpm . db . TaskMgmtSession ; import org . jbpm . file . def . FileDefinition ; import org . jbpm . graph . def . ProcessDefinition ; import org . jbpm . graph . exe . ProcessInstance ; import org . jbpm . taskmgmt . exe . TaskInstance ; import org . kohsuke . stapler . QueryParameter ; import org . kohsuke . stapler . StaplerRequest ; import org . kohsuke . stapler . StaplerResponse ; public class PluginImpl extends Plugin { private static Logger log = Logger . getLogger ( "" ) ; public static PluginImpl INSTANCE ; private ProcessDefinition processDefinition ; public ProcessDefinition getProcessDefinition ( ) { return processDefinition ; } public PluginImpl ( ) { } @ Override public void start ( ) throws Exception { JbpmConfiguration . getInstance ( ) . startJobExecutor ( ) ; PluginServletFilter . addFilter ( new JbpmContextFilter ( ) ) ; GraphicsUtil . class . getName ( ) ; INSTANCE = this ; } public List < ProcessDefinition > getProcessDefinitions ( ) { JbpmContext context = getCurrentJbpmContext ( ) ; return context . getGraphSession ( ) . findAllProcessDefinitions ( ) ; } public List < ProcessDefinition > getLatestProcessDefinitions ( ) { JbpmContext context = getCurrentJbpmContext ( ) ; return context . getGraphSession ( ) . findLatestProcessDefinitions ( ) ; } public ProcessInstance getProcessInstance ( long processInstanceId ) { JbpmContext context = getCurrentJbpmContext ( ) ; return context . getGraphSession ( ) . getProcessInstance ( processInstanceId ) ; } public List < ProcessInstance > getProcessInstances ( ProcessDefinition definition ) { JbpmContext context = getCurrentJbpmContext ( ) ; return context . getGraphSession ( ) . findProcessInstances ( definition . getId ( ) ) ; } public TaskInstanceWrapper getTaskInstance ( String taskInstanceId ) { long l = Long . parseLong ( taskInstanceId ) ; return new TaskInstanceWrapper ( getCurrentJbpmContext ( ) . getTaskInstance ( l ) ) ; } private static JbpmContext getCurrentJbpmContext ( ) { return JbpmConfiguration . getInstance ( ) . getCurrentJbpmContext ( ) ; } public List < TaskInstance > getOpenTasks ( ProcessInstance processInstance ) { JbpmContext context = getCurrentJbpmContext ( ) ; List < TaskInstance > result = context . getTaskMgmtSession ( ) . findTaskInstancesByProcessInstance ( processInstance ) ; return result ; } public List < TaskInstance > getPooledTasks ( ) { JbpmContext context = getCurrentJbpmContext ( ) ; TaskMgmtSession taskMgmtSession = context . getTaskMgmtSession ( ) ; if ( ! Hudson . getAuthentication ( ) . isAuthenticated ( ) ) { return Collections . emptyList ( ) ; } List < String > projectNames = new ArrayList < String > ( ) ; for ( TopLevelItem item : Hudson . getInstance ( ) . getItems ( ) ) { if ( ( item instanceof Job ) && ( ( Job ) item ) . hasPermission ( Job . CONFIGURE ) ) { projectNames . add ( item . getName ( ) ) ; } } if ( projectNames . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < TaskInstance > result = taskMgmtSession . findPooledTaskInstances ( projectNames ) ; return result ; } public void doProcessDefinitionImage ( StaplerRequest req , StaplerResponse rsp , @ QueryParameter ( "" ) long processDefinition ) throws IOException { JbpmContext context = getCurrentJbpmContext ( ) ; ProcessDefinition definition = context . getGraphSession ( ) . getProcessDefinition ( processDefinition ) ; FileDefinition fd = definition . getFileDefinition ( ) ; byte [ ] bytes = fd . getBytes ( "" ) ; rsp . setContentType ( "" ) ; ServletOutputStream output = rsp . getOutputStream ( ) ; BufferedImage loaded = ImageIO . read ( new ByteArrayInputStream ( bytes ) ) ; BufferedImage aimg = new BufferedImage ( loaded . getWidth ( ) , loaded . getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; Graphics2D g = aimg . createGraphics ( ) ; g . drawImage ( loaded , null , , ) ; g . dispose ( ) ; ImageIO . write ( aimg , "" , output ) ; output . flush ( ) ; output . close ( ) ; } public void doUpload ( StaplerRequest req , StaplerResponse rsp ) throws FileUploadException , IOException , ServletException { try { ServletFileUpload upload = new ServletFileUpload ( new DiskFileItemFactory ( ) ) ; FileItem fileItem = ( FileItem ) upload . parseRequest ( req ) . get ( ) ; if ( fileItem . getContentType ( ) . indexOf ( "" ) == - ) { throw new IOException ( "" ) ; } log . fine ( "" + fileItem . getName ( ) ) ; ZipInputStream zipInputStream = new ZipInputStream ( fileItem . getInputStream ( ) ) ; JbpmContext jbpmContext = getCurrentJbpmContext ( ) ; log . fine ( "" ) ; ProcessDefinition processDefinition = ProcessDefinition . parseParZipInputStream ( zipInputStream ) ; log . fine ( "" + processDefinition . getName ( ) ) ; jbpmContext . deployProcessDefinition ( processDefinition ) ; zipInputStream . close ( ) ; rsp . forwardToPreviousPage ( req ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } @ Override public void stop ( ) throws Exception { JbpmConfiguration . getInstance ( ) . getJobExecutor ( ) . stop ( ) ; } public List < TaskInstance > getUserTasks ( ) { Authentication authentication = Hudson . getAuthentication ( ) ; if ( "" . equals ( authentication . getPrincipal ( ) ) ) { return Collections . emptyList ( ) ; } JbpmContext context = getCurrentJbpmContext ( ) ; String userName = ( ( UserDetails ) authentication . getPrincipal ( ) ) . getUsername ( ) ; return context . getTaskList ( userName ) ; } public static void injectTransientVariables ( ContextInstance contextInstance ) { contextInstance . setTransientVariable ( "" , Hudson . getInstance ( ) ) ; } } package hudson . jbpm ; import java . util . logging . Logger ; import hudson . Extension ; import hudson . model . AbstractBuild ; import hudson . model . ParametersAction ; import hudson . model . Run ; import hudson . model . TaskListener ; import hudson . model . listeners . RunListener ; import org . jbpm . JbpmConfiguration ; import org . jbpm . JbpmContext ; import org . jbpm . taskmgmt . exe . TaskInstance ; @ Extension public class HudsonRunListener extends RunListener { private static Logger log = Logger . getLogger ( HudsonRunListener . class . getName ( ) ) ; public HudsonRunListener ( ) { super ( AbstractBuild . class ) ; } @ Override public synchronized void onCompleted ( Run r , TaskListener listener ) { ParametersAction parameters = r . getAction ( ParametersAction . class ) ; if ( parameters == null ) { return ; } String task = ( String ) parameters . getValue ( "" ) ; if ( task == null ) { return ; } long taskInstanceId = Integer . parseInt ( task ) ; JbpmContext context = JbpmConfiguration . getInstance ( ) . createJbpmContext ( ) ; try { TaskInstance taskInstance = context . loadTaskInstance ( taskInstanceId ) ; PluginImpl . injectTransientVariables ( taskInstance . getProcessInstance ( ) . getContextInstance ( ) ) ; taskInstance . setVariableLocally ( "" , r . getResult ( ) . toString ( ) ) ; taskInstance . end ( ) ; context . save ( taskInstance ) ; return ; } catch ( Exception e ) { e . printStackTrace ( listener . error ( "" + getClass ( ) . getName ( ) ) ) ; } finally { context . close ( ) ; } } @ Override public synchronized void onStarted ( Run r , TaskListener listener ) { ParametersAction parameters = r . getAction ( ParametersAction . class ) ; if ( parameters == null ) { return ; } String task = ( String ) parameters . getValue ( "" ) ; if ( task == null ) { return ; } long taskInstanceId = Integer . parseInt ( task ) ; JbpmContext context = JbpmConfiguration . getInstance ( ) . createJbpmContext ( ) ; try { TaskInstance taskInstance = context . getTaskInstance ( taskInstanceId ) ; if ( taskInstance == null ) { System . err . println ( "" + taskInstanceId ) ; } PluginImpl . injectTransientVariables ( taskInstance . getContextInstance ( ) ) ; taskInstance . setVariableLocally ( "" , r ) ; taskInstance . start ( ) ; context . save ( taskInstance ) ; } finally { context . close ( ) ; } } } package hudson . jbpm ; import hudson . model . Hudson ; import java . io . IOException ; import java . io . Serializable ; import java . security . Principal ; import javax . servlet . Filter ; import javax . servlet . FilterChain ; import javax . servlet . FilterConfig ; import javax . servlet . ServletException ; import javax . servlet . ServletRequest ; import javax . servlet . ServletResponse ; import javax . servlet . http . HttpServletRequest ; import org . acegisecurity . Authentication ; import org . jbpm . JbpmConfiguration ; import org . jbpm . JbpmContext ; public class JbpmContextFilter implements Filter , Serializable { private static final long serialVersionUID = ; String jbpmConfigurationResource = null ; String jbpmContextName = null ; boolean isAuthenticationEnabled = true ; public void init ( FilterConfig filterConfig ) throws ServletException { this . jbpmConfigurationResource = filterConfig . getInitParameter ( "" ) ; this . jbpmContextName = filterConfig . getInitParameter ( "" ) ; if ( jbpmContextName == null ) { jbpmContextName = JbpmContext . DEFAULT_JBPM_CONTEXT_NAME ; } String isAuthenticationEnabledText = filterConfig . getInitParameter ( "" ) ; if ( ( isAuthenticationEnabledText != null ) && ( "" . equalsIgnoreCase ( isAuthenticationEnabledText ) ) ) { isAuthenticationEnabled = false ; } } public void doFilter ( ServletRequest servletRequest , ServletResponse servletResponse , FilterChain filterChain ) throws IOException , ServletException { String actorId = null ; if ( servletRequest instanceof HttpServletRequest ) { HttpServletRequest httpServletRequest = ( HttpServletRequest ) servletRequest ; Principal userPrincipal = httpServletRequest . getUserPrincipal ( ) ; if ( userPrincipal != null ) { actorId = userPrincipal . getName ( ) ; } } if ( actorId == null ) { Authentication auth = Hudson . getAuthentication ( ) ; if ( auth != null ) { actorId = auth . getName ( ) ; } } JbpmContext jbpmContext = getJbpmConfiguration ( ) . createJbpmContext ( jbpmContextName ) ; try { if ( isAuthenticationEnabled ) { jbpmContext . setActorId ( actorId ) ; } filterChain . doFilter ( servletRequest , servletResponse ) ; } finally { jbpmContext . close ( ) ; } } protected JbpmConfiguration getJbpmConfiguration ( ) { return JbpmConfiguration . getInstance ( jbpmConfigurationResource ) ; } public void destroy ( ) { } } package hudson . jbpm ; import hudson . Extension ; import hudson . model . AbstractProject ; import hudson . model . Hudson ; import hudson . model . ParameterValue ; import hudson . model . ParameterizedProjectTask ; import hudson . model . PeriodicWork ; import hudson . model . Run ; import hudson . model . RunParameterValue ; import hudson . model . StringParameterValue ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . logging . Level ; import java . util . logging . Logger ; import org . jbpm . JbpmConfiguration ; import org . jbpm . JbpmContext ; import org . jbpm . taskmgmt . exe . TaskInstance ; @ Extension public class HudsonTaskListener extends PeriodicWork { private static Logger log = Logger . getLogger ( HudsonTaskListener . class . getName ( ) ) ; @ Override public long getRecurrencePeriod ( ) { return ; } @ Override protected void doRun ( ) { JbpmContext context = JbpmConfiguration . getInstance ( ) . createJbpmContext ( ) ; try { List < TaskInstance > tasks = context . getTaskMgmtSession ( ) . findTaskInstances ( "" ) ; for ( TaskInstance task : tasks ) { if ( task . getStart ( ) == null ) { try { scheduleBuild ( task ) ; } catch ( Exception e ) { log . log ( Level . WARNING , "" + task . getId ( ) , e ) ; } } } } finally { context . close ( ) ; } } private void scheduleBuild ( TaskInstance task ) { Run < ? , ? > run = ( Run < ? , ? > ) task . getContextInstance ( ) . getVariable ( "" ) ; String projectName = ( String ) task . getVariableLocally ( "" ) ; if ( projectName == null ) { return ; } AbstractProject < ? , ? > project = ( AbstractProject < ? , ? > ) Hudson . getInstance ( ) . getItem ( projectName . trim ( ) ) ; List < ParameterValue > parameters = new ArrayList < ParameterValue > ( ) ; RunParameterValue runParameter = new RunParameterValue ( "" , run . getId ( ) ) ; StringParameterValue taskParameter = new StringParameterValue ( "" , Long . toString ( task . getId ( ) ) ) ; parameters . add ( runParameter ) ; parameters . add ( taskParameter ) ; for ( Map . Entry entry : ( ( Set < Map . Entry > ) task . getVariablesLocally ( ) . entrySet ( ) ) ) { if ( entry . getValue ( ) instanceof String ) { parameters . add ( new StringParameterValue ( ( String ) entry . getKey ( ) , ( String ) entry . getValue ( ) ) ) ; } } Hudson . getInstance ( ) . getQueue ( ) . add ( new ParameterizedProjectTask ( project , parameters ) , ) ; } } package hudson . jbpm . hibernate ; import hudson . model . Hudson ; import hudson . model . Job ; import hudson . model . Run ; import org . jbpm . context . exe . Converter ; public class RunToStringConverter implements Converter { private static final long serialVersionUID = ; public boolean supports ( Object value ) { if ( value == null ) return true ; return Run . class . isAssignableFrom ( value . getClass ( ) ) ; } public Object convert ( Object o ) { Run < ? , ? > run = ( Run < ? , ? > ) o ; Job < ? , ? > job = run . getParent ( ) ; String convertedValue = job . getName ( ) + "" + run . getNumber ( ) ; return convertedValue ; } public Object revert ( Object o ) { String id = ( String ) o ; int hash = id . lastIndexOf ( '' ) ; String jobName = id . substring ( , hash ) ; String runNumber = id . substring ( hash + ) ; Job < ? , ? > job = ( Job < ? , ? > ) Hudson . getInstance ( ) . getItem ( jobName ) ; Run < ? , ? > run = job . getBuildByNumber ( Integer . parseInt ( runNumber ) ) ; return run ; } } package hudson . jbpm . hibernate ; import hudson . model . Hudson ; import hudson . model . Job ; import org . jbpm . context . exe . Converter ; public class JobToStringConverter implements Converter { private static final long serialVersionUID = ; public boolean supports ( Object value ) { if ( value == null ) return true ; return Job . class . isAssignableFrom ( value . getClass ( ) ) ; } public Object convert ( Object o ) { Job job = ( Job ) o ; String convertedValue = job . getName ( ) ; return convertedValue ; } public Object revert ( Object o ) { String name = ( String ) o ; return Hudson . getInstance ( ) . getItem ( name ) ; } } package hudson . jbpm . workflow ; import hudson . model . Job ; import org . jbpm . graph . exe . ExecutionContext ; import org . jbpm . taskmgmt . def . AssignmentHandler ; import org . jbpm . taskmgmt . exe . Assignable ; public class ProjectMemberAssignmentHandler implements AssignmentHandler { public void assign ( Assignable assignable , ExecutionContext executionContext ) throws Exception { Job < ? , ? > job = ( Job < ? , ? > ) executionContext . getTaskInstance ( ) . getVariable ( "" ) ; assignable . setPooledActors ( new String [ ] { job . getName ( ) } ) ; } } package hudson . jbpm . workflow ; import org . jbpm . graph . def . ActionHandler ; import org . jbpm . graph . exe . ExecutionContext ; import org . jbpm . taskmgmt . exe . TaskInstance ; public class FormActionHandler implements ActionHandler { private String formClass ; public String getFormClass ( ) { return formClass ; } public void setFormClass ( String formClass ) { this . formClass = formClass ; } public void execute ( ExecutionContext executionContext ) throws Exception { TaskInstance task = executionContext . getTaskInstance ( ) ; task . setVariableLocally ( "" , formClass ) ; } } package hudson . jbpm . workflow ; import org . jbpm . graph . def . ActionHandler ; import org . jbpm . graph . exe . ExecutionContext ; public class StartProjectActionHandler implements ActionHandler { private static final long serialVersionUID = - ; private String projectName ; public StartProjectActionHandler ( ) { } public StartProjectActionHandler ( String projectName ) { this . projectName = projectName ; } public void execute ( ExecutionContext executionContext ) throws Exception { executionContext . getTaskInstance ( ) . setVariableLocally ( "" , projectName ) ; } public String getProjectName ( ) { return projectName ; } public void setProjectName ( String projectName ) { this . projectName = projectName ; } } package hudson . jbpm . model ; import hudson . jbpm . PluginImpl ; import java . io . IOException ; import javax . servlet . ServletException ; import org . jbpm . taskmgmt . exe . TaskInstance ; import org . kohsuke . stapler . StaplerRequest ; import org . kohsuke . stapler . StaplerResponse ; public class Form { private final TaskInstance taskInstance ; public Form ( TaskInstance taskInstance ) { super ( ) ; this . taskInstance = taskInstance ; } public TaskInstance getTaskInstance ( ) { return taskInstance ; } public void handle ( StaplerRequest request , StaplerResponse response ) throws ServletException , IOException { } public void doSubmit ( StaplerRequest request , StaplerResponse response ) throws ServletException , IOException { request . bindParameters ( this ) ; PluginImpl . injectTransientVariables ( taskInstance . getContextInstance ( ) ) ; handle ( request , response ) ; response . forwardToPreviousPage ( request ) ; } } package hudson . jbpm . model ; import java . util . List ; import org . jbpm . taskmgmt . exe . TaskInstance ; import hudson . Extension ; import hudson . jbpm . PluginImpl ; import hudson . widgets . Widget ; @ Extension public class UserTasks extends Widget { @ Override public String getUrlName ( ) { return "" ; } public List < TaskInstance > getTasks ( ) { return PluginImpl . INSTANCE . getPooledTasks ( ) ; } } package hudson . jbpm . model ; import hudson . jbpm . PluginImpl ; import hudson . jbpm . model . gpd . GPD ; import hudson . jbpm . model . gpd . Node ; import hudson . jbpm . rendering . ProcessInstanceRenderer ; import hudson . model . Action ; import hudson . model . Run ; import java . awt . Graphics2D ; import java . awt . image . BufferedImage ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import javax . imageio . ImageIO ; import javax . servlet . ServletOutputStream ; import javax . xml . xpath . XPathExpressionException ; import org . dom4j . DocumentException ; import org . jbpm . graph . exe . ProcessInstance ; import org . jbpm . taskmgmt . exe . TaskInstance ; import org . kohsuke . stapler . StaplerRequest ; import org . kohsuke . stapler . StaplerResponse ; public class ProcessInstanceAction implements Action { private final long processInstanceId ; private transient GPD gpd ; public ProcessInstanceAction ( long processInstanceId ) { this . processInstanceId = processInstanceId ; } public String getDisplayName ( ) { return "" ; } public String getIconFileName ( ) { return null ; } public String getUrlName ( ) { return "" ; } public long getProcessInstanceId ( ) { return processInstanceId ; } public ProcessInstance getProcessInstance ( ) { return PluginImpl . INSTANCE . getProcessInstance ( processInstanceId ) ; } public synchronized GPD getGPD ( ) { if ( gpd == null ) { gpd = GPD . get ( getProcessInstance ( ) ) ; } return gpd ; } public List < TaskInstanceWrapper > getOpenTasks ( ) { ProcessInstance processInstance = getProcessInstance ( ) ; List < TaskInstanceWrapper > result = new ArrayList < TaskInstanceWrapper > ( ) ; for ( TaskInstance ti : PluginImpl . INSTANCE . getOpenTasks ( processInstance ) ) { TaskInstanceWrapper hti = new TaskInstanceWrapper ( ti ) ; result . add ( hti ) ; } return result ; } public List < TaskInstanceWrapper > getMyTasks ( ) { ProcessInstance processInstance = getProcessInstance ( ) ; List < TaskInstanceWrapper > result = new ArrayList < TaskInstanceWrapper > ( ) ; for ( TaskInstance task : PluginImpl . INSTANCE . getPooledTasks ( ) ) { if ( task . getProcessInstance ( ) . equals ( processInstance ) ) { result . add ( new TaskInstanceWrapper ( task ) ) ; } } for ( TaskInstance task : PluginImpl . INSTANCE . getUserTasks ( ) ) { if ( task . getProcessInstance ( ) . equals ( processInstance ) ) { result . add ( new TaskInstanceWrapper ( task ) ) ; } } return result ; } public void doImage ( StaplerRequest req , StaplerResponse rsp ) throws IOException , XPathExpressionException , DocumentException { ProcessInstance processInstance = getProcessInstance ( ) ; GPD gpd = getGPD ( ) ; ServletOutputStream output = rsp . getOutputStream ( ) ; ProcessInstanceRenderer panel = new ProcessInstanceRenderer ( processInstance , gpd ) ; BufferedImage aimg = new BufferedImage ( panel . getWidth ( ) , panel . getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; Graphics2D g = aimg . createGraphics ( ) ; panel . paint ( g ) ; g . dispose ( ) ; ImageIO . write ( aimg , "" , output ) ; output . flush ( ) ; output . close ( ) ; } public List < ImageMapElement > getNodes ( ) { ProcessInstance processInstance = getProcessInstance ( ) ; Collection < TaskInstance > taskInstances = processInstance . getTaskMgmtInstance ( ) . getTaskInstances ( ) ; List < ImageMapElement > result = new ArrayList < ImageMapElement > ( ) ; for ( Node node : getGPD ( ) . nodes ) { Run run = null ; for ( TaskInstance taskInstance : taskInstances ) { if ( taskInstance . getTask ( ) . getTaskNode ( ) . getName ( ) . equals ( node . getName ( ) ) ) { run = ( Run ) taskInstance . getVariableLocally ( "" ) ; } } if ( run != null ) { ImageMapElement ime = new ImageMapElement ( run . toString ( ) , run . getUrl ( ) , node . getX ( ) , node . getY ( ) , node . getX ( ) + node . getWidth ( ) , node . getY ( ) + node . getHeight ( ) ) ; result . add ( ime ) ; } } return result ; } public static class ImageMapElement { public final int x1 , y1 , x2 , y2 ; public final String name ; public final String url ; public ImageMapElement ( String name , String url , int x1 , int y1 , int x2 , int y2 ) { super ( ) ; this . name = name ; this . url = url ; this . x1 = x1 ; this . x2 = x2 ; this . y1 = y1 ; this . y2 = y2 ; } } } package hudson . jbpm . model . gpd ; import com . thoughtworks . xstream . annotations . XStreamAlias ; import com . thoughtworks . xstream . annotations . XStreamAsAttribute ; @ XStreamAlias ( "" ) public class BendPoint { public int getW1 ( ) { return w1 ; } public void setW1 ( int w1 ) { this . w1 = w1 ; } public int getH1 ( ) { return h1 ; } public void setH1 ( int h1 ) { this . h1 = h1 ; } public int getW2 ( ) { return w2 ; } public void setW2 ( int w2 ) { this . w2 = w2 ; } public int getH2 ( ) { return h2 ; } public void setH2 ( int h2 ) { this . h2 = h2 ; } @ XStreamAsAttribute int w1 , h1 , w2 , h2 ; } package hudson . jbpm . model . gpd ; import com . thoughtworks . xstream . annotations . XStreamAlias ; import com . thoughtworks . xstream . annotations . XStreamAsAttribute ; @ XStreamAlias ( "" ) public class Label { public int getX ( ) { return x ; } public void setX ( int x ) { this . x = x ; } public int getY ( ) { return y ; } public void setY ( int y ) { this . y = y ; } @ XStreamAsAttribute int x , y ; } package hudson . jbpm . model . gpd ; import java . awt . geom . Rectangle2D ; import java . util . List ; import com . thoughtworks . xstream . annotations . XStreamAlias ; import com . thoughtworks . xstream . annotations . XStreamAsAttribute ; import com . thoughtworks . xstream . annotations . XStreamImplicit ; @ XStreamAlias ( "" ) public class Node { public void setName ( String name ) { this . name = name ; } public void setX ( int x ) { this . x = x ; } public void setY ( int y ) { this . y = y ; } public void setWidth ( int width ) { this . width = width ; } public void setHeight ( int height ) { this . height = height ; } public void setEdges ( List < Edge > edges ) { this . edges = edges ; } @ XStreamAsAttribute String name ; @ XStreamAsAttribute int x , y , width , height ; @ XStreamImplicit ( itemFieldName = "" ) public List < Edge > edges ; private transient NodeState state ; public NodeState getState ( ) { return state ; } public void setState ( NodeState state ) { this . state = state ; } public String getName ( ) { return name ; } public int getX ( ) { return x ; } public int getY ( ) { return y ; } public int getWidth ( ) { return width ; } public int getHeight ( ) { return height ; } public List < Edge > getEdges ( ) { return edges ; } public Rectangle2D . Double asRectangle ( ) { return new Rectangle2D . Double ( x , y , width , height ) ; } public Edge getEdge ( int i ) { return edges != null ? edges . get ( i ) : null ; } } package hudson . jbpm . model . gpd ; public enum NodeState { Entered , Started , Completed , TaskCreated ; } package hudson . jbpm . model . gpd ; import java . util . Collections ; import java . util . List ; import com . thoughtworks . xstream . annotations . XStreamAlias ; import com . thoughtworks . xstream . annotations . XStreamImplicit ; @ XStreamAlias ( "" ) public class Edge { Label label ; public Label getLabel ( ) { return label ; } public void setLabel ( Label label ) { this . label = label ; } public void setBendpoints ( List < BendPoint > bendpoints ) { this . bendpoints = bendpoints ; } @ XStreamImplicit ( itemFieldName = "" ) public List < BendPoint > bendpoints ; public List < BendPoint > getBendPoints ( ) { if ( bendpoints == null ) { return Collections . EMPTY_LIST ; } else { return bendpoints ; } } } package hudson . jbpm . model . gpd ; import java . io . ByteArrayInputStream ; import java . util . List ; import org . jbpm . graph . def . ProcessDefinition ; import org . jbpm . graph . exe . ProcessInstance ; import com . thoughtworks . xstream . XStream ; import com . thoughtworks . xstream . annotations . XStreamAlias ; import com . thoughtworks . xstream . annotations . XStreamAsAttribute ; import com . thoughtworks . xstream . annotations . XStreamImplicit ; @ XStreamAlias ( "" ) public class GPD { private static XStream xstream = new XStream ( ) ; static { xstream . setClassLoader ( GPD . class . getClassLoader ( ) ) ; xstream . processAnnotations ( new Class [ ] { GPD . class , Node . class , Edge . class , Label . class , BendPoint . class } ) ; } public static GPD get ( ProcessInstance instance ) { ProcessDefinition def = instance . getProcessDefinition ( ) ; byte [ ] gpd = def . getFileDefinition ( ) . getBytes ( "" ) ; return ( GPD ) xstream . fromXML ( new ByteArrayInputStream ( gpd ) ) ; } @ XStreamAsAttribute public String name ; @ XStreamAsAttribute public int width , height ; @ XStreamImplicit ( itemFieldName = "" ) public List < Node > nodes ; public Node getNode ( String name ) { for ( Node node : nodes ) { if ( name . equals ( node . name ) ) { return node ; } } return null ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public int getWidth ( ) { return width ; } public int getHeight ( ) { return height ; } } package hudson . jbpm . model ; import hudson . jbpm . ProcessClassLoaderCache ; import hudson . model . Action ; import hudson . model . Hudson ; import java . io . IOException ; import java . lang . reflect . InvocationTargetException ; import javax . servlet . ServletException ; import org . acegisecurity . userdetails . UserDetails ; import org . apache . commons . lang . StringUtils ; import org . jbpm . JbpmConfiguration ; import org . jbpm . JbpmContext ; import org . jbpm . taskmgmt . exe . TaskInstance ; import org . kohsuke . stapler . QueryParameter ; import org . kohsuke . stapler . StaplerRequest ; import org . kohsuke . stapler . StaplerResponse ; public class TaskInstanceWrapper implements Action { private final long taskInstanceId ; private TaskInstance taskInstance ; public TaskInstanceWrapper ( long taskInstanceId ) { this . taskInstanceId = taskInstanceId ; } public TaskInstanceWrapper ( TaskInstance ti ) { this . taskInstance = ti ; taskInstanceId = taskInstance . getId ( ) ; } public long getId ( ) { return taskInstanceId ; } public String getDisplayName ( ) { return null ; } public String getIconFileName ( ) { return null ; } public String getUrlName ( ) { return null ; } public synchronized TaskInstance getTaskInstance ( ) { if ( taskInstance == null ) { JbpmContext context = JbpmConfiguration . getInstance ( ) . getCurrentJbpmContext ( ) ; taskInstance = context . getTaskMgmtSession ( ) . getTaskInstance ( taskInstanceId ) ; } return taskInstance ; } public Object getForm ( ) { TaskInstance ti = getTaskInstance ( ) ; try { ClassLoader processClassLoader = ProcessClassLoaderCache . INSTANCE . getClassLoader ( ti . getProcessInstance ( ) . getProcessDefinition ( ) ) ; String formClass = ( String ) ti . getVariableLocally ( "" ) ; if ( formClass == null ) { return new Form ( ti ) ; } else { Class < ? > cl = processClassLoader . loadClass ( formClass ) ; return cl . getConstructor ( TaskInstance . class ) . newInstance ( ti ) ; } } catch ( InvocationTargetException e ) { throw new RuntimeException ( e . getCause ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } public void doTriggerTransition ( StaplerRequest req , StaplerResponse rsp , @ QueryParameter ( "" ) String transition ) throws ServletException , IOException { JbpmContext context = JbpmConfiguration . getInstance ( ) . getCurrentJbpmContext ( ) ; TaskInstance taskInstance = getTaskInstance ( ) ; if ( StringUtils . isEmpty ( transition ) ) { taskInstance . end ( ) ; } else { taskInstance . end ( transition ) ; } context . save ( taskInstance ) ; rsp . forwardToPreviousPage ( req ) ; } public void doStart ( StaplerRequest req , StaplerResponse rsp ) throws ServletException , IOException { String userName = ( ( UserDetails ) Hudson . getInstance ( ) . getAuthentication ( ) . getPrincipal ( ) ) . getUsername ( ) ; JbpmContext context = JbpmConfiguration . getInstance ( ) . getCurrentJbpmContext ( ) ; TaskInstance taskInstance = getTaskInstance ( ) ; taskInstance . setActorId ( userName ) ; taskInstance . start ( ) ; context . save ( taskInstance ) ; rsp . forwardToPreviousPage ( req ) ; } } package hudson . stagingworkflow ; import hudson . jbpm . model . Form ; import java . io . IOException ; import javax . servlet . ServletException ; import org . jbpm . JbpmConfiguration ; import org . jbpm . JbpmContext ; import org . jbpm . taskmgmt . exe . TaskInstance ; import org . kohsuke . stapler . StaplerRequest ; import org . kohsuke . stapler . StaplerResponse ; public class ReleaseInformationForm extends Form { private String releaseVersion , nextDevelopmentVersion , voteEmailAddress , releaseEmailAddress ; public String getVoteAnnouncementEmailAddress ( ) { return voteEmailAddress ; } public void setVoteAnnouncementEmailAddress ( String voteAnnouncementEmailAddress ) { this . voteEmailAddress = voteAnnouncementEmailAddress ; } public String getReleaseAnnouncementEmailAddress ( ) { return releaseEmailAddress ; } public String getReleaseVersion ( ) { return releaseVersion ; } public void setReleaseVersion ( String releaseVersion ) { this . releaseVersion = releaseVersion ; } public String getVoteEmailAddress ( ) { return voteEmailAddress ; } public void setVoteEmailAddress ( String voteEmailAddress ) { this . voteEmailAddress = voteEmailAddress ; } public String getReleaseEmailAddress ( ) { return releaseEmailAddress ; } public void setReleaseEmailAddress ( String releaseEmailAddress ) { this . releaseEmailAddress = releaseEmailAddress ; } public String getNextDevelopmentVersion ( ) { return nextDevelopmentVersion ; } public void setNextDevelopmentVersion ( String nextDevelopmentVersion ) { this . nextDevelopmentVersion = nextDevelopmentVersion ; } public ReleaseInformationForm ( TaskInstance taskInstance ) { super ( taskInstance ) ; } @ Override public void handle ( StaplerRequest request , StaplerResponse response ) throws ServletException , IOException { TaskInstance ti = getTaskInstance ( ) ; ti . setVariable ( "" , releaseVersion ) ; ti . setVariable ( "" , nextDevelopmentVersion ) ; ti . setVariable ( "" , voteEmailAddress ) ; ti . setVariable ( "" , releaseEmailAddress ) ; JbpmContext context = JbpmConfiguration . getInstance ( ) . getCurrentJbpmContext ( ) ; ti . end ( ) ; context . save ( ti ) ; } } package hudson . stagingworkflow ; import hudson . jbpm . model . Form ; import java . io . IOException ; import javax . servlet . ServletException ; import org . jbpm . JbpmConfiguration ; import org . jbpm . graph . exe . Token ; import org . jbpm . taskmgmt . exe . TaskInstance ; import org . kohsuke . stapler . StaplerRequest ; import org . kohsuke . stapler . StaplerResponse ; public class EndVoteForm extends Form { public EndVoteForm ( TaskInstance taskInstance ) { super ( taskInstance ) ; } @ Override public void handle ( StaplerRequest request , StaplerResponse response ) throws ServletException , IOException { TaskInstance taskInstance = getTaskInstance ( ) ; Token token = taskInstance . getToken ( ) ; taskInstance . end ( ) ; token . signal ( "" ) ; JbpmConfiguration . getInstance ( ) . getCurrentJbpmContext ( ) . save ( token ) ; } } package hudson . stagingworkflow ; import org . jbpm . graph . def . ActionHandler ; import org . jbpm . graph . exe . ExecutionContext ; import org . jbpm . graph . exe . Token ; import org . jbpm . graph . node . TaskNode ; import org . jbpm . taskmgmt . def . Task ; import org . jbpm . taskmgmt . exe . TaskInstance ; import org . jbpm . taskmgmt . exe . TaskMgmtInstance ; public class CreateVotingTasksHandler implements ActionHandler { public void execute ( ExecutionContext executionContext ) throws Exception { Token token = executionContext . getToken ( ) ; TaskMgmtInstance tmi = executionContext . getTaskMgmtInstance ( ) ; TaskNode taskNode = ( TaskNode ) executionContext . getNode ( ) ; Task voteTask = taskNode . getTask ( "" ) ; TaskInstance taskInstance = tmi . createTaskInstance ( voteTask , token ) ; taskInstance . setActorId ( "" ) ; taskInstance . setVariableLocally ( "" , VoteForm . class . getName ( ) ) ; taskInstance = tmi . createTaskInstance ( voteTask , token ) ; taskInstance . setActorId ( "" ) ; taskInstance . setVariableLocally ( "" , VoteForm . class . getName ( ) ) ; taskInstance = tmi . createTaskInstance ( taskNode . getTask ( "" ) , token ) ; taskInstance . setVariableLocally ( "" , EndVoteForm . class . getName ( ) ) ; taskInstance . assign ( executionContext ) ; } } package hudson . stagingworkflow ; import hudson . model . AbstractBuild ; import hudson . staging . DeployAction ; import org . jbpm . graph . def . ActionHandler ; import org . jbpm . graph . exe . ExecutionContext ; public class DeployStagedReleaseHandler implements ActionHandler { public DeployStagedReleaseHandler ( ) { } public void execute ( ExecutionContext executionContext ) throws Exception { AbstractBuild build = ( AbstractBuild ) executionContext . getContextInstance ( ) . getVariable ( "" ) ; DeployAction action = build . getAction ( DeployAction . class ) ; action . setRepositoryId ( "" ) ; action . setRepositoryUrl ( "" ) ; action . deploy ( ) ; executionContext . getToken ( ) . signal ( ) ; } } package hudson . stagingworkflow ; import java . util . Map ; import org . apache . commons . lang . StringUtils ; import org . jbpm . JbpmConfiguration ; import org . jbpm . JbpmContext ; import org . jbpm . context . exe . ContextInstance ; import org . jbpm . graph . def . ActionHandler ; import org . jbpm . graph . exe . ExecutionContext ; import org . jbpm . graph . node . DecisionHandler ; public class VoteCountingActionHandler implements ActionHandler { private static final int VOTES_REQUIRED = ; public void execute ( ExecutionContext executionContext ) throws Exception { JbpmContext context = JbpmConfiguration . getInstance ( ) . getCurrentJbpmContext ( ) ; ContextInstance ci = executionContext . getContextInstance ( ) ; Map < String , String > variables = ci . getVariables ( ) ; int positive = ; int negative = ; StringBuilder voteResultText = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : variables . entrySet ( ) ) { if ( entry . getKey ( ) . startsWith ( "" ) ) { String vote = entry . getValue ( ) ; if ( vote . equals ( "" ) ) { positive ++ ; } else if ( vote . equals ( "" ) ) { negative ++ ; } String comment = variables . get ( "" + entry . getKey ( ) . substring ( ) ) ; String user = entry . getKey ( ) . substring ( ) ; voteResultText . append ( "" + user + "" + vote ) ; if ( ! StringUtils . isEmpty ( comment ) ) { voteResultText . append ( "" ) . append ( comment ) ; } voteResultText . append ( "" ) ; } } voteResultText . append ( "" ) ; voteResultText . append ( String . format ( "" , positive , negative ) ) ; voteResultText . append ( "" ) ; String voteResult = null ; if ( positive >= VOTES_REQUIRED && positive > negative ) { voteResultText . append ( "" ) ; voteResult = "" ; } else if ( positive <= negative ) { voteResultText . append ( "" ) ; voteResult = "" ; } else { voteResultText . append ( "" + VOTES_REQUIRED + "" ) ; voteResult = "" ; } ci . setVariable ( "" , voteResultText . toString ( ) ) ; ci . setVariable ( "" , voteResult ) ; context . save ( ci . getProcessInstance ( ) ) ; } } package hudson . stagingworkflow ; import hudson . jbpm . model . Form ; import java . io . IOException ; import javax . servlet . ServletException ; import org . jbpm . taskmgmt . exe . TaskInstance ; import org . kohsuke . stapler . StaplerRequest ; import org . kohsuke . stapler . StaplerResponse ; public class VoteForm extends Form { private String vote ; private String comment ; public String getVote ( ) { return vote ; } public void setVote ( String vote ) { this . vote = vote ; } public void handle ( StaplerRequest request , StaplerResponse response ) throws ServletException , IOException { TaskInstance ti = getTaskInstance ( ) ; String actorId = ti . getActorId ( ) ; ti . setVariable ( "" + actorId , vote ) ; ti . setVariable ( "" + actorId , comment ) ; } public String getComment ( ) { return comment ; } public void setComment ( String comment ) { this . comment = comment ; } public VoteForm ( TaskInstance taskInstance ) { super ( taskInstance ) ; vote = ( String ) taskInstance . getVariable ( "" + taskInstance . getActorId ( ) ) ; comment = ( String ) taskInstance . getVariable ( "" + taskInstance . getActorId ( ) ) ; } } package hudson . stagingworkflow ; import org . jbpm . graph . def . ActionHandler ; import org . jbpm . graph . exe . ExecutionContext ; public class StartReleaseProjectHandler implements ActionHandler { private static final long serialVersionUID = - ; private String projectName ; public StartReleaseProjectHandler ( ) { } public StartReleaseProjectHandler ( String projectName ) { this . projectName = projectName ; } public void execute ( ExecutionContext executionContext ) throws Exception { executionContext . getTaskInstance ( ) . setVariableLocally ( "" , projectName ) ; executionContext . getTaskInstance ( ) . setVariableLocally ( "" , executionContext . getVariable ( "" ) ) ; } public String getProjectName ( ) { return projectName ; } public void setProjectName ( String projectName ) { this . projectName = projectName ; } } package net . thucydides . showcase . simple ; import net . thucydides . core . annotations . Managed ; import net . thucydides . core . annotations . ManagedPages ; import net . thucydides . core . annotations . Steps ; import net . thucydides . core . annotations . Story ; import net . thucydides . core . pages . Pages ; import net . thucydides . junit . runners . ThucydidesRunner ; import net . thucydides . showcase . simple . requirements . Application ; import net . thucydides . showcase . simple . steps . DeveloperSteps ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . openqa . selenium . WebDriver ; import static net . thucydides . core . matchers . BeanMatchers . the_count ; import static net . thucydides . core . matchers . BeanMatchers . each ; import static net . thucydides . core . matchers . BeanMatchers . the ; import static org . hamcrest . Matchers . greaterThanOrEqualTo ; import static org . hamcrest . Matchers . is ; import static org . hamcrest . Matchers . startsWith ; @ RunWith ( ThucydidesRunner . class ) @ Story ( Application . Search . SearchForArtifactsByName . class ) public class WhenSearchingForArtifacts { @ Managed WebDriver driver ; @ ManagedPages ( defaultUrl = "" ) public Pages pages ; @ Steps public DeveloperSteps developer ; @ Test public void should_search_for_artifacts_by_name ( ) { developer . opens_the_search_page ( ) ; developer . searches_for ( "" ) ; developer . should_see_artifacts_where ( the ( "" , is ( "" ) ) , the ( "" , is ( "" ) ) ) ; } @ Test public void should_search_for_artifact_objects_by_name ( ) { developer . opens_the_search_page ( ) ; developer . searches_for ( "" ) ; developer . should_see_artifact_objects_where ( the ( "" , is ( "" ) ) , the ( "" , is ( "" ) ) ) ; } @ Test public void should_find_the_right_number_of_artifacts ( ) { developer . opens_the_search_page ( ) ; developer . searches_for ( "" ) ; developer . should_see_artifacts_where ( the ( "" , startsWith ( "" ) ) , each ( "" ) . isDifferent ( ) , the_count ( is ( greaterThanOrEqualTo ( ) ) ) ) ; } } package net . thucydides . showcase . simple ; import net . thucydides . core . annotations . Managed ; import net . thucydides . core . annotations . ManagedPages ; import net . thucydides . core . annotations . Steps ; import net . thucydides . core . annotations . Story ; import net . thucydides . core . pages . Pages ; import net . thucydides . junit . runners . ThucydidesRunner ; import net . thucydides . showcase . simple . requirements . Application ; import net . thucydides . showcase . simple . steps . DeveloperSteps ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . openqa . selenium . WebDriver ; import static net . thucydides . core . matchers . BeanMatchers . each ; import static net . thucydides . core . matchers . BeanMatchers . the ; import static net . thucydides . core . matchers . BeanMatchers . the_count ; import static org . hamcrest . Matchers . greaterThanOrEqualTo ; import static org . hamcrest . Matchers . is ; import static org . hamcrest . Matchers . startsWith ; @ RunWith ( ThucydidesRunner . class ) @ Story ( Application . Search . SearchForArtifactsByName . class ) public class WhenSearchingForArtifactsUsingMultipleCriteriaInTheAdvancedSearch { @ Managed WebDriver driver ; @ ManagedPages ( defaultUrl = "" ) public Pages pages ; @ Steps public DeveloperSteps developer ; @ Test public void should_search_for_artifacts_by_group_id_and_version ( ) { developer . opens_the_advanced_search_page ( ) ; developer . searches_by_group_and_version ( "" , "" ) ; developer . should_see_artifacts_where ( the ( "" , is ( "" ) ) , the ( "" , is ( "" ) ) ) ; } } package net . thucydides . showcase . simple . steps ; import net . thucydides . core . annotations . Step ; import net . thucydides . core . matchers . BeanFieldMatcher ; import net . thucydides . core . matchers . BeanMatcher ; import net . thucydides . core . pages . Pages ; import net . thucydides . core . steps . ScenarioSteps ; import net . thucydides . showcase . simple . pages . AdvancedSearchPage ; import net . thucydides . showcase . simple . pages . ArtifactDetailsPage ; import net . thucydides . showcase . simple . pages . SearchPage ; import net . thucydides . showcase . simple . pages . SearchResultsPage ; import static net . thucydides . core . matchers . BeanMatcherAsserts . shouldMatch ; public class DeveloperSteps extends ScenarioSteps { public DeveloperSteps ( Pages pages ) { super ( pages ) ; } @ Step public void opens_the_search_page ( ) { onSearchPage ( ) . open ( ) ; } @ Step public DeveloperSteps searches_for ( String search_terms ) { onSearchPage ( ) . enter_search_terms ( search_terms ) ; onSearchPage ( ) . starts_search ( ) ; return this ; } @ Step public void should_see_artifacts_where ( BeanMatcher ... matchers ) { shouldMatch ( onSearchResultsPage ( ) . getSearchResults ( ) , matchers ) ; } @ Step public void should_see_artifact_objects_where ( BeanMatcher ... matchers ) { shouldMatch ( onSearchResultsPage ( ) . getResults ( ) , matchers ) ; } @ Step public void should_see_error_message ( String expectedMessage ) { onSearchResultsPage ( ) . resultTable ( ) . shouldContainText ( expectedMessage ) ; } @ Step public void open_artifact_where ( BeanMatcher ... matchers ) { onSearchResultsPage ( ) . clickOnFirstRowMatching ( matchers ) ; } @ Step public void should_see_artifact_details_where ( BeanMatcher ... matchers ) { shouldMatch ( onArtifactDetailsPage ( ) , matchers ) ; } public void opens_the_advanced_search_page ( ) { onSearchPage ( ) . open ( ) ; onSearchPage ( ) . clickOnAdvancedSearch ( ) ; } public void searches_by_group ( String group ) { onAdvancedSearchPage ( ) . setGroupId ( group ) ; onAdvancedSearchPage ( ) . startSearch ( ) ; } public void searches_by_artifact ( String artifact ) { onAdvancedSearchPage ( ) . setArtifactId ( artifact ) ; onAdvancedSearchPage ( ) . startSearch ( ) ; } public void searches_by_group_and_version ( String group , String version ) { onAdvancedSearchPage ( ) . setGroupId ( group ) ; onAdvancedSearchPage ( ) . setVersion ( version ) ; onAdvancedSearchPage ( ) . startSearch ( ) ; } private SearchPage onSearchPage ( ) { return getPages ( ) . get ( SearchPage . class ) ; } private AdvancedSearchPage onAdvancedSearchPage ( ) { return getPages ( ) . get ( AdvancedSearchPage . class ) ; } private SearchResultsPage onSearchResultsPage ( ) { return getPages ( ) . get ( SearchResultsPage . class ) ; } private ArtifactDetailsPage onArtifactDetailsPage ( ) { return getPages ( ) . get ( ArtifactDetailsPage . class ) ; } } package net . thucydides . showcase . simple . requirements ; import net . thucydides . core . annotations . Feature ; public class Application { @ Feature public class Search { public class SearchForArtifactsByName { } public class AdvancedSearch { } } @ Feature public class DisplayArtifacts { public class ViewArtifactDetails { } } } package net . thucydides . showcase . simple ; import net . thucydides . core . annotations . Managed ; import net . thucydides . core . annotations . ManagedPages ; import net . thucydides . core . annotations . Steps ; import net . thucydides . core . annotations . Story ; import net . thucydides . core . pages . Pages ; import net . thucydides . junit . runners . ThucydidesRunner ; import net . thucydides . showcase . simple . requirements . Application ; import net . thucydides . showcase . simple . steps . DeveloperSteps ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . openqa . selenium . WebDriver ; import static net . thucydides . core . matchers . BeanMatchers . each ; import static net . thucydides . core . matchers . BeanMatchers . the ; import static net . thucydides . core . matchers . BeanMatchers . the_count ; import static org . hamcrest . Matchers . greaterThanOrEqualTo ; import static org . hamcrest . Matchers . is ; import static org . hamcrest . Matchers . startsWith ; @ RunWith ( ThucydidesRunner . class ) @ Story ( Application . Search . SearchForArtifactsByName . class ) public class WhenSearchingForArtifactsUsingTheAdvancedSearch { @ Managed WebDriver driver ; @ ManagedPages ( defaultUrl = "" ) public Pages pages ; @ Steps public DeveloperSteps developer ; @ Test public void should_search_for_artifacts_by_group_id ( ) { developer . opens_the_advanced_search_page ( ) ; developer . searches_by_group ( "" ) ; developer . should_see_artifacts_where ( the ( "" , is ( "" ) ) , the_count ( greaterThanOrEqualTo ( ) ) ) ; } @ Test public void should_search_for_artifacts_by_artifact_id ( ) { developer . opens_the_advanced_search_page ( ) ; developer . searches_by_artifact ( "" ) ; developer . should_see_artifacts_where ( the ( "" , is ( "" ) ) , the_count ( is ( ) ) ) ; } } package net . thucydides . showcase . simple ; import net . thucydides . core . annotations . Managed ; import net . thucydides . core . annotations . ManagedPages ; import net . thucydides . core . annotations . Steps ; import net . thucydides . core . annotations . Story ; import net . thucydides . core . pages . Pages ; import net . thucydides . junit . runners . ThucydidesRunner ; import net . thucydides . showcase . simple . requirements . Application ; import net . thucydides . showcase . simple . steps . DeveloperSteps ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . openqa . selenium . WebDriver ; import static net . thucydides . core . matchers . BeanMatchers . each ; import static net . thucydides . core . matchers . BeanMatchers . the ; import static net . thucydides . core . matchers . BeanMatchers . the_count ; import static org . hamcrest . Matchers . greaterThanOrEqualTo ; import static org . hamcrest . Matchers . is ; import static org . hamcrest . Matchers . startsWith ; @ RunWith ( ThucydidesRunner . class ) @ Story ( Application . Search . SearchForArtifactsByName . class ) public class WhenSearchingForArtifactsUsingAWildCard { @ Managed WebDriver driver ; @ ManagedPages ( defaultUrl = "" ) public Pages pages ; @ Steps public DeveloperSteps developer ; @ Test public void should_search_for_artifacts_by_name_containing_a_wildcard ( ) { developer . opens_the_search_page ( ) ; developer . searches_for ( "" ) ; developer . should_see_artifacts_where ( the ( "" , is ( "" ) ) , the ( "" , is ( "" ) ) ) ; } @ Test public void should_find_the_right_number_of_artifacts_when_using_a_wildcard ( ) { developer . opens_the_search_page ( ) ; developer . searches_for ( "" ) ; developer . should_see_artifacts_where ( the ( "" , startsWith ( "" ) ) , each ( "" ) . isDifferent ( ) , the_count ( is ( greaterThanOrEqualTo ( ) ) ) ) ; } } package net . thucydides . showcase . simple ; import net . thucydides . core . annotations . Managed ; import net . thucydides . core . annotations . ManagedPages ; import net . thucydides . core . annotations . Steps ; import net . thucydides . core . annotations . Story ; import net . thucydides . core . pages . Pages ; import net . thucydides . junit . runners . ThucydidesRunner ; import net . thucydides . showcase . simple . requirements . Application ; import net . thucydides . showcase . simple . steps . DeveloperSteps ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . openqa . selenium . WebDriver ; import static net . thucydides . core . matchers . BeanMatchers . the ; import static org . hamcrest . Matchers . is ; @ RunWith ( ThucydidesRunner . class ) @ Story ( Application . DisplayArtifacts . ViewArtifactDetails . class ) public class WhenViewingArtifactDetails { @ Managed WebDriver driver ; @ ManagedPages ( defaultUrl = "" ) public Pages pages ; @ Steps public DeveloperSteps developer ; @ Test public void clicking_on_artifact_should_display_details_page ( ) { developer . opens_the_search_page ( ) ; developer . searches_for ( "" ) ; developer . open_artifact_where ( the ( "" , is ( "" ) ) , the ( "" , is ( "" ) ) ) ; developer . should_see_artifact_details_where ( the ( "" , is ( "" ) ) , the ( "" , is ( "" ) ) ) ; } } package net . thucydides . showcase . simple . pages ; public class ArtifactEntry { private final String groupId ; private final String artifactId ; private final String latestVersion ; public ArtifactEntry ( String groupId , String artifactId , String latestVersion ) { this . groupId = groupId ; this . artifactId = artifactId ; this . latestVersion = latestVersion ; } public String getGroupId ( ) { return groupId ; } public String getArtifactId ( ) { return artifactId ; } public String getLatestVersion ( ) { return latestVersion ; } } package net . thucydides . showcase . simple . pages ; import net . thucydides . core . pages . PageObject ; import org . openqa . selenium . WebDriver ; import org . openqa . selenium . WebElement ; public class ArtifactDetailsPage extends PageObject { WebElement groupid ; WebElement artifactid ; WebElement versionid ; public ArtifactDetailsPage ( WebDriver driver ) { super ( driver ) ; } public String getGroupId ( ) { return element ( groupid ) . getTextValue ( ) ; } public String getArtifactId ( ) { return element ( artifactid ) . getTextValue ( ) ; } public String getVersionId ( ) { return element ( versionid ) . getTextValue ( ) ; } } package net . thucydides . showcase . simple . pages ; import net . thucydides . core . annotations . DefaultUrl ; import net . thucydides . core . pages . PageObject ; import org . openqa . selenium . WebDriver ; import org . openqa . selenium . WebElement ; import org . openqa . selenium . support . FindBy ; @ DefaultUrl ( "" ) public class SearchPage extends PageObject { @ FindBy ( id = "" ) private WebElement search ; @ FindBy ( id = "" ) private WebElement searchButton ; @ FindBy ( linkText = "" ) WebElement advancedSearch ; public SearchPage ( WebDriver driver ) { super ( driver ) ; } public void enter_search_terms ( String searchTerms ) { element ( search ) . type ( searchTerms ) ; } public void starts_search ( ) { element ( searchButton ) . click ( ) ; } public void clickOnAdvancedSearch ( ) { element ( advancedSearch ) . click ( ) ; } } package net . thucydides . showcase . simple . pages ; import net . thucydides . core . annotations . DefaultUrl ; import net . thucydides . core . pages . PageObject ; import org . openqa . selenium . WebDriver ; import org . openqa . selenium . WebElement ; import org . openqa . selenium . support . FindBy ; @ DefaultUrl ( "" ) public class AdvancedSearchPage extends PageObject { private WebElement groupId ; private WebElement artifactId ; private String value ; private WebElement version ; private WebElement packaging ; private WebElement classifier ; private WebElement gavSearchButton ; public AdvancedSearchPage ( WebDriver driver ) { super ( driver ) ; } public void setGroupId ( String value ) { element ( groupId ) . type ( value ) ; } public void setArtifactId ( String value ) { element ( artifactId ) . type ( value ) ; } public void setVersion ( String value ) { element ( version ) . type ( value ) ; } public void setPackaging ( String value ) { element ( packaging ) . type ( value ) ; } public void setClassifier ( String value ) { element ( classifier ) . type ( value ) ; } public void startSearch ( ) { element ( gavSearchButton ) . click ( ) ; } } package net . thucydides . showcase . simple . pages ; import ch . lambdaj . function . convert . Converter ; import net . thucydides . core . matchers . BeanMatcher ; import net . thucydides . core . pages . PageObject ; import net . thucydides . core . pages . WebElementFacade ; import org . openqa . selenium . By ; import org . openqa . selenium . WebDriver ; import org . openqa . selenium . WebElement ; import org . openqa . selenium . support . FindBy ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import static ch . lambdaj . Lambda . convert ; import static net . thucydides . core . pages . components . HtmlTable . filterRows ; import static net . thucydides . core . pages . components . HtmlTable . rowsFrom ; public class SearchResultsPage extends PageObject { @ FindBy ( xpath = "" ) WebElement resultTable ; public SearchResultsPage ( WebDriver driver ) { super ( driver ) ; } public List < Map < Object , String > > getSearchResults ( ) { return rowsFrom ( resultTable ) ; } public class Artifact { private final String groupId ; private final String artifactId ; private final String latestVersion ; public Artifact ( String groupId , String artifactId , String latestVersion ) { this . groupId = groupId ; this . artifactId = artifactId ; this . latestVersion = latestVersion ; } public String getGroupId ( ) { return groupId ; } public String getArtifactId ( ) { return artifactId ; } public String getLatestVersion ( ) { return latestVersion ; } } public List < Artifact > getResults ( ) { List < WebElement > rows = resultTable . findElements ( By . xpath ( "" ) ) ; return convert ( rows , toArtifacts ( ) ) ; } private Converter < WebElement , Artifact > toArtifacts ( ) { return new Converter < WebElement , Artifact > ( ) { public Artifact convert ( WebElement row ) { List < WebElement > cells = row . findElements ( By . tagName ( "" ) ) ; String groupId = cells . get ( ) . getText ( ) ; String artifactId = cells . get ( ) . getText ( ) ; String latestVersion = cells . get ( ) . getText ( ) ; return new Artifact ( groupId , artifactId , latestVersion ) ; } } ; } public WebElementFacade resultTable ( ) { return element ( resultTable ) ; } public void clickOnFirstRowMatching ( BeanMatcher ... matchers ) { List < WebElement > matchingRows = filterRows ( resultTable , matchers ) ; WebElement targetRow = matchingRows . get ( ) ; WebElement detailsLink = targetRow . findElement ( By . xpath ( "" ) ) ; detailsLink . click ( ) ; } } package com . facebook . android ; public class DialogError extends Throwable { private static final long serialVersionUID = ; private int mErrorCode ; private String mFailingUrl ; public DialogError ( String message , int errorCode , String failingUrl ) { super ( message ) ; mErrorCode = errorCode ; mFailingUrl = failingUrl ; } int getErrorCode ( ) { return mErrorCode ; } String getFailingUrl ( ) { return mFailingUrl ; } } package com . facebook . android ; import android . app . Dialog ; import android . app . ProgressDialog ; import android . content . Context ; import android . content . Intent ; import android . graphics . Bitmap ; import android . graphics . Color ; import android . graphics . drawable . Drawable ; import android . net . Uri ; import android . os . Bundle ; import android . util . Log ; import android . view . View ; import android . view . ViewGroup ; import android . view . ViewGroup . LayoutParams ; import android . view . Window ; import android . webkit . WebView ; import android . webkit . WebViewClient ; import android . widget . FrameLayout ; import android . widget . ImageView ; import android . widget . LinearLayout ; import com . facebook . android . Facebook . DialogListener ; public class FbDialog extends Dialog { static final int FB_BLUE = ; static final float [ ] DIMENSIONS_DIFF_LANDSCAPE = { , } ; static final float [ ] DIMENSIONS_DIFF_PORTRAIT = { , } ; static final FrameLayout . LayoutParams FILL = new FrameLayout . LayoutParams ( ViewGroup . LayoutParams . FILL_PARENT , ViewGroup . LayoutParams . FILL_PARENT ) ; static final int MARGIN = ; static final int PADDING = ; static final String DISPLAY_STRING = "" ; static final String FB_ICON = "" ; private String mUrl ; private DialogListener mListener ; private ProgressDialog mSpinner ; private ImageView mCrossImage ; private WebView mWebView ; private FrameLayout mContent ; public FbDialog ( Context context , String url , DialogListener listener ) { super ( context , android . R . style . Theme_Translucent_NoTitleBar ) ; mUrl = url ; mListener = listener ; } @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; mSpinner = new ProgressDialog ( getContext ( ) ) ; mSpinner . requestWindowFeature ( Window . FEATURE_NO_TITLE ) ; mSpinner . setMessage ( "" ) ; requestWindowFeature ( Window . FEATURE_NO_TITLE ) ; mContent = new FrameLayout ( getContext ( ) ) ; createCrossImage ( ) ; int crossWidth = mCrossImage . getDrawable ( ) . getIntrinsicWidth ( ) ; setUpWebView ( crossWidth / ) ; mContent . addView ( mCrossImage , new LayoutParams ( LayoutParams . WRAP_CONTENT , LayoutParams . WRAP_CONTENT ) ) ; addContentView ( mContent , new LayoutParams ( LayoutParams . FILL_PARENT , LayoutParams . FILL_PARENT ) ) ; } private void createCrossImage ( ) { mCrossImage = new ImageView ( getContext ( ) ) ; mCrossImage . setOnClickListener ( new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { mListener . onCancel ( ) ; FbDialog . this . dismiss ( ) ; } } ) ; Drawable crossDrawable = getContext ( ) . getResources ( ) . getDrawable ( R . drawable . close ) ; mCrossImage . setImageDrawable ( crossDrawable ) ; mCrossImage . setVisibility ( View . INVISIBLE ) ; } private void setUpWebView ( int margin ) { LinearLayout webViewContainer = new LinearLayout ( getContext ( ) ) ; mWebView = new WebView ( getContext ( ) ) ; mWebView . setVerticalScrollBarEnabled ( false ) ; mWebView . setHorizontalScrollBarEnabled ( false ) ; mWebView . setWebViewClient ( new FbDialog . FbWebViewClient ( ) ) ; mWebView . getSettings ( ) . setJavaScriptEnabled ( true ) ; mWebView . loadUrl ( mUrl ) ; mWebView . setLayoutParams ( FILL ) ; mWebView . setVisibility ( View . INVISIBLE ) ; webViewContainer . setPadding ( margin , margin , margin , margin ) ; webViewContainer . addView ( mWebView ) ; mContent . addView ( webViewContainer ) ; } private class FbWebViewClient extends WebViewClient { @ Override public boolean shouldOverrideUrlLoading ( WebView view , String url ) { Log . d ( "" , "" + url ) ; if ( url . startsWith ( Facebook . REDIRECT_URI ) ) { Bundle values = Util . parseUrl ( url ) ; String error = values . getString ( "" ) ; if ( error == null ) { error = values . getString ( "" ) ; } if ( error == null ) { mListener . onComplete ( values ) ; } else if ( error . equals ( "" ) || error . equals ( "" ) ) { mListener . onCancel ( ) ; } else { mListener . onFacebookError ( new FacebookError ( error ) ) ; } FbDialog . this . dismiss ( ) ; return true ; } else if ( url . startsWith ( Facebook . CANCEL_URI ) ) { mListener . onCancel ( ) ; FbDialog . this . dismiss ( ) ; return true ; } else if ( url . contains ( DISPLAY_STRING ) ) { return false ; } getContext ( ) . startActivity ( new Intent ( Intent . ACTION_VIEW , Uri . parse ( url ) ) ) ; return true ; } @ Override public void onReceivedError ( WebView view , int errorCode , String description , String failingUrl ) { super . onReceivedError ( view , errorCode , description , failingUrl ) ; mListener . onError ( new DialogError ( description , errorCode , failingUrl ) ) ; FbDialog . this . dismiss ( ) ; } @ Override public void onPageStarted ( WebView view , String url , Bitmap favicon ) { Log . d ( "" , "" + url ) ; super . onPageStarted ( view , url , favicon ) ; mSpinner . show ( ) ; } @ Override public void onPageFinished ( WebView view , String url ) { super . onPageFinished ( view , url ) ; try { mSpinner . dismiss ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } mContent . setBackgroundColor ( Color . TRANSPARENT ) ; mWebView . setVisibility ( View . VISIBLE ) ; mCrossImage . setVisibility ( View . VISIBLE ) ; } } } package com . facebook . android ; public class FacebookError extends Throwable { private static final long serialVersionUID = ; private int mErrorCode = ; private String mErrorType ; public FacebookError ( String message ) { super ( message ) ; } public FacebookError ( String message , String type , int code ) { super ( message ) ; mErrorType = type ; mErrorCode = code ; } public int getErrorCode ( ) { return mErrorCode ; } public String getErrorType ( ) { return mErrorType ; } } package com . facebook . android ; import java . io . BufferedOutputStream ; import java . io . BufferedReader ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . net . HttpURLConnection ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLDecoder ; import java . net . URLEncoder ; import org . json . JSONException ; import org . json . JSONObject ; import android . app . AlertDialog . Builder ; import android . content . Context ; import android . os . Bundle ; import android . util . Log ; import android . webkit . CookieManager ; import android . webkit . CookieSyncManager ; public final class Util { public static String encodePostBody ( Bundle parameters , String boundary ) { if ( parameters == null ) return "" ; StringBuilder sb = new StringBuilder ( ) ; for ( String key : parameters . keySet ( ) ) { if ( parameters . getByteArray ( key ) != null ) { continue ; } sb . append ( "" + key + "" + parameters . getString ( key ) ) ; sb . append ( "" + "" + boundary + "" ) ; } return sb . toString ( ) ; } public static String encodeUrl ( Bundle parameters ) { if ( parameters == null ) { return "" ; } StringBuilder sb = new StringBuilder ( ) ; boolean first = true ; for ( String key : parameters . keySet ( ) ) { if ( first ) first = false ; else sb . append ( "" ) ; sb . append ( URLEncoder . encode ( key ) + "" + URLEncoder . encode ( parameters . getString ( key ) ) ) ; } return sb . toString ( ) ; } public static Bundle decodeUrl ( String s ) { Bundle params = new Bundle ( ) ; if ( s != null ) { String array [ ] = s . split ( "" ) ; for ( String parameter : array ) { String v [ ] = parameter . split ( "" ) ; params . putString ( URLDecoder . decode ( v [ ] ) , URLDecoder . decode ( v [ ] ) ) ; } } return params ; } public static Bundle parseUrl ( String url ) { url = url . replace ( "" , "" ) ; try { URL u = new URL ( url ) ; Bundle b = decodeUrl ( u . getQuery ( ) ) ; b . putAll ( decodeUrl ( u . getRef ( ) ) ) ; return b ; } catch ( MalformedURLException e ) { return new Bundle ( ) ; } } public static String openUrl ( String url , String method , Bundle params ) throws MalformedURLException , IOException { String strBoundary = "" ; String endLine = "" ; OutputStream os ; if ( method . equals ( "" ) ) { url = url + "" + encodeUrl ( params ) ; } Log . d ( "" , method + "" + url ) ; HttpURLConnection conn = ( HttpURLConnection ) new URL ( url ) . openConnection ( ) ; conn . setRequestProperty ( "" , System . getProperties ( ) . getProperty ( "" ) + "" ) ; if ( ! method . equals ( "" ) ) { Bundle dataparams = new Bundle ( ) ; for ( String key : params . keySet ( ) ) { if ( params . getByteArray ( key ) != null ) { dataparams . putByteArray ( key , params . getByteArray ( key ) ) ; } } if ( ! params . containsKey ( "" ) ) { params . putString ( "" , method ) ; } if ( params . containsKey ( "" ) ) { String decoded_token = URLDecoder . decode ( params . getString ( "" ) ) ; params . putString ( "" , decoded_token ) ; } conn . setRequestMethod ( "" ) ; conn . setRequestProperty ( "" , "" + strBoundary ) ; conn . setDoOutput ( true ) ; conn . setDoInput ( true ) ; conn . setRequestProperty ( "" , "" ) ; conn . connect ( ) ; os = new BufferedOutputStream ( conn . getOutputStream ( ) ) ; os . write ( ( "" + strBoundary + endLine ) . getBytes ( ) ) ; os . write ( ( encodePostBody ( params , strBoundary ) ) . getBytes ( ) ) ; os . write ( ( endLine + "" + strBoundary + endLine ) . getBytes ( ) ) ; if ( ! dataparams . isEmpty ( ) ) { for ( String key : dataparams . keySet ( ) ) { os . write ( ( "" + key + "" + endLine ) . getBytes ( ) ) ; os . write ( ( "" + endLine + endLine ) . getBytes ( ) ) ; os . write ( dataparams . getByteArray ( key ) ) ; os . write ( ( endLine + "" + strBoundary + endLine ) . getBytes ( ) ) ; } } os . flush ( ) ; } String response = "" ; try { response = read ( conn . getInputStream ( ) ) ; } catch ( FileNotFoundException e ) { response = read ( conn . getErrorStream ( ) ) ; } return response ; } private static String read ( InputStream in ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; BufferedReader r = new BufferedReader ( new InputStreamReader ( in ) , ) ; for ( String line = r . readLine ( ) ; line != null ; line = r . readLine ( ) ) { sb . append ( line ) ; } in . close ( ) ; return sb . toString ( ) ; } public static void clearCookies ( Context context ) { @ SuppressWarnings ( "" ) CookieSyncManager cookieSyncMngr = CookieSyncManager . createInstance ( context ) ; CookieManager cookieManager = CookieManager . getInstance ( ) ; cookieManager . removeAllCookie ( ) ; } public static JSONObject parseJson ( String response ) throws JSONException , FacebookError { if ( response . equals ( "" ) ) { throw new FacebookError ( "" ) ; } if ( response . equals ( "" ) ) { response = "" ; } JSONObject json = new JSONObject ( response ) ; if ( json . has ( "" ) ) { JSONObject error = json . getJSONObject ( "" ) ; throw new FacebookError ( error . getString ( "" ) , error . getString ( "" ) , ) ; } if ( json . has ( "" ) && json . has ( "" ) ) { throw new FacebookError ( json . getString ( "" ) , "" , Integer . parseInt ( json . getString ( "" ) ) ) ; } if ( json . has ( "" ) ) { throw new FacebookError ( "" , "" , Integer . parseInt ( json . getString ( "" ) ) ) ; } if ( json . has ( "" ) ) { throw new FacebookError ( json . getString ( "" ) ) ; } if ( json . has ( "" ) ) { throw new FacebookError ( json . getString ( "" ) ) ; } return json ; } public static void showAlert ( Context context , String title , String text ) { Builder alertBuilder = new Builder ( context ) ; alertBuilder . setTitle ( title ) ; alertBuilder . setMessage ( text ) ; alertBuilder . create ( ) . show ( ) ; } } package com . facebook . android ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . MalformedURLException ; import android . content . Context ; import android . os . Bundle ; public class AsyncFacebookRunner { Facebook fb ; public AsyncFacebookRunner ( Facebook fb ) { this . fb = fb ; } public void logout ( final Context context , final RequestListener listener , final Object state ) { new Thread ( ) { @ Override public void run ( ) { try { String response = fb . logout ( context ) ; if ( response . length ( ) == || response . equals ( "" ) ) { listener . onFacebookError ( new FacebookError ( "" ) , state ) ; return ; } listener . onComplete ( response , state ) ; } catch ( FileNotFoundException e ) { listener . onFileNotFoundException ( e , state ) ; } catch ( MalformedURLException e ) { listener . onMalformedURLException ( e , state ) ; } catch ( IOException e ) { listener . onIOException ( e , state ) ; } } } . start ( ) ; } public void logout ( final Context context , final RequestListener listener ) { logout ( context , listener , null ) ; } public void request ( Bundle parameters , RequestListener listener , final Object state ) { request ( null , parameters , "" , listener , state ) ; } public void request ( Bundle parameters , RequestListener listener ) { request ( null , parameters , "" , listener , null ) ; } public void request ( String graphPath , RequestListener listener , final Object state ) { request ( graphPath , new Bundle ( ) , "" , listener , state ) ; } public void request ( String graphPath , RequestListener listener ) { request ( graphPath , new Bundle ( ) , "" , listener , null ) ; } public void request ( String graphPath , Bundle parameters , RequestListener listener , final Object state ) { request ( graphPath , parameters , "" , listener , state ) ; } public void request ( String graphPath , Bundle parameters , RequestListener listener ) { request ( graphPath , parameters , "" , listener , null ) ; } public void request ( final String graphPath , final Bundle parameters , final String httpMethod , final RequestListener listener , final Object state ) { new Thread ( ) { @ Override public void run ( ) { try { String resp = fb . request ( graphPath , parameters , httpMethod ) ; listener . onComplete ( resp , state ) ; } catch ( FileNotFoundException e ) { listener . onFileNotFoundException ( e , state ) ; } catch ( MalformedURLException e ) { listener . onMalformedURLException ( e , state ) ; } catch ( IOException e ) { listener . onIOException ( e , state ) ; } } } . start ( ) ; } public static interface RequestListener { public void onComplete ( String response , Object state ) ; public void onIOException ( IOException e , Object state ) ; public void onFileNotFoundException ( FileNotFoundException e , Object state ) ; public void onMalformedURLException ( MalformedURLException e , Object state ) ; public void onFacebookError ( FacebookError e , Object state ) ; } } package com . facebook . android ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . MalformedURLException ; import android . Manifest ; import android . app . Activity ; import android . content . ActivityNotFoundException ; import android . content . ComponentName ; import android . content . Context ; import android . content . Intent ; import android . content . ServiceConnection ; import android . content . pm . PackageInfo ; import android . content . pm . PackageManager ; import android . content . pm . PackageManager . NameNotFoundException ; import android . content . pm . ResolveInfo ; import android . content . pm . Signature ; import android . os . Bundle ; import android . os . Handler ; import android . os . IBinder ; import android . os . Message ; import android . os . Messenger ; import android . os . RemoteException ; import android . text . TextUtils ; import android . util . Log ; import android . webkit . CookieSyncManager ; public class Facebook { public static final String REDIRECT_URI = "" ; public static final String CANCEL_URI = "" ; public static final String TOKEN = "" ; public static final String EXPIRES = "" ; public static final String SINGLE_SIGN_ON_DISABLED = "" ; public static final int FORCE_DIALOG_AUTH = - ; private static final String LOGIN = "" ; private static final int DEFAULT_AUTH_ACTIVITY_CODE = ; protected static String DIALOG_BASE_URL = "" ; protected static String GRAPH_BASE_URL = "" ; protected static String RESTSERVER_URL = "" ; private String mAccessToken = null ; private long mLastAccessUpdate = ; private long mAccessExpires = ; private String mAppId ; private Activity mAuthActivity ; private String [ ] mAuthPermissions ; private int mAuthActivityCode ; private DialogListener mAuthDialogListener ; private FbDialog mFbDialog ; final private long REFRESH_TOKEN_BARRIER = * * * ; public Facebook ( String appId ) { if ( appId == null ) { throw new IllegalArgumentException ( "" + "" ) ; } mAppId = appId ; } public void authorize ( Activity activity , final DialogListener listener ) { authorize ( activity , new String [ ] { } , DEFAULT_AUTH_ACTIVITY_CODE , listener ) ; } public void authorize ( Activity activity , String [ ] permissions , final DialogListener listener ) { authorize ( activity , permissions , DEFAULT_AUTH_ACTIVITY_CODE , listener ) ; } public void authorize ( Activity activity , String [ ] permissions , int activityCode , final DialogListener listener ) { boolean singleSignOnStarted = false ; mAuthDialogListener = listener ; if ( activityCode >= ) { singleSignOnStarted = startSingleSignOn ( activity , mAppId , permissions , activityCode ) ; } if ( ! singleSignOnStarted ) { startDialogAuth ( activity , permissions ) ; } } private boolean startSingleSignOn ( Activity activity , String applicationId , String [ ] permissions , int activityCode ) { boolean didSucceed = true ; Intent intent = new Intent ( ) ; intent . setClassName ( "" , "" ) ; intent . putExtra ( "" , applicationId ) ; if ( permissions . length > ) { intent . putExtra ( "" , TextUtils . join ( "" , permissions ) ) ; } if ( ! validateAppSignatureForIntent ( activity , intent ) ) { return false ; } mAuthActivity = activity ; mAuthPermissions = permissions ; mAuthActivityCode = activityCode ; try { activity . startActivityForResult ( intent , activityCode ) ; } catch ( ActivityNotFoundException e ) { didSucceed = false ; } return didSucceed ; } private boolean validateAppSignatureForIntent ( Context context , Intent intent ) { ResolveInfo resolveInfo = context . getPackageManager ( ) . resolveActivity ( intent , ) ; if ( resolveInfo == null ) { return false ; } String packageName = resolveInfo . activityInfo . packageName ; PackageInfo packageInfo ; try { packageInfo = context . getPackageManager ( ) . getPackageInfo ( packageName , PackageManager . GET_SIGNATURES ) ; } catch ( NameNotFoundException e ) { return false ; } for ( Signature signature : packageInfo . signatures ) { if ( signature . toCharsString ( ) . equals ( FB_APP_SIGNATURE ) ) { return true ; } } return false ; } private void startDialogAuth ( Activity activity , String [ ] permissions ) { Bundle params = new Bundle ( ) ; if ( permissions . length > ) { params . putString ( "" , TextUtils . join ( "" , permissions ) ) ; } CookieSyncManager . createInstance ( activity ) ; dialog ( activity , LOGIN , params , new DialogListener ( ) { public void onComplete ( Bundle values ) { CookieSyncManager . getInstance ( ) . sync ( ) ; setAccessToken ( values . getString ( TOKEN ) ) ; setAccessExpiresIn ( values . getString ( EXPIRES ) ) ; if ( isSessionValid ( ) ) { Log . d ( "" , "" + getAccessToken ( ) + "" + getAccessExpires ( ) ) ; mAuthDialogListener . onComplete ( values ) ; } else { mAuthDialogListener . onFacebookError ( new FacebookError ( "" ) ) ; } } public void onError ( DialogError error ) { Log . d ( "" , "" + error ) ; mAuthDialogListener . onError ( error ) ; } public void onFacebookError ( FacebookError error ) { Log . d ( "" , "" + error ) ; mAuthDialogListener . onFacebookError ( error ) ; } public void onCancel ( ) { Log . d ( "" , "" ) ; mAuthDialogListener . onCancel ( ) ; } } ) ; } public void authorizeCallback ( int requestCode , int resultCode , Intent data ) { if ( requestCode == mAuthActivityCode ) { if ( resultCode == Activity . RESULT_OK ) { String error = data . getStringExtra ( "" ) ; if ( error == null ) { error = data . getStringExtra ( "" ) ; } if ( error != null ) { if ( error . equals ( SINGLE_SIGN_ON_DISABLED ) || error . equals ( "" ) ) { Log . d ( "" , "" + "" ) ; startDialogAuth ( mAuthActivity , mAuthPermissions ) ; } else if ( error . equals ( "" ) || error . equals ( "" ) ) { Log . d ( "" , "" ) ; mAuthDialogListener . onCancel ( ) ; } else { String description = data . getStringExtra ( "" ) ; if ( description != null ) { error = error + "" + description ; } Log . d ( "" , "" + error ) ; mAuthDialogListener . onFacebookError ( new FacebookError ( error ) ) ; } } else { setAccessToken ( data . getStringExtra ( TOKEN ) ) ; setAccessExpiresIn ( data . getStringExtra ( EXPIRES ) ) ; if ( isSessionValid ( ) ) { Log . d ( "" , "" + getAccessToken ( ) + "" + getAccessExpires ( ) ) ; mAuthDialogListener . onComplete ( data . getExtras ( ) ) ; } else { mAuthDialogListener . onFacebookError ( new FacebookError ( "" ) ) ; } } } else if ( resultCode == Activity . RESULT_CANCELED ) { if ( data != null ) { Log . d ( "" , "" + data . getStringExtra ( "" ) ) ; mAuthDialogListener . onError ( new DialogError ( data . getStringExtra ( "" ) , data . getIntExtra ( "" , - ) , data . getStringExtra ( "" ) ) ) ; } else { Log . d ( "" , "" ) ; mAuthDialogListener . onCancel ( ) ; } } } } public boolean extendAccessToken ( Context context , ServiceListener serviceListener ) { Intent intent = new Intent ( ) ; intent . setClassName ( "" , "" ) ; if ( ! validateAppSignatureForIntent ( context , intent ) ) { return false ; } return context . bindService ( intent , new TokenRefreshServiceConnection ( context , serviceListener ) , Context . BIND_AUTO_CREATE ) ; } public boolean extendAccessTokenIfNeeded ( Context context , ServiceListener serviceListener ) { if ( shouldExtendAccessToken ( ) ) { return extendAccessToken ( context , serviceListener ) ; } return true ; } public boolean shouldExtendAccessToken ( ) { return isSessionValid ( ) && ( System . currentTimeMillis ( ) - mLastAccessUpdate >= REFRESH_TOKEN_BARRIER ) ; } private class TokenRefreshServiceConnection implements ServiceConnection { final Messenger messageReceiver = new Messenger ( new Handler ( ) { @ Override public void handleMessage ( Message msg ) { String token = msg . getData ( ) . getString ( TOKEN ) ; long expiresAt = msg . getData ( ) . getLong ( EXPIRES ) * ; Bundle resultBundle = ( Bundle ) msg . getData ( ) . clone ( ) ; resultBundle . putLong ( EXPIRES , expiresAt ) ; if ( token != null ) { setAccessToken ( token ) ; setAccessExpires ( expiresAt ) ; if ( serviceListener != null ) { serviceListener . onComplete ( resultBundle ) ; } } else if ( serviceListener != null ) { String error = msg . getData ( ) . getString ( "" ) ; if ( msg . getData ( ) . containsKey ( "" ) ) { int errorCode = msg . getData ( ) . getInt ( "" ) ; serviceListener . onFacebookError ( new FacebookError ( error , null , errorCode ) ) ; } else { serviceListener . onError ( new Error ( error != null ? error : "" ) ) ; } } applicationsContext . unbindService ( TokenRefreshServiceConnection . this ) ; } } ) ; final ServiceListener serviceListener ; final Context applicationsContext ; Messenger messageSender = null ; public TokenRefreshServiceConnection ( Context applicationsContext , ServiceListener serviceListener ) { this . applicationsContext = applicationsContext ; this . serviceListener = serviceListener ; } @ Override public void onServiceConnected ( ComponentName className , IBinder service ) { messageSender = new Messenger ( service ) ; refreshToken ( ) ; } @ Override public void onServiceDisconnected ( ComponentName arg ) { serviceListener . onError ( new Error ( "" ) ) ; mAuthActivity . unbindService ( TokenRefreshServiceConnection . this ) ; } private void refreshToken ( ) { Bundle requestData = new Bundle ( ) ; requestData . putString ( TOKEN , mAccessToken ) ; Message request = Message . obtain ( ) ; request . setData ( requestData ) ; request . replyTo = messageReceiver ; try { messageSender . send ( request ) ; } catch ( RemoteException e ) { serviceListener . onError ( new Error ( "" ) ) ; } } } ; public String logout ( Context context ) throws MalformedURLException , IOException { Util . clearCookies ( context ) ; Bundle b = new Bundle ( ) ; b . putString ( "" , "" ) ; String response = request ( b ) ; setAccessToken ( null ) ; setAccessExpires ( ) ; return response ; } public String request ( Bundle parameters ) throws MalformedURLException , IOException { if ( ! parameters . containsKey ( "" ) ) { throw new IllegalArgumentException ( "" + "" + "" ) ; } return request ( null , parameters , "" ) ; } public String request ( String graphPath ) throws MalformedURLException , IOException { return request ( graphPath , new Bundle ( ) , "" ) ; } public String request ( String graphPath , Bundle parameters ) throws MalformedURLException , IOException { return request ( graphPath , parameters , "" ) ; } public String request ( String graphPath , Bundle params , String httpMethod ) throws FileNotFoundException , MalformedURLException , IOException { params . putString ( "" , "" ) ; if ( isSessionValid ( ) ) { params . putString ( TOKEN , getAccessToken ( ) ) ; } String url = ( graphPath != null ) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL ; return Util . openUrl ( url , httpMethod , params ) ; } public void dialog ( Context context , String action , DialogListener listener ) { dialog ( context , action , new Bundle ( ) , listener ) ; } public void dialog ( Context context , String action , Bundle parameters , final DialogListener listener ) { String endpoint = DIALOG_BASE_URL + action ; parameters . putString ( "" , "" ) ; parameters . putString ( "" , REDIRECT_URI ) ; if ( action . equals ( LOGIN ) ) { parameters . putString ( "" , "" ) ; parameters . putString ( "" , mAppId ) ; } else { parameters . putString ( "" , mAppId ) ; } if ( isSessionValid ( ) ) { parameters . putString ( TOKEN , getAccessToken ( ) ) ; } String url = endpoint + "" + Util . encodeUrl ( parameters ) ; if ( context . checkCallingOrSelfPermission ( Manifest . permission . INTERNET ) != PackageManager . PERMISSION_GRANTED ) { Util . showAlert ( context , "" , "" ) ; } else { if ( mFbDialog != null && mFbDialog . isShowing ( ) ) mFbDialog . dismiss ( ) ; mFbDialog = new FbDialog ( context , url , listener ) ; mFbDialog . show ( ) ; } } public void onDestroy ( ) { if ( mFbDialog != null && mFbDialog . isShowing ( ) ) mFbDialog . dismiss ( ) ; mFbDialog = null ; } public boolean isSessionValid ( ) { return ( getAccessToken ( ) != null ) && ( ( getAccessExpires ( ) == ) || ( System . currentTimeMillis ( ) < getAccessExpires ( ) ) ) ; } public String getAccessToken ( ) { return mAccessToken ; } public long getAccessExpires ( ) { return mAccessExpires ; } public void setAccessToken ( String token ) { mAccessToken = token ; mLastAccessUpdate = System . currentTimeMillis ( ) ; } public void setAccessExpires ( long time ) { mAccessExpires = time ; } public void setAccessExpiresIn ( String expiresIn ) { if ( expiresIn != null ) { long expires = expiresIn . equals ( "" ) ? : System . currentTimeMillis ( ) + Long . parseLong ( expiresIn ) * ; setAccessExpires ( expires ) ; } } public String getAppId ( ) { return mAppId ; } public void setAppId ( String appId ) { mAppId = appId ; } public static interface DialogListener { public void onComplete ( Bundle values ) ; public void onFacebookError ( FacebookError e ) ; public void onError ( DialogError e ) ; public void onCancel ( ) ; } public static interface ServiceListener { public void onComplete ( Bundle values ) ; public void onFacebookError ( FacebookError e ) ; public void onError ( Error e ) ; } public static final String FB_APP_SIGNATURE = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; } package com . google . android . c2dm ; import android . app . PendingIntent ; import android . content . Context ; import android . content . Intent ; import android . content . SharedPreferences ; import android . content . SharedPreferences . Editor ; public class C2DMessaging { public static final String EXTRA_SENDER = "" ; public static final String EXTRA_APPLICATION_PENDING_INTENT = "" ; public static final String REQUEST_UNREGISTRATION_INTENT = "" ; public static final String REQUEST_REGISTRATION_INTENT = "" ; public static final String LAST_REGISTRATION_CHANGE = "" ; public static final String BACKOFF = "" ; public static final String GSF_PACKAGE = "" ; static final String PREFERENCE = "" ; private static final long DEFAULT_BACKOFF = ; public static void register ( Context context , String senderId ) { Intent registrationIntent = new Intent ( REQUEST_REGISTRATION_INTENT ) ; registrationIntent . setPackage ( GSF_PACKAGE ) ; registrationIntent . putExtra ( EXTRA_APPLICATION_PENDING_INTENT , PendingIntent . getBroadcast ( context , , new Intent ( ) , ) ) ; registrationIntent . putExtra ( EXTRA_SENDER , senderId ) ; context . startService ( registrationIntent ) ; } public static void unregister ( Context context ) { Intent regIntent = new Intent ( REQUEST_UNREGISTRATION_INTENT ) ; regIntent . setPackage ( GSF_PACKAGE ) ; regIntent . putExtra ( EXTRA_APPLICATION_PENDING_INTENT , PendingIntent . getBroadcast ( context , , new Intent ( ) , ) ) ; context . startService ( regIntent ) ; } public static String getRegistrationId ( Context context ) { final SharedPreferences prefs = context . getSharedPreferences ( PREFERENCE , Context . MODE_PRIVATE ) ; String registrationId = prefs . getString ( "" , "" ) ; return registrationId ; } public static long getLastRegistrationChange ( Context context ) { final SharedPreferences prefs = context . getSharedPreferences ( PREFERENCE , Context . MODE_PRIVATE ) ; return prefs . getLong ( LAST_REGISTRATION_CHANGE , ) ; } static long getBackoff ( Context context ) { final SharedPreferences prefs = context . getSharedPreferences ( PREFERENCE , Context . MODE_PRIVATE ) ; return prefs . getLong ( BACKOFF , DEFAULT_BACKOFF ) ; } static void setBackoff ( Context context , long backoff ) { final SharedPreferences prefs = context . getSharedPreferences ( PREFERENCE , Context . MODE_PRIVATE ) ; Editor editor = prefs . edit ( ) ; editor . putLong ( BACKOFF , backoff ) ; editor . commit ( ) ; } static void clearRegistrationId ( Context context ) { final SharedPreferences prefs = context . getSharedPreferences ( PREFERENCE , Context . MODE_PRIVATE ) ; Editor editor = prefs . edit ( ) ; editor . putString ( "" , "" ) ; editor . putLong ( LAST_REGISTRATION_CHANGE , System . currentTimeMillis ( ) ) ; editor . commit ( ) ; } static void setRegistrationId ( Context context , String registrationId ) { final SharedPreferences prefs = context . getSharedPreferences ( PREFERENCE , Context . MODE_PRIVATE ) ; Editor editor = prefs . edit ( ) ; editor . putString ( "" , registrationId ) ; editor . commit ( ) ; } } package com . google . android . c2dm ; import java . io . IOException ; import android . app . AlarmManager ; import android . app . IntentService ; import android . app . PendingIntent ; import android . content . Context ; import android . content . ContextWrapper ; import android . content . Intent ; import android . os . PowerManager ; import android . util . Log ; public abstract class C2DMBaseReceiver extends IntentService { private static final String C2DM_RETRY = "" ; public static final String REGISTRATION_CALLBACK_INTENT = "" ; private static final String C2DM_INTENT = "" ; private static final String TAG = "" ; public static final String EXTRA_UNREGISTERED = "" ; public static final String EXTRA_ERROR = "" ; public static final String EXTRA_REGISTRATION_ID = "" ; public static final String ERR_SERVICE_NOT_AVAILABLE = "" ; public static final String ERR_ACCOUNT_MISSING = "" ; public static final String ERR_AUTHENTICATION_FAILED = "" ; public static final String ERR_TOO_MANY_REGISTRATIONS = "" ; public static final String ERR_INVALID_PARAMETERS = "" ; public static final String ERR_INVALID_SENDER = "" ; public static final String ERR_PHONE_REGISTRATION_ERROR = "" ; private static final String WAKELOCK_KEY = "" ; private static PowerManager . WakeLock mWakeLock ; private final String senderId ; public C2DMBaseReceiver ( String senderId ) { super ( senderId ) ; this . senderId = senderId ; } protected abstract void onMessage ( Context context , Intent intent ) ; public abstract void onError ( Context context , String errorId ) ; public void onRegistered ( Context context , String registrationId ) throws IOException { } public void onUnregistered ( Context context ) { } @ Override public final void onHandleIntent ( Intent intent ) { try { Context context = getApplicationContext ( ) ; if ( intent . getAction ( ) . equals ( REGISTRATION_CALLBACK_INTENT ) ) { handleRegistration ( context , intent ) ; } else if ( intent . getAction ( ) . equals ( C2DM_INTENT ) ) { onMessage ( context , intent ) ; } else if ( intent . getAction ( ) . equals ( C2DM_RETRY ) ) { C2DMessaging . register ( context , senderId ) ; } } finally { mWakeLock . release ( ) ; } } static void runIntentInService ( Context context , Intent intent ) { if ( mWakeLock == null ) { PowerManager pm = ( PowerManager ) context . getSystemService ( Context . POWER_SERVICE ) ; mWakeLock = pm . newWakeLock ( PowerManager . PARTIAL_WAKE_LOCK , WAKELOCK_KEY ) ; } mWakeLock . acquire ( ) ; ContextWrapper cwrap = ( ContextWrapper ) context ; String receiver = cwrap . getBaseContext ( ) . getClass ( ) . getPackage ( ) . getName ( ) + "" ; intent . setClassName ( context , receiver ) ; context . startService ( intent ) ; } private void handleRegistration ( final Context context , Intent intent ) { final String registrationId = intent . getStringExtra ( EXTRA_REGISTRATION_ID ) ; String error = intent . getStringExtra ( EXTRA_ERROR ) ; String removed = intent . getStringExtra ( EXTRA_UNREGISTERED ) ; if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "" + registrationId + "" + error + "" + removed ) ; } if ( removed != null ) { C2DMessaging . clearRegistrationId ( context ) ; onUnregistered ( context ) ; return ; } else if ( error != null ) { C2DMessaging . clearRegistrationId ( context ) ; Log . e ( TAG , "" + error ) ; onError ( context , error ) ; if ( "" . equals ( error ) ) { long backoffTimeMs = C2DMessaging . getBackoff ( context ) ; Log . d ( TAG , "" + backoffTimeMs ) ; Intent retryIntent = new Intent ( C2DM_RETRY ) ; PendingIntent retryPIntent = PendingIntent . getBroadcast ( context , , retryIntent , ) ; AlarmManager am = ( AlarmManager ) context . getSystemService ( Context . ALARM_SERVICE ) ; am . set ( AlarmManager . ELAPSED_REALTIME , backoffTimeMs , retryPIntent ) ; backoffTimeMs *= ; C2DMessaging . setBackoff ( context , backoffTimeMs ) ; } } else { try { onRegistered ( context , registrationId ) ; C2DMessaging . setRegistrationId ( context , registrationId ) ; } catch ( IOException ex ) { Log . e ( TAG , "" + ex . getMessage ( ) ) ; } } } } package com . google . android . c2dm ; import android . app . Activity ; import android . content . BroadcastReceiver ; import android . content . Context ; import android . content . Intent ; public class C2DMBroadcastReceiver extends BroadcastReceiver { @ Override public final void onReceive ( Context context , Intent intent ) { C2DMBaseReceiver . runIntentInService ( context , intent ) ; setResult ( Activity . RESULT_OK , null , null ) ; } } package org . miscwidgets . widget ; import org . miscwidgets . R ; import android . content . Context ; import android . content . res . TypedArray ; import android . graphics . Canvas ; import android . graphics . drawable . Drawable ; import android . text . method . KeyListener ; import android . util . AttributeSet ; import android . util . Log ; import android . view . GestureDetector ; import android . view . KeyEvent ; import android . view . MotionEvent ; import android . view . View ; import android . view . ViewGroup ; import android . view . ViewParent ; import android . view . GestureDetector . OnGestureListener ; import android . view . animation . Animation ; import android . view . animation . Interpolator ; import android . view . animation . LinearInterpolator ; import android . view . animation . TranslateAnimation ; import android . view . animation . Animation . AnimationListener ; import android . widget . FrameLayout ; import android . widget . LinearLayout ; public class Panel extends LinearLayout { private static final String TAG = "" ; public static interface OnPanelListener { public void onPanelClosed ( Panel panel ) ; public void onPanelOpened ( Panel panel ) ; } private boolean mIsShrinking ; private int mPosition ; private int mDuration ; private boolean mLinearFlying ; private int mHandleId ; private int mContentId ; private View mHandle ; private View mContent ; private Drawable mOpenedHandle ; private Drawable mClosedHandle ; private float mTrackX ; private float mTrackY ; private float mVelocity ; private OnPanelListener panelListener ; public static final int TOP = ; public static final int BOTTOM = ; public static final int LEFT = ; public static final int RIGHT = ; private enum State { ABOUT_TO_ANIMATE , ANIMATING , READY , TRACKING , FLYING , } ; private State mState ; private Interpolator mInterpolator ; private GestureDetector mGestureDetector ; private int mContentHeight ; private int mContentWidth ; private int mOrientation ; private float mWeight ; private PanelOnGestureListener mGestureListener ; private boolean mBringToFront ; public Panel ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; TypedArray a = context . obtainStyledAttributes ( attrs , R . styleable . Panel ) ; mDuration = a . getInteger ( R . styleable . Panel_animationDuration , ) ; mPosition = a . getInteger ( R . styleable . Panel_position , BOTTOM ) ; mLinearFlying = a . getBoolean ( R . styleable . Panel_linearFlying , false ) ; mWeight = a . getFraction ( R . styleable . Panel_weight , , , ) ; if ( mWeight < || mWeight > ) { mWeight = ; Log . w ( TAG , a . getPositionDescription ( ) + "" ) ; } mOpenedHandle = a . getDrawable ( R . styleable . Panel_openedHandle ) ; mClosedHandle = a . getDrawable ( R . styleable . Panel_closedHandle ) ; RuntimeException e = null ; mHandleId = a . getResourceId ( R . styleable . Panel_handle , ) ; if ( mHandleId == ) { e = new IllegalArgumentException ( a . getPositionDescription ( ) + "" ) ; } mContentId = a . getResourceId ( R . styleable . Panel_content , ) ; if ( mContentId == ) { e = new IllegalArgumentException ( a . getPositionDescription ( ) + "" ) ; } a . recycle ( ) ; if ( e != null ) { throw e ; } mOrientation = ( mPosition == TOP || mPosition == BOTTOM ) ? VERTICAL : HORIZONTAL ; setOrientation ( mOrientation ) ; mState = State . READY ; mGestureListener = new PanelOnGestureListener ( ) ; mGestureDetector = new GestureDetector ( mGestureListener ) ; mGestureDetector . setIsLongpressEnabled ( false ) ; setBaselineAligned ( false ) ; } public void setOnPanelListener ( OnPanelListener onPanelListener ) { panelListener = onPanelListener ; } public View getHandle ( ) { return mHandle ; } public View getContent ( ) { return mContent ; } public void setInterpolator ( Interpolator i ) { mInterpolator = i ; } public boolean setOpen ( boolean open , boolean animate ) { if ( mState == State . READY && isOpen ( ) ^ open ) { mIsShrinking = ! open ; if ( animate ) { mState = State . ABOUT_TO_ANIMATE ; if ( ! mIsShrinking ) { mContent . setVisibility ( VISIBLE ) ; } post ( startAnimation ) ; } else { mContent . setVisibility ( open ? VISIBLE : GONE ) ; postProcess ( ) ; } return true ; } return false ; } public boolean isOpen ( ) { return mContent . getVisibility ( ) == VISIBLE ; } @ Override protected void onFinishInflate ( ) { super . onFinishInflate ( ) ; mHandle = findViewById ( mHandleId ) ; if ( mHandle == null ) { String name = getResources ( ) . getResourceEntryName ( mHandleId ) ; throw new RuntimeException ( "" + name + "" ) ; } mHandle . setOnTouchListener ( touchListener ) ; mHandle . setOnClickListener ( clickListener ) ; mContent = findViewById ( mContentId ) ; if ( mContent == null ) { String name = getResources ( ) . getResourceEntryName ( mHandleId ) ; throw new RuntimeException ( "" + name + "" ) ; } removeView ( mHandle ) ; removeView ( mContent ) ; if ( mPosition == TOP || mPosition == LEFT ) { addView ( mContent ) ; addView ( mHandle ) ; } else { addView ( mHandle ) ; addView ( mContent ) ; } if ( mClosedHandle != null ) { mHandle . setBackgroundDrawable ( mClosedHandle ) ; } mContent . setClickable ( true ) ; mContent . setVisibility ( GONE ) ; if ( mWeight > ) { ViewGroup . LayoutParams params = mContent . getLayoutParams ( ) ; if ( mOrientation == VERTICAL ) { params . height = ViewGroup . LayoutParams . FILL_PARENT ; } else { params . width = ViewGroup . LayoutParams . FILL_PARENT ; } mContent . setLayoutParams ( params ) ; } } @ Override protected void onAttachedToWindow ( ) { super . onAttachedToWindow ( ) ; ViewParent parent = getParent ( ) ; if ( parent != null && parent instanceof FrameLayout ) { mBringToFront = true ; } } @ Override protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { if ( mWeight > && mContent . getVisibility ( ) == VISIBLE ) { View parent = ( View ) getParent ( ) ; if ( parent != null ) { if ( mOrientation == VERTICAL ) { heightMeasureSpec = MeasureSpec . makeMeasureSpec ( ( int ) ( parent . getHeight ( ) * mWeight ) , MeasureSpec . EXACTLY ) ; } else { widthMeasureSpec = MeasureSpec . makeMeasureSpec ( ( int ) ( parent . getWidth ( ) * mWeight ) , MeasureSpec . EXACTLY ) ; } } } super . onMeasure ( widthMeasureSpec , heightMeasureSpec ) ; } @ Override protected void onLayout ( boolean changed , int l , int t , int r , int b ) { super . onLayout ( changed , l , t , r , b ) ; mContentWidth = mContent . getWidth ( ) ; mContentHeight = mContent . getHeight ( ) ; } @ Override protected void dispatchDraw ( Canvas canvas ) { if ( mState == State . ABOUT_TO_ANIMATE && ! mIsShrinking ) { int delta = mOrientation == VERTICAL ? mContentHeight : mContentWidth ; if ( mPosition == LEFT || mPosition == TOP ) { delta = - delta ; } if ( mOrientation == VERTICAL ) { canvas . translate ( , delta ) ; } else { canvas . translate ( delta , ) ; } } if ( mState == State . TRACKING || mState == State . FLYING ) { canvas . translate ( mTrackX , mTrackY ) ; } super . dispatchDraw ( canvas ) ; } private float ensureRange ( float v , int min , int max ) { v = Math . max ( v , min ) ; v = Math . min ( v , max ) ; return v ; } OnTouchListener touchListener = new OnTouchListener ( ) { int initX ; int initY ; boolean setInitialPosition ; public boolean onTouch ( View v , MotionEvent event ) { if ( mState == State . ANIMATING ) { return false ; } int action = event . getAction ( ) ; if ( action == MotionEvent . ACTION_DOWN ) { if ( mBringToFront ) { bringToFront ( ) ; } initX = ; initY = ; if ( mContent . getVisibility ( ) == GONE ) { if ( mOrientation == VERTICAL ) { initY = mPosition == TOP ? - : ; } else { initX = mPosition == LEFT ? - : ; } } setInitialPosition = true ; } else { if ( setInitialPosition ) { initX *= mContentWidth ; initY *= mContentHeight ; mGestureListener . setScroll ( initX , initY ) ; setInitialPosition = false ; initX = - initX ; initY = - initY ; } event . offsetLocation ( initX , initY ) ; } if ( ! mGestureDetector . onTouchEvent ( event ) ) { if ( action == MotionEvent . ACTION_UP ) { post ( startAnimation ) ; } } return false ; } } ; OnClickListener clickListener = new OnClickListener ( ) { public void onClick ( View v ) { if ( mBringToFront ) { bringToFront ( ) ; } if ( initChange ( ) ) { post ( startAnimation ) ; } } } ; public boolean initChange ( ) { if ( mState != State . READY ) { return false ; } mState = State . ABOUT_TO_ANIMATE ; mIsShrinking = mContent . getVisibility ( ) == VISIBLE ; if ( ! mIsShrinking ) { mContent . setVisibility ( VISIBLE ) ; } return true ; } Runnable startAnimation = new Runnable ( ) { public void run ( ) { TranslateAnimation animation ; int fromXDelta = , toXDelta = , fromYDelta = , toYDelta = ; if ( mState == State . FLYING ) { mIsShrinking = ( mPosition == TOP || mPosition == LEFT ) ^ ( mVelocity > ) ; } int calculatedDuration ; if ( mOrientation == VERTICAL ) { int height = mContentHeight ; if ( ! mIsShrinking ) { fromYDelta = mPosition == TOP ? - height : height ; } else { toYDelta = mPosition == TOP ? - height : height ; } if ( mState == State . TRACKING ) { if ( Math . abs ( mTrackY - fromYDelta ) < Math . abs ( mTrackY - toYDelta ) ) { mIsShrinking = ! mIsShrinking ; toYDelta = fromYDelta ; } fromYDelta = ( int ) mTrackY ; } else if ( mState == State . FLYING ) { fromYDelta = ( int ) mTrackY ; } if ( mState == State . FLYING && mLinearFlying ) { calculatedDuration = ( int ) ( * Math . abs ( ( toYDelta - fromYDelta ) / mVelocity ) ) ; calculatedDuration = Math . max ( calculatedDuration , ) ; } else { calculatedDuration = mDuration * Math . abs ( toYDelta - fromYDelta ) / mContentHeight ; } } else { int width = mContentWidth ; if ( ! mIsShrinking ) { fromXDelta = mPosition == LEFT ? - width : width ; } else { toXDelta = mPosition == LEFT ? - width : width ; } if ( mState == State . TRACKING ) { if ( Math . abs ( mTrackX - fromXDelta ) < Math . abs ( mTrackX - toXDelta ) ) { mIsShrinking = ! mIsShrinking ; toXDelta = fromXDelta ; } fromXDelta = ( int ) mTrackX ; } else if ( mState == State . FLYING ) { fromXDelta = ( int ) mTrackX ; } if ( mState == State . FLYING && mLinearFlying ) { calculatedDuration = ( int ) ( * Math . abs ( ( toXDelta - fromXDelta ) / mVelocity ) ) ; calculatedDuration = Math . max ( calculatedDuration , ) ; } else { calculatedDuration = mDuration * Math . abs ( toXDelta - fromXDelta ) / mContentWidth ; } } mTrackX = mTrackY = ; if ( calculatedDuration == ) { mState = State . READY ; if ( mIsShrinking ) { mContent . setVisibility ( GONE ) ; } postProcess ( ) ; return ; } animation = new TranslateAnimation ( fromXDelta , toXDelta , fromYDelta , toYDelta ) ; animation . setDuration ( calculatedDuration ) ; animation . setAnimationListener ( animationListener ) ; if ( mState == State . FLYING && mLinearFlying ) { animation . setInterpolator ( new LinearInterpolator ( ) ) ; } else if ( mInterpolator != null ) { animation . setInterpolator ( mInterpolator ) ; } startAnimation ( animation ) ; } } ; private AnimationListener animationListener = new AnimationListener ( ) { public void onAnimationEnd ( Animation animation ) { mState = State . READY ; if ( mIsShrinking ) { mContent . setVisibility ( GONE ) ; } postProcess ( ) ; } public void onAnimationRepeat ( Animation animation ) { } public void onAnimationStart ( Animation animation ) { mState = State . ANIMATING ; } } ; private void postProcess ( ) { if ( mIsShrinking && mClosedHandle != null ) { mHandle . setBackgroundDrawable ( mClosedHandle ) ; } else if ( ! mIsShrinking && mOpenedHandle != null ) { mHandle . setBackgroundDrawable ( mOpenedHandle ) ; } if ( panelListener != null ) { if ( mIsShrinking ) { panelListener . onPanelClosed ( Panel . this ) ; } else { panelListener . onPanelOpened ( Panel . this ) ; } } } class PanelOnGestureListener implements OnGestureListener { float scrollY ; float scrollX ; public void setScroll ( int initScrollX , int initScrollY ) { scrollX = initScrollX ; scrollY = initScrollY ; } public boolean onDown ( MotionEvent e ) { scrollX = scrollY = ; initChange ( ) ; return true ; } public boolean onFling ( MotionEvent e1 , MotionEvent e2 , float velocityX , float velocityY ) { mState = State . FLYING ; mVelocity = mOrientation == VERTICAL ? velocityY : velocityX ; post ( startAnimation ) ; return true ; } public void onLongPress ( MotionEvent e ) { } public boolean onScroll ( MotionEvent e1 , MotionEvent e2 , float distanceX , float distanceY ) { mState = State . TRACKING ; float tmpY = , tmpX = ; if ( mOrientation == VERTICAL ) { scrollY -= distanceY ; if ( mPosition == TOP ) { tmpY = ensureRange ( scrollY , - mContentHeight , ) ; } else { tmpY = ensureRange ( scrollY , , mContentHeight ) ; } } else { scrollX -= distanceX ; if ( mPosition == LEFT ) { tmpX = ensureRange ( scrollX , - mContentWidth , ) ; } else { tmpX = ensureRange ( scrollX , , mContentWidth ) ; } } if ( tmpX != mTrackX || tmpY != mTrackY ) { mTrackX = tmpX ; mTrackY = tmpY ; invalidate ( ) ; } return true ; } public void onShowPress ( MotionEvent e ) { } public boolean onSingleTapUp ( MotionEvent e ) { return false ; } } } package og . android . tether ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . lang . reflect . Field ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Hashtable ; import java . util . List ; import java . util . Properties ; import java . util . UUID ; import com . google . analytics . tracking . android . EasyTracker ; import og . android . tether . data . ClientData ; import og . android . tether . system . Configuration ; import og . android . tether . system . ConfigurationAdv ; import og . android . tether . system . CoreTask ; import og . android . tether . system . WebserviceTask ; import android . app . AlarmManager ; import android . app . Application ; import android . app . Notification ; import android . app . NotificationManager ; import android . app . PendingIntent ; import android . content . Context ; import android . content . Intent ; import android . content . SharedPreferences ; import android . content . pm . PackageInfo ; import android . content . pm . PackageManager ; import android . location . Location ; import android . location . LocationManager ; import android . net . Uri ; import android . os . Build ; import android . os . Bundle ; import android . os . Handler ; import android . os . Looper ; import android . os . Message ; import android . os . PowerManager ; import android . preference . PreferenceManager ; import android . provider . Settings ; import android . provider . Settings . SettingNotFoundException ; import android . telephony . TelephonyManager ; import android . util . Log ; import android . widget . Toast ; public class TetherApplication extends Application { public static final String MSG_TAG = "" ; public static final String MESHCLIENT_GOOGLE_PLAY_URL = "" ; public static final String MESSAGE_LAUNCH_CHECK = "" ; public final String DEFAULT_PASSPHRASE = "" ; public final String DEFAULT_LANNETWORK = "" ; public final String DEFAULT_ENCSETUP = "" ; public final String DEFAULT_SSID = "" ; public String deviceType = Configuration . DEVICE_GENERIC ; public String interfaceDriver = Configuration . DRIVER_WEXT ; public ConfigurationAdv configurationAdv = new ConfigurationAdv ( ) ; public boolean startupCheckPerformed = false ; static final int CLIENT_CONNECT_ACDISABLED = ; static final int CLIENT_CONNECT_AUTHORIZED = ; static final int CLIENT_CONNECT_NOTAUTHORIZED = ; static TetherApplication singleton ; private PowerManager powerManager = null ; private PowerManager . WakeLock wakeLock = null ; public SharedPreferences settings = null ; public SharedPreferences . Editor preferenceEditor = null ; public NotificationManager notificationManager ; private Notification notification ; private int clientNotificationCount = ; private PendingIntent mainIntent ; private PendingIntent accessControlIntent ; ArrayList < ClientData > clientDataAddList = new ArrayList < ClientData > ( ) ; ArrayList < String > clientMacRemoveList = new ArrayList < String > ( ) ; boolean accessControlSupported = true ; int lastTemperature = ; public CoreTask . Whitelist whitelist = null ; public CoreTask . WpaSupplicant wpasupplicant = null ; public CoreTask . TiWlanConf tiwlan = null ; public CoreTask . TetherConfig tethercfg = null ; public CoreTask . DnsmasqConfig dnsmasqcfg = null ; public CoreTask . HostapdConfig hostapdcfg = null ; public CoreTask . BluetoothConfig btcfg = null ; public CoreTask coretask = null ; public FBManager FBManager = null ; boolean offeredMeshclient = false ; private static final String APPLICATION_PROPERTIES_URL = "" ; private static final String APPLICATION_DOWNLOAD_URL = "" ; private static final String APPLICATION_STATS_URL = "" ; static final String FORUM_URL = "" ; static final String FORUM_RSS_URL = "" ; static final String MESSAGE_POST_STATS = "" ; static final String MESSAGE_REPORT_STATS = "" ; @ Override public void onCreate ( ) { Log . d ( MSG_TAG , "" ) ; EasyTracker . getInstance ( ) . setContext ( getApplicationContext ( ) ) ; TetherApplication . singleton = this ; this . coretask = new CoreTask ( ) ; try { this . coretask . setPath ( this . getApplicationContext ( ) . getFilesDir ( ) . getParent ( ) ) ; } catch ( Exception e ) { this . coretask . setPath ( "" ) ; } Log . d ( MSG_TAG , "" + this . coretask . DATA_FILE_PATH ) ; this . checkDirs ( ) ; this . deviceType = Configuration . getDeviceType ( ) ; this . interfaceDriver = Configuration . getWifiInterfaceDriver ( this . deviceType ) ; this . settings = PreferenceManager . getDefaultSharedPreferences ( this ) ; this . preferenceEditor = settings . edit ( ) ; this . whitelist = this . coretask . new Whitelist ( ) ; this . wpasupplicant = this . coretask . new WpaSupplicant ( ) ; this . tiwlan = this . coretask . new TiWlanConf ( ) ; this . tethercfg = this . coretask . new TetherConfig ( ) ; this . tethercfg . read ( ) ; this . dnsmasqcfg = this . coretask . new DnsmasqConfig ( ) ; this . hostapdcfg = this . coretask . new HostapdConfig ( ) ; this . btcfg = this . coretask . new BluetoothConfig ( ) ; powerManager = ( PowerManager ) getSystemService ( Context . POWER_SERVICE ) ; wakeLock = powerManager . newWakeLock ( PowerManager . SCREEN_DIM_WAKE_LOCK , "" ) ; if ( this . settings . getBoolean ( "" , false ) ) { FBManager = new FBManager ( this ) ; FBManager . extendAccessTokenIfNeeded ( this , null ) ; } this . notificationManager = ( NotificationManager ) this . getSystemService ( Context . NOTIFICATION_SERVICE ) ; this . notification = new Notification ( R . drawable . start_notification , "" , System . currentTimeMillis ( ) ) ; this . mainIntent = PendingIntent . getActivity ( this , , new Intent ( this , MainActivity . class ) , ) ; this . accessControlIntent = PendingIntent . getActivity ( this , , new Intent ( this , AccessControlActivity . class ) , ) ; requestStatsAlarm ( ) ; updateDeviceParametersAdv ( ) ; updateConfiguration ( ) ; } @ Override public void onTerminate ( ) { Log . d ( MSG_TAG , "" ) ; this . notificationManager . cancelAll ( ) ; } public synchronized void addClientData ( ClientData clientData ) { this . clientDataAddList . add ( clientData ) ; } public synchronized void removeClientMac ( String mac ) { this . clientMacRemoveList . add ( mac ) ; } public synchronized ArrayList < ClientData > getClientDataAddList ( ) { ArrayList < ClientData > tmp = this . clientDataAddList ; this . clientDataAddList = new ArrayList < ClientData > ( ) ; return tmp ; } public synchronized ArrayList < String > getClientMacRemoveList ( ) { ArrayList < String > tmp = this . clientMacRemoveList ; this . clientMacRemoveList = new ArrayList < String > ( ) ; return tmp ; } public synchronized void resetClientMacLists ( ) { this . clientDataAddList = new ArrayList < ClientData > ( ) ; this . clientMacRemoveList = new ArrayList < String > ( ) ; } public void updateConfiguration ( ) { Log . d ( MSG_TAG , "" ) ; if ( ! this . settings . getString ( "" , "" ) . equals ( "" ) ) { updateConfigurationAdv ( ) ; return ; } long startStamp = System . currentTimeMillis ( ) ; boolean bluetoothPref = this . settings . getBoolean ( "" , false ) ; boolean encEnabled = this . settings . getBoolean ( "" , false ) ; boolean acEnabled = this . settings . getBoolean ( "" , false ) ; String ssid = this . settings . getString ( "" , DEFAULT_SSID ) ; String txpower = this . settings . getString ( "" , "" ) ; String lannetwork = this . settings . getString ( "" , DEFAULT_LANNETWORK ) ; String wepkey = this . settings . getString ( "" , DEFAULT_PASSPHRASE ) ; String wepsetupMethod = this . settings . getString ( "" , DEFAULT_ENCSETUP ) ; String channel = this . settings . getString ( "" , "" ) ; String subnet = lannetwork . substring ( , lannetwork . lastIndexOf ( "" ) ) ; this . tethercfg . read ( ) ; this . tethercfg . put ( "" , deviceType ) ; this . tethercfg . put ( "" , bluetoothPref ? "" : "" ) ; this . tethercfg . put ( "" , ssid ) ; this . tethercfg . put ( "" , channel ) ; this . tethercfg . put ( "" , lannetwork . split ( "" ) [ ] ) ; this . tethercfg . put ( "" , subnet + "" ) ; if ( Configuration . enableFixPersist ( ) ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , "" ) ; } if ( Configuration . enableFixRoute ( ) ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , "" ) ; } if ( Configuration . getDeviceType ( ) . equals ( Configuration . DEVICE_NEXUSONE ) && Configuration . getWifiInterfaceDriver ( this . deviceType ) . equals ( Configuration . DRIVER_SOFTAP_GOG ) ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , this . coretask . getProp ( "" ) ) ; } this . tethercfg . put ( "" , txpower ) ; if ( encEnabled ) { if ( this . interfaceDriver . startsWith ( "" ) ) { this . tethercfg . put ( "" , "" ) ; } else if ( this . interfaceDriver . equals ( Configuration . DRIVER_HOSTAP ) ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , "" ) ; } this . tethercfg . put ( "" , wepkey ) ; if ( wepsetupMethod . equals ( "" ) ) { wepsetupMethod = Configuration . getEncryptionAutoMethod ( deviceType ) ; } this . tethercfg . put ( "" , wepsetupMethod ) ; if ( wepsetupMethod . equals ( "" ) ) { if ( this . wpasupplicant . exists ( ) == false ) { this . installWpaSupplicantConfig ( ) ; } Hashtable < String , String > values = new Hashtable < String , String > ( ) ; values . put ( "" , "" + this . settings . getString ( "" , DEFAULT_SSID ) + "" ) ; values . put ( "" , "" + this . settings . getString ( "" , DEFAULT_PASSPHRASE ) + "" ) ; this . wpasupplicant . write ( values ) ; } } else { this . tethercfg . put ( "" , "" ) ; this . tethercfg . put ( "" , "" ) ; if ( this . wpasupplicant . exists ( ) ) { this . wpasupplicant . remove ( ) ; } } this . tethercfg . put ( "" , Configuration . getWifiInterfaceDriver ( deviceType ) ) ; if ( this . tethercfg . write ( ) == false ) { Log . e ( MSG_TAG , "" ) ; } this . dnsmasqcfg . set ( lannetwork ) ; if ( this . dnsmasqcfg . write ( ) == false ) { Log . e ( MSG_TAG , "" ) ; } if ( this . interfaceDriver . equals ( Configuration . DRIVER_HOSTAP ) ) { this . installHostapdConfig ( ) ; this . hostapdcfg . read ( ) ; if ( this . deviceType . equals ( Configuration . DEVICE_DROIDX ) ) { this . hostapdcfg . put ( "" , ssid ) ; this . hostapdcfg . put ( "" , channel ) ; if ( encEnabled ) { this . hostapdcfg . put ( "" , "" + ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , wepkey ) ; } } else if ( this . deviceType . equals ( Configuration . DEVICE_BLADE ) ) { this . hostapdcfg . put ( "" , ssid ) ; this . hostapdcfg . put ( "" , channel ) ; if ( encEnabled ) { this . hostapdcfg . put ( "" , "" + ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , wepkey ) ; } } if ( this . hostapdcfg . write ( ) == false ) { Log . e ( MSG_TAG , "" ) ; } } this . btcfg . set ( lannetwork ) ; if ( this . btcfg . write ( ) == false ) { Log . e ( MSG_TAG , "" ) ; } if ( acEnabled ) { if ( this . whitelist . exists ( ) == false ) { try { this . whitelist . touch ( ) ; } catch ( IOException e ) { Log . e ( MSG_TAG , "" ) ; e . printStackTrace ( ) ; } } } else { if ( this . whitelist . exists ( ) ) { this . whitelist . remove ( ) ; } } if ( deviceType . equals ( Configuration . DEVICE_DREAM ) ) { Hashtable < String , String > values = new Hashtable < String , String > ( ) ; values . put ( "" , this . settings . getString ( "" , DEFAULT_SSID ) ) ; values . put ( "" , this . settings . getString ( "" , "" ) ) ; this . tiwlan . write ( values ) ; } Log . d ( MSG_TAG , "" + ( System . currentTimeMillis ( ) - startStamp ) + "" ) ; } public String getTetherNetworkDevice ( ) { boolean bluetoothPref = this . settings . getBoolean ( "" , false ) ; if ( bluetoothPref ) return "" ; else { if ( Configuration . getDeviceType ( ) . equals ( Configuration . DEVICE_NEXUSONE ) && Configuration . getWifiInterfaceDriver ( this . deviceType ) . equals ( Configuration . DRIVER_SOFTAP_GOG ) ) { return "" ; } else { return this . coretask . getProp ( "" ) ; } } } public boolean isConfigurationAdv ( ) { return ! this . settings . getString ( "" , "" ) . equals ( "" ) || ! this . settings . getString ( "" , "" ) . equals ( "" ) ; } public void updateDeviceParametersAdv ( ) { Log . d ( MSG_TAG , "" ) ; String device = this . settings . getString ( "" , "" ) ; if ( device . equals ( "" ) ) { device = Configuration . getDeviceType ( ) ; } else if ( device . equals ( "" ) ) { this . configurationAdv = new ConfigurationAdv ( ) ; } else { this . configurationAdv = new ConfigurationAdv ( device ) ; } } public ConfigurationAdv getDeviceParametersAdv ( ) { return this . configurationAdv ; } public void updateConfigurationAdv ( ) { Log . d ( MSG_TAG , "" ) ; long startStamp = System . currentTimeMillis ( ) ; updateDeviceParametersAdv ( ) ; boolean encEnabled = this . settings . getBoolean ( "" , false ) ; boolean acEnabled = this . settings . getBoolean ( "" , false ) ; boolean bluetoothPref = this . settings . getBoolean ( "" , false ) ; String ssid = this . settings . getString ( "" , DEFAULT_SSID ) ; String txpower = this . settings . getString ( "" , "" ) ; String lannetwork = this . settings . getString ( "" , DEFAULT_LANNETWORK ) ; String wepkey = this . settings . getString ( "" , DEFAULT_PASSPHRASE ) ; String wepsetupMethod = this . settings . getString ( "" , DEFAULT_ENCSETUP ) ; String channel = this . settings . getString ( "" , "" ) ; boolean mssclampingEnabled = this . settings . getBoolean ( "" , false ) ; boolean routefixEnabled = this . settings . getBoolean ( "" , false ) ; String primaryDns = this . settings . getString ( "" , "" ) ; String secondaryDns = this . settings . getString ( "" , "" ) ; boolean hideSSID = this . settings . getBoolean ( "" , false ) ; boolean reloadDriver = this . settings . getBoolean ( "" , true ) ; String setupMethod = this . settings . getString ( "" , "" ) ; if ( configurationAdv . isTiadhocSupported ( ) == false ) { if ( setupMethod . equals ( "" ) ) { setupMethod = configurationAdv . getAutoSetupMethod ( ) ; } } else { setupMethod = "" ; } Log . d ( MSG_TAG , "" + setupMethod ) ; String subnet = lannetwork . substring ( , lannetwork . lastIndexOf ( "" ) ) ; this . tethercfg . put ( "" , "" ) ; this . tethercfg . put ( "" , bluetoothPref ? "" : "" ) ; this . tethercfg . put ( "" , configurationAdv . getDevice ( ) ) ; this . tethercfg . put ( "" , ssid ) ; this . tethercfg . put ( "" , channel ) ; this . tethercfg . put ( "" , lannetwork . split ( "" ) [ ] ) ; this . tethercfg . put ( "" , subnet + "" ) ; this . tethercfg . put ( "" , "" ) ; this . tethercfg . put ( "" , primaryDns ) ; this . tethercfg . put ( "" , secondaryDns ) ; if ( mssclampingEnabled ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , "" ) ; } if ( hideSSID ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , "" ) ; } if ( reloadDriver ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , "" ) ; } if ( routefixEnabled ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , "" ) ; } this . tethercfg . put ( "" , "" + configurationAdv . isGenericSetupSection ( ) ) ; this . tethercfg . put ( "" , this . coretask . getProp ( "" ) ) ; this . tethercfg . put ( "" , setupMethod ) ; if ( setupMethod . equals ( "" ) ) { this . tethercfg . put ( "" , this . tethercfg . get ( "" ) ) ; if ( encEnabled ) { this . tethercfg . put ( "" , "" ) ; } } else if ( setupMethod . equals ( "" ) ) { this . tethercfg . put ( "" , configurationAdv . getNetdInterface ( ) ) ; if ( encEnabled ) { this . tethercfg . put ( "" , configurationAdv . getEncryptionIdentifier ( ) ) ; } else { this . tethercfg . put ( "" , configurationAdv . getOpennetworkIdentifier ( ) ) ; } } else if ( setupMethod . equals ( "" ) ) { this . tethercfg . put ( "" , configurationAdv . getHostapdKernelModulePath ( ) ) ; this . tethercfg . put ( "" , configurationAdv . getHostapdKernelModuleName ( ) ) ; this . tethercfg . put ( "" , configurationAdv . getHostapdPath ( ) ) ; this . tethercfg . put ( "" , configurationAdv . getHostapdInterface ( ) ) ; if ( encEnabled ) { this . tethercfg . put ( "" , "" ) ; } if ( configurationAdv . getHostapdLoaderCmd ( ) == null || configurationAdv . getHostapdLoaderCmd ( ) . length ( ) <= ) { this . tethercfg . put ( "" , "" ) ; } else { this . tethercfg . put ( "" , configurationAdv . getHostapdLoaderCmd ( ) ) ; } } else if ( setupMethod . equals ( "" ) ) { this . tethercfg . put ( "" , configurationAdv . getTiadhocInterface ( ) ) ; if ( encEnabled ) { this . tethercfg . put ( "" , "" ) ; } } else if ( setupMethod . startsWith ( "" ) ) { this . tethercfg . put ( "" , configurationAdv . getSoftapInterface ( ) ) ; this . tethercfg . put ( "" , configurationAdv . getSoftapFirmwarePath ( ) ) ; if ( encEnabled ) { this . tethercfg . put ( "" , configurationAdv . getEncryptionIdentifier ( ) ) ; } else { this . tethercfg . put ( "" , configurationAdv . getOpennetworkIdentifier ( ) ) ; } } this . tethercfg . put ( "" , configurationAdv . getWifiLoadCmd ( ) ) ; this . tethercfg . put ( "" , configurationAdv . getWifiUnloadCmd ( ) ) ; this . tethercfg . put ( "" , txpower ) ; if ( encEnabled ) { this . tethercfg . put ( "" , wepkey ) ; if ( wepsetupMethod . equals ( "" ) ) { if ( configurationAdv . isWextSupported ( ) ) { wepsetupMethod = "" ; } else if ( configurationAdv . isTiadhocSupported ( ) ) { wepsetupMethod = "" ; } } this . tethercfg . put ( "" , wepsetupMethod ) ; if ( wepsetupMethod . equals ( "" ) ) { if ( this . wpasupplicant . exists ( ) == false ) { this . installWpaSupplicantConfig ( ) ; } Hashtable < String , String > values = new Hashtable < String , String > ( ) ; values . put ( "" , "" + this . settings . getString ( "" , DEFAULT_SSID ) + "" ) ; values . put ( "" , "" + this . settings . getString ( "" , DEFAULT_PASSPHRASE ) + "" ) ; this . wpasupplicant . write ( values ) ; } } else { this . tethercfg . put ( "" , "" ) ; this . tethercfg . put ( "" , "" ) ; if ( this . wpasupplicant . exists ( ) ) { this . wpasupplicant . remove ( ) ; } } String [ ] lanparts = lannetwork . split ( "" ) ; this . tethercfg . put ( "" , lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" ) ; if ( this . tethercfg . write ( ) == false ) { Log . e ( MSG_TAG , "" ) ; } if ( setupMethod . equals ( "" ) ) { this . installHostapdConfig ( configurationAdv . getHostapdTemplate ( ) ) ; this . hostapdcfg . read ( ) ; if ( configurationAdv . getHostapdTemplate ( ) . equals ( "" ) ) { this . hostapdcfg . put ( "" , ssid ) ; this . hostapdcfg . put ( "" , channel ) ; this . hostapdcfg . put ( "" , configurationAdv . getHostapdInterface ( ) ) ; if ( encEnabled ) { this . hostapdcfg . put ( "" , "" + ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , wepkey ) ; } } else if ( configurationAdv . getHostapdTemplate ( ) . equals ( "" ) ) { this . hostapdcfg . put ( "" , ssid ) ; this . hostapdcfg . put ( "" , channel ) ; if ( encEnabled ) { this . hostapdcfg . put ( "" , "" + ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , wepkey ) ; } } else if ( configurationAdv . getHostapdTemplate ( ) . equals ( "" ) ) { this . hostapdcfg . put ( "" , ssid ) ; this . hostapdcfg . put ( "" , channel ) ; this . hostapdcfg . put ( "" , configurationAdv . getHostapdInterface ( ) ) ; if ( encEnabled ) { this . hostapdcfg . put ( "" , "" + ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , "" ) ; this . hostapdcfg . put ( "" , wepkey ) ; } } if ( this . hostapdcfg . write ( ) == false ) { Log . e ( MSG_TAG , "" ) ; } } if ( acEnabled ) { if ( this . whitelist . exists ( ) == false ) { try { this . whitelist . touch ( ) ; } catch ( IOException e ) { Log . e ( MSG_TAG , "" ) ; e . printStackTrace ( ) ; } } } else { if ( this . whitelist . exists ( ) ) { this . whitelist . remove ( ) ; } } if ( configurationAdv . isTiadhocSupported ( ) ) { TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . tiwlan_ini ) ; Hashtable < String , String > values = this . tiwlan . get ( ) ; values . put ( "" , this . settings . getString ( "" , DEFAULT_SSID ) ) ; values . put ( "" , this . settings . getString ( "" , "" ) ) ; this . tiwlan . write ( values ) ; } else { File tiwlanconf = new File ( TetherApplication . this . coretask . DATA_FILE_PATH + "" ) ; if ( tiwlanconf . exists ( ) ) { tiwlanconf . delete ( ) ; } } Log . d ( MSG_TAG , "" + ( System . currentTimeMillis ( ) - startStamp ) + "" ) ; } public void installHostapdConfig ( String hostapdTemplate ) { if ( hostapdTemplate . equals ( "" ) ) { this . copyFile ( this . coretask . DATA_FILE_PATH + "" , "" , R . raw . hostapd_conf_droi ) ; } else if ( hostapdTemplate . equals ( "" ) ) { this . copyFile ( this . coretask . DATA_FILE_PATH + "" , "" , R . raw . hostapd_conf_mini ) ; } else if ( hostapdTemplate . equals ( "" ) ) { this . copyFile ( this . coretask . DATA_FILE_PATH + "" , "" , R . raw . hostapd_conf_tiap ) ; } } public boolean isWakeLockDisabled ( ) { return this . settings . getBoolean ( "" , true ) ; } public boolean isSyncDisabled ( ) { return this . settings . getBoolean ( "" , false ) ; } public boolean isUpdatecDisabled ( ) { return this . settings . getBoolean ( "" , false ) ; } public boolean showDonationDialog ( ) { return this . settings . getBoolean ( "" , true ) ; } public void releaseWakeLock ( ) { try { if ( this . wakeLock != null && this . wakeLock . isHeld ( ) ) { Log . d ( MSG_TAG , "" ) ; this . wakeLock . release ( ) ; } } catch ( Exception ex ) { Log . d ( MSG_TAG , "" + ex . getMessage ( ) ) ; } } public void acquireWakeLock ( ) { try { if ( this . isWakeLockDisabled ( ) == false ) { Log . d ( MSG_TAG , "" ) ; this . wakeLock . acquire ( ) ; } } catch ( Exception ex ) { Log . d ( MSG_TAG , "" + ex . getMessage ( ) ) ; } } public int getNotificationType ( ) { return Integer . parseInt ( this . settings . getString ( "" , "" ) ) ; } public void showStartNotification ( String message ) { notification . flags = Notification . FLAG_ONGOING_EVENT ; notification . setLatestEventInfo ( this , getString ( R . string . global_application_name ) , message , this . mainIntent ) ; this . notificationManager . notify ( - , this . notification ) ; } public Notification getStartNotification ( String message ) { notification . flags = Notification . FLAG_ONGOING_EVENT ; notification . setLatestEventInfo ( this , getString ( R . string . global_application_name ) , message , this . mainIntent ) ; return notification ; } Handler clientConnectHandler = new Handler ( ) { public void handleMessage ( Message msg ) { ClientData clientData = ( ClientData ) msg . obj ; TetherApplication . this . showClientConnectNotification ( clientData , msg . what ) ; } } ; public void showClientConnectNotification ( ClientData clientData , int authType ) { int notificationIcon = R . drawable . secmedium ; String notificationString = "" ; switch ( authType ) { case CLIENT_CONNECT_ACDISABLED : notificationIcon = R . drawable . secmedium ; notificationString = getString ( R . string . global_application_accesscontrol_disabled ) ; break ; case CLIENT_CONNECT_AUTHORIZED : notificationIcon = R . drawable . sechigh ; notificationString = getString ( R . string . global_application_accesscontrol_authorized ) ; break ; case CLIENT_CONNECT_NOTAUTHORIZED : notificationIcon = R . drawable . seclow ; notificationString = getString ( R . string . global_application_accesscontrol_authorized ) ; } Log . d ( MSG_TAG , "" + notificationString + "" + clientData . getClientName ( ) + "" + clientData . getMacAddress ( ) ) ; Notification clientConnectNotification = new Notification ( notificationIcon , getString ( R . string . global_application_name ) , System . currentTimeMillis ( ) ) ; clientConnectNotification . tickerText = clientData . getClientName ( ) + "" + clientData . getMacAddress ( ) + "" ; if ( ! this . settings . getString ( "" , "" ) . equals ( "" ) ) clientConnectNotification . sound = Uri . parse ( this . settings . getString ( "" , "" ) ) ; if ( this . settings . getBoolean ( "" , true ) ) clientConnectNotification . vibrate = new long [ ] { , , , } ; if ( this . accessControlSupported ) clientConnectNotification . setLatestEventInfo ( this , getString ( R . string . global_application_name ) + "" + notificationString , clientData . getClientName ( ) + "" + clientData . getMacAddress ( ) + "" + getString ( R . string . global_application_connected ) + "" , this . accessControlIntent ) ; else clientConnectNotification . setLatestEventInfo ( this , getString ( R . string . global_application_name ) + "" + notificationString , clientData . getClientName ( ) + "" + clientData . getMacAddress ( ) + "" + getString ( R . string . global_application_connected ) + "" , this . mainIntent ) ; clientConnectNotification . flags = Notification . FLAG_AUTO_CANCEL ; this . notificationManager . notify ( this . clientNotificationCount , clientConnectNotification ) ; this . clientNotificationCount ++ ; } public boolean binariesExists ( ) { File file = new File ( this . coretask . DATA_FILE_PATH + "" ) ; return file . exists ( ) ; } public void installWpaSupplicantConfig ( ) { this . copyFile ( this . coretask . DATA_FILE_PATH + "" , "" , R . raw . wpa_supplicant_conf ) ; } public void installHostapdConfig ( ) { if ( this . deviceType . equals ( Configuration . DEVICE_DROIDX ) ) { this . copyFile ( this . coretask . DATA_FILE_PATH + "" , "" , R . raw . hostapd_conf_droidx ) ; } else if ( this . deviceType . equals ( Configuration . DEVICE_BLADE ) ) { this . copyFile ( this . coretask . DATA_FILE_PATH + "" , "" , R . raw . hostapd_conf_blade ) ; } } Handler displayMessageHandler = new Handler ( ) { public void handleMessage ( Message msg ) { if ( msg . obj != null ) { TetherApplication . this . displayToastMessage ( ( String ) msg . obj ) ; } super . handleMessage ( msg ) ; } } ; public void installFiles ( ) { String message = null ; if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . tether ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . dnsmasq ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . iptables ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . iptables2 ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . ifconfig ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . iwconfig ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . ultra_bcm_config ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . pand ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . blue_up_sh ) ; } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . blue_down_sh ) ; } if ( Configuration . enableFixPersist ( ) ) { if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . fixpersist_sh ) ; } } if ( Configuration . enableFixRoute ( ) ) { if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . fixroute_sh ) ; } } if ( message == null ) { message = TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . dnsmasq_conf ) ; TetherApplication . this . coretask . updateDnsmasqFilepath ( ) ; } if ( message == null ) { TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . tiwlan_ini ) ; } if ( message == null ) { TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . tether_edify ) ; } if ( message == null ) { TetherApplication . this . copyFile ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" , R . raw . tether_conf ) ; } TetherApplication . this . coretask . chmod ( TetherApplication . this . coretask . DATA_FILE_PATH + "" , "" ) ; if ( message == null ) { message = getString ( R . string . global_application_installed ) ; } Message msg = new Message ( ) ; msg . obj = message ; TetherApplication . this . displayMessageHandler . sendMessage ( msg ) ; } public static Object getDeclaredField ( Class < ? > c , String name ) throws SecurityException , NoSuchFieldException , IllegalArgumentException , IllegalAccessException { Field f = c . getDeclaredField ( name ) ; f . setAccessible ( true ) ; return f . get ( c ) ; } public static Object getDeclaredField ( String className , String fieldName ) throws SecurityException , IllegalArgumentException , NoSuchFieldException , IllegalAccessException , ClassNotFoundException { return getDeclaredField ( Class . forName ( className ) , fieldName ) ; } public boolean isProviderSupported ( String checkProvider ) { List < String > providers ; try { LocationManager lm = ( LocationManager ) getSystemService ( Context . LOCATION_SERVICE ) ; providers = lm . getAllProviders ( ) ; } catch ( Throwable e ) { return false ; } for ( String provider : providers ) { if ( checkProvider . equals ( provider ) ) { return true ; } } return false ; } private boolean isPackageInstalled ( String packageName ) { PackageManager packageManager = getPackageManager ( ) ; boolean installed = false ; try { packageManager . getPackageInfo ( packageName , PackageManager . GET_ACTIVITIES ) ; installed = true ; } catch ( PackageManager . NameNotFoundException e ) { } return installed ; } public boolean isPhone ( ) { TelephonyManager tm = ( TelephonyManager ) getSystemService ( Context . TELEPHONY_SERVICE ) ; switch ( tm . getPhoneType ( ) ) { case TelephonyManager . PHONE_TYPE_NONE : return false ; case TelephonyManager . PHONE_TYPE_GSM : case TelephonyManager . PHONE_TYPE_CDMA : default : return true ; } } public void reportStats ( int status , boolean synchronous ) { final HashMap < String , Object > h = new HashMap < String , Object > ( ) ; String aid = null ; try { aid = Settings . Secure . getString ( getContentResolver ( ) , Settings . Secure . ANDROID_ID ) ; } catch ( NullPointerException e ) { Log . e ( "" , "" , e ) ; } if ( aid != null ) { h . put ( "" , aid ) ; } String uuid = "" ; for ( int i = ; i < ; i ++ ) { if ( aid != null ) { uuid += aid ; } try { uuid += getDeclaredField ( android . os . Build . class , "" ) ; } catch ( IllegalArgumentException e ) { } catch ( IllegalAccessException e ) { } catch ( NoSuchFieldError e ) { } catch ( SecurityException e ) { } catch ( NoSuchFieldException e ) { } } if ( uuid . length ( ) < ) { uuid = settings . getString ( "" , UUID . randomUUID ( ) . toString ( ) ) ; settings . edit ( ) . putString ( "" , uuid ) . commit ( ) ; } else { uuid = ( uuid . substring ( , ) + "" + uuid . substring ( , ) + "" + uuid . substring ( , ) + "" + uuid . substring ( , ) + "" + uuid . substring ( , ) ) ; } h . put ( "" , uuid . toUpperCase ( ) ) ; h . put ( "" , Build . VERSION . RELEASE ) ; try { h . put ( "" , getDeclaredField ( android . os . Build . VERSION . class , "" ) ) ; } catch ( IllegalArgumentException e ) { } catch ( IllegalAccessException e ) { } catch ( SecurityException e ) { } catch ( NoSuchFieldException e ) { } h . put ( "" , Build . MODEL ) ; try { h . put ( "" , getDeclaredField ( android . os . Build . class , "" ) ) ; } catch ( SecurityException e ) { } catch ( IllegalArgumentException e ) { } catch ( NoSuchFieldException e ) { } catch ( IllegalAccessException e ) { } TelephonyManager tm = ( TelephonyManager ) getSystemService ( Context . TELEPHONY_SERVICE ) ; h . put ( "" , tm . getNetworkOperatorName ( ) ) ; h . put ( "" , tm . getDeviceId ( ) ) ; LocationManager lm = ( LocationManager ) getSystemService ( Context . LOCATION_SERVICE ) ; if ( isProviderSupported ( LocationManager . PASSIVE_PROVIDER ) ) { Location l = lm . getLastKnownLocation ( LocationManager . PASSIVE_PROVIDER ) ; if ( l != null ) { h . put ( "" , String . format ( "" , l . getLatitude ( ) , l . getLongitude ( ) ) ) ; } } h . put ( "" , settings . getBoolean ( "" , false ) ) ; h . put ( "" , settings . getLong ( "" , - ) ) ; h . put ( "" , getVersionNumber ( ) ) ; h . put ( "" , coretask . hasRootPermission ( ) ) ; h . put ( "" , coretask . isNetfilterSupported ( ) ) ; h . put ( "" , coretask . isAccessControlSupported ( ) ) ; h . put ( "" , isTransmitPowerSupported ( ) ) ; h . put ( "" , Configuration . hasKernelFeature ( "" ) ) ; h . put ( "" , Configuration . hasKernelFeature ( "" ) ) ; h . put ( "" , deviceType ) ; h . put ( "" , interfaceDriver ) ; h . put ( "" , binariesExists ( ) ) ; h . put ( "" , status ) ; try { String tetherNetworkDevice = TetherApplication . this . getTetherNetworkDevice ( ) ; long [ ] trafficCount = TetherApplication . this . coretask . getDataTraffic ( tetherNetworkDevice ) ; h . put ( "" , trafficCount [ ] ) ; h . put ( "" , trafficCount [ ] ) ; } catch ( UnsatisfiedLinkError e ) { } h . put ( "" , isPackageInstalled ( "" ) ) ; try { h . put ( "" , getDeclaredField ( "" , "" ) ) ; } catch ( Exception e ) { h . put ( "" , false ) ; } try { h . put ( "" , Settings . Secure . getInt ( getContentResolver ( ) , Settings . Secure . INSTALL_NON_MARKET_APPS ) ) ; } catch ( SettingNotFoundException e ) { } h . put ( "" , lastTemperature ) ; h . put ( "" , isPhone ( ) ) ; h . put ( "" , settings . getBoolean ( "" , false ) ) ; h . put ( "" , settings . getInt ( "" , ) ) ; h . put ( "" , settings . getInt ( "" , ) ) ; h . put ( "" , settings . getInt ( "" , ) ) ; h . put ( "" , settings . getInt ( "" , ) ) ; h . put ( "" , settings . getInt ( "" , ) ) ; h . put ( "" , settings . getBoolean ( "" , false ) ) ; h . put ( "" , settings . getInt ( "" , ) ) ; h . put ( "" , settings . getInt ( "" , ) ) ; h . put ( "" , settings . getInt ( "" , ) ) ; h . put ( "" , settings . getString ( "" , SetupActivity . DEFAULT_DEVICE ) ) ; h . put ( "" , settings . getString ( "" , SetupActivity . DEFAULT_SETUP ) ) ; h . put ( "" , getPackageName ( ) ) ; if ( synchronous ) { Log . d ( MSG_TAG , "" + h . toString ( ) ) ; WebserviceTask . report ( APPLICATION_STATS_URL , h ) ; Log . d ( MSG_TAG , "" ) ; } else { new Thread ( new Runnable ( ) { public void run ( ) { Looper . prepare ( ) ; Log . d ( MSG_TAG , "" + h . toString ( ) ) ; WebserviceTask . report ( APPLICATION_STATS_URL , h ) ; Log . d ( MSG_TAG , "" ) ; Looper . loop ( ) ; } } ) . start ( ) ; } } public void statFBPostOk ( ) { this . preferenceEditor . putInt ( "" , this . settings . getInt ( "" , ) + ) . commit ( ) ; } public void statFBPostError ( ) { this . preferenceEditor . putInt ( "" , this . settings . getInt ( "" , ) + ) . commit ( ) ; } public void statConnectActivity ( ) { this . preferenceEditor . putInt ( "" , this . settings . getInt ( "" , ) + ) . commit ( ) ; } public void statFBConnectRequest ( ) { this . preferenceEditor . putInt ( "" , this . settings . getInt ( "" , ) + ) . commit ( ) ; } public void statFBConnectOk ( ) { this . preferenceEditor . putInt ( "" , this . settings . getInt ( "" , ) + ) . commit ( ) ; } public void statCommunityClicks ( ) { this . preferenceEditor . putInt ( "" , this . settings . getInt ( "" , ) + ) . commit ( ) ; } public void statRSSClicks ( ) { this . preferenceEditor . putInt ( "" , this . settings . getInt ( "" , ) + ) . commit ( ) ; } public void checkForUpdate ( ) { if ( this . isUpdatecDisabled ( ) ) { Log . d ( MSG_TAG , "" ) ; return ; } new Thread ( new Runnable ( ) { public void run ( ) { Looper . prepare ( ) ; Properties updateProperties = WebserviceTask . queryForProperty ( APPLICATION_PROPERTIES_URL ) ; if ( updateProperties != null && updateProperties . containsKey ( "" ) ) { int availableVersion = Integer . parseInt ( updateProperties . getProperty ( "" ) ) ; int installedVersion = TetherApplication . this . getVersionNumber ( ) ; String fileName = updateProperties . getProperty ( "" , "" ) ; String updateMessage = updateProperties . getProperty ( "" , "" ) ; String updateTitle = updateProperties . getProperty ( "" , "" ) ; if ( availableVersion != installedVersion ) { Log . d ( MSG_TAG , "" + installedVersion + "" + availableVersion + "" ) ; MainActivity . currentInstance . openUpdateDialog ( APPLICATION_DOWNLOAD_URL + fileName , fileName , updateMessage , updateTitle ) ; } } Looper . loop ( ) ; } } ) . start ( ) ; } public void downloadUpdate ( final String downloadFileUrl , final String fileName ) { new Thread ( new Runnable ( ) { public void run ( ) { Message msg = Message . obtain ( ) ; msg . what = MainActivity . MESSAGE_DOWNLOAD_STARTING ; msg . obj = "" ; MainActivity . currentInstance . viewUpdateHandler . sendMessage ( msg ) ; WebserviceTask . downloadUpdateFile ( downloadFileUrl , fileName ) ; Intent intent = new Intent ( Intent . ACTION_VIEW ) ; intent . setDataAndType ( android . net . Uri . fromFile ( new File ( WebserviceTask . DOWNLOAD_FILEPATH + "" + fileName ) ) , "" ) ; MainActivity . currentInstance . startActivity ( intent ) ; } } ) . start ( ) ; } private String copyFile ( String filename , String permission , int ressource ) { String result = this . copyFile ( filename , ressource ) ; if ( result != null ) { return result ; } if ( this . coretask . chmod ( filename , permission ) != true ) { result = "" + filename + "" ; } return result ; } private String copyFile ( String filename , int ressource ) { File outFile = new File ( filename ) ; Log . d ( MSG_TAG , "" + filename + "" ) ; InputStream is = this . getResources ( ) . openRawResource ( ressource ) ; byte buf [ ] = new byte [ ] ; int len ; try { OutputStream out = new FileOutputStream ( outFile ) ; while ( ( len = is . read ( buf ) ) > ) { out . write ( buf , , len ) ; } out . close ( ) ; is . close ( ) ; } catch ( IOException e ) { return "" + filename + "" ; } return null ; } private void checkDirs ( ) { File dir = new File ( this . coretask . DATA_FILE_PATH ) ; if ( dir . exists ( ) == false ) { this . displayToastMessage ( "" ) ; } else { String [ ] dirs = { "" , "" , "" } ; for ( String dirname : dirs ) { dir = new File ( this . coretask . DATA_FILE_PATH + dirname ) ; if ( dir . exists ( ) == false ) { if ( ! dir . mkdir ( ) ) { this . displayToastMessage ( "" + dirname + "" ) ; } } else { Log . d ( MSG_TAG , "" + dir . getAbsolutePath ( ) + "" ) ; } } } } public void displayToastMessage ( String message ) { Toast . makeText ( getApplicationContext ( ) , message , Toast . LENGTH_LONG ) . show ( ) ; } public int getVersionNumber ( ) { int version = - ; try { PackageInfo pi = getPackageManager ( ) . getPackageInfo ( getPackageName ( ) , ) ; version = pi . versionCode ; } catch ( Exception e ) { Log . e ( MSG_TAG , "" , e ) ; } return version ; } public String getVersionName ( ) { String version = "" ; try { PackageInfo pi = getPackageManager ( ) . getPackageInfo ( getPackageName ( ) , ) ; version = pi . versionName ; } catch ( Exception e ) { Log . e ( MSG_TAG , "" , e ) ; } return version ; } public boolean isTransmitPowerSupported ( ) { if ( Configuration . getWifiInterfaceDriver ( deviceType ) . equals ( Configuration . DRIVER_WEXT ) ) { return true ; } return false ; } public Bundle getParamsForPost ( ) { Bundle params = new Bundle ( ) ; String text = settings . getString ( "" , getString ( R . string . post_text ) ) ; text = text . replaceFirst ( "" , MainActivity . formatCountForPost ( TetherService . dataCount . totalDownload ) ) ; params . putString ( "" , text ) ; params . putString ( "" , "" ) ; params . putString ( "" , "" ) ; params . putString ( "" , "" ) ; params . putString ( "" , "" ) ; params . putString ( "" , settings . getString ( "" , "" ) ) ; return params ; } void requestStatsAlarm ( ) { ( ( AlarmManager ) getSystemService ( ALARM_SERVICE ) ) . setInexactRepeating ( AlarmManager . RTC_WAKEUP , System . currentTimeMillis ( ) + * , AlarmManager . INTERVAL_DAY , PendingIntent . getBroadcast ( this , , new Intent ( this , AlarmReceiver . class ) . setAction ( MESSAGE_REPORT_STATS ) , ) ) ; Log . d ( MSG_TAG , "" ) ; } void openLaunchedDialog ( ) { Intent launchDialog = new Intent ( Intent . ACTION_VIEW ) . setData ( Uri . parse ( "" + MESSAGE_LAUNCH_CHECK ) ) . addFlags ( Intent . FLAG_ACTIVITY_REORDER_TO_FRONT | Intent . FLAG_ACTIVITY_NEW_TASK ) ; startActivity ( launchDialog ) ; } String readLogfile ( ) { FileInputStream fis = null ; InputStreamReader isr = null ; String data = "" ; try { File file = new File ( this . coretask . DATA_FILE_PATH + "" ) ; fis = new FileInputStream ( file ) ; isr = new InputStreamReader ( fis , "" ) ; char [ ] buff = new char [ ( int ) file . length ( ) ] ; isr . read ( buff ) ; data = new String ( buff ) ; } catch ( Exception e ) { displayToastMessage ( getString ( R . string . log_activity_nologfile ) ) ; } finally { try { if ( isr != null ) isr . close ( ) ; if ( fis != null ) fis . close ( ) ; } catch ( Exception e ) { } } return data ; } boolean onlyEncryptionOrNothingFailed ( ) { Log . d ( MSG_TAG , "" ) ; String log = readLogfile ( ) ; if ( log == null ) return true ; log = log . toLowerCase ( ) ; int encryptionIndex = log . indexOf ( "" ) ; int nextFailedIndex = log . indexOf ( "" ) ; if ( ( encryptionIndex == - && nextFailedIndex != - ) || nextFailedIndex < encryptionIndex ) { return false ; } nextFailedIndex = log . indexOf ( "" , encryptionIndex ) ; int nextDoneIndex = log . indexOf ( "" , encryptionIndex ) ; if ( nextFailedIndex < nextDoneIndex || nextDoneIndex == - ) { return log . indexOf ( "" , nextFailedIndex + ) == - ; } return false ; } } package og . android . tether . data ; import java . util . Date ; public class ClientData { private boolean connected ; private boolean accessAllowed ; private String macAddress ; private String clientName ; private String ipAddress ; private Date connectTime ; public boolean isConnected ( ) { return connected ; } public void setConnected ( boolean connected ) { this . connected = connected ; } public boolean isAccessAllowed ( ) { return accessAllowed ; } public void setAccessAllowed ( boolean accessAllowed ) { this . accessAllowed = accessAllowed ; } public String getMacAddress ( ) { return macAddress ; } public void setMacAddress ( String macAddress ) { this . macAddress = macAddress ; } public String getClientName ( ) { return clientName ; } public void setClientName ( String clientName ) { this . clientName = clientName ; } public String getIpAddress ( ) { return ipAddress ; } public void setIpAddress ( String ipAddress ) { this . ipAddress = ipAddress ; } public Date getConnectTime ( ) { return connectTime ; } public void setConnectTime ( Date connectTime ) { this . connectTime = connectTime ; } } package og . android . tether . data ; import java . util . ArrayList ; import og . android . tether . R ; import og . android . tether . AccessControlActivity ; import og . android . tether . TetherApplication ; import android . graphics . Color ; import android . util . Log ; import android . view . LayoutInflater ; import android . view . View ; import android . view . ViewGroup ; import android . widget . BaseAdapter ; import android . widget . CheckBox ; import android . widget . CompoundButton ; import android . widget . TextView ; import android . widget . CompoundButton . OnCheckedChangeListener ; public class ClientAdapter extends BaseAdapter { public static final String MSG_TAG = "" ; private LayoutInflater inflater ; private ArrayList < ClientData > rows = new ArrayList < ClientData > ( ) ; public boolean saveRequired = false ; public boolean accessControlActive = false ; public TetherApplication application ; public AccessControlActivity accessControlActivity ; public ClientAdapter ( AccessControlActivity accessControlActivity , ArrayList < ClientData > rows , TetherApplication app ) { super ( ) ; this . accessControlActivity = accessControlActivity ; this . application = app ; this . accessControlActive = application . whitelist . exists ( ) ; this . rows = rows ; this . inflater = LayoutInflater . from ( accessControlActivity ) ; } public ArrayList < ClientData > getClientData ( ) { return this . rows ; } public synchronized void refreshData ( ArrayList < ClientData > rows ) { this . accessControlActive = application . whitelist . exists ( ) ; this . rows = rows ; this . notifyDataSetChanged ( ) ; } public synchronized void addClient ( ClientData clientData ) { Log . d ( MSG_TAG , "" + clientData . getClientName ( ) ) ; this . rows . add ( clientData ) ; this . notifyDataSetChanged ( ) ; } public synchronized void removeClient ( String mac ) { for ( int i = ; i < this . rows . size ( ) ; i ++ ) { ClientData tmpClientData = this . rows . get ( i ) ; if ( tmpClientData . getMacAddress ( ) . equals ( mac ) ) { this . rows . remove ( i ) ; break ; } } this . notifyDataSetChanged ( ) ; } public void toggleChecked ( int position , boolean isChecked ) { ClientData tmpClientData = this . rows . get ( position ) ; if ( tmpClientData . isAccessAllowed ( ) != isChecked ) { tmpClientData . setAccessAllowed ( isChecked ) ; Log . d ( MSG_TAG , "" + tmpClientData . getClientName ( ) + "" + tmpClientData . isAccessAllowed ( ) ) ; this . rows . set ( position , tmpClientData ) ; this . saveRequired = true ; this . accessControlActivity . toggleACFooter ( ) ; } } public View getView ( final int position , View returnView , ViewGroup parent ) { Log . d ( MSG_TAG , "" + position ) ; ClientData row = this . rows . get ( position ) ; returnView = inflater . inflate ( R . layout . clientrow , null ) ; TextView macaddress = ( TextView ) returnView . findViewById ( R . id . macaddress ) ; TextView clientname = ( TextView ) returnView . findViewById ( R . id . clientname ) ; TextView ipaddress = ( TextView ) returnView . findViewById ( R . id . ipaddress ) ; CheckBox checkBoxAllowed = ( CheckBox ) returnView . findViewById ( R . id . checkBoxAllowed ) ; if ( this . accessControlActive == false ) { checkBoxAllowed . setVisibility ( View . GONE ) ; } else { checkBoxAllowed . setOnCheckedChangeListener ( new OnCheckedChangeListener ( ) { public void onCheckedChanged ( CompoundButton compoundButton , boolean isChecked ) { toggleChecked ( position , isChecked ) ; } } ) ; } macaddress . setText ( row . getMacAddress ( ) ) ; if ( row . isConnected ( ) ) { macaddress . setTextColor ( Color . rgb ( , , ) ) ; clientname . setTextColor ( Color . rgb ( , , ) ) ; ipaddress . setTextColor ( Color . rgb ( , , ) ) ; if ( row . getIpAddress ( ) != null ) { ipaddress . setText ( row . getIpAddress ( ) ) ; } if ( row . getClientName ( ) != null ) { clientname . setText ( row . getClientName ( ) ) ; } } else { clientname . setText ( "" ) ; ipaddress . setText ( "" ) ; macaddress . setTextColor ( Color . rgb ( , , ) ) ; clientname . setTextColor ( Color . rgb ( , , ) ) ; ipaddress . setTextColor ( Color . rgb ( , , ) ) ; } if ( row . isAccessAllowed ( ) ) { checkBoxAllowed . setChecked ( true ) ; } return returnView ; } public int getCount ( ) { return rows . size ( ) ; } public Object getItem ( int position ) { return rows . get ( position ) ; } public long getItemId ( int position ) { return position ; } } package og . android . tether ; import com . google . analytics . tracking . android . TrackedActivity ; import android . R . drawable ; import android . app . Activity ; import android . content . Context ; import android . content . SharedPreferences ; import android . os . Bundle ; import android . preference . PreferenceManager ; import android . util . Log ; import android . view . View ; import android . view . View . OnClickListener ; import android . view . View . OnFocusChangeListener ; import android . view . ViewGroup ; import android . view . inputmethod . InputMethodManager ; import android . widget . Button ; import android . widget . CheckBox ; import android . widget . EditText ; import og . android . tether . OnPostCompleteListener ; public class PostActivity extends TrackedActivity { private static final String TAG = "" ; private SharedPreferences mPrefs ; private SharedPreferences . Editor mPrefsEdit ; private InputMethodManager mInputManager ; private EditText mPostEditor ; private Button mPostButton ; private CheckBox mCheckFacebook ; private Bundle mParams = null ; @ Override public void onCreate ( Bundle savedInstanceState ) { Log . d ( TAG , "" ) ; super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . postview ) ; mInputManager = ( InputMethodManager ) getSystemService ( Context . INPUT_METHOD_SERVICE ) ; mPrefs = PreferenceManager . getDefaultSharedPreferences ( this ) ; mPrefsEdit = mPrefs . edit ( ) ; mCheckFacebook = ( CheckBox ) findViewById ( R . id . facebookCheck ) ; mCheckFacebook . setChecked ( mPrefs . getBoolean ( "" , false ) ) ; mPostButton = ( Button ) findViewById ( R . id . postButton ) ; mPostButton . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View view ) { Log . d ( TAG , "" + view ) ; mInputManager . toggleSoftInput ( , ) ; if ( mCheckFacebook . isChecked ( ) ) { mPrefsEdit . putBoolean ( "" , true ) . commit ( ) ; mParams . putString ( "" , mPostEditor . getText ( ) . toString ( ) ) ; postToFacebook ( mParams ) ; } else { mPrefsEdit . putBoolean ( "" , false ) . commit ( ) ; finish ( ) ; } } } ) ; mPostEditor = ( EditText ) findViewById ( R . id . postEditor ) ; Log . d ( TAG , "" + getIntent ( ) ) ; if ( getIntent ( ) . getData ( ) . getPath ( ) . equals ( "" ) ) { mParams = ( ( TetherApplication ) getApplication ( ) ) . getParamsForPost ( ) ; mPostEditor . setText ( mParams . getString ( "" ) ) ; ViewGroup . LayoutParams layoutParams = mPostEditor . getLayoutParams ( ) ; layoutParams . height = ViewGroup . LayoutParams . WRAP_CONTENT ; mPostEditor . setLayoutParams ( layoutParams ) ; mPostEditor . setOnFocusChangeListener ( new OnFocusChangeListener ( ) { public void onFocusChange ( View v , boolean hasFocus ) { Log . d ( TAG , "" + v + "" + hasFocus ) ; if ( hasFocus ) { } } } ) ; mPostEditor . requestFocus ( ) ; if ( getIntent ( ) . getBooleanExtra ( "" , false ) ) { postToFacebookWithAuthorize ( mParams ) ; return ; } if ( mPrefs . getBoolean ( "" , true ) ) { postToFacebook ( mParams ) ; return ; } } } void postToFacebook ( Bundle params ) { ( ( TetherApplication ) getApplication ( ) ) . FBManager . postToFacebook ( params , new OnPostCompleteListener ( ) { @ Override void onPostComplete ( String result ) { Log . d ( TAG , "" ) ; PostActivity . this . finish ( ) ; } } ) ; } void postToFacebookWithAuthorize ( Bundle params ) { ( ( TetherApplication ) getApplication ( ) ) . FBManager . postToFacebookWithAuthorize ( PostActivity . this , params , new OnPostCompleteListener ( ) { @ Override void onPostComplete ( String result ) { Log . d ( TAG , "" ) ; PostActivity . this . finish ( ) ; } } ) ; } @ Override public void onResume ( ) { Log . d ( TAG , "" ) ; mInputManager . toggleSoftInput ( InputMethodManager . SHOW_FORCED , ) ; super . onResume ( ) ; } @ Override public void onPause ( ) { Log . d ( TAG , "" ) ; mInputManager . toggleSoftInput ( , ) ; if ( ( ( TetherApplication ) getApplication ( ) ) . FBManager != null ) ( ( TetherApplication ) getApplication ( ) ) . FBManager . destroyDialog ( ) ; super . onPause ( ) ; } } package og . android . tether . system ; import android . app . Application ; import android . bluetooth . BluetoothAdapter ; public class BluetoothService_eclair extends BluetoothService { BluetoothAdapter btAdapter = null ; public BluetoothService_eclair ( ) { super ( ) ; btAdapter = BluetoothAdapter . getDefaultAdapter ( ) ; } @ Override public boolean startBluetooth ( ) { boolean connected = false ; this . btAdapter . enable ( ) ; int checkcounter = ; while ( connected == false && checkcounter <= ) { connected = this . btAdapter . isEnabled ( ) ; if ( connected == false ) { checkcounter ++ ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } else { break ; } } return connected ; } @ Override public boolean stopBluetooth ( ) { return this . btAdapter . disable ( ) ; } @ Override public boolean isBluetoothEnabled ( ) { return this . btAdapter . isEnabled ( ) ; } @ Override public void setApplication ( Application application ) { } } package og . android . tether . system ; import android . util . Log ; public class NativeTask { public static final String MSG_TAG = "" ; static { try { Log . i ( MSG_TAG , "" ) ; System . loadLibrary ( "" ) ; } catch ( UnsatisfiedLinkError ule ) { Log . e ( MSG_TAG , "" ) ; } } public static native String getProp ( String name ) ; public static native int runCommand ( String command ) ; } package og . android . tether . system ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map . Entry ; import java . util . Properties ; import java . util . Set ; import java . util . zip . GZIPInputStream ; import og . android . tether . MainActivity ; import org . apache . http . HttpEntity ; import org . apache . http . HttpResponse ; import org . apache . http . StatusLine ; import org . apache . http . client . ClientProtocolException ; import org . apache . http . client . HttpClient ; import org . apache . http . client . methods . HttpGet ; import org . apache . http . client . utils . URLEncodedUtils ; import org . apache . http . impl . client . DefaultHttpClient ; import org . apache . http . message . BasicNameValuePair ; import android . os . Message ; import android . util . Log ; public class WebserviceTask { public static final String MSG_TAG = "" ; public static final String DOWNLOAD_FILEPATH = "" ; public static final String BLUETOOTH_FILEPATH = "" ; public static HttpResponse makeRequest ( String url , List < BasicNameValuePair > params ) throws ClientProtocolException , IOException { HttpClient client = new DefaultHttpClient ( ) ; String paramString = URLEncodedUtils . format ( params , "" ) ; Log . d ( MSG_TAG , url + "" + paramString ) ; HttpGet request = new HttpGet ( url + "" + paramString ) ; return client . execute ( request ) ; } public static void report ( String url , HashMap < String , Object > paramMap ) { List < BasicNameValuePair > params = new ArrayList < BasicNameValuePair > ( ) ; Set < Entry < String , Object > > a = paramMap . entrySet ( ) ; for ( Entry < String , Object > e : a ) { Object o = e . getValue ( ) ; if ( o != null ) { params . add ( new BasicNameValuePair ( e . getKey ( ) , o . toString ( ) ) ) ; } } try { HttpResponse response = makeRequest ( url , params ) ; StatusLine status = response . getStatusLine ( ) ; Log . d ( MSG_TAG , "" + status ) ; if ( status . getStatusCode ( ) == ) { HttpEntity entity = response . getEntity ( ) ; Log . d ( MSG_TAG , "" + entity . getContent ( ) ) ; } } catch ( Exception e ) { Log . d ( MSG_TAG , "" + url + "" + e . toString ( ) + "" ) ; } } public static Properties queryForProperty ( String url ) { Properties properties = null ; HttpClient client = new DefaultHttpClient ( ) ; HttpGet request = new HttpGet ( String . format ( url ) ) ; try { HttpResponse response = client . execute ( request ) ; StatusLine status = response . getStatusLine ( ) ; Log . d ( MSG_TAG , "" + status ) ; if ( status . getStatusCode ( ) == ) { HttpEntity entity = response . getEntity ( ) ; properties = new Properties ( ) ; properties . load ( entity . getContent ( ) ) ; } } catch ( IOException e ) { Log . d ( MSG_TAG , "" + url + "" ) ; } return properties ; } public static boolean downloadUpdateFile ( String downloadFileUrl , String destinationFilename ) { if ( android . os . Environment . getExternalStorageState ( ) . equals ( android . os . Environment . MEDIA_MOUNTED ) == false ) { return false ; } File downloadDir = new File ( DOWNLOAD_FILEPATH ) ; if ( downloadDir . exists ( ) == false ) { downloadDir . mkdirs ( ) ; } else { File downloadFile = new File ( DOWNLOAD_FILEPATH + "" + destinationFilename ) ; if ( downloadFile . exists ( ) ) { downloadFile . delete ( ) ; } } return downloadFile ( downloadFileUrl , DOWNLOAD_FILEPATH , destinationFilename ) ; } public static boolean downloadBluetoothModule ( String downloadFileUrl , String destinationFilename ) { if ( android . os . Environment . getExternalStorageState ( ) . equals ( android . os . Environment . MEDIA_MOUNTED ) == false ) { return false ; } File bluetoothDir = new File ( BLUETOOTH_FILEPATH ) ; if ( bluetoothDir . exists ( ) == false ) { bluetoothDir . mkdirs ( ) ; } if ( downloadFile ( downloadFileUrl , "" , destinationFilename ) == true ) { try { FileOutputStream out = new FileOutputStream ( new File ( destinationFilename . replace ( "" , "" ) ) ) ; FileInputStream fis = new FileInputStream ( destinationFilename ) ; GZIPInputStream gzin = new GZIPInputStream ( new BufferedInputStream ( fis ) ) ; int count ; byte buf [ ] = new byte [ ] ; while ( ( count = gzin . read ( buf , , ) ) != - ) { out . write ( buf , , count ) ; } out . flush ( ) ; out . close ( ) ; gzin . close ( ) ; File inputFile = new File ( destinationFilename ) ; inputFile . delete ( ) ; } catch ( IOException e ) { return false ; } return true ; } else return false ; } public static boolean downloadFile ( String url , String destinationDirectory , String destinationFilename ) { boolean filedownloaded = true ; HttpClient client = new DefaultHttpClient ( ) ; HttpGet request = new HttpGet ( String . format ( url ) ) ; Message msg = Message . obtain ( ) ; try { HttpResponse response = client . execute ( request ) ; StatusLine status = response . getStatusLine ( ) ; Log . d ( MSG_TAG , "" + status ) ; if ( status . getStatusCode ( ) == ) { HttpEntity entity = response . getEntity ( ) ; InputStream instream = entity . getContent ( ) ; int fileSize = ( int ) entity . getContentLength ( ) ; FileOutputStream out = new FileOutputStream ( new File ( destinationDirectory + "" + destinationFilename ) ) ; byte buf [ ] = new byte [ ] ; int len ; int totalRead = ; while ( ( len = instream . read ( buf ) ) > ) { msg = Message . obtain ( ) ; msg . what = MainActivity . MESSAGE_DOWNLOAD_PROGRESS ; totalRead += len ; msg . arg1 = totalRead / ; msg . arg2 = fileSize / ; MainActivity . currentInstance . viewUpdateHandler . sendMessage ( msg ) ; out . write ( buf , , len ) ; } out . close ( ) ; } else { throw new IOException ( ) ; } } catch ( IOException e ) { Log . d ( MSG_TAG , "" + url + "" + destinationDirectory + "" + destinationFilename + "" ) ; filedownloaded = false ; } msg = Message . obtain ( ) ; msg . what = MainActivity . MESSAGE_DOWNLOAD_COMPLETE ; MainActivity . currentInstance . viewUpdateHandler . sendMessage ( msg ) ; return filedownloaded ; } } package og . android . tether . system ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . util . zip . GZIPInputStream ; import android . os . Build ; public class Configuration { public static final String DEVICE_NEXUSONE = "" ; public static final String DEVICE_GALAXY1X = "" ; public static final String DEVICE_GALAXY2X = "" ; public static final String DEVICE_LEGEND = "" ; public static final String DEVICE_DREAM = "" ; public static final String DEVICE_MOMENT = "" ; public static final String DEVICE_ALLY = "" ; public static final String DEVICE_DROIDX = "" ; public static final String DEVICE_BLADE = "" ; public static final String DEVICE_GENERIC = "" ; public static final String DRIVER_TIWLAN0 = "" ; public static final String DRIVER_WEXT = "" ; public static final String DRIVER_SOFTAP_HTC1 = "" ; public static final String DRIVER_SOFTAP_HTC2 = "" ; public static final String DRIVER_SOFTAP_GOG = "" ; public static final String DRIVER_HOSTAP = "" ; public static String getDeviceType ( ) { if ( ( new File ( "" ) ) . exists ( ) == true ) { return DEVICE_NEXUSONE ; } else if ( ( new File ( "" ) ) . exists ( ) == true ) { int sdkVersion = Integer . parseInt ( Build . VERSION . SDK ) ; if ( sdkVersion >= Build . VERSION_CODES . DONUT ) { return DEVICE_GALAXY2X ; } return DEVICE_GALAXY1X ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { return DEVICE_DROIDX ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { return DEVICE_LEGEND ; } else if ( ( new File ( "" ) ) . exists ( ) == true ) { return DEVICE_DREAM ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { return DEVICE_MOMENT ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { return DEVICE_ALLY ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { return DEVICE_BLADE ; } return DEVICE_GENERIC ; } public static String getWifiInterfaceDriver ( String deviceType ) { if ( deviceType . equals ( DEVICE_DREAM ) ) { return DRIVER_TIWLAN0 ; } else if ( deviceType . equals ( DEVICE_NEXUSONE ) && hasKernelFeature ( "" ) ) { if ( Integer . parseInt ( Build . VERSION . SDK ) >= Build . VERSION_CODES . FROYO ) { return DRIVER_SOFTAP_HTC2 ; } return DRIVER_SOFTAP_HTC1 ; } else if ( deviceType . equals ( DEVICE_NEXUSONE ) && ( new File ( "" ) ) . exists ( ) ) { return DRIVER_SOFTAP_GOG ; } else if ( deviceType . equals ( DEVICE_DROIDX ) || deviceType . equals ( DEVICE_BLADE ) ) { return DRIVER_HOSTAP ; } return DRIVER_WEXT ; } public static String getEncryptionAutoMethod ( String deviceType ) { if ( deviceType . equals ( DEVICE_LEGEND ) || deviceType . equals ( DEVICE_NEXUSONE ) ) { return "" ; } return "" ; } public static boolean enableFixPersist ( ) { if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && getWifiInterfaceDriver ( getDeviceType ( ) ) . equals ( DRIVER_WEXT ) == true ) { return true ; } if ( getDeviceType ( ) . equals ( DEVICE_LEGEND ) == true ) { return true ; } return false ; } public static boolean enableFixRoute ( ) { if ( ( new File ( "" ) ) . exists ( ) == true && NativeTask . getProp ( "" ) . equalsIgnoreCase ( "" ) ) { return true ; } return false ; } public static boolean hasKernelFeature ( String feature ) { try { File cfg = new File ( "" ) ; if ( cfg . exists ( ) == false ) { return true ; } FileInputStream fis = new FileInputStream ( cfg ) ; GZIPInputStream gzin = new GZIPInputStream ( fis ) ; BufferedReader in = null ; String line = "" ; in = new BufferedReader ( new InputStreamReader ( gzin ) ) ; while ( ( line = in . readLine ( ) ) != null ) { if ( line . startsWith ( feature ) ) { gzin . close ( ) ; return true ; } } gzin . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return false ; } } package og . android . tether . system ; import java . lang . reflect . Method ; import android . app . Application ; public class BluetoothService_cupcake extends BluetoothService { Application application = null ; @ SuppressWarnings ( "" ) private Object callBluetoothMethod ( String methodName ) { Object manager = this . application . getSystemService ( "" ) ; Class c = manager . getClass ( ) ; Object returnValue = null ; if ( c == null ) { } else { try { Method enable = c . getMethod ( methodName ) ; enable . setAccessible ( true ) ; returnValue = enable . invoke ( manager ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return returnValue ; } @ Override public boolean isBluetoothEnabled ( ) { return ( Boolean ) callBluetoothMethod ( "" ) ; } @ Override public boolean startBluetooth ( ) { boolean connected = false ; callBluetoothMethod ( "" ) ; int checkcounter = ; while ( connected == false && checkcounter <= ) { connected = ( Boolean ) callBluetoothMethod ( "" ) ; if ( connected == false ) { checkcounter ++ ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } else { break ; } } return connected ; } @ Override public boolean stopBluetooth ( ) { callBluetoothMethod ( "" ) ; return true ; } @ Override public void setApplication ( Application application ) { this . application = application ; } } package og . android . tether . system ; import android . app . Application ; import android . os . Build ; public abstract class BluetoothService { public abstract boolean startBluetooth ( ) ; public abstract boolean stopBluetooth ( ) ; public abstract boolean isBluetoothEnabled ( ) ; public abstract void setApplication ( Application application ) ; private static BluetoothService bluetoothService ; public static BluetoothService getInstance ( ) { if ( bluetoothService == null ) { String className ; int sdkVersion = Integer . parseInt ( Build . VERSION . SDK ) ; if ( sdkVersion < Build . VERSION_CODES . ECLAIR ) { className = "" ; } else { className = "" ; } try { Class < ? extends BluetoothService > clazz = Class . forName ( className ) . asSubclass ( BluetoothService . class ) ; bluetoothService = clazz . newInstance ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } } return bluetoothService ; } } package og . android . tether . system ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . util . zip . GZIPInputStream ; import android . util . Log ; public class ConfigurationAdv { public static final String MSG_TAG = "" ; public static final int SDK_EC = ; public static final int SDK_FR = ; public static final int SDK_GB = ; public static final int SDK_ICS = ; public static final String DEVICE_GENERIC = "" ; public static final String DEVICE_GENERIC_ICS = "" ; public static final String DEVICE_BLADE = "" ; public static final String DEVICE_PASSION = "" ; public static final String DEVICE_SPHD700 = "" ; public static final String DEVICE_SCHI500 = "" ; public static final String DEVICE_SCHI510 = "" ; public static final String DEVICE_SGHI897 = "" ; public static final String DEVICE_SCHR910 = "" ; public static final String DEVICE_MAGURO = "" ; public static final String DEVICE_TORO = "" ; public static final String DEVICE_GTI9000 = "" ; public static final String DEVICE_GTI9100 = "" ; public static final String DEVICE_SPHD710 = "" ; public static final String DEVICE_SUPERSONIC = "" ; public static final String DEVICE_PYRAMID = "" ; public static final String DEVICE_VIGOR = "" ; public static final String DEVICE_THUNDERC = "" ; public static final String DEVICE_BRAVO = "" ; public static final String DEVICE_BRAVOC = "" ; public static final String DEVICE_MECHA = "" ; public static final String DEVICE_SAPPHIRE = "" ; public static final String DEVICE_DREAM = "" ; public static final String DEVICE_HERO = "" ; public static final String DEVICE_HEROC = "" ; public static final String DEVICE_DROID2WE = "" ; public static final String DEVICE_UMTSJORDAN = "" ; public static final String DEVICE_CDMASHOLES = "" ; public static final String DEVICE_UMTSSHOLES = "" ; public static final String DEVICE_CDMASHADOW = "" ; public static final String DEVICE_UMTSSHADOW = "" ; public static final String DEVICE_CDMADROID2 = "" ; public static final String DEVICE_UMTSDROID2 = "" ; public static final String DEVICE_CDMAVENUS2 = "" ; public static final String DEVICE_UMTSVENUS2 = "" ; public static final String DEVICE_EDISON = "" ; public static final String DEVICE_CDMATARGA = "" ; public static final String DEVICE_CDMASOLANA = "" ; public static final String DEVICE_UMTSSOLANA = "" ; public static final String DEVICE_CDMASPYDER = "" ; public static final String DEVICE_UMTSSPYDER = "" ; public static final String DEVICE_LS855 = "" ; public static final String DEVICE_LU3000 = "" ; public static final String DEVICE_P970 = "" ; public static final String DEVICE_P970G = "" ; public static final String DEVICE_P920 = "" ; public static final String DEVICE_P925 = "" ; public static final String DEVICE_P925G = "" ; public static final String DEVICE_GALAXYSL = "" ; public static final String DEVICE_RUBY = "" ; private String device = DEVICE_GENERIC ; private int sdk = ; private boolean wextSupported = false ; private boolean hostapdSupported = false ; private boolean softapSupported = false ; private boolean softapSamsungSupported = false ; private boolean netdSupported = false ; private boolean tiadhocSupported = false ; private boolean autoInternalNetSetup = false ; private String wextInterface = "" ; private String hostapdPath = "" ; private String hostapdKernelModulePath = "" ; private String hostapdKernelModuleName = "" ; private String hostapdInterface = "" ; private String hostapdTemplate = "" ; private String hostapdLoaderCmd = "" ; private String netdInterface = "" ; private String softapInterface = "" ; private String softapFirmwarePath = "" ; private String tiadhocInterface = "" ; private String encryptionIdentifier = "" ; private String opennetworkIdentifier = "" ; private String autoSetupMethod = "" ; private boolean genericSetupSection = true ; private String wifiLoadCmd = "" ; private String wifiUnloadCmd = "" ; public ConfigurationAdv ( ) { this . device = android . os . Build . DEVICE ; this . sdk = android . os . Build . VERSION . SDK_INT ; Log . d ( MSG_TAG , "" + this . device + "" + this . sdk ) ; this . setupDevice ( ) ; } public ConfigurationAdv ( String device ) { this . device = device ; this . sdk = android . os . Build . VERSION . SDK_INT ; Log . d ( MSG_TAG , "" + this . device + "" + this . sdk ) ; this . setupDevice ( ) ; } private void setupDevice ( ) { if ( device . equals ( DEVICE_BLADE ) ) { this . setupBlade ( ) ; } else if ( device . equals ( DEVICE_PASSION ) ) { this . setupSoftapGoogle ( ) ; } else if ( device . equals ( DEVICE_GTI9000 ) ) { this . setupGTI9000 ( ) ; } else if ( device . equals ( DEVICE_GTI9100 ) || device . equals ( DEVICE_SPHD710 ) ) { if ( android . os . Build . VERSION . SDK_INT >= ) this . setupNetdGalaxyNexus ( ) ; else this . setupGTI9100 ( ) ; } else if ( device . equals ( DEVICE_MAGURO ) || device . equals ( DEVICE_TORO ) ) { this . setupNetdGalaxyNexus ( ) ; } else if ( device . equals ( DEVICE_THUNDERC ) ) { this . setupThunderc ( ) ; } else if ( device . equals ( DEVICE_BRAVOC ) || device . equals ( DEVICE_BRAVO ) || device . equals ( DEVICE_SUPERSONIC ) || device . equals ( DEVICE_PYRAMID ) || device . equals ( DEVICE_MECHA ) ) { this . setupSoftapHTC ( ) ; } else if ( device . equals ( DEVICE_DREAM ) || device . equals ( DEVICE_SAPPHIRE ) || device . equals ( DEVICE_HERO ) || device . equals ( DEVICE_HEROC ) ) { this . setupTiAdhoc ( ) ; } else if ( device . equals ( DEVICE_SGHI897 ) || device . equals ( DEVICE_SCHI500 ) || device . equals ( DEVICE_SCHI510 ) || device . equals ( DEVICE_SCHR910 ) ) { this . setupSoftapSamsung ( ) ; } else if ( device . equals ( DEVICE_LS855 ) || device . equals ( DEVICE_LU3000 ) || device . equals ( DEVICE_P970 ) || device . equals ( DEVICE_P970G ) || device . equals ( DEVICE_GALAXYSL ) ) { this . setupHostapLGomap3 ( ) ; } else if ( device . equals ( DEVICE_P920 ) || device . equals ( DEVICE_P925 ) || device . equals ( DEVICE_P925G ) ) { this . setupHostapLGomap4 ( ) ; } else if ( device . equals ( DEVICE_DROID2WE ) || device . equals ( DEVICE_UMTSSHOLES ) || device . equals ( DEVICE_UMTSJORDAN ) || device . equals ( DEVICE_CDMASHADOW ) || device . equals ( DEVICE_UMTSSHADOW ) || device . equals ( DEVICE_CDMADROID2 ) || device . equals ( DEVICE_UMTSDROID2 ) || device . equals ( DEVICE_CDMAVENUS2 ) || device . equals ( DEVICE_UMTSVENUS2 ) ) { this . setupHostapMotOMAP3 ( ) ; } else if ( device . equals ( DEVICE_EDISON ) || device . equals ( DEVICE_CDMATARGA ) || device . equals ( DEVICE_CDMASOLANA ) || device . equals ( DEVICE_UMTSSOLANA ) || device . equals ( DEVICE_CDMASPYDER ) || device . equals ( DEVICE_UMTSSPYDER ) ) { this . setupHostapMotOMAP4 ( ) ; } else if ( device . equals ( DEVICE_RUBY ) ) { this . setupHostapGenWiLink7 ( ) ; } else if ( device . equals ( DEVICE_GENERIC_ICS ) ) { this . setupNetdGalaxyNexus ( ) ; } else if ( device . equals ( DEVICE_VIGOR ) ) { this . setupNetdHTCRezound ( ) ; } else { if ( ( new File ( "" ) . exists ( ) || new File ( "" ) . exists ( ) ) && new File ( "" ) . exists ( ) ) { this . setupSoftapHTC ( ) ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . setupHostapMotOMAP3 ( ) ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . setupHostapMotOMAP4 ( ) ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . setupHostapLGomap3 ( ) ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . setupHostapLGomap4 ( ) ; } else if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . setupHostapGenWiLink7 ( ) ; } else { this . setupGeneric ( ) ; } } } private void setupTiAdhoc ( ) { this . wextSupported = false ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = false ; this . tiadhocSupported = true ; this . tiadhocInterface = "" ; this . genericSetupSection = true ; this . autoSetupMethod = "" ; } private void setupBlade ( ) { this . wextSupported = true ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = true ; this . tiadhocSupported = false ; this . wextInterface = "" ; if ( ( new File ( "" ) ) . exists ( ) == true ) { this . hostapdSupported = true ; this . hostapdPath = "" ; this . hostapdInterface = "" ; this . hostapdTemplate = "" ; this . autoSetupMethod = "" ; this . hostapdLoaderCmd = "" ; } else { this . hostapdSupported = false ; this . autoSetupMethod = "" ; } this . netdInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . hostapdKernelModulePath = "" ; this . hostapdKernelModuleName = "" ; this . genericSetupSection = true ; } private void setupSoftapGoogle ( ) { this . wextSupported = true ; this . softapSupported = true ; this . softapSamsungSupported = false ; this . netdSupported = true ; this . hostapdSupported = false ; this . tiadhocSupported = false ; this . autoInternalNetSetup = true ; this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; } else if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; } this . autoSetupMethod = "" ; this . genericSetupSection = true ; } private void setupNetdHTCRezound ( ) { this . wextSupported = true ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = true ; this . hostapdSupported = false ; this . tiadhocSupported = false ; this . autoInternalNetSetup = true ; if ( sdk >= SDK_ICS ) { this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . softapFirmwarePath = "" ; } } else { this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . softapFirmwarePath = "" ; } } this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . autoSetupMethod = "" ; this . genericSetupSection = true ; } private void setupSoftapHTC ( ) { this . wextSupported = true ; this . softapSupported = true ; this . softapSamsungSupported = false ; this . netdSupported = false ; this . hostapdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; } else if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; } this . autoSetupMethod = "" ; this . genericSetupSection = true ; } private void setupHostapGenWiLink7 ( ) { this . wextSupported = false ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . hostapdSupported = true ; this . hostapdPath = "" ; this . hostapdInterface = "" ; this . hostapdTemplate = "" ; this . autoSetupMethod = "" ; this . hostapdLoaderCmd = "" ; } this . netdInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . hostapdKernelModulePath = "" ; this . hostapdKernelModuleName = "" ; this . genericSetupSection = true ; } private void setupHostapMotOMAP3 ( ) { this . wextSupported = true ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . hostapdSupported = true ; this . hostapdPath = "" ; this . hostapdInterface = "" ; this . hostapdTemplate = "" ; this . autoSetupMethod = "" ; this . hostapdLoaderCmd = "" ; } else { this . hostapdSupported = false ; this . autoSetupMethod = "" ; } this . netdInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . hostapdKernelModulePath = "" ; this . hostapdKernelModuleName = "" ; this . genericSetupSection = true ; } private void setupHostapMotOMAP4 ( ) { this . wextSupported = false ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . hostapdSupported = true ; this . hostapdPath = "" ; this . hostapdInterface = "" ; this . hostapdTemplate = "" ; this . autoSetupMethod = "" ; this . hostapdLoaderCmd = "" ; } else { this . hostapdSupported = false ; this . autoSetupMethod = "" ; } this . netdInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . hostapdKernelModulePath = "" ; this . hostapdKernelModuleName = "" ; this . genericSetupSection = true ; } private void setupSoftapSamsung ( ) { this . wextSupported = true ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = false ; this . hostapdSupported = false ; this . tiadhocSupported = false ; this . autoSetupMethod = "" ; this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; this . autoSetupMethod = "" ; this . softapSamsungSupported = true ; this . netdSupported = false ; this . encryptionIdentifier = "" ; } this . genericSetupSection = true ; } private void setupNetdGalaxyNexus ( ) { this . wextSupported = true ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = true ; this . hostapdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . softapFirmwarePath = "" ; this . autoSetupMethod = "" ; this . genericSetupSection = true ; } private void setupGTI9000 ( ) { this . wextSupported = true ; this . softapSupported = true ; this . softapSamsungSupported = false ; this . netdSupported = true ; this . hostapdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . softapFirmwarePath = "" ; this . wifiLoadCmd = "" ; this . wifiUnloadCmd = "" ; this . autoSetupMethod = "" ; this . genericSetupSection = true ; } private void setupGTI9100 ( ) { this . wextSupported = true ; this . softapSupported = true ; this . softapSamsungSupported = false ; this . netdSupported = true ; this . hostapdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; } else if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; } else if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; } this . wifiLoadCmd = "" ; this . wifiUnloadCmd = "" ; this . autoSetupMethod = "" ; this . genericSetupSection = true ; } private void setupThunderc ( ) { this . wextSupported = true ; this . softapSupported = true ; this . softapSamsungSupported = false ; this . netdSupported = true ; this . hostapdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; this . netdInterface = "" ; this . softapInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; if ( new File ( "" ) . exists ( ) ) { this . softapFirmwarePath = "" ; this . autoSetupMethod = "" ; this . softapSupported = true ; this . netdSupported = true ; } else { this . autoSetupMethod = "" ; this . softapSupported = false ; this . netdSupported = false ; } this . genericSetupSection = true ; } private void setupHostapLGomap3 ( ) { this . wextSupported = false ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . hostapdSupported = true ; this . hostapdPath = "" ; this . hostapdInterface = "" ; this . hostapdTemplate = "" ; this . autoSetupMethod = "" ; this . hostapdLoaderCmd = "" ; } else { this . hostapdSupported = false ; this . autoSetupMethod = "" ; } this . netdInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . hostapdKernelModulePath = "" ; this . hostapdKernelModuleName = "" ; this . genericSetupSection = true ; } private void setupHostapLGomap4 ( ) { this . wextSupported = false ; this . softapSupported = false ; this . softapSamsungSupported = false ; this . netdSupported = false ; this . tiadhocSupported = false ; this . wextInterface = "" ; if ( ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true && ( new File ( "" ) ) . exists ( ) == true ) { this . hostapdSupported = true ; this . hostapdPath = "" ; this . hostapdInterface = "" ; this . hostapdTemplate = "" ; this . autoSetupMethod = "" ; this . hostapdLoaderCmd = "" ; } else { this . hostapdSupported = false ; this . autoSetupMethod = "" ; } this . netdInterface = "" ; this . encryptionIdentifier = "" ; this . opennetworkIdentifier = "" ; this . hostapdKernelModulePath = "" ; this . hostapdKernelModuleName = "" ; this . genericSetupSection = true ; } private void setupGeneric ( ) { this . wextSupported = true ; this . hostapdSupported = false ; this . softapSupported = false ; this . netdSupported = false ; this . tiadhocSupported = false ; this . autoSetupMethod = "" ; this . encryptionIdentifier = "" ; this . genericSetupSection = true ; } public String getDevice ( ) { return device ; } public boolean isTiadhocSupported ( ) { return tiadhocSupported ; } public String getTiadhocInterface ( ) { return tiadhocInterface ; } public boolean isWextSupported ( ) { return wextSupported ; } public boolean isHostapdSupported ( ) { return hostapdSupported ; } public boolean isSoftapSupported ( ) { return softapSupported ; } public boolean isSoftapSamsungSupported ( ) { return softapSamsungSupported ; } public boolean isNetdSupported ( ) { return netdSupported ; } public String getWextInterface ( ) { return wextInterface ; } public String getHostapdPath ( ) { return hostapdPath ; } public String getHostapdTemplate ( ) { return hostapdTemplate ; } public synchronized String getHostapdKernelModuleName ( ) { return hostapdKernelModuleName ; } public String getHostapdKernelModulePath ( ) { return hostapdKernelModulePath ; } public String getHostapdInterface ( ) { return hostapdInterface ; } public String getNetdInterface ( ) { return netdInterface ; } public String getSoftapInterface ( ) { return softapInterface ; } public String getEncryptionIdentifier ( ) { return encryptionIdentifier ; } public String getOpennetworkIdentifier ( ) { return opennetworkIdentifier ; } public boolean isAutoInternalNetSetup ( ) { return autoInternalNetSetup ; } public void setAutoInternalConfig ( boolean autoInternalConfig ) { this . autoInternalNetSetup = autoInternalConfig ; } public boolean isGenericSetupSection ( ) { return genericSetupSection ; } public String getSoftapFirmwarePath ( ) { return softapFirmwarePath ; } public String getAutoSetupMethod ( ) { return autoSetupMethod ; } public String getHostapdLoaderCmd ( ) { return hostapdLoaderCmd ; } public String getWifiLoadCmd ( ) { return wifiLoadCmd ; } public void setWifiLoadCmd ( String wifiLoadCmd ) { this . wifiLoadCmd = wifiLoadCmd ; } public String getWifiUnloadCmd ( ) { return wifiUnloadCmd ; } public void setWifiUnloadCmd ( String wifiUnloadCmd ) { this . wifiUnloadCmd = wifiUnloadCmd ; } public static boolean hasKernelFeature ( String feature ) { try { File cfg = new File ( "" ) ; if ( cfg . exists ( ) == false ) { return true ; } FileInputStream fis = new FileInputStream ( cfg ) ; GZIPInputStream gzin = new GZIPInputStream ( fis ) ; BufferedReader in = null ; String line = "" ; in = new BufferedReader ( new InputStreamReader ( gzin ) ) ; while ( ( line = in . readLine ( ) ) != null ) { if ( line . startsWith ( feature ) ) { gzin . close ( ) ; return true ; } } gzin . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return false ; } } package og . android . tether . system ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . FilenameFilter ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Date ; import java . util . HashMap ; import java . util . Hashtable ; import og . android . tether . data . ClientData ; import android . util . Log ; public class CoreTask { public static final String MSG_TAG = "" ; public String DATA_FILE_PATH ; private static final String FILESET_VERSION = "" ; private static final String defaultDNS1 = "" ; private Hashtable < String , String > runningProcesses = new Hashtable < String , String > ( ) ; public void setPath ( String path ) { this . DATA_FILE_PATH = path ; } public class Whitelist { public ArrayList < String > whitelist ; public Whitelist ( ) { this . whitelist = new ArrayList < String > ( ) ; } public boolean exists ( ) { File file = new File ( DATA_FILE_PATH + "" ) ; return ( file . exists ( ) && file . canRead ( ) ) ; } public boolean remove ( ) { File file = new File ( DATA_FILE_PATH + "" ) ; if ( file . exists ( ) ) return file . delete ( ) ; return false ; } public void touch ( ) throws IOException { File file = new File ( DATA_FILE_PATH + "" ) ; file . createNewFile ( ) ; } public void save ( ) throws Exception { FileOutputStream fos = null ; File file = new File ( DATA_FILE_PATH + "" ) ; try { fos = new FileOutputStream ( file ) ; for ( String mac : this . whitelist ) { fos . write ( ( mac + "" ) . getBytes ( ) ) ; } } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { } } } } public ArrayList < String > get ( ) { return readLinesFromFile ( DATA_FILE_PATH + "" ) ; } } public class WpaSupplicant { public boolean exists ( ) { File file = new File ( DATA_FILE_PATH + "" ) ; return ( file . exists ( ) && file . canRead ( ) ) ; } public boolean remove ( ) { File file = new File ( DATA_FILE_PATH + "" ) ; if ( file . exists ( ) ) { return file . delete ( ) ; } return false ; } public Hashtable < String , String > get ( ) { File inFile = new File ( DATA_FILE_PATH + "" ) ; if ( inFile . exists ( ) == false ) { return null ; } Hashtable < String , String > SuppConf = new Hashtable < String , String > ( ) ; ArrayList < String > lines = readLinesFromFile ( DATA_FILE_PATH + "" ) ; for ( String line : lines ) { if ( line . contains ( "" ) ) { String [ ] pair = line . split ( "" ) ; if ( pair [ ] != null && pair [ ] != null && pair [ ] . length ( ) > && pair [ ] . length ( ) > ) { SuppConf . put ( pair [ ] . trim ( ) , pair [ ] . trim ( ) ) ; } } } return SuppConf ; } public synchronized boolean write ( Hashtable < String , String > values ) { String filename = DATA_FILE_PATH + "" ; String fileString = "" ; ArrayList < String > inputLines = readLinesFromFile ( filename ) ; for ( String line : inputLines ) { if ( line . contains ( "" ) ) { String key = line . split ( "" ) [ ] ; if ( values . containsKey ( key ) ) { line = key + "" + values . get ( key ) ; } } line += "" ; fileString += line ; } if ( writeLinesToFile ( filename , fileString ) ) { CoreTask . this . chmod ( filename , "" ) ; return true ; } return false ; } } public class TiWlanConf { public Hashtable < String , String > get ( ) { Hashtable < String , String > tiWlanConf = new Hashtable < String , String > ( ) ; ArrayList < String > lines = readLinesFromFile ( DATA_FILE_PATH + "" ) ; for ( String line : lines ) { String [ ] pair = line . split ( "" ) ; if ( pair [ ] != null && pair [ ] != null && pair [ ] . length ( ) > && pair [ ] . length ( ) > ) { tiWlanConf . put ( pair [ ] . trim ( ) , pair [ ] . trim ( ) ) ; } } return tiWlanConf ; } public synchronized boolean write ( String name , String value ) { Hashtable < String , String > table = new Hashtable < String , String > ( ) ; table . put ( name , value ) ; return write ( table ) ; } public synchronized boolean write ( Hashtable < String , String > values ) { String filename = DATA_FILE_PATH + "" ; ArrayList < String > valueNames = Collections . list ( values . keys ( ) ) ; String fileString = "" ; ArrayList < String > inputLines = readLinesFromFile ( filename ) ; for ( String line : inputLines ) { for ( String name : valueNames ) { if ( line . contains ( name ) ) { line = name + "" + values . get ( name ) ; break ; } } line += "" ; fileString += line ; } return writeLinesToFile ( filename , fileString ) ; } } public class TetherConfig extends HashMap < String , String > { private static final long serialVersionUID = ; public HashMap < String , String > read ( ) { String filename = DATA_FILE_PATH + "" ; this . clear ( ) ; for ( String line : readLinesFromFile ( filename ) ) { if ( line . startsWith ( "" ) ) continue ; if ( ! line . contains ( "" ) ) continue ; String [ ] data = line . split ( "" ) ; if ( data . length > ) { this . put ( data [ ] , data [ ] ) ; } else { this . put ( data [ ] , "" ) ; } } return this ; } public boolean write ( ) { String lines = new String ( ) ; for ( String key : this . keySet ( ) ) { lines += key + "" + this . get ( key ) + "" ; } return writeLinesToFile ( DATA_FILE_PATH + "" , lines ) ; } } public class HostapdConfig extends HashMap < String , String > { private static final long serialVersionUID = ; public HashMap < String , String > read ( ) { String filename = DATA_FILE_PATH + "" ; this . clear ( ) ; for ( String line : readLinesFromFile ( filename ) ) { if ( line . startsWith ( "" ) ) continue ; if ( ! line . contains ( "" ) ) continue ; String [ ] data = line . split ( "" ) ; if ( data . length > ) { this . put ( data [ ] , data [ ] ) ; } else { this . put ( data [ ] , "" ) ; } } return this ; } public boolean write ( ) { String lines = new String ( ) ; for ( String key : this . keySet ( ) ) { lines += key + "" + this . get ( key ) + "" ; } return writeLinesToFile ( DATA_FILE_PATH + "" , lines ) ; } } public class DnsmasqConfig { private static final long serialVersionUID = ; private String lanconfig ; public void set ( String lanconfig ) { this . lanconfig = lanconfig ; } public boolean write ( ) { String [ ] lanparts = lanconfig . split ( "" ) ; String iprange = lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" ; StringBuffer buffer = new StringBuffer ( ) ; ; ArrayList < String > inputLines = readLinesFromFile ( DATA_FILE_PATH + "" ) ; for ( String line : inputLines ) { if ( line . contains ( "" ) ) { line = "" + iprange ; } buffer . append ( line + "" ) ; } if ( writeLinesToFile ( DATA_FILE_PATH + "" , buffer . toString ( ) ) == false ) { Log . e ( MSG_TAG , "" ) ; return false ; } return true ; } } public class BluetoothConfig { private static final long serialVersionUID = ; private String lanconfig ; public void set ( String lanconfig ) { this . lanconfig = lanconfig ; } public boolean write ( ) { String [ ] lanparts = lanconfig . split ( "" ) ; String gateway = lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" ; StringBuffer buffer = new StringBuffer ( ) ; ; ArrayList < String > inputLines = readLinesFromFile ( DATA_FILE_PATH + "" ) ; for ( String line : inputLines ) { if ( line . contains ( "" ) && line . endsWith ( "" ) ) { line = reassembleLine ( line , "" , "" , gateway ) ; } buffer . append ( line + "" ) ; } if ( writeLinesToFile ( DATA_FILE_PATH + "" , buffer . toString ( ) ) == false ) { Log . e ( MSG_TAG , "" ) ; return false ; } return true ; } } public Hashtable < String , ClientData > getLeases ( ) throws Exception { Hashtable < String , ClientData > returnHash = new Hashtable < String , ClientData > ( ) ; ClientData clientData ; ArrayList < String > lines = readLinesFromFile ( this . DATA_FILE_PATH + "" ) ; for ( String line : lines ) { clientData = new ClientData ( ) ; String [ ] data = line . split ( "" ) ; Date connectTime = new Date ( Long . parseLong ( data [ ] + "" ) ) ; String macAddress = data [ ] ; String ipAddress = data [ ] ; String clientName = data [ ] ; clientData . setConnectTime ( connectTime ) ; clientData . setClientName ( clientName ) ; clientData . setIpAddress ( ipAddress ) ; clientData . setMacAddress ( macAddress ) ; clientData . setConnected ( true ) ; returnHash . put ( macAddress , clientData ) ; } return returnHash ; } public boolean chmod ( String file , String mode ) { if ( NativeTask . runCommand ( "" + mode + "" + file ) == ) { return true ; } return false ; } public ArrayList < String > readLinesFromFile ( String filename ) { String line = null ; BufferedReader br = null ; InputStream ins = null ; ArrayList < String > lines = new ArrayList < String > ( ) ; File file = new File ( filename ) ; if ( file . canRead ( ) == false ) return lines ; try { ins = new FileInputStream ( file ) ; br = new BufferedReader ( new InputStreamReader ( ins ) , ) ; while ( ( line = br . readLine ( ) ) != null ) { lines . add ( line . trim ( ) ) ; } } catch ( Exception e ) { Log . d ( MSG_TAG , "" + e . getMessage ( ) ) ; } finally { try { ins . close ( ) ; br . close ( ) ; } catch ( Exception e ) { } } return lines ; } public boolean writeLinesToFile ( String filename , String lines ) { OutputStream out = null ; boolean returnStatus = false ; Log . d ( MSG_TAG , "" + lines . length ( ) + "" + filename ) ; try { out = new FileOutputStream ( filename ) ; out . write ( lines . getBytes ( ) ) ; out . flush ( ) ; } catch ( Exception e ) { Log . d ( MSG_TAG , "" + e . getMessage ( ) ) ; } finally { try { if ( out != null ) out . close ( ) ; returnStatus = true ; } catch ( IOException e ) { returnStatus = false ; } } return returnStatus ; } public boolean isNatEnabled ( ) { ArrayList < String > lines = readLinesFromFile ( "" ) ; return lines . contains ( "" ) ; } public String getKernelVersion ( ) { ArrayList < String > lines = readLinesFromFile ( "" ) ; String version = lines . get ( ) . split ( "" ) [ ] ; Log . d ( MSG_TAG , "" + version ) ; return version ; } public boolean isNetfilterSupported ( ) { if ( ( new File ( "" ) ) . exists ( ) == false ) { if ( ( new File ( "" ) ) . exists ( ) == false ) return false ; if ( ( new File ( "" ) ) . exists ( ) == false ) return false ; } else { if ( ! Configuration . hasKernelFeature ( "" ) || ! Configuration . hasKernelFeature ( "" ) || ! Configuration . hasKernelFeature ( "" ) ) return false ; } return true ; } public boolean isAccessControlSupported ( ) { if ( ( new File ( "" ) ) . exists ( ) == false ) { if ( ( new File ( "" ) ) . exists ( ) == false ) { return false ; } if ( Configuration . getDeviceType ( ) . equals ( Configuration . DEVICE_DROIDX ) ) { return false ; } } else { if ( ! Configuration . hasKernelFeature ( "" ) ) return false ; } return true ; } public boolean isProcessRunning ( String processName ) throws Exception { boolean processIsRunning = false ; Hashtable < String , String > tmpRunningProcesses = new Hashtable < String , String > ( ) ; File procDir = new File ( "" ) ; FilenameFilter filter = new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { try { Integer . parseInt ( name ) ; } catch ( NumberFormatException ex ) { return false ; } return true ; } } ; File [ ] processes = procDir . listFiles ( filter ) ; for ( File process : processes ) { String cmdLine = "" ; if ( this . runningProcesses . containsKey ( process . getAbsoluteFile ( ) . toString ( ) ) ) { cmdLine = this . runningProcesses . get ( process . getAbsoluteFile ( ) . toString ( ) ) ; } else { ArrayList < String > cmdlineContent = this . readLinesFromFile ( process . getAbsoluteFile ( ) + "" ) ; if ( cmdlineContent != null && cmdlineContent . size ( ) > ) { cmdLine = cmdlineContent . get ( ) ; } } tmpRunningProcesses . put ( process . getAbsoluteFile ( ) . toString ( ) , cmdLine ) ; if ( cmdLine . contains ( processName ) ) { processIsRunning = true ; } } this . runningProcesses = tmpRunningProcesses ; return processIsRunning ; } public boolean hasRootPermission ( ) { boolean rooted = false ; try { String path = System . getenv ( "" ) ; if ( path == null || path . length ( ) < ) { path = "" ; } Log . d ( MSG_TAG , "" + path ) ; for ( String dir : path . split ( "" ) ) { File su = new File ( dir + "" ) ; if ( su . exists ( ) ) { rooted = true ; break ; } } } catch ( Exception e ) { Log . d ( MSG_TAG , "" + e . getMessage ( ) ) ; } return rooted ; } public boolean rootWorks ( ) { return runRootCommand ( "" ) ; } public boolean runRootCommand ( String command ) { Log . d ( MSG_TAG , "" + command + "" ) ; int returncode = NativeTask . runCommand ( "" + command + "" ) ; if ( returncode == ) { return true ; } Log . d ( MSG_TAG , "" + returncode ) ; return false ; } public String getProp ( String property ) { return NativeTask . getProp ( property ) ; } public long [ ] getDataTraffic ( String device ) { long [ ] dataCount = new long [ ] { , } ; if ( device == "" ) return dataCount ; for ( String line : readLinesFromFile ( "" ) ) { if ( line . startsWith ( device ) == false ) continue ; line = line . replace ( '' , '' ) ; String [ ] values = line . split ( "" ) ; dataCount [ ] += Long . parseLong ( values [ ] ) ; dataCount [ ] += Long . parseLong ( values [ ] ) ; } return dataCount ; } public synchronized void updateDnsmasqFilepath ( ) { String dnsmasqConf = this . DATA_FILE_PATH + "" ; String newDnsmasq = new String ( ) ; boolean writeconfig = false ; ArrayList < String > lines = readLinesFromFile ( dnsmasqConf ) ; for ( String line : lines ) { if ( line . contains ( "" ) && ! line . contains ( CoreTask . this . DATA_FILE_PATH ) ) { line = "" + CoreTask . this . DATA_FILE_PATH + "" ; writeconfig = true ; } else if ( line . contains ( "" ) && ! line . contains ( CoreTask . this . DATA_FILE_PATH ) ) { line = "" + CoreTask . this . DATA_FILE_PATH + "" ; writeconfig = true ; } newDnsmasq += line + "" ; } if ( writeconfig == true ) writeLinesToFile ( dnsmasqConf , newDnsmasq ) ; } public synchronized String [ ] getCurrentDns ( ) { String dns [ ] = new String [ ] ; dns [ ] = getProp ( "" ) ; dns [ ] = getProp ( "" ) ; if ( dns [ ] == null || dns [ ] . length ( ) <= || dns [ ] . equals ( "" ) ) { dns [ ] = defaultDNS1 ; } if ( dns [ ] == null || dns [ ] . length ( ) <= || dns [ ] . equals ( "" ) ) { dns [ ] = "" ; } return dns ; } public synchronized String [ ] updateResolvConf ( ) { String resolvConf = this . DATA_FILE_PATH + "" ; String dns [ ] = this . getCurrentDns ( ) ; String linesToWrite = new String ( ) ; linesToWrite = "" + dns [ ] + "" ; if ( dns [ ] . length ( ) > ) { linesToWrite += "" + dns [ ] + "" ; } this . writeLinesToFile ( resolvConf , linesToWrite ) ; return dns ; } public boolean filesetOutdated ( ) { boolean outdated = true ; File inFile = new File ( this . DATA_FILE_PATH + "" ) ; if ( inFile . exists ( ) == false ) { return false ; } ArrayList < String > lines = readLinesFromFile ( this . DATA_FILE_PATH + "" ) ; int linecount = ; for ( String line : lines ) { if ( line . contains ( "" ) ) { String instVersion = line . split ( "" ) [ ] ; if ( instVersion != null && FILESET_VERSION . equals ( instVersion . trim ( ) ) == true ) { outdated = false ; } break ; } if ( linecount ++ > ) break ; } return outdated ; } public long getModifiedDate ( String filename ) { File file = new File ( filename ) ; if ( file . exists ( ) == false ) { return - ; } return file . lastModified ( ) ; } public synchronized boolean writeLanConf ( String lanconfString ) { boolean writesuccess = false ; String filename = null ; ArrayList < String > inputLines = null ; String fileString = null ; String [ ] lanparts = lanconfString . split ( "" ) ; String gateway = lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" ; String iprange = lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" + lanparts [ ] + "" ; fileString = "" ; filename = this . DATA_FILE_PATH + "" ; inputLines = readLinesFromFile ( filename ) ; for ( String line : inputLines ) { if ( line . contains ( "" ) && line . endsWith ( "" ) ) { line = reassembleLine ( line , "" , "" , gateway ) ; } fileString += line + "" ; } writesuccess = writeLinesToFile ( filename , fileString ) ; if ( writesuccess == false ) { Log . e ( MSG_TAG , "" ) ; return writesuccess ; } fileString = "" ; filename = this . DATA_FILE_PATH + "" ; inputLines = readLinesFromFile ( filename ) ; for ( String line : inputLines ) { if ( line . contains ( "" ) ) { line = "" + iprange ; } fileString += line + "" ; } writesuccess = writeLinesToFile ( filename , fileString ) ; if ( writesuccess == false ) { Log . e ( MSG_TAG , "" ) ; return writesuccess ; } return writesuccess ; } private String reassembleLine ( String source , String splitPattern , String prefix , String target ) { String returnString = new String ( ) ; String [ ] sourceparts = source . split ( splitPattern ) ; boolean prefixmatch = false ; boolean prefixfound = false ; for ( String part : sourceparts ) { if ( prefixmatch ) { returnString += target + "" ; prefixmatch = false ; } else { returnString += part + "" ; } if ( prefixfound == false && part . trim ( ) . equals ( prefix ) ) { prefixmatch = true ; prefixfound = true ; } } return returnString ; } } package og . android . tether ; import java . io . IOException ; import java . util . ArrayList ; import com . google . analytics . tracking . android . EasyTracker ; import og . android . tether . system . Configuration ; import android . R . drawable ; import android . app . AlertDialog ; import android . app . Dialog ; import android . app . ProgressDialog ; import android . content . BroadcastReceiver ; import android . content . Context ; import android . content . DialogInterface ; import android . content . Intent ; import android . content . IntentFilter ; import android . content . SharedPreferences ; import android . content . SharedPreferences . OnSharedPreferenceChangeListener ; import android . content . res . Resources ; import android . graphics . Color ; import android . os . Build ; import android . os . Bundle ; import android . os . Handler ; import android . os . Looper ; import android . os . Message ; import android . preference . CheckBoxPreference ; import android . preference . EditTextPreference ; import android . preference . ListPreference ; import android . preference . Preference ; import android . preference . PreferenceActivity ; import android . preference . PreferenceGroup ; import android . preference . PreferenceManager ; import android . text . Editable ; import android . text . TextWatcher ; import android . util . Log ; import android . view . LayoutInflater ; import android . view . Menu ; import android . view . MenuItem ; import android . view . SubMenu ; import android . view . View ; public class SetupActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { private TetherApplication application = null ; private ProgressDialog progressDialog ; public static final String MSG_TAG = "" ; public static final String DEFAULT_DEVICE = "" ; public static final String DEFAULT_SETUP = "" ; private String currentDevice ; private String currentSetup ; private String currentSSID ; private String currentChannel ; private String currentPassphrase ; private String currentLAN ; private boolean currentEncryptionEnabled ; private String currentTransmitPower ; private EditTextPreference prefPassphrase ; private EditTextPreference prefSSID ; private ListPreference prefDevice ; private static int ID_DIALOG_RESTARTING = ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; this . application = ( TetherApplication ) this . getApplication ( ) ; this . currentDevice = this . application . settings . getString ( "" , DEFAULT_DEVICE ) ; this . currentSetup = this . application . settings . getString ( "" , DEFAULT_SETUP ) ; this . currentSSID = this . application . settings . getString ( "" , "" ) ; this . currentChannel = this . application . settings . getString ( "" , "" ) ; this . currentPassphrase = this . application . settings . getString ( "" , this . application . DEFAULT_PASSPHRASE ) ; this . currentLAN = this . application . settings . getString ( "" , this . application . DEFAULT_LANNETWORK ) ; this . currentEncryptionEnabled = this . application . settings . getBoolean ( "" , false ) ; this . currentTransmitPower = this . application . settings . getString ( "" , "" ) ; this . updateSettingsMenu ( ) ; if ( ! this . application . accessControlSupported ) { PreferenceGroup securityGroup = ( PreferenceGroup ) findPreference ( "" ) ; securityGroup . setEnabled ( false ) ; } if ( Configuration . hasKernelFeature ( "" ) == false ) { PreferenceGroup btGroup = ( PreferenceGroup ) findPreference ( "" ) ; btGroup . setEnabled ( false ) ; } else { if ( Integer . parseInt ( Build . VERSION . SDK ) < Build . VERSION_CODES . ECLAIR ) { PreferenceGroup btGroup = ( PreferenceGroup ) findPreference ( "" ) ; CheckBoxPreference btdiscoverablePreference = ( CheckBoxPreference ) findPreference ( "" ) ; btGroup . removePreference ( btdiscoverablePreference ) ; } } this . prefSSID = ( EditTextPreference ) findPreference ( "" ) ; this . prefSSID . setOnPreferenceChangeListener ( new Preference . OnPreferenceChangeListener ( ) { public boolean onPreferenceChange ( Preference preference , Object newValue ) { String message = validateSSID ( newValue . toString ( ) ) ; if ( ! message . equals ( "" ) ) { SetupActivity . this . application . displayToastMessage ( message ) ; return false ; } return true ; } } ) ; Boolean bluetoothOn = PreferenceManager . getDefaultSharedPreferences ( this ) . getBoolean ( "" , false ) ; Message msg = Message . obtain ( ) ; msg . what = bluetoothOn ? : ; SetupActivity . this . setWifiPrefsEnableHandler . sendMessage ( msg ) ; } @ Override public void onStart ( ) { super . onStart ( ) ; EasyTracker . getInstance ( ) . activityStart ( this ) ; } @ Override public void onStop ( ) { super . onStop ( ) ; EasyTracker . getInstance ( ) . activityStop ( this ) ; } private void updateSettingsMenu ( ) { Resources resources = getResources ( ) ; CharSequence [ ] entries , entryvalues , targetentries , targetentryvalues ; if ( getPreferenceScreen ( ) != null ) { getPreferenceScreen ( ) . removeAll ( ) ; } addPreferencesFromResource ( R . layout . setupview ) ; if ( this . currentDevice . equals ( DEFAULT_DEVICE ) ) this . application . settings . edit ( ) . putString ( "" , DEFAULT_SETUP ) . commit ( ) ; String setupMethod = this . application . settings . getString ( "" , DEFAULT_SETUP ) ; if ( setupMethod . equals ( "" ) ) { setupMethod = this . application . getDeviceParametersAdv ( ) . getAutoSetupMethod ( ) ; } if ( ! ( setupMethod . startsWith ( "" ) || setupMethod . equals ( "" ) ) ) { PreferenceGroup wifiGroup = ( PreferenceGroup ) findPreference ( "" ) ; CheckBoxPreference reloadWifiPreference = ( CheckBoxPreference ) findPreference ( "" ) ; wifiGroup . removePreference ( reloadWifiPreference ) ; } if ( setupMethod . equals ( "" ) == false ) { PreferenceGroup wifiGroup = ( PreferenceGroup ) findPreference ( "" ) ; ListPreference txpowerPreference = ( ListPreference ) findPreference ( "" ) ; wifiGroup . removePreference ( txpowerPreference ) ; } if ( this . application . interfaceDriver . startsWith ( "" ) || this . application . interfaceDriver . equals ( Configuration . DRIVER_HOSTAP ) ) { PreferenceGroup wifiGroup = ( PreferenceGroup ) findPreference ( "" ) ; ListPreference encsetupPreference = ( ListPreference ) findPreference ( "" ) ; wifiGroup . removePreference ( encsetupPreference ) ; } this . prefPassphrase = ( EditTextPreference ) findPreference ( "" ) ; final int origTextColorPassphrase = SetupActivity . this . prefPassphrase . getEditText ( ) . getCurrentTextColor ( ) ; if ( ( setupMethod . equals ( DEFAULT_SETUP ) && Configuration . getWifiInterfaceDriver ( this . application . deviceType ) . startsWith ( "" ) || Configuration . getWifiInterfaceDriver ( this . application . deviceType ) . equals ( Configuration . DRIVER_HOSTAP ) ) || ( setupMethod . equals ( "" ) || setupMethod . equals ( "" ) || setupMethod . startsWith ( "" ) ) ) { Log . d ( MSG_TAG , "" ) ; this . prefPassphrase . setSummary ( this . prefPassphrase . getSummary ( ) + "" ) ; this . prefPassphrase . setDialogMessage ( getString ( R . string . setup_activity_error_passphrase_info ) ) ; this . prefPassphrase . getEditText ( ) . addTextChangedListener ( new TextWatcher ( ) { public void afterTextChanged ( Editable s ) { } public void beforeTextChanged ( CharSequence s , int start , int count , int after ) { } public void onTextChanged ( CharSequence s , int start , int before , int count ) { if ( s . length ( ) < || s . length ( ) > ) { SetupActivity . this . prefPassphrase . getEditText ( ) . setTextColor ( Color . RED ) ; } else { SetupActivity . this . prefPassphrase . getEditText ( ) . setTextColor ( origTextColorPassphrase ) ; } } } ) ; this . prefPassphrase . setOnPreferenceChangeListener ( new Preference . OnPreferenceChangeListener ( ) { public boolean onPreferenceChange ( Preference preference , Object newValue ) { String validChars = "" + "" + "" ; if ( newValue . toString ( ) . length ( ) < ) { SetupActivity . this . application . displayToastMessage ( getString ( R . string . setup_activity_error_passphrase_tooshort ) ) ; return false ; } else if ( newValue . toString ( ) . length ( ) > ) { SetupActivity . this . application . displayToastMessage ( getString ( R . string . setup_activity_error_passphrase_toolong ) ) ; return false ; } for ( int i = ; i < newValue . toString ( ) . length ( ) ; i ++ ) { if ( ! validChars . contains ( newValue . toString ( ) . substring ( i , i + ) ) ) { SetupActivity . this . application . displayToastMessage ( getString ( R . string . setup_activity_error_passphrase_invalidchars ) ) ; return false ; } } return true ; } } ) ; } else { Log . d ( MSG_TAG , "" ) ; this . prefPassphrase . setSummary ( this . prefPassphrase . getSummary ( ) + "" ) ; this . prefPassphrase . setDialogMessage ( getString ( R . string . setup_activity_error_passphrase_13chars ) ) ; this . prefPassphrase . getEditText ( ) . addTextChangedListener ( new TextWatcher ( ) { public void afterTextChanged ( Editable s ) { } public void beforeTextChanged ( CharSequence s , int start , int count , int after ) { } public void onTextChanged ( CharSequence s , int start , int before , int count ) { if ( s . length ( ) == ) { SetupActivity . this . prefPassphrase . getEditText ( ) . setTextColor ( origTextColorPassphrase ) ; } else { SetupActivity . this . prefPassphrase . getEditText ( ) . setTextColor ( Color . RED ) ; } } } ) ; this . prefPassphrase . setOnPreferenceChangeListener ( new Preference . OnPreferenceChangeListener ( ) { public boolean onPreferenceChange ( Preference preference , Object newValue ) { String validChars = "" + "" + "" ; if ( newValue . toString ( ) . length ( ) == ) { for ( int i = ; i < ; i ++ ) { if ( ! validChars . contains ( newValue . toString ( ) . substring ( i , i + ) ) ) { SetupActivity . this . application . displayToastMessage ( getString ( R . string . setup_activity_error_passphrase_invalidchars ) ) ; return false ; } } return true ; } else { SetupActivity . this . application . displayToastMessage ( getString ( R . string . setup_activity_error_passphrase_tooshort ) ) ; return false ; } } } ) ; } if ( this . application . interfaceDriver . startsWith ( "" ) == false || this . application . interfaceDriver . equals ( Configuration . DRIVER_HOSTAP ) == false ) { ListPreference channelpref = ( ListPreference ) findPreference ( "" ) ; entries = channelpref . getEntries ( ) ; targetentries = new CharSequence [ entries . length - ] ; for ( int i = ; i < entries . length ; i ++ ) { targetentries [ i - ] = entries [ i ] ; } entryvalues = channelpref . getEntryValues ( ) ; targetentryvalues = new CharSequence [ entries . length - ] ; for ( int i = ; i < entryvalues . length ; i ++ ) { targetentryvalues [ i - ] = entryvalues [ i ] ; } channelpref . setEntries ( targetentries ) ; channelpref . setEntryValues ( targetentryvalues ) ; } ListPreference setuppref = ( ListPreference ) findPreference ( "" ) ; String [ ] setupnames = resources . getStringArray ( R . array . setupnames ) ; String [ ] setupvalues = resources . getStringArray ( R . array . setupvalues ) ; ArrayList < String > tmpsetupnames = new ArrayList < String > ( ) ; ArrayList < String > tmpsetupvalues = new ArrayList < String > ( ) ; for ( int i = ; i < setupvalues . length ; i ++ ) { if ( ! setupvalues [ i ] . equals ( DEFAULT_SETUP ) && this . application . settings . getString ( "" , DEFAULT_DEVICE ) . equals ( DEFAULT_DEVICE ) ) continue ; if ( ! this . application . settings . getString ( "" , DEFAULT_DEVICE ) . equals ( DEFAULT_DEVICE ) && setupvalues [ i ] . equals ( DEFAULT_SETUP ) ) continue ; if ( setupvalues [ i ] . equals ( "" ) ) { if ( this . application . configurationAdv . isNetdSupported ( ) == false ) { continue ; } } else if ( setupvalues [ i ] . equals ( "" ) ) { if ( this . application . configurationAdv . isHostapdSupported ( ) == false ) { continue ; } } else if ( setupvalues [ i ] . equals ( "" ) ) { if ( this . application . configurationAdv . isSoftapSupported ( ) == false ) { continue ; } } else if ( setupvalues [ i ] . equals ( "" ) ) { if ( this . application . configurationAdv . isSoftapSamsungSupported ( ) == false ) { continue ; } } else if ( setupvalues [ i ] . equals ( "" ) ) { if ( this . application . configurationAdv . isWextSupported ( ) == false ) { continue ; } } tmpsetupnames . add ( setupnames [ i ] ) ; tmpsetupvalues . add ( setupvalues [ i ] ) ; } targetentries = new CharSequence [ tmpsetupnames . size ( ) ] ; targetentryvalues = new CharSequence [ tmpsetupvalues . size ( ) ] ; for ( int i = ; i < tmpsetupnames . size ( ) ; i ++ ) { targetentries [ i ] = tmpsetupnames . get ( i ) ; targetentryvalues [ i ] = tmpsetupvalues . get ( i ) ; } setuppref . setEntries ( targetentries ) ; setuppref . setEntryValues ( targetentryvalues ) ; } protected void onNewIntent ( Intent i ) { Log . d ( MSG_TAG , "" + i ) ; setIntent ( i ) ; } @ Override protected void onResume ( ) { Log . d ( MSG_TAG , "" ) ; super . onResume ( ) ; getPreferenceScreen ( ) . getSharedPreferences ( ) . registerOnSharedPreferenceChangeListener ( this ) ; IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( TetherService . INTENT_STATE ) ; registerReceiver ( intentReceiver , filter ) ; try { if ( getIntent ( ) . getAction ( ) . equals ( "" ) ) { } } catch ( NullPointerException e ) { Log . d ( MSG_TAG , "" , e ) ; } } @ Override protected void onPause ( ) { Log . d ( MSG_TAG , "" ) ; super . onPause ( ) ; getPreferenceScreen ( ) . getSharedPreferences ( ) . unregisterOnSharedPreferenceChangeListener ( this ) ; unregisterReceiver ( intentReceiver ) ; } @ Override protected Dialog onCreateDialog ( int id ) { if ( id == ID_DIALOG_RESTARTING ) { progressDialog = new ProgressDialog ( this ) ; progressDialog . setTitle ( getString ( R . string . setup_activity_restart_tethering_title ) ) ; progressDialog . setMessage ( getString ( R . string . setup_activity_restart_tethering_message ) ) ; progressDialog . setIndeterminate ( false ) ; progressDialog . setCancelable ( true ) ; return progressDialog ; } return null ; } public void onSharedPreferenceChanged ( SharedPreferences sharedPreferences , String key ) { updateConfiguration ( sharedPreferences , key ) ; } private BroadcastReceiver intentReceiver = new BroadcastReceiver ( ) { @ Override public void onReceive ( Context context , Intent intent ) { String action = intent . getAction ( ) ; if ( action . equals ( TetherService . INTENT_STATE ) ) { switch ( intent . getIntExtra ( "" , TetherService . STATE_IDLE ) ) { case TetherService . STATE_RESTARTING : showDialog ( SetupActivity . ID_DIALOG_RESTARTING ) ; break ; case TetherService . STATE_RUNNING : dismissDialog ( SetupActivity . ID_DIALOG_RESTARTING ) ; break ; default : dismissDialog ( SetupActivity . ID_DIALOG_RESTARTING ) ; break ; } } } } ; Handler displayToastMessageHandler = new Handler ( ) { public void handleMessage ( Message msg ) { if ( msg . obj != null ) { SetupActivity . this . application . displayToastMessage ( ( String ) msg . obj ) ; } super . handleMessage ( msg ) ; System . gc ( ) ; } } ; Handler updateSettingsMenuHandler = new Handler ( ) { public void handleMessage ( Message msg ) { SetupActivity . this . updateSettingsMenu ( ) ; super . handleMessage ( msg ) ; } } ; private void updateConfiguration ( final SharedPreferences sharedPreferences , final String key ) { EasyTracker . getTracker ( ) . trackEvent ( "" , "" , key , ) ; new Thread ( new Runnable ( ) { public void run ( ) { Looper . prepare ( ) ; String message = null ; if ( key . equals ( "" ) ) { String newDevice = sharedPreferences . getString ( "" , DEFAULT_DEVICE ) ; if ( SetupActivity . this . currentDevice . equals ( newDevice ) == false ) { SetupActivity . this . currentDevice = newDevice ; if ( newDevice . equals ( DEFAULT_DEVICE ) ) { SetupActivity . this . application . settings . edit ( ) . putString ( "" , DEFAULT_SETUP ) . commit ( ) ; } else if ( SetupActivity . this . currentSetup . equals ( DEFAULT_SETUP ) ) { SetupActivity . this . application . settings . edit ( ) . putString ( "" , "" ) . commit ( ) ; } SetupActivity . this . application . updateDeviceParametersAdv ( ) ; SetupActivity . this . updateSettingsMenuHandler . sendEmptyMessage ( ) ; message = getString ( R . string . setup_activity_info_device_changedto ) + "" + newDevice + "" ; try { if ( TetherService . singleton != null && TetherService . singleton . getState ( ) == TetherService . STATE_RUNNING ) { TetherService . singleton . restartTether ( ) ; } } catch ( Exception ex ) { message = getString ( R . string . setup_activity_error_restart_tethering ) ; } Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } } else if ( key . equals ( "" ) ) { String newSetup = sharedPreferences . getString ( "" , DEFAULT_SETUP ) ; if ( SetupActivity . this . currentSetup . equals ( newSetup ) == false ) { SetupActivity . this . currentSetup = newSetup ; if ( newSetup . equals ( DEFAULT_SETUP ) ) SetupActivity . this . application . settings . edit ( ) . putString ( "" , DEFAULT_DEVICE ) . commit ( ) ; SetupActivity . this . application . updateDeviceParametersAdv ( ) ; SetupActivity . this . updateSettingsMenuHandler . sendEmptyMessage ( ) ; message = getString ( R . string . setup_activity_info_setup_changedto ) + "" + newSetup + "" ; try { if ( TetherService . singleton != null && TetherService . singleton . getState ( ) == TetherService . STATE_RUNNING ) { TetherService . singleton . restartTether ( ) ; } } catch ( Exception ex ) { message = getString ( R . string . setup_activity_error_restart_tethering ) ; } Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } } else if ( key . equals ( "" ) ) { String newSSID = sharedPreferences . getString ( "" , "" ) ; if ( SetupActivity . this . currentSSID . equals ( newSSID ) == false ) { SetupActivity . this . currentSSID = newSSID ; message = getString ( R . string . setup_activity_info_ssid_changedto ) + "" + newSSID + "" ; try { if ( application . coretask . isNatEnabled ( ) && application . coretask . isProcessRunning ( "" ) ) { if ( TetherService . singleton != null ) TetherService . singleton . restartTether ( ) ; } } catch ( Exception ex ) { message = getString ( R . string . setup_activity_error_restart_tethering ) ; } Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } } else if ( key . equals ( "" ) ) { String newChannel = sharedPreferences . getString ( "" , "" ) ; if ( SetupActivity . this . currentChannel . equals ( newChannel ) == false ) { SetupActivity . this . currentChannel = newChannel ; message = getString ( R . string . setup_activity_info_channel_changedto ) + "" + newChannel + "" ; try { if ( application . coretask . isNatEnabled ( ) && application . coretask . isProcessRunning ( "" ) ) { if ( TetherService . singleton != null ) TetherService . singleton . restartTether ( ) ; } } catch ( Exception ex ) { message = getString ( R . string . setup_activity_error_restart_tethering ) ; } Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } } else if ( key . equals ( "" ) ) { try { boolean disableWakeLock = sharedPreferences . getBoolean ( "" , true ) ; if ( application . coretask . isNatEnabled ( ) && application . coretask . isProcessRunning ( "" ) ) { if ( disableWakeLock ) { SetupActivity . this . application . releaseWakeLock ( ) ; message = getString ( R . string . setup_activity_info_wakelock_disabled ) ; } else { SetupActivity . this . application . acquireWakeLock ( ) ; message = getString ( R . string . setup_activity_info_wakelock_enabled ) ; } } } catch ( Exception ex ) { Log . e ( MSG_TAG , "" ) ; } Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } else if ( key . equals ( "" ) ) { boolean enableAccessCtrl = sharedPreferences . getBoolean ( "" , false ) ; if ( enableAccessCtrl ) { if ( SetupActivity . this . application . whitelist . exists ( ) == false ) { try { application . whitelist . touch ( ) ; if ( TetherService . singleton != null ) TetherService . singleton . restartSecuredWifi ( ) ; message = getString ( R . string . setup_activity_info_accesscontrol_enabled ) ; } catch ( IOException e ) { message = "" ; } } } else { if ( SetupActivity . this . application . whitelist . exists ( ) == true ) { application . whitelist . remove ( ) ; if ( TetherService . singleton != null ) TetherService . singleton . restartSecuredWifi ( ) ; message = getString ( R . string . setup_activity_info_accesscontrol_disabled ) ; } } Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } else if ( key . equals ( "" ) ) { boolean enableEncryption = sharedPreferences . getBoolean ( "" , false ) ; if ( enableEncryption != SetupActivity . this . currentEncryptionEnabled ) { try { if ( application . coretask . isNatEnabled ( ) && application . coretask . isProcessRunning ( "" ) ) { if ( TetherService . singleton != null ) TetherService . singleton . restartTether ( ) ; } } catch ( Exception ex ) { } SetupActivity . this . currentEncryptionEnabled = enableEncryption ; Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } } else if ( key . equals ( "" ) ) { String passphrase = sharedPreferences . getString ( "" , SetupActivity . this . application . DEFAULT_PASSPHRASE ) ; if ( passphrase . equals ( SetupActivity . this . currentPassphrase ) == false ) { try { if ( application . coretask . isNatEnabled ( ) && application . coretask . isProcessRunning ( "" ) && application . wpasupplicant . exists ( ) ) { if ( TetherService . singleton != null ) TetherService . singleton . restartTether ( ) ; } } catch ( Exception ex ) { Log . e ( MSG_TAG , "" + ex ) ; } message = getString ( R . string . setup_activity_info_passphrase_changedto ) + "" + passphrase + "" ; SetupActivity . this . currentPassphrase = passphrase ; Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } } else if ( key . equals ( "" ) ) { String transmitPower = sharedPreferences . getString ( "" , "" ) ; if ( transmitPower . equals ( SetupActivity . this . currentTransmitPower ) == false ) { try { if ( application . coretask . isNatEnabled ( ) && application . coretask . isProcessRunning ( "" ) ) { if ( TetherService . singleton != null ) TetherService . singleton . restartTether ( ) ; } } catch ( Exception ex ) { Log . e ( MSG_TAG , "" + ex ) ; } message = getString ( R . string . setup_activity_info_txpower_changedto ) + "" + transmitPower + "" ; SetupActivity . this . currentTransmitPower = transmitPower ; Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; boolean shoTxPowerWarning = SetupActivity . this . application . settings . getBoolean ( "" , false ) ; if ( shoTxPowerWarning == false && transmitPower . equals ( "" ) == false ) { LayoutInflater li = LayoutInflater . from ( SetupActivity . this ) ; View view = li . inflate ( R . layout . txpowerwarningview , null ) ; new AlertDialog . Builder ( SetupActivity . this ) . setTitle ( getString ( R . string . setup_activity_txpower_warning_title ) ) . setView ( view ) . setNeutralButton ( getString ( R . string . setup_activity_txpower_warning_ok ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; SetupActivity . this . application . preferenceEditor . putBoolean ( "" , true ) ; SetupActivity . this . application . preferenceEditor . commit ( ) ; } } ) . show ( ) ; } } } else if ( key . equals ( "" ) ) { String lannetwork = sharedPreferences . getString ( "" , SetupActivity . this . application . DEFAULT_LANNETWORK ) ; if ( lannetwork . equals ( SetupActivity . this . currentLAN ) == false ) { try { if ( application . coretask . isNatEnabled ( ) && application . coretask . isProcessRunning ( "" ) ) { if ( TetherService . singleton != null ) TetherService . singleton . restartTether ( ) ; } message = getString ( R . string . setup_activity_info_lan_changedto ) + "" + lannetwork + "" ; SetupActivity . this . currentLAN = lannetwork ; } catch ( Exception ex ) { message = getString ( R . string . setup_activity_error_restart_tethering ) ; Log . e ( MSG_TAG , "" + ex ) ; } Message msg = new Message ( ) ; msg . obj = message ; SetupActivity . this . displayToastMessageHandler . sendMessage ( msg ) ; } } else if ( key . equals ( "" ) ) { Boolean bluetoothOn = sharedPreferences . getBoolean ( "" , false ) ; Message msg = Message . obtain ( ) ; msg . what = bluetoothOn ? : ; SetupActivity . this . setWifiPrefsEnableHandler . sendMessage ( msg ) ; try { if ( application . coretask . isNatEnabled ( ) && ( application . coretask . isProcessRunning ( "" ) || application . coretask . isProcessRunning ( "" ) ) ) { if ( TetherService . singleton != null ) TetherService . singleton . restartTether ( ) ; } } catch ( Exception ex ) { message = getString ( R . string . setup_activity_error_restart_tethering ) ; } boolean showBtWarning = SetupActivity . this . application . settings . getBoolean ( "" , false ) ; if ( showBtWarning == false && bluetoothOn == true ) { LayoutInflater li = LayoutInflater . from ( SetupActivity . this ) ; View view = li . inflate ( R . layout . btwarningview , null ) ; new AlertDialog . Builder ( SetupActivity . this ) . setTitle ( getString ( R . string . setup_activity_bt_warning_title ) ) . setView ( view ) . setNeutralButton ( getString ( R . string . setup_activity_bt_warning_ok ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; SetupActivity . this . application . preferenceEditor . putBoolean ( "" , true ) ; SetupActivity . this . application . preferenceEditor . commit ( ) ; } } ) . show ( ) ; } } else if ( key . equals ( "" ) ) { Boolean bluetoothWifi = sharedPreferences . getBoolean ( "" , false ) ; if ( bluetoothWifi ) { if ( TetherService . singleton != null ) TetherService . singleton . enableWifi ( ) ; } } Looper . loop ( ) ; } } ) . start ( ) ; } Handler setWifiPrefsEnableHandler = new Handler ( ) { public void handleMessage ( Message msg ) { PreferenceGroup wifiGroup = ( PreferenceGroup ) findPreference ( "" ) ; wifiGroup . setEnabled ( msg . what == ) ; super . handleMessage ( msg ) ; } } ; public String validateSSID ( String newSSID ) { String message = "" ; String validChars = "" + "" + "" ; for ( int i = ; i < newSSID . length ( ) ; i ++ ) { if ( ! validChars . contains ( newSSID . substring ( i , i + ) ) ) { message = getString ( R . string . setup_activity_error_ssid_invalidchars ) ; } } if ( newSSID . equals ( "" ) ) { message = getString ( R . string . setup_activity_error_ssid_empty ) ; } if ( message . length ( ) > ) message += getString ( R . string . setup_activity_error_ssid_notsaved ) ; return message ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { boolean supRetVal = super . onCreateOptionsMenu ( menu ) ; SubMenu installBinaries = menu . addSubMenu ( , , , getString ( R . string . setup_activity_reinstall ) ) ; installBinaries . setIcon ( drawable . ic_menu_set_as ) ; return supRetVal ; } @ Override public boolean onOptionsItemSelected ( MenuItem menuItem ) { boolean supRetVal = super . onOptionsItemSelected ( menuItem ) ; Log . d ( MSG_TAG , "" + menuItem . getItemId ( ) + "" + menuItem . getTitle ( ) ) ; if ( menuItem . getItemId ( ) == ) { this . application . installFiles ( ) ; } return supRetVal ; } } package og . android . tether ; import android . content . Context ; import android . content . Intent ; import android . sax . Element ; import android . sax . EndElementListener ; import android . sax . EndTextElementListener ; import android . sax . RootElement ; import android . util . Log ; import java . io . IOException ; import java . io . InputStream ; import org . apache . http . HttpResponse ; import org . apache . http . client . ClientProtocolException ; import org . apache . http . client . methods . HttpGet ; import org . apache . http . impl . client . DefaultHttpClient ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import org . xml . sax . ContentHandler ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; import org . xml . sax . XMLReader ; import org . xml . sax . helpers . XMLReaderFactory ; public class RSSReader { static { System . setProperty ( "" , "" ) ; } private final static String TAG = "" ; public final static String MESSAGE_JSON_RSS = "" ; public final static String EXTRA_JSON_RSS = "" ; public final static String [ ] _PARSED_ITEM_ELEMENTS = { "" , "" , "" , "" } ; public final static String [ ] [ ] _PARSED_ITEM_DTD_ELEMENTS = { { "" , "" } } ; public final String [ ] PARSED_ITEM_ELEMENTS ; public final String [ ] [ ] PARSED_ITEM_DTD_ELEMENTS ; public final String RSS_URL ; public final Context mContext ; private JSONArray mRssItems = null ; private JSONObject mRssItem = null ; RSSReader ( Context context , String RSSUrl ) { mContext = context ; RSS_URL = RSSUrl ; PARSED_ITEM_ELEMENTS = _PARSED_ITEM_ELEMENTS ; PARSED_ITEM_DTD_ELEMENTS = _PARSED_ITEM_DTD_ELEMENTS ; } RSSReader ( Context context , String RSSUrl , String [ ] parsedItemElements , String [ ] [ ] parsedItemNSElements ) { mContext = context ; RSS_URL = RSSUrl ; PARSED_ITEM_ELEMENTS = parsedItemElements ; PARSED_ITEM_DTD_ELEMENTS = parsedItemNSElements ; } void readRSS ( ) { if ( mRssItems != null ) return ; new Thread ( new Runnable ( ) { public void run ( ) { mRssItems = new JSONArray ( ) ; mRssItem = new JSONObject ( ) ; parseRSS ( httpGetRSS ( RSS_URL ) ) ; mContext . sendBroadcast ( new Intent ( MESSAGE_JSON_RSS ) . putExtra ( EXTRA_JSON_RSS , mRssItems . toString ( ) ) ) ; mRssItems = null ; } } ) . start ( ) ; } InputStream httpGetRSS ( String url ) { HttpResponse response = null ; InputStream content = null ; try { response = new DefaultHttpClient ( ) . execute ( new HttpGet ( RSS_URL ) ) ; content = response . getEntity ( ) . getContent ( ) ; } catch ( ClientProtocolException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } if ( response == null ) { Log . e ( TAG , "" ) ; } else if ( response . getStatusLine ( ) . getStatusCode ( ) != ) { Log . e ( TAG , "" + response . getStatusLine ( ) . getStatusCode ( ) ) ; } else { Log . d ( TAG , "" + response . getStatusLine ( ) . getStatusCode ( ) ) ; } return content ; } void parseRSS ( InputStream feed ) { XMLReader parser = null ; try { parser = XMLReaderFactory . createXMLReader ( ) ; parser . setContentHandler ( getRSSContentHandler ( ) ) ; parser . parse ( new InputSource ( feed ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( SAXException e ) { e . printStackTrace ( ) ; } } ContentHandler getRSSContentHandler ( ) { RootElement root = new RootElement ( "" ) ; Element element = root . getChild ( "" ) . getChild ( "" ) ; element . setEndElementListener ( new EndElementListener ( ) { public void end ( ) { mRssItems . put ( mRssItem ) ; mRssItem = new JSONObject ( ) ; } } ) ; for ( String el : PARSED_ITEM_ELEMENTS ) element . getChild ( el ) . setEndTextElementListener ( new RSSElementListener ( el ) ) ; for ( String [ ] dtdAndEl : PARSED_ITEM_DTD_ELEMENTS ) element . getChild ( dtdAndEl [ ] , dtdAndEl [ ] ) . setEndTextElementListener ( new RSSElementListener ( dtdAndEl [ ] ) ) ; return root . getContentHandler ( ) ; } class RSSElementListener implements EndTextElementListener { String element ; RSSElementListener ( String element ) { this . element = element ; } public void end ( String body ) { try { mRssItem . put ( element , body ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } } } } package og . android . tether ; import java . io . IOException ; import og . android . tether . R ; import org . apache . http . client . ClientProtocolException ; import org . apache . http . client . methods . HttpGet ; import org . apache . http . impl . client . DefaultHttpClient ; import android . app . Notification ; import android . app . NotificationManager ; import android . app . PendingIntent ; import android . content . Context ; import android . content . Intent ; import android . content . SharedPreferences ; import android . media . AudioManager ; import android . media . Ringtone ; import android . media . RingtoneManager ; import android . net . Uri ; import android . os . Bundle ; import android . preference . PreferenceManager ; import android . util . Log ; import com . google . android . c2dm . C2DMBaseReceiver ; public class C2DMReceiver extends C2DMBaseReceiver { private static final String TAG = "" ; public C2DMReceiver ( ) { super ( DeviceRegistrar . SENDER_ID ) ; } public static SharedPreferences prefs ( final Context context ) { return PreferenceManager . getDefaultSharedPreferences ( context ) ; } @ Override public void onRegistered ( Context context , String registration ) { DeviceRegistrar . registerWithServer ( context , registration ) ; } @ Override public void onUnregistered ( Context context ) { SharedPreferences prefs = prefs ( context ) ; String deviceRegistrationID = prefs . getString ( "" , null ) ; DeviceRegistrar . unregisterWithServer ( context , deviceRegistrationID ) ; } @ Override public void onError ( Context context , String errorId ) { context . sendBroadcast ( new Intent ( "" ) ) ; } @ Override public void onMessage ( Context context , Intent intent ) { Bundle extras = intent . getExtras ( ) ; if ( extras != null ) { Log . d ( TAG , "" + extras . toString ( ) ) ; String msg = ( String ) extras . get ( "" ) ; String title = ( String ) extras . get ( "" ) ; String uid = ( String ) extras . get ( "" ) ; DefaultHttpClient client = new DefaultHttpClient ( ) ; HttpGet get = new HttpGet ( DeviceRegistrar . RECEIVED_PATH + "" + uid ) ; try { client . execute ( get ) ; } catch ( ClientProtocolException e ) { } catch ( IOException e ) { } String url = DeviceRegistrar . REACT_PATH + "" + uid ; Intent launchIntent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( url ) ) ; launchIntent . setFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; generateNotification ( context , msg , title , launchIntent ) ; } } public static void generateNotification ( Context context , String msg , String title , Intent intent ) { int icon = R . drawable . icon_og_bev ; long when = System . currentTimeMillis ( ) ; Notification notification = new Notification ( icon , title , when ) ; notification . setLatestEventInfo ( context , title , msg , PendingIntent . getActivity ( context , , intent , ) ) ; notification . flags |= Notification . FLAG_AUTO_CANCEL ; notification . defaults = Notification . DEFAULT_ALL ; Log . d ( TAG , "" + notification . toString ( ) ) ; SharedPreferences settings = prefs ( context ) ; int notificatonID = settings . getInt ( "" , ) ; NotificationManager nm = ( NotificationManager ) context . getSystemService ( Context . NOTIFICATION_SERVICE ) ; nm . notify ( notificatonID , notification ) ; playNotificationSound ( context ) ; SharedPreferences . Editor editor = settings . edit ( ) ; editor . putInt ( "" , ++ notificatonID % ) ; editor . commit ( ) ; } public static void playNotificationSound ( Context context ) { Uri uri = RingtoneManager . getDefaultUri ( RingtoneManager . TYPE_NOTIFICATION ) ; if ( uri != null ) { Ringtone rt = RingtoneManager . getRingtone ( context , uri ) ; if ( rt != null ) { rt . setStreamType ( AudioManager . STREAM_NOTIFICATION ) ; rt . play ( ) ; } } } } package og . android . tether ; import java . util . ArrayList ; import java . util . List ; import og . android . tether . system . WebserviceTask ; import org . apache . http . HttpResponse ; import org . apache . http . message . BasicNameValuePair ; import android . content . Context ; import android . content . SharedPreferences ; import android . content . SharedPreferences . Editor ; import android . content . res . Configuration ; import android . preference . PreferenceManager ; import android . provider . Settings . Secure ; import android . util . Log ; public class DeviceRegistrar { public static final String STATUS_EXTRA = "" ; public static final int REGISTERED_STATUS = ; public static final int AUTH_ERROR_STATUS = ; public static final int UNREGISTERED_STATUS = ; public static final int ERROR_STATUS = ; private static final String TAG = "" ; static final String SENDER_ID = "" ; static final String BASE_URL = "" ; private static final String REGISTER_PATH = BASE_URL + "" ; private static final String UNREGISTER_PATH = BASE_URL + "" ; static final String RECEIVED_PATH = BASE_URL + "" ; static final String REACT_PATH = BASE_URL + "" ; public static SharedPreferences prefs ( final Context context ) { return PreferenceManager . getDefaultSharedPreferences ( context ) ; } public static void registerWithServer ( final Context context , final String deviceRegistrationID ) { new Thread ( new Runnable ( ) { public void run ( ) { try { HttpResponse res = makeRequest ( context , deviceRegistrationID , REGISTER_PATH ) ; if ( res . getStatusLine ( ) . getStatusCode ( ) == ) { Log . i ( TAG , "" ) ; Editor editor = prefs ( context ) . edit ( ) ; editor . putBoolean ( "" , true ) ; editor . commit ( ) ; } else { Log . w ( TAG , "" + String . valueOf ( res . getStatusLine ( ) . getStatusCode ( ) ) ) ; } } catch ( Exception e ) { Log . w ( TAG , "" + e . getMessage ( ) ) ; } } } ) . start ( ) ; } public static void unregisterWithServer ( final Context context , final String deviceRegistrationID ) { new Thread ( new Runnable ( ) { public void run ( ) { try { HttpResponse res = makeRequest ( context , deviceRegistrationID , UNREGISTER_PATH ) ; if ( res . getStatusLine ( ) . getStatusCode ( ) == ) { Log . i ( TAG , "" ) ; Editor editor = prefs ( context ) . edit ( ) ; editor . putBoolean ( "" , false ) ; editor . commit ( ) ; } else { Log . w ( TAG , "" + String . valueOf ( res . getStatusLine ( ) . getStatusCode ( ) ) ) ; } } catch ( Exception e ) { Log . w ( TAG , "" + e . getMessage ( ) ) ; } } } ) . start ( ) ; } private static HttpResponse makeRequest ( Context context , String deviceRegistrationID , String urlPath ) throws Exception { List < BasicNameValuePair > params = new ArrayList < BasicNameValuePair > ( ) ; params . add ( new BasicNameValuePair ( "" , deviceRegistrationID ) ) ; String aid = Secure . getString ( context . getContentResolver ( ) , Secure . ANDROID_ID ) ; if ( aid != null ) { params . add ( new BasicNameValuePair ( "" , aid ) ) ; } params . add ( new BasicNameValuePair ( "" , isTablet ( context ) ? "" : "" ) ) ; return WebserviceTask . makeRequest ( urlPath , params ) ; } static boolean isTablet ( Context context ) { int xlargeBit = ; Configuration config = context . getResources ( ) . getConfiguration ( ) ; return ( config . screenLayout & xlargeBit ) == xlargeBit ; } } package og . android . tether ; import android . content . BroadcastReceiver ; import android . content . Context ; import android . content . Intent ; import android . util . Log ; public class AlarmReceiver extends BroadcastReceiver { private static String TAG = "" ; @ Override public void onReceive ( Context context , Intent intent ) { Log . d ( TAG , "" + context + "" + intent ) ; if ( intent . getAction ( ) . equals ( TetherApplication . MESSAGE_REPORT_STATS ) ) { TetherApplication . singleton . reportStats ( - , true ) ; } } } package og . android . tether ; import og . android . tether . R ; import android . content . Context ; import android . content . Intent ; import android . content . ComponentName ; import android . content . SharedPreferences ; import android . appwidget . AppWidgetProvider ; import android . appwidget . AppWidgetManager ; import android . app . PendingIntent ; import android . widget . RemoteViews ; import android . view . View ; import android . util . Log ; import android . os . AsyncTask ; import android . os . Handler ; import android . preference . PreferenceManager ; public class WidgetProvider extends AppWidgetProvider { public static final String MSG_TAG = "" ; public static final StateTracker stateTracker = new StateTracker ( ) ; static final ComponentName THIS_APPWIDGET = new ComponentName ( "" , "" ) ; Context ctx ; private SharedPreferences mPrefs ; private SharedPreferences . Editor mPrefsEditor ; static Handler animateHandler = new Handler ( ) ; static WidgetAnimator widgetAnimator = new WidgetAnimator ( ) ; static int FRAME_DELAY = ; static RemoteViews buildUpdate ( Context context ) { Intent intent = new Intent ( context , WidgetProvider . class ) ; intent . addCategory ( Intent . CATEGORY_ALTERNATIVE ) ; PendingIntent pendingIntent = PendingIntent . getBroadcast ( context , , intent , ) ; RemoteViews views = new RemoteViews ( context . getPackageName ( ) , R . layout . appwidget_provider_layout ) ; views . setOnClickPendingIntent ( R . id . button , pendingIntent ) ; updateWidgetButtons ( views , context ) ; return views ; } public static void updateWidget ( Context context ) { RemoteViews views = buildUpdate ( context ) ; AppWidgetManager . getInstance ( context ) . updateAppWidget ( THIS_APPWIDGET , views ) ; } public void onUpdate ( Context context , AppWidgetManager appWidgetManager , int [ ] appWidgetIds ) { final int N = appWidgetIds . length ; RemoteViews views = buildUpdate ( context ) ; for ( int i = ; i < N ; i ++ ) { int appWidgetId = appWidgetIds [ i ] ; appWidgetManager . updateAppWidget ( appWidgetId , views ) ; } ctx = context ; } public void onReceive ( Context context , Intent intent ) { super . onReceive ( context , intent ) ; if ( intent . hasCategory ( Intent . CATEGORY_ALTERNATIVE ) ) { mPrefs = PreferenceManager . getDefaultSharedPreferences ( context ) ; mPrefsEditor = mPrefs . edit ( ) ; mPrefsEditor . putInt ( "" , mPrefs . getInt ( "" , ) + ) . commit ( ) ; stateTracker . sendBroadcastChange ( context ) ; } else if ( intent . getAction ( ) . equals ( TetherService . INTENT_STATE ) ) { int stateArg = intent . getIntExtra ( "" , TetherService . MANAGE_STOPPED ) ; stateTracker . currentState = stateArg ; updateWidget ( context ) ; } } public static void updateWidgetButtons ( RemoteViews remoteViews , Context context ) { animateHandler . removeCallbacks ( widgetAnimator ) ; switch ( stateTracker . currentState ) { case TetherService . STATE_RUNNING : case TetherService . STATE_FAIL_LOG : remoteViews . setImageViewResource ( R . id . button , R . drawable . widgeton ) ; break ; case TetherService . STATE_IDLE : case TetherService . STATE_FAIL_EXEC_START : case TetherService . STATE_FAIL_EXEC_STOP : remoteViews . setImageViewResource ( R . id . button , R . drawable . widgetoff ) ; break ; default : if ( stateTracker . currentState == TetherService . STATE_STARTING ) { widgetAnimator . currentFrame = ; widgetAnimator . turningOn = true ; } else { widgetAnimator . currentFrame = ; widgetAnimator . turningOn = false ; } widgetAnimator . views = remoteViews ; widgetAnimator . context = context ; animateHandler . postDelayed ( widgetAnimator , FRAME_DELAY ) ; break ; } } public void launchApp ( View v ) { Intent i = new Intent ( Intent . ACTION_MAIN ) ; i . addCategory ( Intent . CATEGORY_LAUNCHER ) ; ctx . startActivity ( i ) ; } } class StateTracker { int currentState ; boolean isChanging = false ; public StateTracker ( ) { if ( TetherService . singleton != null ) currentState = TetherService . singleton . getState ( ) ; else currentState = TetherService . STATE_IDLE ; } void changeState ( ) { } void sendBroadcastChange ( Context context ) { Log . d ( WidgetProvider . MSG_TAG , "" + currentState ) ; int newState ; switch ( currentState ) { case TetherService . STATE_RUNNING : case TetherService . STATE_FAIL_LOG : newState = TetherService . MANAGE_STOP ; break ; default : newState = TetherService . MANAGE_START ; break ; } new IntentAsyncTask ( context , newState ) . execute ( new Void [ ] ) ; } } class IntentAsyncTask extends AsyncTask < Void , Void , Void > { Context context ; int state ; public IntentAsyncTask ( Context context , int state ) { this . context = context ; this . state = state ; } protected Void doInBackground ( Void ... arg ) { Intent intent = new Intent ( ) ; intent . setAction ( TetherService . INTENT_MANAGE ) ; intent . putExtra ( "" , state ) ; context . sendBroadcast ( intent ) ; Log . d ( WidgetProvider . MSG_TAG , "" + state ) ; return null ; } } class WidgetAnimator implements Runnable { int currentFrame = ; boolean turningOn = true ; RemoteViews views ; Context context ; public void run ( ) { views . setImageViewResource ( R . id . button , getImageId ( currentFrame ) ) ; AppWidgetManager . getInstance ( context ) . updateAppWidget ( WidgetProvider . THIS_APPWIDGET , views ) ; if ( turningOn ) { if ( ++ currentFrame > ) currentFrame = ; } else { if ( -- currentFrame < ) currentFrame = ; } WidgetProvider . animateHandler . postDelayed ( WidgetProvider . widgetAnimator , WidgetProvider . FRAME_DELAY ) ; } int getImageId ( int index ) { switch ( index ) { case : return R . drawable . widgetwait1 ; case : return R . drawable . widgetwait2 ; case : return R . drawable . widgetwait3 ; case : default : return R . drawable . widgetwait4 ; } } } package og . android . tether ; import java . io . File ; import java . io . FileInputStream ; import java . io . InputStreamReader ; import com . google . analytics . tracking . android . TrackedActivity ; import og . android . tether . R ; import android . app . Activity ; import android . os . Bundle ; import android . webkit . WebSettings ; import android . webkit . WebView ; public class LogActivity extends TrackedActivity { public static final String MSG_TAG = "" ; private static final String HEADER = "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String FOOTER = "" ; private WebView webView = null ; private TetherApplication application ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . logview ) ; this . application = ( TetherApplication ) this . getApplication ( ) ; this . webView = ( WebView ) findViewById ( R . id . webviewLog ) ; this . webView . getSettings ( ) . setJavaScriptEnabled ( false ) ; this . webView . getSettings ( ) . setCacheMode ( WebSettings . LOAD_NO_CACHE ) ; this . webView . getSettings ( ) . setJavaScriptCanOpenWindowsAutomatically ( false ) ; this . webView . getSettings ( ) . setPluginsEnabled ( false ) ; this . webView . getSettings ( ) . setSupportMultipleWindows ( false ) ; this . webView . getSettings ( ) . setSupportZoom ( false ) ; this . setWebViewContent ( ) ; } private void setWebViewContent ( ) { this . webView . loadDataWithBaseURL ( "" , HEADER + this . application . readLogfile ( ) + FOOTER , "" , "" , "" ) ; } } package og . android . tether ; import java . io . UnsupportedEncodingException ; import java . net . URLEncoder ; import android . R . drawable ; import android . annotation . TargetApi ; import android . app . Activity ; import android . app . AlertDialog ; import android . app . Dialog ; import android . app . ProgressDialog ; import android . app . AlertDialog . Builder ; import android . content . ActivityNotFoundException ; import android . content . BroadcastReceiver ; import android . content . Context ; import android . content . DialogInterface ; import android . content . Intent ; import android . content . IntentFilter ; import android . net . Uri ; import android . os . Bundle ; import android . os . Handler ; import android . os . Message ; import android . text . Html ; import android . text . Spanned ; import android . util . Log ; import android . view . KeyEvent ; import android . view . LayoutInflater ; import android . view . Menu ; import android . view . MenuItem ; import android . view . MotionEvent ; import android . view . SubMenu ; import android . view . View ; import android . view . View . OnClickListener ; import android . view . animation . Animation ; import android . view . animation . BounceInterpolator ; import android . view . animation . ScaleAnimation ; import android . widget . AdapterView ; import android . widget . AdapterView . OnItemClickListener ; import android . widget . ArrayAdapter ; import android . widget . Button ; import android . widget . CompoundButton ; import android . widget . CompoundButton . OnCheckedChangeListener ; import android . widget . CheckBox ; import android . widget . ImageView ; import android . widget . LinearLayout ; import android . widget . ListView ; import android . widget . ProgressBar ; import android . widget . RelativeLayout ; import android . widget . TableRow ; import android . widget . TextView ; import com . google . analytics . tracking . android . EasyTracker ; import com . google . analytics . tracking . android . TrackedActivity ; import com . google . android . c2dm . C2DMessaging ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import org . miscwidgets . widget . Panel ; import org . miscwidgets . widget . Panel . OnPanelListener ; public class MainActivity extends TrackedActivity { private TetherApplication application = null ; private ProgressDialog progressDialog ; private ImageView startBtn = null ; private OnClickListener startBtnListener = null ; private ImageView stopBtn = null ; private OnClickListener stopBtnListener = null ; private CompoundButton lockBtn = null ; private OnCheckedChangeListener lockBtnListener = null ; private TextView radioModeLabel = null ; private ImageView radioModeImage = null ; private TextView progressTitle = null ; private TextView progressText = null ; private ProgressBar progressBar = null ; private RelativeLayout downloadUpdateLayout = null ; private RelativeLayout batteryTemperatureLayout = null ; private CheckBox lockButtonCheckbox = null ; private RelativeLayout trafficRow = null ; private TextView downloadText = null ; private TextView uploadText = null ; private TextView downloadRateText = null ; private TextView uploadRateText = null ; private TextView batteryTemperature = null ; private TableRow startTblRow = null ; private TableRow stopTblRow = null ; private ScaleAnimation animation = null ; private RSSReader rssReader = null ; private ListView rssView = null ; private ArrayAdapter < Spanned > rssAdapter = null ; private JSONArray jsonRssArray = null ; private Panel rssPanel = null ; private TextView communityText = null ; private LinearLayout bottomButtonLayout = null ; private static int ID_DIALOG_STARTING = ; private static int ID_DIALOG_STOPPING = ; public static final int MESSAGE_CHECK_LOG = ; public static final int MESSAGE_CANT_START_TETHER = ; public static final int MESSAGE_DOWNLOAD_STARTING = ; public static final int MESSAGE_DOWNLOAD_PROGRESS = ; public static final int MESSAGE_DOWNLOAD_COMPLETE = ; public static final int MESSAGE_DOWNLOAD_BLUETOOTH_COMPLETE = ; public static final int MESSAGE_DOWNLOAD_BLUETOOTH_FAILED = ; public static final int MESSAGE_TRAFFIC_START = ; public static final int MESSAGE_TRAFFIC_COUNT = ; public static final int MESSAGE_TRAFFIC_RATE = ; public static final int MESSAGE_TRAFFIC_END = ; public static final String MSG_TAG = "" ; public static MainActivity currentInstance = null ; private static void setCurrent ( MainActivity current ) { MainActivity . currentInstance = current ; } String tagURL ( String url , String medium , String content , String campaign ) { String p = url . contains ( "" ) ? "" : "" ; String source = "" + application . getVersionNumber ( ) ; try { source = URLEncoder . encode ( source , "" ) ; medium = URLEncoder . encode ( medium , "" ) ; content = URLEncoder . encode ( content , "" ) ; campaign = URLEncoder . encode ( campaign , "" ) ; } catch ( UnsupportedEncodingException e ) { } return url + p + "" + source + "" + medium + "" + content + "" + campaign ; } @ TargetApi ( ) @ Override public void onCreate ( Bundle savedInstanceState ) { Log . d ( MSG_TAG , "" ) ; super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . main ) ; this . application = ( TetherApplication ) this . getApplication ( ) ; MainActivity . setCurrent ( this ) ; this . startTblRow = ( TableRow ) findViewById ( R . id . startRow ) ; this . stopTblRow = ( TableRow ) findViewById ( R . id . stopRow ) ; this . radioModeImage = ( ImageView ) findViewById ( R . id . radioModeImage ) ; this . progressBar = ( ProgressBar ) findViewById ( R . id . progressBar ) ; this . progressText = ( TextView ) findViewById ( R . id . progressText ) ; this . progressTitle = ( TextView ) findViewById ( R . id . progressTitle ) ; this . downloadUpdateLayout = ( RelativeLayout ) findViewById ( R . id . layoutDownloadUpdate ) ; this . batteryTemperatureLayout = ( RelativeLayout ) findViewById ( R . id . layoutBatteryTemp ) ; this . lockButtonCheckbox = ( CheckBox ) findViewById ( R . id . lockButton ) ; this . trafficRow = ( RelativeLayout ) findViewById ( R . id . trafficRow ) ; this . downloadText = ( TextView ) findViewById ( R . id . trafficDown ) ; this . uploadText = ( TextView ) findViewById ( R . id . trafficUp ) ; this . downloadRateText = ( TextView ) findViewById ( R . id . trafficDownRate ) ; this . uploadRateText = ( TextView ) findViewById ( R . id . trafficUpRate ) ; this . batteryTemperature = ( TextView ) findViewById ( R . id . batteryTempText ) ; animation = new ScaleAnimation ( , , , , ScaleAnimation . RELATIVE_TO_SELF , , ScaleAnimation . RELATIVE_TO_SELF , ) ; animation . setDuration ( ) ; animation . setFillAfter ( true ) ; animation . setStartOffset ( ) ; animation . setRepeatCount ( ) ; animation . setRepeatMode ( Animation . REVERSE ) ; if ( this . application . startupCheckPerformed == false ) { if ( this . application . settings . getLong ( "" , - ) == - ) { long t = System . currentTimeMillis ( ) / ; this . application . preferenceEditor . putLong ( "" , t ) ; } } this . application . reportStats ( - , false ) ; if ( this . application . startupCheckPerformed == false ) { this . application . startupCheckPerformed = true ; String regId = C2DMessaging . getRegistrationId ( this ) ; boolean registered = this . application . settings . getBoolean ( "" , false ) ; if ( ! registered || regId == null || "" . equals ( regId ) ) { Log . d ( MSG_TAG , "" ) ; C2DMessaging . register ( this , DeviceRegistrar . SENDER_ID ) ; } else { Log . d ( MSG_TAG , "" ) ; } if ( ! this . application . coretask . isNetfilterSupported ( ) ) { this . openNoNetfilterDialog ( ) ; this . application . accessControlSupported = false ; this . application . whitelist . remove ( ) ; } else { if ( ! this . application . coretask . isAccessControlSupported ( ) ) { if ( this . application . settings . getBoolean ( "" , false ) == false ) { this . openNoAccessControlDialog ( ) ; this . application . preferenceEditor . putBoolean ( "" , true ) ; this . application . preferenceEditor . commit ( ) ; } this . application . accessControlSupported = false ; this . application . whitelist . remove ( ) ; } } if ( this . application . binariesExists ( ) == false || this . application . coretask . filesetOutdated ( ) ) { if ( this . application . coretask . hasRootPermission ( ) ) { this . application . installFiles ( ) ; } } this . openDonateDialog ( ) ; this . application . checkForUpdate ( ) ; } if ( ! this . application . coretask . hasRootPermission ( ) ) openLaunchedDialog ( true ) ; this . rssReader = new RSSReader ( getApplicationContext ( ) , TetherApplication . FORUM_RSS_URL ) ; this . rssView = ( ListView ) findViewById ( R . id . RSSView ) ; this . rssAdapter = new ArrayAdapter < Spanned > ( this , R . layout . rss_item ) ; this . rssView . setAdapter ( this . rssAdapter ) ; this . rssView . setOnItemClickListener ( new OnItemClickListener ( ) { public void onItemClick ( AdapterView < ? > parent , View view , int position , long id ) { Log . d ( MSG_TAG , parent + "" + view + "" + position + "" + id ) ; MainActivity . this . application . statRSSClicks ( ) ; String url = null ; try { url = MainActivity . this . jsonRssArray . getJSONObject ( position ) . getString ( "" ) ; } catch ( JSONException e ) { url = TetherApplication . FORUM_URL ; } url = tagURL ( url , "" , "" , "" ) ; Intent viewRssLink = new Intent ( Intent . ACTION_VIEW ) . setData ( Uri . parse ( url ) ) ; try { startActivity ( viewRssLink ) ; } catch ( ActivityNotFoundException e ) { url = tagURL ( TetherApplication . FORUM_URL , "" , "" , "" ) ; viewRssLink = new Intent ( Intent . ACTION_VIEW ) . setData ( Uri . parse ( url ) ) ; try { startActivity ( viewRssLink ) ; } catch ( ActivityNotFoundException e2 ) { e2 . printStackTrace ( ) ; } } } } ) ; this . rssPanel = ( Panel ) findViewById ( R . id . RSSPanel ) ; this . rssPanel . setInterpolator ( new BounceInterpolator ( ) ) ; this . rssPanel . setOnPanelListener ( new OnPanelListener ( ) { public void onPanelClosed ( Panel panel ) { hideCommunityText ( true ) ; MainActivity . this . application . preferenceEditor . putBoolean ( "" , true ) . commit ( ) ; } public void onPanelOpened ( Panel panel ) { hideCommunityText ( false ) ; MainActivity . this . application . preferenceEditor . putBoolean ( "" , false ) . commit ( ) ; } } ) ; this . communityText = ( TextView ) findViewById ( R . id . communityHeader ) ; this . communityText . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View v ) { MainActivity . this . rssPanel . setOpen ( ! MainActivity . this . rssPanel . isOpen ( ) , true ) ; } } ) ; hideCommunityText ( ! this . rssPanel . isOpen ( ) ) ; this . bottomButtonLayout = ( LinearLayout ) findViewById ( R . id . bottomButtonLayout ) ; ( ( Button ) findViewById ( R . id . anchorLinkButton ) ) . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View v ) { startGooglePlayMeshclient ( "" ) ; } } ) ; ( ( Button ) findViewById ( R . id . configButton ) ) . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View v ) { startActivityForResult ( new Intent ( MainActivity . this , SetupActivity . class ) . setAction ( "" ) , ) ; } } ) ; this . startBtn = ( ImageView ) findViewById ( R . id . startTetherBtn ) ; this . startBtnListener = new OnClickListener ( ) { public void onClick ( View v ) { Log . d ( MSG_TAG , "" ) ; new Thread ( new Runnable ( ) { public void run ( ) { Intent intent = new Intent ( TetherService . INTENT_MANAGE ) ; intent . putExtra ( "" , TetherService . MANAGE_START ) ; Log . d ( MSG_TAG , "" + intent ) ; MainActivity . this . sendBroadcast ( intent ) ; } } ) . start ( ) ; } } ; this . startBtn . setOnClickListener ( this . startBtnListener ) ; this . stopBtn = ( ImageView ) findViewById ( R . id . stopTetherBtn ) ; this . stopBtnListener = new OnClickListener ( ) { public void onClick ( View v ) { Log . d ( MSG_TAG , "" ) ; if ( MainActivity . this . lockBtn . isChecked ( ) ) { Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . displayToastMessage ( getString ( R . string . main_activity_locked ) ) ; return ; } new Thread ( new Runnable ( ) { public void run ( ) { Intent intent = new Intent ( TetherService . INTENT_MANAGE ) ; intent . setAction ( TetherService . INTENT_MANAGE ) ; intent . putExtra ( "" , TetherService . MANAGE_STOP ) ; Log . d ( MSG_TAG , "" + intent ) ; MainActivity . this . sendBroadcast ( intent ) ; } } ) . start ( ) ; } } ; this . stopBtn . setOnClickListener ( this . stopBtnListener ) ; this . lockBtn = ( CompoundButton ) findViewById ( R . id . lockButton ) ; this . lockBtnListener = new OnCheckedChangeListener ( ) { public void onCheckedChanged ( CompoundButton buttonView , boolean isChecked ) { Log . d ( MSG_TAG , "" ) ; } } ; this . lockBtn . setOnCheckedChangeListener ( this . lockBtnListener ) ; this . toggleStartStop ( ) ; } @ Override public boolean onTrackballEvent ( MotionEvent event ) { if ( event . getAction ( ) == MotionEvent . ACTION_DOWN ) { Log . d ( MSG_TAG , "" ) ; String tetherStatus = this . application . coretask . getProp ( "" ) ; if ( ! tetherStatus . equals ( "" ) ) { new AlertDialog . Builder ( this ) . setMessage ( getString ( R . string . main_activity_trackball_pressed_start ) ) . setPositiveButton ( getString ( R . string . main_activity_confirm ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int which ) { Log . d ( MSG_TAG , "" ) ; MainActivity . currentInstance . startBtnListener . onClick ( MainActivity . currentInstance . startBtn ) ; } } ) . setNegativeButton ( getString ( R . string . main_activity_cancel ) , null ) . show ( ) ; } else { if ( MainActivity . this . lockBtn . isChecked ( ) ) { Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . displayToastMessage ( getString ( R . string . main_activity_locked ) ) ; return false ; } new AlertDialog . Builder ( this ) . setMessage ( getString ( R . string . main_activity_trackball_pressed_stop ) ) . setPositiveButton ( getString ( R . string . main_activity_confirm ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int which ) { Log . d ( MSG_TAG , "" ) ; MainActivity . currentInstance . stopBtnListener . onClick ( MainActivity . currentInstance . startBtn ) ; } } ) . setNegativeButton ( getString ( R . string . main_activity_cancel ) , null ) . show ( ) ; } } return true ; } public void onStop ( ) { Log . d ( MSG_TAG , "" ) ; super . onStop ( ) ; } public void onDestroy ( ) { Log . d ( MSG_TAG , "" ) ; super . onDestroy ( ) ; } public void onPause ( ) { Log . d ( MSG_TAG , "" ) ; try { unregisterReceiver ( this . intentReceiver ) ; } catch ( Exception ex ) { ; } super . onPause ( ) ; } protected void onNewIntent ( Intent intent ) { Log . d ( MSG_TAG , "" + intent ) ; setIntent ( intent ) ; } public void onResume ( ) { Log . d ( MSG_TAG , "" ) ; Log . d ( MSG_TAG , "" + this . application . settings . getBoolean ( "" , false ) ) ; try { if ( getIntent ( ) . getData ( ) . getPath ( ) . equals ( "" ) ) { setIntent ( null ) ; openLaunchedDialog ( false ) ; } } catch ( Exception e ) { } this . showRadioMode ( ) ; super . onResume ( ) ; this . intentFilter = new IntentFilter ( ) ; if ( this . application . settings . getString ( "" , "" ) . equals ( "" ) == false ) { this . intentFilter . addAction ( Intent . ACTION_BATTERY_CHANGED ) ; this . batteryTemperatureLayout . setVisibility ( View . VISIBLE ) ; } else { this . batteryTemperatureLayout . setVisibility ( View . INVISIBLE ) ; } this . intentFilter . addAction ( TetherService . INTENT_TRAFFIC ) ; this . intentFilter . addAction ( TetherService . INTENT_STATE ) ; this . intentFilter . addAction ( RSSReader . MESSAGE_JSON_RSS ) ; this . intentFilter . addAction ( TetherApplication . MESSAGE_POST_STATS ) ; registerReceiver ( this . intentReceiver , this . intentFilter ) ; this . toggleStartStop ( ) ; if ( this . stopTblRow . getVisibility ( ) == View . VISIBLE && this . application . settings . getBoolean ( "" , true ) == false ) { this . lockButtonCheckbox . setVisibility ( View . VISIBLE ) ; } else { this . lockButtonCheckbox . setVisibility ( View . GONE ) ; } this . rssPanel . setOpen ( ! this . application . settings . getBoolean ( "" , false ) , true ) ; hideCommunityText ( ! this . rssPanel . isOpen ( ) ) ; this . rssReader . readRSS ( ) ; } private static final int MENU_SETUP = ; private static final int MENU_LOG = ; private static final int MENU_ABOUT = ; private static final int MENU_ACCESS = ; private static final int MENU_CONNECT = ; private static final int MENU_COMMUNITY = ; @ Override public boolean onCreateOptionsMenu ( Menu menu ) { boolean supRetVal = super . onCreateOptionsMenu ( menu ) ; SubMenu setup = menu . addSubMenu ( , MENU_SETUP , , getString ( R . string . main_activity_settings ) ) ; setup . setIcon ( drawable . ic_menu_preferences ) ; if ( this . application . accessControlSupported ) { SubMenu accessctr = menu . addSubMenu ( , MENU_ACCESS , , getString ( R . string . main_activity_accesscontrol ) ) ; accessctr . setIcon ( drawable . ic_menu_manage ) ; } SubMenu connect = menu . addSubMenu ( , MENU_CONNECT , , getString ( R . string . main_activity_connect ) ) ; connect . setIcon ( drawable . ic_menu_add ) ; SubMenu log = menu . addSubMenu ( , MENU_LOG , , getString ( R . string . main_activity_showlog ) ) ; log . setIcon ( drawable . ic_menu_agenda ) ; SubMenu community = menu . addSubMenu ( , MENU_COMMUNITY , , getString ( R . string . main_activity_community ) ) ; community . setIcon ( drawable . ic_menu_myplaces ) ; SubMenu about = menu . addSubMenu ( , MENU_ABOUT , , getString ( R . string . main_activity_about ) ) ; about . setIcon ( drawable . ic_menu_info_details ) ; return supRetVal ; } @ Override public boolean onOptionsItemSelected ( MenuItem menuItem ) { boolean supRetVal = super . onOptionsItemSelected ( menuItem ) ; Log . d ( MSG_TAG , "" + menuItem . getItemId ( ) ) ; switch ( menuItem . getItemId ( ) ) { case MENU_SETUP : startActivityForResult ( new Intent ( MainActivity . this , SetupActivity . class ) , ) ; break ; case MENU_LOG : startActivityForResult ( new Intent ( MainActivity . this , LogActivity . class ) , ) ; break ; case MENU_ABOUT : this . openAboutDialog ( ) ; break ; case MENU_ACCESS : startActivityForResult ( new Intent ( MainActivity . this , AccessControlActivity . class ) , ) ; break ; case MENU_CONNECT : startActivity ( new Intent ( MainActivity . this , ConnectActivity . class ) ) ; break ; case MENU_COMMUNITY : this . application . statCommunityClicks ( ) ; startActivity ( new Intent ( Intent . ACTION_VIEW , Uri . parse ( getString ( R . string . communityUrl ) ) ) ) ; break ; } return supRetVal ; } @ Override protected Dialog onCreateDialog ( int id ) { if ( id == ID_DIALOG_STARTING ) { progressDialog = new ProgressDialog ( this ) ; progressDialog . setTitle ( getString ( R . string . main_activity_start ) ) ; progressDialog . setMessage ( getString ( R . string . main_activity_start_summary ) ) ; progressDialog . setIndeterminate ( false ) ; progressDialog . setCancelable ( true ) ; return progressDialog ; } else if ( id == ID_DIALOG_STOPPING ) { progressDialog = new ProgressDialog ( this ) ; progressDialog . setTitle ( getString ( R . string . main_activity_stop ) ) ; progressDialog . setMessage ( getString ( R . string . main_activity_stop_summary ) ) ; progressDialog . setIndeterminate ( false ) ; progressDialog . setCancelable ( true ) ; return progressDialog ; } return null ; } private IntentFilter intentFilter ; private BroadcastReceiver intentReceiver ; public Handler viewUpdateHandler ; public MainActivity ( ) { intentReceiver = new BroadcastReceiver ( ) { @ Override public void onReceive ( Context context , Intent intent ) { Log . d ( MSG_TAG , "" + intent ) ; String action = intent . getAction ( ) ; if ( action . equals ( Intent . ACTION_BATTERY_CHANGED ) ) { int temp = ( intent . getIntExtra ( "" , ) ) ; MainActivity . this . application . lastTemperature = temp ; int celsius = ( int ) ( ( temp + ) / ) ; int fahrenheit = ( int ) ( ( ( temp / ) / ) + + ) ; Log . d ( MSG_TAG , "" + temp + "" + celsius + "" + fahrenheit ) ; if ( MainActivity . this . application . settings . getString ( "" , "" ) . equals ( "" ) ) { batteryTemperature . setText ( "" + celsius + getString ( R . string . main_activity_temperatureunit_celsius ) ) ; } else { batteryTemperature . setText ( "" + fahrenheit + getString ( R . string . main_activity_temperatureunit_fahrenheit ) ) ; } } else { if ( action . equals ( TetherService . INTENT_TRAFFIC ) ) updateTrafficDisplay ( intent . getLongArrayExtra ( "" ) ) ; if ( action . equals ( TetherService . INTENT_STATE ) ) { Log . d ( MSG_TAG , "" + intent . getIntExtra ( "" , ) ) ; try { switch ( intent . getIntExtra ( "" , TetherService . STATE_IDLE ) ) { case TetherService . STATE_RESTARTING : try { MainActivity . this . dismissDialog ( MainActivity . ID_DIALOG_STOPPING ) ; } catch ( Exception e ) { } break ; case TetherService . STATE_STARTING : MainActivity . this . showDialog ( MainActivity . ID_DIALOG_STARTING ) ; break ; case TetherService . STATE_RUNNING : try { MainActivity . this . dismissDialog ( MainActivity . ID_DIALOG_STARTING ) ; } catch ( Exception e ) { } MainActivity . this . toggleStartStop ( ) ; break ; case TetherService . STATE_STOPPING : MainActivity . this . showDialog ( MainActivity . ID_DIALOG_STOPPING ) ; break ; case TetherService . STATE_IDLE : try { MainActivity . this . dismissDialog ( MainActivity . ID_DIALOG_STOPPING ) ; } catch ( Exception e ) { } MainActivity . this . toggleStartStop ( ) ; break ; case TetherService . STATE_FAIL_LOG : try { MainActivity . this . dismissDialog ( MainActivity . ID_DIALOG_STARTING ) ; } catch ( Exception e ) { } MainActivity . this . application . displayToastMessage ( getString ( R . string . main_activity_start_errors ) ) ; MainActivity . this . toggleStartStop ( ) ; break ; case TetherService . STATE_FAIL_EXEC_START : try { MainActivity . this . dismissDialog ( MainActivity . ID_DIALOG_STARTING ) ; } catch ( Exception e ) { } MainActivity . this . application . displayToastMessage ( getString ( R . string . main_activity_start_unable ) ) ; MainActivity . this . toggleStartStop ( ) ; break ; case TetherService . STATE_FAIL_EXEC_STOP : try { MainActivity . this . dismissDialog ( MainActivity . ID_DIALOG_STOPPING ) ; } catch ( Exception e ) { } MainActivity . this . toggleStartStop ( ) ; break ; } } catch ( Exception e ) { } finally { } } else if ( action . equals ( RSSReader . MESSAGE_JSON_RSS ) ) { updateRSSView ( intent . getStringExtra ( RSSReader . EXTRA_JSON_RSS ) ) ; } } } } ; viewUpdateHandler = new Handler ( ) { public void handleMessage ( Message msg ) { Log . d ( MSG_TAG , "" + msg ) ; switch ( msg . what ) { case MESSAGE_CHECK_LOG : Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . displayToastMessage ( getString ( R . string . main_activity_start_errors ) ) ; MainActivity . this . toggleStartStop ( ) ; break ; case MESSAGE_CANT_START_TETHER : Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . displayToastMessage ( getString ( R . string . main_activity_start_unable ) ) ; MainActivity . this . toggleStartStop ( ) ; break ; case MESSAGE_TRAFFIC_START : MainActivity . this . trafficRow . setVisibility ( View . VISIBLE ) ; break ; case MESSAGE_TRAFFIC_COUNT : MainActivity . this . trafficRow . setVisibility ( View . VISIBLE ) ; long uploadTraffic = ( ( TetherService . DataCount ) msg . obj ) . totalUpload ; long downloadTraffic = ( ( TetherService . DataCount ) msg . obj ) . totalDownload ; long uploadRate = ( ( TetherService . DataCount ) msg . obj ) . uploadRate ; long downloadRate = ( ( TetherService . DataCount ) msg . obj ) . downloadRate ; if ( uploadRate < ) uploadRate = ; if ( downloadRate < ) downloadRate = ; MainActivity . this . uploadText . setText ( MainActivity . this . formatCount ( uploadTraffic , false ) ) ; MainActivity . this . downloadText . setText ( MainActivity . this . formatCount ( downloadTraffic , false ) ) ; MainActivity . this . downloadText . invalidate ( ) ; MainActivity . this . uploadText . invalidate ( ) ; MainActivity . this . uploadRateText . setText ( MainActivity . this . formatCount ( uploadRate , true ) ) ; MainActivity . this . downloadRateText . setText ( MainActivity . this . formatCount ( downloadRate , true ) ) ; MainActivity . this . downloadRateText . invalidate ( ) ; MainActivity . this . uploadRateText . invalidate ( ) ; break ; case MESSAGE_TRAFFIC_END : MainActivity . this . trafficRow . setVisibility ( View . INVISIBLE ) ; break ; case MESSAGE_DOWNLOAD_STARTING : Log . d ( MSG_TAG , "" ) ; MainActivity . this . progressBar . setIndeterminate ( true ) ; MainActivity . this . progressTitle . setText ( ( String ) msg . obj ) ; MainActivity . this . progressText . setText ( "" ) ; MainActivity . this . downloadUpdateLayout . setVisibility ( View . VISIBLE ) ; break ; case MESSAGE_DOWNLOAD_PROGRESS : MainActivity . this . progressBar . setIndeterminate ( false ) ; MainActivity . this . progressText . setText ( msg . arg1 + "" + msg . arg2 + "" ) ; MainActivity . this . progressBar . setProgress ( msg . arg1 * / msg . arg2 ) ; break ; case MESSAGE_DOWNLOAD_COMPLETE : Log . d ( MSG_TAG , "" ) ; MainActivity . this . progressText . setText ( "" ) ; MainActivity . this . progressTitle . setText ( "" ) ; MainActivity . this . downloadUpdateLayout . setVisibility ( View . GONE ) ; break ; case MESSAGE_DOWNLOAD_BLUETOOTH_COMPLETE : Log . d ( MSG_TAG , "" ) ; MainActivity . this . startBtn . setClickable ( true ) ; MainActivity . this . radioModeLabel . setText ( "" ) ; break ; case MESSAGE_DOWNLOAD_BLUETOOTH_FAILED : Log . d ( MSG_TAG , "" ) ; MainActivity . this . startBtn . setClickable ( true ) ; MainActivity . this . application . preferenceEditor . putBoolean ( "" , false ) ; MainActivity . this . application . preferenceEditor . commit ( ) ; MainActivity . this . application . displayToastMessage ( "" ) ; default : MainActivity . this . toggleStartStop ( ) ; } super . handleMessage ( msg ) ; } } ; } private synchronized void updateRSSView ( String JSONrss ) { Log . d ( MSG_TAG , "" + JSONrss ) ; try { this . rssAdapter . clear ( ) ; this . rssAdapter . notifyDataSetChanged ( ) ; this . jsonRssArray = new JSONArray ( JSONrss ) ; for ( int i = ; i < jsonRssArray . length ( ) ; i ++ ) { JSONObject jsonRssItem = jsonRssArray . getJSONObject ( i ) ; this . rssAdapter . add ( Html . fromHtml ( jsonRssItem . getString ( "" ) + "" + jsonRssItem . getString ( "" ) + "" ) ) ; } if ( jsonRssArray . length ( ) > && ! this . application . settings . getBoolean ( "" , false ) ) this . rssPanel . setOpen ( true , true ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } } private void updateTrafficDisplay ( long [ ] trafficData ) { MainActivity . this . trafficRow . setVisibility ( View . VISIBLE ) ; long uploadTraffic = trafficData [ ] ; long downloadTraffic = trafficData [ ] ; long uploadRate = trafficData [ ] ; long downloadRate = trafficData [ ] ; if ( uploadRate < ) uploadRate = ; if ( downloadRate < ) downloadRate = ; MainActivity . this . uploadText . setText ( MainActivity . this . formatCount ( uploadTraffic , false ) ) ; MainActivity . this . downloadText . setText ( MainActivity . this . formatCount ( downloadTraffic , false ) ) ; MainActivity . this . downloadText . invalidate ( ) ; MainActivity . this . uploadText . invalidate ( ) ; MainActivity . this . uploadRateText . setText ( MainActivity . this . formatCount ( uploadRate , true ) ) ; MainActivity . this . downloadRateText . setText ( MainActivity . this . formatCount ( downloadRate , true ) ) ; MainActivity . this . downloadRateText . invalidate ( ) ; MainActivity . this . uploadRateText . invalidate ( ) ; } private void toggleStartStop ( ) { if ( ( TetherService . singleton != null ) && ( ( TetherService . singleton . getState ( ) == TetherService . STATE_RUNNING ) || ( TetherService . singleton . getState ( ) == TetherService . STATE_FAIL_LOG ) || ( TetherService . singleton . getState ( ) == TetherService . STATE_STOPPING ) ) ) { Log . d ( MSG_TAG , "" ) ; this . startTblRow . setVisibility ( View . GONE ) ; this . stopTblRow . setVisibility ( View . VISIBLE ) ; this . bottomButtonLayout . setVisibility ( View . INVISIBLE ) ; if ( this . animation != null ) this . stopBtn . startAnimation ( this . animation ) ; this . application . showStartNotification ( getString ( R . string . global_application_tethering_running ) ) ; if ( MainActivity . this . application . settings . getBoolean ( "" , true ) == false ) { MainActivity . this . lockButtonCheckbox . setVisibility ( View . VISIBLE ) ; } } else if ( ( TetherService . singleton == null ) || ( TetherService . singleton . getState ( ) == TetherService . STATE_IDLE ) || ( TetherService . singleton . getState ( ) == TetherService . STATE_STARTING ) || ( TetherService . singleton . getState ( ) == TetherService . STATE_RESTARTING ) || ( TetherService . singleton . getState ( ) == TetherService . STATE_FAIL_EXEC_START ) || ( TetherService . singleton . getState ( ) == TetherService . STATE_FAIL_EXEC_STOP ) ) { Log . d ( MSG_TAG , "" ) ; this . startTblRow . setVisibility ( View . VISIBLE ) ; this . stopTblRow . setVisibility ( View . GONE ) ; this . trafficRow . setVisibility ( View . INVISIBLE ) ; this . bottomButtonLayout . setVisibility ( View . VISIBLE ) ; if ( this . animation != null ) this . startBtn . startAnimation ( this . animation ) ; this . application . notificationManager . cancelAll ( ) ; MainActivity . this . lockButtonCheckbox . setVisibility ( View . GONE ) ; } else { Log . d ( MSG_TAG , "" ) ; this . startTblRow . setVisibility ( View . VISIBLE ) ; this . stopTblRow . setVisibility ( View . VISIBLE ) ; MainActivity . this . application . displayToastMessage ( getString ( R . string . main_activity_start_unknownstate ) ) ; } this . showRadioMode ( ) ; System . gc ( ) ; } static String formatCount ( long count , boolean rate ) { if ( count < * ) return ( ( float ) ( ( int ) ( count * / ) ) / + ( rate ? "" : "" ) ) ; return ( ( float ) ( ( int ) ( count * / / ) ) / + ( rate ? "" : "" ) ) ; } static String formatCountForPost ( long count ) { if ( count < * ) return ( ( float ) ( ( int ) ( count * / ) ) / + ( "" ) ) ; return ( ( float ) ( ( int ) ( count * / / ) ) / + ( "" ) ) ; } private void openNoNetfilterDialog ( ) { LayoutInflater li = LayoutInflater . from ( this ) ; View view = li . inflate ( R . layout . nonetfilterview , null ) ; new AlertDialog . Builder ( MainActivity . this ) . setTitle ( getString ( R . string . main_activity_nonetfilter ) ) . setView ( view ) . setNegativeButton ( getString ( R . string . main_activity_exit ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; MainActivity . this . finish ( ) ; } } ) . setNeutralButton ( getString ( R . string . main_activity_ignore ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . displayToastMessage ( "" ) ; } } ) . show ( ) ; } private void openNoAccessControlDialog ( ) { LayoutInflater li = LayoutInflater . from ( this ) ; View view = li . inflate ( R . layout . noaccesscontrolview , null ) ; new AlertDialog . Builder ( MainActivity . this ) . setTitle ( getString ( R . string . main_activity_noaccesscontrol ) ) . setView ( view ) . setNeutralButton ( getString ( R . string . main_activity_ok ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . displayToastMessage ( getString ( R . string . main_activity_accesscontrol_disabled ) ) ; } } ) . show ( ) ; } private void openAboutDialog ( ) { LayoutInflater li = LayoutInflater . from ( this ) ; View view = li . inflate ( R . layout . aboutview , null ) ; TextView versionName = ( TextView ) view . findViewById ( R . id . versionName ) ; versionName . setText ( this . application . getVersionName ( ) ) ; new AlertDialog . Builder ( MainActivity . this ) . setTitle ( getString ( R . string . main_activity_about ) ) . setView ( view ) . setNeutralButton ( getString ( R . string . main_activity_donate ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . preferenceEditor . putBoolean ( "" , false ) ; MainActivity . this . application . preferenceEditor . commit ( ) ; Uri uri = Uri . parse ( getString ( R . string . paypalUrl ) ) ; startActivity ( new Intent ( Intent . ACTION_VIEW , uri ) ) ; } } ) . setNegativeButton ( getString ( R . string . main_activity_close ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; } } ) . show ( ) ; } private void openDonateDialog ( ) { if ( this . application . showDonationDialog ( ) ) { LayoutInflater li = LayoutInflater . from ( this ) ; View view = li . inflate ( R . layout . donateview , null ) ; new AlertDialog . Builder ( MainActivity . this ) . setTitle ( getString ( R . string . main_activity_donate ) ) . setView ( view ) . setNeutralButton ( getString ( R . string . main_activity_close ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; } } ) . setNegativeButton ( getString ( R . string . main_activity_donate ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . preferenceEditor . putBoolean ( "" , false ) ; MainActivity . this . application . preferenceEditor . commit ( ) ; Uri uri = Uri . parse ( getString ( R . string . paypalUrl ) ) ; startActivity ( new Intent ( Intent . ACTION_VIEW , uri ) ) ; } } ) . show ( ) ; } } private void showRadioMode ( ) { boolean usingBluetooth = this . application . settings . getBoolean ( "" , false ) ; if ( usingBluetooth ) { this . radioModeImage . setImageResource ( R . drawable . bluetooth ) ; } else { this . radioModeImage . setImageResource ( R . drawable . wifi ) ; } } public void openUpdateDialog ( final String downloadFileUrl , final String fileName , final String message , final String updateTitle ) { LayoutInflater li = LayoutInflater . from ( this ) ; Builder dialog ; View view ; view = li . inflate ( R . layout . updateview , null ) ; TextView messageView = ( TextView ) view . findViewById ( R . id . updateMessage ) ; TextView updateNowText = ( TextView ) view . findViewById ( R . id . updateNowText ) ; if ( fileName . length ( ) == ) updateNowText . setVisibility ( View . GONE ) ; messageView . setText ( message ) ; dialog = new AlertDialog . Builder ( MainActivity . this ) . setTitle ( updateTitle ) . setView ( view ) ; if ( fileName . length ( ) > ) { dialog . setNeutralButton ( getString ( R . string . main_activity_no ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; } } ) ; dialog . setNegativeButton ( getString ( R . string . main_activity_yes ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; MainActivity . this . application . downloadUpdate ( downloadFileUrl , fileName ) ; } } ) ; } else dialog . setNeutralButton ( getString ( R . string . main_activity_ok ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int whichButton ) { Log . d ( MSG_TAG , "" ) ; } } ) ; dialog . show ( ) ; } public Dialog openLaunchedDialog ( final boolean noroot ) { final long value = noroot ? : ; EasyTracker . getTracker ( ) . trackEvent ( "" , "" , "" , value ) ; Dialog dialog = new AlertDialog . Builder ( this ) . setMessage ( noroot ? R . string . dialog_noroot_text : R . string . dialog_launched_text ) . setTitle ( getString ( R . string . dialog_launched_title ) ) . setIcon ( R . drawable . og_app_icon ) . setCancelable ( false ) . setOnKeyListener ( new DialogInterface . OnKeyListener ( ) { public boolean onKey ( DialogInterface dialog , int keyCode , KeyEvent event ) { if ( keyCode == KeyEvent . KEYCODE_BACK ) MainActivity . this . finish ( ) ; if ( keyCode < KeyEvent . KEYCODE_DPAD_UP || keyCode > KeyEvent . KEYCODE_DPAD_CENTER ) return true ; else return false ; } } ) . setPositiveButton ( getString ( R . string . main_activity_ok ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int id ) { EasyTracker . getTracker ( ) . trackEvent ( "" , "" , "" , value ) ; startGooglePlayMeshclient ( noroot ? "" : "" ) ; } } ) . setNegativeButton ( getString ( R . string . main_activity_cancel ) , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int id ) { EasyTracker . getTracker ( ) . trackEvent ( "" , "" , "" , value ) ; } } ) . create ( ) ; dialog . show ( ) ; return dialog ; } void startGooglePlayMeshclient ( String content ) { Log . d ( MSG_TAG , "" ) ; Intent meshclientInstall = new Intent ( Intent . ACTION_VIEW ) . setData ( Uri . parse ( TetherApplication . MESHCLIENT_GOOGLE_PLAY_URL + content ) ) ; startActivity ( meshclientInstall ) ; } private void hideCommunityText ( boolean hide ) { if ( hide ) { MainActivity . this . communityText . setText ( String . format ( "" + this . communityText . getText ( ) . length ( ) + "" , "" ) ) ; } else MainActivity . this . communityText . setText ( R . string . community_header ) ; } } package og . android . tether ; import android . content . BroadcastReceiver ; import android . content . Context ; import android . content . ComponentName ; import android . content . Intent ; import android . util . Log ; public class TetherServiceReceiver extends BroadcastReceiver { static final String MSG_TAG = "" ; @ Override public void onReceive ( Context contextArg , Intent intentArg ) { Log . d ( MSG_TAG , "" + intentArg + "" + intentArg . getIntExtra ( "" , - ) ) ; if ( intentArg . getAction ( ) . equals ( TetherService . INTENT_MANAGE ) ) { switch ( intentArg . getIntExtra ( "" , TetherService . MANAGE_START ) ) { case TetherService . MANAGE_START : if ( TetherService . singleton == null ) contextArg . startService ( new Intent ( contextArg , TetherService . class ) ) ; else sendBroadcastManage ( contextArg , TetherService . MANAGE_STARTED ) ; break ; case TetherService . MANAGE_STARTED : if ( ( TetherService . singleton != null ) && ( TetherService . singleton . getState ( ) != TetherService . STATE_STARTING ) && ( TetherService . singleton . getState ( ) != TetherService . STATE_RESTARTING ) ) TetherService . singleton . startTether ( ) ; break ; case TetherService . MANAGE_STOP : if ( ( TetherService . singleton != null ) && ( TetherService . singleton . getState ( ) != TetherService . STATE_STOPPING ) ) TetherService . singleton . stopTether ( ) ; break ; case TetherService . MANAGE_STOPPED : if ( TetherService . singleton != null ) TetherService . singleton . stopSelf ( ) ; break ; default : break ; } } else if ( intentArg . getAction ( ) . equals ( TetherService . INTENT_STATE ) ) { int serviceState = intentArg . getIntExtra ( "" , - ) ; switch ( serviceState ) { case TetherService . STATE_RUNNING : case TetherService . STATE_FAIL_EXEC_START : case TetherService . STATE_FAIL_EXEC_STOP : case TetherService . STATE_FAIL_LOG : case TetherService . STATE_IDLE : break ; } } } void sendBroadcastManage ( Context context , int state ) { Intent intent = new Intent ( TetherService . INTENT_MANAGE ) ; intent . putExtra ( "" , state ) ; Log . d ( MSG_TAG , "" + state ) ; context . sendBroadcast ( intent ) ; } } package og . android . tether ; import android . app . Activity ; import android . content . Intent ; import android . os . Bundle ; import android . os . Looper ; import android . util . Log ; import com . facebook . android . DialogError ; import com . facebook . android . Facebook ; import com . facebook . android . Facebook . DialogListener ; import com . facebook . android . FacebookError ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . MalformedURLException ; import org . json . JSONException ; import org . json . JSONObject ; public class FBManager { private static final String TAG = "" ; private static final String FACEBOOK_APP_ID = "" ; public static final String MESSAGE_FB_CONNECTED = "" ; private Facebook mFacebook ; private TetherApplication mApplication ; FBManager ( TetherApplication application ) { mApplication = application ; mFacebook = new Facebook ( FACEBOOK_APP_ID ) ; } public void connectToFacebook ( final Activity activity ) { new Thread ( new Runnable ( ) { public void run ( ) { Log . d ( TAG , "" ) ; Looper . prepare ( ) ; mFacebook . authorize ( activity , new String [ ] { "" , "" } , new FacebookConnectListener ( activity ) ) ; Looper . loop ( ) ; } } ) . start ( ) ; } public void postToFacebookWithAuthorize ( final Activity activity , final Bundle params , final OnPostCompleteListener listener ) { new Thread ( new Runnable ( ) { public void run ( ) { Log . d ( TAG , "" ) ; Looper . prepare ( ) ; mFacebook . authorize ( activity , new String [ ] { "" , "" } , new FacebookPostListener ( activity , params , listener ) ) ; Looper . loop ( ) ; } } ) . start ( ) ; } public void postToFacebook ( final Bundle params , final OnPostCompleteListener listener ) { new Thread ( new Runnable ( ) { public void run ( ) { Looper . prepare ( ) ; Log . d ( TAG , "" ) ; String result = postToFacebook ( params ) ; if ( listener != null ) listener . onPostComplete ( result ) ; Looper . loop ( ) ; } } ) . start ( ) ; } private String postToFacebook ( Bundle params ) { String result = null ; try { result = FBManager . this . mFacebook . request ( "" , params , "" ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } Log . d ( TAG , "" + result ) ; if ( result == null ) return "" ; try { JSONObject resultInfo = new JSONObject ( result ) ; if ( resultInfo . has ( "" ) ) { result = "" ; mApplication . statFBPostOk ( ) ; } else if ( resultInfo . has ( "" ) ) { result = "" ; mApplication . statFBPostError ( ) ; resultInfo = resultInfo . getJSONObject ( "" ) ; if ( resultInfo . getString ( "" ) . equals ( "" ) ) { result = "" ; } } else { result = "" ; mApplication . statFBPostError ( ) ; } } catch ( JSONException e ) { e . printStackTrace ( ) ; } return result ; } class FacebookConnectListener implements DialogListener { private static final String TAG = "" ; private Activity mActivity ; FacebookConnectListener ( Activity activity ) { mActivity = activity ; } public void onComplete ( Bundle values ) { Log . d ( TAG , "" + values ) ; if ( values . getString ( "" ) != null ) { mApplication . preferenceEditor . putString ( "" , values . getString ( "" ) ) . commit ( ) ; Intent fbConnected = new Intent ( MESSAGE_FB_CONNECTED ) . putExtra ( "" , values . getString ( "" ) ) ; mActivity . getApplicationContext ( ) . sendBroadcast ( fbConnected ) ; mApplication . statFBConnectOk ( ) ; } } public void onFacebookError ( FacebookError error ) { Log . d ( TAG , "" + error ) ; } public void onError ( DialogError error ) { Log . d ( TAG , "" + error ) ; } public void onCancel ( ) { Log . d ( TAG , "" ) ; } } class FacebookPostListener implements DialogListener { public static final String TAG = "" ; private Activity mActivity ; private Bundle mBundle ; private OnPostCompleteListener mListener = null ; FacebookPostListener ( Activity activity , Bundle bundle ) { mActivity = activity ; mBundle = bundle ; } FacebookPostListener ( Activity activity , Bundle bundle , OnPostCompleteListener listener ) { mActivity = activity ; mBundle = bundle ; mListener = listener ; } public void onComplete ( Bundle values ) { Log . d ( TAG , "" + values ) ; if ( values . getString ( "" ) != null ) { String result = postToFacebook ( mBundle ) ; if ( mListener != null ) mListener . onPostComplete ( result ) ; mApplication . preferenceEditor . putString ( "" , values . getString ( "" ) ) . commit ( ) ; } } public void onFacebookError ( FacebookError error ) { Log . d ( TAG , "" + error ) ; } public void onError ( DialogError error ) { Log . d ( TAG , "" + error ) ; } public void onCancel ( ) { Log . d ( TAG , "" ) ; } } void authorizeCallback ( int requestCode , int resultCode , Intent data ) { mFacebook . authorizeCallback ( requestCode , resultCode , data ) ; } public void destroyDialog ( ) { mFacebook . onDestroy ( ) ; } public void extendAccessTokenIfNeeded ( android . content . Context context , com . facebook . android . Facebook . ServiceListener listener ) { mFacebook . extendAccessTokenIfNeeded ( context , listener ) ; } } abstract class OnPostCompleteListener { abstract void onPostComplete ( String result ) ; } package og . android . tether ; import com . google . analytics . tracking . android . TrackedActivity ; import android . R . drawable ; import android . app . Activity ; import android . content . BroadcastReceiver ; import android . content . Context ; import android . content . Intent ; import android . content . IntentFilter ; import android . content . SharedPreferences ; import android . os . Bundle ; import android . preference . PreferenceManager ; import android . util . Log ; import android . view . View ; import android . view . View . OnClickListener ; import android . widget . Button ; import android . widget . CheckBox ; import android . widget . CompoundButton ; import android . widget . CompoundButton . OnCheckedChangeListener ; import android . widget . EditText ; import android . widget . Toast ; public class ConnectActivity extends TrackedActivity { private static final String TAG = "" ; private SharedPreferences mPrefs ; private SharedPreferences . Editor mPrefsEdit ; private Button mConnectFacebook ; private EditText mPostEditor ; private CheckBox mAutoPost ; @ Override public void onCreate ( Bundle savedInstanceState ) { Log . d ( TAG , "" ) ; super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . connectview ) ; mPrefs = PreferenceManager . getDefaultSharedPreferences ( this ) ; mPrefsEdit = mPrefs . edit ( ) ; String message ; if ( ( message = mPrefs . getString ( "" , null ) ) == null ) { mPrefsEdit . putString ( "" , message = getString ( R . string . post_text ) ) ; mPrefsEdit . commit ( ) ; } mPostEditor = ( EditText ) findViewById ( R . id . postEditor ) ; mPostEditor . setText ( message ) ; mAutoPost = ( CheckBox ) findViewById ( R . id . autoPostCheck ) ; mAutoPost . setChecked ( mPrefs . getBoolean ( "" , true ) ) ; mAutoPost . setOnCheckedChangeListener ( new OnCheckedChangeListener ( ) { public void onCheckedChanged ( CompoundButton buttonView , boolean isChecked ) { mPrefsEdit . putBoolean ( "" , isChecked ) ; mPrefsEdit . commit ( ) ; } } ) ; mConnectFacebook = ( Button ) findViewById ( R . id . connectFacebook ) ; if ( mPrefs . getBoolean ( "" , false ) ) { mConnectFacebook . setText ( getString ( R . string . facebook_connected ) ) ; ConnectActivity . this . mConnectFacebook . setCompoundDrawablesWithIntrinsicBounds ( R . drawable . connect_facebook , , drawable . checkbox_on_background , ) ; } mConnectFacebook . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View view ) { Log . d ( TAG , "" + view ) ; if ( mPrefs . getBoolean ( "" , false ) ) { mConnectFacebook . setText ( getString ( R . string . connect_facebook ) ) ; ConnectActivity . this . mConnectFacebook . setCompoundDrawablesWithIntrinsicBounds ( R . drawable . connect_facebook , , drawable . ic_menu_add , ) ; mPrefsEdit . putBoolean ( "" , false ) . commit ( ) ; Toast . makeText ( getApplicationContext ( ) , "" , Toast . LENGTH_LONG ) . show ( ) ; } else { ( ( TetherApplication ) getApplication ( ) ) . statFBConnectRequest ( ) ; if ( ( ( TetherApplication ) getApplication ( ) ) . FBManager == null ) ( ( TetherApplication ) getApplication ( ) ) . FBManager = new FBManager ( ( TetherApplication ) getApplication ( ) ) ; ( ( TetherApplication ) getApplication ( ) ) . FBManager . connectToFacebook ( ConnectActivity . this ) ; } } } ) ; } private BroadcastReceiver mReceiver = new BroadcastReceiver ( ) { @ Override public void onReceive ( Context context , Intent intent ) { Log . d ( TAG , "" + intent . getAction ( ) + "" + intent ) ; String action = intent . getAction ( ) ; if ( action . equals ( FBManager . MESSAGE_FB_CONNECTED ) ) { Toast . makeText ( getApplicationContext ( ) , "" , Toast . LENGTH_LONG ) . show ( ) ; ConnectActivity . this . mConnectFacebook . setText ( getString ( R . string . facebook_connected ) ) ; ConnectActivity . this . mConnectFacebook . setCompoundDrawablesWithIntrinsicBounds ( R . drawable . connect_facebook , , drawable . checkbox_on_background , ) ; ConnectActivity . this . mPrefsEdit . putBoolean ( "" , true ) ; ConnectActivity . this . mPrefsEdit . putBoolean ( "" , true ) ; ConnectActivity . this . mPrefsEdit . putString ( "" , intent . getStringExtra ( "" ) ) ; ConnectActivity . this . mPrefsEdit . commit ( ) ; } } } ; @ Override public void onActivityResult ( int requestCode , int resultCode , Intent data ) { Log . d ( TAG , "" + requestCode + "" + resultCode + "" + data ) ; super . onActivityResult ( requestCode , resultCode , data ) ; if ( ( ( TetherApplication ) getApplication ( ) ) . FBManager != null ) ( ( TetherApplication ) getApplication ( ) ) . FBManager . authorizeCallback ( requestCode , resultCode , data ) ; } @ Override public void onResume ( ) { Log . d ( TAG , "" ) ; super . onResume ( ) ; IntentFilter i = new IntentFilter ( FBManager . MESSAGE_FB_CONNECTED ) ; registerReceiver ( mReceiver , i ) ; ( ( TetherApplication ) getApplication ( ) ) . statConnectActivity ( ) ; } @ Override public void onPause ( ) { Log . d ( TAG , "" ) ; if ( ( ( TetherApplication ) getApplication ( ) ) . FBManager != null ) ( ( TetherApplication ) getApplication ( ) ) . FBManager . destroyDialog ( ) ; mPrefsEdit . putString ( "" , mPostEditor . getText ( ) . toString ( ) ) ; if ( ( ( CheckBox ) findViewById ( R . id . autoPostCheck ) ) . isChecked ( ) ) mPrefsEdit . putBoolean ( "" , true ) ; mPrefsEdit . commit ( ) ; super . onPause ( ) ; } @ Override public void onDestroy ( ) { Log . d ( TAG , "" ) ; super . onDestroy ( ) ; try { unregisterReceiver ( mReceiver ) ; } catch ( IllegalArgumentException e ) { Log . e ( TAG , "" , e ) ; } } } package og . android . tether ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Enumeration ; import java . util . Hashtable ; import com . google . analytics . tracking . android . TrackedListActivity ; import og . android . tether . R ; import og . android . tether . data . ClientData ; import og . android . tether . data . ClientAdapter ; import og . android . tether . system . CoreTask ; import android . R . drawable ; import android . app . ListActivity ; import android . os . Bundle ; import android . os . Handler ; import android . os . Looper ; import android . os . Message ; import android . util . Log ; import android . view . Menu ; import android . view . MenuItem ; import android . view . SubMenu ; import android . view . View ; import android . view . View . OnClickListener ; import android . widget . Button ; import android . widget . RelativeLayout ; import android . widget . TextView ; import android . widget . ToggleButton ; public class AccessControlActivity extends TrackedListActivity { private TetherApplication application = null ; private ToggleButton buttonAC = null ; private Button buttonApply = null ; private TextView statusAC = null ; private RelativeLayout applyFooterAC = null ; private ClientAdapter clientAdapter ; public CoreTask . Whitelist whitelist ; public static final String MSG_TAG = "" ; public static AccessControlActivity currentInstance = null ; private static void setCurrent ( AccessControlActivity current ) { AccessControlActivity . currentInstance = current ; } @ Override public void onCreate ( Bundle savedInstanceState ) { Log . d ( MSG_TAG , "" ) ; super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . accesscontrolview ) ; this . application = ( TetherApplication ) this . getApplication ( ) ; this . whitelist = this . application . whitelist ; this . statusAC = ( TextView ) findViewById ( R . id . statusAC ) ; this . applyFooterAC = ( RelativeLayout ) findViewById ( R . id . layoutFooterAC ) ; this . buttonAC = ( ToggleButton ) findViewById ( R . id . buttonAC ) ; this . buttonAC . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View v ) { if ( buttonAC . isChecked ( ) == false ) { Log . d ( MSG_TAG , "" ) ; if ( whitelist . remove ( ) ) { AccessControlActivity . this . application . displayToastMessage ( getString ( R . string . accesscontrol_activity_disabled ) ) ; AccessControlActivity . this . clientAdapter . refreshData ( AccessControlActivity . this . getCurrentClientData ( ) ) ; if ( TetherService . singleton != null ) TetherService . singleton . restartSecuredWifi ( ) ; AccessControlActivity . this . application . preferenceEditor . putBoolean ( "" , false ) ; AccessControlActivity . this . application . preferenceEditor . commit ( ) ; AccessControlActivity . this . toggleACHeader ( ) ; } } else { Log . d ( MSG_TAG , "" ) ; try { whitelist . touch ( ) ; AccessControlActivity . this . application . displayToastMessage ( getString ( R . string . accesscontrol_activity_enabled ) ) ; AccessControlActivity . this . clientAdapter . refreshData ( AccessControlActivity . this . getCurrentClientData ( ) ) ; if ( TetherService . singleton != null ) TetherService . singleton . restartSecuredWifi ( ) ; AccessControlActivity . this . application . preferenceEditor . putBoolean ( "" , true ) ; AccessControlActivity . this . application . preferenceEditor . commit ( ) ; AccessControlActivity . this . toggleACHeader ( ) ; } catch ( IOException e ) { } } } } ) ; this . buttonApply = ( Button ) findViewById ( R . id . buttonApplyAC ) ; this . buttonApply . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View v ) { Log . d ( MSG_TAG , "" ) ; AccessControlActivity . this . saveWhiteList ( ) ; AccessControlActivity . this . clientAdapter . saveRequired = false ; AccessControlActivity . this . toggleACFooter ( ) ; if ( TetherService . singleton != null ) TetherService . singleton . restartSecuredWifi ( ) ; } } ) ; this . application = ( TetherApplication ) this . getApplication ( ) ; AccessControlActivity . setCurrent ( this ) ; this . clientAdapter = new ClientAdapter ( this , this . getCurrentClientData ( ) , this . application ) ; this . setListAdapter ( this . clientAdapter ) ; this . toggleACHeader ( ) ; this . toggleACFooter ( ) ; } public void onStop ( ) { Log . d ( MSG_TAG , "" ) ; if ( this . clientAdapter . saveRequired ) { this . saveWhiteList ( ) ; this . clientAdapter . saveRequired = false ; if ( TetherService . singleton != null ) TetherService . singleton . restartSecuredWifi ( ) ; } super . onStop ( ) ; } @ Override protected void onResume ( ) { Log . d ( MSG_TAG , "" ) ; super . onResume ( ) ; this . toggleACHeader ( ) ; this . updateListView ( ) ; } private void toggleACHeader ( ) { if ( whitelist . exists ( ) ) { this . statusAC . setText ( getString ( R . string . accesscontrol_activity_is_enabled ) ) ; this . buttonAC . setChecked ( true ) ; } else { this . statusAC . setText ( getString ( R . string . accesscontrol_activity_is_disabled ) ) ; this . buttonAC . setChecked ( false ) ; } } public void toggleACFooter ( ) { if ( this . clientAdapter . saveRequired ) this . applyFooterAC . setVisibility ( View . VISIBLE ) ; else this . applyFooterAC . setVisibility ( View . GONE ) ; } Handler clientConnectHandler = new Handler ( ) { public void handleMessage ( Message msg ) { AccessControlActivity . this . updateListView ( ) ; } } ; private void saveWhiteList ( ) { Log . d ( MSG_TAG , "" ) ; new Thread ( new Runnable ( ) { public void run ( ) { Looper . prepare ( ) ; if ( whitelist . exists ( ) ) { whitelist . whitelist . clear ( ) ; for ( ClientData tmpClientData : AccessControlActivity . this . clientAdapter . getClientData ( ) ) { if ( tmpClientData . isAccessAllowed ( ) ) { whitelist . whitelist . add ( tmpClientData . getMacAddress ( ) ) ; } } try { whitelist . save ( ) ; if ( application . coretask . isNatEnabled ( ) && application . coretask . isProcessRunning ( "" ) ) { if ( TetherService . singleton != null ) TetherService . singleton . restartSecuredWifi ( ) ; } } catch ( Exception ex ) { application . displayToastMessage ( getString ( R . string . accesscontrol_activity_error_save_whitelistfile ) ) ; } } else { if ( whitelist . exists ( ) ) { if ( ! whitelist . remove ( ) ) { application . displayToastMessage ( getString ( R . string . accesscontrol_activity_error_remove_whitelistfile ) ) ; } } } application . displayToastMessage ( getString ( R . string . accesscontrol_activity_config_saved ) ) ; Looper . loop ( ) ; } } ) . start ( ) ; } private void updateListView ( ) { ArrayList < ClientData > clientDataAddList = this . application . getClientDataAddList ( ) ; ArrayList < String > clientMacRemoveList = this . application . getClientMacRemoveList ( ) ; for ( ClientData tmpClientData : clientDataAddList ) { this . clientAdapter . addClient ( tmpClientData ) ; } for ( String tmpMac : clientMacRemoveList ) { this . clientAdapter . removeClient ( tmpMac ) ; } } private ArrayList < ClientData > getCurrentClientData ( ) { ArrayList < ClientData > clientDataList = new ArrayList < ClientData > ( ) ; Hashtable < String , ClientData > leases = null ; try { leases = application . coretask . getLeases ( ) ; } catch ( Exception e ) { AccessControlActivity . this . application . displayToastMessage ( getString ( R . string . accesscontrol_activity_error_read_leasefile ) ) ; } if ( whitelist != null ) { for ( String macAddress : whitelist . get ( ) ) { ClientData clientData = new ClientData ( ) ; clientData . setConnected ( false ) ; clientData . setIpAddress ( getString ( R . string . accesscontrol_activity_not_connected ) ) ; if ( leases . containsKey ( macAddress ) ) { clientData = leases . get ( macAddress ) ; Log . d ( MSG_TAG , clientData . isConnected ( ) + "" + clientData . getIpAddress ( ) ) ; leases . remove ( macAddress ) ; } clientData . setAccessAllowed ( true ) ; clientData . setMacAddress ( macAddress ) ; clientDataList . add ( clientData ) ; } } if ( leases != null ) { Enumeration < String > enumLeases = leases . keys ( ) ; while ( enumLeases . hasMoreElements ( ) ) { String macAddress = enumLeases . nextElement ( ) ; clientDataList . add ( leases . get ( macAddress ) ) ; } } this . application . resetClientMacLists ( ) ; return clientDataList ; } private static final int MENU_RELOAD_CLIENTS = ; private static final int MENU_APPLY = ; @ Override public boolean onCreateOptionsMenu ( Menu menu ) { boolean supRetVal = super . onCreateOptionsMenu ( menu ) ; SubMenu refreshClientList = menu . addSubMenu ( , MENU_RELOAD_CLIENTS , , getString ( R . string . accesscontrol_activity_reloadclientlist ) ) ; refreshClientList . setIcon ( drawable . ic_menu_revert ) ; SubMenu saveWhitelist = menu . addSubMenu ( , MENU_APPLY , , getString ( R . string . accesscontrol_activity_applysettings ) ) ; saveWhitelist . setIcon ( drawable . ic_menu_save ) ; return supRetVal ; } @ Override public boolean onOptionsItemSelected ( MenuItem menuItem ) { boolean supRetVal = super . onOptionsItemSelected ( menuItem ) ; Log . d ( MSG_TAG , "" + menuItem . getItemId ( ) ) ; switch ( menuItem . getItemId ( ) ) { case MENU_APPLY : this . saveWhiteList ( ) ; this . clientAdapter . saveRequired = false ; this . toggleACFooter ( ) ; if ( TetherService . singleton != null ) TetherService . singleton . restartSecuredWifi ( ) ; break ; case MENU_RELOAD_CLIENTS : this . clientAdapter . refreshData ( AccessControlActivity . this . getCurrentClientData ( ) ) ; } return supRetVal ; } } package og . android . tether ; import og . android . tether . data . ClientData ; import og . android . tether . system . BluetoothService ; import android . app . Service ; import android . app . Notification ; import android . bluetooth . BluetoothAdapter ; import android . net . Uri ; import android . net . wifi . WifiManager ; import android . content . Context ; import android . content . Intent ; import android . os . Binder ; import android . os . IBinder ; import android . os . Message ; import android . os . Build ; import android . util . Log ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . Date ; import java . util . Enumeration ; import java . util . Hashtable ; import com . google . analytics . tracking . android . EasyTracker ; public class TetherService extends Service { public static final String MSG_TAG = "" ; public static final int MANAGE_START = ; public static final int MANAGE_STARTED = ; public static final int MANAGE_STOP = ; public static final int MANAGE_STOPPED = ; public static final int STATE_STARTING = ; public static final int STATE_RUNNING = ; public static final int STATE_STOPPING = ; public static final int STATE_IDLE = ; public static final int STATE_RESTARTING = ; public static final int STATE_FAIL_EXEC_START = ; public static final int STATE_FAIL_EXEC_STOP = ; public static final int STATE_FAIL_LOG = ; public static final String INTENT_STATE = "" ; public static final String INTENT_MANAGE = "" ; public static final String INTENT_TRAFFIC = "" ; public static TetherService singleton = null ; private int serviceState = STATE_IDLE ; private TetherApplication application = null ; private final ServiceBinder serviceBinder ; private static final Class < ? > [ ] startForegroundSignature = new Class [ ] { int . class , Notification . class } ; private static final Class < ? > [ ] stopForegroundSignature = new Class [ ] { boolean . class } ; private Method startForeground ; private Object [ ] startForegroundArgs = new Object [ ] ; private Method stopForeground ; private Object [ ] stopForegroundArgs = new Object [ ] ; private WifiManager wifiManager = null ; BluetoothService bluetoothService = null ; private static boolean origWifiState = false ; private static boolean origBluetoothState = false ; private Thread clientConnectThread = null ; private Thread trafficCounterThread = null ; private Thread dnsUpdateThread = null ; public static DataCount dataCount = null ; private boolean configAdv = false ; private boolean offeredMeshclient = false ; public TetherService ( ) { this . serviceBinder = new ServiceBinder ( ) ; } public static TetherService getInstance ( ) { return TetherService . singleton ; } public int getState ( ) { return this . serviceState ; } @ Override public IBinder onBind ( Intent intent ) { return this . serviceBinder ; } class ServiceBinder extends Binder { public ServiceBinder ( ) { } TetherService getService ( ) { return TetherService . this ; } } @ Override public void onCreate ( ) { Log . d ( MSG_TAG , "" ) ; super . onCreate ( ) ; TetherService . singleton = this ; this . application = ( TetherApplication ) getApplication ( ) ; this . configAdv = this . application . isConfigurationAdv ( ) ; this . wifiManager = ( WifiManager ) this . getSystemService ( Context . WIFI_SERVICE ) ; this . bluetoothService = BluetoothService . getInstance ( ) ; this . bluetoothService . setApplication ( this . application ) ; try { startForeground = getClass ( ) . getMethod ( "" , startForegroundSignature ) ; stopForeground = getClass ( ) . getMethod ( "" , stopForegroundSignature ) ; } catch ( NoSuchMethodException e ) { startForeground = stopForeground = null ; Log . d ( MSG_TAG , "" ) ; } if ( this . application . coretask . getProp ( "" ) . equals ( "" ) ) { Log . d ( MSG_TAG , "" ) ; this . serviceState = STATE_RUNNING ; } sendBroadcastManage ( MANAGE_STARTED ) ; } @ Override public int onStartCommand ( Intent intent , int flags , int startId ) { Log . d ( MSG_TAG , "" + flags + "" + startId ) ; return START_STICKY ; } @ Override public void onDestroy ( ) { Log . d ( MSG_TAG , "" ) ; if ( this . serviceState == STATE_RUNNING ) stopTether ( ) ; TetherService . singleton = null ; super . onDestroy ( ) ; } private void sendBroadcastManage ( int state ) { Intent intent = new Intent ( INTENT_MANAGE ) ; intent . putExtra ( "" , state ) ; Log . d ( MSG_TAG , "" + state ) ; sendBroadcast ( intent ) ; } private void sendBroadcastState ( int state ) { Intent intent = new Intent ( INTENT_STATE ) ; intent . putExtra ( "" , state ) ; sendBroadcast ( intent ) ; } private void sendBroadcastTraffic ( long [ ] trafficCount ) { Intent intent = new Intent ( TetherService . INTENT_TRAFFIC ) ; intent . putExtra ( "" , trafficCount ) ; sendBroadcast ( intent ) ; } public void startTether ( ) { Log . d ( MSG_TAG , "" ) ; sendBroadcastState ( this . serviceState = STATE_STARTING ) ; new Thread ( new Runnable ( ) { public void run ( ) { if ( ( ( ! TetherService . this . application . binariesExists ( ) ) || ( TetherService . this . application . coretask . filesetOutdated ( ) ) ) && ( TetherService . this . application . coretask . hasRootPermission ( ) ) ) TetherService . this . application . installFiles ( ) ; boolean started = false ; boolean bluetoothPref = TetherService . this . application . settings . getBoolean ( "" , false ) ; boolean bluetoothWifi = TetherService . this . application . settings . getBoolean ( "" , false ) ; String tetherCommand = "" ; TetherService . this . application . updateConfiguration ( ) ; configAdv = TetherService . this . application . isConfigurationAdv ( ) ; if ( configAdv ) { tetherCommand = "" ; } if ( bluetoothPref ) { if ( setBluetoothState ( true ) == false ) { Log . e ( MSG_TAG , "" ) ; TetherService . this . serviceState = STATE_FAIL_LOG ; started = false ; } if ( bluetoothWifi == false ) { TetherService . this . disableWifi ( ) ; } } else { TetherService . this . disableWifi ( ) ; } String dns [ ] = TetherService . this . application . coretask . updateResolvConf ( ) ; if ( ( TetherService . this . serviceState != STATE_RUNNING ) && ( TetherService . this . serviceState != STATE_FAIL_LOG ) ) { if ( started = TetherService . this . application . coretask . runRootCommand ( TetherService . this . application . coretask . DATA_FILE_PATH + tetherCommand ) ) { TetherService . this . serviceState = STATE_RUNNING ; TetherService . this . application . acquireWakeLock ( ) ; } else TetherService . this . serviceState = STATE_FAIL_EXEC_START ; } else started = true ; if ( started ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } if ( ! TetherService . this . application . coretask . getProp ( "" ) . equals ( "" ) ) TetherService . this . serviceState = STATE_FAIL_LOG ; TetherService . this . clientConnectEnable ( true ) ; TetherService . this . trafficCounterEnable ( true ) ; TetherService . this . dnsUpdateEnable ( dns , true ) ; if ( Integer . parseInt ( Build . VERSION . SDK ) >= Build . VERSION_CODES . ECLAIR ) { if ( bluetoothPref ) { boolean bluetoothDiscoverable = TetherService . this . application . settings . getBoolean ( "" , false ) ; if ( bluetoothDiscoverable ) { TetherService . this . makeDiscoverable ( ) ; } } } } TetherApplication . singleton . reportStats ( serviceState , false ) ; EasyTracker . getTracker ( ) . trackEvent ( "" , "" , "" , ) ; if ( ! started || TetherService . this . serviceState != STATE_RUNNING ) { TetherService . this . enableWifi ( ) ; } Log . d ( MSG_TAG , "" + started + "" + TetherService . this . serviceState ) ; sendBroadcastState ( TetherService . this . serviceState ) ; if ( ( ! started || ( TetherService . this . serviceState != STATE_RUNNING && ! TetherApplication . singleton . onlyEncryptionOrNothingFailed ( ) ) ) && ! TetherApplication . singleton . offeredMeshclient ) { TetherApplication . singleton . openLaunchedDialog ( ) ; TetherApplication . singleton . offeredMeshclient = true ; } } } ) . start ( ) ; String message ; switch ( TetherService . this . serviceState ) { case TetherService . STATE_FAIL_EXEC_START : message = getString ( R . string . main_activity_start_unable ) ; break ; case TetherService . STATE_FAIL_LOG : message = getString ( R . string . main_activity_start_errors ) ; break ; default : message = getString ( R . string . global_application_tethering_running ) ; break ; } startForeground ( - , TetherService . this . application . getStartNotification ( message ) ) ; } public void stopTether ( ) { Log . d ( MSG_TAG , "" ) ; sendBroadcastState ( this . serviceState = STATE_STOPPING ) ; new Thread ( new Runnable ( ) { public void run ( ) { TetherApplication . singleton . reportStats ( STATE_IDLE , false ) ; long bytes = ; try { String tetherNetworkDevice = TetherApplication . singleton . getTetherNetworkDevice ( ) ; long [ ] trafficCount = TetherApplication . singleton . coretask . getDataTraffic ( tetherNetworkDevice ) ; bytes += trafficCount [ ] ; bytes += trafficCount [ ] ; } catch ( UnsatisfiedLinkError e ) { } EasyTracker . getTracker ( ) . trackEvent ( "" , "" , "" , bytes ) ; TetherService . this . trafficCounterEnable ( false ) ; TetherService . this . dnsUpdateEnable ( false ) ; TetherService . this . clientConnectEnable ( false ) ; TetherService . this . application . releaseWakeLock ( ) ; boolean bluetoothPref = TetherService . this . application . settings . getBoolean ( "" , false ) ; boolean bluetoothWifi = TetherService . this . application . settings . getBoolean ( "" , false ) ; String tetherCommand = "" ; if ( configAdv ) { tetherCommand = "" ; } boolean stopped = TetherService . this . application . coretask . runRootCommand ( TetherService . this . application . coretask . DATA_FILE_PATH + tetherCommand ) ; if ( ! stopped ) TetherService . this . serviceState = STATE_FAIL_EXEC_STOP ; else TetherService . this . serviceState = STATE_IDLE ; TetherService . this . application . notificationManager . cancelAll ( ) ; if ( bluetoothPref && origBluetoothState == false ) { setBluetoothState ( false ) ; } if ( bluetoothPref == false || bluetoothWifi == false ) { TetherService . this . enableWifi ( ) ; } Log . d ( MSG_TAG , "" + stopped + "" + TetherService . this . serviceState ) ; sendBroadcastState ( TetherService . this . serviceState ) ; sendBroadcastManage ( TetherService . MANAGE_STOPPED ) ; postToFacebook ( ) ; } } ) . start ( ) ; stopForeground ( true ) ; } private void postToFacebook ( ) { if ( ! application . settings . getBoolean ( "" , false ) ) return ; Log . d ( MSG_TAG , "" ) ; if ( ! application . settings . getBoolean ( "" , true ) ) { Intent postActivity = getPostActivityIntent ( ) ; startActivity ( postActivity ) ; } else { application . FBManager . postToFacebook ( application . getParamsForPost ( ) , new OnPostCompleteListener ( ) { @ Override void onPostComplete ( String result ) { Log . d ( MSG_TAG , "" + result ) ; if ( result == "" ) { Intent postActivity = getPostActivityIntent ( ) ; postActivity . putExtra ( "" , true ) ; startActivity ( postActivity ) ; } } } ) ; } } Intent getPostActivityIntent ( ) { Intent postStats = new Intent ( Intent . ACTION_VIEW ) ; postStats . setData ( Uri . parse ( "" + TetherApplication . MESSAGE_POST_STATS ) ) ; postStats . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; return postStats ; } public void restartTether ( ) { Log . d ( MSG_TAG , "" ) ; sendBroadcastState ( TetherService . this . serviceState = STATE_RESTARTING ) ; final String tetherStopCommand = configAdv ? "" : "" ; final String tetherStartCommand = configAdv ? "" : "" ; new Thread ( new Runnable ( ) { public void run ( ) { TetherApplication . singleton . reportStats ( STATE_IDLE , false ) ; boolean status = TetherService . this . application . coretask . runRootCommand ( TetherService . this . application . coretask . DATA_FILE_PATH + tetherStopCommand ) ; if ( ! status ) TetherService . this . serviceState = STATE_FAIL_EXEC_STOP ; TetherService . this . application . notificationManager . cancelAll ( ) ; TetherService . this . trafficCounterEnable ( false ) ; boolean bluetoothPref = TetherService . this . application . settings . getBoolean ( "" , false ) ; boolean bluetoothWifi = TetherService . this . application . settings . getBoolean ( "" , false ) ; if ( configAdv ) { TetherService . this . application . updateConfigurationAdv ( ) ; } else { TetherService . this . application . updateConfiguration ( ) ; } if ( bluetoothPref ) { if ( setBluetoothState ( true ) == false ) { status = false ; } if ( bluetoothWifi == false ) { TetherService . this . disableWifi ( ) ; } } else { if ( origBluetoothState == false ) { setBluetoothState ( false ) ; } TetherService . this . disableWifi ( ) ; } if ( TetherService . this . serviceState != STATE_RUNNING ) { if ( status && ( status = TetherService . this . application . coretask . runRootCommand ( TetherService . this . application . coretask . DATA_FILE_PATH + tetherStartCommand ) ) ) { TetherService . this . application . showStartNotification ( getString ( R . string . global_application_tethering_running ) ) ; TetherService . this . trafficCounterEnable ( true ) ; TetherService . this . serviceState = STATE_RUNNING ; } else TetherService . this . serviceState = STATE_FAIL_EXEC_START ; } if ( status ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } if ( ! TetherService . this . application . coretask . getProp ( "" ) . equals ( "" ) ) TetherService . this . serviceState = STATE_FAIL_LOG ; } TetherApplication . singleton . reportStats ( serviceState , false ) ; Log . d ( MSG_TAG , "" + status + "" + TetherService . this . serviceState ) ; sendBroadcastState ( TetherService . this . serviceState ) ; } } ) . start ( ) ; } private boolean setBluetoothState ( boolean enabled ) { boolean connected = false ; if ( enabled == false ) { this . bluetoothService . stopBluetooth ( ) ; return false ; } origBluetoothState = this . bluetoothService . isBluetoothEnabled ( ) ; if ( origBluetoothState == false ) { connected = this . bluetoothService . startBluetooth ( ) ; if ( connected == false ) { Log . d ( MSG_TAG , "" ) ; } } else { connected = true ; } return connected ; } private void disableWifi ( ) { if ( this . wifiManager . isWifiEnabled ( ) ) { origWifiState = true ; this . wifiManager . setWifiEnabled ( false ) ; Log . d ( MSG_TAG , "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } } public void enableWifi ( ) { if ( origWifiState ) { this . wifiManager . setWifiEnabled ( true ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } Log . d ( MSG_TAG , "" ) ; } } public void restartSecuredWifi ( ) { try { TetherApplication . singleton . reportStats ( serviceState , false ) ; String tetherRestartCommand = configAdv ? "" : "" ; if ( this . application . coretask . isNatEnabled ( ) && this . application . coretask . isProcessRunning ( "" ) ) { Log . d ( MSG_TAG , "" ) ; if ( ! this . application . coretask . runRootCommand ( this . application . coretask . DATA_FILE_PATH + tetherRestartCommand ) ) { this . application . displayToastMessage ( getString ( R . string . global_application_error_restartsecwifi ) ) ; return ; } } } catch ( Exception e ) { } } private void makeDiscoverable ( ) { Log . d ( MSG_TAG , "" ) ; Intent discoverableIntent = new Intent ( BluetoothAdapter . ACTION_REQUEST_DISCOVERABLE ) ; discoverableIntent . putExtra ( BluetoothAdapter . EXTRA_DISCOVERABLE_DURATION , ) ; discoverableIntent . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; startActivity ( discoverableIntent ) ; } public void clientConnectEnable ( boolean enable ) { if ( enable == true ) { if ( this . clientConnectThread == null || this . clientConnectThread . isAlive ( ) == false ) { this . clientConnectThread = new Thread ( new ClientConnect ( ) ) ; this . clientConnectThread . start ( ) ; } } else { if ( this . clientConnectThread != null ) this . clientConnectThread . interrupt ( ) ; } } class ClientConnect implements Runnable { private ArrayList < String > knownWhitelists = new ArrayList < String > ( ) ; private ArrayList < String > knownLeases = new ArrayList < String > ( ) ; private Hashtable < String , ClientData > currentLeases = new Hashtable < String , ClientData > ( ) ; private long timestampLeasefile = - ; private long timestampWhitelistfile = - ; public void run ( ) { while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { int notificationType = TetherService . this . application . getNotificationType ( ) ; boolean accessControlActive = TetherService . this . application . whitelist . exists ( ) ; if ( accessControlActive ) { long currentTimestampWhitelistFile = TetherService . this . application . coretask . getModifiedDate ( TetherService . this . application . coretask . DATA_FILE_PATH + "" ) ; if ( this . timestampWhitelistfile != currentTimestampWhitelistFile ) { knownWhitelists = TetherService . this . application . whitelist . get ( ) ; this . timestampWhitelistfile = currentTimestampWhitelistFile ; } } long currentTimestampLeaseFile = TetherService . this . application . coretask . getModifiedDate ( TetherService . this . application . coretask . DATA_FILE_PATH + "" ) ; if ( this . timestampLeasefile != currentTimestampLeaseFile ) { try { this . currentLeases = TetherService . this . application . coretask . getLeases ( ) ; for ( String lease : this . knownLeases ) { if ( this . currentLeases . containsKey ( lease ) == false ) { Log . d ( MSG_TAG , "" + lease + "" ) ; this . knownLeases . remove ( lease ) ; notifyActivity ( ) ; TetherService . this . application . removeClientMac ( lease ) ; } } Enumeration < String > leases = this . currentLeases . keys ( ) ; while ( leases . hasMoreElements ( ) ) { String mac = leases . nextElement ( ) ; Log . d ( MSG_TAG , "" + mac + "" + knownWhitelists . contains ( mac ) + "" + knownLeases . contains ( mac ) ) ; if ( knownLeases . contains ( mac ) == false ) { if ( knownWhitelists . contains ( mac ) == false ) { TetherService . this . application . addClientData ( this . currentLeases . get ( mac ) ) ; if ( accessControlActive ) { if ( notificationType == || notificationType == ) { this . sendClientMessage ( this . currentLeases . get ( mac ) , TetherApplication . CLIENT_CONNECT_NOTAUTHORIZED ) ; } } else { if ( notificationType == ) { this . sendClientMessage ( this . currentLeases . get ( mac ) , TetherApplication . CLIENT_CONNECT_ACDISABLED ) ; } } this . knownLeases . add ( mac ) ; } else if ( knownWhitelists . contains ( mac ) == true ) { ClientData clientData = this . currentLeases . get ( mac ) ; clientData . setAccessAllowed ( true ) ; TetherService . this . application . addClientData ( clientData ) ; if ( notificationType == ) { this . sendClientMessage ( this . currentLeases . get ( mac ) , TetherApplication . CLIENT_CONNECT_AUTHORIZED ) ; this . knownLeases . add ( mac ) ; } } notifyActivity ( ) ; } } this . timestampLeasefile = currentTimestampLeaseFile ; } catch ( Exception e ) { Log . d ( MSG_TAG , "" + e . getMessage ( ) ) ; e . printStackTrace ( ) ; } } try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } } private void notifyActivity ( ) { if ( AccessControlActivity . currentInstance != null ) { AccessControlActivity . currentInstance . clientConnectHandler . sendMessage ( new Message ( ) ) ; } } private void sendClientMessage ( ClientData clientData , int connectType ) { Message m = new Message ( ) ; m . obj = clientData ; m . what = connectType ; TetherService . this . application . clientConnectHandler . sendMessage ( m ) ; } } public void dnsUpdateEnable ( boolean enable ) { this . dnsUpdateEnable ( null , enable ) ; } public void dnsUpdateEnable ( String [ ] dns , boolean enable ) { if ( enable == true ) { if ( this . dnsUpdateThread == null || this . dnsUpdateThread . isAlive ( ) == false ) { this . dnsUpdateThread = new Thread ( new DnsUpdate ( dns ) ) ; this . dnsUpdateThread . start ( ) ; } } else { if ( this . dnsUpdateThread != null ) this . dnsUpdateThread . interrupt ( ) ; } } class DnsUpdate implements Runnable { String [ ] dns ; public DnsUpdate ( String [ ] dns ) { this . dns = dns ; } public void run ( ) { while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { String [ ] currentDns = TetherService . this . application . coretask . getCurrentDns ( ) ; if ( this . dns == null || this . dns [ ] . equals ( currentDns [ ] ) == false || this . dns [ ] . equals ( currentDns [ ] ) == false ) { this . dns = TetherService . this . application . coretask . updateResolvConf ( ) ; } try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } } } public void trafficCounterEnable ( boolean enable ) { if ( enable == true ) { if ( this . trafficCounterThread == null || this . trafficCounterThread . isAlive ( ) == false ) { this . trafficCounterThread = new Thread ( new TrafficCounter ( ) ) ; this . trafficCounterThread . start ( ) ; } } else { if ( this . trafficCounterThread != null ) this . trafficCounterThread . interrupt ( ) ; } } class TrafficCounter implements Runnable { private static final int INTERVAL = ; long previousDownload ; long previousUpload ; long lastTimeChecked ; public void run ( ) { this . previousDownload = this . previousUpload = ; this . lastTimeChecked = new Date ( ) . getTime ( ) ; String tetherNetworkDevice = TetherService . this . application . getTetherNetworkDevice ( ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { long [ ] trafficCount = TetherService . this . application . coretask . getDataTraffic ( tetherNetworkDevice ) ; long currentTime = new Date ( ) . getTime ( ) ; float elapsedTime = ( float ) ( ( currentTime - this . lastTimeChecked ) / ) ; this . lastTimeChecked = currentTime ; long [ ] trafficCount2 = new long [ ] ; trafficCount2 [ ] = trafficCount [ ] ; trafficCount2 [ ] = trafficCount [ ] ; trafficCount2 [ ] = ( long ) ( ( trafficCount [ ] - this . previousUpload ) * / elapsedTime ) ; trafficCount2 [ ] = ( long ) ( ( trafficCount [ ] - this . previousDownload ) * / elapsedTime ) ; this . previousUpload = trafficCount [ ] ; this . previousDownload = trafficCount [ ] ; sendBroadcastTraffic ( trafficCount2 ) ; try { Thread . sleep ( INTERVAL * ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } DataCount dataCount = new DataCount ( ) ; dataCount . totalDownload = previousDownload ; dataCount . totalUpload = previousUpload ; TetherService . this . dataCount = dataCount ; } } public class DataCount { public long totalUpload ; public long totalDownload ; public long uploadRate ; public long downloadRate ; } } package com . loiane . test ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertNotNull ; import java . util . List ; import org . junit . AfterClass ; import org . junit . BeforeClass ; import org . junit . Test ; import com . loiane . dao . BlogDAO ; import com . loiane . model . Blog ; public class TestBlogDAO { private static BlogDAO blogDAO ; @ BeforeClass public static void runBeforeClass ( ) { blogDAO = new BlogDAO ( ) ; } @ AfterClass public static void runAfterClass ( ) { blogDAO = null ; } @ Test public void testSelect ( ) { List < Blog > list = blogDAO . select ( ) ; assertNotNull ( list ) ; assertEquals ( , list . size ( ) ) ; for ( Blog blog : list ) { System . out . println ( blog . toString ( ) ) ; } } @ Test public void testSelectN1ProblemSolution ( ) { List < Blog > list = blogDAO . selectN1ProblemSolution ( ) ; assertNotNull ( list ) ; assertEquals ( , list . size ( ) ) ; for ( Blog blog : list ) { System . out . println ( blog . toString ( ) ) ; } } } package com . loiane . test ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertNotNull ; import java . util . List ; import org . junit . AfterClass ; import org . junit . BeforeClass ; import org . junit . Test ; import com . loiane . dao . BlogAnnotationDAO ; import com . loiane . model . Blog ; public class TestBlogAnnotationDAO { private static BlogAnnotationDAO blogAnnotationDAO ; @ BeforeClass public static void runBeforeClass ( ) { blogAnnotationDAO = new BlogAnnotationDAO ( ) ; } @ AfterClass public static void runAfterClass ( ) { blogAnnotationDAO = null ; } @ Test public void testSelectAllBlogs ( ) { List < Blog > list = blogAnnotationDAO . selectAllBlogs ( ) ; assertNotNull ( list ) ; assertEquals ( , list . size ( ) ) ; for ( Blog blog : list ) { System . out . println ( blog . toString ( ) ) ; } } } package com . loiane . data ; import java . util . List ; import org . apache . ibatis . annotations . Many ; import org . apache . ibatis . annotations . One ; import org . apache . ibatis . annotations . Result ; import org . apache . ibatis . annotations . Results ; import org . apache . ibatis . annotations . Select ; import com . loiane . model . Author ; import com . loiane . model . Blog ; import com . loiane . model . Post ; public interface BlogMapper { final String SELECT_POSTS = "" + "" + "" ; @ Select ( "" ) @ Results ( value = { @ Result ( property = "" , column = "" ) , @ Result ( property = "" , column = "" ) , @ Result ( property = "" , column = "" ) , @ Result ( property = "" , column = "" , javaType = Author . class , one = @ One ( select = "" ) ) , @ Result ( property = "" , column = "" , javaType = List . class , many = @ Many ( select = "" ) ) } ) List < Blog > selectAllBlogs ( ) ; @ Select ( "" ) Author selectAuthor ( String idBlog ) ; @ Select ( SELECT_POSTS ) @ Results ( value = { @ Result ( property = "" , column = "" ) , @ Result ( property = "" , column = "" ) , @ Result ( property = "" , column = "" , javaType = List . class , many = @ Many ) } ) List < Post > selectBlogPosts ( String idBlog ) ; } package com . loiane . model ; import java . util . List ; public class Post { private int id ; private String title ; private List < Tag > tags ; public int getId ( ) { return id ; } public void setId ( int id ) { this . id = id ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } public List < Tag > getTags ( ) { return tags ; } public void setTags ( List < Tag > tags ) { this . tags = tags ; } public String toString ( ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( "" ) . append ( id ) . append ( "" ) ; sb . append ( "" ) . append ( title ) ; if ( tags != null ) { for ( Tag t : tags ) { sb . append ( "" ) . append ( t . toString ( ) ) ; } } return sb . toString ( ) ; } } package com . loiane . model ; public class Tag { private int id ; private String value ; public int getId ( ) { return id ; } public void setId ( int id ) { this . id = id ; } public String getValue ( ) { return value ; } public void setValue ( String value ) { this . value = value ; } public String toString ( ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( "" ) . append ( id ) . append ( "" ) ; sb . append ( "" ) . append ( value ) ; return sb . toString ( ) ; } } package com . loiane . model ; import java . util . List ; public class Blog { private int id ; private String name ; private String url ; private Author author ; private List < Post > posts ; public int getId ( ) { return id ; } public void setId ( int id ) { this . id = id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getUrl ( ) { return url ; } public void setUrl ( String url ) { this . url = url ; } public Author getAuthor ( ) { return author ; } public void setAuthor ( Author author ) { this . author = author ; } public List < Post > getPosts ( ) { return posts ; } public void setPosts ( List < Post > posts ) { this . posts = posts ; } public String toString ( ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( "" ) . append ( id ) . append ( "" ) ; sb . append ( "" ) . append ( name ) . append ( "" ) ; sb . append ( "" ) . append ( url ) . append ( "" ) ; sb . append ( "" ) . append ( author . toString ( ) ) . append ( "" ) ; for ( Post p : posts ) { sb . append ( p . toString ( ) ) . append ( "" ) ; } return sb . toString ( ) ; } } package com . loiane . model ; public class Author { private int id ; private String name ; private String email ; public int getId ( ) { return id ; } public void setId ( int id ) { this . id = id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getEmail ( ) { return email ; } public void setEmail ( String email ) { this . email = email ; } public String toString ( ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( "" ) . append ( id ) . append ( "" ) ; sb . append ( "" ) . append ( name ) . append ( "" ) ; sb . append ( "" ) . append ( email ) ; return sb . toString ( ) ; } } package com . loiane . dao ; import java . util . List ; import org . apache . ibatis . session . SqlSession ; import org . apache . ibatis . session . SqlSessionFactory ; import com . loiane . model . Blog ; public class BlogDAO { @ SuppressWarnings ( "" ) public List < Blog > select ( ) { SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory . getSqlSessionFactory ( ) ; SqlSession session = sqlSessionFactory . openSession ( ) ; try { List < Blog > list = session . selectList ( "" ) ; return list ; } finally { session . close ( ) ; } } @ SuppressWarnings ( "" ) public List < Blog > selectN1ProblemSolution ( ) { SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory . getSqlSessionFactory ( ) ; SqlSession session = sqlSessionFactory . openSession ( ) ; try { List < Blog > list = session . selectList ( "" ) ; return list ; } finally { session . close ( ) ; } } } package com . loiane . dao ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . Reader ; import org . apache . ibatis . io . Resources ; import org . apache . ibatis . session . SqlSessionFactory ; import org . apache . ibatis . session . SqlSessionFactoryBuilder ; import com . loiane . data . BlogMapper ; public class MyBatisConnectionFactory { private static SqlSessionFactory sqlSessionFactory ; static { try { String resource = "" ; Reader reader = Resources . getResourceAsReader ( resource ) ; if ( sqlSessionFactory == null ) { sqlSessionFactory = new SqlSessionFactoryBuilder ( ) . build ( reader ) ; sqlSessionFactory . getConfiguration ( ) . addMapper ( BlogMapper . class ) ; } } catch ( FileNotFoundException fileNotFoundException ) { fileNotFoundException . printStackTrace ( ) ; } catch ( IOException iOException ) { iOException . printStackTrace ( ) ; } } public static SqlSessionFactory getSqlSessionFactory ( ) { return sqlSessionFactory ; } } package com . loiane . dao ; import java . util . List ; import org . apache . ibatis . session . SqlSession ; import org . apache . ibatis . session . SqlSessionFactory ; import com . loiane . data . BlogMapper ; import com . loiane . model . Blog ; public class BlogAnnotationDAO { public List < Blog > selectAllBlogs ( ) { SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory . getSqlSessionFactory ( ) ; SqlSession session = sqlSessionFactory . openSession ( ) ; try { BlogMapper mapper = session . getMapper ( BlogMapper . class ) ; List < Blog > list = mapper . selectAllBlogs ( ) ; return list ; } finally { session . close ( ) ; } } } package fi . koku . services . entity . ccis . v1 ; public class EfficaCC { } package fi . koku . services . entity . kks . v1 ; import java . util . ArrayList ; import java . util . List ; public class GroupsHelper { private KksServicePortType kksServicePortType ; private final String component ; public GroupsHelper ( String uid , String pwd , String component , String endpointAddress ) { this . component = component ; this . kksServicePortType = new KksServiceFactory ( uid , pwd , endpointAddress ) . getKksService ( ) ; } public List < InfoGroup > getInfoGroups ( String userPic ) { AuditInfoType audit = new AuditInfoType ( ) ; audit . setComponent ( component ) ; audit . setUserId ( userPic ) ; List < InfoGroup > groups = new ArrayList < InfoGroup > ( ) ; try { KksCollectionClassesType collections = kksServicePortType . opGetKksCollectionClasses ( "" , audit ) ; for ( KksCollectionClassType collection : collections . getKksCollectionClass ( ) ) { InfoGroup topLevelGroup = new InfoGroup ( "" + collection . getId ( ) , collection . getName ( ) ) ; for ( KksGroupType group : collection . getKksGroups ( ) . getKksGroup ( ) ) { boolean groupExist = ! "" . equals ( group . getName ( ) ) ; InfoGroup infoGroup = groupExist ? new InfoGroup ( "" + group . getId ( ) , group . getName ( ) ) : topLevelGroup ; for ( KksGroupType subGroup : group . getSubGroups ( ) . getKksGroup ( ) ) { boolean subGroupExist = ! "" . equals ( subGroup . getName ( ) ) ; if ( subGroupExist ) { infoGroup . addSubGroup ( new InfoGroup ( "" + subGroup . getId ( ) , subGroup . getName ( ) ) ) ; } } if ( groupExist ) { topLevelGroup . addSubGroup ( infoGroup ) ; } } groups . add ( topLevelGroup ) ; } } catch ( ServiceFault e ) { throw new RuntimeException ( e ) ; } return groups ; } } package fi . koku . services . entity . kks . v1 ; import java . net . URL ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class KksServiceFactory { private static Logger log = LoggerFactory . getLogger ( KksServiceFactory . class ) ; public static String SERVICE_AREA_DAYCARE = "" ; public static String SERVICE_AREA_BASIC_EDUCATION = "" ; public static String SERVICE_AREA_CHILD_HEALTH = "" ; private String uid ; private String pwd ; private String endpointBaseUrl ; private final URL KKS_WSDL_LOCATION = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; public KksServiceFactory ( String uid , String pwd , String endpointBaseUrl ) { this . uid = uid ; this . pwd = pwd ; this . endpointBaseUrl = endpointBaseUrl ; } public KksServicePortType getKksService ( ) { if ( KKS_WSDL_LOCATION == null ) log . error ( "" ) ; KksService service = new KksService ( KKS_WSDL_LOCATION , new QName ( "" , "" ) ) ; KksServicePortType kksServicePort = service . getKksServiceSoap11Port ( ) ; String epAddr = endpointBaseUrl + "" ; log . debug ( "" + epAddr ) ; ( ( BindingProvider ) kksServicePort ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; ( ( BindingProvider ) kksServicePort ) . getRequestContext ( ) . put ( BindingProvider . USERNAME_PROPERTY , uid ) ; ( ( BindingProvider ) kksServicePort ) . getRequestContext ( ) . put ( BindingProvider . PASSWORD_PROPERTY , pwd ) ; return kksServicePort ; } } package fi . koku . services . entity . kks . v1 ; import java . util . ArrayList ; import java . util . List ; public class InfoGroup { public InfoGroup ( String id , String name ) { super ( ) ; this . id = id ; this . name = name ; } private String id ; private String name ; private List < InfoGroup > subGroups ; public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public List < InfoGroup > getSubGroups ( ) { return subGroups ; } public void addSubGroup ( InfoGroup ig ) { if ( subGroups == null ) { subGroups = new ArrayList < InfoGroup > ( ) ; } subGroups . add ( ig ) ; } @ Override public String toString ( ) { return "" + id + "" + name + "" ; } } package fi . koku . services . entity . his . v1 ; public class Pegasos { } package fi . koku . services . utility . authorizationinfo . sample ; import java . util . List ; import java . util . logging . Logger ; import fi . koku . services . utility . authorizationinfo . v1 . Constants ; import fi . koku . services . utility . authorizationinfo . v1 . AuthorizationInfoService ; import fi . koku . services . utility . authorizationinfo . v1 . impl . AuthorizationInfoServiceDummyImpl ; import fi . koku . services . utility . authorizationinfo . v1 . model . Group ; import fi . koku . services . utility . authorizationinfo . v1 . model . OrgUnit ; import fi . koku . services . utility . authorizationinfo . v1 . model . Registry ; import fi . koku . services . utility . authorizationinfo . v1 . model . Role ; public class SampleClientUsage { private static final Logger LOG = Logger . getAnonymousLogger ( ) ; public static void main ( String args [ ] ) { AuthorizationInfoService serv = new AuthorizationInfoServiceDummyImpl ( ) ; List < Role > roles = serv . getUsersRoles ( Constants . DOMAIN_LOG , "" ) ; LOG . info ( "" + roles . size ( ) ) ; if ( roles . contains ( Constants . ROLE_LOK_ADMIN ) ) { LOG . info ( "" ) ; } else { LOG . info ( "" ) ; } List < Registry > regs = serv . getUsersAuthorizedRegistries ( "" ) ; if ( regs . contains ( new Registry ( "" ) ) ) { LOG . info ( "" ) ; List < OrgUnit > orgUnits = serv . getUsersOrgUnits ( Constants . DOMAIN_CHILD_WELFARE_CLINIC , "" ) ; if ( orgUnits . contains ( new OrgUnit ( "" ) ) ) { LOG . info ( "" ) ; } else { LOG . info ( "" ) ; } } else { LOG . info ( "" ) ; } List < Group > groups = serv . getUsersGroups ( Constants . DOMAIN_DAYCARE , "" ) ; if ( groups . contains ( new Group ( "" ) ) ) { LOG . info ( "" ) ; } else { LOG . info ( "" ) ; } } } package fi . koku . services . utility . authorizationinfo . util ; import java . util . List ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . KoKuException ; import fi . koku . KoKuNotAuthorizedException ; import fi . koku . auth . KoKuRoleUtil ; import fi . koku . services . utility . authorizationinfo . v1 . model . Role ; public class AuthUtils { private static Logger logger = LoggerFactory . getLogger ( AuthUtils . class ) ; private AuthUtils ( ) { } public static boolean isOperationAllowed ( String operation , List < Role > roles ) { Set < String > allowedRoles = KoKuRoleUtil . getAllowedRoles ( operation ) ; for ( Role r : roles ) { if ( allowedRoles . contains ( r . getId ( ) ) ) { return true ; } } return false ; } public static void requirePermission ( String operation , String userId , List < Role > roles ) { if ( ! isOperationAllowed ( operation , roles ) ) { logger . info ( "" , new Object [ ] { operation , userId , roles } ) ; throw new KoKuNotAuthorizedException ( KoKuException . NOT_AUTHORIZED_ERROR_CODE , KoKuException . NOT_AUTHORIZED_ERROR_MESSAGE ) ; } } } package fi . koku . services . utility . authorizationinfo . v1 ; import fi . koku . services . utility . authorizationinfo . v1 . model . Registry ; import fi . koku . services . utility . authorizationinfo . v1 . model . Role ; public class Constants { public static String DOMAIN_DAYCARE = "" ; public static String DOMAIN_LOG = "" ; public static String DOMAIN_CHILD_WELFARE_CLINIC ; public static Registry REGISTRY_PATIENT_INFORMATION = new Registry ( "" ) ; public static Registry REGISTRY_DAYCARE_CUSTOMER_INFORMATION = new Registry ( "" ) ; public static Role ROLE_LOK_ADMIN = new Role ( "" ) ; public static Role ROLE_LOK_LOG_ADMIN = new Role ( "" ) ; } package fi . koku . services . utility . authorizationinfo . v1 ; import java . util . List ; import fi . koku . services . utility . authorizationinfo . v1 . model . Group ; import fi . koku . services . utility . authorizationinfo . v1 . model . OrgUnit ; import fi . koku . services . utility . authorizationinfo . v1 . model . Registry ; import fi . koku . services . utility . authorizationinfo . v1 . model . Role ; import fi . koku . services . utility . authorizationinfo . v1 . model . User ; public interface AuthorizationInfoService { List < Registry > getUsersAuthorizedRegistries ( String uid ) ; List < Role > getUsersRoles ( String domain , String uid ) ; List < OrgUnit > getUsersOrgUnits ( String domain , String uid ) ; List < Group > getUsersGroups ( String domain , String uid ) ; List < User > getGroupMembersByGroupId ( String domain , String gid ) ; } package fi . koku . services . utility . authorizationinfo . v1 . impl ; import java . util . ArrayList ; import java . util . List ; import fi . koku . services . utility . authorizationinfo . v1 . AuthorizationInfoService ; import fi . koku . services . utility . authorizationinfo . v1 . Constants ; import fi . koku . services . utility . authorizationinfo . v1 . model . Group ; import fi . koku . services . utility . authorizationinfo . v1 . model . OrgUnit ; import fi . koku . services . utility . authorizationinfo . v1 . model . Registry ; import fi . koku . services . utility . authorizationinfo . v1 . model . Role ; import fi . koku . services . utility . authorizationinfo . v1 . model . User ; public class AuthorizationInfoServiceDummyImpl implements AuthorizationInfoService { public List < Registry > getUsersAuthorizedRegistries ( String uid ) { List < Registry > ret = new ArrayList < Registry > ( ) ; if ( uid . equals ( "" ) ) { ret . add ( new Registry ( "" , "" ) ) ; } else if ( uid . equals ( "" ) ) { ret . add ( new Registry ( "" , "" ) ) ; } return ret ; } public List < Role > getUsersRoles ( String context , String uid ) { List < Role > ret = new ArrayList < Role > ( ) ; if ( "" . equals ( uid ) ) { ret . add ( Constants . ROLE_LOK_ADMIN ) ; } else if ( "" . equals ( uid ) ) { ret . add ( Constants . ROLE_LOK_LOG_ADMIN ) ; } return ret ; } public List < OrgUnit > getUsersOrgUnits ( String context , String uid ) { List < OrgUnit > ret = new ArrayList < OrgUnit > ( ) ; if ( uid . equals ( "" ) ) { ret . add ( new OrgUnit ( "" , "" , "" ) ) ; } else if ( uid . equals ( "" ) ) { ret . add ( new OrgUnit ( "" , "" , "" ) ) ; } ret . add ( new OrgUnit ( "" , "" , "" ) ) ; return ret ; } public List < Group > getUsersGroups ( String context , String uid ) { List < Group > ret = new ArrayList < Group > ( ) ; ret . add ( new Group ( "" , "" ) ) ; return ret ; } public List < User > getGroupMembersByGroupId ( String context , String gid ) { List < User > ret = new ArrayList < User > ( ) ; User u1 = new User ( ) ; u1 . setId ( "" ) ; u1 . setFirstname ( "" ) ; u1 . setLastname ( "" ) ; ret . add ( u1 ) ; User u2 = new User ( ) ; u2 . setId ( "" ) ; u2 . setFirstname ( "" ) ; u2 . setLastname ( "" ) ; ret . add ( u2 ) ; return ret ; } } package fi . koku . services . utility . authorizationinfo . v1 . impl ; import java . util . ArrayList ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . KoKuFaultException ; import fi . koku . services . utility . authorization . v1 . AuthorizationInfoServicePortType ; import fi . koku . services . utility . authorization . v1 . GroupQueryCriteriaType ; import fi . koku . services . utility . authorization . v1 . GroupType ; import fi . koku . services . utility . authorization . v1 . GroupsType ; import fi . koku . services . utility . authorization . v1 . MemberPicsType ; import fi . koku . services . utility . authorization . v1 . ServiceFault ; import fi . koku . services . utility . authorizationinfo . v1 . AuthorizationInfoService ; import fi . koku . services . utility . authorizationinfo . v1 . model . Group ; import fi . koku . services . utility . authorizationinfo . v1 . model . OrgUnit ; import fi . koku . services . utility . authorizationinfo . v1 . model . Registry ; import fi . koku . services . utility . authorizationinfo . v1 . model . Role ; import fi . koku . services . utility . authorizationinfo . v1 . model . User ; public class AuthorizationInfoServiceWSImpl implements AuthorizationInfoService { private Logger logger = LoggerFactory . getLogger ( AuthorizationInfoServiceWSImpl . class ) ; private AuthorizationInfoServicePortType authzService ; public AuthorizationInfoServiceWSImpl ( AuthorizationInfoServicePortType ep ) { this . authzService = ep ; } @ Override public List < Registry > getUsersAuthorizedRegistries ( String uid ) { List < Registry > res = getGroups ( null , "" , uid , new GroupTypeMapper < Registry > ( ) { @ Override public Registry mapToSpecializedGroup ( GroupType grp ) { return new Registry ( grp . getId ( ) , grp . getName ( ) ) ; } } ) ; return res ; } @ Override public List < Role > getUsersRoles ( String domain , String uid ) { List < Role > res = getGroups ( domain , "" , uid , new GroupTypeMapper < Role > ( ) { @ Override public Role mapToSpecializedGroup ( GroupType grp ) { return new Role ( grp . getId ( ) , grp . getName ( ) ) ; } } ) ; return res ; } @ Override public List < OrgUnit > getUsersOrgUnits ( String domain , String uid ) { GroupTypeMapper < OrgUnit > m = new GroupTypeMapper < OrgUnit > ( ) { @ Override public OrgUnit mapToSpecializedGroup ( GroupType grp ) { return new OrgUnit ( grp . getId ( ) , grp . getName ( ) ) ; } } ; List < OrgUnit > res = getGroups ( domain , "" , uid , m ) ; return res ; } @ Override public List < Group > getUsersGroups ( String domain , String uid ) { List < Group > res = getGroups ( domain , "" , uid , new GroupTypeMapper < Group > ( ) { @ Override public Group mapToSpecializedGroup ( GroupType grp ) { return new Group ( grp . getId ( ) , grp . getName ( ) ) ; } } ) ; return res ; } @ Override public List < User > getGroupMembersByGroupId ( String domain , String gid ) { throw new KoKuFaultException ( , "" ) ; } private static interface GroupTypeMapper < T > { public T mapToSpecializedGroup ( GroupType grp ) ; } private < T > List < T > getGroups ( String domain , String groupClass , String uid , GroupTypeMapper < T > m ) { List < T > res = new ArrayList < T > ( ) ; GroupQueryCriteriaType qc = new GroupQueryCriteriaType ( ) ; qc . setGroupClass ( groupClass ) ; if ( domain != null ) { qc . setDomain ( domain ) ; } qc . setMemberPics ( new MemberPicsType ( ) ) ; qc . getMemberPics ( ) . getMemberPic ( ) . add ( uid ) ; try { GroupsType groups = authzService . opQueryGroups ( qc ) ; for ( GroupType g : groups . getGroup ( ) ) { res . add ( m . mapToSpecializedGroup ( g ) ) ; } } catch ( ServiceFault e ) { logger . error ( "" + uid , e ) ; throw new KoKuFaultException ( , "" + uid ) ; } return res ; } } package fi . koku . services . utility . authorizationinfo . v1 . model ; public class OrgUnit { private String id ; private String name ; private String serviceArea ; public OrgUnit ( String id ) { this . id = id ; } public OrgUnit ( String id , String name ) { this . id = id ; this . name = name ; } public OrgUnit ( String id , String name , String serviceArea ) { this . id = id ; this . name = name ; this . serviceArea = serviceArea ; } public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getServiceArea ( ) { return serviceArea ; } public void setServiceArea ( String serviceArea ) { this . serviceArea = serviceArea ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( id == null ) ? : id . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; OrgUnit other = ( OrgUnit ) obj ; if ( id == null ) { if ( other . id != null ) return false ; } else if ( ! id . equals ( other . id ) ) return false ; return true ; } } package fi . koku . services . utility . authorizationinfo . v1 . model ; public class Role { private String id ; private String name ; public Role ( String id ) { this . id = id ; } public Role ( String id , String name ) { this . id = id ; this . name = name ; } public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public boolean equals ( String o ) { return true ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Role other = ( Role ) obj ; if ( id == null ) { if ( other . id != null ) return false ; } else if ( ! id . equals ( other . id ) ) return false ; return true ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( id == null ) ? : id . hashCode ( ) ) ; return result ; } @ Override public String toString ( ) { return "" + id + "" + name + "" ; } } package fi . koku . services . utility . authorizationinfo . v1 . model ; public class Group { private String id ; private String name ; public Group ( String id ) { this . id = id ; } public Group ( String id , String name ) { this . id = id ; this . name = name ; } public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( id == null ) ? : id . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Group other = ( Group ) obj ; if ( id == null ) { if ( other . id != null ) return false ; } else if ( ! id . equals ( other . id ) ) return false ; return true ; } } package fi . koku . services . utility . authorizationinfo . v1 . model ; public class User { private String id ; private String firstname ; private String lastname ; public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getFirstname ( ) { return firstname ; } public void setFirstname ( String firstname ) { this . firstname = firstname ; } public String getLastname ( ) { return lastname ; } public void setLastname ( String lastname ) { this . lastname = lastname ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( id == null ) ? : id . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; User other = ( User ) obj ; if ( id == null ) { if ( other . id != null ) return false ; } else if ( ! id . equals ( other . id ) ) return false ; return true ; } } package fi . koku . services . utility . authorizationinfo . v1 . model ; public class Registry { private String id ; private String name ; public Registry ( String id ) { this . id = id ; } public Registry ( String id , String name ) { this . id = id ; this . name = name ; } public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( id == null ) ? : id . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Registry other = ( Registry ) obj ; if ( id == null ) { if ( other . id != null ) return false ; } else if ( ! id . equals ( other . id ) ) return false ; return true ; } } package fi . koku . services . utility . authorizationinfo . v1 ; import java . net . URL ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . services . utility . authorization . v1 . AuthorizationInfoService ; import fi . koku . services . utility . authorization . v1 . AuthorizationInfoServicePortType ; import fi . koku . services . utility . authorizationinfo . v1 . impl . AuthorizationInfoServiceDummyImpl ; import fi . koku . services . utility . authorizationinfo . v1 . impl . AuthorizationInfoServiceWSImpl ; public class AuthorizationInfoServiceFactory { private String uid ; private String pwd ; private String endpointPathUrl ; private final URL wsdlLocation = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; private static Logger log = LoggerFactory . getLogger ( AuthorizationInfoServiceFactory . class ) ; public AuthorizationInfoServiceFactory ( String uid , String pwd , String endpointPathUrl ) { this . uid = uid ; this . pwd = pwd ; this . endpointPathUrl = endpointPathUrl ; } public fi . koku . services . utility . authorizationinfo . v1 . AuthorizationInfoService getAuthorizationInfoService ( ) { return new AuthorizationInfoServiceWSImpl ( getAuthorizationInfoServicePortType ( ) ) ; } public fi . koku . services . utility . authorizationinfo . v1 . AuthorizationInfoService getAuthorizationInfoService ( String implType ) { if ( "" . equals ( implType ) ) return new AuthorizationInfoServiceDummyImpl ( ) ; return getAuthorizationInfoService ( ) ; } private AuthorizationInfoServicePortType getAuthorizationInfoServicePortType ( ) { if ( wsdlLocation == null ) log . error ( "" ) ; AuthorizationInfoService service = new AuthorizationInfoService ( wsdlLocation , new QName ( "" , "" ) ) ; AuthorizationInfoServicePortType port = service . getAuthorizationInfoServiceSoap11Port ( ) ; String epAddr = endpointPathUrl + "" ; log . debug ( "" + epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . USERNAME_PROPERTY , uid ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . PASSWORD_PROPERTY , pwd ) ; return port ; } } package fi . koku . services . entity . customercommunication . v1 ; import java . io . FileInputStream ; import java . io . IOException ; import java . net . URL ; import java . security . GeneralSecurityException ; import java . security . KeyStore ; import java . security . KeyStoreException ; import java . security . NoSuchAlgorithmException ; import javax . net . ssl . KeyManager ; import javax . net . ssl . KeyManagerFactory ; import javax . net . ssl . TrustManager ; import javax . net . ssl . TrustManagerFactory ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . apache . cxf . configuration . jsse . TLSClientParameters ; import org . apache . cxf . frontend . ClientProxy ; import org . apache . cxf . transport . http . HTTPConduit ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . tampere . contract . municipalityportal . ccs . CustomerCommunicationService ; import fi . tampere . contract . municipalityportal . ccs . CustomerCommunicationServicePortType ; public class CustomerCommunicationServiceFactory { private String uid ; private String pwd ; private String endpointUrl ; private final URL wsdlLocation = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; private static Logger log = LoggerFactory . getLogger ( CustomerCommunicationServiceFactory . class ) ; public CustomerCommunicationServiceFactory ( String uid , String pwd , String endpointUrl ) { this . uid = uid ; this . pwd = pwd ; this . endpointUrl = endpointUrl ; } public CustomerCommunicationServicePortType getCustomerCommunicationService ( ) { if ( wsdlLocation == null ) log . error ( "" ) ; CustomerCommunicationService service = new CustomerCommunicationService ( wsdlLocation , new QName ( "" , "" ) ) ; CustomerCommunicationServicePortType port = service . getCustomerCommunicationServicePort ( ) ; String epAddr = endpointUrl ; log . debug ( "" + epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . USERNAME_PROPERTY , uid ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . PASSWORD_PROPERTY , pwd ) ; try { final HTTPConduit httpConduit = ( HTTPConduit ) ClientProxy . getClient ( port ) . getConduit ( ) ; final TLSClientParameters tlsCP = new TLSClientParameters ( ) ; final String keyStoreLoc = System . getProperty ( "" ) ; final String keyPassword = System . getProperty ( "" ) ; final String keystoreType = System . getProperty ( "" ) ; log . info ( "" + keystoreType + "" + keyStoreLoc ) ; final KeyStore keyStore = KeyStore . getInstance ( keystoreType ) ; keyStore . load ( new FileInputStream ( keyStoreLoc ) , keyPassword . toCharArray ( ) ) ; final KeyManager [ ] myKeyManagers = getKeyManagers ( keyStore , keyPassword ) ; tlsCP . setKeyManagers ( myKeyManagers ) ; final String trustStoreLoc = System . getProperty ( "" ) ; final String trustStorePassword = System . getProperty ( "" ) ; final String trustStoreType = System . getProperty ( "" ) ; log . info ( "" + trustStoreType + "" + trustStoreLoc ) ; final KeyStore trustStore = KeyStore . getInstance ( trustStoreType ) ; trustStore . load ( new FileInputStream ( trustStoreLoc ) , trustStorePassword . toCharArray ( ) ) ; final TrustManager [ ] myTrustStoreKeyManagers = getTrustManagers ( trustStore ) ; tlsCP . setTrustManagers ( myTrustStoreKeyManagers ) ; httpConduit . setTlsClientParameters ( tlsCP ) ; } catch ( Exception e ) { log . info ( "" + e . getMessage ( ) , e ) ; } return port ; } private static TrustManager [ ] getTrustManagers ( KeyStore trustStore ) throws NoSuchAlgorithmException , KeyStoreException { String alg = KeyManagerFactory . getDefaultAlgorithm ( ) ; TrustManagerFactory fac = TrustManagerFactory . getInstance ( alg ) ; fac . init ( trustStore ) ; return fac . getTrustManagers ( ) ; } private static KeyManager [ ] getKeyManagers ( KeyStore keyStore , String keyPassword ) throws GeneralSecurityException , IOException { String alg = KeyManagerFactory . getDefaultAlgorithm ( ) ; char [ ] keyPass = keyPassword != null ? keyPassword . toCharArray ( ) : null ; KeyManagerFactory fac = KeyManagerFactory . getInstance ( alg ) ; fac . init ( keyStore , keyPass ) ; return fac . getKeyManagers ( ) ; } } package fi . koku . services . entity . customer . v1 ; import java . net . URL ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CustomerServiceFactory { private String uid ; private String pwd ; private String endpointBaseUrl ; private final URL wsdlLocation = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; private static Logger log = LoggerFactory . getLogger ( CustomerServiceFactory . class ) ; public CustomerServiceFactory ( String uid , String pwd , String endpointBaseUrl ) { this . uid = uid ; this . pwd = pwd ; this . endpointBaseUrl = endpointBaseUrl ; } public CustomerServicePortType getCustomerService ( ) { if ( wsdlLocation == null ) log . error ( "" ) ; CustomerService service = new CustomerService ( wsdlLocation , new QName ( "" , "" ) ) ; CustomerServicePortType port = service . getCustomerServiceSoap11Port ( ) ; String epAddr = endpointBaseUrl + "" ; log . debug ( "" + epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . USERNAME_PROPERTY , uid ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . PASSWORD_PROPERTY , pwd ) ; return port ; } public static AuditInfoType createAuditInfoType ( String component , String userPic ) { AuditInfoType audit = new AuditInfoType ( ) ; audit . setComponent ( component ) ; audit . setUserId ( userPic ) ; return audit ; } } package fi . koku . services . entity . customer . v1 ; public class CustomerServiceConstants { public static final String QUERY_SELECTION_BASIC = "" ; private CustomerServiceConstants ( ) { } } package fi . koku . services . entity . community . v1 ; public class CommunityServiceConstants { final public static String COMMUNITY_TYPE_GUARDIAN_COMMUNITY = "" ; final public static String COMMUNITY_TYPE_FAMILY = "" ; final public static String COMMUNITY_ROLE_DEPENDANT = "" ; final public static String COMMUNITY_ROLE_GUARDIAN = "" ; final public static String COMMUNITY_ROLE_PARENT = "" ; final public static String COMMUNITY_ROLE_FATHER = "" ; final public static String COMMUNITY_ROLE_MOTHER = "" ; final public static String COMMUNITY_ROLE_CHILD = "" ; final public static String MEMBERSHIP_REQUEST_STATUS_NEW = "" ; final public static String MEMBERSHIP_REQUEST_STATUS_APPROVED = "" ; final public static String MEMBERSHIP_REQUEST_STATUS_REJECTED = "" ; private CommunityServiceConstants ( ) { } } package fi . koku . services . entity . community . v1 ; import java . net . URL ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CommunityServiceFactory { private String uid ; private String pwd ; private String endpointBaseUrl ; private final URL wsdlLocation = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; private static Logger log = LoggerFactory . getLogger ( CommunityServiceFactory . class ) ; public CommunityServiceFactory ( String uid , String pwd , String endpointBaseUrl ) { this . uid = uid ; this . pwd = pwd ; this . endpointBaseUrl = endpointBaseUrl ; } public CommunityServicePortType getCommunityService ( ) { if ( wsdlLocation == null ) log . error ( "" ) ; CommunityService service = new CommunityService ( wsdlLocation , new QName ( "" , "" ) ) ; CommunityServicePortType port = service . getCommunityServiceSoap11Port ( ) ; String epAddr = endpointBaseUrl + "" ; log . debug ( "" + epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . USERNAME_PROPERTY , uid ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . PASSWORD_PROPERTY , pwd ) ; return port ; } public static AuditInfoType createAuditInfoType ( String component , String userPic ) { AuditInfoType audit = new AuditInfoType ( ) ; audit . setComponent ( component ) ; audit . setUserId ( userPic ) ; return audit ; } } package fi . koku . services . entity . customerservice . helper ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . services . entity . customerservice . model . CommunityRole ; import fi . koku . services . entity . customerservice . model . Message ; import fi . koku . services . entity . customerservice . model . Person ; import fi . koku . services . entity . community . v1 . CommunityServiceConstants ; import fi . koku . services . entity . community . v1 . CommunityServiceFactory ; import fi . koku . services . entity . community . v1 . CommunityServicePortType ; import fi . koku . services . entity . community . v1 . MembershipApprovalType ; import fi . koku . services . entity . community . v1 . MembershipApprovalsType ; import fi . koku . services . entity . community . v1 . MembershipRequestQueryCriteriaType ; import fi . koku . services . entity . community . v1 . MembershipRequestType ; import fi . koku . services . entity . community . v1 . MembershipRequestsType ; import fi . koku . services . entity . community . v1 . ServiceFault ; import fi . koku . services . entity . customer . v1 . CustomerQueryCriteriaType ; import fi . koku . services . entity . customer . v1 . CustomerServiceFactory ; import fi . koku . services . entity . customer . v1 . CustomerServicePortType ; import fi . koku . services . entity . customer . v1 . CustomerType ; import fi . koku . services . entity . customer . v1 . CustomersType ; import fi . koku . services . entity . customer . v1 . PicsType ; public class MessageHelper { private static Logger logger = LoggerFactory . getLogger ( MessageHelper . class ) ; private CustomerServicePortType customerService ; private CommunityServicePortType communityService ; private String componentName ; public MessageHelper ( CustomerServicePortType customerService , CommunityServicePortType communityService , String componentName ) { super ( ) ; this . customerService = customerService ; this . communityService = communityService ; this . componentName = componentName ; } public List < Message > getMessagesFor ( Person user , boolean userFamilyHasTwoParents , String newReqMessageText , String newReqMessageTextTwoParents ) throws ServiceFault , fi . koku . services . entity . customer . v1 . ServiceFault { List < Message > requestMessages = new ArrayList < Message > ( ) ; if ( user == null ) { return requestMessages ; } logger . debug ( "" + user . getPic ( ) ) ; MembershipRequestQueryCriteriaType membershipRequestQueryCriteria = new MembershipRequestQueryCriteriaType ( ) ; membershipRequestQueryCriteria . setApproverPic ( user . getPic ( ) ) ; MembershipRequestsType membershipRequestsType = communityService . opQueryMembershipRequests ( membershipRequestQueryCriteria , CommunityServiceFactory . createAuditInfoType ( componentName , user . getPic ( ) ) ) ; if ( membershipRequestsType != null ) { List < String > memberToAddPics = new ArrayList < String > ( ) ; List < String > messageIds = new ArrayList < String > ( ) ; List < String > senderPics = new ArrayList < String > ( ) ; List < String > userApprovalStatusList = new ArrayList < String > ( ) ; List < String > addedMemberRoles = new ArrayList < String > ( ) ; List < MembershipRequestType > membershipRequests = membershipRequestsType . getMembershipRequest ( ) ; Iterator < MembershipRequestType > mrti = membershipRequests . iterator ( ) ; while ( mrti . hasNext ( ) ) { MembershipRequestType membershipRequest = mrti . next ( ) ; memberToAddPics . add ( membershipRequest . getMemberPic ( ) ) ; messageIds . add ( membershipRequest . getId ( ) ) ; senderPics . add ( membershipRequest . getRequesterPic ( ) ) ; addedMemberRoles . add ( membershipRequest . getMemberRole ( ) ) ; MembershipApprovalsType membershipApprovalsType = membershipRequest . getApprovals ( ) ; List < MembershipApprovalType > approvals = membershipApprovalsType . getApproval ( ) ; Iterator < MembershipApprovalType > ait = approvals . iterator ( ) ; while ( ait . hasNext ( ) ) { MembershipApprovalType approval = ait . next ( ) ; String approverPic = approval . getApproverPic ( ) ; if ( approverPic . equals ( user . getPic ( ) ) ) { userApprovalStatusList . add ( approval . getStatus ( ) ) ; break ; } } } List < Person > requestSenders = getPersons ( senderPics , user . getPic ( ) ) ; List < Person > targetPersons = getPersons ( memberToAddPics , user . getPic ( ) ) ; Person requestSender = null ; Iterator < Person > targetPersonIterator = targetPersons . iterator ( ) ; Iterator < String > messageIdIterator = messageIds . iterator ( ) ; Iterator < String > memberToAddIterator = memberToAddPics . iterator ( ) ; Iterator < String > messageSenderIterator = senderPics . iterator ( ) ; Iterator < String > approvalStatusIterator = userApprovalStatusList . iterator ( ) ; Iterator < String > addedMemberRoleIterator = addedMemberRoles . iterator ( ) ; while ( messageIdIterator . hasNext ( ) ) { String messageId = messageIdIterator . next ( ) ; String memberToAddPic = memberToAddIterator . next ( ) ; String senderPic = messageSenderIterator . next ( ) ; String userApprovalStatus = approvalStatusIterator . next ( ) ; String addedMemberRole = addedMemberRoleIterator . next ( ) ; if ( CommunityServiceConstants . MEMBERSHIP_REQUEST_STATUS_NEW . equals ( userApprovalStatus ) ) { Iterator < Person > ri = requestSenders . iterator ( ) ; while ( ri . hasNext ( ) ) { Person sender = ri . next ( ) ; if ( sender . getPic ( ) . equals ( senderPic ) ) { requestSender = sender ; } } Person targetPerson = targetPersonIterator . next ( ) ; String senderName = "" ; String targetName = "" ; if ( addedMemberRole == null ) { addedMemberRole = "" ; } if ( requestSender != null ) { senderName = requestSender . getFullName ( ) ; } if ( targetPerson != null ) { targetName = targetPerson . getFullName ( ) ; } boolean twoParentsInFamily = false ; if ( memberToAddPic . equals ( user . getPic ( ) ) ) { twoParentsInFamily = userFamilyHasTwoParents ; } String messageText = "" ; if ( twoParentsInFamily ) { messageText = newReqMessageTextTwoParents . replace ( "" , senderName ) ; } else { messageText = newReqMessageText . replace ( "" , senderName ) . replace ( "" , targetName ) ; } Message message = new Message ( messageId , senderPic , memberToAddPic , addedMemberRole , messageText , twoParentsInFamily ) ; requestMessages . add ( message ) ; } } } return requestMessages ; } public List < Message > getSentMessages ( Person user , String sentReqMessageText ) throws ServiceFault , fi . koku . services . entity . customer . v1 . ServiceFault { List < Message > requestMessages = new ArrayList < Message > ( ) ; if ( user == null ) { return requestMessages ; } logger . debug ( "" + user . getPic ( ) ) ; MembershipRequestQueryCriteriaType membershipRequestQueryCriteria = new MembershipRequestQueryCriteriaType ( ) ; membershipRequestQueryCriteria . setRequesterPic ( user . getPic ( ) ) ; MembershipRequestsType membershipRequestsType = null ; membershipRequestsType = communityService . opQueryMembershipRequests ( membershipRequestQueryCriteria , CommunityServiceFactory . createAuditInfoType ( componentName , user . getPic ( ) ) ) ; if ( membershipRequestsType != null ) { List < String > memberToAddPics = new ArrayList < String > ( ) ; List < String > messageIds = new ArrayList < String > ( ) ; List < String > senderPics = new ArrayList < String > ( ) ; List < String > memberRoles = new ArrayList < String > ( ) ; List < MembershipRequestType > membershipRequests = membershipRequestsType . getMembershipRequest ( ) ; Iterator < MembershipRequestType > mrti = membershipRequests . iterator ( ) ; MembershipRequestType membershipRequest = null ; while ( mrti . hasNext ( ) ) { membershipRequest = mrti . next ( ) ; memberToAddPics . add ( membershipRequest . getMemberPic ( ) ) ; messageIds . add ( membershipRequest . getId ( ) ) ; senderPics . add ( membershipRequest . getRequesterPic ( ) ) ; memberRoles . add ( membershipRequest . getMemberRole ( ) ) ; } List < Person > membersToAdd = getPersons ( memberToAddPics , user . getPic ( ) ) ; Iterator < Person > pi = membersToAdd . iterator ( ) ; Iterator < String > messageIdIt = messageIds . iterator ( ) ; Iterator < String > senderPicIt = senderPics . iterator ( ) ; Iterator < String > memberRoleIt = memberRoles . iterator ( ) ; String targetPersonName = "" ; String messageId = "" ; String senderPic = "" ; String memberRole = "" ; while ( pi . hasNext ( ) ) { Person targetPerson = pi . next ( ) ; targetPersonName = targetPerson . getFullName ( ) ; messageId = messageIdIt . next ( ) ; senderPic = senderPicIt . next ( ) ; memberRole = memberRoleIt . next ( ) ; String messageText = sentReqMessageText . replace ( "" , targetPersonName ) ; Message message = new Message ( messageId , senderPic , "" , memberRole , messageText , false ) ; requestMessages . add ( message ) ; } } return requestMessages ; } private List < Person > getPersons ( List < String > pics , String currentUserPic ) throws fi . koku . services . entity . customer . v1 . ServiceFault { ArrayList < Person > persons = new ArrayList < Person > ( ) ; if ( pics == null || pics . size ( ) == ) { return persons ; } PicsType picsType = new PicsType ( ) ; picsType . getPic ( ) . addAll ( pics ) ; CustomerQueryCriteriaType customerQueryCriteria = new CustomerQueryCriteriaType ( ) ; customerQueryCriteria . setPics ( picsType ) ; CustomersType customersType = customerService . opQueryCustomers ( customerQueryCriteria , CustomerServiceFactory . createAuditInfoType ( componentName , currentUserPic ) ) ; if ( customersType != null ) { List < CustomerType > customers = customersType . getCustomer ( ) ; Iterator < CustomerType > ci = customers . iterator ( ) ; while ( ci . hasNext ( ) ) { persons . add ( new Person ( ci . next ( ) ) ) ; } } return persons ; } public void sendParentAdditionMessage ( String communityId , String memberToAddPic , String requesterPic , CommunityRole role ) throws ServiceFault { logger . debug ( "" ) ; logger . debug ( "" + communityId ) ; logger . debug ( "" + memberToAddPic ) ; logger . debug ( "" + requesterPic ) ; logger . debug ( "" + role . getRoleID ( ) ) ; fi . koku . services . entity . community . v1 . AuditInfoType communityAuditInfoType = CommunityServiceFactory . createAuditInfoType ( componentName , requesterPic ) ; MembershipRequestQueryCriteriaType membershipRequestQueryCriteria = new MembershipRequestQueryCriteriaType ( ) ; membershipRequestQueryCriteria . setRequesterPic ( requesterPic ) ; MembershipRequestsType membershipRequestsType = communityService . opQueryMembershipRequests ( membershipRequestQueryCriteria , communityAuditInfoType ) ; List < MembershipRequestType > membershipRequests = membershipRequestsType . getMembershipRequest ( ) ; Iterator < MembershipRequestType > mri = membershipRequests . iterator ( ) ; while ( mri . hasNext ( ) ) { MembershipRequestType request = mri . next ( ) ; CommunityRole requestRole = CommunityRole . createFromRoleID ( request . getMemberRole ( ) ) ; if ( CommunityRole . FATHER . equals ( requestRole ) || CommunityRole . MOTHER . equals ( requestRole ) || CommunityRole . PARENT . equals ( requestRole ) ) { return ; } } MembershipApprovalType membershipApproval = new MembershipApprovalType ( ) ; membershipApproval . setApproverPic ( memberToAddPic ) ; membershipApproval . setStatus ( CommunityServiceConstants . MEMBERSHIP_REQUEST_STATUS_NEW ) ; MembershipApprovalsType membershipApprovalsType = new MembershipApprovalsType ( ) ; membershipApprovalsType . getApproval ( ) . add ( membershipApproval ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "" ) ; Iterator < MembershipApprovalType > mi = membershipApprovalsType . getApproval ( ) . iterator ( ) ; while ( mi . hasNext ( ) ) { MembershipApprovalType approval = mi . next ( ) ; logger . debug ( "" + approval . getApproverPic ( ) + "" + approval . getStatus ( ) ) ; } } MembershipRequestType membershipRequest = new MembershipRequestType ( ) ; membershipRequest . setCommunityId ( communityId ) ; membershipRequest . setMemberRole ( role . getRoleID ( ) ) ; membershipRequest . setMemberPic ( memberToAddPic ) ; membershipRequest . setRequesterPic ( requesterPic ) ; membershipRequest . setApprovals ( membershipApprovalsType ) ; communityService . opAddMembershipRequest ( membershipRequest , communityAuditInfoType ) ; } public void sendFamilyAdditionMessage ( String communityId , List < String > recipients , String requesterPic , String memberToAddPic , CommunityRole role ) throws ServiceFault { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "" ) ; logger . debug ( "" + communityId ) ; logger . debug ( "" ) ; Iterator < String > ri = recipients . iterator ( ) ; while ( ri . hasNext ( ) ) { String recipientPic = ri . next ( ) ; logger . debug ( "" + recipientPic ) ; } logger . debug ( "" + requesterPic ) ; logger . debug ( "" + memberToAddPic ) ; logger . debug ( "" + role . getRoleID ( ) ) ; } fi . koku . services . entity . community . v1 . AuditInfoType communityAuditInfoType = CommunityServiceFactory . createAuditInfoType ( componentName , requesterPic ) ; MembershipRequestQueryCriteriaType membershipRequestQueryCriteria = new MembershipRequestQueryCriteriaType ( ) ; membershipRequestQueryCriteria . setRequesterPic ( requesterPic ) ; MembershipRequestsType membershipRequestsType = communityService . opQueryMembershipRequests ( membershipRequestQueryCriteria , communityAuditInfoType ) ; List < MembershipRequestType > membershipRequests = membershipRequestsType . getMembershipRequest ( ) ; Iterator < MembershipRequestType > mri = membershipRequests . iterator ( ) ; while ( mri . hasNext ( ) ) { MembershipRequestType request = mri . next ( ) ; if ( request . getMemberPic ( ) . equals ( memberToAddPic ) ) { return ; } } MembershipApprovalsType membershipApprovalsType = new MembershipApprovalsType ( ) ; Iterator < String > recipientsIterator = recipients . iterator ( ) ; while ( recipientsIterator . hasNext ( ) ) { String approverPic = recipientsIterator . next ( ) ; MembershipApprovalType membershipApproval = new MembershipApprovalType ( ) ; membershipApproval . setApproverPic ( approverPic ) ; membershipApproval . setStatus ( "" ) ; membershipApprovalsType . getApproval ( ) . add ( membershipApproval ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "" ) ; Iterator < MembershipApprovalType > mi = membershipApprovalsType . getApproval ( ) . iterator ( ) ; while ( mi . hasNext ( ) ) { MembershipApprovalType approval = mi . next ( ) ; logger . debug ( "" + approval . getApproverPic ( ) + "" + approval . getStatus ( ) ) ; } } MembershipRequestType membershipRequest = new MembershipRequestType ( ) ; membershipRequest . setCommunityId ( communityId ) ; membershipRequest . setMemberRole ( role . getRoleID ( ) ) ; membershipRequest . setMemberPic ( memberToAddPic ) ; membershipRequest . setRequesterPic ( requesterPic ) ; membershipRequest . setApprovals ( membershipApprovalsType ) ; communityService . opAddMembershipRequest ( membershipRequest , communityAuditInfoType ) ; } } package fi . koku . services . entity . customerservice . helper ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . services . entity . community . v1 . CommunitiesType ; import fi . koku . services . entity . community . v1 . CommunityQueryCriteriaType ; import fi . koku . services . entity . community . v1 . CommunityServiceConstants ; import fi . koku . services . entity . community . v1 . CommunityServiceFactory ; import fi . koku . services . entity . community . v1 . CommunityServicePortType ; import fi . koku . services . entity . community . v1 . CommunityType ; import fi . koku . services . entity . community . v1 . MemberPicsType ; import fi . koku . services . entity . community . v1 . MemberType ; import fi . koku . services . entity . community . v1 . MembersType ; import fi . koku . services . entity . community . v1 . ServiceFault ; import fi . koku . services . entity . customer . v1 . CustomerQueryCriteriaType ; import fi . koku . services . entity . customer . v1 . CustomerServiceConstants ; import fi . koku . services . entity . customer . v1 . CustomerServiceFactory ; import fi . koku . services . entity . customer . v1 . CustomerServicePortType ; import fi . koku . services . entity . customer . v1 . CustomerType ; import fi . koku . services . entity . customer . v1 . CustomersType ; import fi . koku . services . entity . customer . v1 . PicsType ; import fi . koku . services . entity . customerservice . exception . FamilyNotFoundException ; import fi . koku . services . entity . customerservice . exception . TooManyFamiliesException ; import fi . koku . services . entity . customerservice . model . CommunityRole ; import fi . koku . services . entity . customerservice . model . Dependant ; import fi . koku . services . entity . customerservice . model . DependantsAndFamily ; import fi . koku . services . entity . customerservice . model . Family ; import fi . koku . services . entity . customerservice . model . FamilyIdAndFamilyMembers ; import fi . koku . services . entity . customerservice . model . FamilyMember ; import fi . koku . services . entity . customerservice . model . Message ; import fi . koku . services . entity . customerservice . model . Person ; public class FamilyHelper { private static Logger logger = LoggerFactory . getLogger ( FamilyHelper . class ) ; private CustomerServicePortType customerService ; private CommunityServicePortType communityService ; private String componentName ; public FamilyHelper ( CustomerServicePortType customerService , CommunityServicePortType communityService , String componentName ) { super ( ) ; this . customerService = customerService ; this . communityService = communityService ; this . componentName = componentName ; } public DependantsAndFamily getDependantsAndFamily ( String userPic , Family userFamily ) throws fi . koku . services . entity . community . v1 . ServiceFault , fi . koku . services . entity . customer . v1 . ServiceFault { List < Dependant > dependants = new ArrayList < Dependant > ( ) ; CommunityQueryCriteriaType communityQueryCriteria = new CommunityQueryCriteriaType ( ) ; communityQueryCriteria . setCommunityType ( CommunityServiceConstants . COMMUNITY_TYPE_GUARDIAN_COMMUNITY ) ; MemberPicsType memberPics = new MemberPicsType ( ) ; memberPics . getMemberPic ( ) . add ( userPic ) ; communityQueryCriteria . setMemberPics ( memberPics ) ; CommunitiesType communitiesType = communityService . opQueryCommunities ( communityQueryCriteria , CommunityServiceFactory . createAuditInfoType ( componentName , userPic ) ) ; ArrayList < String > depPics = new ArrayList < String > ( ) ; if ( communitiesType != null ) { List < CommunityType > communities = communitiesType . getCommunity ( ) ; Iterator < CommunityType > ci = communities . iterator ( ) ; while ( ci . hasNext ( ) ) { CommunityType community = ci . next ( ) ; MembersType membersType = community . getMembers ( ) ; List < MemberType > members = membersType . getMember ( ) ; Iterator < MemberType > mi = members . iterator ( ) ; while ( mi . hasNext ( ) ) { MemberType member = mi . next ( ) ; if ( member . getRole ( ) . equals ( CommunityServiceConstants . COMMUNITY_ROLE_DEPENDANT ) ) { depPics . add ( member . getPic ( ) ) ; } } } } DependantsAndFamily dependantsAndFamily = new DependantsAndFamily ( ) ; if ( depPics . size ( ) > ) { PicsType picsType = new PicsType ( ) ; picsType . getPic ( ) . addAll ( depPics ) ; CustomerQueryCriteriaType customerQueryCriteriaType = new CustomerQueryCriteriaType ( ) ; customerQueryCriteriaType . setPics ( picsType ) ; CustomersType customersType = null ; customersType = customerService . opQueryCustomers ( customerQueryCriteriaType , CustomerServiceFactory . createAuditInfoType ( componentName , userPic ) ) ; if ( customersType != null ) { List < CustomerType > customers = customersType . getCustomer ( ) ; Iterator < CustomerType > ci = customers . iterator ( ) ; while ( ci . hasNext ( ) ) { CustomerType customer = ci . next ( ) ; dependants . add ( new Dependant ( customer ) ) ; } } if ( userFamily != null && dependants . size ( ) > ) { Iterator < Dependant > di = dependants . iterator ( ) ; while ( di . hasNext ( ) ) { Dependant d = di . next ( ) ; List < MemberType > members = userFamily . getAllMembers ( ) ; Iterator < MemberType > mi = members . iterator ( ) ; while ( mi . hasNext ( ) ) { MemberType member = mi . next ( ) ; if ( d . getPic ( ) . equals ( member . getPic ( ) ) ) { d . setMemberOfUserFamily ( true ) ; } } } dependantsAndFamily . setFamily ( userFamily ) ; } } dependantsAndFamily . setDependants ( dependants ) ; if ( logger . isDebugEnabled ( ) ) { Iterator < Dependant > it = dependants . iterator ( ) ; logger . debug ( "" ) ; while ( it . hasNext ( ) ) { logger . debug ( "" + it . next ( ) . getPic ( ) ) ; } logger . debug ( "" ) ; } return dependantsAndFamily ; } public FamilyIdAndFamilyMembers getOtherFamilyMembers ( String userPic , Family family ) throws ServiceFault , fi . koku . services . entity . customer . v1 . ServiceFault { List < Dependant > dependants = getDependantsAndFamily ( userPic , family ) . getDependants ( ) ; Set < String > dependantPics = new HashSet < String > ( ) ; Iterator < Dependant > di = dependants . iterator ( ) ; while ( di . hasNext ( ) ) { dependantPics . add ( di . next ( ) . getPic ( ) ) ; } List < FamilyMember > otherFamilyMembers = new ArrayList < FamilyMember > ( ) ; CommunityQueryCriteriaType communityQueryCriteria = new CommunityQueryCriteriaType ( ) ; communityQueryCriteria . setCommunityType ( CommunityServiceConstants . COMMUNITY_TYPE_FAMILY ) ; MemberPicsType memberPics = new MemberPicsType ( ) ; memberPics . getMemberPic ( ) . add ( userPic ) ; communityQueryCriteria . setMemberPics ( memberPics ) ; CommunitiesType communitiesType = communityService . opQueryCommunities ( communityQueryCriteria , CommunityServiceFactory . createAuditInfoType ( componentName , userPic ) ) ; String familyId = "" ; if ( communitiesType != null ) { List < CommunityType > communities = communitiesType . getCommunity ( ) ; Iterator < CommunityType > ci = communities . iterator ( ) ; List < String > otherFamilyMemberPics = new ArrayList < String > ( ) ; List < String > otherFamilyMemberRoles = new ArrayList < String > ( ) ; while ( ci . hasNext ( ) ) { CommunityType community = ci . next ( ) ; familyId = community . getId ( ) ; MembersType membersType = community . getMembers ( ) ; List < MemberType > members = membersType . getMember ( ) ; Iterator < MemberType > mi = members . iterator ( ) ; while ( mi . hasNext ( ) ) { MemberType member = mi . next ( ) ; if ( ! dependantPics . contains ( member . getPic ( ) ) && ! userPic . equals ( member . getPic ( ) ) ) { otherFamilyMemberPics . add ( member . getPic ( ) ) ; otherFamilyMemberRoles . add ( member . getRole ( ) ) ; } } } if ( otherFamilyMemberPics . size ( ) > ) { CustomersType customersType = null ; CustomerQueryCriteriaType customerCriteria = new CustomerQueryCriteriaType ( ) ; PicsType picsType = new PicsType ( ) ; picsType . getPic ( ) . addAll ( otherFamilyMemberPics ) ; customerCriteria . setPics ( picsType ) ; customerCriteria . setSelection ( CustomerServiceConstants . QUERY_SELECTION_BASIC ) ; customersType = customerService . opQueryCustomers ( customerCriteria , CustomerServiceFactory . createAuditInfoType ( componentName , userPic ) ) ; if ( customersType != null ) { Iterator < CustomerType > customerIterator = customersType . getCustomer ( ) . iterator ( ) ; Iterator < String > roleIterator = otherFamilyMemberRoles . iterator ( ) ; while ( customerIterator . hasNext ( ) ) { CustomerType customer = customerIterator . next ( ) ; String role = roleIterator . next ( ) ; otherFamilyMembers . add ( new FamilyMember ( customer , CommunityRole . createFromRoleID ( role ) ) ) ; } } } } if ( logger . isDebugEnabled ( ) ) { Iterator < FamilyMember > it = otherFamilyMembers . iterator ( ) ; logger . debug ( "" ) ; while ( it . hasNext ( ) ) { logger . debug ( "" + it . next ( ) . getPic ( ) ) ; } } FamilyIdAndFamilyMembers fidm = new FamilyIdAndFamilyMembers ( ) ; fidm . setFamilyMembers ( otherFamilyMembers ) ; fidm . setFamilyId ( familyId ) ; return fidm ; } private Set < String > getDependantPics ( String userPic ) throws ServiceFault , fi . koku . services . entity . customer . v1 . ServiceFault { Set < String > dependantPics = new HashSet < String > ( ) ; List < Dependant > dependants = getDependantsAndFamily ( userPic , null ) . getDependants ( ) ; Iterator < Dependant > di = dependants . iterator ( ) ; while ( di . hasNext ( ) ) { dependantPics . add ( di . next ( ) . getPic ( ) ) ; } return dependantPics ; } private Set < String > getFamilyMemberPics ( String userPic ) throws ServiceFault , fi . koku . services . entity . customer . v1 . ServiceFault { Set < String > familyMemberPics = new HashSet < String > ( ) ; List < FamilyMember > familyMembers = getOtherFamilyMembers ( userPic , null ) . getFamilyMembers ( ) ; Iterator < FamilyMember > fmi = familyMembers . iterator ( ) ; while ( fmi . hasNext ( ) ) { familyMemberPics . add ( fmi . next ( ) . getPic ( ) ) ; } return familyMemberPics ; } public List < Person > searchUsers ( String surname , String customerPic , String currentUserPic ) throws ServiceFault , fi . koku . services . entity . customer . v1 . ServiceFault { CustomerQueryCriteriaType customerCriteria = new CustomerQueryCriteriaType ( ) ; PicsType pics = new PicsType ( ) ; pics . getPic ( ) . add ( customerPic ) ; customerCriteria . setPics ( pics ) ; CustomersType customersType = customerService . opQueryCustomers ( customerCriteria , CustomerServiceFactory . createAuditInfoType ( componentName , currentUserPic ) ) ; Set < String > depPics = getDependantPics ( currentUserPic ) ; Set < String > familyMemberPics = getFamilyMemberPics ( currentUserPic ) ; List < Person > searchedUsers = new ArrayList < Person > ( ) ; if ( customersType != null ) { List < CustomerType > customers = customersType . getCustomer ( ) ; Iterator < CustomerType > ci = customers . iterator ( ) ; while ( ci . hasNext ( ) ) { CustomerType customer = ci . next ( ) ; if ( ! depPics . contains ( customer . getHenkiloTunnus ( ) ) && ! familyMemberPics . contains ( customer . getHenkiloTunnus ( ) ) && ! currentUserPic . equals ( customer . getHenkiloTunnus ( ) ) && surname . equalsIgnoreCase ( customer . getSukuNimi ( ) ) ) { searchedUsers . add ( new Person ( customer ) ) ; } } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "" ) ; Iterator < Person > pi = searchedUsers . iterator ( ) ; while ( pi . hasNext ( ) ) { Person p = pi . next ( ) ; logger . debug ( "" + p . getPic ( ) ) ; } } return searchedUsers ; } public Family getFamily ( String pic ) throws TooManyFamiliesException , FamilyNotFoundException , ServiceFault { List < Family > families = new ArrayList < Family > ( ) ; CommunityQueryCriteriaType communityCriteria = new CommunityQueryCriteriaType ( ) ; communityCriteria . setCommunityType ( CommunityServiceConstants . COMMUNITY_TYPE_FAMILY ) ; MemberPicsType memberPics = new MemberPicsType ( ) ; memberPics . getMemberPic ( ) . add ( pic ) ; communityCriteria . setMemberPics ( memberPics ) ; CommunitiesType communitiesType = communityService . opQueryCommunities ( communityCriteria , CommunityServiceFactory . createAuditInfoType ( componentName , pic ) ) ; if ( communitiesType != null ) { List < CommunityType > communities = communitiesType . getCommunity ( ) ; Iterator < CommunityType > ci = communities . iterator ( ) ; if ( ! ci . hasNext ( ) ) { throw new FamilyNotFoundException ( "" + pic + "" ) ; } while ( ci . hasNext ( ) ) { CommunityType community = ci . next ( ) ; families . add ( new Family ( community ) ) ; } if ( families . size ( ) > ) { throw new TooManyFamiliesException ( "" + pic + "" ) ; } else if ( families . size ( ) > ) { Family family = families . get ( ) ; logger . debug ( "" + family . getCommunityId ( ) ) ; return family ; } } logger . debug ( "" ) ; return null ; } public boolean isParentsSet ( String userPic , Family family ) { if ( family != null ) { logger . debug ( "" + family . isParentsSet ( ) ) ; return family . isParentsSet ( ) ; } logger . debug ( "" ) ; return false ; } } package fi . koku . services . entity . customerservice . model ; import fi . koku . services . entity . customer . v1 . CustomerType ; public class Dependant extends Person { private boolean memberOfUserFamily ; public Dependant ( CustomerType customer ) { super ( customer ) ; memberOfUserFamily = false ; } public boolean getMemberOfUserFamily ( ) { return memberOfUserFamily ; } public void setMemberOfUserFamily ( boolean isMember ) { this . memberOfUserFamily = isMember ; } } package fi . koku . services . entity . customerservice . model ; import fi . koku . services . entity . customerservice . model . CommunityRole ; import fi . koku . services . entity . customer . v1 . CustomerType ; public class FamilyMember extends Person { private CommunityRole role ; public FamilyMember ( CustomerType customer , CommunityRole role ) { super ( customer ) ; this . role = role ; } public String getRoleId ( ) { return role . getRoleID ( ) ; } public CommunityRole getRole ( ) { return role ; } @ Override public String toString ( ) { return super . toString ( ) + "" + role + "" ; } } package fi . koku . services . entity . customerservice . model ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import fi . koku . services . entity . customerservice . model . CommunityRole ; import fi . koku . services . entity . community . v1 . CommunityType ; import fi . koku . services . entity . community . v1 . MemberType ; import fi . koku . services . entity . community . v1 . MembersType ; public class Family { private CommunityType community ; public Family ( ) { } public Family ( CommunityType community ) { this . community = community ; } public String getCommunityId ( ) { return community . getId ( ) ; } public String getCommunityType ( ) { return community . getType ( ) ; } public String getCommunityName ( ) { return community . getName ( ) ; } public MembersType getCommunityMembers ( ) { return community . getMembers ( ) ; } public CommunityType getCommunity ( ) { return community ; } public void combineFamily ( Family family ) { for ( MemberType member : family . getAllMembers ( ) ) { addFamilyMember ( member . getPic ( ) , member . getRole ( ) ) ; } } public MemberType getOtherParent ( String notWantedParentPic ) { for ( MemberType m : getParents ( ) ) { if ( ! m . getPic ( ) . equals ( notWantedParentPic ) ) { return m ; } } return null ; } public void addFamilyMember ( String memberPic , String role ) { MembersType membersType = community . getMembers ( ) ; List < MemberType > members = membersType . getMember ( ) ; MemberType newMember = new MemberType ( ) ; newMember . setPic ( memberPic ) ; newMember . setRole ( role ) ; members . add ( newMember ) ; } public List < MemberType > getParents ( ) { List < MemberType > parents = new ArrayList < MemberType > ( ) ; MembersType membersType = community . getMembers ( ) ; List < MemberType > members = membersType . getMember ( ) ; Iterator < MemberType > mi = members . iterator ( ) ; while ( mi . hasNext ( ) ) { MemberType member = mi . next ( ) ; CommunityRole memberRole = CommunityRole . createFromRoleID ( member . getRole ( ) ) ; if ( CommunityRole . PARENT . equals ( memberRole ) || CommunityRole . MOTHER . equals ( memberRole ) || CommunityRole . FATHER . equals ( memberRole ) ) { parents . add ( member ) ; } } return parents ; } public List < MemberType > getAllMembers ( ) { MembersType membersType = community . getMembers ( ) ; List < MemberType > members = membersType . getMember ( ) ; return members ; } public boolean isParentsSet ( ) { return getParents ( ) . size ( ) >= ; } } package fi . koku . services . entity . customerservice . model ; import java . util . Iterator ; import java . util . List ; import fi . koku . services . entity . customer . v1 . CustomerType ; import fi . koku . services . entity . customer . v1 . ElectronicContactInfoType ; import fi . koku . services . entity . customer . v1 . ElectronicContactInfosType ; public class Person { private boolean requestPending ; private CustomerType customer ; public Person ( CustomerType customer ) { this . customer = customer ; } public String getFirstname ( ) { return customer . getEtuNimi ( ) ; } public String getFirstnames ( ) { return customer . getEtunimetNimi ( ) ; } public String getSurname ( ) { return customer . getSukuNimi ( ) ; } public String getPic ( ) { return customer . getHenkiloTunnus ( ) ; } public String getBirthdate ( ) { return customer . getSyntymaPvm ( ) . toString ( ) ; } public String getEcontactinfo ( ) { String electronicContactInfo = "" ; ElectronicContactInfosType contactInfoType = customer . getElectronicContactInfos ( ) ; if ( contactInfoType != null ) { List < ElectronicContactInfoType > contactInfos = contactInfoType . getEContactInfo ( ) ; Iterator < ElectronicContactInfoType > cii = contactInfos . iterator ( ) ; while ( cii . hasNext ( ) ) { ElectronicContactInfoType contactInfo = cii . next ( ) ; String info = contactInfo . getContactInfo ( ) ; electronicContactInfo += info + "" ; } } return electronicContactInfo ; } public String getFullName ( ) { return getFirstname ( ) + "" + getSurname ( ) ; } public String getCapFullName ( ) { return ( getFirstname ( ) + "" + getSurname ( ) + "" + getPic ( ) ) . toUpperCase ( ) ; } public boolean isRequestPending ( ) { return this . requestPending ; } public void setRequestPending ( boolean requestPending ) { this . requestPending = requestPending ; } @ Override public String toString ( ) { return "" + getFirstname ( ) + "" + getSurname ( ) + "" + getPic ( ) + "" ; } } package fi . koku . services . entity . customerservice . model ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class Message { private static Logger log = LoggerFactory . getLogger ( Message . class ) ; private String id ; private String from ; private String role ; private String text ; private boolean twoParentsInFamily ; private String memberToAddPic ; public Message ( String id , String fromUserPic , String memberToAddPic , String role , String text , boolean twoParentsInFamily ) { log . debug ( "" ) ; log . debug ( "" + id ) ; log . debug ( "" + fromUserPic ) ; log . debug ( "" + role ) ; log . debug ( "" + text ) ; this . id = id ; this . from = fromUserPic ; this . role = role ; this . text = text ; this . twoParentsInFamily = twoParentsInFamily ; this . memberToAddPic = memberToAddPic ; } public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getFrom ( ) { return from ; } public void setFrom ( String from ) { this . from = from ; } public String getRole ( ) { return role ; } public void setRole ( String role ) { this . role = role ; } public String getText ( ) { return text ; } public void setText ( String text ) { this . text = text ; } public boolean getTwoParentsInFamily ( ) { return twoParentsInFamily ; } public String getMemberToAddPic ( ) { return memberToAddPic ; } } package fi . koku . services . entity . customerservice . model ; import java . util . List ; public class DependantsAndFamily { private Family family ; private List < Dependant > dependants ; public DependantsAndFamily ( ) { } public void setDependants ( List < Dependant > dependants ) { this . dependants = dependants ; } public void setFamily ( Family family ) { this . family = family ; } public List < Dependant > getDependants ( ) { return dependants ; } public Family getFamily ( ) { return family ; } } package fi . koku . services . entity . customerservice . model ; import java . util . List ; public class FamilyIdAndFamilyMembers { private String familyId ; private List < FamilyMember > familyMembers ; public FamilyIdAndFamilyMembers ( ) { } public void setFamilyMembers ( List < FamilyMember > members ) { this . familyMembers = members ; } public void setFamilyId ( String id ) { this . familyId = id ; } public List < FamilyMember > getFamilyMembers ( ) { return familyMembers ; } public String getFamilyId ( ) { return familyId ; } } package fi . koku . services . entity . customerservice . model ; public enum CommunityRole { FATHER ( "" ) , MOTHER ( "" ) , FAMILY_MEMBER ( "" ) , DEPENDANT ( "" ) , CHILD ( "" ) , PARENT ( "" ) , GUARDIAN ( "" ) ; private String roleID ; private CommunityRole ( String roleID ) { this . roleID = roleID ; } public static CommunityRole create ( String text ) { for ( CommunityRole r : values ( ) ) { if ( r . toString ( ) . equals ( text ) ) { return r ; } } return CommunityRole . FAMILY_MEMBER ; } public static CommunityRole createFromRoleID ( String roleID ) { for ( CommunityRole r : values ( ) ) { if ( r . getRoleID ( ) . equals ( roleID ) ) { return r ; } } return CommunityRole . FAMILY_MEMBER ; } public String getRoleID ( ) { return roleID ; } } package fi . koku . services . entity . customerservice . exception ; public class GuardianForChildNotFoundException extends Exception { private static final long serialVersionUID = - ; public GuardianForChildNotFoundException ( String message ) { super ( message ) ; } } package fi . koku . services . entity . customerservice . exception ; public class TooManyFamiliesException extends Exception { private static final long serialVersionUID = ; public TooManyFamiliesException ( String message ) { super ( message ) ; } } package fi . koku . services . entity . customerservice . exception ; public class FamilyNotFoundException extends Exception { private static final long serialVersionUID = ; public FamilyNotFoundException ( String message ) { super ( message ) ; } } package fi . koku . services . entity . userinformation ; import fi . koku . settings . KoKuPropertiesUtil ; public class UserInformationConstants { final public static String USER_INFORMATION_SERVICE_FULL_URL = KoKuPropertiesUtil . get ( "" ) ; } package fi . koku . services . entity . userinformation . v1 ; import java . net . URL ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . tampere . contract . municipalityportal . uis . UserInformationService ; import fi . tampere . contract . municipalityportal . uis . UserInformationServicePortType ; public class UserInformationServiceFactory { private String uid ; private String pwd ; private String endpointUrl ; private final URL wsdlLocation = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; private static Logger log = LoggerFactory . getLogger ( UserInformationServiceFactory . class ) ; public UserInformationServiceFactory ( String uid , String pwd , String endpointUrl ) { this . uid = uid ; this . pwd = pwd ; this . endpointUrl = endpointUrl ; } public UserInformationServicePortType getUserInformationService ( ) { if ( wsdlLocation == null ) log . error ( "" ) ; UserInformationService service = new UserInformationService ( wsdlLocation , new QName ( "" , "" ) ) ; UserInformationServicePortType port = service . getUserInformationServicePort ( ) ; String epAddr = endpointUrl ; log . debug ( "" + epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . USERNAME_PROPERTY , uid ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . PASSWORD_PROPERTY , pwd ) ; return port ; } } package fi . koku . services . common . kahva ; import java . net . URL ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . arcusys . tampere . hrsoa . ws . ldap . LdapService ; import fi . arcusys . tampere . hrsoa . ws . ldap . LdapService_Service ; public class LdapServiceFactory { private String epAddr ; private final URL wsdlLocation = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; private static Logger log = LoggerFactory . getLogger ( LdapServiceFactory . class ) ; public LdapServiceFactory ( String endpointAddr ) { this . epAddr = endpointAddr ; } public LdapService getOrganizationService ( ) { if ( wsdlLocation == null ) log . error ( "" ) ; LdapService_Service service = new LdapService_Service ( wsdlLocation , new QName ( "" , "" ) ) ; log . debug ( "" + epAddr ) ; LdapService port = service . getLdapServiceSOAP ( ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; return port ; } } package fi . koku . services . entity . family ; import fi . koku . settings . KoKuPropertiesUtil ; public class FamilyConstants { final public static String CUSTOMER_SERVICE_ENDPOINT = KoKuPropertiesUtil . get ( "" ) ; final public static String COMMUNITY_SERVICE_ENDPOINT = KoKuPropertiesUtil . get ( "" ) ; final public static String COMMUNITY_TYPE_GUARDIAN_COMMUNITY = "" ; final public static String COMMUNITY_TYPE_FAMILY = "" ; final public static String ROLE_DEPENDANT = "" ; final public static String ROLE_GUARDIAN = "" ; } package fi . koku . services . entity . family . v1 ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . services . entity . community . v1 . CommunityQueryCriteriaType ; import fi . koku . services . entity . community . v1 . CommunityServiceFactory ; import fi . koku . services . entity . community . v1 . CommunityServicePortType ; import fi . koku . services . entity . community . v1 . CommunityType ; import fi . koku . services . entity . community . v1 . MemberPicsType ; import fi . koku . services . entity . community . v1 . MemberType ; import fi . koku . services . entity . community . v1 . ServiceFault ; import fi . koku . services . entity . customer . v1 . CustomerQueryCriteriaType ; import fi . koku . services . entity . customer . v1 . CustomerServiceFactory ; import fi . koku . services . entity . customer . v1 . CustomerServicePortType ; import fi . koku . services . entity . customer . v1 . CustomerType ; import fi . koku . services . entity . customer . v1 . CustomersType ; import fi . koku . services . entity . customer . v1 . PicsType ; import fi . koku . services . entity . family . FamilyConstants ; public class FamilyService { private static final Logger LOG = LoggerFactory . getLogger ( FamilyService . class ) ; private CustomerServicePortType customerService ; private CommunityServicePortType communityService ; public FamilyService ( String customerServiceUserId , String customerServicePassword , String communityServiceUserId , String communityServicePassword ) { CustomerServiceFactory customerServiceFactory = new CustomerServiceFactory ( customerServiceUserId , customerServicePassword , FamilyConstants . CUSTOMER_SERVICE_ENDPOINT ) ; customerService = customerServiceFactory . getCustomerService ( ) ; CommunityServiceFactory communityServiceFactory = new CommunityServiceFactory ( communityServiceUserId , communityServicePassword , FamilyConstants . COMMUNITY_SERVICE_ENDPOINT ) ; communityService = communityServiceFactory . getCommunityService ( ) ; } public List < CustomerType > getPersonsChildren ( String pic , String auditUserId , String auditComponentId ) throws Exception { List < CustomerType > children = new ArrayList < CustomerType > ( ) ; List < CommunityType > communities = null ; Set < String > memberPics = new HashSet < String > ( ) ; try { communities = searchPersonsCommunitiesByPic ( pic , auditUserId , auditComponentId ) ; if ( communities != null && communities . size ( ) > ) { for ( CommunityType community : communities ) { List < MemberType > members = community . getMembers ( ) . getMember ( ) ; memberPics . addAll ( filterMemberPicsWithRole ( members , FamilyConstants . ROLE_DEPENDANT ) ) ; } children = searchPersonsByPicList ( memberPics , auditUserId , auditComponentId ) ; } else { LOG . debug ( "" + pic ) ; } } catch ( fi . koku . services . entity . community . v1 . ServiceFault communityFault ) { LOG . error ( "" , communityFault ) ; } return children ; } public List < CustomerType > getPersonsParents ( String pic , String auditUserId , String auditComponentId ) throws Exception { List < CustomerType > parents = new ArrayList < CustomerType > ( ) ; List < CommunityType > communities = null ; Set < String > memberPics = new HashSet < String > ( ) ; try { communities = searchPersonsCommunitiesByPic ( pic , auditUserId , auditComponentId ) ; if ( communities != null && communities . size ( ) > ) { for ( CommunityType community : communities ) { List < MemberType > members = community . getMembers ( ) . getMember ( ) ; memberPics . addAll ( filterMemberPicsWithRole ( members , FamilyConstants . ROLE_GUARDIAN ) ) ; memberPics . remove ( pic ) ; parents = searchPersonsByPicList ( memberPics , auditUserId , auditComponentId ) ; } } else { LOG . debug ( "" + pic ) ; } } catch ( fi . koku . services . entity . community . v1 . ServiceFault communityFault ) { LOG . error ( "" , communityFault ) ; } return parents ; } private List < CustomerType > searchPersonsByPicList ( Set < String > memberPics , String auditUserId , String auditComponentId ) throws fi . koku . services . entity . customer . v1 . ServiceFault { if ( memberPics == null || memberPics . isEmpty ( ) ) { return new ArrayList < CustomerType > ( ) ; } CustomerQueryCriteriaType query = new CustomerQueryCriteriaType ( ) ; fi . koku . services . entity . customer . v1 . AuditInfoType customerAuditInfoType = new fi . koku . services . entity . customer . v1 . AuditInfoType ( ) ; customerAuditInfoType . setComponent ( auditComponentId ) ; customerAuditInfoType . setUserId ( auditUserId ) ; PicsType picsType = new PicsType ( ) ; for ( String memberPic : memberPics ) { picsType . getPic ( ) . add ( memberPic ) ; } query . setPics ( picsType ) ; CustomersType customersType = customerService . opQueryCustomers ( query , customerAuditInfoType ) ; return customersType . getCustomer ( ) ; } private List < CommunityType > searchPersonsCommunitiesByPic ( String pic , String auditUserId , String auditComponentId ) throws ServiceFault { List < CommunityType > communities ; fi . koku . services . entity . community . v1 . AuditInfoType communityAuditInfoType = new fi . koku . services . entity . community . v1 . AuditInfoType ( ) ; communityAuditInfoType . setComponent ( auditComponentId ) ; communityAuditInfoType . setUserId ( auditUserId ) ; CommunityQueryCriteriaType criteria = new CommunityQueryCriteriaType ( ) ; MemberPicsType picsType = new MemberPicsType ( ) ; picsType . getMemberPic ( ) . add ( pic ) ; criteria . setMemberPics ( picsType ) ; criteria . setCommunityType ( FamilyConstants . COMMUNITY_TYPE_GUARDIAN_COMMUNITY ) ; communities = communityService . opQueryCommunities ( criteria , communityAuditInfoType ) . getCommunity ( ) ; LOG . debug ( "" + pic + "" + FamilyConstants . COMMUNITY_TYPE_GUARDIAN_COMMUNITY + "" + "" + communityAuditInfoType . getUserId ( ) + "" + communityAuditInfoType . getComponent ( ) + "" + communities . size ( ) ) ; return communities ; } private Set < String > filterMemberPicsWithRole ( List < MemberType > members , final String roleId ) { Set < String > pics = null ; if ( members != null && roleId != null ) { pics = new HashSet < String > ( members . size ( ) ) ; for ( MemberType m : members ) { if ( roleId . equals ( m . getRole ( ) ) ) { if ( m . getPic ( ) != null ) { pics . add ( m . getPic ( ) ) ; } } else { LOG . debug ( "" + m . getPic ( ) + "" + m . getRole ( ) + "" ) ; } } } return pics ; } } package fi . koku . services . utility . log . v1 ; import java . net . URL ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class LogServiceFactory { private String uid ; private String pwd ; private String endpointBaseUrl ; private final URL wsdlLocation = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; private static Logger log = LoggerFactory . getLogger ( LogServiceFactory . class ) ; public LogServiceFactory ( String uid , String pwd , String endpointBaseUrl ) { this . uid = uid ; this . pwd = pwd ; this . endpointBaseUrl = endpointBaseUrl ; } public LogServicePortType getLogService ( ) { if ( wsdlLocation == null ) log . error ( "" ) ; LogService service = new LogService ( wsdlLocation , new QName ( "" , "" ) ) ; LogServicePortType port = service . getLogServiceSoap11Port ( ) ; String epAddr = endpointBaseUrl + "" ; log . debug ( "" + epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . USERNAME_PROPERTY , uid ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . PASSWORD_PROPERTY , pwd ) ; log . debug ( "" + epAddr + "" + uid ) ; return port ; } } package fi . koku . services . entity . person . v1 ; import java . util . List ; public interface PersonInfoProvider { List < Person > getPersonsFromCustomerDomainWithUidList ( List < String > uids , String auditUserId , String auditComponentId ) ; List < Person > getPersonsFromOfficerDomainWithUidList ( List < String > uids , String auditUserId , String auditComponentId ) ; List < Person > getPersonsFromCustomerDomainWithPicList ( List < String > pics , String auditUserId , String auditComponentId ) ; List < Person > getPersonsFromOfficerDomainWithPicList ( List < String > pics , String auditUserId , String auditComponentId ) ; } package fi . koku . services . entity . person . v1 ; public class Person { private String pic ; private String uid ; private String fname ; private String sname ; public Person ( ) { } public Person ( String pic , String fname , String sname ) { this . pic = pic ; this . fname = fname ; this . sname = sname ; } public String getPic ( ) { return pic ; } public void setPic ( String pic ) { this . pic = pic ; } public String getUid ( ) { return uid ; } public void setUid ( String uid ) { this . uid = uid ; } public String getFname ( ) { return fname ; } public void setFname ( String fname ) { this . fname = fname ; } public String getSname ( ) { return sname ; } public void setSname ( String sname ) { this . sname = sname ; } } package fi . koku . services . entity . person . v1 ; import fi . koku . settings . KoKuPropertiesUtil ; public class PersonConstants { final public static String CUSTOMER_SERVICE_ENDPOINT = KoKuPropertiesUtil . get ( "" ) ; final public static String CUSTOMER_SERVICE_USER_ID = "" ; final public static String CUSTOMER_SERVICE_PASSWORD = "" ; final public static String KAHVA_SERVICE_FULL_URL = KoKuPropertiesUtil . get ( "" ) ; final public static String USER_INFORMATION_SERVICE_FULL_URL = KoKuPropertiesUtil . get ( "" ) ; final public static String USER_INFORMATION_SERVICE_USER_ID = "" ; final public static String USER_INFORMATION_SERVICE_PASSWORD = "" ; final public static String PERSON_SERVICE_DOMAIN_CUSTOMER = "" ; final public static String PERSON_SERVICE_DOMAIN_OFFICER = "" ; final public static String USER_INFO_SERVICE_ENDPOINT = KoKuPropertiesUtil . get ( "" ) ; final public static String USER_INFO_SERVICE_USER_ID = KoKuPropertiesUtil . get ( "" ) ; final public static String USER_INFO_SERVICE_PASSWORD = KoKuPropertiesUtil . get ( "" ) ; final public static String PERSON_PROVIDER_IMPL_CLASS_NAME = KoKuPropertiesUtil . get ( "" ) ; } package fi . koku . services . entity . person . v1 . impl ; import java . util . ArrayList ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . arcusys . tampere . hrsoa . entity . User ; import fi . arcusys . tampere . hrsoa . ws . ldap . LdapService ; import fi . koku . services . common . kahva . LdapServiceFactory ; import fi . koku . services . entity . customer . v1 . AuditInfoType ; import fi . koku . services . entity . customer . v1 . CustomerQueryCriteriaType ; import fi . koku . services . entity . customer . v1 . CustomerServiceFactory ; import fi . koku . services . entity . customer . v1 . CustomerServicePortType ; import fi . koku . services . entity . customer . v1 . CustomerType ; import fi . koku . services . entity . customer . v1 . CustomersType ; import fi . koku . services . entity . customer . v1 . PicsType ; import fi . koku . services . entity . customer . v1 . ServiceFault ; import fi . koku . services . entity . person . v1 . Person ; import fi . koku . services . entity . person . v1 . PersonConstants ; import fi . koku . services . entity . person . v1 . PersonInfoProvider ; import fi . koku . services . entity . person . v1 . PersonService ; import fi . koku . services . entity . userinformation . UserInformationConstants ; import fi . koku . services . entity . userinformation . v1 . UserInformationServiceFactory ; import fi . tampere . contract . municipalityportal . uis . UserInformationFault ; import fi . tampere . contract . municipalityportal . uis . UserInformationServicePortType ; import fi . tampere . schema . municipalityportal . uis . UserInformationType ; public class TampereImpl implements PersonInfoProvider { private static final Logger LOG = LoggerFactory . getLogger ( PersonService . class ) ; private static String endpoint ; private CustomerServicePortType customerService ; private LdapService ldapService ; private UserInformationServicePortType userInformationService ; public TampereImpl ( ) { CustomerServiceFactory customerServiceFactory = new CustomerServiceFactory ( PersonConstants . CUSTOMER_SERVICE_USER_ID , PersonConstants . CUSTOMER_SERVICE_PASSWORD , PersonConstants . CUSTOMER_SERVICE_ENDPOINT ) ; customerService = customerServiceFactory . getCustomerService ( ) ; LdapServiceFactory f = new LdapServiceFactory ( PersonConstants . KAHVA_SERVICE_FULL_URL ) ; ldapService = f . getOrganizationService ( ) ; endpoint = PersonConstants . KAHVA_SERVICE_FULL_URL ; UserInformationServiceFactory uisFactory = new UserInformationServiceFactory ( PersonConstants . USER_INFORMATION_SERVICE_USER_ID , PersonConstants . USER_INFORMATION_SERVICE_PASSWORD , UserInformationConstants . USER_INFORMATION_SERVICE_FULL_URL ) ; userInformationService = uisFactory . getUserInformationService ( ) ; } @ Override public List < Person > getPersonsFromCustomerDomainWithUidList ( List < String > uids , String auditUserId , String auditComponentId ) { List < Person > personList = new ArrayList < Person > ( uids . size ( ) ) ; UserInformationType u = null ; for ( String uid : uids ) { try { u = userInformationService . getSsnByUsername ( uid ) ; if ( u != null ) { personList . add ( new Person ( u . getSsn ( ) , u . getFirstName ( ) , u . getLastName ( ) ) ) ; } } catch ( UserInformationFault e ) { LOG . error ( "" + uid , e ) ; } } return personList ; } @ Override public List < Person > getPersonsFromOfficerDomainWithUidList ( List < String > uids , String auditUserId , String auditComponentId ) { List < Person > personList = new ArrayList < Person > ( uids . size ( ) ) ; for ( String uid : uids ) { try { User userFromWS = ldapService . getUserById ( uid ) ; personList . add ( new Person ( userFromWS . getSsn ( ) , userFromWS . getFirstName ( ) , userFromWS . getLastName ( ) ) ) ; } catch ( Exception e ) { LOG . error ( "" + endpoint , e ) ; } } return personList ; } @ Override public List < Person > getPersonsFromCustomerDomainWithPicList ( List < String > pics , String auditUserId , String auditComponentId ) { List < Person > personList = new ArrayList < Person > ( pics . size ( ) ) ; AuditInfoType customerAuditInfo = new AuditInfoType ( ) ; customerAuditInfo . setComponent ( auditComponentId ) ; customerAuditInfo . setUserId ( auditUserId ) ; CustomerQueryCriteriaType query = new CustomerQueryCriteriaType ( ) ; PicsType picsType = new PicsType ( ) ; for ( String pic : pics ) { picsType . getPic ( ) . add ( pic ) ; } query . setPics ( picsType ) ; try { CustomersType customersType = customerService . opQueryCustomers ( query , customerAuditInfo ) ; for ( CustomerType c : customersType . getCustomer ( ) ) { personList . add ( new Person ( c . getHenkiloTunnus ( ) , c . getEtuNimi ( ) , c . getSukuNimi ( ) ) ) ; } } catch ( ServiceFault e ) { LOG . error ( "" + pics . size ( ) + "" + auditUserId + "" + auditComponentId , e ) ; personList = null ; } return personList ; } @ Override public List < Person > getPersonsFromOfficerDomainWithPicList ( List < String > pics , String auditUserId , String auditComponentId ) { List < Person > personList = new ArrayList < Person > ( pics . size ( ) ) ; for ( String pic : pics ) { try { User userFromWS = ldapService . getUserBySSN ( pic ) ; personList . add ( new Person ( userFromWS . getSsn ( ) , userFromWS . getFirstName ( ) , userFromWS . getLastName ( ) ) ) ; } catch ( Exception e ) { LOG . error ( "" + endpoint , e ) ; } } return personList ; } } package fi . koku . services . entity . person . v1 . impl ; import java . util . ArrayList ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . services . entity . customer . v1 . AuditInfoType ; import fi . koku . services . entity . customer . v1 . CustomerQueryCriteriaType ; import fi . koku . services . entity . customer . v1 . CustomerServiceFactory ; import fi . koku . services . entity . customer . v1 . CustomerServicePortType ; import fi . koku . services . entity . customer . v1 . CustomerType ; import fi . koku . services . entity . customer . v1 . CustomersType ; import fi . koku . services . entity . customer . v1 . PicsType ; import fi . koku . services . entity . customer . v1 . ServiceFault ; import fi . koku . services . entity . person . v1 . Person ; import fi . koku . services . entity . person . v1 . PersonConstants ; import fi . koku . services . entity . person . v1 . PersonInfoProvider ; import fi . koku . services . utility . user . v1 . UserIdsQueryParamType ; import fi . koku . services . utility . user . v1 . UserInfoServicePortType ; import fi . koku . services . utility . user . v1 . UserPicsQueryParamType ; import fi . koku . services . utility . user . v1 . UserType ; import fi . koku . services . utility . user . v1 . UsersType ; import fi . koku . services . utility . userinfo . v1 . UserInfoServiceConstants ; import fi . koku . services . utility . userinfo . v1 . UserInfoServiceFactory ; public class SaloImpl implements PersonInfoProvider { private static final Logger LOG = LoggerFactory . getLogger ( SaloImpl . class ) ; private CustomerServicePortType customerService ; private UserInfoServicePortType userService ; public SaloImpl ( ) { CustomerServiceFactory customerServiceFactory = new CustomerServiceFactory ( PersonConstants . CUSTOMER_SERVICE_USER_ID , PersonConstants . CUSTOMER_SERVICE_PASSWORD , PersonConstants . CUSTOMER_SERVICE_ENDPOINT ) ; customerService = customerServiceFactory . getCustomerService ( ) ; UserInfoServiceFactory factory = new UserInfoServiceFactory ( PersonConstants . USER_INFO_SERVICE_USER_ID , PersonConstants . USER_INFO_SERVICE_PASSWORD , PersonConstants . USER_INFO_SERVICE_ENDPOINT ) ; userService = factory . getUserInfoService ( ) ; } @ Override public List < Person > getPersonsFromCustomerDomainWithUidList ( List < String > uids , String auditUserId , String auditComponentId ) { List < Person > personList = new ArrayList < Person > ( ) ; UserIdsQueryParamType uidsQueryType = new UserIdsQueryParamType ( ) ; uidsQueryType . setDomain ( UserInfoServiceConstants . USER_INFO_SERVICE_DOMAIN_CUSTOMER ) ; uidsQueryType . getId ( ) . addAll ( uids ) ; try { UsersType usersType = userService . opGetUsersByIds ( uidsQueryType ) ; for ( UserType userType : usersType . getUser ( ) ) { personList . add ( new Person ( userType . getPic ( ) , userType . getFirstname ( ) , userType . getLastname ( ) ) ) ; } } catch ( Exception e ) { LOG . error ( "" , e ) ; } return personList ; } @ Override public List < Person > getPersonsFromOfficerDomainWithUidList ( List < String > uids , String auditUserId , String auditComponentId ) { UserIdsQueryParamType uidsQueryType = new UserIdsQueryParamType ( ) ; uidsQueryType . setDomain ( UserInfoServiceConstants . USER_INFO_SERVICE_DOMAIN_OFFICER ) ; uidsQueryType . getId ( ) . addAll ( uids ) ; UsersType users = null ; try { users = userService . opGetUsersByIds ( uidsQueryType ) ; } catch ( Exception e ) { LOG . error ( "" , e ) ; } List < Person > personList = new ArrayList < Person > ( uids . size ( ) ) ; if ( users != null ) { for ( UserType emp : users . getUser ( ) ) { personList . add ( new Person ( emp . getPic ( ) , emp . getFirstname ( ) , emp . getLastname ( ) ) ) ; } } return personList ; } @ Override public List < Person > getPersonsFromCustomerDomainWithPicList ( List < String > pics , String auditUserId , String auditComponentId ) { List < Person > personList = new ArrayList < Person > ( pics . size ( ) ) ; AuditInfoType customerAuditInfo = new AuditInfoType ( ) ; customerAuditInfo . setComponent ( auditComponentId ) ; customerAuditInfo . setUserId ( auditUserId ) ; CustomerQueryCriteriaType query = new CustomerQueryCriteriaType ( ) ; PicsType picsType = new PicsType ( ) ; for ( String pic : pics ) { picsType . getPic ( ) . add ( pic ) ; } query . setPics ( picsType ) ; try { CustomersType customersType = customerService . opQueryCustomers ( query , customerAuditInfo ) ; for ( CustomerType c : customersType . getCustomer ( ) ) { personList . add ( new Person ( c . getHenkiloTunnus ( ) , c . getEtuNimi ( ) , c . getSukuNimi ( ) ) ) ; } } catch ( ServiceFault e ) { LOG . error ( "" + pics . size ( ) + "" + auditUserId + "" + auditComponentId , e ) ; personList = null ; } return personList ; } @ Override public List < Person > getPersonsFromOfficerDomainWithPicList ( List < String > pics , String auditUserId , String auditComponentId ) { UserPicsQueryParamType picsQueryType = new UserPicsQueryParamType ( ) ; picsQueryType . setDomain ( UserInfoServiceConstants . USER_INFO_SERVICE_DOMAIN_OFFICER ) ; picsQueryType . getPic ( ) . addAll ( pics ) ; UsersType users = null ; try { users = userService . opGetUsersByPics ( picsQueryType ) ; } catch ( Exception e ) { LOG . error ( "" , e ) ; } List < Person > personList = new ArrayList < Person > ( pics . size ( ) ) ; if ( users != null ) { for ( UserType emp : users . getUser ( ) ) { personList . add ( new Person ( emp . getPic ( ) , emp . getFirstname ( ) , emp . getLastname ( ) ) ) ; } } return personList ; } } package fi . koku . services . entity . person . v1 ; import java . util . ArrayList ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . KoKuFaultException ; public class PersonService { private static final Logger LOG = LoggerFactory . getLogger ( PersonService . class ) ; private PersonInfoProvider infoProvider ; public PersonService ( ) { try { infoProvider = ( PersonInfoProvider ) this . getClass ( ) . getClassLoader ( ) . loadClass ( PersonConstants . PERSON_PROVIDER_IMPL_CLASS_NAME ) . newInstance ( ) ; LOG . info ( "" + infoProvider ) ; } catch ( Exception e ) { throw new KoKuFaultException ( , "" + PersonConstants . PERSON_PROVIDER_IMPL_CLASS_NAME , e ) ; } } public List < Person > getPersonsByPics ( List < String > pics , final String domain , final String auditUserId , final String auditComponentId ) { List < Person > personList = null ; if ( pics != null && ! pics . isEmpty ( ) ) { if ( isNotNullOrEmpty ( auditUserId ) & isNotNullOrEmpty ( auditComponentId ) ) { if ( PersonConstants . PERSON_SERVICE_DOMAIN_CUSTOMER . equals ( domain ) ) { personList = infoProvider . getPersonsFromCustomerDomainWithPicList ( pics , auditUserId , auditComponentId ) ; } else if ( PersonConstants . PERSON_SERVICE_DOMAIN_OFFICER . equals ( domain ) ) { personList = infoProvider . getPersonsFromOfficerDomainWithPicList ( pics , auditUserId , auditComponentId ) ; } else { LOG . error ( "" ) ; } } else { LOG . debug ( "" + domain + "" + auditUserId + "" + auditComponentId ) ; } } else { LOG . debug ( "" ) ; } return personList ; } public List < Person > getPersonsByUids ( List < String > uids , final String domain , final String auditUserId , final String auditComponentId ) { List < Person > personList = null ; if ( uids != null && ! uids . isEmpty ( ) ) { personList = new ArrayList < Person > ( uids . size ( ) ) ; if ( isNotNullOrEmpty ( auditUserId ) & isNotNullOrEmpty ( auditComponentId ) ) { if ( PersonConstants . PERSON_SERVICE_DOMAIN_OFFICER . equals ( domain ) ) { personList = infoProvider . getPersonsFromOfficerDomainWithUidList ( uids , auditUserId , auditComponentId ) ; } else if ( PersonConstants . PERSON_SERVICE_DOMAIN_CUSTOMER . equals ( domain ) ) { personList = infoProvider . getPersonsFromCustomerDomainWithUidList ( uids , auditUserId , auditComponentId ) ; } else { LOG . error ( "" ) ; } } else { LOG . debug ( "" + domain + "" + auditUserId + "" + auditComponentId ) ; } } else { LOG . debug ( "" ) ; } return personList ; } private boolean isNotNullOrEmpty ( String s ) { if ( s != null && ! s . isEmpty ( ) ) { return true ; } else { return false ; } } } package fi . koku . services . entity . sis . v1 ; public class Helmi { } package fi . koku . services . utility . userinfo . v1 ; import java . net . URL ; import javax . xml . namespace . QName ; import javax . xml . ws . BindingProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import fi . koku . services . utility . user . v1 . UserInfoService ; import fi . koku . services . utility . user . v1 . UserInfoServicePortType ; public class UserInfoServiceFactory { private String uid ; private String pwd ; private String endpointBaseUrl ; private final URL wsdlLocation = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; private static Logger log = LoggerFactory . getLogger ( UserInfoServiceFactory . class ) ; public UserInfoServiceFactory ( String uid , String pwd , String endpointBaseUrl ) { this . uid = uid ; this . pwd = pwd ; this . endpointBaseUrl = endpointBaseUrl ; } public UserInfoServicePortType getUserInfoService ( ) { if ( wsdlLocation == null ) log . error ( "" ) ; UserInfoService service = new UserInfoService ( wsdlLocation , new QName ( "" , "" ) ) ; UserInfoServicePortType port = service . getUserInfoServiceSoap11Port ( ) ; String epAddr = endpointBaseUrl + "" ; log . debug ( "" + epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . ENDPOINT_ADDRESS_PROPERTY , epAddr ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . USERNAME_PROPERTY , uid ) ; ( ( BindingProvider ) port ) . getRequestContext ( ) . put ( BindingProvider . PASSWORD_PROPERTY , pwd ) ; log . debug ( "" + epAddr + "" + uid ) ; return port ; } } package fi . koku . services . utility . userinfo . v1 ; public interface UserInfoServiceConstants { final public static String USER_INFO_SERVICE_DOMAIN_CUSTOMER = "" ; final public static String USER_INFO_SERVICE_DOMAIN_OFFICER = "" ; } package br . com . caelum . vraptor . dash . statement ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import static org . junit . Assert . assertEquals ; import org . junit . Test ; public class StatementTest extends DatabaseIntegrationTest { @ Test public void shouldEscapeLowerThanSymbol ( ) { String hql = "" ; Statement stmt = new Statement ( "" , hql ) ; assertEquals ( "" , stmt . getEscapedHql ( ) ) ; assertEquals ( "" , stmt . getHql ( ) ) ; } @ Test public void shouldEscapeGreaterThanSymbol ( ) { String hql = "" ; Statement stmt = new Statement ( "" , hql ) ; assertEquals ( "" , stmt . getEscapedHql ( ) ) ; assertEquals ( "" , stmt . getHql ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void deleteIsNotValid ( ) { String hql = "" ; Statement stmt = new Statement ( hql , hql ) ; stmt . validate ( new StatementDao ( session ) , null ) ; } @ Test ( expected = IllegalArgumentException . class ) public void updateIsNotValid ( ) { String hql = "" ; Statement stmt = new Statement ( hql , hql ) ; stmt . validate ( new StatementDao ( session ) , null ) ; } @ Test ( expected = IllegalArgumentException . class ) public void hqlReferencingUnexistingEntityIsNotValid ( ) { Statement statement = new Statement ( "" , "" ) ; statement . validate ( new StatementDao ( session ) , null ) ; } @ Test public void canAccessAStatementWithTheCorrectKey ( ) { Statement statement = new Statement ( "" , "" ) ; statement . setPassword ( "" ) ; assertTrue ( statement . canBeAccessedWithKey ( "" ) ) ; } @ Test public void cannotAccessIfThereIsNoPassword ( ) { Statement statement = new Statement ( "" , "" ) ; assertFalse ( statement . canBeAccessedWithKey ( null ) ) ; assertFalse ( statement . canBeAccessedWithKey ( "" ) ) ; } @ Test public void cannotAccessWithWrongKey ( ) { Statement statement = new Statement ( "" , "" ) ; statement . setPassword ( "" ) ; assertFalse ( statement . canBeAccessedWithKey ( null ) ) ; assertFalse ( statement . canBeAccessedWithKey ( "" ) ) ; } } package br . com . caelum . vraptor . dash . statement ; import org . hibernate . SessionFactory ; import org . hibernate . cfg . AnnotationConfiguration ; import org . hibernate . classic . Session ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; public abstract class DatabaseIntegrationTest { private static SessionFactory factory ; protected Session session ; @ BeforeClass public static void setup ( ) { factory = new AnnotationConfiguration ( ) . configure ( ) . addAnnotatedClass ( Statement . class ) . buildSessionFactory ( ) ; } @ Before public void setupSession ( ) { this . session = factory . openSession ( ) ; } @ After public void shutdownSession ( ) { if ( this . session != null ) { session . createQuery ( "" ) . executeUpdate ( ) ; this . session . close ( ) ; } } @ AfterClass public static void shutdown ( ) { if ( factory != null ) { factory . close ( ) ; } } } package br . com . caelum . vraptor . dash . statement ; import static org . junit . Assert . assertEquals ; import java . util . Arrays ; import java . util . List ; import org . hibernate . Transaction ; import org . junit . Test ; public class StatementDaoTest extends DatabaseIntegrationTest { @ Test ( expected = IllegalArgumentException . class ) public void throwsExceptionWhenValidatingInvalidHql ( ) { new StatementDao ( session ) . validate ( "" , null ) ; } @ Test ( expected = IllegalArgumentException . class ) public void throwsExceptionWhenValidatingHqlThatDoesNotExecute ( ) throws Exception { new StatementDao ( session ) . validate ( "" , null ) ; } @ Test public void returnsAnEmptyListForAStatementWithoutResults ( ) throws Exception { List < Object [ ] > result = new StatementDao ( session ) . execute ( new Statement ( "" , "" ) , null , ) ; assertEquals ( , result . size ( ) ) ; } @ Test public void assemblesResultListWithLinesFromQueryResultWhenEachLineHasOnlyOneColumn ( ) { Transaction tx = session . beginTransaction ( ) ; session . save ( new Statement ( "" , "" ) ) ; session . save ( new Statement ( "" , "" ) ) ; tx . commit ( ) ; List < Object [ ] > result = new StatementDao ( session ) . execute ( new Statement ( "" , "" ) , null , ) ; assertEquals ( , result . size ( ) ) ; assertEquals ( , result . get ( ) . length ) ; assertEquals ( , result . get ( ) . length ) ; assertEquals ( "" , result . get ( ) [ ] ) ; assertEquals ( "" , result . get ( ) [ ] ) ; } @ Test public void assemblesResultListWithLinesFromQueryResultWhenEachLineHasManyColumns ( ) { Transaction tx = session . beginTransaction ( ) ; session . save ( new Statement ( "" , "" ) ) ; session . save ( new Statement ( "" , "" ) ) ; tx . commit ( ) ; List < Object [ ] > result = new StatementDao ( session ) . execute ( new Statement ( "" , "" ) , null , ) ; assertEquals ( , result . size ( ) ) ; assertEquals ( , result . get ( ) . length ) ; assertEquals ( , result . get ( ) . length ) ; assertEquals ( "" , result . get ( ) [ ] ) ; assertEquals ( "" , result . get ( ) [ ] ) ; assertEquals ( "" , result . get ( ) [ ] ) ; assertEquals ( "" , result . get ( ) [ ] ) ; } private void createStatements ( Integer size ) { Transaction tx = session . beginTransaction ( ) ; for ( int i = ; i <= size ; i ++ ) { session . save ( new Statement ( "" + i , "" ) ) ; } tx . commit ( ) ; } @ Test public void shouldOnlyReturn1000ItensWhenIsRequested ( ) { createStatements ( ) ; List < Object [ ] > results = new StatementDao ( session ) . execute ( new Statement ( "" , "" ) , null , ) ; assertEquals ( , results . size ( ) ) ; } @ Test public void shouldExecuteAQueryWithParameters ( ) { Transaction tx = session . beginTransaction ( ) ; session . save ( new Statement ( "" , "" ) ) ; session . save ( new Statement ( "" , "" ) ) ; tx . commit ( ) ; List < Object [ ] > results = new StatementDao ( session ) . execute ( new Statement ( "" , "" ) , Arrays . < String > asList ( "" ) , ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( ) [ ] ) ; assertEquals ( "" , results . get ( ) [ ] ) ; } } package br . com . caelum . vraptor . dash . hibernate ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . when ; import static org . mockito . MockitoAnnotations . initMocks ; import java . io . IOException ; import java . util . Arrays ; import org . hibernate . Session ; import org . hibernate . stat . Statistics ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . dash . runtime . RuntimeStatisticsCollector ; import br . com . caelum . vraptor . dash . statistics . Collector ; import br . com . caelum . vraptor . dash . statistics . Collectors ; @ RunWith ( MockitoJUnitRunner . class ) public class AuditControllerTest { @ Mock private Result result ; @ Mock private Session session ; @ Mock private Statistics statistics ; @ Mock private HibernateAuditAwareUser user ; @ Mock private Runtime runtime ; private Collectors hibernateCollector ; private Collectors runtimeCollector ; @ Before public void setup ( ) { initMocks ( this ) ; hibernateCollector = new Collectors ( Arrays . < Collector > asList ( new HibernateStatisticsCollector ( statistics ) ) ) ; runtimeCollector = new Collectors ( Arrays . < Collector > asList ( new RuntimeStatisticsCollector ( runtime ) ) ) ; } @ Test public void shouldIncludeHibernateStatisticConnectionCount ( ) throws Exception { when ( statistics . getConnectCount ( ) ) . thenReturn ( ) ; when ( user . canSeeHibernateAudits ( ) ) . thenReturn ( true ) ; new AuditController ( session , user , result ) . collectStatistics ( hibernateCollector ) ; verify ( result ) . include ( "" , "" ) ; } @ Test public void shouldIncludeHibernateStatisticSecondLevelCacheMissCount ( ) throws Exception { when ( statistics . getSecondLevelCacheMissCount ( ) ) . thenReturn ( ) ; when ( user . canSeeHibernateAudits ( ) ) . thenReturn ( true ) ; new AuditController ( session , user , result ) . collectStatistics ( hibernateCollector ) ; verify ( result ) . include ( "" , "" ) ; } @ Test public void shouldIncludeHibernateStatistictSecondLevelCacheHitCount ( ) throws Exception { when ( statistics . getSecondLevelCacheHitCount ( ) ) . thenReturn ( ) ; when ( user . canSeeHibernateAudits ( ) ) . thenReturn ( true ) ; new AuditController ( session , user , result ) . collectStatistics ( hibernateCollector ) ; verify ( result ) . include ( "" , "" ) ; } @ Test public void shouldIncludeHibernateStatistictSecondLevelCachePutCount ( ) throws Exception { when ( statistics . getSecondLevelCachePutCount ( ) ) . thenReturn ( ) ; when ( user . canSeeHibernateAudits ( ) ) . thenReturn ( true ) ; new AuditController ( session , user , result ) . collectStatistics ( hibernateCollector ) ; verify ( result ) . include ( "" , "" ) ; } @ Test public void shouldIncludeVmStatisticTotalMemory ( ) { when ( runtime . totalMemory ( ) ) . thenReturn ( ) ; new AuditController ( session , user , result ) . collectStatistics ( runtimeCollector ) ; verify ( result ) . include ( "" , "" ) ; } @ Test public void shouldIncludeVmStatisticUsedMemory ( ) { when ( runtime . totalMemory ( ) ) . thenReturn ( ) ; when ( runtime . freeMemory ( ) ) . thenReturn ( ) ; new AuditController ( session , user , result ) . collectStatistics ( runtimeCollector ) ; verify ( result ) . include ( "" , "" ) ; } @ Test public void shouldIncludeVmStatisticUsedMemoryPerCent ( ) { when ( runtime . totalMemory ( ) ) . thenReturn ( ) ; when ( runtime . freeMemory ( ) ) . thenReturn ( ) ; new AuditController ( session , user , result ) . collectStatistics ( runtimeCollector ) ; verify ( result ) . include ( "" , "" ) ; } @ Test public void shouldIncludeVmStatisticFreeMemory ( ) { when ( runtime . freeMemory ( ) ) . thenReturn ( ) ; new AuditController ( session , user , result ) . collectStatistics ( runtimeCollector ) ; verify ( result ) . include ( "" , "" ) ; } @ Test public void shouldIncludeVmStatisticFreeMemoryPercent ( ) { when ( runtime . totalMemory ( ) ) . thenReturn ( ) ; when ( runtime . freeMemory ( ) ) . thenReturn ( ) ; new AuditController ( session , user , result ) . collectStatistics ( runtimeCollector ) ; verify ( result ) . include ( "" , "" ) ; } } package br . com . caelum . vraptor . dash . hibernate ; import static org . junit . Assert . assertFalse ; import java . lang . reflect . Method ; import java . util . Calendar ; import org . junit . Test ; import br . com . caelum . vraptor . dash . hibernate . stats . OpenRequest ; public class OpenRequestTest { @ Test public void openRequestIdsMustBeDifferent ( ) throws Exception { Class < ? > clazz = Class . class ; Method method = clazz . getDeclaredMethods ( ) [ ] ; Calendar now = Calendar . getInstance ( ) ; OpenRequest request1 = new OpenRequest ( method , clazz , now ) ; OpenRequest request2 = new OpenRequest ( method , clazz , now ) ; assertFalse ( request1 . getId ( ) . equals ( request2 . getId ( ) ) ) ; } } package br . com . caelum . vraptor . dash . hibernate ; import static br . com . caelum . vraptor . dash . matchers . IsEmptyMapMatcher . isEmptyMap ; import static br . com . caelum . vraptor . dash . matchers . IsOfResourceMatcher . isOpenRequestOfResource ; import static org . hamcrest . Matchers . hasEntry ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertThat ; import java . lang . reflect . Method ; import org . junit . Before ; import org . junit . Test ; import br . com . caelum . vraptor . dash . hibernate . stats . OpenRequest ; import br . com . caelum . vraptor . dash . hibernate . stats . OpenRequests ; import br . com . caelum . vraptor . resource . DefaultResourceClass ; import br . com . caelum . vraptor . resource . DefaultResourceMethod ; public class OpenRequestsTest { private DefaultResourceMethod wrapped ; private OpenRequests openRequests ; @ Before public void setup ( ) { Class < ? > type = Class . class ; Method method = type . getDeclaredMethods ( ) [ ] ; wrapped = new DefaultResourceMethod ( new DefaultResourceClass ( type ) , method ) ; openRequests = new OpenRequests ( ) ; } @ Test public void createsAnOpenRequestForTheAddedResourceMethod ( ) throws Exception { assertThat ( openRequests . add ( wrapped ) , isOpenRequestOfResource ( wrapped ) ) ; } @ Test public void returnsAMapOfOpenRequestsWithTheAddedResourceMethod ( ) throws Exception { assertEquals ( , openRequests . toMap ( ) . size ( ) ) ; OpenRequest added = openRequests . add ( wrapped ) ; assertThat ( openRequests . toMap ( ) , hasEntry ( added . getId ( ) , added ) ) ; } @ Test public void returnsAnEmptyMapWhenAllTheAddedRequestsAreRemoved ( ) throws Exception { OpenRequest request = openRequests . add ( wrapped ) ; openRequests . remove ( request ) ; assertThat ( openRequests . toMap ( ) , isEmptyMap ( ) ) ; } } package br . com . caelum . vraptor . dash . audit ; import static br . com . caelum . vraptor . dash . matchers . IsOfResourceMatcher . isOpenRequestOfResource ; import static org . mockito . Matchers . argThat ; import static org . mockito . Mockito . doThrow ; import static org . mockito . Mockito . inOrder ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . when ; import java . lang . reflect . Method ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . InOrder ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import br . com . caelum . vraptor . InterceptionException ; import br . com . caelum . vraptor . core . InterceptorStack ; import br . com . caelum . vraptor . dash . hibernate . stats . OpenRequest ; import br . com . caelum . vraptor . dash . hibernate . stats . OpenRequestInterceptor ; import br . com . caelum . vraptor . dash . hibernate . stats . OpenRequests ; import br . com . caelum . vraptor . resource . DefaultResourceClass ; import br . com . caelum . vraptor . resource . ResourceClass ; import br . com . caelum . vraptor . resource . ResourceMethod ; @ RunWith ( MockitoJUnitRunner . class ) public class LogRequestTimeInterceptorTest { private OpenRequestInterceptor interceptor ; private @ Mock OpenRequests requests ; private @ Mock InterceptorStack stack ; private @ Mock ResourceMethod resourceMethod ; @ Before public void setUp ( ) throws Exception { configureMockResourceMethod ( ) ; OpenRequest openRequest = new OpenRequest ( resourceMethod ) ; when ( requests . add ( resourceMethod ) ) . thenReturn ( openRequest ) ; interceptor = new OpenRequestInterceptor ( requests ) ; } private void configureMockResourceMethod ( ) { Method method = Class . class . getDeclaredMethods ( ) [ ] ; when ( resourceMethod . getMethod ( ) ) . thenReturn ( method ) ; ResourceClass resourceClass = new DefaultResourceClass ( Class . class ) ; when ( resourceMethod . getResource ( ) ) . thenReturn ( resourceClass ) ; } @ Test public void addsAndRemovesResourceMethodsInOpenRequestsBeforeAndAfterStackExecutionRespectively ( ) throws Exception { interceptor . intercept ( stack , resourceMethod , null ) ; InOrder inOrder = inOrder ( requests , stack ) ; inOrder . verify ( requests ) . add ( resourceMethod ) ; inOrder . verify ( stack ) . next ( resourceMethod , null ) ; inOrder . verify ( requests ) . remove ( argThat ( isOpenRequestOfResource ( resourceMethod ) ) ) ; } @ Test ( expected = InterceptionException . class ) public void addsAndRemovesResourceMethodsInOpenRequestsEvenWhenStackExecutionThrowsException ( ) throws Exception { doThrow ( new InterceptionException ( "" ) ) . when ( stack ) . next ( resourceMethod , null ) ; interceptor . intercept ( stack , resourceMethod , null ) ; verify ( requests ) . add ( resourceMethod ) ; verify ( requests ) . remove ( argThat ( isOpenRequestOfResource ( resourceMethod ) ) ) ; } } package br . com . caelum . vraptor . dash . interceptor ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import java . lang . reflect . Method ; import javax . servlet . http . HttpServletResponse ; import net . vidageek . mirror . dsl . Mirror ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import br . com . caelum . vraptor . Validator ; import br . com . caelum . vraptor . dash . statement . StatementController ; import br . com . caelum . vraptor . resource . DefaultResourceClass ; import br . com . caelum . vraptor . resource . DefaultResourceMethod ; import br . com . caelum . vraptor . resource . ResourceMethod ; @ RunWith ( MockitoJUnitRunner . class ) public class ContentTypeInterceptorTest { private @ Mock HttpServletResponse response ; @ Test public void acceptsOnlyControllersInsideDashPackage ( ) throws Exception { ContentTypeInterceptor interceptor = new ContentTypeInterceptor ( response ) ; ResourceMethod vraptorDashMethod = resourceMethodInClass ( StatementController . class , "" , Integer . class ) ; assertTrue ( interceptor . accepts ( vraptorDashMethod ) ) ; ResourceMethod vraptorRandomMethod = resourceMethodInClass ( Validator . class , "" , Object . class ) ; assertFalse ( interceptor . accepts ( vraptorRandomMethod ) ) ; } private ResourceMethod resourceMethodInClass ( Class < ? > type , String methodName , Class < ? > ... methodArgs ) { DefaultResourceClass vraptorDashController = new DefaultResourceClass ( type ) ; Method dashMethod = new Mirror ( ) . on ( vraptorDashController . getClass ( ) ) . reflect ( ) . method ( methodName ) . withArgs ( methodArgs ) ; DefaultResourceMethod vraptorDashMethod = new DefaultResourceMethod ( vraptorDashController , dashMethod ) ; return vraptorDashMethod ; } } package br . com . caelum . vraptor . dash . monitor ; import static org . junit . Assert . assertEquals ; import static org . mockito . Mockito . when ; import java . util . EnumSet ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import br . com . caelum . vraptor . http . route . Route ; import br . com . caelum . vraptor . resource . HttpMethod ; @ RunWith ( MockitoJUnitRunner . class ) public class FreemarkerRouteTest { private @ Mock Route routeMock ; private FreemarkerRoute route ; @ Before public void setUp ( ) throws Exception { route = new FreemarkerRoute ( routeMock ) ; } @ Test public void returnsGETandPOSTWhenHttpMethodsGETAndPOSTAllowed ( ) { when ( routeMock . allowedMethods ( ) ) . thenReturn ( EnumSet . of ( HttpMethod . GET , HttpMethod . POST ) ) ; assertEquals ( "" , route . getAllowedMethods ( ) ) ; } @ Test public void returnsPUTandDeleteWhenHttpMethodsPutAndDeleteAllowed ( ) { when ( routeMock . allowedMethods ( ) ) . thenReturn ( EnumSet . of ( HttpMethod . PUT , HttpMethod . DELETE ) ) ; assertEquals ( "" , route . getAllowedMethods ( ) ) ; } @ Test public void returnsALLWhenAllHttpMethodsAllowed ( ) { when ( routeMock . allowedMethods ( ) ) . thenReturn ( EnumSet . allOf ( HttpMethod . class ) ) ; assertEquals ( "" , route . getAllowedMethods ( ) ) ; } } package br . com . caelum . vraptor . dash . monitor ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . when ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import br . com . caelum . vraptor . environment . Environment ; import br . com . caelum . vraptor . http . route . Router ; import br . com . caelum . vraptor . util . test . MockResult ; @ RunWith ( MockitoJUnitRunner . class ) public class RoutesControllerTest { private @ Mock Router router ; private @ Mock Environment environment ; private @ Mock MonitorAwareUser user ; private RoutesController controller ; @ Before public void setUp ( ) throws Exception { this . controller = new RoutesController ( router , new MockResult ( ) , environment , user ) ; when ( user . canSeeMonitorStats ( ) ) . thenReturn ( true ) ; } @ Test public void showsAllRegisteredRoutesWhenAccessedOutOfProductionEnvironment ( ) throws Exception { when ( environment . getName ( ) ) . thenReturn ( "" ) ; controller . allRoutes ( ) ; verify ( router ) . allRoutes ( ) ; } @ Test ( expected = UnsupportedOperationException . class ) public void throwsExceptionWhenAccessedInProductionEnvironment ( ) throws Exception { when ( environment . getName ( ) ) . thenReturn ( "" ) ; controller . allRoutes ( ) ; } } package br . com . caelum . vraptor . dash . monitor ; import static org . mockito . Matchers . anyString ; import static org . mockito . Mockito . verify ; import static org . mockito . Mockito . when ; import org . junit . Assert ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . mockito . Mock ; import org . mockito . runners . MockitoJUnitRunner ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . environment . Environment ; import br . com . caelum . vraptor . interceptor . download . InputStreamDownload ; import br . com . caelum . vraptor . view . Results ; import br . com . caelum . vraptor . view . Status ; @ RunWith ( MockitoJUnitRunner . class ) public class SystemControllerTest { private @ Mock Result result ; private @ Mock Status httpStatus ; private @ Mock Environment environment ; private @ Mock MonitorAwareUser user ; private SystemController controller ; @ Before public void setUp ( ) throws Exception { controller = new SystemController ( environment , result , user ) ; when ( result . use ( Results . status ( ) ) ) . thenReturn ( httpStatus ) ; when ( user . canSeeMonitorStats ( ) ) . thenReturn ( true ) ; } @ Test public void allowsAccessToExistingFilesMatchingTheConfiguredPattern ( ) throws Exception { when ( environment . get ( SystemController . ALLOWED_LOG_REGEX ) ) . thenReturn ( "" ) ; InputStreamDownload logContent = controller . log ( "" ) ; Assert . assertNotNull ( logContent ) ; } @ Test ( expected = IllegalStateException . class ) public void throwsIllegalStateExceptionIfThePatternMatchesTheFilenameAndTheFileDoesNotExists ( ) throws Exception { when ( environment . get ( SystemController . ALLOWED_LOG_REGEX ) ) . thenReturn ( "" ) ; controller . log ( "" ) ; } @ Test public void ifTheConfiguredPatternDoesNotMatchTheFilenameSendStatusForbidden ( ) throws Exception { when ( environment . get ( SystemController . ALLOWED_LOG_REGEX ) ) . thenReturn ( "" ) ; controller . log ( "" ) ; verify ( httpStatus ) . forbidden ( anyString ( ) ) ; } } package br . com . caelum . vraptor . dash . matchers ; import java . util . Map ; import org . hamcrest . Description ; import org . hamcrest . Factory ; import org . hamcrest . Matcher ; import org . hamcrest . TypeSafeMatcher ; public class IsEmptyMapMatcher extends TypeSafeMatcher < Map < ? , ? > > { @ Override public void describeTo ( Description description ) { description . appendText ( "" ) ; } @ Override protected boolean matchesSafely ( Map < ? , ? > map ) { return map . isEmpty ( ) ; } @ Factory public static Matcher < Map < ? , ? > > isEmptyMap ( ) { return new IsEmptyMapMatcher ( ) ; } } package br . com . caelum . vraptor . dash . matchers ; import org . hamcrest . Description ; import org . hamcrest . Factory ; import org . hamcrest . TypeSafeMatcher ; import br . com . caelum . vraptor . dash . hibernate . stats . OpenRequest ; import br . com . caelum . vraptor . resource . ResourceMethod ; public final class IsOfResourceMatcher extends TypeSafeMatcher < OpenRequest > { private final ResourceMethod resourceMethod ; private IsOfResourceMatcher ( ResourceMethod resourceMethod ) { this . resourceMethod = resourceMethod ; } @ Override public void describeTo ( Description description ) { description . appendText ( "" ) ; description . appendValue ( resourceMethod ) ; } @ Override protected boolean matchesSafely ( OpenRequest item ) { return new OpenRequest ( this . resourceMethod ) . getResource ( ) . equals ( item . getResource ( ) ) ; } @ Override protected void describeMismatchSafely ( OpenRequest item , Description mismatchDescription ) { } @ Factory public static IsOfResourceMatcher isOpenRequestOfResource ( ResourceMethod resourceMethod ) { return new IsOfResourceMatcher ( resourceMethod ) ; } } package br . com . caelum . vraptor . dash . statement ; import java . util . ArrayList ; import java . util . List ; import java . util . StringTokenizer ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . Lob ; import javax . persistence . Table ; import org . hibernate . annotations . GenericGenerator ; @ Entity ( name = "" ) @ Table ( name = "" ) public class Statement { @ Id @ GeneratedValue ( generator = "" ) @ GenericGenerator ( name = "" , strategy = "" ) private String id ; private String name ; @ Lob private String hql ; private String password ; public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getPassword ( ) { return password ; } public void setPassword ( String password ) { this . password = password ; } @ Deprecated protected Statement ( ) { } public Statement ( String name , String hql ) { this . name = name ; this . hql = hql ; } public String getHql ( ) { return hql ; } public String getEscapedHql ( ) { String escapedHql = hql . replace ( "" , "" ) ; escapedHql = escapedHql . replace ( ">" , "" ) ; return escapedHql ; } public void setHql ( String hql ) { this . hql = hql ; } public void validate ( StatementDao dao , List < String > parameters ) { if ( hql . contains ( "" ) || hql . contains ( "" ) ) { throw new IllegalArgumentException ( "" ) ; } try { dao . validate ( hql , parameters ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( ex ) ; } } public boolean canBeAccessedWithKey ( String key ) { return isOpenForOthersWithPassword ( ) && password . equals ( key ) ; } public boolean isOpenForOthersWithPassword ( ) { return password != null && ! password . isEmpty ( ) ; } public List < String > getColumns ( ) { String onlyFields = stripSelectAndFrom ( ) ; List < String > columns = new ArrayList < String > ( ) ; StringTokenizer tokens = new StringTokenizer ( onlyFields , "" ) ; while ( tokens . hasMoreTokens ( ) ) { columns . add ( tokens . nextToken ( ) ) ; } return columns ; } private String stripSelectAndFrom ( ) { String hql = this . getHql ( ) . toLowerCase ( ) ; int selectPos = hql . indexOf ( "" ) > ? hql . indexOf ( "" ) : ; int fromPos = hql . indexOf ( "" ) ; String onlyFields = null ; if ( fromPos > ) { onlyFields = this . getHql ( ) . substring ( selectPos + , fromPos ) ; } else { onlyFields = this . getHql ( ) ; } return onlyFields ; } } package br . com . caelum . vraptor . dash . statement ; public interface StatementAwareUser { boolean canCreateStatements ( ) ; } package br . com . caelum . vraptor . dash . statement ; import java . util . List ; import br . com . caelum . vraptor . Delete ; import br . com . caelum . vraptor . Get ; import br . com . caelum . vraptor . Path ; import br . com . caelum . vraptor . Post ; import br . com . caelum . vraptor . Put ; import br . com . caelum . vraptor . Resource ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . Validator ; import br . com . caelum . vraptor . freemarker . FreemarkerView ; import br . com . caelum . vraptor . validator . I18nMessage ; import br . com . caelum . vraptor . view . HttpResult ; import br . com . caelum . vraptor . view . Results ; @ Resource public class StatementController { private static final String SHOW = "" ; private static final String NONE = "" ; private static final String INDEX = "" ; private final Result result ; private final Validator validator ; private final StatementDao statements ; private final StatementAwareUser currentUser ; public StatementController ( Result result , Validator validator , StatementDao statementDao , StatementAwareUser currentUser ) { this . result = result ; this . validator = validator ; this . statements = statementDao ; this . currentUser = currentUser ; } @ Path ( "" ) @ Get public void index ( Integer size ) { if ( ! currentUser . canCreateStatements ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } if ( size == null ) { size = ; } result . include ( "" , statements . all ( size ) ) ; result . include ( "" , size ) ; result . use ( FreemarkerView . class ) . withTemplate ( INDEX ) ; } @ Path ( value = "" , priority = Path . LOWEST ) @ Post public void show ( Statement statement , String password , Integer maxResults ) { statement = statements . load ( statement . getId ( ) ) ; maxResults = ( maxResults == null ? : maxResults ) ; if ( canView ( statement , password ) ) { List < Object [ ] > results = executeStatement ( statement , maxResults ) ; List < String > columns = statement . getColumns ( ) ; renderResponse ( statement , results , columns , maxResults ) ; } else { result . use ( HttpResult . class ) . sendError ( ) ; } } private boolean canView ( Statement statement , String password ) { return currentUser . canCreateStatements ( ) || statement . canBeAccessedWithKey ( password ) ; } @ Path ( "" ) @ Get public void form ( Statement statement , Integer maxResults ) { if ( canView ( statement , "" ) ) { result . forwardTo ( this ) . show ( statement , "" , maxResults ) ; } else { result . include ( "" , maxResults ) ; result . include ( "" , statement ) ; result . use ( FreemarkerView . class ) . withTemplate ( "" ) ; } } @ Path ( "" ) @ Post public void showJSON ( Statement statement , String password , Integer maxResults ) { statement = statements . load ( statement . getId ( ) ) ; if ( canView ( statement , password ) ) { List < Object [ ] > results = executeStatement ( statement , maxResults ) ; result . use ( Results . json ( ) ) . from ( results ) . serialize ( ) ; } else { result . use ( HttpResult . class ) . sendError ( ) ; } } private List < Object [ ] > executeStatement ( Statement statement , Integer maxResults ) { if ( maxResults == null ) { maxResults = ; } validateStatement ( statement , null ) ; List < Object [ ] > results = statements . execute ( statement , null , maxResults ) ; return results ; } private void renderResponse ( Statement statement , List < Object [ ] > results , List < String > columns , Integer maxResults ) { result . include ( "" , statement ) ; result . include ( "" , results ) ; result . include ( "" , columns ) ; result . include ( "" , maxResults ) ; result . use ( FreemarkerView . class ) . withTemplate ( SHOW ) ; } @ Path ( "" ) @ Post public void execute ( Statement statement , List < String > parameters , Integer maxResults ) { if ( ! currentUser . canCreateStatements ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } if ( maxResults == null ) { maxResults = ; } validateStatement ( statement , parameters ) ; List < Object [ ] > results = statements . execute ( statement , parameters , maxResults ) ; List < String > columns = statement . getColumns ( ) ; renderResponse ( statement , results , columns , maxResults ) ; } @ Path ( "" ) @ Post public void create ( Statement statement , Integer maxResults ) { if ( ! currentUser . canCreateStatements ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } validateStatement ( statement , null ) ; statements . save ( statement ) ; result . redirectTo ( this ) . form ( statement , maxResults ) ; } @ Path ( "" ) @ Put public void update ( Statement statement ) { validateStatement ( statement , null ) ; if ( ! currentUser . canCreateStatements ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } Statement loaded = statements . load ( statement . getId ( ) ) ; loaded . setHql ( statement . getHql ( ) ) ; loaded . setName ( statement . getName ( ) ) ; validateStatement ( loaded , null ) ; statements . merge ( loaded ) ; result . forwardTo ( this ) . show ( loaded , loaded . getPassword ( ) , null ) ; } @ Path ( "" ) @ Delete public void delete ( Statement statement ) { statements . delete ( statement ) ; result . nothing ( ) ; } private void validateStatement ( Statement statement , List < String > parameters ) { try { statement . validate ( statements , parameters ) ; } catch ( IllegalArgumentException e ) { validator . add ( new I18nMessage ( "" , "" , e . getCause ( ) . getMessage ( ) ) ) ; validator . onErrorRedirectTo ( this ) . index ( null ) ; } } } package br . com . caelum . vraptor . dash . statement ; import java . util . ArrayList ; import java . util . List ; import org . hibernate . Query ; import org . hibernate . Session ; import br . com . caelum . vraptor . ioc . Component ; @ Component public class StatementDao { private final Session session ; public StatementDao ( Session session ) { this . session = session ; } public void validate ( String hql , List < String > parameters ) { try { createQuery ( hql , parameters , ) . list ( ) ; } catch ( Exception exception ) { throw new IllegalArgumentException ( exception ) ; } } @ SuppressWarnings ( "" ) public List < Object [ ] > execute ( Statement st , List < String > parameters , Integer size ) { List results = createQuery ( st . getHql ( ) , parameters , size ) . list ( ) ; if ( ! results . isEmpty ( ) && results . get ( ) . getClass ( ) . isArray ( ) ) { return results ; } List < Object [ ] > wrappedResults = new ArrayList < Object [ ] > ( ) ; for ( Object o : results ) { wrappedResults . add ( new Object [ ] { o } ) ; } return wrappedResults ; } public void save ( Statement statement ) { session . save ( statement ) ; } public void merge ( Statement statement ) { session . merge ( statement ) ; } public Statement load ( String id ) { return ( Statement ) session . load ( Statement . class , id ) ; } public void delete ( Statement statement ) { session . delete ( statement ) ; } @ SuppressWarnings ( "" ) public List < Statement > all ( Integer size ) { return createQuery ( "" , null , size ) . setCacheable ( true ) . list ( ) ; } private Query createQuery ( String hql , List < String > parameters , Integer size ) { Query query = session . createQuery ( hql ) ; if ( parameters != null ) { for ( int i = ; i < parameters . size ( ) ; i ++ ) { query . setParameter ( i , parameters . get ( i ) ) ; } } return query . setMaxResults ( size ) ; } } package br . com . caelum . vraptor . dash . uristats ; import java . util . Enumeration ; import javax . servlet . ServletResponse ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . apache . log4j . Logger ; import br . com . caelum . vraptor . InterceptionException ; import br . com . caelum . vraptor . core . InterceptorStack ; import br . com . caelum . vraptor . dash . cache . ObservableResponse ; import br . com . caelum . vraptor . http . VRaptorResponse ; import br . com . caelum . vraptor . interceptor . Interceptor ; import br . com . caelum . vraptor . ioc . Container ; import br . com . caelum . vraptor . resource . ResourceMethod ; public class BaseURIStatInterceptor implements Interceptor { private static final Logger LOG = Logger . getLogger ( BaseURIStatInterceptor . class ) ; private final HttpServletRequest request ; private final Container container ; private final HttpServletResponse response ; public BaseURIStatInterceptor ( Container container , HttpServletRequest request , HttpServletResponse response ) { this . container = container ; this . request = request ; this . response = response ; } public boolean accepts ( ResourceMethod arg0 ) { return true ; } public void intercept ( InterceptorStack stack , ResourceMethod method , Object instance ) throws InterceptionException { long before = System . currentTimeMillis ( ) ; stack . next ( method , instance ) ; try { long time = System . currentTimeMillis ( ) - before ; String key = userKey ( container ) ; String resource = method . getResource ( ) . getType ( ) . getName ( ) ; String methodName = method . getMethod ( ) . getName ( ) ; String etag = "" ; String cacheControl = "" ; String hadEtag = "" ; long size = ; int status = ; if ( response instanceof VRaptorResponse ) { VRaptorResponse r = ( VRaptorResponse ) response ; ServletResponse sr = r . getResponse ( ) ; if ( sr instanceof ObservableResponse ) { ObservableResponse resp = ( ObservableResponse ) sr ; etag = resp . getEtagHeader ( ) ; if ( etag . equals ( "" ) ) { etag = resp . getMd5 ( ) ; hadEtag = "" ; } else { hadEtag = "" ; } size = resp . size ( ) ; cacheControl = resp . getCacheControlHeader ( ) ; status = resp . getGivenStatus ( ) ; } } String queryString = extractQueryString ( request . getMethod ( ) ) ; Stat stat = new Stat ( key , request . getRequestURI ( ) , queryString , time , request . getMethod ( ) , resource , methodName , etag , status , hadEtag , cacheControl , size ) ; saveStat ( stat ) ; } catch ( Exception ex ) { LOG . error ( "" , ex ) ; } } private String extractQueryString ( String method ) { if ( ! method . equalsIgnoreCase ( "" ) ) return "" ; String queryString = "" ; Enumeration < String > paramNames = request . getParameterNames ( ) ; boolean hadParameter = false ; while ( paramNames . hasMoreElements ( ) ) { if ( hadParameter ) { queryString += "" ; } String name = paramNames . nextElement ( ) ; queryString += name + "" + request . getParameter ( name ) ; hadParameter = true ; } return queryString ; } protected void saveStat ( Stat stat ) { stat . log ( ) ; } public static String userKey ( Container container ) { String key = "" ; try { IdeableUser user = container . instanceFor ( IdeableUser . class ) ; key = user . getId ( ) . toString ( ) ; } catch ( Exception e ) { key = "" ; } return key ; } } package br . com . caelum . vraptor . dash . uristats ; import java . io . Serializable ; public interface IdeableUser { Serializable getId ( ) ; } package br . com . caelum . vraptor . dash . uristats ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . hibernate . Session ; import org . hibernate . Transaction ; import br . com . caelum . vraptor . ioc . Container ; public class SessionURIStatInterceptor extends BaseURIStatInterceptor { private final Session session ; public SessionURIStatInterceptor ( Container container , Session session , HttpServletRequest request , HttpServletResponse response ) { super ( container , request , response ) ; this . session = session ; } protected void saveStat ( Stat stat ) { Transaction tx = session . getTransaction ( ) ; boolean created = false ; if ( tx == null || ! tx . isActive ( ) ) { tx = session . beginTransaction ( ) ; created = true ; } try { session . save ( stat ) ; if ( created ) { tx . commit ( ) ; } } finally { if ( created && tx . isActive ( ) ) { tx . rollback ( ) ; } } } } package br . com . caelum . vraptor . dash . uristats ; import java . util . Calendar ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . Lob ; import javax . persistence . Table ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; @ Table ( name = "" ) @ Entity ( name = "" ) public class Stat { @ Id @ GeneratedValue private Long id ; @ Lob private final String uri ; @ Lob private final String queryString ; private final String userId ; private final Calendar createdAt ; private final String verb ; private final String resource ; private final String method ; private final long time ; private final String etag ; private final int resultCode ; private final String hadEtag ; private final String cache ; private final long size ; Stat ( ) { this ( "" , "" , "" , , "" , "" , "" , "" , , "" , "" , ) ; } public Stat ( String userId , String uri , String queryString , long time , String verb , String resource , String action , String etag , int resultCode , String hadEtag , String cache , long size ) { this . userId = userId ; this . uri = uri ; this . queryString = queryString ; this . time = time ; this . verb = verb ; this . resultCode = resultCode ; this . hadEtag = hadEtag ; this . cache = cache ; this . size = size ; this . createdAt = Calendar . getInstance ( ) ; this . resource = resource ; this . method = action ; this . etag = etag ; } private static final Logger LOG = LoggerFactory . getLogger ( Stat . class ) ; public void log ( ) { if ( "" . equalsIgnoreCase ( verb ) ) { LOG . info ( String . format ( "" , createdAt , etag , verb , resource , method , time , hadEtag , resultCode , cache , size , userId , uri , queryString ) ) ; } else { LOG . info ( String . format ( "" , createdAt , etag , verb , resource , method , time , hadEtag , resultCode , cache , size , userId , uri ) ) ; } } } package br . com . caelum . vraptor . dash . config ; import javax . persistence . Column ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . Table ; import org . hibernate . annotations . Cache ; import org . hibernate . annotations . CacheConcurrencyStrategy ; @ Table ( name = "" ) @ Entity ( name = "" ) @ Cache ( usage = CacheConcurrencyStrategy . NONSTRICT_READ_WRITE ) public class UserConfig { @ Id @ GeneratedValue private Long id ; @ Column ( name = "" ) private String key ; private String value ; private String userId ; UserConfig ( ) { this ( "" , "" , "" ) ; } public UserConfig ( String key , String value , String userId ) { this . key = key ; this . value = value ; this . userId = userId ; } public String getKey ( ) { return key ; } public void setKey ( String key ) { this . key = key ; } public String getValue ( ) { return value ; } public void setValue ( String value ) { this . value = value ; } } package br . com . caelum . vraptor . dash . config ; public interface ConfigurationsAwareUser { boolean canSeeConfigurations ( ) ; } package br . com . caelum . vraptor . dash . config ; import java . io . IOException ; import java . util . List ; import org . hibernate . Query ; import org . hibernate . Session ; import br . com . caelum . vraptor . Get ; import br . com . caelum . vraptor . Path ; import br . com . caelum . vraptor . Post ; import br . com . caelum . vraptor . Resource ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . dash . uristats . IdeableUser ; import br . com . caelum . vraptor . freemarker . FreemarkerView ; import br . com . caelum . vraptor . view . HttpResult ; import freemarker . template . TemplateException ; import javax . servlet . http . HttpServletResponse ; @ Resource public class ConfigController { private static final String JS = "" ; private final Session session ; private final IdeableUser currentUser ; private final Result result ; private final ConfigurationsAwareUser user ; private final HttpServletResponse response ; public ConfigController ( Session session , IdeableUser currentUser , Result result , ConfigurationsAwareUser user , HttpServletResponse response ) { this . session = session ; this . currentUser = currentUser ; this . result = result ; this . user = user ; this . response = response ; } @ SuppressWarnings ( "" ) private List < UserConfig > all ( String key ) { if ( ! user . canSeeConfigurations ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return null ; } Query all = session . createQuery ( "" ) . setCacheable ( true ) ; all . setParameter ( "" , currentUser . getId ( ) ) ; all . setParameter ( "" , key ) ; return all . list ( ) ; } @ Path ( "" ) @ Post public void create ( String key , String value ) throws IOException , TemplateException { if ( ! user . canSeeConfigurations ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } session . save ( new UserConfig ( key , value , currentUser . getId ( ) . toString ( ) ) ) ; result . nothing ( ) ; } @ Path ( "" ) @ Get public void js ( String key ) throws IOException , TemplateException { if ( ! user . canSeeConfigurations ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } result . include ( "" , all ( key ) ) ; response . setContentType ( "" ) ; result . use ( FreemarkerView . class ) . withTemplate ( JS ) ; } } package br . com . caelum . vraptor . dash . hibernate ; import java . text . NumberFormat ; import org . hibernate . stat . Statistics ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . dash . statistics . Collector ; public class HibernateStatisticsCollector implements Collector { private NumberFormat decimalFormat ; private Statistics statistics ; public HibernateStatisticsCollector ( Statistics statistics ) { this . statistics = statistics ; this . decimalFormat = NumberFormat . getNumberInstance ( ) ; } public void collect ( Result result ) { result . include ( "" , decimalFormat . format ( statistics . getConnectCount ( ) ) ) ; result . include ( "" , decimalFormat . format ( statistics . getSecondLevelCacheMissCount ( ) ) ) ; result . include ( "" , decimalFormat . format ( statistics . getSecondLevelCacheHitCount ( ) ) ) ; result . include ( "" , decimalFormat . format ( statistics . getSecondLevelCachePutCount ( ) ) ) ; } } package br . com . caelum . vraptor . dash . hibernate . stats ; public class EntityCacheStatsWrapper { private EntityStatsWrapper entityStatsWrapper ; private CacheStatsWrapper cacheStatsWrapper ; public void setEntityStatsWrapper ( EntityStatsWrapper entityStatsWrapper ) { this . entityStatsWrapper = entityStatsWrapper ; } public void setCacheStatsWrapper ( CacheStatsWrapper cacheStatsWrapper ) { this . cacheStatsWrapper = cacheStatsWrapper ; } public String getName ( ) { if ( "" . equals ( getEntityName ( ) ) ) { return getCacheName ( ) ; } return getEntityName ( ) ; } public long getFetchCount ( ) { return entityStatsWrapper == null ? : entityStatsWrapper . getFetchCount ( ) ; } public long getLoadCount ( ) { return entityStatsWrapper == null ? : entityStatsWrapper . getLoadCount ( ) ; } public String getEntityName ( ) { return entityStatsWrapper == null ? "" : entityStatsWrapper . getEntityName ( ) ; } public long getHitCount ( ) { return cacheStatsWrapper == null ? : cacheStatsWrapper . getHitCount ( ) ; } public long getMissCount ( ) { return cacheStatsWrapper == null ? : cacheStatsWrapper . getMissCount ( ) ; } public long getPutCount ( ) { return cacheStatsWrapper == null ? : cacheStatsWrapper . getPutCount ( ) ; } public String getCacheName ( ) { return cacheStatsWrapper == null ? "" : cacheStatsWrapper . getCacheName ( ) ; } } package br . com . caelum . vraptor . dash . hibernate . stats ; import java . lang . reflect . Method ; import java . util . Calendar ; import java . util . Random ; import br . com . caelum . vraptor . resource . ResourceMethod ; public class OpenRequest { private final String resource ; private final Calendar startingTime ; private final long id ; public OpenRequest ( ResourceMethod resourceMethod ) { this ( resourceMethod . getMethod ( ) , resourceMethod . getResource ( ) . getType ( ) ) ; } public OpenRequest ( Method method , Class < ? > type ) { this ( method , type , Calendar . getInstance ( ) ) ; } public OpenRequest ( Method method , Class < ? > type , Calendar startingTime ) { this . resource = ( "" + method . getName ( ) + "" + type . getName ( ) ) ; this . startingTime = startingTime ; this . id = hashCode ( ) * new Random ( ) . nextInt ( ) ; } public String getResource ( ) { return resource ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( startingTime == null ) ? : startingTime . hashCode ( ) ) ; result = prime * result + ( ( resource == null ) ? : resource . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } OpenRequest other = ( OpenRequest ) obj ; if ( startingTime == null ) { if ( other . startingTime != null ) { return false ; } } else if ( ! startingTime . equals ( other . startingTime ) ) { return false ; } if ( resource == null ) { if ( other . resource != null ) { return false ; } } else if ( ! resource . equals ( other . resource ) ) { return false ; } return true ; } public Long getLivingTimeInSeconds ( ) { return ( Calendar . getInstance ( ) . getTimeInMillis ( ) - this . startingTime . getTimeInMillis ( ) ) / ; } public Long getId ( ) { return this . id ; } } package br . com . caelum . vraptor . dash . hibernate . stats ; import org . hibernate . stat . QueryStatistics ; public class QueryStatsWrapper { private final String query ; private final QueryStatistics queryStats ; public QueryStatsWrapper ( String query , QueryStatistics queryStats ) { this . query = query ; this . queryStats = queryStats ; } public long getCacheHitCount ( ) { return queryStats . getCacheHitCount ( ) ; } public long getCacheMissCount ( ) { return queryStats . getCacheMissCount ( ) ; } public long getCachePutCount ( ) { return queryStats . getCachePutCount ( ) ; } public long getExecutionAvgTime ( ) { return queryStats . getExecutionAvgTime ( ) ; } public long getExecutionCount ( ) { return queryStats . getExecutionCount ( ) ; } public String getQuery ( ) { return query ; } } package br . com . caelum . vraptor . dash . hibernate . stats ; public interface HibernateStatsAwareUser { boolean canSeeHibernateStats ( ) ; } package br . com . caelum . vraptor . dash . hibernate . stats ; import org . hibernate . stat . EntityStatistics ; public class EntityStatsWrapper { private final String entityName ; private final EntityStatistics entityStatistics ; public EntityStatsWrapper ( String entityName , EntityStatistics entityStatistics ) { this . entityName = entityName ; this . entityStatistics = entityStatistics ; } public long getFetchCount ( ) { return entityStatistics . getFetchCount ( ) ; } public long getLoadCount ( ) { return entityStatistics . getLoadCount ( ) ; } public String getEntityName ( ) { return entityName ; } } package br . com . caelum . vraptor . dash . hibernate . stats ; import br . com . caelum . vraptor . Path ; import br . com . caelum . vraptor . Resource ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . view . HttpResult ; @ Resource public class RequestsController { private final Result result ; private final OpenRequests requests ; private final HibernateStatsAwareUser user ; public RequestsController ( Result result , OpenRequests requests , HibernateStatsAwareUser user ) { this . result = result ; this . requests = requests ; this . user = user ; } @ Path ( "" ) public void show ( ) { if ( ! user . canSeeHibernateStats ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } result . include ( "" , requests . toMap ( ) ) ; } } package br . com . caelum . vraptor . dash . hibernate . stats ; import org . hibernate . stat . SecondLevelCacheStatistics ; public class CacheStatsWrapper { private final String cacheName ; private final SecondLevelCacheStatistics statistics ; public CacheStatsWrapper ( String cacheName , SecondLevelCacheStatistics statistics ) { this . cacheName = cacheName ; this . statistics = statistics ; } public long getHitCount ( ) { return statistics . getHitCount ( ) ; } public long getMissCount ( ) { return statistics . getMissCount ( ) ; } public long getPutCount ( ) { return statistics . getPutCount ( ) ; } public String getCacheName ( ) { return cacheName ; } } package br . com . caelum . vraptor . dash . hibernate . stats ; import org . hibernate . stat . CollectionStatistics ; import org . hibernate . stat . SecondLevelCacheStatistics ; import org . hibernate . stat . Statistics ; public class CollectionStatsWrapper { private final String collectionRoleName ; private final CollectionStatistics collectionStatistics ; private SecondLevelCacheStatistics collectionSecondLevel ; public CollectionStatsWrapper ( String collectionRoleName , Statistics statistics ) { this . collectionRoleName = collectionRoleName ; this . collectionStatistics = statistics . getCollectionStatistics ( collectionRoleName ) ; this . collectionSecondLevel = statistics . getSecondLevelCacheStatistics ( collectionRoleName ) ; } public String getCollectionRoleName ( ) { return collectionRoleName ; } public long getFetchCount ( ) { return collectionStatistics == null ? : collectionStatistics . getFetchCount ( ) ; } public long getLoadCount ( ) { return collectionStatistics == null ? : collectionStatistics . getLoadCount ( ) ; } public long getHitCount ( ) { return collectionSecondLevel == null ? : collectionSecondLevel . getHitCount ( ) ; } public long getMissCount ( ) { return collectionSecondLevel == null ? : collectionSecondLevel . getMissCount ( ) ; } public long getPutCount ( ) { return collectionSecondLevel == null ? : collectionSecondLevel . getPutCount ( ) ; } } package br . com . caelum . vraptor . dash . hibernate . stats ; import br . com . caelum . vraptor . InterceptionException ; import br . com . caelum . vraptor . core . InterceptorStack ; import br . com . caelum . vraptor . interceptor . Interceptor ; import br . com . caelum . vraptor . ioc . Component ; import br . com . caelum . vraptor . resource . ResourceMethod ; @ Component public class OpenRequestInterceptor implements Interceptor { private final OpenRequests requests ; public OpenRequestInterceptor ( OpenRequests requests ) { this . requests = requests ; } @ Override public boolean accepts ( ResourceMethod arg0 ) { return true ; } @ Override public void intercept ( InterceptorStack stack , ResourceMethod method , Object instance ) throws InterceptionException { OpenRequest openRequest = requests . add ( method ) ; try { stack . next ( method , instance ) ; } finally { requests . remove ( openRequest ) ; } } } package br . com . caelum . vraptor . dash . hibernate . stats ; import java . util . Map ; import java . util . concurrent . ConcurrentHashMap ; import br . com . caelum . vraptor . ioc . ApplicationScoped ; import br . com . caelum . vraptor . ioc . Component ; import br . com . caelum . vraptor . resource . ResourceMethod ; @ ApplicationScoped @ Component public class OpenRequests { private final Map < Long , OpenRequest > openRequests = new ConcurrentHashMap < Long , OpenRequest > ( ) ; public OpenRequest add ( ResourceMethod resourceMethod ) { OpenRequest req = new OpenRequest ( resourceMethod ) ; openRequests . put ( req . getId ( ) , req ) ; return req ; } public void remove ( OpenRequest request ) { openRequests . remove ( request . getId ( ) ) ; } public Map < Long , OpenRequest > toMap ( ) { return openRequests ; } } package br . com . caelum . vraptor . dash . hibernate ; public interface HibernateAuditAwareUser { boolean canSeeHibernateAudits ( ) ; } package br . com . caelum . vraptor . dash . hibernate ; import java . io . IOException ; import java . text . NumberFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . sf . ehcache . CacheManager ; import net . vidageek . mirror . dsl . Mirror ; import org . hibernate . Session ; import org . hibernate . stat . EntityStatistics ; import org . hibernate . stat . QueryStatistics ; import org . hibernate . stat . Statistics ; import br . com . caelum . vraptor . Get ; import br . com . caelum . vraptor . Path ; import br . com . caelum . vraptor . Resource ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . dash . hibernate . stats . CacheStatsWrapper ; import br . com . caelum . vraptor . dash . hibernate . stats . CollectionStatsWrapper ; import br . com . caelum . vraptor . dash . hibernate . stats . EntityCacheStatsWrapper ; import br . com . caelum . vraptor . dash . hibernate . stats . EntityStatsWrapper ; import br . com . caelum . vraptor . dash . hibernate . stats . QueryStatsWrapper ; import br . com . caelum . vraptor . dash . runtime . RuntimeStatisticsCollector ; import br . com . caelum . vraptor . dash . statistics . Collectors ; import br . com . caelum . vraptor . freemarker . FreemarkerView ; import br . com . caelum . vraptor . freemarker . Template ; import br . com . caelum . vraptor . view . HttpResult ; import com . mchange . v2 . c3p0 . mbean . C3P0PooledDataSource ; @ Resource public class AuditController { private static final String CONTROL_PANEL = "" ; private final Session session ; private final HibernateAuditAwareUser user ; private final Result result ; public AuditController ( Session session , HibernateAuditAwareUser user , Result result ) { this . session = session ; this . user = user ; this . result = result ; } @ Path ( "" ) @ Get public void controlPanel ( ) { if ( ! user . canSeeHibernateAudits ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } NumberFormat decimalFormat = NumberFormat . getNumberInstance ( ) ; decimalFormat . setGroupingUsed ( true ) ; Statistics statistics = session . getSessionFactory ( ) . getStatistics ( ) ; Runtime runtime = Runtime . getRuntime ( ) ; Collectors collectors = new Collectors ( Arrays . asList ( new HibernateStatisticsCollector ( statistics ) , new RuntimeStatisticsCollector ( runtime ) ) ) ; collectStatistics ( collectors ) ; C3P0PooledDataSource c3p0PooledDataSource = new C3P0PooledDataSource ( ) ; result . include ( "" , c3p0PooledDataSource . getMaxPoolSize ( ) ) ; result . include ( "" , c3p0PooledDataSource . getInitialPoolSize ( ) ) ; result . include ( "" , c3p0PooledDataSource . getMinPoolSize ( ) ) ; String [ ] queries = statistics . getQueries ( ) ; List < QueryStatsWrapper > queryStatsList = new ArrayList < QueryStatsWrapper > ( ) ; for ( String query : queries ) { QueryStatistics queryStats = statistics . getQueryStatistics ( query ) ; queryStatsList . add ( new QueryStatsWrapper ( query , queryStats ) ) ; } result . include ( "" , queryStatsList ) ; String [ ] entityNames = statistics . getEntityNames ( ) ; Map < String , EntityCacheStatsWrapper > entityCacheStats = new HashMap < String , EntityCacheStatsWrapper > ( ) ; for ( String entityName : entityNames ) { EntityStatistics entityStatistics = statistics . getEntityStatistics ( entityName ) ; EntityCacheStatsWrapper entityCacheStatsWrapper = new EntityCacheStatsWrapper ( ) ; entityCacheStatsWrapper . setEntityStatsWrapper ( new EntityStatsWrapper ( entityName , entityStatistics ) ) ; entityCacheStats . put ( entityName , entityCacheStatsWrapper ) ; } for ( String regionName : statistics . getSecondLevelCacheRegionNames ( ) ) { CacheStatsWrapper cacheStatsWrapper = new CacheStatsWrapper ( regionName , statistics . getSecondLevelCacheStatistics ( regionName ) ) ; if ( entityCacheStats . containsKey ( regionName ) ) { EntityCacheStatsWrapper entityCacheStatsWrapper = entityCacheStats . get ( regionName ) ; EntityCacheStatsWrapper entityStatsWrapper = entityCacheStatsWrapper ; entityStatsWrapper . setCacheStatsWrapper ( cacheStatsWrapper ) ; } else { EntityCacheStatsWrapper entityCacheStatsWrapper = new EntityCacheStatsWrapper ( ) ; entityCacheStatsWrapper . setCacheStatsWrapper ( cacheStatsWrapper ) ; entityCacheStats . put ( regionName , entityCacheStatsWrapper ) ; } } result . include ( "" , entityCacheStats ) ; List < CollectionStatsWrapper > collectionsStatsList = new ArrayList < CollectionStatsWrapper > ( ) ; for ( String collectionRoleName : statistics . getCollectionRoleNames ( ) ) { collectionsStatsList . add ( new CollectionStatsWrapper ( collectionRoleName , statistics ) ) ; } result . include ( "" , collectionsStatsList ) ; List < net . sf . ehcache . Statistics > collectionsCacheStatsList = new ArrayList < net . sf . ehcache . Statistics > ( ) ; List < CacheManager > allCacheManagers = CacheManager . ALL_CACHE_MANAGERS ; for ( CacheManager cacheManager : allCacheManagers ) { for ( String cacheName : cacheManager . getCacheNames ( ) ) { collectionsCacheStatsList . add ( cacheManager . getCache ( cacheName ) . getStatistics ( ) ) ; } } result . include ( "" , collectionsCacheStatsList ) ; includeMethodInvocationReturnInResult ( "" , c3p0PooledDataSource , "" ) ; includeMethodInvocationReturnInResult ( "" , c3p0PooledDataSource , "" ) ; includeMethodInvocationReturnInResult ( "" , c3p0PooledDataSource , "" ) ; includeMethodInvocationReturnInResult ( "" , c3p0PooledDataSource , "" ) ; result . use ( FreemarkerView . class ) . withTemplate ( CONTROL_PANEL ) ; } void collectStatistics ( Collectors collectors ) { collectors . collect ( result ) ; } void includeMethodInvocationReturnInResult ( String name , Object obj , String methodName ) { try { Object toBeIncluded = new Mirror ( ) . on ( obj ) . invoke ( ) . method ( methodName ) . withoutArgs ( ) ; result . include ( name , toBeIncluded ) ; } catch ( Exception e ) { result . include ( name , "" ) ; } } } package br . com . caelum . vraptor . dash . interceptor ; import javax . servlet . http . HttpServletResponse ; import br . com . caelum . vraptor . InterceptionException ; import br . com . caelum . vraptor . Intercepts ; import br . com . caelum . vraptor . Lazy ; import br . com . caelum . vraptor . core . InterceptorStack ; import br . com . caelum . vraptor . interceptor . Interceptor ; import br . com . caelum . vraptor . ioc . RequestScoped ; import br . com . caelum . vraptor . resource . ResourceMethod ; @ Intercepts @ RequestScoped @ Lazy public class ContentTypeInterceptor implements Interceptor { private final HttpServletResponse response ; public ContentTypeInterceptor ( HttpServletResponse response ) { this . response = response ; } @ Override public boolean accepts ( ResourceMethod method ) { return method . getResource ( ) . getType ( ) . getPackage ( ) . getName ( ) . startsWith ( "" ) ; } @ Override public void intercept ( InterceptorStack stack , ResourceMethod method , Object object ) throws InterceptionException { response . setContentType ( "" ) ; stack . next ( method , object ) ; } } package br . com . caelum . vraptor . dash . audit ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . METHOD ) public @ interface Audit { String [ ] value ( ) default { } ; } package br . com . caelum . vraptor . dash . audit ; import javax . servlet . http . HttpServletRequest ; import org . apache . log4j . Logger ; import br . com . caelum . vraptor . InterceptionException ; import br . com . caelum . vraptor . core . InterceptorStack ; import br . com . caelum . vraptor . dash . uristats . BaseURIStatInterceptor ; import br . com . caelum . vraptor . interceptor . Interceptor ; import br . com . caelum . vraptor . ioc . Component ; import br . com . caelum . vraptor . ioc . Container ; import br . com . caelum . vraptor . resource . ResourceMethod ; @ Component public class AuditLogInterceptor implements Interceptor { private static final Logger LOG = Logger . getLogger ( AuditLogInterceptor . class ) ; private final HttpServletRequest request ; private final Container container ; public AuditLogInterceptor ( Container container , HttpServletRequest request ) { this . container = container ; this . request = request ; } @ Override public boolean accepts ( ResourceMethod method ) { return method . containsAnnotation ( Audit . class ) ; } @ Override public void intercept ( InterceptorStack stack , ResourceMethod method , Object object ) throws InterceptionException { try { if ( LOG . isInfoEnabled ( ) ) { StringBuilder builder = new StringBuilder ( String . format ( "" , method . toString ( ) , BaseURIStatInterceptor . userKey ( container ) , request . getRemoteAddr ( ) , request . getRemoteHost ( ) , request . getHeader ( "" ) ) ) ; if ( "" . equalsIgnoreCase ( request . getMethod ( ) ) ) { Audit audit = method . getMethod ( ) . getAnnotation ( Audit . class ) ; for ( String value : audit . value ( ) ) { builder . append ( "" + value + "" + request . getParameter ( value ) + "" ) ; } } LOG . info ( builder . toString ( ) ) ; } stack . next ( method , object ) ; } catch ( Exception ex ) { LOG . error ( "" , ex ) ; } } } package br . com . caelum . vraptor . dash . cache ; import java . io . IOException ; import javax . servlet . Filter ; import javax . servlet . FilterChain ; import javax . servlet . FilterConfig ; import javax . servlet . ServletException ; import javax . servlet . ServletRequest ; import javax . servlet . ServletResponse ; import javax . servlet . http . HttpServletResponse ; import org . apache . log4j . Logger ; public class CacheCheckFilter implements Filter { private final static Logger LOGGER = Logger . getLogger ( CacheCheckFilter . class ) ; public void destroy ( ) { } public void doFilter ( ServletRequest req , ServletResponse res , FilterChain chain ) throws IOException , ServletException { try { res = new ObservableResponse ( ( HttpServletResponse ) res ) ; } catch ( Exception ex ) { LOGGER . error ( "" , ex ) ; } chain . doFilter ( req , res ) ; } public void init ( FilterConfig arg0 ) throws ServletException { } } package br . com . caelum . vraptor . dash . cache ; import java . io . IOException ; import java . io . PrintWriter ; import java . security . MessageDigest ; import java . security . NoSuchAlgorithmException ; import javax . servlet . ServletOutputStream ; import javax . servlet . http . HttpServletResponse ; import javax . servlet . http . HttpServletResponseWrapper ; public class ObservableResponse extends HttpServletResponseWrapper { private MessageDigest digester ; public ObservableResponse ( HttpServletResponse res ) { super ( res ) ; try { this . digester = MessageDigest . getInstance ( "" ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } } private int status = ; private PrintWriter writer ; private ResponseServletOutputStream oStream ; private String cacheControl = "" ; private String etag = "" ; public ServletOutputStream getOutputStream ( ) throws IOException { if ( this . oStream == null ) { this . oStream = new ResponseServletOutputStream ( super . getOutputStream ( ) ) ; } return this . oStream ; } public PrintWriter getWriter ( ) throws IOException { if ( this . writer == null ) { this . writer = new ResponsePrintWriter ( super . getWriter ( ) ) ; } return this . writer ; } @ Override public void resetBuffer ( ) { try { this . digester = MessageDigest . getInstance ( "" ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } } @ Override public void reset ( ) { super . reset ( ) ; resetBuffer ( ) ; } public String getMd5 ( ) { String c = "" ; for ( byte b : this . digester . digest ( ) ) { c += ( int ) b ; } return c ; } private int size ; private class ResponseServletOutputStream extends ServletOutputStream { private final ServletOutputStream original ; public ResponseServletOutputStream ( ServletOutputStream outputStream ) { this . original = outputStream ; } @ Override public void write ( int b ) throws IOException { original . write ( b ) ; digester . update ( ( byte ) b ) ; size ++ ; } @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { original . write ( b , off , len ) ; digester . update ( b , off , len ) ; size += len ; } } private class ResponsePrintWriter extends PrintWriter { private ResponsePrintWriter ( PrintWriter printWriter ) { super ( printWriter ) ; } @ Override public void write ( char buf [ ] , int off , int len ) { super . write ( buf , off , len ) ; super . flush ( ) ; size += len ; digester . update ( new String ( buf ) . getBytes ( ) ) ; } @ Override public void write ( String s , int off , int len ) { super . write ( s , off , len ) ; super . flush ( ) ; size += len ; digester . update ( s . getBytes ( ) ) ; } @ Override public void write ( int c ) { size ++ ; digester . update ( ( byte ) c ) ; super . write ( c ) ; super . flush ( ) ; } } public long size ( ) { return size ; } @ Override public void addHeader ( String name , String value ) { if ( name . toLowerCase ( ) . equals ( "" ) ) { this . cacheControl += "" + value ; } else if ( name . toLowerCase ( ) . equals ( "" ) ) { this . etag += "" + value ; } super . addHeader ( name , value ) ; } @ Override public void setHeader ( String name , String value ) { if ( name . toLowerCase ( ) . equals ( "" ) ) { this . cacheControl = value ; } else if ( name . toLowerCase ( ) . equals ( "" ) ) { this . etag = value ; } super . setHeader ( name , value ) ; } public String getEtagHeader ( ) { return etag ; } public String getCacheControlHeader ( ) { return cacheControl ; } public int getGivenStatus ( ) { return status ; } @ Override public void sendError ( int sc , String msg ) throws IOException { this . status = sc ; super . sendError ( sc , msg ) ; } @ Override public void sendError ( int sc ) throws IOException { this . status = sc ; super . sendError ( sc ) ; } @ Override public void sendRedirect ( String location ) throws IOException { this . status = ; super . sendRedirect ( location ) ; } @ Override public void setStatus ( int sc , String sm ) { this . status = sc ; super . setStatus ( sc , sm ) ; } @ Override public void setStatus ( int sc ) { this . status = sc ; super . setStatus ( sc ) ; } } package br . com . caelum . vraptor . dash . monitor ; import java . io . ByteArrayInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . nio . charset . Charset ; import java . util . Map . Entry ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import br . com . caelum . vraptor . Get ; import br . com . caelum . vraptor . Resource ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . dash . audit . Audit ; import br . com . caelum . vraptor . dash . hibernate . AuditController ; import br . com . caelum . vraptor . environment . Environment ; import br . com . caelum . vraptor . freemarker . FreemarkerView ; import br . com . caelum . vraptor . interceptor . download . InputStreamDownload ; import br . com . caelum . vraptor . view . HttpResult ; import br . com . caelum . vraptor . view . Results ; import freemarker . template . TemplateException ; @ Resource public class SystemController { public static final String ALLOWED_LOG_REGEX = "" ; private static final Logger LOG = LoggerFactory . getLogger ( AuditController . class ) ; private final Environment environment ; private final Result result ; private final MonitorAwareUser user ; public SystemController ( Environment environment , Result result , MonitorAwareUser user ) { this . environment = environment ; this . result = result ; this . user = user ; } @ Get ( "" ) public InputStreamDownload properties ( ) throws IOException { if ( ! user . canSeeMonitorStats ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return null ; } StringBuilder sb = new StringBuilder ( ) ; Set < Entry < Object , Object > > entrySet = System . getProperties ( ) . entrySet ( ) ; for ( Entry < Object , Object > entry : entrySet ) { sb . append ( String . format ( "" , entry . getKey ( ) , entry . getValue ( ) ) ) ; } sb . append ( String . format ( "" , "" , Charset . defaultCharset ( ) ) ) ; return new InputStreamDownload ( new ByteArrayInputStream ( sb . toString ( ) . getBytes ( ) ) , "" , "" ) ; } @ Get ( "" ) @ Audit public InputStreamDownload log ( String name ) throws IOException { if ( ! user . canSeeMonitorStats ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return null ; } File file = new File ( name ) ; String allowedPattern = environment . get ( SystemController . ALLOWED_LOG_REGEX ) ; if ( ! name . matches ( allowedPattern ) ) { result . use ( Results . status ( ) ) . forbidden ( "" ) ; return null ; } LOG . debug ( "" + file . getCanonicalPath ( ) ) ; if ( ! file . exists ( ) ) { throw new IllegalStateException ( "" ) ; } return new InputStreamDownload ( new FileInputStream ( file ) , "" , "" ) ; } @ Get ( "" ) public void threads ( ) throws IOException , TemplateException { if ( ! user . canSeeMonitorStats ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } result . include ( "" , Thread . getAllStackTraces ( ) . entrySet ( ) ) ; result . use ( FreemarkerView . class ) . withTemplate ( "" ) ; } @ Get ( "" ) public void threadStats ( ) { if ( ! user . canSeeMonitorStats ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } new BasicMonitor ( ) . logStats ( ) ; result . use ( Results . http ( ) ) . body ( "" ) . setStatusCode ( ) ; } } package br . com . caelum . vraptor . dash . monitor ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import br . com . caelum . vraptor . Get ; import br . com . caelum . vraptor . Path ; import br . com . caelum . vraptor . Resource ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . environment . Environment ; import br . com . caelum . vraptor . freemarker . FreemarkerView ; import br . com . caelum . vraptor . http . route . Route ; import br . com . caelum . vraptor . http . route . Router ; import br . com . caelum . vraptor . view . HttpResult ; import freemarker . template . TemplateException ; @ Resource public class RoutesController { private static final String PRODUCTION = "" ; private static final String INDEX = "" ; private final Router router ; private final Environment environment ; private final Result result ; private final MonitorAwareUser user ; public RoutesController ( Router router , Result result , Environment environment , MonitorAwareUser user ) { this . router = router ; this . result = result ; this . environment = environment ; this . user = user ; } @ Path ( "" ) @ Get public void allRoutes ( ) throws IOException , TemplateException { if ( PRODUCTION . equals ( environment . getName ( ) ) ) { throw new UnsupportedOperationException ( ) ; } if ( ! user . canSeeMonitorStats ( ) ) { result . use ( HttpResult . class ) . sendError ( ) ; return ; } List < Route > routes = orderRoutesByURI ( router . allRoutes ( ) ) ; List < FreemarkerRoute > freemarkerRoutes = createRoutesForFreeMarker ( routes ) ; result . include ( "" , freemarkerRoutes ) ; result . use ( FreemarkerView . class ) . withTemplate ( INDEX ) ; } private List < FreemarkerRoute > createRoutesForFreeMarker ( List < Route > routes ) { List < FreemarkerRoute > freemakerRoutes = new ArrayList < FreemarkerRoute > ( ) ; for ( Route route : routes ) { freemakerRoutes . add ( new FreemarkerRoute ( route ) ) ; } return freemakerRoutes ; } private List < Route > orderRoutesByURI ( List < Route > allRoutes ) { List < Route > routes = new ArrayList < Route > ( allRoutes ) ; Collections . sort ( routes , new RouteUriComparator ( ) ) ; return routes ; } private final class RouteUriComparator implements Comparator < Route > { public int compare ( Route r1 , Route r2 ) { return r1 . getOriginalUri ( ) . compareTo ( r2 . getOriginalUri ( ) ) ; } } } package br . com . caelum . vraptor . dash . monitor ; import java . lang . reflect . Field ; import java . util . EnumSet ; import net . vidageek . mirror . dsl . Mirror ; import br . com . caelum . vraptor . http . route . FixedMethodStrategy ; import br . com . caelum . vraptor . http . route . Route ; import br . com . caelum . vraptor . resource . HttpMethod ; import br . com . caelum . vraptor . resource . ResourceMethod ; public class FreemarkerRoute { private final Route route ; public FreemarkerRoute ( Route route ) { this . route = route ; } public String getAllowedMethods ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; if ( routeSupportsAllHttpMethods ( this . route ) ) { builder . append ( "" ) ; } else { builder . append ( httpMethodsToString ( this . route . allowedMethods ( ) ) ) ; } builder . append ( "" ) ; return builder . toString ( ) ; } public String getControllerAndMethodName ( ) { Field resourceMethodField = new Mirror ( ) . on ( FixedMethodStrategy . class ) . reflect ( ) . field ( "" ) ; resourceMethodField . setAccessible ( true ) ; try { ResourceMethod resourceMethod = ( ResourceMethod ) resourceMethodField . get ( route ) ; return resourceMethod . getMethod ( ) . toString ( ) ; } catch ( Exception e ) { return "" + e . getMessage ( ) ; } } public String getOriginalUri ( ) { return route . getOriginalUri ( ) ; } private void deleteLastCharFrom ( StringBuilder builder ) { builder . deleteCharAt ( builder . length ( ) - ) ; } private String httpMethodsToString ( EnumSet < HttpMethod > httpMethods ) { StringBuilder builder = new StringBuilder ( ) ; for ( HttpMethod httpMethod : httpMethods ) { builder . append ( httpMethod . name ( ) ) ; builder . append ( "" ) ; } deleteLastCharFrom ( builder ) ; return builder . toString ( ) ; } private boolean routeSupportsAllHttpMethods ( Route route ) { return route . allowedMethods ( ) . size ( ) == HttpMethod . values ( ) . length ; } } package br . com . caelum . vraptor . dash . monitor ; import java . lang . management . ManagementFactory ; import java . lang . management . MemoryMXBean ; import java . lang . management . ThreadMXBean ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class BasicMonitor { private static final Logger logger = LoggerFactory . getLogger ( BasicMonitor . class ) ; public void logStats ( ) { ThreadMXBean threads = ManagementFactory . getThreadMXBean ( ) ; MemoryMXBean memory = ManagementFactory . getMemoryMXBean ( ) ; checkDeadlocks ( threads ) ; logger . info ( "" , new Object [ ] { memory . getHeapMemoryUsage ( ) . getUsed ( ) / ( * ) , memory . getHeapMemoryUsage ( ) . getMax ( ) / ( * ) , threads . getThreadCount ( ) } ) ; } private void checkDeadlocks ( ThreadMXBean threads ) { { long [ ] ids = threads . findDeadlockedThreads ( ) ; if ( ids != null ) { for ( long id : ids ) { logger . info ( "" , threads . getThreadInfo ( id ) . getThreadName ( ) ) ; logTrace ( threads . getThreadInfo ( id ) . getStackTrace ( ) ) ; } } } { long [ ] ids = threads . findMonitorDeadlockedThreads ( ) ; if ( ids != null ) { for ( long id : ids ) { logger . info ( "" , threads . getThreadInfo ( id ) . getThreadName ( ) ) ; logTrace ( threads . getThreadInfo ( id ) . getStackTrace ( ) ) ; } } } } private void logTrace ( StackTraceElement [ ] stackTrace ) { StringBuilder sb = new StringBuilder ( ) ; for ( StackTraceElement e : stackTrace ) { sb . append ( e . getClassName ( ) + e . getMethodName ( ) + "" + e . getLineNumber ( ) + "" ) ; } logger . info ( sb . toString ( ) ) ; } } package br . com . caelum . vraptor . dash . monitor ; public interface MonitorAwareUser { boolean canSeeMonitorStats ( ) ; } package br . com . caelum . vraptor . dash . runtime ; import java . text . NumberFormat ; import br . com . caelum . vraptor . Result ; import br . com . caelum . vraptor . dash . statistics . Collector ; public class RuntimeStatisticsCollector implements Collector { private Runtime runtime ; public RuntimeStatisticsCollector ( Runtime runtime ) { this . runtime = runtime ; } public void collect ( Result result ) { NumberFormat decimalFormat = NumberFormat . getNumberInstance ( ) ; NumberFormat percentFormat = NumberFormat . getPercentInstance ( ) ; result . include ( "" , decimalFormat . format ( runtime . totalMemory ( ) ) ) ; result . include ( "" , decimalFormat . format ( usedMemory ( ) ) ) ; result . include ( "" , percentFormat . format ( usedMemory ( ) / runtime . totalMemory ( ) ) ) ; result . include ( "" , decimalFormat . format ( runtime . freeMemory ( ) ) ) ; result . include ( "" , percentFormat . format ( ( double ) runtime . freeMemory ( ) / runtime . totalMemory ( ) ) ) ; } private double usedMemory ( ) { return runtime . totalMemory ( ) - runtime . freeMemory ( ) ; } } package br . com . caelum . vraptor . dash . statistics ; import br . com . caelum . vraptor . Result ; public interface Collector { void collect ( Result result ) ; } package br . com . caelum . vraptor . dash . statistics ; import java . util . List ; import br . com . caelum . vraptor . Result ; public class Collectors implements Collector { private List < Collector > collectors ; public Collectors ( List < Collector > collectors ) { this . collectors = collectors ; } @ Override public void collect ( Result result ) { for ( Collector collector : collectors ) { collector . collect ( result ) ; } } } package info . naturwerk . app ; public final class R { public static final class attr { } public static final class drawable { public static final int background = ; public static final int ic_launcher = ; public static final int naturweklogo = ; } public static final class id { public static final int buttonCreateObservation = ; public static final int buttonGetFoto = ; public static final int detailTextFamily = ; public static final int detailTextName = ; public static final int detailTextNameDe = ; public static final int detailTextOpt1 = ; public static final int detailTextOpt2 = ; public static final int imageViewFoto = ; public static final int itemPrefs = ; public static final int itemToggleService = ; public static final int listCategory = ; public static final int listFauna = ; public static final int textCategoryCount = ; public static final int textCategoryName = ; public static final int textFaunaLatinName = ; public static final int textFaunaName = ; } public static final class layout { public static final int category = ; public static final int category_row = ; public static final int detail = ; public static final int fauna = ; public static final int fauna_row = ; } public static final class menu { public static final int menu = ; } public static final class string { public static final int app_name = ; public static final int hello = ; public static final int summaryApiRoot = ; public static final int summaryPassword = ; public static final int summaryUsername = ; public static final int titleApiRoot = ; public static final int titleDetail = ; public static final int titlePassword = ; public static final int titlePrefs = ; public static final int titleServiceStart = ; public static final int titleUsername = ; } public static final class xml { public static final int prefs = ; } } package info . naturwerk . app ; import android . os . Bundle ; import android . preference . PreferenceActivity ; public class NWPrefsActivity extends PreferenceActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; addPreferencesFromResource ( R . xml . prefs ) ; } } package info . naturwerk . app ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLConnection ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import android . app . Application ; import android . content . ContentValues ; import android . content . SharedPreferences ; import android . content . SharedPreferences . OnSharedPreferenceChangeListener ; import android . preference . PreferenceManager ; import android . util . Log ; public class NWApplication extends Application implements OnSharedPreferenceChangeListener { private static final String TAG = NWApplication . class . getSimpleName ( ) ; private SharedPreferences prefs ; private boolean serviceRunning ; private NWDataBase nwDataBase ; private NWObservation observation ; private int category ; public NWObservation getObservation ( ) { return observation ; } public int getCategory ( ) { return category ; } public void setCategory ( int category ) { this . category = category ; } @ Override public void onCreate ( ) { super . onCreate ( ) ; this . prefs = PreferenceManager . getDefaultSharedPreferences ( this ) ; this . prefs . registerOnSharedPreferenceChangeListener ( this ) ; this . nwDataBase = new NWDataBase ( this ) ; Log . i ( TAG , "" ) ; } @ Override public void onTerminate ( ) { super . onTerminate ( ) ; Log . i ( TAG , "" ) ; } public void onSharedPreferenceChanged ( SharedPreferences sharedPreferences , String key ) { ; } public boolean isServiceRunning ( ) { return serviceRunning ; } public void setServiceRunning ( boolean serviceRunning ) { this . serviceRunning = serviceRunning ; } public SharedPreferences getPrefs ( ) { return prefs ; } public NWDataBase getNWDataBase ( ) { return nwDataBase ; } public boolean setObservation ( int id ) { observation = new NWObservation ( ) ; return this . getNWDataBase ( ) . createObservation ( observation , id ) ; } public synchronized void fetchServerData ( ) { try { URL nwURL = new URL ( getPrefs ( ) . getString ( "" , "" ) ) ; JSONArray jArr = new JSONArray ( getJSON ( nwURL ) ) ; ContentValues values = new ContentValues ( ) ; for ( int i = ; i < jArr . length ( ) ; i ++ ) { JSONObject item = jArr . getJSONObject ( i ) ; Log . d ( TAG , "" + item . getString ( "" ) ) ; values . put ( NWDataBase . C_NAME , item . getString ( "" ) ) ; Log . d ( TAG , "" + item . getString ( "" ) ) ; values . put ( NWDataBase . C_COUNT , item . getString ( "" ) ) ; Log . d ( TAG , "" + item . getString ( "" ) ) ; values . put ( NWDataBase . C_INVENTORY_TYPE_ID , item . getString ( "" ) ) ; this . getNWDataBase ( ) . insertCategoryOrIgnore ( values ) ; int category_id = Integer . parseInt ( item . getString ( "" ) ) ; URL catURL = new URL ( nwURL . toString ( ) + "" + category_id ) ; Log . d ( TAG , "" + catURL . toString ( ) ) ; if ( category_id == ) continue ; JSONArray jCatArr = new JSONArray ( getJSON ( catURL ) ) ; for ( int j = ; j < jCatArr . length ( ) ; j ++ ) { JSONObject catItem = jCatArr . getJSONObject ( j ) ; if ( category_id != ) { ContentValues faunaCon = new ContentValues ( ) ; Log . v ( TAG , "" + catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_INVENTORY_TYPE_ID , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_NAME , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_FAMILY , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_PROTECTION , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_CSCF_NR , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_NAME_DE , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_GENUS , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_SPECIES , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FAUNA_CLASS_ID , catItem . getString ( "" ) ) ; this . getNWDataBase ( ) . insertFaunaOrIgnore ( faunaCon ) ; faunaCon . clear ( ) ; } else { ContentValues faunaCon = new ContentValues ( ) ; faunaCon . put ( NWDataBase . FLORA_INVENTORY_TYPE_ID , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FLORA_NAME , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FLORA_FAMILY , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FLORA_GATTUNG , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FLORA_ART , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FLORA_NAME_DE , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FLORA_IS_NEOPHYTE , catItem . getString ( "" ) ) ; faunaCon . put ( NWDataBase . FLORA_STATUS , catItem . getString ( "" ) ) ; this . getNWDataBase ( ) . insertFloraOrIgnore ( faunaCon ) ; faunaCon . clear ( ) ; } } } } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } } private String getJSON ( URL nwURL ) throws IOException { URLConnection nwConn = nwURL . openConnection ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( nwConn . getInputStream ( ) ) ) ; StringBuilder sb = new StringBuilder ( ) ; String line = null ; while ( ( line = in . readLine ( ) ) != null ) { sb . append ( line + "" ) ; } in . close ( ) ; return sb . toString ( ) ; } } package info . naturwerk . app ; import android . database . Cursor ; public class NWObservation { public int id ; public boolean isFauna ; public String faunaFamily ; public String faunaName ; public int faunaProtectionCh ; public int faunaCscfNr ; public String faunaNameDe ; public String faunaGenus ; public String faunaSpecies ; public int faunaClassId ; public String floraName ; public String floraFamilie ; public String floraGattung ; public String floraArt ; public String floraNameDe ; public String floraIsNeophyte ; public String floraStatus ; } package info . naturwerk . app ; import android . content . Intent ; import android . graphics . Bitmap ; import android . os . Bundle ; import android . view . View ; import android . view . View . OnClickListener ; import android . widget . Button ; import android . widget . ImageView ; import android . widget . TextView ; public class NWDetailActivity extends NWBaseActivity implements OnClickListener { private static final String TAG = NWDetailActivity . class . getSimpleName ( ) ; private static final int CAMERA_PIC_REQUEST = ; private NWObservation obs ; private Button buttonGetPicture , buttonCreateObservation ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . detail ) ; obs = ( ( NWApplication ) super . getApplication ( ) ) . getObservation ( ) ; ( ( TextView ) findViewById ( R . id . detailTextFamily ) ) . setText ( obs . faunaFamily ) ; ( ( TextView ) findViewById ( R . id . detailTextNameDe ) ) . setText ( obs . faunaNameDe ) ; ( ( TextView ) findViewById ( R . id . detailTextName ) ) . setText ( obs . faunaFamily ) ; buttonCreateObservation = ( Button ) findViewById ( R . id . buttonCreateObservation ) ; buttonCreateObservation . setOnClickListener ( this ) ; buttonGetPicture = ( Button ) findViewById ( R . id . buttonGetFoto ) ; buttonGetPicture . setOnClickListener ( this ) ; } public void onClick ( View v ) { switch ( v . getId ( ) ) { case R . id . buttonGetFoto : { Intent cameraIntent = new Intent ( android . provider . MediaStore . ACTION_IMAGE_CAPTURE ) ; startActivityForResult ( cameraIntent , CAMERA_PIC_REQUEST ) ; break ; } } } protected void onActivityResult ( int requestCode , int resultCode , Intent data ) { if ( requestCode == CAMERA_PIC_REQUEST ) { Bitmap thumbnail = ( Bitmap ) data . getExtras ( ) . get ( "" ) ; ImageView image = ( ImageView ) findViewById ( R . id . imageViewFoto ) ; image . setImageBitmap ( thumbnail ) ; } } } package info . naturwerk . app ; import android . app . Activity ; import android . content . Intent ; import android . os . Bundle ; import android . view . Menu ; import android . view . MenuItem ; public class NWBaseActivity extends Activity { NWApplication nwApplication ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; nwApplication = ( NWApplication ) getApplication ( ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { getMenuInflater ( ) . inflate ( R . menu . menu , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { switch ( item . getItemId ( ) ) { case R . id . itemPrefs : startActivity ( new Intent ( this , NWPrefsActivity . class ) . addFlags ( Intent . FLAG_ACTIVITY_REORDER_TO_FRONT ) ) ; break ; case R . id . itemToggleService : if ( nwApplication . isServiceRunning ( ) ) { stopService ( new Intent ( this , NWUpdateService . class ) ) ; } else { startService ( new Intent ( this , NWUpdateService . class ) ) ; } } return true ; } } package info . naturwerk . app ; import android . content . Intent ; import android . database . Cursor ; import android . os . Bundle ; import android . util . Log ; import android . view . View ; import android . widget . AdapterView ; import android . widget . AdapterView . OnItemClickListener ; import android . widget . ListView ; import android . widget . SimpleCursorAdapter ; public class NWFaunaActivity extends NWBaseActivity { private static final String TAG = NWFaunaActivity . class . getSimpleName ( ) ; Cursor cursor ; ListView listCategory ; SimpleCursorAdapter adapter ; static final String [ ] FROM_FAUNA = { NWDataBase . FAUNA_NAME_DE , NWDataBase . FAUNA_SPECIES } ; static final String [ ] FROM_FLORA = { NWDataBase . FLORA_NAME_DE , NWDataBase . FLORA_NAME } ; static final int [ ] TO = { R . id . textFaunaName , R . id . textFaunaLatinName } ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . fauna ) ; listCategory = ( ListView ) findViewById ( R . id . listFauna ) ; listCategory . setOnItemClickListener ( new CategoryOnItemClickedListener ( ) ) ; Log . i ( TAG , "" ) ; } @ Override protected void onResume ( ) { super . onResume ( ) ; this . setupList ( ) ; } private void setupList ( ) { int category = ( ( NWApplication ) getApplicationContext ( ) ) . getCategory ( ) ; if ( category != ) { cursor = nwApplication . getNWDataBase ( ) . getFauna ( category ) ; startManagingCursor ( cursor ) ; adapter = new SimpleCursorAdapter ( this , R . layout . fauna_row , cursor , FROM_FAUNA , TO ) ; } else { cursor = nwApplication . getNWDataBase ( ) . getFloras ( ) ; startManagingCursor ( cursor ) ; adapter = new SimpleCursorAdapter ( this , R . layout . fauna_row , cursor , FROM_FLORA , TO ) ; } listCategory . setAdapter ( adapter ) ; } public class CategoryOnItemClickedListener implements OnItemClickListener { @ Override public void onItemClick ( AdapterView < ? > arg0 , View view , int pos , long id ) { ( ( NWApplication ) getApplicationContext ( ) ) . setObservation ( ( int ) id ) ; Intent intent = new Intent ( NWFaunaActivity . this , NWDetailActivity . class ) ; startActivity ( intent ) ; } } } package info . naturwerk . app ; import android . content . ContentValues ; import android . content . Context ; import android . database . Cursor ; import android . database . sqlite . SQLiteDatabase ; import android . database . sqlite . SQLiteOpenHelper ; import android . util . Log ; public class NWDataBase { private static final String TAG = NWDataBase . class . getSimpleName ( ) ; static final int VERSION = ; static final String DATABASE = "" ; static final String CATEGORY_TABLE = "" ; static final String FLORA_TABLE = "" ; static final String FAUNA_TABLE = "" ; public static final String C_COUNT = "" ; public static final String C_INVENTORY_TYPE_ID = "" ; public static final String C_NAME = "" ; public static final String FLORA_INVENTORY_TYPE_ID = "" ; public static final String FLORA_FAMILY = "" ; public static final String FLORA_NAME = "" ; public static final String FLORA_GATTUNG = "" ; public static final String FLORA_ART = "" ; public static final String FLORA_NAME_DE = "" ; public static final String FLORA_IS_NEOPHYTE = "" ; public static final String FLORA_STATUS = "" ; public static final String FAUNA_INVENTORY_TYPE_ID = "" ; public static final String FAUNA_FAMILY = "" ; public static final String FAUNA_NAME = "" ; public static final String FAUNA_PROTECTION = "" ; public static final String FAUNA_CSCF_NR = "" ; public static final String FAUNA_NAME_DE = "" ; public static final String FAUNA_GENUS = "" ; public static final String FAUNA_SPECIES = "" ; public static final String FAUNA_CLASS_ID = "" ; private static final String GET_ALL_CATEGORIES_ORDER_BY = C_NAME + "" ; private static final String GET_ALL_FLORAS_ORDER_BY = FLORA_NAME_DE + "" ; private static final String GET_ALL_FAUNAS_ORDER_BY = FAUNA_NAME_DE + "" ; class DbHelper extends SQLiteOpenHelper { public DbHelper ( Context context ) { super ( context , DATABASE , null , VERSION ) ; } @ Override public void onCreate ( SQLiteDatabase db ) { Log . i ( TAG , "" + DATABASE ) ; Log . i ( TAG , "" + CATEGORY_TABLE ) ; db . execSQL ( "" + CATEGORY_TABLE + "" + C_INVENTORY_TYPE_ID + "" + C_COUNT + "" + C_NAME + "" ) ; Log . i ( TAG , "" + FLORA_TABLE ) ; db . execSQL ( "" + FLORA_TABLE + "" + FLORA_INVENTORY_TYPE_ID + "" + FLORA_FAMILY + "" + FLORA_NAME + "" + FLORA_GATTUNG + "" + FLORA_ART + "" + FLORA_NAME_DE + "" + FLORA_IS_NEOPHYTE + "" + FLORA_STATUS + "" ) ; Log . i ( TAG , "" + FAUNA_TABLE ) ; db . execSQL ( "" + FAUNA_TABLE + "" + FAUNA_INVENTORY_TYPE_ID + "" + FAUNA_FAMILY + "" + FAUNA_NAME + "" + FAUNA_PROTECTION + "" + FAUNA_CSCF_NR + "" + FAUNA_NAME_DE + "" + FAUNA_GENUS + "" + FAUNA_SPECIES + "" + FAUNA_CLASS_ID + "" ) ; } @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { Log . i ( TAG , "" + DATABASE ) ; db . execSQL ( "" + CATEGORY_TABLE ) ; db . execSQL ( "" + FLORA_TABLE ) ; db . execSQL ( "" + FAUNA_TABLE ) ; this . onCreate ( db ) ; } } final DbHelper dbHelper ; public NWDataBase ( Context context ) { this . dbHelper = new DbHelper ( context ) ; Log . i ( TAG , "" ) ; } public void close ( ) { this . dbHelper . close ( ) ; } public void insertCategoryOrIgnore ( ContentValues values ) { Log . d ( TAG , "" + values ) ; SQLiteDatabase db = this . dbHelper . getWritableDatabase ( ) ; try { db . insertWithOnConflict ( CATEGORY_TABLE , null , values , SQLiteDatabase . CONFLICT_IGNORE ) ; } finally { db . close ( ) ; } } public void insertFloraOrIgnore ( ContentValues values ) { Log . d ( TAG , "" + values ) ; SQLiteDatabase db = this . dbHelper . getWritableDatabase ( ) ; try { db . insertWithOnConflict ( FLORA_TABLE , null , values , SQLiteDatabase . CONFLICT_IGNORE ) ; } finally { db . close ( ) ; } } public void insertFaunaOrIgnore ( ContentValues values ) { Log . d ( TAG , "" + values ) ; SQLiteDatabase db = this . dbHelper . getWritableDatabase ( ) ; try { db . insertWithOnConflict ( FAUNA_TABLE , null , values , SQLiteDatabase . CONFLICT_IGNORE ) ; } finally { db . close ( ) ; } } public Cursor getCategories ( ) { SQLiteDatabase db = this . dbHelper . getReadableDatabase ( ) ; return db . query ( CATEGORY_TABLE , null , null , null , null , null , GET_ALL_CATEGORIES_ORDER_BY ) ; } public Cursor getFloras ( ) { SQLiteDatabase db = this . dbHelper . getReadableDatabase ( ) ; return db . query ( FLORA_TABLE , null , null , null , null , null , GET_ALL_FLORAS_ORDER_BY ) ; } public Cursor getFlora ( int category ) { SQLiteDatabase db = this . dbHelper . getReadableDatabase ( ) ; return db . query ( FLORA_TABLE , null , null , null , null , null , GET_ALL_FLORAS_ORDER_BY ) ; } public Cursor getFaunas ( ) { SQLiteDatabase db = this . dbHelper . getReadableDatabase ( ) ; return db . query ( FAUNA_TABLE , null , null , null , null , null , GET_ALL_FAUNAS_ORDER_BY ) ; } public Cursor getFauna ( int category ) { SQLiteDatabase db = this . dbHelper . getReadableDatabase ( ) ; return db . query ( FAUNA_TABLE , null , FAUNA_CLASS_ID + "" + Integer . toString ( category ) , null , null , null , GET_ALL_FAUNAS_ORDER_BY ) ; } public Cursor getFaunaItem ( int item ) { SQLiteDatabase db = this . dbHelper . getReadableDatabase ( ) ; return db . query ( FAUNA_TABLE , null , FAUNA_INVENTORY_TYPE_ID + "" + Integer . toString ( item ) , null , null , null , null ) ; } public Cursor getFloraItem ( int item ) { SQLiteDatabase db = this . dbHelper . getReadableDatabase ( ) ; return db . query ( FLORA_TABLE , null , FLORA_INVENTORY_TYPE_ID + "" + Integer . toString ( item ) , null , null , null , null ) ; } public boolean createObservation ( NWObservation obs , int obsId ) { obs . id = obsId ; if ( obs . id == ) { Cursor c = getFauna ( obs . id ) ; if ( ! c . moveToFirst ( ) ) return false ; obs . floraArt = c . getString ( c . getColumnIndex ( FLORA_ART ) ) ; obs . floraFamilie = c . getString ( c . getColumnIndex ( FLORA_FAMILY ) ) ; obs . floraGattung = c . getString ( c . getColumnIndex ( FLORA_GATTUNG ) ) ; obs . floraIsNeophyte = c . getString ( c . getColumnIndex ( FLORA_IS_NEOPHYTE ) ) ; obs . floraName = c . getString ( c . getColumnIndex ( FLORA_NAME ) ) ; obs . floraNameDe = c . getString ( c . getColumnIndex ( FLORA_NAME_DE ) ) ; obs . floraStatus = c . getString ( c . getColumnIndex ( FLORA_STATUS ) ) ; } else { Cursor c = getFaunaItem ( obs . id ) ; if ( ! c . moveToFirst ( ) ) return false ; obs . faunaClassId = c . getInt ( c . getColumnIndex ( FAUNA_CLASS_ID ) ) ; obs . faunaCscfNr = c . getInt ( c . getColumnIndex ( FAUNA_CSCF_NR ) ) ; obs . faunaFamily = c . getString ( c . getColumnIndex ( FAUNA_FAMILY ) ) ; obs . faunaGenus = c . getString ( c . getColumnIndex ( FAUNA_GENUS ) ) ; obs . faunaName = c . getString ( c . getColumnIndex ( FAUNA_NAME ) ) ; obs . faunaNameDe = c . getString ( c . getColumnIndex ( FAUNA_NAME_DE ) ) ; obs . faunaProtectionCh = c . getInt ( c . getColumnIndex ( FAUNA_PROTECTION ) ) ; obs . faunaSpecies = c . getString ( c . getColumnIndex ( FAUNA_SPECIES ) ) ; } return true ; } public boolean getFloraItem ( NWObservation obs ) { SQLiteDatabase db = this . dbHelper . getReadableDatabase ( ) ; if ( obs . id == ) { Cursor cur = db . query ( FLORA_TABLE , null , "" + Integer . toString ( obs . id ) , null , null , null , null ) ; if ( ! cur . moveToFirst ( ) ) return false ; } return false ; } public void delete ( ) { SQLiteDatabase db = dbHelper . getWritableDatabase ( ) ; db . delete ( CATEGORY_TABLE , null , null ) ; db . delete ( FLORA_TABLE , null , null ) ; db . delete ( FAUNA_TABLE , null , null ) ; db . close ( ) ; } } package info . naturwerk . app ; import android . app . Service ; import android . content . Intent ; import android . os . IBinder ; import android . util . Log ; public class NWUpdateService extends Service { private static final String TAG = "" ; static final int DELAY = ; private boolean runFlag = false ; private Updater updater ; @ Override public IBinder onBind ( Intent intent ) { return null ; } @ Override public void onCreate ( ) { super . onCreate ( ) ; this . updater = new Updater ( ) ; Log . d ( TAG , "" ) ; } @ Override public int onStartCommand ( Intent intent , int flag , int startId ) { if ( ! runFlag ) { this . runFlag = true ; this . updater . start ( ) ; ( ( NWApplication ) super . getApplication ( ) ) . setServiceRunning ( true ) ; Log . d ( TAG , "" ) ; } return Service . START_STICKY ; } @ Override public void onDestroy ( ) { super . onDestroy ( ) ; this . runFlag = false ; this . updater . interrupt ( ) ; this . updater = null ; ( ( NWApplication ) super . getApplication ( ) ) . setServiceRunning ( false ) ; Log . d ( TAG , "" ) ; } private class Updater extends Thread { public Updater ( ) { super ( "" ) ; } @ Override public void run ( ) { NWUpdateService updaterService = NWUpdateService . this ; Log . d ( TAG , "" ) ; try { NWApplication nwapp = ( NWApplication ) updaterService . getApplication ( ) ; nwapp . fetchServerData ( ) ; Thread . sleep ( DELAY ) ; } catch ( InterruptedException e ) { updaterService . runFlag = false ; } } } } package info . naturwerk . app ; import android . content . Intent ; import android . database . Cursor ; import android . os . Bundle ; import android . util . Log ; import android . view . View ; import android . widget . AdapterView ; import android . widget . AdapterView . OnItemClickListener ; import android . widget . ListView ; import android . widget . SimpleCursorAdapter ; public class NWCategoryActivity extends NWBaseActivity { private static final String TAG = NWCategoryActivity . class . getSimpleName ( ) ; Cursor cursor ; ListView listCategory ; SimpleCursorAdapter adapter ; static final String [ ] FROM = { NWDataBase . C_NAME , NWDataBase . C_COUNT } ; static final int [ ] TO = { R . id . textCategoryName , R . id . textCategoryCount } ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . category ) ; listCategory = ( ListView ) findViewById ( R . id . listCategory ) ; listCategory . setOnItemClickListener ( new CategoryOnItemClickedListener ( ) ) ; Log . i ( TAG , "" ) ; } @ Override protected void onResume ( ) { super . onResume ( ) ; this . setupList ( ) ; } private void setupList ( ) { cursor = nwApplication . getNWDataBase ( ) . getCategories ( ) ; startManagingCursor ( cursor ) ; adapter = new SimpleCursorAdapter ( this , R . layout . category_row , cursor , FROM , TO ) ; listCategory . setAdapter ( adapter ) ; } public class CategoryOnItemClickedListener implements OnItemClickListener { @ Override public void onItemClick ( AdapterView < ? > arg0 , View view , int pos , long id ) { ( ( NWApplication ) getApplicationContext ( ) ) . setCategory ( ( int ) id ) ; Intent intent = new Intent ( NWCategoryActivity . this , NWFaunaActivity . class ) ; startActivity ( intent ) ; } } } package com . asakusafw . dmdl . semantics ; public interface Type extends Element { Type map ( PropertyMappingKind mapping ) ; boolean isSame ( Type other ) ; } package com . asakusafw . dmdl . semantics . type ; package com . asakusafw . dmdl . semantics . type ; import java . text . MessageFormat ; import com . asakusafw . dmdl . model . AstBasicType ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . PropertyMappingKind ; import com . asakusafw . dmdl . semantics . Type ; public class BasicType implements Type { private final AstBasicType originalAst ; private final BasicTypeKind kind ; public BasicType ( AstBasicType originalAst , BasicTypeKind kind ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . kind = kind ; } @ Override public AstBasicType getOriginalAst ( ) { return originalAst ; } public BasicTypeKind getKind ( ) { return kind ; } @ Override public Type map ( PropertyMappingKind mapping ) { if ( mapping == null ) { throw new IllegalArgumentException ( "" ) ; } switch ( mapping ) { case ANY : case MAX : case MIN : return this ; case COUNT : return new BasicType ( originalAst , BasicTypeKind . LONG ) ; case SUM : switch ( kind ) { case BYTE : case SHORT : case INT : case LONG : return new BasicType ( originalAst , BasicTypeKind . LONG ) ; case DECIMAL : return new BasicType ( originalAst , BasicTypeKind . DECIMAL ) ; case FLOAT : case DOUBLE : return new BasicType ( originalAst , BasicTypeKind . DOUBLE ) ; case BOOLEAN : case DATE : case DATETIME : case TEXT : return null ; default : throw new AssertionError ( mapping ) ; } default : throw new AssertionError ( mapping ) ; } } @ Override public boolean isSame ( Type other ) { if ( this == other ) { return true ; } if ( ( other instanceof BasicType ) == false ) { return false ; } return kind == ( ( BasicType ) other ) . kind ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , kind . name ( ) ) ; } } package com . asakusafw . dmdl . semantics ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstDescription ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public class ModelDeclaration implements Declaration { private final DmdlSemantics owner ; private final AstModelDefinition < ? > originalAst ; private final AstSimpleName name ; private final AstDescription description ; private final List < AstAttribute > attributes ; private final List < PropertyDeclaration > declaredProperties ; private final Map < Class < ? extends Trait < ? > > , Trait < ? > > traits ; protected ModelDeclaration ( DmdlSemantics owner , AstModelDefinition < ? > originalAst , AstSimpleName name , AstDescription description , List < ? extends AstAttribute > attributes ) { if ( owner == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } this . owner = owner ; this . originalAst = originalAst ; this . name = name ; this . description = description ; this . attributes = Lists . freeze ( attributes ) ; this . declaredProperties = Lists . create ( ) ; this . traits = Maps . create ( ) ; } public ModelSymbol getSymbol ( ) { return new ModelSymbol ( owner , name ) ; } @ Override public AstModelDefinition < ? > getOriginalAst ( ) { return originalAst ; } @ Override public AstSimpleName getName ( ) { return name ; } @ Override public AstDescription getDescription ( ) { return description ; } @ Override public List < AstAttribute > getAttributes ( ) { return attributes ; } public PropertyDeclaration declareProperty ( AstNode propertyOriginalAst , AstSimpleName propertyName , Type propertyType , AstDescription propertyDescription , List < ? extends AstAttribute > propertyAttributes ) { if ( propertyName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( propertyType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( propertyAttributes == null ) { throw new IllegalArgumentException ( "" ) ; } if ( findPropertyDeclaration ( propertyName . identifier ) != null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , propertyName , getName ( ) ) ) ; } PropertyDeclaration property = new PropertyDeclaration ( getSymbol ( ) , propertyOriginalAst , propertyName , propertyType , propertyDescription , propertyAttributes ) ; declaredProperties . add ( property ) ; return property ; } public PropertyDeclaration findPropertyDeclaration ( String propertyName ) { if ( propertyName == null ) { throw new IllegalArgumentException ( "" ) ; } for ( PropertyDeclaration property : declaredProperties ) { if ( property . getName ( ) . identifier . equals ( propertyName ) ) { return property ; } } return null ; } public List < PropertyDeclaration > getDeclaredProperties ( ) { return declaredProperties ; } public PropertySymbol createPropertySymbol ( AstSimpleName propertyName ) { if ( propertyName == null ) { throw new IllegalArgumentException ( "" ) ; } return new PropertySymbol ( getSymbol ( ) , propertyName ) ; } @ Override public < T extends Trait < T > > T getTrait ( Class < T > kind ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } return kind . cast ( traits . get ( kind ) ) ; } @ Override public < T extends Trait < T > > void putTrait ( Class < T > kind , T trait ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( trait == null ) { traits . remove ( kind ) ; } else { traits . put ( kind , trait ) ; } } @ Override public String toString ( ) { return MessageFormat . format ( "" , originalAst . kind , name ) ; } } package com . asakusafw . dmdl . semantics ; package com . asakusafw . dmdl . semantics ; public enum PropertyMappingKind { ANY , SUM , COUNT , MAX , MIN , } package com . asakusafw . dmdl . semantics . trait ; package com . asakusafw . dmdl . semantics . trait ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstName ; import com . asakusafw . dmdl . semantics . Trait ; public class NamespaceTrait implements Trait < NamespaceTrait > { private AstAttribute originalAst ; private AstName namespace ; public NamespaceTrait ( AstAttribute originalAst , AstName namespace ) { if ( namespace == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . namespace = namespace ; } @ Override public AstAttribute getOriginalAst ( ) { return originalAst ; } public AstName getNamespace ( ) { return namespace ; } } package com . asakusafw . dmdl . semantics . trait ; import java . util . List ; import com . asakusafw . dmdl . model . AstExpression ; import com . asakusafw . dmdl . model . AstSummarize ; import com . asakusafw . dmdl . semantics . Trait ; public class SummarizeTrait implements Trait < SummarizeTrait > { private final AstExpression < AstSummarize > expression ; private final List < ReduceTerm < AstSummarize > > terms ; public SummarizeTrait ( AstExpression < AstSummarize > expression , List < ReduceTerm < AstSummarize > > terms ) { if ( expression == null ) { throw new IllegalArgumentException ( "" ) ; } if ( terms == null ) { throw new IllegalArgumentException ( "" ) ; } this . expression = expression ; this . terms = terms ; } @ Override public AstExpression < AstSummarize > getOriginalAst ( ) { return expression ; } public List < ReduceTerm < AstSummarize > > getTerms ( ) { return terms ; } } package com . asakusafw . dmdl . semantics . trait ; import java . util . List ; import com . asakusafw . dmdl . model . AstExpression ; import com . asakusafw . dmdl . model . AstJoin ; import com . asakusafw . dmdl . semantics . Trait ; public class JoinTrait implements Trait < JoinTrait > { private final AstExpression < AstJoin > expression ; private final List < ReduceTerm < AstJoin > > terms ; public JoinTrait ( AstExpression < AstJoin > expression , List < ReduceTerm < AstJoin > > terms ) { if ( expression == null ) { throw new IllegalArgumentException ( "" ) ; } if ( terms == null ) { throw new IllegalArgumentException ( "" ) ; } this . expression = expression ; this . terms = terms ; } @ Override public AstExpression < AstJoin > getOriginalAst ( ) { return expression ; } public List < ReduceTerm < AstJoin > > getTerms ( ) { return terms ; } } package com . asakusafw . dmdl . semantics . trait ; import java . util . List ; import com . asakusafw . dmdl . model . AstTerm ; import com . asakusafw . dmdl . semantics . Element ; import com . asakusafw . dmdl . semantics . ModelSymbol ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . utils . collections . Lists ; public class ReduceTerm < T extends AstTerm < T > > implements Element { private final T term ; private final ModelSymbol source ; private final List < MappingFactor > mappings ; private final List < PropertySymbol > grouping ; public ReduceTerm ( T term , ModelSymbol source , List < MappingFactor > mappings , List < PropertySymbol > grouping ) { if ( term == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( grouping == null ) { throw new IllegalArgumentException ( "" ) ; } this . term = term ; this . source = source ; this . mappings = Lists . freeze ( mappings ) ; this . grouping = Lists . freeze ( grouping ) ; } @ Override public T getOriginalAst ( ) { return term ; } public ModelSymbol getSource ( ) { return source ; } public List < MappingFactor > getMappings ( ) { return mappings ; } public List < PropertySymbol > getGrouping ( ) { return grouping ; } } package com . asakusafw . dmdl . semantics . trait ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . Element ; import com . asakusafw . dmdl . semantics . PropertyMappingKind ; import com . asakusafw . dmdl . semantics . PropertySymbol ; public class MappingFactor implements Element { private final AstNode mapping ; private final PropertyMappingKind kind ; private final PropertySymbol source ; private final PropertySymbol target ; public MappingFactor ( AstNode originalAst , PropertyMappingKind kind , PropertySymbol source , PropertySymbol target ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } this . mapping = originalAst ; this . kind = kind ; this . source = source ; this . target = target ; } @ Override public AstNode getOriginalAst ( ) { return mapping ; } public PropertyMappingKind getKind ( ) { return kind ; } public PropertySymbol getSource ( ) { return source ; } public PropertySymbol getTarget ( ) { return target ; } } package com . asakusafw . dmdl . semantics . trait ; import java . util . List ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . ModelSymbol ; import com . asakusafw . dmdl . semantics . Trait ; public class ProjectionsTrait implements Trait < ProjectionsTrait > { private final AstNode originalAst ; private final List < ModelSymbol > projectives ; public ProjectionsTrait ( AstNode originalAst , List < ModelSymbol > projectives ) { if ( projectives == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . projectives = projectives ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public List < ModelSymbol > getProjections ( ) { return projectives ; } } package com . asakusafw . dmdl . semantics ; public interface Trait < T extends Trait < T > > extends Element { } package com . asakusafw . dmdl . semantics ; import java . text . MessageFormat ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . model . AstSimpleName ; public class ModelSymbol implements Symbol < ModelDeclaration > { private final DmdlSemantics owner ; private final AstSimpleName name ; protected ModelSymbol ( DmdlSemantics owner , AstSimpleName name ) { if ( owner == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . owner = owner ; this . name = name ; } @ Override public AstNode getOriginalAst ( ) { return name ; } @ Override public AstSimpleName getName ( ) { return name ; } public PropertySymbol createPropertySymbol ( AstSimpleName propertyName ) { if ( propertyName == null ) { throw new IllegalArgumentException ( "" ) ; } return new PropertySymbol ( this , propertyName ) ; } @ Override public ModelDeclaration findDeclaration ( ) { return owner . findModelDeclaration ( getName ( ) . identifier ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + name . hashCode ( ) ; result = prime * result + owner . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ModelSymbol other = ( ModelSymbol ) obj ; if ( ! name . equals ( other . name ) ) { return false ; } if ( ! owner . equals ( other . owner ) ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , name ) ; } } package com . asakusafw . dmdl . semantics ; import java . util . List ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstDescription ; import com . asakusafw . dmdl . model . AstSimpleName ; public interface Declaration extends Element { AstSimpleName getName ( ) ; AstDescription getDescription ( ) ; List < AstAttribute > getAttributes ( ) ; < T extends Trait < T > > T getTrait ( Class < T > kind ) ; < T extends Trait < T > > void putTrait ( Class < T > kind , T trait ) ; } package com . asakusafw . dmdl . semantics ; import com . asakusafw . dmdl . model . AstNode ; public interface Element { AstNode getOriginalAst ( ) ; } package com . asakusafw . dmdl . semantics ; import java . text . MessageFormat ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . model . AstSimpleName ; public class PropertySymbol implements Symbol < PropertyDeclaration > { private final ModelSymbol owner ; private final AstSimpleName name ; protected PropertySymbol ( ModelSymbol owner , AstSimpleName name ) { if ( owner == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . owner = owner ; this . name = name ; } @ Override public AstNode getOriginalAst ( ) { return name ; } public ModelSymbol getOwner ( ) { return owner ; } @ Override public AstSimpleName getName ( ) { return name ; } @ Override public PropertyDeclaration findDeclaration ( ) { ModelDeclaration ownerDecl = getOwner ( ) . findDeclaration ( ) ; if ( ownerDecl == null ) { return null ; } return ownerDecl . findPropertyDeclaration ( name . identifier ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + name . hashCode ( ) ; result = prime * result + owner . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } PropertySymbol other = ( PropertySymbol ) obj ; if ( ! name . equals ( other . name ) ) { return false ; } if ( ! owner . equals ( other . owner ) ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , owner , name ) ; } } package com . asakusafw . dmdl . semantics ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstDescription ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public class PropertyDeclaration implements Declaration { private final AstNode originalAst ; private final ModelSymbol owner ; private final AstSimpleName name ; private final Type type ; private final AstDescription description ; private final List < AstAttribute > attributes ; private final Map < Class < ? extends Trait < ? > > , Trait < ? > > traits ; protected PropertyDeclaration ( ModelSymbol owner , AstNode originalAst , AstSimpleName name , Type type , AstDescription description , List < ? extends AstAttribute > attributes ) { if ( owner == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . owner = owner ; this . name = name ; this . type = type ; this . description = description ; this . attributes = Lists . freeze ( attributes ) ; this . traits = Maps . create ( ) ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } @ Override public AstSimpleName getName ( ) { return name ; } public Type getType ( ) { return type ; } @ Override public AstDescription getDescription ( ) { return description ; } @ Override public List < AstAttribute > getAttributes ( ) { return attributes ; } public ModelSymbol getOwner ( ) { return owner ; } public PropertySymbol getSymbol ( ) { return new PropertySymbol ( owner , name ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , owner , name , type ) ; } @ Override public < T extends Trait < T > > T getTrait ( Class < T > kind ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } return kind . cast ( traits . get ( kind ) ) ; } @ Override public < T extends Trait < T > > void putTrait ( Class < T > kind , T trait ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( trait == null ) { traits . remove ( kind ) ; } else { traits . put ( kind , trait ) ; } } } package com . asakusafw . dmdl . semantics ; import com . asakusafw . dmdl . model . AstSimpleName ; public interface Symbol < D extends Declaration > extends Element { AstSimpleName getName ( ) ; D findDeclaration ( ) ; } package com . asakusafw . dmdl . semantics ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstDescription ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public class DmdlSemantics { private final Map < String , ModelDeclaration > declaredModels = Maps . create ( ) ; private final List < Diagnostic > diagnostics = Lists . create ( ) ; private boolean sawError = false ; public ModelDeclaration declareModel ( AstModelDefinition < ? > modelOriginalAst , AstSimpleName modelName , AstDescription modelDescription , List < ? extends AstAttribute > modelAttributes ) { if ( modelName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( modelAttributes == null ) { throw new IllegalArgumentException ( "" ) ; } if ( declaredModels . containsKey ( modelName . identifier ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , modelName ) ) ; } ModelDeclaration declared = new ModelDeclaration ( this , modelOriginalAst , modelName , modelDescription , modelAttributes ) ; declaredModels . put ( modelName . identifier , declared ) ; return declared ; } public ModelSymbol createModelSymbol ( AstSimpleName modelName ) { if ( modelName == null ) { throw new IllegalArgumentException ( "" ) ; } return new ModelSymbol ( this , modelName ) ; } public ModelDeclaration findModelDeclaration ( String modelName ) { if ( modelName == null ) { throw new IllegalArgumentException ( "" ) ; } return declaredModels . get ( modelName ) ; } public Collection < ModelDeclaration > getDeclaredModels ( ) { return Collections . unmodifiableCollection ( declaredModels . values ( ) ) ; } public void reportAll ( Iterable < ? extends Diagnostic > diagnosticList ) { if ( diagnosticList == null ) { throw new IllegalArgumentException ( "" ) ; } for ( Diagnostic diagnostic : diagnosticList ) { report ( diagnostic ) ; } } public void report ( Diagnostic diagnostic ) { if ( diagnostic == null ) { throw new IllegalArgumentException ( "" ) ; } sawError |= ( diagnostic . level == Level . ERROR ) ; diagnostics . add ( diagnostic ) ; } public boolean hasError ( ) { return sawError ; } public List < Diagnostic > getDiagnostics ( ) { return Collections . unmodifiableList ( diagnostics ) ; } } package com . asakusafw . dmdl . source ; import java . io . IOException ; import java . io . Reader ; import java . net . URI ; import java . util . Iterator ; import java . util . List ; import java . util . NoSuchElementException ; import com . asakusafw . utils . collections . Lists ; public class CompositeSourceRepository implements DmdlSourceRepository { private final List < DmdlSourceRepository > repositories ; public CompositeSourceRepository ( List < ? extends DmdlSourceRepository > repositories ) { if ( repositories == null ) { throw new IllegalArgumentException ( "" ) ; } this . repositories = Lists . freeze ( repositories ) ; } @ Override public Cursor createCursor ( ) throws IOException { return new CompositeCursor ( repositories . iterator ( ) ) ; } private static class CompositeCursor implements Cursor { private final Iterator < DmdlSourceRepository > rest ; private Cursor current ; CompositeCursor ( Iterator < DmdlSourceRepository > iterator ) { assert iterator != null ; this . rest = iterator ; this . current = null ; } @ Override public boolean next ( ) throws IOException { if ( current == null ) { if ( rest . hasNext ( ) ) { current = rest . next ( ) . createCursor ( ) ; } else { return false ; } } assert current != null ; while ( true ) { if ( current . next ( ) ) { return true ; } if ( rest . hasNext ( ) ) { current = rest . next ( ) . createCursor ( ) ; } else { current = null ; return false ; } } } @ Override public URI getIdentifier ( ) throws IOException { if ( current == null ) { throw new NoSuchElementException ( ) ; } return current . getIdentifier ( ) ; } @ Override public Reader openResource ( ) throws IOException { if ( current == null ) { throw new NoSuchElementException ( ) ; } return current . openResource ( ) ; } @ Override public void close ( ) throws IOException { if ( current == null ) { return ; } current . close ( ) ; current = null ; while ( rest . hasNext ( ) ) { rest . next ( ) ; } } } } package com . asakusafw . dmdl . source ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . net . URI ; import java . nio . charset . Charset ; import java . util . Iterator ; import java . util . List ; import java . util . NoSuchElementException ; import com . asakusafw . utils . collections . Lists ; public class DmdlSourceFile implements DmdlSourceRepository { private final List < File > files ; private final Charset encoding ; public DmdlSourceFile ( List < File > sourceFiles , Charset encoding ) { if ( sourceFiles == null ) { throw new IllegalArgumentException ( "" ) ; } if ( encoding == null ) { throw new IllegalArgumentException ( "" ) ; } this . files = Lists . freeze ( sourceFiles ) ; this . encoding = encoding ; } @ Override public Cursor createCursor ( ) throws IOException { return new FileListCursor ( files . iterator ( ) , encoding ) ; } static class FileListCursor implements Cursor { private final Iterator < File > rest ; private final Charset encoding ; private File current ; FileListCursor ( Iterator < File > iterator , Charset encoding ) { assert iterator != null ; assert encoding != null ; this . current = null ; this . rest = iterator ; this . encoding = encoding ; } @ Override public boolean next ( ) throws IOException { if ( rest . hasNext ( ) ) { current = rest . next ( ) ; return true ; } else { current = null ; return false ; } } @ Override public URI getIdentifier ( ) { if ( current == null ) { throw new NoSuchElementException ( ) ; } return current . toURI ( ) ; } @ Override public Reader openResource ( ) throws IOException { if ( current == null ) { throw new NoSuchElementException ( ) ; } InputStream in = new FileInputStream ( current ) ; return new InputStreamReader ( in , encoding ) ; } @ Override public void close ( ) { current = null ; while ( rest . hasNext ( ) ) { rest . next ( ) ; rest . remove ( ) ; } } } } package com . asakusafw . dmdl . source ; import java . io . File ; import java . io . IOException ; import java . nio . charset . Charset ; import java . util . ArrayList ; import java . util . List ; import java . util . regex . Pattern ; public class DmdlSourceDirectory implements DmdlSourceRepository { private File directory ; private Charset encoding ; private Pattern inclusionPattern ; private Pattern exclusionPattern ; public DmdlSourceDirectory ( File directory , Charset encoding , Pattern inclusionPattern , Pattern exclusionPattern ) { if ( directory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( encoding == null ) { throw new IllegalArgumentException ( "" ) ; } if ( inclusionPattern == null ) { throw new IllegalArgumentException ( "" ) ; } if ( exclusionPattern == null ) { throw new IllegalArgumentException ( "" ) ; } this . directory = directory ; this . encoding = encoding ; this . inclusionPattern = inclusionPattern ; this . exclusionPattern = exclusionPattern ; } @ Override public Cursor createCursor ( ) throws IOException { List < File > files = collect ( directory , new ArrayList < File > ( ) ) ; return new DmdlSourceFile . FileListCursor ( files . iterator ( ) , encoding ) ; } private List < File > collect ( File current , List < File > files ) { assert current != null ; if ( current . isFile ( ) ) { if ( accept ( current ) ) { files . add ( current ) ; } } else { for ( File child : current . listFiles ( ) ) { collect ( child , files ) ; } } return files ; } boolean accept ( File file ) { assert file != null ; String name = file . getName ( ) ; if ( inclusionPattern . matcher ( name ) . matches ( ) == false ) { return false ; } if ( exclusionPattern . matcher ( name ) . matches ( ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . source ; package com . asakusafw . dmdl . source ; import java . io . Closeable ; import java . io . IOException ; import java . io . Reader ; import java . net . URI ; import java . util . NoSuchElementException ; public interface DmdlSourceRepository { Cursor createCursor ( ) throws IOException ; public interface Cursor extends Closeable { boolean next ( ) throws IOException ; URI getIdentifier ( ) throws IOException ; Reader openResource ( ) throws IOException ; } } package com . asakusafw . dmdl . source ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . nio . charset . Charset ; import java . util . Iterator ; import java . util . List ; import java . util . NoSuchElementException ; import com . asakusafw . utils . collections . Lists ; public class DmdlSourceResource implements DmdlSourceRepository { private final List < URL > resources ; private final Charset encoding ; public DmdlSourceResource ( List < URL > sourceFiles , Charset encoding ) { if ( sourceFiles == null ) { throw new IllegalArgumentException ( "" ) ; } if ( encoding == null ) { throw new IllegalArgumentException ( "" ) ; } this . resources = Lists . freeze ( sourceFiles ) ; this . encoding = encoding ; } @ Override public Cursor createCursor ( ) throws IOException { return new UrlListCursor ( resources . iterator ( ) , encoding ) ; } static class UrlListCursor implements Cursor { private final Iterator < URL > rest ; private final Charset encoding ; private URL current ; UrlListCursor ( Iterator < URL > iterator , Charset encoding ) { assert iterator != null ; assert encoding != null ; this . current = null ; this . rest = iterator ; this . encoding = encoding ; } @ Override public boolean next ( ) throws IOException { if ( rest . hasNext ( ) ) { current = rest . next ( ) ; return true ; } else { current = null ; return false ; } } @ Override public URI getIdentifier ( ) throws IOException { if ( current == null ) { throw new NoSuchElementException ( ) ; } try { return current . toURI ( ) ; } catch ( URISyntaxException e ) { throw new IOException ( e ) ; } } @ Override public Reader openResource ( ) throws IOException { if ( current == null ) { throw new NoSuchElementException ( ) ; } InputStream in = current . openStream ( ) ; return new InputStreamReader ( in , encoding ) ; } @ Override public void close ( ) { current = null ; while ( rest . hasNext ( ) ) { rest . next ( ) ; rest . remove ( ) ; } } } } package com . asakusafw . dmdl . analyzer ; package com . asakusafw . dmdl . analyzer ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . utils . collections . Lists ; public class DmdlSemanticException extends Exception { private static final long serialVersionUID = ; private final List < Diagnostic > diagnostics ; public DmdlSemanticException ( String message , List < Diagnostic > diagnostics ) { super ( message ) ; if ( diagnostics == null ) { throw new IllegalArgumentException ( "" ) ; } this . diagnostics = Lists . from ( diagnostics ) ; } public List < Diagnostic > getDiagnostics ( ) { return Collections . unmodifiableList ( diagnostics ) ; } } package com . asakusafw . dmdl . analyzer ; import java . util . List ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstType ; import com . asakusafw . dmdl . semantics . Declaration ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . spi . AttributeDriver ; import com . asakusafw . dmdl . spi . TypeDriver ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public class Context { static final Logger LOG = LoggerFactory . getLogger ( Context . class ) ; private final DmdlSemantics world ; private final List < TypeDriver > typeDrivers ; private final Map < String , AttributeDriver > attributeDrivers ; public Context ( DmdlSemantics world , Iterable < ? extends TypeDriver > typeDrivers , Iterable < ? extends AttributeDriver > attributeDrivers ) { if ( world == null ) { throw new IllegalArgumentException ( "" ) ; } if ( typeDrivers == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributeDrivers == null ) { throw new IllegalArgumentException ( "" ) ; } this . world = world ; this . typeDrivers = buildTypeDrivers ( typeDrivers ) ; this . attributeDrivers = buildAttributeDriverMap ( attributeDrivers ) ; } public DmdlSemantics getWorld ( ) { return world ; } public Type resolveType ( AstType type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } for ( TypeDriver driver : typeDrivers ) { Type resolved = driver . resolve ( world , type ) ; if ( resolved != null ) { return resolved ; } } return null ; } public AttributeDriver findAttributeDriver ( AstAttribute attribute ) { if ( attribute == null ) { throw new IllegalArgumentException ( "" ) ; } String name = attribute . name . toString ( ) ; return attributeDrivers . get ( name ) ; } private List < TypeDriver > buildTypeDrivers ( Iterable < ? extends TypeDriver > drivers ) { assert drivers != null ; List < TypeDriver > results = Lists . create ( ) ; for ( TypeDriver driver : drivers ) { LOG . debug ( "" , driver . getClass ( ) . getName ( ) ) ; results . add ( driver ) ; } return results ; } private Map < String , AttributeDriver > buildAttributeDriverMap ( Iterable < ? extends AttributeDriver > flatDrivers ) { assert flatDrivers != null ; Map < String , List < AttributeDriver > > group = Maps . create ( ) ; for ( AttributeDriver driver : flatDrivers ) { LOG . debug ( "" , driver . getClass ( ) . getName ( ) ) ; String target = driver . getTargetName ( ) ; Maps . addToList ( group , target , driver ) ; } Map < String , AttributeDriver > results = Maps . create ( ) ; for ( Map . Entry < String , List < AttributeDriver > > entry : group . entrySet ( ) ) { String target = entry . getKey ( ) ; LOG . debug ( "" , target ) ; List < AttributeDriver > targetDrivers = entry . getValue ( ) ; AttributeDriver singular ; if ( targetDrivers . size ( ) == ) { singular = targetDrivers . get ( ) ; } else { assert targetDrivers . isEmpty ( ) == false ; singular = new CompositeAttributeDriver ( targetDrivers ) ; } results . put ( target , singular ) ; } return results ; } private static class CompositeAttributeDriver extends AttributeDriver { final List < AttributeDriver > drivers ; private final String targetName ; CompositeAttributeDriver ( List < AttributeDriver > drivers ) { assert drivers != null ; assert drivers . isEmpty ( ) == false ; this . targetName = drivers . get ( ) . getTargetName ( ) ; this . drivers = drivers ; } @ Override public String getTargetName ( ) { return targetName ; } @ Override public void process ( DmdlSemantics environment , Declaration declaration , AstAttribute attribute ) { for ( AttributeDriver driver : drivers ) { driver . process ( environment , declaration , attribute ) ; } } } } package com . asakusafw . dmdl . analyzer . driver ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . AstName ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . trait . NamespaceTrait ; import com . asakusafw . dmdl . spi . ModelAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class NamespaceDriver extends ModelAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { AstName name = getName ( environment , attribute ) ; if ( name != null ) { declaration . putTrait ( NamespaceTrait . class , new NamespaceTrait ( attribute , name ) ) ; } } private AstName getName ( DmdlSemantics environment , AstAttribute attribute ) { assert environment != null ; assert attribute != null ; Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; AstAttributeElement nameElement = elements . remove ( ELEMENT_NAME ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; if ( nameElement == null ) { environment . report ( new Diagnostic ( Level . ERROR , attribute . name , "" , TARGET_NAME , ELEMENT_NAME ) ) ; return null ; } else if ( ( nameElement . value instanceof AstName ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , nameElement , "" , TARGET_NAME , ELEMENT_NAME ) ) ; return null ; } else { return ( AstName ) nameElement . value ; } } } package com . asakusafw . dmdl . analyzer . driver ; import com . asakusafw . dmdl . model . AstBasicType ; import com . asakusafw . dmdl . model . AstType ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . dmdl . spi . TypeDriver ; public class BasicTypeDriver extends TypeDriver { @ Override public BasicType resolve ( DmdlSemantics world , AstType syntax ) { if ( syntax instanceof AstBasicType ) { AstBasicType ast = ( AstBasicType ) syntax ; return new BasicType ( ast , ast . kind ) ; } return null ; } } package com . asakusafw . dmdl . analyzer . driver ; package com . asakusafw . dmdl . analyzer . driver ; import java . util . List ; import java . util . Map ; import java . util . Set ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . ModelSymbol ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . trait . ProjectionsTrait ; import com . asakusafw . dmdl . spi . ModelAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; public class AutoProjectionDriver extends ModelAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; List < ModelSymbol > autoProjectios = collectProjections ( environment , declaration ) ; ProjectionsTrait projections = declaration . getTrait ( ProjectionsTrait . class ) ; if ( projections == null ) { projections = new ProjectionsTrait ( declaration . getOriginalAst ( ) . expression , autoProjectios ) ; } else { List < ModelSymbol > composite = Lists . create ( ) ; composite . addAll ( projections . getProjections ( ) ) ; composite . addAll ( autoProjectios ) ; projections = new ProjectionsTrait ( declaration . getOriginalAst ( ) . expression , composite ) ; } declaration . putTrait ( ProjectionsTrait . class , projections ) ; } private List < ModelSymbol > collectProjections ( DmdlSemantics environment , ModelDeclaration model ) { assert environment != null ; assert model != null ; Map < String , Type > properties = Maps . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { properties . put ( property . getName ( ) . identifier , property . getType ( ) ) ; } Set < String > saw = Sets . create ( ) ; saw . add ( model . getName ( ) . identifier ) ; ProjectionsTrait projections = model . getTrait ( ProjectionsTrait . class ) ; if ( projections != null ) { for ( ModelSymbol symbol : projections . getProjections ( ) ) { saw . add ( symbol . getName ( ) . identifier ) ; } } List < ModelSymbol > autoProjectios = Lists . create ( ) ; for ( ModelDeclaration other : environment . getDeclaredModels ( ) ) { if ( other . getOriginalAst ( ) . kind != ModelDefinitionKind . PROJECTIVE ) { continue ; } if ( saw . contains ( other . getName ( ) . identifier ) ) { continue ; } saw . add ( other . getName ( ) . identifier ) ; if ( contains ( properties , other ) ) { autoProjectios . add ( other . getSymbol ( ) ) ; } } return autoProjectios ; } private boolean contains ( Map < String , Type > properties , ModelDeclaration other ) { assert properties != null ; assert other != null ; List < PropertyDeclaration > projectionProperties = other . getDeclaredProperties ( ) ; if ( properties . size ( ) < projectionProperties . size ( ) ) { return false ; } for ( PropertyDeclaration projectionProperty : projectionProperties ) { Type type = properties . get ( projectionProperty . getName ( ) . identifier ) ; if ( type == null || type . isSame ( projectionProperty . getType ( ) ) == false ) { return false ; } } return true ; } } package com . asakusafw . dmdl . analyzer ; import java . util . Collection ; import com . asakusafw . dmdl . model . AstExpression ; import com . asakusafw . dmdl . model . AstJoin ; import com . asakusafw . dmdl . model . AstModelReference ; import com . asakusafw . dmdl . model . AstNode . AbstractVisitor ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . model . AstSummarize ; import com . asakusafw . dmdl . model . AstTerm ; import com . asakusafw . dmdl . model . AstUnionExpression ; public class ModelSymbolCollector extends AbstractVisitor < Collection < AstSimpleName > , Void > { public static final ModelSymbolCollector INSTANCE = new ModelSymbolCollector ( ) ; @ Override public Void visitModelReference ( Collection < AstSimpleName > context , AstModelReference node ) { context . add ( node . name ) ; return null ; } @ Override public Void visitJoin ( Collection < AstSimpleName > context , AstJoin node ) { node . reference . accept ( context , this ) ; return null ; } @ Override public Void visitSummarize ( Collection < AstSimpleName > context , AstSummarize node ) { node . reference . accept ( context , this ) ; return null ; } @ Override public < T extends AstTerm < T > > Void visitUnionExpression ( Collection < AstSimpleName > context , AstUnionExpression < T > node ) { for ( T child : node . terms ) { child . accept ( context , this ) ; } return null ; } } package com . asakusafw . dmdl . analyzer ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . Region ; import com . asakusafw . dmdl . model . * ; import com . asakusafw . dmdl . model . AstNode . AbstractVisitor ; import com . asakusafw . dmdl . semantics . Declaration ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . ModelSymbol ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . PropertyMappingKind ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . trait . JoinTrait ; import com . asakusafw . dmdl . semantics . trait . MappingFactor ; import com . asakusafw . dmdl . semantics . trait . ProjectionsTrait ; import com . asakusafw . dmdl . semantics . trait . ReduceTerm ; import com . asakusafw . dmdl . semantics . trait . SummarizeTrait ; import com . asakusafw . dmdl . spi . AttributeDriver ; import com . asakusafw . dmdl . spi . TypeDriver ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; public class DmdlAnalyzer { static final Logger LOG = LoggerFactory . getLogger ( DmdlAnalyzer . class ) ; final Context context ; private final Graph < String > modelDependencies ; public DmdlAnalyzer ( Iterable < ? extends TypeDriver > typeDrivers , Iterable < ? extends AttributeDriver > attributeDrivers ) { if ( typeDrivers == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributeDrivers == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = new Context ( new DmdlSemantics ( ) , typeDrivers , attributeDrivers ) ; this . modelDependencies = Graphs . newInstance ( ) ; } void report ( Diagnostic diagnostic ) { assert diagnostic != null ; context . getWorld ( ) . report ( diagnostic ) ; } public void addModel ( AstModelDefinition < ? > definition ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } DmdlSemantics world = context . getWorld ( ) ; if ( world . findModelDeclaration ( definition . name . identifier ) != null ) { report ( new Diagnostic ( Diagnostic . Level . ERROR , definition . name , "" , definition . name . identifier ) ) ; } else { world . declareModel ( definition , definition . name , definition . description , definition . attributes ) ; computeDependencies ( definition ) ; } } private void computeDependencies ( AstModelDefinition < ? > definition ) { assert definition != null ; LOG . debug ( "" , definition . name ) ; Set < AstSimpleName > references = Sets . create ( ) ; definition . expression . accept ( references , ModelSymbolCollector . INSTANCE ) ; modelDependencies . addNode ( definition . name . identifier ) ; for ( AstSimpleName target : references ) { modelDependencies . addEdge ( definition . name . identifier , target . identifier ) ; } } public synchronized DmdlSemantics resolve ( ) throws DmdlSemanticException { checkDiagnostics ( ) ; resolveSymbols ( ) ; checkDiagnostics ( ) ; resolveAttributes ( ) ; checkDiagnostics ( ) ; return context . getWorld ( ) ; } private void checkDiagnostics ( ) throws DmdlSemanticException { if ( context . getWorld ( ) . hasError ( ) ) { throw new DmdlSemanticException ( "" , context . getWorld ( ) . getDiagnostics ( ) ) ; } } private void resolveSymbols ( ) { LOG . debug ( "" ) ; Set < Set < String > > circuits = Graphs . findCircuit ( modelDependencies ) ; if ( circuits . isEmpty ( ) == false ) { for ( Set < String > loop : circuits ) { report ( new Diagnostic ( Level . ERROR , ( Region ) null , "" , loop ) ) ; } return ; } DmdlSemantics world = context . getWorld ( ) ; for ( String name : Graphs . sortPostOrder ( modelDependencies ) ) { ModelDeclaration model = world . findModelDeclaration ( name ) ; if ( model == null ) { continue ; } resolveModelSymbol ( model ) ; } } private void resolveModelSymbol ( ModelDeclaration model ) { assert model != null ; AstModelDefinition < ? > definition = model . getOriginalAst ( ) ; LOG . debug ( "" , definition . name ) ; switch ( definition . kind ) { case RECORD : resolveRecord ( model , definition . asRecord ( ) . expression ) ; break ; case PROJECTIVE : resolveRecord ( model , definition . asProjective ( ) . expression ) ; break ; case JOINED : resolveJoined ( model , definition . asJoined ( ) . expression ) ; break ; case SUMMARIZED : resolveSummarize ( model , definition . asSummarized ( ) . expression ) ; break ; default : throw new AssertionError ( definition . kind ) ; } } private void resolveRecord ( ModelDeclaration model , AstExpression < AstRecord > expression ) { assert model != null ; assert expression != null ; LOG . debug ( "" , model . getName ( ) ) ; RecordExpressionResolver resolver = new RecordExpressionResolver ( ) ; expression . accept ( model , resolver ) ; ProjectionsTrait projections = new ProjectionsTrait ( expression , resolver . projections ) ; LOG . debug ( "" , model . getName ( ) , projections . getProjections ( ) ) ; model . putTrait ( ProjectionsTrait . class , projections ) ; } private void resolveJoined ( ModelDeclaration model , AstExpression < AstJoin > expression ) { assert model != null ; assert expression != null ; LOG . debug ( "" , model . getName ( ) ) ; List < ReduceTerm < AstJoin > > results = Lists . create ( ) ; for ( AstJoin term : extract ( expression ) ) { LOG . debug ( "" , model . getName ( ) , term . reference . name ) ; ModelSymbol source = context . getWorld ( ) . createModelSymbol ( term . reference . name ) ; if ( source . findDeclaration ( ) == null ) { report ( new Diagnostic ( Level . ERROR , term . reference , "" , term . reference . name ) ) ; continue ; } resolveJoinProperties ( model , source , term ) ; List < MappingFactor > mappings = resolveMapping ( model , source , term . mapping ) ; List < PropertySymbol > grouping = resolveGrouping ( model , term . grouping ) ; results . add ( new ReduceTerm < AstJoin > ( term , source , mappings , grouping ) ) ; } if ( checkJoinTerms ( model , results ) ) { model . putTrait ( JoinTrait . class , new JoinTrait ( expression , results ) ) ; } } private void resolveJoinProperties ( ModelDeclaration model , ModelSymbol sourceModel , AstJoin term ) { assert model != null ; assert sourceModel != null ; assert term != null ; LOG . debug ( "" , term . mapping ) ; Set < String > groupingPropertyNames = Sets . create ( ) ; if ( term . grouping != null ) { for ( AstSimpleName name : term . grouping . properties ) { groupingPropertyNames . add ( name . identifier ) ; } } ModelDeclaration sourceDecl = sourceModel . findDeclaration ( ) ; assert sourceDecl != null ; if ( term . mapping == null ) { for ( PropertyDeclaration prop : sourceDecl . getDeclaredProperties ( ) ) { PropertyDeclaration declared = model . findPropertyDeclaration ( prop . getName ( ) . identifier ) ; if ( declared != null ) { LOG . debug ( "" , prop . getSymbol ( ) ) ; } else { model . declareProperty ( sourceModel . getName ( ) , prop . getName ( ) , prop . getType ( ) , prop . getDescription ( ) , prop . getAttributes ( ) ) ; } } } else { Set < String > saw = Sets . create ( ) ; for ( AstPropertyMapping property : term . mapping . properties ) { if ( saw . contains ( property . target . identifier ) ) { report ( new Diagnostic ( Level . ERROR , property , "" , property . target . identifier ) ) ; continue ; } saw . add ( property . target . identifier ) ; PropertyDeclaration sourceProp = sourceDecl . findPropertyDeclaration ( property . source . identifier ) ; if ( sourceProp == null ) { report ( new Diagnostic ( Level . ERROR , sourceModel . getName ( ) , "" , property . source . identifier , sourceModel . getName ( ) . identifier ) ) ; continue ; } PropertyDeclaration declared = model . findPropertyDeclaration ( property . target . identifier ) ; if ( declared != null ) { LOG . debug ( "" , property . target ) ; } else { model . declareProperty ( property , property . target , sourceProp . getType ( ) , property . description , property . attributes ) ; } } } } private List < MappingFactor > resolveMapping ( ModelDeclaration model , ModelSymbol source , AstModelMapping mapping ) { assert model != null ; assert source != null ; ModelDeclaration sourceModel = source . findDeclaration ( ) ; assert sourceModel != null ; List < MappingFactor > results = Lists . create ( ) ; if ( mapping == null ) { for ( PropertyDeclaration property : sourceModel . getDeclaredProperties ( ) ) { PropertyDeclaration targetProperty = model . findPropertyDeclaration ( property . getName ( ) . identifier ) ; if ( targetProperty != null ) { results . add ( new MappingFactor ( source . getName ( ) , PropertyMappingKind . ANY , source . createPropertySymbol ( property . getName ( ) ) , targetProperty . getSymbol ( ) ) ) ; } } } else { for ( AstPropertyMapping propertyMapping : mapping . properties ) { PropertyDeclaration targetProperty = model . findPropertyDeclaration ( propertyMapping . target . identifier ) ; if ( targetProperty != null ) { results . add ( new MappingFactor ( source . getName ( ) , PropertyMappingKind . ANY , source . createPropertySymbol ( propertyMapping . source ) , targetProperty . getSymbol ( ) ) ) ; } } } return results ; } private boolean checkJoinTerms ( ModelDeclaration model , List < ReduceTerm < AstJoin > > terms ) { assert model != null ; assert terms != null ; if ( checkGrouping ( model , terms ) == false ) { return false ; } boolean green = true ; Map < String , Type > typeMap = Maps . create ( ) ; for ( ReduceTerm < AstJoin > term : terms ) { Set < String > groupingProperties = Sets . create ( ) ; for ( PropertySymbol grouping : term . getGrouping ( ) ) { groupingProperties . add ( grouping . getName ( ) . identifier ) ; } for ( MappingFactor factor : term . getMappings ( ) ) { PropertySymbol target = factor . getTarget ( ) ; Type declared = typeMap . get ( target . getName ( ) . identifier ) ; if ( declared == null ) { typeMap . put ( target . getName ( ) . identifier , target . findDeclaration ( ) . getType ( ) ) ; } else if ( groupingProperties . contains ( target . getName ( ) . identifier ) == false ) { report ( new Diagnostic ( Level . ERROR , term . getOriginalAst ( ) , "" , target . getName ( ) . identifier ) ) ; green = false ; } } } return green ; } private void resolveSummarize ( ModelDeclaration model , AstExpression < AstSummarize > expression ) { assert model != null ; assert expression != null ; LOG . debug ( "" , model . getName ( ) ) ; List < ReduceTerm < AstSummarize > > results = Lists . create ( ) ; for ( AstSummarize term : extract ( expression ) ) { LOG . debug ( "" , model . getName ( ) , term . reference . name ) ; ModelSymbol source = context . getWorld ( ) . createModelSymbol ( term . reference . name ) ; if ( source . findDeclaration ( ) == null ) { report ( new Diagnostic ( Level . ERROR , term . reference , "" , term . reference . name ) ) ; continue ; } resolveSummarizeProperties ( model , source , term ) ; List < MappingFactor > foldings = resolveFolding ( model , source , term . folding ) ; List < PropertySymbol > grouping = resolveGrouping ( model , term . grouping ) ; results . add ( new ReduceTerm < AstSummarize > ( term , source , foldings , grouping ) ) ; } if ( checkSummarizeTerms ( model , results ) ) { model . putTrait ( SummarizeTrait . class , new SummarizeTrait ( expression , results ) ) ; } } private void resolveSummarizeProperties ( ModelDeclaration model , ModelSymbol source , AstSummarize term ) { assert model != null ; assert source != null ; assert term != null ; LOG . debug ( "" , term . folding ) ; ModelDeclaration decl = source . findDeclaration ( ) ; assert decl != null ; for ( AstPropertyFolding property : term . folding . properties ) { PropertyDeclaration original = decl . findPropertyDeclaration ( property . source . identifier ) ; if ( original == null ) { report ( new Diagnostic ( Level . ERROR , source . getName ( ) , "" , property . source . identifier , source . getName ( ) . identifier ) ) ; continue ; } PropertyMappingKind mapping = resolveAggregateFunction ( property . aggregator ) ; if ( mapping == null ) { report ( new Diagnostic ( Level . ERROR , property . aggregator , "" , property . aggregator . toString ( ) ) ) ; continue ; } Type resolved = original . getType ( ) . map ( mapping ) ; if ( resolved == null ) { report ( new Diagnostic ( Level . ERROR , property , "" , property . aggregator . toString ( ) , property . source . identifier , original . getType ( ) ) ) ; continue ; } PropertyDeclaration declared = model . findPropertyDeclaration ( property . target . identifier ) ; if ( declared != null ) { report ( new Diagnostic ( Level . ERROR , property . target , "" , property . target . identifier ) ) ; continue ; } model . declareProperty ( property , property . target , resolved , property . description , property . attributes ) ; } } private List < MappingFactor > resolveFolding ( ModelDeclaration model , ModelSymbol source , AstModelFolding folding ) { assert model != null ; assert source != null ; assert folding != null ; ModelDeclaration sourceModel = source . findDeclaration ( ) ; assert sourceModel != null ; List < MappingFactor > results = Lists . create ( ) ; for ( AstPropertyFolding propertyFolding : folding . properties ) { PropertyDeclaration targetProperty = model . findPropertyDeclaration ( propertyFolding . target . identifier ) ; PropertyMappingKind mapping = resolveAggregateFunction ( propertyFolding . aggregator ) ; if ( targetProperty != null && mapping != null ) { results . add ( new MappingFactor ( source . getName ( ) , mapping , source . createPropertySymbol ( propertyFolding . source ) , targetProperty . getSymbol ( ) ) ) ; } } return results ; } private boolean checkSummarizeTerms ( ModelDeclaration model , List < ReduceTerm < AstSummarize > > terms ) { assert model != null ; assert terms != null ; if ( checkGrouping ( model , terms ) == false ) { return false ; } return terms . size ( ) == ; } private PropertyMappingKind resolveAggregateFunction ( AstName aggregator ) { assert aggregator != null ; String name = aggregator . toString ( ) . toUpperCase ( ) ; try { return PropertyMappingKind . valueOf ( name ) ; } catch ( Exception e ) { return null ; } } private List < PropertySymbol > resolveGrouping ( ModelDeclaration model , AstGrouping grouping ) { assert model != null ; if ( grouping == null ) { return Collections . emptyList ( ) ; } else { Map < String , PropertySymbol > map = Maps . create ( ) ; for ( PropertyDeclaration p : model . getDeclaredProperties ( ) ) { map . put ( p . getName ( ) . identifier , p . getSymbol ( ) ) ; } List < PropertySymbol > results = Lists . create ( ) ; for ( AstSimpleName name : grouping . properties ) { PropertySymbol property = map . get ( name . identifier ) ; if ( property == null ) { report ( new Diagnostic ( Level . ERROR , name , "" , name . identifier ) ) ; continue ; } results . add ( model . createPropertySymbol ( name ) ) ; } return results ; } } private < T extends AstTerm < T > > boolean checkGrouping ( ModelDeclaration model , List < ReduceTerm < T > > terms ) { assert model != null ; assert terms != null ; Iterator < ReduceTerm < T > > iter = terms . iterator ( ) ; if ( iter . hasNext ( ) == false ) { return false ; } boolean green = true ; ReduceTerm < T > first = iter . next ( ) ; List < PropertyDeclaration > firstSources = resolveGroupingSources ( first ) ; while ( iter . hasNext ( ) ) { ReduceTerm < T > next = iter . next ( ) ; if ( first . getGrouping ( ) . size ( ) != next . getGrouping ( ) . size ( ) ) { report ( new Diagnostic ( Level . ERROR , next . getOriginalAst ( ) , "" , model . getName ( ) ) ) ; return false ; } List < PropertyDeclaration > nextSources = resolveGroupingSources ( next ) ; assert firstSources . size ( ) == nextSources . size ( ) ; for ( int i = , n = firstSources . size ( ) ; i < n ; i ++ ) { PropertyDeclaration left = firstSources . get ( i ) ; PropertyDeclaration right = nextSources . get ( i ) ; if ( left . getType ( ) . isSame ( right . getType ( ) ) == false ) { PropertySymbol rightSymbol = next . getGrouping ( ) . get ( i ) ; report ( new Diagnostic ( Level . ERROR , rightSymbol . getOriginalAst ( ) , "" , rightSymbol . getName ( ) ) ) ; green = false ; } } } return green ; } private List < PropertyDeclaration > resolveGroupingSources ( ReduceTerm < ? > term ) { assert term != null ; Map < PropertySymbol , PropertySymbol > rmap = new HashMap < PropertySymbol , PropertySymbol > ( ) ; for ( MappingFactor entry : term . getMappings ( ) ) { rmap . put ( entry . getTarget ( ) , entry . getSource ( ) ) ; } List < PropertyDeclaration > results = new ArrayList < PropertyDeclaration > ( ) ; for ( PropertySymbol prop : term . getGrouping ( ) ) { PropertySymbol source = rmap . get ( prop ) ; if ( source == null ) { source = prop ; } results . add ( source . findDeclaration ( ) ) ; } return results ; } private void resolveAttributes ( ) { for ( ModelDeclaration model : context . getWorld ( ) . getDeclaredModels ( ) ) { LOG . debug ( "" , model . getName ( ) ) ; resolveAttributes ( model ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { resolveAttributes ( property ) ; } } } private void resolveAttributes ( Declaration declaration ) { assert declaration != null ; for ( AstAttribute attribute : declaration . getAttributes ( ) ) { String name = attribute . name . toString ( ) ; LOG . debug ( "" , declaration . getName ( ) , name ) ; AttributeDriver driver = context . findAttributeDriver ( attribute ) ; if ( driver == null ) { report ( new Diagnostic ( Level . ERROR , attribute . name , "" , name ) ) ; continue ; } LOG . debug ( "" , name , driver ) ; driver . process ( context . getWorld ( ) , declaration , attribute ) ; } } private < T extends AstTerm < T > > List < T > extract ( AstExpression < T > expression ) { if ( expression instanceof AstTerm < ? > ) { AstTerm < T > term = ( AstTerm < T > ) expression ; return Collections . singletonList ( term . getUnit ( ) ) ; } else if ( expression instanceof AstUnionExpression < ? > ) { AstUnionExpression < T > union = ( AstUnionExpression < T > ) expression ; return union . terms ; } else { throw new AssertionError ( expression ) ; } } private class RecordExpressionResolver extends AbstractVisitor < ModelDeclaration , Void > { final List < ModelSymbol > projections = Lists . create ( ) ; RecordExpressionResolver ( ) { return ; } @ Override public < T extends AstTerm < T > > Void visitUnionExpression ( ModelDeclaration model , AstUnionExpression < T > node ) { for ( T term : node . terms ) { term . accept ( model , this ) ; } return null ; } @ Override public Void visitModelReference ( ModelDeclaration model , AstModelReference node ) { LOG . debug ( "" , node ) ; ModelDeclaration decl = context . getWorld ( ) . findModelDeclaration ( node . name . identifier ) ; if ( decl == null ) { report ( new Diagnostic ( Level . ERROR , node . name , "" , node . name . identifier ) ) ; return null ; } for ( PropertyDeclaration property : decl . getDeclaredProperties ( ) ) { PropertyDeclaration other = model . findPropertyDeclaration ( property . getName ( ) . identifier ) ; if ( other != null ) { LOG . debug ( "" , property . getSymbol ( ) ) ; if ( property . getType ( ) . isSame ( other . getType ( ) ) == false ) { report ( new Diagnostic ( Level . ERROR , node , "" , property . getName ( ) , model . getName ( ) ) ) ; } continue ; } model . declareProperty ( node , property . getName ( ) , property . getType ( ) , property . getDescription ( ) , property . getAttributes ( ) ) ; } if ( decl . getOriginalAst ( ) . kind == ModelDefinitionKind . PROJECTIVE ) { projections . add ( context . getWorld ( ) . createModelSymbol ( node . name ) ) ; } return null ; } @ Override public Void visitRecordDefinition ( ModelDeclaration model , AstRecordDefinition node ) { LOG . debug ( "" , node ) ; Set < String > sawPropertyName = Sets . create ( ) ; for ( AstPropertyDefinition property : node . properties ) { if ( sawPropertyName . contains ( property . name . identifier ) ) { report ( new Diagnostic ( Level . ERROR , property . name , "" , property . name . identifier ) ) ; } sawPropertyName . add ( property . name . identifier ) ; Type type = context . resolveType ( property . type ) ; if ( type == null ) { report ( new Diagnostic ( Level . ERROR , property . type , "" , property . type . toString ( ) ) ) ; continue ; } PropertyDeclaration other = model . findPropertyDeclaration ( property . name . identifier ) ; if ( other != null ) { LOG . debug ( "" , property . name ) ; if ( type . equals ( other . getType ( ) ) == false ) { report ( new Diagnostic ( Level . ERROR , property . name , "" , property . name , model . getName ( ) ) ) ; } continue ; } model . declareProperty ( property , property . name , type , property . description , property . attributes ) ; } return null ; } } } package com . asakusafw . dmdl . spi ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . semantics . Declaration ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; public abstract class ModelAttributeDriver extends AttributeDriver { @ Override public final void process ( DmdlSemantics environment , Declaration declaration , AstAttribute attribute ) { assert attribute . name . toString ( ) . equals ( getTargetName ( ) ) ; if ( ( declaration instanceof ModelDeclaration ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , declaration . getOriginalAst ( ) , "" , getTargetName ( ) ) ) ; return ; } process ( environment , ( ModelDeclaration ) declaration , attribute ) ; } public abstract void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) ; } package com . asakusafw . dmdl . spi ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . semantics . Declaration ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; public abstract class PropertyAttributeDriver extends AttributeDriver { @ Override public final void process ( DmdlSemantics environment , Declaration declaration , AstAttribute attribute ) { assert attribute . name . toString ( ) . equals ( getTargetName ( ) ) ; if ( ( declaration instanceof PropertyDeclaration ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , declaration . getOriginalAst ( ) , "" , getTargetName ( ) ) ) ; return ; } process ( environment , ( PropertyDeclaration ) declaration , attribute ) ; } public abstract void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) ; } package com . asakusafw . dmdl . spi ; import com . asakusafw . dmdl . model . AstType ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . Type ; public abstract class TypeDriver { public abstract Type resolve ( DmdlSemantics environment , AstType syntax ) ; } package com . asakusafw . dmdl . spi ; package com . asakusafw . dmdl . spi ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . semantics . Declaration ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; public abstract class AttributeDriver { public abstract String getTargetName ( ) ; public abstract void process ( DmdlSemantics environment , Declaration declaration , AstAttribute attribute ) ; @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) ; } } package com . asakusafw . dmdl ; import java . io . Serializable ; import java . net . URI ; import java . text . MessageFormat ; public final class Region implements Serializable { private static final long serialVersionUID = - ; public final URI sourceFile ; public final int beginLine ; public final int beginColumn ; public final int endLine ; public final int endColumn ; public Region ( URI sourceFile , int beginLine , int beginColumn , int endLine , int endColumn ) { this . sourceFile = sourceFile ; this . beginLine = beginLine ; this . beginColumn = beginColumn ; this . endLine = endLine ; this . endColumn = endColumn ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , sourceFile == null ? "" : sourceFile , beginLine , beginColumn , endLine , endColumn ) ; } } package com . asakusafw . dmdl . parser ; import static com . asakusafw . dmdl . parser . JjDmdlParserConstants . * ; import java . text . MessageFormat ; import com . asakusafw . dmdl . Region ; import com . asakusafw . dmdl . parser . JjDmdlParser . ParseFrame ; public class DmdlSyntaxException extends Exception { private static final long serialVersionUID = ; private final Region region ; public DmdlSyntaxException ( ParseException exception , JjDmdlParser parser ) { super ( buildMessage ( exception , parser ) , exception ) ; this . region = computeRegion ( exception , parser ) ; } public Region getRegion ( ) { return region ; } private Region computeRegion ( ParseException exception , JjDmdlParser parser ) { assert exception != null ; assert parser != null ; Token token = parser . getToken ( ) ; if ( token != null && token . kind != EOF ) { return new Region ( parser . getSourceFile ( ) , token . beginLine , token . beginColumn , token . endLine , token . endColumn ) ; } return null ; } private static String buildMessage ( ParseException exception , JjDmdlParser parser ) { assert exception != null ; assert parser != null ; ParseFrame [ ] frames = parser . getFrames ( ) ; if ( frames . length == ) { return MessageFormat . format ( "" , parser . getSourceFile ( ) , getReason ( exception , parser ) ) ; } else { ParseFrame top = frames [ ] ; return MessageFormat . format ( "" , parser . getSourceFile ( ) , getReason ( exception , parser ) , top . getRuleName ( ) ) ; } } private static String getReason ( ParseException exception , JjDmdlParser parser ) { assert exception != null ; assert parser != null ; Token token = parser . getToken ( ) ; if ( token . kind == UNEXPECTED ) { return MessageFormat . format ( "" , token . image ) ; } for ( int [ ] sequence : exception . expectedTokenSequences ) { if ( sequence . length == ) { continue ; } int next = sequence [ ] ; if ( next == END_OF_DECLARATION ) { return MessageFormat . format ( "" , exception . tokenImage [ END_OF_DECLARATION ] ) ; } } if ( token . kind == EOF ) { return "" ; } if ( token . image == null || token . image . isEmpty ( ) ) { return exception . tokenImage [ token . kind ] ; } else { return token . image ; } } } package com . asakusafw . dmdl . parser ; import java . io . Reader ; import java . io . StringReader ; import java . net . URI ; import java . net . URISyntaxException ; import java . text . MessageFormat ; import java . util . Arrays ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . AstScript ; public class DmdlParser { static final Logger LOG = LoggerFactory . getLogger ( DmdlParser . class ) ; public AstScript parse ( Reader source , URI identifier ) throws DmdlSyntaxException { if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , identifier ) ; JjDmdlParser parser = new JjDmdlParser ( source ) ; try { return parser . parse ( identifier ) ; } catch ( ParseException e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , identifier , e . currentToken , Arrays . toString ( parser . getFrames ( ) ) ) , e ) ; } throw new DmdlSyntaxException ( e , parser ) ; } } public AstLiteral parseLiteral ( String token ) throws DmdlSyntaxException { if ( token == null ) { throw new IllegalArgumentException ( "" ) ; } JjDmdlParser parser = new JjDmdlParser ( new StringReader ( token ) ) ; try { return parser . parseLiteral ( new URI ( "" ) ) ; } catch ( ParseException e ) { throw new DmdlSyntaxException ( e , parser ) ; } catch ( URISyntaxException e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . dmdl . parser ; package com . asakusafw . dmdl . parser ; import java . io . PrintWriter ; import java . text . MessageFormat ; import java . util . Iterator ; import java . util . LinkedList ; import com . asakusafw . dmdl . model . * ; public final class DmdlEmitter { public static void emit ( AstNode node , PrintWriter output ) { if ( node == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } Context context = new Context ( output ) ; node . accept ( context , Engine . INSTANCE ) ; } private DmdlEmitter ( ) { return ; } private static class Engine implements AstNode . Visitor < Context , Void > { static final Engine INSTANCE = new Engine ( ) ; @ Override public Void visitAttribute ( Context context , AstAttribute node ) { context . print ( "" ) ; node . name . accept ( context , this ) ; if ( node . elements . isEmpty ( ) == false ) { context . println ( "" ) ; context . enter ( ) ; for ( int i = , n = node . elements . size ( ) ; i < n ; i ++ ) { node . elements . get ( i ) . accept ( context , this ) ; if ( i != n - ) { context . println ( "" ) ; } else { context . println ( ) ; } } context . exit ( ) ; context . print ( "" ) ; } return null ; } @ Override public Void visitAttributeElement ( Context context , AstAttributeElement node ) { node . name . accept ( context , this ) ; context . print ( "" ) ; node . value . accept ( context , this ) ; return null ; } @ Override public Void visitAttributeValueArray ( Context context , AstAttributeValueArray node ) { context . println ( "" ) ; context . enter ( ) ; for ( int i = , n = node . elements . size ( ) ; i < n ; i ++ ) { node . elements . get ( i ) . accept ( context , this ) ; if ( i != n - ) { context . println ( "" ) ; } else { context . println ( ) ; } } context . exit ( ) ; context . print ( "" ) ; return null ; } @ Override public Void visitBasicType ( Context context , AstBasicType node ) { context . print ( "" , node . kind . name ( ) ) ; return null ; } @ Override public Void visitDescription ( Context context , AstDescription node ) { context . print ( "" , node . token ) ; return null ; } @ Override public Void visitGrouping ( Context context , AstGrouping node ) { context . print ( "" ) ; Iterator < AstSimpleName > iter = node . properties . iterator ( ) ; if ( iter . hasNext ( ) ) { iter . next ( ) . accept ( context , this ) ; while ( iter . hasNext ( ) ) { context . print ( "" ) ; iter . next ( ) . accept ( context , this ) ; } } return null ; } @ Override public Void visitJoin ( Context context , AstJoin node ) { node . reference . accept ( context , this ) ; if ( node . mapping != null ) { context . print ( "" ) ; node . mapping . accept ( context , this ) ; } if ( node . grouping != null ) { context . print ( "" ) ; node . grouping . accept ( context , this ) ; } return null ; } @ Override public Void visitLiteral ( Context context , AstLiteral node ) { context . print ( "" , node . token ) ; return null ; } @ Override public < T extends AstTerm < T > > Void visitModelDefinition ( Context context , AstModelDefinition < T > node ) { if ( node . description != null ) { node . description . accept ( context , this ) ; context . println ( ) ; } for ( AstAttribute attribute : node . attributes ) { attribute . accept ( context , this ) ; context . println ( ) ; } switch ( node . kind ) { case JOINED : context . print ( "" ) ; break ; case PROJECTIVE : context . print ( "" ) ; break ; case SUMMARIZED : context . print ( "" ) ; break ; default : break ; } node . name . accept ( context , this ) ; context . print ( "" ) ; node . expression . accept ( context , this ) ; context . print ( "" ) ; return null ; } @ Override public Void visitModelFolding ( Context context , AstModelFolding node ) { context . println ( "" , "" ) ; context . enter ( ) ; for ( AstPropertyFolding property : node . properties ) { property . accept ( context , this ) ; context . println ( ) ; } context . exit ( ) ; context . print ( "" , "" ) ; return null ; } @ Override public Void visitModelMapping ( Context context , AstModelMapping node ) { context . println ( "" , "" ) ; context . enter ( ) ; for ( AstPropertyMapping property : node . properties ) { property . accept ( context , this ) ; context . println ( ) ; } context . exit ( ) ; context . print ( "" , "" ) ; return null ; } @ Override public Void visitModelReference ( Context context , AstModelReference node ) { node . name . accept ( context , this ) ; return null ; } @ Override public Void visitPropertyDefinition ( Context context , AstPropertyDefinition node ) { if ( node . description != null ) { node . description . accept ( context , this ) ; context . println ( ) ; } for ( AstAttribute attribute : node . attributes ) { attribute . accept ( context , this ) ; context . println ( ) ; } node . name . accept ( context , this ) ; context . print ( "" ) ; node . type . accept ( context , this ) ; context . print ( "" ) ; return null ; } @ Override public Void visitPropertyFolding ( Context context , AstPropertyFolding node ) { if ( node . description != null ) { node . description . accept ( context , this ) ; context . println ( ) ; } for ( AstAttribute attribute : node . attributes ) { attribute . accept ( context , this ) ; context . println ( ) ; } node . aggregator . accept ( context , this ) ; context . print ( "" ) ; node . source . accept ( context , this ) ; context . print ( "" ) ; node . target . accept ( context , this ) ; context . print ( "" ) ; return null ; } @ Override public Void visitPropertyMapping ( Context context , AstPropertyMapping node ) { if ( node . description != null ) { node . description . accept ( context , this ) ; context . println ( ) ; } for ( AstAttribute attribute : node . attributes ) { attribute . accept ( context , this ) ; context . println ( ) ; } node . source . accept ( context , this ) ; context . print ( "" ) ; node . target . accept ( context , this ) ; context . print ( "" ) ; return null ; } @ Override public Void visitRecordDefinition ( Context context , AstRecordDefinition node ) { context . println ( "" ) ; context . enter ( ) ; for ( AstPropertyDefinition property : node . properties ) { property . accept ( context , this ) ; context . println ( ) ; } context . exit ( ) ; context . print ( "" ) ; return null ; } @ Override public Void visitReferenceType ( Context context , AstReferenceType node ) { node . name . accept ( context , this ) ; return null ; } @ Override public Void visitSequenceType ( Context context , AstSequenceType node ) { node . elementType . accept ( context , this ) ; context . print ( "" ) ; return null ; } @ Override public Void visitScript ( Context context , AstScript node ) { Iterator < AstModelDefinition < ? > > iter = node . models . iterator ( ) ; if ( iter . hasNext ( ) ) { iter . next ( ) . accept ( context , this ) ; while ( iter . hasNext ( ) ) { context . println ( ) ; context . println ( ) ; iter . next ( ) . accept ( context , this ) ; } } return null ; } @ Override public Void visitSummarize ( Context context , AstSummarize node ) { node . reference . accept ( context , this ) ; context . print ( "" ) ; node . folding . accept ( context , this ) ; if ( node . grouping != null ) { context . print ( "" ) ; node . grouping . accept ( context , this ) ; } return null ; } @ Override public < T extends AstTerm < T > > Void visitUnionExpression ( Context context , AstUnionExpression < T > node ) { Iterator < T > iter = node . terms . iterator ( ) ; assert iter . hasNext ( ) ; iter . next ( ) . accept ( context , this ) ; while ( iter . hasNext ( ) ) { context . print ( "" ) ; iter . next ( ) . accept ( context , this ) ; } return null ; } @ Override public Void visitSimpleName ( Context context , AstSimpleName node ) { context . print ( "" , node . identifier ) ; return null ; } @ Override public Void visitQualifiedName ( Context context , AstQualifiedName node ) { LinkedList < AstSimpleName > names = new LinkedList < AstSimpleName > ( ) ; AstName current = node ; while ( current . getQualifier ( ) != null ) { names . addFirst ( current . getSimpleName ( ) ) ; current = current . getQualifier ( ) ; } assert current instanceof AstSimpleName ; current . accept ( context , this ) ; for ( AstSimpleName segment : names ) { context . print ( "" ) ; segment . accept ( context , this ) ; } return null ; } } private static class Context { private final PrintWriter writer ; private int indent ; private boolean headOfLine ; Context ( PrintWriter writer ) { assert writer != null ; this . writer = writer ; } public void print ( String pattern , String ... arguments ) { put ( MessageFormat . format ( pattern , ( Object [ ] ) arguments ) ) ; } private void put ( String string ) { if ( string . isEmpty ( ) ) { return ; } if ( headOfLine ) { for ( int i = ; i < indent ; i ++ ) { writer . print ( "" ) ; } headOfLine = false ; } writer . print ( string ) ; } public void println ( String pattern , String ... arguments ) { print ( pattern , arguments ) ; println ( ) ; } public void println ( ) { headOfLine = true ; writer . println ( ) ; } public void enter ( ) { indent ++ ; } public void exit ( ) { indent -- ; } } } package com . asakusafw . dmdl . model ; import java . util . Arrays ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstAttribute extends AbstractAstNode { private final Region region ; public final AstName name ; public final List < AstAttributeElement > elements ; public AstAttribute ( Region region , AstName name , List < AstAttributeElement > elements ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . name = name ; this . elements = Lists . freeze ( elements ) ; } public AstAttribute ( Region region , AstName name , AstAttributeElement ... elements ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . name = name ; this . elements = Lists . freeze ( Arrays . asList ( elements ) ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitAttribute ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + elements . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstAttribute other = ( AstAttribute ) obj ; if ( ! elements . equals ( other . elements ) ) { return false ; } if ( ! name . equals ( other . name ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstRecordDefinition extends AbstractAstNode implements AstRecord { private final Region region ; public final List < AstPropertyDefinition > properties ; public AstRecordDefinition ( Region region , List < AstPropertyDefinition > properties ) { this . region = region ; this . properties = Lists . freeze ( properties ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public AstRecord getUnit ( ) { return this ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitRecordDefinition ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + properties . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstRecordDefinition other = ( AstRecordDefinition ) obj ; if ( ! properties . equals ( other . properties ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import com . asakusafw . dmdl . Region ; public class AstReferenceType extends AbstractAstNode implements AstType { private final Region region ; public final AstSimpleName name ; public AstReferenceType ( Region region , AstSimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . name = name ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitReferenceType ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + name . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstReferenceType other = ( AstReferenceType ) obj ; if ( ! name . equals ( other . name ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; public enum BasicTypeKind { BYTE , SHORT , INT , LONG , DECIMAL , FLOAT , DOUBLE , TEXT , BOOLEAN , DATE , DATETIME , } package com . asakusafw . dmdl . model ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . dmdl . Region ; public class AstModelDefinition < T extends AstTerm < T > > extends AbstractAstNode { private final Region region ; public final ModelDefinitionKind kind ; public final AstDescription description ; public final List < AstAttribute > attributes ; public final AstSimpleName name ; public final AstExpression < T > expression ; public AstModelDefinition ( Region region , ModelDefinitionKind kind , AstDescription description , List < AstAttribute > attributes , AstSimpleName name , AstExpression < T > expression ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( expression == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . kind = kind ; this . description = description ; this . attributes = attributes ; this . name = name ; this . expression = expression ; } public AstModelDefinition < AstRecord > asRecord ( ) { return cast ( ModelDefinitionKind . RECORD ) ; } public AstModelDefinition < AstRecord > asProjective ( ) { return cast ( ModelDefinitionKind . PROJECTIVE ) ; } public AstModelDefinition < AstJoin > asJoined ( ) { return cast ( ModelDefinitionKind . JOINED ) ; } public AstModelDefinition < AstSummarize > asSummarized ( ) { return cast ( ModelDefinitionKind . SUMMARIZED ) ; } private < U extends AstTerm < U > > AstModelDefinition < U > cast ( ModelDefinitionKind target ) { assert target != null ; if ( kind == target ) { @ SuppressWarnings ( "" ) AstModelDefinition < U > cast = ( AstModelDefinition < U > ) this ; return cast ; } throw new IllegalStateException ( MessageFormat . format ( "" , name , target , kind ) ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitModelDefinition ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + kind . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; result = prime * result + attributes . hashCode ( ) ; result = prime * result + ( ( description == null ) ? : description . hashCode ( ) ) ; result = prime * result + expression . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstModelDefinition < ? > other = ( AstModelDefinition < ? > ) obj ; if ( kind != other . kind ) { return false ; } if ( ! name . equals ( other . name ) ) { return false ; } if ( ! attributes . equals ( other . attributes ) ) { return false ; } if ( description == null ) { if ( other . description != null ) { return false ; } } else if ( ! description . equals ( other . description ) ) { return false ; } if ( ! expression . equals ( other . expression ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; public interface AstExpression < T extends AstTerm < T > > extends AstNode { } package com . asakusafw . dmdl . model ; public enum LiteralKind { STRING , INTEGER , DECIMAL , BOOLEAN , } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstAttributeValueArray extends AbstractAstNode implements AstAttributeValue { private final Region region ; public final List < AstAttributeValue > elements ; public AstAttributeValueArray ( Region region , List < ? extends AstAttributeValue > elements ) { this . region = region ; this . elements = Lists . freeze ( elements ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitAttributeValueArray ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + elements . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstAttributeValueArray other = ( AstAttributeValueArray ) obj ; if ( ! elements . equals ( other . elements ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; public interface AstTerm < T extends AstTerm < T > > extends AstExpression < T > { T getUnit ( ) ; } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstScript extends AbstractAstNode { private final Region region ; public final List < AstModelDefinition < ? > > models ; public AstScript ( Region region , List < ? extends AstModelDefinition < ? > > models ) { if ( models == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . models = Lists . freeze ( models ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitScript ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + models . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstScript other = ( AstScript ) obj ; if ( ! models . equals ( other . models ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; package com . asakusafw . dmdl . model ; public interface AstType extends AstNode { } package com . asakusafw . dmdl . model ; import com . asakusafw . dmdl . Region ; public interface AstNode { Region getRegion ( ) ; < C , R > R accept ( C context , Visitor < C , R > visitor ) ; public interface Visitor < C , R > { R visitAttribute ( C context , AstAttribute node ) ; R visitAttributeElement ( C context , AstAttributeElement node ) ; R visitAttributeValueArray ( C context , AstAttributeValueArray node ) ; R visitBasicType ( C context , AstBasicType node ) ; R visitDescription ( C context , AstDescription node ) ; R visitGrouping ( C context , AstGrouping node ) ; R visitJoin ( C context , AstJoin node ) ; R visitLiteral ( C context , AstLiteral node ) ; < T extends AstTerm < T > > R visitModelDefinition ( C context , AstModelDefinition < T > node ) ; R visitModelFolding ( C context , AstModelFolding node ) ; R visitModelMapping ( C context , AstModelMapping node ) ; R visitModelReference ( C context , AstModelReference node ) ; R visitPropertyDefinition ( C context , AstPropertyDefinition node ) ; R visitPropertyFolding ( C context , AstPropertyFolding node ) ; R visitPropertyMapping ( C context , AstPropertyMapping node ) ; R visitReferenceType ( C context , AstReferenceType node ) ; R visitRecordDefinition ( C context , AstRecordDefinition node ) ; R visitSequenceType ( C context , AstSequenceType node ) ; R visitScript ( C context , AstScript node ) ; R visitSummarize ( C context , AstSummarize node ) ; < T extends AstTerm < T > > R visitUnionExpression ( C context , AstUnionExpression < T > node ) ; R visitSimpleName ( C context , AstSimpleName node ) ; R visitQualifiedName ( C context , AstQualifiedName node ) ; } public abstract class AbstractVisitor < C , R > implements Visitor < C , R > { @ Override public R visitAttribute ( C context , AstAttribute node ) { return null ; } @ Override public R visitAttributeElement ( C context , AstAttributeElement node ) { return null ; } @ Override public R visitAttributeValueArray ( C context , AstAttributeValueArray node ) { return null ; } @ Override public R visitBasicType ( C context , AstBasicType node ) { return null ; } @ Override public R visitDescription ( C context , AstDescription node ) { return null ; } @ Override public R visitGrouping ( C context , AstGrouping node ) { return null ; } @ Override public R visitJoin ( C context , AstJoin node ) { return null ; } @ Override public R visitLiteral ( C context , AstLiteral node ) { return null ; } @ Override public < T extends AstTerm < T > > R visitModelDefinition ( C context , AstModelDefinition < T > node ) { return null ; } @ Override public R visitModelFolding ( C context , AstModelFolding node ) { return null ; } @ Override public R visitModelMapping ( C context , AstModelMapping node ) { return null ; } @ Override public R visitModelReference ( C context , AstModelReference node ) { return null ; } @ Override public R visitPropertyDefinition ( C context , AstPropertyDefinition node ) { return null ; } @ Override public R visitPropertyFolding ( C context , AstPropertyFolding node ) { return null ; } @ Override public R visitPropertyMapping ( C context , AstPropertyMapping node ) { return null ; } @ Override public R visitRecordDefinition ( C context , AstRecordDefinition node ) { return null ; } @ Override public R visitReferenceType ( C context , AstReferenceType node ) { return null ; } @ Override public R visitSequenceType ( C context , AstSequenceType node ) { return null ; } @ Override public R visitScript ( C context , AstScript node ) { return null ; } @ Override public R visitSummarize ( C context , AstSummarize node ) { return null ; } @ Override public < T extends AstTerm < T > > R visitUnionExpression ( C context , AstUnionExpression < T > node ) { return null ; } @ Override public R visitSimpleName ( C context , AstSimpleName node ) { return null ; } @ Override public R visitQualifiedName ( C context , AstQualifiedName node ) { return null ; } } } package com . asakusafw . dmdl . model ; public abstract class AbstractAstNode implements AstNode { } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstPropertyMapping extends AbstractAstNode { private final Region region ; public final AstDescription description ; public final List < AstAttribute > attributes ; public final AstSimpleName source ; public final AstSimpleName target ; public AstPropertyMapping ( Region region , AstDescription description , List < AstAttribute > attributes , AstSimpleName source , AstSimpleName target ) { if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . description = description ; this . attributes = Lists . freeze ( attributes ) ; this . source = source ; this . target = target ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitPropertyMapping ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + source . hashCode ( ) ; result = prime * result + target . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstPropertyMapping other = ( AstPropertyMapping ) obj ; if ( ! source . equals ( other . source ) ) { return false ; } if ( ! target . equals ( other . target ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstPropertyDefinition extends AbstractAstNode { private final Region region ; public final AstDescription description ; public final List < AstAttribute > attributes ; public final AstSimpleName name ; public final AstType type ; public AstPropertyDefinition ( Region region , AstDescription description , List < AstAttribute > attributes , AstSimpleName name , AstType type ) { if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . description = description ; this . attributes = Lists . freeze ( attributes ) ; this . name = name ; this . type = type ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitPropertyDefinition ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + attributes . hashCode ( ) ; result = prime * result + ( ( description == null ) ? : description . hashCode ( ) ) ; result = prime * result + name . hashCode ( ) ; result = prime * result + type . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstPropertyDefinition other = ( AstPropertyDefinition ) obj ; if ( ! name . equals ( other . name ) ) { return false ; } if ( ! type . equals ( other . type ) ) { return false ; } if ( ! attributes . equals ( other . attributes ) ) { return false ; } if ( description == null ) { if ( other . description != null ) { return false ; } } else if ( ! description . equals ( other . description ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import com . asakusafw . dmdl . Region ; public class AstSequenceType extends AbstractAstNode implements AstType { private final Region region ; public final AstType elementType ; public AstSequenceType ( Region region , AstType elementType ) { if ( elementType == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . elementType = elementType ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitSequenceType ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + elementType . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstSequenceType other = ( AstSequenceType ) obj ; if ( ! elementType . equals ( other . elementType ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstPropertyFolding extends AbstractAstNode { private final Region region ; public final AstDescription description ; public final List < AstAttribute > attributes ; public final AstName aggregator ; public final AstSimpleName source ; public final AstSimpleName target ; public AstPropertyFolding ( Region region , AstDescription description , List < AstAttribute > attributes , AstName aggregator , AstSimpleName source , AstSimpleName target ) { if ( aggregator == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . description = description ; this . attributes = Lists . freeze ( attributes ) ; this . aggregator = aggregator ; this . source = source ; this . target = target ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitPropertyFolding ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + aggregator . hashCode ( ) ; result = prime * result + source . hashCode ( ) ; result = prime * result + target . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstPropertyFolding other = ( AstPropertyFolding ) obj ; if ( ! aggregator . equals ( other . aggregator ) ) { return false ; } if ( ! source . equals ( other . source ) ) { return false ; } if ( ! target . equals ( other . target ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; public interface AstName extends AstAttributeValue { AstName getQualifier ( ) ; AstSimpleName getSimpleName ( ) ; } package com . asakusafw . dmdl . model ; import com . asakusafw . dmdl . Region ; public class AstBasicType extends AbstractAstNode implements AstType { private final Region region ; public final BasicTypeKind kind ; public AstBasicType ( Region region , BasicTypeKind kind ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . kind = kind ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitBasicType ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + kind . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstBasicType other = ( AstBasicType ) obj ; if ( kind != other . kind ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; public enum ModelDefinitionKind { RECORD , PROJECTIVE , JOINED , SUMMARIZED , } package com . asakusafw . dmdl . model ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . text . MessageFormat ; import com . asakusafw . dmdl . Region ; public class AstLiteral extends AbstractAstNode implements AstAttributeValue { private static final char [ ] ASCII_SPECIAL_ESCAPE = new char [ ] ; static { ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; } private final Region region ; public final String token ; public final LiteralKind kind ; public AstLiteral ( Region region , String token , LiteralKind kind ) { if ( token == null ) { throw new IllegalArgumentException ( "" ) ; } if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . token = token ; this . kind = kind ; } public static String quote ( String string ) { if ( string == null ) { throw new IllegalArgumentException ( "" ) ; } StringBuilder buf = new StringBuilder ( ) ; buf . append ( '' ) ; for ( char c : string . toCharArray ( ) ) { if ( c <= && ASCII_SPECIAL_ESCAPE [ c ] != ) { buf . append ( '' ) ; buf . append ( ASCII_SPECIAL_ESCAPE [ c ] ) ; } else if ( Character . isISOControl ( c ) || Character . isDefined ( c ) == false ) { buf . append ( String . format ( "" , ( int ) c ) ) ; } else { buf . append ( c ) ; } } buf . append ( '' ) ; return buf . toString ( ) ; } public String toStringValue ( ) { checkKind ( LiteralKind . STRING ) ; if ( token . length ( ) >= && token . startsWith ( "" ) && token . endsWith ( "" ) ) { return EscapeDecoder . scan ( token . substring ( , token . length ( ) - ) ) ; } throw new IllegalStateException ( MessageFormat . format ( "" , token ) ) ; } public BigInteger toIntegerValue ( ) { checkKind ( LiteralKind . INTEGER ) ; return new BigInteger ( token ) ; } public BigDecimal toDecimalValue ( ) { checkKind ( LiteralKind . DECIMAL ) ; return new BigDecimal ( token ) ; } public boolean toBooleanValue ( ) { checkKind ( LiteralKind . BOOLEAN ) ; return token . equals ( "" ) ; } private void checkKind ( LiteralKind expected ) { assert expected != null ; if ( kind != expected ) { throw new IllegalStateException ( MessageFormat . format ( "" , token ) ) ; } } @ Override public Region getRegion ( ) { return region ; } public String getToken ( ) { return token ; } public LiteralKind getKind ( ) { return kind ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitLiteral ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + kind . hashCode ( ) ; result = prime * result + token . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstLiteral other = ( AstLiteral ) obj ; if ( kind != other . kind ) { return false ; } if ( ! token . equals ( other . token ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstUnionExpression < T extends AstTerm < T > > extends AbstractAstNode implements AstExpression < T > { private final Region region ; public final List < T > terms ; public AstUnionExpression ( Region region , List < ? extends T > terms ) { if ( terms == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . terms = Lists . freeze ( terms ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitUnionExpression ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + terms . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstUnionExpression < ? > other = ( AstUnionExpression < ? > ) obj ; if ( ! terms . equals ( other . terms ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; public interface AstRecord extends AstTerm < AstRecord > { } package com . asakusafw . dmdl . model ; import com . asakusafw . dmdl . Region ; public class AstSummarize extends AbstractAstNode implements AstTerm < AstSummarize > { private final Region region ; public final AstModelReference reference ; public final AstModelFolding folding ; public final AstGrouping grouping ; public AstSummarize ( Region region , AstModelReference reference , AstModelFolding folding , AstGrouping grouping ) { if ( reference == null ) { throw new IllegalArgumentException ( "" ) ; } if ( folding == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . reference = reference ; this . folding = folding ; this . grouping = grouping ; } @ Override public Region getRegion ( ) { return region ; } @ Override public AstSummarize getUnit ( ) { return this ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitSummarize ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + reference . hashCode ( ) ; result = prime * result + folding . hashCode ( ) ; result = prime * result + ( ( grouping == null ) ? : grouping . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstSummarize other = ( AstSummarize ) obj ; if ( ! reference . equals ( other . reference ) ) { return false ; } if ( ! folding . equals ( other . folding ) ) { return false ; } if ( grouping == null ) { if ( other . grouping != null ) { return false ; } } else if ( ! grouping . equals ( other . grouping ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstSimpleName extends AbstractAstNode implements AstName { private final Region region ; public final String identifier ; public AstSimpleName ( Region region , String identifier ) { if ( identifier == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . identifier = identifier ; } @ Override public Region getRegion ( ) { return region ; } @ Override public AstName getQualifier ( ) { return null ; } @ Override public AstSimpleName getSimpleName ( ) { return this ; } public List < String > getWordList ( ) { int start = identifier . indexOf ( '' ) ; if ( start < ) { return Collections . singletonList ( identifier ) ; } List < String > results = Lists . create ( ) ; if ( start != ) { results . add ( identifier . substring ( , start ) ) ; } start ++ ; while ( true ) { int next = identifier . indexOf ( '' , start ) ; if ( next == start ) { } else if ( next < ) { break ; } else { results . add ( identifier . substring ( start , next ) ) ; } start = next + ; } results . add ( identifier . substring ( start ) ) ; return results ; } @ Override public < C , R > R accept ( C context , Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitSimpleName ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + identifier . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstSimpleName other = ( AstSimpleName ) obj ; if ( ! identifier . equals ( other . identifier ) ) { return false ; } return true ; } @ Override public String toString ( ) { return identifier ; } } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstGrouping extends AbstractAstNode { private final Region region ; public final List < AstSimpleName > properties ; public AstGrouping ( Region region , List < AstSimpleName > properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . properties = Lists . freeze ( properties ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitGrouping ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + properties . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstGrouping other = ( AstGrouping ) obj ; if ( ! properties . equals ( other . properties ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import com . asakusafw . dmdl . Region ; public class AstAttributeElement extends AbstractAstNode { private final Region region ; public final AstSimpleName name ; public final AstAttributeValue value ; public AstAttributeElement ( Region region , AstSimpleName name , AstAttributeValue value ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . name = name ; this . value = value ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitAttributeElement ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + name . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstAttributeElement other = ( AstAttributeElement ) obj ; if ( ! name . equals ( other . name ) ) { return false ; } if ( ! value . equals ( other . value ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstModelMapping extends AbstractAstNode { private final Region region ; public final List < AstPropertyMapping > properties ; public AstModelMapping ( Region region , List < AstPropertyMapping > properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . properties = Lists . freeze ( properties ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitModelMapping ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + properties . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstModelMapping other = ( AstModelMapping ) obj ; if ( ! properties . equals ( other . properties ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; public interface AstAttributeValue extends AstNode { } package com . asakusafw . dmdl . model ; import com . asakusafw . dmdl . Region ; public class AstJoin extends AbstractAstNode implements AstTerm < AstJoin > { private final Region region ; public final AstModelReference reference ; public final AstModelMapping mapping ; public final AstGrouping grouping ; public AstJoin ( Region region , AstModelReference reference , AstModelMapping mapping , AstGrouping grouping ) { if ( reference == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . reference = reference ; this . mapping = mapping ; this . grouping = grouping ; } @ Override public Region getRegion ( ) { return region ; } @ Override public AstJoin getUnit ( ) { return this ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitJoin ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + reference . hashCode ( ) ; result = prime * result + ( ( grouping == null ) ? : grouping . hashCode ( ) ) ; result = prime * result + ( ( mapping == null ) ? : mapping . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstJoin other = ( AstJoin ) obj ; if ( ! reference . equals ( other . reference ) ) { return false ; } if ( grouping == null ) { if ( other . grouping != null ) { return false ; } } else if ( ! grouping . equals ( other . grouping ) ) { return false ; } if ( mapping == null ) { if ( other . mapping != null ) { return false ; } } else if ( ! mapping . equals ( other . mapping ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import com . asakusafw . dmdl . Region ; public class AstModelReference extends AbstractAstNode implements AstRecord { private final Region region ; public final AstSimpleName name ; public AstModelReference ( Region region , AstSimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . name = name ; } @ Override public Region getRegion ( ) { return region ; } @ Override public AstRecord getUnit ( ) { return this ; } @ Override public < C , R > R accept ( C context , Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitModelReference ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + name . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstModelReference other = ( AstModelReference ) obj ; if ( ! name . equals ( other . name ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . text . MessageFormat ; import com . asakusafw . dmdl . Region ; public class AstDescription extends AbstractAstNode { private final Region region ; public final String token ; public AstDescription ( Region region , String token ) { if ( token == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . token = token ; } @ Override public Region getRegion ( ) { return region ; } public String getText ( ) { if ( token . length ( ) >= && token . startsWith ( "" ) && token . endsWith ( "" ) ) { return EscapeDecoder . scan ( token . substring ( , token . length ( ) - ) ) ; } throw new IllegalStateException ( MessageFormat . format ( "" , token ) ) ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitDescription ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + token . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstDescription other = ( AstDescription ) obj ; if ( ! token . equals ( other . token ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . util . List ; import com . asakusafw . dmdl . Region ; import com . asakusafw . utils . collections . Lists ; public class AstModelFolding extends AbstractAstNode { private final Region region ; public final List < AstPropertyFolding > properties ; public AstModelFolding ( Region region , List < AstPropertyFolding > properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . properties = Lists . freeze ( properties ) ; } @ Override public Region getRegion ( ) { return region ; } @ Override public < C , R > R accept ( C context , AstNode . Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitModelFolding ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + properties . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstModelFolding other = ( AstModelFolding ) obj ; if ( ! properties . equals ( other . properties ) ) { return false ; } return true ; } } package com . asakusafw . dmdl . model ; import java . util . LinkedList ; import com . asakusafw . dmdl . Region ; public class AstQualifiedName extends AbstractAstNode implements AstName { private final Region region ; public final AstName qualifier ; public final AstSimpleName simpleName ; public AstQualifiedName ( Region region , AstName qualifier , AstSimpleName simpleName ) { if ( qualifier == null ) { throw new IllegalArgumentException ( "" ) ; } if ( simpleName == null ) { throw new IllegalArgumentException ( "" ) ; } this . region = region ; this . qualifier = qualifier ; this . simpleName = simpleName ; } @ Override public Region getRegion ( ) { return region ; } @ Override public AstName getQualifier ( ) { return qualifier ; } @ Override public AstSimpleName getSimpleName ( ) { return simpleName ; } @ Override public < C , R > R accept ( C context , Visitor < C , R > visitor ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } R result = visitor . visitQualifiedName ( context , this ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + qualifier . hashCode ( ) ; result = prime * result + simpleName . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } AstQualifiedName other = ( AstQualifiedName ) obj ; if ( ! qualifier . equals ( other . qualifier ) ) { return false ; } if ( ! simpleName . equals ( other . simpleName ) ) { return false ; } return true ; } @ Override public String toString ( ) { LinkedList < AstSimpleName > names = new LinkedList < AstSimpleName > ( ) ; AstName current = this ; while ( current . getQualifier ( ) != null ) { names . addFirst ( current . getSimpleName ( ) ) ; current = current . getQualifier ( ) ; } assert current instanceof AstSimpleName ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( current . getSimpleName ( ) . identifier ) ; for ( AstSimpleName segment : names ) { buf . append ( '' ) ; buf . append ( segment . identifier ) ; } return buf . toString ( ) ; } } package com . asakusafw . dmdl ; import java . text . MessageFormat ; import com . asakusafw . dmdl . model . AstNode ; public class Diagnostic { public final Diagnostic . Level level ; public final String message ; public final Region region ; public Diagnostic ( Diagnostic . Level level , Region region , String message , Object ... arguments ) { if ( level == null ) { throw new IllegalArgumentException ( "" ) ; } if ( message == null ) { throw new IllegalArgumentException ( "" ) ; } this . level = level ; this . message = MessageFormat . format ( message , arguments ) ; this . region = region ; } public Diagnostic ( Diagnostic . Level level , AstNode node , String message , Object ... arguments ) { this ( level , node == null ? null : node . getRegion ( ) , message , arguments ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , level , region , message ) ; } public enum Level { INFO , WARN , ERROR , } } package com . asakusafw . dmdl . util ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . URL ; import java . net . URLClassLoader ; import java . nio . charset . Charset ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Locale ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . source . CompositeSourceRepository ; import com . asakusafw . dmdl . source . DmdlSourceDirectory ; import com . asakusafw . dmdl . source . DmdlSourceFile ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . utils . collections . Lists ; public final class CommandLineUtils { static final Logger LOG = LoggerFactory . getLogger ( CommandLineUtils . class ) ; public static Charset parseCharset ( String charsetNameOrNull ) { if ( charsetNameOrNull == null || charsetNameOrNull . isEmpty ( ) ) { return Charset . defaultCharset ( ) ; } return Charset . forName ( charsetNameOrNull ) ; } public static Locale parseLocale ( String localeNameOrNull ) { if ( localeNameOrNull == null || localeNameOrNull . isEmpty ( ) ) { return Locale . getDefault ( ) ; } String [ ] segments = localeNameOrNull . trim ( ) . split ( "" , ) ; if ( segments . length == || segments [ ] . isEmpty ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , localeNameOrNull ) ) ; } String language = segments [ ] ; String country = segments . length > ? segments [ ] : "" ; String variant = segments . length > ? segments [ ] : "" ; assert segments . length <= ; return new Locale ( language , country , variant ) ; } public static List < File > parseFileList ( String fileListOrNull ) { if ( fileListOrNull == null || fileListOrNull . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < File > results = Lists . create ( ) ; int start = ; while ( true ) { int index = fileListOrNull . indexOf ( File . pathSeparatorChar , start ) ; if ( index < ) { break ; } if ( start != index ) { results . add ( new File ( fileListOrNull . substring ( start , index ) . trim ( ) ) ) ; } start = index + ; } results . add ( new File ( fileListOrNull . substring ( start ) . trim ( ) ) ) ; return results ; } public static DmdlSourceRepository buildRepository ( List < File > files , Charset cs ) { if ( files == null ) { throw new IllegalArgumentException ( "" ) ; } if ( cs == null ) { throw new IllegalArgumentException ( "" ) ; } List < DmdlSourceRepository > repositories = Lists . create ( ) ; for ( File file : files ) { if ( file . isFile ( ) ) { repositories . add ( new DmdlSourceFile ( Collections . singletonList ( file ) , cs ) ) ; } else if ( file . isDirectory ( ) ) { repositories . add ( new DmdlSourceDirectory ( file , cs , Pattern . compile ( "" ) , Pattern . compile ( "" ) ) ) ; } else { LOG . warn ( "" , file ) ; } } if ( repositories . size ( ) == ) { return repositories . get ( ) ; } return new CompositeSourceRepository ( repositories ) ; } public static ClassLoader buildPluginLoader ( final ClassLoader parent , List < File > files ) { if ( files == null ) { throw new IllegalArgumentException ( "" ) ; } final List < URL > pluginLocations = Lists . create ( ) ; for ( File file : files ) { try { if ( file . exists ( ) == false ) { throw new FileNotFoundException ( file . getAbsolutePath ( ) ) ; } URL url = file . toURI ( ) . toURL ( ) ; pluginLocations . add ( url ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , file ) , e ) ; } } ClassLoader serviceLoader = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) { URLClassLoader loader = new URLClassLoader ( pluginLocations . toArray ( new URL [ pluginLocations . size ( ) ] ) , parent ) ; return loader ; } } ) ; return serviceLoader ; } private CommandLineUtils ( ) { return ; } } package com . asakusafw . dmdl . util ; import java . io . IOException ; import java . io . Reader ; import java . net . URI ; import java . text . MessageFormat ; import java . util . ServiceLoader ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . analyzer . DmdlAnalyzer ; import com . asakusafw . dmdl . analyzer . DmdlSemanticException ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstScript ; import com . asakusafw . dmdl . parser . DmdlParser ; import com . asakusafw . dmdl . parser . DmdlSyntaxException ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . dmdl . source . DmdlSourceRepository . Cursor ; import com . asakusafw . dmdl . spi . AttributeDriver ; import com . asakusafw . dmdl . spi . TypeDriver ; public class AnalyzeTask { static final Logger LOG = LoggerFactory . getLogger ( AnalyzeTask . class ) ; private final String processName ; private final ClassLoader serviceClassLoader ; public AnalyzeTask ( String processName , ClassLoader serviceClassLoader ) { if ( processName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . processName = processName ; this . serviceClassLoader = serviceClassLoader ; } public DmdlSemantics process ( DmdlSourceRepository repository ) throws IOException { if ( repository == null ) { throw new IllegalArgumentException ( "" ) ; } DmdlAnalyzer analyzer = parse ( repository ) ; try { LOG . info ( "" ) ; return analyzer . resolve ( ) ; } catch ( DmdlSemanticException e ) { LOG . error ( "" , e ) ; for ( Diagnostic diagnostic : e . getDiagnostics ( ) ) { switch ( diagnostic . level ) { case INFO : LOG . info ( "" , diagnostic . message , diagnostic . region ) ; break ; case WARN : LOG . warn ( "" , diagnostic . message , diagnostic . region ) ; break ; case ERROR : LOG . error ( "" , diagnostic . message , diagnostic . region ) ; break ; default : LOG . warn ( "" , diagnostic ) ; break ; } } throw new IOException ( MessageFormat . format ( "" , processName ) ) ; } } private DmdlAnalyzer parse ( DmdlSourceRepository source ) throws IOException { assert source != null ; boolean green = true ; DmdlParser parser = new DmdlParser ( ) ; DmdlAnalyzer analyzer = new DmdlAnalyzer ( ServiceLoader . load ( TypeDriver . class , serviceClassLoader ) , ServiceLoader . load ( AttributeDriver . class , serviceClassLoader ) ) ; int count = ; Cursor cursor = source . createCursor ( ) ; try { while ( cursor . next ( ) ) { URI name = cursor . getIdentifier ( ) ; LOG . info ( "" , name ) ; Reader resource = cursor . openResource ( ) ; try { AstScript script = parser . parse ( resource , name ) ; for ( AstModelDefinition < ? > model : script . models ) { LOG . info ( "" , model . name ) ; analyzer . addModel ( model ) ; count ++ ; } } catch ( DmdlSyntaxException e ) { LOG . error ( MessageFormat . format ( "" , name ) , e ) ; green = false ; } finally { resource . close ( ) ; } } LOG . info ( "" , count ) ; } finally { cursor . close ( ) ; } if ( green == false ) { throw new IOException ( MessageFormat . format ( "" , processName ) ) ; } if ( count == ) { throw new IOException ( "" ) ; } return analyzer ; } } package com . asakusafw . dmdl . util ; package com . asakusafw . dmdl . util ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . LiteralKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public final class AttributeUtil { public static Map < String , AstAttributeElement > getElementMap ( AstAttribute attribute ) { if ( attribute == null ) { throw new IllegalArgumentException ( "" ) ; } Map < String , AstAttributeElement > results = Maps . create ( ) ; for ( AstAttributeElement element : attribute . elements ) { results . put ( element . name . identifier , element ) ; } return results ; } public static List < Diagnostic > reportInvalidElements ( AstAttribute attribute , Collection < ? extends AstAttributeElement > elements ) { if ( attribute == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elements . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < Diagnostic > results = Lists . create ( ) ; for ( AstAttributeElement element : attribute . elements ) { results . add ( new Diagnostic ( Level . ERROR , element . name , "" , element . name , attribute . name ) ) ; } return results ; } public static String takeString ( DmdlSemantics environment , AstAttribute attribute , Map < String , AstAttributeElement > elements , String elementName , boolean mandatory ) { if ( environment == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attribute == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName == null ) { throw new IllegalArgumentException ( "" ) ; } AstAttributeElement target = elements . remove ( elementName ) ; if ( target == null ) { if ( mandatory ) { environment . report ( new Diagnostic ( Level . ERROR , attribute . name , "" , attribute . name . toString ( ) , elementName ) ) ; } return null ; } else if ( ( target . value instanceof AstLiteral ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , target , "" , attribute . name . toString ( ) , elementName ) ) ; return null ; } else { AstLiteral literal = ( AstLiteral ) target . value ; if ( literal . kind != LiteralKind . STRING ) { environment . report ( new Diagnostic ( Level . ERROR , target , "" , attribute . name . toString ( ) , elementName ) ) ; return null ; } return literal . toStringValue ( ) ; } } private AttributeUtil ( ) { return ; } } package com . asakusafw . dmdl ; package com . asakusafw . dmdl ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . text . MessageFormat ; import java . util . List ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Rule ; import org . junit . rules . TestName ; import com . asakusafw . dmdl . analyzer . DmdlAnalyzer ; import com . asakusafw . dmdl . analyzer . DmdlSemanticException ; import com . asakusafw . dmdl . analyzer . driver . BasicTypeDriver ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstScript ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . parser . DmdlParser ; import com . asakusafw . dmdl . parser . DmdlSyntaxException ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelSymbol ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . dmdl . spi . AttributeDriver ; import com . asakusafw . dmdl . spi . TypeDriver ; import com . asakusafw . utils . collections . Lists ; public abstract class DmdlTesterRoot { @ Rule public TestName currentTestName = new TestName ( ) ; protected final List < TypeDriver > typeDrivers = Lists . < TypeDriver > of ( new BasicTypeDriver ( ) ) ; protected final List < AttributeDriver > attributeDrivers = Lists . create ( ) ; protected Matcher < Type > type ( final BasicTypeKind kind ) { return new BaseMatcher < Type > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof BasicType ) { return ( ( BasicType ) object ) . getKind ( ) == kind ; } return false ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( kind . name ( ) ) ; } } ; } protected Matcher < ModelSymbol > model ( final String name ) { return new BaseMatcher < ModelSymbol > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof ModelSymbol ) { return ( ( ModelSymbol ) object ) . getName ( ) . identifier . equals ( name ) ; } return false ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( name ) ; } } ; } protected Matcher < PropertySymbol > property ( final String name ) { return new BaseMatcher < PropertySymbol > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof PropertySymbol ) { return ( ( PropertySymbol ) object ) . getName ( ) . identifier . equals ( name ) ; } return false ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( name ) ; } } ; } protected Matcher < PropertySymbol > property ( final String modelName , final String name ) { return new BaseMatcher < PropertySymbol > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof PropertySymbol ) { PropertySymbol property = ( PropertySymbol ) object ; return property . getName ( ) . identifier . equals ( name ) && property . getOwner ( ) . getName ( ) . identifier . equals ( modelName ) ; } return false ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( MessageFormat . format ( "" , modelName , name ) ) ; } } ; } protected DmdlSemantics resolve ( ) { try { return resolve0 ( ) ; } catch ( DmdlSemanticException e ) { throw new AssertionError ( e . getDiagnostics ( ) ) ; } } protected DmdlSemanticException shouldSemanticError ( ) { try { resolve0 ( ) ; throw new AssertionError ( "" ) ; } catch ( DmdlSemanticException e ) { return e ; } } protected DmdlSemantics resolve0 ( ) throws DmdlSemanticException { AstScript script = parse ( ) ; DmdlAnalyzer result = new DmdlAnalyzer ( typeDrivers , attributeDrivers ) ; for ( AstModelDefinition < ? > model : script . models ) { result . addModel ( model ) ; } DmdlSemantics resolved = result . resolve ( ) ; return resolved ; } protected AstScript parse ( ) { try { return parse0 ( ) ; } catch ( DmdlSyntaxException e ) { throw new AssertionError ( e ) ; } } protected DmdlSyntaxException shouldSyntaxError ( ) { try { parse0 ( ) ; throw new AssertionError ( "" ) ; } catch ( DmdlSyntaxException e ) { return e ; } } protected AstScript parse0 ( ) throws DmdlSyntaxException { return parse ( currentTestName . getMethodName ( ) ) ; } private AstScript parse ( String resource ) throws DmdlSyntaxException { try { String fileName = resource + "" ; URL url = getClass ( ) . getResource ( fileName ) ; assertThat ( fileName , url , is ( not ( nullValue ( ) ) ) ) ; URI uri ; try { uri = url . toURI ( ) ; } catch ( URISyntaxException e ) { uri = null ; } InputStream in = url . openStream ( ) ; try { Reader r = new InputStreamReader ( in , "" ) ; DmdlParser parser = new DmdlParser ( ) ; AstScript script = parser . parse ( r , uri ) ; return script ; } finally { in . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( ) ; } } } package com . asakusafw . dmdl . parser ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . PrintWriter ; import java . io . StringReader ; import java . io . StringWriter ; import java . util . LinkedList ; import java . util . List ; import org . junit . Test ; import com . asakusafw . dmdl . DmdlTesterRoot ; import com . asakusafw . dmdl . model . * ; import com . asakusafw . utils . collections . Lists ; public class DmdlParserTest extends DmdlTesterRoot { @ Test public void record_simple ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstRecord > record = getRecord ( script , "" ) ; assertThat ( record . description , is ( nullValue ( ) ) ) ; assertThat ( record . attributes . isEmpty ( ) , is ( true ) ) ; List < AstRecord > terms = extract ( record . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; AstRecord term = terms . get ( ) ; assertThat ( term , instanceOf ( AstRecordDefinition . class ) ) ; AstRecordDefinition def = ( AstRecordDefinition ) term ; assertThat ( def . properties . size ( ) , is ( ) ) ; AstPropertyDefinition pdef = def . properties . get ( ) ; assertThat ( pdef . description , is ( nullValue ( ) ) ) ; assertThat ( pdef . attributes . isEmpty ( ) , is ( true ) ) ; assertThat ( pdef . name . identifier , is ( "" ) ) ; assertThat ( pdef . type , is ( astType ( BasicTypeKind . INT ) ) ) ; } @ Test public void record_reference ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstRecord > record = getRecord ( script , "" ) ; List < AstRecord > terms = extract ( record . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; assertThat ( terms . get ( ) , instanceOf ( AstModelReference . class ) ) ; AstModelReference ref = ( AstModelReference ) terms . get ( ) ; assertThat ( ref . name . identifier , is ( "" ) ) ; } @ Test public void record_multi_reference ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstRecord > record = getRecord ( script , "" ) ; List < AstRecord > terms = extract ( record . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; assertThat ( terms . get ( ) , instanceOf ( AstModelReference . class ) ) ; assertThat ( terms . get ( ) , instanceOf ( AstModelReference . class ) ) ; assertThat ( terms . get ( ) , instanceOf ( AstModelReference . class ) ) ; AstModelReference a = ( AstModelReference ) terms . get ( ) ; AstModelReference b = ( AstModelReference ) terms . get ( ) ; AstModelReference c = ( AstModelReference ) terms . get ( ) ; assertThat ( a . name . identifier , is ( "" ) ) ; assertThat ( b . name . identifier , is ( "" ) ) ; assertThat ( c . name . identifier , is ( "" ) ) ; } @ Test public void record_mixed ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstRecord > record = getRecord ( script , "" ) ; List < AstRecord > terms = extract ( record . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; assertThat ( terms . get ( ) , instanceOf ( AstModelReference . class ) ) ; assertThat ( terms . get ( ) , instanceOf ( AstModelReference . class ) ) ; assertThat ( terms . get ( ) , instanceOf ( AstRecordDefinition . class ) ) ; AstModelReference a = ( AstModelReference ) terms . get ( ) ; AstModelReference b = ( AstModelReference ) terms . get ( ) ; AstRecordDefinition def = ( AstRecordDefinition ) terms . get ( ) ; assertThat ( a . name . identifier , is ( "" ) ) ; assertThat ( b . name . identifier , is ( "" ) ) ; assertThat ( def . properties . size ( ) , is ( ) ) ; assertThat ( def . properties . get ( ) . name . identifier , is ( "" ) ) ; } @ Test public void projective_simple ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstRecord > record = getProjection ( script , "" ) ; assertThat ( record . description , is ( nullValue ( ) ) ) ; assertThat ( record . attributes . isEmpty ( ) , is ( true ) ) ; List < AstRecord > terms = extract ( record . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; AstRecord term = terms . get ( ) ; assertThat ( term , instanceOf ( AstRecordDefinition . class ) ) ; AstRecordDefinition def = ( AstRecordDefinition ) term ; assertThat ( def . properties . size ( ) , is ( ) ) ; AstPropertyDefinition pdef = def . properties . get ( ) ; assertThat ( pdef . description , is ( nullValue ( ) ) ) ; assertThat ( pdef . attributes . isEmpty ( ) , is ( true ) ) ; assertThat ( pdef . name . identifier , is ( "" ) ) ; assertThat ( pdef . type , is ( astType ( BasicTypeKind . INT ) ) ) ; } @ Test public void join_simple ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstJoin > joined = getJoined ( script , "" ) ; List < AstJoin > terms = extract ( joined . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; AstJoin left = terms . get ( ) ; AstJoin right = terms . get ( ) ; assertThat ( left . reference . name . identifier , is ( "" ) ) ; assertThat ( left . mapping , is ( nullValue ( ) ) ) ; assertThat ( left . grouping , is ( nullValue ( ) ) ) ; assertThat ( right . reference . name . identifier , is ( "" ) ) ; assertThat ( right . mapping , is ( nullValue ( ) ) ) ; assertThat ( right . grouping , is ( nullValue ( ) ) ) ; } @ Test public void join_mapping ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstJoin > joined = getJoined ( script , "" ) ; List < AstJoin > terms = extract ( joined . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; AstJoin left = terms . get ( ) ; AstJoin right = terms . get ( ) ; assertThat ( left . reference . name . identifier , is ( "" ) ) ; assertThat ( left . mapping , not ( nullValue ( ) ) ) ; assertThat ( left . mapping . properties . size ( ) , is ( ) ) ; assertThat ( left . mapping . properties . get ( ) . source . identifier , is ( "" ) ) ; assertThat ( left . mapping . properties . get ( ) . target . identifier , is ( "" ) ) ; assertThat ( right . reference . name . identifier , is ( "" ) ) ; assertThat ( right . mapping , not ( nullValue ( ) ) ) ; assertThat ( right . mapping . properties . size ( ) , is ( ) ) ; assertThat ( right . mapping . properties . get ( ) . source . identifier , is ( "" ) ) ; assertThat ( right . mapping . properties . get ( ) . target . identifier , is ( "" ) ) ; assertThat ( right . mapping . properties . get ( ) . source . identifier , is ( "" ) ) ; assertThat ( right . mapping . properties . get ( ) . target . identifier , is ( "" ) ) ; } @ Test public void join_grouping ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstJoin > joined = getJoined ( script , "" ) ; List < AstJoin > terms = extract ( joined . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; AstJoin left = terms . get ( ) ; AstJoin right = terms . get ( ) ; assertThat ( left . reference . name . identifier , is ( "" ) ) ; assertThat ( left . grouping , not ( nullValue ( ) ) ) ; assertThat ( left . grouping . properties . size ( ) , is ( ) ) ; assertThat ( left . grouping . properties . get ( ) . identifier , is ( "" ) ) ; assertThat ( right . reference . name . identifier , is ( "" ) ) ; assertThat ( right . grouping , not ( nullValue ( ) ) ) ; assertThat ( right . grouping . properties . size ( ) , is ( ) ) ; assertThat ( right . grouping . properties . get ( ) . identifier , is ( "" ) ) ; assertThat ( right . grouping . properties . get ( ) . identifier , is ( "" ) ) ; assertThat ( right . grouping . properties . get ( ) . identifier , is ( "" ) ) ; } @ Test public void summarize_simple ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstSummarize > summarized = getSummarized ( script , "" ) ; List < AstSummarize > terms = extract ( summarized . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; AstSummarize term = terms . get ( ) ; assertThat ( term . reference . name . identifier , is ( "" ) ) ; assertThat ( term . folding . properties . size ( ) , is ( ) ) ; assertThat ( term . folding . properties . get ( ) . aggregator . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . source . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . target . toString ( ) , is ( "" ) ) ; assertThat ( term . grouping , is ( nullValue ( ) ) ) ; } @ Test public void summarize_multi_folding ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstSummarize > summarized = getSummarized ( script , "" ) ; List < AstSummarize > terms = extract ( summarized . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; AstSummarize term = terms . get ( ) ; assertThat ( term . reference . name . identifier , is ( "" ) ) ; assertThat ( term . folding . properties . size ( ) , is ( ) ) ; assertThat ( term . folding . properties . get ( ) . aggregator . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . source . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . target . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . aggregator . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . source . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . target . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . aggregator . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . source . toString ( ) , is ( "" ) ) ; assertThat ( term . folding . properties . get ( ) . target . toString ( ) , is ( "" ) ) ; assertThat ( term . grouping , is ( nullValue ( ) ) ) ; } @ Test public void summarize_grouping ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < AstSummarize > summarized = getSummarized ( script , "" ) ; List < AstSummarize > terms = extract ( summarized . expression ) ; assertThat ( terms . size ( ) , is ( ) ) ; AstSummarize term = terms . get ( ) ; assertThat ( term . reference . name . identifier , is ( "" ) ) ; assertThat ( term . folding . properties . size ( ) , is ( ) ) ; assertThat ( term . grouping , not ( nullValue ( ) ) ) ; assertThat ( term . grouping . properties . size ( ) , is ( ) ) ; assertThat ( term . grouping . properties . get ( ) . identifier , is ( "" ) ) ; } @ Test public void model_description ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < ? > model = script . models . get ( ) ; assertThat ( model . description , not ( nullValue ( ) ) ) ; assertThat ( model . description . token , is ( "" ) ) ; } @ Test public void model_attribute ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < ? > model = script . models . get ( ) ; assertThat ( model . attributes . size ( ) , is ( ) ) ; AstAttribute attribute = model . attributes . get ( ) ; assertThat ( attribute . name . toString ( ) , is ( "" ) ) ; assertThat ( attribute . elements . isEmpty ( ) , is ( true ) ) ; } @ Test public void model_multi_attribute ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , is ( ) ) ; AstModelDefinition < ? > model = script . models . get ( ) ; assertThat ( model . attributes . size ( ) , is ( ) ) ; assertThat ( model . attributes . get ( ) . name . toString ( ) , is ( "" ) ) ; assertThat ( model . attributes . get ( ) . name . toString ( ) , is ( "" ) ) ; assertThat ( model . attributes . get ( ) . name . toString ( ) , is ( "" ) ) ; } @ Test public void property_description ( ) { AstRecordDefinition def = loadFirstTermAs ( AstRecordDefinition . class ) ; assertThat ( def . properties . size ( ) , is ( ) ) ; AstPropertyDefinition prop = def . properties . get ( ) ; assertThat ( prop . description , not ( nullValue ( ) ) ) ; assertThat ( prop . description . token , is ( "" ) ) ; } @ Test public void property_attribute ( ) { AstRecordDefinition def = loadFirstTermAs ( AstRecordDefinition . class ) ; assertThat ( def . properties . size ( ) , is ( ) ) ; AstPropertyDefinition prop = def . properties . get ( ) ; assertThat ( prop . attributes . size ( ) , is ( ) ) ; AstAttribute attribute = prop . attributes . get ( ) ; assertThat ( attribute . name . toString ( ) , is ( "" ) ) ; assertThat ( attribute . elements . isEmpty ( ) , is ( true ) ) ; } @ Test public void property_multi_attribute ( ) { AstRecordDefinition def = loadFirstTermAs ( AstRecordDefinition . class ) ; assertThat ( def . properties . size ( ) , is ( ) ) ; AstPropertyDefinition prop = def . properties . get ( ) ; assertThat ( prop . attributes . size ( ) , is ( ) ) ; assertThat ( prop . attributes . get ( ) . name . toString ( ) , is ( "" ) ) ; assertThat ( prop . attributes . get ( ) . name . toString ( ) , is ( "" ) ) ; assertThat ( prop . attributes . get ( ) . name . toString ( ) , is ( "" ) ) ; } @ Test public void basic_type ( ) { AstRecordDefinition def = loadFirstTermAs ( AstRecordDefinition . class ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . INT ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . LONG ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . BYTE ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . SHORT ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . DECIMAL ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . FLOAT ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . DOUBLE ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . TEXT ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . BOOLEAN ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . DATE ) ) ) ; assertThat ( getProp ( def , "" ) . type , is ( astType ( BasicTypeKind . DATETIME ) ) ) ; } @ Test public void literals ( ) { AstAttribute attr = loadFirstAttribute ( ) ; assertThat ( getValue ( attr , "" ) , is ( value ( "" , LiteralKind . INTEGER ) ) ) ; assertThat ( getValue ( attr , "" ) , is ( value ( "" , LiteralKind . STRING ) ) ) ; assertThat ( getValue ( attr , "" ) , is ( value ( "" , LiteralKind . DECIMAL ) ) ) ; assertThat ( getValue ( attr , "" ) , is ( value ( "" , LiteralKind . BOOLEAN ) ) ) ; } @ Test public void qualified_name ( ) { AstAttribute attr = loadFirstAttribute ( ) ; assertThat ( attr . name . toString ( ) , is ( "" ) ) ; } @ Test public void array ( ) { AstAttribute attr = loadFirstAttribute ( ) ; AstAttributeValue value = getValue ( attr , "" ) ; assertThat ( value , instanceOf ( AstAttributeValueArray . class ) ) ; AstAttributeValueArray array = ( AstAttributeValueArray ) value ; assertThat ( array . elements . size ( ) , is ( ) ) ; assertThat ( array . elements . get ( ) , is ( value ( "" , LiteralKind . INTEGER ) ) ) ; assertThat ( array . elements . get ( ) , is ( value ( "" , LiteralKind . STRING ) ) ) ; assertThat ( array . elements . get ( ) , is ( value ( "" , LiteralKind . DECIMAL ) ) ) ; assertThat ( array . elements . get ( ) , is ( value ( "" , LiteralKind . BOOLEAN ) ) ) ; } @ Test public void value_qname ( ) { AstAttribute attr = loadFirstAttribute ( ) ; AstAttributeValue value = getValue ( attr , "" ) ; assertThat ( value , instanceOf ( AstQualifiedName . class ) ) ; AstQualifiedName name = ( AstQualifiedName ) value ; assertThat ( name . toString ( ) , is ( "" ) ) ; } @ Test public void special_names ( ) { load ( ) ; } @ Test public void invalid_record_nodelim ( ) { shouldSyntaxError ( ) ; } @ Test public void invalid_record_property_nodelim ( ) { shouldSyntaxError ( ) ; } @ Test public void invalid_record_property_type ( ) { shouldSyntaxError ( ) ; } private AstType astType ( BasicTypeKind kind ) { return new AstBasicType ( null , kind ) ; } private AstAttributeValue value ( String token , LiteralKind kind ) { return new AstLiteral ( null , token , kind ) ; } @ SuppressWarnings ( "" ) private < T extends AstTerm < T > > List < T > extract ( AstExpression < T > expression ) { List < T > results = Lists . create ( ) ; LinkedList < AstExpression < T > > work = new LinkedList < AstExpression < T > > ( ) ; work . add ( expression ) ; int count = ; while ( work . isEmpty ( ) == false ) { if ( count ++ > ) { throw new AssertionError ( work ) ; } AstExpression < T > first = work . removeFirst ( ) ; if ( first instanceof AstUnionExpression < ? > ) { AstUnionExpression < T > union = ( AstUnionExpression < T > ) first ; work . addAll ( , union . terms ) ; } else if ( first instanceof AstTerm < ? > ) { results . add ( ( T ) first ) ; } else { throw new AssertionError ( "" + first ) ; } } return results ; } private AstModelDefinition < AstRecord > getRecord ( AstScript script , String name ) { for ( AstModelDefinition < ? > def : script . models ) { if ( def . name . identifier . equals ( name ) ) { return def . asRecord ( ) ; } } throw new AssertionError ( name ) ; } private AstModelDefinition < AstRecord > getProjection ( AstScript script , String name ) { for ( AstModelDefinition < ? > def : script . models ) { if ( def . name . identifier . equals ( name ) ) { return def . asProjective ( ) ; } } throw new AssertionError ( name ) ; } private AstModelDefinition < AstJoin > getJoined ( AstScript script , String name ) { for ( AstModelDefinition < ? > def : script . models ) { if ( def . name . identifier . equals ( name ) ) { return def . asJoined ( ) ; } } throw new AssertionError ( name ) ; } private AstModelDefinition < AstSummarize > getSummarized ( AstScript script , String name ) { for ( AstModelDefinition < ? > def : script . models ) { if ( def . name . identifier . equals ( name ) ) { return def . asSummarized ( ) ; } } throw new AssertionError ( name ) ; } private AstPropertyDefinition getProp ( AstRecordDefinition record , String name ) { for ( AstPropertyDefinition prop : record . properties ) { if ( prop . name . identifier . equals ( name ) ) { return prop ; } } throw new AssertionError ( name ) ; } private AstAttributeValue getValue ( AstAttribute attr , String name ) { for ( AstAttributeElement elem : attr . elements ) { if ( elem . name . identifier . equals ( name ) ) { return elem . value ; } } throw new AssertionError ( name ) ; } private AstScript load ( ) { AstScript script = parse ( ) ; AstScript restored = restore ( script ) ; assertThat ( restored , equalTo ( script ) ) ; return script ; } private AstScript restore ( AstScript script ) { StringWriter output = new StringWriter ( ) ; PrintWriter writer = new PrintWriter ( output ) ; DmdlEmitter . emit ( script , writer ) ; writer . close ( ) ; System . out . println ( script . getRegion ( ) . sourceFile ) ; System . out . println ( output . toString ( ) ) ; DmdlParser parser = new DmdlParser ( ) ; try { return parser . parse ( new StringReader ( output . toString ( ) ) , null ) ; } catch ( DmdlSyntaxException e ) { throw new AssertionError ( e ) ; } } private < T extends AstTerm < ? > > T loadFirstTermAs ( Class < T > termKind ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , greaterThanOrEqualTo ( ) ) ; AstModelDefinition < ? > firstModel = script . models . get ( ) ; List < ? extends AstTerm < ? > > terms = extract ( firstModel . expression ) ; assertThat ( terms . size ( ) , greaterThanOrEqualTo ( ) ) ; AstTerm < ? > term = terms . get ( ) ; return termKind . cast ( term ) ; } private AstAttribute loadFirstAttribute ( ) { AstScript script = load ( ) ; assertThat ( script . models . size ( ) , greaterThanOrEqualTo ( ) ) ; AstModelDefinition < ? > firstModel = script . models . get ( ) ; assertThat ( firstModel . attributes . size ( ) , greaterThanOrEqualTo ( ) ) ; return firstModel . attributes . get ( ) ; } } package com . asakusafw . dmdl . analyzer ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . text . MessageFormat ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Test ; import com . asakusafw . dmdl . DmdlTesterRoot ; import com . asakusafw . dmdl . model . AstJoin ; import com . asakusafw . dmdl . model . AstSummarize ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . PropertyMappingKind ; import com . asakusafw . dmdl . semantics . trait . JoinTrait ; import com . asakusafw . dmdl . semantics . trait . MappingFactor ; import com . asakusafw . dmdl . semantics . trait . ProjectionsTrait ; import com . asakusafw . dmdl . semantics . trait . ReduceTerm ; import com . asakusafw . dmdl . semantics . trait . SummarizeTrait ; public class DmdlAnalyzerTest extends DmdlTesterRoot { @ Test public void simple ( ) { DmdlSemantics resolved = resolve ( ) ; ModelDeclaration simple = resolved . findModelDeclaration ( "" ) ; assertThat ( simple , not ( nullValue ( ) ) ) ; PropertyDeclaration property = simple . findPropertyDeclaration ( "" ) ; assertThat ( property , not ( nullValue ( ) ) ) ; assertThat ( property . getType ( ) , is ( type ( BasicTypeKind . INT ) ) ) ; } @ Test public void projections ( ) { DmdlSemantics resolved = resolve ( ) ; ModelDeclaration simple = resolved . findModelDeclaration ( "" ) ; assertThat ( simple , not ( nullValue ( ) ) ) ; PropertyDeclaration a = simple . findPropertyDeclaration ( "" ) ; assertThat ( a , not ( nullValue ( ) ) ) ; assertThat ( a . getType ( ) , is ( type ( BasicTypeKind . INT ) ) ) ; PropertyDeclaration b = simple . findPropertyDeclaration ( "" ) ; assertThat ( b , not ( nullValue ( ) ) ) ; assertThat ( b . getType ( ) , is ( type ( BasicTypeKind . LONG ) ) ) ; ProjectionsTrait trait = simple . getTrait ( ProjectionsTrait . class ) ; assertThat ( trait , not ( nullValue ( ) ) ) ; assertThat ( trait . getProjections ( ) , hasItem ( model ( "" ) ) ) ; assertThat ( trait . getProjections ( ) , hasItem ( model ( "" ) ) ) ; } @ Test public void join ( ) { DmdlSemantics resolved = resolve ( ) ; ModelDeclaration simple = resolved . findModelDeclaration ( "" ) ; assertThat ( simple , not ( nullValue ( ) ) ) ; PropertyDeclaration sid = simple . findPropertyDeclaration ( "" ) ; assertThat ( sid , not ( nullValue ( ) ) ) ; assertThat ( sid . getType ( ) , is ( type ( BasicTypeKind . LONG ) ) ) ; PropertyDeclaration aValue = simple . findPropertyDeclaration ( "" ) ; assertThat ( aValue , not ( nullValue ( ) ) ) ; assertThat ( aValue . getType ( ) , is ( type ( BasicTypeKind . TEXT ) ) ) ; PropertyDeclaration bValue = simple . findPropertyDeclaration ( "" ) ; assertThat ( bValue , not ( nullValue ( ) ) ) ; assertThat ( bValue . getType ( ) , is ( type ( BasicTypeKind . DATE ) ) ) ; JoinTrait trait = simple . getTrait ( JoinTrait . class ) ; assertThat ( trait , not ( nullValue ( ) ) ) ; assertThat ( trait . getTerms ( ) . size ( ) , is ( ) ) ; ReduceTerm < AstJoin > aTerm = trait . getTerms ( ) . get ( ) ; assertThat ( aTerm . getSource ( ) , is ( model ( "" ) ) ) ; assertThat ( aTerm . getGrouping ( ) , hasItem ( property ( "" ) ) ) ; assertThat ( aTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . ANY , "" , "" ) ) ) ; assertThat ( aTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . ANY , "" , "" ) ) ) ; ReduceTerm < AstJoin > bTerm = trait . getTerms ( ) . get ( ) ; assertThat ( bTerm . getSource ( ) , is ( model ( "" ) ) ) ; assertThat ( bTerm . getGrouping ( ) , hasItem ( property ( "" ) ) ) ; assertThat ( bTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . ANY , "" , "" ) ) ) ; assertThat ( bTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . ANY , "" , "" ) ) ) ; } @ Test public void summarize ( ) { DmdlSemantics resolved = resolve ( ) ; ModelDeclaration simple = resolved . findModelDeclaration ( "" ) ; assertThat ( simple , not ( nullValue ( ) ) ) ; PropertyDeclaration key = simple . findPropertyDeclaration ( "" ) ; assertThat ( key , not ( nullValue ( ) ) ) ; assertThat ( key . getType ( ) , is ( type ( BasicTypeKind . INT ) ) ) ; PropertyDeclaration sum = simple . findPropertyDeclaration ( "" ) ; assertThat ( sum , not ( nullValue ( ) ) ) ; assertThat ( sum . getType ( ) , is ( type ( BasicTypeKind . LONG ) ) ) ; PropertyDeclaration count = simple . findPropertyDeclaration ( "" ) ; assertThat ( count , not ( nullValue ( ) ) ) ; assertThat ( count . getType ( ) , is ( type ( BasicTypeKind . LONG ) ) ) ; PropertyDeclaration max = simple . findPropertyDeclaration ( "" ) ; assertThat ( max , not ( nullValue ( ) ) ) ; assertThat ( max . getType ( ) , is ( type ( BasicTypeKind . DATE ) ) ) ; PropertyDeclaration min = simple . findPropertyDeclaration ( "" ) ; assertThat ( min , not ( nullValue ( ) ) ) ; assertThat ( min . getType ( ) , is ( type ( BasicTypeKind . DATE ) ) ) ; SummarizeTrait trait = simple . getTrait ( SummarizeTrait . class ) ; assertThat ( trait , not ( nullValue ( ) ) ) ; assertThat ( trait . getTerms ( ) . size ( ) , is ( ) ) ; ReduceTerm < AstSummarize > aTerm = trait . getTerms ( ) . get ( ) ; assertThat ( aTerm . getSource ( ) , is ( model ( "" ) ) ) ; assertThat ( aTerm . getGrouping ( ) , hasItem ( property ( "" ) ) ) ; assertThat ( aTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . ANY , "" , "" ) ) ) ; assertThat ( aTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . SUM , "" , "" ) ) ) ; assertThat ( aTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . COUNT , "" , "" ) ) ) ; assertThat ( aTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . MAX , "" , "" ) ) ) ; assertThat ( aTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . MIN , "" , "" ) ) ) ; } @ Test public void summarize_whole ( ) { DmdlSemantics resolved = resolve ( ) ; ModelDeclaration counter = resolved . findModelDeclaration ( "" ) ; assertThat ( counter , not ( nullValue ( ) ) ) ; PropertyDeclaration count = counter . findPropertyDeclaration ( "" ) ; assertThat ( count , not ( nullValue ( ) ) ) ; assertThat ( count . getType ( ) , is ( type ( BasicTypeKind . LONG ) ) ) ; SummarizeTrait trait = counter . getTrait ( SummarizeTrait . class ) ; assertThat ( trait , not ( nullValue ( ) ) ) ; assertThat ( trait . getTerms ( ) . size ( ) , is ( ) ) ; ReduceTerm < AstSummarize > aTerm = trait . getTerms ( ) . get ( ) ; assertThat ( aTerm . getSource ( ) , is ( model ( "" ) ) ) ; assertThat ( aTerm . getGrouping ( ) . size ( ) , is ( ) ) ; assertThat ( aTerm . getMappings ( ) , hasItem ( mapping ( PropertyMappingKind . COUNT , "" , "" ) ) ) ; } @ Test public void invalid_duplicate_model ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_cyclic_dependencies ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_record ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_join ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_summarize ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_mapping ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_folding ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_grouping ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_duplicate_record_property ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_conflict_record_property ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_type ( ) { typeDrivers . clear ( ) ; shouldSemanticError ( ) ; } @ Test public void invalid_duplicate_mapping_property ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_conflict_mapping_property ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_inconsistent_group_count ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_inconsistent_group_type ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_inconsistent_group_type_unified ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_duplicate_folding_property ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_aggregator ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unbound_folding_type ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_unknown_attribute ( ) { shouldSemanticError ( ) ; } private Matcher < MappingFactor > mapping ( final PropertyMappingKind kind , final String source , final String target ) { return new BaseMatcher < MappingFactor > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof MappingFactor ) { MappingFactor factor = ( MappingFactor ) object ; return factor . getKind ( ) == kind && factor . getSource ( ) . getName ( ) . identifier . equals ( source ) && factor . getTarget ( ) . getName ( ) . identifier . equals ( target ) ; } return false ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( MessageFormat . format ( "" , kind . name ( ) . toLowerCase ( ) , source , target ) ) ; } } ; } } package com . asakusafw . dmdl . analyzer . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . DmdlTesterRoot ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . trait . NamespaceTrait ; public class NamespaceDriverTest extends DmdlTesterRoot { @ Before public void setUp ( ) throws Exception { attributeDrivers . add ( new NamespaceDriver ( ) ) ; } @ Test public void namespace ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; NamespaceTrait trait = model . getTrait ( NamespaceTrait . class ) ; assertThat ( trait , not ( nullValue ( ) ) ) ; assertThat ( trait . getNamespace ( ) . toString ( ) , is ( "" ) ) ; } @ Test public void empty ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; NamespaceTrait trait = model . getTrait ( NamespaceTrait . class ) ; assertThat ( trait , nullValue ( ) ) ; } @ Test public void invalid_namespace_property ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_namespace_empty ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_namespace_extra ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_namespace_string ( ) { shouldSemanticError ( ) ; } } package com . asakusafw . dmdl . analyzer . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Collections ; import java . util . List ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . DmdlTesterRoot ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . ModelSymbol ; import com . asakusafw . dmdl . semantics . trait . ProjectionsTrait ; public class AutoProjectionDriverTest extends DmdlTesterRoot { @ Before public void setUp ( ) throws Exception { attributeDrivers . add ( new AutoProjectionDriver ( ) ) ; } @ Test public void auto_projection ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; List < ModelSymbol > projections = projections ( model ) ; assertThat ( projections . size ( ) , is ( ) ) ; assertThat ( projections , hasItem ( model ( "" ) ) ) ; } @ Test public void auto_projection_subset ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; List < ModelSymbol > projections = projections ( model ) ; assertThat ( projections . size ( ) , is ( ) ) ; assertThat ( projections , hasItem ( model ( "" ) ) ) ; } @ Test public void auto_projection_superset ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; List < ModelSymbol > projections = projections ( model ) ; assertThat ( projections . size ( ) , is ( ) ) ; } @ Test public void auto_projection_incompatible ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; List < ModelSymbol > projections = projections ( model ) ; assertThat ( projections . size ( ) , is ( ) ) ; } @ Test public void auto_projection_record ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; List < ModelSymbol > projections = projections ( model ) ; assertThat ( projections . size ( ) , is ( ) ) ; } @ Test public void auto_projection_already ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; List < ModelSymbol > projections = projections ( model ) ; assertThat ( projections . size ( ) , is ( ) ) ; assertThat ( projections , hasItem ( model ( "" ) ) ) ; assertThat ( projections , hasItem ( model ( "" ) ) ) ; } @ Test public void auto_projection_summarize ( ) { DmdlSemantics world = resolve ( ) ; ModelDeclaration model = world . findModelDeclaration ( "" ) ; assertThat ( model . getSymbol ( ) , is ( model ( "" ) ) ) ; List < ModelSymbol > projections = projections ( model ) ; assertThat ( projections . size ( ) , is ( ) ) ; assertThat ( projections , hasItem ( model ( "" ) ) ) ; } @ Test public void invalid_auto_projection_property ( ) { shouldSemanticError ( ) ; } @ Test public void invalid_auto_projection_extra ( ) { shouldSemanticError ( ) ; } private List < ModelSymbol > projections ( ModelDeclaration model ) { ProjectionsTrait trait = model . getTrait ( ProjectionsTrait . class ) ; if ( trait == null ) { return Collections . emptyList ( ) ; } return trait . getProjections ( ) ; } } package com . asakusafw . dmdl . java ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . List ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . util . Emitter ; public class VolatileEmitter extends Emitter { private final List < VolatileJavaFile > emitted = Lists . create ( ) ; @ Override public PrintWriter openFor ( PackageDeclaration packageDeclOrNull , String subPath ) throws IOException { StringBuilder buf = new StringBuilder ( ) ; if ( packageDeclOrNull != null ) { buf . append ( packageDeclOrNull . getName ( ) . toNameString ( ) . replace ( '' , '' ) ) ; buf . append ( "" ) ; } assert subPath . endsWith ( "" ) ; buf . append ( subPath . substring ( , subPath . length ( ) - ) ) ; VolatileJavaFile file = new VolatileJavaFile ( buf . toString ( ) ) ; register ( file ) ; return new PrintWriter ( file . openWriter ( ) ) ; } private void register ( VolatileJavaFile file ) { emitted . add ( file ) ; } public List < VolatileJavaFile > getEmitted ( ) { return emitted ; } } package com . asakusafw . dmdl . java ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import java . util . TreeSet ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . dmdl . source . DmdlSourceRepository . Cursor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . util . Emitter ; public class MainTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void minimum ( ) throws Exception { File output = folder . newFolder ( "" ) ; File source = folder . newFile ( "" ) ; List < String > arguments = Lists . create ( ) ; Collections . addAll ( arguments , "" , output . getPath ( ) ) ; Collections . addAll ( arguments , "" , source . getPath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration config = Main . configure ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( config . getSource ( ) , is ( source ( "" ) ) ) ; assertThat ( config . getOutput ( ) , is ( target ( output ) ) ) ; assertThat ( config . getBasePackage ( ) . toNameString ( ) , is ( "" ) ) ; } @ Test public void source_directory ( ) throws Exception { File output = folder . newFolder ( "" ) ; File source = folder . newFolder ( "" ) ; new File ( source , "" ) . createNewFile ( ) ; new File ( source , "" ) . createNewFile ( ) ; List < String > arguments = Lists . create ( ) ; Collections . addAll ( arguments , "" , output . getPath ( ) ) ; Collections . addAll ( arguments , "" , source . getPath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration config = Main . configure ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( config . getSource ( ) , is ( source ( "" , "" ) ) ) ; } @ Test public void multi_source ( ) throws Exception { File output = folder . newFolder ( "" ) ; File source1 = folder . newFolder ( "" ) ; new File ( source1 , "" ) . createNewFile ( ) ; new File ( source1 , "" ) . createNewFile ( ) ; File source2 = folder . newFile ( "" ) ; List < String > arguments = Lists . create ( ) ; Collections . addAll ( arguments , "" , output . getPath ( ) ) ; Collections . addAll ( arguments , "" , source1 . getPath ( ) + File . pathSeparatorChar + source2 . getPath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration config = Main . configure ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( config . getSource ( ) , is ( source ( "" , "" , "" ) ) ) ; } private Matcher < DmdlSourceRepository > source ( String ... fileNames ) { final Set < String > files = new TreeSet < String > ( ) ; Collections . addAll ( files , fileNames ) ; return new BaseMatcher < DmdlSourceRepository > ( ) { @ Override public boolean matches ( Object target ) { if ( ( target instanceof DmdlSourceRepository ) == false ) { return false ; } Set < String > saw = new TreeSet < String > ( ) ; try { DmdlSourceRepository repo = ( DmdlSourceRepository ) target ; Cursor cursor = repo . createCursor ( ) ; try { while ( cursor . next ( ) ) { String path = cursor . getIdentifier ( ) . getRawPath ( ) ; if ( path . endsWith ( "" ) ) { path = path . substring ( , path . length ( ) - ) ; } String file = path . substring ( path . lastIndexOf ( '' ) + ) ; saw . add ( file ) ; } } finally { cursor . close ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; return false ; } return saw . equals ( files ) ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( files . toString ( ) ) ; } } ; } private Matcher < Emitter > target ( final File output ) { return new BaseMatcher < Emitter > ( ) { @ Override public boolean matches ( Object target ) { if ( ( target instanceof Emitter ) == false ) { return false ; } Emitter emitter = ( Emitter ) target ; try { PrintWriter writer = emitter . openFor ( null , "" ) ; try { writer . println ( "" ) ; } finally { writer . close ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; return false ; } return new File ( output , "" ) . isFile ( ) ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( output . getPath ( ) ) ; } } ; } } package com . asakusafw . dmdl . java . emitter ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; public class HelloDriver extends JavaDataModelDriver { @ Override public List < MethodDeclaration > getMethods ( EmitContext context , ModelDeclaration model ) { ModelFactory f = context . getModelFactory ( ) ; return Collections . singletonList ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , context . resolve ( String . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( new ExpressionBuilder ( f , Models . toLiteral ( f , "" ) ) . toReturnStatement ( ) ) ) ) ; } } package com . asakusafw . dmdl . java . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . Type ; public class CompositeDataModelDriverTest extends GeneratorTesterRoot { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void empty ( ) { emitDrivers . add ( new CompositeDataModelDriver ( Collections . < JavaDataModelDriver > emptyList ( ) ) ) ; generate ( "" ) ; } @ Test public void single ( ) { TrackingDriver driver = new TrackingDriver ( ) ; emitDrivers . add ( new CompositeDataModelDriver ( Arrays . asList ( driver ) ) ) ; generate ( "" ) ; assertThat ( driver . interfaces , hasItem ( "" ) ) ; assertThat ( driver . methods , hasItem ( "" ) ) ; assertThat ( driver . typeAnnotations , hasItem ( "" ) ) ; assertThat ( driver . propertyAnnotations , hasItem ( "" ) ) ; } @ Test public void multi ( ) { TrackingDriver [ ] drivers = new TrackingDriver [ ] { new TrackingDriver ( ) , new TrackingDriver ( ) , new TrackingDriver ( ) , } ; emitDrivers . add ( new CompositeDataModelDriver ( Arrays . asList ( drivers ) ) ) ; generate ( "" ) ; for ( TrackingDriver driver : drivers ) { assertThat ( driver . interfaces , hasItem ( "" ) ) ; assertThat ( driver . methods , hasItem ( "" ) ) ; assertThat ( driver . typeAnnotations , hasItem ( "" ) ) ; assertThat ( driver . propertyAnnotations , hasItem ( "" ) ) ; } } @ Test public void load_spi ( ) { ClassLoader serviceClassLoader ; try { File services = new File ( folder . getRoot ( ) , "" ) ; Assume . assumeTrue ( services . mkdirs ( ) ) ; File spi = new File ( services , JavaDataModelDriver . class . getName ( ) ) ; PrintWriter output = new PrintWriter ( spi , "" ) ; try { output . println ( HelloDriver . class . getName ( ) ) ; } finally { output . close ( ) ; } serviceClassLoader = new URLClassLoader ( new URL [ ] { folder . getRoot ( ) . toURI ( ) . toURL ( ) } ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; Assume . assumeNoException ( e ) ; throw new AssertionError ( ) ; } emitDrivers . add ( new CompositeDataModelDriver ( serviceClassLoader ) ) ; ModelLoader loader = generate ( "" ) ; ModelWrapper object = loader . newModel ( "" ) ; assertThat ( object . invoke ( "" ) , is ( ( Object ) "" ) ) ; } static class TrackingDriver extends JavaDataModelDriver { final Set < String > interfaces = Sets . create ( ) ; final Set < String > methods = Sets . create ( ) ; final Set < String > typeAnnotations = Sets . create ( ) ; final Set < String > propertyAnnotations = Sets . create ( ) ; @ Override public List < Type > getInterfaces ( EmitContext context , ModelDeclaration model ) { interfaces . add ( model . getName ( ) . identifier ) ; return Collections . emptyList ( ) ; } @ Override public List < MethodDeclaration > getMethods ( EmitContext context , ModelDeclaration model ) { methods . add ( model . getName ( ) . identifier ) ; return Collections . emptyList ( ) ; } @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) { typeAnnotations . add ( model . getName ( ) . identifier ) ; return Collections . emptyList ( ) ; } @ Override public List < Annotation > getMemberAnnotations ( EmitContext context , PropertyDeclaration property ) { propertyAnnotations . add ( property . getName ( ) . identifier ) ; return Collections . emptyList ( ) ; } } } package com . asakusafw . dmdl . java . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . io . Text ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; import com . asakusafw . dmdl . java . emitter . driver . ProjectionDriver ; public class ProjectiveModelEmitterTest extends GeneratorTesterRoot { @ Test public void projection ( ) { emitDrivers . add ( new ProjectionDriver ( ) ) ; ModelLoader loader = generate ( ) ; Class < ? > projection = loader . modelType ( "" ) ; ModelWrapper object = loader . newModel ( "" ) ; assertThat ( object . unwrap ( ) , instanceOf ( projection ) ) ; object . setInterfaceType ( projection ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , is ( ( Object ) ) ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , is ( ( Object ) new Text ( "" ) ) ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . io . Text ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; public class ObjectDriverTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new ObjectDriver ( ) ) ; } @ Test public void simple_record ( ) { ModelLoader loader = generate ( ) ; ModelWrapper a = loader . newModel ( "" ) ; ModelWrapper b = loader . newModel ( "" ) ; a . set ( "" , ) ; assertThat ( a . unwrap ( ) . equals ( b . unwrap ( ) ) , is ( false ) ) ; b . copyFrom ( a ) ; assertThat ( a . unwrap ( ) . hashCode ( ) , is ( b . unwrap ( ) . hashCode ( ) ) ) ; assertThat ( a . unwrap ( ) . equals ( b . unwrap ( ) ) , is ( true ) ) ; assertThat ( a . unwrap ( ) . toString ( ) , is ( b . unwrap ( ) . toString ( ) ) ) ; b . set ( "" , new Text ( "" ) ) ; assertThat ( a . unwrap ( ) . equals ( b . unwrap ( ) ) , is ( false ) ) ; } @ Test public void simple_projection ( ) { generate ( ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . io . Text ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; public class StringPropertyDriverTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new StringPropertyDriver ( ) ) ; } @ Test public void simple_record ( ) { ModelLoader loader = generate ( ) ; ModelWrapper a = loader . newModel ( "" ) ; a . invoke ( "" , "" ) ; assertThat ( a . get ( "" ) , is ( ( Object ) new Text ( "" ) ) ) ; assertThat ( a . invoke ( "" ) , is ( ( Object ) "" ) ) ; } @ Test public void string_projection ( ) { emitDrivers . add ( new ProjectionDriver ( ) ) ; ModelLoader loader = generate ( ) ; ModelWrapper a = loader . newModel ( "" ) ; a . setInterfaceType ( loader . modelType ( "" ) ) ; a . invoke ( "" , "" ) ; assertThat ( a . get ( "" ) , is ( ( Object ) new Text ( "" ) ) ) ; assertThat ( a . invoke ( "" ) , is ( ( Object ) "" ) ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . math . BigDecimal ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class WritableDriverTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new WritableDriver ( ) ) ; emitDrivers . add ( new ObjectDriver ( ) ) ; } @ Test public void primitives ( ) throws Exception { ModelLoader loader = generate ( ) ; ModelWrapper object = loader . newModel ( "" ) ; assertThat ( object . unwrap ( ) , instanceOf ( Writable . class ) ) ; object . set ( "" , true ) ; object . set ( "" , ( byte ) ) ; object . set ( "" , ( short ) ) ; object . set ( "" , ) ; object . set ( "" , ) ; object . set ( "" , ) ; object . set ( "" , ) ; object . set ( "" , new BigDecimal ( "" ) ) ; object . set ( "" , new Text ( "" ) ) ; object . set ( "" , new Date ( , , ) ) ; object . set ( "" , new DateTime ( , , , , , ) ) ; Writable writable = ( Writable ) object . unwrap ( ) ; DataOutputBuffer output = new DataOutputBuffer ( ) ; writable . write ( output ) ; Writable copy = ( Writable ) loader . newModel ( "" ) . unwrap ( ) ; DataInputBuffer input = new DataInputBuffer ( ) ; input . reset ( output . getData ( ) , output . getLength ( ) ) ; copy . readFields ( input ) ; assertThat ( input . read ( ) , is ( - ) ) ; assertThat ( writable , equalTo ( copy ) ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; import com . asakusafw . runtime . model . PropertyOrder ; public class PropertyOrderDriverTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new PropertyOrderDriver ( ) ) ; } @ Test public void single_property ( ) throws Exception { ModelLoader loader = generate ( ) ; Class < ? > modelClass = loader . modelType ( "" ) ; PropertyOrder annotation = modelClass . getAnnotation ( PropertyOrder . class ) ; assertThat ( annotation , is ( notNullValue ( ) ) ) ; assertThat ( annotation . value ( ) , is ( new String [ ] { "" } ) ) ; } @ Test public void many_properties ( ) throws Exception { ModelLoader loader = generate ( ) ; Class < ? > modelClass = loader . modelType ( "" ) ; PropertyOrder annotation = modelClass . getAnnotation ( PropertyOrder . class ) ; assertThat ( annotation , is ( notNullValue ( ) ) ) ; assertThat ( annotation . value ( ) , is ( new String [ ] { "" , "" , "" , "" , } ) ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . hamcrest . Matcher ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; public class ProjectionDriverTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new ProjectionDriver ( ) ) ; } @ Test public void projection ( ) { ModelLoader loader = generate ( ) ; Class < ? > a = loader . modelType ( "" ) ; Class < ? > b = loader . modelType ( "" ) ; Class < ? > c = loader . modelType ( "" ) ; Class < ? > d = loader . modelType ( "" ) ; assertThat ( a . getInterfaces ( ) , not ( includes ( b ) ) ) ; assertThat ( a . getInterfaces ( ) , not ( includes ( c ) ) ) ; assertThat ( a . getInterfaces ( ) , not ( includes ( d ) ) ) ; assertThat ( b . getInterfaces ( ) , includes ( a ) ) ; assertThat ( b . getInterfaces ( ) , not ( includes ( c ) ) ) ; assertThat ( b . getInterfaces ( ) , not ( includes ( d ) ) ) ; assertThat ( c . getInterfaces ( ) , not ( includes ( a ) ) ) ; assertThat ( c . getInterfaces ( ) , not ( includes ( b ) ) ) ; assertThat ( c . getInterfaces ( ) , not ( includes ( d ) ) ) ; assertThat ( d . getInterfaces ( ) , not ( includes ( a ) ) ) ; assertThat ( d . getInterfaces ( ) , includes ( b ) ) ; assertThat ( d . getInterfaces ( ) , includes ( c ) ) ; } private Matcher < Object [ ] > includes ( Object object ) { return hasItemInArray ( object ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; public class JoinDriverTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new JoinDriver ( ) ) ; } @ Test public void simple_join ( ) { ModelLoader loader = generate ( ) ; Joined annotation = loader . modelType ( "" ) . getAnnotation ( Joined . class ) ; assertThat ( annotation , not ( nullValue ( ) ) ) ; assertThat ( annotation . terms ( ) . length , is ( ) ) ; Joined . Term a = annotation . terms ( ) [ ] ; assertThat ( a . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( a . mappings ( ) . length , is ( ) ) ; assertThat ( a . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( a . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( a . shuffle ( ) , is ( grouping ( "" ) ) ) ; Joined . Term b = annotation . terms ( ) [ ] ; assertThat ( b . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( b . mappings ( ) . length , is ( ) ) ; assertThat ( b . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( b . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( b . shuffle ( ) , is ( grouping ( "" ) ) ) ; } @ Test public void join_rename_key ( ) { ModelLoader loader = generate ( ) ; Joined annotation = loader . modelType ( "" ) . getAnnotation ( Joined . class ) ; assertThat ( annotation , not ( nullValue ( ) ) ) ; assertThat ( annotation . terms ( ) . length , is ( ) ) ; Joined . Term a = annotation . terms ( ) [ ] ; assertThat ( a . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( a . mappings ( ) . length , is ( ) ) ; assertThat ( a . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( a . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( a . shuffle ( ) , is ( grouping ( "" ) ) ) ; Joined . Term b = annotation . terms ( ) [ ] ; assertThat ( b . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( b . mappings ( ) . length , is ( ) ) ; assertThat ( b . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( b . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( b . shuffle ( ) , is ( grouping ( "" ) ) ) ; } @ Test public void simple_record ( ) { ModelLoader loader = generate ( ) ; Joined annotation = loader . modelType ( "" ) . getAnnotation ( Joined . class ) ; assertThat ( annotation , nullValue ( ) ) ; } private Matcher < Key > grouping ( final String ... properties ) { return new BaseMatcher < Key > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Key ) { Key elem = ( Key ) object ; if ( Arrays . equals ( elem . group ( ) , properties ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( Arrays . toString ( properties ) ) ; } } ; } private Matcher < Joined . Mapping > mapping ( final String src , final String dst ) { return new BaseMatcher < Joined . Mapping > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Joined . Mapping ) { Joined . Mapping elem = ( Joined . Mapping ) object ; if ( src . equals ( elem . source ( ) ) == false ) { return false ; } if ( dst . equals ( elem . destination ( ) ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( src + "" + dst ) ; } } ; } private Matcher < Object > eq ( Object object ) { return is ( object ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import static com . asakusafw . vocabulary . model . Summarized . Aggregator . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; import com . asakusafw . vocabulary . model . Summarized . Aggregator ; import com . asakusafw . vocabulary . model . Summarized . Term ; public class SummarizeDriverTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new SummarizeDriver ( ) ) ; } @ Test public void simple_summarize ( ) { ModelLoader loader = generate ( ) ; Summarized annotation = loader . modelType ( "" ) . getAnnotation ( Summarized . class ) ; assertThat ( annotation , not ( nullValue ( ) ) ) ; Term term = annotation . term ( ) ; assertThat ( term . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( term . foldings ( ) . length , is ( ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( ANY , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( SUM , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( COUNT , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( MAX , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( MIN , "" , "" ) ) ) ; assertThat ( term . shuffle ( ) , is ( grouping ( "" ) ) ) ; } @ Test public void simple_record ( ) { ModelLoader loader = generate ( ) ; Summarized annotation = loader . modelType ( "" ) . getAnnotation ( Summarized . class ) ; assertThat ( annotation , nullValue ( ) ) ; } private Matcher < Key > grouping ( final String ... properties ) { return new BaseMatcher < Key > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Key ) { Key elem = ( Key ) object ; if ( Arrays . equals ( elem . group ( ) , properties ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( Arrays . toString ( properties ) ) ; } } ; } private Matcher < Summarized . Folding > mapping ( final Aggregator aggregator , final String src , final String dst ) { return new BaseMatcher < Summarized . Folding > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Summarized . Folding ) { Summarized . Folding elem = ( Summarized . Folding ) object ; if ( aggregator != elem . aggregator ( ) ) { return false ; } if ( src . equals ( elem . source ( ) ) == false ) { return false ; } if ( dst . equals ( elem . destination ( ) ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( aggregator + "" + src + "" + dst ) ; } } ; } private Matcher < Object > eq ( Object object ) { return is ( object ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . math . BigDecimal ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Text ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . runtime . io . TsvEmitter ; import com . asakusafw . runtime . io . TsvParser ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class ModelInputDriverTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new ModelInputDriver ( ) ) ; emitDrivers . add ( new ModelOutputDriver ( ) ) ; emitDrivers . add ( new ObjectDriver ( ) ) ; } @ SuppressWarnings ( "" ) @ Test public void simple_record ( ) throws Exception { ModelLoader loader = generate ( ) ; Class < ? > type = loader . modelType ( "" ) ; assertThat ( type . isAnnotationPresent ( ModelInputLocation . class ) , is ( true ) ) ; assertThat ( type . isAnnotationPresent ( ModelOutputLocation . class ) , is ( true ) ) ; ModelWrapper object = loader . newModel ( "" ) ; DataOutputBuffer output = new DataOutputBuffer ( ) ; ModelOutput < Object > modelOut = ( ModelOutput < Object > ) type . getAnnotation ( ModelOutputLocation . class ) . value ( ) . getDeclaredConstructor ( RecordEmitter . class ) . newInstance ( new TsvEmitter ( new OutputStreamWriter ( output , "" ) ) ) ; object . set ( "" , ) ; object . set ( "" , new Text ( "" ) ) ; modelOut . write ( object . unwrap ( ) ) ; object . set ( "" , ) ; object . set ( "" , new Text ( "" ) ) ; modelOut . write ( object . unwrap ( ) ) ; object . set ( "" , ) ; object . set ( "" , null ) ; modelOut . write ( object . unwrap ( ) ) ; modelOut . close ( ) ; DataInputBuffer input = new DataInputBuffer ( ) ; input . reset ( output . getData ( ) , output . getLength ( ) ) ; ModelInput < Object > modelIn = ( ModelInput < Object > ) type . getAnnotation ( ModelInputLocation . class ) . value ( ) . getDeclaredConstructor ( RecordParser . class ) . newInstance ( new TsvParser ( new InputStreamReader ( input , "" ) ) ) ; ModelWrapper copy = loader . newModel ( "" ) ; modelIn . readTo ( copy . unwrap ( ) ) ; assertThat ( copy . get ( "" ) , is ( ( Object ) ) ) ; assertThat ( copy . get ( "" ) , is ( ( Object ) new Text ( "" ) ) ) ; modelIn . readTo ( copy . unwrap ( ) ) ; assertThat ( copy . get ( "" ) , is ( ( Object ) ) ) ; assertThat ( copy . get ( "" ) , is ( ( Object ) new Text ( "" ) ) ) ; modelIn . readTo ( copy . unwrap ( ) ) ; assertThat ( copy . get ( "" ) , is ( ( Object ) ) ) ; assertThat ( copy . getOption ( "" ) . isNull ( ) , is ( true ) ) ; assertThat ( input . read ( ) , is ( - ) ) ; modelIn . close ( ) ; } @ SuppressWarnings ( "" ) @ Test public void primitives ( ) throws Exception { ModelLoader loader = generate ( ) ; Class < ? > type = loader . modelType ( "" ) ; assertThat ( type . isAnnotationPresent ( ModelInputLocation . class ) , is ( true ) ) ; assertThat ( type . isAnnotationPresent ( ModelOutputLocation . class ) , is ( true ) ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , true ) ; object . set ( "" , ( byte ) ) ; object . set ( "" , ( short ) ) ; object . set ( "" , ) ; object . set ( "" , ) ; object . set ( "" , ) ; object . set ( "" , ) ; object . set ( "" , new BigDecimal ( "" ) ) ; object . set ( "" , new Text ( "" ) ) ; object . set ( "" , new Date ( , , ) ) ; object . set ( "" , new DateTime ( , , , , , ) ) ; DataOutputBuffer output = new DataOutputBuffer ( ) ; ModelOutput < Object > modelOut = ( ModelOutput < Object > ) type . getAnnotation ( ModelOutputLocation . class ) . value ( ) . getDeclaredConstructor ( RecordEmitter . class ) . newInstance ( new TsvEmitter ( new OutputStreamWriter ( output , "" ) ) ) ; modelOut . write ( object . unwrap ( ) ) ; modelOut . write ( object . unwrap ( ) ) ; modelOut . write ( object . unwrap ( ) ) ; modelOut . close ( ) ; DataInputBuffer input = new DataInputBuffer ( ) ; input . reset ( output . getData ( ) , output . getLength ( ) ) ; ModelInput < Object > modelIn = ( ModelInput < Object > ) type . getAnnotation ( ModelInputLocation . class ) . value ( ) . getDeclaredConstructor ( RecordParser . class ) . newInstance ( new TsvParser ( new InputStreamReader ( input , "" ) ) ) ; ModelWrapper copy = loader . newModel ( "" ) ; modelIn . readTo ( copy . unwrap ( ) ) ; assertThat ( object . unwrap ( ) , equalTo ( copy . unwrap ( ) ) ) ; assertThat ( input . read ( ) , is ( - ) ) ; modelIn . close ( ) ; } } package com . asakusafw . dmdl . java . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . math . BigDecimal ; import org . apache . hadoop . io . Text ; import org . hamcrest . Matcher ; import org . junit . Test ; import com . asakusafw . dmdl . java . GeneratorTesterRoot ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . IntOption ; public class ConcreteModelEmitterTest extends GeneratorTesterRoot { @ Test public void simple ( ) { ModelLoader loader = generate ( ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; assertThat ( object . getOption ( "" ) , eq ( new IntOption ( ) ) ) ; object . setOption ( "" , new IntOption ( ) ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; ModelWrapper copy = loader . newModel ( "" ) ; copy . copyFrom ( object ) ; object . reset ( ) ; assertThat ( object . getOption ( "" ) . isNull ( ) , eq ( true ) ) ; assertThat ( copy . get ( "" ) , eq ( ) ) ; } @ Test public void primitives ( ) { ModelLoader loader = generate ( ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , true ) ; assertThat ( object . is ( "" ) , eq ( true ) ) ; object . set ( "" , ( byte ) ) ; assertThat ( object . get ( "" ) , eq ( ( byte ) ) ) ; object . set ( "" , ( short ) ) ; assertThat ( object . get ( "" ) , eq ( ( short ) ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , new BigDecimal ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new BigDecimal ( "" ) ) ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; object . set ( "" , new Date ( , , ) ) ; assertThat ( object . get ( "" ) , eq ( new Date ( , , ) ) ) ; object . set ( "" , new DateTime ( , , , , , ) ) ; assertThat ( object . get ( "" ) , eq ( new DateTime ( , , , , , ) ) ) ; } @ Test public void namespace ( ) { ModelLoader loader = generate ( ) ; loader . setNamespace ( "" ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; } @ Test public void namespace_complex ( ) { ModelLoader loader = generate ( ) ; loader . setNamespace ( "" ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; } private Matcher < Object > eq ( final Object value ) { return is ( value ) ; } } package com . asakusafw . dmdl . java ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . lang . reflect . Method ; import java . net . URL ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Locale ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . junit . After ; import org . junit . Rule ; import org . junit . rules . TestName ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . java . emitter . NameConstants ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . java . util . JavaName ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . dmdl . source . DmdlSourceResource ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; public class GeneratorTesterRoot { @ Rule public TestName currentTestName = new TestName ( ) ; protected final VolatileCompiler compiler = new VolatileCompiler ( ) ; protected final List < JavaDataModelDriver > emitDrivers = Lists . create ( ) ; @ After public void tearDown ( ) throws Exception { compiler . close ( ) ; } protected ModelLoader generate ( ) { return generate ( currentTestName . getMethodName ( ) ) ; } protected ModelLoader generate ( String name ) { List < VolatileJavaFile > files = emit ( name ) ; ClassLoader loaded = compile ( files ) ; return new ModelLoader ( loaded ) ; } private ClassLoader compile ( List < VolatileJavaFile > files ) { if ( files . isEmpty ( ) ) { throw new AssertionError ( ) ; } for ( JavaFileObject java : files ) { try { System . out . println ( "" + java . getName ( ) ) ; System . out . println ( java . getCharContent ( true ) ) ; System . out . println ( ) ; System . out . println ( ) ; } catch ( IOException e ) { } compiler . addSource ( java ) ; } compiler . addArguments ( "" ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; boolean hasWrong = false ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) == Diagnostic . Kind . ERROR || d . getKind ( ) == Diagnostic . Kind . WARNING ) { System . out . println ( "" ) ; System . out . println ( d . getMessage ( Locale . getDefault ( ) ) ) ; hasWrong = true ; } } if ( hasWrong ) { throw new AssertionError ( diagnostics ) ; } return compiler . getClassLoader ( ) ; } private List < VolatileJavaFile > emit ( String name ) { ModelFactory factory = Models . getModelFactory ( ) ; DmdlSourceRepository source = collectInput ( name ) ; VolatileEmitter emitter = new VolatileEmitter ( ) ; Configuration conf = new Configuration ( factory , source , Models . toName ( factory , "" ) , emitter , getClass ( ) . getClassLoader ( ) , Locale . getDefault ( ) ) ; GenerateTask task = new GenerateTask ( conf ) ; try { task . process ( new CompositeDataModelDriver ( emitDrivers ) ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } return emitter . getEmitted ( ) ; } private DmdlSourceRepository collectInput ( String name ) { URL url = getClass ( ) . getResource ( name + "" ) ; assertThat ( currentTestName . getMethodName ( ) , url , not ( nullValue ( ) ) ) ; return new DmdlSourceResource ( Collections . singletonList ( url ) , Charset . forName ( "" ) ) ; } protected static class ModelLoader { private final ClassLoader classLoader ; private String namespace ; ModelLoader ( ClassLoader loaded ) { assert loaded != null ; this . classLoader = loaded ; this . namespace = NameConstants . DEFAULT_NAMESPACE ; } public final void setNamespace ( String namespace ) { this . namespace = namespace ; } public Class < ? > modelType ( String name ) { return type ( NameConstants . CATEGORY_DATA_MODEL , name ) ; } public ModelWrapper newModel ( String name ) { try { Class < ? > loaded = modelType ( name ) ; Object instance = loaded . newInstance ( ) ; return new ModelWrapper ( instance ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public Object newObject ( String category , String name ) { try { Class < ? > loaded = type ( category , name ) ; Object instance = loaded . newInstance ( ) ; return instance ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Class < ? > type ( String category , String name ) { try { return classLoader . loadClass ( MessageFormat . format ( "" , "" , namespace , category , name ) ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } } } @ SuppressWarnings ( "" ) protected static class ModelWrapper { private final DataModel instance ; private Class < ? > interfaceType ; ModelWrapper ( Object instance ) { this . instance = ( DataModel ) instance ; this . interfaceType = instance . getClass ( ) ; } public Object unwrap ( ) { return instance ; } public void setInterfaceType ( Class < ? > interfaceType ) { this . interfaceType = interfaceType ; } public boolean is ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; Object result = invoke ( jn . toMemberName ( ) ) ; return ( Boolean ) result ; } public Object get ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; return invoke ( jn . toMemberName ( ) ) ; } public void set ( String name , Object value ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; invoke ( jn . toMemberName ( ) , value ) ; } public ValueOption < ? > getOption ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; jn . addLast ( "" ) ; return ( ValueOption < ? > ) invoke ( jn . toMemberName ( ) ) ; } public void setOption ( String name , ValueOption < ? > option ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; jn . addLast ( "" ) ; invoke ( jn . toMemberName ( ) , option ) ; } public void reset ( ) { instance . reset ( ) ; } @ SuppressWarnings ( "" ) public void copyFrom ( ModelWrapper wrapper ) { instance . copyFrom ( wrapper . instance ) ; } public Object invoke ( String name , Object ... arguments ) { for ( Method method : interfaceType . getMethods ( ) ) { if ( method . getName ( ) . equals ( name ) ) { try { return method . invoke ( instance , arguments ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } throw new AssertionError ( name ) ; } } } package com . asakusafw . dmdl . java ; import static com . asakusafw . dmdl . util . CommandLineUtils . * ; import java . io . File ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Locale ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . apache . commons . cli . ParseException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Filer ; import com . asakusafw . utils . java . model . util . Models ; public final class Main { static final Logger LOG = LoggerFactory . getLogger ( Main . class ) ; private static final Option OPT_OUTPUT ; private static final Option OPT_PACKAGE ; private static final Option OPT_SOURCE_ENCODING ; private static final Option OPT_TARGET_ENCODING ; private static final Option OPT_SOURCE_PATH ; private static final Option OPT_PLUGIN ; private static final Options OPTIONS ; static { OPT_OUTPUT = new Option ( "" , true , "" ) ; OPT_OUTPUT . setArgName ( "" ) ; OPT_OUTPUT . setRequired ( true ) ; OPT_SOURCE_PATH = new Option ( "" , true , "" ) ; OPT_SOURCE_PATH . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_SOURCE_PATH . setRequired ( true ) ; OPT_PACKAGE = new Option ( "" , true , "" ) ; OPT_PACKAGE . setArgName ( "" ) ; OPT_PACKAGE . setRequired ( true ) ; OPT_SOURCE_ENCODING = new Option ( "" , true , "" ) ; OPT_SOURCE_ENCODING . setArgName ( "" ) ; OPT_SOURCE_ENCODING . setRequired ( false ) ; OPT_TARGET_ENCODING = new Option ( "" , true , "" ) ; OPT_TARGET_ENCODING . setArgName ( "" ) ; OPT_TARGET_ENCODING . setRequired ( false ) ; OPT_PLUGIN = new Option ( "" , true , "" ) ; OPT_PLUGIN . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN . setValueSeparator ( File . pathSeparatorChar ) ; OPT_PLUGIN . setRequired ( false ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_OUTPUT ) ; OPTIONS . addOption ( OPT_PACKAGE ) ; OPTIONS . addOption ( OPT_SOURCE_ENCODING ) ; OPTIONS . addOption ( OPT_TARGET_ENCODING ) ; OPTIONS . addOption ( OPT_SOURCE_PATH ) ; OPTIONS . addOption ( OPT_PLUGIN ) ; } private Main ( ) { return ; } public static void main ( String ... args ) { GenerateTask task ; try { Configuration conf = configure ( args ) ; task = new GenerateTask ( conf ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , Main . class . getName ( ) ) , OPTIONS , true ) ; e . printStackTrace ( System . out ) ; System . exit ( ) ; return ; } try { task . process ( ) ; } catch ( Exception e ) { e . printStackTrace ( System . out ) ; System . exit ( ) ; return ; } } static Configuration configure ( String [ ] args ) throws ParseException { assert args != null ; CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String output = cmd . getOptionValue ( OPT_OUTPUT . getOpt ( ) ) ; String packageName = cmd . getOptionValue ( OPT_PACKAGE . getOpt ( ) ) ; Charset sourceEnc = parseCharset ( cmd . getOptionValue ( OPT_SOURCE_ENCODING . getOpt ( ) ) ) ; Charset targetEnc = parseCharset ( cmd . getOptionValue ( OPT_TARGET_ENCODING . getOpt ( ) ) ) ; String sourcePaths = cmd . getOptionValue ( OPT_SOURCE_PATH . getOpt ( ) ) ; String plugin = cmd . getOptionValue ( OPT_PLUGIN . getOpt ( ) ) ; File outputDirectory = new File ( output ) ; DmdlSourceRepository source = buildRepository ( parseFileList ( sourcePaths ) , sourceEnc ) ; ClassLoader serviceLoader = buildPluginLoader ( Main . class . getClassLoader ( ) , parseFileList ( plugin ) ) ; ModelFactory factory = Models . getModelFactory ( ) ; return new Configuration ( factory , source , Models . toName ( factory , packageName ) , new Filer ( outputDirectory , targetEnc ) , serviceLoader , Locale . getDefault ( ) ) ; } } package com . asakusafw . dmdl . java . util ; import java . util . LinkedList ; import com . asakusafw . dmdl . model . AstName ; public final class NameUtil { public static String toPackageName ( AstName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } LinkedList < String > simples = new LinkedList < String > ( ) ; for ( AstName current = name ; current != null ; current = current . getQualifier ( ) ) { simples . addFirst ( JavaName . of ( current . getSimpleName ( ) ) . toMemberName ( ) ) ; } StringBuilder buf = new StringBuilder ( ) ; buf . append ( simples . removeFirst ( ) ) ; for ( String simpleName : simples ) { buf . append ( "" ) ; buf . append ( simpleName ) ; } return buf . toString ( ) ; } private NameUtil ( ) { return ; } } package com . asakusafw . dmdl . java . util ; import java . util . List ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . utils . collections . Lists ; public class JavaName { private final List < String > words ; JavaName ( List < ? extends String > words ) { if ( words == null ) { throw new NullPointerException ( "" ) ; } if ( words . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } this . words = Lists . create ( ) ; for ( String word : words ) { this . words . add ( normalize ( word ) ) ; } } public static JavaName of ( AstSimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return new JavaName ( normalize ( name . getWordList ( ) ) ) ; } public String toTypeName ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( capitalize ( words . get ( i ) ) ) ; } return buf . toString ( ) ; } public String toMemberName ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( words . get ( ) . toLowerCase ( ) ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( capitalize ( words . get ( i ) ) ) ; } return buf . toString ( ) ; } public String toConstantName ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( words . get ( ) . toUpperCase ( ) ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( '' ) ; buf . append ( words . get ( i ) . toUpperCase ( ) ) ; } return buf . toString ( ) ; } public void addFirst ( String segment ) { words . add ( , normalize ( segment ) ) ; } public void addLast ( String segment ) { words . add ( normalize ( segment ) ) ; } public JavaName append ( JavaName other ) { if ( other == null ) { throw new IllegalArgumentException ( "" ) ; } words . addAll ( other . words ) ; return this ; } private String capitalize ( String segment ) { assert segment != null ; StringBuilder buf = new StringBuilder ( segment . toLowerCase ( ) ) ; buf . setCharAt ( , Character . toUpperCase ( buf . charAt ( ) ) ) ; return buf . toString ( ) ; } private static String normalize ( String segment ) { if ( segment == null ) { throw new IllegalArgumentException ( "" ) ; } if ( segment . isEmpty ( ) ) { throw new IllegalArgumentException ( ) ; } return segment . toLowerCase ( ) ; } private static List < String > normalize ( List < String > segments ) { List < String > results = Lists . create ( ) ; for ( String segment : segments ) { if ( segment . isEmpty ( ) == false ) { results . add ( segment ) ; } } return results ; } } package com . asakusafw . dmdl . java . util ; package com . asakusafw . dmdl . java ; package com . asakusafw . dmdl . java ; import java . util . Locale ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . util . Emitter ; public class Configuration { private final ModelFactory factory ; private final DmdlSourceRepository source ; private final Name basePackage ; private final Emitter output ; private final ClassLoader serviceClassLoader ; private final Locale locale ; public Configuration ( ModelFactory factory , DmdlSourceRepository source , Name basePackage , Emitter output , ClassLoader serviceClassLoader , Locale locale ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( basePackage == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } if ( locale == null ) { throw new IllegalArgumentException ( "" ) ; } this . factory = factory ; this . source = source ; this . basePackage = basePackage ; this . output = output ; this . serviceClassLoader = serviceClassLoader ; this . locale = locale ; } public ModelFactory getFactory ( ) { return factory ; } public DmdlSourceRepository getSource ( ) { return source ; } public Name getBasePackage ( ) { return basePackage ; } public Emitter getOutput ( ) { return output ; } public ClassLoader getServiceClassLoader ( ) { return serviceClassLoader ; } public Locale getLocale ( ) { return locale ; } } package com . asakusafw . dmdl . java . emitter ; import java . text . MessageFormat ; public final class NameConstants { public static final String DEFAULT_NAMESPACE = "" ; public static final String CATEGORY_DATA_MODEL = "" ; public static final String CATEGORY_IO = "" ; public static final String PATTERN_DATA_MODEL = "" ; private NameConstants ( ) { return ; } } package com . asakusafw . dmdl . java . emitter ; package com . asakusafw . dmdl . java . emitter . driver ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . emitter . NameConstants ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ModelInputDriver extends JavaDataModelDriver { @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) throws IOException { Type type = generate ( context , model ) ; ModelFactory f = context . getModelFactory ( ) ; return new AttributeBuilder ( f ) . annotation ( context . resolve ( ModelInputLocation . class ) , f . newClassLiteral ( context . resolve ( type ) ) ) . toAnnotations ( ) ; } private Type generate ( EmitContext context , ModelDeclaration model ) throws IOException { EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , NameConstants . CATEGORY_IO , "" ) ; Generator . emit ( next , model ) ; return context . resolve ( next . getQualifiedTypeName ( ) ) ; } @ Override public List < Annotation > getMemberAnnotations ( EmitContext context , PropertyDeclaration property ) { return Collections . emptyList ( ) ; } private static final class Generator { private final EmitContext context ; private final ModelDeclaration model ; private final ModelFactory f ; private Generator ( EmitContext context , ModelDeclaration model ) { assert context != null ; assert model != null ; this . context = context ; this . model = model ; this . f = context . getModelFactory ( ) ; } static void emit ( EmitContext context , ModelDeclaration model ) throws IOException { assert context != null ; assert model != null ; Generator emitter = new Generator ( context , model ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" , model . getName ( ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Final ( ) . toAttributes ( ) , context . getTypeName ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( f . newParameterizedType ( context . resolve ( ModelInput . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createParserField ( ) ) ; results . add ( createConstructor ( ) ) ; results . add ( createReader ( ) ) ; results . add ( createCloser ( ) ) ; return results ; } private TypeBodyDeclaration createParserField ( ) { return f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , context . resolve ( RecordParser . class ) , createParserFieldName ( ) , null ) ; } private TypeBodyDeclaration createConstructor ( ) { return f . newConstructorDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( createParserFieldName ( ) ) . text ( "" ) . exception ( context . resolve ( IllegalArgumentException . class ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , context . getTypeName ( ) , Collections . singletonList ( f . newFormalParameterDeclaration ( context . resolve ( RecordParser . class ) , createParserFieldName ( ) ) ) , createConstructorBody ( ) ) ; } private List < Statement > createConstructorBody ( ) { List < Statement > results = Lists . create ( ) ; results . add ( f . newIfStatement ( new ExpressionBuilder ( f , createParserFieldName ( ) ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new TypeBuilder ( f , context . resolve ( IllegalArgumentException . class ) ) . newObject ( Models . toLiteral ( f , createParserFieldName ( ) . getToken ( ) ) ) . toThrowStatement ( ) ) ) ) ; results . add ( new ExpressionBuilder ( f , f . newThis ( null ) ) . field ( createParserFieldName ( ) ) . assignFrom ( createParserFieldName ( ) ) . toStatement ( ) ) ; return results ; } private MethodDeclaration createReader ( ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( boolean . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , createModelParameterName ( ) ) ) , , Collections . singletonList ( context . resolve ( IOException . class ) ) , f . newBlock ( createReaderBody ( ) ) ) ; } private List < Statement > createReaderBody ( ) { List < Statement > results = Lists . create ( ) ; results . add ( f . newIfStatement ( new ExpressionBuilder ( f , createParserFieldName ( ) ) . method ( "" ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , Models . toLiteral ( f , false ) ) . toReturnStatement ( ) ) ) ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { results . add ( createReaderStatement ( property ) ) ; } results . add ( createEndRecordStatement ( ) ) ; results . add ( f . newReturnStatement ( Models . toLiteral ( f , true ) ) ) ; return results ; } private Statement createReaderStatement ( PropertyDeclaration property ) { assert property != null ; SimpleName optionGetterName = context . getOptionGetterName ( property ) ; Expression option = new ExpressionBuilder ( f , createModelParameterName ( ) ) . method ( optionGetterName ) . toExpression ( ) ; Statement fill = new ExpressionBuilder ( f , createParserFieldName ( ) ) . method ( "" , option ) . toStatement ( ) ; return fill ; } private Statement createEndRecordStatement ( ) { return new ExpressionBuilder ( f , createParserFieldName ( ) ) . method ( "" ) . toStatement ( ) ; } private TypeBodyDeclaration createCloser ( ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . singletonList ( context . resolve ( IOException . class ) ) , f . newBlock ( createCloserBody ( ) ) ) ; } private List < Statement > createCloserBody ( ) { List < Statement > results = Lists . create ( ) ; results . add ( new ExpressionBuilder ( f , createParserFieldName ( ) ) . method ( "" ) . toStatement ( ) ) ; return results ; } private SimpleName createParserFieldName ( ) { return f . newSimpleName ( "" ) ; } private SimpleName createModelParameterName ( ) { return f . newSimpleName ( "" ) ; } } } package com . asakusafw . dmdl . java . emitter . driver ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . emitter . NameConstants ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ModelOutputDriver extends JavaDataModelDriver { @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) throws IOException { Type type = generate ( context , model ) ; ModelFactory f = context . getModelFactory ( ) ; return new AttributeBuilder ( f ) . annotation ( context . resolve ( ModelOutputLocation . class ) , f . newClassLiteral ( context . resolve ( type ) ) ) . toAnnotations ( ) ; } private Type generate ( EmitContext context , ModelDeclaration model ) throws IOException { EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , NameConstants . CATEGORY_IO , "" ) ; Generator . emit ( next , model ) ; return context . resolve ( next . getQualifiedTypeName ( ) ) ; } private static final class Generator { private final EmitContext context ; private final ModelDeclaration model ; private final ModelFactory f ; private Generator ( EmitContext context , ModelDeclaration model ) { assert context != null ; assert model != null ; this . context = context ; this . model = model ; this . f = context . getModelFactory ( ) ; } static void emit ( EmitContext context , ModelDeclaration model ) throws IOException { assert context != null ; assert model != null ; Generator emitter = new Generator ( context , model ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" , model . getSymbol ( ) . getName ( ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Final ( ) . toAttributes ( ) , context . getTypeName ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( f . newParameterizedType ( context . resolve ( ModelOutput . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , createBodyDeclarations ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createBodyDeclarations ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createEmitterField ( ) ) ; results . add ( createConstructor ( ) ) ; results . add ( createWriter ( ) ) ; results . add ( createCloser ( ) ) ; return results ; } private TypeBodyDeclaration createEmitterField ( ) { return f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , context . resolve ( RecordEmitter . class ) , createEmitterFieldName ( ) , null ) ; } private TypeBodyDeclaration createConstructor ( ) { return f . newConstructorDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( createEmitterFieldName ( ) ) . text ( "" ) . exception ( context . resolve ( IllegalArgumentException . class ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , context . getTypeName ( ) , Collections . singletonList ( f . newFormalParameterDeclaration ( context . resolve ( RecordEmitter . class ) , createEmitterFieldName ( ) ) ) , createConstructorBody ( ) ) ; } private List < Statement > createConstructorBody ( ) { List < Statement > results = Lists . create ( ) ; results . add ( f . newIfStatement ( new ExpressionBuilder ( f , createEmitterFieldName ( ) ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new TypeBuilder ( f , context . resolve ( IllegalArgumentException . class ) ) . newObject ( ) . toThrowStatement ( ) ) ) ) ; results . add ( new ExpressionBuilder ( f , f . newThis ( null ) ) . field ( createEmitterFieldName ( ) ) . assignFrom ( createEmitterFieldName ( ) ) . toStatement ( ) ) ; return results ; } private TypeBodyDeclaration createWriter ( ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , createModelParameterName ( ) ) ) , , Collections . singletonList ( context . resolve ( IOException . class ) ) , f . newBlock ( createWriterBody ( ) ) ) ; } private List < Statement > createWriterBody ( ) { List < Statement > results = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { results . add ( createWriterStatement ( property ) ) ; } results . add ( new ExpressionBuilder ( f , createEmitterFieldName ( ) ) . method ( "" ) . toStatement ( ) ) ; return results ; } private Statement createWriterStatement ( PropertyDeclaration property ) { assert property != null ; SimpleName optionGetterName = context . getOptionGetterName ( property ) ; Expression option = new ExpressionBuilder ( f , createModelParameterName ( ) ) . method ( optionGetterName ) . toExpression ( ) ; Statement fill = new ExpressionBuilder ( f , createEmitterFieldName ( ) ) . method ( "" , option ) . toStatement ( ) ; return fill ; } private TypeBodyDeclaration createCloser ( ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . singletonList ( context . resolve ( IOException . class ) ) , f . newBlock ( createCloserBody ( ) ) ) ; } private List < Statement > createCloserBody ( ) { List < Statement > results = Lists . create ( ) ; results . add ( new ExpressionBuilder ( f , createEmitterFieldName ( ) ) . method ( "" ) . toStatement ( ) ) ; return results ; } private SimpleName createEmitterFieldName ( ) { return f . newSimpleName ( "" ) ; } private SimpleName createModelParameterName ( ) { return f . newSimpleName ( "" ) ; } } } package com . asakusafw . dmdl . java . emitter . driver ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . Models ; public class GeneratorInfoDriver extends JavaDataModelDriver { private static final String GENERATOR_IDENTIFIER = "" ; @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) { ModelFactory f = context . getModelFactory ( ) ; return new AttributeBuilder ( f ) . annotation ( context . resolve ( DataModelKind . class ) , Models . toLiteral ( f , GENERATOR_IDENTIFIER ) ) . toAnnotations ( ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ObjectDriver extends JavaDataModelDriver { @ Override public List < MethodDeclaration > getMethods ( EmitContext context , ModelDeclaration model ) { if ( model . getOriginalAst ( ) . kind == ModelDefinitionKind . PROJECTIVE ) { return Collections . emptyList ( ) ; } List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createToString ( context , model ) ) ; results . add ( createHashCode ( context , model ) ) ; results . add ( createEquals ( context , model ) ) ; return results ; } private MethodDeclaration createToString ( EmitContext context , ModelDeclaration model ) { assert context != null ; assert model != null ; ModelFactory f = context . getModelFactory ( ) ; List < Statement > statements = Lists . create ( ) ; SimpleName buffer = context . createVariableName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( StringBuilder . class ) ) . newObject ( ) . toLocalVariableDeclaration ( context . resolve ( StringBuilder . class ) , buffer ) ) ; statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , Models . toLiteral ( f , "" ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , Models . toLiteral ( f , "" + model . getName ( ) . identifier ) ) . toStatement ( ) ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , Models . toLiteral ( f , MessageFormat . format ( "" , context . getFieldName ( property ) ) ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . toExpression ( ) ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , Models . toLiteral ( f , "" ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" ) . toReturnStatement ( ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( String . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createHashCode ( EmitContext context , ModelDeclaration model ) { assert context != null ; assert model != null ; ModelFactory f = context . getModelFactory ( ) ; List < Statement > statements = Lists . create ( ) ; SimpleName prime = context . createVariableName ( "" ) ; SimpleName result = context . createVariableName ( "" ) ; statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , ) ) . toLocalVariableDeclaration ( Models . toType ( f , int . class ) , prime ) ) ; statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , ) ) . toLocalVariableDeclaration ( Models . toType ( f , int . class ) , result ) ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { SimpleName field = context . getFieldName ( property ) ; statements . add ( new ExpressionBuilder ( f , result ) . assignFrom ( new ExpressionBuilder ( f , prime ) . apply ( InfixOperator . TIMES , result ) . apply ( InfixOperator . PLUS , new ExpressionBuilder ( f , field ) . method ( "" ) . toExpression ( ) ) . toExpression ( ) ) . toStatement ( ) ) ; } statements . add ( f . newReturnStatement ( result ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Models . toType ( f , int . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createEquals ( EmitContext context , ModelDeclaration model ) { assert context != null ; assert model != null ; ModelFactory f = context . getModelFactory ( ) ; List < Statement > statements = Lists . create ( ) ; SimpleName obj = context . createVariableName ( "" ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , f . newThis ( ) ) . apply ( InfixOperator . EQUALS , obj ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , true ) ) ) ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , obj ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , false ) ) ) ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , f . newThis ( ) ) . method ( "" ) . apply ( InfixOperator . NOT_EQUALS , new ExpressionBuilder ( f , obj ) . method ( "" ) . toExpression ( ) ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , false ) ) ) ) ) ; SimpleName other = context . createVariableName ( "" ) ; Type self = context . resolve ( context . getQualifiedTypeName ( ) ) ; statements . add ( new ExpressionBuilder ( f , obj ) . castTo ( self ) . toLocalVariableDeclaration ( self , other ) ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { SimpleName field = context . getFieldName ( property ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( field ) . method ( "" , new ExpressionBuilder ( f , other ) . field ( field ) . toExpression ( ) ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , false ) ) ) ) ) ; } statements . add ( f . newReturnStatement ( Models . toLiteral ( f , true ) ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Models . toType ( f , boolean . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( context . resolve ( Object . class ) , obj ) ) , statements ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; package com . asakusafw . dmdl . java . emitter . driver ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . Literal ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . Models ; public class PropertyOrderDriver extends JavaDataModelDriver { @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) { ModelFactory f = context . getModelFactory ( ) ; List < Literal > names = Lists . create ( ) ; for ( PropertyDeclaration prop : model . getDeclaredProperties ( ) ) { names . add ( Models . toLiteral ( f , prop . getName ( ) . identifier ) ) ; } return new AttributeBuilder ( f ) . annotation ( context . resolve ( PropertyOrder . class ) , f . newArrayInitializer ( names ) ) . toAnnotations ( ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . java . util . JavaName ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Modifier ; import com . asakusafw . utils . java . model . syntax . ModifierKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . SingleElementAnnotation ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; public class StringPropertyDriver extends JavaDataModelDriver { private static final BasicType TEXT_TYPE = new BasicType ( null , BasicTypeKind . TEXT ) ; @ Override public List < MethodDeclaration > getMethods ( EmitContext context , ModelDeclaration model ) { boolean projective = model . getOriginalAst ( ) . kind == ModelDefinitionKind . PROJECTIVE ; List < MethodDeclaration > results = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( isTextType ( property ) == false ) { continue ; } if ( projective ) { ModelFactory f = context . getModelFactory ( ) ; results . add ( makeInterfaceMethod ( f , createStringGetter ( context , property ) ) ) ; results . add ( makeInterfaceMethod ( f , createStringSetter ( context , property ) ) ) ; } else { results . add ( createStringGetter ( context , property ) ) ; results . add ( createStringSetter ( context , property ) ) ; } } return results ; } private MethodDeclaration createStringGetter ( EmitContext context , PropertyDeclaration property ) { assert context != null ; assert property != null ; JavaName name = JavaName . of ( property . getName ( ) ) ; name . addFirst ( "" ) ; name . addLast ( "" ) ; name . addLast ( "" ) ; ModelFactory f = context . getModelFactory ( ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . returns ( ) . text ( "" , context . getDescription ( property ) ) . exception ( context . resolve ( NullPointerException . class ) ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , context . resolve ( String . class ) , f . newSimpleName ( name . toMemberName ( ) ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . method ( "" ) . toReturnStatement ( ) ) ) ; } private MethodDeclaration createStringSetter ( EmitContext context , PropertyDeclaration property ) { assert context != null ; assert property != null ; JavaName name = JavaName . of ( property . getName ( ) ) ; name . addFirst ( "" ) ; name . addLast ( "" ) ; name . addLast ( "" ) ; ModelFactory f = context . getModelFactory ( ) ; SimpleName paramName = context . createVariableName ( context . getFieldName ( property ) . getToken ( ) ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . param ( paramName ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . annotation ( context . resolve ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . Public ( ) . toAttributes ( ) , context . resolve ( void . class ) , f . newSimpleName ( name . toMemberName ( ) ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( context . resolve ( String . class ) , paramName ) } ) , Collections . singletonList ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . method ( "" , paramName ) . toStatement ( ) ) ) ; } private boolean isTextType ( PropertyDeclaration property ) { assert property != null ; return property . getType ( ) . isSame ( TEXT_TYPE ) ; } private MethodDeclaration makeInterfaceMethod ( ModelFactory f , MethodDeclaration method ) { assert f != null ; assert method != null ; return f . newMethodDeclaration ( method . getJavadoc ( ) , filterInterfaceMethodModifiers ( method . getModifiers ( ) ) , method . getTypeParameters ( ) , method . getReturnType ( ) , method . getName ( ) , method . getFormalParameters ( ) , , method . getExceptionTypes ( ) , null ) ; } private List < Attribute > filterInterfaceMethodModifiers ( List < ? extends Attribute > modifiers ) { assert modifiers != null ; List < Attribute > results = Lists . create ( ) ; for ( Attribute attribute : modifiers ) { if ( attribute . getModelKind ( ) == ModelKind . MODIFIER ) { ModifierKind kind = ( ( Modifier ) attribute ) . getModifierKind ( ) ; if ( kind == ModifierKind . PUBLIC || kind == ModifierKind . ABSTRACT ) { continue ; } } else if ( attribute . getModelKind ( ) == ModelKind . SINGLE_ELEMENT_ANNOTATION ) { SingleElementAnnotation an = ( SingleElementAnnotation ) attribute ; Name name = an . getType ( ) . getName ( ) ; if ( name . toNameString ( ) . equals ( SuppressWarnings . class . getSimpleName ( ) ) ) { continue ; } } results . add ( attribute ) ; } return results ; } } package com . asakusafw . dmdl . java . emitter . driver ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . PropertyMappingKind ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . semantics . trait . MappingFactor ; import com . asakusafw . dmdl . semantics . trait . ReduceTerm ; import com . asakusafw . dmdl . semantics . trait . SummarizeTrait ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . ArrayInitializer ; import com . asakusafw . utils . java . model . syntax . ClassLiteral ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . Literal ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; public class SummarizeDriver extends JavaDataModelDriver { @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) { if ( model . getOriginalAst ( ) . kind != ModelDefinitionKind . SUMMARIZED ) { return Collections . emptyList ( ) ; } SummarizeTrait trait = model . getTrait ( SummarizeTrait . class ) ; if ( trait == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , model . getName ( ) ) ) ; } ModelFactory f = context . getModelFactory ( ) ; List < Annotation > eTerms = Lists . create ( ) ; for ( ReduceTerm < ? > term : trait . getTerms ( ) ) { ClassLiteral source = f . newClassLiteral ( context . resolve ( term . getSource ( ) ) ) ; ArrayInitializer mappings = toMappings ( context , term . getMappings ( ) ) ; Annotation shuffle = toKey ( context , term ) ; eTerms . addAll ( new AttributeBuilder ( f ) . annotation ( context . resolve ( Summarized . Term . class ) , "" , source , "" , mappings , "" , shuffle ) . toAnnotations ( ) ) ; } return new AttributeBuilder ( f ) . annotation ( context . resolve ( Summarized . class ) , "" , eTerms . get ( ) ) . toAnnotations ( ) ; } private ArrayInitializer toMappings ( EmitContext context , List < MappingFactor > foldings ) { assert context != null ; assert foldings != null ; ModelFactory f = context . getModelFactory ( ) ; List < Annotation > eachFolding = Lists . create ( ) ; for ( MappingFactor factor : foldings ) { Expression aggregator = new TypeBuilder ( f , context . resolve ( Summarized . Aggregator . class ) ) . field ( convert ( factor . getKind ( ) ) . name ( ) ) . toExpression ( ) ; String source = context . getFieldName ( factor . getSource ( ) . findDeclaration ( ) ) . getToken ( ) ; String target = context . getFieldName ( factor . getTarget ( ) . findDeclaration ( ) ) . getToken ( ) ; eachFolding . addAll ( new AttributeBuilder ( f ) . annotation ( context . resolve ( Summarized . Folding . class ) , "" , aggregator , "" , Models . toLiteral ( f , source ) , "" , Models . toLiteral ( f , target ) ) . toAnnotations ( ) ) ; } return f . newArrayInitializer ( eachFolding ) ; } private Summarized . Aggregator convert ( PropertyMappingKind kind ) { assert kind != null ; switch ( kind ) { case ANY : return Summarized . Aggregator . ANY ; case COUNT : return Summarized . Aggregator . COUNT ; case MAX : return Summarized . Aggregator . MAX ; case MIN : return Summarized . Aggregator . MIN ; case SUM : return Summarized . Aggregator . SUM ; default : throw new AssertionError ( kind ) ; } } private Annotation toKey ( EmitContext context , ReduceTerm < ? > term ) { assert context != null ; assert term != null ; ModelFactory f = context . getModelFactory ( ) ; List < Literal > properties = Lists . create ( ) ; Map < String , PropertySymbol > reverseMapping = Maps . create ( ) ; for ( MappingFactor mapping : term . getMappings ( ) ) { reverseMapping . put ( mapping . getTarget ( ) . getName ( ) . identifier , mapping . getSource ( ) ) ; } for ( PropertySymbol property : term . getGrouping ( ) ) { PropertySymbol origin = reverseMapping . get ( property . getName ( ) . identifier ) ; assert origin != null ; PropertyDeclaration decl = origin . findDeclaration ( ) ; properties . add ( Models . toLiteral ( f , context . getFieldName ( decl ) . getToken ( ) ) ) ; } return new AttributeBuilder ( f ) . annotation ( context . resolve ( Key . class ) , "" , f . newArrayInitializer ( properties ) ) . toAnnotations ( ) . get ( ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . semantics . trait . JoinTrait ; import com . asakusafw . dmdl . semantics . trait . MappingFactor ; import com . asakusafw . dmdl . semantics . trait . ReduceTerm ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . ArrayInitializer ; import com . asakusafw . utils . java . model . syntax . ClassLiteral ; import com . asakusafw . utils . java . model . syntax . Literal ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; public class JoinDriver extends JavaDataModelDriver { @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) { if ( model . getOriginalAst ( ) . kind != ModelDefinitionKind . JOINED ) { return Collections . emptyList ( ) ; } JoinTrait trait = model . getTrait ( JoinTrait . class ) ; if ( trait == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , model . getName ( ) ) ) ; } ModelFactory f = context . getModelFactory ( ) ; List < Annotation > eTerms = Lists . create ( ) ; for ( ReduceTerm < ? > term : trait . getTerms ( ) ) { ClassLiteral source = f . newClassLiteral ( context . resolve ( term . getSource ( ) ) ) ; ArrayInitializer mappings = toMappings ( context , term . getMappings ( ) ) ; Annotation shuffle = toKey ( context , term ) ; eTerms . addAll ( new AttributeBuilder ( f ) . annotation ( context . resolve ( Joined . Term . class ) , "" , source , "" , mappings , "" , shuffle ) . toAnnotations ( ) ) ; } return new AttributeBuilder ( f ) . annotation ( context . resolve ( Joined . class ) , "" , f . newArrayInitializer ( eTerms ) ) . toAnnotations ( ) ; } private ArrayInitializer toMappings ( EmitContext context , List < MappingFactor > mappings ) { assert context != null ; assert mappings != null ; ModelFactory f = context . getModelFactory ( ) ; List < Annotation > eachMapping = Lists . create ( ) ; for ( MappingFactor factor : mappings ) { String source = context . getFieldName ( factor . getSource ( ) . findDeclaration ( ) ) . getToken ( ) ; String target = context . getFieldName ( factor . getTarget ( ) . findDeclaration ( ) ) . getToken ( ) ; eachMapping . addAll ( new AttributeBuilder ( f ) . annotation ( context . resolve ( Joined . Mapping . class ) , "" , Models . toLiteral ( f , source ) , "" , Models . toLiteral ( f , target ) ) . toAnnotations ( ) ) ; } return f . newArrayInitializer ( eachMapping ) ; } private Annotation toKey ( EmitContext context , ReduceTerm < ? > term ) { assert context != null ; assert term != null ; ModelFactory f = context . getModelFactory ( ) ; List < Literal > properties = Lists . create ( ) ; Map < String , PropertySymbol > reverseMapping = Maps . create ( ) ; for ( MappingFactor mapping : term . getMappings ( ) ) { reverseMapping . put ( mapping . getTarget ( ) . getName ( ) . identifier , mapping . getSource ( ) ) ; } for ( PropertySymbol property : term . getGrouping ( ) ) { PropertySymbol origin = reverseMapping . get ( property . getName ( ) . identifier ) ; assert origin != null ; PropertyDeclaration decl = origin . findDeclaration ( ) ; properties . add ( Models . toLiteral ( f , context . getFieldName ( decl ) . getToken ( ) ) ) ; } return new AttributeBuilder ( f ) . annotation ( context . resolve ( Key . class ) , "" , f . newArrayInitializer ( properties ) ) . toAnnotations ( ) . get ( ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . Writable ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; public class WritableDriver extends JavaDataModelDriver { @ Override public List < Type > getInterfaces ( EmitContext context , ModelDeclaration model ) { return Collections . singletonList ( context . resolve ( Writable . class ) ) ; } @ Override public List < MethodDeclaration > getMethods ( EmitContext context , ModelDeclaration model ) { if ( model . getOriginalAst ( ) . kind == ModelDefinitionKind . PROJECTIVE ) { return Collections . emptyList ( ) ; } List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createWrite ( context , model ) ) ; results . add ( createReadFields ( context , model ) ) ; return results ; } private MethodDeclaration createWrite ( EmitContext context , ModelDeclaration model ) { assert context != null ; assert model != null ; ModelFactory f = context . getModelFactory ( ) ; SimpleName parameter = context . createVariableName ( "" ) ; List < Statement > statements = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { SimpleName fieldName = context . getFieldName ( property ) ; statements . add ( new ExpressionBuilder ( f , fieldName ) . method ( "" , parameter ) . toStatement ( ) ) ; } return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , Models . toType ( f , void . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( context . resolve ( DataOutput . class ) , parameter ) ) , , Collections . singletonList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ; } private MethodDeclaration createReadFields ( EmitContext context , ModelDeclaration model ) { assert context != null ; assert model != null ; ModelFactory f = context . getModelFactory ( ) ; SimpleName parameter = context . createVariableName ( "" ) ; List < Statement > statements = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { SimpleName fieldName = context . getFieldName ( property ) ; statements . add ( new ExpressionBuilder ( f , fieldName ) . method ( "" , parameter ) . toStatement ( ) ) ; } return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , Models . toType ( f , void . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( DataInput . class ) , parameter ) ) , , Collections . singletonList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ; } } package com . asakusafw . dmdl . java . emitter . driver ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . ModelSymbol ; import com . asakusafw . dmdl . semantics . trait . ProjectionsTrait ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Type ; public class ProjectionDriver extends JavaDataModelDriver { @ Override public List < Type > getInterfaces ( EmitContext context , ModelDeclaration model ) { ProjectionsTrait trait = model . getTrait ( ProjectionsTrait . class ) ; if ( trait == null ) { return Collections . emptyList ( ) ; } List < Type > results = Lists . create ( ) ; for ( ModelSymbol projection : trait . getProjections ( ) ) { results . add ( context . resolve ( projection ) ) ; } return results ; } } package com . asakusafw . dmdl . java . emitter ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . Configuration ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; public class ConcreteModelEmitter { private final ModelDeclaration model ; private final EmitContext context ; private final JavaDataModelDriver driver ; private final ModelFactory f ; public ConcreteModelEmitter ( DmdlSemantics semantics , Configuration config , ModelDeclaration model , JavaDataModelDriver driver ) { if ( semantics == null ) { throw new IllegalArgumentException ( "" ) ; } if ( config == null ) { throw new IllegalArgumentException ( "" ) ; } if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } this . model = model ; this . context = new EmitContext ( semantics , config , model , NameConstants . CATEGORY_DATA_MODEL , NameConstants . PATTERN_DATA_MODEL ) ; this . driver = driver ; this . f = config . getFactory ( ) ; } public void emit ( ) throws IOException { driver . generateResources ( context , model ) ; context . emit ( f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( model ) ) . toJavadoc ( ) , createModifiers ( ) , context . getTypeName ( ) , null , createSuperInterfaces ( ) , createMembers ( ) ) ) ; } private List < Attribute > createModifiers ( ) throws IOException { List < Attribute > results = Lists . create ( ) ; results . addAll ( driver . getTypeAnnotations ( context , model ) ) ; results . addAll ( new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) ) ; return results ; } private List < Type > createSuperInterfaces ( ) throws IOException { List < Type > results = Lists . create ( ) ; results . add ( f . newParameterizedType ( context . resolve ( DataModel . class ) , context . resolve ( context . getQualifiedTypeName ( ) ) ) ) ; results . addAll ( driver . getInterfaces ( context , model ) ) ; return results ; } private List < TypeBodyDeclaration > createMembers ( ) throws IOException { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . addAll ( createPropertyFields ( ) ) ; results . addAll ( driver . getFields ( context , model ) ) ; results . addAll ( createDataModelMethods ( ) ) ; results . addAll ( createPropertyAccessors ( ) ) ; results . addAll ( driver . getMethods ( context , model ) ) ; return results ; } private List < FieldDeclaration > createPropertyFields ( ) { List < FieldDeclaration > results = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { Type type = context . getFieldType ( property ) ; SimpleName name = context . getFieldName ( property ) ; results . add ( f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , type , name , context . getFieldInitializer ( property ) ) ) ; } return results ; } private List < MethodDeclaration > createDataModelMethods ( ) { List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createResetMethod ( ) ) ; results . add ( createCopyMethod ( ) ) ; return results ; } private MethodDeclaration createResetMethod ( ) { List < Statement > statements = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { statements . add ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . method ( "" ) . toStatement ( ) ) ; } return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . annotation ( context . resolve ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . Public ( ) . toAttributes ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createCopyMethod ( ) { SimpleName other = context . createVariableName ( "" ) ; List < Statement > statements = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { statements . add ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . method ( "" , new ExpressionBuilder ( f , other ) . field ( context . getFieldName ( property ) ) . toExpression ( ) ) . toStatement ( ) ) ; } return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . annotation ( context . resolve ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . Public ( ) . toAttributes ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( context . resolve ( context . getQualifiedTypeName ( ) ) , other ) ) , statements ) ; } private List < MethodDeclaration > createPropertyAccessors ( ) throws IOException { List < MethodDeclaration > results = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { results . add ( createValueGetter ( property ) ) ; results . add ( createValueSetter ( property ) ) ; results . add ( createOptionGetter ( property ) ) ; results . add ( createOptionSetter ( property ) ) ; } return results ; } private MethodDeclaration createValueGetter ( PropertyDeclaration property ) { assert property != null ; List < Attribute > attributes = Lists . create ( ) ; attributes . addAll ( new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . returns ( ) . text ( "" , context . getDescription ( property ) ) . exception ( context . resolve ( NullPointerException . class ) ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , attributes , context . getValueType ( property ) , context . getValueGetterName ( property ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . method ( "" ) . toReturnStatement ( ) ) ) ; } private MethodDeclaration createValueSetter ( PropertyDeclaration property ) { assert property != null ; SimpleName paramName = context . createVariableName ( "" ) ; Type valueType = context . getValueType ( property ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . param ( paramName ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . annotation ( context . resolve ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . Public ( ) . toAttributes ( ) , context . resolve ( void . class ) , context . getValueSetterName ( property ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( valueType , paramName ) } ) , Collections . singletonList ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . method ( "" , paramName ) . toStatement ( ) ) ) ; } private MethodDeclaration createOptionGetter ( PropertyDeclaration property ) throws IOException { assert property != null ; List < Attribute > attributes = Lists . create ( ) ; attributes . addAll ( driver . getMemberAnnotations ( context , property ) ) ; attributes . addAll ( new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . returns ( ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , attributes , context . getFieldType ( property ) , context . getOptionGetterName ( property ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . toReturnStatement ( ) ) ) ; } private MethodDeclaration createOptionSetter ( PropertyDeclaration property ) { assert property != null ; SimpleName paramName = context . createVariableName ( "" ) ; Type optionType = context . getFieldType ( property ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . param ( paramName ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . annotation ( context . resolve ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . Public ( ) . toAttributes ( ) , context . resolve ( void . class ) , context . getOptionSetterName ( property ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( optionType , paramName ) } ) , Collections . singletonList ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( context . getFieldName ( property ) ) . method ( "" , paramName ) . toStatement ( ) ) ) ; } } package com . asakusafw . dmdl . java . emitter ; import java . io . IOException ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . ServiceLoader ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . Type ; public class CompositeDataModelDriver extends JavaDataModelDriver { static final Logger LOG = LoggerFactory . getLogger ( CompositeDataModelDriver . class ) ; private final List < JavaDataModelDriver > drivers ; public CompositeDataModelDriver ( ClassLoader serviceClassLoader ) { if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . drivers = Lists . freeze ( loadSpi ( serviceClassLoader ) ) ; } private List < JavaDataModelDriver > loadSpi ( ClassLoader serviceClassLoader ) { assert serviceClassLoader != null ; List < JavaDataModelDriver > results = Lists . create ( ) ; ServiceLoader < JavaDataModelDriver > loader = ServiceLoader . load ( JavaDataModelDriver . class , serviceClassLoader ) ; for ( JavaDataModelDriver driver : loader ) { LOG . debug ( "" , driver . getClass ( ) . getName ( ) ) ; results . add ( driver ) ; } Collections . sort ( results , new Comparator < Object > ( ) { @ Override public int compare ( Object o1 , Object o2 ) { assert o2 != null ; int diff = o1 . getClass ( ) . getSimpleName ( ) . compareTo ( o2 . getClass ( ) . getSimpleName ( ) ) ; if ( diff != ) { return diff ; } return o1 . getClass ( ) . getName ( ) . compareTo ( o2 . getClass ( ) . getName ( ) ) ; } } ) ; return results ; } public CompositeDataModelDriver ( List < ? extends JavaDataModelDriver > drivers ) { if ( drivers == null ) { throw new IllegalArgumentException ( "" ) ; } this . drivers = Lists . freeze ( drivers ) ; } public List < JavaDataModelDriver > getDrivers ( ) { return drivers ; } @ Override public void generateResources ( EmitContext context , ModelDeclaration model ) throws IOException { for ( JavaDataModelDriver driver : drivers ) { driver . generateResources ( context , model ) ; } } @ Override public List < Type > getInterfaces ( EmitContext context , ModelDeclaration model ) throws IOException { List < Type > results = Lists . create ( ) ; for ( JavaDataModelDriver driver : drivers ) { results . addAll ( driver . getInterfaces ( context , model ) ) ; } return results ; } @ Override public List < FieldDeclaration > getFields ( EmitContext context , ModelDeclaration model ) throws IOException { List < FieldDeclaration > results = Lists . create ( ) ; for ( JavaDataModelDriver driver : drivers ) { results . addAll ( driver . getFields ( context , model ) ) ; } return results ; } @ Override public List < MethodDeclaration > getMethods ( EmitContext context , ModelDeclaration model ) throws IOException { List < MethodDeclaration > results = Lists . create ( ) ; for ( JavaDataModelDriver driver : drivers ) { results . addAll ( driver . getMethods ( context , model ) ) ; } return results ; } @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) throws IOException { List < Annotation > results = Lists . create ( ) ; for ( JavaDataModelDriver driver : drivers ) { results . addAll ( driver . getTypeAnnotations ( context , model ) ) ; } return results ; } @ Override public List < Annotation > getMemberAnnotations ( EmitContext context , PropertyDeclaration property ) throws IOException { List < Annotation > results = Lists . create ( ) ; for ( JavaDataModelDriver driver : drivers ) { results . addAll ( driver . getMemberAnnotations ( context , property ) ) ; } return results ; } } package com . asakusafw . dmdl . java . emitter ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . Configuration ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; public class ProjectiveModelEmitter { private final ModelDeclaration model ; private final EmitContext context ; private final JavaDataModelDriver driver ; private final ModelFactory f ; public ProjectiveModelEmitter ( DmdlSemantics semantics , Configuration config , ModelDeclaration model , JavaDataModelDriver driver ) { if ( semantics == null ) { throw new IllegalArgumentException ( "" ) ; } if ( config == null ) { throw new IllegalArgumentException ( "" ) ; } if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } this . model = model ; this . driver = driver ; this . context = new EmitContext ( semantics , config , model , NameConstants . CATEGORY_DATA_MODEL , NameConstants . PATTERN_DATA_MODEL ) ; this . f = config . getFactory ( ) ; } public void emit ( ) throws IOException { driver . generateResources ( context , model ) ; context . emit ( f . newInterfaceDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( model ) ) . toJavadoc ( ) , createModifiers ( ) , context . getTypeName ( ) , driver . getInterfaces ( context , model ) , createMembers ( ) ) ) ; } private List < Attribute > createModifiers ( ) throws IOException { List < Attribute > results = Lists . create ( ) ; results . addAll ( driver . getTypeAnnotations ( context , model ) ) ; results . addAll ( new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) ) ; return results ; } private List < TypeBodyDeclaration > createMembers ( ) throws IOException { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . addAll ( driver . getFields ( context , model ) ) ; results . addAll ( createPropertyAccessors ( ) ) ; results . addAll ( driver . getMethods ( context , model ) ) ; return results ; } private List < MethodDeclaration > createPropertyAccessors ( ) throws IOException { List < MethodDeclaration > results = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { results . add ( createGetter ( property ) ) ; results . add ( createSetter ( property ) ) ; results . add ( createOptionGetter ( property ) ) ; results . add ( createOptionSetter ( property ) ) ; } return results ; } private MethodDeclaration createGetter ( PropertyDeclaration property ) { assert property != null ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . returns ( ) . text ( "" , context . getDescription ( property ) ) . exception ( context . resolve ( NullPointerException . class ) ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . getValueType ( property ) , context . getValueGetterName ( property ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . < Type > emptyList ( ) , null ) ; } private MethodDeclaration createSetter ( PropertyDeclaration property ) { assert property != null ; SimpleName paramName = context . createVariableName ( "" ) ; Type valueType = context . getValueType ( property ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . param ( paramName ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , context . getValueSetterName ( property ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( valueType , paramName ) } ) , , Collections . < Type > emptyList ( ) , null ) ; } private MethodDeclaration createOptionGetter ( PropertyDeclaration property ) throws IOException { assert property != null ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . returns ( ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , driver . getMemberAnnotations ( context , property ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . getFieldType ( property ) , context . getOptionGetterName ( property ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . < Type > emptyList ( ) , null ) ; } private MethodDeclaration createOptionSetter ( PropertyDeclaration property ) { assert property != null ; SimpleName paramName = context . createVariableName ( "" ) ; Type optionType = context . getFieldType ( property ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" , context . getDescription ( property ) ) . param ( paramName ) . text ( "" , context . getDescription ( property ) ) . toJavadoc ( ) , new AttributeBuilder ( f ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , context . getOptionSetterName ( property ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( optionType , paramName ) } ) , , Collections . < Type > emptyList ( ) , null ) ; } } package com . asakusafw . dmdl . java . emitter ; import java . io . IOException ; import com . asakusafw . dmdl . java . Configuration ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; public class JavaModelClassGenerator { private final DmdlSemantics semantics ; private final Configuration config ; private final JavaDataModelDriver driver ; public JavaModelClassGenerator ( DmdlSemantics semantics , Configuration config , JavaDataModelDriver driver ) { if ( semantics == null ) { throw new IllegalArgumentException ( "" ) ; } if ( config == null ) { throw new IllegalArgumentException ( "" ) ; } if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } this . semantics = semantics ; this . config = config ; this . driver = driver ; } public void emit ( ModelDeclaration model ) throws IOException { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } switch ( model . getOriginalAst ( ) . kind ) { case PROJECTIVE : new ProjectiveModelEmitter ( semantics , config , model , driver ) . emit ( ) ; break ; case RECORD : case JOINED : case SUMMARIZED : new ConcreteModelEmitter ( semantics , config , model , driver ) . emit ( ) ; break ; default : throw new AssertionError ( model . getOriginalAst ( ) . kind ) ; } } } package com . asakusafw . dmdl . java . emitter ; import java . io . IOException ; import java . io . PrintWriter ; import java . math . BigDecimal ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Set ; import org . apache . hadoop . io . Text ; import com . asakusafw . dmdl . java . Configuration ; import com . asakusafw . dmdl . java . util . JavaName ; import com . asakusafw . dmdl . java . util . NameUtil ; import com . asakusafw . dmdl . model . AstDescription ; import com . asakusafw . dmdl . model . AstName ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . Declaration ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . ModelSymbol ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . trait . NamespaceTrait ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . Models ; public final class EmitContext { private final DmdlSemantics semantics ; private final Configuration config ; private final ModelFactory factory ; private final SimpleName typeName ; private final ImportBuilder imports ; private final Set < String > fieldNames ; public EmitContext ( DmdlSemantics semantics , Configuration config , ModelDeclaration model , String categoryName , String typeNamePattern ) { if ( semantics == null ) { throw new IllegalArgumentException ( "" ) ; } if ( config == null ) { throw new IllegalArgumentException ( "" ) ; } if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } if ( categoryName == null ) { throw new IllegalArgumentException ( "" ) ; } this . semantics = semantics ; this . config = config ; this . factory = config . getFactory ( ) ; this . typeName = getTypeName ( model , typeNamePattern ) ; Name namespace = getNamespace ( model ) ; this . imports = new ImportBuilder ( factory , factory . newPackageDeclaration ( Models . append ( factory , config . getBasePackage ( ) , namespace , factory . newSimpleName ( categoryName ) ) ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . imports . resolvePackageMember ( this . typeName ) ; this . fieldNames = collectFieldNames ( model ) ; } private Set < String > collectFieldNames ( ModelDeclaration model ) { assert model != null ; Set < String > results = Sets . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { results . add ( getFieldName ( property ) . getToken ( ) ) ; } return results ; } public ModelFactory getModelFactory ( ) { return factory ; } public DmdlSemantics getSemantics ( ) { return semantics ; } public Configuration getConfiguration ( ) { return config ; } private SimpleName getTypeName ( ModelDeclaration model , String namePattern ) { assert model != null ; assert namePattern != null ; return factory . newSimpleName ( MessageFormat . format ( namePattern , JavaName . of ( model . getName ( ) ) . toTypeName ( ) ) ) ; } private Name getNamespace ( ModelDeclaration model ) { assert model != null ; NamespaceTrait trait = model . getTrait ( NamespaceTrait . class ) ; AstName name ; if ( trait == null ) { name = new AstSimpleName ( null , NameConstants . DEFAULT_NAMESPACE ) ; } else { name = trait . getNamespace ( ) ; } return Models . toName ( factory , NameUtil . toPackageName ( name ) ) ; } public SimpleName getTypeName ( ) { return typeName ; } public QualifiedName getQualifiedTypeName ( ) { return factory . newQualifiedName ( imports . getPackageDeclaration ( ) . getName ( ) , typeName ) ; } public void emit ( TypeDeclaration type ) throws IOException { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } CompilationUnit compilationUnit = factory . newCompilationUnit ( imports . getPackageDeclaration ( ) , imports . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; PrintWriter writer = config . getOutput ( ) . openFor ( compilationUnit ) ; try { Models . emit ( compilationUnit , writer ) ; } finally { writer . close ( ) ; } } public Type resolve ( ModelSymbol model ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } ModelDeclaration decl = model . findDeclaration ( ) ; if ( decl == null ) { throw new IllegalArgumentException ( ) ; } Name qualifiedName = Models . append ( factory , config . getBasePackage ( ) , getNamespace ( decl ) , factory . newSimpleName ( NameConstants . CATEGORY_DATA_MODEL ) , getTypeName ( decl , NameConstants . PATTERN_DATA_MODEL ) ) ; return imports . toType ( qualifiedName ) ; } public Type resolve ( java . lang . reflect . Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return imports . toType ( type ) ; } public Type resolve ( Name name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return imports . toType ( name ) ; } public Type resolve ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return imports . resolve ( type ) ; } public SimpleName getFieldName ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } String name = JavaName . of ( property . getName ( ) ) . toMemberName ( ) ; return factory . newSimpleName ( name ) ; } public Type getValueType ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } if ( property . getType ( ) instanceof BasicType ) { BasicType bt = ( BasicType ) property . getType ( ) ; switch ( bt . getKind ( ) ) { case BOOLEAN : return resolve ( boolean . class ) ; case DATE : return resolve ( Date . class ) ; case DATETIME : return resolve ( DateTime . class ) ; case DECIMAL : return resolve ( BigDecimal . class ) ; case DOUBLE : return resolve ( double . class ) ; case FLOAT : return resolve ( float . class ) ; case BYTE : return resolve ( byte . class ) ; case SHORT : return resolve ( short . class ) ; case INT : return resolve ( int . class ) ; case LONG : return resolve ( long . class ) ; case TEXT : return resolve ( Text . class ) ; default : throw new IllegalArgumentException ( MessageFormat . format ( "" , bt . getKind ( ) ) ) ; } } throw new IllegalArgumentException ( ) ; } public Type getFieldType ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } if ( property . getType ( ) instanceof BasicType ) { BasicType bt = ( BasicType ) property . getType ( ) ; switch ( bt . getKind ( ) ) { case BOOLEAN : return resolve ( BooleanOption . class ) ; case DATE : return resolve ( DateOption . class ) ; case DATETIME : return resolve ( DateTimeOption . class ) ; case DECIMAL : return resolve ( DecimalOption . class ) ; case BYTE : return resolve ( ByteOption . class ) ; case SHORT : return resolve ( ShortOption . class ) ; case INT : return resolve ( IntOption . class ) ; case LONG : return resolve ( LongOption . class ) ; case FLOAT : return resolve ( FloatOption . class ) ; case DOUBLE : return resolve ( DoubleOption . class ) ; case TEXT : return resolve ( StringOption . class ) ; default : throw new IllegalArgumentException ( MessageFormat . format ( "" , bt . getKind ( ) ) ) ; } } throw new IllegalArgumentException ( ) ; } public Expression getFieldInitializer ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } if ( property . getType ( ) instanceof BasicType ) { return factory . newClassInstanceCreationExpression ( getFieldType ( property ) ) ; } throw new IllegalArgumentException ( ) ; } public SimpleName getValueGetterName ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } JavaName name = JavaName . of ( property . getName ( ) ) ; if ( isBoolean ( property ) ) { name . addFirst ( "" ) ; } else { name . addFirst ( "" ) ; } return factory . newSimpleName ( name . toMemberName ( ) ) ; } private boolean isBoolean ( PropertyDeclaration property ) { assert property != null ; if ( ( property . getType ( ) instanceof BasicType ) == false ) { return false ; } BasicType type = ( BasicType ) property . getType ( ) ; return type . getKind ( ) == BasicTypeKind . BOOLEAN ; } public SimpleName getValueSetterName ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } JavaName name = JavaName . of ( property . getName ( ) ) ; name . addFirst ( "" ) ; return factory . newSimpleName ( name . toMemberName ( ) ) ; } public SimpleName getOptionGetterName ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } JavaName name = JavaName . of ( property . getName ( ) ) ; name . addFirst ( "" ) ; name . addLast ( "" ) ; return factory . newSimpleName ( name . toMemberName ( ) ) ; } public SimpleName getOptionSetterName ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } JavaName name = JavaName . of ( property . getName ( ) ) ; name . addFirst ( "" ) ; name . addLast ( "" ) ; return factory . newSimpleName ( name . toMemberName ( ) ) ; } public SimpleName createVariableName ( String hint ) { if ( hint == null ) { throw new IllegalArgumentException ( "" ) ; } if ( fieldNames . contains ( hint ) == false ) { return factory . newSimpleName ( hint ) ; } for ( int i = ; true ; i ++ ) { String next = hint + i ; if ( fieldNames . contains ( next ) == false ) { return factory . newSimpleName ( next ) ; } } } public String getDescription ( Declaration declaration ) { if ( declaration == null ) { throw new IllegalArgumentException ( "" ) ; } AstDescription description = declaration . getDescription ( ) ; if ( description == null ) { return declaration . getName ( ) . identifier ; } else { return description . getText ( ) ; } } } package com . asakusafw . dmdl . java . spi ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . Type ; public abstract class JavaDataModelDriver { public void generateResources ( EmitContext context , ModelDeclaration model ) throws IOException { return ; } public List < Type > getInterfaces ( EmitContext context , ModelDeclaration model ) throws IOException { return Collections . emptyList ( ) ; } public List < FieldDeclaration > getFields ( EmitContext context , ModelDeclaration model ) throws IOException { return Collections . emptyList ( ) ; } public List < MethodDeclaration > getMethods ( EmitContext context , ModelDeclaration model ) throws IOException { return Collections . emptyList ( ) ; } public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) throws IOException { return Collections . emptyList ( ) ; } public List < Annotation > getMemberAnnotations ( EmitContext context , PropertyDeclaration property ) throws IOException { return Collections . emptyList ( ) ; } } package com . asakusafw . dmdl . java . spi ; package com . asakusafw . dmdl . java ; import java . io . IOException ; import java . util . Collection ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . java . emitter . JavaModelClassGenerator ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . util . AnalyzeTask ; public class GenerateTask { static final Logger LOG = LoggerFactory . getLogger ( GenerateTask . class ) ; private final Configuration conf ; public GenerateTask ( Configuration conf ) { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } this . conf = conf ; } public void process ( ) throws IOException { JavaDataModelDriver driver = new CompositeDataModelDriver ( conf . getServiceClassLoader ( ) ) ; process ( driver ) ; } public void process ( JavaDataModelDriver driver ) throws IOException { if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } DmdlSemantics semantics = analyze ( ) ; JavaModelClassGenerator generator = new JavaModelClassGenerator ( semantics , conf , driver ) ; Collection < ModelDeclaration > models = semantics . getDeclaredModels ( ) ; LOG . info ( "" , models . size ( ) ) ; for ( ModelDeclaration model : models ) { LOG . info ( "" , model . getName ( ) ) ; generator . emit ( model ) ; } LOG . info ( "" ) ; } private DmdlSemantics analyze ( ) throws IOException { AnalyzeTask analyzer = new AnalyzeTask ( "" , conf . getServiceClassLoader ( ) ) ; return analyzer . process ( conf . getSource ( ) ) ; } } package com . asakusafw . testdriver . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . URI ; import java . net . URL ; import java . util . Calendar ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . SpiVerifyRuleProvider ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . core . VerifyContext ; import com . asakusafw . testdriver . core . VerifyRule ; import com . asakusafw . testdriver . core . VerifyRuleProvider ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; import com . asakusafw . testdriver . rule . DataModelCondition ; public class ExcelSheetRuleProviderTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Test public void simple ( ) throws Exception { ExcelSheetRuleProvider provider = new ExcelSheetRuleProvider ( ) ; VerifyRule rule = provider . get ( SIMPLE , context ( ) , uri ( "" , "" ) ) ; assertThat ( rule , not ( nullValue ( ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , not ( equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; } @ Test public void integration ( ) throws Exception { ExcelSheetRuleProvider provider = new ExcelSheetRuleProvider ( ) ; VerifyRule rule = provider . get ( SIMPLE , context ( ) , uri ( "" , "" ) ) ; assertThat ( rule , not ( nullValue ( ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , not ( equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; } @ Test public void spi ( ) throws Exception { VerifyRuleProvider provider = new SpiVerifyRuleProvider ( ExcelSheetRuleProvider . class . getClassLoader ( ) ) ; VerifyRule rule = provider . get ( SIMPLE , context ( ) , uri ( "" , "" ) ) ; assertThat ( rule , not ( nullValue ( ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , not ( equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; } @ Test public void strict ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( null , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , null ) , not ( nullValue ( ) ) ) ; } @ Test public void ignore_absent ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( null , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , null ) , is ( nullValue ( ) ) ) ; } @ Test public void ignore_unexpected ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( null , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , null ) , not ( nullValue ( ) ) ) ; } @ Test public void intersect ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( null , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , null ) , is ( nullValue ( ) ) ) ; } @ Test public void skip ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( null , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , null ) , is ( nullValue ( ) ) ) ; } @ Test ( expected = IOException . class ) public void name_unknown ( ) throws Exception { rule ( "" ) ; } @ Test public void name_empty ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; } @ Test public void value_any ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( null , null ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( null , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , null ) , not ( nullValue ( ) ) ) ; } @ Test public void value_keys ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , not ( equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ) ; assertThat ( rule . getKey ( obj ( , "" ) ) , not ( equalTo ( rule . getKey ( obj ( , "" ) ) ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( null , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , null ) , not ( nullValue ( ) ) ) ; } @ Test public void value_equal ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; } @ Test public void value_contain ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; } @ Test ( expected = IOException . class ) public void value_contain_error ( ) throws Exception { rule ( "" ) ; } @ Test public void value_today ( ) throws Exception { VerifyContext context = context ( ) ; VerifyRule rule = rule ( "" , context ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( , , ) ; assertThat ( rule . verify ( obj ( , "" ) , date ( calendar ) ) , not ( nullValue ( ) ) ) ; calendar . set ( , , ) ; assertThat ( rule . verify ( obj ( , "" ) , date ( calendar ) ) , is ( nullValue ( ) ) ) ; calendar . set ( , , ) ; assertThat ( rule . verify ( obj ( , "" ) , date ( calendar ) ) , not ( nullValue ( ) ) ) ; calendar . set ( , , ) ; assertThat ( rule . verify ( obj ( , "" ) , date ( calendar ) ) , not ( nullValue ( ) ) ) ; } @ Test public void value_today_started_yesterday ( ) throws Exception { VerifyContext context = context ( ) ; VerifyRule rule = rule ( "" , context ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( , , ) ; assertThat ( rule . verify ( obj ( , "" ) , date ( calendar ) ) , not ( nullValue ( ) ) ) ; calendar . set ( , , ) ; assertThat ( rule . verify ( obj ( , "" ) , date ( calendar ) ) , is ( nullValue ( ) ) ) ; calendar . set ( , , ) ; assertThat ( rule . verify ( obj ( , "" ) , date ( calendar ) ) , is ( nullValue ( ) ) ) ; calendar . set ( , , ) ; assertThat ( rule . verify ( obj ( , "" ) , date ( calendar ) ) , not ( nullValue ( ) ) ) ; } @ Test ( expected = IOException . class ) public void value_today_error ( ) throws Exception { rule ( "" ) ; } @ Test public void value_now ( ) throws Exception { VerifyContext context = context ( ) ; VerifyRule rule = rule ( "" , context ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( , , , , , ) ; assertThat ( rule . verify ( obj ( , "" ) , datetime ( calendar ) ) , not ( nullValue ( ) ) ) ; calendar . set ( , , , , , ) ; assertThat ( rule . verify ( obj ( , "" ) , datetime ( calendar ) ) , not ( nullValue ( ) ) ) ; calendar . set ( , , , , , ) ; assertThat ( rule . verify ( obj ( , "" ) , datetime ( calendar ) ) , is ( nullValue ( ) ) ) ; calendar . set ( , , , , , ) ; assertThat ( rule . verify ( obj ( , "" ) , datetime ( calendar ) ) , is ( nullValue ( ) ) ) ; calendar . set ( , , , , , ) ; assertThat ( rule . verify ( obj ( , "" ) , datetime ( calendar ) ) , is ( nullValue ( ) ) ) ; calendar . set ( , , , , , ) ; assertThat ( rule . verify ( obj ( , "" ) , datetime ( calendar ) ) , not ( nullValue ( ) ) ) ; calendar . set ( , , , , , ) ; assertThat ( rule . verify ( obj ( , "" ) , datetime ( calendar ) ) , not ( nullValue ( ) ) ) ; } @ Test ( expected = IOException . class ) public void value_now_error ( ) throws Exception { rule ( "" ) ; } @ Test public void nullity_normal ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( null , "" ) , obj ( null , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( , null ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( null , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , null ) ) , is ( nullValue ( ) ) ) ; } @ Test public void nullity_AA ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , null ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( , null ) ) , is ( nullValue ( ) ) ) ; } @ Test public void nullity_AP ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , null ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( , null ) ) , not ( nullValue ( ) ) ) ; } @ Test public void nullity_DP ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( null , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( null , "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( null , null ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( null , null ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( , null ) ) , not ( nullValue ( ) ) ) ; } @ Test public void nullity_DA ( ) throws Exception { VerifyRule rule = rule ( "" ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( , "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , "" ) , obj ( , null ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( , null ) , obj ( , null ) ) , not ( nullValue ( ) ) ) ; assertThat ( rule . verify ( obj ( null , "" ) , obj ( null , "" ) ) , not ( nullValue ( ) ) ) ; } private DataModelReflection obj ( Integer number , String text ) { Simple simple = new Simple ( ) ; simple . number = number ; simple . text = text ; return SIMPLE . toReflection ( simple ) ; } private DataModelReflection date ( Calendar date ) { Simple simple = new Simple ( ) ; simple . dateValue = date ; return SIMPLE . toReflection ( simple ) ; } private DataModelReflection datetime ( Calendar dateTime ) { Simple simple = new Simple ( ) ; simple . datetimeValue = dateTime ; return SIMPLE . toReflection ( simple ) ; } private VerifyContext context ( int elapsedMinutes ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( , , , , , ) ; VerifyContext result = new VerifyContext ( new TestContext . Empty ( ) , calendar . getTime ( ) ) ; calendar . add ( Calendar . MINUTE , elapsedMinutes ) ; result . setTestFinished ( calendar . getTime ( ) ) ; return result ; } private URI uri ( String file , String fragment ) throws Exception { URL url = getClass ( ) . getResource ( file ) ; assertThat ( file , url , not ( nullValue ( ) ) ) ; URI resource = url . toURI ( ) ; URI uri = new URI ( resource . getScheme ( ) , resource . getUserInfo ( ) , resource . getHost ( ) , resource . getPort ( ) , resource . getPath ( ) , resource . getQuery ( ) , fragment ) ; return uri ; } private VerifyRule rule ( String name ) throws Exception { return rule ( name , context ( ) ) ; } private VerifyRule rule ( String name , VerifyContext context ) throws Exception { assert name != null ; ExcelSheetRuleProvider provider = new ExcelSheetRuleProvider ( ) ; VerifyRule rule = provider . get ( SIMPLE , context , uri ( name , "" ) ) ; assertThat ( rule , not ( nullValue ( ) ) ) ; return rule ; } } package com . asakusafw . testdriver . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . util . EnumSet ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . Sheet ; import org . apache . poi . ss . usermodel . Workbook ; import org . junit . Test ; import com . asakusafw . testdriver . rule . DataModelCondition ; public class DefaultExcelRuleExtractorTest { @ Test public void supports ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . supports ( sheet ) , is ( true ) ) ; } @ Test public void supports_not ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . supports ( sheet ) , is ( false ) ) ; } @ Test public void supports_invalid_version ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . supports ( sheet ) , is ( false ) ) ; } @ Test public void extractDataModelCondition_strict ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractDataModelCondition ( sheet ) , is ( ( Object ) EnumSet . noneOf ( DataModelCondition . class ) ) ) ; } @ Test public void extractDataModelCondition_expect ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractDataModelCondition ( sheet ) , is ( ( Object ) EnumSet . of ( DataModelCondition . IGNORE_UNEXPECTED ) ) ) ; } @ Test public void extractDataModelCondition_actual ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractDataModelCondition ( sheet ) , is ( ( Object ) EnumSet . of ( DataModelCondition . IGNORE_ABSENT ) ) ) ; } @ Test public void extractDataModelCondition_intersect ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractDataModelCondition ( sheet ) , is ( ( Object ) EnumSet . of ( DataModelCondition . IGNORE_UNEXPECTED , DataModelCondition . IGNORE_ABSENT ) ) ) ; } @ Test public void extractDataModelCondition_skip ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractDataModelCondition ( sheet ) , is ( ( Object ) EnumSet . allOf ( DataModelCondition . class ) ) ) ; } @ Test public void extractPropertyRowStartIndex ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractPropertyRowStartIndex ( sheet ) , is ( ) ) ; } @ Test public void extractName ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( "" ) ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( "" ) ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( "" ) ) ; } @ Test public void extractName_empty ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( nullValue ( ) ) ) ; } @ Test public void extractName_blank ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( nullValue ( ) ) ) ; } @ Test public void extractValueCondition ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . ANY ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . KEY ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . EQUAL ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . CONTAIN ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . TODAY ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . NOW ) ) ; } @ Test public void extractNullityCondition ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . NORMAL ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . ACCEPT_ABSENT ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . DENY_ABSENT ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . ACCEPT_PRESENT ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . DENY_PRESENT ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractDataModelCondition_unknown ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractDataModelCondition ( sheet ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractDataModelCondition_blank ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractDataModelCondition ( sheet ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractDataModelCondition_invalid ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractDataModelCondition ( sheet ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractDataModelCondition_missing ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractDataModelCondition ( sheet ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractName_invalid ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractName ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractValueCondition_unknown ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractValueCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractValueCondition_empty ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractValueCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractValueCondition_blank ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractValueCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractValueCondition_invalid ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractValueCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractNullityCondition_unknown ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractNullityCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractNullityCondition_empty ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractNullityCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractNullityCondition_blank ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractNullityCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractNullityCondition_invalid ( ) throws Exception { ExcelRuleExtractor extractor = new DefaultExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractNullityCondition ( sheet . getRow ( ) ) ; } private Sheet sheet ( String name ) { InputStream in = getClass ( ) . getResourceAsStream ( "" + name ) ; assertThat ( name , in , not ( nullValue ( ) ) ) ; try { Workbook book = new HSSFWorkbook ( in ) ; return book . getSheetAt ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } finally { try { in . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } } package com . asakusafw . testdriver . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . URI ; import java . net . URL ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . DataModelSourceProvider ; import com . asakusafw . testdriver . core . SpiDataModelSourceProvider ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class ExcelSheetSourceProviderTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Test public void open_bynumber ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , "" ) ; DataModelSource source = provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; assertThat ( source , not ( nullValue ( ) ) ) ; Simple s1 = next ( source ) ; assertThat ( s1 . number , is ( ) ) ; assertThat ( s1 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void open_byname ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , "" ) ; DataModelSource source = provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; assertThat ( source , not ( nullValue ( ) ) ) ; Simple s1 = next ( source ) ; assertThat ( s1 . number , is ( ) ) ; assertThat ( s1 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void spi ( ) throws Exception { DataModelSourceProvider provider = new SpiDataModelSourceProvider ( ExcelSheetSourceProvider . class . getClassLoader ( ) ) ; URI uri = uri ( "" , "" ) ; DataModelSource source = provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; assertThat ( source , not ( nullValue ( ) ) ) ; Simple s1 = next ( source ) ; assertThat ( s1 . number , is ( ) ) ; assertThat ( s1 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void integration ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , "" ) ; DataModelSource source = provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; assertThat ( source , not ( nullValue ( ) ) ) ; Simple s1 = next ( source ) ; assertThat ( s1 . number , is ( ) ) ; assertThat ( s1 . text , is ( "" ) ) ; Simple s2 = next ( source ) ; assertThat ( s2 . number , is ( ) ) ; assertThat ( s2 . text , is ( "" ) ) ; Simple s3 = next ( source ) ; assertThat ( s3 . number , is ( ) ) ; assertThat ( s3 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void invalid_file ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , "" ) ; DataModelSource source = provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; assertThat ( source , is ( nullValue ( ) ) ) ; } @ Test public void missing_fragment ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , null ) ; DataModelSource source = provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; assertThat ( source , not ( nullValue ( ) ) ) ; Simple s1 = next ( source ) ; assertThat ( s1 . number , is ( ) ) ; assertThat ( s1 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void invalid_fragment ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , "" ) ; DataModelSource source = provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; assertThat ( source , is ( nullValue ( ) ) ) ; } @ Test ( expected = IOException . class ) public void not_found ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = new URI ( "" ) ; provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; } @ Test ( expected = IOException . class ) public void invalid_workbook ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , "" ) ; provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; } @ Test ( expected = IOException . class ) public void invalid_sheet_bynumber ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , "" ) ; provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; } @ Test ( expected = IOException . class ) public void invalid_sheet_byname ( ) throws Exception { ExcelSheetSourceProvider provider = new ExcelSheetSourceProvider ( ) ; URI uri = uri ( "" , "" ) ; provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; } private Simple next ( DataModelSource source ) throws IOException { DataModelReflection next = source . next ( ) ; assertThat ( next , is ( not ( nullValue ( ) ) ) ) ; return SIMPLE . toObject ( next ) ; } private void end ( DataModelSource source ) throws IOException { DataModelReflection next = source . next ( ) ; assertThat ( String . valueOf ( next ) , next , nullValue ( ) ) ; source . close ( ) ; } private URI uri ( String file , String fragment ) throws Exception { URL url = getClass ( ) . getResource ( file ) ; assertThat ( file , url , not ( nullValue ( ) ) ) ; URI resource = url . toURI ( ) ; URI uri = new URI ( resource . getScheme ( ) , resource . getUserInfo ( ) , resource . getHost ( ) , resource . getPort ( ) , resource . getPath ( ) , resource . getQuery ( ) , fragment ) ; return uri ; } } package com . asakusafw . testdriver . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . Row ; import org . apache . poi . ss . usermodel . Sheet ; import org . apache . poi . ss . usermodel . Workbook ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSink ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class ExcelSheetSinkTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { verify ( "" ) ; } @ Test public void create_folder ( ) throws Exception { File container = folder . newFolder ( "" ) ; File file = new File ( container , "" ) ; assertThat ( container . delete ( ) , is ( true ) ) ; assertThat ( file . isFile ( ) , is ( false ) ) ; ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory ( file ) ; DataModelSink sink = factory . createSink ( SIMPLE , new TestContext . Empty ( ) ) ; try { sink . put ( SIMPLE . toReflection ( new Simple ( ) ) ) ; } finally { sink . close ( ) ; } assertThat ( file . isFile ( ) , is ( true ) ) ; } @ Test public void multiple ( ) throws Exception { verify ( "" ) ; } @ Test public void blank_cell ( ) throws Exception { verify ( "" ) ; } @ Test public void stringify ( ) throws Exception { verify ( "" ) ; } @ Test public void empty_string ( ) throws Exception { verify ( "" ) ; } @ Test public void boolean_values ( ) throws Exception { verify ( "" ) ; } @ Test public void byte_values ( ) throws Exception { verify ( "" ) ; } @ Test public void short_values ( ) throws Exception { verify ( "" ) ; } @ Test public void int_values ( ) throws Exception { verify ( "" ) ; } @ Test public void long_values ( ) throws Exception { verify ( "" ) ; } @ Test public void float_values ( ) throws Exception { verify ( "" ) ; } @ Test public void double_values ( ) throws Exception { verify ( "" ) ; } @ Test public void integer_values ( ) throws Exception { verify ( "" ) ; } @ Test public void decimal_values ( ) throws Exception { verify ( "" ) ; } @ Test public void date_values ( ) throws Exception { verify ( "" ) ; } @ Test public void datetime_values ( ) throws Exception { verify ( "" ) ; } @ Test public void blank_row ( ) throws Exception { verify ( "" ) ; } @ Test public void decorated_blank_row ( ) throws Exception { verify ( "" ) ; } @ Test public void many_columns ( ) throws Exception { Object [ ] value = new Object [ ] ; Map < PropertyName , PropertyType > map = new TreeMap < PropertyName , PropertyType > ( ) ; for ( int i = ; i < value . length ; i ++ ) { map . put ( PropertyName . newInstance ( String . format ( "" , i ) ) , PropertyType . INT ) ; value [ i ] = i ; } ArrayModelDefinition def = new ArrayModelDefinition ( map ) ; File file = folder . newFile ( "" ) ; ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory ( file ) ; DataModelSink sink = factory . createSink ( def , new TestContext . Empty ( ) ) ; try { sink . put ( def . toReflection ( value ) ) ; } finally { sink . close ( ) ; } InputStream in = new FileInputStream ( file ) ; try { Workbook workbook = new HSSFWorkbook ( in ) ; Sheet sheet = workbook . getSheetAt ( ) ; Row title = sheet . getRow ( ) ; assertThat ( title . getLastCellNum ( ) , is ( ( short ) ) ) ; Row content = sheet . getRow ( ) ; for ( int i = ; i < title . getLastCellNum ( ) ; i ++ ) { assertThat ( content . getCell ( i ) . getNumericCellValue ( ) , is ( ( double ) ( Integer ) value [ i ] ) ) ; } } finally { in . close ( ) ; } } private void verify ( String file ) throws IOException { Set < DataModelReflection > expected = collect ( open ( file ) ) ; File temp = folder . newFile ( "" ) ; ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory ( temp ) ; DataModelSink sink = factory . createSink ( SIMPLE , new TestContext . Empty ( ) ) ; try { for ( DataModelReflection model : expected ) { sink . put ( model ) ; } } finally { sink . close ( ) ; } Set < DataModelReflection > actual = collect ( open ( temp . toURI ( ) . toURL ( ) ) ) ; assertThat ( actual , is ( expected ) ) ; } private Set < DataModelReflection > collect ( ExcelSheetDataModelSource source ) throws IOException { Set < DataModelReflection > results = new HashSet < DataModelReflection > ( ) ; try { while ( true ) { DataModelReflection next = source . next ( ) ; if ( next == null ) { break ; } assertThat ( next . toString ( ) , results . contains ( source ) , is ( false ) ) ; results . add ( next ) ; } } finally { source . close ( ) ; } return results ; } private ExcelSheetDataModelSource open ( String file ) throws IOException { URL resource = getClass ( ) . getResource ( "" + file ) ; assertThat ( file , resource , not ( nullValue ( ) ) ) ; return open ( resource ) ; } private ExcelSheetDataModelSource open ( URL resource ) throws AssertionError , IOException { URI uri ; try { uri = resource . toURI ( ) ; } catch ( URISyntaxException e ) { throw new AssertionError ( e ) ; } InputStream in = resource . openStream ( ) ; try { HSSFWorkbook book = new HSSFWorkbook ( in ) ; Sheet sheet = book . getSheetAt ( ) ; return new ExcelSheetDataModelSource ( SIMPLE , uri , sheet ) ; } finally { in . close ( ) ; } } } package com . asakusafw . testdriver . excel ; import java . lang . annotation . Annotation ; import java . util . Collection ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . Map ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; public class ArrayModelDefinition implements DataModelDefinition < Object [ ] > { private final Map < PropertyName , PropertyType > nameAndTypes ; public ArrayModelDefinition ( Map < PropertyName , PropertyType > nameAndTypes ) { if ( nameAndTypes == null ) { throw new IllegalArgumentException ( "" ) ; } this . nameAndTypes = Collections . unmodifiableMap ( new LinkedHashMap < PropertyName , PropertyType > ( nameAndTypes ) ) ; } @ Override public Class < Object [ ] > getModelClass ( ) { return Object [ ] . class ; } @ Override public < A extends Annotation > A getAnnotation ( Class < A > annotationType ) { return null ; } @ Override public Collection < PropertyName > getProperties ( ) { return nameAndTypes . keySet ( ) ; } @ Override public PropertyType getType ( PropertyName name ) { return nameAndTypes . get ( name ) ; } @ Override public < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) { return null ; } @ Override public DataModelDefinition . Builder < Object [ ] > newReflection ( ) { return new Builder < Object [ ] > ( this ) ; } @ Override public DataModelReflection toReflection ( Object [ ] object ) { int index = ; DataModelDefinition . Builder < Object [ ] > builder = newReflection ( ) ; for ( PropertyName name : nameAndTypes . keySet ( ) ) { builder . add ( name , object [ index ] ) ; if ( ++ index >= object . length ) { break ; } } return builder . build ( ) ; } @ Override public Object [ ] toObject ( DataModelReflection reflection ) { Object [ ] result = new Object [ nameAndTypes . size ( ) ] ; int index = ; for ( Map . Entry < PropertyName , PropertyType > entry : nameAndTypes . entrySet ( ) ) { Object value = reflection . getValue ( entry . getKey ( ) ) ; result [ index ++ ] = value ; } return result ; } } package com . asakusafw . testdriver . excel . legacy ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . util . EnumSet ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . Sheet ; import org . apache . poi . ss . usermodel . Workbook ; import org . junit . Test ; import com . asakusafw . testdriver . excel . ExcelRuleExtractor ; import com . asakusafw . testdriver . excel . NullityConditionKind ; import com . asakusafw . testdriver . excel . ValueConditionKind ; import com . asakusafw . testdriver . rule . DataModelCondition ; public class LegacyExcelRuleExtractorTest { @ Test public void supports ( ) { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . supports ( sheet ) , is ( true ) ) ; } @ Test public void supports_not ( ) { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . supports ( sheet ) , is ( false ) ) ; } @ Test public void extractDataModelCondition_ignore ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractDataModelCondition ( sheet ) , is ( ( Object ) EnumSet . allOf ( DataModelCondition . class ) ) ) ; } @ Test public void extractDataModelCondition_strict ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractDataModelCondition ( sheet ) , is ( ( Object ) EnumSet . noneOf ( DataModelCondition . class ) ) ) ; } @ Test public void extractDataModelCondition_partial ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractDataModelCondition ( sheet ) , is ( ( Object ) EnumSet . of ( DataModelCondition . IGNORE_UNEXPECTED ) ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractDataModelCondition_invalid ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractDataModelCondition ( sheet ) ; } @ Test public void extractPropertyRowStartIndex ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractPropertyRowStartIndex ( sheet ) , is ( ) ) ; } @ Test public void extractName ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( "" ) ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( "" ) ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( "" ) ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( "" ) ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( "" ) ) ; } @ Test public void extractName_empty ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( nullValue ( ) ) ) ; assertThat ( extractor . extractName ( sheet . getRow ( ) ) , is ( nullValue ( ) ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractName_invalid ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractName ( sheet . getRow ( ) ) ; } @ Test public void extractValueCondition ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . ANY ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . EQUAL ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . CONTAIN ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . NOW ) ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . TODAY ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractValueCondition_unknown ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractValueCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractValueCondition_empty ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractValueCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractValueCondition_invalid_type ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractValueCondition ( sheet . getRow ( ) ) ; } @ Test public void extractValueCondition_key ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . KEY ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . NORMAL ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractValueCondition_key_invalid_type ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractValueCondition ( sheet . getRow ( ) ) ; } @ Test public void extractValueCondition_key_unknown ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractValueCondition ( sheet . getRow ( ) ) , is ( ValueConditionKind . KEY ) ) ; } @ Test public void extractNullityCondition ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . NORMAL ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . ACCEPT_ABSENT ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . DENY_ABSENT ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . ACCEPT_PRESENT ) ) ; assertThat ( extractor . extractNullityCondition ( sheet . getRow ( ) ) , is ( NullityConditionKind . DENY_PRESENT ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractNullityCondition_unknown ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractNullityCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractNullityCondition_blank ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractNullityCondition ( sheet . getRow ( ) ) ; } @ Test ( expected = ExcelRuleExtractor . FormatException . class ) public void extractNullityCondition_invalid_type ( ) throws Exception { ExcelRuleExtractor extractor = new LegacyExcelRuleExtractor ( ) ; Sheet sheet = sheet ( "" ) ; extractor . extractNullityCondition ( sheet . getRow ( ) ) ; } private Sheet sheet ( String name ) { InputStream in = getClass ( ) . getResourceAsStream ( name ) ; assertThat ( name , in , not ( nullValue ( ) ) ) ; try { Workbook book = new HSSFWorkbook ( in ) ; return book . getSheetAt ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } finally { try { in . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } } package com . asakusafw . testdriver . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . math . BigDecimal ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . util . Calendar ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . Sheet ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class ExcelSheetDataModelSourceTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Test public void simple ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple simple = next ( source ) ; assertThat ( simple . number , is ( ) ) ; assertThat ( simple . text , is ( "" ) ) ; end ( source ) ; } @ Test public void multiple ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . number , is ( ) ) ; assertThat ( r1 . text , is ( "" ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . number , is ( ) ) ; assertThat ( r2 . text , is ( "" ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . number , is ( ) ) ; assertThat ( r3 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void blank_cell ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . number , is ( ) ) ; assertThat ( r1 . text , is ( nullValue ( ) ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . number , is ( nullValue ( ) ) ) ; assertThat ( r2 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void stringify ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . number , is ( ) ) ; assertThat ( r1 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void empty_string ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void boolean_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . booleanValue , is ( true ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . booleanValue , is ( false ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . booleanValue , is ( true ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . booleanValue , is ( false ) ) ; end ( source ) ; } @ Test public void byte_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . byteValue , is ( Byte . MIN_VALUE ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . byteValue , is ( Byte . MAX_VALUE ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . byteValue , is ( ( byte ) - ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . byteValue , is ( ( byte ) + ) ) ; end ( source ) ; } @ Test public void short_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . shortValue , is ( Short . MIN_VALUE ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . shortValue , is ( Short . MAX_VALUE ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . shortValue , is ( ( short ) - ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . shortValue , is ( ( short ) + ) ) ; end ( source ) ; } @ Test public void int_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . number , is ( Integer . MIN_VALUE ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . number , is ( Integer . MAX_VALUE ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . number , is ( - ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . number , is ( + ) ) ; end ( source ) ; } @ Test public void long_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . longValue , is ( - ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . longValue , is ( + ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . longValue , is ( Long . MIN_VALUE ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . longValue , is ( Long . MAX_VALUE ) ) ; end ( source ) ; } @ Test public void float_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . floatValue , is ( - ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . floatValue , is ( + ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . floatValue , is ( - ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . floatValue , is ( + ) ) ; end ( source ) ; } @ Test public void double_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . doubleValue , is ( - ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . doubleValue , is ( + ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . doubleValue , is ( - ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . doubleValue , is ( + ) ) ; end ( source ) ; } @ Test public void integer_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . bigIntegerValue , is ( dec ( - ) . toBigInteger ( ) ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . bigIntegerValue , is ( dec ( + ) . toBigInteger ( ) ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . bigIntegerValue , is ( dec ( Long . MIN_VALUE ) . subtract ( BigDecimal . ONE ) . toBigInteger ( ) ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . bigIntegerValue , is ( dec ( Long . MAX_VALUE ) . add ( BigDecimal . ONE ) . toBigInteger ( ) ) ) ; end ( source ) ; } @ Test public void decimal_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . bigDecimalValue , is ( dec ( - ) ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . bigDecimalValue , is ( dec ( + ) ) ) ; Simple r3 = next ( source ) ; assertThat ( r3 . bigDecimalValue , is ( dec ( + ) ) ) ; Simple r4 = next ( source ) ; assertThat ( r4 . bigDecimalValue , is ( new BigDecimal ( "" ) ) ) ; end ( source ) ; } @ Test public void date_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . dateValue , is ( date ( , , ) ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . dateValue , is ( date ( , , ) ) ) ; end ( source ) ; } private Calendar date ( int year , int month , int date ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( year , month - , date ) ; return calendar ; } @ Test public void datetime_values ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . datetimeValue , is ( datetime ( , , , , , ) ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . datetimeValue , is ( datetime ( , , , , , ) ) ) ; end ( source ) ; } private Calendar datetime ( int year , int month , int date , int hour , int minute , int second ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( year , month - , date , hour , minute , second ) ; return calendar ; } private BigDecimal dec ( long value ) { return new BigDecimal ( value ) ; } private BigDecimal dec ( double value ) { return new BigDecimal ( value ) ; } @ Test ( expected = IOException . class ) public void boolean_error ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; next ( source ) ; } @ Test ( expected = IOException . class ) public void number_outofrange ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; next ( source ) ; } @ Test ( expected = IOException . class ) public void long_outofrange ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; next ( source ) ; } @ Test ( expected = IOException . class ) public void number_error ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; next ( source ) ; } @ Test ( expected = IOException . class ) public void double_error ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; next ( source ) ; } @ Test ( expected = IOException . class ) public void decimal_error ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; next ( source ) ; } @ Test ( expected = IOException . class ) public void string_error ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; next ( source ) ; } @ Test ( expected = IOException . class ) public void date_error ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; next ( source ) ; } @ Test public void blank_row ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . number , is ( ) ) ; assertThat ( r1 . text , is ( "" ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . number , is ( ) ) ; assertThat ( r2 . text , is ( "" ) ) ; end ( source ) ; } @ Test public void decorated_blank_row ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; Simple r1 = next ( source ) ; assertThat ( r1 . number , is ( ) ) ; assertThat ( r1 . text , is ( "" ) ) ; Simple r2 = next ( source ) ; assertThat ( r2 . number , is ( ) ) ; assertThat ( r2 . text , is ( "" ) ) ; end ( source ) ; } @ Test ( expected = IOException . class ) public void blank_sheet ( ) throws Exception { open ( "" ) ; } @ Test ( expected = IOException . class ) public void decorated_blank_sheet ( ) throws Exception { open ( "" ) ; } @ Test ( expected = IOException . class ) public void invalid_header ( ) throws Exception { open ( "" ) ; } @ Test ( expected = IOException . class ) public void unknown_property ( ) throws Exception { open ( "" ) ; } @ Test ( expected = IOException . class ) public void formula ( ) throws Exception { ExcelSheetDataModelSource source = open ( "" ) ; source . next ( ) ; } private ExcelSheetDataModelSource open ( String file ) throws IOException { URL resource = getClass ( ) . getResource ( "" + file ) ; assertThat ( file , resource , not ( nullValue ( ) ) ) ; URI uri ; try { uri = resource . toURI ( ) ; } catch ( URISyntaxException e ) { throw new AssertionError ( e ) ; } InputStream in = resource . openStream ( ) ; try { HSSFWorkbook book = new HSSFWorkbook ( in ) ; Sheet sheet = book . getSheetAt ( ) ; return new ExcelSheetDataModelSource ( SIMPLE , uri , sheet ) ; } finally { in . close ( ) ; } } private Simple next ( ExcelSheetDataModelSource source ) throws IOException { DataModelReflection next = source . next ( ) ; assertThat ( next , is ( not ( nullValue ( ) ) ) ) ; return SIMPLE . toObject ( next ) ; } private void end ( ExcelSheetDataModelSource source ) throws IOException { DataModelReflection next = source . next ( ) ; assertThat ( String . valueOf ( next ) , next , nullValue ( ) ) ; source . close ( ) ; } } package com . asakusafw . testdriver . excel ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . util . Calendar ; public class Simple { public Integer number ; public String text ; public Boolean booleanValue ; public Byte byteValue ; public Short shortValue ; public Long longValue ; public BigInteger bigIntegerValue ; public Float floatValue ; public Double doubleValue ; public BigDecimal bigDecimalValue ; public Calendar dateValue ; public Calendar datetimeValue ; } package com . asakusafw . testdriver . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSink ; import com . asakusafw . testdriver . core . DataModelSinkFactory ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . core . TestToolRepository ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class ExcelSheetSinkProviderTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Rule public final TemporaryFolder temp = new TemporaryFolder ( ) ; @ Test public void spi ( ) throws Exception { TestToolRepository repo = new TestToolRepository ( getClass ( ) . getClassLoader ( ) ) ; File file = temp . newFile ( "" ) ; file . delete ( ) ; DataModelSinkFactory factory = repo . getDataModelSinkFactory ( file . toURI ( ) ) ; DataModelSink sink = factory . createSink ( SIMPLE , new TestContext . Empty ( ) ) ; try { Simple model = new Simple ( ) ; model . text = "" ; sink . put ( SIMPLE . toReflection ( model ) ) ; } finally { sink . close ( ) ; } assertThat ( file . exists ( ) , is ( true ) ) ; } @ Test public void spi_wrong_extension ( ) throws Exception { TestToolRepository repo = new TestToolRepository ( getClass ( ) . getClassLoader ( ) ) ; File file = temp . newFile ( "" ) ; file . delete ( ) ; DataModelSinkFactory factory = repo . getDataModelSinkFactory ( file . toURI ( ) ) ; try { DataModelSink sink = factory . createSink ( SIMPLE , new TestContext . Empty ( ) ) ; sink . close ( ) ; fail ( ) ; } catch ( IOException e ) { } } } package com . asakusafw . testdriver . html ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . util . Calendar ; public class Simple { public Integer number ; public String text ; public Boolean booleanValue ; public Byte byteValue ; public Short shortValue ; public Long longValue ; public BigInteger bigIntegerValue ; public Float floatValue ; public Double doubleValue ; public BigDecimal bigDecimalValue ; public Calendar dateValue ; public Calendar datetimeValue ; } package com . asakusafw . testdriver . html ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . Difference ; import com . asakusafw . testdriver . core . DifferenceSink ; import com . asakusafw . testdriver . core . DifferenceSinkFactory ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . core . TestToolRepository ; import com . asakusafw . testdriver . excel . Simple ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class HtmlDifferenceSinkProviderTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Rule public final TemporaryFolder temp = new TemporaryFolder ( ) ; @ Test public void spi ( ) throws Exception { TestToolRepository repo = new TestToolRepository ( getClass ( ) . getClassLoader ( ) ) ; File file = temp . newFile ( "" ) ; file . delete ( ) ; DifferenceSinkFactory factory = repo . getDifferenceSinkFactory ( file . toURI ( ) ) ; DifferenceSink sink = factory . createSink ( SIMPLE , new TestContext . Empty ( ) ) ; try { Simple expected = new Simple ( ) ; expected . text = "" ; Simple actual = new Simple ( ) ; actual . text = "" ; sink . put ( new Difference ( SIMPLE . toReflection ( expected ) , SIMPLE . toReflection ( actual ) , "" ) ) ; } finally { sink . close ( ) ; } assertThat ( file . exists ( ) , is ( true ) ) ; } @ Test public void spi_wrong_extension ( ) throws Exception { TestToolRepository repo = new TestToolRepository ( getClass ( ) . getClassLoader ( ) ) ; File file = temp . newFile ( "" ) ; file . delete ( ) ; DifferenceSinkFactory factory = repo . getDifferenceSinkFactory ( file . toURI ( ) ) ; try { DifferenceSink sink = factory . createSink ( SIMPLE , new TestContext . Empty ( ) ) ; sink . close ( ) ; fail ( ) ; } catch ( IOException e ) { } } } package com . asakusafw . testdriver . json ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; import com . google . gson . JsonObject ; public class JsonObjectDriverTest { @ Test public void simple ( ) throws Exception { DataModelDefinition < Simple > def = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; JsonObject json = new JsonObject ( ) ; json . addProperty ( "" , ) ; json . addProperty ( "" , "" ) ; DataModelReflection ref = JsonObjectDriver . convert ( def , json ) ; Simple object = def . toObject ( ref ) ; assertThat ( object . number , is ( ) ) ; assertThat ( object . text , is ( "" ) ) ; } @ Test public void invalid_property ( ) throws Exception { DataModelDefinition < Simple > def = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; JsonObject json = new JsonObject ( ) ; json . addProperty ( "" , ) ; json . addProperty ( "" , "" ) ; DataModelReflection ref = JsonObjectDriver . convert ( def , json ) ; Simple object = def . toObject ( ref ) ; assertThat ( object . number , is ( nullValue ( ) ) ) ; assertThat ( object . text , is ( "" ) ) ; } @ Test ( expected = IOException . class ) public void inconsistent_type ( ) throws Exception { DataModelDefinition < Simple > def = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; JsonObject json = new JsonObject ( ) ; json . addProperty ( "" , "" ) ; json . addProperty ( "" , "" ) ; JsonObjectDriver . convert ( def , json ) ; } @ Test public void types ( ) throws Exception { DataModelDefinition < Simple > def = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; JsonObject json = new JsonObject ( ) ; json . addProperty ( "" , true ) ; json . addProperty ( "" , ( byte ) ) ; json . addProperty ( "" , ( short ) ) ; json . addProperty ( "" , ) ; json . addProperty ( "" , new BigInteger ( "" ) ) ; json . addProperty ( "" , ) ; json . addProperty ( "" , ) ; json . addProperty ( "" , new BigDecimal ( "" ) ) ; json . addProperty ( "" , "" ) ; json . addProperty ( "" , "" ) ; DataModelReflection ref = JsonObjectDriver . convert ( def , json ) ; Simple object = def . toObject ( ref ) ; assertThat ( object . booleanValue , is ( true ) ) ; assertThat ( object . byteValue , is ( ( byte ) ) ) ; assertThat ( object . shortValue , is ( ( short ) ) ) ; assertThat ( object . longValue , is ( ) ) ; assertThat ( object . bigIntegerValue , is ( new BigInteger ( "" ) ) ) ; assertThat ( object . floatValue , is ( ) ) ; assertThat ( object . doubleValue , is ( ) ) ; assertThat ( object . bigDecimalValue , is ( new BigDecimal ( "" ) ) ) ; assertThat ( object . dateValue , is ( calendar ( "" , "" ) ) ) ; assertThat ( object . datetimeValue , is ( calendar ( "" , "" ) ) ) ; } private Matcher < Calendar > calendar ( final String format , final String value ) { return new BaseMatcher < Calendar > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Calendar ) { Calendar c = ( Calendar ) object ; String actual = new SimpleDateFormat ( format ) . format ( c . getTime ( ) ) ; return value . equals ( actual ) ; } return false ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( value ) ; } } ; } } package com . asakusafw . testdriver . json ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStreamReader ; import java . net . URL ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class JsonDataModelSourceTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Test public void simple ( ) throws Exception { JsonDataModelSource source = open ( "" ) ; try { Simple s1 = SIMPLE . toObject ( source . next ( ) ) ; assertThat ( s1 . number , is ( ) ) ; assertThat ( source . next ( ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void multiple ( ) throws Exception { JsonDataModelSource source = open ( "" ) ; try { Simple s1 = SIMPLE . toObject ( source . next ( ) ) ; assertThat ( s1 . number , is ( ) ) ; Simple s2 = SIMPLE . toObject ( source . next ( ) ) ; assertThat ( s2 . number , is ( nullValue ( ) ) ) ; assertThat ( s2 . text , is ( "" ) ) ; Simple s3 = SIMPLE . toObject ( source . next ( ) ) ; assertThat ( s3 . booleanValue , is ( true ) ) ; assertThat ( s3 . doubleValue , is ( ) ) ; assertThat ( source . next ( ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test ( expected = IOException . class ) public void malform ( ) throws Exception { JsonDataModelSource source = open ( "" ) ; source . next ( ) ; } private JsonDataModelSource open ( String name ) { URL resource = getClass ( ) . getResource ( name + "" ) ; assertThat ( name , resource , not ( nullValue ( ) ) ) ; try { return new JsonDataModelSource ( resource . toURI ( ) , SIMPLE , new InputStreamReader ( resource . openStream ( ) , "" ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . testdriver . json ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import java . net . URL ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . DataModelSourceProvider ; import com . asakusafw . testdriver . core . SpiDataModelSourceProvider ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class JsonSourceProviderTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Test public void simple ( ) throws Exception { JsonSourceProvider provider = new JsonSourceProvider ( ) ; DataModelSource source = provider . open ( SIMPLE , uri ( "" ) , new TestContext . Empty ( ) ) ; assertThat ( source , not ( nullValue ( ) ) ) ; try { Simple s1 = SIMPLE . toObject ( source . next ( ) ) ; assertThat ( s1 . number , is ( ) ) ; assertThat ( source . next ( ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void spi ( ) throws Exception { DataModelSourceProvider provider = new SpiDataModelSourceProvider ( JsonSourceProvider . class . getClassLoader ( ) ) ; DataModelSource source = provider . open ( SIMPLE , uri ( "" ) , new TestContext . Empty ( ) ) ; assertThat ( source , not ( nullValue ( ) ) ) ; try { Simple s1 = SIMPLE . toObject ( source . next ( ) ) ; assertThat ( s1 . number , is ( ) ) ; assertThat ( source . next ( ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void invalid_extension ( ) throws Exception { JsonSourceProvider provider = new JsonSourceProvider ( ) ; DataModelSource source = provider . open ( SIMPLE , uri ( "" ) , new TestContext . Empty ( ) ) ; assertThat ( source , is ( nullValue ( ) ) ) ; } @ Test ( expected = IOException . class ) public void not_found ( ) throws Exception { URI uri ; try { File file = File . createTempFile ( "" , "" ) ; file . delete ( ) ; uri = file . toURI ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } JsonSourceProvider provider = new JsonSourceProvider ( ) ; provider . open ( SIMPLE , uri , new TestContext . Empty ( ) ) ; } private URI uri ( String name ) { URL resource = getClass ( ) . getResource ( name ) ; assertThat ( name , resource , not ( nullValue ( ) ) ) ; try { return resource . toURI ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . testdriver . json ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . util . Calendar ; public class Simple { public Integer number ; public String text ; public Boolean booleanValue ; public Byte byteValue ; public Short shortValue ; public Long longValue ; public BigInteger bigIntegerValue ; public Float floatValue ; public Double doubleValue ; public BigDecimal bigDecimalValue ; public Calendar dateValue ; public Calendar datetimeValue ; } package com . asakusafw . testdriver . json ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Calendar ; import java . util . Iterator ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelDefinition . Builder ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelScanner ; import com . asakusafw . testdriver . core . PropertyName ; import com . google . gson . JsonElement ; import com . google . gson . JsonObject ; public final class JsonObjectDriver extends DataModelScanner < JsonObject , IOException > { private final Builder < ? > builder ; private JsonObjectDriver ( Builder < ? > builder ) { assert builder != null ; this . builder = builder ; } public static DataModelReflection convert ( DataModelDefinition < ? > definition , JsonElement element ) throws IOException { if ( ( element instanceof JsonObject ) == false ) { throw new IOException ( MessageFormat . format ( "" , element ) ) ; } JsonObjectDriver driver = new JsonObjectDriver ( definition . newReflection ( ) ) ; try { driver . scan ( definition , ( JsonObject ) element ) ; } catch ( RuntimeException e ) { throw new IOException ( MessageFormat . format ( "" , element ) , e ) ; } return driver . builder . build ( ) ; } private JsonElement property ( JsonObject context , PropertyName name ) { assert context != null ; assert name != null ; String jsName = toJsName ( name ) ; JsonElement element = context . get ( jsName ) ; return element ; } String toJsName ( PropertyName name ) { assert name != null ; StringBuilder buf = new StringBuilder ( ) ; Iterator < String > iterator = name . getWords ( ) . iterator ( ) ; assert iterator . hasNext ( ) ; buf . append ( iterator . next ( ) ) ; while ( iterator . hasNext ( ) ) { buf . append ( '' ) ; buf . append ( iterator . next ( ) ) ; } return buf . toString ( ) ; } @ Override public void booleanProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsBoolean ( ) ) ; } @ Override public void byteProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsByte ( ) ) ; } @ Override public void shortProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsShort ( ) ) ; } @ Override public void intProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsInt ( ) ) ; } @ Override public void longProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsLong ( ) ) ; } @ Override public void integerProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsBigInteger ( ) ) ; } @ Override public void floatProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsFloat ( ) ) ; } @ Override public void doubleProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsDouble ( ) ) ; } @ Override public void decimalProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsBigDecimal ( ) ) ; } @ Override public void stringProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } builder . add ( name , prop . getAsString ( ) ) ; } private static final Pattern DATE = Pattern . compile ( "" ) ; @ Override public void dateProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } String string = prop . getAsString ( ) ; Matcher matcher = DATE . matcher ( string ) ; if ( matcher . matches ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , name , string , "" ) ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( Calendar . YEAR , Integer . parseInt ( matcher . group ( ) ) ) ; calendar . set ( Calendar . MONTH , Integer . parseInt ( matcher . group ( ) ) - ) ; calendar . set ( Calendar . DATE , Integer . parseInt ( matcher . group ( ) ) ) ; builder . add ( name , calendar ) ; } private static final Pattern TIME = Pattern . compile ( "" ) ; @ Override public void timeProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } String string = prop . getAsString ( ) ; Matcher matcher = TIME . matcher ( string ) ; if ( matcher . matches ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , name , string , "" ) ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( Calendar . HOUR_OF_DAY , Integer . parseInt ( matcher . group ( ) ) ) ; calendar . set ( Calendar . MINUTE , Integer . parseInt ( matcher . group ( ) ) - ) ; calendar . set ( Calendar . SECOND , Integer . parseInt ( matcher . group ( ) ) ) ; builder . add ( name , calendar ) ; } private static final Pattern DATETIME = Pattern . compile ( "" ) ; @ Override public void datetimeProperty ( PropertyName name , JsonObject context ) throws IOException { JsonElement prop = property ( context , name ) ; if ( prop == null ) { return ; } String string = prop . getAsString ( ) ; Matcher matcher = DATETIME . matcher ( string ) ; if ( matcher . matches ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , name , string , "" ) ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( Calendar . YEAR , Integer . parseInt ( matcher . group ( ) ) ) ; calendar . set ( Calendar . MONTH , Integer . parseInt ( matcher . group ( ) ) - ) ; calendar . set ( Calendar . DATE , Integer . parseInt ( matcher . group ( ) ) ) ; calendar . set ( Calendar . HOUR_OF_DAY , Integer . parseInt ( matcher . group ( ) ) ) ; calendar . set ( Calendar . MINUTE , Integer . parseInt ( matcher . group ( ) ) ) ; calendar . set ( Calendar . SECOND , Integer . parseInt ( matcher . group ( ) ) ) ; builder . add ( name , calendar ) ; } } package com . asakusafw . testdriver . json ; import java . io . BufferedInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . net . URI ; import java . net . URL ; import java . nio . charset . Charset ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . DataModelSourceProvider ; import com . asakusafw . testdriver . core . TestContext ; public class JsonSourceProvider implements DataModelSourceProvider { static final Logger LOG = LoggerFactory . getLogger ( JsonSourceProvider . class ) ; private static final String EXTENSION = "" ; private static final Charset ENCONDING = Charset . forName ( "" ) ; @ Override public < T > DataModelSource open ( DataModelDefinition < T > definition , URI source , TestContext context ) throws IOException { String path = source . getSchemeSpecificPart ( ) ; if ( path == null || path . endsWith ( EXTENSION ) == false ) { return null ; } LOG . info ( "" , source ) ; URL url = source . toURL ( ) ; InputStream input = url . openStream ( ) ; boolean established = false ; try { InputStream bin = new BufferedInputStream ( input ) ; Reader reader = new InputStreamReader ( bin , ENCONDING ) ; DataModelSource dms = new JsonDataModelSource ( source , definition , reader ) ; established = true ; return dms ; } finally { if ( established == false ) { input . close ( ) ; } } } } package com . asakusafw . testdriver . json ; package com . asakusafw . testdriver . json ; import java . io . IOException ; import java . io . Reader ; import java . net . URI ; import java . text . MessageFormat ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . google . gson . JsonElement ; import com . google . gson . JsonParseException ; import com . google . gson . JsonStreamParser ; public class JsonDataModelSource implements DataModelSource { private final DataModelDefinition < ? > definition ; private final URI id ; private final Reader reader ; private final JsonStreamParser parser ; public JsonDataModelSource ( URI id , DataModelDefinition < ? > definition , Reader reader ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( reader == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = id ; this . definition = definition ; this . reader = reader ; this . parser = new JsonStreamParser ( reader ) ; } @ Override public DataModelReflection next ( ) throws IOException { try { if ( parser . hasNext ( ) == false ) { return null ; } JsonElement element = parser . next ( ) ; return JsonObjectDriver . convert ( definition , element ) ; } catch ( JsonParseException e ) { throw new IOException ( MessageFormat . format ( "" , id ) , e ) ; } } @ Override public void close ( ) throws IOException { reader . close ( ) ; } } package com . asakusafw . testdriver . html ; import java . io . Closeable ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . math . BigDecimal ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collections ; import java . util . Date ; import java . util . List ; import java . util . Scanner ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . Difference ; import com . asakusafw . testdriver . core . DifferenceSink ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; public class HtmlDifferenceSink implements DifferenceSink { static final Logger LOG = LoggerFactory . getLogger ( HtmlDifferenceSink . class ) ; private static final String CSS_FILE_NAME = "" ; static final Charset CHARSET = Charset . forName ( "" ) ; static final List < String > CSS ; static { List < String > lines = new ArrayList < String > ( ) ; InputStream in = HtmlDifferenceSink . class . getResourceAsStream ( CSS_FILE_NAME ) ; if ( in != null ) { try { Scanner scanner = new Scanner ( in , CHARSET . name ( ) ) ; while ( scanner . hasNextLine ( ) ) { IOException exception = scanner . ioException ( ) ; if ( exception != null ) { throw exception ; } lines . add ( scanner . nextLine ( ) ) ; } } catch ( IOException e ) { LOG . warn ( "" , e ) ; lines . clear ( ) ; } finally { try { in . close ( ) ; } catch ( IOException e ) { } } } CSS = Collections . unmodifiableList ( lines ) ; } private final Context context ; private boolean closed ; public HtmlDifferenceSink ( File output , DataModelDefinition < ? > definition ) throws IOException { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } boolean succeed = false ; OutputStream os = new FileOutputStream ( output ) ; try { PrintWriter writer = new PrintWriter ( new OutputStreamWriter ( os , CHARSET ) , true ) ; this . context = new Context ( writer , definition ) ; succeed = true ; } finally { if ( succeed == false ) { try { os . close ( ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , output ) , e ) ; } } } context . writeHeader ( ) ; } @ Override public void put ( Difference difference ) throws IOException { context . writeDifference ( difference ) ; } @ Override public void close ( ) throws IOException { if ( closed ) { return ; } try { context . writeFooter ( ) ; } finally { context . close ( ) ; } closed = true ; } private static class Context implements Closeable { private static final char [ ] ASCII_SPECIAL_ESCAPE = new char [ ] ; static { ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; } private final DataModelDefinition < ? > definition ; private final PrintWriter writer ; private final SimpleDateFormat dateFormat = new SimpleDateFormat ( "" ) ; private final SimpleDateFormat datetimeFormat = new SimpleDateFormat ( "" ) ; private final SimpleDateFormat timeFormat = new SimpleDateFormat ( "" ) ; Context ( PrintWriter writer , DataModelDefinition < ? > definition ) { assert writer != null ; assert definition != null ; this . writer = writer ; this . definition = definition ; } public void writeDifference ( Difference difference ) { assert difference != null ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( toHtml ( difference . getDiagnostic ( ) ) ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; DataModelReflection expected = difference . getExpected ( ) ; DataModelReflection actual = difference . getActual ( ) ; for ( PropertyName property : definition . getProperties ( ) ) { writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( toHtml ( property ) ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( toHtml ( describeProperty ( expected , property ) ) ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( toHtml ( describeProperty ( actual , property ) ) ) ; writer . println ( "" ) ; writer . println ( "" ) ; } writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; } private Object describeProperty ( DataModelReflection object , PropertyName property ) { assert property != null ; if ( object == null ) { return null ; } Object value = object . getValue ( property ) ; if ( value == null ) { return null ; } PropertyType type = definition . getType ( property ) ; switch ( type ) { case DATE : return dateFormat . format ( ( ( Calendar ) value ) . getTime ( ) ) ; case TIME : return timeFormat . format ( ( ( Calendar ) value ) . getTime ( ) ) ; case DATETIME : return datetimeFormat . format ( ( ( Calendar ) value ) . getTime ( ) ) ; case DECIMAL : return String . format ( "" , ( ( BigDecimal ) value ) . toPlainString ( ) , ( ( BigDecimal ) value ) . scale ( ) ) ; case STRING : return toStringLiteral ( ( String ) value ) ; default : return value ; } } private Object toStringLiteral ( String value ) { assert value != null ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( '' ) ; for ( char c : value . toCharArray ( ) ) { if ( c <= && ASCII_SPECIAL_ESCAPE [ c ] != ) { buf . append ( '' ) ; buf . append ( ASCII_SPECIAL_ESCAPE [ c ] ) ; } else if ( Character . isISOControl ( c ) || ! Character . isDefined ( c ) ) { buf . append ( String . format ( "" , ( int ) c ) ) ; } else { buf . append ( c ) ; } } buf . append ( '' ) ; return buf . toString ( ) ; } public void writeHeader ( ) { writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; for ( String line : CSS ) { writer . println ( line ) ; } writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; } public void writeFooter ( ) { writer . println ( "" ) ; writer . printf ( "" , datetimeFormat . format ( new Date ( ) ) ) ; writer . println ( "" ) ; writer . println ( "" ) ; writer . println ( "" ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } private String toHtml ( Object message ) { String text = String . valueOf ( message ) ; StringBuilder buf = new StringBuilder ( ) ; for ( char c : text . toCharArray ( ) ) { if ( c == '' ) { buf . append ( "" ) ; } else if ( c == '>' ) { buf . append ( "" ) ; } else if ( c == '' ) { buf . append ( "" ) ; } else if ( c == '' ) { buf . append ( "" ) ; } else { buf . append ( c ) ; } } return buf . toString ( ) ; } } } package com . asakusafw . testdriver . html ; package com . asakusafw . testdriver . html ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DifferenceSink ; import com . asakusafw . testdriver . core . DifferenceSinkProvider ; import com . asakusafw . testdriver . core . TestContext ; public class HtmlDifferenceSinkProvider implements DifferenceSinkProvider { static final Logger LOG = LoggerFactory . getLogger ( HtmlDifferenceSinkProvider . class ) ; @ Override public < T > DifferenceSink create ( DataModelDefinition < T > definition , URI sink , TestContext context ) throws IOException { String scheme = sink . getScheme ( ) ; if ( scheme == null || scheme . endsWith ( "" ) == false ) { return null ; } File file = new File ( sink ) ; if ( file . getName ( ) . endsWith ( "" ) == false ) { return null ; } LOG . info ( "" , sink ) ; return new HtmlDifferenceSinkFactory ( file ) . createSink ( definition , context ) ; } } package com . asakusafw . testdriver . html ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DifferenceSink ; import com . asakusafw . testdriver . core . DifferenceSinkFactory ; import com . asakusafw . testdriver . core . TestContext ; public class HtmlDifferenceSinkFactory extends DifferenceSinkFactory { static final Logger LOG = LoggerFactory . getLogger ( HtmlDifferenceSinkFactory . class ) ; final File output ; public HtmlDifferenceSinkFactory ( File output ) { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . output = output ; } public HtmlDifferenceSinkFactory ( String output ) { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . output = new File ( output ) ; } @ Override public < T > DifferenceSink createSink ( DataModelDefinition < T > definition , TestContext context ) throws IOException { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } File parent = output . getParentFile ( ) ; if ( parent != null && parent . isDirectory ( ) == false && parent . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , output ) ) ; } LOG . info ( "" , output . getAbsoluteFile ( ) ) ; return new HtmlDifferenceSink ( output , definition ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , HtmlDifferenceSink . class . getSimpleName ( ) , output ) ; } } package com . asakusafw . testdriver . excel ; import java . io . IOException ; import java . net . URI ; import org . apache . poi . ss . usermodel . Sheet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . DataModelSourceProvider ; import com . asakusafw . testdriver . core . TestContext ; public class ExcelSheetSourceProvider implements DataModelSourceProvider { static final Logger LOG = LoggerFactory . getLogger ( ExcelSheetSourceProvider . class ) ; @ Override public < T > DataModelSource open ( DataModelDefinition < T > definition , URI source , TestContext context ) throws IOException { Sheet sheet = Util . extract ( source ) ; if ( sheet == null ) { return null ; } LOG . info ( "" , source ) ; return new ExcelSheetDataModelSource ( definition , source , sheet ) ; } } package com . asakusafw . testdriver . excel ; import static com . asakusafw . testdriver . rule . Predicates . * ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collections ; import java . util . Date ; import java . util . List ; import java . util . Set ; import org . apache . poi . ss . usermodel . Row ; import org . apache . poi . ss . usermodel . Sheet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . PropertyType ; import com . asakusafw . testdriver . core . VerifyContext ; import com . asakusafw . testdriver . core . VerifyRule ; import com . asakusafw . testdriver . core . VerifyRuleProvider ; import com . asakusafw . testdriver . excel . legacy . LegacyExcelRuleExtractor ; import com . asakusafw . testdriver . rule . BothAreNull ; import com . asakusafw . testdriver . rule . DataModelCondition ; import com . asakusafw . testdriver . rule . Predicates ; import com . asakusafw . testdriver . rule . ValuePredicate ; import com . asakusafw . testdriver . rule . VerifyRuleBuilder ; import com . asakusafw . testdriver . rule . VerifyRuleBuilder . Property ; public class ExcelSheetRuleProvider implements VerifyRuleProvider { static final Logger LOG = LoggerFactory . getLogger ( ExcelSheetRuleProvider . class ) ; private static final List < ExcelRuleExtractor > EXTRACTORS ; static { List < ExcelRuleExtractor > drivers = new ArrayList < ExcelRuleExtractor > ( ) ; drivers . add ( new DefaultExcelRuleExtractor ( ) ) ; drivers . add ( new LegacyExcelRuleExtractor ( ) ) ; EXTRACTORS = Collections . unmodifiableList ( drivers ) ; } @ Override public < T > VerifyRule get ( DataModelDefinition < T > definition , VerifyContext context , URI source ) throws IOException { Sheet sheet = Util . extract ( source ) ; if ( sheet == null ) { return null ; } LOG . debug ( "" , source ) ; ExcelRuleExtractor extractor = findExtractor ( sheet ) ; if ( extractor == null ) { LOG . debug ( "" , source ) ; return null ; } LOG . info ( "" , source ) ; try { return resolve ( definition , context , sheet , extractor ) ; } catch ( ExcelRuleExtractor . FormatException e ) { throw new IOException ( MessageFormat . format ( "" , source ) , e ) ; } } private ExcelRuleExtractor findExtractor ( Sheet sheet ) { assert sheet != null ; for ( ExcelRuleExtractor extractor : EXTRACTORS ) { if ( extractor . supports ( sheet ) ) { return extractor ; } } return null ; } private < T > VerifyRule resolve ( DataModelDefinition < T > definition , VerifyContext context , Sheet sheet , ExcelRuleExtractor extractor ) throws ExcelRuleExtractor . FormatException { assert definition != null ; assert context != null ; assert sheet != null ; assert extractor != null ; VerifyRuleBuilder builder = new VerifyRuleBuilder ( definition ) ; Set < DataModelCondition > modelPredicates = extractor . extractDataModelCondition ( sheet ) ; if ( modelPredicates . contains ( DataModelCondition . IGNORE_ABSENT ) ) { builder . acceptIfAbsent ( ) ; } if ( modelPredicates . contains ( DataModelCondition . IGNORE_UNEXPECTED ) ) { builder . acceptIfUnexpected ( ) ; } if ( modelPredicates . contains ( DataModelCondition . IGNORE_MATCHED ) == false ) { int start = extractor . extractPropertyRowStartIndex ( sheet ) ; int end = sheet . getLastRowNum ( ) + ; for ( int i = start ; i < end ; i ++ ) { Row row = sheet . getRow ( i ) ; if ( row == null ) { continue ; } resolveRow ( builder , definition , context , row , extractor ) ; } } return builder . toVerifyRule ( ) ; } private < T > void resolveRow ( VerifyRuleBuilder builder , DataModelDefinition < T > definition , VerifyContext context , Row row , ExcelRuleExtractor extractor ) throws ExcelRuleExtractor . FormatException { assert builder != null ; assert definition != null ; assert context != null ; assert row != null ; assert extractor != null ; String name = extractor . extractName ( row ) ; if ( name == null ) { return ; } VerifyRuleBuilder . Property property ; try { property = builder . property ( name ) ; } catch ( IllegalArgumentException e ) { throw new ExcelRuleExtractor . FormatException ( MessageFormat . format ( "" , row . getRowNum ( ) + ) , e ) ; } ValueConditionKind value = extractor . extractValueCondition ( row ) ; NullityConditionKind nullity = extractor . extractNullityCondition ( row ) ; if ( buildNullity ( property , value , nullity ) == false ) { return ; } buildValue ( property , context , value ) ; } private boolean buildNullity ( VerifyRuleBuilder . Property property , ValueConditionKind value , NullityConditionKind nullity ) { assert property != null ; assert value != null ; assert nullity != null ; switch ( nullity ) { case NORMAL : if ( value == ValueConditionKind . EQUAL ) { property . accept ( new BothAreNull ( ) ) ; } break ; case ACCEPT_ABSENT : property . accept ( isNull ( ) ) ; break ; case ACCEPT_PRESENT : property . accept ( not ( isNull ( ) ) ) ; break ; case DENY_ABSENT : if ( value == ValueConditionKind . ANY || value == ValueConditionKind . KEY ) { property . accept ( not ( isNull ( ) ) ) ; } break ; case DENY_PRESENT : property . accept ( isNull ( ) ) ; return false ; default : throw new AssertionError ( MessageFormat . format ( "" , property , nullity ) ) ; } return true ; } private void buildValue ( VerifyRuleBuilder . Property property , VerifyContext context , ValueConditionKind value ) throws ExcelRuleExtractor . FormatException { assert property != null ; assert context != null ; assert value != null ; switch ( value ) { case ANY : break ; case KEY : property . asKey ( ) ; break ; case EQUAL : property . accept ( Predicates . equals ( ) ) ; break ; case CONTAIN : if ( property . getType ( ) == PropertyType . STRING ) { property . accept ( containsString ( ) ) ; } else { throw typeError ( property , ValueConditionKind . CONTAIN ) ; } break ; case TODAY : if ( property . getType ( ) == PropertyType . DATE || property . getType ( ) == PropertyType . DATETIME ) { property . accept ( createTodayPredicate ( context ) ) ; } else { throw typeError ( property , ValueConditionKind . TODAY ) ; } break ; case NOW : if ( property . getType ( ) == PropertyType . DATE || property . getType ( ) == PropertyType . DATETIME ) { property . accept ( createNowPredicate ( context ) ) ; } else { throw typeError ( property , ValueConditionKind . NOW ) ; } break ; default : throw new AssertionError ( MessageFormat . format ( "" , property , value ) ) ; } } private ValuePredicate < Calendar > createTodayPredicate ( VerifyContext context ) { assert context != null ; Calendar begin = toDate ( context . getTestStarted ( ) ) ; Calendar end = toDate ( context . getTestFinished ( ) ) ; end . add ( Calendar . DATE , ) ; end . add ( Calendar . MILLISECOND , - ) ; return Predicates . period ( begin , end ) ; } private Calendar toDate ( Date date ) { assert date != null ; Calendar instance = Calendar . getInstance ( ) ; instance . setTime ( date ) ; int y = instance . get ( Calendar . YEAR ) ; int m = instance . get ( Calendar . MONTH ) ; int d = instance . get ( Calendar . DATE ) ; instance . clear ( ) ; instance . set ( y , m , d ) ; return instance ; } private ValuePredicate < Calendar > createNowPredicate ( VerifyContext context ) { assert context != null ; Calendar begin = toDatetime ( context . getTestStarted ( ) ) ; Calendar end = toDatetime ( context . getTestFinished ( ) ) ; end . add ( Calendar . SECOND , ) ; end . add ( Calendar . MILLISECOND , - ) ; return Predicates . period ( begin , end ) ; } private Calendar toDatetime ( Date date ) { assert date != null ; Calendar instance = Calendar . getInstance ( ) ; instance . setTime ( date ) ; int y = instance . get ( Calendar . YEAR ) ; int m = instance . get ( Calendar . MONTH ) ; int d = instance . get ( Calendar . DATE ) ; int ho = instance . get ( Calendar . HOUR_OF_DAY ) ; int mi = instance . get ( Calendar . MINUTE ) ; int se = instance . get ( Calendar . SECOND ) ; instance . clear ( ) ; instance . set ( y , m , d , ho , mi , se ) ; return instance ; } private ExcelRuleExtractor . FormatException typeError ( Property property , ValueConditionKind kind ) { assert property != null ; assert kind != null ; return new ExcelRuleExtractor . FormatException ( MessageFormat . format ( "" , property . getName ( ) , kind . getTitle ( ) , kind . getExpectedType ( ) ) ) ; } } package com . asakusafw . testdriver . excel ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Set ; import org . apache . poi . ss . usermodel . Cell ; import org . apache . poi . ss . usermodel . Row ; import org . apache . poi . ss . usermodel . Sheet ; import com . asakusafw . testdriver . rule . DataModelCondition ; public class DefaultExcelRuleExtractor implements ExcelRuleExtractor { public static final String FORMAT = RuleSheetFormat . FORMAT_VERSION ; @ Override public boolean supports ( Sheet sheet ) { if ( sheet == null ) { throw new IllegalArgumentException ( "" ) ; } RuleSheetFormat item = RuleSheetFormat . FORMAT ; String title = getStringCell ( sheet , item . getRowIndex ( ) , item . getColumnIndex ( ) ) ; if ( title . equals ( item . getTitle ( ) ) == false ) { return false ; } String format = getStringCell ( sheet , item . getRowIndex ( ) , item . getColumnIndex ( ) + ) ; return format != null && format . equals ( FORMAT ) ; } @ Override public Set < DataModelCondition > extractDataModelCondition ( Sheet sheet ) throws FormatException { if ( sheet == null ) { throw new IllegalArgumentException ( "" ) ; } RuleSheetFormat item = RuleSheetFormat . TOTAL_CONDITION ; String text = getStringCell ( sheet , item . getRowIndex ( ) , item . getColumnIndex ( ) + ) ; TotalConditionKind kind = TotalConditionKind . fromOption ( text ) ; if ( kind == null ) { throw new FormatException ( MessageFormat . format ( "" , RuleSheetFormat . TOTAL_CONDITION . getTitle ( ) , text , Arrays . asList ( TotalConditionKind . getOptions ( ) ) ) ) ; } return kind . getPredicates ( ) ; } @ Override public int extractPropertyRowStartIndex ( Sheet sheet ) throws FormatException { if ( sheet == null ) { throw new IllegalArgumentException ( "" ) ; } return RuleSheetFormat . PROPERTY_NAME . getRowIndex ( ) + ; } private String getStringCell ( Sheet sheet , int rowIndex , int colIndex ) { assert sheet != null ; Row row = sheet . getRow ( rowIndex ) ; if ( row == null ) { return "" ; } Cell cell = row . getCell ( colIndex ) ; if ( cell == null || cell . getCellType ( ) != Cell . CELL_TYPE_STRING ) { return "" ; } return cell . getStringCellValue ( ) ; } @ Override public String extractName ( Row row ) throws FormatException { if ( row == null ) { throw new IllegalArgumentException ( "" ) ; } Cell cell = row . getCell ( RuleSheetFormat . PROPERTY_NAME . getColumnIndex ( ) ) ; if ( cell == null || cell . getCellType ( ) == Cell . CELL_TYPE_BLANK ) { return null ; } else if ( cell . getCellType ( ) != Cell . CELL_TYPE_STRING ) { throw new FormatException ( MessageFormat . format ( "" , RuleSheetFormat . PROPERTY_NAME . getTitle ( ) , cell . getRowIndex ( ) + , cell . getColumnIndex ( ) + ) ) ; } String name = cell . getStringCellValue ( ) ; if ( name . isEmpty ( ) ) { return null ; } return name ; } @ Override public ValueConditionKind extractValueCondition ( Row row ) throws FormatException { if ( row == null ) { throw new IllegalArgumentException ( "" ) ; } String cell = getStringCell ( row , RuleSheetFormat . VALUE_CONDITION ) ; ValueConditionKind condition = ValueConditionKind . fromOption ( cell ) ; if ( condition == null ) { throw new FormatException ( MessageFormat . format ( "" , RuleSheetFormat . VALUE_CONDITION . getTitle ( ) , cell , row . getRowNum ( ) + , RuleSheetFormat . VALUE_CONDITION . getColumnIndex ( ) + , Arrays . asList ( ValueConditionKind . getOptions ( ) ) ) ) ; } return condition ; } @ Override public NullityConditionKind extractNullityCondition ( Row row ) throws FormatException { if ( row == null ) { throw new IllegalArgumentException ( "" ) ; } String cell = getStringCell ( row , RuleSheetFormat . NULLITY_CONDITION ) ; NullityConditionKind condition = NullityConditionKind . fromOption ( cell ) ; if ( condition == null ) { throw new FormatException ( MessageFormat . format ( "" , RuleSheetFormat . NULLITY_CONDITION . getTitle ( ) , cell , row . getRowNum ( ) + , RuleSheetFormat . NULLITY_CONDITION . getColumnIndex ( ) + , Arrays . asList ( NullityConditionKind . getOptions ( ) ) ) ) ; } return condition ; } private String getStringCell ( Row row , RuleSheetFormat item ) throws FormatException { assert row != null ; assert item != null ; Cell cell = row . getCell ( item . getColumnIndex ( ) ) ; if ( cell == null || cell . getCellType ( ) == Cell . CELL_TYPE_BLANK ) { return "" ; } else if ( cell . getCellType ( ) == Cell . CELL_TYPE_STRING ) { return cell . getStringCellValue ( ) ; } throw new FormatException ( MessageFormat . format ( "" , item . getTitle ( ) , cell . getRowIndex ( ) + , cell . getColumnIndex ( ) + ) ) ; } } package com . asakusafw . testdriver . excel ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . Map ; import org . apache . poi . ss . usermodel . Cell ; import org . apache . poi . ss . usermodel . Row ; import org . apache . poi . ss . usermodel . Sheet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . PropertyName ; public class ExcelSheetDataModelSource implements DataModelSource { static final Logger LOG = LoggerFactory . getLogger ( ExcelSheetDataModelSource . class ) ; private final DataModelDefinition < ? > definition ; private final URI id ; private final Sheet sheet ; private final Map < PropertyName , Integer > names ; private int nextRowNumber ; public ExcelSheetDataModelSource ( DataModelDefinition < ? > definition , URI id , Sheet sheet ) throws IOException { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sheet == null ) { throw new IllegalArgumentException ( "" ) ; } this . definition = definition ; this . id = id ; this . sheet = sheet ; this . names = extractProperties ( ) ; } private Map < PropertyName , Integer > extractProperties ( ) throws IOException { Row row = sheet . getRow ( ) ; if ( row == null ) { throw new IOException ( MessageFormat . format ( "" , id ) ) ; } nextRowNumber = ; Map < PropertyName , Integer > results = new LinkedHashMap < PropertyName , Integer > ( ) ; for ( Iterator < Cell > iter = row . cellIterator ( ) ; iter . hasNext ( ) ; ) { Cell cell = iter . next ( ) ; int type = cell . getCellType ( ) ; if ( type == Cell . CELL_TYPE_BLANK ) { continue ; } if ( type != Cell . CELL_TYPE_STRING || cell . getStringCellValue ( ) . isEmpty ( ) ) { throw new IOException ( MessageFormat . format ( "" , id , cell . getColumnIndex ( ) + ) ) ; } String name = cell . getStringCellValue ( ) ; PropertyName property = toPropertyName ( cell , name ) ; if ( definition . getType ( property ) == null ) { throw new IOException ( MessageFormat . format ( "" , definition . getModelClass ( ) . getName ( ) , property , id , cell . getColumnIndex ( ) + ) ) ; } results . put ( property , cell . getColumnIndex ( ) ) ; } if ( results . isEmpty ( ) ) { throw new IOException ( MessageFormat . format ( "" , id ) ) ; } return results ; } private PropertyName toPropertyName ( Cell cell , String name ) { assert cell != null ; assert name != null ; String [ ] words = name . split ( "" ) ; return PropertyName . newInstance ( words ) ; } @ Override public DataModelReflection next ( ) throws IOException { while ( nextRowNumber <= sheet . getLastRowNum ( ) ) { Row row = sheet . getRow ( nextRowNumber ++ ) ; if ( row == null ) { LOG . warn ( MessageFormat . format ( "" , id , nextRowNumber ) ) ; continue ; } boolean sawFilled = false ; ExcelDataDriver driver = new ExcelDataDriver ( definition , id ) ; for ( Map . Entry < PropertyName , Integer > entry : names . entrySet ( ) ) { Cell cell = row . getCell ( entry . getValue ( ) , Row . CREATE_NULL_AS_BLANK ) ; int type = cell . getCellType ( ) ; if ( type == Cell . CELL_TYPE_FORMULA || type == Cell . CELL_TYPE_ERROR ) { throw new IOException ( MessageFormat . format ( "" , id , row . getRowNum ( ) + , cell . getColumnIndex ( ) + ) ) ; } sawFilled |= ( type != Cell . CELL_TYPE_BLANK ) ; driver . process ( entry . getKey ( ) , cell ) ; } if ( sawFilled ) { return driver . getReflection ( ) ; } else { LOG . warn ( MessageFormat . format ( "" , id , row . getRowNum ( ) + ) ) ; } } return null ; } @ Override public void close ( ) throws IOException { return ; } } package com . asakusafw . testdriver . excel ; import java . util . Set ; import org . apache . poi . ss . usermodel . Row ; import org . apache . poi . ss . usermodel . Sheet ; import com . asakusafw . testdriver . rule . DataModelCondition ; public interface ExcelRuleExtractor { boolean supports ( Sheet sheet ) ; Set < DataModelCondition > extractDataModelCondition ( Sheet sheet ) throws FormatException ; int extractPropertyRowStartIndex ( Sheet sheet ) throws FormatException ; String extractName ( Row row ) throws FormatException ; ValueConditionKind extractValueCondition ( Row row ) throws FormatException ; NullityConditionKind extractNullityCondition ( Row row ) throws FormatException ; public class FormatException extends Exception { private static final long serialVersionUID = - ; public FormatException ( String message ) { super ( message ) ; } public FormatException ( String message , Throwable cause ) { super ( message , cause ) ; } } } package com . asakusafw . testdriver . excel . legacy ; import java . util . HashMap ; import java . util . Map ; public enum RowMatchingCondition { EXACT ( "" ) , PARTIAL ( "" ) , NONE ( "" ) ; private String japaneseName ; private RowMatchingCondition ( String japaneseName ) { this . japaneseName = japaneseName ; } public String getJapaneseName ( ) { return japaneseName ; } private static Map < String , RowMatchingCondition > japaneseNameMap = new HashMap < String , RowMatchingCondition > ( ) ; static { for ( RowMatchingCondition conditon : RowMatchingCondition . values ( ) ) { String key = conditon . getJapaneseName ( ) ; if ( japaneseNameMap . containsKey ( key ) ) { throw new RuntimeException ( "" ) ; } japaneseNameMap . put ( key , conditon ) ; } } public static RowMatchingCondition getConditonByJapanseName ( String key ) { return japaneseNameMap . get ( key ) ; } public static String [ ] getJapaneseNames ( ) { RowMatchingCondition [ ] values = RowMatchingCondition . values ( ) ; String [ ] result = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { result [ i ] = values [ i ] . getJapaneseName ( ) ; } return result ; } } package com . asakusafw . testdriver . excel . legacy ; import java . util . HashMap ; import java . util . Map ; public enum NullValueCondition { NORMAL ( "" ) , NULL_IS_OK ( "" ) , NULL_IS_NG ( "" ) , NOT_NULL_IS_OK ( "" ) , NOT_NULL_IS_NG ( "" ) ; private String japaneseName ; private NullValueCondition ( String japaneseName ) { this . japaneseName = japaneseName ; } public String getJapaneseName ( ) { return japaneseName ; } private static Map < String , NullValueCondition > japaneseNameMap = new HashMap < String , NullValueCondition > ( ) ; static { for ( NullValueCondition conditon : NullValueCondition . values ( ) ) { String key = conditon . getJapaneseName ( ) ; if ( japaneseNameMap . containsKey ( key ) ) { throw new RuntimeException ( "" ) ; } japaneseNameMap . put ( key , conditon ) ; } } public static NullValueCondition getConditonByJapanseName ( String key ) { return japaneseNameMap . get ( key ) ; } public static String [ ] getJapaneseNames ( ) { NullValueCondition [ ] values = NullValueCondition . values ( ) ; String [ ] result = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { result [ i ] = values [ i ] . getJapaneseName ( ) ; } return result ; } } package com . asakusafw . testdriver . excel . legacy ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . EnumSet ; import java . util . Set ; import org . apache . poi . ss . usermodel . Cell ; import org . apache . poi . ss . usermodel . Row ; import org . apache . poi . ss . usermodel . Sheet ; import com . asakusafw . testdriver . excel . ExcelRuleExtractor ; import com . asakusafw . testdriver . excel . NullityConditionKind ; import com . asakusafw . testdriver . excel . ValueConditionKind ; import com . asakusafw . testdriver . rule . DataModelCondition ; public class LegacyExcelRuleExtractor implements ExcelRuleExtractor { @ Override public boolean supports ( Sheet sheet ) { if ( sheet == null ) { throw new IllegalArgumentException ( "" ) ; } if ( getStringCell ( sheet , , ) != null ) { return false ; } ConditionSheetItem item = ConditionSheetItem . TABLE_NAME ; String cell = getStringCell ( sheet , item . getRow ( ) , item . getCol ( ) ) ; return cell != null && cell . equals ( item . getName ( ) ) ; } @ Override public Set < DataModelCondition > extractDataModelCondition ( Sheet sheet ) throws FormatException { if ( sheet == null ) { throw new IllegalArgumentException ( "" ) ; } ConditionSheetItem item = ConditionSheetItem . ROW_MATCHING_CONDITION ; String cell = getStringCell ( sheet , item . getRow ( ) , item . getCol ( ) + ) ; if ( cell == null ) { cell = "" ; } RowMatchingCondition condition = RowMatchingCondition . getConditonByJapanseName ( cell ) ; if ( condition == null ) { throw new FormatException ( MessageFormat . format ( "" , ConditionSheetItem . ROW_MATCHING_CONDITION . getName ( ) , cell , Arrays . asList ( RowMatchingCondition . getJapaneseNames ( ) ) ) ) ; } switch ( condition ) { case NONE : return EnumSet . allOf ( DataModelCondition . class ) ; case EXACT : return EnumSet . noneOf ( DataModelCondition . class ) ; case PARTIAL : return EnumSet . of ( DataModelCondition . IGNORE_UNEXPECTED ) ; default : throw new AssertionError ( condition ) ; } } @ Override public int extractPropertyRowStartIndex ( Sheet sheet ) throws FormatException { if ( sheet == null ) { throw new IllegalArgumentException ( "" ) ; } return ConditionSheetItem . COLUMN_NAME . getRow ( ) + ; } private String getStringCell ( Sheet sheet , int rowIndex , int colIndex ) { assert sheet != null ; Row row = sheet . getRow ( rowIndex ) ; if ( row == null ) { return null ; } Cell cell = row . getCell ( colIndex ) ; if ( cell == null || cell . getCellType ( ) != Cell . CELL_TYPE_STRING ) { return null ; } return cell . getStringCellValue ( ) ; } @ Override public String extractName ( Row row ) throws FormatException { if ( row == null ) { throw new IllegalArgumentException ( "" ) ; } Cell cell = row . getCell ( ConditionSheetItem . COLUMN_NAME . getCol ( ) ) ; if ( cell == null || cell . getCellType ( ) == Cell . CELL_TYPE_BLANK ) { return null ; } else if ( cell . getCellType ( ) != Cell . CELL_TYPE_STRING ) { throw new FormatException ( MessageFormat . format ( "" , ConditionSheetItem . COLUMN_NAME . getName ( ) , cell . getRowIndex ( ) + , cell . getColumnIndex ( ) + ) ) ; } String name = cell . getStringCellValue ( ) ; if ( name . isEmpty ( ) ) { return null ; } return name . toLowerCase ( ) ; } @ Override public ValueConditionKind extractValueCondition ( Row row ) throws FormatException { if ( row == null ) { throw new IllegalArgumentException ( "" ) ; } if ( isKeyProperty ( row ) ) { return ValueConditionKind . KEY ; } String cell = getStringCell ( row , ConditionSheetItem . MATCHING_CONDITION ) ; ColumnMatchingCondition condition = ColumnMatchingCondition . getConditonByJapanseName ( cell ) ; if ( condition == null ) { throw new FormatException ( MessageFormat . format ( "" , ConditionSheetItem . MATCHING_CONDITION . getName ( ) , cell , row . getRowNum ( ) + , ConditionSheetItem . MATCHING_CONDITION . getCol ( ) + , Arrays . asList ( RowMatchingCondition . getJapaneseNames ( ) ) ) ) ; } switch ( condition ) { case EXACT : return ValueConditionKind . EQUAL ; case NONE : return ValueConditionKind . ANY ; case NOW : return ValueConditionKind . NOW ; case PARTIAL : return ValueConditionKind . CONTAIN ; case TODAY : return ValueConditionKind . TODAY ; default : throw new AssertionError ( condition ) ; } } private boolean isKeyProperty ( Row row ) throws FormatException { assert row != null ; String cell = getStringCell ( row , ConditionSheetItem . KEY_FLAG ) ; return cell . isEmpty ( ) == false ; } @ Override public NullityConditionKind extractNullityCondition ( Row row ) throws FormatException { if ( row == null ) { throw new IllegalArgumentException ( "" ) ; } String cell = getStringCell ( row , ConditionSheetItem . NULL_VALUE_CONDITION ) ; NullValueCondition condition = NullValueCondition . getConditonByJapanseName ( cell ) ; if ( condition == null ) { throw new FormatException ( MessageFormat . format ( "" , ConditionSheetItem . NULL_VALUE_CONDITION . getName ( ) , cell , row . getRowNum ( ) + , ConditionSheetItem . NULL_VALUE_CONDITION . getCol ( ) + , Arrays . asList ( RowMatchingCondition . getJapaneseNames ( ) ) ) ) ; } switch ( condition ) { case NORMAL : return NullityConditionKind . NORMAL ; case NOT_NULL_IS_NG : return NullityConditionKind . DENY_PRESENT ; case NOT_NULL_IS_OK : return NullityConditionKind . ACCEPT_PRESENT ; case NULL_IS_NG : return NullityConditionKind . DENY_ABSENT ; case NULL_IS_OK : return NullityConditionKind . ACCEPT_ABSENT ; default : throw new AssertionError ( condition ) ; } } private String getStringCell ( Row row , ConditionSheetItem item ) throws FormatException { assert row != null ; assert item != null ; Cell cell = row . getCell ( item . getCol ( ) ) ; if ( cell == null || cell . getCellType ( ) == Cell . CELL_TYPE_BLANK ) { return "" ; } else if ( cell . getCellType ( ) == Cell . CELL_TYPE_STRING ) { return cell . getStringCellValue ( ) ; } throw new FormatException ( MessageFormat . format ( "" , item . getName ( ) , cell . getRowIndex ( ) + , cell . getColumnIndex ( ) + ) ) ; } } package com . asakusafw . testdriver . excel . legacy ; public enum ConditionSheetItem { NO ( "" , , , ItemType . COLUMN_ITEM ) , COLUMN_NAME ( "" , , , ItemType . COLUMN_ITEM ) , COLUMN_COMMENT ( "" , , , ItemType . COLUMN_ITEM ) , DATA_TYPE ( "" , , , ItemType . COLUMN_ITEM ) , WIDTH ( "" , , , ItemType . COLUMN_ITEM ) , SCALE ( "" , , , ItemType . COLUMN_ITEM ) , KEY_FLAG ( "" , , , ItemType . COLUMN_ITEM ) , NULLABLE ( "" , , , ItemType . COLUMN_ITEM ) , MATCHING_CONDITION ( "" , , , ItemType . COLUMN_ITEM ) , NULL_VALUE_CONDITION ( "" , , , ItemType . COLUMN_ITEM ) , TABLE_NAME ( "" , , , ItemType . TABLE_ITEM ) , ROW_MATCHING_CONDITION ( "" , , , ItemType . TABLE_ITEM ) ; private String name ; private int row ; private int col ; private ConditionSheetItem ( String name , int row , int col , ItemType itemType ) { assert name != null ; assert itemType != null ; this . name = name ; this . row = row ; this . col = col ; } public enum ItemType { TABLE_ITEM , COLUMN_ITEM , } public String getName ( ) { return name ; } public int getRow ( ) { return row ; } public int getCol ( ) { return col ; } } package com . asakusafw . testdriver . excel . legacy ; package com . asakusafw . testdriver . excel . legacy ; import java . util . HashMap ; import java . util . Map ; public enum ColumnMatchingCondition { NONE ( "" ) , EXACT ( "" ) , PARTIAL ( "" ) , NOW ( "" ) , TODAY ( "" ) ; private String japaneseName ; private ColumnMatchingCondition ( String japaneseName ) { this . japaneseName = japaneseName ; } public String getJapaneseName ( ) { return japaneseName ; } private static Map < String , ColumnMatchingCondition > japaneseNameMap = new HashMap < String , ColumnMatchingCondition > ( ) ; static { for ( ColumnMatchingCondition conditon : ColumnMatchingCondition . values ( ) ) { String key = conditon . getJapaneseName ( ) ; if ( japaneseNameMap . containsKey ( key ) ) { throw new RuntimeException ( "" ) ; } japaneseNameMap . put ( key , conditon ) ; } } public static ColumnMatchingCondition getConditonByJapanseName ( String key ) { return japaneseNameMap . get ( key ) ; } public static String [ ] getJapaneseNames ( ) { ColumnMatchingCondition [ ] values = ColumnMatchingCondition . values ( ) ; String [ ] result = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { result [ i ] = values [ i ] . getJapaneseName ( ) ; } return result ; } } package com . asakusafw . testdriver . excel ; import java . io . BufferedInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . net . URI ; import java . net . URL ; import java . text . MessageFormat ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . Sheet ; import org . apache . poi . ss . usermodel . Workbook ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; final class Util { static final Logger LOG = LoggerFactory . getLogger ( Util . class ) ; private static final Pattern FRAGMENT = Pattern . compile ( "" ) ; private static final String EXTENSION = "" ; private static final String FRAGMENT_FIRST_SHEET = "" ; static Sheet extract ( URI source ) throws IOException { assert source != null ; String path = source . getSchemeSpecificPart ( ) ; if ( path == null || path . endsWith ( EXTENSION ) == false ) { LOG . debug ( "" , source ) ; return null ; } String fragment = source . getFragment ( ) ; if ( fragment == null ) { fragment = FRAGMENT_FIRST_SHEET ; LOG . debug ( "" , source ) ; } Matcher matcher = FRAGMENT . matcher ( fragment ) ; if ( matcher . matches ( ) == false ) { LOG . info ( "" , source ) ; return null ; } LOG . debug ( "" , source ) ; URL url = source . toURL ( ) ; InputStream in = url . openStream ( ) ; Workbook book ; try { InputStream bin = new BufferedInputStream ( in ) ; book = new HSSFWorkbook ( bin ) ; } catch ( IOException e ) { throw new IOException ( MessageFormat . format ( "" , source ) ) ; } finally { in . close ( ) ; } if ( matcher . group ( ) != null ) { int sheetNumber = Integer . parseInt ( matcher . group ( ) ) ; LOG . debug ( "" , sheetNumber ) ; try { Sheet sheet = book . getSheetAt ( sheetNumber ) ; assert sheet != null ; return sheet ; } catch ( RuntimeException e ) { throw new IOException ( MessageFormat . format ( "" , source , sheetNumber ) , e ) ; } } else { String sheetName = matcher . group ( ) ; LOG . debug ( "" , sheetName ) ; assert sheetName != null ; Sheet sheet = book . getSheet ( sheetName ) ; if ( sheet == null ) { throw new IOException ( MessageFormat . format ( "" , source , sheetName ) ) ; } return sheet ; } } static String buildText ( String symbol , String title ) { assert symbol != null ; assert title != null ; if ( symbol . equalsIgnoreCase ( title ) ) { return symbol ; } else { return MessageFormat . format ( "" , title , symbol ) ; } } private static final Pattern TEXT = Pattern . compile ( "" ) ; static String extractSymbol ( String text ) { assert text != null ; Matcher matcher = TEXT . matcher ( text ) ; if ( matcher . matches ( ) ) { return matcher . group ( ) ; } else { return text ; } } private Util ( ) { return ; } } package com . asakusafw . testdriver . excel ; public enum RuleSheetFormat { FORMAT ( "" , , ) , TOTAL_CONDITION ( "" , , ) , PROPERTY_NAME ( "" , , ) , VALUE_CONDITION ( "" , , ) , NULLITY_CONDITION ( "" , , ) , COMMENTS ( "" , , ) , ; public static final String FORMAT_VERSION = "" ; private final String title ; private final int rowIndex ; private final int columnIndex ; private RuleSheetFormat ( String title , int rowIndex , int columnIndex ) { assert title != null ; this . title = title ; this . rowIndex = rowIndex ; this . columnIndex = columnIndex ; } public String getTitle ( ) { return title ; } public int getRowIndex ( ) { return rowIndex ; } public int getColumnIndex ( ) { return columnIndex ; } } package com . asakusafw . testdriver . excel ; public enum NullityConditionKind { NORMAL ( "" , "" ) , ACCEPT_ABSENT ( "" , "" ) , DENY_ABSENT ( "" , "" ) , ACCEPT_PRESENT ( "" , "" ) , DENY_PRESENT ( "" , "" ) , ; private final String symbol ; private final String title ; private final String text ; private NullityConditionKind ( String symbol , String title ) { assert symbol != null ; assert title != null ; this . symbol = symbol ; this . title = title ; this . text = Util . buildText ( symbol , title ) ; } public String getTitle ( ) { return title ; } public String getText ( ) { return text ; } public static NullityConditionKind fromOption ( String text ) { if ( text == null ) { throw new IllegalArgumentException ( "" ) ; } String symbol = Util . extractSymbol ( text ) ; for ( NullityConditionKind kind : values ( ) ) { if ( kind . symbol . equalsIgnoreCase ( symbol ) ) { return kind ; } } return null ; } public static String [ ] getOptions ( ) { NullityConditionKind [ ] values = values ( ) ; String [ ] options = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { options [ i ] = values [ i ] . text ; } return options ; } } package com . asakusafw . testdriver . excel ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . text . MessageFormat ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . Sheet ; import org . apache . poi . ss . usermodel . Workbook ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSink ; import com . asakusafw . testdriver . core . DataModelSinkFactory ; import com . asakusafw . testdriver . core . TestContext ; public class ExcelSheetSinkFactory extends DataModelSinkFactory { private static final int MAX_COLUMN_SIZE = ; static final Logger LOG = LoggerFactory . getLogger ( ExcelSheetSinkFactory . class ) ; final File output ; public ExcelSheetSinkFactory ( File output ) { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . output = output ; } public ExcelSheetSinkFactory ( String output ) { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . output = new File ( output ) ; } @ Override public < T > DataModelSink createSink ( DataModelDefinition < T > definition , TestContext context ) throws IOException { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( definition . getProperties ( ) . size ( ) > MAX_COLUMN_SIZE ) { LOG . warn ( "" , new Object [ ] { definition . getModelClass ( ) . getName ( ) , MAX_COLUMN_SIZE , output , } ) ; } File parent = output . getParentFile ( ) ; if ( parent != null && parent . isDirectory ( ) == false && parent . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , output ) ) ; } final Workbook workbook = new HSSFWorkbook ( ) ; Sheet sheet = workbook . createSheet ( "" ) ; return new ExcelSheetSink ( definition , sheet , MAX_COLUMN_SIZE ) { private boolean closed = false ; @ Override public void close ( ) throws IOException { if ( closed ) { return ; } closed = true ; LOG . info ( "" , output ) ; OutputStream stream = new FileOutputStream ( output ) ; try { workbook . write ( stream ) ; } finally { stream . close ( ) ; } } } ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , ExcelSheetSink . class . getSimpleName ( ) , output ) ; } } package com . asakusafw . testdriver . excel ; import org . apache . poi . ss . usermodel . CellStyle ; import org . apache . poi . ss . usermodel . CreationHelper ; import org . apache . poi . ss . usermodel . DataFormat ; import org . apache . poi . ss . usermodel . Font ; import org . apache . poi . ss . usermodel . IndexedColors ; import org . apache . poi . ss . usermodel . Workbook ; class WorkbookInfo { final Workbook workbook ; private final CellStyle commonStyle ; final CellStyle titleStyle ; final CellStyle dataStyle ; final CellStyle dateDataStyle ; final CellStyle timeDataStyle ; final CellStyle datetimeDataStyle ; public WorkbookInfo ( Workbook workbook ) { if ( workbook == null ) { throw new IllegalArgumentException ( "" ) ; } this . workbook = workbook ; Font font = workbook . createFont ( ) ; commonStyle = workbook . createCellStyle ( ) ; commonStyle . setFont ( font ) ; commonStyle . setBorderTop ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderBottom ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderLeft ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderRight ( CellStyle . BORDER_THIN ) ; titleStyle = workbook . createCellStyle ( ) ; titleStyle . cloneStyleFrom ( commonStyle ) ; titleStyle . setLocked ( true ) ; titleStyle . setFillPattern ( CellStyle . SOLID_FOREGROUND ) ; titleStyle . setFillForegroundColor ( IndexedColors . LIGHT_GREEN . getIndex ( ) ) ; titleStyle . setAlignment ( CellStyle . ALIGN_CENTER ) ; CreationHelper helper = workbook . getCreationHelper ( ) ; DataFormat df = helper . createDataFormat ( ) ; dataStyle = workbook . createCellStyle ( ) ; dataStyle . cloneStyleFrom ( commonStyle ) ; dateDataStyle = workbook . createCellStyle ( ) ; dateDataStyle . cloneStyleFrom ( commonStyle ) ; dateDataStyle . setDataFormat ( df . getFormat ( "" ) ) ; timeDataStyle = workbook . createCellStyle ( ) ; timeDataStyle . cloneStyleFrom ( commonStyle ) ; timeDataStyle . setDataFormat ( df . getFormat ( "" ) ) ; datetimeDataStyle = workbook . createCellStyle ( ) ; datetimeDataStyle . cloneStyleFrom ( commonStyle ) ; datetimeDataStyle . setDataFormat ( df . getFormat ( "" ) ) ; } } package com . asakusafw . testdriver . excel ; import java . io . IOException ; import java . math . BigDecimal ; import java . net . URI ; import java . text . MessageFormat ; import java . util . Calendar ; import org . apache . poi . ss . usermodel . Cell ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelDefinition . Builder ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelScanner ; import com . asakusafw . testdriver . core . PropertyName ; class ExcelDataDriver { private final Engine engine ; public ExcelDataDriver ( DataModelDefinition < ? > definition , URI id ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } this . engine = new Engine ( definition , id ) ; } public void process ( PropertyName propertyName , Cell cell ) throws IOException { if ( propertyName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( cell == null ) { throw new IllegalArgumentException ( "" ) ; } if ( cell . getCellType ( ) == Cell . CELL_TYPE_BLANK ) { return ; } engine . scan ( engine . definition , propertyName , cell ) ; } public DataModelReflection getReflection ( ) { return engine . builder . build ( ) ; } private static class Engine extends DataModelScanner < Cell , IOException > { final DataModelDefinition < ? > definition ; final URI id ; final Builder < ? > builder ; Engine ( DataModelDefinition < ? > definition , URI id ) { assert definition != null ; this . definition = definition ; this . id = id ; this . builder = definition . newReflection ( ) ; } @ Override public void booleanProperty ( PropertyName name , Cell context ) throws IOException { if ( context . getCellType ( ) == Cell . CELL_TYPE_BOOLEAN ) { builder . add ( name , context . getBooleanCellValue ( ) ) ; } else { String string = context . getStringCellValue ( ) ; if ( string . equalsIgnoreCase ( "" ) ) { builder . add ( name , true ) ; } else if ( string . equalsIgnoreCase ( "" ) ) { builder . add ( name , false ) ; } else { throw exception ( name , context , "" ) ; } } } @ Override public void byteProperty ( PropertyName name , Cell context ) throws IOException { long value = toLong ( name , context , "" ) ; checkRange ( name , context , value , Byte . MIN_VALUE , Byte . MAX_VALUE ) ; builder . add ( name , ( byte ) value ) ; } @ Override public void shortProperty ( PropertyName name , Cell context ) throws IOException { long value = toLong ( name , context , "" ) ; checkRange ( name , context , value , Short . MIN_VALUE , Short . MAX_VALUE ) ; builder . add ( name , ( short ) value ) ; } @ Override public void intProperty ( PropertyName name , Cell context ) throws IOException { long value = toLong ( name , context , "" ) ; checkRange ( name , context , value , Integer . MIN_VALUE , Integer . MAX_VALUE ) ; builder . add ( name , ( int ) value ) ; } @ Override public void longProperty ( PropertyName name , Cell context ) throws IOException { long value = toLong ( name , context , "" ) ; builder . add ( name , value ) ; } private long toLong ( PropertyName name , Cell cell , String expected ) throws IOException { assert name != null ; assert cell != null ; assert expected != null ; if ( cell . getCellType ( ) == Cell . CELL_TYPE_NUMERIC ) { return ( long ) cell . getNumericCellValue ( ) ; } else if ( cell . getCellType ( ) == Cell . CELL_TYPE_STRING ) { try { return Long . parseLong ( stripNumber ( cell . getStringCellValue ( ) ) ) ; } catch ( NumberFormatException e ) { } } throw exception ( name , cell , expected ) ; } private String stripNumber ( String string ) { if ( string == null ) { return null ; } String trimmed = string . trim ( ) . replaceAll ( "" , "" ) ; if ( trimmed . startsWith ( "" ) ) { return trimmed . substring ( ) . trim ( ) ; } return trimmed ; } private void checkRange ( PropertyName name , Cell cell , long value , int min , int max ) throws IOException { assert name != null ; assert cell != null ; if ( value < min || max < value ) { throw new IOException ( MessageFormat . format ( "" , name , value , min , max , id , cell . getRowIndex ( ) + , cell . getColumnIndex ( ) + ) ) ; } } @ Override public void floatProperty ( PropertyName name , Cell context ) throws IOException { double value = toDouble ( name , context , "" ) ; builder . add ( name , ( float ) value ) ; } @ Override public void doubleProperty ( PropertyName name , Cell context ) throws IOException { double value = toDouble ( name , context , "" ) ; builder . add ( name , value ) ; } private double toDouble ( PropertyName name , Cell cell , String expected ) throws IOException { assert name != null ; assert cell != null ; assert expected != null ; if ( cell . getCellType ( ) == Cell . CELL_TYPE_NUMERIC ) { return cell . getNumericCellValue ( ) ; } else if ( cell . getCellType ( ) == Cell . CELL_TYPE_STRING ) { try { return Double . parseDouble ( stripNumber ( cell . getStringCellValue ( ) ) ) ; } catch ( NumberFormatException e ) { } } throw exception ( name , cell , expected ) ; } @ Override public void integerProperty ( PropertyName name , Cell context ) throws IOException { BigDecimal decimal = toDecimal ( name , context , "" ) ; builder . add ( name , decimal . toBigInteger ( ) ) ; } @ Override public void decimalProperty ( PropertyName name , Cell context ) throws IOException { BigDecimal decimal = toDecimal ( name , context , "" ) ; builder . add ( name , decimal ) ; } private BigDecimal toDecimal ( PropertyName name , Cell context , String expected ) throws IOException { assert name != null ; assert context != null ; assert expected != null ; if ( context . getCellType ( ) == Cell . CELL_TYPE_NUMERIC ) { return new BigDecimal ( context . getNumericCellValue ( ) ) ; } else if ( context . getCellType ( ) == Cell . CELL_TYPE_STRING ) { try { return new BigDecimal ( stripNumber ( context . getStringCellValue ( ) ) ) ; } catch ( NumberFormatException e ) { } } throw exception ( name , context , expected ) ; } @ Override public void stringProperty ( PropertyName name , Cell context ) throws IOException { if ( context . getCellType ( ) != Cell . CELL_TYPE_STRING ) { throw new IOException ( MessageFormat . format ( "" , id , context . getRowIndex ( ) + , context . getColumnIndex ( ) + ) ) ; } builder . add ( name , context . getStringCellValue ( ) ) ; } @ Override public void dateProperty ( PropertyName name , Cell context ) throws IOException { if ( context . getCellType ( ) != Cell . CELL_TYPE_NUMERIC ) { throw exception ( name , context , "" ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( context . getDateCellValue ( ) ) ; Calendar result = Calendar . getInstance ( ) ; result . clear ( ) ; result . set ( calendar . get ( Calendar . YEAR ) , calendar . get ( Calendar . MONTH ) , calendar . get ( Calendar . DATE ) ) ; builder . add ( name , result ) ; } @ Override public void timeProperty ( PropertyName name , Cell context ) throws IOException { if ( context . getCellType ( ) != Cell . CELL_TYPE_NUMERIC ) { throw exception ( name , context , "" ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( context . getDateCellValue ( ) ) ; Calendar result = Calendar . getInstance ( ) ; result . clear ( ) ; result . set ( Calendar . HOUR_OF_DAY , calendar . get ( Calendar . HOUR_OF_DAY ) ) ; result . set ( Calendar . MINUTE , calendar . get ( Calendar . MINUTE ) ) ; result . set ( Calendar . SECOND , calendar . get ( Calendar . SECOND ) ) ; builder . add ( name , result ) ; } @ Override public void datetimeProperty ( PropertyName name , Cell context ) throws IOException { if ( context . getCellType ( ) != Cell . CELL_TYPE_NUMERIC ) { throw exception ( name , context , "" ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( context . getDateCellValue ( ) ) ; Calendar result = Calendar . getInstance ( ) ; result . clear ( ) ; result . set ( calendar . get ( Calendar . YEAR ) , calendar . get ( Calendar . MONTH ) , calendar . get ( Calendar . DATE ) , calendar . get ( Calendar . HOUR_OF_DAY ) , calendar . get ( Calendar . MINUTE ) , calendar . get ( Calendar . SECOND ) ) ; builder . add ( name , result ) ; } @ Override public void anyProperty ( PropertyName name , Cell context ) throws IOException { throw exception ( name , context , "" ) ; } private IOException exception ( PropertyName name , Cell cell , String expected ) { return new IOException ( MessageFormat . format ( "" , name , expected , id , cell . getRowIndex ( ) + , cell . getColumnIndex ( ) + ) ) ; } } } package com . asakusafw . testdriver . excel ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSink ; import com . asakusafw . testdriver . core . DataModelSinkProvider ; import com . asakusafw . testdriver . core . TestContext ; public class ExcelSheetSinkProvider implements DataModelSinkProvider { static final Logger LOG = LoggerFactory . getLogger ( ExcelSheetSinkProvider . class ) ; @ Override public < T > DataModelSink create ( DataModelDefinition < T > definition , URI sink , TestContext context ) throws IOException { String scheme = sink . getScheme ( ) ; if ( scheme == null || scheme . endsWith ( "" ) == false ) { return null ; } File file = new File ( sink ) ; if ( file . getName ( ) . endsWith ( "" ) == false ) { return null ; } LOG . info ( "" , sink ) ; return new ExcelSheetSinkFactory ( file ) . createSink ( definition , context ) ; } } package com . asakusafw . testdriver . excel ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import com . asakusafw . testdriver . rule . DataModelCondition ; public enum TotalConditionKind { STRICT ( "" , "" ) , SKIP_UNEXPECTED ( "" , "" , DataModelCondition . IGNORE_UNEXPECTED ) , SKIP_ABSENT ( "" , "" , DataModelCondition . IGNORE_ABSENT ) , INTERSECT ( "" , "" , DataModelCondition . IGNORE_UNEXPECTED , DataModelCondition . IGNORE_ABSENT ) , SKIP_ALL ( "" , "" , DataModelCondition . IGNORE_UNEXPECTED , DataModelCondition . IGNORE_ABSENT , DataModelCondition . IGNORE_MATCHED ) , ; private final String symbol ; private final String title ; private final Set < DataModelCondition > predicates ; private final String text ; private TotalConditionKind ( String symbol , String title , DataModelCondition ... conditions ) { assert symbol != null ; assert title != null ; assert conditions != null ; this . symbol = symbol ; this . title = title ; this . predicates = Collections . unmodifiableSet ( new HashSet < DataModelCondition > ( Arrays . asList ( conditions ) ) ) ; this . text = Util . buildText ( symbol , title ) ; } public String getTitle ( ) { return title ; } public Set < DataModelCondition > getPredicates ( ) { return predicates ; } public static TotalConditionKind fromOption ( String text ) { if ( text == null ) { throw new IllegalArgumentException ( "" ) ; } String symbol = Util . extractSymbol ( text ) ; for ( TotalConditionKind kind : values ( ) ) { if ( kind . symbol . equalsIgnoreCase ( symbol ) ) { return kind ; } } return null ; } public static String [ ] getOptions ( ) { TotalConditionKind [ ] values = values ( ) ; String [ ] options = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { options [ i ] = values [ i ] . text ; } return options ; } } package com . asakusafw . testdriver . excel ; import java . io . IOException ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . List ; import org . apache . poi . ss . usermodel . Cell ; import org . apache . poi . ss . usermodel . Row ; import org . apache . poi . ss . usermodel . Sheet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelScanner ; import com . asakusafw . testdriver . core . DataModelSink ; import com . asakusafw . testdriver . core . PropertyName ; public class ExcelSheetSink implements DataModelSink { static final Logger LOG = LoggerFactory . getLogger ( ExcelSheetSink . class ) ; private final Sheet sheet ; private final WorkbookInfo info ; private final Engine engine ; private int rowIndex ; public ExcelSheetSink ( DataModelDefinition < ? > definition , Sheet sheet , int maxColumns ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sheet == null ) { throw new IllegalArgumentException ( "" ) ; } this . sheet = sheet ; this . info = new WorkbookInfo ( sheet . getWorkbook ( ) ) ; this . engine = new Engine ( definition , info , maxColumns ) ; engine . createHeaderRow ( sheet . createRow ( ) ) ; this . rowIndex = ; } @ Override public void put ( DataModelReflection model ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } Row row = sheet . createRow ( rowIndex ++ ) ; engine . process ( model , row ) ; } @ Override public void close ( ) throws IOException { return ; } private static class Engine extends DataModelScanner < Context , RuntimeException > { private final DataModelDefinition < ? > definition ; private final WorkbookInfo info ; private final List < PropertyName > properties ; Engine ( DataModelDefinition < ? > definition , WorkbookInfo info , int maxColumns ) { assert definition != null ; assert info != null ; this . definition = definition ; this . info = info ; List < PropertyName > props = new ArrayList < PropertyName > ( definition . getProperties ( ) ) ; if ( props . size ( ) > maxColumns ) { props = props . subList ( , maxColumns ) ; } this . properties = props ; } void createHeaderRow ( Row row ) { assert row != null ; int columnIndex = ; for ( PropertyName name : properties ) { Cell cell = row . createCell ( columnIndex ++ ) ; cell . setCellStyle ( info . titleStyle ) ; cell . setCellValue ( name . toString ( ) ) ; } } void process ( DataModelReflection model , Row row ) { assert model != null ; assert row != null ; Context context = new Context ( model , row , info ) ; for ( PropertyName name : properties ) { scan ( definition , name , context ) ; } } @ Override public void booleanProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; Boolean value = ( Boolean ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void byteProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; Byte value = ( Byte ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void shortProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; Short value = ( Short ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void intProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; Integer value = ( Integer ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void longProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; Long value = ( Long ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void integerProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; BigInteger value = ( BigInteger ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value . toString ( ) ) ; } } @ Override public void floatProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; Float value = ( Float ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void doubleProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; Double value = ( Double ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void decimalProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; BigDecimal value = ( BigDecimal ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value . toPlainString ( ) ) ; } } @ Override public void stringProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; String value = ( String ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void dateProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; cell . setCellStyle ( info . dataStyle ) ; Calendar value = ( Calendar ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void timeProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; cell . setCellStyle ( info . timeDataStyle ) ; Calendar value = ( Calendar ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void datetimeProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; cell . setCellStyle ( info . datetimeDataStyle ) ; Calendar value = ( Calendar ) context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value ) ; } } @ Override public void anyProperty ( PropertyName name , Context context ) { Cell cell = context . nextCell ( ) ; Object value = context . getValue ( name ) ; if ( value != null ) { cell . setCellValue ( value . toString ( ) ) ; } } } private static class Context { private final DataModelReflection model ; private final Row row ; private final WorkbookInfo info ; private int column ; Context ( DataModelReflection model , Row row , WorkbookInfo info ) { assert model != null ; assert row != null ; assert info != null ; this . model = model ; this . row = row ; this . info = info ; this . column = ; } public Cell nextCell ( ) { Cell cell = row . createCell ( column ++ ) ; cell . setCellStyle ( info . dataStyle ) ; return cell ; } public Object getValue ( PropertyName name ) { assert name != null ; return model . getValue ( name ) ; } } } package com . asakusafw . testdriver . excel ; package com . asakusafw . testdriver . excel ; public enum ValueConditionKind { ANY ( "" , "" , "" ) , KEY ( "" , "" , "" ) , EQUAL ( "" , "" , "" ) , CONTAIN ( "" , "" , "" ) , TODAY ( "" , "" , "" ) , NOW ( "" , "" , "" ) , ; private final String symbol ; private final String title ; private final String expectedType ; private final String text ; private ValueConditionKind ( String symbol , String title , String expectedType ) { assert symbol != null ; assert title != null ; assert expectedType != null ; this . symbol = symbol ; this . title = title ; this . expectedType = expectedType ; this . text = Util . buildText ( symbol , title ) ; } public String getTitle ( ) { return title ; } public String getText ( ) { return text ; } public static ValueConditionKind fromOption ( String text ) { if ( text == null ) { throw new IllegalArgumentException ( "" ) ; } String symbol = Util . extractSymbol ( text ) ; for ( ValueConditionKind kind : values ( ) ) { if ( kind . symbol . equalsIgnoreCase ( symbol ) ) { return kind ; } } return null ; } public String getExpectedType ( ) { return expectedType ; } public static String [ ] getOptions ( ) { ValueConditionKind [ ] values = values ( ) ; String [ ] options = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { options [ i ] = values [ i ] . text ; } return options ; } } package com . asakusafw . testdriver . rule ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . math . BigDecimal ; import java . util . Calendar ; import org . junit . Test ; public class PredicatesTest { @ Test public void equalTo ( ) { ValuePredicate < Object > p = Predicates . equalTo ( ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; p . describeExpected ( , ) ; } @ Test public void isNull ( ) { ValuePredicate < Object > p = Predicates . isNull ( ) ; assertThat ( p . accepts ( , null ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; assertThat ( p . accepts ( null , ) , is ( false ) ) ; p . describeExpected ( , ) ; } @ Test public void not ( ) { ValuePredicate < Object > p = Predicates . not ( Predicates . equalTo ( ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; p . describeExpected ( , ) ; } @ Test public void equals ( ) { ValuePredicate < Object > p = Predicates . equals ( ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; p . describeExpected ( , ) ; } @ Test public void floatRange ( ) { ValuePredicate < Number > p = Predicates . floatRange ( - , + ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; p . describeExpected ( , ) ; } @ Test public void integerRange ( ) { ValuePredicate < Number > p = Predicates . integerRange ( - , + ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( true ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; assertThat ( p . accepts ( , ) , is ( false ) ) ; p . describeExpected ( , ) ; } @ Test public void decimalRange ( ) { ValuePredicate < BigDecimal > p = Predicates . decimalRange ( new BigDecimal ( - ) , new BigDecimal ( + ) ) ; assertThat ( p . accepts ( new BigDecimal ( ) , new BigDecimal ( ) ) , is ( true ) ) ; assertThat ( p . accepts ( new BigDecimal ( ) , new BigDecimal ( ) ) , is ( true ) ) ; assertThat ( p . accepts ( new BigDecimal ( ) , new BigDecimal ( ) ) , is ( true ) ) ; assertThat ( p . accepts ( new BigDecimal ( ) , new BigDecimal ( ) ) , is ( false ) ) ; assertThat ( p . accepts ( new BigDecimal ( ) , new BigDecimal ( ) ) , is ( false ) ) ; p . describeExpected ( new BigDecimal ( ) , new BigDecimal ( ) ) ; } @ Test public void dateRange ( ) { ValuePredicate < Calendar > p = Predicates . dateRange ( - , + ) ; assertThat ( p . accepts ( d ( , , ) , d ( , , ) ) , is ( true ) ) ; assertThat ( p . accepts ( d ( , , ) , d ( , , ) ) , is ( true ) ) ; assertThat ( p . accepts ( d ( , , ) , d ( , , ) ) , is ( true ) ) ; assertThat ( p . accepts ( d ( , , ) , d ( , , ) ) , is ( false ) ) ; assertThat ( p . accepts ( d ( , , ) , d ( , , ) ) , is ( false ) ) ; p . describeExpected ( d ( , , ) , d ( , , ) ) ; } private Calendar d ( int y , int m , int d ) { Calendar c = Calendar . getInstance ( ) ; c . clear ( ) ; c . set ( Calendar . YEAR , y ) ; c . set ( Calendar . MONTH , m - ) ; c . set ( Calendar . DATE , d ) ; return c ; } @ Test public void timeRange ( ) { ValuePredicate < Calendar > p = Predicates . timeRange ( - , + ) ; assertThat ( p . accepts ( t ( , , ) , t ( , , ) ) , is ( true ) ) ; assertThat ( p . accepts ( t ( , , ) , t ( , , ) ) , is ( true ) ) ; assertThat ( p . accepts ( t ( , , ) , t ( , , ) ) , is ( true ) ) ; assertThat ( p . accepts ( t ( , , ) , t ( , , ) ) , is ( false ) ) ; assertThat ( p . accepts ( t ( , , ) , t ( , , ) ) , is ( false ) ) ; p . describeExpected ( t ( , , ) , t ( , , ) ) ; } private Calendar t ( int h , int m , int s ) { Calendar c = Calendar . getInstance ( ) ; c . clear ( ) ; c . set ( Calendar . YEAR , ) ; c . set ( Calendar . MONTH , ) ; c . set ( Calendar . DATE , ) ; c . set ( Calendar . HOUR_OF_DAY , h ) ; c . set ( Calendar . MINUTE , m ) ; c . set ( Calendar . SECOND , s ) ; return c ; } @ Test public void dateAndTime ( ) { ValuePredicate < Calendar > p = Predicates . timeRange ( , ) ; assertThat ( p . accepts ( d ( , , ) , t ( , , , , , ) ) , is ( true ) ) ; assertThat ( p . accepts ( t ( , , , , , ) , d ( , , ) ) , is ( true ) ) ; } private Calendar t ( int y , int mo , int d , int h , int mi , int s ) { Calendar c = Calendar . getInstance ( ) ; c . clear ( ) ; c . set ( Calendar . YEAR , y ) ; c . set ( Calendar . MONTH , mo - ) ; c . set ( Calendar . DATE , d ) ; c . set ( Calendar . HOUR_OF_DAY , h ) ; c . set ( Calendar . MINUTE , mi ) ; c . set ( Calendar . SECOND , s ) ; return c ; } @ Test public void containsString ( ) { ValuePredicate < String > p = Predicates . containsString ( ) ; assertThat ( p . accepts ( "" , "" ) , is ( true ) ) ; assertThat ( p . accepts ( "" , "" ) , is ( true ) ) ; assertThat ( p . accepts ( "" , "" ) , is ( true ) ) ; assertThat ( p . accepts ( "" , "" ) , is ( false ) ) ; assertThat ( p . accepts ( "" , "" ) , is ( false ) ) ; p . describeExpected ( "" , "" ) ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import org . junit . Test ; public class VerifyEngineTest { @ Test public void single ( ) throws Exception { VerifyEngine engine = new VerifyEngine ( new Rule ( ) ) ; engine . addExpected ( source ( "" ) ) ; List < Difference > d1 = engine . inspectInput ( source ( "" ) ) ; assertThat ( d1 . size ( ) , is ( ) ) ; List < Difference > d2 = engine . inspectRest ( ) ; assertThat ( d2 . size ( ) , is ( ) ) ; } @ Test public void mismatch_value ( ) throws Exception { VerifyEngine engine = new VerifyEngine ( new Rule ( ) ) ; engine . addExpected ( source ( "" ) ) ; List < Difference > d1 = engine . inspectInput ( source ( "" ) ) ; assertThat ( d1 . size ( ) , is ( ) ) ; List < Difference > d2 = engine . inspectRest ( ) ; assertThat ( d2 . size ( ) , is ( ) ) ; } @ Test public void mismatch_key ( ) throws Exception { VerifyEngine engine = new VerifyEngine ( new Rule ( ) ) ; engine . addExpected ( source ( "" ) ) ; List < Difference > d1 = engine . inspectInput ( source ( "" ) ) ; assertThat ( d1 . size ( ) , is ( ) ) ; List < Difference > d2 = engine . inspectRest ( ) ; assertThat ( d2 . size ( ) , is ( ) ) ; } DataModelSource source ( String ... values ) { return new IteratorDataModelSource ( ValueDefinition . of ( String . class ) , Arrays . asList ( values ) . iterator ( ) ) ; } static class Rule implements VerifyRule { private final DataModelDefinition < String > def = ValueDefinition . of ( String . class ) ; @ Override public Object getKey ( DataModelReflection target ) { String string = def . toObject ( target ) ; String [ ] split = string . split ( "" , ) ; return split [ ] ; } @ Override public Object verify ( DataModelReflection expected , DataModelReflection actual ) { if ( expected == null || actual == null ) { return "" ; } String ex = def . toObject ( expected ) . split ( "" , ) [ ] ; String ac = def . toObject ( actual ) . split ( "" , ) [ ] ; return ex . equals ( ac ) ? null : "" ; } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class MockImporterPreparator extends AbstractImporterPreparator < MockImporterPreparator . Desc > { public static Desc create ( ) { return new Desc ( ) ; } public SpiImporterPreparator wrap ( ) { return new SpiImporterPreparator ( Collections . singletonList ( this ) ) ; } @ Override public void truncate ( Desc description ) throws IOException { description . lines . clear ( ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , Desc description ) throws IOException { final List < String > lines = description . lines ; return new ModelOutput < V > ( ) { @ Override public void write ( V model ) throws IOException { lines . add ( String . valueOf ( model ) ) ; } @ Override public void close ( ) throws IOException { return ; } } ; } public static class Desc implements ImporterDescription { public final List < String > lines = new ArrayList < String > ( ) ; @ Override public Class < ? > getModelType ( ) { return String . class ; } @ Override public DataSize getDataSize ( ) { return DataSize . UNKNOWN ; } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class MockExporterRetriever extends AbstractExporterRetriever < MockExporterRetriever . Desc > { public static Desc create ( String ... lines ) { return new Desc ( Arrays . asList ( lines ) ) ; } public SpiExporterRetriever wrap ( ) { return new SpiExporterRetriever ( Collections . singletonList ( this ) ) ; } @ Override public void truncate ( Desc description ) throws IOException { description . lines . clear ( ) ; } @ Override public < V > DataModelSource createSource ( DataModelDefinition < V > definition , Desc description ) throws IOException { return new IteratorDataModelSource ( ValueDefinition . of ( String . class ) , description . lines . iterator ( ) ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , Desc description ) throws IOException { final List < String > lines = description . lines ; return new ModelOutput < V > ( ) { @ Override public void write ( V model ) throws IOException { lines . add ( String . valueOf ( model ) ) ; } @ Override public void close ( ) throws IOException { return ; } } ; } public static class Desc implements ExporterDescription { final List < String > lines ; Desc ( List < String > lines ) { this . lines = lines ; } @ Override public Class < ? > getModelType ( ) { return String . class ; } } } package com . asakusafw . testdriver . core ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; public class MockDataModelAdapter implements DataModelAdapter { private final Set < Class < ? > > accepts ; public MockDataModelAdapter ( ) { this ( String . class ) ; } public MockDataModelAdapter ( Class < ? > ... accepts ) { this . accepts = new HashSet < Class < ? > > ( Arrays . asList ( accepts ) ) ; } @ Override public < T > DataModelDefinition < T > get ( Class < T > modelClass ) { if ( accepts == null || accepts . contains ( modelClass ) ) { return new ValueDefinition < T > ( modelClass ) ; } return null ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import org . junit . Test ; import com . asakusafw . testdriver . core . MockExporterRetriever . Desc ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class SpiExporterRetrieverTest extends SpiTestRoot { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Test public void getDescriptionClass ( ) { SpiExporterRetriever target = new SpiExporterRetriever ( getClass ( ) . getClassLoader ( ) ) ; assertThat ( target . getDescriptionClass ( ) , equalTo ( ExporterDescription . class ) ) ; } @ Test public void open ( ) throws Exception { Desc desc = MockExporterRetriever . create ( "" ) ; ClassLoader cl = register ( ExporterRetriever . class , MockExporterRetriever . class ) ; SpiExporterRetriever target = new SpiExporterRetriever ( cl ) ; DataModelSource source = target . createSource ( ValueDefinition . of ( String . class ) , desc , EMPTY ) ; assertThat ( ValueDefinition . of ( String . class ) . toObject ( source . next ( ) ) , is ( "" ) ) ; } @ Test ( expected = IOException . class ) public void open_notfound ( ) throws Exception { Desc desc = MockExporterRetriever . create ( "" ) ; SpiExporterRetriever target = new SpiExporterRetriever ( getClass ( ) . getClassLoader ( ) ) ; target . createSource ( ValueDefinition . of ( String . class ) , desc , EMPTY ) ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . math . BigDecimal ; import java . util . GregorianCalendar ; import org . junit . Test ; public class DifferenceTest { @ Test public void string ( ) { String value = Difference . format ( "" ) ; assertThat ( value , is ( "" ) ) ; } @ Test public void string_escape ( ) { String value = Difference . format ( "" ) ; assertThat ( value , is ( "" ) ) ; } @ Test public void calendar ( ) { String value = Difference . format ( new GregorianCalendar ( , , , , , ) ) ; assertThat ( value , is ( "" ) ) ; } @ Test public void bigdecimal ( ) { String value = Difference . format ( new BigDecimal ( "" ) ) ; assertThat ( value , is ( "" ) ) ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . Arrays ; import org . junit . Test ; import com . asakusafw . testdriver . core . MockImporterPreparator . Desc ; @ Deprecated public class TestDataPreparatorTest extends SpiTestRoot { @ Test public void simple ( ) throws Exception { TestDataPreparator prep = new TestDataPreparator ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockImporterPreparator ( ) . wrap ( ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockImporterPreparator . create ( ) ; prep . prepare ( desc . getModelType ( ) , desc , uri ( "" ) ) ; assertThat ( desc . lines , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void spi ( ) throws Exception { register ( DataModelAdapter . class , MockDataModelAdapter . class ) ; register ( DataModelSourceProvider . class , MockSourceProvider . class ) ; ClassLoader loader = register ( ImporterPreparator . class , MockImporterPreparator . class ) ; TestDataPreparator prep = new TestDataPreparator ( loader ) ; Desc desc = MockImporterPreparator . create ( ) ; prep . prepare ( desc . getModelType ( ) , desc , uri ( "" ) ) ; assertThat ( desc . lines , is ( Arrays . asList ( "" ) ) ) ; } @ Test ( expected = IOException . class ) public void unknown_type ( ) throws Exception { TestDataPreparator prep = new TestDataPreparator ( new MockDataModelAdapter ( Integer . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockImporterPreparator ( ) . wrap ( ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockImporterPreparator . create ( ) ; prep . prepare ( desc . getModelType ( ) , desc , uri ( "" ) ) ; } @ Test ( expected = IOException . class ) public void unknown_source ( ) throws Exception { TestDataPreparator prep = new TestDataPreparator ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockImporterPreparator ( ) . wrap ( ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockImporterPreparator . create ( ) ; prep . prepare ( desc . getModelType ( ) , desc , uri ( "" ) ) ; } private URI uri ( String str ) { try { return new URI ( str ) ; } catch ( URISyntaxException e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . testdriver . core ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . HashMap ; import java . util . Map ; public class MockVerifyRuleProvider implements VerifyRuleProvider { private final Map < URI , VerifyRule > rules = new HashMap < URI , VerifyRule > ( ) ; public MockVerifyRuleProvider ( ) { try { add ( new URI ( "" ) , new VerifyRule ( ) { @ Override public Object getKey ( DataModelReflection target ) { return target ; } @ Override public Object verify ( DataModelReflection expected , DataModelReflection actual ) { if ( expected == null ) { return actual == null ? null : false ; } return expected . equals ( actual ) ? null : false ; } } ) ; } catch ( URISyntaxException e ) { throw new AssertionError ( e ) ; } } public final MockVerifyRuleProvider add ( URI uri , VerifyRule rule ) { rules . put ( uri , rule ) ; return this ; } @ Override public < T > VerifyRule get ( DataModelDefinition < T > definition , VerifyContext context , URI source ) { return rules . get ( source ) ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . net . URI ; import org . junit . Test ; public class SpiVerifyRuleProviderTest extends SpiTestRoot { @ Test public void open ( ) throws Exception { ClassLoader cl = register ( VerifyRuleProvider . class , MockVerifyRuleProvider . class ) ; SpiVerifyRuleProvider target = new SpiVerifyRuleProvider ( cl ) ; VerifyContext context = new VerifyContext ( new TestContext . Empty ( ) ) ; context . testFinished ( ) ; VerifyRule rule = target . get ( ValueDefinition . of ( String . class ) , context , new URI ( "" ) ) ; assertThat ( rule , not ( nullValue ( ) ) ) ; DataModelReflection ref = ValueDefinition . of ( String . class ) . toReflection ( "" ) ; assertThat ( rule . getKey ( ref ) , is ( ( Object ) ref ) ) ; } @ Test public void open_notfound ( ) throws Exception { ClassLoader cl = register ( VerifyRuleProvider . class , MockVerifyRuleProvider . class ) ; SpiVerifyRuleProvider target = new SpiVerifyRuleProvider ( cl ) ; VerifyContext context = new VerifyContext ( new TestContext . Empty ( ) ) ; context . testFinished ( ) ; VerifyRule rule = target . get ( ValueDefinition . of ( String . class ) , context , new URI ( "" ) ) ; assertThat ( rule , is ( nullValue ( ) ) ) ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . List ; import org . junit . Test ; import com . asakusafw . testdriver . core . MockExporterRetriever . Desc ; @ Deprecated public class TestResultInspectorTest extends SpiTestRoot { private final VerifyContext context ; { context = new VerifyContext ( new TestContext . Empty ( ) ) ; context . testFinished ( ) ; } @ Test public void simple ( ) throws Exception { TestResultInspector inspector = new TestResultInspector ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockVerifyRuleProvider ( ) . add ( uri ( "" ) , rule ( ) ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockExporterRetriever . create ( "" ) ; List < Difference > results = inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test public void spi ( ) throws Exception { register ( DataModelAdapter . class , MockDataModelAdapter . class ) ; register ( DataModelSourceProvider . class , MockSourceProvider . class ) ; register ( VerifyRuleProvider . class , MockVerifyRuleProvider . class ) ; ClassLoader loader = register ( ExporterRetriever . class , MockExporterRetriever . class ) ; TestResultInspector inspector = new TestResultInspector ( loader ) ; Desc desc = MockExporterRetriever . create ( "" ) ; List < Difference > results = inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; assertThat ( results . toString ( ) , results . size ( ) , is ( ) ) ; } @ Test public void inconsistent_result ( ) throws Exception { TestResultInspector inspector = new TestResultInspector ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockVerifyRuleProvider ( ) . add ( uri ( "" ) , rule ( ) ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockExporterRetriever . create ( "" ) ; List < Difference > results = inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test public void empty_result ( ) throws Exception { TestResultInspector inspector = new TestResultInspector ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockVerifyRuleProvider ( ) . add ( uri ( "" ) , rule ( ) ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockExporterRetriever . create ( ) ; List < Difference > results = inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test public void extra_result ( ) throws Exception { TestResultInspector inspector = new TestResultInspector ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockVerifyRuleProvider ( ) . add ( uri ( "" ) , rule ( ) ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockExporterRetriever . create ( "" , "" ) ; List < Difference > results = inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test public void inconsistent_key ( ) throws Exception { TestResultInspector inspector = new TestResultInspector ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockVerifyRuleProvider ( ) . add ( uri ( "" ) , rule ( ) ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockExporterRetriever . create ( "" ) ; List < Difference > results = inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; assertThat ( results . toString ( ) , results . size ( ) , is ( ) ) ; } @ Test ( expected = IOException . class ) public void unknown_type ( ) throws Exception { TestResultInspector inspector = new TestResultInspector ( new MockDataModelAdapter ( Integer . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockVerifyRuleProvider ( ) . add ( uri ( "" ) , rule ( ) ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockExporterRetriever . create ( "" ) ; inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; } @ Test ( expected = IOException . class ) public void unknown_source ( ) throws Exception { TestResultInspector inspector = new TestResultInspector ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockVerifyRuleProvider ( ) . add ( uri ( "" ) , rule ( ) ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockExporterRetriever . create ( "" ) ; inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; } @ Test ( expected = IOException . class ) public void unknown_rule ( ) throws Exception { TestResultInspector inspector = new TestResultInspector ( new MockDataModelAdapter ( String . class ) , new MockSourceProvider ( ) . add ( uri ( "" ) , "" ) , new MockVerifyRuleProvider ( ) . add ( uri ( "" ) , rule ( ) ) , new MockExporterRetriever ( ) . wrap ( ) ) ; Desc desc = MockExporterRetriever . create ( "" ) ; inspector . inspect ( desc . getModelType ( ) , desc , context , uri ( "" ) , uri ( "" ) ) ; } private VerifyRule rule ( ) { return new VerifyRule ( ) { private final DataModelDefinition < String > def = ValueDefinition . of ( String . class ) ; @ Override public Object getKey ( DataModelReflection target ) { String string = def . toObject ( target ) ; String [ ] split = string . split ( "" , ) ; return split [ ] ; } @ Override public Object verify ( DataModelReflection expected , DataModelReflection actual ) { if ( expected == null || actual == null ) { return "" ; } String ex = def . toObject ( expected ) . split ( "" , ) [ ] ; String ac = def . toObject ( actual ) . split ( "" , ) [ ] ; return ex . equals ( ac ) ? null : "" ; } } ; } private URI uri ( String str ) { try { return new URI ( str ) ; } catch ( URISyntaxException e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . testdriver . core ; import java . lang . annotation . Annotation ; import java . util . Collection ; import java . util . Collections ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class ValueDefinition < T > implements DataModelDefinition < T > { public static final PropertyName VALUE = PropertyName . newInstance ( "" ) ; private final Class < T > type ; private final PropertyType kind ; public static < T > ValueDefinition < T > of ( Class < T > type ) { return new ValueDefinition < T > ( type ) ; } public ValueDefinition ( Class < T > type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . type = type ; this . kind = SimpleDataModelDefinition . getType ( VALUE , type ) ; if ( kind == null ) { throw new IllegalArgumentException ( type . getName ( ) ) ; } } @ Override public Class < T > getModelClass ( ) { return type ; } @ Override public < A extends Annotation > A getAnnotation ( Class < A > annotationType ) { return type . getAnnotation ( annotationType ) ; } @ Override public Collection < PropertyName > getProperties ( ) { return Collections . singleton ( VALUE ) ; } @ Override public PropertyType getType ( PropertyName name ) { if ( VALUE . equals ( name ) ) { return kind ; } return null ; } @ Override public < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) { return null ; } @ Override public Builder < T > newReflection ( ) { return new Builder < T > ( this ) ; } @ Override public DataModelReflection toReflection ( T object ) { return newReflection ( ) . add ( VALUE , object ) . build ( ) ; } @ Override public T toObject ( DataModelReflection reflection ) { return type . cast ( reflection . getValue ( VALUE ) ) ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; public class PropertyNameTest { @ Test public void simple ( ) { PropertyName name = PropertyName . newInstance ( "" ) ; assertThat ( name , is ( PropertyName . newInstance ( "" ) ) ) ; assertThat ( name , not ( PropertyName . newInstance ( "" ) ) ) ; assertThat ( name , not ( PropertyName . newInstance ( "" , "" ) ) ) ; } @ Test public void multi_word ( ) { PropertyName name = PropertyName . newInstance ( "" , "" ) ; assertThat ( name , not ( PropertyName . newInstance ( "" ) ) ) ; assertThat ( name , not ( PropertyName . newInstance ( "" ) ) ) ; assertThat ( name , is ( PropertyName . newInstance ( "" , "" ) ) ) ; assertThat ( name , not ( PropertyName . newInstance ( "" , "" , "" ) ) ) ; } @ Test public void number_after_underscore ( ) { PropertyName name = PropertyName . newInstance ( "" , "" ) ; assertThat ( name , is ( PropertyName . newInstance ( "" , "" ) ) ) ; assertThat ( name , is ( PropertyName . newInstance ( "" ) ) ) ; assertThat ( name , not ( PropertyName . newInstance ( "" , "" ) ) ) ; assertThat ( name , not ( PropertyName . newInstance ( "" ) ) ) ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import org . junit . Test ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class AbstractExporterRetrieverTest { @ Test public void getDescriptionClass ( ) { class Target extends AbstractExporterRetriever < DummyExporterDescription > { @ Override public void truncate ( DummyExporterDescription description ) throws IOException { return ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , DummyExporterDescription description ) throws IOException { return null ; } @ Override public < V > DataModelSource createSource ( DataModelDefinition < V > definition , DummyExporterDescription description ) throws IOException { return null ; } } Target obj = new Target ( ) ; assertThat ( obj . getDescriptionClass ( ) , is ( ( Object ) DummyExporterDescription . class ) ) ; } @ Test ( expected = RuntimeException . class ) public void getDescriptionClass_raw ( ) { @ SuppressWarnings ( "" ) class Target extends AbstractExporterRetriever { @ Override public void truncate ( ExporterDescription description ) { return ; } @ Override public ModelOutput createOutput ( DataModelDefinition definition , ExporterDescription description ) throws IOException { return null ; } @ Override public DataModelSource createSource ( DataModelDefinition definition , ExporterDescription description ) throws IOException { return null ; } } Target obj = new Target ( ) ; obj . getDescriptionClass ( ) ; } static abstract class DummyExporterDescription implements ExporterDescription { } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . URI ; import org . junit . Test ; public class SpiDataModelSourceProviderTest extends SpiTestRoot { @ Test public void open ( ) throws Exception { ClassLoader cl = register ( DataModelSourceProvider . class , Example . class ) ; SpiDataModelSourceProvider target = new SpiDataModelSourceProvider ( cl ) ; DataModelSource source = target . open ( ValueDefinition . of ( String . class ) , new URI ( "" ) , new TestContext . Empty ( ) ) ; assertThat ( source , not ( nullValue ( ) ) ) ; assertThat ( ValueDefinition . of ( String . class ) . toObject ( source . next ( ) ) , is ( "" ) ) ; } @ Test public void open_notfound ( ) throws Exception { ClassLoader cl = register ( DataModelSourceProvider . class , Example . class ) ; SpiDataModelSourceProvider target = new SpiDataModelSourceProvider ( cl ) ; DataModelSource source = target . open ( ValueDefinition . of ( String . class ) , new URI ( "" ) , new TestContext . Empty ( ) ) ; assertThat ( source , is ( nullValue ( ) ) ) ; } public static class Example implements DataModelSourceProvider { @ Override public < T > DataModelSource open ( DataModelDefinition < T > definition , URI source , TestContext context ) throws IOException { if ( source . getScheme ( ) . equals ( "" ) == false ) { return null ; } return source ( ValueDefinition . of ( String . class ) , "" ) ; } } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class AbstractImporterPreparatorTest { @ Test public void getDescriptionClass ( ) { class Target extends AbstractImporterPreparator < DummyImporterDescription > { @ Override public void truncate ( DummyImporterDescription description ) { return ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , DummyImporterDescription description ) { return null ; } } Target obj = new Target ( ) ; assertThat ( obj . getDescriptionClass ( ) , is ( ( Object ) DummyImporterDescription . class ) ) ; } @ Test ( expected = RuntimeException . class ) public void getDescriptionClass_raw ( ) { @ SuppressWarnings ( "" ) class Target extends AbstractImporterPreparator { @ Override public void truncate ( ImporterDescription description ) { return ; } @ Override public ModelOutput createOutput ( DataModelDefinition definition , ImporterDescription description ) { return null ; } } Target obj = new Target ( ) ; obj . getDescriptionClass ( ) ; } abstract static class DummyImporterDescription implements ImporterDescription { } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import org . junit . Test ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . MockImporterPreparator . Desc ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class SpiImporterPreparatorTest extends SpiTestRoot { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Test public void getDescriptionClass ( ) { SpiImporterPreparator target = new SpiImporterPreparator ( getClass ( ) . getClassLoader ( ) ) ; assertThat ( target . getDescriptionClass ( ) , equalTo ( ImporterDescription . class ) ) ; } @ Test public void open ( ) throws IOException { Desc desc = MockImporterPreparator . create ( ) ; ClassLoader cl = register ( ImporterPreparator . class , MockImporterPreparator . class ) ; SpiImporterPreparator target = new SpiImporterPreparator ( cl ) ; ModelOutput < ? super String > source = target . createOutput ( ValueDefinition . of ( String . class ) , desc , EMPTY ) ; source . write ( "" ) ; source . close ( ) ; assertThat ( desc . lines , is ( Arrays . asList ( "" ) ) ) ; } @ Test ( expected = IOException . class ) public void open_notfound ( ) throws IOException { Desc desc = MockImporterPreparator . create ( ) ; SpiImporterPreparator target = new SpiImporterPreparator ( getClass ( ) . getClassLoader ( ) ) ; target . createOutput ( ValueDefinition . of ( String . class ) , desc , EMPTY ) ; } } package com . asakusafw . testdriver . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; public class SpiDataModelAdapterTest extends SpiTestRoot { @ Test public void getDefinition ( ) { ClassLoader cl = register ( DataModelAdapter . class , MockDataModelAdapter . class ) ; DataModelAdapter adapter = new SpiDataModelAdapter ( cl ) ; assertThat ( adapter . get ( String . class ) , instanceOf ( ValueDefinition . class ) ) ; assertThat ( adapter . get ( Integer . class ) , is ( nullValue ( ) ) ) ; } } package com . asakusafw . testdriver . core ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . Arrays ; import org . junit . Rule ; import org . junit . rules . TemporaryFolder ; public abstract class SpiTestRoot { @ Rule public TemporaryFolder temporaryFolder = new TemporaryFolder ( ) ; public ClassLoader register ( Class < ? > api , Class < ? > ... services ) { File classpath = temporaryFolder . newFolder ( "" ) ; try { File serviceFolder = new File ( classpath , "" ) ; serviceFolder . mkdirs ( ) ; PrintWriter output = new PrintWriter ( new File ( serviceFolder , api . getName ( ) ) ) ; try { for ( Class < ? > serviceClass : services ) { output . println ( serviceClass . getName ( ) ) ; } } finally { output . close ( ) ; } return new URLClassLoader ( new URL [ ] { classpath . toURI ( ) . toURL ( ) } ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } public static < E > DataModelSource source ( DataModelDefinition < E > definition , E ... values ) { return new IteratorDataModelSource ( definition , Arrays . asList ( values ) . iterator ( ) ) ; } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map ; public class MockSourceProvider implements DataModelSourceProvider { private final Map < URI , DataModelSource > sources = new HashMap < URI , DataModelSource > ( ) ; public MockSourceProvider ( ) { try { add ( new URI ( "" ) , "" ) ; } catch ( URISyntaxException e ) { throw new AssertionError ( e ) ; } } public final < T > MockSourceProvider add ( URI uri , DataModelDefinition < T > def , Iterable < ? extends T > iter ) { sources . put ( uri , new IteratorDataModelSource ( def , iter . iterator ( ) ) ) ; return this ; } public final MockSourceProvider add ( URI uri , String ... lines ) { return add ( uri , ValueDefinition . of ( String . class ) , Arrays . asList ( lines ) ) ; } @ Override public < T > DataModelSource open ( DataModelDefinition < T > definition , URI source , TestContext context ) throws IOException { return sources . get ( source ) ; } } package com . asakusafw . testdriver . model ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . math . BigDecimal ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . List ; import org . junit . Test ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; import com . asakusafw . testdriver . testing . model . Naming ; import com . asakusafw . testdriver . testing . model . Ordered ; import com . asakusafw . testdriver . testing . model . Simple ; import com . asakusafw . testdriver . testing . model . Variety ; public class DefaultDataModelDefinitionTest { @ Test public void simple ( ) { DefaultDataModelDefinition < Simple > def = new DefaultDataModelDefinition < Simple > ( Simple . class ) ; assertThat ( def . getModelClass ( ) , equalTo ( Simple . class ) ) ; } @ Test public void naming ( ) { DefaultDataModelDefinition < Naming > def = new DefaultDataModelDefinition < Naming > ( Naming . class ) ; assertThat ( def . getType ( p ( "" ) ) , not ( nullValue ( ) ) ) ; assertThat ( def . getType ( p ( "" ) ) , not ( nullValue ( ) ) ) ; } @ Test public void getType ( ) { DefaultDataModelDefinition < Variety > def = new DefaultDataModelDefinition < Variety > ( Variety . class ) ; assertThat ( def . getType ( p ( "" ) ) , is ( nullValue ( ) ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . INT ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . LONG ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . BYTE ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . SHORT ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . FLOAT ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . DOUBLE ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . DECIMAL ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . STRING ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . BOOLEAN ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . DATE ) ) ; assertThat ( def . getType ( p ( "" ) ) , is ( PropertyType . DATETIME ) ) ; } @ Test public void getProperties ( ) { DefaultDataModelDefinition < Ordered > def = new DefaultDataModelDefinition < Ordered > ( Ordered . class ) ; List < PropertyName > properties = new ArrayList < PropertyName > ( def . getProperties ( ) ) ; assertThat ( properties . size ( ) , is ( ) ) ; assertThat ( properties . get ( ) , is ( PropertyName . newInstance ( "" ) ) ) ; assertThat ( properties . get ( ) , is ( PropertyName . newInstance ( "" , "" ) ) ) ; assertThat ( properties . get ( ) , is ( PropertyName . newInstance ( "" ) ) ) ; assertThat ( properties . get ( ) , is ( PropertyName . newInstance ( "" ) ) ) ; } @ Test public void toReflection ( ) { DefaultDataModelDefinition < Variety > def = new DefaultDataModelDefinition < Variety > ( Variety . class ) ; Variety object = new Variety ( ) ; object . setPInt ( ) ; object . setPLong ( ) ; object . setPByte ( ( byte ) ) ; object . setPShort ( ( short ) ) ; object . setPFloat ( ) ; object . setPDouble ( ) ; object . setPDecimal ( new BigDecimal ( "" ) ) ; object . setPTextAsString ( "" ) ; object . setPBoolean ( true ) ; object . setPDate ( new Date ( , , ) ) ; object . setPDatetime ( new DateTime ( , , , , , ) ) ; DataModelReflection ref = def . toReflection ( object ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) ) ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) ) ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) ( byte ) ) ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) ( short ) ) ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) ) ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) ) ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) new BigDecimal ( "" ) ) ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) "" ) ) ; assertThat ( ref . getValue ( p ( "" ) ) , is ( ( Object ) true ) ) ; Calendar date = ( Calendar ) ref . getValue ( p ( "" ) ) ; assertThat ( new SimpleDateFormat ( "" ) . format ( date . getTime ( ) ) , is ( "" ) ) ; Calendar datetime = ( Calendar ) ref . getValue ( p ( "" ) ) ; assertThat ( new SimpleDateFormat ( "" ) . format ( datetime . getTime ( ) ) , is ( "" ) ) ; } @ Test public void toObject ( ) { DefaultDataModelDefinition < Variety > def = new DefaultDataModelDefinition < Variety > ( Variety . class ) ; Variety object = new Variety ( ) ; object . setPInt ( ) ; object . setPLong ( ) ; object . setPByte ( ( byte ) ) ; object . setPShort ( ( short ) ) ; object . setPFloat ( ) ; object . setPDouble ( ) ; object . setPByte ( ( byte ) ) ; object . setPDecimal ( new BigDecimal ( "" ) ) ; object . setPTextAsString ( "" ) ; object . setPBoolean ( true ) ; object . setPDate ( new Date ( , , ) ) ; object . setPDatetime ( new DateTime ( , , , , , ) ) ; DataModelReflection ref = def . toReflection ( object ) ; Variety restored = def . toObject ( ref ) ; assertThat ( restored , not ( sameInstance ( object ) ) ) ; assertThat ( restored , equalTo ( object ) ) ; } private PropertyName p ( String snake_name ) { return PropertyName . newInstance ( snake_name . split ( "" ) ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . testdriver . testing . model . Simple ; public final class SimpleOutput implements ModelOutput < Simple > { private final RecordEmitter emitter ; public SimpleOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Simple model ) throws IOException { emitter . emit ( model . getDataOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . testdriver . testing . model . Naming ; public final class NamingOutput implements ModelOutput < Naming > { private final RecordEmitter emitter ; public NamingOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Naming model ) throws IOException { emitter . emit ( model . getAOption ( ) ) ; emitter . emit ( model . getVeryVeryVeryLongNameOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . testdriver . testing . model . Ordered ; public final class OrderedInput implements ModelInput < Ordered > { private final RecordParser parser ; public OrderedInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Ordered model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getFirstOption ( ) ) ; parser . fill ( model . getSecondPropertyOption ( ) ) ; parser . fill ( model . getAOption ( ) ) ; parser . fill ( model . getLastOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . testdriver . testing . model . Variety ; public final class VarietyInput implements ModelInput < Variety > { private final RecordParser parser ; public VarietyInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Variety model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getPIntOption ( ) ) ; parser . fill ( model . getPLongOption ( ) ) ; parser . fill ( model . getPByteOption ( ) ) ; parser . fill ( model . getPShortOption ( ) ) ; parser . fill ( model . getPDecimalOption ( ) ) ; parser . fill ( model . getPFloatOption ( ) ) ; parser . fill ( model . getPDoubleOption ( ) ) ; parser . fill ( model . getPTextOption ( ) ) ; parser . fill ( model . getPBooleanOption ( ) ) ; parser . fill ( model . getPDateOption ( ) ) ; parser . fill ( model . getPDatetimeOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . testdriver . testing . model . Projection ; public final class ProjectionOutput implements ModelOutput < Projection > { private final RecordEmitter emitter ; public ProjectionOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Projection model ) throws IOException { emitter . emit ( model . getDataOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . testdriver . testing . model . Simple ; public final class SimpleInput implements ModelInput < Simple > { private final RecordParser parser ; public SimpleInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Simple model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getDataOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . testdriver . testing . model . Ordered ; public final class OrderedOutput implements ModelOutput < Ordered > { private final RecordEmitter emitter ; public OrderedOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Ordered model ) throws IOException { emitter . emit ( model . getFirstOption ( ) ) ; emitter . emit ( model . getSecondPropertyOption ( ) ) ; emitter . emit ( model . getAOption ( ) ) ; emitter . emit ( model . getLastOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . testdriver . testing . model . Naming ; public final class NamingInput implements ModelInput < Naming > { private final RecordParser parser ; public NamingInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Naming model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getAOption ( ) ) ; parser . fill ( model . getVeryVeryVeryLongNameOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . testdriver . testing . model . Projection ; public final class ProjectionInput implements ModelInput < Projection > { private final RecordParser parser ; public ProjectionInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Projection model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getDataOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . testdriver . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . testdriver . testing . model . Variety ; public final class VarietyOutput implements ModelOutput < Variety > { private final RecordEmitter emitter ; public VarietyOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Variety model ) throws IOException { emitter . emit ( model . getPIntOption ( ) ) ; emitter . emit ( model . getPLongOption ( ) ) ; emitter . emit ( model . getPByteOption ( ) ) ; emitter . emit ( model . getPShortOption ( ) ) ; emitter . emit ( model . getPDecimalOption ( ) ) ; emitter . emit ( model . getPFloatOption ( ) ) ; emitter . emit ( model . getPDoubleOption ( ) ) ; emitter . emit ( model . getPTextOption ( ) ) ; emitter . emit ( model . getPBooleanOption ( ) ) ; emitter . emit ( model . getPDateOption ( ) ) ; emitter . emit ( model . getPDatetimeOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . testdriver . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . math . BigDecimal ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . testdriver . testing . io . VarietyInput ; import com . asakusafw . testdriver . testing . io . VarietyOutput ; @ DataModelKind ( "" ) @ ModelInputLocation ( VarietyInput . class ) @ ModelOutputLocation ( VarietyOutput . class ) @ PropertyOrder ( { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ) public class Variety implements DataModel < Variety > , Writable { private final IntOption pInt = new IntOption ( ) ; private final LongOption pLong = new LongOption ( ) ; private final ByteOption pByte = new ByteOption ( ) ; private final ShortOption pShort = new ShortOption ( ) ; private final DecimalOption pDecimal = new DecimalOption ( ) ; private final FloatOption pFloat = new FloatOption ( ) ; private final DoubleOption pDouble = new DoubleOption ( ) ; private final StringOption pText = new StringOption ( ) ; private final BooleanOption pBoolean = new BooleanOption ( ) ; private final DateOption pDate = new DateOption ( ) ; private final DateTimeOption pDatetime = new DateTimeOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . pInt . setNull ( ) ; this . pLong . setNull ( ) ; this . pByte . setNull ( ) ; this . pShort . setNull ( ) ; this . pDecimal . setNull ( ) ; this . pFloat . setNull ( ) ; this . pDouble . setNull ( ) ; this . pText . setNull ( ) ; this . pBoolean . setNull ( ) ; this . pDate . setNull ( ) ; this . pDatetime . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Variety other ) { this . pInt . copyFrom ( other . pInt ) ; this . pLong . copyFrom ( other . pLong ) ; this . pByte . copyFrom ( other . pByte ) ; this . pShort . copyFrom ( other . pShort ) ; this . pDecimal . copyFrom ( other . pDecimal ) ; this . pFloat . copyFrom ( other . pFloat ) ; this . pDouble . copyFrom ( other . pDouble ) ; this . pText . copyFrom ( other . pText ) ; this . pBoolean . copyFrom ( other . pBoolean ) ; this . pDate . copyFrom ( other . pDate ) ; this . pDatetime . copyFrom ( other . pDatetime ) ; } public int getPInt ( ) { return this . pInt . get ( ) ; } @ SuppressWarnings ( "" ) public void setPInt ( int value ) { this . pInt . modify ( value ) ; } public IntOption getPIntOption ( ) { return this . pInt ; } @ SuppressWarnings ( "" ) public void setPIntOption ( IntOption option ) { this . pInt . copyFrom ( option ) ; } public long getPLong ( ) { return this . pLong . get ( ) ; } @ SuppressWarnings ( "" ) public void setPLong ( long value ) { this . pLong . modify ( value ) ; } public LongOption getPLongOption ( ) { return this . pLong ; } @ SuppressWarnings ( "" ) public void setPLongOption ( LongOption option ) { this . pLong . copyFrom ( option ) ; } public byte getPByte ( ) { return this . pByte . get ( ) ; } @ SuppressWarnings ( "" ) public void setPByte ( byte value ) { this . pByte . modify ( value ) ; } public ByteOption getPByteOption ( ) { return this . pByte ; } @ SuppressWarnings ( "" ) public void setPByteOption ( ByteOption option ) { this . pByte . copyFrom ( option ) ; } public short getPShort ( ) { return this . pShort . get ( ) ; } @ SuppressWarnings ( "" ) public void setPShort ( short value ) { this . pShort . modify ( value ) ; } public ShortOption getPShortOption ( ) { return this . pShort ; } @ SuppressWarnings ( "" ) public void setPShortOption ( ShortOption option ) { this . pShort . copyFrom ( option ) ; } public BigDecimal getPDecimal ( ) { return this . pDecimal . get ( ) ; } @ SuppressWarnings ( "" ) public void setPDecimal ( BigDecimal value ) { this . pDecimal . modify ( value ) ; } public DecimalOption getPDecimalOption ( ) { return this . pDecimal ; } @ SuppressWarnings ( "" ) public void setPDecimalOption ( DecimalOption option ) { this . pDecimal . copyFrom ( option ) ; } public float getPFloat ( ) { return this . pFloat . get ( ) ; } @ SuppressWarnings ( "" ) public void setPFloat ( float value ) { this . pFloat . modify ( value ) ; } public FloatOption getPFloatOption ( ) { return this . pFloat ; } @ SuppressWarnings ( "" ) public void setPFloatOption ( FloatOption option ) { this . pFloat . copyFrom ( option ) ; } public double getPDouble ( ) { return this . pDouble . get ( ) ; } @ SuppressWarnings ( "" ) public void setPDouble ( double value ) { this . pDouble . modify ( value ) ; } public DoubleOption getPDoubleOption ( ) { return this . pDouble ; } @ SuppressWarnings ( "" ) public void setPDoubleOption ( DoubleOption option ) { this . pDouble . copyFrom ( option ) ; } public Text getPText ( ) { return this . pText . get ( ) ; } @ SuppressWarnings ( "" ) public void setPText ( Text value ) { this . pText . modify ( value ) ; } public StringOption getPTextOption ( ) { return this . pText ; } @ SuppressWarnings ( "" ) public void setPTextOption ( StringOption option ) { this . pText . copyFrom ( option ) ; } public boolean isPBoolean ( ) { return this . pBoolean . get ( ) ; } @ SuppressWarnings ( "" ) public void setPBoolean ( boolean value ) { this . pBoolean . modify ( value ) ; } public BooleanOption getPBooleanOption ( ) { return this . pBoolean ; } @ SuppressWarnings ( "" ) public void setPBooleanOption ( BooleanOption option ) { this . pBoolean . copyFrom ( option ) ; } public Date getPDate ( ) { return this . pDate . get ( ) ; } @ SuppressWarnings ( "" ) public void setPDate ( Date value ) { this . pDate . modify ( value ) ; } public DateOption getPDateOption ( ) { return this . pDate ; } @ SuppressWarnings ( "" ) public void setPDateOption ( DateOption option ) { this . pDate . copyFrom ( option ) ; } public DateTime getPDatetime ( ) { return this . pDatetime . get ( ) ; } @ SuppressWarnings ( "" ) public void setPDatetime ( DateTime value ) { this . pDatetime . modify ( value ) ; } public DateTimeOption getPDatetimeOption ( ) { return this . pDatetime ; } @ SuppressWarnings ( "" ) public void setPDatetimeOption ( DateTimeOption option ) { this . pDatetime . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . pInt ) ; result . append ( "" ) ; result . append ( this . pLong ) ; result . append ( "" ) ; result . append ( this . pByte ) ; result . append ( "" ) ; result . append ( this . pShort ) ; result . append ( "" ) ; result . append ( this . pDecimal ) ; result . append ( "" ) ; result . append ( this . pFloat ) ; result . append ( "" ) ; result . append ( this . pDouble ) ; result . append ( "" ) ; result . append ( this . pText ) ; result . append ( "" ) ; result . append ( this . pBoolean ) ; result . append ( "" ) ; result . append ( this . pDate ) ; result . append ( "" ) ; result . append ( this . pDatetime ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + pInt . hashCode ( ) ; result = prime * result + pLong . hashCode ( ) ; result = prime * result + pByte . hashCode ( ) ; result = prime * result + pShort . hashCode ( ) ; result = prime * result + pDecimal . hashCode ( ) ; result = prime * result + pFloat . hashCode ( ) ; result = prime * result + pDouble . hashCode ( ) ; result = prime * result + pText . hashCode ( ) ; result = prime * result + pBoolean . hashCode ( ) ; result = prime * result + pDate . hashCode ( ) ; result = prime * result + pDatetime . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Variety other = ( Variety ) obj ; if ( this . pInt . equals ( other . pInt ) == false ) { return false ; } if ( this . pLong . equals ( other . pLong ) == false ) { return false ; } if ( this . pByte . equals ( other . pByte ) == false ) { return false ; } if ( this . pShort . equals ( other . pShort ) == false ) { return false ; } if ( this . pDecimal . equals ( other . pDecimal ) == false ) { return false ; } if ( this . pFloat . equals ( other . pFloat ) == false ) { return false ; } if ( this . pDouble . equals ( other . pDouble ) == false ) { return false ; } if ( this . pText . equals ( other . pText ) == false ) { return false ; } if ( this . pBoolean . equals ( other . pBoolean ) == false ) { return false ; } if ( this . pDate . equals ( other . pDate ) == false ) { return false ; } if ( this . pDatetime . equals ( other . pDatetime ) == false ) { return false ; } return true ; } public String getPTextAsString ( ) { return this . pText . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setPTextAsString ( String pText0 ) { this . pText . modify ( pText0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { pInt . write ( out ) ; pLong . write ( out ) ; pByte . write ( out ) ; pShort . write ( out ) ; pDecimal . write ( out ) ; pFloat . write ( out ) ; pDouble . write ( out ) ; pText . write ( out ) ; pBoolean . write ( out ) ; pDate . write ( out ) ; pDatetime . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { pInt . readFields ( in ) ; pLong . readFields ( in ) ; pByte . readFields ( in ) ; pShort . readFields ( in ) ; pDecimal . readFields ( in ) ; pFloat . readFields ( in ) ; pDouble . readFields ( in ) ; pText . readFields ( in ) ; pBoolean . readFields ( in ) ; pDate . readFields ( in ) ; pDatetime . readFields ( in ) ; } } package com . asakusafw . testdriver . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . testdriver . testing . io . SimpleInput ; import com . asakusafw . testdriver . testing . io . SimpleOutput ; @ DataModelKind ( "" ) @ ModelInputLocation ( SimpleInput . class ) @ ModelOutputLocation ( SimpleOutput . class ) @ PropertyOrder ( { "" } ) public class Simple implements DataModel < Simple > , Projection , Writable { private final StringOption data = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . data . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Simple other ) { this . data . copyFrom ( other . data ) ; } @ Override public Text getData ( ) { return this . data . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setData ( Text value ) { this . data . modify ( value ) ; } @ Override public StringOption getDataOption ( ) { return this . data ; } @ Override @ SuppressWarnings ( "" ) public void setDataOption ( StringOption option ) { this . data . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . data ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + data . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Simple other = ( Simple ) obj ; if ( this . data . equals ( other . data ) == false ) { return false ; } return true ; } @ Override public String getDataAsString ( ) { return this . data . getAsString ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setDataAsString ( String data0 ) { this . data . modify ( data0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { data . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { data . readFields ( in ) ; } } package com . asakusafw . testdriver . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . testdriver . testing . io . OrderedInput ; import com . asakusafw . testdriver . testing . io . OrderedOutput ; @ DataModelKind ( "" ) @ ModelInputLocation ( OrderedInput . class ) @ ModelOutputLocation ( OrderedOutput . class ) @ PropertyOrder ( { "" , "" , "" , "" } ) public class Ordered implements DataModel < Ordered > , Writable { private final IntOption first = new IntOption ( ) ; private final IntOption secondProperty = new IntOption ( ) ; private final StringOption a = new StringOption ( ) ; private final IntOption last = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . first . setNull ( ) ; this . secondProperty . setNull ( ) ; this . a . setNull ( ) ; this . last . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Ordered other ) { this . first . copyFrom ( other . first ) ; this . secondProperty . copyFrom ( other . secondProperty ) ; this . a . copyFrom ( other . a ) ; this . last . copyFrom ( other . last ) ; } public int getFirst ( ) { return this . first . get ( ) ; } @ SuppressWarnings ( "" ) public void setFirst ( int value ) { this . first . modify ( value ) ; } public IntOption getFirstOption ( ) { return this . first ; } @ SuppressWarnings ( "" ) public void setFirstOption ( IntOption option ) { this . first . copyFrom ( option ) ; } public int getSecondProperty ( ) { return this . secondProperty . get ( ) ; } @ SuppressWarnings ( "" ) public void setSecondProperty ( int value ) { this . secondProperty . modify ( value ) ; } public IntOption getSecondPropertyOption ( ) { return this . secondProperty ; } @ SuppressWarnings ( "" ) public void setSecondPropertyOption ( IntOption option ) { this . secondProperty . copyFrom ( option ) ; } public Text getA ( ) { return this . a . get ( ) ; } @ SuppressWarnings ( "" ) public void setA ( Text value ) { this . a . modify ( value ) ; } public StringOption getAOption ( ) { return this . a ; } @ SuppressWarnings ( "" ) public void setAOption ( StringOption option ) { this . a . copyFrom ( option ) ; } public int getLast ( ) { return this . last . get ( ) ; } @ SuppressWarnings ( "" ) public void setLast ( int value ) { this . last . modify ( value ) ; } public IntOption getLastOption ( ) { return this . last ; } @ SuppressWarnings ( "" ) public void setLastOption ( IntOption option ) { this . last . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . first ) ; result . append ( "" ) ; result . append ( this . secondProperty ) ; result . append ( "" ) ; result . append ( this . a ) ; result . append ( "" ) ; result . append ( this . last ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + first . hashCode ( ) ; result = prime * result + secondProperty . hashCode ( ) ; result = prime * result + a . hashCode ( ) ; result = prime * result + last . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Ordered other = ( Ordered ) obj ; if ( this . first . equals ( other . first ) == false ) { return false ; } if ( this . secondProperty . equals ( other . secondProperty ) == false ) { return false ; } if ( this . a . equals ( other . a ) == false ) { return false ; } if ( this . last . equals ( other . last ) == false ) { return false ; } return true ; } public String getAAsString ( ) { return this . a . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setAAsString ( String a0 ) { this . a . modify ( a0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { first . write ( out ) ; secondProperty . write ( out ) ; a . write ( out ) ; last . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { first . readFields ( in ) ; secondProperty . readFields ( in ) ; a . readFields ( in ) ; last . readFields ( in ) ; } } package com . asakusafw . testdriver . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . testdriver . testing . io . NamingInput ; import com . asakusafw . testdriver . testing . io . NamingOutput ; @ DataModelKind ( "" ) @ ModelInputLocation ( NamingInput . class ) @ ModelOutputLocation ( NamingOutput . class ) @ PropertyOrder ( { "" , "" } ) public class Naming implements DataModel < Naming > , Writable { private final IntOption a = new IntOption ( ) ; private final LongOption veryVeryVeryLongName = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . a . setNull ( ) ; this . veryVeryVeryLongName . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Naming other ) { this . a . copyFrom ( other . a ) ; this . veryVeryVeryLongName . copyFrom ( other . veryVeryVeryLongName ) ; } public int getA ( ) { return this . a . get ( ) ; } @ SuppressWarnings ( "" ) public void setA ( int value ) { this . a . modify ( value ) ; } public IntOption getAOption ( ) { return this . a ; } @ SuppressWarnings ( "" ) public void setAOption ( IntOption option ) { this . a . copyFrom ( option ) ; } public long getVeryVeryVeryLongName ( ) { return this . veryVeryVeryLongName . get ( ) ; } @ SuppressWarnings ( "" ) public void setVeryVeryVeryLongName ( long value ) { this . veryVeryVeryLongName . modify ( value ) ; } public LongOption getVeryVeryVeryLongNameOption ( ) { return this . veryVeryVeryLongName ; } @ SuppressWarnings ( "" ) public void setVeryVeryVeryLongNameOption ( LongOption option ) { this . veryVeryVeryLongName . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . a ) ; result . append ( "" ) ; result . append ( this . veryVeryVeryLongName ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + a . hashCode ( ) ; result = prime * result + veryVeryVeryLongName . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Naming other = ( Naming ) obj ; if ( this . a . equals ( other . a ) == false ) { return false ; } if ( this . veryVeryVeryLongName . equals ( other . veryVeryVeryLongName ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { a . write ( out ) ; veryVeryVeryLongName . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { a . readFields ( in ) ; veryVeryVeryLongName . readFields ( in ) ; } } package com . asakusafw . testdriver . testing . model ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . testdriver . testing . io . ProjectionInput ; import com . asakusafw . testdriver . testing . io . ProjectionOutput ; @ DataModelKind ( "" ) @ ModelInputLocation ( ProjectionInput . class ) @ ModelOutputLocation ( ProjectionOutput . class ) @ PropertyOrder ( { "" } ) public interface Projection extends Writable { Text getData ( ) ; void setData ( Text value ) ; StringOption getDataOption ( ) ; void setDataOption ( StringOption option ) ; String getDataAsString ( ) ; void setDataAsString ( String data0 ) ; } package com . asakusafw . testdriver . model ; import java . lang . annotation . Annotation ; import java . lang . reflect . Field ; import java . lang . reflect . Modifier ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . regex . Pattern ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; public class SimpleDataModelDefinition < T > implements DataModelDefinition < T > { private static final Map < Class < ? > , PropertyType > TYPES ; static { Map < Class < ? > , PropertyType > map = new HashMap < Class < ? > , PropertyType > ( ) ; for ( PropertyType type : PropertyType . values ( ) ) { map . put ( type . getRepresentation ( ) , type ) ; } map . put ( PropertyType . DATETIME . getRepresentation ( ) , PropertyType . DATETIME ) ; TYPES = Collections . unmodifiableMap ( map ) ; } private final Class < T > modelClass ; private final Map < PropertyName , Field > fields ; public SimpleDataModelDefinition ( Class < T > modelClass ) { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . modelClass = modelClass ; this . fields = collectProperties ( ) ; } private Map < PropertyName , Field > collectProperties ( ) { Map < PropertyName , Field > results = new HashMap < PropertyName , Field > ( ) ; for ( Field field : modelClass . getDeclaredFields ( ) ) { PropertyName name = extract ( field ) ; if ( name != null ) { results . put ( name , field ) ; } } return Collections . unmodifiableMap ( results ) ; } private static final Pattern NAME = Pattern . compile ( "" ) ; private PropertyName extract ( Field field ) { assert field != null ; if ( Modifier . isPublic ( field . getModifiers ( ) ) == false ) { return null ; } if ( TYPES . containsKey ( field . getType ( ) ) == false ) { return null ; } String name = field . getName ( ) ; if ( NAME . matcher ( name ) . matches ( ) == false ) { return null ; } List < String > words = new ArrayList < String > ( ) ; int start = ; for ( int i = , n = name . length ( ) ; i < n ; i ++ ) { char c = name . charAt ( i ) ; if ( '' <= c && c <= '' ) { words . add ( name . substring ( start , i ) ) ; start = i ; } } words . add ( name . substring ( start ) ) ; return PropertyName . newInstance ( words ) ; } @ Override public Class < T > getModelClass ( ) { return modelClass ; } @ Override public < A extends Annotation > A getAnnotation ( Class < A > annotationType ) { return modelClass . getAnnotation ( annotationType ) ; } @ Override public Collection < PropertyName > getProperties ( ) { return Collections . unmodifiableCollection ( fields . keySet ( ) ) ; } @ Override public PropertyType getType ( PropertyName name ) { Field field = fields . get ( name ) ; return field == null ? null : getType ( name , field . getType ( ) ) ; } public static PropertyType getType ( PropertyName name , Class < ? > type ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } PropertyType kind = TYPES . get ( type ) ; if ( kind == null ) { return null ; } if ( kind . getRepresentation ( ) == Calendar . class ) { List < String > words = name . getWords ( ) ; if ( words . contains ( PropertyType . DATE . name ( ) . toLowerCase ( ) ) ) { return PropertyType . DATE ; } else if ( words . contains ( PropertyType . TIME . name ( ) . toLowerCase ( ) ) ) { return PropertyType . TIME ; } else if ( words . contains ( PropertyType . DATETIME . name ( ) . toLowerCase ( ) ) ) { return PropertyType . DATETIME ; } } return kind ; } @ Override public < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) { Field field = fields . get ( name ) ; return field == null ? null : field . getAnnotation ( annotationType ) ; } @ Override public Builder < T > newReflection ( ) { return new Builder < T > ( this ) ; } @ Override public DataModelReflection toReflection ( T object ) { Builder < T > builder = newReflection ( ) ; for ( Map . Entry < PropertyName , Field > entry : fields . entrySet ( ) ) { PropertyName name = entry . getKey ( ) ; Field field = entry . getValue ( ) ; try { Object value = field . get ( object ) ; builder . add ( name , value ) ; } catch ( IllegalAccessException e ) { throw new AssertionError ( e ) ; } } return builder . build ( ) ; } @ Override public T toObject ( DataModelReflection reflection ) { try { T instance = modelClass . newInstance ( ) ; for ( Map . Entry < PropertyName , Field > entry : fields . entrySet ( ) ) { PropertyName name = entry . getKey ( ) ; Field field = entry . getValue ( ) ; Object value = reflection . getValue ( name ) ; try { field . set ( instance , value ) ; } catch ( IllegalAccessException e ) { throw new AssertionError ( e ) ; } } return instance ; } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } } } package com . asakusafw . testdriver . model ; package com . asakusafw . testdriver . model ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . testdriver . core . DataModelAdapter ; import com . asakusafw . testdriver . core . DataModelDefinition ; public class DefaultDataModelAdapter implements DataModelAdapter { private static final String KIND_NAME = "" ; @ Override public < T > DataModelDefinition < T > get ( Class < T > modelClass ) { if ( DataModel . class . isAssignableFrom ( modelClass ) == false ) { return null ; } DataModelKind kind = modelClass . getAnnotation ( DataModelKind . class ) ; if ( kind == null || kind . value ( ) . equals ( KIND_NAME ) == false ) { return null ; } return new DefaultDataModelDefinition < T > ( modelClass ) ; } } package com . asakusafw . testdriver . model ; import java . lang . annotation . Annotation ; import java . lang . reflect . Method ; import java . math . BigDecimal ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; public class DefaultDataModelDefinition < T > implements DataModelDefinition < T > { static final Logger LOG = LoggerFactory . getLogger ( DefaultDataModelDefinition . class ) ; private static final Map < Class < ? > , ValueDriver < ? > > VALUE_DRIVERS ; static { Map < Class < ? > , ValueDriver < ? > > map = new HashMap < Class < ? > , ValueDriver < ? > > ( ) ; map . put ( BooleanOption . class , new ValueDriver < BooleanOption > ( PropertyType . BOOLEAN ) { @ SuppressWarnings ( "" ) @ Override void modify ( BooleanOption holder , Object value ) { holder . modify ( cast ( Boolean . class , value ) ) ; } @ Override Object extract ( BooleanOption holder ) { return holder . get ( ) ; } } ) ; map . put ( ByteOption . class , new ValueDriver < ByteOption > ( PropertyType . BYTE ) { @ SuppressWarnings ( "" ) @ Override void modify ( ByteOption holder , Object value ) { holder . modify ( cast ( Number . class , value ) . byteValue ( ) ) ; } @ Override Object extract ( ByteOption holder ) { return holder . get ( ) ; } } ) ; map . put ( ShortOption . class , new ValueDriver < ShortOption > ( PropertyType . SHORT ) { @ SuppressWarnings ( "" ) @ Override void modify ( ShortOption holder , Object value ) { holder . modify ( cast ( Number . class , value ) . shortValue ( ) ) ; } @ Override Object extract ( ShortOption holder ) { return holder . get ( ) ; } } ) ; map . put ( IntOption . class , new ValueDriver < IntOption > ( PropertyType . INT ) { @ SuppressWarnings ( "" ) @ Override void modify ( IntOption holder , Object value ) { holder . modify ( cast ( Number . class , value ) . intValue ( ) ) ; } @ Override Object extract ( IntOption holder ) { return holder . get ( ) ; } } ) ; map . put ( LongOption . class , new ValueDriver < LongOption > ( PropertyType . LONG ) { @ SuppressWarnings ( "" ) @ Override void modify ( LongOption holder , Object value ) { holder . modify ( cast ( Number . class , value ) . longValue ( ) ) ; } @ Override Object extract ( LongOption holder ) { return holder . get ( ) ; } } ) ; map . put ( FloatOption . class , new ValueDriver < FloatOption > ( PropertyType . FLOAT ) { @ SuppressWarnings ( "" ) @ Override void modify ( FloatOption holder , Object value ) { holder . modify ( cast ( Number . class , value ) . floatValue ( ) ) ; } @ Override Object extract ( FloatOption holder ) { return holder . get ( ) ; } } ) ; map . put ( DoubleOption . class , new ValueDriver < DoubleOption > ( PropertyType . DOUBLE ) { @ SuppressWarnings ( "" ) @ Override void modify ( DoubleOption holder , Object value ) { holder . modify ( cast ( Number . class , value ) . doubleValue ( ) ) ; } @ Override Object extract ( DoubleOption holder ) { return holder . get ( ) ; } } ) ; map . put ( DecimalOption . class , new ValueDriver < DecimalOption > ( PropertyType . DECIMAL ) { @ SuppressWarnings ( "" ) @ Override void modify ( DecimalOption holder , Object value ) { holder . modify ( cast ( BigDecimal . class , value ) ) ; } @ Override Object extract ( DecimalOption holder ) { return holder . get ( ) ; } } ) ; map . put ( StringOption . class , new ValueDriver < StringOption > ( PropertyType . STRING ) { @ SuppressWarnings ( "" ) @ Override void modify ( StringOption holder , Object value ) { holder . modify ( cast ( String . class , value ) ) ; } @ Override Object extract ( StringOption holder ) { return holder . getAsString ( ) ; } } ) ; map . put ( DateOption . class , new ValueDriver < DateOption > ( PropertyType . DATE ) { @ SuppressWarnings ( "" ) @ Override void modify ( DateOption holder , Object value ) { Calendar calendar = ( Calendar ) value ; holder . modify ( new Date ( calendar . get ( Calendar . YEAR ) , calendar . get ( Calendar . MONTH ) + , calendar . get ( Calendar . DATE ) ) ) ; } @ Override Object extract ( DateOption holder ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( Calendar . YEAR , holder . get ( ) . getYear ( ) ) ; calendar . set ( Calendar . MONTH , holder . get ( ) . getMonth ( ) - ) ; calendar . set ( Calendar . DATE , holder . get ( ) . getDay ( ) ) ; return calendar ; } } ) ; map . put ( DateTimeOption . class , new ValueDriver < DateTimeOption > ( PropertyType . DATETIME ) { @ SuppressWarnings ( "" ) @ Override void modify ( DateTimeOption holder , Object value ) { Calendar calendar = ( Calendar ) value ; holder . modify ( new DateTime ( calendar . get ( Calendar . YEAR ) , calendar . get ( Calendar . MONTH ) + , calendar . get ( Calendar . DATE ) , calendar . get ( Calendar . HOUR_OF_DAY ) , calendar . get ( Calendar . MINUTE ) , calendar . get ( Calendar . SECOND ) ) ) ; } @ Override Object extract ( DateTimeOption holder ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( Calendar . YEAR , holder . get ( ) . getYear ( ) ) ; calendar . set ( Calendar . MONTH , holder . get ( ) . getMonth ( ) - ) ; calendar . set ( Calendar . DATE , holder . get ( ) . getDay ( ) ) ; calendar . set ( Calendar . HOUR_OF_DAY , holder . get ( ) . getHour ( ) ) ; calendar . set ( Calendar . MINUTE , holder . get ( ) . getMinute ( ) ) ; calendar . set ( Calendar . SECOND , holder . get ( ) . getSecond ( ) ) ; return calendar ; } } ) ; VALUE_DRIVERS = Collections . unmodifiableMap ( map ) ; } private final Class < T > modelClass ; private final Map < PropertyName , Method > accessors ; public DefaultDataModelDefinition ( Class < T > modelClass ) { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . modelClass = modelClass ; this . accessors = extractAccessors ( ) ; } private Map < PropertyName , Method > extractAccessors ( ) { Map < PropertyName , Method > results = new TreeMap < PropertyName , Method > ( ) ; for ( Method method : modelClass . getMethods ( ) ) { if ( VALUE_DRIVERS . containsKey ( method . getReturnType ( ) ) == false ) { continue ; } PropertyName property = getPropertyNameIfAccessor ( method ) ; if ( property == null ) { continue ; } results . put ( property , method ) ; } PropertyOrder annotation = modelClass . getAnnotation ( PropertyOrder . class ) ; if ( annotation == null ) { LOG . info ( "" , PropertyOrder . class . getSimpleName ( ) , modelClass . getName ( ) ) ; return results ; } Map < PropertyName , Method > ordered = new LinkedHashMap < PropertyName , Method > ( ) ; for ( String name : annotation . value ( ) ) { String [ ] words = name . split ( "" ) ; PropertyName propertyName = PropertyName . newInstance ( words ) ; Method method = results . remove ( propertyName ) ; if ( method == null ) { LOG . warn ( "" , name , modelClass . getName ( ) ) ; } else { ordered . put ( propertyName , method ) ; } } if ( results . isEmpty ( ) == false ) { LOG . warn ( "" , results . keySet ( ) , modelClass . getName ( ) ) ; ordered . putAll ( results ) ; } return ordered ; } private static final Pattern PROPERTY_ACCESSOR = Pattern . compile ( "" ) ; private PropertyName getPropertyNameIfAccessor ( Method method ) { assert method != null ; Matcher matcher = PROPERTY_ACCESSOR . matcher ( method . getName ( ) ) ; if ( matcher . matches ( ) == false ) { return null ; } String name = matcher . group ( ) ; List < String > words = new ArrayList < String > ( ) ; int start = ; for ( int i = , n = name . length ( ) ; i < n ; i ++ ) { char c = name . charAt ( i ) ; if ( '' <= c && c <= '' ) { words . add ( name . substring ( start , i ) ) ; start = i ; } } words . add ( name . substring ( start ) ) ; return PropertyName . newInstance ( words ) ; } @ Override public Class < T > getModelClass ( ) { return modelClass ; } @ Override public < A extends Annotation > A getAnnotation ( Class < A > annotationType ) { if ( annotationType == null ) { throw new IllegalArgumentException ( "" ) ; } return modelClass . getAnnotation ( annotationType ) ; } @ Override public Collection < PropertyName > getProperties ( ) { return Collections . unmodifiableCollection ( accessors . keySet ( ) ) ; } @ Override public PropertyType getType ( PropertyName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } Method accessor = accessors . get ( name ) ; if ( accessor == null ) { return null ; } ValueDriver < ? > driver = VALUE_DRIVERS . get ( accessor . getReturnType ( ) ) ; if ( driver == null ) { throw new AssertionError ( accessor . getReturnType ( ) ) ; } return driver . valueType ; } @ Override public < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( annotationType == null ) { throw new IllegalArgumentException ( "" ) ; } Method accessor = accessors . get ( name ) ; if ( accessor == null ) { return null ; } return accessor . getAnnotation ( annotationType ) ; } @ Override public Builder < T > newReflection ( ) { return new Builder < T > ( this ) ; } @ Override public DataModelReflection toReflection ( T object ) { Builder < T > builder = newReflection ( ) ; try { for ( Map . Entry < PropertyName , Method > entry : accessors . entrySet ( ) ) { PropertyName property = entry . getKey ( ) ; Method accessor = entry . getValue ( ) ; Object value = get ( object , accessor ) ; builder . add ( property , value ) ; } } catch ( Exception e ) { throw new AssertionError ( e ) ; } return builder . build ( ) ; } @ Override public T toObject ( DataModelReflection reflection ) { try { T instance = modelClass . newInstance ( ) ; for ( Map . Entry < PropertyName , Method > entry : accessors . entrySet ( ) ) { PropertyName property = entry . getKey ( ) ; Method accessor = entry . getValue ( ) ; Object value = reflection . getValue ( property ) ; set ( instance , accessor , value ) ; } return instance ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Object get ( T instance , Method property ) { assert instance != null ; assert property != null ; ValueOption < ? > holder = getHolder ( instance , property ) ; if ( holder . isNull ( ) ) { return null ; } ValueDriver < ? > driver = VALUE_DRIVERS . get ( property . getReturnType ( ) ) ; assert driver != null : property ; return driver . extractUnsafe ( holder ) ; } @ SuppressWarnings ( "" ) private void set ( T instance , Method property , Object value ) { assert instance != null ; assert property != null ; ValueOption < ? > holder = getHolder ( instance , property ) ; if ( value == null ) { holder . setNull ( ) ; } else { ValueDriver < ? > driver = VALUE_DRIVERS . get ( property . getReturnType ( ) ) ; assert driver != null : property ; driver . modifyUnsafe ( holder , value ) ; } } private ValueOption < ? > getHolder ( T instance , Method property ) { assert instance != null ; assert property != null ; try { return ( ValueOption < ? > ) property . invoke ( instance ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } abstract static class ValueDriver < T > { final PropertyType valueType ; ValueDriver ( PropertyType valueType ) { assert valueType != null ; this . valueType = valueType ; } @ SuppressWarnings ( "" ) Object extractUnsafe ( Object holder ) { return extract ( ( T ) holder ) ; } @ SuppressWarnings ( "" ) void modifyUnsafe ( Object holder , Object value ) { modify ( ( T ) holder , value ) ; } abstract Object extract ( T holder ) ; abstract void modify ( T holder , Object value ) ; protected < V > V cast ( Class < V > type , Object value ) { if ( type . isInstance ( value ) == false ) { throw new IllegalArgumentException ( ) ; } return type . cast ( value ) ; } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; import java . util . List ; import java . util . ServiceLoader ; public class SpiVerifyRuleProvider implements VerifyRuleProvider { private final List < VerifyRuleProvider > elements ; public SpiVerifyRuleProvider ( ClassLoader serviceClassLoader ) { if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = Util . loadService ( VerifyRuleProvider . class , serviceClassLoader ) ; } @ Override public < T > VerifyRule get ( DataModelDefinition < T > definition , VerifyContext context , URI source ) throws IOException { for ( VerifyRuleProvider service : elements ) { VerifyRule result = service . get ( definition , context , source ) ; if ( result != null ) { return result ; } } return null ; } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . util . Iterator ; public class IteratorDataModelSource implements DataModelSource { private final Iterator < ? extends DataModelReflection > iterator ; public IteratorDataModelSource ( Iterator < ? extends DataModelReflection > iterator ) { if ( iterator == null ) { throw new IllegalArgumentException ( "" ) ; } this . iterator = iterator ; } public < E > IteratorDataModelSource ( DataModelDefinition < E > definition , Iterator < ? extends E > iterator ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( iterator == null ) { throw new IllegalArgumentException ( "" ) ; } this . iterator = new IteratorDriver < E > ( definition , iterator ) ; } @ Override public DataModelReflection next ( ) { if ( iterator . hasNext ( ) ) { return iterator . next ( ) ; } return null ; } @ Override public void close ( ) throws IOException { return ; } private static class IteratorDriver < E > implements Iterator < DataModelReflection > { private final DataModelDefinition < ? super E > definition ; private final Iterator < ? extends E > iterator ; public IteratorDriver ( DataModelDefinition < ? super E > definition , Iterator < ? extends E > iterator ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( iterator == null ) { throw new IllegalArgumentException ( "" ) ; } this . definition = definition ; this . iterator = iterator ; } @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public DataModelReflection next ( ) { E next = iterator . next ( ) ; return definition . toReflection ( next ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; public class VerifyEngine { private final VerifyRule rule ; private final Map < Object , DataModelReflection > expectedRest ; private final Map < Object , DataModelReflection > sawActual ; public VerifyEngine ( VerifyRule rule ) { if ( rule == null ) { throw new IllegalArgumentException ( "" ) ; } this . rule = rule ; this . expectedRest = new LinkedHashMap < Object , DataModelReflection > ( ) ; this . sawActual = new HashMap < Object , DataModelReflection > ( ) ; } public VerifyEngine addExpected ( DataModelSource expected ) throws IOException { if ( expected == null ) { throw new IllegalArgumentException ( "" ) ; } try { while ( true ) { DataModelReflection next = expected . next ( ) ; if ( next == null ) { break ; } Object key = rule . getKey ( next ) ; DataModelReflection old = expectedRest . put ( key , next ) ; if ( old != null ) { throw new IOException ( MessageFormat . format ( "" , key , old , next ) ) ; } } } finally { expected . close ( ) ; } return this ; } public List < Difference > inspectInput ( DataModelSource input ) throws IOException { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } List < Difference > results = new ArrayList < Difference > ( ) ; try { while ( true ) { DataModelReflection actual = input . next ( ) ; if ( actual == null ) { break ; } Object key = rule . getKey ( actual ) ; DataModelReflection saw = sawActual . get ( key ) ; if ( saw != null ) { results . add ( new Difference ( actual , null , MessageFormat . format ( "" , key , saw , actual ) ) ) ; } else { sawActual . put ( key , actual ) ; DataModelReflection expected = expectedRest . remove ( key ) ; Difference diff = verify ( key , expected , actual ) ; if ( diff != null ) { results . add ( diff ) ; } } } } finally { input . close ( ) ; } return results ; } public List < Difference > inspectRest ( ) { List < Difference > results = new ArrayList < Difference > ( ) ; for ( Map . Entry < Object , DataModelReflection > entry : expectedRest . entrySet ( ) ) { Difference diff = verify ( entry . getKey ( ) , entry . getValue ( ) , null ) ; if ( diff != null ) { results . add ( diff ) ; } } expectedRest . clear ( ) ; sawActual . clear ( ) ; return results ; } private Difference verify ( Object key , DataModelReflection expected , DataModelReflection actual ) { assert key != null ; assert expected != null || actual != null ; Object result = rule . verify ( expected , actual ) ; if ( result == null ) { return null ; } return new Difference ( expected , actual , result ) ; } } package com . asakusafw . testdriver . core ; public interface ModelVerifier < T > { Object getKey ( T target ) ; Object verify ( T expected , T actual ) ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; public interface DataModelSourceProvider { < T > DataModelSource open ( DataModelDefinition < T > definition , URI source , TestContext context ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ExporterDescription ; public abstract class AbstractExporterRetriever < T extends ExporterDescription > extends BaseExporterRetriever < T > { public abstract void truncate ( T description ) throws IOException ; @ Override public void truncate ( T description , TestContext context ) throws IOException { truncate ( description ) ; } public abstract < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , T description ) throws IOException ; @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , T description , TestContext context ) throws IOException { return createOutput ( definition , description ) ; } public abstract < V > DataModelSource createSource ( DataModelDefinition < V > definition , T description ) throws IOException ; @ Override public < V > DataModelSource createSource ( DataModelDefinition < V > definition , T description , TestContext context ) throws IOException { return createSource ( definition , description ) ; } } package com . asakusafw . testdriver . core ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . runtime . util . TypeUtil ; import com . asakusafw . vocabulary . external . ImporterDescription ; public abstract class BaseImporterPreparator < T extends ImporterDescription > implements ImporterPreparator < T > { @ SuppressWarnings ( "" ) @ Override public Class < T > getDescriptionClass ( ) { List < Type > arguments = TypeUtil . invoke ( BaseImporterPreparator . class , getClass ( ) ) ; if ( arguments . size ( ) != ) { throw new IllegalStateException ( MessageFormat . format ( "" , getClass ( ) . getName ( ) ) ) ; } Type first = arguments . get ( ) ; if ( ( first instanceof Class < ? > ) == false || ImporterDescription . class . isAssignableFrom ( ( Class < ? > ) first ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , ImporterDescription . class . getName ( ) , getClass ( ) . getName ( ) ) ) ; } return ( Class < T > ) first ; } } package com . asakusafw . testdriver . core ; import java . io . Closeable ; import java . io . IOException ; import java . util . List ; public interface Verifier extends Closeable { List < Difference > verify ( DataModelSource results ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; public interface DifferenceSinkProvider { < T > DifferenceSink create ( DataModelDefinition < T > definition , URI sink , TestContext context ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; @ Deprecated public class TestDataPreparator { private final DataModelAdapter adapter ; private final DataModelSourceProvider sources ; private final ImporterPreparator < ImporterDescription > importers ; private final ExporterRetriever < ExporterDescription > exporters ; private final TestContext context ; public TestDataPreparator ( ClassLoader serviceClassLoader ) { this ( new TestContext . Empty ( ) , serviceClassLoader ) ; } public TestDataPreparator ( DataModelAdapter adapter , DataModelSourceProvider sources , ImporterPreparator < ImporterDescription > importers , ExporterRetriever < ExporterDescription > exporters ) { this ( new TestContext . Empty ( ) , adapter , sources , importers , exporters ) ; } public TestDataPreparator ( TestContext context , ClassLoader serviceClassLoader ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . adapter = new SpiDataModelAdapter ( serviceClassLoader ) ; this . sources = new SpiDataModelSourceProvider ( serviceClassLoader ) ; this . importers = new SpiImporterPreparator ( serviceClassLoader ) ; this . exporters = new SpiExporterRetriever ( serviceClassLoader ) ; } public TestDataPreparator ( TestContext context , DataModelAdapter adapter , DataModelSourceProvider sources , ImporterPreparator < ImporterDescription > importers , ExporterRetriever < ExporterDescription > exporters ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( adapter == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sources == null ) { throw new IllegalArgumentException ( "" ) ; } if ( importers == null ) { throw new IllegalArgumentException ( "" ) ; } if ( exporters == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . adapter = adapter ; this . sources = sources ; this . importers = importers ; this . exporters = exporters ; } public < T > ModelOutput < T > prepare ( Class < T > type , ImporterDescription description ) throws IOException { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type != description . getModelType ( ) ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < T > definition = findDefinition ( type ) ; return importers . createOutput ( definition , description , context ) ; } public < T > ModelOutput < T > prepare ( Class < T > type , ExporterDescription description ) throws IOException { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type != description . getModelType ( ) ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < T > definition = findDefinition ( type ) ; return exporters . createOutput ( definition , description , context ) ; } public void prepare ( Class < ? > type , ImporterDescription description , URI source ) throws IOException { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = findDefinition ( type ) ; prepare ( definition , description , source ) ; } public void prepare ( Class < ? > type , ExporterDescription description , URI source ) throws IOException { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = findDefinition ( type ) ; prepare ( definition , description , source ) ; } public void truncate ( ImporterDescription description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } importers . truncate ( description , context ) ; } public void truncate ( ExporterDescription description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } exporters . truncate ( description , context ) ; } private < T > DataModelDefinition < T > findDefinition ( Class < T > type ) throws IOException { assert type != null ; DataModelDefinition < T > definition = adapter . get ( type ) ; if ( definition == null ) { throw new IOException ( MessageFormat . format ( "" , type . getName ( ) ) ) ; } return definition ; } private < T > void prepare ( DataModelDefinition < T > definition , ImporterDescription desctipion , URI source ) throws IOException { assert definition != null ; assert desctipion != null ; assert source != null ; ModelOutput < T > output = importers . createOutput ( definition , desctipion , context ) ; prepare ( definition , output , source ) ; } private < T > void prepare ( DataModelDefinition < T > definition , ExporterDescription desctipion , URI source ) throws IOException { assert definition != null ; assert desctipion != null ; assert source != null ; ModelOutput < T > output = exporters . createOutput ( definition , desctipion , context ) ; prepare ( definition , output , source ) ; } private < T > void prepare ( DataModelDefinition < T > definition , ModelOutput < T > output , URI source ) throws IOException { try { DataModelSource input = sources . open ( definition , source , context ) ; if ( input == null ) { throw new IOException ( MessageFormat . format ( "" , source ) ) ; } try { while ( true ) { DataModelReflection next = input . next ( ) ; if ( next == null ) { break ; } T object = definition . toObject ( next ) ; output . write ( object ) ; } } finally { input . close ( ) ; } } finally { output . close ( ) ; } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ExporterDescription ; public interface ExporterRetriever < T extends ExporterDescription > { Class < T > getDescriptionClass ( ) ; void truncate ( T description , TestContext context ) throws IOException ; < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , T description , TestContext context ) throws IOException ; < V > DataModelSource createSource ( DataModelDefinition < V > definition , T description , TestContext context ) throws IOException ; } package com . asakusafw . testdriver . core ; public interface ModelTester < T > { Object verify ( T expected , T actual ) ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class TestModerator { private final TestToolRepository repository ; private final TestContext context ; public TestModerator ( TestToolRepository repository , TestContext context ) { if ( repository == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } this . repository = repository ; this . context = context ; } public void truncate ( ImporterDescription description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } getDriver ( description ) . truncate ( description , context ) ; } public void truncate ( ExporterDescription description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } getDriver ( description ) . truncate ( description , context ) ; } public void prepare ( Class < ? > modelClass , ImporterDescription description , DataModelSourceFactory source ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = repository . toDataModelDefinition ( modelClass ) ; prepare ( definition , description , source ) ; } public void prepare ( Class < ? > modelClass , ExporterDescription description , DataModelSourceFactory source ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = repository . toDataModelDefinition ( modelClass ) ; prepare ( definition , description , source ) ; } public List < Difference > inspect ( Class < ? > modelClass , ExporterDescription description , VerifyContext verifyContext , VerifierFactory verifier ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( verifyContext == null ) { throw new IllegalArgumentException ( "" ) ; } if ( verifier == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = repository . toDataModelDefinition ( modelClass ) ; return inspect ( definition , description , verifyContext , verifier ) ; } public void save ( Class < ? > modelClass , ExporterDescription description , DataModelSinkFactory resultDataSink ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( resultDataSink == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = repository . toDataModelDefinition ( modelClass ) ; DataModelSource source = getDriver ( description ) . createSource ( definition , description , context ) ; try { DataModelSink sink = resultDataSink . createSink ( definition , context ) ; try { while ( true ) { DataModelReflection next = source . next ( ) ; if ( next == null ) { break ; } sink . put ( next ) ; } } finally { sink . close ( ) ; } } finally { source . close ( ) ; } } public void save ( Class < ? > modelClass , Iterable < Difference > differences , DifferenceSinkFactory differenceSink ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( differences == null ) { throw new IllegalArgumentException ( "" ) ; } if ( differenceSink == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = repository . toDataModelDefinition ( modelClass ) ; DifferenceSink sink = differenceSink . createSink ( definition , context ) ; try { for ( Difference difference : differences ) { sink . put ( difference ) ; } } finally { sink . close ( ) ; } } private ImporterPreparator < ? super ImporterDescription > getDriver ( ImporterDescription description ) { assert description != null ; return repository . getImporterPreparator ( description ) ; } private ExporterRetriever < ? super ExporterDescription > getDriver ( ExporterDescription description ) { assert description != null ; return repository . getExporterRetriever ( description ) ; } private < T > void prepare ( DataModelDefinition < T > definition , ImporterDescription description , DataModelSourceFactory source ) throws IOException { assert definition != null ; assert description != null ; assert source != null ; ModelOutput < T > output = getDriver ( description ) . createOutput ( definition , description , context ) ; prepare ( definition , output , source ) ; } private < T > void prepare ( DataModelDefinition < T > definition , ExporterDescription desctipion , DataModelSourceFactory source ) throws IOException { assert definition != null ; assert desctipion != null ; assert source != null ; ModelOutput < T > output = getDriver ( desctipion ) . createOutput ( definition , desctipion , context ) ; prepare ( definition , output , source ) ; } private < T > void prepare ( DataModelDefinition < T > definition , ModelOutput < T > output , DataModelSourceFactory source ) throws IOException { assert definition != null ; assert output != null ; assert source != null ; try { DataModelSource input = source . createSource ( definition , context ) ; if ( input == null ) { throw new IOException ( MessageFormat . format ( "" , source ) ) ; } try { while ( true ) { DataModelReflection next = input . next ( ) ; if ( next == null ) { break ; } T object = definition . toObject ( next ) ; output . write ( object ) ; } } finally { input . close ( ) ; } } finally { output . close ( ) ; } } private < T > List < Difference > inspect ( DataModelDefinition < T > definition , ExporterDescription description , VerifyContext verifyContext , VerifierFactory verifier ) throws IOException { assert definition != null ; assert description != null ; assert verifier != null ; List < Difference > results ; DataModelSource target = getDriver ( description ) . createSource ( definition , description , context ) ; try { Verifier engine = verifier . createVerifier ( definition , verifyContext ) ; try { results = engine . verify ( target ) ; } finally { engine . close ( ) ; } } finally { target . close ( ) ; } Collections . sort ( results , new DifferenceComparator ( definition ) ) ; return results ; } private static class DifferenceComparator implements Comparator < Difference > { private final DataModelDefinition < ? > definition ; DifferenceComparator ( DataModelDefinition < ? > definition ) { assert definition != null ; this . definition = definition ; } @ Override public int compare ( Difference o1 , Difference o2 ) { DataModelReflection r1 = key ( o1 ) ; DataModelReflection r2 = key ( o2 ) ; if ( r1 == null && r2 == null ) { return ; } else if ( r1 == null ) { return - ; } else if ( r2 == null ) { return + ; } for ( PropertyName name : definition . getProperties ( ) ) { Class < ? > type = definition . getType ( name ) . getRepresentation ( ) ; if ( Comparable . class . isAssignableFrom ( type ) == false ) { continue ; } Object p1 = r1 . getValue ( name ) ; Object p2 = r2 . getValue ( name ) ; if ( p1 == null && p2 != null ) { return - ; } else if ( p1 != null && p2 == null ) { return + ; } int cmp = compareProperty ( type . asSubclass ( Comparable . class ) , p1 , p2 ) ; if ( cmp != ) { return cmp ; } } return ; } @ SuppressWarnings ( { "" , "" } ) private < T extends Comparable > int compareProperty ( Class < T > type , Object p1 , Object p2 ) { if ( p1 == null && p2 == null ) { return ; } else if ( p1 == null ) { return - ; } else if ( p2 == null ) { return + ; } T o1 = type . cast ( p1 ) ; T o2 = type . cast ( p2 ) ; return o1 . compareTo ( o2 ) ; } private DataModelReflection key ( Difference difference ) { assert difference != null ; DataModelReflection expected = difference . getExpected ( ) ; DataModelReflection actual = difference . getActual ( ) ; if ( expected != null ) { return expected ; } else if ( actual != null ) { return actual ; } else { return null ; } } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; public abstract class DataModelSourceFactory { public abstract < T > DataModelSource createSource ( DataModelDefinition < T > definition , TestContext context ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; import java . util . List ; import java . util . ServiceLoader ; public class SpiDataModelSinkProvider implements DataModelSinkProvider { private final List < DataModelSinkProvider > elements ; public SpiDataModelSinkProvider ( ClassLoader serviceClassLoader ) { if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = Util . loadService ( DataModelSinkProvider . class , serviceClassLoader ) ; } @ Override public < T > DataModelSink create ( DataModelDefinition < T > definition , URI sink , TestContext context ) throws IOException { for ( DataModelSinkProvider service : elements ) { DataModelSink result = service . create ( definition , sink , context ) ; if ( result != null ) { return result ; } } return null ; } } package com . asakusafw . testdriver . core ; import java . util . List ; import java . util . ServiceLoader ; public class SpiDataModelAdapter implements DataModelAdapter { private final List < DataModelAdapter > elements ; public SpiDataModelAdapter ( ClassLoader serviceClassLoader ) { if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = Util . loadService ( DataModelAdapter . class , serviceClassLoader ) ; } @ Override public < T > DataModelDefinition < T > get ( Class < T > modelClass ) { for ( DataModelAdapter service : elements ) { DataModelDefinition < T > result = service . get ( modelClass ) ; if ( result != null ) { return result ; } } return null ; } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . ServiceLoader ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class SpiExporterRetriever implements ExporterRetriever < ExporterDescription > { @ SuppressWarnings ( "" ) private final List < ExporterRetriever > elements ; public SpiExporterRetriever ( ClassLoader serviceClassLoader ) { if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = Util . loadService ( ExporterRetriever . class , serviceClassLoader ) ; } @ SuppressWarnings ( "" ) public SpiExporterRetriever ( List < ? extends ExporterRetriever < ? > > elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = new ArrayList < ExporterRetriever > ( elements ) ; } @ Override public Class < ExporterDescription > getDescriptionClass ( ) { return ExporterDescription . class ; } @ Override public void truncate ( ExporterDescription description , TestContext context ) throws IOException { for ( ExporterRetriever < ? > element : elements ) { if ( element . getDescriptionClass ( ) . isAssignableFrom ( description . getClass ( ) ) ) { truncate0 ( element , description , context ) ; return ; } } throw new IOException ( MessageFormat . format ( "" , description ) ) ; } private < T extends ExporterDescription > void truncate0 ( ExporterRetriever < T > preparator , ExporterDescription description , TestContext context ) throws IOException { assert preparator != null ; assert description != null ; T desc = preparator . getDescriptionClass ( ) . cast ( description ) ; preparator . truncate ( desc , context ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , ExporterDescription description , TestContext context ) throws IOException { for ( ExporterRetriever < ? > element : elements ) { if ( element . getDescriptionClass ( ) . isAssignableFrom ( description . getClass ( ) ) ) { return createOutput0 ( definition , element , description , context ) ; } } throw new IOException ( MessageFormat . format ( "" , description ) ) ; } private < T extends ExporterDescription , V > ModelOutput < V > createOutput0 ( DataModelDefinition < V > definition , ExporterRetriever < T > retriever , ExporterDescription description , TestContext context ) throws IOException { assert definition != null ; assert retriever != null ; assert description != null ; T desc = retriever . getDescriptionClass ( ) . cast ( description ) ; return retriever . createOutput ( definition , desc , context ) ; } @ Override public < V > DataModelSource createSource ( DataModelDefinition < V > definition , ExporterDescription description , TestContext context ) throws IOException { for ( ExporterRetriever < ? > element : elements ) { if ( element . getDescriptionClass ( ) . isAssignableFrom ( description . getClass ( ) ) ) { return createSource0 ( definition , element , description , context ) ; } } throw new IOException ( MessageFormat . format ( "" , description ) ) ; } private < T extends ExporterDescription , V > DataModelSource createSource0 ( DataModelDefinition < ? > definition , ExporterRetriever < T > retriever , ExporterDescription description , TestContext context ) throws IOException { assert retriever != null ; assert description != null ; T desc = retriever . getDescriptionClass ( ) . cast ( description ) ; return retriever . createSource ( definition , desc , context ) ; } } package com . asakusafw . testdriver . core ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; public final class PropertyName implements Comparable < PropertyName > , Serializable { private static final long serialVersionUID = - ; private final List < String > originalWords ; private final List < String > normalized ; private PropertyName ( List < String > words ) { this . originalWords = words ; this . normalized = normalize ( words ) ; } private static List < String > normalize ( List < String > words ) { assert words != null ; List < String > results = new ArrayList < String > ( words . size ( ) ) ; Iterator < String > iter = words . iterator ( ) ; assert iter . hasNext ( ) ; String last = iter . next ( ) ; while ( iter . hasNext ( ) ) { String next = iter . next ( ) ; assert next . isEmpty ( ) == false ; char c = next . charAt ( ) ; if ( '' <= c && c <= '' ) { last += next ; } else { results . add ( last ) ; last = next ; } } results . add ( last ) ; return Collections . unmodifiableList ( results ) ; } public static PropertyName newInstance ( List < String > words ) { if ( words == null ) { throw new IllegalArgumentException ( "" ) ; } if ( words . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } List < String > work = new ArrayList < String > ( words . size ( ) ) ; for ( String w : words ) { work . add ( normalize ( w ) ) ; } return new PropertyName ( work ) ; } public static PropertyName newInstance ( String ... words ) { if ( words == null ) { throw new IllegalArgumentException ( "" ) ; } return newInstance ( Arrays . asList ( words ) ) ; } private static String normalize ( String word ) { if ( word == null ) { throw new IllegalArgumentException ( "" ) ; } return word . toLowerCase ( ) ; } public List < String > getWords ( ) { return originalWords ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + normalized . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } PropertyName other = ( PropertyName ) obj ; if ( ! normalized . equals ( other . normalized ) ) { return false ; } return true ; } @ Override public int compareTo ( PropertyName o ) { Iterator < String > left = normalized . iterator ( ) ; Iterator < String > right = o . normalized . iterator ( ) ; while ( true ) { if ( left . hasNext ( ) == false ) { if ( right . hasNext ( ) == false ) { break ; } return - ; } if ( right . hasNext ( ) == false ) { return + ; } int diff = left . next ( ) . compareTo ( right . next ( ) ) ; if ( diff != ) { return diff ; } } return ; } @ Override public String toString ( ) { StringBuilder buf = new StringBuilder ( ) ; Iterator < String > iter = originalWords . iterator ( ) ; assert iter . hasNext ( ) ; buf . append ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( '' ) ; buf . append ( iter . next ( ) ) ; } return buf . toString ( ) ; } } package com . asakusafw . testdriver . core ; package com . asakusafw . testdriver . core ; public class TesterDriver < T > implements TestRule { private final ModelTester < ? super T > verifier ; private final DataModelDefinition < ? extends T > definition ; public TesterDriver ( ModelTester < ? super T > verifier , DataModelDefinition < ? extends T > definition ) { if ( verifier == null ) { throw new IllegalArgumentException ( "" ) ; } if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } this . verifier = verifier ; this . definition = definition ; } @ Override public Object verify ( DataModelReflection expected , DataModelReflection actual ) { return verifier . verify ( convert ( expected ) , convert ( actual ) ) ; } private T convert ( DataModelReflection reflection ) { if ( reflection == null ) { return null ; } return definition . toObject ( reflection ) ; } } package com . asakusafw . testdriver . core ; import java . io . IOException ; public abstract class VerifierFactory { public abstract < T > Verifier createVerifier ( DataModelDefinition < T > definition , VerifyContext context ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; import java . util . ArrayList ; import java . util . List ; import java . util . ServiceLoader ; public class SpiDataModelSourceProvider implements DataModelSourceProvider { private final List < DataModelSourceProvider > elements ; @ SuppressWarnings ( "" ) public SpiDataModelSourceProvider ( ClassLoader serviceClassLoader ) { if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = new ArrayList < DataModelSourceProvider > ( ) ; this . elements . addAll ( Util . loadService ( SourceProvider . class , serviceClassLoader ) ) ; this . elements . addAll ( Util . loadService ( DataModelSourceProvider . class , serviceClassLoader ) ) ; } @ Override public < T > DataModelSource open ( DataModelDefinition < T > definition , URI source , TestContext context ) throws IOException { for ( DataModelSourceProvider service : elements ) { DataModelSource result = service . open ( definition , source , context ) ; if ( result != null ) { return result ; } } return null ; } } package com . asakusafw . testdriver . core ; import java . math . BigDecimal ; import java . text . MessageFormat ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . LinkedHashMap ; import java . util . Map ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class Difference { private static final char [ ] ASCII_SPECIAL_ESCAPE = new char [ ] ; static { ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; } private final DataModelReflection expected ; private final DataModelReflection actual ; private final Object diagnostic ; public Difference ( DataModelReflection expected , DataModelReflection actual , Object diagnostic ) { this . expected = expected ; this . actual = actual ; this . diagnostic = diagnostic ; } public DataModelReflection getExpected ( ) { return expected ; } public DataModelReflection getActual ( ) { return actual ; } public Object getDiagnostic ( ) { return diagnostic ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , formatMap ( getExpected ( ) ) , formatMap ( getActual ( ) ) , getDiagnostic ( ) ) ; } public static String format ( Object value ) { if ( value instanceof String ) { return toStringLiteral ( ( String ) value ) ; } else if ( value instanceof Calendar ) { Calendar c = ( Calendar ) value ; if ( c . isSet ( Calendar . HOUR_OF_DAY ) ) { return new SimpleDateFormat ( DateTime . FORMAT ) . format ( c . getTime ( ) ) ; } else { return new SimpleDateFormat ( Date . FORMAT ) . format ( c . getTime ( ) ) ; } } else if ( value instanceof BigDecimal ) { return ( ( BigDecimal ) value ) . toPlainString ( ) ; } return String . valueOf ( value ) ; } private static String toStringLiteral ( String value ) { assert value != null ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( '' ) ; for ( char c : value . toCharArray ( ) ) { if ( c <= && ASCII_SPECIAL_ESCAPE [ c ] != ) { buf . append ( '' ) ; buf . append ( ASCII_SPECIAL_ESCAPE [ c ] ) ; } else if ( Character . isISOControl ( c ) || ! Character . isDefined ( c ) ) { buf . append ( String . format ( "" , ( int ) c ) ) ; } else { buf . append ( c ) ; } } buf . append ( '' ) ; return buf . toString ( ) ; } private static Map < Object , String > formatMap ( DataModelReflection reflection ) { if ( reflection == null ) { return null ; } else { Map < ? , ? > map = reflection . properties ; Map < Object , String > results = new LinkedHashMap < Object , String > ( ) ; for ( Map . Entry < ? , ? > entry : map . entrySet ( ) ) { results . put ( entry . getKey ( ) , format ( entry . getValue ( ) ) ) ; } return results ; } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . rule . VerifyRuleBuilder ; import com . asakusafw . vocabulary . external . ExporterDescription ; @ Deprecated public class TestResultInspector { static final Logger LOG = LoggerFactory . getLogger ( TestResultInspector . class ) ; private final DataModelAdapter adapter ; private final DataModelSourceProvider sources ; private final VerifyRuleProvider rules ; private final ExporterRetriever < ExporterDescription > targets ; private final TestContext context ; public TestResultInspector ( ClassLoader serviceClassLoader ) { this ( new TestContext . Empty ( ) , serviceClassLoader ) ; } public TestResultInspector ( DataModelAdapter adapter , DataModelSourceProvider sources , VerifyRuleProvider rules , ExporterRetriever < ExporterDescription > retrievers ) { this ( new TestContext . Empty ( ) , adapter , sources , rules , retrievers ) ; } public TestResultInspector ( TestContext context , ClassLoader serviceClassLoader ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . adapter = new SpiDataModelAdapter ( serviceClassLoader ) ; this . sources = new SpiDataModelSourceProvider ( serviceClassLoader ) ; this . rules = new SpiVerifyRuleProvider ( serviceClassLoader ) ; this . targets = new SpiExporterRetriever ( serviceClassLoader ) ; } public TestResultInspector ( TestContext context , DataModelAdapter adapter , DataModelSourceProvider sources , VerifyRuleProvider rules , ExporterRetriever < ExporterDescription > retrievers ) { if ( adapter == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sources == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rules == null ) { throw new IllegalArgumentException ( "" ) ; } if ( retrievers == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . adapter = adapter ; this . sources = sources ; this . rules = rules ; this . targets = retrievers ; } public List < Difference > inspect ( Class < ? > modelClass , ExporterDescription description , VerifyContext verifyContext , URI expected , URI rule ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( verifyContext == null ) { throw new IllegalArgumentException ( "" ) ; } if ( expected == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rule == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = findDefinition ( modelClass ) ; VerifyRule ruleDesc = findRule ( definition , verifyContext , rule ) ; return inspect ( modelClass , description , expected , ruleDesc ) ; } public VerifyRuleBuilder rule ( Class < ? > modelClass ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = findDefinition ( modelClass ) ; return new VerifyRuleBuilder ( definition ) ; } public < T > VerifyRule rule ( Class < ? extends T > modelClass , ModelVerifier < T > verifier ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( verifier == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? extends T > definition = findDefinition ( modelClass ) ; return new ModelVerifierDriver < T > ( verifier , definition ) ; } public List < Difference > inspect ( Class < ? > modelClass , ExporterDescription description , URI expected , VerifyRule rule ) throws IOException { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( expected == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rule == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < ? > definition = findDefinition ( modelClass ) ; DataModelSource expectedDesc = findSource ( definition , expected ) ; VerifyEngine engine = buildVerifier ( definition , rule , expectedDesc ) ; List < Difference > results = inspect ( definition , description , engine ) ; return results ; } private < T > DataModelDefinition < T > findDefinition ( Class < T > modelClass ) throws IOException { assert modelClass != null ; DataModelDefinition < T > definition = adapter . get ( modelClass ) ; if ( definition == null ) { throw new IOException ( MessageFormat . format ( "" , modelClass . getName ( ) ) ) ; } return definition ; } private < T > List < Difference > inspect ( DataModelDefinition < T > definition , ExporterDescription description , VerifyEngine engine ) throws IOException { assert definition != null ; assert description != null ; assert engine != null ; List < Difference > results = new ArrayList < Difference > ( ) ; DataModelSource target = targets . createSource ( definition , description , context ) ; try { results . addAll ( engine . inspectInput ( target ) ) ; } finally { target . close ( ) ; } results . addAll ( engine . inspectRest ( ) ) ; return results ; } private VerifyEngine buildVerifier ( DataModelDefinition < ? > definition , VerifyRule rule , DataModelSource expected ) throws IOException { assert definition != null ; assert rule != null ; VerifyEngine engine = new VerifyEngine ( rule ) ; engine . addExpected ( expected ) ; return engine ; } private DataModelSource findSource ( DataModelDefinition < ? > definition , URI uri ) throws IOException { assert definition != null ; assert uri != null ; DataModelSource expected = sources . open ( definition , uri , context ) ; if ( expected == null ) { throw new IOException ( MessageFormat . format ( "" , uri ) ) ; } return expected ; } private VerifyRule findRule ( DataModelDefinition < ? > definition , VerifyContext verifyContext , URI ruleUri ) throws IOException { assert definition != null ; assert verifyContext != null ; assert ruleUri != null ; VerifyRule rule = rules . get ( definition , verifyContext , ruleUri ) ; if ( rule == null ) { throw new IOException ( MessageFormat . format ( "" , ruleUri ) ) ; } return rule ; } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . ServiceLoader ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class SpiImporterPreparator implements ImporterPreparator < ImporterDescription > { @ SuppressWarnings ( "" ) private final List < ImporterPreparator > elements ; public SpiImporterPreparator ( ClassLoader serviceClassLoader ) { if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = Util . loadService ( ImporterPreparator . class , serviceClassLoader ) ; } @ SuppressWarnings ( "" ) public SpiImporterPreparator ( List < ? extends ImporterPreparator < ? > > elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = new ArrayList < ImporterPreparator > ( elements ) ; } @ Override public Class < ImporterDescription > getDescriptionClass ( ) { return ImporterDescription . class ; } @ Override public void truncate ( ImporterDescription description , TestContext context ) throws IOException { for ( ImporterPreparator < ? > element : elements ) { if ( element . getDescriptionClass ( ) . isAssignableFrom ( description . getClass ( ) ) ) { truncate0 ( element , description , context ) ; return ; } } throw new IOException ( MessageFormat . format ( "" , description ) ) ; } private < T extends ImporterDescription > void truncate0 ( ImporterPreparator < T > preparator , ImporterDescription description , TestContext context ) throws IOException { assert preparator != null ; assert description != null ; T desc = preparator . getDescriptionClass ( ) . cast ( description ) ; preparator . truncate ( desc , context ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , ImporterDescription description , TestContext context ) throws IOException { for ( ImporterPreparator < ? > element : elements ) { if ( element . getDescriptionClass ( ) . isAssignableFrom ( description . getClass ( ) ) ) { return createOutput0 ( definition , element , description , context ) ; } } throw new IOException ( MessageFormat . format ( "" , description ) ) ; } private < T extends ImporterDescription , V > ModelOutput < V > createOutput0 ( DataModelDefinition < V > definition , ImporterPreparator < T > preparator , ImporterDescription description , TestContext context ) throws IOException { assert definition != null ; assert preparator != null ; assert description != null ; T desc = preparator . getDescriptionClass ( ) . cast ( description ) ; return preparator . createOutput ( definition , desc , context ) ; } } package com . asakusafw . testdriver . core ; public interface DataModelAdapter { < T > DataModelDefinition < T > get ( Class < T > modelClass ) ; } package com . asakusafw . testdriver . core ; public class Sequence { } package com . asakusafw . testdriver . core ; import java . io . Closeable ; import java . io . IOException ; public interface DataModelSink extends Closeable { void put ( DataModelReflection model ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . ServiceLoader ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; final class Util { static final Logger LOG = LoggerFactory . getLogger ( Util . class ) ; static < T > List < T > loadService ( Class < T > spi , ClassLoader loader ) { assert spi != null ; assert loader != null ; LOG . debug ( "" , spi . getSimpleName ( ) ) ; ServiceLoader < T > services = ServiceLoader . load ( spi , loader ) ; List < T > results = new ArrayList < T > ( ) ; for ( T service : services ) { LOG . debug ( "" , service . getClass ( ) . getName ( ) ) ; results . add ( service ) ; } Collections . sort ( results , new Comparator < Object > ( ) { @ Override public int compare ( Object o1 , Object o2 ) { return o1 . getClass ( ) . getName ( ) . compareTo ( o2 . getClass ( ) . getName ( ) ) ; } } ) ; return results ; } private Util ( ) { return ; } } package com . asakusafw . testdriver . core ; import java . io . IOException ; public abstract class DifferenceSinkFactory { public abstract < T > DifferenceSink createSink ( DataModelDefinition < T > definition , TestContext context ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . util . Calendar ; public enum PropertyType { BOOLEAN ( Boolean . class ) , BYTE ( Byte . class ) , SHORT ( Short . class ) , INT ( Integer . class ) , LONG ( Long . class ) , INTEGER ( BigInteger . class ) , FLOAT ( Float . class ) , DOUBLE ( Double . class ) , DECIMAL ( BigDecimal . class ) , STRING ( String . class ) , DATE ( Calendar . class ) , TIME ( Calendar . class ) , DATETIME ( Calendar . class ) , SEQUENCE ( Sequence . class ) , OBJECT ( DataModelReflection . class ) , ; private final Class < ? > representation ; private PropertyType ( Class < ? > representation ) { assert representation != null ; this . representation = representation ; } public Class < ? > getRepresentation ( ) { return representation ; } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ImporterDescription ; public interface ImporterPreparator < T extends ImporterDescription > { Class < T > getDescriptionClass ( ) ; void truncate ( T description , TestContext context ) throws IOException ; < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , T description , TestContext context ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class TestToolRepository { final DataModelAdapter dataModelAdapter ; final ImporterPreparator < ImporterDescription > importerPreparator ; final ExporterRetriever < ExporterDescription > exporterRetriever ; final DataModelSourceProvider dataModelSourceProvider ; final DataModelSinkProvider dataModelSinkProvider ; final DifferenceSinkProvider differenceSinkProvider ; final VerifyRuleProvider verifyRuleProvider ; public TestToolRepository ( ClassLoader classLoader ) { if ( classLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . dataModelAdapter = new SpiDataModelAdapter ( classLoader ) ; this . importerPreparator = new SpiImporterPreparator ( classLoader ) ; this . exporterRetriever = new SpiExporterRetriever ( classLoader ) ; this . dataModelSourceProvider = new SpiDataModelSourceProvider ( classLoader ) ; this . dataModelSinkProvider = new SpiDataModelSinkProvider ( classLoader ) ; this . differenceSinkProvider = new SpiDifferenceSinkProvider ( classLoader ) ; this . verifyRuleProvider = new SpiVerifyRuleProvider ( classLoader ) ; } public < T > DataModelDefinition < T > toDataModelDefinition ( Class < T > dataModelClass ) throws IOException { if ( dataModelClass == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < T > def = dataModelAdapter . get ( dataModelClass ) ; if ( def == null ) { throw new IOException ( MessageFormat . format ( "" , dataModelClass . getName ( ) ) ) ; } return def ; } public < T > VerifyRule toVerifyRule ( Class < T > dataModelClass , ModelVerifier < ? super T > verifier ) throws IOException { if ( dataModelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( verifier == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < T > def = toDataModelDefinition ( dataModelClass ) ; return new ModelVerifierDriver < T > ( verifier , def ) ; } public < T > TestRule toVerifyRuleFragment ( Class < T > dataModelClass , ModelTester < ? super T > tester ) throws IOException { if ( dataModelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tester == null ) { throw new IllegalArgumentException ( "" ) ; } DataModelDefinition < T > def = toDataModelDefinition ( dataModelClass ) ; return new TesterDriver < T > ( tester , def ) ; } public < T extends ImporterDescription > ImporterPreparator < ? super T > getImporterPreparator ( T description ) { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } return importerPreparator ; } public < T extends ExporterDescription > ExporterRetriever < ? super T > getExporterRetriever ( T description ) { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } return exporterRetriever ; } public DataModelSourceFactory getDataModelSourceFactory ( final URI uri ) { if ( uri == null ) { throw new IllegalArgumentException ( "" ) ; } return new DataModelSourceFactory ( ) { @ Override public < T > DataModelSource createSource ( DataModelDefinition < T > definition , TestContext context ) throws IOException { DataModelSource source = dataModelSourceProvider . open ( definition , uri , context ) ; if ( source == null ) { throw new IOException ( MessageFormat . format ( "" , uri ) ) ; } return source ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , uri ) ; } } ; } public DataModelSinkFactory getDataModelSinkFactory ( final URI uri ) { if ( uri == null ) { throw new IllegalArgumentException ( "" ) ; } return new DataModelSinkFactory ( ) { @ Override public < T > DataModelSink createSink ( DataModelDefinition < T > definition , TestContext context ) throws IOException { DataModelSink sink = dataModelSinkProvider . create ( definition , uri , context ) ; if ( sink == null ) { throw new IOException ( MessageFormat . format ( "" , uri ) ) ; } return sink ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , uri ) ; } } ; } public DifferenceSinkFactory getDifferenceSinkFactory ( final URI uri ) { if ( uri == null ) { throw new IllegalArgumentException ( "" ) ; } return new DifferenceSinkFactory ( ) { @ Override public < T > DifferenceSink createSink ( DataModelDefinition < T > definition , TestContext context ) throws IOException { DifferenceSink sink = differenceSinkProvider . create ( definition , uri , context ) ; if ( sink == null ) { throw new IOException ( MessageFormat . format ( "" , uri ) ) ; } return sink ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , uri ) ; } } ; } public VerifierFactory getVerifierFactory ( final URI expectedUri , final URI ruleUri , final List < TestRule > extraRules ) { if ( expectedUri == null ) { throw new IllegalArgumentException ( "" ) ; } if ( ruleUri == null ) { throw new IllegalArgumentException ( "" ) ; } if ( extraRules == null ) { throw new IllegalArgumentException ( "" ) ; } final DataModelSourceFactory expectedFactory = getDataModelSourceFactory ( expectedUri ) ; return new VerifierFactory ( ) { @ Override public < T > Verifier createVerifier ( DataModelDefinition < T > definition , VerifyContext context ) throws IOException { VerifyRule verifyRule = verifyRuleProvider . get ( definition , context , ruleUri ) ; if ( verifyRule == null ) { throw new IOException ( MessageFormat . format ( "" , ruleUri ) ) ; } if ( extraRules . isEmpty ( ) == false ) { verifyRule = new CompositeVerifyRule ( verifyRule , extraRules ) ; } DataModelSource expected = expectedFactory . createSource ( definition , context . getTestContext ( ) ) ; boolean succeed = false ; try { Verifier verifier = new VerifyRuleVerifier ( expected , verifyRule ) ; succeed = true ; return verifier ; } finally { if ( succeed == false ) { expected . close ( ) ; } } } @ Override public String toString ( ) { return MessageFormat . format ( "" , expectedUri , ruleUri ) ; } } ; } public VerifierFactory getVerifierFactory ( final URI expectedUri , final VerifyRule verifyRule ) { if ( expectedUri == null ) { throw new IllegalArgumentException ( "" ) ; } if ( verifyRule == null ) { throw new IllegalArgumentException ( "" ) ; } final DataModelSourceFactory expectedFactory = getDataModelSourceFactory ( expectedUri ) ; return new VerifierFactory ( ) { @ Override public < T > Verifier createVerifier ( DataModelDefinition < T > definition , VerifyContext context ) throws IOException { DataModelSource expected = expectedFactory . createSource ( definition , context . getTestContext ( ) ) ; boolean succeed = false ; try { Verifier verifier = new VerifyRuleVerifier ( expected , verifyRule ) ; succeed = true ; return verifier ; } finally { if ( succeed == false ) { expected . close ( ) ; } } } @ Override public String toString ( ) { return MessageFormat . format ( "" , expectedUri , verifyRule ) ; } } ; } } package com . asakusafw . testdriver . core ; public interface VerifyRule extends TestRule { Object getKey ( DataModelReflection target ) ; @ Override Object verify ( DataModelReflection expected , DataModelReflection actual ) ; } package com . asakusafw . testdriver . core ; import java . io . Serializable ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . Map ; public class DataModelReflection implements Serializable { private static final long serialVersionUID = - ; protected final Map < PropertyName , ? > properties ; public DataModelReflection ( Map < PropertyName , ? > properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } this . properties = normalize ( properties ) ; } private static Map < PropertyName , ? > normalize ( Map < PropertyName , ? > properties ) { assert properties != null ; Map < PropertyName , Object > results = new LinkedHashMap < PropertyName , Object > ( ) ; for ( Map . Entry < PropertyName , ? > entry : properties . entrySet ( ) ) { if ( entry . getKey ( ) != null ) { results . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return Collections . unmodifiableMap ( results ) ; } public Object getValue ( PropertyName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } Object value = properties . get ( name ) ; return value ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + properties . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DataModelReflection other = ( DataModelReflection ) obj ; if ( ! properties . equals ( other . properties ) ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , properties ) ; } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; public class VerifyRuleVerifier implements Verifier { private final DataModelSource expected ; private final VerifyRule rule ; public VerifyRuleVerifier ( DataModelSource expected , VerifyRule rule ) { if ( expected == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rule == null ) { throw new IllegalArgumentException ( "" ) ; } this . expected = expected ; this . rule = rule ; } @ Override public List < Difference > verify ( DataModelSource results ) throws IOException { VerifyEngine engine = new VerifyEngine ( rule ) ; try { engine . addExpected ( expected ) ; } finally { expected . close ( ) ; } List < Difference > differences = new ArrayList < Difference > ( ) ; differences . addAll ( engine . inspectInput ( results ) ) ; differences . addAll ( engine . inspectRest ( ) ) ; return differences ; } @ Override public void close ( ) throws IOException { expected . close ( ) ; } } package com . asakusafw . testdriver . core ; public interface TestRule { Object verify ( DataModelReflection expected , DataModelReflection actual ) ; } package com . asakusafw . testdriver . core ; import java . io . Closeable ; import java . io . IOException ; public interface DifferenceSink extends Closeable { void put ( Difference difference ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ImporterDescription ; public abstract class AbstractImporterPreparator < T extends ImporterDescription > extends BaseImporterPreparator < T > { public abstract void truncate ( T description ) throws IOException ; @ Override public void truncate ( T description , TestContext context ) throws IOException { truncate ( description ) ; } public abstract < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , T description ) throws IOException ; @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , T description , TestContext context ) throws IOException { return createOutput ( definition , description ) ; } } package com . asakusafw . testdriver . core ; import java . math . BigDecimal ; import java . math . BigInteger ; public abstract class DataModelScanner < C , E extends Throwable > { public void scan ( DataModelDefinition < ? > definition , C context ) throws E { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } for ( PropertyName name : definition . getProperties ( ) ) { scan ( definition , name , context ) ; } } public void scan ( DataModelDefinition < ? > definition , PropertyName name , C context ) throws E { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } PropertyType type = definition . getType ( name ) ; if ( type == null ) { anyProperty ( name , context ) ; } else { switch ( type ) { case BOOLEAN : booleanProperty ( name , context ) ; break ; case BYTE : byteProperty ( name , context ) ; break ; case DATE : dateProperty ( name , context ) ; break ; case DATETIME : datetimeProperty ( name , context ) ; break ; case DECIMAL : decimalProperty ( name , context ) ; break ; case DOUBLE : doubleProperty ( name , context ) ; break ; case FLOAT : floatProperty ( name , context ) ; break ; case INT : intProperty ( name , context ) ; break ; case INTEGER : integerProperty ( name , context ) ; break ; case LONG : longProperty ( name , context ) ; break ; case OBJECT : objectProperty ( name , context ) ; break ; case SEQUENCE : sequenceProperty ( name , context ) ; break ; case SHORT : shortProperty ( name , context ) ; break ; case STRING : stringProperty ( name , context ) ; break ; case TIME : timeProperty ( name , context ) ; break ; default : anyProperty ( name , context ) ; break ; } } } public void booleanProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void byteProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void shortProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void intProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void longProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void integerProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void floatProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void doubleProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void decimalProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void stringProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void dateProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void timeProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void datetimeProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void sequenceProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void objectProperty ( PropertyName name , C context ) throws E { anyProperty ( name , context ) ; } public void anyProperty ( PropertyName name , C context ) throws E { return ; } } package com . asakusafw . testdriver . core ; import java . io . Closeable ; import java . io . IOException ; public interface DataModelSource extends Closeable { DataModelReflection next ( ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; import java . util . List ; import java . util . ServiceLoader ; public class SpiDifferenceSinkProvider implements DifferenceSinkProvider { private final List < DifferenceSinkProvider > elements ; public SpiDifferenceSinkProvider ( ClassLoader serviceClassLoader ) { if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . elements = Util . loadService ( DifferenceSinkProvider . class , serviceClassLoader ) ; } @ Override public < T > DifferenceSink create ( DataModelDefinition < T > definition , URI sink , TestContext context ) throws IOException { for ( DifferenceSinkProvider service : elements ) { DifferenceSink result = service . create ( definition , sink , context ) ; if ( result != null ) { return result ; } } return null ; } } package com . asakusafw . testdriver . core ; import java . lang . annotation . Annotation ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; public interface DataModelDefinition < T > { Class < T > getModelClass ( ) ; < A extends Annotation > A getAnnotation ( Class < A > annotationType ) ; Collection < PropertyName > getProperties ( ) ; PropertyType getType ( PropertyName name ) ; < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) ; DataModelDefinition . Builder < T > newReflection ( ) ; DataModelReflection toReflection ( T object ) ; T toObject ( DataModelReflection reflection ) ; public class Builder < T > { protected final DataModelDefinition < T > definition ; protected final Map < PropertyName , Object > properties ; public Builder ( DataModelDefinition < T > definition ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } this . definition = definition ; this . properties = new HashMap < PropertyName , Object > ( ) ; } public Builder < T > add ( PropertyName name , Object value ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties . containsKey ( name ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , definition ) ) ; } PropertyType type = definition . getType ( name ) ; if ( type != null && value != null && type . getRepresentation ( ) . isInstance ( value ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , type , value , definition ) ) ; } properties . put ( name , value ) ; return this ; } public DataModelReflection build ( ) { return new DataModelReflection ( properties ) ; } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; public interface DataModelSinkProvider { < T > DataModelSink create ( DataModelDefinition < T > definition , URI sink , TestContext context ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . runtime . util . TypeUtil ; import com . asakusafw . vocabulary . external . ExporterDescription ; public abstract class BaseExporterRetriever < T extends ExporterDescription > implements ExporterRetriever < T > { @ SuppressWarnings ( "" ) @ Override public Class < T > getDescriptionClass ( ) { List < Type > arguments = TypeUtil . invoke ( BaseExporterRetriever . class , getClass ( ) ) ; if ( arguments . size ( ) != ) { throw new IllegalStateException ( MessageFormat . format ( "" , getClass ( ) . getName ( ) ) ) ; } Type first = arguments . get ( ) ; if ( ( first instanceof Class < ? > ) == false || ExporterDescription . class . isAssignableFrom ( ( Class < ? > ) first ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , ExporterDescription . class . getName ( ) , getClass ( ) . getName ( ) ) ) ; } return ( Class < T > ) first ; } } package com . asakusafw . testdriver . core ; @ Deprecated public interface SourceProvider extends DataModelSourceProvider { } package com . asakusafw . testdriver . core ; public class ModelVerifierDriver < T > implements VerifyRule { private final ModelVerifier < ? super T > verifier ; private final DataModelDefinition < ? extends T > definition ; public ModelVerifierDriver ( ModelVerifier < ? super T > verifier , DataModelDefinition < ? extends T > definition ) { if ( verifier == null ) { throw new IllegalArgumentException ( "" ) ; } if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } this . verifier = verifier ; this . definition = definition ; } @ Override public Object getKey ( DataModelReflection target ) { return verifier . getKey ( convert ( target ) ) ; } @ Override public Object verify ( DataModelReflection expected , DataModelReflection actual ) { return verifier . verify ( convert ( expected ) , convert ( actual ) ) ; } private T convert ( DataModelReflection reflection ) { if ( reflection == null ) { return null ; } return definition . toObject ( reflection ) ; } } package com . asakusafw . testdriver . core ; import java . util . Date ; public class VerifyContext { private final TestContext testContext ; private final Date testStarted ; private volatile Date testFinished ; public VerifyContext ( TestContext testContext ) { this ( testContext , new Date ( ) ) ; } public VerifyContext ( TestContext testContext , Date testStarted ) { if ( testContext == null ) { throw new IllegalArgumentException ( "" ) ; } if ( testStarted == null ) { throw new IllegalArgumentException ( "" ) ; } this . testContext = testContext ; this . testStarted = ( Date ) testStarted . clone ( ) ; } public TestContext getTestContext ( ) { return testContext ; } public void testFinished ( ) { setTestFinished ( new Date ( ) ) ; } public void setTestFinished ( Date testFinished ) { if ( testFinished == null ) { throw new IllegalArgumentException ( "" ) ; } this . testFinished = ( Date ) testFinished . clone ( ) ; } public Date getTestStarted ( ) { return ( Date ) testStarted . clone ( ) ; } public Date getTestFinished ( ) { if ( testFinished == null ) { throw new IllegalStateException ( "" ) ; } return ( Date ) testFinished . clone ( ) ; } } package com . asakusafw . testdriver . core ; import java . util . List ; public class CompositeVerifyRule implements VerifyRule { private final VerifyRule rule ; private final TestRule [ ] fragments ; public CompositeVerifyRule ( VerifyRule rule , List < ? extends TestRule > fragments ) { if ( rule == null ) { throw new IllegalArgumentException ( "" ) ; } if ( fragments == null ) { throw new IllegalArgumentException ( "" ) ; } this . rule = rule ; this . fragments = fragments . toArray ( new TestRule [ fragments . size ( ) ] ) ; } @ Override public Object getKey ( DataModelReflection target ) { return rule . getKey ( target ) ; } @ Override public Object verify ( DataModelReflection expected , DataModelReflection actual ) { Object primary = rule . verify ( expected , actual ) ; if ( primary != null ) { return primary ; } for ( TestRule fragment : fragments ) { Object extra = fragment . verify ( expected , actual ) ; if ( extra != null ) { return extra ; } } return null ; } } package com . asakusafw . testdriver . core ; import java . util . Collections ; import java . util . Map ; public interface TestContext { ClassLoader getClassLoader ( ) ; Map < String , String > getEnvironmentVariables ( ) ; Map < String , String > getArguments ( ) ; public static class Empty implements TestContext { @ Override public Map < String , String > getArguments ( ) { return Collections . emptyMap ( ) ; } @ Override public Map < String , String > getEnvironmentVariables ( ) { return System . getenv ( ) ; } @ Override public ClassLoader getClassLoader ( ) { return ClassLoader . getSystemClassLoader ( ) ; } } } package com . asakusafw . testdriver . core ; import java . io . IOException ; import java . net . URI ; public interface VerifyRuleProvider { < T > VerifyRule get ( DataModelDefinition < T > definition , VerifyContext context , URI source ) throws IOException ; } package com . asakusafw . testdriver . core ; import java . io . IOException ; public abstract class DataModelSinkFactory { public abstract < T > DataModelSink createSink ( DataModelDefinition < T > definition , TestContext context ) throws IOException ; } package com . asakusafw . testdriver . hadoop ; import java . net . URL ; import org . apache . hadoop . conf . Configuration ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; public class ConfigurationFactory extends ConfigurationProvider { static final Logger LOG = LoggerFactory . getLogger ( ConfigurationFactory . class ) ; public ConfigurationFactory ( URL defaultConfigPath ) { super ( defaultConfigPath ) ; } public ConfigurationFactory ( ) { super ( ) ; } public static ConfigurationFactory getDefault ( ) { return new ConfigurationFactory ( ) ; } @ Override protected void configure ( Configuration configuration ) { configuration . set ( "" , AsakusaTestLocalFileSystem . class . getName ( ) ) ; } } package com . asakusafw . testdriver . hadoop ; package com . asakusafw . testdriver . hadoop ; import java . io . IOException ; import java . net . URI ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . LocalFileSystem ; public class AsakusaTestLocalFileSystem extends LocalFileSystem { @ Override public void initialize ( URI name , Configuration conf ) throws IOException { super . initialize ( name , conf ) ; setWorkingDirectory ( getHomeDirectory ( ) ) ; } } package com . asakusafw . testdriver . rule ; import java . math . BigDecimal ; import java . text . MessageFormat ; public class DecimalRange implements ValuePredicate < BigDecimal > { private final BigDecimal lowerBound ; private final BigDecimal upperBound ; public DecimalRange ( BigDecimal lowerBound , BigDecimal upperBound ) { this . lowerBound = lowerBound ; this . upperBound = upperBound ; } @ Override public boolean accepts ( BigDecimal expected , BigDecimal actual ) { if ( expected == null || actual == null ) { throw new IllegalArgumentException ( ) ; } return expected . add ( lowerBound ) . compareTo ( actual ) <= && actual . compareTo ( expected . add ( upperBound ) ) <= ; } @ Override public String describeExpected ( BigDecimal expected , BigDecimal actual ) { if ( expected == null ) { return "" ; } return MessageFormat . format ( "" , Util . format ( expected . add ( lowerBound ) ) , Util . format ( expected . add ( upperBound ) ) ) ; } } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; public class IntegerRange implements ValuePredicate < Number > { private final long lowerBound ; private final long upperBound ; public IntegerRange ( long lowerBound , long upperBound ) { this . lowerBound = lowerBound ; this . upperBound = upperBound ; } @ Override public boolean accepts ( Number expected , Number actual ) { if ( expected == null || actual == null ) { throw new IllegalArgumentException ( ) ; } long e = expected . longValue ( ) ; long a = actual . longValue ( ) ; return ( e + lowerBound <= a && a <= e + upperBound ) ; } @ Override public String describeExpected ( Number expected , Number actual ) { if ( expected == null ) { return "" ; } return MessageFormat . format ( "" , Util . format ( expected . longValue ( ) + lowerBound ) , Util . format ( expected . longValue ( ) + upperBound ) ) ; } } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; import com . asakusafw . testdriver . core . VerifyRule ; public class VerifyRuleBuilder { private final DataModelDefinition < ? > definition ; private final Set < DataModelCondition > dataModelConditions ; private final Map < PropertyName , Property > propertyConditions ; public VerifyRuleBuilder ( DataModelDefinition < ? > definition ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } this . definition = definition ; this . dataModelConditions = new HashSet < DataModelCondition > ( ) ; this . propertyConditions = new LinkedHashMap < PropertyName , VerifyRuleBuilder . Property > ( ) ; } public VerifyRuleBuilder acceptIfAbsent ( ) { this . dataModelConditions . add ( DataModelCondition . IGNORE_ABSENT ) ; return this ; } public VerifyRuleBuilder acceptIfUnexpected ( ) { this . dataModelConditions . add ( DataModelCondition . IGNORE_UNEXPECTED ) ; return this ; } public Property property ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } String [ ] words = name . split ( "" ) ; PropertyName propertyName = PropertyName . newInstance ( words ) ; PropertyType type = definition . getType ( propertyName ) ; if ( type == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , definition . getModelClass ( ) . getName ( ) , propertyName ) ) ; } Property subBuilder = propertyConditions . get ( propertyName ) ; if ( subBuilder == null ) { subBuilder = new Property ( propertyName , type ) ; propertyConditions . put ( propertyName , subBuilder ) ; } return subBuilder ; } public VerifyRule toVerifyRule ( ) { List < PropertyName > keys = new ArrayList < PropertyName > ( ) ; List < PropertyCondition < ? > > properties = new ArrayList < PropertyCondition < ? > > ( ) ; for ( Map . Entry < PropertyName , Property > entry : propertyConditions . entrySet ( ) ) { Property property = entry . getValue ( ) ; if ( property . key ) { keys . add ( entry . getKey ( ) ) ; } if ( property . predicates . isEmpty ( ) == false ) { @ SuppressWarnings ( { "" , "" } ) PropertyCondition < ? > cond = new PropertyCondition ( entry . getKey ( ) , definition . getType ( entry . getKey ( ) ) . getRepresentation ( ) , property . predicates ) ; properties . add ( cond ) ; } } return new VerifyRuleInterpretor ( keys , dataModelConditions , properties ) ; } public static class Property { private final PropertyName name ; private final PropertyType type ; boolean key ; final List < ValuePredicate < ? > > predicates ; Property ( PropertyName name , PropertyType type ) { assert name != null ; assert type != null ; this . name = name ; this . type = type ; this . key = false ; this . predicates = new ArrayList < ValuePredicate < ? > > ( ) ; } public PropertyName getName ( ) { return name ; } public PropertyType getType ( ) { return type ; } public Property asKey ( ) { this . key = true ; return this ; } public Property accept ( ValuePredicate < ? > predicate ) { if ( predicate == null ) { throw new IllegalArgumentException ( "" ) ; } this . predicates . add ( predicate ) ; return this ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( name ) ; builder . append ( "" ) ; builder . append ( type ) ; builder . append ( "" ) ; builder . append ( key ) ; builder . append ( "" ) ; builder . append ( predicates ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } } package com . asakusafw . testdriver . rule ; public interface ValuePredicate < T > { boolean accepts ( T expected , T actual ) ; String describeExpected ( T expected , T actual ) ; } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; public class Not < T > implements ValuePredicate < T > { private final ValuePredicate < T > factor ; public Not ( ValuePredicate < T > factor ) { if ( factor == null ) { throw new IllegalArgumentException ( "" ) ; } this . factor = factor ; } @ Override public boolean accepts ( T expected , T actual ) { return factor . accepts ( expected , actual ) == false ; } @ Override public String describeExpected ( T expected , T actual ) { String factorExpected = factor . describeExpected ( expected , actual ) ; if ( factorExpected == null ) { return null ; } return MessageFormat . format ( "" , factorExpected ) ; } } package com . asakusafw . testdriver . rule ; import java . util . LinkedHashMap ; import java . util . Map ; import com . asakusafw . testdriver . core . Difference ; final class Util { static String format ( Object value ) { return Difference . format ( value ) ; } static Map < Object , String > formatMap ( Map < ? , ? > map ) { assert map != null ; Map < Object , String > results = new LinkedHashMap < Object , String > ( ) ; for ( Map . Entry < ? , ? > entry : map . entrySet ( ) ) { results . put ( entry . getKey ( ) , format ( entry . getValue ( ) ) ) ; } return results ; } private Util ( ) { return ; } } package com . asakusafw . testdriver . rule ; public enum DataModelCondition { IGNORE_MATCHED , IGNORE_ABSENT , IGNORE_UNEXPECTED , } package com . asakusafw . testdriver . rule ; public class IsNull implements ValuePredicate < Object > { @ Override public boolean accepts ( Object expected , Object actual ) { return actual == null ; } @ Override public String describeExpected ( Object expected , Object actual ) { return "" ; } } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; public class FloatRange implements ValuePredicate < Number > { private final double lowerBound ; private final double upperBound ; public FloatRange ( double lowerBound , double upperBound ) { this . lowerBound = lowerBound ; this . upperBound = upperBound ; } @ Override public boolean accepts ( Number expected , Number actual ) { if ( expected == null || actual == null ) { throw new IllegalArgumentException ( ) ; } double e = expected . doubleValue ( ) ; double a = actual . doubleValue ( ) ; return ( e + lowerBound <= a && a <= e + upperBound ) ; } @ Override public String describeExpected ( Number expected , Number actual ) { if ( expected == null ) { return "" ; } return MessageFormat . format ( "" , Util . format ( expected . doubleValue ( ) + lowerBound ) , Util . format ( expected . doubleValue ( ) + upperBound ) ) ; } } package com . asakusafw . testdriver . rule ; import java . math . BigDecimal ; import java . util . Calendar ; public final class Predicates { public static ValuePredicate < Object > equalTo ( Object value ) { return new ExpectConstant < Object > ( value , new Equals ( ) ) ; } public static < T > ValuePredicate < T > not ( ValuePredicate < T > predicate ) { if ( predicate == null ) { throw new IllegalArgumentException ( "" ) ; } return new Not < T > ( predicate ) ; } public static ValuePredicate < Object > equals ( ) { return new Equals ( ) ; } public static ValuePredicate < Object > isNull ( ) { return new IsNull ( ) ; } public static ValuePredicate < Number > floatRange ( double lower , double upper ) { return new FloatRange ( lower , upper ) ; } public static ValuePredicate < Number > integerRange ( long lower , long upper ) { return new IntegerRange ( lower , upper ) ; } public static ValuePredicate < BigDecimal > decimalRange ( BigDecimal lower , BigDecimal upper ) { if ( lower == null ) { throw new IllegalArgumentException ( "" ) ; } if ( upper == null ) { throw new IllegalArgumentException ( "" ) ; } return new DecimalRange ( lower , upper ) ; } public static ValuePredicate < Calendar > dateRange ( int lower , int upper ) { return new CalendarRange ( lower , upper , Calendar . DATE ) ; } public static ValuePredicate < Calendar > timeRange ( int lower , int upper ) { return new CalendarRange ( lower , upper , Calendar . SECOND ) ; } public static ValuePredicate < Calendar > period ( Calendar begin , Calendar end ) { return new Period ( begin , end ) ; } public static ValuePredicate < String > containsString ( ) { return new ContainsString ( ) ; } private Predicates ( ) { return ; } } package com . asakusafw . testdriver . rule ; public class BothAreNull implements ValuePredicate < Object > { @ Override public boolean accepts ( Object expected , Object actual ) { return expected == null && actual == null ; } @ Override public String describeExpected ( Object expected , Object actual ) { if ( expected != null ) { return null ; } return "" ; } } package com . asakusafw . testdriver . rule ; public class ExpectConstant < T > implements ValuePredicate < T > { private final T constant ; private final ValuePredicate < T > successor ; public ExpectConstant ( T constant , ValuePredicate < T > successor ) { if ( successor == null ) { throw new IllegalArgumentException ( "" ) ; } this . constant = constant ; this . successor = successor ; } @ Override public boolean accepts ( T expected , T actual ) { return successor . accepts ( constant , actual ) ; } @ Override public String describeExpected ( T expected , T actual ) { return successor . describeExpected ( constant , actual ) ; } } package com . asakusafw . testdriver . rule ; package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; import java . util . Calendar ; public class Period implements ValuePredicate < Calendar > { private final Calendar begin ; private final Calendar end ; public Period ( Calendar begin , Calendar end ) { this . begin = begin == null ? null : ( Calendar ) begin . clone ( ) ; this . end = end == null ? null : ( Calendar ) end . clone ( ) ; normalize ( this . begin ) ; normalize ( this . end ) ; } private void normalize ( Calendar calendar ) { assert calendar != null ; fillZeroIfUnset ( calendar , Calendar . HOUR_OF_DAY ) ; fillZeroIfUnset ( calendar , Calendar . MINUTE ) ; fillZeroIfUnset ( calendar , Calendar . SECOND ) ; fillZeroIfUnset ( calendar , Calendar . MILLISECOND ) ; } private void fillZeroIfUnset ( Calendar calendar , int field ) { assert calendar != null ; if ( calendar . isSet ( field ) == false ) { calendar . set ( field , ) ; } } @ Override public boolean accepts ( Calendar expected , Calendar actual ) { if ( actual == null ) { throw new IllegalArgumentException ( ) ; } if ( begin != null && begin . compareTo ( actual ) > ) { return false ; } if ( begin != null && actual . compareTo ( end ) > ) { return false ; } return true ; } @ Override public String describeExpected ( Calendar expected , Calendar actual ) { return MessageFormat . format ( "" , begin == null ? "" : Util . format ( begin ) , end == null ? "" : Util . format ( end ) ) ; } } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; public class ContainsString implements ValuePredicate < String > { @ Override public boolean accepts ( String expected , String actual ) { if ( expected == null || actual == null ) { throw new IllegalArgumentException ( ) ; } return actual . indexOf ( expected ) >= ; } @ Override public String describeExpected ( String expected , String actual ) { if ( expected == null ) { return "" ; } return MessageFormat . format ( "" , Util . format ( expected ) ) ; } } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; import java . util . Calendar ; public class CalendarRange implements ValuePredicate < Calendar > { private final int lowerBound ; private final int upperBound ; private final int scale ; public CalendarRange ( int lowerBound , int upperBound , int scale ) { this . lowerBound = lowerBound ; this . upperBound = upperBound ; this . scale = scale ; } @ Override public boolean accepts ( Calendar expected , Calendar actual ) { if ( expected == null || actual == null ) { throw new IllegalArgumentException ( ) ; } return add ( expected , lowerBound ) . compareTo ( actual ) <= && actual . compareTo ( add ( expected , upperBound ) ) <= ; } @ Override public String describeExpected ( Calendar expected , Calendar actual ) { if ( expected == null ) { return "" ; } return MessageFormat . format ( "" , Util . format ( add ( expected , upperBound ) ) , Util . format ( add ( expected , lowerBound ) ) ) ; } private Calendar add ( Calendar c , int offset ) { Calendar copy = ( Calendar ) c . clone ( ) ; copy . add ( scale , offset ) ; return copy ; } } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . VerifyRule ; public class VerifyRuleInterpretor implements VerifyRule { private final List < PropertyName > keys ; private final Set < DataModelCondition > modelConditions ; private final List < ? extends PropertyCondition < ? > > propertyConditions ; public VerifyRuleInterpretor ( List < PropertyName > keys , Set < DataModelCondition > modelConditions , List < ? extends PropertyCondition < ? > > propertyConditions ) { if ( keys == null ) { throw new IllegalArgumentException ( "" ) ; } if ( modelConditions == null ) { throw new IllegalArgumentException ( "" ) ; } if ( propertyConditions == null ) { throw new IllegalArgumentException ( "" ) ; } this . keys = keys ; this . modelConditions = modelConditions ; this . propertyConditions = propertyConditions ; } @ Override public Map < PropertyName , Object > getKey ( DataModelReflection target ) { Map < PropertyName , Object > results = new LinkedHashMap < PropertyName , Object > ( ) ; for ( PropertyName name : keys ) { results . put ( name , target . getValue ( name ) ) ; } return results ; } @ Override public Object verify ( DataModelReflection expected , DataModelReflection actual ) { if ( expected == null ) { if ( modelConditions . contains ( DataModelCondition . IGNORE_UNEXPECTED ) ) { return null ; } else { return MessageFormat . format ( "" , Util . formatMap ( getKey ( actual ) ) ) ; } } if ( actual == null ) { if ( modelConditions . contains ( DataModelCondition . IGNORE_ABSENT ) ) { return null ; } else { return MessageFormat . format ( "" , Util . formatMap ( getKey ( expected ) ) ) ; } } if ( modelConditions . contains ( DataModelCondition . IGNORE_MATCHED ) ) { return null ; } return checkProperties ( expected , actual ) ; } private Object checkProperties ( DataModelReflection expected , DataModelReflection actual ) { List < String > differences = new ArrayList < String > ( ) ; for ( PropertyCondition < ? > condition : propertyConditions ) { Object e = expected . getValue ( condition . getPropertyName ( ) ) ; Object a = actual . getValue ( condition . getPropertyName ( ) ) ; if ( condition . accepts ( e , a ) == false ) { differences . add ( MessageFormat . format ( "" , condition . getPropertyName ( ) , Util . format ( a ) , condition . describeExpected ( e , a ) ) ) ; } } return differences . isEmpty ( ) ? null : differences ; } } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . PropertyName ; public class PropertyCondition < T > { static final Logger LOG = LoggerFactory . getLogger ( PropertyCondition . class ) ; private final PropertyName name ; private final Class < ? extends T > type ; private final List < ? extends ValuePredicate < ? super T > > predicates ; public PropertyCondition ( PropertyName name , Class < ? extends T > type , List < ? extends ValuePredicate < ? super T > > predicates ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( predicates == null ) { throw new IllegalArgumentException ( "" ) ; } if ( predicates . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . type = type ; this . predicates = predicates ; } public PropertyName getPropertyName ( ) { return name ; } public boolean accepts ( Object expected , Object actual ) { T e = type . cast ( expected ) ; T a = type . cast ( actual ) ; for ( ValuePredicate < ? super T > predicate : predicates ) { try { if ( predicate . accepts ( e , a ) ) { return true ; } } catch ( IllegalArgumentException ex ) { } } return false ; } public String describeExpected ( Object expected , Object actual ) { T e = type . cast ( expected ) ; T a = type . cast ( actual ) ; StringBuilder buf = new StringBuilder ( ) ; boolean sawDescription = false ; for ( ValuePredicate < ? super T > pred : predicates ) { String description = pred . describeExpected ( e , a ) ; if ( description == null ) { continue ; } if ( sawDescription ) { buf . append ( "" ) ; } sawDescription = true ; buf . append ( MessageFormat . format ( "" , description ) ) ; } if ( sawDescription ) { return buf . toString ( ) ; } else { return "" ; } } } package com . asakusafw . testdriver . rule ; import java . text . MessageFormat ; public class Equals implements ValuePredicate < Object > { @ Override public boolean accepts ( Object expected , Object actual ) { if ( expected == null || actual == null ) { throw new IllegalArgumentException ( ) ; } return expected . equals ( actual ) ; } @ Override public String describeExpected ( Object expected , Object actual ) { if ( expected == null ) { return "" ; } return MessageFormat . format ( "" , Util . format ( expected ) ) ; } } package com . asakusafw . testdriver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import org . junit . Test ; import com . asakusafw . runtime . core . BatchContext ; import com . asakusafw . runtime . core . Report ; import com . asakusafw . runtime . core . Report . Level ; import com . asakusafw . runtime . core . ResourceConfiguration ; public class OperatorTestEnvironmentTest { @ Test public void load ( ) throws Throwable { OperatorTestEnvironment env = new OperatorTestEnvironment ( getFilePath ( "" ) ) ; env . before ( ) ; try { assertThat ( Collector . lastMessage , is ( "" ) ) ; Report . error ( "" ) ; assertThat ( Collector . lastLevel , is ( Level . ERROR ) ) ; assertThat ( Collector . lastMessage , is ( "" ) ) ; } finally { env . after ( ) ; } assertThat ( Collector . lastMessage , is ( "" ) ) ; } @ Test public void reload ( ) throws Throwable { OperatorTestEnvironment env = new OperatorTestEnvironment ( getFilePath ( "" ) ) ; env . before ( ) ; try { assertThat ( Collector . lastMessage , is ( "" ) ) ; env . configure ( "" , "" ) ; env . configure ( "" , "" ) ; env . reload ( ) ; assertThat ( Collector . lastMessage , is ( "" ) ) ; } finally { env . after ( ) ; } assertThat ( Collector . lastMessage , is ( "" ) ) ; } @ Test public void variable ( ) throws Throwable { OperatorTestEnvironment env = new OperatorTestEnvironment ( getFilePath ( "" ) ) ; env . before ( ) ; try { env . setBatchArg ( "" , "" ) ; env . reload ( ) ; assertThat ( BatchContext . get ( "" ) , is ( "" ) ) ; } finally { env . after ( ) ; } } private String getFilePath ( String name ) { String className = OperatorTestEnvironmentTest . class . getName ( ) ; int lastDot = className . lastIndexOf ( '' ) ; assertThat ( className , lastDot , greaterThanOrEqualTo ( ) ) ; String packageName = className . substring ( , lastDot ) ; return packageName . replace ( '' , '' ) + '' + name ; } public static final class Collector extends Report . Delegate { static volatile Level lastLevel ; static volatile String lastMessage ; @ Override protected void report ( Level level , String message ) throws IOException { lastLevel = level ; lastMessage = message ; } @ Override public void setup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { lastLevel = Level . INFO ; lastMessage = configuration . get ( "" , "" ) ; } @ Override public void cleanup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { lastLevel = Level . INFO ; lastMessage = configuration . get ( "" , "" ) ; } } } package com . asakusafw . testdriver . temporary ; import java . lang . annotation . Annotation ; import java . util . Collection ; import java . util . Collections ; import org . apache . hadoop . io . Text ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; public class MockTextDefinition implements DataModelDefinition < Text > { static final PropertyName VALUE = PropertyName . newInstance ( "" ) ; @ Override public Class < Text > getModelClass ( ) { return Text . class ; } @ Override public < A extends Annotation > A getAnnotation ( Class < A > annotationType ) { return null ; } @ Override public Collection < PropertyName > getProperties ( ) { return Collections . singleton ( VALUE ) ; } @ Override public PropertyType getType ( PropertyName name ) { if ( VALUE . equals ( name ) ) { return PropertyType . STRING ; } return null ; } @ Override public < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) { return null ; } @ Override public Builder < Text > newReflection ( ) { return new Builder < Text > ( this ) ; } @ Override public DataModelReflection toReflection ( Text object ) { return newReflection ( ) . add ( VALUE , object . toString ( ) ) . build ( ) ; } @ Override public Text toObject ( DataModelReflection reflection ) { Text text = new Text ( ) ; String string = ( String ) reflection . getValue ( VALUE ) ; if ( string != null ) { text . set ( string ) ; } return text ; } } package com . asakusafw . testdriver . temporary ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Text ; import org . junit . After ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . runtime . configuration . HadoopEnvironmentChecker ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; public class TemporaryExporterRetrieverTest { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Rule public HadoopEnvironmentChecker check = new HadoopEnvironmentChecker ( false ) ; private ConfigurationFactory factory ; private FileSystem fileSystem ; @ Before public void setUp ( ) throws Exception { factory = ConfigurationFactory . getDefault ( ) ; Configuration conf = factory . newInstance ( ) ; fileSystem = FileSystem . get ( conf ) ; } @ After public void tearDown ( ) throws Exception { if ( fileSystem != null ) { fileSystem . delete ( new Path ( "" ) , true ) ; } } @ Test public void simple ( ) throws Exception { MockFileExporter exporter = new MockFileExporter ( Text . class , "" ) ; TemporaryOutputRetriever retriever = new TemporaryOutputRetriever ( factory ) ; putText ( "" , "" , "" ) ; MockTextDefinition definition = new MockTextDefinition ( ) ; DataModelSource result = retriever . createSource ( definition , exporter , EMPTY ) ; try { DataModelReflection ref ; ref = result . next ( ) ; assertThat ( ref , is ( not ( nullValue ( ) ) ) ) ; assertThat ( definition . toObject ( ref ) , is ( new Text ( "" ) ) ) ; ref = result . next ( ) ; assertThat ( ref , is ( not ( nullValue ( ) ) ) ) ; assertThat ( definition . toObject ( ref ) , is ( new Text ( "" ) ) ) ; ref = result . next ( ) ; assertThat ( ref , is ( nullValue ( ) ) ) ; } finally { result . close ( ) ; } } private void putText ( String path , String ... lines ) throws IOException { ModelOutput < Text > output = TemporaryStorage . openOutput ( factory . newInstance ( ) , Text . class , new Path ( path ) ) ; try { for ( String s : lines ) { output . write ( new Text ( s ) ) ; } } finally { output . close ( ) ; } } private static class MockFileExporter extends TemporaryOutputDescription { private final Class < ? > modelType ; private final String pathPrefix ; MockFileExporter ( Class < ? > modelType , String pathPrefix ) { assert modelType != null ; assert pathPrefix != null ; this . modelType = modelType ; this . pathPrefix = pathPrefix ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getPathPrefix ( ) { return pathPrefix ; } } } package com . asakusafw . testdriver . temporary ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Set ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Text ; import org . junit . After ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . runtime . configuration . HadoopEnvironmentChecker ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . utils . collections . Sets ; public class TemporaryImporterPreparatorTest { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Rule public HadoopEnvironmentChecker check = new HadoopEnvironmentChecker ( false ) ; private ConfigurationFactory factory ; private FileSystem fileSystem ; @ Before public void setUp ( ) throws Exception { factory = ConfigurationFactory . getDefault ( ) ; Configuration conf = factory . newInstance ( ) ; fileSystem = FileSystem . get ( conf ) ; } @ After public void tearDown ( ) throws Exception { if ( fileSystem != null ) { fileSystem . delete ( new Path ( "" ) , true ) ; } } @ Test public void simple ( ) throws Exception { TemporaryInputPreparator target = new TemporaryInputPreparator ( factory ) ; ModelOutput < Text > open = target . createOutput ( new MockTextDefinition ( ) , new MockTemporaryImporter ( Text . class , "" ) , EMPTY ) ; try { open . write ( new Text ( "" ) ) ; open . write ( new Text ( "" ) ) ; } finally { open . close ( ) ; } ModelInput < Text > input = TemporaryStorage . openInput ( factory . newInstance ( ) , Text . class , new Path ( "" ) ) ; try { Text text = new Text ( ) ; assertThat ( input . readTo ( text ) , is ( true ) ) ; assertThat ( text . toString ( ) , is ( "" ) ) ; assertThat ( input . readTo ( text ) , is ( true ) ) ; assertThat ( text . toString ( ) , is ( "" ) ) ; assertThat ( input . readTo ( text ) , is ( false ) ) ; } finally { input . close ( ) ; } } private static class MockTemporaryImporter extends TemporaryInputDescription { private final Class < ? > modelType ; private final Set < String > paths ; MockTemporaryImporter ( Class < ? > modelType , String ... paths ) { this . modelType = modelType ; this . paths = Sets . from ( paths ) ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public Set < String > getPaths ( ) { return paths ; } } } package com . asakusafw . testdriver ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . configuration . FrameworkDeployer ; import com . asakusafw . testdriver . testing . batch . SimpleBatch ; import com . asakusafw . testdriver . testing . model . Simple ; public class BatchTesterTest { @ Rule public FrameworkDeployer framework = new FrameworkDeployer ( ) ; @ Test public void simple ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Simple . class ) . prepare ( "" ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_jobflow ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Simple . class ) . prepare ( "" ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_input_prepare_name ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Simple . class ) . prepare ( "" ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_input_prepare_type ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Void . class ) . prepare ( "" ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_input_prepare_data ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Simple . class ) . prepare ( "" ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_output_prepare_name ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Simple . class ) . prepare ( "" ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . prepare ( "" ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_output_prepare_type ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Simple . class ) . prepare ( "" ) ; tester . jobflow ( "" ) . output ( "" , Void . class ) . prepare ( "" ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_prepare_data ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . prepare ( "" ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_output_verify_name ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Simple . class ) . prepare ( "" ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_output_verify_type ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . input ( "" , Simple . class ) . prepare ( "" ) ; tester . jobflow ( "" ) . output ( "" , Void . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleBatch . class ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_verify_data ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_verify_rule ( ) { BatchTester tester = new BatchTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . jobflow ( "" ) . output ( "" , Simple . class ) . verify ( "" , "" ) ; } } package com . asakusafw . testdriver ; import java . text . MessageFormat ; import com . asakusafw . testdriver . core . ModelVerifier ; public class IdentityVerifier implements ModelVerifier < Object > { @ Override public Object getKey ( Object target ) { return target ; } @ Override public Object verify ( Object expected , Object actual ) { if ( expected == null ) { return MessageFormat . format ( "" , actual ) ; } else if ( actual == null ) { return MessageFormat . format ( "" , expected ) ; } else if ( expected . equals ( actual ) == false ) { return MessageFormat . format ( "" , expected , actual ) ; } return null ; } } package com . asakusafw . testdriver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . net . URL ; import java . net . URLClassLoader ; import org . junit . Assume ; import org . junit . Ignore ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . configuration . FrameworkDeployer ; import com . asakusafw . testdriver . testing . flowpart . SimpleFlowPart ; import com . asakusafw . testdriver . testing . model . Simple ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class FlowPartTesterTest { @ Rule public FrameworkDeployer framework = new FrameworkDeployer ( ) ; @ Test public void simple ( ) { FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; } @ Test public void dumpActual_path ( ) { File target = new File ( "" ) ; target . delete ( ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpActual ( target . getPath ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpActual_noverify ( ) { File target = new File ( "" ) ; target . delete ( ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . dumpActual ( target . getPath ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpActual_uri ( ) { File target = new File ( "" ) ; target . delete ( ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpActual ( target . toURI ( ) . toString ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpActual_file ( ) { File target = new File ( "" ) ; target . delete ( ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpActual ( target ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpDifference_path ( ) { File target = new File ( "" ) ; target . delete ( ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpDifference ( target . getPath ( ) ) ; try { tester . runTest ( new SimpleFlowPart ( in , out ) ) ; fail ( ) ; } catch ( AssertionError e ) { } assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpDifference_uri ( ) { File target = new File ( "" ) ; target . delete ( ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpDifference ( target . toURI ( ) . toString ( ) ) ; try { tester . runTest ( new SimpleFlowPart ( in , out ) ) ; fail ( ) ; } catch ( AssertionError e ) { } assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpDifference_file ( ) { File target = new File ( "" ) ; target . delete ( ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpDifference ( target ) ; try { tester . runTest ( new SimpleFlowPart ( in , out ) ) ; fail ( ) ; } catch ( AssertionError e ) { } assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpDifference_none ( ) { File target = new File ( "" ) ; Assume . assumeThat ( target . exists ( ) == false || target . delete ( ) , is ( true ) ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpDifference ( target . getPath ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; assertThat ( target . exists ( ) , is ( false ) ) ; } @ Test public void inArchive ( ) { URL archive = getClass ( ) . getResource ( "" ) ; assertThat ( archive , is ( notNullValue ( ) ) ) ; URLClassLoader loader = new URLClassLoader ( new URL [ ] { archive } ) ; URL inUrl = loader . findResource ( "" ) ; URL outUrl = loader . findResource ( "" ) ; assertThat ( inUrl , is ( notNullValue ( ) ) ) ; assertThat ( outUrl , is ( notNullValue ( ) ) ) ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( inUrl . toExternalForm ( ) ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( outUrl . toExternalForm ( ) , new IdentityVerifier ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; } @ Ignore ( "" ) @ Test public void withSpace ( ) { FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; } @ Test public void fullpath ( ) { String prefix = getClass ( ) . getName ( ) ; prefix = prefix . substring ( , prefix . length ( ) - getClass ( ) . getSimpleName ( ) . length ( ) ) . replace ( '' , '' ) ; prefix = '' + prefix ; FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( prefix + "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( prefix + "" , new IdentityVerifier ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; } @ Test public void simpleWithDataSize ( ) { FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; FlowPartDriverInput < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) . withDataSize ( DataSize . TINY ) ; assertEquals ( DataSize . TINY , in . getImporterDescription ( ) . getDataSize ( ) ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_input_prepare_data ( ) { FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_prepare_data ( ) { FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . output ( "" , Simple . class ) . prepare ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_verify_data ( ) { FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_verify_rule ( ) { FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . output ( "" , Simple . class ) . verify ( "" , "" ) ; } @ Test public void skip ( ) { FlowPartTester tester = new FlowPartTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . skipCleanInput ( true ) ; tester . skipCleanOutput ( true ) ; tester . skipPrepareInput ( true ) ; tester . skipPrepareOutput ( true ) ; tester . skipRunJobflow ( true ) ; tester . skipVerify ( true ) ; In < Simple > in = tester . input ( "" , Simple . class ) . prepare ( "" ) ; Out < Simple > out = tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( new SimpleFlowPart ( in , out ) ) ; } } package com . asakusafw . testdriver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . configuration . FrameworkDeployer ; import com . asakusafw . testdriver . testing . jobflow . SimpleJobflow ; import com . asakusafw . testdriver . testing . model . Simple ; public class JobFlowTesterTest { @ Rule public FrameworkDeployer framework = new FrameworkDeployer ( ) ; @ Test public void simple ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleJobflow . class ) ; } @ Test public void dumpActual_path ( ) { File target = new File ( "" ) ; target . delete ( ) ; JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpActual ( target . getPath ( ) ) ; tester . runTest ( SimpleJobflow . class ) ; assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpActual_uri ( ) { File target = new File ( "" ) ; target . delete ( ) ; JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpActual ( target . toURI ( ) . toString ( ) ) ; tester . runTest ( SimpleJobflow . class ) ; assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpActual_file ( ) { File target = new File ( "" ) ; target . delete ( ) ; JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpActual ( target ) ; tester . runTest ( SimpleJobflow . class ) ; assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpDifference_path ( ) { File target = new File ( "" ) ; target . delete ( ) ; JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpDifference ( target . getPath ( ) ) ; try { tester . runTest ( SimpleJobflow . class ) ; fail ( ) ; } catch ( AssertionError e ) { } assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpDifference_uri ( ) { File target = new File ( "" ) ; target . delete ( ) ; JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpDifference ( target . toURI ( ) . toString ( ) ) ; try { tester . runTest ( SimpleJobflow . class ) ; fail ( ) ; } catch ( AssertionError e ) { } assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test public void dumpDifference_file ( ) { File target = new File ( "" ) ; target . delete ( ) ; JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) . dumpDifference ( target ) ; try { tester . runTest ( SimpleJobflow . class ) ; fail ( ) ; } catch ( AssertionError e ) { } assertThat ( target . exists ( ) , is ( true ) ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_input_prepare_name ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleJobflow . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_input_prepare_type ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Void . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleJobflow . class ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_input_prepare_data ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_output_prepare_name ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . prepare ( "" ) ; tester . runTest ( SimpleJobflow . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_output_prepare_type ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Void . class ) . prepare ( "" ) ; tester . runTest ( SimpleJobflow . class ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_prepare_data ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . output ( "" , Simple . class ) . prepare ( "" ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_output_verify_name ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleJobflow . class ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_output_verify_type ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . input ( "" , Simple . class ) . prepare ( "" ) ; tester . output ( "" , Void . class ) . verify ( "" , new IdentityVerifier ( ) ) ; tester . runTest ( SimpleJobflow . class ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_verify_data ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . output ( "" , Simple . class ) . verify ( "" , new IdentityVerifier ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_output_verify_rule ( ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setFrameworkHomePath ( framework . getHome ( ) ) ; tester . output ( "" , Simple . class ) . verify ( "" , "" ) ; } } package com . asakusafw . testdriver . testing . jobflow ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . testdriver . testing . model . Simple ; public class SimpleImporter extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Simple . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" ) ; } } package com . asakusafw . testdriver . testing . jobflow ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . testdriver . testing . model . Simple ; public class SimpleExporter extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Simple . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . testdriver . testing . jobflow ; import com . asakusafw . testdriver . testing . flowpart . SimpleFlowPartFactory ; import com . asakusafw . testdriver . testing . flowpart . SimpleFlowPartFactory . SimpleFlowPart ; import com . asakusafw . testdriver . testing . model . Simple ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SimpleJobflow extends FlowDescription { In < Simple > in ; Out < Simple > out ; public SimpleJobflow ( @ Import ( name = "" , description = SimpleImporter . class ) In < Simple > in , @ Export ( name = "" , description = SimpleExporter . class ) Out < Simple > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { SimpleFlowPartFactory factory = new SimpleFlowPartFactory ( ) ; SimpleFlowPart op = factory . create ( in ) ; out . add ( op . out ) ; } } package com . asakusafw . testdriver . testing . operator ; import com . asakusafw . testdriver . testing . model . Simple ; import com . asakusafw . vocabulary . operator . Update ; public abstract class SimpleOperator { @ Update public void setValue ( Simple model , String value ) { model . setValueAsString ( value ) ; } } package com . asakusafw . testdriver . testing . flowpart ; import com . asakusafw . testdriver . testing . model . Simple ; import com . asakusafw . testdriver . testing . operator . SimpleOperatorFactory ; import com . asakusafw . testdriver . testing . operator . SimpleOperatorFactory . SetValue ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; @ FlowPart public class SimpleFlowPart extends FlowDescription { final In < Simple > in ; final Out < Simple > out ; public SimpleFlowPart ( In < Simple > in , Out < Simple > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { SimpleOperatorFactory factory = new SimpleOperatorFactory ( ) ; SetValue operator = factory . setValue ( in , "" ) ; out . add ( operator . out ) ; } } package com . asakusafw . testdriver . testing . batch ; import com . asakusafw . testdriver . testing . jobflow . SimpleJobflow ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class SimpleBatch extends BatchDescription { @ Override protected void describe ( ) { run ( SimpleJobflow . class ) . soon ( ) ; } } package com . asakusafw . testdriver ; import java . io . BufferedReader ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . UnsupportedEncodingException ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import org . apache . commons . io . FileUtils ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . CommandContext ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . testing . StageInfo ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . testdriver . TestExecutionPlan . Command ; import com . asakusafw . testdriver . TestExecutionPlan . Job ; import com . asakusafw . testdriver . core . DataModelSourceFactory ; import com . asakusafw . testdriver . core . Difference ; import com . asakusafw . testdriver . core . TestModerator ; import com . asakusafw . testdriver . core . VerifyContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class JobflowExecutor { static final Logger LOG = LoggerFactory . getLogger ( JobflowExecutor . class ) ; public static final String SUBMIT_JOB_SCRIPT = "" ; private final TestDriverContext context ; private final TestModerator moderator ; private final ConfigurationFactory configurations ; public JobflowExecutor ( TestDriverContext context ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . moderator = new TestModerator ( context . getRepository ( ) , context ) ; this . configurations = ConfigurationFactory . getDefault ( ) ; } public void cleanWorkingDirectory ( ) throws IOException { Configuration conf = configurations . newInstance ( ) ; FileSystem fs = FileSystem . get ( conf ) ; Path path = new Path ( context . getClusterWorkDir ( ) ) ; LOG . debug ( "" , path ) ; fs . delete ( path , true ) ; } public void cleanInputOutput ( JobflowInfo info ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context . isSkipCleanInput ( ) == false ) { for ( Map . Entry < String , ImporterDescription > entry : info . getImporterMap ( ) . entrySet ( ) ) { LOG . debug ( "" , entry . getKey ( ) ) ; moderator . truncate ( entry . getValue ( ) ) ; } } else { LOG . info ( "" ) ; } if ( context . isSkipCleanOutput ( ) == false ) { for ( Map . Entry < String , ExporterDescription > entry : info . getExporterMap ( ) . entrySet ( ) ) { LOG . debug ( "" , entry . getKey ( ) ) ; moderator . truncate ( entry . getValue ( ) ) ; } } else { LOG . info ( "" ) ; } } public void prepareInput ( JobflowInfo info , Iterable < ? extends DriverInputBase < ? > > inputs ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } if ( inputs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context . isSkipPrepareInput ( ) == false ) { for ( DriverInputBase < ? > input : inputs ) { DataModelSourceFactory source = input . getSource ( ) ; if ( source != null ) { String name = input . getName ( ) ; LOG . debug ( "" , name , source ) ; ImporterDescription description = info . findImporter ( name ) ; if ( description == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , info . getJobflow ( ) . getFlowId ( ) ) ) ; } moderator . prepare ( input . getModelType ( ) , description , source ) ; } } } else { LOG . info ( "" ) ; } } public void prepareOutput ( JobflowInfo info , Iterable < ? extends DriverOutputBase < ? > > outputs ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context . isSkipPrepareOutput ( ) == false ) { for ( DriverOutputBase < ? > output : outputs ) { DataModelSourceFactory source = output . getSource ( ) ; if ( source != null ) { String name = output . getName ( ) ; LOG . debug ( "" , name , source ) ; ExporterDescription description = info . findExporter ( name ) ; if ( description == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , info . getJobflow ( ) . getFlowId ( ) ) ) ; } moderator . prepare ( output . getModelType ( ) , description , source ) ; } } } else { LOG . info ( "" ) ; } } public void runJobflow ( JobflowInfo info ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context . isSkipRunJobflow ( ) == false ) { File destDir = context . getJobflowPackageLocation ( info . getJobflow ( ) . getBatchId ( ) ) ; FileUtils . copyFileToDirectory ( info . getPackageFile ( ) , destDir ) ; CommandContext commands = context . getCommandContext ( ) ; Map < String , String > dPropMap = createHadoopProperties ( commands ) ; TestExecutionPlan plan = createExecutionPlan ( info , commands , dPropMap ) ; executePlan ( plan , info . getPackageFile ( ) ) ; } else { LOG . info ( "" ) ; } } private Map < String , String > createHadoopProperties ( CommandContext commands ) { assert commands != null ; Map < String , String > dPropMap = Maps . create ( ) ; dPropMap . put ( StageConstants . PROP_USER , context . getOsUser ( ) ) ; dPropMap . put ( StageConstants . PROP_EXECUTION_ID , commands . getExecutionId ( ) ) ; dPropMap . put ( StageConstants . PROP_ASAKUSA_BATCH_ARGS , commands . getVariableList ( ) ) ; dPropMap . putAll ( context . getExtraConfigurations ( ) ) ; return dPropMap ; } private TestExecutionPlan createExecutionPlan ( JobflowInfo info , CommandContext commands , Map < String , String > properties ) { assert info != null ; assert commands != null ; assert properties != null ; List < Job > jobs = Lists . create ( ) ; for ( StageInfo stage : info . getStages ( ) ) { jobs . add ( new Job ( stage . getClassName ( ) , commands . getExecutionId ( ) , properties ) ) ; } List < Command > initializers = Lists . create ( ) ; List < Command > importers = Lists . create ( ) ; List < Command > exporters = Lists . create ( ) ; List < Command > finalizers = Lists . create ( ) ; for ( ExternalIoCommandProvider provider : info . getCommandProviders ( ) ) { initializers . addAll ( convert ( provider . getInitializeCommand ( commands ) ) ) ; importers . addAll ( convert ( provider . getImportCommand ( commands ) ) ) ; exporters . addAll ( convert ( provider . getExportCommand ( commands ) ) ) ; finalizers . addAll ( convert ( provider . getFinalizeCommand ( commands ) ) ) ; } return new TestExecutionPlan ( info . getJobflow ( ) . getFlowId ( ) , commands . getExecutionId ( ) , initializers , importers , jobs , exporters , finalizers ) ; } private List < TestExecutionPlan . Command > convert ( List < ExternalIoCommandProvider . Command > commands ) { List < TestExecutionPlan . Command > results = Lists . create ( ) ; for ( ExternalIoCommandProvider . Command cmd : commands ) { results . add ( new TestExecutionPlan . Command ( cmd . getCommandTokens ( ) , cmd . getModuleName ( ) , cmd . getProfileName ( ) , cmd . getEnvironment ( ) ) ) ; } return results ; } private void executePlan ( TestExecutionPlan plan , File jobflowPackageFile ) throws IOException { assert plan != null ; assert jobflowPackageFile != null ; try { runJobFlowCommands ( plan . getInitializers ( ) ) ; runJobFlowCommands ( plan . getImporters ( ) ) ; runJobflowJobs ( jobflowPackageFile , plan . getJobs ( ) ) ; runJobFlowCommands ( plan . getExporters ( ) ) ; } finally { runJobFlowCommands ( plan . getFinalizers ( ) ) ; } } private void runJobflowJobs ( File jobflowPackageFile , List < Job > jobs ) throws IOException { assert jobflowPackageFile != null ; assert jobs != null ; for ( Job job : jobs ) { HadoopJobInfo jobElement = new HadoopJobInfo ( job . getExecutionId ( ) , jobflowPackageFile . getAbsolutePath ( ) , job . getClassName ( ) , job . getProperties ( ) ) ; runHadoopJob ( jobElement ) ; } } private void runJobFlowCommands ( List < TestExecutionPlan . Command > cmdList ) throws IOException { assert cmdList != null ; for ( TestExecutionPlan . Command command : cmdList ) { List < String > cmdToken = command . getCommandTokens ( ) ; String [ ] cmd = cmdToken . toArray ( new String [ cmdToken . size ( ) ] ) ; runShellAndAssert ( cmd , getEnvironmentVariables ( ) ) ; } } private void runHadoopJob ( HadoopJobInfo hadoopJobInfo ) throws IOException { assert hadoopJobInfo != null ; List < String > command = Lists . create ( ) ; command . add ( new File ( context . getFrameworkHomePath ( ) , SUBMIT_JOB_SCRIPT ) . getAbsolutePath ( ) ) ; command . add ( hadoopJobInfo . getJarName ( ) ) ; command . add ( hadoopJobInfo . getClassName ( ) ) ; Map < String , String > dPropMap = hadoopJobInfo . getDPropMap ( ) ; if ( dPropMap != null ) { for ( Map . Entry < String , String > entry : dPropMap . entrySet ( ) ) { command . add ( "" ) ; command . add ( entry . getKey ( ) + "" + entry . getValue ( ) ) ; } } int exitValue = runShell ( command . toArray ( new String [ command . size ( ) ] ) , getEnvironmentVariables ( ) ) ; if ( exitValue != ) { throw new AssertionError ( MessageFormat . format ( "" , exitValue , hadoopJobInfo . getJobFlowId ( ) , command ) ) ; } } private Map < String , String > getEnvironmentVariables ( ) { Map < String , String > variables = Maps . create ( ) ; variables . put ( TestDriverContext . ENV_FRAMEWORK_PATH , context . getFrameworkHomePath ( ) . getAbsolutePath ( ) ) ; return variables ; } public int runShell ( String [ ] shellCmd , Map < String , String > environmentVariables ) throws IOException { if ( shellCmd == null ) { throw new IllegalArgumentException ( "" ) ; } if ( environmentVariables == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( "" , toStringShellCmdArray ( shellCmd ) ) ; ProcessBuilder builder = new ProcessBuilder ( shellCmd ) ; builder . redirectErrorStream ( true ) ; builder . environment ( ) . putAll ( environmentVariables ) ; builder . directory ( new File ( System . getProperty ( "" , "" ) ) ) ; int exitCode ; Process process = null ; InputStream is = null ; try { process = builder . start ( ) ; is = process . getInputStream ( ) ; InputStreamThread it = new InputStreamThread ( is ) ; it . start ( ) ; exitCode = process . waitFor ( ) ; it . join ( ) ; } catch ( InterruptedException e ) { throw new IOException ( MessageFormat . format ( "" , toStringShellCmdArray ( shellCmd ) ) , e ) ; } finally { try { if ( is != null ) { is . close ( ) ; } if ( process != null ) { process . getOutputStream ( ) . close ( ) ; process . getErrorStream ( ) . close ( ) ; process . destroy ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } return exitCode ; } private void runShellAndAssert ( String [ ] shellCmd , Map < String , String > variables ) throws IOException { assert shellCmd != null ; assert variables != null ; int exitCode = runShell ( shellCmd , variables ) ; if ( exitCode != ) { throw new AssertionError ( MessageFormat . format ( "" , exitCode , toStringShellCmdArray ( shellCmd ) ) ) ; } } private String toStringShellCmdArray ( String [ ] shellCmd ) { assert shellCmd != null ; StringBuilder sb = new StringBuilder ( ) ; for ( String cmd : shellCmd ) { sb . append ( cmd ) . append ( "" ) ; } return sb . toString ( ) . trim ( ) ; } public void verify ( JobflowInfo info , VerifyContext verifyContext , Iterable < ? extends DriverOutputBase < ? > > outputs ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } if ( verifyContext == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context . isSkipVerify ( ) == false ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "" ) ) ; boolean sawError = false ; for ( DriverOutputBase < ? > output : outputs ) { String name = output . getName ( ) ; ExporterDescription description = info . findExporter ( name ) ; if ( description == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , info . getJobflow ( ) . getFlowId ( ) ) ) ; } if ( output . getResultSink ( ) != null ) { LOG . debug ( "" , output . getName ( ) , output . getVerifier ( ) ) ; moderator . save ( output . getModelType ( ) , description , output . getResultSink ( ) ) ; } if ( output . getVerifier ( ) != null ) { LOG . debug ( "" , name , output . getVerifier ( ) ) ; List < Difference > diffList = moderator . inspect ( output . getModelType ( ) , description , verifyContext , output . getVerifier ( ) ) ; if ( diffList . isEmpty ( ) == false ) { sawError = true ; LOG . warn ( "" , new Object [ ] { info . getJobflow ( ) . getBatchId ( ) , info . getJobflow ( ) . getFlowId ( ) , output . getName ( ) , diffList . size ( ) , } ) ; if ( output . getDifferenceSink ( ) != null ) { LOG . debug ( "" , name , output . getDifferenceSink ( ) ) ; moderator . save ( output . getModelType ( ) , diffList , output . getDifferenceSink ( ) ) ; } for ( Difference difference : diffList ) { sb . append ( String . format ( "" , output . getModelType ( ) . getSimpleName ( ) , difference ) ) ; } } } } if ( sawError ) { throw new AssertionError ( sb ) ; } } else { LOG . info ( "" ) ; } } } class InputStreamThread extends Thread { private BufferedReader br ; private final List < String > list = Lists . create ( ) ; public InputStreamThread ( InputStream is ) { br = new BufferedReader ( new InputStreamReader ( is , Charset . defaultCharset ( ) ) ) ; } public InputStreamThread ( InputStream is , String charset ) { try { br = new BufferedReader ( new InputStreamReader ( is , charset ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } @ Override public void run ( ) { for ( ; ; ) { try { String line = br . readLine ( ) ; if ( line == null ) { break ; } list . add ( line ) ; System . out . println ( line ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } } package com . asakusafw . testdriver ; import java . io . File ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Map ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . CommandContext ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowCompilerOptions . GenericOptionValue ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . core . TestToolRepository ; import com . asakusafw . utils . collections . Maps ; public class TestDriverContext implements TestContext { static final Logger LOG = LoggerFactory . getLogger ( TestDriverContext . class ) ; public static final String KEY_RUNTIME_WORKING_DIRECTORY = "" ; public static final String KEY_COMPILER_WORKING_DIRECTORY = "" ; public static final String ENV_FRAMEWORK_PATH = "" ; private static final String COMPILERWORK_DIR_DEFAULT = "" ; private static final String HADOOPWORK_DIR_DEFAULT = "" ; private volatile File frameworkHomePath ; private final Class < ? > callerClass ; private final TestToolRepository repository ; private final Map < String , String > extraConfigurations ; private final Map < String , String > batchArgs ; private final FlowCompilerOptions options ; private volatile String currentBatchId ; private volatile String currentFlowId ; private volatile String currentExecutionId ; private boolean skipCleanInput ; private boolean skipCleanOutput ; private boolean skipPrepareInput ; private boolean skipPrepareOutput ; private boolean skipRunJobflow ; private boolean skipVerify ; public TestDriverContext ( Class < ? > contextClass ) { if ( contextClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . callerClass = contextClass ; this . repository = new TestToolRepository ( contextClass . getClassLoader ( ) ) ; this . extraConfigurations = new TreeMap < String , String > ( ) ; this . batchArgs = new TreeMap < String , String > ( ) ; this . options = new FlowCompilerOptions ( ) ; configureOptions ( ) ; } private void configureOptions ( ) { LOG . debug ( "" ) ; this . options . putExtraAttribute ( "" , GenericOptionValue . AUTO . getSymbol ( ) ) ; } public void setFrameworkHomePath ( File frameworkHomePath ) { this . frameworkHomePath = frameworkHomePath ; } public File getFrameworkHomePath ( ) { if ( frameworkHomePath == null ) { String defaultHomePath = System . getenv ( ENV_FRAMEWORK_PATH ) ; if ( defaultHomePath == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , ENV_FRAMEWORK_PATH ) ) ; } return new File ( defaultHomePath ) ; } return frameworkHomePath ; } public File getJobflowPackageLocation ( String batchId ) { if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } File apps = new File ( getFrameworkHomePath ( ) , "" ) ; File batch = new File ( apps , batchId ) ; File lib = new File ( batch , "" ) ; return lib ; } public CommandContext getCommandContext ( ) { CommandContext context = new CommandContext ( getFrameworkHomePath ( ) . getAbsolutePath ( ) + "" , getExecutionId ( ) , getBatchArgs ( ) ) ; return context ; } public File getCompilerWorkingDirectory ( ) { return new File ( getCompileWorkBaseDir ( ) ) ; } public String getOsUser ( ) { String user = System . getenv ( "" ) ; return user ; } public String getCompileWorkBaseDir ( ) { String dir = System . getProperty ( KEY_COMPILER_WORKING_DIRECTORY ) ; if ( dir == null ) { return COMPILERWORK_DIR_DEFAULT ; } return dir ; } public String getClusterWorkDir ( ) { String dir = System . getProperty ( KEY_RUNTIME_WORKING_DIRECTORY ) ; if ( dir == null ) { return HADOOPWORK_DIR_DEFAULT ; } return dir ; } public Class < ? > getCallerClass ( ) { return callerClass ; } public TestToolRepository getRepository ( ) { return repository ; } public void prepareCurrentJobflow ( JobflowInfo info ) { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } this . currentBatchId = info . getJobflow ( ) . getBatchId ( ) ; this . currentFlowId = info . getJobflow ( ) . getFlowId ( ) ; this . currentExecutionId = MessageFormat . format ( "" , getCallerClass ( ) . getSimpleName ( ) , currentBatchId , currentFlowId ) ; } public String getExecutionId ( ) { if ( currentExecutionId == null ) { throw new IllegalStateException ( "" ) ; } return currentExecutionId ; } @ Deprecated public void changeExecutionId ( ) { } public Map < String , String > getExtraConfigurations ( ) { return extraConfigurations ; } public Map < String , String > getBatchArgs ( ) { return batchArgs ; } @ Override public Map < String , String > getEnvironmentVariables ( ) { return System . getenv ( ) ; } @ Override public Map < String , String > getArguments ( ) { Map < String , String > copy = Maps . from ( getBatchArgs ( ) ) ; if ( currentBatchId != null ) { copy . put ( StageConstants . VAR_BATCH_ID , currentBatchId ) ; } if ( currentFlowId != null ) { copy . put ( StageConstants . VAR_FLOW_ID , currentFlowId ) ; } if ( currentExecutionId != null ) { copy . put ( StageConstants . VAR_EXECUTION_ID , currentExecutionId ) ; } return Collections . unmodifiableMap ( copy ) ; } public FlowCompilerOptions getOptions ( ) { return options ; } @ Override public ClassLoader getClassLoader ( ) { return callerClass . getClassLoader ( ) ; } public String getCurrentBatchId ( ) { return currentBatchId ; } public void setCurrentBatchId ( String currentBatchId ) { this . currentBatchId = currentBatchId ; } public String getCurrentFlowId ( ) { return currentFlowId ; } public void setCurrentFlowId ( String currentFlowId ) { this . currentFlowId = currentFlowId ; } public String getCurrentExecutionId ( ) { return currentExecutionId ; } public void setCurrentExecutionId ( String currentExecutionId ) { this . currentExecutionId = currentExecutionId ; } public boolean isSkipCleanInput ( ) { return skipCleanInput ; } public void setSkipCleanInput ( boolean skip ) { this . skipCleanInput = skip ; } public boolean isSkipCleanOutput ( ) { return skipCleanOutput ; } public void setSkipCleanOutput ( boolean skip ) { this . skipCleanOutput = skip ; } public boolean isSkipPrepareInput ( ) { return skipPrepareInput ; } public void setSkipPrepareInput ( boolean skip ) { this . skipPrepareInput = skip ; } public boolean isSkipPrepareOutput ( ) { return skipPrepareOutput ; } public void setSkipPrepareOutput ( boolean skip ) { this . skipPrepareOutput = skip ; } public boolean isSkipRunJobflow ( ) { return skipRunJobflow ; } public void setSkipRunJobflow ( boolean skip ) { this . skipRunJobflow = skip ; } public boolean isSkipVerify ( ) { return skipVerify ; } public void setSkipVerify ( boolean skip ) { this . skipVerify = skip ; } } package com . asakusafw . testdriver ; import java . io . File ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; public abstract class TestDriverBase { protected TestDriverContext driverContext ; public TestDriverBase ( Class < ? > callerClass ) { if ( callerClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . driverContext = new TestDriverContext ( callerClass ) ; } public void configure ( String key , String value ) { if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value != null ) { driverContext . getExtraConfigurations ( ) . put ( key , value ) ; } else { driverContext . getExtraConfigurations ( ) . remove ( key ) ; } } public void setBatchArg ( String key , String value ) { if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value != null ) { driverContext . getBatchArgs ( ) . put ( key , value ) ; } else { driverContext . getBatchArgs ( ) . remove ( key ) ; } } public void setOptimize ( int level ) { FlowCompilerOptions options = driverContext . getOptions ( ) ; if ( level <= ) { options . setCompressConcurrentStage ( false ) ; options . setCompressFlowPart ( false ) ; options . setHashJoinForSmall ( false ) ; options . setHashJoinForTiny ( false ) ; options . setEnableCombiner ( false ) ; } else if ( level == ) { options . setCompressConcurrentStage ( FlowCompilerOptions . Item . compressConcurrentStage . defaultValue ) ; options . setCompressFlowPart ( FlowCompilerOptions . Item . compressFlowPart . defaultValue ) ; options . setHashJoinForSmall ( FlowCompilerOptions . Item . hashJoinForSmall . defaultValue ) ; options . setHashJoinForTiny ( FlowCompilerOptions . Item . hashJoinForTiny . defaultValue ) ; options . setEnableCombiner ( FlowCompilerOptions . Item . enableCombiner . defaultValue ) ; } else { options . setCompressConcurrentStage ( true ) ; options . setCompressFlowPart ( true ) ; options . setHashJoinForSmall ( true ) ; options . setHashJoinForTiny ( true ) ; options . setEnableCombiner ( true ) ; } } public void setDebug ( boolean enable ) { driverContext . getOptions ( ) . setEnableDebugLogging ( enable ) ; } public void setFrameworkHomePath ( File frameworkHomePath ) { driverContext . setFrameworkHomePath ( frameworkHomePath ) ; } public void skipCleanInput ( boolean skip ) { driverContext . setSkipCleanInput ( skip ) ; } public void skipCleanOutput ( boolean skip ) { driverContext . setSkipCleanOutput ( skip ) ; } public void skipPrepareInput ( boolean skip ) { driverContext . setSkipPrepareInput ( skip ) ; } public void skipPrepareOutput ( boolean skip ) { driverContext . setSkipPrepareOutput ( skip ) ; } public void skipRunJobflow ( boolean skip ) { driverContext . setSkipRunJobflow ( skip ) ; } public void skipVerify ( boolean skip ) { driverContext . setSkipVerify ( skip ) ; } } package com . asakusafw . testdriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . runtime . stage . StageConstants ; final class FlowPartDriverUtils { private FlowPartDriverUtils ( ) { } public static Location createInputLocation ( TestDriverContext driverContext , String name ) { Location location = Location . fromPath ( driverContext . getClusterWorkDir ( ) , '' ) . append ( StageConstants . EXPR_EXECUTION_ID ) . append ( "" ) . append ( normalize ( name ) ) ; return location ; } public static Location createOutputLocation ( TestDriverContext driverContext , String name ) { Location location = Location . fromPath ( driverContext . getClusterWorkDir ( ) , '' ) . append ( StageConstants . EXPR_EXECUTION_ID ) . append ( "" ) . append ( normalize ( name ) ) . asPrefix ( ) ; return location ; } public static Location createWorkingLocation ( TestDriverContext driverContext ) { Location location = Location . fromPath ( driverContext . getClusterWorkDir ( ) , '' ) . append ( StageConstants . EXPR_EXECUTION_ID ) . append ( "" ) ; return location ; } private static String normalize ( String name ) { StringBuilder buf = new StringBuilder ( ) ; for ( char c : name . toCharArray ( ) ) { if ( '' <= c && c <= '' || '' <= c && c <= '' || '' <= c && c <= '' ) { buf . append ( c ) ; } else if ( c <= ) { buf . append ( '' ) ; buf . append ( String . format ( "" , ( int ) c ) ) ; } else { buf . append ( "" ) ; buf . append ( String . format ( "" , ( int ) c ) ) ; } } return buf . toString ( ) ; } } package com . asakusafw . testdriver ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . LinkedList ; import java . util . List ; import org . apache . commons . io . FileUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . FlowDescriptionDriver ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . testdriver . core . VerifyContext ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class FlowPartTester extends TestDriverBase { static final Logger LOG = LoggerFactory . getLogger ( FlowPartTester . class ) ; private final List < FlowPartDriverInput < ? > > inputs = new LinkedList < FlowPartDriverInput < ? > > ( ) ; private final List < FlowPartDriverOutput < ? > > outputs = new LinkedList < FlowPartDriverOutput < ? > > ( ) ; private final FlowDescriptionDriver descDriver = new FlowDescriptionDriver ( ) ; public FlowPartTester ( Class < ? > callerClass ) { super ( callerClass ) ; } public < T > FlowPartDriverInput < T > input ( String name , Class < T > modelType ) { FlowPartDriverInput < T > input = new FlowPartDriverInput < T > ( driverContext , descDriver , name , modelType ) ; inputs . add ( input ) ; return input ; } public < T > FlowPartDriverOutput < T > output ( String name , Class < T > modelType ) { FlowPartDriverOutput < T > output = new FlowPartDriverOutput < T > ( driverContext , descDriver , name , modelType ) ; outputs . add ( output ) ; return output ; } public void runTest ( FlowDescription flowDescription ) { try { runTestInternal ( flowDescription ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } private void runTestInternal ( FlowDescription flowDescription ) throws IOException { LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; LOG . info ( "" , flowDescription . getClass ( ) . getName ( ) ) ; String batchId = "" ; String flowId = "" ; File compileWorkDir = driverContext . getCompilerWorkingDirectory ( ) ; if ( compileWorkDir . exists ( ) ) { FileUtils . forceDelete ( compileWorkDir ) ; } FlowGraph flowGraph = descDriver . createFlowGraph ( flowDescription ) ; JobflowInfo jobflowInfo = DirectFlowCompiler . compile ( flowGraph , batchId , flowId , "" , FlowPartDriverUtils . createWorkingLocation ( driverContext ) , compileWorkDir , Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( flowDescription . getClass ( ) ) } ) , flowDescription . getClass ( ) . getClassLoader ( ) , driverContext . getOptions ( ) ) ; JobflowExecutor executor = new JobflowExecutor ( driverContext ) ; driverContext . prepareCurrentJobflow ( jobflowInfo ) ; LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; executor . cleanWorkingDirectory ( ) ; executor . cleanInputOutput ( jobflowInfo ) ; LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; executor . prepareInput ( jobflowInfo , inputs ) ; executor . prepareOutput ( jobflowInfo , outputs ) ; LOG . info ( "" , flowDescription . getClass ( ) . getName ( ) ) ; VerifyContext verifyContext = new VerifyContext ( driverContext ) ; executor . runJobflow ( jobflowInfo ) ; verifyContext . testFinished ( ) ; LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; executor . verify ( jobflowInfo , verifyContext , outputs ) ; } } package com . asakusafw . testdriver ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . LinkedList ; import java . util . List ; import org . apache . commons . io . FileUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . JobFlowClass ; import com . asakusafw . compiler . flow . JobFlowDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . testdriver . core . VerifyContext ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class JobFlowTester extends TestDriverBase { static final Logger LOG = LoggerFactory . getLogger ( JobFlowTester . class ) ; protected List < JobFlowDriverInput < ? > > inputs = new LinkedList < JobFlowDriverInput < ? > > ( ) ; protected List < JobFlowDriverOutput < ? > > outputs = new LinkedList < JobFlowDriverOutput < ? > > ( ) ; public JobFlowTester ( Class < ? > callerClass ) { super ( callerClass ) ; } public < T > JobFlowDriverInput < T > input ( String name , Class < T > modelType ) { JobFlowDriverInput < T > input = new JobFlowDriverInput < T > ( driverContext , name , modelType ) ; inputs . add ( input ) ; return input ; } public < T > JobFlowDriverOutput < T > output ( String name , Class < T > modelType ) { JobFlowDriverOutput < T > output = new JobFlowDriverOutput < T > ( driverContext , name , modelType ) ; outputs . add ( output ) ; return output ; } public void runTest ( Class < ? extends FlowDescription > jobFlowDescriptionClass ) { try { runTestInternal ( jobFlowDescriptionClass ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } private void runTestInternal ( Class < ? extends FlowDescription > jobFlowDescriptionClass ) throws IOException { LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; LOG . info ( "" , jobFlowDescriptionClass . getName ( ) ) ; JobFlowDriver jobFlowDriver = JobFlowDriver . analyze ( jobFlowDescriptionClass ) ; assertFalse ( jobFlowDriver . getDiagnostics ( ) . toString ( ) , jobFlowDriver . hasError ( ) ) ; JobFlowClass jobFlowClass = jobFlowDriver . getJobFlowClass ( ) ; String batchId = "" ; String flowId = jobFlowClass . getConfig ( ) . name ( ) ; File compileWorkDir = driverContext . getCompilerWorkingDirectory ( ) ; if ( compileWorkDir . exists ( ) ) { FileUtils . forceDelete ( compileWorkDir ) ; } FlowGraph flowGraph = jobFlowClass . getGraph ( ) ; JobflowInfo jobflowInfo = DirectFlowCompiler . compile ( flowGraph , batchId , flowId , "" , Location . fromPath ( driverContext . getClusterWorkDir ( ) , '' ) , compileWorkDir , Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( jobFlowDescriptionClass ) } ) , jobFlowDescriptionClass . getClassLoader ( ) , driverContext . getOptions ( ) ) ; JobflowExecutor executor = new JobflowExecutor ( driverContext ) ; driverContext . prepareCurrentJobflow ( jobflowInfo ) ; LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; executor . cleanWorkingDirectory ( ) ; executor . cleanInputOutput ( jobflowInfo ) ; LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; executor . prepareInput ( jobflowInfo , inputs ) ; executor . prepareOutput ( jobflowInfo , outputs ) ; LOG . info ( "" , jobFlowDescriptionClass . getName ( ) ) ; VerifyContext verifyContext = new VerifyContext ( driverContext ) ; executor . runJobflow ( jobflowInfo ) ; verifyContext . testFinished ( ) ; LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; executor . verify ( jobflowInfo , verifyContext , outputs ) ; } } package com . asakusafw . testdriver ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class JobFlowDriverInput < T > extends DriverInputBase < T > { private static final Logger LOG = LoggerFactory . getLogger ( JobFlowDriverInput . class ) ; public JobFlowDriverInput ( TestDriverContext driverContext , String name , Class < T > modelType ) { this . driverContext = driverContext ; this . name = name ; this . modelType = modelType ; } public JobFlowDriverInput < T > prepare ( String sourcePath ) { LOG . info ( "" + getModelType ( ) ) ; setSourceUri ( sourcePath ) ; return this ; } } package com . asakusafw . testdriver ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelSinkFactory ; import com . asakusafw . testdriver . core . DifferenceSinkFactory ; import com . asakusafw . testdriver . core . ModelTester ; import com . asakusafw . testdriver . core . ModelVerifier ; import com . asakusafw . testdriver . core . TestRule ; import com . asakusafw . testdriver . core . VerifierFactory ; import com . asakusafw . testdriver . core . VerifyRule ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class DriverOutputBase < T > extends DriverInputBase < T > { private static final Logger LOG = LoggerFactory . getLogger ( DriverOutputBase . class ) ; protected ExporterDescription exporterDescription ; protected VerifierFactory verifier ; protected DataModelSinkFactory resultSink ; protected DifferenceSinkFactory differenceSink ; protected ExporterDescription getExporterDescription ( ) { return exporterDescription ; } protected void setExporterDescription ( ExporterDescription exporterDescription ) { this . exporterDescription = exporterDescription ; } protected VerifierFactory getVerifier ( ) { return verifier ; } protected void setVerifier ( VerifierFactory verifier ) { this . verifier = verifier ; } protected void setVerifier ( URI expectedUri , URI ruleUri , List < ? extends ModelTester < ? super T > > extraRules ) throws IOException { List < TestRule > ruleFragments = Lists . create ( ) ; for ( ModelTester < ? super T > tester : extraRules ) { TestRule fragment = driverContext . getRepository ( ) . toVerifyRuleFragment ( modelType , tester ) ; ruleFragments . add ( fragment ) ; } VerifierFactory factory = driverContext . getRepository ( ) . getVerifierFactory ( expectedUri , ruleUri , ruleFragments ) ; setVerifier ( factory ) ; } protected void setVerifier ( URI expectedUri , ModelVerifier < ? super T > modelVerifier ) throws IOException { LOG . info ( "" , expectedUri ) ; VerifyRule rule = driverContext . getRepository ( ) . toVerifyRule ( modelType , modelVerifier ) ; VerifierFactory factory = driverContext . getRepository ( ) . getVerifierFactory ( expectedUri , rule ) ; setVerifier ( factory ) ; } protected void setVerifier ( String expectedPath , String rulePath , List < ? extends ModelTester < ? super T > > extraRules ) throws IOException { URI expectedUri ; try { expectedUri = toUri ( expectedPath ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( "" + expectedPath , e ) ; } URI ruleUri ; try { ruleUri = toUri ( rulePath ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( "" + rulePath , e ) ; } setVerifier ( expectedUri , ruleUri , extraRules ) ; } protected void setVerifier ( String expectedPath , ModelVerifier < ? super T > modelVerifier ) throws IOException { URI expectedUri ; try { expectedUri = toUri ( expectedPath ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( "" + expectedPath , e ) ; } setVerifier ( expectedUri , modelVerifier ) ; } public DataModelSinkFactory getResultSink ( ) { return resultSink ; } public void setResultSink ( DataModelSinkFactory resultSink ) { this . resultSink = resultSink ; } public void setResultSinkUri ( String path ) { URI uri = toOutputUri ( path ) ; setResultSinkUri ( uri ) ; } public void setResultSinkUri ( URI uri ) { LOG . info ( "" , uri ) ; DataModelSinkFactory sink = driverContext . getRepository ( ) . getDataModelSinkFactory ( uri ) ; setResultSink ( sink ) ; } public DifferenceSinkFactory getDifferenceSink ( ) { return differenceSink ; } public void setDifferenceSink ( DifferenceSinkFactory differenceSink ) { this . differenceSink = differenceSink ; } protected void setDifferenceSinkUri ( String path ) { setDifferenceSinkUri ( toOutputUri ( path ) ) ; } protected void setDifferenceSinkUri ( URI uri ) { LOG . info ( "" , uri ) ; DifferenceSinkFactory sink = driverContext . getRepository ( ) . getDifferenceSinkFactory ( uri ) ; setDifferenceSink ( sink ) ; } protected URI toOutputUri ( String path ) { URI uri = URI . create ( path ) ; if ( uri . getScheme ( ) != null ) { return uri ; } return new File ( path ) . toURI ( ) ; } } package com . asakusafw . testdriver . temporary ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Set ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . testdriver . core . BaseImporterPreparator ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . ImporterPreparator ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; public class TemporaryInputPreparator extends BaseImporterPreparator < TemporaryInputDescription > { static final Logger LOG = LoggerFactory . getLogger ( TemporaryInputPreparator . class ) ; private final ConfigurationFactory configurations ; public TemporaryInputPreparator ( ) { this ( ConfigurationFactory . getDefault ( ) ) ; } public TemporaryInputPreparator ( ConfigurationFactory configurations ) { if ( configurations == null ) { throw new IllegalArgumentException ( "" ) ; } this . configurations = configurations ; } @ Override public void truncate ( TemporaryInputDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; VariableTable variables = createVariables ( context ) ; Configuration config = configurations . newInstance ( ) ; FileSystem fs = FileSystem . get ( config ) ; for ( String path : description . getPaths ( ) ) { String resolved = variables . parse ( path , false ) ; Path target = fs . makeQualified ( new Path ( resolved ) ) ; LOG . debug ( "" , target ) ; boolean succeed = fs . delete ( target , true ) ; LOG . debug ( "" , succeed , target ) ; } return ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , TemporaryInputDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; checkType ( definition , description ) ; Set < String > path = description . getPaths ( ) ; if ( path . isEmpty ( ) ) { return new ModelOutput < V > ( ) { @ Override public void close ( ) throws IOException { return ; } @ Override public void write ( V model ) throws IOException { return ; } } ; } VariableTable variables = createVariables ( context ) ; String destination = path . iterator ( ) . next ( ) ; String resolved = variables . parse ( destination , false ) ; Configuration conf = configurations . newInstance ( ) ; ModelOutput < V > output = TemporaryStorage . openOutput ( conf , definition . getModelClass ( ) , new Path ( resolved ) ) ; return output ; } private VariableTable createVariables ( TestContext context ) { assert context != null ; VariableTable result = new VariableTable ( ) ; result . defineVariables ( context . getArguments ( ) ) ; return result ; } private < V > void checkType ( DataModelDefinition < V > definition , TemporaryInputDescription description ) throws IOException { if ( definition . getModelClass ( ) != description . getModelType ( ) ) { throw new IOException ( MessageFormat . format ( "" , definition . getModelClass ( ) . getName ( ) , description . getModelType ( ) . getName ( ) , description ) ) ; } } } package com . asakusafw . testdriver . temporary ; import java . io . IOException ; import java . util . Iterator ; import java . util . List ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . utils . collections . Lists ; public class TemporaryDataModelSource implements DataModelSource { private final Configuration conf ; private final DataModelDefinition < Object > definition ; private final Object object ; private final FileSystem fs ; private final Iterator < Path > rest ; private volatile ModelInput < Object > current ; @ SuppressWarnings ( "" ) public TemporaryDataModelSource ( Configuration conf , DataModelDefinition < ? > definition , String pathExpression ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( pathExpression == null ) { throw new IllegalArgumentException ( "" ) ; } this . conf = conf ; this . definition = ( DataModelDefinition < Object > ) definition ; this . object = definition . toObject ( definition . newReflection ( ) . build ( ) ) ; Path path = new Path ( pathExpression ) ; this . fs = path . getFileSystem ( conf ) ; FileStatus [ ] list = fs . globStatus ( path ) ; List < Path > paths = Lists . create ( ) ; for ( int i = ; i < list . length ; i ++ ) { paths . add ( list [ i ] . getPath ( ) ) ; } this . rest = paths . iterator ( ) ; } @ Override public DataModelReflection next ( ) throws IOException { while ( true ) { if ( current == null ) { if ( rest . hasNext ( ) == false ) { return null ; } current = TemporaryStorage . openInput ( conf , definition . getModelClass ( ) , rest . next ( ) ) ; } if ( current . readTo ( object ) ) { break ; } else { current . close ( ) ; current = null ; } } return definition . toReflection ( object ) ; } @ Override public void close ( ) throws IOException { if ( current != null ) { current . close ( ) ; current = null ; } } } package com . asakusafw . testdriver . temporary ; package com . asakusafw . testdriver . temporary ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . testdriver . core . BaseExporterRetriever ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . ExporterRetriever ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; public class TemporaryOutputRetriever extends BaseExporterRetriever < TemporaryOutputDescription > { static final Logger LOG = LoggerFactory . getLogger ( TemporaryOutputRetriever . class ) ; private final ConfigurationFactory configurations ; public TemporaryOutputRetriever ( ) { this ( ConfigurationFactory . getDefault ( ) ) ; } public TemporaryOutputRetriever ( ConfigurationFactory configurations ) { if ( configurations == null ) { throw new IllegalArgumentException ( "" ) ; } this . configurations = configurations ; } @ Override public void truncate ( TemporaryOutputDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; VariableTable variables = createVariables ( context ) ; Configuration config = configurations . newInstance ( ) ; FileSystem fs = FileSystem . get ( config ) ; String resolved = variables . parse ( description . getPathPrefix ( ) , false ) ; Path path = new Path ( resolved ) ; Path output = path . getParent ( ) ; Path target ; if ( output == null ) { LOG . warn ( "" , path ) ; target = fs . makeQualified ( path ) ; } else { LOG . warn ( "" , output ) ; target = fs . makeQualified ( output ) ; } LOG . debug ( "" , target ) ; boolean succeed = fs . delete ( target , true ) ; LOG . debug ( "" , succeed , target ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , TemporaryOutputDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; checkType ( definition , description ) ; VariableTable variables = createVariables ( context ) ; String destination = description . getPathPrefix ( ) . replace ( '' , '' ) ; String resolved = variables . parse ( destination , false ) ; Configuration conf = configurations . newInstance ( ) ; ModelOutput < V > output = TemporaryStorage . openOutput ( conf , definition . getModelClass ( ) , new Path ( resolved ) ) ; return output ; } @ Override public < V > DataModelSource createSource ( DataModelDefinition < V > definition , TemporaryOutputDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; VariableTable variables = createVariables ( context ) ; checkType ( definition , description ) ; Configuration conf = configurations . newInstance ( ) ; String resolved = variables . parse ( description . getPathPrefix ( ) , false ) ; return new TemporaryDataModelSource ( conf , definition , resolved ) ; } private VariableTable createVariables ( TestContext context ) { assert context != null ; VariableTable result = new VariableTable ( ) ; result . defineVariables ( context . getArguments ( ) ) ; return result ; } private < V > void checkType ( DataModelDefinition < V > definition , TemporaryOutputDescription description ) throws IOException { if ( definition . getModelClass ( ) != description . getModelType ( ) ) { throw new IOException ( MessageFormat . format ( "" , definition . getModelClass ( ) . getName ( ) , description . getModelType ( ) . getName ( ) , description ) ) ; } } } package com . asakusafw . testdriver ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelSinkFactory ; import com . asakusafw . testdriver . core . DifferenceSinkFactory ; import com . asakusafw . testdriver . core . ModelTester ; import com . asakusafw . testdriver . core . ModelVerifier ; import com . asakusafw . testdriver . core . VerifierFactory ; public class JobFlowDriverOutput < T > extends DriverOutputBase < T > { private static final Logger LOG = LoggerFactory . getLogger ( JobFlowDriverOutput . class ) ; public JobFlowDriverOutput ( TestDriverContext driverContext , String name , Class < T > modelType ) { this . driverContext = driverContext ; this . name = name ; this . modelType = modelType ; } public JobFlowDriverOutput < T > prepare ( String sourcePath ) { LOG . info ( "" + getModelType ( ) ) ; setSourceUri ( sourcePath ) ; return this ; } public JobFlowDriverOutput < T > verify ( String expectedPath , String verifyRulePath ) { LOG . info ( "" + modelType ) ; try { setVerifier ( expectedPath , verifyRulePath , Collections . < ModelTester < T > > emptyList ( ) ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , expectedPath , verifyRulePath ) , e ) ; } return this ; } public JobFlowDriverOutput < T > verify ( String expectedPath , String verifyRulePath , ModelTester < ? super T > tester ) { LOG . info ( "" + modelType ) ; try { setVerifier ( expectedPath , verifyRulePath , Collections . singletonList ( tester ) ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , expectedPath , verifyRulePath , tester ) , e ) ; } return this ; } public JobFlowDriverOutput < T > verify ( String expectedPath , ModelVerifier < ? super T > modelVerifier ) { LOG . info ( "" + modelType ) ; try { setVerifier ( expectedPath , modelVerifier ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , expectedPath , modelVerifier ) , e ) ; } return this ; } public JobFlowDriverOutput < T > verify ( VerifierFactory factory ) { LOG . info ( "" + modelType ) ; setVerifier ( factory ) ; return this ; } public JobFlowDriverOutput < T > dumpActual ( String outputPath ) { setResultSinkUri ( outputPath ) ; return this ; } public JobFlowDriverOutput < T > dumpActual ( File outputPath ) { setResultSinkUri ( outputPath . toURI ( ) ) ; return this ; } public JobFlowDriverOutput < T > dumpActual ( DataModelSinkFactory factory ) { setResultSink ( factory ) ; return this ; } public JobFlowDriverOutput < T > dumpDifference ( String outputPath ) { setDifferenceSinkUri ( outputPath ) ; return this ; } public JobFlowDriverOutput < T > dumpDifference ( File outputPath ) { setDifferenceSinkUri ( outputPath . toURI ( ) ) ; return this ; } public JobFlowDriverOutput < T > dumpDifference ( DifferenceSinkFactory factory ) { setDifferenceSink ( factory ) ; return this ; } } package com . asakusafw . testdriver ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelSourceFactory ; import com . asakusafw . vocabulary . external . ImporterDescription ; public abstract class DriverInputBase < T > { private static final Logger LOG = LoggerFactory . getLogger ( DriverInputBase . class ) ; protected String name ; protected Class < T > modelType ; protected TestDriverContext driverContext ; protected DataModelSourceFactory source ; protected ImporterDescription importerDescription ; protected String getName ( ) { return name ; } protected void setName ( String name ) { this . name = name ; } protected Class < T > getModelType ( ) { return modelType ; } protected void setModelType ( Class < T > modelType ) { this . modelType = modelType ; } protected TestDriverContext getDriverContext ( ) { return driverContext ; } protected void setDriverContext ( TestDriverContext driverContext ) { this . driverContext = driverContext ; } protected ImporterDescription getImporterDescription ( ) { return importerDescription ; } protected void setImporterDescription ( ImporterDescription importerDescription ) { this . importerDescription = importerDescription ; } protected DataModelSourceFactory getSource ( ) { return source ; } protected void setSourceUri ( String sourcePath ) { try { URI sourceUri = toUri ( sourcePath ) ; setSourceUri ( sourceUri ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( "" + sourcePath , e ) ; } } protected void setSourceUri ( URI sourceUri ) { LOG . info ( "" + sourceUri ) ; this . source = driverContext . getRepository ( ) . getDataModelSourceFactory ( sourceUri ) ; } public URI toUri ( String path ) throws URISyntaxException { URI uri = URI . create ( path ) ; if ( uri . getScheme ( ) != null ) { return uri ; } URL url = driverContext . getCallerClass ( ) . getResource ( uri . getPath ( ) ) ; if ( url == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , path , driverContext . getCallerClass ( ) . getName ( ) ) ) ; } URI resourceUri = url . toURI ( ) ; if ( uri . getFragment ( ) == null ) { return resourceUri ; } else { URI resolvedUri = URI . create ( resourceUri . toString ( ) + '' + uri . getFragment ( ) ) ; return resolvedUri ; } } } package com . asakusafw . testdriver ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . FlowDescriptionDriver ; import com . asakusafw . compiler . testing . DirectExporterDescription ; import com . asakusafw . testdriver . core . DataModelSinkFactory ; import com . asakusafw . testdriver . core . DifferenceSinkFactory ; import com . asakusafw . testdriver . core . ModelTester ; import com . asakusafw . testdriver . core . ModelVerifier ; import com . asakusafw . testdriver . core . VerifierFactory ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . Source ; public class FlowPartDriverOutput < T > extends DriverOutputBase < T > implements Out < T > { private static final Logger LOG = LoggerFactory . getLogger ( FlowPartDriverOutput . class ) ; protected FlowDescriptionDriver descDriver ; private final Out < T > out ; public FlowPartDriverOutput ( TestDriverContext driverContext , FlowDescriptionDriver descDriver , String name , Class < T > modelType ) { this . driverContext = driverContext ; this . descDriver = descDriver ; this . name = name ; this . modelType = modelType ; String exportPath = FlowPartDriverUtils . createOutputLocation ( driverContext , name ) . toPath ( '' ) ; LOG . info ( "" + exportPath ) ; exporterDescription = new DirectExporterDescription ( modelType , exportPath ) ; out = descDriver . createOut ( name , exporterDescription ) ; } public FlowPartDriverOutput < T > prepare ( String sourcePath ) { LOG . info ( "" + getModelType ( ) ) ; setSourceUri ( sourcePath ) ; return this ; } public FlowPartDriverOutput < T > verify ( String expectedPath , String verifyRulePath ) { LOG . info ( "" + modelType ) ; try { setVerifier ( expectedPath , verifyRulePath , Collections . < ModelTester < T > > emptyList ( ) ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , expectedPath , verifyRulePath ) , e ) ; } return this ; } public FlowPartDriverOutput < T > verify ( String expectedPath , String verifyRulePath , ModelTester < ? super T > tester ) { LOG . info ( "" + modelType ) ; try { setVerifier ( expectedPath , verifyRulePath , Collections . singletonList ( tester ) ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , expectedPath , verifyRulePath , tester ) , e ) ; } return this ; } public FlowPartDriverOutput < T > verify ( String expectedPath , ModelVerifier < ? super T > modelVerifier ) { LOG . info ( "" + modelType ) ; try { setVerifier ( expectedPath , modelVerifier ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , expectedPath , modelVerifier ) , e ) ; } return this ; } public FlowPartDriverOutput < T > verify ( VerifierFactory factory ) { LOG . info ( "" + modelType ) ; setVerifier ( factory ) ; return this ; } public FlowPartDriverOutput < T > dumpActual ( String outputPath ) { setResultSinkUri ( outputPath ) ; return this ; } public FlowPartDriverOutput < T > dumpActual ( File outputPath ) { setResultSinkUri ( outputPath . toURI ( ) ) ; return this ; } public FlowPartDriverOutput < T > dumpActual ( DataModelSinkFactory factory ) { setResultSink ( factory ) ; return this ; } public FlowPartDriverOutput < T > dumpDifference ( String outputPath ) { setDifferenceSinkUri ( outputPath ) ; return this ; } public FlowPartDriverOutput < T > dumpDifference ( File outputPath ) { setDifferenceSinkUri ( outputPath . toURI ( ) ) ; return this ; } public FlowPartDriverOutput < T > dumpDifference ( DifferenceSinkFactory factory ) { setDifferenceSink ( factory ) ; return this ; } @ Override public void add ( Source < T > upstream ) { out . add ( upstream ) ; } } package com . asakusafw . testdriver ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . FlowDescriptionDriver ; import com . asakusafw . compiler . testing . DirectImporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; public class FlowPartDriverInput < T > extends DriverInputBase < T > implements In < T > { private static final Logger LOG = LoggerFactory . getLogger ( FlowPartDriverInput . class ) ; protected FlowDescriptionDriver descDriver ; private final In < T > in ; public FlowPartDriverInput ( TestDriverContext driverContext , FlowDescriptionDriver descDriver , String name , Class < T > modelType ) { this . driverContext = driverContext ; this . descDriver = descDriver ; this . name = name ; this . modelType = modelType ; String importPath = FlowPartDriverUtils . createInputLocation ( driverContext , name ) . toPath ( '' ) ; LOG . info ( "" + importPath ) ; importerDescription = new DirectImporterDescription ( modelType , importPath ) ; in = descDriver . createIn ( name , importerDescription ) ; } public FlowPartDriverInput < T > prepare ( String sourcePath ) { LOG . info ( "" + getModelType ( ) + "" + sourcePath ) ; setSourceUri ( sourcePath ) ; return this ; } public FlowPartDriverInput < T > withDataSize ( DataSize dataSize ) { if ( ! ( importerDescription instanceof DirectImporterDescription ) ) { throw new UnsupportedOperationException ( "" + importerDescription . getClass ( ) . getName ( ) ) ; } else { ( ( DirectImporterDescription ) importerDescription ) . setDataSize ( dataSize ) ; } return this ; } @ Override public FlowElementOutput toOutputPort ( ) { return in . toOutputPort ( ) ; } } package com . asakusafw . testdriver ; package com . asakusafw . testdriver ; import java . io . Serializable ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . common . Precondition ; public class TestExecutionPlan implements Serializable { private static final long serialVersionUID = - ; private final String definitionId ; private final String executionId ; private final List < Command > initializers ; private final List < Command > importers ; private final List < Job > jobs ; private final List < Command > exporters ; private final List < Command > finalizers ; public TestExecutionPlan ( String definitionId , String executionId , List < Command > initializers , List < Command > importers , List < Job > jobs , List < Command > exporters , List < Command > finalizers ) { Precondition . checkMustNotBeNull ( definitionId , "" ) ; Precondition . checkMustNotBeNull ( executionId , "" ) ; Precondition . checkMustNotBeNull ( initializers , "" ) ; Precondition . checkMustNotBeNull ( importers , "" ) ; Precondition . checkMustNotBeNull ( jobs , "" ) ; Precondition . checkMustNotBeNull ( exporters , "" ) ; Precondition . checkMustNotBeNull ( finalizers , "" ) ; this . definitionId = definitionId ; this . executionId = executionId ; this . initializers = initializers ; this . importers = importers ; this . jobs = jobs ; this . exporters = exporters ; this . finalizers = finalizers ; } public String getDefinitionId ( ) { return definitionId ; } public String getExecutionId ( ) { return executionId ; } public List < Command > getInitializers ( ) { return initializers ; } public List < Command > getImporters ( ) { return importers ; } public List < Job > getJobs ( ) { return jobs ; } public List < Command > getExporters ( ) { return exporters ; } public List < Command > getFinalizers ( ) { return finalizers ; } public static class Job implements Serializable { private static final long serialVersionUID = - ; private final String className ; private final String executionId ; private final Map < String , String > properties ; public Job ( String className , String executionId , Map < String , String > properties ) { Precondition . checkMustNotBeNull ( className , "" ) ; Precondition . checkMustNotBeNull ( executionId , "" ) ; Precondition . checkMustNotBeNull ( properties , "" ) ; this . className = className ; this . executionId = executionId ; this . properties = properties ; } public String getClassName ( ) { return className ; } public String getExecutionId ( ) { return executionId ; } public Map < String , String > getProperties ( ) { return properties ; } } public static class Command implements Serializable { private static final long serialVersionUID = - ; private final List < String > commandLine ; private final String moduleName ; private final String profileName ; private final Map < String , String > environment ; public Command ( List < String > commandLine , String moduleName , String profileName , Map < String , String > environment ) { Precondition . checkMustNotBeNull ( commandLine , "" ) ; Precondition . checkMustNotBeNull ( moduleName , "" ) ; this . commandLine = commandLine ; this . moduleName = moduleName ; this . profileName = profileName ; this . environment = environment ; } public List < String > getCommandTokens ( ) { return commandLine ; } public String getCommandLineString ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : environment . entrySet ( ) ) { buf . append ( "" + entry . getKey ( ) + "" ) ; buf . append ( "" ) ; buf . append ( "" + entry . getValue ( ) + "" ) ; buf . append ( "" ) ; } Iterator < String > iter = commandLine . iterator ( ) ; if ( iter . hasNext ( ) ) { buf . append ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( "" ) ; buf . append ( iter . next ( ) ) ; } } return buf . toString ( ) ; } public String getModuleName ( ) { return moduleName ; } public String getProfileName ( ) { return profileName ; } public Map < String , String > getEnvironment ( ) { return environment ; } } } package com . asakusafw . testdriver ; import java . util . Map ; class HadoopJobInfo { private String jobFlowId ; private String jarName ; private String className ; private Map < String , String > dPropMap ; public HadoopJobInfo ( String jobFlowId , String jarName , String className , Map < String , String > dPropMap ) { this . jobFlowId = jobFlowId ; this . jarName = jarName ; this . className = className ; this . dPropMap = dPropMap ; } public String getJobFlowId ( ) { return jobFlowId ; } public String getJarName ( ) { return jarName ; } public String getClassName ( ) { return className ; } public Map < String , String > getDPropMap ( ) { return dPropMap ; } } package com . asakusafw . testdriver ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Map ; import org . apache . commons . io . FileUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . BatchDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . BatchInfo ; import com . asakusafw . compiler . testing . DirectBatchCompiler ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . testdriver . core . VerifyContext ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . vocabulary . batch . BatchDescription ; public class BatchTester extends TestDriverBase { static final Logger LOG = LoggerFactory . getLogger ( BatchTester . class ) ; private final Map < String , JobFlowTester > jobFlowMap = Maps . create ( ) ; public BatchTester ( Class < ? > callerClass ) { super ( callerClass ) ; } public JobFlowTester jobflow ( String name ) { JobFlowTester driver = jobFlowMap . get ( name ) ; if ( driver == null ) { driver = new JobFlowTester ( driverContext . getCallerClass ( ) ) ; jobFlowMap . put ( name , driver ) ; } return driver ; } public void runTest ( Class < ? extends BatchDescription > batchDescriptionClass ) { try { runTestInternal ( batchDescriptionClass ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } private void runTestInternal ( Class < ? extends BatchDescription > batchDescriptionClass ) throws IOException { LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; LOG . info ( "" , batchDescriptionClass . getName ( ) ) ; BatchDriver batchDriver = BatchDriver . analyze ( batchDescriptionClass ) ; assertFalse ( batchDriver . getDiagnostics ( ) . toString ( ) , batchDriver . hasError ( ) ) ; File compileWorkDir = driverContext . getCompilerWorkingDirectory ( ) ; if ( compileWorkDir . exists ( ) ) { FileUtils . forceDelete ( compileWorkDir ) ; } File compilerOutputDir = new File ( compileWorkDir , "" ) ; File compilerLocalWorkingDir = new File ( compileWorkDir , "" ) ; BatchInfo batchInfo = DirectBatchCompiler . compile ( batchDescriptionClass , "" , Location . fromPath ( driverContext . getClusterWorkDir ( ) , '' ) , compilerOutputDir , compilerLocalWorkingDir , Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( batchDescriptionClass ) } ) , batchDescriptionClass . getClassLoader ( ) , driverContext . getOptions ( ) ) ; for ( String flowId : jobFlowMap . keySet ( ) ) { if ( batchInfo . findJobflow ( flowId ) == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , driverContext . getCallerClass ( ) . getName ( ) , flowId ) ) ; } } LOG . info ( "" , driverContext . getCallerClass ( ) . getName ( ) ) ; JobflowExecutor executor = new JobflowExecutor ( driverContext ) ; executor . cleanWorkingDirectory ( ) ; for ( JobflowInfo jobflowInfo : batchInfo . getJobflows ( ) ) { driverContext . prepareCurrentJobflow ( jobflowInfo ) ; executor . cleanInputOutput ( jobflowInfo ) ; } for ( JobflowInfo jobflowInfo : batchInfo . getJobflows ( ) ) { driverContext . prepareCurrentJobflow ( jobflowInfo ) ; String flowId = jobflowInfo . getJobflow ( ) . getFlowId ( ) ; JobFlowTester tester = jobFlowMap . get ( flowId ) ; if ( tester != null ) { LOG . debug ( "" , batchDescriptionClass . getName ( ) , flowId ) ; executor . prepareInput ( jobflowInfo , tester . inputs ) ; executor . prepareOutput ( jobflowInfo , tester . outputs ) ; LOG . info ( "" , batchDescriptionClass . getName ( ) , flowId ) ; VerifyContext verifyContext = new VerifyContext ( driverContext ) ; executor . runJobflow ( jobflowInfo ) ; verifyContext . testFinished ( ) ; LOG . info ( "" , batchDescriptionClass . getName ( ) , flowId ) ; executor . verify ( jobflowInfo , verifyContext , tester . outputs ) ; } } } } package com . asakusafw . testdriver ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . junit . rules . ExternalResource ; import com . asakusafw . runtime . core . BatchContext ; import com . asakusafw . runtime . flow . RuntimeResourceManager ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . runtime . util . VariableTable . RedefineStrategy ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . utils . collections . Maps ; public class OperatorTestEnvironment extends ExternalResource { private RuntimeResourceManager manager ; private final String configurationPath ; private final Map < String , String > batchArguments ; private final Map < String , String > extraConfigurations ; private boolean dirty ; public OperatorTestEnvironment ( ) { this ( RuntimeResourceManager . CONFIGURATION_FILE_NAME ) ; } public OperatorTestEnvironment ( String configurationPath ) { if ( configurationPath == null ) { throw new IllegalArgumentException ( "" ) ; } this . configurationPath = configurationPath ; this . extraConfigurations = Maps . create ( ) ; this . batchArguments = Maps . create ( ) ; this . dirty = false ; } @ Override protected void before ( ) { Configuration conf = createConfig ( ) ; for ( Map . Entry < String , String > entry : extraConfigurations . entrySet ( ) ) { conf . set ( entry . getKey ( ) , entry . getValue ( ) ) ; } if ( batchArguments . isEmpty ( ) == false ) { VariableTable variables = new VariableTable ( RedefineStrategy . OVERWRITE ) ; for ( Map . Entry < String , String > entry : batchArguments . entrySet ( ) ) { variables . defineVariable ( entry . getKey ( ) , entry . getValue ( ) ) ; } conf . set ( StageConstants . PROP_ASAKUSA_BATCH_ARGS , variables . toSerialString ( ) ) ; } manager = new RuntimeResourceManager ( conf ) ; try { manager . setup ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } public void configure ( String key , String value ) { if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value != null ) { extraConfigurations . put ( key , value ) ; } else { extraConfigurations . remove ( key ) ; } dirty = true ; } public void setBatchArg ( String key , String value ) { if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value != null ) { batchArguments . put ( key , value ) ; } else { batchArguments . remove ( key ) ; } dirty = true ; } public void reload ( ) { dirty = false ; after ( ) ; before ( ) ; } protected Configuration createConfig ( ) { Configuration conf = ConfigurationFactory . getDefault ( ) . newInstance ( ) ; conf . addResource ( configurationPath ) ; return conf ; } @ Override protected void after ( ) { if ( manager != null ) { try { manager . cleanup ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( dirty ) { throw new AssertionError ( "" ) ; } } } package com . asakusafw . testdata . generator ; package com . asakusafw . testdata . generator . excel ; import static com . asakusafw . dmdl . util . CommandLineUtils . * ; import java . io . File ; import java . io . IOException ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . testdata . generator . GenerateTask ; import com . asakusafw . testdata . generator . TemplateGenerator ; public final class Main { static final Logger LOG = LoggerFactory . getLogger ( Main . class ) ; private static final Option OPT_OUTPUT ; private static final Option OPT_FORMAT ; private static final Option OPT_ENCODING ; private static final Option OPT_SOURCE_PATH ; private static final Option OPT_PLUGIN ; private static final Options OPTIONS ; static { OPT_OUTPUT = new Option ( "" , true , "" ) ; OPT_OUTPUT . setArgName ( "" ) ; OPT_OUTPUT . setRequired ( true ) ; OPT_SOURCE_PATH = new Option ( "" , true , "" ) ; OPT_SOURCE_PATH . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_SOURCE_PATH . setRequired ( true ) ; OPT_FORMAT = new Option ( "" , true , "" ) ; OPT_FORMAT . setArgName ( MessageFormat . format ( "" , Arrays . toString ( WorkbookFormat . values ( ) ) ) ) ; OPT_FORMAT . setRequired ( true ) ; OPT_ENCODING = new Option ( "" , true , "" ) ; OPT_ENCODING . setArgName ( "" ) ; OPT_ENCODING . setRequired ( false ) ; OPT_PLUGIN = new Option ( "" , true , "" ) ; OPT_PLUGIN . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN . setValueSeparator ( File . pathSeparatorChar ) ; OPT_PLUGIN . setRequired ( false ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_OUTPUT ) ; OPTIONS . addOption ( OPT_FORMAT ) ; OPTIONS . addOption ( OPT_ENCODING ) ; OPTIONS . addOption ( OPT_SOURCE_PATH ) ; OPTIONS . addOption ( OPT_PLUGIN ) ; } private Main ( ) { return ; } public static void main ( String ... args ) { System . exit ( start ( args ) ) ; } static int start ( String ... args ) { assert args != null ; GenerateTask task ; try { CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; TemplateGenerator generator = getGenerator ( cmd ) ; DmdlSourceRepository repository = getRepository ( cmd ) ; ClassLoader classLoader = getClassLoader ( cmd ) ; task = new GenerateTask ( generator , repository , classLoader ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , Main . class . getName ( ) ) , OPTIONS , true ) ; System . out . printf ( "" , OPT_FORMAT . getOpt ( ) ) ; System . out . printf ( "" , WorkbookFormat . DATA , "" ) ; System . out . printf ( "" , WorkbookFormat . RULE , "" ) ; System . out . printf ( "" , WorkbookFormat . INOUT , "" ) ; System . out . printf ( "" , WorkbookFormat . INSPECT , "" ) ; System . out . printf ( "" , WorkbookFormat . ALL , "" ) ; e . printStackTrace ( System . out ) ; return ; } try { task . process ( ) ; } catch ( IOException e ) { e . printStackTrace ( System . out ) ; return ; } return ; } private static TemplateGenerator getGenerator ( CommandLine cmd ) { assert cmd != null ; String outputCmd = cmd . getOptionValue ( OPT_OUTPUT . getOpt ( ) ) ; String formatCmd = cmd . getOptionValue ( OPT_FORMAT . getOpt ( ) ) ; File output = new File ( outputCmd ) ; WorkbookFormat format = WorkbookFormat . findByName ( formatCmd ) ; if ( format == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , OPT_FORMAT . getOpt ( ) , formatCmd , Arrays . toString ( WorkbookFormat . values ( ) ) ) ) ; } return new WorkbookGenerator ( output , format ) ; } private static DmdlSourceRepository getRepository ( CommandLine cmd ) { assert cmd != null ; Charset encoding = parseCharset ( cmd . getOptionValue ( OPT_ENCODING . getOpt ( ) ) ) ; String sourceCmd = cmd . getOptionValue ( OPT_SOURCE_PATH . getOpt ( ) ) ; DmdlSourceRepository source = buildRepository ( parseFileList ( sourceCmd ) , encoding ) ; return source ; } private static ClassLoader getClassLoader ( CommandLine cmd ) { assert cmd != null ; String pluginCmd = cmd . getOptionValue ( OPT_PLUGIN . getOpt ( ) ) ; List < File > plugins = parseFileList ( pluginCmd ) ; ClassLoader serviceLoader = buildPluginLoader ( Main . class . getClassLoader ( ) , plugins ) ; return serviceLoader ; } } package com . asakusafw . testdata . generator . excel ; import static com . asakusafw . testdata . generator . excel . SheetFormat . * ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; public enum WorkbookFormat { DATA ( "" , data ( "" ) ) , RULE ( "" , rule ( "" ) ) , INOUT ( "" , data ( "" ) , data ( "" ) ) , INSPECT ( "" , data ( "" ) , rule ( "" ) ) , ALL ( "" , data ( "" ) , data ( "" ) , rule ( "" ) ) , ; private final String namePattern ; private final List < SheetFormat > sheets ; private WorkbookFormat ( String namePattern , SheetFormat ... sheets ) { assert namePattern != null ; assert sheets != null ; this . namePattern = namePattern ; List < SheetFormat > results = new ArrayList < SheetFormat > ( sheets . length ) ; Collections . addAll ( results , sheets ) ; this . sheets = Collections . unmodifiableList ( results ) ; } public List < SheetFormat > getSheets ( ) { return sheets ; } public String getFileName ( ModelDeclaration model ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } return MessageFormat . format ( namePattern , model . getName ( ) . identifier ) ; } public static WorkbookFormat findByName ( String format ) { if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } for ( WorkbookFormat item : values ( ) ) { if ( item . name ( ) . equalsIgnoreCase ( format ) ) { return item ; } } return null ; } } package com . asakusafw . testdata . generator . excel ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . text . MessageFormat ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . testdata . generator . TemplateGenerator ; public class WorkbookGenerator implements TemplateGenerator { static final Logger LOG = LoggerFactory . getLogger ( WorkbookGenerator . class ) ; private final File output ; private final WorkbookFormat format ; public WorkbookGenerator ( File output , WorkbookFormat format ) { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } this . output = output ; this . format = format ; } @ Override public void generate ( ModelDeclaration model ) throws IOException { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output . isDirectory ( ) == false && output . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , output ) ) ; } HSSFWorkbook workbook = new HSSFWorkbook ( ) ; SheetBuilder builder = new SheetBuilder ( workbook , model ) ; for ( SheetFormat sheet : format . getSheets ( ) ) { switch ( sheet . getKind ( ) ) { case DATA : LOG . debug ( "" , model . getName ( ) , sheet . getName ( ) ) ; builder . addData ( sheet . getName ( ) ) ; break ; case RULE : LOG . debug ( "" , model . getName ( ) , sheet . getName ( ) ) ; builder . addRule ( sheet . getName ( ) ) ; break ; default : throw new AssertionError ( MessageFormat . format ( "" , sheet ) ) ; } } File file = new File ( output , format . getFileName ( model ) ) ; LOG . debug ( "" , file ) ; OutputStream out = new FileOutputStream ( file ) ; try { workbook . write ( out ) ; } finally { out . close ( ) ; } } @ Override public String getTitle ( ) { return MessageFormat . format ( "" , format ) ; } } package com . asakusafw . testdata . generator . excel ; public final class SheetFormat { private final Kind kind ; private final String name ; private SheetFormat ( Kind kind , String name ) { assert kind != null ; assert name != null ; this . kind = kind ; this . name = name ; } public static SheetFormat data ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return new SheetFormat ( Kind . DATA , name ) ; } public static SheetFormat rule ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return new SheetFormat ( Kind . RULE , name ) ; } public SheetFormat . Kind getKind ( ) { return kind ; } public String getName ( ) { return name ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( kind ) ; builder . append ( "" ) ; builder . append ( name ) ; builder . append ( "" ) ; return builder . toString ( ) ; } public enum Kind { DATA , RULE , } } package com . asakusafw . testdata . generator . excel ; import org . apache . poi . hssf . usermodel . HSSFCellStyle ; import org . apache . poi . hssf . usermodel . HSSFFont ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . CellStyle ; import org . apache . poi . ss . usermodel . CreationHelper ; import org . apache . poi . ss . usermodel . DataFormat ; import org . apache . poi . ss . usermodel . IndexedColors ; public class WorkbookInfo { final HSSFWorkbook workbook ; private final HSSFCellStyle commonStyle ; final HSSFCellStyle titleStyle ; final HSSFCellStyle lockedStyle ; final HSSFCellStyle optionsStyle ; final HSSFCellStyle dataStyle ; final HSSFCellStyle dateDataStyle ; final HSSFCellStyle timeDataStyle ; final HSSFCellStyle datetimeDataStyle ; public WorkbookInfo ( HSSFWorkbook workbook ) { if ( workbook == null ) { throw new IllegalArgumentException ( "" ) ; } this . workbook = workbook ; HSSFFont font = workbook . createFont ( ) ; commonStyle = workbook . createCellStyle ( ) ; commonStyle . setFont ( font ) ; commonStyle . setBorderTop ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderBottom ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderLeft ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderRight ( CellStyle . BORDER_THIN ) ; titleStyle = workbook . createCellStyle ( ) ; titleStyle . cloneStyleFrom ( commonStyle ) ; titleStyle . setLocked ( true ) ; titleStyle . setFillPattern ( CellStyle . SOLID_FOREGROUND ) ; titleStyle . setFillForegroundColor ( IndexedColors . LIGHT_GREEN . getIndex ( ) ) ; titleStyle . setAlignment ( CellStyle . ALIGN_CENTER ) ; lockedStyle = workbook . createCellStyle ( ) ; lockedStyle . cloneStyleFrom ( commonStyle ) ; lockedStyle . setLocked ( true ) ; lockedStyle . setFillPattern ( CellStyle . SOLID_FOREGROUND ) ; lockedStyle . setFillForegroundColor ( IndexedColors . LEMON_CHIFFON . getIndex ( ) ) ; lockedStyle . setAlignment ( CellStyle . ALIGN_CENTER ) ; optionsStyle = workbook . createCellStyle ( ) ; optionsStyle . cloneStyleFrom ( commonStyle ) ; optionsStyle . setFillPattern ( CellStyle . SOLID_FOREGROUND ) ; optionsStyle . setFillForegroundColor ( IndexedColors . WHITE . getIndex ( ) ) ; CreationHelper helper = workbook . getCreationHelper ( ) ; DataFormat df = helper . createDataFormat ( ) ; dataStyle = workbook . createCellStyle ( ) ; dataStyle . cloneStyleFrom ( commonStyle ) ; dateDataStyle = workbook . createCellStyle ( ) ; dateDataStyle . cloneStyleFrom ( commonStyle ) ; dateDataStyle . setDataFormat ( df . getFormat ( "" ) ) ; timeDataStyle = workbook . createCellStyle ( ) ; timeDataStyle . cloneStyleFrom ( commonStyle ) ; timeDataStyle . setDataFormat ( df . getFormat ( "" ) ) ; datetimeDataStyle = workbook . createCellStyle ( ) ; datetimeDataStyle . cloneStyleFrom ( commonStyle ) ; datetimeDataStyle . setDataFormat ( df . getFormat ( "" ) ) ; } } package com . asakusafw . testdata . generator . excel ; package com . asakusafw . testdata . generator . excel ; import org . apache . poi . hssf . usermodel . DVConstraint ; import org . apache . poi . hssf . usermodel . HSSFCell ; import org . apache . poi . hssf . usermodel . HSSFDataValidation ; import org . apache . poi . hssf . usermodel . HSSFRow ; import org . apache . poi . hssf . usermodel . HSSFSheet ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . Row ; import org . apache . poi . ss . util . CellRangeAddressList ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . testdriver . excel . NullityConditionKind ; import com . asakusafw . testdriver . excel . RuleSheetFormat ; import com . asakusafw . testdriver . excel . TotalConditionKind ; import com . asakusafw . testdriver . excel . ValueConditionKind ; public class SheetBuilder { static final Logger LOG = LoggerFactory . getLogger ( SheetBuilder . class ) ; private static final int MINIMUM_COLUMN_WIDTH = ; private static final int MAX_COLUMN_INDEX = ; private final WorkbookInfo info ; private final ModelDeclaration model ; private String sawDataSheet ; private String sawRuleSheet ; public SheetBuilder ( HSSFWorkbook workbook , ModelDeclaration model ) { if ( workbook == null ) { throw new IllegalArgumentException ( "" ) ; } if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } this . info = new WorkbookInfo ( workbook ) ; this . model = model ; } public void addData ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sawDataSheet != null ) { copy ( sawDataSheet , name ) ; return ; } HSSFSheet sheet = info . workbook . createSheet ( name ) ; HSSFRow titleRow = sheet . createRow ( ) ; HSSFRow valueRow = sheet . createRow ( ) ; int index = ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( index > MAX_COLUMN_INDEX ) { LOG . warn ( "" , MAX_COLUMN_INDEX , model . getName ( ) ) ; break ; } HSSFCell title = titleRow . createCell ( index ) ; title . setCellStyle ( info . titleStyle ) ; title . setCellValue ( property . getName ( ) . identifier ) ; HSSFCell value = valueRow . createCell ( index ) ; value . setCellStyle ( info . dataStyle ) ; if ( property . getType ( ) instanceof BasicType ) { BasicType type = ( BasicType ) property . getType ( ) ; switch ( type . getKind ( ) ) { case DATE : value . setCellStyle ( info . dateDataStyle ) ; break ; case DATETIME : value . setCellStyle ( info . datetimeDataStyle ) ; break ; default : break ; } } index ++ ; } adjustDataWidth ( sheet ) ; sawDataSheet = name ; } private void adjustDataWidth ( HSSFSheet sheet ) { assert sheet != null ; int lastColumn = sheet . getRow ( ) . getLastCellNum ( ) ; adjustColumnWidth ( sheet , lastColumn ) ; } public void addRule ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sawRuleSheet != null ) { copy ( sawRuleSheet , name ) ; return ; } HSSFSheet sheet = info . workbook . createSheet ( name ) ; fillRuleTitles ( sheet ) ; fillRuleFormat ( sheet ) ; fillRuleTotalCondition ( sheet ) ; fillRulePropertyConditions ( sheet ) ; adjustRuleWidth ( sheet ) ; sawRuleSheet = name ; } private void fillRuleTitles ( HSSFSheet sheet ) { assert sheet != null ; for ( RuleSheetFormat title : RuleSheetFormat . values ( ) ) { setTitle ( sheet , title ) ; } } private void fillRuleFormat ( HSSFSheet sheet ) { assert sheet != null ; HSSFCell value = getCell ( sheet , RuleSheetFormat . FORMAT , , ) ; value . setCellStyle ( info . lockedStyle ) ; value . setCellValue ( RuleSheetFormat . FORMAT_VERSION ) ; } private void fillRuleTotalCondition ( HSSFSheet sheet ) { assert sheet != null ; HSSFCell value = getCell ( sheet , RuleSheetFormat . TOTAL_CONDITION , , ) ; value . setCellStyle ( info . optionsStyle ) ; String [ ] options = TotalConditionKind . getOptions ( ) ; value . setCellValue ( options [ ] ) ; setExplicitListConstraint ( sheet , options , value . getRowIndex ( ) , value . getColumnIndex ( ) , value . getRowIndex ( ) , value . getColumnIndex ( ) ) ; } private void setTitle ( HSSFSheet sheet , RuleSheetFormat item ) { assert sheet != null ; assert item != null ; HSSFCell cell = getCell ( sheet , item . getRowIndex ( ) , item . getColumnIndex ( ) ) ; cell . setCellStyle ( info . titleStyle ) ; cell . setCellValue ( item . getTitle ( ) ) ; } private void fillRulePropertyConditions ( HSSFSheet sheet ) { int index = ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { HSSFCell name = getCell ( sheet , RuleSheetFormat . PROPERTY_NAME , index , ) ; name . setCellStyle ( info . lockedStyle ) ; name . setCellValue ( property . getName ( ) . identifier ) ; HSSFCell value = getCell ( sheet , RuleSheetFormat . VALUE_CONDITION , index , ) ; value . setCellStyle ( info . optionsStyle ) ; if ( index == ) { value . setCellValue ( ValueConditionKind . KEY . getText ( ) ) ; } else { value . setCellValue ( ValueConditionKind . ANY . getText ( ) ) ; } HSSFCell nullity = getCell ( sheet , RuleSheetFormat . NULLITY_CONDITION , index , ) ; nullity . setCellStyle ( info . optionsStyle ) ; nullity . setCellValue ( NullityConditionKind . NORMAL . getText ( ) ) ; HSSFCell comments = getCell ( sheet , RuleSheetFormat . COMMENTS , index , ) ; comments . setCellStyle ( info . dataStyle ) ; comments . setCellValue ( property . getDescription ( ) == null ? property . getType ( ) . toString ( ) : property . getDescription ( ) . getText ( ) ) ; index ++ ; } int start = RuleSheetFormat . PROPERTY_NAME . getRowIndex ( ) + ; int end = RuleSheetFormat . PROPERTY_NAME . getRowIndex ( ) + index ; setExplicitListConstraint ( sheet , ValueConditionKind . getOptions ( ) , start , RuleSheetFormat . VALUE_CONDITION . getColumnIndex ( ) , end , RuleSheetFormat . VALUE_CONDITION . getColumnIndex ( ) ) ; setExplicitListConstraint ( sheet , NullityConditionKind . getOptions ( ) , start , RuleSheetFormat . NULLITY_CONDITION . getColumnIndex ( ) , end , RuleSheetFormat . NULLITY_CONDITION . getColumnIndex ( ) ) ; } private void adjustRuleWidth ( HSSFSheet sheet ) { assert sheet != null ; int lastColumn = ; for ( RuleSheetFormat format : RuleSheetFormat . values ( ) ) { lastColumn = Math . max ( lastColumn , format . getColumnIndex ( ) ) ; } adjustColumnWidth ( sheet , lastColumn ) ; } private void adjustColumnWidth ( HSSFSheet sheet , int lastColumn ) { assert sheet != null ; for ( int i = ; i <= lastColumn ; i ++ ) { sheet . autoSizeColumn ( i ) ; int width = sheet . getColumnWidth ( i ) ; if ( width < MINIMUM_COLUMN_WIDTH ) { sheet . setColumnWidth ( i , MINIMUM_COLUMN_WIDTH ) ; } } } private HSSFCell getCell ( HSSFSheet sheet , RuleSheetFormat item , int rowOffset , int columnOffset ) { assert sheet != null ; assert item != null ; return getCell ( sheet , item . getRowIndex ( ) + rowOffset , item . getColumnIndex ( ) + columnOffset ) ; } private HSSFCell getCell ( HSSFSheet sheet , int rowIndex , int columnIndex ) { assert sheet != null ; HSSFRow row = sheet . getRow ( rowIndex ) ; if ( row == null ) { row = sheet . createRow ( rowIndex ) ; } HSSFCell cell = row . getCell ( columnIndex , Row . CREATE_NULL_AS_BLANK ) ; return cell ; } private void copy ( String oldName , String newName ) { if ( oldName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( newName == null ) { throw new IllegalArgumentException ( "" ) ; } HSSFWorkbook workbook = info . workbook ; int oldIndex = workbook . getSheetIndex ( oldName ) ; if ( oldIndex < ) { throw new IllegalArgumentException ( ) ; } HSSFSheet newSheet = workbook . cloneSheet ( oldIndex ) ; int newIndex = workbook . getSheetIndex ( newSheet ) ; workbook . setSheetName ( newIndex , newName ) ; } private void setExplicitListConstraint ( HSSFSheet sheet , String [ ] list , int firstRow , int firstCol , int lastRow , int lastCol ) { assert sheet != null ; assert list != null ; CellRangeAddressList addressList = new CellRangeAddressList ( firstRow , lastRow , firstCol , lastCol ) ; DVConstraint constraint = DVConstraint . createExplicitListConstraint ( list ) ; HSSFDataValidation validation = new HSSFDataValidation ( addressList , constraint ) ; validation . setEmptyCellAllowed ( true ) ; validation . setSuppressDropDownArrow ( false ) ; sheet . addValidationData ( validation ) ; } } package com . asakusafw . testdata . generator ; import java . io . IOException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . dmdl . util . AnalyzeTask ; public class GenerateTask { static final Logger LOG = LoggerFactory . getLogger ( GenerateTask . class ) ; private final TemplateGenerator generator ; private final DmdlSourceRepository repository ; private final ClassLoader serviceClassLoader ; public GenerateTask ( TemplateGenerator generator , DmdlSourceRepository repository , ClassLoader serviceClassLoader ) { if ( generator == null ) { throw new IllegalArgumentException ( "" ) ; } if ( repository == null ) { throw new IllegalArgumentException ( "" ) ; } if ( serviceClassLoader == null ) { throw new IllegalArgumentException ( "" ) ; } this . generator = generator ; this . repository = repository ; this . serviceClassLoader = serviceClassLoader ; } public void process ( ) throws IOException { DmdlSemantics semantics = analyze ( ) ; for ( ModelDeclaration model : semantics . getDeclaredModels ( ) ) { LOG . info ( "" , model . getName ( ) . identifier ) ; generator . generate ( model ) ; } } private DmdlSemantics analyze ( ) throws IOException { AnalyzeTask analyzer = new AnalyzeTask ( generator . getTitle ( ) , serviceClassLoader ) ; return analyzer . process ( repository ) ; } } package com . asakusafw . testdata . generator ; import java . io . IOException ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; public interface TemplateGenerator { void generate ( ModelDeclaration model ) throws IOException ; String getTitle ( ) ; } package com . asakusafw . testdata . generator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . URL ; import java . nio . charset . Charset ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . dmdl . source . DmdlSourceResource ; public class GenerateTaskTest { @ Test public void process ( ) throws Exception { Mock mock = new Mock ( ) ; DmdlSourceRepository repo = repo ( "" ) ; GenerateTask task = new GenerateTask ( mock , repo , getClass ( ) . getClassLoader ( ) ) ; task . process ( ) ; assertThat ( mock . saw . size ( ) , is ( ) ) ; assertThat ( mock . saw , hasItem ( "" ) ) ; assertThat ( mock . saw , hasItem ( "" ) ) ; assertThat ( mock . saw , hasItem ( "" ) ) ; assertThat ( mock . saw , hasItem ( "" ) ) ; } private DmdlSourceRepository repo ( String ... files ) { List < URL > resources = new ArrayList < URL > ( ) ; for ( String s : files ) { URL r = getClass ( ) . getResource ( s ) ; assertThat ( s , r , not ( nullValue ( ) ) ) ; resources . add ( r ) ; } return new DmdlSourceResource ( resources , Charset . forName ( "" ) ) ; } static class Mock implements TemplateGenerator { final Set < String > saw = new HashSet < String > ( ) ; @ Override public void generate ( ModelDeclaration model ) throws IOException { saw . add ( model . getName ( ) . identifier ) ; } @ Override public String getTitle ( ) { return getClass ( ) . getName ( ) ; } } } package com . asakusafw . testdata . generator . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . URL ; import java . nio . charset . Charset ; import java . util . Arrays ; import org . apache . poi . hssf . usermodel . HSSFCell ; import org . apache . poi . hssf . usermodel . HSSFRow ; import org . apache . poi . hssf . usermodel . HSSFSheet ; import org . apache . poi . ss . usermodel . Cell ; import org . junit . Rule ; import org . junit . rules . TemporaryFolder ; import org . junit . rules . TestName ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . source . DmdlSourceResource ; import com . asakusafw . dmdl . util . AnalyzeTask ; import com . asakusafw . testdriver . excel . RuleSheetFormat ; public class ExcelTesterRoot { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Rule public TestName testName = new TestName ( ) ; protected ModelDeclaration load ( String dmdl , String model ) { URL resource = getClass ( ) . getResource ( dmdl ) ; assertThat ( dmdl , resource , not ( nullValue ( ) ) ) ; DmdlSourceResource repo = new DmdlSourceResource ( Arrays . asList ( resource ) , Charset . forName ( "" ) ) ; ClassLoader loader = ExcelTesterRoot . class . getClassLoader ( ) ; AnalyzeTask task = new AnalyzeTask ( testName . getMethodName ( ) , loader ) ; try { DmdlSemantics results = task . process ( repo ) ; ModelDeclaration decl = results . findModelDeclaration ( model ) ; assertThat ( dmdl + "" + model , decl , not ( nullValue ( ) ) ) ; return decl ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } protected void checkDataSheet ( HSSFSheet sheet , ModelDeclaration model ) { int index = ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { assertThat ( cell ( sheet , , index ++ ) , is ( property . getName ( ) . identifier ) ) ; } } protected void checkRuleSheet ( HSSFSheet sheet , ModelDeclaration model ) { assertThat ( sheet , not ( nullValue ( ) ) ) ; for ( RuleSheetFormat format : RuleSheetFormat . values ( ) ) { assertThat ( format . name ( ) , cell ( sheet , format , , ) , is ( format . getTitle ( ) ) ) ; } assertThat ( cell ( sheet , RuleSheetFormat . FORMAT , , ) , is ( RuleSheetFormat . FORMAT_VERSION ) ) ; assertThat ( cell ( sheet , RuleSheetFormat . TOTAL_CONDITION , , ) , not ( nullValue ( ) ) ) ; int index = ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { assertThat ( cell ( sheet , RuleSheetFormat . PROPERTY_NAME , index + , ) , is ( property . getName ( ) . identifier ) ) ; assertThat ( cell ( sheet , RuleSheetFormat . VALUE_CONDITION , index + , ) , not ( nullValue ( ) ) ) ; assertThat ( cell ( sheet , RuleSheetFormat . NULLITY_CONDITION , index + , ) , not ( nullValue ( ) ) ) ; index ++ ; } } protected String cell ( HSSFSheet sheet , RuleSheetFormat format , int rowOffset , int colOffset ) { return cell ( sheet , format . getRowIndex ( ) + rowOffset , format . getColumnIndex ( ) + colOffset ) ; } protected String cell ( HSSFSheet sheet , int rowIndex , int columnIndex ) { HSSFRow row = sheet . getRow ( rowIndex ) ; assertThat ( row , not ( nullValue ( ) ) ) ; HSSFCell cell = row . getCell ( columnIndex ) ; if ( cell == null || cell . getCellType ( ) == Cell . CELL_TYPE_BLANK ) { return null ; } assertThat ( cell . getCellType ( ) , is ( Cell . CELL_TYPE_STRING ) ) ; return cell . getStringCellValue ( ) ; } } package com . asakusafw . testdata . generator . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . poi . hssf . usermodel . HSSFSheet ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . junit . Test ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . testdriver . excel . RuleSheetFormat ; public class SheetBuilderTest extends ExcelTesterRoot { @ Test public void data_simple ( ) { HSSFWorkbook workbook = new HSSFWorkbook ( ) ; ModelDeclaration model = load ( "" , "" ) ; SheetBuilder builder = new SheetBuilder ( workbook , model ) ; builder . addData ( "" ) ; HSSFSheet sheet = workbook . getSheet ( "" ) ; assertThat ( sheet , not ( nullValue ( ) ) ) ; assertThat ( cell ( sheet , , ) , is ( "" ) ) ; } @ Test public void data_copy ( ) { HSSFWorkbook workbook = new HSSFWorkbook ( ) ; ModelDeclaration model = load ( "" , "" ) ; SheetBuilder builder = new SheetBuilder ( workbook , model ) ; builder . addData ( "" ) ; builder . addData ( "" ) ; HSSFSheet sheet = workbook . getSheet ( "" ) ; assertThat ( sheet , not ( nullValue ( ) ) ) ; assertThat ( cell ( sheet , , ) , is ( "" ) ) ; } @ Test public void data_primitives ( ) { HSSFWorkbook workbook = new HSSFWorkbook ( ) ; ModelDeclaration model = load ( "" , "" ) ; SheetBuilder builder = new SheetBuilder ( workbook , model ) ; builder . addData ( "" ) ; HSSFSheet sheet = workbook . getSheet ( "" ) ; assertThat ( sheet , not ( nullValue ( ) ) ) ; checkDataSheet ( sheet , model ) ; } @ Test public void rule ( ) { HSSFWorkbook workbook = new HSSFWorkbook ( ) ; ModelDeclaration model = load ( "" , "" ) ; SheetBuilder builder = new SheetBuilder ( workbook , model ) ; builder . addRule ( "" ) ; HSSFSheet sheet = workbook . getSheet ( "" ) ; checkRuleSheet ( sheet , model ) ; } @ Test public void rule_copy ( ) { HSSFWorkbook workbook = new HSSFWorkbook ( ) ; ModelDeclaration model = load ( "" , "" ) ; SheetBuilder builder = new SheetBuilder ( workbook , model ) ; builder . addRule ( "" ) ; builder . addRule ( "" ) ; HSSFSheet sheet = workbook . getSheet ( "" ) ; assertThat ( sheet , not ( nullValue ( ) ) ) ; for ( RuleSheetFormat format : RuleSheetFormat . values ( ) ) { assertThat ( format . name ( ) , cell ( sheet , format , , ) , is ( format . getTitle ( ) ) ) ; } } } package com . asakusafw . testdata . generator . excel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . junit . Test ; public class MainTest extends ExcelTesterRoot { @ Test public void simple ( ) throws Exception { File output = folder . newFolder ( "" ) ; File source = folder . newFolder ( "" ) ; deploy ( "" , source ) ; List < String > args = new ArrayList < String > ( ) ; Collections . addAll ( args , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , source . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , WorkbookFormat . DATA . name ( ) ) ; int exit = Main . start ( args . toArray ( new String [ args . size ( ) ] ) ) ; assertThat ( exit , is ( ) ) ; HSSFWorkbook book = open ( output , "" ) ; assertThat ( cell ( book . getSheetAt ( ) , , ) , is ( "" ) ) ; } @ Test public void less ( ) { List < String > args = new ArrayList < String > ( ) ; Collections . addAll ( args ) ; int exit = Main . start ( args . toArray ( new String [ args . size ( ) ] ) ) ; assertThat ( exit , not ( ) ) ; } @ Test public void invalid_dmdl ( ) throws Exception { File output = folder . newFolder ( "" ) ; File source = folder . newFolder ( "" ) ; deploy ( "" , source ) ; List < String > args = new ArrayList < String > ( ) ; Collections . addAll ( args , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , source . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , WorkbookFormat . DATA . name ( ) ) ; int exit = Main . start ( args . toArray ( new String [ args . size ( ) ] ) ) ; assertThat ( exit , is ( ) ) ; } @ Test public void invalid_output ( ) throws Exception { File output = folder . newFile ( "" ) ; File source = folder . newFolder ( "" ) ; deploy ( "" , source ) ; List < String > args = new ArrayList < String > ( ) ; Collections . addAll ( args , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , source . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , WorkbookFormat . DATA . name ( ) ) ; int exit = Main . start ( args . toArray ( new String [ args . size ( ) ] ) ) ; assertThat ( exit , is ( ) ) ; } @ Test public void invalid_source ( ) throws Exception { File output = folder . newFolder ( "" ) ; List < String > args = new ArrayList < String > ( ) ; Collections . addAll ( args , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , "" ) ; Collections . addAll ( args , "" , WorkbookFormat . DATA . name ( ) ) ; int exit = Main . start ( args . toArray ( new String [ args . size ( ) ] ) ) ; assertThat ( exit , is ( ) ) ; } @ Test public void invalid_format ( ) throws Exception { File output = folder . newFolder ( "" ) ; File source = folder . newFolder ( "" ) ; deploy ( "" , source ) ; List < String > args = new ArrayList < String > ( ) ; Collections . addAll ( args , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , source . getAbsolutePath ( ) ) ; Collections . addAll ( args , "" , "" ) ; int exit = Main . start ( args . toArray ( new String [ args . size ( ) ] ) ) ; assertThat ( exit , is ( ) ) ; } private void deploy ( String name , File target ) throws IOException { InputStream in = getClass ( ) . getResourceAsStream ( name ) ; assertThat ( name , in , not ( nullValue ( ) ) ) ; try { OutputStream out = new FileOutputStream ( new File ( target , name ) ) ; try { byte [ ] buf = new byte [ ] ; while ( true ) { int read = in . read ( buf ) ; if ( read < ) { break ; } out . write ( buf , , read ) ; } } finally { out . close ( ) ; } } finally { in . close ( ) ; } } private HSSFWorkbook open ( File dir , String prefix ) throws IOException { File file = null ; for ( File f : dir . listFiles ( ) ) { if ( f . isFile ( ) && f . getName ( ) . startsWith ( prefix ) ) { file = f ; break ; } } assertThat ( prefix , file , not ( nullValue ( ) ) ) ; InputStream in = new FileInputStream ( file ) ; try { return new HSSFWorkbook ( in ) ; } finally { in . close ( ) ; } } } package com . asakusafw . testdata . generator . excel ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import org . apache . poi . hssf . usermodel . HSSFSheet ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . junit . Test ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . testdata . generator . excel . SheetFormat . Kind ; public class WorkbookGeneratorTest extends ExcelTesterRoot { @ Test public void data ( ) throws Exception { ModelDeclaration model = load ( "" , "" ) ; WorkbookGenerator generator = new WorkbookGenerator ( folder . getRoot ( ) , WorkbookFormat . DATA ) ; generator . generate ( model ) ; HSSFWorkbook workbook = open ( folder . getRoot ( ) , model , WorkbookFormat . DATA ) ; HSSFSheet sheet = workbook . getSheet ( WorkbookFormat . DATA . getSheets ( ) . get ( ) . getName ( ) ) ; checkDataSheet ( sheet , model ) ; } @ Test public void rule ( ) throws Exception { ModelDeclaration model = load ( "" , "" ) ; WorkbookGenerator generator = new WorkbookGenerator ( folder . getRoot ( ) , WorkbookFormat . RULE ) ; generator . generate ( model ) ; HSSFWorkbook workbook = open ( folder . getRoot ( ) , model , WorkbookFormat . RULE ) ; HSSFSheet sheet = workbook . getSheet ( WorkbookFormat . RULE . getSheets ( ) . get ( ) . getName ( ) ) ; checkRuleSheet ( sheet , model ) ; } @ Test public void all_formats ( ) throws Exception { ModelDeclaration model = load ( "" , "" ) ; for ( WorkbookFormat format : WorkbookFormat . values ( ) ) { File dir = folder . newFolder ( format . name ( ) ) ; WorkbookGenerator generator = new WorkbookGenerator ( dir , format ) ; generator . generate ( model ) ; HSSFWorkbook workbook = open ( dir , model , format ) ; for ( SheetFormat sheetForm : format . getSheets ( ) ) { HSSFSheet sheet = workbook . getSheet ( sheetForm . getName ( ) ) ; if ( sheetForm . getKind ( ) == Kind . DATA ) { checkDataSheet ( sheet , model ) ; } else { checkRuleSheet ( sheet , model ) ; } } } } @ Test ( expected = IOException . class ) public void invalid_output ( ) throws Exception { ModelDeclaration model = load ( "" , "" ) ; WorkbookGenerator generator = new WorkbookGenerator ( folder . newFile ( "" ) , WorkbookFormat . DATA ) ; generator . generate ( model ) ; } private HSSFWorkbook open ( File dir , ModelDeclaration model , WorkbookFormat format ) throws IOException { File file = new File ( dir , format . getFileName ( model ) ) ; InputStream in = new FileInputStream ( file ) ; try { return new HSSFWorkbook ( in ) ; } finally { in . close ( ) ; } } } package com . asakusafw . directio . tools ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import org . junit . Test ; public class DirectIoAbortTransactionTest extends DirectIoCommandTestRoot { @ Test public void run ( ) throws Exception { Tool exec = new DirectIoAbortTransaction ( repo ) ; indoubt ( "" ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" } ) , is ( ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" } ) , is ( ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" } ) , is ( ) ) ; } @ Test public void run_invalid ( ) throws Exception { Tool exec = new DirectIoAbortTransaction ( repo ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { } ) , is ( not ( ) ) ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" , "" } ) , is ( not ( ) ) ) ; } } package com . asakusafw . directio . tools ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import org . junit . Test ; public class DirectIoApplyTransactionTest extends DirectIoCommandTestRoot { @ Test public void run ( ) throws Exception { Tool exec = new DirectIoApplyTransaction ( repo ) ; indoubt ( "" ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" } ) , is ( ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" } ) , is ( ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" } ) , is ( ) ) ; } @ Test public void run_failure ( ) throws Exception { Tool exec = new DirectIoApplyTransaction ( repo ) ; indoubt ( "" ) ; writable ( production1 , false ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" } ) , is ( not ( ) ) ) ; } @ Test public void run_invalid ( ) throws Exception { Tool exec = new DirectIoApplyTransaction ( repo ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { } ) , is ( not ( ) ) ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" , "" } ) , is ( not ( ) ) ) ; } } package com . asakusafw . directio . tools ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . util . Arrays ; import java . util . Scanner ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . junit . After ; import org . junit . Assume ; import org . junit . Before ; import org . junit . Rule ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceProvider ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . OutputTransactionContext ; import com . asakusafw . runtime . directio . hadoop . DirectIoTransactionEditor ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceCore ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceProfile ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class DirectIoCommandTestRoot { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; protected Configuration conf ; protected DirectIoTransactionEditor editor ; protected DirectDataSourceRepository repo ; protected File production1 ; protected File production2 ; private File temporary ; @ Before public void setUp ( ) throws Exception { File writeTest = folder . newFolder ( "" ) ; Assume . assumeTrue ( writable ( writeTest , false ) ) ; try { new File ( writeTest , "" ) . createNewFile ( ) ; Assume . assumeTrue ( false ) ; } catch ( IOException e ) { } this . conf = new Configuration ( ) ; conf . set ( HadoopDataSourceUtil . KEY_SYSTEM_DIR , folder . newFolder ( "" ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; temporary = folder . newFolder ( "" ) . getCanonicalFile ( ) ; production1 = folder . newFolder ( "" ) . getCanonicalFile ( ) ; production2 = folder . newFolder ( "" ) . getCanonicalFile ( ) ; HadoopDataSourceProfile profile1 = new HadoopDataSourceProfile ( conf , "" , "" , new Path ( production1 . toURI ( ) ) , new Path ( new File ( temporary , "" ) . toURI ( ) ) ) ; HadoopDataSourceProfile profile2 = new HadoopDataSourceProfile ( conf , "" , "" , new Path ( production2 . toURI ( ) ) , new Path ( new File ( temporary , "" ) . toURI ( ) ) ) ; repo = new DirectDataSourceRepository ( Arrays . asList ( new MockProvider ( profile1 ) , new MockProvider ( profile2 ) ) ) ; editor = new DirectIoTransactionEditor ( repo ) ; editor . setConf ( conf ) ; } @ After public void tearDown ( ) throws Exception { if ( production1 != null ) { writable ( production1 , true ) ; } if ( production2 != null ) { writable ( production2 , true ) ; } if ( temporary != null ) { writable ( temporary , true ) ; } } protected boolean writable ( File target , boolean writable ) { if ( target . exists ( ) == false ) { return false ; } boolean succeed = true ; if ( target . isDirectory ( ) ) { for ( File child : target . listFiles ( ) ) { succeed &= writable ( child , writable ) ; } } return succeed && target . setWritable ( writable ) ; } protected int count ( File dir ) { int count = ; for ( File file : dir . listFiles ( ) ) { if ( file . getName ( ) . startsWith ( "" ) == false ) { count ++ ; } } return count ; } protected void indoubt ( String executionId ) throws IOException , InterruptedException { Path txPath = HadoopDataSourceUtil . getTransactionInfoPath ( conf , executionId ) ; Path cmPath = HadoopDataSourceUtil . getCommitMarkPath ( conf , executionId ) ; FileSystem fs = txPath . getFileSystem ( conf ) ; fs . create ( txPath ) . close ( ) ; fs . create ( cmPath ) . close ( ) ; int index = ; for ( String path : repo . getContainerPaths ( ) ) { String id = repo . getRelatedId ( path ) ; DirectDataSource ds = repo . getRelatedDataSource ( path ) ; OutputTransactionContext txContext = HadoopDataSourceUtil . createContext ( executionId , id ) ; OutputAttemptContext aContext = new OutputAttemptContext ( txContext . getTransactionId ( ) , String . valueOf ( index ) , txContext . getOutputId ( ) , new Counter ( ) ) ; ds . setupTransactionOutput ( txContext ) ; ds . setupAttemptOutput ( aContext ) ; ModelOutput < StringBuilder > output = ds . openOutput ( aContext , StringBuilder . class , new MockFormat ( ) , "" , executionId , new Counter ( ) ) ; try { output . write ( new StringBuilder ( "" ) ) ; } finally { output . close ( ) ; } ds . commitAttemptOutput ( aContext ) ; ds . cleanupAttemptOutput ( aContext ) ; index ++ ; } } protected static final class MockProvider implements DirectDataSourceProvider { HadoopDataSourceProfile profile ; MockProvider ( HadoopDataSourceProfile profile ) { this . profile = profile ; } @ Override public String getId ( ) { return profile . getId ( ) ; } @ Override public String getPath ( ) { return profile . getContextPath ( ) ; } @ Override public DirectDataSource newInstance ( ) throws IOException , InterruptedException { return new HadoopDataSourceCore ( profile ) ; } } protected static class MockFormat extends BinaryStreamFormat < StringBuilder > { MockFormat ( ) { return ; } @ Override public Class < StringBuilder > getSupportedType ( ) { return StringBuilder . class ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return ; } @ Override public ModelInput < StringBuilder > createInput ( Class < ? extends StringBuilder > dataType , String path , InputStream stream , long offset , long fragmentSize ) throws IOException , InterruptedException { final Scanner s = new Scanner ( stream , "" ) ; return new ModelInput < StringBuilder > ( ) { @ Override public boolean readTo ( StringBuilder model ) throws IOException { if ( s . hasNextLine ( ) ) { model . delete ( , model . length ( ) ) ; model . append ( s . nextLine ( ) ) ; return true ; } return false ; } @ Override public void close ( ) throws IOException { s . close ( ) ; } } ; } @ Override public ModelOutput < StringBuilder > createOutput ( Class < ? extends StringBuilder > dataType , String path , OutputStream stream ) throws IOException , InterruptedException { final PrintWriter w = new PrintWriter ( new OutputStreamWriter ( stream ) ) ; return new ModelOutput < StringBuilder > ( ) { @ Override public void write ( StringBuilder model ) throws IOException { w . println ( model . toString ( ) ) ; } @ Override public void close ( ) throws IOException { w . close ( ) ; } } ; } } } package com . asakusafw . directio . tools ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import org . junit . Test ; public class DirectIoListTransactionTest extends DirectIoCommandTestRoot { @ Test public void run ( ) throws Exception { Tool exec = new DirectIoListTransaction ( repo ) ; indoubt ( "" ) ; indoubt ( "" ) ; indoubt ( "" ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] ) , is ( ) ) ; editor . apply ( "" ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] ) , is ( ) ) ; editor . apply ( "" ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] ) , is ( ) ) ; editor . apply ( "" ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] ) , is ( ) ) ; } @ Test public void run_invalid ( ) throws Exception { Tool exec = new DirectIoListTransaction ( repo ) ; assertThat ( ToolRunner . run ( conf , exec , new String [ ] { "" } ) , is ( not ( ) ) ) ; } } package com . asakusafw . directio . tools ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . LinkedList ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . directio . ResourcePattern ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; public final class DirectIoDelete extends Configured implements Tool { static final Log LOG = LogFactory . getLog ( DirectIoDelete . class ) ; private DirectDataSourceRepository repository ; public DirectIoDelete ( ) { return ; } DirectIoDelete ( DirectDataSourceRepository repository ) { this . repository = repository ; } @ Override public int run ( String [ ] args ) throws Exception { LinkedList < String > argList = new LinkedList < String > ( ) ; Collections . addAll ( argList , args ) ; boolean recursive = false ; while ( argList . isEmpty ( ) == false ) { String arg = argList . removeFirst ( ) ; if ( arg . equals ( "" ) || arg . equals ( "" ) ) { recursive = true ; } else if ( arg . equals ( "" ) ) { break ; } else { argList . addFirst ( arg ) ; break ; } } if ( argList . size ( ) < ) { LOG . error ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; System . err . println ( MessageFormat . format ( "" + "" , getClass ( ) . getName ( ) ) ) ; return ; } String path = argList . removeFirst ( ) ; List < FilePattern > patterns = new ArrayList < FilePattern > ( ) ; for ( String arg : argList ) { patterns . add ( FilePattern . compile ( arg ) ) ; } if ( repository == null ) { repository = HadoopDataSourceUtil . loadRepository ( getConf ( ) ) ; } String basePath = repository . getComponentPath ( path ) ; DirectDataSource source = repository . getRelatedDataSource ( path ) ; for ( FilePattern pattern : patterns ) { source . delete ( basePath , pattern , recursive , new Counter ( ) ) ; } return ; } public static void main ( String [ ] args ) throws Exception { int exitCode = ToolRunner . run ( new Configuration ( ) , new DirectIoDelete ( ) , args ) ; System . exit ( exitCode ) ; } } package com . asakusafw . directio . tools ; package com . asakusafw . directio . tools ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . LinkedList ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . directio . ResourceInfo ; import com . asakusafw . runtime . directio . ResourcePattern ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; public final class DirectIoList extends Configured implements Tool { static final Log LOG = LogFactory . getLog ( DirectIoList . class ) ; private DirectDataSourceRepository repository ; public DirectIoList ( ) { return ; } DirectIoList ( DirectDataSourceRepository repository ) { this . repository = repository ; } @ Override public int run ( String [ ] args ) throws Exception { LinkedList < String > argList = new LinkedList < String > ( ) ; Collections . addAll ( argList , args ) ; while ( argList . isEmpty ( ) == false ) { String arg = argList . removeFirst ( ) ; if ( arg . equals ( "" ) ) { break ; } else { argList . addFirst ( arg ) ; break ; } } if ( argList . size ( ) < ) { LOG . error ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; System . err . println ( MessageFormat . format ( "" , getClass ( ) . getName ( ) ) ) ; return ; } String path = argList . removeFirst ( ) ; List < FilePattern > patterns = new ArrayList < FilePattern > ( ) ; for ( String arg : argList ) { patterns . add ( FilePattern . compile ( arg ) ) ; } if ( repository == null ) { repository = HadoopDataSourceUtil . loadRepository ( getConf ( ) ) ; } String basePath = repository . getComponentPath ( path ) ; DirectDataSource source = repository . getRelatedDataSource ( path ) ; for ( FilePattern pattern : patterns ) { List < ResourceInfo > list = source . list ( basePath , pattern , new Counter ( ) ) ; for ( ResourceInfo info : list ) { System . out . println ( info . getPath ( ) ) ; } } return ; } public static void main ( String [ ] args ) throws Exception { int exitCode = ToolRunner . run ( new Configuration ( ) , new DirectIoList ( ) , args ) ; System . exit ( exitCode ) ; } } package com . asakusafw . directio . tools ; import java . text . MessageFormat ; import java . util . Arrays ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . hadoop . DirectIoTransactionEditor ; public final class DirectIoAbortTransaction extends Configured implements Tool { static final Log LOG = LogFactory . getLog ( DirectIoAbortTransaction . class ) ; private DirectDataSourceRepository repository ; public DirectIoAbortTransaction ( ) { return ; } DirectIoAbortTransaction ( DirectDataSourceRepository repository ) { this . repository = repository ; } @ Override public int run ( String [ ] args ) { if ( args . length == ) { String executionId = args [ ] ; DirectIoTransactionEditor editor = new DirectIoTransactionEditor ( repository ) ; editor . setConf ( getConf ( ) ) ; try { editor . abort ( executionId ) ; return ; } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , executionId ) , e ) ; return ; } } else { LOG . error ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; System . err . println ( MessageFormat . format ( "" , getClass ( ) . getName ( ) ) ) ; return ; } } public static void main ( String [ ] args ) throws Exception { int exitCode = ToolRunner . run ( new Configuration ( ) , new DirectIoAbortTransaction ( ) , args ) ; System . exit ( exitCode ) ; } } package com . asakusafw . directio . tools ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . hadoop . DirectIoTransactionEditor ; import com . asakusafw . runtime . directio . hadoop . DirectIoTransactionEditor . TransactionInfo ; public final class DirectIoListTransaction extends Configured implements Tool { static final Log LOG = LogFactory . getLog ( DirectIoListTransaction . class ) ; private DirectDataSourceRepository repository ; public DirectIoListTransaction ( ) { return ; } DirectIoListTransaction ( DirectDataSourceRepository repository ) { this . repository = repository ; } @ Override public int run ( String [ ] args ) { if ( args . length == ) { DirectIoTransactionEditor editor = new DirectIoTransactionEditor ( repository ) ; editor . setConf ( getConf ( ) ) ; try { List < TransactionInfo > list = editor . list ( ) ; if ( list . isEmpty ( ) == false ) { for ( TransactionInfo commit : list ) { System . out . println ( "" ) ; System . out . printf ( "" ) ; System . out . printf ( "" , new java . util . Date ( commit . getTimestamp ( ) ) ) ; System . out . printf ( "" ) ; System . out . printf ( "" , commit . getExecutionId ( ) ) ; System . out . printf ( "" ) ; System . out . printf ( "" , commit . isCommitted ( ) ? "" : "" ) ; System . out . printf ( "" ) ; for ( String line : commit . getComment ( ) ) { System . out . printf ( "" , line ) ; } } System . out . println ( "" ) ; } return ; } catch ( Exception e ) { LOG . error ( "" , e ) ; return ; } } else { LOG . error ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; System . err . println ( MessageFormat . format ( "" , getClass ( ) . getName ( ) ) ) ; return ; } } public static void main ( String [ ] args ) throws Exception { int exitCode = ToolRunner . run ( new Configuration ( ) , new DirectIoListTransaction ( ) , args ) ; System . exit ( exitCode ) ; } } package com . asakusafw . directio . tools ; import java . text . MessageFormat ; import java . util . Arrays ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . hadoop . DirectIoTransactionEditor ; public final class DirectIoApplyTransaction extends Configured implements Tool { static final Log LOG = LogFactory . getLog ( DirectIoApplyTransaction . class ) ; private DirectDataSourceRepository repository ; public DirectIoApplyTransaction ( ) { return ; } DirectIoApplyTransaction ( DirectDataSourceRepository repository ) { this . repository = repository ; } @ Override public int run ( String [ ] args ) { if ( args . length == ) { String executionId = args [ ] ; DirectIoTransactionEditor editor = new DirectIoTransactionEditor ( repository ) ; editor . setConf ( getConf ( ) ) ; try { editor . apply ( executionId ) ; return ; } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , executionId ) , e ) ; return ; } } else { LOG . error ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; System . err . println ( MessageFormat . format ( "" , getClass ( ) . getName ( ) ) ) ; return ; } } public static void main ( String [ ] args ) throws Exception { int exitCode = ToolRunner . run ( new Configuration ( ) , new DirectIoApplyTransaction ( ) , args ) ; System . exit ( exitCode ) ; } } package com . asakusafw . compiler . directio ; package com . asakusafw . compiler . directio ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . BitSet ; import java . util . List ; import java . util . Set ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . runtime . stage . directio . StringTemplate . Format ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . directio . DirectFileOutputDescription ; public final class OutputPattern { static final int CHAR_BRACE_OPEN = '' ; static final int CHAR_BRACE_CLOSE = '' ; static final int CHAR_BLOCK_OPEN = '' ; static final int CHAR_BLOCK_CLOSE = '' ; static final int CHAR_WILDCARD = '' ; static final int CHAR_SEPARATE_IN_BLOCK = '' ; static final int CHAR_VARIABLE_START = '' ; static final BitSet CHAR_MAP_META = new BitSet ( ) ; static { CHAR_MAP_META . set ( , ) ; CHAR_MAP_META . set ( '' ) ; CHAR_MAP_META . set ( '' ) ; CHAR_MAP_META . set ( '' ) ; CHAR_MAP_META . set ( '' ) ; CHAR_MAP_META . set ( '' ) ; CHAR_MAP_META . set ( '' ) ; CHAR_MAP_META . set ( '' ) ; CHAR_MAP_META . set ( '' ) ; CHAR_MAP_META . set ( '' ) ; } private static final Pattern PATTERN_ORDER = Pattern . compile ( "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; private static final int [ ] ORDER_GROUP_INDEX = { , , , , } ; private static final boolean [ ] ASC_MAP = { true , true , false , true , false } ; private OutputPattern ( ) { return ; } public static List < CompiledResourcePattern > compileResourcePattern ( String pattern , DataClass dataType ) { if ( pattern == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } List < CompiledResourcePattern > results = Lists . create ( ) ; Cursor cursor = new Cursor ( pattern ) ; while ( cursor . isEof ( ) == false ) { if ( cursor . isLiteral ( ) ) { String literal = cursor . consumeLiteral ( ) ; results . add ( new CompiledResourcePattern ( literal ) ) ; } else if ( cursor . isPlaceHolder ( ) ) { Formatted ph = cursor . consumePlaceHolder ( ) ; DataClass . Property property = findProperty ( dataType , ( String ) ph . original ) ; if ( property == null ) { cursor . rewind ( ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , cursor , ph . original ) ) ; } String argument = ph . formatString ; Format format = findFormat ( property , argument ) ; if ( format == null ) { cursor . rewind ( ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , cursor , argument == null ? "" : argument ) ) ; } try { format . check ( property . getType ( ) , argument ) ; } catch ( IllegalArgumentException e ) { cursor . rewind ( ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , cursor , argument == null ? "" : argument ) , e ) ; } results . add ( new CompiledResourcePattern ( property , format , argument ) ) ; } else if ( cursor . isRandomNumber ( ) ) { Formatted rand = cursor . consumeRandomNumber ( ) ; RandomNumber source = ( RandomNumber ) rand . original ; results . add ( new CompiledResourcePattern ( source , Format . NATURAL , null ) ) ; } else if ( cursor . isWildcard ( ) ) { cursor . consumeWildcard ( ) ; results . add ( new CompiledResourcePattern ( ) ) ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , cursor ) ) ; } } return results ; } public static List < CompiledOrder > compileOrder ( List < String > orders , DataClass dataType ) { if ( orders == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } Set < String > saw = Sets . create ( ) ; List < CompiledOrder > results = Lists . create ( ) ; for ( String order : orders ) { boolean asc = false ; String name = null ; Matcher matcher = PATTERN_ORDER . matcher ( order . trim ( ) ) ; if ( matcher . matches ( ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , order ) ) ; } for ( int i = ; i < ORDER_GROUP_INDEX . length ; i ++ ) { int groupIndex = ORDER_GROUP_INDEX [ i ] ; if ( matcher . group ( groupIndex ) != null ) { asc = ASC_MAP [ i ] ; name = matcher . group ( groupIndex ) ; break ; } } assert name != null ; DataClass . Property property = findProperty ( dataType , name ) ; if ( property == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , order , name ) ) ; } if ( saw . contains ( property . getName ( ) ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , order , name ) ) ; } saw . add ( property . getName ( ) ) ; results . add ( new CompiledOrder ( property , asc ) ) ; } return results ; } private static Property findProperty ( DataClass dataType , String name ) { assert dataType != null ; assert name != null ; return dataType . findProperty ( name ) ; } private static Format findFormat ( Property property , String argument ) { if ( argument == null ) { return Format . NATURAL ; } Type type = property . getType ( ) ; if ( type == DateOption . class ) { return Format . DATE ; } if ( type == DateTimeOption . class ) { return Format . DATETIME ; } return null ; } private static final class Cursor { private final char [ ] cbuf ; private int lastSegmentPosition ; private int position ; Cursor ( String value ) { assert value != null ; this . cbuf = value . toCharArray ( ) ; this . position = ; } boolean isEof ( ) { return cbuf . length == position ; } boolean isLiteral ( ) { if ( isEof ( ) ) { return false ; } return CHAR_MAP_META . get ( cbuf [ position ] ) == false ; } boolean isPlaceHolder ( ) { if ( isEof ( ) ) { return false ; } return cbuf [ position ] == CHAR_BRACE_OPEN ; } boolean isRandomNumber ( ) { if ( isEof ( ) ) { return false ; } return cbuf [ position ] == CHAR_BLOCK_OPEN ; } boolean isWildcard ( ) { if ( isEof ( ) ) { return false ; } return cbuf [ position ] == CHAR_WILDCARD ; } void rewind ( ) { this . position = lastSegmentPosition ; } String consumeLiteral ( ) { assert isLiteral ( ) ; this . lastSegmentPosition = position ; int start = position ; while ( isLiteral ( ) ) { char c = cbuf [ position ] ; if ( c == CHAR_VARIABLE_START ) { skipVariable ( ) ; } else if ( CHAR_MAP_META . get ( c ) == false ) { advance ( ) ; } else { throw new AssertionError ( c ) ; } } return String . valueOf ( cbuf , start , position - start ) ; } private void skipVariable ( ) { int start = position ; assert cbuf [ position ] == CHAR_VARIABLE_START ; advance ( ) ; if ( isEof ( ) || cbuf [ position ] != CHAR_BRACE_OPEN ) { return ; } advance ( ) ; while ( true ) { if ( isEof ( ) ) { position = start ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this ) ) ; } char c = cbuf [ position ] ; if ( c == CHAR_BRACE_CLOSE ) { break ; } advance ( ) ; } advance ( ) ; } Formatted consumePlaceHolder ( ) { assert isPlaceHolder ( ) ; this . lastSegmentPosition = position ; int start = position + ; String propertyName ; String formatString ; advance ( ) ; while ( true ) { if ( isEof ( ) ) { position = start ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this ) ) ; } char c = cbuf [ position ] ; if ( c == CHAR_BRACE_CLOSE || c == CHAR_SEPARATE_IN_BLOCK ) { break ; } advance ( ) ; } propertyName = String . valueOf ( cbuf , start , position - start ) ; if ( cbuf [ position ] == CHAR_SEPARATE_IN_BLOCK ) { advance ( ) ; int formatStart = position ; while ( true ) { if ( isEof ( ) ) { position = start ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this ) ) ; } char c = cbuf [ position ] ; if ( c == CHAR_BRACE_CLOSE ) { break ; } advance ( ) ; } formatString = String . valueOf ( cbuf , formatStart , position - formatStart ) ; } else { formatString = null ; } assert cbuf [ position ] == CHAR_BRACE_CLOSE ; advance ( ) ; return new Formatted ( propertyName , formatString ) ; } private static final Pattern RNG = Pattern . compile ( "" ) ; Formatted consumeRandomNumber ( ) { assert isRandomNumber ( ) ; this . lastSegmentPosition = position ; int start = position + ; while ( true ) { if ( isEof ( ) ) { position = start ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this ) ) ; } char c = cbuf [ position ] ; if ( c == CHAR_BLOCK_CLOSE ) { break ; } advance ( ) ; } String content = String . valueOf ( cbuf , start , position - start ) ; Matcher matcher = RNG . matcher ( content ) ; if ( matcher . matches ( ) == false ) { position = start ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this ) ) ; } int lower ; try { lower = Integer . parseInt ( matcher . group ( ) ) ; } catch ( NumberFormatException e ) { position = start + matcher . start ( ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this ) , e ) ; } int upper ; try { upper = Integer . parseInt ( matcher . group ( ) ) ; } catch ( NumberFormatException e ) { position = start + matcher . start ( ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this ) , e ) ; } if ( lower >= upper ) { position = start + matcher . start ( ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this ) ) ; } String format = matcher . group ( ) ; advance ( ) ; return new Formatted ( new RandomNumber ( lower , upper ) , format ) ; } void consumeWildcard ( ) { assert isWildcard ( ) ; advance ( ) ; } private void advance ( ) { position = Math . min ( position + , cbuf . length ) ; } @ Override public String toString ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( '' ) ; for ( int i = , n = position ; i < n ; i ++ ) { buf . append ( cbuf [ i ] ) ; } buf . append ( "" ) ; for ( int i = position , n = cbuf . length ; i < n ; i ++ ) { buf . append ( cbuf [ i ] ) ; } buf . append ( '' ) ; return buf . toString ( ) ; } } private static class Formatted { final Object original ; final String formatString ; Formatted ( Object original , String formatString ) { this . original = original ; this . formatString = formatString ; } } public static final class CompiledResourcePattern { private final SourceKind kind ; private final Object source ; private final Format format ; private final String argument ; public CompiledResourcePattern ( ) { this . kind = SourceKind . ENVIRONMENT ; this . source = null ; this . format = Format . PLAIN ; this . argument = null ; } public CompiledResourcePattern ( String string ) { if ( string == null ) { throw new IllegalArgumentException ( "" ) ; } this . kind = SourceKind . NOTHING ; this . source = null ; this . format = Format . PLAIN ; this . argument = string ; } public CompiledResourcePattern ( DataClass . Property target , Format format , String argument ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } this . kind = SourceKind . PROPERTY ; this . source = target ; this . format = format ; this . argument = argument ; format . check ( target . getType ( ) , argument ) ; } public CompiledResourcePattern ( RandomNumber source , Format format , String argument ) { if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } this . kind = SourceKind . RANDOM ; this . source = source ; this . format = format ; this . argument = argument ; } public SourceKind getKind ( ) { return kind ; } public Object getSource ( ) { return source ; } public DataClass . Property getTarget ( ) { if ( kind != SourceKind . PROPERTY ) { return null ; } return ( DataClass . Property ) source ; } public RandomNumber getRandomNumber ( ) { if ( kind != SourceKind . RANDOM ) { return null ; } return ( RandomNumber ) source ; } public Format getFormat ( ) { return format ; } public String getArgument ( ) { return argument ; } } public static final class CompiledOrder { private final DataClass . Property target ; private final boolean ascend ; public CompiledOrder ( DataClass . Property target , boolean ascend ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } this . target = target ; this . ascend = ascend ; } public DataClass . Property getTarget ( ) { return target ; } public boolean isAscend ( ) { return ascend ; } } public enum SourceKind { NOTHING , PROPERTY , RANDOM , ENVIRONMENT , } public static class RandomNumber { private final int lowerBound ; private final int upperBound ; public RandomNumber ( int lowerBound , int upperBound ) { this . lowerBound = lowerBound ; this . upperBound = upperBound ; } public int getLowerBound ( ) { return lowerBound ; } public int getUpperBound ( ) { return upperBound ; } } } package com . asakusafw . compiler . directio . emitter ; package com . asakusafw . compiler . directio . emitter ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . io . NullWritable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . runtime . directio . DirectDataSourceConstants ; import com . asakusafw . runtime . io . util . ShuffleKey . AbstractGroupComparator ; import com . asakusafw . runtime . io . util . ShuffleKey . AbstractOrderComparator ; import com . asakusafw . runtime . io . util . ShuffleKey . Partitioner ; import com . asakusafw . runtime . stage . AbstractStageClient ; import com . asakusafw . runtime . stage . BaseStageClient ; import com . asakusafw . runtime . stage . StageInput ; import com . asakusafw . runtime . stage . StageOutput ; import com . asakusafw . runtime . stage . directio . AbstractDirectOutputKey ; import com . asakusafw . runtime . stage . directio . AbstractDirectOutputMapper ; import com . asakusafw . runtime . stage . directio . AbstractDirectOutputValue ; import com . asakusafw . runtime . stage . directio . AbstractNoReduceDirectOutputMapper ; import com . asakusafw . runtime . stage . directio . DirectOutputReducer ; import com . asakusafw . runtime . stage . directio . DirectOutputSpec ; import com . asakusafw . runtime . stage . output . BridgeOutputFormat ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . ArrayType ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class StageEmitter { static final Logger LOG = LoggerFactory . getLogger ( StageEmitter . class ) ; private final FlowCompilingEnvironment environment ; private final String moduleId ; public StageEmitter ( FlowCompilingEnvironment environment , String moduleId ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( moduleId , "" ) ; this . environment = environment ; this . moduleId = moduleId ; } public CompiledStage emit ( List < Slot > slots , Location outputLocation ) throws IOException { Precondition . checkMustNotBeNull ( slots , "" ) ; Precondition . checkMustNotBeNull ( outputLocation , "" ) ; LOG . debug ( "" , environment . getBatchId ( ) , environment . getFlowId ( ) ) ; if ( requiresReducer ( slots ) ) { return emitClientWithReducer ( slots , outputLocation ) ; } else { return emitClientWithoutReducer ( slots , outputLocation ) ; } } private boolean requiresReducer ( List < Slot > slots ) { assert slots != null ; for ( Slot slot : slots ) { if ( requiresReducer ( slot ) ) { return true ; } } return false ; } private boolean requiresReducer ( Slot slot ) { assert slot != null ; return slot . orderClass != null ; } private CompiledStage emitClientWithReducer ( List < Slot > slots , Location outputLocation ) throws IOException { assert slots != null ; assert outputLocation != null ; LOG . debug ( "" ) ; Name key = emitKey ( slots ) ; LOG . debug ( "" ) ; Name value = emitValue ( slots ) ; LOG . debug ( "" ) ; Name grouping = emitGrouping ( key ) ; LOG . debug ( "" ) ; Name ordering = emitOrdering ( key ) ; LOG . debug ( "" ) ; List < CompiledSlot > compiledSlots = emitMappers ( slots , key , value ) ; LOG . debug ( "" ) ; Name client = emitClient ( compiledSlots , key , value , grouping , ordering , outputLocation ) ; LOG . debug ( "" , new Object [ ] { environment . getBatchId ( ) , environment . getFlowId ( ) , client . toNameString ( ) , } ) ; return new CompiledStage ( client , Naming . getEpilogueName ( moduleId ) ) ; } private CompiledStage emitClientWithoutReducer ( List < Slot > slots , Location outputLocation ) throws IOException { assert slots != null ; assert outputLocation != null ; LOG . debug ( "" ) ; List < CompiledSlot > compiledSlots = emitMappers ( slots , null , null ) ; LOG . debug ( "" ) ; Name client = emitClient ( compiledSlots , null , null , null , null , outputLocation ) ; LOG . debug ( "" , new Object [ ] { environment . getBatchId ( ) , environment . getFlowId ( ) , client . toNameString ( ) , } ) ; return new CompiledStage ( client , Naming . getEpilogueName ( moduleId ) ) ; } private Name emitKey ( List < Slot > slots ) throws IOException { assert slots != null ; return emitWithSpecs ( Naming . getShuffleKeyClass ( ) , AbstractDirectOutputKey . class , slots ) ; } private Name emitValue ( List < Slot > slots ) throws IOException { assert slots != null ; return emitWithSpecs ( Naming . getShuffleValueClass ( ) , AbstractDirectOutputValue . class , slots ) ; } private Name emitGrouping ( Name key ) throws IOException { assert key != null ; return emitWithClass ( Naming . getShuffleGroupingComparatorClass ( ) , AbstractGroupComparator . class , key ) ; } private Name emitOrdering ( Name key ) throws IOException { return emitWithClass ( Naming . getShuffleSortComparatorClass ( ) , AbstractOrderComparator . class , key ) ; } private List < CompiledSlot > emitMappers ( List < Slot > slots , Name keyOrNull , Name valueOrNull ) throws IOException { assert slots != null ; List < CompiledSlot > results = Lists . create ( ) ; int index = ; for ( Slot slot : slots ) { Name mapper ; if ( requiresReducer ( slot ) ) { assert keyOrNull != null ; assert valueOrNull != null ; mapper = emitShuffleMapper ( slot , index , keyOrNull , valueOrNull ) ; } else { mapper = emitOutputMapper ( slot , index ) ; } results . add ( new CompiledSlot ( slot , mapper ) ) ; index ++ ; } return results ; } private Name emitShuffleMapper ( Slot slot , int index , Name key , Name value ) throws IOException { assert slot != null ; assert key != null ; assert value != null ; assert index >= ; assert requiresReducer ( slot ) ; ModelFactory f = environment . getModelFactory ( ) ; SimpleName className = f . newSimpleName ( Naming . getMapClass ( index ) ) ; ImportBuilder importer = new ImportBuilder ( f , f . newPackageDeclaration ( environment . getEpiloguePackageName ( moduleId ) ) , Strategy . TOP_LEVEL ) ; importer . resolvePackageMember ( className ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( Models . toLiteral ( f , index ) ) ; arguments . add ( classLiteralOrNull ( f , importer , key ) ) ; arguments . add ( classLiteralOrNull ( f , importer , value ) ) ; return emitConstructorClass ( className , f . newParameterizedType ( importer . toType ( AbstractDirectOutputMapper . class ) , importer . toType ( slot . valueType ) ) , importer , arguments ) ; } private Name emitOutputMapper ( Slot slot , int index ) throws IOException { assert slot != null ; assert index >= ; assert requiresReducer ( slot ) == false ; ModelFactory f = environment . getModelFactory ( ) ; SimpleName className = f . newSimpleName ( Naming . getMapClass ( index ) ) ; ImportBuilder importer = new ImportBuilder ( f , f . newPackageDeclaration ( environment . getEpiloguePackageName ( moduleId ) ) , Strategy . TOP_LEVEL ) ; importer . resolvePackageMember ( className ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( f . newClassLiteral ( importer . toType ( slot . valueType ) ) ) ; arguments . add ( Models . toLiteral ( f , slot . basePath ) ) ; arguments . add ( Models . toLiteral ( f , slot . resourcePath ) ) ; arguments . add ( f . newClassLiteral ( importer . toType ( slot . formatClass ) ) ) ; return emitConstructorClass ( className , f . newParameterizedType ( importer . toType ( AbstractNoReduceDirectOutputMapper . class ) , importer . toType ( slot . valueType ) ) , importer , arguments ) ; } private Name emitWithSpecs ( String classNameString , Class < ? > baseClass , List < Slot > slots ) throws IOException { assert classNameString != null ; assert baseClass != null ; assert slots != null ; ModelFactory f = environment . getModelFactory ( ) ; SimpleName className = f . newSimpleName ( classNameString ) ; ImportBuilder importer = new ImportBuilder ( f , f . newPackageDeclaration ( environment . getEpiloguePackageName ( moduleId ) ) , Strategy . TOP_LEVEL ) ; importer . resolvePackageMember ( className ) ; List < Expression > elements = Lists . create ( ) ; for ( Slot slot : slots ) { if ( requiresReducer ( slot ) ) { List < Expression > arguments = Lists . create ( ) ; arguments . add ( f . newClassLiteral ( importer . toType ( slot . valueType ) ) ) ; arguments . add ( Models . toLiteral ( f , slot . basePath ) ) ; arguments . add ( f . newClassLiteral ( importer . toType ( slot . formatClass ) ) ) ; arguments . add ( f . newClassLiteral ( importer . toType ( slot . namingClass ) ) ) ; arguments . add ( f . newClassLiteral ( importer . toType ( slot . orderClass ) ) ) ; elements . add ( new TypeBuilder ( f , importer . toType ( DirectOutputSpec . class ) ) . newObject ( arguments ) . toExpression ( ) ) ; } else { elements . add ( Models . toNullLiteral ( f ) ) ; } } return emitConstructorClass ( className , importer . toType ( baseClass ) , importer , Collections . singletonList ( f . newArrayCreationExpression ( ( ArrayType ) importer . toType ( DirectOutputSpec [ ] . class ) , f . newArrayInitializer ( elements ) ) ) ) ; } private Expression classLiteralOrNull ( ModelFactory f , ImportBuilder importer , Name nameOrNull ) { assert f != null ; assert importer != null ; if ( nameOrNull == null ) { return Models . toNullLiteral ( f ) ; } else { return f . newClassLiteral ( importer . toType ( nameOrNull ) ) ; } } private Name emitWithClass ( String classNameString , Class < ? > baseClass , Name argumentClassName ) throws IOException { assert classNameString != null ; assert baseClass != null ; assert argumentClassName != null ; ModelFactory f = environment . getModelFactory ( ) ; SimpleName className = f . newSimpleName ( classNameString ) ; ImportBuilder importer = new ImportBuilder ( f , f . newPackageDeclaration ( environment . getEpiloguePackageName ( moduleId ) ) , Strategy . TOP_LEVEL ) ; importer . resolvePackageMember ( className ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( classLiteralOrNull ( f , importer , argumentClassName ) ) ; return emitConstructorClass ( className , importer . toType ( baseClass ) , importer , arguments ) ; } private Name emitConstructorClass ( SimpleName className , Type baseClass , ImportBuilder importer , List < ? extends Expression > arguments ) throws IOException { assert className != null ; assert importer != null ; assert arguments != null ; ModelFactory f = environment . getModelFactory ( ) ; Statement ctorChain = f . newSuperConstructorInvocation ( arguments ) ; ConstructorDeclaration ctorDecl = f . newConstructorDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , className , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( ctorChain ) ) ; ClassDeclaration typeDecl = f . newClassDeclaration ( new JavadocBuilder ( f ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Final ( ) . toAttributes ( ) , className , importer . resolve ( baseClass ) , Collections . < Type > emptyList ( ) , Collections . singletonList ( ctorDecl ) ) ; CompilationUnit source = f . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( typeDecl ) , Collections . < Comment > emptyList ( ) ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , moduleId , name ) ; return name ; } private Name emitClient ( List < CompiledSlot > compiledSlots , Name keyOrNull , Name valueOrNull , Name groupingOrNull , Name orderingOrNull , Location outputLocation ) throws IOException { assert compiledSlots != null ; assert outputLocation != null ; Name partitionerOrNull ; Name reducerOrNull ; if ( keyOrNull != null ) { partitionerOrNull = Models . toName ( environment . getModelFactory ( ) , Partitioner . class . getName ( ) . replace ( '' , '' ) ) ; reducerOrNull = Models . toName ( environment . getModelFactory ( ) , DirectOutputReducer . class . getName ( ) ) ; } else { partitionerOrNull = null ; reducerOrNull = null ; } Engine engine = new Engine ( environment , moduleId , compiledSlots , outputLocation , keyOrNull , valueOrNull , groupingOrNull , orderingOrNull , partitionerOrNull , reducerOrNull ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , moduleId , name ) ; return name ; } private static class CompiledSlot { final Slot original ; final Name mapperClass ; CompiledSlot ( Slot original , Name mapperClass ) { this . original = original ; this . mapperClass = mapperClass ; } } private static class Engine { private static final char PATH_SEPARATOR = '' ; private final FlowCompilingEnvironment environment ; private final String moduleId ; private final List < CompiledSlot > slots ; private final Location outputDirectory ; private final ModelFactory factory ; private final ImportBuilder importer ; private final Name key ; private final Name value ; private final Name grouping ; private final Name ordering ; private final Name partitioner ; private final Name reducer ; Engine ( FlowCompilingEnvironment environment , String moduleId , List < CompiledSlot > slots , Location outputDirectory , Name key , Name value , Name grouping , Name ordering , Name partitioner , Name reducer ) { assert environment != null ; assert moduleId != null ; assert slots != null ; this . environment = environment ; this . moduleId = moduleId ; this . slots = slots ; this . outputDirectory = outputDirectory ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getEpiloguePackageName ( moduleId ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . key = key ; this . value = value ; this . grouping = grouping ; this . ordering = ordering ; this . partitioner = partitioner ; this . reducer = reducer ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getClientClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createIdMethods ( ) ) ; members . add ( createStageOutputPath ( ) ) ; members . add ( createStageInputsMethod ( ) ) ; members . add ( createStageOutputsMethod ( ) ) ; if ( key != null ) { members . addAll ( createShuffleMethods ( ) ) ; } return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( AbstractStageClient . class ) , Collections . < Type > emptyList ( ) , members ) ; } private List < MethodDeclaration > createIdMethods ( ) { List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_BATCH_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getBatchId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_FLOW_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getFlowId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_STAGE_ID , t ( String . class ) , Models . toLiteral ( factory , Naming . getEpilogueName ( moduleId ) ) ) ) ; return results ; } private MethodDeclaration createStageOutputPath ( ) { return createValueMethod ( AbstractStageClient . METHOD_STAGE_OUTPUT_PATH , t ( String . class ) , Models . toLiteral ( factory , outputDirectory . toPath ( PATH_SEPARATOR ) ) ) ; } private MethodDeclaration createStageInputsMethod ( ) { SimpleName list = factory . newSimpleName ( "" ) ; SimpleName attributes = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageInput . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageInput . class ) ) , list ) ) ; statements . add ( new ExpressionBuilder ( factory , Models . toNullLiteral ( factory ) ) . toLocalVariableDeclaration ( t ( Map . class , t ( String . class ) , t ( String . class ) ) , attributes ) ) ; for ( CompiledSlot slot : slots ) { Type mapperType = importer . toType ( slot . mapperClass ) ; for ( SourceInfo info : slot . original . sources ) { statements . add ( new ExpressionBuilder ( factory , attributes ) . assignFrom ( new TypeBuilder ( factory , t ( HashMap . class , t ( String . class ) , t ( String . class ) ) ) . newObject ( ) . toExpression ( ) ) . toStatement ( ) ) ; for ( Map . Entry < String , String > entry : info . getAttributes ( ) . entrySet ( ) ) { statements . add ( new ExpressionBuilder ( factory , attributes ) . method ( "" , Models . toLiteral ( factory , entry . getKey ( ) ) , Models . toLiteral ( factory , entry . getValue ( ) ) ) . toStatement ( ) ) ; } for ( Location input : info . getLocations ( ) ) { statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageInput . class ) ) . newObject ( Models . toLiteral ( factory , input . toPath ( PATH_SEPARATOR ) ) , factory . newClassLiteral ( t ( info . getFormat ( ) ) ) , factory . newClassLiteral ( mapperType ) , attributes ) . toExpression ( ) ) . toStatement ( ) ) ; } } } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageInput . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_INPUTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private List < MethodDeclaration > createShuffleMethods ( ) { List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_SHUFFLE_KEY_CLASS , key ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_SHUFFLE_VALUE_CLASS , value ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_GROUPING_COMPARATOR_CLASS , grouping ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_SORT_COMPARATOR_CLASS , ordering ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_PARTITIONER_CLASS , partitioner ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_REDUCER_CLASS , reducer ) ) ; return results ; } private MethodDeclaration createClassLiteralMethod ( String methodName , Name typeName ) { assert methodName != null ; Type type = importer . toType ( typeName ) ; return createValueMethod ( methodName , t ( Class . class , type ) , factory . newClassLiteral ( type ) ) ; } private MethodDeclaration createStageOutputsMethod ( ) { SimpleName list = factory . newSimpleName ( "" ) ; SimpleName attributes = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageOutput . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageOutput . class ) ) , list ) ) ; statements . add ( new ExpressionBuilder ( factory , Models . toNullLiteral ( factory ) ) . toLocalVariableDeclaration ( t ( Map . class , t ( String . class ) , t ( String . class ) ) , attributes ) ) ; Type formatType = t ( BridgeOutputFormat . class ) ; for ( CompiledSlot slot : slots ) { Slot origin = slot . original ; Expression valueType = factory . newClassLiteral ( importer . toType ( origin . valueType ) ) ; statements . add ( new ExpressionBuilder ( factory , attributes ) . assignFrom ( new TypeBuilder ( factory , t ( HashMap . class , t ( String . class ) , t ( String . class ) ) ) . newObject ( ) . toExpression ( ) ) . toStatement ( ) ) ; int index = ; for ( String pattern : slot . original . deletePatterns ) { statements . add ( new ExpressionBuilder ( factory , attributes ) . method ( "" , Models . toLiteral ( factory , String . format ( "" , DirectDataSourceConstants . PREFIX_DELETE_PATTERN , index ++ ) ) , Models . toLiteral ( factory , pattern ) ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageOutput . class ) ) . newObject ( Models . toLiteral ( factory , origin . basePath ) , factory . newClassLiteral ( t ( NullWritable . class ) ) , valueType , factory . newClassLiteral ( formatType ) , attributes ) . toExpression ( ) ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageOutput . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_OUTPUTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , moduleId ) . toJavadoc ( ) ; } private MethodDeclaration createValueMethod ( String methodName , Type returnType , Expression expression ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , returnType , factory . newSimpleName ( methodName ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( factory . newReturnStatement ( expression ) ) ) ; } private Type t ( java . lang . reflect . Type type , Type ... typeArgs ) { assert type != null ; assert typeArgs != null ; Type raw = importer . toType ( type ) ; if ( typeArgs . length == ) { return raw ; } return factory . newParameterizedType ( raw , Arrays . asList ( typeArgs ) ) ; } } } package com . asakusafw . compiler . directio . emitter ; import java . util . List ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . stage . directio . DirectOutputOrder ; import com . asakusafw . runtime . stage . directio . DirectOutputSpec ; import com . asakusafw . runtime . stage . directio . StringTemplate ; import com . asakusafw . utils . java . model . syntax . Name ; public class Slot { final String name ; final List < SourceInfo > sources ; final Name valueType ; final String basePath ; final String resourcePath ; final Name formatClass ; final Name namingClass ; final Name orderClass ; final List < String > deletePatterns ; public Slot ( String name , List < SourceInfo > sources , Name valueType , String basePath , String resourcePath , Name formatClass , Name namingClass , Name orderClass , List < String > deletePatterns ) { assert ( namingClass == null ) == ( orderClass == null ) ; this . name = name ; this . sources = sources ; this . valueType = valueType ; this . basePath = basePath ; this . resourcePath = resourcePath ; this . formatClass = formatClass ; this . namingClass = namingClass ; this . orderClass = orderClass ; this . deletePatterns = deletePatterns ; } } package com . asakusafw . compiler . directio . emitter ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Random ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . directio . OutputPattern . CompiledResourcePattern ; import com . asakusafw . compiler . directio . OutputPattern . RandomNumber ; import com . asakusafw . compiler . directio . OutputPattern . SourceKind ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . runtime . stage . directio . StringTemplate ; import com . asakusafw . runtime . stage . directio . StringTemplate . Format ; import com . asakusafw . runtime . stage . directio . StringTemplate . FormatSpec ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; @ SuppressWarnings ( "" ) public class NamingClassEmitter { static final Logger LOG = LoggerFactory . getLogger ( NamingClassEmitter . class ) ; private final FlowCompilingEnvironment environment ; private final String moduleId ; public NamingClassEmitter ( FlowCompilingEnvironment environment , String moduleId ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( moduleId , "" ) ; this . environment = environment ; this . moduleId = moduleId ; } public Name emit ( String outputName , int index , DataClass dataType , List < CompiledResourcePattern > namingInfo ) throws IOException { if ( outputName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( namingInfo == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , new Object [ ] { environment . getBatchId ( ) , environment . getFlowId ( ) , outputName , } ) ; Engine engine = new Engine ( environment , moduleId , outputName , index , dataType , namingInfo ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , new Object [ ] { environment . getBatchId ( ) , environment . getFlowId ( ) , outputName , name . toNameString ( ) , } ) ; return name ; } private static final class Engine { private static final String FIELD_RANDOM_HOLDER = "" ; private static final String FIELD_RANDOMIZER = "" ; private final String moduleId ; private final String outputName ; private final int index ; private final DataClass dataType ; private final List < CompiledResourcePattern > namingInfo ; private final ModelFactory factory ; private final ImportBuilder importer ; Engine ( FlowCompilingEnvironment environment , String moduleId , String outputName , int index , DataClass dataType , List < CompiledResourcePattern > namingInfo ) { assert environment != null ; assert moduleId != null ; assert outputName != null ; assert dataType != null ; assert namingInfo != null ; this . moduleId = moduleId ; this . outputName = outputName ; this . index = index ; this . dataType = dataType ; this . namingInfo = namingInfo ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getEpiloguePackageName ( moduleId ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = getClassName ( ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; if ( requireRandomNumber ( ) ) { members . add ( createRandomHolder ( ) ) ; members . add ( createRandomizer ( ) ) ; } members . add ( createConstructor ( ) ) ; members . add ( createSetMethod ( ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( importer . toType ( SuppressWarnings . class ) , Models . toLiteral ( factory , "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( StringTemplate . class ) , Collections . < Type > emptyList ( ) , members ) ; } private boolean requireRandomNumber ( ) { for ( CompiledResourcePattern naming : namingInfo ) { if ( naming . getKind ( ) == SourceKind . RANDOM ) { return true ; } } return false ; } private FieldDeclaration createRandomHolder ( ) { new IntOption ( ) . modify ( index ) ; return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , importer . toType ( IntOption . class ) , factory . newSimpleName ( FIELD_RANDOM_HOLDER ) , new TypeBuilder ( factory , importer . toType ( IntOption . class ) ) . newObject ( ) . toExpression ( ) ) ; } private FieldDeclaration createRandomizer ( ) { return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , importer . toType ( Random . class ) , factory . newSimpleName ( FIELD_RANDOMIZER ) , new TypeBuilder ( factory , importer . toType ( Random . class ) ) . newObject ( Models . toLiteral ( factory , ) ) . toExpression ( ) ) ; } private ConstructorDeclaration createConstructor ( ) { List < Expression > arguments = Lists . create ( ) ; for ( CompiledResourcePattern naming : namingInfo ) { arguments . add ( new TypeBuilder ( factory , t ( FormatSpec . class ) ) . newObject ( new TypeBuilder ( factory , t ( Format . class ) ) . field ( naming . getFormat ( ) . name ( ) ) . toExpression ( ) , naming . getArgument ( ) == null ? Models . toNullLiteral ( factory ) : Models . toLiteral ( factory , naming . getArgument ( ) ) ) . toExpression ( ) ) ; } List < Statement > statements = Lists . create ( ) ; statements . add ( factory . newSuperConstructorInvocation ( arguments ) ) ; return factory . newConstructorDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , getClassName ( ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createSetMethod ( ) { SimpleName raw = factory . newSimpleName ( "" ) ; SimpleName object = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , raw ) . castTo ( t ( dataType . getType ( ) ) ) . toLocalVariableDeclaration ( t ( dataType . getType ( ) ) , object ) ) ; int position = ; for ( CompiledResourcePattern naming : namingInfo ) { switch ( naming . getKind ( ) ) { case NOTHING : break ; case PROPERTY : { DataClass . Property property = naming . getTarget ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( "" , Models . toLiteral ( factory , position ) , property . createGetter ( object ) ) . toStatement ( ) ) ; break ; } case RANDOM : { RandomNumber rand = naming . getRandomNumber ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( FIELD_RANDOM_HOLDER ) . method ( "" , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( FIELD_RANDOMIZER ) . method ( "" , Models . toLiteral ( factory , rand . getUpperBound ( ) - rand . getLowerBound ( ) + ) ) . apply ( InfixOperator . PLUS , Models . toLiteral ( factory , rand . getLowerBound ( ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( "" , Models . toLiteral ( factory , position ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( FIELD_RANDOM_HOLDER ) . toExpression ( ) ) . toStatement ( ) ) ; break ; } default : throw new AssertionError ( ) ; } position ++ ; } return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( Object . class ) , raw ) ) , statements ) ; } private SimpleName getClassName ( ) { return factory . newSimpleName ( String . format ( "" , "" , index ) ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , moduleId , outputName ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type , Type ... typeArgs ) { assert type != null ; assert typeArgs != null ; Type raw = importer . toType ( type ) ; if ( typeArgs . length == ) { return raw ; } return factory . newParameterizedType ( raw , Arrays . asList ( typeArgs ) ) ; } } } package com . asakusafw . compiler . directio . emitter ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . directio . OutputPattern . CompiledOrder ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . runtime . io . util . InvertOrder ; import com . asakusafw . runtime . stage . directio . DirectOutputOrder ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class OrderingClassEmitter { static final Logger LOG = LoggerFactory . getLogger ( OrderingClassEmitter . class ) ; private final FlowCompilingEnvironment environment ; private final String moduleId ; public OrderingClassEmitter ( FlowCompilingEnvironment environment , String moduleId ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( moduleId , "" ) ; this . environment = environment ; this . moduleId = moduleId ; } public Name emit ( String outputName , int index , DataClass dataType , List < CompiledOrder > orderingInfo ) throws IOException { if ( outputName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( orderingInfo == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , new Object [ ] { environment . getBatchId ( ) , environment . getFlowId ( ) , outputName , } ) ; Engine engine = new Engine ( environment , moduleId , outputName , index , dataType , orderingInfo ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , new Object [ ] { environment . getBatchId ( ) , environment . getFlowId ( ) , outputName , name . toNameString ( ) , } ) ; return name ; } private static final class Engine { private final String moduleId ; private final String outputName ; private final int index ; private final DataClass dataType ; private final List < CompiledOrder > orderingInfo ; private final ModelFactory factory ; private final ImportBuilder importer ; Engine ( FlowCompilingEnvironment environment , String moduleId , String outputName , int index , DataClass dataType , List < CompiledOrder > orderingInfo ) { assert environment != null ; assert moduleId != null ; assert outputName != null ; assert dataType != null ; assert orderingInfo != null ; this . moduleId = moduleId ; this . outputName = outputName ; this . index = index ; this . dataType = dataType ; this . orderingInfo = orderingInfo ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getEpiloguePackageName ( moduleId ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = getClassName ( ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createFields ( ) ) ; members . add ( createConstructor ( ) ) ; members . add ( createSetMethod ( ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( DirectOutputOrder . class ) , Collections . < Type > emptyList ( ) , members ) ; } private List < FieldDeclaration > createFields ( ) { List < FieldDeclaration > results = Lists . create ( ) ; for ( CompiledOrder order : orderingInfo ) { results . add ( factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , t ( order . getTarget ( ) . getType ( ) ) , factory . newSimpleName ( order . getTarget ( ) . getName ( ) ) , null ) ) ; } return results ; } private ConstructorDeclaration createConstructor ( ) { List < Expression > arguments = Lists . create ( ) ; for ( CompiledOrder order : orderingInfo ) { Expression arg = order . getTarget ( ) . createNewInstance ( t ( order . getTarget ( ) . getType ( ) ) ) ; if ( order . isAscend ( ) == false ) { arg = new TypeBuilder ( factory , t ( InvertOrder . class ) ) . newObject ( arg ) . toExpression ( ) ; } arguments . add ( arg ) ; } List < Statement > statements = Lists . create ( ) ; statements . add ( factory . newSuperConstructorInvocation ( arguments ) ) ; int position = ; for ( CompiledOrder order : orderingInfo ) { Expression obj = new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( "" , Models . toLiteral ( factory , position ) ) . toExpression ( ) ; if ( order . isAscend ( ) == false ) { Expression invert = factory . newParenthesizedExpression ( new ExpressionBuilder ( factory , obj ) . castTo ( t ( InvertOrder . class ) ) . toExpression ( ) ) ; obj = new ExpressionBuilder ( factory , invert ) . method ( "" ) . toExpression ( ) ; } statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( order . getTarget ( ) . getName ( ) ) . assignFrom ( new ExpressionBuilder ( factory , obj ) . castTo ( t ( order . getTarget ( ) . getType ( ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; position ++ ; } return factory . newConstructorDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , getClassName ( ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createSetMethod ( ) { SimpleName raw = getArgumentName ( "" ) ; SimpleName object = getArgumentName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , raw ) . castTo ( t ( dataType . getType ( ) ) ) . toLocalVariableDeclaration ( t ( dataType . getType ( ) ) , object ) ) ; for ( CompiledOrder order : orderingInfo ) { DataClass . Property property = order . getTarget ( ) ; statements . add ( property . createGetter ( object , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( property . getName ( ) ) . toExpression ( ) ) ) ; } AttributeBuilder attributes = new AttributeBuilder ( factory ) ; if ( orderingInfo . isEmpty ( ) == false ) { attributes = attributes . annotation ( importer . toType ( SuppressWarnings . class ) , Models . toLiteral ( factory , "" ) ) ; } attributes . annotation ( t ( Override . class ) ) . Public ( ) ; return factory . newMethodDeclaration ( null , attributes . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( Object . class ) , raw ) ) , statements ) ; } private SimpleName getArgumentName ( String pref ) { assert pref != null ; StringBuilder nameBuffer = new StringBuilder ( pref ) ; while ( true ) { boolean conflict = false ; for ( CompiledOrder order : orderingInfo ) { if ( order . getTarget ( ) . getName ( ) . contentEquals ( nameBuffer ) ) { conflict = true ; continue ; } } if ( conflict == false ) { return factory . newSimpleName ( nameBuffer . toString ( ) ) ; } nameBuffer . append ( '' ) ; } } private SimpleName getClassName ( ) { return factory . newSimpleName ( String . format ( "" , "" , index ) ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , moduleId , outputName ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type , Type ... typeArgs ) { assert type != null ; assert typeArgs != null ; Type raw = importer . toType ( type ) ; if ( typeArgs . length == ) { return raw ; } return factory . newParameterizedType ( raw , Arrays . asList ( typeArgs ) ) ; } } } package com . asakusafw . compiler . directio ; import java . io . IOException ; import java . util . Collections ; import java . util . EnumSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import org . apache . hadoop . mapreduce . InputFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . directio . OutputPattern . CompiledOrder ; import com . asakusafw . compiler . directio . OutputPattern . CompiledResourcePattern ; import com . asakusafw . compiler . directio . emitter . NamingClassEmitter ; import com . asakusafw . compiler . directio . emitter . OrderingClassEmitter ; import com . asakusafw . compiler . directio . emitter . Slot ; import com . asakusafw . compiler . directio . emitter . StageEmitter ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . mapreduce . copy . CopierClientEmitter ; import com . asakusafw . compiler . flow . mapreduce . copy . CopyDescription ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSourceConstants ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . stage . input . BridgeInputFormat ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . directio . DirectFileInputDescription ; import com . asakusafw . vocabulary . directio . DirectFileOutputDescription ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class DirectFileIoProcessor extends ExternalIoDescriptionProcessor { static final Logger LOG = LoggerFactory . getLogger ( DirectFileIoProcessor . class ) ; private static final String METHOD_RESOURCE_PATTERN = "" ; private static final String METHOD_ORDER = "" ; private static final String MODULE_NAME = "" ; private static final Class < ? extends InputFormat < ? , ? > > INPUT_FORMAT = BridgeInputFormat . class ; @ Override public Class < ? extends ImporterDescription > getImporterDescriptionType ( ) { return DirectFileInputDescription . class ; } @ Override public Class < ? extends ExporterDescription > getExporterDescriptionType ( ) { return DirectFileOutputDescription . class ; } @ Override public boolean validate ( List < InputDescription > inputs , List < OutputDescription > outputs ) { LOG . debug ( "" , getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) ) ; boolean valid = true ; for ( InputDescription input : inputs ) { LOG . debug ( "" , input . getName ( ) ) ; valid &= validateInput ( input ) ; } for ( OutputDescription output : outputs ) { LOG . debug ( "" , output . getName ( ) ) ; valid &= validateOutput ( output ) ; } LOG . debug ( "" ) ; valid &= validatePaths ( inputs , outputs ) ; return valid ; } private boolean validateInput ( InputDescription input ) { boolean valid = true ; DirectFileInputDescription desc = extract ( input ) ; String pattern = desc . getResourcePattern ( ) ; try { FilePattern . compile ( pattern ) ; } catch ( IllegalArgumentException e ) { getEnvironment ( ) . error ( "" , e . getMessage ( ) , desc . getClass ( ) . getName ( ) ) ; valid = false ; } valid &= validateFormat ( desc . getClass ( ) , desc . getModelType ( ) , desc . getFormat ( ) ) ; return valid ; } private boolean validateOutput ( OutputDescription output ) { boolean valid = true ; DirectFileOutputDescription desc = extract ( output ) ; DataClass dataType = getEnvironment ( ) . getDataClasses ( ) . load ( desc . getModelType ( ) ) ; String pattern = desc . getResourcePattern ( ) ; List < CompiledResourcePattern > compiledPattern ; try { compiledPattern = OutputPattern . compileResourcePattern ( pattern , dataType ) ; } catch ( IllegalArgumentException e ) { getEnvironment ( ) . error ( "" , e . getMessage ( ) , desc . getClass ( ) . getName ( ) ) ; valid = false ; compiledPattern = Collections . emptyList ( ) ; } for ( String patternString : desc . getDeletePatterns ( ) ) { try { FilePattern . compile ( patternString ) ; } catch ( IllegalArgumentException e ) { getEnvironment ( ) . error ( "" , e . getMessage ( ) , desc . getClass ( ) . getName ( ) , patternString ) ; valid = false ; } } List < String > orders = desc . getOrder ( ) ; try { OutputPattern . compileOrder ( orders , dataType ) ; } catch ( IllegalArgumentException e ) { getEnvironment ( ) . error ( "" , e . getMessage ( ) , desc . getClass ( ) . getName ( ) ) ; valid = false ; } Set < OutputPattern . SourceKind > kinds = pickSourceKinds ( compiledPattern ) ; if ( kinds . contains ( OutputPattern . SourceKind . ENVIRONMENT ) ) { if ( kinds . contains ( OutputPattern . SourceKind . PROPERTY ) ) { getEnvironment ( ) . error ( "" + "" , pattern , desc . getClass ( ) . getName ( ) , METHOD_RESOURCE_PATTERN ) ; valid = false ; } if ( kinds . contains ( OutputPattern . SourceKind . RANDOM ) ) { getEnvironment ( ) . error ( "" + "" , pattern , desc . getClass ( ) . getName ( ) , METHOD_RESOURCE_PATTERN ) ; valid = false ; } if ( orders . isEmpty ( ) == false ) { getEnvironment ( ) . error ( "" + "" , pattern , desc . getClass ( ) . getName ( ) , METHOD_ORDER ) ; valid = false ; } } valid &= validateFormat ( desc . getClass ( ) , desc . getModelType ( ) , desc . getFormat ( ) ) ; return valid ; } private boolean validatePaths ( List < InputDescription > inputs , List < OutputDescription > outputs ) { assert inputs != null ; assert outputs != null ; boolean valid = true ; TreeMap < String , InputDescription > inputPaths = new TreeMap < String , InputDescription > ( ) ; for ( InputDescription input : inputs ) { DirectFileInputDescription desc = extract ( input ) ; String path = normalizePath ( desc . getBasePath ( ) ) ; inputPaths . put ( path , input ) ; } TreeMap < String , OutputDescription > outputPaths = new TreeMap < String , OutputDescription > ( ) ; for ( OutputDescription output : outputs ) { DirectFileOutputDescription desc = extract ( output ) ; String path = normalizePath ( desc . getBasePath ( ) ) ; for ( Map . Entry < String , InputDescription > entry : inputPaths . tailMap ( path , true ) . entrySet ( ) ) { if ( entry . getKey ( ) . startsWith ( path ) == false ) { break ; } DirectFileInputDescription other = extract ( entry . getValue ( ) ) ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , other . getClass ( ) . getName ( ) ) ; valid = false ; } if ( outputPaths . containsKey ( path ) ) { DirectFileOutputDescription other = extract ( outputPaths . get ( path ) ) ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , other . getClass ( ) . getName ( ) ) ; valid = false ; } else { outputPaths . put ( path , output ) ; } } for ( Map . Entry < String , OutputDescription > base : outputPaths . entrySet ( ) ) { String path = base . getKey ( ) ; DirectFileOutputDescription desc = extract ( base . getValue ( ) ) ; for ( Map . Entry < String , OutputDescription > entry : outputPaths . tailMap ( path , false ) . entrySet ( ) ) { if ( entry . getKey ( ) . startsWith ( path ) == false ) { break ; } DirectFileOutputDescription other = extract ( entry . getValue ( ) ) ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , other . getClass ( ) . getName ( ) ) ; valid = false ; } } return valid ; } private String normalizePath ( String path ) { assert path != null ; boolean sawSeparator = false ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = path . length ( ) ; i < n ; i ++ ) { char c = path . charAt ( i ) ; if ( c == '' ) { sawSeparator = true ; } else { if ( sawSeparator && buf . length ( ) > ) { buf . append ( '' ) ; } sawSeparator = false ; buf . append ( c ) ; } } if ( sawSeparator == false ) { buf . append ( '' ) ; } return buf . toString ( ) ; } private boolean validateFormat ( Class < ? > desc , Class < ? > model , Class < ? extends DataFormat < ? > > format ) { assert desc != null ; if ( format == null ) { getEnvironment ( ) . error ( "" , desc . getName ( ) ) ; return false ; } DataFormat < ? > formatObject ; try { formatObject = format . getConstructor ( ) . newInstance ( ) ; } catch ( Exception e ) { getEnvironment ( ) . error ( "" , desc . getName ( ) , format . getName ( ) ) ; return false ; } if ( formatObject . getSupportedType ( ) . isAssignableFrom ( model ) == false ) { getEnvironment ( ) . error ( "" , desc . getName ( ) , model . getName ( ) , format . getName ( ) ) ; return false ; } return true ; } @ Override public SourceInfo getInputInfo ( InputDescription description ) { DirectFileInputDescription desc = extract ( description ) ; if ( isCacheTarget ( desc ) ) { String outputName = getProcessedInputName ( description ) ; Location location = getEnvironment ( ) . getPrologueLocation ( MODULE_NAME ) . append ( outputName ) . asPrefix ( ) ; return new SourceInfo ( Collections . singleton ( location ) , TemporaryInputFormat . class ) ; } else { return getOriginalInputInfo ( description ) ; } } private SourceInfo getOriginalInputInfo ( InputDescription description ) { DirectFileInputDescription desc = extract ( description ) ; Set < Location > locations = Collections . singleton ( Location . fromPath ( "" , '' ) . append ( description . getName ( ) ) . append ( Location . fromPath ( desc . getBasePath ( ) , '' ) ) ) ; return new SourceInfo ( locations , INPUT_FORMAT , getAttributes ( desc ) ) ; } private Map < String , String > getAttributes ( DirectFileInputDescription desc ) { Map < String , String > attributes = Maps . create ( ) ; attributes . put ( DirectDataSourceConstants . KEY_DATA_CLASS , desc . getModelType ( ) . getName ( ) ) ; attributes . put ( DirectDataSourceConstants . KEY_FORMAT_CLASS , desc . getFormat ( ) . getName ( ) ) ; attributes . put ( DirectDataSourceConstants . KEY_BASE_PATH , desc . getBasePath ( ) ) ; attributes . put ( DirectDataSourceConstants . KEY_RESOURCE_PATH , desc . getResourcePattern ( ) ) ; return attributes ; } private String getProcessedInputName ( InputDescription description ) { assert description != null ; StringBuilder buf = new StringBuilder ( ) ; for ( char c : description . getName ( ) . toCharArray ( ) ) { if ( '' <= c && c <= '' || '' <= c && c <= '' || '' <= c && c <= '' ) { buf . append ( c ) ; } else if ( c <= ) { buf . append ( '' ) ; buf . append ( String . format ( "" , ( int ) c ) ) ; } else { buf . append ( "" ) ; buf . append ( String . format ( "" , ( int ) c ) ) ; } } return buf . toString ( ) ; } @ Override public List < CompiledStage > emitPrologue ( IoContext context ) throws IOException { List < CopyDescription > targets = Lists . create ( ) ; for ( Input input : context . getInputs ( ) ) { InputDescription description = input . getDescription ( ) ; DirectFileInputDescription desc = extract ( description ) ; if ( isCacheTarget ( desc ) ) { LOG . debug ( "" , description . getName ( ) ) ; targets . add ( new CopyDescription ( getProcessedInputName ( description ) , getEnvironment ( ) . getDataClasses ( ) . load ( description . getDataType ( ) ) , getOriginalInputInfo ( description ) , TemporaryOutputFormat . class ) ) ; } } if ( targets . isEmpty ( ) ) { return Collections . emptyList ( ) ; } CopierClientEmitter emitter = new CopierClientEmitter ( getEnvironment ( ) ) ; CompiledStage stage = emitter . emitPrologue ( MODULE_NAME , targets , getEnvironment ( ) . getPrologueLocation ( MODULE_NAME ) ) ; return Collections . singletonList ( stage ) ; } @ Override public List < CompiledStage > emitEpilogue ( IoContext context ) throws IOException { ModelFactory f = getEnvironment ( ) . getModelFactory ( ) ; NamingClassEmitter namingEmitter = new NamingClassEmitter ( getEnvironment ( ) , MODULE_NAME ) ; OrderingClassEmitter orderingEmitter = new OrderingClassEmitter ( getEnvironment ( ) , MODULE_NAME ) ; List < Slot > slots = Lists . create ( ) ; for ( Output output : context . getOutputs ( ) ) { DirectFileOutputDescription desc = extract ( output . getDescription ( ) ) ; DataClass dataType = getEnvironment ( ) . getDataClasses ( ) . load ( desc . getModelType ( ) ) ; List < CompiledResourcePattern > namingInfo = OutputPattern . compileResourcePattern ( desc . getResourcePattern ( ) , dataType ) ; Set < OutputPattern . SourceKind > kinds = pickSourceKinds ( namingInfo ) ; if ( kinds . contains ( OutputPattern . SourceKind . ENVIRONMENT ) ) { assert kinds . contains ( OutputPattern . SourceKind . PROPERTY ) == false ; assert kinds . contains ( OutputPattern . SourceKind . RANDOM ) == false ; assert desc . getOrder ( ) . isEmpty ( ) ; String outputName = output . getDescription ( ) . getName ( ) ; Slot slot = new Slot ( outputName , output . getSources ( ) , Models . toName ( f , desc . getModelType ( ) . getName ( ) ) , desc . getBasePath ( ) , desc . getResourcePattern ( ) , Models . toName ( f , desc . getFormat ( ) . getName ( ) ) , null , null , desc . getDeletePatterns ( ) ) ; slots . add ( slot ) ; } else { List < CompiledOrder > orderingInfo = OutputPattern . compileOrder ( desc . getOrder ( ) , dataType ) ; String outputName = output . getDescription ( ) . getName ( ) ; Name naming = namingEmitter . emit ( outputName , slots . size ( ) + , dataType , namingInfo ) ; Name ordering = orderingEmitter . emit ( outputName , slots . size ( ) + , dataType , orderingInfo ) ; Slot slot = new Slot ( outputName , output . getSources ( ) , Models . toName ( f , desc . getModelType ( ) . getName ( ) ) , desc . getBasePath ( ) , desc . getResourcePattern ( ) , Models . toName ( f , desc . getFormat ( ) . getName ( ) ) , naming , ordering , desc . getDeletePatterns ( ) ) ; slots . add ( slot ) ; } } if ( slots . isEmpty ( ) ) { return Collections . emptyList ( ) ; } StageEmitter stageEmitter = new StageEmitter ( getEnvironment ( ) , MODULE_NAME ) ; CompiledStage result = stageEmitter . emit ( slots , getEnvironment ( ) . getEpilogueLocation ( MODULE_NAME ) ) ; return Collections . singletonList ( result ) ; } private boolean isCacheTarget ( ImporterDescription desc ) { assert desc != null ; switch ( desc . getDataSize ( ) ) { case TINY : return getEnvironment ( ) . getOptions ( ) . isHashJoinForTiny ( ) ; case SMALL : return getEnvironment ( ) . getOptions ( ) . isHashJoinForSmall ( ) ; default : return false ; } } private Set < OutputPattern . SourceKind > pickSourceKinds ( List < CompiledResourcePattern > fragments ) { assert fragments != null ; Set < OutputPattern . SourceKind > results = EnumSet . noneOf ( OutputPattern . SourceKind . class ) ; for ( CompiledResourcePattern fragment : fragments ) { results . add ( fragment . getKind ( ) ) ; } return results ; } private DirectFileInputDescription extract ( InputDescription description ) { assert description != null ; ImporterDescription importer = description . getImporterDescription ( ) ; assert importer != null ; assert importer instanceof DirectFileInputDescription ; return ( DirectFileInputDescription ) importer ; } private DirectFileOutputDescription extract ( OutputDescription description ) { assert description != null ; ExporterDescription exporter = description . getExporterDescription ( ) ; assert exporter != null ; assert exporter instanceof DirectFileOutputDescription ; return ( DirectFileOutputDescription ) exporter ; } } package com . asakusafw . compiler . directio ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . StringOption ; public class MockData { IntOption intValue ; StringOption stringValue ; DateOption dateValue ; DateTimeOption datetimeValue ; } package com . asakusafw . compiler . directio ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . util . Scanner ; import com . asakusafw . compiler . directio . testing . model . Line ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class LineFormat extends BinaryStreamFormat < Line > { @ Override public Class < Line > getSupportedType ( ) { return Line . class ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public ModelInput < Line > createInput ( Class < ? extends Line > dataType , String path , InputStream stream , long offset , long fragmentSize ) throws IOException , InterruptedException { assert offset == ; final Scanner scanner = new Scanner ( new InputStreamReader ( stream , "" ) ) ; return new ModelInput < Line > ( ) { int position = ; @ Override public boolean readTo ( Line model ) throws IOException { if ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) ; model . setValueAsString ( line ) ; model . setFirstAsString ( line . isEmpty ( ) ? "" : line . substring ( , ) ) ; model . setLength ( line . length ( ) ) ; model . setPosition ( position ) ; position ++ ; return true ; } return false ; } @ Override public void close ( ) throws IOException { scanner . close ( ) ; } } ; } @ Override public ModelOutput < Line > createOutput ( Class < ? extends Line > dataType , String path , OutputStream stream ) throws IOException , InterruptedException { final PrintWriter writer = new PrintWriter ( new OutputStreamWriter ( stream , "" ) ) ; return new ModelOutput < Line > ( ) { @ Override public void write ( Line model ) throws IOException { writer . println ( model . getValueAsString ( ) ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } } ; } } package com . asakusafw . compiler . directio ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . directio . OutputPattern . CompiledOrder ; import com . asakusafw . compiler . directio . OutputPattern . CompiledResourcePattern ; import com . asakusafw . compiler . directio . OutputPattern . SourceKind ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . runtime . stage . directio . StringTemplate . Format ; public class OutputPatternTest { final DataClass dataClass = new MockDataClass ( MockData . class ) ; @ Test public void resource_plain ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . PLAIN ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; } @ Test public void resource_placeholder ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . NATURAL ) ) ; } @ Test public void resource_placeholder_date ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . DATE ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; } @ Test public void resource_placeholder_datetime ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . DATETIME ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; } @ Test public void resource_placeholder_mixed ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . PLAIN ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . NATURAL ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . PLAIN ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; } @ Test public void resource_randomNumber ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getRandomNumber ( ) . getLowerBound ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getRandomNumber ( ) . getUpperBound ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . NATURAL ) ) ; } @ Test public void resource_wildcard ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getKind ( ) , is ( SourceKind . ENVIRONMENT ) ) ; } @ Test public void resource_variable ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . PLAIN ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; } @ Test public void resource_variable_mixed ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . PLAIN ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; } @ Test public void resource_complex ( ) { List < CompiledResourcePattern > pattern = OutputPattern . compileResourcePattern ( "" , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . NATURAL ) ) ; assertThat ( pattern . get ( ) . getKind ( ) , is ( SourceKind . NOTHING ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . DATE ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getKind ( ) , is ( SourceKind . NOTHING ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getRandomNumber ( ) . getLowerBound ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getRandomNumber ( ) . getUpperBound ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getFormat ( ) , is ( Format . PLAIN ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . getKind ( ) , is ( SourceKind . ENVIRONMENT ) ) ; assertThat ( pattern . get ( ) . getKind ( ) , is ( SourceKind . NOTHING ) ) ; assertThat ( pattern . get ( ) . getArgument ( ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_unknown_property ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_unknown_format ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_invalid_format ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_invalid_character ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_placeholder_eof ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_format_eof ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_random_eof ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_variable_eof ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void resource_random_invalid_range ( ) { OutputPattern . compileResourcePattern ( "" , dataClass ) ; } @ Test public void order ( ) { List < CompiledOrder > pattern = OutputPattern . compileOrder ( list ( "" ) , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . isAscend ( ) , is ( true ) ) ; } @ Test public void order_asc ( ) { List < CompiledOrder > pattern = OutputPattern . compileOrder ( list ( "" ) , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . isAscend ( ) , is ( true ) ) ; } @ Test public void order_desc ( ) { List < CompiledOrder > pattern = OutputPattern . compileOrder ( list ( "" ) , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . isAscend ( ) , is ( false ) ) ; } @ Test public void order_asc_legacy ( ) { List < CompiledOrder > pattern = OutputPattern . compileOrder ( list ( "" ) , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . isAscend ( ) , is ( true ) ) ; } @ Test public void order_desc_legacy ( ) { List < CompiledOrder > pattern = OutputPattern . compileOrder ( list ( "" ) , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . isAscend ( ) , is ( false ) ) ; } @ Test public void order_multiple ( ) { List < CompiledOrder > pattern = OutputPattern . compileOrder ( list ( "" , "" , "" ) , dataClass ) ; assertThat ( pattern . size ( ) , is ( ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . isAscend ( ) , is ( true ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . isAscend ( ) , is ( false ) ) ; assertThat ( pattern . get ( ) . getTarget ( ) . getName ( ) , is ( "" ) ) ; assertThat ( pattern . get ( ) . isAscend ( ) , is ( true ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void order_invalid_format ( ) { OutputPattern . compileOrder ( list ( "" ) , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void order_unknown_property ( ) { OutputPattern . compileOrder ( list ( "" ) , dataClass ) ; } @ Test ( expected = IllegalArgumentException . class ) public void order_duplicate ( ) { OutputPattern . compileOrder ( list ( "" , "" , "" ) , dataClass ) ; } private List < String > list ( String ... values ) { return Arrays . asList ( values ) ; } } package com . asakusafw . compiler . directio ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class DualIdentityFlow < A , B > extends FlowDescription { private final In < A > in1 ; private final In < B > in2 ; private final Out < A > out1 ; private final Out < B > out2 ; public DualIdentityFlow ( In < A > in1 , In < B > in2 , Out < A > out1 , Out < B > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { out1 . add ( in1 ) ; out2 . add ( in2 ) ; } } package com . asakusafw . compiler . directio ; import java . lang . reflect . Field ; import java . lang . reflect . Modifier ; import java . lang . reflect . Type ; import java . util . Collection ; import java . util . List ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . Statement ; public class MockDataClass implements DataClass { private final Class < ? > entity ; private final List < Property > properties ; public MockDataClass ( Class < ? > entity ) { this . entity = entity ; this . properties = Lists . create ( ) ; for ( Field field : entity . getDeclaredFields ( ) ) { int modifiers = field . getModifiers ( ) ; if ( Modifier . isStatic ( modifiers ) == false && field . isSynthetic ( ) == false ) { properties . add ( new MockProperty ( field . getName ( ) , field . getType ( ) ) ) ; } } } @ Override public Type getType ( ) { return entity ; } @ Override public Collection < ? extends Property > getProperties ( ) { return properties ; } @ Override public Property findProperty ( String propertyName ) { for ( Property property : properties ) { if ( property . getName ( ) . equals ( propertyName ) ) { return property ; } } return null ; } @ Override public Expression createNewInstance ( com . asakusafw . utils . java . model . syntax . Type type ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement assign ( Expression target , Expression source ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement reset ( Expression object ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement createWriter ( Expression object , Expression dataOutput ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement createReader ( Expression object , Expression dataInput ) { throw new UnsupportedOperationException ( ) ; } private static class MockProperty implements Property { private final String name ; private final Class < ? > type ; MockProperty ( String name , Class < ? > type ) { assert name != null ; assert type != null ; this . name = name ; this . type = type ; } @ Override public String getName ( ) { return name ; } @ Override public Type getType ( ) { return type ; } @ Override public boolean canNull ( ) { throw new UnsupportedOperationException ( ) ; } @ Override public Expression createNewInstance ( com . asakusafw . utils . java . model . syntax . Type target ) { throw new UnsupportedOperationException ( ) ; } @ Override public Expression createIsNull ( Expression object ) { throw new UnsupportedOperationException ( ) ; } @ Override public Expression createGetter ( Expression object ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement assign ( Expression target , Expression source ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement createGetter ( Expression object , Expression target ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement createSetter ( Expression object , Expression value ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement createWriter ( Expression object , Expression dataOutput ) { throw new UnsupportedOperationException ( ) ; } @ Override public Statement createReader ( Expression object , Expression dataInput ) { throw new UnsupportedOperationException ( ) ; } @ Override public Expression createHashCode ( Expression object ) { throw new UnsupportedOperationException ( ) ; } @ Override public Expression createBytesSize ( Expression bytes , Expression start , Expression length ) { throw new UnsupportedOperationException ( ) ; } @ Override public Expression createBytesDiff ( Expression bytes1 , Expression start1 , Expression length1 , Expression bytes2 , Expression start2 , Expression length2 ) { throw new UnsupportedOperationException ( ) ; } @ Override public Expression createValueDiff ( Expression value1 , Expression value2 ) { throw new UnsupportedOperationException ( ) ; } } } package com . asakusafw . compiler . directio ; import java . io . IOException ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . compiler . directio . testing . model . Line ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . hadoop . HadoopFileFormat ; import com . asakusafw . runtime . directio . hadoop . HadoopFileFormatAdapter ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class LineFileFormat extends HadoopFileFormatAdapter < Line > { public LineFileFormat ( ) { super ( new LineFormat ( ) ) ; } @ Override public ModelInput < Line > createInput ( Class < ? extends Line > dataType , FileSystem fileSystem , Path path , long offset , long fragmentSize , Counter counter ) throws IOException , InterruptedException { if ( getConf ( ) == null ) { throw new IllegalStateException ( ) ; } return super . createInput ( dataType , fileSystem , path , offset , fragmentSize , counter ) ; } @ Override public ModelOutput < Line > createOutput ( Class < ? extends Line > dataType , FileSystem fileSystem , Path path , Counter counter ) throws IOException , InterruptedException { if ( getConf ( ) == null ) { throw new IllegalStateException ( ) ; } return super . createOutput ( dataType , fileSystem , path , counter ) ; } } package com . asakusafw . compiler . directio ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class IdentityFlow < T > extends FlowDescription { private In < T > in ; private Out < T > out ; public IdentityFlow ( In < T > in , Out < T > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . directio ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Scanner ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Text ; import org . junit . Rule ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . junit . runners . Parameterized ; import org . junit . runners . Parameterized . Parameters ; import com . asakusafw . compiler . directio . testing . model . Line1 ; import com . asakusafw . compiler . directio . testing . model . Line2 ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . directio . DirectFileInputDescription ; import com . asakusafw . vocabulary . directio . DirectFileOutputDescription ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; @ RunWith ( Parameterized . class ) public class DirectFileIoProcessorRunTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; private final Class < ? extends DataFormat < Text > > format ; @ Parameters public static List < Object [ ] > data ( ) { return Arrays . asList ( new Object [ ] [ ] { { LineFormat . class } , { LineFileFormat . class } , } ) ; } public DirectFileIoProcessorRunTest ( Class < ? extends DataFormat < Text > > format ) { this . format = format ; } @ Test public void simple ( ) throws Exception { put ( "" , "" , "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void tiny ( ) throws Exception { put ( "" , "" , "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( Line1 . class , format , "" , "" , DataSize . TINY ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void input_multi ( ) throws Exception { put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void order ( ) throws Exception { put ( "" , "" , "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; assertThat ( get ( "" ) , is ( list ( "" , "" , "" ) ) ) ; } @ Test public void partition ( ) throws Exception { put ( "" , "" , "" , "" , "" , "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; assertThat ( get ( "" ) , is ( list ( "" ) ) ) ; assertThat ( get ( "" ) , is ( list ( "" , "" ) ) ) ; assertThat ( get ( "" ) , is ( list ( "" , "" , "" ) ) ) ; } @ Test public void random ( ) throws Exception { List < String > lines = Lists . create ( ) ; for ( int i = ; i < ; i ++ ) { lines . add ( String . format ( "" , i ) ) ; } put ( "" , lines . toArray ( new String [ lines . size ( ) ] ) ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > o1 = get ( "" ) ; List < String > o2 = get ( "" ) ; List < String > o3 = get ( "" ) ; List < String > o4 = get ( "" ) ; assertThat ( o1 . size ( ) , is ( greaterThan ( ) ) ) ; assertThat ( o2 . size ( ) , is ( greaterThan ( ) ) ) ; assertThat ( o3 . size ( ) , is ( greaterThan ( ) ) ) ; assertThat ( o4 . size ( ) , is ( greaterThan ( ) ) ) ; List < String > results = Lists . create ( ) ; results . addAll ( o1 ) ; results . addAll ( o2 ) ; results . addAll ( o3 ) ; results . addAll ( o4 ) ; Collections . sort ( results ) ; assertThat ( results , is ( lines ) ) ; } @ Test public void wildcard ( ) throws Exception { put ( "" , "" , "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void variable ( ) throws Exception { put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void variable_wildcard ( ) throws Exception { put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void delete ( ) throws Exception { put ( "" , "" , "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) . delete ( "" ) . delete ( "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void delete_variable ( ) throws Exception { put ( "" , "" , "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) . delete ( "" ) ) ; tester . variables ( ) . defineVariable ( "" , "" ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void input_empty ( ) throws Exception { put ( "" ) ; put ( "" ) ; put ( "" ) ; put ( "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < Path > list = find ( "" ) ; assertThat ( list . toString ( ) , list . size ( ) , is ( ) ) ; } @ Test public void input_empty_noreduce ( ) throws Exception { put ( "" ) ; put ( "" ) ; put ( "" ) ; put ( "" , "" ) ; In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( true ) ) ; List < Path > list = find ( "" ) ; assertThat ( list . toString ( ) , list . size ( ) , is ( ) ) ; } @ Test public void dual_io ( ) throws Exception { put ( "" , "" ) ; put ( "" , "" ) ; In < Line1 > in1 = tester . input ( "" , new Input ( Line1 . class , format , "" , "" , DataSize . LARGE ) ) ; In < Line2 > in2 = tester . input ( "" , new Input ( Line2 . class , format , "" , "" , DataSize . TINY ) ) ; Out < Line1 > out1 = tester . output ( "" , new Output ( Line1 . class , format , "" , "" ) ) ; Out < Line2 > out2 = tester . output ( "" , new Output ( Line2 . class , format , "" , "" ) ) ; assertThat ( tester . runFlow ( new DualIdentityFlow < Line1 , Line2 > ( in1 , in2 , out1 , out2 ) ) , is ( true ) ) ; assertThat ( get ( "" ) , is ( list ( "" ) ) ) ; assertThat ( get ( "" ) , is ( list ( "" ) ) ) ; } @ Test public void dual_io_noreduce ( ) throws Exception { put ( "" , "" ) ; put ( "" , "" ) ; In < Line1 > in1 = tester . input ( "" , new Input ( Line1 . class , format , "" , "" , DataSize . LARGE ) ) ; In < Line2 > in2 = tester . input ( "" , new Input ( Line2 . class , format , "" , "" , DataSize . TINY ) ) ; Out < Line1 > out1 = tester . output ( "" , new Output ( Line1 . class , format , "" , "" ) ) ; Out < Line2 > out2 = tester . output ( "" , new Output ( Line2 . class , format , "" , "" ) ) ; assertThat ( tester . runFlow ( new DualIdentityFlow < Line1 , Line2 > ( in1 , in2 , out1 , out2 ) ) , is ( true ) ) ; assertThat ( get ( "" ) , is ( list ( "" ) ) ) ; assertThat ( get ( "" ) , is ( list ( "" ) ) ) ; } @ Test public void dual_io_mixed ( ) throws Exception { put ( "" , "" ) ; put ( "" , "" ) ; In < Line1 > in1 = tester . input ( "" , new Input ( Line1 . class , format , "" , "" , DataSize . LARGE ) ) ; In < Line2 > in2 = tester . input ( "" , new Input ( Line2 . class , format , "" , "" , DataSize . TINY ) ) ; Out < Line1 > out1 = tester . output ( "" , new Output ( Line1 . class , format , "" , "" ) ) ; Out < Line2 > out2 = tester . output ( "" , new Output ( Line2 . class , format , "" , "" ) ) ; assertThat ( tester . runFlow ( new DualIdentityFlow < Line1 , Line2 > ( in1 , in2 , out1 , out2 ) ) , is ( true ) ) ; assertThat ( get ( "" ) , is ( list ( "" ) ) ) ; assertThat ( get ( "" ) , is ( list ( "" ) ) ) ; } @ Test public void input_missing ( ) throws Exception { In < Line1 > in = tester . input ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = tester . output ( "" , new Output ( format , "" , "" ) ) ; assertThat ( tester . runFlow ( new IdentityFlow < Line1 > ( in , out ) ) , is ( false ) ) ; } private List < String > list ( String ... values ) { return Arrays . asList ( values ) ; } private Path getPath ( String target ) { return new Path ( "" , target ) ; } private List < Path > find ( String target ) throws IOException { FileSystem fs = FileSystem . get ( tester . configuration ( ) ) ; FileStatus [ ] list = fs . globStatus ( getPath ( target ) ) ; if ( list == null ) { return Collections . emptyList ( ) ; } List < Path > results = Lists . create ( ) ; for ( FileStatus file : list ) { results . add ( file . getPath ( ) ) ; } return results ; } private List < String > get ( String target ) throws IOException { FileSystem fs = FileSystem . get ( tester . configuration ( ) ) ; List < String > results = Lists . create ( ) ; for ( Path path : find ( target ) ) { InputStream input = fs . open ( path ) ; try { Scanner s = new Scanner ( new InputStreamReader ( input , "" ) ) ; while ( s . hasNextLine ( ) ) { results . add ( s . nextLine ( ) ) ; } s . close ( ) ; } finally { input . close ( ) ; } } return results ; } private void put ( String target , String ... contents ) throws IOException { FileSystem fs = FileSystem . get ( tester . configuration ( ) ) ; OutputStream output = fs . create ( getPath ( target ) , true ) ; try { PrintWriter w = new PrintWriter ( new OutputStreamWriter ( output , "" ) ) ; for ( String line : contents ) { w . println ( line ) ; } w . close ( ) ; } finally { output . close ( ) ; } } private static class Input extends DirectFileInputDescription { private final Class < ? > modelType ; private final Class < ? extends DataFormat < ? > > format ; private final String basePath ; private final String resourcePattern ; private final DataSize dataSize ; Input ( Class < ? > modelType , Class < ? extends DataFormat < ? > > format , String basePath , String resourcePattern , DataSize dataSize ) { this . modelType = modelType ; this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . format = format ; this . dataSize = dataSize ; } Input ( Class < ? extends DataFormat < ? > > format , String basePath , String resourcePattern ) { this . modelType = Line1 . class ; this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . format = format ; this . dataSize = DataSize . UNKNOWN ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public Class < ? extends DataFormat < ? > > getFormat ( ) { return format ; } @ Override public String getBasePath ( ) { return basePath ; } @ Override public String getResourcePattern ( ) { return resourcePattern ; } @ Override public DataSize getDataSize ( ) { return dataSize ; } } private static class Output extends DirectFileOutputDescription { private final Class < ? > modelType ; private final Class < ? extends DataFormat < ? > > format ; private final String basePath ; private final String resourcePattern ; private final String [ ] order ; private final List < String > deletes = Lists . create ( ) ; Output ( Class < ? > modelType , Class < ? extends DataFormat < ? > > format , String basePath , String resourcePattern , String ... order ) { this . modelType = modelType ; this . format = format ; this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . order = order ; } Output ( Class < ? extends DataFormat < ? > > format , String basePath , String resourcePattern , String ... order ) { this . modelType = Line1 . class ; this . format = format ; this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . order = order ; } Output delete ( String pattern ) { deletes . add ( pattern ) ; return this ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public Class < ? extends DataFormat < ? > > getFormat ( ) { return format ; } @ Override public String getBasePath ( ) { return basePath ; } @ Override public String getResourcePattern ( ) { return resourcePattern ; } @ Override public List < String > getOrder ( ) { return Arrays . asList ( order ) ; } @ Override public List < String > getDeletePatterns ( ) { return deletes ; } } } package com . asakusafw . compiler . directio ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . Text ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import org . junit . runner . RunWith ; import org . junit . runners . Parameterized ; import org . junit . runners . Parameterized . Parameters ; import com . asakusafw . compiler . directio . testing . model . Line1 ; import com . asakusafw . compiler . directio . testing . model . Line2 ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowDescriptionDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectExporterDescription ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . DirectImporterDescription ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . directio . DirectFileInputDescription ; import com . asakusafw . vocabulary . directio . DirectFileOutputDescription ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; @ RunWith ( Parameterized . class ) public class DirectFileIoProcessorTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; private final Class < ? extends DataFormat < Text > > format ; @ Parameters public static List < Object [ ] > data ( ) { return Arrays . asList ( new Object [ ] [ ] { { LineFormat . class } , { LineFileFormat . class } , } ) ; } public DirectFileIoProcessorTest ( Class < ? extends DataFormat < Text > > format ) { this . format = format ; } @ Test public void validate ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_dual ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in1 = flow . createIn ( "" , new Input ( Line1 . class , format , "" , "" , DataSize . LARGE ) ) ; In < Line2 > in2 = flow . createIn ( "" , new Input ( Line2 . class , format , "" , "" , DataSize . TINY ) ) ; Out < Line1 > out1 = flow . createOut ( "" , new Output ( Line1 . class , format , "" , "" ) ) ; Out < Line2 > out2 = flow . createOut ( "" , new Output ( Line2 . class , format , "" , "" ) ) ; FlowDescription desc = new DualIdentityFlow < Line1 , Line2 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_no_input ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new DirectImporterDescription ( Line1 . class , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_no_output ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new DirectExporterDescription ( Line1 . class , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_input_tiny ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( Line1 . class , format , "" , "" , DataSize . TINY ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_input_variable ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_output_pattern ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_output_variable ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_output_wildcard ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_output_asc ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_output_desc ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_output_complexorder ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_output_delete ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) . delete ( "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void validate_output_complexdelete ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) . delete ( "" ) . delete ( "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void invalid_input_resource ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( Line1 . class , format , "" , "" , DataSize . UNKNOWN ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void no_input_format ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( Line1 . class , null , "" , "" , DataSize . UNKNOWN ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_input_format ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( Line1 . class , PrivateFormat . class , "" , "" , DataSize . UNKNOWN ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void inconsistent_input_format ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( Line1 . class , VoidFormat . class , "" , "" , DataSize . UNKNOWN ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_output_resource ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( Line1 . class , format , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_output_order ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( Line1 . class , format , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_output_wildcard_and_property ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( Line1 . class , format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_output_wildcard_and_random ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( Line1 . class , format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_output_wildcard_and_order ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( Line1 . class , format , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_output_delete ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) . delete ( "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void no_output_format ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( Line1 . class , null , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_output_format ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( Line1 . class , PrivateFormat . class , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void inconsistent_output_format ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( Line1 . class , VoidFormat . class , "" , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void input_conflict_output ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void input_contains_output ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void output_contains_input ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new IdentityFlow < Line1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void output_conflict_output ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in1 = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; In < Line1 > in2 = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out1 = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; Out < Line1 > out2 = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new DualIdentityFlow < Line1 , Line1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void output_common_prefix ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in1 = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; In < Line1 > in2 = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out1 = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; Out < Line1 > out2 = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new DualIdentityFlow < Line1 , Line1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void output_contains_output ( ) { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Line1 > in1 = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; In < Line1 > in2 = flow . createIn ( "" , new Input ( format , "" , "" ) ) ; Out < Line1 > out1 = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; Out < Line1 > out2 = flow . createOut ( "" , new Output ( format , "" , "" ) ) ; FlowDescription desc = new DualIdentityFlow < Line1 , Line1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } JobflowInfo compile ( FlowDescriptionDriver flow , FlowDescription desc ) { try { return DirectFlowCompiler . compile ( flow . createFlowGraph ( desc ) , "" , "" , "" , Location . fromPath ( "" , '' ) , folder . newFolder ( "" ) , Collections . < File > emptyList ( ) , getClass ( ) . getClassLoader ( ) , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } } private static class Input extends DirectFileInputDescription { private final Class < ? > modelType ; private final Class < ? extends DataFormat < ? > > format ; private final String basePath ; private final String resourcePattern ; private final DataSize dataSize ; Input ( Class < ? > modelType , Class < ? extends DataFormat < ? > > format , String basePath , String resourcePattern , DataSize dataSize ) { this . modelType = modelType ; this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . format = format ; this . dataSize = dataSize ; } Input ( Class < ? extends DataFormat < ? > > format , String basePath , String resourcePattern ) { this . modelType = Line1 . class ; this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . format = format ; this . dataSize = DataSize . UNKNOWN ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public Class < ? extends DataFormat < ? > > getFormat ( ) { return format ; } @ Override public String getBasePath ( ) { return basePath ; } @ Override public String getResourcePattern ( ) { return resourcePattern ; } @ Override public DataSize getDataSize ( ) { return dataSize ; } } private static class Output extends DirectFileOutputDescription { private final Class < ? > modelType ; private final Class < ? extends DataFormat < ? > > format ; private final String basePath ; private final String resourcePattern ; private final String [ ] order ; private final List < String > deletes = Lists . create ( ) ; Output ( Class < ? > modelType , Class < ? extends DataFormat < ? > > format , String basePath , String resourcePattern , String ... order ) { this . modelType = modelType ; this . format = format ; this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . order = order ; } Output ( Class < ? extends DataFormat < ? > > format , String basePath , String resourcePattern , String ... order ) { this . modelType = Line1 . class ; this . format = format ; this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . order = order ; } Output delete ( String pattern ) { deletes . add ( pattern ) ; return this ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public Class < ? extends DataFormat < ? > > getFormat ( ) { return format ; } @ Override public String getBasePath ( ) { return basePath ; } @ Override public String getResourcePattern ( ) { return resourcePattern ; } @ Override public List < String > getOrder ( ) { return Arrays . asList ( order ) ; } @ Override public List < String > getDeletePatterns ( ) { return deletes ; } } protected abstract static class MockAbstractFormat < T > extends BinaryStreamFormat < T > { private final Class < T > type ; public MockAbstractFormat ( Class < T > type ) { this . type = type ; } @ Override public Class < T > getSupportedType ( ) { return type ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public ModelInput < T > createInput ( Class < ? extends T > dataType , String path , InputStream stream , long offset , long fragmentSize ) throws IOException , InterruptedException { return null ; } @ Override public ModelOutput < T > createOutput ( Class < ? extends T > dataType , String path , OutputStream stream ) throws IOException , InterruptedException { return null ; } } public static class VoidFormat extends MockAbstractFormat < Void > { public VoidFormat ( ) { super ( Void . class ) ; } } private static final class PrivateFormat extends MockAbstractFormat < Object > { private PrivateFormat ( ) { super ( Object . class ) ; } } } package com . asakusafw . compiler . directio . testing . model ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . directio . testing . io . LineInput ; import com . asakusafw . compiler . directio . testing . io . LineOutput ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( LineInput . class ) @ ModelOutputLocation ( LineOutput . class ) @ PropertyOrder ( { "" , "" , "" , "" } ) public interface Line extends Writable { Text getValue ( ) ; void setValue ( Text value0 ) ; StringOption getValueOption ( ) ; void setValueOption ( StringOption option ) ; Text getFirst ( ) ; void setFirst ( Text value0 ) ; StringOption getFirstOption ( ) ; void setFirstOption ( StringOption option ) ; long getPosition ( ) ; void setPosition ( long value0 ) ; LongOption getPositionOption ( ) ; void setPositionOption ( LongOption option ) ; int getLength ( ) ; void setLength ( int value0 ) ; IntOption getLengthOption ( ) ; void setLengthOption ( IntOption option ) ; String getValueAsString ( ) ; void setValueAsString ( String value0 ) ; String getFirstAsString ( ) ; void setFirstAsString ( String first0 ) ; } package com . asakusafw . compiler . directio . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . directio . testing . io . Line2Input ; import com . asakusafw . compiler . directio . testing . io . Line2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Line2Input . class ) @ ModelOutputLocation ( Line2Output . class ) @ PropertyOrder ( { "" , "" , "" , "" } ) public class Line2 implements DataModel < Line2 > , Line , Writable { private final StringOption value = new StringOption ( ) ; private final StringOption first = new StringOption ( ) ; private final LongOption position = new LongOption ( ) ; private final IntOption length = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . value . setNull ( ) ; this . first . setNull ( ) ; this . position . setNull ( ) ; this . length . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Line2 other ) { this . value . copyFrom ( other . value ) ; this . first . copyFrom ( other . first ) ; this . position . copyFrom ( other . position ) ; this . length . copyFrom ( other . length ) ; } @ Override public Text getValue ( ) { return this . value . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setValue ( Text value0 ) { this . value . modify ( value0 ) ; } @ Override public StringOption getValueOption ( ) { return this . value ; } @ Override @ SuppressWarnings ( "" ) public void setValueOption ( StringOption option ) { this . value . copyFrom ( option ) ; } @ Override public Text getFirst ( ) { return this . first . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setFirst ( Text value0 ) { this . first . modify ( value0 ) ; } @ Override public StringOption getFirstOption ( ) { return this . first ; } @ Override @ SuppressWarnings ( "" ) public void setFirstOption ( StringOption option ) { this . first . copyFrom ( option ) ; } @ Override public long getPosition ( ) { return this . position . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setPosition ( long value0 ) { this . position . modify ( value0 ) ; } @ Override public LongOption getPositionOption ( ) { return this . position ; } @ Override @ SuppressWarnings ( "" ) public void setPositionOption ( LongOption option ) { this . position . copyFrom ( option ) ; } @ Override public int getLength ( ) { return this . length . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setLength ( int value0 ) { this . length . modify ( value0 ) ; } @ Override public IntOption getLengthOption ( ) { return this . length ; } @ Override @ SuppressWarnings ( "" ) public void setLengthOption ( IntOption option ) { this . length . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . first ) ; result . append ( "" ) ; result . append ( this . position ) ; result . append ( "" ) ; result . append ( this . length ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + value . hashCode ( ) ; result = prime * result + first . hashCode ( ) ; result = prime * result + position . hashCode ( ) ; result = prime * result + length . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Line2 other = ( Line2 ) obj ; if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . first . equals ( other . first ) == false ) { return false ; } if ( this . position . equals ( other . position ) == false ) { return false ; } if ( this . length . equals ( other . length ) == false ) { return false ; } return true ; } @ Override public String getValueAsString ( ) { return this . value . getAsString ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setValueAsString ( String value0 ) { this . value . modify ( value0 ) ; } @ Override public String getFirstAsString ( ) { return this . first . getAsString ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setFirstAsString ( String first0 ) { this . first . modify ( first0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { value . write ( out ) ; first . write ( out ) ; position . write ( out ) ; length . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { value . readFields ( in ) ; first . readFields ( in ) ; position . readFields ( in ) ; length . readFields ( in ) ; } } package com . asakusafw . compiler . directio . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . directio . testing . io . Line1Input ; import com . asakusafw . compiler . directio . testing . io . Line1Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Line1Input . class ) @ ModelOutputLocation ( Line1Output . class ) @ PropertyOrder ( { "" , "" , "" , "" } ) public class Line1 implements DataModel < Line1 > , Line , Writable { private final StringOption value = new StringOption ( ) ; private final StringOption first = new StringOption ( ) ; private final LongOption position = new LongOption ( ) ; private final IntOption length = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . value . setNull ( ) ; this . first . setNull ( ) ; this . position . setNull ( ) ; this . length . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Line1 other ) { this . value . copyFrom ( other . value ) ; this . first . copyFrom ( other . first ) ; this . position . copyFrom ( other . position ) ; this . length . copyFrom ( other . length ) ; } @ Override public Text getValue ( ) { return this . value . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setValue ( Text value0 ) { this . value . modify ( value0 ) ; } @ Override public StringOption getValueOption ( ) { return this . value ; } @ Override @ SuppressWarnings ( "" ) public void setValueOption ( StringOption option ) { this . value . copyFrom ( option ) ; } @ Override public Text getFirst ( ) { return this . first . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setFirst ( Text value0 ) { this . first . modify ( value0 ) ; } @ Override public StringOption getFirstOption ( ) { return this . first ; } @ Override @ SuppressWarnings ( "" ) public void setFirstOption ( StringOption option ) { this . first . copyFrom ( option ) ; } @ Override public long getPosition ( ) { return this . position . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setPosition ( long value0 ) { this . position . modify ( value0 ) ; } @ Override public LongOption getPositionOption ( ) { return this . position ; } @ Override @ SuppressWarnings ( "" ) public void setPositionOption ( LongOption option ) { this . position . copyFrom ( option ) ; } @ Override public int getLength ( ) { return this . length . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setLength ( int value0 ) { this . length . modify ( value0 ) ; } @ Override public IntOption getLengthOption ( ) { return this . length ; } @ Override @ SuppressWarnings ( "" ) public void setLengthOption ( IntOption option ) { this . length . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . first ) ; result . append ( "" ) ; result . append ( this . position ) ; result . append ( "" ) ; result . append ( this . length ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + value . hashCode ( ) ; result = prime * result + first . hashCode ( ) ; result = prime * result + position . hashCode ( ) ; result = prime * result + length . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Line1 other = ( Line1 ) obj ; if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . first . equals ( other . first ) == false ) { return false ; } if ( this . position . equals ( other . position ) == false ) { return false ; } if ( this . length . equals ( other . length ) == false ) { return false ; } return true ; } @ Override public String getValueAsString ( ) { return this . value . getAsString ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setValueAsString ( String value0 ) { this . value . modify ( value0 ) ; } @ Override public String getFirstAsString ( ) { return this . first . getAsString ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setFirstAsString ( String first0 ) { this . first . modify ( first0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { value . write ( out ) ; first . write ( out ) ; position . write ( out ) ; length . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { value . readFields ( in ) ; first . readFields ( in ) ; position . readFields ( in ) ; length . readFields ( in ) ; } } package com . asakusafw . compiler . directio . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . directio . testing . model . Line1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Line1Input implements ModelInput < Line1 > { private final RecordParser parser ; public Line1Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Line1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getFirstOption ( ) ) ; parser . fill ( model . getPositionOption ( ) ) ; parser . fill ( model . getLengthOption ( ) ) ; parser . endRecord ( ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . directio . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . directio . testing . model . Line1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Line1Output implements ModelOutput < Line1 > { private final RecordEmitter emitter ; public Line1Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Line1 model ) throws IOException { emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getFirstOption ( ) ) ; emitter . emit ( model . getPositionOption ( ) ) ; emitter . emit ( model . getLengthOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . directio . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . directio . testing . model . Line ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class LineInput implements ModelInput < Line > { private final RecordParser parser ; public LineInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Line model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getFirstOption ( ) ) ; parser . fill ( model . getPositionOption ( ) ) ; parser . fill ( model . getLengthOption ( ) ) ; parser . endRecord ( ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . directio . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . directio . testing . model . Line2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Line2Input implements ModelInput < Line2 > { private final RecordParser parser ; public Line2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Line2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getFirstOption ( ) ) ; parser . fill ( model . getPositionOption ( ) ) ; parser . fill ( model . getLengthOption ( ) ) ; parser . endRecord ( ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . directio . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . directio . testing . model . Line2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Line2Output implements ModelOutput < Line2 > { private final RecordEmitter emitter ; public Line2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Line2 model ) throws IOException { emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getFirstOption ( ) ) ; emitter . emit ( model . getPositionOption ( ) ) ; emitter . emit ( model . getLengthOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . directio . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . directio . testing . model . Line ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class LineOutput implements ModelOutput < Line > { private final RecordEmitter emitter ; public LineOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Line model ) throws IOException { emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getFirstOption ( ) ) ; emitter . emit ( model . getPositionOption ( ) ) ; emitter . emit ( model . getLengthOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . dmdl . directio . sequencefile . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Text ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . directio . common . driver . GeneratorTesterRoot ; import com . asakusafw . dmdl . java . emitter . driver . ObjectDriver ; import com . asakusafw . dmdl . java . emitter . driver . WritableDriver ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . hadoop . HadoopFileFormat ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class SequenceFileFormatEmitterTest extends GeneratorTesterRoot { private ClassLoader classLoader ; @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new SequenceFileFormatEmitter ( ) ) ; emitDrivers . add ( new ObjectDriver ( ) ) ; emitDrivers . add ( new WritableDriver ( ) ) ; classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; } @ Override @ After public void tearDown ( ) throws Exception { if ( classLoader != null ) { Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; } } @ Test public void simple ( ) throws Exception { File tempFile = folder . newFile ( "" ) ; Path path = new Path ( tempFile . toURI ( ) ) ; ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; DataFormat < ? > support = ( DataFormat < ? > ) loaded . newObject ( "" , "" ) ; Thread . currentThread ( ) . setContextClassLoader ( support . getClass ( ) . getClassLoader ( ) ) ; Configuration conf = new Configuration ( ) ; FileSystem fs = FileSystem . get ( tempFile . toURI ( ) , conf ) ; if ( support instanceof Configurable ) { ( ( Configurable ) support ) . setConf ( conf ) ; } assertThat ( support . getSupportedType ( ) , is ( ( Object ) model . unwrap ( ) . getClass ( ) ) ) ; HadoopFileFormat < Object > unsafe = unsafe ( support ) ; model . set ( "" , new Text ( "" ) ) ; ModelOutput < Object > writer = unsafe . createOutput ( model . unwrap ( ) . getClass ( ) , fs , path , new Counter ( ) ) ; try { writer . write ( model . unwrap ( ) ) ; } finally { writer . close ( ) ; } ModelInput < Object > reader = unsafe . createInput ( model . unwrap ( ) . getClass ( ) , fs , path , , fs . getFileStatus ( path ) . getLen ( ) , new Counter ( ) ) ; try { Object buffer = loaded . newModel ( "" ) . unwrap ( ) ; assertThat ( reader . readTo ( buffer ) , is ( true ) ) ; assertThat ( buffer , is ( buffer ) ) ; assertThat ( reader . readTo ( buffer ) , is ( false ) ) ; } finally { reader . close ( ) ; } } @ Test public void no_attributes ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; assertThat ( loaded . exists ( "" , "" ) , is ( false ) ) ; } @ SuppressWarnings ( "" ) private HadoopFileFormat < Object > unsafe ( Object support ) { return ( HadoopFileFormat < Object > ) support ; } } package com . asakusafw . dmdl . directio . common . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . lang . reflect . Method ; import java . net . URL ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Locale ; import java . util . regex . Pattern ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . junit . After ; import org . junit . Rule ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . java . emitter . NameConstants ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . java . util . JavaName ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstScript ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . parser . DmdlEmitter ; import com . asakusafw . dmdl . source . DmdlSourceDirectory ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . dmdl . source . DmdlSourceResource ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; public class GeneratorTesterRoot { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; protected final VolatileCompiler compiler = new VolatileCompiler ( ) ; protected final List < JavaDataModelDriver > emitDrivers = Lists . create ( ) ; @ After public void tearDown ( ) throws Exception { compiler . close ( ) ; } protected void emitDmdl ( AstModelDefinition < ? > model ) { AstScript script = new AstScript ( null , Collections . singletonList ( model ) ) ; StringWriter buffer = new StringWriter ( ) ; PrintWriter output = new PrintWriter ( buffer ) ; DmdlEmitter . emit ( script , output ) ; output . close ( ) ; try { File file = folder . newFile ( model . name . identifier + "" ) ; System . out . println ( "" + file . getName ( ) ) ; System . out . println ( buffer . toString ( ) ) ; PrintWriter writer = new PrintWriter ( file , "" ) ; try { writer . print ( buffer . toString ( ) ) ; } finally { writer . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } protected ModelLoader generateJava ( ) { try { List < VolatileJavaFile > files = emit ( new DmdlSourceDirectory ( folder . getRoot ( ) , Charset . forName ( "" ) , Pattern . compile ( "" ) , Pattern . compile ( "" ) ) ) ; ClassLoader loaded = compile ( files ) ; return new ModelLoader ( loaded ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected ModelLoader generateJava ( String name ) { try { List < VolatileJavaFile > files = emit ( collectInput ( name ) ) ; ClassLoader loaded = compile ( files ) ; return new ModelLoader ( loaded ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected void shouldSemanticError ( String name ) { try { emit ( collectInput ( name ) ) ; throw new AssertionError ( "" ) ; } catch ( IOException e ) { } } private ClassLoader compile ( List < VolatileJavaFile > files ) { if ( files . isEmpty ( ) ) { throw new AssertionError ( ) ; } for ( JavaFileObject java : files ) { try { System . out . println ( "" + java . getName ( ) ) ; System . out . println ( java . getCharContent ( true ) ) ; System . out . println ( ) ; System . out . println ( ) ; } catch ( IOException e ) { } compiler . addSource ( java ) ; } compiler . addArguments ( "" ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; boolean hasWrong = false ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) == Diagnostic . Kind . ERROR || d . getKind ( ) == Diagnostic . Kind . WARNING ) { System . out . println ( "" ) ; System . out . println ( d . getMessage ( Locale . getDefault ( ) ) ) ; hasWrong = true ; } } if ( hasWrong ) { throw new AssertionError ( diagnostics ) ; } return compiler . getClassLoader ( ) ; } private List < VolatileJavaFile > emit ( DmdlSourceRepository source ) throws IOException { ModelFactory factory = Models . getModelFactory ( ) ; VolatileEmitter emitter = new VolatileEmitter ( ) ; com . asakusafw . dmdl . java . Configuration conf = new com . asakusafw . dmdl . java . Configuration ( factory , source , Models . toName ( factory , "" ) , emitter , getClass ( ) . getClassLoader ( ) , Locale . getDefault ( ) ) ; com . asakusafw . dmdl . java . GenerateTask task = new com . asakusafw . dmdl . java . GenerateTask ( conf ) ; task . process ( new CompositeDataModelDriver ( emitDrivers ) ) ; return emitter . getEmitted ( ) ; } private DmdlSourceRepository collectInput ( String name ) { URL url = getClass ( ) . getResource ( name + "" ) ; assertThat ( name , url , not ( nullValue ( ) ) ) ; return new DmdlSourceResource ( Collections . singletonList ( url ) , Charset . forName ( "" ) ) ; } protected static class ModelLoader { private final ClassLoader classLoader ; private String namespace ; ModelLoader ( ClassLoader loaded ) { assert loaded != null ; this . classLoader = loaded ; this . namespace = NameConstants . DEFAULT_NAMESPACE ; } public final void setNamespace ( String namespace ) { this . namespace = namespace ; } public Class < ? > modelType ( String name ) { try { return type ( NameConstants . CATEGORY_DATA_MODEL , name ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } } public ModelWrapper newModel ( String name ) { try { Class < ? > loaded = modelType ( name ) ; Object instance = loaded . newInstance ( ) ; return new ModelWrapper ( instance ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public boolean exists ( String category , String name ) { try { type ( category , name ) ; return true ; } catch ( Exception e ) { return false ; } } public Object newObject ( String category , String name ) { try { Class < ? > loaded = type ( category , name ) ; Object instance = loaded . newInstance ( ) ; return instance ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Class < ? > type ( String category , String name ) throws ClassNotFoundException { return classLoader . loadClass ( MessageFormat . format ( "" , "" , namespace , category , name ) ) ; } } @ SuppressWarnings ( "" ) protected static class ModelWrapper { private final DataModel instance ; private Class < ? > interfaceType ; ModelWrapper ( Object instance ) { this . instance = ( DataModel ) instance ; this . interfaceType = instance . getClass ( ) ; } public Object unwrap ( ) { return instance ; } public void setInterfaceType ( Class < ? > interfaceType ) { this . interfaceType = interfaceType ; } public boolean is ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; Object result = invoke ( jn . toMemberName ( ) ) ; return ( Boolean ) result ; } public Object get ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; return invoke ( jn . toMemberName ( ) ) ; } public void set ( String name , Object value ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; invoke ( jn . toMemberName ( ) , value ) ; } public ValueOption < ? > getOption ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; jn . addLast ( "" ) ; return ( ValueOption < ? > ) invoke ( jn . toMemberName ( ) ) ; } public void setOption ( String name , ValueOption < ? > option ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; jn . addLast ( "" ) ; invoke ( jn . toMemberName ( ) , option ) ; } public void reset ( ) { instance . reset ( ) ; } @ SuppressWarnings ( "" ) public void copyFrom ( ModelWrapper wrapper ) { instance . copyFrom ( wrapper . instance ) ; } public Object invoke ( String name , Object ... arguments ) { for ( Method method : interfaceType . getMethods ( ) ) { if ( method . getName ( ) . equals ( name ) ) { try { return method . invoke ( instance , arguments ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } throw new AssertionError ( name ) ; } } } package com . asakusafw . dmdl . directio . common . driver ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . List ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . util . Emitter ; public class VolatileEmitter extends Emitter { private final List < VolatileJavaFile > emitted = Lists . create ( ) ; @ Override public PrintWriter openFor ( PackageDeclaration packageDeclOrNull , String subPath ) throws IOException { StringBuilder buf = new StringBuilder ( ) ; if ( packageDeclOrNull != null ) { buf . append ( packageDeclOrNull . getName ( ) . toNameString ( ) . replace ( '' , '' ) ) ; buf . append ( "" ) ; } assert subPath . endsWith ( "" ) ; buf . append ( subPath . substring ( , subPath . length ( ) - ) ) ; VolatileJavaFile file = new VolatileJavaFile ( buf . toString ( ) ) ; register ( file ) ; return new PrintWriter ( file . openWriter ( ) ) ; } private void register ( VolatileJavaFile file ) { emitted . add ( file ) ; } public List < VolatileJavaFile > getEmitted ( ) { return emitted ; } } package com . asakusafw . dmdl . directio . csv . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . math . BigDecimal ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import java . util . Random ; import org . apache . hadoop . io . Text ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . directio . common . driver . GeneratorTesterRoot ; import com . asakusafw . dmdl . java . emitter . driver . ObjectDriver ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . util . DelimiterRangeInputStream ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . csv . CsvConfiguration ; import com . asakusafw . runtime . io . csv . CsvFormatException ; import com . asakusafw . runtime . io . csv . CsvParser ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . utils . collections . Lists ; public class CsvFormatEmitterTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new CsvFormatEmitter ( ) ) ; emitDrivers . add ( new ObjectDriver ( ) ) ; } @ Test public void simple ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; BinaryStreamFormat < ? > support = ( BinaryStreamFormat < ? > ) loaded . newObject ( "" , "" ) ; assertThat ( support . getSupportedType ( ) , is ( ( Object ) model . unwrap ( ) . getClass ( ) ) ) ; BinaryStreamFormat < Object > unsafe = unsafe ( support ) ; model . set ( "" , new Text ( "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = unsafe . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; Object buffer = loaded . newModel ( "" ) . unwrap ( ) ; ModelInput < Object > reader = unsafe . createInput ( model . unwrap ( ) . getClass ( ) , "" , in ( output ) , , size ( output ) ) ; assertThat ( reader . readTo ( buffer ) , is ( true ) ) ; assertThat ( buffer , is ( buffer ) ) ; assertThat ( reader . readTo ( buffer ) , is ( false ) ) ; } @ Test public void types ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; BinaryStreamFormat < ? > support = ( BinaryStreamFormat < ? > ) loaded . newObject ( "" , "" ) ; assertThat ( support . getSupportedType ( ) , is ( ( Object ) model . unwrap ( ) . getClass ( ) ) ) ; ModelWrapper empty = loaded . newModel ( "" ) ; ModelWrapper all = loaded . newModel ( "" ) ; all . set ( "" , ) ; all . set ( "" , new Text ( "" ) ) ; all . set ( "" , true ) ; all . set ( "" , ( byte ) ) ; all . set ( "" , ( short ) ) ; all . set ( "" , ) ; all . set ( "" , ) ; all . set ( "" , ) ; all . set ( "" , new BigDecimal ( "" ) ) ; all . set ( "" , new Date ( , , ) ) ; all . set ( "" , new DateTime ( , , , , , ) ) ; BinaryStreamFormat < Object > unsafe = unsafe ( support ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = unsafe . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; writer . write ( empty . unwrap ( ) ) ; writer . write ( all . unwrap ( ) ) ; writer . close ( ) ; Object buffer = loaded . newModel ( "" ) . unwrap ( ) ; ModelInput < Object > reader = unsafe . createInput ( model . unwrap ( ) . getClass ( ) , "" , in ( output ) , , size ( output ) ) ; assertThat ( reader . readTo ( buffer ) , is ( true ) ) ; assertThat ( buffer , is ( empty . unwrap ( ) ) ) ; assertThat ( reader . readTo ( buffer ) , is ( true ) ) ; assertThat ( buffer , is ( all . unwrap ( ) ) ) ; assertThat ( reader . readTo ( buffer ) , is ( false ) ) ; } @ Test public void attributes ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; model . set ( "" , new Text ( "" ) ) ; model . set ( "" , true ) ; model . set ( "" , false ) ; model . set ( "" , new Date ( , , ) ) ; model . set ( "" , new DateTime ( , , , , , ) ) ; BinaryStreamFormat < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = support . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; String [ ] [ ] results = parse ( , new String ( output . toByteArray ( ) , "" ) ) ; assertThat ( results , is ( new String [ ] [ ] { { "" , "" , "" , "" , "" } , { "" , "" , "" , "" , "" } , } ) ) ; } @ Test public void header ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; BinaryStreamFormat < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = support . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; model . set ( "" , new Text ( "" ) ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; String [ ] [ ] results = parse ( , new String ( output . toByteArray ( ) , "" ) ) ; assertThat ( results , is ( new String [ ] [ ] { { "" } , { "" } , } ) ) ; } @ Test public void implicit_field_name ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; BinaryStreamFormat < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = support . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; model . set ( "" , new Text ( "" ) ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; String [ ] [ ] results = parse ( , new String ( output . toByteArray ( ) , "" ) ) ; assertThat ( results , is ( new String [ ] [ ] { { "" } , { "" } , } ) ) ; } @ Test public void file_name ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; BinaryStreamFormat < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; assertThat ( support . getMinimumFragmentSize ( ) , is ( greaterThan ( ) ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = support . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; model . set ( "" , new Text ( "" ) ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; ModelInput < Object > reader = support . createInput ( model . unwrap ( ) . getClass ( ) , "" , in ( output ) , , size ( output ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( false ) ) ; } @ Test public void line_number ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; model . set ( "" , new Text ( "" ) ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; BinaryStreamFormat < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = support . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; ModelInput < Object > reader = support . createInput ( model . unwrap ( ) . getClass ( ) , "" , in ( output ) , , size ( output ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( false ) ) ; } @ Test public void record_number ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; model . set ( "" , new Text ( "" ) ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; BinaryStreamFormat < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = support . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; ModelInput < Object > reader = support . createInput ( model . unwrap ( ) . getClass ( ) , "" , in ( output ) , , size ( output ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( false ) ) ; } @ Test public void ignore ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; model . set ( "" , new Text ( "" ) ) ; model . set ( "" , new Text ( "" ) ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; BinaryStreamFormat < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = support . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; ModelInput < Object > reader = support . createInput ( model . unwrap ( ) . getClass ( ) , "" , in ( output ) , , size ( output ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( false ) ) ; } @ Test public void fragmentation ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; Random random = new Random ( ) ; for ( int i = ; i < ; i ++ ) { fragmentation_attempt ( loaded , random ) ; } } @ Test public void fragmentation_header ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; Random random = new Random ( ) ; for ( int i = ; i < ; i ++ ) { fragmentation_attempt ( loaded , random ) ; } } private void fragmentation_attempt ( ModelLoader loaded , Random random ) throws Exception { ModelWrapper model = loaded . newModel ( "" ) ; BinaryStreamFormat < ? > support = ( BinaryStreamFormat < ? > ) loaded . newObject ( "" , "" ) ; assertThat ( support . getSupportedType ( ) , is ( ( Object ) model . unwrap ( ) . getClass ( ) ) ) ; BinaryStreamFormat < Object > unsafe = unsafe ( support ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = unsafe . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; List < Object > expected = Lists . create ( ) ; for ( int line = ; line < ; line ++ ) { ModelWrapper buffer = loaded . newModel ( "" ) ; buffer . set ( "" , new Text ( "" + ( line * ) ) ) ; buffer . set ( "" , new Text ( "" + random . nextInt ( ) ) ) ; buffer . set ( "" , new Text ( "" + random . nextInt ( ) ) ) ; writer . write ( buffer . unwrap ( ) ) ; expected . add ( buffer . unwrap ( ) ) ; } writer . close ( ) ; byte [ ] bytes = output . toByteArray ( ) ; for ( int attempt = ; attempt < ; attempt ++ ) { List < Object > actual = Lists . create ( ) ; int [ ] fragment = new int [ random . nextInt ( ) + ] ; fragment [ ] = output . size ( ) ; for ( int i = ; i < fragment . length ; i ++ ) { fragment [ i ] = random . nextInt ( output . size ( ) + ) ; } Arrays . sort ( fragment ) ; int start = ; for ( int i = ; i < fragment . length ; i ++ ) { int offset = start ; int length = fragment [ i ] - offset ; InputStream in = new ByteArrayInputStream ( bytes , offset , bytes . length - offset ) ; in . mark ( bytes . length - offset ) ; ModelInput < Object > reader = unsafe . createInput ( model . unwrap ( ) . getClass ( ) , "" , in , offset , length ) ; try { while ( true ) { Object buffer = loaded . newModel ( "" ) . unwrap ( ) ; if ( reader . readTo ( buffer ) == false ) { break ; } actual . add ( buffer ) ; } } catch ( CsvFormatException e ) { InputStream reIn = new ByteArrayInputStream ( bytes , offset , bytes . length - offset ) ; InputStream copy = new DelimiterRangeInputStream ( reIn , '' , length , offset > ) ; System . out . println ( copy . read ( ) ) ; throw new IOException ( MessageFormat . format ( "" , attempt , offset , length , bytes . length , new String ( bytes , offset , length , "" ) ) , e ) ; } start = fragment [ i ] ; } assertThat ( actual , is ( expected ) ) ; } } @ Test public void fragmentation_restricted ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; BinaryStreamFormat < ? > support = ( BinaryStreamFormat < ? > ) loaded . newObject ( "" , "" ) ; BinaryStreamFormat < Object > unsafe = unsafe ( support ) ; model . set ( "" , new Text ( "" ) ) ; model . set ( "" , new Text ( "" ) ) ; model . set ( "" , new Text ( "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ModelOutput < Object > writer = unsafe . createOutput ( model . unwrap ( ) . getClass ( ) , "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . close ( ) ; try { unsafe . createInput ( model . unwrap ( ) . getClass ( ) , "" , in ( output ) , , size ( output ) ) ; fail ( ) ; } catch ( Exception e ) { } } @ Test public void no_attributes ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; assertThat ( loaded . exists ( "" , "" ) , is ( false ) ) ; } @ Test public void invalid_file_name ( ) throws Exception { shouldSemanticError ( "" ) ; } @ Test public void invalid_line_number ( ) throws Exception { shouldSemanticError ( "" ) ; } @ Test public void invalid_record_number ( ) throws Exception { shouldSemanticError ( "" ) ; } private String [ ] [ ] parse ( int columns , String string ) { CsvConfiguration conf = new CsvConfiguration ( CsvConfiguration . DEFAULT_CHARSET , CsvConfiguration . DEFAULT_HEADER_CELLS , CsvConfiguration . DEFAULT_TRUE_FORMAT , CsvConfiguration . DEFAULT_FALSE_FORMAT , CsvConfiguration . DEFAULT_DATE_FORMAT , CsvConfiguration . DEFAULT_DATE_TIME_FORMAT ) ; ByteArrayInputStream input = new ByteArrayInputStream ( string . getBytes ( conf . getCharset ( ) ) ) ; CsvParser parser = new CsvParser ( input , string , conf ) ; List < String [ ] > results = Lists . create ( ) ; try { StringOption buffer = new StringOption ( ) ; while ( parser . next ( ) ) { String [ ] line = new String [ columns ] ; for ( int i = ; i < columns ; i ++ ) { parser . fill ( buffer ) ; line [ i ] = buffer . or ( ( String ) null ) ; } parser . endRecord ( ) ; results . add ( line ) ; } parser . close ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } return results . toArray ( new String [ results . size ( ) ] [ ] ) ; } @ Test public void invalid_attribute ( ) throws Exception { shouldSemanticError ( "" ) ; } @ SuppressWarnings ( "" ) private BinaryStreamFormat < Object > unsafe ( Object support ) { return ( BinaryStreamFormat < Object > ) support ; } private ByteArrayInputStream in ( ByteArrayOutputStream output ) { return new ByteArrayInputStream ( output . toByteArray ( ) ) ; } private long size ( ByteArrayOutputStream output ) { return output . size ( ) ; } } package com . asakusafw . dmdl . directio . sequencefile . driver ; import java . util . Map ; import com . asakusafw . dmdl . directio . sequencefile . driver . SequenceFileFormatTrait . Configuration ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . spi . ModelAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class SequenceFileFormatDriver extends ModelAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; Configuration conf = analyzeConfig ( environment , attribute , elements ) ; if ( conf != null ) { declaration . putTrait ( SequenceFileFormatTrait . class , new SequenceFileFormatTrait ( attribute , conf ) ) ; } } private Configuration analyzeConfig ( DmdlSemantics environment , AstAttribute attribute , Map < String , AstAttributeElement > elements ) { assert environment != null ; assert attribute != null ; assert elements != null ; Configuration result = new Configuration ( ) ; return result ; } } package com . asakusafw . dmdl . directio . sequencefile . driver ; package com . asakusafw . dmdl . directio . sequencefile . driver ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . Trait ; public class SequenceFileFormatTrait implements Trait < SequenceFileFormatTrait > { private final AstNode originalAst ; private final Configuration configuration ; public SequenceFileFormatTrait ( AstNode originalAst , Configuration configuration ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . configuration = configuration ; } public Configuration getConfiguration ( ) { return configuration ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public static class Configuration { } } package com . asakusafw . dmdl . directio . sequencefile . driver ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . NullWritable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . directio . sequencefile . driver . SequenceFileFormatTrait . Configuration ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . runtime . directio . hadoop . HadoopFileFormat ; import com . asakusafw . runtime . directio . hadoop . SequenceFileFormat ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class SequenceFileFormatEmitter extends JavaDataModelDriver { static final Logger LOG = LoggerFactory . getLogger ( SequenceFileFormatEmitter . class ) ; public static final String CATEGORY_STREAM = "" ; @ Override public void generateResources ( EmitContext context , ModelDeclaration model ) throws IOException { if ( isTarget ( model ) == false ) { return ; } Name supportName = generateFormat ( context , model ) ; generateImporter ( context , model , supportName ) ; generateExporter ( context , model , supportName ) ; } private Name generateFormat ( EmitContext context , ModelDeclaration model ) throws IOException { assert context != null ; assert model != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; FormatGenerator . emit ( next , model , model . getTrait ( SequenceFileFormatTrait . class ) . getConfiguration ( ) ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private Name generateImporter ( EmitContext context , ModelDeclaration model , Name supportName ) throws IOException { assert context != null ; assert model != null ; assert supportName != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; DescriptionGenerator . emitImporter ( next , model , supportName ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private Name generateExporter ( EmitContext context , ModelDeclaration model , Name supportName ) throws IOException { assert context != null ; assert model != null ; assert supportName != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; DescriptionGenerator . emitExporter ( next , model , supportName ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private boolean isTarget ( ModelDeclaration model ) { assert model != null ; SequenceFileFormatTrait trait = model . getTrait ( SequenceFileFormatTrait . class ) ; return trait != null ; } private static final class FormatGenerator { private final EmitContext context ; private final ModelDeclaration model ; private final ModelFactory f ; private FormatGenerator ( EmitContext context , ModelDeclaration model , Configuration configuration ) { assert context != null ; assert model != null ; assert configuration != null ; this . context = context ; this . model = model ; this . f = context . getModelFactory ( ) ; } static void emit ( EmitContext context , ModelDeclaration model , Configuration conf ) throws IOException { assert context != null ; assert model != null ; assert conf != null ; FormatGenerator emitter = new FormatGenerator ( context , model , conf ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . linkType ( context . resolve ( model . getSymbol ( ) ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , context . getTypeName ( ) , f . newParameterizedType ( context . resolve ( SequenceFileFormat . class ) , context . resolve ( NullWritable . class ) , context . resolve ( model . getSymbol ( ) ) , context . resolve ( model . getSymbol ( ) ) ) , Collections . < com . asakusafw . utils . java . model . syntax . Type > emptyList ( ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = new ArrayList < TypeBodyDeclaration > ( ) ; results . add ( createGetSupportedType ( ) ) ; results . add ( createCreateKeyObject ( ) ) ; results . add ( createCreateValueObject ( ) ) ; results . add ( createCopyToModel ( ) ) ; results . add ( createCopyFromModel ( ) ) ; return results ; } private MethodDeclaration createGetSupportedType ( ) { MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , f . newParameterizedType ( context . resolve ( Class . class ) , context . resolve ( model . getSymbol ( ) ) ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( new Statement [ ] { new TypeBuilder ( f , context . resolve ( model . getSymbol ( ) ) ) . dotClass ( ) . toReturnStatement ( ) } ) ) ; return decl ; } private MethodDeclaration createCreateKeyObject ( ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( NullWritable . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( f . newBlock ( new TypeBuilder ( f , context . resolve ( NullWritable . class ) ) . method ( "" ) . toReturnStatement ( ) ) ) ) ; } private MethodDeclaration createCreateValueObject ( ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( model . getSymbol ( ) ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( f . newBlock ( new TypeBuilder ( f , context . resolve ( model . getSymbol ( ) ) ) . newObject ( ) . toReturnStatement ( ) ) ) ) ; } private MethodDeclaration createCopyToModel ( ) { SimpleName key = f . newSimpleName ( "" ) ; SimpleName value = f . newSimpleName ( "" ) ; SimpleName internal = f . newSimpleName ( "" ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( context . resolve ( NullWritable . class ) , key ) , f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , value ) , f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , internal ) , } ) , Arrays . asList ( f . newBlock ( new ExpressionBuilder ( f , internal ) . method ( "" , value ) . toStatement ( ) ) ) ) ; } private MethodDeclaration createCopyFromModel ( ) { SimpleName key = f . newSimpleName ( "" ) ; SimpleName value = f . newSimpleName ( "" ) ; SimpleName internal = f . newSimpleName ( "" ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , internal ) , f . newFormalParameterDeclaration ( context . resolve ( NullWritable . class ) , key ) , f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , value ) , } ) , Arrays . asList ( f . newBlock ( new ExpressionBuilder ( f , value ) . method ( "" , internal ) . toStatement ( ) ) ) ) ; } } private static final class DescriptionGenerator { private static final String IMPORTER_TYPE_NAME = "" ; private static final String EXPORTER_TYPE_NAME = "" ; private final EmitContext context ; private final ModelDeclaration model ; private final com . asakusafw . utils . java . model . syntax . Type supportClass ; private final ModelFactory f ; private final boolean importer ; private DescriptionGenerator ( EmitContext context , ModelDeclaration model , Name supportClassName , boolean importer ) { assert context != null ; assert model != null ; assert supportClassName != null ; this . context = context ; this . model = model ; this . f = context . getModelFactory ( ) ; this . importer = importer ; this . supportClass = context . resolve ( supportClassName ) ; } static void emitImporter ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; assert supportClassName != null ; DescriptionGenerator emitter = new DescriptionGenerator ( context , model , supportClassName , true ) ; emitter . emit ( ) ; } static void emitExporter ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; assert supportClassName != null ; DescriptionGenerator emitter = new DescriptionGenerator ( context , model , supportClassName , false ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . linkType ( context . resolve ( model . getSymbol ( ) ) ) . text ( "" , importer ? "" : "" ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Abstract ( ) . toAttributes ( ) , context . getTypeName ( ) , context . resolve ( Models . toName ( f , importer ? IMPORTER_TYPE_NAME : EXPORTER_TYPE_NAME ) ) , Collections . < com . asakusafw . utils . java . model . syntax . Type > emptyList ( ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = new ArrayList < TypeBodyDeclaration > ( ) ; results . add ( createGetModelType ( ) ) ; results . add ( createGetStreamSupport ( ) ) ; return results ; } private MethodDeclaration createGetModelType ( ) { return createGetter ( new TypeBuilder ( f , context . resolve ( Class . class ) ) . parameterize ( f . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , context . resolve ( model . getSymbol ( ) ) ) ) . toType ( ) , "" , f . newClassLiteral ( context . resolve ( model . getSymbol ( ) ) ) ) ; } private MethodDeclaration createGetStreamSupport ( ) { return createGetter ( new TypeBuilder ( f , context . resolve ( Class . class ) ) . parameterize ( supportClass ) . toType ( ) , "" , f . newClassLiteral ( supportClass ) ) ; } private MethodDeclaration createGetter ( com . asakusafw . utils . java . model . syntax . Type type , String name , Expression value ) { assert type != null ; assert name != null ; assert value != null ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , type , f . newSimpleName ( name ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( new ExpressionBuilder ( f , value ) . toReturnStatement ( ) ) ) ; } } } package com . asakusafw . dmdl . directio . csv . driver ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . directio . csv . driver . CsvFieldTrait . Kind ; import com . asakusafw . dmdl . directio . csv . driver . CsvFormatTrait . Configuration ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . util . DelimiterRangeInputStream ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . csv . CsvConfiguration ; import com . asakusafw . runtime . io . csv . CsvEmitter ; import com . asakusafw . runtime . io . csv . CsvParser ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ExpressionStatement ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class CsvFormatEmitter extends JavaDataModelDriver { static final Logger LOG = LoggerFactory . getLogger ( CsvFormatEmitter . class ) ; public static final String CATEGORY_STREAM = "" ; @ Override public void generateResources ( EmitContext context , ModelDeclaration model ) throws IOException { if ( isTarget ( model ) == false ) { return ; } checkPropertyType ( model ) ; Name supportName = generateFormat ( context , model ) ; generateImporter ( context , model , supportName ) ; generateExporter ( context , model , supportName ) ; } private Name generateFormat ( EmitContext context , ModelDeclaration model ) throws IOException { assert context != null ; assert model != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; FormatGenerator . emit ( next , model , model . getTrait ( CsvFormatTrait . class ) . getConfiguration ( ) ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private Name generateImporter ( EmitContext context , ModelDeclaration model , Name supportName ) throws IOException { assert context != null ; assert model != null ; assert supportName != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; DescriptionGenerator . emitImporter ( next , model , supportName ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private Name generateExporter ( EmitContext context , ModelDeclaration model , Name supportName ) throws IOException { assert context != null ; assert model != null ; assert supportName != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; DescriptionGenerator . emitExporter ( next , model , supportName ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private boolean isTarget ( ModelDeclaration model ) { assert model != null ; CsvFormatTrait trait = model . getTrait ( CsvFormatTrait . class ) ; return trait != null ; } private void checkPropertyType ( ModelDeclaration model ) throws IOException { assert model != null ; for ( PropertyDeclaration prop : model . getDeclaredProperties ( ) ) { if ( isValueField ( prop ) ) { Type type = prop . getType ( ) ; if ( ( type instanceof BasicType ) == false ) { throw new IOException ( MessageFormat . format ( "" , type , prop . getOwner ( ) . getName ( ) . identifier , prop . getName ( ) . identifier ) ) ; } } } } static boolean isValueField ( PropertyDeclaration property ) { assert property != null ; return CsvFieldTrait . getKind ( property , Kind . VALUE ) == Kind . VALUE ; } private static final class FormatGenerator { private static final String NAME_READER = "" ; private static final String NAME_WRITER = "" ; private static final String METHOD_CONFIG = "" ; private static final String FIELD_PATH_NAME = "" ; private final EmitContext context ; private final ModelDeclaration model ; private final Configuration conf ; private final ModelFactory f ; private FormatGenerator ( EmitContext context , ModelDeclaration model , Configuration configuration ) { assert context != null ; assert model != null ; assert configuration != null ; this . context = context ; this . model = model ; this . conf = configuration ; this . f = context . getModelFactory ( ) ; } static void emit ( EmitContext context , ModelDeclaration model , Configuration conf ) throws IOException { assert context != null ; assert model != null ; assert conf != null ; FormatGenerator emitter = new FormatGenerator ( context , model , conf ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . linkType ( context . resolve ( model . getSymbol ( ) ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Final ( ) . toAttributes ( ) , context . getTypeName ( ) , f . newParameterizedType ( context . resolve ( BinaryStreamFormat . class ) , context . resolve ( model . getSymbol ( ) ) ) , Collections . < com . asakusafw . utils . java . model . syntax . Type > emptyList ( ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createGetConfiguration ( ) ) ; results . add ( createGetSupportedType ( ) ) ; results . add ( createGetPreferredFragmentSize ( ) ) ; results . add ( createGetMinimumFragmentSize ( ) ) ; results . add ( createCreateReader ( ) ) ; results . add ( createCreateWriter ( ) ) ; results . add ( createReaderClass ( ) ) ; results . add ( createWriterClass ( ) ) ; return results ; } private MethodDeclaration createGetConfiguration ( ) { SimpleName head = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( new TypeBuilder ( f , context . resolve ( Charset . class ) ) . method ( "" , Models . toLiteral ( f , conf . getCharsetName ( ) ) ) . toExpression ( ) ) ; if ( conf . isEnableHeader ( ) ) { SimpleName headers = f . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( ArrayList . class ) ) . parameterize ( context . resolve ( String . class ) ) . newObject ( ) . toLocalVariableDeclaration ( new TypeBuilder ( f , context . resolve ( List . class ) ) . parameterize ( context . resolve ( String . class ) ) . toType ( ) , headers ) ) ; List < Statement > headerStatements = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( isValueField ( property ) ) { String fieldName = CsvFieldTrait . getFieldName ( property ) ; headerStatements . add ( new ExpressionBuilder ( f , headers ) . method ( "" , Models . toLiteral ( f , fieldName ) ) . toStatement ( ) ) ; } } statements . add ( f . newIfStatement ( head , f . newBlock ( headerStatements ) ) ) ; arguments . add ( headers ) ; } else { arguments . add ( new TypeBuilder ( f , context . resolve ( CsvConfiguration . class ) ) . field ( "" ) . toExpression ( ) ) ; } arguments . add ( Models . toLiteral ( f , conf . getTrueFormat ( ) ) ) ; arguments . add ( Models . toLiteral ( f , conf . getFalseFormat ( ) ) ) ; arguments . add ( Models . toLiteral ( f , conf . getDateFormat ( ) ) ) ; arguments . add ( Models . toLiteral ( f , conf . getDateTimeFormat ( ) ) ) ; SimpleName config = f . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( CsvConfiguration . class ) ) . newObject ( arguments ) . toLocalVariableDeclaration ( context . resolve ( CsvConfiguration . class ) , config ) ) ; statements . add ( new ExpressionBuilder ( f , config ) . method ( "" , Models . toLiteral ( f , conf . isAllowLinefeed ( ) ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , config ) . toReturnStatement ( ) ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( head ) . text ( "" ) . returns ( ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Protected ( ) . toAttributes ( ) , context . resolve ( CsvConfiguration . class ) , f . newSimpleName ( METHOD_CONFIG ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( boolean . class ) , head ) ) , statements ) ; } private MethodDeclaration createGetSupportedType ( ) { MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , f . newParameterizedType ( context . resolve ( Class . class ) , context . resolve ( model . getSymbol ( ) ) ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( new Statement [ ] { new TypeBuilder ( f , context . resolve ( model . getSymbol ( ) ) ) . dotClass ( ) . toReturnStatement ( ) } ) ) ; return decl ; } private MethodDeclaration createGetPreferredFragmentSize ( ) { Expression value = Models . toLiteral ( f , - ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( long . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( new ExpressionBuilder ( f , value ) . toReturnStatement ( ) ) ) ; } private MethodDeclaration createGetMinimumFragmentSize ( ) { boolean fastMode = isFastMode ( ) ; Expression value = fastMode ? new TypeBuilder ( f , context . resolve ( Long . class ) ) . field ( "" ) . toExpression ( ) : Models . toLiteral ( f , - ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( long . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( new ExpressionBuilder ( f , value ) . toReturnStatement ( ) ) ) ; } private boolean isFastMode ( ) { if ( conf . isAllowLinefeed ( ) ) { return false ; } for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { switch ( CsvFieldTrait . getKind ( property , Kind . VALUE ) ) { case VALUE : case FILE_NAME : case IGNORE : break ; default : return false ; } } return true ; } private MethodDeclaration createCreateReader ( ) { SimpleName dataType = f . newSimpleName ( "" ) ; SimpleName path = f . newSimpleName ( "" ) ; SimpleName stream = f . newSimpleName ( "" ) ; SimpleName offset = f . newSimpleName ( "" ) ; SimpleName fragmentSize = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( createNullCheck ( dataType ) ) ; statements . add ( createNullCheck ( path ) ) ; statements . add ( createNullCheck ( stream ) ) ; Expression isNotHead = new ExpressionBuilder ( f , offset ) . apply ( InfixOperator . GREATER , Models . toLiteral ( f , ) ) . toExpression ( ) ; if ( isFastMode ( ) == false ) { statements . add ( f . newIfStatement ( isNotHead , f . newBlock ( new TypeBuilder ( f , context . resolve ( IllegalArgumentException . class ) ) . newObject ( Models . toLiteral ( f , MessageFormat . format ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ) ) . toThrowStatement ( ) ) ) ) ; } SimpleName fragmentInput = f . newSimpleName ( "" ) ; statements . add ( f . newLocalVariableDeclaration ( context . resolve ( InputStream . class ) , fragmentInput , null ) ) ; statements . add ( new ExpressionBuilder ( f , fragmentInput ) . assignFrom ( new TypeBuilder ( f , context . resolve ( DelimiterRangeInputStream . class ) ) . newObject ( stream , Models . toLiteral ( f , '' ) , fragmentSize , isNotHead ) . toExpression ( ) ) . toStatement ( ) ) ; SimpleName parser = f . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( CsvParser . class ) ) . newObject ( fragmentInput , path , new ExpressionBuilder ( f , f . newThis ( ) ) . method ( METHOD_CONFIG , new ExpressionBuilder ( f , offset ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , ) ) . toExpression ( ) ) . toExpression ( ) ) . toLocalVariableDeclaration ( context . resolve ( CsvParser . class ) , parser ) ) ; statements . add ( new TypeBuilder ( f , f . newNamedType ( f . newSimpleName ( NAME_READER ) ) ) . newObject ( parser ) . toReturnStatement ( ) ) ; MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , f . newParameterizedType ( context . resolve ( ModelInput . class ) , context . resolve ( model . getSymbol ( ) ) ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( f . newParameterizedType ( context . resolve ( Class . class ) , f . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , context . resolve ( model . getSymbol ( ) ) ) ) , dataType ) , f . newFormalParameterDeclaration ( context . resolve ( String . class ) , path ) , f . newFormalParameterDeclaration ( context . resolve ( InputStream . class ) , stream ) , f . newFormalParameterDeclaration ( context . resolve ( long . class ) , offset ) , f . newFormalParameterDeclaration ( context . resolve ( long . class ) , fragmentSize ) ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ; return decl ; } private MethodDeclaration createCreateWriter ( ) { SimpleName dataType = f . newSimpleName ( "" ) ; SimpleName path = f . newSimpleName ( "" ) ; SimpleName stream = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( createNullCheck ( path ) ) ; statements . add ( createNullCheck ( stream ) ) ; SimpleName emitter = f . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( CsvEmitter . class ) ) . newObject ( stream , path , new ExpressionBuilder ( f , f . newThis ( ) ) . method ( METHOD_CONFIG , Models . toLiteral ( f , true ) ) . toExpression ( ) ) . toLocalVariableDeclaration ( context . resolve ( CsvEmitter . class ) , emitter ) ) ; statements . add ( new TypeBuilder ( f , f . newNamedType ( f . newSimpleName ( NAME_WRITER ) ) ) . newObject ( emitter ) . toReturnStatement ( ) ) ; MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( f . newParameterizedType ( context . resolve ( ModelOutput . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( f . newParameterizedType ( context . resolve ( Class . class ) , f . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , context . resolve ( model . getSymbol ( ) ) ) ) , dataType ) , f . newFormalParameterDeclaration ( context . resolve ( String . class ) , path ) , f . newFormalParameterDeclaration ( context . resolve ( OutputStream . class ) , stream ) ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ; return decl ; } private Statement createNullCheck ( SimpleName parameter ) { assert parameter != null ; return f . newIfStatement ( new ExpressionBuilder ( f , parameter ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new TypeBuilder ( f , context . resolve ( IllegalArgumentException . class ) ) . newObject ( Models . toLiteral ( f , MessageFormat . format ( "" , parameter . getToken ( ) ) ) ) . toThrowStatement ( ) ) ) ; } private ClassDeclaration createReaderClass ( ) { SimpleName parser = f . newSimpleName ( "" ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createPrivateField ( CsvParser . class , parser ) ) ; List < ExpressionStatement > constructorStatements = Lists . create ( ) ; constructorStatements . add ( mapField ( parser ) ) ; if ( hasFileName ( ) ) { members . add ( createPrivateField ( StringOption . class , f . newSimpleName ( FIELD_PATH_NAME ) ) ) ; constructorStatements . add ( new ExpressionBuilder ( f , f . newSimpleName ( FIELD_PATH_NAME ) ) . assignFrom ( new TypeBuilder ( f , context . resolve ( StringOption . class ) ) . newObject ( new ExpressionBuilder ( f , parser ) . method ( "" ) . toExpression ( ) ) . toExpression ( ) ) . toStatement ( ) ) ; } members . add ( f . newConstructorDeclaration ( null , new AttributeBuilder ( f ) . toAttributes ( ) , f . newSimpleName ( NAME_READER ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( CsvParser . class ) , parser ) ) , constructorStatements ) ) ; SimpleName object = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , parser ) . method ( "" ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , Models . toLiteral ( f , false ) ) . toReturnStatement ( ) ) ) ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { switch ( CsvFieldTrait . getKind ( property , Kind . VALUE ) ) { case VALUE : statements . add ( new ExpressionBuilder ( f , parser ) . method ( "" , new ExpressionBuilder ( f , object ) . method ( context . getOptionGetterName ( property ) ) . toExpression ( ) ) . toStatement ( ) ) ; break ; case FILE_NAME : statements . add ( new ExpressionBuilder ( f , object ) . method ( context . getOptionSetterName ( property ) , f . newSimpleName ( FIELD_PATH_NAME ) ) . toStatement ( ) ) ; break ; case LINE_NUMBER : statements . add ( new ExpressionBuilder ( f , object ) . method ( context . getValueSetterName ( property ) , new ExpressionBuilder ( f , parser ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; break ; case RECORD_NUMBER : statements . add ( new ExpressionBuilder ( f , object ) . method ( context . getValueSetterName ( property ) , new ExpressionBuilder ( f , parser ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; break ; default : break ; } } statements . add ( new ExpressionBuilder ( f , parser ) . method ( "" ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , true ) ) . toReturnStatement ( ) ) ; members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( boolean . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , object ) ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ) ; members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( new ExpressionBuilder ( f , parser ) . method ( "" ) . toStatement ( ) ) ) ) ; return f . newClassDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Static ( ) . Final ( ) . toAttributes ( ) , f . newSimpleName ( NAME_READER ) , null , Arrays . asList ( f . newParameterizedType ( context . resolve ( ModelInput . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , members ) ; } private ClassDeclaration createWriterClass ( ) { SimpleName emitter = f . newSimpleName ( "" ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createPrivateField ( CsvEmitter . class , emitter ) ) ; members . add ( f . newConstructorDeclaration ( null , new AttributeBuilder ( f ) . toAttributes ( ) , f . newSimpleName ( NAME_WRITER ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( CsvEmitter . class ) , emitter ) ) , Arrays . asList ( mapField ( emitter ) ) ) ) ; SimpleName object = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( isValueField ( property ) ) { statements . add ( new ExpressionBuilder ( f , emitter ) . method ( "" , new ExpressionBuilder ( f , object ) . method ( context . getOptionGetterName ( property ) ) . toExpression ( ) ) . toStatement ( ) ) ; } } statements . add ( new ExpressionBuilder ( f , emitter ) . method ( "" ) . toStatement ( ) ) ; members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , object ) ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ) ; members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( new ExpressionBuilder ( f , emitter ) . method ( "" ) . toStatement ( ) ) ) ) ; return f . newClassDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Static ( ) . Final ( ) . toAttributes ( ) , f . newSimpleName ( NAME_WRITER ) , null , Arrays . asList ( f . newParameterizedType ( context . resolve ( ModelOutput . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , members ) ; } private boolean hasFileName ( ) { for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( CsvFieldTrait . getKind ( property , Kind . VALUE ) == Kind . FILE_NAME ) { return true ; } } return false ; } private ExpressionStatement mapField ( SimpleName name ) { return new ExpressionBuilder ( f , f . newThis ( ) ) . field ( name ) . assignFrom ( name ) . toStatement ( ) ; } private FieldDeclaration createPrivateField ( Class < ? > type , SimpleName name ) { return f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , context . resolve ( type ) , name , null ) ; } } private static final class DescriptionGenerator { private static final String IMPORTER_TYPE_NAME = "" ; private static final String EXPORTER_TYPE_NAME = "" ; private final EmitContext context ; private final ModelDeclaration model ; private final com . asakusafw . utils . java . model . syntax . Type supportClass ; private final ModelFactory f ; private final boolean importer ; private DescriptionGenerator ( EmitContext context , ModelDeclaration model , Name supportClassName , boolean importer ) { assert context != null ; assert model != null ; assert supportClassName != null ; this . context = context ; this . model = model ; this . f = context . getModelFactory ( ) ; this . importer = importer ; this . supportClass = context . resolve ( supportClassName ) ; } static void emitImporter ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; assert supportClassName != null ; DescriptionGenerator emitter = new DescriptionGenerator ( context , model , supportClassName , true ) ; emitter . emit ( ) ; } static void emitExporter ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; assert supportClassName != null ; DescriptionGenerator emitter = new DescriptionGenerator ( context , model , supportClassName , false ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . linkType ( context . resolve ( model . getSymbol ( ) ) ) . text ( "" , importer ? "" : "" ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Abstract ( ) . toAttributes ( ) , context . getTypeName ( ) , context . resolve ( Models . toName ( f , importer ? IMPORTER_TYPE_NAME : EXPORTER_TYPE_NAME ) ) , Collections . < com . asakusafw . utils . java . model . syntax . Type > emptyList ( ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createGetModelType ( ) ) ; results . add ( createGetStreamSupport ( ) ) ; return results ; } private MethodDeclaration createGetModelType ( ) { return createGetter ( new TypeBuilder ( f , context . resolve ( Class . class ) ) . parameterize ( f . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , context . resolve ( model . getSymbol ( ) ) ) ) . toType ( ) , "" , f . newClassLiteral ( context . resolve ( model . getSymbol ( ) ) ) ) ; } private MethodDeclaration createGetStreamSupport ( ) { return createGetter ( new TypeBuilder ( f , context . resolve ( Class . class ) ) . parameterize ( supportClass ) . toType ( ) , "" , f . newClassLiteral ( supportClass ) ) ; } private MethodDeclaration createGetter ( com . asakusafw . utils . java . model . syntax . Type type , String name , Expression value ) { assert type != null ; assert name != null ; assert value != null ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , type , f . newSimpleName ( name ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( new ExpressionBuilder ( f , value ) . toReturnStatement ( ) ) ) ; } } } package com . asakusafw . dmdl . directio . csv . driver ; package com . asakusafw . dmdl . directio . csv . driver ; import com . asakusafw . dmdl . directio . csv . driver . CsvFieldTrait . Kind ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class CsvLineNumberDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; CsvFieldDriver . checkFieldType ( environment , declaration , attribute , BasicTypeKind . INT , BasicTypeKind . LONG ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . LINE_NUMBER , null ) ) ; } } } package com . asakusafw . dmdl . directio . csv . driver ; import java . text . SimpleDateFormat ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . directio . csv . driver . CsvFormatTrait . Configuration ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . LiteralKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . spi . ModelAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . runtime . io . csv . CsvConfiguration ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class CsvFormatDriver extends ModelAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_CHARSET_NAME = "" ; public static final String ELEMENT_HAS_HEADER_NAME = "" ; public static final String ELEMENT_ALLOW_LINEFEED = "" ; public static final String ELEMENT_TRUE_NAME = "" ; public static final String ELEMENT_FALSE_NAME = "" ; public static final String ELEMENT_DATE_NAME = "" ; public static final String ELEMENT_DATE_TIME_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; Configuration conf = analyzeConfig ( environment , attribute , elements ) ; if ( conf != null ) { declaration . putTrait ( CsvFormatTrait . class , new CsvFormatTrait ( attribute , conf ) ) ; } } private Configuration analyzeConfig ( DmdlSemantics environment , AstAttribute attribute , Map < String , AstAttributeElement > elements ) { AstLiteral charset = take ( environment , elements , ELEMENT_CHARSET_NAME , LiteralKind . STRING ) ; AstLiteral header = take ( environment , elements , ELEMENT_HAS_HEADER_NAME , LiteralKind . BOOLEAN ) ; AstLiteral allowlf = take ( environment , elements , ELEMENT_ALLOW_LINEFEED , LiteralKind . BOOLEAN ) ; AstLiteral trueRep = take ( environment , elements , ELEMENT_TRUE_NAME , LiteralKind . STRING ) ; AstLiteral falseRep = take ( environment , elements , ELEMENT_FALSE_NAME , LiteralKind . STRING ) ; AstLiteral dateFormat = take ( environment , elements , ELEMENT_DATE_NAME , LiteralKind . STRING ) ; AstLiteral dateTimeFormat = take ( environment , elements , ELEMENT_DATE_TIME_NAME , LiteralKind . STRING ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; Configuration result = new Configuration ( ) ; if ( charset != null && checkNotEmpty ( environment , ELEMENT_CHARSET_NAME , charset ) ) { result . setCharsetName ( charset . toStringValue ( ) ) ; } if ( header != null ) { result . setEnableHeader ( header . toBooleanValue ( ) ) ; } if ( allowlf != null ) { result . setAllowLinefeed ( allowlf . toBooleanValue ( ) ) ; } if ( trueRep != null && checkNotEmpty ( environment , ELEMENT_TRUE_NAME , trueRep ) ) { result . setTrueFormat ( trueRep . toStringValue ( ) ) ; } if ( falseRep != null && checkNotEmpty ( environment , ELEMENT_FALSE_NAME , falseRep ) ) { result . setFalseFormat ( falseRep . toStringValue ( ) ) ; } if ( dateFormat != null && checkDateFormat ( environment , ELEMENT_DATE_NAME , dateFormat ) ) { result . setDateFormat ( dateFormat . toStringValue ( ) ) ; } if ( dateTimeFormat != null && checkDateFormat ( environment , ELEMENT_DATE_TIME_NAME , dateTimeFormat ) ) { result . setDateTimeFormat ( dateTimeFormat . toStringValue ( ) ) ; } return result ; } private boolean checkNotEmpty ( DmdlSemantics environment , String name , AstLiteral stringLiteral ) { assert environment != null ; assert name != null ; assert stringLiteral != null ; assert stringLiteral . kind == LiteralKind . STRING ; if ( stringLiteral . toStringValue ( ) . isEmpty ( ) ) { environment . report ( new Diagnostic ( Level . ERROR , stringLiteral , "" , TARGET_NAME , name ) ) ; return false ; } return true ; } private boolean checkDateFormat ( DmdlSemantics environment , String name , AstLiteral stringLiteral ) { assert environment != null ; assert name != null ; assert stringLiteral != null ; assert stringLiteral . kind == LiteralKind . STRING ; if ( checkNotEmpty ( environment , name , stringLiteral ) == false ) { return false ; } try { SimpleDateFormat format = new SimpleDateFormat ( stringLiteral . toStringValue ( ) ) ; format . format ( new java . util . Date ( ) ) ; } catch ( IllegalArgumentException e ) { environment . report ( new Diagnostic ( Level . ERROR , stringLiteral , "" , TARGET_NAME , name ) ) ; return false ; } return true ; } private AstLiteral take ( DmdlSemantics environment , Map < String , AstAttributeElement > elements , String elementName , LiteralKind kind ) { assert environment != null ; assert elements != null ; assert elementName != null ; assert kind != null ; AstAttributeElement element = elements . remove ( elementName ) ; if ( element == null ) { return null ; } else if ( ( element . value instanceof AstLiteral ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , element , "" , TARGET_NAME , elementName ) ) ; return null ; } else { AstLiteral literal = ( AstLiteral ) element . value ; if ( literal . kind != kind ) { environment . report ( new Diagnostic ( Level . ERROR , element , "" , TARGET_NAME , elementName ) ) ; return null ; } return literal ; } } } package com . asakusafw . dmdl . directio . csv . driver ; import com . asakusafw . dmdl . directio . csv . driver . CsvFieldTrait . Kind ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class CsvRecordNumberDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; CsvFieldDriver . checkFieldType ( environment , declaration , attribute , BasicTypeKind . INT , BasicTypeKind . LONG ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . RECORD_NUMBER , null ) ) ; } } } package com . asakusafw . dmdl . directio . csv . driver ; import java . text . SimpleDateFormat ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . Trait ; import com . asakusafw . runtime . io . csv . CsvConfiguration ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class CsvFormatTrait implements Trait < CsvFormatTrait > { private final AstNode originalAst ; private final Configuration configuration ; public CsvFormatTrait ( AstNode originalAst , Configuration configuration ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . configuration = configuration ; } public Configuration getConfiguration ( ) { return configuration ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public static class Configuration { private String charsetName = "" ; private boolean allowLinefeed = false ; private boolean enableHeader = false ; private String trueFormat = CsvConfiguration . DEFAULT_TRUE_FORMAT ; private String falseFormat = CsvConfiguration . DEFAULT_FALSE_FORMAT ; private String dateFormat = CsvConfiguration . DEFAULT_DATE_FORMAT ; private String dateTimeFormat = CsvConfiguration . DEFAULT_DATE_TIME_FORMAT ; public String getCharsetName ( ) { return charsetName ; } public void setCharsetName ( String charsetName ) { this . charsetName = charsetName ; } public boolean isEnableHeader ( ) { return enableHeader ; } public void setEnableHeader ( boolean enableHeader ) { this . enableHeader = enableHeader ; } public String getTrueFormat ( ) { return trueFormat ; } public void setTrueFormat ( String format ) { this . trueFormat = format ; } public String getFalseFormat ( ) { return falseFormat ; } public void setFalseFormat ( String format ) { this . falseFormat = format ; } public String getDateFormat ( ) { return dateFormat ; } public void setDateFormat ( String format ) { this . dateFormat = format ; } public String getDateTimeFormat ( ) { return dateTimeFormat ; } public void setDateTimeFormat ( String format ) { this . dateTimeFormat = format ; } public boolean isAllowLinefeed ( ) { return allowLinefeed ; } public void setAllowLinefeed ( boolean allow ) { this . allowLinefeed = allow ; } } } package com . asakusafw . dmdl . directio . csv . driver ; import java . util . Arrays ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . directio . csv . driver . CsvFieldTrait . Kind ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class CsvFieldDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; String value = AttributeUtil . takeString ( environment , attribute , elements , ELEMENT_NAME , false ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; checkFieldType ( environment , declaration , attribute , BasicTypeKind . values ( ) ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . VALUE , value ) ) ; } } static boolean checkConflict ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { assert environment != null ; assert declaration != null ; assert attribute != null ; if ( declaration . getTrait ( CsvFieldTrait . class ) == null ) { return true ; } environment . report ( new Diagnostic ( Level . ERROR , attribute , "" , declaration . getOwner ( ) . getName ( ) . identifier , declaration . getName ( ) . identifier ) ) ; return false ; } static void checkFieldType ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute , BasicTypeKind ... types ) { assert environment != null ; assert declaration != null ; assert attribute != null ; assert types != null ; assert types . length > ; Type type = declaration . getType ( ) ; if ( type instanceof BasicType ) { BasicTypeKind kind = ( ( BasicType ) type ) . getKind ( ) ; for ( BasicTypeKind accept : types ) { if ( kind == accept ) { return ; } } } environment . report ( new Diagnostic ( Level . ERROR , attribute , "" , declaration . getOwner ( ) . getName ( ) . identifier , declaration . getName ( ) . identifier , attribute . name . toString ( ) , Arrays . asList ( types ) ) ) ; } } package com . asakusafw . dmdl . directio . csv . driver ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . Trait ; public class CsvFieldTrait implements Trait < CsvFieldTrait > { private final AstNode originalAst ; private final Kind kind ; private final String name ; public CsvFieldTrait ( AstNode originalAst , Kind kind , String name ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . kind = kind ; this . name = name ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public static Kind getKind ( PropertyDeclaration property , Kind defaultKind ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } CsvFieldTrait trait = property . getTrait ( CsvFieldTrait . class ) ; if ( trait != null ) { return trait . kind ; } return defaultKind ; } public static String getFieldName ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } CsvFieldTrait trait = property . getTrait ( CsvFieldTrait . class ) ; if ( trait != null && trait . name != null ) { return trait . name ; } return property . getName ( ) . identifier ; } public enum Kind { VALUE , FILE_NAME , LINE_NUMBER , RECORD_NUMBER , IGNORE , } } package com . asakusafw . dmdl . directio . csv . driver ; import com . asakusafw . dmdl . directio . csv . driver . CsvFieldTrait . Kind ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class CsvFileNameDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; CsvFieldDriver . checkFieldType ( environment , declaration , attribute , BasicTypeKind . TEXT ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . FILE_NAME , null ) ) ; } } } package com . asakusafw . dmdl . directio . csv . driver ; import com . asakusafw . dmdl . directio . csv . driver . CsvFieldTrait . Kind ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class CsvIgnoreDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . IGNORE , null ) ) ; } } } package com . asakusafw . testdriver . directio ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . util . Scanner ; import org . apache . hadoop . io . Text ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class MockStreamFormat extends BinaryStreamFormat < Text > { @ Override public Class < Text > getSupportedType ( ) { return Text . class ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public ModelInput < Text > createInput ( Class < ? extends Text > dataType , String path , InputStream stream , long offset , long fragmentSize ) throws IOException , InterruptedException { final Scanner s = new Scanner ( stream , "" ) ; return new ModelInput < Text > ( ) { @ Override public boolean readTo ( Text model ) throws IOException { if ( s . hasNextLine ( ) ) { model . set ( s . nextLine ( ) ) ; return true ; } return false ; } @ Override public void close ( ) throws IOException { s . close ( ) ; } } ; } @ Override public ModelOutput < Text > createOutput ( Class < ? extends Text > dataType , String path , OutputStream stream ) throws IOException , InterruptedException { final PrintWriter w = new PrintWriter ( new OutputStreamWriter ( stream ) ) ; return new ModelOutput < Text > ( ) { @ Override public void write ( Text model ) throws IOException { w . println ( model . toString ( ) ) ; } @ Override public void close ( ) throws IOException { w . close ( ) ; } } ; } } package com . asakusafw . testdriver . directio ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . hadoop . io . Text ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import org . junit . runner . RunWith ; import org . junit . runners . Parameterized ; import org . junit . runners . Parameterized . Parameters ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSource ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceProfile ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . SpiExporterRetriever ; @ RunWith ( Parameterized . class ) public class DirectFileOutputRetrieverTest { @ Rule public final ProfileContext profile = new ProfileContext ( ) ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private final Class < ? extends DataFormat < Text > > format ; @ Parameters public static List < Object [ ] > data ( ) { return Arrays . asList ( new Object [ ] [ ] { { MockStreamFormat . class } , { MockFileFormat . class } , } ) ; } public DirectFileOutputRetrieverTest ( Class < ? extends DataFormat < Text > > format ) { this . format = format ; } @ Test public void truncate ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; File file = put ( "" , "" ) ; File deep = put ( "" , "" ) ; File outer = put ( "" , "" ) ; assertThat ( file . exists ( ) , is ( true ) ) ; assertThat ( deep . exists ( ) , is ( true ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; testee . truncate ( new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; assertThat ( file . exists ( ) , is ( false ) ) ; assertThat ( deep . exists ( ) , is ( false ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; } @ Test public void truncate_placeholders ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; File file = put ( "" , "" ) ; File deep = put ( "" , "" ) ; File outer = put ( "" , "" ) ; assertThat ( file . exists ( ) , is ( true ) ) ; assertThat ( deep . exists ( ) , is ( true ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; testee . truncate ( new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; assertThat ( file . exists ( ) , is ( false ) ) ; assertThat ( deep . exists ( ) , is ( false ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; } @ Test public void truncate_wildcard ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; File file = put ( "" , "" ) ; File deep = put ( "" , "" ) ; File outer = put ( "" , "" ) ; assertThat ( file . exists ( ) , is ( true ) ) ; assertThat ( deep . exists ( ) , is ( true ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; testee . truncate ( new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; assertThat ( file . exists ( ) , is ( false ) ) ; assertThat ( deep . exists ( ) , is ( false ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; } @ Test public void truncate_empty ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; testee . truncate ( new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; } @ Test public void truncate_variable ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; File file = put ( "" , "" ) ; File deep = put ( "" , "" ) ; File outer = put ( "" , "" ) ; assertThat ( file . exists ( ) , is ( true ) ) ; assertThat ( deep . exists ( ) , is ( true ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; testee . truncate ( new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( "" , "" ) ) ; assertThat ( file . exists ( ) , is ( false ) ) ; assertThat ( deep . exists ( ) , is ( false ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; } @ Test public void createInput ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; put ( "" , "" ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; DataModelSource input = testee . createSource ( new MockTextDefinition ( ) , new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; List < String > list = get ( input ) ; assertThat ( list , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void createInput_multirecord ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; put ( "" , "" , "" , "" ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; DataModelSource input = testee . createSource ( new MockTextDefinition ( ) , new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; List < String > list = get ( input ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void createInput_multifile ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; DataModelSource input = testee . createSource ( new MockTextDefinition ( ) , new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; List < String > list = get ( input ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void createInput_variables ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; put ( "" , "" ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; DataModelSource input = testee . createSource ( new MockTextDefinition ( ) , new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( "" , "" , "" , "" ) ) ; List < String > list = get ( input ) ; assertThat ( list , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void createInput_placeholders ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; DataModelSource input = testee . createSource ( new MockTextDefinition ( ) , new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; List < String > list = get ( input ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void createInput_wildcard ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; put ( "" , "" ) ; put ( "" , "" ) ; put ( "" , "" ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; DataModelSource input = testee . createSource ( new MockTextDefinition ( ) , new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; List < String > list = get ( input ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test ( expected = IOException . class ) public void no_config ( ) throws Exception { DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; testee . truncate ( new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; } @ Test ( expected = IOException . class ) public void no_datasource ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileOutputRetriever testee = new DirectFileOutputRetriever ( ) ; testee . truncate ( new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; } @ Test public void spi ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; put ( "" , "" ) ; SpiExporterRetriever testee = new SpiExporterRetriever ( getClass ( ) . getClassLoader ( ) ) ; DataModelSource input = testee . createSource ( new MockTextDefinition ( ) , new MockOutputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; List < String > list = get ( input ) ; assertThat ( list , is ( Arrays . asList ( "" ) ) ) ; } private List < String > get ( DataModelSource input ) throws IOException { try { MockTextDefinition def = new MockTextDefinition ( ) ; List < String > results = new ArrayList < String > ( ) ; while ( true ) { DataModelReflection next = input . next ( ) ; if ( next == null ) { break ; } results . add ( def . toObject ( next ) . toString ( ) ) ; } return results ; } finally { input . close ( ) ; } } private File put ( String targetPath , String ... contents ) throws IOException { File target = new File ( folder . getRoot ( ) , targetPath ) ; target . getParentFile ( ) . mkdirs ( ) ; PrintWriter w = new PrintWriter ( target , "" ) ; try { for ( String line : contents ) { w . println ( line ) ; } } finally { w . close ( ) ; } return target ; } } package com . asakusafw . testdriver . directio ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Text ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . hadoop . HadoopFileFormat ; import com . asakusafw . runtime . directio . hadoop . HadoopFileFormatAdapter ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class MockFileFormat extends HadoopFileFormatAdapter < Text > { public MockFileFormat ( ) { super ( new MockStreamFormat ( ) ) ; } @ Override public ModelInput < Text > createInput ( Class < ? extends Text > dataType , FileSystem fileSystem , Path path , long offset , long fragmentSize , Counter counter ) throws IOException , InterruptedException { assertThat ( getConf ( ) , is ( notNullValue ( ) ) ) ; return super . createInput ( dataType , fileSystem , path , offset , fragmentSize , counter ) ; } @ Override public ModelOutput < Text > createOutput ( Class < ? extends Text > dataType , FileSystem fileSystem , Path path , Counter counter ) throws IOException , InterruptedException { assertThat ( getConf ( ) , is ( notNullValue ( ) ) ) ; return super . createOutput ( dataType , fileSystem , path , counter ) ; } } package com . asakusafw . testdriver . directio ; import java . lang . annotation . Annotation ; import java . util . Collection ; import java . util . Collections ; import org . apache . hadoop . io . Text ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; public class MockTextDefinition implements DataModelDefinition < Text > { static final PropertyName VALUE = PropertyName . newInstance ( "" ) ; @ Override public Class < Text > getModelClass ( ) { return Text . class ; } @ Override public < A extends Annotation > A getAnnotation ( Class < A > annotationType ) { return null ; } @ Override public Collection < PropertyName > getProperties ( ) { return Collections . singleton ( VALUE ) ; } @ Override public PropertyType getType ( PropertyName name ) { if ( VALUE . equals ( name ) ) { return PropertyType . STRING ; } return null ; } @ Override public < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) { return null ; } @ Override public Builder < Text > newReflection ( ) { return new Builder < Text > ( this ) ; } @ Override public DataModelReflection toReflection ( Text object ) { return newReflection ( ) . add ( VALUE , object . toString ( ) ) . build ( ) ; } @ Override public Text toObject ( DataModelReflection reflection ) { Text text = new Text ( ) ; String string = ( String ) reflection . getValue ( VALUE ) ; if ( string != null ) { text . set ( string ) ; } return text ; } } package com . asakusafw . testdriver . directio ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . Text ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . vocabulary . directio . DirectFileOutputDescription ; public class MockOutputDescription extends DirectFileOutputDescription { private final String basePath ; private final String resourcePattern ; private final Class < ? extends DataFormat < ? > > format ; MockOutputDescription ( String basePath , String resourcePattern , Class < ? extends DataFormat < ? > > format ) { this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . format = format ; } @ Override public Class < ? > getModelType ( ) { return Text . class ; } @ Override public Class < ? extends DataFormat < ? > > getFormat ( ) { return format ; } @ Override public String getBasePath ( ) { return basePath ; } @ Override public String getResourcePattern ( ) { return resourcePattern ; } @ Override public List < String > getOrder ( ) { return Collections . emptyList ( ) ; } } package com . asakusafw . testdriver . directio ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . LinkedList ; import java . util . List ; import java . util . Scanner ; import org . apache . hadoop . io . Text ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import org . junit . runner . RunWith ; import org . junit . runners . Parameterized ; import org . junit . runners . Parameterized . Parameters ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSource ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceProfile ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . SpiImporterPreparator ; @ RunWith ( Parameterized . class ) public class DirectFileInputPreparatorTest { @ Rule public final ProfileContext profile = new ProfileContext ( ) ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private final Class < ? extends DataFormat < Text > > format ; @ Parameters public static List < Object [ ] > data ( ) { return Arrays . asList ( new Object [ ] [ ] { { MockStreamFormat . class } , { MockFileFormat . class } , } ) ; } public DirectFileInputPreparatorTest ( Class < ? extends DataFormat < Text > > format ) { this . format = format ; } @ Test public void truncate ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; File file = put ( "" , "" ) ; File deep = put ( "" , "" ) ; File outer = put ( "" , "" ) ; assertThat ( file . exists ( ) , is ( true ) ) ; assertThat ( deep . exists ( ) , is ( true ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; testee . truncate ( new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; assertThat ( file . exists ( ) , is ( false ) ) ; assertThat ( deep . exists ( ) , is ( false ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; } @ Test public void truncate_empty ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; testee . truncate ( new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; } @ Test public void truncate_variable ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; File file = put ( "" , "" ) ; File deep = put ( "" , "" ) ; File outer = put ( "" , "" ) ; assertThat ( file . exists ( ) , is ( true ) ) ; assertThat ( deep . exists ( ) , is ( true ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; testee . truncate ( new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( "" , "" ) ) ; assertThat ( file . exists ( ) , is ( false ) ) ; assertThat ( deep . exists ( ) , is ( false ) ) ; assertThat ( outer . exists ( ) , is ( true ) ) ; } @ Test public void createOutput ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; ModelOutput < Text > output = testee . createOutput ( new MockTextDefinition ( ) , new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; put ( output , "" ) ; assertThat ( get ( "" ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void createOutput_multirecord ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; ModelOutput < Text > output = testee . createOutput ( new MockTextDefinition ( ) , new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; put ( output , "" , "" , "" ) ; List < String > list = get ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; assertThat ( list , hasItem ( "" ) ) ; } @ Test public void createOutput_variables ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; ModelOutput < Text > output = testee . createOutput ( new MockTextDefinition ( ) , new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( "" , "" , "" , "" ) ) ; put ( output , "" ) ; assertThat ( get ( "" ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void createInput_placeholders ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; ModelOutput < Text > output = testee . createOutput ( new MockTextDefinition ( ) , new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; put ( output , "" ) ; List < File > files = find ( "" ) ; assertThat ( files . toString ( ) , files . size ( ) , is ( ) ) ; assertThat ( get ( files . get ( ) ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void createOutput_placeholders ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; ModelOutput < Text > output = testee . createOutput ( new MockTextDefinition ( ) , new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; put ( output , "" ) ; List < File > files = find ( "" ) ; assertThat ( files . toString ( ) , files . size ( ) , is ( ) ) ; assertThat ( get ( files . get ( ) ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test ( expected = IOException . class ) public void no_config ( ) throws Exception { DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; testee . truncate ( new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; } @ Test ( expected = IOException . class ) public void no_datasource ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; DirectFileInputPreparator testee = new DirectFileInputPreparator ( ) ; testee . truncate ( new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; } @ Test public void spi ( ) throws Exception { profile . add ( "" , HadoopDataSource . class , "" ) ; profile . add ( "" , HadoopDataSourceProfile . KEY_PATH , folder . getRoot ( ) . toURI ( ) . toURL ( ) . toString ( ) ) ; profile . put ( ) ; SpiImporterPreparator testee = new SpiImporterPreparator ( getClass ( ) . getClassLoader ( ) ) ; ModelOutput < Text > output = testee . createOutput ( new MockTextDefinition ( ) , new MockInputDescription ( "" , "" , format ) , profile . getTextContext ( ) ) ; put ( output , "" ) ; assertThat ( get ( "" ) , is ( Arrays . asList ( "" ) ) ) ; } private List < File > find ( String targetPath ) { List < File > results = new ArrayList < File > ( ) ; LinkedList < File > work = new LinkedList < File > ( ) ; work . add ( new File ( folder . getRoot ( ) , targetPath ) ) ; while ( work . isEmpty ( ) == false ) { File file = work . removeFirst ( ) ; if ( file . getName ( ) . startsWith ( "" ) ) { continue ; } if ( file . isDirectory ( ) ) { Collections . addAll ( work , file . listFiles ( ) ) ; } else { results . add ( file ) ; } } return results ; } private List < String > get ( String targetPath ) throws IOException { return get ( new File ( folder . getRoot ( ) , targetPath ) ) ; } private List < String > get ( File target ) throws FileNotFoundException { Scanner s = new Scanner ( target , "" ) ; try { List < String > results = new ArrayList < String > ( ) ; while ( s . hasNextLine ( ) ) { results . add ( s . nextLine ( ) ) ; } return results ; } finally { s . close ( ) ; } } private void put ( ModelOutput < Text > output , String ... contents ) throws IOException { try { Text text = new Text ( ) ; for ( String line : contents ) { text . set ( line ) ; output . write ( text ) ; } } finally { output . close ( ) ; } } private File put ( String targetPath , String ... contents ) throws IOException { File target = new File ( folder . getRoot ( ) , targetPath ) ; target . getParentFile ( ) . mkdirs ( ) ; PrintWriter w = new PrintWriter ( target , "" ) ; try { for ( String line : contents ) { w . println ( line ) ; } } finally { w . close ( ) ; } return target ; } } package com . asakusafw . testdriver . directio ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . junit . rules . ExternalResource ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . directio . AbstractDirectDataSource ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; import com . asakusafw . runtime . flow . RuntimeResourceManager ; import com . asakusafw . testdriver . core . TestContext ; public class ProfileContext extends ExternalResource { private final TemporaryFolder folder = new TemporaryFolder ( ) ; private final Configuration configuration = new Configuration ( false ) ; @ Override protected void before ( ) throws Throwable { folder . create ( ) ; } @ Override protected void after ( ) { folder . delete ( ) ; } public TestContext getTextContext ( String ... kvs ) { assert kvs . length % == ; final Map < String , String > env = new HashMap < String , String > ( System . getenv ( ) ) ; env . put ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ; final Map < String , String > args = new HashMap < String , String > ( ) ; for ( int i = ; i < kvs . length ; i += ) { args . put ( kvs [ i ] , kvs [ i + ] ) ; } return new TestContext ( ) { @ Override public Map < String , String > getEnvironmentVariables ( ) { return env ; } @ Override public ClassLoader getClassLoader ( ) { return getClass ( ) . getClassLoader ( ) ; } @ Override public Map < String , String > getArguments ( ) { return args ; } } ; } public void add ( String id , Class < ? extends AbstractDirectDataSource > aClass , String path ) { configuration . setClass ( MessageFormat . format ( "" , HadoopDataSourceUtil . PREFIX , id ) , aClass , AbstractDirectDataSource . class ) ; add ( id , HadoopDataSourceUtil . KEY_PATH , path ) ; } public void add ( String id , String key , String value ) { configuration . set ( MessageFormat . format ( "" , HadoopDataSourceUtil . PREFIX , id , key ) , value ) ; } public void put ( ) { try { File file = new File ( folder . getRoot ( ) , RuntimeResourceManager . CONFIGURATION_FILE_PATH ) ; file . getParentFile ( ) . mkdirs ( ) ; FileOutputStream out = new FileOutputStream ( file ) ; try { configuration . writeXml ( out ) ; } finally { out . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . testdriver . directio ; import org . apache . hadoop . io . Text ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . vocabulary . directio . DirectFileInputDescription ; public class MockInputDescription extends DirectFileInputDescription { private final String basePath ; private final String resourcePattern ; private final Class < ? extends DataFormat < ? > > format ; MockInputDescription ( String basePath , String resourcePattern , Class < ? extends DataFormat < ? > > format ) { this . basePath = basePath ; this . resourcePattern = resourcePattern ; this . format = format ; } @ Override public Class < ? > getModelType ( ) { return Text . class ; } @ Override public Class < ? extends DataFormat < ? > > getFormat ( ) { return format ; } @ Override public String getBasePath ( ) { return basePath ; } @ Override public String getResourcePattern ( ) { return resourcePattern ; } } package com . asakusafw . testdriver . directio ; package com . asakusafw . testdriver . directio ; import java . io . File ; import java . io . IOException ; import java . io . InterruptedIOException ; import java . net . URL ; import java . text . MessageFormat ; import java . util . Iterator ; import java . util . List ; import java . util . UUID ; import java . util . WeakHashMap ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . util . ReflectionUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . DirectInputFragment ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . directio . FilePattern . PatternElement ; import com . asakusafw . runtime . directio . FilePattern . Segment ; import com . asakusafw . runtime . directio . FilePattern . Selection ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; import com . asakusafw . runtime . flow . RuntimeResourceManager ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . runtime . util . VariableTable . RedefineStrategy ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . vocabulary . directio . DirectFileInputDescription ; import com . asakusafw . vocabulary . directio . DirectFileOutputDescription ; public final class DirectIoTestHelper { private static final FilePattern ALL = FilePattern . compile ( "" ) ; private static final String WILDCARD_REPLACEMENT = "" ; static final Logger LOG = LoggerFactory . getLogger ( DirectIoTestHelper . class ) ; private static final WeakHashMap < TestContext , DirectDataSourceRepository > REPOSITORY_CACHE = new WeakHashMap < TestContext , DirectDataSourceRepository > ( ) ; private final TestContext context ; private final Configuration hadoopConfiguration ; final VariableTable variables ; final DirectDataSource dataSource ; final String id ; final String fullPath ; final String containerPath ; final String basePath ; public DirectIoTestHelper ( TestContext context , String rootPath ) throws IOException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rootPath == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . hadoopConfiguration = createConfiguration ( ) ; LOG . debug ( "" , rootPath ) ; this . variables = new VariableTable ( RedefineStrategy . ERROR ) ; variables . defineVariables ( context . getArguments ( ) ) ; String resolvedRootPath = resolve ( rootPath ) ; LOG . debug ( "" , rootPath , resolvedRootPath ) ; DirectDataSourceRepository repo = getRepository ( ) ; try { this . id = repo . getRelatedId ( resolvedRootPath ) ; this . dataSource = repo . getRelatedDataSource ( resolvedRootPath ) ; } catch ( IOException e ) { throw new IOException ( MessageFormat . format ( "" , resolvedRootPath , findExtraConfiguration ( ) ) , e ) ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( "" ) . initCause ( e ) ; } this . fullPath = resolvedRootPath ; this . containerPath = repo . getContainerPath ( resolvedRootPath ) ; this . basePath = repo . getComponentPath ( resolvedRootPath ) ; LOG . debug ( "" , resolvedRootPath , id ) ; } private synchronized DirectDataSourceRepository getRepository ( ) { assert context != null ; DirectDataSourceRepository cached = REPOSITORY_CACHE . get ( context ) ; if ( cached != null ) { return cached ; } DirectDataSourceRepository repo = createRepository ( ) ; REPOSITORY_CACHE . put ( context , repo ) ; return repo ; } private Configuration createConfiguration ( ) throws IOException { Configuration conf ; ClassLoader contextLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { conf = ConfigurationFactory . getDefault ( ) . newInstance ( ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( contextLoader ) ; } URL extra = findExtraConfiguration ( ) ; if ( extra != null ) { conf . addResource ( extra ) ; } return conf ; } private DirectDataSourceRepository createRepository ( ) { return HadoopDataSourceUtil . loadRepository ( hadoopConfiguration ) ; } private URL findExtraConfiguration ( ) throws IOException { File file = findFileOnHomePath ( context , RuntimeResourceManager . CONFIGURATION_FILE_PATH ) ; if ( file == null ) { throw new IOException ( MessageFormat . format ( "" , "" , RuntimeResourceManager . CONFIGURATION_FILE_PATH ) ) ; } return file . toURI ( ) . toURL ( ) ; } private static File findFileOnHomePath ( TestContext context , String path ) { assert context != null ; assert path != null ; String home = context . getEnvironmentVariables ( ) . get ( "" ) ; if ( home != null ) { File file = new File ( home , path ) ; if ( file . exists ( ) ) { return file ; } } else { LOG . warn ( "" ) ; } return null ; } public void truncate ( ) throws IOException { LOG . info ( "" , new Object [ ] { fullPath , id , } ) ; try { dataSource . delete ( basePath , ALL , true , new Counter ( ) ) ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( "" ) . initCause ( e ) ; } } public < T > ModelOutput < T > openOutput ( Class < T > dataType , DirectFileInputDescription description ) throws IOException { if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } final OutputAttemptContext outputContext = createOutputContext ( ) ; DataFormat < T > format = createFormat ( dataType , description . getFormat ( ) ) ; String outputPath = toOutputName ( description . getResourcePattern ( ) ) ; LOG . info ( "" , new Object [ ] { fullPath , outputPath , id , description . getClass ( ) . getName ( ) , } ) ; try { dataSource . setupTransactionOutput ( outputContext . getTransactionContext ( ) ) ; dataSource . setupAttemptOutput ( outputContext ) ; Counter counter = new Counter ( ) ; final ModelOutput < T > output = dataSource . openOutput ( outputContext , dataType , format , basePath , outputPath , counter ) ; return new ModelOutput < T > ( ) { @ Override public void write ( T model ) throws IOException { output . write ( model ) ; } @ Override public void close ( ) throws IOException { output . close ( ) ; try { dataSource . commitAttemptOutput ( outputContext ) ; dataSource . cleanupAttemptOutput ( outputContext ) ; dataSource . commitTransactionOutput ( outputContext . getTransactionContext ( ) ) ; dataSource . cleanupTransactionOutput ( outputContext . getTransactionContext ( ) ) ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( "" ) . initCause ( e ) ; } } } ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( "" ) . initCause ( e ) ; } } public < T > ModelInput < T > openInput ( final Class < T > dataType , DirectFileOutputDescription description ) throws IOException { if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } final DataFormat < T > format = createFormat ( dataType , description . getFormat ( ) ) ; final Counter counter = new Counter ( ) ; try { FilePattern pattern = toInputPattern ( description . getResourcePattern ( ) ) ; LOG . info ( "" , new Object [ ] { fullPath , pattern , id , description . getClass ( ) . getName ( ) , } ) ; final List < DirectInputFragment > fragments = dataSource . findInputFragments ( dataType , format , basePath , pattern ) ; return new ModelInput < T > ( ) { private final Iterator < DirectInputFragment > iterator = fragments . iterator ( ) ; private ModelInput < T > current = null ; @ Override public boolean readTo ( T model ) throws IOException { while ( true ) { if ( current == null ) { if ( iterator . hasNext ( ) == false ) { return false ; } DirectInputFragment fragment = iterator . next ( ) ; try { current = dataSource . openInput ( dataType , format , fragment , counter ) ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( "" ) . initCause ( e ) ; } } assert current != null ; if ( current . readTo ( model ) ) { return true ; } current . close ( ) ; current = null ; } } @ Override public void close ( ) throws IOException { if ( current != null ) { current . close ( ) ; } } } ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( "" ) . initCause ( e ) ; } } private String toOutputName ( String inputResourcePattern ) throws IOException { assert inputResourcePattern != null ; String patternString = resolve ( inputResourcePattern ) ; FilePattern pattern = FilePattern . compile ( patternString ) ; if ( pattern . containsVariables ( ) ) { throw new IOException ( MessageFormat . format ( "" , inputResourcePattern , patternString ) ) ; } StringBuilder buf = new StringBuilder ( ) ; for ( Segment segment : pattern . getSegments ( ) ) { if ( buf . length ( ) != ) { buf . append ( '' ) ; } if ( segment . isTraverse ( ) ) { buf . append ( WILDCARD_REPLACEMENT ) ; } for ( PatternElement element : segment . getElements ( ) ) { switch ( element . getKind ( ) ) { case TOKEN : buf . append ( element . getToken ( ) ) ; break ; case SELECTION : buf . append ( ( ( Selection ) element ) . getContents ( ) . get ( ) ) ; break ; default : buf . append ( WILDCARD_REPLACEMENT ) ; break ; } } } return buf . toString ( ) ; } private FilePattern toInputPattern ( String outputResourcePattern ) { assert outputResourcePattern != null ; return ALL ; } private String resolve ( String string ) { assert string != null ; return variables . parse ( string ) ; } private OutputAttemptContext createOutputContext ( ) { String tx = UUID . randomUUID ( ) . toString ( ) ; String attempt = UUID . randomUUID ( ) . toString ( ) ; return new OutputAttemptContext ( tx , attempt , id , new Counter ( ) ) ; } @ SuppressWarnings ( "" ) private < T > DataFormat < T > createFormat ( Class < T > dataType , Class < ? extends DataFormat < ? > > formatClass ) throws IOException { assert dataType != null ; assert formatClass != null ; DataFormat < ? > format ; try { format = ReflectionUtils . newInstance ( formatClass , hadoopConfiguration ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , formatClass . getName ( ) ) , e ) ; } if ( format . getSupportedType ( ) . isAssignableFrom ( dataType ) == false ) { throw new IOException ( MessageFormat . format ( "" , formatClass . getName ( ) , dataType . getName ( ) ) ) ; } return ( DataFormat < T > ) format ; } } package com . asakusafw . testdriver . directio ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . BaseExporterRetriever ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . ExporterRetriever ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . directio . DirectFileOutputDescription ; public class DirectFileOutputRetriever extends BaseExporterRetriever < DirectFileOutputDescription > { static final Logger LOG = LoggerFactory . getLogger ( DirectFileOutputRetriever . class ) ; @ Override public void truncate ( DirectFileOutputDescription description , TestContext context ) throws IOException { DirectIoTestHelper helper = new DirectIoTestHelper ( context , description . getBasePath ( ) ) ; LOG . info ( "" , description . getClass ( ) . getName ( ) ) ; helper . truncate ( ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , DirectFileOutputDescription description , TestContext context ) throws IOException { throw new UnsupportedOperationException ( MessageFormat . format ( "" , description . getClass ( ) . getName ( ) ) ) ; } @ Override public < V > DataModelSource createSource ( final DataModelDefinition < V > definition , DirectFileOutputDescription description , TestContext context ) throws IOException { DirectIoTestHelper helper = new DirectIoTestHelper ( context , description . getBasePath ( ) ) ; LOG . info ( "" , description . getClass ( ) . getName ( ) ) ; final V object = definition . toObject ( definition . newReflection ( ) . build ( ) ) ; final ModelInput < ? super V > input = helper . openInput ( definition . getModelClass ( ) , description ) ; return new DataModelSource ( ) { @ Override public DataModelReflection next ( ) throws IOException { if ( input . readTo ( object ) ) { return definition . toReflection ( object ) ; } return null ; } @ Override public void close ( ) throws IOException { input . close ( ) ; } } ; } } package com . asakusafw . testdriver . directio ; import java . io . IOException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . BaseImporterPreparator ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . ImporterPreparator ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . directio . DirectFileInputDescription ; public class DirectFileInputPreparator extends BaseImporterPreparator < DirectFileInputDescription > { static final Logger LOG = LoggerFactory . getLogger ( DirectFileInputPreparator . class ) ; @ Override public void truncate ( DirectFileInputDescription description , TestContext context ) throws IOException { DirectIoTestHelper helper = new DirectIoTestHelper ( context , description . getBasePath ( ) ) ; LOG . info ( "" , description . getClass ( ) . getName ( ) ) ; helper . truncate ( ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , DirectFileInputDescription description , TestContext context ) throws IOException { DirectIoTestHelper helper = new DirectIoTestHelper ( context , description . getBasePath ( ) ) ; LOG . info ( "" , description . getClass ( ) . getName ( ) ) ; return helper . openOutput ( definition . getModelClass ( ) , description ) ; } } package com . asakusafw . vocabulary . directio ; import java . util . Collections ; import java . util . List ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . vocabulary . external . ExporterDescription ; public abstract class DirectFileOutputDescription implements ExporterDescription { public abstract String getBasePath ( ) ; public abstract String getResourcePattern ( ) ; public List < String > getOrder ( ) { return Collections . emptyList ( ) ; } public List < String > getDeletePatterns ( ) { return Collections . emptyList ( ) ; } public abstract Class < ? extends DataFormat < ? > > getFormat ( ) ; } package com . asakusafw . vocabulary . directio ; package com . asakusafw . vocabulary . directio ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . vocabulary . external . ImporterDescription ; public abstract class DirectFileInputDescription implements ImporterDescription { public abstract String getBasePath ( ) ; public abstract String getResourcePattern ( ) ; public abstract Class < ? extends DataFormat < ? > > getFormat ( ) ; @ Override public DataSize getDataSize ( ) { return DataSize . UNKNOWN ; } } package com . asakusafw . runtime . configuration ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . text . MessageFormat ; import java . util . zip . ZipEntry ; import java . util . zip . ZipInputStream ; import java . util . zip . ZipOutputStream ; import org . junit . rules . TemporaryFolder ; import org . junit . rules . TestRule ; import org . junit . runner . Description ; import org . junit . runners . model . Statement ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . stage . ToolLauncher ; public class FrameworkDeployer implements TestRule { static final Logger LOG = LoggerFactory . getLogger ( FrameworkDeployer . class ) ; final TemporaryFolder folder = new TemporaryFolder ( ) ; final boolean copyDefaults ; private File home ; private File work ; private File runtimeLib ; public FrameworkDeployer ( ) { this ( true ) ; } public FrameworkDeployer ( boolean copyDefaults ) { this . copyDefaults = copyDefaults ; } @ Override public Statement apply ( final Statement base , Description description ) { return new Statement ( ) { @ Override public void evaluate ( ) throws Throwable { folder . create ( ) ; try { createDirs ( ) ; if ( copyDefaults ) { deployMainDist ( ) ; deployTestDist ( ) ; deployRuntimeLibrary ( ) ; } deploy ( ) ; base . evaluate ( ) ; } finally { folder . delete ( ) ; } } } ; } void createDirs ( ) { home = folder . newFolder ( "" ) ; work = folder . newFolder ( "" ) ; } protected void deploy ( ) throws Throwable { return ; } void deployMainDist ( ) throws IOException { LOG . debug ( "" ) ; File source = new File ( "" ) ; if ( source . exists ( ) ) { copy ( source , getHome ( ) ) ; } else { LOG . debug ( "" , source . getAbsolutePath ( ) ) ; } } void deployTestDist ( ) throws IOException { LOG . debug ( "" ) ; File source = new File ( "" ) ; if ( source . exists ( ) ) { copy ( source , getHome ( ) ) ; } else { LOG . debug ( "" , source . getAbsolutePath ( ) ) ; } } void deployRuntimeLibrary ( ) throws IOException { LOG . debug ( "" ) ; runtimeLib = deployLibrary ( ToolLauncher . class , "" ) ; } public File deployLibrary ( Class < ? > memberClass , String targetPath ) throws IOException { File archive = findLibraryPathFromClass ( memberClass ) ; if ( archive == null ) { throw new IOException ( MessageFormat . format ( "" , targetPath ) ) ; } File target = new File ( getHome ( ) , targetPath ) ; deployLibrary ( archive , target ) ; return target ; } public File findLibraryPathFromClass ( Class < ? > aClass ) { if ( aClass == null ) { throw new IllegalArgumentException ( "" ) ; } int start = aClass . getName ( ) . lastIndexOf ( '' ) + ; String name = aClass . getName ( ) . substring ( start ) ; URL resource = aClass . getResource ( name + "" ) ; if ( resource == null ) { LOG . warn ( "" , aClass . getName ( ) ) ; return null ; } String protocol = resource . getProtocol ( ) ; if ( protocol . equals ( "" ) ) { File file = new File ( resource . getPath ( ) ) ; return toClassPathRoot ( aClass , file ) ; } if ( protocol . equals ( "" ) ) { String path = resource . getPath ( ) ; return toClassPathRoot ( aClass , path ) ; } else { LOG . warn ( "" , resource , aClass . getName ( ) ) ; return null ; } } private File toClassPathRoot ( Class < ? > aClass , File classFile ) { assert aClass != null ; assert classFile != null ; assert classFile . isFile ( ) ; String name = aClass . getName ( ) ; File current = classFile . getParentFile ( ) ; assert current != null && current . isDirectory ( ) : classFile ; for ( int i = name . indexOf ( '' ) ; i >= ; i = name . indexOf ( '' , i + ) ) { current = current . getParentFile ( ) ; assert current != null && current . isDirectory ( ) : classFile ; } return current ; } private File toClassPathRoot ( Class < ? > aClass , String uriQualifiedPath ) { assert aClass != null ; assert uriQualifiedPath != null ; int entry = uriQualifiedPath . lastIndexOf ( '' ) ; String qualifier ; if ( entry >= ) { qualifier = uriQualifiedPath . substring ( , entry ) ; } else { qualifier = uriQualifiedPath ; } URI archive ; try { archive = new URI ( qualifier ) ; } catch ( URISyntaxException e ) { LOG . warn ( MessageFormat . format ( "" , qualifier , aClass . getName ( ) ) , e ) ; throw new UnsupportedOperationException ( qualifier , e ) ; } if ( archive . getScheme ( ) . equals ( "" ) == false ) { LOG . warn ( "" , archive , aClass . getName ( ) ) ; return null ; } File file = new File ( archive ) ; assert file . isFile ( ) : file ; return file ; } public File deployLibrary ( File source , File target ) throws IOException { if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source . isFile ( ) ) { copy ( source , target ) ; } else { LOG . debug ( "" , source , target ) ; prepareParent ( target ) ; OutputStream output = new FileOutputStream ( target ) ; try { ZipOutputStream zip = new ZipOutputStream ( output ) ; putEntry ( zip , source , null ) ; zip . close ( ) ; } finally { output . close ( ) ; } } return target ; } private void putEntry ( ZipOutputStream zip , File source , String path ) throws IOException { assert zip != null ; assert source != null ; assert ! ( source . isFile ( ) && path == null ) ; if ( source . isDirectory ( ) ) { for ( File child : source . listFiles ( ) ) { String next = ( path == null ) ? child . getName ( ) : path + '' + child . getName ( ) ; putEntry ( zip , child , next ) ; } } else { zip . putNextEntry ( new ZipEntry ( path ) ) ; InputStream in = new FileInputStream ( source ) ; try { LOG . debug ( "" , source , path ) ; copyStream ( in , zip ) ; } finally { in . close ( ) ; } zip . closeEntry ( ) ; } } public File copy ( File source , File target ) throws IOException { if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source . isDirectory ( ) ) { for ( File child : source . listFiles ( ) ) { copy ( child , new File ( target , child . getName ( ) ) ) ; } } else { copyFile ( source , target ) ; } return target ; } public File dump ( InputStream input , File target ) throws IOException { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } prepareParent ( target ) ; OutputStream output = new FileOutputStream ( target ) ; try { copyStream ( input , output ) ; } finally { output . close ( ) ; } return target ; } private void copyFile ( File source , File target ) throws FileNotFoundException , IOException { assert source != null ; assert target != null ; InputStream input = new FileInputStream ( source ) ; try { prepareParent ( target ) ; OutputStream output = new FileOutputStream ( target ) ; try { copyStream ( input , output ) ; } finally { output . close ( ) ; } } finally { input . close ( ) ; } if ( source . canExecute ( ) ) { target . setExecutable ( true ) ; } } private void copyStream ( InputStream input , OutputStream output ) throws IOException { byte [ ] buf = new byte [ ] ; while ( true ) { int read = input . read ( buf ) ; if ( read < ) { break ; } output . write ( buf , , read ) ; } } private void prepareParent ( File target ) throws IOException { assert target != null ; if ( target . getParentFile ( ) . isDirectory ( ) == false && target . getParentFile ( ) . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , target ) ) ; } } public File extract ( File archive , File target ) throws IOException { if ( archive == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } InputStream input = new FileInputStream ( target ) ; try { ZipInputStream zip = new ZipInputStream ( input ) ; extract ( zip , target ) ; } finally { input . close ( ) ; } return target ; } public File extract ( ZipInputStream input , File target ) throws IOException { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } while ( true ) { ZipEntry entry = input . getNextEntry ( ) ; if ( entry == null ) { break ; } if ( entry . isDirectory ( ) ) { continue ; } File file = new File ( target , entry . getName ( ) ) ; dump ( input , file ) ; } return target ; } public File getHome ( ) { return home ; } public File getWork ( String child ) { File dir = new File ( work , child ) ; if ( dir . mkdirs ( ) == false && dir . isDirectory ( ) == false ) { LOG . warn ( "" , dir . getAbsolutePath ( ) ) ; } return dir ; } public File getCoreRuntimeLibrary ( ) { return runtimeLib ; } public File getCoreConfigurationFile ( ) { File conf = new File ( getHome ( ) , "" ) ; if ( conf . exists ( ) ) { return conf ; } return null ; } } package com . asakusafw . runtime . configuration ; import java . text . MessageFormat ; import junit . framework . Assert ; import org . junit . Assume ; import org . junit . rules . TestWatcher ; import org . junit . runner . Description ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; public class HadoopEnvironmentChecker extends TestWatcher { static final Logger LOG = LoggerFactory . getLogger ( HadoopEnvironmentChecker . class ) ; final boolean failOnError ; public HadoopEnvironmentChecker ( boolean failOnError ) { this . failOnError = failOnError ; } @ Override protected void starting ( Description description ) { boolean found = ConfigurationProvider . findHadoopCommand ( ) != null ; if ( found ) { return ; } if ( failOnError ) { Assert . fail ( "" ) ; } else { LOG . warn ( MessageFormat . format ( "" , description . getTestClass ( ) . getName ( ) , description . getMethodName ( ) ) ) ; Assume . assumeTrue ( false ) ; } } } package com . asakusafw . runtime . directio ; package com . asakusafw . runtime . directio ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public abstract class BinaryStreamFormat < T > implements FragmentableDataFormat < T > { @ Override public abstract long getPreferredFragmentSize ( ) throws IOException , InterruptedException ; @ Override public abstract long getMinimumFragmentSize ( ) throws IOException , InterruptedException ; public abstract ModelInput < T > createInput ( Class < ? extends T > dataType , String path , InputStream stream , long offset , long fragmentSize ) throws IOException , InterruptedException ; public abstract ModelOutput < T > createOutput ( Class < ? extends T > dataType , String path , OutputStream stream ) throws IOException , InterruptedException ; } package com . asakusafw . runtime . directio . util ; import java . io . IOException ; import java . io . OutputStream ; import com . asakusafw . runtime . directio . Counter ; public class CountOutputStream extends OutputStream { private final OutputStream stream ; private final Counter counter ; public CountOutputStream ( OutputStream stream , Counter counter ) { if ( stream == null ) { throw new IllegalArgumentException ( "" ) ; } if ( counter == null ) { throw new IllegalArgumentException ( "" ) ; } this . stream = stream ; this . counter = counter ; } public long getCount ( ) { return counter . get ( ) ; } @ Override public void write ( int b ) throws IOException { stream . write ( b ) ; counter . add ( ) ; } @ Override public void write ( byte [ ] b ) throws IOException { stream . write ( b ) ; counter . add ( b . length ) ; } @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { stream . write ( b , off , len ) ; counter . add ( len ) ; } @ Override public void flush ( ) throws IOException { stream . flush ( ) ; } @ Override public void close ( ) throws IOException { stream . close ( ) ; } } package com . asakusafw . runtime . directio . util ; import java . io . IOException ; import java . io . InputStream ; public class DelimiterRangeInputStream extends InputStream { private final InputStream origin ; private final char delimiter ; private long remaining ; private boolean endOfRange ; private final byte [ ] buffer ; private int bufferOffset ; private int bufferLimit ; public DelimiterRangeInputStream ( InputStream stream , char delimiter , long length , boolean skipFirst ) throws IOException { if ( stream == null ) { throw new IllegalArgumentException ( "" ) ; } this . origin = stream ; this . delimiter = delimiter ; this . remaining = length ; this . endOfRange = false ; this . buffer = new byte [ ] ; this . bufferOffset = ; this . bufferLimit = ; if ( remaining == ) { endOfRange = true ; } else if ( skipFirst ) { discardHead ( ) ; } } @ Override public int read ( ) throws IOException { if ( isBufferRemaining ( ) ) { return buffer [ bufferOffset ++ ] ; } if ( endOfRange ) { return - ; } if ( isSoftLimitExceeded ( ) ) { int c = origin . read ( ) ; if ( c < ) { endOfRange = true ; return - ; } if ( isDelimiter ( c ) ) { endOfRange = true ; } return c ; } else { int c = origin . read ( ) ; if ( c < ) { endOfRange = true ; return - ; } remaining -= ; return c ; } } @ Override public int read ( byte [ ] b ) throws IOException { return read ( b , , b . length ) ; } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { int bufferedSize = fillFromBuffer ( b , off , len ) ; if ( bufferedSize > ) { return bufferedSize ; } if ( endOfRange ) { return - ; } if ( isSoftLimitExceeded ( ) ) { int read = origin . read ( b , off , len ) ; if ( read < ) { endOfRange = true ; return - ; } int index = findDelimiter ( b , off , read ) ; if ( index < ) { return read ; } else { endOfRange = true ; return index - off + ; } } else { assert remaining > ; int rest = ( int ) Math . min ( len , remaining ) ; int read = origin . read ( b , off , rest ) ; if ( read < ) { endOfRange = true ; return - ; } remaining -= read ; return read ; } } @ Override public long skip ( long n ) throws IOException { if ( n <= ) { return ; } if ( isBufferRemaining ( ) ) { long bufferRest = bufferLimit - bufferOffset ; long skipped = Math . min ( n , bufferRest ) ; bufferOffset += skipped ; return skipped ; } if ( endOfRange ) { return ; } if ( isSoftLimitExceeded ( ) ) { assert isBufferRemaining ( ) == false ; int read = read ( buffer ) ; if ( read < ) { return ; } return read ; } else { assert remaining > ; long skipped = origin . skip ( Math . min ( n , remaining ) ) ; remaining -= skipped ; return skipped ; } } @ Override public int available ( ) throws IOException { return origin . available ( ) ; } @ Override public synchronized void mark ( int readlimit ) { throw new UnsupportedOperationException ( ) ; } @ Override public synchronized void reset ( ) throws IOException { throw new UnsupportedOperationException ( ) ; } @ Override public boolean markSupported ( ) { return false ; } @ Override public void close ( ) throws IOException { origin . close ( ) ; } private void discardHead ( ) throws IOException { while ( remaining > ) { int limit = ( int ) Math . min ( buffer . length , remaining ) ; int read = origin . read ( buffer , , limit ) ; if ( read < ) { endOfRange = true ; break ; } remaining -= read ; int index = findDelimiter ( buffer , , read ) ; if ( index >= ) { this . bufferOffset = index + ; this . bufferLimit = read ; return ; } } endOfRange = true ; } private int fillFromBuffer ( byte [ ] b , int off , int len ) { assert b != null ; if ( isBufferRemaining ( ) ) { int bufferLen = bufferLimit - bufferOffset ; assert bufferLen > ; int size = Math . min ( len , bufferLen ) ; System . arraycopy ( buffer , bufferOffset , b , off , size ) ; bufferOffset += size ; return size ; } return ; } private int findDelimiter ( byte [ ] bytes , int offset , int length ) { assert bytes != null ; assert length >= ; for ( int i = offset , n = offset + length ; i < n ; i ++ ) { if ( isDelimiter ( bytes [ i ] ) ) { return i ; } } return - ; } private boolean isBufferRemaining ( ) { return bufferOffset < bufferLimit ; } private boolean isSoftLimitExceeded ( ) { return remaining == ; } private boolean isDelimiter ( int c ) { return c == delimiter ; } } package com . asakusafw . runtime . directio . util ; package com . asakusafw . runtime . directio . util ; import java . io . IOException ; import java . io . InputStream ; import com . asakusafw . runtime . directio . Counter ; public class CountInputStream extends InputStream { private final InputStream target ; private final Counter counter ; public CountInputStream ( InputStream target , Counter counter ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( counter == null ) { throw new IllegalArgumentException ( "" ) ; } this . target = target ; this . counter = counter ; } public long getCount ( ) { return counter . get ( ) ; } @ Override public int read ( ) throws IOException { int read = target . read ( ) ; if ( read > ) { counter . add ( ) ; } return read ; } @ Override public int read ( byte [ ] b ) throws IOException { int read = target . read ( b ) ; if ( read > ) { counter . add ( read ) ; } return read ; } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { int read = target . read ( b , off , len ) ; if ( read > ) { counter . add ( read ) ; } return read ; } @ Override public long skip ( long n ) throws IOException { long read = target . skip ( n ) ; return read ; } @ Override public int available ( ) throws IOException { return target . available ( ) ; } @ Override public void close ( ) throws IOException { target . close ( ) ; } @ Override public synchronized void mark ( int readlimit ) { target . mark ( readlimit ) ; } @ Override public synchronized void reset ( ) throws IOException { target . reset ( ) ; } @ Override public boolean markSupported ( ) { return target . markSupported ( ) ; } } package com . asakusafw . runtime . directio ; public interface DataFormat < T > { Class < T > getSupportedType ( ) ; } package com . asakusafw . runtime . directio ; public final class DirectDataSourceConstants { public static final String KEY_BASE_PATH = "" ; public static final String KEY_RESOURCE_PATH = "" ; public static final String KEY_DATA_CLASS = "" ; public static final String KEY_FORMAT_CLASS = "" ; public static final String PREFIX_DELETE_PATTERN = "" ; private DirectDataSourceConstants ( ) { return ; } } package com . asakusafw . runtime . directio ; import java . util . concurrent . atomic . AtomicLong ; import com . asakusafw . runtime . directio . util . CountInputStream ; import com . asakusafw . runtime . directio . util . CountOutputStream ; public class Counter { private final AtomicLong entity = new AtomicLong ( ) ; public void add ( long delta ) { entity . addAndGet ( delta ) ; onChanged ( ) ; } protected void onChanged ( ) { return ; } public long get ( ) { return entity . get ( ) ; } } package com . asakusafw . runtime . directio ; import java . io . IOException ; import java . util . List ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public interface DirectDataSource { < T > List < DirectInputFragment > findInputFragments ( Class < ? extends T > dataType , DataFormat < T > format , String basePath , ResourcePattern resourcePattern ) throws IOException , InterruptedException ; < T > ModelInput < T > openInput ( Class < ? extends T > dataType , DataFormat < T > format , DirectInputFragment fragment , Counter counter ) throws IOException , InterruptedException ; < T > ModelOutput < T > openOutput ( OutputAttemptContext context , Class < ? extends T > dataType , DataFormat < T > format , String basePath , String resourcePath , Counter counter ) throws IOException , InterruptedException ; List < ResourceInfo > list ( String basePath , ResourcePattern resourcePattern , Counter counter ) throws IOException , InterruptedException ; boolean delete ( String basePath , ResourcePattern resourcePattern , boolean recursive , Counter counter ) throws IOException , InterruptedException ; void setupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException ; void commitAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException ; void cleanupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException ; void setupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException ; void commitTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException ; void cleanupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException ; } package com . asakusafw . runtime . directio ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . BitSet ; import java . util . Collections ; import java . util . List ; public class FilePattern implements ResourcePattern { private static final int CHAR_ESCAPE = '' ; private static final int CHAR_SEPARATOR = '' ; private static final int CHAR_ASTERISK = '' ; private static final int CHAR_BAR = '' ; private static final int CHAR_DOLLER = '' ; private static final int CHAR_QUESTION = '' ; private static final int CHAR_NUMBER = '' ; private static final int CHAR_OPEN_BRACE = '' ; private static final int CHAR_CLOSE_BRACE = '' ; private static final int CHAR_OPEN_BRACKET = '' ; private static final int CHAR_CLOSE_BRACKET = '' ; private static final int CHAR_EOF = - ; private static final int CHAR_ALPHABET = - ; static final BitSet CHARMAP_META ; static { BitSet set = new BitSet ( ) ; set . set ( , ) ; set . set ( CHAR_ESCAPE ) ; set . set ( CHAR_SEPARATOR ) ; set . set ( CHAR_ASTERISK ) ; set . set ( CHAR_BAR ) ; set . set ( CHAR_DOLLER ) ; set . set ( CHAR_QUESTION ) ; set . set ( CHAR_NUMBER ) ; set . set ( CHAR_OPEN_BRACE ) ; set . set ( CHAR_CLOSE_BRACE ) ; set . set ( CHAR_OPEN_BRACKET ) ; set . set ( CHAR_CLOSE_BRACKET ) ; CHARMAP_META = set ; } private final List < Segment > segments ; private final String patternString ; FilePattern ( List < Segment > segments , String patternString ) { assert segments != null ; assert patternString != null ; assert segments . isEmpty ( ) == false ; this . segments = Collections . unmodifiableList ( segments ) ; this . patternString = patternString ; } public boolean containsVariables ( ) { for ( Segment segment : segments ) { for ( PatternElement element : segment . getElements ( ) ) { if ( element . getKind ( ) == PatternElementKind . VARIABLE ) { return true ; } } } return false ; } public List < Segment > getSegments ( ) { return segments ; } public String getPatternString ( ) { return patternString ; } @ Override public String toString ( ) { return patternString ; } public static FilePattern compile ( String patternString ) { if ( patternString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( patternString . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } List < Segment > segments = compileSegments ( patternString ) ; return new FilePattern ( segments , patternString ) ; } private static List < Segment > compileSegments ( String patternString ) { assert patternString != null ; Cursor cursor = new Cursor ( patternString . toCharArray ( ) ) ; List < Segment > segments = new ArrayList < Segment > ( ) ; cursor . skipWhile ( CHAR_SEPARATOR ) ; while ( cursor . get ( ) != CHAR_EOF ) { Segment segment = consumeSegment ( cursor ) ; segments . add ( segment ) ; } return segments ; } private static Segment consumeSegment ( Cursor cursor ) { assert cursor != null ; int first = cursor . get ( ) ; assert first != CHAR_SEPARATOR && first != CHAR_EOF : cursor ; if ( first == CHAR_ASTERISK && cursor . get ( ) == CHAR_ASTERISK && ( cursor . get ( ) == CHAR_SEPARATOR || cursor . get ( ) == CHAR_EOF ) ) { cursor . skipWhile ( CHAR_ASTERISK ) ; cursor . skipWhile ( CHAR_SEPARATOR ) ; return Segment . TRAVERSE ; } List < PatternElement > elements = consumeElements ( cursor ) ; return new Segment ( elements ) ; } private static List < PatternElement > consumeElements ( Cursor cursor ) { assert cursor != null ; ArrayList < PatternElement > results = new ArrayList < PatternElement > ( ) ; LOOP : while ( true ) { int c = cursor . get ( ) ; switch ( c ) { case CHAR_EOF : break LOOP ; case CHAR_SEPARATOR : cursor . skipWhile ( CHAR_SEPARATOR ) ; break LOOP ; case CHAR_ASTERISK : if ( cursor . get ( ) == CHAR_ASTERISK ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , cursor , cursor . getOffset ( ) ) ) ; } cursor . skip ( ) ; results . add ( SingletonPatternElement . WILDCARD ) ; break ; case CHAR_OPEN_BRACE : results . add ( new Selection ( cursor . consumeSelection ( ) ) ) ; break ; case CHAR_DOLLER : results . add ( new Variable ( cursor . consumeVariable ( ) ) ) ; break ; case CHAR_ALPHABET : results . add ( new Token ( cursor . consumeToken ( ) ) ) ; break ; default : throw new IllegalArgumentException ( MessageFormat . format ( "" , cursor , cursor . getOffset ( ) , ( char ) c ) ) ; } } return results ; } private static class Cursor { private final char [ ] cbuf ; private int cursor ; Cursor ( char [ ] cbuf ) { assert cbuf != null ; this . cbuf = cbuf ; this . cursor = ; } @ Override public String toString ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = cursor ; i < n ; i ++ ) { buf . append ( cbuf [ i ] ) ; } buf . append ( "" ) ; for ( int i = cursor , n = cbuf . length ; i < n ; i ++ ) { buf . append ( cbuf [ i ] ) ; } return buf . toString ( ) ; } int getOffset ( ) { return cursor ; } int get ( int offset ) { if ( cursor + offset >= cbuf . length ) { return CHAR_EOF ; } char c = cbuf [ cursor + offset ] ; if ( CHARMAP_META . get ( c ) ) { return c ; } return CHAR_ALPHABET ; } void skip ( ) { cursor = Math . min ( cbuf . length , cursor + ) ; } void skipWhile ( int kind ) { while ( true ) { int result = get ( ) ; if ( result == CHAR_EOF || result != kind ) { break ; } skip ( ) ; } } String consumeToken ( ) { StringBuilder buf = new StringBuilder ( ) ; while ( true ) { int kind = get ( ) ; if ( kind != CHAR_ALPHABET ) { break ; } buf . append ( cbuf [ cursor ] ) ; skip ( ) ; } return buf . toString ( ) ; } String consumeVariable ( ) { assert get ( ) == CHAR_DOLLER ; int start = cursor ; skip ( ) ; if ( get ( ) != CHAR_OPEN_BRACE ) { cursor = start ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this , cursor ) ) ; } skip ( ) ; int nameStart = cursor ; skipWhile ( CHAR_ALPHABET ) ; if ( get ( ) != CHAR_CLOSE_BRACE ) { cursor = start ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this , cursor ) ) ; } String name = String . valueOf ( cbuf , nameStart , cursor - nameStart ) ; skip ( ) ; return name ; } public List < String > consumeSelection ( ) { assert get ( ) == CHAR_OPEN_BRACE ; int start = cursor ; skip ( ) ; List < String > contents = new ArrayList < String > ( ) ; boolean head = true ; while ( true ) { int first = get ( ) ; if ( first == CHAR_EOF ) { cursor = start ; throw new IllegalArgumentException ( MessageFormat . format ( "" , this , cursor ) ) ; } else if ( head || first == CHAR_BAR ) { if ( head == false ) { assert get ( ) == CHAR_BAR ; skip ( ) ; } int alterStart = cursor ; while ( true ) { skipWhile ( CHAR_ALPHABET ) ; if ( get ( ) == CHAR_SEPARATOR ) { skip ( ) ; } else { break ; } } contents . add ( String . valueOf ( cbuf , alterStart , cursor - alterStart ) ) ; } else if ( first == CHAR_CLOSE_BRACE ) { skip ( ) ; break ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , this , cursor ) ) ; } head = false ; } return contents ; } } public static final class Segment { private final List < PatternElement > elements ; static final Segment TRAVERSE = new Segment ( Collections . < PatternElement > emptyList ( ) ) ; Segment ( List < PatternElement > elements ) { assert elements != null ; boolean sawWildcard = false ; for ( PatternElement element : elements ) { boolean isWildcard = element . getKind ( ) == PatternElementKind . WILDCARD ; assert sawWildcard == false || isWildcard == false ; sawWildcard = isWildcard ; } this . elements = Collections . unmodifiableList ( elements ) ; } public List < PatternElement > getElements ( ) { return elements ; } public boolean isTraverse ( ) { return elements . isEmpty ( ) ; } } public enum PatternElementKind { TOKEN , VARIABLE , SELECTION , WILDCARD , } public interface PatternElement { PatternElementKind getKind ( ) ; String getToken ( ) ; } private enum SingletonPatternElement implements PatternElement { WILDCARD { @ Override public PatternElementKind getKind ( ) { return PatternElementKind . WILDCARD ; } @ Override public String getToken ( ) { return "" ; } } , ; @ Override public String toString ( ) { return getToken ( ) ; } } private static class Token implements PatternElement { private final String contents ; Token ( String contents ) { assert contents != null ; assert contents . isEmpty ( ) == false ; this . contents = contents ; } @ Override public PatternElementKind getKind ( ) { return PatternElementKind . TOKEN ; } @ Override public String getToken ( ) { return contents ; } @ Override public String toString ( ) { return getToken ( ) ; } } public static class Variable implements PatternElement { private final String name ; Variable ( String name ) { assert name != null ; this . name = name ; } public String getName ( ) { return name ; } @ Override public PatternElementKind getKind ( ) { return PatternElementKind . VARIABLE ; } @ Override public String getToken ( ) { return String . format ( "" , getName ( ) ) ; } @ Override public String toString ( ) { return getToken ( ) ; } } public static class Selection implements PatternElement { private final List < String > contents ; Selection ( List < String > contents ) { assert contents != null ; assert contents . isEmpty ( ) == false ; this . contents = Collections . unmodifiableList ( contents ) ; } public List < String > getContents ( ) { return contents ; } @ Override public PatternElementKind getKind ( ) { return PatternElementKind . SELECTION ; } @ Override public String getToken ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( ( char ) CHAR_OPEN_BRACE ) ; if ( contents . isEmpty ( ) == false ) { buf . append ( contents . get ( ) ) ; for ( int i = , n = contents . size ( ) ; i < n ; i ++ ) { buf . append ( ( char ) CHAR_BAR ) ; buf . append ( contents . get ( i ) ) ; } } buf . append ( ( char ) CHAR_CLOSE_BRACE ) ; return buf . toString ( ) ; } @ Override public String toString ( ) { return getToken ( ) ; } } } package com . asakusafw . runtime . directio ; import java . util . Collections ; import java . util . List ; import java . util . Map ; public final class DirectInputFragment { private final String path ; private final long offset ; private final long length ; private final List < String > ownerNodeNames ; private final Map < String , String > attributes ; public DirectInputFragment ( String path , long offset , long length , List < String > ownerNodeNames ) { this ( path , offset , length , ownerNodeNames , Collections . < String , String > emptyMap ( ) ) ; } public DirectInputFragment ( String path , long offset , long length , List < String > ownerNodeNames , Map < String , String > attributes ) { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } if ( ownerNodeNames == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } this . path = path ; this . offset = offset ; this . length = length ; this . ownerNodeNames = ownerNodeNames ; this . attributes = attributes ; } public String getPath ( ) { return path ; } public long getOffset ( ) { return offset ; } public long getSize ( ) { return length ; } public List < String > getOwnerNodeNames ( ) { return ownerNodeNames ; } public Map < String , String > getAttributes ( ) { return attributes ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( path ) ; builder . append ( "" ) ; builder . append ( offset ) ; builder . append ( "" ) ; builder . append ( length ) ; builder . append ( "" ) ; builder . append ( ownerNodeNames ) ; builder . append ( "" ) ; builder . append ( attributes ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . runtime . directio ; import java . io . IOException ; public abstract class AbstractDirectDataSource implements DirectDataSource { public abstract void configure ( DirectDataSourceProfile profile ) throws IOException , InterruptedException ; } package com . asakusafw . runtime . directio . keepalive ; import java . io . Closeable ; import java . io . IOException ; import java . lang . Thread . State ; import java . text . MessageFormat ; import java . util . List ; import java . util . concurrent . CopyOnWriteArrayList ; import java . util . concurrent . atomic . AtomicInteger ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . asakusafw . runtime . directio . Counter ; class HeartbeatKeeper implements Closeable { static final Log LOG = LogFactory . getLog ( HeartbeatKeeper . class ) ; static final AtomicInteger THREAD_SERIAL = new AtomicInteger ( ) ; final List < Counter > counters = new CopyOnWriteArrayList < Counter > ( ) ; private final long interval ; private final Thread daemon ; public HeartbeatKeeper ( final long interval ) { this . interval = interval ; this . daemon = new Thread ( new Runnable ( ) { @ Override public void run ( ) { keepAlive ( ) ; } } ) ; daemon . setName ( String . format ( "" , THREAD_SERIAL . incrementAndGet ( ) ) ) ; daemon . setDaemon ( true ) ; } public void register ( Counter counter ) { if ( counter == null ) { throw new IllegalArgumentException ( "" ) ; } counter . add ( ) ; counters . add ( counter ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , daemon . getName ( ) , daemon . getState ( ) , counter ) ) ; } synchronized ( daemon ) { if ( daemon . getState ( ) == State . NEW ) { LOG . info ( MessageFormat . format ( "" , daemon . getName ( ) ) ) ; daemon . start ( ) ; } } } public void unregister ( Counter counter ) { if ( counter == null ) { throw new IllegalArgumentException ( "" ) ; } boolean removed = counters . remove ( counter ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , daemon . getName ( ) , daemon . getState ( ) , counter ) ) ; } if ( removed == false ) { LOG . warn ( MessageFormat . format ( "" , counter ) ) ; } } void keepAlive ( ) { if ( interval <= ) { return ; } try { while ( true ) { if ( LOG . isDebugEnabled ( ) && counters . isEmpty ( ) == false ) { LOG . debug ( MessageFormat . format ( "" , Thread . currentThread ( ) . getName ( ) , counters . size ( ) ) ) ; } for ( Counter counter : counters ) { counter . add ( ) ; } Thread . sleep ( interval ) ; } } catch ( InterruptedException e ) { LOG . info ( MessageFormat . format ( "" , Thread . currentThread ( ) . getName ( ) , counters . size ( ) ) ) ; } } boolean isEmpty ( ) { return counters . isEmpty ( ) ; } @ Override public void close ( ) throws IOException { synchronized ( daemon ) { if ( daemon . isAlive ( ) ) { daemon . interrupt ( ) ; } } } @ Override protected void finalize ( ) throws Throwable { try { close ( ) ; } finally { super . finalize ( ) ; } } } package com . asakusafw . runtime . directio . keepalive ; package com . asakusafw . runtime . directio . keepalive ; import java . io . IOException ; import java . util . List ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectInputFragment ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . OutputTransactionContext ; import com . asakusafw . runtime . directio . ResourceInfo ; import com . asakusafw . runtime . directio . ResourcePattern ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class KeepAliveDataSource implements DirectDataSource { private final DirectDataSource entity ; final HeartbeatKeeper heartbeat ; public KeepAliveDataSource ( DirectDataSource entity , long interval ) { if ( entity == null ) { throw new IllegalArgumentException ( "" ) ; } this . entity = entity ; this . heartbeat = new HeartbeatKeeper ( interval ) ; } @ Override public < T > List < DirectInputFragment > findInputFragments ( Class < ? extends T > dataType , DataFormat < T > format , String basePath , ResourcePattern resourcePattern ) throws IOException , InterruptedException { return entity . findInputFragments ( dataType , format , basePath , resourcePattern ) ; } @ Override public < T > ModelInput < T > openInput ( Class < ? extends T > dataType , DataFormat < T > format , DirectInputFragment fragment , Counter counter ) throws IOException , InterruptedException { ModelInput < T > input = entity . openInput ( dataType , format , fragment , counter ) ; return new WrappedModelInput < T > ( input , heartbeat , counter ) ; } @ Override public < T > ModelOutput < T > openOutput ( OutputAttemptContext context , Class < ? extends T > dataType , DataFormat < T > format , String basePath , String resourcePath , Counter counter ) throws IOException , InterruptedException { ModelOutput < T > output = entity . openOutput ( context , dataType , format , basePath , resourcePath , counter ) ; return new WrappedModelOutput < T > ( output , heartbeat , counter ) ; } @ Override public List < ResourceInfo > list ( String basePath , ResourcePattern resourcePattern , Counter counter ) throws IOException , InterruptedException { heartbeat . register ( counter ) ; try { return entity . list ( basePath , resourcePattern , counter ) ; } finally { heartbeat . unregister ( counter ) ; } } @ Override public boolean delete ( String basePath , ResourcePattern resourcePattern , boolean recursive , Counter counter ) throws IOException , InterruptedException { heartbeat . register ( counter ) ; try { return entity . delete ( basePath , resourcePattern , recursive , counter ) ; } finally { heartbeat . unregister ( counter ) ; } } @ Override public void setupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } Counter counter = context . getCounter ( ) ; heartbeat . register ( counter ) ; try { entity . setupAttemptOutput ( context ) ; } finally { heartbeat . unregister ( counter ) ; } } @ Override public void commitAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } Counter counter = context . getCounter ( ) ; heartbeat . register ( counter ) ; try { entity . commitAttemptOutput ( context ) ; } finally { heartbeat . unregister ( counter ) ; } } @ Override public void cleanupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } Counter counter = context . getCounter ( ) ; heartbeat . register ( counter ) ; try { entity . cleanupAttemptOutput ( context ) ; } finally { heartbeat . unregister ( counter ) ; } } @ Override public void setupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } Counter counter = context . getCounter ( ) ; heartbeat . register ( counter ) ; try { entity . setupTransactionOutput ( context ) ; } finally { heartbeat . unregister ( counter ) ; } } @ Override public void commitTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } Counter counter = context . getCounter ( ) ; heartbeat . register ( counter ) ; try { entity . commitTransactionOutput ( context ) ; } finally { heartbeat . unregister ( counter ) ; } } @ Override public void cleanupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } Counter counter = context . getCounter ( ) ; heartbeat . register ( counter ) ; try { entity . cleanupTransactionOutput ( context ) ; } finally { heartbeat . unregister ( counter ) ; } } private static final class WrappedModelInput < T > implements ModelInput < T > { private final ModelInput < T > component ; private final HeartbeatKeeper keeper ; private final Counter counter ; private boolean closed = false ; WrappedModelInput ( ModelInput < T > component , HeartbeatKeeper keeper , Counter counter ) { assert component != null ; assert keeper != null ; assert counter != null ; this . component = component ; this . keeper = keeper ; this . counter = counter ; keeper . register ( counter ) ; } @ Override public boolean readTo ( T model ) throws IOException { return component . readTo ( model ) ; } @ Override public void close ( ) throws IOException { if ( closed ) { return ; } try { component . close ( ) ; } finally { keeper . unregister ( counter ) ; closed = true ; } } } private static final class WrappedModelOutput < T > implements ModelOutput < T > { private final ModelOutput < T > component ; private final HeartbeatKeeper keeper ; private final Counter counter ; private boolean closed = false ; WrappedModelOutput ( ModelOutput < T > component , HeartbeatKeeper keeper , Counter counter ) { assert component != null ; assert keeper != null ; assert counter != null ; this . component = component ; this . keeper = keeper ; this . counter = counter ; keeper . register ( counter ) ; } @ Override public void write ( T model ) throws IOException { component . write ( model ) ; } @ Override public void close ( ) throws IOException { if ( closed ) { return ; } try { component . close ( ) ; } finally { keeper . unregister ( counter ) ; closed = true ; } } } } package com . asakusafw . runtime . directio ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . Map ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class DirectDataSourceRepository { static final Log LOG = LogFactory . getLog ( DirectDataSourceRepository . class ) ; private final Node root = new Node ( ) ; public DirectDataSourceRepository ( Collection < ? extends DirectDataSourceProvider > providers ) { if ( providers == null ) { throw new IllegalArgumentException ( "" ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , providers . size ( ) ) ) ; } for ( DirectDataSourceProvider provider : providers ) { NodePath path = NodePath . of ( provider . getPath ( ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , provider . getId ( ) , path ) ) ; } Node current = root ; for ( String segment : path ) { current = current . addChild ( segment ) ; } if ( current . hasContent ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , path , provider , current . provider ) ) ; } current . provider = provider ; } } private Node findNode ( NodePath path ) throws IOException { assert path != null ; Node lastContent = null ; Node current = root ; for ( String segment : path ) { if ( current . hasContent ( ) ) { lastContent = current ; } Node next = current . getChild ( segment ) ; if ( next == null ) { break ; } current = next ; } if ( current . hasContent ( ) ) { lastContent = current ; } if ( lastContent == null ) { throw new IOException ( MessageFormat . format ( "" , path ) ) ; } return lastContent ; } public String getRelatedId ( String path ) throws IOException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } NodePath nodePath = NodePath . of ( path ) ; Node node = findNode ( nodePath ) ; assert node != null ; assert node . hasContent ( ) ; return node . getId ( ) ; } public DirectDataSource getRelatedDataSource ( String path ) throws IOException , InterruptedException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } NodePath nodePath = NodePath . of ( path ) ; Node node = findNode ( nodePath ) ; assert node != null ; assert node . hasContent ( ) ; return node . getInstance ( ) ; } public String getContainerPath ( String path ) throws IOException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } NodePath nodePath = NodePath . of ( path ) ; Node node = findNode ( nodePath ) ; assert node != null ; int depth = node . getDepth ( ) ; return nodePath . subPath ( , depth ) . getPathString ( ) ; } public String getComponentPath ( String path ) throws IOException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } NodePath nodePath = NodePath . of ( path ) ; Node node = findNode ( nodePath ) ; assert node != null ; int depth = node . getDepth ( ) ; return nodePath . subPath ( depth , nodePath . size ( ) ) . getPathString ( ) ; } public Collection < String > getContainerPaths ( ) throws IOException , InterruptedException { Collection < String > results = new ArrayList < String > ( ) ; LinkedList < Node > work = new LinkedList < Node > ( ) ; work . add ( root ) ; while ( work . isEmpty ( ) == false ) { Node node = work . removeFirst ( ) ; if ( node . hasContent ( ) ) { results . add ( node . path . getPathString ( ) ) ; } work . addAll ( node . children . values ( ) ) ; } return results ; } private final class Node { final Node parent ; final NodePath path ; final Map < String , Node > children = new HashMap < String , Node > ( ) ; volatile DirectDataSourceProvider provider ; private DirectDataSource instance ; Node ( ) { this . parent = null ; this . path = NodePath . ROOT ; } Node ( Node parent , String name ) { assert parent != null ; assert name != null ; this . parent = parent ; this . path = parent . path . append ( name ) ; } String getId ( ) { if ( provider == null ) { throw new IllegalStateException ( ) ; } return provider . getId ( ) ; } synchronized DirectDataSource getInstance ( ) throws IOException , InterruptedException { if ( provider == null ) { throw new IllegalStateException ( ) ; } if ( instance == null ) { instance = provider . newInstance ( ) ; } return instance ; } Node addChild ( String childName ) { Node child = getChild ( childName ) ; if ( child == null ) { child = new Node ( this , childName ) ; children . put ( childName , child ) ; } return child ; } Node getChild ( String childName ) { return children . get ( childName ) ; } int getDepth ( ) { int depth = ; for ( Node current = parent ; current != null ; current = current . parent ) { depth ++ ; } return depth ; } boolean hasContent ( ) { return provider != null ; } } private static final class NodePath implements Comparable < NodePath > , Iterable < String > { static final NodePath ROOT = new NodePath ( new ArrayList < String > ( ) ) ; private final ArrayList < String > segments ; private NodePath ( ArrayList < String > segments ) { assert segments != null ; this . segments = segments ; } public NodePath append ( String name ) { assert name != null ; ArrayList < String > newSegments = new ArrayList < String > ( segments . size ( ) + ) ; newSegments . addAll ( segments ) ; newSegments . add ( name ) ; return new NodePath ( newSegments ) ; } public static NodePath of ( String pathString ) { if ( pathString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( pathString . isEmpty ( ) ) { return ROOT ; } String [ ] fields = pathString . split ( "" ) ; ArrayList < String > segments = new ArrayList < String > ( ) ; for ( String s : fields ) { if ( s . isEmpty ( ) == false ) { segments . add ( s ) ; } } return new NodePath ( segments ) ; } public NodePath subPath ( int start , int end ) { ArrayList < String > other = new ArrayList < String > ( end - start ) ; for ( int i = start ; i < end ; i ++ ) { other . add ( segments . get ( i ) ) ; } return new NodePath ( other ) ; } @ Override public Iterator < String > iterator ( ) { return segments . iterator ( ) ; } public int size ( ) { return segments . size ( ) ; } public String getPathString ( ) { if ( segments . isEmpty ( ) ) { return "" ; } StringBuilder buf = new StringBuilder ( ) ; ArrayList < String > copy = segments ; buf . append ( copy . get ( ) ) ; for ( int i = , n = copy . size ( ) ; i < n ; i ++ ) { buf . append ( '' ) ; buf . append ( copy . get ( i ) ) ; } return buf . toString ( ) ; } @ Deprecated @ Override public String toString ( ) { if ( segments . isEmpty ( ) ) { return "" ; } else { return getPathString ( ) ; } } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + segments . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } NodePath other = ( NodePath ) obj ; if ( ! segments . equals ( other . segments ) ) { return false ; } return true ; } @ Override public int compareTo ( NodePath o ) { ArrayList < String > a = segments ; ArrayList < String > b = o . segments ; for ( int i = , n = Math . min ( a . size ( ) , b . size ( ) ) ; i < n ; i ++ ) { int cmp = a . get ( i ) . compareTo ( b . get ( i ) ) ; if ( cmp != ) { return cmp ; } } if ( a . size ( ) > b . size ( ) ) { return + ; } else if ( a . size ( ) < b . size ( ) ) { return - ; } return ; } } } package com . asakusafw . runtime . directio ; public class ResourceInfo { private final String id ; private final String path ; private final boolean directory ; public ResourceInfo ( String id , String path ) { this ( id , path , false ) ; } public ResourceInfo ( String id , String path , boolean directory ) { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = id ; this . path = path ; this . directory = directory ; } public String getId ( ) { return id ; } public String getPath ( ) { return path ; } public boolean isDirectory ( ) { return directory ; } } package com . asakusafw . runtime . directio ; import java . io . IOException ; public interface FragmentableDataFormat < T > extends DataFormat < T > { long getPreferredFragmentSize ( ) throws IOException , InterruptedException ; long getMinimumFragmentSize ( ) throws IOException , InterruptedException ; } package com . asakusafw . runtime . directio ; public final class OutputAttemptContext { private final String transactionId ; private final String attemptId ; private final String outputId ; private final Counter counter ; public OutputAttemptContext ( String transactionId , String attemptId , String outputId , Counter counter ) { if ( transactionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attemptId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( counter == null ) { throw new IllegalArgumentException ( "" ) ; } this . transactionId = transactionId ; this . attemptId = attemptId ; this . outputId = outputId ; this . counter = counter ; } public OutputTransactionContext getTransactionContext ( ) { return new OutputTransactionContext ( transactionId , outputId , counter ) ; } public String getTransactionId ( ) { return transactionId ; } public String getAttemptId ( ) { return attemptId ; } public String getOutputId ( ) { return outputId ; } public Counter getCounter ( ) { return counter ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( transactionId ) ; builder . append ( "" ) ; builder . append ( attemptId ) ; builder . append ( "" ) ; builder . append ( outputId ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . runtime . directio ; import java . util . Map ; public class DirectDataSourceProfile { private final String id ; private final Class < ? extends AbstractDirectDataSource > targetClass ; private final String path ; private final Map < String , String > attributes ; public DirectDataSourceProfile ( String id , Class < ? extends AbstractDirectDataSource > targetClass , String path , Map < String , String > attributes ) { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = id ; this . targetClass = targetClass ; this . path = path ; this . attributes = attributes ; } public String getId ( ) { return id ; } public Class < ? extends AbstractDirectDataSource > getTargetClass ( ) { return targetClass ; } public String getPath ( ) { return path ; } public Map < String , String > getAttributes ( ) { return attributes ; } } package com . asakusafw . runtime . directio ; import java . io . IOException ; public interface DirectDataSourceProvider { String getId ( ) ; String getPath ( ) ; DirectDataSource newInstance ( ) throws IOException , InterruptedException ; } package com . asakusafw . runtime . directio ; public final class OutputTransactionContext { private final String transactionId ; private final String outputId ; private final Counter counter ; public OutputTransactionContext ( String transactionId , String outputId , Counter counter ) { if ( transactionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( counter == null ) { throw new IllegalArgumentException ( "" ) ; } this . transactionId = transactionId ; this . outputId = outputId ; this . counter = counter ; } public String getTransactionId ( ) { return transactionId ; } public String getOutputId ( ) { return outputId ; } public Counter getCounter ( ) { return counter ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( transactionId ) ; builder . append ( "" ) ; builder . append ( outputId ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . runtime . directio . hadoop ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Map ; import java . util . TreeSet ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . LocalFileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . runtime . directio . DirectDataSourceProfile ; import com . asakusafw . runtime . directio . FragmentableDataFormat ; public class HadoopDataSourceProfile { static final Log LOG = LogFactory . getLog ( HadoopDataSourceProfile . class ) ; private static final String ROOT_REPRESENTATION = "" ; public static final String KEY_PATH = "" ; public static final String KEY_TEMP = "" ; public static final String KEY_OUTPUT_STAGING = "" ; public static final String KEY_OUTPUT_STREAMING = "" ; public static final String KEY_MIN_FRAGMENT = "" ; public static final String KEY_PREF_FRAGMENT = "" ; public static final String KEY_SPLIT_BLOCKS = "" ; public static final String KEY_COMBINE_BLOCKS = "" ; public static final String KEY_KEEPALIVE_INTERVAL = "" ; private static final String DEFAULT_TEMP_SUFFIX = "" ; private static final boolean DEFAULT_OUTPUT_STAGING = true ; private static final boolean DEFAULT_OUTPUT_STREAMING = true ; private static final long DEFAULT_MIN_FRAGMENT = * * ; private static final long DEFAULT_PREF_FRAGMENT = * * ; private static final boolean DEFAULT_SPLIT_BLOCKS = true ; private static final boolean DEFAULT_COMBINE_BLOCKS = true ; private static final long DEFAULT_KEEPALIVE_INTERVAL = ; private final String id ; private final String contextPath ; private final Path fileSystemPath ; private final Path temporaryPath ; private boolean outputStaging = DEFAULT_OUTPUT_STAGING ; private boolean outputStreaming = DEFAULT_OUTPUT_STREAMING ; private long minimumFragmentSize = DEFAULT_MIN_FRAGMENT ; private long preferredFragmentSize = DEFAULT_PREF_FRAGMENT ; private boolean splitBlocks = DEFAULT_SPLIT_BLOCKS ; private boolean combineBlocks = DEFAULT_COMBINE_BLOCKS ; private long keepAliveInterval = DEFAULT_KEEPALIVE_INTERVAL ; private final FileSystem fileSystem ; private final LocalFileSystem localFileSystem ; public HadoopDataSourceProfile ( Configuration conf , String id , String contextPath , Path fileSystemPath , Path temporaryPath ) throws IOException { this . id = id ; this . contextPath = contextPath ; this . fileSystemPath = fileSystemPath ; this . temporaryPath = temporaryPath ; this . fileSystem = fileSystemPath . getFileSystem ( conf ) ; this . localFileSystem = FileSystem . getLocal ( conf ) ; } public String getId ( ) { return id ; } public String getContextPath ( ) { return contextPath ; } public Path getFileSystemPath ( ) { return fileSystemPath ; } public Path getTemporaryFileSystemPath ( ) { return temporaryPath ; } public FileSystem getFileSystem ( ) { return fileSystem ; } public LocalFileSystem getLocalFileSystem ( ) { return localFileSystem ; } public long getMinimumFragmentSize ( FragmentableDataFormat < ? > format ) throws IOException , InterruptedException { if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } long formatMin = format . getMinimumFragmentSize ( ) ; long totalMin = Math . min ( formatMin , minimumFragmentSize ) ; if ( totalMin <= ) { return - ; } return totalMin ; } public void setMinimumFragmentSize ( long size ) { if ( size <= ) { this . minimumFragmentSize = - ; } this . minimumFragmentSize = size ; } public long getPreferredFragmentSize ( FragmentableDataFormat < ? > format ) throws IOException , InterruptedException { if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } long min = getMinimumFragmentSize ( format ) ; if ( min <= ) { return - ; } long formatPref = format . getPreferredFragmentSize ( ) ; if ( formatPref > ) { return Math . max ( formatPref , min ) ; } return Math . max ( preferredFragmentSize , min ) ; } public void setPreferredFragmentSize ( long size ) { this . preferredFragmentSize = Math . max ( size , ) ; } public boolean isSplitBlocks ( ) { return splitBlocks ; } public void setSplitBlocks ( boolean split ) { this . splitBlocks = split ; } public boolean isCombineBlocks ( ) { return combineBlocks ; } public void setCombineBlocks ( boolean combine ) { this . combineBlocks = combine ; } public boolean isOutputStaging ( ) { return outputStaging ; } public void setOutputStaging ( boolean required ) { this . outputStaging = required ; } public boolean isOutputStreaming ( ) { return outputStreaming ; } public void setOutputStreaming ( boolean required ) { this . outputStreaming = required ; } public long getKeepAliveInterval ( ) { return keepAliveInterval ; } public void setKeepAliveInterval ( long interval ) { this . keepAliveInterval = interval ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( id ) ; builder . append ( "" ) ; builder . append ( contextPath ) ; builder . append ( "" ) ; builder . append ( fileSystemPath ) ; builder . append ( "" ) ; builder . append ( temporaryPath ) ; builder . append ( "" ) ; builder . append ( outputStaging ) ; builder . append ( "" ) ; builder . append ( outputStreaming ) ; builder . append ( "" ) ; builder . append ( minimumFragmentSize ) ; builder . append ( "" ) ; builder . append ( preferredFragmentSize ) ; builder . append ( "" ) ; builder . append ( splitBlocks ) ; builder . append ( "" ) ; builder . append ( combineBlocks ) ; builder . append ( "" ) ; builder . append ( keepAliveInterval ) ; builder . append ( "" ) ; builder . append ( fileSystem ) ; builder . append ( "" ) ; builder . append ( localFileSystem ) ; builder . append ( "" ) ; return builder . toString ( ) ; } public static HadoopDataSourceProfile convert ( DirectDataSourceProfile profile , Configuration conf ) throws IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } Map < String , String > attributes = new HashMap < String , String > ( profile . getAttributes ( ) ) ; Path fsPath = takeFsPath ( profile , attributes , conf ) ; if ( fsPath == null ) { throw new IOException ( MessageFormat . format ( "" , profile . getId ( ) , profile . getPath ( ) . isEmpty ( ) ? ROOT_REPRESENTATION : profile . getPath ( ) , fqn ( profile , KEY_PATH ) ) ) ; } Path tempPath = takeTempPath ( profile , attributes , conf , fsPath ) ; FileSystem fileSystem = fsPath . getFileSystem ( conf ) ; FileSystem tempFs = tempPath . getFileSystem ( conf ) ; if ( getFsIdentity ( fileSystem ) . equals ( getFsIdentity ( tempFs ) ) == false ) { throw new IOException ( MessageFormat . format ( "" , fqn ( profile , KEY_PATH ) , fsPath , fqn ( profile , KEY_TEMP ) , tempPath ) ) ; } fsPath = fsPath . makeQualified ( fileSystem ) ; tempPath = tempPath . makeQualified ( fileSystem ) ; HadoopDataSourceProfile result = new HadoopDataSourceProfile ( conf , profile . getId ( ) , profile . getPath ( ) , fsPath , tempPath ) ; long minFragment = takeMinFragment ( profile , attributes , conf ) ; result . setMinimumFragmentSize ( minFragment ) ; long prefFragment = takePrefFragment ( profile , attributes , conf ) ; result . setPreferredFragmentSize ( prefFragment ) ; result . setOutputStaging ( takeBoolean ( profile , attributes , KEY_OUTPUT_STAGING , DEFAULT_OUTPUT_STAGING ) ) ; result . setOutputStreaming ( takeBoolean ( profile , attributes , KEY_OUTPUT_STREAMING , DEFAULT_OUTPUT_STREAMING ) ) ; result . setSplitBlocks ( takeBoolean ( profile , attributes , KEY_SPLIT_BLOCKS , DEFAULT_SPLIT_BLOCKS ) ) ; result . setCombineBlocks ( takeBoolean ( profile , attributes , KEY_COMBINE_BLOCKS , DEFAULT_COMBINE_BLOCKS ) ) ; result . setKeepAliveInterval ( takeKeepAliveInterval ( profile , attributes , conf ) ) ; if ( attributes . isEmpty ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , profile . getId ( ) , new TreeSet < String > ( attributes . keySet ( ) ) ) ) ; } return result ; } static String getFsIdentity ( FileSystem fileSystem ) { assert fileSystem != null ; return fileSystem . getUri ( ) . toString ( ) ; } private static Object fqn ( DirectDataSourceProfile profile , String key ) { assert profile != null ; assert key != null ; return MessageFormat . format ( "" , profile . getId ( ) , key ) ; } private static Path takeFsPath ( DirectDataSourceProfile profile , Map < String , String > attributes , Configuration conf ) { assert conf != null ; assert attributes != null ; String fsPathString = attributes . remove ( KEY_PATH ) ; if ( fsPathString != null ) { return new Path ( fsPathString ) ; } return null ; } private static Path takeTempPath ( DirectDataSourceProfile profile , Map < String , String > attributes , Configuration conf , Path fsPath ) { assert attributes != null ; assert conf != null ; assert fsPath != null ; String tempPathString = attributes . remove ( KEY_TEMP ) ; Path tempPath ; if ( tempPathString != null ) { tempPath = new Path ( tempPathString ) ; } else { tempPath = new Path ( fsPath , DEFAULT_TEMP_SUFFIX ) ; } return tempPath ; } private static long takeMinFragment ( DirectDataSourceProfile profile , Map < String , String > attributes , Configuration conf ) throws IOException { assert profile != null ; assert attributes != null ; assert conf != null ; String string = attributes . remove ( KEY_MIN_FRAGMENT ) ; if ( string == null ) { return DEFAULT_MIN_FRAGMENT ; } try { long value = Long . parseLong ( string ) ; if ( value == ) { throw new IOException ( MessageFormat . format ( "" , fqn ( profile , KEY_MIN_FRAGMENT ) ) ) ; } return value ; } catch ( NumberFormatException e ) { throw new IOException ( MessageFormat . format ( "" , fqn ( profile , KEY_MIN_FRAGMENT ) , string ) ) ; } } private static long takePrefFragment ( DirectDataSourceProfile profile , Map < String , String > attributes , Configuration conf ) throws IOException { assert profile != null ; assert attributes != null ; assert conf != null ; String string = attributes . remove ( KEY_PREF_FRAGMENT ) ; if ( string == null ) { return DEFAULT_PREF_FRAGMENT ; } try { long value = Long . parseLong ( string ) ; if ( value <= ) { throw new IOException ( MessageFormat . format ( "" , fqn ( profile , KEY_PREF_FRAGMENT ) , string ) ) ; } return value ; } catch ( NumberFormatException e ) { throw new IOException ( MessageFormat . format ( "" , fqn ( profile , KEY_PREF_FRAGMENT ) , string ) ) ; } } private static boolean takeBoolean ( DirectDataSourceProfile profile , Map < String , String > attributes , String key , boolean defaultValue ) throws IOException { assert profile != null ; assert attributes != null ; assert key != null ; String string = attributes . remove ( key ) ; if ( string == null ) { return defaultValue ; } if ( string . equalsIgnoreCase ( "" ) ) { return true ; } else if ( string . equalsIgnoreCase ( "" ) ) { return false ; } else { throw new IOException ( MessageFormat . format ( "" , fqn ( profile , key ) , string ) ) ; } } private static long takeKeepAliveInterval ( DirectDataSourceProfile profile , Map < String , String > attributes , Configuration conf ) throws IOException { assert profile != null ; assert attributes != null ; assert conf != null ; String string = attributes . remove ( KEY_KEEPALIVE_INTERVAL ) ; if ( string == null ) { return DEFAULT_KEEPALIVE_INTERVAL ; } try { long value = Long . parseLong ( string ) ; if ( value < ) { throw new IOException ( MessageFormat . format ( "" , fqn ( profile , KEY_KEEPALIVE_INTERVAL ) ) ) ; } return value ; } catch ( NumberFormatException e ) { throw new IOException ( MessageFormat . format ( "" , fqn ( profile , KEY_KEEPALIVE_INTERVAL ) , string ) ) ; } } } package com . asakusafw . runtime . directio . hadoop ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . fs . BlockLocation ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectInputFragment ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . directio . FragmentableDataFormat ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . OutputTransactionContext ; import com . asakusafw . runtime . directio . ResourceInfo ; import com . asakusafw . runtime . directio . ResourcePattern ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class HadoopDataSourceCore implements DirectDataSource { static final Log LOG = LogFactory . getLog ( HadoopDataSourceCore . class ) ; private static final String ATTEMPT_AREA = "" ; private static final String STAGING_AREA = "" ; private final HadoopDataSourceProfile profile ; public HadoopDataSourceCore ( HadoopDataSourceProfile profile ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; } @ Override public < T > List < DirectInputFragment > findInputFragments ( Class < ? extends T > dataType , DataFormat < T > format , String basePath , ResourcePattern resourcePattern ) throws IOException , InterruptedException { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePattern ) ) ; } FilePattern pattern = validate ( resourcePattern ) ; FragmentableDataFormat < T > sformat = validateFragmentable ( format ) ; HadoopDataSourceProfile p = profile ; FileSystem fs = p . getFileSystem ( ) ; Path root = p . getFileSystemPath ( ) ; Path base = append ( root , basePath ) ; List < FileStatus > stats = HadoopDataSourceUtil . search ( fs , base , pattern ) ; stats = filesOnly ( stats ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePattern , stats . size ( ) ) ) ; } if ( LOG . isTraceEnabled ( ) ) { for ( FileStatus stat : stats ) { LOG . trace ( MessageFormat . format ( "" , stat . getPath ( ) , stat . getLen ( ) ) ) ; } } long minSize = p . getMinimumFragmentSize ( sformat ) ; long prefSize = p . getPreferredFragmentSize ( sformat ) ; boolean combineBlocks = p . isCombineBlocks ( ) ; boolean splitBlocks = p . isSplitBlocks ( ) ; Path temporary = p . getTemporaryFileSystemPath ( ) ; FragmentComputer optimizer = new FragmentComputer ( minSize , prefSize , combineBlocks , splitBlocks ) ; List < DirectInputFragment > results = new ArrayList < DirectInputFragment > ( ) ; for ( FileStatus stat : stats ) { if ( isIn ( stat , temporary ) ) { continue ; } String path = stat . getPath ( ) . toString ( ) ; long fileSize = stat . getLen ( ) ; List < BlockInfo > blocks = toBlocks ( stat ) ; if ( LOG . isTraceEnabled ( ) ) { for ( BlockInfo block : blocks ) { LOG . trace ( MessageFormat . format ( "" , path , block . start , block . end , block . hosts == null ? null : Arrays . toString ( block . hosts ) ) ) ; } } List < DirectInputFragment > fragments = optimizer . computeFragments ( path , fileSize , blocks ) ; if ( LOG . isTraceEnabled ( ) ) { for ( DirectInputFragment fragment : fragments ) { LOG . trace ( MessageFormat . format ( "" , fragment . getPath ( ) , fragment . getOffset ( ) , fragment . getSize ( ) , fragment . getOwnerNodeNames ( ) ) ) ; } } results . addAll ( fragments ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePattern , results . size ( ) ) ) ; } return results ; } private boolean isIn ( FileStatus stat , Path temporary ) { assert stat != null ; assert temporary != null ; Path path = stat . getPath ( ) ; if ( path . equals ( temporary ) || HadoopDataSourceUtil . contains ( temporary , path ) ) { return true ; } return false ; } private List < BlockInfo > toBlocks ( FileStatus stat ) throws IOException { BlockLocation [ ] locations = profile . getFileSystem ( ) . getFileBlockLocations ( stat , , stat . getLen ( ) ) ; List < BlockInfo > results = new ArrayList < BlockInfo > ( ) ; for ( BlockLocation location : locations ) { long length = location . getLength ( ) ; long start = location . getOffset ( ) ; results . add ( new BlockInfo ( start , start + length , location . getHosts ( ) ) ) ; } return results ; } private List < FileStatus > filesOnly ( List < FileStatus > stats ) { List < FileStatus > results = new ArrayList < FileStatus > ( ) ; for ( FileStatus stat : stats ) { if ( stat . isDir ( ) == false ) { results . add ( stat ) ; } } return results ; } @ Override public < T > ModelInput < T > openInput ( Class < ? extends T > dataType , DataFormat < T > format , DirectInputFragment fragment , Counter counter ) throws IOException , InterruptedException { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , fragment . getPath ( ) , fragment . getOffset ( ) , fragment . getSize ( ) ) ) ; } HadoopFileFormat < T > fileFormat = convertFormat ( format ) ; ModelInput < T > input = fileFormat . createInput ( dataType , profile . getFileSystem ( ) , new Path ( fragment . getPath ( ) ) , fragment . getOffset ( ) , fragment . getSize ( ) , counter ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , fragment . getPath ( ) , fragment . getOffset ( ) , fragment . getSize ( ) ) ) ; } return input ; } @ Override public < T > ModelOutput < T > openOutput ( OutputAttemptContext context , Class < ? extends T > dataType , DataFormat < T > format , String basePath , String resourcePath , Counter counter ) throws IOException , InterruptedException { FileSystem fs ; Path attempt ; if ( isLocalAttemptOutput ( ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePath , true ) ) ; } fs = profile . getLocalFileSystem ( ) ; attempt = getLocalAttemptOutput ( context ) ; } else { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePath , false ) ) ; } fs = profile . getFileSystem ( ) ; attempt = getAttemptOutput ( context ) ; } Path file = append ( append ( attempt , basePath ) , resourcePath ) ; HadoopFileFormat < T > fileFormat = convertFormat ( format ) ; ModelOutput < T > output = fileFormat . createOutput ( dataType , fs , file , counter ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePath , file ) ) ; } return output ; } boolean isLocalAttemptOutput ( ) { return profile . isOutputStreaming ( ) == false && HadoopDataSourceUtil . isLocalAttemptOutputDefined ( profile . getLocalFileSystem ( ) ) ; } private FilePattern validate ( ResourcePattern pattern ) throws IOException { assert pattern != null ; if ( ( pattern instanceof FilePattern ) == false ) { throw new IOException ( MessageFormat . format ( "" , profile . getContextPath ( ) , FilePattern . class . getName ( ) , pattern . getClass ( ) . getName ( ) ) ) ; } return ( FilePattern ) pattern ; } private < T > FragmentableDataFormat < T > validateFragmentable ( DataFormat < T > format ) throws IOException { assert format != null ; if ( ( format instanceof FragmentableDataFormat < ? > ) == false ) { throw new IOException ( MessageFormat . format ( "" , profile . getContextPath ( ) , FragmentableDataFormat . class . getName ( ) , format . getClass ( ) . getName ( ) ) ) ; } return ( FragmentableDataFormat < T > ) format ; } private < T > HadoopFileFormat < T > convertFormat ( DataFormat < T > format ) throws IOException { assert format != null ; if ( format instanceof HadoopFileFormat < ? > ) { return ( HadoopFileFormat < T > ) format ; } else { return new HadoopFileFormatAdapter < T > ( validateStream ( format ) , profile . getFileSystem ( ) . getConf ( ) ) ; } } private < T > BinaryStreamFormat < T > validateStream ( DataFormat < T > format ) throws IOException { assert format != null ; if ( ( format instanceof BinaryStreamFormat < ? > ) == false ) { throw new IOException ( MessageFormat . format ( "" , profile . getContextPath ( ) , BinaryStreamFormat . class . getName ( ) , format . getClass ( ) . getName ( ) ) ) ; } return ( BinaryStreamFormat < T > ) format ; } @ Override public List < ResourceInfo > list ( String basePath , ResourcePattern resourcePattern , Counter counter ) throws IOException , InterruptedException { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePattern ) ) ; } FilePattern pattern = validate ( resourcePattern ) ; HadoopDataSourceProfile p = profile ; FileSystem fs = p . getFileSystem ( ) ; Path root = p . getFileSystemPath ( ) ; Path base = append ( root , basePath ) ; Path temporary = p . getTemporaryFileSystemPath ( ) ; List < FileStatus > stats = HadoopDataSourceUtil . search ( fs , base , pattern ) ; stats = normalize ( stats , root , temporary ) ; List < ResourceInfo > results = new ArrayList < ResourceInfo > ( ) ; for ( FileStatus stat : stats ) { counter . add ( ) ; ResourceInfo resource = new ResourceInfo ( profile . getId ( ) , stat . getPath ( ) . toString ( ) , stat . isDir ( ) ) ; results . add ( resource ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePattern , results . size ( ) ) ) ; } return results ; } @ Override public boolean delete ( String basePath , ResourcePattern resourcePattern , boolean recursive , Counter counter ) throws IOException , InterruptedException { assert basePath . startsWith ( "" ) == false ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePattern , recursive ) ) ; } FilePattern pattern = validate ( resourcePattern ) ; HadoopDataSourceProfile p = profile ; FileSystem fs = p . getFileSystem ( ) ; Path root = p . getFileSystemPath ( ) ; Path base = append ( root , basePath ) ; List < FileStatus > stats = HadoopDataSourceUtil . search ( fs , base , pattern ) ; Path temporary = p . getTemporaryFileSystemPath ( ) ; stats = normalize ( stats , root , temporary ) ; if ( recursive ) { stats = HadoopDataSourceUtil . onlyMinimalCovered ( stats ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePattern , stats . size ( ) ) ) ; } boolean succeed = true ; for ( FileStatus stat : stats ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( MessageFormat . format ( "" , profile . getId ( ) , stat . getPath ( ) , recursive ) ) ; } if ( recursive == false && stat . isDir ( ) ) { LOG . info ( MessageFormat . format ( "" , profile . getId ( ) , stat . getPath ( ) ) ) ; } else { counter . add ( ) ; succeed &= fs . delete ( stat . getPath ( ) , recursive ) ; } } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , basePath , resourcePattern , stats . size ( ) ) ) ; } return succeed ; } private List < FileStatus > normalize ( List < FileStatus > stats , Path root , Path temporary ) { assert stats != null ; assert root != null ; assert temporary != null ; List < FileStatus > results = new ArrayList < FileStatus > ( ) ; for ( FileStatus stat : stats ) { if ( root . equals ( stat . getPath ( ) ) == false && isIn ( stat , temporary ) == false ) { results . add ( stat ) ; } } return results ; } private Path append ( Path parent , String child ) { assert parent != null ; assert child != null ; return child . isEmpty ( ) ? parent : new Path ( parent , child ) ; } @ Override public void setupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { if ( profile . isOutputStreaming ( ) == false && isLocalAttemptOutput ( ) == false ) { LOG . warn ( MessageFormat . format ( "" , profile . getId ( ) , HadoopDataSourceUtil . KEY_LOCAL_TEMPDIR ) ) ; } if ( isLocalAttemptOutput ( ) ) { FileSystem fs = profile . getLocalFileSystem ( ) ; Path attempt = getLocalAttemptOutput ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , attempt ) ) ; } fs . mkdirs ( attempt ) ; } else { FileSystem fs = profile . getFileSystem ( ) ; Path attempt = getAttemptOutput ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , attempt ) ) ; } fs . mkdirs ( attempt ) ; } } @ Override public void commitAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { Path target ; if ( profile . isOutputStaging ( ) ) { target = getStagingOutput ( context . getTransactionContext ( ) ) ; } else { target = profile . getFileSystemPath ( ) ; } if ( isLocalAttemptOutput ( ) ) { Path attempt = getLocalAttemptOutput ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , attempt , profile . isOutputStaging ( ) ) ) ; } HadoopDataSourceUtil . moveFromLocal ( context . getCounter ( ) , profile . getLocalFileSystem ( ) , profile . getFileSystem ( ) , attempt , target ) ; } else { Path attempt = getAttemptOutput ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , attempt , profile . isOutputStaging ( ) ) ) ; } HadoopDataSourceUtil . move ( context . getCounter ( ) , profile . getFileSystem ( ) , attempt , target ) ; } } @ Override public void cleanupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { if ( isLocalAttemptOutput ( ) ) { Path attempt = getLocalAttemptOutput ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , attempt ) ) ; } FileSystem fs = profile . getLocalFileSystem ( ) ; fs . delete ( attempt , true ) ; } else { Path attempt = getAttemptOutput ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , attempt ) ) ; } FileSystem fs = profile . getFileSystem ( ) ; fs . delete ( attempt , true ) ; } } @ Override public void setupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { if ( profile . isOutputStaging ( ) ) { FileSystem fs = profile . getFileSystem ( ) ; Path staging = getStagingOutput ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , staging ) ) ; } fs . mkdirs ( staging ) ; } } @ Override public void commitTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { if ( profile . isOutputStaging ( ) ) { FileSystem fs = profile . getFileSystem ( ) ; Path staging = getStagingOutput ( context ) ; Path target = profile . getFileSystemPath ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , staging ) ) ; } HadoopDataSourceUtil . move ( context . getCounter ( ) , fs , staging , target ) ; } } @ Override public void cleanupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { FileSystem fs = profile . getFileSystem ( ) ; Path path = getTemporaryOutput ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , path ) ) ; } try { if ( fs . delete ( path , true ) == false ) { LOG . warn ( MessageFormat . format ( "" , profile . getId ( ) , path ) ) ; } } catch ( FileNotFoundException e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , path ) ) ; } } } private Path getTemporaryOutput ( OutputTransactionContext context ) { assert context != null ; Path tempRoot = profile . getTemporaryFileSystemPath ( ) ; String suffix = String . format ( "" , context . getTransactionId ( ) , context . getOutputId ( ) ) ; return append ( tempRoot , suffix ) ; } Path getStagingOutput ( OutputTransactionContext context ) { assert context != null ; Path tempPath = getTemporaryOutput ( context ) ; String suffix = STAGING_AREA ; return append ( tempPath , suffix ) ; } Path getAttemptOutput ( OutputAttemptContext context ) { assert context != null ; Path tempPath = getTemporaryOutput ( context . getTransactionContext ( ) ) ; String suffix = String . format ( "" , ATTEMPT_AREA , context . getAttemptId ( ) ) ; return append ( tempPath , suffix ) ; } Path getLocalAttemptOutput ( OutputAttemptContext context ) throws IOException { assert context != null ; Path tempPath = HadoopDataSourceUtil . getLocalTemporaryDirectory ( profile . getLocalFileSystem ( ) ) ; String suffix = String . format ( "" , context . getAttemptId ( ) , context . getOutputId ( ) ) ; return append ( tempPath , suffix ) ; } } package com . asakusafw . runtime . directio . hadoop ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . URI ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . ListIterator ; import java . util . Map ; import java . util . NavigableMap ; import java . util . Set ; import java . util . TreeMap ; import java . util . TreeSet ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . LocalFileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . util . Progressable ; import com . asakusafw . runtime . directio . AbstractDirectDataSource ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceProfile ; import com . asakusafw . runtime . directio . DirectDataSourceProvider ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . directio . FilePattern . PatternElement ; import com . asakusafw . runtime . directio . FilePattern . PatternElementKind ; import com . asakusafw . runtime . directio . FilePattern . Segment ; import com . asakusafw . runtime . directio . FilePattern . Selection ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . OutputTransactionContext ; import com . asakusafw . runtime . stage . StageConstants ; public final class HadoopDataSourceUtil { static final Log LOG = LogFactory . getLog ( HadoopDataSourceUtil . class ) ; public static final String PREFIX = "" ; public static final String KEY_PATH = "" ; private static final Pattern PREFIX_PATTERN = Pattern . compile ( '' + Pattern . quote ( PREFIX ) ) ; public static final String KEY_SYSTEM_DIR = "" ; public static final String KEY_LOCAL_TEMPDIR = "" ; static final String DEFAULT_SYSTEM_DIR = "" ; static final String TRANSACTION_INFO_DIR = "" ; public static final Charset COMMENT_CHARSET = Charset . forName ( "" ) ; public static List < DirectDataSourceProfile > loadProfiles ( Configuration conf ) { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } Map < String , String > pathToKey = new HashMap < String , String > ( ) ; Map < String , String > map = getConfigMap ( conf ) ; Set < String > keys = getChildKeys ( map , "" ) ; try { List < DirectDataSourceProfile > results = new ArrayList < DirectDataSourceProfile > ( ) ; for ( String key : keys ) { String className = map . get ( key ) ; Map < String , String > config = createPrefixMap ( map , key + "" ) ; String path = config . remove ( KEY_PATH ) ; if ( path == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , PREFIX + key + '' + KEY_PATH ) ) ; } path = normalizePath ( path ) ; if ( pathToKey . containsKey ( path ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , path . isEmpty ( ) ? "" : path , PREFIX + key + '' + KEY_PATH , PREFIX + pathToKey . get ( key ) + '' + KEY_PATH ) ) ; } else { pathToKey . put ( path , key ) ; } Class < ? extends AbstractDirectDataSource > aClass = conf . getClassByName ( className ) . asSubclass ( AbstractDirectDataSource . class ) ; results . add ( new DirectDataSourceProfile ( key , aClass , path , config ) ) ; } return results ; } catch ( ClassNotFoundException e ) { throw new IllegalStateException ( e ) ; } } private static String normalizePath ( String path ) { assert path != null ; StringBuilder buf = new StringBuilder ( ) ; int offset = ; for ( int i = , n = path . length ( ) ; i < n ; i ++ ) { if ( path . charAt ( i ) == '' ) { offset = i + ; } else { break ; } } boolean sawSeparator = false ; for ( int i = offset , n = path . length ( ) ; i < n ; i ++ ) { char c = path . charAt ( i ) ; if ( c == '' ) { sawSeparator = true ; } else { if ( sawSeparator ) { buf . append ( '' ) ; sawSeparator = false ; } buf . append ( c ) ; } } return buf . toString ( ) ; } private static Map < String , String > getConfigMap ( Configuration conf ) { assert conf != null ; Map < String , String > map = conf . getValByRegex ( PREFIX_PATTERN . pattern ( ) ) ; NavigableMap < String , String > prefixMap = createPrefixMap ( map , PREFIX ) ; return prefixMap ; } private static NavigableMap < String , String > createPrefixMap ( Map < ? , ? > properties , String prefix ) { assert properties != null ; assert prefix != null ; NavigableMap < String , String > results = new TreeMap < String , String > ( ) ; for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { if ( ( entry . getKey ( ) instanceof String ) == false || ( entry . getValue ( ) instanceof String ) == false ) { continue ; } String name = ( String ) entry . getKey ( ) ; if ( name . startsWith ( prefix ) == false ) { continue ; } results . put ( name . substring ( prefix . length ( ) ) , ( String ) entry . getValue ( ) ) ; } return results ; } private static Set < String > getChildKeys ( Map < String , String > properties , String delimitier ) { assert properties != null ; assert delimitier != null ; Set < String > results = new TreeSet < String > ( ) ; for ( Map . Entry < String , String > entry : properties . entrySet ( ) ) { String name = entry . getKey ( ) ; int index = name . indexOf ( delimitier ) ; if ( index < ) { results . add ( name ) ; } else { results . add ( name . substring ( , index ) ) ; } } return results ; } public static DirectDataSourceRepository loadRepository ( Configuration conf ) { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } List < DirectDataSourceProfile > profiles = loadProfiles ( conf ) ; return createRepository ( conf , profiles ) ; } static DirectDataSourceRepository createRepository ( Configuration conf , List < DirectDataSourceProfile > profiles ) { assert conf != null ; assert profiles != null ; List < DirectDataSourceProvider > providers = new ArrayList < DirectDataSourceProvider > ( ) ; for ( DirectDataSourceProfile profile : profiles ) { providers . add ( createProvider ( conf , profile ) ) ; } return new DirectDataSourceRepository ( providers ) ; } private static DirectDataSourceProvider createProvider ( Configuration conf , DirectDataSourceProfile profile ) { assert conf != null ; assert profile != null ; return new HadoopDataSourceProvider ( conf , profile ) ; } public static boolean isLocalAttemptOutputDefined ( LocalFileSystem localFileSystem ) { try { return getLocalTemporaryDirectory ( localFileSystem ) != null ; } catch ( IOException e ) { return false ; } } public static Path getLocalTemporaryDirectory ( LocalFileSystem localFileSystem ) throws IOException { if ( localFileSystem == null ) { throw new IllegalArgumentException ( "" ) ; } Configuration conf = localFileSystem . getConf ( ) ; if ( conf == null ) { return null ; } String path = conf . get ( KEY_LOCAL_TEMPDIR ) ; if ( path == null ) { return null ; } LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path result = fs . makeQualified ( new Path ( path ) ) ; return result ; } public static OutputTransactionContext createContext ( JobContext context , String datasourceId ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( datasourceId == null ) { throw new IllegalArgumentException ( "" ) ; } String transactionId = getTransactionId ( context , datasourceId ) ; return new OutputTransactionContext ( transactionId , datasourceId , createCounter ( context ) ) ; } public static OutputTransactionContext createContext ( String executionId , String datasourceId ) { if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( datasourceId == null ) { throw new IllegalArgumentException ( "" ) ; } String transactionId = getTransactionId ( executionId ) ; return new OutputTransactionContext ( transactionId , datasourceId , new Counter ( ) ) ; } public static OutputAttemptContext createContext ( TaskAttemptContext context , String datasourceId ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( datasourceId == null ) { throw new IllegalArgumentException ( "" ) ; } String transactionId = getTransactionId ( context , datasourceId ) ; String attemptId = getAttemptId ( context , datasourceId ) ; return new OutputAttemptContext ( transactionId , attemptId , datasourceId , createCounter ( context ) ) ; } private static String getTransactionId ( JobContext jobContext , String datasourceId ) { assert jobContext != null ; assert datasourceId != null ; String executionId = jobContext . getConfiguration ( ) . get ( StageConstants . PROP_EXECUTION_ID ) ; if ( executionId == null ) { executionId = jobContext . getJobID ( ) . toString ( ) ; } return getTransactionId ( executionId ) ; } private static String getTransactionId ( String executionId ) { return executionId ; } private static String getAttemptId ( TaskAttemptContext taskContext , String datasourceId ) { assert taskContext != null ; assert datasourceId != null ; return taskContext . getTaskAttemptID ( ) . toString ( ) ; } private static Counter createCounter ( JobContext context ) { assert context != null ; if ( context instanceof Progressable ) { return new ProgressableCounter ( ( Progressable ) context ) ; } else if ( context instanceof org . apache . hadoop . mapred . JobContext ) { return new ProgressableCounter ( ( ( org . apache . hadoop . mapred . JobContext ) context ) . getProgressible ( ) ) ; } else { return new Counter ( ) ; } } public static String getTransactionInfoExecutionId ( Path transactionInfoPath ) { if ( transactionInfoPath == null ) { throw new IllegalArgumentException ( "" ) ; } return getMarkPath ( transactionInfoPath , Pattern . compile ( "" ) ) ; } private static String getMarkPath ( Path path , Pattern pattern ) { assert path != null ; assert pattern != null ; String name = path . getName ( ) ; Matcher matcher = pattern . matcher ( name ) ; if ( matcher . matches ( ) == false ) { return null ; } return matcher . group ( ) ; } public static Path getTransactionInfoPath ( Configuration conf , String executionId ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } return new Path ( getTransactionInfoDir ( conf ) , String . format ( "" , executionId ) ) ; } public static Path getCommitMarkPath ( Configuration conf , String executionId ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } return new Path ( getTransactionInfoDir ( conf ) , String . format ( "" , executionId ) ) ; } public static Collection < FileStatus > findAllTransactionInfoFiles ( Configuration conf ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } Path dir = getTransactionInfoDir ( conf ) ; FileSystem fs = dir . getFileSystem ( conf ) ; FileStatus [ ] statusArray = fs . listStatus ( dir ) ; if ( statusArray == null || statusArray . length == ) { return Collections . emptyList ( ) ; } Collection < FileStatus > results = new ArrayList < FileStatus > ( ) ; for ( FileStatus stat : statusArray ) { if ( getTransactionInfoExecutionId ( stat . getPath ( ) ) != null ) { results . add ( stat ) ; } } return results ; } private static Path getTransactionInfoDir ( Configuration conf ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } String working = conf . get ( KEY_SYSTEM_DIR , DEFAULT_SYSTEM_DIR ) ; Path path = new Path ( working , TRANSACTION_INFO_DIR ) ; return path . makeQualified ( path . getFileSystem ( conf ) ) ; } public static List < FileStatus > search ( FileSystem fs , Path base , FilePattern pattern ) throws IOException { if ( fs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( base == null ) { throw new IllegalArgumentException ( "" ) ; } if ( pattern == null ) { throw new IllegalArgumentException ( "" ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , base , pattern ) ) ; } List < FileStatus > current = new ArrayList < FileStatus > ( ) ; try { FileStatus stat = fs . getFileStatus ( base ) ; current . add ( stat ) ; } catch ( FileNotFoundException e ) { return Collections . emptyList ( ) ; } int steps = ; LinkedList < Segment > segments = new LinkedList < Segment > ( pattern . getSegments ( ) ) ; while ( segments . isEmpty ( ) == false ) { if ( segments . getFirst ( ) . isTraverse ( ) ) { segments . removeFirst ( ) ; current = recursiveStep ( fs , current ) ; } else { List < Path > step = consumeStep ( segments ) ; current = globStep ( fs , current , step ) ; } steps ++ ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , base , pattern , current . size ( ) , steps ) ) ; } return current ; } private static List < Path > consumeStep ( LinkedList < Segment > segments ) { assert segments != null ; assert segments . isEmpty ( ) == false ; assert segments . getFirst ( ) . isTraverse ( ) == false ; List < Path > results = new ArrayList < Path > ( ) ; Segment current = segments . removeFirst ( ) ; for ( String segment : resolve ( current ) ) { results . add ( new Path ( segment ) ) ; } while ( isGlobRequired ( current ) && segments . isEmpty ( ) == false && segments . getFirst ( ) . isTraverse ( ) == false ) { current = segments . removeFirst ( ) ; Set < String > suffixCandidates = resolve ( current ) ; if ( suffixCandidates . size ( ) == ) { String suffix = suffixCandidates . iterator ( ) . next ( ) ; for ( ListIterator < Path > i = results . listIterator ( ) ; i . hasNext ( ) ; ) { Path parent = i . next ( ) ; i . set ( new Path ( parent , suffix ) ) ; } } else { List < Path > nextResults = new ArrayList < Path > ( ) ; for ( Path parent : results ) { for ( String suffix : suffixCandidates ) { nextResults . add ( new Path ( parent , suffix ) ) ; } } results = nextResults ; } } Set < Path > saw = new HashSet < Path > ( ) ; for ( Iterator < Path > iter = results . iterator ( ) ; iter . hasNext ( ) ; ) { Path path = iter . next ( ) ; if ( saw . contains ( path ) ) { iter . remove ( ) ; } else { saw . add ( path ) ; } } return results ; } private static boolean isGlobRequired ( Segment segment ) { assert segment != null ; assert segment . isTraverse ( ) == false ; for ( PatternElement element : segment . getElements ( ) ) { if ( element . getKind ( ) == PatternElementKind . WILDCARD ) { return false ; } } return true ; } private static Set < String > resolve ( Segment segment ) { assert segment != null ; assert segment . isTraverse ( ) == false ; List < Set < String > > candidates = new ArrayList < Set < String > > ( ) ; for ( PatternElement element : segment . getElements ( ) ) { switch ( element . getKind ( ) ) { case TOKEN : candidates . add ( Collections . singleton ( element . getToken ( ) ) ) ; break ; case WILDCARD : candidates . add ( Collections . singleton ( "" ) ) ; break ; case SELECTION : candidates . add ( new TreeSet < String > ( ( ( Selection ) element ) . getContents ( ) ) ) ; break ; default : throw new AssertionError ( ) ; } } List < String > results = stringCrossJoin ( candidates ) ; return new TreeSet < String > ( results ) ; } private static List < String > stringCrossJoin ( List < Set < String > > candidates ) { assert candidates != null ; assert candidates . isEmpty ( ) == false ; List < String > results = new ArrayList < String > ( ) ; Iterator < Set < String > > iter = candidates . iterator ( ) ; assert iter . hasNext ( ) ; results . addAll ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { Set < String > next = iter . next ( ) ; if ( next . size ( ) == ) { String suffix = next . iterator ( ) . next ( ) ; for ( ListIterator < String > i = results . listIterator ( ) ; i . hasNext ( ) ; ) { String vaule = i . next ( ) ; i . set ( vaule + suffix ) ; } } else { List < String > nextResults = new ArrayList < String > ( ) ; for ( String value : results ) { for ( String suffix : next ) { nextResults . add ( value + suffix ) ; } } results = nextResults ; } } return results ; } private static List < FileStatus > recursiveStep ( FileSystem fs , List < FileStatus > current ) throws IOException { assert fs != null ; assert current != null ; Set < Path > paths = new HashSet < Path > ( ) ; List < FileStatus > results = new ArrayList < FileStatus > ( ) ; LinkedList < FileStatus > work = new LinkedList < FileStatus > ( current ) ; while ( work . isEmpty ( ) == false ) { FileStatus next = work . removeFirst ( ) ; Path path = next . getPath ( ) ; if ( paths . contains ( path ) == false ) { paths . add ( path ) ; results . add ( next ) ; if ( next . isDir ( ) ) { FileStatus [ ] children = fs . listStatus ( path ) ; Collections . addAll ( work , children ) ; } } } return results ; } private static List < FileStatus > globStep ( FileSystem fs , List < FileStatus > current , List < Path > expressions ) throws IOException { assert fs != null ; assert current != null ; assert expressions != null ; Set < Path > paths = new HashSet < Path > ( ) ; List < FileStatus > results = new ArrayList < FileStatus > ( ) ; for ( FileStatus status : current ) { if ( status . isDir ( ) == false ) { continue ; } for ( Path expression : expressions ) { Path path = new Path ( status . getPath ( ) , expression ) ; FileStatus [ ] expanded = fs . globStatus ( path ) ; if ( expanded != null ) { for ( FileStatus s : expanded ) { Path p = s . getPath ( ) ; if ( paths . contains ( p ) == false ) { paths . add ( p ) ; results . add ( s ) ; } } } } } return results ; } public static List < FileStatus > onlyMinimalCovered ( List < FileStatus > statList ) { assert statList != null ; FileStatus [ ] stats = statList . toArray ( new FileStatus [ statList . size ( ) ] ) ; for ( int i = ; i < stats . length ; i ++ ) { if ( stats [ i ] == null || stats [ i ] . isDir ( ) == false ) { continue ; } for ( int j = ; j < stats . length ; j ++ ) { if ( i == j || stats [ j ] == null ) { continue ; } if ( contains ( stats [ i ] , stats [ j ] ) ) { stats [ j ] = null ; } } } List < FileStatus > results = new ArrayList < FileStatus > ( ) ; for ( int i = ; i < stats . length ; i ++ ) { FileStatus stat = stats [ i ] ; if ( stat != null ) { results . add ( stat ) ; } } return results ; } private static boolean contains ( FileStatus dir , FileStatus target ) { assert dir != null ; assert target != null ; assert dir . isDir ( ) ; Path parent = dir . getPath ( ) ; Path child = target . getPath ( ) ; return contains ( parent , child ) ; } public static boolean contains ( Path parent , Path child ) { if ( parent == null ) { throw new IllegalArgumentException ( "" ) ; } if ( child == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parent . depth ( ) >= child . depth ( ) ) { return false ; } URI parentUri = parent . toUri ( ) ; URI childUri = child . toUri ( ) ; URI relative = parentUri . relativize ( childUri ) ; if ( relative . equals ( childUri ) == false ) { return true ; } return false ; } public static void move ( Counter counter , FileSystem fs , Path from , Path to ) throws IOException { move ( counter , fs , from , fs , to , false ) ; } public static void moveFromLocal ( Counter counter , LocalFileSystem localFs , FileSystem fs , Path from , Path to ) throws IOException { move ( counter , localFs , from , fs , to , true ) ; } private static void move ( Counter counter , FileSystem fromFs , Path from , FileSystem toFs , Path to , boolean fromLocal ) throws IOException { if ( counter == null ) { throw new IllegalArgumentException ( "" ) ; } if ( fromFs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( from == null ) { throw new IllegalArgumentException ( "" ) ; } if ( toFs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( to == null ) { throw new IllegalArgumentException ( "" ) ; } if ( fromLocal && isLocalPath ( from ) == false ) { throw new IllegalArgumentException ( "" ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , from , to ) ) ; } Path source = fromFs . makeQualified ( from ) ; Path target = toFs . makeQualified ( to ) ; List < Path > list = createFileListRelative ( counter , fromFs , source ) ; if ( list . isEmpty ( ) ) { return ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , from , to , list . size ( ) ) ) ; } Set < Path > directoryCreated = new HashSet < Path > ( ) ; for ( Path path : list ) { Path sourceFile = new Path ( source , path ) ; Path targetFile = new Path ( target , path ) ; if ( LOG . isTraceEnabled ( ) ) { FileStatus stat = fromFs . getFileStatus ( sourceFile ) ; LOG . trace ( MessageFormat . format ( "" , sourceFile , targetFile , stat . getLen ( ) ) ) ; } try { FileStatus stat = toFs . getFileStatus ( targetFile ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , targetFile ) ) ; } if ( stat . isDir ( ) ) { toFs . delete ( targetFile , true ) ; } else { toFs . delete ( targetFile , false ) ; } } catch ( FileNotFoundException e ) { Path targetParent = targetFile . getParent ( ) ; if ( directoryCreated . contains ( targetParent ) == false ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , targetParent ) ) ; } toFs . mkdirs ( targetParent ) ; directoryCreated . add ( targetParent ) ; } } counter . add ( ) ; if ( fromLocal ) { toFs . moveFromLocalFile ( sourceFile , targetFile ) ; } else { boolean succeed = toFs . rename ( sourceFile , targetFile ) ; if ( succeed == false ) { throw new IOException ( MessageFormat . format ( "" , sourceFile , targetFile ) ) ; } } counter . add ( ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , from , to , list . size ( ) ) ) ; } } private static boolean isLocalPath ( Path path ) { assert path != null ; String scheme = path . toUri ( ) . getScheme ( ) ; return scheme != null && scheme . equals ( "" ) ; } @ SuppressWarnings ( "" ) private static List < Path > createFileListRelative ( Counter counter , FileSystem fs , Path source ) throws IOException { assert counter != null ; assert fs != null ; assert source != null ; assert source . isAbsolute ( ) ; URI baseUri = source . toUri ( ) ; FileStatus root ; try { root = fs . getFileStatus ( source ) ; } catch ( FileNotFoundException e ) { LOG . warn ( MessageFormat . format ( "" , baseUri ) ) ; return Collections . emptyList ( ) ; } counter . add ( ) ; List < FileStatus > all = recursiveStep ( fs , Collections . singletonList ( root ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , baseUri , all . size ( ) ) ) ; } List < Path > results = new ArrayList < Path > ( ) ; for ( FileStatus stat : all ) { if ( stat . isDir ( ) ) { continue ; } Path path = stat . getPath ( ) ; URI uri = path . toUri ( ) ; URI relative = baseUri . relativize ( uri ) ; if ( relative . equals ( uri ) == false ) { results . add ( new Path ( relative ) ) ; } else { throw new IOException ( MessageFormat . format ( "" , baseUri , uri ) ) ; } counter . add ( ) ; } Collections . sort ( results ) ; return results ; } private HadoopDataSourceUtil ( ) { return ; } private static class HadoopDataSourceProvider implements DirectDataSourceProvider { private final Configuration configuration ; private final DirectDataSourceProfile profile ; public HadoopDataSourceProvider ( Configuration configuration , DirectDataSourceProfile profile ) { assert configuration != null ; assert profile != null ; this . configuration = configuration ; this . profile = profile ; } @ Override public String getId ( ) { return profile . getId ( ) ; } @ Override public String getPath ( ) { return profile . getPath ( ) ; } @ Override public DirectDataSource newInstance ( ) throws IOException , InterruptedException { try { AbstractDirectDataSource instance = profile . getTargetClass ( ) . getConstructor ( ) . newInstance ( ) ; if ( instance instanceof Configurable ) { ( ( Configurable ) instance ) . setConf ( configuration ) ; } instance . configure ( profile ) ; return instance ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , PREFIX + profile . getId ( ) , profile . getTargetClass ( ) . getName ( ) ) , e ) ; } } } } package com . asakusafw . runtime . directio . hadoop ; package com . asakusafw . runtime . directio . hadoop ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . FragmentableDataFormat ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public abstract class HadoopFileFormat < T > extends Configured implements FragmentableDataFormat < T > { public HadoopFileFormat ( ) { super ( ) ; } public HadoopFileFormat ( Configuration conf ) { super ( conf ) ; } @ Override public abstract long getPreferredFragmentSize ( ) throws IOException , InterruptedException ; @ Override public abstract long getMinimumFragmentSize ( ) throws IOException , InterruptedException ; public abstract ModelInput < T > createInput ( Class < ? extends T > dataType , FileSystem fileSystem , Path path , long offset , long fragmentSize , Counter counter ) throws IOException , InterruptedException ; public abstract ModelOutput < T > createOutput ( Class < ? extends T > dataType , FileSystem fileSystem , Path path , Counter counter ) throws IOException , InterruptedException ; } package com . asakusafw . runtime . directio . hadoop ; import java . util . Arrays ; public final class BlockInfo { private static final String [ ] EMPTY = new String [ ] ; final long start ; final long end ; final String [ ] hosts ; public BlockInfo ( long start , long end , String [ ] hosts ) { this . start = start ; this . end = end ; if ( hosts == null ) { this . hosts = EMPTY ; } else { this . hosts = hosts . clone ( ) ; Arrays . sort ( this . hosts ) ; } } public boolean isSameOwner ( BlockInfo other ) { if ( other == null ) { throw new IllegalArgumentException ( "" ) ; } return Arrays . equals ( hosts , other . hosts ) ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( start ) ; builder . append ( "" ) ; builder . append ( end ) ; builder . append ( "" ) ; builder . append ( Arrays . toString ( hosts ) ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . runtime . directio . hadoop ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . util . CountInputStream ; import com . asakusafw . runtime . directio . util . CountOutputStream ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class HadoopFileFormatAdapter < T > extends HadoopFileFormat < T > { static final Log LOG = LogFactory . getLog ( HadoopFileFormatAdapter . class ) ; private final BinaryStreamFormat < T > streamFormat ; public HadoopFileFormatAdapter ( BinaryStreamFormat < T > streamFormat ) { super ( ) ; if ( streamFormat == null ) { throw new IllegalArgumentException ( "" ) ; } this . streamFormat = streamFormat ; } public HadoopFileFormatAdapter ( BinaryStreamFormat < T > streamFormat , Configuration configuration ) { super ( configuration ) ; if ( streamFormat == null ) { throw new IllegalArgumentException ( "" ) ; } this . streamFormat = streamFormat ; } @ Override public Class < T > getSupportedType ( ) { return streamFormat . getSupportedType ( ) ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return streamFormat . getPreferredFragmentSize ( ) ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return streamFormat . getMinimumFragmentSize ( ) ; } @ Override public ModelInput < T > createInput ( Class < ? extends T > dataType , FileSystem fileSystem , final Path path , final long offset , final long fragmentSize , Counter counter ) throws IOException , InterruptedException { FSDataInputStream stream = fileSystem . open ( path ) ; boolean succeed = false ; try { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , path , offset , fragmentSize ) ) ; } if ( offset != ) { stream . seek ( offset ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , path , offset , fragmentSize ) ) ; } } CountInputStream cstream ; if ( LOG . isDebugEnabled ( ) ) { cstream = new CountInputStream ( stream , counter ) { @ Override public void close ( ) throws IOException { LOG . debug ( MessageFormat . format ( "" , path , offset , fragmentSize ) ) ; super . close ( ) ; LOG . debug ( MessageFormat . format ( "" , path , offset , fragmentSize ) ) ; } } ; } else { cstream = new CountInputStream ( stream , counter ) ; } ModelInput < T > input = streamFormat . createInput ( dataType , path . toString ( ) , cstream , offset , fragmentSize ) ; succeed = true ; return input ; } finally { if ( succeed == false ) { try { stream . close ( ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , path , offset , fragmentSize ) , e ) ; } } } } @ Override public ModelOutput < T > createOutput ( Class < ? extends T > dataType , FileSystem fileSystem , final Path path , Counter counter ) throws IOException , InterruptedException { FSDataOutputStream stream = fileSystem . create ( path ) ; boolean succeed = false ; try { CountOutputStream cstream ; if ( LOG . isDebugEnabled ( ) ) { cstream = new CountOutputStream ( stream , counter ) { @ Override public void close ( ) throws IOException { LOG . debug ( MessageFormat . format ( "" , path ) ) ; super . close ( ) ; LOG . debug ( MessageFormat . format ( "" , path ) ) ; } } ; } else { cstream = new CountOutputStream ( stream , counter ) ; } ModelOutput < T > output = streamFormat . createOutput ( dataType , path . toString ( ) , cstream ) ; succeed = true ; return output ; } finally { if ( succeed == false ) { try { stream . close ( ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , path ) , e ) ; } } } } } package com . asakusafw . runtime . directio . hadoop ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . BitSet ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import com . asakusafw . runtime . directio . DirectInputFragment ; class FragmentComputer { static final long MAX_MIN_SIZE = Long . MAX_VALUE / ; static final double MIN_LOCALITY = ; static final double PRUNE_REL_LOCALITY = ; private final long minSize ; private final long prefSize ; private final boolean combineBlocks ; private final boolean splitBlocks ; public FragmentComputer ( long minSize , long prefSize , boolean combineBlocks , boolean splitBlocks ) { this . minSize = Math . min ( minSize , MAX_MIN_SIZE ) ; this . prefSize = Math . max ( minSize , prefSize ) ; this . combineBlocks = combineBlocks ; this . splitBlocks = splitBlocks ; } public List < DirectInputFragment > computeFragments ( String path , long fileSize , Collection < BlockInfo > blocks ) { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } if ( blocks == null ) { throw new IllegalArgumentException ( "" ) ; } BlockMap map = createBlockMap ( path , fileSize , blocks ) ; List < DirectInputFragment > fragments = computeFragments ( map ) ; return fragments ; } private BlockMap createBlockMap ( String path , long fileSize , Collection < BlockInfo > blockList ) { assert path != null ; assert blockList != null ; BlockInfo [ ] blocks = blockList . toArray ( new BlockInfo [ blockList . size ( ) ] ) ; Arrays . sort ( blocks , new Comparator < BlockInfo > ( ) { @ Override public int compare ( BlockInfo o1 , BlockInfo o2 ) { int startDiff = compareLong ( o1 . start , o2 . start ) ; if ( startDiff != ) { return startDiff ; } return - compareLong ( o1 . hosts . length , o2 . hosts . length ) ; } } ) ; long lastOffset = ; List < BlockInfo > results = new ArrayList < BlockInfo > ( ) ; for ( BlockInfo block : blocks ) { if ( block . start >= fileSize ) { continue ; } if ( lastOffset < block . start ) { results . add ( new BlockInfo ( lastOffset , block . start , null ) ) ; } long start = Math . max ( lastOffset , block . start ) ; long end = Math . min ( fileSize , block . end ) ; if ( start >= end ) { continue ; } results . add ( new BlockInfo ( start , end , block . hosts ) ) ; lastOffset = end ; } assert lastOffset <= fileSize ; if ( lastOffset < fileSize ) { results . add ( new BlockInfo ( lastOffset , fileSize , null ) ) ; } if ( results . isEmpty ( ) ) { results . add ( new BlockInfo ( , fileSize , null ) ) ; } if ( combineBlocks ) { results = combine ( results ) ; } return new BlockMap ( path , results . toArray ( new BlockInfo [ results . size ( ) ] ) ) ; } private List < BlockInfo > combine ( List < BlockInfo > blocks ) { assert blocks != null ; List < BlockInfo > results = new ArrayList < BlockInfo > ( blocks . size ( ) ) ; Iterator < BlockInfo > iter = blocks . iterator ( ) ; assert iter . hasNext ( ) ; BlockInfo last = iter . next ( ) ; while ( iter . hasNext ( ) ) { BlockInfo next = iter . next ( ) ; if ( last . isSameOwner ( next ) ) { last = new BlockInfo ( last . start , next . end , last . hosts ) ; } else { results . add ( last ) ; last = next ; } } results . add ( last ) ; return results ; } private List < DirectInputFragment > computeFragments ( BlockMap map ) { assert map != null ; long size = map . size ; if ( canFragmentation ( ) == false || size / < minSize ) { return Collections . singletonList ( map . get ( , size ) ) ; } assert minSize > ; assert map . size > minSize ; BitSet processed = new BitSet ( map . blocks . length ) ; BlockInfo [ ] blocks = map . blocks ; assert size == blocks [ blocks . length - ] . end ; List < DirectInputFragment > results = new ArrayList < DirectInputFragment > ( ) ; for ( int index = processed . nextClearBit ( ) ; index < blocks . length ; index = processed . nextClearBit ( index + ) ) { int lastIndex = index + ; BlockInfo startBlock = blocks [ index ] ; assert size - startBlock . start >= minSize ; while ( blocks [ lastIndex - ] . end - startBlock . start < minSize ) { lastIndex ++ ; assert lastIndex <= blocks . length ; } long rest = size - blocks [ lastIndex - ] . end ; if ( rest < minSize ) { lastIndex = blocks . length ; } processed . set ( index , lastIndex ) ; long start = startBlock . start ; long end = blocks [ lastIndex - ] . end ; if ( splitBlocks ) { long groupSize = end - start ; int fragmentCount = Math . max ( ( int ) ( groupSize / prefSize ) , ) ; long eachFragmentSize = ( groupSize + fragmentCount - ) / fragmentCount ; long offset = start ; while ( offset != end ) { long fragmentSize = Math . min ( end - offset , eachFragmentSize ) ; results . add ( map . get ( offset , offset + fragmentSize ) ) ; offset += fragmentSize ; assert offset <= end : offset + "" + end ; } assert offset == end ; } else { results . add ( map . get ( start , end ) ) ; } } assert validFragments ( map , results ) ; return results ; } private boolean canFragmentation ( ) { return minSize >= ; } private boolean validFragments ( BlockMap map , List < DirectInputFragment > results ) { assert map != null ; assert results != null ; Collections . sort ( results , new Comparator < DirectInputFragment > ( ) { @ Override public int compare ( DirectInputFragment o1 , DirectInputFragment o2 ) { long i1 = o1 . getOffset ( ) ; long i2 = o2 . getOffset ( ) ; if ( i1 < i2 ) { return - ; } if ( i1 > i2 ) { return + ; } return ; } } ) ; long expectedOffset = ; for ( DirectInputFragment fragment : results ) { long offset = fragment . getOffset ( ) ; assert offset == expectedOffset : offset + "" + expectedOffset ; expectedOffset = offset + fragment . getSize ( ) ; } assert map . size == expectedOffset : map . size + "" + expectedOffset ; return true ; } static int compareLong ( long offset1 , long offset2 ) { if ( offset1 < offset2 ) { return - ; } else if ( offset1 > offset2 ) { return + ; } return ; } private static class BlockMap { final String path ; final BlockInfo [ ] blocks ; final long size ; BlockMap ( String path , BlockInfo [ ] blocks ) { assert path != null ; assert blocks != null ; assert blocks . length >= ; this . path = path ; this . blocks = blocks ; this . size = blocks [ blocks . length - ] . end - blocks [ ] . start ; } public DirectInputFragment get ( long start , long end ) { List < String > hosts = computeHosts ( start , end ) ; return new DirectInputFragment ( path , start , end - start , hosts ) ; } private List < String > computeHosts ( long start , long end ) { assert start <= end ; if ( start == end ) { return Collections . emptyList ( ) ; } List < Map . Entry < String , Long > > rank = computeLocalityRank ( start , end ) ; if ( rank . isEmpty ( ) ) { return Collections . emptyList ( ) ; } long max = rank . get ( ) . getValue ( ) ; if ( max < ( end - start ) * MIN_LOCALITY ) { return Collections . emptyList ( ) ; } long threshold = ( long ) ( max * PRUNE_REL_LOCALITY ) ; List < String > results = new ArrayList < String > ( ) ; for ( int i = , n = rank . size ( ) ; i < n ; i ++ ) { Map . Entry < String , Long > block = rank . get ( i ) ; if ( block . getValue ( ) < threshold ) { break ; } results . add ( block . getKey ( ) ) ; } return results ; } private List < Map . Entry < String , Long > > computeLocalityRank ( long start , long end ) { Map < String , Long > ownBytes = new HashMap < String , Long > ( ) ; for ( BlockInfo block : blocks ) { if ( block . end < start ) { continue ; } if ( block . start >= end ) { break ; } long s = Math . max ( start , block . start ) ; long e = Math . min ( end , block . end ) ; long length = e - s ; for ( String node : block . hosts ) { Long bytes = ownBytes . get ( node ) ; if ( bytes == null ) { ownBytes . put ( node , length ) ; } else { ownBytes . put ( node , bytes + length ) ; } } } if ( ownBytes . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < Map . Entry < String , Long > > entries = new ArrayList < Map . Entry < String , Long > > ( ownBytes . entrySet ( ) ) ; Collections . sort ( entries , new Comparator < Map . Entry < String , Long > > ( ) { @ Override public int compare ( Map . Entry < String , Long > o1 , Map . Entry < String , Long > o2 ) { return - compareLong ( o1 . getValue ( ) , o2 . getValue ( ) ) ; } } ) ; return entries ; } } } package com . asakusafw . runtime . directio . hadoop ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import com . asakusafw . runtime . directio . AbstractDirectDataSource ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceProfile ; import com . asakusafw . runtime . directio . DirectInputFragment ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . OutputTransactionContext ; import com . asakusafw . runtime . directio . ResourceInfo ; import com . asakusafw . runtime . directio . ResourcePattern ; import com . asakusafw . runtime . directio . keepalive . KeepAliveDataSource ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class HadoopDataSource extends AbstractDirectDataSource implements Configurable { static final Log LOG = LogFactory . getLog ( HadoopDataSource . class ) ; private volatile DirectDataSource core ; private volatile Configuration conf ; @ Override public Configuration getConf ( ) { return conf ; } @ Override public void setConf ( Configuration conf ) { this . conf = conf ; } @ Override public void configure ( DirectDataSourceProfile profile ) throws IOException , InterruptedException { if ( conf == null ) { throw new IllegalStateException ( ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , profile . getId ( ) , profile . getPath ( ) ) ) ; } HadoopDataSourceProfile hProfile = HadoopDataSourceProfile . convert ( profile , conf ) ; this . core = new HadoopDataSourceCore ( hProfile ) ; if ( hProfile . getKeepAliveInterval ( ) > ) { this . core = new KeepAliveDataSource ( core , hProfile . getKeepAliveInterval ( ) ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , hProfile ) ) ; } } @ Override public < T > List < DirectInputFragment > findInputFragments ( Class < ? extends T > dataType , DataFormat < T > format , String basePath , ResourcePattern resourcePattern ) throws IOException , InterruptedException { return core . findInputFragments ( dataType , format , basePath , resourcePattern ) ; } @ Override public < T > ModelInput < T > openInput ( Class < ? extends T > dataType , DataFormat < T > format , DirectInputFragment fragment , Counter counter ) throws IOException , InterruptedException { return core . openInput ( dataType , format , fragment , counter ) ; } @ Override public < T > ModelOutput < T > openOutput ( OutputAttemptContext context , Class < ? extends T > dataType , DataFormat < T > format , String basePath , String resourcePath , Counter counter ) throws IOException , InterruptedException { return core . openOutput ( context , dataType , format , basePath , resourcePath , counter ) ; } @ Override public List < ResourceInfo > list ( String basePath , ResourcePattern resourcePattern , Counter counter ) throws IOException , InterruptedException { return core . list ( basePath , resourcePattern , counter ) ; } @ Override public boolean delete ( String basePath , ResourcePattern resourcePattern , boolean recursive , Counter counter ) throws IOException , InterruptedException { return core . delete ( basePath , resourcePattern , recursive , counter ) ; } @ Override public void setupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { core . setupAttemptOutput ( context ) ; } @ Override public void commitAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { core . commitAttemptOutput ( context ) ; } @ Override public void cleanupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { core . cleanupAttemptOutput ( context ) ; } @ Override public void setupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { core . setupTransactionOutput ( context ) ; } @ Override public void commitTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { core . commitTransactionOutput ( context ) ; } @ Override public void cleanupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { core . cleanupTransactionOutput ( context ) ; } } package com . asakusafw . runtime . directio . hadoop ; import java . text . MessageFormat ; import org . apache . hadoop . util . Progressable ; import com . asakusafw . runtime . directio . Counter ; public final class ProgressableCounter extends Counter { private final Progressable progressable ; public ProgressableCounter ( Progressable progressable ) { if ( progressable == null ) { throw new IllegalArgumentException ( "" ) ; } this . progressable = progressable ; } @ Override protected void onChanged ( ) { progressable . progress ( ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , progressable . getClass ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . runtime . directio . hadoop ; import java . io . EOFException ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . SequenceFile . CompressionType ; import org . apache . hadoop . io . compress . CompressionCodec ; import org . apache . hadoop . util . ReflectionUtils ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public abstract class SequenceFileFormat < K , V , T > extends HadoopFileFormat < T > { static final Log LOG = LogFactory . getLog ( SequenceFileFormat . class ) ; static final String KEY_COMPRESSION_CODEC = "" ; static final String VALUE_COMPRESSION_AUTO = "" ; @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return SequenceFile . SYNC_INTERVAL ; } protected abstract K createKeyObject ( ) ; protected abstract V createValueObject ( ) ; protected abstract void copyToModel ( K key , V value , T model ) throws IOException ; protected abstract void copyFromModel ( T model , K key , V value ) throws IOException ; @ Override public ModelInput < T > createInput ( Class < ? extends T > dataType , FileSystem fileSystem , Path path , long offset , long fragmentSize , final Counter counter ) throws IOException , InterruptedException { final long end = offset + fragmentSize ; final K keyBuffer = createKeyObject ( ) ; final V valueBuffer = createValueObject ( ) ; final SequenceFile . Reader reader ; try { reader = new SequenceFile . Reader ( fileSystem , path , getConf ( ) ) ; } catch ( EOFException e ) { FileStatus status = fileSystem . getFileStatus ( path ) ; if ( status . getLen ( ) == ) { LOG . warn ( MessageFormat . format ( "" , path ) ) ; return new ModelInput < T > ( ) { @ Override public boolean readTo ( T model ) throws IOException { return false ; } @ Override public void close ( ) throws IOException { return ; } } ; } throw e ; } boolean succeed = false ; try { if ( offset > reader . getPosition ( ) ) { reader . sync ( offset ) ; } ModelInput < T > result = new ModelInput < T > ( ) { private boolean next = reader . getPosition ( ) < end ; private long lastPosition = reader . getPosition ( ) ; @ Override public boolean readTo ( T model ) throws IOException { if ( next == false ) { return false ; } long current = reader . getPosition ( ) ; @ SuppressWarnings ( "" ) K key = ( K ) reader . next ( keyBuffer ) ; if ( key == null || ( current >= end && reader . syncSeen ( ) ) ) { next = false ; return false ; } else { reader . getCurrentValue ( valueBuffer ) ; SequenceFileFormat . this . copyToModel ( keyBuffer , valueBuffer , model ) ; long nextPosition = reader . getPosition ( ) ; counter . add ( nextPosition - lastPosition ) ; lastPosition = nextPosition ; return true ; } } @ Override public void close ( ) throws IOException { reader . close ( ) ; } } ; succeed = true ; return result ; } finally { if ( succeed == false ) { reader . close ( ) ; } } } @ Override public ModelOutput < T > createOutput ( Class < ? extends T > dataType , FileSystem fileSystem , Path path , final Counter counter ) throws IOException , InterruptedException { final K keyBuffer = createKeyObject ( ) ; final V valueBuffer = createValueObject ( ) ; CompressionCodec codec = getCompressionCodec ( path ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , path , dataType . getName ( ) , codec ) ) ; } configure ( codec ) ; final SequenceFile . Writer writer = SequenceFile . createWriter ( fileSystem , getConf ( ) , path , keyBuffer . getClass ( ) , valueBuffer . getClass ( ) , codec == null ? CompressionType . NONE : CompressionType . BLOCK , codec ) ; boolean succeed = false ; try { ModelOutput < T > output = new ModelOutput < T > ( ) { private long lastPosition = ; @ Override public void write ( T model ) throws IOException { copyFromModel ( model , keyBuffer , valueBuffer ) ; writer . append ( keyBuffer , valueBuffer ) ; long nextPosition = writer . getLength ( ) ; counter . add ( nextPosition - lastPosition ) ; lastPosition = nextPosition ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } } ; succeed = true ; return output ; } finally { if ( succeed == false ) { writer . close ( ) ; } } } private void configure ( Object object ) { if ( object instanceof Configurable ) { Configurable configurable = ( Configurable ) object ; if ( configurable . getConf ( ) == null ) { configurable . setConf ( getConf ( ) ) ; } } } public CompressionCodec getCompressionCodec ( Path path ) throws IOException , InterruptedException { String codecClassName = getConf ( ) . get ( KEY_COMPRESSION_CODEC ) ; if ( codecClassName != null && codecClassName . isEmpty ( ) == false ) { try { Class < ? > codecClass = getConf ( ) . getClassByName ( codecClassName ) ; return ReflectionUtils . newInstance ( codecClass . asSubclass ( CompressionCodec . class ) , getConf ( ) ) ; } catch ( Exception e ) { LOG . warn ( MessageFormat . format ( "" , KEY_COMPRESSION_CODEC , codecClassName ) , e ) ; return null ; } } return null ; } } package com . asakusafw . runtime . directio . hadoop ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStreamReader ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . Scanner ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . OutputTransactionContext ; public final class DirectIoTransactionEditor extends Configured { static final Log LOG = LogFactory . getLog ( DirectIoTransactionEditor . class ) ; private DirectDataSourceRepository repository ; public DirectIoTransactionEditor ( ) { return ; } public DirectIoTransactionEditor ( DirectDataSourceRepository repository ) { this . repository = repository ; } public TransactionInfo get ( String executionId ) throws IOException { if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } Path path = HadoopDataSourceUtil . getTransactionInfoPath ( getConf ( ) , executionId ) ; try { FileStatus status = path . getFileSystem ( getConf ( ) ) . getFileStatus ( path ) ; return toInfoObject ( status ) ; } catch ( FileNotFoundException e ) { return null ; } } public List < TransactionInfo > list ( ) throws IOException { LOG . info ( "" ) ; List < FileStatus > list = new ArrayList < FileStatus > ( HadoopDataSourceUtil . findAllTransactionInfoFiles ( getConf ( ) ) ) ; if ( list . isEmpty ( ) ) { LOG . info ( "" ) ; return Collections . emptyList ( ) ; } Collections . sort ( list , new Comparator < FileStatus > ( ) { @ Override public int compare ( FileStatus o1 , FileStatus o2 ) { long t1 = o1 . getModificationTime ( ) ; long t2 = o2 . getModificationTime ( ) ; if ( t1 < t2 ) { return - ; } else if ( t1 > t2 ) { return + ; } return ; } } ) ; LOG . info ( MessageFormat . format ( "" , list . size ( ) ) ) ; List < TransactionInfo > results = new ArrayList < TransactionInfo > ( ) ; for ( FileStatus stat : list ) { TransactionInfo commitObject = toInfoObject ( stat ) ; if ( commitObject != null ) { results . add ( commitObject ) ; } } LOG . info ( "" ) ; return results ; } public boolean apply ( String executionId ) throws IOException , InterruptedException { if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( MessageFormat . format ( "" , executionId ) ) ; boolean applied = doApply ( executionId ) ; if ( applied ) { LOG . info ( MessageFormat . format ( "" , executionId ) ) ; } else { LOG . info ( MessageFormat . format ( "" , executionId ) ) ; } return applied ; } public boolean abort ( String executionId ) throws IOException , InterruptedException { if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( MessageFormat . format ( "" , executionId ) ) ; boolean aborted = doAbort ( executionId ) ; if ( aborted ) { LOG . info ( MessageFormat . format ( "" , executionId ) ) ; } else { LOG . info ( MessageFormat . format ( "" , executionId ) ) ; } return aborted ; } private TransactionInfo toInfoObject ( FileStatus stat ) throws IOException { assert stat != null ; Path path = stat . getPath ( ) ; String executionId = HadoopDataSourceUtil . getTransactionInfoExecutionId ( path ) ; long timestamp = stat . getModificationTime ( ) ; List < String > comment = new ArrayList < String > ( ) ; Path commitMarkPath = HadoopDataSourceUtil . getCommitMarkPath ( getConf ( ) , executionId ) ; FileSystem fs = path . getFileSystem ( getConf ( ) ) ; boolean committed = fs . exists ( commitMarkPath ) ; try { FSDataInputStream input = fs . open ( path ) ; try { Scanner scanner = new Scanner ( new InputStreamReader ( input , HadoopDataSourceUtil . COMMENT_CHARSET ) ) ; while ( scanner . hasNextLine ( ) ) { comment . add ( scanner . nextLine ( ) ) ; } scanner . close ( ) ; } finally { input . close ( ) ; } } catch ( IOException e ) { comment . add ( e . toString ( ) ) ; } return new TransactionInfo ( executionId , timestamp , committed , comment ) ; } private boolean doApply ( String executionId ) throws IOException , InterruptedException { assert executionId != null ; Path transactionInfo = HadoopDataSourceUtil . getTransactionInfoPath ( getConf ( ) , executionId ) ; Path commitMark = HadoopDataSourceUtil . getCommitMarkPath ( getConf ( ) , executionId ) ; FileSystem fs = commitMark . getFileSystem ( getConf ( ) ) ; if ( fs . exists ( transactionInfo ) == false ) { return false ; } boolean succeed = true ; if ( fs . exists ( commitMark ) == false ) { return false ; } DirectDataSourceRepository repo = getRepository ( ) ; for ( String containerPath : repo . getContainerPaths ( ) ) { String datasourceId = repo . getRelatedId ( containerPath ) ; try { DirectDataSource datasource = repo . getRelatedDataSource ( containerPath ) ; OutputTransactionContext context = HadoopDataSourceUtil . createContext ( executionId , datasourceId ) ; datasource . commitTransactionOutput ( context ) ; datasource . cleanupTransactionOutput ( context ) ; } catch ( IOException e ) { succeed = false ; LOG . error ( MessageFormat . format ( "" , datasourceId , executionId ) ) ; } } if ( succeed ) { LOG . info ( MessageFormat . format ( "" , executionId , commitMark ) ) ; try { if ( fs . delete ( commitMark , true ) == false ) { LOG . warn ( MessageFormat . format ( "" , executionId , commitMark ) ) ; } else if ( fs . delete ( transactionInfo , true ) == false ) { LOG . warn ( MessageFormat . format ( "" , executionId , transactionInfo ) ) ; } } catch ( FileNotFoundException e ) { LOG . warn ( MessageFormat . format ( "" , executionId , commitMark ) , e ) ; } return true ; } else { throw new IOException ( MessageFormat . format ( "" + "" , executionId ) ) ; } } private boolean doAbort ( String executionId ) throws IOException , InterruptedException { assert executionId != null ; Path transactionInfo = HadoopDataSourceUtil . getTransactionInfoPath ( getConf ( ) , executionId ) ; Path commitMark = HadoopDataSourceUtil . getCommitMarkPath ( getConf ( ) , executionId ) ; FileSystem fs = commitMark . getFileSystem ( getConf ( ) ) ; if ( fs . exists ( transactionInfo ) == false ) { return false ; } boolean succeed = true ; if ( fs . exists ( commitMark ) ) { LOG . info ( MessageFormat . format ( "" , executionId , commitMark ) ) ; if ( fs . delete ( commitMark , true ) == false ) { succeed = false ; LOG . warn ( MessageFormat . format ( "" , executionId , commitMark ) ) ; } } DirectDataSourceRepository repo = getRepository ( ) ; for ( String containerPath : repo . getContainerPaths ( ) ) { String datasourceId = repo . getRelatedId ( containerPath ) ; try { DirectDataSource datasource = repo . getRelatedDataSource ( containerPath ) ; OutputTransactionContext context = HadoopDataSourceUtil . createContext ( executionId , datasourceId ) ; datasource . cleanupTransactionOutput ( context ) ; } catch ( IOException e ) { succeed = false ; LOG . error ( MessageFormat . format ( "" , datasourceId , executionId ) ) ; } } if ( succeed ) { LOG . info ( MessageFormat . format ( "" , executionId , commitMark ) ) ; try { if ( fs . delete ( transactionInfo , true ) == false ) { LOG . warn ( MessageFormat . format ( "" , executionId , transactionInfo ) ) ; } } catch ( FileNotFoundException e ) { LOG . warn ( MessageFormat . format ( "" , executionId , commitMark ) , e ) ; } return true ; } else { throw new IOException ( MessageFormat . format ( "" + "" , executionId , transactionInfo ) ) ; } } private synchronized DirectDataSourceRepository getRepository ( ) { if ( repository == null ) { LOG . info ( "" ) ; repository = HadoopDataSourceUtil . loadRepository ( getConf ( ) ) ; LOG . info ( "" ) ; } return repository ; } public static class TransactionInfo { private final String executionId ; private final long timestamp ; private final boolean committed ; private final List < String > comment ; public TransactionInfo ( String executionId , long timestamp , boolean committed , List < String > comment ) { if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( comment == null ) { throw new IllegalArgumentException ( "" ) ; } this . executionId = executionId ; this . timestamp = timestamp ; this . committed = committed ; this . comment = comment ; } public String getExecutionId ( ) { return executionId ; } public long getTimestamp ( ) { return timestamp ; } public boolean isCommitted ( ) { return committed ; } public List < String > getComment ( ) { return comment ; } } } package com . asakusafw . runtime . directio ; public interface ResourcePattern { } package com . asakusafw . runtime . model ; public interface DataModel < T extends DataModel < T > > { void reset ( ) ; void copyFrom ( T other ) ; } package com . asakusafw . runtime . model ; import java . text . MessageFormat ; public final class PropertyInfo { private final String name ; private final Class < ? > type ; private final int ordinal ; public PropertyInfo ( String name , Class < ? > type , int ordinal ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( ordinal < ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . type = type ; this . ordinal = ordinal ; } public String getName ( ) { return name ; } public Class < ? > getType ( ) { return type ; } public int getOrdinal ( ) { return ordinal ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , name , type , String . valueOf ( ordinal ) ) ; } } package com . asakusafw . runtime . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . runtime . io . ModelInput ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface ModelInputLocation { Class < ? extends ModelInput < ? > > value ( ) ; } package com . asakusafw . runtime . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Inherited ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Inherited @ Documented public @ interface DataModelKind { String value ( ) ; String [ ] version ( ) default { } ; } package com . asakusafw . runtime . model ; package com . asakusafw . runtime . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . runtime . io . ModelOutput ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface ModelOutputLocation { Class < ? extends ModelOutput < ? > > value ( ) ; } package com . asakusafw . runtime . model ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) public @ interface PropertyOrder { String [ ] value ( ) ; } package com . asakusafw . runtime . core ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public interface RuntimeResource { void setup ( ResourceConfiguration configuration ) throws IOException , InterruptedException ; void cleanup ( ResourceConfiguration configuration ) throws IOException , InterruptedException ; abstract class DelegateRegisterer < D > implements RuntimeResource { static final Log LOG = LogFactory . getLog ( RuntimeResource . DelegateRegisterer . class ) ; private D registered ; protected abstract String getClassNameKey ( ) ; protected abstract Class < ? extends D > getInterfaceType ( ) ; protected abstract void register ( D delegate , ResourceConfiguration configuration ) throws IOException , InterruptedException ; protected abstract void unregister ( D delegate , ResourceConfiguration configuration ) throws IOException , InterruptedException ; @ Override public void setup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { String className = configuration . get ( getClassNameKey ( ) , null ) ; if ( className == null ) { LOG . warn ( MessageFormat . format ( "" , getClassNameKey ( ) , getInterfaceType ( ) . getName ( ) ) ) ; return ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , getInterfaceType ( ) . getName ( ) , getClassNameKey ( ) , className ) ) ; } D loaded = loadDelegate ( configuration , className ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , getInterfaceType ( ) . getName ( ) , getClassNameKey ( ) , className ) ) ; } register ( loaded , configuration ) ; this . registered = loaded ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , getInterfaceType ( ) . getName ( ) , getClassNameKey ( ) , className ) ) ; } } @ Override public void cleanup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { if ( registered != null ) { unregister ( registered , configuration ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , getInterfaceType ( ) . getName ( ) , registered . getClass ( ) . getName ( ) ) ) ; } registered = null ; } } private D loadDelegate ( ResourceConfiguration configuration , String className ) throws IOException { assert configuration != null ; assert className != null ; try { Class < ? > aClass = configuration . getClassLoader ( ) . loadClass ( className ) ; Class < ? extends D > delegate = aClass . asSubclass ( getInterfaceType ( ) ) ; D instance = delegate . newInstance ( ) ; return instance ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , className ) , e ) ; } } } } package com . asakusafw . runtime . core ; public interface ResourceConfiguration { String get ( String keyName , String defaultValue ) ; void set ( String keyName , String value ) ; ClassLoader getClassLoader ( ) ; } package com . asakusafw . runtime . core . context ; package com . asakusafw . runtime . core . context ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Documented @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . TYPE ) public @ interface SimulationSupport { } package com . asakusafw . runtime . core . context ; public class InconsistentApplicationException extends IllegalStateException { private static final long serialVersionUID = ; public InconsistentApplicationException ( String message ) { super ( message ) ; } public InconsistentApplicationException ( String message , Throwable cause ) { super ( message , cause ) ; } } package com . asakusafw . runtime . core . context ; import java . io . IOException ; import java . io . InputStream ; import java . lang . reflect . Method ; import java . net . URL ; import java . text . MessageFormat ; import java . util . Enumeration ; import java . util . HashMap ; import java . util . Locale ; import java . util . Map ; import java . util . Properties ; import java . util . concurrent . atomic . AtomicReference ; import java . util . logging . Level ; import com . asakusafw . runtime . core . BatchRuntime ; public final class RuntimeContext { static final java . util . logging . Logger LOG = java . util . logging . Logger . getLogger ( RuntimeContext . class . getName ( ) ) ; static { try { Class < ? > bridge = Class . forName ( "" ) ; Method isInstalled = bridge . getMethod ( "" ) ; Method install = bridge . getMethod ( "" ) ; Method clean = bridge . getMethod ( "" ) ; if ( Boolean . FALSE . equals ( isInstalled . invoke ( null ) ) ) { clean . invoke ( null ) ; install . invoke ( null ) ; } } catch ( Exception e ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . log ( Level . FINE , "" , e ) ; } } } public static final RuntimeContext DEFAULT = new RuntimeContext ( ) ; public static final String PATH_APPLICATION_INFO = "" ; public static final String KEY_EXECUTION_MODE = "" ; public static final String KEY_BATCH_ID = "" ; public static final String KEY_FLOW_ID = "" ; public static final String KEY_BUILD_ID = "" ; public static final String KEY_BUILD_DATE = "" ; public static final String KEY_RUNTIME_VERSION = "" ; private static final AtomicReference < RuntimeContext > GLOBAL = new AtomicReference < RuntimeContext > ( DEFAULT ) ; private final String batchId ; private final ExecutionMode mode ; private final String buildId ; private RuntimeContext ( ) { this ( ExecutionMode . PRODUCTION , null , null ) ; } private RuntimeContext ( ExecutionMode mode , String batchId , String verificationCode ) { assert mode != null ; this . mode = mode ; this . batchId = batchId ; this . buildId = verificationCode ; } public static RuntimeContext get ( ) { return GLOBAL . get ( ) ; } public static void set ( RuntimeContext context ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } GLOBAL . set ( context ) ; } public static String getRuntimeVersion ( ) { return BatchRuntime . getLabel ( ) ; } public RuntimeContext mode ( ExecutionMode newValue ) { if ( newValue == null ) { throw new IllegalArgumentException ( "" ) ; } return new RuntimeContext ( newValue , batchId , buildId ) ; } public RuntimeContext batchId ( String newValue ) { return new RuntimeContext ( mode , newValue , buildId ) ; } public RuntimeContext buildId ( String newValue ) { return new RuntimeContext ( mode , batchId , newValue ) ; } public RuntimeContext apply ( Map < String , String > newValueMap ) { if ( newValueMap == null ) { throw new IllegalArgumentException ( "" ) ; } RuntimeContext current = this ; String newModeString = normalize ( newValueMap . get ( KEY_EXECUTION_MODE ) ) ; if ( newModeString != null ) { ExecutionMode newMode = ExecutionMode . fromSymbol ( newModeString ) ; if ( newMode != null ) { current = current . mode ( newMode ) ; } else { if ( LOG . isLoggable ( Level . WARNING ) ) { LOG . warning ( MessageFormat . format ( "" , KEY_EXECUTION_MODE , newModeString ) ) ; } } } String newBatchId = normalize ( newValueMap . get ( KEY_BATCH_ID ) ) ; if ( newBatchId != null ) { current = current . batchId ( newBatchId ) ; } String newVerificationCode = normalize ( newValueMap . get ( KEY_BUILD_ID ) ) ; if ( newVerificationCode != null ) { current = current . buildId ( newVerificationCode ) ; } return current ; } public Map < String , String > unapply ( ) { Map < String , String > results = new HashMap < String , String > ( ) ; put ( results , KEY_EXECUTION_MODE , mode . getSymbol ( ) ) ; put ( results , KEY_BATCH_ID , batchId ) ; put ( results , KEY_BUILD_ID , buildId ) ; return results ; } public boolean isSimulation ( ) { return mode == ExecutionMode . SIMULATION ; } public boolean canExecute ( Object object ) { if ( object == null ) { throw new IllegalArgumentException ( "" ) ; } switch ( mode ) { case PRODUCTION : return true ; case SIMULATION : return isSimulationSupported ( object ) ; default : throw new AssertionError ( mode ) ; } } private boolean isSimulationSupported ( Object object ) { assert object != null ; boolean annotated = object . getClass ( ) . isAnnotationPresent ( SimulationSupport . class ) ; return annotated ; } public void verifyApplication ( ClassLoader classLoader ) { if ( classLoader == null ) { throw new IllegalArgumentException ( "" ) ; } if ( batchId == null ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "" ) ; } return ; } if ( buildId == null ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "" ) ; } return ; } boolean verified = false ; try { Enumeration < URL > infoEnum = classLoader . getResources ( PATH_APPLICATION_INFO ) ; while ( infoEnum . hasMoreElements ( ) ) { URL url = infoEnum . nextElement ( ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( MessageFormat . format ( "" , url ) ) ; } Properties properties = new Properties ( ) ; InputStream in = url . openStream ( ) ; try { properties . load ( in ) ; } finally { in . close ( ) ; } verifyRuntime ( url , properties ) ; verified |= verifyBuildId ( url , properties ) ; } } catch ( IOException e ) { throw new InconsistentApplicationException ( "" , e ) ; } if ( verified ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( MessageFormat . format ( "" , batchId , buildId ) ) ; } return ; } else { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( MessageFormat . format ( "" , batchId , buildId , classLoader ) ) ; } return ; } } private boolean verifyBuildId ( URL url , Properties properties ) { assert batchId != null ; assert buildId != null ; assert url != null ; assert properties != null ; String targetBatchId = normalize ( properties . getProperty ( KEY_BATCH_ID ) ) ; String targetBuildId = normalize ( properties . getProperty ( KEY_BUILD_ID ) ) ; if ( targetBatchId == null || targetBatchId . equals ( batchId ) == false ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( MessageFormat . format ( "" , url , batchId ) ) ; } return false ; } else if ( targetBuildId != null && targetBuildId . equals ( buildId ) ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( MessageFormat . format ( "" , url , batchId ) ) ; } return true ; } else { throw new InconsistentApplicationException ( MessageFormat . format ( "" + "" , url , batchId , buildId , targetBuildId , getHostName ( ) ) ) ; } } private void verifyRuntime ( URL url , Properties properties ) { assert url != null ; assert properties != null ; String runtimeVersion = normalize ( properties . getProperty ( KEY_RUNTIME_VERSION ) ) ; if ( runtimeVersion == null ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( MessageFormat . format ( "" , url ) ) ; } return ; } else if ( runtimeVersion . equals ( BatchRuntime . getLabel ( ) ) ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( MessageFormat . format ( "" , url ) ) ; } return ; } else { throw new InconsistentApplicationException ( MessageFormat . format ( "" + "" , url , batchId , BatchRuntime . getLabel ( ) , runtimeVersion , getHostName ( ) ) ) ; } } private void put ( Map < String , String > map , String key , String value ) { assert map != null ; assert key != null ; if ( value != null ) { map . put ( key , value ) ; } } private String normalize ( String value ) { if ( value == null ) { return null ; } String trimmed = value . trim ( ) ; if ( trimmed . isEmpty ( ) ) { return null ; } return trimmed ; } private String getHostName ( ) { String hostname = System . getenv ( "" ) ; if ( hostname == null ) { hostname = System . getenv ( "" ) ; } return hostname ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( batchId == null ) ? : batchId . hashCode ( ) ) ; result = prime * result + mode . hashCode ( ) ; result = prime * result + ( ( buildId == null ) ? : buildId . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } RuntimeContext other = ( RuntimeContext ) obj ; if ( batchId == null ) { if ( other . batchId != null ) { return false ; } } else if ( ! batchId . equals ( other . batchId ) ) { return false ; } if ( mode != other . mode ) { return false ; } if ( buildId == null ) { if ( other . buildId != null ) { return false ; } } else if ( ! buildId . equals ( other . buildId ) ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( batchId ) ; builder . append ( "" ) ; builder . append ( mode ) ; builder . append ( "" ) ; builder . append ( buildId ) ; builder . append ( "" ) ; return builder . toString ( ) ; } public enum ExecutionMode { PRODUCTION ( "" ) , SIMULATION ( "" ) , ; private final String symbol ; private ExecutionMode ( String symbol ) { assert symbol != null ; this . symbol = symbol ; } public String getSymbol ( ) { return symbol ; } public static ExecutionMode fromSymbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } String s = symbol . toLowerCase ( Locale . ENGLISH ) ; for ( ExecutionMode mode : values ( ) ) { if ( mode . symbol . equals ( s ) ) { return mode ; } } return null ; } } } package com . asakusafw . runtime . core ; package com . asakusafw . runtime . core ; public interface Result < T > { void add ( T result ) ; class OutputException extends RuntimeException { private static final long serialVersionUID = ; public OutputException ( ) { super ( ) ; } public OutputException ( String message ) { super ( message ) ; } public OutputException ( Throwable cause ) { super ( cause ) ; } public OutputException ( String message , Throwable cause ) { super ( message , cause ) ; } } } package com . asakusafw . runtime . core ; import org . apache . hadoop . conf . Configuration ; public class HadoopConfiguration implements ResourceConfiguration { private Configuration configration ; public HadoopConfiguration ( ) { this ( new Configuration ( false ) ) ; } public HadoopConfiguration ( Configuration configuration ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . configration = configuration ; } @ Override public String get ( String keyName , String defaultValue ) { if ( keyName == null ) { throw new IllegalArgumentException ( "" ) ; } return configration . get ( keyName , defaultValue ) ; } @ Override public void set ( String keyName , String value ) { if ( keyName == null ) { throw new IllegalArgumentException ( "" ) ; } configration . set ( keyName , value ) ; } @ Override public ClassLoader getClassLoader ( ) { return configration . getClassLoader ( ) ; } } package com . asakusafw . runtime . core ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . runtime . util . VariableTable ; public class BatchContext { static final ThreadLocal < BatchContext > CONTEXTS = new ThreadLocal < BatchContext > ( ) { @ Override protected BatchContext initialValue ( ) { throw new IllegalStateException ( "" ) ; } } ; private Map < String , String > variables = new HashMap < String , String > ( ) ; protected BatchContext ( Map < String , String > variables ) { if ( variables == null ) { throw new IllegalArgumentException ( "" ) ; } this . variables = new HashMap < String , String > ( variables ) ; } public static String get ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return CONTEXTS . get ( ) . variables . get ( name ) ; } public static class Initializer implements RuntimeResource { @ Override public void setup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { String arguments = configuration . get ( StageConstants . PROP_ASAKUSA_BATCH_ARGS , "" ) ; VariableTable variables = new VariableTable ( VariableTable . RedefineStrategy . IGNORE ) ; variables . defineVariables ( arguments ) ; BatchContext context = new BatchContext ( variables . getVariables ( ) ) ; CONTEXTS . set ( context ) ; } @ Override public void cleanup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { CONTEXTS . remove ( ) ; } } } package com . asakusafw . runtime . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ServiceLoader ; public final class Report { public static final String K_DELEGATE_CLASS = "" ; private static final ThreadLocal < Delegate > DELEGATE = new ThreadLocal < Delegate > ( ) { @ Override protected Delegate initialValue ( ) { throw new FailedException ( "" ) ; } } ; public static void setDelegate ( Delegate delegate ) { if ( delegate == null ) { DELEGATE . remove ( ) ; } else { DELEGATE . set ( delegate ) ; } } public static void info ( String message ) { try { DELEGATE . get ( ) . report ( Level . INFO , message ) ; } catch ( IOException e ) { throw new FailedException ( e ) ; } } public static void warn ( String message ) { try { DELEGATE . get ( ) . report ( Level . WARN , message ) ; } catch ( IOException e ) { throw new FailedException ( e ) ; } } public static void error ( String message ) { try { DELEGATE . get ( ) . report ( Level . ERROR , message ) ; } catch ( IOException e ) { throw new FailedException ( e ) ; } } private Report ( ) { throw new AssertionError ( ) ; } public static class FailedException extends RuntimeException { private static final long serialVersionUID = ; public FailedException ( ) { super ( ) ; } public FailedException ( String message , Throwable cause ) { super ( message , cause ) ; } public FailedException ( String message ) { super ( message ) ; } public FailedException ( Throwable cause ) { super ( cause ) ; } } public abstract static class Delegate implements RuntimeResource { @ Override public void setup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { return ; } @ Override public void cleanup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { return ; } protected abstract void report ( Level level , String message ) throws IOException ; } public enum Level { INFO , WARN , ERROR , } public static class Initializer extends RuntimeResource . DelegateRegisterer < Delegate > { @ Override protected String getClassNameKey ( ) { return K_DELEGATE_CLASS ; } @ Override protected Class < ? extends Delegate > getInterfaceType ( ) { return Delegate . class ; } @ Override protected void register ( Delegate delegate , ResourceConfiguration configuration ) throws IOException , InterruptedException { delegate . setup ( configuration ) ; setDelegate ( delegate ) ; } @ Override protected void unregister ( Delegate delegate , ResourceConfiguration configuration ) throws IOException , InterruptedException { setDelegate ( null ) ; delegate . cleanup ( configuration ) ; } } public static class Default extends Delegate { @ Override protected void report ( Level level , String message ) { switch ( level ) { case INFO : System . out . println ( message ) ; break ; case WARN : System . err . println ( message ) ; new Exception ( "" ) . printStackTrace ( ) ; break ; case ERROR : System . err . println ( message ) ; new Exception ( "" ) . printStackTrace ( ) ; break ; default : throw new AssertionError ( MessageFormat . format ( "" , level , message ) ) ; } } } } package com . asakusafw . runtime . core ; import java . text . MessageFormat ; public final class BatchRuntime { public static final int VERSION_MAJOR = ; public static final int VERSION_MINOR = ; public static void require ( int major , int minor ) { if ( major != VERSION_MAJOR || minor != VERSION_MINOR ) { throw new IllegalStateException ( MessageFormat . format ( "" , toString ( VERSION_MAJOR , VERSION_MINOR ) , toString ( major , minor ) ) ) ; } } public static String getLabel ( ) { return toString ( VERSION_MAJOR , VERSION_MINOR ) ; } private static String toString ( int major , int minor ) { return MessageFormat . format ( "" , String . valueOf ( major ) , String . valueOf ( minor ) ) ; } private BatchRuntime ( ) { return ; } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class DateOption extends ValueOption < DateOption > { private final Date entity = new Date ( ) ; public DateOption ( ) { super ( ) ; } public DateOption ( Date valueOrNull ) { super ( ) ; if ( valueOrNull != null ) { this . entity . setElapsedDays ( valueOrNull . getElapsedDays ( ) ) ; this . nullValue = false ; } } public Date get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return entity ; } public Date or ( Date alternate ) { if ( nullValue ) { return alternate ; } return get ( ) ; } public int or ( int alternate ) { if ( nullValue ) { return alternate ; } return get ( ) . getElapsedDays ( ) ; } @ Deprecated public DateOption modify ( Date newValue ) { if ( newValue == null ) { this . nullValue = true ; } else { this . nullValue = false ; this . entity . setElapsedDays ( newValue . getElapsedDays ( ) ) ; } return this ; } @ Deprecated public DateOption modify ( int newValue ) { this . nullValue = false ; this . entity . setElapsedDays ( newValue ) ; return this ; } @ Override @ Deprecated public void copyFrom ( DateOption optionOrNull ) { if ( this == optionOrNull ) { return ; } else if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { modify ( optionOrNull . entity ) ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + entity . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DateOption other = ( DateOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && entity . equals ( other . entity ) == false ) { return false ; } return true ; } public boolean has ( Date other ) { if ( isNull ( ) ) { return other == null ; } return entity . equals ( other ) ; } @ Override public int compareTo ( WritableRawComparable o ) { DateOption other = ( DateOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } return entity . compareTo ( other . entity ) ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return get ( ) . toString ( ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; out . writeInt ( entity . getElapsedDays ( ) ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { modify ( in . readInt ( ) ) ; } else { setNull ( ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset + ] == ) { setNull ( ) ; return ; } else if ( limit - offset >= + ) { modify ( ByteArrayUtil . readInt ( bytes , offset + ) ) ; return ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return bytes [ offset ] == ? : ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { if ( b1 [ s1 ] == || b2 [ s2 ] == ) { return ByteArrayUtil . compare ( b1 [ s1 ] , b2 [ s2 ] ) ; } return ByteArrayUtil . compare ( ByteArrayUtil . readInt ( b1 , s1 + ) , ByteArrayUtil . readInt ( b2 , s2 + ) ) ; } } package com . asakusafw . runtime . value ; package com . asakusafw . runtime . value ; import java . util . Calendar ; public final class DateUtil { private static final int DAYS_YEAR = ; private static final int DAYS_JANUARY = ; private static final int DAYS_FEBRUARY = DAYS_JANUARY + ; private static final int DAYS_MARCH = DAYS_FEBRUARY + ; private static final int DAYS_APRIL = DAYS_MARCH + ; private static final int DAYS_MAY = DAYS_APRIL + ; private static final int DAYS_JUNE = DAYS_MAY + ; private static final int DAYS_JULY = DAYS_JUNE + ; private static final int DAYS_AUGUST = DAYS_JULY + ; private static final int DAYS_SEPTEMBER = DAYS_AUGUST + ; private static final int DAYS_OCTOBER = DAYS_SEPTEMBER + ; private static final int DAYS_NOVEMBER = DAYS_OCTOBER + ; private static final int [ ] DAYS_MONTH = { , DAYS_JANUARY , DAYS_FEBRUARY , DAYS_MARCH , DAYS_APRIL , DAYS_MAY , DAYS_JUNE , DAYS_JULY , DAYS_AUGUST , DAYS_SEPTEMBER , DAYS_OCTOBER , DAYS_NOVEMBER , } ; private static final int YEARS_LEAP_CYCLE = ; private static final int DAYS_LEAP_CYCLE = DAYS_YEAR * YEARS_LEAP_CYCLE + ( YEARS_LEAP_CYCLE / ) - ( YEARS_LEAP_CYCLE / ) + ( YEARS_LEAP_CYCLE / ) ; private static final int YEARS_CENTURY = ; private static final int DAYS_CENTURY = DAYS_YEAR * YEARS_CENTURY + ( YEARS_CENTURY / ) - ( YEARS_CENTURY / ) + ( YEARS_CENTURY / ) ; private static final int YEARS_LEAP = ; private static final int DAYS_LEAP = DAYS_YEAR * YEARS_LEAP + ( YEARS_LEAP / ) - ( YEARS_LEAP / ) + ( YEARS_LEAP / ) ; public static int getDayFromDate ( int year , int month , int day ) { int result = ; result += getDayFromYear ( year ) ; result += DAYS_MONTH [ month - ] ; result += day - ; if ( month >= && isLeap ( year ) ) { result += ; } return result ; } public static int getDayFromCalendar ( Calendar calendar ) { int year = calendar . get ( Calendar . YEAR ) ; int month = calendar . get ( Calendar . MONTH ) + ; int day = calendar . get ( Calendar . DAY_OF_MONTH ) ; return getDayFromDate ( year , month , day ) ; } public static void setDayToCalendar ( int days , Calendar calendar ) { int year = getYearFromDay ( days ) ; int daysInYear = days - getDayFromYear ( year ) ; boolean leap = isLeap ( year ) ; int month = getMonthOfYear ( daysInYear , leap ) ; int day = getDayOfMonth ( daysInYear , leap ) ; calendar . set ( year , month - , day , , , ) ; calendar . set ( Calendar . MILLISECOND , ) ; } public static int getSecondFromTime ( int hour , int minute , int second ) { int result = ; result += hour * * ; result += minute * ; result += second ; return result ; } public static long getSecondFromCalendar ( Calendar calendar ) { int days = getDayFromCalendar ( calendar ) ; long result = ( long ) days * ; result += calendar . get ( Calendar . HOUR_OF_DAY ) * * ; result += calendar . get ( Calendar . MINUTE ) * ; result += calendar . get ( Calendar . SECOND ) ; return result ; } public static void setSecondToCalendar ( long seconds , Calendar calendar ) { int days = getDayFromSeconds ( seconds ) ; int year = getYearFromDay ( days ) ; int daysInYear = days - getDayFromYear ( year ) ; boolean leap = isLeap ( year ) ; int month = getMonthOfYear ( daysInYear , leap ) ; int day = getDayOfMonth ( daysInYear , leap ) ; int rest = getSecondOfDay ( seconds ) ; int hour = rest / ( * ) ; int minute = rest / % ; int second = rest % ; calendar . set ( year , month - , day , hour , minute , second ) ; calendar . set ( Calendar . MILLISECOND , ) ; } public static int getYearFromDay ( int dayOfEra ) { int cycles = dayOfEra / DAYS_LEAP_CYCLE ; int cycleRest = dayOfEra % DAYS_LEAP_CYCLE ; int centInCycle = cycleRest / DAYS_CENTURY ; int centRest = cycleRest % DAYS_CENTURY ; centRest += DAYS_CENTURY * ( centInCycle / ( YEARS_LEAP_CYCLE / YEARS_CENTURY ) ) ; centInCycle -= ( centInCycle / ( YEARS_LEAP_CYCLE / YEARS_CENTURY ) ) ; int leapInCent = centRest / DAYS_LEAP ; int leapRest = centRest % DAYS_LEAP ; int yearInLeap = leapRest / DAYS_YEAR ; yearInLeap -= ( yearInLeap / YEARS_LEAP ) ; int year = YEARS_LEAP_CYCLE * cycles + YEARS_CENTURY * centInCycle + YEARS_LEAP * leapInCent + yearInLeap + ; return year ; } public static boolean isLeap ( int year ) { if ( year % != ) { return false ; } return ( year % ) != || ( year % ) == ; } public static int getDayFromYear ( int year ) { int y = year - ; return DAYS_YEAR * y + ( y / ) - ( y / ) + ( y / ) ; } public static int getMonthOfYear ( int dayOfYear , boolean leap ) { int d = dayOfYear ; if ( d < DAYS_JANUARY ) { return ; } if ( leap ) { d -- ; } if ( d < DAYS_FEBRUARY ) { return ; } if ( d < DAYS_MARCH ) { return ; } if ( d < DAYS_APRIL ) { return ; } if ( d < DAYS_MAY ) { return ; } if ( d < DAYS_JUNE ) { return ; } if ( d < DAYS_JULY ) { return ; } if ( d < DAYS_AUGUST ) { return ; } if ( d < DAYS_SEPTEMBER ) { return ; } if ( d < DAYS_OCTOBER ) { return ; } if ( d < DAYS_NOVEMBER ) { return ; } return ; } public static int getDayOfMonth ( int dayOfYear , boolean leap ) { int d = dayOfYear ; if ( d < DAYS_JANUARY ) { return d + ; } if ( d < DAYS_FEBRUARY ) { return d - ( DAYS_JANUARY - ) ; } if ( leap ) { if ( d == DAYS_FEBRUARY ) { return ; } d -- ; } if ( d < DAYS_MARCH ) { return d - ( DAYS_FEBRUARY - ) ; } if ( d < DAYS_APRIL ) { return d - ( DAYS_MARCH - ) ; } if ( d < DAYS_MAY ) { return d - ( DAYS_APRIL - ) ; } if ( d < DAYS_JUNE ) { return d - ( DAYS_MAY - ) ; } if ( d < DAYS_JULY ) { return d - ( DAYS_JUNE - ) ; } if ( d < DAYS_AUGUST ) { return d - ( DAYS_JULY - ) ; } if ( d < DAYS_SEPTEMBER ) { return d - ( DAYS_AUGUST - ) ; } if ( d < DAYS_OCTOBER ) { return d - ( DAYS_SEPTEMBER - ) ; } if ( d < DAYS_NOVEMBER ) { return d - ( DAYS_OCTOBER - ) ; } return d - ( DAYS_NOVEMBER - ) ; } public static int getDayFromSeconds ( long seconds ) { return ( int ) ( seconds / ) ; } public static int getSecondOfDay ( long seconds ) { return ( int ) ( seconds % ) ; } private DateUtil ( ) { throw new AssertionError ( ) ; } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . io . WritableComparator ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class DoubleOption extends ValueOption < DoubleOption > { private double value ; public DoubleOption ( ) { super ( ) ; } public DoubleOption ( double value ) { super ( ) ; this . value = value ; this . nullValue = false ; } public double get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return value ; } public double or ( double alternate ) { if ( nullValue ) { return alternate ; } return value ; } public void add ( double delta ) { if ( nullValue ) { throw new NullPointerException ( ) ; } this . value += delta ; } public void add ( DoubleOption other ) { if ( nullValue ) { throw new NullPointerException ( ) ; } if ( other . nullValue ) { return ; } this . value += other . value ; } @ Deprecated public DoubleOption modify ( double newValue ) { this . nullValue = false ; this . value = newValue ; return this ; } @ Override @ Deprecated public void copyFrom ( DoubleOption optionOrNull ) { if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { this . nullValue = false ; this . value = optionOrNull . value ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; long bits = Double . doubleToLongBits ( result ) ; result = prime * result + ( int ) ( bits ^ ( bits > > > ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DoubleOption other = ( DoubleOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && Double . doubleToLongBits ( value ) != Double . doubleToLongBits ( other . value ) ) { return false ; } return true ; } public boolean has ( double other ) { if ( isNull ( ) ) { return false ; } return Double . doubleToLongBits ( value ) != Double . doubleToLongBits ( other ) ; } @ Override public int compareTo ( WritableRawComparable o ) { DoubleOption other = ( DoubleOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } long left = encode ( value ) - Long . MIN_VALUE ; long right = encode ( other . value ) - Long . MIN_VALUE ; if ( left == right ) { return ; } if ( left < right ) { return - ; } return + ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return String . valueOf ( value ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; out . writeLong ( encode ( value ) ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { modify ( decode ( in . readLong ( ) ) ) ; } else { setNull ( ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset + ] == ) { setNull ( ) ; return ; } else if ( limit - offset >= + ) { modify ( decode ( ByteArrayUtil . readLong ( bytes , offset + ) ) ) ; return + ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return bytes [ offset ] == ? : ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { int len1 = getBytesLength ( b1 , s1 , l1 ) ; int len2 = getBytesLength ( b2 , s2 , l2 ) ; return WritableComparator . compareBytes ( b1 , s1 , len1 , b2 , s2 , len2 ) ; } private static long encode ( double decoded ) { long bits = Double . doubleToLongBits ( decoded ) ; bits ^= Long . MIN_VALUE | ( bits > > Long . SIZE - ) ; return bits ; } private static double decode ( long encoded ) { long bits = encoded ; bits ^= Long . MIN_VALUE | ~ ( bits > > Long . SIZE - ) ; return Double . longBitsToDouble ( bits ) ; } } package com . asakusafw . runtime . value ; import java . text . MessageFormat ; public class Date implements Comparable < Date > { public static final String FORMAT = "" ; private int elapsed = ; public Date ( ) { this ( ) ; } public Date ( int year , int month , int day ) { this ( DateUtil . getDayFromDate ( year , month , day ) ) ; } public Date ( int elapsedDays ) { this . elapsed = elapsedDays ; } public int getElapsedDays ( ) { return elapsed ; } public void setElapsedDays ( int days ) { this . elapsed = days ; } public int getYear ( ) { return DateUtil . getYearFromDay ( elapsed ) ; } public int getMonth ( ) { int year = getYear ( ) ; int dayInYear = elapsed - DateUtil . getDayFromYear ( year ) ; return DateUtil . getMonthOfYear ( dayInYear , DateUtil . isLeap ( year ) ) ; } public int getDay ( ) { int year = getYear ( ) ; int dayInYear = elapsed - DateUtil . getDayFromYear ( year ) ; return DateUtil . getDayOfMonth ( dayInYear , DateUtil . isLeap ( year ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + elapsed ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Date other = ( Date ) obj ; if ( elapsed != other . elapsed ) { return false ; } return true ; } @ Override public int compareTo ( Date o ) { int a = elapsed ; int b = o . elapsed ; if ( a == b ) { return ; } if ( a < b ) { return - ; } return + ; } @ Override public String toString ( ) { return String . format ( "" , getYear ( ) , getMonth ( ) , getDay ( ) ) ; } public static Date valueOf ( StringOption dateString , Date . Format format ) { if ( dateString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dateString . isNull ( ) ) { return null ; } return valueOf ( dateString . getAsString ( ) , format ) ; } public static Date valueOf ( String dateString , Date . Format format ) { if ( dateString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } Date date = new Date ( ) ; date . setElapsedDays ( format . parse ( dateString ) ) ; return date ; } public enum Format { SIMPLE { @ Override public int parse ( String dateString ) { if ( dateString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dateString . length ( ) != ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , dateString , "" ) ) ; } int year = get ( dateString , , ) ; int month = get ( dateString , , ) ; int day = get ( dateString , , ) ; return DateUtil . getDayFromDate ( year , month , day ) ; } } , ; public abstract int parse ( String dateString ) ; static int get ( String string , int from , int to ) { return Integer . parseInt ( string . substring ( from , to ) ) ; } } } package com . asakusafw . runtime . value ; import java . text . MessageFormat ; public class DateTime implements Comparable < DateTime > { public static final String FORMAT = "" ; private long elapsedSeconds = ; public DateTime ( ) { this ( ) ; } public DateTime ( long elapsedSeconds ) { this . elapsedSeconds = elapsedSeconds ; } public DateTime ( int year , int month , int day , int hour , int minute , int second ) { int date = DateUtil . getDayFromDate ( year , month , day ) ; int secondsInDay = DateUtil . getSecondFromTime ( hour , minute , second ) ; this . elapsedSeconds = ( long ) date * + secondsInDay ; } public long getElapsedSeconds ( ) { return elapsedSeconds ; } public void setElapsedSeconds ( long elapsed ) { this . elapsedSeconds = elapsed ; } public int getYear ( ) { int days = DateUtil . getDayFromSeconds ( elapsedSeconds ) ; return DateUtil . getYearFromDay ( days ) ; } public int getMonth ( ) { int days = DateUtil . getDayFromSeconds ( elapsedSeconds ) ; int year = getYear ( ) ; int dayInYear = days - DateUtil . getDayFromYear ( year ) ; return DateUtil . getMonthOfYear ( dayInYear , DateUtil . isLeap ( year ) ) ; } public int getDay ( ) { int year = getYear ( ) ; int days = DateUtil . getDayFromSeconds ( elapsedSeconds ) ; int dayInYear = days - DateUtil . getDayFromYear ( year ) ; return DateUtil . getDayOfMonth ( dayInYear , DateUtil . isLeap ( year ) ) ; } public int getHour ( ) { int sec = DateUtil . getSecondOfDay ( elapsedSeconds ) ; return sec / ( * ) ; } public int getMinute ( ) { int sec = DateUtil . getSecondOfDay ( elapsedSeconds ) ; return sec / % ; } public int getSecond ( ) { int sec = DateUtil . getSecondOfDay ( elapsedSeconds ) ; return sec % ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( int ) ( elapsedSeconds ^ ( elapsedSeconds > > > ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DateTime other = ( DateTime ) obj ; if ( elapsedSeconds != other . elapsedSeconds ) { return false ; } return true ; } @ Override public int compareTo ( DateTime o ) { long a = elapsedSeconds ; long b = o . elapsedSeconds ; if ( a == b ) { return ; } if ( a < b ) { return - ; } return + ; } @ Override public String toString ( ) { return String . format ( "" , getYear ( ) , getMonth ( ) , getDay ( ) , getHour ( ) , getMinute ( ) , getSecond ( ) ) ; } public static DateTime valueOf ( StringOption timeString , DateTime . Format format ) { if ( timeString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } if ( timeString . isNull ( ) ) { return null ; } return valueOf ( timeString . getAsString ( ) , format ) ; } public static DateTime valueOf ( String timeString , DateTime . Format format ) { if ( timeString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } DateTime time = new DateTime ( ) ; time . setElapsedSeconds ( format . parse ( timeString ) ) ; return time ; } public enum Format { SIMPLE { @ Override public long parse ( String timeString ) { if ( timeString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( timeString . length ( ) != ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , timeString , "" ) ) ; } int year = get ( timeString , , ) ; int month = get ( timeString , , ) ; int day = get ( timeString , , ) ; int hour = get ( timeString , , ) ; int minute = get ( timeString , , ) ; int second = get ( timeString , , ) ; int date = DateUtil . getDayFromDate ( year , month , day ) ; long seconds = ( long ) date * + DateUtil . getSecondFromTime ( hour , minute , second ) ; return seconds ; } } , ; public abstract long parse ( String timeString ) ; static int get ( String string , int from , int to ) { return Integer . parseInt ( string . substring ( from , to ) ) ; } } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . io . WritableComparator ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class LongOption extends ValueOption < LongOption > { private long value ; public LongOption ( ) { super ( ) ; } public LongOption ( long value ) { super ( ) ; this . value = value ; this . nullValue = false ; } public long get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return value ; } public long or ( long alternate ) { if ( nullValue ) { return alternate ; } return value ; } public void add ( long delta ) { if ( nullValue ) { throw new NullPointerException ( ) ; } this . value += delta ; } public void add ( LongOption other ) { if ( nullValue ) { throw new NullPointerException ( ) ; } if ( other . nullValue ) { return ; } this . value += other . value ; } @ Deprecated public LongOption modify ( long newValue ) { this . nullValue = false ; this . value = newValue ; return this ; } @ Override @ Deprecated public void copyFrom ( LongOption optionOrNull ) { if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { this . nullValue = false ; this . value = optionOrNull . value ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + ( int ) ( value ^ ( value > > > ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } LongOption other = ( LongOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && value != other . value ) { return false ; } return true ; } public boolean has ( long other ) { if ( isNull ( ) ) { return false ; } return value == other ; } @ Override public int compareTo ( WritableRawComparable o ) { LongOption other = ( LongOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } if ( value == other . value ) { return ; } if ( value < other . value ) { return - ; } return + ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return String . valueOf ( value ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; out . writeLong ( value - Long . MIN_VALUE ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { modify ( in . readLong ( ) + Long . MIN_VALUE ) ; } else { setNull ( ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset + ] == ) { setNull ( ) ; return ; } else if ( limit - offset >= + ) { modify ( ByteArrayUtil . readLong ( bytes , offset + ) + Long . MIN_VALUE ) ; return + ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return bytes [ offset ] == ? : ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { int len1 = getBytesLength ( b1 , s1 , l1 ) ; int len2 = getBytesLength ( b2 , s2 , l2 ) ; return WritableComparator . compareBytes ( b1 , s1 , len1 , b2 , s2 , len2 ) ; } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class BooleanOption extends ValueOption < BooleanOption > { private static final int TRUE_HASHCODE = ; private static final int FALSE_HASHCODE = ; private boolean value ; public BooleanOption ( ) { super ( ) ; } public BooleanOption ( boolean value ) { super ( ) ; this . value = value ; this . nullValue = false ; } public boolean get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return value ; } public boolean or ( boolean alternate ) { if ( nullValue ) { return alternate ; } return value ; } @ Deprecated public BooleanOption modify ( boolean newValue ) { this . nullValue = false ; this . value = newValue ; return this ; } @ Override @ Deprecated public void copyFrom ( BooleanOption optionOrNull ) { if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { this . nullValue = false ; this . value = optionOrNull . value ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + ( value ? TRUE_HASHCODE : FALSE_HASHCODE ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } BooleanOption other = ( BooleanOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && value != other . value ) { return false ; } return true ; } public boolean has ( boolean other ) { if ( isNull ( ) ) { return false ; } return value == other ; } @ Override public int compareTo ( WritableRawComparable o ) { BooleanOption other = ( BooleanOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } if ( value ^ other . value ) { return value ? : - ; } return ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return String . valueOf ( value ) ; } } private static final int SERIALIZE_NULL = - ; private static final int SERIALIZE_TRUE = + ; private static final int SERIALIZE_FALSE = ; @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeByte ( SERIALIZE_NULL ) ; } else { out . writeByte ( value ? SERIALIZE_TRUE : SERIALIZE_FALSE ) ; } } @ Override public void readFields ( DataInput in ) throws IOException { byte field = in . readByte ( ) ; restore ( field ) ; } @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset < ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } restore ( bytes [ offset ] ) ; return ; } @ SuppressWarnings ( "" ) private void restore ( byte field ) throws IOException { if ( field == SERIALIZE_NULL ) { setNull ( ) ; } else if ( field == SERIALIZE_TRUE ) { modify ( true ) ; } else if ( field == SERIALIZE_FALSE ) { modify ( false ) ; } else { throw new IOException ( MessageFormat . format ( "" , field ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { return ByteArrayUtil . compare ( b1 [ s1 ] , b2 [ s2 ] ) ; } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . WritableComparator ; import org . apache . hadoop . io . WritableUtils ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class StringOption extends ValueOption < StringOption > { private static final ThreadLocal < Text > BUFFER_POOL = new ThreadLocal < Text > ( ) { @ Override protected Text initialValue ( ) { return new Text ( ) ; } } ; private final Text entity = new Text ( ) ; public StringOption ( ) { this . nullValue = true ; } public StringOption ( String textOrNull ) { if ( textOrNull == null ) { this . nullValue = true ; } else { entity . set ( textOrNull ) ; this . nullValue = false ; } } public Text get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return entity ; } public String getAsString ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return entity . toString ( ) ; } public Text or ( Text alternate ) { if ( nullValue ) { return alternate ; } return get ( ) ; } public String or ( String alternate ) { if ( nullValue ) { return alternate ; } return getAsString ( ) ; } public void reset ( ) { nullValue = false ; entity . clear ( ) ; } @ Deprecated public StringOption modify ( Text newText ) { if ( newText == null ) { this . nullValue = true ; } else { this . nullValue = false ; entity . set ( newText ) ; } return this ; } @ Deprecated public StringOption modify ( String newText ) { if ( newText == null ) { this . nullValue = true ; } else { this . nullValue = false ; entity . set ( newText ) ; } return this ; } @ Override @ Deprecated public void copyFrom ( StringOption optionOrNull ) { if ( this == optionOrNull ) { return ; } else if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { modify ( optionOrNull . entity ) ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + entity . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } StringOption other = ( StringOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && entity . equals ( other . entity ) == false ) { return false ; } return true ; } public boolean has ( String other ) { if ( isNull ( ) ) { return other == null ; } if ( other == null ) { return false ; } Text buffer = BUFFER_POOL . get ( ) ; buffer . set ( other ) ; return entity . equals ( buffer ) ; } public boolean has ( Text other ) { if ( isNull ( ) ) { return other == null ; } if ( other == null ) { return false ; } return entity . equals ( other ) ; } @ Override public int compareTo ( WritableRawComparable o ) { StringOption other = ( StringOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } return entity . compareTo ( other . entity ) ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return getAsString ( ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; entity . write ( out ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) == false ) { setNull ( ) ; } else { nullValue = false ; entity . readFields ( in ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset ] == ) { setNull ( ) ; return ; } int size = WritableUtils . decodeVIntSize ( bytes [ offset + ] ) ; if ( limit - offset < size + ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } int length = ( int ) ByteArrayUtil . readVLong ( bytes , offset + ) ; if ( limit - offset >= size + + length ) { nullValue = false ; entity . set ( bytes , offset + size + , length ) ; return size + + length ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { if ( bytes [ offset ] == ) { return ; } int size = WritableUtils . decodeVIntSize ( bytes [ offset + ] ) ; int textLength = ( int ) ByteArrayUtil . readVLong ( bytes , offset + ) ; return + size + textLength ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { if ( b1 [ s1 ] == || b2 [ s2 ] == ) { return ByteArrayUtil . compare ( b1 [ s1 ] , b2 [ s2 ] ) ; } int n1 = WritableUtils . decodeVIntSize ( b1 [ s1 + ] ) ; int n2 = WritableUtils . decodeVIntSize ( b2 [ s2 + ] ) ; int len1 = ( int ) ByteArrayUtil . readVLong ( b1 , s1 + ) ; int len2 = ( int ) ByteArrayUtil . readVLong ( b2 , s2 + ) ; return WritableComparator . compareBytes ( b1 , s1 + + n1 , len1 , b2 , s2 + + n2 , len2 ) ; } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . io . WritableComparator ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class FloatOption extends ValueOption < FloatOption > { private float value ; public FloatOption ( ) { super ( ) ; } public FloatOption ( float value ) { super ( ) ; this . value = value ; this . nullValue = false ; } public float get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return value ; } public float or ( float alternate ) { if ( nullValue ) { return alternate ; } return value ; } public void add ( float delta ) { if ( nullValue ) { throw new NullPointerException ( ) ; } this . value += delta ; } public void add ( FloatOption other ) { if ( nullValue ) { throw new NullPointerException ( ) ; } if ( other . nullValue ) { return ; } this . value += other . value ; } @ Deprecated public FloatOption modify ( float newValue ) { this . nullValue = false ; this . value = newValue ; return this ; } @ Override @ Deprecated public void copyFrom ( FloatOption optionOrNull ) { if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { this . nullValue = false ; this . value = optionOrNull . value ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + Float . floatToIntBits ( result ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } FloatOption other = ( FloatOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && Float . floatToIntBits ( value ) != Float . floatToIntBits ( other . value ) ) { return false ; } return true ; } public boolean has ( float other ) { if ( isNull ( ) ) { return false ; } return Float . floatToIntBits ( value ) == Float . floatToIntBits ( other ) ; } @ Override public int compareTo ( WritableRawComparable o ) { FloatOption other = ( FloatOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } int left = encode ( value ) - Integer . MIN_VALUE ; int right = encode ( other . value ) - Integer . MIN_VALUE ; if ( left == right ) { return ; } if ( left < right ) { return - ; } return + ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return String . valueOf ( value ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; out . writeInt ( encode ( value ) ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { modify ( decode ( in . readInt ( ) ) ) ; } else { setNull ( ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset + ] == ) { setNull ( ) ; return ; } else if ( limit - offset >= + ) { modify ( decode ( ByteArrayUtil . readInt ( bytes , offset + ) ) ) ; return + ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return bytes [ offset ] == ? : ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { int len1 = getBytesLength ( b1 , s1 , l1 ) ; int len2 = getBytesLength ( b2 , s2 , l2 ) ; return WritableComparator . compareBytes ( b1 , s1 , len1 , b2 , s2 , len2 ) ; } private static int encode ( float decoded ) { int bits = Float . floatToIntBits ( decoded ) ; bits ^= Integer . MIN_VALUE | ( bits > > Integer . SIZE - ) ; return bits ; } private static float decode ( int encoded ) { int bits = encoded ; bits ^= Integer . MIN_VALUE | ~ ( bits > > Integer . SIZE - ) ; return Float . intBitsToFloat ( bits ) ; } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . io . WritableComparator ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class IntOption extends ValueOption < IntOption > { private int value ; public IntOption ( ) { this . nullValue = true ; } public IntOption ( int value ) { this . nullValue = false ; this . value = value ; } public int get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return value ; } public int or ( int alternate ) { if ( nullValue ) { return alternate ; } return value ; } public void add ( int delta ) { if ( nullValue ) { throw new NullPointerException ( ) ; } this . value += delta ; } public void add ( IntOption other ) { if ( nullValue ) { throw new NullPointerException ( ) ; } if ( other . nullValue ) { return ; } this . value += other . value ; } @ Deprecated public IntOption modify ( int newValue ) { this . nullValue = false ; this . value = newValue ; return this ; } @ Override @ Deprecated public void copyFrom ( IntOption optionOrNull ) { if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { this . nullValue = false ; this . value = optionOrNull . value ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + value ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } IntOption other = ( IntOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && value != other . value ) { return false ; } return true ; } public boolean has ( int other ) { if ( isNull ( ) ) { return false ; } return value == other ; } @ Override public int compareTo ( WritableRawComparable o ) { IntOption other = ( IntOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } if ( value == other . value ) { return ; } if ( value < other . value ) { return - ; } return + ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return String . valueOf ( value ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; out . writeInt ( value - Integer . MIN_VALUE ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { modify ( in . readInt ( ) + Integer . MIN_VALUE ) ; } else { setNull ( ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset + ] == ) { setNull ( ) ; return ; } else if ( limit - offset >= + ) { modify ( ByteArrayUtil . readInt ( bytes , offset + ) + Integer . MIN_VALUE ) ; return + ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return bytes [ offset ] == ? : ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { int len1 = getBytesLength ( b1 , s1 , l1 ) ; int len2 = getBytesLength ( b2 , s2 , l2 ) ; return WritableComparator . compareBytes ( b1 , s1 , len1 , b2 , s2 , len2 ) ; } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class ShortOption extends ValueOption < ShortOption > { private short value ; public ShortOption ( ) { super ( ) ; } public ShortOption ( short value ) { super ( ) ; this . value = value ; this . nullValue = false ; } public short get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return value ; } public short or ( short alternate ) { if ( nullValue ) { return alternate ; } return value ; } @ Deprecated public ShortOption modify ( short newValue ) { this . nullValue = false ; this . value = newValue ; return this ; } @ Override @ Deprecated public void copyFrom ( ShortOption optionOrNull ) { if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { this . nullValue = false ; this . value = optionOrNull . value ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + value ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ShortOption other = ( ShortOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && value != other . value ) { return false ; } return true ; } public boolean has ( int other ) { if ( isNull ( ) ) { return false ; } return value == other ; } @ Override public int compareTo ( WritableRawComparable o ) { ShortOption other = ( ShortOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } if ( value == other . value ) { return ; } if ( value < other . value ) { return - ; } return + ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return String . valueOf ( value ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; out . writeShort ( value ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { modify ( in . readShort ( ) ) ; } else { setNull ( ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset + ] == ) { setNull ( ) ; return ; } else if ( limit - offset >= + ) { modify ( ByteArrayUtil . readShort ( bytes , offset + ) ) ; return + ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return bytes [ offset ] == ? : ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { if ( b1 [ s1 ] == || b2 [ s2 ] == ) { return ByteArrayUtil . compare ( b1 [ s1 ] , b2 [ s2 ] ) ; } return ByteArrayUtil . compare ( ByteArrayUtil . readShort ( b1 , s1 + ) , ByteArrayUtil . readShort ( b2 , s2 + ) ) ; } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class ByteOption extends ValueOption < ByteOption > { private byte value ; public ByteOption ( ) { super ( ) ; } public ByteOption ( byte value ) { super ( ) ; this . value = value ; this . nullValue = false ; } public byte get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return value ; } public byte or ( byte alternate ) { if ( nullValue ) { return alternate ; } return value ; } @ Deprecated public ByteOption modify ( byte newValue ) { this . nullValue = false ; this . value = newValue ; return this ; } @ Override @ Deprecated public void copyFrom ( ByteOption optionOrNull ) { if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { this . nullValue = false ; this . value = optionOrNull . value ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + value ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ByteOption other = ( ByteOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && value != other . value ) { return false ; } return true ; } @ Override public int compareTo ( WritableRawComparable o ) { ByteOption other = ( ByteOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } if ( value == other . value ) { return ; } if ( value < other . value ) { return - ; } return + ; } public boolean has ( int other ) { if ( isNull ( ) ) { return false ; } return value == other ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return String . valueOf ( value ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; out . writeByte ( value ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { modify ( in . readByte ( ) ) ; } else { setNull ( ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset + ] == ) { setNull ( ) ; return ; } else if ( limit - offset >= + ) { modify ( bytes [ offset + ] ) ; return ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return bytes [ offset ] == ? : ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { if ( b1 [ s1 ] == || b2 [ s2 ] == ) { return ByteArrayUtil . compare ( b1 [ s1 ] , b2 [ s2 ] ) ; } return ByteArrayUtil . compare ( b1 [ s1 + ] , b2 [ s2 + ] ) ; } } package com . asakusafw . runtime . value ; import java . io . IOException ; import org . apache . hadoop . io . WritableComparator ; final class ByteArrayUtil { static int compare ( int a , int b ) { if ( a == b ) { return ; } if ( a < b ) { return - ; } return + ; } static int compare ( long a , long b ) { if ( a == b ) { return ; } if ( a < b ) { return - ; } return + ; } static short readShort ( byte [ ] bytes , int offset ) { return ( short ) WritableComparator . readUnsignedShort ( bytes , offset ) ; } static int readInt ( byte [ ] bytes , int offset ) { return WritableComparator . readInt ( bytes , offset ) ; } static long readLong ( byte [ ] bytes , int offset ) { return WritableComparator . readLong ( bytes , offset ) ; } static long readVLong ( byte [ ] bytes , int offset ) { try { return WritableComparator . readVLong ( bytes , offset ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( e ) ; } } private ByteArrayUtil ( ) { return ; } } package com . asakusafw . runtime . value ; import java . io . IOException ; public interface Restorable { int restore ( byte [ ] bytes , int offset , int limit ) throws IOException ; } package com . asakusafw . runtime . value ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public abstract class ValueOption < V extends ValueOption < V > > implements WritableRawComparable , Restorable { protected boolean nullValue = true ; public final boolean isNull ( ) { return nullValue ; } @ Deprecated public final ValueOption < V > setNull ( ) { this . nullValue = true ; return this ; } @ Deprecated public abstract void copyFrom ( V otherOrNull ) ; @ SuppressWarnings ( "" ) public final void min ( V other ) { if ( this == other ) { return ; } if ( this . isNull ( ) || other . isNull ( ) ) { setNull ( ) ; } else if ( compareTo ( other ) > ) { copyFrom ( other ) ; } } @ SuppressWarnings ( "" ) public final void max ( V other ) { if ( this == other ) { return ; } if ( this . isNull ( ) || other . isNull ( ) ) { setNull ( ) ; } else if ( compareTo ( other ) < ) { copyFrom ( other ) ; } } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . math . MathContext ; import java . util . Arrays ; import org . apache . hadoop . io . WritableComparator ; import org . apache . hadoop . io . WritableUtils ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class DecimalOption extends ValueOption < DecimalOption > { private BigDecimal entity = BigDecimal . ZERO ; public DecimalOption ( ) { super ( ) ; } public DecimalOption ( BigDecimal valueOrNull ) { super ( ) ; if ( valueOrNull != null ) { this . entity = valueOrNull ; this . nullValue = false ; } } public BigDecimal get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return entity ; } public BigDecimal or ( BigDecimal alternate ) { if ( nullValue ) { return alternate ; } return get ( ) ; } public void add ( BigDecimal delta ) { if ( nullValue ) { throw new NullPointerException ( ) ; } this . entity = entity . add ( delta ) ; } public void add ( DecimalOption other ) { if ( nullValue ) { throw new NullPointerException ( ) ; } if ( other . nullValue ) { return ; } this . entity = entity . add ( other . entity ) ; } @ Deprecated public DecimalOption modify ( BigDecimal newValue ) { if ( newValue == null ) { this . nullValue = true ; } else { this . nullValue = false ; this . entity = newValue ; } return this ; } @ Override @ Deprecated public void copyFrom ( DecimalOption optionOrNull ) { if ( this == optionOrNull ) { return ; } else if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { modify ( optionOrNull . entity ) ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + entity . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DecimalOption other = ( DecimalOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && entity . equals ( other . entity ) == false ) { return false ; } return true ; } public boolean has ( BigDecimal other ) { if ( isNull ( ) ) { return other == null ; } return entity . equals ( other ) ; } @ Override public int compareTo ( WritableRawComparable o ) { DecimalOption other = ( DecimalOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } return entity . compareTo ( other . entity ) ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return get ( ) . toString ( ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( nullValue ) { WritableUtils . writeVLong ( out , - ) ; } else { BigDecimal decimal = entity ; WritableUtils . writeVInt ( out , decimal . precision ( ) ) ; WritableUtils . writeVInt ( out , decimal . scale ( ) ) ; BigInteger unscaled = decimal . unscaledValue ( ) ; byte [ ] bytes = unscaled . toByteArray ( ) ; WritableUtils . writeVInt ( out , bytes . length ) ; out . write ( bytes ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { int precision = WritableUtils . readVInt ( in ) ; if ( precision == - ) { setNull ( ) ; } else { int scale = WritableUtils . readVInt ( in ) ; int byteCount = WritableUtils . readVInt ( in ) ; byte [ ] bytes = new byte [ byteCount ] ; in . readFully ( bytes ) ; modify ( new BigDecimal ( new BigInteger ( bytes ) , scale , new MathContext ( precision ) ) ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { int cursor = offset ; int precision = WritableComparator . readVInt ( bytes , cursor ) ; cursor += WritableUtils . decodeVIntSize ( bytes [ cursor ] ) ; if ( precision < ) { setNull ( ) ; } else { int scale = WritableComparator . readVInt ( bytes , cursor ) ; cursor += WritableUtils . decodeVIntSize ( bytes [ cursor ] ) ; int bytesCount = WritableComparator . readVInt ( bytes , cursor ) ; cursor += WritableUtils . decodeVIntSize ( bytes [ cursor ] ) ; byte [ ] unscaled = Arrays . copyOfRange ( bytes , cursor , cursor + bytesCount ) ; cursor += bytesCount ; modify ( new BigDecimal ( new BigInteger ( unscaled ) , scale , new MathContext ( precision ) ) ) ; } return cursor - offset ; } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { try { int cursor = offset ; int precSize = WritableUtils . decodeVIntSize ( bytes [ cursor ] ) ; if ( WritableComparator . readVInt ( bytes , offset ) < ) { return precSize ; } cursor += precSize ; cursor += WritableUtils . decodeVIntSize ( bytes [ cursor ] ) ; int bytesCount = WritableComparator . readVInt ( bytes , cursor ) ; cursor += WritableUtils . decodeVIntSize ( bytes [ cursor ] ) ; cursor += bytesCount ; return cursor - offset ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { try { int cursor1 = s1 ; int cursor2 = s2 ; int prec1 = WritableComparator . readVInt ( b1 , cursor1 ) ; int prec2 = WritableComparator . readVInt ( b2 , cursor2 ) ; if ( prec1 < ) { if ( prec2 < ) { return ; } return - ; } else if ( prec2 < ) { return + ; } cursor1 += WritableUtils . decodeVIntSize ( b1 [ cursor1 ] ) ; cursor2 += WritableUtils . decodeVIntSize ( b2 [ cursor2 ] ) ; int scale1 = WritableComparator . readVInt ( b1 , cursor1 ) ; int scale2 = WritableComparator . readVInt ( b2 , cursor2 ) ; cursor1 += WritableUtils . decodeVIntSize ( b1 [ cursor1 ] ) ; cursor2 += WritableUtils . decodeVIntSize ( b2 [ cursor2 ] ) ; int bytesCount1 = WritableComparator . readVInt ( b1 , cursor1 ) ; int bytesCount2 = WritableComparator . readVInt ( b2 , cursor2 ) ; cursor1 += WritableUtils . decodeVIntSize ( b1 [ cursor1 ] ) ; cursor2 += WritableUtils . decodeVIntSize ( b2 [ cursor2 ] ) ; if ( b1 [ cursor1 ] < && b2 [ cursor2 ] >= ) { return - ; } else if ( b1 [ cursor1 ] >= && b2 [ cursor2 ] < ) { return + ; } BigInteger unscale1 = new BigInteger ( Arrays . copyOfRange ( b1 , cursor1 , cursor1 + bytesCount1 ) ) ; BigInteger unscale2 = new BigInteger ( Arrays . copyOfRange ( b2 , cursor2 , cursor2 + bytesCount2 ) ) ; if ( scale1 > scale2 ) { unscale2 = unscale2 . multiply ( BigInteger . TEN . pow ( scale1 - scale2 ) ) ; } else if ( scale1 < scale2 ) { unscale1 = unscale1 . multiply ( BigInteger . TEN . pow ( scale2 - scale1 ) ) ; } return unscale1 . compareTo ( unscale2 ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } } package com . asakusafw . runtime . value ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . runtime . io . util . WritableRawComparable ; public final class DateTimeOption extends ValueOption < DateTimeOption > { private final DateTime entity = new DateTime ( ) ; public DateTimeOption ( ) { super ( ) ; } public DateTimeOption ( DateTime valueOrNull ) { super ( ) ; if ( valueOrNull != null ) { this . entity . setElapsedSeconds ( valueOrNull . getElapsedSeconds ( ) ) ; this . nullValue = false ; } } public DateTime get ( ) { if ( nullValue ) { throw new NullPointerException ( ) ; } return entity ; } public DateTime or ( DateTime alternate ) { if ( nullValue ) { return alternate ; } return get ( ) ; } public long or ( long alternate ) { if ( nullValue ) { return alternate ; } return get ( ) . getElapsedSeconds ( ) ; } @ Deprecated public DateTimeOption modify ( DateTime newValue ) { if ( newValue == null ) { this . nullValue = true ; } else { this . nullValue = false ; this . entity . setElapsedSeconds ( newValue . getElapsedSeconds ( ) ) ; } return this ; } @ Deprecated public DateTimeOption modify ( long newValue ) { this . nullValue = false ; this . entity . setElapsedSeconds ( newValue ) ; return this ; } @ Override @ Deprecated public void copyFrom ( DateTimeOption optionOrNull ) { if ( this == optionOrNull ) { return ; } else if ( optionOrNull == null || optionOrNull . nullValue ) { this . nullValue = true ; } else { modify ( optionOrNull . entity ) ; } } @ Override public int hashCode ( ) { final int prime = ; if ( isNull ( ) ) { return ; } int result = ; result = prime * result + entity . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DateTimeOption other = ( DateTimeOption ) obj ; if ( nullValue != other . nullValue ) { return false ; } if ( nullValue == false && entity . equals ( other . entity ) == false ) { return false ; } return true ; } public boolean has ( DateTime other ) { if ( isNull ( ) ) { return other == null ; } return entity . equals ( other ) ; } @ Override public int compareTo ( WritableRawComparable o ) { DateTimeOption other = ( DateTimeOption ) o ; if ( nullValue | other . nullValue ) { if ( nullValue & other . nullValue ) { return ; } return nullValue ? - : + ; } return entity . compareTo ( other . entity ) ; } @ Override public String toString ( ) { if ( isNull ( ) ) { return String . valueOf ( ( Object ) null ) ; } else { return get ( ) . toString ( ) ; } } @ Override public void write ( DataOutput out ) throws IOException { if ( isNull ( ) ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; out . writeLong ( entity . getElapsedSeconds ( ) ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { modify ( in . readLong ( ) ) ; } else { setNull ( ) ; } } @ SuppressWarnings ( "" ) @ Override public int restore ( byte [ ] bytes , int offset , int limit ) throws IOException { if ( limit - offset == ) { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } if ( bytes [ offset + ] == ) { setNull ( ) ; return ; } else if ( limit - offset >= + ) { modify ( ByteArrayUtil . readLong ( bytes , offset + ) ) ; return + ; } else { throw new IOException ( MessageFormat . format ( "" , "" ) ) ; } } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return getBytesLength ( buf , offset , buf . length - offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return compareBytes ( b1 , o1 , b1 . length - o1 , b2 , o2 , b2 . length - o2 ) ; } public static int getBytesLength ( byte [ ] bytes , int offset , int length ) { return bytes [ offset ] == ? : ; } public static int compareBytes ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { if ( b1 [ s1 ] == || b2 [ s2 ] == ) { return ByteArrayUtil . compare ( b1 [ s1 ] , b2 [ s2 ] ) ; } return ByteArrayUtil . compare ( ByteArrayUtil . readLong ( b1 , s1 + ) , ByteArrayUtil . readLong ( b2 , s2 + ) ) ; } } package com . asakusafw . runtime . io ; import java . io . Closeable ; import java . io . IOException ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . runtime . value . ValueOption ; public interface RecordParser extends Closeable { boolean next ( ) throws RecordFormatException , IOException ; void fill ( BooleanOption option ) throws RecordFormatException , IOException ; void fill ( ByteOption option ) throws RecordFormatException , IOException ; void fill ( ShortOption option ) throws RecordFormatException , IOException ; void fill ( IntOption option ) throws RecordFormatException , IOException ; void fill ( LongOption option ) throws RecordFormatException , IOException ; void fill ( FloatOption option ) throws RecordFormatException , IOException ; void fill ( DoubleOption option ) throws RecordFormatException , IOException ; void fill ( DecimalOption option ) throws RecordFormatException , IOException ; void fill ( StringOption option ) throws RecordFormatException , IOException ; void fill ( DateOption option ) throws RecordFormatException , IOException ; void fill ( DateTimeOption option ) throws RecordFormatException , IOException ; void endRecord ( ) throws RecordFormatException , IOException ; } package com . asakusafw . runtime . io ; import java . io . IOException ; public class RecordFormatException extends IOException { private static final long serialVersionUID = ; public RecordFormatException ( String message ) { super ( message ) ; } public RecordFormatException ( String message , Throwable cause ) { super ( message , cause ) ; } } package com . asakusafw . runtime . io . sequencefile ; import java . io . Closeable ; import java . io . IOException ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . SequenceFile ; import com . asakusafw . runtime . io . ModelOutput ; public class SequenceFileModelOutput < T > implements ModelOutput < T > { private final SequenceFile . Writer writer ; private Closeable closeable ; public SequenceFileModelOutput ( SequenceFile . Writer writer ) { this ( writer , writer ) ; } public SequenceFileModelOutput ( SequenceFile . Writer writer , Closeable closeable ) { if ( writer == null ) { throw new IllegalArgumentException ( "" ) ; } if ( closeable == null ) { throw new IllegalArgumentException ( "" ) ; } this . writer = writer ; this . closeable = closeable ; } @ Override public void write ( T model ) throws IOException { writer . append ( NullWritable . get ( ) , model ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; closeable . close ( ) ; } } package com . asakusafw . runtime . io . sequencefile ; package com . asakusafw . runtime . io . sequencefile ; import java . io . BufferedInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FilterFileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . fs . PositionedReadable ; import org . apache . hadoop . fs . Seekable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . SequenceFile . CompressionType ; import org . apache . hadoop . io . compress . CompressionCodec ; public final class SequenceFileUtil { static final Log LOG = LogFactory . getLog ( SequenceFileUtil . class ) ; public static SequenceFile . Reader openReader ( InputStream in , FileStatus status , Configuration conf ) throws IOException { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } if ( status == null ) { throw new IllegalArgumentException ( "" ) ; } if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , status . getPath ( ) ) ) ; } return new SequenceFile . Reader ( new InputStreamFileSystem ( status , in ) , status . getPath ( ) , conf ) ; } public static SequenceFile . Reader openReader ( InputStream in , long length , Configuration conf ) throws IOException { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } FileStatus status = new FileStatus ( length , false , , length , , new Path ( "" ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , status . getPath ( ) ) ) ; } return new SequenceFile . Reader ( new InputStreamFileSystem ( status , in ) , status . getPath ( ) , conf ) ; } public static SequenceFile . Writer openWriter ( OutputStream out , Configuration conf , Class < ? > keyClass , Class < ? > valueClass , CompressionCodec codec ) throws IOException { if ( out == null ) { throw new IllegalArgumentException ( "" ) ; } if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( keyClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( valueClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , keyClass . getName ( ) , valueClass . getName ( ) ) ) ; } FSDataOutputStream output = new FSDataOutputStream ( out , null ) ; if ( codec != null ) { return SequenceFile . createWriter ( conf , output , keyClass , valueClass , CompressionType . BLOCK , codec ) ; } else { return SequenceFile . createWriter ( conf , output , keyClass , valueClass , CompressionType . NONE , null ) ; } } private SequenceFileUtil ( ) { return ; } private static class InputStreamFileSystem extends FilterFileSystem { private final FileStatus status ; private final InputStream input ; InputStreamFileSystem ( FileStatus status , InputStream input ) { assert status != null ; assert input != null ; this . status = status ; this . input = input ; } @ Override public FSDataInputStream open ( Path f ) throws IOException { return open ( f , ) ; } @ Override public FSDataInputStream open ( Path f , int bufferSize ) throws IOException { return new FSDataInputStream ( new WrappedInputStream ( new BufferedInputStream ( input , bufferSize ) ) ) ; } @ Override public FileStatus getFileStatus ( Path f ) throws IOException { return status ; } } private static class WrappedInputStream extends InputStream implements Seekable , PositionedReadable { private final InputStream input ; private long current ; WrappedInputStream ( InputStream input ) { assert input != null ; this . input = input ; this . current = ; } @ Override public int read ( long position , byte [ ] buffer , int offset , int length ) throws IOException { throw new UnsupportedOperationException ( ) ; } @ Override public void readFully ( long position , byte [ ] buffer , int offset , int length ) throws IOException { throw new UnsupportedOperationException ( ) ; } @ Override public void readFully ( long position , byte [ ] buffer ) throws IOException { throw new UnsupportedOperationException ( ) ; } @ Override public void seek ( long pos ) throws IOException { if ( pos < current ) { throw new UnsupportedOperationException ( ) ; } while ( pos > current ) { skip0 ( pos - current ) ; } } @ Override public long getPos ( ) throws IOException { return current ; } @ Override public boolean seekToNewSource ( long targetPos ) throws IOException { return false ; } @ Override public int read ( ) throws IOException { int result = input . read ( ) ; if ( result >= ) { current ++ ; } return result ; } @ Override public int read ( byte [ ] b ) throws IOException { int result = input . read ( b ) ; if ( result >= ) { current += result ; } return result ; } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { int result = input . read ( b , off , len ) ; if ( result >= ) { current += result ; } return result ; } @ Override public long skip ( long n ) throws IOException { return skip0 ( n ) ; } private long skip0 ( long n ) throws IOException { long result = input . skip ( n ) ; if ( result >= ) { current += result ; } return result ; } @ Override public int available ( ) throws IOException { return input . available ( ) ; } @ Override public void close ( ) throws IOException { input . close ( ) ; } @ Override public boolean markSupported ( ) { return false ; } @ Override public synchronized void mark ( int readlimit ) { throw new UnsupportedOperationException ( ) ; } @ Override public synchronized void reset ( ) throws IOException { throw new UnsupportedOperationException ( ) ; } } } package com . asakusafw . runtime . io . sequencefile ; import java . io . Closeable ; import java . io . IOException ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . io . ModelInput ; public class SequenceFileModelInput < T extends Writable > implements ModelInput < T > { private final SequenceFile . Reader reader ; private final Closeable closeable ; public SequenceFileModelInput ( SequenceFile . Reader reader ) { this ( reader , reader ) ; } public SequenceFileModelInput ( SequenceFile . Reader reader , Closeable closeable ) { if ( reader == null ) { throw new IllegalArgumentException ( "" ) ; } this . reader = reader ; this . closeable = closeable ; } @ Override public boolean readTo ( T model ) throws IOException { return reader . next ( NullWritable . get ( ) , model ) ; } @ Override public void close ( ) throws IOException { if ( closeable != null ) { closeable . close ( ) ; } } } package com . asakusafw . runtime . io ; package com . asakusafw . runtime . io ; import java . io . Closeable ; import java . io . IOException ; public interface ModelOutput < T > extends Closeable { void write ( T model ) throws IOException ; } package com . asakusafw . runtime . io ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . nio . charset . Charset ; public class TsvIoFactory < T > extends ModelIoFactory < T > { private static final Charset CHARSET = Charset . forName ( "" ) ; public TsvIoFactory ( Class < T > modelClass ) { super ( modelClass ) ; } @ Override protected RecordParser createRecordParser ( InputStream in ) throws IOException { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } return new TsvParser ( new InputStreamReader ( in , CHARSET ) ) ; } @ Override protected RecordEmitter createRecordEmitter ( OutputStream out ) throws IOException { if ( out == null ) { throw new IllegalArgumentException ( "" ) ; } return new TsvEmitter ( new OutputStreamWriter ( out , CHARSET ) ) ; } } package com . asakusafw . runtime . io . util ; import java . io . InputStream ; public class VoidInputStream extends InputStream { @ Override public int read ( ) { return - ; } } package com . asakusafw . runtime . io . util ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . util . Arrays ; import org . apache . hadoop . util . ReflectionUtils ; public class WritableRawComparableTuple implements WritableRawComparable , Tuple { private final WritableRawComparable [ ] objects ; public WritableRawComparableTuple ( Class < ? > ... classes ) { if ( classes == null ) { throw new IllegalArgumentException ( "" ) ; } this . objects = new WritableRawComparable [ classes . length ] ; for ( int i = ; i < classes . length ; i ++ ) { this . objects [ i ] = ( WritableRawComparable ) ReflectionUtils . newInstance ( classes [ i ] , null ) ; } } public WritableRawComparableTuple ( WritableRawComparable ... objects ) { if ( objects == null ) { throw new IllegalArgumentException ( "" ) ; } this . objects = objects . clone ( ) ; } @ Override public final int size ( ) { return objects . length ; } @ Override public final Object get ( int index ) { return objects [ index ] ; } @ Override public final void write ( DataOutput out ) throws IOException { for ( int i = ; i < objects . length ; i ++ ) { objects [ i ] . write ( out ) ; } } @ Override public final void readFields ( DataInput in ) throws IOException { for ( int i = ; i < objects . length ; i ++ ) { objects [ i ] . readFields ( in ) ; } } @ Override public final int compareTo ( WritableRawComparable o ) { assert getClass ( ) == o . getClass ( ) ; WritableRawComparable [ ] a = objects ; WritableRawComparable [ ] b = ( ( WritableRawComparableTuple ) o ) . objects ; assert a . length == b . length ; for ( int i = ; i < a . length ; i ++ ) { int diff = a [ i ] . compareTo ( b [ i ] ) ; if ( diff != ) { return diff ; } } return ; } @ Override public final int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { int cursor = ; for ( int i = ; i < objects . length ; i ++ ) { cursor += objects [ i ] . getSizeInBytes ( buf , offset + cursor ) ; } return cursor ; } @ Override public final int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { int cursor = ; for ( int i = ; i < objects . length ; i ++ ) { int diff = objects [ i ] . compareInBytes ( b1 , o1 + cursor , b2 , o2 + cursor ) ; if ( diff != ) { return diff ; } cursor += objects [ i ] . getSizeInBytes ( b1 , o1 + cursor ) ; } return ; } @ Override public final int hashCode ( ) { final int prime = ; int result = ; result = prime * result + Arrays . hashCode ( objects ) ; return result ; } @ Override public final boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } WritableRawComparableTuple other = ( WritableRawComparableTuple ) obj ; if ( ! Arrays . equals ( objects , other . objects ) ) { return false ; } return true ; } @ Override public final String toString ( ) { return Arrays . toString ( objects ) ; } } package com . asakusafw . runtime . io . util ; import java . io . IOException ; import java . io . InputStream ; import java . util . zip . ZipInputStream ; public class ZipEntryInputStream extends InputStream { private ZipInputStream zipped ; public ZipEntryInputStream ( ZipInputStream zipped ) { if ( zipped == null ) { throw new IllegalArgumentException ( "" ) ; } this . zipped = zipped ; } @ Override public void close ( ) throws IOException { zipped . closeEntry ( ) ; } @ Override public int read ( byte [ ] b ) throws IOException { return zipped . read ( b ) ; } @ Override public int read ( ) throws IOException { return zipped . read ( ) ; } @ Override public int available ( ) throws IOException { return zipped . available ( ) ; } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { return zipped . read ( b , off , len ) ; } @ Override public long skip ( long n ) throws IOException { return zipped . skip ( n ) ; } @ Override public boolean markSupported ( ) { return zipped . markSupported ( ) ; } @ Override public synchronized void mark ( int readlimit ) { zipped . mark ( readlimit ) ; } @ Override public synchronized void reset ( ) throws IOException { zipped . reset ( ) ; } } package com . asakusafw . runtime . io . util ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Arrays ; import org . apache . hadoop . io . WritableComparator ; import org . apache . hadoop . io . WritableUtils ; import org . apache . hadoop . util . ReflectionUtils ; public class WritableRawComparableUnion implements Union , WritableRawComparable { private final WritableRawComparable [ ] objects ; private int position ; public WritableRawComparableUnion ( Class < ? > ... classes ) { if ( classes == null ) { throw new IllegalArgumentException ( "" ) ; } this . objects = new WritableRawComparable [ classes . length ] ; for ( int i = ; i < classes . length ; i ++ ) { this . objects [ i ] = ( WritableRawComparable ) ReflectionUtils . newInstance ( classes [ i ] , null ) ; } } public WritableRawComparableUnion ( WritableRawComparable ... objects ) { if ( objects == null ) { throw new IllegalArgumentException ( "" ) ; } this . objects = objects . clone ( ) ; } @ Override public final int getPosition ( ) { return position ; } @ Override public Object switchObject ( int newPosition ) { this . position = newPosition ; return getObject ( ) ; } @ Override public final Object getObject ( ) { return objects [ position ] ; } @ Override public void write ( DataOutput out ) throws IOException { WritableUtils . writeVInt ( out , position ) ; objects [ position ] . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { this . position = WritableUtils . readVInt ( in ) ; objects [ position ] . readFields ( in ) ; } @ Override public int compareTo ( WritableRawComparable o ) { WritableRawComparableUnion other = ( WritableRawComparableUnion ) o ; int p1 = position ; int p2 = other . position ; if ( p1 < p2 ) { return - ; } else if ( p1 > p2 ) { return + ; } return objects [ p1 ] . compareTo ( other . objects [ p2 ] ) ; } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { int pos = WritableComparator . readVInt ( buf , offset ) ; WritableRawComparable object = objects [ pos ] ; int meta = WritableUtils . decodeVIntSize ( buf [ offset ] ) ; return meta + object . getSizeInBytes ( buf , offset + meta ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { int p1 = WritableComparator . readVInt ( b1 , o1 ) ; int p2 = WritableComparator . readVInt ( b2 , o2 ) ; if ( p1 < p2 ) { return - ; } else if ( p1 > p2 ) { return + ; } WritableRawComparable object = objects [ p1 ] ; int meta = WritableUtils . decodeVIntSize ( b1 [ o1 ] ) ; return object . compareInBytes ( b1 , o1 + meta , b2 , o2 + meta ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + position ; result = prime * result + Arrays . hashCode ( objects ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } WritableRawComparableUnion other = ( WritableRawComparableUnion ) obj ; if ( position != other . position ) { return false ; } if ( ! Arrays . equals ( objects , other . objects ) ) { return false ; } return true ; } @ Override public String toString ( ) { try { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , position , getObject ( ) ) ; } catch ( RuntimeException e ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , position ) ; } } } package com . asakusafw . runtime . io . util ; package com . asakusafw . runtime . io . util ; import java . io . IOException ; import org . apache . hadoop . io . WritableComparable ; public interface WritableRawComparable extends WritableComparable < WritableRawComparable > { int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException ; int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException ; } package com . asakusafw . runtime . io . util ; import java . io . IOException ; import org . apache . hadoop . io . WritableComparator ; public class WritableRawComparator extends WritableComparator { private final WritableRawComparable object ; protected WritableRawComparator ( Class < ? extends WritableRawComparable > aClass ) { super ( aClass ) ; this . object = ( WritableRawComparable ) newKey ( ) ; } @ Override public int compare ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { try { return object . compareInBytes ( b1 , s1 , b2 , s2 ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } } package com . asakusafw . runtime . io . util ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . WritableComparable ; import org . apache . hadoop . io . WritableComparator ; import org . apache . hadoop . util . ReflectionUtils ; public abstract class ShuffleKey < TGroup extends WritableRawComparable , TOrder extends WritableRawComparable > implements WritableRawComparable { final TGroup groupObject ; final TOrder orderObject ; protected ShuffleKey ( Class < TGroup > groupType , Class < TOrder > orderType ) { if ( groupType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( orderType == null ) { throw new IllegalArgumentException ( "" ) ; } this . groupObject = ReflectionUtils . newInstance ( groupType , null ) ; this . orderObject = ReflectionUtils . newInstance ( orderType , null ) ; } protected ShuffleKey ( TGroup groupObject , TOrder orderObject ) { if ( groupObject == null ) { throw new IllegalArgumentException ( "" ) ; } if ( orderObject == null ) { throw new IllegalArgumentException ( "" ) ; } this . groupObject = groupObject ; this . orderObject = orderObject ; } public final TGroup getGroupObject ( ) { return groupObject ; } public final TOrder getOrderObject ( ) { return orderObject ; } @ Override public final int compareTo ( WritableRawComparable o ) { ShuffleKey < ? , ? > other = ( ShuffleKey < ? , ? > ) o ; int groupDiff = groupObject . compareTo ( other . groupObject ) ; if ( groupDiff != ) { return groupDiff ; } int orderDiff = orderObject . compareTo ( other . orderObject ) ; return orderDiff ; } @ Override public final void write ( DataOutput out ) throws IOException { groupObject . write ( out ) ; orderObject . write ( out ) ; } @ Override public final void readFields ( DataInput in ) throws IOException { groupObject . readFields ( in ) ; orderObject . readFields ( in ) ; } @ Override public final int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { int groupSize = groupObject . getSizeInBytes ( buf , offset ) ; int orderSize = orderObject . getSizeInBytes ( buf , offset + groupSize ) ; return groupSize + orderSize ; } @ Override public final int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { int groupDiff = groupObject . compareInBytes ( b1 , o1 , b2 , o2 ) ; if ( groupDiff != ) { return groupDiff ; } int groupSize = groupObject . getSizeInBytes ( b1 , o1 ) ; assert groupSize == groupObject . getSizeInBytes ( b2 , o2 ) ; int orderDiff = orderObject . compareInBytes ( b1 , o1 + groupSize , b2 , o2 + groupSize ) ; return orderDiff ; } @ Override public final int hashCode ( ) { final int prime = ; int result = ; result = prime * result + groupObject . hashCode ( ) ; result = prime * result + orderObject . hashCode ( ) ; return result ; } @ Override public final boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ShuffleKey < ? , ? > other = ( ShuffleKey < ? , ? > ) obj ; if ( ! groupObject . equals ( other . groupObject ) ) { return false ; } if ( ! orderObject . equals ( other . orderObject ) ) { return false ; } return true ; } @ Override public final String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( groupObject ) ; builder . append ( "" ) ; builder . append ( orderObject ) ; builder . append ( "" ) ; return builder . toString ( ) ; } @ SuppressWarnings ( "" ) public static final class Partitioner extends org . apache . hadoop . mapreduce . Partitioner < ShuffleKey , Object > { @ Override public int getPartition ( ShuffleKey key , Object value , int numPartitions ) { int hash = key . groupObject . hashCode ( ) & Integer . MAX_VALUE ; return hash % numPartitions ; } } @ SuppressWarnings ( "" ) public abstract static class AbstractGroupComparator extends WritableComparator { private final ShuffleKey < ? , ? > object ; protected AbstractGroupComparator ( Class < ? extends ShuffleKey > keyClass ) { super ( keyClass ) ; this . object = ( ShuffleKey < ? , ? > ) newKey ( ) ; } @ Override public int compare ( WritableComparable a , WritableComparable b ) { ShuffleKey < ? , ? > ak = ( ShuffleKey < ? , ? > ) a ; ShuffleKey < ? , ? > bk = ( ShuffleKey < ? , ? > ) b ; return ak . groupObject . compareTo ( bk . groupObject ) ; } @ Override public int compare ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { try { return object . groupObject . compareInBytes ( b1 , s1 , b2 , s2 ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } } @ SuppressWarnings ( "" ) public abstract static class AbstractOrderComparator extends WritableRawComparator { protected AbstractOrderComparator ( Class < ? extends ShuffleKey > keyClass ) { super ( keyClass ) ; } } } package com . asakusafw . runtime . io . util ; public interface Tuple { int size ( ) ; Object get ( int index ) ; } package com . asakusafw . runtime . io . util ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class VoidModelOutput < T > implements ModelOutput < T > { @ Override public void write ( T model ) { return ; } @ Override public void close ( ) { return ; } } package com . asakusafw . runtime . io . util ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; public class InvertOrder implements WritableRawComparable { private final WritableRawComparable entity ; public InvertOrder ( WritableRawComparable entity ) { if ( entity == null ) { throw new IllegalArgumentException ( "" ) ; } this . entity = entity ; } public WritableRawComparable getEntity ( ) { return entity ; } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return entity . getSizeInBytes ( buf , offset ) ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return - entity . compareInBytes ( b1 , o1 , b2 , o2 ) ; } @ Override public void write ( DataOutput out ) throws IOException { entity . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { entity . readFields ( in ) ; } @ Override public int compareTo ( WritableRawComparable o ) { InvertOrder other = ( InvertOrder ) o ; return other . entity . compareTo ( entity ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + entity . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } InvertOrder other = ( InvertOrder ) obj ; if ( ! entity . equals ( other . entity ) ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( entity ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . runtime . io . util ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; public final class NullWritableRawComparable implements WritableRawComparable { public static final NullWritableRawComparable INSTANCE = new NullWritableRawComparable ( ) ; @ Override public void write ( DataOutput out ) throws IOException { return ; } @ Override public void readFields ( DataInput in ) throws IOException { return ; } @ Override public int compareTo ( WritableRawComparable o ) { if ( o instanceof NullWritableRawComparable ) { return ; } throw new IllegalArgumentException ( ) ; } @ Override public int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return ; } @ Override public int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } return true ; } @ Override public String toString ( ) { return "" ; } } package com . asakusafw . runtime . io . util ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelInput ; public class VoidModelInput < T > implements ModelInput < T > { @ Override public boolean readTo ( T model ) throws IOException { return false ; } @ Override public void close ( ) { return ; } } package com . asakusafw . runtime . io . util ; import java . io . IOException ; import java . io . OutputStream ; import java . util . zip . ZipOutputStream ; public class ZipEntryOutputStream extends OutputStream { private ZipOutputStream zipped ; public ZipEntryOutputStream ( ZipOutputStream zipped ) { if ( zipped == null ) { throw new IllegalArgumentException ( "" ) ; } this . zipped = zipped ; } @ Override public void close ( ) throws IOException { zipped . closeEntry ( ) ; } @ Override public void write ( byte [ ] b ) throws IOException { zipped . write ( b ) ; } @ Override public void write ( int b ) throws IOException { zipped . write ( b ) ; } @ Override public void flush ( ) throws IOException { zipped . flush ( ) ; } @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { zipped . write ( b , off , len ) ; } } package com . asakusafw . runtime . io . util ; import java . io . InputStream ; import java . io . OutputStream ; public class VoidOutputStream extends OutputStream { @ Override public void write ( int b ) { return ; } } package com . asakusafw . runtime . io . util ; public interface Union { int getPosition ( ) ; Object switchObject ( int newPosition ) ; Object getObject ( ) ; } package com . asakusafw . runtime . io . util ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . WritableUtils ; import org . apache . hadoop . util . ReflectionUtils ; public class WritableUnion implements Union , Writable { private final Writable [ ] objects ; private int position ; protected WritableUnion ( Class < ? > ... classes ) { if ( classes == null ) { throw new IllegalArgumentException ( "" ) ; } this . objects = new Writable [ classes . length ] ; for ( int i = ; i < classes . length ; i ++ ) { this . objects [ i ] = ( Writable ) ReflectionUtils . newInstance ( classes [ i ] , null ) ; } } protected WritableUnion ( Writable ... objects ) { if ( objects == null ) { throw new IllegalArgumentException ( "" ) ; } this . objects = objects . clone ( ) ; } @ Override public final int getPosition ( ) { return position ; } @ Override public Object switchObject ( int newPosition ) { this . position = newPosition ; return getObject ( ) ; } @ Override public final Object getObject ( ) { return objects [ position ] ; } @ Override public void write ( DataOutput out ) throws IOException { WritableUtils . writeVInt ( out , position ) ; objects [ position ] . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { this . position = WritableUtils . readVInt ( in ) ; objects [ position ] . readFields ( in ) ; } @ Override public String toString ( ) { try { return MessageFormat . format ( "" , position , getObject ( ) ) ; } catch ( RuntimeException e ) { return MessageFormat . format ( "" , position ) ; } } } package com . asakusafw . runtime . io ; import java . io . Closeable ; import java . io . IOException ; public interface ModelInput < T > extends Closeable { boolean readTo ( T model ) throws IOException ; } package com . asakusafw . runtime . io ; import static com . asakusafw . runtime . io . TsvConstants . * ; import java . io . IOException ; import java . io . Writer ; import java . nio . ByteBuffer ; import java . nio . CharBuffer ; import java . nio . charset . Charset ; import java . nio . charset . CharsetDecoder ; import java . nio . charset . CoderResult ; import java . nio . charset . CodingErrorAction ; import java . text . MessageFormat ; import org . apache . hadoop . io . Text ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . runtime . value . ValueOption ; public class TsvEmitter implements RecordEmitter { private static final Charset TEXT_ENCODE = Charset . forName ( "" ) ; private static final int BUFFER_SIZE = ; private final Writer writer ; private final CharsetDecoder decoder ; private final StringBuilder lineBuffer ; private final char [ ] writeBuffer ; private boolean headOfLine ; private final CharBuffer decodeBuffer ; public TsvEmitter ( Writer writer ) throws IOException { if ( writer == null ) { throw new IllegalArgumentException ( "" ) ; } this . writer = writer ; this . decoder = TEXT_ENCODE . newDecoder ( ) . onMalformedInput ( CodingErrorAction . REPORT ) . onUnmappableCharacter ( CodingErrorAction . REPORT ) ; this . lineBuffer = new StringBuilder ( ) ; this . writeBuffer = new char [ BUFFER_SIZE ] ; this . headOfLine = true ; this . decodeBuffer = CharBuffer . wrap ( writeBuffer ) ; } @ Override public void endRecord ( ) throws IOException { flushLineBuffer ( ) ; writer . write ( RECORD_SEPARATOR ) ; headOfLine = true ; } private void flushLineBuffer ( ) throws IOException { int rest = lineBuffer . length ( ) ; int cursor = ; while ( rest > ) { int chunkSize = Math . min ( rest , writeBuffer . length ) ; lineBuffer . getChars ( cursor , cursor + chunkSize , writeBuffer , ) ; writer . write ( writeBuffer , , chunkSize ) ; rest -= chunkSize ; cursor += chunkSize ; } lineBuffer . setLength ( ) ; } private void startCell ( ) { if ( headOfLine == false ) { lineBuffer . append ( CELL_SEPARATOR ) ; } headOfLine = false ; } @ Override public void emit ( BooleanOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } lineBuffer . append ( option . get ( ) ? BOOLEAN_TRUE : BOOLEAN_FALSE ) ; } @ Override public void emit ( ByteOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } lineBuffer . append ( option . get ( ) ) ; } @ Override public void emit ( ShortOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } lineBuffer . append ( option . get ( ) ) ; } @ Override public void emit ( IntOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } lineBuffer . append ( option . get ( ) ) ; } @ Override public void emit ( LongOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } lineBuffer . append ( option . get ( ) ) ; } @ Override public void emit ( FloatOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } lineBuffer . append ( option . get ( ) ) ; } @ Override public void emit ( DoubleOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } lineBuffer . append ( option . get ( ) ) ; } @ Override public void emit ( DecimalOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } lineBuffer . append ( option . get ( ) ) ; } @ Override public void emit ( StringOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } Text text = option . get ( ) ; if ( text . getLength ( ) == ) { return ; } byte [ ] bytes = text . getBytes ( ) ; ByteBuffer source = ByteBuffer . wrap ( bytes , , text . getLength ( ) ) ; decoder . reset ( ) ; decodeBuffer . clear ( ) ; while ( true ) { CoderResult result = decoder . decode ( source , decodeBuffer , true ) ; if ( result . isError ( ) ) { throw new RecordFormatException ( MessageFormat . format ( "" , result ) ) ; } if ( result . isUnderflow ( ) ) { consumeDecoded ( ) ; break ; } if ( result . isOverflow ( ) ) { consumeDecoded ( ) ; } } while ( true ) { CoderResult result = decoder . flush ( decodeBuffer ) ; if ( result . isError ( ) ) { throw new RecordFormatException ( MessageFormat . format ( "" , result ) ) ; } if ( result . isUnderflow ( ) ) { consumeDecoded ( ) ; break ; } if ( result . isOverflow ( ) ) { consumeDecoded ( ) ; } } } private void consumeDecoded ( ) { decodeBuffer . flip ( ) ; if ( decodeBuffer . hasRemaining ( ) ) { char [ ] array = decodeBuffer . array ( ) ; for ( int i = decodeBuffer . position ( ) , n = decodeBuffer . limit ( ) ; i < n ; i ++ ) { char c = array [ i ] ; if ( c == '' ) { lineBuffer . append ( ESCAPE_CHAR ) ; lineBuffer . append ( ESCAPE_HT ) ; } else if ( c == '' ) { lineBuffer . append ( ESCAPE_CHAR ) ; lineBuffer . append ( ESCAPE_LF ) ; } else if ( c == '' ) { lineBuffer . append ( ESCAPE_CHAR ) ; lineBuffer . append ( ESCAPE_CHAR ) ; } else { lineBuffer . append ( c ) ; } } } decodeBuffer . clear ( ) ; } @ Override public void emit ( DateOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } int days = option . get ( ) . getElapsedDays ( ) ; emitDate ( days ) ; } @ Override public void emit ( DateTimeOption option ) throws IOException { startCell ( ) ; if ( emitNull ( option ) ) { return ; } long seconds = option . get ( ) . getElapsedSeconds ( ) ; int days = DateUtil . getDayFromSeconds ( seconds ) ; emitDate ( days ) ; lineBuffer . append ( DATE_TIME_SEPARATOR ) ; int sec = DateUtil . getSecondOfDay ( seconds ) ; emitTime ( sec ) ; } private void emitDate ( int days ) { int year = DateUtil . getYearFromDay ( days ) ; int daysInYear = days - DateUtil . getDayFromYear ( year ) ; boolean leap = DateUtil . isLeap ( year ) ; int month = DateUtil . getMonthOfYear ( daysInYear , leap ) ; int day = DateUtil . getDayOfMonth ( daysInYear , leap ) ; fill ( '' , YEAR_FIELD_LENGTH , year ) ; lineBuffer . append ( DATE_FIELD_SEPARATOR ) ; fill ( '' , MONTH_FIELD_LENGTH , month ) ; lineBuffer . append ( DATE_FIELD_SEPARATOR ) ; fill ( '' , DATE_FIELD_LENGTH , day ) ; } private void emitTime ( int sec ) { fill ( '' , HOUR_FIELD_LENGTH , sec / ( * ) ) ; lineBuffer . append ( TIME_FIELD_SEPARATOR ) ; fill ( '' , MINUTE_FIELD_LENGTH , sec / % ) ; lineBuffer . append ( TIME_FIELD_SEPARATOR ) ; fill ( '' , SECOND_FIELD_LENGTH , sec % ) ; } private void fill ( char filler , int columns , int value ) { for ( int i = , n = countToFill ( columns , value ) ; i < n ; i ++ ) { lineBuffer . append ( filler ) ; } lineBuffer . append ( value ) ; } private int countToFill ( int columns , int value ) { if ( value < ) { return ; } for ( int count = columns - , figure = ; count >= ; count -- , figure *= ) { if ( value < figure ) { return count ; } } return ; } private boolean emitNull ( ValueOption < ? > option ) { if ( option . isNull ( ) ) { lineBuffer . append ( ESCAPE_CHAR ) ; lineBuffer . append ( ESCAPE_NULL_COLUMN ) ; return true ; } return false ; } @ Override public void flush ( ) throws IOException { flushLineBuffer ( ) ; writer . flush ( ) ; } @ Override public void close ( ) throws IOException { if ( headOfLine == false ) { endRecord ( ) ; } writer . close ( ) ; } } package com . asakusafw . runtime . io ; import java . io . Closeable ; import java . io . Flushable ; import java . io . IOException ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . runtime . value . ValueOption ; public interface RecordEmitter extends Flushable , Closeable { void endRecord ( ) throws IOException ; void emit ( BooleanOption option ) throws IOException ; void emit ( ByteOption option ) throws IOException ; void emit ( ShortOption option ) throws IOException ; void emit ( IntOption option ) throws IOException ; void emit ( LongOption option ) throws IOException ; void emit ( FloatOption option ) throws IOException ; void emit ( DoubleOption option ) throws IOException ; void emit ( DecimalOption option ) throws IOException ; void emit ( StringOption option ) throws IOException ; void emit ( DateOption option ) throws IOException ; void emit ( DateTimeOption option ) throws IOException ; } package com . asakusafw . runtime . io . csv ; package com . asakusafw . runtime . io . csv ; import java . nio . charset . Charset ; import java . text . SimpleDateFormat ; import java . util . Collections ; import java . util . List ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class CsvConfiguration { public static final Charset DEFAULT_CHARSET = Charset . forName ( "" ) ; public static final List < String > DEFAULT_HEADER_CELLS = Collections . emptyList ( ) ; public static final String DEFAULT_TRUE_FORMAT = "" ; public static final String DEFAULT_FALSE_FORMAT = "" ; public static final String DEFAULT_DATE_FORMAT = "" ; public static final String DEFAULT_DATE_TIME_FORMAT = "" ; public static final char DEFAULT_SEPARATOR_CHAR = '' ; public static final boolean DEFAULT_LINE_BREAK_IN_VALUE = true ; private final Charset charset ; private final List < String > headerCells ; private final String trueFormat ; private final String falseFormat ; private final String dateFormat ; private final String dateTimeFormat ; private volatile boolean lineBreakInValue = DEFAULT_LINE_BREAK_IN_VALUE ; private volatile char separatorChar = DEFAULT_SEPARATOR_CHAR ; public CsvConfiguration ( Charset charset , List < String > headerCells , String trueFormat , String falseFormat , String dateFormat , String dateTimeFormat ) { if ( charset == null ) { throw new IllegalArgumentException ( "" ) ; } if ( headerCells == null ) { throw new IllegalArgumentException ( "" ) ; } if ( trueFormat == null ) { throw new IllegalArgumentException ( "" ) ; } if ( falseFormat == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dateFormat == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dateTimeFormat == null ) { throw new IllegalArgumentException ( "" ) ; } this . charset = charset ; this . headerCells = headerCells ; this . trueFormat = trueFormat ; this . falseFormat = falseFormat ; this . dateFormat = dateFormat ; this . dateTimeFormat = dateTimeFormat ; } public Charset getCharset ( ) { return charset ; } public List < String > getHeaderCells ( ) { return headerCells ; } public String getTrueFormat ( ) { return trueFormat ; } public String getFalseFormat ( ) { return falseFormat ; } public String getDateFormat ( ) { return dateFormat ; } public String getDateTimeFormat ( ) { return dateTimeFormat ; } public boolean isLineBreakInValue ( ) { return lineBreakInValue ; } public void setLineBreakInValue ( boolean allow ) { this . lineBreakInValue = allow ; } public char getSeparatorChar ( ) { return separatorChar ; } public void setSeparatorChar ( char separatorChar ) { this . separatorChar = separatorChar ; } } package com . asakusafw . runtime . io . csv ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . math . BigDecimal ; import java . nio . CharBuffer ; import java . nio . IntBuffer ; import java . text . MessageFormat ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . io . Text ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . runtime . io . csv . CsvFormatException . Reason ; import com . asakusafw . runtime . io . csv . CsvFormatException . Status ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; public class CsvParser implements RecordParser { static final Log LOG = LogFactory . getLog ( CsvParser . class ) ; private static final int BUFFER_LIMIT = * * ; private static final int INPUT_BUFFER_SIZE = ; private static final int EOF = - ; private static final int STATE_LINE_HEAD = ; private static final int STATE_CELL_HEAD = STATE_LINE_HEAD + ; private static final int STATE_CELL_BODY = STATE_CELL_HEAD + ; private static final int STATE_QUOTED = STATE_CELL_BODY + ; private static final int STATE_NEST_QUOTE = STATE_QUOTED + ; private static final int STATE_SAW_CR = STATE_NEST_QUOTE + ; private static final int STATE_QUOTED_SAW_CR = STATE_SAW_CR + ; private static final int STATE_INIT = STATE_LINE_HEAD ; private static final int STATE_FINAL = - ; private final Reader reader ; private final String path ; private final char separator ; private final String trueFormat ; private final DateFormatter dateFormat ; private final DateTimeFormatter dateTimeFormat ; private final List < String > headerCellsFormat ; private final boolean allowLineBreakInValue ; private boolean firstLine = true ; private IntBuffer cellBeginPositions = IntBuffer . allocate ( ) ; private final CharBuffer readerBuffer = CharBuffer . allocate ( INPUT_BUFFER_SIZE ) ; private CharBuffer lineBuffer = CharBuffer . allocate ( INPUT_BUFFER_SIZE ) ; private int currentRecordNumber = ; private int currentPhysicalLine = ; private int currentPhysicalHeadLine = ; private CsvFormatException . Status exceptionStatus = null ; private final Text textBuffer = new Text ( ) ; public CsvParser ( InputStream stream , String path , CsvConfiguration config ) { if ( stream == null ) { throw new IllegalArgumentException ( "" ) ; } if ( config == null ) { throw new IllegalArgumentException ( "" ) ; } this . reader = new InputStreamReader ( stream , config . getCharset ( ) ) ; this . path = path ; this . separator = config . getSeparatorChar ( ) ; this . trueFormat = config . getTrueFormat ( ) ; this . dateFormat = DateFormatter . newInstance ( config . getDateFormat ( ) ) ; this . dateTimeFormat = DateTimeFormatter . newInstance ( config . getDateTimeFormat ( ) ) ; this . headerCellsFormat = config . getHeaderCells ( ) ; this . allowLineBreakInValue = config . isLineBreakInValue ( ) ; readerBuffer . clear ( ) ; readerBuffer . flip ( ) ; } private void decodeLine ( ) throws IOException { currentPhysicalHeadLine = currentPhysicalLine ; lineBuffer . clear ( ) ; cellBeginPositions . clear ( ) ; int state = STATE_INIT ; addSeparator ( ) ; while ( state != STATE_FINAL ) { int c = getNextCharacter ( ) ; switch ( state ) { case STATE_LINE_HEAD : state = onLineHead ( c ) ; break ; case STATE_CELL_HEAD : state = onCellHead ( c ) ; break ; case STATE_CELL_BODY : state = onCellBody ( c ) ; break ; case STATE_QUOTED : state = onQuoted ( c ) ; break ; case STATE_NEST_QUOTE : state = onNestQuote ( c ) ; break ; case STATE_SAW_CR : state = onSawCr ( c ) ; break ; case STATE_QUOTED_SAW_CR : state = onQuotedSawCr ( c ) ; break ; default : throw new AssertionError ( state ) ; } } lineBuffer . flip ( ) ; cellBeginPositions . flip ( ) ; } private int onLineHead ( int c ) throws IOException { int state ; switch ( c ) { case '' : state = STATE_QUOTED ; break ; case '' : state = STATE_SAW_CR ; break ; case '' : state = STATE_FINAL ; addSeparator ( ) ; currentPhysicalLine ++ ; break ; case EOF : state = STATE_FINAL ; break ; default : if ( c == separator ) { state = STATE_CELL_HEAD ; addSeparator ( ) ; } else { state = STATE_CELL_BODY ; emit ( c ) ; } break ; } return state ; } private int onCellHead ( int c ) throws IOException { int state ; switch ( c ) { case '' : state = STATE_QUOTED ; break ; case '' : state = STATE_SAW_CR ; break ; case '' : state = STATE_FINAL ; addSeparator ( ) ; currentPhysicalLine ++ ; break ; case EOF : state = STATE_FINAL ; addSeparator ( ) ; break ; default : if ( c == separator ) { state = STATE_CELL_HEAD ; addSeparator ( ) ; } else { state = STATE_CELL_BODY ; emit ( c ) ; } break ; } return state ; } private int onCellBody ( int c ) throws IOException { int state ; switch ( c ) { case '' : state = STATE_CELL_BODY ; emit ( c ) ; break ; case '' : state = STATE_SAW_CR ; break ; case '' : state = STATE_FINAL ; addSeparator ( ) ; currentPhysicalLine ++ ; break ; case EOF : state = STATE_FINAL ; addSeparator ( ) ; break ; default : if ( c == separator ) { state = STATE_CELL_HEAD ; addSeparator ( ) ; } else { state = STATE_CELL_BODY ; emit ( c ) ; } break ; } return state ; } private int onQuoted ( int c ) throws IOException { int state ; switch ( c ) { case '' : state = STATE_NEST_QUOTE ; break ; case '' : state = STATE_QUOTED_SAW_CR ; emit ( c ) ; break ; case '' : state = STATE_QUOTED ; if ( allowLineBreakInValue == false ) { exceptionStatus = createStatusInDecode ( Reason . UNEXPECTED_LINE_BREAK , "" , "" ) ; } currentPhysicalLine ++ ; emit ( c ) ; break ; case EOF : state = STATE_FINAL ; addSeparator ( ) ; exceptionStatus = createStatusInDecode ( Reason . UNEXPECTED_EOF , "" , "" ) ; break ; default : state = STATE_QUOTED ; emit ( c ) ; } return state ; } private int onNestQuote ( int c ) throws IOException { int state ; switch ( c ) { case '' : state = STATE_QUOTED ; emit ( c ) ; break ; case '' : state = STATE_SAW_CR ; break ; case '' : state = STATE_FINAL ; addSeparator ( ) ; currentPhysicalLine ++ ; break ; case EOF : state = STATE_FINAL ; addSeparator ( ) ; break ; default : if ( c == separator ) { state = STATE_CELL_HEAD ; addSeparator ( ) ; } else { state = STATE_CELL_BODY ; warn ( createStatusInDecode ( Reason . CHARACTER_AFTER_QUOTE , "" , String . valueOf ( c ) ) ) ; emit ( c ) ; } break ; } return state ; } private int onSawCr ( int c ) { int state ; currentPhysicalLine ++ ; switch ( c ) { case '' : state = STATE_FINAL ; addSeparator ( ) ; break ; case EOF : state = STATE_FINAL ; addSeparator ( ) ; break ; default : state = STATE_FINAL ; addSeparator ( ) ; rewindCharacter ( ) ; } return state ; } private int onQuotedSawCr ( int c ) throws IOException { int state ; currentPhysicalLine ++ ; switch ( c ) { case '' : state = STATE_NEST_QUOTE ; break ; case '' : state = STATE_QUOTED_SAW_CR ; emit ( c ) ; break ; case '' : state = STATE_QUOTED ; if ( allowLineBreakInValue == false ) { exceptionStatus = createStatusInDecode ( Reason . UNEXPECTED_LINE_BREAK , "" , "" ) ; } emit ( c ) ; break ; case EOF : state = STATE_FINAL ; addSeparator ( ) ; exceptionStatus = createStatusInDecode ( Reason . UNEXPECTED_EOF , "" , "" ) ; break ; default : state = STATE_QUOTED ; emit ( c ) ; } return state ; } private void warn ( Status status ) { assert status != null ; LOG . warn ( status . toString ( ) ) ; } private int getNextCharacter ( ) throws IOException { CharBuffer buf = readerBuffer ; if ( buf . remaining ( ) == ) { buf . clear ( ) ; int read = reader . read ( buf ) ; buf . flip ( ) ; assert read != ; if ( read < ) { return EOF ; } } return buf . get ( ) ; } private void rewindCharacter ( ) { CharBuffer buf = readerBuffer ; assert buf . position ( ) > ; buf . position ( buf . position ( ) - ) ; } private void emit ( int c ) throws IOException { assert c >= ; CharBuffer buf = lineBuffer ; if ( buf . remaining ( ) == ) { if ( buf . capacity ( ) == BUFFER_LIMIT ) { throw new IOException ( MessageFormat . format ( "" , path , currentPhysicalHeadLine , BUFFER_LIMIT , currentRecordNumber ) ) ; } CharBuffer newBuf = CharBuffer . allocate ( Math . min ( buf . capacity ( ) * , BUFFER_LIMIT ) ) ; newBuf . clear ( ) ; buf . flip ( ) ; newBuf . put ( buf ) ; buf = newBuf ; lineBuffer = newBuf ; } buf . put ( ( char ) c ) ; } private void addSeparator ( ) { IntBuffer buf = cellBeginPositions ; if ( buf . remaining ( ) == ) { IntBuffer newBuf = IntBuffer . allocate ( buf . capacity ( ) * ) ; newBuf . clear ( ) ; buf . flip ( ) ; newBuf . put ( buf ) ; buf = newBuf ; cellBeginPositions = newBuf ; } buf . put ( lineBuffer . position ( ) ) ; } private Status createStatusInDecode ( Reason reason , String expected , String actual ) { assert reason != null ; return new Status ( reason , path , currentPhysicalLine , currentRecordNumber , cellBeginPositions . limit ( ) , expected , actual ) ; } @ Override public boolean next ( ) throws CsvFormatException , IOException { exceptionStatus = null ; currentRecordNumber ++ ; if ( firstLine ) { firstLine = false ; decodeLine ( ) ; if ( isEof ( ) ) { return false ; } if ( isHeader ( ) ) { decodeLine ( ) ; } } else { decodeLine ( ) ; } if ( exceptionStatus != null ) { throw new CsvFormatException ( exceptionStatus , null ) ; } return isEof ( ) == false ; } public String getPath ( ) { return path ; } public int getCurrentLineNumber ( ) { return currentPhysicalHeadLine ; } public int getCurrentRecordNumber ( ) { return currentRecordNumber ; } private boolean isEof ( ) { return cellBeginPositions . limit ( ) < ; } private boolean isHeader ( ) { if ( headerCellsFormat . isEmpty ( ) ) { return false ; } if ( headerCellsFormat . size ( ) != cellBeginPositions . remaining ( ) - ) { return false ; } for ( int i = , n = headerCellsFormat . size ( ) ; i < n ; i ++ ) { String fieldName = headerCellsFormat . get ( i ) ; CharSequence fieldValue = lineBuffer . subSequence ( cellBeginPositions . get ( i ) , cellBeginPositions . get ( i + ) ) ; if ( fieldName . contentEquals ( fieldValue ) == false ) { return false ; } } return true ; } @ SuppressWarnings ( "" ) @ Override public void fill ( BooleanOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toBooleanValue ( ) ) ; } else { option . setNull ( ) ; } } private boolean toBooleanValue ( ) { return trueFormat . contentEquals ( lineBuffer ) ; } @ SuppressWarnings ( "" ) @ Override public void fill ( ByteOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toByteValue ( ) ) ; } else { option . setNull ( ) ; } } private byte toByteValue ( ) throws CsvFormatException { try { return Byte . parseByte ( lineBuffer . toString ( ) ) ; } catch ( NumberFormatException e ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , "" ) , e ) ; } } @ SuppressWarnings ( "" ) @ Override public void fill ( ShortOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toShortValue ( ) ) ; } else { option . setNull ( ) ; } } private short toShortValue ( ) throws CsvFormatException { try { return Short . parseShort ( lineBuffer . toString ( ) ) ; } catch ( NumberFormatException e ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , "" ) , e ) ; } } @ SuppressWarnings ( "" ) @ Override public void fill ( IntOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toIntValue ( ) ) ; } else { option . setNull ( ) ; } } private int toIntValue ( ) throws CsvFormatException { try { return Integer . parseInt ( lineBuffer . toString ( ) ) ; } catch ( NumberFormatException e ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , "" ) , e ) ; } } @ SuppressWarnings ( "" ) @ Override public void fill ( LongOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toLongValue ( ) ) ; } else { option . setNull ( ) ; } } private long toLongValue ( ) throws CsvFormatException { try { return Long . parseLong ( lineBuffer . toString ( ) ) ; } catch ( NumberFormatException e ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , "" ) , e ) ; } } @ SuppressWarnings ( "" ) @ Override public void fill ( FloatOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toFloatValue ( ) ) ; } else { option . setNull ( ) ; } } private float toFloatValue ( ) throws CsvFormatException { try { return Float . parseFloat ( lineBuffer . toString ( ) ) ; } catch ( NumberFormatException e ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , "" ) , e ) ; } } @ SuppressWarnings ( "" ) @ Override public void fill ( DoubleOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toDoubleValue ( ) ) ; } else { option . setNull ( ) ; } } private double toDoubleValue ( ) throws CsvFormatException { try { return Double . parseDouble ( lineBuffer . toString ( ) ) ; } catch ( NumberFormatException e ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , "" ) , e ) ; } } @ SuppressWarnings ( "" ) @ Override public void fill ( DecimalOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toDecimalValue ( ) ) ; } else { option . setNull ( ) ; } } private BigDecimal toDecimalValue ( ) throws CsvFormatException { try { return new BigDecimal ( lineBuffer . toString ( ) ) ; } catch ( NumberFormatException e ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , "" ) , e ) ; } } @ SuppressWarnings ( "" ) @ Override public void fill ( StringOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toTextValue ( ) ) ; } else { option . setNull ( ) ; } } private Text toTextValue ( ) { textBuffer . set ( lineBuffer . toString ( ) ) ; return textBuffer ; } @ SuppressWarnings ( "" ) @ Override public void fill ( DateOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toDateValue ( ) ) ; } else { option . setNull ( ) ; } } private int toDateValue ( ) throws CsvFormatException { int result = dateFormat . parse ( lineBuffer ) ; if ( result < ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , dateFormat . getPattern ( ) ) , null ) ; } return result ; } @ SuppressWarnings ( "" ) @ Override public void fill ( DateTimeOption option ) throws CsvFormatException , IOException { seekBuffer ( ) ; if ( lineBuffer . hasRemaining ( ) ) { option . modify ( toDateTimeValue ( ) ) ; } else { option . setNull ( ) ; } } private long toDateTimeValue ( ) throws CsvFormatException { long result = dateTimeFormat . parse ( lineBuffer ) ; if ( result < ) { throw new CsvFormatException ( createStatusInLine ( Reason . INVALID_CELL_FORMAT , dateTimeFormat . getPattern ( ) ) , null ) ; } return result ; } private Status createStatusInLine ( Reason reason , String expected ) { return new Status ( reason , path , currentPhysicalHeadLine , currentRecordNumber , cellBeginPositions . position ( ) , expected , lineBuffer . toString ( ) ) ; } @ Override public void endRecord ( ) throws CsvFormatException , IOException { if ( cellBeginPositions . remaining ( ) > ) { seekBuffer ( ) ; throw new CsvFormatException ( new Status ( Reason . TOO_LONG_RECORD , path , currentPhysicalHeadLine , currentRecordNumber , cellBeginPositions . position ( ) , "" , lineBuffer . toString ( ) ) , null ) ; } } private void seekBuffer ( ) throws CsvFormatException { if ( cellBeginPositions . remaining ( ) < ) { throw new CsvFormatException ( new Status ( Reason . TOO_SHORT_RECORD , path , currentPhysicalHeadLine , currentRecordNumber , cellBeginPositions . position ( ) + , "" , "" ) , null ) ; } lineBuffer . limit ( cellBeginPositions . get ( cellBeginPositions . position ( ) + ) ) ; lineBuffer . position ( cellBeginPositions . get ( ) ) ; } @ Override public void close ( ) throws IOException { reader . close ( ) ; } } package com . asakusafw . runtime . io . csv ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . Writer ; import java . util . Iterator ; import java . util . List ; import java . util . regex . Pattern ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; public class CsvEmitter implements RecordEmitter { static final Log LOG = LogFactory . getLog ( CsvEmitter . class ) ; private static final int INITIAL_BUFFER_SIZE = ; private static final String LINE_DELIMITER = "" ; private static final char ESCAPE = '' ; private final Writer writer ; private final char separator ; private final String trueFormat ; private final String falseFormat ; private final DateFormatter dateFormat ; private final boolean escapeDate ; private final DateTimeFormatter dateTimeFormat ; private final boolean escapeDateTime ; private final List < String > headerCellsFormat ; private boolean firstLine = true ; private boolean firstCell = true ; private boolean open = true ; private final StringBuilder lineBuffer = new StringBuilder ( INITIAL_BUFFER_SIZE ) ; private final Pattern escapePattern ; public CsvEmitter ( OutputStream stream , String path , CsvConfiguration config ) { if ( stream == null ) { throw new IllegalArgumentException ( "" ) ; } if ( config == null ) { throw new IllegalArgumentException ( "" ) ; } this . writer = new OutputStreamWriter ( stream , config . getCharset ( ) ) ; this . separator = config . getSeparatorChar ( ) ; this . escapePattern = Pattern . compile ( "" + ESCAPE + separator + LINE_DELIMITER + "" ) ; this . trueFormat = escape ( config . getTrueFormat ( ) ) ; this . falseFormat = escape ( config . getFalseFormat ( ) ) ; this . dateFormat = DateFormatter . newInstance ( config . getDateFormat ( ) ) ; this . escapeDate = hasMetaCharacter ( dateFormat . getPattern ( ) ) ; this . dateTimeFormat = DateTimeFormatter . newInstance ( config . getDateTimeFormat ( ) ) ; this . escapeDateTime = hasMetaCharacter ( dateTimeFormat . getPattern ( ) ) ; this . headerCellsFormat = config . getHeaderCells ( ) ; } private String escape ( String string ) { assert string != null ; if ( hasEscapeTarget ( string ) ) { StringBuilder buffer = new StringBuilder ( ) ; appendEscaped ( buffer , string ) ; return buffer . toString ( ) ; } return string ; } private boolean hasMetaCharacter ( String pattern ) { assert pattern != null ; return escapePattern . matcher ( pattern ) . find ( ) ; } @ Override public void emit ( BooleanOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { lineBuffer . append ( toString ( option . get ( ) ) ) ; } } private String toString ( boolean value ) { return value ? trueFormat : falseFormat ; } @ Override public void emit ( ByteOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { lineBuffer . append ( option . get ( ) ) ; } } @ Override public void emit ( ShortOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { lineBuffer . append ( option . get ( ) ) ; } } @ Override public void emit ( IntOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { lineBuffer . append ( option . get ( ) ) ; } } @ Override public void emit ( LongOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { lineBuffer . append ( option . get ( ) ) ; } } @ Override public void emit ( FloatOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { lineBuffer . append ( option . get ( ) ) ; } } @ Override public void emit ( DoubleOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { lineBuffer . append ( option . get ( ) ) ; } } @ Override public void emit ( DecimalOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { lineBuffer . append ( option . get ( ) ) ; } } @ Override public void emit ( StringOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { String str = option . getAsString ( ) ; if ( hasEscapeTarget ( str ) ) { appendEscaped ( lineBuffer , str ) ; } else { lineBuffer . append ( str ) ; } } } private boolean hasEscapeTarget ( String string ) { for ( int i = , n = string . length ( ) ; i < n ; i ++ ) { char c = string . charAt ( i ) ; if ( c == separator || c == ESCAPE || c == '' || c == '' ) { return true ; } } return false ; } @ Override public void emit ( DateOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { CharSequence string = dateFormat . format ( option . get ( ) . getElapsedDays ( ) ) ; if ( escapeDate ) { appendEscaped ( lineBuffer , string ) ; } else { lineBuffer . append ( string ) ; } } } @ Override public void emit ( DateTimeOption option ) throws IOException { addCellDelimiter ( ) ; if ( option . isNull ( ) == false ) { CharSequence string = dateTimeFormat . format ( option . get ( ) . getElapsedSeconds ( ) ) ; if ( escapeDateTime ) { appendEscaped ( lineBuffer , string ) ; } else { lineBuffer . append ( string ) ; } } } private void appendEscaped ( StringBuilder buffer , CharSequence string ) { buffer . append ( ESCAPE ) ; for ( int i = , n = string . length ( ) ; i < n ; i ++ ) { char c = string . charAt ( i ) ; if ( c == ESCAPE ) { buffer . append ( ESCAPE ) ; } buffer . append ( c ) ; } buffer . append ( ESCAPE ) ; } private void appendEscaped ( StringBuilder buffer , String string ) { buffer . append ( ESCAPE ) ; for ( int i = , n = string . length ( ) ; i < n ; i ++ ) { char c = string . charAt ( i ) ; if ( c == ESCAPE ) { buffer . append ( ESCAPE ) ; } buffer . append ( c ) ; } buffer . append ( ESCAPE ) ; } private void addCellDelimiter ( ) { if ( firstCell ) { firstCell = false ; } else { lineBuffer . append ( separator ) ; } } @ Override public void endRecord ( ) throws IOException { lineBuffer . append ( LINE_DELIMITER ) ; flushBuffer ( ) ; firstLine = false ; firstCell = true ; } @ Override public void flush ( ) throws IOException { flushBuffer ( ) ; writer . flush ( ) ; } private void flushBuffer ( ) throws IOException { if ( firstLine ) { firstLine = false ; Iterator < String > iter = headerCellsFormat . iterator ( ) ; if ( iter . hasNext ( ) ) { writer . append ( escape ( iter . next ( ) ) ) ; while ( iter . hasNext ( ) ) { writer . append ( separator ) ; writer . append ( escape ( iter . next ( ) ) ) ; } writer . append ( LINE_DELIMITER ) ; } } if ( lineBuffer . length ( ) > ) { writer . append ( lineBuffer ) ; lineBuffer . setLength ( ) ; } } @ Override public void close ( ) throws IOException { if ( open ) { flush ( ) ; open = false ; writer . close ( ) ; } } } package com . asakusafw . runtime . io . csv ; import java . nio . CharBuffer ; import java . text . ParsePosition ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import com . asakusafw . runtime . value . DateUtil ; abstract class DateTimeFormatter { private static final DateTimeFormatter [ ] BUILTIN = new DateTimeFormatter [ ] { new Direct ( ) , } ; abstract String getPattern ( ) ; abstract long parse ( CharSequence sequence ) ; abstract CharSequence format ( long elapsedSeconds ) ; static DateTimeFormatter newInstance ( String pattern ) { for ( DateTimeFormatter f : BUILTIN ) { if ( f . getPattern ( ) . equals ( pattern ) ) { return f ; } } return new Default ( new SimpleDateFormat ( pattern ) ) ; } private static final class Default extends DateTimeFormatter { private final SimpleDateFormat format ; private final Calendar calendarBuffer = Calendar . getInstance ( ) ; private final ParsePosition parsePositionBuffer = new ParsePosition ( ) ; Default ( SimpleDateFormat format ) { assert format != null ; this . format = format ; } @ Override String getPattern ( ) { return format . toPattern ( ) ; } @ Override long parse ( CharSequence sequence ) { parsePositionBuffer . setIndex ( ) ; parsePositionBuffer . setErrorIndex ( - ) ; java . util . Date parsed = format . parse ( sequence . toString ( ) , parsePositionBuffer ) ; if ( parsePositionBuffer . getIndex ( ) == ) { return - ; } calendarBuffer . setTime ( parsed ) ; return DateUtil . getSecondFromCalendar ( calendarBuffer ) ; } @ Override String format ( long elapsedSeconds ) { DateUtil . setSecondToCalendar ( elapsedSeconds , calendarBuffer ) ; return format . format ( calendarBuffer . getTime ( ) ) ; } } private static final class Direct extends DateTimeFormatter { private static final int POS_YEAR = ; private static final int POS_MONTH = ; private static final int POS_DAY = ; private static final int POS_HOUR = ; private static final int POS_MINUTE = ; private static final int POS_SECOND = ; private static final int LENGTH = ; private final CharBuffer buffer ; Direct ( ) { buffer = CharBuffer . allocate ( LENGTH ) ; } @ Override String getPattern ( ) { return "" ; } @ Override CharSequence format ( long elapsedSeconds ) { int elapsedDate = DateUtil . getDayFromSeconds ( elapsedSeconds ) ; int year = DateUtil . getYearFromDay ( elapsedDate ) ; int dayInYear = elapsedDate - DateUtil . getDayFromYear ( year ) ; int month = DateUtil . getMonthOfYear ( dayInYear , DateUtil . isLeap ( year ) ) ; int day = DateUtil . getDayOfMonth ( dayInYear , DateUtil . isLeap ( year ) ) ; int secondOfDay = DateUtil . getSecondOfDay ( elapsedSeconds ) ; int hour = secondOfDay / ( * ) ; int minute = secondOfDay / % ; int second = secondOfDay % ; putStringValue ( buffer , year , POS_YEAR , ) ; putStringValue ( buffer , month , POS_MONTH , ) ; putStringValue ( buffer , day , POS_DAY , ) ; putStringValue ( buffer , hour , POS_HOUR , ) ; putStringValue ( buffer , minute , POS_MINUTE , ) ; putStringValue ( buffer , second , POS_SECOND , ) ; return buffer ; } @ Override long parse ( CharSequence sequence ) { if ( sequence . length ( ) != LENGTH ) { return - ; } int year = getNumericValue ( sequence , POS_YEAR , ) ; int month = getNumericValue ( sequence , POS_MONTH , ) ; int day = getNumericValue ( sequence , POS_DAY , ) ; int hour = getNumericValue ( sequence , POS_HOUR , ) ; int minute = getNumericValue ( sequence , POS_MINUTE , ) ; int second = getNumericValue ( sequence , POS_SECOND , ) ; if ( year < || month < || day < || hour < || minute < || second < ) { return - ; } int date = DateUtil . getDayFromDate ( year , month , day ) ; int secondsInDay = DateUtil . getSecondFromTime ( hour , minute , second ) ; return ( long ) date * + secondsInDay ; } } static int getNumericValue ( CharSequence sequence , int from , int length ) { int to = from + length ; int result = ; for ( int i = from ; i < to ; i ++ ) { char c = ( char ) ( sequence . charAt ( i ) - '' ) ; if ( c > ) { return - ; } result = result * + c ; } return result ; } static void putStringValue ( CharBuffer buffer , int value , int from , int length ) { int to = from + length ; int current = value ; for ( int i = to - ; i >= from ; i -- ) { char c = ( char ) ( current % + '' ) ; current = current / ; buffer . put ( i , c ) ; } } } package com . asakusafw . runtime . io . csv ; import java . io . Serializable ; import java . text . MessageFormat ; import com . asakusafw . runtime . io . RecordFormatException ; public class CsvFormatException extends RecordFormatException { private static final long serialVersionUID = ; private final Status status ; public CsvFormatException ( Status status , Throwable cause ) { super ( toMessage ( status ) , cause ) ; this . status = status ; } private static String toMessage ( Status status ) { if ( status == null ) { throw new IllegalArgumentException ( "" ) ; } return status . toString ( ) ; } public Status getStatus ( ) { return status ; } public enum Reason { UNEXPECTED_LINE_BREAK , UNEXPECTED_EOF , CHARACTER_AFTER_QUOTE , INVALID_CELL_FORMAT , TOO_SHORT_RECORD , TOO_LONG_RECORD , } public static final class Status implements Serializable { private static final long serialVersionUID = ; private final Reason reason ; private final String path ; private final int lineNumber ; private final int recordNumber ; private final int columnNumber ; private final String expected ; private final String actual ; public Status ( Reason reason , String path , int lineNumber , int recordNumber , int columnNumber , String expected , String actual ) { this . reason = reason ; this . path = path ; this . lineNumber = lineNumber ; this . recordNumber = recordNumber ; this . columnNumber = columnNumber ; this . expected = expected ; this . actual = actual ; } public Reason getReason ( ) { return reason ; } public String getPath ( ) { return path ; } public int getLineNumber ( ) { return lineNumber ; } public int getRecordNumber ( ) { return recordNumber ; } public int getColumnNumber ( ) { return columnNumber ; } public String getExpected ( ) { return expected ; } public String getActual ( ) { return actual ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getReason ( ) , getPath ( ) , getLineNumber ( ) , getRecordNumber ( ) , getColumnNumber ( ) , getExpected ( ) , getActual ( ) ) ; } } } package com . asakusafw . runtime . io . csv ; import java . nio . CharBuffer ; import java . text . ParsePosition ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import com . asakusafw . runtime . value . DateUtil ; abstract class DateFormatter { private static final DateFormatter [ ] BUILTIN = new DateFormatter [ ] { new Direct ( ) , } ; abstract String getPattern ( ) ; abstract int parse ( CharSequence sequence ) ; abstract CharSequence format ( int elapsedDate ) ; static DateFormatter newInstance ( String pattern ) { for ( DateFormatter f : BUILTIN ) { if ( f . getPattern ( ) . equals ( pattern ) ) { return f ; } } return new Default ( new SimpleDateFormat ( pattern ) ) ; } private static final class Default extends DateFormatter { private final SimpleDateFormat format ; private final Calendar calendarBuffer = Calendar . getInstance ( ) ; private final ParsePosition parsePositionBuffer = new ParsePosition ( ) ; Default ( SimpleDateFormat format ) { assert format != null ; this . format = format ; } @ Override String getPattern ( ) { return format . toPattern ( ) ; } @ Override int parse ( CharSequence sequence ) { parsePositionBuffer . setIndex ( ) ; parsePositionBuffer . setErrorIndex ( - ) ; java . util . Date parsed = format . parse ( sequence . toString ( ) , parsePositionBuffer ) ; if ( parsePositionBuffer . getIndex ( ) == ) { return - ; } calendarBuffer . setTime ( parsed ) ; return DateUtil . getDayFromCalendar ( calendarBuffer ) ; } @ Override String format ( int elapsedDate ) { DateUtil . setDayToCalendar ( elapsedDate , calendarBuffer ) ; return format . format ( calendarBuffer . getTime ( ) ) ; } } private static final class Direct extends DateFormatter { private static final int POS_YEAR = ; private static final int POS_MONTH = ; private static final int POS_DAY = ; private static final int LENGTH = ; private final CharBuffer buffer ; Direct ( ) { buffer = CharBuffer . allocate ( LENGTH ) ; } @ Override String getPattern ( ) { return "" ; } @ Override CharSequence format ( int elapsedDate ) { int year = DateUtil . getYearFromDay ( elapsedDate ) ; int dayInYear = elapsedDate - DateUtil . getDayFromYear ( year ) ; int month = DateUtil . getMonthOfYear ( dayInYear , DateUtil . isLeap ( year ) ) ; int day = DateUtil . getDayOfMonth ( dayInYear , DateUtil . isLeap ( year ) ) ; putStringValue ( buffer , year , POS_YEAR , ) ; putStringValue ( buffer , month , POS_MONTH , ) ; putStringValue ( buffer , day , POS_DAY , ) ; return buffer ; } @ Override int parse ( CharSequence sequence ) { if ( sequence . length ( ) != LENGTH ) { return - ; } int year = getNumericValue ( sequence , POS_YEAR , ) ; int month = getNumericValue ( sequence , POS_MONTH , ) ; int day = getNumericValue ( sequence , POS_DAY , ) ; if ( year < || month < || day < ) { return - ; } return DateUtil . getDayFromDate ( year , month , day ) ; } } static int getNumericValue ( CharSequence sequence , int from , int length ) { int to = from + length ; int result = ; for ( int i = from ; i < to ; i ++ ) { char c = ( char ) ( sequence . charAt ( i ) - '' ) ; if ( c > ) { return - ; } result = result * + c ; } return result ; } static void putStringValue ( CharBuffer buffer , int value , int from , int length ) { int to = from + length ; int current = value ; for ( int i = to - ; i >= from ; i -- ) { char c = ( char ) ( current % + '' ) ; current = current / ; buffer . put ( i , c ) ; } } } package com . asakusafw . runtime . io ; public final class TsvConstants { public static final char BOOLEAN_TRUE = '' ; public static final char BOOLEAN_FALSE = '' ; public static final char ESCAPE_CHAR = '' ; public static final char ESCAPE_NULL_COLUMN = '' ; public static final char ESCAPE_HT = '' ; public static final char ESCAPE_LF = '' ; public static final char CELL_SEPARATOR = '' ; public static final char RECORD_SEPARATOR = '' ; public static final char DATE_FIELD_SEPARATOR = '' ; public static final char TIME_FIELD_SEPARATOR = '' ; public static final char DATE_TIME_SEPARATOR = '' ; public static final int YEAR_FIELD_LENGTH = ; public static final int MONTH_FIELD_LENGTH = ; public static final int DATE_FIELD_LENGTH = ; public static final int HOUR_FIELD_LENGTH = ; public static final int MINUTE_FIELD_LENGTH = ; public static final int SECOND_FIELD_LENGTH = ; private TsvConstants ( ) { return ; } } package com . asakusafw . runtime . io ; import static com . asakusafw . runtime . io . TsvConstants . * ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . Reader ; import java . math . BigDecimal ; import java . nio . ByteBuffer ; import java . nio . CharBuffer ; import java . nio . charset . Charset ; import java . nio . charset . CharsetEncoder ; import java . nio . charset . CoderResult ; import java . nio . charset . CodingErrorAction ; import java . text . MessageFormat ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . apache . hadoop . io . Text ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . runtime . value . ValueOption ; @ SuppressWarnings ( "" ) public final class TsvParser implements RecordParser { private static final Pattern SPECIAL_FLOAT = Pattern . compile ( "" ) ; private static final int SPECIAL_FLOAT_POSITIVE_INF = ; private static final int SPECIAL_FLOAT_NEGATIVE_INF = ; private static final Charset TEXT_ENCODE = Charset . forName ( "" ) ; private static final int INITIAL_BUFFER_SIZE = ; private final Reader reader ; private final CharsetEncoder encoder ; private int lastSeparator ; private int lookAhead ; private char [ ] charBuffer ; private CharBuffer wrappedCharBuffer ; private final ByteBuffer encodeBuffer ; public TsvParser ( Reader reader ) throws IOException { if ( reader == null ) { throw new IllegalArgumentException ( "" ) ; } if ( reader instanceof BufferedReader ) { this . reader = reader ; } else { this . reader = new BufferedReader ( reader ) ; } this . encoder = TEXT_ENCODE . newEncoder ( ) . onMalformedInput ( CodingErrorAction . REPORT ) . onUnmappableCharacter ( CodingErrorAction . REPORT ) ; this . charBuffer = new char [ INITIAL_BUFFER_SIZE ] ; this . lastSeparator = RECORD_SEPARATOR ; this . encodeBuffer = ByteBuffer . allocate ( INITIAL_BUFFER_SIZE ) ; fillLookAhead ( ) ; } private void fillLookAhead ( ) throws IOException { this . lookAhead = reader . read ( ) ; } @ Override public boolean next ( ) throws RecordFormatException , IOException { lastSeparator = CELL_SEPARATOR ; return lookAhead != - ; } private void checkCellStart ( ) throws RecordFormatException { if ( lastSeparator != CELL_SEPARATOR || lookAhead == - ) { throw new RecordFormatException ( "" ) ; } } @ Override public void fill ( BooleanOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } assertHasRest ( option , lookAhead ) ; if ( lookAhead == BOOLEAN_TRUE ) { option . modify ( true ) ; } else if ( lookAhead == BOOLEAN_FALSE ) { option . modify ( false ) ; } else { throw new RecordFormatException ( MessageFormat . format ( "" , ( char ) lookAhead ) ) ; } int next = reader . read ( ) ; if ( isSeparator ( next ) == false ) { throw new RecordFormatException ( MessageFormat . format ( "" , ( char ) next ) ) ; } setLastSeparator ( next ) ; fillLookAhead ( ) ; } @ Override public void fill ( ByteOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } option . modify ( ( byte ) readInt ( option ) ) ; fillLookAhead ( ) ; } @ Override public void fill ( ShortOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } option . modify ( ( short ) readInt ( option ) ) ; fillLookAhead ( ) ; } @ Override public void fill ( IntOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } int value = readInt ( option ) ; option . modify ( value ) ; fillLookAhead ( ) ; } @ Override public void fill ( LongOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } boolean negative = false ; if ( lookAhead == '' ) { lookAhead = reader . read ( ) ; negative = true ; } assertHasRest ( option , lookAhead ) ; long value = toNumber ( lookAhead ) ; while ( true ) { int c = reader . read ( ) ; if ( isSeparator ( c ) ) { setLastSeparator ( c ) ; break ; } value = value * + toNumber ( c ) ; } if ( negative ) { value = - value ; } option . modify ( value ) ; fillLookAhead ( ) ; } @ Override public void fill ( FloatOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } assertHasRest ( option , lookAhead ) ; charBuffer [ ] = ( char ) lookAhead ; int length = readString ( , option ) ; String string = new String ( charBuffer , , length + ) ; try { option . modify ( Float . parseFloat ( string ) ) ; } catch ( NumberFormatException e ) { Matcher matcher = SPECIAL_FLOAT . matcher ( string ) ; if ( matcher . matches ( ) ) { if ( matcher . group ( SPECIAL_FLOAT_POSITIVE_INF ) != null ) { option . modify ( Float . POSITIVE_INFINITY ) ; } else if ( matcher . group ( SPECIAL_FLOAT_NEGATIVE_INF ) != null ) { option . modify ( Float . NEGATIVE_INFINITY ) ; } else { option . modify ( Float . NaN ) ; } } else { throw new RecordFormatException ( MessageFormat . format ( "" , string ) , e ) ; } } fillLookAhead ( ) ; } @ Override public void fill ( DoubleOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } assertHasRest ( option , lookAhead ) ; charBuffer [ ] = ( char ) lookAhead ; int length = readString ( , option ) ; String string = new String ( charBuffer , , length + ) ; try { option . modify ( Double . parseDouble ( string ) ) ; } catch ( NumberFormatException e ) { Matcher matcher = SPECIAL_FLOAT . matcher ( string ) ; if ( matcher . matches ( ) ) { if ( matcher . group ( SPECIAL_FLOAT_POSITIVE_INF ) != null ) { option . modify ( Double . POSITIVE_INFINITY ) ; } else if ( matcher . group ( SPECIAL_FLOAT_NEGATIVE_INF ) != null ) { option . modify ( Double . NEGATIVE_INFINITY ) ; } else { option . modify ( Double . NaN ) ; } } else { throw new RecordFormatException ( MessageFormat . format ( "" , string ) , e ) ; } } fillLookAhead ( ) ; } @ Override public void fill ( DecimalOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } assertHasRest ( option , lookAhead ) ; charBuffer [ ] = ( char ) lookAhead ; int length = readString ( , option ) ; option . modify ( new BigDecimal ( charBuffer , , length + ) ) ; fillLookAhead ( ) ; } @ Override public void fill ( StringOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( wrappedCharBuffer == null ) { wrappedCharBuffer = CharBuffer . wrap ( charBuffer ) ; } else { wrappedCharBuffer . clear ( ) ; } option . reset ( ) ; if ( lookAhead == ESCAPE_CHAR ) { int c = reader . read ( ) ; if ( c == ESCAPE_NULL_COLUMN ) { option . setNull ( ) ; int next = reader . read ( ) ; if ( isSeparator ( next ) == false ) { throw new RecordFormatException ( MessageFormat . format ( "" , option . getClass ( ) . getSimpleName ( ) ) ) ; } setLastSeparator ( next ) ; fillLookAhead ( ) ; return ; } wrappedCharBuffer . append ( unescape ( c ) ) ; } else if ( isSeparator ( lookAhead ) ) { setLastSeparator ( lookAhead ) ; fillLookAhead ( ) ; return ; } else { wrappedCharBuffer . append ( ( char ) lookAhead ) ; } while ( true ) { int c = reader . read ( ) ; if ( isSeparator ( c ) ) { setLastSeparator ( c ) ; break ; } else if ( c == ESCAPE_CHAR ) { int trailing = reader . read ( ) ; wrappedCharBuffer . append ( unescape ( trailing ) ) ; } else { wrappedCharBuffer . append ( ( char ) c ) ; } if ( wrappedCharBuffer . position ( ) == wrappedCharBuffer . limit ( ) ) { wrappedCharBuffer . flip ( ) ; append ( wrappedCharBuffer , option ) ; wrappedCharBuffer . clear ( ) ; } } wrappedCharBuffer . flip ( ) ; append ( wrappedCharBuffer , option ) ; wrappedCharBuffer . clear ( ) ; fillLookAhead ( ) ; } @ Override public void fill ( DateOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } int year = toNumber ( lookAhead ) * + readNumbers ( YEAR_FIELD_LENGTH - , option ) ; consume ( DATE_FIELD_SEPARATOR ) ; int month = readNumbers ( MONTH_FIELD_LENGTH , option ) ; consume ( DATE_FIELD_SEPARATOR ) ; int day = readNumbers ( DATE_FIELD_LENGTH , option ) ; int last = reader . read ( ) ; if ( isSeparator ( last ) == false ) { throw new RecordFormatException ( MessageFormat . format ( "" , option . getClass ( ) . getSimpleName ( ) ) ) ; } setLastSeparator ( last ) ; if ( year == || month == || day == ) { option . setNull ( ) ; } else { option . modify ( DateUtil . getDayFromDate ( year , month , day ) ) ; } fillLookAhead ( ) ; } @ Override public void fill ( DateTimeOption option ) throws RecordFormatException , IOException { checkCellStart ( ) ; if ( applyNull ( option ) ) { return ; } int year = toNumber ( lookAhead ) * + readNumbers ( YEAR_FIELD_LENGTH - , option ) ; consume ( DATE_FIELD_SEPARATOR ) ; int month = readNumbers ( MONTH_FIELD_LENGTH , option ) ; consume ( DATE_FIELD_SEPARATOR ) ; int day = readNumbers ( DATE_FIELD_LENGTH , option ) ; consume ( DATE_TIME_SEPARATOR ) ; int hour = readNumbers ( HOUR_FIELD_LENGTH , option ) ; consume ( TIME_FIELD_SEPARATOR ) ; int minute = readNumbers ( MINUTE_FIELD_LENGTH , option ) ; consume ( TIME_FIELD_SEPARATOR ) ; int second = readNumbers ( SECOND_FIELD_LENGTH , option ) ; int last = reader . read ( ) ; if ( isSeparator ( last ) == false ) { throw new RecordFormatException ( MessageFormat . format ( "" , option . getClass ( ) . getSimpleName ( ) ) ) ; } setLastSeparator ( last ) ; if ( year == || month == || day == ) { option . setNull ( ) ; } else { long result = DateUtil . getDayFromDate ( year , month , day ) ; result *= * * ; result += DateUtil . getSecondFromTime ( hour , minute , second ) ; option . modify ( result ) ; } fillLookAhead ( ) ; } private int readNumbers ( int columns , ValueOption < ? > option ) throws IOException { int total = ; for ( int i = ; i < columns ; i ++ ) { int c = reader . read ( ) ; total = total * + toNumber ( c ) ; } return total ; } private void consume ( char expect ) throws IOException { int c = reader . read ( ) ; if ( c != expect ) { throw new RecordFormatException ( MessageFormat . format ( "" , expect , String . format ( "" , c ) ) ) ; } } private int toNumber ( int c ) throws RecordFormatException { if ( '' <= c && c <= '' ) { return c - '' ; } throw new RecordFormatException ( MessageFormat . format ( "" , String . format ( "" , c ) ) ) ; } private void append ( CharBuffer source , StringOption target ) throws RecordFormatException { if ( source . hasRemaining ( ) == false ) { return ; } Text text = target . get ( ) ; encoder . reset ( ) ; encodeBuffer . clear ( ) ; while ( true ) { CoderResult result = encoder . encode ( source , encodeBuffer , true ) ; if ( result . isError ( ) ) { throw new RecordFormatException ( MessageFormat . format ( "" , result ) ) ; } if ( result . isUnderflow ( ) ) { consumeEncoded ( text ) ; break ; } if ( result . isOverflow ( ) ) { consumeEncoded ( text ) ; } } while ( true ) { CoderResult result = encoder . flush ( encodeBuffer ) ; if ( result . isError ( ) ) { throw new RecordFormatException ( MessageFormat . format ( "" , result ) ) ; } if ( result . isUnderflow ( ) ) { consumeEncoded ( text ) ; break ; } if ( result . isOverflow ( ) ) { consumeEncoded ( text ) ; } } } private void consumeEncoded ( Text text ) { encodeBuffer . flip ( ) ; if ( encodeBuffer . hasRemaining ( ) ) { text . append ( encodeBuffer . array ( ) , encodeBuffer . position ( ) , encodeBuffer . limit ( ) ) ; } encodeBuffer . clear ( ) ; } private char unescape ( int c ) throws RecordFormatException { if ( c == ESCAPE_CHAR ) { return ESCAPE_CHAR ; } if ( c == ESCAPE_HT ) { return '' ; } if ( c == ESCAPE_LF ) { return '' ; } throw new RecordFormatException ( MessageFormat . format ( "" , ( char ) c , String . format ( "" , c ) ) ) ; } private int readInt ( ValueOption < ? > option ) throws IOException , RecordFormatException { boolean negative = false ; if ( lookAhead == '' ) { lookAhead = reader . read ( ) ; negative = true ; } assertHasRest ( option , lookAhead ) ; int value = toNumber ( lookAhead ) ; while ( true ) { int c = reader . read ( ) ; if ( isSeparator ( c ) ) { setLastSeparator ( c ) ; break ; } value = value * + toNumber ( c ) ; } if ( negative ) { value = - value ; } return value ; } private void setLastSeparator ( int c ) { lastSeparator = c ; } private int readString ( int start , ValueOption < ? > option ) throws IOException { int current = start ; while ( true ) { char [ ] cbuf = charBuffer ; for ( int i = current , n = cbuf . length ; i < n ; i ++ ) { int c = reader . read ( ) ; if ( isSeparator ( c ) ) { setLastSeparator ( c ) ; return i - start ; } cbuf [ i ] = ( char ) c ; } current = cbuf . length ; expandCharBuffer ( ) ; } } private void expandCharBuffer ( ) { char [ ] newBuffer = new char [ charBuffer . length * ] ; System . arraycopy ( charBuffer , , newBuffer , , charBuffer . length ) ; charBuffer = newBuffer ; wrappedCharBuffer = null ; } private static boolean isSeparator ( int c ) { return c == - || c == CELL_SEPARATOR || c == RECORD_SEPARATOR ; } private void assertHasRest ( ValueOption < ? > option , int c ) throws RecordFormatException { if ( isSeparator ( c ) ) { throw new RecordFormatException ( MessageFormat . format ( "" , option . getClass ( ) . getSimpleName ( ) ) ) ; } } private boolean applyNull ( ValueOption < ? > option ) throws RecordFormatException , IOException { if ( lookAhead != ESCAPE_CHAR ) { return false ; } int c = reader . read ( ) ; if ( c == ESCAPE_NULL_COLUMN ) { option . setNull ( ) ; int next = reader . read ( ) ; if ( isSeparator ( next ) == false ) { throw new RecordFormatException ( MessageFormat . format ( "" , option . getClass ( ) . getSimpleName ( ) ) ) ; } setLastSeparator ( next ) ; fillLookAhead ( ) ; return true ; } else { throw new RecordFormatException ( MessageFormat . format ( "" , option . getClass ( ) . getSimpleName ( ) , new StringBuilder ( ) . append ( ESCAPE_CHAR ) . append ( ESCAPE_NULL_COLUMN ) ) ) ; } } @ Override public void endRecord ( ) throws RecordFormatException , IOException { if ( lastSeparator != RECORD_SEPARATOR ) { throw new RecordFormatException ( "" ) ; } } @ Override public void close ( ) throws IOException { reader . close ( ) ; } } package com . asakusafw . runtime . io ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . lang . reflect . Constructor ; import java . text . MessageFormat ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; public abstract class ModelIoFactory < T > { static final Log LOG = LogFactory . getLog ( ModelIoFactory . class ) ; static final Pattern MODEL_CLASS_NAME_PATTERN = Pattern . compile ( "" ) ; public static final String MODEL_INPUT_CLASS_FORMAT = "" ; public static final String MODEL_OUTPUT_CLASS_FORMAT = "" ; private final Class < T > modelClass ; public ModelIoFactory ( Class < T > modelClass ) { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . modelClass = modelClass ; } protected Class < T > getModelClass ( ) { return modelClass ; } public T createModelObject ( ) throws IOException { try { return modelClass . newInstance ( ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , getClass ( ) . getName ( ) ) , e ) ; } } public ModelInput < T > createModelInput ( InputStream in ) throws IOException { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } RecordParser parser = createRecordParser ( in ) ; return createModelInput ( parser ) ; } public ModelInput < T > createModelInput ( RecordParser parser ) throws IOException { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } Class < ? > inputClass ; try { inputClass = findModelInputClass ( ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( MessageFormat . format ( "" , modelClass . getName ( ) ) , e ) ; } try { Constructor < ? > ctor = inputClass . getConstructor ( RecordParser . class ) ; @ SuppressWarnings ( "" ) ModelInput < T > instance = ( ModelInput < T > ) ctor . newInstance ( parser ) ; return instance ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , modelClass . getName ( ) ) , e ) ; } } public ModelOutput < T > createModelOutput ( OutputStream out ) throws IOException { if ( out == null ) { throw new IllegalArgumentException ( "" ) ; } RecordEmitter emitter = createRecordEmitter ( out ) ; return createModelOutput ( emitter ) ; } public ModelOutput < T > createModelOutput ( RecordEmitter emitter ) throws IOException { if ( emitter == null ) { throw new IllegalArgumentException ( "" ) ; } Class < ? > outputClass ; try { outputClass = findModelOutputClass ( ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( MessageFormat . format ( "" , modelClass . getName ( ) ) , e ) ; } try { Constructor < ? > ctor = outputClass . getConstructor ( RecordEmitter . class ) ; @ SuppressWarnings ( "" ) ModelOutput < T > instance = ( ModelOutput < T > ) ctor . newInstance ( emitter ) ; return instance ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , modelClass . getName ( ) ) , e ) ; } } protected abstract RecordParser createRecordParser ( InputStream in ) throws IOException ; protected abstract RecordEmitter createRecordEmitter ( OutputStream out ) throws IOException ; protected Class < ? > findModelInputClass ( ) throws ClassNotFoundException { ModelInputLocation annotation = modelClass . getAnnotation ( ModelInputLocation . class ) ; if ( annotation != null ) { return annotation . value ( ) ; } LOG . warn ( MessageFormat . format ( "" , modelClass . getName ( ) , ModelInputLocation . class . getName ( ) , ModelInput . class . getSimpleName ( ) ) ) ; return findClassFromModel ( MODEL_INPUT_CLASS_FORMAT ) ; } protected Class < ? > findModelOutputClass ( ) throws ClassNotFoundException { ModelOutputLocation annotation = modelClass . getAnnotation ( ModelOutputLocation . class ) ; if ( annotation != null ) { return annotation . value ( ) ; } LOG . warn ( MessageFormat . format ( "" , modelClass . getName ( ) , ModelOutputLocation . class . getName ( ) , ModelOutput . class . getSimpleName ( ) ) ) ; return findClassFromModel ( MODEL_OUTPUT_CLASS_FORMAT ) ; } private Class < ? > findClassFromModel ( String format ) throws ClassNotFoundException { Matcher m = MODEL_CLASS_NAME_PATTERN . matcher ( modelClass . getName ( ) ) ; if ( m . matches ( ) == false ) { throw new ClassNotFoundException ( MessageFormat . format ( "" , modelClass . getName ( ) ) ) ; } String qualifier = m . group ( ) ; String simpleName = m . group ( ) ; String result = MessageFormat . format ( format , qualifier , simpleName ) ; return Class . forName ( result , false , modelClass . getClassLoader ( ) ) ; } } package com . asakusafw . runtime . util ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Map ; import java . util . TreeMap ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class VariableTable { private static final Pattern VARIABLE = Pattern . compile ( "" ) ; private final RedefineStrategy redefineStrategy ; private final Map < String , String > variables = new HashMap < String , String > ( ) ; public VariableTable ( ) { this ( RedefineStrategy . ERROR ) ; } public VariableTable ( RedefineStrategy redefineStrategy ) { if ( redefineStrategy == null ) { throw new IllegalArgumentException ( "" ) ; } this . redefineStrategy = redefineStrategy ; } public static String toVariable ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } String expr = "" + name + "" ; if ( VARIABLE . matcher ( expr ) . matches ( ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } return expr ; } public void defineVariable ( String name , String replacement ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( replacement == null ) { throw new IllegalArgumentException ( "" ) ; } if ( redefineStrategy != RedefineStrategy . OVERWRITE && variables . containsKey ( name ) ) { if ( redefineStrategy == RedefineStrategy . ERROR ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , this ) ) ; } } else { this . variables . put ( name , replacement ) ; } } public void defineVariables ( Map < String , String > variableMap ) { if ( variableMap == null ) { throw new IllegalArgumentException ( "" ) ; } for ( Map . Entry < String , String > entry : variableMap . entrySet ( ) ) { defineVariable ( entry . getKey ( ) , entry . getValue ( ) ) ; } } public String toSerialString ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : variables . entrySet ( ) ) { buf . append ( escape ( entry . getKey ( ) ) ) ; buf . append ( "" ) ; buf . append ( escape ( entry . getValue ( ) ) ) ; buf . append ( "" ) ; } if ( buf . length ( ) >= ) { buf . deleteCharAt ( buf . length ( ) - ) ; } return buf . toString ( ) ; } private static final Pattern TO_ESCAPED = Pattern . compile ( "" ) ; private String escape ( String string ) { assert string != null ; return TO_ESCAPED . matcher ( string ) . replaceAll ( "" ) ; } private static final Pattern PAIRS = Pattern . compile ( "" ) ; private static final Pattern KEY_VALUE = Pattern . compile ( "" ) ; public void defineVariables ( String variableList ) { if ( variableList == null ) { throw new IllegalArgumentException ( "" ) ; } String [ ] pairs = PAIRS . split ( variableList ) ; for ( String pair : pairs ) { if ( pair . isEmpty ( ) ) { continue ; } String [ ] kv = KEY_VALUE . split ( pair ) ; if ( kv . length == ) { defineVariable ( "" , "" ) ; } else if ( kv . length == && kv [ ] . equals ( pair ) == false ) { defineVariable ( unescape ( kv [ ] ) , "" ) ; } else if ( kv . length == ) { defineVariable ( unescape ( kv [ ] ) , unescape ( kv [ ] ) ) ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , pair , variableList ) ) ; } } } private String unescape ( String string ) { assert string != null ; StringBuilder buf = new StringBuilder ( ) ; int start = ; while ( true ) { int index = string . indexOf ( '' , start ) ; if ( index < ) { break ; } buf . append ( string . substring ( start , index ) ) ; if ( index != string . length ( ) - ) { buf . append ( string . charAt ( index + ) ) ; start = index + ; } else { buf . append ( string . charAt ( index ) ) ; start = index + ; } } if ( start < string . length ( ) ) { buf . append ( string . substring ( start ) ) ; } return buf . toString ( ) ; } public Map < String , String > getVariables ( ) { return new TreeMap < String , String > ( variables ) ; } public String parse ( String string ) { return parse ( string , true ) ; } public String parse ( String string , boolean strict ) { if ( string == null ) { throw new IllegalArgumentException ( "" ) ; } StringBuilder buf = new StringBuilder ( ) ; int start = ; Matcher matcher = VARIABLE . matcher ( string ) ; while ( matcher . find ( start ) ) { String name = matcher . group ( ) ; String replacement = variables . get ( name ) ; if ( replacement == null ) { if ( strict ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , this ) ) ; } else { buf . append ( string . substring ( start , matcher . start ( ) ) ) ; buf . append ( matcher . group ( ) ) ; } } else { buf . append ( string . substring ( start , matcher . start ( ) ) ) ; buf . append ( replacement ) ; } start = matcher . end ( ) ; } buf . append ( string . substring ( start ) ) ; return buf . toString ( ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , variables . toString ( ) ) ; } public enum RedefineStrategy { OVERWRITE , IGNORE , ERROR , } } package com . asakusafw . runtime . util . hadoop ; package com . asakusafw . runtime . util . hadoop ; import java . io . File ; import java . io . IOException ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLClassLoader ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . text . MessageFormat ; import java . util . Map ; import java . util . regex . Pattern ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; public class ConfigurationProvider { private static final String ENV_PATH = "" ; private static final String ENV_HADOOP_CONF = "" ; private static final String ENV_HADOOP_HOME = "" ; private static final String PATH_HADOOP_COMMAND_FILE = "" ; private static final String PATH_HADOOP_COMMAND = "" ; private static final String PATH_CONF_DIR_0 = "" ; private static final String PATH_CONF_DIR_0_TESTER = "" ; private static final String PATH_CONF_DIR_1 = "" ; static final Log LOG = LogFactory . getLog ( ConfigurationProvider . class ) ; private final ClassLoader loader ; public ConfigurationProvider ( ) { this ( System . getenv ( ) ) ; } ConfigurationProvider ( Map < String , String > envp ) { this ( getConfigurationPath ( envp ) ) ; } public ConfigurationProvider ( URL defaultConfigPath ) { ClassLoader current = getBaseClassLoader ( ) ; this . loader = createLoader ( current , defaultConfigPath ) ; } private static URL getConfigurationPath ( Map < String , String > envp ) { File conf = getConfigurationDirectory ( envp ) ; if ( conf == null || conf . isDirectory ( ) == false ) { LOG . warn ( MessageFormat . format ( "" , conf ) ) ; return null ; } try { return conf . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { LOG . warn ( MessageFormat . format ( "" , conf ) , e ) ; return null ; } } private static File getConfigurationDirectory ( Map < String , String > envp ) { File explicit = getExplicitConfigurationDirectory ( envp ) ; if ( explicit != null ) { return explicit ; } File implicit = getImplicitConfigurationDirectory ( envp ) ; return implicit ; } private static File getExplicitConfigurationDirectory ( Map < String , String > envp ) { String conf = envp . get ( ENV_HADOOP_CONF ) ; if ( conf == null ) { LOG . debug ( MessageFormat . format ( "" , ENV_HADOOP_CONF ) ) ; return null ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , ENV_HADOOP_CONF , conf ) ) ; } return new File ( conf ) ; } private static File getImplicitConfigurationDirectory ( Map < String , String > envp ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" ) ; } File command = findHadoopCommand ( envp ) ; if ( command == null ) { return null ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , command ) ) ; } File home = getHadoopInstallationPath ( command ) ; if ( home == null ) { return null ; } if ( new File ( home , PATH_CONF_DIR_0_TESTER ) . exists ( ) ) { return new File ( home , PATH_CONF_DIR_0 ) ; } return new File ( home , PATH_CONF_DIR_1 ) ; } public static File findHadoopCommand ( ) { return findHadoopCommand ( System . getenv ( ) ) ; } static File findHadoopCommand ( Map < String , String > envp ) { File command = null ; File home = getExplicitHadoopDirectory ( envp ) ; if ( home != null && home . isDirectory ( ) ) { command = new File ( home , PATH_HADOOP_COMMAND ) ; } else { command = findHadoopCommandFromPath ( envp ) ; } if ( command == null || command . canExecute ( ) == false ) { return null ; } return command ; } private static File getExplicitHadoopDirectory ( Map < String , String > envp ) { String homeString = envp . get ( ENV_HADOOP_HOME ) ; if ( homeString == null ) { LOG . debug ( MessageFormat . format ( "" , ENV_HADOOP_HOME ) ) ; return null ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , ENV_HADOOP_HOME , homeString ) ) ; } File home = new File ( homeString ) ; return home ; } private static File getHadoopInstallationPath ( File command ) { assert command != null ; File resolved ; try { resolved = command . getCanonicalFile ( ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , command ) , e ) ; resolved = command ; } File parent1 = resolved . getParentFile ( ) ; if ( parent1 == null || parent1 . isDirectory ( ) == false ) { return null ; } File parent2 = parent1 . getParentFile ( ) ; if ( parent2 == null || parent2 . isDirectory ( ) == false ) { return null ; } return parent2 ; } private static File findHadoopCommandFromPath ( Map < String , String > envp ) { String path = envp . get ( ENV_PATH ) ; if ( path != null && path . trim ( ) . isEmpty ( ) == false ) { String [ ] pathPrefixArray = path . split ( Pattern . quote ( File . pathSeparator ) ) ; for ( String prefix : pathPrefixArray ) { String p = prefix . trim ( ) ; if ( p . isEmpty ( ) ) { continue ; } File bin = new File ( p ) ; if ( bin . isDirectory ( ) == false ) { continue ; } File command = new File ( bin , PATH_HADOOP_COMMAND_FILE ) ; if ( command . canExecute ( ) ) { return command ; } } } return null ; } private ClassLoader getBaseClassLoader ( ) { ClassLoader current = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( current == null ) { current = getClass ( ) . getClassLoader ( ) ; } return current ; } private ClassLoader createLoader ( final ClassLoader current , final URL defaultConfigPath ) { if ( defaultConfigPath != null ) { ClassLoader ehnahced = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) { return new URLClassLoader ( new URL [ ] { defaultConfigPath } , current ) ; } } ) ; if ( ehnahced != null ) { return ehnahced ; } } return current ; } public Configuration newInstance ( ) { ClassLoader context = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( loader ) ; Configuration conf = new Configuration ( true ) ; configure ( conf ) ; return conf ; } finally { Thread . currentThread ( ) . setContextClassLoader ( context ) ; } } protected void configure ( Configuration configuration ) { return ; } } package com . asakusafw . runtime . util ; package com . asakusafw . runtime . util ; import java . lang . reflect . ParameterizedType ; import java . lang . reflect . Type ; import java . lang . reflect . TypeVariable ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . NoSuchElementException ; public final class TypeUtil { public static Class < ? > erase ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } GenericContext generic = toGenericContext ( type ) ; if ( generic == null ) { throw new IllegalArgumentException ( "" ) ; } return generic . raw ; } public static List < Type > invoke ( Class < ? > target , Type context ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target . isPrimitive ( ) || target . isArray ( ) ) { throw new IllegalArgumentException ( "" ) ; } if ( target == Object . class ) { return Collections . emptyList ( ) ; } GenericContext generic = toGenericContext ( context ) ; if ( generic == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target . isAssignableFrom ( generic . raw ) == false ) { return null ; } if ( target . getTypeParameters ( ) . length == ) { return Collections . emptyList ( ) ; } if ( target . isInterface ( ) ) { return invokeInterface ( target , generic ) ; } if ( generic . raw . isInterface ( ) ) { return null ; } return invokeClass ( target , generic ) ; } private static List < Type > invokeClass ( Class < ? > target , GenericContext context ) { assert target != null ; assert context != null ; assert target . isInterface ( ) == false ; assert context . raw . isInterface ( ) == false ; for ( GenericContext current = context . getSuperClass ( ) ; current != null ; current = current . getSuperClass ( ) ) { if ( current . raw == target ) { return current . getTypeArguments ( ) ; } } return null ; } private static List < Type > invokeInterface ( Class < ? > target , GenericContext context ) { assert target != null ; assert context != null ; assert target . isInterface ( ) ; GenericContext bottom = findBottomClass ( target , context ) ; if ( bottom == null ) { return null ; } if ( target == bottom . raw ) { return bottom . getTypeArguments ( ) ; } return findInterface ( target , bottom ) ; } private static List < Type > findInterface ( Class < ? > target , GenericContext context ) { assert target != null ; assert context != null ; assert target . isAssignableFrom ( context . raw ) ; Iterator < GenericContext > iter = context . getSuperInterfaces ( ) ; while ( iter . hasNext ( ) ) { GenericContext intf = iter . next ( ) ; if ( target == intf . raw ) { return intf . getTypeArguments ( ) ; } if ( target . isAssignableFrom ( intf . raw ) ) { return findInterface ( target , intf ) ; } } throw new AssertionError ( target ) ; } private static GenericContext findBottomClass ( Class < ? > target , GenericContext context ) { assert target != null ; assert context != null ; GenericContext bottom = null ; for ( GenericContext current = context ; current != null ; current = current . getSuperClass ( ) ) { if ( target . isAssignableFrom ( current . raw ) ) { bottom = current ; } else { break ; } } return bottom ; } private static GenericContext toGenericContext ( Type context ) { assert context != null ; if ( context instanceof Class < ? > ) { return new GenericContext ( ( Class < ? > ) context ) ; } if ( context instanceof ParameterizedType ) { ParameterizedType t = ( ParameterizedType ) context ; Class < ? > raw = ( Class < ? > ) t . getRawType ( ) ; TypeVariable < ? > [ ] params = raw . getTypeParameters ( ) ; Type [ ] args = t . getActualTypeArguments ( ) ; if ( params . length != args . length ) { return new GenericContext ( raw ) ; } LinkedHashMap < TypeVariable < ? > , Type > mapping = new LinkedHashMap < TypeVariable < ? > , Type > ( ) ; for ( int i = ; i < params . length ; i ++ ) { mapping . put ( params [ i ] , args [ i ] ) ; } return new GenericContext ( raw , mapping ) ; } return null ; } private TypeUtil ( ) { throw new AssertionError ( ) ; } static GenericContext analyze ( Type type , Map < TypeVariable < ? > , Type > mapping ) { assert type != null ; assert mapping != null ; Type subst = substitute ( type , mapping ) ; if ( subst == null ) { return null ; } return toGenericContext ( subst ) ; } private static Type substitute ( Type type , Map < TypeVariable < ? > , Type > mapping ) { assert type != null ; assert mapping != null ; if ( type instanceof Class < ? > ) { return type ; } if ( type instanceof TypeVariable < ? > ) { return mapping . get ( type ) ; } if ( type instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) type ; Class < ? > raw = ( Class < ? > ) pt . getRawType ( ) ; List < Type > arguments = new ArrayList < Type > ( ) ; for ( Type t : pt . getActualTypeArguments ( ) ) { Type subst = substitute ( t , mapping ) ; if ( subst == null ) { return raw ; } arguments . add ( subst ) ; } return new SimpleParameterizedType ( raw , arguments ) ; } return null ; } private static class GenericContext { final Class < ? > raw ; final LinkedHashMap < TypeVariable < ? > , Type > mapping ; GenericContext ( Class < ? > raw ) { this . raw = raw ; this . mapping = new LinkedHashMap < TypeVariable < ? > , Type > ( ) ; } GenericContext ( Class < ? > raw , LinkedHashMap < TypeVariable < ? > , Type > mapping ) { this . raw = raw ; this . mapping = mapping ; } public List < Type > getTypeArguments ( ) { return new ArrayList < Type > ( mapping . values ( ) ) ; } public GenericContext getSuperClass ( ) { if ( raw . getSuperclass ( ) == null ) { return null ; } Type parent = raw . getGenericSuperclass ( ) ; return analyze ( parent , mapping ) ; } public Iterator < GenericContext > getSuperInterfaces ( ) { return new Iterator < TypeUtil . GenericContext > ( ) { Type [ ] interfaces = raw . getGenericInterfaces ( ) ; int index = ; @ Override public boolean hasNext ( ) { return index < interfaces . length ; } @ Override public GenericContext next ( ) { if ( hasNext ( ) == false ) { throw new NoSuchElementException ( ) ; } return analyze ( interfaces [ index ++ ] , mapping ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } } private static class SimpleParameterizedType implements ParameterizedType { private final Class < ? > rawType ; private final List < Type > typeArguments ; SimpleParameterizedType ( Class < ? > rawType , List < Type > typeArguments ) { this . rawType = rawType ; this . typeArguments = typeArguments ; } @ Override public Type [ ] getActualTypeArguments ( ) { return typeArguments . toArray ( new Type [ typeArguments . size ( ) ] ) ; } @ Override public Type getRawType ( ) { return rawType ; } @ Override public Type getOwnerType ( ) { return rawType . getDeclaringClass ( ) ; } } } package com . asakusafw . runtime . report ; package com . asakusafw . runtime . report ; import java . text . MessageFormat ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import com . asakusafw . runtime . core . Report ; import com . asakusafw . runtime . core . Report . Level ; public class CommonsLoggingReport extends Report . Delegate { static final Log LOG = LogFactory . getLog ( CommonsLoggingReport . class ) ; @ Override protected void report ( Level level , String message ) { if ( level == Level . ERROR ) { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( message , new Exception ( "" ) ) ; } } else if ( level == Level . WARN ) { if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( message , new Exception ( "" ) ) ; } } else if ( level == Level . INFO ) { LOG . info ( message ) ; } else { LOG . fatal ( MessageFormat . format ( "" , level , message ) ) ; } } } package com . asakusafw . runtime . testing ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOError ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; public final class TestingUtils { private TestingUtils ( ) { return ; } public static void append ( String path , String message ) { File file = new File ( path ) ; try { OutputStream output = new FileOutputStream ( file , true ) ; try { PrintWriter w = new PrintWriter ( new OutputStreamWriter ( output , "" ) ) ; w . println ( message ) ; w . close ( ) ; } finally { output . close ( ) ; } } catch ( IOException e ) { throw new IOError ( e ) ; } } } package com . asakusafw . runtime . testing ; package com . asakusafw . runtime . testing ; import java . util . ArrayList ; import java . util . List ; import com . asakusafw . runtime . core . Result ; public class MockResult < T > implements Result < T > { private List < T > results = new ArrayList < T > ( ) ; public static < T > MockResult < T > create ( ) { return new MockResult < T > ( ) ; } @ Override public void add ( T result ) { T blessed = bless ( result ) ; results . add ( blessed ) ; } protected T bless ( T result ) { return result ; } public List < T > getResults ( ) { return results ; } } package com . asakusafw . runtime . stage . directio ; package com . asakusafw . runtime . stage . directio ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . util . ReflectionUtils ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . io . util . WritableRawComparableUnion ; public class DirectOutputSpec { private final Class < ? extends Writable > valueType ; private final String path ; private final Class < ? extends DataFormat < ? > > formatClass ; private final Class < ? extends StringTemplate > namingClass ; private final Class < ? extends DirectOutputOrder > orderClass ; public DirectOutputSpec ( Class < ? extends Writable > valueType , String path , Class < ? extends DataFormat < ? > > formatClass , Class < ? extends StringTemplate > namingClass , Class < ? extends DirectOutputOrder > orderClass ) { if ( valueType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } if ( formatClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( namingClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( orderClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . valueType = valueType ; this . path = path ; this . formatClass = formatClass ; this . namingClass = namingClass ; this . orderClass = orderClass ; } static Class < ? > [ ] getValueTypes ( DirectOutputSpec [ ] specs ) { if ( specs == null ) { throw new IllegalArgumentException ( "" ) ; } Class < ? > [ ] results = new Class < ? > [ specs . length ] ; for ( int i = ; i < specs . length ; i ++ ) { DirectOutputSpec spec = specs [ i ] ; if ( spec == null ) { results [ i ] = DirectOutputGroup . EMPTY . getDataType ( ) ; } else { results [ i ] = specs [ i ] . valueType ; } } return results ; } static WritableRawComparableUnion createGroupUnion ( DirectOutputSpec [ ] specs ) { if ( specs == null ) { throw new IllegalArgumentException ( "" ) ; } DirectOutputGroup [ ] elements = new DirectOutputGroup [ specs . length ] ; for ( int i = ; i < specs . length ; i ++ ) { DirectOutputSpec spec = specs [ i ] ; if ( spec == null ) { elements [ i ] = DirectOutputGroup . EMPTY ; } else { elements [ i ] = spec . createGroup ( ) ; } } return new WritableRawComparableUnion ( elements ) ; } static WritableRawComparableUnion createOrderUnion ( DirectOutputSpec [ ] specs ) { if ( specs == null ) { throw new IllegalArgumentException ( "" ) ; } DirectOutputOrder [ ] elements = new DirectOutputOrder [ specs . length ] ; for ( int i = ; i < specs . length ; i ++ ) { DirectOutputSpec spec = specs [ i ] ; if ( spec == null ) { elements [ i ] = DirectOutputOrder . EMPTY ; } else { elements [ i ] = spec . createOrder ( ) ; } } return new WritableRawComparableUnion ( elements ) ; } private DirectOutputGroup createGroup ( ) { DataFormat < ? > format = ReflectionUtils . newInstance ( formatClass , null ) ; StringTemplate nameGenerator = ReflectionUtils . newInstance ( namingClass , null ) ; return new DirectOutputGroup ( path , valueType , format , nameGenerator ) ; } private DirectOutputOrder createOrder ( ) { DirectOutputOrder order = ReflectionUtils . newInstance ( orderClass , null ) ; return order ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( valueType ) ; builder . append ( "" ) ; builder . append ( path ) ; builder . append ( "" ) ; builder . append ( formatClass ) ; builder . append ( "" ) ; builder . append ( namingClass ) ; builder . append ( "" ) ; builder . append ( orderClass ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . runtime . stage . directio ; import java . io . IOException ; import org . apache . hadoop . mapreduce . Mapper ; import org . apache . hadoop . util . ReflectionUtils ; import com . asakusafw . runtime . model . DataModel ; public abstract class AbstractDirectOutputMapper < T extends DataModel < T > > extends Mapper < Object , T , AbstractDirectOutputKey , AbstractDirectOutputValue > { private final AbstractDirectOutputKey outputKey ; private final T outputValue ; private final AbstractDirectOutputValue outputValueUnion ; @ SuppressWarnings ( "" ) protected AbstractDirectOutputMapper ( int position , Class < ? extends AbstractDirectOutputKey > keyClass , Class < ? extends AbstractDirectOutputValue > valueClass ) { this . outputKey = ReflectionUtils . newInstance ( keyClass , null ) ; this . outputValueUnion = ReflectionUtils . newInstance ( valueClass , null ) ; this . outputKey . setPosition ( position ) ; this . outputValue = ( T ) outputValueUnion . switchObject ( position ) ; } @ Override protected void map ( Object key , T value , Context context ) throws IOException , InterruptedException { outputKey . setObject ( value ) ; outputValue . copyFrom ( value ) ; context . write ( outputKey , outputValueUnion ) ; } } package com . asakusafw . runtime . stage . directio ; import com . asakusafw . runtime . io . util . ShuffleKey ; import com . asakusafw . runtime . io . util . WritableRawComparableUnion ; public abstract class AbstractDirectOutputKey extends ShuffleKey < WritableRawComparableUnion , WritableRawComparableUnion > { protected AbstractDirectOutputKey ( DirectOutputSpec ... specs ) { super ( DirectOutputSpec . createGroupUnion ( specs ) , DirectOutputSpec . createOrderUnion ( specs ) ) ; } public void setPosition ( int position ) { getGroupObject ( ) . switchObject ( position ) ; getOrderObject ( ) . switchObject ( position ) ; } public void setObject ( Object value ) { DirectOutputGroup groupValue = ( DirectOutputGroup ) getGroupObject ( ) . getObject ( ) ; groupValue . set ( value ) ; DirectOutputOrder orderValue = ( DirectOutputOrder ) getOrderObject ( ) . getObject ( ) ; orderValue . set ( value ) ; } } package com . asakusafw . runtime . stage . directio ; import com . asakusafw . runtime . io . util . WritableUnion ; public abstract class AbstractDirectOutputValue extends WritableUnion { protected AbstractDirectOutputValue ( DirectOutputSpec ... specs ) { super ( DirectOutputSpec . getValueTypes ( specs ) ) ; } } package com . asakusafw . runtime . stage . directio ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . regex . Pattern ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . mapreduce . Mapper ; import org . apache . hadoop . util . ReflectionUtils ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . runtime . util . VariableTable ; public abstract class AbstractNoReduceDirectOutputMapper < T > extends Mapper < Object , T , Object , Object > { private static final String COUNTER_GROUP = "" ; private final Log log ; private final Class < ? extends T > dataType ; private final String rawBasePath ; private final String rawResourcePath ; private final Class < ? extends DataFormat < ? super T > > dataFormatClass ; public AbstractNoReduceDirectOutputMapper ( Class < ? extends T > dataType , String rawBasePath , String rawResourcePath , Class < ? extends DataFormat < ? super T > > dataFormatClass ) { if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rawBasePath == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rawResourcePath == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataFormatClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . log = LogFactory . getLog ( getClass ( ) ) ; this . dataType = dataType ; this . rawBasePath = rawBasePath ; this . rawResourcePath = rawResourcePath ; this . dataFormatClass = dataFormatClass ; } @ Override public void run ( Context context ) throws IOException , InterruptedException { if ( context . nextKeyValue ( ) == false ) { if ( log . isDebugEnabled ( ) ) { log . debug ( MessageFormat . format ( "" , getClass ( ) . getName ( ) , context . getTaskAttemptID ( ) ) ) ; } } else { if ( log . isDebugEnabled ( ) ) { log . debug ( MessageFormat . format ( "" , getClass ( ) . getName ( ) , context . getTaskAttemptID ( ) ) ) ; } DirectDataSourceRepository repository = HadoopDataSourceUtil . loadRepository ( context . getConfiguration ( ) ) ; String arguments = context . getConfiguration ( ) . get ( StageConstants . PROP_ASAKUSA_BATCH_ARGS , "" ) ; VariableTable variables = new VariableTable ( VariableTable . RedefineStrategy . IGNORE ) ; variables . defineVariables ( arguments ) ; String path = variables . parse ( rawBasePath , false ) ; String id = repository . getRelatedId ( path ) ; OutputAttemptContext outputContext = HadoopDataSourceUtil . createContext ( context , id ) ; DataFormat < ? super T > format = ReflectionUtils . newInstance ( dataFormatClass , context . getConfiguration ( ) ) ; DirectDataSource datasource = repository . getRelatedDataSource ( path ) ; String basePath = repository . getComponentPath ( path ) ; String unresolvedResourcePath = rawResourcePath . replaceAll ( Pattern . quote ( "" ) , String . format ( "" , context . getTaskAttemptID ( ) . getTaskID ( ) . getId ( ) ) ) ; String resourcePath = variables . parse ( unresolvedResourcePath ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( MessageFormat . format ( "" , id , basePath , resourcePath ) ) ; } int records = ; ModelOutput < ? super T > output = datasource . openOutput ( outputContext , dataType , format , basePath , resourcePath , outputContext . getCounter ( ) ) ; try { do { output . write ( context . getCurrentValue ( ) ) ; records ++ ; } while ( context . nextKeyValue ( ) ) ; } finally { if ( log . isDebugEnabled ( ) ) { log . debug ( MessageFormat . format ( "" , getClass ( ) . getName ( ) , context . getTaskAttemptID ( ) ) ) ; } output . close ( ) ; } org . apache . hadoop . mapreduce . Counter recordCounter = context . getCounter ( org . apache . hadoop . mapred . Task . Counter . MAP_OUTPUT_RECORDS ) ; recordCounter . increment ( records ) ; context . getCounter ( COUNTER_GROUP , id + "" ) . increment ( ) ; context . getCounter ( COUNTER_GROUP , id + "" ) . increment ( records ) ; context . getCounter ( COUNTER_GROUP , id + "" ) . increment ( outputContext . getCounter ( ) . get ( ) ) ; } } } package com . asakusafw . runtime . stage . directio ; import com . asakusafw . runtime . io . util . WritableRawComparable ; import com . asakusafw . runtime . io . util . WritableRawComparableTuple ; public abstract class DirectOutputOrder extends WritableRawComparableTuple { public static final DirectOutputOrder EMPTY = new DirectOutputOrder ( ) { @ Override public void set ( Object object ) { return ; } } ; protected DirectOutputOrder ( WritableRawComparable ... objects ) { super ( objects ) ; } public abstract void set ( Object object ) ; } package com . asakusafw . runtime . stage . directio ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . DateFormat ; import java . text . SimpleDateFormat ; import java . util . Arrays ; import java . util . Calendar ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . WritableComparator ; import org . apache . hadoop . io . WritableUtils ; import com . asakusafw . runtime . io . util . WritableRawComparable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DateUtil ; public abstract class StringTemplate implements WritableRawComparable { public static final StringTemplate EMPTY = new StringTemplate ( ) { @ Override public void set ( Object object ) { return ; } } ; private final PropertyFormatter [ ] formatters ; private final Text nameBuffer = new Text ( ) ; protected StringTemplate ( FormatSpec ... specs ) { if ( specs == null ) { throw new IllegalArgumentException ( "" ) ; } this . formatters = new PropertyFormatter [ specs . length ] ; for ( int i = ; i < specs . length ; i ++ ) { formatters [ i ] = specs [ i ] . newFormatter ( ) ; } } public abstract void set ( Object object ) ; protected final void setProperty ( int index , Object value ) { formatters [ index ] . set ( value ) ; } public final String apply ( ) { nameBuffer . clear ( ) ; for ( int i = ; i < formatters . length ; i ++ ) { Text text = formatters [ i ] . representation ; nameBuffer . append ( text . getBytes ( ) , , text . getLength ( ) ) ; } return nameBuffer . toString ( ) ; } @ Override public final void write ( DataOutput out ) throws IOException { for ( int i = ; i < formatters . length ; i ++ ) { formatters [ i ] . write ( out ) ; } } @ Override public final void readFields ( DataInput in ) throws IOException { for ( int i = ; i < formatters . length ; i ++ ) { formatters [ i ] . readFields ( in ) ; } } @ Override public final int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { int cursor = ; for ( int i = ; i < formatters . length ; i ++ ) { int metaSize = WritableUtils . decodeVIntSize ( buf [ offset + cursor ] ) ; int bodySize = WritableComparator . readVInt ( buf , offset + cursor ) ; cursor += metaSize + bodySize ; } return cursor ; } @ Override public final int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { int l1 = getSizeInBytes ( b1 , o1 ) ; int l2 = getSizeInBytes ( b2 , o2 ) ; return WritableComparator . compareBytes ( b1 , o1 , l1 , b2 , o2 , l2 ) ; } @ Override public final int compareTo ( WritableRawComparable o ) { assert this . getClass ( ) == o . getClass ( ) ; if ( this == o ) { return ; } PropertyFormatter [ ] fs1 = formatters ; PropertyFormatter [ ] fs2 = ( ( StringTemplate ) o ) . formatters ; for ( int i = , n = fs1 . length ; i < n ; i ++ ) { int diff = fs1 [ i ] . representation . compareTo ( fs2 [ i ] . representation ) ; if ( diff != ) { return diff ; } } return ; } @ Override public final int hashCode ( ) { return Arrays . hashCode ( formatters ) ; } @ Override public final boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } StringTemplate other = ( StringTemplate ) obj ; return Arrays . equals ( formatters , other . formatters ) ; } public enum Format { PLAIN { @ Override public PropertyFormatter newFormatter ( String formatString ) { return new Constant ( formatString ) ; } @ Override public void check ( java . lang . reflect . Type valueType , String formatString ) { if ( formatString == null ) { throw new IllegalArgumentException ( "" ) ; } } } , NATURAL { @ Override public PropertyFormatter newFormatter ( String formatString ) { return new Variable ( ) { @ Override void set ( Object propertyValue ) { representation . set ( String . valueOf ( propertyValue ) ) ; } } ; } @ Override public void check ( java . lang . reflect . Type valueType , String formatString ) { if ( formatString != null ) { throw new IllegalArgumentException ( "" ) ; } } } , DATE { @ Override public PropertyFormatter newFormatter ( String formatString ) { final Calendar calendar = Calendar . getInstance ( ) ; final DateFormat dateFormat = new SimpleDateFormat ( formatString ) ; return new Variable ( ) { @ Override void set ( Object propertyValue ) { DateOption option = ( DateOption ) propertyValue ; if ( option . isNull ( ) ) { representation . set ( String . valueOf ( option ) ) ; } else { Date date = option . get ( ) ; DateUtil . setDayToCalendar ( date . getElapsedDays ( ) , calendar ) ; representation . set ( String . valueOf ( dateFormat . format ( calendar . getTime ( ) ) ) ) ; } } } ; } @ Override public void check ( java . lang . reflect . Type valueType , String formatString ) { if ( valueType != DateOption . class ) { throw new IllegalArgumentException ( "" ) ; } if ( formatString == null ) { throw new IllegalArgumentException ( "" ) ; } SimpleDateFormat format = new SimpleDateFormat ( ) ; format . applyPattern ( formatString ) ; } } , DATETIME { @ Override public PropertyFormatter newFormatter ( String formatString ) { final Calendar calendar = Calendar . getInstance ( ) ; final DateFormat dateFormat = new SimpleDateFormat ( formatString ) ; return new Variable ( ) { @ Override void set ( Object propertyValue ) { DateTimeOption option = ( DateTimeOption ) propertyValue ; if ( option . isNull ( ) ) { representation . set ( String . valueOf ( option ) ) ; } else { DateTime date = option . get ( ) ; DateUtil . setSecondToCalendar ( date . getElapsedSeconds ( ) , calendar ) ; representation . set ( String . valueOf ( dateFormat . format ( calendar . getTime ( ) ) ) ) ; } } } ; } @ Override public void check ( java . lang . reflect . Type valueType , String formatString ) { if ( valueType != DateTimeOption . class ) { throw new IllegalArgumentException ( "" ) ; } if ( formatString == null ) { throw new IllegalArgumentException ( "" ) ; } SimpleDateFormat format = new SimpleDateFormat ( ) ; format . applyPattern ( formatString ) ; } } , ; public abstract PropertyFormatter newFormatter ( String formatString ) ; public abstract void check ( java . lang . reflect . Type valueType , String formatString ) ; } public static final class FormatSpec { private final Format format ; private final String string ; public FormatSpec ( Format format , String string ) { if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } this . format = format ; this . string = string ; } public Format getFormat ( ) { return format ; } public String getString ( ) { return string ; } public PropertyFormatter newFormatter ( ) { return format . newFormatter ( string ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + format . hashCode ( ) ; result = prime * result + ( ( string == null ) ? : string . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } FormatSpec other = ( FormatSpec ) obj ; if ( format != other . format ) { return false ; } if ( string == null ) { if ( other . string != null ) { return false ; } } else if ( ! string . equals ( other . string ) ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( format ) ; builder . append ( "" ) ; builder . append ( string ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } private abstract static class PropertyFormatter implements Writable { final Text representation ; PropertyFormatter ( ) { this . representation = new Text ( ) ; } abstract void set ( Object propertyValue ) ; @ Override public final int hashCode ( ) { final int prime = ; int result = ; result = prime * result + representation . hashCode ( ) ; return result ; } @ Override public final boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } PropertyFormatter other = ( PropertyFormatter ) obj ; if ( ! representation . equals ( other . representation ) ) { return false ; } return true ; } } private static final class Constant extends PropertyFormatter { Constant ( String value ) { this . representation . set ( value ) ; } @ Override void set ( Object propertyValue ) { return ; } @ Override public void write ( DataOutput out ) throws IOException { WritableUtils . writeVInt ( out , ) ; } @ Override public void readFields ( DataInput in ) throws IOException { WritableUtils . readVInt ( in ) ; } } private abstract static class Variable extends PropertyFormatter { Variable ( ) { return ; } @ Override public void write ( DataOutput out ) throws IOException { representation . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { representation . readFields ( in ) ; } } } package com . asakusafw . runtime . stage . directio ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . io . util . NullWritableRawComparable ; import com . asakusafw . runtime . io . util . WritableRawComparable ; class DirectOutputGroup implements WritableRawComparable { public static final DirectOutputGroup EMPTY = new DirectOutputGroup ( ) ; private final String path ; private final Class < ? > dataType ; private final DataFormat < ? > format ; private final StringTemplate nameGenerator ; private DirectOutputGroup ( ) { this . path = "" ; this . dataType = NullWritableRawComparable . class ; this . format = new DataFormat < NullWritableRawComparable > ( ) { @ Override public Class < NullWritableRawComparable > getSupportedType ( ) { return NullWritableRawComparable . class ; } } ; this . nameGenerator = StringTemplate . EMPTY ; } public DirectOutputGroup ( String path , Class < ? > dataType , DataFormat < ? > format , StringTemplate nameGenerator ) { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } if ( nameGenerator == null ) { throw new IllegalArgumentException ( "" ) ; } this . path = path ; this . dataType = dataType ; this . format = format ; this . nameGenerator = nameGenerator ; } public void set ( Object value ) { nameGenerator . set ( value ) ; } public String getPath ( ) { return path ; } public Class < ? > getDataType ( ) { return dataType ; } public DataFormat < ? > getFormat ( ) { return format ; } public String getResourcePath ( ) { return nameGenerator . apply ( ) ; } public final String generateName ( ) { return nameGenerator . apply ( ) ; } @ Override public final int getSizeInBytes ( byte [ ] buf , int offset ) throws IOException { return nameGenerator . getSizeInBytes ( buf , offset ) ; } @ Override public final int compareInBytes ( byte [ ] b1 , int o1 , byte [ ] b2 , int o2 ) throws IOException { return nameGenerator . compareInBytes ( b1 , o1 , b2 , o2 ) ; } @ Override public final int compareTo ( WritableRawComparable o ) { return nameGenerator . compareTo ( o ) ; } @ Override public final void write ( DataOutput out ) throws IOException { nameGenerator . write ( out ) ; } @ Override public final void readFields ( DataInput in ) throws IOException { nameGenerator . readFields ( in ) ; } @ Override public int hashCode ( ) { return nameGenerator . hashCode ( ) ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DirectOutputGroup other = ( DirectOutputGroup ) obj ; if ( ! nameGenerator . equals ( other . nameGenerator ) ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( path ) ; builder . append ( "" ) ; builder . append ( format ) ; builder . append ( "" ) ; builder . append ( nameGenerator ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . runtime . stage . directio ; import java . io . IOException ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . mapreduce . Reducer ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . util . Union ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . runtime . util . VariableTable ; public final class DirectOutputReducer extends Reducer < AbstractDirectOutputKey , AbstractDirectOutputValue , Object , Object > { private static final String COUNTER_GROUP = "" ; private org . apache . hadoop . mapreduce . Counter recordCounter ; private DirectDataSourceRepository repository ; private VariableTable variables ; @ Override protected void setup ( Context context ) throws IOException , InterruptedException { this . recordCounter = context . getCounter ( org . apache . hadoop . mapred . Task . Counter . REDUCE_OUTPUT_RECORDS ) ; this . repository = HadoopDataSourceUtil . loadRepository ( context . getConfiguration ( ) ) ; String arguments = context . getConfiguration ( ) . get ( StageConstants . PROP_ASAKUSA_BATCH_ARGS , "" ) ; this . variables = new VariableTable ( VariableTable . RedefineStrategy . IGNORE ) ; variables . defineVariables ( arguments ) ; } @ SuppressWarnings ( { "" , "" } ) @ Override protected void reduce ( AbstractDirectOutputKey key , Iterable < AbstractDirectOutputValue > values , Context context ) throws IOException , InterruptedException { DirectOutputGroup group = ( DirectOutputGroup ) key . getGroupObject ( ) . getObject ( ) ; String path = variables . parse ( group . getPath ( ) , false ) ; String id = repository . getRelatedId ( path ) ; OutputAttemptContext outputContext = HadoopDataSourceUtil . createContext ( context , id ) ; DataFormat format = configure ( context , group . getFormat ( ) ) ; DirectDataSource datasource = repository . getRelatedDataSource ( path ) ; String basePath = repository . getComponentPath ( path ) ; String resourcePath = variables . parse ( group . getResourcePath ( ) ) ; Class dataType = group . getDataType ( ) ; Counter counter = new Counter ( ) ; ModelOutput output = datasource . openOutput ( outputContext , dataType , format , basePath , resourcePath , counter ) ; long records = ; try { for ( Union union : values ) { Object object = union . getObject ( ) ; output . write ( object ) ; records ++ ; } } finally { output . close ( ) ; } recordCounter . increment ( records ) ; context . getCounter ( COUNTER_GROUP , id + "" ) . increment ( ) ; context . getCounter ( COUNTER_GROUP , id + "" ) . increment ( records ) ; context . getCounter ( COUNTER_GROUP , id + "" ) . increment ( counter . get ( ) ) ; } private < T > T configure ( Context context , T object ) { if ( object instanceof Configurable ) { ( ( Configurable ) object ) . setConf ( context . getConfiguration ( ) ) ; } return object ; } } package com . asakusafw . runtime . stage . preparator ; import java . io . IOException ; import org . apache . hadoop . mapreduce . Mapper ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . stage . output . StageOutputDriver ; public abstract class PreparatorMapper < T > extends Mapper < Object , T , Object , T > { public static final String NAME_GET_OUTPUT_NAME = "" ; private StageOutputDriver output ; private Result < T > result ; @ SuppressWarnings ( "" ) @ Override protected void setup ( Context context ) throws IOException , InterruptedException { String name = getOutputName ( ) ; this . output = new StageOutputDriver ( context ) ; this . result = ( Result < T > ) output . getResultSink ( name ) ; } public abstract String getOutputName ( ) ; @ Override protected void cleanup ( Context context ) throws IOException , InterruptedException { this . output . close ( ) ; this . output = null ; this . result = null ; } @ Override protected void map ( Object key , T value , Context context ) throws IOException , InterruptedException { result . add ( value ) ; } } package com . asakusafw . runtime . stage . preparator ; package com . asakusafw . runtime . stage . collector ; package com . asakusafw . runtime . stage . collector ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . mapreduce . Reducer ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . stage . output . StageOutputDriver ; public abstract class SlotSorter extends Reducer < SortableSlot , WritableSlot , Object , Object > { public static final String NAME_GET_OUTPUT_NAMES = "" ; public static final String NAME_CREATE_SLOT_OBJECTS = "" ; private StageOutputDriver output ; private Writable [ ] objects ; private Result < Writable > [ ] results ; protected abstract Writable [ ] createSlotObjects ( ) ; protected abstract String [ ] getOutputNames ( ) ; @ Override @ SuppressWarnings ( "" ) protected void setup ( Context context ) throws IOException , InterruptedException { this . objects = createSlotObjects ( ) ; String [ ] names = getOutputNames ( ) ; if ( objects . length != names . length ) { throw new AssertionError ( "" ) ; } this . output = new StageOutputDriver ( context ) ; this . results = new Result [ objects . length ] ; for ( int i = ; i < objects . length ; i ++ ) { String name = names [ i ] ; if ( name != null ) { results [ i ] = output . getResultSink ( name ) ; } } } @ Override protected void cleanup ( Context context ) throws IOException , InterruptedException { this . output . close ( ) ; this . output = null ; this . objects = null ; this . results = null ; } @ Override protected void reduce ( SortableSlot key , Iterable < WritableSlot > values , Context context ) throws IOException , InterruptedException { int slot = key . getSlot ( ) ; Writable cache = objects [ slot ] ; Result < Writable > result = results [ slot ] ; for ( WritableSlot holder : values ) { holder . loadTo ( cache ) ; result . add ( cache ) ; } } } package com . asakusafw . runtime . stage . collector ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . Externalizable ; import java . io . IOException ; import java . io . ObjectInput ; import java . io . ObjectOutput ; import java . security . SecureRandom ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . WritableComparable ; import org . apache . hadoop . io . WritableComparator ; import org . apache . hadoop . io . WritableUtils ; public class SortableSlot implements WritableComparable < SortableSlot > { static final int GROUPING_BITS = ; public static final String NAME_BEGIN = "" ; public static final String NAME_ADD_BYTE = "" ; public static final String NAME_ADD_RANDOM = "" ; public static final String NAME_ADD = "" ; private final SecureRandom random = new SecureRandom ( ) ; private final DataOutputBuffer buffer = new DataOutputBuffer ( ) ; private int slotNumber = - ; public void begin ( int slot ) { this . slotNumber = slot ; buffer . reset ( ) ; } public int getSlot ( ) { return slotNumber ; } public void addByte ( int data ) throws IOException { buffer . writeByte ( data ) ; } public void addRandom ( ) throws IOException { buffer . writeInt ( random . nextInt ( ) ) ; } public void add ( Writable data ) throws IOException { data . write ( buffer ) ; } @ Override public void write ( DataOutput out ) throws IOException { WritableUtils . writeVInt ( out , slotNumber ) ; WritableUtils . writeVInt ( out , buffer . getLength ( ) ) ; out . write ( buffer . getData ( ) , , buffer . getLength ( ) ) ; } @ Override public void readFields ( DataInput in ) throws IOException { buffer . reset ( ) ; this . slotNumber = WritableUtils . readVInt ( in ) ; int length = WritableUtils . readVInt ( in ) ; buffer . write ( in , length ) ; } @ Override public int compareTo ( SortableSlot o ) { if ( slotNumber < o . slotNumber ) { return - ; } else if ( slotNumber > o . slotNumber ) { return + ; } return WritableComparator . compareBytes ( buffer . getData ( ) , , buffer . getLength ( ) , o . buffer . getData ( ) , , o . buffer . getLength ( ) ) ; } int hashCode ( int ignoreTailBits ) { int ignoreTailBytes = ignoreTailBits / Byte . SIZE ; int ignoreTailByteMask = - << ( ignoreTailBits & ( Byte . SIZE - ) ) ; if ( buffer . getLength ( ) <= ignoreTailBytes ) { return ; } int hash = ; final int prime = ; hash = hash * prime + slotNumber ; byte [ ] content = buffer . getData ( ) ; for ( int i = , n = buffer . getLength ( ) - ignoreTailBytes - ; i < n ; i ++ ) { hash = hash * prime + content [ i ] ; } hash = hash * prime + ( content [ buffer . getLength ( ) - ignoreTailBytes - ] & ignoreTailByteMask ) ; return hash ; } @ Override public int hashCode ( ) { return hashCode ( ) ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } SortableSlot other = ( SortableSlot ) obj ; return this . compareTo ( other ) == ; } static { WritableComparator . define ( SortableSlot . class , new Comparator ( ) ) ; } public static class Comparator extends WritableComparator implements Externalizable { public Comparator ( ) { super ( SortableSlot . class ) ; } @ Override public int compare ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { try { int varIntSize ; int offset1 = ; int offset2 = ; varIntSize = WritableUtils . decodeVIntSize ( b1 [ s1 + offset1 ] ) ; int slot1 = WritableComparator . readVInt ( b1 , s1 + offset1 ) ; offset1 += varIntSize ; varIntSize = WritableUtils . decodeVIntSize ( b2 [ s2 + offset2 ] ) ; int slot2 = WritableComparator . readVInt ( b2 , s2 + offset2 ) ; offset2 += varIntSize ; if ( slot1 != slot2 ) { return slot1 - slot2 ; } varIntSize = WritableUtils . decodeVIntSize ( b1 [ s1 + offset1 ] ) ; int length1 = WritableComparator . readVInt ( b1 , s1 + offset1 ) ; offset1 += varIntSize ; varIntSize = WritableUtils . decodeVIntSize ( b2 [ s2 + offset2 ] ) ; int length2 = WritableComparator . readVInt ( b2 , s2 + offset2 ) ; offset2 += varIntSize ; return compareBytes ( b1 , s1 + offset1 , length1 , b2 , s2 + offset2 , length2 ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } @ Override public void writeExternal ( ObjectOutput out ) throws IOException { return ; } @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { return ; } private Object readResolve ( ) { return new Comparator ( ) ; } } public static class Partitioner extends org . apache . hadoop . mapreduce . Partitioner < SortableSlot , Object > { @ Override public int getPartition ( SortableSlot key , Object value , int numPartitions ) { int hash = key . hashCode ( GROUPING_BITS ) ; return ( hash & Integer . MAX_VALUE ) % numPartitions ; } } } package com . asakusafw . runtime . stage . collector ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . mapreduce . Mapper ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . stage . output . StageOutputDriver ; public abstract class SlotDirectMapper extends Mapper < Object , Writable , SortableSlot , WritableSlot > { public static final String NAME_GET_OUTPUT_NAME = "" ; private StageOutputDriver output ; private Result < Writable > result ; @ Override protected void setup ( Context context ) throws IOException , InterruptedException { String name = getOutputName ( ) ; this . output = new StageOutputDriver ( context ) ; this . result = output . getResultSink ( name ) ; } public abstract String getOutputName ( ) ; @ Override protected void cleanup ( Context context ) throws IOException , InterruptedException { this . output . close ( ) ; this . output = null ; this . result = null ; } @ Override protected void map ( Object key , Writable value , Context context ) throws IOException , InterruptedException { result . add ( value ) ; } } package com . asakusafw . runtime . stage . collector ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . WritableUtils ; public class WritableSlot implements Writable { private final DataOutputBuffer output = new DataOutputBuffer ( ) ; private final DataInputBuffer input = new DataInputBuffer ( ) ; public void store ( Writable data ) throws IOException { output . reset ( ) ; data . write ( output ) ; } public void loadTo ( Writable data ) throws IOException { input . reset ( output . getData ( ) , output . getLength ( ) ) ; data . readFields ( input ) ; } @ Override public void write ( DataOutput out ) throws IOException { WritableUtils . writeVInt ( out , output . getLength ( ) ) ; out . write ( output . getData ( ) , , output . getLength ( ) ) ; } @ Override public void readFields ( DataInput in ) throws IOException { output . reset ( ) ; int length = WritableUtils . readVInt ( in ) ; output . write ( in , length ) ; } } package com . asakusafw . runtime . stage . collector ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . mapreduce . Mapper ; public abstract class SlotDistributor < T extends Writable > extends Mapper < Object , T , SortableSlot , WritableSlot > { public static final String NAME_SET_SLOT_SPEC = "" ; private final SortableSlot keyOut = new SortableSlot ( ) ; private final WritableSlot valueOut = new WritableSlot ( ) ; protected abstract void setSlotSpec ( T value , SortableSlot slot ) throws IOException ; @ Override protected void map ( Object key , T value , Context context ) throws IOException , InterruptedException { valueOut . store ( value ) ; setSlotSpec ( value , keyOut ) ; context . write ( keyOut , valueOut ) ; } } package com . asakusafw . runtime . stage . temporary ; package com . asakusafw . runtime . stage . temporary ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . SequenceFile . CompressionType ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . compress . CompressionCodec ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . sequencefile . SequenceFileModelInput ; import com . asakusafw . runtime . io . sequencefile . SequenceFileModelOutput ; import com . asakusafw . runtime . io . sequencefile . SequenceFileUtil ; public final class TemporaryStorage { static final Log LOG = LogFactory . getLog ( TemporaryStorage . class ) ; public static List < Path > list ( Configuration conf , Path pathPattern ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( pathPattern == null ) { throw new IllegalArgumentException ( "" ) ; } FileSystem fs = pathPattern . getFileSystem ( conf ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , pathPattern , fs . getUri ( ) ) ) ; } FileStatus [ ] statusList = fs . globStatus ( pathPattern ) ; if ( statusList == null || statusList . length == ) { return Collections . emptyList ( ) ; } List < Path > results = new ArrayList < Path > ( ) ; for ( FileStatus status : statusList ) { results . add ( status . getPath ( ) ) ; } return results ; } @ SuppressWarnings ( "" ) public static < V > ModelInput < V > openInput ( Configuration conf , Class < V > dataType , Path path ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } FileSystem fs = path . getFileSystem ( conf ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , path , fs . getUri ( ) ) ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; return ( ModelInput < V > ) new SequenceFileModelInput < Writable > ( reader ) ; } @ SuppressWarnings ( "" ) public static < V > ModelInput < V > openInput ( Configuration conf , Class < V > dataType , FileStatus status , InputStream input ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( status == null ) { throw new IllegalArgumentException ( "" ) ; } if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } SequenceFile . Reader reader = SequenceFileUtil . openReader ( input , status , conf ) ; return ( ModelInput < V > ) new SequenceFileModelInput < Writable > ( reader , input ) ; } public static < V > ModelOutput < V > openOutput ( Configuration conf , Class < V > dataType , Path path ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } FileSystem fs = path . getFileSystem ( conf ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , path , fs . getUri ( ) ) ) ; } SequenceFile . Writer out = SequenceFile . createWriter ( fs , conf , path , NullWritable . class , dataType ) ; return new SequenceFileModelOutput < V > ( out ) ; } public static < V > ModelOutput < V > openOutput ( Configuration conf , Class < V > dataType , Path path , CompressionCodec compressionCodec ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } FileSystem fs = path . getFileSystem ( conf ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , path , fs . getUri ( ) ) ) ; } SequenceFile . Writer out ; if ( compressionCodec == null ) { out = SequenceFile . createWriter ( fs , conf , path , NullWritable . class , dataType , CompressionType . NONE ) ; } else { out = SequenceFile . createWriter ( fs , conf , path , NullWritable . class , dataType , CompressionType . BLOCK , compressionCodec ) ; } return new SequenceFileModelOutput < V > ( out ) ; } public static < V > ModelOutput < V > openOutput ( Configuration conf , Class < V > dataType , OutputStream output ) throws IOException { return openOutput ( conf , dataType , output , null ) ; } public static < V > ModelOutput < V > openOutput ( Configuration conf , Class < V > dataType , OutputStream output , CompressionCodec compressionCodec ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } SequenceFile . Writer out = SequenceFileUtil . openWriter ( output , conf , NullWritable . class , dataType , compressionCodec ) ; return new SequenceFileModelOutput < V > ( out ) ; } private TemporaryStorage ( ) { return ; } } package com . asakusafw . runtime . stage . output ; import java . io . IOException ; import java . io . InterruptedIOException ; import java . text . MessageFormat ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . mapred . JobContext ; import org . apache . hadoop . mapred . TaskAttemptContext ; import org . apache . hadoop . mapreduce . JobStatus ; import org . apache . hadoop . mapreduce . JobStatus . State ; import org . apache . hadoop . mapreduce . OutputCommitter ; import org . apache . hadoop . mapreduce . TaskAttemptID ; import org . apache . hadoop . mapreduce . TaskID ; import org . apache . hadoop . util . Progressable ; public class LegacyBridgeOutputCommitter extends org . apache . hadoop . mapred . OutputCommitter { static final Log LOG = LogFactory . getLog ( LegacyBridgeOutputCommitter . class ) ; private final StageOutputFormat format = new StageOutputFormat ( ) ; @ Override public void setupJob ( JobContext jobContext ) throws IOException { org . apache . hadoop . mapreduce . TaskAttemptContext taskContext = toTaskAttemptContext ( jobContext ) ; committer ( taskContext ) . setupJob ( taskContext ) ; } @ Override public void abortJob ( JobContext jobContext , int status ) throws IOException { JobStatus . State state = convert ( status ) ; org . apache . hadoop . mapreduce . TaskAttemptContext taskContext = toTaskAttemptContext ( jobContext ) ; committer ( taskContext ) . abortJob ( taskContext , state ) ; } private State convert ( int status ) { for ( JobStatus . State each : JobStatus . State . values ( ) ) { if ( each . getValue ( ) == status ) { return each ; } } throw new IllegalStateException ( ) ; } @ SuppressWarnings ( "" ) @ Override public void cleanupJob ( JobContext jobContext ) throws IOException { org . apache . hadoop . mapreduce . TaskAttemptContext taskContext = toTaskAttemptContext ( jobContext ) ; committer ( taskContext ) . cleanupJob ( taskContext ) ; } @ Override public void commitJob ( JobContext jobContext ) throws IOException { org . apache . hadoop . mapreduce . TaskAttemptContext taskContext = toTaskAttemptContext ( jobContext ) ; committer ( taskContext ) . commitJob ( taskContext ) ; } @ Override public void setupTask ( TaskAttemptContext taskContext ) throws IOException { committer ( taskContext ) . setupTask ( taskContext ) ; } @ Override public boolean needsTaskCommit ( TaskAttemptContext taskContext ) throws IOException { return committer ( taskContext ) . needsTaskCommit ( taskContext ) ; } @ Override public void commitTask ( TaskAttemptContext taskContext ) throws IOException { committer ( taskContext ) . commitTask ( taskContext ) ; } @ Override public void abortTask ( TaskAttemptContext taskContext ) throws IOException { committer ( taskContext ) . abortTask ( taskContext ) ; } private OutputCommitter committer ( org . apache . hadoop . mapreduce . TaskAttemptContext taskContext ) throws IOException { try { return format . getOutputCommitter ( taskContext ) ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( ) . initCause ( e ) ; } } private org . apache . hadoop . mapreduce . TaskAttemptContext toTaskAttemptContext ( JobContext jobContext ) { assert jobContext != null ; final Progressable progressable = jobContext . getProgressible ( ) ; if ( progressable == null ) { LOG . warn ( MessageFormat . format ( "" , jobContext . getClass ( ) . getName ( ) ) ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , jobContext . getJobID ( ) , progressable ) ) ; } return new org . apache . hadoop . mapreduce . TaskAttemptContext ( jobContext . getConfiguration ( ) , new TaskAttemptID ( new TaskID ( jobContext . getJobID ( ) , true , ) , ) ) { @ Override public void progress ( ) { if ( progressable != null ) { progressable . progress ( ) ; } super . progress ( ) ; } } ; } } package com . asakusafw . runtime . stage . output ; package com . asakusafw . runtime . stage . output ; import java . io . IOException ; import java . lang . reflect . Method ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . mapred . Task ; import org . apache . hadoop . mapreduce . Counter ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . OutputFormat ; import org . apache . hadoop . mapreduce . RecordWriter ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . TaskInputOutputContext ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; import org . apache . hadoop . util . ReflectionUtils ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . flow . ResultOutput ; import com . asakusafw . runtime . stage . StageOutput ; public class StageOutputDriver { static final Log LOG = LogFactory . getLog ( StageOutputDriver . class ) ; private static final String K_NAMES = "" ; private static final String K_FORMAT_PREFIX = "" ; private static final String K_KEY_PREFIX = "" ; private static final String K_VALUE_PREFIX = "" ; private static final String COUNTER_GROUP = "" ; private final Map < String , ResultOutput < ? > > resultSinks ; private final TaskInputOutputContext < ? , ? , ? , ? > context ; public StageOutputDriver ( TaskInputOutputContext < ? , ? , ? , ? > context ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . resultSinks = prepareSinks ( context ) ; } private static Map < String , ResultOutput < ? > > prepareSinks ( TaskInputOutputContext < ? , ? , ? , ? > context ) { assert context != null ; Map < String , ResultOutput < ? > > results = new HashMap < String , ResultOutput < ? > > ( ) ; Configuration conf = context . getConfiguration ( ) ; for ( String name : conf . getStringCollection ( K_NAMES ) ) { results . put ( name , null ) ; } return results ; } private static final String METHOD_SET_OUTPUT_NAME = "" ; private void setOutputFilePrefix ( JobContext localContext , String name ) throws IOException { assert localContext != null ; assert name != null ; try { Method method = FileOutputFormat . class . getDeclaredMethod ( METHOD_SET_OUTPUT_NAME , JobContext . class , String . class ) ; method . setAccessible ( true ) ; method . invoke ( null , localContext , name ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , name ) , e ) ; } } @ SuppressWarnings ( "" ) public synchronized < T extends Writable > Result < T > getResultSink ( String name ) throws IOException , InterruptedException { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( resultSinks . containsKey ( name ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } ResultOutput < ? > sink = resultSinks . get ( name ) ; if ( sink == null ) { sink = buildSink ( name ) ; resultSinks . put ( name , sink ) ; } return ( Result < T > ) sink ; } private ResultOutput < ? > buildSink ( String name ) throws IOException , InterruptedException { assert name != null ; Configuration conf = context . getConfiguration ( ) ; @ SuppressWarnings ( "" ) Class < ? extends OutputFormat > formatClass = conf . getClass ( getPropertyName ( K_FORMAT_PREFIX , name ) , null , OutputFormat . class ) ; Class < ? > keyClass = conf . getClass ( getPropertyName ( K_KEY_PREFIX , name ) , null ) ; Class < ? > valueClass = conf . getClass ( getPropertyName ( K_VALUE_PREFIX , name ) , null ) ; if ( formatClass == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , name ) ) ; } if ( keyClass == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , name ) ) ; } if ( valueClass == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , name ) ) ; } List < Counter > counters = getCounters ( name ) ; if ( TemporaryOutputFormat . class . isAssignableFrom ( formatClass ) ) { return buildTemporarySink ( name , valueClass , counters ) ; } else { return buildNormalSink ( name , formatClass , keyClass , valueClass , counters ) ; } } private List < Counter > getCounters ( String name ) { assert name != null ; try { List < Counter > results = new ArrayList < Counter > ( ) ; if ( context . getTaskAttemptID ( ) . isMap ( ) ) { results . add ( context . getCounter ( Task . Counter . MAP_OUTPUT_RECORDS ) ) ; } else { results . add ( context . getCounter ( Task . Counter . REDUCE_OUTPUT_RECORDS ) ) ; } results . add ( context . getCounter ( COUNTER_GROUP , name ) ) ; return results ; } catch ( RuntimeException e ) { LOG . warn ( "" , e ) ; return Collections . emptyList ( ) ; } } private ResultOutput < ? > buildTemporarySink ( String name , Class < ? > valueClass , List < Counter > counters ) throws IOException , InterruptedException { assert context != null ; assert name != null ; assert valueClass != null ; assert counters != null ; TemporaryOutputFormat < ? > format = new TemporaryOutputFormat < Object > ( ) ; RecordWriter < ? , ? > writer = format . createRecordWriter ( context , name , valueClass ) ; return new ResultOutput < Writable > ( context , writer , counters ) ; } private ResultOutput < ? > buildNormalSink ( String name , @ SuppressWarnings ( "" ) Class < ? extends OutputFormat > formatClass , Class < ? > keyClass , Class < ? > valueClass , List < Counter > counters ) throws IOException , InterruptedException { assert context != null ; assert name != null ; assert formatClass != null ; assert keyClass != null ; assert valueClass != null ; assert counters != null ; Job job = new Job ( context . getConfiguration ( ) ) ; job . setOutputFormatClass ( formatClass ) ; job . setOutputKeyClass ( keyClass ) ; job . setOutputValueClass ( valueClass ) ; TaskAttemptContext localContext = new TaskAttemptContext ( job . getConfiguration ( ) , context . getTaskAttemptID ( ) ) ; if ( FileOutputFormat . class . isAssignableFrom ( formatClass ) ) { setOutputFilePrefix ( localContext , name ) ; } OutputFormat < ? , ? > format = ReflectionUtils . newInstance ( formatClass , localContext . getConfiguration ( ) ) ; RecordWriter < ? , ? > writer = format . getRecordWriter ( localContext ) ; return new ResultOutput < Writable > ( localContext , writer ) ; } public synchronized void close ( ) throws IOException , InterruptedException { for ( Map . Entry < String , ResultOutput < ? > > entry : resultSinks . entrySet ( ) ) { ResultOutput < ? > output = entry . getValue ( ) ; if ( output != null ) { output . close ( ) ; entry . setValue ( null ) ; } } } public static void set ( Job job , String outputPath , Collection < StageOutput > outputList ) { if ( job == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputPath == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputList == null ) { throw new IllegalArgumentException ( "" ) ; } List < StageOutput > brigeOutputs = new ArrayList < StageOutput > ( ) ; List < StageOutput > normalOutputs = new ArrayList < StageOutput > ( ) ; boolean sawFileOutput = false ; boolean sawTemporaryOutput = false ; for ( StageOutput output : outputList ) { Class < ? extends OutputFormat < ? , ? > > formatClass = output . getFormatClass ( ) ; if ( BridgeOutputFormat . class . isAssignableFrom ( formatClass ) ) { brigeOutputs . add ( output ) ; } else { normalOutputs . add ( output ) ; } } if ( brigeOutputs . isEmpty ( ) == false ) { BridgeOutputFormat . set ( job , brigeOutputs ) ; } for ( StageOutput output : normalOutputs ) { String name = output . getName ( ) ; Class < ? > keyClass = output . getKeyClass ( ) ; Class < ? > valueClass = output . getValueClass ( ) ; Class < ? extends OutputFormat < ? , ? > > formatClass = output . getFormatClass ( ) ; sawFileOutput |= FileOutputFormat . class . isAssignableFrom ( formatClass ) ; sawTemporaryOutput |= TemporaryOutputFormat . class . isAssignableFrom ( formatClass ) ; addOutput ( job , name , formatClass , keyClass , valueClass ) ; } if ( sawFileOutput ) { FileOutputFormat . setOutputPath ( job , new Path ( outputPath ) ) ; } if ( sawTemporaryOutput ) { TemporaryOutputFormat . setOutputPath ( job , new Path ( outputPath ) ) ; } } private static void addOutput ( Job job , String name , Class < ? > formatClass , Class < ? > keyClass , Class < ? > valueClass ) { assert job != null ; assert name != null ; assert formatClass != null ; assert keyClass != null ; assert valueClass != null ; if ( isValidName ( name ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } Configuration conf = job . getConfiguration ( ) ; Set < String > names = new TreeSet < String > ( conf . getStringCollection ( K_NAMES ) ) ; if ( names . contains ( name ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } names . add ( name ) ; conf . setStrings ( K_NAMES , names . toArray ( new String [ names . size ( ) ] ) ) ; conf . setClass ( getPropertyName ( K_FORMAT_PREFIX , name ) , formatClass , OutputFormat . class ) ; conf . setClass ( getPropertyName ( K_KEY_PREFIX , name ) , keyClass , Object . class ) ; conf . setClass ( getPropertyName ( K_VALUE_PREFIX , name ) , valueClass , Object . class ) ; } private static String getPropertyName ( String prefix , String name ) { assert prefix != null ; assert name != null ; return prefix + name ; } private static boolean isValidName ( String name ) { assert name != null ; for ( char c : name . toCharArray ( ) ) { if ( isValidNameChar ( c ) == false ) { return false ; } } return true ; } private static boolean isValidNameChar ( char c ) { return ( '' <= c && c <= '' ) || ( '' <= c && c <= '' ) || ( '' <= c && c <= '' ) ; } } package com . asakusafw . runtime . stage . output ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . LinkedHashSet ; import java . util . List ; import java . util . Set ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . JobStatus . State ; import org . apache . hadoop . mapreduce . OutputCommitter ; import org . apache . hadoop . mapreduce . OutputFormat ; import org . apache . hadoop . mapreduce . RecordWriter ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . lib . output . FileOutputCommitter ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; public final class StageOutputFormat extends OutputFormat < Object , Object > { static final Log LOG = LogFactory . getLog ( StageOutputFormat . class ) ; private OutputCommitter outputCommitter ; private final BridgeOutputFormat bridgeOutputFormat = new BridgeOutputFormat ( ) ; private final FileOutputFormat < Object , Object > dummyFileOutputFormat = new EmptyFileOutputFormat ( ) ; private final TemporaryOutputFormat < Object > temporaryOutputFormat = new TemporaryOutputFormat < Object > ( ) ; @ Override public void checkOutputSpecs ( JobContext context ) throws IOException , InterruptedException { if ( isBridgeOutputEnabled ( context ) ) { bridgeOutputFormat . checkOutputSpecs ( context ) ; } if ( isFileOutputEnabled ( context ) ) { dummyFileOutputFormat . checkOutputSpecs ( context ) ; } if ( isTemporaryOutputEnabled ( context ) ) { temporaryOutputFormat . checkOutputSpecs ( context ) ; } } @ Override public RecordWriter < Object , Object > getRecordWriter ( TaskAttemptContext context ) throws IOException , InterruptedException { return dummyFileOutputFormat . getRecordWriter ( context ) ; } @ Override public OutputCommitter getOutputCommitter ( TaskAttemptContext context ) throws IOException , InterruptedException { synchronized ( this ) { if ( outputCommitter == null ) { outputCommitter = createOutputCommitter ( context ) ; } return outputCommitter ; } } private OutputCommitter createOutputCommitter ( TaskAttemptContext context ) throws IOException , InterruptedException { assert context != null ; Set < OutputCommitter > components = new LinkedHashSet < OutputCommitter > ( ) ; if ( isBridgeOutputEnabled ( context ) ) { OutputCommitter committer = bridgeOutputFormat . getOutputCommitter ( context ) ; if ( components . contains ( committer ) == false ) { components . add ( committer ) ; } } if ( isFileOutputEnabled ( context ) ) { OutputCommitter committer = dummyFileOutputFormat . getOutputCommitter ( context ) ; if ( components . contains ( committer ) == false ) { components . add ( committer ) ; } } if ( isTemporaryOutputEnabled ( context ) ) { FileOutputCommitter committer = temporaryOutputFormat . getOutputCommitter ( context ) ; if ( components . contains ( committer ) == false ) { components . add ( committer ) ; } } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , components ) ) ; } return new CombinedOutputCommitter ( new ArrayList < OutputCommitter > ( components ) ) ; } private boolean isBridgeOutputEnabled ( JobContext context ) { assert context != null ; return BridgeOutputFormat . hasOutput ( context ) ; } private boolean isFileOutputEnabled ( JobContext context ) { assert context != null ; return FileOutputFormat . getOutputPath ( context ) != null ; } private boolean isTemporaryOutputEnabled ( JobContext context ) { assert context != null ; return TemporaryOutputFormat . getOutputPath ( context ) != null ; } private static final class CombinedOutputCommitter extends OutputCommitter { private final List < OutputCommitter > components ; CombinedOutputCommitter ( List < OutputCommitter > components ) { assert components != null ; this . components = components ; } @ Override public void setupJob ( JobContext jobContext ) throws IOException { IOException exception = null ; for ( OutputCommitter component : components ) { try { component . setupJob ( jobContext ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , component . getClass ( ) . getName ( ) , jobContext . getJobID ( ) ) , e ) ; if ( exception == null ) { exception = e ; } } } if ( exception != null ) { throw exception ; } } @ Override public void commitJob ( JobContext jobContext ) throws IOException { IOException exception = null ; for ( OutputCommitter component : components ) { try { component . commitJob ( jobContext ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , component . getClass ( ) . getName ( ) , jobContext . getJobID ( ) ) , e ) ; if ( exception == null ) { exception = e ; } } } if ( exception != null ) { throw exception ; } } @ Override public void abortJob ( JobContext jobContext , State state ) throws IOException { IOException exception = null ; for ( OutputCommitter component : components ) { try { component . abortJob ( jobContext , state ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , component . getClass ( ) . getName ( ) , jobContext . getJobID ( ) ) , e ) ; if ( exception == null ) { exception = e ; } } } if ( exception != null ) { throw exception ; } } @ Override public void setupTask ( TaskAttemptContext taskContext ) throws IOException { IOException exception = null ; for ( OutputCommitter component : components ) { try { component . setupTask ( taskContext ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , component . getClass ( ) . getName ( ) , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) , e ) ; if ( exception == null ) { exception = e ; } } } if ( exception != null ) { throw exception ; } } @ Override public boolean needsTaskCommit ( TaskAttemptContext taskContext ) throws IOException { boolean results = false ; IOException exception = null ; for ( OutputCommitter component : components ) { try { results |= component . needsTaskCommit ( taskContext ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , component . getClass ( ) . getName ( ) , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) , e ) ; if ( exception == null ) { exception = e ; } } } if ( exception != null ) { throw exception ; } return results ; } @ Override public void commitTask ( TaskAttemptContext taskContext ) throws IOException { IOException exception = null ; for ( OutputCommitter component : components ) { try { component . commitTask ( taskContext ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , component . getClass ( ) . getName ( ) , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) , e ) ; if ( exception == null ) { exception = e ; } } } if ( exception != null ) { throw exception ; } } @ Override public void abortTask ( TaskAttemptContext taskContext ) throws IOException { IOException exception = null ; for ( OutputCommitter component : components ) { try { component . abortTask ( taskContext ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , component . getClass ( ) . getName ( ) , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) , e ) ; if ( exception == null ) { exception = e ; } } } if ( exception != null ) { throw exception ; } } } } package com . asakusafw . runtime . stage . output ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInputStream ; import java . io . DataOutputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . InterruptedIOException ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Scanner ; import java . util . TreeMap ; import java . util . zip . GZIPInputStream ; import java . util . zip . GZIPOutputStream ; import org . apache . commons . codec . binary . Base64InputStream ; import org . apache . commons . codec . binary . Base64OutputStream ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . WritableUtils ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . JobStatus . State ; import org . apache . hadoop . mapreduce . OutputCommitter ; import org . apache . hadoop . mapreduce . OutputFormat ; import org . apache . hadoop . mapreduce . RecordWriter ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceConstants ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . OutputTransactionContext ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . runtime . stage . StageOutput ; import com . asakusafw . runtime . util . VariableTable ; public final class BridgeOutputFormat extends OutputFormat < Object , Object > { static final Log LOG = LogFactory . getLog ( BridgeOutputFormat . class ) ; private static final Charset ASCII = Charset . forName ( "" ) ; private static final long SERIAL_VERSION = ; private static final String KEY = "" ; private OutputCommitter outputCommitter ; public static boolean hasOutput ( JobContext context ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } return context . getConfiguration ( ) . getRaw ( KEY ) != null ; } public static void set ( JobContext context , List < StageOutput > outputList ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputList == null ) { throw new IllegalArgumentException ( "" ) ; } List < OutputSpec > specs = new ArrayList < OutputSpec > ( ) ; for ( StageOutput output : outputList ) { List < String > deletePatterns = getDeletePatterns ( output ) ; OutputSpec spec = new OutputSpec ( output . getName ( ) , deletePatterns ) ; specs . add ( spec ) ; } save ( context . getConfiguration ( ) , specs ) ; } private static List < String > getDeletePatterns ( StageOutput output ) { assert output != null ; List < String > results = new ArrayList < String > ( ) ; for ( Map . Entry < String , String > entry : output . getAttributes ( ) . entrySet ( ) ) { if ( entry . getKey ( ) . startsWith ( DirectDataSourceConstants . PREFIX_DELETE_PATTERN ) ) { String rawDeletePattern = entry . getValue ( ) ; results . add ( rawDeletePattern ) ; } } return results ; } private static void save ( Configuration conf , List < OutputSpec > specs ) { assert conf != null ; assert specs != null ; try { ByteArrayOutputStream sink = new ByteArrayOutputStream ( ) ; DataOutputStream output = new DataOutputStream ( new GZIPOutputStream ( new Base64OutputStream ( sink ) ) ) ; WritableUtils . writeVLong ( output , SERIAL_VERSION ) ; WritableUtils . writeVInt ( output , specs . size ( ) ) ; for ( OutputSpec spec : specs ) { WritableUtils . writeString ( output , spec . basePath ) ; WritableUtils . writeVInt ( output , spec . deletePatterns . size ( ) ) ; for ( String pattern : spec . deletePatterns ) { WritableUtils . writeString ( output , pattern ) ; } } output . close ( ) ; conf . set ( KEY , new String ( sink . toByteArray ( ) , ASCII ) ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } private static List < OutputSpec > getSpecs ( JobContext context ) { assert context != null ; String encoded = context . getConfiguration ( ) . getRaw ( KEY ) ; if ( encoded == null ) { return Collections . emptyList ( ) ; } try { ByteArrayInputStream source = new ByteArrayInputStream ( encoded . getBytes ( ASCII ) ) ; DataInputStream input = new DataInputStream ( new GZIPInputStream ( new Base64InputStream ( source ) ) ) ; long version = WritableUtils . readVLong ( input ) ; if ( version != SERIAL_VERSION ) { throw new IOException ( MessageFormat . format ( "" , SERIAL_VERSION , version ) ) ; } List < OutputSpec > results = new ArrayList < OutputSpec > ( ) ; int specCount = WritableUtils . readVInt ( input ) ; for ( int specIndex = ; specIndex < specCount ; specIndex ++ ) { String basePath = WritableUtils . readString ( input ) ; int patternCount = WritableUtils . readVInt ( input ) ; List < String > patterns = new ArrayList < String > ( ) ; for ( int patternIndex = ; patternIndex < patternCount ; patternIndex ++ ) { String pattern = WritableUtils . readString ( input ) ; patterns . add ( pattern ) ; } results . add ( new OutputSpec ( basePath , patterns ) ) ; } return results ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } private static DirectDataSourceRepository getDataSourceRepository ( JobContext context ) { assert context != null ; return HadoopDataSourceUtil . loadRepository ( context . getConfiguration ( ) ) ; } @ Override public void checkOutputSpecs ( JobContext context ) throws IOException , InterruptedException { DirectDataSourceRepository repo = getDataSourceRepository ( context ) ; List < OutputSpec > specs = getSpecs ( context ) ; VariableTable table = getVariableTable ( context ) ; for ( OutputSpec spec : specs ) { try { repo . getContainerPath ( spec . basePath ) ; } catch ( IOException e ) { throw new IOException ( MessageFormat . format ( "" , spec . basePath ) , e ) ; } for ( String pattern : spec . deletePatterns ) { try { String resolved = table . parse ( pattern ) ; FilePattern . compile ( resolved ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , pattern ) , e ) ; } } } } @ Override public RecordWriter < Object , Object > getRecordWriter ( TaskAttemptContext context ) throws IOException , InterruptedException { return new EmptyFileOutputFormat ( ) . getRecordWriter ( context ) ; } @ Override public OutputCommitter getOutputCommitter ( TaskAttemptContext context ) throws IOException , InterruptedException { return getOutputCommitter ( ( JobContext ) context ) ; } OutputCommitter getOutputCommitter ( JobContext context ) throws IOException { synchronized ( this ) { if ( outputCommitter == null ) { outputCommitter = createOutputCommitter ( context ) ; } return outputCommitter ; } } private OutputCommitter createOutputCommitter ( JobContext context ) throws IOException { assert context != null ; DirectDataSourceRepository repository = getDataSourceRepository ( context ) ; List < OutputSpec > specs = getSpecs ( context ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , specs ) ) ; } return new BridgeOutputCommitter ( repository , specs ) ; } static VariableTable getVariableTable ( JobContext context ) { assert context != null ; String arguments = context . getConfiguration ( ) . get ( StageConstants . PROP_ASAKUSA_BATCH_ARGS , "" ) ; VariableTable variables = new VariableTable ( VariableTable . RedefineStrategy . IGNORE ) ; variables . defineVariables ( arguments ) ; return variables ; } private static final class OutputSpec { final String basePath ; final List < String > deletePatterns ; OutputSpec ( String basePath , List < String > deletePatterns ) { assert basePath != null ; this . basePath = basePath ; this . deletePatterns = deletePatterns ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , basePath , deletePatterns ) ; } } private static final class BridgeOutputCommitter extends OutputCommitter { private final DirectDataSourceRepository repository ; private final Map < String , String > outputMap ; private final List < OutputSpec > outputSpecs ; BridgeOutputCommitter ( DirectDataSourceRepository repository , List < OutputSpec > outputList ) throws IOException { assert repository != null ; assert outputList != null ; this . repository = repository ; this . outputSpecs = outputList ; this . outputMap = createMap ( repository , outputList ) ; } private static Map < String , String > createMap ( DirectDataSourceRepository repo , List < OutputSpec > specs ) throws IOException { assert repo != null ; assert specs != null ; Map < String , String > results = new TreeMap < String , String > ( ) ; for ( OutputSpec spec : specs ) { String containerPath = repo . getContainerPath ( spec . basePath ) ; String id = repo . getRelatedId ( spec . basePath ) ; results . put ( containerPath , id ) ; } return results ; } @ Override public boolean needsTaskCommit ( TaskAttemptContext taskContext ) throws IOException { return outputMap . isEmpty ( ) == false ; } @ Override public void setupTask ( TaskAttemptContext taskContext ) throws IOException { if ( outputMap . isEmpty ( ) ) { return ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } for ( Map . Entry < String , String > entry : outputMap . entrySet ( ) ) { String containerPath = entry . getKey ( ) ; String id = entry . getValue ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , id , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } OutputAttemptContext context = HadoopDataSourceUtil . createContext ( taskContext , id ) ; try { DirectDataSource repo = repository . getRelatedDataSource ( containerPath ) ; repo . setupAttemptOutput ( context ) ; } catch ( IOException e ) { LOG . error ( MessageFormat . format ( "" , id , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) , e ) ; throw e ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( MessageFormat . format ( "" , context . getTransactionId ( ) , context . getAttemptId ( ) , containerPath ) ) . initCause ( e ) ; } context . getCounter ( ) . add ( ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } } @ Override public void commitTask ( TaskAttemptContext taskContext ) throws IOException { if ( outputMap . isEmpty ( ) ) { return ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } for ( Map . Entry < String , String > entry : outputMap . entrySet ( ) ) { String containerPath = entry . getKey ( ) ; String id = entry . getValue ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , id , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } OutputAttemptContext context = HadoopDataSourceUtil . createContext ( taskContext , id ) ; try { DirectDataSource repo = repository . getRelatedDataSource ( containerPath ) ; repo . commitAttemptOutput ( context ) ; } catch ( IOException e ) { LOG . error ( MessageFormat . format ( "" , id , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) , e ) ; throw e ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( MessageFormat . format ( "" , context . getTransactionId ( ) , context . getAttemptId ( ) , containerPath ) ) . initCause ( e ) ; } catch ( RuntimeException e ) { LOG . fatal ( "" , e ) ; throw e ; } context . getCounter ( ) . add ( ) ; } doCleanupTask ( taskContext ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } } @ Override public void abortTask ( TaskAttemptContext taskContext ) throws IOException { if ( outputMap . isEmpty ( ) ) { return ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } doCleanupTask ( taskContext ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } } private void doCleanupTask ( TaskAttemptContext taskContext ) throws IOException { assert taskContext != null ; for ( Map . Entry < String , String > entry : outputMap . entrySet ( ) ) { String containerPath = entry . getKey ( ) ; String id = entry . getValue ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , id , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) ) ; } OutputAttemptContext context = HadoopDataSourceUtil . createContext ( taskContext , id ) ; try { DirectDataSource repo = repository . getRelatedDataSource ( containerPath ) ; repo . cleanupAttemptOutput ( context ) ; } catch ( IOException e ) { LOG . error ( MessageFormat . format ( "" , id , taskContext . getJobID ( ) , taskContext . getTaskAttemptID ( ) ) , e ) ; throw e ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( MessageFormat . format ( "" , context . getTransactionId ( ) , context . getAttemptId ( ) , containerPath ) ) . initCause ( e ) ; } context . getCounter ( ) . add ( ) ; } } @ Override public void setupJob ( JobContext jobContext ) throws IOException { if ( outputMap . isEmpty ( ) ) { return ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , jobContext . getJobID ( ) ) ) ; } cleanOutput ( jobContext ) ; setTransactionInfo ( jobContext , true ) ; for ( Map . Entry < String , String > entry : outputMap . entrySet ( ) ) { String containerPath = entry . getKey ( ) ; String id = entry . getValue ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , id , jobContext . getJobID ( ) ) ) ; } OutputTransactionContext context = HadoopDataSourceUtil . createContext ( jobContext , id ) ; try { DirectDataSource repo = repository . getRelatedDataSource ( containerPath ) ; repo . setupTransactionOutput ( context ) ; } catch ( IOException e ) { LOG . error ( MessageFormat . format ( "" , id , jobContext . getJobID ( ) ) , e ) ; throw e ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( MessageFormat . format ( "" , context . getTransactionId ( ) , containerPath ) ) . initCause ( e ) ; } context . getCounter ( ) . add ( ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , jobContext . getJobID ( ) ) ) ; } } private void cleanOutput ( JobContext jobContext ) throws IOException { assert jobContext != null ; VariableTable variables = getVariableTable ( jobContext ) ; for ( OutputSpec spec : outputSpecs ) { if ( spec . deletePatterns . isEmpty ( ) ) { continue ; } String id = repository . getRelatedId ( spec . basePath ) ; OutputTransactionContext context = HadoopDataSourceUtil . createContext ( jobContext , id ) ; try { DirectDataSource repo = repository . getRelatedDataSource ( spec . basePath ) ; String basePath = repository . getComponentPath ( spec . basePath ) ; for ( String pattern : spec . deletePatterns ) { String resolved = variables . parse ( pattern ) ; FilePattern resources = FilePattern . compile ( resolved ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , id , basePath , resolved ) ) ; } boolean succeed = repo . delete ( basePath , resources , true , context . getCounter ( ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , id , basePath , resolved , succeed ) ) ; } } } catch ( IOException e ) { LOG . error ( MessageFormat . format ( "" , id , jobContext . getJobID ( ) ) , e ) ; throw e ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( MessageFormat . format ( "" , id , jobContext . getJobID ( ) ) ) . initCause ( e ) ; } } } @ Override public void commitJob ( JobContext jobContext ) throws IOException { if ( outputMap . isEmpty ( ) ) { return ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , jobContext . getJobID ( ) ) ) ; } setCommitted ( jobContext , true ) ; doCleanupJob ( jobContext ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , jobContext . getJobID ( ) ) ) ; } } private void setTransactionInfo ( JobContext jobContext , boolean value ) throws IOException { Configuration conf = jobContext . getConfiguration ( ) ; Path transactionInfo = getTransactionInfoPath ( jobContext ) ; FileSystem fs = transactionInfo . getFileSystem ( conf ) ; if ( value ) { if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , jobContext . getJobID ( ) , fs . makeQualified ( transactionInfo ) ) ) ; } FSDataOutputStream output = fs . create ( transactionInfo , false ) ; boolean closed = false ; try { PrintWriter writer = new PrintWriter ( new OutputStreamWriter ( output , HadoopDataSourceUtil . COMMENT_CHARSET ) ) ; writer . printf ( "" , conf . getRaw ( StageConstants . PROP_USER ) ) ; writer . printf ( "" , conf . getRaw ( StageConstants . PROP_BATCH_ID ) ) ; writer . printf ( "" , conf . getRaw ( StageConstants . PROP_FLOW_ID ) ) ; writer . printf ( "" , conf . getRaw ( StageConstants . PROP_EXECUTION_ID ) ) ; writer . printf ( "" , conf . getRaw ( StageConstants . PROP_ASAKUSA_BATCH_ARGS ) ) ; writer . printf ( "" , jobContext . getJobID ( ) ) ; writer . printf ( "" , jobContext . getJobName ( ) ) ; writer . close ( ) ; closed = true ; } finally { if ( closed == false ) { output . close ( ) ; } } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , jobContext . getJobID ( ) , fs . makeQualified ( transactionInfo ) ) ) ; } if ( LOG . isTraceEnabled ( ) ) { FSDataInputStream input = fs . open ( transactionInfo ) ; try { Scanner scanner = new Scanner ( new InputStreamReader ( input , HadoopDataSourceUtil . COMMENT_CHARSET ) ) ; while ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) ; LOG . trace ( "" + line ) ; } scanner . close ( ) ; } finally { input . close ( ) ; } } } else { if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , jobContext . getJobID ( ) , fs . makeQualified ( transactionInfo ) ) ) ; } fs . delete ( transactionInfo , false ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , jobContext . getJobID ( ) , fs . makeQualified ( transactionInfo ) ) ) ; } } } private void setCommitted ( JobContext jobContext , boolean value ) throws IOException { Configuration conf = jobContext . getConfiguration ( ) ; Path commitMark = getCommitMarkPath ( jobContext ) ; FileSystem fs = commitMark . getFileSystem ( conf ) ; if ( value ) { if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , jobContext . getJobID ( ) , fs . makeQualified ( commitMark ) ) ) ; } fs . create ( commitMark , false ) . close ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , jobContext . getJobID ( ) , fs . makeQualified ( commitMark ) ) ) ; } } else { if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , jobContext . getJobID ( ) , fs . makeQualified ( commitMark ) ) ) ; } fs . delete ( commitMark , false ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , jobContext . getJobID ( ) , fs . makeQualified ( commitMark ) ) ) ; } } } private boolean isCommitted ( JobContext jobContext ) throws IOException { Path commitMark = getCommitMarkPath ( jobContext ) ; FileSystem fs = commitMark . getFileSystem ( jobContext . getConfiguration ( ) ) ; return fs . exists ( commitMark ) ; } @ Override public void abortJob ( JobContext jobContext , State state ) throws IOException { if ( outputMap . isEmpty ( ) ) { return ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , jobContext . getJobID ( ) , state ) ) ; } if ( state == State . FAILED ) { doCleanupJob ( jobContext ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , jobContext . getJobID ( ) , state ) ) ; } } private void doCleanupJob ( JobContext jobContext ) throws IOException { if ( isCommitted ( jobContext ) ) { rollforward ( jobContext ) ; } cleanup ( jobContext ) ; setCommitted ( jobContext , false ) ; setTransactionInfo ( jobContext , false ) ; } private void rollforward ( JobContext jobContext ) throws IOException { assert jobContext != null ; for ( Map . Entry < String , String > entry : outputMap . entrySet ( ) ) { String containerPath = entry . getKey ( ) ; String id = entry . getValue ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , id , jobContext . getJobID ( ) ) ) ; } OutputTransactionContext context = HadoopDataSourceUtil . createContext ( jobContext , id ) ; try { DirectDataSource repo = repository . getRelatedDataSource ( containerPath ) ; repo . commitTransactionOutput ( context ) ; } catch ( IOException e ) { LOG . error ( MessageFormat . format ( "" , id , jobContext . getJobID ( ) ) , e ) ; throw e ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( MessageFormat . format ( "" , context . getTransactionId ( ) , containerPath ) ) . initCause ( e ) ; } context . getCounter ( ) . add ( ) ; } } private void cleanup ( JobContext jobContext ) throws IOException { for ( Map . Entry < String , String > entry : outputMap . entrySet ( ) ) { String containerPath = entry . getKey ( ) ; String id = entry . getValue ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , id , jobContext . getJobID ( ) ) ) ; } OutputTransactionContext context = HadoopDataSourceUtil . createContext ( jobContext , id ) ; try { DirectDataSource repo = repository . getRelatedDataSource ( containerPath ) ; repo . cleanupTransactionOutput ( context ) ; } catch ( IOException e ) { LOG . error ( MessageFormat . format ( "" , id , jobContext . getJobID ( ) ) , e ) ; throw e ; } catch ( InterruptedException e ) { throw ( IOException ) new InterruptedIOException ( MessageFormat . format ( "" , context . getTransactionId ( ) , containerPath ) ) . initCause ( e ) ; } context . getCounter ( ) . add ( ) ; } } private static Path getTransactionInfoPath ( JobContext context ) throws IOException { assert context != null ; Configuration conf = context . getConfiguration ( ) ; String executionId = conf . get ( StageConstants . PROP_EXECUTION_ID ) ; return HadoopDataSourceUtil . getTransactionInfoPath ( conf , executionId ) ; } private static Path getCommitMarkPath ( JobContext context ) throws IOException { assert context != null ; Configuration conf = context . getConfiguration ( ) ; String executionId = conf . get ( StageConstants . PROP_EXECUTION_ID ) ; return HadoopDataSourceUtil . getCommitMarkPath ( conf , executionId ) ; } } } package com . asakusafw . runtime . stage . output ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . SequenceFile . CompressionType ; import org . apache . hadoop . io . compress . CompressionCodec ; import org . apache . hadoop . io . compress . DefaultCodec ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . OutputFormat ; import org . apache . hadoop . mapreduce . RecordWriter ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . lib . output . FileOutputCommitter ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; import org . apache . hadoop . mapreduce . lib . output . SequenceFileOutputFormat ; import org . apache . hadoop . mapreduce . security . TokenCache ; import org . apache . hadoop . util . ReflectionUtils ; public final class TemporaryOutputFormat < T > extends OutputFormat < NullWritable , T > { static final Log LOG = LogFactory . getLog ( TemporaryOutputFormat . class ) ; public static final String DEFAULT_FILE_NAME = "" ; private static final String KEY_OUTPUT_PATH = "" ; private FileOutputCommitter committerCache ; @ Override public void checkOutputSpecs ( JobContext context ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } Path path = getOutputPath ( context ) ; if ( TemporaryOutputFormat . getOutputPath ( context ) == null ) { throw new IOException ( "" ) ; } TokenCache . obtainTokensForNamenodes ( context . getCredentials ( ) , new Path [ ] { path } , context . getConfiguration ( ) ) ; if ( path . getFileSystem ( context . getConfiguration ( ) ) . exists ( path ) ) { throw new IOException ( MessageFormat . format ( "" , path ) ) ; } } @ Override public RecordWriter < NullWritable , T > getRecordWriter ( TaskAttemptContext context ) throws IOException , InterruptedException { @ SuppressWarnings ( "" ) Class < T > valueClass = ( Class < T > ) context . getOutputValueClass ( ) ; return createRecordWriter ( context , DEFAULT_FILE_NAME , valueClass ) ; } public < V > RecordWriter < NullWritable , V > createRecordWriter ( TaskAttemptContext context , String name , Class < V > dataType ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } CompressionCodec codec = null ; CompressionType compressionType = CompressionType . NONE ; Configuration conf = context . getConfiguration ( ) ; if ( FileOutputFormat . getCompressOutput ( context ) ) { compressionType = SequenceFileOutputFormat . getOutputCompressionType ( context ) ; Class < ? > codecClass = FileOutputFormat . getOutputCompressorClass ( context , DefaultCodec . class ) ; codec = ( CompressionCodec ) ReflectionUtils . newInstance ( codecClass , conf ) ; } FileOutputCommitter committer = getOutputCommitter ( context ) ; Path file = new Path ( committer . getWorkPath ( ) , FileOutputFormat . getUniqueFile ( context , name , "" ) ) ; FileSystem fs = file . getFileSystem ( conf ) ; final SequenceFile . Writer out = SequenceFile . createWriter ( fs , conf , file , NullWritable . class , dataType , compressionType , codec , context ) ; return new RecordWriter < NullWritable , V > ( ) { @ Override public void write ( NullWritable key , V value ) throws IOException { out . append ( key , value ) ; } @ Override public void close ( TaskAttemptContext ignored ) throws IOException { out . close ( ) ; } } ; } @ Override public synchronized FileOutputCommitter getOutputCommitter ( TaskAttemptContext context ) throws IOException { if ( committerCache == null ) { committerCache = createOutputCommitter ( context ) ; } return committerCache ; } private FileOutputCommitter createOutputCommitter ( TaskAttemptContext context ) throws IOException { assert context != null ; if ( getOutputPath ( context ) . equals ( FileOutputFormat . getOutputPath ( context ) ) ) { return ( FileOutputCommitter ) new EmptyFileOutputFormat ( ) . getOutputCommitter ( context ) ; } else { return new FileOutputCommitter ( getOutputPath ( context ) , context ) ; } } public static Path getOutputPath ( JobContext context ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } String pathString = context . getConfiguration ( ) . get ( KEY_OUTPUT_PATH ) ; if ( pathString == null ) { return null ; } return new Path ( pathString ) ; } public static void setOutputPath ( JobContext context , Path path ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } context . getConfiguration ( ) . set ( KEY_OUTPUT_PATH , path . toString ( ) ) ; } } package com . asakusafw . runtime . stage . output ; import java . io . IOException ; import org . apache . hadoop . mapreduce . RecordWriter ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; public final class EmptyFileOutputFormat extends FileOutputFormat < Object , Object > { @ Override public RecordWriter < Object , Object > getRecordWriter ( TaskAttemptContext job ) throws IOException , InterruptedException { return new RecordWriter < Object , Object > ( ) { @ Override public void write ( Object key , Object value ) throws IOException , InterruptedException { return ; } @ Override public void close ( TaskAttemptContext context ) throws IOException , InterruptedException { return ; } } ; } } package com . asakusafw . runtime . stage ; import java . io . IOException ; import java . net . URL ; import java . net . URLClassLoader ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . LinkedList ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . util . GenericOptionsParser ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; public final class ToolLauncher { public static final int JOB_SUCCEEDED = ; public static final int JOB_FAILED = ; public static final int LAUNCH_ERROR = - ; public static final int CLIENT_ERROR = - ; public static void main ( String ... args ) { if ( args == null ) { throw new IllegalArgumentException ( "" ) ; } LinkedList < String > arguments = new LinkedList < String > ( ) ; Collections . addAll ( arguments , args ) ; int result = main ( arguments ) ; System . exit ( result ) ; } private static int main ( LinkedList < String > args ) { assert args != null ; if ( args . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } String main = args . removeFirst ( ) ; Tool tool ; try { URL [ ] libraries = parseLibraries ( args ) ; ClassLoader loader = createLoader ( libraries ) ; tool = newTool ( main , loader ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return LAUNCH_ERROR ; } try { return ToolRunner . run ( tool , args . toArray ( new String [ args . size ( ) ] ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return CLIENT_ERROR ; } } private static URL [ ] parseLibraries ( LinkedList < String > args ) throws IOException { assert args != null ; GenericOptionsParser options = new GenericOptionsParser ( args . toArray ( new String [ args . size ( ) ] ) ) ; Configuration conf = options . getConfiguration ( ) ; return GenericOptionsParser . getLibJars ( conf ) ; } private static ClassLoader createLoader ( URL [ ] libraries ) { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( loader == null ) { loader = ToolLauncher . class . getClassLoader ( ) ; } if ( libraries == null || libraries . length == ) { return loader ; } return new URLClassLoader ( libraries , loader ) ; } private static Tool newTool ( String className , ClassLoader loader ) { assert className != null ; assert loader != null ; Class < ? > aClass ; try { aClass = Class . forName ( className , false , loader ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , className ) , e ) ; } if ( Tool . class . isAssignableFrom ( aClass ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , className ) ) ; } ClassLoader context = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( loader ) ; return aClass . asSubclass ( Tool . class ) . newInstance ( ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , aClass ) ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( context ) ; } } private ToolLauncher ( ) { return ; } } package com . asakusafw . runtime . stage ; import static com . asakusafw . runtime . stage . StageConstants . * ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . RawComparator ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . mapreduce . Mapper ; import org . apache . hadoop . mapreduce . OutputFormat ; import org . apache . hadoop . mapreduce . Partitioner ; import org . apache . hadoop . mapreduce . Reducer ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . stage . input . StageInputDriver ; import com . asakusafw . runtime . stage . input . StageInputFormat ; import com . asakusafw . runtime . stage . input . StageInputMapper ; import com . asakusafw . runtime . stage . output . LegacyBridgeOutputCommitter ; import com . asakusafw . runtime . stage . output . StageOutputDriver ; import com . asakusafw . runtime . stage . output . StageOutputFormat ; import com . asakusafw . runtime . stage . resource . StageResourceDriver ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . runtime . util . VariableTable . RedefineStrategy ; public abstract class AbstractStageClient extends BaseStageClient { public static final String METHOD_STAGE_OUTPUT_PATH = "" ; public static final String METHOD_STAGE_INPUTS = "" ; public static final String METHOD_STAGE_OUTPUTS = "" ; public static final String METHOD_STAGE_RESOURCES = "" ; public static final String METHOD_SHUFFLE_KEY_CLASS = "" ; public static final String METHOD_SHUFFLE_VALUE_CLASS = "" ; public static final String METHOD_PARTITIONER_CLASS = "" ; public static final String METHOD_COMBINER_CLASS = "" ; public static final String METHOD_SORT_COMPARATOR_CLASS = "" ; public static final String METHOD_GROUPING_COMPARATOR_CLASS = "" ; public static final String METHOD_REDUCER_CLASS = "" ; static final Log LOG = LogFactory . getLog ( AbstractStageClient . class ) ; protected void configureStage ( Job job , VariableTable variables ) { return ; } protected abstract List < StageInput > getStageInputs ( ) ; protected abstract String getStageOutputPath ( ) ; protected List < StageOutput > getStageOutputs ( ) { return Collections . emptyList ( ) ; } protected List < StageResource > getStageResources ( ) { return Collections . emptyList ( ) ; } protected Class < ? extends Writable > getShuffleKeyClassOrNull ( ) { return null ; } protected Class < ? extends Writable > getShuffleValueClassOrNull ( ) { return null ; } @ SuppressWarnings ( "" ) protected Class < ? extends Partitioner > getPartitionerClassOrNull ( ) { return null ; } @ SuppressWarnings ( "" ) protected Class < ? extends Reducer > getCombinerClassOrNull ( ) { return null ; } @ SuppressWarnings ( "" ) protected Class < ? extends RawComparator > getSortComparatorClassOrNull ( ) { return null ; } @ SuppressWarnings ( "" ) protected Class < ? extends RawComparator > getGroupingComparatorClassOrNull ( ) { return null ; } @ SuppressWarnings ( "" ) protected Class < ? extends Reducer > getReducerClassOrNull ( ) { return null ; } @ Override protected int execute ( String [ ] args ) throws Exception { Configuration conf = getConf ( ) ; conf . set ( StageConstants . PROP_BATCH_ID , getBatchId ( ) ) ; conf . set ( StageConstants . PROP_FLOW_ID , getFlowId ( ) ) ; Job job = createJob ( conf ) ; return submit ( job ) ; } public Job createJob ( Configuration conf ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } Job job = new Job ( conf ) ; VariableTable variables = getPathParser ( job . getConfiguration ( ) ) ; configureJobInfo ( job , variables ) ; configureStageInput ( job , variables ) ; configureStageOutput ( job , variables ) ; configureShuffle ( job , variables ) ; configureStageResource ( job , variables ) ; configureStage ( job , variables ) ; return job ; } private int submit ( Job job ) throws IOException , InterruptedException , ClassNotFoundException { LOG . info ( MessageFormat . format ( "" , job . getJobName ( ) ) ) ; long start = System . currentTimeMillis ( ) ; boolean succeed ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { LOG . info ( MessageFormat . format ( "" , job . getJobName ( ) ) ) ; succeed = true ; } else { job . submit ( ) ; LOG . info ( MessageFormat . format ( "" , job . getJobID ( ) , job . getJobName ( ) ) ) ; succeed = job . waitForCompletion ( true ) ; } long end = System . currentTimeMillis ( ) ; LOG . info ( MessageFormat . format ( "" , job . getJobID ( ) , job . getJobName ( ) , succeed , String . valueOf ( end - start ) ) ) ; return succeed ? ToolLauncher . JOB_SUCCEEDED : ToolLauncher . JOB_FAILED ; } private void configureJobInfo ( Job job , VariableTable variables ) { Class < ? > clientClass = getClass ( ) ; String definitionId = getDefinitionId ( ) ; LOG . info ( MessageFormat . format ( "" , clientClass . getName ( ) ) ) ; job . setJarByClass ( clientClass ) ; LOG . info ( MessageFormat . format ( "" , definitionId ) ) ; job . setJobName ( definitionId ) ; } private void configureStageInput ( Job job , VariableTable variables ) { List < StageInput > inputList = new ArrayList < StageInput > ( ) ; for ( StageInput input : getStageInputs ( ) ) { Class < ? extends Mapper < ? , ? , ? , ? > > mapperClass = input . getMapperClass ( ) ; String pathString = input . getPathString ( ) ; Class < ? extends InputFormat < ? , ? > > formatClass = input . getFormatClass ( ) ; String expanded = variables . parse ( pathString ) ; Map < String , String > attributes = input . getAttributes ( ) ; LOG . info ( MessageFormat . format ( "" , expanded , formatClass . getName ( ) , mapperClass . getName ( ) , attributes ) ) ; inputList . add ( new StageInput ( expanded , formatClass , mapperClass , attributes ) ) ; } StageInputDriver . set ( job , inputList ) ; job . setInputFormatClass ( StageInputFormat . class ) ; job . setMapperClass ( StageInputMapper . class ) ; } @ SuppressWarnings ( "" ) private void configureShuffle ( Job job , VariableTable variables ) { Class < ? extends Reducer > reducer = getReducerClassOrNull ( ) ; if ( reducer != null ) { LOG . info ( MessageFormat . format ( "" , reducer . getName ( ) ) ) ; job . setReducerClass ( reducer ) ; } else { LOG . info ( "" ) ; job . setNumReduceTasks ( ) ; return ; } Class < ? extends Writable > outputKeyClass = or ( getShuffleKeyClassOrNull ( ) , NullWritable . class ) ; Class < ? extends Writable > outputValueClass = or ( getShuffleValueClassOrNull ( ) , NullWritable . class ) ; LOG . info ( MessageFormat . format ( "" , outputKeyClass . getName ( ) , outputValueClass . getName ( ) ) ) ; job . setMapOutputKeyClass ( outputKeyClass ) ; job . setMapOutputValueClass ( outputValueClass ) ; Class < ? extends Reducer > combiner = getCombinerClassOrNull ( ) ; if ( combiner != null ) { LOG . info ( MessageFormat . format ( "" , combiner . getName ( ) ) ) ; job . setCombinerClass ( combiner ) ; } else { LOG . info ( "" ) ; } Class < ? extends Partitioner > partitioner = getPartitionerClassOrNull ( ) ; if ( partitioner != null ) { LOG . info ( MessageFormat . format ( "" , partitioner . getName ( ) ) ) ; job . setPartitionerClass ( partitioner ) ; } else { LOG . info ( "" ) ; } Class < ? extends RawComparator > groupingComparator = getGroupingComparatorClassOrNull ( ) ; if ( groupingComparator != null ) { LOG . info ( MessageFormat . format ( "" , groupingComparator . getName ( ) ) ) ; job . setGroupingComparatorClass ( groupingComparator ) ; } else { LOG . info ( "" ) ; } Class < ? extends RawComparator > sortComparator = getSortComparatorClassOrNull ( ) ; if ( sortComparator != null ) { LOG . info ( MessageFormat . format ( "" , sortComparator . getName ( ) ) ) ; job . setSortComparatorClass ( sortComparator ) ; } else { LOG . info ( "" ) ; } } private void configureStageResource ( Job job , VariableTable variables ) throws IOException { List < StageResource > resources = getStageResources ( ) ; for ( StageResource cache : resources ) { String resolved = variables . parse ( cache . getLocation ( ) ) ; LOG . info ( MessageFormat . format ( "" , cache . getName ( ) , resolved ) ) ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { LOG . info ( "" ) ; } else { StageResourceDriver . add ( job , resolved , cache . getName ( ) ) ; } } } private void configureStageOutput ( Job job , VariableTable variables ) { String outputPath = variables . parse ( getStageOutputPath ( ) ) ; List < StageOutput > outputList = new ArrayList < StageOutput > ( ) ; for ( StageOutput output : getStageOutputs ( ) ) { String name = output . getName ( ) ; Class < ? > keyClass = output . getKeyClass ( ) ; Class < ? > valueClass = output . getValueClass ( ) ; Class < ? extends OutputFormat < ? , ? > > formatClass = output . getFormatClass ( ) ; Map < String , String > attributes = output . getAttributes ( ) ; LOG . info ( MessageFormat . format ( "" , outputPath , name , formatClass . getName ( ) , keyClass . getName ( ) , valueClass . getName ( ) , attributes ) ) ; outputList . add ( new StageOutput ( name , keyClass , valueClass , formatClass , attributes ) ) ; } StageOutputDriver . set ( job , outputPath , outputList ) ; job . setOutputKeyClass ( NullWritable . class ) ; job . setOutputValueClass ( NullWritable . class ) ; job . setOutputFormatClass ( StageOutputFormat . class ) ; job . getConfiguration ( ) . setClass ( "" , LegacyBridgeOutputCommitter . class , org . apache . hadoop . mapred . OutputCommitter . class ) ; } private < T > T or ( T a , T b ) { if ( a != null ) { return a ; } else { return b ; } } private VariableTable getPathParser ( Configuration configuration ) { assert configuration != null ; VariableTable variables = new VariableTable ( RedefineStrategy . IGNORE ) ; variables . defineVariable ( VAR_USER , getUser ( ) ) ; variables . defineVariable ( VAR_DEFINITION_ID , getDefinitionId ( ) ) ; variables . defineVariable ( VAR_STAGE_ID , getStageId ( ) ) ; variables . defineVariable ( VAR_BATCH_ID , getBatchId ( ) ) ; variables . defineVariable ( VAR_FLOW_ID , getFlowId ( ) ) ; variables . defineVariable ( VAR_EXECUTION_ID , getExecutionId ( ) ) ; String arguments = configuration . get ( PROP_ASAKUSA_BATCH_ARGS ) ; if ( arguments == null ) { LOG . warn ( MessageFormat . format ( "" , PROP_ASAKUSA_BATCH_ARGS ) ) ; } else { variables . defineVariables ( arguments ) ; } configuration . set ( PROP_ASAKUSA_BATCH_ARGS , variables . toSerialString ( ) ) ; return variables ; } } package com . asakusafw . runtime . stage . resource ; package com . asakusafw . runtime . stage . resource ; import java . io . Closeable ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . filecache . DistributedCache ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . mapreduce . Job ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; public class StageResourceDriver implements Closeable { static final Log LOG = LogFactory . getLog ( StageResourceDriver . class ) ; private static final String PREFIX_LOCAL_CACHE_NAME = "" ; private final Configuration configuration ; private final FileSystem localFileSystem ; public StageResourceDriver ( Configuration configuration ) throws IOException { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . configuration = configuration ; this . localFileSystem = FileSystem . getLocal ( configuration ) ; } public Configuration getConfiguration ( ) { return configuration ; } public List < Path > findCache ( String resourceName ) throws IOException { if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" + resourceName ) ; } String [ ] localNames = getConfiguration ( ) . getStrings ( getLocalCacheNameKey ( resourceName ) ) ; List < Path > results = new ArrayList < Path > ( ) ; for ( String localName : localNames ) { Path resolvedPath = findLocalCache ( resourceName , localName ) ; if ( resolvedPath == null ) { return Collections . emptyList ( ) ; } results . add ( resolvedPath ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , resourceName , results ) ) ; } return results ; } private Path findLocalCache ( String resourceName , String localName ) throws IOException { assert localName != null ; Path cache = new Path ( localName ) ; if ( localFileSystem . exists ( cache ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" + cache ) ; } return localFileSystem . makeQualified ( cache ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" + localName ) ; } Path directPath = findCacheForLocalMode ( resourceName , localName ) ; return directPath ; } private Path findCacheForLocalMode ( String resourceName , String localName ) throws IOException { assert resourceName != null ; assert localName != null ; Path remotePath = null ; String remoteName = null ; for ( URI uri : DistributedCache . getCacheFiles ( configuration ) ) { if ( localName . equals ( uri . getFragment ( ) ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" + uri ) ; } String rpath = uri . getPath ( ) ; remotePath = new Path ( uri ) ; remoteName = rpath . substring ( rpath . lastIndexOf ( '' ) + ) ; break ; } } if ( remoteName == null ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" + resourceName ) ; } return null ; } assert remotePath != null ; for ( Path path : DistributedCache . getLocalCacheFiles ( configuration ) ) { String localFileName = path . getName ( ) ; if ( remoteName . equals ( localFileName ) == false ) { continue ; } if ( localFileSystem . exists ( path ) == false ) { continue ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" + path ) ; } return localFileSystem . makeQualified ( path ) ; } FileSystem remoteFileSystem = remotePath . getFileSystem ( configuration ) ; remotePath = remoteFileSystem . makeQualified ( remotePath ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" + remotePath ) ; } if ( isLocal ( remoteFileSystem ) == false ) { LOG . warn ( MessageFormat . format ( "" , resourceName , localName ) ) ; } return remotePath ; } private boolean isLocal ( FileSystem fs ) { assert fs != null ; if ( fs == localFileSystem ) { return true ; } return fs . getUri ( ) . equals ( localFileSystem . getUri ( ) ) ; } @ Override public void close ( ) throws IOException { return ; } public static void add ( Job job , String resourcePath , String resourceName ) throws IOException { if ( job == null ) { throw new IllegalArgumentException ( "" ) ; } if ( resourcePath == null ) { throw new IllegalArgumentException ( "" ) ; } if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } List < Path > list = TemporaryStorage . list ( job . getConfiguration ( ) , new Path ( resourcePath ) ) ; if ( list . isEmpty ( ) ) { throw new IOException ( MessageFormat . format ( "" , resourcePath ) ) ; } String [ ] added = job . getConfiguration ( ) . getStrings ( getLocalCacheNameKey ( resourceName ) ) ; List < String > localNames = new ArrayList < String > ( ) ; if ( added != null && added . length >= ) { Collections . addAll ( localNames , added ) ; } int index = localNames . size ( ) ; for ( Path path : list ) { String name = String . format ( "" , resourceName , index ++ ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( path . toString ( ) ) ; buf . append ( '' ) ; buf . append ( name ) ; localNames . add ( name ) ; try { URI uri = new URI ( buf . toString ( ) ) ; DistributedCache . addCacheFile ( uri , job . getConfiguration ( ) ) ; } catch ( URISyntaxException e ) { throw new IllegalStateException ( e ) ; } } job . getConfiguration ( ) . setStrings ( getLocalCacheNameKey ( resourceName ) , localNames . toArray ( new String [ localNames . size ( ) ] ) ) ; if ( ( job . getConfiguration ( ) . get ( "" , "" ) . equals ( "" ) ) && ( job . getConfiguration ( ) . get ( "" , "" ) . equals ( "" ) ) ) { LOG . info ( "" ) ; } else { DistributedCache . createSymlink ( job . getConfiguration ( ) ) ; } } private static String getLocalCacheNameKey ( String resourceName ) { assert resourceName != null ; return PREFIX_LOCAL_CACHE_NAME + resourceName ; } } package com . asakusafw . runtime . stage ; import static com . asakusafw . runtime . stage . StageConstants . * ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . runtime . util . VariableTable . RedefineStrategy ; public abstract class AbstractCleanupStageClient extends BaseStageClient { public static final String IMPLEMENTATION = "" ; public static final String METHOD_CLEANUP_PATH = "" ; static final Log LOG = LogFactory . getLog ( AbstractCleanupStageClient . class ) ; protected abstract String getCleanupPath ( ) ; @ Override protected int execute ( String [ ] args ) throws IOException , InterruptedException { Configuration conf = getConf ( ) ; Path path = getPath ( conf ) ; FileSystem fileSystem = FileSystem . get ( path . toUri ( ) , conf ) ; try { LOG . info ( MessageFormat . format ( "" , getBatchId ( ) , getFlowId ( ) , getExecutionId ( ) , path ) ) ; long start = System . currentTimeMillis ( ) ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { LOG . info ( MessageFormat . format ( "" + "" , getBatchId ( ) , getFlowId ( ) , getExecutionId ( ) , path ) ) ; } else { FileStatus stat = fileSystem . getFileStatus ( path ) ; if ( stat == null ) { throw new FileNotFoundException ( path . toString ( ) ) ; } LOG . info ( MessageFormat . format ( "" , getBatchId ( ) , getFlowId ( ) , getExecutionId ( ) , path ) ) ; if ( fileSystem . delete ( path , true ) == false ) { throw new IOException ( "" ) ; } } long end = System . currentTimeMillis ( ) ; LOG . info ( MessageFormat . format ( "" , getBatchId ( ) , getFlowId ( ) , getExecutionId ( ) , path , end - start ) ) ; return ; } catch ( FileNotFoundException e ) { LOG . warn ( MessageFormat . format ( "" , getBatchId ( ) , getFlowId ( ) , getExecutionId ( ) , path ) ) ; return ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , getBatchId ( ) , getFlowId ( ) , getExecutionId ( ) , path ) , e ) ; return ; } finally { FileSystem . closeAll ( ) ; } } private Path getPath ( Configuration conf ) { VariableTable variables = getPathParser ( conf ) ; String barePath = getCleanupPath ( ) ; String pathString = variables . parse ( barePath , false ) ; Path path = new Path ( pathString ) ; return path ; } private VariableTable getPathParser ( Configuration configuration ) { assert configuration != null ; VariableTable variables = new VariableTable ( RedefineStrategy . IGNORE ) ; variables . defineVariable ( VAR_USER , getUser ( ) ) ; variables . defineVariable ( VAR_DEFINITION_ID , getDefinitionId ( ) ) ; variables . defineVariable ( VAR_STAGE_ID , getStageId ( ) ) ; variables . defineVariable ( VAR_BATCH_ID , getBatchId ( ) ) ; variables . defineVariable ( VAR_FLOW_ID , getFlowId ( ) ) ; variables . defineVariable ( VAR_EXECUTION_ID , getExecutionId ( ) ) ; String arguments = configuration . get ( PROP_ASAKUSA_BATCH_ARGS ) ; if ( arguments == null ) { LOG . warn ( MessageFormat . format ( "" , PROP_ASAKUSA_BATCH_ARGS ) ) ; } else { variables . defineVariables ( arguments ) ; } return variables ; } } package com . asakusafw . runtime . stage ; package com . asakusafw . runtime . stage ; import java . util . Collections ; import java . util . Map ; import java . util . TreeMap ; import org . apache . hadoop . mapreduce . OutputFormat ; public class StageOutput { private final String name ; private final Class < ? > keyClass ; private final Class < ? > valueClass ; private final Class < ? extends OutputFormat < ? , ? > > formatClass ; private final Map < String , String > attributes ; @ SuppressWarnings ( { "" } ) public StageOutput ( String name , Class < ? > keyClass , Class < ? > valueClass , Class < ? extends OutputFormat > formatClass ) { this ( name , keyClass , valueClass , formatClass , Collections . < String , String > emptyMap ( ) ) ; } @ SuppressWarnings ( { "" , "" } ) public StageOutput ( String name , Class < ? > keyClass , Class < ? > valueClass , Class < ? extends OutputFormat > formatClass , Map < String , String > attributes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( keyClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( valueClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( formatClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . keyClass = keyClass ; this . valueClass = valueClass ; this . formatClass = ( Class < ? extends OutputFormat < ? , ? > > ) formatClass ; this . attributes = Collections . unmodifiableMap ( new TreeMap < String , String > ( attributes ) ) ; } public String getName ( ) { return name ; } public Class < ? > getKeyClass ( ) { return keyClass ; } public Class < ? > getValueClass ( ) { return valueClass ; } public Class < ? extends OutputFormat < ? , ? > > getFormatClass ( ) { return formatClass ; } public Map < String , String > getAttributes ( ) { return attributes ; } } package com . asakusafw . runtime . stage . input ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . Mapper ; public abstract class SplitCombiner { protected abstract List < StageInputSplit > combine ( JobContext context , List < StageInputSplit > splits ) throws IOException , InterruptedException ; public static final class Util { private Util ( ) { return ; } public static Map < Class < ? extends Mapper < ? , ? , ? , ? > > , List < StageInputSplit . Source > > groupByMapper ( List < StageInputSplit > splits ) { if ( splits == null ) { throw new IllegalArgumentException ( "" ) ; } Map < Class < ? extends Mapper < ? , ? , ? , ? > > , List < StageInputSplit . Source > > results = new HashMap < Class < ? extends Mapper < ? , ? , ? , ? > > , List < StageInputSplit . Source > > ( ) ; for ( StageInputSplit split : splits ) { Class < ? extends Mapper < ? , ? , ? , ? > > mapper = split . getMapperClass ( ) ; List < StageInputSplit . Source > group = results . get ( mapper ) ; if ( group == null ) { group = new ArrayList < StageInputSplit . Source > ( ) ; results . put ( mapper , group ) ; } group . addAll ( split . getSources ( ) ) ; } return results ; } } } package com . asakusafw . runtime . stage . input ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInput ; import java . io . DataInputStream ; import java . io . DataOutput ; import java . io . DataOutputStream ; import java . io . IOException ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . SortedSet ; import java . util . TreeSet ; import java . util . zip . GZIPInputStream ; import java . util . zip . GZIPOutputStream ; import org . apache . commons . codec . binary . Base64InputStream ; import org . apache . commons . codec . binary . Base64OutputStream ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . WritableUtils ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . mapreduce . Mapper ; import com . asakusafw . runtime . stage . StageInput ; public final class StageInputDriver { static final Log LOG = LogFactory . getLog ( StageInputDriver . class ) ; private static final Charset ASCII = Charset . forName ( "" ) ; private static final long SERIAL_VERSION = ; private static final String KEY = "" ; public static void set ( Job job , List < StageInput > inputList ) { if ( job == null ) { throw new IllegalArgumentException ( "" ) ; } if ( inputList == null ) { throw new IllegalArgumentException ( "" ) ; } try { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , inputList . size ( ) ) ) ; } String encoded = encode ( inputList ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , encoded . length ( ) ) ) ; } job . getConfiguration ( ) . set ( KEY , encoded ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , KEY ) , e ) ; } } static List < StageInput > getInputs ( Configuration conf ) throws IOException { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } String encoded = conf . getRaw ( KEY ) ; if ( encoded == null ) { return Collections . emptyList ( ) ; } try { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , encoded . length ( ) ) ) ; } List < StageInput > inputList = decode ( conf , encoded ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , inputList . size ( ) ) ) ; } return inputList ; } catch ( IOException e ) { throw new IOException ( MessageFormat . format ( "" , KEY ) , e ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( MessageFormat . format ( "" , KEY ) , e ) ; } } private static String encode ( List < StageInput > inputList ) throws IOException { assert inputList != null ; String [ ] dictionary = buildDictionary ( inputList ) ; ByteArrayOutputStream sink = new ByteArrayOutputStream ( ) ; DataOutputStream output = new DataOutputStream ( new GZIPOutputStream ( new Base64OutputStream ( sink ) ) ) ; WritableUtils . writeVLong ( output , SERIAL_VERSION ) ; WritableUtils . writeStringArray ( output , dictionary ) ; WritableUtils . writeVInt ( output , inputList . size ( ) ) ; for ( StageInput input : inputList ) { writeEncoded ( output , dictionary , input . getPathString ( ) ) ; writeEncoded ( output , dictionary , input . getFormatClass ( ) . getName ( ) ) ; writeEncoded ( output , dictionary , input . getMapperClass ( ) . getName ( ) ) ; WritableUtils . writeVInt ( output , input . getAttributes ( ) . size ( ) ) ; for ( Map . Entry < String , String > attribute : input . getAttributes ( ) . entrySet ( ) ) { writeEncoded ( output , dictionary , attribute . getKey ( ) ) ; writeEncoded ( output , dictionary , attribute . getValue ( ) ) ; } } output . close ( ) ; return new String ( sink . toByteArray ( ) , ASCII ) ; } @ SuppressWarnings ( "" ) private static List < StageInput > decode ( Configuration conf , String encoded ) throws IOException , ClassNotFoundException { assert conf != null ; assert encoded != null ; ByteArrayInputStream source = new ByteArrayInputStream ( encoded . getBytes ( ASCII ) ) ; DataInputStream input = new DataInputStream ( new GZIPInputStream ( new Base64InputStream ( source ) ) ) ; long version = WritableUtils . readVLong ( input ) ; if ( version != SERIAL_VERSION ) { throw new IOException ( MessageFormat . format ( "" , SERIAL_VERSION , version ) ) ; } String [ ] dictionary = WritableUtils . readStringArray ( input ) ; int inputListSize = WritableUtils . readVInt ( input ) ; List < StageInput > results = new ArrayList < StageInput > ( ) ; for ( int inputListIndex = ; inputListIndex < inputListSize ; inputListIndex ++ ) { String pathString = readEncoded ( input , dictionary ) ; String formatName = readEncoded ( input , dictionary ) ; String mapperName = readEncoded ( input , dictionary ) ; int attributeCount = WritableUtils . readVInt ( input ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; for ( int attributeIndex = ; attributeIndex < attributeCount ; attributeIndex ++ ) { String keyString = readEncoded ( input , dictionary ) ; String valueString = readEncoded ( input , dictionary ) ; attributes . put ( keyString , valueString ) ; } Class < ? extends InputFormat > formatClass = conf . getClassByName ( formatName ) . asSubclass ( InputFormat . class ) ; Class < ? extends Mapper > mapperClass = conf . getClassByName ( mapperName ) . asSubclass ( Mapper . class ) ; results . add ( new StageInput ( pathString , formatClass , mapperClass , attributes ) ) ; } return results ; } private static String [ ] buildDictionary ( List < StageInput > inputList ) { assert inputList != null ; SortedSet < String > values = new TreeSet < String > ( ) ; for ( StageInput input : inputList ) { values . add ( input . getPathString ( ) ) ; values . add ( input . getFormatClass ( ) . getName ( ) ) ; values . add ( input . getMapperClass ( ) . getName ( ) ) ; values . addAll ( input . getAttributes ( ) . keySet ( ) ) ; values . addAll ( input . getAttributes ( ) . values ( ) ) ; } return values . toArray ( new String [ values . size ( ) ] ) ; } private static String readEncoded ( DataInput input , String [ ] dictionary ) throws IOException { assert input != null ; assert dictionary != null ; int index = WritableUtils . readVInt ( input ) ; if ( index < || index >= dictionary . length ) { throw new IOException ( MessageFormat . format ( "" , index , Arrays . toString ( dictionary ) ) ) ; } return dictionary [ index ] ; } private static void writeEncoded ( DataOutput output , String [ ] dictionary , String value ) throws IOException { assert output != null ; assert dictionary != null ; assert value != null ; int index = Arrays . binarySearch ( dictionary , value ) ; if ( index < ) { throw new IllegalStateException ( MessageFormat . format ( "" , value , Arrays . toString ( dictionary ) ) ) ; } WritableUtils . writeVInt ( output , index ) ; } private StageInputDriver ( ) { return ; } } package com . asakusafw . runtime . stage . input ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . InputSplit ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . Mapper ; import org . apache . hadoop . mapreduce . RecordReader ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . lib . input . FileInputFormat ; import org . apache . hadoop . util . ReflectionUtils ; import com . asakusafw . runtime . stage . StageInput ; import com . asakusafw . runtime . stage . input . StageInputSplit . Source ; @ SuppressWarnings ( "" ) public class StageInputFormat extends InputFormat { private static final String DEFAULT = "" ; static final Log LOG = LogFactory . getLog ( StageInputFormat . class ) ; private static final Map < String , Class < ? extends SplitCombiner > > SPLIT_COMBINERS ; static { Map < String , Class < ? extends SplitCombiner > > map = new HashMap < String , Class < ? extends SplitCombiner > > ( ) ; map . put ( DEFAULT , DefaultSplitCombiner . class ) ; map . put ( "" , IdentitySplitCombiner . class ) ; map . put ( "" , ExtremeSplitCombiner . class ) ; SPLIT_COMBINERS = Collections . unmodifiableMap ( map ) ; } @ Override public List < InputSplit > getSplits ( JobContext context ) throws IOException , InterruptedException { List < StageInputSplit > splits = computeSplits ( context ) ; SplitCombiner combiner = getSplitCombiner ( context ) ; if ( LOG . isDebugEnabled ( ) ) { if ( ( combiner instanceof IdentitySplitCombiner ) == false ) { LOG . debug ( MessageFormat . format ( "" , splits . size ( ) , combiner . getClass ( ) . getName ( ) ) ) ; } } List < StageInputSplit > combined = combiner . combine ( context , splits ) ; if ( LOG . isDebugEnabled ( ) && splits . size ( ) != combined . size ( ) ) { LOG . debug ( MessageFormat . format ( "" , splits . size ( ) , combined . size ( ) ) ) ; } return new ArrayList < InputSplit > ( combined ) ; } private List < StageInputSplit > computeSplits ( JobContext context ) throws IOException , InterruptedException { assert context != null ; Map < FormatAndMapper , List < StageInput > > paths = getPaths ( context ) ; Map < Class < ? extends InputFormat < ? , ? > > , InputFormat < ? , ? > > formats = instantiateFormats ( context , paths . keySet ( ) ) ; Job temporaryJob = new Job ( context . getConfiguration ( ) ) ; List < StageInputSplit > results = new ArrayList < StageInputSplit > ( ) ; for ( Map . Entry < FormatAndMapper , List < StageInput > > entry : paths . entrySet ( ) ) { FormatAndMapper formatAndMapper = entry . getKey ( ) ; List < StageInput > current = entry . getValue ( ) ; InputFormat < ? , ? > format = formats . get ( formatAndMapper . formatClass ) ; List < ? extends InputSplit > splits ; if ( format instanceof FileInputFormat < ? , ? > ) { FileInputFormat . setInputPaths ( temporaryJob , toPathArray ( current ) ) ; splits = format . getSplits ( temporaryJob ) ; } else if ( format instanceof BridgeInputFormat ) { splits = ( ( BridgeInputFormat ) format ) . getSplits ( context , current ) ; } else if ( format instanceof TemporaryInputFormat < ? > ) { splits = ( ( TemporaryInputFormat < ? > ) format ) . getSplits ( context , current ) ; } else { splits = format . getSplits ( temporaryJob ) ; } assert format != null : formatAndMapper . formatClass . getName ( ) ; Class < ? extends Mapper < ? , ? , ? , ? > > mapper = formatAndMapper . mapperClass ; for ( InputSplit split : splits ) { Source source = new Source ( split , formatAndMapper . formatClass ) ; StageInputSplit wrapped = new StageInputSplit ( mapper , Collections . singletonList ( source ) ) ; wrapped . setConf ( context . getConfiguration ( ) ) ; results . add ( wrapped ) ; } } return results ; } private SplitCombiner getSplitCombiner ( JobContext context ) { assert context != null ; Class < ? extends SplitCombiner > combinerClass = getSplitCombinerClass ( context ) ; return ReflectionUtils . newInstance ( combinerClass , context . getConfiguration ( ) ) ; } private Class < ? extends SplitCombiner > getSplitCombinerClass ( JobContext context ) { assert context != null ; Configuration conf = context . getConfiguration ( ) ; String combinerType = conf . get ( "" , DEFAULT ) ; if ( isLocalMode ( context ) && combinerType . equals ( DEFAULT ) ) { return ExtremeSplitCombiner . class ; } Class < ? extends SplitCombiner > defined = SPLIT_COMBINERS . get ( combinerType ) ; if ( defined != null ) { return defined ; } try { return conf . getClassByName ( combinerType ) . asSubclass ( SplitCombiner . class ) ; } catch ( Exception e ) { LOG . warn ( MessageFormat . format ( "" , combinerType ) , e ) ; return IdentitySplitCombiner . class ; } } private boolean isLocalMode ( JobContext context ) { assert context != null ; return context . getConfiguration ( ) . get ( "" , "" ) . equals ( "" ) ; } private Path [ ] toPathArray ( List < StageInput > inputs ) { assert inputs != null ; List < Path > paths = new ArrayList < Path > ( ) ; for ( StageInput input : inputs ) { paths . add ( new Path ( input . getPathString ( ) ) ) ; } return paths . toArray ( new Path [ paths . size ( ) ] ) ; } private Map < FormatAndMapper , List < StageInput > > getPaths ( JobContext context ) throws IOException { assert context != null ; List < StageInput > inputs = StageInputDriver . getInputs ( context . getConfiguration ( ) ) ; Map < FormatAndMapper , List < StageInput > > paths = new HashMap < FormatAndMapper , List < StageInput > > ( ) ; for ( StageInput input : inputs ) { FormatAndMapper fam = new FormatAndMapper ( input . getFormatClass ( ) , input . getMapperClass ( ) ) ; List < StageInput > list = paths . get ( fam ) ; if ( list == null ) { list = new ArrayList < StageInput > ( ) ; paths . put ( fam , list ) ; } list . add ( input ) ; } return paths ; } private Map < Class < ? extends InputFormat < ? , ? > > , InputFormat < ? , ? > > instantiateFormats ( JobContext context , Set < FormatAndMapper > pairs ) throws IOException { assert context != null ; assert pairs != null ; Configuration conf = context . getConfiguration ( ) ; Map < Class < ? extends InputFormat < ? , ? > > , InputFormat < ? , ? > > results = new HashMap < Class < ? extends InputFormat < ? , ? > > , InputFormat < ? , ? > > ( ) ; for ( FormatAndMapper pair : pairs ) { Class < ? extends InputFormat < ? , ? > > type = pair . formatClass ; if ( results . containsKey ( type ) == false ) { try { InputFormat < ? , ? > instance = ReflectionUtils . newInstance ( type , conf ) ; results . put ( type , instance ) ; } catch ( RuntimeException e ) { throw new IOException ( MessageFormat . format ( "" , type . getName ( ) ) , e ) ; } } } return results ; } @ Override public RecordReader createRecordReader ( InputSplit split , TaskAttemptContext context ) throws IOException , InterruptedException { assert split instanceof StageInputSplit ; return new StageInputRecordReader ( ) ; } private static class FormatAndMapper { final Class < ? extends InputFormat < ? , ? > > formatClass ; final Class < ? extends Mapper < ? , ? , ? , ? > > mapperClass ; FormatAndMapper ( Class < ? extends InputFormat < ? , ? > > formatClass , Class < ? extends Mapper < ? , ? , ? , ? > > mapperClass ) { assert formatClass != null ; assert mapperClass != null ; this . formatClass = formatClass ; this . mapperClass = mapperClass ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + formatClass . hashCode ( ) ; result = prime * result + mapperClass . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } FormatAndMapper other = ( FormatAndMapper ) obj ; if ( formatClass . equals ( other . formatClass ) == false ) { return false ; } if ( mapperClass . equals ( other . mapperClass ) == false ) { return false ; } return true ; } } } package com . asakusafw . runtime . stage . input ; package com . asakusafw . runtime . stage . input ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . WritableUtils ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . InputSplit ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . RecordReader ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . util . ReflectionUtils ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceConstants ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . DirectInputFragment ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . directio . hadoop . HadoopDataSourceUtil ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . runtime . stage . StageInput ; import com . asakusafw . runtime . util . VariableTable ; public final class BridgeInputFormat extends InputFormat < NullWritable , Object > { static final Log LOG = LogFactory . getLog ( BridgeInputFormat . class ) ; @ Override @ Deprecated public List < InputSplit > getSplits ( JobContext context ) throws IOException , InterruptedException { throw new UnsupportedOperationException ( "" ) ; } public List < InputSplit > getSplits ( JobContext context , List < StageInput > inputList ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( inputList == null ) { throw new IllegalArgumentException ( "" ) ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , inputList . size ( ) ) ) ; } DirectDataSourceRepository repo = getDataSourceRepository ( context ) ; List < InputSplit > results = new ArrayList < InputSplit > ( ) ; Map < DirectInputGroup , List < InputPath > > patternGroups = extractInputList ( context , repo , inputList ) ; long totalSize = ; for ( Map . Entry < DirectInputGroup , List < InputPath > > entry : patternGroups . entrySet ( ) ) { DirectInputGroup group = entry . getKey ( ) ; List < InputPath > paths = entry . getValue ( ) ; DataFormat < ? > format = ReflectionUtils . newInstance ( group . formatClass , context . getConfiguration ( ) ) ; DirectDataSource dataSource = repo . getRelatedDataSource ( group . containerPath ) ; for ( InputPath path : paths ) { List < DirectInputFragment > fragments = getFragments ( repo , group , path , format , dataSource ) ; for ( DirectInputFragment fragment : fragments ) { totalSize += fragment . getSize ( ) ; results . add ( new BridgeInputSplit ( group , fragment ) ) ; } } } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( MessageFormat . format ( "" , inputList . size ( ) , results . size ( ) , totalSize ) ) ; } return results ; } private < T > List < DirectInputFragment > getFragments ( DirectDataSourceRepository repo , DirectInputGroup group , InputPath path , DataFormat < T > format , DirectDataSource dataSource ) throws IOException , InterruptedException { assert group != null ; assert path != null ; assert format != null ; assert dataSource != null ; Class < ? extends T > dataType = group . dataType . asSubclass ( format . getSupportedType ( ) ) ; List < DirectInputFragment > fragments = dataSource . findInputFragments ( dataType , format , path . componentPath , path . pattern ) ; if ( fragments . isEmpty ( ) ) { String id = repo . getRelatedId ( group . containerPath ) ; throw new IOException ( MessageFormat . format ( "" , id , path . originalBasePath , path . pattern ) ) ; } return fragments ; } private Map < DirectInputGroup , List < InputPath > > extractInputList ( JobContext context , DirectDataSourceRepository repo , List < StageInput > inputList ) throws IOException { assert context != null ; assert repo != null ; assert inputList != null ; String arguments = context . getConfiguration ( ) . get ( StageConstants . PROP_ASAKUSA_BATCH_ARGS , "" ) ; VariableTable variables = new VariableTable ( VariableTable . RedefineStrategy . IGNORE ) ; variables . defineVariables ( arguments ) ; Map < DirectInputGroup , List < InputPath > > results = new HashMap < DirectInputGroup , List < InputPath > > ( ) ; for ( StageInput input : inputList ) { String fullBasePath = extractBasePath ( input ) ; String basePath = variables . parse ( repo . getComponentPath ( fullBasePath ) ) ; FilePattern pattern = extractSearchPattern ( context , variables , input ) ; Class < ? > dataClass = extractDataClass ( context , input ) ; Class < ? extends DataFormat < ? > > formatClass = extractFormatClass ( context , input ) ; DirectInputGroup group = new DirectInputGroup ( fullBasePath , dataClass , formatClass ) ; List < InputPath > paths = results . get ( group ) ; if ( paths == null ) { paths = new ArrayList < InputPath > ( ) ; results . put ( group , paths ) ; } paths . add ( new InputPath ( fullBasePath , basePath , pattern ) ) ; } return results ; } private String extractBasePath ( StageInput input ) throws IOException { assert input != null ; return extract ( input , DirectDataSourceConstants . KEY_BASE_PATH ) ; } private FilePattern extractSearchPattern ( JobContext context , VariableTable variables , StageInput input ) throws IOException { assert context != null ; assert input != null ; String value = extract ( input , DirectDataSourceConstants . KEY_RESOURCE_PATH ) ; value = variables . parse ( value ) ; try { FilePattern compiled = FilePattern . compile ( value ) ; if ( compiled . containsVariables ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , value ) ) ; } return compiled ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , extractBasePath ( input ) , value ) , e ) ; } } private Class < ? > extractDataClass ( JobContext context , StageInput input ) throws IOException { assert context != null ; assert input != null ; String value = extract ( input , DirectDataSourceConstants . KEY_DATA_CLASS ) ; try { return Class . forName ( value , false , context . getConfiguration ( ) . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( MessageFormat . format ( "" , extractBasePath ( input ) , value ) , e ) ; } } @ SuppressWarnings ( "" ) private Class < ? extends DataFormat < ? > > extractFormatClass ( JobContext context , StageInput input ) throws IOException { assert context != null ; assert input != null ; String value = extract ( input , DirectDataSourceConstants . KEY_FORMAT_CLASS ) ; try { Class < ? > aClass = Class . forName ( value , false , context . getConfiguration ( ) . getClassLoader ( ) ) ; return ( Class < ? extends DataFormat < ? > > ) aClass . asSubclass ( DataFormat . class ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , extractBasePath ( input ) , value ) , e ) ; } } private String extract ( StageInput input , String key ) throws IOException { String value = input . getAttributes ( ) . get ( key ) ; if ( value == null ) { throw new IOException ( MessageFormat . format ( "" , input . getPathString ( ) , key ) ) ; } return value ; } @ Override public RecordReader < NullWritable , Object > createRecordReader ( InputSplit split , TaskAttemptContext context ) throws IOException , InterruptedException { assert split instanceof BridgeInputSplit ; BridgeInputSplit bridgeInfo = ( BridgeInputSplit ) split ; DataFormat < ? > format = ReflectionUtils . newInstance ( bridgeInfo . group . formatClass , context . getConfiguration ( ) ) ; return createRecordReader ( format , bridgeInfo , context ) ; } private < T > RecordReader < NullWritable , Object > createRecordReader ( DataFormat < T > format , BridgeInputSplit split , TaskAttemptContext context ) throws IOException , InterruptedException { assert format != null ; assert split != null ; assert context != null ; Configuration conf = context . getConfiguration ( ) ; Class < ? extends T > type = split . group . dataType . asSubclass ( format . getSupportedType ( ) ) ; T buffer = ReflectionUtils . newInstance ( type , conf ) ; Counter counter = new Counter ( ) ; ModelInput < T > input = createInput ( context , split . group . containerPath , type , format , counter , split . fragment ) ; return new BridgeRecordReader < T > ( input , buffer , counter , split . fragment . getSize ( ) ) ; } private < T > ModelInput < T > createInput ( TaskAttemptContext context , String containerPath , Class < ? extends T > dataType , DataFormat < T > format , Counter counter , DirectInputFragment fragment ) throws IOException , InterruptedException { assert context != null ; assert containerPath != null ; assert dataType != null ; assert format != null ; assert counter != null ; assert fragment != null ; DirectDataSourceRepository repo = getDataSourceRepository ( context ) ; DirectDataSource ds = repo . getRelatedDataSource ( containerPath ) ; return ds . openInput ( dataType , format , fragment , counter ) ; } private static DirectDataSourceRepository getDataSourceRepository ( JobContext context ) { assert context != null ; return HadoopDataSourceUtil . loadRepository ( context . getConfiguration ( ) ) ; } private static class DirectInputGroup { final String containerPath ; final Class < ? > dataType ; final Class < ? extends DataFormat < ? > > formatClass ; DirectInputGroup ( String containerPath , Class < ? > dataType , Class < ? extends DataFormat < ? > > formatClass ) { assert containerPath != null ; assert dataType != null ; assert formatClass != null ; this . containerPath = containerPath ; this . dataType = dataType ; this . formatClass = formatClass ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + containerPath . hashCode ( ) ; result = prime * result + dataType . hashCode ( ) ; result = prime * result + formatClass . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DirectInputGroup other = ( DirectInputGroup ) obj ; if ( ! containerPath . equals ( other . containerPath ) ) { return false ; } if ( ! dataType . equals ( other . dataType ) ) { return false ; } if ( ! formatClass . equals ( other . formatClass ) ) { return false ; } return true ; } } private static class InputPath { final String originalBasePath ; final String componentPath ; final FilePattern pattern ; InputPath ( String originalBasePath , String componentPath , FilePattern pattern ) { assert originalBasePath != null ; assert componentPath != null ; assert pattern != null ; this . originalBasePath = originalBasePath ; this . componentPath = componentPath ; this . pattern = pattern ; } } public static class BridgeInputSplit extends InputSplit implements Writable , Configurable { volatile Configuration conf ; volatile DirectInputGroup group ; volatile DirectInputFragment fragment ; public BridgeInputSplit ( ) { return ; } BridgeInputSplit ( DirectInputGroup group , DirectInputFragment fragment ) { this . group = group ; this . fragment = fragment ; } @ Override public void setConf ( Configuration conf ) { this . conf = conf ; } @ Override public Configuration getConf ( ) { return conf ; } @ Override public long getLength ( ) throws IOException , InterruptedException { return fragment . getSize ( ) ; } @ Override public String [ ] getLocations ( ) throws IOException , InterruptedException { List < String > locations = fragment . getOwnerNodeNames ( ) ; return locations . toArray ( new String [ locations . size ( ) ] ) ; } @ Override public void write ( DataOutput out ) throws IOException { DirectInputGroup groupCopy = group ; WritableUtils . writeString ( out , groupCopy . containerPath ) ; WritableUtils . writeString ( out , groupCopy . dataType . getName ( ) ) ; WritableUtils . writeString ( out , groupCopy . formatClass . getName ( ) ) ; DirectInputFragment fragmentCopy = fragment ; WritableUtils . writeString ( out , fragmentCopy . getPath ( ) ) ; WritableUtils . writeVLong ( out , fragmentCopy . getOffset ( ) ) ; WritableUtils . writeVLong ( out , fragmentCopy . getSize ( ) ) ; List < String > ownerNodeNames = fragmentCopy . getOwnerNodeNames ( ) ; WritableUtils . writeStringArray ( out , ownerNodeNames . toArray ( new String [ ownerNodeNames . size ( ) ] ) ) ; Map < String , String > attributes = fragmentCopy . getAttributes ( ) ; WritableUtils . writeVInt ( out , attributes . size ( ) ) ; for ( Map . Entry < String , String > entry : attributes . entrySet ( ) ) { WritableUtils . writeString ( out , entry . getKey ( ) ) ; WritableUtils . writeString ( out , entry . getValue ( ) ) ; } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { String containerPath = WritableUtils . readString ( in ) ; String dataTypeName = WritableUtils . readString ( in ) ; String supportTypeName = WritableUtils . readString ( in ) ; String path = WritableUtils . readString ( in ) ; long offset = WritableUtils . readVLong ( in ) ; long length = WritableUtils . readVLong ( in ) ; String [ ] locations = WritableUtils . readStringArray ( in ) ; Map < String , String > attributes ; int attributeCount = WritableUtils . readVInt ( in ) ; if ( attributeCount == ) { attributes = Collections . emptyMap ( ) ; } else { attributes = new HashMap < String , String > ( ) ; for ( int i = ; i < attributeCount ; i ++ ) { String key = WritableUtils . readString ( in ) ; String value = WritableUtils . readString ( in ) ; attributes . put ( key , value ) ; } } this . fragment = new DirectInputFragment ( path , offset , length , Arrays . asList ( locations ) , attributes ) ; try { Class < ? extends DataFormat < ? > > formatClass = ( Class < ? extends DataFormat < ? > > ) conf . getClassByName ( supportTypeName ) . asSubclass ( DataFormat . class ) ; Class < ? > dataType = conf . getClassByName ( dataTypeName ) ; this . group = new DirectInputGroup ( containerPath , dataType , formatClass ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( "" , e ) ; } } } private static final class BridgeRecordReader < T > extends RecordReader < NullWritable , Object > { private static final NullWritable KEY = NullWritable . get ( ) ; private final ModelInput < T > input ; private final T buffer ; private final Counter sizeCounter ; private final double fragmentSize ; private boolean closed = false ; public BridgeRecordReader ( ModelInput < T > input , T buffer , Counter sizeCounter , long fragmentSize ) { assert input != null ; assert buffer != null ; assert sizeCounter != null ; this . sizeCounter = sizeCounter ; this . input = input ; this . buffer = buffer ; if ( fragmentSize < ) { this . fragmentSize = Double . POSITIVE_INFINITY ; } else { this . fragmentSize = fragmentSize ; } } @ Override public void initialize ( InputSplit split , TaskAttemptContext context ) throws IOException , InterruptedException { assert split instanceof BridgeInputSplit ; } @ Override public boolean nextKeyValue ( ) throws IOException , InterruptedException { if ( closed ) { return false ; } boolean exists = input . readTo ( buffer ) ; if ( exists == false ) { return false ; } return exists ; } @ Override public NullWritable getCurrentKey ( ) throws IOException , InterruptedException { return KEY ; } @ Override public Object getCurrentValue ( ) throws IOException , InterruptedException { return buffer ; } @ Override public float getProgress ( ) throws IOException , InterruptedException { if ( closed ) { return ; } float progress = ( float ) ( sizeCounter . get ( ) / fragmentSize ) ; return Math . min ( progress , ) ; } @ Override public void close ( ) throws IOException { if ( closed ) { return ; } closed = true ; input . close ( ) ; } } } package com . asakusafw . runtime . stage . input ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . BitSet ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Random ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . Mapper ; import com . asakusafw . runtime . stage . input . StageInputSplit . Source ; public class DefaultSplitCombiner extends SplitCombiner { static final Log LOG = LogFactory . getLog ( DefaultSplitCombiner . class ) ; static final String KEY_MAX = "" ; static final String KEY_GENERATIONS = "" ; static final String KEY_POPULATIONS = "" ; static final String KEY_MUTATION_RATIO = "" ; static final double DEFAULT_LOCAL_SCORE_FACTOR = ; static final double DEFAULT_GOBAL_SCORE_FACTOR = ; static final int DEFAULT_POPULATIONS = ; static final int DEFAULT_GENERATIONS = ; static final float DEFAULT_MUTATION_RATIO = ; static final int MIN_POPULATIONS = ; static final int MIN_GENERATIONS = ; static final double MIN_MUTATION_RATIO = ; static final double LOCALITY_TOTAL_FACTOR = ; static final double LOCALITY_COMPARISON_FACTOR = ; @ Override protected List < StageInputSplit > combine ( JobContext context , List < StageInputSplit > splits ) throws IOException , InterruptedException { int max = getMaxSplitsPerMapper ( context ) ; int populations = context . getConfiguration ( ) . getInt ( KEY_POPULATIONS , DEFAULT_POPULATIONS ) ; int generations = context . getConfiguration ( ) . getInt ( KEY_GENERATIONS , DEFAULT_GENERATIONS ) ; double mutations = context . getConfiguration ( ) . getFloat ( KEY_MUTATION_RATIO , DEFAULT_MUTATION_RATIO ) ; populations = Math . max ( populations , MIN_POPULATIONS ) ; generations = Math . max ( generations , MIN_GENERATIONS ) ; mutations = Math . max ( mutations , MIN_MUTATION_RATIO ) ; return combine ( max , populations , generations , mutations , splits ) ; } List < StageInputSplit > combine ( int max , int populations , int generations , double mutations , List < StageInputSplit > splits ) throws IOException , InterruptedException { assert splits != null ; Map < Class < ? extends Mapper < ? , ? , ? , ? > > , List < Source > > groups = Util . groupByMapper ( splits ) ; List < StageInputSplit > results = new ArrayList < StageInputSplit > ( ) ; for ( Map . Entry < Class < ? extends Mapper < ? , ? , ? , ? > > , List < Source > > entry : groups . entrySet ( ) ) { Class < ? extends Mapper < ? , ? , ? , ? > > mapper = entry . getKey ( ) ; List < Source > sources = entry . getValue ( ) ; List < StageInputSplit > combined = combineSources ( mapper , sources , max , populations , generations , mutations ) ; results . addAll ( combined ) ; } return results ; } private int getMaxSplitsPerMapper ( JobContext context ) { assert context != null ; int max = context . getConfiguration ( ) . getInt ( KEY_MAX , - ) ; if ( max > ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , KEY_MAX , max ) ) ; } return max ; } return Integer . MAX_VALUE ; } private List < StageInputSplit > combineSources ( Class < ? extends Mapper < ? , ? , ? , ? > > mapper , List < Source > sources , int max , int populations , int generations , double mutations ) throws IOException , InterruptedException { assert sources != null ; assert max > ; if ( sources . size ( ) <= max ) { List < StageInputSplit > results = new ArrayList < StageInputSplit > ( ) ; for ( Source source : sources ) { results . add ( new StageInputSplit ( mapper , Collections . singletonList ( source ) ) ) ; } return results ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , mapper . getName ( ) , sources . size ( ) , max ) ) ; } if ( max == ) { return Collections . singletonList ( new StageInputSplit ( mapper , sources ) ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , mapper . getName ( ) , sources . size ( ) , max ) ) ; LOG . debug ( MessageFormat . format ( "" , max , populations , generations , mutations ) ) ; } Environment env = createEnvironment ( max , populations , generations , mutations , sources ) ; Gene gene = compute ( env ) ; List < StageInputSplit > results = resolve ( env , gene , mapper ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , mapper . getName ( ) , sources . size ( ) , results . size ( ) ) ) ; } return results ; } private List < StageInputSplit > resolve ( Environment env , Gene gene , Class < ? extends Mapper < ? , ? , ? , ? > > mapper ) { List < List < SplitDef > > slots = new ArrayList < List < SplitDef > > ( ) ; for ( int i = , n = env . slots . length ; i < n ; i ++ ) { slots . add ( new ArrayList < SplitDef > ( ) ) ; } int [ ] schema = gene . schema ; for ( int splitId = ; splitId < schema . length ; splitId ++ ) { int slotId = schema [ splitId ] ; slots . get ( slotId ) . add ( env . splits [ splitId ] ) ; } List < StageInputSplit > results = new ArrayList < StageInputSplit > ( ) ; for ( List < SplitDef > splits : slots ) { if ( splits . isEmpty ( ) == false ) { List < Source > sources = new ArrayList < Source > ( ) ; for ( SplitDef split : splits ) { sources . add ( split . origin ) ; } String [ ] locations = computeLocations ( env , splits ) ; results . add ( new StageInputSplit ( mapper , sources , locations ) ) ; } } return results ; } private String [ ] computeLocations ( Environment env , List < SplitDef > splits ) { String [ ] locationNames = env . locations ; LocationAndTime [ ] pairs = new LocationAndTime [ locationNames . length ] ; for ( int i = ; i < pairs . length ; i ++ ) { pairs [ i ] = new LocationAndTime ( i , ) ; } double totalLocalTime = ; for ( SplitDef split : splits ) { BitSet locations = split . locations ; totalLocalTime += split . localTime ; for ( int i = locations . nextSetBit ( ) ; i >= ; i = locations . nextSetBit ( i + ) ) { pairs [ i ] . time += split . localTime ; } } Arrays . sort ( pairs ) ; double first = pairs [ ] . time ; if ( first == ) { return null ; } List < String > locations = new ArrayList < String > ( ) ; locations . add ( locationNames [ pairs [ ] . location ] ) ; for ( int i = ; i < pairs . length ; i ++ ) { double totalScore = pairs [ i ] . time / totalLocalTime ; double comparisonScore = pairs [ i ] . time / first ; if ( totalScore < LOCALITY_TOTAL_FACTOR ) { break ; } if ( comparisonScore < LOCALITY_COMPARISON_FACTOR ) { break ; } locations . add ( locationNames [ pairs [ i ] . location ] ) ; } return locations . toArray ( new String [ locations . size ( ) ] ) ; } private Environment createEnvironment ( int slots , int populations , int generations , double mutations , List < Source > sources ) throws IOException , InterruptedException { assert sources != null ; Map < String , Integer > locationIds = new HashMap < String , Integer > ( ) ; List < SplitDef > results = new ArrayList < SplitDef > ( sources . size ( ) ) ; for ( Source source : sources ) { String [ ] locationArray = source . getSplit ( ) . getLocations ( ) ; long length = source . getSplit ( ) . getLength ( ) ; BitSet locations = new BitSet ( ) ; if ( locationArray != null ) { for ( String location : locationArray ) { Integer id = locationIds . get ( location ) ; if ( id == null ) { id = locationIds . size ( ) ; locationIds . put ( location , id ) ; } locations . set ( id ) ; } } double localScore = length * DEFAULT_LOCAL_SCORE_FACTOR ; double globalScore = length * DEFAULT_GOBAL_SCORE_FACTOR ; results . add ( new SplitDef ( source , locations , localScore , globalScore ) ) ; } if ( locationIds . isEmpty ( ) ) { locationIds . put ( "" , locationIds . size ( ) ) ; } String [ ] locations = new String [ locationIds . size ( ) ] ; for ( Map . Entry < String , Integer > entry : locationIds . entrySet ( ) ) { locations [ entry . getValue ( ) ] = entry . getKey ( ) ; } SplitDef [ ] splitDefs = results . toArray ( new SplitDef [ results . size ( ) ] ) ; SlotDef [ ] slotDefs = resolveSlots ( slots , locations , results ) ; return new Environment ( locations , splitDefs , slotDefs , populations , generations , mutations ) ; } private SlotDef [ ] resolveSlots ( int slots , String [ ] locationNames , List < SplitDef > splits ) { assert locationNames != null ; assert locationNames . length >= ; assert splits != null ; double [ ] locationScores = new double [ locationNames . length ] ; for ( SplitDef split : splits ) { BitSet locations = split . locations ; for ( int i = locations . nextSetBit ( ) ; i >= ; i = locations . nextSetBit ( i + ) ) { locationScores [ i ] += split . localTime ; } } LocationAndTime [ ] pairs = new LocationAndTime [ locationNames . length ] ; for ( int i = ; i < pairs . length ; i ++ ) { LocationAndTime pair = new LocationAndTime ( i , locationScores [ i ] ) ; pairs [ i ] = pair ; } Arrays . sort ( pairs ) ; SlotDef [ ] results = new SlotDef [ slots ] ; for ( int i = ; i < results . length ; i ++ ) { results [ i ] = new SlotDef ( pairs [ i % pairs . length ] . location ) ; } return results ; } private static Gene compute ( Environment env ) { assert env != null ; Gene [ ] current = createGenes ( env ) ; Gene [ ] parent = createGenes ( env ) ; for ( Gene gene : current ) { initializeGene ( env , gene ) ; } int generations = env . generations ; for ( int iteration = ; iteration < generations ; iteration ++ ) { Gene [ ] hold = parent ; parent = current ; current = hold ; populate ( env , parent , current ) ; } return findBest ( current ) ; } private static Gene [ ] createGenes ( Environment env ) { assert env != null ; Gene [ ] genes = new Gene [ env . populations ] ; for ( int geneIndex = ; geneIndex < genes . length ; geneIndex ++ ) { genes [ geneIndex ] = new Gene ( env ) ; } return genes ; } private static void initializeGene ( Environment env , Gene gene ) { assert env != null ; assert gene != null ; Random random = env . random ; int [ ] schema = gene . schema ; for ( int i = ; i < schema . length ; i ++ ) { schema [ i ] = random . nextInt ( env . slots . length ) ; } gene . eval ( ) ; } private static Gene findBest ( Gene [ ] genes ) { Gene best = genes [ ] ; boolean changed = false ; for ( int i = ; i < genes . length ; i ++ ) { if ( genes [ i ] . isBetterThan ( best ) ) { best = genes [ i ] ; changed = true ; } } if ( changed && LOG . isTraceEnabled ( ) ) { LOG . trace ( MessageFormat . format ( "" , best . time ) ) ; } return best ; } private static void populate ( Environment env , Gene [ ] parent , Gene [ ] next ) { assert parent != null ; assert next != null ; assert env != null ; int schemaLength = next [ ] . schema . length ; Gene parentBest = findBest ( parent ) ; Gene nextBest = next [ ] ; System . arraycopy ( parentBest . schema , , nextBest . schema , , schemaLength ) ; nextBest . time = parentBest . time ; Arrays . sort ( parent , Gene . COMPARATOR ) ; Random random = env . random ; for ( int i = ; i < next . length ; i ++ ) { int limit = ( next . length + i + ) / ; assert limit > ; assert limit <= next . length ; int p1 = random . nextInt ( limit ) ; int p2 = env . random . nextInt ( limit ) ; crossOver ( env , parent [ p1 ] , parent [ p2 ] , next [ i ] ) ; } for ( int i = ; i < next . length ; i ++ ) { Gene gene = next [ i ] ; mutate ( env , gene ) ; gene . eval ( ) ; } } private static void crossOver ( Environment env , Gene parent1 , Gene parent2 , Gene child ) { Random random = env . random ; int schemaLength = parent1 . schema . length ; int point = random . nextInt ( schemaLength - ) + ; System . arraycopy ( parent1 . schema , , child . schema , , point ) ; System . arraycopy ( parent2 . schema , point , child . schema , point , schemaLength - point ) ; } private static void mutate ( Environment env , Gene gene ) { Random random = env . random ; int [ ] schema = gene . schema ; double mutations = env . mutations ; for ( int i = ; i < schema . length ; i ++ ) { if ( random . nextDouble ( ) < mutations ) { schema [ i ] = random . nextInt ( env . slots . length ) ; } } } private static final class Environment { final Random random = new Random ( ) ; final String [ ] locations ; final SplitDef [ ] splits ; final SlotDef [ ] slots ; final int populations ; final int generations ; final double mutations ; Environment ( String [ ] locations , SplitDef [ ] splits , SlotDef [ ] slots , int populations , int generations , double mutations ) { assert locations != null ; assert splits != null ; assert slots != null ; this . locations = locations ; this . splits = splits ; this . slots = slots ; this . populations = populations ; this . generations = generations ; this . mutations = mutations ; } } private static final class SlotDef { final int location ; SlotDef ( int location ) { this . location = location ; } } private static final class SplitDef { final Source origin ; final BitSet locations ; final double localTime ; final double globalTime ; SplitDef ( Source origin , BitSet locations , double localScore , double globalScore ) { assert origin != null ; assert locations != null ; this . origin = origin ; this . locations = locations ; this . localTime = localScore ; this . globalTime = globalScore ; } double eval ( SlotDef slot ) { return eval ( slot . location ) ; } double eval ( int location ) { if ( locations . get ( location ) ) { return localTime ; } else { return globalTime ; } } } private static final class LocationAndTime implements Comparable < LocationAndTime > { final int location ; double time ; LocationAndTime ( int location , double score ) { this . location = location ; this . time = score ; } @ Override public int compareTo ( LocationAndTime o ) { double a = time ; double b = o . time ; if ( a < b ) { return + ; } else if ( a > b ) { return - ; } else { return ; } } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + location ; long temp ; temp = Double . doubleToLongBits ( time ) ; result = prime * result + ( int ) ( temp ^ ( temp > > > ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } LocationAndTime other = ( LocationAndTime ) obj ; if ( location != other . location ) { return false ; } if ( Double . doubleToLongBits ( time ) != Double . doubleToLongBits ( other . time ) ) { return false ; } return true ; } } private static final class Gene { static final Comparator < Gene > COMPARATOR = GeneComparator . INSTANCE ; final Environment environment ; final int [ ] schema ; double time ; private final double [ ] slotScoreBuf ; Gene ( Environment env ) { this . environment = env ; this . schema = new int [ env . splits . length ] ; this . slotScoreBuf = new double [ env . slots . length ] ; } public boolean isBetterThan ( Gene other ) { return time < other . time ; } public void eval ( ) { Environment env = this . environment ; double [ ] slotScores = slotScoreBuf ; int [ ] splitSlots = schema ; Arrays . fill ( slotScores , ) ; for ( int splitId = ; splitId < splitSlots . length ; splitId ++ ) { int slotId = splitSlots [ splitId ] ; SplitDef split = env . splits [ splitId ] ; SlotDef slot = env . slots [ slotId ] ; slotScores [ slotId ] += split . eval ( slot ) ; } double max = slotScores [ ] ; for ( int i = ; i < slotScores . length ; i ++ ) { if ( slotScores [ i ] > max ) { max = slotScores [ i ] ; } } this . time = max ; } private enum GeneComparator implements Comparator < Gene > { INSTANCE , ; @ Override public int compare ( Gene o1 , Gene o2 ) { double a = o1 . time ; double b = o2 . time ; if ( a < b ) { return - ; } else if ( a > b ) { return + ; } else { return ; } } } } } package com . asakusafw . runtime . stage . input ; import java . util . List ; import org . apache . hadoop . mapreduce . JobContext ; public final class IdentitySplitCombiner extends SplitCombiner { @ Override protected List < StageInputSplit > combine ( JobContext context , List < StageInputSplit > splits ) { return splits ; } } package com . asakusafw . runtime . stage . input ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . Mapper ; import com . asakusafw . runtime . stage . input . StageInputSplit . Source ; public final class ExtremeSplitCombiner extends SplitCombiner { @ Override protected List < StageInputSplit > combine ( JobContext context , List < StageInputSplit > splits ) { Map < Class < ? extends Mapper < ? , ? , ? , ? > > , List < Source > > groups = Util . groupByMapper ( splits ) ; List < StageInputSplit > results = new ArrayList < StageInputSplit > ( ) ; for ( Map . Entry < Class < ? extends Mapper < ? , ? , ? , ? > > , List < Source > > entry : groups . entrySet ( ) ) { results . add ( new StageInputSplit ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } return results ; } } package com . asakusafw . runtime . stage . input ; import java . io . IOException ; import java . util . Iterator ; import java . util . List ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . InputSplit ; import org . apache . hadoop . mapreduce . RecordReader ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . util . ReflectionUtils ; import com . asakusafw . runtime . stage . input . StageInputSplit . Source ; @ SuppressWarnings ( "" ) public class StageInputRecordReader extends RecordReader { private static final RecordReader < ? , ? > VOID = new RecordReader < Object , Object > ( ) { @ Override public void initialize ( InputSplit split , TaskAttemptContext ctxt ) { return ; } @ Override public boolean nextKeyValue ( ) { return false ; } @ Override public Object getCurrentKey ( ) { throw new IllegalStateException ( ) ; } @ Override public Object getCurrentValue ( ) { throw new IllegalStateException ( ) ; } @ Override public float getProgress ( ) { return ; } @ Override public void close ( ) { return ; } } ; private Iterator < Source > sources ; private TaskAttemptContext context ; private RecordReader < ? , ? > current ; private boolean eof ; private float progressPerSource ; private float baseProgress ; @ Override public void initialize ( InputSplit split , TaskAttemptContext taskContext ) throws IOException , InterruptedException { assert split instanceof StageInputSplit ; List < Source > sourceList = ( ( StageInputSplit ) split ) . getSources ( ) ; this . sources = sourceList . iterator ( ) ; this . context = taskContext ; this . progressPerSource = sourceList . isEmpty ( ) ? : / sourceList . size ( ) ; this . baseProgress = ; prepare ( ) ; } private void prepare ( ) throws IOException , InterruptedException { if ( current != null ) { baseProgress += progressPerSource ; current . close ( ) ; } if ( sources . hasNext ( ) ) { Source next = sources . next ( ) ; InputFormat < ? , ? > format = ReflectionUtils . newInstance ( next . getFormatClass ( ) , context . getConfiguration ( ) ) ; current = format . createRecordReader ( next . getSplit ( ) , context ) ; current . initialize ( next . getSplit ( ) , context ) ; } else { eof = true ; current = VOID ; } } @ Override public boolean nextKeyValue ( ) throws IOException , InterruptedException { while ( eof == false ) { if ( current . nextKeyValue ( ) ) { return true ; } prepare ( ) ; } return false ; } @ Override public Object getCurrentKey ( ) throws IOException , InterruptedException { return current . getCurrentKey ( ) ; } @ Override public Object getCurrentValue ( ) throws IOException , InterruptedException { return current . getCurrentValue ( ) ; } @ Override public float getProgress ( ) throws IOException , InterruptedException { float progress = current . getProgress ( ) ; return baseProgress + progress * progressPerSource ; } @ Override public void close ( ) throws IOException { current . close ( ) ; } } package com . asakusafw . runtime . stage . input ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . mapreduce . Mapper ; import org . apache . hadoop . util . ReflectionUtils ; @ SuppressWarnings ( { "" , "" } ) public class StageInputMapper extends Mapper { private Mapper mapper ; @ Override protected void setup ( Context context ) throws IOException , InterruptedException { assert context . getInputSplit ( ) instanceof StageInputSplit ; StageInputSplit split = ( StageInputSplit ) context . getInputSplit ( ) ; try { this . mapper = ReflectionUtils . newInstance ( split . getMapperClass ( ) , context . getConfiguration ( ) ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , split . getMapperClass ( ) . getName ( ) ) , e ) ; } } @ Override public void run ( Context context ) throws IOException , InterruptedException { setup ( context ) ; mapper . run ( context ) ; cleanup ( context ) ; } @ Override protected void cleanup ( Context context ) throws IOException , InterruptedException { this . mapper = null ; } } package com . asakusafw . runtime . stage . input ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . InputSplit ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . RecordReader ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . lib . input . FileInputFormat ; import org . apache . hadoop . mapreduce . lib . input . SequenceFileInputFormat ; import com . asakusafw . runtime . stage . StageInput ; public final class TemporaryInputFormat < T > extends InputFormat < NullWritable , T > { static final Log LOG = LogFactory . getLog ( TemporaryInputFormat . class ) ; private final FileInputFormat < NullWritable , T > bridge = new SequenceFileInputFormat < NullWritable , T > ( ) ; @ Override public List < InputSplit > getSplits ( JobContext context ) throws IOException , InterruptedException { return bridge . getSplits ( context ) ; } public List < InputSplit > getSplits ( JobContext context , List < StageInput > inputList ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( inputList == null ) { throw new IllegalArgumentException ( "" ) ; } List < Path > paths = new ArrayList < Path > ( ) ; for ( StageInput input : inputList ) { paths . add ( new Path ( input . getPathString ( ) ) ) ; } Job job = new Job ( context . getConfiguration ( ) ) ; setInputPaths ( job , paths ) ; return bridge . getSplits ( job ) ; } public static void setInputPaths ( Job job , List < Path > paths ) throws IOException { if ( job == null ) { throw new IllegalArgumentException ( "" ) ; } if ( paths == null ) { throw new IllegalArgumentException ( "" ) ; } FileInputFormat . setInputPaths ( job , paths . toArray ( new Path [ paths . size ( ) ] ) ) ; } @ Override public RecordReader < NullWritable , T > createRecordReader ( InputSplit split , TaskAttemptContext context ) throws IOException , InterruptedException { return bridge . createRecordReader ( split , context ) ; } } package com . asakusafw . runtime . stage . input ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . WritableUtils ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . InputSplit ; import org . apache . hadoop . mapreduce . Mapper ; import org . apache . hadoop . util . ReflectionUtils ; public class StageInputSplit extends InputSplit implements Writable , Configurable { private Class < ? extends Mapper < ? , ? , ? , ? > > mapperClass ; private List < Source > sources = new ArrayList < Source > ( ) ; private Configuration configuration ; private String [ ] locations ; public StageInputSplit ( ) { return ; } @ Deprecated public StageInputSplit ( InputSplit original , Class < ? extends InputFormat < ? , ? > > formatClass , Class < ? extends Mapper < ? , ? , ? , ? > > mapperClass ) { if ( original == null ) { throw new IllegalArgumentException ( "" ) ; } if ( formatClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( mapperClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . sources = Collections . singletonList ( new Source ( original , formatClass ) ) ; this . mapperClass = mapperClass ; } public StageInputSplit ( Class < ? extends Mapper < ? , ? , ? , ? > > mapperClass , List < Source > sources ) { this ( mapperClass , sources , null ) ; } public StageInputSplit ( Class < ? extends Mapper < ? , ? , ? , ? > > mapperClass , List < Source > sources , String [ ] locations ) { if ( mapperClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sources == null ) { throw new IllegalArgumentException ( "" ) ; } this . mapperClass = mapperClass ; this . sources = sources ; this . locations = locations == null ? null : locations . clone ( ) ; } @ Override public long getLength ( ) throws IOException , InterruptedException { long results = ; for ( Source source : sources ) { results += source . getSplit ( ) . getLength ( ) ; } return results ; } @ Override public String [ ] getLocations ( ) throws IOException , InterruptedException { if ( locations != null ) { return locations . clone ( ) ; } List < String > results = new ArrayList < String > ( ) ; Set < String > saw = new HashSet < String > ( ) ; for ( Source source : sources ) { String [ ] elements = source . getSplit ( ) . getLocations ( ) ; if ( elements != null ) { for ( String element : elements ) { if ( saw . contains ( element ) == false ) { saw . add ( element ) ; results . add ( element ) ; } } } } return results . toArray ( new String [ results . size ( ) ] ) ; } @ Deprecated public InputSplit getOriginal ( ) { if ( sources . size ( ) != ) { throw new UnsupportedOperationException ( ) ; } return sources . get ( ) . getSplit ( ) ; } @ Deprecated public Class < ? extends InputFormat < ? , ? > > getFormatClass ( ) { if ( sources . size ( ) != ) { throw new UnsupportedOperationException ( ) ; } return sources . get ( ) . getFormatClass ( ) ; } public List < Source > getSources ( ) { return sources ; } public Class < ? extends Mapper < ? , ? , ? , ? > > getMapperClass ( ) { return mapperClass ; } @ Override public void write ( DataOutput out ) throws IOException { writeClassByName ( out , mapperClass ) ; WritableUtils . writeVInt ( out , sources . size ( ) ) ; for ( Source source : sources ) { Class < ? extends InputSplit > splitClass = source . getSplit ( ) . getClass ( ) ; writeClassByName ( out , source . getFormatClass ( ) ) ; writeClassByName ( out , splitClass ) ; ( ( Writable ) source . getSplit ( ) ) . write ( out ) ; } if ( locations == null ) { WritableUtils . writeVInt ( out , - ) ; } else { WritableUtils . writeVInt ( out , locations . length ) ; for ( String string : locations ) { WritableUtils . writeString ( out , string ) ; } } } @ SuppressWarnings ( "" ) @ Override public void readFields ( DataInput in ) throws IOException { this . mapperClass = ( Class < ? extends Mapper < ? , ? , ? , ? > > ) readClassByName ( Mapper . class , in ) ; int sourceCount = WritableUtils . readVInt ( in ) ; List < Source > newSources = new ArrayList < Source > ( ) ; for ( int i = ; i < sourceCount ; i ++ ) { Class < ? extends InputFormat < ? , ? > > formatClass = ( Class < ? extends InputFormat < ? , ? > > ) readClassByName ( InputFormat . class , in ) ; Class < ? extends InputSplit > splitClass = readClassByName ( InputSplit . class , in ) ; InputSplit inputSplit = ReflectionUtils . newInstance ( splitClass , getConf ( ) ) ; ( ( Writable ) inputSplit ) . readFields ( in ) ; newSources . add ( new Source ( inputSplit , formatClass ) ) ; } this . sources = newSources ; int locationCount = WritableUtils . readVInt ( in ) ; if ( locationCount < ) { this . locations = null ; } else { String [ ] array = new String [ locationCount ] ; for ( int i = ; i < array . length ; i ++ ) { array [ i ] = WritableUtils . readString ( in ) ; } this . locations = array ; } } private void writeClassByName ( DataOutput out , Class < ? > aClass ) throws IOException { assert out != null ; assert aClass != null ; out . writeUTF ( aClass . getName ( ) ) ; } private < T > Class < ? extends T > readClassByName ( Class < T > baseClass , DataInput in ) throws IOException { assert baseClass != null ; assert in != null ; String className = in . readUTF ( ) ; try { Class < ? > loaded = getConf ( ) . getClassByName ( className ) ; return loaded . asSubclass ( baseClass ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , className ) , e ) ; } } @ Override public void setConf ( Configuration conf ) { this . configuration = conf ; } @ Override public Configuration getConf ( ) { return configuration ; } public static final class Source { private final InputSplit split ; private final Class < ? extends InputFormat < ? , ? > > formatClass ; public Source ( InputSplit split , Class < ? extends InputFormat < ? , ? > > formatClass ) { if ( split == null ) { throw new IllegalArgumentException ( "" ) ; } if ( formatClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . split = split ; this . formatClass = formatClass ; } public InputSplit getSplit ( ) { return split ; } public Class < ? extends InputFormat < ? , ? > > getFormatClass ( ) { return formatClass ; } } } package com . asakusafw . runtime . stage ; public class StageResource { private String location ; private String name ; public StageResource ( String location , String name ) { if ( location == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . location = location ; this . name = name ; } public String getLocation ( ) { return location ; } public String getName ( ) { return name ; } } package com . asakusafw . runtime . stage ; import java . util . Collections ; import java . util . Map ; import java . util . TreeMap ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . Mapper ; public class StageInput { private final String pathString ; private final Class < ? extends InputFormat < ? , ? > > formatClass ; private final Class < ? extends Mapper < ? , ? , ? , ? > > mapperClass ; private final Map < String , String > attributes ; @ SuppressWarnings ( { "" } ) public StageInput ( String pathString , Class < ? extends InputFormat > formatClass , Class < ? extends Mapper > mapperClass ) { this ( pathString , formatClass , mapperClass , Collections . < String , String > emptyMap ( ) ) ; } @ SuppressWarnings ( { "" , "" } ) public StageInput ( String pathString , Class < ? extends InputFormat > formatClass , Class < ? extends Mapper > mapperClass , Map < String , String > attributes ) { if ( pathString == null ) { throw new IllegalArgumentException ( "" ) ; } if ( formatClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( mapperClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } this . pathString = pathString ; this . formatClass = ( Class < ? extends InputFormat < ? , ? > > ) formatClass ; this . mapperClass = ( Class < ? extends Mapper < ? , ? , ? , ? > > ) mapperClass ; this . attributes = Collections . unmodifiableMap ( new TreeMap < String , String > ( attributes ) ) ; } public String getPathString ( ) { return pathString ; } public Class < ? extends InputFormat < ? , ? > > getFormatClass ( ) { return formatClass ; } public Class < ? extends Mapper < ? , ? , ? , ? > > getMapperClass ( ) { return mapperClass ; } public Map < String , String > getAttributes ( ) { return attributes ; } } package com . asakusafw . runtime . stage ; import java . text . MessageFormat ; import com . asakusafw . runtime . util . VariableTable ; public final class StageConstants { public static final String PROP_USER = "" ; public static final String PROP_EXECUTION_ID = "" ; public static final String PROP_BATCH_ID = "" ; public static final String PROP_FLOW_ID = "" ; public static final String PROP_ASAKUSA_BATCH_ARGS = "" ; public static final String VAR_USER = "" ; public static final String VAR_EXECUTION_ID = "" ; public static final String VAR_BATCH_ID = "" ; public static final String VAR_FLOW_ID = "" ; public static final String VAR_DEFINITION_ID = "" ; public static final String VAR_STAGE_ID = "" ; public static final String EXPR_USER = VariableTable . toVariable ( VAR_USER ) ; public static final String EXPR_EXECUTION_ID = VariableTable . toVariable ( VAR_EXECUTION_ID ) ; public static final String EXPR_DEFINITION_ID = VariableTable . toVariable ( VAR_DEFINITION_ID ) ; public static final String EXPR_STAGE_ID = VariableTable . toVariable ( VAR_STAGE_ID ) ; public static String getDefinitionId ( String batchId , String flowId , String stageId ) { if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( stageId == null ) { throw new IllegalArgumentException ( "" ) ; } return MessageFormat . format ( "" , batchId , flowId , stageId ) ; } private StageConstants ( ) { return ; } } package com . asakusafw . runtime . stage ; import static com . asakusafw . runtime . stage . StageConstants . * ; import java . text . MessageFormat ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . util . Tool ; import com . asakusafw . runtime . core . context . RuntimeContext ; public abstract class BaseStageClient extends Configured implements Tool { public static final String METHOD_BATCH_ID = "" ; public static final String METHOD_FLOW_ID = "" ; public static final String METHOD_STAGE_ID = "" ; protected String getUser ( ) { return getMandatoryProperty ( PROP_USER ) ; } protected String getExecutionId ( ) { return getMandatoryProperty ( PROP_EXECUTION_ID ) ; } private String getMandatoryProperty ( String key ) { assert key != null ; String value = getConf ( ) . get ( key ) ; if ( value == null || value . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , key ) ) ; } return value ; } protected abstract String getBatchId ( ) ; protected abstract String getFlowId ( ) ; protected abstract String getStageId ( ) ; protected String getDefinitionId ( ) { String batchId = getBatchId ( ) ; String flowId = getFlowId ( ) ; String stageId = getStageId ( ) ; return StageConstants . getDefinitionId ( batchId , flowId , stageId ) ; } @ Override public final int run ( String [ ] args ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( getConf ( ) . getClassLoader ( ) ) ; return execute ( args ) ; } protected abstract int execute ( String [ ] args ) throws Exception ; } package com . asakusafw . runtime . flow ; import com . asakusafw . runtime . core . Result ; public class VoidResult < T > implements Result < T > { @ Override public void add ( T result ) { return ; } } package com . asakusafw . runtime . flow ; package com . asakusafw . runtime . flow ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . ServiceLoader ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import com . asakusafw . runtime . core . HadoopConfiguration ; import com . asakusafw . runtime . core . ResourceConfiguration ; import com . asakusafw . runtime . core . RuntimeResource ; public class RuntimeResourceManager { static final Log LOG = LogFactory . getLog ( RuntimeResourceManager . class ) ; public static final String CONFIGURATION_FILE_NAME = "" ; public static final String CONFIGURATION_FILE_PATH = "" + CONFIGURATION_FILE_NAME ; private final ResourceConfiguration configuration ; private List < RuntimeResource > resources ; public RuntimeResourceManager ( Configuration configuration ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . configuration = new HadoopConfiguration ( configuration ) ; this . resources = Collections . emptyList ( ) ; } public void setup ( ) throws IOException , InterruptedException { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" ) ; } List < ? extends RuntimeResource > loaded = load ( ) ; this . resources = new ArrayList < RuntimeResource > ( ) ; for ( RuntimeResource resource : loaded ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , resource . getClass ( ) . getName ( ) ) ) ; } resource . setup ( configuration ) ; resources . add ( resource ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , resources . size ( ) ) ) ; } } public void cleanup ( ) throws IOException , InterruptedException { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , resources . size ( ) ) ) ; } try { for ( RuntimeResource resource : resources ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , resource . getClass ( ) . getName ( ) ) ) ; } resource . cleanup ( configuration ) ; } } finally { this . resources = Collections . emptyList ( ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , resources . size ( ) ) ) ; } } protected List < RuntimeResource > load ( ) throws IOException { List < RuntimeResource > results = new ArrayList < RuntimeResource > ( ) ; ClassLoader loader = configuration . getClassLoader ( ) ; try { for ( RuntimeResource resource : ServiceLoader . load ( RuntimeResource . class , loader ) ) { results . add ( resource ) ; } } catch ( RuntimeException e ) { throw new IOException ( MessageFormat . format ( "" , RuntimeResource . class . getName ( ) ) , e ) ; } return results ; } } package com . asakusafw . runtime . flow ; public class BufferException extends RuntimeException { private static final long serialVersionUID = - ; public BufferException ( String message ) { super ( message ) ; } public BufferException ( String message , Throwable cause ) { super ( message , cause ) ; } } package com . asakusafw . runtime . flow . join ; import java . io . IOException ; import java . util . List ; public interface LookUpTable < T > { List < T > get ( LookUpKey key ) throws IOException ; interface Builder < T > { void add ( LookUpKey key , T value ) throws IOException ; LookUpTable < T > build ( ) throws IOException ; } } package com . asakusafw . runtime . flow . join ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; public class VolatileLookUpTable < T > implements LookUpTable < T > { private final Map < LookUpKey , List < T > > entity ; public VolatileLookUpTable ( Map < LookUpKey , List < T > > entity ) { if ( entity == null ) { throw new IllegalArgumentException ( "" ) ; } this . entity = entity ; } @ Override public List < T > get ( LookUpKey key ) { if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } List < T > list = entity . get ( key ) ; if ( list == null ) { return Collections . emptyList ( ) ; } return list ; } public static class Builder < T > implements LookUpTable . Builder < T > { private final Map < LookUpKey , List < T > > entity = new HashMap < LookUpKey , List < T > > ( ) ; @ Override public void add ( LookUpKey key , T value ) throws IOException { if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } List < T > list = entity . get ( key ) ; if ( list == null ) { list = new ArrayList < T > ( ) ; entity . put ( key . copy ( ) , list ) ; } list . add ( value ) ; } @ Override public LookUpTable < T > build ( ) throws IOException { return new VolatileLookUpTable < T > ( entity ) ; } } } package com . asakusafw . runtime . flow . join ; import java . io . IOException ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Writable ; public class LookUpKey { private static final int INITIAL_SIZE = ; private DataOutputBuffer buffer ; public LookUpKey ( ) { this ( INITIAL_SIZE ) ; } public LookUpKey ( int bufferSize ) { this . buffer = new DataOutputBuffer ( bufferSize ) ; } public void reset ( ) throws IOException { buffer . reset ( ) ; } public void add ( Writable writable ) throws IOException { if ( writable == null ) { throw new IllegalArgumentException ( "" ) ; } writable . write ( buffer ) ; } public LookUpKey copy ( ) throws IOException { LookUpKey result = new LookUpKey ( buffer . getLength ( ) ) ; result . buffer . write ( buffer . getData ( ) , , buffer . getLength ( ) ) ; return result ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; byte [ ] b = buffer . getData ( ) ; for ( int i = , n = buffer . getLength ( ) ; i < n ; i ++ ) { result = result * prime + b [ i ] ; } return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } LookUpKey other = ( LookUpKey ) obj ; if ( buffer . getLength ( ) != other . buffer . getLength ( ) ) { return false ; } byte [ ] b1 = buffer . getData ( ) ; byte [ ] b2 = other . buffer . getData ( ) ; for ( int i = , n = buffer . getLength ( ) ; i < n ; i ++ ) { if ( b1 [ i ] != b2 [ i ] ) { return false ; } } return true ; } } package com . asakusafw . runtime . flow . join ; package com . asakusafw . runtime . flow . join ; public class LookUpException extends RuntimeException { private static final long serialVersionUID = ; public LookUpException ( String message , Throwable cause ) { super ( message , cause ) ; } } package com . asakusafw . runtime . flow . join ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . flow . FlowResource ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . stage . resource . StageResourceDriver ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; public abstract class JoinResource < L extends Writable , R > implements FlowResource { static final Log LOG = LogFactory . getLog ( JoinResource . class ) ; private final LookUpKey lookupKeyBuffer = new LookUpKey ( ) ; private LookUpTable < L > table ; @ Override public void setup ( Configuration configuration ) throws IOException , InterruptedException { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , getCacheName ( ) ) ) ; } StageResourceDriver driver = new StageResourceDriver ( configuration ) ; try { List < Path > paths = driver . findCache ( getCacheName ( ) ) ; if ( paths . isEmpty ( ) ) { throw new FileNotFoundException ( MessageFormat . format ( "" , getCacheName ( ) ) ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , getCacheName ( ) , paths ) ) ; } try { table = createTable ( driver , paths ) ; } catch ( IOException e ) { throw new IOException ( MessageFormat . format ( "" , getCacheName ( ) ) , e ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , getCacheName ( ) ) ) ; } } finally { driver . close ( ) ; } } private LookUpTable < L > createTable ( StageResourceDriver driver , List < Path > paths ) throws IOException { assert driver != null ; assert paths != null ; LookUpTable . Builder < L > builder = createLookUpTable ( ) ; L value = createValueObject ( ) ; for ( Path path : paths ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , getCacheName ( ) , path ) ) ; } @ SuppressWarnings ( "" ) ModelInput < L > input = ( ModelInput < L > ) TemporaryStorage . openInput ( driver . getConfiguration ( ) , value . getClass ( ) , path ) ; try { while ( input . readTo ( value ) ) { lookupKeyBuffer . reset ( ) ; LookUpKey k = buildLeftKey ( value , lookupKeyBuffer ) ; builder . add ( k , value ) ; value = createValueObject ( ) ; } } finally { input . close ( ) ; } } return builder . build ( ) ; } @ Override public void cleanup ( Configuration configuration ) throws IOException , InterruptedException { return ; } protected LookUpTable . Builder < L > createLookUpTable ( ) { return new VolatileLookUpTable . Builder < L > ( ) ; } protected abstract String getCacheName ( ) ; protected abstract L createValueObject ( ) ; protected abstract LookUpKey buildLeftKey ( L value , LookUpKey buffer ) throws IOException ; protected abstract LookUpKey buildRightKey ( R value , LookUpKey buffer ) throws IOException ; public List < L > find ( R value ) { try { lookupKeyBuffer . reset ( ) ; LookUpKey k = buildRightKey ( value , lookupKeyBuffer ) ; List < L > found = table . get ( k ) ; return found ; } catch ( IOException e ) { throw new LookUpException ( MessageFormat . format ( "" , value ) , e ) ; } } } package com . asakusafw . runtime . flow ; import org . apache . hadoop . io . Writable ; public abstract class Rendezvous < V extends Writable > { public static final String BEGIN = "" ; public static final String PROCESS = "" ; public static final String END = "" ; public abstract void begin ( ) ; public abstract void process ( V value ) ; public abstract void end ( ) ; } package com . asakusafw . runtime . flow ; import org . apache . hadoop . io . Writable ; public interface SegmentedWritable extends Writable { String ID_GETTER = "" ; int getSegmentId ( ) ; } package com . asakusafw . runtime . flow ; import java . util . AbstractList ; import java . util . RandomAccess ; public class ArrayListBuffer < E > extends AbstractList < E > implements ListBuffer < E > , RandomAccess { private static final int BUFFER_SIZE = ; private Object [ ] buffer ; private int size ; private int cursor ; private int limit ; public ArrayListBuffer ( ) { this ( BUFFER_SIZE ) ; } public ArrayListBuffer ( int bufferSize ) { this . buffer = new Object [ Math . max ( bufferSize , BUFFER_SIZE / ) ] ; this . size = ; this . cursor = - ; this . limit = ; } @ Override public void begin ( ) { size = - ; cursor = ; modCount ++ ; } @ Override public void end ( ) { if ( cursor >= ) { size = cursor ; cursor = - ; modCount ++ ; } } public int getCursorPosition ( ) { return cursor ; } @ Override public boolean isExpandRequired ( ) { return limit <= cursor ; } @ Override public void expand ( E value ) { expandBuffer ( buffer . length << ) ; buffer [ limit ++ ] = value ; } @ Override public E advance ( ) { @ SuppressWarnings ( "" ) E next = ( E ) buffer [ cursor ] ; cursor ++ ; return next ; } @ Override public int size ( ) { return size ; } @ Override @ SuppressWarnings ( "" ) public E get ( int index ) { if ( index >= size ) { throw new IndexOutOfBoundsException ( ) ; } return ( E ) buffer [ index ] ; } @ Override public void shrink ( ) { return ; } private void expandBuffer ( int newLength ) { if ( buffer . length <= limit ) { Object [ ] newBuffer = new Object [ newLength ] ; System . arraycopy ( buffer , , newBuffer , , buffer . length ) ; buffer = newBuffer ; } } } package com . asakusafw . runtime . flow ; import java . io . IOException ; import java . util . Iterator ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . mapreduce . Reducer ; public abstract class SegmentedReducer < KEYIN extends SegmentedWritable , VALUEIN extends SegmentedWritable , KEYOUT extends Writable , VALUEOUT extends Writable > extends Reducer < KEYIN , VALUEIN , KEYOUT , VALUEOUT > { public static final String GET_RENDEZVOUS = "" ; protected abstract Rendezvous < VALUEIN > getRendezvous ( KEYIN key ) ; @ Override protected void reduce ( KEYIN key , Iterable < VALUEIN > values , Context context ) throws IOException , InterruptedException { Iterator < VALUEIN > iter = values . iterator ( ) ; if ( iter . hasNext ( ) == false ) { return ; } Rendezvous < VALUEIN > group = getRendezvous ( key ) ; group . begin ( ) ; while ( iter . hasNext ( ) ) { VALUEIN row = iter . next ( ) ; group . process ( row ) ; } group . end ( ) ; } } package com . asakusafw . runtime . flow ; import java . util . List ; public interface ListBuffer < E > extends List < E > { void begin ( ) ; void end ( ) ; boolean isExpandRequired ( ) ; void expand ( E value ) ; E advance ( ) ; void shrink ( ) ; } package com . asakusafw . runtime . flow ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . Counter ; import org . apache . hadoop . mapreduce . RecordWriter ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import com . asakusafw . runtime . core . Result ; public class ResultOutput < T > implements Result < T > { static final Log LOG = LogFactory . getLog ( ResultOutput . class ) ; private final TaskAttemptContext context ; private final RecordWriter < Object , Object > writer ; private final List < Counter > counters ; private long records ; @ SuppressWarnings ( { "" } ) public ResultOutput ( TaskAttemptContext context , RecordWriter writer ) throws IOException , InterruptedException { this ( context , writer , Collections . < Counter > emptyList ( ) ) ; } @ SuppressWarnings ( { "" , "" } ) public ResultOutput ( TaskAttemptContext context , RecordWriter writer , List < Counter > counters ) throws IOException , InterruptedException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( writer == null ) { throw new IllegalArgumentException ( "" ) ; } if ( counters == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . writer = writer ; this . counters = counters ; } @ Override public void add ( T result ) { try { writer . write ( getKey ( result ) , result ) ; records ++ ; } catch ( Exception e ) { throw new Result . OutputException ( e ) ; } } protected Object getKey ( T result ) { return NullWritable . get ( ) ; } public void close ( ) throws IOException , InterruptedException { for ( Counter counter : counters ) { counter . increment ( records ) ; } writer . close ( context ) ; } } package com . asakusafw . runtime . flow ; import java . io . IOException ; import org . apache . hadoop . conf . Configuration ; public interface FlowResource { void setup ( Configuration configuration ) throws IOException , InterruptedException ; void cleanup ( Configuration configuration ) throws IOException , InterruptedException ; } package com . asakusafw . runtime . flow ; import java . io . IOException ; import java . util . Iterator ; import org . apache . hadoop . mapreduce . Reducer ; public abstract class SegmentedCombiner < KEY extends SegmentedWritable , VALUE extends SegmentedWritable > extends Reducer < KEY , VALUE , KEY , VALUE > { public static final String GET_RENDEZVOUS = "" ; protected abstract Rendezvous < VALUE > getRendezvous ( KEY key ) ; @ Override protected void reduce ( KEY key , Iterable < VALUE > values , Context context ) throws IOException , InterruptedException { Iterator < VALUE > iter = values . iterator ( ) ; if ( iter . hasNext ( ) == false ) { return ; } Rendezvous < VALUE > group = getRendezvous ( key ) ; if ( group == null ) { while ( iter . hasNext ( ) ) { VALUE row = iter . next ( ) ; KEY current = context . getCurrentKey ( ) ; context . write ( current , row ) ; } } else { group . begin ( ) ; while ( iter . hasNext ( ) ) { VALUE row = iter . next ( ) ; group . process ( row ) ; } group . end ( ) ; } } } package com . asakusafw . runtime . flow ; import java . io . File ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . text . MessageFormat ; import java . util . AbstractList ; import java . util . Arrays ; import java . util . RandomAccess ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . io . Writable ; public class FileMapListBuffer < E extends Writable > extends AbstractList < E > implements ListBuffer < E > , RandomAccess { static final Log LOG = LogFactory . getLog ( FileMapListBuffer . class ) ; private static final int DEFAULT_BUFFER_SIZE = ; private static final int MINIMUM_BUFFER_SIZE = ; private final BackingStore backingStore ; private final E [ ] pageBuffer ; private int currentPage ; private int size ; private int cursor ; private int limit ; public FileMapListBuffer ( ) { this ( DEFAULT_BUFFER_SIZE ) ; } @ SuppressWarnings ( "" ) public FileMapListBuffer ( int bufferSize ) { this . backingStore = new BackingStore ( ) ; this . pageBuffer = ( E [ ] ) new Writable [ Math . max ( bufferSize , MINIMUM_BUFFER_SIZE ) ] ; this . size = ; this . cursor = - ; this . limit = ; } @ Override public void begin ( ) { size = - ; cursor = ; currentPage = ; modCount ++ ; } @ Override public void end ( ) { if ( cursor >= ) { size = cursor ; cursor = - ; modCount ++ ; } } @ Override public boolean isExpandRequired ( ) { return limit <= toElementOffsetInPage ( cursor ) ; } @ Override public void expand ( E value ) { pageBuffer [ limit ] = value ; limit ++ ; } @ Override public E advance ( ) { escapePage ( cursor ) ; E next = pageBuffer [ toElementOffsetInPage ( cursor ) ] ; cursor ++ ; return next ; } @ Override public int size ( ) { return size ; } @ Override public E get ( int index ) { if ( index >= size ) { throw new IndexOutOfBoundsException ( ) ; } restorePage ( index ) ; return pageBuffer [ toElementOffsetInPage ( index ) ] ; } private int toElementOffsetInPage ( int index ) { return index % pageBuffer . length ; } private void escapePage ( int index ) { int targetPage = getTargetPage ( index ) ; if ( targetPage != currentPage ) { saveCurrentPage ( ) ; currentPage = targetPage ; } } private void restorePage ( int index ) { int targetPage = getTargetPage ( index ) ; if ( targetPage != currentPage ) { saveCurrentPage ( ) ; try { backingStore . restore ( targetPage , pageBuffer ) ; } catch ( IOException e ) { throw new BufferException ( MessageFormat . format ( "" , index , targetPage , pageBuffer . length ) , e ) ; } currentPage = targetPage ; } } private void saveCurrentPage ( ) throws AssertionError { assert limit == pageBuffer . length : "" ; if ( backingStore . isSaved ( currentPage ) == false ) { try { backingStore . save ( currentPage , pageBuffer ) ; } catch ( IOException e ) { throw new BufferException ( MessageFormat . format ( "" , currentPage , pageBuffer . length ) , e ) ; } } } private int getTargetPage ( int index ) { return index / pageBuffer . length ; } @ Override public void shrink ( ) { try { backingStore . shrink ( ) ; } catch ( IOException e ) { LOG . warn ( "" , e ) ; } } private static class BackingStore { private static final int INITIAL_INDEX_SIZE = ; private static final String PAGE_STORE_PREFIX = "" ; private static final String PAGE_STORE_SUFFIX = "" ; private static final int NOT_SAVED = - ; private File mapFilePath ; private RandomAccessFile mapFile ; private long cursor ; private long [ ] pageIndex ; public BackingStore ( ) { cursor = NOT_SAVED ; pageIndex = new long [ INITIAL_INDEX_SIZE ] ; Arrays . fill ( pageIndex , NOT_SAVED ) ; } public boolean isSaved ( int page ) { if ( page < pageIndex . length ) { return pageIndex [ page ] != NOT_SAVED ; } return false ; } public void save ( int pageNumber , Writable [ ] objects ) throws IOException { prepareMapFile ( objects ) ; prepaerPageIndex ( pageNumber ) ; assert mapFile != null ; assert pageNumber < pageIndex . length ; mapFile . seek ( cursor ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , mapFilePath , pageNumber * objects . length , cursor ) ) ; } for ( Writable writable : objects ) { writable . write ( mapFile ) ; } pageIndex [ pageNumber ] = cursor ; cursor = mapFile . getFilePointer ( ) ; } private void prepareMapFile ( Writable [ ] objects ) throws IOException { if ( cursor == NOT_SAVED ) { assert mapFile == null ; assert mapFilePath == null ; mapFilePath = File . createTempFile ( PAGE_STORE_PREFIX , PAGE_STORE_SUFFIX ) ; LOG . info ( MessageFormat . format ( "" , mapFilePath ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , mapFilePath , objects [ ] ) ) ; } mapFile = new RandomAccessFile ( mapFilePath , "" ) ; cursor = ; } } private void prepaerPageIndex ( int pageNumber ) { if ( pageNumber < pageIndex . length ) { return ; } long [ ] newPageIndex = Arrays . copyOf ( pageIndex , Math . min ( pageIndex . length * , pageNumber + ) ) ; Arrays . fill ( newPageIndex , pageIndex . length , newPageIndex . length , NOT_SAVED ) ; pageIndex = newPageIndex ; } public void restore ( int pageNumber , Writable [ ] objects ) throws IOException { if ( isSaved ( pageNumber ) == false ) { throw new IOException ( MessageFormat . format ( "" , pageNumber ) ) ; } long start = pageIndex [ pageNumber ] ; assert start != NOT_SAVED ; assert mapFile != null ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , mapFilePath , pageNumber * objects . length , start ) ) ; } mapFile . seek ( start ) ; for ( Writable writable : objects ) { writable . readFields ( mapFile ) ; } } public void shrink ( ) throws IOException { if ( cursor != NOT_SAVED ) { assert mapFile != null ; assert mapFilePath != null ; mapFile . close ( ) ; if ( mapFilePath . delete ( ) == false ) { LOG . warn ( MessageFormat . format ( "" , mapFilePath ) ) ; } Arrays . fill ( pageIndex , NOT_SAVED ) ; cursor = NOT_SAVED ; mapFile = null ; mapFilePath = null ; } assert mapFile == null ; assert mapFilePath == null ; } } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class ByteOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { ByteOption option = new ByteOption ( ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void get ( ) { ByteOption option = new ByteOption ( ) ; option . modify ( ( byte ) ) ; assertThat ( option . get ( ) , is ( ( byte ) ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; } @ Test public void or ( ) { ByteOption option = new ByteOption ( ) ; assertThat ( option . or ( ( byte ) ) , is ( ( byte ) ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void orNotNull ( ) { ByteOption option = new ByteOption ( ) ; option . modify ( ( byte ) ) ; assertThat ( option . or ( ( byte ) ) , is ( ( byte ) ) ) ; } @ Test public void copy ( ) { ByteOption option = new ByteOption ( ) ; ByteOption other = new ByteOption ( ) ; other . modify ( ( byte ) ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( ( byte ) ) ) ; option . modify ( ( byte ) ) ; assertThat ( other . get ( ) , is ( ( byte ) ) ) ; } @ Test public void copyNull ( ) { ByteOption option = new ByteOption ( ) ; option . modify ( ( byte ) ) ; ByteOption other = new ByteOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( ( byte ) ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compareTo ( ) { ByteOption a = new ByteOption ( ) ; ByteOption b = new ByteOption ( ) ; ByteOption c = new ByteOption ( ) ; ByteOption d = new ByteOption ( ) ; a . modify ( ( byte ) - ) ; b . modify ( ( byte ) ) ; c . modify ( ( byte ) ) ; d . modify ( ( byte ) - ) ; assertThat ( compare ( a , b ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , greaterThan ( ) ) ; assertThat ( compare ( a , c ) , lessThan ( ) ) ; assertThat ( compare ( b , a ) , greaterThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; } @ Test public void compareNull ( ) { ByteOption a = new ByteOption ( ) ; ByteOption b = new ByteOption ( ) ; ByteOption c = new ByteOption ( ) ; a . modify ( ( byte ) ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void write ( ) { ByteOption option = new ByteOption ( ) ; option . modify ( ( byte ) ) ; ByteOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_max ( ) { ByteOption option = new ByteOption ( ) ; option . modify ( Byte . MAX_VALUE ) ; ByteOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_min ( ) { ByteOption option = new ByteOption ( ) ; option . modify ( Byte . MIN_VALUE ) ; ByteOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeNull ( ) { ByteOption option = new ByteOption ( ) ; ByteOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class BooleanOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { BooleanOption option = new BooleanOption ( ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void get ( ) { BooleanOption option = new BooleanOption ( ) ; option . modify ( false ) ; assertThat ( option . get ( ) , is ( false ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; } @ Test public void or ( ) { BooleanOption option = new BooleanOption ( ) ; assertThat ( option . or ( true ) , is ( true ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void orNotNull ( ) { BooleanOption option = new BooleanOption ( ) ; option . modify ( true ) ; assertThat ( option . or ( false ) , is ( true ) ) ; } @ Test public void copy ( ) { BooleanOption option = new BooleanOption ( ) ; BooleanOption other = new BooleanOption ( ) ; other . modify ( true ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( true ) ) ; option . modify ( false ) ; assertThat ( other . get ( ) , is ( true ) ) ; } @ Test public void copyNull ( ) { BooleanOption option = new BooleanOption ( ) ; option . modify ( true ) ; BooleanOption other = new BooleanOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( true ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compareTo ( ) { BooleanOption a = new BooleanOption ( ) ; BooleanOption b = new BooleanOption ( ) ; BooleanOption c = new BooleanOption ( ) ; a . modify ( false ) ; b . modify ( true ) ; c . modify ( false ) ; assertThat ( compare ( a , b ) , lessThan ( ) ) ; assertThat ( compare ( b , a ) , greaterThan ( ) ) ; assertThat ( compare ( a , c ) , is ( ) ) ; } @ Test public void compareNull ( ) { BooleanOption a = new BooleanOption ( ) ; BooleanOption b = new BooleanOption ( ) ; BooleanOption c = new BooleanOption ( ) ; a . modify ( false ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void writeTrue ( ) { BooleanOption option = new BooleanOption ( ) ; option . modify ( true ) ; BooleanOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeFalse ( ) { BooleanOption option = new BooleanOption ( ) ; option . modify ( true ) ; BooleanOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeNull ( ) { BooleanOption option = new BooleanOption ( ) ; BooleanOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class DoubleOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { DoubleOption option = new DoubleOption ( ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void get ( ) { DoubleOption option = new DoubleOption ( ) ; option . modify ( ) ; assertThat ( option . get ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; } @ Test public void or ( ) { DoubleOption option = new DoubleOption ( ) ; assertThat ( option . or ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void orNotNull ( ) { DoubleOption option = new DoubleOption ( ) ; option . modify ( ) ; assertThat ( option . or ( ) , is ( ) ) ; } @ Test public void copy ( ) { DoubleOption option = new DoubleOption ( ) ; DoubleOption other = new DoubleOption ( ) ; other . modify ( ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( ) ) ; option . modify ( ) ; assertThat ( other . get ( ) , is ( ) ) ; } @ Test public void copyNull ( ) { DoubleOption option = new DoubleOption ( ) ; option . modify ( ) ; DoubleOption other = new DoubleOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compareTo ( ) { DoubleOption a = new DoubleOption ( ) ; DoubleOption b = new DoubleOption ( ) ; DoubleOption c = new DoubleOption ( ) ; DoubleOption d = new DoubleOption ( ) ; DoubleOption e = new DoubleOption ( ) ; a . modify ( - ) ; b . modify ( ) ; c . modify ( ) ; d . modify ( - ) ; e . modify ( - ) ; assertThat ( compare ( a , b ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , greaterThan ( ) ) ; assertThat ( compare ( a , c ) , lessThan ( ) ) ; assertThat ( compare ( b , a ) , greaterThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; assertThat ( compare ( a , e ) , greaterThan ( ) ) ; } @ Test public void compareNull ( ) { DoubleOption a = new DoubleOption ( ) ; DoubleOption b = new DoubleOption ( ) ; DoubleOption c = new DoubleOption ( ) ; a . modify ( Double . NEGATIVE_INFINITY ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void write ( ) { DoubleOption option = new DoubleOption ( ) ; option . modify ( ) ; DoubleOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_max ( ) { DoubleOption option = new DoubleOption ( ) ; option . modify ( Double . POSITIVE_INFINITY ) ; DoubleOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_min ( ) { DoubleOption option = new DoubleOption ( ) ; option . modify ( Double . NEGATIVE_INFINITY ) ; DoubleOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeNull ( ) { DoubleOption option = new DoubleOption ( ) ; DoubleOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInputStream ; import java . io . DataOutputStream ; import java . io . IOException ; import java . lang . reflect . Method ; import org . apache . hadoop . io . Writable ; public class ValueOptionTestRoot { protected < T extends ValueOption < T > > int compare ( T a , T b ) { int object = a . compareTo ( b ) ; Class < ? > klass = a . getClass ( ) ; try { byte [ ] b1 = toBytes ( a ) ; byte [ ] b2 = toBytes ( b ) ; Method method = klass . getMethod ( "" , byte [ ] . class , int . class , int . class , byte [ ] . class , int . class , int . class ) ; int bytes = ( Integer ) method . invoke ( null , b1 , , b1 . length , b2 , , b2 . length ) ; assertThat ( sign ( bytes ) , is ( sign ( object ) ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } return object ; } private int sign ( int value ) { if ( value == ) { return ; } if ( value < ) { return - ; } return + ; } protected < T extends ValueOption < T > > T restore ( T value ) { checkLength ( value ) ; restoreRestorable ( value ) ; return restoreWritable ( value ) ; } private < T extends ValueOption < T > > void restoreRestorable ( T value ) { try { byte [ ] bytes = toBytes ( value ) ; Restorable copy = value . getClass ( ) . newInstance ( ) ; int offset = copy . restore ( bytes , , bytes . length ) ; assertThat ( offset , is ( bytes . length ) ) ; assertThat ( copy , is ( ( Restorable ) value ) ) ; assertThat ( copy . hashCode ( ) , is ( value . hashCode ( ) ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ SuppressWarnings ( "" ) private < T extends Writable > T restoreWritable ( T value ) { try { ByteArrayInputStream read = new ByteArrayInputStream ( toBytes ( value ) ) ; DataInputStream in = new DataInputStream ( read ) ; Writable copy = value . getClass ( ) . newInstance ( ) ; copy . readFields ( in ) ; assertThat ( in . read ( ) , is ( - ) ) ; assertThat ( copy , is ( ( Writable ) value ) ) ; assertThat ( copy . hashCode ( ) , is ( value . hashCode ( ) ) ) ; return ( T ) copy ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private void checkLength ( Writable value ) { Class < ? > klass = value . getClass ( ) ; try { byte [ ] bytes = toBytes ( value ) ; Method method = klass . getMethod ( "" , byte [ ] . class , int . class , int . class ) ; int length = ( Integer ) method . invoke ( null , bytes , , bytes . length ) ; assertThat ( length , is ( bytes . length ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private byte [ ] toBytes ( Writable value ) { try { ByteArrayOutputStream write = new ByteArrayOutputStream ( ) ; DataOutputStream out = new DataOutputStream ( write ) ; value . write ( out ) ; out . close ( ) ; byte [ ] bytes = write . toByteArray ( ) ; return bytes ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . io . Text ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class StringOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { StringOption option = new StringOption ( ) ; assertThat ( "" , option . isNull ( ) , is ( true ) ) ; } @ Test public void text ( ) { StringOption option = new StringOption ( ) ; option . modify ( new Text ( "" ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; assertThat ( option . get ( ) . toString ( ) , is ( "" ) ) ; } @ Test public void textOr ( ) { StringOption option = new StringOption ( ) ; assertThat ( option . or ( new Text ( "" ) ) . toString ( ) , is ( "" ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( new Text ( "" ) ) ; assertThat ( option . or ( new Text ( "" ) ) . toString ( ) , is ( "" ) ) ; } @ Test public void string ( ) { StringOption option = new StringOption ( ) ; option . modify ( "" ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; assertThat ( option . getAsString ( ) , is ( "" ) ) ; } @ Test public void stringOr ( ) { StringOption option = new StringOption ( ) ; assertThat ( option . or ( "" ) , is ( "" ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( "" ) ; assertThat ( option . or ( "" ) , is ( "" ) ) ; } @ Test public void modifyNull ( ) { StringOption option = new StringOption ( ) ; option . modify ( "" ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; option . modify ( ( String ) null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( "" ) ; option . modify ( ( Text ) null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void copy ( ) { StringOption option = new StringOption ( ) ; StringOption other = new StringOption ( ) ; other . modify ( "" ) ; option . copyFrom ( other ) ; assertThat ( option . getAsString ( ) , is ( "" ) ) ; option . modify ( "" ) ; assertThat ( other . getAsString ( ) , is ( "" ) ) ; } @ Test public void copyNull ( ) { StringOption option = new StringOption ( ) ; option . modify ( "" ) ; StringOption other = new StringOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( "" ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void japanese ( ) { StringOption option = new StringOption ( ) ; option . modify ( new Text ( "" ) ) ; assertThat ( option . getAsString ( ) , is ( "" ) ) ; } @ Test public void compare ( ) { StringOption a = new StringOption ( ) ; StringOption b = new StringOption ( ) ; StringOption c = new StringOption ( ) ; StringOption d = new StringOption ( ) ; a . modify ( "" ) ; b . modify ( "" ) ; c . modify ( "" ) ; d . modify ( "" ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , lessThan ( ) ) ; assertThat ( compare ( a , c ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , a ) , is ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; } @ Test public void compareNull ( ) { StringOption a = new StringOption ( ) ; StringOption b = new StringOption ( ) ; StringOption c = new StringOption ( ) ; a . modify ( "" ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void max ( ) { StringOption a = new StringOption ( ) ; StringOption b = new StringOption ( ) ; StringOption c = new StringOption ( ) ; a . modify ( "" ) ; b . modify ( "" ) ; c . modify ( "" ) ; a . max ( b ) ; assertThat ( a . getAsString ( ) , is ( "" ) ) ; assertThat ( b . getAsString ( ) , is ( "" ) ) ; a . max ( c ) ; assertThat ( a . getAsString ( ) , is ( "" ) ) ; assertThat ( b . getAsString ( ) , is ( "" ) ) ; assertThat ( c . getAsString ( ) , is ( "" ) ) ; } @ Test public void min ( ) { StringOption a = new StringOption ( ) ; StringOption b = new StringOption ( ) ; StringOption c = new StringOption ( ) ; a . modify ( "" ) ; b . modify ( "" ) ; c . modify ( "" ) ; a . min ( b ) ; assertThat ( a . getAsString ( ) , is ( "" ) ) ; assertThat ( b . getAsString ( ) , is ( "" ) ) ; a . min ( c ) ; assertThat ( a . getAsString ( ) , is ( "" ) ) ; assertThat ( b . getAsString ( ) , is ( "" ) ) ; assertThat ( c . getAsString ( ) , is ( "" ) ) ; } @ Test public void writable ( ) { StringOption option = new StringOption ( ) ; option . modify ( "" ) ; StringOption restored = restore ( option ) ; assertThat ( option . getAsString ( ) , is ( restored . getAsString ( ) ) ) ; } @ Test public void writable_long ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( char c = ; c < ; c ++ ) { buf . append ( c ) ; } StringOption option = new StringOption ( ) ; option . modify ( buf . toString ( ) ) ; StringOption restored = restore ( option ) ; assertThat ( option . getAsString ( ) , is ( restored . getAsString ( ) ) ) ; } @ Test public void writable_empty ( ) { StringOption option = new StringOption ( ) ; option . modify ( "" ) ; StringOption restored = restore ( option ) ; assertThat ( option . getAsString ( ) , is ( restored . getAsString ( ) ) ) ; } @ Test public void writableOption ( ) { StringOption option = new StringOption ( ) ; StringOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class ShortOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { ShortOption option = new ShortOption ( ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void get ( ) { ShortOption option = new ShortOption ( ) ; option . modify ( ( short ) ) ; assertThat ( option . get ( ) , is ( ( short ) ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; } @ Test public void or ( ) { ShortOption option = new ShortOption ( ) ; assertThat ( option . or ( ( short ) ) , is ( ( short ) ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void orNotNull ( ) { ShortOption option = new ShortOption ( ) ; option . modify ( ( short ) ) ; assertThat ( option . or ( ( short ) ) , is ( ( short ) ) ) ; } @ Test public void copy ( ) { ShortOption option = new ShortOption ( ) ; ShortOption other = new ShortOption ( ) ; other . modify ( ( short ) ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( ( short ) ) ) ; option . modify ( ( short ) ) ; assertThat ( other . get ( ) , is ( ( short ) ) ) ; } @ Test public void copyNull ( ) { ShortOption option = new ShortOption ( ) ; option . modify ( ( short ) ) ; ShortOption other = new ShortOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( ( short ) ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compareTo ( ) { ShortOption a = new ShortOption ( ) ; ShortOption b = new ShortOption ( ) ; ShortOption c = new ShortOption ( ) ; ShortOption d = new ShortOption ( ) ; a . modify ( ( short ) - ) ; b . modify ( ( short ) ) ; c . modify ( ( short ) ) ; d . modify ( ( short ) - ) ; assertThat ( compare ( a , b ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , greaterThan ( ) ) ; assertThat ( compare ( a , c ) , lessThan ( ) ) ; assertThat ( compare ( b , a ) , greaterThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; } @ Test public void compareNull ( ) { ShortOption a = new ShortOption ( ) ; ShortOption b = new ShortOption ( ) ; ShortOption c = new ShortOption ( ) ; a . modify ( ( short ) ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void write ( ) { ShortOption option = new ShortOption ( ) ; option . modify ( ( short ) ) ; ShortOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_max ( ) { ShortOption option = new ShortOption ( ) ; option . modify ( Short . MAX_VALUE ) ; ShortOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_min ( ) { ShortOption option = new ShortOption ( ) ; option . modify ( Short . MIN_VALUE ) ; ShortOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeNull ( ) { ShortOption option = new ShortOption ( ) ; ShortOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Calendar ; import java . util . GregorianCalendar ; import java . util . TimeZone ; import org . junit . Test ; public class DateTest { @ Test public void get1583_1600 ( ) { checkCalendar ( , ) ; } @ Test public void get1601_1700 ( ) { checkCalendar ( , ) ; } @ Test public void get1701_1800 ( ) { checkCalendar ( , ) ; } @ Test public void get1801_1900 ( ) { checkCalendar ( , ) ; } @ Test public void get1901_2000 ( ) { checkCalendar ( , ) ; } @ Test public void get2001_2100 ( ) { checkCalendar ( , ) ; } @ Test public void get2101_2200 ( ) { checkCalendar ( , ) ; } @ Test public void get2201_2300 ( ) { checkCalendar ( , ) ; } @ Test public void get2301_2400 ( ) { checkCalendar ( , ) ; } @ Test public void get2401_2500 ( ) { checkCalendar ( , ) ; } @ Test public void parse ( ) { Date date = Date . valueOf ( "" , Date . Format . SIMPLE ) ; assertThat ( date . getYear ( ) , is ( ) ) ; assertThat ( date . getMonth ( ) , is ( ) ) ; assertThat ( date . getDay ( ) , is ( ) ) ; } @ Test public void parse_zero ( ) { Date date = Date . valueOf ( "" , Date . Format . SIMPLE ) ; assertThat ( date . getYear ( ) , is ( ) ) ; assertThat ( date . getMonth ( ) , is ( ) ) ; assertThat ( date . getDay ( ) , is ( ) ) ; } @ Test public void parse_big ( ) { Date date = Date . valueOf ( "" , Date . Format . SIMPLE ) ; assertThat ( date . getYear ( ) , is ( ) ) ; assertThat ( date . getMonth ( ) , is ( ) ) ; assertThat ( date . getDay ( ) , is ( ) ) ; } @ Test public void parse_option ( ) { StringOption option = new StringOption ( "" ) ; Date date = Date . valueOf ( option , Date . Format . SIMPLE ) ; assertThat ( date . getYear ( ) , is ( ) ) ; assertThat ( date . getMonth ( ) , is ( ) ) ; assertThat ( date . getDay ( ) , is ( ) ) ; } @ Test public void parse_null ( ) { StringOption option = new StringOption ( null ) ; Date date = Date . valueOf ( option , Date . Format . SIMPLE ) ; assertThat ( date , is ( nullValue ( ) ) ) ; } void checkCalendar ( int start , int end ) { GregorianCalendar calendar = new GregorianCalendar ( TimeZone . getTimeZone ( "" ) ) ; calendar . clear ( ) ; calendar . set ( Calendar . YEAR , start ) ; calendar . set ( Calendar . MONTH , Calendar . JANUARY ) ; calendar . set ( Calendar . DATE , ) ; Date date = new Date ( ) ; date . setElapsedDays ( DateUtil . getDayFromDate ( start , , ) ) ; while ( calendar . get ( Calendar . YEAR ) <= end ) { String calString = calendar . toString ( ) ; assertThat ( "" + calString , date . getYear ( ) , is ( calendar . get ( Calendar . YEAR ) ) ) ; assertThat ( "" + calString , date . getMonth ( ) , is ( calendar . get ( Calendar . MONTH ) + ) ) ; assertThat ( "" + calString , date . getDay ( ) , is ( calendar . get ( Calendar . DATE ) ) ) ; calendar . add ( Calendar . DATE , ) ; date . setElapsedDays ( date . getElapsedDays ( ) + ) ; } } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class FloatOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { FloatOption option = new FloatOption ( ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void get ( ) { FloatOption option = new FloatOption ( ) ; option . modify ( ) ; assertThat ( option . get ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; } @ Test public void or ( ) { FloatOption option = new FloatOption ( ) ; assertThat ( option . or ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void orNotNull ( ) { FloatOption option = new FloatOption ( ) ; option . modify ( ) ; assertThat ( option . or ( ) , is ( ) ) ; } @ Test public void copy ( ) { FloatOption option = new FloatOption ( ) ; FloatOption other = new FloatOption ( ) ; other . modify ( ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( ) ) ; option . modify ( ) ; assertThat ( other . get ( ) , is ( ) ) ; } @ Test public void copyNull ( ) { FloatOption option = new FloatOption ( ) ; option . modify ( ) ; FloatOption other = new FloatOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compareTo ( ) { FloatOption a = new FloatOption ( ) ; FloatOption b = new FloatOption ( ) ; FloatOption c = new FloatOption ( ) ; FloatOption d = new FloatOption ( ) ; FloatOption e = new FloatOption ( ) ; a . modify ( - ) ; b . modify ( ) ; c . modify ( ) ; d . modify ( - ) ; e . modify ( - ) ; assertThat ( compare ( a , b ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , greaterThan ( ) ) ; assertThat ( compare ( a , c ) , lessThan ( ) ) ; assertThat ( compare ( b , a ) , greaterThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; assertThat ( compare ( d , e ) , greaterThan ( ) ) ; } @ Test public void compareNull ( ) { FloatOption a = new FloatOption ( ) ; FloatOption b = new FloatOption ( ) ; FloatOption c = new FloatOption ( ) ; a . modify ( Float . NEGATIVE_INFINITY ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void write ( ) { FloatOption option = new FloatOption ( ) ; option . modify ( ) ; FloatOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_max ( ) { FloatOption option = new FloatOption ( ) ; option . modify ( Float . POSITIVE_INFINITY ) ; FloatOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_0 ( ) { FloatOption option = new FloatOption ( ) ; option . modify ( ) ; FloatOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeNull ( ) { FloatOption option = new FloatOption ( ) ; FloatOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class DateTimeOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { DateTimeOption option = new DateTimeOption ( ) ; assertThat ( "" , option . isNull ( ) , is ( true ) ) ; } @ Test public void setLong ( ) { DateTimeOption option = new DateTimeOption ( ) ; option . modify ( ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; assertThat ( option . get ( ) , is ( time ( ) ) ) ; } @ Test public void intOr ( ) { DateTimeOption option = new DateTimeOption ( ) ; assertThat ( option . or ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( ) ; assertThat ( option . or ( ) , is ( ) ) ; } @ Test public void string ( ) { DateTimeOption option = new DateTimeOption ( ) ; option . modify ( time ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; assertThat ( option . get ( ) , is ( time ( ) ) ) ; } @ Test public void stringOr ( ) { DateTimeOption option = new DateTimeOption ( ) ; assertThat ( option . or ( time ( ) ) , is ( time ( ) ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( time ( ) ) ; assertThat ( option . or ( time ( ) ) , is ( time ( ) ) ) ; } @ Test public void modifyNull ( ) { DateTimeOption option = new DateTimeOption ( ) ; option . modify ( time ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; option . modify ( ( DateTime ) null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void copy ( ) { DateTimeOption option = new DateTimeOption ( ) ; DateTimeOption other = new DateTimeOption ( ) ; other . modify ( time ( ) ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( time ( ) ) ) ; option . modify ( time ( ) ) ; assertThat ( other . get ( ) , is ( time ( ) ) ) ; } @ Test public void copyNull ( ) { DateTimeOption option = new DateTimeOption ( ) ; option . modify ( time ( ) ) ; DateTimeOption other = new DateTimeOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( time ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compare ( ) { DateTimeOption a = new DateTimeOption ( ) ; DateTimeOption b = new DateTimeOption ( ) ; DateTimeOption c = new DateTimeOption ( ) ; DateTimeOption d = new DateTimeOption ( ) ; a . modify ( time ( ) ) ; b . modify ( time ( ) ) ; c . modify ( time ( ) ) ; d . modify ( time ( ) ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , lessThan ( ) ) ; assertThat ( compare ( a , c ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , a ) , is ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; } @ Test public void compareNull ( ) { DateTimeOption a = new DateTimeOption ( ) ; DateTimeOption b = new DateTimeOption ( ) ; DateTimeOption c = new DateTimeOption ( ) ; a . modify ( time ( ) ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void max ( ) { DateTimeOption a = new DateTimeOption ( ) ; DateTimeOption b = new DateTimeOption ( ) ; DateTimeOption c = new DateTimeOption ( ) ; a . modify ( time ( ) ) ; b . modify ( time ( ) ) ; c . modify ( time ( ) ) ; a . max ( b ) ; assertThat ( a . get ( ) , is ( time ( ) ) ) ; assertThat ( b . get ( ) , is ( time ( ) ) ) ; a . max ( c ) ; assertThat ( a . get ( ) , is ( time ( ) ) ) ; assertThat ( b . get ( ) , is ( time ( ) ) ) ; assertThat ( c . get ( ) , is ( time ( ) ) ) ; } @ Test public void min ( ) { DateTimeOption a = new DateTimeOption ( ) ; DateTimeOption b = new DateTimeOption ( ) ; DateTimeOption c = new DateTimeOption ( ) ; a . modify ( time ( ) ) ; b . modify ( time ( ) ) ; c . modify ( time ( ) ) ; a . min ( b ) ; assertThat ( a . get ( ) , is ( time ( ) ) ) ; assertThat ( b . get ( ) , is ( time ( ) ) ) ; a . min ( c ) ; assertThat ( a . get ( ) , is ( time ( ) ) ) ; assertThat ( b . get ( ) , is ( time ( ) ) ) ; assertThat ( c . get ( ) , is ( time ( ) ) ) ; } @ Test public void writable ( ) { DateTimeOption option = new DateTimeOption ( ) ; option . modify ( time ( ) ) ; DateTimeOption restored = restore ( option ) ; assertThat ( option . get ( ) , is ( restored . get ( ) ) ) ; } @ Test public void writable_max ( ) { DateTimeOption option = new DateTimeOption ( ) ; option . modify ( time ( Long . MAX_VALUE ) ) ; DateTimeOption restored = restore ( option ) ; assertThat ( option . get ( ) , is ( restored . get ( ) ) ) ; } @ Test public void writable_0 ( ) { DateTimeOption option = new DateTimeOption ( ) ; option . modify ( time ( ) ) ; DateTimeOption restored = restore ( option ) ; assertThat ( option . get ( ) , is ( restored . get ( ) ) ) ; } @ Test public void writableOption ( ) { DateTimeOption option = new DateTimeOption ( ) ; DateTimeOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } private DateTime time ( long elapsed ) { DateTime date = new DateTime ( ) ; date . setElapsedSeconds ( elapsed ) ; return date ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Calendar ; import java . util . GregorianCalendar ; import java . util . TimeZone ; import org . junit . Test ; public class DateTimeTest { @ Test public void get1583_1600 ( ) { checkCalendar ( , ) ; } @ Test public void get1601_1700 ( ) { checkCalendar ( , ) ; } @ Test public void get1701_1800 ( ) { checkCalendar ( , ) ; } @ Test public void get1801_1900 ( ) { checkCalendar ( , ) ; } @ Test public void get1901_2000 ( ) { checkCalendar ( , ) ; } @ Test public void get2001_2100 ( ) { checkCalendar ( , ) ; } @ Test public void get2101_2200 ( ) { checkCalendar ( , ) ; } @ Test public void get2201_2300 ( ) { checkCalendar ( , ) ; } @ Test public void get2301_2400 ( ) { checkCalendar ( , ) ; } @ Test public void get2401_2500 ( ) { checkCalendar ( , ) ; } @ Test public void parse ( ) { DateTime time = DateTime . valueOf ( "" , DateTime . Format . SIMPLE ) ; assertThat ( time . getYear ( ) , is ( ) ) ; assertThat ( time . getMonth ( ) , is ( ) ) ; assertThat ( time . getDay ( ) , is ( ) ) ; assertThat ( time . getHour ( ) , is ( ) ) ; assertThat ( time . getMinute ( ) , is ( ) ) ; assertThat ( time . getSecond ( ) , is ( ) ) ; } @ Test public void parse_zero ( ) { DateTime time = DateTime . valueOf ( "" , DateTime . Format . SIMPLE ) ; assertThat ( time . getYear ( ) , is ( ) ) ; assertThat ( time . getMonth ( ) , is ( ) ) ; assertThat ( time . getDay ( ) , is ( ) ) ; assertThat ( time . getHour ( ) , is ( ) ) ; assertThat ( time . getMinute ( ) , is ( ) ) ; assertThat ( time . getSecond ( ) , is ( ) ) ; } @ Test public void parse_big ( ) { DateTime time = DateTime . valueOf ( "" , DateTime . Format . SIMPLE ) ; assertThat ( time . getYear ( ) , is ( ) ) ; assertThat ( time . getMonth ( ) , is ( ) ) ; assertThat ( time . getDay ( ) , is ( ) ) ; assertThat ( time . getHour ( ) , is ( ) ) ; assertThat ( time . getMinute ( ) , is ( ) ) ; assertThat ( time . getSecond ( ) , is ( ) ) ; } @ Test public void parse_option ( ) { StringOption option = new StringOption ( "" ) ; DateTime time = DateTime . valueOf ( option , DateTime . Format . SIMPLE ) ; assertThat ( time . getYear ( ) , is ( ) ) ; assertThat ( time . getMonth ( ) , is ( ) ) ; assertThat ( time . getDay ( ) , is ( ) ) ; assertThat ( time . getHour ( ) , is ( ) ) ; assertThat ( time . getMinute ( ) , is ( ) ) ; assertThat ( time . getSecond ( ) , is ( ) ) ; } @ Test public void parse_null ( ) { StringOption option = new StringOption ( null ) ; DateTime time = DateTime . valueOf ( option , DateTime . Format . SIMPLE ) ; assertThat ( time , is ( nullValue ( ) ) ) ; } void checkCalendar ( int start , int end ) { GregorianCalendar calendar = new GregorianCalendar ( TimeZone . getTimeZone ( "" ) ) ; calendar . clear ( ) ; calendar . set ( Calendar . YEAR , start ) ; calendar . set ( Calendar . MONTH , Calendar . JANUARY ) ; calendar . set ( Calendar . DATE , ) ; DateTime time = new DateTime ( ) ; time . setElapsedSeconds ( ( long ) DateUtil . getDayFromDate ( start , , ) * ) ; while ( calendar . get ( Calendar . YEAR ) <= end ) { String calString = calendar . toString ( ) ; assertThat ( "" + calString , time . getYear ( ) , is ( calendar . get ( Calendar . YEAR ) ) ) ; assertThat ( "" + calString , time . getMonth ( ) , is ( calendar . get ( Calendar . MONTH ) + ) ) ; assertThat ( "" + calString , time . getDay ( ) , is ( calendar . get ( Calendar . DATE ) ) ) ; assertThat ( "" + calString , time . getHour ( ) , is ( calendar . get ( Calendar . HOUR_OF_DAY ) ) ) ; assertThat ( "" + calString , time . getMinute ( ) , is ( calendar . get ( Calendar . MINUTE ) ) ) ; assertThat ( "" + calString , time . getSecond ( ) , is ( calendar . get ( Calendar . SECOND ) ) ) ; calendar . add ( Calendar . SECOND , ) ; time . setElapsedSeconds ( time . getElapsedSeconds ( ) + ) ; } } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . math . BigDecimal ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class DecimalOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { DecimalOption option = new DecimalOption ( ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void get ( ) { DecimalOption option = new DecimalOption ( ) ; option . modify ( decimal ( ) ) ; assertThat ( option . get ( ) , is ( decimal ( ) ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; } @ Test public void or ( ) { DecimalOption option = new DecimalOption ( ) ; assertThat ( option . or ( decimal ( ) ) , is ( decimal ( ) ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void orNotNull ( ) { DecimalOption option = new DecimalOption ( ) ; option . modify ( decimal ( ) ) ; assertThat ( option . or ( decimal ( ) ) , is ( decimal ( ) ) ) ; } @ Test public void copy ( ) { DecimalOption option = new DecimalOption ( ) ; DecimalOption other = new DecimalOption ( ) ; other . modify ( decimal ( ) ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( decimal ( ) ) ) ; option . modify ( decimal ( ) ) ; assertThat ( other . get ( ) , is ( decimal ( ) ) ) ; } @ Test public void copyNull ( ) { DecimalOption option = new DecimalOption ( ) ; option . modify ( decimal ( ) ) ; DecimalOption other = new DecimalOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( decimal ( ) ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compareTo ( ) { DecimalOption a = new DecimalOption ( ) ; DecimalOption b = new DecimalOption ( ) ; DecimalOption c = new DecimalOption ( ) ; DecimalOption d = new DecimalOption ( ) ; DecimalOption e = new DecimalOption ( ) ; a . modify ( decimal ( - ) ) ; b . modify ( decimal ( ) ) ; c . modify ( decimal ( ) ) ; d . modify ( decimal ( - ) ) ; e . modify ( decimal ( - ) ) ; assertThat ( compare ( a , b ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , greaterThan ( ) ) ; assertThat ( compare ( a , c ) , lessThan ( ) ) ; assertThat ( compare ( b , a ) , greaterThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; assertThat ( compare ( a , e ) , greaterThan ( ) ) ; } @ Test public void compareTo_scale ( ) { DecimalOption a1 = new DecimalOption ( ) ; DecimalOption a2 = new DecimalOption ( ) ; DecimalOption b1 = new DecimalOption ( ) ; DecimalOption b2 = new DecimalOption ( ) ; DecimalOption c1 = new DecimalOption ( ) ; DecimalOption c2 = new DecimalOption ( ) ; DecimalOption d1 = new DecimalOption ( ) ; DecimalOption d2 = new DecimalOption ( ) ; a1 . modify ( decimal ( "" ) ) ; a2 . modify ( decimal ( "" ) ) ; b1 . modify ( decimal ( "" ) ) ; b2 . modify ( decimal ( "" ) ) ; c1 . modify ( decimal ( "" ) ) ; c2 . modify ( decimal ( "" ) ) ; d1 . modify ( decimal ( "" ) ) ; d2 . modify ( decimal ( "" ) ) ; assertThat ( compare ( a1 , a2 ) , equalTo ( ) ) ; assertThat ( compare ( b1 , b2 ) , equalTo ( ) ) ; assertThat ( compare ( c1 , c2 ) , equalTo ( ) ) ; assertThat ( compare ( d1 , d2 ) , equalTo ( ) ) ; assertThat ( compare ( a1 , b1 ) , greaterThan ( ) ) ; assertThat ( compare ( a1 , b2 ) , greaterThan ( ) ) ; assertThat ( compare ( a1 , c1 ) , greaterThan ( ) ) ; assertThat ( compare ( a1 , c2 ) , greaterThan ( ) ) ; assertThat ( compare ( b1 , c1 ) , greaterThan ( ) ) ; assertThat ( compare ( b1 , c2 ) , greaterThan ( ) ) ; assertThat ( compare ( b1 , a1 ) , lessThan ( ) ) ; assertThat ( compare ( b1 , a2 ) , lessThan ( ) ) ; assertThat ( compare ( c1 , a1 ) , lessThan ( ) ) ; assertThat ( compare ( c1 , a2 ) , lessThan ( ) ) ; assertThat ( compare ( c1 , b1 ) , lessThan ( ) ) ; assertThat ( compare ( c1 , b2 ) , lessThan ( ) ) ; } @ Test public void compareNull ( ) { DecimalOption a = new DecimalOption ( ) ; DecimalOption b = new DecimalOption ( ) ; DecimalOption c = new DecimalOption ( ) ; a . modify ( decimal ( Long . MIN_VALUE ) ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void write ( ) { DecimalOption option = new DecimalOption ( ) ; option . modify ( decimal ( "" ) ) ; DecimalOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_max ( ) { DecimalOption option = new DecimalOption ( ) ; option . modify ( decimal ( Long . MAX_VALUE ) . add ( decimal ( Long . MAX_VALUE ) ) ) ; DecimalOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_min ( ) { DecimalOption option = new DecimalOption ( ) ; option . modify ( decimal ( Long . MIN_VALUE ) . add ( decimal ( Long . MAX_VALUE ) ) ) ; DecimalOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeNull ( ) { DecimalOption option = new DecimalOption ( ) ; DecimalOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } private BigDecimal decimal ( long value ) { return new BigDecimal ( value ) ; } private BigDecimal decimal ( String value ) { return new BigDecimal ( value ) ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class LongOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { LongOption option = new LongOption ( ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void get ( ) { LongOption option = new LongOption ( ) ; option . modify ( ) ; assertThat ( option . get ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; } @ Test public void or ( ) { LongOption option = new LongOption ( ) ; assertThat ( option . or ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void orNotNull ( ) { LongOption option = new LongOption ( ) ; option . modify ( ) ; assertThat ( option . or ( ) , is ( ) ) ; } @ Test public void copy ( ) { LongOption option = new LongOption ( ) ; LongOption other = new LongOption ( ) ; other . modify ( ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( ) ) ; option . modify ( ) ; assertThat ( other . get ( ) , is ( ) ) ; } @ Test public void copyNull ( ) { LongOption option = new LongOption ( ) ; option . modify ( ) ; LongOption other = new LongOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compareTo ( ) { LongOption a = new LongOption ( ) ; LongOption b = new LongOption ( ) ; LongOption c = new LongOption ( ) ; LongOption d = new LongOption ( ) ; a . modify ( Long . MIN_VALUE ) ; b . modify ( ) ; c . modify ( ) ; d . modify ( Long . MIN_VALUE ) ; assertThat ( compare ( a , b ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , greaterThan ( ) ) ; assertThat ( compare ( a , c ) , lessThan ( ) ) ; assertThat ( compare ( b , a ) , greaterThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; } @ Test public void compareNull ( ) { LongOption a = new LongOption ( ) ; LongOption b = new LongOption ( ) ; LongOption c = new LongOption ( ) ; a . modify ( Long . MIN_VALUE ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void write ( ) { LongOption option = new LongOption ( ) ; option . modify ( ) ; LongOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_max ( ) { LongOption option = new LongOption ( ) ; option . modify ( Long . MAX_VALUE ) ; LongOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_min ( ) { LongOption option = new LongOption ( ) ; option . modify ( Long . MIN_VALUE ) ; LongOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeNull ( ) { LongOption option = new LongOption ( ) ; LongOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class DateOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { DateOption option = new DateOption ( ) ; assertThat ( "" , option . isNull ( ) , is ( true ) ) ; } @ Test public void setInt ( ) { DateOption option = new DateOption ( ) ; option . modify ( ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; assertThat ( option . get ( ) . getElapsedDays ( ) , is ( ) ) ; } @ Test public void intOr ( ) { DateOption option = new DateOption ( ) ; assertThat ( option . or ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( ) ; assertThat ( option . or ( ) , is ( ) ) ; } @ Test public void string ( ) { DateOption option = new DateOption ( ) ; option . modify ( date ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; assertThat ( option . get ( ) , is ( date ( ) ) ) ; } @ Test public void stringOr ( ) { DateOption option = new DateOption ( ) ; assertThat ( option . or ( date ( ) ) , is ( date ( ) ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( date ( ) ) ; assertThat ( option . or ( date ( ) ) , is ( date ( ) ) ) ; } @ Test public void modifyNull ( ) { DateOption option = new DateOption ( ) ; option . modify ( date ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; option . modify ( ( Date ) null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void copy ( ) { DateOption option = new DateOption ( ) ; DateOption other = new DateOption ( ) ; other . modify ( date ( ) ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( date ( ) ) ) ; option . modify ( date ( ) ) ; assertThat ( other . get ( ) , is ( date ( ) ) ) ; } @ Test public void copyNull ( ) { DateOption option = new DateOption ( ) ; option . modify ( date ( ) ) ; DateOption other = new DateOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( date ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compare ( ) { DateOption a = new DateOption ( ) ; DateOption b = new DateOption ( ) ; DateOption c = new DateOption ( ) ; DateOption d = new DateOption ( ) ; a . modify ( date ( ) ) ; b . modify ( date ( ) ) ; c . modify ( date ( ) ) ; d . modify ( date ( ) ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , lessThan ( ) ) ; assertThat ( compare ( a , c ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , a ) , is ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; } @ Test public void compareNull ( ) { DateOption a = new DateOption ( ) ; DateOption b = new DateOption ( ) ; DateOption c = new DateOption ( ) ; a . modify ( date ( ) ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void max ( ) { DateOption a = new DateOption ( ) ; DateOption b = new DateOption ( ) ; DateOption c = new DateOption ( ) ; a . modify ( date ( ) ) ; b . modify ( date ( ) ) ; c . modify ( date ( ) ) ; a . max ( b ) ; assertThat ( a . get ( ) , is ( date ( ) ) ) ; assertThat ( b . get ( ) , is ( date ( ) ) ) ; a . max ( c ) ; assertThat ( a . get ( ) , is ( date ( ) ) ) ; assertThat ( b . get ( ) , is ( date ( ) ) ) ; assertThat ( c . get ( ) , is ( date ( ) ) ) ; } @ Test public void min ( ) { DateOption a = new DateOption ( ) ; DateOption b = new DateOption ( ) ; DateOption c = new DateOption ( ) ; a . modify ( date ( ) ) ; b . modify ( date ( ) ) ; c . modify ( date ( ) ) ; a . min ( b ) ; assertThat ( a . get ( ) , is ( date ( ) ) ) ; assertThat ( b . get ( ) , is ( date ( ) ) ) ; a . min ( c ) ; assertThat ( a . get ( ) , is ( date ( ) ) ) ; assertThat ( b . get ( ) , is ( date ( ) ) ) ; assertThat ( c . get ( ) , is ( date ( ) ) ) ; } @ Test public void writable ( ) { DateOption option = new DateOption ( ) ; option . modify ( date ( ) ) ; DateOption restored = restore ( option ) ; assertThat ( option . get ( ) , is ( restored . get ( ) ) ) ; } @ Test public void writable_max ( ) { DateOption option = new DateOption ( ) ; option . modify ( date ( Integer . MAX_VALUE ) ) ; DateOption restored = restore ( option ) ; assertThat ( option . get ( ) , is ( restored . get ( ) ) ) ; } @ Test public void writable_zero ( ) { DateOption option = new DateOption ( ) ; option . modify ( date ( ) ) ; DateOption restored = restore ( option ) ; assertThat ( option . get ( ) , is ( restored . get ( ) ) ) ; } @ Test public void writableOption ( ) { DateOption option = new DateOption ( ) ; DateOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } private Date date ( int elapsed ) { Date date = new Date ( ) ; date . setElapsedDays ( elapsed ) ; return date ; } } package com . asakusafw . runtime . value ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; @ SuppressWarnings ( "" ) public class IntOptionTest extends ValueOptionTestRoot { @ Test public void init ( ) { IntOption option = new IntOption ( ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void get ( ) { IntOption option = new IntOption ( ) ; option . modify ( ) ; assertThat ( option . get ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( false ) ) ; } @ Test public void or ( ) { IntOption option = new IntOption ( ) ; assertThat ( option . or ( ) , is ( ) ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void orNotNull ( ) { IntOption option = new IntOption ( ) ; option . modify ( ) ; assertThat ( option . or ( ) , is ( ) ) ; } @ Test public void copy ( ) { IntOption option = new IntOption ( ) ; IntOption other = new IntOption ( ) ; other . modify ( ) ; option . copyFrom ( other ) ; assertThat ( option . get ( ) , is ( ) ) ; option . modify ( ) ; assertThat ( other . get ( ) , is ( ) ) ; } @ Test public void copyNull ( ) { IntOption option = new IntOption ( ) ; option . modify ( ) ; IntOption other = new IntOption ( ) ; option . copyFrom ( other ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; option . modify ( ) ; option . copyFrom ( null ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; } @ Test public void compareTo ( ) { IntOption a = new IntOption ( ) ; IntOption b = new IntOption ( ) ; IntOption c = new IntOption ( ) ; IntOption d = new IntOption ( ) ; a . modify ( - ) ; b . modify ( ) ; c . modify ( ) ; d . modify ( - ) ; assertThat ( compare ( a , b ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , lessThan ( ) ) ; assertThat ( compare ( c , a ) , greaterThan ( ) ) ; assertThat ( compare ( a , c ) , lessThan ( ) ) ; assertThat ( compare ( b , a ) , greaterThan ( ) ) ; assertThat ( compare ( c , b ) , greaterThan ( ) ) ; assertThat ( compare ( a , d ) , is ( ) ) ; } @ Test public void compareNull ( ) { IntOption a = new IntOption ( ) ; IntOption b = new IntOption ( ) ; IntOption c = new IntOption ( ) ; a . modify ( ) ; assertThat ( compare ( a , b ) , greaterThan ( ) ) ; assertThat ( compare ( b , a ) , lessThan ( ) ) ; assertThat ( compare ( b , c ) , is ( ) ) ; } @ Test public void write ( ) { IntOption option = new IntOption ( ) ; option . modify ( ) ; IntOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_max ( ) { IntOption option = new IntOption ( ) ; option . modify ( Integer . MAX_VALUE ) ; IntOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void write_0 ( ) { IntOption option = new IntOption ( ) ; option . modify ( ) ; IntOption restored = restore ( option ) ; assertThat ( restored . get ( ) , is ( option . get ( ) ) ) ; } @ Test public void writeNull ( ) { IntOption option = new IntOption ( ) ; IntOption restored = restore ( option ) ; assertThat ( restored . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . io ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . InputStream ; import java . util . Collections ; import java . util . LinkedList ; import org . junit . Test ; import com . asakusafw . runtime . io . testing . model . MockModel ; public class TsvIoFactoryTest { @ Test public void input ( ) throws Exception { TsvIoFactory < MockModel > factory = new TsvIoFactory < MockModel > ( MockModel . class ) ; MockModel object = factory . createModelObject ( ) ; InputStream in = new ByteArrayInputStream ( "" . getBytes ( "" ) ) ; LinkedList < String > expected = new LinkedList < String > ( ) ; Collections . addAll ( expected , "" , "" , "" , "" ) ; ModelInput < MockModel > modelIn = factory . createModelInput ( in ) ; try { while ( modelIn . readTo ( object ) ) { assertThat ( expected . isEmpty ( ) , is ( false ) ) ; object . assertValueIs ( expected . removeFirst ( ) ) ; } assertThat ( expected . isEmpty ( ) , is ( true ) ) ; } finally { modelIn . close ( ) ; } } @ SuppressWarnings ( "" ) @ Test public void output ( ) throws Exception { TsvIoFactory < MockModel > factory = new TsvIoFactory < MockModel > ( MockModel . class ) ; MockModel object = factory . createModelObject ( ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; ModelOutput < MockModel > modelOut = factory . createModelOutput ( out ) ; try { object . value . modify ( "" ) ; modelOut . write ( object ) ; object . value . modify ( "" ) ; modelOut . write ( object ) ; object . value . modify ( "" ) ; modelOut . write ( object ) ; object . value . modify ( "" ) ; modelOut . write ( object ) ; } finally { modelOut . close ( ) ; } String result = new String ( out . toByteArray ( ) , "" ) ; assertThat ( result , is ( "" ) ) ; } } package com . asakusafw . runtime . io ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . StringReader ; import java . io . StringWriter ; import java . math . BigDecimal ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; @ SuppressWarnings ( "" ) public class TsvEmitterTest { private static final String LONG_STRING = "" ; private final StringWriter buffer = new StringWriter ( ) ; private TsvEmitter emitter ; @ Before public void setUp ( ) throws Exception { emitter = new TsvEmitter ( buffer ) ; } private RecordParser parser ( ) throws IOException { emitter . close ( ) ; return new TsvParser ( new StringReader ( buffer . toString ( ) ) ) ; } @ Test public void emitBoolean ( ) throws Exception { BooleanOption value = new BooleanOption ( ) ; value . modify ( true ) ; emitter . emit ( value ) ; value . modify ( false ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . modify ( false ) ; emitter . emit ( value ) ; value . modify ( true ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( true ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( false ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( false ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( true ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( false ) ) ; } @ Test public void emitByte ( ) throws Exception { ByteOption value = new ByteOption ( ) ; value . modify ( ( byte ) ) ; emitter . emit ( value ) ; value . modify ( ( byte ) ) ; emitter . emit ( value ) ; value . modify ( ( byte ) - ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( Byte . MAX_VALUE ) ; emitter . emit ( value ) ; value . modify ( Byte . MIN_VALUE ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( byte ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( byte ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( byte ) - ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Byte . MAX_VALUE ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Byte . MIN_VALUE ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitShort ( ) throws Exception { ShortOption value = new ShortOption ( ) ; value . modify ( ( short ) ) ; emitter . emit ( value ) ; value . modify ( ( short ) ) ; emitter . emit ( value ) ; value . modify ( ( short ) - ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( Short . MAX_VALUE ) ; emitter . emit ( value ) ; value . modify ( Short . MIN_VALUE ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( short ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( short ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( short ) - ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Short . MAX_VALUE ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Short . MIN_VALUE ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitInt ( ) throws Exception { IntOption value = new IntOption ( ) ; value . modify ( ) ; emitter . emit ( value ) ; value . modify ( ) ; emitter . emit ( value ) ; value . modify ( - ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( Integer . MAX_VALUE ) ; emitter . emit ( value ) ; value . modify ( Integer . MIN_VALUE ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Integer . MAX_VALUE ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Integer . MIN_VALUE ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitLong ( ) throws Exception { LongOption value = new LongOption ( ) ; value . modify ( ) ; emitter . emit ( value ) ; value . modify ( ) ; emitter . emit ( value ) ; value . modify ( - ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( Long . MAX_VALUE ) ; emitter . emit ( value ) ; value . modify ( Long . MIN_VALUE ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Long . MAX_VALUE ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Long . MIN_VALUE ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitFloat ( ) throws Exception { FloatOption value = new FloatOption ( ) ; value . modify ( + ) ; emitter . emit ( value ) ; value . modify ( - ) ; emitter . emit ( value ) ; value . modify ( + ) ; emitter . emit ( value ) ; value . modify ( - ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( Float . POSITIVE_INFINITY ) ; emitter . emit ( value ) ; value . modify ( Float . NEGATIVE_INFINITY ) ; emitter . emit ( value ) ; value . modify ( Float . NaN ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( + ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( + ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Float . POSITIVE_INFINITY ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Float . NEGATIVE_INFINITY ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Float . NaN ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitDouble ( ) throws Exception { DoubleOption value = new DoubleOption ( ) ; value . modify ( + ) ; emitter . emit ( value ) ; value . modify ( - ) ; emitter . emit ( value ) ; value . modify ( + ) ; emitter . emit ( value ) ; value . modify ( - ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( Float . POSITIVE_INFINITY ) ; emitter . emit ( value ) ; value . modify ( Float . NEGATIVE_INFINITY ) ; emitter . emit ( value ) ; value . modify ( Float . NaN ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( + ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( + ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Double . POSITIVE_INFINITY ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Double . NEGATIVE_INFINITY ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Double . NaN ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitDecimal ( ) throws Exception { DecimalOption value = new DecimalOption ( ) ; value . modify ( decimal ( "" ) ) ; emitter . emit ( value ) ; value . modify ( decimal ( "" ) ) ; emitter . emit ( value ) ; value . modify ( decimal ( "" ) ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( decimal ( "" ) ) ; emitter . emit ( value ) ; value . modify ( decimal ( "" ) ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitString ( ) throws Exception { StringOption value = new StringOption ( ) ; value . modify ( "" ) ; emitter . emit ( value ) ; value . modify ( "" ) ; emitter . emit ( value ) ; value . modify ( "" ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( "" ) ; emitter . emit ( value ) ; value . modify ( LONG_STRING ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( LONG_STRING ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitDate ( ) throws Exception { DateOption value = new DateOption ( ) ; value . modify ( date ( , , ) ) ; emitter . emit ( value ) ; value . modify ( date ( , , ) ) ; emitter . emit ( value ) ; value . modify ( date ( , , ) ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( date ( , , ) ) ; emitter . emit ( value ) ; value . modify ( date ( , , ) ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void emitDateTime ( ) throws Exception { DateTimeOption value = new DateTimeOption ( ) ; value . modify ( time ( , , , , , ) ) ; emitter . emit ( value ) ; value . modify ( time ( , , , , , ) ) ; emitter . emit ( value ) ; value . modify ( time ( , , , , , ) ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; value . setNull ( ) ; emitter . emit ( value ) ; value . modify ( time ( , , , , , ) ) ; emitter . emit ( value ) ; value . modify ( time ( , , , , , ) ) ; emitter . emit ( value ) ; emitter . endRecord ( ) ; emitter . close ( ) ; RecordParser parser = parser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } private Date date ( int y , int m , int d ) { int elapsed = DateUtil . getDayFromDate ( y , m , d ) ; Date date = new Date ( ) ; date . setElapsedDays ( elapsed ) ; return date ; } private DateTime time ( int y , int m , int d , int h , int min , int s ) { int days = DateUtil . getDayFromDate ( y , m , d ) ; int secs = DateUtil . getSecondFromTime ( h , min , s ) ; DateTime date = new DateTime ( ) ; date . setElapsedSeconds ( ( long ) days * + secs ) ; return date ; } private BigDecimal decimal ( String representation ) { return new BigDecimal ( representation ) ; } } package com . asakusafw . runtime . io . sequencefile ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . BufferedOutputStream ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . InputStream ; import java . io . OutputStream ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . LocalFileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . LongWritable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . compress . DefaultCodec ; import org . junit . After ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class SequenceFileUtilTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; private LocalFileSystem fs ; private Path workingDirectory ; private Configuration conf ; @ Before public void setUp ( ) throws Exception { conf = new Configuration ( ) ; fs = FileSystem . getLocal ( conf ) ; workingDirectory = fs . getWorkingDirectory ( ) ; fs . setWorkingDirectory ( new Path ( folder . getRoot ( ) . getAbsoluteFile ( ) . toURI ( ) ) ) ; } @ After public void tearDown ( ) throws Exception { if ( fs != null && workingDirectory != null ) { fs . setWorkingDirectory ( workingDirectory ) ; } } @ Test public void read ( ) throws Exception { Path path = new Path ( "" ) ; Text key = new Text ( ) ; Text value = new Text ( ) ; SequenceFile . Writer writer = SequenceFile . createWriter ( fs , conf , path , key . getClass ( ) , value . getClass ( ) ) ; try { key . set ( "" ) ; value . set ( "" ) ; writer . append ( key , value ) ; } finally { writer . close ( ) ; } key . clear ( ) ; value . clear ( ) ; FileStatus status = fs . getFileStatus ( path ) ; InputStream in = new FileInputStream ( fs . pathToFile ( path ) ) ; try { SequenceFile . Reader reader = SequenceFileUtil . openReader ( in , status , conf ) ; assertThat ( reader . next ( key , value ) , is ( true ) ) ; assertThat ( key . toString ( ) , is ( "" ) ) ; assertThat ( value . toString ( ) , is ( "" ) ) ; assertThat ( reader . next ( key , value ) , is ( false ) ) ; reader . close ( ) ; } finally { in . close ( ) ; } } @ Test public void read_new ( ) throws Exception { Path path = new Path ( "" ) ; Text key = new Text ( ) ; Text value = new Text ( ) ; SequenceFile . Writer writer = SequenceFile . createWriter ( fs , conf , path , key . getClass ( ) , value . getClass ( ) ) ; try { key . set ( "" ) ; value . set ( "" ) ; writer . append ( key , value ) ; } finally { writer . close ( ) ; } key . clear ( ) ; value . clear ( ) ; FileStatus status = fs . getFileStatus ( path ) ; InputStream in = new FileInputStream ( fs . pathToFile ( path ) ) ; try { SequenceFile . Reader reader = SequenceFileUtil . openReader ( in , status . getLen ( ) , conf ) ; assertThat ( reader . next ( key , value ) , is ( true ) ) ; assertThat ( key . toString ( ) , is ( "" ) ) ; assertThat ( value . toString ( ) , is ( "" ) ) ; assertThat ( reader . next ( key , value ) , is ( false ) ) ; reader . close ( ) ; } finally { in . close ( ) ; } } @ Test public void original_large ( ) throws Exception { Path path = new Path ( "" ) ; LongWritable key = new LongWritable ( ) ; LongWritable value = new LongWritable ( ) ; SequenceFile . Writer writer = SequenceFile . createWriter ( fs , conf , path , key . getClass ( ) , value . getClass ( ) ) ; try { for ( long i = ; i < ; i ++ ) { key . set ( i ) ; value . set ( i + ) ; writer . append ( key , value ) ; } } finally { writer . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { for ( long i = ; i < ; i ++ ) { assertThat ( reader . next ( key , value ) , is ( true ) ) ; assertThat ( key . get ( ) , is ( i ) ) ; assertThat ( value . get ( ) , is ( i + ) ) ; } assertThat ( reader . next ( key , value ) , is ( false ) ) ; } finally { reader . close ( ) ; } } @ Test public void read_large ( ) throws Exception { Path path = new Path ( "" ) ; LongWritable key = new LongWritable ( ) ; LongWritable value = new LongWritable ( ) ; SequenceFile . Writer writer = SequenceFile . createWriter ( fs , conf , path , key . getClass ( ) , value . getClass ( ) ) ; try { for ( long i = ; i < ; i ++ ) { key . set ( i ) ; value . set ( i + ) ; writer . append ( key , value ) ; } } finally { writer . close ( ) ; } FileStatus status = fs . getFileStatus ( path ) ; InputStream in = new FileInputStream ( fs . pathToFile ( path ) ) ; try { SequenceFile . Reader reader = SequenceFileUtil . openReader ( in , status , conf ) ; for ( long i = ; i < ; i ++ ) { assertThat ( reader . next ( key , value ) , is ( true ) ) ; assertThat ( key . get ( ) , is ( i ) ) ; assertThat ( value . get ( ) , is ( i + ) ) ; } assertThat ( reader . next ( key , value ) , is ( false ) ) ; reader . close ( ) ; } finally { in . close ( ) ; } } @ Test public void write ( ) throws Exception { Path path = new Path ( "" ) ; Text key = new Text ( ) ; Text value = new Text ( ) ; OutputStream out = new FileOutputStream ( fs . pathToFile ( path ) ) ; try { SequenceFile . Writer writer = SequenceFileUtil . openWriter ( new BufferedOutputStream ( out ) , conf , key . getClass ( ) , value . getClass ( ) , null ) ; key . set ( "" ) ; value . set ( "" ) ; writer . append ( key , value ) ; writer . close ( ) ; } finally { out . close ( ) ; } key . clear ( ) ; value . clear ( ) ; SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { assertThat ( reader . next ( key , value ) , is ( true ) ) ; assertThat ( key . toString ( ) , is ( "" ) ) ; assertThat ( value . toString ( ) , is ( "" ) ) ; assertThat ( reader . next ( key , value ) , is ( false ) ) ; } finally { reader . close ( ) ; } } @ Test public void write_large ( ) throws Exception { Path path = new Path ( "" ) ; LongWritable key = new LongWritable ( ) ; LongWritable value = new LongWritable ( ) ; OutputStream out = new FileOutputStream ( fs . pathToFile ( path ) ) ; try { SequenceFile . Writer writer = SequenceFileUtil . openWriter ( new BufferedOutputStream ( out ) , conf , key . getClass ( ) , value . getClass ( ) , null ) ; for ( long i = ; i < ; i ++ ) { key . set ( i ) ; value . set ( i + ) ; writer . append ( key , value ) ; } writer . close ( ) ; } finally { out . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { for ( long i = ; i < ; i ++ ) { assertThat ( reader . next ( key , value ) , is ( true ) ) ; assertThat ( key . get ( ) , is ( i ) ) ; assertThat ( value . get ( ) , is ( i + ) ) ; } assertThat ( reader . next ( key , value ) , is ( false ) ) ; } finally { reader . close ( ) ; } } @ Test public void write_compressed ( ) throws Exception { DefaultCodec codec = new DefaultCodec ( ) ; codec . setConf ( conf ) ; Path path = new Path ( "" ) ; LongWritable key = new LongWritable ( ) ; LongWritable value = new LongWritable ( ) ; OutputStream out = new FileOutputStream ( fs . pathToFile ( path ) ) ; try { SequenceFile . Writer writer = SequenceFileUtil . openWriter ( new BufferedOutputStream ( out ) , conf , key . getClass ( ) , value . getClass ( ) , codec ) ; for ( long i = ; i < ; i ++ ) { key . set ( i ) ; value . set ( i + ) ; writer . append ( key , value ) ; } writer . close ( ) ; } finally { out . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { for ( long i = ; i < ; i ++ ) { assertThat ( reader . next ( key , value ) , is ( true ) ) ; assertThat ( key . get ( ) , is ( i ) ) ; assertThat ( value . get ( ) , is ( i + ) ) ; } assertThat ( reader . next ( key , value ) , is ( false ) ) ; } finally { reader . close ( ) ; } } } package com . asakusafw . runtime . io . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ SuppressWarnings ( "" ) public class WritableUnionTest extends WritableTestRoot { @ Test public void createFromClasses ( ) throws Exception { Union union = new WritableUnion ( IntOption . class , LongOption . class , StringOption . class ) ; assertThat ( union . switchObject ( ) , instanceOf ( IntOption . class ) ) ; assertThat ( union . switchObject ( ) , instanceOf ( LongOption . class ) ) ; assertThat ( union . switchObject ( ) , instanceOf ( StringOption . class ) ) ; ( ( IntOption ) union . switchObject ( ) ) . modify ( ) ; assertThat ( union . getPosition ( ) , is ( ) ) ; ( ( LongOption ) union . switchObject ( ) ) . modify ( ) ; assertThat ( union . getPosition ( ) , is ( ) ) ; ( ( StringOption ) union . switchObject ( ) ) . modify ( "" ) ; assertThat ( union . getPosition ( ) , is ( ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; } @ Test public void createFromObject ( ) throws Exception { Union union = new WritableUnion ( new IntOption ( ) , new LongOption ( ) , new StringOption ( "" ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; } @ Test public void serialize ( ) throws Exception { WritableUnion union = new WritableUnion ( new IntOption ( ) , new LongOption ( ) , new StringOption ( "" ) , new StringOption ( ) ) ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = buf . capacity ( ) ; i < n ; i ++ ) { buf . append ( ( char ) ( '' + ( i * % ) ) ) ; } ( ( StringOption ) union . switchObject ( ) ) . modify ( buf . toString ( ) ) ; WritableUnion r0 = new WritableUnion ( IntOption . class , LongOption . class , StringOption . class ) ; union . switchObject ( ) ; byte [ ] s0 = ser ( union ) ; des ( r0 , s0 ) ; assertThat ( r0 . getPosition ( ) , is ( ) ) ; assertThat ( r0 . getObject ( ) , is ( ( Object ) new IntOption ( ) ) ) ; WritableUnion r1 = new WritableUnion ( IntOption . class , LongOption . class , StringOption . class ) ; union . switchObject ( ) ; byte [ ] s1 = ser ( union ) ; des ( r1 , s1 ) ; assertThat ( r1 . getPosition ( ) , is ( ) ) ; assertThat ( r1 . getObject ( ) , is ( ( Object ) new LongOption ( ) ) ) ; WritableUnion r2 = new WritableUnion ( IntOption . class , LongOption . class , StringOption . class ) ; union . switchObject ( ) ; byte [ ] s2 = ser ( union ) ; des ( r2 , s2 ) ; assertThat ( r2 . getPosition ( ) , is ( ) ) ; assertThat ( r2 . getObject ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; byte [ ] large = ser ( ( StringOption ) union . switchObject ( ) ) ; assertThat ( s0 . length , lessThan ( large . length ) ) ; assertThat ( s1 . length , lessThan ( large . length ) ) ; assertThat ( s2 . length , lessThan ( large . length ) ) ; } } package com . asakusafw . runtime . io . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ SuppressWarnings ( "" ) public class WritableRawComparableTupleTest extends WritableTestRoot { @ Test public void createFromClasses ( ) throws Exception { WritableRawComparableTuple tuple = new WritableRawComparableTuple ( IntOption . class , LongOption . class , StringOption . class ) ; assertThat ( tuple . size ( ) , is ( ) ) ; assertThat ( tuple . get ( ) , instanceOf ( IntOption . class ) ) ; assertThat ( tuple . get ( ) , instanceOf ( LongOption . class ) ) ; assertThat ( tuple . get ( ) , instanceOf ( StringOption . class ) ) ; ( ( IntOption ) tuple . get ( ) ) . modify ( ) ; ( ( LongOption ) tuple . get ( ) ) . modify ( ) ; ( ( StringOption ) tuple . get ( ) ) . modify ( "" ) ; assertThat ( tuple . get ( ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( tuple . get ( ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( tuple . get ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; } @ Test public void createFromObjects ( ) throws Exception { WritableRawComparableTuple tuple = new WritableRawComparableTuple ( new IntOption ( ) , new LongOption ( ) , new StringOption ( "" ) ) ; assertThat ( tuple . get ( ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( tuple . get ( ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( tuple . get ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; } @ Test public void serialize ( ) throws Exception { WritableRawComparableTuple tuple = new WritableRawComparableTuple ( new IntOption ( ) , new LongOption ( ) , new StringOption ( "" ) ) ; WritableRawComparableTuple restored = new WritableRawComparableTuple ( IntOption . class , LongOption . class , StringOption . class ) ; byte [ ] serialized = ser ( tuple ) ; des ( restored , serialized ) ; assertThat ( restored . get ( ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( restored . get ( ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( restored . get ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; } @ Test public void compare ( ) throws Exception { WritableRawComparableTuple a = new WritableRawComparableTuple ( new IntOption ( ) , new IntOption ( ) , new IntOption ( ) ) ; WritableRawComparableTuple b = new WritableRawComparableTuple ( new IntOption ( ) , new IntOption ( ) , new IntOption ( ) ) ; WritableRawComparableTuple c = new WritableRawComparableTuple ( new IntOption ( ) , new IntOption ( ) , new IntOption ( ) ) ; WritableRawComparableTuple d = new WritableRawComparableTuple ( new IntOption ( ) , new IntOption ( ) , new IntOption ( ) ) ; WritableRawComparableTuple e = new WritableRawComparableTuple ( new IntOption ( ) , new IntOption ( ) , new IntOption ( ) ) ; assertThat ( cmp ( a , b ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( a , c ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( a , d ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( b , c ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( b , d ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( c , d ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( e , a ) , is ( equalTo ( ) ) ) ; assertThat ( cmp ( b , a ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( c , b ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( d , c ) , is ( greaterThan ( ) ) ) ; } } package com . asakusafw . runtime . io . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . runtime . value . IntOption ; public class InvertOrderTest extends WritableTestRoot { @ Test public void fundamental ( ) throws Exception { IntOption entity = new IntOption ( ) ; InvertOrder invert = new InvertOrder ( entity ) ; assertThat ( invert . getEntity ( ) , sameInstance ( ( Object ) entity ) ) ; } @ Test public void serialize ( ) throws Exception { IntOption entity = new IntOption ( ) ; InvertOrder invert = new InvertOrder ( entity ) ; byte [ ] serialized = ser ( invert ) ; InvertOrder restored = des ( new InvertOrder ( new IntOption ( ) ) , serialized ) ; assertThat ( restored . getEntity ( ) , is ( ( Object ) entity ) ) ; assertThat ( restored . getEntity ( ) , not ( sameInstance ( ( Object ) entity ) ) ) ; } @ Test public void compare ( ) throws Exception { InvertOrder a = new InvertOrder ( new IntOption ( ) ) ; InvertOrder b = new InvertOrder ( new IntOption ( ) ) ; InvertOrder c = new InvertOrder ( new IntOption ( ) ) ; assertThat ( cmp ( a , b ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( b , a ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( a , c ) , is ( equalTo ( ) ) ) ; } } package com . asakusafw . runtime . io . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ SuppressWarnings ( "" ) public class WritableRawComparableUnionTest extends WritableTestRoot { @ Test public void createFromClasses ( ) throws Exception { Union union = new WritableRawComparableUnion ( IntOption . class , LongOption . class , StringOption . class ) ; assertThat ( union . switchObject ( ) , instanceOf ( IntOption . class ) ) ; assertThat ( union . switchObject ( ) , instanceOf ( LongOption . class ) ) ; assertThat ( union . switchObject ( ) , instanceOf ( StringOption . class ) ) ; ( ( IntOption ) union . switchObject ( ) ) . modify ( ) ; assertThat ( union . getPosition ( ) , is ( ) ) ; ( ( LongOption ) union . switchObject ( ) ) . modify ( ) ; assertThat ( union . getPosition ( ) , is ( ) ) ; ( ( StringOption ) union . switchObject ( ) ) . modify ( "" ) ; assertThat ( union . getPosition ( ) , is ( ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; } @ Test public void createFromObject ( ) throws Exception { Union union = new WritableRawComparableUnion ( new IntOption ( ) , new LongOption ( ) , new StringOption ( "" ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( union . switchObject ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; } @ Test public void serialize ( ) throws Exception { WritableRawComparableUnion union = new WritableRawComparableUnion ( new IntOption ( ) , new LongOption ( ) , new StringOption ( "" ) , new StringOption ( ) ) ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = buf . capacity ( ) ; i < n ; i ++ ) { buf . append ( ( char ) ( '' + ( i * % ) ) ) ; } ( ( StringOption ) union . switchObject ( ) ) . modify ( buf . toString ( ) ) ; WritableRawComparableUnion r0 = new WritableRawComparableUnion ( IntOption . class , LongOption . class , StringOption . class ) ; union . switchObject ( ) ; byte [ ] s0 = ser ( union ) ; des ( r0 , s0 ) ; assertThat ( r0 . getPosition ( ) , is ( ) ) ; assertThat ( r0 . getObject ( ) , is ( ( Object ) new IntOption ( ) ) ) ; WritableRawComparableUnion r1 = new WritableRawComparableUnion ( IntOption . class , LongOption . class , StringOption . class ) ; union . switchObject ( ) ; byte [ ] s1 = ser ( union ) ; des ( r1 , s1 ) ; assertThat ( r1 . getPosition ( ) , is ( ) ) ; assertThat ( r1 . getObject ( ) , is ( ( Object ) new LongOption ( ) ) ) ; WritableRawComparableUnion r2 = new WritableRawComparableUnion ( IntOption . class , LongOption . class , StringOption . class ) ; union . switchObject ( ) ; byte [ ] s2 = ser ( union ) ; des ( r2 , s2 ) ; assertThat ( r2 . getPosition ( ) , is ( ) ) ; assertThat ( r2 . getObject ( ) , is ( ( Object ) new StringOption ( "" ) ) ) ; byte [ ] large = ser ( ( StringOption ) union . switchObject ( ) ) ; assertThat ( s0 . length , lessThan ( large . length ) ) ; assertThat ( s1 . length , lessThan ( large . length ) ) ; assertThat ( s2 . length , lessThan ( large . length ) ) ; } @ Test public void compare ( ) throws Exception { WritableRawComparableUnion a = new WritableRawComparableUnion ( new IntOption ( ) , new LongOption ( ) ) ; WritableRawComparableUnion b = new WritableRawComparableUnion ( new IntOption ( ) , new LongOption ( ) ) ; WritableRawComparableUnion c = new WritableRawComparableUnion ( new IntOption ( ) , new LongOption ( ) ) ; a . switchObject ( ) ; b . switchObject ( ) ; c . switchObject ( ) ; assertThat ( cmp ( a , b ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( b , c ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( c , a ) , is ( equalTo ( ) ) ) ; a . switchObject ( ) ; b . switchObject ( ) ; c . switchObject ( ) ; assertThat ( cmp ( a , b ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( b , c ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( c , a ) , is ( equalTo ( ) ) ) ; a . switchObject ( ) ; c . switchObject ( ) ; assertThat ( cmp ( a , c ) , is ( not ( ) ) ) ; assertThat ( cmp ( c , a ) , is ( not ( ) ) ) ; } } package com . asakusafw . runtime . io . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . WritableComparator ; public class WritableTestRoot { static byte [ ] ser ( Writable writable ) throws IOException { DataOutputBuffer out = new DataOutputBuffer ( ) ; writable . write ( out ) ; byte [ ] results = Arrays . copyOfRange ( out . getData ( ) , , out . getLength ( ) ) ; return results ; } static byte [ ] ser ( WritableRawComparable writable ) throws IOException { DataOutputBuffer out = new DataOutputBuffer ( ) ; writable . write ( out ) ; assertThat ( writable . getSizeInBytes ( out . getData ( ) , ) , is ( out . getLength ( ) ) ) ; byte [ ] results = Arrays . copyOfRange ( out . getData ( ) , , out . getLength ( ) ) ; return results ; } static < T extends Writable > T des ( T writable , byte [ ] serialized ) throws IOException { DataInputBuffer buf = new DataInputBuffer ( ) ; buf . reset ( serialized , serialized . length ) ; writable . readFields ( buf ) ; return writable ; } static int cmp ( WritableRawComparable a , WritableRawComparable b ) throws IOException { int cmp = a . compareTo ( b ) ; assertThat ( a . equals ( b ) , is ( cmp == ) ) ; if ( cmp == ) { assertThat ( a . hashCode ( ) , is ( b . hashCode ( ) ) ) ; } byte [ ] serA = ser ( a ) ; byte [ ] serB = ser ( b ) ; int serCmp = a . compareInBytes ( serA , , serB , ) ; assertThat ( serCmp , is ( cmp ) ) ; return cmp ; } static int cmp ( WritableRawComparable a , WritableRawComparable b , WritableComparator comp ) throws IOException { int cmp = comp . compare ( a , b ) ; byte [ ] serA = ser ( a ) ; byte [ ] serB = ser ( b ) ; int serCmp = comp . compare ( serA , , serA . length , serB , , serB . length ) ; assertThat ( serCmp , is ( cmp ) ) ; return cmp ; } } package com . asakusafw . runtime . io . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Random ; import org . apache . hadoop . io . WritableComparator ; import org . apache . hadoop . mapreduce . Partitioner ; import org . junit . Test ; import com . asakusafw . runtime . value . StringOption ; public class ShuffleKeyTest extends WritableTestRoot { @ Test public void serialize ( ) throws Exception { Mock mock = new Mock ( "" , "" ) ; byte [ ] serialized = ser ( mock ) ; Mock restored = des ( new Mock ( ) , serialized ) ; assertThat ( restored . toString ( ) , restored , is ( mock ) ) ; assertThat ( restored . compareTo ( mock ) , is ( ) ) ; assertThat ( restored . getGroupObject ( ) . getAsString ( ) , is ( "" ) ) ; assertThat ( restored . getOrderObject ( ) . getAsString ( ) , is ( "" ) ) ; } @ Test public void compare ( ) throws Exception { Mock o11 = new Mock ( "" , "" ) ; Mock o12 = new Mock ( "" , "" ) ; Mock o21 = new Mock ( "" , "" ) ; Mock o22 = new Mock ( "" , "" ) ; assertThat ( cmp ( o11 , o11 ) , is ( ) ) ; assertThat ( cmp ( o11 , o12 ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( o12 , o11 ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( o12 , o21 ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( o21 , o12 ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( o21 , o22 ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( o22 , o21 ) , is ( greaterThan ( ) ) ) ; } @ SuppressWarnings ( "" ) @ Test public void partition ( ) throws Exception { Partitioner < ShuffleKey , ? > part = new ShuffleKey . Partitioner ( ) ; Mock o11 = new Mock ( "" , "" ) ; Mock o12 = new Mock ( "" , "" ) ; Mock o21 = new Mock ( "" , "" ) ; Mock o22 = new Mock ( "" , "" ) ; assertThat ( part . getPartition ( o11 , null , ) , equalTo ( part . getPartition ( o11 , null , ) ) ) ; assertThat ( part . getPartition ( o11 , null , ) , equalTo ( part . getPartition ( o12 , null , ) ) ) ; assertThat ( part . getPartition ( o21 , null , ) , equalTo ( part . getPartition ( o22 , null , ) ) ) ; Random random = new Random ( ) ; for ( int i = ; i < ; i ++ ) { Mock mock = new Mock ( String . valueOf ( random . nextInt ( ) ) , "" ) ; int value = part . getPartition ( mock , null , ) ; assertThat ( value , is ( greaterThanOrEqualTo ( ) ) ) ; } boolean found = false ; for ( int i = ; i < ; i ++ ) { Mock left = new Mock ( String . valueOf ( random . nextInt ( ) ) , "" ) ; Mock right = new Mock ( String . valueOf ( random . nextInt ( ) ) , "" ) ; if ( left . getGroupObject ( ) . equals ( right . getGroupObject ( ) ) ) { continue ; } if ( part . getPartition ( left , null , ) != part . getPartition ( right , null , ) ) { found = true ; break ; } } assertThat ( found , is ( true ) ) ; } @ Test public void grouping ( ) throws Exception { WritableComparator comp = new Group ( ) ; Mock o11 = new Mock ( "" , "" ) ; Mock o12 = new Mock ( "" , "" ) ; Mock o21 = new Mock ( "" , "" ) ; Mock o22 = new Mock ( "" , "" ) ; assertThat ( cmp ( o11 , o11 , comp ) , is ( ) ) ; assertThat ( cmp ( o11 , o12 , comp ) , is ( equalTo ( ) ) ) ; assertThat ( cmp ( o12 , o11 , comp ) , is ( equalTo ( ) ) ) ; assertThat ( cmp ( o21 , o22 , comp ) , is ( equalTo ( ) ) ) ; assertThat ( cmp ( o22 , o21 , comp ) , is ( equalTo ( ) ) ) ; assertThat ( cmp ( o12 , o21 , comp ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( o21 , o12 , comp ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( o11 , o22 , comp ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( o22 , o11 , comp ) , is ( greaterThan ( ) ) ) ; } @ Test public void ordering ( ) throws Exception { WritableComparator comp = new Order ( ) ; Mock o11 = new Mock ( "" , "" ) ; Mock o12 = new Mock ( "" , "" ) ; Mock o21 = new Mock ( "" , "" ) ; Mock o22 = new Mock ( "" , "" ) ; assertThat ( cmp ( o11 , o11 , comp ) , is ( ) ) ; assertThat ( cmp ( o11 , o12 , comp ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( o12 , o11 , comp ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( o12 , o21 , comp ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( o21 , o12 , comp ) , is ( greaterThan ( ) ) ) ; assertThat ( cmp ( o21 , o22 , comp ) , is ( lessThan ( ) ) ) ; assertThat ( cmp ( o22 , o21 , comp ) , is ( greaterThan ( ) ) ) ; } private static class Mock extends ShuffleKey < StringOption , StringOption > { Mock ( ) { super ( StringOption . class , StringOption . class ) ; } Mock ( String group , String order ) { super ( new StringOption ( group ) , new StringOption ( order ) ) ; } } private static class Group extends ShuffleKey . AbstractGroupComparator { Group ( ) { super ( Mock . class ) ; } } private static class Order extends ShuffleKey . AbstractOrderComparator { Order ( ) { super ( Mock . class ) ; } } } package com . asakusafw . runtime . io ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . math . BigDecimal ; import org . junit . After ; import org . junit . Test ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; public class TsvParserTest { private static final String LONG_STRING = "" ; private TsvParser parser ; private void create ( String fileName ) throws IOException { InputStream in = TsvParserTest . class . getResourceAsStream ( "" + fileName ) ; assertThat ( fileName , in , is ( not ( nullValue ( ) ) ) ) ; parser = new TsvParser ( new InputStreamReader ( in , "" ) ) ; } @ After public void tearDown ( ) throws Exception { if ( parser != null ) { parser . close ( ) ; } } @ Test public void fillBoolean ( ) throws Exception { BooleanOption value = new BooleanOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( false ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( false ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( false ) ) ; parser . endRecord ( ) ; } @ Test public void fillByte ( ) throws Exception { ByteOption value = new ByteOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( byte ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( byte ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( byte ) - ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Byte . MAX_VALUE ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Byte . MIN_VALUE ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillShort ( ) throws Exception { ShortOption value = new ShortOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( short ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( short ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ( short ) - ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Short . MAX_VALUE ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Short . MIN_VALUE ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillInt ( ) throws Exception { IntOption value = new IntOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Integer . MAX_VALUE ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Integer . MIN_VALUE ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillLong ( ) throws Exception { LongOption value = new LongOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Long . MAX_VALUE ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Long . MIN_VALUE ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillFloat ( ) throws Exception { FloatOption value = new FloatOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( + ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( + ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Float . POSITIVE_INFINITY ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Float . NEGATIVE_INFINITY ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Float . NaN ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillDouble ( ) throws Exception { DoubleOption value = new DoubleOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( + ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( + ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( - ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Double . POSITIVE_INFINITY ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Double . NEGATIVE_INFINITY ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( Double . NaN ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillDecimal ( ) throws Exception { DecimalOption value = new DecimalOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( decimal ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillString ( ) throws Exception { StringOption value = new StringOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; parser . fill ( value ) ; assertThat ( value . getAsString ( ) , is ( LONG_STRING ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillDate ( ) throws Exception { DateOption value = new DateOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( date ( , , ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void fillDateTime ( ) throws Exception { DateTimeOption value = new DateTimeOption ( ) ; create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; parser . fill ( value ) ; assertThat ( value . get ( ) , is ( time ( , , , , , ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . fill ( value ) ; assertThat ( value . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } private Date date ( int y , int m , int d ) { int elapsed = DateUtil . getDayFromDate ( y , m , d ) ; Date date = new Date ( ) ; date . setElapsedDays ( elapsed ) ; return date ; } private DateTime time ( int y , int m , int d , int h , int min , int s ) { int days = DateUtil . getDayFromDate ( y , m , d ) ; int secs = DateUtil . getSecondFromTime ( h , min , s ) ; DateTime date = new DateTime ( ) ; date . setElapsedSeconds ( ( long ) days * + secs ) ; return date ; } private BigDecimal decimal ( String representation ) { return new BigDecimal ( representation ) ; } } package com . asakusafw . runtime . io . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . runtime . io . testing . model . MockModel ; public class MockModelModelOutput implements ModelOutput < MockModel > { private RecordEmitter emitter ; public MockModelModelOutput ( RecordEmitter emitter ) { this . emitter = emitter ; } @ Override public void write ( MockModel model ) throws IOException { emitter . emit ( model . value ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . runtime . io . testing . io ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . runtime . io . testing . model . MockModel ; public class MockModelModelInput implements ModelInput < MockModel > { private RecordParser parser ; public MockModelModelInput ( RecordParser parser ) { this . parser = parser ; } @ Override public boolean readTo ( MockModel model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . value ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . runtime . io . testing . model ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import com . asakusafw . runtime . value . StringOption ; public class MockModel { public StringOption value = new StringOption ( ) ; public void assertValueIs ( String expect ) { assertThat ( value . getAsString ( ) , is ( expect ) ) ; } } package com . asakusafw . runtime . io . csv ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . math . BigDecimal ; import java . util . Arrays ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TestName ; import com . asakusafw . runtime . io . csv . CsvFormatException . Reason ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; public class CsvParserTest { @ Rule public final TestName testName = new TestName ( ) ; private List < String > headers = CsvConfiguration . DEFAULT_HEADER_CELLS ; private String trueFormat = CsvConfiguration . DEFAULT_TRUE_FORMAT ; private String falseFormat = CsvConfiguration . DEFAULT_FALSE_FORMAT ; private String dateFormat = CsvConfiguration . DEFAULT_DATE_FORMAT ; private String dateTimeFormat = CsvConfiguration . DEFAULT_DATE_TIME_FORMAT ; private CsvParser create ( String content ) { CsvConfiguration conf = new CsvConfiguration ( CsvConfiguration . DEFAULT_CHARSET , headers , trueFormat , falseFormat , dateFormat , dateTimeFormat ) ; return new CsvParser ( new ByteArrayInputStream ( content . getBytes ( conf . getCharset ( ) ) ) , testName . getMethodName ( ) , conf ) ; } @ Test public void boolean_values ( ) throws Exception { trueFormat = "" ; falseFormat = "" ; CsvParser parser = create ( "" ) ; BooleanOption option = new BooleanOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( false ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void byte_values ( ) throws Exception { CsvParser parser = create ( "" ) ; ByteOption option = new ByteOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( byte ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( byte ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( byte ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( byte ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( byte ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( byte ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( byte ) - ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void invalid_byte ( ) throws Exception { CsvParser parser = create ( String . valueOf ( Byte . MAX_VALUE + ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new ByteOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void short_values ( ) throws Exception { CsvParser parser = create ( "" + Short . MAX_VALUE + "" + Short . MIN_VALUE + "" ) ; ShortOption option = new ShortOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( short ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( short ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( short ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( short ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( short ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( Short . MAX_VALUE ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( Short . MIN_VALUE ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void invalid_short ( ) throws Exception { CsvParser parser = create ( String . valueOf ( Short . MAX_VALUE + ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new ShortOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void int_values ( ) throws Exception { CsvParser parser = create ( "" + Integer . MAX_VALUE + "" + Integer . MIN_VALUE + "" ) ; IntOption option = new IntOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( Integer . MAX_VALUE ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( Integer . MIN_VALUE ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void invalid_int ( ) throws Exception { CsvParser parser = create ( String . valueOf ( ( long ) Integer . MAX_VALUE + ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new IntOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void long_values ( ) throws Exception { CsvParser parser = create ( "" + Long . MAX_VALUE + "" + Long . MIN_VALUE + "" ) ; LongOption option = new LongOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( long ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( long ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( long ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( long ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( long ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( Long . MAX_VALUE ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( Long . MIN_VALUE ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void invalid_long ( ) throws Exception { CsvParser parser = create ( String . valueOf ( Long . MAX_VALUE + "" ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new LongOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void float_values ( ) throws Exception { CsvParser parser = create ( "" + "" ) ; FloatOption option = new FloatOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( float ) - ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void invalid_float ( ) throws Exception { CsvParser parser = create ( String . valueOf ( "" ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new FloatOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void double_values ( ) throws Exception { CsvParser parser = create ( "" + "" ) ; DoubleOption option = new DoubleOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( double ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( double ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( double ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( double ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ( double ) - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( - ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( - ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void invalid_double ( ) throws Exception { CsvParser parser = create ( String . valueOf ( "" ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new DoubleOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void decimal_values ( ) throws Exception { CsvParser parser = create ( "" + "" ) ; DecimalOption option = new DecimalOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( decimal ( "" ) ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } private BigDecimal decimal ( String string ) { return new BigDecimal ( string ) ; } @ Test public void invalid_decimal ( ) throws Exception { CsvParser parser = create ( String . valueOf ( "" ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new DecimalOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void string_values ( ) throws Exception { CsvParser parser = create ( "" + "" + "" ) ; StringOption option = new StringOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . getAsString ( ) , is ( "" ) ) ; parser . fill ( option ) ; assertThat ( option . getAsString ( ) , is ( "" ) ) ; parser . fill ( option ) ; assertThat ( option . getAsString ( ) , is ( "" ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void date_values ( ) throws Exception { dateFormat = "" ; CsvParser parser = create ( "" + "" ) ; DateOption option = new DateOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( new Date ( , , ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( new Date ( , , ) ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void date_values_direct ( ) throws Exception { dateFormat = "" ; CsvParser parser = create ( "" + "" ) ; DateOption option = new DateOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( new Date ( , , ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( new Date ( , , ) ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void invalid_date ( ) throws Exception { CsvParser parser = create ( String . valueOf ( "" ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new DateOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void datetime_values ( ) throws Exception { dateTimeFormat = "" ; CsvParser parser = create ( "" + "" ) ; DateTimeOption option = new DateTimeOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( new DateTime ( , , , , , ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( new DateTime ( , , , , , ) ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void datetime_values_direct ( ) throws Exception { dateTimeFormat = "" ; CsvParser parser = create ( "" + "" ) ; DateTimeOption option = new DateTimeOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( new DateTime ( , , , , , ) ) ) ; parser . fill ( option ) ; assertThat ( option . get ( ) , is ( new DateTime ( , , , , , ) ) ) ; parser . fill ( option ) ; assertThat ( option . isNull ( ) , is ( true ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void invalid_datetime ( ) throws Exception { CsvParser parser = create ( String . valueOf ( "" ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { parser . fill ( new DateTimeOption ( ) ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . INVALID_CELL_FORMAT ) ) ; } } @ Test public void with_header ( ) throws Exception { headers = Arrays . asList ( "" , "" ) ; CsvParser parser = create ( "" + "" ) ; StringOption key = new StringOption ( ) ; StringOption value = new StringOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; parser . fill ( key ) ; parser . fill ( value ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; assertThat ( key . getAsString ( ) , is ( "" ) ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; } @ Test public void not_header ( ) throws Exception { headers = Arrays . asList ( "" , "" ) ; CsvParser parser = create ( "" + "" ) ; StringOption key = new StringOption ( ) ; StringOption value = new StringOption ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; parser . fill ( key ) ; parser . fill ( value ) ; parser . endRecord ( ) ; assertThat ( key . getAsString ( ) , is ( "" ) ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; parser . fill ( key ) ; parser . fill ( value ) ; parser . endRecord ( ) ; assertThat ( key . getAsString ( ) , is ( "" ) ) ; assertThat ( value . getAsString ( ) , is ( "" ) ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void empty_with_header ( ) throws Exception { headers = Arrays . asList ( "" , "" ) ; CsvParser parser = create ( "" ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void only_header ( ) throws Exception { headers = Arrays . asList ( "" , "" ) ; CsvParser parser = create ( "" ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void state_line_head ( ) throws Exception { CsvParser parser = create ( "" + "" + "" + "" + "" + "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void state_cell_head ( ) throws Exception { CsvParser parser = create ( "" + "" + "" + "" + "" + "" + "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; assertFill ( parser , null ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void state_cell_body ( ) throws Exception { CsvParser parser = create ( "" + "" + "" + "" + "" + "" + "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void state_quoted ( ) throws Exception { CsvParser parser = create ( "" + "" + "" + "" + "" + "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; try { assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( new StringOption ( ) ) ; parser . endRecord ( ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . UNEXPECTED_EOF ) ) ; } assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void state_nest_quote ( ) throws Exception { CsvParser parser = create ( "" + "" + "" + "" + "" + "" + "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void state_saw_cr ( ) throws Exception { CsvParser parser = create ( "" + "" + "" + "" + "" + "" + "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void state_quoted_saw_cr ( ) throws Exception { CsvParser parser = create ( "" + "" + "" + "" + "" + "" + "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( parser . getCurrentLineNumber ( ) , is ( ) ) ; assertThat ( parser . getCurrentRecordNumber ( ) , is ( ) ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; try { assertThat ( parser . next ( ) , is ( true ) ) ; parser . fill ( new StringOption ( "" ) ) ; parser . endRecord ( ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . UNEXPECTED_EOF ) ) ; } assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void many_separators ( ) throws Exception { StringBuilder buf = new StringBuilder ( ) ; final int separators = ; for ( int i = ; i < separators ; i ++ ) { buf . append ( '' ) ; buf . append ( '' ) ; } CsvParser parser = create ( buf . toString ( ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; for ( int i = ; i < separators ; i ++ ) { assertFill ( parser , "" ) ; } assertFill ( parser , null ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void many_characters ( ) throws Exception { StringBuilder buf = new StringBuilder ( ) ; final int characters = ; for ( int i = ; i < characters ; i ++ ) { buf . append ( '' ) ; } CsvParser parser = create ( buf . toString ( ) ) ; assertThat ( parser . next ( ) , is ( true ) ) ; StringOption option = new StringOption ( ) ; parser . fill ( option ) ; assertThat ( option . getAsString ( ) . length ( ) , is ( characters ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void too_many_characters ( ) throws Exception { InputStream infinite = new InputStream ( ) { @ Override public int read ( ) throws IOException { return '' ; } } ; CsvConfiguration conf = new CsvConfiguration ( CsvConfiguration . DEFAULT_CHARSET , headers , trueFormat , falseFormat , dateFormat , dateTimeFormat ) ; CsvParser parser = new CsvParser ( infinite , "" , conf ) ; try { assertThat ( parser . next ( ) , is ( true ) ) ; fail ( ) ; } catch ( IOException e ) { } } @ Test public void too_short_record ( ) throws Exception { CsvParser parser = create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { assertFill ( parser , "" ) ; assertFill ( parser , "" ) ; assertFill ( parser , "" ) ; parser . fill ( new StringOption ( ) ) ; parser . endRecord ( ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . TOO_SHORT_RECORD ) ) ; } assertThat ( parser . next ( ) , is ( false ) ) ; } @ Test public void too_long_record ( ) throws Exception { CsvParser parser = create ( "" ) ; assertThat ( parser . next ( ) , is ( true ) ) ; try { assertFill ( parser , "" ) ; assertFill ( parser , "" ) ; parser . endRecord ( ) ; fail ( ) ; } catch ( CsvFormatException e ) { assertThat ( e . getStatus ( ) . getReason ( ) , is ( Reason . TOO_LONG_RECORD ) ) ; } assertThat ( parser . next ( ) , is ( false ) ) ; } private void assertFill ( CsvParser parser , String expect ) throws CsvFormatException , IOException { StringOption buffer = new StringOption ( ) ; parser . fill ( buffer ) ; assertThat ( buffer . toString ( ) , buffer . has ( expect ) , is ( true ) ) ; } } package com . asakusafw . runtime . io . csv ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . math . BigDecimal ; import java . util . Arrays ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TestName ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . DoubleOption ; import com . asakusafw . runtime . value . FloatOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . runtime . value . ValueOption ; public class CsvEmitterTest { @ Rule public final TestName testName = new TestName ( ) ; private final ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; private List < String > headers = CsvConfiguration . DEFAULT_HEADER_CELLS ; private String trueFormat = CsvConfiguration . DEFAULT_TRUE_FORMAT ; private String falseFormat = CsvConfiguration . DEFAULT_FALSE_FORMAT ; private String dateFormat = CsvConfiguration . DEFAULT_DATE_FORMAT ; private String dateTimeFormat = CsvConfiguration . DEFAULT_DATE_TIME_FORMAT ; private CsvEmitter createEmitter ( ) { CsvConfiguration conf = new CsvConfiguration ( CsvConfiguration . DEFAULT_CHARSET , headers , trueFormat , falseFormat , dateFormat , dateTimeFormat ) ; return new CsvEmitter ( output , testName . getMethodName ( ) , conf ) ; } private CsvParser createParser ( ) { CsvConfiguration conf = new CsvConfiguration ( CsvConfiguration . DEFAULT_CHARSET , headers , trueFormat , falseFormat , dateFormat , dateTimeFormat ) ; return new CsvParser ( new ByteArrayInputStream ( output . toByteArray ( ) ) , testName . getMethodName ( ) , conf ) ; } private void assertRestorable ( ValueOption < ? > option ) { CsvConfiguration conf = new CsvConfiguration ( CsvConfiguration . DEFAULT_CHARSET , headers , trueFormat , falseFormat , dateFormat , dateTimeFormat ) ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; CsvEmitter emitter = new CsvEmitter ( buffer , testName . getMethodName ( ) , conf ) ; try { emit ( emitter , option ) ; emitter . endRecord ( ) ; emitter . close ( ) ; CsvParser parser = new CsvParser ( new ByteArrayInputStream ( buffer . toByteArray ( ) ) , testName . getMethodName ( ) , conf ) ; assertThat ( parser . next ( ) , is ( true ) ) ; ValueOption < ? > copy = option . getClass ( ) . newInstance ( ) ; fill ( parser , copy ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; assertThat ( copy , is ( ( Object ) option ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private < T extends ValueOption < ? > > T fill ( CsvParser parser , T option ) { try { CsvParser . class . getMethod ( "" , option . getClass ( ) ) . invoke ( parser , option ) ; return option ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private < T extends ValueOption < ? > > T emit ( CsvEmitter emitter , T option ) { try { CsvEmitter . class . getMethod ( "" , option . getClass ( ) ) . invoke ( emitter , option ) ; return option ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ Test public void boolean_values ( ) throws Exception { assertRestorable ( new BooleanOption ( true ) ) ; assertRestorable ( new BooleanOption ( false ) ) ; assertRestorable ( new BooleanOption ( ) ) ; trueFormat = "" ; falseFormat = "" ; assertRestorable ( new BooleanOption ( true ) ) ; assertRestorable ( new BooleanOption ( false ) ) ; } @ Test public void byte_values ( ) throws Exception { assertRestorable ( new ByteOption ( ( byte ) ) ) ; assertRestorable ( new ByteOption ( ( byte ) ) ) ; assertRestorable ( new ByteOption ( ( byte ) - ) ) ; assertRestorable ( new ByteOption ( ( byte ) ) ) ; assertRestorable ( new ByteOption ( ( byte ) - ) ) ; assertRestorable ( new ByteOption ( Byte . MAX_VALUE ) ) ; assertRestorable ( new ByteOption ( Byte . MIN_VALUE ) ) ; assertRestorable ( new ByteOption ( ) ) ; } @ Test public void short_values ( ) throws Exception { assertRestorable ( new ShortOption ( ( short ) ) ) ; assertRestorable ( new ShortOption ( ( short ) ) ) ; assertRestorable ( new ShortOption ( ( short ) - ) ) ; assertRestorable ( new ShortOption ( ( short ) ) ) ; assertRestorable ( new ShortOption ( ( short ) - ) ) ; assertRestorable ( new ShortOption ( Short . MAX_VALUE ) ) ; assertRestorable ( new ShortOption ( Short . MIN_VALUE ) ) ; assertRestorable ( new ShortOption ( ) ) ; } @ Test public void int_values ( ) throws Exception { assertRestorable ( new IntOption ( ) ) ; assertRestorable ( new IntOption ( ) ) ; assertRestorable ( new IntOption ( - ) ) ; assertRestorable ( new IntOption ( ) ) ; assertRestorable ( new IntOption ( - ) ) ; assertRestorable ( new IntOption ( Integer . MAX_VALUE ) ) ; assertRestorable ( new IntOption ( Integer . MIN_VALUE ) ) ; assertRestorable ( new IntOption ( ) ) ; } @ Test public void long_vaules ( ) throws Exception { assertRestorable ( new LongOption ( ) ) ; assertRestorable ( new LongOption ( ) ) ; assertRestorable ( new LongOption ( - ) ) ; assertRestorable ( new LongOption ( ) ) ; assertRestorable ( new LongOption ( - ) ) ; assertRestorable ( new LongOption ( Long . MAX_VALUE ) ) ; assertRestorable ( new LongOption ( Long . MIN_VALUE ) ) ; assertRestorable ( new LongOption ( ) ) ; } @ Test public void float_values ( ) throws Exception { assertRestorable ( new FloatOption ( ) ) ; assertRestorable ( new FloatOption ( ) ) ; assertRestorable ( new FloatOption ( - ) ) ; assertRestorable ( new FloatOption ( ) ) ; assertRestorable ( new FloatOption ( - ) ) ; assertRestorable ( new FloatOption ( Float . MAX_VALUE ) ) ; assertRestorable ( new FloatOption ( Float . MIN_VALUE ) ) ; assertRestorable ( new FloatOption ( ) ) ; } @ Test public void double_values ( ) throws Exception { assertRestorable ( new DoubleOption ( ) ) ; assertRestorable ( new DoubleOption ( ) ) ; assertRestorable ( new DoubleOption ( - ) ) ; assertRestorable ( new DoubleOption ( ) ) ; assertRestorable ( new DoubleOption ( - ) ) ; assertRestorable ( new DoubleOption ( Double . MAX_VALUE ) ) ; assertRestorable ( new DoubleOption ( Double . MIN_VALUE ) ) ; assertRestorable ( new DoubleOption ( ) ) ; } @ Test public void decimal_values ( ) throws Exception { assertRestorable ( new DecimalOption ( decimal ( "" ) ) ) ; assertRestorable ( new DecimalOption ( decimal ( "" ) ) ) ; assertRestorable ( new DecimalOption ( decimal ( "" ) ) ) ; assertRestorable ( new DecimalOption ( decimal ( "" ) ) ) ; assertRestorable ( new DecimalOption ( decimal ( "" ) ) ) ; assertRestorable ( new DecimalOption ( decimal ( "" ) ) ) ; assertRestorable ( new DecimalOption ( decimal ( "" ) ) ) ; assertRestorable ( new DecimalOption ( decimal ( "" ) ) ) ; assertRestorable ( new DecimalOption ( ) ) ; } private BigDecimal decimal ( String string ) { return new BigDecimal ( string ) ; } @ Test public void text_values ( ) throws Exception { assertRestorable ( new StringOption ( "" ) ) ; assertRestorable ( new StringOption ( "" ) ) ; assertRestorable ( new StringOption ( "" ) ) ; assertRestorable ( new StringOption ( ) ) ; } @ Test public void date_values ( ) throws Exception { assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; assertRestorable ( new DateOption ( ) ) ; dateFormat = "" ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; dateFormat = "" ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; dateFormat = "" ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; dateFormat = "" ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; } @ Test public void date_values_direct ( ) throws Exception { dateFormat = "" ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; assertRestorable ( new DateOption ( new Date ( , , ) ) ) ; assertRestorable ( new DateOption ( ) ) ; } @ Test public void datetime_values ( ) throws Exception { assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertRestorable ( new DateTimeOption ( ) ) ; dateTimeFormat = "" ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; dateTimeFormat = "" ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; dateTimeFormat = "" ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; dateTimeFormat = "" ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; } @ Test public void datetime_values_direct ( ) throws Exception { dateTimeFormat = "" ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertRestorable ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertRestorable ( new DateTimeOption ( ) ) ; } @ Test public void multi_cells ( ) throws Exception { CsvEmitter emitter = createEmitter ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . close ( ) ; CsvParser parser = createParser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; parser . close ( ) ; } @ Test public void multi_records ( ) throws Exception { CsvEmitter emitter = createEmitter ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . close ( ) ; CsvParser parser = createParser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; parser . close ( ) ; } @ Test public void matrix ( ) throws Exception { CsvEmitter emitter = createEmitter ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . close ( ) ; CsvParser parser = createParser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; parser . close ( ) ; } @ Test public void with_header ( ) throws Exception { headers = Arrays . asList ( "" , "" ) ; CsvEmitter emitter = createEmitter ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . close ( ) ; headers = Arrays . asList ( ) ; CsvParser parser = createParser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; parser . close ( ) ; } @ Test public void with_malformed_header ( ) throws Exception { headers = Arrays . asList ( "" , "" ) ; CsvEmitter emitter = createEmitter ( ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . emit ( new StringOption ( "" ) ) ; emitter . endRecord ( ) ; emitter . close ( ) ; headers = Arrays . asList ( ) ; CsvParser parser = createParser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; parser . close ( ) ; } @ Test public void empty_with_header ( ) throws Exception { headers = Arrays . asList ( "" , "" ) ; CsvEmitter emitter = createEmitter ( ) ; emitter . close ( ) ; headers = Arrays . asList ( ) ; CsvParser parser = createParser ( ) ; assertThat ( parser . next ( ) , is ( true ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; assertThat ( fill ( parser , new StringOption ( ) ) , is ( new StringOption ( "" ) ) ) ; parser . endRecord ( ) ; assertThat ( parser . next ( ) , is ( false ) ) ; parser . close ( ) ; } } package com . asakusafw . runtime . report ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . runtime . core . Report ; public class CommonsLoggingReportTest { @ Before public void setUp ( ) throws Exception { Report . setDelegate ( new CommonsLoggingReport ( ) ) ; } @ After public void tearDown ( ) throws Exception { Report . setDelegate ( null ) ; } @ Test public void report ( ) { Report . info ( "" ) ; Report . warn ( "" ) ; Report . error ( "" ) ; } } package com . asakusafw . runtime . stage . directio ; import static com . asakusafw . runtime . stage . directio . StringTemplate . Format . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import com . asakusafw . runtime . io . util . WritableRawComparable ; import com . asakusafw . runtime . stage . directio . StringTemplate . Format ; import com . asakusafw . runtime . stage . directio . StringTemplate . FormatSpec ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; public class StringTemplateTest { @ Test public void plain ( ) throws Exception { Mock mock = new Mock ( plain ( "" ) ) ; assertThat ( mock . apply ( ) , is ( "" ) ) ; } @ Test public void placeholder ( ) throws Exception { Mock mock = new Mock ( spec ( NATURAL ) ) ; mock . setMock ( "" ) ; assertThat ( mock . apply ( ) , is ( "" ) ) ; } @ Test public void placeholder_date ( ) throws Exception { Mock mock = new Mock ( spec ( DATE , "" ) ) ; mock . setMock ( new DateOption ( new Date ( , , ) ) ) ; assertThat ( mock . apply ( ) , is ( "" ) ) ; } @ Test public void placeholder_date_null ( ) throws Exception { Mock mock = new Mock ( spec ( DATE , "" ) ) ; mock . setMock ( new DateOption ( ) ) ; mock . apply ( ) ; } @ Test public void placeholder_datetime ( ) throws Exception { Mock mock = new Mock ( spec ( DATETIME , "" ) ) ; mock . setMock ( new DateTimeOption ( new DateTime ( , , , , , ) ) ) ; assertThat ( mock . apply ( ) , is ( "" ) ) ; } @ Test public void placeholder_datetime_null ( ) throws Exception { Mock mock = new Mock ( spec ( DATETIME , "" ) ) ; mock . setMock ( new DateTimeOption ( ) ) ; mock . apply ( ) ; } @ Test public void mixed ( ) throws Exception { Mock mock = new Mock ( plain ( "" ) , spec ( NATURAL ) , plain ( "" ) ) ; mock . setMock ( "" , "" , "" ) ; assertThat ( mock . apply ( ) , is ( "" ) ) ; } @ Test public void serialize ( ) throws Exception { Mock mock = new Mock ( plain ( "" ) , spec ( NATURAL ) , plain ( "" ) , spec ( DATE , "" ) ) ; mock . setMock ( "" , "" , "" , new DateOption ( new Date ( , , ) ) ) ; byte [ ] s0 = ser ( mock ) ; Mock r0 = new Mock ( plain ( "" ) , spec ( NATURAL ) , plain ( "" ) , spec ( DATE , "" ) ) ; des ( r0 , s0 ) ; assertThat ( r0 . apply ( ) , is ( "" ) ) ; mock . setMock ( "" , "" , "" ) ; byte [ ] s2 = ser ( mock ) ; Mock r2 = new Mock ( plain ( "" ) , spec ( NATURAL ) , plain ( "" ) , spec ( DATE , "" ) ) ; des ( r2 , s2 ) ; assertThat ( s0 , is ( s2 ) ) ; } @ Test public void compare ( ) throws Exception { Mock a = new Mock ( plain ( "" ) , spec ( NATURAL ) , plain ( "" ) , spec ( DATE , "" ) ) ; a . setMock ( "" , "" , "" , new DateOption ( new Date ( , , ) ) ) ; Mock b = new Mock ( plain ( "" ) , spec ( NATURAL ) , plain ( "" ) , spec ( DATE , "" ) ) ; b . setMock ( "" , "" , "" , new DateOption ( new Date ( , , ) ) ) ; Mock c = new Mock ( plain ( "" ) , spec ( NATURAL ) , plain ( "" ) , spec ( DATE , "" ) ) ; c . setMock ( "" , "" , "" , new DateOption ( new Date ( , , ) ) ) ; Mock d = new Mock ( plain ( "" ) , spec ( NATURAL ) , plain ( "" ) , spec ( DATE , "" ) ) ; d . setMock ( "" , "" , "" , new DateOption ( new Date ( , , ) ) ) ; assertThat ( cmp ( a , b ) , is ( not ( ) ) ) ; assertThat ( cmp ( b , c ) , is ( not ( ) ) ) ; assertThat ( cmp ( a , d ) , is ( equalTo ( ) ) ) ; } private FormatSpec plain ( String string ) { return spec ( Format . PLAIN , string ) ; } private FormatSpec spec ( Format format ) { return spec ( format , null ) ; } private FormatSpec spec ( Format format , String string ) { return new FormatSpec ( format , string ) ; } static byte [ ] ser ( WritableRawComparable writable ) throws IOException { DataOutputBuffer out = new DataOutputBuffer ( ) ; writable . write ( out ) ; assertThat ( writable . getSizeInBytes ( out . getData ( ) , ) , is ( out . getLength ( ) ) ) ; byte [ ] results = Arrays . copyOfRange ( out . getData ( ) , , out . getLength ( ) ) ; return results ; } static < T extends Writable > T des ( T writable , byte [ ] serialized ) throws IOException { DataInputBuffer buf = new DataInputBuffer ( ) ; buf . reset ( serialized , serialized . length ) ; writable . readFields ( buf ) ; return writable ; } static int cmp ( WritableRawComparable a , WritableRawComparable b ) throws IOException { int cmp = a . compareTo ( b ) ; assertThat ( a . equals ( b ) , is ( cmp == ) ) ; if ( cmp == ) { assertThat ( a . hashCode ( ) , is ( b . hashCode ( ) ) ) ; } byte [ ] serA = ser ( a ) ; byte [ ] serB = ser ( b ) ; int serCmp = a . compareInBytes ( serA , , serB , ) ; assertThat ( serCmp , is ( cmp ) ) ; return cmp ; } private static class Mock extends StringTemplate { Mock ( FormatSpec ... specs ) { super ( specs ) ; } void setMock ( Object ... values ) { set ( values ) ; } @ Override public void set ( Object object ) { Object [ ] values = ( Object [ ] ) object ; for ( int i = ; i < values . length ; i ++ ) { setProperty ( i , values [ i ] ) ; } } } } package com . asakusafw . runtime . stage . collector ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import com . asakusafw . runtime . value . IntOption ; public class WritableSlotTest { @ SuppressWarnings ( "" ) @ Test public void loadStore ( ) throws Exception { WritableSlot slot = new WritableSlot ( ) ; IntOption value = new IntOption ( ) ; IntOption copy = new IntOption ( ) ; slot . store ( value ) ; slot . loadTo ( copy ) ; assertThat ( copy , is ( value ) ) ; value . modify ( ) ; slot . store ( value ) ; slot . loadTo ( copy ) ; assertThat ( copy , is ( value ) ) ; } @ SuppressWarnings ( "" ) @ Test public void writable ( ) throws Exception { WritableSlot slot = new WritableSlot ( ) ; IntOption value = new IntOption ( ) ; IntOption copy = new IntOption ( ) ; slot . store ( value ) ; WritableSlot restored1 = restore ( slot ) ; restored1 . loadTo ( copy ) ; assertThat ( copy , is ( value ) ) ; value . modify ( ) ; slot . store ( value ) ; WritableSlot restored2 = restore ( slot ) ; restored2 . loadTo ( copy ) ; assertThat ( copy , is ( value ) ) ; } @ SuppressWarnings ( "" ) private static < T extends Writable > T restore ( T writable ) { try { return read ( ( T ) writable . getClass ( ) . newInstance ( ) , write ( writable ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } static byte [ ] write ( Writable writable ) { DataOutputBuffer buffer = new DataOutputBuffer ( ) ; buffer . reset ( ) ; try { writable . write ( buffer ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } return Arrays . copyOf ( buffer . getData ( ) , buffer . getLength ( ) ) ; } static < T extends Writable > T read ( T writable , byte [ ] bytes ) { DataInputBuffer buffer = new DataInputBuffer ( ) ; buffer . reset ( bytes , bytes . length ) ; try { writable . readFields ( buffer ) ; assertThat ( "" , buffer . read ( ) , is ( - ) ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } return writable ; } } package com . asakusafw . runtime . stage . collector ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . apache . hadoop . io . RawComparator ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import com . asakusafw . runtime . value . IntOption ; public class SortableSlotTest { @ Test public void begin ( ) { SortableSlot slot = new SortableSlot ( ) ; slot . begin ( ) ; assertThat ( slot . getSlot ( ) , is ( ) ) ; SortableSlot other = new SortableSlot ( ) ; other . begin ( ) ; assertThat ( slot , is ( not ( other ) ) ) ; } @ Test public void addByte ( ) throws Exception { Map < String , SortableSlot > slots = new HashMap < String , SortableSlot > ( ) ; slots . put ( "" , createWithByte ( Byte . MIN_VALUE ) ) ; slots . put ( "" , createWithByte ( Byte . MIN_VALUE / ) ) ; slots . put ( "" , createWithByte ( - ) ) ; slots . put ( "" , createWithByte ( ) ) ; slots . put ( "" , createWithByte ( ) ) ; slots . put ( "" , createWithByte ( Byte . MAX_VALUE / ) ) ; slots . put ( "" , createWithByte ( Byte . MAX_VALUE ) ) ; slots . put ( "" , createWithByte ( ) ) ; slots . get ( "" ) . addByte ( - ) ; slots . put ( "" , createWithByte ( ) ) ; slots . get ( "" ) . addByte ( - ) ; slots . put ( "" , createWithByte ( ) ) ; slots . get ( "" ) . addByte ( - ) ; List < SortableSlot > copy = new ArrayList < SortableSlot > ( slots . values ( ) ) ; Collections . sort ( copy ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; } private SortableSlot createWithByte ( int value ) throws IOException { SortableSlot slot = new SortableSlot ( ) ; slot . begin ( ) ; slot . addByte ( value - Byte . MIN_VALUE ) ; return slot ; } @ Test public void addRandom ( ) throws Exception { SortableSlot slot = new SortableSlot ( ) ; slot . begin ( ) ; slot . addRandom ( ) ; int same = ; for ( int i = ; i < ; i ++ ) { SortableSlot random = new SortableSlot ( ) ; random . begin ( ) ; random . addRandom ( ) ; if ( slot . equals ( random ) ) { same ++ ; } } assertThat ( same , lessThan ( ) ) ; } @ Test public void add ( ) throws Exception { Map < String , SortableSlot > slots = new HashMap < String , SortableSlot > ( ) ; slots . put ( "" , createWithInt ( ) ) ; slots . put ( "" , createWithInt ( - ) ) ; slots . put ( "" , createWithInt ( ) ) ; slots . put ( "" , createWithInt ( Integer . MIN_VALUE ) ) ; slots . put ( "" , createWithInt ( Integer . MAX_VALUE ) ) ; slots . put ( "" , createWithInt ( null ) ) ; slots . put ( "" , createWithInt ( ) ) ; slots . get ( "" ) . add ( new IntOption ( ) ) ; List < SortableSlot > copy = new ArrayList < SortableSlot > ( slots . values ( ) ) ; Collections . sort ( copy ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; assertThat ( copy . get ( ) , is ( slots . get ( "" ) ) ) ; } private SortableSlot createWithInt ( Integer value ) throws IOException { SortableSlot slot = new SortableSlot ( ) ; slot . begin ( ) ; IntOption option ; if ( value == null ) { option = new IntOption ( ) ; } else { option = new IntOption ( value ) ; } slot . add ( option ) ; return slot ; } @ Test public void writable ( ) throws Exception { SortableSlot slot = new SortableSlot ( ) ; slot . begin ( ) ; slot . addByte ( ) ; SortableSlot s1 = read ( new SortableSlot ( ) , write ( slot ) ) ; slot . begin ( ) ; slot . addByte ( ) ; SortableSlot s2 = read ( new SortableSlot ( ) , write ( slot ) ) ; SortableSlot a1 = new SortableSlot ( ) ; a1 . begin ( ) ; a1 . addByte ( ) ; SortableSlot a2 = new SortableSlot ( ) ; a2 . begin ( ) ; a2 . addByte ( ) ; assertThat ( s1 , is ( a1 ) ) ; assertThat ( s2 , is ( a2 ) ) ; } @ SuppressWarnings ( "" ) @ Test public void comparator ( ) throws Exception { LinkedList < SortableSlot > slots = new LinkedList < SortableSlot > ( ) ; slots . add ( createWithByte ( Byte . MIN_VALUE ) ) ; slots . add ( createWithByte ( Byte . MIN_VALUE / ) ) ; slots . add ( createWithByte ( - ) ) ; slots . add ( createWithByte ( ) ) ; slots . add ( createWithByte ( ) ) ; slots . add ( createWithByte ( Byte . MAX_VALUE / ) ) ; slots . add ( createWithByte ( Byte . MAX_VALUE ) ) ; slots . add ( createWithByte ( ) ) ; slots . getLast ( ) . addByte ( - ) ; slots . add ( createWithByte ( ) ) ; slots . getLast ( ) . addByte ( ) ; slots . add ( createWithByte ( ) ) ; slots . getLast ( ) . addByte ( ) ; LinkedList < SortableSlot > copy = new LinkedList < SortableSlot > ( slots ) ; Collections . sort ( slots , new SortableSlot . Comparator ( ) ) ; Collections . sort ( copy , new BinaryComparator ( new SortableSlot . Comparator ( ) ) ) ; assertThat ( copy , is ( slots ) ) ; } @ Test public void partitioner ( ) throws Exception { final int partitions = ; final int records = ; SortableSlot . Partitioner partitioner = new SortableSlot . Partitioner ( ) ; List < List < SortableSlot > > slotsParts = new ArrayList < List < SortableSlot > > ( ) ; for ( int i = ; i < partitions ; i ++ ) { slotsParts . add ( new ArrayList < SortableSlot > ( ) ) ; } int lastPartition = - ; int partitionChanged = - ; int [ ] partitionMemberCount = new int [ partitions ] ; for ( int i = ; i < partitions ; i ++ ) { for ( int j = ; j < records ; j ++ ) { SortableSlot slot = new SortableSlot ( ) ; slot . begin ( i ) ; slot . add ( new IntOption ( j ) ) ; int partition = partitioner . getPartition ( slot , null , partitions ) ; partitionMemberCount [ partition ] ++ ; if ( lastPartition != partition ) { partitionChanged ++ ; } lastPartition = partition ; } } int max = - ; for ( int memberCount : partitionMemberCount ) { max = Math . max ( max , memberCount ) ; } assertThat ( "" + Arrays . toString ( partitionMemberCount ) , ( double ) max / records , lessThan ( ) ) ; double sequencialReadAve = records * partitions / partitionChanged ; assertThat ( "" , sequencialReadAve , greaterThan ( ) ) ; assertThat ( "" , sequencialReadAve , lessThan ( ) ) ; } static byte [ ] write ( Writable writable ) { DataOutputBuffer buffer = new DataOutputBuffer ( ) ; buffer . reset ( ) ; try { writable . write ( buffer ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } return Arrays . copyOf ( buffer . getData ( ) , buffer . getLength ( ) ) ; } static < T extends Writable > T read ( T writable , byte [ ] bytes ) { DataInputBuffer buffer = new DataInputBuffer ( ) ; buffer . reset ( bytes , bytes . length ) ; try { writable . readFields ( buffer ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } return writable ; } static class BinaryComparator implements Comparator < Writable > { private RawComparator < ? > comparator ; BinaryComparator ( RawComparator < ? > comparator ) { this . comparator = comparator ; } @ Override public int compare ( Writable o1 , Writable o2 ) { byte [ ] b1 = write ( o1 ) ; byte [ ] b2 = write ( o2 ) ; return comparator . compare ( b1 , , b1 . length , b2 , , b2 . length ) ; } } } package com . asakusafw . runtime . stage . input ; import java . io . IOException ; import org . apache . hadoop . mapreduce . InputSplit ; public class MockInputSplit extends InputSplit { final int tag ; private final long length ; private final String [ ] locations ; MockInputSplit ( int tag , long length , String ... locations ) { this . tag = tag ; this . length = length ; this . locations = locations ; } @ Override public long getLength ( ) throws IOException , InterruptedException { return length ; } @ Override public String [ ] getLocations ( ) throws IOException , InterruptedException { return locations ; } } package com . asakusafw . runtime . stage . input ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . TreeSet ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . InputSplit ; import org . apache . hadoop . mapreduce . JobContext ; import org . apache . hadoop . mapreduce . Mapper ; import org . apache . hadoop . mapreduce . RecordReader ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Test ; import com . asakusafw . runtime . stage . input . StageInputSplit . Source ; public class DefaultSplitCombinerTest { @ Test public void simple ( ) throws Exception { DefaultSplitCombiner combiner = new DefaultSplitCombiner ( ) ; List < StageInputSplit > combined = combine ( combiner , , list ( split ( , , "" ) ) ) ; assertThat ( combined . size ( ) , is ( ) ) ; assertSan ( combined ) ; } @ Test public void single_slot ( ) throws Exception { DefaultSplitCombiner combiner = new DefaultSplitCombiner ( ) ; List < StageInputSplit > combined = combine ( combiner , , list ( split ( , , "" ) , split ( , , "" ) ) ) ; assertThat ( combined . get ( ) . getLocations ( ) , is ( locations ( "" , "" ) ) ) ; assertThat ( combined . size ( ) , is ( ) ) ; assertSan ( combined ) ; } @ Test public void over_slot ( ) throws Exception { DefaultSplitCombiner combiner = new DefaultSplitCombiner ( ) ; List < StageInputSplit > combined = combine ( combiner , , list ( split ( , , "" ) , split ( , , "" ) ) ) ; assertThat ( combined . size ( ) , is ( ) ) ; assertSan ( combined ) ; } @ Test public void ga_simple ( ) throws Exception { DefaultSplitCombiner combiner = new DefaultSplitCombiner ( ) ; List < StageInputSplit > combined = combine ( combiner , , list ( split ( , , "" ) , split ( , , "" ) , split ( , , "" ) , split ( , , "" ) ) ) ; assertThat ( combined . size ( ) , is ( ) ) ; assertSan ( combined ) ; StageInputSplit tag1 = find ( combined , ) ; assertTags ( tag1 , , ) ; StageInputSplit tag3 = find ( combined , ) ; assertTags ( tag3 , , ) ; } @ Test public void ga_nolocation ( ) throws Exception { DefaultSplitCombiner combiner = new DefaultSplitCombiner ( ) ; List < StageInputSplit > combined = combine ( combiner , , list ( split ( , , ( String [ ] ) null ) , split ( , , ( String [ ] ) null ) , split ( , , ( String [ ] ) null ) , split ( , , ( String [ ] ) null ) ) ) ; assertThat ( combined . size ( ) , is ( ) ) ; assertSan ( combined ) ; StageInputSplit tag1 = find ( combined , ) ; assertTags ( tag1 , , , ) ; StageInputSplit tag4 = find ( combined , ) ; assertTags ( tag4 , ) ; } @ Test public void ga_minimize ( ) throws Exception { DefaultSplitCombiner combiner = new DefaultSplitCombiner ( ) ; List < StageInputSplit > combined = combine ( combiner , , list ( split ( , , "" ) , split ( , , "" ) , split ( , , "" ) , split ( , , "" ) ) ) ; assertThat ( combined . size ( ) , is ( ) ) ; assertSan ( combined ) ; assertThat ( combined . get ( ) . getSources ( ) . size ( ) , is ( ) ) ; assertThat ( combined . get ( ) . getSources ( ) . size ( ) , is ( ) ) ; } @ Test public void ga_locality ( ) throws Exception { DefaultSplitCombiner combiner = new DefaultSplitCombiner ( ) ; List < StageInputSplit > combined = combine ( combiner , , list ( split ( , , "" ) , split ( , , "" ) , split ( , , "" ) , split ( , , "" ) ) ) ; assertThat ( combined . size ( ) , is ( ) ) ; assertSan ( combined ) ; assertThat ( find ( combined , ) , is ( not ( find ( combined , ) ) ) ) ; } @ Test public void ga_many ( ) throws Exception { String [ ] [ ] locations = { { } , { "" , "" } , { } , { "" } , { "" } , { "" } , { "" } , { "" } , { "" } , } ; List < StageInputSplit > splits = new ArrayList < StageInputSplit > ( ) ; long total = ; for ( int i = ; i < ; i ++ ) { long size = i * + ; splits . add ( split ( i , size , locations [ i % locations . length ] ) ) ; total += size ; } DefaultSplitCombiner combiner = new DefaultSplitCombiner ( ) ; for ( int i = ; i <= ; i ++ ) { int slots = i * ; int prefSlots = i * / ; List < StageInputSplit > combined = combine ( combiner , slots , splits ) ; assertThat ( combined . size ( ) , is ( greaterThan ( prefSlots ) ) ) ; assertSan ( combined ) ; long prefMaxSize = total * / prefSlots ; for ( StageInputSplit split : combined ) { assertThat ( split . getLength ( ) , is ( lessThan ( prefMaxSize ) ) ) ; } } } private List < StageInputSplit > combine ( DefaultSplitCombiner combiner , int slots , List < StageInputSplit > splits ) throws IOException , InterruptedException { return combiner . combine ( slots , DefaultSplitCombiner . DEFAULT_POPULATIONS , DefaultSplitCombiner . DEFAULT_GENERATIONS , DefaultSplitCombiner . DEFAULT_MUTATION_RATIO , splits ) ; } private void assertSan ( List < StageInputSplit > splits ) { Set < Integer > saw = new HashSet < Integer > ( ) ; for ( StageInputSplit stage : splits ) { for ( Source source : stage . getSources ( ) ) { MockInputSplit split = ( MockInputSplit ) source . getSplit ( ) ; assertThat ( saw , not ( hasItem ( split . tag ) ) ) ; saw . add ( split . tag ) ; } } } private StageInputSplit find ( List < StageInputSplit > list , int tag ) { for ( StageInputSplit stage : list ) { for ( Source source : stage . getSources ( ) ) { MockInputSplit mock = ( MockInputSplit ) source . getSplit ( ) ; if ( mock . tag == tag ) { return stage ; } } } throw new AssertionError ( tag ) ; } private void assertTags ( StageInputSplit split , int ... tags ) { Set < Integer > expected = new TreeSet < Integer > ( ) ; for ( int tag : tags ) { expected . add ( tag ) ; } Set < Integer > actual = new TreeSet < Integer > ( ) ; for ( Source source : split . getSources ( ) ) { MockInputSplit mock = ( MockInputSplit ) source . getSplit ( ) ; actual . add ( mock . tag ) ; } assertThat ( actual , is ( expected ) ) ; } private Matcher < String [ ] > locations ( String ... locations ) { final Set < String > set = new TreeSet < String > ( ) ; Collections . addAll ( set , locations ) ; return new BaseMatcher < String [ ] > ( ) { @ Override public boolean matches ( Object arg ) { String [ ] actualArray = ( String [ ] ) arg ; Set < String > actual = new TreeSet < String > ( ) ; if ( actualArray != null ) { Collections . addAll ( actual , actualArray ) ; } return set . equals ( actual ) ; } @ Override public void describeTo ( Description desc ) { desc . appendValue ( set ) ; } } ; } private List < StageInputSplit > list ( StageInputSplit ... splits ) { return Arrays . asList ( splits ) ; } private StageInputSplit split ( int tag , long length , String ... locations ) { Class < ? extends Mapper < ? , ? , ? , ? > > mapper = A . class ; return split ( tag , mapper , length , locations ) ; } private StageInputSplit split ( int tag , Class < ? extends Mapper < ? , ? , ? , ? > > mapper , long length , String ... locations ) { InputSplit split = new MockInputSplit ( tag , length , locations ) ; return new StageInputSplit ( mapper , Collections . singletonList ( new StageInputSplit . Source ( split , F . class ) ) ) ; } private static final class A extends Mapper < Object , Object , Object , Object > { } private static final class F extends InputFormat < Object , Object > { @ Override public List < InputSplit > getSplits ( JobContext context ) { return null ; } @ Override public RecordReader < Object , Object > createRecordReader ( InputSplit split , TaskAttemptContext context ) { return null ; } } } package com . asakusafw . runtime . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . lang . reflect . Type ; import java . util . AbstractCollection ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import java . util . Set ; import org . junit . Test ; public class TypeUtilTest { @ Test public void object ( ) { List < Type > invoked = TypeUtil . invoke ( Object . class , String . class ) ; assertThat ( invoked . size ( ) , is ( ) ) ; } @ Test public void invokeClass ( ) { List < Type > invoked = TypeUtil . invoke ( ArrayList . class , StringList . class ) ; assertThat ( invoked . size ( ) , is ( ) ) ; assertThat ( invoked . get ( ) , is ( ( Type ) String . class ) ) ; } @ Test public void invokeDeepClass ( ) { List < Type > invoked = TypeUtil . invoke ( AbstractCollection . class , StringList . class ) ; assertThat ( invoked . size ( ) , is ( ) ) ; assertThat ( invoked . get ( ) , is ( ( Type ) String . class ) ) ; } @ Test public void invokeInterface ( ) { List < Type > invoked = TypeUtil . invoke ( List . class , StringList . class ) ; assertThat ( invoked . size ( ) , is ( ) ) ; assertThat ( invoked . get ( ) , is ( ( Type ) String . class ) ) ; } @ Test public void invokeDeepInterface ( ) { List < Type > invoked = TypeUtil . invoke ( Collection . class , StringList . class ) ; assertThat ( invoked . size ( ) , is ( ) ) ; assertThat ( invoked . get ( ) , is ( ( Type ) String . class ) ) ; } @ Test public void invokeInterfaceFromInterface ( ) { List < Type > invoked = TypeUtil . invoke ( List . class , IStringList . class ) ; assertThat ( invoked . size ( ) , is ( ) ) ; assertThat ( invoked . get ( ) , is ( ( Type ) String . class ) ) ; } @ Test public void invokeDeepInterfaceFromInterface ( ) { List < Type > invoked = TypeUtil . invoke ( Collection . class , IStringList . class ) ; assertThat ( invoked . size ( ) , is ( ) ) ; assertThat ( invoked . get ( ) , is ( ( Type ) String . class ) ) ; } @ Test public void invokeOrthogonal ( ) { List < Type > invoked = TypeUtil . invoke ( Set . class , IStringList . class ) ; assertThat ( invoked , is ( nullValue ( ) ) ) ; } private static class StringList extends ArrayList < String > { private static final long serialVersionUID = ; } private interface IStringList extends List < String > { } } package com . asakusafw . runtime . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; public class VariableTableTest { @ Test public void raw ( ) { VariableTable parser = new VariableTable ( ) ; assertThat ( parser . parse ( "" ) , is ( "" ) ) ; } @ Test public void single ( ) { VariableTable parser = new VariableTable ( ) ; parser . defineVariable ( "" , "" ) ; assertThat ( parser . parse ( "" ) , is ( "" ) ) ; } @ Test public void multi ( ) { VariableTable parser = new VariableTable ( ) ; parser . defineVariable ( "" , "" ) ; parser . defineVariable ( "" , "" ) ; parser . defineVariable ( "" , "" ) ; assertThat ( parser . parse ( "" ) , is ( "" ) ) ; } @ Test public void list_empty ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; } @ Test public void list_single ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void list_multi ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void list_escaped ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void list_escapeSequenceFragment ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void list_notKeyValue ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void list_redefine ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; } @ Test public void list_emptyKey ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void list_emptyValue ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void list_emptyKeyValue ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariables ( "" ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void toVariable ( ) { String exprHello = VariableTable . toVariable ( "" ) ; VariableTable vars = new VariableTable ( ) ; vars . defineVariable ( "" , "" ) ; assertThat ( vars . parse ( exprHello ) , is ( "" ) ) ; } @ Test public void toSerialString_simple ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariable ( "" , "" ) ; VariableTable copy = new VariableTable ( ) ; copy . defineVariables ( vars . toSerialString ( ) ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void toSerialString_multiple ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariable ( "" , "" ) ; vars . defineVariable ( "" , "" ) ; vars . defineVariable ( "" , "" ) ; VariableTable copy = new VariableTable ( ) ; copy . defineVariables ( vars . toSerialString ( ) ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void toSerialString_escaped ( ) { VariableTable vars = new VariableTable ( ) ; vars . defineVariable ( "" , "" ) ; vars . defineVariable ( "" , "" ) ; vars . defineVariable ( "" , "" ) ; vars . defineVariable ( "" , "" ) ; VariableTable copy = new VariableTable ( ) ; copy . defineVariables ( vars . toSerialString ( ) ) ; assertThat ( vars . getVariables ( ) . size ( ) , is ( ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( vars . getVariables ( ) . get ( "" ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void undefined ( ) { VariableTable parser = new VariableTable ( ) ; parser . defineVariable ( "" , "" ) ; parser . defineVariable ( "" , "" ) ; assertThat ( parser . parse ( "" ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void redefined ( ) { VariableTable parser = new VariableTable ( ) ; parser . defineVariable ( "" , "" ) ; parser . defineVariable ( "" , "" ) ; } } package com . asakusafw . runtime . util . hadoop ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . util . HashMap ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . junit . After ; import org . junit . Assume ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class ConfigurationProviderTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private ClassLoader contextLoader ; private boolean contextLoaderSaved = false ; @ Before public void setUp ( ) throws Exception { this . contextLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; this . contextLoaderSaved = true ; } @ After public void tearDown ( ) throws Exception { if ( contextLoaderSaved ) { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; Thread . currentThread ( ) . setContextClassLoader ( contextLoader ) ; assertThat ( cl , is ( sameInstance ( contextLoader ) ) ) ; } } @ Test public void findHadoopCommand_explicit ( ) { putExec ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ; File file = ConfigurationProvider . findHadoopCommand ( envp ) ; assertThat ( file , is ( notNullValue ( ) ) ) ; assertThat ( file . toString ( ) , file . canExecute ( ) , is ( true ) ) ; } @ Test public void findHadoopCommand_path ( ) { putExec ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; File file = ConfigurationProvider . findHadoopCommand ( envp ) ; assertThat ( file , is ( notNullValue ( ) ) ) ; assertThat ( file . toString ( ) , file . canExecute ( ) , is ( true ) ) ; } @ Test public void findHadoopCommand_both ( ) { putExec ( "" ) ; putExec ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; envp . put ( "" , new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; File file = ConfigurationProvider . findHadoopCommand ( envp ) ; assertThat ( file , is ( notNullValue ( ) ) ) ; assertThat ( file . toString ( ) , file . canExecute ( ) , is ( true ) ) ; assertThat ( file . toString ( ) , file . getParentFile ( ) . getName ( ) , is ( "" ) ) ; } @ Test public void findHadoopCommand_manypath ( ) { putExec ( "" ) ; putExec ( "" ) ; putExec ( "" ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( File . pathSeparator ) ; buf . append ( new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; buf . append ( File . pathSeparator ) ; buf . append ( new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; buf . append ( File . pathSeparator ) ; buf . append ( new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; buf . append ( File . pathSeparator ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , buf . toString ( ) ) ; File file = ConfigurationProvider . findHadoopCommand ( envp ) ; assertThat ( file , is ( notNullValue ( ) ) ) ; assertThat ( file . toString ( ) , file . canExecute ( ) , is ( true ) ) ; assertThat ( file . toString ( ) , file . getParentFile ( ) . getName ( ) , is ( "" ) ) ; } @ Test public void newInstance_explicit ( ) { putConf ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; Configuration conf = new ConfigurationProvider ( envp ) . newInstance ( ) ; assertThat ( isLoaded ( conf ) , is ( true ) ) ; } @ Test public void newInstance_home ( ) { putExec ( "" ) ; create ( "" ) ; putConf ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ; Configuration conf = new ConfigurationProvider ( envp ) . newInstance ( ) ; assertThat ( isLoaded ( conf ) , is ( true ) ) ; } @ Test public void newInstance_home_no_env_sh ( ) { putExec ( "" ) ; putConf ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ; Configuration conf = new ConfigurationProvider ( envp ) . newInstance ( ) ; assertThat ( isLoaded ( conf ) , is ( false ) ) ; } @ Test public void newInstance_home_etc ( ) { putExec ( "" ) ; putConf ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ; Configuration conf = new ConfigurationProvider ( envp ) . newInstance ( ) ; assertThat ( isLoaded ( conf ) , is ( true ) ) ; } @ Test public void newInstance_path ( ) { putExec ( "" ) ; create ( "" ) ; putConf ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; Configuration conf = new ConfigurationProvider ( envp ) . newInstance ( ) ; assertThat ( isLoaded ( conf ) , is ( true ) ) ; } @ Test public void newInstance_path_no_env_sh ( ) { putExec ( "" ) ; putConf ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; Configuration conf = new ConfigurationProvider ( envp ) . newInstance ( ) ; assertThat ( isLoaded ( conf ) , is ( false ) ) ; } @ Test public void newInstance_path_etc ( ) { putExec ( "" ) ; putConf ( "" ) ; Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; Configuration conf = new ConfigurationProvider ( envp ) . newInstance ( ) ; assertThat ( isLoaded ( conf ) , is ( true ) ) ; } @ Test public void symlink ( ) { File cmd = putExec ( "" ) ; putConf ( "" ) ; File path = folder . newFolder ( "" ) ; try { Process proc = new ProcessBuilder ( "" , "" , cmd . getAbsolutePath ( ) , new File ( path , "" ) . getAbsolutePath ( ) ) . start ( ) ; try { int exitCode = proc . waitFor ( ) ; Assume . assumeThat ( exitCode , is ( ) ) ; } finally { proc . destroy ( ) ; } } catch ( Exception e ) { System . out . println ( "" ) ; e . printStackTrace ( System . out ) ; Assume . assumeNoException ( e ) ; } Map < String , String > envp = new HashMap < String , String > ( ) ; envp . put ( "" , path . getAbsolutePath ( ) ) ; Configuration conf = new ConfigurationProvider ( envp ) . newInstance ( ) ; assertThat ( isLoaded ( conf ) , is ( true ) ) ; File file = ConfigurationProvider . findHadoopCommand ( envp ) ; assertThat ( file , is ( notNullValue ( ) ) ) ; assertThat ( file . toString ( ) , file . canExecute ( ) , is ( true ) ) ; assertThat ( file . toString ( ) , file . getParentFile ( ) . getName ( ) , is ( "" ) ) ; } private File putExec ( String path ) { File file = create ( path ) ; file . setExecutable ( true ) ; return file ; } private File create ( String path ) { File file = new File ( folder . getRoot ( ) , path ) ; assertThat ( file . getParentFile ( ) . isDirectory ( ) || file . getParentFile ( ) . mkdirs ( ) , is ( true ) ) ; try { assertThat ( file . createNewFile ( ) , is ( true ) ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } file . setExecutable ( false ) ; return file ; } private void putConf ( String path ) { Configuration c = new Configuration ( false ) ; c . set ( "" , "" ) ; File file = create ( path ) ; try { OutputStream s = new FileOutputStream ( file ) ; try { c . writeXml ( s ) ; } finally { s . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } private boolean isLoaded ( Configuration c ) { return c . get ( "" , "" ) . equals ( "" ) ; } } package com . asakusafw . runtime . core . context ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; public class RuntimeContextTest { @ Rule public final RuntimeContextKeeper keeper = new RuntimeContextKeeper ( ) ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void apply ( ) { RuntimeContext applied = RuntimeContext . DEFAULT . apply ( new HashMap < String , String > ( ) ) ; assertThat ( applied , is ( RuntimeContext . DEFAULT ) ) ; } @ Test public void apply_batchId ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( RuntimeContext . KEY_BATCH_ID , "" ) ; RuntimeContext applied = RuntimeContext . DEFAULT . apply ( map ) ; assertThat ( applied , is ( not ( RuntimeContext . DEFAULT ) ) ) ; assertThat ( applied , is ( RuntimeContext . DEFAULT . batchId ( "" ) ) ) ; } @ Test public void apply_mode_prod ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( RuntimeContext . KEY_EXECUTION_MODE , ExecutionMode . PRODUCTION . getSymbol ( ) ) ; RuntimeContext applied = RuntimeContext . DEFAULT . apply ( map ) ; assertThat ( applied , is ( RuntimeContext . DEFAULT . mode ( ExecutionMode . PRODUCTION ) ) ) ; } @ Test public void apply_mode_sim ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( RuntimeContext . KEY_EXECUTION_MODE , ExecutionMode . SIMULATION . getSymbol ( ) ) ; RuntimeContext applied = RuntimeContext . DEFAULT . apply ( map ) ; assertThat ( applied , is ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ) ; } @ Test public void apply_mode_invalid ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( RuntimeContext . KEY_EXECUTION_MODE , "" ) ; RuntimeContext applied = RuntimeContext . DEFAULT . apply ( map ) ; assertThat ( applied , is ( RuntimeContext . DEFAULT ) ) ; } @ Test public void apply_verificationCode ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( RuntimeContext . KEY_BUILD_ID , "" ) ; RuntimeContext applied = RuntimeContext . DEFAULT . apply ( map ) ; assertThat ( applied , is ( not ( RuntimeContext . DEFAULT ) ) ) ; assertThat ( applied , is ( RuntimeContext . DEFAULT . buildId ( "" ) ) ) ; } @ Test public void unapply_empty ( ) { Map < String , String > map = RuntimeContext . DEFAULT . unapply ( ) ; assertThat ( RuntimeContext . DEFAULT . apply ( map ) , is ( RuntimeContext . DEFAULT ) ) ; } @ Test public void unapply ( ) { RuntimeContext context = RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) . batchId ( "" ) . buildId ( "" ) ; Map < String , String > map = context . unapply ( ) ; assertThat ( RuntimeContext . DEFAULT . apply ( map ) , is ( context ) ) ; } @ Test public void isSimulation_production ( ) { assertThat ( RuntimeContext . DEFAULT . mode ( ExecutionMode . PRODUCTION ) . isSimulation ( ) , is ( false ) ) ; } @ Test public void isSimulation_simulation ( ) { assertThat ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) . isSimulation ( ) , is ( true ) ) ; } @ Test public void canExecute_normal_prod ( ) { RuntimeContext context = RuntimeContext . DEFAULT . mode ( ExecutionMode . PRODUCTION ) ; assertThat ( context . canExecute ( new Object ( ) ) , is ( true ) ) ; } @ Test public void canExecute_supported_prod ( ) { RuntimeContext context = RuntimeContext . DEFAULT . mode ( ExecutionMode . PRODUCTION ) ; assertThat ( context . canExecute ( new SimulatableObject ( ) ) , is ( true ) ) ; } @ Test public void canExecute_normal_sim ( ) { RuntimeContext context = RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ; assertThat ( context . canExecute ( new Object ( ) ) , is ( false ) ) ; } @ Test public void canExecute_supported_sim ( ) { RuntimeContext context = RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ; assertThat ( context . canExecute ( new SimulatableObject ( ) ) , is ( true ) ) ; } @ Test public void verifyApplication_ok ( ) { RuntimeContext context = RuntimeContext . DEFAULT . batchId ( "" ) . buildId ( "" ) ; ClassLoader loader = loader ( "" , "" , RuntimeContext . getRuntimeVersion ( ) ) ; context . verifyApplication ( loader ) ; } @ Test ( expected = InconsistentApplicationException . class ) public void verifyApplication_build_fail ( ) { RuntimeContext context = RuntimeContext . DEFAULT . batchId ( "" ) . buildId ( "" ) ; ClassLoader loader = loader ( "" , "" , RuntimeContext . getRuntimeVersion ( ) ) ; context . verifyApplication ( loader ) ; } @ Test ( expected = InconsistentApplicationException . class ) public void verifyApplication_runtime_fail ( ) { RuntimeContext context = RuntimeContext . DEFAULT . batchId ( "" ) . buildId ( "" ) ; ClassLoader loader = loader ( "" , "" , "" ) ; context . verifyApplication ( loader ) ; } @ Test public void verifyApplication_orthogonal ( ) { RuntimeContext context = RuntimeContext . DEFAULT . batchId ( "" ) . buildId ( "" ) ; ClassLoader loader = loader ( "" , "" , RuntimeContext . getRuntimeVersion ( ) ) ; context . verifyApplication ( loader ) ; } @ Test public void global ( ) { assertThat ( RuntimeContext . get ( ) , is ( RuntimeContext . DEFAULT ) ) ; RuntimeContext context = RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) . batchId ( "" ) . buildId ( "" ) ; RuntimeContext . set ( context ) ; assertThat ( RuntimeContext . get ( ) , is ( context ) ) ; } private ClassLoader loader ( String batchId , String buildId , String rtVersion ) { File file = new File ( folder . getRoot ( ) , RuntimeContext . PATH_APPLICATION_INFO ) ; assertThat ( file . getParentFile ( ) . mkdirs ( ) , is ( true ) ) ; Properties p = new Properties ( ) ; p . setProperty ( RuntimeContext . KEY_BATCH_ID , batchId ) ; p . setProperty ( RuntimeContext . KEY_BUILD_ID , buildId ) ; p . setProperty ( RuntimeContext . KEY_RUNTIME_VERSION , rtVersion ) ; try { OutputStream s = new FileOutputStream ( file ) ; try { p . store ( s , "" ) ; } finally { s . close ( ) ; } return new URLClassLoader ( new URL [ ] { folder . getRoot ( ) . toURI ( ) . toURL ( ) , } ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } @ SimulationSupport private static class SimulatableObject { public SimulatableObject ( ) { return ; } } } package com . asakusafw . runtime . core . context ; import org . junit . rules . ExternalResource ; public class RuntimeContextKeeper extends ExternalResource { private RuntimeContext context ; @ Override protected void before ( ) throws Throwable { context = RuntimeContext . get ( ) ; } @ Override protected void after ( ) { if ( context != null ) { RuntimeContext . set ( context ) ; } } } package com . asakusafw . runtime . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . runtime . core . Report . Level ; public class ReportTest { @ Before public void setUp ( ) throws Exception { Report . setDelegate ( null ) ; Mock . levels . clear ( ) ; Mock . messages . clear ( ) ; } @ Test ( expected = Report . FailedException . class ) public void noDelegate ( ) { Report . info ( "" ) ; } @ Test public void info ( ) { Report . setDelegate ( new Mock ( ) ) ; Report . info ( "" ) ; assertThat ( Mock . levels , is ( list ( Level . INFO ) ) ) ; assertThat ( Mock . messages , is ( list ( "" ) ) ) ; } @ Test ( expected = Report . FailedException . class ) public void info_error ( ) { Report . setDelegate ( new Report . Delegate ( ) { @ Override protected void report ( Level level , String message ) throws IOException { throw new IOException ( ) ; } } ) ; Report . info ( "" ) ; } @ Test public void warn ( ) { Report . setDelegate ( new Mock ( ) ) ; Report . warn ( "" ) ; assertThat ( Mock . levels , is ( list ( Level . WARN ) ) ) ; assertThat ( Mock . messages , is ( list ( "" ) ) ) ; } @ Test ( expected = Report . FailedException . class ) public void warn_error ( ) { Report . setDelegate ( new Report . Delegate ( ) { @ Override protected void report ( Level level , String message ) throws IOException { throw new IOException ( ) ; } } ) ; Report . warn ( "" ) ; } @ Test public void testError ( ) { Report . setDelegate ( new Mock ( ) ) ; Report . error ( "" ) ; assertThat ( Mock . levels , is ( list ( Level . ERROR ) ) ) ; assertThat ( Mock . messages , is ( list ( "" ) ) ) ; } @ Test ( expected = Report . FailedException . class ) public void error_error ( ) { Report . setDelegate ( new Report . Delegate ( ) { @ Override protected void report ( Level level , String message ) throws IOException { throw new IOException ( ) ; } } ) ; Report . error ( "" ) ; } @ Test public void initialize ( ) throws Exception { ResourceConfiguration conf = new HadoopConfiguration ( ) ; conf . set ( Report . K_DELEGATE_CLASS , Mock . class . getName ( ) ) ; Report . Initializer init = new Report . Initializer ( ) ; init . setup ( conf ) ; Report . info ( "" ) ; init . cleanup ( conf ) ; assertThat ( Mock . levels , is ( list ( Level . INFO ) ) ) ; assertThat ( Mock . messages , is ( list ( "" ) ) ) ; } private < T > List < T > list ( T ... values ) { return Arrays . asList ( values ) ; } public static class Mock extends Report . Delegate { static final List < Level > levels = new ArrayList < Level > ( ) ; static final List < String > messages = new ArrayList < String > ( ) ; @ Override protected void report ( Level level , String message ) throws IOException { levels . add ( level ) ; messages . add ( message ) ; } } } package com . asakusafw . runtime . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import java . util . List ; import java . util . concurrent . atomic . AtomicInteger ; import org . apache . hadoop . conf . Configuration ; import org . junit . Test ; import com . asakusafw . runtime . core . Report ; import com . asakusafw . runtime . core . ResourceConfiguration ; import com . asakusafw . runtime . core . RuntimeResource ; public class RuntimeResourceManagerTest { @ Test public void load ( ) throws Exception { Configuration conf = new Configuration ( ) ; RuntimeResourceManager manager = new RuntimeResourceManager ( conf ) ; List < RuntimeResource > loaded = manager . load ( ) ; boolean found = false ; for ( RuntimeResource resource : loaded ) { if ( resource instanceof Report . Initializer ) { found = true ; break ; } } assertThat ( found , is ( true ) ) ; } @ Test public void setup ( ) throws Exception { final AtomicInteger passed = new AtomicInteger ( ) ; Configuration conf = new Configuration ( ) ; conf . set ( "" , "" ) ; RuntimeResourceManager manager = new RuntimeResourceManager ( conf ) { @ Override protected List < RuntimeResource > load ( ) throws IOException { return Arrays . < RuntimeResource > asList ( new Adapter ( ) { @ Override public void setup ( ResourceConfiguration configuration ) { passed . incrementAndGet ( ) ; assertThat ( configuration . get ( "" , null ) , is ( "" ) ) ; } } ) ; } } ; manager . setup ( ) ; assertThat ( passed . get ( ) , is ( ) ) ; } @ Test ( expected = IOException . class ) public void setup_exception ( ) throws Exception { Configuration conf = new Configuration ( ) ; RuntimeResourceManager manager = new RuntimeResourceManager ( conf ) { @ Override protected List < RuntimeResource > load ( ) throws IOException { return Arrays . < RuntimeResource > asList ( new Adapter ( ) { @ Override public void setup ( ResourceConfiguration configuration ) throws IOException { throw new IOException ( ) ; } } ) ; } } ; manager . setup ( ) ; } @ Test public void setup_multi ( ) throws Exception { final AtomicInteger passed = new AtomicInteger ( ) ; Configuration conf = new Configuration ( ) ; conf . set ( "" , "" ) ; RuntimeResourceManager manager = new RuntimeResourceManager ( conf ) { @ Override protected List < RuntimeResource > load ( ) throws IOException { RuntimeResource adapter = new Adapter ( ) { @ Override public void setup ( ResourceConfiguration configuration ) { passed . addAndGet ( ) ; assertThat ( configuration . get ( "" , null ) , is ( "" ) ) ; } } ; return Arrays . asList ( adapter , adapter , adapter ) ; } } ; manager . setup ( ) ; assertThat ( passed . get ( ) , is ( ) ) ; } @ Test public void cleanup ( ) throws Exception { final AtomicInteger passed = new AtomicInteger ( ) ; Configuration conf = new Configuration ( ) ; conf . set ( "" , "" ) ; RuntimeResourceManager manager = new RuntimeResourceManager ( conf ) { @ Override protected List < RuntimeResource > load ( ) throws IOException { return Arrays . < RuntimeResource > asList ( new Adapter ( ) { @ Override public void cleanup ( ResourceConfiguration configuration ) { passed . incrementAndGet ( ) ; assertThat ( configuration . get ( "" , null ) , is ( "" ) ) ; } } ) ; } } ; manager . setup ( ) ; assertThat ( passed . get ( ) , is ( ) ) ; manager . cleanup ( ) ; assertThat ( passed . get ( ) , is ( ) ) ; } @ Test ( expected = IOException . class ) public void cleanup_exception ( ) throws Exception { Configuration conf = new Configuration ( ) ; RuntimeResourceManager manager = new RuntimeResourceManager ( conf ) { @ Override protected List < RuntimeResource > load ( ) throws IOException { return Arrays . < RuntimeResource > asList ( new Adapter ( ) { @ Override public void cleanup ( ResourceConfiguration configuration ) throws IOException { throw new IOException ( ) ; } } ) ; } } ; manager . setup ( ) ; manager . cleanup ( ) ; } @ Test public void cleanup_multi ( ) throws Exception { final AtomicInteger passed = new AtomicInteger ( ) ; Configuration conf = new Configuration ( ) ; conf . set ( "" , "" ) ; RuntimeResourceManager manager = new RuntimeResourceManager ( conf ) { @ Override protected List < RuntimeResource > load ( ) throws IOException { RuntimeResource adapter = new Adapter ( ) { @ Override public void cleanup ( ResourceConfiguration configuration ) { passed . addAndGet ( ) ; assertThat ( configuration . get ( "" , null ) , is ( "" ) ) ; } } ; return Arrays . asList ( adapter , adapter , adapter ) ; } } ; manager . setup ( ) ; manager . cleanup ( ) ; assertThat ( passed . get ( ) , is ( ) ) ; } @ Test public void partial_setup_cleanup ( ) throws Exception { final AtomicInteger passed = new AtomicInteger ( ) ; Configuration conf = new Configuration ( ) ; RuntimeResourceManager manager = new RuntimeResourceManager ( conf ) { @ Override protected List < RuntimeResource > load ( ) throws IOException { RuntimeResource adapter = new Adapter ( ) { @ Override public void setup ( ResourceConfiguration configuration ) throws IOException { if ( passed . get ( ) >= ) { throw new IOException ( ) ; } passed . addAndGet ( ) ; } @ Override public void cleanup ( ResourceConfiguration configuration ) { passed . addAndGet ( - ) ; } } ; return Arrays . asList ( adapter , adapter , adapter , adapter , adapter ) ; } } ; try { manager . setup ( ) ; fail ( ) ; } catch ( IOException e ) { } assertThat ( "" , passed . get ( ) , is ( ) ) ; manager . cleanup ( ) ; assertThat ( "" , passed . get ( ) , is ( ) ) ; } static class Adapter implements RuntimeResource { @ Override public void setup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { return ; } @ Override public void cleanup ( ResourceConfiguration configuration ) throws IOException , InterruptedException { return ; } } } package com . asakusafw . runtime . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import com . asakusafw . runtime . model . DataModel ; public class FileMapListBufferTest { @ Test public void createEmpty ( ) { FileMapListBuffer < Holder > buf = new FileMapListBuffer < Holder > ( ) ; buf . begin ( ) ; buf . end ( ) ; assertThat ( buf . size ( ) , is ( ) ) ; buf . shrink ( ) ; } @ Test public void createSingle ( ) { FileMapListBuffer < Holder > buf = new FileMapListBuffer < Holder > ( ) ; buf . begin ( ) ; assertThat ( buf . isExpandRequired ( ) , is ( true ) ) ; buf . expand ( new Holder ( "" ) ) ; assertThat ( buf . isExpandRequired ( ) , is ( false ) ) ; buf . advance ( ) . value = "" ; buf . end ( ) ; assertThat ( buf . size ( ) , is ( ) ) ; assertThat ( buf . get ( ) , is ( new Holder ( "" ) ) ) ; buf . shrink ( ) ; } @ Test public void reuse ( ) { FileMapListBuffer < Holder > buf = new FileMapListBuffer < Holder > ( ) ; buf . begin ( ) ; assertThat ( buf . isExpandRequired ( ) , is ( true ) ) ; buf . expand ( new Holder ( "" ) ) ; buf . advance ( ) . value = "" ; buf . end ( ) ; buf . shrink ( ) ; buf . begin ( ) ; buf . advance ( ) . value = "" ; buf . end ( ) ; assertThat ( buf . size ( ) , is ( ) ) ; assertThat ( buf . get ( ) , is ( new Holder ( "" ) ) ) ; buf . shrink ( ) ; } @ Test public void createBigList ( ) { int size = ; FileMapListBuffer < Holder > buf = new FileMapListBuffer < Holder > ( ) ; buf . begin ( ) ; for ( int i = ; i < size ; i ++ ) { if ( buf . isExpandRequired ( ) ) { buf . expand ( new Holder ( "" ) ) ; } buf . advance ( ) . value = String . valueOf ( i ) ; } buf . end ( ) ; assertThat ( buf . size ( ) , is ( size ) ) ; for ( int i = ; i < size ; i ++ ) { assertThat ( buf . get ( i ) . value , is ( String . valueOf ( i ) ) ) ; } buf . shrink ( ) ; } @ Test ( expected = IndexOutOfBoundsException . class ) public void over_expand ( ) { FileMapListBuffer < Holder > buf = new FileMapListBuffer < Holder > ( ) ; try { buf . begin ( ) ; while ( true ) { buf . expand ( new Holder ( "" ) ) ; } } finally { buf . shrink ( ) ; } } @ Test ( expected = IndexOutOfBoundsException . class ) public void get_UpperOutOfBounds ( ) { FileMapListBuffer < Holder > buf = new FileMapListBuffer < Holder > ( ) ; try { buf . begin ( ) ; buf . end ( ) ; buf . get ( ) ; } finally { buf . shrink ( ) ; } } @ Test ( expected = IndexOutOfBoundsException . class ) public void get_LowerOutOfBounds ( ) { FileMapListBuffer < Holder > buf = new FileMapListBuffer < Holder > ( ) ; try { buf . begin ( ) ; buf . end ( ) ; buf . get ( - ) ; } finally { buf . shrink ( ) ; } } static class Holder implements DataModel < Holder > , Writable { String value ; Holder ( String value ) { this . value = value ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( value == null ) ? : value . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Holder other = ( Holder ) obj ; if ( value == null ) { if ( other . value != null ) { return false ; } } else if ( ! value . equals ( other . value ) ) { return false ; } return true ; } @ Override public String toString ( ) { return String . valueOf ( value ) ; } @ Override public void write ( DataOutput out ) throws IOException { if ( value != null ) { out . writeBoolean ( true ) ; out . writeUTF ( value ) ; } else { out . writeBoolean ( false ) ; } } @ Override public void readFields ( DataInput in ) throws IOException { if ( in . readBoolean ( ) ) { value = in . readUTF ( ) ; } else { value = null ; } } @ Override public void reset ( ) { value = null ; } @ Override public void copyFrom ( Holder other ) { value = other . value ; } } } package com . asakusafw . runtime . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; public class ArrayListBufferTest { @ Test public void createEmpty ( ) { ArrayListBuffer < Holder > buf = new ArrayListBuffer < Holder > ( ) ; buf . begin ( ) ; buf . end ( ) ; assertThat ( buf . size ( ) , is ( ) ) ; buf . shrink ( ) ; } @ Test public void createSingle ( ) { ArrayListBuffer < Holder > buf = new ArrayListBuffer < Holder > ( ) ; buf . begin ( ) ; assertThat ( buf . isExpandRequired ( ) , is ( true ) ) ; buf . expand ( new Holder ( "" ) ) ; assertThat ( buf . isExpandRequired ( ) , is ( false ) ) ; buf . advance ( ) . value = "" ; buf . end ( ) ; assertThat ( buf . size ( ) , is ( ) ) ; assertThat ( buf . get ( ) , is ( new Holder ( "" ) ) ) ; buf . shrink ( ) ; } @ Test public void reuse ( ) { ArrayListBuffer < Holder > buf = new ArrayListBuffer < Holder > ( ) ; buf . begin ( ) ; assertThat ( buf . isExpandRequired ( ) , is ( true ) ) ; buf . expand ( new Holder ( "" ) ) ; buf . advance ( ) . value = "" ; buf . end ( ) ; buf . shrink ( ) ; buf . begin ( ) ; assertThat ( buf . getCursorPosition ( ) , is ( ) ) ; buf . advance ( ) . value = "" ; buf . end ( ) ; assertThat ( buf . size ( ) , is ( ) ) ; assertThat ( buf . get ( ) , is ( new Holder ( "" ) ) ) ; buf . shrink ( ) ; } @ Test public void createBigList ( ) { int size = ; ArrayListBuffer < Holder > buf = new ArrayListBuffer < Holder > ( ) ; buf . begin ( ) ; for ( int i = ; i < size ; i ++ ) { if ( buf . isExpandRequired ( ) ) { buf . expand ( new Holder ( "" ) ) ; } buf . advance ( ) . value = String . valueOf ( i ) ; } buf . end ( ) ; assertThat ( buf . size ( ) , is ( size ) ) ; for ( int i = ; i < size ; i ++ ) { assertThat ( buf . get ( i ) . value , is ( String . valueOf ( i ) ) ) ; } buf . shrink ( ) ; } @ Test ( expected = IndexOutOfBoundsException . class ) public void advance_OutOfBounds ( ) { ArrayListBuffer < Holder > buf = new ArrayListBuffer < Holder > ( ) ; try { buf . begin ( ) ; while ( true ) { buf . advance ( ) ; } } finally { buf . shrink ( ) ; } } @ Test ( expected = IndexOutOfBoundsException . class ) public void get_UpperOutOfBounds ( ) { ArrayListBuffer < Holder > buf = new ArrayListBuffer < Holder > ( ) ; try { buf . begin ( ) ; buf . end ( ) ; buf . get ( ) ; } finally { buf . shrink ( ) ; } } @ Test ( expected = IndexOutOfBoundsException . class ) public void get_LowerOutOfBounds ( ) { ArrayListBuffer < Holder > buf = new ArrayListBuffer < Holder > ( ) ; try { buf . begin ( ) ; buf . end ( ) ; buf . get ( - ) ; } finally { buf . shrink ( ) ; } } static class Holder { String value ; Holder ( String value ) { this . value = value ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( value == null ) ? : value . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Holder other = ( Holder ) obj ; if ( value == null ) { if ( other . value != null ) { return false ; } } else if ( ! value . equals ( other . value ) ) { return false ; } return true ; } @ Override public String toString ( ) { return String . valueOf ( value ) ; } } } package com . asakusafw . runtime . flow . join ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . junit . Test ; import com . asakusafw . runtime . value . IntOption ; public class VolatileLookUpTableTest { @ Test public void empty ( ) throws Exception { VolatileLookUpTable . Builder < IntOption > builder = new VolatileLookUpTable . Builder < IntOption > ( ) ; LookUpTable < IntOption > table = builder . build ( ) ; assertThat ( sort ( table . get ( key ( ) ) ) , is ( values ( ) ) ) ; } @ Test public void simple ( ) throws Exception { VolatileLookUpTable . Builder < IntOption > builder = new VolatileLookUpTable . Builder < IntOption > ( ) ; builder . add ( key ( ) , new IntOption ( ) ) ; LookUpTable < IntOption > table = builder . build ( ) ; assertThat ( sort ( table . get ( key ( ) ) ) , is ( values ( ) ) ) ; assertThat ( sort ( table . get ( key ( ) ) ) , is ( values ( ) ) ) ; } @ Test public void duplicate ( ) throws Exception { VolatileLookUpTable . Builder < IntOption > builder = new VolatileLookUpTable . Builder < IntOption > ( ) ; builder . add ( key ( ) , new IntOption ( ) ) ; builder . add ( key ( ) , new IntOption ( ) ) ; builder . add ( key ( ) , new IntOption ( ) ) ; LookUpTable < IntOption > table = builder . build ( ) ; assertThat ( sort ( table . get ( key ( ) ) ) , is ( values ( , , ) ) ) ; assertThat ( sort ( table . get ( key ( ) ) ) , is ( values ( ) ) ) ; } @ Test public void reuseKeys ( ) throws Exception { VolatileLookUpTable . Builder < IntOption > builder = new VolatileLookUpTable . Builder < IntOption > ( ) ; LookUpKey key = key ( ) ; key . add ( new IntOption ( ) ) ; builder . add ( key , new IntOption ( ) ) ; key . reset ( ) ; key . add ( new IntOption ( ) ) ; builder . add ( key , new IntOption ( ) ) ; key . reset ( ) ; key . add ( new IntOption ( ) ) ; builder . add ( key , new IntOption ( ) ) ; key . reset ( ) ; LookUpTable < IntOption > table = builder . build ( ) ; assertThat ( sort ( table . get ( key ( ) ) ) , is ( values ( ) ) ) ; assertThat ( sort ( table . get ( key ( ) ) ) , is ( values ( ) ) ) ; assertThat ( sort ( table . get ( key ( ) ) ) , is ( values ( ) ) ) ; } private LookUpKey key ( int ... values ) throws IOException { LookUpKey result = new LookUpKey ( ) ; for ( int value : values ) { result . add ( new IntOption ( value ) ) ; } return result ; } private List < IntOption > sort ( List < IntOption > list ) { Collections . sort ( list ) ; return list ; } private List < IntOption > values ( int ... values ) { List < IntOption > options = new ArrayList < IntOption > ( ) ; for ( int value : values ) { options . add ( new IntOption ( value ) ) ; } return sort ( options ) ; } } package com . asakusafw . runtime . flow . join ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . runtime . value . IntOption ; public class LookUpKeyTest { @ Test public void add ( ) throws Exception { LookUpKey k1 = new LookUpKey ( ) ; LookUpKey k2 = new LookUpKey ( ) ; LookUpKey k3 = new LookUpKey ( ) ; k1 . add ( new IntOption ( ) ) ; k2 . add ( new IntOption ( ) ) ; k3 . add ( new IntOption ( ) ) ; k1 . add ( new IntOption ( ) ) ; k2 . add ( new IntOption ( ) ) ; k3 . add ( new IntOption ( ) ) ; k1 . add ( new IntOption ( ) ) ; k2 . add ( new IntOption ( ) ) ; assertThat ( k1 . equals ( k2 ) , is ( true ) ) ; assertThat ( k1 . equals ( k3 ) , is ( false ) ) ; assertThat ( k1 . hashCode ( ) , is ( k2 . hashCode ( ) ) ) ; } @ Test public void copy ( ) throws Exception { LookUpKey k1 = new LookUpKey ( ) ; k1 . add ( new IntOption ( ) ) ; LookUpKey k2 = k1 . copy ( ) ; k2 . add ( new IntOption ( ) ) ; LookUpKey k3 = new LookUpKey ( ) ; k3 . add ( new IntOption ( ) ) ; k3 . add ( new IntOption ( ) ) ; assertThat ( k1 . equals ( k2 ) , is ( false ) ) ; assertThat ( k2 . equals ( k3 ) , is ( true ) ) ; assertThat ( k2 . hashCode ( ) , is ( k3 . hashCode ( ) ) ) ; } @ Test public void reset ( ) throws Exception { LookUpKey k1 = new LookUpKey ( ) ; k1 . add ( new IntOption ( ) ) ; k1 . reset ( ) ; k1 . add ( new IntOption ( ) ) ; LookUpKey k2 = new LookUpKey ( ) ; k2 . add ( new IntOption ( ) ) ; assertThat ( k1 . equals ( k2 ) , is ( true ) ) ; assertThat ( k1 . hashCode ( ) , is ( k2 . hashCode ( ) ) ) ; } } package com . asakusafw . runtime . directio ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . junit . Test ; public class DirectDataSourceRepositoryTest { @ Test public void simple ( ) throws Exception { DirectDataSourceRepository repo = repo ( "" ) ; assertThat ( repo . getRelatedId ( "" ) , is ( "" ) ) ; assertThat ( repo . getRelatedId ( "" ) , is ( "" ) ) ; assertThat ( repo . getRelatedId ( "" ) , is ( "" ) ) ; assertThat ( repo . getContainerPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getContainerPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getContainerPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getComponentPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getComponentPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getComponentPath ( "" ) , is ( "" ) ) ; } @ Test public void root ( ) throws Exception { DirectDataSourceRepository repo = repo ( "" ) ; assertThat ( repo . getRelatedId ( "" ) , is ( "" ) ) ; assertThat ( repo . getRelatedId ( "" ) , is ( "" ) ) ; assertThat ( repo . getRelatedId ( "" ) , is ( "" ) ) ; assertThat ( repo . getContainerPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getContainerPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getContainerPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getComponentPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getComponentPath ( "" ) , is ( "" ) ) ; assertThat ( repo . getComponentPath ( "" ) , is ( "" ) ) ; } private DirectDataSourceRepository repo ( String ... specs ) { List < MockProvider > providers = new ArrayList < MockProvider > ( ) ; for ( String spec : specs ) { String [ ] fields = spec . split ( "" , ) ; providers . add ( new MockProvider ( fields [ ] , fields [ ] ) ) ; } return new DirectDataSourceRepository ( providers ) ; } private static final class MockProvider implements DirectDataSourceProvider { private final String id ; private final String path ; MockProvider ( String id , String path ) { this . id = id ; this . path = path ; } @ Override public String getId ( ) { return id ; } @ Override public String getPath ( ) { return path ; } @ Override public DirectDataSource newInstance ( ) throws IOException , InterruptedException { MockDirectDataSource ds = new MockDirectDataSource ( ) ; ds . configure ( new DirectDataSourceProfile ( id , MockDirectDataSource . class , path , Collections . < String , String > emptyMap ( ) ) ) ; return ds ; } } } package com . asakusafw . runtime . directio . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . nio . charset . Charset ; import java . util . Arrays ; import java . util . Random ; import org . apache . hadoop . io . InputBuffer ; import org . junit . Test ; public class DelimiterRangeInputStreamTest { @ Test public void readByte_nodelim ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_enough ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_delimited ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_just_not_delimited ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_just_delimited ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_skip ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_skip_too_small ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_skip_small ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_skip_nodelim ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_skip_nodelim_small ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee ) , is ( "" ) ) ; } @ Test public void readByte_random ( ) throws Exception { byte [ ] bytes = "" . getBytes ( Charset . forName ( "" ) ) ; InputBuffer buffer = new InputBuffer ( ) ; buffer . reset ( bytes , bytes . length ) ; Random random = new Random ( ) ; for ( int i = ; i < ; i ++ ) { int [ ] bounds = new int [ ] ; for ( int j = ; j < bounds . length ; j ++ ) { bounds [ j ] = random . nextInt ( bytes . length + ) ; } Arrays . sort ( bounds ) ; StringBuilder buf = new StringBuilder ( ) ; int start = ; for ( int j = ; j < bounds . length ; j ++ ) { int end = bounds [ j ] ; copy ( buffer , buf , start , end ) ; start = end ; } copy ( buffer , buf , start , bytes . length ) ; assertThat ( Arrays . toString ( bounds ) , buf . toString ( ) , is ( "" ) ) ; } } @ Test public void readArray_nodelim ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_enough ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_delimited ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_just_not_delimited ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_just_delimited ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , false ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_skip ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_skip_too_small ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_skip_small ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_skip_nodelim ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_skip_nodelim_small ( ) throws Exception { InputStream origin = bytes ( "" ) ; InputStream testee = new DelimiterRangeInputStream ( origin , '' , , true ) ; assertThat ( readBytes ( testee , ) , is ( "" ) ) ; } @ Test public void readArray_random ( ) throws Exception { byte [ ] bytes = "" . getBytes ( Charset . forName ( "" ) ) ; InputBuffer buffer = new InputBuffer ( ) ; buffer . reset ( bytes , bytes . length ) ; Random random = new Random ( ) ; for ( int i = ; i < ; i ++ ) { int [ ] bounds = new int [ ] ; for ( int j = ; j < bounds . length ; j ++ ) { bounds [ j ] = random . nextInt ( bytes . length + ) ; } Arrays . sort ( bounds ) ; StringBuilder buf = new StringBuilder ( ) ; int start = ; for ( int j = ; j < bounds . length ; j ++ ) { int end = bounds [ j ] ; copy ( buffer , buf , start , end , ) ; start = end ; } copy ( buffer , buf , start , bytes . length , ) ; assertThat ( Arrays . toString ( bounds ) , buf . toString ( ) , is ( "" ) ) ; } } private InputStream bytes ( String content ) { return new ByteArrayInputStream ( content . getBytes ( Charset . forName ( "" ) ) ) ; } private String readBytes ( InputStream in ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; while ( true ) { int c = in . read ( ) ; if ( c < ) { break ; } output . write ( c ) ; } return new String ( output . toByteArray ( ) , Charset . forName ( "" ) ) ; } private String readBytes ( InputStream in , int size ) throws IOException { byte [ ] buf = new byte [ size ] ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; while ( true ) { int read = in . read ( buf ) ; if ( read < ) { break ; } output . write ( buf , , read ) ; } return new String ( output . toByteArray ( ) , Charset . forName ( "" ) ) ; } private void copy ( InputBuffer source , StringBuilder sink , int start , int end ) throws IOException { source . reset ( ) ; assertThat ( source . skip ( start ) , is ( ( long ) start ) ) ; InputStream testee = new DelimiterRangeInputStream ( source , '' , end - start , start > ) ; sink . append ( readBytes ( testee ) ) ; } private void copy ( InputBuffer source , StringBuilder sink , int start , int end , int size ) throws IOException { source . reset ( ) ; assertThat ( source . skip ( start ) , is ( ( long ) start ) ) ; InputStream testee = new DelimiterRangeInputStream ( source , '' , end - start , start > ) ; sink . append ( readBytes ( testee , size ) ) ; } } package com . asakusafw . runtime . directio ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class MockDirectDataSource extends AbstractDirectDataSource { public DirectDataSourceProfile profile ; @ Override public void configure ( DirectDataSourceProfile p ) throws IOException , InterruptedException { this . profile = p ; } @ Override public < T > List < DirectInputFragment > findInputFragments ( Class < ? extends T > dataType , DataFormat < T > format , String basePath , ResourcePattern resourcePattern ) throws IOException , InterruptedException { return Collections . emptyList ( ) ; } @ Override public < T > ModelInput < T > openInput ( Class < ? extends T > dataType , DataFormat < T > format , DirectInputFragment fragment , Counter counter ) throws IOException , InterruptedException { return new ModelInput < T > ( ) { @ Override public boolean readTo ( T model ) throws IOException { return false ; } @ Override public void close ( ) throws IOException { return ; } } ; } @ Override public < T > ModelOutput < T > openOutput ( OutputAttemptContext context , Class < ? extends T > dataType , DataFormat < T > format , String basePath , String resourcePath , Counter counter ) throws IOException , InterruptedException { return new ModelOutput < T > ( ) { @ Override public void write ( T model ) throws IOException { return ; } @ Override public void close ( ) throws IOException { return ; } } ; } @ Override public List < ResourceInfo > list ( String basePath , ResourcePattern resourcePattern , Counter counter ) throws IOException , InterruptedException { return Collections . emptyList ( ) ; } @ Override public boolean delete ( String basePath , ResourcePattern resourcePattern , boolean recursive , Counter counter ) throws IOException , InterruptedException { return false ; } @ Override public void setupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { return ; } @ Override public void commitAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { return ; } @ Override public void cleanupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { return ; } @ Override public void setupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { return ; } @ Override public void commitTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { return ; } @ Override public void cleanupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { return ; } } package com . asakusafw . runtime . directio . hadoop ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Random ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . LocalFileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . LongWritable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . compress . CompressionCodec ; import org . apache . hadoop . io . compress . DefaultCodec ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . value . StringOption ; public class SequenceFileFormatTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private Configuration conf ; private MockFormat format ; @ Before public void setUp ( ) throws Exception { this . conf = new Configuration ( true ) ; this . format = new MockFormat ( ) ; format . setConf ( conf ) ; } @ Test public void input ( ) throws Exception { final int count = ; LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; SequenceFile . Writer writer = SequenceFile . createWriter ( fs , conf , path , LongWritable . class , Text . class ) ; try { LongWritable k = new LongWritable ( ) ; Text v = new Text ( ) ; for ( int i = ; i < count ; i ++ ) { k . set ( i ) ; v . set ( "" + i ) ; writer . append ( k , v ) ; } } finally { writer . close ( ) ; } ModelInput < StringOption > in = format . createInput ( StringOption . class , fs , path , , fs . getFileStatus ( path ) . getLen ( ) , new Counter ( ) ) ; try { StringOption value = new StringOption ( ) ; for ( int i = ; i < count ; i ++ ) { String answer = "" + i ; assertThat ( answer , in . readTo ( value ) , is ( true ) ) ; assertThat ( value . getAsString ( ) , is ( answer ) ) ; } assertThat ( "" , in . readTo ( value ) , is ( false ) ) ; } finally { in . close ( ) ; } } @ Test public void input_fragment ( ) throws Exception { final int count = ; Random rand = new Random ( ) ; LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; SequenceFile . Writer writer = SequenceFile . createWriter ( fs , conf , path , LongWritable . class , Text . class ) ; try { LongWritable k = new LongWritable ( ) ; Text v = new Text ( ) ; for ( int i = ; i < count ; i ++ ) { k . set ( i ) ; v . set ( "" + i ) ; writer . append ( k , v ) ; } } finally { writer . close ( ) ; } long fileLen = fs . getFileStatus ( path ) . getLen ( ) ; StringOption value = new StringOption ( ) ; for ( int attempt = ; attempt < ; attempt ++ ) { int index = ; long offset = ; while ( offset < fileLen ) { long length = SequenceFile . SYNC_INTERVAL * ( rand . nextInt ( ) + ) ; length = Math . min ( length , fileLen - offset ) ; ModelInput < StringOption > in = format . createInput ( StringOption . class , fs , path , offset , length , new Counter ( ) ) ; try { while ( in . readTo ( value ) ) { String answer = "" + index ; assertThat ( value . getAsString ( ) , is ( answer ) ) ; index ++ ; } assertThat ( "" , in . readTo ( value ) , is ( false ) ) ; } finally { in . close ( ) ; } offset += length ; } assertThat ( index , is ( count ) ) ; } } @ Test public void input_largerecord ( ) throws Exception { StringBuilder buf = new StringBuilder ( ) ; for ( int i = ; i < ; i ++ ) { buf . append ( "" ) ; } Text record = new Text ( buf . toString ( ) ) ; final int count = ; LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; SequenceFile . Writer writer = SequenceFile . createWriter ( fs , conf , path , LongWritable . class , Text . class ) ; try { LongWritable k = new LongWritable ( ) ; Text v = new Text ( ) ; for ( int i = ; i < count ; i ++ ) { k . set ( i ) ; v . set ( record ) ; writer . append ( k , v ) ; } } finally { writer . close ( ) ; } long fileLen = fs . getFileStatus ( path ) . getLen ( ) ; StringOption value = new StringOption ( ) ; int index = ; long offset = ; while ( offset < fileLen ) { long length = SequenceFile . SYNC_INTERVAL * ; length = Math . min ( length , fileLen - offset ) ; ModelInput < StringOption > in = format . createInput ( StringOption . class , fs , path , offset , length , new Counter ( ) ) ; try { while ( in . readTo ( value ) ) { assertThat ( value . get ( ) , is ( record ) ) ; index ++ ; } assertThat ( "" , in . readTo ( value ) , is ( false ) ) ; } finally { in . close ( ) ; } offset += length ; } assertThat ( index , is ( count ) ) ; } @ Test public void input_empty ( ) throws Exception { LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; fs . create ( path ) . close ( ) ; ModelInput < StringOption > in = format . createInput ( StringOption . class , fs , path , , fs . getFileStatus ( path ) . getLen ( ) , new Counter ( ) ) ; try { assertThat ( "" , in . readTo ( new StringOption ( ) ) , is ( false ) ) ; } finally { in . close ( ) ; } } @ Test ( expected = IOException . class ) public void input_invalid ( ) throws Exception { LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; FSDataOutputStream output = fs . create ( path ) ; try { output . writeUTF ( "" ) ; } finally { output . close ( ) ; } ModelInput < StringOption > in = format . createInput ( StringOption . class , fs , path , , fs . getFileStatus ( path ) . getLen ( ) , new Counter ( ) ) ; in . close ( ) ; } @ SuppressWarnings ( "" ) @ Test public void output ( ) throws Exception { final int count = ; LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; ModelOutput < StringOption > out = format . createOutput ( StringOption . class , fs , path , new Counter ( ) ) ; try { StringOption value = new StringOption ( ) ; for ( int i = ; i < count ; i ++ ) { value . modify ( "" + i ) ; out . write ( value ) ; } } finally { out . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { LongWritable k = new LongWritable ( ) ; Text v = new Text ( ) ; for ( int i = ; i < count ; i ++ ) { String answer = "" + i ; assertThat ( answer , reader . next ( k , v ) , is ( true ) ) ; assertThat ( answer , k . get ( ) , is ( ) ) ; assertThat ( answer , v . toString ( ) , is ( answer ) ) ; } assertThat ( "" , reader . next ( k ) , is ( false ) ) ; } finally { reader . close ( ) ; } } @ Test public void output_compressed ( ) throws Exception { LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; ModelOutput < StringOption > out = format . codec ( new DefaultCodec ( ) ) . createOutput ( StringOption . class , fs , path , new Counter ( ) ) ; try { out . write ( new StringOption ( "" ) ) ; } finally { out . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { assertThat ( reader . getCompressionCodec ( ) , instanceOf ( DefaultCodec . class ) ) ; } finally { reader . close ( ) ; } } @ Test public void output_no_compressed ( ) throws Exception { LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; ModelOutput < StringOption > out = format . codec ( null ) . createOutput ( StringOption . class , fs , path , new Counter ( ) ) ; try { out . write ( new StringOption ( "" ) ) ; } finally { out . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { assertThat ( reader . getCompressionCodec ( ) , is ( nullValue ( ) ) ) ; } finally { reader . close ( ) ; } } @ Test public void output_compressed_conf ( ) throws Exception { LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; format . getConf ( ) . set ( SequenceFileFormat . KEY_COMPRESSION_CODEC , DefaultCodec . class . getName ( ) ) ; ModelOutput < StringOption > out = format . createOutput ( StringOption . class , fs , path , new Counter ( ) ) ; try { out . write ( new StringOption ( "" ) ) ; } finally { out . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { assertThat ( reader . getCompressionCodec ( ) , instanceOf ( DefaultCodec . class ) ) ; } finally { reader . close ( ) ; } } @ Test public void output_compressed_invalid ( ) throws Exception { LocalFileSystem fs = FileSystem . getLocal ( conf ) ; Path path = new Path ( folder . newFile ( "" ) . toURI ( ) ) ; format . getConf ( ) . set ( SequenceFileFormat . KEY_COMPRESSION_CODEC , "" ) ; ModelOutput < StringOption > out = format . createOutput ( StringOption . class , fs , path , new Counter ( ) ) ; try { out . write ( new StringOption ( "" ) ) ; } finally { out . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , conf ) ; try { assertThat ( reader . getCompressionCodec ( ) , is ( nullValue ( ) ) ) ; } finally { reader . close ( ) ; } } private static class MockFormat extends SequenceFileFormat < LongWritable , Text , StringOption > { private CompressionCodec codec ; private boolean codecSet ; MockFormat ( ) { return ; } MockFormat codec ( CompressionCodec c ) { this . codecSet = true ; this . codec = c ; return this ; } @ Override public Class < StringOption > getSupportedType ( ) { return StringOption . class ; } @ Override protected LongWritable createKeyObject ( ) { return new LongWritable ( ) ; } @ Override protected Text createValueObject ( ) { return new Text ( ) ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return SequenceFile . SYNC_INTERVAL * ; } @ SuppressWarnings ( "" ) @ Override protected void copyToModel ( LongWritable key , Text value , StringOption model ) throws IOException { model . modify ( value ) ; } @ Override protected void copyFromModel ( StringOption model , LongWritable key , Text value ) throws IOException { key . set ( ) ; value . set ( model . get ( ) ) ; } @ Override public CompressionCodec getCompressionCodec ( Path path ) throws IOException , InterruptedException { if ( codecSet == false ) { return super . getCompressionCodec ( path ) ; } return codec ; } } } package com . asakusafw . runtime . directio . hadoop ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import org . junit . Test ; import com . asakusafw . runtime . directio . DirectInputFragment ; public class FragmentComputerTest { @ Test public void simple ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( find ( results , ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; } @ Test public void empty ( ) { BlockBuilder builder = new BlockBuilder ( ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test public void no_info ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . seek ( ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test public void sparse ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . seek ( ) ; builder . add ( , "" ) ; builder . seek ( ) ; builder . add ( , "" ) ; builder . seek ( ) ; builder . add ( , "" ) ; builder . seek ( ) ; builder . add ( , "" ) ; builder . seek ( ) ; builder . add ( , "" ) ; builder . seek ( ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( find ( results , ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; } @ Test public void no_fragmentation ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( - , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test public void too_small ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test public void head_too_small ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; } @ Test public void tail_too_small ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; } @ Test public void edge_too_small ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; } @ Test public void pref_size ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; } @ Test public void pref_size_with_join ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; } @ Test public void pref_size_without_join ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; builder . add ( , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getSize ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getSize ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getSize ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getSize ( ) , is ( ) ) ; } @ Test public void ignore_little_locality ( ) { BlockBuilder builder = new BlockBuilder ( ) ; builder . add ( , "" ) ; builder . add ( , "" , "" , "" ) ; List < DirectInputFragment > results = builder . compute ( , , true , true ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , hasItem ( "" ) ) ; assertThat ( results . get ( ) . getOwnerNodeNames ( ) , not ( hasItem ( "" ) ) ) ; } private DirectInputFragment find ( List < DirectInputFragment > results , long position ) { for ( DirectInputFragment fragment : results ) { long offset = fragment . getOffset ( ) ; long size = fragment . getSize ( ) ; if ( offset <= position && position < offset + size ) { return fragment ; } } throw new AssertionError ( position ) ; } private static class BlockBuilder { long offset ; List < BlockInfo > blocks = new ArrayList < BlockInfo > ( ) ; BlockBuilder ( ) { return ; } void add ( long size , String ... hosts ) { blocks . add ( new BlockInfo ( offset , offset + size , hosts ) ) ; offset += size ; } void seek ( long delta ) { offset += delta ; } List < DirectInputFragment > compute ( long min , long pref , boolean combine , boolean split ) { FragmentComputer computer = new FragmentComputer ( min , pref , combine , split ) ; List < DirectInputFragment > results = computer . computeFragments ( "" , offset , blocks ) ; return validate ( results ) ; } private List < DirectInputFragment > validate ( List < DirectInputFragment > fragments ) { List < DirectInputFragment > results = new ArrayList < DirectInputFragment > ( fragments ) ; Collections . sort ( results , new Comparator < DirectInputFragment > ( ) { @ Override public int compare ( DirectInputFragment o1 , DirectInputFragment o2 ) { long i1 = o1 . getOffset ( ) ; long i2 = o2 . getOffset ( ) ; if ( i1 < i2 ) { return - ; } if ( i1 > i2 ) { return + ; } return ; } } ) ; long expectedOffset = ; for ( DirectInputFragment fragment : results ) { assertThat ( fragment . getOffset ( ) , is ( expectedOffset ) ) ; expectedOffset = fragment . getOffset ( ) + fragment . getSize ( ) ; } assertThat ( offset , is ( expectedOffset ) ) ; return results ; } } } package com . asakusafw . runtime . directio . hadoop ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . LocalFileSystem ; import org . apache . hadoop . fs . Path ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceProfile ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . FilePattern ; public class HadoopDataSourceUtilTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void loadProfiles_simple ( ) { Configuration conf = new Configuration ( ) ; conf . set ( key ( "" ) , MockHadoopDataSource . class . getName ( ) ) ; conf . set ( key ( "" , "" ) , "" ) ; List < DirectDataSourceProfile > profiles = HadoopDataSourceUtil . loadProfiles ( conf ) ; assertThat ( profiles . size ( ) , is ( ) ) ; DirectDataSourceProfile profile = find ( profiles , "" ) ; assertThat ( profile . getTargetClass ( ) , equalTo ( ( Object ) MockHadoopDataSource . class ) ) ; assertThat ( profile . getAttributes ( ) , is ( map ( ) ) ) ; } @ Test public void loadProfiles_path ( ) { Configuration conf = new Configuration ( ) ; conf . set ( key ( "" ) , MockHadoopDataSource . class . getName ( ) ) ; conf . set ( key ( "" , "" ) , "" ) ; List < DirectDataSourceProfile > profiles = HadoopDataSourceUtil . loadProfiles ( conf ) ; assertThat ( profiles . size ( ) , is ( ) ) ; DirectDataSourceProfile profile = find ( profiles , "" ) ; assertThat ( profile . getTargetClass ( ) , equalTo ( ( Object ) MockHadoopDataSource . class ) ) ; assertThat ( profile . getAttributes ( ) , is ( map ( ) ) ) ; } @ Test public void loadProfiles_attribute ( ) { Configuration conf = new Configuration ( ) ; conf . set ( key ( "" ) , MockHadoopDataSource . class . getName ( ) ) ; conf . set ( key ( "" , "" ) , "" ) ; conf . set ( key ( "" , "" ) , "" ) ; conf . set ( key ( "" , "" ) , "" ) ; conf . set ( key ( "" , "" ) , "" ) ; List < DirectDataSourceProfile > profiles = HadoopDataSourceUtil . loadProfiles ( conf ) ; assertThat ( profiles . size ( ) , is ( ) ) ; DirectDataSourceProfile profile = find ( profiles , "" ) ; assertThat ( profile . getTargetClass ( ) , equalTo ( ( Object ) MockHadoopDataSource . class ) ) ; assertThat ( profile . getAttributes ( ) , is ( map ( "" , "" , "" , "" , "" , "" ) ) ) ; } @ Test public void loadProfiles_multiple ( ) { Configuration conf = new Configuration ( ) ; conf . set ( key ( "" ) , MockHadoopDataSource . class . getName ( ) ) ; conf . set ( key ( "" , "" ) , "" ) ; conf . set ( key ( "" ) , MockHadoopDataSource . class . getName ( ) ) ; conf . set ( key ( "" , "" ) , "" ) ; conf . set ( key ( "" ) , MockHadoopDataSource . class . getName ( ) ) ; conf . set ( key ( "" , "" ) , "" ) ; List < DirectDataSourceProfile > profiles = HadoopDataSourceUtil . loadProfiles ( conf ) ; assertThat ( profiles . size ( ) , is ( ) ) ; DirectDataSourceProfile a = find ( profiles , "" ) ; assertThat ( a . getTargetClass ( ) , equalTo ( ( Object ) MockHadoopDataSource . class ) ) ; assertThat ( a . getAttributes ( ) , is ( map ( ) ) ) ; DirectDataSourceProfile b = find ( profiles , "" ) ; assertThat ( b . getTargetClass ( ) , equalTo ( ( Object ) MockHadoopDataSource . class ) ) ; assertThat ( b . getAttributes ( ) , is ( map ( ) ) ) ; DirectDataSourceProfile c = find ( profiles , "" ) ; assertThat ( c . getTargetClass ( ) , equalTo ( ( Object ) MockHadoopDataSource . class ) ) ; assertThat ( c . getAttributes ( ) , is ( map ( ) ) ) ; } private Map < String , String > map ( String ... kvs ) { assertThat ( kvs . length % , is ( ) ) ; Map < String , String > results = new HashMap < String , String > ( ) ; for ( int i = ; i < kvs . length ; i += ) { results . put ( kvs [ i ] , kvs [ i + ] ) ; } return results ; } private DirectDataSourceProfile find ( List < DirectDataSourceProfile > profiles , String path ) { for ( DirectDataSourceProfile p : profiles ) { if ( p . getPath ( ) . equals ( path ) ) { return p ; } } throw new AssertionError ( path ) ; } private String key ( String first , String ... rest ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( HadoopDataSourceUtil . PREFIX ) ; buf . append ( first ) ; for ( String s : rest ) { buf . append ( "" ) ; buf . append ( s ) ; } return buf . toString ( ) ; } @ Test public void loadRepository ( ) throws Exception { Configuration conf = new Configuration ( ) ; conf . set ( key ( "" ) , MockHadoopDataSource . class . getName ( ) ) ; conf . set ( key ( "" , "" ) , "" ) ; conf . set ( key ( "" , "" ) , "" ) ; DirectDataSourceRepository repo = HadoopDataSourceUtil . loadRepository ( conf ) ; DirectDataSource ds = repo . getRelatedDataSource ( "" ) ; assertThat ( ds , instanceOf ( MockHadoopDataSource . class ) ) ; MockHadoopDataSource mock = ( MockHadoopDataSource ) ds ; assertThat ( mock . conf , is ( notNullValue ( ) ) ) ; assertThat ( mock . profile . getPath ( ) , is ( "" ) ) ; } @ Test public void transactionInfo ( ) throws Exception { Configuration conf = new Configuration ( ) ; conf . set ( HadoopDataSourceUtil . KEY_SYSTEM_DIR , folder . getRoot ( ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; assertThat ( "" , folder . getRoot ( ) . listFiles ( ) , is ( new File [ ] ) ) ; assertThat ( HadoopDataSourceUtil . findAllTransactionInfoFiles ( conf ) . size ( ) , is ( ) ) ; Path t1 = HadoopDataSourceUtil . getTransactionInfoPath ( conf , "" ) ; assertThat ( HadoopDataSourceUtil . getTransactionInfoExecutionId ( t1 ) , is ( "" ) ) ; t1 . getFileSystem ( conf ) . create ( t1 ) . close ( ) ; assertThat ( folder . getRoot ( ) . listFiles ( ) . length , is ( greaterThan ( ) ) ) ; Path t2 = HadoopDataSourceUtil . getTransactionInfoPath ( conf , "" ) ; assertThat ( t2 , is ( not ( t1 ) ) ) ; assertThat ( HadoopDataSourceUtil . getTransactionInfoExecutionId ( t2 ) , is ( "" ) ) ; t2 . getFileSystem ( conf ) . create ( t2 ) . close ( ) ; Path c2 = HadoopDataSourceUtil . getCommitMarkPath ( conf , "" ) ; assertThat ( c2 , is ( not ( t2 ) ) ) ; c2 . getFileSystem ( conf ) . create ( c2 ) . close ( ) ; List < Path > paths = new ArrayList < Path > ( ) ; for ( FileStatus stat : HadoopDataSourceUtil . findAllTransactionInfoFiles ( conf ) ) { paths . add ( stat . getPath ( ) ) ; } assertThat ( paths . size ( ) , is ( ) ) ; assertThat ( paths , hasItem ( t1 ) ) ; assertThat ( paths , hasItem ( t2 ) ) ; } @ Test public void search_direct ( ) throws Exception { touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" ) ) ) ; } @ Test public void search_direct_deep ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" ) ) ) ; } @ Test public void search_wildcard ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" ) ) ) ; } @ Test public void search_wildcard_dir ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" ) ) ) ; } @ Test public void search_selection ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" ) ) ) ; } @ Test public void search_selection_multiple ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" , "" , "" ) ) ) ; } @ Test public void search_selection_complex ( ) throws Exception { for ( int year = ; year <= ; year ++ ) { for ( int month = ; month <= ; month ++ ) { touch ( String . format ( "" , year , month , "" ) ) ; } } FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" ) ) ) ; } @ Test public void search_traverse ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" , "" , "" , "" , "" , "" ) ) ) ; } @ Test public void search_traverse_file ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > results = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" , "" ) ) ) ; } @ Test public void minimalCovered_trivial ( ) throws Exception { touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > raw = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( raw . size ( ) , is ( ) ) ; List < FileStatus > results = HadoopDataSourceUtil . onlyMinimalCovered ( raw ) ; assertThat ( normalize ( results ) , is ( path ( "" ) ) ) ; } @ Test public void minimalCovered_siblings ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > raw = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( raw . size ( ) , is ( ) ) ; List < FileStatus > results = HadoopDataSourceUtil . onlyMinimalCovered ( raw ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" , "" ) ) ) ; } @ Test public void minimalCovered_parent ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > raw = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; assertThat ( raw . size ( ) , is ( ) ) ; List < FileStatus > results = HadoopDataSourceUtil . onlyMinimalCovered ( raw ) ; assertThat ( normalize ( results ) , is ( path ( "" ) ) ) ; } @ Test public void minimalCovered_deep ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; List < FileStatus > raw = HadoopDataSourceUtil . search ( fs , getBase ( ) , FilePattern . compile ( "" ) ) ; for ( Iterator < FileStatus > iterator = raw . iterator ( ) ; iterator . hasNext ( ) ; ) { FileStatus fileStatus = iterator . next ( ) ; if ( fileStatus . getPath ( ) . getName ( ) . equals ( "" ) ) { iterator . remove ( ) ; } } assertThat ( raw . size ( ) , is ( ) ) ; List < FileStatus > results = HadoopDataSourceUtil . onlyMinimalCovered ( raw ) ; assertThat ( normalize ( results ) , is ( path ( "" , "" ) ) ) ; } @ Test public void move_simple ( ) throws Exception { touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; HadoopDataSourceUtil . move ( new Counter ( ) , fs , getPath ( "" ) , getPath ( "" ) ) ; assertThat ( collect ( ) , is ( path ( "" ) ) ) ; } @ Test public void move_multiple ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; HadoopDataSourceUtil . move ( new Counter ( ) , fs , getPath ( "" ) , getPath ( "" ) ) ; assertThat ( collect ( ) , is ( path ( "" , "" , "" ) ) ) ; } @ Test public void move_deep ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; HadoopDataSourceUtil . move ( new Counter ( ) , fs , getPath ( "" ) , getPath ( "" ) ) ; assertThat ( collect ( ) , is ( path ( "" , "" , "" ) ) ) ; } @ Test public void move_merge ( ) throws Exception { touch ( "" ) ; touch ( "" ) ; touch ( "" ) ; FileSystem fs = getTempFileSystem ( ) ; HadoopDataSourceUtil . move ( new Counter ( ) , fs , getPath ( "" ) , getPath ( "" ) ) ; assertThat ( collect ( ) , is ( path ( "" , "" , "" ) ) ) ; } private List < String > collect ( ) throws IOException { List < FileStatus > all = HadoopDataSourceUtil . search ( getTempFileSystem ( ) , getBase ( ) , FilePattern . compile ( "" ) ) ; List < FileStatus > files = new ArrayList < FileStatus > ( ) ; for ( FileStatus stat : all ) { if ( stat . isDir ( ) == false ) { files . add ( stat ) ; } } return normalize ( files ) ; } private List < String > normalize ( List < FileStatus > stats ) throws IOException { File base = folder . getRoot ( ) . getCanonicalFile ( ) ; List < String > normalized = new ArrayList < String > ( ) ; for ( FileStatus stat : stats ) { URI uri = stat . getPath ( ) . toUri ( ) ; try { File file = new File ( uri ) . getCanonicalFile ( ) ; String f = file . getAbsolutePath ( ) ; String b = base . getAbsolutePath ( ) ; assertThat ( f , startsWith ( b ) ) ; String r = f . substring ( b . length ( ) ) ; while ( r . startsWith ( File . separator ) ) { r = r . substring ( ) ; } normalized . add ( r ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } Collections . sort ( normalized ) ; return normalized ; } private Matcher < List < String > > path ( final String ... paths ) { return new BaseMatcher < List < String > > ( ) { @ Override public boolean matches ( Object obj ) { @ SuppressWarnings ( "" ) List < String > actuals = ( List < String > ) obj ; List < String > normalized = new ArrayList < String > ( actuals ) ; List < String > expected = new ArrayList < String > ( ) ; Collections . addAll ( expected , paths ) ; Collections . sort ( expected ) ; Collections . sort ( normalized ) ; return expected . equals ( normalized ) ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( Arrays . toString ( paths ) ) ; } } ; } private FileSystem getTempFileSystem ( ) throws IOException { Configuration conf = new Configuration ( ) ; LocalFileSystem local = FileSystem . getLocal ( conf ) ; return local ; } private Path getBase ( ) { return new Path ( folder . getRoot ( ) . toURI ( ) ) ; } private Path getPath ( String path ) { return new Path ( getBase ( ) , path ) ; } private void touch ( String path ) throws IOException { File file = new File ( folder . getRoot ( ) , path ) ; file . getParentFile ( ) . mkdirs ( ) ; file . createNewFile ( ) ; assertThat ( file . isFile ( ) , is ( true ) ) ; } } package com . asakusafw . runtime . directio . hadoop ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . BufferedOutputStream ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . Scanner ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import org . junit . runner . RunWith ; import org . junit . runners . Parameterized ; import org . junit . runners . Parameterized . Parameters ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectInputFragment ; import com . asakusafw . runtime . directio . FilePattern ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . util . CountInputStream ; import com . asakusafw . runtime . directio . util . CountOutputStream ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; @ RunWith ( Parameterized . class ) public class HadoopDataSourceCoreTest { @ Rule public final TemporaryFolder temp = new TemporaryFolder ( ) ; private final DataFormat < StringBuilder > format ; private Configuration conf ; private File mapping ; private File temporary ; private File localtemp ; private HadoopDataSourceProfile profile ; private OutputAttemptContext context ; private final Counter counter = new Counter ( ) ; @ Parameters public static List < Object [ ] > data ( ) { return Arrays . asList ( new Object [ ] [ ] { { new MockStreamFormat ( ) } , { new MockFileFormat ( ) } , } ) ; } public HadoopDataSourceCoreTest ( DataFormat < StringBuilder > format ) { this . format = format ; } @ Before public void setUp ( ) throws Exception { conf = new Configuration ( true ) ; if ( format instanceof Configurable ) { ( ( Configurable ) format ) . setConf ( conf ) ; } mapping = new File ( temp . getRoot ( ) , "" ) . getCanonicalFile ( ) ; temporary = new File ( temp . getRoot ( ) , "" ) . getCanonicalFile ( ) ; localtemp = new File ( temp . getRoot ( ) , "" ) . getCanonicalFile ( ) ; profile = new HadoopDataSourceProfile ( conf , "" , "" , new Path ( mapping . toURI ( ) ) , new Path ( temporary . toURI ( ) ) ) ; context = new OutputAttemptContext ( "" , "" , profile . getId ( ) , new Counter ( ) ) ; } @ Test public void input ( ) throws Exception { put ( new File ( mapping , "" ) , "" ) ; profile . setMinimumFragmentSize ( - ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; List < DirectInputFragment > fragments = core . findInputFragments ( StringBuilder . class , format , "" , FilePattern . compile ( "" ) ) ; assertThat ( fragments . size ( ) , is ( ) ) ; List < String > results = consume ( core , fragments ) ; assertThat ( counter . get ( ) , is ( greaterThan ( ) ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results , hasItem ( "" ) ) ; } @ Test public void input_multirecord ( ) throws Exception { put ( new File ( mapping , "" ) , "" , "" , "" ) ; profile . setMinimumFragmentSize ( - ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; List < DirectInputFragment > fragments = core . findInputFragments ( StringBuilder . class , format , "" , FilePattern . compile ( "" ) ) ; assertThat ( fragments . size ( ) , is ( ) ) ; List < String > results = consume ( core , fragments ) ; assertThat ( counter . get ( ) , is ( greaterThan ( ) ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results , hasItem ( "" ) ) ; assertThat ( results , hasItem ( "" ) ) ; assertThat ( results , hasItem ( "" ) ) ; } @ Test public void input_large ( ) throws Exception { long fragmentSize = * * ; int fragmentCount = ; put ( new File ( mapping , "" ) , fragmentSize * fragmentCount ) ; profile . setMinimumFragmentSize ( ) ; profile . setPreferredFragmentSize ( fragmentSize ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; List < DirectInputFragment > fragments = core . findInputFragments ( StringBuilder . class , format , "" , FilePattern . compile ( "" ) ) ; assertThat ( fragments . size ( ) , is ( greaterThanOrEqualTo ( fragmentCount / ) ) ) ; for ( DirectInputFragment fragment : fragments ) { assertThat ( fragment . getSize ( ) , is ( greaterThanOrEqualTo ( fragmentSize / ) ) ) ; assertThat ( fragment . getSize ( ) , is ( lessThanOrEqualTo ( fragmentSize * ) ) ) ; } } @ Test public void input_multifile ( ) throws Exception { put ( new File ( mapping , "" ) , "" ) ; put ( new File ( mapping , "" ) , "" ) ; put ( new File ( mapping , "" ) , "" ) ; profile . setMinimumFragmentSize ( - ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; List < DirectInputFragment > fragments = core . findInputFragments ( StringBuilder . class , format , "" , FilePattern . compile ( "" ) ) ; assertThat ( fragments . size ( ) , is ( ) ) ; List < String > results = consume ( core , fragments ) ; assertThat ( counter . get ( ) , is ( greaterThan ( ) ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results , hasItem ( "" ) ) ; assertThat ( results , hasItem ( "" ) ) ; assertThat ( results , hasItem ( "" ) ) ; } @ Test public void output ( ) throws Exception { HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; setup ( core ) ; ModelOutput < StringBuilder > output = core . openOutput ( context , StringBuilder . class , format , "" , "" , counter ) ; try { output . write ( new StringBuilder ( "" ) ) ; } finally { output . close ( ) ; } assertThat ( counter . get ( ) , is ( greaterThan ( ) ) ) ; File target = new File ( mapping , "" ) ; assertThat ( target . exists ( ) , is ( false ) ) ; commitAttempt ( core ) ; assertThat ( target . exists ( ) , is ( false ) ) ; commitTransaction ( core ) ; assertThat ( target . exists ( ) , is ( true ) ) ; assertThat ( get ( target ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void output_nostaging ( ) throws Exception { profile . setOutputStaging ( false ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; setup ( core ) ; ModelOutput < StringBuilder > output = core . openOutput ( context , StringBuilder . class , format , "" , "" , counter ) ; try { output . write ( new StringBuilder ( "" ) ) ; } finally { output . close ( ) ; } assertThat ( counter . get ( ) , is ( greaterThan ( ) ) ) ; File target = new File ( mapping , "" ) ; assertThat ( target . exists ( ) , is ( false ) ) ; commitAttempt ( core ) ; assertThat ( target . exists ( ) , is ( true ) ) ; commitTransaction ( core ) ; assertThat ( target . exists ( ) , is ( true ) ) ; assertThat ( get ( target ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void output_nostreaming ( ) throws Exception { profile . setOutputStreaming ( false ) ; profile . getLocalFileSystem ( ) . getConf ( ) . set ( HadoopDataSourceUtil . KEY_LOCAL_TEMPDIR , localtemp . getPath ( ) ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; setup ( core ) ; ModelOutput < StringBuilder > output = core . openOutput ( context , StringBuilder . class , format , "" , "" , counter ) ; try { output . write ( new StringBuilder ( "" ) ) ; } finally { output . close ( ) ; } assertThat ( counter . get ( ) , is ( greaterThan ( ) ) ) ; File target = new File ( mapping , "" ) ; assertThat ( target . exists ( ) , is ( false ) ) ; commitAttempt ( core ) ; assertThat ( target . exists ( ) , is ( false ) ) ; commitTransaction ( core ) ; assertThat ( target . exists ( ) , is ( true ) ) ; assertThat ( get ( target ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void output_nomove ( ) throws Exception { profile . setOutputStaging ( false ) ; profile . setOutputStreaming ( false ) ; profile . getLocalFileSystem ( ) . getConf ( ) . set ( HadoopDataSourceUtil . KEY_LOCAL_TEMPDIR , localtemp . getPath ( ) ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; setup ( core ) ; ModelOutput < StringBuilder > output = core . openOutput ( context , StringBuilder . class , format , "" , "" , counter ) ; try { output . write ( new StringBuilder ( "" ) ) ; } finally { output . close ( ) ; } assertThat ( counter . get ( ) , is ( greaterThan ( ) ) ) ; File target = new File ( mapping , "" ) ; assertThat ( target . exists ( ) , is ( false ) ) ; commitAttempt ( core ) ; assertThat ( target . exists ( ) , is ( true ) ) ; commitTransaction ( core ) ; assertThat ( target . exists ( ) , is ( true ) ) ; assertThat ( get ( target ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void output_multirecord ( ) throws Exception { HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; setup ( core ) ; ModelOutput < StringBuilder > output = core . openOutput ( context , StringBuilder . class , format , "" , "" , counter ) ; try { output . write ( new StringBuilder ( "" ) ) ; } finally { output . close ( ) ; } File target = new File ( mapping , "" ) ; assertThat ( target . exists ( ) , is ( false ) ) ; commitAttempt ( core ) ; assertThat ( target . exists ( ) , is ( false ) ) ; commitTransaction ( core ) ; assertThat ( target . exists ( ) , is ( true ) ) ; assertThat ( get ( target ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void output_multifile ( ) throws Exception { HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; setup ( core ) ; for ( int i = ; i < ; i ++ ) { ModelOutput < StringBuilder > output = core . openOutput ( context , StringBuilder . class , format , "" , "" + i + "" , counter ) ; try { for ( int j = ; j < i + ; j ++ ) { output . write ( new StringBuilder ( "" + j ) ) ; } } finally { output . close ( ) ; } } commit ( core ) ; assertThat ( get ( new File ( mapping , "" ) ) , is ( Arrays . asList ( "" ) ) ) ; assertThat ( get ( new File ( mapping , "" ) ) , is ( Arrays . asList ( "" , "" ) ) ) ; assertThat ( get ( new File ( mapping , "" ) ) , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test public void output_rollback ( ) throws Exception { HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; setup ( core ) ; ModelOutput < StringBuilder > output = core . openOutput ( context , StringBuilder . class , format , "" , "" , counter ) ; try { output . write ( new StringBuilder ( "" ) ) ; } finally { output . close ( ) ; } cleanup ( core ) ; assertThat ( new File ( mapping , "" ) . exists ( ) , is ( false ) ) ; } @ Test public void delete ( ) throws Exception { File file = new File ( mapping , "" ) ; put ( file , "" ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; assertThat ( file . exists ( ) , is ( true ) ) ; boolean result = core . delete ( "" , FilePattern . compile ( "" ) , true , counter ) ; assertThat ( result , is ( true ) ) ; assertThat ( file . exists ( ) , is ( false ) ) ; } @ Test public void delete_multifile ( ) throws Exception { File [ ] files = { new File ( mapping , "" ) , new File ( mapping , "" ) , new File ( mapping , "" ) , new File ( mapping , "" ) , } ; for ( File file : files ) { put ( file , "" ) ; } HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; for ( File file : files ) { assertThat ( file . exists ( ) , is ( true ) ) ; } boolean result = core . delete ( "" , FilePattern . compile ( "" ) , true , counter ) ; assertThat ( result , is ( true ) ) ; for ( File file : files ) { assertThat ( file . exists ( ) , is ( false ) ) ; } } @ Test public void delete_sharetemp ( ) throws Exception { HadoopDataSourceProfile shareTempProfile = new HadoopDataSourceProfile ( conf , profile . getId ( ) , profile . getContextPath ( ) , profile . getFileSystemPath ( ) , new Path ( profile . getFileSystemPath ( ) , "" ) ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( shareTempProfile ) ; File onProd = new File ( mapping , "" ) ; File onTemp = new File ( mapping , "" ) ; put ( onProd , "" ) ; put ( onTemp , "" ) ; assertThat ( onProd . exists ( ) , is ( true ) ) ; assertThat ( onTemp . exists ( ) , is ( true ) ) ; boolean result = core . delete ( "" , FilePattern . compile ( "" ) , true , counter ) ; assertThat ( result , is ( true ) ) ; assertThat ( onProd . exists ( ) , is ( false ) ) ; assertThat ( onTemp . exists ( ) , is ( true ) ) ; } @ Test public void delete_all ( ) throws Exception { File file = new File ( mapping , "" ) ; put ( file , "" ) ; HadoopDataSourceCore core = new HadoopDataSourceCore ( profile ) ; assertThat ( file . exists ( ) , is ( true ) ) ; boolean result = core . delete ( "" , FilePattern . compile ( "" ) , true , counter ) ; assertThat ( result , is ( true ) ) ; assertThat ( file . exists ( ) , is ( false ) ) ; assertThat ( "" , mapping . exists ( ) , is ( true ) ) ; } private List < String > consume ( HadoopDataSourceCore core , List < DirectInputFragment > fragments ) throws IOException , InterruptedException { List < String > results = new ArrayList < String > ( ) ; for ( DirectInputFragment fragment : fragments ) { ModelInput < StringBuilder > input = core . openInput ( StringBuilder . class , format , fragment , counter ) ; try { StringBuilder buf = new StringBuilder ( ) ; while ( input . readTo ( buf ) ) { results . add ( buf . toString ( ) ) ; } } finally { input . close ( ) ; } } return results ; } private List < String > get ( File target ) throws IOException { Scanner s = new Scanner ( target , "" ) ; try { List < String > results = new ArrayList < String > ( ) ; while ( s . hasNextLine ( ) ) { results . add ( s . nextLine ( ) ) ; } return results ; } finally { s . close ( ) ; } } private void put ( File target , String ... contents ) throws IOException { target . getParentFile ( ) . mkdirs ( ) ; PrintWriter w = new PrintWriter ( target , "" ) ; try { for ( String line : contents ) { w . println ( line ) ; } } finally { w . close ( ) ; } } private void put ( File target , long size ) throws IOException { byte [ ] buf = "" . getBytes ( ) ; long rest = size ; target . getParentFile ( ) . mkdirs ( ) ; OutputStream out = new FileOutputStream ( target ) ; try { OutputStream bufferred = new BufferedOutputStream ( out ) ; while ( rest > ) { int count = ( int ) Math . min ( buf . length , rest ) ; bufferred . write ( buf , , count ) ; rest -= count ; } bufferred . close ( ) ; } finally { out . close ( ) ; } } private void setup ( HadoopDataSourceCore core ) throws IOException , InterruptedException { core . setupTransactionOutput ( context . getTransactionContext ( ) ) ; core . setupAttemptOutput ( context ) ; } private void commit ( HadoopDataSourceCore core ) throws IOException , InterruptedException { commitAttempt ( core ) ; commitTransaction ( core ) ; } private void commitAttempt ( HadoopDataSourceCore core ) throws IOException , InterruptedException { core . commitAttemptOutput ( context ) ; core . cleanupAttemptOutput ( context ) ; } private void commitTransaction ( HadoopDataSourceCore core ) throws IOException , InterruptedException { core . commitTransactionOutput ( context . getTransactionContext ( ) ) ; core . cleanupTransactionOutput ( context . getTransactionContext ( ) ) ; } private void cleanup ( HadoopDataSourceCore core ) throws IOException , InterruptedException { core . cleanupAttemptOutput ( context ) ; core . cleanupTransactionOutput ( context . getTransactionContext ( ) ) ; } private static class MockStreamFormat extends BinaryStreamFormat < StringBuilder > { MockStreamFormat ( ) { return ; } @ Override public Class < StringBuilder > getSupportedType ( ) { return StringBuilder . class ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return ; } @ Override public ModelInput < StringBuilder > createInput ( Class < ? extends StringBuilder > dataType , String path , InputStream stream , long offset , long fragmentSize ) throws IOException , InterruptedException { final Scanner s = new Scanner ( stream , "" ) ; return new ModelInput < StringBuilder > ( ) { @ Override public boolean readTo ( StringBuilder model ) throws IOException { if ( s . hasNextLine ( ) ) { model . delete ( , model . length ( ) ) ; model . append ( s . nextLine ( ) ) ; return true ; } return false ; } @ Override public void close ( ) throws IOException { s . close ( ) ; } } ; } @ Override public ModelOutput < StringBuilder > createOutput ( Class < ? extends StringBuilder > dataType , String path , OutputStream stream ) throws IOException , InterruptedException { final PrintWriter w = new PrintWriter ( new OutputStreamWriter ( stream ) ) ; return new ModelOutput < StringBuilder > ( ) { @ Override public void write ( StringBuilder model ) throws IOException { w . println ( model . toString ( ) ) ; } @ Override public void close ( ) throws IOException { w . close ( ) ; } } ; } } private static class MockFileFormat extends HadoopFileFormat < StringBuilder > { private final MockStreamFormat format = new MockStreamFormat ( ) ; MockFileFormat ( ) { return ; } @ Override public Class < StringBuilder > getSupportedType ( ) { return format . getSupportedType ( ) ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return format . getPreferredFragmentSize ( ) ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return format . getMinimumFragmentSize ( ) ; } @ Override public ModelInput < StringBuilder > createInput ( Class < ? extends StringBuilder > dataType , FileSystem fileSystem , Path path , long offset , long fragmentSize , Counter counter ) throws IOException , InterruptedException { FileSystem fs = FileSystem . get ( path . toUri ( ) , getConf ( ) ) ; FSDataInputStream in = fs . open ( path ) ; boolean succeed = false ; try { in . seek ( offset ) ; ModelInput < StringBuilder > result = format . createInput ( dataType , path . toString ( ) , new CountInputStream ( in , counter ) , offset , fragmentSize ) ; succeed = true ; return result ; } finally { if ( succeed == false ) { in . close ( ) ; } } } @ Override public ModelOutput < StringBuilder > createOutput ( Class < ? extends StringBuilder > dataType , FileSystem fileSystem , Path path , Counter counter ) throws IOException , InterruptedException { FileSystem fs = FileSystem . get ( path . toUri ( ) , getConf ( ) ) ; FSDataOutputStream out = fs . create ( path ) ; return format . createOutput ( dataType , path . toString ( ) , new CountOutputStream ( out , counter ) ) ; } } } package com . asakusafw . runtime . directio . hadoop ; import static com . asakusafw . runtime . directio . hadoop . HadoopDataSourceProfile . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . URI ; import java . util . HashMap ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . FilterFileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . fs . RawLocalFileSystem ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . DirectDataSourceProfile ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class HadoopDataSourceProfileTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void convert ( ) throws Exception { Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_PATH , folder . getRoot ( ) . getCanonicalFile ( ) . toURI ( ) . toString ( ) ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; Configuration conf = new Configuration ( ) ; HadoopDataSourceProfile result = HadoopDataSourceProfile . convert ( profile , conf ) ; assertThat ( result . getId ( ) , is ( "" ) ) ; assertThat ( result . getContextPath ( ) , is ( "" ) ) ; assertThat ( result . getFileSystem ( ) . getUri ( ) . getScheme ( ) , is ( "" ) ) ; assertThat ( new File ( result . getFileSystemPath ( ) . toUri ( ) ) , is ( folder . getRoot ( ) ) ) ; assertThat ( new File ( result . getTemporaryFileSystemPath ( ) . getParent ( ) . toUri ( ) ) , is ( folder . getRoot ( ) ) ) ; assertThat ( result . isOutputStaging ( ) , is ( true ) ) ; assertThat ( result . isOutputStreaming ( ) , is ( true ) ) ; assertThat ( result . isCombineBlocks ( ) , is ( true ) ) ; assertThat ( result . isSplitBlocks ( ) , is ( true ) ) ; assertThat ( result . getKeepAliveInterval ( ) , is ( ) ) ; } @ Test ( expected = IOException . class ) public void convert_nopath ( ) throws Exception { Map < String , String > attributes = new HashMap < String , String > ( ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; Configuration conf = new Configuration ( ) ; HadoopDataSourceProfile . convert ( profile , conf ) ; } @ Test public void convert_relpath ( ) throws Exception { Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_PATH , "" ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; Configuration conf = new Configuration ( ) ; HadoopDataSourceProfile result = HadoopDataSourceProfile . convert ( profile , conf ) ; FileSystem defaultFs = FileSystem . get ( conf ) ; Path path = new Path ( defaultFs . getWorkingDirectory ( ) , "" ) . makeQualified ( defaultFs ) ; assertThat ( result . getFileSystem ( ) . getCanonicalServiceName ( ) , is ( defaultFs . getCanonicalServiceName ( ) ) ) ; assertThat ( result . getFileSystemPath ( ) , is ( path ) ) ; } @ Test public void convert_all ( ) throws Exception { File prod = folder . newFolder ( "" ) ; File temp = folder . newFolder ( "" ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_PATH , prod . getCanonicalFile ( ) . toURI ( ) . toString ( ) ) ; attributes . put ( KEY_TEMP , temp . getCanonicalFile ( ) . toURI ( ) . toString ( ) ) ; attributes . put ( KEY_MIN_FRAGMENT , "" ) ; attributes . put ( KEY_PREF_FRAGMENT , "" ) ; attributes . put ( KEY_OUTPUT_STAGING , "" ) ; attributes . put ( KEY_OUTPUT_STREAMING , "" ) ; attributes . put ( KEY_SPLIT_BLOCKS , "" ) ; attributes . put ( KEY_COMBINE_BLOCKS , "" ) ; attributes . put ( KEY_KEEPALIVE_INTERVAL , "" ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; Configuration conf = new Configuration ( ) ; HadoopDataSourceProfile result = HadoopDataSourceProfile . convert ( profile , conf ) ; assertThat ( result . getId ( ) , is ( "" ) ) ; assertThat ( result . getContextPath ( ) , is ( "" ) ) ; assertThat ( result . getFileSystem ( ) . getUri ( ) . getScheme ( ) , is ( "" ) ) ; assertThat ( new File ( result . getFileSystemPath ( ) . toUri ( ) ) , is ( prod ) ) ; assertThat ( new File ( result . getTemporaryFileSystemPath ( ) . toUri ( ) ) , is ( temp ) ) ; assertThat ( result . getMinimumFragmentSize ( new MockFormat ( , - ) ) , is ( ) ) ; assertThat ( result . getMinimumFragmentSize ( new MockFormat ( , - ) ) , is ( ) ) ; assertThat ( result . getMinimumFragmentSize ( new MockFormat ( - , - ) ) , is ( lessThan ( ) ) ) ; assertThat ( result . getPreferredFragmentSize ( new MockFormat ( , - ) ) , is ( ) ) ; assertThat ( result . getPreferredFragmentSize ( new MockFormat ( , ) ) , is ( ) ) ; assertThat ( result . getPreferredFragmentSize ( new MockFormat ( - , - ) ) , is ( lessThan ( ) ) ) ; assertThat ( result . isOutputStaging ( ) , is ( false ) ) ; assertThat ( result . isOutputStreaming ( ) , is ( false ) ) ; assertThat ( result . isCombineBlocks ( ) , is ( false ) ) ; assertThat ( result . isSplitBlocks ( ) , is ( false ) ) ; assertThat ( result . getKeepAliveInterval ( ) , is ( ) ) ; } @ Test ( expected = IOException . class ) public void convert_inconsistent_fs ( ) throws Exception { Configuration conf = new Configuration ( ) ; conf . setClass ( "" , MockFs . class , FileSystem . class ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_PATH , folder . getRoot ( ) . toURI ( ) . toString ( ) ) ; attributes . put ( KEY_TEMP , "" + folder . getRoot ( ) . toURI ( ) . toString ( ) ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; HadoopDataSourceProfile . convert ( profile , conf ) ; } @ Test ( expected = IOException . class ) public void convert_minSize_notInt ( ) throws Exception { Configuration conf = new Configuration ( ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_MIN_FRAGMENT , "" ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; HadoopDataSourceProfile . convert ( profile , conf ) ; } @ Test ( expected = IOException . class ) public void convert_minSize_zero ( ) throws Exception { Configuration conf = new Configuration ( ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_MIN_FRAGMENT , "" ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; HadoopDataSourceProfile . convert ( profile , conf ) ; } @ Test ( expected = IOException . class ) public void convert_prefSize_notInt ( ) throws Exception { Configuration conf = new Configuration ( ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_PREF_FRAGMENT , "" ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; HadoopDataSourceProfile . convert ( profile , conf ) ; } @ Test ( expected = IOException . class ) public void convert_prefSize_zero ( ) throws Exception { Configuration conf = new Configuration ( ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_PREF_FRAGMENT , "" ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; HadoopDataSourceProfile . convert ( profile , conf ) ; } @ Test ( expected = IOException . class ) public void convert_unknown_properties ( ) throws Exception { Configuration conf = new Configuration ( ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( KEY_PATH , folder . getRoot ( ) . getCanonicalFile ( ) . toURI ( ) . toString ( ) ) ; attributes . put ( "" , "" ) ; DirectDataSourceProfile profile = new DirectDataSourceProfile ( "" , HadoopDataSource . class , "" , attributes ) ; HadoopDataSourceProfile . convert ( profile , conf ) ; } public static class MockFs extends FilterFileSystem { public MockFs ( ) { super ( new RawLocalFileSystem ( ) ) ; } @ Override public URI getUri ( ) { return URI . create ( "" ) ; } } private static class MockFormat extends BinaryStreamFormat < Object > { private final long min ; private final long pref ; MockFormat ( long min , long pref ) { this . min = min ; this . pref = pref ; } @ Override public Class < Object > getSupportedType ( ) { return Object . class ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return pref ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return min ; } @ Override public ModelInput < Object > createInput ( Class < ? extends Object > dataType , String path , InputStream stream , long offset , long fragmentSize ) throws IOException , InterruptedException { throw new UnsupportedOperationException ( ) ; } @ Override public ModelOutput < Object > createOutput ( Class < ? extends Object > dataType , String path , OutputStream stream ) throws IOException , InterruptedException { throw new UnsupportedOperationException ( ) ; } } } package com . asakusafw . runtime . directio . hadoop ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import com . asakusafw . runtime . directio . AbstractDirectDataSource ; import com . asakusafw . runtime . directio . MockDirectDataSource ; public class MockHadoopDataSource extends MockDirectDataSource implements Configurable { Configuration conf ; @ Override public void setConf ( Configuration conf ) { this . conf = conf ; } @ Override public Configuration getConf ( ) { return conf ; } } package com . asakusafw . runtime . directio . hadoop ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . util . Arrays ; import java . util . List ; import java . util . Scanner ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . junit . After ; import org . junit . Assume ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . directio . BinaryStreamFormat ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectDataSourceProvider ; import com . asakusafw . runtime . directio . DirectDataSourceRepository ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . OutputTransactionContext ; import com . asakusafw . runtime . directio . hadoop . DirectIoTransactionEditor . TransactionInfo ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class DirectIoTransactionEditorTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private Configuration conf ; private DirectIoTransactionEditor testee ; private DirectDataSourceRepository repo ; private File production1 ; private File production2 ; private File temporary ; @ Before public void setUp ( ) throws Exception { File writeTest = folder . newFolder ( "" ) ; Assume . assumeTrue ( writable ( writeTest , false ) ) ; try { new File ( writeTest , "" ) . createNewFile ( ) ; Assume . assumeTrue ( false ) ; } catch ( IOException e ) { } this . conf = new Configuration ( ) ; conf . set ( HadoopDataSourceUtil . KEY_SYSTEM_DIR , folder . newFolder ( "" ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; temporary = folder . newFolder ( "" ) . getCanonicalFile ( ) ; production1 = folder . newFolder ( "" ) . getCanonicalFile ( ) ; production2 = folder . newFolder ( "" ) . getCanonicalFile ( ) ; HadoopDataSourceProfile profile1 = new HadoopDataSourceProfile ( conf , "" , "" , new Path ( production1 . toURI ( ) ) , new Path ( new File ( temporary , "" ) . toURI ( ) ) ) ; HadoopDataSourceProfile profile2 = new HadoopDataSourceProfile ( conf , "" , "" , new Path ( production2 . toURI ( ) ) , new Path ( new File ( temporary , "" ) . toURI ( ) ) ) ; repo = new DirectDataSourceRepository ( Arrays . asList ( new MockProvider ( profile1 ) , new MockProvider ( profile2 ) ) ) ; testee = new DirectIoTransactionEditor ( repo ) ; testee . setConf ( conf ) ; } @ After public void tearDown ( ) throws Exception { if ( production1 != null ) { writable ( production1 , true ) ; } if ( production2 != null ) { writable ( production2 , true ) ; } if ( temporary != null ) { writable ( temporary , true ) ; } } @ Test public void apply ( ) throws Exception { indoubt ( "" ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( testee . apply ( "" ) , is ( false ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( testee . apply ( "" ) , is ( true ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( testee . apply ( "" ) , is ( false ) ) ; } @ Test public void apply_partial ( ) throws Exception { indoubt ( "" ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; writable ( production1 , false ) ; try { testee . apply ( "" ) ; } catch ( IOException e ) { } assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; writable ( production1 , true ) ; assertThat ( testee . apply ( "" ) , is ( true ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( testee . apply ( "" ) , is ( false ) ) ; } @ Test public void abort ( ) throws Exception { indoubt ( "" ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( testee . abort ( "" ) , is ( false ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( testee . abort ( "" ) , is ( true ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( testee . abort ( "" ) , is ( false ) ) ; } @ Test public void abort_partial ( ) throws Exception { indoubt ( "" ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; writable ( production1 , false ) ; try { testee . apply ( "" ) ; } catch ( IOException e ) { } assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; writable ( production1 , true ) ; assertThat ( testee . abort ( "" ) , is ( true ) ) ; assertThat ( count ( production1 ) , is ( ) ) ; assertThat ( count ( production2 ) , is ( ) ) ; assertThat ( testee . abort ( "" ) , is ( false ) ) ; } @ Test public void list ( ) throws Exception { indoubt ( "" ) ; indoubt ( "" ) ; indoubt ( "" ) ; List < TransactionInfo > c1 = testee . list ( ) ; assertThat ( c1 . size ( ) , is ( ) ) ; get ( c1 , "" ) ; get ( c1 , "" ) ; get ( c1 , "" ) ; testee . apply ( "" ) ; List < TransactionInfo > c2 = testee . list ( ) ; assertThat ( c2 . size ( ) , is ( ) ) ; get ( c1 , "" ) ; get ( c1 , "" ) ; testee . apply ( "" ) ; List < TransactionInfo > c3 = testee . list ( ) ; assertThat ( c3 . size ( ) , is ( ) ) ; get ( c1 , "" ) ; testee . apply ( "" ) ; List < TransactionInfo > c4 = testee . list ( ) ; assertThat ( c4 . size ( ) , is ( ) ) ; } private boolean writable ( File target , boolean lock ) { if ( target . exists ( ) == false ) { return false ; } boolean succeed = true ; if ( target . isDirectory ( ) ) { for ( File child : target . listFiles ( ) ) { succeed &= writable ( child , lock ) ; } } return succeed && target . setWritable ( lock ) ; } private int count ( File dir ) { int count = ; for ( File file : dir . listFiles ( ) ) { if ( file . getName ( ) . startsWith ( "" ) == false ) { count ++ ; } } return count ; } private TransactionInfo get ( List < TransactionInfo > list , String executionId ) { for ( TransactionInfo commit : list ) { if ( commit . getExecutionId ( ) . equals ( executionId ) ) { return commit ; } } throw new AssertionError ( executionId ) ; } private void indoubt ( String executionId ) throws IOException , InterruptedException { Path txPath = HadoopDataSourceUtil . getTransactionInfoPath ( conf , executionId ) ; Path cmPath = HadoopDataSourceUtil . getCommitMarkPath ( conf , executionId ) ; FileSystem fs = txPath . getFileSystem ( conf ) ; fs . create ( txPath ) . close ( ) ; fs . create ( cmPath ) . close ( ) ; int index = ; for ( String path : repo . getContainerPaths ( ) ) { String id = repo . getRelatedId ( path ) ; DirectDataSource ds = repo . getRelatedDataSource ( path ) ; OutputTransactionContext txContext = HadoopDataSourceUtil . createContext ( executionId , id ) ; OutputAttemptContext aContext = new OutputAttemptContext ( txContext . getTransactionId ( ) , String . valueOf ( index ) , txContext . getOutputId ( ) , new Counter ( ) ) ; ds . setupTransactionOutput ( txContext ) ; ds . setupAttemptOutput ( aContext ) ; ModelOutput < StringBuilder > output = ds . openOutput ( aContext , StringBuilder . class , new MockFormat ( ) , "" , executionId , new Counter ( ) ) ; try { output . write ( new StringBuilder ( "" ) ) ; } finally { output . close ( ) ; } ds . commitAttemptOutput ( aContext ) ; ds . cleanupAttemptOutput ( aContext ) ; index ++ ; } } private static final class MockProvider implements DirectDataSourceProvider { HadoopDataSourceProfile profile ; MockProvider ( HadoopDataSourceProfile profile ) { this . profile = profile ; } @ Override public String getId ( ) { return profile . getId ( ) ; } @ Override public String getPath ( ) { return profile . getContextPath ( ) ; } @ Override public DirectDataSource newInstance ( ) throws IOException , InterruptedException { return new HadoopDataSourceCore ( profile ) ; } } private static class MockFormat extends BinaryStreamFormat < StringBuilder > { MockFormat ( ) { return ; } @ Override public Class < StringBuilder > getSupportedType ( ) { return StringBuilder . class ; } @ Override public long getPreferredFragmentSize ( ) throws IOException , InterruptedException { return - ; } @ Override public long getMinimumFragmentSize ( ) throws IOException , InterruptedException { return ; } @ Override public ModelInput < StringBuilder > createInput ( Class < ? extends StringBuilder > dataType , String path , InputStream stream , long offset , long fragmentSize ) throws IOException , InterruptedException { final Scanner s = new Scanner ( stream , "" ) ; return new ModelInput < StringBuilder > ( ) { @ Override public boolean readTo ( StringBuilder model ) throws IOException { if ( s . hasNextLine ( ) ) { model . delete ( , model . length ( ) ) ; model . append ( s . nextLine ( ) ) ; return true ; } return false ; } @ Override public void close ( ) throws IOException { s . close ( ) ; } } ; } @ Override public ModelOutput < StringBuilder > createOutput ( Class < ? extends StringBuilder > dataType , String path , OutputStream stream ) throws IOException , InterruptedException { final PrintWriter w = new PrintWriter ( new OutputStreamWriter ( stream ) ) ; return new ModelOutput < StringBuilder > ( ) { @ Override public void write ( StringBuilder model ) throws IOException { w . println ( model . toString ( ) ) ; } @ Override public void close ( ) throws IOException { w . close ( ) ; } } ; } } } package com . asakusafw . runtime . directio . keepalive ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . runtime . directio . Counter ; public class HeartbeatKeeperTest { private HeartbeatKeeper keeper ; @ Before public void setUp ( ) throws Exception { keeper = new HeartbeatKeeper ( ) ; } @ After public void tearDown ( ) throws Exception { keeper . close ( ) ; } @ Test public void simple ( ) throws Exception { Mock mock = new Mock ( ) ; long s0 = mock . count ; assertThat ( s0 , is ( ) ) ; keeper . register ( mock ) ; long s11 = mock . count ; Thread . sleep ( ) ; long s12 = mock . count ; assertThat ( s12 , greaterThan ( s11 ) ) ; keeper . unregister ( mock ) ; long s21 = mock . count ; Thread . sleep ( ) ; long s22 = mock . count ; assertThat ( s22 , is ( s21 ) ) ; keeper . unregister ( mock ) ; } private static class Mock extends Counter { volatile long count ; Mock ( ) { return ; } @ Override protected void onChanged ( ) { count ++ ; } } } package com . asakusafw . runtime . directio . keepalive ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import org . junit . After ; import org . junit . Test ; import com . asakusafw . runtime . directio . Counter ; import com . asakusafw . runtime . directio . DataFormat ; import com . asakusafw . runtime . directio . DirectDataSource ; import com . asakusafw . runtime . directio . DirectInputFragment ; import com . asakusafw . runtime . directio . OutputAttemptContext ; import com . asakusafw . runtime . directio . OutputTransactionContext ; import com . asakusafw . runtime . directio . ResourceInfo ; import com . asakusafw . runtime . directio . ResourcePattern ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public class KeepAliveDataSourceTest { final KeepAliveDataSource ds = new KeepAliveDataSource ( new WaitDataSource ( ) , ) ; final Mock counter = new Mock ( ) ; @ After public void tearDown ( ) throws Exception { try { assertThat ( ds . heartbeat . isEmpty ( ) , is ( true ) ) ; } finally { ds . heartbeat . close ( ) ; } } @ Test public void testOpenInput ( ) throws Exception { ModelInput < Object > input = ds . openInput ( null , null , null , counter ) ; try { assertKeepAlive ( true ) ; } finally { input . close ( ) ; } assertKeepAlive ( false ) ; } @ Test public void testOpenOutput ( ) throws Exception { ModelOutput < Object > output = ds . openOutput ( null , null , null , null , null , counter ) ; try { assertKeepAlive ( true ) ; } finally { output . close ( ) ; } assertKeepAlive ( false ) ; } @ Test public void testSetupAttemptOutput ( ) throws Exception { OutputAttemptContext context = context ( ) ; long s1 = counter . count ; ds . setupAttemptOutput ( context ) ; long s2 = counter . count ; assertThat ( s2 , greaterThan ( s1 ) ) ; assertKeepAlive ( false ) ; } @ Test public void testCommitAttemptOutput ( ) throws Exception { OutputAttemptContext context = context ( ) ; long s1 = counter . count ; ds . commitAttemptOutput ( context ) ; long s2 = counter . count ; assertThat ( s2 , greaterThan ( s1 ) ) ; assertKeepAlive ( false ) ; } @ Test public void testCleanupAttemptOutput ( ) throws Exception { OutputAttemptContext context = context ( ) ; long s1 = counter . count ; ds . cleanupAttemptOutput ( context ) ; long s2 = counter . count ; assertThat ( s2 , greaterThan ( s1 ) ) ; assertKeepAlive ( false ) ; } @ Test public void testSetupTransactionOutput ( ) throws Exception { OutputAttemptContext context = context ( ) ; long s1 = counter . count ; ds . setupTransactionOutput ( context . getTransactionContext ( ) ) ; long s2 = counter . count ; assertThat ( s2 , greaterThan ( s1 ) ) ; assertKeepAlive ( false ) ; } @ Test public void testCommitTransactionOutput ( ) throws Exception { OutputAttemptContext context = context ( ) ; long s1 = counter . count ; ds . commitTransactionOutput ( context . getTransactionContext ( ) ) ; long s2 = counter . count ; assertThat ( s2 , greaterThan ( s1 ) ) ; assertKeepAlive ( false ) ; } @ Test public void testCleanupTransactionOutput ( ) throws Exception { OutputAttemptContext context = context ( ) ; long s1 = counter . count ; ds . cleanupTransactionOutput ( context . getTransactionContext ( ) ) ; long s2 = counter . count ; assertThat ( s2 , greaterThan ( s1 ) ) ; assertKeepAlive ( false ) ; } private OutputAttemptContext context ( ) { return new OutputAttemptContext ( "" , "" , "" , counter ) ; } private void assertKeepAlive ( boolean b ) throws InterruptedException { long s1 = counter . count ; Thread . sleep ( ) ; long s2 = counter . count ; assertThat ( s2 , b ? greaterThan ( s1 ) : is ( s1 ) ) ; } private static class Mock extends Counter { volatile long count ; Mock ( ) { return ; } @ Override protected void onChanged ( ) { count ++ ; } } private static class WaitDataSource implements DirectDataSource { public WaitDataSource ( ) { return ; } @ Override public < T > List < DirectInputFragment > findInputFragments ( Class < ? extends T > dataType , DataFormat < T > format , String basePath , ResourcePattern resourcePattern ) throws IOException , InterruptedException { return Collections . emptyList ( ) ; } @ Override public < T > ModelInput < T > openInput ( Class < ? extends T > dataType , DataFormat < T > format , DirectInputFragment fragment , Counter counter ) throws IOException , InterruptedException { return new ModelInput < T > ( ) { @ Override public boolean readTo ( T model ) throws IOException { return false ; } @ Override public void close ( ) throws IOException { return ; } } ; } @ Override public < T > ModelOutput < T > openOutput ( OutputAttemptContext context , Class < ? extends T > dataType , DataFormat < T > format , String basePath , String resourcePath , Counter counter ) throws IOException , InterruptedException { return new ModelOutput < T > ( ) { @ Override public void write ( T model ) throws IOException { return ; } @ Override public void close ( ) throws IOException { return ; } } ; } @ Override public List < ResourceInfo > list ( String basePath , ResourcePattern resourcePattern , Counter counter ) throws IOException , InterruptedException { return Collections . emptyList ( ) ; } @ Override public boolean delete ( String basePath , ResourcePattern resourcePattern , boolean recursive , Counter counter ) throws IOException , InterruptedException { return false ; } @ Override public void setupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { Thread . sleep ( ) ; } @ Override public void commitAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { Thread . sleep ( ) ; } @ Override public void cleanupAttemptOutput ( OutputAttemptContext context ) throws IOException , InterruptedException { Thread . sleep ( ) ; } @ Override public void setupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { Thread . sleep ( ) ; } @ Override public void commitTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { Thread . sleep ( ) ; } @ Override public void cleanupTransactionOutput ( OutputTransactionContext context ) throws IOException , InterruptedException { Thread . sleep ( ) ; } } } package com . asakusafw . runtime . directio ; import static com . asakusafw . runtime . directio . FilePattern . PatternElementKind . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Test ; import com . asakusafw . runtime . directio . FilePattern . PatternElement ; import com . asakusafw . runtime . directio . FilePattern . PatternElementKind ; import com . asakusafw . runtime . directio . FilePattern . Segment ; public class FilePatternTest { @ Test public void traverse ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( true ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( ) ) ) ; } @ Test public void token ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; assertThat ( compiled . containsVariables ( ) , is ( false ) ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( TOKEN ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; } @ Test public void wildcard ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; assertThat ( compiled . containsVariables ( ) , is ( false ) ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( WILDCARD ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; } @ Test public void variable ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; assertThat ( compiled . containsVariables ( ) , is ( true ) ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( VARIABLE ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; } @ Test public void variable_empty ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( VARIABLE ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; } @ Test public void selection ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; assertThat ( compiled . containsVariables ( ) , is ( false ) ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( SELECTION ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; } @ Test public void containsWildcard ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( TOKEN , WILDCARD , TOKEN ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" , "" , "" ) ) ) ; } @ Test public void selection_containsEmpty ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; assertThat ( compiled . containsVariables ( ) , is ( false ) ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( SELECTION ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; } @ Test public void selection_empty ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; assertThat ( compiled . containsVariables ( ) , is ( false ) ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( SELECTION ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; } @ Test public void segments ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( TOKEN ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( TOKEN ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( TOKEN ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; } @ Test public void all_csv ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( true ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( WILDCARD , TOKEN ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" , "" ) ) ) ; } @ Test public void complex ( ) { FilePattern compiled = FilePattern . compile ( "" ) ; assertThat ( compiled . containsVariables ( ) , is ( true ) ) ; List < Segment > segments = compiled . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( TOKEN ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( true ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( SELECTION ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" ) ) ) ; assertThat ( segments . get ( ) . isTraverse ( ) , is ( false ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( kind ( VARIABLE , TOKEN , WILDCARD , TOKEN ) ) ) ; assertThat ( segments . get ( ) . getElements ( ) , is ( token ( "" , "" , "" , "" ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void consecutive_wildcard ( ) { FilePattern . compile ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void doller ( ) { FilePattern . compile ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void variable_unclosed ( ) { FilePattern . compile ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void selection_unclosed ( ) { FilePattern . compile ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void selection_invalid_character ( ) { FilePattern . compile ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_character ( ) { FilePattern . compile ( "" ) ; } private Matcher < List < PatternElement > > kind ( final PatternElementKind ... kinds ) { return new BaseMatcher < List < PatternElement > > ( ) { @ Override public boolean matches ( Object obj ) { @ SuppressWarnings ( "" ) List < PatternElement > elements = ( List < PatternElement > ) obj ; if ( elements . size ( ) != kinds . length ) { return false ; } for ( int i = ; i < kinds . length ; i ++ ) { if ( elements . get ( i ) . getKind ( ) != kinds [ i ] ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( Arrays . toString ( kinds ) ) ; } } ; } private Matcher < List < PatternElement > > token ( final String ... tokens ) { return new BaseMatcher < List < PatternElement > > ( ) { @ Override public boolean matches ( Object obj ) { @ SuppressWarnings ( "" ) List < PatternElement > elements = ( List < PatternElement > ) obj ; if ( elements . size ( ) != tokens . length ) { return false ; } for ( int i = ; i < tokens . length ; i ++ ) { if ( elements . get ( i ) . getToken ( ) . equals ( tokens [ i ] ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( Arrays . toString ( tokens ) ) ; } } ; } } package $ { package } . batch ; import $ { package } . jobflow . CategorySummaryJob ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class SummarizeBatch extends BatchDescription { @ Override protected void describe ( ) { run ( CategorySummaryJob . class ) . soon ( ) ; } } package $ { package } . operator ; import java . util . List ; import $ { package } . modelgen . dmdl . model . ImCategorySummary ; import $ { package } . modelgen . dmdl . model . JoinedSalesInfo ; import $ { package } . modelgen . table . model . ErrorRecord ; import $ { package } . modelgen . table . model . ItemInfo ; import $ { package } . modelgen . table . model . SalesDetail ; import $ { package } . modelgen . table . model . StoreInfo ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . MasterCheck ; import com . asakusafw . vocabulary . operator . MasterJoin ; import com . asakusafw . vocabulary . operator . MasterSelection ; import com . asakusafw . vocabulary . operator . Summarize ; import com . asakusafw . vocabulary . operator . Update ; public abstract class CategorySummaryOperator { @ MasterCheck public abstract boolean checkStore ( @ Key ( group = "" ) StoreInfo info , @ Key ( group = "" ) SalesDetail sales ) ; @ MasterJoin ( selection = "" ) public abstract JoinedSalesInfo joinItemInfo ( ItemInfo info , SalesDetail sales ) ; private final Date dateBuffer = new Date ( ) ; @ MasterSelection public ItemInfo selectAvailableItem ( List < ItemInfo > candidates , SalesDetail sales ) { DateTime dateTime = sales . getSalesDateTime ( ) ; dateBuffer . setElapsedDays ( DateUtil . getDayFromDate ( dateTime . getYear ( ) , dateTime . getMonth ( ) , dateTime . getDay ( ) ) ) ; for ( ItemInfo item : candidates ) { if ( item . getBeginDate ( ) . compareTo ( dateBuffer ) <= && dateBuffer . compareTo ( item . getEndDate ( ) ) <= ) { return item ; } } return null ; } @ Summarize public abstract ImCategorySummary summarizeByCategory ( JoinedSalesInfo info ) ; @ Update public void setErrorMessage ( ErrorRecord record , String message ) { record . setSidOption ( null ) ; record . setMessageAsString ( message ) ; } } package $ { package } . jobflow ; import $ { package } . modelgen . table . model . ErrorRecord ; import com . asakusafw . vocabulary . bulkloader . DbExporterDescription ; public class ErrorRecordToJdbc extends DbExporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return ErrorRecord . class ; } } package $ { package } . jobflow ; import $ { package } . modelgen . table . model . CategorySummary ; import com . asakusafw . vocabulary . bulkloader . DbExporterDescription ; public class CategorySummaryToJdbc extends DbExporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return CategorySummary . class ; } } package $ { package } . jobflow ; import $ { package } . modelgen . table . model . CategorySummary ; import $ { package } . modelgen . table . model . ErrorRecord ; import $ { package } . modelgen . table . model . ItemInfo ; import $ { package } . modelgen . table . model . SalesDetail ; import $ { package } . modelgen . table . model . StoreInfo ; import $ { package } . operator . CategorySummaryOperatorFactory ; import $ { package } . operator . CategorySummaryOperatorFactory . CheckStore ; import $ { package } . operator . CategorySummaryOperatorFactory . JoinItemInfo ; import $ { package } . operator . CategorySummaryOperatorFactory . SetErrorMessage ; import $ { package } . operator . CategorySummaryOperatorFactory . SummarizeByCategory ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Extend ; @ JobFlow ( name = "" ) public class CategorySummaryJob extends FlowDescription { final In < SalesDetail > salesDetail ; final In < StoreInfo > storeInfo ; final In < ItemInfo > itemInfo ; final Out < CategorySummary > categorySummary ; final Out < ErrorRecord > errorRecord ; public CategorySummaryJob ( @ Import ( name = "" , description = SalesDetailFromJdbc . class ) In < SalesDetail > salesDetail , @ Import ( name = "" , description = StoreInfoFromJdbc . class ) In < StoreInfo > storeInfo , @ Import ( name = "" , description = ItemInfoFromJdbc . class ) In < ItemInfo > itemInfo , @ Export ( name = "" , description = CategorySummaryToJdbc . class ) Out < CategorySummary > categorySummary , @ Export ( name = "" , description = ErrorRecordToJdbc . class ) Out < ErrorRecord > errorRecord ) { this . salesDetail = salesDetail ; this . storeInfo = storeInfo ; this . itemInfo = itemInfo ; this . categorySummary = categorySummary ; this . errorRecord = errorRecord ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; CategorySummaryOperatorFactory operators = new CategorySummaryOperatorFactory ( ) ; CheckStore checkStore = operators . checkStore ( storeInfo , salesDetail ) ; JoinItemInfo joinItemInfo = operators . joinItemInfo ( itemInfo , checkStore . found ) ; SummarizeByCategory summarize = operators . summarizeByCategory ( joinItemInfo . joined ) ; Extend < CategorySummary > extendCategory = core . extend ( summarize . out , CategorySummary . class ) ; categorySummary . add ( extendCategory . out ) ; SetErrorMessage unknownStore = operators . setErrorMessage ( core . restructure ( checkStore . missed , ErrorRecord . class ) , "" ) ; errorRecord . add ( unknownStore . out ) ; SetErrorMessage unknownItem = operators . setErrorMessage ( core . restructure ( joinItemInfo . missed , ErrorRecord . class ) , "" ) ; errorRecord . add ( unknownItem . out ) ; } } package $ { package } . jobflow ; import $ { package } . modelgen . table . model . ItemInfo ; import com . asakusafw . vocabulary . bulkloader . DbImporterDescription ; public class ItemInfoFromJdbc extends DbImporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return ItemInfo . class ; } @ Override public LockType getLockType ( ) { return LockType . CHECK ; } } package $ { package } . jobflow ; import $ { package } . modelgen . table . model . SalesDetail ; import com . asakusafw . vocabulary . bulkloader . DbImporterDescription ; public class SalesDetailFromJdbc extends DbImporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return SalesDetail . class ; } @ Override public LockType getLockType ( ) { return LockType . TABLE ; } } package $ { package } . jobflow ; import $ { package } . modelgen . table . model . StoreInfo ; import com . asakusafw . vocabulary . bulkloader . DbImporterDescription ; public class StoreInfoFromJdbc extends DbImporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return StoreInfo . class ; } @ Override public LockType getLockType ( ) { return LockType . CHECK ; } @ Override public DataSize getDataSize ( ) { return DataSize . TINY ; } } package $ { package } . jobflow ; import org . junit . Test ; import $ { package } . jobflow . CategorySummaryJob ; import $ { package } . modelgen . table . model . CategorySummary ; import $ { package } . modelgen . table . model . ErrorRecord ; import $ { package } . modelgen . table . model . ItemInfo ; import $ { package } . modelgen . table . model . SalesDetail ; import $ { package } . modelgen . table . model . StoreInfo ; import $ { package } . util . CountVerifier ; import com . asakusafw . testdriver . JobFlowTester ; public class CategorySummaryJobTest { @ Test public void simple ( ) { run ( "" , ) ; } @ Test public void summarize ( ) { run ( "" , ) ; } @ Test public void available_date ( ) { run ( "" , ) ; } @ Test public void invalid_store ( ) { run ( "" , ) ; } private void run ( String dataSet , long errors ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setBatchArg ( "" , "" ) ; tester . input ( "" , StoreInfo . class ) . prepare ( "" ) ; tester . input ( "" , ItemInfo . class ) . prepare ( "" ) ; tester . input ( "" , SalesDetail . class ) . prepare ( dataSet + "" ) ; tester . output ( "" , CategorySummary . class ) . verify ( dataSet + "" , dataSet + "" ) ; tester . output ( "" , ErrorRecord . class ) . verify ( CountVerifier . factory ( errors ) ) ; tester . runTest ( CategorySummaryJob . class ) ; } } package $ { package } . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . List ; import org . junit . Test ; import $ { package } . modelgen . table . model . ItemInfo ; import $ { package } . modelgen . table . model . SalesDetail ; import $ { package } . operator . CategorySummaryOperator ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class CategorySummaryOperatorTest { @ Test public void selectAvailableItem ( ) { List < ItemInfo > candidates = new ArrayList < ItemInfo > ( ) ; candidates . add ( item ( "" , , ) ) ; candidates . add ( item ( "" , , ) ) ; candidates . add ( item ( "" , , ) ) ; CategorySummaryOperator operator = new CategorySummaryOperatorImpl ( ) ; ItemInfo item1 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item5 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item10 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item15 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item20 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item30 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item31 = operator . selectAvailableItem ( candidates , sales ( ) ) ; assertThat ( item1 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item5 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item10 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item15 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item20 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item30 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item31 , is ( nullValue ( ) ) ) ; } private SalesDetail sales ( int day ) { SalesDetail object = new SalesDetail ( ) ; object . setSalesDateTime ( new DateTime ( , , day , , , ) ) ; return object ; } private ItemInfo item ( String categoryCode , int begin , int end ) { ItemInfo object = new ItemInfo ( ) ; object . setCategoryCodeAsString ( categoryCode ) ; object . setBeginDate ( new Date ( , , begin ) ) ; object . setEndDate ( new Date ( , , end ) ) ; return object ; } } package $ { package } . util ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . Difference ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . Verifier ; import com . asakusafw . testdriver . core . VerifierFactory ; import com . asakusafw . testdriver . core . VerifyContext ; public class CountVerifier implements Verifier { private final long expected ; public CountVerifier ( long expected ) { this . expected = expected ; } public static VerifierFactory factory ( final long expected ) { return new VerifierFactory ( ) { @ Override public < T > Verifier createVerifier ( DataModelDefinition < T > definition , VerifyContext context ) { return new CountVerifier ( expected ) ; } } ; } @ Override public List < Difference > verify ( DataModelSource results ) throws IOException { long actual = ; while ( results . next ( ) != null ) { actual ++ ; } List < Difference > result = new ArrayList < Difference > ( ) ; if ( expected != actual ) { result . add ( createDifference ( actual ) ) ; } return result ; } private Difference createDifference ( long actual ) { PropertyName name = PropertyName . newInstance ( "" ) ; return new Difference ( new DataModelReflection ( Collections . singletonMap ( name , expected ) ) , new DataModelReflection ( Collections . singletonMap ( name , actual ) ) , "" ) ; } @ Override public void close ( ) throws IOException { return ; } } package $ { package } . jobflow ; import org . junit . Test ; import $ { package } . modelgen . dmdl . model . CategorySummary ; import $ { package } . modelgen . dmdl . model . ErrorRecord ; import $ { package } . modelgen . dmdl . model . ItemInfo ; import $ { package } . modelgen . dmdl . model . SalesDetail ; import $ { package } . modelgen . dmdl . model . StoreInfo ; import $ { package } . util . CountVerifier ; import com . asakusafw . testdriver . JobFlowTester ; public class CategorySummaryJobTest { @ Test public void simple ( ) { run ( "" , ) ; } @ Test public void summarize ( ) { run ( "" , ) ; } @ Test public void available_date ( ) { run ( "" , ) ; } @ Test public void invalid_store ( ) { run ( "" , ) ; } private void run ( String dataSet , long errors ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setBatchArg ( "" , "" ) ; tester . input ( "" , StoreInfo . class ) . prepare ( "" ) ; tester . input ( "" , ItemInfo . class ) . prepare ( "" ) ; tester . input ( "" , SalesDetail . class ) . prepare ( dataSet + "" ) ; tester . output ( "" , CategorySummary . class ) . verify ( dataSet + "" , dataSet + "" ) ; tester . output ( "" , ErrorRecord . class ) . verify ( CountVerifier . factory ( errors ) ) ; tester . runTest ( CategorySummaryJob . class ) ; } } package $ { package } . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . List ; import org . junit . Test ; import $ { package } . modelgen . dmdl . model . ItemInfo ; import $ { package } . modelgen . dmdl . model . SalesDetail ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class CategorySummaryOperatorTest { @ Test public void selectAvailableItem ( ) { List < ItemInfo > candidates = new ArrayList < ItemInfo > ( ) ; candidates . add ( item ( "" , , ) ) ; candidates . add ( item ( "" , , ) ) ; candidates . add ( item ( "" , , ) ) ; CategorySummaryOperator operator = new CategorySummaryOperatorImpl ( ) ; ItemInfo item1 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item5 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item10 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item15 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item20 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item30 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item31 = operator . selectAvailableItem ( candidates , sales ( ) ) ; assertThat ( item1 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item5 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item10 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item15 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item20 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item30 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item31 , is ( nullValue ( ) ) ) ; } private SalesDetail sales ( int day ) { SalesDetail object = new SalesDetail ( ) ; object . setSalesDateTime ( new DateTime ( , , day , , , ) ) ; return object ; } private ItemInfo item ( String categoryCode , int begin , int end ) { ItemInfo object = new ItemInfo ( ) ; object . setCategoryCodeAsString ( categoryCode ) ; object . setBeginDate ( new Date ( , , begin ) ) ; object . setEndDate ( new Date ( , , end ) ) ; return object ; } } package $ { package } . util ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . Difference ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . Verifier ; import com . asakusafw . testdriver . core . VerifierFactory ; import com . asakusafw . testdriver . core . VerifyContext ; public class CountVerifier implements Verifier { private final long expected ; public CountVerifier ( long expected ) { this . expected = expected ; } public static VerifierFactory factory ( final long expected ) { return new VerifierFactory ( ) { @ Override public < T > Verifier createVerifier ( DataModelDefinition < T > definition , VerifyContext context ) { return new CountVerifier ( expected ) ; } } ; } @ Override public List < Difference > verify ( DataModelSource results ) throws IOException { long actual = ; while ( results . next ( ) != null ) { actual ++ ; } List < Difference > result = new ArrayList < Difference > ( ) ; if ( expected != actual ) { result . add ( createDifference ( actual ) ) ; } return result ; } private Difference createDifference ( long actual ) { PropertyName name = PropertyName . newInstance ( "" ) ; return new Difference ( new DataModelReflection ( Collections . singletonMap ( name , expected ) ) , new DataModelReflection ( Collections . singletonMap ( name , actual ) ) , "" ) ; } @ Override public void close ( ) throws IOException { return ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . csv . AbstractStoreInfoCsvInputDescription ; public class StoreInfoFromCsv extends AbstractStoreInfoCsvInputDescription { @ Override public String getBasePath ( ) { return "" ; } @ Override public String getResourcePattern ( ) { return "" ; } @ Override public DataSize getDataSize ( ) { return DataSize . TINY ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . model . CategorySummary ; import $ { package } . modelgen . dmdl . model . ErrorRecord ; import $ { package } . modelgen . dmdl . model . ItemInfo ; import $ { package } . modelgen . dmdl . model . SalesDetail ; import $ { package } . modelgen . dmdl . model . StoreInfo ; import $ { package } . operator . CategorySummaryOperatorFactory ; import $ { package } . operator . CategorySummaryOperatorFactory . CheckStore ; import $ { package } . operator . CategorySummaryOperatorFactory . JoinItemInfo ; import $ { package } . operator . CategorySummaryOperatorFactory . SetErrorMessage ; import $ { package } . operator . CategorySummaryOperatorFactory . SummarizeByCategory ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ JobFlow ( name = "" ) public class CategorySummaryJob extends FlowDescription { final In < SalesDetail > salesDetail ; final In < StoreInfo > storeInfo ; final In < ItemInfo > itemInfo ; final Out < CategorySummary > categorySummary ; final Out < ErrorRecord > errorRecord ; public CategorySummaryJob ( @ Import ( name = "" , description = SalesDetailFromCsv . class ) In < SalesDetail > salesDetail , @ Import ( name = "" , description = StoreInfoFromCsv . class ) In < StoreInfo > storeInfo , @ Import ( name = "" , description = ItemInfoFromCsv . class ) In < ItemInfo > itemInfo , @ Export ( name = "" , description = CategorySummaryToCsv . class ) Out < CategorySummary > categorySummary , @ Export ( name = "" , description = ErrorRecordToCsv . class ) Out < ErrorRecord > errorRecord ) { this . salesDetail = salesDetail ; this . storeInfo = storeInfo ; this . itemInfo = itemInfo ; this . categorySummary = categorySummary ; this . errorRecord = errorRecord ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; CategorySummaryOperatorFactory operators = new CategorySummaryOperatorFactory ( ) ; CheckStore checkStore = operators . checkStore ( storeInfo , salesDetail ) ; JoinItemInfo joinItemInfo = operators . joinItemInfo ( itemInfo , checkStore . found ) ; SummarizeByCategory summarize = operators . summarizeByCategory ( joinItemInfo . joined ) ; categorySummary . add ( summarize . out ) ; SetErrorMessage unknownStore = operators . setErrorMessage ( core . restructure ( checkStore . missed , ErrorRecord . class ) , "" ) ; errorRecord . add ( unknownStore . out ) ; SetErrorMessage unknownItem = operators . setErrorMessage ( core . restructure ( joinItemInfo . missed , ErrorRecord . class ) , "" ) ; errorRecord . add ( unknownItem . out ) ; } } package $ { package } . jobflow ; import java . util . Arrays ; import java . util . List ; import $ { package } . modelgen . dmdl . csv . AbstractErrorRecordCsvOutputDescription ; public class ErrorRecordToCsv extends AbstractErrorRecordCsvOutputDescription { @ Override public String getBasePath ( ) { return "" ; } @ Override public String getResourcePattern ( ) { return "" ; } @ Override public List < String > getOrder ( ) { return Arrays . asList ( "" ) ; } } package $ { package } . jobflow ; import java . util . Arrays ; import java . util . List ; import $ { package } . modelgen . dmdl . csv . AbstractCategorySummaryCsvOutputDescription ; public class CategorySummaryToCsv extends AbstractCategorySummaryCsvOutputDescription { @ Override public String getBasePath ( ) { return "" ; } @ Override public String getResourcePattern ( ) { return "" ; } @ Override public List < String > getOrder ( ) { return Arrays . asList ( "" ) ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . csv . AbstractItemInfoCsvInputDescription ; public class ItemInfoFromCsv extends AbstractItemInfoCsvInputDescription { @ Override public String getBasePath ( ) { return "" ; } @ Override public String getResourcePattern ( ) { return "" ; } @ Override public DataSize getDataSize ( ) { return DataSize . LARGE ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . csv . AbstractSalesDetailCsvInputDescription ; public class SalesDetailFromCsv extends AbstractSalesDetailCsvInputDescription { @ Override public String getBasePath ( ) { return "" ; } @ Override public String getResourcePattern ( ) { return "" ; } @ Override public DataSize getDataSize ( ) { return DataSize . LARGE ; } } package $ { package } . operator ; import java . util . List ; import $ { package } . modelgen . dmdl . model . CategorySummary ; import $ { package } . modelgen . dmdl . model . ErrorRecord ; import $ { package } . modelgen . dmdl . model . ItemInfo ; import $ { package } . modelgen . dmdl . model . JoinedSalesInfo ; import $ { package } . modelgen . dmdl . model . SalesDetail ; import $ { package } . modelgen . dmdl . model . StoreInfo ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . MasterCheck ; import com . asakusafw . vocabulary . operator . MasterJoin ; import com . asakusafw . vocabulary . operator . MasterSelection ; import com . asakusafw . vocabulary . operator . Summarize ; import com . asakusafw . vocabulary . operator . Update ; public abstract class CategorySummaryOperator { @ MasterCheck public abstract boolean checkStore ( @ Key ( group = "" ) StoreInfo info , @ Key ( group = "" ) SalesDetail sales ) ; @ MasterJoin ( selection = "" ) public abstract JoinedSalesInfo joinItemInfo ( ItemInfo info , SalesDetail sales ) ; private final Date dateBuffer = new Date ( ) ; @ MasterSelection public ItemInfo selectAvailableItem ( List < ItemInfo > candidates , SalesDetail sales ) { DateTime dateTime = sales . getSalesDateTime ( ) ; dateBuffer . setElapsedDays ( DateUtil . getDayFromDate ( dateTime . getYear ( ) , dateTime . getMonth ( ) , dateTime . getDay ( ) ) ) ; for ( ItemInfo item : candidates ) { if ( item . getBeginDate ( ) . compareTo ( dateBuffer ) <= && dateBuffer . compareTo ( item . getEndDate ( ) ) <= ) { return item ; } } return null ; } @ Summarize public abstract CategorySummary summarizeByCategory ( JoinedSalesInfo info ) ; @ Update public void setErrorMessage ( ErrorRecord record , String message ) { record . setMessageAsString ( message ) ; } } package $ { package } . batch ; import $ { package } . jobflow . CategorySummaryJob ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class SummarizeBatch extends BatchDescription { @ Override protected void describe ( ) { run ( CategorySummaryJob . class ) . soon ( ) ; } } package $ { package } . jobflow ; import org . junit . Test ; import $ { package } . modelgen . dmdl . model . CategorySummary ; import $ { package } . modelgen . dmdl . model . ErrorRecord ; import $ { package } . modelgen . dmdl . model . ItemInfo ; import $ { package } . modelgen . dmdl . model . SalesDetail ; import $ { package } . modelgen . dmdl . model . StoreInfo ; import $ { package } . util . CountVerifier ; import com . asakusafw . testdriver . JobFlowTester ; public class CategorySummaryJobTest { @ Test public void simple ( ) { run ( "" , ) ; } @ Test public void summarize ( ) { run ( "" , ) ; } @ Test public void available_date ( ) { run ( "" , ) ; } @ Test public void invalid_store ( ) { run ( "" , ) ; } private void run ( String dataSet , long errors ) { JobFlowTester tester = new JobFlowTester ( getClass ( ) ) ; tester . setBatchArg ( "" , "" ) ; tester . input ( "" , StoreInfo . class ) . prepare ( "" ) ; tester . input ( "" , ItemInfo . class ) . prepare ( "" ) ; tester . input ( "" , SalesDetail . class ) . prepare ( dataSet + "" ) ; tester . output ( "" , CategorySummary . class ) . verify ( dataSet + "" , dataSet + "" ) ; tester . output ( "" , ErrorRecord . class ) . verify ( CountVerifier . factory ( errors ) ) ; tester . runTest ( CategorySummaryJob . class ) ; } } package $ { package } . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . List ; import org . junit . Test ; import $ { package } . modelgen . dmdl . model . ItemInfo ; import $ { package } . modelgen . dmdl . model . SalesDetail ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class CategorySummaryOperatorTest { @ Test public void selectAvailableItem ( ) { List < ItemInfo > candidates = new ArrayList < ItemInfo > ( ) ; candidates . add ( item ( "" , , ) ) ; candidates . add ( item ( "" , , ) ) ; candidates . add ( item ( "" , , ) ) ; CategorySummaryOperator operator = new CategorySummaryOperatorImpl ( ) ; ItemInfo item1 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item5 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item10 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item15 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item20 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item30 = operator . selectAvailableItem ( candidates , sales ( ) ) ; ItemInfo item31 = operator . selectAvailableItem ( candidates , sales ( ) ) ; assertThat ( item1 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item5 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item10 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item15 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item20 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item30 . getCategoryCodeAsString ( ) , is ( "" ) ) ; assertThat ( item31 , is ( nullValue ( ) ) ) ; } private SalesDetail sales ( int day ) { SalesDetail object = new SalesDetail ( ) ; object . setSalesDateTime ( new DateTime ( , , day , , , ) ) ; return object ; } private ItemInfo item ( String categoryCode , int begin , int end ) { ItemInfo object = new ItemInfo ( ) ; object . setCategoryCodeAsString ( categoryCode ) ; object . setBeginDate ( new Date ( , , begin ) ) ; object . setEndDate ( new Date ( , , end ) ) ; return object ; } } package $ { package } . util ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . Difference ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . Verifier ; import com . asakusafw . testdriver . core . VerifierFactory ; import com . asakusafw . testdriver . core . VerifyContext ; public class CountVerifier implements Verifier { private final long expected ; public CountVerifier ( long expected ) { this . expected = expected ; } public static VerifierFactory factory ( final long expected ) { return new VerifierFactory ( ) { @ Override public < T > Verifier createVerifier ( DataModelDefinition < T > definition , VerifyContext context ) { return new CountVerifier ( expected ) ; } } ; } @ Override public List < Difference > verify ( DataModelSource results ) throws IOException { long actual = ; while ( results . next ( ) != null ) { actual ++ ; } List < Difference > result = new ArrayList < Difference > ( ) ; if ( expected != actual ) { result . add ( createDifference ( actual ) ) ; } return result ; } private Difference createDifference ( long actual ) { PropertyName name = PropertyName . newInstance ( "" ) ; return new Difference ( new DataModelReflection ( Collections . singletonMap ( name , expected ) ) , new DataModelReflection ( Collections . singletonMap ( name , actual ) ) , "" ) ; } @ Override public void close ( ) throws IOException { return ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . csv . AbstractErrorRecordCsvExporterDescription ; public class ErrorRecordToCsv extends AbstractErrorRecordCsvExporterDescription { @ Override public String getProfileName ( ) { return "" ; } @ Override public String getPath ( ) { return "" ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . csv . AbstractCategorySummaryCsvExporterDescription ; public class CategorySummaryToCsv extends AbstractCategorySummaryCsvExporterDescription { @ Override public String getProfileName ( ) { return "" ; } @ Override public String getPath ( ) { return "" ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . csv . AbstractItemInfoCsvImporterDescription ; public class ItemInfoFromCsv extends AbstractItemInfoCsvImporterDescription { @ Override public String getProfileName ( ) { return "" ; } @ Override public String getPath ( ) { return "" ; } @ Override public DataSize getDataSize ( ) { return DataSize . LARGE ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . csv . AbstractSalesDetailCsvImporterDescription ; public class SalesDetailFromCsv extends AbstractSalesDetailCsvImporterDescription { @ Override public String getProfileName ( ) { return "" ; } @ Override public String getPath ( ) { return "" ; } @ Override public DataSize getDataSize ( ) { return DataSize . LARGE ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . csv . AbstractStoreInfoCsvImporterDescription ; public class StoreInfoFromCsv extends AbstractStoreInfoCsvImporterDescription { @ Override public String getProfileName ( ) { return "" ; } @ Override public String getPath ( ) { return "" ; } @ Override public DataSize getDataSize ( ) { return DataSize . TINY ; } } package $ { package } . jobflow ; import $ { package } . modelgen . dmdl . model . CategorySummary ; import $ { package } . modelgen . dmdl . model . ErrorRecord ; import $ { package } . modelgen . dmdl . model . ItemInfo ; import $ { package } . modelgen . dmdl . model . SalesDetail ; import $ { package } . modelgen . dmdl . model . StoreInfo ; import $ { package } . operator . CategorySummaryOperatorFactory ; import $ { package } . operator . CategorySummaryOperatorFactory . CheckStore ; import $ { package } . operator . CategorySummaryOperatorFactory . JoinItemInfo ; import $ { package } . operator . CategorySummaryOperatorFactory . SetErrorMessage ; import $ { package } . operator . CategorySummaryOperatorFactory . SummarizeByCategory ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ JobFlow ( name = "" ) public class CategorySummaryJob extends FlowDescription { final In < SalesDetail > salesDetail ; final In < StoreInfo > storeInfo ; final In < ItemInfo > itemInfo ; final Out < CategorySummary > categorySummary ; final Out < ErrorRecord > errorRecord ; public CategorySummaryJob ( @ Import ( name = "" , description = SalesDetailFromCsv . class ) In < SalesDetail > salesDetail , @ Import ( name = "" , description = StoreInfoFromCsv . class ) In < StoreInfo > storeInfo , @ Import ( name = "" , description = ItemInfoFromCsv . class ) In < ItemInfo > itemInfo , @ Export ( name = "" , description = CategorySummaryToCsv . class ) Out < CategorySummary > categorySummary , @ Export ( name = "" , description = ErrorRecordToCsv . class ) Out < ErrorRecord > errorRecord ) { this . salesDetail = salesDetail ; this . storeInfo = storeInfo ; this . itemInfo = itemInfo ; this . categorySummary = categorySummary ; this . errorRecord = errorRecord ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; CategorySummaryOperatorFactory operators = new CategorySummaryOperatorFactory ( ) ; CheckStore checkStore = operators . checkStore ( storeInfo , salesDetail ) ; JoinItemInfo joinItemInfo = operators . joinItemInfo ( itemInfo , checkStore . found ) ; SummarizeByCategory summarize = operators . summarizeByCategory ( joinItemInfo . joined ) ; categorySummary . add ( summarize . out ) ; SetErrorMessage unknownStore = operators . setErrorMessage ( core . restructure ( checkStore . missed , ErrorRecord . class ) , "" ) ; errorRecord . add ( unknownStore . out ) ; SetErrorMessage unknownItem = operators . setErrorMessage ( core . restructure ( joinItemInfo . missed , ErrorRecord . class ) , "" ) ; errorRecord . add ( unknownItem . out ) ; } } package $ { package } . operator ; import java . util . List ; import $ { package } . modelgen . dmdl . model . CategorySummary ; import $ { package } . modelgen . dmdl . model . ErrorRecord ; import $ { package } . modelgen . dmdl . model . ItemInfo ; import $ { package } . modelgen . dmdl . model . JoinedSalesInfo ; import $ { package } . modelgen . dmdl . model . SalesDetail ; import $ { package } . modelgen . dmdl . model . StoreInfo ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . MasterCheck ; import com . asakusafw . vocabulary . operator . MasterJoin ; import com . asakusafw . vocabulary . operator . MasterSelection ; import com . asakusafw . vocabulary . operator . Summarize ; import com . asakusafw . vocabulary . operator . Update ; public abstract class CategorySummaryOperator { @ MasterCheck public abstract boolean checkStore ( @ Key ( group = "" ) StoreInfo info , @ Key ( group = "" ) SalesDetail sales ) ; @ MasterJoin ( selection = "" ) public abstract JoinedSalesInfo joinItemInfo ( ItemInfo info , SalesDetail sales ) ; private final Date dateBuffer = new Date ( ) ; @ MasterSelection public ItemInfo selectAvailableItem ( List < ItemInfo > candidates , SalesDetail sales ) { DateTime dateTime = sales . getSalesDateTime ( ) ; dateBuffer . setElapsedDays ( DateUtil . getDayFromDate ( dateTime . getYear ( ) , dateTime . getMonth ( ) , dateTime . getDay ( ) ) ) ; for ( ItemInfo item : candidates ) { if ( item . getBeginDate ( ) . compareTo ( dateBuffer ) <= && dateBuffer . compareTo ( item . getEndDate ( ) ) <= ) { return item ; } } return null ; } @ Summarize public abstract CategorySummary summarizeByCategory ( JoinedSalesInfo info ) ; @ Update public void setErrorMessage ( ErrorRecord record , String message ) { record . setMessageAsString ( message ) ; } } package $ { package } . batch ; import $ { package } . jobflow . CategorySummaryJob ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class SummarizeBatch extends BatchDescription { @ Override protected void describe ( ) { run ( CategorySummaryJob . class ) . soon ( ) ; } } package com . asakusafw . yaess . basic ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionLock ; import com . asakusafw . yaess . core . ExecutionLock . Scope ; import com . asakusafw . yaess . core . ExecutionLockProvider ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicLockProvider extends ExecutionLockProvider { static final Logger LOG = LoggerFactory . getLogger ( BasicLockProvider . class ) ; public static final String KEY_DIRECTORY = "" ; private volatile File directory ; @ Override public void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { LOG . debug ( "" , profile . getPrefix ( ) ) ; directory = prepareDirectory ( profile ) ; LOG . debug ( "" , directory ) ; } private File prepareDirectory ( ServiceProfile < ? > profile ) throws IOException { assert profile != null ; String path = profile . getConfiguration ( KEY_DIRECTORY , true , true ) ; File dir = new File ( path ) ; if ( dir . isDirectory ( ) == false && dir . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , dir . getAbsolutePath ( ) ) ) ; } return dir ; } @ Override protected ExecutionLock newInstance ( Scope lockScope , String batchId ) throws IOException { if ( lockScope == null ) { throw new IllegalArgumentException ( "" ) ; } if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } return new FileExecutionLock ( lockScope , batchId , directory ) ; } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . Executor ; import java . util . concurrent . ExecutorService ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . Job ; public class ThreadedJobExecutor implements JobExecutor { private final Executor executor ; public ThreadedJobExecutor ( Executor executor ) { if ( executor == null ) { throw new IllegalArgumentException ( "" ) ; } this . executor = executor ; } @ Override public Executing submit ( ExecutionMonitor monitor , ExecutionContext context , Job job , BlockingQueue < Executing > doneQueue ) throws InterruptedException , IOException { if ( monitor == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( job == null ) { throw new IllegalArgumentException ( "" ) ; } Executing executing = new Executing ( monitor , context , job , doneQueue ) ; executor . execute ( executing ) ; return executing ; } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . CancellationException ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . LinkedBlockingQueue ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . basic . JobExecutor . Executing ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . Job ; import com . asakusafw . yaess . core . JobScheduler ; import com . asakusafw . yaess . core . PhaseMonitor ; import com . asakusafw . yaess . core . PhaseMonitor . JobStatus ; import com . asakusafw . yaess . core . YaessLogger ; public abstract class AbstractJobScheduler extends JobScheduler { static final YaessLogger YSLOG = new YaessBasicLogger ( AbstractJobScheduler . class ) ; static final Logger LOG = LoggerFactory . getLogger ( AbstractJobScheduler . class ) ; protected abstract JobExecutor getJobExecutor ( ) ; @ Override public final void execute ( PhaseMonitor monitor , ExecutionContext context , List < ? extends Job > jobs , ErrorHandler errorHandler ) throws InterruptedException , IOException { if ( monitor == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( jobs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( errorHandler == null ) { throw new IllegalArgumentException ( "" ) ; } monitor . open ( jobs . size ( ) ) ; try { monitor . checkCancelled ( ) ; Engine engine = new Engine ( getJobExecutor ( ) , monitor , context , errorHandler , jobs ) ; engine . run ( ) ; } finally { monitor . close ( ) ; } } private static final class Engine { private final JobExecutor executor ; final PhaseMonitor monitor ; final ExecutionContext context ; private final ErrorHandler handler ; private final LinkedList < Job > waiting ; private final Map < String , Executing > executing ; private final BlockingQueue < Executing > doneQueue ; private final Set < String > blockers ; private boolean sawError ; Engine ( JobExecutor executor , PhaseMonitor monitor , ExecutionContext context , ErrorHandler handler , List < ? extends Job > waiting ) { assert executor != null ; assert monitor != null ; assert context != null ; assert handler != null ; assert waiting != null ; this . executor = executor ; this . monitor = monitor ; this . context = context ; this . handler = handler ; this . waiting = new LinkedList < Job > ( waiting ) ; this . executing = new HashMap < String , Executing > ( ) ; this . doneQueue = new LinkedBlockingQueue < Executing > ( ) ; this . blockers = new TreeSet < String > ( ) ; for ( Job job : waiting ) { blockers . add ( job . getId ( ) ) ; } this . sawError = false ; } void run ( ) throws IOException , InterruptedException { while ( waiting . isEmpty ( ) == false ) { boolean submitted = submitAllWaiting ( ) ; if ( submitted == false && executing . isEmpty ( ) ) { assert waiting . isEmpty ( ) == false ; if ( sawError ) { waiting . clear ( ) ; } else { throw new IOException ( MessageFormat . format ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) , blockers ) ) ; } } else { waitForDone ( ) ; } } while ( executing . isEmpty ( ) == false ) { waitForDone ( ) ; } if ( sawError ) { throw new IOException ( MessageFormat . format ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) ) ) ; } } private boolean submitAllWaiting ( ) throws IOException , InterruptedException { boolean sawSubmit = false ; for ( Iterator < Job > iter = waiting . iterator ( ) ; iter . hasNext ( ) ; ) { Job next = iter . next ( ) ; LOG . debug ( "" , next . getId ( ) ) ; if ( isBlocked ( next ) ) { LOG . debug ( "" , next . getId ( ) ) ; continue ; } iter . remove ( ) ; if ( submit ( next ) ) { sawSubmit = true ; } } return sawSubmit ; } private void waitForDone ( ) throws InterruptedException , IOException { assert executing . isEmpty ( ) == false ; monitor . checkCancelled ( ) ; Executing done = doneQueue . take ( ) ; assert done . isDone ( ) ; handleDone ( done ) ; while ( true ) { monitor . checkCancelled ( ) ; Executing rest = doneQueue . poll ( ) ; if ( rest == null ) { break ; } assert rest . isDone ( ) ; handleDone ( rest ) ; } } private void handleDone ( Executing done ) throws InterruptedException , IOException { assert done != null ; assert done . isDone ( ) ; Executing removed = executing . remove ( done . getJob ( ) . getId ( ) ) ; assert removed != null ; try { done . get ( ) ; done ( done . getJob ( ) ) ; monitor . reportJobStatus ( done . getJob ( ) . getId ( ) , JobStatus . SUCCESS , null ) ; } catch ( CancellationException e ) { sawError = true ; monitor . reportJobStatus ( done . getJob ( ) . getId ( ) , JobStatus . CANCELLED , e ) ; } catch ( ExecutionException e ) { sawError = true ; Throwable cause = e . getCause ( ) ; if ( cause instanceof InterruptedException ) { monitor . reportJobStatus ( done . getJob ( ) . getId ( ) , JobStatus . CANCELLED , cause ) ; cancelExecution ( ) ; throw ( InterruptedException ) cause ; } else if ( cause instanceof IOException ) { monitor . reportJobStatus ( done . getJob ( ) . getId ( ) , JobStatus . FAILED , cause ) ; handleException ( done . getJob ( ) , ( IOException ) cause ) ; } else if ( cause instanceof Error ) { monitor . reportJobStatus ( done . getJob ( ) . getId ( ) , JobStatus . FAILED , cause ) ; cancelExecution ( ) ; throw ( Error ) cause ; } else if ( cause instanceof RuntimeException ) { monitor . reportJobStatus ( done . getJob ( ) . getId ( ) , JobStatus . FAILED , cause ) ; cancelExecution ( ) ; throw ( RuntimeException ) cause ; } else { monitor . reportJobStatus ( done . getJob ( ) . getId ( ) , JobStatus . FAILED , cause ) ; cancelExecution ( ) ; throw new AssertionError ( cause ) ; } } } private boolean submit ( Job job ) throws InterruptedException , IOException { assert job != null ; monitor . checkCancelled ( ) ; try { Executing execution = executor . submit ( monitor . createJobMonitor ( job . getId ( ) , ) , context , job , doneQueue ) ; executing . put ( execution . getJob ( ) . getId ( ) , execution ) ; return true ; } catch ( IOException e ) { sawError = true ; handleException ( job , e ) ; return false ; } } private void handleException ( Job job , IOException exception ) throws IOException { assert job != null ; assert exception != null ; YSLOG . error ( exception , "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , job . getJobLabel ( ) , job . getServiceLabel ( ) ) ; if ( handler . handle ( context , exception ) == false ) { cancelExecution ( ) ; throw exception ; } } private void cancelExecution ( ) { for ( Executing exec : executing . values ( ) ) { exec . cancel ( true ) ; } } private boolean isBlocked ( Job job ) { assert job != null ; for ( String blocker : job . getBlockerIds ( ) ) { if ( blockers . contains ( blocker ) ) { return true ; } } return false ; } private void done ( Job job ) { assert job != null ; blockers . remove ( job . getId ( ) ) ; } } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . io . OutputStream ; import java . util . List ; import java . util . Map ; import com . asakusafw . yaess . core . ExecutionContext ; public interface ProcessExecutor { @ Deprecated int execute ( ExecutionContext context , List < String > commandLineTokens , Map < String , String > environmentVariables ) throws InterruptedException , IOException ; int execute ( ExecutionContext context , List < String > commandLineTokens , Map < String , String > environmentVariables , OutputStream output ) throws InterruptedException , IOException ; } package com . asakusafw . yaess . basic ; import java . io . IOException ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicCommandScriptHandler extends ProcessCommandScriptHandler { @ Override protected void configureExtension ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { return ; } @ Override protected ProcessExecutor getCommandExecutor ( ) { return ProcessUtil . getProcessExecutor ( ) ; } } package com . asakusafw . yaess . basic ; package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . Callable ; import java . util . concurrent . FutureTask ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . Job ; public interface JobExecutor { Executing submit ( ExecutionMonitor monitor , ExecutionContext context , Job job , BlockingQueue < Executing > doneQueue ) throws InterruptedException , IOException ; public final class Executing extends FutureTask < Void > { static final Logger LOG = LoggerFactory . getLogger ( JobExecutor . class ) ; private final Job job ; private final BlockingQueue < Executing > doneQueue ; public Executing ( ExecutionMonitor monitor , ExecutionContext context , Job job , BlockingQueue < Executing > doneQueue ) { super ( build ( monitor , context , job ) ) ; this . job = job ; this . doneQueue = doneQueue ; } private static Callable < Void > build ( final ExecutionMonitor monitor , final ExecutionContext context , final Job job ) { if ( monitor == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( job == null ) { throw new IllegalArgumentException ( "" ) ; } return new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { LOG . debug ( "" , job . getId ( ) , Thread . currentThread ( ) . getName ( ) ) ; job . launch ( monitor , context ) ; LOG . debug ( "" , job . getId ( ) , Thread . currentThread ( ) . getName ( ) ) ; return null ; } } ; } public Job getJob ( ) { return job ; } @ Override protected void done ( ) { if ( doneQueue != null ) { doneQueue . add ( this ) ; } } } } package com . asakusafw . yaess . basic ; import com . asakusafw . yaess . core . CoreProfile ; public class BasicCoreProfile extends CoreProfile { } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandlerBase ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . YaessLogger ; public abstract class ProcessHadoopScriptHandler extends ExecutionScriptHandlerBase implements HadoopScriptHandler { static final YaessLogger YSLOG = new YaessBasicLogger ( ProcessHadoopScriptHandler . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ProcessHadoopScriptHandler . class ) ; public static final String CLEANUP_STAGE_CLASS = "" ; @ Deprecated public static final String KEY_WORKING_DIRECTORY = "" ; public static final String KEY_CLEANUP = "" ; public static final String PATH_EXECUTE = "" ; public static final String VAR_BATCH_ID = "" ; public static final String VAR_FLOW_ID = "" ; public static final String VAR_EXECUTION_ID = "" ; private volatile ServiceProfile < ? > currentProfile ; private volatile List < String > commandPrefix ; private boolean cleanup ; @ Override protected final void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { this . currentProfile = profile ; this . commandPrefix = extractCommand ( profile , ProcessUtil . PREFIX_COMMAND ) ; this . cleanup = extractBoolean ( profile , KEY_CLEANUP , true ) ; checkCleanupConfigurations ( profile ) ; configureExtension ( profile ) ; } private void checkCleanupConfigurations ( ServiceProfile < ? > profile ) throws IOException { assert profile != null ; String workingDirectory = profile . getConfiguration ( ) . get ( KEY_WORKING_DIRECTORY ) ; if ( workingDirectory != null ) { YSLOG . warn ( "" , profile . getPrefix ( ) , KEY_WORKING_DIRECTORY , KEY_CLEANUP ) ; } List < String > cleanupPrefix = extractCommand ( profile , ProcessUtil . PREFIX_CLEANUP ) ; if ( cleanupPrefix . isEmpty ( ) == false ) { YSLOG . warn ( "" , profile . getPrefix ( ) , ProcessUtil . PREFIX_CLEANUP + "" , KEY_CLEANUP ) ; } } private List < String > extractCommand ( ServiceProfile < ? > profile , String prefix ) throws IOException { try { return ProcessUtil . extractCommandLineTokens ( prefix , profile . getConfiguration ( ) , profile . getContext ( ) . getContextParameters ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) + '' + prefix + '' ) , e ) ; } } private boolean extractBoolean ( ServiceProfile < ? > profile , String key , boolean defaultValue ) throws IOException { assert profile != null ; assert key != null ; String string = profile . getConfiguration ( key , false , true ) ; if ( string == null ) { return defaultValue ; } string = string . trim ( ) ; if ( string . isEmpty ( ) ) { return defaultValue ; } try { return Boolean . parseBoolean ( string ) ; } catch ( RuntimeException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) + '' + key , string ) , e ) ; } } protected abstract void configureExtension ( ServiceProfile < ? > profile ) throws InterruptedException , IOException ; protected abstract ProcessExecutor getCommandExecutor ( ) ; @ Override public final void execute ( ExecutionMonitor monitor , ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { execute0 ( monitor , context , script ) ; } finally { monitor . close ( ) ; } } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { if ( cleanup ) { YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , getHandlerId ( ) ) ; HadoopScript script = new HadoopScript ( context . getPhase ( ) . getSymbol ( ) , Collections . < String > emptySet ( ) , CLEANUP_STAGE_CLASS , Collections . < String , String > emptyMap ( ) , Collections . < String , String > emptyMap ( ) ) ; execute0 ( monitor , context , script ) ; } else { YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , getHandlerId ( ) ) ; } } finally { monitor . close ( ) ; } } private void execute0 ( ExecutionMonitor monitor , ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { assert monitor != null ; assert context != null ; assert script != null ; Map < String , String > env = buildEnvironmentVariables ( context , script ) ; LOG . debug ( "" , env ) ; List < String > original = buildExecutionCommand ( context , script ) ; List < String > command ; try { command = ProcessUtil . buildCommand ( commandPrefix , original , Collections . < String > emptyList ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) , script . getId ( ) , currentProfile . getPrefix ( ) , original ) , e ) ; } LOG . debug ( "" , command ) ; monitor . checkCancelled ( ) ; ProcessExecutor executor = getCommandExecutor ( ) ; int exit = executor . execute ( context , command , env , monitor . getOutput ( ) ) ; if ( exit == ) { return ; } throw new ExitCodeException ( MessageFormat . format ( "" + "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) , script . getId ( ) , String . valueOf ( exit ) ) , exit ) ; } private Map < String , String > buildEnvironmentVariables ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException { assert script != null ; Map < String , String > env = new HashMap < String , String > ( ) ; env . putAll ( getEnvironmentVariables ( context , script ) ) ; env . putAll ( context . getEnvironmentVariables ( ) ) ; env . putAll ( script . getEnvironmentVariables ( ) ) ; return env ; } private List < String > buildExecutionCommand ( ExecutionContext context , HadoopScript script ) throws IOException , InterruptedException { assert context != null ; assert script != null ; List < String > command = new ArrayList < String > ( ) ; command . add ( getCommand ( context , PATH_EXECUTE , script ) ) ; command . add ( script . getClassName ( ) ) ; command . add ( context . getBatchId ( ) ) ; command . add ( context . getFlowId ( ) ) ; command . add ( context . getExecutionId ( ) ) ; command . add ( context . getArgumentsAsString ( ) ) ; Map < String , String > props = buildHadoopProperties ( context , script ) ; for ( Map . Entry < String , String > entry : props . entrySet ( ) ) { command . add ( "" ) ; command . add ( MessageFormat . format ( "" , entry . getKey ( ) , entry . getValue ( ) ) ) ; } return command ; } private Map < String , String > buildHadoopProperties ( ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { assert context != null ; assert script != null ; Map < String , String > props = new TreeMap < String , String > ( ) ; props . putAll ( getProperties ( context , script ) ) ; props . putAll ( script . getHadoopProperties ( ) ) ; return props ; } private String getCommand ( ExecutionContext context , String command , HadoopScript script ) throws IOException , InterruptedException { assert command != null ; Map < String , String > variables ; if ( script != null ) { variables = buildEnvironmentVariables ( context , script ) ; } else { variables = getEnvironmentVariables ( context , null ) ; } String home = variables . get ( ExecutionScript . ENV_ASAKUSA_HOME ) ; if ( home == null ) { throw new IOException ( MessageFormat . format ( "" , currentProfile . getPrefix ( ) + '' + KEY_ENV_PREFIX + ExecutionScript . ENV_ASAKUSA_HOME ) ) ; } if ( home . endsWith ( getPathSegmentSeparator ( ) ) ) { return home + command ; } else { return home + getPathSegmentSeparator ( ) + command ; } } protected String getPathSegmentSeparator ( ) { return "" ; } } package com . asakusafw . yaess . basic ; import java . io . IOException ; public class ExitCodeException extends IOException { private static final long serialVersionUID = ; private final int exitCode ; public ExitCodeException ( String message , int exitCode ) { super ( message ) ; this . exitCode = exitCode ; } public int getExitCode ( ) { return exitCode ; } } package com . asakusafw . yaess . basic ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . yaess . core . YaessLogger ; public class YaessBasicLogger extends YaessLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public YaessBasicLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitorProvider ; import com . asakusafw . yaess . core . PhaseMonitor ; import com . asakusafw . yaess . core . ServiceProfile ; @ SimulationSupport public class BasicMonitorProvider extends ExecutionMonitorProvider { static final Logger LOG = LoggerFactory . getLogger ( BasicMonitorProvider . class ) ; private volatile double stepUnit ; public static final String KEY_STEP_UNIT = "" ; @ Override protected void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { configureStepUnit ( profile ) ; } private void configureStepUnit ( ServiceProfile < ? > profile ) throws IOException { assert profile != null ; String stepUnitString = profile . getConfiguration ( KEY_STEP_UNIT , false , true ) ; if ( stepUnitString == null ) { LOG . debug ( "" , KEY_STEP_UNIT , profile . getPrefix ( ) ) ; } else { try { stepUnit = Double . parseDouble ( stepUnitString ) ; } catch ( NumberFormatException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , KEY_STEP_UNIT , stepUnitString ) ) ; } } } @ Override public PhaseMonitor newInstance ( ExecutionContext context ) throws InterruptedException , IOException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } return new LoggingExecutionMonitor ( context , stepUnit ) ; } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicHadoopScriptHandler extends ProcessHadoopScriptHandler { @ Override protected void configureExtension ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { return ; } @ Override protected ProcessExecutor getCommandExecutor ( ) { return ProcessUtil . getProcessExecutor ( ) ; } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandlerBase ; import com . asakusafw . yaess . core . ServiceProfile ; public abstract class ProcessCommandScriptHandler extends ExecutionScriptHandlerBase implements CommandScriptHandler { static final Logger LOG = LoggerFactory . getLogger ( ProcessCommandScriptHandler . class ) ; private volatile ServiceProfile < ? > currentProfile ; private volatile List < String > commandPrefix ; private volatile List < String > setupCommand ; private volatile List < String > cleanupCommand ; @ Override protected final void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { this . currentProfile = profile ; this . commandPrefix = extractCommand ( profile , ProcessUtil . PREFIX_COMMAND ) ; this . setupCommand = extractCommand ( profile , ProcessUtil . PREFIX_SETUP ) ; this . cleanupCommand = extractCommand ( profile , ProcessUtil . PREFIX_CLEANUP ) ; configureExtension ( profile ) ; } private List < String > extractCommand ( ServiceProfile < ? > profile , String prefix ) throws IOException { try { return ProcessUtil . extractCommandLineTokens ( prefix , profile . getConfiguration ( ) , profile . getContext ( ) . getContextParameters ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) + '' + prefix + '' ) , e ) ; } } protected abstract void configureExtension ( ServiceProfile < ? > profile ) throws InterruptedException , IOException ; protected abstract ProcessExecutor getCommandExecutor ( ) ; @ Override public final void execute ( ExecutionMonitor monitor , ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { execute0 ( monitor , context , script ) ; } finally { monitor . close ( ) ; } } @ Override public void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { if ( setupCommand . isEmpty ( ) == false ) { command ( monitor , context , null , setupCommand ) ; } else { voidSetUp ( context ) ; } } finally { monitor . close ( ) ; } } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { if ( cleanupCommand . isEmpty ( ) == false ) { command ( monitor , context , null , cleanupCommand ) ; } else { voidCleanUp ( context ) ; } } finally { monitor . close ( ) ; } } private void execute0 ( ExecutionMonitor monitor , ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { assert monitor != null ; assert context != null ; assert script != null ; Map < String , String > env = buildEnvironmentVariables ( context , script ) ; LOG . debug ( "" , env ) ; List < String > original = script . getCommandLineTokens ( ) ; List < String > command ; try { command = ProcessUtil . buildCommand ( commandPrefix , original , Collections . < String > emptyList ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) , script . getId ( ) , currentProfile . getPrefix ( ) , original ) , e ) ; } LOG . debug ( "" , command ) ; monitor . checkCancelled ( ) ; ProcessExecutor executor = getCommandExecutor ( ) ; int exit = executor . execute ( context , command , env , monitor . getOutput ( ) ) ; if ( exit == ) { return ; } throw new ExitCodeException ( MessageFormat . format ( "" + "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) , script . getId ( ) , String . valueOf ( exit ) ) , exit ) ; } private void command ( ExecutionMonitor monitor , ExecutionContext context , ExecutionScript script , List < String > command ) throws InterruptedException , IOException { assert monitor != null ; assert context != null ; assert command != null ; assert command . isEmpty ( ) == false ; LOG . debug ( "" , command ) ; monitor . checkCancelled ( ) ; ProcessExecutor executor = getCommandExecutor ( ) ; int exit = executor . execute ( context , command , getEnvironmentVariables ( context , script ) , monitor . getOutput ( ) ) ; if ( exit == ) { return ; } throw new ExitCodeException ( MessageFormat . format ( "" + "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) , String . valueOf ( exit ) ) , exit ) ; } private Map < String , String > buildEnvironmentVariables ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException { assert script != null ; Map < String , String > env = new HashMap < String , String > ( ) ; env . putAll ( getEnvironmentVariables ( context , script ) ) ; env . putAll ( context . getEnvironmentVariables ( ) ) ; env . putAll ( script . getEnvironmentVariables ( ) ) ; return env ; } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . PhaseMonitor ; public class LoggingExecutionMonitor extends PhaseMonitor { static final Logger LOG = LoggerFactory . getLogger ( LoggingExecutionMonitor . class ) ; private final String label ; private final double stepUnit ; private double totalTaskSize ; private double workedTaskSize ; private int workedStep = ; private boolean opened ; private boolean closed ; public LoggingExecutionMonitor ( ExecutionContext context , double stepUnit ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } this . label = MessageFormat . format ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) ) ; if ( stepUnit <= ) { this . stepUnit = Double . MAX_VALUE ; } else { this . stepUnit = Math . max ( stepUnit , ) - ; } } @ Override public synchronized void open ( double taskSize ) { if ( opened ) { throw new IllegalStateException ( MessageFormat . format ( "" , label ) ) ; } opened = true ; this . totalTaskSize = taskSize ; LOG . info ( MessageFormat . format ( "" , label ) ) ; } @ Override public synchronized void progressed ( double deltaSize ) { set ( workedTaskSize + deltaSize ) ; } @ Override public synchronized void setProgress ( double workedSize ) { set ( workedSize ) ; } @ Override protected void onJobMonitorOpened ( String jobId ) { if ( jobId == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( MessageFormat . format ( "" , label , jobId ) ) ; } @ Override protected void onJobMonitorClosed ( String jobId ) { if ( jobId == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( MessageFormat . format ( "" , label , jobId ) ) ; } @ Override public void reportJobStatus ( String jobId , JobStatus status , Throwable cause ) throws IOException { if ( jobId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( status == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( MessageFormat . format ( "" , label , jobId , status ) ) ; } @ Override public synchronized void close ( ) { if ( closed ) { return ; } closed = true ; set ( totalTaskSize ) ; LOG . info ( MessageFormat . format ( "" , label ) ) ; } private void set ( double workedSize ) { double normalized = Math . max ( , Math . min ( totalTaskSize , workedSize ) ) ; double relative = normalized / totalTaskSize ; int step = ( int ) Math . floor ( relative / stepUnit ) ; if ( step != workedStep && closed == false ) { LOG . info ( MessageFormat . format ( "" , label , String . format ( "" , relative * ) ) ) ; } this . workedTaskSize = normalized ; this . workedStep = step ; } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . concurrent . Executors ; import java . util . concurrent . ThreadFactory ; import java . util . concurrent . atomic . AtomicInteger ; import com . asakusafw . yaess . core . JobScheduler ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicJobScheduler extends AbstractJobScheduler { static final AtomicInteger COUNTER = new AtomicInteger ( ) ; private volatile JobExecutor executor ; @ Override protected void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { this . executor = new ThreadedJobExecutor ( Executors . newFixedThreadPool ( , new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable r ) { Thread thread = new Thread ( r ) ; thread . setName ( MessageFormat . format ( "" , COUNTER . incrementAndGet ( ) ) ) ; return thread ; } } ) ) ; } @ Override protected JobExecutor getJobExecutor ( ) { return executor ; } } package com . asakusafw . yaess . basic ; import java . io . Closeable ; import java . io . File ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . nio . channels . FileLock ; import java . nio . channels . OverlappingFileLockException ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionLock ; import com . asakusafw . yaess . core . YaessLogger ; class FileExecutionLock extends ExecutionLock { static final YaessLogger YSLOG = new YaessBasicLogger ( FileExecutionLock . class ) ; static final Logger LOG = LoggerFactory . getLogger ( FileExecutionLock . class ) ; private static final String NAME_WORLD = "" ; private static final String NAME_BATCH = "" ; private static final String NAME_FLOW = "" ; private static final String NAME_EXECUTION = "" ; private final Scope lockScope ; private final String batchId ; private final File directory ; private final LockObject batchLock ; private final Map < String , LockObject > flowLocks ; private boolean closed ; public FileExecutionLock ( Scope lockScope , String batchId , File directory ) throws IOException { if ( lockScope == null ) { throw new IllegalArgumentException ( "" ) ; } if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( directory == null ) { throw new IllegalArgumentException ( "" ) ; } this . lockScope = lockScope ; this . batchId = batchId ; this . directory = directory ; this . flowLocks = new HashMap < String , LockObject > ( ) ; try { this . batchLock = acquireForBatch ( ) ; } catch ( IOException e ) { YSLOG . error ( "" , batchId , lockScope ) ; throw e ; } } @ Override public synchronized void beginFlow ( String flowId , String executionId ) throws IOException { if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( closed ) { throw new IOException ( "" ) ; } LockObject other = flowLocks . get ( flowId ) ; if ( other != null ) { YSLOG . error ( "" , batchId , flowId , executionId , lockScope ) ; throw new IOException ( MessageFormat . format ( "" , flowId , other . label ) ) ; } try { LockObject lock = acquireForFlow ( flowId , executionId ) ; if ( lock != null ) { flowLocks . put ( flowId , lock ) ; } } catch ( IOException e ) { YSLOG . error ( "" , batchId , flowId , executionId , lockScope ) ; throw e ; } } @ Override public synchronized void endFlow ( String flowId , String executionId ) throws IOException { if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( closed ) { throw new IOException ( "" ) ; } LockObject lock = flowLocks . remove ( flowId ) ; closeQuiet ( lock ) ; } @ Override public synchronized void close ( ) { if ( closed ) { return ; } closeQuiet ( batchLock ) ; for ( LockObject lock : flowLocks . values ( ) ) { closeQuiet ( lock ) ; } closed = true ; } private void closeQuiet ( LockObject lock ) { if ( lock == null ) { return ; } lock . close ( ) ; } private LockObject acquireForBatch ( ) throws IOException { assert directory != null ; assert batchId != null ; switch ( lockScope ) { case WORLD : return new LockObject ( "" , new File ( directory , NAME_WORLD ) ) ; case BATCH : return new LockObject ( MessageFormat . format ( "" , batchId ) , new File ( directory , MessageFormat . format ( NAME_BATCH , batchId ) ) ) ; default : return null ; } } private LockObject acquireForFlow ( String flowId , String executionId ) throws IOException { assert flowId != null ; assert executionId != null ; switch ( lockScope ) { case WORLD : case BATCH : case FLOW : return new LockObject ( MessageFormat . format ( "" , batchId , flowId ) , new File ( directory , MessageFormat . format ( NAME_FLOW , batchId , flowId , executionId ) ) ) ; case EXECUTION : return new LockObject ( MessageFormat . format ( "" , batchId , flowId , executionId ) , new File ( directory , MessageFormat . format ( NAME_EXECUTION , batchId , flowId , executionId ) ) ) ; default : return null ; } } private static class LockObject implements Closeable { final String label ; final File path ; private final RandomAccessFile file ; private final FileLock lock ; private boolean closed ; LockObject ( String label , File path ) throws IOException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } if ( label == null ) { throw new IllegalArgumentException ( "" ) ; } this . label = label ; this . path = path ; this . file = new RandomAccessFile ( path , "" ) ; boolean succeed = false ; try { this . lock = acquireFileLock ( ) ; succeed = true ; } finally { if ( succeed == false ) { closeFile ( ) ; } } } private FileLock acquireFileLock ( ) throws IOException { assert file != null ; LOG . debug ( "" , label ) ; FileLock flock ; try { flock = file . getChannel ( ) . tryLock ( ) ; if ( flock != null ) { return flock ; } LOG . debug ( "" , path ) ; } catch ( OverlappingFileLockException e ) { LOG . debug ( MessageFormat . format ( "" , label , path ) , e ) ; } throw new IOException ( MessageFormat . format ( "" , path ) ) ; } @ Override public void close ( ) { if ( closed ) { return ; } closed = true ; releaseLock ( ) ; closeFile ( ) ; deleteFile ( ) ; } private void closeFile ( ) { try { this . file . close ( ) ; } catch ( IOException e ) { YSLOG . warn ( e , "" , label , path ) ; } } private void releaseLock ( ) { try { this . lock . release ( ) ; } catch ( IOException e ) { YSLOG . warn ( e , "" , label , path ) ; } } private void deleteFile ( ) { if ( path . delete ( ) == false ) { YSLOG . warn ( "" , label , path ) ; } } } } package com . asakusafw . yaess . basic ; import java . io . ByteArrayInputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import java . util . NavigableMap ; import java . util . SortedMap ; import java . util . TreeMap ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . ThreadFactory ; import java . util . concurrent . atomic . AtomicInteger ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . VariableResolver ; import com . asakusafw . yaess . core . util . PropertiesUtil ; import com . asakusafw . yaess . core . util . StreamRedirectTask ; final class ProcessUtil { static final Logger LOG = LoggerFactory . getLogger ( ProcessUtil . class ) ; public static final String PREFIX_COMMAND = "" ; public static final String PREFIX_SETUP = "" ; public static final String PREFIX_CLEANUP = "" ; private static final Pattern ARGUMENT = Pattern . compile ( "" ) ; private static final ExecutorService REDIRECT ; static { REDIRECT = Executors . newCachedThreadPool ( new ThreadFactory ( ) { private final AtomicInteger counter = new AtomicInteger ( ) ; @ Override public Thread newThread ( Runnable r ) { Thread thread = new Thread ( r , MessageFormat . format ( "" , String . valueOf ( counter . incrementAndGet ( ) ) ) ) ; thread . setDaemon ( true ) ; return thread ; } } ) ; } public static List < String > extractCommandLineTokens ( String prefix , Map < String , String > configuration , VariableResolver variables ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } NavigableMap < String , String > map = PropertiesUtil . createPrefixMap ( configuration , prefix ) ; SortedMap < Integer , String > ordered = new TreeMap < Integer , String > ( ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { Integer position ; try { position = Integer . valueOf ( entry . getKey ( ) ) ; if ( position < ) { position = null ; } } catch ( NumberFormatException e ) { position = null ; } if ( position == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix + entry . getKey ( ) , entry . getValue ( ) ) ) ; } else { ordered . put ( position , entry . getValue ( ) ) ; } } List < String > results = new ArrayList < String > ( ) ; if ( variables == null ) { results . addAll ( ordered . values ( ) ) ; } else { for ( String token : ordered . values ( ) ) { String resolved = variables . replace ( token , true ) ; results . add ( resolved ) ; } } LOG . debug ( "" , results ) ; return results ; } public static List < String > buildCommand ( List < String > head , List < String > original , List < String > tail ) { if ( head == null ) { throw new IllegalArgumentException ( "" ) ; } if ( original == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tail == null ) { throw new IllegalArgumentException ( "" ) ; } List < String > results = new ArrayList < String > ( ) ; results . addAll ( resolveCommand ( head , original ) ) ; results . addAll ( original ) ; results . addAll ( resolveCommand ( tail , original ) ) ; LOG . debug ( "" , results ) ; return results ; } private static List < String > resolveCommand ( List < String > target , List < String > original ) { assert target != null ; assert original != null ; List < String > results = new ArrayList < String > ( ) ; for ( String token : target ) { StringBuilder buf = new StringBuilder ( ) ; int start = ; Matcher matcher = ARGUMENT . matcher ( token ) ; while ( matcher . find ( start ) ) { buf . append ( token . substring ( start , matcher . start ( ) ) ) ; int position = Integer . parseInt ( matcher . group ( ) ) ; assert position >= ; if ( position >= original . size ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , matcher . group ( ) ) ) ; } buf . append ( original . get ( position ) ) ; start = matcher . end ( ) ; } buf . append ( token . substring ( start ) ) ; results . add ( buf . toString ( ) ) ; } return results ; } public static ProcessExecutor getProcessExecutor ( ) { return new ProcessExecutor ( ) { @ Override public int execute ( ExecutionContext context , List < String > commandLineTokens , Map < String , String > environmentVariables ) throws InterruptedException , IOException { return execute ( context , commandLineTokens , environmentVariables , System . out ) ; } @ Override public int execute ( ExecutionContext context , List < String > command , Map < String , String > env , OutputStream output ) throws InterruptedException , IOException { return ProcessUtil . execute ( context , command , env , output ) ; } } ; } public static int execute ( ExecutionContext context , List < String > command , Map < String , String > env , OutputStream output ) throws InterruptedException , IOException { if ( command == null ) { throw new IllegalArgumentException ( "" ) ; } if ( env == null ) { throw new IllegalArgumentException ( "" ) ; } ProcessBuilder builder = new ProcessBuilder ( command ) ; builder . redirectErrorStream ( true ) ; builder . environment ( ) . putAll ( env ) ; String home = System . getProperty ( "" , "" ) ; File homeDirectory = new File ( home ) ; if ( homeDirectory . isDirectory ( ) ) { builder . directory ( homeDirectory ) ; } Process process = builder . start ( ) ; try { ByteArrayInputStream empty = new ByteArrayInputStream ( new byte [ ] ) ; redirect ( empty , process . getOutputStream ( ) ) ; Future < ? > stdout = redirect ( process . getInputStream ( ) , output ) ; int exit = process . waitFor ( ) ; try { stdout . get ( ) ; } catch ( ExecutionException e ) { } return exit ; } finally { process . destroy ( ) ; } } private static Future < ? > redirect ( InputStream source , OutputStream sink ) { assert source != null ; assert sink != null ; return REDIRECT . submit ( new StreamRedirectTask ( source , sink ) ) ; } private ProcessUtil ( ) { return ; } } package com . asakusafw . yaess . core ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . TreeMap ; import com . asakusafw . yaess . core . util . PropertiesUtil ; public class YaessProfile { public static final char QUALIFIER = '' ; public static final String PREFIX_CORE = "" ; public static final String PREFIX_MONITOR = "" ; public static final String PREFIX_LOCK = "" ; public static final String PREFIX_SCHEDULER = "" ; public static final String PREFIX_HADOOP = "" ; public static final String PREFIX_COMMAND = "" ; private static final String GROUP_PREFIX_COMMAND = PREFIX_COMMAND + QUALIFIER ; private final ServiceProfile < CoreProfile > core ; private final ServiceProfile < ExecutionMonitorProvider > monitors ; private final ServiceProfile < ExecutionLockProvider > locks ; private final ServiceProfile < JobScheduler > scheduler ; private final ServiceProfile < HadoopScriptHandler > hadoopHandler ; private final Map < String , ServiceProfile < CommandScriptHandler > > commandHandlers ; public YaessProfile ( ServiceProfile < CoreProfile > core , ServiceProfile < ExecutionMonitorProvider > monitors , ServiceProfile < ExecutionLockProvider > locks , ServiceProfile < JobScheduler > scheduler , ServiceProfile < HadoopScriptHandler > hadoopHandler , Collection < ServiceProfile < CommandScriptHandler > > commandHandlers ) { if ( core == null ) { throw new IllegalArgumentException ( "" ) ; } if ( monitors == null ) { throw new IllegalArgumentException ( "" ) ; } if ( locks == null ) { throw new IllegalArgumentException ( "" ) ; } if ( scheduler == null ) { throw new IllegalArgumentException ( "" ) ; } if ( hadoopHandler == null ) { throw new IllegalArgumentException ( "" ) ; } if ( commandHandlers == null ) { throw new IllegalArgumentException ( "" ) ; } checkPrefix ( core , PREFIX_CORE ) ; checkPrefix ( monitors , PREFIX_MONITOR ) ; checkPrefix ( locks , PREFIX_LOCK ) ; checkPrefix ( scheduler , PREFIX_SCHEDULER ) ; checkPrefix ( hadoopHandler , PREFIX_HADOOP ) ; this . core = core ; this . monitors = monitors ; this . locks = locks ; this . scheduler = scheduler ; this . hadoopHandler = hadoopHandler ; Map < String , ServiceProfile < CommandScriptHandler > > map = new TreeMap < String , ServiceProfile < CommandScriptHandler > > ( ) ; for ( ServiceProfile < CommandScriptHandler > profile : commandHandlers ) { if ( profile . getPrefix ( ) . startsWith ( GROUP_PREFIX_COMMAND ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , GROUP_PREFIX_COMMAND , profile . getPrefix ( ) , profile . getServiceClass ( ) . getName ( ) ) ) ; } String profileName = profile . getPrefix ( ) . substring ( GROUP_PREFIX_COMMAND . length ( ) ) ; if ( map . containsKey ( profileName ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profileName , profile . getServiceClass ( ) . getName ( ) , map . get ( profileName ) . getServiceClass ( ) . getName ( ) ) ) ; } map . put ( profileName , profile ) ; } this . commandHandlers = Collections . unmodifiableMap ( map ) ; } private void checkPrefix ( ServiceProfile < ? > profile , String prefix ) { assert profile != null ; assert prefix != null ; if ( profile . getPrefix ( ) . equals ( prefix ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix , profile . getPrefix ( ) , profile . getServiceClass ( ) . getName ( ) ) ) ; } } @ Deprecated public static YaessProfile load ( Properties properties , ClassLoader classLoader ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( classLoader == null ) { throw new IllegalArgumentException ( "" ) ; } return load ( properties , ProfileContext . system ( classLoader ) ) ; } public static YaessProfile load ( Properties properties , ProfileContext context ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } ServiceProfile < CoreProfile > core = ServiceProfile . load ( properties , PREFIX_CORE , CoreProfile . class , context ) ; ServiceProfile < ExecutionMonitorProvider > monitors = ServiceProfile . load ( properties , PREFIX_MONITOR , ExecutionMonitorProvider . class , context ) ; ServiceProfile < ExecutionLockProvider > locks = ServiceProfile . load ( properties , PREFIX_LOCK , ExecutionLockProvider . class , context ) ; ServiceProfile < JobScheduler > scheduler = ServiceProfile . load ( properties , PREFIX_SCHEDULER , JobScheduler . class , context ) ; ServiceProfile < HadoopScriptHandler > hadoopHandler = ServiceProfile . load ( properties , PREFIX_HADOOP , HadoopScriptHandler . class , context ) ; List < ServiceProfile < CommandScriptHandler > > commandHandlers = new ArrayList < ServiceProfile < CommandScriptHandler > > ( ) ; for ( String commandHandlerPrefix : PropertiesUtil . getChildKeys ( properties , GROUP_PREFIX_COMMAND , "" ) ) { ServiceProfile < CommandScriptHandler > profile = ServiceProfile . load ( properties , commandHandlerPrefix , CommandScriptHandler . class , context ) ; commandHandlers . add ( profile ) ; } return new YaessProfile ( core , monitors , locks , scheduler , hadoopHandler , commandHandlers ) ; } public ServiceProfile < CoreProfile > getCore ( ) { return core ; } public ServiceProfile < ExecutionMonitorProvider > getMonitors ( ) { return monitors ; } public ServiceProfile < ExecutionLockProvider > getLocks ( ) { return locks ; } public ServiceProfile < JobScheduler > getScheduler ( ) { return scheduler ; } public ServiceProfile < HadoopScriptHandler > getHadoopHandler ( ) { return hadoopHandler ; } public Map < String , ServiceProfile < CommandScriptHandler > > getCommandHandlers ( ) { return commandHandlers ; } } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Map ; import java . util . NavigableMap ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . util . PropertiesUtil ; public abstract class ExecutionScriptHandlerBase implements Service { static final YaessLogger YSLOG = new YaessCoreLogger ( ExecutionScriptHandlerBase . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ExecutionScriptHandlerBase . class ) ; private volatile String prefix ; private volatile String resourceId ; private volatile Map < String , String > properties ; private volatile Map < String , String > environmentVariables ; @ Override public final void configure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { this . prefix = profile . getPrefix ( ) ; try { configureResourceId ( profile ) ; Map < String , String > desiredProperties = getDesiredProperties ( profile ) ; Map < String , String > desiredEnvironmentVariables = getDesiredEnvironmentVariables ( profile ) ; this . properties = Collections . unmodifiableMap ( desiredProperties ) ; this . environmentVariables = Collections . unmodifiableMap ( desiredEnvironmentVariables ) ; doConfigure ( profile , desiredProperties , desiredEnvironmentVariables ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , profile . getPrefix ( ) ) , e ) ; } } public final String getHandlerId ( ) { return prefix ; } private void configureResourceId ( ServiceProfile < ? > profile ) { assert profile != null ; String override = profile . getConfiguration ( ExecutionScriptHandler . KEY_RESOURCE , false , true ) ; if ( override == null ) { LOG . debug ( "" , profile . getPrefix ( ) ) ; resourceId = ExecutionScriptHandler . DEFAULT_RESOURCE_ID ; } else { LOG . debug ( "" , profile . getPrefix ( ) , override ) ; resourceId = override ; } } private Map < String , String > getDesiredProperties ( ServiceProfile < ? > profile ) throws IOException { assert profile != null ; NavigableMap < String , String > vars = PropertiesUtil . createPrefixMap ( profile . getConfiguration ( ) , ExecutionScriptHandler . KEY_PROP_PREFIX ) ; Map < String , String > resolved = new TreeMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : vars . entrySet ( ) ) { String key = entry . getKey ( ) ; String unresolved = entry . getValue ( ) ; try { String value = profile . getContext ( ) . getContextParameters ( ) . replace ( unresolved , true ) ; resolved . put ( key , value ) ; } catch ( IllegalArgumentException e ) { YSLOG . error ( e , "" , profile . getPrefix ( ) , ExecutionScriptHandler . KEY_PROP_PREFIX , key , unresolved ) ; throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , ExecutionScriptHandler . KEY_PROP_PREFIX , key , unresolved ) , e ) ; } } LOG . debug ( "" , profile . getPrefix ( ) , resolved ) ; return resolved ; } private Map < String , String > getDesiredEnvironmentVariables ( ServiceProfile < ? > profile ) throws IOException { assert profile != null ; NavigableMap < String , String > vars = PropertiesUtil . createPrefixMap ( profile . getConfiguration ( ) , ExecutionScriptHandler . KEY_ENV_PREFIX ) ; Map < String , String > resolved = new TreeMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : vars . entrySet ( ) ) { String key = entry . getKey ( ) ; String unresolved = entry . getValue ( ) ; try { String value = profile . getContext ( ) . getContextParameters ( ) . replace ( unresolved , true ) ; resolved . put ( key , value ) ; } catch ( IllegalArgumentException e ) { YSLOG . error ( e , "" , profile . getPrefix ( ) , ExecutionScriptHandler . KEY_ENV_PREFIX , key , unresolved ) ; throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , ExecutionScriptHandler . KEY_ENV_PREFIX , key , unresolved ) , e ) ; } } LOG . debug ( "" , profile . getPrefix ( ) , resolved ) ; return resolved ; } protected abstract void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException ; public final String getResourceId ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException { return resourceId ; } public Map < String , String > getProperties ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException { return properties ; } public Map < String , String > getEnvironmentVariables ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException { return environmentVariables ; } public void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { voidSetUp ( context ) ; } finally { monitor . close ( ) ; } } public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { voidCleanUp ( context ) ; } finally { monitor . close ( ) ; } } protected final void voidSetUp ( ExecutionContext context ) { YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , getHandlerId ( ) ) ; } protected final void voidCleanUp ( ExecutionContext context ) { YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , getHandlerId ( ) ) ; } } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . List ; public abstract class JobScheduler implements Service { @ Override public final void configure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { try { doConfigure ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , profile . getPrefix ( ) ) , e ) ; } } protected void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { return ; } public static final ErrorHandler STRICT = new ErrorHandler ( ) { @ Override public boolean handle ( ExecutionContext context , IOException exception ) { return false ; } } ; public static final ErrorHandler BEST_EFFORT = new ErrorHandler ( ) { @ Override public boolean handle ( ExecutionContext context , IOException exception ) { return true ; } } ; public abstract void execute ( PhaseMonitor monitor , ExecutionContext context , List < ? extends Job > jobs , ErrorHandler errorHandler ) throws InterruptedException , IOException ; public abstract static class ErrorHandler { public abstract boolean handle ( ExecutionContext context , IOException exception ) ; } } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class HadoopScript implements ExecutionScript { static final Logger LOG = LoggerFactory . getLogger ( HadoopScript . class ) ; private final String id ; private final Set < String > blockerIds ; private final String className ; private final Map < String , String > hadoopProperties ; private final Map < String , String > environmentVariables ; private final boolean resolved ; public HadoopScript ( String id , Set < String > blockerIds , String className , Map < String , String > hadoopProperties , Map < String , String > environmentVariables ) { this ( id , blockerIds , className , hadoopProperties , environmentVariables , false ) ; } private HadoopScript ( String id , Set < String > blockerIds , String className , Map < String , String > hadoopProperties , Map < String , String > environmentVariables , boolean resolved ) { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } if ( blockerIds == null ) { throw new IllegalArgumentException ( "" ) ; } if ( className == null ) { throw new IllegalArgumentException ( "" ) ; } if ( hadoopProperties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( environmentVariables == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = id ; this . blockerIds = Collections . unmodifiableSet ( new TreeSet < String > ( blockerIds ) ) ; this . className = className ; this . hadoopProperties = Collections . unmodifiableMap ( new LinkedHashMap < String , String > ( hadoopProperties ) ) ; this . environmentVariables = Collections . unmodifiableMap ( new LinkedHashMap < String , String > ( environmentVariables ) ) ; this . resolved = resolved ; } @ Override public Kind getKind ( ) { return Kind . HADOOP ; } @ Override public String getId ( ) { return id ; } @ Override public Set < String > getBlockerIds ( ) { return blockerIds ; } public String getClassName ( ) { return className ; } public Map < String , String > getHadoopProperties ( ) { return hadoopProperties ; } @ Override public Map < String , String > getEnvironmentVariables ( ) { return environmentVariables ; } @ Override public boolean isResolved ( ) { return resolved ; } @ Override public HadoopScript resolve ( ExecutionContext context , ExecutionScriptHandler < ? > handler ) throws InterruptedException , IOException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( handler == null ) { throw new IllegalArgumentException ( "" ) ; } if ( isResolved ( ) ) { return this ; } LOG . debug ( "" , this ) ; PlaceholderResolver resolver = new PlaceholderResolver ( this , context , handler ) ; Map < String , String > resolvedProperties = new LinkedHashMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : getHadoopProperties ( ) . entrySet ( ) ) { resolvedProperties . put ( entry . getKey ( ) , resolver . resolve ( entry . getValue ( ) ) ) ; } LOG . debug ( "" , resolvedProperties ) ; Map < String , String > resolvedEnvironments = new LinkedHashMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : getEnvironmentVariables ( ) . entrySet ( ) ) { resolvedEnvironments . put ( entry . getKey ( ) , resolver . resolve ( entry . getValue ( ) ) ) ; } LOG . debug ( "" , resolvedEnvironments ) ; return new HadoopScript ( getId ( ) , getBlockerIds ( ) , className , resolvedProperties , resolvedEnvironments , true ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getId ( ) , getBlockerIds ( ) , getClassName ( ) , getHadoopProperties ( ) , getEnvironmentVariables ( ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + id . hashCode ( ) ; result = prime * result + blockerIds . hashCode ( ) ; result = prime * result + className . hashCode ( ) ; result = prime * result + hadoopProperties . hashCode ( ) ; result = prime * result + environmentVariables . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } HadoopScript other = ( HadoopScript ) obj ; if ( ! id . equals ( other . id ) ) { return false ; } if ( ! blockerIds . equals ( other . blockerIds ) ) { return false ; } if ( ! className . equals ( other . className ) ) { return false ; } if ( ! hadoopProperties . equals ( other . hadoopProperties ) ) { return false ; } if ( ! environmentVariables . equals ( other . environmentVariables ) ) { return false ; } return true ; } } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Map ; import java . util . Properties ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . util . PropertiesUtil ; public class ServiceProfile < T extends Service > { static final Logger LOG = LoggerFactory . getLogger ( ServiceProfile . class ) ; private final String prefix ; private final Class < ? extends T > serviceClass ; private final Map < String , String > configuration ; private final ProfileContext context ; public ServiceProfile ( String prefix , Class < ? extends T > serviceClass , Map < String , String > configuration , ProfileContext context ) { if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } if ( serviceClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } this . prefix = prefix ; this . serviceClass = serviceClass ; this . configuration = Collections . unmodifiableMap ( new TreeMap < String , String > ( configuration ) ) ; this . context = context ; } public String getPrefix ( ) { return prefix ; } public Class < ? extends T > getServiceClass ( ) { return serviceClass ; } public Map < String , String > getConfiguration ( ) { return configuration ; } public String getConfiguration ( String key , boolean mandatory , boolean resolve ) { if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } String value = getConfiguration ( ) . get ( key ) ; return normalize ( key , value , mandatory , resolve ) ; } public String normalize ( String key , String value , boolean mandatory , boolean resolve ) { if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } String string = value ; if ( string == null ) { if ( mandatory ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , getPrefix ( ) + '' + key ) ) ; } else { return null ; } } string = string . trim ( ) ; if ( resolve ) { try { string = getContext ( ) . getContextParameters ( ) . replace ( string , true ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , getPrefix ( ) + '' + key , string ) , e ) ; } } if ( string . isEmpty ( ) ) { if ( mandatory ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , getPrefix ( ) + '' + key ) ) ; } else { return null ; } } return string ; } public ProfileContext getContext ( ) { return context ; } @ Deprecated public ClassLoader getClassLoader ( ) { return getContext ( ) . getClassLoader ( ) ; } public T newInstance ( ) throws InterruptedException , IOException { LOG . debug ( "" , prefix , serviceClass . getName ( ) ) ; T instance ; try { instance = serviceClass . newInstance ( ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , getPrefix ( ) , getServiceClass ( ) . getName ( ) ) , e ) ; } instance . configure ( this ) ; return instance ; } @ Deprecated public T newInstance ( VariableResolver variables ) throws InterruptedException , IOException { if ( variables == null ) { throw new IllegalArgumentException ( "" ) ; } return newInstance ( ) ; } @ Deprecated public static < T extends Service > ServiceProfile < T > load ( Properties properties , String prefix , Class < T > serviceBaseClass , ClassLoader classLoader ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } if ( serviceBaseClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( classLoader == null ) { throw new IllegalArgumentException ( "" ) ; } return load ( properties , prefix , serviceBaseClass , ProfileContext . system ( classLoader ) ) ; } public static < T extends Service > ServiceProfile < T > load ( Properties properties , String prefix , Class < T > serviceBaseClass , ProfileContext context ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } if ( serviceBaseClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } String targetClassName = properties . getProperty ( prefix ) ; if ( targetClassName == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix ) ) ; } Class < ? > loaded ; try { loaded = context . getClassLoader ( ) . loadClass ( targetClassName ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix , targetClassName ) ) ; } if ( serviceBaseClass . isAssignableFrom ( loaded ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix , targetClassName , serviceBaseClass . getName ( ) ) ) ; } Class < ? extends T > targetClass = loaded . asSubclass ( serviceBaseClass ) ; Map < String , String > conf = PropertiesUtil . createPrefixMap ( properties , prefix + '' ) ; return new ServiceProfile < T > ( prefix , targetClass , conf , context ) ; } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } properties . setProperty ( prefix , getServiceClass ( ) . getName ( ) ) ; for ( Map . Entry < String , String > entry : getConfiguration ( ) . entrySet ( ) ) { properties . setProperty ( prefix + '' + entry . getKey ( ) , entry . getValue ( ) ) ; } } } package com . asakusafw . yaess . core ; package com . asakusafw . yaess . core ; import java . io . IOException ; import java . util . Map ; public interface ExecutionScriptHandler < T extends ExecutionScript > extends Service { String KEY_ENV_PREFIX = "" ; String KEY_PROP_PREFIX = "" ; String KEY_RESOURCE = "" ; String DEFAULT_RESOURCE_ID = "" ; String getHandlerId ( ) ; String getResourceId ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException ; Map < String , String > getProperties ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException ; Map < String , String > getEnvironmentVariables ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException ; void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException ; void execute ( ExecutionMonitor monitor , ExecutionContext context , T script ) throws InterruptedException , IOException ; void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException ; } package com . asakusafw . yaess . core ; public class ProfileContext { private final ClassLoader classLoader ; private final VariableResolver contextParameters ; public ProfileContext ( ClassLoader classLoader , VariableResolver contextParameters ) { if ( classLoader == null ) { throw new IllegalArgumentException ( "" ) ; } if ( contextParameters == null ) { throw new IllegalArgumentException ( "" ) ; } this . classLoader = classLoader ; this . contextParameters = contextParameters ; } public static ProfileContext system ( ClassLoader classLoader ) { return new ProfileContext ( classLoader , new VariableResolver ( System . getenv ( ) ) ) ; } public ClassLoader getClassLoader ( ) { return classLoader ; } public VariableResolver getContextParameters ( ) { return contextParameters ; } } package com . asakusafw . yaess . core . util ; import java . util . Map ; import java . util . NavigableMap ; import java . util . Properties ; import java . util . Set ; import java . util . TreeMap ; import java . util . TreeSet ; public final class PropertiesUtil { public static Set < String > getChildKeys ( Map < ? , ? > properties , String parentPrefix , String delimitier ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parentPrefix == null ) { throw new IllegalArgumentException ( "" ) ; } if ( delimitier == null ) { throw new IllegalArgumentException ( "" ) ; } int parentLength = parentPrefix . length ( ) ; Set < String > results = new TreeSet < String > ( ) ; for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { if ( ( entry . getKey ( ) instanceof String ) == false || ( entry . getValue ( ) instanceof String ) == false ) { continue ; } String name = ( String ) entry . getKey ( ) ; if ( name . startsWith ( parentPrefix ) == false ) { continue ; } int index = name . indexOf ( delimitier , parentLength ) ; if ( index < ) { results . add ( name ) ; } else { results . add ( name . substring ( , index ) ) ; } } return results ; } public static NavigableMap < String , String > createPrefixMap ( Map < ? , ? > properties , String prefix ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } NavigableMap < String , String > results = new TreeMap < String , String > ( ) ; for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { if ( ( entry . getKey ( ) instanceof String ) == false || ( entry . getValue ( ) instanceof String ) == false ) { continue ; } String name = ( String ) entry . getKey ( ) ; if ( name . startsWith ( prefix ) == false ) { continue ; } results . put ( name . substring ( prefix . length ( ) ) , ( String ) entry . getValue ( ) ) ; } return results ; } private PropertiesUtil ( ) { return ; } } package com . asakusafw . yaess . core . util ; package com . asakusafw . yaess . core . util ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import com . asakusafw . yaess . core . YaessCoreLogger ; import com . asakusafw . yaess . core . YaessLogger ; public class StreamRedirectTask implements Runnable { static final YaessLogger YSLOG = new YaessCoreLogger ( StreamRedirectTask . class ) ; private final InputStream input ; private final OutputStream output ; private final boolean closeInput ; private final boolean closeOutput ; public StreamRedirectTask ( InputStream input , OutputStream output ) { this ( input , output , false , false ) ; } public StreamRedirectTask ( InputStream input , OutputStream output , boolean closeInput , boolean closeOutput ) { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . input = input ; this . output = output ; this . closeInput = closeInput ; this . closeOutput = closeOutput ; } @ Override public void run ( ) { boolean outputFailed = false ; try { InputStream in = input ; OutputStream out = output ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = in . read ( buf ) ; if ( read == - ) { break ; } if ( outputFailed == false ) { try { out . write ( buf , , read ) ; } catch ( IOException e ) { outputFailed = true ; YSLOG . warn ( e , "" ) ; } } } } catch ( IOException e ) { YSLOG . warn ( e , "" ) ; } finally { if ( closeInput ) { close ( input ) ; } if ( closeOutput ) { close ( output ) ; } } } private static void close ( InputStream c ) { try { c . close ( ) ; } catch ( IOException e ) { YSLOG . warn ( e , "" ) ; } } private static void close ( OutputStream c ) { try { c . close ( ) ; } catch ( IOException e ) { YSLOG . warn ( e , "" ) ; } } } package com . asakusafw . yaess . core . task ; import java . io . IOException ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; public class CleanupJob extends HandlerLifecycleJob { private static final String JOB_ID = "" ; public CleanupJob ( ExecutionScriptHandler < ? > handler ) { super ( handler ) ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { handler . cleanUp ( monitor , context ) ; } @ Override public String getServiceLabel ( ) { return handler . getHandlerId ( ) ; } @ Override public String getJobLabel ( ) { return JOB_ID ; } } package com . asakusafw . yaess . core . task ; package com . asakusafw . yaess . core . task ; import java . io . IOException ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; import com . asakusafw . yaess . core . Job ; public abstract class HandlerLifecycleJob extends Job { protected final ExecutionScriptHandler < ? > handler ; public HandlerLifecycleJob ( ExecutionScriptHandler < ? > handler ) { if ( handler == null ) { throw new IllegalArgumentException ( "" ) ; } this . handler = handler ; } @ Override public String getId ( ) { return handler . getHandlerId ( ) ; } @ Override public Set < String > getBlockerIds ( ) { return Collections . emptySet ( ) ; } @ Override public String getResourceId ( ExecutionContext context ) throws InterruptedException , IOException { return handler . getResourceId ( context , null ) ; } } package com . asakusafw . yaess . core . task ; import java . io . IOException ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; public class SetupJob extends HandlerLifecycleJob { private static final String JOB_ID = "" ; public SetupJob ( ExecutionScriptHandler < ? > handler ) { super ( handler ) ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { handler . setUp ( monitor , context ) ; } @ Override public String getServiceLabel ( ) { return handler . getHandlerId ( ) ; } @ Override public String getJobLabel ( ) { return JOB_ID ; } } package com . asakusafw . yaess . core . task ; import java . io . IOException ; import java . util . Set ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; import com . asakusafw . yaess . core . Job ; public class ScriptJob < T extends ExecutionScript > extends Job { private final ExecutionScriptHandler < ? super T > handler ; private final T script ; public ScriptJob ( T script , ExecutionScriptHandler < ? super T > handler ) { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } if ( handler == null ) { throw new IllegalArgumentException ( "" ) ; } this . handler = handler ; this . script = script ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { handler . execute ( monitor , context , script ) ; } @ Override public String getServiceLabel ( ) { return handler . getHandlerId ( ) ; } @ Override public String getJobLabel ( ) { return script . getId ( ) ; } @ Override public String getId ( ) { return script . getId ( ) ; } @ Override public Set < String > getBlockerIds ( ) { return script . getBlockerIds ( ) ; } @ Override public String getResourceId ( ExecutionContext context ) throws InterruptedException , IOException { return handler . getResourceId ( context , script ) ; } } package com . asakusafw . yaess . core . task ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . TreeMap ; import java . util . UUID ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . Callable ; import java . util . concurrent . CancellationException ; import java . util . concurrent . ConcurrentHashMap ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . FutureTask ; import java . util . concurrent . LinkedBlockingQueue ; import java . util . concurrent . ThreadFactory ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . yaess . core . * ; import com . asakusafw . yaess . core . JobScheduler . ErrorHandler ; public class ExecutionTask { static final String KEY_SKIP_FLOWS = "" ; static final String KEY_SERIALIZE_FLOWS = "" ; static final String KEY_VERIFY_APPLICATION = "" ; static final String KEY_VERIFY_DRYRUN = "" ; static final YaessLogger YSLOG = new YaessCoreLogger ( ExecutionTask . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ExecutionTask . class ) ; private final ExecutionMonitorProvider monitors ; private final ExecutionLockProvider locks ; private final JobScheduler scheduler ; private final HadoopScriptHandler hadoopHandler ; private final Map < String , CommandScriptHandler > commandHandlers ; private final BatchScript script ; private final Map < String , String > batchArguments ; private final Map < String , String > subprocessEnvironmentVaritables = new ConcurrentHashMap < String , String > ( ) ; private final Set < String > skipFlows = Collections . synchronizedSet ( new HashSet < String > ( ) ) ; private volatile RuntimeContext runtimeContext ; private volatile boolean serializeFlows = false ; public ExecutionTask ( ExecutionMonitorProvider monitors , ExecutionLockProvider locks , JobScheduler scheduler , HadoopScriptHandler hadoopHandler , Map < String , CommandScriptHandler > commandHandlers , BatchScript script , Map < String , String > batchArguments ) { if ( monitors == null ) { throw new IllegalArgumentException ( "" ) ; } if ( locks == null ) { throw new IllegalArgumentException ( "" ) ; } if ( scheduler == null ) { throw new IllegalArgumentException ( "" ) ; } if ( hadoopHandler == null ) { throw new IllegalArgumentException ( "" ) ; } if ( commandHandlers == null ) { throw new IllegalArgumentException ( "" ) ; } if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } if ( batchArguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . monitors = monitors ; this . locks = locks ; this . scheduler = scheduler ; this . hadoopHandler = hadoopHandler ; this . commandHandlers = Collections . unmodifiableMap ( new HashMap < String , CommandScriptHandler > ( commandHandlers ) ) ; this . script = script ; this . batchArguments = Collections . unmodifiableMap ( new LinkedHashMap < String , String > ( batchArguments ) ) ; this . runtimeContext = RuntimeContext . get ( ) ; } public static ExecutionTask load ( YaessProfile profile , Properties script , Map < String , String > batchArguments ) throws InterruptedException , IOException { return load ( profile , script , batchArguments , Collections . < String , String > emptyMap ( ) ) ; } public static ExecutionTask load ( YaessProfile profile , Properties script , Map < String , String > batchArguments , Map < String , String > yaessArguments ) throws InterruptedException , IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } if ( batchArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( yaessArguments == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; ExecutionMonitorProvider monitors = profile . getMonitors ( ) . newInstance ( ) ; LOG . debug ( "" ) ; ExecutionLockProvider locks = profile . getLocks ( ) . newInstance ( ) ; LOG . debug ( "" ) ; JobScheduler scheduler = profile . getScheduler ( ) . newInstance ( ) ; LOG . debug ( "" ) ; HadoopScriptHandler hadoopHandler = profile . getHadoopHandler ( ) . newInstance ( ) ; LOG . debug ( "" ) ; Map < String , CommandScriptHandler > commandHandlers = new HashMap < String , CommandScriptHandler > ( ) ; for ( Map . Entry < String , ServiceProfile < CommandScriptHandler > > entry : profile . getCommandHandlers ( ) . entrySet ( ) ) { commandHandlers . put ( entry . getKey ( ) , entry . getValue ( ) . newInstance ( ) ) ; } LOG . debug ( "" ) ; BatchScript batch = BatchScript . load ( script ) ; ExecutionTask result = new ExecutionTask ( monitors , locks , scheduler , hadoopHandler , commandHandlers , batch , batchArguments ) ; LOG . debug ( "" ) ; Map < String , String > copyDefinitions = new TreeMap < String , String > ( yaessArguments ) ; consumeRuntimeContext ( result , copyDefinitions , batch ) ; consumeSkipFlows ( result , copyDefinitions , batch ) ; consumeSerializeFlows ( result , copyDefinitions , batch ) ; checkRest ( copyDefinitions ) ; return result ; } private static void consumeRuntimeContext ( ExecutionTask result , Map < String , String > copyDefinitions , BatchScript script ) { assert result != null ; assert copyDefinitions != null ; assert script != null ; RuntimeContext rc = RuntimeContext . get ( ) . batchId ( script . getId ( ) ) . buildId ( script . getBuildId ( ) ) ; Ternary dryRunResult = consumeBoolean ( copyDefinitions , KEY_VERIFY_DRYRUN ) ; if ( dryRunResult == Ternary . TRUE ) { rc = rc . mode ( ExecutionMode . SIMULATION ) ; } else if ( dryRunResult == Ternary . FALSE ) { rc = rc . mode ( ExecutionMode . PRODUCTION ) ; } Ternary verify = consumeBoolean ( copyDefinitions , KEY_VERIFY_APPLICATION ) ; if ( verify == Ternary . FALSE ) { rc = rc . buildId ( null ) ; } result . runtimeContext = rc ; result . getEnv ( ) . putAll ( rc . unapply ( ) ) ; } private static void consumeSkipFlows ( ExecutionTask task , Map < String , String > copyDefinitions , BatchScript script ) { assert task != null ; assert copyDefinitions != null ; assert script != null ; String flows = copyDefinitions . remove ( KEY_SKIP_FLOWS ) ; if ( flows == null || flows . trim ( ) . isEmpty ( ) ) { return ; } LOG . debug ( "" , KEY_SKIP_FLOWS , flows ) ; for ( String flowIdCandidate : flows . split ( "" ) ) { String flowId = flowIdCandidate . trim ( ) ; if ( flowId . isEmpty ( ) == false ) { FlowScript flow = script . findFlow ( flowId ) ; if ( flow == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , KEY_SKIP_FLOWS , flowId ) ) ; } task . skipFlows . add ( flowId ) ; } } } private static void consumeSerializeFlows ( ExecutionTask task , Map < String , String > copyDefinitions , BatchScript script ) { assert task != null ; assert copyDefinitions != null ; assert script != null ; Ternary serialize = consumeBoolean ( copyDefinitions , KEY_SERIALIZE_FLOWS ) ; if ( serialize == null ) { return ; } task . serializeFlows = serialize == Ternary . TRUE ; } private static Ternary consumeBoolean ( Map < String , String > copyDefinitions , String key ) { assert copyDefinitions != null ; String value = copyDefinitions . remove ( key ) ; if ( value == null ) { return Ternary . UNDEF ; } value = value . trim ( ) ; LOG . debug ( "" , key , value ) ; if ( value . equalsIgnoreCase ( "" ) ) { return Ternary . TRUE ; } else if ( value . equalsIgnoreCase ( "" ) ) { return Ternary . FALSE ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , key , value ) ) ; } } private static void checkRest ( Map < String , String > copyDefinitions ) { assert copyDefinitions != null ; if ( copyDefinitions . isEmpty ( ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , copyDefinitions . keySet ( ) ) ) ; } } Set < String > getSkipFlows ( ) { return skipFlows ; } void setSerializeFlows ( boolean serialize ) { this . serializeFlows = serialize ; } void setRuntimeContext ( RuntimeContext runtimeContext ) { this . runtimeContext = runtimeContext ; } Map < String , String > getEnv ( ) { return this . subprocessEnvironmentVaritables ; } public void executeBatch ( String batchId ) throws InterruptedException , IOException { if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } ExecutorService executor = createJobflowExecutor ( batchId ) ; YSLOG . info ( "" , batchId ) ; long start = System . currentTimeMillis ( ) ; try { ExecutionLock lock = acquireExecutionLock ( batchId ) ; try { BatchScheduler batchScheduler = new BatchScheduler ( batchId , script , lock , executor ) ; batchScheduler . run ( ) ; } finally { lock . close ( ) ; } YSLOG . info ( "" , batchId ) ; } catch ( IOException e ) { YSLOG . error ( e , "" , batchId ) ; throw e ; } catch ( InterruptedException e ) { YSLOG . warn ( e , "" , batchId ) ; throw e ; } finally { long end = System . currentTimeMillis ( ) ; YSLOG . info ( "" , batchId , end - start ) ; } } private ExecutionLock acquireExecutionLock ( String batchId ) throws IOException { assert batchId != null ; if ( runtimeContext . canExecute ( locks ) ) { return locks . newInstance ( batchId ) ; } else { return ExecutionLock . NULL ; } } private PhaseMonitor obtainPhaseMonitor ( ExecutionContext context ) throws InterruptedException , IOException { assert context != null ; if ( runtimeContext . canExecute ( monitors ) ) { return monitors . newInstance ( context ) ; } else { return PhaseMonitor . NULL ; } } private ExecutorService createJobflowExecutor ( final String batchId ) { assert batchId != null ; ThreadFactory threadFactory = new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable r ) { Thread thread = new Thread ( r ) ; thread . setName ( MessageFormat . format ( "" , batchId ) ) ; thread . setDaemon ( true ) ; return thread ; } } ; if ( serializeFlows ) { return Executors . newFixedThreadPool ( , threadFactory ) ; } else { return Executors . newCachedThreadPool ( threadFactory ) ; } } public void executeFlow ( String batchId , String flowId , String executionId ) throws InterruptedException , IOException { if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } FlowScript flow = script . findFlow ( flowId ) ; if ( flow == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , batchId , flowId , executionId ) ) ; } ExecutionLock lock = acquireExecutionLock ( batchId ) ; try { lock . beginFlow ( flowId , executionId ) ; executeFlow ( batchId , flow , executionId ) ; lock . endFlow ( flowId , executionId ) ; } finally { lock . close ( ) ; } } public void executePhase ( String batchId , String flowId , String executionId , ExecutionPhase phase ) throws InterruptedException , IOException { if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( phase == null ) { throw new IllegalArgumentException ( "" ) ; } ExecutionContext context = new ExecutionContext ( batchId , flowId , executionId , phase , batchArguments , subprocessEnvironmentVaritables ) ; executePhase ( context ) ; } public void executePhase ( ExecutionContext context ) throws InterruptedException , IOException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } FlowScript flow = script . findFlow ( context . getFlowId ( ) ) ; if ( flow == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) ) ) ; } Set < ExecutionScript > executions = flow . getScripts ( ) . get ( context . getPhase ( ) ) ; ExecutionLock lock = acquireExecutionLock ( context . getBatchId ( ) ) ; try { lock . beginFlow ( context . getFlowId ( ) , context . getExecutionId ( ) ) ; executePhase ( context , executions ) ; lock . endFlow ( context . getFlowId ( ) , context . getExecutionId ( ) ) ; } finally { lock . close ( ) ; } } void executeFlow ( String batchId , FlowScript flow , String executionId ) throws InterruptedException , IOException { assert batchId != null ; assert flow != null ; assert executionId != null ; YSLOG . info ( "" , batchId , flow . getId ( ) , executionId ) ; long start = System . currentTimeMillis ( ) ; try { if ( skipFlows . contains ( flow . getId ( ) ) ) { YSLOG . info ( "" , batchId , flow . getId ( ) , executionId ) ; return ; } executePhase ( batchId , flow , executionId , ExecutionPhase . SETUP ) ; boolean succeed = false ; try { executePhase ( batchId , flow , executionId , ExecutionPhase . INITIALIZE ) ; executePhase ( batchId , flow , executionId , ExecutionPhase . IMPORT ) ; executePhase ( batchId , flow , executionId , ExecutionPhase . PROLOGUE ) ; executePhase ( batchId , flow , executionId , ExecutionPhase . MAIN ) ; executePhase ( batchId , flow , executionId , ExecutionPhase . EPILOGUE ) ; executePhase ( batchId , flow , executionId , ExecutionPhase . EXPORT ) ; succeed = true ; } finally { if ( succeed ) { executePhase ( batchId , flow , executionId , ExecutionPhase . FINALIZE ) ; } else { YSLOG . info ( "" , batchId , flow . getId ( ) , executionId ) ; try { executePhase ( batchId , flow , executionId , ExecutionPhase . FINALIZE ) ; } catch ( Exception e ) { YSLOG . warn ( e , "" , batchId , flow . getId ( ) , executionId ) ; } } } try { executePhase ( batchId , flow , executionId , ExecutionPhase . CLEANUP ) ; } catch ( Exception e ) { YSLOG . warn ( e , "" , batchId , flow . getId ( ) , executionId ) ; } YSLOG . info ( "" , batchId , flow . getId ( ) , executionId ) ; } catch ( IOException e ) { YSLOG . error ( e , "" , batchId , flow . getId ( ) , executionId ) ; throw e ; } catch ( InterruptedException e ) { YSLOG . warn ( e , "" , batchId , flow . getId ( ) , executionId ) ; throw e ; } finally { long end = System . currentTimeMillis ( ) ; YSLOG . info ( "" , batchId , flow . getId ( ) , executionId , end - start ) ; } } private void executePhase ( String batchId , FlowScript flow , String executionId , ExecutionPhase phase ) throws InterruptedException , IOException { ExecutionContext context = new ExecutionContext ( batchId , flow . getId ( ) , executionId , phase , batchArguments , subprocessEnvironmentVaritables ) ; Set < ExecutionScript > scripts = flow . getScripts ( ) . get ( phase ) ; assert scripts != null ; executePhase ( context , scripts ) ; } private void executePhase ( ExecutionContext context , Set < ExecutionScript > executions ) throws InterruptedException , IOException { assert context != null ; assert executions != null ; YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) ) ; long start = System . currentTimeMillis ( ) ; try { if ( skipFlows . contains ( context . getFlowId ( ) ) ) { YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) ) ; return ; } List < ? extends Job > jobs ; ErrorHandler handler ; switch ( context . getPhase ( ) ) { case SETUP : jobs = buildSetupJobs ( context ) ; handler = JobScheduler . STRICT ; break ; case CLEANUP : jobs = buildCleanupJobs ( context ) ; handler = JobScheduler . BEST_EFFORT ; break ; case FINALIZE : jobs = buildExecutionJobs ( context , executions ) ; handler = JobScheduler . BEST_EFFORT ; break ; default : jobs = buildExecutionJobs ( context , executions ) ; handler = JobScheduler . STRICT ; break ; } PhaseMonitor monitor = obtainPhaseMonitor ( context ) ; try { scheduler . execute ( monitor , context , jobs , handler ) ; } finally { monitor . close ( ) ; } YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) ) ; } catch ( IOException e ) { YSLOG . error ( e , "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) ) ; throw e ; } catch ( InterruptedException e ) { YSLOG . warn ( e , "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) ) ; throw e ; } finally { long end = System . currentTimeMillis ( ) ; YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , end - start ) ; } } private List < SetupJob > buildSetupJobs ( ExecutionContext context ) { assert context != null ; List < SetupJob > results = new ArrayList < SetupJob > ( ) ; results . add ( new SetupJob ( hadoopHandler ) ) ; for ( CommandScriptHandler commandHandler : commandHandlers . values ( ) ) { results . add ( new SetupJob ( commandHandler ) ) ; } return results ; } private List < CleanupJob > buildCleanupJobs ( ExecutionContext context ) { assert context != null ; List < CleanupJob > results = new ArrayList < CleanupJob > ( ) ; results . add ( new CleanupJob ( hadoopHandler ) ) ; for ( CommandScriptHandler commandHandler : commandHandlers . values ( ) ) { results . add ( new CleanupJob ( commandHandler ) ) ; } return results ; } private List < ScriptJob < ? > > buildExecutionJobs ( ExecutionContext context , Set < ExecutionScript > executions ) throws IOException , InterruptedException { assert context != null ; assert executions != null ; List < ScriptJob < ? > > results = new ArrayList < ScriptJob < ? > > ( ) ; for ( ExecutionScript execution : executions ) { switch ( execution . getKind ( ) ) { case COMMAND : { CommandScript exec = ( CommandScript ) execution ; String profileName = exec . getProfileName ( ) ; CommandScriptHandler handler = profileName == null ? null : commandHandlers . get ( profileName ) ; if ( handler == null ) { LOG . debug ( "" , profileName , exec . getId ( ) ) ; handler = commandHandlers . get ( CommandScriptHandler . PROFILE_WILDCARD ) ; } if ( handler == null ) { throw new IOException ( MessageFormat . format ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) . getSymbol ( ) , exec . getModuleName ( ) , exec . getId ( ) , profileName ) ) ; } results . add ( new ScriptJob < CommandScript > ( exec . resolve ( context , handler ) , handler ) ) ; break ; } case HADOOP : { HadoopScript exec = ( HadoopScript ) execution ; results . add ( new ScriptJob < HadoopScript > ( exec . resolve ( context , hadoopHandler ) , hadoopHandler ) ) ; break ; } default : throw new AssertionError ( MessageFormat . format ( "" , execution ) ) ; } } return results ; } private class BatchScheduler { final String batchId ; final LinkedList < FlowScript > flows ; final ExecutionLock lock ; final ExecutorService executor ; final Map < String , FlowScriptTask > running ; final Set < String > blocking ; final BlockingQueue < FlowScriptTask > doneQueue ; BatchScheduler ( String batchId , BatchScript batchScript , ExecutionLock lock , ExecutorService executor ) { assert batchId != null ; assert batchScript != null ; assert lock != null ; assert executor != null ; this . batchId = batchId ; this . flows = new LinkedList < FlowScript > ( batchScript . getAllFlows ( ) ) ; this . lock = lock ; this . executor = executor ; this . running = new HashMap < String , FlowScriptTask > ( ) ; this . blocking = new HashSet < String > ( ) ; for ( FlowScript flow : flows ) { blocking . add ( flow . getId ( ) ) ; } this . doneQueue = new LinkedBlockingQueue < FlowScriptTask > ( ) ; } public void run ( ) throws InterruptedException , IOException { try { while ( flows . isEmpty ( ) == false ) { boolean submitted = submit ( ) ; if ( submitted == false ) { if ( running . isEmpty ( ) ) { throw new IOException ( MessageFormat . format ( "" , batchId , blocking ) ) ; } waitForComplete ( ) ; } } while ( running . isEmpty ( ) == false ) { waitForComplete ( ) ; } } finally { YSLOG . info ( "" , batchId ) ; for ( FlowScriptTask task : running . values ( ) ) { task . cancel ( true ) ; } while ( running . isEmpty ( ) == false ) { try { waitForComplete ( ) ; } catch ( IOException e ) { YSLOG . warn ( e , "" , batchId ) ; } } } } private boolean submit ( ) { LOG . debug ( "" , batchId ) ; boolean submitted = false ; for ( Iterator < FlowScript > iter = flows . iterator ( ) ; iter . hasNext ( ) ; ) { FlowScript flow = iter . next ( ) ; boolean blocked = false ; for ( String blockerId : flow . getBlockerIds ( ) ) { if ( blocking . contains ( blockerId ) ) { blocked = true ; break ; } } if ( blocked == false ) { submit ( flow ) ; iter . remove ( ) ; submitted = true ; } } return submitted ; } private void submit ( final FlowScript flow ) { LOG . debug ( "" , flow . getId ( ) , batchId ) ; FlowScriptTask task = new FlowScriptTask ( flow , doneQueue , new Callable < Void > ( ) { @ Override public Void call ( ) throws InterruptedException , IOException { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } String executionId = UUID . randomUUID ( ) . toString ( ) ; LOG . debug ( "" , flow . getId ( ) , executionId ) ; lock . beginFlow ( flow . getId ( ) , executionId ) ; executeFlow ( batchId , flow , executionId ) ; lock . endFlow ( flow . getId ( ) , executionId ) ; LOG . debug ( "" , flow . getId ( ) , batchId ) ; return null ; } } ) ; YSLOG . info ( "" , batchId , flow . getId ( ) ) ; executor . execute ( task ) ; running . put ( flow . getId ( ) , task ) ; } private void waitForComplete ( ) throws InterruptedException , IOException { LOG . debug ( "" , batchId ) ; FlowScriptTask done = doneQueue . take ( ) ; assert done . isDone ( ) ; FlowScript flow = done . script ; try { done . get ( ) ; boolean blocked = blocking . remove ( flow . getId ( ) ) ; assert blocked ; } catch ( CancellationException e ) { YSLOG . info ( e , "" , batchId , flow . getId ( ) ) ; } catch ( ExecutionException e ) { if ( e . getCause ( ) instanceof IOException ) { throw ( IOException ) e . getCause ( ) ; } else if ( e . getCause ( ) instanceof InterruptedException ) { throw ( InterruptedException ) e . getCause ( ) ; } else if ( e . getCause ( ) instanceof Error ) { throw ( Error ) e . getCause ( ) ; } else { throw new IOException ( "" , e ) ; } } finally { FlowScriptTask ran = running . remove ( flow . getId ( ) ) ; assert ran != null ; } } } private static class FlowScriptTask extends FutureTask < Void > { final FlowScript script ; private final BlockingQueue < FlowScriptTask > doneQueue ; FlowScriptTask ( FlowScript script , BlockingQueue < FlowScriptTask > doneQueue , Callable < Void > callable ) { super ( callable ) ; assert script != null ; assert doneQueue != null ; this . script = script ; this . doneQueue = doneQueue ; } @ Override protected void done ( ) { try { doneQueue . put ( this ) ; } catch ( InterruptedException e ) { throw new AssertionError ( e ) ; } } } private enum Ternary { TRUE , FALSE , UNDEF , } } package com . asakusafw . yaess . core ; import java . io . Closeable ; import java . io . IOException ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public abstract class ExecutionLock implements Closeable { static final Logger LOG = LoggerFactory . getLogger ( ExecutionLock . class ) ; public static final ExecutionLock NULL = new ExecutionLock ( ) { @ Override public void endFlow ( String flowId , String executionId ) { return ; } @ Override public void beginFlow ( String flowId , String executionId ) { return ; } @ Override public void close ( ) throws IOException { return ; } } ; public abstract void beginFlow ( String flowId , String executionId ) throws IOException ; public abstract void endFlow ( String flowId , String executionId ) throws IOException ; public enum Scope { WORLD , BATCH , FLOW , EXECUTION , ; public static Scope getDefault ( ) { return EXECUTION ; } public String getSymbol ( ) { return name ( ) . toLowerCase ( ) ; } @ Override public String toString ( ) { return getSymbol ( ) ; } public static Scope findFromSymbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } return Lazy . SYMBOLS . get ( symbol ) ; } private static final class Lazy { static final Map < String , Scope > SYMBOLS ; static { Map < String , Scope > map = new HashMap < String , Scope > ( ) ; for ( Scope phase : values ( ) ) { map . put ( phase . getSymbol ( ) , phase ) ; } SYMBOLS = Collections . unmodifiableMap ( map ) ; } private Lazy ( ) { return ; } } } } package com . asakusafw . yaess . core ; import java . io . IOException ; public interface Service { void configure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException ; } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; public abstract class CoreProfile implements Service { public static final String KEY_VERSION = "" ; private volatile String version ; @ Override public final void configure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { try { configureVersion ( profile ) ; doConfigure ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , profile . getServiceClass ( ) . getName ( ) ) , e ) ; } } private void configureVersion ( ServiceProfile < ? > profile ) { assert profile != null ; this . version = profile . getConfiguration ( KEY_VERSION , true , false ) ; } protected void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { return ; } public String getVersion ( ) { return version ; } } package com . asakusafw . yaess . core ; import java . text . MessageFormat ; import java . util . ResourceBundle ; public class YaessCoreLogger extends YaessLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public YaessCoreLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . yaess . core ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public enum ExecutionPhase { SETUP , INITIALIZE , IMPORT , PROLOGUE , MAIN , EPILOGUE , EXPORT , FINALIZE , CLEANUP , ; public String getSymbol ( ) { return name ( ) . toLowerCase ( ) ; } public static ExecutionPhase findFromSymbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } return Lazy . SYMBOLS . get ( symbol ) ; } @ Override public String toString ( ) { return getSymbol ( ) ; } private static final class Lazy { static final Map < String , ExecutionPhase > SYMBOLS ; static { Map < String , ExecutionPhase > map = new HashMap < String , ExecutionPhase > ( ) ; for ( ExecutionPhase phase : values ( ) ) { map . put ( phase . getSymbol ( ) , phase ) ; } SYMBOLS = Collections . unmodifiableMap ( map ) ; } private Lazy ( ) { return ; } } } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . io . OutputStream ; public class JobMonitor implements ExecutionMonitor { private final PhaseMonitor parent ; private final String jobId ; private final double taskSizeInParent ; private double currentTaskSize ; private double currentProgress ; private boolean closed ; public JobMonitor ( PhaseMonitor parent , String jobId , double taskSizeInParent ) { if ( parent == null ) { throw new IllegalArgumentException ( "" ) ; } if ( jobId == null ) { throw new IllegalArgumentException ( "" ) ; } this . parent = parent ; this . jobId = jobId ; this . taskSizeInParent = taskSizeInParent ; } @ Override public void checkCancelled ( ) throws InterruptedException { parent . checkCancelled ( ) ; } @ Override public synchronized void open ( double taskSize ) throws IOException { if ( taskSize <= ) { throw new IllegalArgumentException ( "" ) ; } this . currentTaskSize = taskSize ; parent . onJobMonitorOpened ( jobId ) ; } @ Override public synchronized void progressed ( double size ) throws IOException { double nextProgress = currentProgress + size ; changeCurrentProgress ( nextProgress ) ; } @ Override public synchronized void setProgress ( double workedSize ) throws IOException { changeCurrentProgress ( workedSize ) ; } @ Override public OutputStream getOutput ( ) throws IOException { return parent . getJobOutput ( jobId ) ; } @ Override public synchronized void close ( ) throws IOException { changeCurrentProgress ( currentTaskSize ) ; parent . onJobMonitorClosed ( jobId ) ; } private void changeCurrentProgress ( double nextProgress ) throws IOException { if ( closed ) { return ; } closed = true ; if ( taskSizeInParent == ) { return ; } double normalized = Math . max ( , Math . min ( currentTaskSize , nextProgress ) ) ; assert <= normalized && normalized <= currentTaskSize ; double delta = normalized - currentProgress ; double deltaInParent = delta / taskSizeInParent ; currentProgress = normalized ; if ( deltaInParent != ) { parent . progressed ( deltaInParent ) ; } } } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public abstract class ExecutionLockProvider implements Service { static final Logger LOG = LoggerFactory . getLogger ( ExecutionLockProvider . class ) ; public static final String KEY_SCOPE = "" ; private volatile ExecutionLock . Scope scope ; @ Override public final void configure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { try { configureScope ( profile ) ; doConfigure ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , profile . getPrefix ( ) ) , e ) ; } } private void configureScope ( ServiceProfile < ? > profile ) throws IOException { assert profile != null ; String scopeSymbol = profile . getConfiguration ( KEY_SCOPE , false , true ) ; if ( scopeSymbol == null ) { scope = ExecutionLock . Scope . getDefault ( ) ; LOG . debug ( "" , scope . getSymbol ( ) ) ; } else { scope = ExecutionLock . Scope . findFromSymbol ( scopeSymbol ) ; if ( scope == null ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , KEY_SCOPE , scopeSymbol ) ) ; } } } protected abstract void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException ; private ExecutionLock . Scope getScope ( ) { if ( scope == null ) { throw new IllegalStateException ( ) ; } return scope ; } public final ExecutionLock newInstance ( String batchId ) throws IOException { if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } return newInstance ( getScope ( ) , batchId ) ; } protected abstract ExecutionLock newInstance ( ExecutionLock . Scope lockScope , String batchId ) throws IOException ; } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . io . OutputStream ; public abstract class PhaseMonitor implements ExecutionMonitor { public static final PhaseMonitor NULL = new PhaseMonitor ( ) { @ Override public void progressed ( double deltaSize ) { return ; } @ Override public void setProgress ( double workedSize ) throws IOException { return ; } @ Override public void open ( double taskSize ) { return ; } @ Override public void reportJobStatus ( String jobId , JobStatus status , Throwable cause ) { return ; } @ Override public void close ( ) { return ; } } ; @ Override public void checkCancelled ( ) throws InterruptedException { if ( Thread . interrupted ( ) || isCancelRequested ( ) ) { throw new InterruptedException ( ) ; } } protected boolean isCancelRequested ( ) { return false ; } @ Override public OutputStream getOutput ( ) throws IOException { return System . out ; } public ExecutionMonitor createJobMonitor ( String jobId , double childTaskSize ) { if ( jobId == null ) { throw new IllegalArgumentException ( "" ) ; } return new JobMonitor ( this , jobId , childTaskSize ) ; } public abstract void reportJobStatus ( String jobId , JobStatus status , Throwable cause ) throws IOException ; protected void onJobMonitorOpened ( String jobId ) throws IOException { return ; } protected OutputStream getJobOutput ( String jobId ) throws IOException { return getOutput ( ) ; } protected void onJobMonitorClosed ( String jobId ) throws IOException { return ; } public enum JobStatus { SUCCESS , CANCELLED , FAILED , } } package com . asakusafw . yaess . core ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Properties ; import java . util . Set ; import java . util . SortedMap ; import java . util . TreeMap ; public class BatchScript { public static final String KEY_ID = "" ; public static final String KEY_VERSION = "" ; public static final String KEY_VERIFICATION_CODE = "" ; public static final String VERSION = "" ; private final String id ; private final String buildId ; private final SortedMap < String , FlowScript > flows ; public BatchScript ( String id , Collection < FlowScript > flows ) { this ( id , null , flows ) ; } public BatchScript ( String batchId , String buildId , Collection < FlowScript > flows ) { if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flows == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = batchId ; this . buildId = buildId ; SortedMap < String , FlowScript > map = new TreeMap < String , FlowScript > ( ) ; for ( FlowScript flow : flows ) { map . put ( flow . getId ( ) , flow ) ; } this . flows = Collections . unmodifiableSortedMap ( map ) ; } public String getId ( ) { return id ; } public String getBuildId ( ) { return buildId ; } public FlowScript findFlow ( String flowId ) { if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } return flows . get ( flowId ) ; } public List < FlowScript > getAllFlows ( ) { LinkedList < FlowScript > work = new LinkedList < FlowScript > ( flows . values ( ) ) ; Set < String > blockerIds = new HashSet < String > ( flows . keySet ( ) ) ; List < FlowScript > results = new ArrayList < FlowScript > ( ) ; while ( work . isEmpty ( ) == false ) { boolean worked = false ; for ( Iterator < FlowScript > iter = work . iterator ( ) ; iter . hasNext ( ) ; ) { FlowScript script = iter . next ( ) ; boolean blocked = false ; for ( String blockerId : script . getBlockerIds ( ) ) { if ( blockerIds . contains ( blockerId ) ) { blocked = true ; break ; } } if ( blocked == false ) { iter . remove ( ) ; blockerIds . remove ( script . getId ( ) ) ; results . add ( script ) ; } } if ( worked == false ) { results . addAll ( work ) ; work . clear ( ) ; } } return results ; } public static BatchScript load ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } String version = properties . getProperty ( KEY_VERSION ) ; if ( VERSION . equals ( version ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , version ) ) ; } String batchId = properties . getProperty ( KEY_ID ) ; String verificationCode = properties . getProperty ( KEY_VERIFICATION_CODE ) ; Set < String > flowIds = FlowScript . extractFlowIds ( properties ) ; List < FlowScript > flowScripts = new ArrayList < FlowScript > ( ) ; for ( String flowId : flowIds ) { FlowScript flowScript = FlowScript . load ( properties , flowId ) ; flowScripts . add ( flowScript ) ; } return new BatchScript ( batchId , verificationCode , flowScripts ) ; } } package com . asakusafw . yaess . core ; import java . io . Closeable ; import java . io . IOException ; import java . io . OutputStream ; public interface ExecutionMonitor extends Closeable { ExecutionMonitor NULL = new ExecutionMonitor ( ) { @ Override public void progressed ( double deltaSize ) { return ; } @ Override public void setProgress ( double workedSize ) throws IOException { return ; } @ Override public void open ( double taskSize ) { return ; } @ Override public void checkCancelled ( ) throws InterruptedException { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } } @ Override public OutputStream getOutput ( ) throws IOException { return System . out ; } @ Override public void close ( ) { return ; } } ; void open ( double taskSize ) throws IOException ; void checkCancelled ( ) throws InterruptedException ; void progressed ( double deltaSize ) throws IOException ; void setProgress ( double workedSize ) throws IOException ; OutputStream getOutput ( ) throws IOException ; @ Override void close ( ) throws IOException ; } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . util . Set ; public abstract class Job { static final YaessLogger YSLOG = new YaessCoreLogger ( Job . class ) ; public final void launch ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { if ( monitor == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , getJobLabel ( ) , getServiceLabel ( ) ) ; long start = System . currentTimeMillis ( ) ; try { execute ( monitor , context ) ; YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , getJobLabel ( ) , getServiceLabel ( ) ) ; } catch ( IOException e ) { YSLOG . error ( e , "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , getJobLabel ( ) , getServiceLabel ( ) ) ; throw e ; } catch ( InterruptedException e ) { YSLOG . warn ( e , "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , getJobLabel ( ) , getServiceLabel ( ) ) ; throw e ; } finally { long end = System . currentTimeMillis ( ) ; YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , getJobLabel ( ) , getServiceLabel ( ) , end - start ) ; } } protected abstract void execute ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException ; public abstract String getJobLabel ( ) ; public abstract String getServiceLabel ( ) ; public abstract String getId ( ) ; public abstract Set < String > getBlockerIds ( ) ; public abstract String getResourceId ( ExecutionContext context ) throws InterruptedException , IOException ; } package com . asakusafw . yaess . core ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class ExecutionContext { static final Logger LOG = LoggerFactory . getLogger ( ExecutionContext . class ) ; private final String batchId ; private final String flowId ; private final String executionId ; private final ExecutionPhase phase ; private final Map < String , String > arguments ; private final Map < String , String > environmentVariables ; public ExecutionContext ( String batchId , String flowId , String executionId , ExecutionPhase phase , Map < String , String > arguments ) { this ( batchId , flowId , executionId , phase , arguments , Collections . < String , String > emptyMap ( ) ) ; } public ExecutionContext ( String batchId , String flowId , String executionId , ExecutionPhase phase , Map < String , String > arguments , Map < String , String > environmentVariables ) { if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( phase == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . batchId = batchId ; this . flowId = flowId ; this . executionId = executionId ; this . phase = phase ; this . arguments = Collections . unmodifiableMap ( new HashMap < String , String > ( arguments ) ) ; this . environmentVariables = Collections . unmodifiableMap ( new HashMap < String , String > ( environmentVariables ) ) ; } public String getBatchId ( ) { return batchId ; } public String getFlowId ( ) { return flowId ; } public String getExecutionId ( ) { return executionId ; } public ExecutionPhase getPhase ( ) { return phase ; } public Map < String , String > getArguments ( ) { return arguments ; } public Map < String , String > getEnvironmentVariables ( ) { return environmentVariables ; } public String getArgumentsAsString ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : arguments . entrySet ( ) ) { buf . append ( escape ( entry . getKey ( ) ) ) ; buf . append ( "" ) ; buf . append ( escape ( entry . getValue ( ) ) ) ; buf . append ( "" ) ; } if ( buf . length ( ) >= ) { buf . deleteCharAt ( buf . length ( ) - ) ; } return buf . toString ( ) ; } private static final Pattern TO_ESCAPED = Pattern . compile ( "" ) ; private String escape ( String string ) { assert string != null ; return TO_ESCAPED . matcher ( string ) . replaceAll ( "" ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , batchId , flowId , executionId , phase , arguments , environmentVariables ) ; } } package com . asakusafw . yaess . core ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public abstract class YaessLogger { private final Logger internal ; private final MessageFormat format = new MessageFormat ( "" ) ; private final String componentName ; public YaessLogger ( Class < ? > target , String componentName ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( componentName == null ) { throw new IllegalArgumentException ( "" ) ; } this . componentName = componentName ; this . internal = LoggerFactory . getLogger ( target ) ; } public void info ( String code , Object ... arguments ) { if ( internal . isInfoEnabled ( ) ) { String message = message ( code , arguments ) ; internal . info ( message ) ; } } public void info ( Exception exception , String code , Object ... arguments ) { if ( internal . isInfoEnabled ( ) ) { String message = message ( code , arguments ) ; internal . info ( message , exception ) ; } } public void warn ( String code , Object ... arguments ) { if ( internal . isWarnEnabled ( ) ) { String message = message ( code , arguments ) ; internal . warn ( message ) ; } } public void warn ( Exception exception , String code , Object ... arguments ) { if ( internal . isWarnEnabled ( ) ) { String message = message ( code , arguments ) ; internal . warn ( message , exception ) ; } } public void error ( String code , Object ... arguments ) { if ( internal . isErrorEnabled ( ) ) { String message = message ( code , arguments ) ; internal . error ( message ) ; } } public void error ( Exception exception , String code , Object ... arguments ) { if ( internal . isErrorEnabled ( ) ) { String message = message ( code , arguments ) ; internal . error ( message , exception ) ; } } private String message ( String code , Object ... arguments ) { assert code != null ; assert arguments != null ; String message = getMessage ( code , arguments ) ; return format . format ( new Object [ ] { componentName , code , message } ) ; } protected abstract String getMessage ( String code , Object ... arguments ) ; } package com . asakusafw . yaess . core ; public interface CommandScriptHandler extends ExecutionScriptHandler < CommandScript > { String PROFILE_WILDCARD = "" ; } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; public abstract class ExecutionMonitorProvider implements Service { @ Override public final void configure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { try { doConfigure ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , profile . getPrefix ( ) ) , e ) ; } } protected void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { return ; } public abstract PhaseMonitor newInstance ( ExecutionContext context ) throws InterruptedException , IOException ; } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CommandScript implements ExecutionScript { static final Logger LOG = LoggerFactory . getLogger ( CommandScript . class ) ; public static final String DEFAULT_PROFILE_NAME = "" ; private final String id ; private final Set < String > blockerIds ; private final String profileName ; private final List < String > command ; private final String moduleName ; private final Map < String , String > environmentVariables ; private final boolean resolved ; public CommandScript ( String id , Set < String > blockerIds , String profileName , String moduleName , List < String > command , Map < String , String > environmentVariables ) { this ( id , blockerIds , profileName , moduleName , command , environmentVariables , false ) ; } private CommandScript ( String id , Set < String > blockerIds , String profileName , String moduleName , List < String > command , Map < String , String > environmentVariables , boolean resolved ) { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } if ( blockerIds == null ) { throw new IllegalArgumentException ( "" ) ; } if ( profileName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( moduleName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( command == null ) { throw new IllegalArgumentException ( "" ) ; } if ( command . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } if ( environmentVariables == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = id ; this . blockerIds = Collections . unmodifiableSet ( new TreeSet < String > ( blockerIds ) ) ; this . profileName = profileName ; this . command = Collections . unmodifiableList ( new ArrayList < String > ( command ) ) ; this . moduleName = moduleName ; this . environmentVariables = Collections . unmodifiableMap ( new LinkedHashMap < String , String > ( environmentVariables ) ) ; this . resolved = resolved ; } @ Override public Kind getKind ( ) { return Kind . COMMAND ; } @ Override public String getId ( ) { return id ; } @ Override public Set < String > getBlockerIds ( ) { return blockerIds ; } public String getProfileName ( ) { return profileName ; } public String getModuleName ( ) { return moduleName ; } public List < String > getCommandLineTokens ( ) { return command ; } @ Override public Map < String , String > getEnvironmentVariables ( ) { return environmentVariables ; } @ Override public boolean isResolved ( ) { return resolved ; } @ Override public CommandScript resolve ( ExecutionContext context , ExecutionScriptHandler < ? > handler ) throws InterruptedException , IOException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( handler == null ) { throw new IllegalArgumentException ( "" ) ; } if ( isResolved ( ) ) { return this ; } LOG . debug ( "" , this ) ; PlaceholderResolver resolver = new PlaceholderResolver ( this , context , handler ) ; List < String > resolvedCommands = new ArrayList < String > ( ) ; for ( String token : getCommandLineTokens ( ) ) { resolvedCommands . add ( resolver . resolve ( token ) ) ; } LOG . debug ( "" , resolvedCommands ) ; Map < String , String > resolvedEnvironments = new LinkedHashMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : getEnvironmentVariables ( ) . entrySet ( ) ) { resolvedEnvironments . put ( entry . getKey ( ) , resolver . resolve ( entry . getValue ( ) ) ) ; } LOG . debug ( "" , resolvedEnvironments ) ; return new CommandScript ( getId ( ) , getBlockerIds ( ) , getProfileName ( ) , getModuleName ( ) , resolvedCommands , resolvedEnvironments , true ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getId ( ) , getBlockerIds ( ) , getProfileName ( ) , getModuleName ( ) , getCommandLineTokens ( ) , getEnvironmentVariables ( ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + id . hashCode ( ) ; result = prime * result + blockerIds . hashCode ( ) ; result = prime * result + profileName . hashCode ( ) ; result = prime * result + moduleName . hashCode ( ) ; result = prime * result + command . hashCode ( ) ; result = prime * result + environmentVariables . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } CommandScript other = ( CommandScript ) obj ; if ( ! id . equals ( other . id ) ) { return false ; } if ( ! blockerIds . equals ( other . blockerIds ) ) { return false ; } if ( ! profileName . equals ( other . profileName ) ) { return false ; } if ( ! moduleName . equals ( other . moduleName ) ) { return false ; } if ( ! command . equals ( other . command ) ) { return false ; } if ( ! environmentVariables . equals ( other . environmentVariables ) ) { return false ; } return true ; } } package com . asakusafw . yaess . core ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . EnumMap ; import java . util . Iterator ; import java . util . LinkedHashSet ; import java . util . List ; import java . util . Map ; import java . util . NavigableMap ; import java . util . Properties ; import java . util . Set ; import java . util . TreeMap ; import java . util . TreeSet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . util . PropertiesUtil ; public final class FlowScript { static final Logger LOG = LoggerFactory . getLogger ( FlowScript . class ) ; public static final String KEY_FLOW_PREFIX = "" ; public static final String KEY_ID = "" ; public static final String KEY_BLOCKERS = "" ; public static final String KEY_KIND = "" ; public static final String KEY_CLASS_NAME = "" ; public static final String KEY_PROFILE = "" ; public static final String KEY_MODULE = "" ; public static final String KEY_ENV_PREFIX = "" ; private static final String KEY_COMMAND_PREFIX = "" ; private static final String KEY_PROP_PREFIX = "" ; private static final Comparator < ExecutionScript > SCRIPT_COMPARATOR = new Comparator < ExecutionScript > ( ) { @ Override public int compare ( ExecutionScript o1 , ExecutionScript o2 ) { return o1 . getId ( ) . compareTo ( o2 . getId ( ) ) ; } } ; private final String id ; private final Set < String > blockerIds ; private final Map < ExecutionPhase , Set < ExecutionScript > > scripts ; public FlowScript ( String id , Set < String > blockerIds , Map < ExecutionPhase , ? extends Collection < ? extends ExecutionScript > > scripts ) { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } if ( id . indexOf ( '' ) >= ) { throw new IllegalArgumentException ( "" ) ; } if ( blockerIds == null ) { throw new IllegalArgumentException ( "" ) ; } if ( scripts == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = id ; this . blockerIds = Collections . unmodifiableSet ( new LinkedHashSet < String > ( blockerIds ) ) ; EnumMap < ExecutionPhase , Set < ExecutionScript > > map = new EnumMap < ExecutionPhase , Set < ExecutionScript > > ( ExecutionPhase . class ) ; for ( ExecutionPhase phase : ExecutionPhase . values ( ) ) { if ( scripts . containsKey ( phase ) ) { TreeSet < ExecutionScript > set = new TreeSet < ExecutionScript > ( SCRIPT_COMPARATOR ) ; set . addAll ( scripts . get ( phase ) ) ; if ( set . size ( ) != scripts . get ( phase ) . size ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , id , phase ) ) ; } map . put ( phase , Collections . unmodifiableSet ( set ) ) ; } else { map . put ( phase , Collections . < ExecutionScript > emptySet ( ) ) ; } } this . scripts = Collections . unmodifiableMap ( map ) ; } public String getId ( ) { return id ; } public Set < String > getBlockerIds ( ) { return blockerIds ; } public Map < ExecutionPhase , Set < ExecutionScript > > getScripts ( ) { return scripts ; } private static String getPrefix ( String flowId ) { assert flowId != null ; return KEY_FLOW_PREFIX + flowId + '' ; } private static String getPrefix ( String flowId , ExecutionPhase phase ) { assert flowId != null ; assert phase != null ; return getPrefix ( flowId ) + phase . getSymbol ( ) + '' ; } private static String getPrefix ( String flowId , ExecutionPhase phase , String nodeId ) { assert flowId != null ; assert phase != null ; assert nodeId != null ; return getPrefix ( flowId , phase ) + nodeId + '' ; } public static FlowScript load ( Properties properties , String flowId ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } String prefix = getPrefix ( flowId ) ; LOG . debug ( "" , prefix ) ; NavigableMap < String , String > flowMap = PropertiesUtil . createPrefixMap ( properties , prefix ) ; String blockersString = extract ( flowMap , prefix , KEY_BLOCKERS ) ; Set < String > blockerIds = parseTokens ( blockersString ) ; EnumMap < ExecutionPhase , List < ExecutionScript > > scripts = new EnumMap < ExecutionPhase , List < ExecutionScript > > ( ExecutionPhase . class ) ; for ( ExecutionPhase phase : ExecutionPhase . values ( ) ) { scripts . put ( phase , Collections . < ExecutionScript > emptyList ( ) ) ; } int count = ; Map < String , NavigableMap < String , String > > phaseMap = partitioning ( flowMap ) ; for ( Map . Entry < String , NavigableMap < String , String > > entry : phaseMap . entrySet ( ) ) { String phaseSymbol = entry . getKey ( ) ; NavigableMap < String , String > phaseContents = entry . getValue ( ) ; ExecutionPhase phase = ExecutionPhase . findFromSymbol ( phaseSymbol ) ; if ( phase == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , flowId , phaseSymbol ) ) ; } List < ExecutionScript > scriptsInPhase = loadScripts ( flowId , phase , phaseContents ) ; scripts . put ( phase , scriptsInPhase ) ; count += scriptsInPhase . size ( ) ; } FlowScript script = new FlowScript ( flowId , blockerIds , scripts ) ; LOG . debug ( "" , count , prefix ) ; LOG . trace ( "" , prefix , script ) ; return script ; } public static Set < ExecutionScript > load ( Properties properties , String flowId , ExecutionPhase phase ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( phase == null ) { throw new IllegalArgumentException ( "" ) ; } String prefix = getPrefix ( flowId , phase ) ; LOG . debug ( "" , prefix ) ; Set < String > availableFlowIds = extractFlowIds ( properties ) ; if ( availableFlowIds . contains ( flowId ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , flowId ) ) ; } NavigableMap < String , String > contents = PropertiesUtil . createPrefixMap ( properties , prefix ) ; List < ExecutionScript > scripts = loadScripts ( flowId , phase , contents ) ; LOG . debug ( "" , scripts . size ( ) , prefix ) ; LOG . trace ( "" , prefix , scripts ) ; TreeSet < ExecutionScript > results = new TreeSet < ExecutionScript > ( SCRIPT_COMPARATOR ) ; results . addAll ( scripts ) ; return results ; } private static List < ExecutionScript > loadScripts ( String flowId , ExecutionPhase phase , NavigableMap < String , String > contents ) { assert flowId != null ; assert phase != null ; assert contents != null ; if ( contents . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < ExecutionScript > results = new ArrayList < ExecutionScript > ( ) ; Map < String , NavigableMap < String , String > > scripts = partitioning ( contents ) ; for ( Map . Entry < String , NavigableMap < String , String > > entry : scripts . entrySet ( ) ) { String scriptId = entry . getKey ( ) ; NavigableMap < String , String > scriptContents = entry . getValue ( ) ; ExecutionScript script = loadScript ( flowId , phase , scriptId , scriptContents ) ; results . add ( script ) ; } checkBlockers ( flowId , phase , results ) ; return results ; } private static void checkBlockers ( String flowId , ExecutionPhase phase , List < ExecutionScript > scripts ) { assert flowId != null ; assert phase != null ; assert scripts != null ; } private static ExecutionScript loadScript ( String flowId , ExecutionPhase phase , String nodeId , Map < String , String > contents ) { assert flowId != null ; assert phase != null ; assert nodeId != null ; assert contents != null ; String prefix = getPrefix ( flowId , phase , nodeId ) ; String scriptId = extract ( contents , prefix , KEY_ID ) ; String kindSymbol = extract ( contents , prefix , KEY_KIND ) ; ExecutionScript . Kind kind = ExecutionScript . Kind . findFromSymbol ( kindSymbol ) ; String blockersString = extract ( contents , prefix , KEY_BLOCKERS ) ; Set < String > blockers = parseTokens ( blockersString ) ; Map < String , String > environmentVariables = PropertiesUtil . createPrefixMap ( contents , KEY_ENV_PREFIX ) ; ExecutionScript script ; if ( kind == ExecutionScript . Kind . COMMAND ) { String profileName = extract ( contents , prefix , KEY_PROFILE ) ; String moduleName = extract ( contents , prefix , KEY_MODULE ) ; NavigableMap < String , String > commandMap = PropertiesUtil . createPrefixMap ( contents , KEY_COMMAND_PREFIX ) ; if ( commandMap . isEmpty ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix + KEY_COMMAND_PREFIX ) ) ; } List < String > command = new ArrayList < String > ( commandMap . values ( ) ) ; script = new CommandScript ( scriptId , blockers , profileName , moduleName , command , environmentVariables ) ; } else if ( kind == ExecutionScript . Kind . HADOOP ) { String className = extract ( contents , prefix , KEY_CLASS_NAME ) ; Map < String , String > properties = PropertiesUtil . createPrefixMap ( contents , KEY_PROP_PREFIX ) ; script = new HadoopScript ( scriptId , blockers , className , properties , environmentVariables ) ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix + KEY_KIND , kindSymbol ) ) ; } LOG . trace ( "" , script ) ; return script ; } private static String extract ( Map < String , String > contents , String prefix , String key ) { assert contents != null ; assert prefix != null ; assert key != null ; String kindSymbol = contents . remove ( key ) ; if ( kindSymbol == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix + key ) ) ; } return kindSymbol ; } private static Map < String , NavigableMap < String , String > > partitioning ( NavigableMap < String , String > map ) { assert map != null ; Map < String , NavigableMap < String , String > > results = new TreeMap < String , NavigableMap < String , String > > ( ) ; while ( map . isEmpty ( ) == false ) { String name = map . firstKey ( ) ; int index = name . indexOf ( '' ) ; if ( index >= ) { name = name . substring ( , index ) ; } String first = name + '' ; String last = name + ( char ) ( '' + ) ; NavigableMap < String , String > partition = new TreeMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : map . subMap ( first , last ) . entrySet ( ) ) { String key = entry . getKey ( ) ; partition . put ( key . substring ( name . length ( ) + ) , entry . getValue ( ) ) ; } results . put ( name , partition ) ; map . remove ( name ) ; map . subMap ( first , last ) . clear ( ) ; } return results ; } public static Set < String > extractFlowIds ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; Set < String > childKeys = PropertiesUtil . getChildKeys ( properties , KEY_FLOW_PREFIX , String . valueOf ( '' ) ) ; int prefixLength = KEY_FLOW_PREFIX . length ( ) ; Set < String > results = new TreeSet < String > ( ) ; for ( String childKey : childKeys ) { assert childKey . startsWith ( KEY_FLOW_PREFIX ) ; results . add ( childKey . substring ( prefixLength ) ) ; } LOG . debug ( "" , results ) ; return results ; } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } properties . setProperty ( getPrefix ( getId ( ) ) + KEY_BLOCKERS , join ( getBlockerIds ( ) ) ) ; for ( Map . Entry < ExecutionPhase , Set < ExecutionScript > > phase : getScripts ( ) . entrySet ( ) ) { int index = ; for ( ExecutionScript script : phase . getValue ( ) ) { String scriptPrefix = getPrefix ( getId ( ) , phase . getKey ( ) , String . format ( "" , index ++ ) ) ; properties . setProperty ( scriptPrefix + KEY_ID , script . getId ( ) ) ; properties . setProperty ( scriptPrefix + KEY_KIND , script . getKind ( ) . getSymbol ( ) ) ; properties . setProperty ( scriptPrefix + KEY_BLOCKERS , join ( script . getBlockerIds ( ) ) ) ; String envPrefix = scriptPrefix + KEY_ENV_PREFIX ; for ( Map . Entry < String , String > entry : script . getEnvironmentVariables ( ) . entrySet ( ) ) { properties . setProperty ( envPrefix + entry . getKey ( ) , entry . getValue ( ) ) ; } switch ( script . getKind ( ) ) { case COMMAND : { CommandScript s = ( CommandScript ) script ; properties . setProperty ( scriptPrefix + KEY_PROFILE , s . getProfileName ( ) ) ; properties . setProperty ( scriptPrefix + KEY_MODULE , s . getModuleName ( ) ) ; List < String > command = s . getCommandLineTokens ( ) ; assert command . size ( ) <= ; String commandPrefix = scriptPrefix + KEY_COMMAND_PREFIX ; for ( int i = , n = command . size ( ) ; i < n ; i ++ ) { properties . setProperty ( String . format ( "" , commandPrefix , i ) , command . get ( i ) ) ; } break ; } case HADOOP : { HadoopScript s = ( HadoopScript ) script ; properties . setProperty ( scriptPrefix + KEY_CLASS_NAME , s . getClassName ( ) ) ; String propPrefix = scriptPrefix + KEY_PROP_PREFIX ; for ( Map . Entry < String , String > entry : s . getHadoopProperties ( ) . entrySet ( ) ) { properties . setProperty ( propPrefix + entry . getKey ( ) , entry . getValue ( ) ) ; } break ; } default : throw new AssertionError ( script . getKind ( ) ) ; } } } } private static Set < String > parseTokens ( String tokens ) { assert tokens != null ; String trimmed = tokens . trim ( ) ; if ( trimmed . isEmpty ( ) ) { return Collections . emptySet ( ) ; } Set < String > results = new LinkedHashSet < String > ( ) ; for ( String token : trimmed . split ( "" ) ) { if ( token . isEmpty ( ) ) { continue ; } results . add ( token ) ; } return results ; } private String join ( Set < String > tokens ) { assert tokens != null ; if ( tokens . isEmpty ( ) ) { return "" ; } StringBuilder buf = new StringBuilder ( ) ; Iterator < String > iter = tokens . iterator ( ) ; assert iter . hasNext ( ) ; buf . append ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( '' ) ; buf . append ( iter . next ( ) ) ; } return buf . toString ( ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( id == null ) ? : id . hashCode ( ) ) ; result = prime * result + ( ( blockerIds == null ) ? : blockerIds . hashCode ( ) ) ; result = prime * result + ( ( scripts == null ) ? : scripts . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } FlowScript other = ( FlowScript ) obj ; if ( id == null ) { if ( other . id != null ) { return false ; } } else if ( ! id . equals ( other . id ) ) { return false ; } if ( blockerIds == null ) { if ( other . blockerIds != null ) { return false ; } } else if ( ! blockerIds . equals ( other . blockerIds ) ) { return false ; } if ( scripts == null ) { if ( other . scripts != null ) { return false ; } } else if ( ! scripts . equals ( other . scripts ) ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getId ( ) , getBlockerIds ( ) , getScripts ( ) ) ; } } package com . asakusafw . yaess . core ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . TreeMap ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class VariableResolver { static final Logger LOG = LoggerFactory . getLogger ( VariableResolver . class ) ; private static final Pattern VARIABLE = Pattern . compile ( "" ) ; private final Map < String , String > entries ; public VariableResolver ( Map < String , String > entries ) { if ( entries == null ) { throw new IllegalArgumentException ( "" ) ; } this . entries = Collections . unmodifiableMap ( new TreeMap < String , String > ( entries ) ) ; } public static VariableResolver system ( ) { Map < String , String > entries = new HashMap < String , String > ( ) ; entries . putAll ( System . getenv ( ) ) ; for ( Map . Entry < Object , Object > entry : System . getProperties ( ) . entrySet ( ) ) { Object key = entry . getKey ( ) ; Object value = entry . getValue ( ) ; if ( key instanceof String && value instanceof String ) { entries . put ( ( String ) key , ( String ) value ) ; } } return new VariableResolver ( entries ) ; } public String replace ( String string , boolean strict ) { if ( string == null ) { throw new IllegalArgumentException ( "" ) ; } StringBuilder buf = new StringBuilder ( ) ; int start = ; Matcher matcher = VARIABLE . matcher ( string ) ; while ( matcher . find ( start ) ) { String name = matcher . group ( ) ; String replacement = entries . get ( name ) ; if ( replacement == null ) { if ( strict ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , this ) ) ; } else { buf . append ( string . substring ( start , matcher . start ( ) + ) ) ; } start = matcher . start ( ) + ; } else { buf . append ( string . substring ( start , matcher . start ( ) ) ) ; buf . append ( replacement ) ; start = matcher . end ( ) ; } } buf . append ( string . substring ( start ) ) ; return buf . toString ( ) ; } @ Override public String toString ( ) { return entries . toString ( ) ; } } package com . asakusafw . yaess . core ; public interface HadoopScriptHandler extends ExecutionScriptHandler < HadoopScript > { } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . Set ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public interface ExecutionScript { String ENV_ASAKUSA_HOME = "" ; String PLACEHOLDER_HOME = "" ; String PLACEHOLDER_EXECUTION_ID = "" ; String PLACEHOLDER_ARGUMENTS = "" ; Kind getKind ( ) ; String getId ( ) ; Set < String > getBlockerIds ( ) ; Map < String , String > getEnvironmentVariables ( ) ; boolean isResolved ( ) ; ExecutionScript resolve ( ExecutionContext context , ExecutionScriptHandler < ? > handler ) throws InterruptedException , IOException ; public enum Kind { COMMAND , HADOOP , ; public String getSymbol ( ) { return name ( ) . toLowerCase ( ) ; } public static Kind findFromSymbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } return Lazy . SYMBOLS . get ( symbol ) ; } private static final class Lazy { static final Map < String , Kind > SYMBOLS ; static { Map < String , Kind > map = new HashMap < String , Kind > ( ) ; for ( Kind phase : values ( ) ) { map . put ( phase . getSymbol ( ) , phase ) ; } SYMBOLS = Collections . unmodifiableMap ( map ) ; } private Lazy ( ) { return ; } } } public class PlaceholderResolver { static final Logger LOG = LoggerFactory . getLogger ( ExecutionScript . class ) ; private static final Pattern PLACEHOLDERS = Pattern . compile ( Pattern . quote ( PLACEHOLDER_HOME ) + '' + Pattern . quote ( PLACEHOLDER_EXECUTION_ID ) + '' + Pattern . quote ( PLACEHOLDER_ARGUMENTS ) ) ; private final Map < String , String > replacements ; public PlaceholderResolver ( ExecutionScript script , ExecutionContext context , ExecutionScriptHandler < ? > handler ) throws InterruptedException , IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( handler == null ) { throw new IllegalArgumentException ( "" ) ; } replacements = new HashMap < String , String > ( ) ; replacements . put ( PLACEHOLDER_HOME , getAsakusaHomePath ( context , script , handler ) ) ; replacements . put ( PLACEHOLDER_EXECUTION_ID , context . getExecutionId ( ) ) ; replacements . put ( PLACEHOLDER_ARGUMENTS , context . getArgumentsAsString ( ) ) ; } private String getAsakusaHomePath ( ExecutionContext context , ExecutionScript script , ExecutionScriptHandler < ? > handler ) throws IOException , InterruptedException { assert context != null ; assert script != null ; assert handler != null ; String inScript = script . getEnvironmentVariables ( ) . get ( ENV_ASAKUSA_HOME ) ; if ( inScript != null && inScript . equals ( PLACEHOLDER_HOME ) == false ) { LOG . debug ( "" , script . getId ( ) , inScript ) ; return inScript ; } Map < String , String > environmentVariables = handler . getEnvironmentVariables ( context , script ) ; String inHandler = environmentVariables . get ( ENV_ASAKUSA_HOME ) ; if ( inHandler != null ) { LOG . debug ( "" , script . getId ( ) , inHandler ) ; return inHandler ; } throw new IOException ( MessageFormat . format ( "" , ENV_ASAKUSA_HOME , handler . getHandlerId ( ) ) ) ; } public String resolve ( String target ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } Matcher matcher = PLACEHOLDERS . matcher ( target ) ; StringBuilder buf = new StringBuilder ( ) ; int start = ; while ( matcher . find ( start ) ) { buf . append ( target . substring ( start , matcher . start ( ) ) ) ; String replacement = replacements . get ( matcher . group ( ) ) ; assert replacement != null ; buf . append ( replacement ) ; start = matcher . end ( ) ; } buf . append ( target . substring ( start ) ) ; return buf . toString ( ) ; } } } package com . asakusafw . yaess . basic ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicHadoopScriptHandlerTest extends BasicScriptHandlerTestRoot { @ Test public void simple ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( "" , "" , "" , "" ) ) ; execute ( context , script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results . subList ( , ) , is ( Arrays . asList ( "" , "" , "" , "" , context . getArgumentsAsString ( ) ) ) ) ; } @ Test public void properties ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( "" , "" , "" , "" ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" , "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; execute ( context , script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results . subList ( , ) , is ( Arrays . asList ( "" , "" , "" , "" , context . getArgumentsAsString ( ) ) ) ) ; List < String > rest = results . subList ( , results . size ( ) ) ; int hello = rest . indexOf ( "" ) ; assertThat ( hello , greaterThanOrEqualTo ( ) ) ; assertThat ( rest . get ( hello - ) , is ( "" ) ) ; int hoge = rest . indexOf ( "" ) ; assertThat ( hoge , greaterThanOrEqualTo ( ) ) ; assertThat ( rest . get ( hoge - ) , is ( "" ) ) ; int bar = rest . indexOf ( "" ) ; assertThat ( bar , greaterThanOrEqualTo ( ) ) ; assertThat ( rest . get ( bar - ) , is ( "" ) ) ; } @ Test public void complex_prefix ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" , "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( "" , "" , "" , "" ) ) ; execute ( context , script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results . subList ( , ) , is ( Arrays . asList ( "" , shell . getAbsolutePath ( ) , "" , "" , "" , "" , context . getArgumentsAsString ( ) ) ) ) ; } @ Test public void environment ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( "" , "" , "" , "" ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" , "" , "" ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; } @ Test public void runtime_context ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( "" , "" , "" , "" ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" , "" , "" ) ; RuntimeContext rc = RuntimeContext . DEFAULT . batchId ( "" ) . mode ( ExecutionMode . SIMULATION ) . buildId ( "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) , rc . unapply ( ) ) ; execute ( context , script , handler ) ; Map < String , String > map = new HashMap < String , String > ( ) ; for ( String line : getOutput ( shell ) ) { if ( line . trim ( ) . isEmpty ( ) ) { continue ; } String [ ] kv = line . split ( "" , ) ; if ( kv . length != ) { continue ; } map . put ( kv [ ] , kv [ ] ) ; } assertThat ( RuntimeContext . DEFAULT . apply ( map ) , is ( rc ) ) ; } @ Test public void setup ( ) throws Exception { HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . SETUP , map ( ) ) ; handler . setUp ( ExecutionMonitor . NULL , context ) ; } @ Test ( expected = ExitCodeException . class ) public void abnormal_exit ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void home_missing ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void script_missing ( ) throws Exception { HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void invalid_prefix ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test public void cleanup ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , ProcessHadoopScriptHandler . KEY_CLEANUP , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . CLEANUP , map ( ) ) ; handler . cleanUp ( ExecutionMonitor . NULL , context ) ; List < String > results = getOutput ( shell ) ; assertThat ( results . subList ( , ) , is ( Arrays . asList ( ProcessHadoopScriptHandler . CLEANUP_STAGE_CLASS , "" , "" , "" , context . getArgumentsAsString ( ) ) ) ) ; } @ Test public void cleanup_skip ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , ProcessHadoopScriptHandler . KEY_CLEANUP , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . CLEANUP , map ( ) ) ; handler . cleanUp ( ExecutionMonitor . NULL , context ) ; try { getOutput ( shell ) ; fail ( ) ; } catch ( IOException e ) { } } @ SuppressWarnings ( "" ) @ Test public void cleanup_obsolete_profiles ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , ProcessHadoopScriptHandler . KEY_CLEANUP , "" , ProcessHadoopScriptHandler . KEY_WORKING_DIRECTORY , "" , ProcessUtil . PREFIX_CLEANUP + "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . CLEANUP , map ( ) ) ; handler . cleanUp ( ExecutionMonitor . NULL , context ) ; List < String > results = getOutput ( shell ) ; assertThat ( results . subList ( , ) , is ( Arrays . asList ( ProcessHadoopScriptHandler . CLEANUP_STAGE_CLASS , "" , "" , "" , context . getArgumentsAsString ( ) ) ) ) ; } private HadoopScriptHandler handler ( String ... keyValuePairs ) { Map < String , String > conf = map ( keyValuePairs ) ; ServiceProfile < HadoopScriptHandler > profile = new ServiceProfile < HadoopScriptHandler > ( "" , BasicHadoopScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; try { return profile . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . yaess . basic ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . yaess . core . ExecutionLock ; import com . asakusafw . yaess . core . ExecutionLockProvider ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . VariableResolver ; public class BasicLockProviderTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { File lockDir = folder . getRoot ( ) ; int start = lockDir . list ( ) . length ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , lockDir . getAbsolutePath ( ) ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionLockProvider instance = profile . newInstance ( ) ; ExecutionLock lock = instance . newInstance ( "" ) ; try { lock . beginFlow ( "" , "" ) ; assertThat ( lockDir . list ( ) . length , is ( greaterThan ( start ) ) ) ; } finally { lock . close ( ) ; } assertThat ( lockDir . list ( ) . length , is ( start ) ) ; } @ Test public void with_variable ( ) throws Exception { File lockDir = folder . getRoot ( ) ; int start = lockDir . list ( ) . length ; VariableResolver var = new VariableResolver ( Collections . singletonMap ( "" , lockDir . getAbsolutePath ( ) ) ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , "" ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , new ProfileContext ( getClass ( ) . getClassLoader ( ) , var ) ) ; ExecutionLockProvider instance = profile . newInstance ( ) ; ExecutionLock lock = instance . newInstance ( "" ) ; try { lock . beginFlow ( "" , "" ) ; assertThat ( lockDir . list ( ) . length , is ( greaterThan ( start ) ) ) ; } finally { lock . close ( ) ; } assertThat ( lockDir . list ( ) . length , is ( start ) ) ; } @ Test ( expected = IOException . class ) public void invalid_variable ( ) throws Exception { File lockDir = folder . getRoot ( ) ; VariableResolver var = new VariableResolver ( Collections . singletonMap ( "" , lockDir . getAbsolutePath ( ) ) ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , "" ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , new ProfileContext ( getClass ( ) . getClassLoader ( ) , var ) ) ; profile . newInstance ( ) ; } @ Test public void world ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , folder . getRoot ( ) . getAbsolutePath ( ) ) ; conf . put ( ExecutionLockProvider . KEY_SCOPE , ExecutionLock . Scope . WORLD . getSymbol ( ) ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionLockProvider instance1 = profile . newInstance ( ) ; ExecutionLockProvider instance2 = profile . newInstance ( ) ; ExecutionLock lock = instance1 . newInstance ( "" ) ; try { try { instance2 . newInstance ( "" ) ; fail ( "" ) ; } catch ( IOException e ) { } try { instance2 . newInstance ( "" ) ; fail ( "" ) ; } catch ( IOException e ) { } lock . beginFlow ( "" , "" ) ; lock . beginFlow ( "" , "" ) ; try { lock . beginFlow ( "" , "" ) ; fail ( "" ) ; } catch ( IOException e ) { } } finally { lock . close ( ) ; } } @ Test public void batch ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , folder . getRoot ( ) . getAbsolutePath ( ) ) ; conf . put ( ExecutionLockProvider . KEY_SCOPE , ExecutionLock . Scope . BATCH . getSymbol ( ) ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionLockProvider instance1 = profile . newInstance ( ) ; ExecutionLockProvider instance2 = profile . newInstance ( ) ; ExecutionLock lock = instance1 . newInstance ( "" ) ; try { lock . beginFlow ( "" , "" ) ; try { instance2 . newInstance ( "" ) ; fail ( "" ) ; } catch ( IOException e ) { } ExecutionLock other = instance2 . newInstance ( "" ) ; try { other . beginFlow ( "" , "" ) ; other . endFlow ( "" , "" ) ; other . beginFlow ( "" , "" ) ; other . endFlow ( "" , "" ) ; other . beginFlow ( "" , "" ) ; other . endFlow ( "" , "" ) ; } finally { other . close ( ) ; } } finally { lock . close ( ) ; } } @ Test public void flow ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , folder . getRoot ( ) . getAbsolutePath ( ) ) ; conf . put ( ExecutionLockProvider . KEY_SCOPE , ExecutionLock . Scope . FLOW . getSymbol ( ) ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionLockProvider instance1 = profile . newInstance ( ) ; ExecutionLockProvider instance2 = profile . newInstance ( ) ; ExecutionLock lock = instance1 . newInstance ( "" ) ; try { lock . beginFlow ( "" , "" ) ; ExecutionLock other = instance2 . newInstance ( "" ) ; try { other . beginFlow ( "" , "" ) ; other . endFlow ( "" , "" ) ; other . beginFlow ( "" , "" ) ; other . endFlow ( "" , "" ) ; try { other . beginFlow ( "" , "" ) ; fail ( "" ) ; } catch ( IOException e ) { } } finally { other . close ( ) ; } other = instance2 . newInstance ( "" ) ; try { other . beginFlow ( "" , "" ) ; } finally { other . close ( ) ; } } finally { lock . close ( ) ; } } @ Test public void execution ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , folder . getRoot ( ) . getAbsolutePath ( ) ) ; conf . put ( ExecutionLockProvider . KEY_SCOPE , ExecutionLock . Scope . EXECUTION . getSymbol ( ) ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionLockProvider instance1 = profile . newInstance ( ) ; ExecutionLockProvider instance2 = profile . newInstance ( ) ; ExecutionLock lock = instance1 . newInstance ( "" ) ; try { lock . beginFlow ( "" , "" ) ; ExecutionLock other = instance2 . newInstance ( "" ) ; try { other . beginFlow ( "" , "" ) ; other . endFlow ( "" , "" ) ; other . beginFlow ( "" , "" ) ; other . endFlow ( "" , "" ) ; other . beginFlow ( "" , "" ) ; other . endFlow ( "" , "" ) ; try { other . beginFlow ( "" , "" ) ; fail ( "" ) ; } catch ( IOException e ) { } } finally { other . close ( ) ; } other = instance2 . newInstance ( "" ) ; try { other . beginFlow ( "" , "" ) ; } finally { other . close ( ) ; } } finally { lock . close ( ) ; } } @ Test public void missing_directory ( ) throws Exception { File lockDir = folder . newFolder ( "" ) ; Assume . assumeThat ( lockDir . delete ( ) , is ( true ) ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , lockDir . getAbsolutePath ( ) ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionLockProvider instance = profile . newInstance ( ) ; ExecutionLock lock = instance . newInstance ( "" ) ; try { lock . beginFlow ( "" , "" ) ; lock . endFlow ( "" , "" ) ; } finally { lock . close ( ) ; } } @ Test ( expected = IOException . class ) public void missing_directory_config ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionLockProvider instance = profile . newInstance ( ) ; instance . newInstance ( "" ) ; } @ Test ( expected = IOException . class ) public void invalid_directory ( ) throws Exception { File lockDir = folder . newFile ( "" ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicLockProvider . KEY_DIRECTORY , lockDir . getAbsolutePath ( ) ) ; ServiceProfile < ExecutionLockProvider > profile = new ServiceProfile < ExecutionLockProvider > ( "" , BasicLockProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionLockProvider instance = profile . newInstance ( ) ; instance . newInstance ( "" ) ; } } package com . asakusafw . yaess . basic ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Scanner ; import java . util . Set ; import java . util . TreeSet ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . rules . TemporaryFolder ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; public class BasicScriptHandlerTestRoot { static final Logger LOG = LoggerFactory . getLogger ( BasicScriptHandlerTestRoot . class ) ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; protected < T extends ExecutionScript > void execute ( T script , ExecutionScriptHandler < T > handler ) { ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; execute ( context , script , handler ) ; } protected < T extends ExecutionScript > void execute ( ExecutionContext context , T script , ExecutionScriptHandler < T > handler ) { try { handler . execute ( ExecutionMonitor . NULL , context , script ) ; } catch ( InterruptedException e ) { throw new AssertionError ( e ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; Assume . assumeNoException ( e ) ; } } protected List < String > getOutput ( File copier ) throws IOException { File output = new File ( copier . getParentFile ( ) , copier . getName ( ) + "" ) ; List < String > results = new ArrayList < String > ( ) ; Scanner scanner = new Scanner ( output ) ; while ( scanner . hasNextLine ( ) ) { results . add ( scanner . nextLine ( ) ) ; } return results ; } protected File getAsakusaHome ( ) { return folder . getRoot ( ) ; } protected File putScript ( String source , String path ) throws IOException { File file = new File ( getAsakusaHome ( ) , path ) ; return putScript ( source , file ) ; } protected File putScript ( String source , File file ) throws IOException { LOG . debug ( "" , source , file ) ; InputStream in = getClass ( ) . getResourceAsStream ( source ) ; assertThat ( source , in , is ( notNullValue ( ) ) ) ; try { copyTo ( in , file ) ; } finally { in . close ( ) ; } file . setExecutable ( true ) ; return file ; } protected Set < String > set ( String ... values ) { return new TreeSet < String > ( Arrays . asList ( values ) ) ; } protected Map < String , String > map ( String ... keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > conf = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length - ; i += ) { conf . put ( keyValuePairs [ i ] , keyValuePairs [ i + ] ) ; } return conf ; } private void copyTo ( InputStream input , File target ) throws IOException { assert input != null ; assert target != null ; File parent = target . getParentFile ( ) ; assertThat ( parent . getAbsolutePath ( ) , parent , not ( nullValue ( ) ) ) ; if ( parent . isDirectory ( ) == false ) { assertThat ( parent . getAbsolutePath ( ) , parent . mkdirs ( ) , is ( true ) ) ; } FileOutputStream output = new FileOutputStream ( target ) ; try { byte [ ] buf = new byte [ ] ; while ( true ) { int read = input . read ( buf ) ; if ( read < ) { break ; } output . write ( buf , , read ) ; } } finally { output . close ( ) ; } } } package com . asakusafw . yaess . basic ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import org . junit . Test ; import com . asakusafw . yaess . core . CoreProfile ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicCoreProfileTest { @ Test public void version ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( CoreProfile . KEY_VERSION , "" ) ; ServiceProfile < CoreProfile > profile = new ServiceProfile < CoreProfile > ( "" , BasicCoreProfile . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; CoreProfile instance = profile . newInstance ( ) ; assertThat ( instance . getVersion ( ) , is ( "" ) ) ; } @ Test ( expected = IOException . class ) public void version_missing ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < CoreProfile > profile = new ServiceProfile < CoreProfile > ( "" , BasicCoreProfile . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; profile . newInstance ( ) ; } } package com . asakusafw . yaess . basic ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . junit . Assume ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicCommandScriptHandlerTest extends BasicScriptHandlerTestRoot { @ Test public void simple ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void multiple_arguments ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) , "" , "" , "" , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , is ( Arrays . asList ( "" , "" , "" , "" ) ) ) ; } @ Test public void with_prefix ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( "" , shell . getAbsolutePath ( ) ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void complex_prefix ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( "" , "" , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( "" , shell . getAbsolutePath ( ) , "" , "" ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , is ( Arrays . asList ( "" , "" , "" , "" ) ) ) ; } @ Test public void environment ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) ) , map ( "" , "" , "" , "" ) ) ; CommandScriptHandler handler = handler ( "" , "" , "" , "" ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; } @ Test public void runtime_context ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) ) , map ( "" , "" , "" , "" ) ) ; CommandScriptHandler handler = handler ( "" , "" , "" , "" ) ; RuntimeContext rc = RuntimeContext . DEFAULT . batchId ( "" ) . mode ( ExecutionMode . SIMULATION ) . buildId ( "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) , rc . unapply ( ) ) ; execute ( context , script , handler ) ; Map < String , String > map = new HashMap < String , String > ( ) ; for ( String line : getOutput ( shell ) ) { if ( line . trim ( ) . isEmpty ( ) ) { continue ; } String [ ] kv = line . split ( "" , ) ; if ( kv . length != ) { continue ; } map . put ( kv [ ] , kv [ ] ) ; } assertThat ( RuntimeContext . DEFAULT . apply ( map ) , is ( rc ) ) ; } @ Test ( expected = ExitCodeException . class ) public void abnormal_exit ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test public void setup ( ) throws Exception { CommandScriptHandler handler = handler ( ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . SETUP , map ( ) ) ; handler . setUp ( ExecutionMonitor . NULL , context ) ; } @ Test public void cleanup ( ) throws Exception { CommandScriptHandler handler = handler ( ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . CLEANUP , map ( ) ) ; handler . cleanUp ( ExecutionMonitor . NULL , context ) ; } @ Test ( expected = IOException . class ) public void script_missing ( ) throws Exception { File shell = putScript ( "" , "" ) ; Assume . assumeThat ( shell . delete ( ) , is ( true ) ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void invaid_prefix ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( "" , shell . getAbsolutePath ( ) , "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } private CommandScriptHandler handler ( String ... keyValuePairs ) { Map < String , String > conf = map ( keyValuePairs ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , BasicCommandScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; try { return profile . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . yaess . basic ; import java . io . IOException ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . junit . Test ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionMonitorProvider ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicMonitorProviderTest { private static final Map < String , String > EMPTY = Collections . < String , String > emptyMap ( ) ; private static final ExecutionContext CONTEXT = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , EMPTY ) ; @ Test public void simple ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < ExecutionMonitorProvider > profile = new ServiceProfile < ExecutionMonitorProvider > ( "" , BasicMonitorProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionMonitorProvider instance = profile . newInstance ( ) ; ExecutionMonitor monitor = instance . newInstance ( CONTEXT ) ; monitor . open ( ) ; try { monitor . progressed ( ) ; monitor . progressed ( ) ; monitor . progressed ( ) ; } finally { monitor . close ( ) ; } } @ Test public void with_stepUnit ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicMonitorProvider . KEY_STEP_UNIT , "" ) ; ServiceProfile < ExecutionMonitorProvider > profile = new ServiceProfile < ExecutionMonitorProvider > ( "" , BasicMonitorProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionMonitorProvider instance = profile . newInstance ( ) ; ExecutionMonitor monitor = instance . newInstance ( CONTEXT ) ; monitor . open ( ) ; try { for ( int i = ; i < ; i ++ ) { monitor . progressed ( ) ; } } finally { monitor . close ( ) ; } } @ Test public void large_stepUnit ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicMonitorProvider . KEY_STEP_UNIT , "" ) ; ServiceProfile < ExecutionMonitorProvider > profile = new ServiceProfile < ExecutionMonitorProvider > ( "" , BasicMonitorProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; ExecutionMonitorProvider instance = profile . newInstance ( ) ; ExecutionMonitor monitor = instance . newInstance ( CONTEXT ) ; monitor . open ( ) ; try { for ( int i = ; i < ; i ++ ) { monitor . progressed ( ) ; } } finally { monitor . close ( ) ; } } @ Test ( expected = IOException . class ) public void invalid_stepUnit ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( BasicMonitorProvider . KEY_STEP_UNIT , "" ) ; ServiceProfile < ExecutionMonitorProvider > profile = new ServiceProfile < ExecutionMonitorProvider > ( "" , BasicMonitorProvider . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; profile . newInstance ( ) ; } } package com . asakusafw . yaess . basic ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; 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 . concurrent . atomic . AtomicInteger ; import org . junit . Test ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . Job ; import com . asakusafw . yaess . core . JobScheduler ; import com . asakusafw . yaess . core . PhaseMonitor ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class BasicJobSchedulerTest { private static final ExecutionContext CONTEXT = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) ) ; @ Test public void simple ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < JobScheduler > profile = new ServiceProfile < JobScheduler > ( "" , BasicJobScheduler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; JobScheduler instance = profile . newInstance ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) ) ; instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void multiple ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < JobScheduler > profile = new ServiceProfile < JobScheduler > ( "" , BasicJobScheduler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; JobScheduler instance = profile . newInstance ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) ) ; jobs . add ( new Mock ( "" ) ) ; jobs . add ( new Mock ( "" ) ) ; instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void dependencies ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < JobScheduler > profile = new ServiceProfile < JobScheduler > ( "" , BasicJobScheduler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; JobScheduler instance = profile . newInstance ( ) ; AtomicInteger group = new AtomicInteger ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; jobs . add ( new Mock ( group , "" , "" , "" ) ) ; jobs . add ( new Mock ( group , "" ) ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; assertThat ( ordinary ( jobs , "" ) , lessThan ( ordinary ( jobs , "" ) ) ) ; assertThat ( ordinary ( jobs , "" ) , lessThan ( ordinary ( jobs , "" ) ) ) ; assertThat ( ordinary ( jobs , "" ) , lessThan ( ordinary ( jobs , "" ) ) ) ; assertThat ( ordinary ( jobs , "" ) , lessThan ( ordinary ( jobs , "" ) ) ) ; } @ Test public void cyclic ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < JobScheduler > profile = new ServiceProfile < JobScheduler > ( "" , BasicJobScheduler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; JobScheduler instance = profile . newInstance ( ) ; AtomicInteger group = new AtomicInteger ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( group , "" ) ) ; jobs . add ( new Mock ( group , "" , "" , "" ) ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; try { instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; fail ( ) ; } catch ( IOException e ) { } Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; assertThat ( rest , hasItem ( "" ) ) ; assertThat ( rest , hasItem ( "" ) ) ; assertThat ( rest , hasItem ( "" ) ) ; assertThat ( rest , hasItem ( "" ) ) ; } @ Test public void fail_job ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < JobScheduler > profile = new ServiceProfile < JobScheduler > ( "" , BasicJobScheduler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; JobScheduler instance = profile . newInstance ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws IOException { throw new IOException ( ) ; } } ) ; try { instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; fail ( ) ; } catch ( IOException e ) { } Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void fail_besteffort ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < JobScheduler > profile = new ServiceProfile < JobScheduler > ( "" , BasicJobScheduler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; JobScheduler instance = profile . newInstance ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws IOException { throw new IOException ( ) ; } } ) ; jobs . add ( new Mock ( "" ) ) ; jobs . add ( new Mock ( "" ) ) ; try { instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . BEST_EFFORT ) ; fail ( ) ; } catch ( IOException e ) { } Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void fail_stuck ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < JobScheduler > profile = new ServiceProfile < JobScheduler > ( "" , BasicJobScheduler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; JobScheduler instance = profile . newInstance ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws IOException { throw new IOException ( ) ; } } ) ; jobs . add ( new Mock ( "" ) ) ; jobs . add ( new Mock ( "" , "" , "" ) ) ; try { instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . BEST_EFFORT ) ; fail ( ) ; } catch ( IOException e ) { } Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; assertThat ( rest , hasItem ( "" ) ) ; } private int ordinary ( List < Mock > jobs , String name ) { for ( Mock mock : jobs ) { if ( mock . getId ( ) . equals ( name ) ) { return mock . count ; } } throw new AssertionError ( name ) ; } private Set < String > collectRest ( List < Mock > jobs ) { Set < String > results = new HashSet < String > ( ) ; for ( Mock mock : jobs ) { if ( mock . executed == false ) { results . add ( mock . id ) ; } } return results ; } private static class Mock extends Job { private final AtomicInteger counter ; final String id ; final Set < String > blockers ; volatile boolean executed ; volatile int count ; Mock ( String id , String ... blockers ) { this ( new AtomicInteger ( ) , id , blockers ) ; } Mock ( AtomicInteger c , String id , String ... blockers ) { assert id != null ; assert blockers != null ; this . counter = c ; this . id = id ; this . blockers = new HashSet < String > ( Arrays . asList ( blockers ) ) ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { executed = true ; count = counter . incrementAndGet ( ) ; hook ( ) ; } finally { monitor . close ( ) ; } } protected void hook ( ) throws InterruptedException , IOException { return ; } @ Override public String getJobLabel ( ) { return id ; } @ Override public String getServiceLabel ( ) { return id ; } @ Override public String getId ( ) { return id ; } @ Override public Set < String > getBlockerIds ( ) { return blockers ; } @ Override public String getResourceId ( ExecutionContext context ) { return "" ; } } } package com . asakusafw . yaess . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . TreeSet ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class FlowScriptTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { Map < ExecutionPhase , List < ? extends ExecutionScript > > exec = new HashMap < ExecutionPhase , List < ? extends ExecutionScript > > ( ) ; exec . put ( ExecutionPhase . MAIN , Arrays . asList ( hadoop ( ) ) ) ; FlowScript script = new FlowScript ( "" , set ( "" , "" ) , exec ) ; assertThat ( script . getId ( ) , is ( "" ) ) ; assertThat ( script . getBlockerIds ( ) , is ( set ( "" , "" ) ) ) ; assertThat ( script . getScripts ( ) . size ( ) , is ( ExecutionPhase . values ( ) . length ) ) ; assertThat ( script . getScripts ( ) . get ( ExecutionPhase . MAIN ) , hasItem ( hadoop ( ) ) ) ; } @ Test public void loadFlow ( ) throws Exception { Map < ExecutionPhase , List < ? extends ExecutionScript > > exec = new HashMap < ExecutionPhase , List < ? extends ExecutionScript > > ( ) ; exec . put ( ExecutionPhase . IMPORT , Arrays . asList ( command ( ) ) ) ; exec . put ( ExecutionPhase . MAIN , Arrays . asList ( hadoop ( ) , command ( , ) ) ) ; exec . put ( ExecutionPhase . EXPORT , Arrays . asList ( command ( ) ) ) ; FlowScript script = new FlowScript ( "" , set ( "" , "" ) , exec ) ; exec . put ( ExecutionPhase . INITIALIZE , Arrays . asList ( command ( ) ) ) ; FlowScript dummy = new FlowScript ( "" , set ( ) , exec ) ; Properties p = new Properties ( ) ; script . storeTo ( p ) ; dummy . storeTo ( p ) ; FlowScript loaded = FlowScript . load ( p , "" ) ; assertThat ( loaded , is ( script ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFlow_missing ( ) throws Exception { Properties p = new Properties ( ) ; FlowScript . load ( p , "" ) ; } @ Test public void loadPhase ( ) throws Exception { Map < ExecutionPhase , List < ? extends ExecutionScript > > exec = new HashMap < ExecutionPhase , List < ? extends ExecutionScript > > ( ) ; exec . put ( ExecutionPhase . IMPORT , Arrays . asList ( command ( ) ) ) ; exec . put ( ExecutionPhase . MAIN , Arrays . asList ( hadoop ( ) , command ( , ) ) ) ; exec . put ( ExecutionPhase . EXPORT , Arrays . asList ( command ( ) ) ) ; FlowScript script = new FlowScript ( "" , set ( "" , "" ) , exec ) ; exec . put ( ExecutionPhase . INITIALIZE , Arrays . asList ( command ( ) ) ) ; FlowScript dummy = new FlowScript ( "" , set ( ) , exec ) ; Properties p = new Properties ( ) ; script . storeTo ( p ) ; dummy . storeTo ( p ) ; Set < ExecutionScript > loaded = FlowScript . load ( p , "" , ExecutionPhase . MAIN ) ; assertThat ( loaded . size ( ) , is ( ) ) ; assertThat ( loaded , hasItem ( hadoop ( ) ) ) ; assertThat ( loaded , hasItem ( command ( , ) ) ) ; } @ Test public void loadPhase_empty ( ) throws Exception { Map < ExecutionPhase , List < ? extends ExecutionScript > > exec = new HashMap < ExecutionPhase , List < ? extends ExecutionScript > > ( ) ; FlowScript script = new FlowScript ( "" , set ( "" , "" ) , exec ) ; exec . put ( ExecutionPhase . INITIALIZE , Arrays . asList ( command ( ) ) ) ; FlowScript dummy = new FlowScript ( "" , set ( ) , exec ) ; Properties p = new Properties ( ) ; script . storeTo ( p ) ; dummy . storeTo ( p ) ; Set < ExecutionScript > loaded = FlowScript . load ( p , "" , ExecutionPhase . MAIN ) ; assertThat ( loaded . size ( ) , is ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadPhase_missing ( ) throws Exception { Properties p = new Properties ( ) ; FlowScript . load ( p , "" , ExecutionPhase . MAIN ) ; } private ExecutionScript hadoop ( int num , int ... blockers ) { Set < String > blockerIds = toBlockerIds ( blockers ) ; return new HadoopScript ( toId ( num ) , blockerIds , "" + num , map ( "" , "" + num ) , map ( "" , "" + num + "" ) ) ; } private ExecutionScript command ( int num , int ... blockers ) { Set < String > blockerIds = toBlockerIds ( blockers ) ; return new CommandScript ( toId ( num ) , blockerIds , "" + num , "" + num , Arrays . asList ( "" , "" , toId ( num ) ) , map ( "" , "" + num + "" ) ) ; } private String toId ( int num ) { return "" + num ; } private Set < String > toBlockerIds ( int ... blockers ) { Set < String > blockerIds = new HashSet < String > ( ) ; for ( int blocker : blockers ) { blockerIds . add ( toId ( blocker ) ) ; } return blockerIds ; } private Set < String > set ( String ... values ) { return new TreeSet < String > ( Arrays . asList ( values ) ) ; } private Map < String , String > map ( String ... keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > conf = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length - ; i += ) { conf . put ( keyValuePairs [ i ] , keyValuePairs [ i + ] ) ; } return conf ; } } package com . asakusafw . yaess . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . HashMap ; import java . util . Map ; import org . junit . Assume ; import org . junit . Test ; public class VariableResolverTest { @ Test public void simple ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; VariableResolver resolver = new VariableResolver ( map ) ; assertThat ( resolver . replace ( "" , true ) , is ( "" ) ) ; } @ Test public void inLine ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; VariableResolver resolver = new VariableResolver ( map ) ; assertThat ( resolver . replace ( "" , true ) , is ( "" ) ) ; } @ Test public void multiple ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; map . put ( "" , "" ) ; VariableResolver resolver = new VariableResolver ( map ) ; assertThat ( resolver . replace ( "" , true ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalid_strict ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( map ) ; resolver . replace ( "" , true ) ; } @ Test public void invalid_keep ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( map ) ; assertThat ( resolver . replace ( "" , false ) , is ( "" ) ) ; } @ Test public void system ( ) { Assume . assumeNotNull ( System . getProperty ( "" ) ) ; VariableResolver resolver = VariableResolver . system ( ) ; assertThat ( resolver . replace ( "" , true ) , is ( System . getProperty ( "" ) ) ) ; } } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . util . Map ; public class MockCommandScriptHandler extends ExecutionScriptHandlerBase implements CommandScriptHandler { @ Override protected void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { return ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { hook ( context , script ) ; } finally { monitor . close ( ) ; } } protected void hook ( ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { return ; } } package com . asakusafw . yaess . core . util ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import static org . junit . matchers . JUnitMatchers . * ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import org . junit . Test ; public class PropertiesUtilTest { @ Test public void getChildKeys ( ) { Properties properties = new Properties ( ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; Set < String > keys = PropertiesUtil . getChildKeys ( properties , "" , "" ) ; assertThat ( keys . size ( ) , is ( ) ) ; assertThat ( keys , hasItem ( "" ) ) ; assertThat ( keys , hasItem ( "" ) ) ; assertThat ( keys , hasItem ( "" ) ) ; } @ Test public void createPrefixMap ( ) { Properties properties = new Properties ( ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; char [ ] array = "" . toCharArray ( ) ; properties . put ( array , "" ) ; properties . put ( "" , array ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; assertThat ( PropertiesUtil . createPrefixMap ( properties , "" ) , is ( answer ) ) ; } } package com . asakusafw . yaess . core . util ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import org . junit . Test ; public class StreamRedirectTaskTest { private static final byte [ ] BYTES = new byte [ ] ; static { for ( int i = ; i < BYTES . length ; i ++ ) { BYTES [ i ] = ( byte ) ( ( i > > ) ^ i ) ; } } private final TestInputStream in = new TestInputStream ( BYTES ) ; private final TestOutputStream out = new TestOutputStream ( ) ; @ Test ( timeout = ) public void redirect ( ) { StreamRedirectTask t = new StreamRedirectTask ( in , out ) ; t . run ( ) ; assertThat ( out . toByteArray ( ) , is ( BYTES ) ) ; assertThat ( in . read ( ) , is ( - ) ) ; assertThat ( in . closed , is ( false ) ) ; assertThat ( out . closed , is ( false ) ) ; } @ Test ( timeout = ) public void quietExitOnInputError ( ) throws Exception { StreamRedirectTask t = new StreamRedirectTask ( new ErroneousInputStream ( ) , out ) ; t . run ( ) ; } @ Test ( timeout = ) public void quietExitOnOutputError ( ) throws Exception { StreamRedirectTask t = new StreamRedirectTask ( in , new ErroneousOutputStream ( ) ) ; t . run ( ) ; assertThat ( "" , in . read ( ) , is ( - ) ) ; } @ Test ( timeout = ) public void consumeInputOnOutputError ( ) throws Exception { StreamRedirectTask t = new StreamRedirectTask ( in , new ErroneousOutputStream ( ) ) ; t . run ( ) ; assertThat ( "" , in . read ( ) , is ( - ) ) ; } @ Test ( timeout = ) public void closeInput ( ) { StreamRedirectTask t = new StreamRedirectTask ( in , out , true , false ) ; t . run ( ) ; assertThat ( out . toByteArray ( ) , is ( BYTES ) ) ; assertThat ( in . closed , is ( true ) ) ; assertThat ( out . closed , is ( false ) ) ; } @ Test ( timeout = ) public void closeOutput ( ) { StreamRedirectTask t = new StreamRedirectTask ( in , out , false , true ) ; t . run ( ) ; assertThat ( out . toByteArray ( ) , is ( BYTES ) ) ; assertThat ( in . closed , is ( false ) ) ; assertThat ( out . closed , is ( true ) ) ; } static class ErroneousInputStream extends InputStream { private volatile int rest ; ErroneousInputStream ( int rest ) { this . rest = rest ; } @ Override public int read ( ) throws IOException { if ( -- rest < ) { throw new IOException ( ) ; } return ; } } static class ErroneousOutputStream extends OutputStream { private volatile int rest ; ErroneousOutputStream ( int rest ) { this . rest = rest ; } @ Override public void write ( int b ) throws IOException { if ( -- rest < ) { throw new IOException ( ) ; } } } static class TestInputStream extends ByteArrayInputStream { boolean closed ; TestInputStream ( byte [ ] buf ) { super ( buf ) ; } @ Override public void close ( ) throws IOException { this . closed = true ; } } static class TestOutputStream extends ByteArrayOutputStream { boolean closed ; @ Override public void close ( ) throws IOException { this . closed = true ; } } } package com . asakusafw . yaess . core . task ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Map ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScriptHandlerBase ; import com . asakusafw . yaess . core . ServiceProfile ; public class TrackingCommandScriptHandler extends ExecutionScriptHandlerBase implements CommandScriptHandler { private volatile ExecutionTracker tracker ; private volatile ExecutionTracker . Id id ; @ Override protected void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { Map < String , String > conf = profile . getConfiguration ( ) ; String trackerClassName = conf . get ( ExecutionTracker . KEY_CLASS ) ; String trackingId = conf . get ( ExecutionTracker . KEY_ID ) ; assertThat ( trackerClassName , is ( notNullValue ( ) ) ) ; assertThat ( trackingId , is ( notNullValue ( ) ) ) ; try { Class < ? > trackerClass = profile . getContext ( ) . getClassLoader ( ) . loadClass ( trackerClassName ) ; this . tracker = trackerClass . asSubclass ( ExecutionTracker . class ) . newInstance ( ) ; this . id = ExecutionTracker . Id . get ( trackingId ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , script , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } @ Override public void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , null , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , null , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } } package com . asakusafw . yaess . core . task ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . TreeSet ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . junit . After ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . yaess . basic . BasicLockProvider ; import com . asakusafw . yaess . basic . BasicMonitorProvider ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . ExecutionLock ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . YaessProfile ; import com . asakusafw . yaess . core . task . ExecutionTracker . Record ; public class ExecutionTaskTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Before public void setUp ( ) throws Exception { SerialExecutionTracker . clear ( ) ; } @ After public void tearDown ( ) throws Exception { SerialExecutionTracker . clear ( ) ; } @ Test public void phase_setup ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . SETUP ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Record > records = phase ( results , "" , ExecutionPhase . SETUP ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_initialize ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . INITIALIZE ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Record > records = phase ( results , "" , ExecutionPhase . INITIALIZE ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_import ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . IMPORT ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Record > records = phase ( results , "" , ExecutionPhase . IMPORT ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_prologue ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . PROLOGUE ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Record > records = phase ( results , "" , ExecutionPhase . PROLOGUE ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_main ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . MAIN ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( id ( results ) , is ( set ( "" , "" , "" , "" ) ) ) ; checkScriptHappensBefore ( results , "" , "" ) ; checkScriptHappensBefore ( results , "" , "" ) ; checkScriptHappensBefore ( results , "" , "" ) ; checkScriptHappensBefore ( results , "" , "" ) ; List < Record > records = phase ( results , "" , ExecutionPhase . MAIN ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_epilogue ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . EPILOGUE ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Record > records = phase ( results , "" , ExecutionPhase . EPILOGUE ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_export ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . EXPORT ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Record > records = phase ( results , "" , ExecutionPhase . EXPORT ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_finalize ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . FINALIZE ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Record > records = phase ( results , "" , ExecutionPhase . FINALIZE ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_cleanup ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . CLEANUP ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Record > records = phase ( results , "" , ExecutionPhase . CLEANUP ) ; assertThat ( records , is ( results ) ) ; } @ Test public void phase_sskip ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . getSkipFlows ( ) . add ( "" ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . SETUP ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; assertThat ( results , is ( Collections . < Record > emptyList ( ) ) ) ; } @ Test public void phase_sim ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setInvalid ( ) ; ExecutionTask task = prf . task ( ) ; task . setRuntimeContext ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; task . executePhase ( "" , "" , "" , ExecutionPhase . MAIN ) ; } @ Test public void executeFlow ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executeFlow ( "" , "" , "" ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; } @ Test public void executeFlow_skip ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . getSkipFlows ( ) . add ( "" ) ; task . executeFlow ( "" , "" , "" ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; assertThat ( results , is ( Collections . < Record > emptyList ( ) ) ) ; } @ Test public void executeFlow_sim ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setInvalid ( ) ; ExecutionTask task = prf . task ( ) ; task . setRuntimeContext ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; task . executeFlow ( "" , "" , "" ) ; } @ Test public void executeFlow_failed_export ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setTracker ( ExporterFailed . class ) ; ExecutionTask task = prf . task ( ) ; try { task . executeFlow ( "" , "" , "" ) ; fail ( ) ; } catch ( IOException e ) { } List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , lessThan ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; } @ Test public void executeFlow_failed_finalize ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setTracker ( FinalizerFailed . class ) ; ExecutionTask task = prf . task ( ) ; try { task . executeFlow ( "" , "" , "" ) ; fail ( ) ; } catch ( IOException e ) { } List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; } @ Test public void executeFlow_failed_cleanup ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setTracker ( CleanerFailed . class ) ; ExecutionTask task = prf . task ( ) ; task . executeFlow ( "" , "" , "" ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; } @ Test public void executeBatch ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . executeBatch ( "" ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; } @ Test public void executeBatch_skip ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; ExecutionTask task = prf . task ( ) ; task . getSkipFlows ( ) . add ( "" ) ; task . executeBatch ( "" ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( flow ( results , "" ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; } @ Test public void executeBatch_seriaize ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setTracker ( FlowSerialized . class ) ; ExecutionTask task = prf . task ( ) ; task . setSerializeFlows ( true ) ; task . executeBatch ( "" ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; verifyPhaseOrder ( results ) ; } @ Test public void executeBatch_sim ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setInvalid ( ) ; ExecutionTask task = prf . task ( ) ; task . setRuntimeContext ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; task . executeBatch ( "" ) ; } @ Test public void executeBatch_failed_export ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setTracker ( ExporterFailed . class ) ; ExecutionTask task = prf . task ( ) ; try { task . executeBatch ( "" ) ; fail ( ) ; } catch ( IOException e ) { } List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; checkFlowHappensBefore ( results , "" , "" ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , lessThan ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( flow ( results , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( results , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( results , "" ) . size ( ) , is ( ) ) ; } @ Test public void executeBatch_failed_finalize ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setTracker ( FinalizerFailed . class ) ; ExecutionTask task = prf . task ( ) ; try { task . executeBatch ( "" ) ; fail ( ) ; } catch ( IOException e ) { } List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( flow ( results , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( results , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( results , "" ) . size ( ) , is ( ) ) ; } @ Test public void executeBatch_failed_cleanup ( ) throws Exception { ProfileBuilder prf = new ProfileBuilder ( folder . getRoot ( ) ) ; prf . setTracker ( CleanerFailed . class ) ; ExecutionTask task = prf . task ( ) ; task . executeBatch ( "" ) ; List < Record > results = SerialExecutionTracker . get ( prf . trackingId ) ; verifyPhaseOrder ( results ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , lessThan ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , lessThan ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . INITIALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . IMPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . EXPORT ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . FINALIZE ) . size ( ) , is ( ) ) ; assertThat ( phase ( results , "" , ExecutionPhase . CLEANUP ) . size ( ) , lessThan ( ) ) ; } private void checkScriptHappensBefore ( List < Record > results , String head , String follow ) { boolean sawFollow = false ; for ( Record r : results ) { String id = id ( r ) ; if ( head . equals ( id ) ) { if ( sawFollow ) { throw new AssertionError ( head + "" + follow ) ; } } else if ( follow . equals ( id ) ) { sawFollow = false ; } } } private void checkFlowHappensBefore ( List < Record > results , String head , String follow ) { boolean sawFollow = false ; for ( Record r : results ) { String id = r . context . getFlowId ( ) ; if ( head . equals ( id ) ) { if ( sawFollow ) { throw new AssertionError ( head + "" + follow ) ; } } else if ( follow . equals ( id ) ) { sawFollow = false ; } } } private Set < String > id ( List < Record > records ) { TreeSet < String > results = new TreeSet < String > ( ) ; for ( Record r : records ) { results . add ( id ( r ) ) ; } return results ; } private String id ( Record r ) { return r . script == null ? r . handler . getHandlerId ( ) : r . script . getId ( ) ; } private Set < String > set ( String ... values ) { return new TreeSet < String > ( Arrays . asList ( values ) ) ; } private void verifyPhaseOrder ( List < Record > results ) { Map < String , List < Record > > partitions = flowPartition ( results ) ; for ( Map . Entry < String , List < Record > > entry : partitions . entrySet ( ) ) { String flowId = entry . getKey ( ) ; List < Record > records = entry . getValue ( ) ; ExecutionPhase last = ExecutionPhase . SETUP ; for ( Record r : records ) { ExecutionPhase phase = r . context . getPhase ( ) ; assertThat ( flowId , phase , greaterThanOrEqualTo ( last ) ) ; last = phase ; } } } private Map < String , List < Record > > flowPartition ( List < Record > records ) { Map < String , List < Record > > results = new HashMap < String , List < Record > > ( ) ; for ( Record r : records ) { String flowId = r . context . getFlowId ( ) ; List < Record > list = results . get ( flowId ) ; if ( list == null ) { list = new ArrayList < ExecutionTracker . Record > ( ) ; results . put ( flowId , list ) ; } list . add ( r ) ; } return results ; } private List < Record > flow ( List < Record > records , String flowId ) { List < Record > results = new ArrayList < Record > ( ) ; for ( Record r : records ) { if ( r . context . getFlowId ( ) . equals ( flowId ) ) { results . add ( r ) ; } } return results ; } private List < Record > phase ( List < Record > records , String flowId , ExecutionPhase phase ) { List < Record > results = new ArrayList < Record > ( ) ; for ( Record r : flow ( records , flowId ) ) { if ( r . context . getPhase ( ) == phase ) { results . add ( r ) ; } } return results ; } static String profile ( Record record ) { return ( ( CommandScript ) record . script ) . getProfileName ( ) ; } public static class FlowSerialized extends SerialExecutionTracker { private String flowId ; @ Override public synchronized void add ( Id id , Record record ) throws IOException , InterruptedException { switch ( record . context . getPhase ( ) ) { case SETUP : assertThat ( flowId , is ( nullValue ( ) ) ) ; flowId = record . context . getFlowId ( ) ; break ; case CLEANUP : assertThat ( flowId , is ( record . context . getFlowId ( ) ) ) ; flowId = null ; break ; default : Thread . sleep ( ) ; assertThat ( flowId , is ( record . context . getFlowId ( ) ) ) ; break ; } super . add ( id , record ) ; } } public static class ExporterFailed extends SerialExecutionTracker { @ Override public synchronized void add ( Id id , Record record ) throws IOException , InterruptedException { if ( record . context . getPhase ( ) == ExecutionPhase . EXPORT && profile ( record ) . equals ( "" ) ) { throw new IOException ( ) ; } super . add ( id , record ) ; } } public static class FinalizerFailed extends SerialExecutionTracker { @ Override public synchronized void add ( Id id , Record record ) throws IOException , InterruptedException { if ( record . context . getPhase ( ) == ExecutionPhase . FINALIZE && profile ( record ) . equals ( "" ) ) { throw new IOException ( ) ; } super . add ( id , record ) ; } } public static class CleanerFailed extends SerialExecutionTracker { @ Override public synchronized void add ( Id id , Record record ) throws IOException , InterruptedException { if ( record . context . getPhase ( ) == ExecutionPhase . CLEANUP && record . handler . getHandlerId ( ) . equals ( "" ) ) { throw new IOException ( ) ; } super . add ( id , record ) ; } } private static class ProfileBuilder { static final Pattern PLACEHOLDER = Pattern . compile ( "" ) ; final File asakusaHome ; final File lockDir ; final ExecutionTracker . Id trackingId ; final Map < String , String > replacement ; final Properties override ; ProfileBuilder ( File working ) { this . asakusaHome = new File ( working , "" ) ; this . lockDir = new File ( working , "" ) ; this . trackingId = ExecutionTracker . Id . get ( "" ) ; this . replacement = new HashMap < String , String > ( ) ; this . replacement . put ( "" , asakusaHome . getAbsolutePath ( ) ) ; this . replacement . put ( "" , ExecutionLock . Scope . WORLD . getSymbol ( ) ) ; this . replacement . put ( "" , BasicLockProvider . class . getName ( ) ) ; this . replacement . put ( "" , BasicMonitorProvider . class . getName ( ) ) ; this . replacement . put ( "" , lockDir . getAbsolutePath ( ) ) ; this . replacement . put ( "" , SerialExecutionTracker . class . getName ( ) ) ; this . replacement . put ( "" , "" ) ; this . override = new Properties ( ) ; SerialExecutionTracker . clear ( ) ; } void setTracker ( Class < ? extends ExecutionTracker > tracker ) { this . replacement . put ( "" , tracker . getName ( ) ) ; } void setInvalid ( ) { this . replacement . put ( "" , MonitorProviderInvalid . class . getName ( ) ) ; this . replacement . put ( "" , LockProviderInvalid . class . getName ( ) ) ; } ExecutionTask task ( ) throws IOException , InterruptedException { Properties properties = loadProfile ( ) ; YaessProfile profile = YaessProfile . load ( properties , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Map < String , String > arguments = Collections . emptyMap ( ) ; Properties script = loadScript ( ) ; return ExecutionTask . load ( profile , script , arguments ) ; } Properties loadScript ( ) throws IOException { Properties result = load ( "" ) ; return result ; } Properties loadProfile ( ) throws IOException { Properties result = load ( "" ) ; result . putAll ( override ) ; for ( Map . Entry < Object , Object > entry : result . entrySet ( ) ) { String value = ( String ) entry . getValue ( ) ; StringBuilder buf = new StringBuilder ( ) ; int start = ; Matcher matcher = PLACEHOLDER . matcher ( value ) ; while ( matcher . find ( start ) ) { buf . append ( value . subSequence ( start , matcher . start ( ) ) ) ; String rep = replacement . get ( matcher . group ( ) ) ; if ( rep == null ) { throw new AssertionError ( matcher . group ( ) ) ; } buf . append ( rep ) ; start = matcher . end ( ) ; } buf . append ( value . substring ( start ) ) ; entry . setValue ( buf . toString ( ) ) ; } return result ; } private Properties load ( String name ) throws IOException { Properties result = new Properties ( ) ; InputStream in = getClass ( ) . getResourceAsStream ( name ) ; assertThat ( in , is ( notNullValue ( ) ) ) ; try { result . load ( in ) ; } finally { in . close ( ) ; } return result ; } } } package com . asakusafw . yaess . core . task ; import java . io . IOException ; import com . asakusafw . yaess . core . ExecutionLock ; import com . asakusafw . yaess . core . ExecutionLockProvider ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . ExecutionLock . Scope ; public class LockProviderInvalid extends ExecutionLockProvider { @ Override protected void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { return ; } @ Override protected ExecutionLock newInstance ( Scope lockScope , String batchId ) throws IOException { throw new AssertionError ( ) ; } } package com . asakusafw . yaess . core . task ; import java . io . IOException ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitorProvider ; import com . asakusafw . yaess . core . PhaseMonitor ; public class MonitorProviderInvalid extends ExecutionMonitorProvider { @ Override public PhaseMonitor newInstance ( ExecutionContext context ) throws InterruptedException , IOException { throw new AssertionError ( ) ; } } package com . asakusafw . yaess . core . task ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Map ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; public interface ExecutionTracker { String KEY_CLASS = "" ; String KEY_ID = "" ; void add ( Id id , Record record ) throws IOException , InterruptedException ; public class Record { public final ExecutionContext context ; public final ExecutionScript script ; public final ExecutionScriptHandler < ? > handler ; public Record ( ExecutionContext context , ExecutionScript script , ExecutionScriptHandler < ? > handler ) { this . context = context ; this . script = script ; this . handler = handler ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , context . getFlowId ( ) , context . getPhase ( ) , script == null ? handler . getHandlerId ( ) : script . getId ( ) ) ; } } public class Id { private static final Map < String , Id > CACHE = new HashMap < String , Id > ( ) ; private final String token ; private Id ( String token ) { this . token = token ; } public static Id get ( String token ) { synchronized ( CACHE ) { Id cached = CACHE . get ( token ) ; if ( cached != null ) { return cached ; } Id id = new Id ( token ) ; CACHE . put ( token , id ) ; return id ; } } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + token . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Id other = ( Id ) obj ; if ( ! token . equals ( other . token ) ) { return false ; } return true ; } @ Override public String toString ( ) { return token ; } } } package com . asakusafw . yaess . core . task ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Map ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScriptHandlerBase ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; public class TrackingHadoopScriptHandler extends ExecutionScriptHandlerBase implements HadoopScriptHandler { private volatile ExecutionTracker tracker ; private volatile ExecutionTracker . Id id ; @ Override protected void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { Map < String , String > conf = profile . getConfiguration ( ) ; String trackerClassName = conf . get ( ExecutionTracker . KEY_CLASS ) ; String trackingId = conf . get ( ExecutionTracker . KEY_ID ) ; assertThat ( trackerClassName , is ( notNullValue ( ) ) ) ; assertThat ( trackingId , is ( notNullValue ( ) ) ) ; try { Class < ? > trackerClass = profile . getContext ( ) . getClassLoader ( ) . loadClass ( trackerClassName ) ; this . tracker = trackerClass . asSubclass ( ExecutionTracker . class ) . newInstance ( ) ; this . id = ExecutionTracker . Id . get ( trackingId ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , script , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } @ Override public void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , null , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , null , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } } package com . asakusafw . yaess . core . task ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . WeakHashMap ; public class SerialExecutionTracker implements ExecutionTracker { private static final Map < Id , List < Record > > map = new WeakHashMap < ExecutionTracker . Id , List < Record > > ( ) ; @ Override public synchronized void add ( Id id , Record record ) throws IOException , InterruptedException { List < Record > history = map . get ( id ) ; if ( history == null ) { history = new ArrayList < Record > ( ) ; map . put ( id , history ) ; } history . add ( record ) ; } public static synchronized void clear ( ) { map . clear ( ) ; } public static synchronized List < Record > get ( Id id ) { List < Record > results = map . get ( id ) ; if ( results == null ) { results = Collections . emptyList ( ) ; } return new ArrayList < Record > ( results ) ; } } package com . asakusafw . yaess . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Properties ; import org . junit . Test ; public class ServiceProfileTest { @ Test public void load ( ) { Properties prop = new Properties ( ) ; prop . setProperty ( "" , MockService . class . getName ( ) ) ; prop . setProperty ( "" , "" ) ; ClassLoader cl = getClass ( ) . getClassLoader ( ) ; ServiceProfile < Service > service = ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( cl ) ) ; assertThat ( service . getPrefix ( ) , is ( "" ) ) ; assertThat ( service . getServiceClass ( ) , is ( ( Object ) MockService . class ) ) ; assertThat ( service . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( service . getContext ( ) . getClassLoader ( ) , is ( cl ) ) ; } @ Test public void load_with_config ( ) { Properties prop = new Properties ( ) ; prop . setProperty ( "" , MockService . class . getName ( ) ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; ClassLoader cl = getClass ( ) . getClassLoader ( ) ; ServiceProfile < Service > service = ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( cl ) ) ; assertThat ( service . getPrefix ( ) , is ( "" ) ) ; assertThat ( service . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( service . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( service . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void load_invalid_empty ( ) { Properties prop = new Properties ( ) ; ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void load_invalid_class ( ) { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void load_invalid_service ( ) { Properties prop = new Properties ( ) ; prop . setProperty ( "" , String . class . getName ( ) ) ; ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void load_invalid_base ( ) { Properties prop = new Properties ( ) ; prop . setProperty ( "" , MockService . class . getName ( ) ) ; ServiceProfile . load ( prop , "" , CoreProfile . class , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test public void newInstance ( ) throws Exception { Properties prop = new Properties ( ) ; prop . setProperty ( "" , MockService . class . getName ( ) ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; ClassLoader cl = getClass ( ) . getClassLoader ( ) ; ServiceProfile < Service > service = ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( cl ) ) ; Service instance = service . newInstance ( ) ; assertThat ( instance , is ( MockService . class ) ) ; MockService mock = ( MockService ) instance ; assertThat ( mock . serviceProfile . getPrefix ( ) , is ( "" ) ) ; assertThat ( mock . serviceProfile . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( mock . serviceProfile . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( mock . serviceProfile . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; } @ Test ( expected = IOException . class ) public void newInstance_fail_new ( ) throws Exception { Properties prop = new Properties ( ) ; prop . setProperty ( "" , PrivateService . class . getName ( ) ) ; ClassLoader cl = getClass ( ) . getClassLoader ( ) ; ServiceProfile < Service > service = ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( cl ) ) ; service . newInstance ( ) ; } @ Test ( expected = IOException . class ) public void newInstance_fail_configure ( ) throws Exception { Properties prop = new Properties ( ) ; prop . setProperty ( "" , InvalidService . class . getName ( ) ) ; ClassLoader cl = getClass ( ) . getClassLoader ( ) ; ServiceProfile < Service > service = ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( cl ) ) ; service . newInstance ( ) ; } @ Test public void storeTo ( ) { Properties prop = new Properties ( ) ; prop . setProperty ( "" , MockService . class . getName ( ) ) ; ClassLoader cl = getClass ( ) . getClassLoader ( ) ; ServiceProfile < Service > service = ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( cl ) ) ; Properties target = new Properties ( ) ; service . storeTo ( target ) ; assertThat ( target , is ( prop ) ) ; } @ Test public void storeTo_with_configuration ( ) { Properties prop = new Properties ( ) ; prop . setProperty ( "" , MockService . class . getName ( ) ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; ClassLoader cl = getClass ( ) . getClassLoader ( ) ; ServiceProfile < Service > service = ServiceProfile . load ( prop , "" , Service . class , ProfileContext . system ( cl ) ) ; Properties target = new Properties ( ) ; service . storeTo ( target ) ; assertThat ( target , is ( prop ) ) ; } } package com . asakusafw . yaess . core ; public class PrivateService implements Service { private PrivateService ( ) { return ; } @ Override public void configure ( ServiceProfile < ? > profile ) { return ; } } package com . asakusafw . yaess . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class CommandScriptTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) { CommandScript script = new CommandScript ( "" , set ( "" , "" ) , "" , "" , Arrays . asList ( "" , "" ) , map ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ) ; assertThat ( script . getKind ( ) , is ( ExecutionScript . Kind . COMMAND ) ) ; assertThat ( script . getId ( ) , is ( "" ) ) ; assertThat ( script . getBlockerIds ( ) , is ( set ( "" , "" ) ) ) ; assertThat ( script . getProfileName ( ) , is ( "" ) ) ; assertThat ( script . getModuleName ( ) , is ( "" ) ) ; assertThat ( script . getCommandLineTokens ( ) , is ( Arrays . asList ( "" , "" ) ) ) ; assertThat ( script . getEnvironmentVariables ( ) . size ( ) , is ( ) ) ; assertThat ( script . getEnvironmentVariables ( ) . get ( "" ) , is ( folder . getRoot ( ) . getAbsolutePath ( ) ) ) ; } @ Test public void resolve_nothing ( ) throws Exception { CommandScript script = new CommandScript ( "" , set ( "" , "" ) , "" , "" , Arrays . asList ( "" , "" ) , map ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( "" , "" ) ) ; CommandScript resolved = script . resolve ( context , handler ( ) ) ; assertThat ( resolved . isResolved ( ) , is ( true ) ) ; assertThat ( resolved , is ( script ) ) ; } @ Test public void resolve ( ) throws Exception { CommandScript script = new CommandScript ( "" , set ( "" , "" ) , "" , "" , Arrays . asList ( ExecutionScript . PLACEHOLDER_HOME + "" , ExecutionScript . PLACEHOLDER_EXECUTION_ID , ExecutionScript . PLACEHOLDER_ARGUMENTS ) , map ( "" , ExecutionScript . PLACEHOLDER_HOME ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( "" , "" ) ) ; CommandScript resolved = script . resolve ( context , handler ( ExecutionScriptHandler . KEY_ENV_PREFIX + "" , "" ) ) ; assertThat ( resolved . isResolved ( ) , is ( true ) ) ; assertThat ( resolved . getCommandLineTokens ( ) , is ( Arrays . asList ( "" , "" , context . getArgumentsAsString ( ) ) ) ) ; assertThat ( resolved . getEnvironmentVariables ( ) . size ( ) , is ( ) ) ; assertThat ( resolved . getEnvironmentVariables ( ) . get ( "" ) , is ( "" ) ) ; } private CommandScriptHandler handler ( String ... keyValuePairs ) { Map < String , String > conf = map ( keyValuePairs ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , MockCommandScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; try { return profile . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Set < String > set ( String ... values ) { return new TreeSet < String > ( Arrays . asList ( values ) ) ; } private Map < String , String > map ( String ... keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > conf = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length - ; i += ) { conf . put ( keyValuePairs [ i ] , keyValuePairs [ i + ] ) ; } return conf ; } } package com . asakusafw . yaess . core ; import java . io . IOException ; public class MockService implements Service { ServiceProfile < ? > serviceProfile ; @ Override public void configure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { this . serviceProfile = profile ; } } package com . asakusafw . yaess . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class HadoopScriptTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) { HadoopScript script = new HadoopScript ( "" , set ( "" , "" ) , "" , map ( "" , "" ) , map ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ) ; assertThat ( script . getKind ( ) , is ( ExecutionScript . Kind . HADOOP ) ) ; assertThat ( script . getId ( ) , is ( "" ) ) ; assertThat ( script . getBlockerIds ( ) , is ( set ( "" , "" ) ) ) ; assertThat ( script . getClassName ( ) , is ( "" ) ) ; assertThat ( script . getHadoopProperties ( ) . size ( ) , is ( ) ) ; assertThat ( script . getHadoopProperties ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( script . getEnvironmentVariables ( ) . size ( ) , is ( ) ) ; assertThat ( script . getEnvironmentVariables ( ) . get ( "" ) , is ( folder . getRoot ( ) . getAbsolutePath ( ) ) ) ; } @ Test public void resolve_nothing ( ) throws Exception { HadoopScript script = new HadoopScript ( "" , set ( "" , "" ) , "" , map ( "" , "" ) , map ( "" , folder . getRoot ( ) . getAbsolutePath ( ) ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( "" , "" ) ) ; HadoopScript resolved = script . resolve ( context , handler ( ) ) ; assertThat ( resolved . isResolved ( ) , is ( true ) ) ; assertThat ( resolved , is ( script ) ) ; } @ Test public void resolve ( ) throws Exception { HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( "" , ExecutionScript . PLACEHOLDER_HOME , "" , ExecutionScript . PLACEHOLDER_EXECUTION_ID , "" , ExecutionScript . PLACEHOLDER_ARGUMENTS ) , map ( "" , ExecutionScript . PLACEHOLDER_HOME ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( "" , "" ) ) ; HadoopScript resolved = script . resolve ( context , handler ( ExecutionScriptHandler . KEY_ENV_PREFIX + "" , "" ) ) ; assertThat ( resolved . isResolved ( ) , is ( true ) ) ; assertThat ( resolved . getHadoopProperties ( ) . size ( ) , is ( ) ) ; assertThat ( resolved . getHadoopProperties ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( resolved . getHadoopProperties ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( resolved . getHadoopProperties ( ) . get ( "" ) , is ( context . getArgumentsAsString ( ) ) ) ; assertThat ( resolved . getEnvironmentVariables ( ) . size ( ) , is ( ) ) ; assertThat ( resolved . getEnvironmentVariables ( ) . get ( "" ) , is ( "" ) ) ; } private HadoopScriptHandler handler ( String ... keyValuePairs ) { Map < String , String > conf = map ( keyValuePairs ) ; ServiceProfile < HadoopScriptHandler > profile = new ServiceProfile < HadoopScriptHandler > ( "" , MockHadoopScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; try { return profile . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Set < String > set ( String ... values ) { return new TreeSet < String > ( Arrays . asList ( values ) ) ; } private Map < String , String > map ( String ... keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > conf = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length - ; i += ) { conf . put ( keyValuePairs [ i ] , keyValuePairs [ i + ] ) ; } return conf ; } } package com . asakusafw . yaess . core ; import java . io . IOException ; public class InvalidService implements Service { @ Override public void configure ( ServiceProfile < ? > profile ) throws IOException { throw new IOException ( ) ; } } package com . asakusafw . yaess . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . junit . Test ; public class ExecutionScriptHandlerBaseTest { @ Test public void simple ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , MockCommandScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; CommandScriptHandler handler = profile . newInstance ( ) ; assertThat ( handler . getHandlerId ( ) , is ( "" ) ) ; assertThat ( handler . getResourceId ( context ( ) , null ) , is ( ExecutionScriptHandler . DEFAULT_RESOURCE_ID ) ) ; assertThat ( handler . getEnvironmentVariables ( context ( ) , null ) . size ( ) , is ( ) ) ; } @ Test public void environment_variables ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( ExecutionScriptHandler . KEY_ENV_PREFIX + "" , "" ) ; conf . put ( ExecutionScriptHandler . KEY_ENV_PREFIX + "" , "" ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , MockCommandScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; CommandScriptHandler handler = profile . newInstance ( ) ; assertThat ( handler . getHandlerId ( ) , is ( "" ) ) ; assertThat ( handler . getEnvironmentVariables ( context ( ) , null ) . size ( ) , is ( ) ) ; assertThat ( handler . getEnvironmentVariables ( context ( ) , null ) . get ( "" ) , is ( "" ) ) ; assertThat ( handler . getEnvironmentVariables ( context ( ) , null ) . get ( "" ) , is ( "" ) ) ; } @ Test public void resource ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( ExecutionScriptHandler . KEY_RESOURCE , "" ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , MockCommandScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; CommandScriptHandler handler = profile . newInstance ( ) ; assertThat ( handler . getHandlerId ( ) , is ( "" ) ) ; assertThat ( handler . getResourceId ( context ( ) , null ) , is ( "" ) ) ; } @ Test public void variables ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( ExecutionScriptHandler . KEY_ENV_PREFIX + "" , "" ) ; conf . put ( ExecutionScriptHandler . KEY_RESOURCE , "" ) ; Map < String , String > entries = new HashMap < String , String > ( ) ; entries . put ( "" , "" ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , MockCommandScriptHandler . class , conf , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( entries ) ) ) ; CommandScriptHandler handler = profile . newInstance ( ) ; assertThat ( handler . getHandlerId ( ) , is ( "" ) ) ; assertThat ( handler . getResourceId ( context ( ) , null ) , is ( "" ) ) ; assertThat ( handler . getEnvironmentVariables ( context ( ) , null ) . size ( ) , is ( ) ) ; assertThat ( handler . getEnvironmentVariables ( context ( ) , null ) . get ( "" ) , is ( "" ) ) ; } @ Test ( expected = IOException . class ) public void variables_unresolved ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( ExecutionScriptHandler . KEY_ENV_PREFIX + "" , "" ) ; conf . put ( ExecutionScriptHandler . KEY_RESOURCE , "" ) ; Map < String , String > entries = new HashMap < String , String > ( ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , MockCommandScriptHandler . class , conf , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( entries ) ) ) ; profile . newInstance ( ) ; } private ExecutionContext context ( ) { return new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) ) ; } } package com . asakusafw . yaess . core ; import java . io . IOException ; import java . util . Map ; public class MockHadoopScriptHandler extends ExecutionScriptHandlerBase implements HadoopScriptHandler { @ Override protected void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { return ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { hook ( context , script ) ; } finally { monitor . close ( ) ; } } protected void hook ( ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { return ; } } package com . asakusafw . yaess . bootstrap ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . WeakHashMap ; public class SerialExecutionTracker implements ExecutionTracker { private static final Map < Id , List < Record > > map = new WeakHashMap < ExecutionTracker . Id , List < Record > > ( ) ; @ Override public synchronized void add ( Id id , Record record ) throws IOException , InterruptedException { List < Record > history = map . get ( id ) ; if ( history == null ) { history = new ArrayList < Record > ( ) ; map . put ( id , history ) ; } history . add ( record ) ; } public static synchronized void clear ( ) { map . clear ( ) ; } public static synchronized List < Record > get ( Id id ) { List < Record > results = map . get ( id ) ; if ( results == null ) { results = Collections . emptyList ( ) ; } return new ArrayList < Record > ( results ) ; } } package com . asakusafw . yaess . bootstrap ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Map ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScriptHandlerBase ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; public class TrackingHadoopScriptHandler extends ExecutionScriptHandlerBase implements HadoopScriptHandler { private volatile ExecutionTracker tracker ; private volatile ExecutionTracker . Id id ; @ Override protected void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { Map < String , String > conf = profile . getConfiguration ( ) ; String trackerClassName = conf . get ( ExecutionTracker . KEY_CLASS ) ; String trackingId = conf . get ( ExecutionTracker . KEY_ID ) ; assertThat ( trackerClassName , is ( notNullValue ( ) ) ) ; assertThat ( trackingId , is ( notNullValue ( ) ) ) ; try { Class < ? > trackerClass = profile . getContext ( ) . getClassLoader ( ) . loadClass ( trackerClassName ) ; this . tracker = trackerClass . asSubclass ( ExecutionTracker . class ) . newInstance ( ) ; this . id = ExecutionTracker . Id . get ( trackingId ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , script , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } @ Override public void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , null , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , null , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } } package com . asakusafw . yaess . bootstrap ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . Properties ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class CommandLineUtilTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void loadProperties_local ( ) throws Exception { Properties p = new Properties ( ) ; p . setProperty ( "" , "" ) ; File file = store ( p ) ; Properties loaded = CommandLineUtil . loadProperties ( file ) ; assertThat ( loaded , is ( p ) ) ; } @ Test public void parseFileList ( ) throws Exception { File a = folder . newFile ( "" ) ; File b = folder . newFile ( "" ) ; File c = folder . newFile ( "" ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( a ) ; buf . append ( File . pathSeparatorChar ) ; buf . append ( b ) ; buf . append ( File . pathSeparatorChar ) ; buf . append ( c ) ; List < File > result = canonicalize ( CommandLineUtil . parseFileList ( buf . toString ( ) ) ) ; assertThat ( result , is ( Arrays . asList ( a , b , c ) ) ) ; } @ Test public void parseFileList_null ( ) { List < File > result = canonicalize ( CommandLineUtil . parseFileList ( null ) ) ; assertThat ( result , is ( Arrays . < File > asList ( ) ) ) ; } @ Test public void parseFileList_empty ( ) { List < File > result = canonicalize ( CommandLineUtil . parseFileList ( "" ) ) ; assertThat ( result , is ( Arrays . < File > asList ( ) ) ) ; } private List < File > canonicalize ( List < File > list ) { List < File > results = new ArrayList < File > ( ) ; for ( File f : list ) { try { results . add ( f . getCanonicalFile ( ) ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } return results ; } @ Test public void buildPluginLoader ( ) throws Exception { File cp1 = folder . newFolder ( "" ) ; File cp2 = folder . newFolder ( "" ) ; new File ( cp1 , "" ) . createNewFile ( ) ; new File ( cp2 , "" ) . createNewFile ( ) ; ClassLoader cl = CommandLineUtil . buildPluginLoader ( getClass ( ) . getClassLoader ( ) , Arrays . asList ( cp1 , cp2 ) ) ; assertThat ( cl . getResource ( "" ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( cl . getResource ( "" ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( cl . getResource ( "" ) , is ( nullValue ( ) ) ) ; } @ Test public void buildPluginLoader_missing_path ( ) throws Exception { File cp1 = folder . newFolder ( "" ) ; File cp2 = folder . newFolder ( "" ) ; new File ( cp1 , "" ) . createNewFile ( ) ; Assume . assumeTrue ( cp2 . delete ( ) ) ; ClassLoader cl = CommandLineUtil . buildPluginLoader ( getClass ( ) . getClassLoader ( ) , Arrays . asList ( cp1 , cp2 ) ) ; assertThat ( cl . getResource ( "" ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( cl . getResource ( "" ) , is ( nullValue ( ) ) ) ; assertThat ( cl . getResource ( "" ) , is ( nullValue ( ) ) ) ; } private File store ( Properties p ) throws IOException , FileNotFoundException { File file = folder . newFile ( "" ) ; FileOutputStream out = new FileOutputStream ( file ) ; try { p . store ( out , "" ) ; } finally { out . close ( ) ; } return file ; } } package com . asakusafw . yaess . bootstrap ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Map ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; public interface ExecutionTracker { String KEY_CLASS = "" ; String KEY_ID = "" ; void add ( Id id , Record record ) throws IOException , InterruptedException ; public class Record { public final ExecutionContext context ; public final ExecutionScript script ; public final ExecutionScriptHandler < ? > handler ; public Record ( ExecutionContext context , ExecutionScript script , ExecutionScriptHandler < ? > handler ) { this . context = context ; this . script = script ; this . handler = handler ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , context . getFlowId ( ) , context . getPhase ( ) , script == null ? handler . getHandlerId ( ) : script . getId ( ) ) ; } } public class Id { private static final Map < String , Id > CACHE = new HashMap < String , Id > ( ) ; private final String token ; private Id ( String token ) { this . token = token ; } public static Id get ( String token ) { synchronized ( CACHE ) { Id cached = CACHE . get ( token ) ; if ( cached != null ) { return cached ; } Id id = new Id ( token ) ; CACHE . put ( token , id ) ; return id ; } } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + token . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Id other = ( Id ) obj ; if ( ! token . equals ( other . token ) ) { return false ; } return true ; } @ Override public String toString ( ) { return token ; } } } package com . asakusafw . yaess . bootstrap ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Map ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScriptHandlerBase ; import com . asakusafw . yaess . core . ServiceProfile ; public class TrackingCommandScriptHandler extends ExecutionScriptHandlerBase implements CommandScriptHandler { private volatile ExecutionTracker tracker ; private volatile ExecutionTracker . Id id ; @ Override protected void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { Map < String , String > conf = profile . getConfiguration ( ) ; String trackerClassName = conf . get ( ExecutionTracker . KEY_CLASS ) ; String trackingId = conf . get ( ExecutionTracker . KEY_ID ) ; assertThat ( trackerClassName , is ( notNullValue ( ) ) ) ; assertThat ( trackingId , is ( notNullValue ( ) ) ) ; try { Class < ? > trackerClass = profile . getContext ( ) . getClassLoader ( ) . loadClass ( trackerClassName ) ; this . tracker = trackerClass . asSubclass ( ExecutionTracker . class ) . newInstance ( ) ; this . id = ExecutionTracker . Id . get ( trackingId ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , script , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } @ Override public void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , null , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { ExecutionTracker . Record record = new ExecutionTracker . Record ( context , null , this ) ; tracker . add ( id , record ) ; } finally { monitor . close ( ) ; } } } package com . asakusafw . yaess . bootstrap ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . yaess . bootstrap . ExecutionTracker . Record ; import com . asakusafw . yaess . bootstrap . Yaess . Configuration ; import com . asakusafw . yaess . bootstrap . Yaess . Mode ; import com . asakusafw . yaess . core . ExecutionLock ; import com . asakusafw . yaess . core . ExecutionPhase ; public class YaessTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void config_batch ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration conf = Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . mode , is ( Mode . BATCH ) ) ; assertThat ( conf . batchId , is ( "" ) ) ; assertThat ( conf . flowId , is ( nullValue ( ) ) ) ; assertThat ( conf . executionId , is ( nullValue ( ) ) ) ; assertThat ( conf . phase , is ( nullValue ( ) ) ) ; assertThat ( conf . arguments . size ( ) , is ( ) ) ; } @ Test public void config_flow ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration conf = Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . mode , is ( Mode . FLOW ) ) ; assertThat ( conf . batchId , is ( "" ) ) ; assertThat ( conf . flowId , is ( "" ) ) ; assertThat ( conf . executionId , is ( "" ) ) ; assertThat ( conf . phase , is ( nullValue ( ) ) ) ; assertThat ( conf . arguments . size ( ) , is ( ) ) ; } @ Test public void config_phase ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , ExecutionPhase . MAIN . getSymbol ( ) ) ; Configuration conf = Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . mode , is ( Mode . PHASE ) ) ; assertThat ( conf . batchId , is ( "" ) ) ; assertThat ( conf . flowId , is ( "" ) ) ; assertThat ( conf . executionId , is ( "" ) ) ; assertThat ( conf . phase , is ( ExecutionPhase . MAIN ) ) ; assertThat ( conf . arguments . size ( ) , is ( ) ) ; } @ Test public void config_arguments ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration conf = Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . mode , is ( Mode . BATCH ) ) ; assertThat ( conf . batchId , is ( "" ) ) ; assertThat ( conf . flowId , is ( nullValue ( ) ) ) ; assertThat ( conf . executionId , is ( nullValue ( ) ) ) ; assertThat ( conf . phase , is ( nullValue ( ) ) ) ; assertThat ( conf . arguments . size ( ) , is ( ) ) ; assertThat ( conf . arguments . get ( "" ) , is ( "" ) ) ; assertThat ( conf . arguments . get ( "" ) , is ( "" ) ) ; assertThat ( conf . arguments . get ( "" ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void config_invalid_profile ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) + "" ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void config_invalid_script ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) + "" ) ; Collections . addAll ( arguments , "" , "" ) ; Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void config_invalid_phase ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void config_batch_invalid_exec ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void config_batch_invalid_phase ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , ExecutionPhase . MAIN . getSymbol ( ) ) ; Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void config_flow_missing_exec ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Yaess . parseConfiguration ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; } @ Test public void execute_batch ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; int exit = Yaess . execute ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( exit , is ( ) ) ; List < Record > records = SerialExecutionTracker . get ( builder . trackingId ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( greaterThan ( ) ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( greaterThan ( ) ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( greaterThan ( ) ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( greaterThan ( ) ) ) ; Set < String > execs = new HashSet < String > ( ) ; execs . add ( flow ( records , "" ) . get ( ) . context . getExecutionId ( ) ) ; execs . add ( flow ( records , "" ) . get ( ) . context . getExecutionId ( ) ) ; execs . add ( flow ( records , "" ) . get ( ) . context . getExecutionId ( ) ) ; execs . add ( flow ( records , "" ) . get ( ) . context . getExecutionId ( ) ) ; assertThat ( execs . size ( ) , is ( ) ) ; } @ Test public void execute_flow ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; int exit = Yaess . execute ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( exit , is ( ) ) ; List < Record > records = SerialExecutionTracker . get ( builder . trackingId ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( greaterThan ( ) ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( ) ) ; List < Record > flow = flow ( records , "" ) ; assertThat ( flow . get ( ) . context . getExecutionId ( ) , is ( "" ) ) ; } @ Test public void execute_phase ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , ExecutionPhase . MAIN . getSymbol ( ) ) ; int exit = Yaess . execute ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( exit , is ( ) ) ; List < Record > records = SerialExecutionTracker . get ( builder . trackingId ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( greaterThan ( ) ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( records , "" ) . size ( ) , is ( ) ) ; assertThat ( flow ( records , "" ) , is ( phase ( records , "" , ExecutionPhase . MAIN ) ) ) ; } @ Test public void execute_invalid_config ( ) throws Exception { List < String > arguments = new ArrayList < String > ( ) ; int exit = Yaess . execute ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void execute_invalid_jobs ( ) throws Exception { ProfileBuilder builder = new ProfileBuilder ( folder . getRoot ( ) ) ; builder . setTracker ( InvalidTracker . class ) ; File profile = builder . getProfile ( ) ; File script = builder . getScript ( ) ; List < String > arguments = new ArrayList < String > ( ) ; Collections . addAll ( arguments , "" , profile . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , script . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , ExecutionPhase . MAIN . getSymbol ( ) ) ; int exit = Yaess . execute ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } private List < Record > flow ( List < Record > records , String flowId ) { List < Record > results = new ArrayList < Record > ( ) ; for ( Record r : records ) { if ( r . context . getFlowId ( ) . equals ( flowId ) ) { results . add ( r ) ; } } return results ; } private List < Record > phase ( List < Record > records , String flowId , ExecutionPhase phase ) { List < Record > results = new ArrayList < Record > ( ) ; for ( Record r : flow ( records , flowId ) ) { if ( r . context . getPhase ( ) == phase ) { results . add ( r ) ; } } return results ; } private static class ProfileBuilder { static final Pattern PLACEHOLDER = Pattern . compile ( "" ) ; final File asakusaHome ; final File lockDir ; final File tempDir ; final ExecutionTracker . Id trackingId ; final Map < String , String > replacement ; final Properties override ; ProfileBuilder ( File working ) { this . asakusaHome = new File ( working , "" ) ; this . lockDir = new File ( working , "" ) ; this . tempDir = new File ( working , "" ) ; this . trackingId = ExecutionTracker . Id . get ( "" ) ; this . replacement = new HashMap < String , String > ( ) ; this . replacement . put ( "" , asakusaHome . getAbsolutePath ( ) ) ; this . replacement . put ( "" , ExecutionLock . Scope . WORLD . getSymbol ( ) ) ; this . replacement . put ( "" , lockDir . getAbsolutePath ( ) ) ; this . replacement . put ( "" , SerialExecutionTracker . class . getName ( ) ) ; this . replacement . put ( "" , "" ) ; this . override = new Properties ( ) ; SerialExecutionTracker . clear ( ) ; } void setTracker ( Class < ? extends ExecutionTracker > tracker ) { this . replacement . put ( "" , tracker . getName ( ) ) ; } Properties loadScript ( ) throws IOException { Properties result = load ( "" ) ; return result ; } File getScript ( ) throws IOException { Properties properties = loadScript ( ) ; return createPropertiesFile ( "" , properties ) ; } Properties loadProfile ( ) throws IOException { Properties result = load ( "" ) ; result . putAll ( override ) ; for ( Map . Entry < Object , Object > entry : result . entrySet ( ) ) { String value = ( String ) entry . getValue ( ) ; StringBuilder buf = new StringBuilder ( ) ; int start = ; Matcher matcher = PLACEHOLDER . matcher ( value ) ; while ( matcher . find ( start ) ) { buf . append ( value . subSequence ( start , matcher . start ( ) ) ) ; String rep = replacement . get ( matcher . group ( ) ) ; if ( rep == null ) { throw new AssertionError ( matcher . group ( ) ) ; } buf . append ( rep ) ; start = matcher . end ( ) ; } buf . append ( value . substring ( start ) ) ; entry . setValue ( buf . toString ( ) ) ; } return result ; } File getProfile ( ) throws IOException { Properties properties = loadProfile ( ) ; return createPropertiesFile ( "" , properties ) ; } private File createPropertiesFile ( String name , Properties properties ) throws IOException { tempDir . mkdirs ( ) ; File file = new File ( tempDir , name ) ; FileOutputStream out = new FileOutputStream ( file ) ; try { properties . store ( out , name ) ; } finally { out . close ( ) ; } return file ; } private Properties load ( String name ) throws IOException { Properties result = new Properties ( ) ; InputStream in = getClass ( ) . getResourceAsStream ( name ) ; assertThat ( in , is ( notNullValue ( ) ) ) ; try { result . load ( in ) ; } finally { in . close ( ) ; } return result ; } } public static class InvalidTracker implements ExecutionTracker { @ Override public void add ( Id id , Record record ) throws IOException , InterruptedException { throw new IOException ( ) ; } } } package com . asakusafw . yaess . bootstrap ; package com . asakusafw . yaess . bootstrap ; import java . io . File ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . TreeMap ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . apache . commons . cli . ParseException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . YaessLogger ; import com . asakusafw . yaess . core . YaessProfile ; import com . asakusafw . yaess . core . task . ExecutionTask ; public final class Yaess { static final YaessLogger YSLOG = new YaessBootstrapLogger ( Yaess . class ) ; static final Logger LOG = LoggerFactory . getLogger ( Yaess . class ) ; static final Option OPT_PROFILE ; static final Option OPT_SCRIPT ; static final Option OPT_BATCH_ID ; static final Option OPT_FLOW_ID ; static final Option OPT_EXECUTION_ID ; static final Option OPT_PHASE_NAME ; static final Option OPT_PLUGIN ; static final Option OPT_ARGUMENT ; static final Option OPT_DEFINITION ; private static final Options OPTIONS ; static { OPT_PROFILE = new Option ( "" , true , "" ) ; OPT_PROFILE . setArgName ( "" ) ; OPT_PROFILE . setRequired ( true ) ; OPT_SCRIPT = new Option ( "" , true , "" ) ; OPT_SCRIPT . setArgName ( "" ) ; OPT_SCRIPT . setRequired ( true ) ; OPT_BATCH_ID = new Option ( "" , true , "" ) ; OPT_BATCH_ID . setArgName ( "" ) ; OPT_BATCH_ID . setRequired ( true ) ; OPT_FLOW_ID = new Option ( "" , true , "" ) ; OPT_FLOW_ID . setArgName ( "" ) ; OPT_FLOW_ID . setRequired ( false ) ; OPT_EXECUTION_ID = new Option ( "" , true , "" ) ; OPT_EXECUTION_ID . setArgName ( "" ) ; OPT_EXECUTION_ID . setRequired ( false ) ; OPT_PHASE_NAME = new Option ( "" , true , "" ) ; OPT_PHASE_NAME . setArgName ( "" ) ; OPT_PHASE_NAME . setRequired ( false ) ; OPT_PLUGIN = new Option ( "" , true , "" ) ; OPT_PLUGIN . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN . setRequired ( false ) ; OPT_ARGUMENT = new Option ( "" , true , "" ) ; OPT_ARGUMENT . setArgs ( ) ; OPT_ARGUMENT . setValueSeparator ( '' ) ; OPT_ARGUMENT . setArgName ( "" ) ; OPT_ARGUMENT . setRequired ( false ) ; OPT_DEFINITION = new Option ( "" , true , "" ) ; OPT_DEFINITION . setArgs ( ) ; OPT_DEFINITION . setValueSeparator ( '' ) ; OPT_DEFINITION . setArgName ( "" ) ; OPT_DEFINITION . setRequired ( false ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_PROFILE ) ; OPTIONS . addOption ( OPT_SCRIPT ) ; OPTIONS . addOption ( OPT_BATCH_ID ) ; OPTIONS . addOption ( OPT_FLOW_ID ) ; OPTIONS . addOption ( OPT_EXECUTION_ID ) ; OPTIONS . addOption ( OPT_PHASE_NAME ) ; OPTIONS . addOption ( OPT_PLUGIN ) ; OPTIONS . addOption ( OPT_ARGUMENT ) ; OPTIONS . addOption ( OPT_DEFINITION ) ; } private Yaess ( ) { return ; } public static void main ( String ... args ) { CommandLineUtil . prepareLogContext ( ) ; YSLOG . info ( "" ) ; long start = System . currentTimeMillis ( ) ; int status = execute ( args ) ; long end = System . currentTimeMillis ( ) ; YSLOG . info ( "" , status , end - start ) ; System . exit ( status ) ; } static int execute ( String [ ] args ) { assert args != null ; Configuration conf ; try { conf = parseConfiguration ( args ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , Yaess . class . getName ( ) ) , OPTIONS , true ) ; System . out . println ( "" ) ; for ( ExecutionPhase phase : ExecutionPhase . values ( ) ) { System . out . printf ( "" , phase . getSymbol ( ) ) ; } YSLOG . error ( e , "" , Arrays . toString ( args ) ) ; return ; } ExecutionTask task ; try { task = ExecutionTask . load ( conf . profile , conf . script , conf . arguments , conf . definitions ) ; } catch ( Exception e ) { YSLOG . error ( e , "" , conf ) ; return ; } YSLOG . info ( "" , conf ) ; try { switch ( conf . mode ) { case BATCH : task . executeBatch ( conf . batchId ) ; break ; case FLOW : task . executeFlow ( conf . batchId , conf . flowId , conf . executionId ) ; break ; case PHASE : task . executePhase ( conf . batchId , conf . flowId , conf . executionId , conf . phase ) ; break ; default : throw new AssertionError ( conf . mode ) ; } return ; } catch ( Exception e ) { YSLOG . error ( e , "" , conf ) ; return ; } } static Configuration parseConfiguration ( String [ ] args ) throws ParseException { assert args != null ; LOG . debug ( "" , Arrays . toString ( args ) ) ; CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String profile = cmd . getOptionValue ( OPT_PROFILE . getOpt ( ) ) ; LOG . debug ( "" , profile ) ; String script = cmd . getOptionValue ( OPT_SCRIPT . getOpt ( ) ) ; LOG . debug ( "" , script ) ; String batchId = cmd . getOptionValue ( OPT_BATCH_ID . getOpt ( ) ) ; LOG . debug ( "" , batchId ) ; String flowId = cmd . getOptionValue ( OPT_FLOW_ID . getOpt ( ) ) ; LOG . debug ( "" , flowId ) ; String executionId = cmd . getOptionValue ( OPT_EXECUTION_ID . getOpt ( ) ) ; LOG . debug ( "" , executionId ) ; String phaseName = cmd . getOptionValue ( OPT_PHASE_NAME . getOpt ( ) ) ; LOG . debug ( "" , phaseName ) ; String plugins = cmd . getOptionValue ( OPT_PLUGIN . getOpt ( ) ) ; LOG . debug ( "" , plugins ) ; Properties arguments = cmd . getOptionProperties ( OPT_ARGUMENT . getOpt ( ) ) ; LOG . debug ( "" , arguments ) ; Properties definitions = cmd . getOptionProperties ( OPT_DEFINITION . getOpt ( ) ) ; LOG . debug ( "" , definitions ) ; LOG . debug ( "" , plugins ) ; List < File > pluginFiles = CommandLineUtil . parseFileList ( plugins ) ; ClassLoader loader = CommandLineUtil . buildPluginLoader ( Yaess . class . getClassLoader ( ) , pluginFiles ) ; Configuration result = new Configuration ( ) ; result . mode = computeMode ( flowId , executionId , phaseName ) ; LOG . debug ( "" , profile ) ; try { ProfileContext context = ProfileContext . system ( loader ) ; Properties properties = CommandLineUtil . loadProperties ( new File ( profile ) ) ; result . profile = YaessProfile . load ( properties , context ) ; } catch ( Exception e ) { YSLOG . error ( e , "" , profile ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile ) , e ) ; } LOG . debug ( "" , script ) ; try { Properties properties = CommandLineUtil . loadProperties ( new File ( script ) ) ; result . script = properties ; } catch ( Exception e ) { YSLOG . error ( e , "" , script ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , script ) , e ) ; } result . batchId = batchId ; result . flowId = flowId ; result . executionId = executionId ; if ( phaseName != null ) { result . phase = ExecutionPhase . findFromSymbol ( phaseName ) ; if ( result . phase == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , phaseName ) ) ; } } result . arguments = toMap ( arguments ) ; result . definitions = toMap ( definitions ) ; LOG . debug ( "" ) ; return result ; } private static Map < String , String > toMap ( Properties p ) { assert p != null ; Map < String , String > results = new TreeMap < String , String > ( ) ; for ( Map . Entry < Object , Object > entry : p . entrySet ( ) ) { results . put ( ( String ) entry . getKey ( ) , ( String ) entry . getValue ( ) ) ; } return results ; } private static Mode computeMode ( String flowId , String executionId , String phaseName ) { if ( flowId == null ) { if ( executionId != null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , OPT_EXECUTION_ID . getOpt ( ) , OPT_FLOW_ID . getOpt ( ) ) ) ; } if ( phaseName != null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , OPT_PHASE_NAME . getOpt ( ) , OPT_FLOW_ID . getOpt ( ) ) ) ; } return Mode . BATCH ; } else { if ( executionId == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , OPT_EXECUTION_ID . getOpt ( ) , OPT_FLOW_ID . getOpt ( ) ) ) ; } if ( phaseName == null ) { return Mode . FLOW ; } else { return Mode . PHASE ; } } } static final class Configuration { Mode mode ; YaessProfile profile ; Properties script ; String batchId ; String flowId ; String executionId ; ExecutionPhase phase ; Map < String , String > arguments ; Map < String , String > definitions ; @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( mode ) ; builder . append ( "" ) ; builder . append ( batchId ) ; if ( flowId != null ) { builder . append ( "" ) ; builder . append ( flowId ) ; } if ( executionId != null ) { builder . append ( "" ) ; builder . append ( executionId ) ; } if ( phase != null ) { builder . append ( "" ) ; builder . append ( phase ) ; } builder . append ( "" ) ; return builder . toString ( ) ; } } enum Mode { BATCH , FLOW , PHASE , } } package com . asakusafw . yaess . bootstrap ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . URL ; import java . net . URLClassLoader ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . slf4j . MDC ; import com . asakusafw . yaess . core . YaessLogger ; public final class CommandLineUtil { static final YaessLogger YSLOG = new YaessBootstrapLogger ( CommandLineUtil . class ) ; static final Logger LOG = LoggerFactory . getLogger ( CommandLineUtil . class ) ; public static final String LOG_CONTEXT_PREFIX = "" ; public static final String SCHEME_CLASSPATH = "" ; public static void prepareLogContext ( ) { Map < String , String > registered = new TreeMap < String , String > ( ) ; Properties properties = System . getProperties ( ) ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { if ( ( entry . getKey ( ) instanceof String ) == false || ( entry . getValue ( ) instanceof String ) == false ) { continue ; } String key = ( String ) entry . getKey ( ) ; if ( key . startsWith ( LOG_CONTEXT_PREFIX ) == false ) { continue ; } String value = ( String ) entry . getValue ( ) ; String name = key . substring ( LOG_CONTEXT_PREFIX . length ( ) ) ; MDC . put ( name , value ) ; registered . put ( name , value ) ; } LOG . debug ( "" , registered ) ; } public static Properties loadProperties ( File path ) throws IOException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , path ) ; FileInputStream in = new FileInputStream ( path ) ; try { Properties properties = new Properties ( ) ; BufferedInputStream bin = new BufferedInputStream ( in ) ; properties . load ( bin ) ; bin . close ( ) ; return properties ; } finally { in . close ( ) ; } } public static List < File > parseFileList ( String fileListOrNull ) { if ( fileListOrNull == null || fileListOrNull . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < File > results = new ArrayList < File > ( ) ; int start = ; while ( true ) { int index = fileListOrNull . indexOf ( File . pathSeparatorChar , start ) ; if ( index < ) { break ; } if ( start != index ) { results . add ( new File ( fileListOrNull . substring ( start , index ) . trim ( ) ) ) ; } start = index + ; } results . add ( new File ( fileListOrNull . substring ( start ) . trim ( ) ) ) ; return results ; } public static ClassLoader buildPluginLoader ( final ClassLoader parent , List < File > files ) { if ( files == null ) { throw new IllegalArgumentException ( "" ) ; } final List < URL > pluginLocations = new ArrayList < URL > ( ) ; for ( File file : files ) { try { if ( file . exists ( ) == false ) { throw new FileNotFoundException ( MessageFormat . format ( "" , file . getAbsolutePath ( ) ) ) ; } URL url = file . toURI ( ) . toURL ( ) ; pluginLocations . add ( url ) ; } catch ( IOException e ) { YSLOG . warn ( e , "" , file . getAbsolutePath ( ) ) ; } } ClassLoader serviceLoader = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) { URLClassLoader loader = new URLClassLoader ( pluginLocations . toArray ( new URL [ pluginLocations . size ( ) ] ) , parent ) ; return loader ; } } ) ; return serviceLoader ; } private CommandLineUtil ( ) { return ; } } package com . asakusafw . yaess . bootstrap ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . yaess . core . YaessLogger ; public class YaessBootstrapLogger extends YaessLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public YaessBootstrapLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . yaess . tools ; package com . asakusafw . yaess . tools ; import java . text . MessageFormat ; import java . util . Map ; import java . util . Properties ; import java . util . SortedMap ; import java . util . TreeMap ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . apache . commons . cli . ParseException ; public final class GenerateExecutionId { static final Option OPT_BATCH_ID ; static final Option OPT_FLOW_ID ; static final Option OPT_ARGUMENT ; private static final Options OPTIONS ; static { OPT_BATCH_ID = new Option ( "" , true , "" ) ; OPT_BATCH_ID . setArgName ( "" ) ; OPT_BATCH_ID . setRequired ( true ) ; OPT_FLOW_ID = new Option ( "" , true , "" ) ; OPT_FLOW_ID . setArgName ( "" ) ; OPT_FLOW_ID . setRequired ( true ) ; OPT_ARGUMENT = new Option ( "" , true , "" ) ; OPT_ARGUMENT . setArgs ( ) ; OPT_ARGUMENT . setValueSeparator ( '' ) ; OPT_ARGUMENT . setArgName ( "" ) ; OPT_ARGUMENT . setRequired ( false ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_BATCH_ID ) ; OPTIONS . addOption ( OPT_FLOW_ID ) ; OPTIONS . addOption ( OPT_ARGUMENT ) ; } private GenerateExecutionId ( ) { return ; } public static void main ( String ... args ) { int status = execute ( args ) ; System . exit ( status ) ; } static int execute ( String [ ] args ) { assert args != null ; Configuration conf ; try { conf = parseConfiguration ( args ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , GenerateExecutionId . class . getName ( ) ) , OPTIONS , true ) ; e . printStackTrace ( System . out ) ; return ; } try { String executionId = computeExecutionId ( conf ) ; System . out . print ( executionId ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return ; } return ; } static String computeExecutionId ( Configuration conf ) { assert conf != null ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( normalize ( conf . batchId ) ) ; buf . append ( '' ) ; buf . append ( normalize ( conf . flowId ) ) ; buf . append ( '' ) ; long hash = * * ; final int prime = ; hash = hash * prime + conf . batchId . trim ( ) . hashCode ( ) ; hash = hash * prime + conf . flowId . trim ( ) . hashCode ( ) ; for ( Map . Entry < String , String > entry : conf . arguments . entrySet ( ) ) { hash = hash * prime + entry . getKey ( ) . trim ( ) . hashCode ( ) ; hash = hash * prime + entry . getValue ( ) . trim ( ) . hashCode ( ) ; } buf . append ( String . format ( "" , hash ) ) ; return buf . toString ( ) ; } private static String normalize ( String string ) { assert string != null ; StringBuilder buf = new StringBuilder ( ) ; for ( char c : string . toCharArray ( ) ) { if ( Character . isJavaIdentifierPart ( c ) ) { buf . append ( c ) ; } else { buf . append ( '' ) ; } } return buf . toString ( ) ; } static Configuration parseConfiguration ( String [ ] args ) throws ParseException { assert args != null ; CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String batchId = cmd . getOptionValue ( OPT_BATCH_ID . getOpt ( ) ) ; String flowId = cmd . getOptionValue ( OPT_FLOW_ID . getOpt ( ) ) ; Properties arguments = cmd . getOptionProperties ( OPT_ARGUMENT . getOpt ( ) ) ; SortedMap < String , String > pairs = new TreeMap < String , String > ( ) ; for ( Map . Entry < Object , Object > entry : arguments . entrySet ( ) ) { Object key = entry . getKey ( ) ; Object value = entry . getValue ( ) ; if ( key instanceof String && value instanceof String ) { pairs . put ( ( String ) key , ( String ) value ) ; } } Configuration result = new Configuration ( ) ; result . batchId = batchId ; result . flowId = flowId ; result . arguments = pairs ; return result ; } static final class Configuration { String batchId ; String flowId ; SortedMap < String , String > arguments ; } } package com . asakusafw . yaess . tools ; import java . io . File ; import java . io . IOException ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . io . Writer ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Collection ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . apache . commons . cli . ParseException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . BatchScript ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . FlowScript ; import com . google . gson . Gson ; import com . google . gson . GsonBuilder ; import com . google . gson . JsonArray ; import com . google . gson . JsonObject ; import com . google . gson . JsonPrimitive ; public final class Explain { static final Logger LOG = LoggerFactory . getLogger ( Explain . class ) ; static final Option OPT_SCRIPT ; private static final Options OPTIONS ; static { OPT_SCRIPT = new Option ( "" , true , "" ) ; OPT_SCRIPT . setArgName ( "" ) ; OPT_SCRIPT . setRequired ( true ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_SCRIPT ) ; } private Explain ( ) { return ; } public static void main ( String ... args ) { int status = execute ( args ) ; System . exit ( status ) ; } static int execute ( String [ ] args ) { assert args != null ; Configuration conf ; try { conf = parseConfiguration ( args ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , Explain . class . getName ( ) ) , OPTIONS , true ) ; e . printStackTrace ( System . out ) ; return ; } try { explainBatch ( conf . script ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return ; } return ; } private static void explainBatch ( BatchScript script ) throws IOException { assert script != null ; JsonObject batch = analyzeBatch ( script ) ; Gson gson = new GsonBuilder ( ) . disableHtmlEscaping ( ) . setPrettyPrinting ( ) . create ( ) ; Writer writer = new PrintWriter ( new OutputStreamWriter ( System . out , Charset . defaultCharset ( ) ) ) ; gson . toJson ( batch , writer ) ; writer . flush ( ) ; } private static JsonObject analyzeBatch ( BatchScript script ) { assert script != null ; JsonArray jobflows = new JsonArray ( ) ; for ( FlowScript flowScript : script . getAllFlows ( ) ) { JsonObject jobflow = analyzeJobflow ( flowScript ) ; jobflows . add ( jobflow ) ; } JsonObject batch = new JsonObject ( ) ; batch . addProperty ( "" , script . getId ( ) ) ; batch . add ( "" , jobflows ) ; return batch ; } private static JsonObject analyzeJobflow ( FlowScript flowScript ) { assert flowScript != null ; JsonArray phases = new JsonArray ( ) ; for ( Map . Entry < ExecutionPhase , Set < ExecutionScript > > entry : flowScript . getScripts ( ) . entrySet ( ) ) { ExecutionPhase phase = entry . getKey ( ) ; if ( entry . getValue ( ) . isEmpty ( ) == false || phase == ExecutionPhase . SETUP || phase == ExecutionPhase . CLEANUP ) { phases . add ( new JsonPrimitive ( phase . getSymbol ( ) ) ) ; } } JsonObject jobflow = new JsonObject ( ) ; jobflow . addProperty ( "" , flowScript . getId ( ) ) ; jobflow . add ( "" , toJsonArray ( flowScript . getBlockerIds ( ) ) ) ; jobflow . add ( "" , phases ) ; return jobflow ; } private static JsonArray toJsonArray ( Collection < String > values ) { assert values != null ; JsonArray array = new JsonArray ( ) ; for ( String value : values ) { array . add ( new JsonPrimitive ( value ) ) ; } return array ; } static Configuration parseConfiguration ( String [ ] args ) throws ParseException { assert args != null ; LOG . debug ( "" , Arrays . toString ( args ) ) ; CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String script = cmd . getOptionValue ( OPT_SCRIPT . getOpt ( ) ) ; LOG . debug ( "" , script ) ; Configuration result = new Configuration ( ) ; LOG . debug ( "" , script ) ; try { Properties properties = CommandLineUtil . loadProperties ( new File ( script ) ) ; result . script = BatchScript . load ( properties ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , script ) , e ) ; } LOG . debug ( "" ) ; return result ; } static final class Configuration { BatchScript script ; } } package com . asakusafw . yaess . tools ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . URL ; import java . net . URLClassLoader ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Properties ; public final class CommandLineUtil { public static final String SCHEME_CLASSPATH = "" ; public static Properties loadProperties ( File path ) throws IOException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } FileInputStream in = new FileInputStream ( path ) ; try { Properties properties = new Properties ( ) ; BufferedInputStream bin = new BufferedInputStream ( in ) ; properties . load ( bin ) ; bin . close ( ) ; return properties ; } finally { in . close ( ) ; } } public static List < File > parseFileList ( String fileListOrNull ) { if ( fileListOrNull == null || fileListOrNull . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < File > results = new ArrayList < File > ( ) ; int start = ; while ( true ) { int index = fileListOrNull . indexOf ( File . pathSeparatorChar , start ) ; if ( index < ) { break ; } if ( start != index ) { results . add ( new File ( fileListOrNull . substring ( start , index ) . trim ( ) ) ) ; } start = index + ; } results . add ( new File ( fileListOrNull . substring ( start ) . trim ( ) ) ) ; return results ; } public static ClassLoader buildPluginLoader ( final ClassLoader parent , List < File > files ) { if ( files == null ) { throw new IllegalArgumentException ( "" ) ; } final List < URL > pluginLocations = new ArrayList < URL > ( ) ; for ( File file : files ) { try { if ( file . exists ( ) == false ) { throw new FileNotFoundException ( MessageFormat . format ( "" , file . getAbsolutePath ( ) ) ) ; } URL url = file . toURI ( ) . toURL ( ) ; pluginLocations . add ( url ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } ClassLoader serviceLoader = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) { URLClassLoader loader = new URLClassLoader ( pluginLocations . toArray ( new URL [ pluginLocations . size ( ) ] ) , parent ) ; return loader ; } } ) ; return serviceLoader ; } private CommandLineUtil ( ) { return ; } } package com . asakusafw . compiler . yaess ; package com . asakusafw . compiler . yaess ; import java . io . File ; import java . io . IOException ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . WorkflowProcessor ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . Command ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . CommandContext ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graph . Vertex ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . yaess . core . BatchScript ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . FlowScript ; import com . asakusafw . yaess . core . HadoopScript ; public class YaessWorkflowProcessor extends AbstractWorkflowProcessor { static final Logger LOG = LoggerFactory . getLogger ( YaessWorkflowProcessor . class ) ; public static final String PATH = "" ; public static File getScriptOutput ( File outputDir ) { Precondition . checkMustNotBeNull ( outputDir , "" ) ; return new File ( outputDir , PATH ) ; } @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( JobFlowWorkDescriptionProcessor . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { LOG . debug ( "" ) ; List < FlowScript > scripts = processJobflowList ( workflow ) ; LOG . debug ( "" ) ; Properties properties = new Properties ( ) ; properties . setProperty ( BatchScript . KEY_ID , getBatchId ( ) ) ; properties . setProperty ( BatchScript . KEY_VERSION , BatchScript . VERSION ) ; properties . setProperty ( BatchScript . KEY_VERIFICATION_CODE , getEnvironment ( ) . getBuildId ( ) ) ; for ( FlowScript script : scripts ) { LOG . trace ( "" , script . getId ( ) ) ; script . storeTo ( properties ) ; } LOG . debug ( "" ) ; OutputStream output = getEnvironment ( ) . openResource ( PATH ) ; try { properties . store ( output , MessageFormat . format ( "" , getBatchId ( ) , BatchScript . VERSION ) ) ; } finally { output . close ( ) ; } LOG . debug ( "" ) ; } private List < FlowScript > processJobflowList ( Workflow workflow ) { assert workflow != null ; List < FlowScript > jobflows = Lists . create ( ) ; for ( Graph . Vertex < Workflow . Unit > vertex : sortJobflow ( workflow . getGraph ( ) ) ) { FlowScript jobflow = processJobflow ( vertex . getNode ( ) , vertex . getConnected ( ) ) ; jobflows . add ( jobflow ) ; } return jobflows ; } private List < Graph . Vertex < JobflowModel . Stage > > sortStage ( Iterable < Graph . Vertex < JobflowModel . Stage > > vertices ) { assert vertices != null ; List < Graph . Vertex < JobflowModel . Stage > > results = Lists . create ( ) ; for ( Graph . Vertex < JobflowModel . Stage > vertex : vertices ) { results . add ( vertex ) ; } Collections . sort ( results , new Comparator < Graph . Vertex < JobflowModel . Stage > > ( ) { @ Override public int compare ( Vertex < JobflowModel . Stage > o1 , Vertex < JobflowModel . Stage > o2 ) { int stage1 = o1 . getNode ( ) . getNumber ( ) ; int stage2 = o2 . getNode ( ) . getNumber ( ) ; if ( stage1 < stage2 ) { return - ; } else if ( stage1 > stage2 ) { return + ; } else { return ; } } } ) ; return results ; } private List < Graph . Vertex < Workflow . Unit > > sortJobflow ( Iterable < Graph . Vertex < Workflow . Unit > > vertices ) { assert vertices != null ; List < Graph . Vertex < Workflow . Unit > > results = Lists . create ( ) ; for ( Graph . Vertex < Workflow . Unit > vertex : vertices ) { results . add ( vertex ) ; } Collections . sort ( results , new Comparator < Graph . Vertex < Workflow . Unit > > ( ) { @ Override public int compare ( Vertex < Workflow . Unit > o1 , Vertex < Workflow . Unit > o2 ) { return o1 . getNode ( ) . getDescription ( ) . getName ( ) . compareTo ( o2 . getNode ( ) . getDescription ( ) . getName ( ) ) ; } } ) ; return results ; } private FlowScript processJobflow ( Workflow . Unit unit , Set < Workflow . Unit > blockers ) { assert unit != null ; assert blockers != null ; JobflowModel model = toJobflowModel ( unit ) ; CommandContext context = new CommandContext ( ExecutionScript . PLACEHOLDER_HOME + '' , ExecutionScript . PLACEHOLDER_EXECUTION_ID , ExecutionScript . PLACEHOLDER_ARGUMENTS ) ; Map < ExecutionPhase , List < ExecutionScript > > scripts = Maps . create ( ) ; scripts . put ( ExecutionPhase . INITIALIZE , processInitializers ( model , context ) ) ; scripts . put ( ExecutionPhase . IMPORT , processImporters ( model , context ) ) ; scripts . put ( ExecutionPhase . PROLOGUE , processPrologues ( model , context ) ) ; scripts . put ( ExecutionPhase . MAIN , processMain ( model , context ) ) ; scripts . put ( ExecutionPhase . EPILOGUE , processEpilogues ( model , context ) ) ; scripts . put ( ExecutionPhase . EXPORT , processExporters ( model , context ) ) ; scripts . put ( ExecutionPhase . FINALIZE , processFinalizers ( model , context ) ) ; return new FlowScript ( model . getFlowId ( ) , toUnitNames ( blockers ) , scripts ) ; } private List < ExecutionScript > processInitializers ( JobflowModel model , CommandContext context ) { assert model != null ; assert context != null ; List < ExecutionScript > results = Lists . create ( ) ; for ( ExternalIoCommandProvider provider : model . getCompiled ( ) . getCommandProviders ( ) ) { List < Command > commands = provider . getInitializeCommand ( context ) ; List < ExecutionScript > scripts = processCommands ( provider , commands ) ; results . addAll ( scripts ) ; } return results ; } private List < ExecutionScript > processImporters ( JobflowModel model , CommandContext context ) { assert model != null ; assert context != null ; List < ExecutionScript > results = Lists . create ( ) ; for ( ExternalIoCommandProvider provider : model . getCompiled ( ) . getCommandProviders ( ) ) { List < ExecutionScript > scripts = processCommands ( provider , provider . getImportCommand ( context ) ) ; results . addAll ( scripts ) ; } return results ; } private List < ExecutionScript > processExporters ( JobflowModel model , CommandContext context ) { assert model != null ; assert context != null ; List < ExecutionScript > results = Lists . create ( ) ; for ( ExternalIoCommandProvider provider : model . getCompiled ( ) . getCommandProviders ( ) ) { List < ExecutionScript > scripts = processCommands ( provider , provider . getExportCommand ( context ) ) ; results . addAll ( scripts ) ; } return results ; } private List < ExecutionScript > processFinalizers ( JobflowModel model , CommandContext context ) { assert model != null ; assert context != null ; List < ExecutionScript > results = Lists . create ( ) ; for ( ExternalIoCommandProvider provider : model . getCompiled ( ) . getCommandProviders ( ) ) { List < ExecutionScript > scripts = processCommands ( provider , provider . getFinalizeCommand ( context ) ) ; results . addAll ( scripts ) ; } return results ; } private List < ExecutionScript > processCommands ( ExternalIoCommandProvider provider , List < Command > commands ) { assert provider != null ; assert commands != null ; List < ExecutionScript > scripts = Lists . create ( ) ; String prefix = provider . getName ( ) ; int index = ; for ( Command command : commands ) { String id = String . format ( "" , prefix , '' , index ++ ) ; String profile = command . getProfileName ( ) ; scripts . add ( new CommandScript ( id , Collections . < String > emptySet ( ) , profile == null ? CommandScript . DEFAULT_PROFILE_NAME : profile , command . getModuleName ( ) , command . getCommandTokens ( ) , command . getEnvironment ( ) ) ) ; } return scripts ; } private List < ExecutionScript > processPrologues ( JobflowModel model , CommandContext context ) { assert model != null ; assert context != null ; return processStages ( model . getCompiled ( ) . getPrologueStages ( ) ) ; } private List < ExecutionScript > processEpilogues ( JobflowModel model , CommandContext context ) { assert model != null ; assert context != null ; return processStages ( model . getCompiled ( ) . getEpilogueStages ( ) ) ; } private List < ExecutionScript > processMain ( JobflowModel model , CommandContext context ) { assert model != null ; assert context != null ; List < ExecutionScript > results = Lists . create ( ) ; for ( Graph . Vertex < JobflowModel . Stage > stage : sortStage ( model . getDependencyGraph ( ) ) ) { results . add ( processStage ( stage . getNode ( ) . getCompiled ( ) , stage . getConnected ( ) ) ) ; } return results ; } private List < ExecutionScript > processStages ( List < CompiledStage > stages ) { assert stages != null ; List < ExecutionScript > results = Lists . create ( ) ; for ( CompiledStage stage : stages ) { results . add ( processStage ( stage , Collections . < JobflowModel . Stage > emptySet ( ) ) ) ; } return results ; } private ExecutionScript processStage ( CompiledStage stage , Set < JobflowModel . Stage > blockers ) { assert stage != null ; assert blockers != null ; String stageId = stage . getStageId ( ) ; Set < String > blockerIds = toStageNames ( blockers ) ; String className = stage . getQualifiedName ( ) . toNameString ( ) ; Map < String , String > props = Collections . emptyMap ( ) ; Map < String , String > envs = Collections . emptyMap ( ) ; return new HadoopScript ( stageId , blockerIds , className , props , envs ) ; } private JobflowModel toJobflowModel ( Workflow . Unit unit ) { assert unit != null ; assert unit . getDescription ( ) instanceof JobFlowWorkDescription ; return ( JobflowModel ) unit . getProcessed ( ) ; } private Set < String > toUnitNames ( Set < Workflow . Unit > blockers ) { assert blockers != null ; Set < String > names = Sets . create ( ) ; for ( Workflow . Unit unit : blockers ) { names . add ( unit . getDescription ( ) . getName ( ) ) ; } return names ; } private Set < String > toStageNames ( Set < JobflowModel . Stage > blockers ) { assert blockers != null ; Set < String > names = Sets . create ( ) ; for ( JobflowModel . Stage stage : blockers ) { names . add ( stage . getCompiled ( ) . getStageId ( ) ) ; } return names ; } private String getBatchId ( ) { return getEnvironment ( ) . getConfiguration ( ) . getBatchId ( ) ; } } package com . asakusafw . compiler . yaess ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . TreeSet ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectBatchCompiler ; import com . asakusafw . compiler . yaess . testing . batch . ComplexBatch ; import com . asakusafw . compiler . yaess . testing . batch . DiamondBatch ; import com . asakusafw . compiler . yaess . testing . batch . SimpleBatch ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . yaess . core . BatchScript ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . FlowScript ; public class YaessWorkflowProcessorTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { Properties p = compile ( SimpleBatch . class ) ; BatchScript script = BatchScript . load ( p ) ; assertThat ( FlowScript . extractFlowIds ( p ) , is ( set ( "" ) ) ) ; FlowScript first = script . findFlow ( "" ) ; assertThat ( first . getId ( ) , is ( "" ) ) ; assertThat ( first . getBlockerIds ( ) , is ( set ( ) ) ) ; Map < ExecutionPhase , Set < ExecutionScript > > firstScripts = first . getScripts ( ) ; assertThat ( firstScripts . get ( ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . CLEANUP ) . size ( ) , is ( ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . INITIALIZE ) , hasCommands ( "" ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . IMPORT ) , hasCommands ( "" ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . PROLOGUE ) . size ( ) , is ( ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . EPILOGUE ) . size ( ) , is ( ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . EXPORT ) , hasCommands ( "" ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . FINALIZE ) , hasCommands ( "" ) ) ; assertThat ( firstScripts . get ( ExecutionPhase . SETUP ) . size ( ) , is ( ) ) ; } @ Test public void complex ( ) throws Exception { Properties p = compile ( ComplexBatch . class ) ; BatchScript script = BatchScript . load ( p ) ; assertThat ( FlowScript . extractFlowIds ( p ) , is ( set ( "" ) ) ) ; FlowScript last = script . findFlow ( "" ) ; assertThat ( last . getId ( ) , is ( "" ) ) ; assertThat ( last . getBlockerIds ( ) , is ( set ( ) ) ) ; Map < ExecutionPhase , Set < ExecutionScript > > lastScripts = last . getScripts ( ) ; assertThat ( lastScripts . get ( ExecutionPhase . MAIN ) . size ( ) , is ( ) ) ; Set < String > blockers = Sets . create ( ) ; for ( ExecutionScript ex : lastScripts . get ( ExecutionPhase . MAIN ) ) { blockers . addAll ( ex . getBlockerIds ( ) ) ; } assertThat ( blockers . size ( ) , is ( greaterThan ( ) ) ) ; } @ Test public void diamond ( ) throws Exception { Properties p = compile ( DiamondBatch . class ) ; BatchScript script = BatchScript . load ( p ) ; assertThat ( FlowScript . extractFlowIds ( p ) , is ( set ( "" , "" , "" , "" ) ) ) ; FlowScript first = script . findFlow ( "" ) ; FlowScript left = script . findFlow ( "" ) ; FlowScript right = script . findFlow ( "" ) ; FlowScript last = script . findFlow ( "" ) ; assertThat ( first . getId ( ) , is ( "" ) ) ; assertThat ( left . getId ( ) , is ( "" ) ) ; assertThat ( right . getId ( ) , is ( "" ) ) ; assertThat ( last . getId ( ) , is ( "" ) ) ; assertThat ( first . getBlockerIds ( ) , is ( set ( ) ) ) ; assertThat ( left . getBlockerIds ( ) , is ( set ( "" ) ) ) ; assertThat ( right . getBlockerIds ( ) , is ( set ( "" ) ) ) ; assertThat ( last . getBlockerIds ( ) , is ( set ( "" , "" ) ) ) ; } private Matcher < Set < ExecutionScript > > hasCommands ( String ... executables ) { final Set < String > expected = new TreeSet < String > ( ) ; Collections . addAll ( expected , executables ) ; return new BaseMatcher < Set < ExecutionScript > > ( ) { @ Override public boolean matches ( Object target ) { if ( ( target instanceof Set < ? > ) == false ) { return false ; } @ SuppressWarnings ( "" ) Set < ExecutionScript > scripts = ( Set < ExecutionScript > ) target ; Set < String > actual = new TreeSet < String > ( ) ; for ( ExecutionScript ex : scripts ) { if ( ( ex instanceof CommandScript ) == false ) { return false ; } CommandScript cs = ( CommandScript ) ex ; actual . add ( cs . getCommandLineTokens ( ) . get ( ) ) ; } return actual . equals ( expected ) ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( "" ) ; desc . appendValue ( expected ) ; } } ; } private Set < String > set ( String ... values ) { return new TreeSet < String > ( Arrays . asList ( values ) ) ; } private Properties compile ( Class < ? extends BatchDescription > batchClass ) throws IOException { File output = folder . newFolder ( "" ) ; DirectBatchCompiler . compile ( batchClass , "" , Location . fromPath ( "" , '' ) , output , folder . newFolder ( "" ) , Collections . < File > emptyList ( ) , getClass ( ) . getClassLoader ( ) , new FlowCompilerOptions ( ) ) ; File script = YaessWorkflowProcessor . getScriptOutput ( output ) ; assertThat ( script . isFile ( ) , is ( true ) ) ; FileInputStream in = new FileInputStream ( script ) ; try { Properties result = new Properties ( ) ; result . load ( in ) ; return result ; } finally { in . close ( ) ; } } } package com . asakusafw . compiler . yaess . testing . flow ; import com . asakusafw . compiler . yaess . testing . mock . MockExporterDescription ; import com . asakusafw . compiler . yaess . testing . mock . MockImporterDescription ; import com . asakusafw . compiler . yaess . testing . model . Dummy ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; @ JobFlow ( name = "" ) public class RightFlow extends FlowDescription { private final In < Dummy > in ; private final Out < Dummy > out ; public RightFlow ( @ Import ( name = "" , description = MockImporterDescription . class ) In < Dummy > in , @ Export ( name = "" , description = MockExporterDescription . class ) Out < Dummy > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory op = new CoreOperatorFactory ( ) ; Restructure < Dummy > first = op . restructure ( in , Dummy . class ) ; out . add ( first ) ; } } package com . asakusafw . compiler . yaess . testing . flow ; import com . asakusafw . compiler . yaess . testing . mock . MockExporterDescription ; import com . asakusafw . compiler . yaess . testing . mock . MockImporterDescription ; import com . asakusafw . compiler . yaess . testing . model . Dummy ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; @ JobFlow ( name = "" ) public class LeftFlow extends FlowDescription { private final In < Dummy > in ; private final Out < Dummy > out ; public LeftFlow ( @ Import ( name = "" , description = MockImporterDescription . class ) In < Dummy > in , @ Export ( name = "" , description = MockExporterDescription . class ) Out < Dummy > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory op = new CoreOperatorFactory ( ) ; Restructure < Dummy > first = op . restructure ( in , Dummy . class ) ; out . add ( first ) ; } } package com . asakusafw . compiler . yaess . testing . flow ; import com . asakusafw . compiler . yaess . testing . mock . MockExporterDescription ; import com . asakusafw . compiler . yaess . testing . mock . MockImporterDescription ; import com . asakusafw . compiler . yaess . testing . model . Dummy ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; @ JobFlow ( name = "" ) public class FirstFlow extends FlowDescription { private final In < Dummy > in ; private final Out < Dummy > out ; public FirstFlow ( @ Import ( name = "" , description = MockImporterDescription . class ) In < Dummy > in , @ Export ( name = "" , description = MockExporterDescription . class ) Out < Dummy > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory op = new CoreOperatorFactory ( ) ; Restructure < Dummy > first = op . restructure ( in , Dummy . class ) ; out . add ( first ) ; } } package com . asakusafw . compiler . yaess . testing . flow ; import com . asakusafw . compiler . yaess . testing . mock . MockExporterDescription ; import com . asakusafw . compiler . yaess . testing . mock . MockImporterDescription ; import com . asakusafw . compiler . yaess . testing . model . Dummy ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; @ JobFlow ( name = "" ) public class LastFlow extends FlowDescription { private final In < Dummy > in ; private final Out < Dummy > out ; public LastFlow ( @ Import ( name = "" , description = MockImporterDescription . class ) In < Dummy > in , @ Export ( name = "" , description = MockExporterDescription . class ) Out < Dummy > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory op = new CoreOperatorFactory ( ) ; Restructure < Dummy > first = op . restructure ( in , Dummy . class ) ; Restructure < Dummy > second = op . restructure ( op . checkpoint ( first ) , Dummy . class ) ; Restructure < Dummy > last = op . restructure ( op . checkpoint ( second ) , Dummy . class ) ; out . add ( last ) ; } } package com . asakusafw . compiler . yaess . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . yaess . testing . io . DummyInput ; import com . asakusafw . compiler . yaess . testing . io . DummyOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( DummyInput . class ) @ ModelOutputLocation ( DummyOutput . class ) public class Dummy implements DataModel < Dummy > , Writable { private final IntOption value = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Dummy other ) { this . value . copyFrom ( other . value ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Dummy other = ( Dummy ) obj ; if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { value . readFields ( in ) ; } } package com . asakusafw . compiler . yaess . testing . mock ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class MockIoDescriptionProcessor extends ExternalIoDescriptionProcessor { @ Override public Class < ? extends ImporterDescription > getImporterDescriptionType ( ) { return MockImporterDescription . class ; } @ Override public Class < ? extends ExporterDescription > getExporterDescriptionType ( ) { return MockExporterDescription . class ; } @ Override public boolean validate ( List < InputDescription > inputs , List < OutputDescription > outputs ) { return true ; } @ Override public SourceInfo getInputInfo ( InputDescription description ) { Set < Location > locations = Sets . create ( ) ; locations . add ( getEnvironment ( ) . getTargetLocation ( ) . append ( description . getName ( ) ) ) ; return new SourceInfo ( locations , TemporaryInputFormat . class ) ; } @ Override public List < CompiledStage > emitPrologue ( IoContext context ) throws IOException { ModelFactory f = getEnvironment ( ) . getModelFactory ( ) ; return Arrays . asList ( new CompiledStage ( Models . toName ( f , "" ) , "" ) ) ; } @ Override public List < CompiledStage > emitEpilogue ( IoContext context ) throws IOException { ModelFactory f = getEnvironment ( ) . getModelFactory ( ) ; return Arrays . asList ( new CompiledStage ( Models . toName ( f , "" ) , "" ) ) ; } @ Override public ExternalIoCommandProvider createCommandProvider ( IoContext context ) { return new CommandProvider ( ) ; } static class CommandProvider extends ExternalIoCommandProvider { private static final long serialVersionUID = ; @ Override public String getName ( ) { return "" ; } @ Override public List < Command > getInitializeCommand ( CommandContext context ) { return Arrays . asList ( new Command [ ] { new Command ( Arrays . asList ( new String [ ] { "" , } ) , "" , null , Collections . < String , String > emptyMap ( ) ) } ) ; } @ Override public List < Command > getImportCommand ( CommandContext context ) { return Arrays . asList ( new Command [ ] { new Command ( Arrays . asList ( new String [ ] { "" , } ) , "" , "" , Collections . < String , String > emptyMap ( ) ) } ) ; } @ Override public List < Command > getExportCommand ( CommandContext context ) { return Arrays . asList ( new Command [ ] { new Command ( Arrays . asList ( new String [ ] { "" , } ) , "" , "" , Collections . < String , String > emptyMap ( ) ) } ) ; } @ Override public List < Command > getFinalizeCommand ( CommandContext context ) { return Arrays . asList ( new Command [ ] { new Command ( Arrays . asList ( new String [ ] { "" , } ) , "" , null , Collections . < String , String > emptyMap ( ) ) } ) ; } } } package com . asakusafw . compiler . yaess . testing . mock ; import com . asakusafw . compiler . yaess . testing . model . Dummy ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class MockImporterDescription implements ImporterDescription { @ Override public Class < ? > getModelType ( ) { return Dummy . class ; } @ Override public DataSize getDataSize ( ) { return DataSize . UNKNOWN ; } } package com . asakusafw . compiler . yaess . testing . mock ; import com . asakusafw . compiler . yaess . testing . model . Dummy ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class MockExporterDescription implements ExporterDescription { @ Override public Class < ? > getModelType ( ) { return Dummy . class ; } } package com . asakusafw . compiler . yaess . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . yaess . testing . model . Dummy ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class DummyOutput implements ModelOutput < Dummy > { private final RecordEmitter emitter ; public DummyOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Dummy model ) throws IOException { emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . yaess . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . yaess . testing . model . Dummy ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class DummyInput implements ModelInput < Dummy > { private final RecordParser parser ; public DummyInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Dummy model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . yaess . testing . batch ; import com . asakusafw . compiler . yaess . testing . flow . FirstFlow ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class SimpleBatch extends BatchDescription { @ Override protected void describe ( ) { run ( FirstFlow . class ) . soon ( ) ; } } package com . asakusafw . compiler . yaess . testing . batch ; import com . asakusafw . compiler . yaess . testing . flow . FirstFlow ; import com . asakusafw . compiler . yaess . testing . flow . LastFlow ; import com . asakusafw . compiler . yaess . testing . flow . LeftFlow ; import com . asakusafw . compiler . yaess . testing . flow . RightFlow ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . batch . Work ; @ Batch ( name = "" ) public class DiamondBatch extends BatchDescription { @ Override protected void describe ( ) { Work first = run ( FirstFlow . class ) . soon ( ) ; Work left = run ( LeftFlow . class ) . after ( first ) ; Work right = run ( RightFlow . class ) . after ( first ) ; run ( LastFlow . class ) . after ( left , right ) ; } } package com . asakusafw . compiler . yaess . testing . batch ; import com . asakusafw . compiler . yaess . testing . flow . LastFlow ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class ComplexBatch extends BatchDescription { @ Override protected void describe ( ) { run ( LastFlow . class ) . soon ( ) ; } } package com . asakusafw . yaess . jsch ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Scanner ; import java . util . Set ; import java . util . TreeSet ; import org . junit . Assume ; import org . junit . Before ; import org . junit . Rule ; import org . junit . rules . TemporaryFolder ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; public class SshScriptHandlerTestRoot { static final Logger LOG = LoggerFactory . getLogger ( SshScriptHandlerTestRoot . class ) ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; protected File privateKey ; @ Before public void setUp ( ) throws Exception { File home = new File ( System . getProperty ( "" ) ) ; privateKey = new File ( home , "" ) . getCanonicalFile ( ) ; if ( privateKey . isFile ( ) == false ) { System . err . printf ( "" , privateKey ) ; Assume . assumeTrue ( false ) ; } if ( new File ( "" ) . canExecute ( ) == false ) { System . err . printf ( "" , "" ) ; Assume . assumeTrue ( false ) ; } } protected < T extends ExecutionScript > void execute ( T script , ExecutionScriptHandler < T > handler ) { ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; execute ( context , script , handler ) ; } protected < T extends ExecutionScript > void execute ( ExecutionContext context , T script , ExecutionScriptHandler < T > handler ) { try { handler . execute ( ExecutionMonitor . NULL , context , script ) ; } catch ( InterruptedException e ) { throw new AssertionError ( e ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; Assume . assumeNoException ( e ) ; } } protected List < String > getOutput ( File copier ) throws IOException { File output = new File ( copier . getParentFile ( ) , copier . getName ( ) + "" ) ; List < String > results = new ArrayList < String > ( ) ; Scanner scanner = new Scanner ( output ) ; while ( scanner . hasNextLine ( ) ) { results . add ( scanner . nextLine ( ) ) ; } return results ; } protected File getAsakusaHome ( ) { return folder . getRoot ( ) ; } protected File putScript ( String source , String path ) throws IOException { File file = new File ( getAsakusaHome ( ) , path ) ; return putScript ( source , file ) ; } protected File putScript ( String source , File file ) throws IOException { LOG . debug ( "" , source , file ) ; InputStream in = getClass ( ) . getResourceAsStream ( source ) ; assertThat ( source , in , is ( notNullValue ( ) ) ) ; try { copyTo ( in , file ) ; } finally { in . close ( ) ; } file . setExecutable ( true ) ; return file ; } protected Set < String > set ( String ... values ) { return new TreeSet < String > ( Arrays . asList ( values ) ) ; } protected Map < String , String > map ( String ... keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > conf = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length - ; i += ) { conf . put ( keyValuePairs [ i ] , keyValuePairs [ i + ] ) ; } return conf ; } private void copyTo ( InputStream input , File target ) throws IOException { assert input != null ; assert target != null ; File parent = target . getParentFile ( ) ; assertThat ( parent . getAbsolutePath ( ) , parent , not ( nullValue ( ) ) ) ; if ( parent . isDirectory ( ) == false ) { assertThat ( parent . getAbsolutePath ( ) , parent . mkdirs ( ) , is ( true ) ) ; } FileOutputStream output = new FileOutputStream ( target ) ; try { byte [ ] buf = new byte [ ] ; while ( true ) { int read = input . read ( buf ) ; if ( read < ) { break ; } output . write ( buf , , read ) ; } } finally { output . close ( ) ; } } } package com . asakusafw . yaess . jsch ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . junit . Assume ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . PhaseMonitor ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class SshCommandScriptHandlerTest extends SshScriptHandlerTestRoot { @ Test public void simple ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void multiple_arguments ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) , "" , "" , "" , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , is ( Arrays . asList ( "" , "" , "" , "" ) ) ) ; } @ Test public void with_prefix ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( "" , shell . getAbsolutePath ( ) ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void complex_prefix ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( "" , "" , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( "" , shell . getAbsolutePath ( ) , "" , "" ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , is ( Arrays . asList ( "" , "" , "" , "" ) ) ) ; } @ Test public void environment ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) ) , map ( "" , "" , "" , "" ) ) ; CommandScriptHandler handler = handler ( "" , "" , "" , "" ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; } @ Test public void runtime_context ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) ) , map ( "" , "" , "" , "" ) ) ; CommandScriptHandler handler = handler ( "" , "" , "" , "" ) ; RuntimeContext rc = RuntimeContext . DEFAULT . batchId ( "" ) . mode ( ExecutionMode . SIMULATION ) . buildId ( "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) , rc . unapply ( ) ) ; execute ( context , script , handler ) ; Map < String , String > map = new HashMap < String , String > ( ) ; for ( String line : getOutput ( shell ) ) { if ( line . trim ( ) . isEmpty ( ) ) { continue ; } String [ ] kv = line . split ( "" , ) ; if ( kv . length != ) { continue ; } map . put ( kv [ ] , kv [ ] ) ; } assertThat ( RuntimeContext . DEFAULT . apply ( map ) , is ( rc ) ) ; } @ Test ( expected = IOException . class ) public void missing_config ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , "" ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; Map < String , String > conf = map ( ) ; conf . put ( "" , target ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , SshCommandScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; profile . newInstance ( ) ; } @ Test ( expected = IOException . class ) public void invalid_id ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , "" ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; Map < String , String > conf = map ( ) ; conf . put ( JschProcessExecutor . KEY_USER , "" ) ; conf . put ( JschProcessExecutor . KEY_HOST , "" ) ; conf . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) + "" ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , SshCommandScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; profile . newInstance ( ) ; } @ Test ( expected = IOException . class ) public void abnormal_exit ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( PhaseMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void script_missing ( ) throws Exception { File shell = putScript ( "" , "" ) ; Assume . assumeThat ( shell . delete ( ) , is ( true ) ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( shell . getAbsolutePath ( ) , "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void invaid_prefix ( ) throws Exception { File shell = putScript ( "" , "" ) ; CommandScript script = new CommandScript ( "" , set ( ) , "" , "" , Arrays . asList ( "" ) , map ( ) ) ; CommandScriptHandler handler = handler ( "" , shell . getAbsolutePath ( ) , "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } private CommandScriptHandler handler ( String ... keyValuePairs ) { Map < String , String > conf = map ( keyValuePairs ) ; conf . put ( JschProcessExecutor . KEY_USER , "" ) ; conf . put ( JschProcessExecutor . KEY_HOST , "" ) ; conf . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; ServiceProfile < CommandScriptHandler > profile = new ServiceProfile < CommandScriptHandler > ( "" , SshCommandScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; try { return profile . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . yaess . jsch ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . junit . Assume ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . VariableResolver ; import com . jcraft . jsch . JSchException ; public class JschProcessExecutorTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private File privateKey ; @ Before public void setUp ( ) throws Exception { File home = new File ( System . getProperty ( "" ) ) ; privateKey = new File ( home , "" ) . getCanonicalFile ( ) ; if ( privateKey . isFile ( ) == false ) { System . err . printf ( "" , privateKey ) ; Assume . assumeTrue ( false ) ; } if ( new File ( "" ) . canExecute ( ) == false ) { System . err . printf ( "" , "" ) ; Assume . assumeTrue ( false ) ; } } @ Test public void extract ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; assertThat ( extracted . getUser ( ) , is ( "" ) ) ; assertThat ( extracted . getHost ( ) , is ( "" ) ) ; assertThat ( extracted . getPort ( ) , is ( nullValue ( ) ) ) ; assertThat ( extracted . getPrivateKey ( ) , is ( privateKey . getAbsolutePath ( ) ) ) ; assertThat ( extracted . getPassPhrase ( ) , is ( nullValue ( ) ) ) ; } @ Test public void extract_with_port ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PORT , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; assertThat ( extracted . getUser ( ) , is ( "" ) ) ; assertThat ( extracted . getHost ( ) , is ( "" ) ) ; assertThat ( extracted . getPort ( ) , is ( ) ) ; assertThat ( extracted . getPrivateKey ( ) , is ( privateKey . getAbsolutePath ( ) ) ) ; assertThat ( extracted . getPassPhrase ( ) , is ( nullValue ( ) ) ) ; } @ Test public void extract_with_passphrase ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; config . put ( JschProcessExecutor . KEY_PASS_PHRASE , "" ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; assertThat ( extracted . getUser ( ) , is ( "" ) ) ; assertThat ( extracted . getHost ( ) , is ( "" ) ) ; assertThat ( extracted . getPort ( ) , is ( nullValue ( ) ) ) ; assertThat ( extracted . getPrivateKey ( ) , is ( privateKey . getAbsolutePath ( ) ) ) ; assertThat ( extracted . getPassPhrase ( ) , is ( "" ) ) ; } @ Test public void extract_variables ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , "" ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; variables . put ( "" , "" ) ; variables . put ( "" , "" ) ; variables . put ( "" , privateKey . getAbsolutePath ( ) ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; assertThat ( extracted . getUser ( ) , is ( "" ) ) ; assertThat ( extracted . getHost ( ) , is ( "" ) ) ; assertThat ( extracted . getPrivateKey ( ) , is ( privateKey . getAbsolutePath ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void extract_without_user ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor . extract ( "" , config , resolver ) ; } @ Test ( expected = IllegalArgumentException . class ) public void extract_without_host ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor . extract ( "" , config , resolver ) ; } @ Test ( expected = IllegalArgumentException . class ) public void extract_without_id ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor . extract ( "" , config , resolver ) ; } @ Test ( expected = IllegalArgumentException . class ) public void extract_invalid_variables ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor . extract ( "" , config , resolver ) ; } @ Test ( expected = IllegalArgumentException . class ) public void extract_invalid_port ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PORT , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor . extract ( "" , config , resolver ) ; } @ Test ( expected = JSchException . class ) public void extract_invalid_id ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) + "" ) ; Map < String , String > variables = new HashMap < String , String > ( ) ; VariableResolver resolver = new VariableResolver ( variables ) ; JschProcessExecutor . extract ( "" , config , resolver ) ; } @ Test public void execute ( ) throws Exception { File file = folder . newFile ( "" ) ; Assume . assumeTrue ( file . delete ( ) ) ; Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; VariableResolver resolver = VariableResolver . system ( ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; try { int exit = extracted . execute ( new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) ) , Arrays . asList ( "" , file . getAbsolutePath ( ) ) , Collections . < String , String > emptyMap ( ) ) ; assertThat ( exit , is ( ) ) ; } catch ( IOException e ) { System . err . printf ( "" ) ; Assume . assumeNoException ( e ) ; } assertThat ( file . exists ( ) , is ( true ) ) ; } @ Test public void execute_with_variables ( ) throws Exception { File file1 = folder . newFile ( "" ) ; Assume . assumeTrue ( file1 . delete ( ) ) ; File file2 = folder . newFile ( "" ) ; Assume . assumeTrue ( file2 . delete ( ) ) ; File script = folder . newFile ( "" ) ; PrintWriter writer = new PrintWriter ( script ) ; try { writer . print ( "" ) ; writer . print ( "" ) ; writer . print ( "" ) ; } finally { writer . close ( ) ; } script . setExecutable ( true ) ; Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; VariableResolver resolver = VariableResolver . system ( ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; try { Map < String , String > env = new HashMap < String , String > ( ) ; env . put ( "" , file1 . getAbsolutePath ( ) ) ; env . put ( "" , file2 . getAbsolutePath ( ) ) ; int exit = extracted . execute ( new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) ) , Arrays . asList ( script . getAbsolutePath ( ) ) , env ) ; assertThat ( exit , is ( ) ) ; } catch ( IOException e ) { System . err . printf ( "" ) ; e . printStackTrace ( ) ; Assume . assumeNoException ( e ) ; } assertThat ( file1 . exists ( ) , is ( true ) ) ; assertThat ( file2 . exists ( ) , is ( true ) ) ; } @ Test public void execute_missing ( ) throws Exception { Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; VariableResolver resolver = VariableResolver . system ( ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; try { int exit = extracted . execute ( new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) ) , Arrays . asList ( "" ) , Collections . < String , String > emptyMap ( ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } catch ( IOException e ) { System . err . printf ( "" ) ; Assume . assumeNoException ( e ) ; } } @ Test public void execute_metacharacter ( ) throws Exception { File file = folder . newFile ( "" ) ; Assume . assumeTrue ( file . delete ( ) ) ; Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; VariableResolver resolver = VariableResolver . system ( ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; try { int exit = extracted . execute ( new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) ) , Arrays . asList ( "" , file . getAbsolutePath ( ) ) , Collections . < String , String > emptyMap ( ) ) ; assertThat ( exit , is ( ) ) ; } catch ( IOException e ) { System . err . printf ( "" ) ; Assume . assumeNoException ( e ) ; } assertThat ( file . exists ( ) , is ( true ) ) ; } @ Test public void execute_metacharacter_variables ( ) throws Exception { File file = folder . newFile ( "" ) ; Assume . assumeTrue ( file . delete ( ) ) ; File script = folder . newFile ( "" ) ; PrintWriter writer = new PrintWriter ( script ) ; try { writer . print ( "" ) ; writer . print ( "" ) ; } finally { writer . close ( ) ; } script . setExecutable ( true ) ; Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( JschProcessExecutor . KEY_USER , "" ) ; config . put ( JschProcessExecutor . KEY_HOST , "" ) ; config . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; VariableResolver resolver = VariableResolver . system ( ) ; JschProcessExecutor extracted = JschProcessExecutor . extract ( "" , config , resolver ) ; try { Map < String , String > env = new HashMap < String , String > ( ) ; env . put ( "" , file . getAbsolutePath ( ) ) ; int exit = extracted . execute ( new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) ) , Arrays . asList ( script . getAbsolutePath ( ) ) , env ) ; assertThat ( exit , is ( ) ) ; } catch ( IOException e ) { System . err . printf ( "" ) ; e . printStackTrace ( ) ; Assume . assumeNoException ( e ) ; } assertThat ( file . exists ( ) , is ( true ) ) ; } } package com . asakusafw . yaess . jsch ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . yaess . basic . ProcessHadoopScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class SshHadoopScriptHandlerTest extends SshScriptHandlerTestRoot { @ Test public void simple ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( "" , "" , "" , "" ) ) ; execute ( context , script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results . subList ( , ) , is ( Arrays . asList ( "" , "" , "" , "" , context . getArgumentsAsString ( ) ) ) ) ; } @ Test public void properties ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( "" , "" , "" , "" ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" , "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; execute ( context , script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results . subList ( , ) , is ( Arrays . asList ( "" , "" , "" , "" , context . getArgumentsAsString ( ) ) ) ) ; List < String > rest = results . subList ( , results . size ( ) ) ; int hello = rest . indexOf ( "" ) ; assertThat ( hello , greaterThanOrEqualTo ( ) ) ; assertThat ( rest . get ( hello - ) , is ( "" ) ) ; int hoge = rest . indexOf ( "" ) ; assertThat ( hoge , greaterThanOrEqualTo ( ) ) ; assertThat ( rest . get ( hoge - ) , is ( "" ) ) ; int bar = rest . indexOf ( "" ) ; assertThat ( bar , greaterThanOrEqualTo ( ) ) ; assertThat ( rest . get ( bar - ) , is ( "" ) ) ; } @ Test public void complex_prefix ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" , "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( "" , "" , "" , "" ) ) ; execute ( context , script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results . subList ( , ) , is ( Arrays . asList ( "" , shell . getAbsolutePath ( ) , "" , "" , "" , "" , context . getArgumentsAsString ( ) ) ) ) ; } @ Test public void environment ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( "" , "" , "" , "" ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" , "" , "" ) ; execute ( script , handler ) ; List < String > results = getOutput ( shell ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; assertThat ( results , hasItem ( equalToIgnoringWhiteSpace ( "" ) ) ) ; } @ Test public void runtime_context ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; File shell = putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( "" , "" , "" , "" ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" , "" , "" ) ; RuntimeContext rc = RuntimeContext . DEFAULT . batchId ( "" ) . mode ( ExecutionMode . SIMULATION ) . buildId ( "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) , rc . unapply ( ) ) ; execute ( context , script , handler ) ; Map < String , String > map = new HashMap < String , String > ( ) ; for ( String line : getOutput ( shell ) ) { if ( line . trim ( ) . isEmpty ( ) ) { continue ; } String [ ] kv = line . split ( "" , ) ; if ( kv . length != ) { continue ; } map . put ( kv [ ] , kv [ ] ) ; } assertThat ( RuntimeContext . DEFAULT . apply ( map ) , is ( rc ) ) ; } @ Test ( expected = IOException . class ) public void missing_config ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; Map < String , String > conf = map ( ) ; conf . put ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; ServiceProfile < HadoopScriptHandler > profile = new ServiceProfile < HadoopScriptHandler > ( "" , SshHadoopScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; profile . newInstance ( ) ; } @ Test ( expected = IOException . class ) public void invalid_id ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; Map < String , String > conf = map ( ) ; conf . put ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; conf . put ( JschProcessExecutor . KEY_USER , "" ) ; conf . put ( JschProcessExecutor . KEY_HOST , "" ) ; conf . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) + "" ) ; ServiceProfile < HadoopScriptHandler > profile = new ServiceProfile < HadoopScriptHandler > ( "" , SshHadoopScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; profile . newInstance ( ) ; } @ Test ( expected = IOException . class ) public void home_missing ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( JschProcessExecutor . KEY_USER , "" , JschProcessExecutor . KEY_HOST , "" , JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void abnormal_exit ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void script_missing ( ) throws Exception { HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void invalid_prefix ( ) throws Exception { String target = new File ( getAsakusaHome ( ) , ProcessHadoopScriptHandler . PATH_EXECUTE ) . getAbsolutePath ( ) ; putScript ( "" , new File ( target ) ) ; HadoopScript script = new HadoopScript ( "" , set ( ) , "" , map ( ) , map ( ) ) ; HadoopScriptHandler handler = handler ( "" , getAsakusaHome ( ) . getAbsolutePath ( ) , "" , "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , map ( ) ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } private HadoopScriptHandler handler ( String ... keyValuePairs ) { Map < String , String > conf = map ( keyValuePairs ) ; conf . put ( JschProcessExecutor . KEY_USER , "" ) ; conf . put ( JschProcessExecutor . KEY_HOST , "" ) ; conf . put ( JschProcessExecutor . KEY_PRIVATE_KEY , privateKey . getAbsolutePath ( ) ) ; ServiceProfile < HadoopScriptHandler > profile = new ServiceProfile < HadoopScriptHandler > ( "" , SshHadoopScriptHandler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; try { return profile . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . yaess . jsch ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . yaess . basic . ProcessExecutor ; import com . asakusafw . yaess . basic . ProcessHadoopScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; import com . jcraft . jsch . JSchException ; public class SshHadoopScriptHandler extends ProcessHadoopScriptHandler { private volatile JschProcessExecutor executor ; @ Override protected void configureExtension ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { try { this . executor = JschProcessExecutor . extract ( profile . getPrefix ( ) , profile . getConfiguration ( ) , profile . getContext ( ) . getContextParameters ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) ) , e ) ; } catch ( JSchException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) ) , e ) ; } } @ Override protected ProcessExecutor getCommandExecutor ( ) { return executor ; } } package com . asakusafw . yaess . jsch ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import java . util . concurrent . TimeUnit ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . basic . ProcessExecutor ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . VariableResolver ; import com . asakusafw . yaess . core . YaessLogger ; import com . jcraft . jsch . ChannelExec ; import com . jcraft . jsch . JSch ; import com . jcraft . jsch . JSchException ; import com . jcraft . jsch . Session ; public class JschProcessExecutor implements ProcessExecutor { static final YaessLogger YSLOG = new YaessJschLogger ( JschProcessExecutor . class ) ; static final Logger LOG = LoggerFactory . getLogger ( JschProcessExecutor . class ) ; private static final String PREFIX = "" ; public static final String KEY_USER = PREFIX + "" ; public static final String KEY_HOST = PREFIX + "" ; public static final String KEY_PORT = PREFIX + "" ; public static final String KEY_PRIVATE_KEY = PREFIX + "" ; public static final String KEY_PASS_PHRASE = PREFIX + "" ; private static final Pattern SH_NAME = Pattern . compile ( "" ) ; private static final Pattern SH_METACHARACTERS = Pattern . compile ( "" ) ; private final String user ; private final String host ; private final Integer port ; private final String privateKey ; private final String passPhrase ; private final JSch jsch ; public JschProcessExecutor ( String user , String host , Integer portOrNull , String privateKeyPath , String passPhraseOrNull ) throws JSchException { if ( user == null ) { throw new IllegalArgumentException ( "" ) ; } if ( host == null ) { throw new IllegalArgumentException ( "" ) ; } if ( privateKeyPath == null ) { throw new IllegalArgumentException ( "" ) ; } this . user = user ; this . host = host ; this . port = portOrNull ; this . jsch = new JSch ( ) ; this . privateKey = privateKeyPath ; this . passPhrase = passPhraseOrNull ; jsch . addIdentity ( privateKeyPath , passPhraseOrNull ) ; } public String getUser ( ) { return user ; } public String getHost ( ) { return host ; } public Integer getPort ( ) { return port ; } public String getPrivateKey ( ) { return privateKey ; } public String getPassPhrase ( ) { return passPhrase ; } public static JschProcessExecutor extract ( String servicePrefix , Map < String , String > configuration , VariableResolver variables ) throws JSchException { if ( servicePrefix == null ) { throw new IllegalArgumentException ( "" ) ; } if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( variables == null ) { throw new IllegalArgumentException ( "" ) ; } String user = extract ( KEY_USER , servicePrefix , configuration , variables , true ) ; String host = extract ( KEY_HOST , servicePrefix , configuration , variables , true ) ; String portString = extract ( KEY_PORT , servicePrefix , configuration , variables , false ) ; String privateKey = extract ( KEY_PRIVATE_KEY , servicePrefix , configuration , variables , false ) ; String passPhrase = extract ( KEY_PASS_PHRASE , servicePrefix , configuration , variables , false ) ; Integer port = null ; if ( portString != null ) { try { port = Integer . valueOf ( portString ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , servicePrefix + '' + KEY_PORT , portString ) ) ; } } return new JschProcessExecutor ( user , host , port , privateKey , passPhrase ) ; } private static String extract ( String key , String prefix , Map < String , String > configuration , VariableResolver variables , boolean mandatory ) { assert key != null ; assert prefix != null ; assert configuration != null ; assert variables != null ; String value = configuration . get ( key ) ; if ( value == null ) { if ( mandatory ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix + '' + key ) ) ; } else { return null ; } } try { return variables . replace ( value , true ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix + '' + key , value ) ) ; } } @ Override public int execute ( ExecutionContext context , List < String > commandLineTokens , Map < String , String > environmentVariables ) throws InterruptedException , IOException { return execute ( context , commandLineTokens , environmentVariables , System . out ) ; } @ Override public int execute ( ExecutionContext context , List < String > commandLineTokens , Map < String , String > environmentVariables , OutputStream output ) throws InterruptedException , IOException { try { return execute0 ( context , commandLineTokens , environmentVariables , output ) ; } catch ( JSchException e ) { throw new IOException ( MessageFormat . format ( "" , user , host , String . valueOf ( port ) ) , e ) ; } } private int execute0 ( ExecutionContext context , List < String > commandLineTokens , Map < String , String > environmentVariables , OutputStream output ) throws JSchException , InterruptedException { assert context != null ; assert commandLineTokens != null ; assert environmentVariables != null ; assert output != null ; Session session = jsch . getSession ( user , host ) ; if ( port != null ) { session . setPort ( port ) ; } session . setConfig ( "" , "" ) ; session . setServerAliveInterval ( ( int ) TimeUnit . SECONDS . toMillis ( ) ) ; try { YSLOG . info ( "" , user , host , port , privateKey ) ; long sessionStart = System . currentTimeMillis ( ) ; session . connect ( ( int ) TimeUnit . SECONDS . toMillis ( ) ) ; long sessionEnd = System . currentTimeMillis ( ) ; YSLOG . info ( "" , user , host , port , privateKey , sessionEnd - sessionStart ) ; int exitStatus ; try { ChannelExec channel = ( ChannelExec ) session . openChannel ( "" ) ; channel . setCommand ( buildCommand ( commandLineTokens , environmentVariables ) ) ; channel . setInputStream ( new ByteArrayInputStream ( new byte [ ] ) , true ) ; channel . setOutputStream ( output , true ) ; channel . setErrStream ( output , true ) ; YSLOG . info ( "" , user , host , port , privateKey , commandLineTokens . get ( ) ) ; long channelStart = System . currentTimeMillis ( ) ; channel . connect ( ( int ) TimeUnit . SECONDS . toMillis ( ) ) ; long channelEnd = System . currentTimeMillis ( ) ; YSLOG . info ( "" , user , host , port , privateKey , commandLineTokens . get ( ) , channelEnd - channelStart ) ; try { while ( true ) { if ( channel . isClosed ( ) ) { break ; } Thread . sleep ( ) ; } exitStatus = channel . getExitStatus ( ) ; } finally { channel . disconnect ( ) ; } } finally { session . disconnect ( ) ; } YSLOG . info ( "" , user , host , port , privateKey , commandLineTokens . get ( ) , exitStatus ) ; return exitStatus ; } catch ( JSchException e ) { YSLOG . error ( e , "" , user , host , port , privateKey ) ; throw e ; } } private String buildCommand ( List < String > commandLineTokens , Map < String , String > environmentVariables ) { assert commandLineTokens != null ; assert environmentVariables != null ; StringBuilder buf = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : environmentVariables . entrySet ( ) ) { if ( SH_NAME . matcher ( entry . getKey ( ) ) . matches ( ) == false ) { YSLOG . warn ( "" , entry . getKey ( ) , entry . getValue ( ) ) ; continue ; } if ( buf . length ( ) > ) { buf . append ( '' ) ; } buf . append ( entry . getKey ( ) ) ; String replaced = SH_METACHARACTERS . matcher ( entry . getValue ( ) ) . replaceAll ( "" ) ; buf . append ( '' ) ; buf . append ( '' ) ; buf . append ( replaced ) ; buf . append ( '' ) ; } for ( String token : commandLineTokens ) { if ( buf . length ( ) > ) { buf . append ( '' ) ; } String replaced = SH_METACHARACTERS . matcher ( token ) . replaceAll ( "" ) ; buf . append ( '' ) ; buf . append ( replaced ) ; buf . append ( '' ) ; } return buf . toString ( ) ; } } package com . asakusafw . yaess . jsch ; package com . asakusafw . yaess . jsch ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . yaess . core . YaessLogger ; public class YaessJschLogger extends YaessLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public YaessJschLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . yaess . jsch ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . yaess . basic . ProcessCommandScriptHandler ; import com . asakusafw . yaess . basic . ProcessExecutor ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; import com . jcraft . jsch . JSchException ; public class SshCommandScriptHandler extends ProcessCommandScriptHandler { private volatile JschProcessExecutor executor ; @ Override protected void configureExtension ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { try { this . executor = JschProcessExecutor . extract ( profile . getPrefix ( ) , profile . getConfiguration ( ) , profile . getContext ( ) . getContextParameters ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) ) , e ) ; } catch ( JSchException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) ) , e ) ; } } @ Override protected ProcessExecutor getCommandExecutor ( ) { return executor ; } } package com . asakusafw . yaess . jobqueue . client ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . InetSocketAddress ; import java . net . URL ; import java . util . HashMap ; import org . apache . http . HttpEntity ; import org . apache . http . HttpEntityEnclosingRequest ; import org . apache . http . HttpException ; import org . apache . http . HttpRequest ; import org . apache . http . HttpResponse ; import org . apache . http . HttpStatus ; import org . apache . http . entity . StringEntity ; import org . apache . http . localserver . LocalTestServer ; import org . apache . http . localserver . RequestBasicAuth ; import org . apache . http . localserver . ResponseBasicUnauthorized ; import org . apache . http . protocol . BasicHttpProcessor ; import org . apache . http . protocol . HttpContext ; import org . apache . http . protocol . HttpRequestHandler ; import org . apache . http . protocol . ResponseConnControl ; import org . apache . http . protocol . ResponseContent ; import org . apache . http . protocol . ResponseDate ; import org . apache . http . protocol . ResponseServer ; import org . apache . http . util . EntityUtils ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . google . gson . Gson ; import com . google . gson . JsonElement ; import com . google . gson . JsonObject ; import com . google . gson . JsonParser ; public class HttpJobClientTest { static final Logger LOG = LoggerFactory . getLogger ( HttpJobClientTest . class ) ; private LocalTestServer server ; private String baseUrl ; @ Before public void setUp ( ) throws Exception { BasicHttpProcessor proc = new BasicHttpProcessor ( ) ; proc . addInterceptor ( new ResponseDate ( ) ) ; proc . addInterceptor ( new ResponseServer ( ) ) ; proc . addInterceptor ( new ResponseContent ( ) ) ; proc . addInterceptor ( new ResponseConnControl ( ) ) ; proc . addInterceptor ( new RequestBasicAuth ( ) ) ; proc . addInterceptor ( new ResponseBasicUnauthorized ( ) ) ; server = new LocalTestServer ( proc , null ) ; server . start ( ) ; InetSocketAddress address = server . getServiceAddress ( ) ; baseUrl = new URL ( "" , address . getHostName ( ) , address . getPort ( ) , "" ) . toExternalForm ( ) ; } @ After public void tearDown ( ) throws Exception { server . stop ( ) ; } @ Test public void register ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobScript script = new JobScript ( ) ; script . setBatchId ( "" ) ; script . setFlowId ( "" ) ; script . setExecutionId ( "" ) ; script . setPhase ( ExecutionPhase . MAIN ) ; script . setStageId ( "" ) ; script . setMainClassName ( "" ) ; script . setProperties ( new HashMap < String , String > ( ) ) ; script . setEnvironmentVariables ( new HashMap < String , String > ( ) ) ; JobId id = client . register ( script ) ; assertThat ( id , is ( new JobId ( "" ) ) ) ; assertThat ( handler . requestElement , is ( notNullValue ( ) ) ) ; JsonObject object = handler . requestElement ; assertThat ( object . get ( "" ) . getAsString ( ) , is ( "" ) ) ; assertThat ( object . get ( "" ) . getAsString ( ) , is ( "" ) ) ; assertThat ( object . get ( "" ) . getAsString ( ) , is ( "" ) ) ; assertThat ( object . get ( "" ) . getAsString ( ) , is ( "" ) ) ; assertThat ( object . get ( "" ) . getAsString ( ) , is ( "" ) ) ; assertThat ( object . get ( "" ) . isJsonObject ( ) , is ( true ) ) ; assertThat ( object . get ( "" ) . isJsonObject ( ) , is ( true ) ) ; } @ Test public void register_error ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobScript script = new JobScript ( ) ; script . setBatchId ( "" ) ; script . setFlowId ( "" ) ; script . setPhase ( ExecutionPhase . MAIN ) ; script . setStageId ( "" ) ; script . setExecutionId ( "" ) ; script . setMainClassName ( "" ) ; script . setProperties ( new HashMap < String , String > ( ) ) ; script . setEnvironmentVariables ( new HashMap < String , String > ( ) ) ; try { client . register ( script ) ; fail ( ) ; } catch ( IOException e ) { LOG . debug ( "" , e ) ; } assertThat ( handler . requestElement , is ( notNullValue ( ) ) ) ; } @ Test public void register_missing ( ) throws Exception { ErrorHandler handler = new ErrorHandler ( , null ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobScript script = new JobScript ( ) ; script . setBatchId ( "" ) ; script . setFlowId ( "" ) ; script . setPhase ( ExecutionPhase . MAIN ) ; script . setStageId ( "" ) ; script . setExecutionId ( "" ) ; script . setMainClassName ( "" ) ; script . setProperties ( new HashMap < String , String > ( ) ) ; script . setEnvironmentVariables ( new HashMap < String , String > ( ) ) ; try { client . register ( script ) ; fail ( ) ; } catch ( IOException e ) { LOG . debug ( "" , e ) ; } assertThat ( handler . requestElement , is ( notNullValue ( ) ) ) ; } @ Test public void register_no_connections ( ) throws Exception { server . stop ( ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobScript script = new JobScript ( ) ; script . setBatchId ( "" ) ; script . setFlowId ( "" ) ; script . setPhase ( ExecutionPhase . MAIN ) ; script . setStageId ( "" ) ; script . setExecutionId ( "" ) ; script . setMainClassName ( "" ) ; script . setProperties ( new HashMap < String , String > ( ) ) ; script . setEnvironmentVariables ( new HashMap < String , String > ( ) ) ; try { client . register ( script ) ; fail ( ) ; } catch ( IOException e ) { LOG . debug ( "" , e ) ; } } @ Test public void register_auth ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , new AuthHandler ( handler ) ) ; HttpJobClient client = new HttpJobClient ( baseUrl , "" , "" ) ; JobScript script = new JobScript ( ) ; script . setBatchId ( "" ) ; script . setFlowId ( "" ) ; script . setExecutionId ( "" ) ; script . setPhase ( ExecutionPhase . MAIN ) ; script . setStageId ( "" ) ; script . setMainClassName ( "" ) ; script . setProperties ( new HashMap < String , String > ( ) ) ; script . setEnvironmentVariables ( new HashMap < String , String > ( ) ) ; client . register ( script ) ; } @ Test public void register_unauth ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , new AuthHandler ( handler ) ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobScript script = new JobScript ( ) ; script . setBatchId ( "" ) ; script . setFlowId ( "" ) ; script . setExecutionId ( "" ) ; script . setPhase ( ExecutionPhase . MAIN ) ; script . setStageId ( "" ) ; script . setMainClassName ( "" ) ; script . setProperties ( new HashMap < String , String > ( ) ) ; script . setEnvironmentVariables ( new HashMap < String , String > ( ) ) ; try { client . register ( script ) ; fail ( ) ; } catch ( IOException e ) { LOG . debug ( "" , e ) ; } } @ Test public void status_initialized ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobStatus status = client . getStatus ( new JobId ( "" ) ) ; assertThat ( status . getKind ( ) , is ( JobStatus . Kind . INITIALIZED ) ) ; assertThat ( handler . requestElement , is ( nullValue ( ) ) ) ; } @ Test public void status_waiting ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobStatus status = client . getStatus ( new JobId ( "" ) ) ; assertThat ( status . getKind ( ) , is ( JobStatus . Kind . WAITING ) ) ; assertThat ( handler . requestElement , is ( nullValue ( ) ) ) ; } @ Test public void status_running ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobStatus status = client . getStatus ( new JobId ( "" ) ) ; assertThat ( status . getKind ( ) , is ( JobStatus . Kind . RUNNING ) ) ; assertThat ( handler . requestElement , is ( nullValue ( ) ) ) ; } @ Test public void status_completed ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobStatus status = client . getStatus ( new JobId ( "" ) ) ; assertThat ( status . getKind ( ) , is ( JobStatus . Kind . COMPLETED ) ) ; assertThat ( status . getExitCode ( ) , is ( Integer . valueOf ( ) ) ) ; assertThat ( handler . requestElement , is ( nullValue ( ) ) ) ; } @ Test public void status_error ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; JobStatus status = client . getStatus ( new JobId ( "" ) ) ; assertThat ( status . getKind ( ) , is ( JobStatus . Kind . ERROR ) ) ; assertThat ( handler . requestElement , is ( nullValue ( ) ) ) ; } @ Test public void status_missing ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; try { client . getStatus ( new JobId ( "" ) ) ; fail ( ) ; } catch ( IOException e ) { } } @ Test public void submit ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; client . submit ( new JobId ( "" ) ) ; assertThat ( handler . requestElement , is ( nullValue ( ) ) ) ; } @ Test public void submit_error ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; try { client . submit ( new JobId ( "" ) ) ; fail ( ) ; } catch ( IOException e ) { } assertThat ( handler . requestElement , is ( nullValue ( ) ) ) ; } @ Test public void submit_missing ( ) throws Exception { JsonObject result = new JsonObject ( ) ; result . addProperty ( "" , "" ) ; result . addProperty ( "" , "" ) ; JsonHandler handler = new JsonHandler ( result ) ; server . register ( "" , handler ) ; HttpJobClient client = new HttpJobClient ( baseUrl ) ; try { client . submit ( new JobId ( "" ) ) ; fail ( ) ; } catch ( IOException e ) { } assertThat ( handler . requestElement , is ( nullValue ( ) ) ) ; } static JsonElement parse ( String content ) { return new JsonParser ( ) . parse ( content ) ; } private static class JsonHandler implements HttpRequestHandler { final JsonElement responseElement ; volatile JsonObject requestElement ; public JsonHandler ( JsonElement element ) { this . responseElement = element ; } @ Override public void handle ( HttpRequest request , HttpResponse response , HttpContext context ) throws HttpException , IOException { response . setStatusCode ( ) ; response . setEntity ( new StringEntity ( new Gson ( ) . toJson ( responseElement ) . toString ( ) , HttpJobClient . CONTENT_TYPE ) ) ; if ( request instanceof HttpEntityEnclosingRequest ) { HttpEntity entity = ( ( HttpEntityEnclosingRequest ) request ) . getEntity ( ) ; String content = EntityUtils . toString ( entity , "" ) ; JsonElement element = parse ( content ) ; if ( element instanceof JsonObject ) { requestElement = ( JsonObject ) element ; } } } } private static class AuthHandler implements HttpRequestHandler { private final HttpRequestHandler delegate ; public AuthHandler ( HttpRequestHandler delegate ) { this . delegate = delegate ; } @ Override public void handle ( HttpRequest request , HttpResponse response , HttpContext context ) throws HttpException , IOException { String credentials = ( String ) context . getAttribute ( "" ) ; if ( credentials == null || credentials . equals ( "" ) == false ) { response . setStatusCode ( HttpStatus . SC_UNAUTHORIZED ) ; } else { delegate . handle ( request , response , context ) ; } } } private static class ErrorHandler implements HttpRequestHandler { private final int status ; private final String code ; volatile JsonObject requestElement ; public ErrorHandler ( int status , String code ) { this . status = status ; this . code = code ; } @ Override public void handle ( HttpRequest request , HttpResponse response , HttpContext context ) throws HttpException , IOException { response . setStatusCode ( status ) ; if ( code != null ) { JsonObject object = new JsonObject ( ) ; object . addProperty ( "" , code ) ; object . addProperty ( "" , code ) ; response . setEntity ( new StringEntity ( new Gson ( ) . toJson ( object ) . toString ( ) , HttpJobClient . CONTENT_TYPE ) ) ; } if ( request instanceof HttpEntityEnclosingRequest ) { HttpEntity entity = ( ( HttpEntityEnclosingRequest ) request ) . getEntity ( ) ; String content = EntityUtils . toString ( entity , "" ) ; JsonElement element = parse ( content ) ; if ( element instanceof JsonObject ) { requestElement = ( JsonObject ) element ; } } } } } package com . asakusafw . yaess . jobqueue ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . junit . Test ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . VariableResolver ; import com . asakusafw . yaess . jobqueue . client . HttpJobClient ; import com . asakusafw . yaess . jobqueue . client . JobClient ; public class JobClientProfileTest { @ Test public void convert ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { "" , "" } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile profile = JobClientProfile . convert ( original ) ; assertThat ( profile . getPrefix ( ) , is ( "" ) ) ; assertThat ( profile . getTimeout ( ) , is ( JobClientProfile . DEFAULT_TIMEOUT ) ) ; assertThat ( profile . getPollingInterval ( ) , is ( JobClientProfile . DEFAULT_POLLING_INTERVAL ) ) ; List < JobClient > clients = profile . getClients ( ) ; assertThat ( clients . size ( ) , is ( ) ) ; assertThat ( clients . get ( ) , is ( HttpJobClient . class ) ) ; HttpJobClient c0 = ( HttpJobClient ) clients . get ( ) ; assertThat ( c0 . getBaseUri ( ) , is ( "" ) ) ; assertThat ( c0 . getUser ( ) , is ( nullValue ( ) ) ) ; } @ Test public void convert_explicit ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { JobClientProfile . KEY_TIMEOUT , String . valueOf ( JobClientProfile . DEFAULT_TIMEOUT + ) , JobClientProfile . KEY_POLLING_INTERVAL , String . valueOf ( JobClientProfile . DEFAULT_POLLING_INTERVAL + ) , "" , "" , "" , "" , "" , "" , "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile profile = JobClientProfile . convert ( original ) ; assertThat ( profile . getPrefix ( ) , is ( "" ) ) ; assertThat ( profile . getTimeout ( ) , is ( JobClientProfile . DEFAULT_TIMEOUT + ) ) ; assertThat ( profile . getPollingInterval ( ) , is ( JobClientProfile . DEFAULT_POLLING_INTERVAL + ) ) ; List < JobClient > clients = profile . getClients ( ) ; assertThat ( clients . size ( ) , is ( ) ) ; assertThat ( clients . get ( ) , is ( HttpJobClient . class ) ) ; assertThat ( clients . get ( ) , is ( HttpJobClient . class ) ) ; HttpJobClient c0 = ( HttpJobClient ) clients . get ( ) ; assertThat ( c0 . getBaseUri ( ) , is ( "" ) ) ; assertThat ( c0 . getUser ( ) , is ( nullValue ( ) ) ) ; HttpJobClient c1 = ( HttpJobClient ) clients . get ( ) ; assertThat ( c1 . getBaseUri ( ) , is ( "" ) ) ; assertThat ( c1 . getUser ( ) , is ( "" ) ) ; } @ Test public void convert_resolve ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { JobClientProfile . KEY_TIMEOUT , "" , JobClientProfile . KEY_POLLING_INTERVAL , "" , "" , "" , "" , "" , "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , } ) ) ) ) ; JobClientProfile profile = JobClientProfile . convert ( original ) ; assertThat ( profile . getTimeout ( ) , is ( ) ) ; assertThat ( profile . getPollingInterval ( ) , is ( ) ) ; List < JobClient > clients = profile . getClients ( ) ; assertThat ( clients . size ( ) , is ( ) ) ; assertThat ( clients . get ( ) , is ( HttpJobClient . class ) ) ; HttpJobClient c0 = ( HttpJobClient ) clients . get ( ) ; assertThat ( c0 . getBaseUri ( ) , is ( "" ) ) ; assertThat ( c0 . getUser ( ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_malform_timeout ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { JobClientProfile . KEY_TIMEOUT , "" , "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile . convert ( original ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_invalid_timeout ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { JobClientProfile . KEY_TIMEOUT , "" , "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile . convert ( original ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_malform_interval ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { JobClientProfile . KEY_POLLING_INTERVAL , "" , "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile . convert ( original ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_invalid_interval ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { JobClientProfile . KEY_POLLING_INTERVAL , "" , "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile . convert ( original ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_missing_client ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile . convert ( original ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_missing_client_url ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile . convert ( original ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_invalid_client_prefix ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile . convert ( original ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_unresolved ( ) throws Exception { ServiceProfile < ? > original = new ServiceProfile < HadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( new String [ ] { "" , "" , } ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( new String [ ] { } ) ) ) ) ; JobClientProfile . convert ( original ) ; } private Map < String , String > map ( String [ ] keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > results = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length ; i += ) { results . put ( keyValuePairs [ i + ] , keyValuePairs [ i + ] ) ; } return results ; } } package com . asakusafw . yaess . jobqueue ; import static com . asakusafw . yaess . jobqueue . client . JobStatus . Kind . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . concurrent . ConcurrentHashMap ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . VariableResolver ; import com . asakusafw . yaess . jobqueue . client . JobClient ; import com . asakusafw . yaess . jobqueue . client . JobId ; import com . asakusafw . yaess . jobqueue . client . JobScript ; import com . asakusafw . yaess . jobqueue . client . JobStatus ; public class QueueHadoopScriptHandlerTest { @ Test public void execute ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" , COMPLETED ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; JobScript js = c1 . registered . get ( "" ) ; assertThat ( js , is ( notNullValue ( ) ) ) ; assertThat ( js . getBatchId ( ) , is ( context . getBatchId ( ) ) ) ; assertThat ( js . getFlowId ( ) , is ( context . getFlowId ( ) ) ) ; assertThat ( js . getExecutionId ( ) , is ( context . getExecutionId ( ) ) ) ; assertThat ( js . getPhase ( ) , is ( context . getPhase ( ) ) ) ; assertThat ( js . getStageId ( ) , is ( script . getId ( ) ) ) ; assertThat ( js . getMainClassName ( ) , is ( script . getClassName ( ) ) ) ; assertThat ( js . getArguments ( ) , is ( context . getArguments ( ) ) ) ; Map < String , String > properties = new HashMap < String , String > ( ) ; properties . putAll ( map ( "" , "" ) ) ; properties . putAll ( script . getHadoopProperties ( ) ) ; assertThat ( js . getProperties ( ) , is ( properties ) ) ; assertThat ( js . getEnvironmentVariables ( ) , is ( script . getEnvironmentVariables ( ) ) ) ; } @ Test public void execute_step ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" , WAITING , RUNNING , COMPLETED ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void execute_fail ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" ) ; JobStatus fail = new JobStatus ( ) ; fail . setKind ( COMPLETED ) ; fail . setExitCode ( ) ; c1 . add ( fail ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void execute_error ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" , ERROR ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void execute_aborted ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void execute_register_failed ( ) throws Exception { MockJobClient c1 = new MockJobClient ( null , COMPLETED ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; } @ Test ( expected = IOException . class ) public void execute_register_failover ( ) throws Exception { MockJobClient c1 = new MockJobClient ( null , ERROR ) ; MockJobClient c2 = new MockJobClient ( "" , COMPLETED ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; assertThat ( c2 . count , is ( greaterThan ( ) ) ) ; } @ Test ( expected = IOException . class ) public void execute_register_timeout ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" , ERROR ) { @ Override public JobId register ( JobScript script ) throws IOException , InterruptedException { Thread . sleep ( ) ; return super . register ( script ) ; } } ; MockJobClient c2 = new MockJobClient ( "" , COMPLETED ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; assertThat ( c2 . count , is ( greaterThan ( ) ) ) ; } @ Test ( expected = IOException . class ) public void execute_round ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" , COMPLETED ) ; MockJobClient c2 = new MockJobClient ( "" , COMPLETED ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; assertThat ( c1 . count , is ( greaterThan ( ) ) ) ; assertThat ( c2 . count , is ( greaterThan ( ) ) ) ; } @ Test public void execute_runtime_context ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" , COMPLETED ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; RuntimeContext rc = RuntimeContext . DEFAULT . batchId ( "" ) . mode ( ExecutionMode . SIMULATION ) . buildId ( "" ) ; ExecutionContext context = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) , rc . unapply ( ) ) ; HadoopScript script = script ( ) ; handler . execute ( ExecutionMonitor . NULL , context , script ) ; JobScript js = c1 . registered . get ( "" ) ; assertThat ( RuntimeContext . DEFAULT . apply ( js . getEnvironmentVariables ( ) ) , is ( rc ) ) ; } @ Test public void cleanup ( ) throws Exception { MockJobClient c1 = new MockJobClient ( "" , COMPLETED ) ; JobClientProfile profile = new JobClientProfile ( "" , list ( c1 ) , , ) ; QueueHadoopScriptHandler handler = create ( ) ; handler . doConfigure ( profile ) ; ExecutionContext context = context ( ) ; handler . cleanUp ( ExecutionMonitor . NULL , context ) ; JobScript js = c1 . registered . get ( "" ) ; assertThat ( js , is ( notNullValue ( ) ) ) ; assertThat ( js . getBatchId ( ) , is ( context . getBatchId ( ) ) ) ; assertThat ( js . getFlowId ( ) , is ( context . getFlowId ( ) ) ) ; assertThat ( js . getExecutionId ( ) , is ( context . getExecutionId ( ) ) ) ; assertThat ( js . getPhase ( ) , is ( context . getPhase ( ) ) ) ; assertThat ( js . getMainClassName ( ) , is ( QueueHadoopScriptHandler . CLEANUP_STAGE_CLASS ) ) ; assertThat ( js . getArguments ( ) , is ( context . getArguments ( ) ) ) ; Map < String , String > properties = new HashMap < String , String > ( ) ; properties . putAll ( map ( "" , "" ) ) ; assertThat ( js . getProperties ( ) , is ( properties ) ) ; } QueueHadoopScriptHandler create ( ) { ServiceProfile < QueueHadoopScriptHandler > profile = new ServiceProfile < QueueHadoopScriptHandler > ( "" , QueueHadoopScriptHandler . class , map ( "" , "" , "" , "" ) , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( map ( ) ) ) ) ; try { return profile . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private HadoopScript script ( ) { Map < String , String > prop = new HashMap < String , String > ( ) ; prop . put ( "" , "" ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . put ( "" , "" ) ; return new HadoopScript ( "" , Collections . < String > emptySet ( ) , "" , prop , env ) ; } private ExecutionContext context ( ) { Map < String , String > args = new HashMap < String , String > ( ) ; args . put ( "" , "" ) ; return new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , args ) ; } private < T > List < T > list ( T ... values ) { return Arrays . asList ( values ) ; } private Map < String , String > map ( String ... keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > results = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length ; i += ) { results . put ( keyValuePairs [ i + ] , keyValuePairs [ i + ] ) ; } return results ; } private static class MockJobClient implements JobClient { volatile int count ; final Map < String , JobScript > registered = new ConcurrentHashMap < String , JobScript > ( ) ; private final JobId jobId ; private final LinkedList < JobStatus > sequence ; private volatile boolean submitted ; public MockJobClient ( String id , JobStatus . Kind ... sequence ) { this . jobId = id == null ? null : new JobId ( id ) ; this . sequence = new LinkedList < JobStatus > ( ) ; for ( JobStatus . Kind kind : sequence ) { JobStatus result = new JobStatus ( ) ; result . setKind ( kind ) ; result . setJobId ( id == null ? "" : id ) ; result . setExitCode ( ) ; this . sequence . addLast ( result ) ; } } void add ( JobStatus status ) { sequence . add ( status ) ; } @ Override public JobId register ( JobScript script ) throws IOException , InterruptedException { count ++ ; if ( jobId == null ) { throw new IOException ( ) ; } registered . put ( jobId . getToken ( ) , script ) ; return jobId ; } @ Override public void submit ( JobId id ) throws IOException , InterruptedException { assertThat ( id , is ( jobId ) ) ; submitted = true ; } @ Override public JobStatus getStatus ( JobId id ) throws IOException , InterruptedException { assertThat ( id , is ( jobId ) ) ; if ( submitted == false ) { throw new IOException ( ) ; } if ( sequence . isEmpty ( ) ) { throw new IOException ( ) ; } JobStatus status = sequence . removeFirst ( ) ; return status ; } } } package com . asakusafw . yaess . jobqueue ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . util . PropertiesUtil ; import com . asakusafw . yaess . jobqueue . client . HttpJobClient ; import com . asakusafw . yaess . jobqueue . client . JobClient ; public class JobClientProfile { static final Logger LOG = LoggerFactory . getLogger ( JobClientProfile . class ) ; static final String KEY_TIMEOUT = "" ; static final String KEY_POLLING_INTERVAL = "" ; static final Pattern PATTERN_COMPONENT = Pattern . compile ( "" ) ; static final String KEY_URL = "" ; static final String KEY_USER = "" ; static final String KEY_PASSWORD = "" ; static final long DEFAULT_TIMEOUT = ; static final long DEFAULT_POLLING_INTERVAL = ; private final String prefix ; private final List < JobClient > clients ; private final long timeout ; private final long pollingInterval ; public JobClientProfile ( String prefix , List < ? extends JobClient > clients , long timeout , long pollingInterval ) { if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } if ( clients == null ) { throw new IllegalArgumentException ( "" ) ; } if ( clients . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } if ( timeout < ) { throw new IllegalArgumentException ( "" ) ; } if ( pollingInterval <= ) { throw new IllegalArgumentException ( "" ) ; } this . prefix = prefix ; this . clients = Collections . unmodifiableList ( new ArrayList < JobClient > ( clients ) ) ; this . timeout = timeout ; this . pollingInterval = pollingInterval ; } public String getPrefix ( ) { return prefix ; } public List < JobClient > getClients ( ) { return clients ; } public long getTimeout ( ) { return timeout ; } public long getPollingInterval ( ) { return pollingInterval ; } public static JobClientProfile convert ( ServiceProfile < ? > profile ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } Map < String , String > conf = new HashMap < String , String > ( profile . getConfiguration ( ) ) ; conf . remove ( ExecutionScriptHandler . KEY_RESOURCE ) ; removeKeyPrefix ( conf , ExecutionScriptHandler . KEY_PROP_PREFIX ) ; long timeout = extractLong ( profile , conf , KEY_TIMEOUT , DEFAULT_TIMEOUT ) ; if ( timeout <= ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , KEY_TIMEOUT , timeout ) ) ; } long pollingInterval = extractLong ( profile , conf , KEY_POLLING_INTERVAL , DEFAULT_POLLING_INTERVAL ) ; if ( pollingInterval <= ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , KEY_TIMEOUT , pollingInterval ) ) ; } List < JobClient > clients = extractClients ( profile , conf ) ; if ( clients . isEmpty ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) ) ) ; } return new JobClientProfile ( profile . getPrefix ( ) , clients , timeout , pollingInterval ) ; } private static long extractLong ( ServiceProfile < ? > profile , Map < String , String > conf , String key , long defaultValue ) { assert profile != null ; assert conf != null ; assert key != null ; String value = profile . normalize ( key , conf . remove ( key ) , false , true ) ; if ( value == null ) { return defaultValue ; } try { return Long . parseLong ( value ) ; } catch ( RuntimeException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , key , value ) ) ; } } private static List < JobClient > extractClients ( ServiceProfile < ? > profile , Map < String , String > conf ) { assert profile != null ; Set < String > keys = PropertiesUtil . getChildKeys ( conf , "" , "" ) ; Map < Integer , JobClient > results = new TreeMap < Integer , JobClient > ( ) ; for ( String key : keys ) { if ( isClientPrefix ( key ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , key ) ) ; } int number = Integer . parseInt ( key ) ; Map < String , String > subconf = PropertiesUtil . createPrefixMap ( conf , key + "" ) ; String prefix = profile . getPrefix ( ) + "" + key ; String url = resolve ( profile , subconf , prefix , KEY_URL ) ; if ( url == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , prefix , KEY_URL ) ) ; } String user = resolve ( profile , subconf , prefix , KEY_USER ) ; String password = resolve ( profile , subconf , prefix , KEY_PASSWORD ) ; if ( user == null || user . isEmpty ( ) ) { results . put ( number , new HttpJobClient ( url ) ) ; } else { password = password == null ? "" : password ; results . put ( number , new HttpJobClient ( url , user , password ) ) ; } } return new ArrayList < JobClient > ( results . values ( ) ) ; } private static String resolve ( ServiceProfile < ? > profile , Map < String , String > conf , String prefix , String key ) { assert profile != null ; assert conf != null ; assert prefix != null ; assert key != null ; String value = conf . get ( key ) ; if ( value == null ) { return null ; } return resolve ( profile , prefix + "" + key , value ) ; } private static String resolve ( ServiceProfile < ? > profile , String key , String value ) { assert profile != null ; assert key != null ; assert value != null ; try { return profile . getContext ( ) . getContextParameters ( ) . replace ( value , true ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , key , value ) , e ) ; } } private static boolean isClientPrefix ( String key ) { assert key != null ; return PATTERN_COMPONENT . matcher ( key ) . matches ( ) ; } private static void removeKeyPrefix ( Map < ? , ? > properties , String prefix ) { assert properties != null ; assert prefix != null ; for ( Iterator < ? > iter = properties . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Object key = iter . next ( ) ; if ( ( key instanceof String ) == false ) { continue ; } String name = ( String ) key ; if ( name . startsWith ( prefix ) ) { iter . remove ( ) ; } } } } package com . asakusafw . yaess . jobqueue ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . yaess . core . YaessLogger ; public class YaessJobQueueLogger extends YaessLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public YaessJobQueueLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . yaess . jobqueue ; package com . asakusafw . yaess . jobqueue . client ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . lang . reflect . Field ; import java . lang . reflect . Type ; import java . net . Socket ; import java . net . URI ; import java . nio . charset . Charset ; import java . security . GeneralSecurityException ; import java . security . KeyManagementException ; import java . security . NoSuchAlgorithmException ; import java . security . cert . CertificateException ; import java . security . cert . X509Certificate ; import java . text . MessageFormat ; import javax . net . ssl . SSLContext ; import javax . net . ssl . TrustManager ; import javax . net . ssl . X509TrustManager ; import org . apache . http . HttpEntity ; import org . apache . http . HttpResponse ; import org . apache . http . HttpStatus ; import org . apache . http . auth . AuthScope ; import org . apache . http . auth . UsernamePasswordCredentials ; import org . apache . http . client . HttpClient ; import org . apache . http . client . methods . HttpGet ; import org . apache . http . client . methods . HttpPost ; import org . apache . http . client . methods . HttpPut ; import org . apache . http . client . methods . HttpUriRequest ; import org . apache . http . conn . scheme . Scheme ; import org . apache . http . conn . ssl . SSLSocketFactory ; import org . apache . http . entity . ContentType ; import org . apache . http . entity . StringEntity ; import org . apache . http . impl . client . DefaultHttpClient ; import org . apache . http . impl . conn . PoolingClientConnectionManager ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . google . gson . FieldNamingStrategy ; import com . google . gson . GsonBuilder ; import com . google . gson . JsonDeserializationContext ; import com . google . gson . JsonDeserializer ; import com . google . gson . JsonElement ; import com . google . gson . JsonObject ; import com . google . gson . JsonParseException ; import com . google . gson . JsonParser ; import com . google . gson . JsonPrimitive ; import com . google . gson . JsonSerializationContext ; import com . google . gson . JsonSerializer ; import com . google . gson . annotations . SerializedName ; public class HttpJobClient implements JobClient { static final Logger LOG = LoggerFactory . getLogger ( HttpJobClient . class ) ; private static final Charset ENCODING = Charset . forName ( "" ) ; static final ContentType CONTENT_TYPE = ContentType . create ( "" , ENCODING ) ; private static final GsonBuilder GSON_BUILDER ; static { GSON_BUILDER = new GsonBuilder ( ) ; GSON_BUILDER . registerTypeAdapter ( JobStatus . Kind . class , new JobStatusKindAdapter ( ) ) ; GSON_BUILDER . registerTypeAdapter ( ExecutionPhase . class , new ExecutionPhaseAdapter ( ) ) ; GSON_BUILDER . setFieldNamingStrategy ( new FieldNamingStrategy ( ) { @ Override public String translateName ( Field f ) { SerializedName name = f . getAnnotation ( SerializedName . class ) ; if ( name != null ) { return name . value ( ) ; } return f . getName ( ) ; } } ) ; } private final String baseUri ; private final String user ; private final HttpClient http ; public HttpJobClient ( String baseUri ) { if ( baseUri == null ) { throw new IllegalArgumentException ( "" ) ; } this . baseUri = normalize ( baseUri ) ; this . user = null ; this . http = createClient ( ) ; } public HttpJobClient ( String baseUri , String user , String password ) { if ( baseUri == null ) { throw new IllegalArgumentException ( "" ) ; } if ( user == null ) { throw new IllegalArgumentException ( "" ) ; } if ( password == null ) { throw new IllegalArgumentException ( "" ) ; } this . baseUri = normalize ( baseUri ) ; this . user = user ; DefaultHttpClient client = createClient ( ) ; client . getCredentialsProvider ( ) . setCredentials ( AuthScope . ANY , new UsernamePasswordCredentials ( user , password ) ) ; this . http = client ; } private DefaultHttpClient createClient ( ) { try { DefaultHttpClient client = new DefaultHttpClient ( new PoolingClientConnectionManager ( ) ) ; SSLSocketFactory socketFactory = TrustedSSLSocketFactory . create ( ) ; Scheme sch = new Scheme ( "" , , socketFactory ) ; client . getConnectionManager ( ) . getSchemeRegistry ( ) . register ( sch ) ; return client ; } catch ( GeneralSecurityException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , baseUri ) , e ) ; } } private static String normalize ( String url ) { assert url != null ; if ( url . endsWith ( "" ) ) { return url ; } return url + "" ; } public String getBaseUri ( ) { return baseUri ; } public String getUser ( ) { return user ; } @ Override public JobId register ( JobScript script ) throws IOException , InterruptedException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } HttpPost request = new HttpPost ( ) ; URI uri = createUri ( "" ) ; request . setURI ( uri ) ; request . setEntity ( createEntity ( script ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , uri , script ) ; } HttpResponse response = http . execute ( request ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { JobStatus status = extractJobStatus ( request , response ) ; if ( status . getKind ( ) == JobStatus . Kind . ERROR ) { throw toException ( request , response , status , MessageFormat . format ( "" , script , status . getErrorMessage ( ) ) ) ; } return new JobId ( status . getJobId ( ) ) ; } else { throw toException ( request , response , MessageFormat . format ( "" , script ) ) ; } } @ Override public JobStatus getStatus ( JobId id ) throws IOException , InterruptedException { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } HttpGet request = new HttpGet ( ) ; URI uri = createUri ( String . format ( "" , id . getToken ( ) ) ) ; request . setURI ( uri ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , uri ) ; } HttpResponse response = http . execute ( request ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { JobStatus status = extractJobStatus ( request , response ) ; return status ; } else { throw toException ( request , response , MessageFormat . format ( "" , id . getToken ( ) , request . getURI ( ) ) ) ; } } @ Override public void submit ( JobId id ) throws IOException , InterruptedException { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } HttpPut request = new HttpPut ( ) ; URI uri = createUri ( String . format ( "" , id . getToken ( ) ) ) ; request . setURI ( uri ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , uri ) ; } HttpResponse response = http . execute ( request ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { JobStatus status = extractJobStatus ( request , response ) ; if ( status . getKind ( ) == JobStatus . Kind . ERROR ) { throw toException ( request , response , status , MessageFormat . format ( "" , id . getToken ( ) , request . getURI ( ) ) ) ; } } else { throw toException ( request , response , MessageFormat . format ( "" , id . getToken ( ) , request . getURI ( ) ) ) ; } } private URI createUri ( String path ) { return URI . create ( baseUri + path ) ; } private JobStatus extractJobStatus ( HttpUriRequest request , HttpResponse response ) throws IOException { assert request != null ; assert response != null ; JobStatus status = extractContent ( JobStatus . class , request , response ) ; if ( status . getKind ( ) == null ) { throw new IOException ( MessageFormat . format ( "" , request . getURI ( ) ) ) ; } if ( status . getKind ( ) != JobStatus . Kind . ERROR && status . getJobId ( ) == null ) { throw new IOException ( MessageFormat . format ( "" , request . getURI ( ) ) ) ; } if ( status . getKind ( ) == JobStatus . Kind . COMPLETED && status . getExitCode ( ) == null ) { throw new IOException ( MessageFormat . format ( "" , request . getURI ( ) ) ) ; } return status ; } private < T > T extractContent ( Class < T > type , HttpUriRequest request , HttpResponse response ) throws IOException { assert request != null ; assert response != null ; HttpEntity entity = response . getEntity ( ) ; if ( entity == null ) { throw new IOException ( MessageFormat . format ( "" , request . getURI ( ) , response . getStatusLine ( ) ) ) ; } InputStream input = entity . getContent ( ) ; try { Reader reader = new BufferedReader ( new InputStreamReader ( input , ENCODING ) ) ; JsonParser parser = new JsonParser ( ) ; JsonElement element = parser . parse ( reader ) ; if ( ( element instanceof JsonObject ) == false ) { throw new IOException ( MessageFormat . format ( "" , request . getURI ( ) , response . getStatusLine ( ) ) ) ; } if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "" , new Object [ ] { element } ) ; } return GSON_BUILDER . create ( ) . fromJson ( element , type ) ; } catch ( RuntimeException e ) { throw new IOException ( MessageFormat . format ( "" , request . getURI ( ) , response . getStatusLine ( ) ) , e ) ; } finally { input . close ( ) ; } } private IOException toException ( HttpUriRequest request , HttpResponse response , String message ) { assert request != null ; assert response != null ; assert message != null ; try { JobStatus status = extractJobStatus ( request , response ) ; return toException ( request , response , status , message ) ; } catch ( IOException e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , request . getURI ( ) , response . getStatusLine ( ) ) , e ) ; } } return new IOException ( MessageFormat . format ( "" , message , request . getURI ( ) , response ) ) ; } private IOException toException ( HttpUriRequest request , HttpResponse response , JobStatus status , String message ) { assert request != null ; assert response != null ; assert status != null ; assert message != null ; return new IOException ( MessageFormat . format ( "" , message , request . getURI ( ) , response . getStatusLine ( ) , status . getErrorCode ( ) , status . getErrorMessage ( ) ) ) ; } private HttpEntity createEntity ( JobScript script ) { assert script != null ; String json = GSON_BUILDER . create ( ) . toJson ( script ) ; LOG . trace ( "" , json ) ; return new StringEntity ( json , CONTENT_TYPE ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , baseUri ) ; } private static final class JobStatusKindAdapter implements JsonDeserializer < JobStatus . Kind > { public JobStatusKindAdapter ( ) { return ; } @ Override public JobStatus . Kind deserialize ( JsonElement json , Type type , JsonDeserializationContext context ) throws JsonParseException { if ( json . isJsonPrimitive ( ) ) { JsonPrimitive primitive = ( JsonPrimitive ) json ; if ( primitive . isString ( ) ) { JobStatus . Kind kind = JobStatus . Kind . findFromSymbol ( primitive . getAsString ( ) ) ; if ( kind != null ) { return kind ; } } } throw new JsonParseException ( MessageFormat . format ( "" , json ) ) ; } } private static final class ExecutionPhaseAdapter implements JsonSerializer < ExecutionPhase > { public ExecutionPhaseAdapter ( ) { return ; } @ Override public JsonElement serialize ( ExecutionPhase src , Type type , JsonSerializationContext context ) { return new JsonPrimitive ( src . getSymbol ( ) ) ; } } private static final class TrustedSSLSocketFactory extends SSLSocketFactory { private static final String SSL_CONTEXT = "" ; private final SSLContext context ; private TrustedSSLSocketFactory ( SSLContext context ) { super ( context ) ; this . context = context ; } static TrustedSSLSocketFactory create ( ) throws NoSuchAlgorithmException , KeyManagementException { SSLContext context = SSLContext . getInstance ( SSL_CONTEXT ) ; context . init ( null , new TrustManager [ ] { new X509TrustManager ( ) { @ Override public void checkClientTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { return ; } @ Override public void checkServerTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { return ; } @ Override public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } } } , null ) ; return new TrustedSSLSocketFactory ( context ) ; } @ Override public Socket createSocket ( ) throws IOException { return context . getSocketFactory ( ) . createSocket ( ) ; } } } package com . asakusafw . yaess . jobqueue . client ; import java . util . Map ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . google . gson . annotations . SerializedName ; public class JobScript { private String batchId ; private String flowId ; private String executionId ; @ SerializedName ( "" ) private ExecutionPhase phase ; private String stageId ; @ SerializedName ( "" ) private String mainClassName ; private Map < String , String > arguments ; private Map < String , String > properties ; @ SerializedName ( "" ) private Map < String , String > environmentVariables ; public String getBatchId ( ) { return batchId ; } public void setBatchId ( String id ) { this . batchId = id ; } public String getFlowId ( ) { return flowId ; } public void setFlowId ( String id ) { this . flowId = id ; } public String getExecutionId ( ) { return executionId ; } public void setExecutionId ( String id ) { this . executionId = id ; } public ExecutionPhase getPhase ( ) { return phase ; } public void setPhase ( ExecutionPhase phase ) { this . phase = phase ; } public String getStageId ( ) { return stageId ; } public void setStageId ( String id ) { this . stageId = id ; } public String getMainClassName ( ) { return mainClassName ; } public void setMainClassName ( String name ) { this . mainClassName = name ; } public Map < String , String > getArguments ( ) { return arguments ; } public void setArguments ( Map < String , String > arguments ) { this . arguments = arguments ; } public Map < String , String > getProperties ( ) { return properties ; } public void setProperties ( Map < String , String > map ) { this . properties = map ; } public Map < String , String > getEnvironmentVariables ( ) { return environmentVariables ; } public void setEnvironmentVariables ( Map < String , String > map ) { this . environmentVariables = map ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( batchId ) ; builder . append ( "" ) ; builder . append ( flowId ) ; builder . append ( "" ) ; builder . append ( executionId ) ; builder . append ( "" ) ; builder . append ( phase ) ; builder . append ( "" ) ; builder . append ( stageId ) ; builder . append ( "" ) ; builder . append ( mainClassName ) ; builder . append ( "" ) ; builder . append ( arguments ) ; builder . append ( "" ) ; builder . append ( properties ) ; builder . append ( "" ) ; builder . append ( environmentVariables ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . yaess . jobqueue . client ; import com . google . gson . annotations . SerializedName ; public class JobStatus { @ SerializedName ( "" ) private Kind kind ; @ SerializedName ( "" ) private String jobId ; private Integer exitCode ; @ SerializedName ( "" ) private String errorCode ; @ SerializedName ( "" ) private String errorMessage ; public Kind getKind ( ) { return kind ; } public void setKind ( Kind kind ) { this . kind = kind ; } public String getJobId ( ) { return jobId ; } public void setJobId ( String jobId ) { this . jobId = jobId ; } public Integer getExitCode ( ) { return exitCode ; } public void setExitCode ( Integer exitCode ) { this . exitCode = exitCode ; } public String getErrorCode ( ) { return errorCode ; } public void setErrorCode ( String errorCode ) { this . errorCode = errorCode ; } public String getErrorMessage ( ) { return errorMessage ; } public void setErrorMessage ( String message ) { this . errorMessage = message ; } public enum Kind { INITIALIZED ( "" ) , WAITING ( "" ) , RUNNING ( "" ) , COMPLETED ( "" ) , ERROR ( "" ) , ; private final String symbol ; private Kind ( String symbol ) { assert symbol != null ; this . symbol = symbol ; } public String getSymbol ( ) { return symbol ; } public static Kind findFromSymbol ( String string ) { if ( string == null ) { throw new IllegalArgumentException ( "" ) ; } for ( Kind kind : values ( ) ) { if ( kind . getSymbol ( ) . equals ( string ) ) { return kind ; } } return null ; } } } package com . asakusafw . yaess . jobqueue . client ; import java . io . Serializable ; import java . text . MessageFormat ; import com . google . gson . annotations . SerializedName ; public final class JobId implements Serializable { private static final long serialVersionUID = - ; @ SerializedName ( "" ) private String token ; public JobId ( ) { return ; } public JobId ( String token ) { if ( token == null ) { throw new IllegalArgumentException ( "" ) ; } this . token = token ; } public void setToken ( String token ) { this . token = token ; } public String getToken ( ) { return token ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( token == null ) ? : token . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } JobId other = ( JobId ) obj ; if ( token == null ) { if ( other . token != null ) { return false ; } } else if ( ! token . equals ( other . token ) ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , token ) ; } } package com . asakusafw . yaess . jobqueue . client ; package com . asakusafw . yaess . jobqueue . client ; import java . io . IOException ; public interface JobClient { JobId register ( JobScript script ) throws IOException , InterruptedException ; void submit ( JobId id ) throws IOException , InterruptedException ; JobStatus getStatus ( JobId id ) throws IOException , InterruptedException ; } package com . asakusafw . yaess . jobqueue ; import java . util . Arrays ; import java . util . Collection ; import com . asakusafw . yaess . jobqueue . client . JobClient ; public class JobClientProvider { private final JobClient [ ] clients ; private final boolean [ ] blackList ; private int location ; public JobClientProvider ( Collection < ? extends JobClient > clients ) { if ( clients == null ) { throw new IllegalArgumentException ( "" ) ; } if ( clients . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } this . clients = clients . toArray ( new JobClient [ clients . size ( ) ] ) ; this . blackList = new boolean [ clients . size ( ) ] ; this . location = ; } public int count ( ) { return clients . length ; } public JobClient get ( ) { JobClient [ ] cs = clients ; boolean [ ] bs = blackList ; assert cs . length >= ; while ( true ) { synchronized ( cs ) { for ( int i = ; i < cs . length ; i ++ ) { JobClient client = cs [ location ] ; boolean enabled = blackList [ location ] == false ; location = ( location + ) % cs . length ; if ( enabled ) { return client ; } } } synchronized ( cs ) { Arrays . fill ( bs , false ) ; } } } public void setError ( JobClient client ) { if ( client == null ) { throw new IllegalArgumentException ( "" ) ; } int index = - ; JobClient [ ] cs = clients ; for ( int i = ; i < cs . length ; i ++ ) { if ( cs [ i ] == client ) { index = i ; break ; } } if ( index >= ) { boolean [ ] bs = blackList ; synchronized ( cs ) { bs [ index ] = true ; } } } } package com . asakusafw . yaess . jobqueue ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . concurrent . Callable ; import java . util . concurrent . CancellationException ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . ThreadFactory ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import java . util . concurrent . atomic . AtomicInteger ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . basic . ExitCodeException ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandlerBase ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . YaessLogger ; import com . asakusafw . yaess . jobqueue . client . JobClient ; import com . asakusafw . yaess . jobqueue . client . JobId ; import com . asakusafw . yaess . jobqueue . client . JobScript ; import com . asakusafw . yaess . jobqueue . client . JobStatus ; public class QueueHadoopScriptHandler extends ExecutionScriptHandlerBase implements HadoopScriptHandler { static final String CLEANUP_STAGE_CLASS = "" ; static final YaessLogger YSLOG = new YaessJobQueueLogger ( QueueHadoopScriptHandler . class ) ; static final Logger LOG = LoggerFactory . getLogger ( QueueHadoopScriptHandler . class ) ; private static final ExecutorService TIMEOUT_THREAD = Executors . newCachedThreadPool ( new ThreadFactory ( ) { private final AtomicInteger counter = new AtomicInteger ( ) ; @ Override public Thread newThread ( Runnable r ) { Thread thread = new Thread ( r , String . format ( "" , counter . incrementAndGet ( ) ) ) ; thread . setDaemon ( true ) ; return thread ; } } ) ; private volatile JobClientProvider clients ; private volatile long timeout ; private volatile long pollingInterval ; @ Override protected void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { if ( desiredEnvironmentVariables . isEmpty ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , getClass ( ) . getName ( ) , profile . getPrefix ( ) , KEY_ENV_PREFIX , desiredEnvironmentVariables ) ) ; } desiredEnvironmentVariables . put ( ExecutionScript . ENV_ASAKUSA_HOME , "" ) ; JobClientProfile p ; try { p = JobClientProfile . convert ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) ) , e ) ; } doConfigure ( p ) ; } void doConfigure ( JobClientProfile p ) { this . timeout = p . getTimeout ( ) ; this . pollingInterval = p . getPollingInterval ( ) ; this . clients = new JobClientProvider ( p . getClients ( ) ) ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { run ( monitor , context , script ) ; } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { HadoopScript script = new HadoopScript ( context . getPhase ( ) . getSymbol ( ) , Collections . < String > emptySet ( ) , CLEANUP_STAGE_CLASS , Collections . < String , String > emptyMap ( ) , Collections . < String , String > emptyMap ( ) ) ; run ( monitor , context , script ) ; } private void run ( ExecutionMonitor monitor , ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { assert monitor != null ; assert context != null ; assert script != null ; monitor . open ( ) ; try { monitor . checkCancelled ( ) ; JobInfo info = registerScript ( monitor , context , script ) ; monitor . progressed ( ) ; monitor . checkCancelled ( ) ; submitScript ( context , info ) ; monitor . progressed ( ) ; monitor . checkCancelled ( ) ; YSLOG . info ( "" , info . script . getBatchId ( ) , info . script . getFlowId ( ) , info . script . getPhase ( ) , info . script . getExecutionId ( ) , info . script . getStageId ( ) , info . client , info . id ) ; long start = System . currentTimeMillis ( ) ; try { JobStatus . Kind lastKind = JobStatus . Kind . INITIALIZED ; while ( true ) { JobStatus status = poll ( context , info ) ; JobStatus . Kind currentKind = status . getKind ( ) ; if ( lastKind . compareTo ( currentKind ) < ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , new Object [ ] { lastKind , currentKind , info , } ) ; } switch ( currentKind ) { case WAITING : break ; case RUNNING : monitor . progressed ( ) ; break ; case COMPLETED : case ERROR : checkError ( context , info , status ) ; return ; default : throw new AssertionError ( currentKind ) ; } } lastKind = currentKind ; monitor . checkCancelled ( ) ; Thread . sleep ( pollingInterval ) ; } } finally { long end = System . currentTimeMillis ( ) ; YSLOG . info ( "" , info . script . getBatchId ( ) , info . script . getFlowId ( ) , info . script . getPhase ( ) , info . script . getExecutionId ( ) , info . script . getStageId ( ) , info . client , info . id , end - start ) ; } } finally { monitor . close ( ) ; } } private JobInfo registerScript ( ExecutionMonitor monitor , ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { assert monitor != null ; assert context != null ; assert script != null ; JobScript job = convert ( context , script ) ; for ( int i = , n = clients . count ( ) * ; i <= n ; i ++ ) { monitor . checkCancelled ( ) ; JobClient client = clients . get ( ) ; try { JobId id = registerWithTimeout ( job , client ) ; return new JobInfo ( job , id , client ) ; } catch ( IOException e ) { clients . setError ( client ) ; YSLOG . warn ( e , "" , job . getBatchId ( ) , job . getFlowId ( ) , job . getPhase ( ) , job . getExecutionId ( ) , job . getStageId ( ) , client ) ; } } YSLOG . warn ( "" , job . getBatchId ( ) , job . getFlowId ( ) , job . getPhase ( ) , job . getExecutionId ( ) , job . getStageId ( ) , clients . count ( ) ) ; throw new IOException ( MessageFormat . format ( "" + "" , job . getBatchId ( ) , job . getFlowId ( ) , job . getPhase ( ) , job . getExecutionId ( ) , job . getStageId ( ) ) ) ; } private JobId registerWithTimeout ( final JobScript job , final JobClient client ) throws IOException , InterruptedException { assert job != null ; assert client != null ; Future < JobId > future = TIMEOUT_THREAD . submit ( new Callable < JobId > ( ) { @ Override public JobId call ( ) throws Exception { YSLOG . info ( "" , job . getBatchId ( ) , job . getFlowId ( ) , job . getPhase ( ) , job . getExecutionId ( ) , job . getStageId ( ) , client ) ; long start = System . currentTimeMillis ( ) ; JobId id = client . register ( job ) ; long end = System . currentTimeMillis ( ) ; YSLOG . info ( "" , job . getBatchId ( ) , job . getFlowId ( ) , job . getPhase ( ) , job . getExecutionId ( ) , job . getStageId ( ) , client , id , end - start ) ; return id ; } } ) ; try { return future . get ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else if ( cause instanceof InterruptedException ) { throw ( InterruptedException ) cause ; } else if ( cause instanceof CancellationException ) { throw ( CancellationException ) cause ; } else { throw new IOException ( MessageFormat . format ( "" + "" , job . getBatchId ( ) , job . getFlowId ( ) , job . getPhase ( ) , job . getExecutionId ( ) , job . getStageId ( ) , client ) , cause ) ; } } catch ( TimeoutException e ) { throw new IOException ( MessageFormat . format ( "" + "" , job . getBatchId ( ) , job . getFlowId ( ) , job . getPhase ( ) , job . getExecutionId ( ) , job . getStageId ( ) , client ) , e ) ; } } private JobScript convert ( ExecutionContext context , HadoopScript script ) throws InterruptedException , IOException { assert context != null ; assert script != null ; JobScript result = new JobScript ( ) ; result . setBatchId ( context . getBatchId ( ) ) ; result . setFlowId ( context . getFlowId ( ) ) ; result . setExecutionId ( context . getExecutionId ( ) ) ; result . setPhase ( context . getPhase ( ) ) ; result . setArguments ( new HashMap < String , String > ( context . getArguments ( ) ) ) ; result . setStageId ( script . getId ( ) ) ; result . setMainClassName ( script . getClassName ( ) ) ; Map < String , String > props = new HashMap < String , String > ( ) ; props . putAll ( getProperties ( context , script ) ) ; props . putAll ( script . getHadoopProperties ( ) ) ; result . setProperties ( props ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . putAll ( context . getEnvironmentVariables ( ) ) ; env . putAll ( script . getEnvironmentVariables ( ) ) ; result . setEnvironmentVariables ( env ) ; return result ; } private void submitScript ( ExecutionContext context , JobInfo info ) throws IOException , InterruptedException { assert context != null ; assert info != null ; YSLOG . info ( "" , info . script . getBatchId ( ) , info . script . getFlowId ( ) , info . script . getPhase ( ) , info . script . getExecutionId ( ) , info . script . getStageId ( ) , info . client , info . id ) ; long start = System . currentTimeMillis ( ) ; try { info . client . submit ( info . id ) ; } catch ( IOException e ) { YSLOG . error ( e , "" , info . script . getBatchId ( ) , info . script . getFlowId ( ) , info . script . getPhase ( ) , info . script . getExecutionId ( ) , info . script . getStageId ( ) , info . client , info . id ) ; throw e ; } long end = System . currentTimeMillis ( ) ; YSLOG . info ( "" , info . script . getBatchId ( ) , info . script . getFlowId ( ) , info . script . getPhase ( ) , info . script . getExecutionId ( ) , info . script . getStageId ( ) , info . client , info . id , end - start ) ; } private JobStatus poll ( ExecutionContext context , JobInfo info ) throws IOException , InterruptedException { assert context != null ; assert info != null ; try { return info . client . getStatus ( info . id ) ; } catch ( IOException e ) { YSLOG . error ( e , "" , info . script . getBatchId ( ) , info . script . getFlowId ( ) , info . script . getPhase ( ) , info . script . getExecutionId ( ) , info . script . getStageId ( ) , info . client , info . id ) ; throw e ; } } private void checkError ( ExecutionContext context , JobInfo info , JobStatus status ) throws IOException { assert context != null ; assert info != null ; assert status != null ; JobStatus . Kind kind = status . getKind ( ) ; switch ( kind ) { case COMPLETED : if ( status . getExitCode ( ) != ) { throw new ExitCodeException ( MessageFormat . format ( "" , info , String . valueOf ( status . getExitCode ( ) ) ) , status . getExitCode ( ) ) ; } return ; case ERROR : throw new IOException ( MessageFormat . format ( "" , info , status . getErrorMessage ( ) == null ? status . getErrorCode ( ) == null ? "" : MessageFormat . format ( "" , status . getErrorCode ( ) ) : status . getErrorMessage ( ) ) ) ; default : throw new AssertionError ( kind ) ; } } private static final class JobInfo { final JobScript script ; final JobId id ; final JobClient client ; JobInfo ( JobScript script , JobId id , JobClient client ) { assert script != null ; assert id != null ; assert client != null ; this . script = script ; this . id = id ; this . client = client ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , id , client , script . getBatchId ( ) , script . getFlowId ( ) , script . getPhase ( ) , script . getExecutionId ( ) , script . getStageId ( ) ) ; } } } package com . asakusafw . yaess . paralleljob ; package com . asakusafw . yaess . paralleljob ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . yaess . core . YaessLogger ; public class YaessParallelJobLogger extends YaessLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public YaessParallelJobLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . yaess . paralleljob ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . NavigableMap ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . ThreadFactory ; import java . util . concurrent . atomic . AtomicInteger ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . basic . JobExecutor ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; import com . asakusafw . yaess . core . Job ; import com . asakusafw . yaess . core . VariableResolver ; import com . asakusafw . yaess . core . YaessLogger ; import com . asakusafw . yaess . core . util . PropertiesUtil ; public class ParallelJobExecutor implements JobExecutor { static final YaessLogger YSLOG = new YaessParallelJobLogger ( ParallelJobExecutor . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ParallelJobExecutor . class ) ; public static final String KEY_PARALLEL_PREFIX = "" ; public static final String DEFAULT_RESOURCE_ID = ExecutionScriptHandler . DEFAULT_RESOURCE_ID ; private final ExecutorService defaultExecutor ; private final Map < String , ExecutorService > resourceExecutors ; public ParallelJobExecutor ( int defaultResuorce , Map < String , Integer > threadConfig ) { if ( defaultResuorce <= ) { throw new IllegalArgumentException ( "" ) ; } if ( threadConfig == null ) { throw new IllegalArgumentException ( "" ) ; } this . defaultExecutor = Executors . newFixedThreadPool ( defaultResuorce , new ThreadFactory ( ) { private final AtomicInteger count = new AtomicInteger ( ) ; @ Override public Thread newThread ( Runnable r ) { Thread thread = new Thread ( r ) ; thread . setName ( MessageFormat . format ( "" , String . valueOf ( count . incrementAndGet ( ) ) ) ) ; return thread ; } } ) ; HashMap < String , ExecutorService > map = new HashMap < String , ExecutorService > ( ) ; for ( Map . Entry < String , Integer > entry : threadConfig . entrySet ( ) ) { final String name = entry . getKey ( ) ; Integer value = entry . getValue ( ) ; if ( value == null || value < ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , value ) ) ; } map . put ( name , Executors . newFixedThreadPool ( value , new ThreadFactory ( ) { private final AtomicInteger count = new AtomicInteger ( ) ; @ Override public Thread newThread ( Runnable r ) { Thread thread = new Thread ( r ) ; thread . setName ( MessageFormat . format ( "" , name , String . valueOf ( count . incrementAndGet ( ) ) ) ) ; return thread ; } } ) ) ; } map . put ( DEFAULT_RESOURCE_ID , defaultExecutor ) ; resourceExecutors = Collections . unmodifiableMap ( map ) ; } public static ParallelJobExecutor extract ( String servicePrefix , Map < String , String > configuration , VariableResolver variables ) { if ( servicePrefix == null ) { throw new IllegalArgumentException ( "" ) ; } if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( variables == null ) { throw new IllegalArgumentException ( "" ) ; } NavigableMap < String , String > segment = PropertiesUtil . createPrefixMap ( configuration , KEY_PARALLEL_PREFIX ) ; Map < String , Integer > conf = new HashMap < String , Integer > ( ) ; for ( Map . Entry < String , String > entry : segment . entrySet ( ) ) { String name = entry . getKey ( ) ; String valueString = entry . getValue ( ) ; try { valueString = variables . replace ( valueString , true ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , servicePrefix + '' + name , valueString ) , e ) ; } Integer value ; try { value = Integer . valueOf ( valueString ) ; } catch ( NumberFormatException e ) { value = null ; } if ( value == null || value <= ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , servicePrefix + '' + KEY_PARALLEL_PREFIX + name , valueString ) ) ; } conf . put ( name , value ) ; } LOG . debug ( "" , conf ) ; Integer defaultValue = conf . remove ( DEFAULT_RESOURCE_ID ) ; if ( defaultValue == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , servicePrefix + '' + KEY_PARALLEL_PREFIX + DEFAULT_RESOURCE_ID ) ) ; } return new ParallelJobExecutor ( defaultValue , conf ) ; } @ Override public Executing submit ( ExecutionMonitor monitor , ExecutionContext context , Job job , BlockingQueue < Executing > doneQueue ) throws InterruptedException , IOException { if ( monitor == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( job == null ) { throw new IllegalArgumentException ( "" ) ; } String resourceId = job . getResourceId ( context ) ; ExecutorService executor = resourceExecutors . get ( resourceId ) ; if ( executor == null ) { YSLOG . warn ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , job . getJobLabel ( ) , job . getServiceLabel ( ) , resourceId ) ; LOG . debug ( "" , resourceId , job . getId ( ) ) ; executor = defaultExecutor ; } else { YSLOG . info ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) , job . getJobLabel ( ) , job . getServiceLabel ( ) , resourceId ) ; } Executing executing = new Executing ( monitor , context , job , doneQueue ) ; executor . execute ( executing ) ; return executing ; } } package com . asakusafw . yaess . paralleljob ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . basic . AbstractJobScheduler ; import com . asakusafw . yaess . basic . JobExecutor ; import com . asakusafw . yaess . core . JobScheduler ; import com . asakusafw . yaess . core . ServiceProfile ; public class ParallelJobScheduler extends AbstractJobScheduler { static final Logger LOG = LoggerFactory . getLogger ( ParallelJobScheduler . class ) ; private volatile JobExecutor executor ; @ Override protected void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { try { this . executor = ParallelJobExecutor . extract ( profile . getPrefix ( ) , profile . getConfiguration ( ) , profile . getContext ( ) . getContextParameters ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) ) , e ) ; } } @ Override protected JobExecutor getJobExecutor ( ) { return executor ; } } package com . asakusafw . yaess . paralleljob ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; 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 . concurrent . BrokenBarrierException ; import java . util . concurrent . CyclicBarrier ; import java . util . concurrent . atomic . AtomicInteger ; import org . junit . Test ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; import com . asakusafw . yaess . core . Job ; import com . asakusafw . yaess . core . JobScheduler ; import com . asakusafw . yaess . core . PhaseMonitor ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class ParallelJobSchedulerTest { private static final ExecutionContext CONTEXT = new ExecutionContext ( "" , "" , "" , ExecutionPhase . MAIN , Collections . < String , String > emptyMap ( ) ) ; @ Test public void simple ( ) throws Exception { JobScheduler instance = create ( "" , "" ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) ) ; instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void multiple ( ) throws Exception { JobScheduler instance = create ( "" , "" ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) ) ; jobs . add ( new Mock ( "" ) ) ; jobs . add ( new Mock ( "" ) ) ; instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void dependencies ( ) throws Exception { JobScheduler instance = create ( "" , "" ) ; AtomicInteger group = new AtomicInteger ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; jobs . add ( new Mock ( group , "" , "" , "" ) ) ; jobs . add ( new Mock ( group , "" ) ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; assertThat ( ordinary ( jobs , "" ) , lessThan ( ordinary ( jobs , "" ) ) ) ; assertThat ( ordinary ( jobs , "" ) , lessThan ( ordinary ( jobs , "" ) ) ) ; assertThat ( ordinary ( jobs , "" ) , lessThan ( ordinary ( jobs , "" ) ) ) ; assertThat ( ordinary ( jobs , "" ) , lessThan ( ordinary ( jobs , "" ) ) ) ; } @ Test ( timeout = ) public void parallel ( ) throws Exception { JobScheduler instance = create ( "" , "" , "" , "" ) ; final CyclicBarrier barrier = new CyclicBarrier ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws InterruptedException , IOException { try { barrier . await ( ) ; } catch ( BrokenBarrierException e ) { throw new IOException ( e ) ; } } } . resource ( "" ) ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws InterruptedException , IOException { try { barrier . await ( ) ; } catch ( BrokenBarrierException e ) { throw new IOException ( e ) ; } } } . resource ( "" ) ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws InterruptedException , IOException { try { barrier . await ( ) ; } catch ( BrokenBarrierException e ) { throw new IOException ( e ) ; } } } . resource ( "" ) ) ; instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void cyclic ( ) throws Exception { JobScheduler instance = create ( "" , "" ) ; AtomicInteger group = new AtomicInteger ( ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( group , "" ) ) ; jobs . add ( new Mock ( group , "" , "" , "" ) ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; jobs . add ( new Mock ( group , "" , "" ) ) ; try { instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; fail ( ) ; } catch ( IOException e ) { } Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; assertThat ( rest , hasItem ( "" ) ) ; assertThat ( rest , hasItem ( "" ) ) ; assertThat ( rest , hasItem ( "" ) ) ; assertThat ( rest , hasItem ( "" ) ) ; } @ Test public void fail_job ( ) throws Exception { JobScheduler instance = create ( "" , "" ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws IOException { throw new IOException ( ) ; } } ) ; try { instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . STRICT ) ; fail ( ) ; } catch ( IOException e ) { } Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void fail_besteffort ( ) throws Exception { JobScheduler instance = create ( "" , "" ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws IOException { throw new IOException ( ) ; } } ) ; jobs . add ( new Mock ( "" ) ) ; jobs . add ( new Mock ( "" ) ) ; try { instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . BEST_EFFORT ) ; fail ( ) ; } catch ( IOException e ) { } Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; } @ Test public void fail_stuck ( ) throws Exception { JobScheduler instance = create ( "" , "" ) ; List < Mock > jobs = new ArrayList < Mock > ( ) ; jobs . add ( new Mock ( "" ) { @ Override protected void hook ( ) throws IOException { throw new IOException ( ) ; } } ) ; jobs . add ( new Mock ( "" ) ) ; jobs . add ( new Mock ( "" , "" , "" ) ) ; try { instance . execute ( PhaseMonitor . NULL , CONTEXT , jobs , JobScheduler . BEST_EFFORT ) ; fail ( ) ; } catch ( IOException e ) { } Set < String > rest = collectRest ( jobs ) ; assertThat ( rest . size ( ) , is ( ) ) ; assertThat ( rest , hasItem ( "" ) ) ; } @ Test ( expected = IOException . class ) public void missing_default ( ) throws Exception { create ( ) ; } @ Test ( expected = IOException . class ) public void zero_parallel ( ) throws Exception { create ( "" , "" ) ; } @ Test ( expected = IOException . class ) public void invalid_parallel ( ) throws Exception { create ( "" , "" ) ; } private JobScheduler create ( String ... keyValuePairs ) throws InterruptedException , IOException { assert keyValuePairs != null ; Map < String , String > conf = map ( keyValuePairs ) ; ServiceProfile < JobScheduler > profile = new ServiceProfile < JobScheduler > ( "" , ParallelJobScheduler . class , conf , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; JobScheduler instance = profile . newInstance ( ) ; return instance ; } private int ordinary ( List < Mock > jobs , String name ) { for ( Mock mock : jobs ) { if ( mock . getId ( ) . equals ( name ) ) { return mock . count ; } } throw new AssertionError ( name ) ; } private Set < String > collectRest ( List < Mock > jobs ) { Set < String > results = new HashSet < String > ( ) ; for ( Mock mock : jobs ) { if ( mock . executed == false ) { results . add ( mock . id ) ; } } return results ; } protected Map < String , String > map ( String ... keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > conf = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length - ; i += ) { conf . put ( keyValuePairs [ i ] , keyValuePairs [ i + ] ) ; } return conf ; } private static class Mock extends Job { private final AtomicInteger counter ; final String id ; final Set < String > blockers ; volatile boolean executed ; volatile int count ; private String resourceId = ExecutionScriptHandler . DEFAULT_RESOURCE_ID ; Mock ( String id , String ... blockers ) { this ( new AtomicInteger ( ) , id , blockers ) ; } Mock ( AtomicInteger c , String id , String ... blockers ) { assert id != null ; assert blockers != null ; this . counter = c ; this . id = id ; this . blockers = new HashSet < String > ( Arrays . asList ( blockers ) ) ; } Mock resource ( String rid ) { this . resourceId = rid ; return this ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { monitor . open ( ) ; try { executed = true ; count = counter . incrementAndGet ( ) ; hook ( ) ; } finally { monitor . close ( ) ; } } protected void hook ( ) throws InterruptedException , IOException { return ; } @ Override public String getJobLabel ( ) { return id ; } @ Override public String getServiceLabel ( ) { return id ; } @ Override public String getId ( ) { return id ; } @ Override public Set < String > getBlockerIds ( ) { return blockers ; } @ Override public String getResourceId ( ExecutionContext context ) { return resourceId ; } } } package com . asakusafw . yaess . multidispatch ; import java . io . IOException ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; public class FailCommandScriptHandler extends MockCommandScriptHandler { @ Override void hook ( ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { String resourceId = getResourceId ( context , script ) ; throw new MessageException ( context , resourceId ) ; } static final class MessageException extends IOException { private static final long serialVersionUID = ; final ExecutionContext context ; final String message ; MessageException ( ExecutionContext context , String message ) { this . context = context ; this . message = message ; } } } package com . asakusafw . yaess . multidispatch ; import java . io . IOException ; import java . util . Map ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . CommandScriptHandler ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScriptHandlerBase ; import com . asakusafw . yaess . core . ServiceProfile ; public class MockCommandScriptHandler extends ExecutionScriptHandlerBase implements CommandScriptHandler { @ Override protected void doConfigure ( ServiceProfile < ? > profile , Map < String , String > desiredProperties , Map < String , String > desiredEnvironmentVariables ) throws InterruptedException , IOException { return ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { monitor . open ( ) ; try { hook ( context , script ) ; } finally { monitor . close ( ) ; } } @ Override public void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { hook ( context , null ) ; } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { hook ( context , null ) ; } void hook ( ExecutionContext context , CommandScript script ) throws InterruptedException , IOException { return ; } } package com . asakusafw . yaess . multidispatch ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . VariableResolver ; import com . asakusafw . yaess . multidispatch . FailCommandScriptHandler . MessageException ; public class ExecutionScriptHandlerDispatcherTest { private static final String BATCH_ID = "" ; private static final String PREFIX = "" ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void getHandlerId ( ) throws Exception { Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; assertThat ( dispatcher . getHandlerId ( ) , is ( PREFIX ) ) ; } @ Test public void getResourceId ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" ) ; assertThat ( dispatcher . getResourceId ( something , null ) , is ( "" ) ) ; ExecutionContext testing = context ( "" ) ; assertThat ( dispatcher . getResourceId ( testing , null ) , is ( "" ) ) ; } @ Test public void getProperties ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" ) ; assertThat ( dispatcher . getProperties ( something , null ) . get ( "" ) , is ( "" ) ) ; ExecutionContext testing = context ( "" ) ; assertThat ( dispatcher . getProperties ( testing , null ) . get ( "" ) , is ( "" ) ) ; } @ Test public void getEnvironmentVariables ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" ) ; assertThat ( dispatcher . getEnvironmentVariables ( something , null ) . get ( "" ) , is ( "" ) ) ; ExecutionContext testing = context ( "" ) ; assertThat ( dispatcher . getEnvironmentVariables ( testing , null ) . get ( "" ) , is ( "" ) ) ; } @ Test public void setUp ( ) throws Exception { Map < String , String > conf = createConf ( ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" , ExecutionPhase . SETUP ) ; try { dispatcher . setUp ( ExecutionMonitor . NULL , something ) ; fail ( ) ; } catch ( MessageException e ) { assertThat ( e . message , is ( "" ) ) ; assertThat ( e . context . getPhase ( ) , is ( ExecutionPhase . SETUP ) ) ; } } @ Test public void setUp_match ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" , ExecutionPhase . SETUP ) ; try { dispatcher . setUp ( ExecutionMonitor . NULL , something ) ; fail ( ) ; } catch ( MessageException e ) { assertThat ( e . message , is ( "" ) ) ; assertThat ( e . context . getPhase ( ) , is ( ExecutionPhase . SETUP ) ) ; } } @ Test public void setUp_specified ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , ExecutionScriptHandlerDispatcher . KEY_SETUP , "" ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" , ExecutionPhase . SETUP ) ; try { dispatcher . setUp ( ExecutionMonitor . NULL , something ) ; fail ( ) ; } catch ( MessageException e ) { assertThat ( e . message , is ( "" ) ) ; assertThat ( e . context . getPhase ( ) , is ( ExecutionPhase . SETUP ) ) ; } } @ Test public void execute ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; CommandScript script = script ( "" ) ; ExecutionContext something = context ( "" , ExecutionPhase . MAIN ) ; try { dispatcher . execute ( ExecutionMonitor . NULL , something , script ) ; fail ( ) ; } catch ( MessageException e ) { assertThat ( e . message , is ( "" ) ) ; assertThat ( e . context . getPhase ( ) , is ( ExecutionPhase . MAIN ) ) ; } ExecutionContext testing = context ( "" ) ; try { dispatcher . execute ( ExecutionMonitor . NULL , testing , script ) ; fail ( ) ; } catch ( MessageException e ) { assertThat ( e . message , is ( "" ) ) ; assertThat ( e . context . getPhase ( ) , is ( ExecutionPhase . MAIN ) ) ; } } @ Test public void match_stage ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext context = context ( "" , ExecutionPhase . MAIN ) ; CommandScript script = script ( "" ) ; assertThat ( dispatcher . getResourceId ( context , script ) , is ( "" ) ) ; ExecutionContext otherFlow = context ( "" , ExecutionPhase . MAIN ) ; assertThat ( dispatcher . getResourceId ( otherFlow , script ) , is ( "" ) ) ; ExecutionContext otherPhase = context ( "" , ExecutionPhase . PROLOGUE ) ; assertThat ( dispatcher . getResourceId ( otherPhase , script ) , is ( "" ) ) ; CommandScript otherScript = script ( "" ) ; assertThat ( dispatcher . getResourceId ( context , otherScript ) , is ( "" ) ) ; } @ Test public void match_phase ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext context = context ( "" , ExecutionPhase . MAIN ) ; CommandScript script = script ( "" ) ; assertThat ( dispatcher . getResourceId ( context , script ) , is ( "" ) ) ; ExecutionContext otherFlow = context ( "" , ExecutionPhase . MAIN ) ; assertThat ( dispatcher . getResourceId ( otherFlow , script ) , is ( "" ) ) ; ExecutionContext otherPhase = context ( "" , ExecutionPhase . PROLOGUE ) ; assertThat ( dispatcher . getResourceId ( otherPhase , script ) , is ( "" ) ) ; CommandScript otherScript = script ( "" ) ; assertThat ( dispatcher . getResourceId ( context , otherScript ) , is ( "" ) ) ; } @ Test public void match_flow ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext context = context ( "" , ExecutionPhase . MAIN ) ; CommandScript script = script ( "" ) ; assertThat ( dispatcher . getResourceId ( context , script ) , is ( "" ) ) ; ExecutionContext otherFlow = context ( "" , ExecutionPhase . MAIN ) ; assertThat ( dispatcher . getResourceId ( otherFlow , script ) , is ( "" ) ) ; ExecutionContext otherPhase = context ( "" , ExecutionPhase . PROLOGUE ) ; assertThat ( dispatcher . getResourceId ( otherPhase , script ) , is ( "" ) ) ; CommandScript otherScript = script ( "" ) ; assertThat ( dispatcher . getResourceId ( context , otherScript ) , is ( "" ) ) ; } @ Test public void match_batch ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext context = context ( "" , ExecutionPhase . MAIN ) ; CommandScript script = script ( "" ) ; assertThat ( dispatcher . getResourceId ( context , script ) , is ( "" ) ) ; ExecutionContext otherFlow = context ( "" , ExecutionPhase . MAIN ) ; assertThat ( dispatcher . getResourceId ( otherFlow , script ) , is ( "" ) ) ; ExecutionContext otherPhase = context ( "" , ExecutionPhase . PROLOGUE ) ; assertThat ( dispatcher . getResourceId ( otherPhase , script ) , is ( "" ) ) ; CommandScript otherScript = script ( "" ) ; assertThat ( dispatcher . getResourceId ( context , otherScript ) , is ( "" ) ) ; } @ Test public void cleanUp ( ) throws Exception { Map < String , String > conf = createConf ( ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" , ExecutionPhase . CLEANUP ) ; try { dispatcher . cleanUp ( ExecutionMonitor . NULL , something ) ; fail ( ) ; } catch ( MessageException e ) { assertThat ( e . message , is ( "" ) ) ; assertThat ( e . context . getPhase ( ) , is ( ExecutionPhase . CLEANUP ) ) ; } } @ Test public void cleanUp_match ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" , ExecutionPhase . CLEANUP ) ; try { dispatcher . cleanUp ( ExecutionMonitor . NULL , something ) ; fail ( ) ; } catch ( MessageException e ) { assertThat ( e . message , is ( "" ) ) ; assertThat ( e . context . getPhase ( ) , is ( ExecutionPhase . CLEANUP ) ) ; } } @ Test public void cleanUp_specified ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , "" , FailCommandScriptHandler . class ) ; declare ( conf , ExecutionScriptHandlerDispatcher . KEY_CLEANUP , "" ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext something = context ( "" , ExecutionPhase . CLEANUP ) ; try { dispatcher . cleanUp ( ExecutionMonitor . NULL , something ) ; fail ( ) ; } catch ( MessageException e ) { assertThat ( e . message , is ( "" ) ) ; assertThat ( e . context . getPhase ( ) , is ( ExecutionPhase . CLEANUP ) ) ; } } @ Test ( expected = IOException . class ) public void unknown_resource ( ) throws Exception { put ( "" ) ; Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; ExecutionContext testing = context ( "" ) ; dispatcher . getResourceId ( testing , null ) ; } @ Test ( expected = IOException . class ) public void missing_confdir ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; create ( conf ) ; } @ Test ( expected = IOException . class ) public void invalid_forceSetup ( ) throws Exception { Map < String , String > conf = createConf ( ) ; declare ( conf , ExecutionScriptHandlerDispatcher . KEY_SETUP , "" ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; create ( conf ) ; } @ Test ( expected = IOException . class ) public void invalid_forceCleanup ( ) throws Exception { Map < String , String > conf = createConf ( ) ; declare ( conf , ExecutionScriptHandlerDispatcher . KEY_CLEANUP , "" ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; create ( conf ) ; } @ Test ( expected = IOException . class ) public void invalid_confdir ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( ExecutionScriptHandlerDispatcher . KEY_DIRECTORY , "" ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; create ( conf ) ; } @ Test public void confdir_not_exist ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( ExecutionScriptHandlerDispatcher . KEY_DIRECTORY , new File ( folder . getRoot ( ) , "" ) . getAbsolutePath ( ) ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; CommandScriptHandlerDispatcher dispatcher = create ( conf ) ; assertThat ( dispatcher . getResourceId ( context ( "" ) , null ) , is ( "" ) ) ; } @ Test ( expected = IOException . class ) public void invalid_subcomponent ( ) throws Exception { Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; conf . put ( "" , "" ) ; create ( conf ) ; } @ Test ( expected = IOException . class ) public void missing_defaultcomponent ( ) throws Exception { Map < String , String > conf = createConf ( ) ; declare ( conf , "" , MockCommandScriptHandler . class ) ; create ( conf ) ; } private CommandScriptHandlerDispatcher create ( Map < String , String > conf ) throws InterruptedException , IOException { ServiceProfile < CommandScriptHandlerDispatcher > profile = new ServiceProfile < CommandScriptHandlerDispatcher > ( PREFIX , CommandScriptHandlerDispatcher . class , conf , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( Collections . < String , String > emptyMap ( ) ) ) ) ; return profile . newInstance ( ) ; } private Map < String , String > createConf ( ) { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( ExecutionScriptHandlerDispatcher . KEY_DIRECTORY , folder . getRoot ( ) . getAbsolutePath ( ) ) ; return conf ; } private void declare ( Map < String , String > conf , String key , String value ) { conf . put ( key , value ) ; } private void declare ( Map < String , String > conf , String name , Class < ? > aClass ) { conf . put ( name , aClass . getName ( ) ) ; conf . put ( name + "" + ExecutionScriptHandler . KEY_RESOURCE , name ) ; conf . put ( name + "" + ExecutionScriptHandler . KEY_ENV_PREFIX + "" , name ) ; conf . put ( name + "" + ExecutionScriptHandler . KEY_PROP_PREFIX + "" , name ) ; } private void put ( String ... pairs ) throws IOException { Properties p = new Properties ( ) ; for ( String pair : pairs ) { String [ ] atoms = pair . split ( "" , ) ; p . setProperty ( atoms [ ] , atoms [ ] ) ; } File file = folder . newFile ( BATCH_ID + ExecutionScriptHandlerDispatcher . SUFFIX_CONF ) ; OutputStream output = new FileOutputStream ( file ) ; try { p . store ( output , BATCH_ID ) ; } finally { output . close ( ) ; } } private ExecutionContext context ( String flowId ) { return context ( flowId , ExecutionPhase . MAIN ) ; } private ExecutionContext context ( String flowId , ExecutionPhase phase ) { return new ExecutionContext ( BATCH_ID , flowId , "" , phase , Collections . < String , String > emptyMap ( ) ) ; } CommandScript script ( String scriptId ) { CommandScript script = new CommandScript ( scriptId , Collections . < String > emptySet ( ) , "" , "" , Collections . singletonList ( "" ) , Collections . < String , String > emptyMap ( ) ) ; return script ; } } package com . asakusafw . yaess . multidispatch ; package com . asakusafw . yaess . multidispatch ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . lang . ref . Reference ; import java . lang . ref . SoftReference ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionScript ; import com . asakusafw . yaess . core . ExecutionScriptHandler ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . YaessLogger ; import com . asakusafw . yaess . core . util . PropertiesUtil ; public abstract class ExecutionScriptHandlerDispatcher < T extends ExecutionScript > implements ExecutionScriptHandler < T > { static final YaessLogger YSLOG = new YaessMultiDispatchLogger ( ExecutionScriptHandlerDispatcher . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ExecutionScriptHandlerDispatcher . class ) ; private static final String LABEL_UNDEFINED = "" ; static final String PREFIX_CONF = "" ; static final String KEY_DIRECTORY = PREFIX_CONF + "" ; static final String KEY_SETUP = PREFIX_CONF + "" ; static final String KEY_CLEANUP = PREFIX_CONF + "" ; static final String PREFIX_DEFAULT = "" ; static final String SUFFIX_CONF = "" ; private final Class < ? extends ExecutionScriptHandler < T > > handlerKind ; private volatile String prefix ; private volatile File confDirectory ; private volatile Reference < Map < String , Properties > > confCache = new SoftReference < Map < String , Properties > > ( null ) ; private volatile Map < String , ExecutionScriptHandler < T > > delegations ; private volatile String forceSetUp ; private volatile String forceCleanUp ; protected ExecutionScriptHandlerDispatcher ( Class < ? extends ExecutionScriptHandler < T > > handlerKind ) { if ( handlerKind == null ) { throw new IllegalArgumentException ( "" ) ; } this . handlerKind = handlerKind ; } @ Override public void configure ( ServiceProfile < ? > profile ) throws IOException , InterruptedException { this . prefix = profile . getPrefix ( ) ; try { this . confDirectory = getConfDirectory ( profile ) ; this . delegations = getDelegations ( profile ) ; this . forceSetUp = profile . getConfiguration ( KEY_SETUP , false , true ) ; this . forceCleanUp = profile . getConfiguration ( KEY_CLEANUP , false , true ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , profile . getServiceClass ( ) . getName ( ) ) , e ) ; } if ( forceSetUp != null && delegations . containsKey ( forceSetUp ) == false ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , KEY_SETUP , forceSetUp ) ) ; } if ( forceCleanUp != null && delegations . containsKey ( forceCleanUp ) == false ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , KEY_CLEANUP , forceCleanUp ) ) ; } } private File getConfDirectory ( ServiceProfile < ? > profile ) { assert profile != null ; String value = profile . getConfiguration ( KEY_DIRECTORY , true , true ) ; File dir = new File ( value ) ; if ( dir . exists ( ) == false ) { YSLOG . info ( "" , profile . getPrefix ( ) , KEY_DIRECTORY , value ) ; } return dir ; } private Map < String , ExecutionScriptHandler < T > > getDelegations ( ServiceProfile < ? > profile ) throws IOException , InterruptedException { assert profile != null ; Map < String , String > conf = profile . getConfiguration ( ) ; Set < String > keys = PropertiesUtil . getChildKeys ( conf , "" , "" ) ; keys . remove ( PREFIX_CONF ) ; if ( keys . contains ( PREFIX_DEFAULT ) == false ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , PREFIX_DEFAULT ) ) ; } Properties properties = new Properties ( ) ; for ( Map . Entry < String , String > entry : conf . entrySet ( ) ) { String key = profile . getPrefix ( ) + "" + entry . getKey ( ) ; String value = entry . getValue ( ) ; properties . setProperty ( key , value ) ; } Map < String , ExecutionScriptHandler < T > > results = new HashMap < String , ExecutionScriptHandler < T > > ( ) ; for ( String key : keys ) { String subPrefix = profile . getPrefix ( ) + "" + key ; ServiceProfile < ? extends ExecutionScriptHandler < T > > subProfile ; try { subProfile = ServiceProfile . load ( properties , subPrefix , handlerKind , profile . getContext ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , subPrefix ) , e ) ; } ExecutionScriptHandler < T > subInstance = subProfile . newInstance ( ) ; results . put ( key , subInstance ) ; } return results ; } @ Override public String getHandlerId ( ) { return prefix ; } private ExecutionScriptHandler < T > resolve ( ExecutionContext context , ExecutionScript script ) throws IOException { assert context != null ; Properties batchConf = getBatchConf ( context , script ) ; String key = findKey ( context , script , batchConf ) ; if ( key != null ) { ExecutionScriptHandler < T > target = delegations . get ( key ) ; if ( target != null ) { return target ; } throw new IOException ( MessageFormat . format ( "" + "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , script == null ? LABEL_UNDEFINED : script . getId ( ) , key ) ) ; } ExecutionScriptHandler < T > defaultTarget = delegations . get ( PREFIX_DEFAULT ) ; assert defaultTarget != null ; return defaultTarget ; } private String findKey ( ExecutionContext context , ExecutionScript script , Properties batchConf ) { if ( batchConf != null ) { for ( FindPattern pattern : FindPattern . values ( ) ) { String key = pattern . getKey ( context , script ) ; if ( key == null ) { continue ; } String value = batchConf . getProperty ( key ) ; if ( value == null ) { continue ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , new Object [ ] { context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , script == null ? LABEL_UNDEFINED : script . getId ( ) , key , value , } ) ; } return value ; } } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , new Object [ ] { context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) . getSymbol ( ) , script == null ? LABEL_UNDEFINED : script . getId ( ) , } ) ; } return null ; } private Properties getBatchConf ( ExecutionContext context , ExecutionScript script ) throws IOException { assert context != null ; Map < String , Properties > cached = confCache . get ( ) ; if ( cached != null ) { String batchId = context . getBatchId ( ) ; synchronized ( this ) { if ( cached . containsKey ( batchId ) ) { return cached . get ( batchId ) ; } } } Properties batchConf = loadBatchConf ( context , script ) ; synchronized ( this ) { cached = confCache . get ( ) ; if ( cached == null ) { cached = new HashMap < String , Properties > ( ) ; confCache = new SoftReference < Map < String , Properties > > ( cached ) ; } cached . put ( context . getBatchId ( ) , batchConf ) ; } return batchConf ; } private Properties loadBatchConf ( ExecutionContext context , ExecutionScript script ) throws IOException { assert context != null ; String fileName = context . getBatchId ( ) + SUFFIX_CONF ; File file = new File ( confDirectory , fileName ) ; LOG . debug ( "" , context . getBatchId ( ) , file ) ; if ( file . isFile ( ) == false ) { LOG . debug ( "" , context . getBatchId ( ) , file ) ; return null ; } LOG . debug ( "" , context . getBatchId ( ) , file ) ; try { InputStream in = new FileInputStream ( file ) ; try { Properties properties = new Properties ( ) ; properties . load ( in ) ; return properties ; } finally { in . close ( ) ; } } catch ( IOException e ) { YSLOG . error ( e , "" , context . getBatchId ( ) , file . getAbsolutePath ( ) ) ; throw e ; } } @ Override public String getResourceId ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException { ExecutionScriptHandler < T > target = resolve ( context , script ) ; return target . getResourceId ( context , script ) ; } @ Override public Map < String , String > getProperties ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException { ExecutionScriptHandler < T > target = resolve ( context , script ) ; return target . getProperties ( context , script ) ; } @ Override public Map < String , String > getEnvironmentVariables ( ExecutionContext context , ExecutionScript script ) throws InterruptedException , IOException { ExecutionScriptHandler < T > target = resolve ( context , script ) ; return target . getEnvironmentVariables ( context , script ) ; } @ Override public void setUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { ExecutionScriptHandler < T > target ; if ( forceSetUp != null ) { target = delegations . get ( forceSetUp ) ; } else { target = resolve ( context , null ) ; } assert target != null ; YSLOG . info ( "" , target . getHandlerId ( ) , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) ) ; target . setUp ( monitor , context ) ; } @ Override public void execute ( ExecutionMonitor monitor , ExecutionContext context , T script ) throws InterruptedException , IOException { ExecutionScriptHandler < T > target = resolve ( context , script ) ; assert target != null ; YSLOG . info ( "" , target . getHandlerId ( ) , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) , script . getId ( ) ) ; target . execute ( monitor , context , script ) ; } @ Override public void cleanUp ( ExecutionMonitor monitor , ExecutionContext context ) throws InterruptedException , IOException { ExecutionScriptHandler < T > target ; if ( forceCleanUp != null ) { target = delegations . get ( forceCleanUp ) ; } else { target = resolve ( context , null ) ; } assert target != null ; YSLOG . info ( "" , target . getHandlerId ( ) , context . getBatchId ( ) , context . getFlowId ( ) , context . getPhase ( ) , context . getExecutionId ( ) ) ; target . cleanUp ( monitor , context ) ; } private enum FindPattern { STAGE { @ Override String getKey ( ExecutionContext context , ExecutionScript script ) { if ( script == null ) { return null ; } return MessageFormat . format ( "" , context . getFlowId ( ) , context . getPhase ( ) . getSymbol ( ) , script . getId ( ) ) ; } } , PHASE { @ Override String getKey ( ExecutionContext context , ExecutionScript script ) { return MessageFormat . format ( "" , context . getFlowId ( ) , context . getPhase ( ) . getSymbol ( ) , WILDCARD ) ; } } , FLOW { @ Override String getKey ( ExecutionContext context , ExecutionScript script ) { return MessageFormat . format ( "" , context . getFlowId ( ) , WILDCARD ) ; } } , BATCH { @ Override String getKey ( ExecutionContext context , ExecutionScript script ) { return WILDCARD ; } } , ; private static final String WILDCARD = "" ; abstract String getKey ( ExecutionContext context , ExecutionScript script ) ; } } package com . asakusafw . yaess . multidispatch ; import com . asakusafw . yaess . core . CommandScript ; import com . asakusafw . yaess . core . CommandScriptHandler ; public class CommandScriptHandlerDispatcher extends ExecutionScriptHandlerDispatcher < CommandScript > implements CommandScriptHandler { public CommandScriptHandlerDispatcher ( ) { super ( CommandScriptHandler . class ) ; } } package com . asakusafw . yaess . multidispatch ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . yaess . core . YaessLogger ; public class YaessMultiDispatchLogger extends YaessLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public YaessMultiDispatchLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . yaess . multidispatch ; import com . asakusafw . yaess . core . HadoopScript ; import com . asakusafw . yaess . core . HadoopScriptHandler ; public class HadoopScriptHandlerDispatcher extends ExecutionScriptHandlerDispatcher < HadoopScript > implements HadoopScriptHandler { public HadoopScriptHandlerDispatcher ( ) { super ( HadoopScriptHandler . class ) ; } } package com . asakusafw . yaess . flowlog ; package com . asakusafw . yaess . flowlog ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . yaess . core . YaessLogger ; public class YaessFlowLogLogger extends YaessLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public YaessFlowLogLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override public String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . yaess . flowlog ; import java . io . File ; import java . nio . charset . Charset ; import java . text . DateFormat ; import java . text . MessageFormat ; import java . text . SimpleDateFormat ; import java . util . Map ; import java . util . TreeMap ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ServiceProfile ; public class FlowLoggerProfile { static final String KEY_DIRECTORY = "" ; static final String KEY_ENCODING = "" ; static final String KEY_STEP_UNIT = "" ; static final String KEY_DATE_FORMAT = "" ; static final String KEY_REPORT_JOB = "" ; static final String KEY_DELETE_ON_SETUP = "" ; static final String KEY_DELETE_ON_CLEANUP = "" ; static final String DEFAULT_ENCODING = "" ; static final String DEFAULT_STEP_UNIT = "" ; static final String DEFAULT_DATE_FORMAT = "" ; static final String DEFAULT_REPORT_JOB = "" ; static final String DEFAULT_DELETE_ON_SETUP = "" ; static final String DEFAULT_DELETE_ON_CLEANUP = "" ; private final File directory ; private final Charset encoding ; private final DateFormat dateFormat ; private final double stepUnit ; private final boolean reportJob ; private final boolean deleteOnSetup ; private final boolean deleteOnCleanup ; FlowLoggerProfile ( File directory , Charset encoding , DateFormat dateFormat , double stepUnit , boolean reportJob , boolean deleteOnSetup , boolean deleteOnCleanup ) { if ( directory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( encoding == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dateFormat == null ) { throw new IllegalArgumentException ( "" ) ; } this . directory = directory ; this . encoding = encoding ; this . dateFormat = dateFormat ; this . stepUnit = stepUnit ; this . reportJob = reportJob ; this . deleteOnSetup = deleteOnSetup ; this . deleteOnCleanup = deleteOnCleanup ; } public File getDirectory ( ) { return directory ; } public Charset getEncoding ( ) { return encoding ; } public DateFormat getDateFormat ( ) { return ( DateFormat ) dateFormat . clone ( ) ; } public double getStepUnit ( ) { return stepUnit ; } public boolean isReportJob ( ) { return reportJob ; } public boolean isDeleteOnSetup ( ) { return deleteOnSetup ; } public boolean isDeleteOnCleanup ( ) { return deleteOnCleanup ; } public File getLogFile ( ExecutionContext context ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } return getFile ( context , "" ) ; } public File getEscapeFile ( ExecutionContext context ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } return getFile ( context , "" ) ; } private File getFile ( ExecutionContext context , String dirName ) { assert context != null ; assert dirName != null ; File base = new File ( getDirectory ( ) , context . getBatchId ( ) ) ; File ongoing = new File ( base , dirName ) ; File log = new File ( ongoing , context . getFlowId ( ) ) ; return log ; } public static FlowLoggerProfile convert ( ServiceProfile < ? > profile ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } Map < String , String > copy = new TreeMap < String , String > ( profile . getConfiguration ( ) ) ; String dirString = extract ( profile , copy , KEY_DIRECTORY , null ) ; String encString = extract ( profile , copy , KEY_ENCODING , DEFAULT_ENCODING ) ; String dfString = extract ( profile , copy , KEY_DATE_FORMAT , DEFAULT_DATE_FORMAT ) ; double stepUnit = extractDouble ( profile , copy , KEY_STEP_UNIT , DEFAULT_STEP_UNIT ) ; boolean reportJob = extractBoolean ( profile , copy , KEY_REPORT_JOB , DEFAULT_REPORT_JOB ) ; boolean deleteOnSetup = extractBoolean ( profile , copy , KEY_DELETE_ON_SETUP , DEFAULT_DELETE_ON_SETUP ) ; boolean deleteOnCleanup = extractBoolean ( profile , copy , KEY_DELETE_ON_CLEANUP , DEFAULT_DELETE_ON_CLEANUP ) ; if ( copy . isEmpty ( ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , copy ) ) ; } File file = new File ( dirString ) ; Charset encoding ; try { encoding = Charset . forName ( encString ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , KEY_ENCODING , encString ) , e ) ; } DateFormat dateFormat ; try { dateFormat = new SimpleDateFormat ( dfString ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , KEY_DATE_FORMAT , dfString ) , e ) ; } return new FlowLoggerProfile ( file , encoding , dateFormat , stepUnit , reportJob , deleteOnSetup , deleteOnCleanup ) ; } private static String extract ( ServiceProfile < ? > profile , Map < String , String > copy , String key , String defaultValue ) { String value = profile . normalize ( key , copy . remove ( key ) , defaultValue == null , true ) ; if ( value == null ) { assert defaultValue != null ; return defaultValue ; } return value ; } private static double extractDouble ( ServiceProfile < ? > profile , Map < String , String > copy , String key , String defaultValue ) { String value = extract ( profile , copy , key , defaultValue ) ; try { return Double . parseDouble ( value ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , key , value ) , e ) ; } } private static boolean extractBoolean ( ServiceProfile < ? > profile , Map < String , String > copy , String key , String defaultValue ) { String value = extract ( profile , copy , key , defaultValue ) ; if ( value . equalsIgnoreCase ( "" ) ) { return true ; } else if ( value . equals ( "" ) ) { return false ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getPrefix ( ) , key , value ) ) ; } } } package com . asakusafw . yaess . flowlog ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitorProvider ; import com . asakusafw . yaess . core . PhaseMonitor ; import com . asakusafw . yaess . core . ServiceProfile ; public class FlowLoggerProvider extends ExecutionMonitorProvider { private volatile FlowLoggerProfile logProfile ; @ Override protected void doConfigure ( ServiceProfile < ? > profile ) throws InterruptedException , IOException { try { this . logProfile = FlowLoggerProfile . convert ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getPrefix ( ) , profile . getServiceClass ( ) . getName ( ) ) , e ) ; } } @ Override public PhaseMonitor newInstance ( ExecutionContext context ) throws InterruptedException , IOException { return new FlowLogger ( context , logProfile ) ; } } package com . asakusafw . yaess . flowlog ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . io . Writer ; import java . nio . charset . Charset ; import java . text . DateFormat ; import java . text . MessageFormat ; import java . util . Date ; import java . util . ResourceBundle ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . PhaseMonitor ; import com . asakusafw . yaess . core . YaessLogger ; public class FlowLogger extends PhaseMonitor { static final YaessLogger YSLOG = new YaessFlowLogLogger ( FlowLogger . class ) ; static final Logger LOG = LoggerFactory . getLogger ( FlowLogger . class ) ; private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; private static final double MIN_STEP_UNIT = ; private static final double DELTA_STEP_UNIT = ; private final ExecutionContext context ; private final String label ; private final double stepUnit ; private double totalTaskSize ; private double workedTaskSize ; private int workedStep = ; private boolean opened ; private boolean closed ; private final File file ; private final File escapeFile ; private PrintWriter writer ; private final boolean reportJob ; private final boolean deleteOnCleanup ; private JobStatus worstStatus ; private Throwable occurredException ; private final DateFormat dateFormat ; private final Charset encoding ; private final boolean deleteOnSetup ; public FlowLogger ( ExecutionContext context , FlowLoggerProfile profile ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } this . context = context ; this . label = MessageFormat . format ( "" , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) ) ; if ( profile . getStepUnit ( ) <= ) { this . stepUnit = Double . MAX_VALUE ; } else { this . stepUnit = Math . max ( profile . getStepUnit ( ) , MIN_STEP_UNIT ) - DELTA_STEP_UNIT ; } this . file = profile . getLogFile ( context ) ; this . escapeFile = profile . getEscapeFile ( context ) ; this . encoding = profile . getEncoding ( ) ; this . dateFormat = profile . getDateFormat ( ) ; this . reportJob = profile . isReportJob ( ) ; this . deleteOnSetup = profile . isDeleteOnSetup ( ) ; this . deleteOnCleanup = profile . isDeleteOnCleanup ( ) ; this . worstStatus = JobStatus . SUCCESS ; this . occurredException = null ; } @ Override public synchronized void open ( double taskSize ) throws IOException { if ( opened ) { throw new IllegalStateException ( MessageFormat . format ( "" , label ) ) ; } opened = true ; prepareParentDirectory ( file ) ; boolean keepLogs = deleteOnSetup == false || context . getPhase ( ) != ExecutionPhase . SETUP ; if ( keepLogs == false ) { cleanEscapedLog ( ) ; } OutputStream output = new FileOutputStream ( file , keepLogs ) ; boolean succeed = false ; try { Writer w = new OutputStreamWriter ( output , encoding ) ; this . writer = new PrintWriter ( new BufferedWriter ( w ) ) ; succeed = true ; } finally { if ( succeed == false ) { output . close ( ) ; } } this . totalTaskSize = taskSize ; record ( Level . INFO , Target . PHASE , Trigger . START ) ; } @ Override public synchronized void progressed ( double deltaSize ) { set ( workedTaskSize + deltaSize ) ; } @ Override public synchronized void setProgress ( double workedSize ) { set ( workedSize ) ; } @ Override protected void onJobMonitorOpened ( String jobId ) { if ( jobId == null ) { throw new IllegalArgumentException ( "" ) ; } record ( Level . INFO , Target . JOB , Trigger . START , jobId ) ; } @ Override protected void onJobMonitorClosed ( String jobId ) { return ; } @ Override public void reportJobStatus ( String jobId , JobStatus status , Throwable cause ) throws IOException { if ( jobId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( status == null ) { throw new IllegalArgumentException ( "" ) ; } record ( cause , toLevel ( status ) , Target . JOB , Trigger . FINISH , jobId , status ) ; if ( status . compareTo ( worstStatus ) > ) { worstStatus = status ; } if ( cause != null && occurredException == null ) { occurredException = cause ; } } @ Override public synchronized void close ( ) throws IOException { if ( closed ) { if ( writer != null ) { writer . close ( ) ; writer = null ; } return ; } closed = true ; set ( totalTaskSize ) ; record ( occurredException , toLevel ( worstStatus ) , Target . PHASE , Trigger . FINISH , worstStatus ) ; if ( writer != null ) { writer . close ( ) ; writer = null ; } if ( context . getPhase ( ) == ExecutionPhase . CLEANUP && worstStatus == JobStatus . SUCCESS ) { if ( deleteOnCleanup ) { cleanCurrentLog ( ) ; } else { cleanEscapedLog ( ) ; escapeCurrentLog ( ) ; } } } private void prepareParentDirectory ( File f ) { assert f != null ; File parent = f . getParentFile ( ) ; if ( parent . mkdirs ( ) == false ) { if ( parent . isDirectory ( ) == false ) { YSLOG . warn ( "" , label , parent . getAbsolutePath ( ) ) ; } } } private void cleanCurrentLog ( ) { if ( file . exists ( ) ) { YSLOG . info ( "" , label , file . getAbsolutePath ( ) ) ; if ( file . delete ( ) == false && file . exists ( ) ) { YSLOG . warn ( "" , label , file . getAbsolutePath ( ) ) ; } } } private void cleanEscapedLog ( ) { if ( escapeFile . exists ( ) ) { YSLOG . info ( "" , label , escapeFile . getAbsolutePath ( ) ) ; if ( escapeFile . delete ( ) == false && escapeFile . exists ( ) ) { YSLOG . warn ( "" , label , escapeFile . getAbsolutePath ( ) ) ; } } } private void escapeCurrentLog ( ) { YSLOG . info ( "" , label , file . getAbsolutePath ( ) , escapeFile . getAbsolutePath ( ) ) ; prepareParentDirectory ( escapeFile ) ; if ( file . renameTo ( escapeFile ) == false ) { YSLOG . warn ( "" , label , file . getAbsolutePath ( ) , escapeFile . getAbsolutePath ( ) ) ; } } private void set ( double workedSize ) { double normalized = Math . max ( , Math . min ( totalTaskSize , workedSize ) ) ; double relative = normalized / totalTaskSize ; int step = ( int ) Math . floor ( relative / stepUnit ) ; if ( step != workedStep && closed == false ) { record ( Level . INFO , Target . PHASE , Trigger . STEP , String . format ( "" , relative * ) ) ; } this . workedTaskSize = normalized ; this . workedStep = step ; } private Level toLevel ( JobStatus status ) { assert status != null ; switch ( status ) { case SUCCESS : return Level . INFO ; case FAILED : return Level . ERROR ; case CANCELLED : return Level . ERROR ; default : throw new AssertionError ( status ) ; } } private void record ( Level level , Target target , Trigger trigger , Object ... arguments ) { record ( null , level , target , trigger , arguments ) ; } private synchronized void record ( Throwable t , Level level , Target target , Trigger trigger , Object ... arguments ) { if ( target == Target . JOB && reportJob == false ) { return ; } String pattern = BUNDLE . getString ( target . name ( ) + trigger . name ( ) ) ; String message = MessageFormat . format ( pattern , arguments ) ; String record = MessageFormat . format ( "" , now ( ) , level , trigger , context . getPhase ( ) . name ( ) , target , message , context . getBatchId ( ) , context . getFlowId ( ) , context . getExecutionId ( ) , context . getPhase ( ) ) ; record ( t , record ) ; } private synchronized void record ( Throwable exception , String message ) { LOG . debug ( message , exception ) ; writer . println ( message ) ; if ( exception != null ) { exception . printStackTrace ( writer ) ; } writer . flush ( ) ; } private String now ( ) { return dateFormat . format ( new Date ( ) ) ; } private enum Level { INFO , WARN , ERROR , } private enum Target { PHASE , JOB , } private enum Trigger { START , STEP , FINISH , } } package com . asakusafw . yaess . flowlog ; import static com . asakusafw . yaess . core . ExecutionPhase . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . nio . charset . Charset ; import java . text . SimpleDateFormat ; import java . util . Collections ; import java . util . Scanner ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . yaess . core . ExecutionContext ; import com . asakusafw . yaess . core . ExecutionMonitor ; import com . asakusafw . yaess . core . ExecutionPhase ; import com . asakusafw . yaess . core . PhaseMonitor . JobStatus ; public class FlowLoggerTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { FlowLoggerProfile profile = profile ( false , false , false ) ; File log = profile . getLogFile ( context ( MAIN ) ) ; File escape = profile . getEscapeFile ( context ( MAIN ) ) ; int l00 = ; FlowLogger log1 = new FlowLogger ( context ( MAIN ) , profile ) ; log1 . open ( ) ; int l11 = checkLines ( log , l00 , MAIN ) ; log1 . close ( ) ; int l12 = checkLines ( log , l11 , MAIN ) ; FlowLogger log2 = new FlowLogger ( context ( CLEANUP ) , profile ) ; log2 . open ( ) ; int l21 = checkLines ( log , l12 , CLEANUP ) ; log2 . close ( ) ; assertThat ( log . isFile ( ) , is ( false ) ) ; checkLines ( escape , l21 , CLEANUP ) ; } @ Test public void chain ( ) throws Exception { FlowLoggerProfile profile = profile ( false , false , false ) ; File log = profile . getLogFile ( context ( MAIN ) ) ; File escape = profile . getEscapeFile ( context ( MAIN ) ) ; int l00 = ; FlowLogger log1 = new FlowLogger ( context ( MAIN ) , profile ) ; log1 . open ( ) ; int l11 = checkLines ( log , l00 , MAIN ) ; log1 . close ( ) ; int l12 = checkLines ( log , l11 , MAIN ) ; FlowLogger log2 = new FlowLogger ( context ( CLEANUP ) , profile ) ; log2 . open ( ) ; int l21 = checkLines ( log , l12 , CLEANUP ) ; log2 . close ( ) ; assertThat ( log . isFile ( ) , is ( false ) ) ; checkLines ( escape , l21 , CLEANUP ) ; FlowLogger log3 = new FlowLogger ( context ( SETUP ) , profile ) ; log3 . open ( ) ; int l31 = checkLines ( log , l00 , SETUP ) ; log3 . close ( ) ; checkLines ( log , l31 , SETUP ) ; } @ Test public void deleteOnSetup ( ) throws Exception { FlowLoggerProfile profile = profile ( false , true , false ) ; File log = profile . getLogFile ( context ( MAIN ) ) ; int l00 = ; FlowLogger log1 = new FlowLogger ( context ( MAIN ) , profile ) ; log1 . open ( ) ; int l11 = checkLines ( log , l00 , MAIN ) ; log1 . close ( ) ; int l12 = checkLines ( log , l11 , MAIN ) ; FlowLogger log2 = new FlowLogger ( context ( SETUP ) , profile ) ; log2 . open ( ) ; int l21 = checkLines ( log , l00 , SETUP ) ; log2 . close ( ) ; checkLines ( log , l21 , SETUP ) ; assertThat ( l21 , is ( lessThan ( l12 ) ) ) ; } @ Test public void deleteOnCleanup ( ) throws Exception { FlowLoggerProfile profile = profile ( false , true , true ) ; File log = profile . getLogFile ( context ( MAIN ) ) ; File escape = profile . getEscapeFile ( context ( MAIN ) ) ; int l00 = ; FlowLogger log1 = new FlowLogger ( context ( MAIN ) , profile ) ; log1 . open ( ) ; int l11 = checkLines ( log , l00 , MAIN ) ; log1 . close ( ) ; int l12 = checkLines ( log , l11 , MAIN ) ; FlowLogger log2 = new FlowLogger ( context ( CLEANUP ) , profile ) ; log2 . open ( ) ; checkLines ( log , l12 , CLEANUP ) ; log2 . close ( ) ; assertThat ( log . isFile ( ) , is ( false ) ) ; assertThat ( escape . isFile ( ) , is ( false ) ) ; } @ Test public void deleteOnCleanup_error ( ) throws Exception { FlowLoggerProfile profile = profile ( true , true , true ) ; File log = profile . getLogFile ( context ( MAIN ) ) ; File escape = profile . getEscapeFile ( context ( MAIN ) ) ; int l00 = ; FlowLogger log1 = new FlowLogger ( context ( MAIN ) , profile ) ; log1 . open ( ) ; int l11 = checkLines ( log , l00 , MAIN ) ; log1 . close ( ) ; int l12 = checkLines ( log , l11 , MAIN ) ; FlowLogger log2 = new FlowLogger ( context ( CLEANUP ) , profile ) ; log2 . open ( ) ; try { checkLines ( log , l12 , CLEANUP ) ; ExecutionMonitor jm = log2 . createJobMonitor ( "" , ) ; jm . open ( ) ; jm . close ( ) ; log2 . reportJobStatus ( "" , JobStatus . FAILED , new Exception ( ) ) ; } finally { log2 . close ( ) ; } assertThat ( log . isFile ( ) , is ( true ) ) ; assertThat ( escape . isFile ( ) , is ( false ) ) ; } private int checkLines ( File log , int last , ExecutionPhase phase ) throws IOException { int count = ; boolean found = false ; assertThat ( log . isFile ( ) , is ( true ) ) ; String pattern = phase . toString ( ) ; Scanner scanner = new Scanner ( log , "" ) ; while ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) ; if ( found == false && count >= last ) { found = line . indexOf ( pattern ) >= ; } count ++ ; } assertThat ( pattern , found , is ( true ) ) ; assertThat ( count , greaterThan ( last ) ) ; return count ; } private ExecutionContext context ( ExecutionPhase phase ) { return new ExecutionContext ( "" , "" , "" , phase , Collections . < String , String > emptyMap ( ) ) ; } private FlowLoggerProfile profile ( boolean reportJob , boolean deleteOnSetup , boolean deleteOnCleanup ) { return new FlowLoggerProfile ( folder . getRoot ( ) , Charset . forName ( "" ) , new SimpleDateFormat ( "" ) , , reportJob , deleteOnSetup , deleteOnCleanup ) ; } } package com . asakusafw . yaess . flowlog ; import static com . asakusafw . yaess . flowlog . FlowLoggerProfile . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . nio . charset . Charset ; import java . text . DateFormat ; import java . text . SimpleDateFormat ; import java . util . HashMap ; import java . util . Map ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . yaess . core . ProfileContext ; import com . asakusafw . yaess . core . ServiceProfile ; import com . asakusafw . yaess . core . VariableResolver ; public class FlowLoggerProfileTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void convert ( ) throws Exception { Map < String , String > conf = map ( KEY_DIRECTORY , folder . getRoot ( ) . getAbsolutePath ( ) ) ; Map < String , String > vars = map ( ) ; ServiceProfile < FlowLoggerProvider > sp = profile ( conf , vars ) ; FlowLoggerProfile profile = FlowLoggerProfile . convert ( sp ) ; assertThat ( profile . getDirectory ( ) . getCanonicalFile ( ) , is ( folder . getRoot ( ) . getCanonicalFile ( ) ) ) ; assertThat ( profile . getEncoding ( ) , is ( Charset . forName ( DEFAULT_ENCODING ) ) ) ; assertThat ( profile . getDateFormat ( ) , is ( ( DateFormat ) new SimpleDateFormat ( DEFAULT_DATE_FORMAT ) ) ) ; assertThat ( profile . getStepUnit ( ) , closeTo ( Double . parseDouble ( DEFAULT_STEP_UNIT ) , ) ) ; assertThat ( profile . isReportJob ( ) , is ( Boolean . parseBoolean ( DEFAULT_REPORT_JOB ) ) ) ; assertThat ( profile . isDeleteOnSetup ( ) , is ( Boolean . parseBoolean ( DEFAULT_DELETE_ON_SETUP ) ) ) ; assertThat ( profile . isDeleteOnCleanup ( ) , is ( Boolean . parseBoolean ( DEFAULT_DELETE_ON_CLEANUP ) ) ) ; } @ Test public void convert_all ( ) throws Exception { Map < String , String > conf = map ( KEY_DIRECTORY , folder . getRoot ( ) . getAbsolutePath ( ) , KEY_ENCODING , "" , KEY_DATE_FORMAT , "" , KEY_STEP_UNIT , "" , KEY_REPORT_JOB , "" , KEY_DELETE_ON_SETUP , "" , KEY_DELETE_ON_CLEANUP , "" ) ; Map < String , String > vars = map ( ) ; ServiceProfile < FlowLoggerProvider > sp = profile ( conf , vars ) ; FlowLoggerProfile profile = FlowLoggerProfile . convert ( sp ) ; assertThat ( profile . getDirectory ( ) . getCanonicalFile ( ) , is ( folder . getRoot ( ) . getCanonicalFile ( ) ) ) ; assertThat ( profile . getEncoding ( ) , is ( Charset . forName ( "" ) ) ) ; assertThat ( profile . getDateFormat ( ) , is ( ( DateFormat ) new SimpleDateFormat ( "" ) ) ) ; assertThat ( profile . getStepUnit ( ) , closeTo ( Double . parseDouble ( "" ) , ) ) ; assertThat ( profile . isReportJob ( ) , is ( Boolean . parseBoolean ( "" ) ) ) ; assertThat ( profile . isDeleteOnSetup ( ) , is ( Boolean . parseBoolean ( "" ) ) ) ; assertThat ( profile . isDeleteOnCleanup ( ) , is ( Boolean . parseBoolean ( "" ) ) ) ; } @ Test public void convert_param ( ) throws Exception { Map < String , String > conf = map ( KEY_DIRECTORY , "" , KEY_ENCODING , "" ) ; Map < String , String > vars = map ( "" , folder . getRoot ( ) . getAbsolutePath ( ) , "" , "" ) ; ServiceProfile < FlowLoggerProvider > sp = profile ( conf , vars ) ; FlowLoggerProfile profile = FlowLoggerProfile . convert ( sp ) ; assertThat ( profile . getDirectory ( ) . getCanonicalFile ( ) , is ( folder . getRoot ( ) . getCanonicalFile ( ) ) ) ; assertThat ( profile . getEncoding ( ) , is ( Charset . forName ( "" ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_empty ( ) { Map < String , String > conf = map ( ) ; Map < String , String > vars = map ( ) ; ServiceProfile < FlowLoggerProvider > sp = profile ( conf , vars ) ; FlowLoggerProfile . convert ( sp ) ; } ServiceProfile < FlowLoggerProvider > profile ( Map < String , String > conf , Map < String , String > vars ) { ServiceProfile < FlowLoggerProvider > profile = new ServiceProfile < FlowLoggerProvider > ( "" , FlowLoggerProvider . class , conf , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new VariableResolver ( vars ) ) ) ; return profile ; } private Map < String , String > map ( String ... keyValuePairs ) { assert keyValuePairs . length % == ; Map < String , String > results = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length ; i += ) { results . put ( keyValuePairs [ i + ] , keyValuePairs [ i + ] ) ; } return results ; } } package com . asakusafw . compiler . tool . analysis ; import java . io . Closeable ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . UUID ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Reduce ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Stage ; import com . asakusafw . compiler . flow . stage . StageModel . Factor ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . MapUnit ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . batch . WorkDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription . Declaration ; public class VisualizeCompiledStructureProcessor extends AbstractWorkflowProcessor { static final Logger LOG = LoggerFactory . getLogger ( VisualizeCompiledStructureProcessor . class ) ; static final Charset ENCODING = Charset . forName ( "" ) ; public static final String NAIVE_PATH = Constants . PATH_BATCH + "" ; public static final String MERGED_PATH = Constants . PATH_BATCH + "" ; @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( JobFlowWorkDescriptionProcessor . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { process ( workflow , NAIVE_PATH , false ) ; process ( workflow , MERGED_PATH , true ) ; } void process ( Workflow workflow , String path , boolean merged ) throws IOException { OutputStream output = getEnvironment ( ) . openResource ( path ) ; try { Context context = new Context ( output , merged ) ; context . put ( "" ) ; context . push ( ) ; context . put ( "" ) ; Class < ? extends BatchDescription > desc = workflow . getDescription ( ) . getClass ( ) ; String batchId = context . label ( desc , "" , getEnvironment ( ) . getConfiguration ( ) . getBatchId ( ) ) ; dump ( context , batchId , workflow . getGraph ( ) ) ; context . pop ( ) ; context . put ( "" ) ; context . close ( ) ; } finally { output . close ( ) ; } } private void dump ( Context context , String batchId , Graph < Workflow . Unit > graph ) { assert context != null ; assert graph != null ; for ( Workflow . Unit unit : Graphs . sortPostOrder ( graph ) ) { String flowId = dumpUnit ( context , unit ) ; context . connect ( batchId , flowId ) ; } } private String dumpUnit ( Context context , Workflow . Unit unit ) { assert context != null ; assert unit != null ; WorkDescription desc = unit . getDescription ( ) ; if ( desc instanceof JobFlowWorkDescription ) { return dumpDescription ( context , ( JobFlowWorkDescription ) desc , ( JobflowModel ) unit . getProcessed ( ) ) ; } else { throw new AssertionError ( desc ) ; } } private String dumpDescription ( Context context , JobFlowWorkDescription desc , JobflowModel model ) { assert context != null ; assert desc != null ; assert model != null ; String id = context . label ( desc . getFlowClass ( ) , "" , model . getFlowId ( ) ) ; for ( Stage stage : model . getStages ( ) ) { String stageId = dumpStage ( context , stage ) ; context . connect ( id , stageId ) ; } return id ; } private String dumpStage ( Context context , Stage stage ) { assert context != null ; assert stage != null ; String id = context . label ( stage , "" , stage . getCompiled ( ) . getQualifiedName ( ) . toNameString ( ) ) ; for ( MapUnit unit : stage . getModel ( ) . getMapUnits ( ) ) { String unitId = context . label ( unit , "" , unit . getCompiled ( ) . getQualifiedName ( ) . toNameString ( ) ) ; context . connect ( id , unitId ) ; for ( Fragment fragment : unit . getFragments ( ) ) { String fragmentId = dumpFragment ( context , fragment ) ; context . connect ( unitId , fragmentId ) ; } } Reduce reducer = stage . getReduceOrNull ( ) ; if ( reducer != null ) { String unitId = context . label ( reducer , "" , reducer . getReducerTypeName ( ) . toNameString ( ) ) ; context . connect ( id , unitId ) ; for ( ReduceUnit unit : stage . getModel ( ) . getReduceUnits ( ) ) { for ( Fragment fragment : unit . getFragments ( ) ) { String fragmentId = dumpFragment ( context , fragment ) ; context . connect ( unitId , fragmentId ) ; } } } return id ; } private String dumpFragment ( Context context , Fragment fragment ) { assert context != null ; assert fragment != null ; String id = context . label ( fragment , "" , fragment . getCompiled ( ) . getQualifiedName ( ) . toNameString ( ) ) ; for ( Factor factor : fragment . getFactors ( ) ) { String factorId = dumpFactor ( context , factor ) ; if ( factorId != null ) { context . connect ( id , factorId ) ; } } return id ; } private String dumpFactor ( Context context , Factor factor ) { FlowElementDescription desc = factor . getElement ( ) . getDescription ( ) ; switch ( desc . getKind ( ) ) { case OPERATOR : Declaration decl = ( ( OperatorDescription ) desc ) . getDeclaration ( ) ; if ( decl . getDeclaring ( ) . getName ( ) . startsWith ( "" ) == false ) { String id = context . label ( decl . toMethod ( ) , decl . getAnnotationType ( ) . getSimpleName ( ) , MessageFormat . format ( "" , decl . getDeclaring ( ) . getSimpleName ( ) , decl . toMethod ( ) . getName ( ) ) ) ; return id ; } return null ; case FLOW_COMPONENT : case INPUT : case OUTPUT : case PSEUD : return null ; default : throw new AssertionError ( ) ; } } private static class Context implements Closeable { private final PrintWriter writer ; private final boolean merged ; private final Map < Object , String > ids = Maps . create ( ) ; private final Set < String > sawConnections = Sets . create ( ) ; private int indent = ; Context ( OutputStream output , boolean merged ) { assert output != null ; this . writer = new PrintWriter ( new OutputStreamWriter ( output , ENCODING ) ) ; this . merged = merged ; } void push ( ) { indent ++ ; } void pop ( ) { if ( indent == ) { throw new IllegalStateException ( ) ; } indent -- ; } String label ( Object source , String kind , String detail ) { if ( merged == false ) { return newLabel ( kind , detail ) ; } else { String id = ids . get ( source ) ; if ( id == null ) { id = newLabel ( kind , detail ) ; ids . put ( source , id ) ; } return id ; } } String newLabel ( String kind , String detail ) { String id = UUID . randomUUID ( ) . toString ( ) ; put ( "" , id , kind , detail ) ; return id ; } void connect ( String src , String dst ) { if ( merged ) { String id = src + '' + dst ; if ( sawConnections . contains ( id ) == false ) { sawConnections . add ( id ) ; put ( "" , src , dst ) ; } } else { put ( "" , src , dst ) ; } } void put ( String pattern , Object ... arguments ) { assert pattern != null ; assert arguments != null ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = indent ; i < n ; i ++ ) { buf . append ( "" ) ; } if ( arguments . length == ) { buf . append ( pattern ) ; } else { buf . append ( MessageFormat . format ( pattern , arguments ) ) ; } String text = buf . toString ( ) ; writer . println ( text ) ; LOG . debug ( text ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } } } package com . asakusafw . compiler . tool . analysis ; import java . io . IOException ; import java . io . OutputStream ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . visualizer . VisualAnalyzer ; import com . asakusafw . compiler . flow . visualizer . VisualGraph ; import com . asakusafw . compiler . flow . visualizer . VisualGraphEmitter ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . batch . WorkDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class VisualizeJobflowStructureProcessor extends AbstractWorkflowProcessor { static final Logger LOG = LoggerFactory . getLogger ( VisualizeJobflowStructureProcessor . class ) ; static final Charset ENCODING = Charset . forName ( "" ) ; private static final String PATH_FLOW_GRAPH = Constants . PATH_JOBFLOW + "" ; private static final String PATH_STAGE_GRAPH = Constants . PATH_JOBFLOW + "" ; private static final String PATH_STAGE_BLOCK = Constants . PATH_JOBFLOW + "" ; @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( JobFlowWorkDescriptionProcessor . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { for ( Workflow . Unit unit : workflow . getGraph ( ) . getNodeSet ( ) ) { processUnit ( unit ) ; } } private void processUnit ( Workflow . Unit unit ) throws IOException { assert unit != null ; WorkDescription desc = unit . getDescription ( ) ; if ( desc instanceof JobFlowWorkDescription ) { processDescription ( ( JobFlowWorkDescription ) desc , ( JobflowModel ) unit . getProcessed ( ) ) ; } else { throw new AssertionError ( desc ) ; } } private void processDescription ( JobFlowWorkDescription desc , JobflowModel model ) throws IOException { assert desc != null ; assert model != null ; StageGraph stageGraph = model . getStageGraph ( ) ; processFlowGraph ( model . getFlowId ( ) , stageGraph . getInput ( ) . getSource ( ) . getOrigin ( ) ) ; processStageGraph ( model . getFlowId ( ) , stageGraph ) ; for ( StageBlock stage : stageGraph . getStages ( ) ) { processStageBlock ( model . getFlowId ( ) , stage ) ; } } private void processFlowGraph ( String flowId , FlowGraph graph ) throws IOException { assert flowId != null ; assert graph != null ; VisualGraph model = VisualAnalyzer . convertFlowGraph ( graph ) ; emit ( MessageFormat . format ( PATH_FLOW_GRAPH , flowId ) , false , model ) ; } private void processStageGraph ( String flowId , StageGraph graph ) throws IOException { assert flowId != null ; assert graph != null ; VisualGraph model = VisualAnalyzer . convertStageGraph ( graph ) ; emit ( MessageFormat . format ( PATH_STAGE_GRAPH , flowId ) , false , model ) ; } private void processStageBlock ( String flowId , StageBlock stage ) throws IOException { assert flowId != null ; assert stage != null ; VisualGraph model = VisualAnalyzer . convertStageBlock ( stage ) ; emit ( MessageFormat . format ( PATH_STAGE_BLOCK , flowId , String . valueOf ( stage . getStageNumber ( ) ) ) , true , model ) ; } private void emit ( String path , boolean partial , VisualGraph model ) throws IOException { assert path != null ; assert model != null ; OutputStream output = getEnvironment ( ) . openResource ( path ) ; try { VisualGraphEmitter . emit ( model , partial , output ) ; } finally { output . close ( ) ; } } } package com . asakusafw . compiler . tool . analysis ; final class Constants { public static final String PATH_PREFIX = "" ; public static final String PATH_BATCH = PATH_PREFIX + "" ; public static final String PATH_JOBFLOW = PATH_PREFIX + "" ; private Constants ( ) { return ; } } package com . asakusafw . compiler . tool . analysis ; package com . asakusafw . compiler . tool . analysis ; import java . io . Closeable ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Export ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Import ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Stage ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Factor ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . MapUnit ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . batch . WorkDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; public class DescribeCompiledStructureProcessor extends AbstractWorkflowProcessor { static final Logger LOG = LoggerFactory . getLogger ( DescribeCompiledStructureProcessor . class ) ; static final Charset ENCODING = Charset . forName ( "" ) ; public static final String PATH = Constants . PATH_BATCH + "" ; @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( JobFlowWorkDescriptionProcessor . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { OutputStream output = getEnvironment ( ) . openResource ( PATH ) ; try { Context context = new Context ( output ) ; context . put ( "" , getEnvironment ( ) . getConfiguration ( ) . getBatchId ( ) ) ; dump ( context , workflow . getGraph ( ) ) ; context . close ( ) ; } finally { output . close ( ) ; } } private void dump ( Context context , Graph < Workflow . Unit > graph ) { assert context != null ; assert graph != null ; for ( Workflow . Unit unit : Graphs . sortPostOrder ( graph ) ) { dumpUnit ( context , unit ) ; } } private void dumpUnit ( Context context , Workflow . Unit unit ) { assert context != null ; assert unit != null ; WorkDescription desc = unit . getDescription ( ) ; if ( desc instanceof JobFlowWorkDescription ) { dumpDescription ( context , ( JobFlowWorkDescription ) desc , ( JobflowModel ) unit . getProcessed ( ) ) ; } else { throw new AssertionError ( desc ) ; } } private void dumpDescription ( Context context , JobFlowWorkDescription desc , JobflowModel model ) { assert context != null ; assert desc != null ; assert model != null ; context . put ( "" , model . getFlowId ( ) ) ; context . push ( ) ; context . put ( "" ) ; context . push ( ) ; writeInput ( context , model ) ; context . pop ( ) ; context . put ( "" ) ; context . push ( ) ; writeOutput ( context , model ) ; context . pop ( ) ; context . put ( "" ) ; context . push ( ) ; writeBody ( context , model ) ; context . pop ( ) ; context . pop ( ) ; } private void writeInput ( Context context , JobflowModel model ) { for ( Import ext : model . getImports ( ) ) { context . put ( "" , ext . getDescription ( ) . getName ( ) , ext . getDescription ( ) . getImporterDescription ( ) . getClass ( ) . getName ( ) ) ; } } private void writeOutput ( Context context , JobflowModel model ) { for ( Export ext : model . getExports ( ) ) { context . put ( "" , ext . getDescription ( ) . getName ( ) , ext . getDescription ( ) . getExporterDescription ( ) . getClass ( ) . getName ( ) ) ; } } private void writeBody ( Context context , JobflowModel model ) { assert model != null ; context . put ( "" ) ; context . push ( ) ; writeCompiledStages ( context , model . getCompiled ( ) . getPrologueStages ( ) ) ; context . pop ( ) ; context . put ( "" ) ; context . push ( ) ; writeStages ( context , model ) ; context . pop ( ) ; context . put ( "" ) ; context . push ( ) ; writeCompiledStages ( context , model . getCompiled ( ) . getEpilogueStages ( ) ) ; context . pop ( ) ; } private void writeStages ( Context context , JobflowModel model ) { Graph < Stage > predGraph = model . getDependencyGraph ( ) ; Graph < Stage > succGraph = Graphs . transpose ( predGraph ) ; for ( Stage stage : model . getStages ( ) ) { context . put ( "" , stage . getCompiled ( ) . getQualifiedName ( ) . toNameString ( ) ) ; context . push ( ) ; for ( Stage pred : sort ( predGraph . getConnected ( stage ) ) ) { context . put ( "" , pred . getCompiled ( ) . getQualifiedName ( ) . toNameString ( ) ) ; } for ( Stage succ : sort ( succGraph . getConnected ( stage ) ) ) { context . put ( "" , succ . getCompiled ( ) . getQualifiedName ( ) . toNameString ( ) ) ; } writeStageBody ( context , stage ) ; context . pop ( ) ; } } private List < Stage > sort ( Set < Stage > stages ) { List < Stage > results = Lists . create ( ) ; Collections . sort ( results , new Comparator < Stage > ( ) { @ Override public int compare ( Stage o1 , Stage o2 ) { return o1 . getCompiled ( ) . getStageId ( ) . compareTo ( o2 . getCompiled ( ) . getStageId ( ) ) ; } } ) ; return results ; } private void writeStageBody ( Context context , Stage stage ) { StageModel model = stage . getModel ( ) ; for ( MapUnit unit : model . getMapUnits ( ) ) { context . put ( "" , name ( unit . getCompiled ( ) . getQualifiedName ( ) ) ) ; context . push ( ) ; writeFragments ( context , unit . getFragments ( ) ) ; context . pop ( ) ; } if ( stage . getReduceOrNull ( ) != null ) { context . put ( "" , name ( stage . getReduceOrNull ( ) . getReducerTypeName ( ) ) ) ; context . push ( ) ; for ( ReduceUnit unit : model . getReduceUnits ( ) ) { writeFragments ( context , unit . getFragments ( ) ) ; } context . pop ( ) ; } } private String name ( Name name ) { if ( name == null ) { return "" ; } return name . toNameString ( ) ; } private void writeFragments ( Context context , List < Fragment > fragments ) { for ( Fragment fragment : fragments ) { context . put ( "" , name ( fragment . getCompiled ( ) . getQualifiedName ( ) ) ) ; context . push ( ) ; for ( Factor factor : fragment . getFactors ( ) ) { FlowElementDescription description = factor . getElement ( ) . getDescription ( ) ; if ( description . getKind ( ) != FlowElementKind . PSEUD ) { context . put ( "" , description . getKind ( ) . name ( ) . toLowerCase ( ) , description ) ; context . push ( ) ; for ( FlowResourceDescription resource : factor . getElement ( ) . getDescription ( ) . getResources ( ) ) { for ( InputDescription input : resource . getSideDataInputs ( ) ) { context . put ( "" , input . getName ( ) , input . getImporterDescription ( ) . getClass ( ) . getName ( ) ) ; } } context . pop ( ) ; } } context . pop ( ) ; } } private void writeCompiledStages ( Context context , List < CompiledStage > stages ) { for ( CompiledStage stage : stages ) { context . put ( "" , stage . getQualifiedName ( ) . toNameString ( ) ) ; } } private static class Context implements Closeable { private final PrintWriter writer ; private int indent = ; public Context ( OutputStream output ) { assert output != null ; writer = new PrintWriter ( new OutputStreamWriter ( output , ENCODING ) ) ; } public void push ( ) { indent ++ ; } public void pop ( ) { if ( indent == ) { throw new IllegalStateException ( ) ; } indent -- ; } public void put ( String pattern , Object ... arguments ) { assert pattern != null ; assert arguments != null ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = indent ; i < n ; i ++ ) { buf . append ( "" ) ; } if ( arguments . length == ) { buf . append ( pattern ) ; } else { buf . append ( MessageFormat . format ( pattern , arguments ) ) ; } String text = buf . toString ( ) ; writer . println ( text ) ; LOG . debug ( text ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } } } package com . asakusafw . compiler . tool . analysis ; import java . io . Closeable ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Export ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Import ; import com . asakusafw . compiler . flow . plan . FlowGraphUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . batch . WorkDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; public class DescribeOriginalStructureProcessor extends AbstractWorkflowProcessor { static final Logger LOG = LoggerFactory . getLogger ( DescribeOriginalStructureProcessor . class ) ; static final Charset ENCODING = Charset . forName ( "" ) ; public static final String PATH = Constants . PATH_BATCH + "" ; @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( JobFlowWorkDescriptionProcessor . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { OutputStream output = getEnvironment ( ) . openResource ( PATH ) ; try { Context context = new Context ( output ) ; context . put ( "" , getEnvironment ( ) . getConfiguration ( ) . getBatchId ( ) ) ; dump ( context , workflow . getGraph ( ) ) ; context . close ( ) ; } finally { output . close ( ) ; } } private void dump ( Context context , Graph < Workflow . Unit > graph ) { assert context != null ; assert graph != null ; for ( Workflow . Unit unit : Graphs . sortPostOrder ( graph ) ) { dumpUnit ( context , unit ) ; } } private void dumpUnit ( Context context , Workflow . Unit unit ) { assert context != null ; assert unit != null ; WorkDescription desc = unit . getDescription ( ) ; if ( desc instanceof JobFlowWorkDescription ) { dumpDescription ( context , ( JobFlowWorkDescription ) desc , ( JobflowModel ) unit . getProcessed ( ) ) ; } else { throw new AssertionError ( desc ) ; } } private void dumpDescription ( Context context , JobFlowWorkDescription desc , JobflowModel model ) { assert context != null ; assert desc != null ; assert model != null ; context . put ( "" , model . getFlowId ( ) ) ; context . push ( ) ; context . put ( "" ) ; context . push ( ) ; writeInput ( context , model ) ; context . pop ( ) ; context . put ( "" ) ; context . push ( ) ; writeOutput ( context , model ) ; context . pop ( ) ; writeFlow ( context , model . getStageGraph ( ) . getInput ( ) . getSource ( ) . getOrigin ( ) ) ; context . pop ( ) ; } private void writeFlow ( Context context , FlowGraph flow ) { context . put ( "" , flow . getDescription ( ) . getName ( ) ) ; context . push ( ) ; for ( FlowElement element : FlowGraphUtil . collectElements ( flow ) ) { FlowElementDescription desc = element . getDescription ( ) ; switch ( desc . getKind ( ) ) { case INPUT : case OUTPUT : case OPERATOR : context . put ( "" , desc . getKind ( ) . name ( ) . toLowerCase ( ) , desc . toString ( ) ) ; break ; case FLOW_COMPONENT : writeFlow ( context , ( ( FlowPartDescription ) desc ) . getFlowGraph ( ) ) ; break ; case PSEUD : break ; default : throw new AssertionError ( ) ; } } context . pop ( ) ; } private void writeInput ( Context context , JobflowModel model ) { for ( Import ext : model . getImports ( ) ) { context . put ( "" , ext . getDescription ( ) . getName ( ) , ext . getDescription ( ) . getImporterDescription ( ) . getClass ( ) . getName ( ) ) ; } } private void writeOutput ( Context context , JobflowModel model ) { for ( Export ext : model . getExports ( ) ) { context . put ( "" , ext . getDescription ( ) . getName ( ) , ext . getDescription ( ) . getExporterDescription ( ) . getClass ( ) . getName ( ) ) ; } } private static class Context implements Closeable { private final PrintWriter writer ; private int indent = ; public Context ( OutputStream output ) { assert output != null ; writer = new PrintWriter ( new OutputStreamWriter ( output , ENCODING ) ) ; } public void push ( ) { indent ++ ; } public void pop ( ) { if ( indent == ) { throw new IllegalStateException ( ) ; } indent -- ; } public void put ( String pattern , Object ... arguments ) { assert pattern != null ; assert arguments != null ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = indent ; i < n ; i ++ ) { buf . append ( "" ) ; } if ( arguments . length == ) { buf . append ( pattern ) ; } else { buf . append ( MessageFormat . format ( pattern , arguments ) ) ; } String text = buf . toString ( ) ; writer . println ( text ) ; LOG . debug ( text ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } } } package com . asakusafw . compiler . tool . analysis ; import java . io . Closeable ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . UUID ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . plan . FlowGraphUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . batch . WorkDescription ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription . Declaration ; public class VisualizeOriginalStructureProcessor extends AbstractWorkflowProcessor { static final Logger LOG = LoggerFactory . getLogger ( VisualizeOriginalStructureProcessor . class ) ; static final Charset ENCODING = Charset . forName ( "" ) ; public static final String NAIVE_PATH = Constants . PATH_BATCH + "" ; public static final String MERGED_PATH = Constants . PATH_BATCH + "" ; @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( JobFlowWorkDescriptionProcessor . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { process ( workflow , NAIVE_PATH , false ) ; process ( workflow , MERGED_PATH , true ) ; } void process ( Workflow workflow , String path , boolean merged ) throws IOException { OutputStream output = getEnvironment ( ) . openResource ( path ) ; try { Context context = new Context ( output , merged ) ; context . put ( "" ) ; context . push ( ) ; context . put ( "" ) ; Class < ? extends BatchDescription > desc = workflow . getDescription ( ) . getClass ( ) ; String batchId = context . label ( desc , "" , desc . getSimpleName ( ) ) ; dump ( context , batchId , workflow . getGraph ( ) ) ; context . pop ( ) ; context . put ( "" ) ; context . close ( ) ; } finally { output . close ( ) ; } } private void dump ( Context context , String batchId , Graph < Workflow . Unit > graph ) { assert context != null ; assert graph != null ; for ( Workflow . Unit unit : Graphs . sortPostOrder ( graph ) ) { String flowId = dumpUnit ( context , unit ) ; context . connect ( batchId , flowId ) ; } } private String dumpUnit ( Context context , Workflow . Unit unit ) { assert context != null ; assert unit != null ; WorkDescription desc = unit . getDescription ( ) ; if ( desc instanceof JobFlowWorkDescription ) { return dumpDescription ( context , ( JobFlowWorkDescription ) desc , ( JobflowModel ) unit . getProcessed ( ) ) ; } else { throw new AssertionError ( desc ) ; } } private String dumpDescription ( Context context , JobFlowWorkDescription desc , JobflowModel model ) { assert context != null ; assert desc != null ; assert model != null ; String id = context . label ( desc . getFlowClass ( ) , "" , desc . getFlowClass ( ) . getSimpleName ( ) ) ; dumpFlowBody ( context , id , model . getStageGraph ( ) . getInput ( ) . getSource ( ) . getOrigin ( ) ) ; return id ; } private void dumpFlowBody ( Context context , String flowId , FlowGraph flow ) { for ( FlowElement element : FlowGraphUtil . collectElements ( flow ) ) { FlowElementDescription desc = element . getDescription ( ) ; switch ( desc . getKind ( ) ) { case OPERATOR : Declaration decl = ( ( OperatorDescription ) desc ) . getDeclaration ( ) ; if ( decl . getDeclaring ( ) . getName ( ) . startsWith ( "" ) == false ) { String elementId = context . label ( decl . toMethod ( ) , decl . getAnnotationType ( ) . getSimpleName ( ) , MessageFormat . format ( "" , decl . getDeclaring ( ) . getSimpleName ( ) , decl . toMethod ( ) . getName ( ) ) ) ; context . connect ( flowId , elementId ) ; } break ; case FLOW_COMPONENT : FlowPartDescription part = ( FlowPartDescription ) desc ; Class < ? extends FlowDescription > description = part . getFlowGraph ( ) . getDescription ( ) ; String elementId = context . label ( description , "" , description . getSimpleName ( ) ) ; context . connect ( flowId , elementId ) ; dumpFlowBody ( context , elementId , part . getFlowGraph ( ) ) ; break ; case INPUT : case OUTPUT : case PSEUD : break ; default : throw new AssertionError ( ) ; } } } private static class Context implements Closeable { private final PrintWriter writer ; private final boolean merged ; private final Map < Object , String > ids = Maps . create ( ) ; private final Set < String > sawConnections = Sets . create ( ) ; private int indent = ; Context ( OutputStream output , boolean merged ) { assert output != null ; this . writer = new PrintWriter ( new OutputStreamWriter ( output , ENCODING ) ) ; this . merged = merged ; } void push ( ) { indent ++ ; } void pop ( ) { if ( indent == ) { throw new IllegalStateException ( ) ; } indent -- ; } String label ( Object source , String kind , String detail ) { if ( merged == false ) { return newLabel ( kind , detail ) ; } else { String id = ids . get ( source ) ; if ( id == null ) { id = newLabel ( kind , detail ) ; ids . put ( source , id ) ; } return id ; } } String newLabel ( String kind , String detail ) { String id = UUID . randomUUID ( ) . toString ( ) ; put ( "" , id , kind , detail ) ; return id ; } void connect ( String src , String dst ) { if ( merged ) { String id = src + '' + dst ; if ( sawConnections . contains ( id ) == false ) { sawConnections . add ( id ) ; put ( "" , src , dst ) ; } } else { put ( "" , src , dst ) ; } } void put ( String pattern , Object ... arguments ) { assert pattern != null ; assert arguments != null ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = indent ; i < n ; i ++ ) { buf . append ( "" ) ; } if ( arguments . length == ) { buf . append ( pattern ) ; } else { buf . append ( MessageFormat . format ( pattern , arguments ) ) ; } String text = buf . toString ( ) ; writer . println ( text ) ; LOG . debug ( text ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } } } package com . asakusafw . compiler . bootstrap ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . URL ; import java . text . MessageFormat ; import java . util . List ; import java . util . Set ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . ResourceRepository ; import com . asakusafw . compiler . batch . ResourceRepository . Cursor ; import com . asakusafw . compiler . common . FileRepository ; import com . asakusafw . compiler . common . ZipRepository ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; public final class AllBatchCompilerDriver { static final Logger LOG = LoggerFactory . getLogger ( AllBatchCompilerDriver . class ) ; private static final Option OPT_OUTPUT ; private static final Option OPT_PACKAGE ; private static final Option OPT_HADOOPWORK ; private static final Option OPT_COMPILERWORK ; private static final Option OPT_LINK ; private static final Option OPT_PLUGIN ; private static final Option OPT_SKIPERROR ; private static final Option OPT_SCANPATH ; private static final Options OPTIONS ; static { OPT_OUTPUT = new Option ( "" , true , "" ) ; OPT_OUTPUT . setArgName ( "" ) ; OPT_OUTPUT . setValueSeparator ( File . pathSeparatorChar ) ; OPT_OUTPUT . setRequired ( true ) ; OPT_PACKAGE = new Option ( "" , true , "" ) ; OPT_PACKAGE . setArgName ( "" ) ; OPT_PACKAGE . setRequired ( true ) ; OPT_HADOOPWORK = new Option ( "" , true , "" ) ; OPT_HADOOPWORK . setArgName ( "" ) ; OPT_HADOOPWORK . setRequired ( true ) ; OPT_COMPILERWORK = new Option ( "" , true , "" ) ; OPT_COMPILERWORK . setArgName ( "" ) ; OPT_COMPILERWORK . setRequired ( false ) ; OPT_LINK = new Option ( "" , true , "" ) ; OPT_LINK . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN = new Option ( "" , true , "" ) ; OPT_PLUGIN . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN . setRequired ( false ) ; OPT_SKIPERROR = new Option ( "" , "" ) ; OPT_SCANPATH = new Option ( "" , true , "" ) ; OPT_SCANPATH . setArgName ( "" ) ; OPT_SCANPATH . setRequired ( true ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_OUTPUT ) ; OPTIONS . addOption ( OPT_PACKAGE ) ; OPTIONS . addOption ( OPT_HADOOPWORK ) ; OPTIONS . addOption ( OPT_COMPILERWORK ) ; OPTIONS . addOption ( OPT_LINK ) ; OPTIONS . addOption ( OPT_PLUGIN ) ; OPTIONS . addOption ( OPT_SKIPERROR ) ; OPTIONS . addOption ( OPT_SCANPATH ) ; } public static void main ( String ... args ) { try { if ( start ( args ) == false ) { System . exit ( ) ; } } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , AllBatchCompilerDriver . class . getName ( ) ) , OPTIONS , true ) ; e . printStackTrace ( System . out ) ; System . exit ( ) ; } } private static boolean start ( String [ ] args ) throws Exception { CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String output = cmd . getOptionValue ( OPT_OUTPUT . getOpt ( ) ) ; String scanPath = cmd . getOptionValue ( OPT_SCANPATH . getOpt ( ) ) ; String packageName = cmd . getOptionValue ( OPT_PACKAGE . getOpt ( ) ) ; String hadoopWork = cmd . getOptionValue ( OPT_HADOOPWORK . getOpt ( ) ) ; String compilerWork = cmd . getOptionValue ( OPT_COMPILERWORK . getOpt ( ) ) ; String link = cmd . getOptionValue ( OPT_LINK . getOpt ( ) ) ; String plugin = cmd . getOptionValue ( OPT_PLUGIN . getOpt ( ) ) ; boolean skipError = cmd . hasOption ( OPT_SKIPERROR . getOpt ( ) ) ; File outputDirectory = new File ( output ) ; Location hadoopWorkLocation = Location . fromPath ( hadoopWork , '' ) ; File compilerWorkDirectory = new File ( compilerWork ) ; List < File > linkingResources = Lists . create ( ) ; if ( link != null ) { for ( String s : link . split ( File . pathSeparator ) ) { linkingResources . add ( new File ( s ) ) ; } } List < URL > pluginLocations = Lists . create ( ) ; if ( plugin != null ) { for ( String s : plugin . split ( File . pathSeparator ) ) { try { File file = new File ( s ) ; if ( file . exists ( ) == false ) { throw new FileNotFoundException ( file . getAbsolutePath ( ) ) ; } URL url = file . toURI ( ) . toURL ( ) ; pluginLocations . add ( url ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , s ) , e ) ; } } } Set < String > errorBatches = Sets . create ( ) ; boolean succeeded = true ; try { ResourceRepository scanner = getScanner ( new File ( scanPath ) ) ; Cursor cursor = scanner . createCursor ( ) ; try { while ( cursor . next ( ) ) { Location location = cursor . getLocation ( ) ; Class < ? extends BatchDescription > batchDescription = getBatchDescription ( location ) ; if ( batchDescription == null ) { continue ; } boolean singleSucceeded = BatchCompilerDriver . compile ( outputDirectory , batchDescription , packageName , hadoopWorkLocation , compilerWorkDirectory , linkingResources , pluginLocations ) ; succeeded &= singleSucceeded ; if ( singleSucceeded == false ) { errorBatches . add ( toClassName ( location ) ) ; if ( skipError == false ) { break ; } } } } finally { cursor . close ( ) ; } } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , scanPath ) , e ) ; } if ( succeeded == false ) { LOG . error ( "" , errorBatches ) ; } return succeeded ; } private static Class < ? extends BatchDescription > getBatchDescription ( Location location ) { assert location != null ; if ( isValidClassFileName ( location ) == false ) { LOG . debug ( "" , location ) ; return null ; } String className = toClassName ( location ) ; Class < ? extends BatchDescription > batchClass = loadIfBatchClass ( className ) ; if ( batchClass == null ) { LOG . debug ( "" , className ) ; return null ; } LOG . info ( "" , className ) ; return batchClass ; } private static String toClassName ( Location location ) { assert location != null ; String className = location . toPath ( '' ) ; className = className . substring ( , className . length ( ) - "" . length ( ) ) ; return className ; } private static boolean isValidClassFileName ( Location location ) { assert location != null ; String simpleName = location . getName ( ) ; if ( simpleName . endsWith ( "" ) == false ) { return false ; } for ( Location current = location . getParent ( ) ; current != null ; current = current . getParent ( ) ) { if ( current . getName ( ) . indexOf ( '' ) >= ) { return false ; } } if ( simpleName . indexOf ( '' ) >= ) { return false ; } return true ; } private static Class < ? extends BatchDescription > loadIfBatchClass ( String className ) { try { Class < ? > aClass = Class . forName ( className ) ; if ( BatchDescription . class . isAssignableFrom ( aClass ) == false ) { return null ; } if ( aClass . isAnnotationPresent ( Batch . class ) == false ) { LOG . warn ( "" , aClass . getName ( ) ) ; return null ; } return aClass . asSubclass ( BatchDescription . class ) ; } catch ( ClassNotFoundException e ) { LOG . debug ( "" , e ) ; return null ; } } private static ResourceRepository getScanner ( File scanPath ) throws IOException { assert scanPath != null ; String name = scanPath . getName ( ) ; if ( scanPath . exists ( ) == false ) { throw new FileNotFoundException ( MessageFormat . format ( "" , scanPath ) ) ; } if ( scanPath . isDirectory ( ) ) { return new FileRepository ( scanPath ) ; } else if ( scanPath . isFile ( ) && ( name . endsWith ( "" ) || name . endsWith ( "" ) ) ) { return new ZipRepository ( scanPath ) ; } else { throw new IOException ( MessageFormat . format ( "" , scanPath ) ) ; } } private AllBatchCompilerDriver ( ) { return ; } } package com . asakusafw . compiler . bootstrap ; package com . asakusafw . compiler . bootstrap ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . URL ; import java . net . URLClassLoader ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . text . MessageFormat ; import java . util . List ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . BatchDriver ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectBatchCompiler ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . batch . BatchDescription ; public final class BatchCompilerDriver { static final Logger LOG = LoggerFactory . getLogger ( BatchCompilerDriver . class ) ; private static final Option OPT_OUTPUT ; private static final Option OPT_PACKAGE ; private static final Option OPT_HADOOPWORK ; private static final Option OPT_COMPILERWORK ; private static final Option OPT_LINK ; private static final Option OPT_PLUGIN ; private static final Option OPT_CLASS ; private static final Options OPTIONS ; static { OPT_OUTPUT = new Option ( "" , true , "" ) ; OPT_OUTPUT . setArgName ( "" ) ; OPT_OUTPUT . setValueSeparator ( File . pathSeparatorChar ) ; OPT_OUTPUT . setRequired ( true ) ; OPT_PACKAGE = new Option ( "" , true , "" ) ; OPT_PACKAGE . setArgName ( "" ) ; OPT_PACKAGE . setRequired ( true ) ; OPT_HADOOPWORK = new Option ( "" , true , "" ) ; OPT_HADOOPWORK . setArgName ( "" ) ; OPT_HADOOPWORK . setRequired ( true ) ; OPT_COMPILERWORK = new Option ( "" , true , "" ) ; OPT_COMPILERWORK . setArgName ( "" ) ; OPT_COMPILERWORK . setRequired ( false ) ; OPT_LINK = new Option ( "" , true , "" ) ; OPT_LINK . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN = new Option ( "" , true , "" ) ; OPT_PLUGIN . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN . setRequired ( false ) ; OPT_CLASS = new Option ( "" , true , "" ) ; OPT_CLASS . setArgName ( "" ) ; OPT_CLASS . setRequired ( true ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_OUTPUT ) ; OPTIONS . addOption ( OPT_PACKAGE ) ; OPTIONS . addOption ( OPT_HADOOPWORK ) ; OPTIONS . addOption ( OPT_COMPILERWORK ) ; OPTIONS . addOption ( OPT_LINK ) ; OPTIONS . addOption ( OPT_PLUGIN ) ; OPTIONS . addOption ( OPT_CLASS ) ; } public static void main ( String ... args ) { try { if ( start ( args ) == false ) { System . exit ( ) ; } } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , BatchCompilerDriver . class . getName ( ) ) , OPTIONS , true ) ; e . printStackTrace ( System . out ) ; System . exit ( ) ; } } private static boolean start ( String [ ] args ) throws Exception { CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String output = cmd . getOptionValue ( OPT_OUTPUT . getOpt ( ) ) ; String className = cmd . getOptionValue ( OPT_CLASS . getOpt ( ) ) ; String packageName = cmd . getOptionValue ( OPT_PACKAGE . getOpt ( ) ) ; String hadoopWork = cmd . getOptionValue ( OPT_HADOOPWORK . getOpt ( ) ) ; String compilerWork = cmd . getOptionValue ( OPT_COMPILERWORK . getOpt ( ) ) ; String link = cmd . getOptionValue ( OPT_LINK . getOpt ( ) ) ; String plugin = cmd . getOptionValue ( OPT_PLUGIN . getOpt ( ) ) ; File outputDirectory = new File ( output ) ; Location hadoopWorkLocation = Location . fromPath ( hadoopWork , '' ) ; File compilerWorkDirectory = new File ( compilerWork ) ; List < File > linkingResources = Lists . create ( ) ; if ( link != null ) { for ( String s : link . split ( File . pathSeparator ) ) { linkingResources . add ( new File ( s ) ) ; } } List < URL > pluginLocations = Lists . create ( ) ; if ( plugin != null ) { for ( String s : plugin . split ( File . pathSeparator ) ) { try { File file = new File ( s ) ; if ( file . exists ( ) == false ) { throw new FileNotFoundException ( file . getAbsolutePath ( ) ) ; } URL url = file . toURI ( ) . toURL ( ) ; pluginLocations . add ( url ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , s ) , e ) ; } } } Class < ? extends BatchDescription > batchDescription = Class . forName ( className ) . asSubclass ( BatchDescription . class ) ; boolean succeeded = compile ( outputDirectory , batchDescription , packageName , hadoopWorkLocation , compilerWorkDirectory , linkingResources , pluginLocations ) ; if ( succeeded ) { LOG . info ( "" , batchDescription . getName ( ) ) ; } else { LOG . error ( MessageFormat . format ( "" , className ) ) ; } return succeeded ; } static boolean compile ( File outputDirectory , Class < ? extends BatchDescription > batchDescription , String packageName , Location hadoopWorkLocation , File compilerWorkDirectory , List < File > linkingResources , final List < URL > pluginLibraries ) { assert outputDirectory != null ; assert batchDescription != null ; assert packageName != null ; assert hadoopWorkLocation != null ; assert compilerWorkDirectory != null ; assert linkingResources != null ; try { BatchDriver analyzed = BatchDriver . analyze ( batchDescription ) ; if ( analyzed . hasError ( ) ) { for ( String diagnostic : analyzed . getDiagnostics ( ) ) { LOG . error ( diagnostic ) ; } return false ; } String batchId = analyzed . getBatchClass ( ) . getConfig ( ) . name ( ) ; ClassLoader serviceLoader = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) { URLClassLoader loader = new URLClassLoader ( pluginLibraries . toArray ( new URL [ pluginLibraries . size ( ) ] ) , BatchCompilerDriver . class . getClassLoader ( ) ) ; return loader ; } } ) ; DirectBatchCompiler . compile ( analyzed . getDescription ( ) , packageName , hadoopWorkLocation , new File ( outputDirectory , batchId ) , new File ( compilerWorkDirectory , batchId ) , linkingResources , serviceLoader , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; return true ; } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , batchDescription . getName ( ) ) , e ) ; return false ; } } private BatchCompilerDriver ( ) { return ; } } package com . asakusafw . compiler . bootstrap ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . LinkedHashSet ; import java . util . List ; import java . util . Set ; import javax . tools . JavaCompiler ; import javax . tools . JavaCompiler . CompilationTask ; import javax . tools . StandardJavaFileManager ; import javax . tools . ToolProvider ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . utils . collections . Lists ; public final class OperatorCompilerDriver { static final Logger LOG = LoggerFactory . getLogger ( OperatorCompilerDriver . class ) ; private static final Option OPT_SOURCEPATH ; private static final Option OPT_OUTPUT ; private static final Option OPT_ENCODING ; private static final Option OPT_CLASSES ; private static final Options OPTIONS ; static { OPT_SOURCEPATH = new Option ( "" , true , "" ) ; OPT_SOURCEPATH . setArgName ( "" ) ; OPT_SOURCEPATH . setRequired ( true ) ; OPT_ENCODING = new Option ( "" , true , "" ) ; OPT_ENCODING . setArgName ( "" ) ; OPT_OUTPUT = new Option ( "" , true , "" ) ; OPT_OUTPUT . setArgName ( "" ) ; OPT_OUTPUT . setValueSeparator ( File . pathSeparatorChar ) ; OPT_OUTPUT . setRequired ( true ) ; OPT_CLASSES = new Option ( "" , true , "" ) ; OPT_CLASSES . setArgName ( "" ) ; OPT_CLASSES . setArgs ( Option . UNLIMITED_VALUES ) ; OPT_CLASSES . setRequired ( true ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_SOURCEPATH ) ; OPTIONS . addOption ( OPT_ENCODING ) ; OPTIONS . addOption ( OPT_OUTPUT ) ; OPTIONS . addOption ( OPT_CLASSES ) ; } public static void compile ( File sourcePath , File outputPath , Charset encoding , List < Class < ? > > operatorClasses ) throws IOException { if ( sourcePath == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputPath == null ) { throw new IllegalArgumentException ( "" ) ; } if ( encoding == null ) { throw new IllegalArgumentException ( "" ) ; } if ( operatorClasses == null ) { throw new IllegalArgumentException ( "" ) ; } List < File > sourceFiles = toSources ( sourcePath , operatorClasses ) ; LOG . info ( "" , sourceFiles ) ; List < String > arguments = toArguments ( sourcePath , outputPath , encoding ) ; LOG . debug ( "" , arguments ) ; if ( outputPath . isDirectory ( ) == false && outputPath . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , outputPath ) ) ; } JavaCompiler compiler = ToolProvider . getSystemJavaCompiler ( ) ; if ( compiler == null ) { throw new IOException ( "" ) ; } StandardJavaFileManager files = compiler . getStandardFileManager ( null , null , encoding ) ; try { CompilationTask task = compiler . getTask ( null , files , null , arguments , Collections . < String > emptyList ( ) , files . getJavaFileObjectsFromFiles ( sourceFiles ) ) ; if ( task . call ( ) == false ) { LOG . error ( "" ) ; } } finally { files . close ( ) ; } LOG . info ( "" ) ; } private static List < String > toArguments ( File sourcePath , File outputPath , Charset encoding ) { assert sourcePath != null ; assert outputPath != null ; assert encoding != null ; List < String > results = Lists . create ( ) ; Collections . addAll ( results , "" ) ; Collections . addAll ( results , "" , "" ) ; Collections . addAll ( results , "" , "" ) ; Collections . addAll ( results , "" , encoding . displayName ( ) ) ; Collections . addAll ( results , "" , sourcePath . getAbsolutePath ( ) ) ; Collections . addAll ( results , "" , outputPath . getAbsolutePath ( ) ) ; return results ; } private static List < File > toSources ( File sourcePath , List < Class < ? > > operatorClasses ) throws IOException { assert sourcePath != null ; assert operatorClasses != null ; Set < File > results = new LinkedHashSet < File > ( ) ; for ( Class < ? > aClass : operatorClasses ) { File source = findSource ( sourcePath , aClass ) ; if ( results . contains ( source ) == false ) { results . add ( source ) ; } } return Lists . from ( results ) ; } private static File findSource ( File sourcePath , Class < ? > aClass ) throws IOException { assert sourcePath != null ; assert aClass != null ; String [ ] segments = aClass . getName ( ) . split ( "" ) ; File current = sourcePath ; for ( int i = ; i < segments . length - ; i ++ ) { current = new File ( current , segments [ i ] ) ; if ( current . isDirectory ( ) == false ) { throw new FileNotFoundException ( MessageFormat . format ( "" , current , aClass . getName ( ) ) ) ; } } String name = segments [ segments . length - ] ; int enclosing = name . indexOf ( '' ) ; if ( enclosing >= ) { name = name . substring ( , enclosing ) ; } File file = new File ( current , name + "" ) ; if ( file . isFile ( ) == false ) { if ( current . isDirectory ( ) == false ) { throw new FileNotFoundException ( MessageFormat . format ( "" , file , aClass . getName ( ) ) ) ; } } return file . getCanonicalFile ( ) ; } public static void main ( String ... args ) { try { start ( args ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , OperatorCompilerDriver . class . getName ( ) ) , OPTIONS , true ) ; e . printStackTrace ( System . out ) ; System . exit ( ) ; } } private static void start ( String [ ] args ) throws Exception { CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String sourcePath = cmd . getOptionValue ( OPT_SOURCEPATH . getOpt ( ) ) ; String output = cmd . getOptionValue ( OPT_OUTPUT . getOpt ( ) ) ; String encoding = cmd . getOptionValue ( OPT_ENCODING . getOpt ( ) , "" ) ; String [ ] classes = cmd . getOptionValues ( OPT_CLASSES . getOpt ( ) ) ; List < Class < ? > > operatorClasses = Lists . create ( ) ; for ( String className : classes ) { Class < ? > oc = Class . forName ( className ) ; operatorClasses . add ( oc ) ; } compile ( new File ( sourcePath ) , new File ( output ) , Charset . forName ( encoding ) , operatorClasses ) ; } private OperatorCompilerDriver ( ) { return ; } } package com . asakusafw . compiler . common ; package com . asakusafw . compiler . common ; import java . lang . annotation . Annotation ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface TargetOperator { Class < ? extends Annotation > value ( ) ; } package com . asakusafw . compiler . common ; import java . util . Set ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; public class NameGenerator { private final ModelFactory factory ; private final Set < String > used = Sets . create ( ) ; public NameGenerator ( ModelFactory factory ) { Precondition . checkMustNotBeNull ( factory , "" ) ; this . factory = factory ; } public String reserve ( String name ) { Precondition . checkMustNotBeNull ( name , "" ) ; used . add ( name ) ; return name ; } public SimpleName create ( String hint ) { Precondition . checkMustNotBeNull ( hint , "" ) ; int initial = ; String name = hint ; if ( used . contains ( name ) ) { int number = initial ; String current ; do { current = name + number ; number ++ ; } while ( used . contains ( current ) ) ; name = current ; } used . add ( name ) ; return factory . newSimpleName ( name ) ; } } package com . asakusafw . compiler . common ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . Iterator ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . ResourceRepository ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . utils . collections . Lists ; public class FileRepository implements ResourceRepository { static final Logger LOG = LoggerFactory . getLogger ( FileRepository . class ) ; private final File root ; public FileRepository ( File root ) throws IOException { Precondition . checkMustNotBeNull ( root , "" ) ; if ( root . isDirectory ( ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , root ) ) ; } this . root = root . getAbsoluteFile ( ) . getCanonicalFile ( ) ; } @ Override public Cursor createCursor ( ) throws IOException { List < Resource > results = Lists . create ( ) ; collect ( results , null , root ) ; return new ResourceCursor ( results . iterator ( ) ) ; } private void collect ( List < Resource > results , Location location , File file ) { assert results != null ; assert file != null ; if ( file . isFile ( ) ) { results . add ( new Resource ( file , location ) ) ; } else if ( file . isDirectory ( ) ) { for ( File child : file . listFiles ( ) ) { Location enter = new Location ( location , child . getName ( ) ) ; collect ( results , enter , child ) ; } } else { LOG . warn ( "" , file ) ; } } private static class Resource { public final File file ; public final Location location ; Resource ( File file , Location location ) { assert file != null ; assert location != null ; this . file = file ; this . location = location ; } } private static class ResourceCursor implements Cursor { private final Iterator < Resource > iterator ; private Resource current ; ResourceCursor ( Iterator < Resource > iterator ) { assert iterator != null ; this . iterator = iterator ; } @ Override public boolean next ( ) throws IOException { if ( iterator . hasNext ( ) == false ) { return false ; } current = iterator . next ( ) ; return true ; } @ Override public Location getLocation ( ) { return current . location ; } @ Override public InputStream openResource ( ) throws IOException { return new FileInputStream ( current . file ) ; } @ Override public void close ( ) throws IOException { } } } package com . asakusafw . compiler . common ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . zip . ZipEntry ; import java . util . zip . ZipInputStream ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . ResourceRepository ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . runtime . io . util . ZipEntryInputStream ; public class ZipRepository implements ResourceRepository { static final Logger LOG = LoggerFactory . getLogger ( ZipRepository . class ) ; private final File archive ; public ZipRepository ( File archive ) throws IOException { Precondition . checkMustNotBeNull ( archive , "" ) ; if ( archive . isFile ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , archive ) ) ; } this . archive = archive . getAbsoluteFile ( ) . getCanonicalFile ( ) ; } @ Override public Cursor createCursor ( ) throws IOException { FileInputStream input = new FileInputStream ( archive ) ; boolean success = false ; try { Cursor cursor = new EntryCursor ( archive , new ZipInputStream ( input ) ) ; success = true ; return cursor ; } finally { if ( success == false ) { input . close ( ) ; } } } private static class EntryCursor implements Cursor { private final File source ; private final ZipInputStream stream ; private ZipEntry current ; private int entries ; EntryCursor ( File source , ZipInputStream stream ) { assert source != null ; assert stream != null ; this . source = source ; this . stream = stream ; this . entries = ; } @ Override public boolean next ( ) throws IOException { while ( true ) { current = stream . getNextEntry ( ) ; if ( current == null ) { if ( entries == ) { throw new IOException ( MessageFormat . format ( "" , source ) ) ; } return false ; } entries ++ ; if ( current . isDirectory ( ) == false ) { return true ; } } } @ Override public Location getLocation ( ) { return Location . fromPath ( current . getName ( ) . replace ( '' , '' ) , '' ) ; } @ Override public InputStream openResource ( ) throws IOException { return new ZipEntryInputStream ( stream ) ; } @ Override public void close ( ) throws IOException { stream . close ( ) ; } } } package com . asakusafw . compiler . common ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Collection ; import java . util . List ; import java . util . Map ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Tuple2 ; import com . asakusafw . utils . collections . Tuples ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; public final class EnumUtil { public static List < Tuple2 < Enum < ? > , FlowElementPortDescription > > extractConstants ( Class < ? > enumType , Collection < FlowElementPortDescription > ports ) { Precondition . checkMustNotBeNull ( enumType , "" ) ; Precondition . checkMustNotBeNull ( ports , "" ) ; Enum < ? > [ ] constants = ( Enum < ? > [ ] ) enumType . getEnumConstants ( ) ; if ( constants == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , enumType ) ) ; } Map < String , FlowElementPortDescription > portNames = Maps . create ( ) ; for ( FlowElementPortDescription port : ports ) { portNames . put ( port . getName ( ) , port ) ; } List < Tuple2 < Enum < ? > , FlowElementPortDescription > > results = Lists . create ( ) ; for ( Enum < ? > constant : constants ) { String name = JavaName . of ( constant . name ( ) ) . toMemberName ( ) ; FlowElementPortDescription port = portNames . get ( name ) ; if ( port == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , constant . name ( ) , portNames ) ) ; } results . add ( Tuples . < Enum < ? > , FlowElementPortDescription > of ( constant , port ) ) ; } if ( ports . size ( ) > results . size ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , Arrays . asList ( constants ) , ports ) ) ; } return results ; } private EnumUtil ( ) { throw new AssertionError ( ) ; } } package com . asakusafw . compiler . common ; import java . text . MessageFormat ; public final class Naming { public static String getClientClass ( ) { return "" ; } public static String getMapClass ( int inputId ) { return String . format ( "" , "" , inputId ) ; } public static String getReduceClass ( ) { return "" ; } public static String getCombineClass ( ) { return "" ; } public static String getMapFragmentClass ( int serialNumber ) { return String . format ( "" , "" , serialNumber ) ; } public static String getReduceFragmentClass ( int serialNumber ) { return String . format ( "" , "" , serialNumber ) ; } public static String getMapOutputFragmentClass ( int serialNumber ) { return String . format ( "" , "" , serialNumber ) ; } public static String getCombineOutputFragmentClass ( int serialNumber ) { return String . format ( "" , "" , serialNumber ) ; } public static String getCombineFragmentClass ( int serialNumber ) { return String . format ( "" , "" , serialNumber ) ; } public static String getShuffleKeyClass ( ) { return "" ; } public static String getShuffleValueClass ( ) { return "" ; } public static String getShufflePartitionerClass ( ) { return "" ; } public static String getShuffleGroupingComparatorClass ( ) { return "" ; } public static String getShuffleSortComparatorClass ( ) { return "" ; } public static String getShuffleKeyGroupCopier ( ) { return "" ; } public static String getShuffleKeyGroupProperty ( int elementId , int termId ) { return String . format ( "" , elementId , termId ) ; } public static String getShuffleKeySortProperty ( int portId , int termId ) { return String . format ( "" , portId , termId ) ; } public static String getShuffleKeySetter ( int portId ) { return String . format ( "" , portId ) ; } public static String getShuffleValueGetter ( int portId ) { return String . format ( "" , portId ) ; } public static String getShuffleValueSetter ( int portId ) { return String . format ( "" , portId ) ; } public static String getStageName ( int stageNumber ) { return String . format ( "" , stageNumber ) ; } public static String getCleanupStageName ( ) { return "" ; } public static String getPrologueName ( String moduleId ) { Precondition . checkMustNotBeNull ( moduleId , "" ) ; return MessageFormat . format ( "" , moduleId ) ; } public static String getPrologueName ( String moduleId , String stageId ) { Precondition . checkMustNotBeNull ( moduleId , "" ) ; return MessageFormat . format ( "" , moduleId , stageId ) ; } public static String getEpilogueName ( String moduleId ) { Precondition . checkMustNotBeNull ( moduleId , "" ) ; return MessageFormat . format ( "" , moduleId ) ; } public static String getEpilogueName ( String moduleId , String stageId ) { Precondition . checkMustNotBeNull ( moduleId , "" ) ; return MessageFormat . format ( "" , moduleId , stageId ) ; } public static String getJobflowClassPackageName ( String flowId ) { Precondition . checkMustNotBeNull ( flowId , "" ) ; return String . format ( "" , flowId , "" ) ; } public static String getJobflowSourceBundleName ( String flowId ) { Precondition . checkMustNotBeNull ( flowId , "" ) ; return String . format ( "" , flowId , "" ) ; } private Naming ( ) { throw new AssertionError ( ) ; } } package com . asakusafw . compiler . common ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; public class JavaName { private static final Set < String > RESERVED ; static { Set < String > set = Sets . create ( ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; RESERVED = Collections . unmodifiableSet ( set ) ; } private static final String EMPTY_NAME = "" ; private final List < String > words ; JavaName ( List < ? extends String > words ) { if ( words == null ) { throw new NullPointerException ( "" ) ; } this . words = Lists . create ( ) ; for ( String word : words ) { this . words . add ( normalize ( word ) ) ; } } public static JavaName of ( String nameString ) { if ( nameString . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } else if ( nameString . indexOf ( '' ) >= || nameString . toUpperCase ( ) . equals ( nameString ) ) { String [ ] segments = nameString . split ( EMPTY_NAME ) ; return new JavaName ( normalize ( Arrays . asList ( segments ) ) ) ; } else { List < String > segments = Lists . create ( ) ; int start = ; for ( int i = , n = nameString . length ( ) ; i < n ; i ++ ) { if ( Character . isUpperCase ( nameString . charAt ( i ) ) ) { segments . add ( nameString . substring ( start , i ) ) ; start = i ; } } segments . add ( nameString . substring ( start ) ) ; return new JavaName ( normalize ( segments ) ) ; } } public List < String > getSegments ( ) { return Lists . from ( words ) ; } public String toTypeName ( ) { if ( words . isEmpty ( ) ) { return EMPTY_NAME ; } StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( capitalize ( words . get ( i ) ) ) ; } return buf . toString ( ) ; } public String toMemberName ( ) { if ( words . isEmpty ( ) ) { return EMPTY_NAME ; } StringBuilder buf = new StringBuilder ( ) ; buf . append ( words . get ( ) . toLowerCase ( ) ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( capitalize ( words . get ( i ) ) ) ; } String result = buf . toString ( ) ; if ( RESERVED . contains ( result ) || Character . isJavaIdentifierStart ( result . charAt ( ) ) == false ) { return escape ( result ) ; } return result ; } private String escape ( String result ) { assert result != null ; return result + '' ; } public String toConstantName ( ) { if ( words . isEmpty ( ) ) { return EMPTY_NAME ; } StringBuilder buf = new StringBuilder ( ) ; buf . append ( words . get ( ) . toUpperCase ( ) ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( '' ) ; buf . append ( words . get ( i ) . toUpperCase ( ) ) ; } return buf . toString ( ) ; } public void addFirst ( String segment ) { words . add ( , normalize ( segment ) ) ; } public void removeFirst ( ) { if ( words . isEmpty ( ) ) { throw new IllegalStateException ( ) ; } words . remove ( ) ; } public void addLast ( String segment ) { words . add ( normalize ( segment ) ) ; } public void removeLast ( ) { if ( words . isEmpty ( ) ) { throw new IllegalStateException ( ) ; } words . remove ( words . size ( ) - ) ; } private String capitalize ( String segment ) { assert segment != null ; StringBuilder buf = new StringBuilder ( segment . toLowerCase ( ) ) ; buf . setCharAt ( , Character . toUpperCase ( buf . charAt ( ) ) ) ; return buf . toString ( ) ; } private static String normalize ( String segment ) { Precondition . checkMustNotBeNull ( segment , "" ) ; if ( segment . isEmpty ( ) ) { throw new IllegalArgumentException ( ) ; } return segment . toLowerCase ( ) ; } private static List < String > normalize ( List < String > segments ) { List < String > results = Lists . create ( ) ; for ( String segment : segments ) { if ( segment . isEmpty ( ) == false ) { results . add ( segment ) ; } } return results ; } } package com . asakusafw . compiler . common ; import java . text . MessageFormat ; public final class Precondition { public static void checkMustNotBeNull ( Object value , String expression ) { if ( value == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , expression ) ) ; } } private Precondition ( ) { return ; } } package com . asakusafw . compiler . operator ; import javax . lang . model . type . TypeMirror ; public interface DataModelMirrorRepository { DataModelMirror load ( OperatorCompilingEnvironment environment , TypeMirror type ) ; } package com . asakusafw . compiler . operator . processor ; import java . util . List ; import javax . lang . model . type . TypeMirror ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . CoGroup ; @ TargetOperator ( CoGroup . class ) public class CoGroupOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isVoid ( ) == false ) { a . error ( "" ) ; } int startResults = ; for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { TypeConstraint type = a . getParameterType ( i ) ; if ( type . isResult ( ) ) { break ; } if ( type . isList ( ) == false ) { a . error ( i , "" ) ; } else if ( type . getTypeArgument ( ) . isModel ( ) == false ) { a . error ( i , "" ) ; } startResults ++ ; } if ( startResults == ) { a . error ( "" ) ; } int startParameters = startResults ; for ( int i = startResults , n = a . countParameters ( ) ; i < n ; i ++ ) { TypeConstraint param = a . getParameterType ( i ) ; if ( param . isResult ( ) == false ) { break ; } else if ( param . getTypeArgument ( ) . isModel ( ) == false ) { a . error ( i , "" ) ; } else { startParameters ++ ; } } if ( startParameters == startResults ) { a . error ( "" ) ; } for ( int i = startParameters , n = a . countParameters ( ) ; i < n ; i ++ ) { TypeConstraint param = a . getParameterType ( i ) ; if ( param . isResult ( ) ) { a . error ( i , "" ) ; } else if ( param . isBasic ( ) == false ) { a . error ( i , "" ) ; } } if ( a . hasError ( ) ) { return null ; } List < ShuffleKey > keys = Lists . create ( ) ; for ( int i = ; i < startResults ; i ++ ) { ShuffleKey key = a . getParameterKey ( i ) ; if ( key == null ) { a . error ( i , "" ) ; } else { keys . add ( key ) ; } } if ( keys . isEmpty ( ) == false ) { ShuffleKey first = keys . get ( ) ; for ( int i = , n = keys . size ( ) ; i < n ; i ++ ) { if ( first . getGroupProperties ( ) . size ( ) != keys . get ( i ) . getGroupProperties ( ) . size ( ) ) { a . error ( , "" ) ; } } } if ( a . hasError ( ) ) { return null ; } CoGroup annotation = context . element . getAnnotation ( CoGroup . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . addAttribute ( annotation . inputBuffer ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; for ( int i = ; i < startResults ; i ++ ) { builder . addInput ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getTypeArgument ( ) . getType ( ) , i , keys . get ( i ) ) ; } for ( int i = startResults ; i < startParameters ; i ++ ) { TypeConstraint outputType = a . getParameterType ( i ) . getTypeArgument ( ) ; TypeMirror outputTypeMirror = outputType . getType ( ) ; String found = builder . findInput ( outputTypeMirror ) ; if ( found == null && outputType . isProjectiveModel ( ) ) { a . error ( "" , outputTypeMirror ) ; } builder . addOutput ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , outputTypeMirror , found , i ) ; } for ( int i = startParameters , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import javax . lang . model . element . ExecutableElement ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . compiler . operator . processor . MasterKindOperatorAnalyzer . ResolveException ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterJoinUpdate ; @ TargetOperator ( MasterJoinUpdate . class ) public class MasterJoinUpdateOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isVoid ( ) == false ) { a . error ( "" ) ; } TypeConstraint master = a . getParameterType ( ) ; if ( master . isModel ( ) == false ) { a . error ( , "" ) ; } TypeConstraint transaction = a . getParameterType ( ) ; if ( transaction . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { if ( a . getParameterType ( i ) . isBasic ( ) == false ) { a . error ( i , "" ) ; } } if ( a . hasError ( ) ) { return null ; } ShuffleKey masterKey = a . getParameterKey ( ) ; if ( masterKey == null ) { a . error ( "" ) ; } ShuffleKey transactionKey = a . getParameterKey ( ) ; if ( transactionKey == null ) { a . error ( "" ) ; } ExecutableElement selector = null ; try { selector = MasterKindOperatorAnalyzer . findSelector ( context . environment , context ) ; } catch ( ResolveException e ) { a . error ( e . getMessage ( ) ) ; } MasterJoinUpdate annotation = context . element . getAnnotation ( MasterJoinUpdate . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } OperatorProcessorUtil . checkPortName ( a , new String [ ] { annotation . updatedPort ( ) , annotation . missedPort ( ) , } ) ; if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; if ( selector != null ) { builder . addOperatorHelper ( selector ) ; } builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , masterKey ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , transactionKey ) ; builder . addOutput ( "" , annotation . updatedPort ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; builder . addOutput ( "" , annotation . missedPort ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import javax . lang . model . type . TypeMirror ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . CoGroup ; import com . asakusafw . vocabulary . operator . GroupSort ; @ TargetOperator ( GroupSort . class ) public class GroupSortOperatorProcessor extends AbstractOperatorProcessor { private static final int RESULT_START = ; @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isVoid ( ) == false ) { a . error ( "" ) ; } if ( a . getParameterType ( ) . isList ( ) == false ) { a . error ( , "" ) ; } else if ( a . getParameterType ( ) . getTypeArgument ( ) . isModel ( ) == false ) { a . error ( , "" ) ; } int startParameters = RESULT_START ; for ( int i = RESULT_START , n = a . countParameters ( ) ; i < n ; i ++ ) { TypeConstraint param = a . getParameterType ( i ) ; if ( param . isResult ( ) == false ) { break ; } else if ( param . getTypeArgument ( ) . isModel ( ) == false ) { a . error ( i , "" ) ; } else { startParameters ++ ; } } if ( startParameters == RESULT_START ) { a . error ( "" ) ; } for ( int i = startParameters , n = a . countParameters ( ) ; i < n ; i ++ ) { TypeConstraint param = a . getParameterType ( i ) ; if ( param . isResult ( ) ) { a . error ( i , "" ) ; } else if ( param . isBasic ( ) == false ) { a . error ( i , "" ) ; } } if ( a . hasError ( ) ) { return null ; } ShuffleKey key = a . getParameterKey ( ) ; if ( key == null ) { a . error ( "" ) ; return null ; } GroupSort annotation = context . element . getAnnotation ( GroupSort . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } Builder builder = new Builder ( CoGroup . class , context ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . addAttribute ( annotation . inputBuffer ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getTypeArgument ( ) . getType ( ) , , key ) ; for ( int i = ; i < startParameters ; i ++ ) { TypeConstraint outputType = a . getParameterType ( i ) . getTypeArgument ( ) ; TypeMirror outputTypeMirror = outputType . getType ( ) ; String found = builder . findInput ( outputTypeMirror ) ; if ( found == null && outputType . isProjectiveModel ( ) ) { a . error ( "" , outputTypeMirror ) ; } builder . addOutput ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , outputTypeMirror , found , i ) ; } for ( int i = startParameters , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import java . util . List ; import javax . lang . model . element . ExecutableElement ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . ImplementationBuilder ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . compiler . operator . processor . MasterKindOperatorAnalyzer . ResolveException ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterJoin ; @ TargetOperator ( MasterJoin . class ) public class MasterJoinOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isGeneric ( ) ) { a . error ( "" ) ; } if ( a . isAbstract ( ) == false ) { a . error ( "" ) ; } TypeConstraint joined = a . getReturnType ( ) ; if ( joined . isConcreteModel ( ) == false ) { a . error ( "" ) ; } TypeConstraint master = a . getParameterType ( ) ; if ( master . isModel ( ) == false ) { a . error ( , "" ) ; } TypeConstraint transaction = a . getParameterType ( ) ; if ( transaction . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { a . error ( i , "" ) ; } ExecutableElement selector = null ; try { selector = MasterKindOperatorAnalyzer . findSelector ( context . environment , context ) ; } catch ( ResolveException e ) { a . error ( e . getMessage ( ) ) ; } if ( joined . isJoinedModel ( master . getType ( ) , transaction . getType ( ) ) == false ) { a . error ( "" ) ; return null ; } ShuffleKey masterKey = joined . getJoinKey ( master . getType ( ) ) ; ShuffleKey transactionKey = joined . getJoinKey ( transaction . getType ( ) ) ; MasterJoin annotation = context . element . getAnnotation ( MasterJoin . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } OperatorProcessorUtil . checkPortName ( a , new String [ ] { annotation . joinedPort ( ) , annotation . missedPort ( ) , } ) ; if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; if ( selector != null ) { builder . addOperatorHelper ( selector ) ; } builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , masterKey ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , transactionKey ) ; builder . addOutput ( a . getReturnDocument ( ) , annotation . joinedPort ( ) , a . getReturnType ( ) . getType ( ) , null , null ) ; builder . addOutput ( "" , annotation . missedPort ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; return builder . toDescriptor ( ) ; } @ Override protected List < ? extends TypeBodyDeclaration > override ( Context context ) { ImplementationBuilder builder = new ImplementationBuilder ( context ) ; ModelFactory f = context . environment . getFactory ( ) ; builder . addStatement ( new TypeBuilder ( f , context . importer . toType ( UnsupportedOperationException . class ) ) . newObject ( Models . toLiteral ( f , "" ) ) . toThrowStatement ( ) ) ; return builder . toImplementation ( ) ; } } package com . asakusafw . compiler . operator . processor ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . ImplementationBuilder ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . Summarize ; @ TargetOperator ( Summarize . class ) public class SummarizeOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isGeneric ( ) ) { a . error ( "" ) ; } if ( a . isAbstract ( ) == false ) { a . error ( "" ) ; } TypeConstraint summarized = a . getReturnType ( ) ; if ( summarized . isConcreteModel ( ) == false ) { a . error ( "" ) ; } TypeConstraint summarizee = a . getParameterType ( ) ; if ( summarizee . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { a . error ( i , "" ) ; } if ( a . hasError ( ) ) { return null ; } if ( summarized . isSummarizedModel ( summarizee . getType ( ) ) == false ) { a . error ( "" ) ; return null ; } ShuffleKey key = summarized . getSummarizeKey ( ) ; Summarize annotation = context . element . getAnnotation ( Summarize . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } OperatorProcessorUtil . checkPortName ( a , new String [ ] { annotation . summarizedPort ( ) , } ) ; if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . addAttribute ( annotation . partialAggregation ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , key ) ; builder . addOutput ( a . getReturnDocument ( ) , annotation . summarizedPort ( ) , a . getReturnType ( ) . getType ( ) , null , null ) ; return builder . toDescriptor ( ) ; } @ Override protected List < ? extends TypeBodyDeclaration > override ( Context context ) { ImplementationBuilder builder = new ImplementationBuilder ( context ) ; ModelFactory f = context . environment . getFactory ( ) ; builder . addStatement ( new TypeBuilder ( f , context . importer . toType ( UnsupportedOperationException . class ) ) . newObject ( Models . toLiteral ( f , "" ) ) . toThrowStatement ( ) ) ; return builder . toImplementation ( ) ; } } package com . asakusafw . compiler . operator . processor ; import java . util . List ; import javax . lang . model . element . ExecutableElement ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . ImplementationBuilder ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . compiler . operator . processor . MasterKindOperatorAnalyzer . ResolveException ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterCheck ; @ TargetOperator ( MasterCheck . class ) public class MasterCheckOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) == false ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isBoolean ( ) == false ) { a . error ( "" ) ; } TypeConstraint master = a . getParameterType ( ) ; if ( master . isModel ( ) == false ) { a . error ( , "" ) ; } TypeConstraint transaction = a . getParameterType ( ) ; if ( transaction . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { a . error ( i , "" ) ; } if ( a . hasError ( ) ) { return null ; } ShuffleKey masterKey = a . getParameterKey ( ) ; if ( masterKey == null ) { a . error ( "" ) ; } ShuffleKey transactionKey = a . getParameterKey ( ) ; if ( transactionKey == null ) { a . error ( "" ) ; } ExecutableElement selector = null ; try { selector = MasterKindOperatorAnalyzer . findSelector ( context . environment , context ) ; } catch ( ResolveException e ) { a . error ( e . getMessage ( ) ) ; } MasterCheck annotation = context . element . getAnnotation ( MasterCheck . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } OperatorProcessorUtil . checkPortName ( a , new String [ ] { annotation . foundPort ( ) , annotation . missedPort ( ) , } ) ; if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; if ( selector != null ) { builder . addOperatorHelper ( selector ) ; } builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , masterKey ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , transactionKey ) ; builder . addOutput ( a . getParameterName ( ) + "" + a . getParameterName ( ) , annotation . foundPort ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; builder . addOutput ( a . getParameterName ( ) + "" + a . getParameterName ( ) , annotation . missedPort ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; return builder . toDescriptor ( ) ; } @ Override protected List < ? extends TypeBodyDeclaration > override ( Context context ) { ImplementationBuilder builder = new ImplementationBuilder ( context ) ; ModelFactory f = context . environment . getFactory ( ) ; builder . addStatement ( new TypeBuilder ( f , context . importer . toType ( UnsupportedOperationException . class ) ) . newObject ( Models . toLiteral ( f , "" ) ) . toThrowStatement ( ) ) ; return builder . toImplementation ( ) ; } } package com . asakusafw . compiler . operator . processor ; package com . asakusafw . compiler . operator . processor ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . VariableElement ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . compiler . operator . processor . MasterKindOperatorAnalyzer . ResolveException ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterBranch ; @ TargetOperator ( MasterBranch . class ) public class MasterBranchOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } List < VariableElement > constants = Collections . emptyList ( ) ; if ( a . getReturnType ( ) . isEnum ( ) == false ) { a . error ( "" ) ; } else { constants = a . getReturnType ( ) . getEnumConstants ( ) ; if ( constants . isEmpty ( ) ) { a . error ( "" ) ; } } TypeConstraint master = a . getParameterType ( ) ; if ( master . isModel ( ) == false ) { a . error ( , "" ) ; } TypeConstraint transaction = a . getParameterType ( ) ; if ( transaction . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { if ( a . getParameterType ( i ) . isBasic ( ) == false ) { a . error ( i , "" ) ; } } if ( a . hasError ( ) ) { return null ; } ShuffleKey masterKey = a . getParameterKey ( ) ; if ( masterKey == null ) { a . error ( "" ) ; } ShuffleKey transactionKey = a . getParameterKey ( ) ; if ( transactionKey == null ) { a . error ( "" ) ; } ExecutableElement selector = null ; try { selector = MasterKindOperatorAnalyzer . findSelector ( context . environment , context ) ; } catch ( ResolveException e ) { a . error ( e . getMessage ( ) ) ; } if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; if ( selector != null ) { builder . addOperatorHelper ( selector ) ; } builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , masterKey ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , transactionKey ) ; for ( VariableElement var : constants ) { builder . addOutput ( a . getDocument ( var ) , JavaName . of ( var . getSimpleName ( ) . toString ( ) ) . toMemberName ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . Fold ; @ TargetOperator ( Fold . class ) public class FoldOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isVoid ( ) == false ) { a . error ( "" ) ; } TypeConstraint left = a . getParameterType ( ) ; if ( left . isModel ( ) == false ) { a . error ( , "" ) ; } TypeConstraint right = a . getParameterType ( ) ; if ( right . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { if ( a . getParameterType ( i ) . isBasic ( ) == false ) { a . error ( i , "" ) ; } } if ( a . hasError ( ) ) { return null ; } if ( context . environment . getTypeUtils ( ) . isSameType ( left . getType ( ) , right . getType ( ) ) == false ) { a . error ( , "" ) ; } ShuffleKey foldKey = a . getParameterKey ( ) ; if ( foldKey == null ) { a . error ( "" ) ; } Fold annotation = context . element . getAnnotation ( Fold . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } OperatorProcessorUtil . checkPortName ( a , new String [ ] { annotation . outputPort ( ) , } ) ; if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . addAttribute ( annotation . partialAggregation ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , Fold . INPUT , a . getParameterType ( ) . getType ( ) , , foldKey ) ; builder . addOutput ( "" , annotation . outputPort ( ) , a . getParameterType ( ) . getType ( ) , Fold . INPUT , ) ; for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import javax . lang . model . element . AnnotationValue ; import javax . lang . model . element . Element ; import javax . lang . model . element . ElementKind ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . VariableElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Types ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . DataModelMirror ; import com . asakusafw . compiler . operator . DataModelMirror . Kind ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . compiler . operator . OperatorProcessor ; import com . asakusafw . vocabulary . operator . MasterSelection ; public final class MasterKindOperatorAnalyzer { public static ExecutableElement findSelector ( OperatorCompilingEnvironment environment , OperatorProcessor . Context context ) throws ResolveException { Precondition . checkMustNotBeNull ( context , "" ) ; String selectorName = getSelectorName ( context ) ; if ( selectorName == null ) { return null ; } ExecutableElement selectorMethod = getSelectorMethod ( context , selectorName ) ; checkParameters ( environment , context . element , selectorMethod ) ; return selectorMethod ; } private static void checkParameters ( OperatorCompilingEnvironment environment , ExecutableElement operatorMethod , ExecutableElement selectorMethod ) throws ResolveException { assert environment != null ; assert operatorMethod != null ; assert selectorMethod != null ; assert operatorMethod . getParameters ( ) . isEmpty ( ) == false ; List < ? extends VariableElement > operatorParams = operatorMethod . getParameters ( ) ; List < ? extends VariableElement > selectorParams = selectorMethod . getParameters ( ) ; checkParameterCount ( operatorMethod , selectorMethod ) ; DataModelMirror operatorMaster = environment . loadDataModel ( operatorParams . get ( ) . asType ( ) ) ; DataModelMirror selectorMaster = extractSelectorMaster ( environment , selectorMethod , selectorParams . get ( ) . asType ( ) ) ; if ( isValidMaster ( operatorMaster , selectorMaster ) == false ) { throw new ResolveException ( MessageFormat . format ( "" , selectorMethod . getSimpleName ( ) , operatorMaster ) ) ; } if ( selectorParams . size ( ) == ) { return ; } DataModelMirror operatorTx = environment . loadDataModel ( operatorParams . get ( ) . asType ( ) ) ; DataModelMirror selectorTx = environment . loadDataModel ( selectorParams . get ( ) . asType ( ) ) ; if ( isValidTx ( operatorTx , selectorTx ) == false ) { throw new ResolveException ( MessageFormat . format ( "" , selectorMethod . getSimpleName ( ) , operatorTx ) ) ; } DataModelMirror selectorResult = environment . loadDataModel ( selectorMethod . getReturnType ( ) ) ; if ( isValidResult ( operatorMaster , selectorMaster , selectorResult ) == false ) { throw new ResolveException ( MessageFormat . format ( "" , selectorMethod . getSimpleName ( ) , operatorMaster ) ) ; } for ( int i = , n = selectorParams . size ( ) ; i < n ; i ++ ) { TypeMirror expected = operatorParams . get ( i ) . asType ( ) ; TypeMirror actual = selectorParams . get ( i ) . asType ( ) ; if ( environment . getTypeUtils ( ) . isSubtype ( expected , actual ) == false ) { throw new ResolveException ( MessageFormat . format ( "" , selectorMethod . getSimpleName ( ) , expected , String . valueOf ( i + ) ) ) ; } } } private static boolean isValidMaster ( DataModelMirror operatorMaster , DataModelMirror selectorMaster ) { if ( operatorMaster == null || selectorMaster == null ) { return false ; } return operatorMaster . canContain ( selectorMaster ) ; } private static boolean isValidTx ( DataModelMirror operatorTx , DataModelMirror selectorTx ) { if ( operatorTx == null || selectorTx == null ) { return false ; } return operatorTx . canInvoke ( selectorTx ) ; } private static boolean isValidResult ( DataModelMirror operatorMaster , DataModelMirror selectorMaster , DataModelMirror selectorResult ) { if ( operatorMaster == null || selectorMaster == null || selectorResult == null ) { return false ; } if ( selectorResult . canInvoke ( operatorMaster ) ) { return true ; } if ( selectorMaster . getKind ( ) == Kind . PARTIAL && selectorMaster . isSame ( selectorResult ) ) { return true ; } return false ; } private static void checkParameterCount ( ExecutableElement operatorMethod , ExecutableElement selectorMethod ) throws ResolveException { assert operatorMethod != null ; assert selectorMethod != null ; List < ? extends VariableElement > operatorParams = operatorMethod . getParameters ( ) ; List < ? extends VariableElement > selectorParams = selectorMethod . getParameters ( ) ; if ( operatorParams . size ( ) < selectorParams . size ( ) ) { throw new ResolveException ( MessageFormat . format ( "" , selectorMethod . getSimpleName ( ) ) ) ; } if ( selectorParams . size ( ) == ) { throw new ResolveException ( MessageFormat . format ( "" , selectorMethod . getSimpleName ( ) , operatorParams . get ( ) . asType ( ) ) ) ; } } private static DataModelMirror extractSelectorMaster ( OperatorCompilingEnvironment environment , ExecutableElement selectorMethod , TypeMirror firstParameter ) throws ResolveException { assert environment != null ; assert selectorMethod != null ; assert firstParameter != null ; TypeMirror erasedSelector = environment . getErasure ( firstParameter ) ; Types types = environment . getTypeUtils ( ) ; if ( types . isSameType ( erasedSelector , environment . getDeclaredType ( List . class ) ) == false ) { throw new ResolveException ( MessageFormat . format ( "" , selectorMethod . getSimpleName ( ) ) ) ; } DeclaredType list = ( DeclaredType ) firstParameter ; if ( list . getTypeArguments ( ) . size ( ) != ) { throw new ResolveException ( MessageFormat . format ( "" , selectorMethod . getSimpleName ( ) ) ) ; } TypeMirror selectorElement = list . getTypeArguments ( ) . get ( ) ; return environment . loadDataModel ( selectorElement ) ; } private static ExecutableElement getSelectorMethod ( OperatorProcessor . Context context , String selectorName ) throws ResolveException { assert context != null ; assert selectorName != null ; for ( Element member : context . element . getEnclosingElement ( ) . getEnclosedElements ( ) ) { if ( member . getKind ( ) != ElementKind . METHOD ) { continue ; } if ( member . getSimpleName ( ) . contentEquals ( selectorName ) ) { if ( member . getAnnotation ( MasterSelection . class ) == null ) { throw new ResolveException ( MessageFormat . format ( "" , selectorName , MasterSelection . class . getSimpleName ( ) ) ) ; } return ( ExecutableElement ) member ; } } throw new ResolveException ( MessageFormat . format ( "" , selectorName ) ) ; } private static String getSelectorName ( OperatorProcessor . Context context ) { assert context != null ; for ( Map . Entry < ? extends ExecutableElement , ? extends AnnotationValue > entry : context . annotation . getElementValues ( ) . entrySet ( ) ) { if ( entry . getKey ( ) . getSimpleName ( ) . contentEquals ( MasterSelection . ELEMENT_NAME ) ) { Object value = entry . getValue ( ) . getValue ( ) ; if ( value instanceof String ) { return ( String ) value ; } } } return null ; } private MasterKindOperatorAnalyzer ( ) { return ; } public static class ResolveException extends Exception { private static final long serialVersionUID = ; public ResolveException ( String message ) { super ( message ) ; } public ResolveException ( String message , Throwable cause ) { super ( message , cause ) ; } } } package com . asakusafw . compiler . operator . processor ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . vocabulary . operator . Convert ; @ TargetOperator ( Convert . class ) public class ConvertOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isConcreteModel ( ) == false ) { a . error ( "" ) ; } if ( a . getParameterType ( ) . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { if ( a . getParameterType ( i ) . isBasic ( ) == false ) { a . error ( i , "" ) ; } } Convert annotation = context . element . getAnnotation ( Convert . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } OperatorProcessorUtil . checkPortName ( a , new String [ ] { annotation . originalPort ( ) , annotation . convertedPort ( ) , } ) ; if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , ) ; builder . addOutput ( "" , annotation . originalPort ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , ) ; builder . addOutput ( a . getReturnDocument ( ) , annotation . convertedPort ( ) , a . getReturnType ( ) . getType ( ) , null , null ) ; for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . VariableElement ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . vocabulary . operator . Branch ; @ TargetOperator ( Branch . class ) public class BranchOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } List < VariableElement > constants = Collections . emptyList ( ) ; if ( a . getReturnType ( ) . isEnum ( ) == false ) { a . error ( "" ) ; } else { constants = a . getReturnType ( ) . getEnumConstants ( ) ; if ( constants . isEmpty ( ) ) { a . error ( "" ) ; } } if ( a . getParameterType ( ) . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { if ( a . getParameterType ( i ) . isBasic ( ) == false ) { a . error ( i , "" ) ; } } if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , ) ; for ( VariableElement var : constants ) { builder . addOutput ( a . getDocument ( var ) , JavaName . of ( var . getSimpleName ( ) . toString ( ) ) . toMemberName ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ImplementationBuilder ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . GroupSort ; import com . asakusafw . vocabulary . operator . Unique ; @ Deprecated @ TargetOperator ( Unique . class ) public class UniqueOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) == false ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isVoid ( ) == false ) { a . error ( "" ) ; } if ( a . getParameterType ( ) . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { a . error ( i , "" ) ; } if ( a . hasError ( ) ) { return null ; } ShuffleKey key = a . getParameterKey ( ) ; if ( key == null ) { a . error ( "" ) ; return null ; } if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , , key ) ; builder . addOutput ( "" , "" , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; builder . addOutput ( "" , "" , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , null ) ; return builder . toDescriptor ( ) ; } @ Override protected List < ? extends TypeBodyDeclaration > override ( Context context ) { ImplementationBuilder builder = new ImplementationBuilder ( context ) ; ModelFactory f = context . environment . getFactory ( ) ; builder . addStatement ( new TypeBuilder ( f , context . importer . toType ( UnsupportedOperationException . class ) ) . newObject ( Models . toLiteral ( f , "" ) ) . toThrowStatement ( ) ) ; return builder . toImplementation ( ) ; } } package com . asakusafw . compiler . operator . processor ; import javax . lang . model . type . TypeMirror ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . vocabulary . operator . Extract ; @ TargetOperator ( Extract . class ) public class ExtractOperatorProcessor extends AbstractOperatorProcessor { private static final int RESULT_START = ; @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isVoid ( ) == false ) { a . error ( "" ) ; } if ( a . getParameterType ( ) . isModel ( ) == false ) { a . error ( , "" ) ; } int startParameters = RESULT_START ; for ( int i = RESULT_START , n = a . countParameters ( ) ; i < n ; i ++ ) { TypeConstraint param = a . getParameterType ( i ) ; if ( param . isResult ( ) == false ) { break ; } else if ( param . getTypeArgument ( ) . isModel ( ) == false ) { a . error ( i , "" ) ; } else { startParameters ++ ; } } if ( startParameters == RESULT_START ) { a . error ( "" ) ; } for ( int i = startParameters , n = a . countParameters ( ) ; i < n ; i ++ ) { TypeConstraint param = a . getParameterType ( i ) ; if ( param . isResult ( ) ) { a . error ( i , "" ) ; } else if ( param . isBasic ( ) == false ) { a . error ( i , "" ) ; } } if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( Extract . class , context ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , ) ; for ( int i = ; i < startParameters ; i ++ ) { TypeConstraint outputType = a . getParameterType ( i ) . getTypeArgument ( ) ; TypeMirror outputTypeMirror = outputType . getType ( ) ; String found = builder . findInput ( outputTypeMirror ) ; if ( found == null && outputType . isProjectiveModel ( ) ) { a . error ( "" , outputTypeMirror ) ; } builder . addOutput ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , outputTypeMirror , found , i ) ; } for ( int i = startParameters , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import java . util . Set ; import java . util . regex . Pattern ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . utils . collections . Sets ; public final class OperatorProcessorUtil { public static void checkPortName ( ExecutableAnalyzer analyzer , String [ ] names ) { Precondition . checkMustNotBeNull ( analyzer , "" ) ; Precondition . checkMustNotBeNull ( names , "" ) ; for ( String name : names ) { checkName ( analyzer , name ) ; } Set < String > saw = Sets . create ( ) ; for ( String name : names ) { if ( saw . contains ( name ) ) { analyzer . error ( "" , name ) ; saw . remove ( name ) ; } else { saw . add ( name ) ; } } } private static final Pattern VALID_NAME = Pattern . compile ( "" ) ; private static void checkName ( ExecutableAnalyzer analyzer , String name ) { assert name != null ; if ( VALID_NAME . matcher ( name ) . matches ( ) == false ) { analyzer . error ( "" , name ) ; } } private OperatorProcessorUtil ( ) { return ; } } package com . asakusafw . compiler . operator . processor ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . ImplementationBuilder ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . operator . Split ; @ TargetOperator ( Split . class ) public class SplitOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isGeneric ( ) ) { a . error ( "" ) ; } if ( a . isAbstract ( ) == false ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isVoid ( ) == false ) { a . error ( "" ) ; } if ( a . getParameterType ( ) . isConcreteModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = ; i <= ; i ++ ) { if ( a . getParameterType ( i ) . isResult ( ) == false ) { a . error ( i , "" , i + ) ; } else if ( a . getParameterType ( i ) . getTypeArgument ( ) . isModel ( ) == false ) { a . error ( i , "" , i + ) ; } } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { a . error ( i , "" ) ; } if ( a . hasError ( ) ) { return null ; } TypeConstraint joined = a . getParameterType ( ) ; TypeConstraint from = a . getParameterType ( ) . getTypeArgument ( ) ; TypeConstraint join = a . getParameterType ( ) . getTypeArgument ( ) ; if ( joined . isJoinedModel ( from . getType ( ) , join . getType ( ) ) == false ) { a . error ( , "" ) ; return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , ) ; builder . addOutput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getTypeArgument ( ) . getType ( ) , null , ) ; builder . addOutput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getTypeArgument ( ) . getType ( ) , null , ) ; return builder . toDescriptor ( ) ; } @ Override protected List < ? extends TypeBodyDeclaration > override ( Context context ) { ImplementationBuilder builder = new ImplementationBuilder ( context ) ; ModelFactory f = context . environment . getFactory ( ) ; builder . addStatement ( new TypeBuilder ( f , context . importer . toType ( UnsupportedOperationException . class ) ) . newObject ( Models . toLiteral ( f , "" ) ) . toThrowStatement ( ) ) ; return builder . toImplementation ( ) ; } } package com . asakusafw . compiler . operator . processor ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . DocElement ; import com . asakusafw . vocabulary . flow . graph . Connectivity ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . operator . Logging ; @ TargetOperator ( Logging . class ) public class LoggingOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isString ( ) == false ) { a . error ( "" ) ; } if ( a . getParameterType ( ) . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { if ( a . getParameterType ( i ) . isBasic ( ) == false ) { a . error ( i , "" ) ; } } Logging annotation = context . element . getAnnotation ( Logging . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } OperatorProcessorUtil . checkPortName ( a , new String [ ] { annotation . outputPort ( ) , } ) ; if ( a . hasError ( ) ) { return null ; } List < DocElement > elements = Lists . create ( ) ; elements . addAll ( a . getExecutableDocument ( ) ) ; elements . add ( context . environment . getFactory ( ) . newDocText ( "" ) ) ; Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( a . getObservationCount ( ObservationCount . AT_LEAST_ONCE ) ) ; builder . addAttribute ( Connectivity . OPTIONAL ) ; builder . addAttribute ( annotation . value ( ) ) ; builder . setDocumentation ( elements ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , ) ; builder . addOutput ( "" , annotation . outputPort ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , ) ; for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator . processor ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . AbstractOperatorProcessor ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . vocabulary . operator . Update ; @ TargetOperator ( Update . class ) public class UpdateOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . isAbstract ( ) ) { a . error ( "" ) ; } if ( a . getReturnType ( ) . isVoid ( ) == false ) { a . error ( "" ) ; } if ( a . getParameterType ( ) . isModel ( ) == false ) { a . error ( , "" ) ; } for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { if ( a . getParameterType ( i ) . isBasic ( ) == false ) { a . error ( i , "" ) ; } } Update annotation = context . element . getAnnotation ( Update . class ) ; if ( annotation == null ) { a . error ( "" ) ; return null ; } OperatorProcessorUtil . checkPortName ( a , new String [ ] { annotation . outputPort ( ) , } ) ; if ( a . hasError ( ) ) { return null ; } Builder builder = new Builder ( getTargetAnnotationType ( ) , context ) ; builder . addAttribute ( a . getObservationCount ( ) ) ; builder . setDocumentation ( a . getExecutableDocument ( ) ) ; builder . addInput ( a . getParameterDocument ( ) , a . getParameterName ( ) , a . getParameterType ( ) . getType ( ) , ) ; builder . addOutput ( "" , annotation . outputPort ( ) , a . getParameterType ( ) . getType ( ) , a . getParameterName ( ) , ) ; for ( int i = , n = a . countParameters ( ) ; i < n ; i ++ ) { builder . addParameter ( a . getParameterDocument ( i ) , a . getParameterName ( i ) , a . getParameterType ( i ) . getType ( ) , i ) ; } return builder . toDescriptor ( ) ; } } package com . asakusafw . compiler . operator ; import java . lang . annotation . Annotation ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . ServiceLoader ; import java . util . Set ; import javax . annotation . processing . Completion ; import javax . annotation . processing . ProcessingEnvironment ; import javax . annotation . processing . Processor ; import javax . annotation . processing . RoundEnvironment ; import javax . lang . model . SourceVersion ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . Element ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; import javax . tools . Diagnostic ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . util . Models ; public class OperatorCompiler implements Processor { public static final String VERSION = "" ; static final Logger LOG = LoggerFactory . getLogger ( OperatorCompiler . class ) ; private OperatorCompilingEnvironment environment ; private Set < OperatorProcessor > subProcessors ; @ Override public void init ( ProcessingEnvironment processingEnv ) { try { OperatorCompilerOptions options = loadOptions ( processingEnv ) ; this . environment = new OperatorCompilingEnvironment ( processingEnv , Models . getModelFactory ( ) , options ) ; this . subProcessors = loadSubProcessors ( environment ) ; } catch ( RuntimeException e ) { environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , e . getMessage ( ) ) ; LOG . error ( e . getMessage ( ) , e ) ; } } protected OperatorCompilerOptions loadOptions ( ProcessingEnvironment processingEnv ) { Precondition . checkMustNotBeNull ( processingEnv , "" ) ; return OperatorCompilerOptions . parse ( processingEnv . getOptions ( ) ) ; } private Set < OperatorProcessor > loadSubProcessors ( OperatorCompilingEnvironment env ) { assert env != null ; Map < Class < ? > , OperatorProcessor > results = Maps . create ( ) ; for ( OperatorProcessor proc : findOperatorProcessors ( env ) ) { proc . initialize ( env ) ; Class < ? extends Annotation > target = proc . getTargetAnnotationType ( ) ; if ( target == null ) { env . getMessager ( ) . printMessage ( Diagnostic . Kind . WARNING , MessageFormat . format ( "" , proc . getClass ( ) . getName ( ) ) ) ; } else if ( results . containsKey ( target ) ) { env . getMessager ( ) . printMessage ( Diagnostic . Kind . WARNING , MessageFormat . format ( "" , proc . getClass ( ) . getName ( ) , target . getName ( ) , results . get ( target ) . getClass ( ) . getName ( ) ) ) ; } else { results . put ( target , proc ) ; } } return Sets . from ( results . values ( ) ) ; } protected Iterable < OperatorProcessor > findOperatorProcessors ( OperatorCompilingEnvironment env ) { List < OperatorProcessor > results = Lists . create ( ) ; Iterator < OperatorProcessor > iter = ServiceLoader . load ( OperatorProcessor . class , env . getServiceClassLoader ( ) ) . iterator ( ) ; while ( iter . hasNext ( ) ) { try { results . add ( iter . next ( ) ) ; } catch ( RuntimeException e ) { environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , "" ) ; LOG . debug ( "" , e ) ; } } return results ; } @ Override public Set < String > getSupportedOptions ( ) { return Collections . emptySet ( ) ; } @ Override public SourceVersion getSupportedSourceVersion ( ) { return SourceVersion . RELEASE_6 ; } @ Override public Set < String > getSupportedAnnotationTypes ( ) { Set < String > results = Sets . create ( ) ; for ( OperatorProcessor proc : subProcessors ) { Class < ? extends Annotation > type = proc . getTargetAnnotationType ( ) ; results . add ( type . getName ( ) ) ; } return results ; } @ Override public Iterable < ? extends Completion > getCompletions ( Element element , AnnotationMirror annotation , ExecutableElement member , String userText ) { return Collections . emptyList ( ) ; } @ Override public boolean process ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv ) { assert annotations != null ; assert roundEnv != null ; if ( annotations . isEmpty ( ) ) { return false ; } try { start ( roundEnv ) ; } catch ( OperatorCompilerException e ) { environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , e . getMessage ( ) ) ; LOG . debug ( e . getMessage ( ) , e ) ; } catch ( RuntimeException e ) { environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , MessageFormat . format ( "" , e . toString ( ) ) ) ; LOG . error ( "" , e ) ; } return false ; } private void start ( RoundEnvironment roundEnv ) { assert roundEnv != null ; OperatorClassCollector collector = new OperatorClassCollector ( environment , roundEnv ) ; for ( OperatorProcessor proc : subProcessors ) { collector . add ( proc ) ; } List < OperatorClass > classes = collector . collect ( ) ; OperatorClassEmitter emitter = new OperatorClassEmitter ( environment ) ; for ( OperatorClass operatorClass : classes ) { emitter . emit ( operatorClass ) ; } } } package com . asakusafw . compiler . operator . flow ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import javax . annotation . processing . Completion ; import javax . annotation . processing . ProcessingEnvironment ; import javax . annotation . processing . Processor ; import javax . annotation . processing . RoundEnvironment ; import javax . lang . model . SourceVersion ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . Element ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; import javax . tools . Diagnostic ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . operator . OperatorCompilerException ; import com . asakusafw . compiler . operator . OperatorCompilerOptions ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . FlowPart ; public class FlowOperatorCompiler implements Processor { public static final String VERSION = "" ; static final Logger LOG = LoggerFactory . getLogger ( FlowOperatorCompiler . class ) ; private OperatorCompilingEnvironment environment ; @ Override public void init ( ProcessingEnvironment processingEnv ) { this . environment = new OperatorCompilingEnvironment ( processingEnv , Models . getModelFactory ( ) , OperatorCompilerOptions . parse ( processingEnv . getOptions ( ) ) ) ; } @ Override public Set < String > getSupportedOptions ( ) { return Collections . emptySet ( ) ; } @ Override public Set < String > getSupportedAnnotationTypes ( ) { Set < String > results = Sets . create ( ) ; results . add ( FlowPart . class . getName ( ) ) ; return results ; } @ Override public SourceVersion getSupportedSourceVersion ( ) { return SourceVersion . RELEASE_6 ; } @ Override public Iterable < ? extends Completion > getCompletions ( Element element , AnnotationMirror annotation , ExecutableElement member , String userText ) { return Collections . emptyList ( ) ; } @ Override public boolean process ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv ) { try { start ( roundEnv ) ; } catch ( OperatorCompilerException e ) { environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , e . getMessage ( ) ) ; LOG . debug ( e . getMessage ( ) , e ) ; } return false ; } private void start ( RoundEnvironment roundEnv ) { assert roundEnv != null ; FlowPartClassCollector collector = new FlowPartClassCollector ( environment ) ; for ( Element element : roundEnv . getElementsAnnotatedWith ( FlowPart . class ) ) { collector . add ( element ) ; } List < FlowPartClass > collected = collector . collect ( ) ; FlowClassEmitter emitter = new FlowClassEmitter ( environment ) ; for ( FlowPartClass aClass : collected ) { emitter . emit ( aClass ) ; } } } package com . asakusafw . compiler . operator . flow ; package com . asakusafw . compiler . operator . flow ; import java . util . List ; import javax . lang . model . element . TypeElement ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . OperatorPortDeclaration ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . DocElement ; public class FlowPartClass { private TypeElement element ; private List < DocElement > documentation ; private List < OperatorPortDeclaration > inputPorts ; private List < OperatorPortDeclaration > outputPorts ; private List < OperatorPortDeclaration > parameters ; public FlowPartClass ( TypeElement element , List < ? extends DocElement > documentation , List < OperatorPortDeclaration > inputPorts , List < OperatorPortDeclaration > outputPorts , List < OperatorPortDeclaration > parameters ) { Precondition . checkMustNotBeNull ( element , "" ) ; Precondition . checkMustNotBeNull ( documentation , "" ) ; Precondition . checkMustNotBeNull ( inputPorts , "" ) ; Precondition . checkMustNotBeNull ( outputPorts , "" ) ; Precondition . checkMustNotBeNull ( parameters , "" ) ; this . element = element ; this . documentation = Lists . from ( documentation ) ; this . inputPorts = Lists . from ( inputPorts ) ; this . outputPorts = Lists . from ( outputPorts ) ; this . parameters = Lists . from ( parameters ) ; } public TypeElement getElement ( ) { return element ; } public List < DocElement > getDocumentation ( ) { return documentation ; } public List < OperatorPortDeclaration > getInputPorts ( ) { return inputPorts ; } public List < OperatorPortDeclaration > getOutputPorts ( ) { return outputPorts ; } public List < OperatorPortDeclaration > getParameters ( ) { return parameters ; } } package com . asakusafw . compiler . operator . flow ; import java . text . MessageFormat ; import java . util . List ; import javax . lang . model . element . Element ; import javax . lang . model . element . ElementKind ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . Modifier ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . TypeKind ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Types ; import javax . tools . Diagnostic ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . ExecutableAnalyzer ; import com . asakusafw . compiler . operator . ExecutableAnalyzer . TypeConstraint ; import com . asakusafw . compiler . operator . OperatorCompilerException ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . compiler . operator . OperatorPortDeclaration ; import com . asakusafw . compiler . operator . PortTypeDescription ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . DocElement ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class FlowPartClassCollector { private final OperatorCompilingEnvironment environment ; private final List < FlowPartClass > collected ; private boolean sawError ; public FlowPartClassCollector ( OperatorCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; this . collected = Lists . create ( ) ; this . sawError = false ; } public void add ( Element element ) { Precondition . checkMustNotBeNull ( element , "" ) ; if ( element . getKind ( ) != ElementKind . CLASS ) { error ( element , "" ) ; return ; } TypeElement typeDecl = ( TypeElement ) element ; FlowPartClass result = toFlowPartClass ( typeDecl ) ; if ( result != null ) { collected . add ( result ) ; } } private FlowPartClass toFlowPartClass ( Element element ) { assert element != null ; if ( validateClassModifiers ( element ) == false ) { return null ; } TypeElement type = ( TypeElement ) element ; ExecutableElement ctor = findConstructor ( type ) ; if ( ctor == null ) { return null ; } validateConstructorModifiers ( ctor ) ; FlowPartClass aClass = analyze ( type , ctor ) ; return aClass ; } private FlowPartClass analyze ( TypeElement aClass , ExecutableElement ctor ) { assert aClass != null ; assert ctor != null ; ExecutableAnalyzer analyzer = new ExecutableAnalyzer ( environment , ctor ) ; List < ? extends DocElement > documentation = analyzer . getDocument ( aClass ) ; List < OperatorPortDeclaration > inputPorts = Lists . create ( ) ; List < OperatorPortDeclaration > outputPorts = Lists . create ( ) ; List < OperatorPortDeclaration > parameters = Lists . create ( ) ; for ( int i = , n = analyzer . countParameters ( ) ; i < n ; i ++ ) { OperatorPortDeclaration port = analyzePort ( analyzer , i ) ; if ( port == null ) { continue ; } else if ( port . getKind ( ) == OperatorPortDeclaration . Kind . INPUT ) { inputPorts . add ( port ) ; } else if ( port . getKind ( ) == OperatorPortDeclaration . Kind . OUTPUT ) { outputPorts . add ( port ) ; } else { parameters . add ( port ) ; } } if ( inputPorts . isEmpty ( ) && outputPorts . isEmpty ( ) ) { analyzer . error ( "" ) ; } if ( analyzer . hasError ( ) ) { sawError = true ; return null ; } outputPorts = inferTypeVariables ( analyzer , inputPorts , outputPorts , parameters ) ; if ( analyzer . hasError ( ) ) { sawError = true ; return null ; } return new FlowPartClass ( aClass , documentation , inputPorts , outputPorts , parameters ) ; } private OperatorPortDeclaration analyzePort ( ExecutableAnalyzer analyzer , int index ) { TypeConstraint type = analyzer . getParameterType ( index ) ; if ( type . isIn ( ) ) { return toPort ( OperatorPortDeclaration . Kind . INPUT , analyzer , type , index ) ; } else if ( type . isOut ( ) ) { return toPort ( OperatorPortDeclaration . Kind . OUTPUT , analyzer , type , index ) ; } else { return toParameter ( analyzer , index , type ) ; } } private List < OperatorPortDeclaration > inferTypeVariables ( ExecutableAnalyzer analyzer , List < OperatorPortDeclaration > inputPorts , List < OperatorPortDeclaration > outputPorts , List < OperatorPortDeclaration > parameters ) { assert analyzer != null ; assert inputPorts != null ; assert outputPorts != null ; assert parameters != null ; List < OperatorPortDeclaration > inferred = Lists . create ( ) ; for ( OperatorPortDeclaration output : outputPorts ) { if ( output . getType ( ) . getRepresentation ( ) . getKind ( ) != TypeKind . TYPEVAR ) { inferred . add ( new OperatorPortDeclaration ( output . getKind ( ) , output . getDocumentation ( ) , output . getName ( ) , PortTypeDescription . direct ( output . getType ( ) . getRepresentation ( ) ) , output . getParameterPosition ( ) , null ) ) ; } else { OperatorPortDeclaration outputType = inferOutputType ( output , inputPorts , parameters ) ; if ( outputType != null ) { inferred . add ( outputType ) ; } else { analyzer . error ( output . getParameterPosition ( ) , "" , output . getName ( ) , output . getType ( ) . getRepresentation ( ) ) ; } } } return inferred ; } private OperatorPortDeclaration inferOutputType ( OperatorPortDeclaration output , List < OperatorPortDeclaration > inputPorts , List < OperatorPortDeclaration > parameters ) { assert output != null ; assert inputPorts != null ; assert parameters != null ; Types types = environment . getTypeUtils ( ) ; TypeMirror outputType = output . getType ( ) . getRepresentation ( ) ; for ( OperatorPortDeclaration input : inputPorts ) { if ( types . isSameType ( outputType , input . getType ( ) . getRepresentation ( ) ) ) { return new OperatorPortDeclaration ( output . getKind ( ) , output . getDocumentation ( ) , output . getName ( ) , PortTypeDescription . reference ( outputType , input . getName ( ) ) , output . getParameterPosition ( ) , null ) ; } } DeclaredType classType = environment . getDeclaredType ( Class . class ) ; for ( OperatorPortDeclaration param : parameters ) { TypeMirror paramType = param . getType ( ) . getRepresentation ( ) ; if ( paramType . getKind ( ) != TypeKind . DECLARED ) { continue ; } DeclaredType declParamType = ( DeclaredType ) paramType ; if ( declParamType . getTypeArguments ( ) . size ( ) != ) { continue ; } if ( types . isSameType ( environment . getErasure ( paramType ) , classType ) == false ) { continue ; } if ( types . isSameType ( declParamType . getTypeArguments ( ) . get ( ) , outputType ) ) { return new OperatorPortDeclaration ( output . getKind ( ) , output . getDocumentation ( ) , output . getName ( ) , PortTypeDescription . reference ( outputType , param . getName ( ) ) , output . getParameterPosition ( ) , null ) ; } } return null ; } private OperatorPortDeclaration toPort ( OperatorPortDeclaration . Kind kind , ExecutableAnalyzer analyzer , TypeConstraint type , int index ) { assert analyzer != null ; assert type != null ; TypeConstraint dataType = type . getTypeArgument ( ) ; if ( dataType . isModel ( ) == false ) { analyzer . error ( index , "" ) ; return null ; } return new OperatorPortDeclaration ( kind , analyzer . getParameterDocument ( index ) , analyzer . getParameterName ( index ) , PortTypeDescription . reference ( dataType . getType ( ) , analyzer . getParameterName ( index ) ) , index , null ) ; } private OperatorPortDeclaration toParameter ( ExecutableAnalyzer analyzer , int index , TypeConstraint type ) { assert analyzer != null ; assert type != null ; if ( type . isOperator ( ) ) { analyzer . error ( index , "" ) ; return null ; } return new OperatorPortDeclaration ( OperatorPortDeclaration . Kind . CONSTANT , analyzer . getParameterDocument ( index ) , analyzer . getParameterName ( index ) , PortTypeDescription . direct ( type . getType ( ) ) , index , null ) ; } private ExecutableElement findConstructor ( TypeElement type ) { assert type != null ; List < ExecutableElement > elements = Lists . create ( ) ; for ( Element element : type . getEnclosedElements ( ) ) { if ( element . getKind ( ) == ElementKind . CONSTRUCTOR && element . getModifiers ( ) . contains ( Modifier . PUBLIC ) ) { elements . add ( ( ExecutableElement ) element ) ; } } if ( elements . isEmpty ( ) ) { error ( type , "" ) ; return null ; } if ( elements . size ( ) >= ) { for ( ExecutableElement odd : elements ) { error ( odd , "" ) ; } return null ; } return elements . get ( ) ; } public List < FlowPartClass > collect ( ) { if ( sawError ) { throw new OperatorCompilerException ( "" ) ; } return collected ; } private boolean validateClassModifiers ( Element element ) { assert element != null ; TypeElement type = ( TypeElement ) element ; DeclaredType superType = environment . getDeclaredType ( FlowDescription . class ) ; if ( environment . getTypeUtils ( ) . isSubtype ( type . asType ( ) , superType ) == false ) { raiseInvalidClass ( type , MessageFormat . format ( "" , "" , FlowDescription . class . getName ( ) ) ) ; } if ( type . getEnclosingElement ( ) . getKind ( ) != ElementKind . PACKAGE ) { raiseInvalidClass ( type , "" ) ; } if ( type . getModifiers ( ) . contains ( Modifier . PUBLIC ) == false ) { raiseInvalidClass ( type , "" ) ; } if ( type . getModifiers ( ) . contains ( Modifier . ABSTRACT ) ) { raiseInvalidClass ( type , "" ) ; } return true ; } private void validateConstructorModifiers ( ExecutableElement ctor ) { assert ctor != null ; if ( ctor . getThrownTypes ( ) . isEmpty ( ) == false ) { error ( ctor , "" ) ; } if ( ctor . getTypeParameters ( ) . isEmpty ( ) == false ) { error ( ctor , "" ) ; } } private void raiseInvalidClass ( TypeElement element , String message ) { error ( element , MessageFormat . format ( message , element . getQualifiedName ( ) ) ) ; } private void error ( Element element , String message ) { assert element != null ; assert message != null ; this . environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , message , element ) ; this . sawError = true ; } } package com . asakusafw . compiler . operator . flow ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . PackageElement ; import javax . tools . Diagnostic ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ImportDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; public class FlowClassEmitter { static final Logger LOG = LoggerFactory . getLogger ( FlowClassEmitter . class ) ; private final OperatorCompilingEnvironment environment ; public FlowClassEmitter ( OperatorCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public void emit ( FlowPartClass aClass ) { assert aClass != null ; ModelFactory f = environment . getFactory ( ) ; PackageDeclaration packageDecl = getPackage ( f , aClass ) ; ImportBuilder imports = getImportBuilder ( f , packageDecl ) ; FlowFactoryClassGenerator generator = new FlowFactoryClassGenerator ( environment , f , imports , aClass ) ; TypeDeclaration type = generator . generate ( ) ; List < ImportDeclaration > decls = imports . toImportDeclarations ( ) ; try { emit ( f , packageDecl , decls , type ) ; } catch ( IOException e ) { LOG . debug ( e . getMessage ( ) , e ) ; environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , MessageFormat . format ( "" , aClass . getElement ( ) . getQualifiedName ( ) . toString ( ) , e . getMessage ( ) ) ) ; } } private void emit ( ModelFactory factory , PackageDeclaration packageDecl , List < ImportDeclaration > importDecls , TypeDeclaration typeDecl ) throws IOException { CompilationUnit unit = factory . newCompilationUnit ( packageDecl , importDecls , Collections . singletonList ( typeDecl ) , Collections . < Comment > emptyList ( ) ) ; environment . emit ( unit ) ; } private PackageDeclaration getPackage ( ModelFactory factory , FlowPartClass aClass ) { PackageElement parent = ( PackageElement ) aClass . getElement ( ) . getEnclosingElement ( ) ; return new Jsr269 ( factory ) . convert ( parent ) ; } private ImportBuilder getImportBuilder ( ModelFactory factory , PackageDeclaration packageDecl ) { assert factory != null ; assert packageDecl != null ; return new ImportBuilder ( factory , packageDecl , Strategy . TOP_LEVEL ) ; } } package com . asakusafw . compiler . operator . flow ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . compiler . operator . OperatorPortDeclaration ; import com . asakusafw . compiler . operator . util . GeneratorUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . Inline ; public class FlowFactoryClassGenerator { static final String RESOLVER_FIELD_NAME = "" ; private final ModelFactory factory ; private final ImportBuilder importer ; private final FlowPartClass flowClass ; private final GeneratorUtil util ; private final OperatorCompilingEnvironment environment ; public FlowFactoryClassGenerator ( OperatorCompilingEnvironment environment , ModelFactory factory , ImportBuilder importer , FlowPartClass flowClass ) { this . environment = environment ; this . factory = factory ; this . importer = importer ; this . flowClass = flowClass ; this . util = new GeneratorUtil ( environment , factory , importer ) ; } public TypeDeclaration generate ( ) { SimpleName name = getClassName ( ) ; importer . resolvePackageMember ( Models . append ( factory , name , getObjectClassName ( ) ) ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . code ( flowClass . getElement ( ) . getSimpleName ( ) . toString ( ) ) . text ( "" ) . seeType ( new Jsr269 ( factory ) . convert ( environment . getErasure ( flowClass . getElement ( ) . asType ( ) ) ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( util . t ( Generated . class ) , util . v ( "" , FlowOperatorCompiler . class . getSimpleName ( ) , FlowOperatorCompiler . VERSION ) ) . Public ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . < Type > emptyList ( ) , createMembers ( ) ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; TypeDeclaration objectClass = createObjectClass ( ) ; results . add ( objectClass ) ; NamedType objectType = ( NamedType ) importer . resolvePackageMember ( Models . append ( factory , getClassName ( ) , objectClass . getName ( ) ) ) ; MethodDeclaration factoryMethod = createFactoryMethod ( objectType ) ; if ( factoryMethod != null ) { results . add ( factoryMethod ) ; } return results ; } private TypeDeclaration createObjectClass ( ) { SimpleName name = getObjectClassName ( ) ; NamedType objectType = ( NamedType ) importer . resolvePackageMember ( Models . append ( factory , getClassName ( ) , name ) ) ; List < TypeBodyDeclaration > members = createObjectMembers ( objectType ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . inline ( flowClass . getDocumentation ( ) ) . seeType ( new Jsr269 ( factory ) . convert ( environment . getErasure ( flowClass . getElement ( ) . asType ( ) ) ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Static ( ) . Final ( ) . toAttributes ( ) , name , util . toTypeParameters ( flowClass . getElement ( ) ) , null , Collections . singletonList ( util . t ( Operator . class ) ) , members ) ; } private SimpleName getObjectClassName ( ) { return factory . newSimpleName ( JavaName . of ( flowClass . getElement ( ) . getSimpleName ( ) . toString ( ) ) . toTypeName ( ) ) ; } private List < TypeBodyDeclaration > createObjectMembers ( NamedType objectType ) { assert objectType != null ; NameGenerator names = new NameGenerator ( factory ) ; List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createResolverField ( ) ) ; for ( OperatorPortDeclaration var : flowClass . getOutputPorts ( ) ) { results . add ( createObjectOutputField ( var , names ) ) ; } results . add ( createObjectConstructor ( objectType , names ) ) ; results . add ( createRenamer ( objectType , names ) ) ; results . add ( createInliner ( objectType , names ) ) ; return results ; } private FieldDeclaration createResolverField ( ) { return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , util . t ( FlowElementResolver . class ) , factory . newSimpleName ( RESOLVER_FIELD_NAME ) , null ) ; } private MethodDeclaration createRenamer ( NamedType objectType , NameGenerator names ) { assert objectType != null ; assert names != null ; SimpleName newName = names . create ( "" ) ; return factory . newMethodDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . param ( newName ) . text ( "" ) . returns ( ) . text ( "" ) . exception ( util . t ( IllegalArgumentException . class ) ) . text ( "" ) . code ( "" ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , getType ( objectType ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( util . t ( String . class ) , newName ) ) , Arrays . asList ( new Statement [ ] { new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( RESOLVER_FIELD_NAME ) . method ( "" , newName ) . toStatement ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . toReturnStatement ( ) , } ) ) ; } private MethodDeclaration createInliner ( NamedType objectType , NameGenerator names ) { assert objectType != null ; assert names != null ; SimpleName optimize = names . create ( "" ) ; return factory . newMethodDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . param ( optimize ) . text ( "" ) . returns ( ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , getType ( objectType ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( util . t ( boolean . class ) , optimize ) ) , Arrays . asList ( new Statement [ ] { new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( RESOLVER_FIELD_NAME ) . method ( "" ) . method ( "" , factory . newConditionalExpression ( optimize , new TypeBuilder ( factory , util . t ( Inline . class ) ) . field ( Inline . FORCE_AGGREGATE . name ( ) ) . toExpression ( ) , new TypeBuilder ( factory , util . t ( Inline . class ) ) . field ( Inline . KEEP_SEGREGATED . name ( ) ) . toExpression ( ) ) ) . toStatement ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . toReturnStatement ( ) , } ) ) ; } private TypeBodyDeclaration createObjectOutputField ( OperatorPortDeclaration var , NameGenerator names ) { assert var != null ; assert names != null ; return factory . newFieldDeclaration ( new JavadocBuilder ( factory ) . inline ( var . getDocumentation ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Final ( ) . toAttributes ( ) , util . toSourceType ( var . getType ( ) . getRepresentation ( ) ) , factory . newSimpleName ( names . reserve ( var . getName ( ) ) ) , null ) ; } private TypeBodyDeclaration createObjectConstructor ( NamedType objectType , NameGenerator names ) { assert objectType != null ; List < FormalParameterDeclaration > parameters = createParametersForConstructor ( names ) ; List < Statement > statements = createBodyForConstructor ( parameters , names ) ; return factory . newConstructorDeclaration ( null , new AttributeBuilder ( factory ) . toAttributes ( ) , objectType . getName ( ) . getLastSegment ( ) , parameters , statements ) ; } private List < FormalParameterDeclaration > createParametersForConstructor ( NameGenerator names ) { List < FormalParameterDeclaration > parameters = Lists . create ( ) ; for ( OperatorPortDeclaration var : flowClass . getInputPorts ( ) ) { SimpleName name = factory . newSimpleName ( names . reserve ( var . getName ( ) ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( util . toSourceType ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; } for ( OperatorPortDeclaration var : flowClass . getParameters ( ) ) { SimpleName name = factory . newSimpleName ( names . reserve ( var . getName ( ) ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( util . t ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; } return parameters ; } private List < Statement > createBodyForConstructor ( List < FormalParameterDeclaration > parameters , NameGenerator names ) { assert parameters != null ; List < Statement > statements = Lists . create ( ) ; SimpleName builderName = names . create ( "" ) ; statements . add ( new TypeBuilder ( factory , util . t ( FlowPartDescription . Builder . class ) ) . newObject ( factory . newClassLiteral ( util . t ( flowClass . getElement ( ) ) ) ) . toLocalVariableDeclaration ( util . t ( FlowPartDescription . Builder . class ) , builderName ) ) ; Expression [ ] arguments = new Expression [ flowClass . getInputPorts ( ) . size ( ) + flowClass . getOutputPorts ( ) . size ( ) + flowClass . getParameters ( ) . size ( ) ] ; for ( OperatorPortDeclaration var : flowClass . getInputPorts ( ) ) { SimpleName name = names . create ( var . getName ( ) ) ; statements . add ( new ExpressionBuilder ( factory , builderName ) . method ( "" , util . v ( var . getName ( ) ) , factory . newSimpleName ( var . getType ( ) . getReference ( ) ) ) . toLocalVariableDeclaration ( util . toInType ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; arguments [ var . getParameterPosition ( ) ] = name ; } for ( OperatorPortDeclaration var : flowClass . getOutputPorts ( ) ) { SimpleName name = names . create ( var . getName ( ) ) ; Expression type ; switch ( var . getType ( ) . getKind ( ) ) { case DIRECT : type = factory . newClassLiteral ( util . t ( var . getType ( ) . getDirect ( ) ) ) ; break ; case REFERENCE : type = factory . newSimpleName ( var . getType ( ) . getReference ( ) ) ; break ; default : throw new AssertionError ( var . getType ( ) . getKind ( ) ) ; } assert type != null ; statements . add ( new ExpressionBuilder ( factory , builderName ) . method ( "" , util . v ( var . getName ( ) ) , type ) . toLocalVariableDeclaration ( util . toOutType ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; arguments [ var . getParameterPosition ( ) ] = name ; } for ( OperatorPortDeclaration var : flowClass . getParameters ( ) ) { SimpleName name = factory . newSimpleName ( var . getName ( ) ) ; arguments [ var . getParameterPosition ( ) ] = name ; } SimpleName descName = names . create ( "" ) ; statements . add ( new TypeBuilder ( factory , getType ( util . t ( flowClass . getElement ( ) ) ) ) . newObject ( arguments ) . toLocalVariableDeclaration ( util . t ( FlowDescription . class ) , descName ) ) ; Expression resolver = new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( RESOLVER_FIELD_NAME ) . toExpression ( ) ; statements . add ( new ExpressionBuilder ( factory , resolver ) . assignFrom ( new ExpressionBuilder ( factory , builderName ) . method ( "" , descName ) . toExpression ( ) ) . toStatement ( ) ) ; for ( OperatorPortDeclaration var : flowClass . getInputPorts ( ) ) { statements . add ( new ExpressionBuilder ( factory , resolver ) . method ( "" , util . v ( var . getName ( ) ) , factory . newSimpleName ( var . getName ( ) ) ) . toStatement ( ) ) ; } for ( OperatorPortDeclaration var : flowClass . getOutputPorts ( ) ) { statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( var . getName ( ) ) . assignFrom ( new ExpressionBuilder ( factory , resolver ) . method ( "" , util . v ( var . getName ( ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; } return statements ; } private MethodDeclaration createFactoryMethod ( NamedType objectType ) { assert objectType != null ; JavadocBuilder javadoc = new JavadocBuilder ( factory ) ; javadoc . inline ( flowClass . getDocumentation ( ) ) ; List < FormalParameterDeclaration > parameters = Lists . create ( ) ; List < Expression > arguments = Lists . create ( ) ; for ( OperatorPortDeclaration var : flowClass . getInputPorts ( ) ) { SimpleName name = factory . newSimpleName ( var . getName ( ) ) ; javadoc . param ( name ) . inline ( var . getDocumentation ( ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( util . toSourceType ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; arguments . add ( name ) ; } for ( OperatorPortDeclaration var : flowClass . getParameters ( ) ) { SimpleName name = factory . newSimpleName ( var . getName ( ) ) ; javadoc . param ( name ) . inline ( var . getDocumentation ( ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( util . t ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; arguments . add ( name ) ; } Type type = getType ( objectType ) ; javadoc . returns ( ) . text ( "" ) ; javadoc . seeType ( util . t ( flowClass . getElement ( ) ) ) ; return factory . newMethodDeclaration ( javadoc . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , util . toTypeParameters ( flowClass . getElement ( ) ) , type , factory . newSimpleName ( "" ) , parameters , , Collections . < Type > emptyList ( ) , factory . newBlock ( new TypeBuilder ( factory , type ) . newObject ( arguments ) . toReturnStatement ( ) ) ) ; } private Type getType ( Type objectType ) { assert objectType != null ; assert objectType . getModelKind ( ) != ModelKind . PARAMETERIZED_TYPE ; Type type ; if ( flowClass . getElement ( ) . getTypeParameters ( ) . isEmpty ( ) ) { type = objectType ; } else { type = new TypeBuilder ( factory , objectType ) . parameterize ( util . toTypeVariables ( flowClass . getElement ( ) ) ) . toType ( ) ; } return type ; } private SimpleName getClassName ( ) { return util . getFactoryName ( flowClass . getElement ( ) ) ; } } package com . asakusafw . compiler . operator . model ; package com . asakusafw . compiler . operator . model ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . type . TypeMirror ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . DataModelMirror ; public class DefaultPropertyMirror implements DataModelMirror . PropertyMirror { private final String name ; private final ExecutableElement element ; public DefaultPropertyMirror ( String name , ExecutableElement element ) { Precondition . checkMustNotBeNull ( name , "" ) ; Precondition . checkMustNotBeNull ( element , "" ) ; this . name = name ; this . element = element ; } @ Override public String getName ( ) { return name ; } @ Override public TypeMirror getType ( ) { return element . getReturnType ( ) ; } } package com . asakusafw . compiler . operator . model ; import java . util . LinkedHashMap ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import javax . lang . model . element . Element ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; import javax . lang . model . element . TypeParameterElement ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . type . TypeVariable ; import javax . lang . model . util . ElementFilter ; import javax . lang . model . util . Elements ; import javax . lang . model . util . Types ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . DataModelMirror ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; final class PartialDataModelMirror implements DataModelMirror { private final OperatorCompilingEnvironment environment ; final TypeVariable type ; private Map < String , PropertyMirror > properties ; public PartialDataModelMirror ( OperatorCompilingEnvironment environment , TypeVariable type ) { if ( environment == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . environment = environment ; this . type = type ; } @ Override public Kind getKind ( ) { return Kind . PARTIAL ; } @ Override public boolean isSame ( DataModelMirror other ) { Precondition . checkMustNotBeNull ( other , "" ) ; if ( other instanceof PartialDataModelMirror ) { PartialDataModelMirror that = ( PartialDataModelMirror ) other ; return environment . getTypeUtils ( ) . isSameType ( this . type , that . type ) ; } return false ; } @ Override public boolean canInvoke ( DataModelMirror other ) { Precondition . checkMustNotBeNull ( other , "" ) ; if ( other instanceof ConcreteDataModelMirror ) { ConcreteDataModelMirror that = ( ConcreteDataModelMirror ) other ; return environment . getTypeUtils ( ) . isSubtype ( this . type , that . type ) ; } if ( other instanceof PartialDataModelMirror ) { PartialDataModelMirror that = ( PartialDataModelMirror ) other ; return environment . getTypeUtils ( ) . isSubtype ( this . type , that . type . getUpperBound ( ) ) ; } return false ; } @ Override public boolean canContain ( DataModelMirror other ) { Precondition . checkMustNotBeNull ( other , "" ) ; if ( other instanceof PartialDataModelMirror ) { PartialDataModelMirror that = ( PartialDataModelMirror ) other ; Types typeUtils = environment . getTypeUtils ( ) ; return typeUtils . isSubtype ( this . type , that . type . getUpperBound ( ) ) && typeUtils . isSubtype ( that . type . getLowerBound ( ) , this . type ) ; } return false ; } @ Override public PropertyMirror findProperty ( String name ) { Precondition . checkMustNotBeNull ( name , "" ) ; String normalized = Util . normalize ( name ) ; synchronized ( this ) { if ( properties == null ) { properties = buildProperties ( ) ; } return properties . get ( normalized ) ; } } private Map < String , PropertyMirror > buildProperties ( ) { Map < String , PropertyMirror > results = new LinkedHashMap < String , PropertyMirror > ( ) ; Elements elementUtils = environment . getElementUtils ( ) ; for ( TypeElement element : collectUpperBounds ( ) ) { for ( ExecutableElement method : ElementFilter . methodsIn ( elementUtils . getAllMembers ( element ) ) ) { PropertyMirror property = Util . toProperty ( method ) ; if ( property != null ) { results . put ( property . getName ( ) , property ) ; } } } return results ; } private List < TypeElement > collectUpperBounds ( ) { LinkedList < TypeMirror > works = new LinkedList < TypeMirror > ( ) ; works . add ( type ) ; Set < TypeMirror > saw = Sets . create ( ) ; List < TypeElement > types = Lists . create ( ) ; int countDown = ; while ( works . isEmpty ( ) == false && -- countDown >= ) { TypeMirror target = works . removeFirst ( ) ; if ( saw . contains ( target ) ) { continue ; } saw . add ( target ) ; Element element = environment . getTypeUtils ( ) . asElement ( target ) ; if ( element == null ) { continue ; } switch ( element . getKind ( ) ) { case CLASS : case INTERFACE : types . add ( ( TypeElement ) element ) ; break ; case TYPE_PARAMETER : works . addAll ( ( ( TypeParameterElement ) element ) . getBounds ( ) ) ; break ; default : continue ; } } return types ; } @ Override public String toString ( ) { return type . toString ( ) ; } } package com . asakusafw . compiler . operator . model ; import java . util . List ; import javax . lang . model . element . Element ; import javax . lang . model . element . ElementKind ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; import javax . lang . model . element . TypeParameterElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . TypeKind ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . type . TypeVariable ; import javax . lang . model . util . Types ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . operator . DataModelMirror . PropertyMirror ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . vocabulary . flow . FlowDescription ; final class Util { static boolean isConcrete ( OperatorCompilingEnvironment environment , TypeMirror type ) { assert environment != null ; assert type != null ; if ( type . getKind ( ) != TypeKind . DECLARED ) { return false ; } if ( isKindMatched ( environment , type ) == false ) { return false ; } TypeMirror datamodel = environment . getDeclaredType ( DataModel . class ) ; return environment . getTypeUtils ( ) . isSubtype ( type , datamodel ) ; } static boolean isPartial ( OperatorCompilingEnvironment environment , TypeMirror type ) { assert environment != null ; assert type != null ; if ( type . getKind ( ) != TypeKind . TYPEVAR ) { return false ; } TypeVariable var = ( TypeVariable ) type ; TypeParameterElement parameter = ( TypeParameterElement ) var . asElement ( ) ; if ( hasKindMatched ( environment , parameter ) == false ) { return false ; } Element parent = parameter . getEnclosingElement ( ) ; if ( parent == null ) { return true ; } return isOperatorSource ( environment , parent ) ; } private static boolean isKindMatched ( OperatorCompilingEnvironment environment , TypeMirror type ) { assert environment != null ; assert type != null ; TypeElement element = ( TypeElement ) environment . getTypeUtils ( ) . asElement ( type ) ; DataModelKind kind = element . getAnnotation ( DataModelKind . class ) ; return kind != null && kind . value ( ) . equals ( "" ) ; } private static boolean hasKindMatched ( OperatorCompilingEnvironment environment , TypeParameterElement parameter ) { assert environment != null ; assert parameter != null ; for ( TypeMirror bound : parameter . getBounds ( ) ) { if ( isKindMatched ( environment , bound ) ) { return true ; } } return false ; } private static boolean isOperatorSource ( OperatorCompilingEnvironment environment , Element element ) { assert environment != null ; assert element != null ; if ( element . getKind ( ) == ElementKind . METHOD ) { return true ; } if ( element . getKind ( ) == ElementKind . CLASS ) { Types typeUtils = environment . getTypeUtils ( ) ; DeclaredType type = typeUtils . getDeclaredType ( ( TypeElement ) element ) ; return typeUtils . isSubtype ( type , environment . getDeclaredType ( FlowDescription . class ) ) ; } return false ; } static PropertyMirror toProperty ( ExecutableElement element ) { assert element != null ; JavaName name = JavaName . of ( element . getSimpleName ( ) . toString ( ) ) ; List < String > segments = name . getSegments ( ) ; if ( segments . size ( ) <= ) { return null ; } if ( segments . get ( ) . equals ( "" ) == false || segments . get ( segments . size ( ) - ) . equals ( "" ) == false ) { return null ; } name . removeLast ( ) ; name . removeFirst ( ) ; String propertyName = name . toMemberName ( ) ; return new DefaultPropertyMirror ( propertyName , element ) ; } static String normalize ( String name ) { assert name != null ; String trimmed = name . trim ( ) ; if ( trimmed . isEmpty ( ) ) { return trimmed ; } return JavaName . of ( name ) . toMemberName ( ) ; } private Util ( ) { return ; } } package com . asakusafw . compiler . operator . model ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . type . TypeVariable ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . DataModelMirror ; import com . asakusafw . compiler . operator . DataModelMirrorRepository ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; public class DefaultDataModelMirrorRepository implements DataModelMirrorRepository { @ Override public DataModelMirror load ( OperatorCompilingEnvironment environment , TypeMirror type ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( type , "" ) ; if ( Util . isConcrete ( environment , type ) ) { return new ConcreteDataModelMirror ( environment , ( DeclaredType ) type ) ; } else if ( Util . isPartial ( environment , type ) ) { return new PartialDataModelMirror ( environment , ( TypeVariable ) type ) ; } return null ; } } package com . asakusafw . compiler . operator . model ; import java . util . LinkedHashMap ; import java . util . Map ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . util . ElementFilter ; import javax . lang . model . util . Elements ; import javax . lang . model . util . Types ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . DataModelMirror ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; final class ConcreteDataModelMirror implements DataModelMirror { private final OperatorCompilingEnvironment environment ; final DeclaredType type ; private Map < String , PropertyMirror > properties ; public ConcreteDataModelMirror ( OperatorCompilingEnvironment environment , DeclaredType type ) { if ( environment == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . environment = environment ; this . type = type ; } @ Override public Kind getKind ( ) { return Kind . CONCRETE ; } @ Override public boolean isSame ( DataModelMirror other ) { Precondition . checkMustNotBeNull ( other , "" ) ; if ( other instanceof ConcreteDataModelMirror ) { ConcreteDataModelMirror that = ( ConcreteDataModelMirror ) other ; return environment . getTypeUtils ( ) . isSameType ( this . type , that . type ) ; } return false ; } @ Override public boolean canInvoke ( DataModelMirror other ) { Precondition . checkMustNotBeNull ( other , "" ) ; if ( other instanceof ConcreteDataModelMirror ) { ConcreteDataModelMirror that = ( ConcreteDataModelMirror ) other ; return environment . getTypeUtils ( ) . isSubtype ( this . type , that . type ) ; } if ( other instanceof PartialDataModelMirror ) { PartialDataModelMirror that = ( PartialDataModelMirror ) other ; return environment . getTypeUtils ( ) . isSubtype ( this . type , that . type . getUpperBound ( ) ) ; } return false ; } @ Override public boolean canContain ( DataModelMirror other ) { Precondition . checkMustNotBeNull ( other , "" ) ; if ( other instanceof ConcreteDataModelMirror ) { ConcreteDataModelMirror that = ( ConcreteDataModelMirror ) other ; return environment . getTypeUtils ( ) . isSameType ( this . type , that . type ) ; } if ( other instanceof PartialDataModelMirror ) { PartialDataModelMirror that = ( PartialDataModelMirror ) other ; Types typeUtils = environment . getTypeUtils ( ) ; return typeUtils . isSubtype ( this . type , that . type . getUpperBound ( ) ) && typeUtils . isSubtype ( that . type . getLowerBound ( ) , this . type ) ; } return false ; } @ Override public PropertyMirror findProperty ( String name ) { Precondition . checkMustNotBeNull ( name , "" ) ; String normalized = Util . normalize ( name ) ; synchronized ( this ) { if ( properties == null ) { properties = buildProperties ( ) ; } return properties . get ( normalized ) ; } } private Map < String , PropertyMirror > buildProperties ( ) { Map < String , PropertyMirror > results = new LinkedHashMap < String , PropertyMirror > ( ) ; Elements elementUtils = environment . getElementUtils ( ) ; TypeElement element = ( TypeElement ) type . asElement ( ) ; for ( ExecutableElement method : ElementFilter . methodsIn ( elementUtils . getAllMembers ( element ) ) ) { PropertyMirror property = Util . toProperty ( method ) ; if ( property != null ) { results . put ( property . getName ( ) , property ) ; } } return results ; } @ Override public String toString ( ) { return type . toString ( ) ; } } package com . asakusafw . compiler . operator ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . PackageElement ; import javax . tools . Diagnostic ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ImportDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; public class OperatorClassEmitter { static final Logger LOG = LoggerFactory . getLogger ( OperatorClassEmitter . class ) ; private OperatorCompilingEnvironment environment ; private boolean sawError ; public OperatorClassEmitter ( OperatorCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public void emit ( OperatorClass operatorClass ) { Precondition . checkMustNotBeNull ( operatorClass , "" ) ; emitFactory ( operatorClass ) ; if ( sawError == false ) { emitImplementation ( operatorClass ) ; } } public boolean hasError ( ) { return sawError ; } private void emitImplementation ( OperatorClass operatorClass ) { assert operatorClass != null ; ModelFactory f = environment . getFactory ( ) ; PackageDeclaration packageDecl = getPackage ( f , operatorClass ) ; ImportBuilder imports = getImportBuilder ( f , packageDecl ) ; OperatorClassGenerator generator = new OperatorImplementationClassGenerator ( environment , f , imports , operatorClass ) ; TypeDeclaration type = generator . generate ( ) ; if ( type == null ) { sawError = true ; return ; } List < ImportDeclaration > decls = imports . toImportDeclarations ( ) ; try { emit ( f , packageDecl , decls , type ) ; } catch ( IOException e ) { LOG . debug ( e . getMessage ( ) , e ) ; environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , MessageFormat . format ( "" , operatorClass . getElement ( ) . getQualifiedName ( ) . toString ( ) , e . getMessage ( ) ) ) ; } } private void emitFactory ( OperatorClass operatorClass ) { assert operatorClass != null ; ModelFactory f = environment . getFactory ( ) ; PackageDeclaration packageDecl = getPackage ( f , operatorClass ) ; ImportBuilder imports = getImportBuilder ( f , packageDecl ) ; OperatorClassGenerator generator = new OperatorFactoryClassGenerator ( environment , f , imports , operatorClass ) ; TypeDeclaration type = generator . generate ( ) ; if ( type == null ) { sawError = true ; return ; } List < ImportDeclaration > decls = imports . toImportDeclarations ( ) ; try { emit ( f , packageDecl , decls , type ) ; } catch ( IOException e ) { LOG . debug ( e . getMessage ( ) , e ) ; environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , MessageFormat . format ( "" , operatorClass . getElement ( ) . getQualifiedName ( ) . toString ( ) , e . getMessage ( ) ) ) ; } } private void emit ( ModelFactory factory , PackageDeclaration packageDecl , List < ImportDeclaration > importDecls , TypeDeclaration typeDecl ) throws IOException { CompilationUnit unit = factory . newCompilationUnit ( packageDecl , importDecls , Collections . singletonList ( typeDecl ) , Collections . < Comment > emptyList ( ) ) ; environment . emit ( unit ) ; } private PackageDeclaration getPackage ( ModelFactory factory , OperatorClass operatorClass ) { PackageElement parent = ( PackageElement ) operatorClass . getElement ( ) . getEnclosingElement ( ) ; return new Jsr269 ( factory ) . convert ( parent ) ; } private ImportBuilder getImportBuilder ( ModelFactory factory , PackageDeclaration packageDecl ) { assert factory != null ; assert packageDecl != null ; return new ImportBuilder ( factory , packageDecl , Strategy . TOP_LEVEL ) ; } } package com . asakusafw . compiler . operator ; import java . lang . annotation . Annotation ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . Modifier ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Types ; import javax . tools . Diagnostic ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; public abstract class AbstractOperatorProcessor implements OperatorProcessor { private OperatorCompilingEnvironment environment ; private Class < ? extends Annotation > targetOperatorAnnotation ; private TypeMirror targetOperatorAnnotationType ; @ Override public void initialize ( OperatorCompilingEnvironment env ) { Precondition . checkMustNotBeNull ( env , "" ) ; this . environment = env ; TargetOperator target = getClass ( ) . getAnnotation ( TargetOperator . class ) ; if ( target != null ) { this . targetOperatorAnnotation = target . value ( ) ; } else { env . getMessager ( ) . printMessage ( Diagnostic . Kind . WARNING , MessageFormat . format ( "" , getClass ( ) . getName ( ) , TargetOperator . class . getName ( ) ) ) ; } } @ Override public Class < ? extends Annotation > getTargetAnnotationType ( ) { return targetOperatorAnnotation ; } @ Override public synchronized AnnotationMirror getOperatorAnnotation ( ExecutableElement element ) { if ( targetOperatorAnnotationType == null ) { this . targetOperatorAnnotationType = environment . getElementUtils ( ) . getTypeElement ( targetOperatorAnnotation . getCanonicalName ( ) ) . asType ( ) ; } Types types = environment . getTypeUtils ( ) ; for ( AnnotationMirror annotation : element . getAnnotationMirrors ( ) ) { if ( types . isSameType ( annotation . getAnnotationType ( ) , targetOperatorAnnotationType ) ) { return annotation ; } } return null ; } @ Override public List < ? extends TypeBodyDeclaration > implement ( Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; if ( context . element . getModifiers ( ) . contains ( Modifier . ABSTRACT ) == false ) { return Collections . emptyList ( ) ; } return override ( context ) ; } protected List < ? extends TypeBodyDeclaration > override ( Context context ) { return null ; } } package com . asakusafw . compiler . operator ; public class OperatorCompilerException extends RuntimeException { private static final long serialVersionUID = ; public OperatorCompilerException ( String message ) { super ( message ) ; } public OperatorCompilerException ( String message , Throwable cause ) { super ( message , cause ) ; } } package com . asakusafw . compiler . operator ; import javax . lang . model . type . TypeMirror ; public interface DataModelMirror { Kind getKind ( ) ; boolean isSame ( DataModelMirror other ) ; boolean canInvoke ( DataModelMirror other ) ; boolean canContain ( DataModelMirror other ) ; PropertyMirror findProperty ( String name ) ; public enum Kind { CONCRETE , PARTIAL , } public interface PropertyMirror { String getName ( ) ; TypeMirror getType ( ) ; } } package com . asakusafw . compiler . operator ; import java . util . List ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; public class OperatorClass { private TypeElement element ; private List < OperatorMethod > methods ; public OperatorClass ( TypeElement type ) { Precondition . checkMustNotBeNull ( type , "" ) ; this . element = type ; this . methods = Lists . create ( ) ; } public TypeElement getElement ( ) { return this . element ; } public void add ( ExecutableElement methodElement , OperatorProcessor processor ) { Precondition . checkMustNotBeNull ( methodElement , "" ) ; Precondition . checkMustNotBeNull ( processor , "" ) ; if ( element . equals ( methodElement . getEnclosingElement ( ) ) == false ) { throw new IllegalArgumentException ( "" ) ; } OperatorMethod method = new OperatorMethod ( methodElement , processor ) ; methods . add ( method ) ; } public List < OperatorMethod > getMethods ( ) { return methods ; } } package com . asakusafw . compiler . operator ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . AnnotationValue ; import javax . lang . model . element . Element ; import javax . lang . model . element . ElementKind ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . Modifier ; import javax . lang . model . element . TypeElement ; import javax . lang . model . element . VariableElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . TypeKind ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Types ; import javax . tools . Diagnostic ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . DataModelMirror . Kind ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . DocBlock ; import com . asakusafw . utils . java . model . syntax . DocElement ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . parser . javadoc . JavadocConverter ; import com . asakusafw . utils . java . parser . javadoc . JavadocParseException ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; import com . asakusafw . vocabulary . operator . Sticky ; import com . asakusafw . vocabulary . operator . Volatile ; public class ExecutableAnalyzer { final OperatorCompilingEnvironment environment ; final ExecutableElement executable ; final Javadoc documentation ; private boolean sawError ; public ExecutableAnalyzer ( OperatorCompilingEnvironment environment , ExecutableElement executable ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( executable , "" ) ; this . environment = environment ; this . executable = executable ; this . documentation = getJavadoc ( environment , executable ) ; this . sawError = false ; } public void error ( String message , Object ... arguments ) { Precondition . checkMustNotBeNull ( message , "" ) ; environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , format ( message , arguments ) , executable ) ; sawError = true ; } public void error ( int parameterIndex , String message , Object ... arguments ) { Precondition . checkMustNotBeNull ( message , "" ) ; if ( parameterIndex < || parameterIndex >= executable . getParameters ( ) . size ( ) ) { error ( format ( message , arguments ) ) ; return ; } environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , format ( message , arguments ) , executable . getParameters ( ) . get ( parameterIndex ) ) ; sawError = true ; } boolean typeEqual ( TypeMirror a , TypeMirror b ) { Types types = environment . getTypeUtils ( ) ; return types . isSameType ( a , b ) ; } boolean typeDeclEqual ( TypeMirror a , TypeMirror b ) { if ( a . getKind ( ) != TypeKind . DECLARED ) { return false ; } if ( b . getKind ( ) != TypeKind . DECLARED ) { return false ; } Types types = environment . getTypeUtils ( ) ; if ( types . isSameType ( a , b ) ) { return true ; } DeclaredType at = ( DeclaredType ) a ; DeclaredType bt = ( DeclaredType ) b ; return at . asElement ( ) . equals ( bt . asElement ( ) ) ; } private String format ( String message , Object ... arguments ) { if ( arguments == null || arguments . length == ) { return message ; } else { return MessageFormat . format ( message , arguments ) ; } } public boolean hasError ( ) { return sawError ; } public boolean isAbstract ( ) { return executable . getModifiers ( ) . contains ( Modifier . ABSTRACT ) ; } public boolean isGeneric ( ) { return executable . getTypeParameters ( ) . isEmpty ( ) == false ; } public ObservationCount getObservationCount ( ObservationCount ... defaults ) { Precondition . checkMustNotBeNull ( defaults , "" ) ; ObservationCount current = ObservationCount . DONT_CARE ; for ( ObservationCount oc : defaults ) { current = current . and ( oc ) ; } if ( current . atLeastOnce == false ) { if ( executable . getAnnotation ( Sticky . class ) != null ) { current = current . and ( ObservationCount . AT_LEAST_ONCE ) ; } } if ( current . atMostOnce == false ) { if ( executable . getAnnotation ( Volatile . class ) != null ) { current = current . and ( ObservationCount . AT_MOST_ONCE ) ; } } return current ; } public List < ? extends DocElement > getDocument ( Element element ) { Precondition . checkMustNotBeNull ( element , "" ) ; Javadoc doc = getJavadoc ( environment , element ) ; return getAbstractBlock ( doc ) ; } private static Javadoc getJavadoc ( OperatorCompilingEnvironment environment , Element element ) { assert environment != null ; assert element != null ; ModelFactory f = environment . getFactory ( ) ; String comment = environment . getElementUtils ( ) . getDocComment ( element ) ; if ( comment == null ) { return f . newJavadoc ( Collections . < DocBlock > emptyList ( ) ) ; } if ( comment . startsWith ( "" ) == false ) { comment = "" + comment ; } if ( comment . endsWith ( "" ) == false ) { comment = comment + "" ; } try { return new JavadocConverter ( f ) . convert ( comment , ) ; } catch ( JavadocParseException e ) { environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , e . getMessage ( ) , element ) ; return f . newJavadoc ( Collections . < DocBlock > emptyList ( ) ) ; } } private static List < ? extends DocElement > getAbstractBlock ( Javadoc doc ) { assert doc != null ; List < ? extends DocBlock > blocks = doc . getBlocks ( ) ; if ( blocks . isEmpty ( ) ) { return Collections . emptyList ( ) ; } DocBlock first = blocks . get ( ) ; if ( first . getTag ( ) . equals ( "" ) == false ) { return Collections . emptyList ( ) ; } return first . getElements ( ) ; } public int countParameters ( ) { return executable . getParameters ( ) . size ( ) ; } public TypeConstraint getReturnType ( ) { return new TypeConstraint ( executable . getReturnType ( ) ) ; } public TypeConstraint getParameterType ( int index ) { List < ? extends VariableElement > parameters = executable . getParameters ( ) ; if ( index >= parameters . size ( ) ) { return new TypeConstraint ( environment . getTypeUtils ( ) . getNoType ( TypeKind . NONE ) ) ; } return new TypeConstraint ( parameters . get ( index ) . asType ( ) ) ; } public String getParameterName ( int index ) { List < ? extends VariableElement > parameters = executable . getParameters ( ) ; String name = parameters . get ( index ) . getSimpleName ( ) . toString ( ) ; return name ; } public ShuffleKey getParameterKey ( int index ) { VariableElement parameter = executable . getParameters ( ) . get ( index ) ; TypeConstraint type = getParameterType ( index ) ; TypeConstraint arg = type . getTypeArgument ( ) ; if ( arg . exists ( ) ) { type = arg ; } DataModelMirror model = environment . loadDataModel ( type . getType ( ) ) ; if ( model == null ) { return null ; } return toShuffleKey ( index , model , findAnnotation ( parameter , environment . getDeclaredType ( Key . class ) ) ) ; } public List < ? extends DocElement > getExecutableDocument ( ) { Javadoc doc = documentation ; return getAbstractBlock ( doc ) ; } public List < ? extends DocElement > getParameterDocument ( int index ) { String name = getParameterName ( index ) ; for ( DocBlock block : documentation . getBlocks ( ) ) { if ( block . getTag ( ) . equals ( "" ) == false ) { continue ; } List < ? extends DocElement > elements = block . getElements ( ) ; if ( elements . isEmpty ( ) ) { continue ; } DocElement first = elements . get ( ) ; if ( first . getModelKind ( ) != ModelKind . SIMPLE_NAME ) { continue ; } if ( name . equals ( ( ( SimpleName ) first ) . getToken ( ) ) == false ) { continue ; } return elements . subList ( , elements . size ( ) ) ; } return Collections . emptyList ( ) ; } public List < ? extends DocElement > getReturnDocument ( ) { for ( DocBlock block : documentation . getBlocks ( ) ) { if ( block . getTag ( ) . equals ( "" ) == false && block . getTag ( ) . equals ( "" ) == false ) { continue ; } return block . getElements ( ) ; } return Collections . emptyList ( ) ; } ShuffleKey toShuffleKey ( int position , DataModelMirror model , AnnotationMirror annotation ) { if ( annotation == null ) { return null ; } ShuffleKey key = toUncheckedShuffleKey ( position , annotation ) ; if ( key == null ) { return null ; } checkShuffleKey ( position , model , key ) ; return key ; } ShuffleKey toUncheckedShuffleKey ( int position , AnnotationMirror annotation ) { assert annotation != null ; Map < String , AnnotationValue > values = getValues ( annotation ) ; List < String > group = toStringList ( values . get ( "" ) ) ; List < String > order = toStringList ( values . get ( "" ) ) ; if ( group == null ) { error ( position , "" ) ; return null ; } if ( order == null ) { order = Collections . emptyList ( ) ; } List < ShuffleKey . Order > formedOrder = Lists . create ( ) ; for ( String orderString : order ) { ShuffleKey . Order o = ShuffleKey . Order . parse ( orderString ) ; if ( o == null ) { error ( position , "" , orderString ) ; } else { formedOrder . add ( o ) ; } } return new ShuffleKey ( group , formedOrder ) ; } private void checkShuffleKey ( int position , DataModelMirror model , ShuffleKey key ) { assert model != null ; assert key != null ; for ( String name : key . getGroupProperties ( ) ) { if ( model . findProperty ( name ) == null ) { error ( position , "" , name , model ) ; } } for ( ShuffleKey . Order order : key . getOrderings ( ) ) { if ( model . findProperty ( order . getProperty ( ) ) == null ) { error ( position , "" , order . getProperty ( ) , model ) ; } } } List < String > toStringList ( AnnotationValue value ) { if ( value == null ) { return null ; } Object object = value . getValue ( ) ; if ( object instanceof String ) { return Collections . singletonList ( ( String ) object ) ; } if ( ( object instanceof List < ? > ) == false ) { return null ; } List < ? > list = ( List < ? > ) object ; List < String > results = Lists . create ( ) ; for ( Object element : list ) { Object elementValue = ( ( AnnotationValue ) element ) . getValue ( ) ; if ( ( elementValue instanceof String ) == false ) { return null ; } results . add ( ( String ) elementValue ) ; } return results ; } AnnotationMirror findAnnotation ( Element elem , DeclaredType annotationType ) { assert annotationType != null ; if ( elem == null ) { return null ; } for ( AnnotationMirror annotation : elem . getAnnotationMirrors ( ) ) { DeclaredType aType = annotation . getAnnotationType ( ) ; if ( typeEqual ( aType , annotationType ) ) { return annotation ; } } return null ; } static < T > T getValue ( Class < T > valueType , Map < String , AnnotationValue > valueMap , String name ) { assert valueType != null ; assert valueMap != null ; assert name != null ; AnnotationValue value = valueMap . get ( name ) ; if ( value == null ) { return null ; } Object content = value . getValue ( ) ; if ( valueType . isInstance ( content ) == false ) { return null ; } return valueType . cast ( content ) ; } @ SuppressWarnings ( "" ) static List < ? extends AnnotationValue > getList ( Map < String , AnnotationValue > valueMap , String name ) { assert valueMap != null ; assert name != null ; AnnotationValue value = valueMap . get ( name ) ; if ( value == null ) { return null ; } Object content = value . getValue ( ) ; if ( ( content instanceof List < ? > ) == false ) { return null ; } return ( List < ? extends AnnotationValue > ) content ; } static TypeMirror getReduceTermType ( AnnotationMirror annotation ) { assert annotation != null ; Map < String , AnnotationValue > values = getValues ( annotation ) ; return getValue ( TypeMirror . class , values , "" ) ; } static AnnotationMirror getReduceTermKey ( AnnotationMirror annotation ) { assert annotation != null ; Map < String , AnnotationValue > values = getValues ( annotation ) ; return getValue ( AnnotationMirror . class , values , "" ) ; } static Map < String , AnnotationValue > getValues ( AnnotationMirror annotation ) { assert annotation != null ; Map < String , AnnotationValue > results = Maps . create ( ) ; for ( Map . Entry < ? extends ExecutableElement , ? extends AnnotationValue > entry : annotation . getElementValues ( ) . entrySet ( ) ) { ExecutableElement key = entry . getKey ( ) ; AnnotationValue value = entry . getValue ( ) ; results . put ( key . getSimpleName ( ) . toString ( ) , value ) ; } return results ; } public class TypeConstraint { private final TypeMirror type ; private final Element element ; TypeConstraint ( TypeMirror type ) { Precondition . checkMustNotBeNull ( type , "" ) ; this . type = type ; this . element = environment . getTypeUtils ( ) . asElement ( type ) ; } public TypeMirror getType ( ) { return type ; } public boolean exists ( ) { return type . getKind ( ) != TypeKind . NONE ; } public boolean isVoid ( ) { return type . getKind ( ) == TypeKind . VOID ; } public boolean isTypeVariable ( ) { return type . getKind ( ) == TypeKind . TYPEVAR ; } public boolean isEnum ( ) { if ( element == null ) { return false ; } if ( element . getKind ( ) == ElementKind . ENUM ) { return true ; } return false ; } public TypeElement getTypeElement ( ) { if ( element instanceof TypeElement ) { return ( TypeElement ) element ; } return null ; } public List < VariableElement > getEnumConstants ( ) { if ( isEnum ( ) == false ) { throw new IllegalStateException ( ) ; } TypeElement decl = ( TypeElement ) element ; List < VariableElement > results = Lists . create ( ) ; for ( Element member : decl . getEnclosedElements ( ) ) { if ( member . getKind ( ) == ElementKind . ENUM_CONSTANT ) { results . add ( ( VariableElement ) member ) ; } } return results ; } public boolean isOperator ( ) { return environment . getTypeUtils ( ) . isSubtype ( type , environment . getDeclaredType ( Operator . class ) ) ; } public boolean isModel ( ) { DataModelMirror model = environment . loadDataModel ( type ) ; return model != null ; } public boolean isConcreteModel ( ) { DataModelMirror model = environment . loadDataModel ( type ) ; return model != null && model . getKind ( ) == Kind . CONCRETE ; } public boolean isProjectiveModel ( ) { DataModelMirror model = environment . loadDataModel ( type ) ; return model != null && model . getKind ( ) == Kind . PARTIAL ; } public boolean isJoinedModel ( TypeMirror a , TypeMirror b ) { AnnotationMirror annotation = findAnnotation ( element , environment . getDeclaredType ( Joined . class ) ) ; if ( annotation == null ) { return false ; } Map < String , AnnotationValue > values = getValues ( annotation ) ; List < ? extends AnnotationValue > terms = getList ( values , "" ) ; if ( terms == null || terms . size ( ) != || ( terms . get ( ) . getValue ( ) instanceof AnnotationMirror ) == false || ( terms . get ( ) . getValue ( ) instanceof AnnotationMirror ) == false ) { return false ; } AnnotationMirror from = ( AnnotationMirror ) terms . get ( ) . getValue ( ) ; AnnotationMirror join = ( AnnotationMirror ) terms . get ( ) . getValue ( ) ; TypeMirror fromType = getReduceTermType ( from ) ; TypeMirror joinType = getReduceTermType ( join ) ; if ( fromType == null || joinType == null ) { return false ; } if ( environment . getTypeUtils ( ) . isSameType ( a , fromType ) ) { return environment . getTypeUtils ( ) . isSameType ( b , joinType ) ; } if ( environment . getTypeUtils ( ) . isSameType ( b , fromType ) ) { return environment . getTypeUtils ( ) . isSameType ( a , joinType ) ; } return false ; } public boolean isJoinFrom ( TypeMirror target ) { Precondition . checkMustNotBeNull ( target , "" ) ; AnnotationMirror annotation = findAnnotation ( element , environment . getDeclaredType ( Joined . class ) ) ; if ( annotation == null ) { return false ; } Map < String , AnnotationValue > values = getValues ( annotation ) ; List < ? extends AnnotationValue > terms = getList ( values , "" ) ; if ( terms == null || terms . isEmpty ( ) || ( terms . get ( ) . getValue ( ) instanceof AnnotationMirror ) == false ) { return false ; } AnnotationMirror from = ( AnnotationMirror ) terms . get ( ) . getValue ( ) ; TypeMirror fromType = getReduceTermType ( from ) ; if ( fromType == null ) { return false ; } return typeEqual ( fromType , target ) ; } public ShuffleKey getJoinKey ( TypeMirror target ) { Precondition . checkMustNotBeNull ( target , "" ) ; DataModelMirror model = environment . loadDataModel ( target ) ; AnnotationMirror annotation = findAnnotation ( element , environment . getDeclaredType ( Joined . class ) ) ; if ( model == null || annotation == null ) { throw new IllegalArgumentException ( ) ; } Map < String , AnnotationValue > values = getValues ( annotation ) ; List < ? extends AnnotationValue > terms = getList ( values , "" ) ; if ( terms == null ) { throw new IllegalArgumentException ( ) ; } for ( AnnotationValue value : terms ) { if ( ( value . getValue ( ) instanceof AnnotationMirror ) == false ) { continue ; } AnnotationMirror term = ( AnnotationMirror ) value . getValue ( ) ; if ( typeEqual ( target , getReduceTermType ( term ) ) ) { AnnotationMirror shuffle = getReduceTermKey ( term ) ; ShuffleKey key = toShuffleKey ( - , model , shuffle ) ; return key ; } } throw new IllegalArgumentException ( ) ; } public boolean isSummarizedModel ( TypeMirror target ) { Precondition . checkMustNotBeNull ( target , "" ) ; AnnotationMirror annotation = findAnnotation ( element , environment . getDeclaredType ( Summarized . class ) ) ; if ( annotation == null ) { return false ; } Map < String , AnnotationValue > values = getValues ( annotation ) ; AnnotationMirror from = getValue ( AnnotationMirror . class , values , "" ) ; if ( from == null ) { return false ; } TypeMirror fromType = getReduceTermType ( from ) ; if ( fromType == null ) { return false ; } return typeEqual ( fromType , target ) ; } public ShuffleKey getSummarizeKey ( ) { AnnotationMirror annotation = findAnnotation ( element , environment . getDeclaredType ( Summarized . class ) ) ; if ( annotation == null ) { throw new IllegalArgumentException ( ) ; } Map < String , AnnotationValue > values = getValues ( annotation ) ; AnnotationMirror reduce = getValue ( AnnotationMirror . class , values , "" ) ; if ( reduce == null ) { throw new IllegalArgumentException ( ) ; } TypeMirror shuffleType = getReduceTermType ( reduce ) ; DataModelMirror model = environment . loadDataModel ( shuffleType ) ; AnnotationMirror shuffleKey = getReduceTermKey ( reduce ) ; if ( model != null && shuffleKey != null ) { return toShuffleKey ( - , model , shuffleKey ) ; } throw new IllegalArgumentException ( ) ; } public boolean isBoolean ( ) { return type . getKind ( ) == TypeKind . BOOLEAN ; } public boolean isString ( ) { return typeEqual ( type , environment . getDeclaredType ( String . class ) ) ; } public boolean isList ( ) { return typeDeclEqual ( type , environment . getDeclaredType ( List . class ) ) ; } public boolean isResult ( ) { return typeDeclEqual ( type , environment . getDeclaredType ( Result . class ) ) ; } public boolean isIn ( ) { return typeDeclEqual ( type , environment . getDeclaredType ( In . class ) ) ; } public boolean isOut ( ) { return typeDeclEqual ( type , environment . getDeclaredType ( Out . class ) ) ; } public boolean isBasic ( ) { if ( type . getKind ( ) . isPrimitive ( ) || typeEqual ( type , environment . getDeclaredType ( String . class ) ) ) { return true ; } return false ; } public TypeConstraint getTypeArgument ( ) { if ( type . getKind ( ) != TypeKind . DECLARED ) { return new TypeConstraint ( environment . getTypeUtils ( ) . getNoType ( TypeKind . NONE ) ) ; } DeclaredType declared = ( DeclaredType ) type ; List < ? extends TypeMirror > arguments = declared . getTypeArguments ( ) ; if ( arguments . isEmpty ( ) ) { return new TypeConstraint ( environment . getTypeUtils ( ) . getNoType ( TypeKind . NONE ) ) ; } return new TypeConstraint ( arguments . get ( ) ) ; } } } package com . asakusafw . compiler . operator ; import java . util . Collections ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . util . GeneratorUtil ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; public abstract class OperatorClassGenerator { protected final OperatorCompilingEnvironment environment ; protected final ModelFactory factory ; protected final ImportBuilder importer ; protected final OperatorClass operatorClass ; protected final GeneratorUtil util ; public OperatorClassGenerator ( OperatorCompilingEnvironment environment , ModelFactory factory , ImportBuilder importer , OperatorClass operatorClass ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( importer , "" ) ; Precondition . checkMustNotBeNull ( operatorClass , "" ) ; this . environment = environment ; this . factory = factory ; this . importer = importer ; this . operatorClass = operatorClass ; this . util = new GeneratorUtil ( environment , factory , importer ) ; } public TypeDeclaration generate ( ) { SimpleName name = getClassName ( ) ; importer . resolvePackageMember ( name ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( util . t ( Generated . class ) , util . v ( "" , getClass ( ) . getSimpleName ( ) , OperatorCompiler . VERSION ) ) . Public ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , getSuperClass ( ) , Collections . < Type > emptyList ( ) , createMembers ( ) ) ; } protected abstract SimpleName getClassName ( ) ; protected Type getSuperClass ( ) { return null ; } protected abstract Javadoc createJavadoc ( ) ; protected abstract List < TypeBodyDeclaration > createMembers ( ) ; } package com . asakusafw . compiler . operator ; import java . lang . annotation . Annotation ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import java . util . Set ; import javax . annotation . processing . RoundEnvironment ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . Element ; import javax . lang . model . element . ElementKind ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . Modifier ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . util . ElementFilter ; import javax . tools . Diagnostic ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . operator . OperatorHelper ; public class OperatorClassCollector { private final OperatorCompilingEnvironment environment ; private final RoundEnvironment round ; private final List < TargetMethod > targetMethods ; private boolean sawError ; public OperatorClassCollector ( OperatorCompilingEnvironment environment , RoundEnvironment round ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( round , "" ) ; this . environment = environment ; this . round = round ; this . targetMethods = Lists . create ( ) ; } public void add ( OperatorProcessor processor ) { Precondition . checkMustNotBeNull ( processor , "" ) ; Class < ? extends Annotation > target = processor . getTargetAnnotationType ( ) ; assert target != null ; Set < ? extends Element > elements = round . getElementsAnnotatedWith ( target ) ; for ( Element element : elements ) { ExecutableElement method = toOperatorMethodElement ( element ) ; if ( method == null ) { continue ; } registerMethod ( processor , method ) ; } } private void registerMethod ( OperatorProcessor processor , ExecutableElement method ) { assert processor != null ; assert method != null ; targetMethods . add ( new TargetMethod ( method , processor ) ) ; } private ExecutableElement toOperatorMethodElement ( Element element ) { assert element != null ; if ( element . getKind ( ) != ElementKind . METHOD ) { raiseInvalid ( element , "" ) ; return null ; } ExecutableElement method = ( ExecutableElement ) element ; validateMethodModifiers ( method ) ; return method ; } private void validateMethodModifiers ( ExecutableElement method ) { assert method != null ; if ( method . getModifiers ( ) . contains ( Modifier . PUBLIC ) == false ) { raiseInvalid ( method , "" ) ; } if ( method . getModifiers ( ) . contains ( Modifier . STATIC ) ) { raiseInvalid ( method , "" ) ; } if ( method . getThrownTypes ( ) . isEmpty ( ) == false ) { raiseInvalid ( method , "" ) ; } } private void raiseInvalid ( Element member , String message ) { assert member != null ; assert message != null ; environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , MessageFormat . format ( message , member . getSimpleName ( ) ) , member ) ; sawError = true ; } public List < OperatorClass > collect ( ) { if ( sawError ) { throw new OperatorCompilerException ( "" ) ; } Map < TypeElement , List < TargetMethod > > mapping = Maps . create ( ) ; for ( TargetMethod target : targetMethods ) { Maps . addToList ( mapping , target . type , target ) ; } List < OperatorClass > results = Lists . create ( ) ; for ( Map . Entry < TypeElement , List < TargetMethod > > entry : mapping . entrySet ( ) ) { OperatorClass klass = toOperatorClass ( entry . getKey ( ) , entry . getValue ( ) ) ; results . add ( klass ) ; } if ( sawError ) { throw new OperatorCompilerException ( "" ) ; } return results ; } private OperatorClass toOperatorClass ( TypeElement type , List < TargetMethod > targets ) { assert type != null ; assert targets != null ; validateClassModifiers ( type ) ; validateConstructorWithNoParameters ( type ) ; validateMemberNames ( type ) ; validateCoverage ( type , targets ) ; OperatorClass result = new OperatorClass ( type ) ; for ( TargetMethod target : targets ) { result . add ( target . method , target . processor ) ; } return result ; } private void validateClassModifiers ( TypeElement type ) { assert type != null ; if ( type . getKind ( ) != ElementKind . CLASS ) { raiseInvalidClass ( type , "" ) ; } if ( type . getEnclosingElement ( ) . getKind ( ) != ElementKind . PACKAGE ) { raiseInvalidClass ( type , "" ) ; } if ( type . getTypeParameters ( ) . isEmpty ( ) == false ) { raiseInvalidClass ( type , "" ) ; } if ( type . getModifiers ( ) . contains ( Modifier . PUBLIC ) == false ) { raiseInvalidClass ( type , "" ) ; } if ( type . getModifiers ( ) . contains ( Modifier . ABSTRACT ) == false ) { raiseInvalidClass ( type , "" ) ; } } private void validateConstructorWithNoParameters ( TypeElement type ) { assert type != null ; List < ExecutableElement > ctors = ElementFilter . constructorsIn ( type . getEnclosedElements ( ) ) ; if ( ctors . isEmpty ( ) ) { return ; } for ( ExecutableElement ctor : ctors ) { if ( ctor . getParameters ( ) . isEmpty ( ) && ctor . getTypeParameters ( ) . isEmpty ( ) && ctor . getThrownTypes ( ) . isEmpty ( ) ) { return ; } } raiseInvalidClass ( type , "" ) ; } private void validateMemberNames ( TypeElement type ) { Map < String , Element > saw = Maps . create ( ) ; for ( Element member : type . getEnclosedElements ( ) ) { ElementKind kind = member . getKind ( ) ; if ( kind != ElementKind . METHOD && kind . isClass ( ) == false && kind . isInterface ( ) == false ) { continue ; } String id = member . getSimpleName ( ) . toString ( ) . toUpperCase ( ) ; if ( saw . containsKey ( id ) ) { raiseInvalid ( member , MessageFormat . format ( "" , "" , member . getSimpleName ( ) ) ) ; } else { saw . put ( id , member ) ; } } } private void validateCoverage ( TypeElement type , List < TargetMethod > targets ) { assert type != null ; assert targets != null ; Set < ExecutableElement > methods = Sets . create ( ) ; methods . addAll ( ElementFilter . methodsIn ( type . getEnclosedElements ( ) ) ) ; Set < ExecutableElement > saw = Sets . create ( ) ; for ( TargetMethod target : targets ) { ExecutableElement method = target . method ; if ( saw . contains ( method ) ) { raiseInvalid ( method , "" ) ; } else { saw . add ( method ) ; boolean removed = methods . remove ( method ) ; assert removed : method ; } } for ( ExecutableElement method : methods ) { boolean helper = isOperatorHelper ( method ) ; boolean open = method . getModifiers ( ) . contains ( Modifier . PUBLIC ) ; if ( helper && open == false ) { raiseInvalid ( method , "" ) ; } else if ( helper == false && open ) { raiseInvalid ( method , "" ) ; } } } private boolean isOperatorHelper ( ExecutableElement method ) { assert method != null ; for ( AnnotationMirror mirror : method . getAnnotationMirrors ( ) ) { DeclaredType annotationType = mirror . getAnnotationType ( ) ; Element element = annotationType . asElement ( ) ; if ( element != null && element . getAnnotation ( OperatorHelper . class ) != null ) { return true ; } } return false ; } private void raiseInvalidClass ( TypeElement element , String message ) { environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , MessageFormat . format ( message , element . getQualifiedName ( ) ) , element ) ; sawError = true ; } private static class TargetMethod { final TypeElement type ; final ExecutableElement method ; final OperatorProcessor processor ; public TargetMethod ( ExecutableElement method , OperatorProcessor processor ) { assert method != null ; assert processor != null ; this . type = ( TypeElement ) method . getEnclosingElement ( ) ; this . method = method ; this . processor = processor ; } } } package com . asakusafw . compiler . operator ; import java . util . Collections ; import java . util . List ; import javax . lang . model . type . TypeMirror ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; public class OperatorImplementationClassGenerator extends OperatorClassGenerator { public OperatorImplementationClassGenerator ( OperatorCompilingEnvironment environment , ModelFactory factory , ImportBuilder importer , OperatorClass operatorClass ) { super ( environment , factory , importer , operatorClass ) ; } @ Override protected SimpleName getClassName ( ) { return util . getImplementorName ( operatorClass . getElement ( ) ) ; } @ Override protected Type getSuperClass ( ) { TypeMirror type = operatorClass . getElement ( ) . asType ( ) ; return util . t ( type ) ; } @ Override protected Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . linkType ( util . t ( operatorClass . getElement ( ) ) ) . text ( "" ) . toJavadoc ( ) ; } @ Override protected List < TypeBodyDeclaration > createMembers ( ) { NameGenerator names = new NameGenerator ( factory ) ; List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createConstructor ( ) ) ; for ( OperatorMethod method : operatorClass . getMethods ( ) ) { OperatorProcessor . Context context = new OperatorProcessor . Context ( environment , method . getAnnotation ( ) , method . getElement ( ) , importer , names ) ; OperatorProcessor processor = method . getProcessor ( ) ; List < ? extends TypeBodyDeclaration > members = processor . implement ( context ) ; if ( members != null ) { results . addAll ( members ) ; } } return results ; } private ConstructorDeclaration createConstructor ( ) { return factory . newConstructorDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , getClassName ( ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( factory . newReturnStatement ( ) ) ) ; } } package com . asakusafw . compiler . operator . util ; package com . asakusafw . compiler . operator . util ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; import javax . lang . model . element . TypeParameterElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . TypeMirror ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . Literal ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . Source ; public class GeneratorUtil { private final OperatorCompilingEnvironment environment ; private final ModelFactory factory ; private final ImportBuilder importer ; public GeneratorUtil ( OperatorCompilingEnvironment environment , ModelFactory factory , ImportBuilder importer ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( importer , "" ) ; this . environment = environment ; this . factory = factory ; this . importer = importer ; } public final SimpleName getFactoryName ( TypeElement type ) { Precondition . checkMustNotBeNull ( type , "" ) ; return factory . newSimpleName ( MessageFormat . format ( "" , type . getSimpleName ( ) , "" ) ) ; } public final SimpleName getImplementorName ( TypeElement type ) { Precondition . checkMustNotBeNull ( type , "" ) ; return factory . newSimpleName ( getImplmentorName ( type . getSimpleName ( ) . toString ( ) ) ) ; } public static final String getImplmentorName ( String typeName ) { Precondition . checkMustNotBeNull ( typeName , "" ) ; return MessageFormat . format ( "" , typeName , "" ) ; } public final Type t ( TypeMirror type ) { Precondition . checkMustNotBeNull ( type , "" ) ; return importer . resolve ( new Jsr269 ( factory ) . convert ( type ) ) ; } public final Type t ( TypeElement type ) { Precondition . checkMustNotBeNull ( type , "" ) ; DeclaredType t = environment . getTypeUtils ( ) . getDeclaredType ( type ) ; return importer . resolve ( new Jsr269 ( factory ) . convert ( t ) ) ; } public final Type t ( java . lang . reflect . Type type ) { Precondition . checkMustNotBeNull ( type , "" ) ; return importer . toType ( type ) ; } public Literal v ( String value ) { Precondition . checkMustNotBeNull ( value , "" ) ; return Models . toLiteral ( factory , value ) ; } public Literal v ( String pattern , Object ... arguments ) { Precondition . checkMustNotBeNull ( pattern , "" ) ; Precondition . checkMustNotBeNull ( arguments , "" ) ; return Models . toLiteral ( factory , MessageFormat . format ( pattern , arguments ) ) ; } public Type toSourceType ( TypeMirror type ) { Precondition . checkMustNotBeNull ( type , "" ) ; Type source = t ( Source . class ) ; Type modelType = t ( type ) ; return factory . newParameterizedType ( source , Collections . singletonList ( modelType ) ) ; } public Type toInType ( TypeMirror type ) { Precondition . checkMustNotBeNull ( type , "" ) ; Type source = t ( In . class ) ; Type modelType = t ( type ) ; return factory . newParameterizedType ( source , Collections . singletonList ( modelType ) ) ; } public Type toOutType ( TypeMirror type ) { Precondition . checkMustNotBeNull ( type , "" ) ; Type source = t ( Out . class ) ; Type modelType = t ( type ) ; return factory . newParameterizedType ( source , Collections . singletonList ( modelType ) ) ; } public List < TypeParameterDeclaration > toTypeParameters ( ExecutableElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; return toTypeParameters ( element . getTypeParameters ( ) ) ; } public List < TypeParameterDeclaration > toTypeParameters ( TypeElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; return toTypeParameters ( element . getTypeParameters ( ) ) ; } private List < TypeParameterDeclaration > toTypeParameters ( List < ? extends TypeParameterElement > typeParameters ) { assert typeParameters != null ; List < TypeParameterDeclaration > results = Lists . create ( ) ; for ( TypeParameterElement typeParameter : typeParameters ) { SimpleName name = factory . newSimpleName ( typeParameter . getSimpleName ( ) . toString ( ) ) ; List < Type > typeBounds = Lists . create ( ) ; for ( TypeMirror typeBound : typeParameter . getBounds ( ) ) { typeBounds . add ( t ( typeBound ) ) ; } results . add ( factory . newTypeParameterDeclaration ( name , typeBounds ) ) ; } return results ; } public List < Type > toTypeVariables ( ExecutableElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; return toTypeVariables ( element . getTypeParameters ( ) ) ; } public List < Type > toTypeVariables ( TypeElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; return toTypeVariables ( element . getTypeParameters ( ) ) ; } private List < Type > toTypeVariables ( List < ? extends TypeParameterElement > typeParameters ) { List < Type > results = Lists . create ( ) ; for ( TypeParameterElement typeParameter : typeParameters ) { SimpleName name = factory . newSimpleName ( typeParameter . getSimpleName ( ) . toString ( ) ) ; results . add ( factory . newNamedType ( name ) ) ; } return results ; } } package com . asakusafw . compiler . operator ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeParameterElement ; import javax . lang . model . element . VariableElement ; import javax . lang . model . type . TypeMirror ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldAccessExpression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ImplementationBuilder { private ExecutableElement element ; private ModelFactory factory ; private ImportBuilder importer ; private NameGenerator names ; private Jsr269 converter ; private List < Statement > statements ; private List < FieldDeclaration > fields ; public ImplementationBuilder ( OperatorProcessor . Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; this . element = context . element ; this . factory = context . environment . getFactory ( ) ; this . importer = context . importer ; this . names = context . names ; this . converter = new Jsr269 ( factory ) ; this . statements = Lists . create ( ) ; this . fields = Lists . create ( ) ; } public SimpleName getParameterName ( int index ) { VariableElement parameter = element . getParameters ( ) . get ( index ) ; return factory . newSimpleName ( parameter . getSimpleName ( ) . toString ( ) ) ; } public Type getParameterType ( int index ) { VariableElement parameter = element . getParameters ( ) . get ( index ) ; return importer . resolve ( converter . convert ( parameter . asType ( ) ) ) ; } public void addStatement ( Statement statement ) { Precondition . checkMustNotBeNull ( statement , "" ) ; this . statements . add ( statement ) ; } public void addCopyStatement ( Expression from , Expression to ) { Precondition . checkMustNotBeNull ( from , "" ) ; Precondition . checkMustNotBeNull ( to , "" ) ; this . statements . add ( new ExpressionBuilder ( factory , to ) . method ( "" , from ) . toStatement ( ) ) ; } public FieldAccessExpression addModelObjectField ( TypeMirror type , String name ) { Precondition . checkMustNotBeNull ( type , "" ) ; Precondition . checkMustNotBeNull ( name , "" ) ; return addModelObjectField ( converter . convert ( type ) , name ) ; } public FieldAccessExpression addModelObjectField ( Type type , String name ) { Precondition . checkMustNotBeNull ( type , "" ) ; Precondition . checkMustNotBeNull ( name , "" ) ; SimpleName fieldName = names . create ( name ) ; Type fieldType = importer . resolve ( type ) ; fields . add ( factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , fieldType , fieldName , new TypeBuilder ( factory , fieldType ) . newObject ( ) . toExpression ( ) ) ) ; return factory . newFieldAccessExpression ( factory . newThis ( ) , fieldName ) ; } public List < TypeBodyDeclaration > toImplementation ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . addAll ( fields ) ; results . add ( toMethodDeclaration ( ) ) ; return results ; } private MethodDeclaration toMethodDeclaration ( ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( importer . toType ( Override . class ) ) . Public ( ) . toAttributes ( ) , toTypeParameters ( ) , importer . resolve ( converter . convert ( element . getReturnType ( ) ) ) , factory . newSimpleName ( element . getSimpleName ( ) . toString ( ) ) , toParameters ( ) , , Collections . < Type > emptyList ( ) , factory . newBlock ( statements ) ) ; } private List < FormalParameterDeclaration > toParameters ( ) { List < ? extends VariableElement > parameters = element . getParameters ( ) ; List < FormalParameterDeclaration > results = Lists . create ( ) ; for ( int i = , n = parameters . size ( ) ; i < n ; i ++ ) { VariableElement var = parameters . get ( i ) ; results . add ( factory . newFormalParameterDeclaration ( Collections . < Attribute > emptyList ( ) , importer . resolve ( converter . convert ( var . asType ( ) ) ) , ( i == n - ) && element . isVarArgs ( ) , factory . newSimpleName ( var . getSimpleName ( ) . toString ( ) ) , ) ) ; } return results ; } private List < TypeParameterDeclaration > toTypeParameters ( ) { List < ? extends TypeParameterElement > typeParameters = element . getTypeParameters ( ) ; if ( typeParameters . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < TypeParameterDeclaration > results = Lists . create ( ) ; for ( TypeParameterElement typeParameter : typeParameters ) { SimpleName name = factory . newSimpleName ( typeParameter . getSimpleName ( ) . toString ( ) ) ; List < Type > typeBounds = Lists . create ( ) ; for ( TypeMirror typeBound : typeParameter . getBounds ( ) ) { typeBounds . add ( importer . resolve ( converter . convert ( typeBound ) ) ) ; } results . add ( factory . newTypeParameterDeclaration ( name , typeBounds ) ) ; } return results ; } } package com . asakusafw . compiler . operator ; package com . asakusafw . compiler . operator ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . VariableElement ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . operator . OperatorProcessor . Context ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; public class OperatorFactoryClassGenerator extends OperatorClassGenerator { static final String RESOLVER_FIELD_NAME = "" ; public OperatorFactoryClassGenerator ( OperatorCompilingEnvironment environment , ModelFactory factory , ImportBuilder importer , OperatorClass operatorClass ) { super ( environment , factory , importer , operatorClass ) ; } @ Override public TypeDeclaration generate ( ) { for ( OperatorMethod method : operatorClass . getMethods ( ) ) { importer . resolvePackageMember ( Models . append ( factory , getClassName ( ) , getObjectClassName ( method . getElement ( ) ) ) ) ; } return super . generate ( ) ; } @ Override protected SimpleName getClassName ( ) { return util . getFactoryName ( operatorClass . getElement ( ) ) ; } @ Override protected Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . linkType ( util . t ( operatorClass . getElement ( ) ) ) . text ( "" ) . seeType ( util . t ( operatorClass . getElement ( ) ) ) . toJavadoc ( ) ; } @ Override protected List < TypeBodyDeclaration > createMembers ( ) { NameGenerator names = new NameGenerator ( factory ) ; List < TypeBodyDeclaration > results = Lists . create ( ) ; for ( OperatorMethod method : operatorClass . getMethods ( ) ) { OperatorProcessor . Context context = new OperatorProcessor . Context ( environment , method . getAnnotation ( ) , method . getElement ( ) , importer , names ) ; OperatorProcessor processor = method . getProcessor ( ) ; OperatorMethodDescriptor descriptor = processor . describe ( context ) ; if ( descriptor == null ) { continue ; } TypeDeclaration objectClass = createObjectClass ( context , descriptor ) ; if ( objectClass == null ) { continue ; } Type objectType = importer . resolvePackageMember ( Models . append ( factory , getClassName ( ) , objectClass . getName ( ) ) ) ; if ( context . element . getTypeParameters ( ) . isEmpty ( ) == false ) { objectType = new TypeBuilder ( factory , objectType ) . parameterize ( util . toTypeVariables ( context . element ) ) . toType ( ) ; } MethodDeclaration factoryMethod = createFactoryMethod ( context , descriptor , objectType ) ; if ( factoryMethod == null ) { continue ; } results . add ( objectClass ) ; results . add ( factoryMethod ) ; } return results ; } private TypeDeclaration createObjectClass ( Context context , OperatorMethodDescriptor descriptor ) { assert context != null ; assert descriptor != null ; SimpleName name = getObjectClassName ( context . element ) ; NamedType objectType = ( NamedType ) importer . resolvePackageMember ( Models . append ( factory , getClassName ( ) , name ) ) ; List < TypeParameterDeclaration > typeParameters = util . toTypeParameters ( context . element ) ; List < TypeBodyDeclaration > members = createObjectMembers ( context , descriptor , objectType ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . inline ( descriptor . getDocumentation ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Static ( ) . Final ( ) . toAttributes ( ) , name , typeParameters , null , Collections . singletonList ( util . t ( Operator . class ) ) , members ) ; } private SimpleName getObjectClassName ( ExecutableElement element ) { assert element != null ; return factory . newSimpleName ( JavaName . of ( element . getSimpleName ( ) . toString ( ) ) . toTypeName ( ) ) ; } private List < TypeBodyDeclaration > createObjectMembers ( Context context , OperatorMethodDescriptor descriptor , NamedType objectType ) { assert context != null ; assert descriptor != null ; assert objectType != null ; List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createResolverField ( context ) ) ; for ( OperatorPortDeclaration var : descriptor . getOutputPorts ( ) ) { results . add ( createObjectOutputField ( context , var ) ) ; } results . add ( createObjectConstructor ( context , descriptor , objectType ) ) ; results . add ( createRenamer ( context , objectType ) ) ; return results ; } private MethodDeclaration createRenamer ( Context context , NamedType rawObjectType ) { assert context != null ; assert rawObjectType != null ; Type objectType ; if ( context . element . getTypeParameters ( ) . isEmpty ( ) ) { objectType = rawObjectType ; } else { objectType = new TypeBuilder ( factory , rawObjectType ) . parameterize ( util . toTypeVariables ( context . element ) ) . toType ( ) ; } SimpleName newName = context . names . create ( "" ) ; return factory . newMethodDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . param ( newName ) . text ( "" ) . returns ( ) . text ( "" ) . exception ( util . t ( IllegalArgumentException . class ) ) . text ( "" ) . code ( "" ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , objectType , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( util . t ( String . class ) , newName ) ) , Arrays . asList ( new Statement [ ] { new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( RESOLVER_FIELD_NAME ) . method ( "" , newName ) . toStatement ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . toReturnStatement ( ) , } ) ) ; } private FieldDeclaration createResolverField ( Context context ) { assert context != null ; return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , util . t ( FlowElementResolver . class ) , factory . newSimpleName ( RESOLVER_FIELD_NAME ) , null ) ; } private FieldDeclaration createObjectOutputField ( Context context , OperatorPortDeclaration var ) { assert context != null ; assert var != null ; return factory . newFieldDeclaration ( new JavadocBuilder ( factory ) . inline ( var . getDocumentation ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Final ( ) . toAttributes ( ) , util . toSourceType ( var . getType ( ) . getRepresentation ( ) ) , factory . newSimpleName ( context . names . reserve ( var . getName ( ) ) ) , null ) ; } private ConstructorDeclaration createObjectConstructor ( Context context , OperatorMethodDescriptor descriptor , NamedType objectType ) { assert context != null ; assert descriptor != null ; assert objectType != null ; List < FormalParameterDeclaration > parameters = createParametersForConstructor ( context , descriptor ) ; List < Statement > statements = createBodyForConstructor ( context , descriptor , parameters ) ; return factory . newConstructorDeclaration ( null , new AttributeBuilder ( factory ) . toAttributes ( ) , objectType . getName ( ) . getLastSegment ( ) , parameters , statements ) ; } private List < Statement > createBodyForConstructor ( Context context , OperatorMethodDescriptor descriptor , List < FormalParameterDeclaration > parameters ) { assert context != null ; assert descriptor != null ; assert parameters != null ; List < Statement > statements = Lists . create ( ) ; SimpleName builderName = context . names . create ( "" ) ; statements . add ( new TypeBuilder ( factory , util . t ( OperatorDescription . Builder . class ) ) . newObject ( factory . newClassLiteral ( util . t ( descriptor . getAnnotationType ( ) ) ) ) . toLocalVariableDeclaration ( util . t ( OperatorDescription . Builder . class ) , builderName ) ) ; statements . add ( new ExpressionBuilder ( factory , builderName ) . method ( "" , factory . newClassLiteral ( util . t ( operatorClass . getElement ( ) ) ) , factory . newClassLiteral ( factory . newNamedType ( util . getImplementorName ( operatorClass . getElement ( ) ) ) ) , util . v ( descriptor . getName ( ) ) ) . toStatement ( ) ) ; for ( VariableElement parameter : context . element . getParameters ( ) ) { statements . add ( new ExpressionBuilder ( factory , builderName ) . method ( "" , new TypeBuilder ( factory , util . t ( environment . getErasure ( parameter . asType ( ) ) ) ) . dotClass ( ) . toExpression ( ) ) . toStatement ( ) ) ; } for ( OperatorPortDeclaration var : descriptor . getInputPorts ( ) ) { ShuffleKey key = var . getShuffleKey ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( util . v ( var . getName ( ) ) ) ; arguments . add ( factory . newSimpleName ( var . getName ( ) ) ) ; if ( key != null ) { arguments . add ( toSource ( key ) ) ; } statements . add ( new ExpressionBuilder ( factory , builderName ) . method ( "" , arguments ) . toStatement ( ) ) ; } for ( OperatorPortDeclaration var : descriptor . getOutputPorts ( ) ) { Expression type = toExpression ( var ) ; statements . add ( new ExpressionBuilder ( factory , builderName ) . method ( "" , util . v ( var . getName ( ) ) , type ) . toStatement ( ) ) ; } for ( OperatorPortDeclaration var : descriptor . getParameters ( ) ) { Expression type = toExpression ( var ) ; statements . add ( new ExpressionBuilder ( factory , builderName ) . method ( "" , util . v ( var . getName ( ) ) , type , factory . newSimpleName ( var . getName ( ) ) ) . toStatement ( ) ) ; } for ( Expression attr : descriptor . getAttributes ( ) ) { statements . add ( new ExpressionBuilder ( factory , builderName ) . method ( "" , attr ) . toStatement ( ) ) ; } Expression resolver = new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( RESOLVER_FIELD_NAME ) . toExpression ( ) ; statements . add ( new ExpressionBuilder ( factory , resolver ) . assignFrom ( new ExpressionBuilder ( factory , builderName ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; for ( OperatorPortDeclaration var : descriptor . getInputPorts ( ) ) { statements . add ( new ExpressionBuilder ( factory , resolver ) . method ( "" , util . v ( var . getName ( ) ) , factory . newSimpleName ( var . getName ( ) ) ) . toStatement ( ) ) ; } for ( OperatorPortDeclaration var : descriptor . getOutputPorts ( ) ) { statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( var . getName ( ) ) . assignFrom ( new ExpressionBuilder ( factory , resolver ) . method ( "" , util . v ( var . getName ( ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; } return statements ; } private Expression toExpression ( OperatorPortDeclaration var ) throws AssertionError { Expression type ; switch ( var . getType ( ) . getKind ( ) ) { case DIRECT : type = factory . newClassLiteral ( util . t ( var . getType ( ) . getDirect ( ) ) ) ; break ; case REFERENCE : type = factory . newSimpleName ( var . getType ( ) . getReference ( ) ) ; break ; default : throw new AssertionError ( var . getType ( ) . getKind ( ) ) ; } return type ; } private Expression toSource ( ShuffleKey key ) { assert key != null ; List < Expression > group = Lists . create ( ) ; for ( String property : key . getGroupProperties ( ) ) { group . add ( Models . toLiteral ( factory , property ) ) ; } List < Expression > order = Lists . create ( ) ; for ( ShuffleKey . Order o : key . getOrderings ( ) ) { order . add ( new TypeBuilder ( factory , util . t ( ShuffleKey . Order . class ) ) . newObject ( Models . toLiteral ( factory , o . getProperty ( ) ) , new TypeBuilder ( factory , util . t ( ShuffleKey . Direction . class ) ) . field ( o . getDirection ( ) . name ( ) ) . toExpression ( ) ) . toExpression ( ) ) ; } return new TypeBuilder ( factory , util . t ( ShuffleKey . class ) ) . newObject ( toList ( util . t ( String . class ) , group ) , toList ( util . t ( ShuffleKey . Order . class ) , order ) ) . toExpression ( ) ; } private Expression toList ( Type type , List < Expression > expressions ) { assert type != null ; assert expressions != null ; return new TypeBuilder ( factory , util . t ( Arrays . class ) ) . method ( "" , factory . newArrayCreationExpression ( factory . newArrayType ( type ) , Collections . < Expression > emptyList ( ) , factory . newArrayInitializer ( expressions ) ) ) . toExpression ( ) ; } private List < FormalParameterDeclaration > createParametersForConstructor ( Context context , OperatorMethodDescriptor descriptor ) { assert context != null ; assert descriptor != null ; List < FormalParameterDeclaration > parameters = Lists . create ( ) ; for ( OperatorPortDeclaration var : descriptor . getInputPorts ( ) ) { SimpleName name = factory . newSimpleName ( context . names . reserve ( var . getName ( ) ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( util . toSourceType ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; } for ( OperatorPortDeclaration var : descriptor . getParameters ( ) ) { SimpleName name = factory . newSimpleName ( context . names . reserve ( var . getName ( ) ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( util . t ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; } return parameters ; } private MethodDeclaration createFactoryMethod ( Context context , OperatorMethodDescriptor descriptor , Type objectType ) { assert context != null ; assert descriptor != null ; assert objectType != null ; JavadocBuilder javadoc = new JavadocBuilder ( factory ) ; javadoc . inline ( descriptor . getDocumentation ( ) ) ; List < FormalParameterDeclaration > parameters = Lists . create ( ) ; List < Expression > arguments = Lists . create ( ) ; for ( OperatorPortDeclaration var : descriptor . getInputPorts ( ) ) { SimpleName name = factory . newSimpleName ( var . getName ( ) ) ; javadoc . param ( name ) . inline ( var . getDocumentation ( ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( util . toSourceType ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; arguments . add ( name ) ; } for ( OperatorPortDeclaration var : descriptor . getParameters ( ) ) { SimpleName name = factory . newSimpleName ( var . getName ( ) ) ; javadoc . param ( name ) . inline ( var . getDocumentation ( ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( util . t ( var . getType ( ) . getRepresentation ( ) ) , name ) ) ; arguments . add ( name ) ; } javadoc . returns ( ) . text ( "" ) ; List < Type > rawParameterTypes = Lists . create ( ) ; for ( VariableElement var : context . element . getParameters ( ) ) { rawParameterTypes . add ( util . t ( environment . getErasure ( var . asType ( ) ) ) ) ; } javadoc . seeMethod ( util . t ( operatorClass . getElement ( ) ) , descriptor . getName ( ) , rawParameterTypes ) ; return factory . newMethodDeclaration ( javadoc . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , util . toTypeParameters ( context . element ) , objectType , factory . newSimpleName ( JavaName . of ( descriptor . getName ( ) ) . toMemberName ( ) ) , parameters , , Collections . < Type > emptyList ( ) , factory . newBlock ( new TypeBuilder ( factory , objectType ) . newObject ( arguments ) . toReturnStatement ( ) ) ) ; } } package com . asakusafw . compiler . operator ; import java . lang . annotation . Annotation ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . VariableElement ; import javax . lang . model . type . TypeKind ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Types ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . OperatorPortDeclaration . Kind ; import com . asakusafw . compiler . operator . OperatorProcessor . Context ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . DocElement ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; import com . asakusafw . vocabulary . flow . graph . OperatorHelper ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; public class OperatorMethodDescriptor { private final Class < ? extends Annotation > annotationType ; private final List < DocElement > documentation ; private final String name ; private final List < OperatorPortDeclaration > inputPorts ; private final List < OperatorPortDeclaration > outputPorts ; private final List < OperatorPortDeclaration > parameters ; private final List < Expression > attributes ; public OperatorMethodDescriptor ( Class < ? extends Annotation > annotationType , List < DocElement > documentation , String name , List < OperatorPortDeclaration > inputPorts , List < OperatorPortDeclaration > outputPorts , List < OperatorPortDeclaration > parameters , List < Expression > attributes ) { Precondition . checkMustNotBeNull ( annotationType , "" ) ; Precondition . checkMustNotBeNull ( documentation , "" ) ; Precondition . checkMustNotBeNull ( name , "" ) ; Precondition . checkMustNotBeNull ( inputPorts , "" ) ; Precondition . checkMustNotBeNull ( outputPorts , "" ) ; Precondition . checkMustNotBeNull ( parameters , "" ) ; this . annotationType = annotationType ; this . documentation = Lists . freeze ( documentation ) ; this . name = name ; this . inputPorts = Lists . freeze ( inputPorts ) ; this . outputPorts = Lists . freeze ( outputPorts ) ; this . parameters = Lists . freeze ( parameters ) ; this . attributes = Lists . freeze ( attributes ) ; } public Class < ? extends Annotation > getAnnotationType ( ) { return annotationType ; } public List < DocElement > getDocumentation ( ) { return documentation ; } public String getName ( ) { return name ; } public List < OperatorPortDeclaration > getInputPorts ( ) { return inputPorts ; } public List < OperatorPortDeclaration > getOutputPorts ( ) { return outputPorts ; } public List < OperatorPortDeclaration > getParameters ( ) { return parameters ; } public List < Expression > getAttributes ( ) { return attributes ; } public static class Builder { private final Class < ? extends Annotation > annotationType ; private List < DocElement > operatorDescription ; private final String name ; private final List < OperatorPortDeclaration > inputPorts ; private final List < OperatorPortDeclaration > outputPorts ; private final List < OperatorPortDeclaration > parameters ; private final List < Expression > attributes ; private final Context context ; public Builder ( Class < ? extends Annotation > annotationType , OperatorProcessor . Context context ) { Precondition . checkMustNotBeNull ( annotationType , "" ) ; Precondition . checkMustNotBeNull ( context , "" ) ; this . context = context ; this . annotationType = annotationType ; this . name = context . element . getSimpleName ( ) . toString ( ) ; this . operatorDescription = Lists . create ( ) ; this . inputPorts = Lists . create ( ) ; this . outputPorts = Lists . create ( ) ; this . parameters = Lists . create ( ) ; this . attributes = Lists . create ( ) ; } public String findInput ( TypeMirror type ) { Precondition . checkMustNotBeNull ( type , "" ) ; if ( type . getKind ( ) != TypeKind . TYPEVAR ) { return null ; } Types types = context . environment . getTypeUtils ( ) ; for ( OperatorPortDeclaration input : inputPorts ) { if ( types . isSameType ( type , input . getType ( ) . getRepresentation ( ) ) ) { return input . getName ( ) ; } } return null ; } public void setDocumentation ( List < ? extends DocElement > description ) { Precondition . checkMustNotBeNull ( description , "" ) ; this . operatorDescription = Lists . from ( description ) ; } public void addInput ( List < ? extends DocElement > documentation , String varName , TypeMirror type , Integer position ) { addInput ( documentation , varName , type , position , null ) ; } public void addInput ( List < ? extends DocElement > documentation , String varName , TypeMirror type , Integer position , ShuffleKey shuffleKey ) { Precondition . checkMustNotBeNull ( documentation , "" ) ; Precondition . checkMustNotBeNull ( varName , "" ) ; inputPorts . add ( new OperatorPortDeclaration ( Kind . INPUT , documentation , varName , PortTypeDescription . reference ( type , varName ) , position , shuffleKey ) ) ; } public void addOutput ( List < ? extends DocElement > documentation , String varName , TypeMirror type , String correspondedInputName , Integer position ) { Precondition . checkMustNotBeNull ( documentation , "" ) ; Precondition . checkMustNotBeNull ( varName , "" ) ; Precondition . checkMustNotBeNull ( type , "" ) ; PortTypeDescription typeDesc ; if ( correspondedInputName != null ) { typeDesc = PortTypeDescription . reference ( type , correspondedInputName ) ; } else { typeDesc = PortTypeDescription . direct ( type ) ; } outputPorts . add ( new OperatorPortDeclaration ( Kind . OUTPUT , documentation , varName , typeDesc , position , null ) ) ; } public void addOutput ( String documentation , String varName , TypeMirror type , String correspondedInputName , Integer position ) { Precondition . checkMustNotBeNull ( documentation , "" ) ; Precondition . checkMustNotBeNull ( type , "" ) ; Precondition . checkMustNotBeNull ( varName , "" ) ; List < ? extends DocElement > elements = Collections . emptyList ( ) ; if ( documentation != null ) { elements = Collections . singletonList ( Models . getModelFactory ( ) . newDocText ( documentation ) ) ; } addOutput ( elements , varName , type , correspondedInputName , position ) ; } public void addParameter ( List < ? extends DocElement > documentation , String varName , TypeMirror type , Integer position ) { Precondition . checkMustNotBeNull ( documentation , "" ) ; Precondition . checkMustNotBeNull ( varName , "" ) ; Precondition . checkMustNotBeNull ( type , "" ) ; parameters . add ( new OperatorPortDeclaration ( Kind . CONSTANT , documentation , varName , PortTypeDescription . direct ( type ) , position , null ) ) ; } public void addAttribute ( Expression attribute ) { Precondition . checkMustNotBeNull ( attribute , "" ) ; attributes . add ( attribute ) ; } public void addAttribute ( Enum < ? extends FlowElementAttribute > constant ) { Precondition . checkMustNotBeNull ( constant , "" ) ; ModelFactory f = context . environment . getFactory ( ) ; ImportBuilder ib = context . importer ; Expression attribute = new TypeBuilder ( f , ib . toType ( constant . getDeclaringClass ( ) ) ) . field ( constant . name ( ) ) . toExpression ( ) ; addAttribute ( attribute ) ; } public void addOperatorHelper ( ExecutableElement helperMethod ) { Precondition . checkMustNotBeNull ( helperMethod , "" ) ; ModelFactory f = context . environment . getFactory ( ) ; ImportBuilder ib = context . importer ; Jsr269 conv = new Jsr269 ( f ) ; List < Expression > parameterTypeLiterals = Lists . create ( ) ; for ( VariableElement parameter : helperMethod . getParameters ( ) ) { TypeMirror type = context . environment . getErasure ( parameter . asType ( ) ) ; parameterTypeLiterals . add ( new TypeBuilder ( f , ib . resolve ( conv . convert ( type ) ) ) . dotClass ( ) . toExpression ( ) ) ; } Expression attribute = new TypeBuilder ( f , ib . toType ( OperatorHelper . class ) ) . newObject ( new Expression [ ] { Models . toLiteral ( f , helperMethod . getSimpleName ( ) . toString ( ) ) , new TypeBuilder ( f , ib . toType ( Arrays . class ) ) . method ( "" , new TypeBuilder ( f , ib . toType ( Class . class ) ) . parameterize ( f . newWildcard ( ) ) . array ( ) . newArray ( f . newArrayInitializer ( parameterTypeLiterals ) ) . toExpression ( ) ) . toExpression ( ) } ) . toExpression ( ) ; addAttribute ( attribute ) ; } public OperatorMethodDescriptor toDescriptor ( ) { return new OperatorMethodDescriptor ( annotationType , operatorDescription , name , inputPorts , outputPorts , parameters , attributes ) ; } } } package com . asakusafw . compiler . operator ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . ExecutableElement ; import com . asakusafw . compiler . common . Precondition ; public class OperatorMethod { private ExecutableElement element ; private OperatorProcessor processor ; public OperatorMethod ( ExecutableElement element , OperatorProcessor processor ) { Precondition . checkMustNotBeNull ( element , "" ) ; Precondition . checkMustNotBeNull ( processor , "" ) ; this . element = element ; this . processor = processor ; } public AnnotationMirror getAnnotation ( ) { return processor . getOperatorAnnotation ( element ) ; } public ExecutableElement getElement ( ) { return this . element ; } public OperatorProcessor getProcessor ( ) { return this . processor ; } } package com . asakusafw . compiler . operator ; import java . io . IOException ; import java . util . Map ; import javax . annotation . processing . Filer ; import javax . annotation . processing . Messager ; import javax . annotation . processing . ProcessingEnvironment ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . TypeKind ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Elements ; import javax . lang . model . util . Types ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; public class OperatorCompilingEnvironment { private final ProcessingEnvironment processingEnvironment ; private final ModelFactory factory ; private final OperatorCompilerOptions options ; private final Map < Class < ? > , DeclaredType > rawTypeCache = Maps . create ( ) ; public OperatorCompilingEnvironment ( ProcessingEnvironment processingEnvironment , ModelFactory factory , OperatorCompilerOptions options ) { Precondition . checkMustNotBeNull ( processingEnvironment , "" ) ; Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( options , "" ) ; this . processingEnvironment = processingEnvironment ; this . factory = factory ; this . options = options ; } public ProcessingEnvironment getProcessingEnvironment ( ) { return processingEnvironment ; } public ModelFactory getFactory ( ) { return factory ; } public ClassLoader getServiceClassLoader ( ) { return options . getServiceClassLoader ( ) ; } public OperatorCompilerOptions getOptions ( ) { return options ; } public Messager getMessager ( ) { return getProcessingEnvironment ( ) . getMessager ( ) ; } public Elements getElementUtils ( ) { return getProcessingEnvironment ( ) . getElementUtils ( ) ; } public Types getTypeUtils ( ) { return getProcessingEnvironment ( ) . getTypeUtils ( ) ; } public void emit ( CompilationUnit unit ) throws IOException { Precondition . checkMustNotBeNull ( unit , "" ) ; Filer filer = getProcessingEnvironment ( ) . getFiler ( ) ; new Jsr269 ( factory ) . emit ( filer , unit ) ; } public DataModelMirror loadDataModel ( TypeMirror type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return options . getDataModelRepository ( ) . load ( this , type ) ; } public DeclaredType getDeclaredType ( Class < ? > type ) { Precondition . checkMustNotBeNull ( type , "" ) ; DeclaredType result = rawTypeCache . get ( type ) ; if ( result == null ) { TypeElement elem = getElementUtils ( ) . getTypeElement ( type . getName ( ) ) ; if ( elem == null ) { throw new IllegalStateException ( type . getName ( ) ) ; } result = getTypeUtils ( ) . getDeclaredType ( elem ) ; rawTypeCache . put ( type , result ) ; } return result ; } public TypeMirror getErasure ( TypeMirror type ) { Precondition . checkMustNotBeNull ( type , "" ) ; if ( type . getKind ( ) == TypeKind . DECLARED ) { TypeElement element = ( TypeElement ) ( ( DeclaredType ) type ) . asElement ( ) ; return getTypeUtils ( ) . getDeclaredType ( element ) ; } return getTypeUtils ( ) . erasure ( type ) ; } } package com . asakusafw . compiler . operator ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . DocElement ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; public class OperatorPortDeclaration { private final Kind kind ; private final List < DocElement > documentation ; private final String name ; private final PortTypeDescription type ; private final Integer position ; private final ShuffleKey shuffleKey ; public OperatorPortDeclaration ( Kind kind , List < ? extends DocElement > documentation , String name , PortTypeDescription type , Integer position , ShuffleKey shuffleKey ) { Precondition . checkMustNotBeNull ( kind , "" ) ; Precondition . checkMustNotBeNull ( documentation , "" ) ; Precondition . checkMustNotBeNull ( name , "" ) ; Precondition . checkMustNotBeNull ( type , "" ) ; this . kind = kind ; this . documentation = Lists . freeze ( documentation ) ; this . name = name ; this . type = type ; this . position = position ; this . shuffleKey = shuffleKey ; } public Integer getParameterPosition ( ) { return position ; } public Kind getKind ( ) { return this . kind ; } public List < DocElement > getDocumentation ( ) { return this . documentation ; } public String getName ( ) { return this . name ; } public PortTypeDescription getType ( ) { return this . type ; } public ShuffleKey getShuffleKey ( ) { return shuffleKey ; } public enum Kind { INPUT , OUTPUT , CONSTANT , } } package com . asakusafw . compiler . operator ; import java . text . MessageFormat ; import java . util . Map ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . repository . SpiDataModelMirrorRepository ; public final class OperatorCompilerOptions { private ClassLoader serviceClassLoader ; private DataModelMirrorRepository dataModelRepository ; private OperatorCompilerOptions ( ) { return ; } public static OperatorCompilerOptions parse ( Map < String , String > options ) { Precondition . checkMustNotBeNull ( options , "" ) ; OperatorCompilerOptions result = new OperatorCompilerOptions ( ) ; result . serviceClassLoader = OperatorCompilerOptions . class . getClassLoader ( ) ; result . dataModelRepository = new SpiDataModelMirrorRepository ( result . serviceClassLoader ) ; return result ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) ) ; } public ClassLoader getServiceClassLoader ( ) { return serviceClassLoader ; } public DataModelMirrorRepository getDataModelRepository ( ) { return dataModelRepository ; } } package com . asakusafw . compiler . operator ; import java . lang . annotation . Annotation ; import java . util . List ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . ExecutableElement ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . ImportBuilder ; public interface OperatorProcessor { void initialize ( OperatorCompilingEnvironment env ) ; Class < ? extends Annotation > getTargetAnnotationType ( ) ; AnnotationMirror getOperatorAnnotation ( ExecutableElement element ) ; OperatorMethodDescriptor describe ( Context context ) ; List < ? extends TypeBodyDeclaration > implement ( Context context ) ; class Context { public final OperatorCompilingEnvironment environment ; public final AnnotationMirror annotation ; public final ExecutableElement element ; public final ImportBuilder importer ; public final NameGenerator names ; public Context ( OperatorCompilingEnvironment environment , AnnotationMirror annotation , ExecutableElement element , ImportBuilder importer , NameGenerator names ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( annotation , "" ) ; Precondition . checkMustNotBeNull ( element , "" ) ; Precondition . checkMustNotBeNull ( importer , "" ) ; Precondition . checkMustNotBeNull ( names , "" ) ; this . environment = environment ; this . annotation = annotation ; this . element = element ; this . importer = importer ; this . names = names ; } } } package com . asakusafw . compiler . operator ; import javax . lang . model . type . TypeMirror ; public final class PortTypeDescription { private final Kind kind ; private final TypeMirror representation ; private final TypeMirror direct ; private final String reference ; private PortTypeDescription ( Kind kind , TypeMirror representation , TypeMirror direct , String reference ) { assert kind != null ; assert representation != null ; assert direct != null || reference != null ; this . kind = kind ; this . representation = representation ; this . direct = direct ; this . reference = reference ; } public static PortTypeDescription direct ( TypeMirror type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return new PortTypeDescription ( Kind . DIRECT , type , type , null ) ; } public static PortTypeDescription reference ( TypeMirror representation , String variableName ) { if ( representation == null ) { throw new IllegalArgumentException ( "" ) ; } if ( variableName == null ) { throw new IllegalArgumentException ( "" ) ; } return new PortTypeDescription ( Kind . REFERENCE , representation , null , variableName ) ; } public Kind getKind ( ) { return kind ; } public TypeMirror getRepresentation ( ) { return representation ; } public TypeMirror getDirect ( ) { return direct ; } public String getReference ( ) { if ( kind != Kind . REFERENCE ) { throw new IllegalStateException ( ) ; } return reference ; } public enum Kind { DIRECT , REFERENCE , } } package com . asakusafw . compiler . repository ; import java . util . List ; import java . util . Map ; import java . util . ServiceLoader ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class SpiExternalIoDescriptionProcessorRepository extends FlowCompilingEnvironment . Initialized implements ExternalIoDescriptionProcessor . Repository { static final Logger LOG = LoggerFactory . getLogger ( SpiExternalIoDescriptionProcessorRepository . class ) ; private List < ExternalIoDescriptionProcessor > processors ; private Map < Class < ? > , ExternalIoDescriptionProcessor > map ; @ Override protected void doInitialize ( ) { LOG . info ( "" ) ; this . processors = Lists . create ( ) ; this . map = Maps . create ( ) ; ServiceLoader < ExternalIoDescriptionProcessor > services = ServiceLoader . load ( ExternalIoDescriptionProcessor . class , getEnvironment ( ) . getServiceClassLoader ( ) ) ; for ( ExternalIoDescriptionProcessor proc : services ) { proc . initialize ( getEnvironment ( ) ) ; processors . add ( proc ) ; Class < ? > importerType = proc . getImporterDescriptionType ( ) ; Class < ? > exporterType = proc . getExporterDescriptionType ( ) ; if ( map . containsKey ( importerType ) ) { getEnvironment ( ) . error ( "" , importerType . getName ( ) , map . get ( importerType ) . getClass ( ) . getName ( ) , proc . getClass ( ) . getName ( ) ) ; } else { LOG . debug ( "" , proc . getImporterDescriptionType ( ) . getName ( ) , proc . getClass ( ) . getName ( ) ) ; map . put ( importerType , proc ) ; } if ( map . containsKey ( exporterType ) ) { getEnvironment ( ) . error ( "" , exporterType . getName ( ) , map . get ( exporterType ) . getClass ( ) . getName ( ) , proc . getClass ( ) . getName ( ) ) ; } else { LOG . debug ( "" , proc . getExporterDescriptionType ( ) . getName ( ) , proc . getClass ( ) . getName ( ) ) ; map . put ( exporterType , proc ) ; } } } @ Override public ExternalIoDescriptionProcessor findProcessor ( InputDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; ImporterDescription desc = description . getImporterDescription ( ) ; if ( desc == null ) { return null ; } Class < ? > keyClass = desc . getClass ( ) ; return findProcessor ( keyClass ) ; } @ Override public ExternalIoDescriptionProcessor findProcessor ( OutputDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; ExporterDescription desc = description . getExporterDescription ( ) ; if ( desc == null ) { return null ; } Class < ? > keyClass = desc . getClass ( ) ; return findProcessor ( keyClass ) ; } private ExternalIoDescriptionProcessor findProcessor ( Class < ? > keyClass ) { assert keyClass != null ; Class < ? > current = keyClass ; while ( current != null ) { ExternalIoDescriptionProcessor processor = map . get ( current ) ; if ( processor != null ) { return processor ; } current = current . getSuperclass ( ) ; } return null ; } } package com . asakusafw . compiler . repository ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . ServiceLoader ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . BatchCompilingEnvironment ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . WorkflowProcessor ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . batch . WorkDescription ; public class SpiWorkflowProcessorRepository extends BatchCompilingEnvironment . Initialized implements WorkflowProcessor . Repository { static final Logger LOG = LoggerFactory . getLogger ( SpiWorkflowProcessorRepository . class ) ; private Map < WorkflowProcessor , Set < WorkDescriptionProcessor < ? > > > processors ; private Map < Class < ? extends WorkDescription > , WorkDescriptionProcessor < ? > > descriptionProcessors ; @ Override protected void doInitialize ( ) { LOG . info ( "" ) ; Iterable < ? extends WorkflowProcessor > services = loadServices ( ) ; List < WorkflowProcessor > procs = Lists . create ( ) ; for ( WorkflowProcessor proc : services ) { proc . initialize ( getEnvironment ( ) ) ; procs . add ( proc ) ; LOG . debug ( "" , proc . getClass ( ) . getName ( ) ) ; } Map < Class < ? extends WorkDescriptionProcessor < ? > > , WorkDescriptionProcessor < ? > > saw = Maps . create ( ) ; descriptionProcessors = Maps . create ( ) ; for ( WorkflowProcessor proc : procs ) { proc . initialize ( getEnvironment ( ) ) ; for ( Class < ? extends WorkDescriptionProcessor < ? > > type : proc . getDescriptionProcessors ( ) ) { if ( saw . containsKey ( type ) ) { continue ; } saw . put ( type , null ) ; WorkDescriptionProcessor < ? > dproc = newInstance ( type ) ; if ( dproc == null ) { continue ; } dproc . initialize ( getEnvironment ( ) ) ; saw . put ( type , dproc ) ; Class < ? extends WorkDescription > target = dproc . getTargetType ( ) ; descriptionProcessors . put ( target , dproc ) ; } } processors = Maps . create ( ) ; for ( WorkflowProcessor proc : procs ) { Set < WorkDescriptionProcessor < ? > > subProcs = Sets . create ( ) ; for ( Class < ? extends WorkDescriptionProcessor < ? > > subProcClass : proc . getDescriptionProcessors ( ) ) { WorkDescriptionProcessor < ? > subProc = saw . get ( subProcClass ) ; if ( subProc != null ) { subProcs . add ( subProc ) ; } } processors . put ( proc , subProcs ) ; } } protected Iterable < ? extends WorkflowProcessor > loadServices ( ) { Iterable < WorkflowProcessor > services = ServiceLoader . load ( WorkflowProcessor . class , getEnvironment ( ) . getConfiguration ( ) . getServiceClassLoader ( ) ) ; return services ; } private < T extends WorkDescriptionProcessor < ? > > T newInstance ( Class < T > type ) { try { return type . newInstance ( ) ; } catch ( Exception e ) { getEnvironment ( ) . error ( "" , type . getName ( ) ) ; return null ; } } @ Override public Set < WorkflowProcessor > findWorkflowProcessors ( Set < ? extends WorkDescription > descriptions ) { Precondition . checkMustNotBeNull ( descriptions , "" ) ; if ( descriptions . isEmpty ( ) ) { return Collections . emptySet ( ) ; } Set < WorkDescriptionProcessor < ? > > procs = Sets . create ( ) ; for ( WorkDescription desc : descriptions ) { WorkDescriptionProcessor < ? > proc = findDescriptionProcessor ( desc ) ; if ( proc == null ) { return Collections . emptySet ( ) ; } procs . add ( proc ) ; } Set < WorkflowProcessor > results = Sets . create ( ) ; for ( Map . Entry < WorkflowProcessor , Set < WorkDescriptionProcessor < ? > > > entry : processors . entrySet ( ) ) { if ( entry . getValue ( ) . containsAll ( procs ) ) { results . add ( entry . getKey ( ) ) ; } } return results ; } @ Override public WorkDescriptionProcessor < ? > findDescriptionProcessor ( WorkDescription workDescription ) { Precondition . checkMustNotBeNull ( workDescription , "" ) ; Class < ? extends WorkDescription > aClass = workDescription . getClass ( ) ; Class < ? > current = aClass ; while ( current != null ) { WorkDescriptionProcessor < ? > proc = descriptionProcessors . get ( current ) ; if ( proc != null ) { if ( current != aClass ) { descriptionProcessors . put ( aClass , proc ) ; } return proc ; } current = current . getSuperclass ( ) ; } return null ; } } package com . asakusafw . compiler . repository ; import java . lang . annotation . Annotation ; import java . util . Map ; import java . util . ServiceLoader ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . compiler . flow . LineProcessor ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; public class SpiFlowElementProcessorRepository extends FlowCompilingEnvironment . Initialized implements FlowElementProcessor . Repository { static final Logger LOG = LoggerFactory . getLogger ( SpiFlowElementProcessorRepository . class ) ; private LinePartProcessor emptyProcessor ; private Map < Class < ? extends Annotation > , LineProcessor > lines ; private Map < Class < ? extends Annotation > , RendezvousProcessor > rendezvouses ; @ Override protected void doInitialize ( ) { LOG . info ( "" ) ; this . emptyProcessor = new LinePartProcessor . Nop ( ) ; this . lines = Maps . create ( ) ; this . rendezvouses = Maps . create ( ) ; emptyProcessor . initialize ( getEnvironment ( ) ) ; Map < Class < ? > , FlowElementProcessor > saw = Maps . create ( ) ; ServiceLoader < FlowElementProcessor > services = ServiceLoader . load ( FlowElementProcessor . class , getEnvironment ( ) . getServiceClassLoader ( ) ) ; for ( FlowElementProcessor proc : services ) { proc . initialize ( getEnvironment ( ) ) ; Class < ? extends Annotation > targetType = proc . getTargetAnnotationType ( ) ; if ( saw . containsKey ( targetType ) ) { getEnvironment ( ) . error ( "" , targetType . getName ( ) , saw . get ( targetType ) . getClass ( ) . getName ( ) , proc . getClass ( ) . getName ( ) ) ; continue ; } LOG . debug ( "" , targetType . getName ( ) , proc . getClass ( ) . getName ( ) ) ; saw . put ( targetType , proc ) ; switch ( proc . getKind ( ) ) { case LINE_PART : case LINE_END : lines . put ( targetType , ( LineProcessor ) proc ) ; break ; case RENDEZVOUS : rendezvouses . put ( targetType , ( RendezvousProcessor ) proc ) ; break ; default : throw new AssertionError ( proc . getKind ( ) ) ; } } } @ Override public LinePartProcessor getEmptyProcessor ( ) { return emptyProcessor ; } @ Override public FlowElementProcessor findProcessor ( FlowElementDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; LineProcessor lineProc = findLineProcessor ( description ) ; if ( lineProc != null ) { return lineProc ; } RendezvousProcessor rendProc = findRendezvousProcessor ( description ) ; if ( rendProc != null ) { return rendProc ; } return null ; } @ Override public LineProcessor findLineProcessor ( FlowElementDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; if ( description . getKind ( ) != FlowElementKind . OPERATOR ) { return null ; } OperatorDescription op = ( OperatorDescription ) description ; return lines . get ( op . getDeclaration ( ) . getAnnotationType ( ) ) ; } @ Override public RendezvousProcessor findRendezvousProcessor ( FlowElementDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; if ( description . getKind ( ) != FlowElementKind . OPERATOR ) { return null ; } OperatorDescription op = ( OperatorDescription ) description ; return rendezvouses . get ( op . getDeclaration ( ) . getAnnotationType ( ) ) ; } } package com . asakusafw . compiler . repository ; import java . util . List ; import java . util . ServiceLoader ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowGraphRewriter ; import com . asakusafw . utils . collections . Lists ; public class SpiFlowGraphRewriterRepository extends FlowCompilingEnvironment . Initialized implements FlowGraphRewriter . Repository { static final Logger LOG = LoggerFactory . getLogger ( SpiFlowGraphRewriterRepository . class ) ; private List < FlowGraphRewriter > rewriters ; @ Override protected void doInitialize ( ) { LOG . info ( "" ) ; this . rewriters = Lists . create ( ) ; ServiceLoader < FlowGraphRewriter > services = ServiceLoader . load ( FlowGraphRewriter . class , getEnvironment ( ) . getServiceClassLoader ( ) ) ; for ( FlowGraphRewriter rewriter : services ) { rewriter . initialize ( getEnvironment ( ) ) ; LOG . debug ( "" , rewriter . getClass ( ) . getName ( ) ) ; rewriters . add ( rewriter ) ; } } @ Override public List < FlowGraphRewriter > getRewriters ( ) { return rewriters ; } } package com . asakusafw . compiler . repository ; import java . text . MessageFormat ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ValueOptionProperty implements DataClass . Property { private ModelFactory factory ; private String name ; private Class < ? extends ValueOption < ? > > optionClass ; public ValueOptionProperty ( ModelFactory factory , String name , Class < ? extends ValueOption < ? > > optionClass ) { Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( name , "" ) ; Precondition . checkMustNotBeNull ( optionClass , "" ) ; this . factory = factory ; this . name = name ; this . optionClass = optionClass ; } @ Override public String getName ( ) { return name ; } @ Override public java . lang . reflect . Type getType ( ) { return optionClass ; } @ Override public Expression createNewInstance ( Type target ) { return new TypeBuilder ( factory , target ) . newObject ( ) . toExpression ( ) ; } @ Override public boolean canNull ( ) { return true ; } @ Override public Expression createIsNull ( Expression object ) { JavaName javaName = JavaName . of ( name ) ; javaName . addFirst ( "" ) ; javaName . addLast ( "" ) ; return new ExpressionBuilder ( factory , object ) . method ( javaName . toMemberName ( ) ) . method ( "" ) . toExpression ( ) ; } @ Override public Expression createGetter ( Expression object ) { JavaName javaName = JavaName . of ( name ) ; javaName . addFirst ( "" ) ; javaName . addLast ( "" ) ; return new ExpressionBuilder ( factory , object ) . method ( javaName . toMemberName ( ) ) . toExpression ( ) ; } @ Override public Statement assign ( Expression target , Expression source ) { return new ExpressionBuilder ( factory , target ) . method ( "" , source ) . toStatement ( ) ; } @ Override public Statement createGetter ( Expression object , Expression target ) { return assign ( target , createGetter ( object ) ) ; } @ Override public Statement createSetter ( Expression object , Expression value ) { JavaName javaName = JavaName . of ( name ) ; javaName . addFirst ( "" ) ; javaName . addLast ( "" ) ; return new ExpressionBuilder ( factory , object ) . method ( javaName . toMemberName ( ) , value ) . toStatement ( ) ; } @ Override public Statement createWriter ( Expression object , Expression dataOutput ) { Precondition . checkMustNotBeNull ( object , "" ) ; Precondition . checkMustNotBeNull ( dataOutput , "" ) ; return new ExpressionBuilder ( factory , object ) . method ( "" , dataOutput ) . toStatement ( ) ; } @ Override public Statement createReader ( Expression object , Expression dataInput ) { Precondition . checkMustNotBeNull ( object , "" ) ; Precondition . checkMustNotBeNull ( dataInput , "" ) ; return new ExpressionBuilder ( factory , object ) . method ( "" , dataInput ) . toStatement ( ) ; } @ Override public Expression createHashCode ( Expression source ) { Precondition . checkMustNotBeNull ( source , "" ) ; return new ExpressionBuilder ( factory , source ) . method ( "" ) . toExpression ( ) ; } @ Override public Expression createBytesSize ( Expression bytes , Expression start , Expression length ) { Precondition . checkMustNotBeNull ( bytes , "" ) ; Precondition . checkMustNotBeNull ( start , "" ) ; Precondition . checkMustNotBeNull ( length , "" ) ; Type type = factory . newNamedType ( Models . toName ( factory , optionClass . getName ( ) ) ) ; return new TypeBuilder ( factory , type ) . method ( "" , bytes , start , length ) . toExpression ( ) ; } @ Override public Expression createBytesDiff ( Expression bytes1 , Expression start1 , Expression length1 , Expression bytes2 , Expression start2 , Expression length2 ) { Precondition . checkMustNotBeNull ( bytes1 , "" ) ; Precondition . checkMustNotBeNull ( start1 , "" ) ; Precondition . checkMustNotBeNull ( length1 , "" ) ; Precondition . checkMustNotBeNull ( bytes2 , "" ) ; Precondition . checkMustNotBeNull ( start2 , "" ) ; Precondition . checkMustNotBeNull ( length2 , "" ) ; Type type = factory . newNamedType ( Models . toName ( factory , optionClass . getName ( ) ) ) ; return new TypeBuilder ( factory , type ) . method ( "" , bytes1 , start1 , length1 , bytes2 , start2 , length2 ) . toExpression ( ) ; } @ Override public Expression createValueDiff ( Expression value1 , Expression value2 ) { Precondition . checkMustNotBeNull ( value1 , "" ) ; Precondition . checkMustNotBeNull ( value2 , "" ) ; return new ExpressionBuilder ( factory , value1 ) . method ( "" , value2 ) . toExpression ( ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + name . hashCode ( ) ; result = prime * result + optionClass . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ValueOptionProperty other = ( ValueOptionProperty ) obj ; if ( name . equals ( other . name ) == false ) { return false ; } if ( optionClass . equals ( other . optionClass ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , getName ( ) , getType ( ) ) ; } } package com . asakusafw . compiler . repository ; package com . asakusafw . compiler . repository ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . ServiceLoader ; import javax . lang . model . type . TypeMirror ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . operator . DataModelMirror ; import com . asakusafw . compiler . operator . DataModelMirrorRepository ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . utils . collections . Lists ; public class SpiDataModelMirrorRepository implements DataModelMirrorRepository { static final Logger LOG = LoggerFactory . getLogger ( SpiDataModelMirrorRepository . class ) ; private final List < DataModelMirrorRepository > repositories ; public SpiDataModelMirrorRepository ( ClassLoader serviceLoader ) { Precondition . checkMustNotBeNull ( serviceLoader , "" ) ; this . repositories = loadRepositories ( serviceLoader ) ; } @ Override public DataModelMirror load ( OperatorCompilingEnvironment environment , TypeMirror type ) { for ( DataModelMirrorRepository repo : repositories ) { DataModelMirror result = repo . load ( environment , type ) ; if ( result != null ) { return result ; } } return null ; } private List < DataModelMirrorRepository > loadRepositories ( ClassLoader serviceLoader ) { assert serviceLoader != null ; LOG . debug ( "" ) ; ServiceLoader < DataModelMirrorRepository > services = ServiceLoader . load ( DataModelMirrorRepository . class , serviceLoader ) ; List < DataModelMirrorRepository > results = Lists . create ( ) ; for ( DataModelMirrorRepository repo : services ) { results . add ( repo ) ; } Collections . sort ( results , new Comparator < DataModelMirrorRepository > ( ) { @ Override public int compare ( DataModelMirrorRepository o1 , DataModelMirrorRepository o2 ) { return o1 . getClass ( ) . getName ( ) . compareTo ( o2 . getClass ( ) . getName ( ) ) ; } } ) ; return results ; } } package com . asakusafw . compiler . repository ; import java . lang . reflect . Type ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . ServiceLoader ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClassRepository ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . utils . collections . Lists ; public class SpiDataClassRepository extends FlowCompilingEnvironment . Initialized implements DataClassRepository { static final Logger LOG = LoggerFactory . getLogger ( SpiDataClassRepository . class ) ; private List < DataClassRepository > repositories ; @ Override protected void doInitialize ( ) { LOG . info ( "" ) ; List < DataClassRepository > results = Lists . create ( ) ; ServiceLoader < DataClassRepository > services = ServiceLoader . load ( DataClassRepository . class , getEnvironment ( ) . getServiceClassLoader ( ) ) ; for ( DataClassRepository repo : services ) { assert repo . getClass ( ) . equals ( this . getClass ( ) ) == false ; repo . initialize ( getEnvironment ( ) ) ; LOG . debug ( "" , repo . getClass ( ) . getName ( ) ) ; results . add ( repo ) ; } Collections . sort ( results , new Comparator < DataClassRepository > ( ) { @ Override public int compare ( DataClassRepository o1 , DataClassRepository o2 ) { String name1 = o1 . getClass ( ) . getName ( ) ; String name2 = o2 . getClass ( ) . getName ( ) ; return name1 . compareTo ( name2 ) ; } } ) ; this . repositories = results ; } @ Override public DataClass load ( Type type ) { Precondition . checkMustNotBeNull ( type , "" ) ; LOG . debug ( "" , type ) ; for ( DataClassRepository repository : repositories ) { DataClass dataClass = repository . load ( type ) ; if ( dataClass != null ) { return dataClass ; } } return null ; } } package com . asakusafw . compiler . testing ; package com . asakusafw . compiler . testing ; import java . text . MessageFormat ; import com . asakusafw . vocabulary . external . ExporterDescription ; public abstract class TemporaryOutputDescription implements ExporterDescription { public abstract String getPathPrefix ( ) ; @ Override public String toString ( ) { return MessageFormat . format ( "" , getPathPrefix ( ) ) ; } } package com . asakusafw . compiler . testing ; import java . io . File ; import java . io . IOException ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . BatchCompiler ; import com . asakusafw . compiler . batch . BatchCompilerConfiguration ; import com . asakusafw . compiler . batch . BatchDriver ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . repository . SpiDataClassRepository ; import com . asakusafw . compiler . repository . SpiExternalIoDescriptionProcessorRepository ; import com . asakusafw . compiler . repository . SpiFlowElementProcessorRepository ; import com . asakusafw . compiler . repository . SpiFlowGraphRewriterRepository ; import com . asakusafw . compiler . repository . SpiWorkflowProcessorRepository ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; public final class DirectBatchCompiler { static final Logger LOG = LoggerFactory . getLogger ( DirectBatchCompiler . class ) ; public static BatchInfo compile ( Class < ? extends BatchDescription > batchClass , String basePackageName , Location clusterWorkingDirectory , File outputDirectory , File localWorkingDirectory , List < File > extraResources , ClassLoader serviceClassLoader , FlowCompilerOptions flowCompilerOptions ) throws IOException { Precondition . checkMustNotBeNull ( batchClass , "" ) ; Precondition . checkMustNotBeNull ( clusterWorkingDirectory , "" ) ; Precondition . checkMustNotBeNull ( outputDirectory , "" ) ; Precondition . checkMustNotBeNull ( localWorkingDirectory , "" ) ; Precondition . checkMustNotBeNull ( extraResources , "" ) ; Precondition . checkMustNotBeNull ( serviceClassLoader , "" ) ; Precondition . checkMustNotBeNull ( flowCompilerOptions , "" ) ; if ( localWorkingDirectory . exists ( ) ) { clean ( localWorkingDirectory ) ; } BatchDriver driver = BatchDriver . analyze ( batchClass ) ; if ( driver . hasError ( ) ) { throw new IOException ( driver . getDiagnostics ( ) . toString ( ) ) ; } String batchId = driver . getBatchClass ( ) . getConfig ( ) . name ( ) ; BatchCompilerConfiguration config = createConfig ( batchId , basePackageName , clusterWorkingDirectory , outputDirectory , localWorkingDirectory , extraResources , serviceClassLoader , flowCompilerOptions ) ; BatchCompiler compiler = new BatchCompiler ( config ) ; Workflow workflow = compiler . compile ( driver . getBatchClass ( ) . getDescription ( ) ) ; return toInfo ( workflow , outputDirectory ) ; } public static BatchInfo toInfo ( Workflow workflow , File outputDirectory ) { Precondition . checkMustNotBeNull ( workflow , "" ) ; Precondition . checkMustNotBeNull ( outputDirectory , "" ) ; List < JobflowInfo > jobflows = Lists . create ( ) ; for ( Workflow . Unit unit : Graphs . sortPostOrder ( workflow . getGraph ( ) ) ) { JobflowInfo jobflow = toJobflow ( unit , outputDirectory ) ; if ( jobflow != null ) { jobflows . add ( jobflow ) ; } } return new BatchInfo ( workflow , outputDirectory , jobflows ) ; } private static void clean ( File localWorkingDirectory ) { assert localWorkingDirectory != null ; LOG . info ( "" , localWorkingDirectory ) ; delete ( localWorkingDirectory ) ; } private static boolean delete ( File target ) { assert target != null ; boolean success = true ; if ( target . isDirectory ( ) ) { for ( File child : target . listFiles ( ) ) { success &= delete ( child ) ; } } success &= target . delete ( ) ; return success ; } public static BatchCompilerConfiguration createConfig ( String batchId , String basePackageName , Location clusterWorkingLocation , File outputDirectory , File localWorkingDirectory , List < File > extraResources , ClassLoader serviceClassLoader , FlowCompilerOptions flowCompilerOptions ) throws IOException { assert batchId != null ; assert basePackageName != null ; assert clusterWorkingLocation != null ; assert outputDirectory != null ; assert localWorkingDirectory != null ; assert extraResources != null ; assert serviceClassLoader != null ; assert flowCompilerOptions != null ; BatchCompilerConfiguration config = new BatchCompilerConfiguration ( ) ; config . setBatchId ( batchId ) ; config . setDataClasses ( new SpiDataClassRepository ( ) ) ; config . setExternals ( new SpiExternalIoDescriptionProcessorRepository ( ) ) ; config . setGraphRewriters ( new SpiFlowGraphRewriterRepository ( ) ) ; config . setFactory ( Models . getModelFactory ( ) ) ; config . setFlowElements ( new SpiFlowElementProcessorRepository ( ) ) ; config . setLinkingResources ( DirectFlowCompiler . createRepositories ( serviceClassLoader , extraResources ) ) ; config . setOutputDirectory ( outputDirectory ) ; config . setRootLocation ( clusterWorkingLocation ) ; config . setRootPackageName ( basePackageName ) ; config . setWorkflows ( new SpiWorkflowProcessorRepository ( ) ) ; config . setServiceClassLoader ( serviceClassLoader ) ; config . setWorkingDirectory ( localWorkingDirectory ) ; config . setFlowCompilerOptions ( flowCompilerOptions ) ; return config ; } private static JobflowInfo toJobflow ( Workflow . Unit unit , File outputDirectory ) { assert unit != null ; assert outputDirectory != null ; if ( ( unit . getDescription ( ) instanceof JobFlowWorkDescription ) == false ) { return null ; } JobflowModel model = ( JobflowModel ) unit . getProcessed ( ) ; String flowId = model . getFlowId ( ) ; return new JobflowInfo ( model , JobFlowWorkDescriptionProcessor . getPackageLocation ( outputDirectory , flowId ) , JobFlowWorkDescriptionProcessor . getSourceLocation ( outputDirectory , flowId ) , toStagePlan ( model ) ) ; } private static List < StageInfo > toStagePlan ( JobflowModel jobflow ) { assert jobflow != null ; List < StageInfo > results = Lists . create ( ) ; for ( CompiledStage compiled : jobflow . getCompiled ( ) . getPrologueStages ( ) ) { results . add ( toInfo ( compiled ) ) ; } Graph < JobflowModel . Stage > depenedencies = jobflow . getDependencyGraph ( ) ; for ( JobflowModel . Stage stage : Graphs . sortPostOrder ( depenedencies ) ) { results . add ( toInfo ( stage . getCompiled ( ) ) ) ; } for ( CompiledStage compiled : jobflow . getCompiled ( ) . getEpilogueStages ( ) ) { results . add ( toInfo ( compiled ) ) ; } return results ; } private static StageInfo toInfo ( CompiledStage stage ) { assert stage != null ; String className = stage . getQualifiedName ( ) . toNameString ( ) ; return new StageInfo ( className ) ; } private DirectBatchCompiler ( ) { return ; } } package com . asakusafw . compiler . testing ; import java . text . MessageFormat ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . Location ; public class DirectExporterDescription extends TemporaryOutputDescription { private final Class < ? > modelType ; private final String pathPrefix ; public DirectExporterDescription ( Class < ? > modelType , String pathPrefix ) { Precondition . checkMustNotBeNull ( modelType , "" ) ; Precondition . checkMustNotBeNull ( pathPrefix , "" ) ; if ( Location . fromPath ( pathPrefix , '' ) . isPrefix ( ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , pathPrefix , Location . WILDCARD_SUFFIX ) ) ; } this . modelType = modelType ; this . pathPrefix = pathPrefix ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getPathPrefix ( ) { return pathPrefix ; } } package com . asakusafw . compiler . testing ; import java . io . File ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Export ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Import ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class JobflowInfo { private final File packageFile ; private final File sourceArchive ; private final List < StageInfo > stages ; private final JobflowModel jobflow ; public JobflowInfo ( JobflowModel jobflow , File packageArchive , File sourceArchive , List < StageInfo > stages ) { Precondition . checkMustNotBeNull ( jobflow , "" ) ; Precondition . checkMustNotBeNull ( packageArchive , "" ) ; Precondition . checkMustNotBeNull ( sourceArchive , "" ) ; Precondition . checkMustNotBeNull ( stages , "" ) ; this . jobflow = jobflow ; this . packageFile = packageArchive ; this . sourceArchive = sourceArchive ; this . stages = stages ; } public ImporterDescription findImporter ( String inputId ) { if ( inputId == null ) { throw new IllegalArgumentException ( "" ) ; } for ( Import importer : jobflow . getImports ( ) ) { if ( inputId . equals ( importer . getId ( ) ) ) { return importer . getDescription ( ) . getImporterDescription ( ) ; } } return null ; } public Map < String , ImporterDescription > getImporterMap ( ) { Map < String , ImporterDescription > results = Maps . create ( ) ; for ( Import importer : jobflow . getImports ( ) ) { results . put ( importer . getId ( ) , importer . getDescription ( ) . getImporterDescription ( ) ) ; } return results ; } public ExporterDescription findExporter ( String outputId ) { if ( outputId == null ) { throw new IllegalArgumentException ( "" ) ; } for ( Export exporter : jobflow . getExports ( ) ) { if ( outputId . equals ( exporter . getId ( ) ) ) { return exporter . getDescription ( ) . getExporterDescription ( ) ; } } return null ; } public Map < String , ExporterDescription > getExporterMap ( ) { Map < String , ExporterDescription > results = Maps . create ( ) ; for ( Export exporter : jobflow . getExports ( ) ) { results . put ( exporter . getId ( ) , exporter . getDescription ( ) . getExporterDescription ( ) ) ; } return results ; } public List < ExternalIoCommandProvider > getCommandProviders ( ) { return jobflow . getCompiled ( ) . getCommandProviders ( ) ; } public JobflowModel getJobflow ( ) { return jobflow ; } public File getPackageFile ( ) { return packageFile ; } public File getSourceArchive ( ) { return sourceArchive ; } public List < StageInfo > getStages ( ) { return stages ; } } package com . asakusafw . compiler . testing ; import java . io . IOException ; import java . util . LinkedList ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . runtime . io . ModelInput ; public class MultipleModelInput < T > implements ModelInput < T > { private LinkedList < ModelInput < T > > inputs ; public MultipleModelInput ( List < ? extends ModelInput < T > > inputs ) { Precondition . checkMustNotBeNull ( inputs , "" ) ; this . inputs = new LinkedList < ModelInput < T > > ( inputs ) ; } @ Override public boolean readTo ( T model ) throws IOException { while ( inputs . isEmpty ( ) == false ) { ModelInput < T > input = inputs . getFirst ( ) ; if ( input . readTo ( model ) ) { return true ; } inputs . removeFirst ( ) . close ( ) ; } return false ; } @ Override public void close ( ) throws IOException { IOException first = null ; while ( inputs . isEmpty ( ) == false ) { ModelInput < T > input = inputs . removeFirst ( ) ; try { input . close ( ) ; } catch ( IOException e ) { if ( first == null ) { first = e ; } } } if ( first != null ) { throw first ; } } } package com . asakusafw . compiler . testing ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import java . util . regex . Pattern ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . mapreduce . parallel . ParallelSortClientEmitter ; import com . asakusafw . compiler . flow . mapreduce . parallel . ResolvedSlot ; import com . asakusafw . compiler . flow . mapreduce . parallel . Slot ; import com . asakusafw . compiler . flow . mapreduce . parallel . SlotResolver ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class TemporaryIoProcessor extends ExternalIoDescriptionProcessor { private static final Pattern VALID_OUTPUT_NAME = Pattern . compile ( "" ) ; private static final String MODULE_NAME = "" ; @ Override public Class < ? extends ImporterDescription > getImporterDescriptionType ( ) { return TemporaryInputDescription . class ; } @ Override public Class < ? extends ExporterDescription > getExporterDescriptionType ( ) { return TemporaryOutputDescription . class ; } @ Override public boolean validate ( List < InputDescription > inputs , List < OutputDescription > outputs ) { boolean valid = true ; for ( OutputDescription output : outputs ) { TemporaryOutputDescription desc = extract ( output ) ; String pathPrefix = desc . getPathPrefix ( ) ; if ( pathPrefix == null ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) ) ; } else { Location location = Location . fromPath ( pathPrefix , '' ) ; if ( location . isPrefix ( ) == false ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , pathPrefix ) ; } if ( location . getParent ( ) == null ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , pathPrefix ) ; } if ( VALID_OUTPUT_NAME . matcher ( location . getName ( ) ) . matches ( ) == false ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , pathPrefix ) ; } } } return valid ; } @ Override public SourceInfo getInputInfo ( InputDescription description ) { TemporaryInputDescription desc = extract ( description ) ; Set < Location > locations = Sets . create ( ) ; for ( String path : desc . getPaths ( ) ) { locations . add ( Location . fromPath ( path , '' ) ) ; } return new SourceInfo ( locations , TemporaryInputFormat . class ) ; } @ Override public List < CompiledStage > emitEpilogue ( IoContext context ) throws IOException { Set < String > saw = Sets . create ( ) ; List < CompiledStage > results = Lists . create ( ) ; for ( Map . Entry < Location , List < Slot > > entry : groupByOutputLocation ( context ) . entrySet ( ) ) { List < Slot > slots = entry . getValue ( ) ; List < ResolvedSlot > resolved = new SlotResolver ( getEnvironment ( ) ) . resolve ( slots ) ; if ( getEnvironment ( ) . hasError ( ) ) { return Collections . emptyList ( ) ; } ParallelSortClientEmitter emitter = new ParallelSortClientEmitter ( getEnvironment ( ) ) ; String moduleId = generateModuleName ( saw , entry . getKey ( ) ) ; CompiledStage stage = emitter . emit ( moduleId , resolved , entry . getKey ( ) ) ; results . add ( stage ) ; } return results ; } private String generateModuleName ( Set < String > saw , Location target ) { assert saw != null ; assert target != null ; String simpleSuffix = generateSuffix ( target ) ; String baseModuleId = MessageFormat . format ( "" , MODULE_NAME , simpleSuffix ) ; if ( saw . contains ( baseModuleId ) == false ) { saw . add ( baseModuleId ) ; return baseModuleId ; } int index = ; while ( true ) { String moduleIdCandidate = baseModuleId + index ; if ( saw . contains ( moduleIdCandidate ) == false ) { saw . add ( moduleIdCandidate ) ; return moduleIdCandidate ; } index ++ ; } } private String generateSuffix ( Location target ) { assert target != null ; String name = target . getName ( ) ; if ( name . isEmpty ( ) ) { return "" ; } StringBuilder buf = new StringBuilder ( ) ; if ( Character . isJavaIdentifierStart ( name . charAt ( ) ) == false ) { buf . append ( '' ) ; } for ( char c : name . toCharArray ( ) ) { if ( Character . isJavaIdentifierPart ( c ) ) { buf . append ( c ) ; } } assert buf . length ( ) >= ; return buf . toString ( ) ; } private Map < Location , List < Slot > > groupByOutputLocation ( IoContext context ) { assert context != null ; Map < Location , List < Slot > > results = new TreeMap < Location , List < Slot > > ( new Comparator < Location > ( ) { @ Override public int compare ( Location o1 , Location o2 ) { String parentPath1 = ( o1 . getParent ( ) == null ) ? "" : o1 . getParent ( ) . toPath ( '' ) ; String parentPath2 = ( o2 . getParent ( ) == null ) ? "" : o2 . getParent ( ) . toPath ( '' ) ; int parentDiff = parentPath1 . compareTo ( parentPath2 ) ; if ( parentDiff != ) { return ( parentDiff > ) ? + : - ; } return o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; } } ) ; for ( Output output : context . getOutputs ( ) ) { TemporaryOutputDescription desc = extract ( output . getDescription ( ) ) ; Location path = Location . fromPath ( desc . getPathPrefix ( ) , '' ) ; Location parent = path . getParent ( ) ; Maps . addToList ( results , parent , toSlot ( output , path . getName ( ) ) ) ; } return results ; } private Slot toSlot ( Output output , String name ) { assert output != null ; assert name != null ; return new Slot ( name , output . getDescription ( ) . getDataType ( ) , Collections . < String > emptyList ( ) , output . getSources ( ) , TemporaryOutputFormat . class ) ; } private TemporaryInputDescription extract ( InputDescription description ) { assert description != null ; ImporterDescription importer = description . getImporterDescription ( ) ; assert importer != null ; return ( TemporaryInputDescription ) importer ; } private TemporaryOutputDescription extract ( OutputDescription description ) { assert description != null ; ExporterDescription exporter = description . getExporterDescription ( ) ; assert exporter != null ; return ( TemporaryOutputDescription ) exporter ; } } package com . asakusafw . compiler . testing ; import java . io . File ; import java . util . List ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . common . Precondition ; public class BatchInfo { private final Workflow workflow ; private final List < JobflowInfo > jobflows ; private final File output ; public BatchInfo ( Workflow workflow , File output , List < JobflowInfo > jobflows ) { Precondition . checkMustNotBeNull ( workflow , "" ) ; Precondition . checkMustNotBeNull ( output , "" ) ; Precondition . checkMustNotBeNull ( jobflows , "" ) ; this . workflow = workflow ; this . output = output ; this . jobflows = jobflows ; } public JobflowInfo findJobflow ( String flowId ) { if ( flowId == null ) { throw new IllegalArgumentException ( "" ) ; } for ( JobflowInfo info : jobflows ) { if ( info . getJobflow ( ) . getFlowId ( ) . equals ( flowId ) ) { return info ; } } return null ; } public File getOutputDirectory ( ) { return output ; } public Workflow getWorkflow ( ) { return workflow ; } public List < JobflowInfo > getJobflows ( ) { return this . jobflows ; } } package com . asakusafw . compiler . testing ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . text . MessageFormat ; import java . util . Enumeration ; import java . util . List ; import java . util . Set ; import java . util . UUID ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . ResourceRepository ; import com . asakusafw . compiler . common . FileRepository ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . ZipRepository ; import com . asakusafw . compiler . flow . FlowCompiler ; import com . asakusafw . compiler . flow . FlowCompilerConfiguration ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . Packager ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . packager . FilePackager ; import com . asakusafw . compiler . repository . SpiDataClassRepository ; import com . asakusafw . compiler . repository . SpiExternalIoDescriptionProcessorRepository ; import com . asakusafw . compiler . repository . SpiFlowElementProcessorRepository ; import com . asakusafw . compiler . repository . SpiFlowGraphRewriterRepository ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public final class DirectFlowCompiler { static final Logger LOG = LoggerFactory . getLogger ( DirectFlowCompiler . class ) ; public static JobflowInfo compile ( FlowGraph flowGraph , String batchId , String flowId , String basePackageName , Location clusterWorkingDirectory , File localWorkingDirectory , List < File > extraResources , ClassLoader serviceClassLoader , FlowCompilerOptions flowCompilerOptions ) throws IOException { Precondition . checkMustNotBeNull ( flowGraph , "" ) ; Precondition . checkMustNotBeNull ( batchId , "" ) ; Precondition . checkMustNotBeNull ( flowId , "" ) ; Precondition . checkMustNotBeNull ( clusterWorkingDirectory , "" ) ; Precondition . checkMustNotBeNull ( localWorkingDirectory , "" ) ; Precondition . checkMustNotBeNull ( extraResources , "" ) ; Precondition . checkMustNotBeNull ( serviceClassLoader , "" ) ; Precondition . checkMustNotBeNull ( flowCompilerOptions , "" ) ; if ( localWorkingDirectory . exists ( ) ) { clean ( localWorkingDirectory ) ; } List < ResourceRepository > repositories = createRepositories ( serviceClassLoader , extraResources ) ; FlowCompilerConfiguration config = createConfig ( batchId , flowId , basePackageName , clusterWorkingDirectory , localWorkingDirectory , repositories , serviceClassLoader , flowCompilerOptions ) ; FlowCompiler compiler = new FlowCompiler ( config ) ; JobflowModel jobflow = compiler . compile ( flowGraph ) ; File jobflowSources = new File ( localWorkingDirectory , Naming . getJobflowSourceBundleName ( flowId ) ) ; File jobflowPackage = new File ( localWorkingDirectory , Naming . getJobflowClassPackageName ( flowId ) ) ; compiler . collectSources ( jobflowSources ) ; compiler . buildSources ( jobflowPackage ) ; return toInfo ( jobflow , jobflowSources , jobflowPackage ) ; } public static JobflowInfo toInfo ( JobflowModel jobflow , File sourceBundle , File packageFile ) { Precondition . checkMustNotBeNull ( jobflow , "" ) ; Precondition . checkMustNotBeNull ( sourceBundle , "" ) ; Precondition . checkMustNotBeNull ( packageFile , "" ) ; List < StageInfo > stages = Lists . create ( ) ; for ( CompiledStage compiled : jobflow . getCompiled ( ) . getPrologueStages ( ) ) { stages . add ( toInfo ( compiled ) ) ; } Graph < JobflowModel . Stage > depenedencies = jobflow . getDependencyGraph ( ) ; for ( JobflowModel . Stage stage : Graphs . sortPostOrder ( depenedencies ) ) { stages . add ( toInfo ( stage . getCompiled ( ) ) ) ; } for ( CompiledStage compiled : jobflow . getCompiled ( ) . getEpilogueStages ( ) ) { stages . add ( toInfo ( compiled ) ) ; } return new JobflowInfo ( jobflow , packageFile , sourceBundle , stages ) ; } private static void clean ( File localWorkingDirectory ) { assert localWorkingDirectory != null ; LOG . info ( "" , localWorkingDirectory ) ; delete ( localWorkingDirectory ) ; } private static boolean delete ( File target ) { assert target != null ; boolean success = true ; if ( target . isDirectory ( ) ) { for ( File child : target . listFiles ( ) ) { success &= delete ( child ) ; } } success &= target . delete ( ) ; return success ; } static List < ResourceRepository > createRepositories ( ClassLoader classLoader , List < File > extraResources ) throws IOException { assert classLoader != null ; assert extraResources != null ; List < File > targets = Lists . create ( ) ; targets . addAll ( collectLibraryPathsFromMarker ( classLoader ) ) ; targets . addAll ( extraResources ) ; List < ResourceRepository > results = Lists . create ( ) ; Set < File > saw = Sets . create ( ) ; for ( File file : targets ) { LOG . debug ( "" , file ) ; File canonical = file . getAbsoluteFile ( ) . getCanonicalFile ( ) ; if ( saw . contains ( canonical ) ) { LOG . debug ( "" , file ) ; continue ; } saw . add ( file ) ; if ( file . isDirectory ( ) ) { results . add ( new FileRepository ( file ) ) ; } else if ( file . isFile ( ) && file . getName ( ) . endsWith ( "" ) ) { results . add ( new ZipRepository ( file ) ) ; } else if ( file . isFile ( ) && file . getName ( ) . endsWith ( "" ) ) { results . add ( new ZipRepository ( file ) ) ; } else { LOG . warn ( "" , file ) ; } } return results ; } private static FlowCompilerConfiguration createConfig ( String batchId , String flowId , String basePackageName , Location baseLocation , File workingDirectory , List < ? extends ResourceRepository > repositories , ClassLoader serviceClassLoader , FlowCompilerOptions flowCompilerOptions ) { assert batchId != null ; assert flowId != null ; assert basePackageName != null ; assert baseLocation != null ; assert workingDirectory != null ; assert repositories != null ; assert serviceClassLoader != null ; assert flowCompilerOptions != null ; FlowCompilerConfiguration config = new FlowCompilerConfiguration ( ) ; ModelFactory factory = Models . getModelFactory ( ) ; config . setBatchId ( batchId ) ; config . setFlowId ( flowId ) ; config . setFactory ( factory ) ; config . setProcessors ( new SpiFlowElementProcessorRepository ( ) ) ; config . setExternals ( new SpiExternalIoDescriptionProcessorRepository ( ) ) ; config . setDataClasses ( new SpiDataClassRepository ( ) ) ; config . setGraphRewriters ( new SpiFlowGraphRewriterRepository ( ) ) ; config . setPackager ( new FilePackager ( workingDirectory , repositories ) ) ; config . setRootPackageName ( basePackageName ) ; config . setRootLocation ( baseLocation ) ; config . setServiceClassLoader ( serviceClassLoader ) ; config . setOptions ( flowCompilerOptions ) ; config . setBuildId ( UUID . randomUUID ( ) . toString ( ) ) ; return config ; } private static StageInfo toInfo ( CompiledStage stage ) { assert stage != null ; String className = stage . getQualifiedName ( ) . toNameString ( ) ; return new StageInfo ( className ) ; } public static File toLibraryPath ( Class < ? > memberClass ) { Precondition . checkMustNotBeNull ( memberClass , "" ) ; return findLibraryPathFromClass ( memberClass ) ; } private static List < File > collectLibraryPathsFromMarker ( ClassLoader classLoader ) throws IOException { assert classLoader != null ; String path = Packager . FRAGMENT_MARKER_PATH . toPath ( '' ) ; Enumeration < URL > resources = classLoader . getResources ( path ) ; List < File > results = Lists . create ( ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; LOG . debug ( "" , url ) ; File library = findLibraryFromUrl ( url , path ) ; if ( library != null ) { LOG . info ( MessageFormat . format ( "" , library ) ) ; results . add ( library ) ; } } return results ; } private static File findLibraryPathFromClass ( Class < ? > aClass ) { assert aClass != null ; String className = aClass . getName ( ) ; int start = className . lastIndexOf ( '' ) + ; String name = className . substring ( start ) ; URL resource = aClass . getResource ( name + "" ) ; if ( resource == null ) { LOG . warn ( "" , aClass . getName ( ) ) ; return null ; } String resourcePath = className . replace ( '' , '' ) + "" ; return findLibraryFromUrl ( resource , resourcePath ) ; } private static File findLibraryFromUrl ( URL resource , String resourcePath ) { assert resource != null ; assert resourcePath != null ; String protocol = resource . getProtocol ( ) ; if ( protocol . equals ( "" ) ) { File file = new File ( resource . getPath ( ) ) ; return toClassPathRoot ( file , resourcePath ) ; } if ( protocol . equals ( "" ) ) { String path = resource . getPath ( ) ; return toClassPathRoot ( path , resourcePath ) ; } else { LOG . warn ( "" , resource , resourcePath ) ; return null ; } } private static File toClassPathRoot ( File resourceFile , String resourcePath ) { assert resourceFile != null ; assert resourcePath != null ; assert resourceFile . isFile ( ) ; File current = resourceFile . getParentFile ( ) ; assert current != null && current . isDirectory ( ) : resourceFile ; for ( int start = resourcePath . indexOf ( '' ) ; start >= ; start = resourcePath . indexOf ( '' , start + ) ) { current = current . getParentFile ( ) ; if ( current == null || current . isDirectory ( ) == false ) { LOG . warn ( "" , resourceFile , resourcePath ) ; return null ; } } return current ; } private static File toClassPathRoot ( String uriQualifiedPath , String resourceName ) { assert uriQualifiedPath != null ; assert resourceName != null ; int entry = uriQualifiedPath . lastIndexOf ( '' ) ; String qualifier ; if ( entry >= ) { qualifier = uriQualifiedPath . substring ( , entry ) ; } else { qualifier = uriQualifiedPath ; } URI archive ; try { archive = new URI ( qualifier ) ; } catch ( URISyntaxException e ) { LOG . warn ( MessageFormat . format ( "" , qualifier , resourceName ) , e ) ; throw new UnsupportedOperationException ( qualifier , e ) ; } if ( archive . getScheme ( ) . equals ( "" ) == false ) { LOG . warn ( "" , archive , resourceName ) ; return null ; } File file = new File ( archive ) ; assert file . isFile ( ) : file ; return file ; } private DirectFlowCompiler ( ) { return ; } } package com . asakusafw . compiler . testing ; import com . asakusafw . compiler . common . Precondition ; public class StageInfo { private String className ; public StageInfo ( String className ) { Precondition . checkMustNotBeNull ( className , "" ) ; this . className = className ; } public String getClassName ( ) { return className ; } } package com . asakusafw . compiler . testing ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Sets ; public class DirectImporterDescription extends TemporaryInputDescription { private final Class < ? > modelType ; private final Set < String > paths ; private DataSize dataSize ; public DirectImporterDescription ( Class < ? > modelType , Set < String > paths ) { Precondition . checkMustNotBeNull ( modelType , "" ) ; Precondition . checkMustNotBeNull ( paths , "" ) ; if ( paths . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } this . modelType = modelType ; this . paths = Sets . freeze ( paths ) ; } public DirectImporterDescription ( Class < ? > modelType , String path , String ... pathRest ) { Precondition . checkMustNotBeNull ( modelType , "" ) ; Precondition . checkMustNotBeNull ( path , "" ) ; Precondition . checkMustNotBeNull ( pathRest , "" ) ; this . modelType = modelType ; Set < String > pathSet = Sets . create ( ) ; pathSet . add ( path ) ; Collections . addAll ( pathSet , pathRest ) ; this . paths = Collections . unmodifiableSet ( pathSet ) ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public Set < String > getPaths ( ) { return paths ; } public void setDataSize ( DataSize dataSize ) { this . dataSize = dataSize ; } @ Override public DataSize getDataSize ( ) { if ( dataSize == null ) { return DataSize . UNKNOWN ; } return dataSize ; } } package com . asakusafw . compiler . testing ; import java . text . MessageFormat ; import java . util . Set ; import com . asakusafw . vocabulary . external . ImporterDescription ; public abstract class TemporaryInputDescription implements ImporterDescription { @ Override public DataSize getDataSize ( ) { return DataSize . UNKNOWN ; } public abstract Set < String > getPaths ( ) ; @ Override public String toString ( ) { return MessageFormat . format ( "" , getPaths ( ) ) ; } } package com . asakusafw . compiler . flow . model ; import java . lang . ref . Reference ; import java . lang . ref . SoftReference ; import java . lang . reflect . Type ; import java . util . HashMap ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClassRepository ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . utils . collections . Maps ; public class DataModelClassRepository extends FlowCompilingEnvironment . Initialized implements DataClassRepository { private static final String KIND = "" ; static final Logger LOG = LoggerFactory . getLogger ( DataModelClassRepository . class ) ; private Reference < Map < Type , DataClass > > cache ; @ Override protected void doInitialize ( ) { cache = new SoftReference < Map < Type , DataClass > > ( new HashMap < Type , DataClass > ( ) ) ; } @ Override public DataClass load ( Type type ) { Precondition . checkMustNotBeNull ( type , "" ) ; Map < Type , DataClass > cacheMap = cache . get ( ) ; if ( cacheMap != null ) { if ( cacheMap . containsKey ( type ) ) { return cacheMap . get ( type ) ; } } if ( ( type instanceof Class < ? > ) == false ) { return null ; } Class < ? > aClass = ( Class < ? > ) type ; if ( isSuitable ( aClass ) == false ) { return null ; } DataModelClass created = DataModelClass . create ( getEnvironment ( ) , aClass ) ; if ( cacheMap == null ) { cacheMap = Maps . create ( ) ; cache = new SoftReference < Map < Type , DataClass > > ( cacheMap ) ; } cacheMap . put ( type , created ) ; return created ; } private boolean isSuitable ( Class < ? > aClass ) { assert aClass != null ; if ( DataModel . class . isAssignableFrom ( aClass ) == false ) { LOG . debug ( "" , aClass . getName ( ) , DataModel . class . getName ( ) ) ; return false ; } DataModelKind kind = aClass . getAnnotation ( DataModelKind . class ) ; if ( kind == null ) { LOG . debug ( "" , aClass . getName ( ) , DataModelKind . class . getName ( ) ) ; return false ; } if ( kind . value ( ) . equals ( KIND ) == false ) { LOG . debug ( "" , new Object [ ] { aClass . getName ( ) , DataModelKind . class . getName ( ) , KIND , } ) ; return false ; } return true ; } } package com . asakusafw . compiler . flow . model ; import java . lang . reflect . Method ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . repository . ValueOptionProperty ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class DataModelClass implements DataClass { private final ModelFactory factory ; private final Class < ? > type ; private final Map < String , DataClass . Property > properties ; public static DataModelClass create ( FlowCompilingEnvironment environment , Class < ? > type ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( type , "" ) ; Map < String , Property > properties = collectProperties ( environment , type ) ; return new DataModelClass ( environment . getModelFactory ( ) , type , properties ) ; } private static Map < String , DataClass . Property > collectProperties ( FlowCompilingEnvironment environment , Class < ? > aClass ) { assert environment != null ; assert aClass != null ; Map < String , Property > results = Maps . create ( ) ; for ( Method method : aClass . getMethods ( ) ) { String propertyName = toPropertyName ( method ) ; Class < ? > propertyType = method . getReturnType ( ) ; if ( propertyType == ValueOption . class || ValueOption . class . isAssignableFrom ( propertyType ) == false ) { continue ; } @ SuppressWarnings ( "" ) Class < ? extends ValueOption < ? > > valueOptionType = ( Class < ? extends ValueOption < ? > > ) propertyType ; results . put ( propertyName , new ValueOptionProperty ( environment . getModelFactory ( ) , propertyName , valueOptionType ) ) ; } return results ; } private static String toPropertyName ( Method method ) { assert method != null ; JavaName name = JavaName . of ( method . getName ( ) ) ; List < String > segments = name . getSegments ( ) ; if ( segments . size ( ) <= ) { return null ; } if ( segments . get ( ) . equals ( "" ) == false || segments . get ( segments . size ( ) - ) . equals ( "" ) == false ) { return null ; } name . removeLast ( ) ; name . removeFirst ( ) ; return name . toMemberName ( ) ; } protected DataModelClass ( ModelFactory factory , Class < ? > type , Map < String , Property > properties ) { Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( type , "" ) ; Precondition . checkMustNotBeNull ( properties , "" ) ; this . factory = factory ; this . type = type ; this . properties = properties ; } @ Override public java . lang . reflect . Type getType ( ) { return type ; } @ Override public Statement reset ( Expression object ) { Precondition . checkMustNotBeNull ( object , "" ) ; return new ExpressionBuilder ( factory , object ) . method ( "" ) . toStatement ( ) ; } @ Override public Expression createNewInstance ( Type target ) { Precondition . checkMustNotBeNull ( target , "" ) ; return new TypeBuilder ( factory , target ) . newObject ( ) . toExpression ( ) ; } @ Override public Statement assign ( Expression target , Expression source ) { Precondition . checkMustNotBeNull ( target , "" ) ; Precondition . checkMustNotBeNull ( source , "" ) ; return new ExpressionBuilder ( factory , target ) . method ( "" , source ) . toStatement ( ) ; } @ Override public Statement createWriter ( Expression object , Expression dataOutput ) { Precondition . checkMustNotBeNull ( object , "" ) ; Precondition . checkMustNotBeNull ( dataOutput , "" ) ; return new ExpressionBuilder ( factory , object ) . method ( "" , dataOutput ) . toStatement ( ) ; } @ Override public Statement createReader ( Expression object , Expression dataInput ) { Precondition . checkMustNotBeNull ( object , "" ) ; Precondition . checkMustNotBeNull ( dataInput , "" ) ; return new ExpressionBuilder ( factory , object ) . method ( "" , dataInput ) . toStatement ( ) ; } @ Override public Collection < ? extends Property > getProperties ( ) { return Collections . unmodifiableCollection ( properties . values ( ) ) ; } @ Override public Property findProperty ( String propertyName ) { Precondition . checkMustNotBeNull ( propertyName , "" ) ; if ( propertyName . trim ( ) . isEmpty ( ) ) { return null ; } String normalName = JavaName . of ( propertyName ) . toMemberName ( ) ; return properties . get ( normalName ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + type . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DataModelClass other = ( DataModelClass ) obj ; if ( type . equals ( other . type ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , type . getName ( ) ) ; } } package com . asakusafw . compiler . flow . model ; package com . asakusafw . compiler . flow ; import java . io . IOException ; import java . io . OutputStream ; import java . io . PrintWriter ; import java . util . jar . JarFile ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Name ; public interface Packager extends FlowCompilingEnvironment . Initializable { Location MANIFEST_FILE = Location . fromPath ( JarFile . MANIFEST_NAME , '' ) ; Location PACKAGE_META_INFO = MANIFEST_FILE . getParent ( ) ; Location FRAMEWORK_INFO = PACKAGE_META_INFO . append ( "" ) ; Location FRAGMENT_MARKER_PATH = FRAMEWORK_INFO . append ( "" ) ; PrintWriter openWriter ( CompilationUnit source ) throws IOException ; OutputStream openStream ( Name packageNameOrNull , String relativePath ) throws IOException ; void build ( OutputStream output ) throws IOException ; void packageSources ( OutputStream output ) throws IOException ; } package com . asakusafw . compiler . flow ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . apache . hadoop . mapreduce . InputFormat ; import org . apache . hadoop . mapreduce . OutputFormat ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public abstract class ExternalIoDescriptionProcessor extends FlowCompilingEnvironment . Initialized { public abstract Class < ? extends ImporterDescription > getImporterDescriptionType ( ) ; public abstract Class < ? extends ExporterDescription > getExporterDescriptionType ( ) ; public abstract boolean validate ( List < InputDescription > inputs , List < OutputDescription > outputs ) ; public abstract SourceInfo getInputInfo ( InputDescription description ) ; public List < CompiledStage > emitPrologue ( IoContext context ) throws IOException { return Collections . emptyList ( ) ; } public List < CompiledStage > emitEpilogue ( IoContext context ) throws IOException { return Collections . emptyList ( ) ; } public void emitPackage ( IoContext context ) throws IOException { return ; } public ExternalIoCommandProvider createCommandProvider ( IoContext context ) { Precondition . checkMustNotBeNull ( context , "" ) ; return new ExternalIoCommandProvider ( ) ; } public static class IoContext { private final List < Input > inputs ; private final List < Output > outputs ; public IoContext ( List < Input > inputs , List < Output > outputs ) { this . inputs = inputs ; this . outputs = outputs ; } public List < Input > getInputs ( ) { return inputs ; } public List < Output > getOutputs ( ) { return outputs ; } } public static class Output { private final OutputDescription description ; private final List < SourceInfo > sources ; public Output ( OutputDescription description , List < SourceInfo > sources ) { Precondition . checkMustNotBeNull ( description , "" ) ; Precondition . checkMustNotBeNull ( sources , "" ) ; this . description = description ; this . sources = sources ; } public OutputDescription getDescription ( ) { return description ; } public List < SourceInfo > getSources ( ) { return sources ; } } public static class Input { private final InputDescription description ; private final Class < ? extends OutputFormat < ? , ? > > format ; @ SuppressWarnings ( { "" , "" } ) public Input ( InputDescription description , Class < ? extends OutputFormat > format ) { this . description = description ; this . format = ( Class < ? extends OutputFormat < ? , ? > > ) format ; } public InputDescription getDescription ( ) { return description ; } public Class < ? extends OutputFormat < ? , ? > > getFormat ( ) { return format ; } } public static class SourceInfo { private final Set < Location > locations ; private final Class < ? extends InputFormat < ? , ? > > format ; private final Map < String , String > attributes ; @ SuppressWarnings ( { "" } ) public SourceInfo ( Set < Location > locations , Class < ? extends InputFormat > format ) { this ( locations , format , Collections . < String , String > emptyMap ( ) ) ; } @ SuppressWarnings ( { "" , "" } ) public SourceInfo ( Set < Location > locations , Class < ? extends InputFormat > format , Map < String , String > attributes ) { Precondition . checkMustNotBeNull ( locations , "" ) ; Precondition . checkMustNotBeNull ( format , "" ) ; Precondition . checkMustNotBeNull ( attributes , "" ) ; this . locations = locations ; this . format = ( Class < ? extends InputFormat < ? , ? > > ) format ; this . attributes = Maps . freeze ( attributes ) ; } public Set < Location > getLocations ( ) { return locations ; } public Class < ? extends InputFormat < ? , ? > > getFormat ( ) { return format ; } public Map < String , String > getAttributes ( ) { return attributes ; } } public interface Repository extends FlowCompilingEnvironment . Initializable { ExternalIoDescriptionProcessor findProcessor ( InputDescription description ) ; ExternalIoDescriptionProcessor findProcessor ( OutputDescription description ) ; } } package com . asakusafw . compiler . flow ; import java . io . IOException ; import java . io . OutputStream ; import java . io . PrintWriter ; import java . text . MessageFormat ; import java . util . concurrent . atomic . AtomicBoolean ; import java . util . concurrent . atomic . AtomicInteger ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . util . Models ; public class FlowCompilingEnvironment { static final Logger LOG = LoggerFactory . getLogger ( FlowCompilingEnvironment . class ) ; private final FlowCompilerConfiguration config ; private final AtomicBoolean initialized = new AtomicBoolean ( false ) ; private final AtomicInteger counter = new AtomicInteger ( ) ; private String firstError ; public FlowCompilingEnvironment ( FlowCompilerConfiguration config ) { Precondition . checkMustNotBeNull ( config , "" ) ; this . config = config ; clearError ( ) ; } public FlowCompilingEnvironment bless ( ) { if ( initialized . compareAndSet ( false , true ) == false ) { return this ; } config . getDataClasses ( ) . initialize ( this ) ; config . getExternals ( ) . initialize ( this ) ; config . getPackager ( ) . initialize ( this ) ; config . getProcessors ( ) . initialize ( this ) ; config . getGraphRewriters ( ) . initialize ( this ) ; clearError ( ) ; return this ; } public String getErrorMessage ( ) { return firstError ; } public final boolean hasError ( ) { return firstError != null ; } public final void clearError ( ) { firstError = null ; } public ModelFactory getModelFactory ( ) { return config . getFactory ( ) ; } public FlowElementProcessor . Repository getProcessors ( ) { return config . getProcessors ( ) ; } public DataClassRepository getDataClasses ( ) { return config . getDataClasses ( ) ; } public ExternalIoDescriptionProcessor . Repository getExternals ( ) { return config . getExternals ( ) ; } public FlowGraphRewriter . Repository getGraphRewriters ( ) { return config . getGraphRewriters ( ) ; } public String getBatchId ( ) { return config . getBatchId ( ) ; } public String getFlowId ( ) { return config . getFlowId ( ) ; } public String getTargetId ( ) { return MessageFormat . format ( "" , getBatchId ( ) , getFlowId ( ) ) ; } public Name getTargetPackageName ( ) { Name root = Models . toName ( getModelFactory ( ) , config . getRootPackageName ( ) ) ; Name batch = Models . toName ( getModelFactory ( ) , normalize ( getBatchId ( ) ) ) ; Name flow = Models . toName ( getModelFactory ( ) , normalize ( getFlowId ( ) ) ) ; return Models . append ( getModelFactory ( ) , root , batch , flow ) ; } private String normalize ( String name ) { assert name != null ; StringBuilder buf = new StringBuilder ( ) ; String [ ] segments = name . split ( Pattern . quote ( "" ) ) ; buf . append ( memberName ( segments [ ] ) ) ; for ( int i = ; i < segments . length ; i ++ ) { buf . append ( '' ) ; buf . append ( memberName ( segments [ i ] ) ) ; } return buf . toString ( ) ; } private String memberName ( String string ) { assert string != null ; if ( string . isEmpty ( ) ) { return "" ; } return JavaName . of ( string ) . toMemberName ( ) ; } public Name getStagePackageName ( int stageNumber ) { if ( stageNumber < ) { throw new IllegalArgumentException ( "" ) ; } return Models . append ( config . getFactory ( ) , getTargetPackageName ( ) , String . format ( "" , stageNumber ) ) ; } public Name getResourcePackage ( String resourceKind ) { Precondition . checkMustNotBeNull ( resourceKind , "" ) ; return Models . append ( getModelFactory ( ) , getTargetPackageName ( ) , normalize ( resourceKind ) ) ; } public SimpleName createUniqueName ( String prefix ) { Precondition . checkMustNotBeNull ( prefix , "" ) ; return getModelFactory ( ) . newSimpleName ( prefix + counter . incrementAndGet ( ) ) ; } public Name getProloguePackageName ( String moduleId ) { Precondition . checkMustNotBeNull ( moduleId , "" ) ; return Models . append ( config . getFactory ( ) , getTargetPackageName ( ) , MessageFormat . format ( "" , memberName ( moduleId ) ) ) ; } public Name getEpiloguePackageName ( String moduleId ) { Precondition . checkMustNotBeNull ( moduleId , "" ) ; return Models . append ( config . getFactory ( ) , getTargetPackageName ( ) , MessageFormat . format ( "" , memberName ( moduleId ) ) ) ; } public Location getTargetLocation ( ) { return config . getRootLocation ( ) . append ( getBatchId ( ) ) . append ( getFlowId ( ) ) ; } public Location getStageLocation ( int stageNumber ) { if ( stageNumber < ) { throw new IllegalArgumentException ( "" ) ; } String stageSuffix = String . format ( "" , stageNumber ) ; return getTargetLocation ( ) . append ( stageSuffix ) ; } public Location getPrologueLocation ( String moduleId ) { Precondition . checkMustNotBeNull ( moduleId , "" ) ; return getTargetLocation ( ) . append ( "" ) . append ( moduleId ) ; } public Location getEpilogueLocation ( String moduleId ) { Precondition . checkMustNotBeNull ( moduleId , "" ) ; return getTargetLocation ( ) . append ( "" ) . append ( moduleId ) ; } public void emit ( CompilationUnit source ) throws IOException { Precondition . checkMustNotBeNull ( source , "" ) ; PrintWriter writer = config . getPackager ( ) . openWriter ( source ) ; try { Models . emit ( source , writer ) ; } finally { writer . close ( ) ; } } public OutputStream openResource ( Name packageNameOrNull , String subPath ) throws IOException { Precondition . checkMustNotBeNull ( subPath , "" ) ; return config . getPackager ( ) . openStream ( packageNameOrNull , subPath ) ; } public ClassLoader getServiceClassLoader ( ) { return config . getServiceClassLoader ( ) ; } public FlowCompilerOptions getOptions ( ) { return config . getOptions ( ) ; } public String getBuildId ( ) { return config . getBuildId ( ) ; } public void error ( String format , Object ... args ) { Precondition . checkMustNotBeNull ( format , "" ) ; Precondition . checkMustNotBeNull ( args , "" ) ; String text = format ( format , args ) ; LOG . error ( text ) ; if ( firstError == null ) { firstError = text ; } } private String format ( String format , Object [ ] args ) { assert format != null ; assert args != null ; if ( args . length == ) { return format ; } return MessageFormat . format ( format , args ) ; } public interface Initializable { void initialize ( FlowCompilingEnvironment environment ) ; } public abstract static class Initialized implements Initializable { private FlowCompilingEnvironment environment ; @ Override public final void initialize ( FlowCompilingEnvironment env ) { Precondition . checkMustNotBeNull ( env , "" ) ; this . environment = env ; doInitialize ( ) ; } protected void doInitialize ( ) { return ; } protected FlowCompilingEnvironment getEnvironment ( ) { return environment ; } } } package com . asakusafw . compiler . flow ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; public class FlowCompilerConfiguration { private ModelFactory factory ; private Packager packager ; private FlowElementProcessor . Repository processors ; private DataClassRepository dataClasses ; private ExternalIoDescriptionProcessor . Repository externals ; private FlowGraphRewriter . Repository graphRewriters ; private String batchId ; private String flowId ; private String rootPackageName ; private Location rootLocation ; private ClassLoader serviceClassLoader ; private FlowCompilerOptions options ; private String buildId ; public ModelFactory getFactory ( ) { return factory ; } public void setFactory ( ModelFactory factory ) { this . factory = factory ; } public Packager getPackager ( ) { return packager ; } public void setPackager ( Packager packager ) { this . packager = packager ; } public FlowElementProcessor . Repository getProcessors ( ) { return processors ; } public void setProcessors ( FlowElementProcessor . Repository processors ) { this . processors = processors ; } public DataClassRepository getDataClasses ( ) { return dataClasses ; } public void setDataClasses ( DataClassRepository dataClasses ) { this . dataClasses = dataClasses ; } public ExternalIoDescriptionProcessor . Repository getExternals ( ) { return externals ; } public void setExternals ( ExternalIoDescriptionProcessor . Repository externals ) { this . externals = externals ; } public FlowGraphRewriter . Repository getGraphRewriters ( ) { return graphRewriters ; } public void setGraphRewriters ( FlowGraphRewriter . Repository graphRewriters ) { this . graphRewriters = graphRewriters ; } public String getBatchId ( ) { return batchId ; } public void setBatchId ( String batchId ) { this . batchId = batchId ; } public String getFlowId ( ) { return flowId ; } public void setFlowId ( String flowId ) { this . flowId = flowId ; } public String getRootPackageName ( ) { return rootPackageName ; } public void setRootPackageName ( String rootPackageName ) { this . rootPackageName = rootPackageName ; } public Location getRootLocation ( ) { return rootLocation ; } public void setRootLocation ( Location rootLocation ) { this . rootLocation = rootLocation ; } public ClassLoader getServiceClassLoader ( ) { return serviceClassLoader ; } public void setServiceClassLoader ( ClassLoader serviceClassLoader ) { this . serviceClassLoader = serviceClassLoader ; } public FlowCompilerOptions getOptions ( ) { return options ; } public void setOptions ( FlowCompilerOptions options ) { this . options = options ; } public String getBuildId ( ) { return buildId ; } public void setBuildId ( String buildId ) { this . buildId = buildId ; } } package com . asakusafw . compiler . flow . logging ; package com . asakusafw . compiler . flow . logging ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowGraphRewriter ; import com . asakusafw . compiler . flow . plan . FlowGraphUtil ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Logging ; import com . asakusafw . vocabulary . operator . Logging . Level ; public class LoggingFilter extends FlowCompilingEnvironment . Initialized implements FlowGraphRewriter { static final Logger LOG = LoggerFactory . getLogger ( LoggingFilter . class ) ; @ Override public boolean rewrite ( FlowGraph graph ) throws RewriteException { if ( getEnvironment ( ) . getOptions ( ) . isEnableDebugLogging ( ) ) { LOG . info ( "" ) ; return false ; } LOG . info ( "" ) ; return rewriteGraph ( graph ) ; } private boolean rewriteGraph ( FlowGraph graph ) { boolean modified = false ; for ( FlowElement element : FlowGraphUtil . collectElements ( graph ) ) { if ( element . getDescription ( ) . getKind ( ) == FlowElementKind . FLOW_COMPONENT ) { FlowPartDescription desc = ( FlowPartDescription ) element . getDescription ( ) ; rewriteGraph ( desc . getFlowGraph ( ) ) ; } else if ( isDebugLogging ( element ) ) { LOG . debug ( "" , element ) ; FlowGraphUtil . skip ( element ) ; } } return modified ; } private boolean isDebugLogging ( FlowElement element ) { assert element != null ; if ( element . getDescription ( ) . getKind ( ) != FlowElementKind . OPERATOR ) { return false ; } OperatorDescription desc = ( OperatorDescription ) element . getDescription ( ) ; if ( desc . getDeclaration ( ) . getAnnotationType ( ) != Logging . class ) { return false ; } if ( desc . getAttribute ( Logging . Level . class ) != Level . DEBUG ) { return false ; } return true ; } @ Override public Name resolve ( FlowResourceDescription resource ) throws RewriteException { return null ; } } package com . asakusafw . compiler . flow ; public interface Compilable < T > { boolean isCompiled ( ) ; T getCompiled ( ) ; void setCompiled ( T object ) ; class Trait < T > implements Compilable < T > { private T compiled ; @ Override public boolean isCompiled ( ) { return compiled != null ; } @ Override public T getCompiled ( ) { if ( isCompiled ( ) == false ) { throw new IllegalStateException ( ) ; } return compiled ; } @ Override public void setCompiled ( T object ) { if ( isCompiled ( ) ) { throw new IllegalStateException ( ) ; } this . compiled = object ; } } } package com . asakusafw . compiler . flow ; import java . lang . annotation . Annotation ; import java . lang . reflect . Constructor ; import java . lang . reflect . Modifier ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . runtime . util . TypeUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public final class JobFlowDriver { static final Logger LOG = LoggerFactory . getLogger ( JobFlowDriver . class ) ; private Class < ? extends FlowDescription > description ; private JobFlowClass jobFlowClass ; private List < String > diagnostics ; private JobFlowDriver ( Class < ? extends FlowDescription > description ) { assert description != null ; this . description = description ; this . diagnostics = Lists . create ( ) ; } public static JobFlowDriver analyze ( Class < ? extends FlowDescription > description ) { Precondition . checkMustNotBeNull ( description , "" ) ; JobFlowDriver analyzer = new JobFlowDriver ( description ) ; analyzer . analyze ( ) ; return analyzer ; } public JobFlowClass getJobFlowClass ( ) { return jobFlowClass ; } public Class < ? extends FlowDescription > getDescription ( ) { return description ; } public List < String > getDiagnostics ( ) { return diagnostics ; } private void analyze ( ) { JobFlow config = findConfig ( ) ; Constructor < ? extends FlowDescription > ctor = findConstructor ( ) ; if ( ctor == null ) { return ; } FlowDescriptionDriver driver = parseParameters ( ctor ) ; if ( hasError ( ) ) { return ; } FlowDescription instance = newInstance ( ctor , driver . getPorts ( ) ) ; if ( hasError ( ) ) { return ; } try { FlowGraph graph = driver . createFlowGraph ( instance ) ; this . jobFlowClass = new JobFlowClass ( config , graph ) ; } catch ( Exception e ) { error ( e , "" , description . getName ( ) , e . toString ( ) ) ; } } private FlowDescription newInstance ( Constructor < ? extends FlowDescription > ctor , List < ? > ports ) { assert ctor != null ; assert ports != null ; try { return ctor . newInstance ( ports . toArray ( ) ) ; } catch ( Exception e ) { error ( e , "" , description . getName ( ) , e . toString ( ) ) ; return null ; } } private JobFlow findConfig ( ) { if ( description . getEnclosingClass ( ) != null ) { error ( null , "" ) ; } if ( Modifier . isPublic ( description . getModifiers ( ) ) == false ) { error ( null , "" ) ; } if ( Modifier . isAbstract ( description . getModifiers ( ) ) ) { error ( null , "" ) ; } JobFlow conf = description . getAnnotation ( JobFlow . class ) ; if ( conf == null ) { error ( null , "" ) ; } return conf ; } private Constructor < ? extends FlowDescription > findConstructor ( ) { @ SuppressWarnings ( "" ) Constructor < ? extends FlowDescription > [ ] ctors = ( Constructor < ? extends FlowDescription > [ ] ) description . getConstructors ( ) ; if ( ctors . length == ) { error ( null , "" ) ; return null ; } else if ( ctors . length >= ) { error ( null , "" ) ; return ctors [ ] ; } else { return ctors [ ] ; } } public boolean hasError ( ) { return diagnostics . isEmpty ( ) == false ; } private FlowDescriptionDriver parseParameters ( Constructor < ? > ctor ) { assert ctor != null ; List < Parameter > rawParams = parseRawParameters ( ctor ) ; FlowDescriptionDriver driver = new FlowDescriptionDriver ( ) ; for ( Parameter raw : rawParams ) { analyzeParameter ( raw , driver ) ; } return driver ; } private void analyzeParameter ( Parameter parameter , FlowDescriptionDriver driver ) { assert parameter != null ; assert driver != null ; if ( parameter . raw == In . class ) { analyzeInput ( parameter , driver ) ; } else if ( parameter . raw == Out . class ) { analyzeOutput ( parameter , driver ) ; } else { error ( null , "" , parameter . getPosition ( ) ) ; } } private void analyzeInput ( Parameter parameter , FlowDescriptionDriver driver ) { assert parameter != null ; assert driver != null ; Type dataType = invoke ( In . class , parameter . type ) ; if ( dataType == null ) { error ( null , "" , parameter . getPosition ( ) ) ; return ; } if ( parameter . exporter != null ) { error ( null , "" , parameter . getPosition ( ) ) ; } if ( parameter . importer == null ) { error ( null , "" , parameter . getPosition ( ) ) ; return ; } else { String name = parameter . importer . name ( ) ; if ( driver . isValidName ( name ) == false ) { error ( null , "" , parameter . getPosition ( ) , name ) ; return ; } Class < ? extends ImporterDescription > aClass = parameter . importer . description ( ) ; ImporterDescription importer ; try { importer = aClass . newInstance ( ) ; } catch ( Exception e ) { error ( e , "" , aClass . getName ( ) , parameter . getPosition ( ) ) ; return ; } if ( importer . getModelType ( ) == null ) { error ( null , "" , aClass . getName ( ) , parameter . getPosition ( ) ) ; return ; } if ( dataType . equals ( importer . getModelType ( ) ) == false ) { error ( null , "" , aClass . getName ( ) , parameter . getPosition ( ) ) ; return ; } driver . createIn ( name , importer ) ; } } private void analyzeOutput ( Parameter parameter , FlowDescriptionDriver driver ) { assert parameter != null ; assert driver != null ; Type dataType = invoke ( Out . class , parameter . type ) ; if ( dataType == null ) { error ( null , "" , parameter . getPosition ( ) ) ; return ; } if ( parameter . importer != null ) { error ( null , "" , parameter . getPosition ( ) ) ; } if ( parameter . exporter == null ) { error ( null , "" , parameter . getPosition ( ) ) ; return ; } else { String name = parameter . exporter . name ( ) ; if ( driver . isValidName ( name ) == false ) { error ( null , "" , parameter . getPosition ( ) , name ) ; return ; } Class < ? extends ExporterDescription > aClass = parameter . exporter . description ( ) ; ExporterDescription exporter ; try { exporter = aClass . newInstance ( ) ; } catch ( Exception e ) { error ( e , "" , aClass . getName ( ) , parameter . getPosition ( ) ) ; return ; } if ( exporter . getModelType ( ) == null ) { error ( null , "" , aClass . getName ( ) , parameter . getPosition ( ) ) ; return ; } if ( dataType . equals ( exporter . getModelType ( ) ) == false ) { error ( null , "" , aClass . getName ( ) , parameter . getPosition ( ) ) ; return ; } driver . createOut ( name , exporter ) ; } } private void error ( Throwable reason , String message , Object ... args ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( format ( message , args ) ) ; buf . append ( "" ) ; buf . append ( description . getName ( ) ) ; String text = buf . toString ( ) ; diagnostics . add ( text ) ; if ( reason == null ) { LOG . error ( text ) ; } else { LOG . error ( text , reason ) ; } } private String format ( String message , Object ... args ) { assert message != null ; assert args != null ; if ( args . length == ) { return message ; } else { return MessageFormat . format ( message , args ) ; } } private Type invoke ( Class < ? > target , Type subtype ) { assert target != null ; assert subtype != null ; List < Type > invoked = TypeUtil . invoke ( target , subtype ) ; if ( invoked == null || invoked . size ( ) != ) { return null ; } return invoked . get ( ) ; } private List < Parameter > parseRawParameters ( Constructor < ? > ctor ) { assert ctor != null ; Class < ? > [ ] rawTypes = ctor . getParameterTypes ( ) ; Type [ ] types = ctor . getGenericParameterTypes ( ) ; Annotation [ ] [ ] annotations = ctor . getParameterAnnotations ( ) ; List < Parameter > results = Lists . create ( ) ; for ( int i = ; i < types . length ; i ++ ) { Import importer = null ; Export expoter = null ; for ( Annotation a : annotations [ i ] ) { if ( a . annotationType ( ) == Import . class ) { importer = ( Import ) a ; } else if ( a . annotationType ( ) == Export . class ) { expoter = ( Export ) a ; } } results . add ( new Parameter ( i , rawTypes [ i ] , types [ i ] , importer , expoter ) ) ; } return results ; } private static class Parameter { final int index ; final Class < ? > raw ; final Type type ; final Import importer ; final Export exporter ; Parameter ( int index , Class < ? > raw , Type type , Import importer , Export exporter ) { assert raw != null ; assert type != null ; this . index = index ; this . raw = raw ; this . type = type ; this . importer = importer ; this . exporter = exporter ; } int getPosition ( ) { return index + ; } } } package com . asakusafw . compiler . flow ; import java . lang . reflect . Type ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; public class ShuffleDescription { private Type outputType ; private ShuffleKey keyInfo ; private LinePartProcessor converter ; public ShuffleDescription ( Type outputType , ShuffleKey keyInfo , LinePartProcessor converter ) { Precondition . checkMustNotBeNull ( outputType , "" ) ; Precondition . checkMustNotBeNull ( keyInfo , "" ) ; Precondition . checkMustNotBeNull ( converter , "" ) ; this . outputType = outputType ; this . keyInfo = keyInfo ; this . converter = converter ; } public Type getOutputType ( ) { return outputType ; } public ShuffleKey getKeyInfo ( ) { return keyInfo ; } public LinePartProcessor getConverter ( ) { return converter ; } } package com . asakusafw . compiler . flow ; import java . lang . annotation . Annotation ; import java . text . MessageFormat ; import com . asakusafw . compiler . common . TargetOperator ; public abstract class AbstractFlowElementProcessor extends FlowCompilingEnvironment . Initialized implements FlowElementProcessor { private Class < ? extends Annotation > targetOperatorAnnotation ; protected Class < ? extends Annotation > loadTargetAnnotationType ( ) { TargetOperator target = getClass ( ) . getAnnotation ( TargetOperator . class ) ; if ( target != null ) { return target . value ( ) ; } else { return null ; } } @ Override public Class < ? extends Annotation > getTargetAnnotationType ( ) { if ( targetOperatorAnnotation == null ) { this . targetOperatorAnnotation = loadTargetAnnotationType ( ) ; if ( targetOperatorAnnotation == null ) { getEnvironment ( ) . error ( "" , getClass ( ) ) ; throw new IllegalStateException ( ) ; } } return targetOperatorAnnotation ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getName ( ) ) ; } } package com . asakusafw . compiler . flow . plan ; import java . lang . annotation . Annotation ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowCompilerOptions . GenericOptionValue ; import com . asakusafw . compiler . flow . FlowGraphRewriter ; import com . asakusafw . compiler . flow . FlowGraphRewriter . RewriteException ; import com . asakusafw . compiler . flow . debugging . Debug ; import com . asakusafw . compiler . flow . join . operator . SideDataBranch ; import com . asakusafw . compiler . flow . join . operator . SideDataCheck ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . flow . graph . Connectivity ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . FlowOut ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . Inline ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; import com . asakusafw . vocabulary . operator . Branch ; import com . asakusafw . vocabulary . operator . Logging ; import com . asakusafw . vocabulary . operator . Project ; import com . asakusafw . vocabulary . operator . Restructure ; import com . asakusafw . vocabulary . operator . Split ; public class StagePlanner { static final String KEY_COMPRESS_FLOW_BLOCK_GROUP = "" ; static final GenericOptionValue DEFAULT_COMPRESS_FLOW_BLOCK_GROUP = GenericOptionValue . ENABLED ; static final Logger LOG = LoggerFactory . getLogger ( StagePlanner . class ) ; private final List < ? extends FlowGraphRewriter > rewriters ; private final FlowCompilerOptions options ; private final List < StagePlanner . Diagnostic > diagnostics = Lists . create ( ) ; private int blockSequence = ; public StagePlanner ( List < ? extends FlowGraphRewriter > rewriters , FlowCompilerOptions options ) { Precondition . checkMustNotBeNull ( rewriters , "" ) ; Precondition . checkMustNotBeNull ( options , "" ) ; this . rewriters = rewriters ; this . options = options ; } public StageGraph plan ( FlowGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; if ( validate ( graph ) == false ) { return null ; } LOG . info ( "" , graph ) ; LOG . debug ( "" , options . isCompressFlowPart ( ) ) ; LOG . debug ( "" , options . isCompressConcurrentStage ( ) ) ; FlowGraph copy = FlowGraphUtil . deepCopy ( graph ) ; if ( rewrite ( copy ) == false ) { return null ; } normalizeFlowGraph ( copy ) ; StageGraph result = buildStageGraph ( copy ) ; return result ; } private boolean rewrite ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; boolean modified = false ; for ( FlowGraphRewriter rewriter : rewriters ) { try { modified |= rewriter . rewrite ( graph ) ; } catch ( RewriteException e ) { LOG . warn ( MessageFormat . format ( "" , rewriter . getClass ( ) . getName ( ) , e . getMessage ( ) ) , e ) ; error ( graph , Collections . < FlowElement > emptyList ( ) , "" , e . getMessage ( ) ) ; return false ; } } if ( modified && validate ( graph ) == false ) { return false ; } return true ; } private void unifyGlobalSideEffects ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; for ( FlowElement element : FlowGraphUtil . collectElements ( graph ) ) { if ( FlowGraphUtil . hasGlobalSideEffect ( element ) ) { LOG . debug ( "" , graph ) ; for ( FlowElementOutput output : element . getOutputPorts ( ) ) { FlowGraphUtil . insertCheckpoint ( output ) ; } } } } public List < StagePlanner . Diagnostic > getDiagnostics ( ) { return diagnostics ; } StageGraph buildStageGraph ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; FlowBlock input = buildInputBlock ( graph ) ; FlowBlock output = buildOutputBlock ( graph ) ; List < FlowBlock > computation = buildComputationBlocks ( graph ) ; connectFlowBlocks ( input , output , computation ) ; detachFlowBlocks ( input , output , computation ) ; trimFlowBlocks ( computation ) ; List < StageBlock > stageBlocks = buildStageBlocks ( computation ) ; compressStageBlocks ( stageBlocks ) ; sortStageBlocks ( stageBlocks ) ; return new StageGraph ( input , output , stageBlocks ) ; } private void compressStageBlocks ( List < StageBlock > blocks ) { assert blocks != null ; boolean changed ; LOG . debug ( "" ) ; do { changed = false ; Iterator < StageBlock > iter = blocks . iterator ( ) ; while ( iter . hasNext ( ) ) { StageBlock block = iter . next ( ) ; changed |= block . compaction ( ) ; if ( block . isEmpty ( ) ) { LOG . debug ( "" , block ) ; iter . remove ( ) ; changed = true ; } } } while ( changed ) ; } private void sortStageBlocks ( List < StageBlock > stageBlocks ) { assert stageBlocks != null ; LOG . debug ( "" ) ; Map < FlowBlock , StageBlock > membership = Maps . create ( ) ; for ( StageBlock stage : stageBlocks ) { for ( FlowBlock flow : stage . getMapBlocks ( ) ) { membership . put ( flow , stage ) ; } for ( FlowBlock flow : stage . getReduceBlocks ( ) ) { membership . put ( flow , stage ) ; } } Graph < StageBlock > graph = Graphs . newInstance ( ) ; for ( Map . Entry < FlowBlock , StageBlock > entry : membership . entrySet ( ) ) { FlowBlock flow = entry . getKey ( ) ; StageBlock stage = entry . getValue ( ) ; graph . addNode ( stage ) ; for ( FlowBlock . Output output : flow . getBlockOutputs ( ) ) { for ( FlowBlock . Connection conn : output . getConnections ( ) ) { FlowBlock succFlow = conn . getDownstream ( ) . getOwner ( ) ; StageBlock succ = membership . get ( succFlow ) ; if ( succ == null || succ == stage ) { continue ; } graph . addEdge ( succ , stage ) ; } } } List < StageBlock > ordered = Graphs . sortPostOrder ( graph ) ; int stageNumber = ; for ( StageBlock stage : ordered ) { stage . setStageNumber ( stageNumber ) ; stageNumber ++ ; } Collections . sort ( stageBlocks , new Comparator < StageBlock > ( ) { @ Override public int compare ( StageBlock o1 , StageBlock o2 ) { int n1 = o1 . getStageNumber ( ) ; int n2 = o2 . getStageNumber ( ) ; if ( n1 == n2 ) { return ; } else if ( n1 < n2 ) { return - ; } else { return + ; } } } ) ; } private List < StageBlock > buildStageBlocks ( List < FlowBlock > blocks ) { assert blocks != null ; LOG . debug ( "" , blocks ) ; List < StageBlock > results = Lists . create ( ) ; List < FlowBlockGroup > flowBlockGroups = collectFlowBlockGroups ( blocks ) ; compressFlowBlockGroups ( flowBlockGroups ) ; for ( FlowBlockGroup group : flowBlockGroups ) { if ( group . reducer ) { Set < FlowBlock > predecessors = getPredecessors ( group . members ) ; assert predecessors . isEmpty ( ) == false ; StageBlock stage = new StageBlock ( predecessors , group . members ) ; results . add ( stage ) ; LOG . debug ( "" , new Object [ ] { stage , group . members , predecessors , } ) ; } else { StageBlock stage = new StageBlock ( group . members , Collections . < FlowBlock > emptySet ( ) ) ; results . add ( stage ) ; LOG . debug ( "" , stage , group . members ) ; } } return results ; } private void compressFlowBlockGroups ( List < FlowBlockGroup > flowBlockGroups ) { assert flowBlockGroups != null ; GenericOptionValue active = options . getGenericExtraAttribute ( KEY_COMPRESS_FLOW_BLOCK_GROUP , DEFAULT_COMPRESS_FLOW_BLOCK_GROUP ) ; if ( active == GenericOptionValue . DISABLED ) { return ; } LOG . debug ( "" ) ; List < FlowBlock > blocks = Lists . create ( ) ; Map < FlowBlock . Input , Set < FlowBlock . Input > > inputMapping = Maps . create ( ) ; Map < FlowBlock . Output , Set < FlowBlock . Output > > outputMapping = Maps . create ( ) ; for ( FlowBlockGroup group : flowBlockGroups ) { if ( group . reducer ) { Set < FlowBlock > predecessors = getPredecessors ( group . members ) ; if ( predecessors . size ( ) >= ) { LOG . debug ( "" , predecessors ) ; FlowBlock mergedPreds = FlowBlock . fromBlocks ( predecessors , inputMapping , outputMapping ) ; group . predeceaseBlocks . clear ( ) ; group . predeceaseBlocks . add ( mergedPreds ) ; blocks . add ( mergedPreds ) ; } } if ( group . members . size ( ) >= ) { LOG . debug ( "" , group . members ) ; FlowBlock mergedBlocks = FlowBlock . fromBlocks ( group . members , inputMapping , outputMapping ) ; group . members . clear ( ) ; group . members . add ( mergedBlocks ) ; blocks . add ( mergedBlocks ) ; } } for ( Map . Entry < FlowBlock . Input , Set < FlowBlock . Input > > entry : inputMapping . entrySet ( ) ) { FlowBlock . Input origin = entry . getKey ( ) ; for ( FlowBlock . Connection conn : Lists . from ( origin . getConnections ( ) ) ) { FlowBlock . Output opposite = conn . getUpstream ( ) ; Collection < FlowBlock . Output > resolvedOpposites ; if ( outputMapping . containsKey ( opposite ) ) { resolvedOpposites = outputMapping . get ( opposite ) ; } else { resolvedOpposites = Collections . singleton ( opposite ) ; } conn . disconnect ( ) ; for ( FlowBlock . Input mapped : entry . getValue ( ) ) { for ( FlowBlock . Output resolved : resolvedOpposites ) { FlowBlock . connect ( resolved , mapped ) ; } } } } for ( Map . Entry < FlowBlock . Output , Set < FlowBlock . Output > > entry : outputMapping . entrySet ( ) ) { FlowBlock . Output origin = entry . getKey ( ) ; for ( FlowBlock . Connection conn : Lists . from ( origin . getConnections ( ) ) ) { FlowBlock . Input opposite = conn . getDownstream ( ) ; Collection < FlowBlock . Input > resolvedOpposites ; if ( inputMapping . containsKey ( opposite ) ) { resolvedOpposites = inputMapping . get ( opposite ) ; } else { resolvedOpposites = Collections . singleton ( opposite ) ; } conn . disconnect ( ) ; for ( FlowBlock . Output mapped : entry . getValue ( ) ) { for ( FlowBlock . Input resolved : resolvedOpposites ) { FlowBlock . connect ( mapped , resolved ) ; } } } } detachFlowBlocks ( blocks ) ; unifyFlowBlocks ( blocks ) ; trimFlowBlocks ( blocks ) ; } private List < FlowBlockGroup > collectFlowBlockGroups ( List < FlowBlock > blocks ) { assert blocks != null ; LOG . debug ( "" ) ; LinkedList < FlowBlockGroup > groups = new LinkedList < FlowBlockGroup > ( ) ; for ( FlowBlock block : blocks ) { if ( block . isReduceBlock ( ) == false && block . isSucceedingReduceBlock ( ) ) { continue ; } groups . add ( new FlowBlockGroup ( block ) ) ; } if ( options . isCompressConcurrentStage ( ) == false ) { LOG . debug ( "" ) ; return Lists . from ( groups ) ; } LOG . debug ( "" ) ; computeCriticalPaths ( groups ) ; List < FlowBlockGroup > results = Lists . create ( ) ; while ( groups . isEmpty ( ) == false ) { FlowBlockGroup first = groups . removeFirst ( ) ; Iterator < FlowBlockGroup > rest = groups . iterator ( ) ; while ( rest . hasNext ( ) ) { FlowBlockGroup next = rest . next ( ) ; if ( first . combine ( next ) ) { LOG . debug ( "" , first . founder , next . founder ) ; rest . remove ( ) ; } } results . add ( first ) ; } return results ; } private void computeCriticalPaths ( List < FlowBlockGroup > groups ) { assert groups != null ; Map < FlowBlock , FlowBlockGroup > mapping = Maps . create ( ) ; LinkedList < FlowBlockGroup > work = new LinkedList < FlowBlockGroup > ( ) ; for ( FlowBlockGroup group : groups ) { work . add ( group ) ; mapping . put ( group . founder , group ) ; } PROPAGATION : while ( work . isEmpty ( ) == false ) { int maxDistance = ; FlowBlockGroup first = work . removeFirst ( ) ; for ( FlowBlock predecessor : first . predeceaseBlocks ) { FlowBlockGroup predGroup = mapping . get ( predecessor ) ; if ( predGroup . distance == - ) { work . addLast ( first ) ; continue PROPAGATION ; } else { maxDistance = Math . max ( maxDistance , predGroup . distance ) ; } } first . distance = maxDistance + ; } } private Set < FlowBlock > getPredecessors ( Set < FlowBlock > blocks ) { assert blocks != null ; Set < FlowBlock > results = Sets . create ( ) ; for ( FlowBlock block : blocks ) { for ( FlowBlock . Input port : block . getBlockInputs ( ) ) { for ( FlowBlock . Connection conn : port . getConnections ( ) ) { FlowBlock pred = conn . getUpstream ( ) . getOwner ( ) ; results . add ( pred ) ; } } } return results ; } private FlowBlock buildInputBlock ( FlowGraph graph ) { assert graph != null ; List < FlowElementOutput > outputs = Lists . create ( ) ; Set < FlowElement > elements = Sets . create ( ) ; for ( FlowIn < ? > node : graph . getFlowInputs ( ) ) { outputs . add ( node . toOutputPort ( ) ) ; elements . add ( node . getFlowElement ( ) ) ; } return FlowBlock . fromPorts ( nextBlockSequenceNumber ( ) , graph , Collections . < FlowElementInput > emptyList ( ) , outputs , elements ) ; } private FlowBlock buildOutputBlock ( FlowGraph graph ) { assert graph != null ; List < FlowElementInput > inputs = Lists . create ( ) ; Set < FlowElement > elements = Sets . create ( ) ; for ( FlowOut < ? > node : graph . getFlowOutputs ( ) ) { inputs . add ( node . toInputPort ( ) ) ; elements . add ( node . getFlowElement ( ) ) ; } return FlowBlock . fromPorts ( nextBlockSequenceNumber ( ) , graph , inputs , Collections . < FlowElementOutput > emptyList ( ) , elements ) ; } private List < FlowBlock > buildComputationBlocks ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; Collection < FlowPath > shuffleSuccessors = Sets . create ( ) ; Collection < FlowPath > shufflePredecessors = Sets . create ( ) ; Map < FlowElement , FlowPath > stageSuccessors = Maps . create ( ) ; Map < FlowElement , FlowPath > stagePredecessors = Maps . create ( ) ; for ( FlowElement boundary : FlowGraphUtil . collectBoundaries ( graph ) ) { boolean shuffle = FlowGraphUtil . isShuffleBoundary ( boundary ) ; boolean success = FlowGraphUtil . hasSuccessors ( boundary ) ; boolean predecease = FlowGraphUtil . hasPredecessors ( boundary ) ; if ( shuffle ) { assert success ; assert predecease ; shuffleSuccessors . add ( FlowGraphUtil . getSucceedBoundaryPath ( boundary ) ) ; shufflePredecessors . add ( FlowGraphUtil . getPredeceaseBoundaryPath ( boundary ) ) ; } else { if ( success ) { stageSuccessors . put ( boundary , FlowGraphUtil . getSucceedBoundaryPath ( boundary ) ) ; } if ( predecease ) { stagePredecessors . put ( boundary , FlowGraphUtil . getPredeceaseBoundaryPath ( boundary ) ) ; } } } List < FlowBlock > results = Lists . create ( ) ; results . addAll ( collectShuffleToStage ( graph , shuffleSuccessors ) ) ; results . addAll ( collectStageToShuffle ( graph , shufflePredecessors , stageSuccessors ) ) ; results . addAll ( collectStageToStage ( graph , stageSuccessors , stagePredecessors ) ) ; return results ; } private List < FlowBlock > collectStageToStage ( FlowGraph graph , Map < FlowElement , FlowPath > stageSuccessors , Map < FlowElement , FlowPath > stagePredecessors ) { assert graph != null ; assert stageSuccessors != null ; assert stagePredecessors != null ; LOG . debug ( "" , graph ) ; List < FlowBlock > results = Lists . create ( ) ; Collection < FlowPath > ss = stageSuccessors . values ( ) ; for ( FlowPath stageForward : ss ) { List < FlowPath > stageBackwards = Lists . create ( ) ; for ( FlowElement arrival : stageForward . getArrivals ( ) ) { if ( FlowGraphUtil . isShuffleBoundary ( arrival ) == false ) { FlowPath stageBackward = stagePredecessors . get ( arrival ) ; assert stageBackward != null ; stageBackwards . add ( stageBackward ) ; } } if ( stageBackwards . isEmpty ( ) ) { continue ; } FlowPath backward = FlowGraphUtil . union ( stageBackwards ) ; FlowPath path = stageForward . transposeIntersect ( backward ) ; FlowBlock block = path . createBlock ( graph , nextBlockSequenceNumber ( ) , false , false ) ; results . add ( block ) ; LOG . debug ( "" , block . getBlockInputs ( ) , block . getBlockOutputs ( ) ) ; } return results ; } private List < FlowBlock > collectStageToShuffle ( FlowGraph graph , Collection < FlowPath > shufflePredecessors , Map < FlowElement , FlowPath > stageSuccessors ) { assert graph != null ; assert shufflePredecessors != null ; assert stageSuccessors != null ; LOG . debug ( "" , graph ) ; List < FlowBlock > results = Lists . create ( ) ; for ( FlowPath shuffleBackward : shufflePredecessors ) { Set < FlowElement > arrivals = shuffleBackward . getArrivals ( ) ; for ( FlowElement stageStart : arrivals ) { assert FlowGraphUtil . isShuffleBoundary ( stageStart ) == false ; FlowPath stageForward = stageSuccessors . get ( stageStart ) ; assert stageForward != null ; FlowPath path = stageForward . transposeIntersect ( shuffleBackward ) ; FlowBlock block = path . createBlock ( graph , nextBlockSequenceNumber ( ) , false , false ) ; results . add ( block ) ; LOG . debug ( "" , block . getBlockInputs ( ) , block . getBlockOutputs ( ) ) ; } } return results ; } private List < FlowBlock > collectShuffleToStage ( FlowGraph graph , Collection < FlowPath > shuffleSuccessors ) { assert graph != null ; assert shuffleSuccessors != null ; LOG . debug ( "" , graph ) ; List < FlowBlock > results = Lists . create ( ) ; for ( FlowPath path : shuffleSuccessors ) { FlowBlock block = path . createBlock ( graph , nextBlockSequenceNumber ( ) , true , false ) ; results . add ( block ) ; LOG . debug ( "" , block . getBlockInputs ( ) , block . getBlockOutputs ( ) ) ; } return results ; } private int nextBlockSequenceNumber ( ) { return blockSequence ++ ; } private void connectFlowBlocks ( FlowBlock inputBlock , FlowBlock outputBlock , List < FlowBlock > computationBlocks ) { assert inputBlock != null ; assert outputBlock != null ; assert computationBlocks != null ; LOG . debug ( "" ) ; List < FlowBlock > blocks = Lists . create ( ) ; blocks . add ( inputBlock ) ; blocks . add ( outputBlock ) ; blocks . addAll ( computationBlocks ) ; Map < PortConnection , Set < FlowBlock . Input > > mapping = Maps . create ( ) ; for ( FlowBlock block : blocks ) { for ( FlowBlock . Input input : block . getBlockInputs ( ) ) { for ( PortConnection conn : input . getOriginalConnections ( ) ) { Maps . addToSet ( mapping , conn , input ) ; } } } for ( FlowBlock block : blocks ) { for ( FlowBlock . Output output : block . getBlockOutputs ( ) ) { for ( PortConnection conn : output . getOriginalConnections ( ) ) { Set < PortConnection > next = FlowGraphUtil . getSucceedingConnections ( conn , mapping . keySet ( ) ) ; for ( PortConnection successor : next ) { Set < FlowBlock . Input > connected = mapping . get ( successor ) ; for ( FlowBlock . Input opposite : connected ) { FlowBlock . connect ( output , opposite ) ; } } } } } } private void detachFlowBlocks ( FlowBlock input , FlowBlock output , List < FlowBlock > computation ) { assert input != null ; assert output != null ; assert computation != null ; input . detach ( ) ; output . detach ( ) ; detachFlowBlocks ( computation ) ; } private void detachFlowBlocks ( List < FlowBlock > blocks ) { assert blocks != null ; for ( FlowBlock block : blocks ) { block . detach ( ) ; } } private void unifyFlowBlocks ( List < FlowBlock > blocks ) { assert blocks != null ; for ( FlowBlock block : blocks ) { block . unify ( ) ; } } private void trimFlowBlocks ( List < FlowBlock > blocks ) { assert blocks != null ; boolean changed ; LOG . debug ( "" ) ; do { changed = false ; Iterator < FlowBlock > iter = blocks . iterator ( ) ; while ( iter . hasNext ( ) ) { FlowBlock block = iter . next ( ) ; changed |= block . compaction ( ) ; if ( block . isEmpty ( ) ) { LOG . debug ( "" , block ) ; iter . remove ( ) ; changed = true ; } } } while ( changed ) ; } void normalizeFlowGraph ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; inlineFlowParts ( graph ) ; unifyGlobalSideEffects ( graph ) ; insertCheckpoints ( graph ) ; insertIdentities ( graph ) ; splitIdentities ( graph ) ; reduceIdentities ( graph ) ; } private void inlineFlowParts ( FlowGraph graph ) { assert graph != null ; for ( FlowElement element : FlowGraphUtil . collectFlowParts ( graph ) ) { FlowPartDescription desc = ( FlowPartDescription ) element . getDescription ( ) ; inlineFlowParts ( desc . getFlowGraph ( ) ) ; Inline inlineConfig = element . getAttribute ( Inline . class ) ; if ( inlineConfig == null || inlineConfig == Inline . DEFAULT ) { inlineConfig = options . isCompressFlowPart ( ) ? Inline . FORCE_AGGREGATE : Inline . KEEP_SEGREGATED ; } if ( inlineConfig == Inline . FORCE_AGGREGATE ) { LOG . debug ( "" , element . getDescription ( ) . getName ( ) ) ; FlowGraphUtil . inlineFlowPart ( element ) ; } else { FlowGraphUtil . inlineFlowPart ( element , FlowBoundary . STAGE ) ; } } assert FlowGraphUtil . collectFlowParts ( graph ) . isEmpty ( ) : FlowGraphUtil . collectFlowParts ( graph ) ; } void insertCheckpoints ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; for ( FlowElement element : FlowGraphUtil . collectBoundaries ( graph ) ) { insertCheckpoints ( element ) ; } } private void insertCheckpoints ( FlowElement element ) { assert element != null ; if ( FlowGraphUtil . isShuffleBoundary ( element ) == false ) { return ; } for ( FlowElementOutput output : element . getOutputPorts ( ) ) { insertCheckpointsWithPushDown ( output ) ; } } private void insertCheckpointsWithPushDown ( FlowElementOutput start ) { assert start != null ; LinkedList < FlowElementOutput > work = new LinkedList < FlowElementOutput > ( ) ; work . add ( start ) ; while ( work . isEmpty ( ) == false ) { FlowElementOutput output = work . removeFirst ( ) ; if ( isSuccessShuffleBoundary ( output ) == false ) { continue ; } Set < PortConnection > connections = output . getConnected ( ) ; if ( connections . size ( ) != ) { LOG . debug ( "" , output ) ; FlowGraphUtil . insertCheckpoint ( output ) ; continue ; } FlowElementInput input = connections . iterator ( ) . next ( ) . getDownstream ( ) ; FlowElement successor = input . getOwner ( ) ; if ( isPushDownTarget ( successor ) == false ) { LOG . debug ( "" , output ) ; FlowGraphUtil . insertCheckpoint ( output ) ; continue ; } LOG . debug ( "" , successor ) ; work . addAll ( successor . getOutputPorts ( ) ) ; } } private boolean isSuccessShuffleBoundary ( FlowElementOutput output ) { assert output != null ; Collection < FlowElement > successors = FlowGraphUtil . getSucceedingBoundaries ( output ) ; for ( FlowElement successor : successors ) { assert FlowGraphUtil . isBoundary ( successor ) ; if ( FlowGraphUtil . isShuffleBoundary ( successor ) == false ) { continue ; } return true ; } return false ; } private boolean isPushDownTarget ( FlowElement element ) { assert element != null ; if ( element . getInputPorts ( ) . size ( ) != ) { return false ; } FlowElementInput input = element . getInputPorts ( ) . get ( ) ; if ( input . getConnected ( ) . size ( ) != ) { return false ; } if ( FlowGraphUtil . isBoundary ( element ) ) { return false ; } FlowElementDescription desc = element . getDescription ( ) ; if ( desc . getKind ( ) == FlowElementKind . PSEUD ) { return true ; } else if ( desc . getKind ( ) == FlowElementKind . OPERATOR ) { OperatorDescription op = ( OperatorDescription ) desc ; Class < ? extends Annotation > kind = op . getDeclaration ( ) . getAnnotationType ( ) ; if ( kind == Branch . class || kind == Split . class || kind == Project . class || kind == Restructure . class || kind == SideDataCheck . class || kind == SideDataBranch . class || kind == Logging . class || kind == Debug . class ) { return true ; } } return false ; } void insertIdentities ( FlowGraph graph ) { assert graph != null ; for ( FlowElement element : FlowGraphUtil . collectBoundaries ( graph ) ) { insertIdentities ( element ) ; } } private void insertIdentities ( FlowElement element ) { assert element != null ; if ( FlowGraphUtil . isStageBoundary ( element ) == false ) { return ; } for ( FlowElementOutput output : element . getOutputPorts ( ) ) { for ( FlowElementInput opposite : output . getOpposites ( ) ) { FlowElement successor = opposite . getOwner ( ) ; if ( FlowGraphUtil . isBoundary ( successor ) ) { FlowGraphUtil . insertIdentity ( output ) ; } } } } void splitIdentities ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; boolean changed ; do { changed = false ; for ( FlowElement element : FlowGraphUtil . collectElements ( graph ) ) { if ( FlowGraphUtil . isIdentity ( element ) ) { changed |= FlowGraphUtil . splitIdentity ( element ) ; } } } while ( changed ) ; } void reduceIdentities ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; boolean changed ; do { changed = false ; for ( FlowElement element : FlowGraphUtil . collectElements ( graph ) ) { if ( FlowGraphUtil . isIdentity ( element ) == false ) { continue ; } Set < FlowElement > preds = FlowGraphUtil . getPredecessors ( element ) ; Set < FlowElement > succs = FlowGraphUtil . getSuccessors ( element ) ; assert preds . size ( ) == && succs . size ( ) == : "" ; FlowElement pred = preds . iterator ( ) . next ( ) ; FlowElement succ = succs . iterator ( ) . next ( ) ; if ( FlowGraphUtil . isStageBoundary ( pred ) && FlowGraphUtil . isBoundary ( succ ) ) { continue ; } LOG . debug ( "" , element ) ; changed = true ; FlowGraphUtil . skip ( element ) ; } } while ( changed ) ; } boolean validate ( FlowGraph graph ) { assert graph != null ; LOG . debug ( "" , graph ) ; Graph < FlowElement > elements = FlowGraphUtil . toElementGraph ( graph ) ; boolean valid = true ; valid &= validateConnection ( graph , elements ) ; valid &= validateAcyclic ( graph , elements ) ; for ( FlowElement element : FlowGraphUtil . collectFlowParts ( graph ) ) { FlowPartDescription description = ( FlowPartDescription ) element . getDescription ( ) ; valid &= validate ( description . getFlowGraph ( ) ) ; } return valid ; } private boolean validateConnection ( FlowGraph graph , Graph < FlowElement > elements ) { assert graph != null ; assert elements != null ; LOG . debug ( "" , graph ) ; boolean sawError = false ; for ( FlowElement element : elements . getNodeSet ( ) ) { Connectivity connectivity = element . getAttribute ( Connectivity . class ) ; if ( connectivity == null ) { connectivity = Connectivity . getDefault ( ) ; } for ( FlowElementInput port : element . getInputPorts ( ) ) { if ( port . getConnected ( ) . isEmpty ( ) == false ) { continue ; } error ( graph , Collections . singletonList ( element ) , "" , element . getDescription ( ) . getName ( ) , port . getDescription ( ) . getName ( ) ) ; sawError = true ; } for ( FlowElementOutput port : element . getOutputPorts ( ) ) { if ( port . getConnected ( ) . isEmpty ( ) == false ) { continue ; } if ( connectivity == Connectivity . MANDATORY ) { error ( graph , Collections . singletonList ( element ) , "" , element . getDescription ( ) . getName ( ) , port . getDescription ( ) . getName ( ) ) ; sawError = true ; } else { LOG . debug ( "" , element . getDescription ( ) . getName ( ) , port . getDescription ( ) . getName ( ) ) ; FlowGraphUtil . stop ( port ) ; } } } return sawError == false ; } private boolean validateAcyclic ( FlowGraph graph , Graph < FlowElement > elements ) { assert graph != null ; assert elements != null ; LOG . debug ( "" , graph ) ; Set < Set < FlowElement > > circuits = Graphs . findCircuit ( elements ) ; for ( Set < FlowElement > cyclic : circuits ) { List < FlowElement > context = Lists . from ( cyclic ) ; List < String > names = Lists . create ( ) ; for ( FlowElement elem : context ) { names . add ( elem . getDescription ( ) . getName ( ) ) ; } error ( graph , context , "" , names ) ; } return circuits . isEmpty ( ) ; } private void error ( FlowGraph graph , List < FlowElement > context , String message , Object ... messageArguments ) { assert graph != null ; assert context != null ; assert message != null ; assert messageArguments != null ; String text ; if ( messageArguments . length == ) { text = message ; } else { text = MessageFormat . format ( message , messageArguments ) ; } diagnostics . add ( new Diagnostic ( graph , context , text ) ) ; } public static class Diagnostic { public final FlowGraph graph ; public final List < FlowElement > context ; public final String message ; public Diagnostic ( FlowGraph graph , List < FlowElement > context , String message ) { Precondition . checkMustNotBeNull ( graph , "" ) ; Precondition . checkMustNotBeNull ( context , "" ) ; Precondition . checkMustNotBeNull ( message , "" ) ; this . graph = graph ; this . context = Collections . unmodifiableList ( context ) ; this . message = message ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , graph , message , context ) ; } } private static class FlowBlockGroup { final FlowBlock founder ; @ SuppressWarnings ( "" ) private final Set < FlowBlock . Output > groupSource ; final Set < FlowBlock > predeceaseBlocks ; final Set < FlowBlock > members ; final boolean reducer ; int distance = - ; FlowBlockGroup ( FlowBlock flowBlock ) { assert flowBlock != null ; this . founder = flowBlock ; this . members = Sets . create ( ) ; this . members . add ( flowBlock ) ; this . reducer = flowBlock . isReduceBlock ( ) ; this . groupSource = collectStageSource ( flowBlock ) ; this . predeceaseBlocks = collectPredeceaseBlocks ( flowBlock ) ; } private Set < FlowBlock . Output > collectStageSource ( FlowBlock flowBlock ) { assert flowBlock != null ; if ( flowBlock . isReduceBlock ( ) ) { Set < FlowBlock . Output > results = Sets . create ( ) ; for ( FlowBlock predecessor : getPredeceaseBlocks ( flowBlock ) ) { assert predecessor . isReduceBlock ( ) == false ; results . addAll ( collectBlockSource ( predecessor ) ) ; } return results ; } else { return collectBlockSource ( flowBlock ) ; } } private Set < FlowBlock > getPredeceaseBlocks ( FlowBlock flowBlock ) { assert flowBlock != null ; Set < FlowBlock > results = Sets . create ( ) ; for ( FlowBlock . Input input : flowBlock . getBlockInputs ( ) ) { for ( FlowBlock . Connection conn : input . getConnections ( ) ) { FlowBlock pred = conn . getUpstream ( ) . getOwner ( ) ; results . add ( pred ) ; } } return results ; } private Set < FlowBlock . Output > collectBlockSource ( FlowBlock flowBlock ) { assert flowBlock != null ; Set < FlowBlock . Output > results = Sets . create ( ) ; for ( FlowBlock . Input input : flowBlock . getBlockInputs ( ) ) { for ( FlowBlock . Connection conn : input . getConnections ( ) ) { results . add ( conn . getUpstream ( ) ) ; } } return results ; } private Set < FlowBlock > collectPredeceaseBlocks ( FlowBlock flowBlock ) { assert flowBlock != null ; Set < FlowBlock > results = Sets . create ( ) ; LinkedList < FlowBlock > work = new LinkedList < FlowBlock > ( ) ; work . addLast ( flowBlock ) ; while ( work . isEmpty ( ) == false ) { FlowBlock first = work . removeFirst ( ) ; Set < FlowBlock > preds = getPredeceaseBlocks ( first ) ; for ( FlowBlock block : preds ) { if ( block . getBlockInputs ( ) . isEmpty ( ) ) { continue ; } if ( block . isReduceBlock ( ) || block . isSucceedingReduceBlock ( ) == false ) { results . add ( block ) ; } else { work . addLast ( block ) ; } } } return results ; } boolean combine ( FlowBlockGroup other ) { assert other != null ; if ( this . reducer != other . reducer ) { return false ; } if ( this . distance == - || this . distance != other . distance ) { return false ; } this . members . addAll ( other . members ) ; return true ; } } } package com . asakusafw . compiler . flow . plan ; package com . asakusafw . compiler . flow . plan ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; public class FlowBlock { static final Logger LOG = LoggerFactory . getLogger ( FlowBlock . class ) ; private final int serialNumber ; private final FlowGraph source ; private final List < FlowBlock . Input > blockInputs ; private final List < FlowBlock . Output > blockOutputs ; private Set < FlowElement > elements ; private boolean detached ; public static FlowBlock fromPorts ( int serialNumber , FlowGraph source , List < FlowElementInput > inputs , List < FlowElementOutput > outputs , Set < FlowElement > elements ) { List < PortConnection > toInput = Lists . create ( ) ; List < PortConnection > fromOutput = Lists . create ( ) ; for ( FlowElementInput in : inputs ) { toInput . addAll ( in . getConnected ( ) ) ; } for ( FlowElementOutput out : outputs ) { fromOutput . addAll ( out . getConnected ( ) ) ; } return new FlowBlock ( serialNumber , source , toInput , fromOutput , elements ) ; } public static FlowBlock fromBlocks ( Collection < FlowBlock > blocks , Map < FlowBlock . Input , Set < FlowBlock . Input > > inputMapping , Map < FlowBlock . Output , Set < FlowBlock . Output > > outputMapping ) { Precondition . checkMustNotBeNull ( blocks , "" ) ; Precondition . checkMustNotBeNull ( inputMapping , "" ) ; Precondition . checkMustNotBeNull ( outputMapping , "" ) ; FlowGraph graph = null ; int minSerialNumber = Integer . MAX_VALUE ; int reduces = ; for ( FlowBlock block : blocks ) { if ( block . detached == false ) { throw new IllegalArgumentException ( ) ; } graph = graph == null ? block . source : graph ; minSerialNumber = Math . min ( minSerialNumber , block . serialNumber ) ; reduces += block . isReduceBlock ( ) ? : ; } if ( reduces != && reduces != blocks . size ( ) ) { throw new IllegalArgumentException ( "" ) ; } final Set < PortConnection > empty = Collections . < PortConnection > emptySet ( ) ; FlowBlock result = new FlowBlock ( minSerialNumber , graph ) ; for ( FlowBlock block : blocks ) { result . elements . addAll ( block . elements ) ; for ( FlowBlock . Input origin : block . getBlockInputs ( ) ) { FlowBlock . Input mapped = result . new Input ( origin . getElementPort ( ) , empty ) ; result . blockInputs . add ( mapped ) ; Maps . addToSet ( inputMapping , origin , mapped ) ; } for ( FlowBlock . Output origin : block . getBlockOutputs ( ) ) { FlowBlock . Output mapped = result . new Output ( origin . getElementPort ( ) , empty ) ; result . blockOutputs . add ( mapped ) ; Maps . addToSet ( outputMapping , origin , mapped ) ; } } return result ; } public FlowBlock ( int serialNumber , FlowGraph source , List < PortConnection > inputs , List < PortConnection > outputs , Set < FlowElement > elements ) { Precondition . checkMustNotBeNull ( source , "" ) ; Precondition . checkMustNotBeNull ( inputs , "" ) ; Precondition . checkMustNotBeNull ( outputs , "" ) ; Precondition . checkMustNotBeNull ( elements , "" ) ; int shuffles = countShuffleBoundary ( inputs ) ; if ( shuffles != && shuffles != inputs . size ( ) ) { throw new IllegalArgumentException ( "" ) ; } this . serialNumber = serialNumber ; this . source = source ; this . blockInputs = toBlockInputs ( inputs ) ; this . blockOutputs = toBlockOutputs ( outputs ) ; this . elements = Sets . from ( elements ) ; this . detached = false ; } private FlowBlock ( int serialNumber , FlowGraph source ) { Precondition . checkMustNotBeNull ( source , "" ) ; this . serialNumber = serialNumber ; this . source = source ; this . blockInputs = Lists . create ( ) ; this . blockOutputs = Lists . create ( ) ; this . elements = Sets . create ( ) ; this . detached = false ; } private int countShuffleBoundary ( List < PortConnection > inputs ) { assert inputs != null ; int result = ; for ( PortConnection input : inputs ) { if ( FlowGraphUtil . isShuffleBoundary ( input . getDownstream ( ) . getOwner ( ) ) ) { result ++ ; } } return result ; } private List < FlowBlock . Input > toBlockInputs ( List < PortConnection > inputs ) { assert inputs != null ; Map < FlowElementInput , Set < PortConnection > > map = new LinkedHashMap < FlowElementInput , Set < PortConnection > > ( ) ; for ( PortConnection input : inputs ) { FlowElementInput port = input . getDownstream ( ) ; Maps . addToSet ( map , port , input ) ; } List < FlowBlock . Input > results = Lists . create ( ) ; for ( Map . Entry < FlowElementInput , Set < PortConnection > > entry : map . entrySet ( ) ) { results . add ( new FlowBlock . Input ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } return results ; } private List < FlowBlock . Output > toBlockOutputs ( List < PortConnection > outputs ) { assert outputs != null ; Map < FlowElementOutput , Set < PortConnection > > map = new LinkedHashMap < FlowElementOutput , Set < PortConnection > > ( ) ; for ( PortConnection output : outputs ) { FlowElementOutput port = output . getUpstream ( ) ; Maps . addToSet ( map , port , output ) ; } List < FlowBlock . Output > results = Lists . create ( ) ; for ( Map . Entry < FlowElementOutput , Set < PortConnection > > entry : map . entrySet ( ) ) { results . add ( new FlowBlock . Output ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } return results ; } public FlowGraph getSource ( ) { return source ; } public int getSerialNumber ( ) { return serialNumber ; } public List < FlowBlock . Input > getBlockInputs ( ) { return blockInputs ; } public List < FlowBlock . Output > getBlockOutputs ( ) { return blockOutputs ; } public Set < FlowElement > getElements ( ) { return elements ; } public static boolean isConnected ( FlowBlock . Output upstream , FlowBlock . Input downstream ) { Precondition . checkMustNotBeNull ( upstream , "" ) ; Precondition . checkMustNotBeNull ( downstream , "" ) ; for ( FlowBlock . Connection conn : upstream . getConnections ( ) ) { if ( conn . getDownstream ( ) . equals ( downstream ) ) { return true ; } } return false ; } public static void connect ( FlowBlock . Output upstream , FlowBlock . Input downstream ) { Precondition . checkMustNotBeNull ( upstream , "" ) ; Precondition . checkMustNotBeNull ( downstream , "" ) ; if ( upstream . isConnected ( downstream ) ) { return ; } FlowBlock . Connection conn = new FlowBlock . Connection ( upstream , downstream ) ; upstream . addConnection ( conn ) ; downstream . addConnection ( conn ) ; assert upstream . getElementPort ( ) . getDescription ( ) . getDataType ( ) . equals ( downstream . getElementPort ( ) . getDescription ( ) . getDataType ( ) ) ; } public boolean isEmpty ( ) { return blockInputs . isEmpty ( ) && blockOutputs . isEmpty ( ) ; } public boolean isReduceBlock ( ) { if ( blockInputs . isEmpty ( ) ) { return false ; } FlowBlock . Input first = blockInputs . get ( ) ; return FlowGraphUtil . isShuffleBoundary ( first . getElementPort ( ) . getOwner ( ) ) ; } public boolean isSucceedingReduceBlock ( ) { if ( detached == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , this ) ) ; } for ( FlowBlock . Output output : blockOutputs ) { for ( FlowBlock . Connection conn : output . getConnections ( ) ) { FlowBlock successor = conn . getDownstream ( ) . getOwner ( ) ; return successor . isReduceBlock ( ) ; } } return false ; } public void detach ( ) { if ( detached ) { return ; } LOG . debug ( "" , this , getSource ( ) ) ; Map < FlowElement , FlowElement > elementMapping = Maps . create ( ) ; Map < FlowElementInput , FlowElementInput > inputMapping = Maps . create ( ) ; Map < FlowElementOutput , FlowElementOutput > outputMapping = Maps . create ( ) ; FlowGraphUtil . deepCopy ( elements , elementMapping , inputMapping , outputMapping ) ; this . elements = Sets . from ( elementMapping . values ( ) ) ; reconnectBlockInOut ( inputMapping , outputMapping ) ; detached = true ; } private void reconnectBlockInOut ( Map < FlowElementInput , FlowElementInput > inputMapping , Map < FlowElementOutput , FlowElementOutput > outputMapping ) { assert inputMapping != null ; assert outputMapping != null ; for ( FlowBlock . Input bound : blockInputs ) { FlowElementInput port = inputMapping . get ( bound . getElementPort ( ) ) ; assert port != null ; bound . setElementPort ( port ) ; } for ( FlowBlock . Output bound : blockOutputs ) { FlowElementOutput port = outputMapping . get ( bound . getElementPort ( ) ) ; assert port != null ; bound . setElementPort ( port ) ; } } public void unify ( ) { if ( detached == false ) { throw new IllegalStateException ( ) ; } Map < FlowElement , FlowElement > elementMapping = Maps . create ( ) ; Map < FlowElementInput , FlowElementInput > inputMapping = Maps . create ( ) ; Map < FlowElementOutput , FlowElementOutput > outputMapping = Maps . create ( ) ; FlowGraphUtil . deepCopy ( elements , elementMapping , inputMapping , outputMapping ) ; unifyElements ( elementMapping , inputMapping , outputMapping ) ; unifyInputs ( elementMapping , inputMapping , outputMapping ) ; unifyOutputs ( elementMapping , inputMapping , outputMapping ) ; } private void unifyElements ( Map < FlowElement , FlowElement > elementMapping , Map < FlowElementInput , FlowElementInput > inputMapping , Map < FlowElementOutput , FlowElementOutput > outputMapping ) { assert elementMapping != null ; assert inputMapping != null ; assert outputMapping != null ; LOG . debug ( "" , this ) ; Map < Object , FlowElement > unifier = Maps . create ( ) ; Map < FlowElement , FlowElement > unifiedElements = Maps . create ( ) ; Map < FlowElementInput , FlowElementInput > unifiedInputs = Maps . create ( ) ; Map < FlowElementOutput , FlowElementOutput > unifiedOutputs = Maps . create ( ) ; for ( Map . Entry < FlowElement , FlowElement > entry : elementMapping . entrySet ( ) ) { FlowElement orig = entry . getKey ( ) ; FlowElement dest = entry . getValue ( ) ; assert orig . getIdentity ( ) . equals ( orig . getIdentity ( ) ) ; FlowElement unified ; if ( unifier . containsKey ( orig . getIdentity ( ) ) == false ) { unified = dest ; unifier . put ( orig . getIdentity ( ) , unified ) ; } else { unified = unifier . get ( orig . getIdentity ( ) ) ; LOG . debug ( "" , dest , unified ) ; } unifiedElements . put ( dest , unified ) ; List < FlowElementInput > srcInput = orig . getInputPorts ( ) ; List < FlowElementInput > dstInput = dest . getInputPorts ( ) ; List < FlowElementInput > uniInput = unified . getInputPorts ( ) ; assert srcInput . size ( ) == uniInput . size ( ) ; for ( int i = , n = srcInput . size ( ) ; i < n ; i ++ ) { if ( inputMapping . containsKey ( srcInput . get ( i ) ) ) { inputMapping . put ( srcInput . get ( i ) , uniInput . get ( i ) ) ; unifiedInputs . put ( dstInput . get ( i ) , uniInput . get ( i ) ) ; } } List < FlowElementOutput > srcOutput = orig . getOutputPorts ( ) ; List < FlowElementOutput > dstOutput = dest . getOutputPorts ( ) ; List < FlowElementOutput > uniOutput = unified . getOutputPorts ( ) ; assert srcOutput . size ( ) == uniOutput . size ( ) ; for ( int i = , n = srcOutput . size ( ) ; i < n ; i ++ ) { if ( outputMapping . containsKey ( srcOutput . get ( i ) ) ) { outputMapping . put ( srcOutput . get ( i ) , uniOutput . get ( i ) ) ; unifiedOutputs . put ( dstOutput . get ( i ) , uniOutput . get ( i ) ) ; } } } for ( Map . Entry < FlowElement , FlowElement > entry : elementMapping . entrySet ( ) ) { FlowElement elem = entry . getValue ( ) ; FlowElement unified = unifiedElements . get ( elem ) ; assert unified != null ; if ( elem != unified ) { List < FlowElementInput > srcInput = elem . getInputPorts ( ) ; List < FlowElementInput > uniInput = unified . getInputPorts ( ) ; assert srcInput . size ( ) == uniInput . size ( ) ; for ( int i = , n = srcInput . size ( ) ; i < n ; i ++ ) { FlowElementInput srcPort = srcInput . get ( i ) ; FlowElementInput uniPort = uniInput . get ( i ) ; for ( PortConnection conn : srcPort . getConnected ( ) ) { FlowElementOutput opposite = unifiedOutputs . get ( conn . getUpstream ( ) ) ; assert opposite != null ; PortConnection . connect ( opposite , uniPort ) ; } srcPort . disconnectAll ( ) ; } } } for ( FlowElement elem : elementMapping . values ( ) ) { FlowElement unified = unifiedElements . get ( elem ) ; assert unified != null ; if ( elem != unified ) { List < FlowElementOutput > srcOutput = elem . getOutputPorts ( ) ; List < FlowElementOutput > uniOutput = unified . getOutputPorts ( ) ; assert srcOutput . size ( ) == uniOutput . size ( ) ; for ( int i = , n = srcOutput . size ( ) ; i < n ; i ++ ) { FlowElementOutput srcPort = srcOutput . get ( i ) ; FlowElementOutput uniPort = uniOutput . get ( i ) ; for ( PortConnection conn : srcPort . getConnected ( ) ) { FlowElementInput opposite = unifiedInputs . get ( conn . getDownstream ( ) ) ; assert opposite != null ; PortConnection . connect ( uniPort , opposite ) ; } srcPort . disconnectAll ( ) ; } } } for ( Map . Entry < FlowElement , FlowElement > entry : elementMapping . entrySet ( ) ) { FlowElement elem = entry . getValue ( ) ; FlowElement unified = unifiedElements . get ( elem ) ; assert unified != null ; entry . setValue ( unified ) ; } this . elements = Sets . from ( elementMapping . values ( ) ) ; } private void unifyInputs ( Map < FlowElement , FlowElement > elementMapping , Map < FlowElementInput , FlowElementInput > inputMapping , Map < FlowElementOutput , FlowElementOutput > outputMapping ) { assert elementMapping != null ; assert inputMapping != null ; assert outputMapping != null ; Map < FlowElementInput , FlowBlock . Input > map = Maps . create ( ) ; for ( Iterator < FlowBlock . Input > iter = blockInputs . iterator ( ) ; iter . hasNext ( ) ; ) { FlowBlock . Input blockPort = iter . next ( ) ; FlowElementInput elementPort = inputMapping . get ( blockPort . getElementPort ( ) ) ; assert elementPort != null ; FlowBlock . Input unified = map . get ( elementPort ) ; if ( unified == null ) { map . put ( elementPort , blockPort ) ; blockPort . setElementPort ( elementPort ) ; } else { LOG . debug ( "" , blockPort ) ; iter . remove ( ) ; for ( FlowBlock . Connection conn : blockPort . getConnections ( ) ) { FlowBlock . Output opposite = conn . getUpstream ( ) ; FlowBlock . connect ( opposite , unified ) ; } blockPort . disconnect ( ) ; } } } private void unifyOutputs ( Map < FlowElement , FlowElement > elementMapping , Map < FlowElementInput , FlowElementInput > inputMapping , Map < FlowElementOutput , FlowElementOutput > outputMapping ) { assert elementMapping != null ; assert outputMapping != null ; assert inputMapping != null ; Map < FlowElementOutput , FlowBlock . Output > map = Maps . create ( ) ; for ( Iterator < FlowBlock . Output > iter = blockOutputs . iterator ( ) ; iter . hasNext ( ) ; ) { FlowBlock . Output blockPort = iter . next ( ) ; FlowElementOutput elementPort = outputMapping . get ( blockPort . getElementPort ( ) ) ; assert elementPort != null ; FlowBlock . Output unified = map . get ( elementPort ) ; if ( unified == null ) { map . put ( elementPort , blockPort ) ; blockPort . setElementPort ( elementPort ) ; } else { LOG . debug ( "" , blockPort ) ; iter . remove ( ) ; for ( FlowBlock . Connection conn : blockPort . getConnections ( ) ) { FlowBlock . Input opposite = conn . getDownstream ( ) ; FlowBlock . connect ( unified , opposite ) ; } blockPort . disconnect ( ) ; } } } public boolean compaction ( ) { if ( detached == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , this ) ) ; } LOG . debug ( "" , this ) ; boolean changed = false ; boolean localChanged ; do { localChanged = false ; changed |= mergeSameBlockEdges ( ) ; changed |= trimDisconnectedBlockEdges ( ) ; changed |= trimDeadElements ( ) ; changed |= trimDeadBlockEdges ( ) ; localChanged |= mergeIdentity ( ) ; changed |= localChanged ; } while ( localChanged ) ; if ( changed ) { collectGarbages ( ) ; } return changed ; } private boolean mergeSameBlockEdges ( ) { boolean changed = false ; LOG . debug ( "" , this ) ; Map < FlowElementInput , FlowBlock . Input > inputMapping = Maps . create ( ) ; for ( FlowBlock . Input port : blockInputs ) { FlowBlock . Input prime = inputMapping . get ( port . getElementPort ( ) ) ; if ( prime != null ) { LOG . debug ( "" , port , this ) ; for ( FlowBlock . Connection conn : port . getConnections ( ) ) { FlowBlock . connect ( conn . getUpstream ( ) , prime ) ; } port . disconnect ( ) ; changed = true ; } else { inputMapping . put ( port . getElementPort ( ) , port ) ; } } Map < FlowElementOutput , FlowBlock . Output > outputMapping = Maps . create ( ) ; for ( FlowBlock . Output port : blockOutputs ) { FlowBlock . Output prime = outputMapping . get ( port . getElementPort ( ) ) ; if ( prime != null ) { LOG . debug ( "" , port , this ) ; for ( FlowBlock . Connection conn : port . getConnections ( ) ) { FlowBlock . connect ( prime , conn . getDownstream ( ) ) ; } port . disconnect ( ) ; changed = true ; } else { outputMapping . put ( port . getElementPort ( ) , port ) ; } } return changed ; } private boolean trimDisconnectedBlockEdges ( ) { boolean changed = false ; LOG . debug ( "" , this ) ; Iterator < FlowBlock . Input > inputs = blockInputs . iterator ( ) ; while ( inputs . hasNext ( ) ) { FlowBlock . Input port = inputs . next ( ) ; if ( port . getConnections ( ) . isEmpty ( ) ) { LOG . debug ( "" , port , this ) ; inputs . remove ( ) ; changed = true ; } } Iterator < FlowBlock . Output > outputs = blockOutputs . iterator ( ) ; while ( outputs . hasNext ( ) ) { FlowBlock . Output port = outputs . next ( ) ; if ( port . getConnections ( ) . isEmpty ( ) ) { LOG . debug ( "" , port , this ) ; outputs . remove ( ) ; changed = true ; } } return changed ; } private boolean trimDeadElements ( ) { boolean changed = false ; LOG . debug ( "" , this ) ; Set < FlowElement > blockEdge = collectBlockEdges ( ) ; Set < FlowElement > removed = Sets . create ( ) ; LinkedList < FlowElement > work = new LinkedList < FlowElement > ( ) ; work . addAll ( elements ) ; while ( work . isEmpty ( ) == false ) { FlowElement element = work . removeFirst ( ) ; if ( removed . contains ( element ) ) { continue ; } if ( blockEdge . contains ( element ) ) { continue ; } if ( FlowGraphUtil . isAlwaysEmpty ( element ) ) { LOG . debug ( "" , element , this ) ; work . addAll ( FlowGraphUtil . getSuccessors ( element ) ) ; remove ( element ) ; removed . add ( element ) ; changed = true ; } else if ( FlowGraphUtil . isAlwaysStop ( element ) && FlowGraphUtil . hasMandatorySideEffect ( element ) == false ) { LOG . debug ( "" , element , this ) ; work . addAll ( FlowGraphUtil . getPredecessors ( element ) ) ; remove ( element ) ; removed . add ( element ) ; changed = true ; } } return changed ; } private boolean trimDeadBlockEdges ( ) { boolean changed = false ; LOG . debug ( "" , this ) ; Set < FlowElement > inputElements = Sets . create ( ) ; Set < FlowElement > outputElements = Sets . create ( ) ; for ( FlowBlock . Output output : blockOutputs ) { outputElements . add ( output . getElementPort ( ) . getOwner ( ) ) ; } Iterator < FlowBlock . Input > inputs = blockInputs . iterator ( ) ; while ( inputs . hasNext ( ) ) { FlowBlock . Input port = inputs . next ( ) ; FlowElement element = port . getElementPort ( ) . getOwner ( ) ; if ( FlowGraphUtil . hasSuccessors ( element ) == false && FlowGraphUtil . hasMandatorySideEffect ( element ) == false && outputElements . contains ( element ) == false ) { LOG . debug ( "" , port , this ) ; port . disconnect ( ) ; inputs . remove ( ) ; changed = true ; } else { inputElements . add ( element ) ; } } Iterator < FlowBlock . Output > outputs = blockOutputs . iterator ( ) ; while ( outputs . hasNext ( ) ) { FlowBlock . Output port = outputs . next ( ) ; FlowElement element = port . getElementPort ( ) . getOwner ( ) ; if ( FlowGraphUtil . hasPredecessors ( element ) == false && inputElements . contains ( element ) == false ) { LOG . debug ( "" , port , this ) ; port . disconnect ( ) ; outputs . remove ( ) ; changed = true ; } } return changed ; } private boolean mergeIdentity ( ) { boolean changed = false ; boolean foundTarget = false ; Map < FlowBlock . Input , List < FlowBlock . Output > > targets = Maps . create ( ) ; for ( FlowBlock . Output output : blockOutputs ) { FlowElement element = output . getElementPort ( ) . getOwner ( ) ; if ( element . getDescription ( ) . getKind ( ) != FlowElementKind . PSEUD ) { continue ; } if ( output . getConnections ( ) . size ( ) != ) { continue ; } FlowBlock . Input opposite = output . getConnections ( ) . get ( ) . getDownstream ( ) ; List < FlowBlock . Output > list = targets . get ( opposite ) ; if ( list == null ) { list = new ArrayList < FlowBlock . Output > ( ) ; targets . put ( opposite , list ) ; } else { foundTarget = true ; } list . add ( output ) ; } if ( foundTarget == false ) { return changed ; } Map < FlowElementInput , FlowBlock . Input > inputs = Maps . create ( ) ; for ( FlowBlock . Input input : blockInputs ) { FlowElementInput elementInput = input . getElementPort ( ) ; assert inputs . containsKey ( elementInput ) == false ; inputs . put ( elementInput , input ) ; } for ( Map . Entry < FlowBlock . Input , List < FlowBlock . Output > > entry : targets . entrySet ( ) ) { List < FlowBlock . Output > upstream = entry . getValue ( ) ; if ( upstream . size ( ) == ) { continue ; } FlowElement primaryElement = upstream . get ( ) . getElementPort ( ) . getOwner ( ) ; assert primaryElement . getDescription ( ) . getKind ( ) == FlowElementKind . PSEUD ; assert primaryElement . getInputPorts ( ) . size ( ) == ; FlowElementInput primaryInput = primaryElement . getInputPorts ( ) . get ( ) ; FlowBlock . Input primarySource = inputs . get ( primaryInput ) ; assert primarySource != null ; for ( int i = , n = upstream . size ( ) ; i < n ; i ++ ) { FlowBlock . Output otherTarget = upstream . get ( i ) ; FlowElement otherElement = otherTarget . getElementPort ( ) . getOwner ( ) ; LOG . debug ( "" , otherElement , primaryElement ) ; assert otherElement . getDescription ( ) . getKind ( ) == FlowElementKind . PSEUD ; assert otherElement . getInputPorts ( ) . size ( ) == ; FlowElementInput otherInput = otherElement . getInputPorts ( ) . get ( ) ; FlowBlock . Input otherSource = inputs . get ( otherInput ) ; assert otherSource != null ; for ( FlowBlock . Connection conn : otherSource . getConnections ( ) ) { FlowBlock . connect ( conn . getUpstream ( ) , primarySource ) ; } otherSource . disconnect ( ) ; otherTarget . disconnect ( ) ; changed = true ; } } return changed ; } public boolean collectGarbages ( ) { LOG . debug ( "" , this ) ; Set < FlowElement > blockEdge = collectBlockEdges ( ) ; boolean changed = false ; LOOP : for ( Iterator < FlowElement > iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { FlowElement element = iter . next ( ) ; if ( blockEdge . contains ( element ) ) { continue ; } for ( FlowElementInput input : element . getInputPorts ( ) ) { if ( input . getConnected ( ) . isEmpty ( ) == false ) { continue LOOP ; } } for ( FlowElementOutput output : element . getOutputPorts ( ) ) { if ( output . getConnected ( ) . isEmpty ( ) == false ) { continue LOOP ; } } iter . remove ( ) ; changed = true ; } return changed ; } private void remove ( FlowElement element ) { assert element != null ; elements . remove ( element ) ; FlowGraphUtil . disconnect ( element ) ; } private Set < FlowElement > collectBlockEdges ( ) { Set < FlowElement > blockEdge = Sets . create ( ) ; for ( FlowBlock . Input input : getBlockInputs ( ) ) { blockEdge . add ( input . getElementPort ( ) . getOwner ( ) ) ; } for ( FlowBlock . Output output : getBlockOutputs ( ) ) { blockEdge . add ( output . getElementPort ( ) . getOwner ( ) ) ; } return blockEdge ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , String . valueOf ( serialNumber ) , isReduceBlock ( ) ? "" : "" , getBlockInputs ( ) . isEmpty ( ) ? "" : getBlockInputs ( ) . get ( ) ) ; } public class Input { private FlowElementInput input ; private final List < Connection > connections ; private Set < PortConnection > originalConnections ; public Input ( FlowElementInput input , Set < PortConnection > originalConnections ) { Precondition . checkMustNotBeNull ( input , "" ) ; this . input = input ; this . connections = Lists . create ( ) ; this . originalConnections = originalConnections ; } public Set < PortConnection > getOriginalConnections ( ) { return originalConnections ; } public FlowBlock getOwner ( ) { return FlowBlock . this ; } public FlowElementInput getElementPort ( ) { return this . input ; } public List < Connection > getConnections ( ) { return this . connections ; } void setElementPort ( FlowElementInput port ) { assert port != null ; this . input = port ; this . originalConnections = Collections . emptySet ( ) ; } void addConnection ( Connection conn ) { assert conn != null ; connections . add ( conn ) ; } void disconnect ( ) { for ( Connection conn : Lists . from ( connections ) ) { conn . disconnect ( ) ; } } @ Override public String toString ( ) { return MessageFormat . format ( "" , getElementPort ( ) , String . valueOf ( FlowBlock . this . hashCode ( ) ) ) ; } } public class Output { private FlowElementOutput output ; private final List < Connection > connections ; private Set < PortConnection > originalConnections ; public Output ( FlowElementOutput output , Set < PortConnection > originalConnections ) { Precondition . checkMustNotBeNull ( output , "" ) ; this . output = output ; this . connections = Lists . create ( ) ; this . originalConnections = originalConnections ; } boolean isConnected ( FlowBlock . Input downstream ) { for ( Connection conn : connections ) { if ( conn . getDownstream ( ) == downstream ) { return true ; } } return false ; } public Set < PortConnection > getOriginalConnections ( ) { return originalConnections ; } public FlowBlock getOwner ( ) { return FlowBlock . this ; } public FlowElementOutput getElementPort ( ) { return this . output ; } public List < Connection > getConnections ( ) { return this . connections ; } void setElementPort ( FlowElementOutput port ) { assert port != null ; this . output = port ; this . originalConnections = Collections . emptySet ( ) ; } void addConnection ( Connection conn ) { assert conn != null ; connections . add ( conn ) ; } void disconnect ( ) { for ( Connection conn : Lists . from ( connections ) ) { conn . disconnect ( ) ; } } @ Override public String toString ( ) { return MessageFormat . format ( "" , getElementPort ( ) , String . valueOf ( FlowBlock . this . hashCode ( ) ) ) ; } } public static class Connection { private final FlowBlock . Output upstream ; private final FlowBlock . Input downstream ; public Connection ( Output upstream , Input downstream ) { Precondition . checkMustNotBeNull ( upstream , "" ) ; Precondition . checkMustNotBeNull ( downstream , "" ) ; this . upstream = upstream ; this . downstream = downstream ; } public FlowBlock . Output getUpstream ( ) { return upstream ; } public FlowBlock . Input getDownstream ( ) { return downstream ; } public void disconnect ( ) { upstream . getConnections ( ) . remove ( this ) ; downstream . getConnections ( ) . remove ( this ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getUpstream ( ) , getDownstream ( ) ) ; } } } package com . asakusafw . compiler . flow . plan ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; public class StageGraph { private FlowBlock input ; private FlowBlock output ; private List < StageBlock > stages ; public StageGraph ( FlowBlock input , FlowBlock output , List < StageBlock > stages ) { Precondition . checkMustNotBeNull ( input , "" ) ; Precondition . checkMustNotBeNull ( output , "" ) ; Precondition . checkMustNotBeNull ( stages , "" ) ; this . input = input ; this . output = output ; this . stages = Lists . from ( stages ) ; } public FlowBlock getInput ( ) { return input ; } public FlowBlock getOutput ( ) { return output ; } public List < StageBlock > getStages ( ) { return stages ; } } package com . asakusafw . compiler . flow . plan ; import java . text . MessageFormat ; import java . util . List ; import java . util . Set ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; public class FlowPath { private final Direction direction ; private final Set < FlowElement > startings ; private final Set < FlowElement > passings ; private final Set < FlowElement > arrivals ; public FlowPath ( Direction direction , Set < FlowElement > startings , Set < FlowElement > passings , Set < FlowElement > arrivals ) { Precondition . checkMustNotBeNull ( direction , "" ) ; Precondition . checkMustNotBeNull ( startings , "" ) ; Precondition . checkMustNotBeNull ( passings , "" ) ; Precondition . checkMustNotBeNull ( arrivals , "" ) ; this . direction = direction ; this . startings = Sets . freeze ( startings ) ; this . passings = Sets . freeze ( passings ) ; this . arrivals = Sets . freeze ( arrivals ) ; } public Direction getDirection ( ) { return this . direction ; } public Set < FlowElement > getStartings ( ) { return this . startings ; } public Set < FlowElement > getPassings ( ) { return this . passings ; } public Set < FlowElement > getArrivals ( ) { return this . arrivals ; } public FlowBlock createBlock ( FlowGraph graph , int blockSequence , boolean includeStartings , boolean includeArrivals ) { Precondition . checkMustNotBeNull ( graph , "" ) ; if ( direction != Direction . FORWARD ) { throw new IllegalStateException ( "" ) ; } if ( includeStartings == false && includeArrivals == false && passings . isEmpty ( ) ) { throw new IllegalArgumentException ( ) ; } Set < FlowElement > elements = createBlockElements ( includeStartings , includeArrivals ) ; List < PortConnection > inputs = createBlockInputs ( includeStartings ) ; List < PortConnection > outputs = createBlockOutputs ( includeArrivals ) ; return new FlowBlock ( blockSequence , graph , inputs , outputs , elements ) ; } private List < PortConnection > createBlockInputs ( boolean includeStartings ) { List < PortConnection > results = Lists . create ( ) ; if ( includeStartings ) { for ( FlowElement element : startings ) { for ( FlowElementInput input : element . getInputPorts ( ) ) { results . addAll ( input . getConnected ( ) ) ; } } } else { for ( FlowElement element : startings ) { for ( FlowElementOutput output : element . getOutputPorts ( ) ) { for ( PortConnection conn : output . getConnected ( ) ) { FlowElement target = conn . getDownstream ( ) . getOwner ( ) ; if ( passings . contains ( target ) || arrivals . contains ( target ) ) { results . add ( conn ) ; } } } } } return results ; } private List < PortConnection > createBlockOutputs ( boolean includeArrivals ) { List < PortConnection > results = Lists . create ( ) ; if ( includeArrivals ) { for ( FlowElement element : arrivals ) { for ( FlowElementOutput output : element . getOutputPorts ( ) ) { results . addAll ( output . getConnected ( ) ) ; } } } else { for ( FlowElement element : arrivals ) { for ( FlowElementInput input : element . getInputPorts ( ) ) { for ( PortConnection conn : input . getConnected ( ) ) { FlowElement target = conn . getUpstream ( ) . getOwner ( ) ; if ( passings . contains ( target ) || startings . contains ( target ) ) { results . add ( conn ) ; } } } } } return results ; } private Set < FlowElement > createBlockElements ( boolean includeStartings , boolean includeArrivals ) { Set < FlowElement > elements = Sets . create ( ) ; elements . addAll ( passings ) ; if ( includeStartings ) { elements . addAll ( startings ) ; } if ( includeArrivals ) { elements . addAll ( arrivals ) ; } return elements ; } public FlowPath union ( FlowPath other ) { Precondition . checkMustNotBeNull ( other , "" ) ; if ( this . direction != other . direction ) { throw new IllegalArgumentException ( "" ) ; } Set < FlowElement > newStartings = Sets . from ( startings ) ; newStartings . addAll ( other . startings ) ; Set < FlowElement > newPassings = Sets . from ( passings ) ; newPassings . addAll ( other . passings ) ; Set < FlowElement > newArrivals = Sets . from ( arrivals ) ; newArrivals . addAll ( other . arrivals ) ; return new FlowPath ( direction , newStartings , newPassings , newArrivals ) ; } public FlowPath transposeIntersect ( FlowPath other ) { Precondition . checkMustNotBeNull ( other , "" ) ; if ( this . direction == other . direction ) { throw new IllegalArgumentException ( "" ) ; } Set < FlowElement > newStartings = Sets . from ( startings ) ; newStartings . retainAll ( other . arrivals ) ; Set < FlowElement > newPassings = Sets . from ( passings ) ; newPassings . retainAll ( other . passings ) ; Set < FlowElement > newArrivals = Sets . from ( arrivals ) ; newArrivals . retainAll ( other . startings ) ; return new FlowPath ( direction , newStartings , newPassings , newArrivals ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , direction , startings , arrivals ) ; } public enum Direction { FORWARD , BACKWORD , } } package com . asakusafw . compiler . flow . plan ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . FlowOut ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; import com . asakusafw . vocabulary . flow . util . PseudElementDescription ; public final class FlowGraphUtil { public static Set < FlowElement > collectElements ( FlowGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; Set < FlowElement > elements = Sets . create ( ) ; for ( FlowIn < ? > in : graph . getFlowInputs ( ) ) { elements . add ( in . getFlowElement ( ) ) ; } for ( FlowOut < ? > out : graph . getFlowOutputs ( ) ) { elements . add ( out . getFlowElement ( ) ) ; } collect ( elements ) ; return elements ; } public static Set < FlowElement > collectFlowParts ( FlowGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; Set < FlowElement > results = Sets . create ( ) ; for ( FlowElement element : collectElements ( graph ) ) { FlowElementDescription description = element . getDescription ( ) ; if ( description . getKind ( ) == FlowElementKind . FLOW_COMPONENT ) { results . add ( element ) ; } } return results ; } public static Set < FlowElement > collectBoundaries ( FlowGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; Set < FlowElement > results = Sets . create ( ) ; for ( FlowElement element : FlowGraphUtil . collectElements ( graph ) ) { if ( FlowGraphUtil . isBoundary ( element ) ) { results . add ( element ) ; } } return results ; } public static Graph < FlowElement > toElementGraph ( FlowGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; Graph < FlowElement > results = Graphs . newInstance ( ) ; for ( FlowElement source : FlowGraphUtil . collectElements ( graph ) ) { results . addEdges ( source , FlowGraphUtil . getSuccessors ( source ) ) ; } return results ; } public static FlowGraph deepCopy ( FlowGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; Map < FlowElement , FlowElement > elemMapping = Maps . create ( ) ; List < FlowIn < ? > > flowInputs = Lists . create ( ) ; for ( FlowIn < ? > orig : graph . getFlowInputs ( ) ) { FlowIn < ? > copy = FlowIn . newInstance ( orig . getDescription ( ) ) ; elemMapping . put ( orig . getFlowElement ( ) , copy . getFlowElement ( ) ) ; flowInputs . add ( copy ) ; } List < FlowOut < ? > > flowOutputs = Lists . create ( ) ; for ( FlowOut < ? > orig : graph . getFlowOutputs ( ) ) { FlowOut < ? > copy = FlowOut . newInstance ( orig . getDescription ( ) ) ; elemMapping . put ( orig . getFlowElement ( ) , copy . getFlowElement ( ) ) ; flowOutputs . add ( copy ) ; } deepCopy ( collectElements ( graph ) , elemMapping , new HashMap < FlowElementInput , FlowElementInput > ( ) , new HashMap < FlowElementOutput , FlowElementOutput > ( ) ) ; FlowGraph copy = new FlowGraph ( graph . getDescription ( ) , flowInputs , flowOutputs ) ; copy . setOrigin ( graph ) ; return copy ; } public static void deepCopy ( Set < FlowElement > elements , Map < FlowElement , FlowElement > elementMapping , Map < FlowElementInput , FlowElementInput > inputMapping , Map < FlowElementOutput , FlowElementOutput > outputMapping ) { Precondition . checkMustNotBeNull ( elements , "" ) ; Precondition . checkMustNotBeNull ( elementMapping , "" ) ; for ( FlowElement orig : elements ) { FlowElement copy = createMapping ( elementMapping , orig ) ; addMapping ( inputMapping , orig . getInputPorts ( ) , copy . getInputPorts ( ) ) ; addMapping ( outputMapping , orig . getOutputPorts ( ) , copy . getOutputPorts ( ) ) ; } for ( Map . Entry < FlowElementInput , FlowElementInput > entry : inputMapping . entrySet ( ) ) { FlowElementInput origIn = entry . getKey ( ) ; FlowElementInput copyIn = entry . getValue ( ) ; for ( FlowElementOutput origOut : origIn . getOpposites ( ) ) { if ( elements . contains ( origOut . getOwner ( ) ) == false ) { continue ; } FlowElementOutput copyOut = outputMapping . get ( origOut ) ; assert copyOut != null ; PortConnection . connect ( copyOut , copyIn ) ; } } } private static FlowElement createMapping ( Map < FlowElement , FlowElement > elemMapping , FlowElement orig ) { assert elemMapping != null ; assert orig != null ; FlowElement mapped = elemMapping . get ( orig ) ; if ( mapped != null ) { return mapped ; } FlowElement copy ; FlowElementDescription description = orig . getDescription ( ) ; if ( description . getKind ( ) == FlowElementKind . FLOW_COMPONENT ) { FlowPartDescription fcd = ( FlowPartDescription ) description ; FlowGraph subgraph = deepCopy ( fcd . getFlowGraph ( ) ) ; FlowPartDescription partCopy = new FlowPartDescription ( subgraph ) ; copy = new FlowElement ( partCopy , orig . getAttributeOverride ( ) ) ; } else { copy = orig . copy ( ) ; } elemMapping . put ( orig , copy ) ; return copy ; } private static < T > void addMapping ( Map < T , T > mapping , List < T > source , List < T > target ) { assert mapping != null ; assert source != null ; assert target != null ; assert source . size ( ) == target . size ( ) ; Iterator < T > sIter = source . iterator ( ) ; Iterator < T > tIter = target . iterator ( ) ; while ( sIter . hasNext ( ) ) { assert tIter . hasNext ( ) ; T s = sIter . next ( ) ; T t = tIter . next ( ) ; assert mapping . containsKey ( s ) == false ; mapping . put ( s , t ) ; } assert tIter . hasNext ( ) == false ; } private static void collect ( Set < FlowElement > collected ) { assert collected != null ; LinkedList < FlowElement > work = new LinkedList < FlowElement > ( collected ) ; while ( work . isEmpty ( ) == false ) { FlowElement first = work . removeFirst ( ) ; if ( collected . contains ( first ) == false ) { collected . add ( first ) ; } for ( FlowElement pred : FlowGraphUtil . getPredecessors ( first ) ) { if ( collected . contains ( pred ) == false ) { work . add ( pred ) ; } } for ( FlowElement succ : FlowGraphUtil . getSuccessors ( first ) ) { if ( collected . contains ( succ ) == false ) { work . add ( succ ) ; } } } } public static boolean hasMandatorySideEffect ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; ObservationCount count = element . getAttribute ( ObservationCount . class ) ; if ( count == null ) { return false ; } return count . atLeastOnce ; } public static boolean hasGlobalSideEffect ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; ObservationCount count = element . getAttribute ( ObservationCount . class ) ; if ( count == null ) { return false ; } return count . atMostOnce ; } public static boolean isAlwaysEmpty ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; List < FlowElementInput > ports = element . getInputPorts ( ) ; if ( ports . isEmpty ( ) ) { return false ; } for ( FlowElementInput input : ports ) { if ( input . getConnected ( ) . isEmpty ( ) == false ) { return false ; } } return true ; } public static boolean isAlwaysStop ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; List < FlowElementOutput > ports = element . getOutputPorts ( ) ; if ( ports . isEmpty ( ) ) { return false ; } for ( FlowElementOutput output : ports ) { if ( output . getConnected ( ) . isEmpty ( ) == false ) { return false ; } } return true ; } public static boolean isIdentity ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; FlowElementDescription description = element . getDescription ( ) ; return isBoundary ( element ) == false && description . getKind ( ) == FlowElementKind . PSEUD && element . getInputPorts ( ) . size ( ) == && element . getOutputPorts ( ) . size ( ) == ; } public static boolean splitIdentity ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; if ( isIdentity ( element ) == false ) { throw new IllegalArgumentException ( "" ) ; } assert element . getInputPorts ( ) . size ( ) == ; assert element . getOutputPorts ( ) . size ( ) == ; FlowElementInput input = element . getInputPorts ( ) . get ( ) ; FlowElementOutput output = element . getOutputPorts ( ) . get ( ) ; Set < PortConnection > sources = Sets . from ( input . getConnected ( ) ) ; Set < PortConnection > targets = Sets . from ( output . getConnected ( ) ) ; if ( sources . size ( ) <= && targets . size ( ) <= ) { return false ; } else { for ( PortConnection source : sources ) { FlowElementOutput upstream = source . getUpstream ( ) ; for ( PortConnection target : targets ) { FlowElementInput downstream = target . getDownstream ( ) ; connectWithIdentity ( element , upstream , downstream ) ; } } disconnect ( element ) ; return true ; } } public static void stop ( FlowElementOutput output ) { Precondition . checkMustNotBeNull ( output , "" ) ; FlowElementDescription desc = new PseudElementDescription ( "" , output . getDescription ( ) . getDataType ( ) , true , false , FlowBoundary . STAGE ) ; FlowElementResolver resolver = new FlowElementResolver ( desc ) ; FlowElementInput stopIn = resolver . getInput ( PseudElementDescription . INPUT_PORT_NAME ) ; PortConnection . connect ( output , stopIn ) ; } public static void skip ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; List < FlowElementOutput > sources = Lists . create ( ) ; for ( FlowElementInput input : element . getInputPorts ( ) ) { sources . addAll ( input . disconnectAll ( ) ) ; } List < FlowElementInput > targets = Lists . create ( ) ; for ( FlowElementOutput output : element . getOutputPorts ( ) ) { targets . addAll ( output . disconnectAll ( ) ) ; } for ( FlowElementOutput upstream : sources ) { for ( FlowElementInput downstream : targets ) { PortConnection . connect ( upstream , downstream ) ; } } } public static boolean isBoundary ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; return isStageBoundary ( element ) || isShuffleBoundary ( element ) ; } public static boolean isShuffleBoundary ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; return element . getAttribute ( FlowBoundary . class ) == FlowBoundary . SHUFFLE ; } public static boolean isStageBoundary ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; return element . getAttribute ( FlowBoundary . class ) == FlowBoundary . STAGE ; } public static boolean isStagePadding ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; return isStageBoundary ( element ) && element . getDescription ( ) . getKind ( ) == FlowElementKind . PSEUD ; } public static FlowPath getSucceedBoundaryPath ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; Set < FlowElement > startings = Sets . create ( ) ; startings . add ( element ) ; return getSuccessBoundaryPath ( startings ) ; } private static FlowPath getSuccessBoundaryPath ( Set < FlowElement > startings ) { assert startings != null ; Set < FlowElement > passings = Sets . create ( ) ; Set < FlowElement > arrivals = Sets . create ( ) ; Set < FlowElement > saw = Sets . create ( ) ; LinkedList < FlowElement > successors = new LinkedList < FlowElement > ( ) ; for ( FlowElement starting : startings ) { addSuccessors ( successors , starting ) ; } while ( successors . isEmpty ( ) == false ) { FlowElement successor = successors . removeFirst ( ) ; if ( saw . contains ( successor ) ) { continue ; } saw . add ( successor ) ; if ( isBoundary ( successor ) ) { arrivals . add ( successor ) ; } else { passings . add ( successor ) ; addSuccessors ( successors , successor ) ; } } return new FlowPath ( FlowPath . Direction . FORWARD , startings , passings , arrivals ) ; } public static FlowPath getPredeceaseBoundaryPath ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; Set < FlowElement > startings = Sets . create ( ) ; startings . add ( element ) ; return getPredeceaseBoundaryPath ( startings ) ; } private static FlowPath getPredeceaseBoundaryPath ( Set < FlowElement > startings ) { assert startings != null ; Set < FlowElement > passings = Sets . create ( ) ; Set < FlowElement > arrivals = Sets . create ( ) ; Set < FlowElement > saw = Sets . create ( ) ; LinkedList < FlowElement > predecessors = new LinkedList < FlowElement > ( ) ; for ( FlowElement starting : startings ) { addPredecessors ( predecessors , starting ) ; } while ( predecessors . isEmpty ( ) == false ) { FlowElement predecessor = predecessors . removeFirst ( ) ; if ( saw . contains ( predecessor ) ) { continue ; } saw . add ( predecessor ) ; if ( isBoundary ( predecessor ) ) { arrivals . add ( predecessor ) ; } else { passings . add ( predecessor ) ; addPredecessors ( predecessors , predecessor ) ; } } return new FlowPath ( FlowPath . Direction . BACKWORD , startings , passings , arrivals ) ; } public static FlowPath union ( Collection < FlowPath > paths ) { Precondition . checkMustNotBeNull ( paths , "" ) ; if ( paths . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } Iterator < FlowPath > iter = paths . iterator ( ) ; assert iter . hasNext ( ) ; FlowPath left = iter . next ( ) ; while ( iter . hasNext ( ) ) { FlowPath right = iter . next ( ) ; left = left . union ( right ) ; } return left ; } public static boolean hasSuccessors ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; for ( FlowElementOutput output : element . getOutputPorts ( ) ) { if ( output . getConnected ( ) . isEmpty ( ) == false ) { return true ; } } return false ; } public static boolean hasPredecessors ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; for ( FlowElementInput input : element . getInputPorts ( ) ) { if ( input . getConnected ( ) . isEmpty ( ) == false ) { return true ; } } return false ; } public static Set < FlowElement > getSuccessors ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; Set < FlowElement > results = Sets . create ( ) ; addSuccessors ( results , element ) ; return results ; } private static void addSuccessors ( Collection < FlowElement > target , FlowElement element ) { assert target != null ; assert element != null ; for ( FlowElementOutput output : element . getOutputPorts ( ) ) { for ( FlowElementInput opposite : output . getOpposites ( ) ) { target . add ( opposite . getOwner ( ) ) ; } } } public static Set < FlowElement > getPredecessors ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; Set < FlowElement > results = Sets . create ( ) ; addPredecessors ( results , element ) ; return results ; } private static void addPredecessors ( Collection < FlowElement > target , FlowElement element ) { assert target != null ; assert element != null ; for ( FlowElementInput input : element . getInputPorts ( ) ) { for ( FlowElementOutput opposite : input . getOpposites ( ) ) { target . add ( opposite . getOwner ( ) ) ; } } } public static Set < FlowElement > getSucceedingBoundaries ( FlowElementOutput output ) { Precondition . checkMustNotBeNull ( output , "" ) ; LinkedList < FlowElement > nextSuccessors = new LinkedList < FlowElement > ( ) ; for ( FlowElementInput next : output . getOpposites ( ) ) { nextSuccessors . add ( next . getOwner ( ) ) ; } if ( nextSuccessors . isEmpty ( ) ) { return Collections . emptySet ( ) ; } Set < FlowElement > saw = Sets . create ( ) ; Set < FlowElement > results = Sets . create ( ) ; while ( nextSuccessors . isEmpty ( ) == false ) { FlowElement successor = nextSuccessors . removeFirst ( ) ; if ( saw . contains ( successor ) ) { continue ; } saw . add ( successor ) ; if ( isBoundary ( successor ) ) { results . add ( successor ) ; } else { addSuccessors ( nextSuccessors , successor ) ; } } return results ; } public static Set < PortConnection > getSucceedingConnections ( PortConnection start , Set < PortConnection > connections ) { Precondition . checkMustNotBeNull ( start , "" ) ; Precondition . checkMustNotBeNull ( connections , "" ) ; LinkedList < PortConnection > next = new LinkedList < PortConnection > ( ) ; next . add ( start ) ; Set < PortConnection > results = Sets . create ( ) ; while ( next . isEmpty ( ) == false ) { PortConnection successor = next . removeFirst ( ) ; if ( connections . contains ( successor ) ) { results . add ( successor ) ; } else { FlowElementInput nextInput = successor . getDownstream ( ) ; for ( FlowElementOutput output : nextInput . getOwner ( ) . getOutputPorts ( ) ) { next . addAll ( output . getConnected ( ) ) ; } } } return results ; } public static void inlineFlowPart ( FlowElement element , FlowElementAttribute ... attributes ) { Precondition . checkMustNotBeNull ( element , "" ) ; FlowElementDescription description = element . getDescription ( ) ; if ( description . getKind ( ) != FlowElementKind . FLOW_COMPONENT ) { throw new IllegalArgumentException ( "" ) ; } FlowPartDescription component = ( FlowPartDescription ) description ; FlowGraph graph = component . getFlowGraph ( ) ; List < FlowElementInput > externalInputs = element . getInputPorts ( ) ; List < FlowElementOutput > internalInputs = Lists . create ( ) ; for ( FlowIn < ? > fin : graph . getFlowInputs ( ) ) { internalInputs . add ( fin . toOutputPort ( ) ) ; } bypass ( externalInputs , internalInputs , attributes ) ; List < FlowElementOutput > externalOutputs = element . getOutputPorts ( ) ; List < FlowElementInput > internalOutputs = Lists . create ( ) ; for ( FlowOut < ? > fout : graph . getFlowOutputs ( ) ) { internalOutputs . add ( fout . toInputPort ( ) ) ; } bypass ( internalOutputs , externalOutputs , attributes ) ; for ( FlowIn < ? > fin : graph . getFlowInputs ( ) ) { disconnect ( fin . getFlowElement ( ) ) ; } for ( FlowOut < ? > fout : graph . getFlowOutputs ( ) ) { disconnect ( fout . getFlowElement ( ) ) ; } disconnect ( element ) ; } private static void bypass ( List < FlowElementInput > inputs , List < FlowElementOutput > outputs , FlowElementAttribute ... attributes ) { assert inputs != null ; assert outputs != null ; if ( inputs . size ( ) != outputs . size ( ) ) { throw new IllegalArgumentException ( ) ; } Iterator < FlowElementInput > inputIterator = inputs . iterator ( ) ; Iterator < FlowElementOutput > outputIterator = outputs . iterator ( ) ; while ( inputIterator . hasNext ( ) ) { assert outputIterator . hasNext ( ) ; FlowElementInput input = inputIterator . next ( ) ; FlowElementOutput output = outputIterator . next ( ) ; bypass ( input , output , attributes ) ; } assert outputIterator . hasNext ( ) == false ; } private static void bypass ( FlowElementInput input , FlowElementOutput output , FlowElementAttribute ... attributes ) { assert input != null ; assert output != null ; assert attributes != null ; Collection < FlowElementOutput > upstreams = input . disconnectAll ( ) ; Collection < FlowElementInput > downstreams = output . disconnectAll ( ) ; for ( FlowElementOutput upstream : upstreams ) { for ( FlowElementInput downstream : downstreams ) { if ( attributes . length >= ) { FlowElementDescription desc = new PseudElementDescription ( "" , output . getDescription ( ) . getDataType ( ) , true , true , attributes ) ; FlowElementResolver resolver = new FlowElementResolver ( desc ) ; FlowElementInput bypassIn = resolver . getInput ( PseudElementDescription . INPUT_PORT_NAME ) ; FlowElementOutput bypassOut = resolver . getOutput ( PseudElementDescription . OUTPUT_PORT_NAME ) ; PortConnection . connect ( upstream , bypassIn ) ; PortConnection . connect ( bypassOut , downstream ) ; } else { PortConnection . connect ( upstream , downstream ) ; } } } } private static void connectWithIdentity ( FlowElement element , FlowElementOutput upstream , FlowElementInput downstream ) { assert element != null ; assert upstream != null ; assert downstream != null ; assert element . getDescription ( ) . getKind ( ) == FlowElementKind . PSEUD ; FlowElementResolver resolver = new FlowElementResolver ( element . copy ( ) ) ; FlowElementInput input = resolver . getInput ( PseudElementDescription . INPUT_PORT_NAME ) ; FlowElementOutput output = resolver . getOutput ( PseudElementDescription . OUTPUT_PORT_NAME ) ; PortConnection . connect ( upstream , input ) ; PortConnection . connect ( output , downstream ) ; } public static void disconnect ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; for ( FlowElementInput input : element . getInputPorts ( ) ) { input . disconnectAll ( ) ; } for ( FlowElementOutput output : element . getOutputPorts ( ) ) { output . disconnectAll ( ) ; } } public static void insertCheckpoint ( FlowElementOutput output ) { Precondition . checkMustNotBeNull ( output , "" ) ; insertElement ( output , "" , FlowBoundary . STAGE ) ; } public static void insertIdentity ( FlowElementOutput output ) { Precondition . checkMustNotBeNull ( output , "" ) ; insertElement ( output , "" ) ; } private static void insertElement ( FlowElementOutput output , String name , FlowElementAttribute ... attributes ) { assert output != null ; assert name != null ; assert attributes != null ; Collection < FlowElementInput > originalDownstreams = output . disconnectAll ( ) ; FlowElementDescription desc = new PseudElementDescription ( name , output . getDescription ( ) . getDataType ( ) , true , true , attributes ) ; FlowElementResolver resolver = new FlowElementResolver ( desc ) ; FlowElementInput insertIn = resolver . getInput ( PseudElementDescription . INPUT_PORT_NAME ) ; PortConnection . connect ( output , insertIn ) ; FlowElementOutput insertOut = resolver . getOutput ( PseudElementDescription . OUTPUT_PORT_NAME ) ; for ( FlowElementInput downstream : originalDownstreams ) { PortConnection . connect ( insertOut , downstream ) ; } } private FlowGraphUtil ( ) { return ; } } package com . asakusafw . compiler . flow . plan ; import java . text . MessageFormat ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; public class StageBlock { static final Logger LOG = LoggerFactory . getLogger ( StageBlock . class ) ; private static final int NOT_SET = - ; private final Set < FlowBlock > mapBlocks ; private final Set < FlowBlock > reduceBlocks ; private int stageNumber = NOT_SET ; public StageBlock ( Set < FlowBlock > mapBlocks , Set < FlowBlock > reduceBlocks ) { Precondition . checkMustNotBeNull ( mapBlocks , "" ) ; Precondition . checkMustNotBeNull ( reduceBlocks , "" ) ; this . mapBlocks = Sets . from ( mapBlocks ) ; this . reduceBlocks = Sets . from ( reduceBlocks ) ; } public int getStageNumber ( ) { if ( stageNumber == NOT_SET ) { throw new IllegalStateException ( ) ; } return stageNumber ; } public void setStageNumber ( int stageNumber ) { if ( stageNumber == NOT_SET ) { throw new IllegalArgumentException ( ) ; } LOG . debug ( "" , this , stageNumber ) ; this . stageNumber = stageNumber ; } public Set < FlowBlock > getMapBlocks ( ) { return mapBlocks ; } public Set < FlowBlock > getReduceBlocks ( ) { return reduceBlocks ; } public boolean hasReduceBlocks ( ) { return reduceBlocks . isEmpty ( ) == false ; } public boolean isEmpty ( ) { if ( reduceBlocks . isEmpty ( ) == false ) { return false ; } for ( FlowBlock block : mapBlocks ) { if ( block . isEmpty ( ) == false ) { return false ; } } return true ; } public boolean compaction ( ) { LOG . debug ( "" , this ) ; boolean changed = false ; if ( reduceBlocks . isEmpty ( ) == false ) { return changed ; } for ( Iterator < FlowBlock > iter = mapBlocks . iterator ( ) ; iter . hasNext ( ) ; ) { FlowBlock block = iter . next ( ) ; boolean localChanged = false ; localChanged |= bypass ( block ) ; changed |= localChanged ; if ( localChanged ) { changed |= block . compaction ( ) ; } if ( block . isEmpty ( ) ) { LOG . debug ( "" , this , block ) ; iter . remove ( ) ; changed = true ; } } return changed ; } private boolean bypass ( FlowBlock block ) { assert block != null ; Map < FlowElementOutput , FlowBlock . Output > outputs = Maps . create ( ) ; for ( FlowBlock . Output blockOutput : block . getBlockOutputs ( ) ) { outputs . put ( blockOutput . getElementPort ( ) , blockOutput ) ; } boolean changed = false ; for ( FlowBlock . Input blockInput : block . getBlockInputs ( ) ) { FlowElement element = blockInput . getElementPort ( ) . getOwner ( ) ; if ( FlowGraphUtil . isIdentity ( element ) == false ) { continue ; } FlowElementOutput output = element . getOutputPorts ( ) . get ( ) ; FlowBlock . Output blockOutput = outputs . get ( output ) ; if ( blockOutput == null ) { continue ; } LOG . debug ( "" , blockInput , blockOutput ) ; bypass ( blockInput , blockOutput ) ; changed = true ; } return changed ; } private void bypass ( FlowBlock . Input input , FlowBlock . Output output ) { assert input != null ; assert output != null ; List < FlowBlock . Output > upstreams = Lists . create ( ) ; List < FlowBlock . Connection > inConns = Lists . from ( input . getConnections ( ) ) ; for ( FlowBlock . Connection conn : inConns ) { upstreams . add ( conn . getUpstream ( ) ) ; conn . disconnect ( ) ; } List < FlowBlock . Input > downstreams = Lists . create ( ) ; List < FlowBlock . Connection > outConns = Lists . from ( output . getConnections ( ) ) ; for ( FlowBlock . Connection conn : outConns ) { downstreams . add ( conn . getDownstream ( ) ) ; conn . disconnect ( ) ; } for ( FlowBlock . Output upstream : upstreams ) { for ( FlowBlock . Input downstream : downstreams ) { FlowBlock . connect ( upstream , downstream ) ; } } } @ Override public String toString ( ) { return MessageFormat . format ( "" , stageNumber == NOT_SET ? '' + String . valueOf ( hashCode ( ) ) : String . valueOf ( stageNumber ) , String . valueOf ( mapBlocks . size ( ) ) , String . valueOf ( reduceBlocks . size ( ) ) ) ; } } package com . asakusafw . compiler . flow ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttributeProvider ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; public abstract class LineProcessor extends AbstractFlowElementProcessor { public abstract static class LineProcessorContext extends AbstractProcessorContext { protected final List < Statement > generatedStatements ; protected LineProcessorContext ( FlowCompilingEnvironment environment , FlowElementAttributeProvider element , ImportBuilder importer , NameGenerator names , OperatorDescription desc , Map < FlowResourceDescription , Expression > resources ) { super ( environment , element , importer , names , desc , resources ) ; this . generatedStatements = Lists . create ( ) ; } public void add ( Statement statement ) { Precondition . checkMustNotBeNull ( statement , "" ) ; generatedStatements . add ( statement ) ; } public List < Statement > getGeneratedStatements ( ) { return generatedStatements ; } public Expression createLocalVariable ( java . lang . reflect . Type type , Expression initializer ) { Precondition . checkMustNotBeNull ( type , "" ) ; return createLocalVariable ( Models . toType ( factory , type ) , initializer ) ; } public Expression createLocalVariable ( Type type , Expression initializer ) { Precondition . checkMustNotBeNull ( type , "" ) ; SimpleName name = names . create ( "" ) ; add ( new ExpressionBuilder ( factory , initializer ) . toLocalVariableDeclaration ( importer . resolve ( type ) , name ) ) ; return name ; } } } package com . asakusafw . compiler . flow ; import java . util . LinkedList ; import java . util . regex . Pattern ; import com . asakusafw . compiler . common . Precondition ; public class Location { public static final String WILDCARD_SUFFIX = "" ; private final Location parent ; private final String name ; private boolean prefix ; public Location ( Location parent , String name ) { Precondition . checkMustNotBeNull ( name , "" ) ; if ( parent != null && parent . isPrefix ( ) ) { throw new IllegalArgumentException ( ) ; } this . parent = parent ; this . name = name ; this . prefix = false ; } public Location asPrefix ( ) { Location copy = new Location ( parent , name ) ; copy . prefix = true ; return copy ; } public boolean isPrefix ( ) { return prefix ; } public Location getParent ( ) { return parent ; } public String getName ( ) { return name ; } public Location append ( String lastName ) { Precondition . checkMustNotBeNull ( lastName , "" ) ; return new Location ( this , lastName ) ; } public Location append ( Location suffix ) { Precondition . checkMustNotBeNull ( suffix , "" ) ; LinkedList < String > segments = new LinkedList < String > ( ) ; Location current = suffix ; while ( current != null ) { segments . addFirst ( current . name ) ; current = current . parent ; } current = this ; for ( String segment : segments ) { current = new Location ( current , segment ) ; } if ( suffix . isPrefix ( ) ) { current = current . asPrefix ( ) ; } return current ; } public static Location fromPath ( String pathString , char separator ) { Precondition . checkMustNotBeNull ( pathString , "" ) ; boolean prefix = pathString . endsWith ( WILDCARD_SUFFIX ) ; String normalized = prefix ? pathString . substring ( , pathString . length ( ) - WILDCARD_SUFFIX . length ( ) ) : pathString ; String [ ] segments = normalized . split ( Pattern . quote ( String . valueOf ( separator ) ) ) ; Location current = null ; for ( String segment : segments ) { if ( segment . isEmpty ( ) ) { continue ; } current = new Location ( current , segment ) ; } assert current != null ; if ( prefix ) { current = current . asPrefix ( ) ; } return current ; } public String toPath ( char separator ) { LinkedList < String > segments = new LinkedList < String > ( ) ; Location current = this ; while ( current != null ) { segments . addFirst ( current . name ) ; current = current . parent ; } StringBuilder buf = new StringBuilder ( ) ; buf . append ( segments . removeFirst ( ) ) ; for ( String segment : segments ) { buf . append ( separator ) ; buf . append ( segment ) ; } if ( prefix ) { buf . append ( WILDCARD_SUFFIX ) ; } return buf . toString ( ) ; } public boolean isPrefixOf ( Location other ) { if ( other == null ) { throw new IllegalArgumentException ( "" ) ; } int thisSegments = count ( this ) ; int otherSegments = count ( other ) ; if ( thisSegments > otherSegments ) { return false ; } Location current = other ; for ( int i = , n = otherSegments - thisSegments ; i < n ; i ++ ) { current = current . getParent ( ) ; } return this . equals ( current ) ; } private int count ( Location location ) { int count = ; Location current = location . getParent ( ) ; while ( current != null ) { count ++ ; current = current . getParent ( ) ; } return count ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; Location current = this ; result = prime * result + ( prefix ? : ) ; while ( current != null ) { result = prime * result + current . name . hashCode ( ) ; current = current . parent ; } return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Location other = ( Location ) obj ; Location thisCur = this ; Location otherCur = other ; if ( thisCur . prefix != otherCur . prefix ) { return false ; } while ( thisCur != null && otherCur != null ) { if ( thisCur == otherCur ) { return true ; } if ( thisCur . name . equals ( otherCur . name ) == false ) { return false ; } thisCur = thisCur . parent ; otherCur = otherCur . parent ; } return thisCur == otherCur ; } @ Override public String toString ( ) { return toPath ( '' ) ; } } package com . asakusafw . compiler . flow ; public interface DataClassRepository extends FlowCompilingEnvironment . Initializable { DataClass load ( java . lang . reflect . Type type ) ; } package com . asakusafw . compiler . flow . debugging ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Debug { } package com . asakusafw . compiler . flow . debugging ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LinePartProcessor ; @ TargetOperator ( Debug . class ) public class DebugFlowProcessor extends LinePartProcessor { @ Override public void emitLinePart ( Context context ) { DebuggingAttribute attribute = context . getAttribute ( DebuggingAttribute . class ) ; assert attribute != null ; attribute . processor . emitLinePart ( context ) ; } } package com . asakusafw . compiler . flow . debugging ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; class DebuggingAttribute implements FlowElementAttribute { final LinePartProcessor processor ; DebuggingAttribute ( LinePartProcessor processor ) { this . processor = processor ; } @ Override public Class < ? extends FlowElementAttribute > getDeclaringClass ( ) { return DebuggingAttribute . class ; } } package com . asakusafw . compiler . flow . debugging ; package com . asakusafw . compiler . flow . debugging ; import java . lang . reflect . Type ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; public final class DebuggingUtils { private static final String PORT_IN = "" ; private static final String PORT_OUT = "" ; private DebuggingUtils ( ) { return ; } public static FlowElement debug ( FlowElementInput port , LinePartProcessor delegate ) { FlowElementResolver resolver = createResolver ( port . getDescription ( ) . getDataType ( ) , delegate ) ; for ( FlowElementOutput opposite : port . disconnectAll ( ) ) { PortConnection . connect ( opposite , resolver . getInput ( PORT_IN ) ) ; } PortConnection . connect ( resolver . getOutput ( PORT_OUT ) , port ) ; return resolver . getElement ( ) ; } public static FlowElement debug ( FlowElementOutput port , LinePartProcessor delegate ) { FlowElementResolver resolver = createResolver ( port . getDescription ( ) . getDataType ( ) , delegate ) ; for ( FlowElementInput opposite : port . disconnectAll ( ) ) { PortConnection . connect ( resolver . getOutput ( PORT_OUT ) , opposite ) ; } PortConnection . connect ( port , resolver . getInput ( PORT_IN ) ) ; return resolver . getElement ( ) ; } private static FlowElementResolver createResolver ( Type type , LinePartProcessor delegate ) { FlowElementResolver resolver = new OperatorDescription . Builder ( Debug . class ) . addAttribute ( ObservationCount . AT_LEAST_ONCE ) . addAttribute ( new DebuggingAttribute ( delegate ) ) . addInput ( PORT_IN , type ) . addOutput ( PORT_OUT , type ) . declare ( DebuggingUtils . class , DebuggingUtils . class , "" ) . toResolver ( ) ; return resolver ; } } package com . asakusafw . compiler . flow . jobflow ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Delivery ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Export ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Import ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Process ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Reduce ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . SideData ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Source ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Stage ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Target ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . CompiledReduce ; import com . asakusafw . compiler . flow . stage . CompiledShuffle ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class JobflowAnalyzer { static final Logger LOG = LoggerFactory . getLogger ( JobflowAnalyzer . class ) ; private final FlowCompilingEnvironment environment ; private boolean sawError ; public JobflowAnalyzer ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public boolean hasError ( ) { return sawError ; } public void clearError ( ) { sawError = false ; } public JobflowModel analyze ( StageGraph graph , Collection < StageModel > stageModels ) { Precondition . checkMustNotBeNull ( graph , "" ) ; Precondition . checkMustNotBeNull ( stageModels , "" ) ; LOG . debug ( "" , graph . getInput ( ) . getSource ( ) . getDescription ( ) . getName ( ) ) ; List < Import > imports = analyzeImports ( graph , stageModels ) ; List < Export > exports = analyzeExports ( graph , stageModels ) ; List < Stage > stages = analyzeStages ( stageModels ) ; if ( hasError ( ) ) { return null ; } resolve ( imports , exports , stages ) ; if ( hasError ( ) ) { return null ; } return new JobflowModel ( graph , environment . getBatchId ( ) , environment . getFlowId ( ) , imports , exports , stages ) ; } private List < Import > analyzeImports ( StageGraph graph , Collection < StageModel > stageModels ) { assert graph != null ; assert stageModels != null ; LOG . debug ( "" , graph . getInput ( ) ) ; Set < InputDescription > saw = Sets . create ( ) ; List < Import > results = Lists . create ( ) ; for ( FlowBlock . Output source : graph . getInput ( ) . getBlockOutputs ( ) ) { FlowElement element = source . getElementPort ( ) . getOwner ( ) ; FlowElementDescription desc = element . getDescription ( ) ; if ( desc . getKind ( ) != FlowElementKind . INPUT ) { error ( "" , desc ) ; continue ; } InputDescription description = ( InputDescription ) desc ; saw . add ( description ) ; ExternalIoDescriptionProcessor proc = environment . getExternals ( ) . findProcessor ( description ) ; if ( proc == null ) { error ( "" , desc ) ; continue ; } Import prologue = new Import ( source , description , proc ) ; LOG . debug ( "" , prologue ) ; results . add ( prologue ) ; } Set < InputDescription > sideData = Sets . create ( ) ; for ( StageModel stage : stageModels ) { sideData . addAll ( stage . getSideDataInputs ( ) ) ; } sideData . removeAll ( saw ) ; for ( InputDescription input : sideData ) { ExternalIoDescriptionProcessor proc = environment . getExternals ( ) . findProcessor ( input ) ; if ( proc == null ) { error ( "" , input ) ; continue ; } Import prologue = new Import ( input , proc ) ; LOG . debug ( "" , prologue ) ; results . add ( prologue ) ; } return results ; } private List < Export > analyzeExports ( StageGraph graph , Collection < StageModel > stageModels ) { assert graph != null ; assert stageModels != null ; LOG . debug ( "" , graph . getOutput ( ) ) ; List < Export > results = Lists . create ( ) ; for ( FlowBlock . Input target : graph . getOutput ( ) . getBlockInputs ( ) ) { FlowElement element = target . getElementPort ( ) . getOwner ( ) ; FlowElementDescription desc = element . getDescription ( ) ; if ( desc . getKind ( ) != FlowElementKind . OUTPUT ) { error ( "" , desc ) ; continue ; } OutputDescription description = ( OutputDescription ) desc ; ExternalIoDescriptionProcessor proc = environment . getExternals ( ) . findProcessor ( description ) ; if ( proc == null ) { error ( "" , desc ) ; continue ; } Export epilogue = new Export ( Collections . singletonList ( target ) , description , proc ) ; results . add ( epilogue ) ; LOG . debug ( "" , epilogue ) ; } return results ; } private List < Stage > analyzeStages ( Collection < StageModel > stageModels ) { assert stageModels != null ; List < Stage > results = Lists . create ( ) ; for ( StageModel model : sort ( stageModels ) ) { results . add ( analyzeStage ( model ) ) ; } return results ; } private Stage analyzeStage ( StageModel model ) { assert model != null ; LOG . debug ( "" , model ) ; List < Process > processes = analyzeProcesses ( model ) ; List < Delivery > deliveries = analyzeDeliveries ( model ) ; Set < SideData > sideData = analyzeSideData ( model ) ; Reduce reduce = analyzeReduce ( model ) ; Stage stage = new Stage ( model , processes , deliveries , reduce , sideData ) ; LOG . debug ( "" , model ) ; return stage ; } private Reduce analyzeReduce ( StageModel model ) { if ( model . getShuffleModel ( ) == null ) { assert model . getReduceUnits ( ) . isEmpty ( ) ; return null ; } assert model . getReduceUnits ( ) . isEmpty ( ) == false ; CompiledShuffle shuffle = model . getShuffleModel ( ) . getCompiled ( ) ; CompiledReduce reducer = model . getReduceUnits ( ) . get ( ) . getCompiled ( ) ; return new Reduce ( reducer . getReducerType ( ) . getQualifiedName ( ) , reducer . getCombinerTypeOrNull ( ) == null ? null : reducer . getCombinerTypeOrNull ( ) . getQualifiedName ( ) , shuffle . getKeyTypeName ( ) , shuffle . getValueTypeName ( ) , shuffle . getGroupComparatorTypeName ( ) , shuffle . getSortComparatorTypeName ( ) , shuffle . getPartitionerTypeName ( ) ) ; } private List < Delivery > analyzeDeliveries ( StageModel model ) { assert model != null ; Location base = environment . getStageLocation ( model . getStageBlock ( ) . getStageNumber ( ) ) ; List < Delivery > deliveries = Lists . create ( ) ; for ( StageModel . Sink sink : model . getStageResults ( ) ) { Location location = base . append ( sink . getName ( ) ) . asPrefix ( ) ; deliveries . add ( new Delivery ( sink . getOutputs ( ) , Collections . singleton ( location ) ) ) ; } return deliveries ; } private List < Process > analyzeProcesses ( StageModel model ) { List < Process > processes = Lists . create ( ) ; for ( StageModel . MapUnit unit : model . getMapUnits ( ) ) { processes . add ( new Process ( unit . getInputs ( ) , unit . getCompiled ( ) . getQualifiedName ( ) ) ) ; } return processes ; } private Set < SideData > analyzeSideData ( StageModel model ) { assert model != null ; Set < SideData > results = Sets . create ( ) ; for ( InputDescription input : model . getSideDataInputs ( ) ) { ExternalIoDescriptionProcessor proc = environment . getExternals ( ) . findProcessor ( input ) ; if ( proc == null ) { error ( "" , input ) ; continue ; } Set < Location > locations = proc . getInputInfo ( input ) . getLocations ( ) ; results . add ( new SideData ( locations , input . getName ( ) ) ) ; } return results ; } private List < StageModel > sort ( Collection < StageModel > stageModels ) { List < StageModel > models = Lists . from ( stageModels ) ; Collections . sort ( models , new Comparator < StageModel > ( ) { @ Override public int compare ( StageModel o1 , StageModel o2 ) { int s1 = o1 . getStageBlock ( ) . getStageNumber ( ) ; int s2 = o2 . getStageBlock ( ) . getStageNumber ( ) ; if ( s1 == s2 ) { return ; } if ( s1 < s2 ) { return - ; } return + ; } } ) ; return models ; } private void resolve ( List < Import > imports , List < Export > exports , List < Stage > stages ) { assert imports != null ; assert exports != null ; assert stages != null ; Map < FlowBlock . Output , Source > sources = createOutputMap ( imports , stages ) ; for ( Target target : exports ) { resolveTarget ( target , sources ) ; } for ( Stage stage : stages ) { for ( Target target : stage . getProcesses ( ) ) { resolveTarget ( target , sources ) ; } } } private void resolveTarget ( Target target , Map < FlowBlock . Output , Source > sources ) { assert target != null ; assert sources != null ; Set < Source > opposites = Sets . create ( ) ; for ( FlowBlock . Input input : target . getInputs ( ) ) { for ( FlowBlock . Connection conn : input . getConnections ( ) ) { FlowBlock . Output upstream = conn . getUpstream ( ) ; Source source = sources . get ( upstream ) ; assert source != null ; opposites . add ( source ) ; } } target . resolveSources ( opposites ) ; } private Map < FlowBlock . Output , Source > createOutputMap ( List < Import > imports , List < Stage > stages ) { assert imports != null ; assert stages != null ; Map < FlowBlock . Output , Source > sources = Maps . create ( ) ; for ( Source source : imports ) { for ( FlowBlock . Output output : source . getOutputs ( ) ) { sources . put ( output , source ) ; } } for ( Stage stage : stages ) { for ( Source source : stage . getDeliveries ( ) ) { for ( FlowBlock . Output output : source . getOutputs ( ) ) { sources . put ( output , source ) ; } } } return sources ; } private void error ( String format , Object ... args ) { environment . error ( format , args ) ; sawError = true ; } } package com . asakusafw . compiler . flow . jobflow ; package com . asakusafw . compiler . flow . jobflow ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; public class CompiledJobflow { private List < ExternalIoCommandProvider > commands ; private List < CompiledStage > prologueStages ; private List < CompiledStage > epilogueStages ; public CompiledJobflow ( List < ExternalIoCommandProvider > commands , List < CompiledStage > prologueStages , List < CompiledStage > epilogueStages ) { Precondition . checkMustNotBeNull ( commands , "" ) ; Precondition . checkMustNotBeNull ( prologueStages , "" ) ; Precondition . checkMustNotBeNull ( epilogueStages , "" ) ; this . commands = commands ; this . prologueStages = prologueStages ; this . epilogueStages = epilogueStages ; } public List < ExternalIoCommandProvider > getCommandProviders ( ) { return commands ; } public List < CompiledStage > getPrologueStages ( ) { return prologueStages ; } public List < CompiledStage > getEpilogueStages ( ) { return epilogueStages ; } } package com . asakusafw . compiler . flow . jobflow ; import java . io . IOException ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . Input ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . IoContext ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . Output ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Delivery ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Export ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Import ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Process ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Processible ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Reduce ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . SideData ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Source ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Stage ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; public class JobflowCompiler { static final Logger LOG = LoggerFactory . getLogger ( JobflowCompiler . class ) ; @ SuppressWarnings ( "" ) private final FlowCompilingEnvironment environment ; private final JobflowAnalyzer analyzer ; private final StageClientEmitter stageClientEmitter ; private final CleanupStageClientEmitter cleanupStageClientEmitter ; public JobflowCompiler ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; this . analyzer = new JobflowAnalyzer ( environment ) ; this . stageClientEmitter = new StageClientEmitter ( environment ) ; this . cleanupStageClientEmitter = new CleanupStageClientEmitter ( environment ) ; } public JobflowModel compile ( StageGraph graph , Collection < StageModel > stageModels ) throws IOException { Precondition . checkMustNotBeNull ( graph , "" ) ; Precondition . checkMustNotBeNull ( stageModels , "" ) ; LOG . debug ( "" , graph . getInput ( ) . getSource ( ) . getDescription ( ) . getName ( ) ) ; JobflowModel jobflow = analyze ( graph , stageModels ) ; compileClients ( jobflow ) ; CompiledJobflow compiled = emit ( jobflow ) ; jobflow . setCompiled ( compiled ) ; reportSummary ( jobflow ) ; return jobflow ; } private JobflowModel analyze ( StageGraph graph , Collection < StageModel > stageModels ) throws IOException { assert graph != null ; assert stageModels != null ; JobflowModel jobflow = analyzer . analyze ( graph , stageModels ) ; if ( analyzer . hasError ( ) ) { analyzer . clearError ( ) ; throw new IOException ( "" ) ; } return jobflow ; } private CompiledJobflow emit ( JobflowModel model ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; LOG . debug ( "" , model . getBatchId ( ) , model . getFlowId ( ) ) ; Map < ExternalIoDescriptionProcessor , List < Import > > imports = group ( model . getImports ( ) ) ; Map < ExternalIoDescriptionProcessor , List < Export > > exports = group ( model . getExports ( ) ) ; fillEmptyList ( imports , exports . keySet ( ) ) ; fillEmptyList ( exports , imports . keySet ( ) ) ; List < ExternalIoCommandProvider > commands = Lists . create ( ) ; List < CompiledStage > prologues = Lists . create ( ) ; List < CompiledStage > epilogues = Lists . create ( ) ; for ( Map . Entry < ExternalIoDescriptionProcessor , List < Import > > entry : imports . entrySet ( ) ) { ExternalIoDescriptionProcessor proc = entry . getKey ( ) ; List < Import > importGroup = entry . getValue ( ) ; List < Export > exportGroup = exports . get ( proc ) ; assert exportGroup != null ; assert importGroup . isEmpty ( ) == false || exportGroup . isEmpty ( ) == false ; IoContext context = createEmitContext ( proc , importGroup , exportGroup ) ; LOG . debug ( "" , proc . getClass ( ) . getName ( ) ) ; proc . emitPackage ( context ) ; LOG . debug ( "" , proc . getClass ( ) . getName ( ) ) ; prologues . addAll ( proc . emitPrologue ( context ) ) ; LOG . debug ( "" , proc . getClass ( ) . getName ( ) ) ; epilogues . addAll ( proc . emitEpilogue ( context ) ) ; commands . add ( proc . createCommandProvider ( context ) ) ; } return new CompiledJobflow ( commands , prologues , epilogues ) ; } private IoContext createEmitContext ( ExternalIoDescriptionProcessor processor , List < Import > importGroup , List < Export > exportGroup ) { assert processor != null ; assert importGroup != null ; assert exportGroup != null ; List < Input > inputs = Lists . create ( ) ; for ( Import model : importGroup ) { inputs . add ( new Input ( model . getDescription ( ) , model . getOutputFormatType ( ) ) ) ; } List < Output > outputs = Lists . create ( ) ; for ( Export model : exportGroup ) { List < SourceInfo > sources = Lists . create ( ) ; for ( Source source : model . getResolvedSources ( ) ) { sources . add ( source . getInputInfo ( ) ) ; } outputs . add ( new Output ( model . getDescription ( ) , sources ) ) ; } IoContext context = new IoContext ( inputs , outputs ) ; return context ; } private void reportSummary ( JobflowModel jobflow ) { LOG . info ( "" , jobflow . getBatchId ( ) , jobflow . getFlowId ( ) ) ; LOG . info ( "" , jobflow . getImports ( ) . size ( ) ) ; LOG . info ( "" , jobflow . getExports ( ) . size ( ) ) ; LOG . info ( "" , jobflow . getStages ( ) . size ( ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" ) ; for ( Import stage : jobflow . getImports ( ) ) { LOG . debug ( "" ) ; LOG . debug ( "" , stage . getId ( ) ) ; LOG . debug ( "" , stage . getDescription ( ) . getImporterDescription ( ) . getClass ( ) . getName ( ) ) ; LOG . debug ( "" , stage . getInputInfo ( ) . getLocations ( ) ) ; LOG . debug ( "" , stage . getInputInfo ( ) . getFormat ( ) . getName ( ) ) ; } for ( CompiledStage stage : jobflow . getCompiled ( ) . getPrologueStages ( ) ) { LOG . debug ( "" ) ; LOG . debug ( "" , stage . getStageId ( ) ) ; LOG . debug ( "" , stage . getQualifiedName ( ) . toNameString ( ) ) ; } Graph < Stage > graph = jobflow . getDependencyGraph ( ) ; Graph < Stage > tgraph = Graphs . transpose ( graph ) ; for ( Stage stage : jobflow . getStages ( ) ) { LOG . debug ( "" ) ; LOG . debug ( "" , stage . getCompiled ( ) . getStageId ( ) ) ; LOG . debug ( "" , stage . getCompiled ( ) . getQualifiedName ( ) . toNameString ( ) ) ; for ( Process unit : stage . getProcesses ( ) ) { LOG . debug ( "" , unit . getResolvedLocations ( ) , unit . getDataType ( ) ) ; } for ( Delivery unit : stage . getDeliveries ( ) ) { LOG . debug ( "" , unit . getInputInfo ( ) . getLocations ( ) , unit . getDataType ( ) ) ; } Reduce reducer = stage . getReduceOrNull ( ) ; if ( reducer != null ) { LOG . debug ( "" , reducer . getKeyTypeName ( ) . toNameString ( ) ) ; LOG . debug ( "" , reducer . getValueTypeName ( ) . toNameString ( ) ) ; LOG . debug ( "" , reducer . getPartitionerTypeName ( ) . toNameString ( ) ) ; LOG . debug ( "" , reducer . getGroupingComparatorTypeName ( ) . toNameString ( ) ) ; LOG . debug ( "" , reducer . getSortComparatorTypeName ( ) . toNameString ( ) ) ; LOG . debug ( "" , reducer . getCombinerTypeNameOrNull ( ) == null ? "" : reducer . getCombinerTypeNameOrNull ( ) . toNameString ( ) ) ; LOG . debug ( "" , reducer . getReducerTypeName ( ) . toNameString ( ) ) ; } for ( SideData data : stage . getSideData ( ) ) { LOG . debug ( "" , data . getLocalName ( ) , data . getClusterPaths ( ) ) ; } LOG . debug ( "" , getStageIds ( graph . getConnected ( stage ) ) ) ; LOG . debug ( "" , getStageIds ( tgraph . getConnected ( stage ) ) ) ; } for ( CompiledStage stage : jobflow . getCompiled ( ) . getEpilogueStages ( ) ) { LOG . debug ( "" ) ; LOG . debug ( "" , stage . getStageId ( ) ) ; LOG . debug ( "" , stage . getQualifiedName ( ) . toNameString ( ) ) ; } for ( Export stage : jobflow . getExports ( ) ) { LOG . debug ( "" ) ; LOG . debug ( "" , stage . getId ( ) ) ; LOG . debug ( "" , stage . getDescription ( ) . getExporterDescription ( ) . getClass ( ) . getName ( ) ) ; LOG . debug ( "" , stage . getResolvedLocations ( ) ) ; } LOG . debug ( "" ) ; } } private List < String > getStageIds ( Collection < Stage > stages ) { assert stages != null ; List < String > results = Lists . create ( ) ; for ( Stage stage : stages ) { results . add ( stage . getCompiled ( ) . getStageId ( ) ) ; } Collections . sort ( results ) ; return results ; } private < K , V > void fillEmptyList ( Map < K , List < V > > map , Set < K > samples ) { assert map != null ; assert samples != null ; for ( K sample : samples ) { if ( map . containsKey ( sample ) == false ) { map . put ( sample , Collections . < V > emptyList ( ) ) ; } } } private < T extends Processible > Map < ExternalIoDescriptionProcessor , List < T > > group ( List < T > targets ) { assert targets != null ; Map < ExternalIoDescriptionProcessor , List < T > > results = Maps . create ( ) ; for ( T processible : targets ) { ExternalIoDescriptionProcessor proc = processible . getProcessor ( ) ; Maps . addToList ( results , proc , processible ) ; } return results ; } private void compileClients ( JobflowModel jobflow ) throws IOException { assert jobflow != null ; for ( Stage stage : jobflow . getStages ( ) ) { CompiledStage client = stageClientEmitter . emit ( stage ) ; stage . setCompiled ( client ) ; } cleanupStageClientEmitter . emit ( ) ; } } package com . asakusafw . compiler . flow . jobflow ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . runtime . stage . AbstractCleanupStageClient ; import com . asakusafw . runtime . stage . BaseStageClient ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; public class CleanupStageClientEmitter { static final Logger LOG = LoggerFactory . getLogger ( CleanupStageClientEmitter . class ) ; private final FlowCompilingEnvironment environment ; public CleanupStageClientEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledStage emit ( ) throws IOException { LOG . debug ( "" , environment . getFlowId ( ) ) ; Engine engine = new Engine ( environment ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , environment . getFlowId ( ) , name ) ; return new CompiledStage ( name , Naming . getCleanupStageName ( ) ) ; } private static class Engine { private static final char PATH_SEPARATOR = '' ; private final FlowCompilingEnvironment environment ; private final ModelFactory factory ; private final ImportBuilder importer ; private final QualifiedName fqn ; Engine ( FlowCompilingEnvironment environment ) { assert environment != null ; this . environment = environment ; this . factory = environment . getModelFactory ( ) ; this . fqn = ( QualifiedName ) Models . toName ( factory , AbstractCleanupStageClient . IMPLEMENTATION ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( fqn . getQualifier ( ) ) , ImportBuilder . Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { importer . resolvePackageMember ( fqn . getSimpleName ( ) ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createIdMethods ( ) ) ; members . add ( createStageOutputPath ( ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Final ( ) . toAttributes ( ) , fqn . getSimpleName ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( AbstractCleanupStageClient . class ) , Collections . < Type > emptyList ( ) , members ) ; } private List < MethodDeclaration > createIdMethods ( ) { List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_BATCH_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getBatchId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_FLOW_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getFlowId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_STAGE_ID , t ( String . class ) , Models . toLiteral ( factory , Naming . getCleanupStageName ( ) ) ) ) ; return results ; } private MethodDeclaration createStageOutputPath ( ) { Location location = environment . getTargetLocation ( ) ; location = getCleanupTarget ( location ) ; String path = location . toPath ( PATH_SEPARATOR ) ; return createValueMethod ( AbstractCleanupStageClient . METHOD_CLEANUP_PATH , t ( String . class ) , Models . toLiteral ( factory , path ) ) ; } private Location getCleanupTarget ( Location location ) { Location candidate = location ; Location current = location ; while ( current != null ) { String name = current . getName ( ) ; if ( name . indexOf ( StageConstants . EXPR_EXECUTION_ID ) >= ) { candidate = current ; } current = current . getParent ( ) ; } return candidate ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" ) . toJavadoc ( ) ; } private MethodDeclaration createValueMethod ( String methodName , Type returnType , Expression expression ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , returnType , factory . newSimpleName ( methodName ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( factory . newReturnStatement ( expression ) ) ) ; } private Type t ( java . lang . reflect . Type type , Type ... typeArgs ) { assert type != null ; assert typeArgs != null ; Type raw = importer . toType ( type ) ; if ( typeArgs . length == ) { return raw ; } return factory . newParameterizedType ( raw , Arrays . asList ( typeArgs ) ) ; } } } package com . asakusafw . compiler . flow . jobflow ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . apache . hadoop . mapreduce . OutputFormat ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . Compilable ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class JobflowModel extends Compilable . Trait < CompiledJobflow > { private final StageGraph stageGraph ; private final String batchId ; private final String flowId ; private final List < Import > imports ; private final List < Export > exports ; private final List < Stage > stages ; public JobflowModel ( StageGraph stageGraph , String batchId , String flowId , List < Import > imports , List < Export > exports , List < Stage > stages ) { Precondition . checkMustNotBeNull ( stageGraph , "" ) ; Precondition . checkMustNotBeNull ( batchId , "" ) ; Precondition . checkMustNotBeNull ( flowId , "" ) ; Precondition . checkMustNotBeNull ( imports , "" ) ; Precondition . checkMustNotBeNull ( exports , "" ) ; Precondition . checkMustNotBeNull ( stages , "" ) ; this . stageGraph = stageGraph ; this . batchId = batchId ; this . flowId = flowId ; this . imports = imports ; this . exports = exports ; this . stages = stages ; } public StageGraph getStageGraph ( ) { return stageGraph ; } public String getBatchId ( ) { return batchId ; } public String getFlowId ( ) { return flowId ; } public List < Import > getImports ( ) { return imports ; } public List < Export > getExports ( ) { return exports ; } public List < Stage > getStages ( ) { return stages ; } public Graph < Stage > getDependencyGraph ( ) { Map < Delivery , Stage > deliveries = Maps . create ( ) ; for ( Stage stage : stages ) { for ( Delivery delivery : stage . getDeliveries ( ) ) { deliveries . put ( delivery , stage ) ; } } Graph < Stage > graph = Graphs . newInstance ( ) ; for ( Stage stage : stages ) { graph . addNode ( stage ) ; for ( Process process : stage . getProcesses ( ) ) { for ( Source source : process . getResolvedSources ( ) ) { Stage dependence = deliveries . get ( source ) ; if ( dependence == null ) { continue ; } graph . addEdge ( stage , dependence ) ; } } } return graph ; } public static class Stage extends Compilable . Trait < CompiledStage > { private final StageModel model ; private final List < Process > processes ; private final List < Delivery > deliveries ; private final Reduce reduceOrNull ; private final Set < SideData > sideData ; public Stage ( StageModel model , List < Process > processes , List < Delivery > deliveries , Reduce reduceOrNull , Set < SideData > sideData ) { Precondition . checkMustNotBeNull ( model , "" ) ; Precondition . checkMustNotBeNull ( processes , "" ) ; Precondition . checkMustNotBeNull ( deliveries , "" ) ; Precondition . checkMustNotBeNull ( sideData , "" ) ; this . model = model ; this . processes = processes ; this . deliveries = deliveries ; this . reduceOrNull = reduceOrNull ; this . sideData = sideData ; } public int getNumber ( ) { return model . getStageBlock ( ) . getStageNumber ( ) ; } public StageModel getModel ( ) { return model ; } public List < Process > getProcesses ( ) { return processes ; } public List < Delivery > getDeliveries ( ) { return deliveries ; } public Reduce getReduceOrNull ( ) { return reduceOrNull ; } public Set < SideData > getSideData ( ) { return sideData ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , String . valueOf ( getNumber ( ) ) ) ; } } public static class Reduce { private final Name reducerTypeName ; private final Name combinerTypeNameOrNull ; private final Name keyTypeName ; private final Name valueTypeName ; private final Name groupingComparatorTypeName ; private final Name sortComparatorTypeName ; private final Name partitionerTypeName ; public Reduce ( Name reducerTypeName , Name combinerTypeNameOrNull , Name keyTypeName , Name valueTypeName , Name groupingComparatorTypeName , Name sortComparatorTypeName , Name partitionerTypeName ) { Precondition . checkMustNotBeNull ( reducerTypeName , "" ) ; Precondition . checkMustNotBeNull ( keyTypeName , "" ) ; Precondition . checkMustNotBeNull ( valueTypeName , "" ) ; Precondition . checkMustNotBeNull ( groupingComparatorTypeName , "" ) ; Precondition . checkMustNotBeNull ( sortComparatorTypeName , "" ) ; Precondition . checkMustNotBeNull ( partitionerTypeName , "" ) ; this . reducerTypeName = reducerTypeName ; this . combinerTypeNameOrNull = combinerTypeNameOrNull ; this . keyTypeName = keyTypeName ; this . valueTypeName = valueTypeName ; this . groupingComparatorTypeName = groupingComparatorTypeName ; this . sortComparatorTypeName = sortComparatorTypeName ; this . partitionerTypeName = partitionerTypeName ; } public Name getCombinerTypeNameOrNull ( ) { return combinerTypeNameOrNull ; } public Name getReducerTypeName ( ) { return reducerTypeName ; } public Name getKeyTypeName ( ) { return keyTypeName ; } public Name getValueTypeName ( ) { return valueTypeName ; } public Name getGroupingComparatorTypeName ( ) { return groupingComparatorTypeName ; } public Name getSortComparatorTypeName ( ) { return sortComparatorTypeName ; } public Name getPartitionerTypeName ( ) { return partitionerTypeName ; } } public abstract static class Source { private final Set < FlowBlock . Output > outputs ; protected Source ( Set < FlowBlock . Output > outputs ) { Precondition . checkMustNotBeNull ( outputs , "" ) ; this . outputs = outputs ; } public abstract SourceInfo getInputInfo ( ) ; public Set < FlowBlock . Output > getOutputs ( ) { return outputs ; } } public abstract static class Target { private final List < FlowBlock . Input > inputs ; private Set < Source > sources ; public Target ( List < FlowBlock . Input > inputs ) { Precondition . checkMustNotBeNull ( inputs , "" ) ; if ( inputs . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } this . inputs = inputs ; } public void resolveSources ( Collection < ? extends Source > opposites ) { Precondition . checkMustNotBeNull ( opposites , "" ) ; this . sources = Sets . from ( opposites ) ; } public Set < Source > getResolvedSources ( ) { if ( sources == null ) { throw new IllegalStateException ( ) ; } return sources ; } public Set < Location > getResolvedLocations ( ) { Set < Location > results = Sets . create ( ) ; for ( Source source : getResolvedSources ( ) ) { results . addAll ( source . getInputInfo ( ) . getLocations ( ) ) ; } return results ; } public List < FlowBlock . Input > getInputs ( ) { return inputs ; } public java . lang . reflect . Type getDataType ( ) { if ( inputs . isEmpty ( ) ) { return void . class ; } return inputs . get ( ) . getElementPort ( ) . getDescription ( ) . getDataType ( ) ; } } public interface Processible { ExternalIoDescriptionProcessor getProcessor ( ) ; } public static class Process extends Target { private final Name mapperTypeName ; public Process ( List < FlowBlock . Input > inputs , Name mapperTypeName ) { super ( inputs ) ; Precondition . checkMustNotBeNull ( mapperTypeName , "" ) ; this . mapperTypeName = mapperTypeName ; } public Name getMapperTypeName ( ) { return mapperTypeName ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getInputs ( ) , getMapperTypeName ( ) ) ; } } public static class Delivery extends Source { private final Set < Location > locations ; public Delivery ( Set < FlowBlock . Output > outputs , Set < Location > locations ) { super ( outputs ) ; Precondition . checkMustNotBeNull ( locations , "" ) ; this . locations = locations ; } public java . lang . reflect . Type getDataType ( ) { FlowBlock . Output first = getOutputs ( ) . iterator ( ) . next ( ) ; FlowElementOutput port = first . getElementPort ( ) ; return port . getDescription ( ) . getDataType ( ) ; } @ Override public SourceInfo getInputInfo ( ) { return new SourceInfo ( locations , TemporaryInputFormat . class ) ; } @ SuppressWarnings ( "" ) public Class < ? extends OutputFormat > getOutputFormatType ( ) { return TemporaryOutputFormat . class ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getOutputs ( ) , getInputInfo ( ) . getLocations ( ) ) ; } } public static class Import extends Source implements Processible { private final InputDescription description ; private final ExternalIoDescriptionProcessor processor ; public Import ( InputDescription description , ExternalIoDescriptionProcessor processor ) { super ( Collections . < FlowBlock . Output > emptySet ( ) ) ; Precondition . checkMustNotBeNull ( description , "" ) ; Precondition . checkMustNotBeNull ( processor , "" ) ; this . description = description ; this . processor = processor ; } public Import ( FlowBlock . Output output , InputDescription description , ExternalIoDescriptionProcessor processor ) { super ( Collections . singleton ( output ) ) ; Precondition . checkMustNotBeNull ( description , "" ) ; Precondition . checkMustNotBeNull ( processor , "" ) ; this . description = description ; this . processor = processor ; } public String getId ( ) { return description . getName ( ) ; } @ Override public SourceInfo getInputInfo ( ) { return processor . getInputInfo ( description ) ; } @ SuppressWarnings ( "" ) public Class < ? extends OutputFormat > getOutputFormatType ( ) { return TemporaryOutputFormat . class ; } public InputDescription getDescription ( ) { return description ; } @ Override public ExternalIoDescriptionProcessor getProcessor ( ) { return processor ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getOutputs ( ) , getInputInfo ( ) . getLocations ( ) , getDescription ( ) ) ; } } public static class Export extends Target implements Processible { private final OutputDescription description ; private final ExternalIoDescriptionProcessor processor ; public Export ( List < FlowBlock . Input > inputs , OutputDescription description , ExternalIoDescriptionProcessor processor ) { super ( inputs ) ; Precondition . checkMustNotBeNull ( description , "" ) ; Precondition . checkMustNotBeNull ( processor , "" ) ; this . description = description ; this . processor = processor ; } public String getId ( ) { return description . getName ( ) ; } public OutputDescription getDescription ( ) { return description ; } @ Override public ExternalIoDescriptionProcessor getProcessor ( ) { return processor ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getInputs ( ) , getDescription ( ) ) ; } } public static class SideData { private final Set < Location > clusterPaths ; private final String localName ; public SideData ( Set < Location > clusterPaths , String localName ) { Precondition . checkMustNotBeNull ( clusterPaths , "" ) ; Precondition . checkMustNotBeNull ( localName , "" ) ; this . clusterPaths = clusterPaths ; this . localName = localName ; } public Set < Location > getClusterPaths ( ) { return clusterPaths ; } public String getLocalName ( ) { return localName ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClusterPaths ( ) , getLocalName ( ) ) ; } } } package com . asakusafw . compiler . flow . jobflow ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . io . NullWritable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Delivery ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Process ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Reduce ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . SideData ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Source ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Stage ; import com . asakusafw . runtime . stage . AbstractStageClient ; import com . asakusafw . runtime . stage . BaseStageClient ; import com . asakusafw . runtime . stage . StageInput ; import com . asakusafw . runtime . stage . StageOutput ; import com . asakusafw . runtime . stage . StageResource ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class StageClientEmitter { static final Logger LOG = LoggerFactory . getLogger ( StageClientEmitter . class ) ; private final FlowCompilingEnvironment environment ; public StageClientEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledStage emit ( JobflowModel . Stage stage ) throws IOException { Precondition . checkMustNotBeNull ( stage , "" ) ; LOG . debug ( "" , stage ) ; Engine engine = new Engine ( environment , stage ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , stage , name ) ; return new CompiledStage ( name , Naming . getStageName ( stage . getNumber ( ) ) ) ; } private static class Engine { private static final char PATH_SEPARATOR = '' ; private final FlowCompilingEnvironment environment ; private final Stage stage ; private final ModelFactory factory ; private final ImportBuilder importer ; Engine ( FlowCompilingEnvironment environment , Stage stage ) { assert environment != null ; assert stage != null ; this . environment = environment ; this . stage = stage ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( stage . getNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getClientClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createIdMethods ( ) ) ; members . add ( createStageOutputPath ( ) ) ; members . add ( createStageInputsMethod ( ) ) ; members . add ( createStageOutputsMethod ( ) ) ; members . add ( createStageResourcesMethod ( ) ) ; if ( stage . getReduceOrNull ( ) != null ) { members . addAll ( createShuffleMethods ( ) ) ; } return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( AbstractStageClient . class ) , Collections . < Type > emptyList ( ) , members ) ; } private List < MethodDeclaration > createIdMethods ( ) { List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_BATCH_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getBatchId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_FLOW_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getFlowId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_STAGE_ID , t ( String . class ) , Models . toLiteral ( factory , Naming . getStageName ( stage . getNumber ( ) ) ) ) ) ; return results ; } private MethodDeclaration createStageOutputPath ( ) { String path = environment . getStageLocation ( stage . getNumber ( ) ) . toPath ( PATH_SEPARATOR ) ; return createValueMethod ( AbstractStageClient . METHOD_STAGE_OUTPUT_PATH , t ( String . class ) , Models . toLiteral ( factory , path ) ) ; } private MethodDeclaration createStageInputsMethod ( ) { SimpleName list = factory . newSimpleName ( "" ) ; SimpleName attributes = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageInput . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageInput . class ) ) , list ) ) ; statements . add ( new ExpressionBuilder ( factory , Models . toNullLiteral ( factory ) ) . toLocalVariableDeclaration ( t ( Map . class , t ( String . class ) , t ( String . class ) ) , attributes ) ) ; for ( Process process : stage . getProcesses ( ) ) { Expression mapperType = dotClass ( process . getMapperTypeName ( ) ) ; for ( Source source : process . getResolvedSources ( ) ) { SourceInfo info = source . getInputInfo ( ) ; Class < ? > inputFormatType = info . getFormat ( ) ; statements . add ( new ExpressionBuilder ( factory , attributes ) . assignFrom ( new TypeBuilder ( factory , t ( HashMap . class , t ( String . class ) , t ( String . class ) ) ) . newObject ( ) . toExpression ( ) ) . toStatement ( ) ) ; for ( Map . Entry < String , String > entry : info . getAttributes ( ) . entrySet ( ) ) { statements . add ( new ExpressionBuilder ( factory , attributes ) . method ( "" , Models . toLiteral ( factory , entry . getKey ( ) ) , Models . toLiteral ( factory , entry . getValue ( ) ) ) . toStatement ( ) ) ; } for ( Location location : info . getLocations ( ) ) { statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageInput . class ) ) . newObject ( Models . toLiteral ( factory , location . toPath ( '' ) ) , factory . newClassLiteral ( t ( inputFormatType ) ) , mapperType , attributes ) . toExpression ( ) ) . toStatement ( ) ) ; } } } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageInput . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_INPUTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createStageOutputsMethod ( ) { SimpleName list = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageOutput . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageOutput . class ) ) , list ) ) ; for ( Delivery process : stage . getDeliveries ( ) ) { Expression valueType = factory . newClassLiteral ( t ( process . getDataType ( ) ) ) ; Class < ? > outputFormatType = process . getOutputFormatType ( ) ; for ( Location location : process . getInputInfo ( ) . getLocations ( ) ) { statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageOutput . class ) ) . newObject ( Models . toLiteral ( factory , location . getName ( ) ) , factory . newClassLiteral ( t ( NullWritable . class ) ) , valueType , factory . newClassLiteral ( t ( outputFormatType ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; } } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageOutput . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_OUTPUTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private TypeBodyDeclaration createStageResourcesMethod ( ) { SimpleName list = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageResource . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageResource . class ) ) , list ) ) ; for ( SideData sideData : stage . getSideData ( ) ) { for ( Location location : sideData . getClusterPaths ( ) ) { statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageResource . class ) ) . newObject ( Models . toLiteral ( factory , location . toPath ( '' ) ) , Models . toLiteral ( factory , sideData . getLocalName ( ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; } } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageResource . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_RESOURCES ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private List < MethodDeclaration > createShuffleMethods ( ) { Reduce reduce = stage . getReduceOrNull ( ) ; List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_SHUFFLE_KEY_CLASS , importer . toType ( reduce . getKeyTypeName ( ) ) ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_SHUFFLE_VALUE_CLASS , importer . toType ( reduce . getValueTypeName ( ) ) ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_PARTITIONER_CLASS , importer . toType ( reduce . getPartitionerTypeName ( ) ) ) ) ; if ( reduce . getCombinerTypeNameOrNull ( ) != null ) { results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_COMBINER_CLASS , importer . toType ( reduce . getCombinerTypeNameOrNull ( ) ) ) ) ; } results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_SORT_COMPARATOR_CLASS , importer . toType ( reduce . getSortComparatorTypeName ( ) ) ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_GROUPING_COMPARATOR_CLASS , importer . toType ( reduce . getGroupingComparatorTypeName ( ) ) ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_REDUCER_CLASS , importer . toType ( reduce . getReducerTypeName ( ) ) ) ) ; return results ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , stage . getNumber ( ) ) . toJavadoc ( ) ; } private MethodDeclaration createClassLiteralMethod ( String methodName , Type type ) { assert methodName != null ; assert type != null ; return createValueMethod ( methodName , t ( Class . class , type ) , factory . newClassLiteral ( type ) ) ; } private MethodDeclaration createValueMethod ( String methodName , Type returnType , Expression expression ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , returnType , factory . newSimpleName ( methodName ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( factory . newReturnStatement ( expression ) ) ) ; } private Type t ( java . lang . reflect . Type type , Type ... typeArgs ) { assert type != null ; assert typeArgs != null ; Type raw = importer . toType ( type ) ; if ( typeArgs . length == ) { return raw ; } return factory . newParameterizedType ( raw , Arrays . asList ( typeArgs ) ) ; } private Expression dotClass ( Name name ) { assert name != null ; return factory . newClassLiteral ( importer . toType ( name ) ) ; } } } package com . asakusafw . compiler . flow . jobflow ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . java . model . syntax . Name ; public class CompiledStage { private Name qualifiedName ; private String stageId ; public CompiledStage ( Name qualifiedName , String stageId ) { Precondition . checkMustNotBeNull ( qualifiedName , "" ) ; Precondition . checkMustNotBeNull ( stageId , "" ) ; this . qualifiedName = qualifiedName ; this . stageId = stageId ; } public Name getQualifiedName ( ) { return qualifiedName ; } public String getStageId ( ) { return stageId ; } } package com . asakusafw . compiler . flow . join ; import java . io . IOException ; import java . lang . annotation . Annotation ; import java . lang . reflect . Type ; import java . util . LinkedList ; import java . util . List ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowGraphRewriter ; import com . asakusafw . compiler . flow . join . operator . SideDataBranch ; import com . asakusafw . compiler . flow . join . operator . SideDataCheck ; import com . asakusafw . compiler . flow . join . operator . SideDataJoin ; import com . asakusafw . compiler . flow . join . operator . SideDataJoinUpdate ; import com . asakusafw . compiler . flow . plan . FlowGraphUtil ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterBranch ; import com . asakusafw . vocabulary . operator . MasterCheck ; import com . asakusafw . vocabulary . operator . MasterJoin ; import com . asakusafw . vocabulary . operator . MasterJoinUpdate ; public class JoinRewriter extends FlowCompilingEnvironment . Initialized implements FlowGraphRewriter { static final Logger LOG = LoggerFactory . getLogger ( JoinRewriter . class ) ; @ Override public boolean rewrite ( FlowGraph graph ) throws RewriteException { Precondition . checkMustNotBeNull ( graph , "" ) ; FlowCompilerOptions options = getEnvironment ( ) . getOptions ( ) ; if ( options . isHashJoinForSmall ( ) == false && options . isHashJoinForTiny ( ) == false ) { LOG . debug ( "" ) ; return false ; } return rewriteGraph ( graph ) ; } private boolean rewriteGraph ( FlowGraph graph ) { assert graph != null ; boolean modified = false ; for ( FlowIn < ? > input : graph . getFlowInputs ( ) ) { if ( rewriteRequired ( input ) == false ) { continue ; } modified |= rewriteSuccessors ( input . getDescription ( ) , input ) ; } return modified ; } private boolean rewriteRequired ( FlowIn < ? > input ) { assert input != null ; InputDescription desc = input . getDescription ( ) ; ImporterDescription importer = desc . getImporterDescription ( ) ; if ( importer == null ) { return false ; } if ( isSupportedSize ( desc ) == false ) { return false ; } if ( isSupportedFormat ( desc ) == false ) { return false ; } return true ; } private boolean isSupportedSize ( InputDescription desc ) { assert desc != null ; ImporterDescription importer = desc . getImporterDescription ( ) ; assert importer != null ; FlowCompilerOptions options = getEnvironment ( ) . getOptions ( ) ; switch ( importer . getDataSize ( ) ) { case TINY : return options . isHashJoinForTiny ( ) ; case SMALL : return false ; default : return false ; } } private boolean isSupportedFormat ( InputDescription desc ) { assert desc != null ; assert desc . getImporterDescription ( ) != null ; ExternalIoDescriptionProcessor proc = getEnvironment ( ) . getExternals ( ) . findProcessor ( desc ) ; if ( proc == null ) { return false ; } Class < ? > formatType = proc . getInputInfo ( desc ) . getFormat ( ) ; return formatType == TemporaryInputFormat . class ; } private boolean rewriteSuccessors ( InputDescription source , FlowIn < ? > input ) { assert input != null ; LinkedList < FlowElementInput > successors = new LinkedList < FlowElementInput > ( ) ; for ( FlowElementOutput output : input . getFlowElement ( ) . getOutputPorts ( ) ) { successors . addAll ( output . getOpposites ( ) ) ; } Set < FlowElement > saw = Sets . create ( ) ; boolean modified = false ; while ( successors . isEmpty ( ) == false ) { FlowElementInput next = successors . removeFirst ( ) ; FlowElement element = next . getOwner ( ) ; if ( saw . contains ( element ) ) { continue ; } saw . add ( element ) ; if ( element . getDescription ( ) . getKind ( ) == FlowElementKind . PSEUD ) { for ( FlowElementOutput output : element . getOutputPorts ( ) ) { successors . addAll ( output . getOpposites ( ) ) ; } continue ; } if ( element . getDescription ( ) . getKind ( ) == FlowElementKind . FLOW_COMPONENT ) { FlowPartDescription desc = ( FlowPartDescription ) element . getDescription ( ) ; FlowIn < ? > internal = desc . getInternalInputPort ( next . getDescription ( ) ) ; modified |= rewriteSuccessors ( source , internal ) ; continue ; } if ( element . getDescription ( ) . getKind ( ) == FlowElementKind . OPERATOR ) { modified |= rewriteOperator ( source , next ) ; continue ; } } return modified ; } private boolean rewriteOperator ( InputDescription source , FlowElementInput input ) { assert source != null ; assert input != null ; FlowElement element = input . getOwner ( ) ; assert element . getDescription ( ) . getKind ( ) == FlowElementKind . OPERATOR ; OperatorDescription desc = ( OperatorDescription ) element . getDescription ( ) ; Class < ? extends Annotation > annotationType = desc . getDeclaration ( ) . getAnnotationType ( ) ; Class < ? extends Annotation > sideDataType ; FlowElementInput master ; FlowElementInput tx ; if ( annotationType == MasterJoin . class ) { sideDataType = SideDataJoin . class ; master = getInput ( element , MasterJoin . ID_INPUT_MASTER ) ; tx = getInput ( element , MasterJoin . ID_INPUT_TRANSACTION ) ; } else if ( annotationType == MasterBranch . class ) { sideDataType = SideDataBranch . class ; master = getInput ( element , MasterBranch . ID_INPUT_MASTER ) ; tx = getInput ( element , MasterBranch . ID_INPUT_TRANSACTION ) ; } else if ( annotationType == MasterCheck . class ) { sideDataType = SideDataCheck . class ; master = getInput ( element , MasterCheck . ID_INPUT_MASTER ) ; tx = getInput ( element , MasterCheck . ID_INPUT_TRANSACTION ) ; } else if ( annotationType == MasterJoinUpdate . class ) { sideDataType = SideDataJoinUpdate . class ; master = getInput ( element , MasterJoinUpdate . ID_INPUT_MASTER ) ; tx = getInput ( element , MasterJoinUpdate . ID_INPUT_TRANSACTION ) ; } else { return false ; } if ( master . equals ( input ) == false ) { return false ; } OperatorDescription . Builder builder = createSideDataOperator ( desc , sideDataType ) ; builder . addInput ( tx . getDescription ( ) . getName ( ) , tx . getDescription ( ) . getDataType ( ) ) ; builder . addResource ( createResource ( source , master , tx ) ) ; FlowElement rewrite = new FlowElement ( builder . toDescription ( ) ) ; for ( FlowElementOutput upstream : tx . getOpposites ( ) ) { PortConnection . connect ( upstream , rewrite . getInputPorts ( ) . get ( ) ) ; } List < FlowElementOutput > originalOutputs = element . getOutputPorts ( ) ; List < FlowElementOutput > rewriteOutputs = rewrite . getOutputPorts ( ) ; assert originalOutputs . size ( ) == rewriteOutputs . size ( ) ; for ( int i = , n = originalOutputs . size ( ) ; i < n ; i ++ ) { FlowElementOutput originalPort = originalOutputs . get ( i ) ; FlowElementOutput rewritePort = rewriteOutputs . get ( i ) ; for ( FlowElementInput downstream : originalPort . getOpposites ( ) ) { PortConnection . connect ( rewritePort , downstream ) ; } } FlowGraphUtil . disconnect ( element ) ; return false ; } private FlowResourceDescription createResource ( InputDescription source , FlowElementInput master , FlowElementInput tx ) { assert source != null ; assert master != null ; assert tx != null ; return new JoinResourceDescription ( source , toDataClass ( master ) , toJoinKey ( master ) , toDataClass ( tx ) , toJoinKey ( tx ) ) ; } private DataClass toDataClass ( FlowElementInput input ) { assert input != null ; Type runtime = input . getDescription ( ) . getDataType ( ) ; DataClass type = getEnvironment ( ) . getDataClasses ( ) . load ( runtime ) ; if ( type == null ) { getEnvironment ( ) . error ( "" , runtime ) ; return new DataClass . Unresolved ( getEnvironment ( ) . getModelFactory ( ) , runtime ) ; } return type ; } private List < Property > toJoinKey ( FlowElementInput input ) { assert input != null ; DataClass dataClass = toDataClass ( input ) ; ShuffleKey key = input . getDescription ( ) . getShuffleKey ( ) ; assert key != null ; List < Property > results = Lists . create ( ) ; for ( String name : key . getGroupProperties ( ) ) { Property property = dataClass . findProperty ( name ) ; if ( property == null ) { getEnvironment ( ) . error ( "" , dataClass , name ) ; } else { results . add ( property ) ; } } return results ; } private FlowElementInput getInput ( FlowElement element , int id ) { assert element != null ; return element . getInputPorts ( ) . get ( id ) ; } private OperatorDescription . Builder createSideDataOperator ( OperatorDescription desc , Class < ? extends Annotation > operatorType ) { assert desc != null ; assert operatorType != null ; OperatorDescription . Builder builder = new OperatorDescription . Builder ( operatorType ) ; builder . declare ( desc . getDeclaration ( ) . getDeclaring ( ) , desc . getDeclaration ( ) . getImplementing ( ) , desc . getDeclaration ( ) . getName ( ) ) ; for ( Class < ? > parameterType : desc . getDeclaration ( ) . getParameterTypes ( ) ) { builder . declareParameter ( parameterType ) ; } for ( FlowElementPortDescription port : desc . getOutputPorts ( ) ) { builder . addOutput ( port . getName ( ) , port . getDataType ( ) ) ; } for ( OperatorDescription . Parameter parameter : desc . getParameters ( ) ) { builder . addParameter ( parameter . getName ( ) , parameter . getType ( ) , parameter . getValue ( ) ) ; } for ( FlowElementAttribute attribute : desc . getAttributes ( ) ) { if ( attribute == FlowBoundary . SHUFFLE ) { builder . addAttribute ( FlowBoundary . DEFAULT ) ; } else { builder . addAttribute ( attribute ) ; } } return builder ; } @ Override public Name resolve ( FlowResourceDescription resource ) throws RewriteException { Precondition . checkMustNotBeNull ( resource , "" ) ; if ( ( resource instanceof JoinResourceDescription ) == false ) { return null ; } try { JoinResourceDescription joinResource = ( JoinResourceDescription ) resource ; Name compiled = JoinResourceEmitter . emit ( getEnvironment ( ) , joinResource ) ; return compiled ; } catch ( IOException e ) { throw new RewriteException ( "" , e ) ; } } } package com . asakusafw . compiler . flow . join ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; public class JoinResourceDescription implements FlowResourceDescription { private InputDescription masterInput ; private DataClass masterDataClass ; private List < DataClass . Property > masterJoinKeys ; private DataClass transactionDataClass ; private List < DataClass . Property > transactionJoinKeys ; public JoinResourceDescription ( InputDescription masterInput , DataClass masterDataClass , List < Property > masterJoinKeys , DataClass transactionDataClass , List < Property > transactionJoinKeys ) { Precondition . checkMustNotBeNull ( masterInput , "" ) ; Precondition . checkMustNotBeNull ( masterDataClass , "" ) ; Precondition . checkMustNotBeNull ( masterJoinKeys , "" ) ; Precondition . checkMustNotBeNull ( transactionDataClass , "" ) ; Precondition . checkMustNotBeNull ( transactionJoinKeys , "" ) ; this . masterInput = masterInput ; this . masterDataClass = masterDataClass ; this . masterJoinKeys = masterJoinKeys ; this . transactionDataClass = transactionDataClass ; this . transactionJoinKeys = transactionJoinKeys ; } @ Override public Set < InputDescription > getSideDataInputs ( ) { return Collections . singleton ( masterInput ) ; } public String getCacheName ( ) { return masterInput . getName ( ) ; } public DataClass getMasterDataClass ( ) { return masterDataClass ; } public DataClass getTransactionDataClass ( ) { return transactionDataClass ; } public List < DataClass . Property > getMasterJoinKeys ( ) { return masterJoinKeys ; } public List < DataClass . Property > getTransactionJoinKeys ( ) { return transactionJoinKeys ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + masterDataClass . hashCode ( ) ; result = prime * result + masterInput . hashCode ( ) ; result = prime * result + masterJoinKeys . hashCode ( ) ; result = prime * result + transactionDataClass . hashCode ( ) ; result = prime * result + transactionJoinKeys . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } JoinResourceDescription other = ( JoinResourceDescription ) obj ; if ( ! masterDataClass . equals ( other . masterDataClass ) ) { return false ; } if ( ! masterInput . equals ( other . masterInput ) ) { return false ; } if ( ! masterJoinKeys . equals ( other . masterJoinKeys ) ) { return false ; } if ( ! transactionDataClass . equals ( other . transactionDataClass ) ) { return false ; } if ( ! transactionJoinKeys . equals ( other . transactionJoinKeys ) ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , masterInput . getName ( ) , masterDataClass , masterJoinKeys , transactionDataClass , transactionJoinKeys ) ; } } package com . asakusafw . compiler . flow . join ; package com . asakusafw . compiler . flow . join . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . operator . MasterCheck ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface SideDataCheck { int ID_INPUT_TRANSACTION = ; int ID_OUTPUT_FOUND = ; int ID_OUTPUT_MISSED = ; int ID_RESOURCE_MASTER = ; } package com . asakusafw . compiler . flow . join . operator ; package com . asakusafw . compiler . flow . join . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . operator . MasterJoinUpdate ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface SideDataJoinUpdate { int ID_INPUT_TRANSACTION = ; int ID_OUTPUT_UPDATED = ; int ID_OUTPUT_MISSED = ; int ID_RESOURCE_MASTER = ; } package com . asakusafw . compiler . flow . join . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . operator . MasterBranch ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface SideDataBranch { int ID_INPUT_TRANSACTION = ; int ID_RESOURCE_MASTER = ; } package com . asakusafw . compiler . flow . join . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . operator . MasterJoin ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface SideDataJoin { int ID_INPUT_TRANSACTION = ; int ID_OUTPUT_JOINED = ; int ID_OUTPUT_MISSED = ; int ID_RESOURCE_MASTER = ; } package com . asakusafw . compiler . flow . join . processor ; package com . asakusafw . compiler . flow . join . processor ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . compiler . flow . join . JoinResourceDescription ; import com . asakusafw . compiler . flow . join . operator . SideDataCheck ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; @ TargetOperator ( SideDataCheck . class ) public class SideDataCheckFlowProcessor extends LineEndProcessor { @ Override public void emitLineEnd ( Context context ) { FlowResourceDescription resource = context . getResourceDescription ( SideDataCheck . ID_RESOURCE_MASTER ) ; SideDataKindFlowAnalyzer helper = new SideDataKindFlowAnalyzer ( context , ( JoinResourceDescription ) resource ) ; ModelFactory f = context . getModelFactory ( ) ; FlowElementPortDescription foundPort = context . getOutputPort ( SideDataCheck . ID_OUTPUT_FOUND ) ; FlowElementPortDescription missedPort = context . getOutputPort ( SideDataCheck . ID_OUTPUT_MISSED ) ; ResultMirror found = context . getOutput ( foundPort ) ; ResultMirror missed = context . getOutput ( missedPort ) ; context . add ( f . newIfStatement ( helper . getHasMasterExpresion ( ) , f . newBlock ( found . createAdd ( context . getInput ( ) ) ) , f . newBlock ( missed . createAdd ( context . getInput ( ) ) ) ) ) ; } } package com . asakusafw . compiler . flow . join . processor ; import java . lang . reflect . Method ; import java . util . List ; import com . asakusafw . compiler . common . EnumUtil ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . compiler . flow . join . JoinResourceDescription ; import com . asakusafw . compiler . flow . join . operator . SideDataBranch ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Tuple2 ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; @ TargetOperator ( SideDataBranch . class ) public class SideDataBranchFlowProcessor extends LineEndProcessor { @ Override public void emitLineEnd ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; FlowResourceDescription resource = context . getResourceDescription ( SideDataBranch . ID_RESOURCE_MASTER ) ; SideDataKindFlowAnalyzer helper = new SideDataKindFlowAnalyzer ( context , ( JoinResourceDescription ) resource ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( helper . getGetCheckedMasterExpression ( ) ) ; arguments . add ( context . getInput ( ) ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } Method method = desc . getDeclaration ( ) . toMethod ( ) ; assert method != null : desc . getDeclaration ( ) ; Class < ? > enumType = method . getReturnType ( ) ; List < Tuple2 < Enum < ? > , FlowElementPortDescription > > constants = EnumUtil . extractConstants ( enumType , desc . getOutputPorts ( ) ) ; Expression impl = context . createImplementation ( ) ; Expression branch = context . createLocalVariable ( context . convert ( enumType ) , new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toExpression ( ) ) ; List < Statement > cases = Lists . create ( ) ; for ( Tuple2 < Enum < ? > , FlowElementPortDescription > tuple : constants ) { Enum < ? > constant = tuple . first ; FlowElementPortDescription port = tuple . second ; ResultMirror next = context . getOutput ( port ) ; cases . add ( f . newSwitchCaseLabel ( f . newSimpleName ( constant . name ( ) ) ) ) ; cases . add ( next . createAdd ( context . getInput ( ) ) ) ; cases . add ( f . newBreakStatement ( ) ) ; } cases . add ( f . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( f , context . convert ( AssertionError . class ) ) . newObject ( branch ) . toThrowStatement ( ) ) ; context . add ( f . newSwitchStatement ( branch , cases ) ) ; } } package com . asakusafw . compiler . flow . join . processor ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . compiler . flow . join . JoinResourceDescription ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorHelper ; public class SideDataKindFlowAnalyzer { private final JoinResourceDescription resource ; private Expression hasMasterExpresion ; private Expression getMasterExpression ; private Expression getCheckedMasterExpression ; public SideDataKindFlowAnalyzer ( LineEndProcessor . Context context , JoinResourceDescription resource ) { Precondition . checkMustNotBeNull ( context , "" ) ; Precondition . checkMustNotBeNull ( resource , "" ) ; OperatorHelper selector = context . getOperatorDescription ( ) . getAttribute ( OperatorHelper . class ) ; this . resource = resource ; if ( selector == null ) { processMasterFirst ( context ) ; } else { processMasterSelection ( context , selector ) ; } } public Expression getHasMasterExpresion ( ) { return hasMasterExpresion ; } public Expression getGetRawMasterExpression ( ) { return getMasterExpression ; } public Expression getGetCheckedMasterExpression ( ) { return getCheckedMasterExpression ; } private void processMasterFirst ( LineEndProcessor . Context context ) { assert context != null ; ModelFactory f = context . getModelFactory ( ) ; Expression lookup = createLookup ( context , f ) ; this . hasMasterExpresion = new ExpressionBuilder ( f , lookup ) . method ( "" ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) ; this . getMasterExpression = new ExpressionBuilder ( f , lookup ) . method ( "" , Models . toLiteral ( f , ) ) . toExpression ( ) ; this . getCheckedMasterExpression = f . newConditionalExpression ( new ExpressionBuilder ( f , lookup ) . method ( "" ) . toExpression ( ) , Models . toNullLiteral ( f ) , getMasterExpression ) ; } private void processMasterSelection ( LineEndProcessor . Context context , OperatorHelper selector ) { assert context != null ; assert selector != null ; ModelFactory f = context . getModelFactory ( ) ; Expression lookup = createLookup ( context , f ) ; Expression selected = context . createLocalVariable ( resource . getMasterDataClass ( ) . getType ( ) , Models . toNullLiteral ( f ) ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( lookup ) ; arguments . add ( context . getInput ( ) ) ; for ( OperatorDescription . Parameter param : context . getOperatorDescription ( ) . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } assert selector . getParameterTypes ( ) . size ( ) <= arguments . size ( ) ; if ( selector . getParameterTypes ( ) . size ( ) <= arguments . size ( ) ) { arguments = arguments . subList ( , selector . getParameterTypes ( ) . size ( ) ) ; } Expression impl = context . createImplementation ( ) ; context . add ( f . newIfStatement ( new ExpressionBuilder ( f , lookup ) . apply ( InfixOperator . NOT_EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , selected ) . assignFrom ( new ExpressionBuilder ( f , impl ) . method ( selector . getName ( ) , arguments ) . toExpression ( ) ) . toStatement ( ) ) ) ) ; this . hasMasterExpresion = new ExpressionBuilder ( f , selected ) . apply ( InfixOperator . NOT_EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) ; this . getMasterExpression = selected ; this . getCheckedMasterExpression = selected ; } private Expression createLookup ( LineEndProcessor . Context context , ModelFactory f ) { assert context != null ; assert f != null ; Expression lookup = context . createLocalVariable ( context . simplify ( new TypeBuilder ( f , Models . toType ( f , List . class ) ) . parameterize ( Models . toType ( f , resource . getMasterDataClass ( ) . getType ( ) ) ) . toType ( ) ) , new ExpressionBuilder ( f , context . getResource ( resource ) ) . method ( "" , context . getInput ( ) ) . toExpression ( ) ) ; return lookup ; } } package com . asakusafw . compiler . flow . join . processor ; import java . util . List ; import java . util . Set ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . compiler . flow . join . JoinResourceDescription ; import com . asakusafw . compiler . flow . join . operator . SideDataJoin ; import com . asakusafw . runtime . util . TypeUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . model . Joined ; @ TargetOperator ( SideDataJoin . class ) public class SideDataJoinFlowProcessor extends LineEndProcessor { @ Override public void emitLineEnd ( Context context ) { FlowResourceDescription resource = context . getResourceDescription ( SideDataJoin . ID_RESOURCE_MASTER ) ; SideDataKindFlowAnalyzer helper = new SideDataKindFlowAnalyzer ( context , ( JoinResourceDescription ) resource ) ; ModelFactory f = context . getModelFactory ( ) ; FlowElementPortDescription joinedPort = context . getOutputPort ( SideDataJoin . ID_OUTPUT_JOINED ) ; FlowElementPortDescription missedPort = context . getOutputPort ( SideDataJoin . ID_OUTPUT_MISSED ) ; DataObjectMirror resultCache = context . createModelCache ( joinedPort . getDataType ( ) ) ; DataClass outputType = getEnvironment ( ) . getDataClasses ( ) . load ( joinedPort . getDataType ( ) ) ; List < Statement > process = Lists . create ( ) ; process . add ( resultCache . createReset ( ) ) ; Joined annotation = TypeUtil . erase ( joinedPort . getDataType ( ) ) . getAnnotation ( Joined . class ) ; Set < String > saw = Sets . create ( ) ; for ( Joined . Term term : annotation . terms ( ) ) { DataClass inputType = getEnvironment ( ) . getDataClasses ( ) . load ( term . source ( ) ) ; Expression input ; if ( term . source ( ) . equals ( context . getInputPort ( SideDataJoin . ID_INPUT_TRANSACTION ) . getDataType ( ) ) ) { input = context . getInput ( ) ; } else { input = helper . getGetRawMasterExpression ( ) ; } for ( Joined . Mapping mapping : term . mappings ( ) ) { if ( saw . contains ( mapping . destination ( ) ) ) { continue ; } saw . add ( mapping . destination ( ) ) ; Property sourceProperty = inputType . findProperty ( mapping . source ( ) ) ; Property destinationProperty = outputType . findProperty ( mapping . destination ( ) ) ; process . add ( destinationProperty . createSetter ( resultCache . get ( ) , sourceProperty . createGetter ( input ) ) ) ; } } ResultMirror joined = context . getOutput ( joinedPort ) ; process . add ( joined . createAdd ( resultCache . get ( ) ) ) ; ResultMirror missed = context . getOutput ( missedPort ) ; context . add ( f . newIfStatement ( helper . getHasMasterExpresion ( ) , f . newBlock ( process ) , f . newBlock ( missed . createAdd ( context . getInput ( ) ) ) ) ) ; } } package com . asakusafw . compiler . flow . join . processor ; import java . util . List ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . compiler . flow . join . JoinResourceDescription ; import com . asakusafw . compiler . flow . join . operator . SideDataJoinUpdate ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; @ TargetOperator ( SideDataJoinUpdate . class ) public class SideDataJoinUpdateFlowProcessor extends LineEndProcessor { @ Override public void emitLineEnd ( Context context ) { FlowResourceDescription resource = context . getResourceDescription ( SideDataJoinUpdate . ID_RESOURCE_MASTER ) ; SideDataKindFlowAnalyzer helper = new SideDataKindFlowAnalyzer ( context , ( JoinResourceDescription ) resource ) ; ModelFactory f = context . getModelFactory ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; FlowElementPortDescription updatedPort = context . getOutputPort ( SideDataJoinUpdate . ID_OUTPUT_UPDATED ) ; FlowElementPortDescription missedPort = context . getOutputPort ( SideDataJoinUpdate . ID_OUTPUT_MISSED ) ; ResultMirror updated = context . getOutput ( updatedPort ) ; ResultMirror missed = context . getOutput ( missedPort ) ; Expression impl = context . createImplementation ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( helper . getGetRawMasterExpression ( ) ) ; arguments . add ( context . getInput ( ) ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } context . add ( f . newIfStatement ( helper . getHasMasterExpresion ( ) , f . newBlock ( new Statement [ ] { new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toStatement ( ) , updated . createAdd ( context . getInput ( ) ) } ) , f . newBlock ( missed . createAdd ( context . getInput ( ) ) ) ) ) ; } } package com . asakusafw . compiler . flow . join ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . runtime . flow . join . JoinResource ; import com . asakusafw . runtime . flow . join . LookUpKey ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public final class JoinResourceEmitter { static final Logger LOG = LoggerFactory . getLogger ( JoinResourceEmitter . class ) ; private final FlowCompilingEnvironment environment ; private final ModelFactory factory ; private final ImportBuilder importer ; private final JoinResourceDescription resource ; private JoinResourceEmitter ( FlowCompilingEnvironment environment , JoinResourceDescription resource ) { assert environment != null ; assert resource != null ; this . environment = environment ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getResourcePackage ( "" ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . resource = resource ; } public static Name emit ( FlowCompilingEnvironment environment , JoinResourceDescription resource ) throws IOException { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( resource , "" ) ; JoinResourceEmitter emitter = new JoinResourceEmitter ( environment , resource ) ; return emitter . emit ( ) ; } private Name emit ( ) throws IOException { LOG . info ( "" , resource ) ; CompilationUnit source = generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , resource , name ) ; return name ; } private CompilationUnit generate ( ) { ClassDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private ClassDeclaration createType ( ) { SimpleName name = environment . createUniqueName ( "" ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = createMembers ( ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . linkType ( importer . toType ( resource . getMasterDataClass ( ) . getType ( ) ) ) . text ( "" ) . linkType ( importer . toType ( resource . getTransactionDataClass ( ) . getType ( ) ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , name , importer . resolve ( new TypeBuilder ( factory , Models . toType ( factory , JoinResource . class ) ) . parameterize ( resource . getMasterDataClass ( ) . getType ( ) , resource . getTransactionDataClass ( ) . getType ( ) ) . toType ( ) ) , Collections . < Type > emptyList ( ) , members ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createGetCacheName ( ) ) ; results . add ( createCreateValueObject ( ) ) ; results . add ( createBuildLeftKey ( ) ) ; results . add ( createBuildRightKey ( ) ) ; return results ; } private MethodDeclaration createGetCacheName ( ) { Expression result = Models . toLiteral ( factory , resource . getCacheName ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . Protected ( ) . toAttributes ( ) , importer . toType ( String . class ) , factory . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( new ExpressionBuilder ( factory , result ) . toReturnStatement ( ) ) ) ; } private MethodDeclaration createCreateValueObject ( ) { Expression result = new TypeBuilder ( factory , importer . toType ( resource . getMasterDataClass ( ) . getType ( ) ) ) . newObject ( ) . toExpression ( ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . Protected ( ) . toAttributes ( ) , importer . toType ( resource . getMasterDataClass ( ) . getType ( ) ) , factory . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( new ExpressionBuilder ( factory , result ) . toReturnStatement ( ) ) ) ; } private MethodDeclaration createBuildLeftKey ( ) { return createBuildKey ( "" , resource . getMasterDataClass ( ) , resource . getMasterJoinKeys ( ) ) ; } private MethodDeclaration createBuildRightKey ( ) { return createBuildKey ( "" , resource . getTransactionDataClass ( ) , resource . getTransactionJoinKeys ( ) ) ; } private MethodDeclaration createBuildKey ( String methodName , DataClass dataClass , List < Property > joinKeys ) { assert methodName != null ; assert dataClass != null ; assert joinKeys != null ; SimpleName value = factory . newSimpleName ( "" ) ; SimpleName key = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; for ( Property join : joinKeys ) { statements . add ( new ExpressionBuilder ( factory , key ) . method ( "" , join . createGetter ( value ) ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( factory , key ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . Protected ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , importer . toType ( LookUpKey . class ) , factory . newSimpleName ( methodName ) , Arrays . asList ( new FormalParameterDeclaration [ ] { factory . newFormalParameterDeclaration ( importer . toType ( dataClass . getType ( ) ) , value ) , factory . newFormalParameterDeclaration ( importer . toType ( LookUpKey . class ) , key ) , } ) , , Collections . singletonList ( importer . toType ( IOException . class ) ) , factory . newBlock ( statements ) ) ; } } package com . asakusafw . compiler . flow ; package com . asakusafw . compiler . flow . external ; package com . asakusafw . compiler . flow . external ; import java . util . List ; import java . util . ListIterator ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . Repository ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . collections . Tuple2 ; import com . asakusafw . utils . collections . Tuples ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . FlowOut ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class ExternalIoAnalyzer { static final Logger LOG = LoggerFactory . getLogger ( ExternalIoAnalyzer . class ) ; private final FlowCompilingEnvironment environment ; public ExternalIoAnalyzer ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public boolean validate ( FlowGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; LOG . info ( "" , graph . getDescription ( ) . getName ( ) ) ; List < Tuple2 < InputDescription , ExternalIoDescriptionProcessor > > inputs = Lists . create ( ) ; List < Tuple2 < OutputDescription , ExternalIoDescriptionProcessor > > outputs = Lists . create ( ) ; if ( collect ( graph , inputs , outputs ) == false ) { return false ; } boolean valid = true ; Set < ExternalIoDescriptionProcessor > processors = getActiveProcessors ( inputs , outputs ) ; for ( ExternalIoDescriptionProcessor proc : processors ) { List < InputDescription > in = getOnly ( inputs , proc ) ; List < OutputDescription > out = getOnly ( outputs , proc ) ; valid &= proc . validate ( in , out ) ; } return valid ; } private < T > List < T > getOnly ( List < Tuple2 < T , ExternalIoDescriptionProcessor > > inputs , ExternalIoDescriptionProcessor proc ) { assert inputs != null ; assert proc != null ; List < T > results = Lists . create ( ) ; for ( Tuple2 < T , ExternalIoDescriptionProcessor > tuple : inputs ) { if ( tuple . second . equals ( proc ) ) { results . add ( tuple . first ) ; } } return results ; } private Set < ExternalIoDescriptionProcessor > getActiveProcessors ( List < Tuple2 < InputDescription , ExternalIoDescriptionProcessor > > inputs , List < Tuple2 < OutputDescription , ExternalIoDescriptionProcessor > > outputs ) { assert inputs != null ; assert outputs != null ; Map < Class < ? > , ExternalIoDescriptionProcessor > actives = Maps . create ( ) ; for ( Tuple2 < InputDescription , ExternalIoDescriptionProcessor > tuple : inputs ) { actives . put ( tuple . second . getClass ( ) , tuple . second ) ; } for ( Tuple2 < OutputDescription , ExternalIoDescriptionProcessor > tuple : outputs ) { actives . put ( tuple . second . getClass ( ) , tuple . second ) ; } normalize ( inputs , actives ) ; normalize ( outputs , actives ) ; return Sets . from ( actives . values ( ) ) ; } private < T > void normalize ( List < Tuple2 < T , ExternalIoDescriptionProcessor > > list , Map < Class < ? > , ExternalIoDescriptionProcessor > actives ) { assert list != null ; assert actives != null ; for ( ListIterator < Tuple2 < T , ExternalIoDescriptionProcessor > > iter = list . listIterator ( ) ; iter . hasNext ( ) ; ) { Tuple2 < T , ExternalIoDescriptionProcessor > tuple = iter . next ( ) ; ExternalIoDescriptionProcessor normal = actives . get ( tuple . second . getClass ( ) ) ; iter . set ( Tuples . of ( tuple . first , normal ) ) ; } } private boolean collect ( FlowGraph graph , List < Tuple2 < InputDescription , ExternalIoDescriptionProcessor > > inputs , List < Tuple2 < OutputDescription , ExternalIoDescriptionProcessor > > outputs ) { assert graph != null ; assert inputs != null ; assert outputs != null ; boolean valid = true ; Repository externals = environment . getExternals ( ) ; for ( FlowIn < ? > port : graph . getFlowInputs ( ) ) { InputDescription desc = port . getDescription ( ) ; ExternalIoDescriptionProcessor processor = externals . findProcessor ( desc ) ; if ( processor != null ) { inputs . add ( Tuples . of ( desc , processor ) ) ; } else { environment . error ( "" , desc . getClass ( ) . getName ( ) ) ; valid = false ; } } for ( FlowOut < ? > port : graph . getFlowOutputs ( ) ) { OutputDescription desc = port . getDescription ( ) ; ExternalIoDescriptionProcessor processor = externals . findProcessor ( desc ) ; if ( processor != null ) { outputs . add ( Tuples . of ( desc , processor ) ) ; } else { valid = false ; } } return valid ; } } package com . asakusafw . compiler . flow ; import java . util . Map ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttributeProvider ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; public abstract class LineEndProcessor extends LineProcessor { @ Override public final Kind getKind ( ) { return Kind . LINE_END ; } public abstract void emitLineEnd ( Context context ) ; public static class Context extends LineProcessorContext { private final Expression input ; private final Map < FlowElementPortDescription , Expression > outputs ; public Context ( FlowCompilingEnvironment environment , FlowElementAttributeProvider element , ImportBuilder importer , NameGenerator names , OperatorDescription desc , Expression input , Map < FlowElementPortDescription , Expression > outputs , Map < FlowResourceDescription , Expression > resources ) { super ( environment , element , importer , names , desc , resources ) ; Precondition . checkMustNotBeNull ( input , "" ) ; Precondition . checkMustNotBeNull ( outputs , "" ) ; this . input = input ; this . outputs = outputs ; } public Expression getInput ( ) { return input ; } public ResultMirror getOutput ( FlowElementPortDescription port ) { Precondition . checkMustNotBeNull ( port , "" ) ; Expression result = outputs . get ( port ) ; if ( result == null ) { throw new IllegalArgumentException ( ) ; } return new ResultMirror ( factory , result ) ; } } } package com . asakusafw . compiler . flow ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttributeProvider ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; public abstract class RendezvousProcessor extends AbstractFlowElementProcessor { @ Override public final Kind getKind ( ) { return Kind . RENDEZVOUS ; } public ShuffleDescription getShuffleDescription ( FlowElementDescription element , FlowElementPortDescription port ) { Precondition . checkMustNotBeNull ( element , "" ) ; Precondition . checkMustNotBeNull ( port , "" ) ; LinePartProcessor nop = new LinePartProcessor . Nop ( ) ; nop . initialize ( getEnvironment ( ) ) ; return new ShuffleDescription ( port . getDataType ( ) , port . getShuffleKey ( ) , nop ) ; } public abstract void emitRendezvous ( Context context ) ; public boolean isPartial ( FlowElementDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; return false ; } public static class Context extends AbstractProcessorContext { private final Map < FlowElementPortDescription , Expression > inputs ; private final Map < FlowElementPortDescription , Expression > outputs ; private final List < Statement > beginStatements ; private final Map < FlowElementPortDescription , List < Statement > > processStatements ; private final List < Statement > endStatements ; public Context ( FlowCompilingEnvironment environment , FlowElementAttributeProvider element , ImportBuilder importer , NameGenerator names , OperatorDescription desc , Map < FlowElementPortDescription , Expression > inputs , Map < FlowElementPortDescription , Expression > outputs , Map < FlowResourceDescription , Expression > resources ) { super ( environment , element , importer , names , desc , resources ) ; Precondition . checkMustNotBeNull ( inputs , "" ) ; Precondition . checkMustNotBeNull ( outputs , "" ) ; this . inputs = inputs ; this . outputs = outputs ; this . beginStatements = Lists . create ( ) ; this . processStatements = Maps . create ( ) ; this . endStatements = Lists . create ( ) ; for ( FlowElementPortDescription input : inputs . keySet ( ) ) { processStatements . put ( input , new ArrayList < Statement > ( ) ) ; } } public ResultMirror getOutput ( FlowElementPortDescription port ) { Precondition . checkMustNotBeNull ( port , "" ) ; Expression result = outputs . get ( port ) ; if ( result == null ) { throw new IllegalArgumentException ( port . toString ( ) ) ; } return new ResultMirror ( factory , result ) ; } public Expression getProcessInput ( FlowElementPortDescription port ) { Precondition . checkMustNotBeNull ( port , "" ) ; return getCommonInput ( port ) ; } private Expression getCommonInput ( FlowElementPortDescription port ) { assert port != null ; Expression input = inputs . get ( port ) ; if ( input == null ) { throw new IllegalArgumentException ( port . toString ( ) ) ; } return input ; } public void addBegin ( Statement statement ) { Precondition . checkMustNotBeNull ( statement , "" ) ; beginStatements . add ( statement ) ; } public void addProcess ( FlowElementPortDescription port , Statement statement ) { Precondition . checkMustNotBeNull ( port , "" ) ; Precondition . checkMustNotBeNull ( statement , "" ) ; List < Statement > statements = processStatements . get ( port ) ; if ( statements == null ) { throw new IllegalArgumentException ( port . toString ( ) ) ; } statements . add ( statement ) ; } public void addEnd ( Statement statement ) { Precondition . checkMustNotBeNull ( statement , "" ) ; endStatements . add ( statement ) ; } public List < Statement > getBeginStatements ( ) { return beginStatements ; } public List < Statement > getProcessStatements ( FlowElementPortDescription port ) { Precondition . checkMustNotBeNull ( port , "" ) ; List < Statement > statements = processStatements . get ( port ) ; if ( statements == null ) { throw new IllegalArgumentException ( port . toString ( ) ) ; } return statements ; } public List < Statement > getEndStatements ( ) { return endStatements ; } } } package com . asakusafw . compiler . flow ; import java . text . MessageFormat ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . regex . Pattern ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . FlowOut ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class FlowDescriptionDriver { private final List < Object > ports = Lists . create ( ) ; private final Map < String , FlowIn < ? > > inputs = new LinkedHashMap < String , FlowIn < ? > > ( ) ; private final Map < String , FlowOut < ? > > outputs = new LinkedHashMap < String , FlowOut < ? > > ( ) ; public < T > In < T > createIn ( String name , ImporterDescription importer ) { Precondition . checkMustNotBeNull ( name , "" ) ; Precondition . checkMustNotBeNull ( importer , "" ) ; if ( isValidName ( name ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } if ( inputs . containsKey ( name ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , name ) ) ; } FlowIn < T > in = new FlowIn < T > ( new InputDescription ( name , importer ) ) ; inputs . put ( name , in ) ; ports . add ( in ) ; return in ; } public < T > Out < T > createOut ( String name , ExporterDescription exporter ) { Precondition . checkMustNotBeNull ( name , "" ) ; Precondition . checkMustNotBeNull ( exporter , "" ) ; if ( isValidName ( name ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } if ( outputs . containsKey ( name ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , name ) ) ; } FlowOut < T > out = new FlowOut < T > ( new OutputDescription ( name , exporter ) ) ; outputs . put ( name , out ) ; ports . add ( out ) ; return out ; } private static final Pattern VALID_NAME = Pattern . compile ( "" ) ; public boolean isValidName ( String name ) { if ( name == null ) { return false ; } return VALID_NAME . matcher ( name ) . matches ( ) ; } public List < Object > getPorts ( ) { return ports ; } public FlowGraph createFlowGraph ( FlowDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; description . start ( ) ; FlowGraph result = new FlowGraph ( description . getClass ( ) , Lists . from ( inputs . values ( ) ) , Lists . from ( outputs . values ( ) ) ) ; inputs . clear ( ) ; outputs . clear ( ) ; return result ; } } package com . asakusafw . compiler . flow ; import java . util . List ; import com . asakusafw . runtime . flow . FlowResource ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; public interface FlowGraphRewriter extends FlowCompilingEnvironment . Initializable { boolean rewrite ( FlowGraph graph ) throws RewriteException ; Name resolve ( FlowResourceDescription resource ) throws RewriteException ; class RewriteException extends Exception { private static final long serialVersionUID = ; public RewriteException ( ) { super ( ) ; } public RewriteException ( String message , Throwable cause ) { super ( message , cause ) ; } public RewriteException ( String message ) { super ( message ) ; } public RewriteException ( Throwable cause ) { super ( cause ) ; } } interface Repository extends FlowCompilingEnvironment . Initializable { List < FlowGraphRewriter > getRewriters ( ) ; } } package com . asakusafw . compiler . flow ; import java . io . Serializable ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . runtime . util . VariableTable ; public class ExternalIoCommandProvider implements Serializable { private static final long serialVersionUID = ; public String getName ( ) { return "" ; } public List < Command > getImportCommand ( CommandContext context ) { return Collections . emptyList ( ) ; } public List < Command > getExportCommand ( CommandContext context ) { return Collections . emptyList ( ) ; } @ Deprecated public List < Command > getRecoverCommand ( CommandContext context ) { return Collections . emptyList ( ) ; } public List < Command > getInitializeCommand ( CommandContext context ) { return Collections . emptyList ( ) ; } public List < Command > getFinalizeCommand ( CommandContext context ) { return Collections . emptyList ( ) ; } public static class CommandContext { private final String homePathPrefix ; private final String executionId ; private final String variableList ; public CommandContext ( String homePathPrefix , String executionId , String variableList ) { Precondition . checkMustNotBeNull ( homePathPrefix , "" ) ; Precondition . checkMustNotBeNull ( executionId , "" ) ; Precondition . checkMustNotBeNull ( variableList , "" ) ; this . homePathPrefix = homePathPrefix ; this . executionId = executionId ; this . variableList = variableList ; } public CommandContext ( String homePathPrefix , String executionId , Map < String , String > variables ) { Precondition . checkMustNotBeNull ( homePathPrefix , "" ) ; Precondition . checkMustNotBeNull ( executionId , "" ) ; Precondition . checkMustNotBeNull ( variables , "" ) ; this . homePathPrefix = homePathPrefix ; this . executionId = executionId ; VariableTable table = new VariableTable ( ) ; table . defineVariables ( variables ) ; this . variableList = table . toSerialString ( ) ; } public String getHomePathPrefix ( ) { return homePathPrefix ; } public String getExecutionId ( ) { return executionId ; } public String getVariableList ( ) { return variableList ; } } public static class Command { private final List < String > commandLine ; private final String moduleName ; private final String profileName ; private final Map < String , String > environment ; public Command ( List < String > commandLine , String moduleName , String profileName , Map < String , String > environment ) { Precondition . checkMustNotBeNull ( commandLine , "" ) ; Precondition . checkMustNotBeNull ( moduleName , "" ) ; this . commandLine = commandLine ; this . moduleName = moduleName ; this . profileName = profileName ; this . environment = environment ; } public List < String > getCommandTokens ( ) { return commandLine ; } public String getCommandLineString ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : environment . entrySet ( ) ) { buf . append ( "" + entry . getKey ( ) + "" ) ; buf . append ( "" ) ; buf . append ( "" + entry . getValue ( ) + "" ) ; buf . append ( "" ) ; } Iterator < String > iter = commandLine . iterator ( ) ; if ( iter . hasNext ( ) ) { buf . append ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( "" ) ; buf . append ( iter . next ( ) ) ; } } return buf . toString ( ) ; } public String getModuleName ( ) { return moduleName ; } public String getProfileName ( ) { return profileName ; } public Map < String , String > getEnvironment ( ) { return environment ; } } } package com . asakusafw . compiler . flow ; import java . io . DataInput ; import java . io . DataOutput ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . CommentEmitTrait ; import com . asakusafw . utils . java . model . util . Models ; public interface DataClass { java . lang . reflect . Type getType ( ) ; Collection < ? extends Property > getProperties ( ) ; Property findProperty ( String propertyName ) ; Expression createNewInstance ( Type type ) ; Statement assign ( Expression target , Expression source ) ; Statement reset ( Expression object ) ; Statement createWriter ( Expression object , Expression dataOutput ) ; Statement createReader ( Expression object , Expression dataInput ) ; class Unresolved implements DataClass { private final ModelFactory factory ; private final java . lang . reflect . Type runtimeType ; public Unresolved ( ModelFactory factory , java . lang . reflect . Type runtimeType ) { Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( runtimeType , "" ) ; this . factory = factory ; this . runtimeType = runtimeType ; } @ Override public java . lang . reflect . Type getType ( ) { return runtimeType ; } @ Override public Collection < ? extends Property > getProperties ( ) { return Collections . emptySet ( ) ; } @ Override public Property findProperty ( String propertyName ) { return null ; } @ Override public Statement reset ( Expression object ) { Statement statement = factory . newEmptyStatement ( ) ; statement . putModelTrait ( CommentEmitTrait . class , new CommentEmitTrait ( Arrays . asList ( MessageFormat . format ( "" , runtimeType ) ) ) ) ; return statement ; } @ Override public Expression createNewInstance ( Type type ) { Expression expression = Models . toNullLiteral ( factory ) ; expression . putModelTrait ( CommentEmitTrait . class , new CommentEmitTrait ( Arrays . asList ( MessageFormat . format ( "" , runtimeType ) ) ) ) ; return expression ; } @ Override public Statement assign ( Expression target , Expression source ) { Statement statement = factory . newEmptyStatement ( ) ; statement . putModelTrait ( CommentEmitTrait . class , new CommentEmitTrait ( Arrays . asList ( MessageFormat . format ( "" , runtimeType ) ) ) ) ; return statement ; } @ Override public Statement createWriter ( Expression object , Expression dataOutput ) { Statement statement = factory . newEmptyStatement ( ) ; statement . putModelTrait ( CommentEmitTrait . class , new CommentEmitTrait ( Arrays . asList ( MessageFormat . format ( "" , runtimeType ) ) ) ) ; return statement ; } @ Override public Statement createReader ( Expression object , Expression dataInput ) { Statement statement = factory . newEmptyStatement ( ) ; statement . putModelTrait ( CommentEmitTrait . class , new CommentEmitTrait ( Arrays . asList ( MessageFormat . format ( "" , runtimeType ) ) ) ) ; return statement ; } } interface Property { String getName ( ) ; java . lang . reflect . Type getType ( ) ; boolean canNull ( ) ; Expression createNewInstance ( Type target ) ; Expression createIsNull ( Expression object ) ; Expression createGetter ( Expression object ) ; Statement assign ( Expression target , Expression source ) ; Statement createGetter ( Expression object , Expression target ) ; Statement createSetter ( Expression object , Expression value ) ; Statement createWriter ( Expression object , Expression dataOutput ) ; Statement createReader ( Expression object , Expression dataInput ) ; Expression createHashCode ( Expression object ) ; Expression createBytesSize ( Expression bytes , Expression start , Expression length ) ; Expression createBytesDiff ( Expression bytes1 , Expression start1 , Expression length1 , Expression bytes2 , Expression start2 , Expression length2 ) ; Expression createValueDiff ( Expression value1 , Expression value2 ) ; } } package com . asakusafw . compiler . flow . packager ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Locale ; import java . util . Set ; import java . util . jar . JarEntry ; import java . util . jar . JarOutputStream ; import java . util . zip . ZipEntry ; import javax . tools . Diagnostic ; import javax . tools . DiagnosticCollector ; import javax . tools . JavaCompiler ; import javax . tools . JavaCompiler . CompilationTask ; import javax . tools . JavaFileObject ; import javax . tools . StandardJavaFileManager ; import javax . tools . ToolProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . ResourceRepository ; import com . asakusafw . compiler . batch . ResourceRepository . Cursor ; import com . asakusafw . compiler . common . FileRepository ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . Packager ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . util . Filer ; public class FilePackager extends FlowCompilingEnvironment . Initialized implements Packager { static final Logger LOG = LoggerFactory . getLogger ( FilePackager . class ) ; private static final Charset CHARSET = Charset . forName ( "" ) ; private static final String SOURCE_DIRECTORY = "" ; private static final String CLASS_DIRECTORY = "" ; private final File sourceDirectory ; private final File classDirectory ; private final Filer sourceFiler ; private final Filer resourceFiler ; private final List < ? extends ResourceRepository > fragmentRepositories ; public FilePackager ( File workingDirectory , List < ? extends ResourceRepository > fragmentRepositories ) { Precondition . checkMustNotBeNull ( workingDirectory , "" ) ; Precondition . checkMustNotBeNull ( fragmentRepositories , "" ) ; this . fragmentRepositories = fragmentRepositories ; this . sourceDirectory = new File ( workingDirectory , SOURCE_DIRECTORY ) ; this . classDirectory = new File ( workingDirectory , CLASS_DIRECTORY ) ; this . sourceFiler = new Filer ( sourceDirectory , CHARSET ) ; this . resourceFiler = new Filer ( classDirectory , CHARSET ) ; } @ Override public PrintWriter openWriter ( CompilationUnit source ) throws IOException { Precondition . checkMustNotBeNull ( source , "" ) ; return sourceFiler . openFor ( source ) ; } @ Override public OutputStream openStream ( Name packageNameOrNull , String relativePath ) throws IOException { Precondition . checkMustNotBeNull ( relativePath , "" ) ; File directory = resourceFiler . getFolderFor ( packageNameOrNull ) ; File file = new File ( directory , relativePath ) ; mkdir ( file . getParentFile ( ) ) ; return new FileOutputStream ( file ) ; } private void mkdir ( File file ) throws IOException { assert file != null ; if ( file . isDirectory ( ) == false ) { if ( file . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , file ) ) ; } } } @ Override public void build ( OutputStream output ) throws IOException { compile ( ) ; JarOutputStream jar = new JarOutputStream ( output ) ; try { LOG . info ( "" ) ; List < ResourceRepository > repos = Lists . create ( ) ; if ( classDirectory . exists ( ) ) { repos . add ( new FileRepository ( classDirectory ) ) ; } boolean exists = drain ( jar , repos , fragmentRepositories ) ; if ( exists == false ) { LOG . warn ( "" ) ; addDummyEntry ( jar ) ; } } finally { try { jar . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } @ Override public void packageSources ( OutputStream output ) throws IOException { LOG . debug ( "" ) ; JarOutputStream jar = new JarOutputStream ( output ) ; try { boolean exists = drain ( jar , Collections . singletonList ( new FileRepository ( sourceDirectory ) ) , Collections . < ResourceRepository > emptyList ( ) ) ; if ( exists == false ) { LOG . warn ( "" ) ; addDummyEntry ( jar ) ; } } finally { try { jar . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } private boolean drain ( JarOutputStream jar , Iterable < ? extends ResourceRepository > main , Iterable < ? extends ResourceRepository > fragments ) throws IOException { assert jar != null ; assert fragments != null ; Set < Location > saw = Sets . create ( ) ; for ( ResourceRepository repo : main ) { drainRepo ( repo , jar , saw , true ) ; } for ( ResourceRepository repo : fragments ) { drainRepo ( repo , jar , saw , false ) ; } return saw . isEmpty ( ) == false ; } private void drainRepo ( ResourceRepository repo , JarOutputStream jar , Set < Location > saw , boolean allowFrameworkInfo ) throws IOException { assert repo != null ; assert jar != null ; assert saw != null ; Cursor cursor = repo . createCursor ( ) ; try { while ( cursor . next ( ) ) { Location location = cursor . getLocation ( ) ; if ( allowFrameworkInfo == false && ( FRAMEWORK_INFO . isPrefixOf ( location ) || MANIFEST_FILE . isPrefixOf ( location ) ) ) { LOG . debug ( "" , location ) ; continue ; } if ( saw . contains ( location ) ) { LOG . warn ( "" , location ) ; continue ; } saw . add ( location ) ; addEntry ( jar , cursor . openResource ( ) , location ) ; } } finally { cursor . close ( ) ; } } private void addDummyEntry ( JarOutputStream jar ) throws IOException { ZipEntry entry = new ZipEntry ( "" ) ; entry . setComment ( "" ) ; jar . putNextEntry ( entry ) ; } private void addEntry ( JarOutputStream jar , InputStream source , Location location ) throws IOException { assert jar != null ; assert source != null ; assert location != null ; LOG . trace ( "" , location ) ; JarEntry entry = new JarEntry ( location . toPath ( '' ) ) ; jar . putNextEntry ( entry ) ; try { byte [ ] buffer = new byte [ ] ; while ( true ) { int read = source . read ( buffer ) ; if ( read < ) { break ; } jar . write ( buffer , , read ) ; } jar . closeEntry ( ) ; } finally { source . close ( ) ; } } private void compile ( ) throws IOException { LOG . debug ( "" ) ; JavaCompiler compiler = ToolProvider . getSystemJavaCompiler ( ) ; if ( compiler == null ) { throw new IllegalStateException ( "" ) ; } if ( sourceDirectory . isDirectory ( ) == false ) { return ; } List < File > sources = collect ( sourceDirectory , new ArrayList < File > ( ) ) ; if ( sources . isEmpty ( ) ) { return ; } compile ( compiler , sources ) ; } private void compile ( JavaCompiler compiler , List < File > sources ) throws IOException { assert compiler != null ; assert sources != null ; LOG . info ( "" , sources . size ( ) ) ; LOG . debug ( "" , classDirectory ) ; mkdir ( sourceDirectory ) ; mkdir ( classDirectory ) ; DiagnosticCollector < JavaFileObject > diagnostics = new DiagnosticCollector < JavaFileObject > ( ) ; StandardJavaFileManager fileManager = compiler . getStandardFileManager ( diagnostics , Locale . getDefault ( ) , CHARSET ) ; try { List < String > arguments = Lists . create ( ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , CHARSET . name ( ) ) ; Collections . addAll ( arguments , "" , sourceDirectory . getCanonicalFile ( ) . toString ( ) ) ; Collections . addAll ( arguments , "" , classDirectory . getCanonicalFile ( ) . toString ( ) ) ; Collections . addAll ( arguments , "" ) ; StringWriter errors = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( errors ) ; LOG . debug ( "" , arguments ) ; CompilationTask task = compiler . getTask ( pw , fileManager , diagnostics , arguments , Collections . < String > emptyList ( ) , fileManager . getJavaFileObjectsFromFiles ( sources ) ) ; Boolean succeeded = task . call ( ) ; pw . close ( ) ; for ( Diagnostic < ? > diagnostic : diagnostics . getDiagnostics ( ) ) { switch ( diagnostic . getKind ( ) ) { case ERROR : case MANDATORY_WARNING : getEnvironment ( ) . error ( diagnostic . getMessage ( null ) ) ; break ; case WARNING : LOG . warn ( diagnostic . getMessage ( null ) ) ; break ; default : LOG . info ( diagnostic . getMessage ( null ) ) ; break ; } } if ( Boolean . TRUE . equals ( succeeded ) == false ) { throw new IOException ( MessageFormat . format ( "" , getEnvironment ( ) . getTargetId ( ) , errors . toString ( ) ) ) ; } } finally { fileManager . close ( ) ; } } private List < File > collect ( File file , List < File > sourceFiles ) { if ( file . isFile ( ) ) { LOG . trace ( "" , file ) ; sourceFiles . add ( file ) ; } else { for ( File child : file . listFiles ( ) ) { collect ( child , sourceFiles ) ; } } return sourceFiles ; } } package com . asakusafw . compiler . flow . packager ; package com . asakusafw . compiler . flow ; import java . lang . annotation . Annotation ; import java . util . Map ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttributeProvider ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Identity ; public abstract class LinePartProcessor extends LineProcessor { @ Override public final Kind getKind ( ) { return Kind . LINE_PART ; } public abstract void emitLinePart ( Context context ) ; public static class Context extends LineProcessorContext { private final Expression input ; private Expression resultValue ; public Context ( FlowCompilingEnvironment environment , FlowElementAttributeProvider element , ImportBuilder importer , NameGenerator names , OperatorDescription desc , Expression input , Map < FlowResourceDescription , Expression > resources ) { super ( environment , element , importer , names , desc , resources ) ; Precondition . checkMustNotBeNull ( input , "" ) ; this . input = input ; this . resultValue = null ; } public Expression getInput ( ) { return input ; } public void setOutput ( Expression expresion ) { Precondition . checkMustNotBeNull ( expresion , "" ) ; if ( this . resultValue != null ) { throw new IllegalStateException ( ) ; } this . resultValue = expresion ; } public Expression getOutput ( ) { if ( resultValue == null ) { throw new IllegalStateException ( ) ; } return resultValue ; } } @ TargetOperator ( Identity . class ) public static class Nop extends LinePartProcessor { @ Override protected Class < ? extends Annotation > loadTargetAnnotationType ( ) { return Identity . class ; } @ Override public void emitLinePart ( Context context ) { context . setOutput ( context . getInput ( ) ) ; } } } package com . asakusafw . compiler . flow ; import java . util . Collections ; import java . util . Map ; import java . util . NoSuchElementException ; import java . util . Properties ; import java . util . Set ; import java . util . TreeSet ; import java . util . concurrent . ConcurrentHashMap ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; public class FlowCompilerOptions { static final Logger LOG = LoggerFactory . getLogger ( FlowCompilerOptions . class ) ; public static final String K_OPTIONS = "" ; public static final String PREFIX_EXTRA_OPTION = "" ; public enum Item { enableCombiner ( false ) { @ Override public void setTo ( FlowCompilerOptions options , boolean value ) { options . setEnableCombiner ( value ) ; } } , compressFlowPart ( true ) { @ Override public void setTo ( FlowCompilerOptions options , boolean value ) { options . setCompressFlowPart ( value ) ; } } , compressConcurrentStage ( true ) { @ Override public void setTo ( FlowCompilerOptions options , boolean value ) { options . setCompressConcurrentStage ( value ) ; } } , hashJoinForTiny ( true ) { @ Override public void setTo ( FlowCompilerOptions options , boolean value ) { options . setHashJoinForTiny ( value ) ; } } , hashJoinForSmall ( false ) { @ Override public void setTo ( FlowCompilerOptions options , boolean value ) { options . setHashJoinForSmall ( value ) ; } } , enableDebugLogging ( false ) { @ Override public void setTo ( FlowCompilerOptions options , boolean value ) { options . setEnableDebugLogging ( value ) ; } } , ; public final boolean defaultValue ; private Item ( boolean defaultValue ) { this . defaultValue = defaultValue ; } public abstract void setTo ( FlowCompilerOptions options , boolean value ) ; } public enum GenericOptionValue { ENABLED ( "" , "" , "" , "" , "" , "" , "" ) , DISABLED ( "" , "" , "" , "" , "" , "" , "" ) , AUTO ( "" ) , INVALID ( "" ) , ; private final String primary ; private final Set < String > symbols ; private GenericOptionValue ( String primary , String ... symbols ) { assert primary != null ; assert symbols != null ; this . primary = primary ; this . symbols = new TreeSet < String > ( String . CASE_INSENSITIVE_ORDER ) ; Collections . addAll ( this . symbols , primary ) ; Collections . addAll ( this . symbols , symbols ) ; } public String getSymbol ( ) { return primary ; } public static GenericOptionValue fromSymbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } for ( GenericOptionValue value : values ( ) ) { if ( value . symbols . contains ( symbol ) ) { return value ; } } return INVALID ; } } private volatile boolean enableCombiner ; private volatile boolean compressFlowPart ; private volatile boolean compressConcurrentStage ; private volatile boolean hashJoinForTiny ; private volatile boolean hashJoinForSmall ; private volatile boolean enableDebugLogging ; private final Map < String , String > extraAttributes = new ConcurrentHashMap < String , String > ( ) ; public FlowCompilerOptions ( ) { for ( Item item : Item . values ( ) ) { item . setTo ( this , item . defaultValue ) ; } } private static final Pattern OPTION = Pattern . compile ( "" ) ; private static final Pattern EXTRA_OPTION = Pattern . compile ( "" ) ; public static FlowCompilerOptions load ( Properties properties ) { Precondition . checkMustNotBeNull ( properties , "" ) ; String [ ] options = properties . getProperty ( K_OPTIONS , "" ) . split ( "" ) ; FlowCompilerOptions results = new FlowCompilerOptions ( ) ; for ( String option : options ) { if ( option . isEmpty ( ) ) { continue ; } Matcher optionMatcher = OPTION . matcher ( option ) ; if ( optionMatcher . matches ( ) ) { boolean value = optionMatcher . group ( ) . equals ( "" ) ; String name = optionMatcher . group ( ) ; try { Item item = Item . valueOf ( name ) ; item . setTo ( results , value ) ; } catch ( NoSuchElementException e ) { LOG . warn ( "" , option ) ; } } else { Matcher extraMatcher = EXTRA_OPTION . matcher ( option ) ; if ( extraMatcher . matches ( ) ) { String key = extraMatcher . group ( ) . trim ( ) ; String value = extraMatcher . group ( ) . trim ( ) ; results . extraAttributes . put ( key , value ) ; } else { LOG . warn ( "" , option ) ; } } } return results ; } public boolean isEnableCombiner ( ) { return enableCombiner ; } public void setEnableCombiner ( boolean enable ) { this . enableCombiner = enable ; } public boolean isCompressFlowPart ( ) { return compressFlowPart ; } public void setCompressFlowPart ( boolean enable ) { this . compressFlowPart = enable ; } public boolean isCompressConcurrentStage ( ) { return compressConcurrentStage ; } public void setCompressConcurrentStage ( boolean enable ) { this . compressConcurrentStage = enable ; } public boolean isHashJoinForTiny ( ) { return hashJoinForTiny ; } public void setHashJoinForTiny ( boolean enable ) { this . hashJoinForTiny = enable ; } public boolean isHashJoinForSmall ( ) { return hashJoinForSmall ; } public void setHashJoinForSmall ( boolean enable ) { this . hashJoinForSmall = enable ; } public boolean isEnableDebugLogging ( ) { return this . enableDebugLogging ; } public void setEnableDebugLogging ( boolean enable ) { this . enableDebugLogging = enable ; } public String getExtraAttributeKeyName ( String optionName ) { if ( optionName == null ) { throw new IllegalArgumentException ( "" ) ; } return PREFIX_EXTRA_OPTION + optionName ; } public String getExtraAttribute ( String name ) { return this . extraAttributes . get ( name ) ; } public GenericOptionValue getGenericExtraAttribute ( String name , GenericOptionValue defaultValue ) { String value = this . extraAttributes . get ( name ) ; if ( value == null ) { return defaultValue ; } GenericOptionValue symbol = GenericOptionValue . fromSymbol ( value ) ; return symbol ; } public void putExtraAttribute ( String name , String value ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value == null ) { this . extraAttributes . remove ( name ) ; } else { this . extraAttributes . put ( name , value ) ; } } } package com . asakusafw . compiler . flow ; import java . lang . annotation . Annotation ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . NoSuchElementException ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . runtime . flow . ArrayListBuffer ; import com . asakusafw . runtime . flow . FileMapListBuffer ; import com . asakusafw . runtime . flow . ListBuffer ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttributeProvider ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; public interface FlowElementProcessor extends FlowCompilingEnvironment . Initializable { String RESULT_METHOD_NAME = "" ; FlowElementProcessor . Kind getKind ( ) ; Class < ? extends Annotation > getTargetAnnotationType ( ) ; public abstract static class AbstractProcessorContext implements FlowElementAttributeProvider { protected final FlowCompilingEnvironment environment ; private final FlowElementAttributeProvider element ; protected final ModelFactory factory ; protected final ImportBuilder importer ; protected final NameGenerator names ; protected final OperatorDescription description ; protected final Map < FlowResourceDescription , Expression > resources ; protected final List < FieldDeclaration > generatedFields ; public AbstractProcessorContext ( FlowCompilingEnvironment environment , FlowElementAttributeProvider element , ImportBuilder importer , NameGenerator names , OperatorDescription desc , Map < FlowResourceDescription , Expression > resources ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( importer , "" ) ; Precondition . checkMustNotBeNull ( element , "" ) ; Precondition . checkMustNotBeNull ( names , "" ) ; Precondition . checkMustNotBeNull ( desc , "" ) ; Precondition . checkMustNotBeNull ( resources , "" ) ; this . environment = environment ; this . element = element ; this . factory = environment . getModelFactory ( ) ; this . importer = importer ; this . names = names ; this . description = desc ; this . resources = resources ; this . generatedFields = Lists . create ( ) ; } public OperatorDescription getOperatorDescription ( ) { return description ; } @ Override public < T extends FlowElementAttribute > T getAttribute ( Class < T > attributeClass ) { if ( attributeClass == null ) { throw new IllegalArgumentException ( "" ) ; } return element . getAttribute ( attributeClass ) ; } public FlowElementPortDescription getInputPort ( int portNumber ) { if ( portNumber < || portNumber >= description . getInputPorts ( ) . size ( ) ) { throw new IllegalArgumentException ( "" ) ; } return description . getInputPorts ( ) . get ( portNumber ) ; } public FlowElementPortDescription getOutputPort ( int portNumber ) { if ( portNumber < || portNumber >= description . getOutputPorts ( ) . size ( ) ) { throw new IllegalArgumentException ( "" ) ; } return description . getOutputPorts ( ) . get ( portNumber ) ; } public FlowResourceDescription getResourceDescription ( int resourceNumber ) { if ( resourceNumber < || resourceNumber >= description . getResources ( ) . size ( ) ) { throw new IllegalArgumentException ( "" ) ; } FlowResourceDescription resource = description . getResources ( ) . get ( resourceNumber ) ; return resource ; } public Expression getResource ( FlowResourceDescription resource ) { Precondition . checkMustNotBeNull ( resource , "" ) ; Expression expression = resources . get ( resource ) ; assert expression != null ; return expression ; } public ModelFactory getModelFactory ( ) { return factory ; } private Expression addField ( Type type , String name , Expression init ) { assert type != null ; assert name != null ; SimpleName fieldName = createName ( name ) ; FieldDeclaration field = factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , type , fieldName , init ) ; generatedFields . add ( field ) ; return factory . newFieldAccessExpression ( factory . newThis ( ) , fieldName ) ; } public List < FieldDeclaration > getGeneratedFields ( ) { return generatedFields ; } public SimpleName createName ( String hint ) { Precondition . checkMustNotBeNull ( hint , "" ) ; return names . create ( hint ) ; } public Expression createImplementation ( ) { Class < ? > implementing = description . getDeclaration ( ) . getImplementing ( ) ; Type type = convert ( implementing ) ; return addField ( type , "" , new TypeBuilder ( factory , type ) . newObject ( ) . toExpression ( ) ) ; } public Expression createField ( java . lang . reflect . Type type , String name ) { Precondition . checkMustNotBeNull ( type , "" ) ; Precondition . checkMustNotBeNull ( name , "" ) ; return addField ( importer . toType ( type ) , name , null ) ; } public DataObjectMirror createModelCache ( java . lang . reflect . Type type ) { Precondition . checkMustNotBeNull ( type , "" ) ; DataClass data = environment . getDataClasses ( ) . load ( type ) ; if ( data == null ) { environment . error ( "" , type ) ; data = new DataClass . Unresolved ( factory , type ) ; } Type domType = importer . toType ( type ) ; Expression cache = addField ( domType , "" , data . createNewInstance ( domType ) ) ; return new DataObjectMirror ( factory , cache , data ) ; } public ListBufferMirror createListBuffer ( java . lang . reflect . Type type , InputBuffer bufferKind ) { Precondition . checkMustNotBeNull ( type , "" ) ; Precondition . checkMustNotBeNull ( bufferKind , "" ) ; Type elementType = importer . toType ( type ) ; Class < ? > bufferType = inputBufferTypeFromKind ( bufferKind ) ; Type listType = importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , bufferType ) , Collections . singletonList ( elementType ) ) ) ; Expression list = addField ( listType , "" , new TypeBuilder ( factory , listType ) . newObject ( ) . toExpression ( ) ) ; DataClass component = environment . getDataClasses ( ) . load ( type ) ; if ( component == null ) { environment . error ( "" , type ) ; component = new DataClass . Unresolved ( factory , type ) ; } return new ListBufferMirror ( factory , list , component , elementType ) ; } private Class < ? > inputBufferTypeFromKind ( InputBuffer kind ) { assert kind != null ; switch ( kind ) { case EXPAND : return ArrayListBuffer . class ; case ESCAPE : return FileMapListBuffer . class ; default : throw new AssertionError ( kind ) ; } } public Type convert ( java . lang . reflect . Type type ) { Precondition . checkMustNotBeNull ( type , "" ) ; return importer . toType ( type ) ; } public Type simplify ( Type type ) { Precondition . checkMustNotBeNull ( type , "" ) ; return importer . resolve ( type ) ; } } public static class DataObjectMirror { private final Expression object ; private final DataClass dataClass ; public DataObjectMirror ( ModelFactory factory , Expression object , DataClass dataClass ) { Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( object , "" ) ; Precondition . checkMustNotBeNull ( dataClass , "" ) ; this . object = object ; this . dataClass = dataClass ; } public Expression get ( ) { return object ; } public Statement createSet ( Expression value ) { Precondition . checkMustNotBeNull ( value , "" ) ; return dataClass . assign ( object , value ) ; } public Statement createReset ( ) { return dataClass . reset ( object ) ; } } public static class ResultMirror { private final ModelFactory factory ; private final Expression object ; public ResultMirror ( ModelFactory factory , Expression object ) { Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( object , "" ) ; this . factory = factory ; this . object = object ; } public Expression get ( ) { return object ; } public Statement createAdd ( Expression value ) { Precondition . checkMustNotBeNull ( value , "" ) ; return new ExpressionBuilder ( factory , object ) . method ( RESULT_METHOD_NAME , value ) . toStatement ( ) ; } } public static class ListBufferMirror { private static final String BEGIN = "" ; private static final String ADVANCE = "" ; private static final String END = "" ; private static final String EXPAND = "" ; private static final String IS_EXPAND_REQUIRED = "" ; private static final String SHRINK = "" ; private final ModelFactory factory ; private final Expression object ; private final DataClass dataClass ; private final Type elementType ; public ListBufferMirror ( ModelFactory factory , Expression object , DataClass dataClass , Type elementType ) { Precondition . checkMustNotBeNull ( factory , "" ) ; Precondition . checkMustNotBeNull ( object , "" ) ; Precondition . checkMustNotBeNull ( dataClass , "" ) ; this . factory = factory ; this . object = object ; this . dataClass = dataClass ; this . elementType = elementType ; } public Expression get ( ) { return object ; } public Statement createBegin ( ) { return new ExpressionBuilder ( factory , object ) . method ( BEGIN ) . toStatement ( ) ; } public Statement createAdvance ( Expression value ) { Precondition . checkMustNotBeNull ( value , "" ) ; List < Statement > thenBlock = Arrays . asList ( new Statement [ ] { new ExpressionBuilder ( factory , object ) . method ( EXPAND , dataClass . createNewInstance ( elementType ) ) . toStatement ( ) , dataClass . assign ( new ExpressionBuilder ( factory , object ) . method ( ADVANCE ) . toExpression ( ) , value ) , } ) ; List < Statement > elseBlock = Arrays . asList ( new Statement [ ] { dataClass . assign ( new ExpressionBuilder ( factory , object ) . method ( ADVANCE ) . toExpression ( ) , value ) , } ) ; return factory . newIfStatement ( new ExpressionBuilder ( factory , object ) . method ( IS_EXPAND_REQUIRED ) . toExpression ( ) , factory . newBlock ( thenBlock ) , factory . newBlock ( elseBlock ) ) ; } public Statement createEnd ( ) { return new ExpressionBuilder ( factory , object ) . method ( END ) . toStatement ( ) ; } public Statement createShrink ( ) { return new ExpressionBuilder ( factory , object ) . method ( SHRINK ) . toStatement ( ) ; } } interface Repository extends FlowCompilingEnvironment . Initializable { LinePartProcessor getEmptyProcessor ( ) ; FlowElementProcessor findProcessor ( FlowElementDescription description ) ; LineProcessor findLineProcessor ( FlowElementDescription description ) ; RendezvousProcessor findRendezvousProcessor ( FlowElementDescription description ) ; } enum Kind { LINE_PART , LINE_END , RENDEZVOUS , } } package com . asakusafw . compiler . flow . stage ; package com . asakusafw . compiler . flow . stage ; import java . util . Arrays ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . TaskInputOutputContext ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . ResourceFragment ; import com . asakusafw . compiler . flow . stage . StageModel . Sink ; import com . asakusafw . compiler . flow . stage . StageModel . Unit ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . flow . RuntimeResourceManager ; import com . asakusafw . runtime . flow . VoidResult ; import com . asakusafw . runtime . stage . output . StageOutputDriver ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . utils . java . model . syntax . BasicTypeKind ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; public class FragmentFlow { private final FlowCompilingEnvironment environment ; private final ImportBuilder importer ; private final NameGenerator names ; private final StageModel stage ; private final List < ? extends StageModel . Unit < ? > > units ; private final ShuffleModel shuffle ; private final SimpleName resourceManager ; private final SimpleName stageOutputs ; private final Map < FlowElementInput , FragmentNode > lines = Maps . create ( ) ; private final Map < FlowElement , FragmentNode > rendezvous = Maps . create ( ) ; private Map < ResourceFragment , SimpleName > resources = Maps . create ( ) ; private final ModelFactory factory ; private final Graph < FragmentNode > dependencies ; public FragmentFlow ( FlowCompilingEnvironment environment , ImportBuilder importer , NameGenerator names , StageModel model , List < ? extends StageModel . Unit < ? > > units ) { Precondition . checkMustNotBeNull ( environment , "" ) ; Precondition . checkMustNotBeNull ( importer , "" ) ; Precondition . checkMustNotBeNull ( names , "" ) ; Precondition . checkMustNotBeNull ( model , "" ) ; Precondition . checkMustNotBeNull ( units , "" ) ; this . environment = environment ; this . factory = environment . getModelFactory ( ) ; this . importer = importer ; this . names = names ; this . stage = model ; this . units = units ; this . shuffle = model . getShuffleModel ( ) ; this . resources = createResources ( ) ; this . dependencies = analyzeDependencies ( ) ; resolveDependencies ( ) ; this . resourceManager = createRuntimeResourceManager ( ) ; this . stageOutputs = createStageOutputs ( ) ; } private SimpleName createRuntimeResourceManager ( ) { return names . create ( "" ) ; } private SimpleName createStageOutputs ( ) { for ( FragmentNode node : dependencies . getNodeSet ( ) ) { if ( node . getKind ( ) == Kind . OUTPUT ) { return names . create ( "" ) ; } } return null ; } private Graph < FragmentNode > analyzeDependencies ( ) { Map < FlowElementOutput , List < FragmentNode > > nodes = analyzeNodes ( ) ; Graph < FragmentNode > graph = Graphs . newInstance ( ) ; buildFragmentGraph ( nodes , graph ) ; buildOutputGraph ( nodes , graph ) ; if ( shuffle != null ) { buildShuffleGraph ( nodes , graph ) ; } return graph ; } private Map < ResourceFragment , SimpleName > createResources ( ) { Map < ResourceFragment , SimpleName > results = Maps . create ( ) ; for ( Unit < ? > unit : units ) { for ( Fragment fragment : unit . getFragments ( ) ) { for ( ResourceFragment resource : fragment . getResources ( ) ) { if ( results . containsKey ( resource ) ) { continue ; } results . put ( resource , names . create ( "" ) ) ; } } } return results ; } private void resolveDependencies ( ) { assert dependencies != null ; Graph < FragmentNode > tgraph = Graphs . transpose ( dependencies ) ; for ( Graph . Vertex < FragmentNode > vertex : tgraph ) { if ( vertex . getConnected ( ) . isEmpty ( ) == false ) { continue ; } FragmentNode node = vertex . getNode ( ) ; collectFragment ( node ) ; } } private void collectFragment ( FragmentNode node ) throws AssertionError { FlowElementInput port = ( ( StageModel . Fragment ) node . getValue ( ) ) . getInputPorts ( ) . get ( ) ; switch ( node . getKind ( ) ) { case LINE : assert lines . containsKey ( port ) == false ; lines . put ( port , node ) ; break ; case RENDEZVOUS : assert rendezvous . containsKey ( port . getOwner ( ) ) == false ; rendezvous . put ( port . getOwner ( ) , node ) ; break ; default : throw new AssertionError ( node . getKind ( ) ) ; } } private Map < FlowElementOutput , List < FragmentNode > > analyzeNodes ( ) { Set < Fragment > saw = Sets . create ( ) ; Map < FlowElementOutput , List < FragmentNode > > results = Maps . create ( ) ; for ( StageModel . Unit < ? > unit : units ) { for ( Fragment fragment : unit . getFragments ( ) ) { if ( saw . contains ( fragment ) ) { continue ; } saw . add ( fragment ) ; FragmentNode node ; if ( fragment . isRendezvous ( ) ) { node = new FragmentNode ( Kind . RENDEZVOUS , fragment , names . create ( "" ) ) ; } else { node = new FragmentNode ( Kind . LINE , fragment , names . create ( "" ) ) ; } for ( FlowElementOutput output : fragment . getOutputPorts ( ) ) { Maps . addToList ( results , output , node ) ; } } } return results ; } private void buildFragmentGraph ( Map < FlowElementOutput , List < FragmentNode > > nodes , Graph < FragmentNode > graph ) { assert nodes != null ; assert graph != null ; Set < FragmentNode > saw = Sets . create ( ) ; for ( Map . Entry < FlowElementOutput , List < FragmentNode > > entry : nodes . entrySet ( ) ) { for ( FragmentNode node : entry . getValue ( ) ) { if ( saw . contains ( node ) ) { continue ; } saw . add ( node ) ; graph . addNode ( node ) ; Fragment fragment = ( Fragment ) node . getValue ( ) ; for ( FlowElementInput input : fragment . getInputPorts ( ) ) { for ( FlowElementOutput pred : input . getOpposites ( ) ) { List < FragmentNode > sources = nodes . get ( pred ) ; if ( sources == null ) { continue ; } for ( FragmentNode source : sources ) { source . addDownstream ( pred , node ) ; graph . addEdge ( source , node ) ; } } } } } } private void buildOutputGraph ( Map < FlowElementOutput , List < FragmentNode > > nodes , Graph < FragmentNode > graph ) { assert nodes != null ; assert graph != null ; for ( Sink sink : stage . getStageResults ( ) ) { SimpleName name = names . create ( "" ) ; FragmentNode node = new FragmentNode ( Kind . OUTPUT , sink , name ) ; for ( FlowBlock . Output output : sink . getOutputs ( ) ) { FlowElementOutput target = output . getElementPort ( ) ; List < FragmentNode > sources = nodes . get ( target ) ; if ( sources == null ) { continue ; } for ( FragmentNode source : sources ) { source . addDownstream ( target , node ) ; graph . addEdge ( source , node ) ; } } } } private void buildShuffleGraph ( Map < FlowElementOutput , List < FragmentNode > > nodes , Graph < FragmentNode > graph ) { assert nodes != null ; assert graph != null ; assert shuffle != null ; assert stage . getStageBlock ( ) . hasReduceBlocks ( ) ; Map < FlowElementInput , FlowBlock . Input > inputMap = Maps . create ( ) ; for ( FlowBlock reduceBlock : stage . getStageBlock ( ) . getReduceBlocks ( ) ) { for ( FlowBlock . Input blockInput : reduceBlock . getBlockInputs ( ) ) { assert inputMap . containsKey ( blockInput . getElementPort ( ) ) == false ; inputMap . put ( blockInput . getElementPort ( ) , blockInput ) ; } } for ( ShuffleModel . Segment segment : shuffle . getSegments ( ) ) { FlowElementInput input = segment . getPort ( ) ; FlowBlock . Input blockInput = inputMap . get ( input ) ; if ( blockInput == null ) { continue ; } FragmentNode node = new FragmentNode ( Kind . SHUFFLE , segment , names . create ( "" ) ) ; for ( FlowBlock . Connection conn : blockInput . getConnections ( ) ) { FlowElementOutput shuffleOut = conn . getUpstream ( ) . getElementPort ( ) ; List < FragmentNode > sources = nodes . get ( shuffleOut ) ; if ( sources == null ) { continue ; } for ( FragmentNode source : sources ) { source . addDownstream ( shuffleOut , node ) ; graph . addEdge ( source , node ) ; } } } } public List < FieldDeclaration > createFields ( ) { List < FieldDeclaration > results = Lists . create ( ) ; results . add ( createResourceManagerField ( ) ) ; if ( stageOutputs != null ) { results . add ( createStageOutputsField ( ) ) ; } for ( Map . Entry < ResourceFragment , SimpleName > entry : resources . entrySet ( ) ) { results . add ( createResourceField ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } for ( FragmentNode node : lines . values ( ) ) { results . add ( createFragmentField ( node , ( StageModel . Fragment ) node . getValue ( ) ) ) ; } for ( FragmentNode node : rendezvous . values ( ) ) { results . add ( createFragmentField ( node , ( StageModel . Fragment ) node . getValue ( ) ) ) ; } return results ; } private FieldDeclaration createResourceField ( ResourceFragment resource , SimpleName name ) { assert resource != null ; assert name != null ; FieldDeclaration field = factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , importer . toType ( resource . getCompiled ( ) . getQualifiedName ( ) ) , name , null ) ; return field ; } private FieldDeclaration createResourceManagerField ( ) { FieldDeclaration field = factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , importer . toType ( RuntimeResourceManager . class ) , resourceManager , null ) ; return field ; } private FieldDeclaration createStageOutputsField ( ) { FieldDeclaration field = factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , importer . toType ( StageOutputDriver . class ) , stageOutputs , null ) ; return field ; } private FieldDeclaration createFragmentField ( FragmentNode node , StageModel . Fragment value ) { assert node != null ; assert value != null ; Type type = importer . resolve ( factory . newNamedType ( value . getCompiled ( ) . getQualifiedName ( ) ) ) ; return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , type , node . getName ( ) , null ) ; } public List < Statement > createSetup ( Expression context ) { Precondition . checkMustNotBeNull ( context , "" ) ; List < Statement > results = Lists . create ( ) ; results . addAll ( setupResourceManager ( context ) ) ; if ( stageOutputs != null ) { results . addAll ( setupStageOutputs ( context ) ) ; } results . addAll ( setupResources ( context ) ) ; results . addAll ( setupFragments ( context ) ) ; return results ; } private List < Statement > setupResources ( Expression context ) { assert context != null ; List < Statement > results = Lists . create ( ) ; for ( Map . Entry < ResourceFragment , SimpleName > entry : resources . entrySet ( ) ) { ResourceFragment resource = entry . getKey ( ) ; SimpleName field = entry . getValue ( ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( field ) . assignFrom ( new TypeBuilder ( factory , importer . toType ( resource . getCompiled ( ) . getQualifiedName ( ) ) ) . newObject ( ) . toExpression ( ) ) . toStatement ( ) ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( field ) . method ( "" , new ExpressionBuilder ( factory , context ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; } return results ; } private List < Statement > setupFragments ( Expression context ) { List < Statement > results = Lists . create ( ) ; for ( FragmentNode node : Graphs . sortPostOrder ( dependencies ) ) { switch ( node . getKind ( ) ) { case LINE : results . add ( setupLine ( node , ( StageModel . Fragment ) node . getValue ( ) ) ) ; break ; case RENDEZVOUS : results . add ( setupRendezvous ( node , ( StageModel . Fragment ) node . getValue ( ) ) ) ; break ; case SHUFFLE : results . add ( setupShuffle ( node , context , ( ShuffleModel . Segment ) node . getValue ( ) ) ) ; break ; case OUTPUT : results . add ( setupOutput ( node , ( StageModel . Sink ) node . getValue ( ) ) ) ; break ; default : throw new AssertionError ( node ) ; } } return results ; } private List < Statement > setupResourceManager ( Expression context ) { assert context != null ; List < Statement > results = Lists . create ( ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( resourceManager ) . assignFrom ( new TypeBuilder ( factory , importer . toType ( RuntimeResourceManager . class ) ) . newObject ( new ExpressionBuilder ( factory , context ) . method ( "" ) . toExpression ( ) ) . toExpression ( ) ) . toStatement ( ) ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( resourceManager ) . method ( "" ) . toStatement ( ) ) ; return results ; } private List < Statement > setupStageOutputs ( Expression context ) { assert context != null ; List < Statement > results = Lists . create ( ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( stageOutputs ) . assignFrom ( new TypeBuilder ( factory , importer . toType ( StageOutputDriver . class ) ) . newObject ( context ) . toExpression ( ) ) . toStatement ( ) ) ; return results ; } private Statement setupLine ( FragmentNode node , StageModel . Fragment value ) { assert node != null ; assert value != null ; assert value . getInputPorts ( ) . size ( ) == ; FlowElementInput input = value . getInputPorts ( ) . get ( ) ; Type type = importer . resolve ( factory . newNamedType ( value . getCompiled ( ) . getQualifiedName ( ) ) ) ; List < Expression > arguments = resolveArguments ( node , value ) ; if ( lines . containsKey ( input ) ) { return new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( node . getName ( ) ) . assignFrom ( new TypeBuilder ( factory , type ) . newObject ( arguments ) . toExpression ( ) ) . toStatement ( ) ; } else { return factory . newLocalVariableDeclaration ( new AttributeBuilder ( factory ) . Final ( ) . toAttributes ( ) , type , Collections . singletonList ( factory . newVariableDeclarator ( node . getName ( ) , new TypeBuilder ( factory , type ) . newObject ( arguments ) . toExpression ( ) ) ) ) ; } } private Statement setupRendezvous ( FragmentNode node , StageModel . Fragment value ) { assert node != null ; assert value != null ; assert value . getInputPorts ( ) . isEmpty ( ) == false ; FlowElement element = value . getInputPorts ( ) . get ( ) . getOwner ( ) ; Type type = importer . resolve ( factory . newNamedType ( value . getCompiled ( ) . getQualifiedName ( ) ) ) ; List < Expression > arguments = resolveArguments ( node , value ) ; assert rendezvous . containsKey ( element ) ; return new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( node . getName ( ) ) . assignFrom ( new TypeBuilder ( factory , type ) . newObject ( arguments ) . toExpression ( ) ) . toStatement ( ) ; } private List < Expression > resolveArguments ( FragmentNode node , StageModel . Fragment fragment ) { assert node != null ; assert fragment != null ; List < Expression > results = Lists . create ( ) ; for ( ResourceFragment resource : fragment . getResources ( ) ) { results . add ( resolveResouce ( resource ) ) ; } for ( FlowElementOutput output : fragment . getOutputPorts ( ) ) { results . add ( resolveArgument ( output . getDescription ( ) . getDataType ( ) , node . getDownstream ( output ) ) ) ; } return results ; } private Expression resolveResouce ( ResourceFragment resource ) { assert resource != null ; SimpleName name = resources . get ( resource ) ; assert name != null ; return name ; } private Expression resolveArgument ( java . lang . reflect . Type type , Set < FragmentNode > downstream ) { assert type != null ; assert downstream != null ; if ( downstream . isEmpty ( ) ) { return new TypeBuilder ( factory , importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , VoidResult . class ) , Collections . singletonList ( Models . toType ( factory , type ) ) ) ) ) . newObject ( ) . toExpression ( ) ; } if ( downstream . size ( ) == ) { FragmentNode succ = downstream . iterator ( ) . next ( ) ; return succ . getName ( ) ; } DataClass model = environment . getDataClasses ( ) . load ( type ) ; if ( model == null ) { throw new IllegalStateException ( type . toString ( ) ) ; } Type dataType = importer . toType ( model . getType ( ) ) ; SimpleName cacheName = names . create ( "" ) ; FieldDeclaration cache = factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , dataType , cacheName , model . createNewInstance ( dataType ) ) ; SimpleName argumentName = names . create ( "" ) ; List < Statement > statements = Lists . create ( ) ; Iterator < FragmentNode > iter = downstream . iterator ( ) ; while ( iter . hasNext ( ) ) { FragmentNode node = iter . next ( ) ; if ( iter . hasNext ( ) ) { statements . add ( model . assign ( cacheName , argumentName ) ) ; statements . add ( new ExpressionBuilder ( factory , node . getName ( ) ) . method ( FlowElementProcessor . RESULT_METHOD_NAME , cacheName ) . toStatement ( ) ) ; } else { statements . add ( new ExpressionBuilder ( factory , node . getName ( ) ) . method ( FlowElementProcessor . RESULT_METHOD_NAME , argumentName ) . toStatement ( ) ) ; } } MethodDeclaration result = factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( importer . toType ( Override . class ) ) . Public ( ) . toAttributes ( ) , factory . newBasicType ( BasicTypeKind . VOID ) , factory . newSimpleName ( FlowElementProcessor . RESULT_METHOD_NAME ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( Models . toType ( factory , model . getType ( ) ) , argumentName ) ) , statements ) ; return factory . newClassInstanceCreationExpression ( null , Collections . < Type > emptyList ( ) , importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , Result . class ) , dataType ) ) , Collections . < Expression > emptyList ( ) , factory . newClassBody ( Arrays . asList ( cache , result ) ) ) ; } private Statement setupShuffle ( FragmentNode node , Expression context , ShuffleModel . Segment value ) { assert node != null ; assert context != null ; assert value != null ; Type type = importer . toType ( value . getCompiled ( ) . getMapOutputType ( ) . getQualifiedName ( ) ) ; return factory . newLocalVariableDeclaration ( new AttributeBuilder ( factory ) . Final ( ) . toAttributes ( ) , type , Collections . singletonList ( factory . newVariableDeclarator ( node . getName ( ) , new TypeBuilder ( factory , type ) . newObject ( context ) . toExpression ( ) ) ) ) ; } private Statement setupOutput ( FragmentNode node , StageModel . Sink value ) { assert node != null ; assert value != null ; Type type = importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , Result . class ) , Models . toType ( factory , value . getType ( ) ) ) ) ; return factory . newLocalVariableDeclaration ( new AttributeBuilder ( factory ) . Final ( ) . toAttributes ( ) , type , Collections . singletonList ( factory . newVariableDeclarator ( node . getName ( ) , new ExpressionBuilder ( factory , stageOutputs ) . method ( "" , Models . toLiteral ( factory , value . getName ( ) ) ) . toExpression ( ) ) ) ) ; } public List < Statement > createCleanup ( SimpleName context ) { Precondition . checkMustNotBeNull ( context , "" ) ; List < Statement > results = Lists . create ( ) ; results . addAll ( cleanResourceManager ( context ) ) ; if ( stageOutputs != null ) { results . addAll ( cleanStageOutputs ( context ) ) ; } for ( Map . Entry < ResourceFragment , SimpleName > entry : resources . entrySet ( ) ) { results . add ( factory . newIfStatement ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( entry . getValue ( ) ) . apply ( InfixOperator . NOT_EQUALS , Models . toNullLiteral ( factory ) ) . toExpression ( ) , factory . newBlock ( new Statement [ ] { new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( entry . getValue ( ) ) . method ( "" , new ExpressionBuilder ( factory , context ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( entry . getValue ( ) ) . assignFrom ( Models . toNullLiteral ( factory ) ) . toStatement ( ) } ) ) ) ; } for ( FragmentNode node : lines . values ( ) ) { results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( node . getName ( ) ) . assignFrom ( Models . toNullLiteral ( factory ) ) . toStatement ( ) ) ; } for ( FragmentNode node : rendezvous . values ( ) ) { results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( node . getName ( ) ) . assignFrom ( Models . toNullLiteral ( factory ) ) . toStatement ( ) ) ; } return results ; } private List < Statement > cleanResourceManager ( SimpleName context ) { assert context != null ; List < Statement > results = Lists . create ( ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( resourceManager ) . method ( "" ) . toStatement ( ) ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( resourceManager ) . assignFrom ( Models . toNullLiteral ( factory ) ) . toStatement ( ) ) ; return results ; } private List < Statement > cleanStageOutputs ( SimpleName context ) { assert context != null ; List < Statement > results = Lists . create ( ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( stageOutputs ) . method ( "" ) . toStatement ( ) ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( stageOutputs ) . assignFrom ( Models . toNullLiteral ( factory ) ) . toStatement ( ) ) ; return results ; } public Type getShuffleKeyType ( ) { if ( shuffle == null ) { return importer . toType ( NullWritable . class ) ; } Name keyName = shuffle . getCompiled ( ) . getKeyTypeName ( ) ; return importer . resolve ( factory . newNamedType ( keyName ) ) ; } public Type getShuffleValueType ( ) { if ( shuffle == null ) { return importer . toType ( NullWritable . class ) ; } Name valueName = shuffle . getCompiled ( ) . getValueTypeName ( ) ; return importer . resolve ( factory . newNamedType ( valueName ) ) ; } public Expression getLine ( FlowElementInput input ) { Precondition . checkMustNotBeNull ( input , "" ) ; FragmentNode node = lines . get ( input ) ; if ( node == null ) { throw new IllegalArgumentException ( ) ; } return new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( node . getName ( ) ) . toExpression ( ) ; } public Expression getRendezvous ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; FragmentNode node = rendezvous . get ( element ) ; if ( node == null ) { throw new IllegalArgumentException ( ) ; } return new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( node . getName ( ) ) . toExpression ( ) ; } private static class FragmentNode { private final Kind kind ; private final Object value ; private final SimpleName name ; private final Map < FlowElementOutput , Set < FragmentNode > > downstreams ; FragmentNode ( Kind kind , Object value , SimpleName name ) { assert kind != null ; assert value != null ; assert name != null ; this . kind = kind ; this . value = value ; this . name = name ; this . downstreams = Maps . create ( ) ; } public void addDownstream ( FlowElementOutput output , FragmentNode downstream ) { assert output != null ; assert downstream != null ; Maps . addToSet ( downstreams , output , downstream ) ; } public Set < FragmentNode > getDownstream ( FlowElementOutput output ) { assert output != null ; Set < FragmentNode > set = downstreams . get ( output ) ; if ( set == null ) { return Collections . emptySet ( ) ; } return set ; } public Kind getKind ( ) { return kind ; } public Object getValue ( ) { return value ; } public SimpleName getName ( ) { return name ; } } public enum Kind { LINE , RENDEZVOUS , SHUFFLE , OUTPUT , } } package com . asakusafw . compiler . flow . stage ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . java . model . syntax . Name ; public class CompiledShuffle { private Name keyTypeName ; private Name valueTypeName ; private Name groupComparatorTypeName ; private Name sortComparatorTypeName ; private Name partitionerTypeName ; public CompiledShuffle ( Name keyTypeName , Name valueTypeName , Name groupComparatorTypeName , Name sortComparatorTypeName , Name partitionerTypeName ) { Precondition . checkMustNotBeNull ( keyTypeName , "" ) ; Precondition . checkMustNotBeNull ( valueTypeName , "" ) ; Precondition . checkMustNotBeNull ( groupComparatorTypeName , "" ) ; Precondition . checkMustNotBeNull ( sortComparatorTypeName , "" ) ; Precondition . checkMustNotBeNull ( partitionerTypeName , "" ) ; this . keyTypeName = keyTypeName ; this . valueTypeName = valueTypeName ; this . groupComparatorTypeName = groupComparatorTypeName ; this . sortComparatorTypeName = sortComparatorTypeName ; this . partitionerTypeName = partitionerTypeName ; } public Name getKeyTypeName ( ) { return keyTypeName ; } public Name getValueTypeName ( ) { return valueTypeName ; } public Name getGroupComparatorTypeName ( ) { return groupComparatorTypeName ; } public Name getSortComparatorTypeName ( ) { return sortComparatorTypeName ; } public Name getPartitionerTypeName ( ) { return partitionerTypeName ; } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . NullWritable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . flow . SegmentedReducer ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; public class ReducerEmitter { static final Logger LOG = LoggerFactory . getLogger ( ReducerEmitter . class ) ; private final FlowCompilingEnvironment environment ; public ReducerEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledType emit ( StageModel model ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; LOG . debug ( "" , model ) ; Engine engine = new Engine ( environment , model ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , model , name ) ; return new CompiledType ( name ) ; } private static class Engine { private final ShuffleModel shuffle ; private final ModelFactory factory ; private final ImportBuilder importer ; private final NameGenerator names ; private final FragmentFlow fragments ; private final SimpleName context ; Engine ( FlowCompilingEnvironment environment , StageModel model ) { assert environment != null ; assert model != null ; this . shuffle = model . getShuffleModel ( ) ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( model . getStageBlock ( ) . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . names = new NameGenerator ( factory ) ; this . fragments = new FragmentFlow ( environment , importer , names , model , model . getReduceUnits ( ) ) ; this . context = names . create ( "" ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getReduceClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( fragments . createFields ( ) ) ; members . add ( createSetup ( ) ) ; members . add ( createCleanup ( ) ) ; members . add ( createGetRendezvous ( ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , SegmentedReducer . class ) , Arrays . asList ( fragments . getShuffleKeyType ( ) , fragments . getShuffleValueType ( ) , t ( NullWritable . class ) , t ( NullWritable . class ) ) ) ) , Collections . < Type > emptyList ( ) , members ) ; } private MethodDeclaration createSetup ( ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newNamedType ( factory . newSimpleName ( "" ) ) , context ) ) , , Arrays . asList ( t ( IOException . class ) , t ( InterruptedException . class ) ) , factory . newBlock ( fragments . createSetup ( context ) ) ) ; } private MethodDeclaration createCleanup ( ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newNamedType ( factory . newSimpleName ( "" ) ) , context ) ) , , Arrays . asList ( t ( IOException . class ) , t ( InterruptedException . class ) ) , factory . newBlock ( fragments . createCleanup ( context ) ) ) ; } private MethodDeclaration createGetRendezvous ( ) { List < Statement > cases = Lists . create ( ) ; for ( List < ShuffleModel . Segment > group : ShuffleEmiterUtil . groupByElement ( shuffle ) ) { for ( ShuffleModel . Segment segment : group ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; } FlowElement element = group . get ( ) . getPort ( ) . getOwner ( ) ; cases . add ( new ExpressionBuilder ( factory , fragments . getRendezvous ( element ) ) . toReturnStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( ) . toThrowStatement ( ) ) ; SimpleName argument = names . create ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( factory . newSwitchStatement ( new ExpressionBuilder ( factory , argument ) . method ( SegmentedWritable . ID_GETTER ) . toExpression ( ) , cases ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , Rendezvous . class ) , Arrays . asList ( fragments . getShuffleValueType ( ) ) ) ) , factory . newSimpleName ( SegmentedReducer . GET_RENDEZVOUS ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( fragments . getShuffleKeyType ( ) , argument ) ) , statements ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , shuffle . getStageBlock ( ) . getStageNumber ( ) ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . ResourceFragment ; import com . asakusafw . compiler . flow . stage . StageModel . Unit ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; public class StageCompiler { static final Logger LOG = LoggerFactory . getLogger ( StageCompiler . class ) ; private final FlowCompilingEnvironment environment ; private final ShuffleAnalyzer shuffleAnalyzer ; private final StageAnalyzer mapredAnalyzer ; private final ShuffleKeyEmitter shuffleKeyEmitter ; private final ShuffleValueEmitter shuffleValueEmitter ; private final ShuffleGroupingComparatorEmitter shuffleGroupingEmitter ; private final ShuffleSortComparatorEmitter shuffleSortingEmitter ; private final ShufflePartitionerEmitter shuffleParitioningEmitter ; private final FlowResourceEmitter flowResourceEmitter ; private final MapFragmentEmitter mapFragmentEmitter ; private final ShuffleFragmentEmitter shuffleFragmentEmitter ; private final ReduceFragmentEmitter reduceFragmentEmitter ; private final MapperEmitter mapperEmitter ; private final ReducerEmitter reducerEmitter ; private final CombinerEmitter combinerEmitter ; public StageCompiler ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; this . shuffleAnalyzer = new ShuffleAnalyzer ( environment ) ; this . mapredAnalyzer = new StageAnalyzer ( environment ) ; this . shuffleKeyEmitter = new ShuffleKeyEmitter ( environment ) ; this . shuffleValueEmitter = new ShuffleValueEmitter ( environment ) ; this . shuffleGroupingEmitter = new ShuffleGroupingComparatorEmitter ( environment ) ; this . shuffleSortingEmitter = new ShuffleSortComparatorEmitter ( environment ) ; this . shuffleParitioningEmitter = new ShufflePartitionerEmitter ( environment ) ; this . flowResourceEmitter = new FlowResourceEmitter ( environment ) ; this . mapFragmentEmitter = new MapFragmentEmitter ( environment ) ; this . shuffleFragmentEmitter = new ShuffleFragmentEmitter ( environment ) ; this . reduceFragmentEmitter = new ReduceFragmentEmitter ( environment ) ; this . mapperEmitter = new MapperEmitter ( environment ) ; this . reducerEmitter = new ReducerEmitter ( environment ) ; this . combinerEmitter = new CombinerEmitter ( environment ) ; } public List < StageModel > compile ( StageGraph graph ) throws IOException { Precondition . checkMustNotBeNull ( graph , "" ) ; LOG . info ( "" , graph . getInput ( ) . getSource ( ) . getDescription ( ) . getName ( ) ) ; Map < FlowResourceDescription , CompiledType > resourceMap = compileResources ( graph ) ; List < StageModel > results = Lists . create ( ) ; for ( StageBlock block : graph . getStages ( ) ) { StageModel model = compileStage ( block , resourceMap ) ; results . add ( model ) ; } if ( environment . hasError ( ) ) { throw new IOException ( MessageFormat . format ( "" , environment . getErrorMessage ( ) ) ) ; } return results ; } private StageModel compileStage ( StageBlock block , Map < FlowResourceDescription , CompiledType > resourceMap ) throws IOException { assert block != null ; assert resourceMap != null ; LOG . info ( "" , block ) ; StageModel model = analyze ( block ) ; blessResources ( model , resourceMap ) ; compileShuffle ( model ) ; compileFragments ( model ) ; compileUnits ( model ) ; return model ; } private void compileUnits ( StageModel model ) throws IOException { assert model != null ; for ( StageModel . MapUnit unit : model . getMapUnits ( ) ) { CompiledType compiled = mapperEmitter . emit ( model , unit ) ; unit . setCompiled ( compiled ) ; } if ( model . getReduceUnits ( ) . isEmpty ( ) == false ) { CompiledType compiledReducer = reducerEmitter . emit ( model ) ; CompiledType compiledCombiner = combinerEmitter . emit ( model ) ; CompiledReduce compiled = new CompiledReduce ( compiledReducer , compiledCombiner ) ; for ( StageModel . ReduceUnit unit : model . getReduceUnits ( ) ) { unit . setCompiled ( compiled ) ; } } } private void compileFragments ( StageModel model ) throws IOException { assert model != null ; StageBlock block = model . getStageBlock ( ) ; for ( StageModel . MapUnit unit : model . getMapUnits ( ) ) { for ( StageModel . Fragment fragment : unit . getFragments ( ) ) { if ( fragment . isCompiled ( ) ) { continue ; } CompiledType compiled = mapFragmentEmitter . emit ( fragment , block ) ; fragment . setCompiled ( compiled ) ; } } ShuffleModel shuffle = model . getShuffleModel ( ) ; if ( shuffle == null ) { return ; } Name keyTypeName = shuffle . getCompiled ( ) . getKeyTypeName ( ) ; Name valueTypeName = shuffle . getCompiled ( ) . getValueTypeName ( ) ; for ( ShuffleModel . Segment segment : shuffle . getSegments ( ) ) { CompiledShuffleFragment fragment = shuffleFragmentEmitter . emit ( segment , keyTypeName , valueTypeName , block ) ; segment . setCompiled ( fragment ) ; } for ( StageModel . ReduceUnit unit : model . getReduceUnits ( ) ) { for ( StageModel . Fragment fragment : unit . getFragments ( ) ) { if ( fragment . isCompiled ( ) ) { continue ; } CompiledType compiled ; if ( fragment . isRendezvous ( ) ) { compiled = reduceFragmentEmitter . emit ( fragment , shuffle , block ) ; } else { compiled = mapFragmentEmitter . emit ( fragment , block ) ; } fragment . setCompiled ( compiled ) ; } } } private StageModel analyze ( StageBlock block ) throws IOException { ShuffleModel shuffle = shuffleAnalyzer . analyze ( block ) ; StageModel model = mapredAnalyzer . analyze ( block , shuffle ) ; if ( mapredAnalyzer . hasError ( ) || shuffleAnalyzer . hasError ( ) ) { mapredAnalyzer . clearError ( ) ; shuffleAnalyzer . clearError ( ) ; throw new IOException ( "" ) ; } return model ; } private void compileShuffle ( StageModel model ) throws IOException { assert model != null ; ShuffleModel shuffle = model . getShuffleModel ( ) ; if ( shuffle == null ) { return ; } Name keyTypeName = shuffleKeyEmitter . emit ( shuffle ) ; Name valueTypeName = shuffleValueEmitter . emit ( shuffle ) ; Name groupComparatorTypeName = shuffleGroupingEmitter . emit ( shuffle , keyTypeName ) ; Name sortComparatorTypeName = shuffleSortingEmitter . emit ( shuffle , keyTypeName ) ; Name partitionerTypeName = shuffleParitioningEmitter . emit ( shuffle , keyTypeName , valueTypeName ) ; CompiledShuffle compiled = new CompiledShuffle ( keyTypeName , valueTypeName , groupComparatorTypeName , sortComparatorTypeName , partitionerTypeName ) ; shuffle . setCompiled ( compiled ) ; } private Map < FlowResourceDescription , CompiledType > compileResources ( StageGraph graph ) throws IOException { assert graph != null ; Set < FlowResourceDescription > resources = collectResources ( graph ) ; return flowResourceEmitter . emit ( resources ) ; } private Set < FlowResourceDescription > collectResources ( StageGraph graph ) { assert graph != null ; Set < FlowResourceDescription > resources = Sets . create ( ) ; for ( StageBlock stage : graph . getStages ( ) ) { List < FlowBlock > blocks = Lists . create ( ) ; blocks . addAll ( stage . getMapBlocks ( ) ) ; blocks . addAll ( stage . getReduceBlocks ( ) ) ; for ( FlowBlock block : blocks ) { for ( FlowElement element : block . getElements ( ) ) { for ( FlowResourceDescription resource : element . getDescription ( ) . getResources ( ) ) { resources . add ( resource ) ; } } } } return resources ; } private void blessResources ( StageModel model , Map < FlowResourceDescription , CompiledType > resourceMap ) { assert model != null ; assert resourceMap != null ; List < ResourceFragment > resources = Lists . create ( ) ; List < Unit < ? > > units = Lists . create ( ) ; units . addAll ( model . getMapUnits ( ) ) ; units . addAll ( model . getReduceUnits ( ) ) ; for ( Unit < ? > unit : units ) { for ( Fragment fragment : unit . getFragments ( ) ) { resources . addAll ( fragment . getResources ( ) ) ; } } Set < FlowResourceDescription > saw = Sets . create ( ) ; for ( ResourceFragment fragment : resources ) { if ( fragment . isCompiled ( ) ) { continue ; } CompiledType resolved = resourceMap . get ( fragment . getDescription ( ) ) ; if ( resolved == null ) { if ( saw . contains ( fragment . getDescription ( ) ) == false ) { environment . error ( "" , fragment . getDescription ( ) ) ; saw . add ( fragment . getDescription ( ) ) ; } continue ; } fragment . setCompiled ( resolved ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . FlowElementProcessor . Kind ; import com . asakusafw . compiler . flow . FlowElementProcessor . ResultMirror ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . stage . StageModel . Factor ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Identity ; public class MapFragmentEmitter { static final Logger LOG = LoggerFactory . getLogger ( MapFragmentEmitter . class ) ; private final FlowCompilingEnvironment environment ; public MapFragmentEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledType emit ( StageModel . Fragment fragment , StageBlock stageBlock ) throws IOException { Precondition . checkMustNotBeNull ( fragment , "" ) ; Precondition . checkMustNotBeNull ( stageBlock , "" ) ; if ( fragment . isRendezvous ( ) ) { throw new IllegalArgumentException ( ) ; } LOG . debug ( "" , fragment ) ; Engine engine = new Engine ( environment , stageBlock , fragment ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , fragment , name ) ; return new CompiledType ( name ) ; } private static class Engine { private final FlowCompilingEnvironment environment ; private final Fragment fragment ; private final ModelFactory factory ; private final ImportBuilder importer ; private final NameGenerator names ; private final FragmentConnection connection ; private final List < FieldDeclaration > extraFields = Lists . create ( ) ; Engine ( FlowCompilingEnvironment environment , StageBlock stageBlock , Fragment fragment ) { assert environment != null ; assert stageBlock != null ; assert fragment != null ; this . environment = environment ; this . fragment = fragment ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( stageBlock . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . names = new NameGenerator ( factory ) ; this . connection = new FragmentConnection ( environment , fragment , names , importer ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getMapFragmentClass ( fragment . getSerialNumber ( ) ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( connection . createFields ( ) ) ; ConstructorDeclaration ctor = connection . createConstructor ( name ) ; MethodDeclaration method = createBody ( ) ; members . addAll ( extraFields ) ; members . add ( ctor ) ; members . add ( method ) ; Type inputType = createInputType ( ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( importer . resolve ( factory . newParameterizedType ( t ( Result . class ) , Collections . singletonList ( inputType ) ) ) ) , members ) ; } private MethodDeclaration createBody ( ) { SimpleName argument = names . create ( "" ) ; List < Statement > statements = createStatements ( argument ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( FlowElementProcessor . RESULT_METHOD_NAME ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( createInputType ( ) , argument ) ) , statements ) ; } private List < Statement > createStatements ( SimpleName argument ) { assert argument != null ; List < Statement > results = Lists . create ( ) ; boolean end = false ; Expression input = argument ; Iterator < Factor > factors = fragment . getFactors ( ) . iterator ( ) ; while ( factors . hasNext ( ) ) { Factor factor = factors . next ( ) ; if ( factor . isLineEnd ( ) ) { assert factors . hasNext ( ) == false ; emitEnd ( results , factor , input ) ; end = true ; } else { input = emitPart ( results , factor , input ) ; } } if ( end == false ) { emitImplicitEnd ( results , input ) ; } return results ; } private Expression emitPart ( List < Statement > results , Factor factor , Expression input ) { assert results != null ; assert factor != null ; assert input != null ; FlowElementProcessor proc = factor . getProcessor ( ) ; assert proc . getKind ( ) == Kind . LINE_PART ; LinePartProcessor processor = ( LinePartProcessor ) proc ; LOG . debug ( "" , factor , processor ) ; LinePartProcessor . Context context = createPartConext ( factor , input ) ; processor . emitLinePart ( context ) ; return mergePartContext ( context , results ) ; } private void emitEnd ( List < Statement > statements , Factor factor , Expression input ) { assert statements != null ; assert factor != null ; assert input != null ; FlowElementProcessor proc = factor . getProcessor ( ) ; assert proc . getKind ( ) == Kind . LINE_END ; LineEndProcessor processor = ( LineEndProcessor ) proc ; LOG . debug ( "" , factor , processor ) ; LineEndProcessor . Context context = createEndConext ( factor , input ) ; processor . emitLineEnd ( context ) ; mergeEndContext ( context , statements ) ; } private void emitImplicitEnd ( List < Statement > statements , Expression input ) { assert statements != null ; assert input != null ; LOG . debug ( "" , fragment ) ; List < FlowElementOutput > outputs = fragment . getOutputPorts ( ) ; assert outputs . size ( ) == ; LineEndProcessor . Context context = createEndConext ( null , input ) ; ResultMirror result = context . getOutput ( outputs . get ( ) . getDescription ( ) ) ; context . add ( result . createAdd ( input ) ) ; mergeEndContext ( context , statements ) ; } private LinePartProcessor . Context createPartConext ( Factor factor , Expression input ) { assert factor != null ; assert input != null ; FlowElementDescription description = factor . getElement ( ) . getDescription ( ) ; if ( ( description instanceof OperatorDescription ) == false ) { description = new OperatorDescription . Builder ( Identity . class ) . declare ( Void . class , Void . class , "" ) . addInput ( "" , Object . class ) . addOutput ( "" , Object . class ) . toDescription ( ) ; } return new LinePartProcessor . Context ( environment , factor . getElement ( ) , importer , names , ( OperatorDescription ) description , input , connection . getResources ( ) ) ; } private Expression mergePartContext ( LinePartProcessor . Context context , List < Statement > statements ) { assert context != null ; statements . addAll ( context . getGeneratedStatements ( ) ) ; extraFields . addAll ( context . getGeneratedFields ( ) ) ; return context . getOutput ( ) ; } private LineEndProcessor . Context createEndConext ( Factor factorOrNull , Expression input ) { assert input != null ; OperatorDescription description ; if ( factorOrNull == null ) { description = new OperatorDescription . Builder ( Identity . class ) . declare ( Void . class , Void . class , "" ) . addInput ( "" , Object . class ) . addOutput ( "" , Object . class ) . toDescription ( ) ; } else { FlowElementDescription desc = factorOrNull . getElement ( ) . getDescription ( ) ; if ( ( desc instanceof OperatorDescription ) == false ) { throw new IllegalArgumentException ( desc . toString ( ) ) ; } description = ( OperatorDescription ) desc ; } return new LineEndProcessor . Context ( environment , factorOrNull == null ? description : factorOrNull . getElement ( ) , importer , names , description , input , connection . getOutputs ( ) , connection . getResources ( ) ) ; } private void mergeEndContext ( LineEndProcessor . Context context , List < Statement > statements ) { assert context != null ; assert statements != null ; statements . addAll ( context . getGeneratedStatements ( ) ) ; extraFields . addAll ( context . getGeneratedFields ( ) ) ; } private Type createInputType ( ) { List < FlowElementInput > inputs = fragment . getInputPorts ( ) ; assert inputs . size ( ) == ; return t ( inputs . get ( ) . getDescription ( ) . getDataType ( ) ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . code ( "" , fragment . getInputPorts ( ) ) . text ( "" ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . Compilable ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . FlowElementProcessor . Kind ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; public class StageModel { private final StageBlock stageBlock ; private final List < MapUnit > mapUnits ; private final ShuffleModel shuffleModel ; private final List < ReduceUnit > reduceUnits ; private final List < Sink > sinks ; public StageModel ( StageBlock stageBlock , List < MapUnit > mapUnits , ShuffleModel shuffleModel , List < ReduceUnit > reduceUnits , List < Sink > sinks ) { Precondition . checkMustNotBeNull ( stageBlock , "" ) ; Precondition . checkMustNotBeNull ( mapUnits , "" ) ; Precondition . checkMustNotBeNull ( reduceUnits , "" ) ; Precondition . checkMustNotBeNull ( sinks , "" ) ; this . stageBlock = stageBlock ; this . shuffleModel = shuffleModel ; int unitSerial = ; for ( MapUnit unit : mapUnits ) { unit . renumberUnit ( unitSerial ++ ) ; } for ( ReduceUnit unit : reduceUnits ) { unit . renumberUnit ( unitSerial ++ ) ; } this . mapUnits = mapUnits ; this . reduceUnits = reduceUnits ; this . sinks = sinks ; } public StageBlock getStageBlock ( ) { return stageBlock ; } public List < MapUnit > getMapUnits ( ) { return mapUnits ; } public ShuffleModel getShuffleModel ( ) { return shuffleModel ; } public List < ReduceUnit > getReduceUnits ( ) { return reduceUnits ; } public Set < InputDescription > getSideDataInputs ( ) { Set < ResourceFragment > resources = Sets . create ( ) ; List < Unit < ? > > units = Lists . create ( ) ; units . addAll ( getMapUnits ( ) ) ; units . addAll ( getReduceUnits ( ) ) ; for ( Unit < ? > unit : units ) { for ( Fragment fragment : unit . getFragments ( ) ) { resources . addAll ( fragment . getResources ( ) ) ; } } Set < InputDescription > results = Sets . create ( ) ; for ( ResourceFragment resource : resources ) { results . addAll ( resource . getDescription ( ) . getSideDataInputs ( ) ) ; } return results ; } public List < Sink > getStageResults ( ) { return sinks ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getMapUnits ( ) , getShuffleModel ( ) , getReduceUnits ( ) ) ; } public abstract static class Unit < T > extends Compilable . Trait < T > { private final List < FlowBlock . Input > inputs ; private final List < Fragment > fragments ; private int serialNumber = - ; public Unit ( List < FlowBlock . Input > inputs , List < Fragment > fragments ) { Precondition . checkMustNotBeNull ( inputs , "" ) ; Precondition . checkMustNotBeNull ( fragments , "" ) ; this . inputs = inputs ; this . fragments = fragments ; } boolean hasSerialNumber ( ) { return serialNumber >= ; } public int getSerialNumber ( ) { if ( serialNumber < ) { throw new IllegalStateException ( ) ; } return serialNumber ; } public List < FlowBlock . Input > getInputs ( ) { return inputs ; } public List < Fragment > getFragments ( ) { return fragments ; } void renumberUnit ( int serial ) { this . serialNumber = serial ; } } public static class MapUnit extends Unit < CompiledType > { public MapUnit ( List < FlowBlock . Input > inputs , List < Fragment > fragments ) { super ( inputs , fragments ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getInputs ( ) , getFragments ( ) , hasSerialNumber ( ) ? String . valueOf ( getSerialNumber ( ) ) : "" ) ; } } public static class ReduceUnit extends Unit < CompiledReduce > { public ReduceUnit ( List < FlowBlock . Input > inputs , List < Fragment > fragments ) { super ( inputs , fragments ) ; } public boolean canCombine ( ) { List < Fragment > fragments = getFragments ( ) ; if ( fragments . isEmpty ( ) ) { return false ; } Fragment headFragment = fragments . get ( ) ; return headFragment . canCombine ( ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getInputs ( ) , getFragments ( ) , hasSerialNumber ( ) ? String . valueOf ( getSerialNumber ( ) ) : "" ) ; } } public static class Fragment extends Compilable . Trait < CompiledType > { private final int serialNumber ; private final List < Factor > factors ; private final List < ResourceFragment > resources ; public Fragment ( int serialNumber , List < Factor > factors , List < ResourceFragment > resources ) { Precondition . checkMustNotBeNull ( factors , "" ) ; Precondition . checkMustNotBeNull ( resources , "" ) ; if ( factors . isEmpty ( ) ) { throw new IllegalArgumentException ( ) ; } Factor first = factors . get ( ) ; if ( first . getElement ( ) . getInputPorts ( ) . size ( ) != && first . isRendezvous ( ) == false ) { throw new IllegalArgumentException ( ) ; } if ( factors . size ( ) >= && first . isRendezvous ( ) ) { throw new IllegalArgumentException ( ) ; } this . serialNumber = serialNumber ; this . factors = Lists . from ( factors ) ; this . resources = resources ; } public int getSerialNumber ( ) { return serialNumber ; } public boolean canCombine ( ) { if ( isRendezvous ( ) == false ) { return false ; } Factor first = factors . get ( ) ; assert first . isRendezvous ( ) ; RendezvousProcessor processor = ( RendezvousProcessor ) first . getProcessor ( ) ; return processor . isPartial ( first . getElement ( ) . getDescription ( ) ) ; } public List < Factor > getFactors ( ) { return factors ; } public List < FlowElementInput > getInputPorts ( ) { if ( factors . isEmpty ( ) ) { return Collections . emptyList ( ) ; } Factor first = factors . get ( ) ; return first . getElement ( ) . getInputPorts ( ) ; } public List < FlowElementOutput > getOutputPorts ( ) { if ( factors . isEmpty ( ) ) { return Collections . emptyList ( ) ; } Factor last = factors . get ( factors . size ( ) - ) ; return last . getElement ( ) . getOutputPorts ( ) ; } public List < ResourceFragment > getResources ( ) { return resources ; } public boolean isRendezvous ( ) { if ( factors . isEmpty ( ) ) { return false ; } Factor first = factors . get ( ) ; return first . isRendezvous ( ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getInputPorts ( ) ) ; } } public static class Factor { private final FlowElement element ; private final FlowElementProcessor processor ; public Factor ( FlowElement element , FlowElementProcessor processor ) { Precondition . checkMustNotBeNull ( element , "" ) ; Precondition . checkMustNotBeNull ( processor , "" ) ; this . element = element ; this . processor = processor ; } public boolean isRendezvous ( ) { return processor . getKind ( ) == Kind . RENDEZVOUS ; } public boolean isLineEnd ( ) { return processor . getKind ( ) == Kind . LINE_END ; } public FlowElement getElement ( ) { return element ; } public FlowElementProcessor getProcessor ( ) { return processor ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , element ) ; } } public static class ResourceFragment extends Compilable . Trait < CompiledType > { private final FlowResourceDescription description ; public ResourceFragment ( FlowResourceDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; this . description = description ; } public FlowResourceDescription getDescription ( ) { return description ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + description . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ResourceFragment other = ( ResourceFragment ) obj ; if ( description . equals ( other . description ) == false ) { return false ; } return true ; } } public static class Sink { private final Set < FlowBlock . Output > outputs ; private final String name ; public Sink ( Set < FlowBlock . Output > outputs , String name ) { Precondition . checkMustNotBeNull ( outputs , "" ) ; Precondition . checkMustNotBeNull ( name , "" ) ; this . outputs = outputs ; this . name = name ; } public Set < FlowBlock . Output > getOutputs ( ) { return outputs ; } public java . lang . reflect . Type getType ( ) { return outputs . iterator ( ) . next ( ) . getElementPort ( ) . getDescription ( ) . getDataType ( ) ; } public String getName ( ) { return name ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getName ( ) ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . mapreduce . Partitioner ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Arrangement ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Term ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ShufflePartitionerEmitter { static final Logger LOG = LoggerFactory . getLogger ( ShufflePartitionerEmitter . class ) ; private FlowCompilingEnvironment environment ; public ShufflePartitionerEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public Name emit ( ShuffleModel model , Name keyTypeName , Name valueTypeName ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; Precondition . checkMustNotBeNull ( keyTypeName , "" ) ; LOG . debug ( "" , model . getStageBlock ( ) ) ; Engine engine = new Engine ( environment , model , keyTypeName , valueTypeName ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , model . getStageBlock ( ) , name ) ; return name ; } private static class Engine { private static final String HASH_CODE_METHOD_NAME = "" ; private ShuffleModel model ; private ModelFactory factory ; private ImportBuilder importer ; private Type keyType ; private Type valueType ; public Engine ( FlowCompilingEnvironment environment , ShuffleModel model , Name keyTypeName , Name valueTypeName ) { assert environment != null ; assert model != null ; assert keyTypeName != null ; assert valueTypeName != null ; this . model = model ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( model . getStageBlock ( ) . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . keyType = importer . resolve ( factory . newNamedType ( keyTypeName ) ) ; this . valueType = importer . resolve ( factory . newNamedType ( valueTypeName ) ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getShufflePartitionerClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createPartition ( ) ) ; members . add ( createHashCode ( ) ) ; members . add ( ShuffleEmiterUtil . createPortToElement ( factory , model ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , importer . resolve ( factory . newParameterizedType ( t ( Partitioner . class ) , Arrays . asList ( keyType , valueType ) ) ) , Collections . < Type > emptyList ( ) , members ) ; } private MethodDeclaration createPartition ( ) { SimpleName key = factory . newSimpleName ( "" ) ; SimpleName value = factory . newSimpleName ( "" ) ; SimpleName partitions = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( HASH_CODE_METHOD_NAME , key ) . apply ( InfixOperator . AND , new TypeBuilder ( factory , t ( Integer . class ) ) . field ( "" ) . toExpression ( ) ) . apply ( InfixOperator . REMAINDER , partitions ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { factory . newFormalParameterDeclaration ( keyType , key ) , factory . newFormalParameterDeclaration ( valueType , value ) , factory . newFormalParameterDeclaration ( t ( int . class ) , partitions ) , } ) , statements ) ; } private MethodDeclaration createHashCode ( ) { SimpleName key = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; SimpleName portId = factory . newSimpleName ( "" ) ; SimpleName result = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , key ) . method ( SegmentedWritable . ID_GETTER ) . toLocalVariableDeclaration ( t ( int . class ) , portId ) ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , portId ) . toLocalVariableDeclaration ( t ( int . class ) , result ) ) ; List < Statement > cases = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; for ( Term term : segment . getTerms ( ) ) { if ( term . getArrangement ( ) != Arrangement . GROUPING ) { continue ; } Expression hash = term . getSource ( ) . createHashCode ( new ExpressionBuilder ( factory , key ) . field ( ShuffleEmiterUtil . getPropertyName ( segment , term ) ) . toExpression ( ) ) ; cases . add ( new ExpressionBuilder ( factory , result ) . assignFrom ( new ExpressionBuilder ( factory , result ) . apply ( InfixOperator . TIMES , v ( ) ) . apply ( InfixOperator . PLUS , hash ) . toExpression ( ) ) . toStatement ( ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( portId ) . toThrowStatement ( ) ) ; statements . add ( factory . newSwitchStatement ( portId , cases ) ) ; statements . add ( new ExpressionBuilder ( factory , result ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( HASH_CODE_METHOD_NAME ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( keyType , key ) ) , statements ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , model . getStageBlock ( ) . getStageNumber ( ) ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; public class CompiledReduce { private CompiledType reducerType ; private CompiledType combinerTypeOrNull ; public CompiledReduce ( CompiledType reducerType , CompiledType combinerTypeOrNull ) { if ( reducerType == null ) { throw new IllegalArgumentException ( "" ) ; } this . reducerType = reducerType ; this . combinerTypeOrNull = combinerTypeOrNull ; } public CompiledType getReducerType ( ) { return reducerType ; } public CompiledType getCombinerTypeOrNull ( ) { return combinerTypeOrNull ; } } package com . asakusafw . compiler . flow . stage ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Arrangement ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Term ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ShuffleKeyEmitter { static final Logger LOG = LoggerFactory . getLogger ( ShuffleKeyEmitter . class ) ; private FlowCompilingEnvironment environment ; public ShuffleKeyEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public Name emit ( ShuffleModel model ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; LOG . debug ( "" , model . getStageBlock ( ) ) ; Engine engine = new Engine ( environment , model ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , model . getStageBlock ( ) , name ) ; return name ; } private static class Engine { private static final String PORT_ID_FIELD_NAME = "" ; private ShuffleModel model ; private ModelFactory factory ; private ImportBuilder importer ; public Engine ( FlowCompilingEnvironment environment , ShuffleModel model ) { assert environment != null ; assert model != null ; this . model = model ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( model . getStageBlock ( ) . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getShuffleKeyClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createSegmentDistinction ( ) ) ; members . addAll ( createProperties ( ) ) ; members . addAll ( createConverters ( ) ) ; members . add ( createCopier ( ) ) ; members . addAll ( createWritables ( ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( t ( SegmentedWritable . class ) ) , members ) ; } private List < TypeBodyDeclaration > createSegmentDistinction ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createSegmentIdField ( ) ) ; results . add ( createSegmentIdGetter ( ) ) ; return results ; } private FieldDeclaration createSegmentIdField ( ) { return factory . newFieldDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( PORT_ID_FIELD_NAME ) , v ( - ) ) ; } private TypeBodyDeclaration createSegmentIdGetter ( ) { Statement body = new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( PORT_ID_FIELD_NAME ) . toReturnStatement ( ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( SegmentedWritable . ID_GETTER ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( body ) ) ; } private List < FieldDeclaration > createProperties ( ) { List < FieldDeclaration > results = Lists . create ( ) ; for ( List < Segment > segments : ShuffleEmiterUtil . groupByElement ( model ) ) { Segment first = segments . get ( ) ; for ( Term term : first . getTerms ( ) ) { if ( term . getArrangement ( ) != Arrangement . GROUPING ) { continue ; } results . add ( createProperty ( first , term ) ) ; } for ( Segment segment : segments ) { for ( Term term : segment . getTerms ( ) ) { if ( term . getArrangement ( ) == Arrangement . GROUPING ) { continue ; } results . add ( createProperty ( segment , term ) ) ; } } } return results ; } private FieldDeclaration createProperty ( Segment segment , Term term ) { assert segment != null ; assert term != null ; Property source = term . getSource ( ) ; String name = ShuffleEmiterUtil . getPropertyName ( segment , term ) ; return factory . newFieldDeclaration ( new JavadocBuilder ( factory ) . text ( "" , segment . getPort ( ) . getOwner ( ) . getDescription ( ) . getName ( ) , segment . getPort ( ) . getDescription ( ) . getName ( ) , source . getName ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , t ( source . getType ( ) ) , factory . newSimpleName ( name ) , source . createNewInstance ( t ( source . getType ( ) ) ) ) ; } private List < MethodDeclaration > createConverters ( ) { List < MethodDeclaration > results = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { results . add ( createConverter ( segment ) ) ; } return results ; } private MethodDeclaration createConverter ( Segment segment ) { assert segment != null ; String methodName = Naming . getShuffleKeySetter ( segment . getPortId ( ) ) ; SimpleName argument = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( PORT_ID_FIELD_NAME ) . assignFrom ( v ( segment . getPortId ( ) ) ) . toStatement ( ) ) ; for ( Term term : segment . getTerms ( ) ) { String name = ShuffleEmiterUtil . getPropertyName ( segment , term ) ; statements . add ( term . getSource ( ) . createGetter ( argument , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( name ) . toExpression ( ) ) ) ; } return factory . newMethodDeclaration ( new JavadocBuilder ( factory ) . text ( "" , segment . getPort ( ) . getOwner ( ) . getDescription ( ) . getName ( ) , segment . getPort ( ) . getDescription ( ) . getName ( ) ) . param ( argument ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( methodName ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( segment . getTarget ( ) . getType ( ) ) , argument ) ) , statements ) ; } private MethodDeclaration createCopier ( ) { SimpleName argument = factory . newSimpleName ( "" ) ; List < Statement > cases = Lists . create ( ) ; for ( List < Segment > segments : ShuffleEmiterUtil . groupByElement ( model ) ) { for ( Segment segment : segments ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; } Segment segment = segments . get ( ) ; for ( Term term : segment . getTerms ( ) ) { if ( term . getArrangement ( ) != Arrangement . GROUPING ) { continue ; } String name = ShuffleEmiterUtil . getPropertyName ( segment , term ) ; cases . add ( term . getSource ( ) . assign ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( name ) . toExpression ( ) , new ExpressionBuilder ( factory , argument ) . field ( name ) . toExpression ( ) ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( factory . newSimpleName ( PORT_ID_FIELD_NAME ) ) . assignFrom ( new ExpressionBuilder ( factory , argument ) . field ( factory . newSimpleName ( PORT_ID_FIELD_NAME ) ) . toExpression ( ) ) . toExpression ( ) ) . toThrowStatement ( ) ) ; SimpleName typeName = factory . newSimpleName ( Naming . getShuffleKeyClass ( ) ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( factory . newSimpleName ( PORT_ID_FIELD_NAME ) ) . assignFrom ( new ExpressionBuilder ( factory , argument ) . field ( factory . newSimpleName ( PORT_ID_FIELD_NAME ) ) . toExpression ( ) ) . toStatement ( ) ) ; statements . add ( factory . newIfStatement ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( factory . newSimpleName ( PORT_ID_FIELD_NAME ) ) . apply ( InfixOperator . LESS , v ( ) ) . toExpression ( ) , factory . newBlock ( factory . newReturnStatement ( ) ) , null ) ) ; statements . add ( factory . newSwitchStatement ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( factory . newSimpleName ( PORT_ID_FIELD_NAME ) ) . toExpression ( ) , cases ) ) ; return factory . newMethodDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . param ( argument ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( Naming . getShuffleKeyGroupCopier ( ) ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newNamedType ( typeName ) , argument ) ) , statements ) ; } private List < MethodDeclaration > createWritables ( ) { return Arrays . asList ( createWriteMethod ( ) , createReadFieldsMethod ( ) ) ; } private MethodDeclaration createWriteMethod ( ) { SimpleName out = factory . newSimpleName ( "" ) ; Expression segmentId = new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( PORT_ID_FIELD_NAME ) . toExpression ( ) ; List < Statement > cases = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; cases . add ( new ExpressionBuilder ( factory , out ) . method ( "" , v ( segment . getPortId ( ) ) ) . toStatement ( ) ) ; for ( Term term : segment . getTerms ( ) ) { String fieldName = ShuffleEmiterUtil . getPropertyName ( segment , term ) ; cases . add ( term . getSource ( ) . createWriter ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( fieldName ) . toExpression ( ) , out ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( segmentId ) . toThrowStatement ( ) ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( factory . newSwitchStatement ( segmentId , cases ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( DataOutput . class ) , out ) ) , , Collections . singletonList ( t ( IOException . class ) ) , factory . newBlock ( statements ) ) ; } private MethodDeclaration createReadFieldsMethod ( ) { SimpleName in = factory . newSimpleName ( "" ) ; Expression segmentId = new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( PORT_ID_FIELD_NAME ) . toExpression ( ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , segmentId ) . assignFrom ( new ExpressionBuilder ( factory , in ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; List < Statement > cases = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; for ( Term term : segment . getTerms ( ) ) { String fieldName = ShuffleEmiterUtil . getPropertyName ( segment , term ) ; cases . add ( term . getSource ( ) . createReader ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( fieldName ) . toExpression ( ) , in ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( segmentId ) . toThrowStatement ( ) ) ; statements . add ( factory . newSwitchStatement ( segmentId , cases ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( DataInput . class ) , in ) ) , , Collections . singletonList ( t ( IOException . class ) ) , factory . newBlock ( statements ) ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , model . getStageBlock ( ) . getStageNumber ( ) ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . java . model . syntax . Name ; public class CompiledType { private Name qualifiedName ; public CompiledType ( Name qualifiedName ) { Precondition . checkMustNotBeNull ( qualifiedName , "" ) ; this . qualifiedName = qualifiedName ; } public Name getQualifiedName ( ) { return qualifiedName ; } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . mapreduce . TaskInputOutputContext ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . compiler . flow . LinePartProcessor . Context ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Identity ; public class ShuffleFragmentEmitter { static final Logger LOG = LoggerFactory . getLogger ( ShuffleFragmentEmitter . class ) ; private final FlowCompilingEnvironment environment ; public ShuffleFragmentEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledShuffleFragment emit ( ShuffleModel . Segment segment , Name keyTypeName , Name valueTypeName , StageBlock stageBlock ) throws IOException { Precondition . checkMustNotBeNull ( segment , "" ) ; Precondition . checkMustNotBeNull ( stageBlock , "" ) ; LOG . debug ( "" , segment ) ; CompiledType mapOut = emitMapOutput ( segment , keyTypeName , valueTypeName , stageBlock ) ; CompiledType combineOut = emitCombineOutput ( segment , keyTypeName , valueTypeName , stageBlock ) ; LOG . debug ( "" , new Object [ ] { segment , mapOut . getQualifiedName ( ) . toNameString ( ) , combineOut . getQualifiedName ( ) . toNameString ( ) , } ) ; return new CompiledShuffleFragment ( mapOut , combineOut ) ; } private CompiledType emitMapOutput ( ShuffleModel . Segment segment , Name keyTypeName , Name valueTypeName , StageBlock stageBlock ) throws IOException { assert segment != null ; assert keyTypeName != null ; assert valueTypeName != null ; assert stageBlock != null ; Engine engine = new MapOutputEngine ( environment , stageBlock , segment , keyTypeName , valueTypeName ) ; return generate ( segment , engine ) ; } private CompiledType emitCombineOutput ( ShuffleModel . Segment segment , Name keyTypeName , Name valueTypeName , StageBlock stageBlock ) throws IOException { assert segment != null ; assert keyTypeName != null ; assert valueTypeName != null ; assert stageBlock != null ; Engine engine = new CombineOutputEngine ( environment , stageBlock , segment , keyTypeName , valueTypeName ) ; return generate ( segment , engine ) ; } private CompiledType generate ( ShuffleModel . Segment segment , Engine engine ) throws IOException { assert segment != null ; assert engine != null ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name typeName = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , segment , typeName ) ; CompiledType compiled = new CompiledType ( typeName ) ; return compiled ; } private static class MapOutputEngine extends Engine { public MapOutputEngine ( FlowCompilingEnvironment environment , StageBlock stageBlock , Segment segment , Name keyTypeName , Name valueTypeName ) { super ( environment , stageBlock , segment , keyTypeName , valueTypeName ) ; } @ Override SimpleName getClassSimpleName ( ) { return factory . newSimpleName ( Naming . getMapOutputFragmentClass ( segment . getPortId ( ) ) ) ; } @ Override Type getInputType ( ) { return importer . toType ( segment . getSource ( ) . getType ( ) ) ; } @ Override Expression preprocess ( Context context , List < Statement > results ) { LinePartProcessor processor = segment . getDescription ( ) . getConverter ( ) ; if ( processor == null ) { return context . getInput ( ) ; } processor . emitLinePart ( context ) ; LOG . debug ( "" , segment , processor ) ; results . addAll ( context . getGeneratedStatements ( ) ) ; extraFields . addAll ( context . getGeneratedFields ( ) ) ; return context . getOutput ( ) ; } } private static class CombineOutputEngine extends Engine { public CombineOutputEngine ( FlowCompilingEnvironment environment , StageBlock stageBlock , Segment segment , Name keyTypeName , Name valueTypeName ) { super ( environment , stageBlock , segment , keyTypeName , valueTypeName ) ; } @ Override SimpleName getClassSimpleName ( ) { return factory . newSimpleName ( Naming . getCombineOutputFragmentClass ( segment . getPortId ( ) ) ) ; } @ Override Type getInputType ( ) { return importer . toType ( segment . getTarget ( ) . getType ( ) ) ; } } private abstract static class Engine { final FlowCompilingEnvironment environment ; final Segment segment ; final ModelFactory factory ; final ImportBuilder importer ; final NameGenerator names ; final SimpleName collector ; final Type keyType ; final Type valueType ; final SimpleName keyModel ; final SimpleName valueModel ; final List < FieldDeclaration > extraFields = Lists . create ( ) ; Engine ( FlowCompilingEnvironment environment , StageBlock stageBlock , Segment segment , Name keyTypeName , Name valueTypeName ) { assert environment != null ; assert stageBlock != null ; assert segment != null ; assert keyTypeName != null ; assert valueTypeName != null ; this . environment = environment ; this . segment = segment ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( stageBlock . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . names = new NameGenerator ( factory ) ; this . collector = names . create ( "" ) ; this . keyType = importer . toType ( keyTypeName ) ; this . valueType = importer . toType ( valueTypeName ) ; this . keyModel = names . create ( "" ) ; this . valueModel = names . create ( "" ) ; } abstract SimpleName getClassSimpleName ( ) ; public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = getClassSimpleName ( ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createFields ( ) ) ; ConstructorDeclaration ctor = createConstructor ( ) ; MethodDeclaration method = createBody ( ) ; members . addAll ( extraFields ) ; members . add ( ctor ) ; members . add ( method ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( importer . resolve ( factory . newParameterizedType ( t ( Result . class ) , getInputType ( ) ) ) ) , members ) ; } abstract Type getInputType ( ) ; private List < FieldDeclaration > createFields ( ) { List < FieldDeclaration > results = Lists . create ( ) ; results . add ( createCollectorField ( ) ) ; results . add ( createKeyField ( ) ) ; results . add ( createValueField ( ) ) ; return results ; } private FieldDeclaration createCollectorField ( ) { return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , createContextType ( ) , collector , null ) ; } private FieldDeclaration createKeyField ( ) { return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , keyType , keyModel , new TypeBuilder ( factory , keyType ) . newObject ( ) . toExpression ( ) ) ; } private FieldDeclaration createValueField ( ) { return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , valueType , valueModel , new TypeBuilder ( factory , valueType ) . newObject ( ) . toExpression ( ) ) ; } private ConstructorDeclaration createConstructor ( ) { SimpleName name = getClassSimpleName ( ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( collector ) . assignFrom ( collector ) . toStatement ( ) ) ; return factory . newConstructorDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . param ( collector ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , name , Collections . singletonList ( factory . newFormalParameterDeclaration ( createContextType ( ) , collector ) ) , statements ) ; } private Type createContextType ( ) { return importer . resolve ( factory . newParameterizedType ( t ( TaskInputOutputContext . class ) , factory . newWildcard ( ) , factory . newWildcard ( ) , factory . newWildcard ( WildcardBoundKind . LOWER_BOUNDED , keyType ) , factory . newWildcard ( WildcardBoundKind . LOWER_BOUNDED , valueType ) ) ) ; } private MethodDeclaration createBody ( ) { SimpleName argument = names . create ( "" ) ; List < Statement > statements = createStatements ( argument ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( FlowElementProcessor . RESULT_METHOD_NAME ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( getInputType ( ) , argument ) ) , statements ) ; } private List < Statement > createStatements ( SimpleName argument ) { assert argument != null ; List < Statement > results = Lists . create ( ) ; LinePartProcessor . Context context = createPartConext ( argument ) ; Expression shuffleInput = preprocess ( context , results ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( keyModel ) . method ( Naming . getShuffleKeySetter ( segment . getPortId ( ) ) , shuffleInput ) . toStatement ( ) ) ; results . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( valueModel ) . method ( Naming . getShuffleValueSetter ( segment . getPortId ( ) ) , shuffleInput ) . toStatement ( ) ) ; SimpleName exception = names . create ( "" ) ; results . add ( factory . newTryStatement ( factory . newBlock ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( collector ) . method ( "" , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( keyModel ) . toExpression ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( valueModel ) . toExpression ( ) ) . toStatement ( ) ) , Collections . singletonList ( factory . newCatchClause ( factory . newFormalParameterDeclaration ( t ( Exception . class ) , exception ) , factory . newBlock ( new TypeBuilder ( factory , t ( Result . OutputException . class ) ) . newObject ( exception ) . toThrowStatement ( ) ) ) ) , null ) ) ; return results ; } Expression preprocess ( LinePartProcessor . Context context , List < Statement > results ) { return context . getInput ( ) ; } private LinePartProcessor . Context createPartConext ( Expression input ) { assert input != null ; OperatorDescription description = new OperatorDescription . Builder ( Identity . class ) . declare ( Void . class , Void . class , "" ) . addInput ( "" , Object . class ) . addOutput ( "" , Object . class ) . toDescription ( ) ; return new LinePartProcessor . Context ( environment , description , importer , names , description , input , Collections . < FlowResourceDescription , Expression > emptyMap ( ) ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . code ( "" , segment . getPort ( ) ) . text ( "" ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Arrangement ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Term ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . BasicTypeKind ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; final class ShuffleEmiterUtil { public static final String COMPARE_INT = "" ; public static final String PORT_TO_ELEMENT = "" ; public static List < List < Segment > > groupByElement ( ShuffleModel model ) { List < List < Segment > > results = Lists . create ( ) ; List < Segment > lastSegment = Collections . emptyList ( ) ; int lastElementId = - ; for ( Segment segment : model . getSegments ( ) ) { if ( lastElementId != segment . getElementId ( ) ) { lastElementId = segment . getElementId ( ) ; if ( lastSegment . isEmpty ( ) == false ) { results . add ( lastSegment ) ; } lastSegment = Lists . create ( ) ; } lastSegment . add ( segment ) ; } if ( lastSegment . isEmpty ( ) == false ) { results . add ( lastSegment ) ; } return results ; } public static String getPropertyName ( Segment segment , Term term ) { assert segment != null ; assert term != null ; String name ; if ( term . getArrangement ( ) == Arrangement . GROUPING ) { name = Naming . getShuffleKeyGroupProperty ( segment . getElementId ( ) , term . getTermId ( ) ) ; } else { name = Naming . getShuffleKeySortProperty ( segment . getPortId ( ) , term . getTermId ( ) ) ; } return name ; } public static MethodDeclaration createCompareInts ( ModelFactory factory ) { SimpleName a = factory . newSimpleName ( "" ) ; SimpleName b = factory . newSimpleName ( "" ) ; Statement statement = factory . newIfStatement ( new ExpressionBuilder ( factory , a ) . apply ( InfixOperator . EQUALS , b ) . toExpression ( ) , new ExpressionBuilder ( factory , Models . toLiteral ( factory , ) ) . toReturnStatement ( ) , factory . newIfStatement ( new ExpressionBuilder ( factory , a ) . apply ( InfixOperator . LESS , b ) . toExpression ( ) , new ExpressionBuilder ( factory , Models . toLiteral ( factory , - ) ) . toReturnStatement ( ) , new ExpressionBuilder ( factory , Models . toLiteral ( factory , + ) ) . toReturnStatement ( ) ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , factory . newBasicType ( BasicTypeKind . INT ) , factory . newSimpleName ( COMPARE_INT ) , Arrays . asList ( new FormalParameterDeclaration [ ] { factory . newFormalParameterDeclaration ( factory . newBasicType ( BasicTypeKind . INT ) , a ) , factory . newFormalParameterDeclaration ( factory . newBasicType ( BasicTypeKind . INT ) , b ) , } ) , Collections . singletonList ( statement ) ) ; } public static MethodDeclaration createPortToElement ( ModelFactory factory , ShuffleModel model ) { List < Statement > cases = Lists . create ( ) ; for ( List < Segment > segments : groupByElement ( model ) ) { for ( Segment segment : segments ) { cases . add ( factory . newSwitchCaseLabel ( Models . toLiteral ( factory , segment . getPortId ( ) ) ) ) ; } cases . add ( factory . newReturnStatement ( Models . toLiteral ( factory , segments . get ( ) . getElementId ( ) ) ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( factory . newReturnStatement ( Models . toLiteral ( factory , - ) ) ) ; SimpleName pid = factory . newSimpleName ( "" ) ; Statement statement = factory . newSwitchStatement ( pid , cases ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , factory . newBasicType ( BasicTypeKind . INT ) , factory . newSimpleName ( PORT_TO_ELEMENT ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newBasicType ( BasicTypeKind . INT ) , pid ) ) , Collections . singletonList ( statement ) ) ; } private ShuffleEmiterUtil ( ) { return ; } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . Mapper ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; public class MapperEmitter { static final Logger LOG = LoggerFactory . getLogger ( MapperEmitter . class ) ; private final FlowCompilingEnvironment environment ; public MapperEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledType emit ( StageModel model , StageModel . MapUnit unit ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; Precondition . checkMustNotBeNull ( unit , "" ) ; LOG . debug ( "" , unit ) ; Engine engine = new Engine ( environment , model , unit ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , unit , name ) ; return new CompiledType ( name ) ; } private static class Engine { private final StageModel . MapUnit unit ; private final ModelFactory factory ; private final ImportBuilder importer ; private final NameGenerator names ; private final FragmentFlow fragments ; private final SimpleName context ; private final SimpleName cache ; private DataClass dataClass ; Engine ( FlowCompilingEnvironment environment , StageModel model , StageModel . MapUnit unit ) { assert model != null ; assert unit != null ; this . unit = unit ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( model . getStageBlock ( ) . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . names = new NameGenerator ( factory ) ; this . fragments = new FragmentFlow ( environment , importer , names , model , Collections . singletonList ( unit ) ) ; this . context = names . create ( "" ) ; this . cache = names . create ( "" ) ; this . dataClass = environment . getDataClasses ( ) . load ( getInputTypeAsReflect ( ) ) ; if ( dataClass == null ) { environment . error ( "" , getInputTypeAsReflect ( ) ) ; dataClass = new DataClass . Unresolved ( factory , getInputTypeAsReflect ( ) ) ; } } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getMapClass ( unit . getSerialNumber ( ) ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createCache ( ) ) ; members . addAll ( fragments . createFields ( ) ) ; members . add ( createSetup ( ) ) ; members . add ( createCleanup ( ) ) ; members . add ( createRun ( ) ) ; Type inputType = createInputType ( ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , Mapper . class ) , Arrays . asList ( t ( NullWritable . class ) , inputType , fragments . getShuffleKeyType ( ) , fragments . getShuffleValueType ( ) ) ) ) , Collections . < Type > emptyList ( ) , members ) ; } private FieldDeclaration createCache ( ) { java . lang . reflect . Type type = dataClass . getType ( ) ; return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , t ( type ) , cache , dataClass . createNewInstance ( t ( type ) ) ) ; } private MethodDeclaration createSetup ( ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newNamedType ( factory . newSimpleName ( "" ) ) , context ) ) , , Arrays . asList ( t ( IOException . class ) , t ( InterruptedException . class ) ) , factory . newBlock ( fragments . createSetup ( context ) ) ) ; } private MethodDeclaration createCleanup ( ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newNamedType ( factory . newSimpleName ( "" ) ) , context ) ) , , Arrays . asList ( t ( IOException . class ) , t ( InterruptedException . class ) ) , factory . newBlock ( fragments . createCleanup ( context ) ) ) ; } private MethodDeclaration createRun ( ) { List < Statement > loop = Lists . create ( ) ; for ( FlowBlock . Input input : unit . getInputs ( ) ) { Expression expr = fragments . getLine ( input . getElementPort ( ) ) ; loop . add ( dataClass . assign ( cache , new ExpressionBuilder ( factory , context ) . method ( "" ) . toExpression ( ) ) ) ; loop . add ( new ExpressionBuilder ( factory , expr ) . method ( FlowElementProcessor . RESULT_METHOD_NAME , cache ) . toStatement ( ) ) ; } List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( "" , context ) . toStatement ( ) ) ; statements . add ( factory . newWhileStatement ( new ExpressionBuilder ( factory , context ) . method ( "" ) . toExpression ( ) , factory . newBlock ( loop ) ) ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( "" , context ) . toStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newNamedType ( factory . newSimpleName ( "" ) ) , context ) ) , , Arrays . asList ( t ( IOException . class ) , t ( InterruptedException . class ) ) , factory . newBlock ( statements ) ) ; } private Type createInputType ( ) { return t ( getInputTypeAsReflect ( ) ) ; } private java . lang . reflect . Type getInputTypeAsReflect ( ) { FlowElementInput port = unit . getInputs ( ) . get ( ) . getElementPort ( ) ; FlowElementPortDescription input = port . getDescription ( ) ; return input . getDataType ( ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . code ( "" , unit . getInputs ( ) ) . text ( "" ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . FlowElementProcessor . Kind ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . StageModel . Factor ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; public class ReduceFragmentEmitter { static final Logger LOG = LoggerFactory . getLogger ( ReduceFragmentEmitter . class ) ; private final FlowCompilingEnvironment environment ; public ReduceFragmentEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledType emit ( StageModel . Fragment fragment , ShuffleModel shuffle , StageBlock stageBlock ) throws IOException { Precondition . checkMustNotBeNull ( fragment , "" ) ; Precondition . checkMustNotBeNull ( shuffle , "" ) ; Precondition . checkMustNotBeNull ( stageBlock , "" ) ; if ( fragment . isRendezvous ( ) == false ) { throw new IllegalArgumentException ( ) ; } if ( shuffle . isCompiled ( ) == false ) { throw new IllegalArgumentException ( ) ; } assert fragment . getFactors ( ) . size ( ) == ; LOG . debug ( "" , fragment ) ; Engine engine = new Engine ( environment , stageBlock , fragment , shuffle ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , fragment , name ) ; return new CompiledType ( name ) ; } private static class Engine { private static final String PROCESS_PREFIX = "" ; private final FlowCompilingEnvironment environment ; private final Fragment fragment ; private final ShuffleModel shuffle ; private final ModelFactory factory ; private final ImportBuilder importer ; private final NameGenerator names ; private final List < FieldDeclaration > extraFields = Lists . create ( ) ; private final Type valueType ; private final FragmentConnection connection ; Engine ( FlowCompilingEnvironment environment , StageBlock stageBlock , Fragment fragment , ShuffleModel shuffle ) { assert environment != null ; assert stageBlock != null ; assert fragment != null ; assert shuffle != null ; this . environment = environment ; this . fragment = fragment ; this . shuffle = shuffle ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( stageBlock . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . names = new NameGenerator ( factory ) ; this . valueType = importer . resolve ( factory . newNamedType ( shuffle . getCompiled ( ) . getValueTypeName ( ) ) ) ; this . connection = new FragmentConnection ( environment , fragment , names , importer ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getReduceFragmentClass ( fragment . getSerialNumber ( ) ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( connection . createFields ( ) ) ; ConstructorDeclaration ctor = connection . createConstructor ( name ) ; List < MethodDeclaration > methods = Lists . create ( ) ; SimpleName value = names . create ( "" ) ; methods . add ( createProcess ( value ) ) ; methods . addAll ( emit ( value ) ) ; members . addAll ( extraFields ) ; members . add ( ctor ) ; members . addAll ( methods ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , factory . newParameterizedType ( Models . toType ( factory , Rendezvous . class ) , Arrays . asList ( valueType ) ) , Collections . < Type > emptyList ( ) , members ) ; } private MethodDeclaration createBegin ( List < Statement > statements ) { assert statements != null ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( Rendezvous . BEGIN ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createProcess ( SimpleName value ) { assert value != null ; List < Statement > cases = Lists . create ( ) ; for ( FlowElementInput input : fragment . getInputPorts ( ) ) { Segment segment = shuffle . findSegment ( input ) ; cases . add ( factory . newSwitchCaseLabel ( Models . toLiteral ( factory , segment . getPortId ( ) ) ) ) ; Expression model = new ExpressionBuilder ( factory , value ) . method ( Naming . getShuffleValueGetter ( segment . getPortId ( ) ) ) . toExpression ( ) ; cases . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( getMethodName ( PROCESS_PREFIX , segment ) , model ) . toStatement ( ) ) ; cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( value ) . toThrowStatement ( ) ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( factory . newSwitchStatement ( new ExpressionBuilder ( factory , value ) . method ( SegmentedWritable . ID_GETTER ) . toExpression ( ) , cases ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( Rendezvous . PROCESS ) , Arrays . asList ( factory . newFormalParameterDeclaration ( valueType , value ) ) , statements ) ; } private MethodDeclaration createEnd ( List < Statement > statements ) { assert statements != null ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( Rendezvous . END ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private List < MethodDeclaration > emit ( SimpleName argument ) { assert argument != null ; assert fragment . getFactors ( ) . size ( ) == ; Factor factor = fragment . getFactors ( ) . get ( ) ; FlowElementProcessor proc = factor . getProcessor ( ) ; assert proc . getKind ( ) == Kind . RENDEZVOUS ; RendezvousProcessor processor = ( RendezvousProcessor ) proc ; LOG . debug ( "" , factor , processor ) ; RendezvousProcessor . Context context = createConext ( factor , argument ) ; processor . emitRendezvous ( context ) ; return mergeContext ( context , argument ) ; } private RendezvousProcessor . Context createConext ( Factor factor , SimpleName argument ) { assert argument != null ; FlowElementDescription desc = factor . getElement ( ) . getDescription ( ) ; if ( ( desc instanceof OperatorDescription ) == false ) { throw new IllegalArgumentException ( desc . toString ( ) ) ; } OperatorDescription description = ( OperatorDescription ) desc ; Map < FlowElementPortDescription , Expression > inputs = Maps . create ( ) ; for ( FlowElementInput port : factor . getElement ( ) . getInputPorts ( ) ) { inputs . put ( port . getDescription ( ) , argument ) ; } return new RendezvousProcessor . Context ( environment , factor . getElement ( ) , importer , names , description , inputs , connection . getOutputs ( ) , connection . getResources ( ) ) ; } private List < MethodDeclaration > mergeContext ( RendezvousProcessor . Context context , SimpleName argument ) { assert context != null ; assert argument != null ; extraFields . addAll ( context . getGeneratedFields ( ) ) ; List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createBegin ( context . getBeginStatements ( ) ) ) ; results . add ( createEnd ( context . getEndStatements ( ) ) ) ; for ( FlowElementInput input : fragment . getInputPorts ( ) ) { Segment segment = shuffle . findSegment ( input ) ; MethodDeclaration port = createPort ( PROCESS_PREFIX , segment , argument , context . getProcessStatements ( input . getDescription ( ) ) ) ; LOG . debug ( "" , segment , port . getName ( ) ) ; results . add ( port ) ; } return results ; } private MethodDeclaration createPort ( String prefix , Segment segment , SimpleName argument , List < Statement > statements ) { assert prefix != null ; assert segment != null ; assert argument != null ; assert statements != null ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , t ( void . class ) , getMethodName ( prefix , segment ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( segment . getTarget ( ) . getType ( ) ) , argument ) ) , statements ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . code ( "" , fragment . getInputPorts ( ) ) . text ( "" ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } private SimpleName getMethodName ( String prefix , Segment segment ) { return factory . newSimpleName ( String . format ( "" , prefix , segment . getPortId ( ) ) ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowGraphRewriter ; import com . asakusafw . compiler . flow . FlowGraphRewriter . RewriteException ; import com . asakusafw . runtime . flow . FlowResource ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; public class FlowResourceEmitter { static final Logger LOG = LoggerFactory . getLogger ( FlowResourceEmitter . class ) ; private final FlowCompilingEnvironment environment ; private final List < FlowGraphRewriter > rewriters ; public FlowResourceEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; this . rewriters = environment . getGraphRewriters ( ) . getRewriters ( ) ; } public Map < FlowResourceDescription , CompiledType > emit ( Set < FlowResourceDescription > resources ) throws IOException { Precondition . checkMustNotBeNull ( resources , "" ) ; Map < FlowResourceDescription , CompiledType > results = Maps . create ( ) ; for ( FlowResourceDescription resource : resources ) { Name compiled = compile ( resource ) ; if ( compiled != null ) { results . put ( resource , new CompiledType ( compiled ) ) ; } } return results ; } private Name compile ( FlowResourceDescription resource ) { assert resource != null ; for ( FlowGraphRewriter rewriter : rewriters ) { try { Name compiled = rewriter . resolve ( resource ) ; if ( compiled != null ) { LOG . debug ( "" , resource , compiled ) ; return compiled ; } } catch ( RewriteException e ) { environment . error ( "" , resource , e . getMessage ( ) ) ; LOG . error ( MessageFormat . format ( "" , resource ) , e ) ; } } environment . error ( "" , resource ) ; return null ; } } package com . asakusafw . compiler . flow . stage ; public class CompiledShuffleFragment { private CompiledType mapOutputType ; private CompiledType combineOutputType ; public CompiledShuffleFragment ( CompiledType mapOutput , CompiledType combineOutput ) { if ( mapOutput == null ) { throw new IllegalArgumentException ( "" ) ; } if ( combineOutput == null ) { throw new IllegalArgumentException ( "" ) ; } this . mapOutputType = mapOutput ; this . combineOutputType = combineOutput ; } public CompiledType getMapOutputType ( ) { return mapOutputType ; } public CompiledType getCombineOutputType ( ) { return combineOutputType ; } } package com . asakusafw . compiler . flow . stage ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . ResourceFragment ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; public class FragmentConnection { private final Map < FlowResourceDescription , SimpleName > resources = Maps . create ( ) ; private final Map < FlowElementOutput , SimpleName > successors = Maps . create ( ) ; private final ModelFactory factory ; private final Fragment fragment ; private final ImportBuilder importer ; public FragmentConnection ( FlowCompilingEnvironment environment , Fragment fragment , NameGenerator names , ImportBuilder importer ) { assert environment != null ; assert fragment != null ; assert names != null ; assert importer != null ; this . factory = environment . getModelFactory ( ) ; this . fragment = fragment ; this . importer = importer ; for ( ResourceFragment resource : fragment . getResources ( ) ) { SimpleName name = names . create ( "" ) ; resources . put ( resource . getDescription ( ) , name ) ; } for ( FlowElementOutput output : fragment . getOutputPorts ( ) ) { SimpleName name = names . create ( output . getDescription ( ) . getName ( ) ) ; successors . put ( output , name ) ; } } public List < FieldDeclaration > createFields ( ) { List < FieldDeclaration > results = Lists . create ( ) ; for ( ResourceFragment resource : fragment . getResources ( ) ) { results . add ( createResourceField ( resource ) ) ; } for ( FlowElementOutput output : fragment . getOutputPorts ( ) ) { results . add ( createOutputField ( output ) ) ; } return results ; } public ConstructorDeclaration createConstructor ( SimpleName className ) { Precondition . checkMustNotBeNull ( className , "" ) ; JavadocBuilder javadoc = new JavadocBuilder ( factory ) . text ( "" ) ; List < FormalParameterDeclaration > parameters = Lists . create ( ) ; List < Statement > statements = Lists . create ( ) ; for ( ResourceFragment resource : fragment . getResources ( ) ) { SimpleName param = getResource ( resource . getDescription ( ) ) ; javadoc . param ( param ) . text ( resource . getDescription ( ) . toString ( ) ) ; parameters . add ( factory . newFormalParameterDeclaration ( importer . toType ( resource . getCompiled ( ) . getQualifiedName ( ) ) , param ) ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( param ) . assignFrom ( param ) . toStatement ( ) ) ; } for ( FlowElementOutput output : fragment . getOutputPorts ( ) ) { SimpleName chain = successors . get ( output ) ; assert chain != null ; javadoc . param ( chain ) . code ( "" , output . getOwner ( ) . getDescription ( ) . getName ( ) , output . getDescription ( ) . getName ( ) ) . text ( "" ) ; parameters . add ( factory . newFormalParameterDeclaration ( importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , Result . class ) , Models . toType ( factory , output . getDescription ( ) . getDataType ( ) ) ) ) , chain ) ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( chain ) . assignFrom ( chain ) . toStatement ( ) ) ; } return factory . newConstructorDeclaration ( javadoc . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , className , parameters , statements ) ; } private FieldDeclaration createResourceField ( ResourceFragment resource ) { assert resource != null ; return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , importer . toType ( resource . getCompiled ( ) . getQualifiedName ( ) ) , getResource ( resource . getDescription ( ) ) , null ) ; } private FieldDeclaration createOutputField ( FlowElementOutput output ) { assert output != null ; return factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . Final ( ) . toAttributes ( ) , importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , Result . class ) , Models . toType ( factory , output . getDescription ( ) . getDataType ( ) ) ) ) , successors . get ( output ) , null ) ; } private SimpleName getResource ( FlowResourceDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; SimpleName name = resources . get ( description ) ; Precondition . checkMustNotBeNull ( name , "" ) ; return name ; } public Map < FlowResourceDescription , Expression > getResources ( ) { Map < FlowResourceDescription , Expression > results = Maps . create ( ) ; for ( ResourceFragment key : fragment . getResources ( ) ) { SimpleName name = resources . get ( key . getDescription ( ) ) ; assert name != null ; results . put ( key . getDescription ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( name ) . toExpression ( ) ) ; } return results ; } public Map < FlowElementPortDescription , Expression > getOutputs ( ) { Map < FlowElementPortDescription , Expression > results = Maps . create ( ) ; for ( FlowElementOutput key : fragment . getOutputPorts ( ) ) { SimpleName name = successors . get ( key ) ; assert name != null ; results . put ( key . getDescription ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( name ) . toExpression ( ) ) ; } return results ; } } package com . asakusafw . compiler . flow . stage ; import java . lang . reflect . Type ; import java . util . List ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . DataClassRepository ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . compiler . flow . ShuffleDescription ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Arrangement ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Term ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; public class ShuffleAnalyzer { static final Logger LOG = LoggerFactory . getLogger ( ShuffleAnalyzer . class ) ; private FlowCompilingEnvironment environment ; private boolean sawError ; public ShuffleAnalyzer ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public boolean hasError ( ) { return sawError ; } public void clearError ( ) { sawError = false ; } public ShuffleModel analyze ( StageBlock block ) { Precondition . checkMustNotBeNull ( block , "" ) ; LOG . info ( "" , block ) ; if ( block . hasReduceBlocks ( ) == false ) { LOG . debug ( "" , block ) ; return null ; } List < FlowElement > elements = collectRendezvousElements ( block . getReduceBlocks ( ) ) ; List < ShuffleModel . Segment > segments = collectSegments ( elements ) ; ShuffleModel model = new ShuffleModel ( block , segments ) ; if ( environment . hasError ( ) ) { LOG . debug ( "" , block ) ; return null ; } LOG . debug ( "" , block , model ) ; return model ; } private List < ShuffleModel . Segment > collectSegments ( List < FlowElement > elements ) { assert elements != null ; LOG . debug ( "" ) ; List < ShuffleModel . Segment > segments = Lists . create ( ) ; for ( int elementId = , n = elements . size ( ) ; elementId < n ; elementId ++ ) { FlowElement element = elements . get ( elementId ) ; FlowElementDescription description = element . getDescription ( ) ; RendezvousProcessor proc = environment . getProcessors ( ) . findRendezvousProcessor ( description ) ; if ( proc == null ) { error ( "" , description , FlowElementProcessor . class . getName ( ) ) ; continue ; } List < ShuffleModel . Segment > segmentsInElement = Lists . create ( ) ; LOG . debug ( "" , element , proc ) ; for ( FlowElementInput input : element . getInputPorts ( ) ) { ShuffleDescription desc = extractDescription ( proc , input ) ; ShuffleModel . Segment segment = resolveDescription ( elementId , segments . size ( ) + segmentsInElement . size ( ) + , input , desc ) ; if ( segment != null ) { segmentsInElement . add ( segment ) ; } } checkValidSegmentsInElement ( segmentsInElement ) ; segments . addAll ( segmentsInElement ) ; } return segments ; } private void checkValidSegmentsInElement ( List < ShuffleModel . Segment > segmentsInElement ) { assert segmentsInElement != null ; if ( segmentsInElement . size ( ) == ) { return ; } ShuffleModel . Segment first = segmentsInElement . get ( ) ; List < ShuffleModel . Term > group = getGroupingTerms ( first ) ; for ( int i = , n = segmentsInElement . size ( ) ; i < n ; i ++ ) { List < ShuffleModel . Term > other = getGroupingTerms ( segmentsInElement . get ( i ) ) ; if ( group . size ( ) != other . size ( ) ) { environment . error ( "" , first . getPort ( ) . getOwner ( ) ) ; break ; } for ( int j = , m = group . size ( ) ; j < m ; j ++ ) { Property firstTerm = group . get ( j ) . getSource ( ) ; Property otherTerm = other . get ( j ) . getSource ( ) ; if ( isCompatible ( firstTerm . getType ( ) , otherTerm . getType ( ) ) == false ) { environment . error ( "" , first . getPort ( ) . getOwner ( ) ) ; } } } } private boolean isCompatible ( Type a , Type b ) { assert a != null ; assert b != null ; return a . equals ( b ) ; } private List < Term > getGroupingTerms ( ShuffleModel . Segment segment ) { assert segment != null ; List < Term > results = Lists . create ( ) ; for ( ShuffleModel . Term term : segment . getTerms ( ) ) { if ( term . getArrangement ( ) == Arrangement . GROUPING ) { results . add ( term ) ; } } return results ; } private ShuffleDescription extractDescription ( RendezvousProcessor processor , FlowElementInput input ) { assert processor != null ; assert input != null ; ShuffleDescription desc = processor . getShuffleDescription ( input . getOwner ( ) . getDescription ( ) , input . getDescription ( ) ) ; return desc ; } private List < FlowElement > collectRendezvousElements ( Set < FlowBlock > reduceBlocks ) { assert reduceBlocks != null ; assert reduceBlocks . isEmpty ( ) == false ; LOG . debug ( "" , reduceBlocks ) ; List < FlowElement > results = Lists . create ( ) ; Set < FlowElement > saw = Sets . create ( ) ; for ( FlowBlock reducer : reduceBlocks ) { for ( FlowBlock . Input input : reducer . getBlockInputs ( ) ) { FlowElement rendezvous = input . getElementPort ( ) . getOwner ( ) ; if ( saw . contains ( rendezvous ) ) { continue ; } LOG . debug ( "" , reducer , rendezvous ) ; saw . add ( rendezvous ) ; results . add ( rendezvous ) ; } } return results ; } private ShuffleModel . Segment resolveDescription ( int elementId , int portId , FlowElementInput input , ShuffleDescription desciption ) { assert input != null ; assert desciption != null ; ShuffleKey keyInfo = desciption . getKeyInfo ( ) ; Type inputType = input . getDescription ( ) . getDataType ( ) ; DataClassRepository dataClasses = environment . getDataClasses ( ) ; DataClass source = dataClasses . load ( inputType ) ; DataClass target = dataClasses . load ( desciption . getOutputType ( ) ) ; if ( source == null ) { error ( "" , inputType ) ; } if ( target == null ) { error ( "" , desciption . getOutputType ( ) ) ; } if ( source == null || target == null ) { return null ; } List < ShuffleModel . Term > terms = Lists . create ( ) ; for ( String name : keyInfo . getGroupProperties ( ) ) { int termId = terms . size ( ) + ; DataClass . Property property = target . findProperty ( name ) ; if ( property == null ) { error ( "" , target , name ) ; continue ; } terms . add ( new ShuffleModel . Term ( termId , property , ShuffleModel . Arrangement . GROUPING ) ) ; } for ( ShuffleKey . Order order : keyInfo . getOrderings ( ) ) { int termId = terms . size ( ) + ; DataClass . Property property = target . findProperty ( order . getProperty ( ) ) ; if ( property == null ) { error ( "" , target , order . getProperty ( ) ) ; continue ; } ShuffleModel . Arrangement arrange ; if ( order . getDirection ( ) == ShuffleKey . Direction . ASC ) { arrange = ShuffleModel . Arrangement . ASCENDING ; } else { arrange = ShuffleModel . Arrangement . DESCENDING ; } terms . add ( new ShuffleModel . Term ( termId , property , arrange ) ) ; } return new ShuffleModel . Segment ( elementId , portId , desciption , input , source , target , terms ) ; } private void error ( String format , Object ... args ) { environment . error ( format , args ) ; sawError = true ; } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . RawComparator ; import org . apache . hadoop . io . WritableComparator ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Arrangement ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Term ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . IfStatement ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ShuffleGroupingComparatorEmitter { static final Logger LOG = LoggerFactory . getLogger ( ShuffleGroupingComparatorEmitter . class ) ; private FlowCompilingEnvironment environment ; public ShuffleGroupingComparatorEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public Name emit ( ShuffleModel model , Name keyTypeName ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; Precondition . checkMustNotBeNull ( keyTypeName , "" ) ; LOG . debug ( "" , model . getStageBlock ( ) ) ; Engine engine = new Engine ( environment , model , keyTypeName ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , model . getStageBlock ( ) , name ) ; return name ; } private static class Engine { private ShuffleModel model ; private ModelFactory factory ; private ImportBuilder importer ; private Type keyType ; public Engine ( FlowCompilingEnvironment environment , ShuffleModel model , Name keyTypeName ) { assert environment != null ; assert model != null ; assert keyTypeName != null ; this . model = model ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( model . getStageBlock ( ) . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . keyType = importer . resolve ( factory . newNamedType ( keyTypeName ) ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getShuffleGroupingComparatorClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createCompareBytes ( ) ) ; members . add ( createCompareObjects ( ) ) ; members . add ( ShuffleEmiterUtil . createCompareInts ( factory ) ) ; members . add ( ShuffleEmiterUtil . createPortToElement ( factory , model ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( importer . resolve ( factory . newParameterizedType ( t ( RawComparator . class ) , Collections . singletonList ( keyType ) ) ) ) , members ) ; } private MethodDeclaration createCompareBytes ( ) { SimpleName b1 = factory . newSimpleName ( "" ) ; SimpleName s1 = factory . newSimpleName ( "" ) ; SimpleName l1 = factory . newSimpleName ( "" ) ; SimpleName b2 = factory . newSimpleName ( "" ) ; SimpleName s2 = factory . newSimpleName ( "" ) ; SimpleName l2 = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; SimpleName segmentId1 = factory . newSimpleName ( "" ) ; SimpleName segmentId2 = factory . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( factory , t ( WritableComparator . class ) ) . method ( "" , b1 , s1 ) . toLocalVariableDeclaration ( t ( int . class ) , segmentId1 ) ) ; statements . add ( new TypeBuilder ( factory , t ( WritableComparator . class ) ) . method ( "" , b2 , s2 ) . toLocalVariableDeclaration ( t ( int . class ) , segmentId2 ) ) ; SimpleName diff = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . COMPARE_INT , new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , segmentId1 ) . toExpression ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , segmentId2 ) . toExpression ( ) ) . toLocalVariableDeclaration ( t ( int . class ) , diff ) ) ; statements . add ( createDiffBranch ( diff ) ) ; SimpleName o1 = factory . newSimpleName ( "" ) ; SimpleName o2 = factory . newSimpleName ( "" ) ; SimpleName size1 = factory . newSimpleName ( "" ) ; SimpleName size2 = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , v ( ) ) . toLocalVariableDeclaration ( t ( int . class ) , o1 ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( ) ) . toLocalVariableDeclaration ( t ( int . class ) , o2 ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( - ) ) . toLocalVariableDeclaration ( t ( int . class ) , size1 ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( - ) ) . toLocalVariableDeclaration ( t ( int . class ) , size2 ) ) ; List < Statement > cases = Lists . create ( ) ; for ( List < Segment > segments : ShuffleEmiterUtil . groupByElement ( model ) ) { for ( Segment segment : segments ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; } for ( Term term : segments . get ( ) . getTerms ( ) ) { if ( term . getArrangement ( ) != Arrangement . GROUPING ) { continue ; } cases . add ( new ExpressionBuilder ( factory , size1 ) . assignFrom ( term . getSource ( ) . createBytesSize ( b1 , factory . newInfixExpression ( s1 , InfixOperator . PLUS , o1 ) , factory . newInfixExpression ( l1 , InfixOperator . MINUS , o1 ) ) ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , size2 ) . assignFrom ( term . getSource ( ) . createBytesSize ( b2 , factory . newInfixExpression ( s2 , InfixOperator . PLUS , o2 ) , factory . newInfixExpression ( l2 , InfixOperator . MINUS , o2 ) ) ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , diff ) . assignFrom ( term . getSource ( ) . createBytesDiff ( b1 , factory . newInfixExpression ( s1 , InfixOperator . PLUS , o1 ) , size1 , b2 , factory . newInfixExpression ( s2 , InfixOperator . PLUS , o2 ) , size2 ) ) . toStatement ( ) ) ; cases . add ( createDiffBranch ( diff ) ) ; cases . add ( new ExpressionBuilder ( factory , o1 ) . assignFrom ( InfixOperator . PLUS , size1 ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , o2 ) . assignFrom ( InfixOperator . PLUS , size2 ) . toStatement ( ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( ) . toThrowStatement ( ) ) ; statements . add ( factory . newSwitchStatement ( segmentId1 , cases ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( ) ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { factory . newFormalParameterDeclaration ( t ( byte [ ] . class ) , b1 ) , factory . newFormalParameterDeclaration ( t ( int . class ) , s1 ) , factory . newFormalParameterDeclaration ( t ( int . class ) , l1 ) , factory . newFormalParameterDeclaration ( t ( byte [ ] . class ) , b2 ) , factory . newFormalParameterDeclaration ( t ( int . class ) , s2 ) , factory . newFormalParameterDeclaration ( t ( int . class ) , l2 ) , } ) , statements ) ; } private IfStatement createDiffBranch ( SimpleName diff ) { return factory . newIfStatement ( new ExpressionBuilder ( factory , diff ) . apply ( InfixOperator . NOT_EQUALS , v ( ) ) . toExpression ( ) , new ExpressionBuilder ( factory , diff ) . toReturnStatement ( ) , null ) ; } private TypeBodyDeclaration createCompareObjects ( ) { SimpleName o1 = factory . newSimpleName ( "" ) ; SimpleName o2 = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; SimpleName segmentId1 = factory . newSimpleName ( "" ) ; SimpleName segmentId2 = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , o1 ) . method ( SegmentedWritable . ID_GETTER ) . toLocalVariableDeclaration ( t ( int . class ) , segmentId1 ) ) ; statements . add ( new ExpressionBuilder ( factory , o2 ) . method ( SegmentedWritable . ID_GETTER ) . toLocalVariableDeclaration ( t ( int . class ) , segmentId2 ) ) ; SimpleName diff = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . COMPARE_INT , new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , segmentId1 ) . toExpression ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , segmentId2 ) . toExpression ( ) ) . toLocalVariableDeclaration ( t ( int . class ) , diff ) ) ; statements . add ( createDiffBranch ( diff ) ) ; List < Statement > cases = Lists . create ( ) ; for ( List < Segment > segments : ShuffleEmiterUtil . groupByElement ( model ) ) { for ( Segment segment : segments ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; } Segment segment = segments . get ( ) ; for ( Term term : segment . getTerms ( ) ) { if ( term . getArrangement ( ) != Arrangement . GROUPING ) { continue ; } String name = ShuffleEmiterUtil . getPropertyName ( segment , term ) ; Expression rhs = term . getSource ( ) . createValueDiff ( new ExpressionBuilder ( factory , o1 ) . field ( name ) . toExpression ( ) , new ExpressionBuilder ( factory , o2 ) . field ( name ) . toExpression ( ) ) ; cases . add ( new ExpressionBuilder ( factory , diff ) . assignFrom ( rhs ) . toStatement ( ) ) ; cases . add ( createDiffBranch ( diff ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( ) . toThrowStatement ( ) ) ; statements . add ( factory . newSwitchStatement ( segmentId1 , cases ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( ) ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { factory . newFormalParameterDeclaration ( keyType , o1 ) , factory . newFormalParameterDeclaration ( keyType , o2 ) , } ) , statements ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , model . getStageBlock ( ) . getStageNumber ( ) ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . util . Collection ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . FlowElementProcessor . Kind ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . plan . FlowGraphUtil ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . stage . StageModel . Factor ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . MapUnit ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . compiler . flow . stage . StageModel . ResourceFragment ; import com . asakusafw . compiler . flow . stage . StageModel . Sink ; import com . asakusafw . compiler . flow . stage . StageModel . Unit ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; public class StageAnalyzer { static final Logger LOG = LoggerFactory . getLogger ( StageAnalyzer . class ) ; private final FlowCompilingEnvironment environment ; private boolean sawError ; public StageAnalyzer ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public boolean hasError ( ) { return sawError ; } public void clearError ( ) { sawError = false ; } public StageModel analyze ( StageBlock block , ShuffleModel shuffle ) { Precondition . checkMustNotBeNull ( block , "" ) ; LOG . debug ( "" , block ) ; Context context = new Context ( environment ) ; List < MapUnit > mapUnits = Lists . create ( ) ; for ( FlowBlock flowBlock : block . getMapBlocks ( ) ) { mapUnits . addAll ( collectMapUnits ( context , flowBlock ) ) ; } mapUnits = composeMapUnits ( mapUnits ) ; List < ReduceUnit > reduceUnits = Lists . create ( ) ; for ( FlowBlock flowBlock : block . getReduceBlocks ( ) ) { reduceUnits . addAll ( collectReduceUnits ( context , flowBlock ) ) ; } List < Sink > outputs = Lists . create ( ) ; if ( block . hasReduceBlocks ( ) ) { outputs . addAll ( collectOutputs ( context , reduceUnits , block . getReduceBlocks ( ) ) ) ; } else { outputs . addAll ( collectOutputs ( context , mapUnits , block . getMapBlocks ( ) ) ) ; } if ( hasError ( ) ) { return null ; } StageModel model = new StageModel ( block , mapUnits , shuffle , reduceUnits , outputs ) ; LOG . debug ( "" , block , model ) ; return model ; } private List < MapUnit > collectMapUnits ( Context context , FlowBlock block ) { assert context != null ; assert block != null ; LOG . debug ( "" , block ) ; Set < FlowElement > startElements = collectFragmentStartElements ( block ) ; Map < FlowElement , Fragment > fragments = collectFragments ( context , startElements ) ; Graph < Fragment > fgraph = buildFragmentGraph ( fragments ) ; List < MapUnit > units = buildMapUnits ( context , block , fragments , fgraph ) ; return units ; } private List < MapUnit > composeMapUnits ( List < MapUnit > mapUnits ) { assert mapUnits != null ; Map < Set < FlowBlock . Output > , List < MapUnit > > sameInputs = Maps . create ( ) ; for ( MapUnit unit : mapUnits ) { Set < FlowBlock . Output > sources = Sets . create ( ) ; for ( FlowBlock . Input input : unit . getInputs ( ) ) { for ( FlowBlock . Connection conn : input . getConnections ( ) ) { sources . add ( conn . getUpstream ( ) ) ; } } Maps . addToList ( sameInputs , sources , unit ) ; } List < MapUnit > results = Lists . create ( ) ; for ( Map . Entry < Set < FlowBlock . Output > , List < MapUnit > > entry : sameInputs . entrySet ( ) ) { Set < FlowBlock . Output > sources = entry . getKey ( ) ; List < MapUnit > group = entry . getValue ( ) ; results . add ( compose ( sources , group ) ) ; } return results ; } private MapUnit compose ( Set < FlowBlock . Output > sources , List < MapUnit > group ) { assert sources != null ; assert group != null ; assert group . isEmpty ( ) == false ; if ( group . size ( ) == ) { return group . get ( ) ; } Set < FlowBlock . Input > sawInputs = Sets . create ( ) ; List < FlowBlock . Input > inputs = Lists . create ( ) ; List < Fragment > fragments = Lists . create ( ) ; for ( MapUnit unit : group ) { fragments . addAll ( unit . getFragments ( ) ) ; for ( FlowBlock . Input input : unit . getInputs ( ) ) { if ( sawInputs . contains ( input ) ) { continue ; } sawInputs . add ( input ) ; inputs . add ( input ) ; } } return new MapUnit ( inputs , fragments ) ; } private List < ReduceUnit > collectReduceUnits ( Context context , FlowBlock block ) { assert context != null ; assert block != null ; LOG . debug ( "" , block ) ; Set < FlowElement > startElements = collectFragmentStartElements ( block ) ; Map < FlowElement , Fragment > fragments = collectFragments ( context , startElements ) ; Graph < Fragment > fgraph = buildFragmentGraph ( fragments ) ; List < ReduceUnit > units = buildReduceUnits ( context , block , fragments , fgraph ) ; return units ; } private List < MapUnit > buildMapUnits ( Context context , FlowBlock block , Map < FlowElement , Fragment > fragments , Graph < Fragment > fgraph ) { assert context != null ; assert block != null ; assert fragments != null ; assert fgraph != null ; Map < FlowBlock . Input , Graph < Fragment > > streams = new LinkedHashMap < FlowBlock . Input , Graph < Fragment > > ( ) ; for ( FlowBlock . Input blockInput : block . getBlockInputs ( ) ) { FlowElementInput input = blockInput . getElementPort ( ) ; Fragment head = fragments . get ( input . getOwner ( ) ) ; Graph < Fragment > subgraph = createSubgraph ( head , fgraph ) ; streams . put ( blockInput , subgraph ) ; } List < MapUnit > results = Lists . create ( ) ; for ( Map . Entry < FlowBlock . Input , Graph < Fragment > > entry : streams . entrySet ( ) ) { FlowBlock . Input input = entry . getKey ( ) ; Graph < Fragment > subgraph = entry . getValue ( ) ; List < Fragment > body = sort ( subgraph ) ; for ( int i = , n = body . size ( ) ; i < n ; i ++ ) { body . set ( i , body . get ( i ) ) ; } MapUnit unit = new MapUnit ( Collections . singletonList ( input ) , body ) ; LOG . debug ( "" , input , unit ) ; results . add ( unit ) ; } return results ; } private List < ReduceUnit > buildReduceUnits ( Context context , FlowBlock block , Map < FlowElement , Fragment > fragments , Graph < Fragment > fgraph ) { assert context != null ; assert block != null ; assert fragments != null ; assert fgraph != null ; Map < FlowElement , List < FlowBlock . Input > > inputGroups = new LinkedHashMap < FlowElement , List < FlowBlock . Input > > ( ) ; for ( FlowBlock . Input blockInput : block . getBlockInputs ( ) ) { FlowElement element = blockInput . getElementPort ( ) . getOwner ( ) ; Maps . addToList ( inputGroups , element , blockInput ) ; } Map < FlowElement , Graph < Fragment > > streams = Maps . create ( ) ; for ( FlowElement element : inputGroups . keySet ( ) ) { Fragment head = fragments . get ( element ) ; Graph < Fragment > subgraph = createSubgraph ( head , fgraph ) ; streams . put ( element , subgraph ) ; } List < ReduceUnit > results = Lists . create ( ) ; for ( Map . Entry < FlowElement , Graph < Fragment > > entry : streams . entrySet ( ) ) { FlowElement element = entry . getKey ( ) ; Graph < Fragment > subgraph = entry . getValue ( ) ; List < Fragment > body = sort ( subgraph ) ; for ( int i = , n = body . size ( ) ; i < n ; i ++ ) { body . set ( i , body . get ( i ) ) ; } List < FlowBlock . Input > inputs = inputGroups . get ( element ) ; ReduceUnit unit = new ReduceUnit ( inputs , body ) ; LOG . debug ( "" , element , unit ) ; results . add ( unit ) ; } return results ; } private List < Sink > collectOutputs ( Context context , Collection < ? extends Unit < ? > > units , Collection < FlowBlock > blocks ) { assert context != null ; assert units != null ; assert blocks != null ; Set < FlowElementOutput > candidates = Sets . create ( ) ; for ( FlowBlock block : blocks ) { for ( FlowBlock . Output blockOutput : block . getBlockOutputs ( ) ) { candidates . add ( blockOutput . getElementPort ( ) ) ; } } Set < FlowElementOutput > outputs = Sets . create ( ) ; for ( Unit < ? > unit : units ) { for ( Fragment fragment : unit . getFragments ( ) ) { for ( FlowElementOutput output : fragment . getOutputPorts ( ) ) { if ( candidates . contains ( output ) ) { outputs . add ( output ) ; } } } } Map < Set < FlowBlock . Input > , Set < FlowBlock . Output > > opposites = Maps . create ( ) ; for ( FlowBlock block : blocks ) { for ( FlowBlock . Output blockOutput : block . getBlockOutputs ( ) ) { if ( outputs . contains ( blockOutput . getElementPort ( ) ) == false ) { continue ; } Set < FlowBlock . Input > downstream = Sets . create ( ) ; for ( FlowBlock . Connection connection : blockOutput . getConnections ( ) ) { downstream . add ( connection . getDownstream ( ) ) ; } Maps . addToSet ( opposites , downstream , blockOutput ) ; } } List < Sink > results = Lists . create ( ) ; for ( Set < FlowBlock . Output > group : opposites . values ( ) ) { String name = context . names . create ( "" ) . getToken ( ) ; results . add ( new Sink ( group , context . names . create ( name ) . getToken ( ) ) ) ; } return results ; } private List < Fragment > sort ( Graph < Fragment > subgraph ) { assert subgraph != null ; Graph < Fragment > tgraph = Graphs . transpose ( subgraph ) ; List < Fragment > sorted = Graphs . sortPostOrder ( tgraph ) ; return sorted ; } private Graph < Fragment > createSubgraph ( Fragment head , Graph < Fragment > fgraph ) { assert head != null ; assert fgraph != null ; Set < Fragment > path = Graphs . collectAllConnected ( fgraph , Collections . singleton ( head ) ) ; path . add ( head ) ; Graph < Fragment > result = Graphs . newInstance ( ) ; for ( Fragment fragment : path ) { result . addNode ( fragment ) ; for ( Fragment successor : fgraph . getConnected ( fragment ) ) { if ( path . contains ( successor ) ) { result . addEdge ( fragment , successor ) ; } } } return result ; } private Graph < Fragment > buildFragmentGraph ( Map < FlowElement , Fragment > fragments ) { assert fragments != null ; Graph < Fragment > result = Graphs . newInstance ( ) ; for ( Fragment fragment : fragments . values ( ) ) { result . addNode ( fragment ) ; for ( FlowElementOutput output : fragment . getOutputPorts ( ) ) { for ( FlowElementInput next : output . getOpposites ( ) ) { Fragment successor = fragments . get ( next . getOwner ( ) ) ; assert successor != null ; result . addEdge ( fragment , successor ) ; } } } return result ; } private Map < FlowElement , Fragment > collectFragments ( Context context , Set < FlowElement > startElements ) { assert context != null ; assert startElements != null ; Map < FlowElement , Fragment > results = Maps . create ( ) ; for ( FlowElement element : startElements ) { Fragment fragment = getFragment ( context , element , startElements ) ; assert results . containsKey ( element ) == false ; results . put ( element , fragment ) ; } return results ; } private Fragment getFragment ( Context context , FlowElement element , Set < FlowElement > startElements ) { assert context != null ; assert element != null ; assert startElements != null ; FlowElement current = element ; List < Factor > factors = Lists . create ( ) ; List < ResourceFragment > resources = Lists . create ( ) ; while ( true ) { Factor factor = getFactor ( current ) ; if ( factor == null ) { break ; } factors . add ( factor ) ; resources . addAll ( getResources ( current ) ) ; if ( factor . isLineEnd ( ) ) { break ; } Set < FlowElement > successors = FlowGraphUtil . getSuccessors ( current ) ; if ( successors . size ( ) != ) { break ; } FlowElement next = successors . iterator ( ) . next ( ) ; if ( startElements . contains ( next ) ) { break ; } current = next ; } return new Fragment ( context . getNextFragmentNumber ( ) , factors , resources ) ; } private Set < FlowElement > collectFragmentStartElements ( FlowBlock block ) { assert block != null ; Set < FlowElement > outputs = Sets . create ( ) ; for ( FlowBlock . Output blockOutput : block . getBlockOutputs ( ) ) { outputs . add ( blockOutput . getElementPort ( ) . getOwner ( ) ) ; } Set < FlowElement > results = Sets . create ( ) ; for ( FlowBlock . Input blockInput : block . getBlockInputs ( ) ) { results . add ( blockInput . getElementPort ( ) . getOwner ( ) ) ; } for ( FlowElement element : block . getElements ( ) ) { Set < FlowElement > predecessors = FlowGraphUtil . getPredecessors ( element ) ; if ( predecessors . size ( ) != ) { results . add ( element ) ; } Set < FlowElement > successors = FlowGraphUtil . getSuccessors ( element ) ; if ( successors . size ( ) >= || element . getOutputPorts ( ) . size ( ) >= ) { results . addAll ( successors ) ; } else if ( outputs . contains ( element ) ) { results . addAll ( successors ) ; } else if ( isFragmentEnd ( element ) ) { results . addAll ( successors ) ; } } return results ; } private boolean isFragmentEnd ( FlowElement element ) { assert element != null ; FlowElementDescription description = element . getDescription ( ) ; if ( description . getKind ( ) == FlowElementKind . PSEUD ) { return false ; } assert description . getKind ( ) == FlowElementKind . OPERATOR ; FlowElementProcessor . Repository repo = environment . getProcessors ( ) ; FlowElementProcessor processor = repo . findProcessor ( description ) ; if ( processor == null ) { error ( "" , description ) ; return false ; } return processor . getKind ( ) == Kind . LINE_END || processor . getKind ( ) == Kind . RENDEZVOUS ; } private Factor getFactor ( FlowElement element ) { assert element != null ; FlowElementProcessor . Repository repo = environment . getProcessors ( ) ; FlowElementDescription description = element . getDescription ( ) ; if ( description . getKind ( ) == FlowElementKind . PSEUD ) { return new Factor ( element , repo . getEmptyProcessor ( ) ) ; } FlowElementProcessor processor = repo . findProcessor ( description ) ; if ( processor == null ) { error ( "" , description ) ; return new Factor ( element , repo . getEmptyProcessor ( ) ) ; } return new Factor ( element , processor ) ; } private List < ResourceFragment > getResources ( FlowElement element ) { assert element != null ; List < FlowResourceDescription > resources = element . getDescription ( ) . getResources ( ) ; if ( resources . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < ResourceFragment > results = Lists . create ( ) ; for ( FlowResourceDescription description : resources ) { results . add ( new ResourceFragment ( description ) ) ; } return results ; } private void error ( String format , Object ... args ) { environment . error ( format , args ) ; sawError = true ; } private static class Context { final NameGenerator names ; private int fragmentSerialNumber = ; Context ( FlowCompilingEnvironment environment ) { names = new NameGenerator ( environment . getModelFactory ( ) ) ; } int getNextFragmentNumber ( ) { return ++ fragmentSerialNumber ; } } } package com . asakusafw . compiler . flow . stage ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . Compilable ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . ShuffleDescription ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; public class ShuffleModel extends Compilable . Trait < CompiledShuffle > { private final StageBlock stageBlock ; private final List < Segment > segments ; public ShuffleModel ( StageBlock stageBlock , List < Segment > segments ) { Precondition . checkMustNotBeNull ( stageBlock , "" ) ; Precondition . checkMustNotBeNull ( segments , "" ) ; this . stageBlock = stageBlock ; this . segments = segments ; } public StageBlock getStageBlock ( ) { return stageBlock ; } public List < Segment > getSegments ( ) { return segments ; } public Segment findSegment ( FlowElementInput input ) { Precondition . checkMustNotBeNull ( input , "" ) ; for ( Segment segment : getSegments ( ) ) { if ( segment . getPort ( ) . equals ( input ) ) { return segment ; } } return null ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , segments ) ; } public static class Segment extends Compilable . Trait < CompiledShuffleFragment > { private final int elementId ; private final int portId ; private final ShuffleDescription description ; private final FlowElementInput port ; private final DataClass source ; private final DataClass target ; private final List < Term > terms ; public Segment ( int elementId , int portId , ShuffleDescription description , FlowElementInput port , DataClass source , DataClass target , List < Term > terms ) { Precondition . checkMustNotBeNull ( description , "" ) ; Precondition . checkMustNotBeNull ( port , "" ) ; Precondition . checkMustNotBeNull ( source , "" ) ; Precondition . checkMustNotBeNull ( target , "" ) ; Precondition . checkMustNotBeNull ( terms , "" ) ; this . elementId = elementId ; this . portId = portId ; this . description = description ; this . port = port ; this . source = source ; this . target = target ; this . terms = terms ; } public int getElementId ( ) { return elementId ; } public int getPortId ( ) { return portId ; } public ShuffleDescription getDescription ( ) { return description ; } public FlowElementInput getPort ( ) { return port ; } public DataClass getSource ( ) { return source ; } public DataClass getTarget ( ) { return target ; } public List < Term > getTerms ( ) { return terms ; } public Term findTerm ( String propertyName ) { Precondition . checkMustNotBeNull ( propertyName , "" ) ; if ( propertyName . trim ( ) . isEmpty ( ) ) { return null ; } String name = JavaName . of ( propertyName ) . toMemberName ( ) ; for ( Term term : terms ) { if ( term . getSource ( ) . getName ( ) . equals ( name ) ) { return term ; } } return null ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , port , terms , portId ) ; } } public static class Term { private final int termId ; private final DataClass . Property source ; private final Arrangement arrangement ; public Term ( int termId , DataClass . Property source , Arrangement arrangement ) { Precondition . checkMustNotBeNull ( source , "" ) ; Precondition . checkMustNotBeNull ( arrangement , "" ) ; this . termId = termId ; this . source = source ; this . arrangement = arrangement ; } public int getTermId ( ) { return termId ; } public DataClass . Property getSource ( ) { return source ; } public Arrangement getArrangement ( ) { return arrangement ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getSource ( ) . getName ( ) , getArrangement ( ) ) ; } } public enum Arrangement { GROUPING , ASCENDING , DESCENDING , } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . NameGenerator ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . flow . SegmentedCombiner ; import com . asakusafw . runtime . flow . SegmentedReducer ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; public class CombinerEmitter { static final Logger LOG = LoggerFactory . getLogger ( CombinerEmitter . class ) ; private final FlowCompilingEnvironment environment ; public CombinerEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledType emit ( StageModel model ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; if ( canCombine ( model ) == false ) { LOG . debug ( "" , model ) ; return null ; } LOG . debug ( "" , model ) ; Engine engine = new Engine ( environment , model ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , model , name ) ; return new CompiledType ( name ) ; } private boolean canCombine ( StageModel model ) { assert model != null ; for ( ReduceUnit unit : model . getReduceUnits ( ) ) { if ( unit . canCombine ( ) ) { return true ; } } return false ; } private static class Engine { private final List < ReduceUnit > reduceUnits ; private final ShuffleModel shuffle ; private final ModelFactory factory ; private final ImportBuilder importer ; private final NameGenerator names ; private final SimpleName context ; private final Map < ShuffleModel . Segment , SimpleName > shuffleNames ; private final Map < Fragment , SimpleName > rendezvousNames ; Engine ( FlowCompilingEnvironment environment , StageModel model ) { assert environment != null ; assert model != null ; this . reduceUnits = model . getReduceUnits ( ) ; this . shuffle = model . getShuffleModel ( ) ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( model . getStageBlock ( ) . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . names = new NameGenerator ( factory ) ; this . context = names . create ( "" ) ; this . shuffleNames = Maps . create ( ) ; this . rendezvousNames = Maps . create ( ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getCombineClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( prepareFields ( ) ) ; members . add ( createSetup ( ) ) ; members . add ( createCleanup ( ) ) ; members . add ( createGetRendezvous ( ) ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . text ( "" , shuffle . getStageBlock ( ) . getStageNumber ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , SegmentedCombiner . class ) , Arrays . asList ( importer . toType ( shuffle . getCompiled ( ) . getKeyTypeName ( ) ) , importer . toType ( shuffle . getCompiled ( ) . getValueTypeName ( ) ) ) ) ) , Collections . < Type > emptyList ( ) , members ) ; } private List < FieldDeclaration > prepareFields ( ) { List < FieldDeclaration > fields = Lists . create ( ) ; for ( ShuffleModel . Segment segment : shuffle . getSegments ( ) ) { SimpleName shuffleName = names . create ( "" ) ; shuffleNames . put ( segment , shuffleName ) ; Name shuffleTypeName = segment . getCompiled ( ) . getCombineOutputType ( ) . getQualifiedName ( ) ; fields . add ( factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , importer . toType ( shuffleTypeName ) , shuffleName , null ) ) ; } for ( ReduceUnit unit : reduceUnits ) { if ( unit . canCombine ( ) == false ) { continue ; } Fragment first = unit . getFragments ( ) . get ( ) ; SimpleName rendezvousName = names . create ( "" ) ; rendezvousNames . put ( first , rendezvousName ) ; fields . add ( factory . newFieldDeclaration ( null , new AttributeBuilder ( factory ) . Private ( ) . toAttributes ( ) , importer . toType ( first . getCompiled ( ) . getQualifiedName ( ) ) , rendezvousName , null ) ) ; } return fields ; } private MethodDeclaration createSetup ( ) { Map < FlowElementInput , Segment > segments = Maps . create ( ) ; List < Statement > statements = Lists . create ( ) ; for ( Map . Entry < ShuffleModel . Segment , SimpleName > entry : shuffleNames . entrySet ( ) ) { ShuffleModel . Segment segment = entry . getKey ( ) ; SimpleName name = entry . getValue ( ) ; Name shuffleTypeName = segment . getCompiled ( ) . getCombineOutputType ( ) . getQualifiedName ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( name ) . assignFrom ( new TypeBuilder ( factory , importer . toType ( shuffleTypeName ) ) . newObject ( context ) . toExpression ( ) ) . toStatement ( ) ) ; segments . put ( segment . getPort ( ) , segment ) ; } for ( Map . Entry < Fragment , SimpleName > entry : rendezvousNames . entrySet ( ) ) { Fragment fragment = entry . getKey ( ) ; Type rendezvousType = importer . toType ( fragment . getCompiled ( ) . getQualifiedName ( ) ) ; List < Expression > arguments = Lists . create ( ) ; for ( FlowElementInput input : fragment . getInputPorts ( ) ) { Segment segment = segments . get ( input ) ; assert segment != null ; SimpleName shuffleName = shuffleNames . get ( segment ) ; assert shuffleName != null ; arguments . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( shuffleName ) . toExpression ( ) ) ; } SimpleName name = entry . getValue ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( name ) . assignFrom ( new TypeBuilder ( factory , rendezvousType ) . newObject ( arguments ) . toExpression ( ) ) . toStatement ( ) ) ; } return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newNamedType ( factory . newSimpleName ( "" ) ) , context ) ) , , Arrays . asList ( t ( IOException . class ) , t ( InterruptedException . class ) ) , factory . newBlock ( statements ) ) ; } private MethodDeclaration createCleanup ( ) { List < Statement > statements = Lists . create ( ) ; for ( SimpleName name : shuffleNames . values ( ) ) { statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( name ) . assignFrom ( Models . toNullLiteral ( factory ) ) . toStatement ( ) ) ; } for ( SimpleName name : rendezvousNames . values ( ) ) { statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( name ) . assignFrom ( Models . toNullLiteral ( factory ) ) . toStatement ( ) ) ; } return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( factory . newNamedType ( factory . newSimpleName ( "" ) ) , context ) ) , , Arrays . asList ( t ( IOException . class ) , t ( InterruptedException . class ) ) , factory . newBlock ( statements ) ) ; } private MethodDeclaration createGetRendezvous ( ) { Map < FlowElement , SimpleName > fragments = Maps . create ( ) ; for ( Map . Entry < Fragment , SimpleName > entry : rendezvousNames . entrySet ( ) ) { fragments . put ( entry . getKey ( ) . getFactors ( ) . get ( ) . getElement ( ) , entry . getValue ( ) ) ; } List < Statement > cases = Lists . create ( ) ; for ( List < ShuffleModel . Segment > group : ShuffleEmiterUtil . groupByElement ( shuffle ) ) { for ( ShuffleModel . Segment segment : group ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; } FlowElement element = group . get ( ) . getPort ( ) . getOwner ( ) ; SimpleName rendezvousName = fragments . get ( element ) ; if ( rendezvousName == null ) { cases . add ( new ExpressionBuilder ( factory , Models . toNullLiteral ( factory ) ) . toReturnStatement ( ) ) ; } else { cases . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( rendezvousName ) . toReturnStatement ( ) ) ; } } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( ) . toThrowStatement ( ) ) ; SimpleName argument = names . create ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( factory . newSwitchStatement ( new ExpressionBuilder ( factory , argument ) . method ( SegmentedWritable . ID_GETTER ) . toExpression ( ) , cases ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , importer . resolve ( factory . newParameterizedType ( Models . toType ( factory , Rendezvous . class ) , importer . toType ( shuffle . getCompiled ( ) . getValueTypeName ( ) ) ) ) , factory . newSimpleName ( SegmentedReducer . GET_RENDEZVOUS ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( importer . toType ( shuffle . getCompiled ( ) . getKeyTypeName ( ) ) , argument ) ) , statements ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ShuffleValueEmitter { static final Logger LOG = LoggerFactory . getLogger ( ShuffleValueEmitter . class ) ; private FlowCompilingEnvironment environment ; public ShuffleValueEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public Name emit ( ShuffleModel model ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; LOG . debug ( "" , model . getStageBlock ( ) ) ; Engine engine = new Engine ( environment , model ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , model . getStageBlock ( ) , name ) ; return name ; } private static class Engine { private static final String SEGMENT_ID_FIELD_NAME = "" ; private ShuffleModel model ; private ModelFactory factory ; private ImportBuilder importer ; public Engine ( FlowCompilingEnvironment environment , ShuffleModel model ) { assert environment != null ; assert model != null ; this . model = model ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( model . getStageBlock ( ) . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getShuffleValueClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createSegmentDistinction ( ) ) ; members . addAll ( createProperties ( ) ) ; members . addAll ( createAccessors ( ) ) ; members . addAll ( createWritables ( ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( t ( SegmentedWritable . class ) ) , members ) ; } private List < TypeBodyDeclaration > createSegmentDistinction ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createSegmentIdField ( ) ) ; results . add ( createSegmentIdGetter ( ) ) ; return results ; } private FieldDeclaration createSegmentIdField ( ) { return factory . newFieldDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( SEGMENT_ID_FIELD_NAME ) , v ( - ) ) ; } private TypeBodyDeclaration createSegmentIdGetter ( ) { Statement body = new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( SEGMENT_ID_FIELD_NAME ) . toReturnStatement ( ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( SegmentedWritable . ID_GETTER ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( body ) ) ; } private List < FieldDeclaration > createProperties ( ) { List < FieldDeclaration > results = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { results . add ( createProperty ( segment ) ) ; } return results ; } private String createPropertyName ( Segment segment ) { return String . format ( "" , "" , segment . getPortId ( ) ) ; } private FieldDeclaration createProperty ( Segment segment ) { assert segment != null ; String name = createPropertyName ( segment ) ; DataClass target = segment . getTarget ( ) ; return factory . newFieldDeclaration ( new JavadocBuilder ( factory ) . text ( "" , segment . getPort ( ) . getOwner ( ) . getDescription ( ) . getName ( ) , segment . getPort ( ) . getDescription ( ) . getName ( ) , segment . getPortId ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , t ( target . getType ( ) ) , factory . newSimpleName ( name ) , target . createNewInstance ( t ( target . getType ( ) ) ) ) ; } private List < MethodDeclaration > createAccessors ( ) { List < MethodDeclaration > results = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { results . add ( createGetter ( segment ) ) ; results . add ( createSetter ( segment ) ) ; } return results ; } private MethodDeclaration createGetter ( Segment segment ) { assert segment != null ; String methodName = Naming . getShuffleValueGetter ( segment . getPortId ( ) ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( factory . newIfStatement ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( SEGMENT_ID_FIELD_NAME ) . apply ( InfixOperator . NOT_EQUALS , v ( segment . getPortId ( ) ) ) . toExpression ( ) , new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( ) . toThrowStatement ( ) , null ) ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( createPropertyName ( segment ) ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( new JavadocBuilder ( factory ) . text ( "" , segment . getPort ( ) . getOwner ( ) . getDescription ( ) . getName ( ) , segment . getPort ( ) . getDescription ( ) . getName ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , t ( segment . getTarget ( ) . getType ( ) ) , factory . newSimpleName ( methodName ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createSetter ( Segment segment ) { assert segment != null ; String methodName = Naming . getShuffleValueSetter ( segment . getPortId ( ) ) ; DataClass type = segment . getTarget ( ) ; SimpleName argument = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( factory . newSimpleName ( SEGMENT_ID_FIELD_NAME ) ) . assignFrom ( v ( segment . getPortId ( ) ) ) . toStatement ( ) ) ; statements . add ( type . assign ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( createPropertyName ( segment ) ) . toExpression ( ) , argument ) ) ; return factory . newMethodDeclaration ( new JavadocBuilder ( factory ) . text ( "" , segment . getPort ( ) . getOwner ( ) . getDescription ( ) . getName ( ) , segment . getPort ( ) . getDescription ( ) . getName ( ) ) . param ( argument ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , t ( void . class ) , factory . newSimpleName ( methodName ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( type . getType ( ) ) , argument ) ) , statements ) ; } private List < MethodDeclaration > createWritables ( ) { return Arrays . asList ( createWriteMethod ( ) , createReadFieldsMethod ( ) ) ; } private MethodDeclaration createWriteMethod ( ) { SimpleName out = factory . newSimpleName ( "" ) ; Expression segmentId = new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( SEGMENT_ID_FIELD_NAME ) . toExpression ( ) ; List < Statement > cases = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; cases . add ( new ExpressionBuilder ( factory , out ) . method ( "" , v ( segment . getPortId ( ) ) ) . toStatement ( ) ) ; String fieldName = createPropertyName ( segment ) ; cases . add ( segment . getTarget ( ) . createWriter ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( fieldName ) . toExpression ( ) , out ) ) ; cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( segmentId ) . toThrowStatement ( ) ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( factory . newSwitchStatement ( segmentId , cases ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( DataOutput . class ) , out ) ) , , Collections . singletonList ( t ( IOException . class ) ) , factory . newBlock ( statements ) ) ; } private MethodDeclaration createReadFieldsMethod ( ) { SimpleName in = factory . newSimpleName ( "" ) ; Expression segmentId = new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( SEGMENT_ID_FIELD_NAME ) . toExpression ( ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , segmentId ) . assignFrom ( new ExpressionBuilder ( factory , in ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; List < Statement > cases = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; String fieldName = createPropertyName ( segment ) ; cases . add ( segment . getTarget ( ) . createReader ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . field ( fieldName ) . toExpression ( ) , in ) ) ; cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( segmentId ) . toThrowStatement ( ) ) ; statements . add ( factory . newSwitchStatement ( segmentId , cases ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( void . class ) , factory . newSimpleName ( "" ) , Collections . singletonList ( factory . newFormalParameterDeclaration ( t ( DataInput . class ) , in ) ) , , Collections . singletonList ( t ( IOException . class ) ) , factory . newBlock ( statements ) ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , model . getStageBlock ( ) . getStageNumber ( ) ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . stage ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . RawComparator ; import org . apache . hadoop . io . WritableComparator ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Arrangement ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Term ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . IfStatement ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . ThrowStatement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . UnaryOperator ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ShuffleSortComparatorEmitter { static final Logger LOG = LoggerFactory . getLogger ( ShuffleSortComparatorEmitter . class ) ; private final FlowCompilingEnvironment environment ; public ShuffleSortComparatorEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public Name emit ( ShuffleModel model , Name keyTypeName ) throws IOException { Precondition . checkMustNotBeNull ( model , "" ) ; Precondition . checkMustNotBeNull ( keyTypeName , "" ) ; LOG . debug ( "" , model . getStageBlock ( ) ) ; Engine engine = new Engine ( environment , model , keyTypeName ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , model . getStageBlock ( ) , name ) ; return name ; } private static class Engine { private final ShuffleModel model ; private final ModelFactory factory ; private final ImportBuilder importer ; private final Type keyType ; public Engine ( FlowCompilingEnvironment environment , ShuffleModel model , Name keyTypeName ) { assert environment != null ; assert model != null ; assert keyTypeName != null ; this . model = model ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getStagePackageName ( model . getStageBlock ( ) . getStageNumber ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; this . keyType = importer . resolve ( factory . newNamedType ( keyTypeName ) ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getShuffleSortComparatorClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createCompareBytes ( ) ) ; members . add ( createCompareObjects ( ) ) ; members . add ( ShuffleEmiterUtil . createCompareInts ( factory ) ) ; members . add ( ShuffleEmiterUtil . createPortToElement ( factory , model ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . annotation ( t ( SuppressWarnings . class ) , v ( "" ) ) . Public ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( importer . resolve ( factory . newParameterizedType ( t ( RawComparator . class ) , Collections . singletonList ( keyType ) ) ) ) , members ) ; } private MethodDeclaration createCompareBytes ( ) { SimpleName b1 = factory . newSimpleName ( "" ) ; SimpleName s1 = factory . newSimpleName ( "" ) ; SimpleName l1 = factory . newSimpleName ( "" ) ; SimpleName b2 = factory . newSimpleName ( "" ) ; SimpleName s2 = factory . newSimpleName ( "" ) ; SimpleName l2 = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; SimpleName segmentId1 = factory . newSimpleName ( "" ) ; SimpleName segmentId2 = factory . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( factory , t ( WritableComparator . class ) ) . method ( "" , b1 , s1 ) . toLocalVariableDeclaration ( t ( int . class ) , segmentId1 ) ) ; statements . add ( new TypeBuilder ( factory , t ( WritableComparator . class ) ) . method ( "" , b2 , s2 ) . toLocalVariableDeclaration ( t ( int . class ) , segmentId2 ) ) ; SimpleName diff = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . COMPARE_INT , new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , segmentId1 ) . toExpression ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , segmentId2 ) . toExpression ( ) ) . toLocalVariableDeclaration ( t ( int . class ) , diff ) ) ; statements . add ( createDiff ( diff ) ) ; SimpleName o1 = factory . newSimpleName ( "" ) ; SimpleName o2 = factory . newSimpleName ( "" ) ; SimpleName lim1 = factory . newSimpleName ( "" ) ; SimpleName lim2 = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , v ( ) ) . toLocalVariableDeclaration ( t ( int . class ) , o1 ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( ) ) . toLocalVariableDeclaration ( t ( int . class ) , o2 ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( - ) ) . toLocalVariableDeclaration ( t ( int . class ) , lim1 ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( - ) ) . toLocalVariableDeclaration ( t ( int . class ) , lim2 ) ) ; List < Statement > cases = Lists . create ( ) ; for ( List < Segment > segments : ShuffleEmiterUtil . groupByElement ( model ) ) { for ( Segment segment : segments ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; } for ( Term term : segments . get ( ) . getTerms ( ) ) { if ( term . getArrangement ( ) != Arrangement . GROUPING ) { continue ; } cases . add ( new ExpressionBuilder ( factory , lim1 ) . assignFrom ( term . getSource ( ) . createBytesSize ( b1 , factory . newInfixExpression ( s1 , InfixOperator . PLUS , o1 ) , factory . newInfixExpression ( l1 , InfixOperator . MINUS , o1 ) ) ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , lim2 ) . assignFrom ( term . getSource ( ) . createBytesSize ( b2 , factory . newInfixExpression ( s2 , InfixOperator . PLUS , o2 ) , factory . newInfixExpression ( l2 , InfixOperator . MINUS , o2 ) ) ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , diff ) . assignFrom ( term . getSource ( ) . createBytesDiff ( b1 , factory . newInfixExpression ( s1 , InfixOperator . PLUS , o1 ) , lim1 , b2 , factory . newInfixExpression ( s2 , InfixOperator . PLUS , o2 ) , lim2 ) ) . toStatement ( ) ) ; cases . add ( createDiff ( diff ) ) ; cases . add ( new ExpressionBuilder ( factory , o1 ) . assignFrom ( InfixOperator . PLUS , lim1 ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , o2 ) . assignFrom ( InfixOperator . PLUS , lim2 ) . toStatement ( ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( createAssertionError ( ) ) ; statements . add ( factory . newSwitchStatement ( segmentId1 , cases ) ) ; statements . add ( new ExpressionBuilder ( factory , diff ) . assignFrom ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . COMPARE_INT , segmentId1 , segmentId2 ) . toExpression ( ) ) . toStatement ( ) ) ; statements . add ( createDiff ( diff ) ) ; cases = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; for ( Term term : segment . getTerms ( ) ) { if ( term . getArrangement ( ) == Arrangement . GROUPING ) { continue ; } cases . add ( new ExpressionBuilder ( factory , lim1 ) . assignFrom ( term . getSource ( ) . createBytesSize ( b1 , factory . newInfixExpression ( s1 , InfixOperator . PLUS , o1 ) , factory . newInfixExpression ( l1 , InfixOperator . MINUS , o1 ) ) ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , lim2 ) . assignFrom ( term . getSource ( ) . createBytesSize ( b2 , factory . newInfixExpression ( s2 , InfixOperator . PLUS , o2 ) , factory . newInfixExpression ( l2 , InfixOperator . MINUS , o2 ) ) ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , diff ) . assignFrom ( term . getSource ( ) . createBytesDiff ( b1 , factory . newInfixExpression ( s1 , InfixOperator . PLUS , o1 ) , lim1 , b2 , factory . newInfixExpression ( s2 , InfixOperator . PLUS , o2 ) , lim2 ) ) . toStatement ( ) ) ; cases . add ( createDiff ( diff , term . getArrangement ( ) == Arrangement . DESCENDING ) ) ; cases . add ( new ExpressionBuilder ( factory , o1 ) . assignFrom ( InfixOperator . PLUS , lim1 ) . toStatement ( ) ) ; cases . add ( new ExpressionBuilder ( factory , o2 ) . assignFrom ( InfixOperator . PLUS , lim2 ) . toStatement ( ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( createAssertionError ( ) ) ; statements . add ( factory . newSwitchStatement ( segmentId1 , cases ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( ) ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { factory . newFormalParameterDeclaration ( t ( byte [ ] . class ) , b1 ) , factory . newFormalParameterDeclaration ( t ( int . class ) , s1 ) , factory . newFormalParameterDeclaration ( t ( int . class ) , l1 ) , factory . newFormalParameterDeclaration ( t ( byte [ ] . class ) , b2 ) , factory . newFormalParameterDeclaration ( t ( int . class ) , s2 ) , factory . newFormalParameterDeclaration ( t ( int . class ) , l2 ) , } ) , statements ) ; } private ThrowStatement createAssertionError ( ) { return new TypeBuilder ( factory , t ( AssertionError . class ) ) . newObject ( ) . toThrowStatement ( ) ; } private IfStatement createDiff ( Expression diff ) { return factory . newIfStatement ( new ExpressionBuilder ( factory , diff ) . apply ( InfixOperator . NOT_EQUALS , v ( ) ) . toExpression ( ) , new ExpressionBuilder ( factory , diff ) . toReturnStatement ( ) , null ) ; } private IfStatement createDiff ( Expression diff , boolean desc ) { return factory . newIfStatement ( new ExpressionBuilder ( factory , diff ) . apply ( InfixOperator . NOT_EQUALS , v ( ) ) . toExpression ( ) , new ExpressionBuilder ( factory , diff ) . apply ( desc ? UnaryOperator . MINUS : UnaryOperator . PLUS ) . toReturnStatement ( ) , null ) ; } private TypeBodyDeclaration createCompareObjects ( ) { SimpleName o1 = factory . newSimpleName ( "" ) ; SimpleName o2 = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; SimpleName segmentId1 = factory . newSimpleName ( "" ) ; SimpleName segmentId2 = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , o1 ) . method ( SegmentedWritable . ID_GETTER ) . toLocalVariableDeclaration ( t ( int . class ) , segmentId1 ) ) ; statements . add ( new ExpressionBuilder ( factory , o2 ) . method ( SegmentedWritable . ID_GETTER ) . toLocalVariableDeclaration ( t ( int . class ) , segmentId2 ) ) ; SimpleName diff = factory . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . COMPARE_INT , new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , segmentId1 ) . toExpression ( ) , new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . PORT_TO_ELEMENT , segmentId2 ) . toExpression ( ) ) . toLocalVariableDeclaration ( t ( int . class ) , diff ) ) ; statements . add ( createDiff ( diff ) ) ; List < Statement > cases = Lists . create ( ) ; for ( List < Segment > segments : ShuffleEmiterUtil . groupByElement ( model ) ) { for ( Segment segment : segments ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; } Segment segment = segments . get ( ) ; for ( Term term : segment . getTerms ( ) ) { if ( term . getArrangement ( ) != Arrangement . GROUPING ) { continue ; } String name = ShuffleEmiterUtil . getPropertyName ( segment , term ) ; Expression rhs = term . getSource ( ) . createValueDiff ( new ExpressionBuilder ( factory , o1 ) . field ( name ) . toExpression ( ) , new ExpressionBuilder ( factory , o2 ) . field ( name ) . toExpression ( ) ) ; cases . add ( new ExpressionBuilder ( factory , diff ) . assignFrom ( rhs ) . toStatement ( ) ) ; cases . add ( createDiff ( diff ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( createAssertionError ( ) ) ; statements . add ( factory . newSwitchStatement ( segmentId1 , cases ) ) ; statements . add ( new ExpressionBuilder ( factory , diff ) . assignFrom ( new ExpressionBuilder ( factory , factory . newThis ( ) ) . method ( ShuffleEmiterUtil . COMPARE_INT , segmentId1 , segmentId2 ) . toExpression ( ) ) . toStatement ( ) ) ; statements . add ( createDiff ( diff ) ) ; cases = Lists . create ( ) ; for ( Segment segment : model . getSegments ( ) ) { cases . add ( factory . newSwitchCaseLabel ( v ( segment . getPortId ( ) ) ) ) ; for ( Term term : segment . getTerms ( ) ) { if ( term . getArrangement ( ) == Arrangement . GROUPING ) { continue ; } String name = ShuffleEmiterUtil . getPropertyName ( segment , term ) ; Expression rhs = term . getSource ( ) . createValueDiff ( new ExpressionBuilder ( factory , o1 ) . field ( name ) . toExpression ( ) , new ExpressionBuilder ( factory , o2 ) . field ( name ) . toExpression ( ) ) ; cases . add ( new ExpressionBuilder ( factory , diff ) . assignFrom ( rhs ) . toStatement ( ) ) ; cases . add ( createDiff ( diff , term . getArrangement ( ) == Arrangement . DESCENDING ) ) ; } cases . add ( factory . newBreakStatement ( ) ) ; } cases . add ( factory . newSwitchDefaultLabel ( ) ) ; cases . add ( createAssertionError ( ) ) ; statements . add ( factory . newSwitchStatement ( segmentId1 , cases ) ) ; statements . add ( new ExpressionBuilder ( factory , v ( ) ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Public ( ) . toAttributes ( ) , t ( int . class ) , factory . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { factory . newFormalParameterDeclaration ( keyType , o1 ) , factory . newFormalParameterDeclaration ( keyType , o2 ) , } ) , statements ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , model . getStageBlock ( ) . getStageNumber ( ) ) . toJavadoc ( ) ; } private Type t ( java . lang . reflect . Type type ) { return importer . resolve ( Models . toType ( factory , type ) ) ; } private Expression v ( Object value ) { return Models . toLiteral ( factory , value ) ; } } } package com . asakusafw . compiler . flow . visualizer ; import java . util . Collections ; import java . util . Set ; import java . util . UUID ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Sets ; public class VisualGraph implements VisualNode { private final UUID id = UUID . randomUUID ( ) ; private final String label ; private final Set < VisualNode > nodes ; public VisualGraph ( String label , Set < ? extends VisualNode > nodes ) { Precondition . checkMustNotBeNull ( nodes , "" ) ; this . label = label ; this . nodes = Sets . from ( nodes ) ; } public String getLabel ( ) { return label ; } @ Override public UUID getId ( ) { return id ; } public Set < VisualNode > getNodes ( ) { return Collections . unmodifiableSet ( nodes ) ; } @ Override public Kind getKind ( ) { return Kind . GRAPH ; } @ Override public < R , C , E extends Throwable > R accept ( VisualNodeVisitor < R , C , E > visitor , C context ) throws E { Precondition . checkMustNotBeNull ( visitor , "" ) ; R result = visitor . visitGraph ( context , this ) ; return result ; } } package com . asakusafw . compiler . flow . visualizer ; import java . util . UUID ; import com . asakusafw . compiler . common . Precondition ; public class VisualLabel implements VisualNode { private final UUID id = UUID . randomUUID ( ) ; private String label ; public VisualLabel ( String label ) { this . label = label ; } @ Override public Kind getKind ( ) { return Kind . LABEL ; } @ Override public UUID getId ( ) { return id ; } public String getLabel ( ) { return label ; } @ Override public < R , C , E extends Throwable > R accept ( VisualNodeVisitor < R , C , E > visitor , C context ) throws E { Precondition . checkMustNotBeNull ( visitor , "" ) ; R result = visitor . visitLabel ( context , this ) ; return result ; } } package com . asakusafw . compiler . flow . visualizer ; import java . io . Closeable ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . UUID ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . visualizer . VisualNode . Kind ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . internal . model . util . LiteralAnalyzer ; import com . asakusafw . utils . java . model . util . NoThrow ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . FlowOut ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; public final class VisualGraphEmitter { static final Charset ENCODING = Charset . forName ( "" ) ; static final Logger LOG = LoggerFactory . getLogger ( VisualGraphEmitter . class ) ; private VisualGraphEmitter ( ) { throw new AssertionError ( ) ; } public static void emit ( VisualGraph graph , boolean partial , OutputStream stream ) throws IOException { Precondition . checkMustNotBeNull ( graph , "" ) ; Precondition . checkMustNotBeNull ( stream , "" ) ; LOG . debug ( "" , graph . getId ( ) ) ; EmitContext context = new EmitContext ( stream ) ; try { List < Relation > relations = analyzeRelations ( graph , partial ) ; dump ( context , graph . getNodes ( ) , relations ) ; } finally { context . close ( ) ; } } public static void emit ( VisualGraph graph , boolean partial , File file ) throws IOException { Precondition . checkMustNotBeNull ( graph , "" ) ; Precondition . checkMustNotBeNull ( file , "" ) ; OutputStream output = new FileOutputStream ( file ) ; try { emit ( graph , partial , output ) ; } finally { output . close ( ) ; } } private static List < Relation > analyzeRelations ( VisualGraph graph , boolean partial ) { assert graph != null ; LOG . debug ( "" ) ; List < Relation > result = RelationCollector . collect ( Collections . singleton ( graph ) , partial ) ; return result ; } private static void dump ( EmitContext context , Set < VisualNode > nodes , List < Relation > relations ) { assert context != null ; assert nodes != null ; assert relations != null ; LOG . debug ( "" ) ; context . put ( "" ) ; context . push ( ) ; dumpStructure ( context , nodes ) ; dumpLabels ( context , relations ) ; dumpRelations ( context , relations ) ; context . pop ( ) ; context . put ( "" ) ; } private static void dumpLabels ( EmitContext context , List < Relation > relations ) { assert relations != null ; Set < UUID > saw = Sets . create ( ) ; for ( Relation relation : relations ) { if ( saw . contains ( relation . source . getResolved ( ) . getId ( ) ) == false ) { dumpLabel ( context , relation . source . getResolved ( ) ) ; saw . add ( relation . source . getResolved ( ) . getId ( ) ) ; } if ( saw . contains ( relation . source . getResolved ( ) . getId ( ) ) == false ) { dumpLabel ( context , relation . source . getResolved ( ) ) ; saw . add ( relation . source . getResolved ( ) . getId ( ) ) ; } dumpLabel ( context , relation . sink . getResolved ( ) ) ; } } private static void dumpLabel ( EmitContext context , VisualNode node ) { assert node != null ; if ( node . getKind ( ) == Kind . LABEL ) { StructureEmitter emitter = new StructureEmitter ( ) ; node . accept ( emitter , context ) ; } } private static void dumpStructure ( EmitContext context , Set < VisualNode > nodes ) { assert context != null ; assert nodes != null ; StructureEmitter emitter = new StructureEmitter ( ) ; for ( VisualNode node : nodes ) { node . accept ( emitter , context ) ; } } private static void dumpRelations ( EmitContext context , List < Relation > relations ) { assert context != null ; assert relations != null ; for ( Relation relation : relations ) { context . put ( "" , toLiteral ( relation . source . getResolved ( ) . getId ( ) . toString ( ) ) , toLiteral ( relation . sink . getResolved ( ) . getId ( ) . toString ( ) ) , toLiteral ( MessageFormat . format ( "" , relation . source . name , relation . sink . name ) ) ) ; } } static String toLiteral ( String string ) { assert string != null ; return LiteralAnalyzer . stringLiteralOf ( string ) ; } private static class RelationCollector extends VisualNodeVisitor < Void , Void , NoThrow > { private final boolean partial ; private final Set < Relation > saw = Sets . create ( ) ; final List < Relation > relations = Lists . create ( ) ; final Map < FlowElement , VisualNode > resolveMap = Maps . create ( ) ; RelationCollector ( boolean partial ) { this . partial = partial ; } static List < Relation > collect ( Iterable < ? extends VisualNode > nodes , boolean partial ) { RelationCollector engine = new RelationCollector ( partial ) ; engine . acceptAll ( null , nodes ) ; Iterator < Relation > iter = engine . relations . iterator ( ) ; while ( iter . hasNext ( ) ) { Relation relation = iter . next ( ) ; boolean removed = false ; if ( engine . resolve ( relation . source ) == false ) { if ( partial == false ) { resolveFailed ( relation . source ) ; } iter . remove ( ) ; removed = true ; } if ( engine . resolve ( relation . sink ) == false ) { if ( partial == false ) { resolveFailed ( relation . sink ) ; } if ( removed == false ) { iter . remove ( ) ; } } } return engine . relations ; } private static void resolveFailed ( Port port ) { assert port != null ; LOG . warn ( "" , port . element ) ; } @ Override protected Void visitGraph ( Void context , VisualGraph node ) { acceptAll ( context , node . getNodes ( ) ) ; return null ; } @ Override protected Void visitBlock ( Void context , VisualBlock node ) { if ( partial ) { for ( FlowBlock . Input input : node . getInputs ( ) ) { Port sink = toPort ( input . getElementPort ( ) ) ; for ( FlowBlock . Connection conn : input . getConnections ( ) ) { Port source = toPort ( conn . getUpstream ( ) . getElementPort ( ) ) ; related ( source , sink ) ; } } } for ( FlowBlock . Output output : node . getOutputs ( ) ) { Port source = toPort ( output . getElementPort ( ) ) ; for ( FlowBlock . Connection conn : output . getConnections ( ) ) { FlowElementInput downstream = conn . getDownstream ( ) . getElementPort ( ) ; connect ( source , downstream ) ; } } acceptAll ( context , node . getNodes ( ) ) ; return null ; } @ Override protected Void visitFlowPart ( Void context , VisualFlowPart node ) throws NoThrow { register ( node , node . getElement ( ) ) ; connectSuccessors ( node . getElement ( ) ) ; acceptAll ( context , node . getNodes ( ) ) ; return null ; } @ Override protected Void visitElement ( Void context , VisualElement node ) { register ( node , node . getElement ( ) ) ; connectSuccessors ( node . getElement ( ) ) ; return null ; } private void connectSuccessors ( FlowElement element ) { assert element != null ; if ( element . getDescription ( ) . getKind ( ) == FlowElementKind . FLOW_COMPONENT ) { FlowPartDescription desc = ( FlowPartDescription ) element . getDescription ( ) ; for ( FlowElementOutput output : element . getOutputPorts ( ) ) { FlowOut < ? > internal = desc . getInternalOutputPort ( output . getDescription ( ) ) ; Port source = toPort ( internal . toInputPort ( ) ) ; for ( FlowElementInput downstream : output . getOpposites ( ) ) { connect ( source , downstream ) ; } } } else { for ( FlowElementOutput output : element . getOutputPorts ( ) ) { Port source = toPort ( output ) ; for ( FlowElementInput downstream : output . getOpposites ( ) ) { connect ( source , downstream ) ; } } } } private void connect ( Port source , FlowElementInput downstream ) { assert source != null ; assert downstream != null ; if ( downstream . getOwner ( ) . getDescription ( ) . getKind ( ) == FlowElementKind . FLOW_COMPONENT ) { FlowPartDescription desc = ( FlowPartDescription ) downstream . getOwner ( ) . getDescription ( ) ; FlowIn < ? > internal = desc . getInternalInputPort ( downstream . getDescription ( ) ) ; Port sink = toPort ( internal . toOutputPort ( ) ) ; related ( source , sink ) ; } else { Port sink = toPort ( downstream ) ; related ( source , sink ) ; } } private Port toPort ( FlowElementOutput port ) { assert port != null ; return new Port ( port . getOwner ( ) , port . getDescription ( ) . getName ( ) ) ; } private Port toPort ( FlowElementInput port ) { assert port != null ; return new Port ( port . getOwner ( ) , port . getDescription ( ) . getName ( ) ) ; } private boolean resolve ( Port port ) { assert port != null ; VisualNode node = resolveMap . get ( port . element ) ; if ( node != null ) { port . setResolved ( node ) ; return true ; } if ( partial ) { port . setResolved ( new VisualLabel ( null ) ) ; return true ; } return false ; } private void register ( VisualNode node , FlowElement element ) { assert node != null ; assert element != null ; resolveMap . put ( element , node ) ; } private void related ( Port source , Port sink ) { assert source != null ; assert sink != null ; Relation relation = new Relation ( source , sink ) ; if ( saw . contains ( relation ) == false ) { relations . add ( relation ) ; saw . add ( relation ) ; } } private void acceptAll ( Void context , Iterable < ? extends VisualNode > nodes ) { for ( VisualNode node : nodes ) { node . accept ( this , context ) ; } } } private static class Relation { final Port source ; final Port sink ; Relation ( Port source , Port sink ) { assert source != null ; assert sink != null ; this . source = source ; this . sink = sink ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + sink . hashCode ( ) ; result = prime * result + source . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Relation other = ( Relation ) obj ; if ( ! sink . equals ( other . sink ) ) { return false ; } if ( ! source . equals ( other . source ) ) { return false ; } return true ; } } private static class Port { final FlowElement element ; final String name ; private VisualNode resolved ; public Port ( FlowElement element , String name ) { assert element != null ; assert name != null ; this . element = element ; this . name = name ; } public VisualNode getResolved ( ) { assert resolved != null ; return resolved ; } public void setResolved ( VisualNode resolved ) { assert resolved != null ; assert this . resolved == null || this . resolved == resolved ; this . resolved = resolved ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + element . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Port other = ( Port ) obj ; if ( ! element . equals ( other . element ) ) { return false ; } if ( ! name . equals ( other . name ) ) { return false ; } return true ; } } private static class StructureEmitter extends VisualNodeVisitor < Void , EmitContext , NoThrow > { StructureEmitter ( ) { return ; } @ Override public Void visitGraph ( EmitContext context , VisualGraph node ) { if ( node . getLabel ( ) != null ) { context . put ( "" , toLiteral ( "" + node . getId ( ) . toString ( ) ) ) ; context . push ( ) ; context . put ( "" , toLiteral ( node . getLabel ( ) ) ) ; context . put ( "" ) ; } for ( VisualNode element : node . getNodes ( ) ) { element . accept ( this , context ) ; } if ( node . getLabel ( ) != null ) { context . pop ( ) ; context . put ( "" ) ; } return null ; } @ Override protected Void visitBlock ( EmitContext context , VisualBlock node ) throws NoThrow { if ( node . getLabel ( ) != null ) { context . put ( "" , toLiteral ( "" + node . getId ( ) . toString ( ) ) ) ; context . push ( ) ; context . put ( "" , toLiteral ( node . getLabel ( ) ) ) ; } for ( VisualNode element : node . getNodes ( ) ) { element . accept ( this , context ) ; } if ( node . getLabel ( ) != null ) { context . pop ( ) ; context . put ( "" ) ; } return null ; } @ Override protected Void visitFlowPart ( EmitContext context , VisualFlowPart node ) throws NoThrow { context . put ( "" , toLiteral ( "" + node . getId ( ) . toString ( ) ) ) ; context . push ( ) ; context . put ( "" , toLiteral ( node . getElement ( ) . getDescription ( ) . getName ( ) ) ) ; for ( VisualNode element : node . getNodes ( ) ) { element . accept ( this , context ) ; } context . pop ( ) ; context . put ( "" ) ; return null ; } @ Override protected Void visitElement ( EmitContext context , VisualElement node ) { FlowElement element = node . getElement ( ) ; switch ( element . getDescription ( ) . getKind ( ) ) { case INPUT : case OUTPUT : context . put ( "" , toLiteral ( node . getId ( ) . toString ( ) ) , toLiteral ( element . getDescription ( ) . getName ( ) ) ) ; break ; case OPERATOR : context . put ( "" , toLiteral ( node . getId ( ) . toString ( ) ) , toLiteral ( toOperatorName ( node ) ) ) ; break ; case FLOW_COMPONENT : context . put ( "" , toLiteral ( node . getId ( ) . toString ( ) ) , toLiteral ( element . getDescription ( ) . getName ( ) ) ) ; break ; default : context . put ( "" , toLiteral ( node . getId ( ) . toString ( ) ) ) ; break ; } return null ; } @ Override protected Void visitLabel ( EmitContext context , VisualLabel node ) { if ( node . getLabel ( ) == null ) { context . put ( "" , toLiteral ( node . getId ( ) . toString ( ) ) ) ; } else { context . put ( "" , toLiteral ( node . getId ( ) . toString ( ) ) , toLiteral ( node . getLabel ( ) ) ) ; } return super . visitLabel ( context , node ) ; } static String toOperatorName ( VisualElement node ) { assert node != null ; FlowElement element = node . getElement ( ) ; assert element . getDescription ( ) . getKind ( ) == FlowElementKind . OPERATOR ; OperatorDescription desc = ( OperatorDescription ) element . getDescription ( ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( "" ) ; buf . append ( desc . getDeclaration ( ) . getAnnotationType ( ) . getSimpleName ( ) ) ; buf . append ( "" ) ; buf . append ( desc . getName ( ) ) ; return buf . toString ( ) ; } } private static class EmitContext implements Closeable { private static final int INDENT_UNIT = ; private final PrintWriter writer ; private int indent = ; public EmitContext ( OutputStream output ) { assert output != null ; writer = new PrintWriter ( new OutputStreamWriter ( output , ENCODING ) ) ; } public void push ( ) { indent ++ ; } public void pop ( ) { assert indent >= ; indent -- ; } public void put ( String pattern , Object ... arguments ) { assert pattern != null ; assert arguments != null ; StringBuilder buf = new StringBuilder ( ) ; insertIndent ( buf ) ; if ( arguments . length == ) { buf . append ( pattern ) ; } else { buf . append ( MessageFormat . format ( pattern , arguments ) ) ; } String text = buf . toString ( ) ; writer . println ( text ) ; LOG . debug ( text ) ; } private void insertIndent ( StringBuilder buf ) { for ( int i = , n = indent * INDENT_UNIT ; i < n ; i ++ ) { buf . append ( '' ) ; } } @ Override public void close ( ) { writer . close ( ) ; } } } package com . asakusafw . compiler . flow . visualizer ; import java . util . UUID ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; public class VisualElement implements VisualNode { private final UUID id = UUID . randomUUID ( ) ; private final FlowElement element ; public VisualElement ( FlowElement element ) { Precondition . checkMustNotBeNull ( element , "" ) ; this . element = element ; } @ Override public Kind getKind ( ) { return Kind . ELEMENT ; } @ Override public UUID getId ( ) { return id ; } public FlowElement getElement ( ) { return element ; } @ Override public < R , C , E extends Throwable > R accept ( VisualNodeVisitor < R , C , E > visitor , C context ) throws E { Precondition . checkMustNotBeNull ( visitor , "" ) ; R result = visitor . visitElement ( context , this ) ; return result ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( element ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . compiler . flow . visualizer ; import java . util . Collections ; import java . util . Set ; import java . util . UUID ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; public class VisualFlowPart implements VisualNode { private final UUID id = UUID . randomUUID ( ) ; private final FlowElement element ; private final Set < VisualNode > nodes ; public VisualFlowPart ( FlowElement element , Set < ? extends VisualNode > nodes ) { Precondition . checkMustNotBeNull ( element , "" ) ; Precondition . checkMustNotBeNull ( nodes , "" ) ; this . element = element ; this . nodes = Sets . from ( nodes ) ; } @ Override public Kind getKind ( ) { return Kind . FLOW_PART ; } @ Override public UUID getId ( ) { return id ; } public FlowElement getElement ( ) { return element ; } public Set < VisualNode > getNodes ( ) { return Collections . unmodifiableSet ( nodes ) ; } @ Override public < R , C , E extends Throwable > R accept ( VisualNodeVisitor < R , C , E > visitor , C context ) throws E { Precondition . checkMustNotBeNull ( visitor , "" ) ; R result = visitor . visitFlowPart ( context , this ) ; return result ; } } package com . asakusafw . compiler . flow . visualizer ; import java . util . Collections ; import java . util . Set ; import java . util . UUID ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . utils . collections . Sets ; public class VisualBlock implements VisualNode { private final UUID id = UUID . randomUUID ( ) ; private final String label ; private final Set < FlowBlock . Input > inputs ; private final Set < FlowBlock . Output > outputs ; private final Set < VisualNode > nodes ; public VisualBlock ( String label , Set < FlowBlock . Input > inputs , Set < FlowBlock . Output > outputs , Set < ? extends VisualNode > nodes ) { Precondition . checkMustNotBeNull ( inputs , "" ) ; Precondition . checkMustNotBeNull ( outputs , "" ) ; Precondition . checkMustNotBeNull ( nodes , "" ) ; this . label = label ; this . inputs = Sets . from ( inputs ) ; this . outputs = Sets . from ( outputs ) ; this . nodes = Sets . from ( nodes ) ; } public String getLabel ( ) { return label ; } @ Override public UUID getId ( ) { return id ; } public Set < FlowBlock . Input > getInputs ( ) { return inputs ; } public Set < FlowBlock . Output > getOutputs ( ) { return outputs ; } public Set < VisualNode > getNodes ( ) { return Collections . unmodifiableSet ( nodes ) ; } @ Override public Kind getKind ( ) { return Kind . BLOCK ; } @ Override public < R , C , E extends Throwable > R accept ( VisualNodeVisitor < R , C , E > visitor , C context ) throws E { Precondition . checkMustNotBeNull ( visitor , "" ) ; R result = visitor . visitBlock ( context , this ) ; return result ; } } package com . asakusafw . compiler . flow . visualizer ; public abstract class VisualNodeVisitor < R , C , E extends Throwable > { protected R visitGraph ( C context , VisualGraph node ) throws E { return null ; } protected R visitBlock ( C context , VisualBlock node ) throws E { return null ; } protected R visitFlowPart ( C context , VisualFlowPart node ) throws E { return null ; } protected R visitElement ( C context , VisualElement node ) throws E { return null ; } protected R visitLabel ( C context , VisualLabel node ) throws E { return null ; } } package com . asakusafw . compiler . flow . visualizer ; import java . util . UUID ; public interface VisualNode { Kind getKind ( ) ; UUID getId ( ) ; < R , C , E extends Throwable > R accept ( VisualNodeVisitor < R , C , E > visitor , C context ) throws E ; enum Kind { GRAPH , BLOCK , FLOW_PART , ELEMENT , LABEL , } } package com . asakusafw . compiler . flow . visualizer ; package com . asakusafw . compiler . flow . visualizer ; import java . io . IOException ; import java . io . OutputStream ; import java . text . MessageFormat ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class FlowVisualizer { private static final String PATH_FLOW_GRAPH = "" ; private static final String PATH_STAGE_GRAPH = "" ; private static final String PATH_STAGE_BLOCK = "" ; private final FlowCompilingEnvironment environment ; public FlowVisualizer ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public void visualize ( StageGraph graph ) throws IOException { Precondition . checkMustNotBeNull ( graph , "" ) ; VisualGraph model = VisualAnalyzer . convertStageGraph ( graph ) ; emit ( PATH_STAGE_GRAPH , false , model ) ; } public void visualize ( StageBlock block ) throws IOException { Precondition . checkMustNotBeNull ( block , "" ) ; VisualGraph model = VisualAnalyzer . convertStageBlock ( block ) ; emit ( MessageFormat . format ( PATH_STAGE_BLOCK , String . valueOf ( block . getStageNumber ( ) ) ) , true , model ) ; } public void visualize ( FlowGraph graph ) throws IOException { Precondition . checkMustNotBeNull ( graph , "" ) ; VisualGraph model = VisualAnalyzer . convertFlowGraph ( graph ) ; emit ( PATH_FLOW_GRAPH , false , model ) ; } private void emit ( String path , boolean partial , VisualGraph model ) throws IOException { assert path != null ; assert model != null ; OutputStream output = environment . openResource ( null , path ) ; try { VisualGraphEmitter . emit ( model , partial , output ) ; } finally { output . close ( ) ; } } } package com . asakusafw . compiler . flow . visualizer ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . plan . FlowBlock ; import com . asakusafw . compiler . flow . plan . FlowGraphUtil ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; public final class VisualAnalyzer { static final Logger LOG = LoggerFactory . getLogger ( VisualAnalyzer . class ) ; private final Set < FlowElement > sawElements = Sets . create ( ) ; private VisualAnalyzer ( ) { return ; } public static VisualGraph convertFlowGraph ( FlowGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; LOG . debug ( "" , graph ) ; VisualAnalyzer analyzer = new VisualAnalyzer ( ) ; Set < VisualNode > nodes = Sets . create ( ) ; for ( FlowElement element : FlowGraphUtil . collectElements ( graph ) ) { VisualNode node = analyzer . convertElement ( element ) ; if ( node != null ) { nodes . add ( node ) ; } } return new VisualGraph ( null , nodes ) ; } public static VisualGraph convertStageGraph ( StageGraph graph ) { Precondition . checkMustNotBeNull ( graph , "" ) ; LOG . debug ( "" , graph ) ; VisualAnalyzer analyzer = new VisualAnalyzer ( ) ; Set < VisualNode > nodes = Sets . create ( ) ; nodes . add ( analyzer . convertBlock ( "" , graph . getInput ( ) ) ) ; for ( StageBlock stage : graph . getStages ( ) ) { nodes . add ( analyzer . convertStage ( stage ) ) ; } nodes . add ( analyzer . convertBlock ( "" , graph . getOutput ( ) ) ) ; return new VisualGraph ( null , nodes ) ; } public static VisualGraph convertStageBlock ( StageBlock stage ) { Precondition . checkMustNotBeNull ( stage , "" ) ; LOG . debug ( "" , stage ) ; VisualAnalyzer analyzer = new VisualAnalyzer ( ) ; Set < VisualNode > nodes = Sets . create ( ) ; for ( FlowBlock head : stage . getMapBlocks ( ) ) { for ( FlowBlock . Input input : head . getBlockInputs ( ) ) { for ( FlowBlock . Connection conn : input . getConnections ( ) ) { FlowElement element = conn . getUpstream ( ) . getElementPort ( ) . getOwner ( ) ; VisualNode node = analyzer . convertElement ( element ) ; if ( node != null ) { nodes . add ( node ) ; } } } } nodes . add ( analyzer . convertStage ( stage ) ) ; Set < FlowBlock > tails = stage . hasReduceBlocks ( ) ? stage . getReduceBlocks ( ) : stage . getMapBlocks ( ) ; for ( FlowBlock tail : tails ) { for ( FlowBlock . Output output : tail . getBlockOutputs ( ) ) { for ( FlowBlock . Connection conn : output . getConnections ( ) ) { FlowElement element = conn . getDownstream ( ) . getElementPort ( ) . getOwner ( ) ; VisualNode node = analyzer . convertElement ( element ) ; if ( node != null ) { nodes . add ( node ) ; } } } } return new VisualGraph ( null , nodes ) ; } public static VisualGraph convertFlowBlock ( FlowBlock block ) { Precondition . checkMustNotBeNull ( block , "" ) ; LOG . debug ( "" , block ) ; VisualAnalyzer analyzer = new VisualAnalyzer ( ) ; Set < VisualNode > nodes = Sets . create ( ) ; nodes . add ( analyzer . convertBlock ( "" , block ) ) ; return new VisualGraph ( null , nodes ) ; } private VisualGraph convertStage ( StageBlock stage ) { assert stage != null ; Set < VisualBlock > nodes = Sets . create ( ) ; for ( FlowBlock block : stage . getMapBlocks ( ) ) { nodes . add ( convertBlock ( null , block ) ) ; } for ( FlowBlock block : stage . getReduceBlocks ( ) ) { nodes . add ( convertBlock ( null , block ) ) ; } return new VisualGraph ( Naming . getStageName ( stage . getStageNumber ( ) ) , nodes ) ; } private VisualBlock convertBlock ( String label , FlowBlock block ) { assert block != null ; Set < VisualNode > nodes = Sets . create ( ) ; for ( FlowElement element : block . getElements ( ) ) { VisualNode node = convertElement ( element ) ; if ( node != null ) { nodes . add ( node ) ; } } return new VisualBlock ( label , Sets . from ( block . getBlockInputs ( ) ) , Sets . from ( block . getBlockOutputs ( ) ) , nodes ) ; } private VisualNode convertElement ( FlowElement element ) { assert element != null ; if ( sawElements . contains ( element ) ) { LOG . debug ( "" , element ) ; return null ; } sawElements . add ( element ) ; if ( element . getDescription ( ) . getKind ( ) == FlowElementKind . FLOW_COMPONENT ) { FlowPartDescription desc = ( FlowPartDescription ) element . getDescription ( ) ; Set < VisualNode > nodes = Sets . create ( ) ; for ( FlowElement inner : FlowGraphUtil . collectElements ( desc . getFlowGraph ( ) ) ) { VisualNode node = convertElement ( inner ) ; if ( node != null ) { nodes . add ( node ) ; } } return new VisualFlowPart ( element , nodes ) ; } return new VisualElement ( element ) ; } } package com . asakusafw . compiler . flow ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class JobFlowClass { private JobFlow config ; private FlowGraph graph ; public JobFlowClass ( JobFlow config , FlowGraph graph ) { Precondition . checkMustNotBeNull ( config , "" ) ; Precondition . checkMustNotBeNull ( graph , "" ) ; this . config = config ; this . graph = graph ; } public JobFlow getConfig ( ) { return config ; } public FlowGraph getGraph ( ) { return this . graph ; } } package com . asakusafw . compiler . flow . processor ; import java . util . List ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; import com . asakusafw . vocabulary . operator . CoGroup ; @ TargetOperator ( CoGroup . class ) public class CoGroupFlowProcessor extends RendezvousProcessor { @ Override public void emitRendezvous ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; InputBuffer bufferKind = desc . getAttribute ( InputBuffer . class ) ; assert bufferKind != null ; List < Expression > arguments = Lists . create ( ) ; List < ListBufferMirror > buffers = Lists . create ( ) ; for ( FlowElementPortDescription input : desc . getInputPorts ( ) ) { ListBufferMirror list = context . createListBuffer ( input . getDataType ( ) , bufferKind ) ; buffers . add ( list ) ; context . addBegin ( list . createBegin ( ) ) ; Expression proc = context . getProcessInput ( input ) ; context . addProcess ( input , list . createAdvance ( proc ) ) ; context . addEnd ( list . createEnd ( ) ) ; arguments . add ( list . get ( ) ) ; } for ( FlowElementPortDescription output : desc . getOutputPorts ( ) ) { arguments . add ( context . getOutput ( output ) . get ( ) ) ; } for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } Expression impl = context . createImplementation ( ) ; context . addEnd ( new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toStatement ( ) ) ; for ( ListBufferMirror list : buffers ) { context . addEnd ( list . createShrink ( ) ) ; } } } package com . asakusafw . compiler . flow . processor ; import java . util . List ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . MasterJoinUpdate ; @ TargetOperator ( MasterJoinUpdate . class ) public class MasterJoinUpdateFlowProcessor extends RendezvousProcessor { @ Override public void emitRendezvous ( Context context ) { MasterKindFlowAnalyzer masterAnalyzer = new MasterKindFlowAnalyzer ( context ) ; ModelFactory f = context . getModelFactory ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; FlowElementPortDescription tx = context . getInputPort ( MasterJoinUpdate . ID_INPUT_TRANSACTION ) ; FlowElementPortDescription updatedPort = context . getOutputPort ( MasterJoinUpdate . ID_OUTPUT_UPDATED ) ; FlowElementPortDescription missedPort = context . getOutputPort ( MasterJoinUpdate . ID_OUTPUT_MISSED ) ; ResultMirror updated = context . getOutput ( updatedPort ) ; ResultMirror missed = context . getOutput ( missedPort ) ; Expression impl = context . createImplementation ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( masterAnalyzer . getGetRawMasterExpression ( ) ) ; arguments . add ( context . getProcessInput ( tx ) ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } context . addProcess ( tx , f . newIfStatement ( masterAnalyzer . getHasMasterExpresion ( ) , f . newBlock ( new Statement [ ] { new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toStatement ( ) , updated . createAdd ( context . getProcessInput ( tx ) ) } ) , f . newBlock ( missed . createAdd ( context . getProcessInput ( tx ) ) ) ) ) ; } } package com . asakusafw . compiler . flow . processor ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . operator . Project ; @ TargetOperator ( Project . class ) public class ProjectFlowProcessor extends LinePartProcessor { @ Override public void emitLinePart ( Context context ) { FlowElementPortDescription input = context . getInputPort ( Project . ID_INPUT ) ; FlowElementPortDescription output = context . getOutputPort ( Project . ID_OUTPUT ) ; DataObjectMirror cache = context . createModelCache ( output . getDataType ( ) ) ; context . setOutput ( cache . get ( ) ) ; DataClass sourceType = loadChecked ( input ) ; DataClass sinkType = loadChecked ( output ) ; if ( sourceType == null || sinkType == null ) { return ; } context . add ( cache . createReset ( ) ) ; Expression inputObject = context . getInput ( ) ; Expression outputObject = cache . get ( ) ; for ( DataClass . Property sinkProperty : sinkType . getProperties ( ) ) { Property sourceProperty = sourceType . findProperty ( sinkProperty . getName ( ) ) ; if ( sourceProperty == null ) { getEnvironment ( ) . error ( "" , context . getOperatorDescription ( ) . getName ( ) , sourceType , sinkType , sinkProperty . getName ( ) ) ; } else if ( sourceProperty . getType ( ) . equals ( sinkProperty . getType ( ) ) == false ) { getEnvironment ( ) . error ( "" , context . getOperatorDescription ( ) . getName ( ) , sourceType , sourceProperty . getName ( ) , sinkType , sinkProperty . getName ( ) ) ; } else { context . add ( sinkProperty . createSetter ( outputObject , sourceProperty . createGetter ( inputObject ) ) ) ; } } } private DataClass loadChecked ( FlowElementPortDescription port ) { DataClass resolved = getEnvironment ( ) . getDataClasses ( ) . load ( port . getDataType ( ) ) ; if ( resolved == null ) { getEnvironment ( ) . error ( "" , port . getDataType ( ) ) ; } return resolved ; } } package com . asakusafw . compiler . flow . processor ; import java . util . List ; import java . util . Set ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . runtime . util . TypeUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . operator . MasterJoin ; @ TargetOperator ( MasterJoin . class ) public class MasterJoinFlowProcessor extends RendezvousProcessor { @ Override public void emitRendezvous ( Context context ) { MasterKindFlowAnalyzer masterAnalyzer = new MasterKindFlowAnalyzer ( context ) ; ModelFactory f = context . getModelFactory ( ) ; FlowElementPortDescription tx = context . getInputPort ( MasterJoin . ID_INPUT_TRANSACTION ) ; FlowElementPortDescription joinedPort = context . getOutputPort ( MasterJoin . ID_OUTPUT_JOINED ) ; FlowElementPortDescription missedPort = context . getOutputPort ( MasterJoin . ID_OUTPUT_MISSED ) ; DataObjectMirror resultCache = context . createModelCache ( joinedPort . getDataType ( ) ) ; DataClass outputType = getEnvironment ( ) . getDataClasses ( ) . load ( joinedPort . getDataType ( ) ) ; List < Statement > process = Lists . create ( ) ; process . add ( resultCache . createReset ( ) ) ; Joined annotation = TypeUtil . erase ( joinedPort . getDataType ( ) ) . getAnnotation ( Joined . class ) ; Set < String > saw = Sets . create ( ) ; for ( Joined . Term term : annotation . terms ( ) ) { DataClass inputType = getEnvironment ( ) . getDataClasses ( ) . load ( term . source ( ) ) ; Expression input ; if ( term . source ( ) . equals ( context . getInputPort ( MasterJoin . ID_INPUT_MASTER ) . getDataType ( ) ) ) { input = masterAnalyzer . getGetRawMasterExpression ( ) ; } else { input = context . getProcessInput ( tx ) ; } for ( Joined . Mapping mapping : term . mappings ( ) ) { if ( saw . contains ( mapping . destination ( ) ) ) { continue ; } saw . add ( mapping . destination ( ) ) ; Property sourceProperty = inputType . findProperty ( mapping . source ( ) ) ; Property destinationProperty = outputType . findProperty ( mapping . destination ( ) ) ; process . add ( destinationProperty . createSetter ( resultCache . get ( ) , sourceProperty . createGetter ( input ) ) ) ; } } ResultMirror joined = context . getOutput ( joinedPort ) ; process . add ( joined . createAdd ( resultCache . get ( ) ) ) ; ResultMirror missed = context . getOutput ( missedPort ) ; context . addProcess ( tx , f . newIfStatement ( masterAnalyzer . getHasMasterExpresion ( ) , f . newBlock ( process ) , f . newBlock ( missed . createAdd ( context . getProcessInput ( tx ) ) ) ) ) ; } } package com . asakusafw . compiler . flow . processor ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . operator . Restructure ; @ TargetOperator ( Restructure . class ) public class RestructureFlowProcessor extends LinePartProcessor { @ Override public void emitLinePart ( Context context ) { FlowElementPortDescription input = context . getInputPort ( Restructure . ID_INPUT ) ; FlowElementPortDescription output = context . getOutputPort ( Restructure . ID_OUTPUT ) ; DataObjectMirror cache = context . createModelCache ( output . getDataType ( ) ) ; context . setOutput ( cache . get ( ) ) ; DataClass sourceType = loadChecked ( input ) ; DataClass sinkType = loadChecked ( output ) ; if ( sourceType == null || sinkType == null ) { return ; } context . add ( cache . createReset ( ) ) ; Expression inputObject = context . getInput ( ) ; Expression outputObject = cache . get ( ) ; for ( DataClass . Property sourceProperty : sourceType . getProperties ( ) ) { Property sinkProperty = sinkType . findProperty ( sourceProperty . getName ( ) ) ; if ( sinkProperty == null ) { } else if ( sourceProperty . getType ( ) . equals ( sinkProperty . getType ( ) ) == false ) { getEnvironment ( ) . error ( "" , context . getOperatorDescription ( ) . getName ( ) , sourceType , sourceProperty . getName ( ) , sinkType , sinkProperty . getName ( ) ) ; } else { context . add ( sinkProperty . createSetter ( outputObject , sourceProperty . createGetter ( inputObject ) ) ) ; } } } private DataClass loadChecked ( FlowElementPortDescription port ) { DataClass resolved = getEnvironment ( ) . getDataClasses ( ) . load ( port . getDataType ( ) ) ; if ( resolved == null ) { getEnvironment ( ) . error ( "" , port . getDataType ( ) ) ; } return resolved ; } } package com . asakusafw . compiler . flow . processor ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowElementProcessor . DataObjectMirror ; import com . asakusafw . compiler . flow . FlowElementProcessor . ListBufferMirror ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorHelper ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; public class MasterKindFlowAnalyzer { private Expression hasMasterExpresion ; private Expression getMasterExpression ; private Expression getCheckedMasterExpression ; public MasterKindFlowAnalyzer ( RendezvousProcessor . Context context ) { Precondition . checkMustNotBeNull ( context , "" ) ; OperatorHelper selector = context . getOperatorDescription ( ) . getAttribute ( OperatorHelper . class ) ; if ( selector == null ) { processMasterFirst ( context ) ; } else { processMasterSelection ( context , selector ) ; } } public Expression getHasMasterExpresion ( ) { return hasMasterExpresion ; } public Expression getGetRawMasterExpression ( ) { return getMasterExpression ; } public Expression getGetCheckedMasterExpression ( ) { return getCheckedMasterExpression ; } private void processMasterFirst ( RendezvousProcessor . Context context ) { assert context != null ; ModelFactory f = context . getModelFactory ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; FlowElementPortDescription master = desc . getInputPorts ( ) . get ( ) ; Expression hasMaster = context . createField ( boolean . class , "" ) ; DataObjectMirror masterCache = context . createModelCache ( master . getDataType ( ) ) ; context . addBegin ( new ExpressionBuilder ( f , hasMaster ) . assignFrom ( Models . toLiteral ( f , false ) ) . toStatement ( ) ) ; context . addProcess ( master , f . newIfStatement ( new ExpressionBuilder ( f , hasMaster ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) , f . newBlock ( new Statement [ ] { masterCache . createSet ( context . getProcessInput ( master ) ) , new ExpressionBuilder ( f , hasMaster ) . assignFrom ( Models . toLiteral ( f , true ) ) . toStatement ( ) } ) , null ) ) ; this . hasMasterExpresion = hasMaster ; this . getMasterExpression = masterCache . get ( ) ; this . getCheckedMasterExpression = f . newConditionalExpression ( hasMasterExpresion , getMasterExpression , Models . toNullLiteral ( f ) ) ; } private void processMasterSelection ( RendezvousProcessor . Context context , OperatorHelper selector ) { assert context != null ; assert selector != null ; ModelFactory f = context . getModelFactory ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; FlowElementPortDescription master = desc . getInputPorts ( ) . get ( ) ; FlowElementPortDescription tx = desc . getInputPorts ( ) . get ( ) ; ListBufferMirror list = context . createListBuffer ( master . getDataType ( ) , InputBuffer . EXPAND ) ; context . addBegin ( list . createBegin ( ) ) ; Expression proc = context . getProcessInput ( master ) ; context . addProcess ( master , list . createAdvance ( proc ) ) ; context . addEnd ( list . createEnd ( ) ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( list . get ( ) ) ; arguments . add ( context . getProcessInput ( tx ) ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } assert selector . getParameterTypes ( ) . size ( ) <= arguments . size ( ) ; if ( selector . getParameterTypes ( ) . size ( ) <= arguments . size ( ) ) { arguments = arguments . subList ( , selector . getParameterTypes ( ) . size ( ) ) ; } context . addProcess ( tx , list . createEnd ( ) ) ; Expression impl = context . createImplementation ( ) ; SimpleName selected = context . createName ( "" ) ; context . addProcess ( tx , new ExpressionBuilder ( f , impl ) . method ( selector . getName ( ) , arguments ) . toLocalVariableDeclaration ( context . convert ( master . getDataType ( ) ) , selected ) ) ; context . addEnd ( list . createShrink ( ) ) ; this . hasMasterExpresion = new ExpressionBuilder ( f , selected ) . apply ( InfixOperator . NOT_EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) ; this . getMasterExpression = selected ; this . getCheckedMasterExpression = selected ; } } package com . asakusafw . compiler . flow . processor ; import java . util . List ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Update ; @ TargetOperator ( Update . class ) public class UpdateFlowProcessor extends LinePartProcessor { @ Override public void emitLinePart ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; Expression input = context . getInput ( ) ; Expression impl = context . createImplementation ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( input ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } context . add ( new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toStatement ( ) ) ; context . setOutput ( input ) ; } } package com . asakusafw . compiler . flow . processor ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . operator . MasterCheck ; @ TargetOperator ( MasterCheck . class ) public class MasterCheckFlowProcessor extends RendezvousProcessor { @ Override public void emitRendezvous ( Context context ) { MasterKindFlowAnalyzer masterAnalyzer = new MasterKindFlowAnalyzer ( context ) ; ModelFactory f = context . getModelFactory ( ) ; FlowElementPortDescription tx = context . getInputPort ( MasterCheck . ID_INPUT_TRANSACTION ) ; FlowElementPortDescription foundPort = context . getOutputPort ( MasterCheck . ID_OUTPUT_FOUND ) ; FlowElementPortDescription missedPort = context . getOutputPort ( MasterCheck . ID_OUTPUT_MISSED ) ; ResultMirror found = context . getOutput ( foundPort ) ; ResultMirror missed = context . getOutput ( missedPort ) ; context . addProcess ( tx , f . newIfStatement ( masterAnalyzer . getHasMasterExpresion ( ) , f . newBlock ( found . createAdd ( context . getProcessInput ( tx ) ) ) , f . newBlock ( missed . createAdd ( context . getProcessInput ( tx ) ) ) ) ) ; } } package com . asakusafw . compiler . flow . processor ; import java . util . List ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Convert ; @ TargetOperator ( Convert . class ) public class ConvertFlowProcessor extends LineEndProcessor { @ Override public void emitLineEnd ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; Expression input = context . getInput ( ) ; Expression impl = context . createImplementation ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; FlowElementPortDescription converted = context . getOutputPort ( Convert . ID_OUTPUT_CONVERTED ) ; FlowElementPortDescription original = context . getOutputPort ( Convert . ID_OUTPUT_ORIGINAL ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( input ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } Expression result = context . createLocalVariable ( converted . getDataType ( ) , new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toExpression ( ) ) ; context . add ( context . getOutput ( original ) . createAdd ( input ) ) ; context . add ( context . getOutput ( converted ) . createAdd ( result ) ) ; } } package com . asakusafw . compiler . flow . processor ; import java . util . Map ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . runtime . util . TypeUtil ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Joined . Term ; import com . asakusafw . vocabulary . operator . Split ; @ TargetOperator ( Split . class ) public class SplitFlowProcessor extends LineEndProcessor { @ Override public void emitLineEnd ( Context context ) { FlowElementPortDescription inputPort = context . getInputPort ( Split . ID_INPUT ) ; Joined joined = TypeUtil . erase ( inputPort . getDataType ( ) ) . getAnnotation ( Joined . class ) ; assert joined != null ; Map < Class < ? > , Term > terms = Maps . create ( ) ; for ( Term term : joined . terms ( ) ) { terms . put ( term . source ( ) , term ) ; } for ( FlowElementPortDescription output : context . getOperatorDescription ( ) . getOutputPorts ( ) ) { Term term = terms . get ( output . getDataType ( ) ) ; assert term != null ; emitTerm ( context , term , inputPort , output ) ; } } private void emitTerm ( Context context , Joined . Term term , FlowElementPortDescription inputPort , FlowElementPortDescription outputPort ) { DataClass inputType = getEnvironment ( ) . getDataClasses ( ) . load ( inputPort . getDataType ( ) ) ; DataClass outputType = getEnvironment ( ) . getDataClasses ( ) . load ( outputPort . getDataType ( ) ) ; DataObjectMirror cache = context . createModelCache ( term . source ( ) ) ; context . add ( cache . createReset ( ) ) ; for ( Joined . Mapping mapping : term . mappings ( ) ) { Property source = inputType . findProperty ( mapping . destination ( ) ) ; Property destination = outputType . findProperty ( mapping . source ( ) ) ; context . add ( destination . createSetter ( cache . get ( ) , source . createGetter ( context . getInput ( ) ) ) ) ; } ResultMirror result = context . getOutput ( outputPort ) ; context . add ( result . createAdd ( cache . get ( ) ) ) ; } } package com . asakusafw . compiler . flow . processor ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . compiler . flow . ShuffleDescription ; import com . asakusafw . runtime . util . TypeUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . flow . processor . PartialAggregation ; import com . asakusafw . vocabulary . model . Summarized ; import com . asakusafw . vocabulary . model . Summarized . Aggregator ; import com . asakusafw . vocabulary . operator . Summarize ; @ TargetOperator ( Summarize . class ) public class SummarizeFlowProcessor extends RendezvousProcessor { @ Override public ShuffleDescription getShuffleDescription ( FlowElementDescription element , FlowElementPortDescription port ) { FlowElementPortDescription output = element . getOutputPorts ( ) . get ( Summarize . ID_OUTPUT ) ; LinePartProcessor line = new Prologue ( port . getDataType ( ) , output . getDataType ( ) ) ; line . initialize ( getEnvironment ( ) ) ; return new ShuffleDescription ( output . getDataType ( ) , rebuildShuffleKey ( output , port ) , line ) ; } private ShuffleKey rebuildShuffleKey ( FlowElementPortDescription output , FlowElementPortDescription input ) { assert output != null ; assert input != null ; Summarized summarized = TypeUtil . erase ( output . getDataType ( ) ) . getAnnotation ( Summarized . class ) ; if ( summarized == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , Summarized . class . getSimpleName ( ) , output . getDataType ( ) , output ) ) ; } Map < String , String > mapping = Maps . create ( ) ; for ( Summarized . Folding folding : summarized . term ( ) . foldings ( ) ) { if ( folding . aggregator ( ) == Aggregator . ANY ) { mapping . put ( folding . source ( ) , folding . destination ( ) ) ; } } List < String > remapped = Lists . create ( ) ; for ( String original : input . getShuffleKey ( ) . getGroupProperties ( ) ) { String target = mapping . get ( original ) ; if ( target == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , output . getDataType ( ) , input . getShuffleKey ( ) , mapping ) ) ; } remapped . add ( target ) ; } return new ShuffleKey ( remapped , Collections . < ShuffleKey . Order > emptyList ( ) ) ; } @ Override public void emitRendezvous ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; FlowElementPortDescription input = context . getInputPort ( Summarize . ID_INPUT ) ; FlowElementPortDescription output = context . getOutputPort ( Summarize . ID_OUTPUT ) ; Expression init = context . createField ( boolean . class , "" ) ; context . addBegin ( new ExpressionBuilder ( f , init ) . assignFrom ( Models . toLiteral ( f , false ) ) . toStatement ( ) ) ; DataObjectMirror cache = context . createModelCache ( output . getDataType ( ) ) ; List < Statement > combine = Lists . create ( ) ; DataClass outputType = getEnvironment ( ) . getDataClasses ( ) . load ( output . getDataType ( ) ) ; Summarized summarized = TypeUtil . erase ( output . getDataType ( ) ) . getAnnotation ( Summarized . class ) ; for ( Summarized . Folding folding : summarized . term ( ) . foldings ( ) ) { if ( folding . aggregator ( ) == Aggregator . ANY ) { continue ; } combine . add ( createAddSummarizeFor ( context , folding , outputType , cache . get ( ) ) ) ; } context . addProcess ( input , f . newIfStatement ( init , f . newBlock ( combine ) , f . newBlock ( cache . createSet ( context . getProcessInput ( input ) ) , new ExpressionBuilder ( f , init ) . assignFrom ( Models . toLiteral ( f , true ) ) . toStatement ( ) ) ) ) ; ResultMirror result = context . getOutput ( output ) ; context . addEnd ( result . createAdd ( cache . get ( ) ) ) ; } private Statement createAddSummarizeFor ( Context context , Summarized . Folding folding , DataClass summarizing , Expression outputCache ) { assert context != null ; assert folding != null ; assert summarizing != null ; assert outputCache != null ; Property property = summarizing . findProperty ( folding . destination ( ) ) ; Expression input = context . getProcessInput ( context . getInputPort ( Summarize . ID_INPUT ) ) ; ModelFactory f = context . getModelFactory ( ) ; switch ( folding . aggregator ( ) ) { case MAX : return new ExpressionBuilder ( f , property . createGetter ( outputCache ) ) . method ( "" , property . createGetter ( input ) ) . toStatement ( ) ; case MIN : return new ExpressionBuilder ( f , property . createGetter ( outputCache ) ) . method ( "" , property . createGetter ( input ) ) . toStatement ( ) ; case SUM : case COUNT : return new ExpressionBuilder ( f , property . createGetter ( outputCache ) ) . method ( "" , property . createGetter ( input ) ) . toStatement ( ) ; default : throw new AssertionError ( ) ; } } @ Override public boolean isPartial ( FlowElementDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; PartialAggregation partial = description . getAttribute ( PartialAggregation . class ) ; if ( partial == PartialAggregation . PARTIAL ) { return true ; } else if ( partial == PartialAggregation . TOTAL ) { return false ; } return getEnvironment ( ) . getOptions ( ) . isEnableCombiner ( ) ; } static class Prologue extends LinePartProcessor { private final Type inputType ; private final Type outputType ; Prologue ( Type inputType , Type outputType ) { assert inputType != null ; assert outputType != null ; this . inputType = inputType ; this . outputType = outputType ; } @ Override public void emitLinePart ( Context context ) { Summarized summarized = TypeUtil . erase ( outputType ) . getAnnotation ( Summarized . class ) ; DataObjectMirror cache = context . createModelCache ( outputType ) ; DataClass inputData = getEnvironment ( ) . getDataClasses ( ) . load ( inputType ) ; DataClass outputData = getEnvironment ( ) . getDataClasses ( ) . load ( outputType ) ; for ( Summarized . Folding folding : summarized . term ( ) . foldings ( ) ) { context . add ( createStartSummarizeFor ( context , folding , inputData , outputData , cache . get ( ) ) ) ; } context . setOutput ( cache . get ( ) ) ; } private Statement createStartSummarizeFor ( Context context , Summarized . Folding folding , DataClass input , DataClass output , Expression outputCache ) { Property source = input . findProperty ( folding . source ( ) ) ; Property destination = output . findProperty ( folding . destination ( ) ) ; ModelFactory f = context . getModelFactory ( ) ; switch ( folding . aggregator ( ) ) { case ANY : return destination . createSetter ( outputCache , source . createGetter ( context . getInput ( ) ) ) ; case MAX : case MIN : case SUM : return new ExpressionBuilder ( f , destination . createGetter ( outputCache ) ) . method ( "" , new ExpressionBuilder ( f , source . createGetter ( context . getInput ( ) ) ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ; case COUNT : return new ExpressionBuilder ( f , destination . createGetter ( outputCache ) ) . method ( "" , Models . toLiteral ( f , ) ) . toStatement ( ) ; default : throw new AssertionError ( ) ; } } } } package com . asakusafw . compiler . flow . processor ; package com . asakusafw . compiler . flow . processor ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . processor . PartialAggregation ; import com . asakusafw . vocabulary . operator . Fold ; @ TargetOperator ( Fold . class ) public class FoldFlowProcessor extends RendezvousProcessor { @ Override public void emitRendezvous ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; FlowElementPortDescription input = context . getInputPort ( Fold . ID_INPUT ) ; FlowElementPortDescription output = context . getOutputPort ( Fold . ID_OUTPUT ) ; Expression init = context . createField ( boolean . class , "" ) ; context . addBegin ( new ExpressionBuilder ( f , init ) . assignFrom ( Models . toLiteral ( f , false ) ) . toStatement ( ) ) ; DataObjectMirror cache = context . createModelCache ( output . getDataType ( ) ) ; Expression impl = context . createImplementation ( ) ; Expression proc = context . getProcessInput ( input ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( cache . get ( ) ) ; arguments . add ( proc ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } context . addProcess ( input , f . newIfStatement ( init , f . newBlock ( new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toStatement ( ) ) , f . newBlock ( cache . createSet ( proc ) , new ExpressionBuilder ( f , init ) . assignFrom ( Models . toLiteral ( f , true ) ) . toStatement ( ) ) ) ) ; ResultMirror result = context . getOutput ( context . getOutputPort ( Fold . ID_OUTPUT ) ) ; context . addEnd ( result . createAdd ( cache . get ( ) ) ) ; } @ Override public boolean isPartial ( FlowElementDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; PartialAggregation partial = description . getAttribute ( PartialAggregation . class ) ; if ( partial == PartialAggregation . PARTIAL ) { return true ; } else if ( partial == PartialAggregation . TOTAL ) { return false ; } return getEnvironment ( ) . getOptions ( ) . isEnableCombiner ( ) ; } } package com . asakusafw . compiler . flow . processor ; import java . lang . reflect . Method ; import java . util . List ; import com . asakusafw . compiler . common . EnumUtil ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . RendezvousProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Tuple2 ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . MasterBranch ; @ TargetOperator ( MasterBranch . class ) public class MasterBranchFlowProcessor extends RendezvousProcessor { @ Override public void emitRendezvous ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; MasterKindFlowAnalyzer masterAnalyzer = new MasterKindFlowAnalyzer ( context ) ; FlowElementPortDescription tx = context . getInputPort ( MasterBranch . ID_INPUT_TRANSACTION ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( masterAnalyzer . getGetCheckedMasterExpression ( ) ) ; arguments . add ( context . getProcessInput ( tx ) ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } Method method = desc . getDeclaration ( ) . toMethod ( ) ; assert method != null : desc . getDeclaration ( ) ; Class < ? > enumType = method . getReturnType ( ) ; List < Tuple2 < Enum < ? > , FlowElementPortDescription > > constants = EnumUtil . extractConstants ( enumType , desc . getOutputPorts ( ) ) ; Expression impl = context . createImplementation ( ) ; SimpleName branch = context . createName ( "" ) ; context . addProcess ( tx , new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toLocalVariableDeclaration ( context . convert ( enumType ) , branch ) ) ; List < Statement > cases = Lists . create ( ) ; for ( Tuple2 < Enum < ? > , FlowElementPortDescription > tuple : constants ) { Enum < ? > constant = tuple . first ; FlowElementPortDescription port = tuple . second ; ResultMirror next = context . getOutput ( port ) ; cases . add ( f . newSwitchCaseLabel ( f . newSimpleName ( constant . name ( ) ) ) ) ; cases . add ( next . createAdd ( context . getProcessInput ( tx ) ) ) ; cases . add ( f . newBreakStatement ( ) ) ; } cases . add ( f . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( f , context . convert ( AssertionError . class ) ) . newObject ( branch ) . toThrowStatement ( ) ) ; context . addProcess ( tx , f . newSwitchStatement ( branch , cases ) ) ; } } package com . asakusafw . compiler . flow . processor ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . operator . Extend ; @ TargetOperator ( Extend . class ) public class ExtendFlowProcessor extends LinePartProcessor { @ Override public void emitLinePart ( Context context ) { FlowElementPortDescription input = context . getInputPort ( Extend . ID_INPUT ) ; FlowElementPortDescription output = context . getOutputPort ( Extend . ID_OUTPUT ) ; DataObjectMirror cache = context . createModelCache ( output . getDataType ( ) ) ; context . setOutput ( cache . get ( ) ) ; DataClass sourceType = loadChecked ( input ) ; DataClass sinkType = loadChecked ( output ) ; if ( sourceType == null || sinkType == null ) { return ; } context . add ( cache . createReset ( ) ) ; Expression inputObject = context . getInput ( ) ; Expression outputObject = cache . get ( ) ; for ( DataClass . Property sourceProperty : sourceType . getProperties ( ) ) { Property sinkProperty = sinkType . findProperty ( sourceProperty . getName ( ) ) ; if ( sinkProperty == null ) { getEnvironment ( ) . error ( "" , context . getOperatorDescription ( ) . getName ( ) , sinkType , sourceType , sourceProperty . getName ( ) ) ; } else if ( sourceProperty . getType ( ) . equals ( sinkProperty . getType ( ) ) == false ) { getEnvironment ( ) . error ( "" , context . getOperatorDescription ( ) . getName ( ) , sourceType , sourceProperty . getName ( ) , sinkType , sinkProperty . getName ( ) ) ; } else { context . add ( sinkProperty . createSetter ( outputObject , sourceProperty . createGetter ( inputObject ) ) ) ; } } } private DataClass loadChecked ( FlowElementPortDescription port ) { DataClass resolved = getEnvironment ( ) . getDataClasses ( ) . load ( port . getDataType ( ) ) ; if ( resolved == null ) { getEnvironment ( ) . error ( "" , port . getDataType ( ) ) ; } return resolved ; } } package com . asakusafw . compiler . flow . processor ; import java . lang . reflect . Method ; import java . util . List ; import com . asakusafw . compiler . common . EnumUtil ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Tuple2 ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Branch ; import com . asakusafw . vocabulary . operator . Update ; @ TargetOperator ( Branch . class ) public class BranchFlowProcessor extends LineEndProcessor { @ Override public void emitLineEnd ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; Expression input = context . getInput ( ) ; Expression impl = context . createImplementation ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; Method method = desc . getDeclaration ( ) . toMethod ( ) ; assert method != null : desc . getDeclaration ( ) ; Class < ? > enumType = method . getReturnType ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( input ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } Expression result = context . createLocalVariable ( enumType , new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toExpression ( ) ) ; List < Tuple2 < Enum < ? > , FlowElementPortDescription > > constants = EnumUtil . extractConstants ( enumType , desc . getOutputPorts ( ) ) ; List < Statement > cases = Lists . create ( ) ; for ( Tuple2 < Enum < ? > , FlowElementPortDescription > tuple : constants ) { Enum < ? > constant = tuple . first ; FlowElementPortDescription port = tuple . second ; ResultMirror next = context . getOutput ( port ) ; cases . add ( f . newSwitchCaseLabel ( f . newSimpleName ( constant . name ( ) ) ) ) ; cases . add ( next . createAdd ( input ) ) ; cases . add ( f . newBreakStatement ( ) ) ; } cases . add ( f . newSwitchDefaultLabel ( ) ) ; cases . add ( new TypeBuilder ( f , context . convert ( AssertionError . class ) ) . newObject ( result ) . toThrowStatement ( ) ) ; context . add ( f . newSwitchStatement ( result , cases ) ) ; } } package com . asakusafw . compiler . flow . processor ; import java . util . List ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LinePartProcessor ; import com . asakusafw . runtime . core . Report ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Logging ; import com . asakusafw . vocabulary . operator . Logging . Level ; @ TargetOperator ( Logging . class ) public class LoggingFlowProcessor extends LinePartProcessor { @ Override public void emitLinePart ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; Expression input = context . getInput ( ) ; Expression impl = context . createImplementation ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( input ) ; for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } Expression result = context . createLocalVariable ( String . class , new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toExpression ( ) ) ; Level level = context . getOperatorDescription ( ) . getAttribute ( Logging . Level . class ) ; switch ( level == null ? Level . getDefault ( ) : level ) { case WARN : context . add ( new TypeBuilder ( f , context . convert ( Report . class ) ) . method ( "" , result ) . toStatement ( ) ) ; break ; case ERROR : context . add ( new TypeBuilder ( f , context . convert ( Report . class ) ) . method ( "" , result ) . toStatement ( ) ) ; break ; default : context . add ( new TypeBuilder ( f , context . convert ( Report . class ) ) . method ( "" , result ) . toStatement ( ) ) ; break ; } context . setOutput ( input ) ; } } package com . asakusafw . compiler . flow . processor ; import java . util . List ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . flow . LineEndProcessor ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Extract ; @ TargetOperator ( Extract . class ) public class ExtractFlowProcessor extends LineEndProcessor { @ Override public void emitLineEnd ( Context context ) { ModelFactory f = context . getModelFactory ( ) ; Expression input = context . getInput ( ) ; Expression impl = context . createImplementation ( ) ; OperatorDescription desc = context . getOperatorDescription ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( input ) ; for ( FlowElementPortDescription output : desc . getOutputPorts ( ) ) { arguments . add ( context . getOutput ( output ) . get ( ) ) ; } for ( OperatorDescription . Parameter param : desc . getParameters ( ) ) { arguments . add ( Models . toLiteral ( f , param . getValue ( ) ) ) ; } context . add ( new ExpressionBuilder ( f , impl ) . method ( desc . getDeclaration ( ) . getName ( ) , arguments ) . toStatement ( ) ) ; } } package com . asakusafw . compiler . flow ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . List ; import java . util . Properties ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . external . ExternalIoAnalyzer ; import com . asakusafw . compiler . flow . jobflow . JobflowCompiler ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . plan . StagePlanner ; import com . asakusafw . compiler . flow . stage . StageCompiler ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . visualizer . FlowVisualizer ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class FlowCompiler { private final FlowCompilerConfiguration configuration ; private final FlowCompilingEnvironment environment ; public FlowCompiler ( FlowCompilerConfiguration configuration ) { Precondition . checkMustNotBeNull ( configuration , "" ) ; this . configuration = configuration ; this . environment = createEnvironment ( ) ; } public String getTargetFlowId ( ) { return configuration . getFlowId ( ) ; } public JobflowModel compile ( FlowGraph graph ) throws IOException { Precondition . checkMustNotBeNull ( graph , "" ) ; validate ( graph ) ; StageGraph stageGraph = plan ( graph ) ; visualize ( graph , stageGraph ) ; List < StageModel > stages = compileStages ( stageGraph ) ; JobflowModel jobflow = compileJobflow ( stageGraph , stages ) ; addApplicationInfo ( ) ; return jobflow ; } public void buildSources ( File output ) throws IOException { Precondition . checkMustNotBeNull ( output , "" ) ; OutputStream stream = open ( output ) ; try { buildSources ( stream ) ; } finally { stream . close ( ) ; } } public void collectSources ( File output ) throws IOException { Precondition . checkMustNotBeNull ( output , "" ) ; OutputStream stream = open ( output ) ; try { collectSources ( stream ) ; } finally { stream . close ( ) ; } } private OutputStream open ( File file ) throws IOException { assert file != null ; if ( file . exists ( ) == false ) { File parent = file . getParentFile ( ) ; assert parent != null ; if ( parent . isDirectory ( ) == false && parent . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , file ) ) ; } } return new FileOutputStream ( file ) ; } public void buildSources ( OutputStream output ) throws IOException { Precondition . checkMustNotBeNull ( output , "" ) ; configuration . getPackager ( ) . build ( output ) ; } public void collectSources ( OutputStream output ) throws IOException { Precondition . checkMustNotBeNull ( output , "" ) ; configuration . getPackager ( ) . packageSources ( output ) ; } private FlowCompilingEnvironment createEnvironment ( ) { assert configuration != null ; FlowCompilingEnvironment result = new FlowCompilingEnvironment ( configuration ) ; result . bless ( ) ; return result ; } private void validate ( FlowGraph graph ) throws IOException { assert graph != null ; ExternalIoAnalyzer analyzer = new ExternalIoAnalyzer ( environment ) ; if ( analyzer . validate ( graph ) == false ) { throw new IOException ( MessageFormat . format ( "" , environment . getErrorMessage ( ) ) ) ; } } private StageGraph plan ( FlowGraph flowGraph ) throws IOException { assert flowGraph != null ; StagePlanner planner = new StagePlanner ( configuration . getGraphRewriters ( ) . getRewriters ( ) , configuration . getOptions ( ) ) ; StageGraph plan = planner . plan ( flowGraph ) ; if ( plan == null ) { throw new IOException ( MessageFormat . format ( "" , planner . getDiagnostics ( ) ) ) ; } return plan ; } private void visualize ( FlowGraph flowGraph , StageGraph stageGraph ) throws IOException { assert flowGraph != null ; assert stageGraph != null ; FlowVisualizer visualizer = new FlowVisualizer ( environment ) ; visualizer . visualize ( flowGraph ) ; visualizer . visualize ( stageGraph ) ; for ( StageBlock stage : stageGraph . getStages ( ) ) { visualizer . visualize ( stage ) ; } } private void addApplicationInfo ( ) throws IOException { Properties properties = new Properties ( ) ; properties . put ( RuntimeContext . KEY_BATCH_ID , environment . getBatchId ( ) ) ; properties . put ( RuntimeContext . KEY_FLOW_ID , environment . getFlowId ( ) ) ; properties . put ( RuntimeContext . KEY_BUILD_ID , environment . getBuildId ( ) ) ; properties . put ( RuntimeContext . KEY_BUILD_DATE , new SimpleDateFormat ( "" ) . format ( new Date ( ) ) ) ; properties . put ( RuntimeContext . KEY_RUNTIME_VERSION , RuntimeContext . getRuntimeVersion ( ) ) ; OutputStream output = environment . openResource ( null , RuntimeContext . PATH_APPLICATION_INFO ) ; try { properties . store ( output , "" ) ; } finally { output . close ( ) ; } } private List < StageModel > compileStages ( StageGraph stageGraph ) throws IOException { assert stageGraph != null ; StageCompiler compiler = new StageCompiler ( environment ) ; return compiler . compile ( stageGraph ) ; } private JobflowModel compileJobflow ( StageGraph stageGraph , List < StageModel > model ) throws IOException { assert stageGraph != null ; assert model != null ; JobflowCompiler compiler = new JobflowCompiler ( environment ) ; return compiler . compile ( stageGraph , model ) ; } } package com . asakusafw . compiler . flow . mapreduce . copy ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . CompiledType ; import com . asakusafw . runtime . stage . preparator . PreparatorMapper ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; final class CopierMapperEmitter { static final Logger LOG = LoggerFactory . getLogger ( CopierMapperEmitter . class ) ; private final FlowCompilingEnvironment environment ; public CopierMapperEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledType emit ( String moduleId , CopyDescription slot , boolean prologue ) throws IOException { Precondition . checkMustNotBeNull ( moduleId , "" ) ; Precondition . checkMustNotBeNull ( slot , "" ) ; LOG . debug ( "" , slot . getName ( ) , moduleId ) ; CompilationUnit source ; Engine engine = new Engine ( environment , moduleId , slot , prologue ) ; source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , slot . getName ( ) , name ) ; return new CompiledType ( name ) ; } private static class Engine { private final CopyDescription slot ; private final ModelFactory factory ; private final ImportBuilder importer ; Engine ( FlowCompilingEnvironment envinronment , String moduleId , CopyDescription slot , boolean prologue ) { assert envinronment != null ; assert moduleId != null ; assert slot != null ; this . slot = slot ; this . factory = envinronment . getModelFactory ( ) ; Name packageName = Models . append ( factory , prologue ? envinronment . getProloguePackageName ( moduleId ) : envinronment . getEpiloguePackageName ( moduleId ) , JavaName . of ( slot . getName ( ) ) . toMemberName ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getMapClass ( ) ) ; importer . resolvePackageMember ( name ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . text ( "" , slot . getName ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , factory . newParameterizedType ( importer . toType ( PreparatorMapper . class ) , importer . toType ( slot . getDataModel ( ) . getType ( ) ) ) , Collections . < Type > emptyList ( ) , Collections . singletonList ( createOutputName ( ) ) ) ; } private MethodDeclaration createOutputName ( ) { List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , Models . toLiteral ( factory , slot . getName ( ) ) ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( importer . toType ( Override . class ) ) . Public ( ) . toAttributes ( ) , importer . toType ( String . class ) , factory . newSimpleName ( PreparatorMapper . NAME_GET_OUTPUT_NAME ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } } } package com . asakusafw . compiler . flow . mapreduce . copy ; package com . asakusafw . compiler . flow . mapreduce . copy ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . io . NullWritable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . stage . CompiledType ; import com . asakusafw . runtime . stage . AbstractStageClient ; import com . asakusafw . runtime . stage . BaseStageClient ; import com . asakusafw . runtime . stage . StageInput ; import com . asakusafw . runtime . stage . StageOutput ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class CopierClientEmitter { static final Logger LOG = LoggerFactory . getLogger ( CopierClientEmitter . class ) ; private final FlowCompilingEnvironment environment ; public CopierClientEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledStage emitPrologue ( String moduleId , List < CopyDescription > slots , Location outputDirectory ) throws IOException { return emit ( moduleId , slots , outputDirectory , true ) ; } public CompiledStage emitEpilogue ( String moduleId , List < CopyDescription > slots , Location outputDirectory ) throws IOException { return emit ( moduleId , slots , outputDirectory , false ) ; } private CompiledStage emit ( String moduleId , List < CopyDescription > slots , Location outputDirectory , boolean prologue ) throws IOException { Precondition . checkMustNotBeNull ( moduleId , "" ) ; Precondition . checkMustNotBeNull ( slots , "" ) ; Precondition . checkMustNotBeNull ( outputDirectory , "" ) ; LOG . debug ( "" , moduleId , prologue ? "" : "" ) ; Engine engine = new Engine ( environment , moduleId , slots , outputDirectory , prologue ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , moduleId , name ) ; return new CompiledStage ( name , prologue ? Naming . getPrologueName ( moduleId ) : Naming . getEpilogueName ( moduleId ) ) ; } private static class Engine { private static final char PATH_SEPARATOR = '' ; private final FlowCompilingEnvironment environment ; private final String moduleId ; private final List < CopyDescription > slots ; private final Location outputDirectory ; private final ModelFactory factory ; private final ImportBuilder importer ; private final boolean prologue ; Engine ( FlowCompilingEnvironment environment , String moduleId , List < CopyDescription > slots , Location outputDirectory , boolean prologue ) { assert environment != null ; assert moduleId != null ; assert slots != null ; this . environment = environment ; this . moduleId = moduleId ; this . slots = slots ; this . outputDirectory = outputDirectory ; this . prologue = prologue ; this . factory = environment . getModelFactory ( ) ; Name packageName = prologue ? environment . getProloguePackageName ( moduleId ) : environment . getEpiloguePackageName ( moduleId ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) throws IOException { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) throws IOException { SimpleName name = factory . newSimpleName ( Naming . getClientClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createIdMethods ( ) ) ; members . add ( createStageOutputPath ( ) ) ; members . add ( createStageInputsMethod ( ) ) ; members . add ( createStageOutputsMethod ( ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( AbstractStageClient . class ) , Collections . < Type > emptyList ( ) , members ) ; } private List < MethodDeclaration > createIdMethods ( ) { List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_BATCH_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getBatchId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_FLOW_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getFlowId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_STAGE_ID , t ( String . class ) , Models . toLiteral ( factory , prologue ? Naming . getPrologueName ( moduleId ) : Naming . getEpilogueName ( moduleId ) ) ) ) ; return results ; } private MethodDeclaration createStageOutputPath ( ) { return createValueMethod ( AbstractStageClient . METHOD_STAGE_OUTPUT_PATH , t ( String . class ) , Models . toLiteral ( factory , outputDirectory . toPath ( PATH_SEPARATOR ) ) ) ; } private MethodDeclaration createStageInputsMethod ( ) throws IOException { SimpleName list = factory . newSimpleName ( "" ) ; SimpleName attributes = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageInput . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageInput . class ) ) , list ) ) ; statements . add ( new ExpressionBuilder ( factory , Models . toNullLiteral ( factory ) ) . toLocalVariableDeclaration ( t ( Map . class , t ( String . class ) , t ( String . class ) ) , attributes ) ) ; for ( CopyDescription slot : slots ) { SourceInfo info = slot . getInput ( ) ; Type mapperType = generateMapper ( slot ) ; Type formatClass = t ( info . getFormat ( ) ) ; statements . add ( new ExpressionBuilder ( factory , attributes ) . assignFrom ( new TypeBuilder ( factory , t ( HashMap . class , t ( String . class ) , t ( String . class ) ) ) . newObject ( ) . toExpression ( ) ) . toStatement ( ) ) ; for ( Map . Entry < String , String > entry : info . getAttributes ( ) . entrySet ( ) ) { statements . add ( new ExpressionBuilder ( factory , attributes ) . method ( "" , Models . toLiteral ( factory , entry . getKey ( ) ) , Models . toLiteral ( factory , entry . getValue ( ) ) ) . toStatement ( ) ) ; } for ( Location input : info . getLocations ( ) ) { statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageInput . class ) ) . newObject ( Models . toLiteral ( factory , input . toPath ( PATH_SEPARATOR ) ) , factory . newClassLiteral ( formatClass ) , factory . newClassLiteral ( mapperType ) , attributes ) . toExpression ( ) ) . toStatement ( ) ) ; } } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageInput . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_INPUTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createStageOutputsMethod ( ) { SimpleName list = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageOutput . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageOutput . class ) ) , list ) ) ; for ( CopyDescription slot : slots ) { Expression valueType = factory . newClassLiteral ( t ( slot . getDataModel ( ) . getType ( ) ) ) ; statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageOutput . class ) ) . newObject ( Models . toLiteral ( factory , slot . getName ( ) ) , factory . newClassLiteral ( t ( NullWritable . class ) ) , valueType , factory . newClassLiteral ( t ( slot . getOutputFormatType ( ) ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageOutput . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_OUTPUTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private Type generateMapper ( CopyDescription slot ) throws IOException { assert slot != null ; CopierMapperEmitter sub = new CopierMapperEmitter ( environment ) ; CompiledType type = sub . emit ( moduleId , slot , prologue ) ; return importer . toType ( type . getQualifiedName ( ) ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , moduleId ) . toJavadoc ( ) ; } private MethodDeclaration createValueMethod ( String methodName , Type returnType , Expression expression ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , returnType , factory . newSimpleName ( methodName ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( factory . newReturnStatement ( expression ) ) ) ; } private Type t ( java . lang . reflect . Type type , Type ... typeArgs ) { assert type != null ; assert typeArgs != null ; Type raw = importer . toType ( type ) ; if ( typeArgs . length == ) { return raw ; } return factory . newParameterizedType ( raw , Arrays . asList ( typeArgs ) ) ; } } } package com . asakusafw . compiler . flow . mapreduce . copy ; import org . apache . hadoop . mapreduce . OutputFormat ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; public class CopyDescription { private final String name ; private final DataClass dataModel ; private final SourceInfo input ; @ SuppressWarnings ( "" ) private final Class < ? extends OutputFormat > outputFormatType ; @ SuppressWarnings ( "" ) public CopyDescription ( String name , DataClass dataModel , SourceInfo input , Class < ? extends OutputFormat > outputFormatType ) { Precondition . checkMustNotBeNull ( name , "" ) ; Precondition . checkMustNotBeNull ( input , "" ) ; Precondition . checkMustNotBeNull ( dataModel , "" ) ; Precondition . checkMustNotBeNull ( outputFormatType , "" ) ; this . name = name ; this . dataModel = dataModel ; this . input = input ; this . outputFormatType = outputFormatType ; } public String getName ( ) { return name ; } public SourceInfo getInput ( ) { return input ; } public DataClass getDataModel ( ) { return dataModel ; } @ SuppressWarnings ( "" ) public Class < ? extends OutputFormat > getOutputFormatType ( ) { return outputFormatType ; } } package com . asakusafw . compiler . flow . mapreduce . parallel ; package com . asakusafw . compiler . flow . mapreduce . parallel ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; public class ResolvedSlot { private Slot source ; private int slotNumber ; private DataClass valueClass ; private List < Property > sortProperties ; public ResolvedSlot ( Slot source , int slotNumber , DataClass valueClass , List < Property > sortProperties ) { Precondition . checkMustNotBeNull ( source , "" ) ; Precondition . checkMustNotBeNull ( valueClass , "" ) ; Precondition . checkMustNotBeNull ( sortProperties , "" ) ; this . source = source ; this . slotNumber = slotNumber ; this . valueClass = valueClass ; this . sortProperties = sortProperties ; } public Slot getSource ( ) { return source ; } public int getSlotNumber ( ) { return slotNumber ; } public DataClass getValueClass ( ) { return valueClass ; } public List < DataClass . Property > getSortProperties ( ) { return sortProperties ; } } package com . asakusafw . compiler . flow . mapreduce . parallel ; import java . lang . reflect . Type ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; public class Slot { private final String outputName ; private final Type type ; private final List < String > propertyNames ; private final List < SourceInfo > inputs ; private final Class < ? > outputFormatType ; public Slot ( String outputName , Type type , List < String > propertyNames , List < SourceInfo > inputs , Class < ? > outputFormatType ) { Precondition . checkMustNotBeNull ( outputName , "" ) ; Precondition . checkMustNotBeNull ( type , "" ) ; Precondition . checkMustNotBeNull ( propertyNames , "" ) ; Precondition . checkMustNotBeNull ( inputs , "" ) ; Precondition . checkMustNotBeNull ( outputFormatType , "" ) ; this . outputName = outputName ; this . type = type ; this . propertyNames = propertyNames ; this . inputs = inputs ; this . outputFormatType = outputFormatType ; } public String getOutputName ( ) { return outputName ; } public Type getType ( ) { return type ; } public List < String > getSortPropertyNames ( ) { return propertyNames ; } public List < SourceInfo > getInputs ( ) { return inputs ; } public Class < ? > getOutputFormatType ( ) { return outputFormatType ; } } package com . asakusafw . compiler . flow . mapreduce . parallel ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . Writable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . CompiledType ; import com . asakusafw . runtime . stage . collector . SlotSorter ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; final class ParallelSortReducerEmitter { static final Logger LOG = LoggerFactory . getLogger ( ParallelSortReducerEmitter . class ) ; private final FlowCompilingEnvironment environment ; public ParallelSortReducerEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledType emit ( String moduleId , List < ResolvedSlot > slots ) throws IOException { LOG . debug ( "" , moduleId ) ; Engine engine = new Engine ( environment , moduleId , slots ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , name ) ; return new CompiledType ( name ) ; } private static class Engine { private final List < ResolvedSlot > slots ; private final FlowCompilingEnvironment environment ; private final ModelFactory factory ; private final ImportBuilder importer ; Engine ( FlowCompilingEnvironment envinronment , String moduleId , List < ResolvedSlot > slots ) { assert envinronment != null ; assert moduleId != null ; assert slots != null ; this . slots = slots ; this . environment = envinronment ; this . factory = envinronment . getModelFactory ( ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( envinronment . getEpiloguePackageName ( moduleId ) ) , Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getReduceClass ( ) ) ; importer . resolvePackageMember ( name ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , importer . toType ( SlotSorter . class ) , Collections . < Type > emptyList ( ) , Arrays . asList ( createSlotNames ( ) , createSlotObjects ( ) ) ) ; } private MethodDeclaration createSlotNames ( ) { SimpleName resultName = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , importer . toType ( String . class ) ) . array ( ) . newArray ( getSlotCount ( ) ) . toLocalVariableDeclaration ( importer . toType ( String [ ] . class ) , resultName ) ) ; for ( ResolvedSlot slot : slots ) { Expression outputName ; if ( slot . getSortProperties ( ) . isEmpty ( ) && ParallelSortClientEmitter . legacy ( environment ) == false ) { outputName = Models . toNullLiteral ( factory ) ; } else { outputName = Models . toLiteral ( factory , slot . getSource ( ) . getOutputName ( ) ) ; } statements . add ( new ExpressionBuilder ( factory , resultName ) . array ( slot . getSlotNumber ( ) ) . assignFrom ( outputName ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( factory , resultName ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( importer . toType ( Override . class ) ) . Protected ( ) . toAttributes ( ) , importer . toType ( String [ ] . class ) , factory . newSimpleName ( SlotSorter . NAME_GET_OUTPUT_NAMES ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createSlotObjects ( ) { SimpleName resultName = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , importer . toType ( Writable . class ) ) . array ( ) . newArray ( getSlotCount ( ) ) . toLocalVariableDeclaration ( importer . toType ( Writable [ ] . class ) , resultName ) ) ; for ( ResolvedSlot slot : slots ) { Expression object ; if ( slot . getSortProperties ( ) . isEmpty ( ) && ParallelSortClientEmitter . legacy ( environment ) == false ) { object = Models . toNullLiteral ( factory ) ; } else { DataClass slotClass = slot . getValueClass ( ) ; object = slotClass . createNewInstance ( importer . toType ( slotClass . getType ( ) ) ) ; } statements . add ( new ExpressionBuilder ( factory , resultName ) . array ( slot . getSlotNumber ( ) ) . assignFrom ( object ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( factory , resultName ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( importer . toType ( Override . class ) ) . Protected ( ) . toAttributes ( ) , importer . toType ( Writable [ ] . class ) , factory . newSimpleName ( SlotSorter . NAME_CREATE_SLOT_OBJECTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private int getSlotCount ( ) { int max = ; for ( ResolvedSlot slot : slots ) { max = Math . max ( max , slot . getSlotNumber ( ) + ) ; } return max ; } } } package com . asakusafw . compiler . flow . mapreduce . parallel ; import java . util . List ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . utils . collections . Lists ; public class SlotResolver { private FlowCompilingEnvironment environment ; public SlotResolver ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public List < ResolvedSlot > resolve ( List < Slot > slots ) { Precondition . checkMustNotBeNull ( slots , "" ) ; List < ResolvedSlot > results = Lists . create ( ) ; int number = ; for ( Slot slot : slots ) { ResolvedSlot compiled = compile ( slot , number ++ ) ; results . add ( compiled ) ; } return results ; } private ResolvedSlot compile ( Slot slot , int number ) { assert slot != null ; DataClass valueClass = environment . getDataClasses ( ) . load ( slot . getType ( ) ) ; List < Property > sortProperties = Lists . create ( ) ; if ( valueClass == null ) { valueClass = new DataClass . Unresolved ( environment . getModelFactory ( ) , slot . getType ( ) ) ; environment . error ( "" , slot . getType ( ) ) ; } else { for ( String name : slot . getSortPropertyNames ( ) ) { Property property = valueClass . findProperty ( name ) ; if ( property == null ) { environment . error ( "" , slot . getType ( ) , name ) ; } else { sortProperties . add ( property ) ; } } } return new ResolvedSlot ( slot , number , valueClass , sortProperties ) ; } } package com . asakusafw . compiler . flow . mapreduce . parallel ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . io . NullWritable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . stage . CompiledType ; import com . asakusafw . runtime . stage . AbstractStageClient ; import com . asakusafw . runtime . stage . BaseStageClient ; import com . asakusafw . runtime . stage . StageInput ; import com . asakusafw . runtime . stage . StageOutput ; import com . asakusafw . runtime . stage . collector . SortableSlot ; import com . asakusafw . runtime . stage . collector . WritableSlot ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ParallelSortClientEmitter { static final Logger LOG = LoggerFactory . getLogger ( ParallelSortClientEmitter . class ) ; public static final String ATTRIBUTE_LEGACY = ParallelSortClientEmitter . class . getName ( ) + "" ; private final FlowCompilingEnvironment environment ; public ParallelSortClientEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } static boolean legacy ( FlowCompilingEnvironment environment ) { return environment . getOptions ( ) . getExtraAttribute ( ParallelSortClientEmitter . ATTRIBUTE_LEGACY ) != null ; } public CompiledStage emit ( String moduleId , List < ResolvedSlot > slots , Location outputDirectory ) throws IOException { Precondition . checkMustNotBeNull ( moduleId , "" ) ; Precondition . checkMustNotBeNull ( slots , "" ) ; Precondition . checkMustNotBeNull ( outputDirectory , "" ) ; LOG . debug ( "" , moduleId ) ; Engine engine = new Engine ( environment , moduleId , slots , outputDirectory ) ; CompilationUnit source = engine . generate ( ) ; environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; QualifiedName name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , moduleId , name ) ; return new CompiledStage ( name , Naming . getEpilogueName ( moduleId ) ) ; } private static class Engine { private static final char PATH_SEPARATOR = '' ; private final FlowCompilingEnvironment environment ; private final String moduleId ; private final List < ResolvedSlot > slots ; private final Location outputDirectory ; private final ModelFactory factory ; private final ImportBuilder importer ; Engine ( FlowCompilingEnvironment environment , String moduleId , List < ResolvedSlot > slots , Location outputDirectory ) { assert environment != null ; assert moduleId != null ; assert slots != null ; this . environment = environment ; this . moduleId = moduleId ; this . slots = slots ; this . outputDirectory = outputDirectory ; this . factory = environment . getModelFactory ( ) ; Name packageName = environment . getEpiloguePackageName ( moduleId ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , ImportBuilder . Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) throws IOException { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) throws IOException { SimpleName name = factory . newSimpleName ( Naming . getClientClass ( ) ) ; importer . resolvePackageMember ( name ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . addAll ( createIdMethods ( ) ) ; members . add ( createStageOutputPath ( ) ) ; members . add ( createStageInputsMethod ( ) ) ; members . add ( createStageOutputsMethod ( ) ) ; members . addAll ( createShuffleMethods ( ) ) ; return factory . newClassDeclaration ( createJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , t ( AbstractStageClient . class ) , Collections . < Type > emptyList ( ) , members ) ; } private List < MethodDeclaration > createIdMethods ( ) { List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_BATCH_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getBatchId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_FLOW_ID , t ( String . class ) , Models . toLiteral ( factory , environment . getFlowId ( ) ) ) ) ; results . add ( createValueMethod ( BaseStageClient . METHOD_STAGE_ID , t ( String . class ) , Models . toLiteral ( factory , Naming . getEpilogueName ( moduleId ) ) ) ) ; return results ; } private MethodDeclaration createStageOutputPath ( ) { return createValueMethod ( AbstractStageClient . METHOD_STAGE_OUTPUT_PATH , t ( String . class ) , Models . toLiteral ( factory , outputDirectory . toPath ( PATH_SEPARATOR ) ) ) ; } private MethodDeclaration createStageInputsMethod ( ) throws IOException { SimpleName list = factory . newSimpleName ( "" ) ; SimpleName attributes = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageInput . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageInput . class ) ) , list ) ) ; statements . add ( new ExpressionBuilder ( factory , Models . toNullLiteral ( factory ) ) . toLocalVariableDeclaration ( t ( Map . class , t ( String . class ) , t ( String . class ) ) , attributes ) ) ; for ( ResolvedSlot slot : slots ) { Type mapperType = generateMapper ( slot ) ; statements . add ( new ExpressionBuilder ( factory , attributes ) . assignFrom ( new TypeBuilder ( factory , t ( HashMap . class , t ( String . class ) , t ( String . class ) ) ) . newObject ( ) . toExpression ( ) ) . toStatement ( ) ) ; for ( SourceInfo input : slot . getSource ( ) . getInputs ( ) ) { for ( Map . Entry < String , String > entry : input . getAttributes ( ) . entrySet ( ) ) { statements . add ( new ExpressionBuilder ( factory , attributes ) . method ( "" , Models . toLiteral ( factory , entry . getKey ( ) ) , Models . toLiteral ( factory , entry . getValue ( ) ) ) . toStatement ( ) ) ; } for ( Location location : input . getLocations ( ) ) { statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageInput . class ) ) . newObject ( Models . toLiteral ( factory , location . toPath ( PATH_SEPARATOR ) ) , factory . newClassLiteral ( t ( input . getFormat ( ) ) ) , factory . newClassLiteral ( mapperType ) , attributes ) . toExpression ( ) ) . toStatement ( ) ) ; } } } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageInput . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_INPUTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createStageOutputsMethod ( ) { SimpleName list = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( factory , t ( ArrayList . class , t ( StageOutput . class ) ) ) . newObject ( ) . toLocalVariableDeclaration ( t ( List . class , t ( StageOutput . class ) ) , list ) ) ; for ( ResolvedSlot slot : slots ) { Expression valueType = factory . newClassLiteral ( t ( slot . getValueClass ( ) . getType ( ) ) ) ; Class < ? > outputFormatType = slot . getSource ( ) . getOutputFormatType ( ) ; statements . add ( new ExpressionBuilder ( factory , list ) . method ( "" , new TypeBuilder ( factory , t ( StageOutput . class ) ) . newObject ( Models . toLiteral ( factory , slot . getSource ( ) . getOutputName ( ) ) , factory . newClassLiteral ( t ( NullWritable . class ) ) , valueType , factory . newClassLiteral ( t ( outputFormatType ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( factory , list ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , t ( List . class , t ( StageOutput . class ) ) , factory . newSimpleName ( AbstractStageClient . METHOD_STAGE_OUTPUTS ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private List < MethodDeclaration > createShuffleMethods ( ) throws IOException { List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_SHUFFLE_KEY_CLASS , importer . toType ( SortableSlot . class ) ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_SHUFFLE_VALUE_CLASS , importer . toType ( WritableSlot . class ) ) ) ; if ( doSort ( ) ) { Type reducer = generateReducer ( ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_PARTITIONER_CLASS , importer . toType ( SortableSlot . Partitioner . class ) ) ) ; results . add ( createClassLiteralMethod ( AbstractStageClient . METHOD_REDUCER_CLASS , reducer ) ) ; } return results ; } private boolean doSort ( ) { if ( ParallelSortClientEmitter . legacy ( environment ) ) { return true ; } for ( ResolvedSlot slot : slots ) { if ( slot . getSortProperties ( ) . isEmpty ( ) == false ) { return true ; } } return false ; } private Type generateMapper ( ResolvedSlot slot ) throws IOException { assert slot != null ; ParallelSortMapperEmitter sub = new ParallelSortMapperEmitter ( environment ) ; CompiledType type = sub . emit ( moduleId , slot ) ; return importer . toType ( type . getQualifiedName ( ) ) ; } private Type generateReducer ( ) throws IOException { ParallelSortReducerEmitter sub = new ParallelSortReducerEmitter ( environment ) ; CompiledType type = sub . emit ( moduleId , slots ) ; return importer . toType ( type . getQualifiedName ( ) ) ; } private Javadoc createJavadoc ( ) { return new JavadocBuilder ( factory ) . text ( "" , moduleId ) . toJavadoc ( ) ; } private MethodDeclaration createClassLiteralMethod ( String methodName , Type type ) { assert methodName != null ; assert type != null ; return createValueMethod ( methodName , t ( Class . class , type ) , factory . newClassLiteral ( type ) ) ; } private MethodDeclaration createValueMethod ( String methodName , Type returnType , Expression expression ) { return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( t ( Override . class ) ) . Protected ( ) . toAttributes ( ) , returnType , factory . newSimpleName ( methodName ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Collections . singletonList ( factory . newReturnStatement ( expression ) ) ) ; } private Type t ( java . lang . reflect . Type type , Type ... typeArgs ) { assert type != null ; assert typeArgs != null ; Type raw = importer . toType ( type ) ; if ( typeArgs . length == ) { return raw ; } return factory . newParameterizedType ( raw , Arrays . asList ( typeArgs ) ) ; } } } package com . asakusafw . compiler . flow . mapreduce . parallel ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . DataClass ; import com . asakusafw . compiler . flow . FlowCompilingEnvironment ; import com . asakusafw . compiler . flow . stage . CompiledType ; import com . asakusafw . runtime . stage . collector . SlotDirectMapper ; import com . asakusafw . runtime . stage . collector . SlotDistributor ; import com . asakusafw . runtime . stage . collector . SortableSlot ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; final class ParallelSortMapperEmitter { static final Logger LOG = LoggerFactory . getLogger ( ParallelSortMapperEmitter . class ) ; private final FlowCompilingEnvironment environment ; public ParallelSortMapperEmitter ( FlowCompilingEnvironment environment ) { Precondition . checkMustNotBeNull ( environment , "" ) ; this . environment = environment ; } public CompiledType emit ( String moduleId , ResolvedSlot slot ) throws IOException { Precondition . checkMustNotBeNull ( moduleId , "" ) ; Precondition . checkMustNotBeNull ( slot , "" ) ; LOG . debug ( "" , slot . getSource ( ) . getOutputName ( ) , moduleId ) ; CompilationUnit source ; if ( slot . getSortProperties ( ) . isEmpty ( ) && ParallelSortClientEmitter . legacy ( environment ) == false ) { DirectEngine engine = new DirectEngine ( environment , moduleId , slot ) ; source = engine . generate ( ) ; } else { DistributeEngine engine = new DistributeEngine ( environment , moduleId , slot ) ; source = engine . generate ( ) ; } environment . emit ( source ) ; Name packageName = source . getPackageDeclaration ( ) . getName ( ) ; SimpleName simpleName = source . getTypeDeclarations ( ) . get ( ) . getName ( ) ; Name name = environment . getModelFactory ( ) . newQualifiedName ( packageName , simpleName ) ; LOG . debug ( "" , slot . getSource ( ) . getOutputName ( ) , name ) ; return new CompiledType ( name ) ; } private static class DirectEngine { private final ResolvedSlot slot ; private final ModelFactory factory ; private final ImportBuilder importer ; DirectEngine ( FlowCompilingEnvironment envinronment , String moduleId , ResolvedSlot slot ) { assert envinronment != null ; assert moduleId != null ; assert slot != null ; this . slot = slot ; this . factory = envinronment . getModelFactory ( ) ; Name packageName = Models . append ( factory , envinronment . getEpiloguePackageName ( moduleId ) , JavaName . of ( slot . getSource ( ) . getOutputName ( ) ) . toMemberName ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getMapClass ( ) ) ; importer . resolvePackageMember ( name ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . text ( "" , slot . getSource ( ) . getOutputName ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , importer . toType ( SlotDirectMapper . class ) , Collections . < Type > emptyList ( ) , Collections . singletonList ( createOutputName ( ) ) ) ; } private MethodDeclaration createOutputName ( ) { List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , Models . toLiteral ( factory , slot . getSource ( ) . getOutputName ( ) ) ) . toReturnStatement ( ) ) ; return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( importer . toType ( Override . class ) ) . Public ( ) . toAttributes ( ) , importer . toType ( String . class ) , factory . newSimpleName ( SlotDirectMapper . NAME_GET_OUTPUT_NAME ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } } private static class DistributeEngine { private final ResolvedSlot slot ; private final ModelFactory factory ; private final ImportBuilder importer ; DistributeEngine ( FlowCompilingEnvironment envinronment , String moduleId , ResolvedSlot slot ) { assert envinronment != null ; assert moduleId != null ; assert slot != null ; this . slot = slot ; this . factory = envinronment . getModelFactory ( ) ; Name packageName = Models . append ( factory , envinronment . getEpiloguePackageName ( moduleId ) , JavaName . of ( slot . getSource ( ) . getOutputName ( ) ) . toMemberName ( ) ) ; this . importer = new ImportBuilder ( factory , factory . newPackageDeclaration ( packageName ) , Strategy . TOP_LEVEL ) ; } public CompilationUnit generate ( ) { TypeDeclaration type = createType ( ) ; return factory . newCompilationUnit ( importer . getPackageDeclaration ( ) , importer . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; } private TypeDeclaration createType ( ) { SimpleName name = factory . newSimpleName ( Naming . getMapClass ( ) ) ; importer . resolvePackageMember ( name ) ; return factory . newClassDeclaration ( new JavadocBuilder ( factory ) . text ( "" , slot . getSource ( ) . getOutputName ( ) ) . toJavadoc ( ) , new AttributeBuilder ( factory ) . Public ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , new TypeBuilder ( factory , importer . toType ( SlotDistributor . class ) ) . parameterize ( importer . toType ( slot . getValueClass ( ) . getType ( ) ) ) . toType ( ) , Collections . < Type > emptyList ( ) , Collections . singletonList ( createSlotSpec ( ) ) ) ; } private MethodDeclaration createSlotSpec ( ) { SimpleName valueName = factory . newSimpleName ( "" ) ; SimpleName slotName = factory . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( factory , slotName ) . method ( SortableSlot . NAME_BEGIN , Models . toLiteral ( factory , slot . getSlotNumber ( ) ) ) . toStatement ( ) ) ; if ( slot . getSortProperties ( ) . isEmpty ( ) ) { statements . add ( new ExpressionBuilder ( factory , slotName ) . method ( SortableSlot . NAME_ADD_RANDOM ) . toStatement ( ) ) ; } for ( DataClass . Property property : slot . getSortProperties ( ) ) { if ( property . canNull ( ) ) { statements . add ( factory . newIfStatement ( property . createIsNull ( valueName ) , factory . newBlock ( new Statement [ ] { new ExpressionBuilder ( factory , slotName ) . method ( SortableSlot . NAME_ADD_BYTE , Models . toLiteral ( factory , ) ) . toStatement ( ) , new ExpressionBuilder ( factory , slotName ) . method ( SortableSlot . NAME_ADD_RANDOM ) . toStatement ( ) , } ) , factory . newBlock ( new Statement [ ] { new ExpressionBuilder ( factory , slotName ) . method ( SortableSlot . NAME_ADD_BYTE , Models . toLiteral ( factory , ) ) . toStatement ( ) , new ExpressionBuilder ( factory , slotName ) . method ( SortableSlot . NAME_ADD , property . createGetter ( valueName ) ) . toStatement ( ) , } ) ) ) ; } else { statements . add ( new ExpressionBuilder ( factory , slotName ) . method ( SortableSlot . NAME_ADD , property . createGetter ( valueName ) ) . toStatement ( ) ) ; } } return factory . newMethodDeclaration ( null , new AttributeBuilder ( factory ) . annotation ( importer . toType ( Override . class ) ) . Protected ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , importer . toType ( void . class ) , factory . newSimpleName ( SlotDistributor . NAME_SET_SLOT_SPEC ) , Arrays . asList ( new FormalParameterDeclaration [ ] { factory . newFormalParameterDeclaration ( importer . toType ( slot . getValueClass ( ) . getType ( ) ) , valueName ) , factory . newFormalParameterDeclaration ( importer . toType ( SortableSlot . class ) , slotName ) , } ) , , Collections . singletonList ( importer . toType ( IOException . class ) ) , factory . newBlock ( statements ) ) ; } } } package com . asakusafw . compiler . batch ; import java . lang . reflect . Constructor ; import java . lang . reflect . Modifier ; import java . text . MessageFormat ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; public final class BatchDriver { static final Logger LOG = LoggerFactory . getLogger ( BatchDriver . class ) ; private Class < ? extends BatchDescription > description ; private BatchClass batchClass ; private List < String > diagnostics ; private BatchDriver ( Class < ? extends BatchDescription > description ) { Precondition . checkMustNotBeNull ( description , "" ) ; this . description = description ; this . diagnostics = Lists . create ( ) ; } public static BatchDriver analyze ( Class < ? extends BatchDescription > description ) { Precondition . checkMustNotBeNull ( description , "" ) ; BatchDriver analyzer = new BatchDriver ( description ) ; analyzer . analyze ( ) ; return analyzer ; } public BatchClass getBatchClass ( ) { return batchClass ; } public Class < ? extends BatchDescription > getDescription ( ) { return this . description ; } public List < String > getDiagnostics ( ) { return diagnostics ; } private void analyze ( ) { Batch config = findConfig ( ) ; BatchDescription instance = describe ( ) ; if ( hasError ( ) ) { return ; } this . batchClass = new BatchClass ( config , instance ) ; } private Batch findConfig ( ) { if ( description . getEnclosingClass ( ) != null ) { error ( null , "" ) ; } if ( Modifier . isPublic ( description . getModifiers ( ) ) == false ) { error ( null , "" ) ; } if ( Modifier . isAbstract ( description . getModifiers ( ) ) ) { error ( null , "" ) ; } Batch conf = description . getAnnotation ( Batch . class ) ; if ( conf == null ) { error ( null , "" ) ; } return conf ; } private BatchDescription describe ( ) { Constructor < ? extends BatchDescription > ctor ; try { ctor = description . getConstructor ( ) ; } catch ( Exception e ) { error ( e , "" , description . getName ( ) , e . toString ( ) ) ; return null ; } BatchDescription instance ; try { instance = ctor . newInstance ( ) ; } catch ( Exception e ) { error ( e , "" , description . getName ( ) , e . toString ( ) ) ; return null ; } try { instance . start ( ) ; } catch ( Exception e ) { error ( e , "" , description . getName ( ) , e . toString ( ) ) ; return null ; } return instance ; } private void error ( Throwable reason , String message , Object ... args ) { String text = format ( message , args ) ; diagnostics . add ( text ) ; if ( reason == null ) { LOG . error ( text ) ; } else { LOG . error ( text , reason ) ; } } private String format ( String message , Object ... args ) { assert message != null ; assert args != null ; if ( args . length == ) { return message ; } else { return MessageFormat . format ( message , args ) ; } } public boolean hasError ( ) { return getDiagnostics ( ) . isEmpty ( ) == false ; } } package com . asakusafw . compiler . batch ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . runtime . util . TypeUtil ; import com . asakusafw . vocabulary . batch . WorkDescription ; public abstract class AbstractWorkDescriptionProcessor < T extends WorkDescription > extends BatchCompilingEnvironment . Initialized implements WorkDescriptionProcessor < T > { @ SuppressWarnings ( "" ) @ Override public Class < T > getTargetType ( ) { List < Type > typeArguments = TypeUtil . invoke ( WorkDescriptionProcessor . class , getClass ( ) ) ; if ( typeArguments == null || typeArguments . size ( ) != ) { throw new IllegalStateException ( MessageFormat . format ( "" , getClass ( ) . getName ( ) , WorkDescriptionProcessor . class . getName ( ) ) ) ; } Type first = typeArguments . get ( ) ; if ( ( first instanceof Class < ? > ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , getClass ( ) . getName ( ) , WorkDescriptionProcessor . class . getName ( ) , first ) ) ; } return ( Class < T > ) first ; } } package com . asakusafw . compiler . batch ; import java . io . IOException ; import java . util . Collection ; import java . util . Set ; import com . asakusafw . vocabulary . batch . WorkDescription ; public interface WorkflowProcessor extends BatchCompilingEnvironment . Initializable { Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) ; void process ( Workflow workflow ) throws IOException ; interface Repository extends BatchCompilingEnvironment . Initializable { Set < WorkflowProcessor > findWorkflowProcessors ( Set < ? extends WorkDescription > descriptions ) ; WorkDescriptionProcessor < ? > findDescriptionProcessor ( WorkDescription workDescription ) ; } } package com . asakusafw . compiler . batch ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . UUID ; import java . util . concurrent . atomic . AtomicBoolean ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . Precondition ; public class BatchCompilingEnvironment { static final Logger LOG = LoggerFactory . getLogger ( BatchCompilingEnvironment . class ) ; private final BatchCompilerConfiguration configuration ; private final AtomicBoolean initialized = new AtomicBoolean ( false ) ; private final String buildId = UUID . randomUUID ( ) . toString ( ) ; private String firstError ; public BatchCompilingEnvironment ( BatchCompilerConfiguration configuration ) { Precondition . checkMustNotBeNull ( configuration , "" ) ; this . configuration = configuration ; } public BatchCompilingEnvironment bless ( ) { if ( initialized . compareAndSet ( false , true ) == false ) { return this ; } configuration . getWorkflows ( ) . initialize ( this ) ; clearError ( ) ; return this ; } public String getBuildId ( ) { return buildId ; } public String getErrorMessage ( ) { return firstError ; } public boolean hasError ( ) { return firstError != null ; } public void clearError ( ) { firstError = null ; } public BatchCompilerConfiguration getConfiguration ( ) { return configuration ; } public WorkflowProcessor . Repository getWorkflows ( ) { return configuration . getWorkflows ( ) ; } public OutputStream openResource ( String path ) throws IOException { Precondition . checkMustNotBeNull ( path , "" ) ; File output = configuration . getOutputDirectory ( ) ; File file = new File ( output , path ) ; File parent = file . getParentFile ( ) ; if ( parent . mkdirs ( ) == false && parent . isDirectory ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , parent ) ) ; } return new FileOutputStream ( file ) ; } public void error ( String format , Object ... arguments ) { Precondition . checkMustNotBeNull ( format , "" ) ; Precondition . checkMustNotBeNull ( arguments , "" ) ; String text ; if ( arguments . length == ) { text = format ; } else { text = MessageFormat . format ( format , arguments ) ; } LOG . error ( text ) ; if ( firstError == null ) { firstError = text ; } } public interface Initializable { void initialize ( BatchCompilingEnvironment environment ) ; } public abstract static class Initialized implements Initializable { private BatchCompilingEnvironment environment ; @ Override public final void initialize ( BatchCompilingEnvironment env ) { Precondition . checkMustNotBeNull ( env , "" ) ; this . environment = env ; doInitialize ( ) ; } protected void doInitialize ( ) { return ; } protected BatchCompilingEnvironment getEnvironment ( ) { return environment ; } } } package com . asakusafw . compiler . batch ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . batch . WorkDescription ; public class Workflow { private final BatchDescription description ; private final Graph < Unit > graph ; public Workflow ( BatchDescription description , Graph < Unit > graph ) { Precondition . checkMustNotBeNull ( description , "" ) ; Precondition . checkMustNotBeNull ( graph , "" ) ; this . description = description ; this . graph = graph ; } public BatchDescription getDescription ( ) { return description ; } public Graph < Unit > getGraph ( ) { return graph ; } public static class Unit { private final WorkDescription description ; private boolean isProcessed ; private Object processed ; public Unit ( WorkDescription description ) { Precondition . checkMustNotBeNull ( description , "" ) ; this . description = description ; } public WorkDescription getDescription ( ) { return description ; } public Object getProcessed ( ) { if ( isProcessed == false ) { throw new IllegalStateException ( ) ; } return processed ; } public void setProcessed ( Object result ) { if ( isProcessed ) { throw new IllegalStateException ( ) ; } isProcessed = true ; this . processed = result ; } } } package com . asakusafw . compiler . batch ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Map ; import java . util . Set ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . batch . Work ; import com . asakusafw . vocabulary . batch . WorkDescription ; public class BatchCompiler { private final BatchCompilingEnvironment environment ; public BatchCompiler ( BatchCompilerConfiguration configuration ) { Precondition . checkMustNotBeNull ( configuration , "" ) ; this . environment = new BatchCompilingEnvironment ( configuration ) . bless ( ) ; } public Workflow compile ( BatchDescription description ) throws IOException { Precondition . checkMustNotBeNull ( description , "" ) ; Workflow workflow = createWorkflow ( description ) ; processUnits ( workflow . getGraph ( ) . getNodeSet ( ) ) ; if ( environment . hasError ( ) ) { throw new IOException ( MessageFormat . format ( "" , environment . getErrorMessage ( ) ) ) ; } processWorkflow ( workflow ) ; if ( environment . hasError ( ) ) { throw new IOException ( MessageFormat . format ( "" , environment . getErrorMessage ( ) ) ) ; } return workflow ; } private void processWorkflow ( Workflow workflow ) throws IOException { assert workflow != null ; Set < WorkDescription > descriptions = Sets . create ( ) ; for ( Workflow . Unit unit : workflow . getGraph ( ) . getNodeSet ( ) ) { descriptions . add ( unit . getDescription ( ) ) ; } WorkflowProcessor . Repository repo = environment . getWorkflows ( ) ; Set < WorkflowProcessor > procs = repo . findWorkflowProcessors ( descriptions ) ; for ( WorkflowProcessor proc : procs ) { proc . process ( workflow ) ; } } private void processUnits ( Set < Workflow . Unit > units ) throws IOException { assert units != null ; WorkflowProcessor . Repository repo = environment . getWorkflows ( ) ; for ( Workflow . Unit unit : units ) { WorkDescriptionProcessor < ? > proc = repo . findDescriptionProcessor ( unit . getDescription ( ) ) ; if ( proc == null ) { environment . error ( "" , unit . getClass ( ) . getName ( ) ) ; continue ; } processUnit ( unit , proc ) ; } } private < T extends WorkDescription > void processUnit ( Workflow . Unit unit , WorkDescriptionProcessor < T > proc ) throws IOException { assert unit != null ; assert proc != null ; assert proc . getTargetType ( ) . isInstance ( unit . getDescription ( ) ) ; T desc = proc . getTargetType ( ) . cast ( unit . getDescription ( ) ) ; Object result = proc . process ( desc ) ; unit . setProcessed ( result ) ; } private Workflow createWorkflow ( BatchDescription description ) { assert description != null ; Collection < Work > works = description . getWorks ( ) ; Map < Work , Workflow . Unit > units = Maps . create ( ) ; for ( Work work : works ) { units . put ( work , new Workflow . Unit ( work . getDescription ( ) ) ) ; } Graph < Workflow . Unit > graph = Graphs . newInstance ( ) ; for ( Map . Entry < Work , Workflow . Unit > entry : units . entrySet ( ) ) { Workflow . Unit unit = entry . getValue ( ) ; graph . addNode ( unit ) ; for ( Work dependency : entry . getKey ( ) . getDependencies ( ) ) { Workflow . Unit predecessor = units . get ( dependency ) ; assert predecessor != null ; graph . addEdge ( unit , predecessor ) ; } } Workflow workflow = new Workflow ( description , graph ) ; return workflow ; } } package com . asakusafw . compiler . batch . experimental ; import java . io . Closeable ; import java . io . File ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . List ; import java . util . Map ; import java . util . SortedMap ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . batch . processor . ScriptWorkDescriptionProcessor ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . utils . collections . Lists ; public class DumpEnvironmentProcessor extends AbstractWorkflowProcessor { static final Logger LOG = LoggerFactory . getLogger ( DumpEnvironmentProcessor . class ) ; static final Charset ENCODING = Charset . forName ( "" ) ; public static final String PATH = "" ; public static final String PREFIX_ENV = "" ; public static final String PREFIX_SYSPROP = "" ; public static File getScriptOutput ( File outputDir ) { Precondition . checkMustNotBeNull ( outputDir , "" ) ; return new File ( outputDir , PATH ) ; } @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( JobFlowWorkDescriptionProcessor . class ) ; results . add ( ScriptWorkDescriptionProcessor . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { OutputStream output = getEnvironment ( ) . openResource ( PATH ) ; try { Context context = new Context ( output ) ; dumpInternal ( context ) ; dumpEnv ( context ) ; dumpSystemProperties ( context ) ; context . close ( ) ; } finally { output . close ( ) ; } } private void dumpInternal ( Context context ) { context . put ( "" , getEnvironment ( ) . getConfiguration ( ) . getBatchId ( ) ) ; context . put ( "" , getEnvironment ( ) . getBuildId ( ) ) ; } private void dumpEnv ( Context context ) { try { SortedMap < String , String > map = sortFilter ( System . getenv ( ) , PREFIX_ENV ) ; for ( Map . Entry < String , ? > entry : map . entrySet ( ) ) { context . put ( "" , entry . getKey ( ) , entry . getValue ( ) ) ; } } catch ( SecurityException e ) { LOG . warn ( "" , e ) ; } } private void dumpSystemProperties ( Context context ) { try { SortedMap < String , Object > map = sortFilter ( System . getProperties ( ) , PREFIX_SYSPROP ) ; for ( Map . Entry < String , ? > entry : map . entrySet ( ) ) { context . put ( "" , entry . getKey ( ) , entry . getValue ( ) ) ; } } catch ( SecurityException e ) { LOG . warn ( "" , e ) ; } } private < T > SortedMap < String , T > sortFilter ( Map < ? , T > map , String prefix ) { assert map != null ; assert prefix != null ; SortedMap < String , T > results = new TreeMap < String , T > ( ) ; for ( Map . Entry < ? , T > entry : map . entrySet ( ) ) { String key = String . valueOf ( entry . getKey ( ) ) ; if ( key . startsWith ( prefix ) ) { results . put ( key , entry . getValue ( ) ) ; } } return results ; } private static class Context implements Closeable { private final PrintWriter writer ; public Context ( OutputStream output ) { assert output != null ; writer = new PrintWriter ( new OutputStreamWriter ( output , ENCODING ) ) ; } public void put ( String pattern , Object ... arguments ) { assert pattern != null ; assert arguments != null ; String text ; if ( arguments . length == ) { text = pattern ; } else { text = MessageFormat . format ( pattern , arguments ) ; } writer . println ( text ) ; LOG . debug ( text ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } } } package com . asakusafw . compiler . batch . experimental ; package com . asakusafw . compiler . batch ; package com . asakusafw . compiler . batch ; import java . io . IOException ; import com . asakusafw . vocabulary . batch . WorkDescription ; public interface WorkDescriptionProcessor < T extends WorkDescription > extends BatchCompilingEnvironment . Initializable { Class < T > getTargetType ( ) ; Object process ( T description ) throws IOException ; } package com . asakusafw . compiler . batch ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; public class BatchClass { private Batch config ; private BatchDescription description ; public BatchClass ( Batch config , BatchDescription description ) { Precondition . checkMustNotBeNull ( config , "" ) ; Precondition . checkMustNotBeNull ( description , "" ) ; this . config = config ; this . description = description ; } public Batch getConfig ( ) { return config ; } public BatchDescription getDescription ( ) { return description ; } } package com . asakusafw . compiler . batch ; public abstract class AbstractWorkflowProcessor extends BatchCompilingEnvironment . Initialized implements WorkflowProcessor { } package com . asakusafw . compiler . batch ; import java . io . File ; import java . util . List ; import com . asakusafw . compiler . batch . WorkflowProcessor . Repository ; import com . asakusafw . compiler . flow . DataClassRepository ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowElementProcessor ; import com . asakusafw . compiler . flow . FlowGraphRewriter ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; public class BatchCompilerConfiguration { private ModelFactory factory ; private FlowElementProcessor . Repository flowElements ; private DataClassRepository dataClasses ; private ExternalIoDescriptionProcessor . Repository externals ; private FlowGraphRewriter . Repository graphRewriters ; private String batchId ; private String rootPackageName ; private Location rootLocation ; private File workingDirectory ; private List < ? extends ResourceRepository > linkingResources ; private File outputDirectory ; private Repository workflows ; private ClassLoader serviceClassLoader ; private FlowCompilerOptions flowCompilerOptions ; public ModelFactory getFactory ( ) { return factory ; } public void setFactory ( ModelFactory factory ) { this . factory = factory ; } public WorkflowProcessor . Repository getWorkflows ( ) { return workflows ; } public void setWorkflows ( Repository workflows ) { this . workflows = workflows ; } public FlowElementProcessor . Repository getFlowElements ( ) { return flowElements ; } public void setFlowElements ( FlowElementProcessor . Repository flowElements ) { this . flowElements = flowElements ; } public DataClassRepository getDataClasses ( ) { return dataClasses ; } public void setDataClasses ( DataClassRepository dataClasses ) { this . dataClasses = dataClasses ; } public ExternalIoDescriptionProcessor . Repository getExternals ( ) { return externals ; } public void setExternals ( ExternalIoDescriptionProcessor . Repository externals ) { this . externals = externals ; } public FlowGraphRewriter . Repository getGraphRewriters ( ) { return graphRewriters ; } public void setGraphRewriters ( FlowGraphRewriter . Repository graphRewriters ) { this . graphRewriters = graphRewriters ; } public String getBatchId ( ) { return batchId ; } public void setBatchId ( String batchId ) { this . batchId = batchId ; } public String getRootPackageName ( ) { return rootPackageName ; } public void setRootPackageName ( String rootPackageName ) { this . rootPackageName = rootPackageName ; } public Location getRootLocation ( ) { return rootLocation ; } public void setRootLocation ( Location rootLocation ) { this . rootLocation = rootLocation ; } public File getWorkingDirectory ( ) { return workingDirectory ; } public void setWorkingDirectory ( File workingDirectory ) { this . workingDirectory = workingDirectory ; } public List < ? extends ResourceRepository > getLinkingResources ( ) { return linkingResources ; } public void setLinkingResources ( List < ? extends ResourceRepository > linkingResources ) { this . linkingResources = linkingResources ; } public File getOutputDirectory ( ) { return outputDirectory ; } public void setOutputDirectory ( File outputDirectory ) { this . outputDirectory = outputDirectory ; } public ClassLoader getServiceClassLoader ( ) { return serviceClassLoader ; } public void setServiceClassLoader ( ClassLoader serviceClassLoader ) { this . serviceClassLoader = serviceClassLoader ; } public FlowCompilerOptions getFlowCompilerOptions ( ) { return flowCompilerOptions ; } public void setFlowCompilerOptions ( FlowCompilerOptions flowCompilerOptions ) { this . flowCompilerOptions = flowCompilerOptions ; } } package com . asakusafw . compiler . batch ; import java . io . Closeable ; import java . io . IOException ; import java . io . InputStream ; import com . asakusafw . compiler . flow . Location ; public interface ResourceRepository { Cursor createCursor ( ) throws IOException ; interface Cursor extends Closeable { boolean next ( ) throws IOException ; Location getLocation ( ) ; InputStream openResource ( ) throws IOException ; } } package com . asakusafw . compiler . batch . processor ; package com . asakusafw . compiler . batch . processor ; import java . io . IOException ; import com . asakusafw . compiler . batch . AbstractWorkDescriptionProcessor ; import com . asakusafw . vocabulary . batch . ScriptWorkDescription ; public class ScriptWorkDescriptionProcessor extends AbstractWorkDescriptionProcessor < ScriptWorkDescription > { @ Override public Void process ( ScriptWorkDescription description ) throws IOException { if ( isLocal ( description ) ) { } return null ; } private boolean isLocal ( ScriptWorkDescription description ) { assert description != null ; return false ; } } package com . asakusafw . compiler . batch . processor ; import java . io . File ; import java . io . IOException ; import com . asakusafw . compiler . batch . AbstractWorkDescriptionProcessor ; import com . asakusafw . compiler . batch . BatchCompilerConfiguration ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . FlowCompiler ; import com . asakusafw . compiler . flow . FlowCompilerConfiguration ; import com . asakusafw . compiler . flow . JobFlowClass ; import com . asakusafw . compiler . flow . JobFlowDriver ; import com . asakusafw . compiler . flow . Packager ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . packager . FilePackager ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class JobFlowWorkDescriptionProcessor extends AbstractWorkDescriptionProcessor < JobFlowWorkDescription > { public static final String JOBFLOW_PACKAGE = "" ; private static final String JOBFLOW_TEMPORARY = "" ; @ Override public JobflowModel process ( JobFlowWorkDescription description ) throws IOException { JobflowModel model = build ( description ) ; return model ; } private JobflowModel build ( JobFlowWorkDescription description ) throws IOException { JobFlowClass jobflow = analyze ( description ) ; if ( jobflow == null ) { return null ; } FlowCompilerConfiguration config = createConfiguration ( jobflow ) ; FlowCompiler compiler = new FlowCompiler ( config ) ; JobflowModel model = compiler . compile ( jobflow . getGraph ( ) ) ; File batchOutput = getEnvironment ( ) . getConfiguration ( ) . getOutputDirectory ( ) ; String flowId = compiler . getTargetFlowId ( ) ; compiler . buildSources ( getPackageLocation ( batchOutput , flowId ) ) ; compiler . collectSources ( getSourceLocation ( batchOutput , flowId ) ) ; return model ; } private FlowCompilerConfiguration createConfiguration ( JobFlowClass jobflow ) { assert jobflow != null ; BatchCompilerConfiguration batch = getEnvironment ( ) . getConfiguration ( ) ; FlowCompilerConfiguration result = new FlowCompilerConfiguration ( ) ; result . setBatchId ( batch . getBatchId ( ) ) ; result . setDataClasses ( batch . getDataClasses ( ) ) ; result . setExternals ( batch . getExternals ( ) ) ; result . setFactory ( batch . getFactory ( ) ) ; result . setFlowId ( jobflow . getConfig ( ) . name ( ) ) ; result . setGraphRewriters ( batch . getGraphRewriters ( ) ) ; result . setPackager ( createPackager ( jobflow ) ) ; result . setProcessors ( batch . getFlowElements ( ) ) ; result . setRootLocation ( batch . getRootLocation ( ) ) ; result . setRootPackageName ( batch . getRootPackageName ( ) ) ; result . setServiceClassLoader ( batch . getServiceClassLoader ( ) ) ; result . setOptions ( getEnvironment ( ) . getConfiguration ( ) . getFlowCompilerOptions ( ) ) ; result . setBuildId ( getEnvironment ( ) . getBuildId ( ) ) ; return result ; } private Packager createPackager ( JobFlowClass jobflow ) { assert jobflow != null ; BatchCompilerConfiguration batch = getEnvironment ( ) . getConfiguration ( ) ; return new FilePackager ( new File ( new File ( batch . getWorkingDirectory ( ) , jobflow . getConfig ( ) . name ( ) ) , JOBFLOW_TEMPORARY ) , batch . getLinkingResources ( ) ) ; } private JobFlowClass analyze ( JobFlowWorkDescription description ) { assert description != null ; Class < ? extends FlowDescription > flowClass = description . getFlowClass ( ) ; JobFlowDriver driver = JobFlowDriver . analyze ( flowClass ) ; if ( driver . hasError ( ) ) { for ( String message : driver . getDiagnostics ( ) ) { getEnvironment ( ) . error ( message ) ; } return null ; } return driver . getJobFlowClass ( ) ; } public static File getPackageLocation ( File batchOutput , String flowId ) { Precondition . checkMustNotBeNull ( batchOutput , "" ) ; Precondition . checkMustNotBeNull ( flowId , "" ) ; File dir = new File ( batchOutput , JOBFLOW_PACKAGE ) ; File file = new File ( dir , Naming . getJobflowClassPackageName ( flowId ) ) ; return file ; } public static File getSourceLocation ( File batchOutput , String flowId ) { Precondition . checkMustNotBeNull ( batchOutput , "" ) ; Precondition . checkMustNotBeNull ( flowId , "" ) ; File dir = new File ( batchOutput , JOBFLOW_PACKAGE ) ; File file = new File ( dir , Naming . getJobflowSourceBundleName ( flowId ) ) ; return file ; } } package com . asakusafw . compiler . repository ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import org . hamcrest . Matcher ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . batch . AbstractWorkDescriptionProcessor ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . BatchCompilerEnvironmentProvider ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . WorkflowProcessor ; import com . asakusafw . compiler . flow . example . SimpleJobFlow ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . batch . WorkDescription ; public class SpiWorkflowProcessorRepositoryTest { @ Rule public BatchCompilerEnvironmentProvider prov = new BatchCompilerEnvironmentProvider ( ) ; @ Test public void findWorkflowProcessors_simple ( ) { SpiWorkflowProcessorRepository repo = new SpiWorkflowProcessorRepository ( ) { @ Override protected Iterable < ? extends WorkflowProcessor > loadServices ( ) { return Arrays . asList ( new WorkflowProcessor [ ] { new MockProc1 ( ) , } ) ; } } ; repo . initialize ( prov . getEnvironment ( ) ) ; Set < WorkflowProcessor > processors = repo . findWorkflowProcessors ( set ( new MockDesc1 ( ) ) ) ; assertThat ( classes ( processors ) , contains ( ( Object ) MockProc1 . class ) ) ; } @ Test public void findWorkflowProcessors_multi ( ) { SpiWorkflowProcessorRepository repo = new SpiWorkflowProcessorRepository ( ) { @ Override protected Iterable < ? extends WorkflowProcessor > loadServices ( ) { return Arrays . asList ( new WorkflowProcessor [ ] { new MockProc1 ( ) , new MockProc2 ( ) , } ) ; } } ; repo . initialize ( prov . getEnvironment ( ) ) ; Set < WorkflowProcessor > processors = repo . findWorkflowProcessors ( set ( new MockDesc1 ( ) , new MockDesc2 ( ) ) ) ; assertThat ( classes ( processors ) , contains ( ( Object ) MockProc2 . class ) ) ; } @ Test public void findWorkflowProcessors_super ( ) { SpiWorkflowProcessorRepository repo = new SpiWorkflowProcessorRepository ( ) { @ Override protected Iterable < ? extends WorkflowProcessor > loadServices ( ) { return Arrays . asList ( new WorkflowProcessor [ ] { new MockProc3 ( ) , } ) ; } } ; repo . initialize ( prov . getEnvironment ( ) ) ; Set < WorkflowProcessor > processors = repo . findWorkflowProcessors ( set ( new MockDesc1 ( ) , new MockDesc2 ( ) , new JobFlowWorkDescription ( SimpleJobFlow . class ) ) ) ; assertThat ( classes ( processors ) , contains ( ( Object ) MockProc3 . class ) ) ; } @ Test public void findWorkflowProcessors_containsUnknown ( ) { SpiWorkflowProcessorRepository repo = new SpiWorkflowProcessorRepository ( ) { @ Override protected Iterable < ? extends WorkflowProcessor > loadServices ( ) { return Arrays . asList ( new WorkflowProcessor [ ] { new MockProc1 ( ) , new MockProc2 ( ) , } ) ; } } ; repo . initialize ( prov . getEnvironment ( ) ) ; Set < WorkflowProcessor > processors = repo . findWorkflowProcessors ( set ( new MockDesc1 ( ) , new JobFlowWorkDescription ( SimpleJobFlow . class ) , new MockDesc2 ( ) ) ) ; assertThat ( processors . size ( ) , is ( ) ) ; } @ Test public void findDescriptionProcessor_simple ( ) { SpiWorkflowProcessorRepository repo = new SpiWorkflowProcessorRepository ( ) { @ Override protected Iterable < ? extends WorkflowProcessor > loadServices ( ) { return Arrays . asList ( new WorkflowProcessor [ ] { new MockProc1 ( ) , } ) ; } } ; repo . initialize ( prov . getEnvironment ( ) ) ; assertThat ( repo . findDescriptionProcessor ( new MockDesc1 ( ) ) , instanceOf ( MockDescProc1 . class ) ) ; assertThat ( repo . findDescriptionProcessor ( new MockDesc2 ( ) ) , is ( nullValue ( ) ) ) ; } @ Test public void findDescriptionProcessor_multi ( ) { SpiWorkflowProcessorRepository repo = new SpiWorkflowProcessorRepository ( ) { @ Override protected Iterable < ? extends WorkflowProcessor > loadServices ( ) { return Arrays . asList ( new WorkflowProcessor [ ] { new MockProc1 ( ) , new MockProc2 ( ) , } ) ; } } ; repo . initialize ( prov . getEnvironment ( ) ) ; assertThat ( repo . findDescriptionProcessor ( new MockDesc1 ( ) ) , instanceOf ( MockDescProc1 . class ) ) ; assertThat ( repo . findDescriptionProcessor ( new MockDesc2 ( ) ) , instanceOf ( MockDescProc2 . class ) ) ; } @ Test public void findDescriptionProcessor_super ( ) { SpiWorkflowProcessorRepository repo = new SpiWorkflowProcessorRepository ( ) { @ Override protected Iterable < ? extends WorkflowProcessor > loadServices ( ) { return Arrays . asList ( new WorkflowProcessor [ ] { new MockProc3 ( ) , } ) ; } } ; repo . initialize ( prov . getEnvironment ( ) ) ; assertThat ( repo . findDescriptionProcessor ( new MockDesc1 ( ) ) , instanceOf ( MockDescProc3 . class ) ) ; assertThat ( repo . findDescriptionProcessor ( new MockDesc2 ( ) ) , instanceOf ( MockDescProc3 . class ) ) ; } private Set < WorkDescription > set ( WorkDescription ... descriptions ) { return Sets . from ( descriptions ) ; } private Set < Object > classes ( Set < ? > instances ) { Set < Object > results = Sets . create ( ) ; for ( Object t : instances ) { results . add ( t . getClass ( ) ) ; } return results ; } private < T > Matcher < ? super Set < T > > contains ( T ... values ) { Set < T > expect = Sets . create ( ) ; Collections . addAll ( expect , values ) ; return is ( expect ) ; } private static class MockProc1 extends AbstractWorkflowProcessor { public MockProc1 ( ) { return ; } @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( MockDescProc1 . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { return ; } } private static class MockProc2 extends AbstractWorkflowProcessor { public MockProc2 ( ) { return ; } @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( MockDescProc1 . class ) ; results . add ( MockDescProc2 . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { return ; } } private static class MockProc3 extends AbstractWorkflowProcessor { public MockProc3 ( ) { return ; } @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( MockDescProc3 . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { return ; } } private static class MockDescProc1 extends AbstractWorkDescriptionProcessor < MockDesc1 > { @ SuppressWarnings ( "" ) public MockDescProc1 ( ) { return ; } @ Override public Object process ( MockDesc1 description ) throws IOException { return null ; } } private static class MockDescProc2 extends AbstractWorkDescriptionProcessor < MockDesc2 > { @ SuppressWarnings ( "" ) public MockDescProc2 ( ) { return ; } @ Override public Object process ( MockDesc2 description ) throws IOException { return null ; } } private static class MockDescProc3 extends AbstractWorkDescriptionProcessor < WorkDescription > { @ SuppressWarnings ( "" ) public MockDescProc3 ( ) { return ; } @ Override public Object process ( WorkDescription description ) throws IOException { return null ; } } private static class MockDesc1 extends WorkDescription { public MockDesc1 ( ) { return ; } @ Override public String getName ( ) { return "" ; } } private static class MockDesc2 extends WorkDescription { public MockDesc2 ( ) { return ; } @ Override public String getName ( ) { return "" ; } } } package com . asakusafw . compiler . testing ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . Arrays ; import java . util . Comparator ; import java . util . List ; import java . util . jar . JarFile ; import java . util . zip . ZipInputStream ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . processor . flow . UpdateFlowSimple ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . flow . DuplicateFragments ; import com . asakusafw . compiler . testing . flow . StraightFragments ; import com . asakusafw . compiler . testing . flow . StraightRendezvousFragments ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . HadoopDriver ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; import com . asakusafw . runtime . value . ValueOption ; public class DirectFlowCompilerTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void folderLibraryPath ( ) throws Exception { File file = extract ( "" ) ; Class < ? > aClass = load ( file , "" ) ; File library = DirectFlowCompiler . toLibraryPath ( aClass ) ; assertThat ( library , not ( nullValue ( ) ) ) ; assertThat ( file . getCanonicalFile ( ) , is ( library . getCanonicalFile ( ) ) ) ; } @ Test public void folderLibraryPathWithInner ( ) throws Exception { File file = extract ( "" ) ; Class < ? > aClass = load ( file , "" ) ; File library = DirectFlowCompiler . toLibraryPath ( aClass ) ; assertThat ( library , not ( nullValue ( ) ) ) ; assertThat ( file . getCanonicalFile ( ) , is ( library . getCanonicalFile ( ) ) ) ; } @ Test public void jarLibraryPath ( ) throws Exception { File file = copy ( "" ) ; Class < ? > aClass = load ( file , "" ) ; File library = DirectFlowCompiler . toLibraryPath ( aClass ) ; assertThat ( library , not ( nullValue ( ) ) ) ; assertThat ( file . getCanonicalFile ( ) , is ( library . getCanonicalFile ( ) ) ) ; } @ Test public void jarLibraryPathWithInner ( ) throws Exception { File file = copy ( "" ) ; Class < ? > aClass = load ( file , "" ) ; File library = DirectFlowCompiler . toLibraryPath ( aClass ) ; assertThat ( library , not ( nullValue ( ) ) ) ; assertThat ( file . getCanonicalFile ( ) , is ( library . getCanonicalFile ( ) ) ) ; } @ Test public void zipLibraryPath ( ) throws Exception { File file = copy ( "" ) ; Class < ? > aClass = load ( file , "" ) ; File library = DirectFlowCompiler . toLibraryPath ( aClass ) ; assertThat ( library , not ( nullValue ( ) ) ) ; assertThat ( file . getCanonicalFile ( ) , is ( library . getCanonicalFile ( ) ) ) ; } @ Test public void simpleCompile ( ) throws Exception { List < File > classpath = Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( ValueOption . class ) , DirectFlowCompiler . toLibraryPath ( Ex1 . class ) , } ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; JobflowInfo info = DirectFlowCompiler . compile ( tester . analyzeFlow ( new UpdateFlowSimple ( in . flow ( ) , out . flow ( ) ) ) , "" , "" , "" , Location . fromPath ( HadoopDriver . RUNTIME_WORK_ROOT , '' ) , tester . framework ( ) . getWork ( "" ) , classpath , getClass ( ) . getClassLoader ( ) , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > results = out . toList ( ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void straightFragmentsCompile ( ) throws Exception { List < File > classpath = Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( ValueOption . class ) , DirectFlowCompiler . toLibraryPath ( Ex1 . class ) , } ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; JobflowInfo info = DirectFlowCompiler . compile ( tester . analyzeFlow ( new StraightFragments ( in . flow ( ) , out . flow ( ) ) ) , "" , "" , "" , Location . fromPath ( HadoopDriver . RUNTIME_WORK_ROOT , '' ) , tester . framework ( ) . getWork ( "" ) , classpath , getClass ( ) . getClassLoader ( ) , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > results = out . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void duplicateCompile ( ) throws Exception { List < File > classpath = Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( ValueOption . class ) , DirectFlowCompiler . toLibraryPath ( Ex1 . class ) , } ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; JobflowInfo info = DirectFlowCompiler . compile ( tester . analyzeFlow ( new DuplicateFragments ( in . flow ( ) , out . flow ( ) ) ) , "" , "" , "" , Location . fromPath ( HadoopDriver . RUNTIME_WORK_ROOT , '' ) , tester . framework ( ) . getWork ( "" ) , classpath , getClass ( ) . getClassLoader ( ) , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > results = out . toList ( ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void straightRendezvousFragmentsCompile ( ) throws Exception { List < File > classpath = Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( ValueOption . class ) , DirectFlowCompiler . toLibraryPath ( Ex1 . class ) , } ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; JobflowInfo info = DirectFlowCompiler . compile ( tester . analyzeFlow ( new StraightRendezvousFragments ( in . flow ( ) , out . flow ( ) ) ) , "" , "" , "" , Location . fromPath ( HadoopDriver . RUNTIME_WORK_ROOT , '' ) , tester . framework ( ) . getWork ( "" ) , classpath , getClass ( ) . getClassLoader ( ) , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > results = out . toList ( ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void compileWithSubmoduleJar ( ) throws Exception { List < File > classpath = Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( ValueOption . class ) , DirectFlowCompiler . toLibraryPath ( Ex1 . class ) , } ) ; File jar = copy ( "" ) ; ClassLoader cl = new URLClassLoader ( new URL [ ] { jar . toURI ( ) . toURL ( ) } , getClass ( ) . getClassLoader ( ) ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; JobflowInfo info = DirectFlowCompiler . compile ( tester . analyzeFlow ( new UpdateFlowSimple ( in . flow ( ) , out . flow ( ) ) ) , "" , "" , "" , Location . fromPath ( HadoopDriver . RUNTIME_WORK_ROOT , '' ) , tester . framework ( ) . getWork ( "" ) , classpath , cl , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; File compiled = info . getPackageFile ( ) ; load ( compiled , "" ) ; find ( compiled , "" ) ; } @ Test public void compileWithSubmoduleFolder ( ) throws Exception { List < File > classpath = Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( ValueOption . class ) , DirectFlowCompiler . toLibraryPath ( Ex1 . class ) , } ) ; File jar = extract ( "" ) ; ClassLoader cl = new URLClassLoader ( new URL [ ] { jar . toURI ( ) . toURL ( ) } , getClass ( ) . getClassLoader ( ) ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; JobflowInfo info = DirectFlowCompiler . compile ( tester . analyzeFlow ( new UpdateFlowSimple ( in . flow ( ) , out . flow ( ) ) ) , "" , "" , "" , Location . fromPath ( HadoopDriver . RUNTIME_WORK_ROOT , '' ) , tester . framework ( ) . getWork ( "" ) , classpath , cl , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; File compiled = info . getPackageFile ( ) ; load ( compiled , "" ) ; find ( compiled , "" ) ; } @ Test public void compileWithSubmoduleDuplicated ( ) throws Exception { File jar = copy ( "" ) ; List < File > classpath = Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( ValueOption . class ) , DirectFlowCompiler . toLibraryPath ( Ex1 . class ) , DirectFlowCompiler . toLibraryPath ( ValueOption . class ) , DirectFlowCompiler . toLibraryPath ( Ex1 . class ) , jar , } ) ; ClassLoader cl = new URLClassLoader ( new URL [ ] { jar . toURI ( ) . toURL ( ) } , getClass ( ) . getClassLoader ( ) ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; JobflowInfo info = DirectFlowCompiler . compile ( tester . analyzeFlow ( new UpdateFlowSimple ( in . flow ( ) , out . flow ( ) ) ) , "" , "" , "" , Location . fromPath ( HadoopDriver . RUNTIME_WORK_ROOT , '' ) , tester . framework ( ) . getWork ( "" ) , classpath , cl , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; File compiled = info . getPackageFile ( ) ; load ( compiled , "" ) ; find ( compiled , "" ) ; } private Class < ? > load ( File file , String className ) { try { URLClassLoader loader = new URLClassLoader ( new URL [ ] { file . toURI ( ) . toURL ( ) } ) ; return Class . forName ( className , false , loader ) ; } catch ( MalformedURLException e ) { Assume . assumeNoException ( e ) ; throw new AssertionError ( e ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private void find ( File file , String path ) { try { JarFile jar = new JarFile ( file ) ; try { assertThat ( path , jar . getEntry ( path ) , is ( notNullValue ( ) ) ) ; } finally { jar . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } private File copy ( String name ) { InputStream input = open ( name ) ; try { try { File target = new File ( tester . framework ( ) . getWork ( "" ) , name ) ; tester . framework ( ) . dump ( input , target ) ; return target ; } finally { input . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } private File extract ( String name ) { InputStream input = open ( name ) ; try { try { ZipInputStream zip = new ZipInputStream ( input ) ; File target = new File ( tester . framework ( ) . getWork ( "" ) , name ) ; tester . framework ( ) . extract ( zip , target ) ; zip . close ( ) ; return target ; } finally { input . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } private InputStream open ( String name ) { String path = getClass ( ) . getSimpleName ( ) + "" + name ; InputStream input = getClass ( ) . getResourceAsStream ( path ) ; assertThat ( path , input , not ( nullValue ( ) ) ) ; return input ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class NestedOutExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class SingularOutputExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SingularOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public SingularOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = SingularOutputExporterDesc . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MultipleOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output1 ; private final Out < Ex1 > output2 ; private final Out < Ex1 > output3 ; private final Out < Ex1 > output4 ; public MultipleOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Out1ExporterDesc . class ) Out < Ex1 > output1 , @ Export ( name = "" , description = Out2ExporterDesc . class ) Out < Ex1 > output2 , @ Export ( name = "" , description = Out3ExporterDesc . class ) Out < Ex1 > output3 , @ Export ( name = "" , description = Out4ExporterDesc . class ) Out < Ex1 > output4 ) { this . input = input ; this . output1 = output1 ; this . output2 = output2 ; this . output3 = output3 ; this . output4 = output4 ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result1 = op . update ( input , ) ; output1 . add ( result1 . out ) ; Update result2 = op . update ( input , ) ; output2 . add ( result2 . out ) ; Update result3 = op . update ( input , ) ; output3 . add ( result3 . out ) ; Update result4 = op . update ( input , ) ; output4 . add ( result4 . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . processor . operator . BranchFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class StraightFragments extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public StraightFragments ( In < Ex1 > in1 , Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { UpdateFlowFactory updates = new UpdateFlowFactory ( ) ; BranchFlowFactory branches = new BranchFlowFactory ( ) ; BranchFlowFactory . Simple branch = branches . simple ( in1 ) ; UpdateFlowFactory . Simple update = updates . simple ( branch . stop ) ; out1 . add ( update . out ) ; out1 . add ( branch . high ) ; out1 . add ( branch . low ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class InvalidFileNameOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public InvalidFileNameOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = InvalidFileNameExporterDesc . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class InvalidFileNameExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class NestedOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; private final Out < Ex1 > nested ; public NestedOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Out1ExporterDesc . class ) Out < Ex1 > output , @ Export ( name = "" , description = NestedOutExporterDesc . class ) Out < Ex1 > nested ) { this . input = input ; this . output = output ; this . nested = nested ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result1 = op . update ( input , ) ; output . add ( result1 . out ) ; Update result2 = op . update ( input , ) ; nested . add ( result2 . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class MissingPathExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return null ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class RootOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public RootOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = RootOutputExporterDesc . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class IndependentOutExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . processor . operator . FoldFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class StraightRendezvousFragments extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public StraightRendezvousFragments ( In < Ex1 > in1 , Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { FoldFlowFactory folds = new FoldFlowFactory ( ) ; UpdateFlowFactory updates = new UpdateFlowFactory ( ) ; FoldFlowFactory . Simple fold = folds . simple ( in1 ) ; UpdateFlowFactory . Simple update = updates . simple ( fold . out ) ; out1 . add ( update . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Out4ExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Out2ExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Out1ExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . processor . operator . LoggingFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; public class DuplicateFragments extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public DuplicateFragments ( In < Ex1 > in1 , Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; UpdateFlowFactory updates = new UpdateFlowFactory ( ) ; LoggingFlowFactory loggings = new LoggingFlowFactory ( ) ; UpdateFlowFactory . Simple update = updates . simple ( in1 ) ; LoggingFlowFactory . Simple logging = loggings . simple ( update . out ) ; UpdateFlowFactory . Simple copy1 = updates . simple ( update . out ) ; UpdateFlowFactory . Simple copy2 = updates . simple ( update . out ) ; out1 . add ( copy1 . out ) ; out1 . add ( copy2 . out ) ; core . stop ( logging . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class RootOutputExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MissingPathOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public MissingPathOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = MissingPathExporterDesc . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SingleOutputJob extends FlowDescription { private In < Ex1 > input ; private Out < Ex1 > output1 ; public SingleOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Out1ExporterDesc . class ) Out < Ex1 > output1 ) { this . input = input ; this . output1 = output1 ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output1 . add ( result . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class IndependentOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; private final Out < Ex1 > independent ; public IndependentOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Out1ExporterDesc . class ) Out < Ex1 > output , @ Export ( name = "" , description = IndependentOutExporterDesc . class ) Out < Ex1 > independent ) { this . input = input ; this . output = output ; this . independent = independent ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result1 = op . update ( input , ) ; output . add ( result1 . out ) ; Update result2 = op . update ( input , ) ; independent . add ( result2 . out ) ; } } package com . asakusafw . compiler . testing . flow ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Out3ExporterDesc extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . testing ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . testing . TemporaryIoProcessor ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . compiler . testing . flow . IndependentOutExporterDesc ; import com . asakusafw . compiler . testing . flow . IndependentOutputJob ; import com . asakusafw . compiler . testing . flow . InvalidFileNameOutputJob ; import com . asakusafw . compiler . testing . flow . MissingPathOutputJob ; import com . asakusafw . compiler . testing . flow . MultipleOutputJob ; import com . asakusafw . compiler . testing . flow . NestedOutExporterDesc ; import com . asakusafw . compiler . testing . flow . NestedOutputJob ; import com . asakusafw . compiler . testing . flow . Out1ExporterDesc ; import com . asakusafw . compiler . testing . flow . Out2ExporterDesc ; import com . asakusafw . compiler . testing . flow . Out3ExporterDesc ; import com . asakusafw . compiler . testing . flow . Out4ExporterDesc ; import com . asakusafw . compiler . testing . flow . RootOutputJob ; import com . asakusafw . compiler . testing . flow . SingleOutputJob ; import com . asakusafw . compiler . testing . flow . SingularOutputJob ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . value . IntOption ; public class TemporaryIoProcessorTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void validate ( ) throws Exception { tester . compileJobflow ( SingleOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_missing_path ( ) throws Exception { tester . compileJobflow ( MissingPathOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_inavalid_file_name ( ) throws Exception { tester . compileJobflow ( InvalidFileNameOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_singular_file ( ) throws Exception { tester . compileJobflow ( SingularOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_root ( ) throws Exception { tester . compileJobflow ( RootOutputJob . class ) ; } @ Test public void single ( ) throws Exception { JobflowInfo info = tester . compileJobflow ( SingleOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; } @ Test public void multiple ( ) throws Exception { JobflowInfo info = tester . compileJobflow ( MultipleOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( Out2ExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; List < Ex1 > out3 = getList ( Out3ExporterDesc . class ) ; checkSids ( out3 ) ; checlValues ( out3 , ) ; List < Ex1 > out4 = getList ( Out4ExporterDesc . class ) ; checkSids ( out4 ) ; checlValues ( out4 , ) ; } @ Test public void independent ( ) throws Exception { JobflowInfo info = tester . compileJobflow ( IndependentOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( IndependentOutExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; } @ Test public void nested ( ) throws Exception { JobflowInfo info = tester . compileJobflow ( NestedOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( NestedOutExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; } private void checkSids ( List < Ex1 > results ) { assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getSidOption ( ) . isNull ( ) , is ( true ) ) ; for ( int i = ; i < ; i ++ ) { assertThat ( results . get ( i ) . getSid ( ) , is ( ( long ) i ) ) ; } } private void checlValues ( List < Ex1 > results , int value ) { for ( Ex1 ex1 : results ) { assertThat ( ex1 . getValueOption ( ) , is ( new IntOption ( value ) ) ) ; } } private void writeTestData ( ModelOutput < Ex1 > source ) throws IOException { Ex1 value = new Ex1 ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; } private List < Ex1 > getList ( Class < ? extends TemporaryOutputDescription > exporter ) { try { TemporaryOutputDescription instance = exporter . newInstance ( ) ; return tester . getList ( Ex1 . class , Location . fromPath ( instance . getPathPrefix ( ) , '' ) , new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . compiler . flow . mock ; import java . io . IOException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . mapreduce . Counter ; import org . apache . hadoop . mapreduce . StatusReporter ; import org . apache . hadoop . mapreduce . TaskAttemptID ; import org . apache . hadoop . mapreduce . TaskInputOutputContext ; import com . asakusafw . runtime . core . Result ; public class MockOutput < KEYOUT , VALUEOUT > extends TaskInputOutputContext < Object , Object , KEYOUT , VALUEOUT > { private final Result < ? super KEYOUT > keyOut ; private final Result < ? super VALUEOUT > valueOut ; public static < K , V > MockOutput < K , V > create ( Result < K > keyOut , Result < V > valueOut ) { return new MockOutput < K , V > ( keyOut , valueOut ) ; } public MockOutput ( Result < ? super KEYOUT > keyOut , Result < ? super VALUEOUT > valueOut ) { super ( new Configuration ( false ) , new TaskAttemptID ( ) , null , null , new MockStatusReporter ( ) ) ; this . keyOut = keyOut ; this . valueOut = valueOut ; } @ Override public void write ( KEYOUT key , VALUEOUT value ) { keyOut . add ( key ) ; valueOut . add ( value ) ; } @ Override public boolean nextKeyValue ( ) throws IOException , InterruptedException { throw new UnsupportedOperationException ( ) ; } @ Override public Object getCurrentKey ( ) throws IOException , InterruptedException { throw new UnsupportedOperationException ( ) ; } @ Override public Object getCurrentValue ( ) throws IOException , InterruptedException { throw new UnsupportedOperationException ( ) ; } private static final class MockStatusReporter extends StatusReporter { MockStatusReporter ( ) { return ; } @ Override public Counter getCounter ( Enum < ? > name ) { return getCounter ( name . getDeclaringClass ( ) . getName ( ) , name . name ( ) ) ; } @ Override public Counter getCounter ( String group , String name ) { return new Counter ( ) { } ; } @ Override public void progress ( ) { return ; } @ Override public void setStatus ( String status ) { return ; } } } package com . asakusafw . compiler . flow ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Locale ; import java . util . Map ; import java . util . TreeMap ; import java . util . jar . JarEntry ; import java . util . jar . JarOutputStream ; import javax . tools . Diagnostic ; import javax . tools . DiagnosticCollector ; import javax . tools . FileObject ; import javax . tools . JavaCompiler ; import javax . tools . JavaCompiler . CompilationTask ; import javax . tools . JavaFileObject ; import javax . tools . ToolProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . batch . MockEmitter ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileClassFile ; import com . asakusafw . utils . java . jsr199 . testing . VolatileClassOutputManager ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . jsr199 . testing . VolatileResourceFile ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Name ; public class VolatilePackager extends FlowCompilingEnvironment . Initialized implements Packager { static final Logger LOG = LoggerFactory . getLogger ( VolatilePackager . class ) ; private static final Charset CHARSET = Charset . forName ( "" ) ; private final MockEmitter emitter ; Map < String , byte [ ] > contents ; public VolatilePackager ( ) { this . emitter = new MockEmitter ( ) ; this . contents = new TreeMap < String , byte [ ] > ( ) ; } public MockEmitter getEmitter ( ) { return emitter ; } @ Override public PrintWriter openWriter ( CompilationUnit source ) throws IOException { if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } return emitter . openFor ( source ) ; } @ Override public OutputStream openStream ( Name packageNameOrNull , String relativePath ) throws IOException { if ( relativePath == null ) { throw new IllegalArgumentException ( "" ) ; } StringBuilder buf = new StringBuilder ( ) ; if ( packageNameOrNull != null ) { buf . append ( packageNameOrNull . toNameString ( ) . replace ( '' , '' ) ) ; buf . append ( '' ) ; } buf . append ( relativePath . replace ( '' , '' ) ) ; final String name = buf . toString ( ) ; return new ByteArrayOutputStream ( ) { @ Override public void close ( ) throws IOException { contents . put ( name , toByteArray ( ) ) ; } } ; } @ Override public void build ( OutputStream output ) throws IOException { JarOutputStream jar = new JarOutputStream ( output ) ; try { compile ( jar ) ; } finally { jar . close ( ) ; } } @ Override public void packageSources ( OutputStream output ) throws IOException { JarOutputStream jar = new JarOutputStream ( output ) ; try { collect ( jar ) ; } finally { jar . close ( ) ; } } private void collect ( JarOutputStream jar ) throws IOException { assert jar != null ; for ( VolatileJavaFile file : emitter . getEmitted ( ) ) { String path = file . toUri ( ) . getPath ( ) ; JarEntry entry = new JarEntry ( path ) ; jar . putNextEntry ( entry ) ; jar . write ( file . getCharContent ( false ) . toString ( ) . getBytes ( CHARSET ) ) ; jar . closeEntry ( ) ; } } private void compile ( JarOutputStream jar ) throws IOException { JavaCompiler compiler = ToolProvider . getSystemJavaCompiler ( ) ; if ( compiler == null ) { throw new IllegalStateException ( "" ) ; } compile ( compiler , jar ) ; } private void compile ( JavaCompiler compiler , JarOutputStream jar ) throws IOException { assert compiler != null ; assert jar != null ; DiagnosticCollector < JavaFileObject > diagnostics = new DiagnosticCollector < JavaFileObject > ( ) ; VolatileClassOutputManager fileManager = new VolatileClassOutputManager ( compiler . getStandardFileManager ( diagnostics , Locale . getDefault ( ) , CHARSET ) ) ; try { List < String > arguments = Lists . create ( ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , CHARSET . name ( ) ) ; StringWriter errors = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( errors ) ; CompilationTask task = compiler . getTask ( pw , fileManager , diagnostics , arguments , Collections . < String > emptyList ( ) , emitter . getEmitted ( ) ) ; Boolean successed = task . call ( ) ; pw . close ( ) ; for ( Diagnostic < ? > diagnostic : diagnostics . getDiagnostics ( ) ) { switch ( diagnostic . getKind ( ) ) { case ERROR : case MANDATORY_WARNING : getEnvironment ( ) . error ( diagnostic . getMessage ( null ) ) ; break ; case WARNING : LOG . warn ( diagnostic . getMessage ( null ) ) ; break ; default : LOG . info ( diagnostic . getMessage ( null ) ) ; break ; } } if ( Boolean . TRUE . equals ( successed ) == false ) { throw new IOException ( MessageFormat . format ( "" , getEnvironment ( ) . getTargetId ( ) , errors . toString ( ) ) ) ; } for ( VolatileResourceFile file : fileManager . getResources ( ) ) { addEntry ( jar , file ) ; } for ( VolatileClassFile file : fileManager . getCompiled ( ) ) { addEntry ( jar , file ) ; } for ( Map . Entry < String , byte [ ] > entry : contents . entrySet ( ) ) { addEntry ( jar , entry . getKey ( ) , entry . getValue ( ) ) ; } } finally { fileManager . close ( ) ; } } private void addEntry ( JarOutputStream jar , String path , byte [ ] content ) throws IOException { assert jar != null ; assert path != null ; assert content != null ; JarEntry entry = new JarEntry ( path ) ; jar . putNextEntry ( entry ) ; jar . write ( content ) ; jar . closeEntry ( ) ; } private void addEntry ( JarOutputStream jar , FileObject file ) throws IOException { assert jar != null ; String path = file . toUri ( ) . getPath ( ) ; while ( path . startsWith ( "" ) ) { path = path . substring ( ) ; } JarEntry entry = new JarEntry ( path ) ; jar . putNextEntry ( entry ) ; InputStream input = file . openInputStream ( ) ; try { byte [ ] buffer = new byte [ ] ; while ( true ) { int read = input . read ( buffer ) ; if ( read < ) { break ; } jar . write ( buffer , , read ) ; } jar . closeEntry ( ) ; } finally { input . close ( ) ; } } } package com . asakusafw . compiler . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . example . NoShuffleStage ; import com . asakusafw . compiler . flow . example . SimpleShuffleStage ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory . Join ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; public class FlowCompilerTest { @ SuppressWarnings ( "" ) @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void mapOnly ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; FlowDescription flow = new NoShuffleStage ( in . flow ( ) , out . flow ( ) ) ; assertThat ( tester . runFlow ( flow ) , is ( true ) ) ; List < Ex1 > list = out . toList ( ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void withReduce ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < ExSummarized > out = tester . output ( ExSummarized . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; FlowDescription flow = new SimpleShuffleStage ( in . flow ( ) , out . flow ( ) ) ; assertThat ( tester . runFlow ( flow ) , is ( true ) ) ; List < ExSummarized > list = out . toList ( new Comparator < ExSummarized > ( ) { @ Override public int compare ( ExSummarized o1 , ExSummarized o2 ) { return o1 . getCountOption ( ) . compareTo ( o2 . getCountOption ( ) ) ; } } ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( list . get ( ) . getCount ( ) , is ( ) ) ; assertThat ( list . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( list . get ( ) . getCount ( ) , is ( ) ) ; } @ Test public void unifiedResources ( ) throws Exception { TestInput < Ex1 > mst = tester . input ( Ex1 . class , "" , DataSize . TINY ) ; TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex1 > in2 = tester . input ( Ex1 . class , "" ) ; TestOutput < ExJoined > out = tester . output ( ExJoined . class , "" ) ; Ex1 dMst = new Ex1 ( ) ; dMst . setSid ( ) ; dMst . setValue ( ) ; mst . add ( dMst ) ; Ex1 dIn1 = new Ex1 ( ) ; dIn1 . setSid ( ) ; dIn1 . setValue ( ) ; in1 . add ( dIn1 ) ; Ex1 dIn2 = new Ex1 ( ) ; dIn2 . setSid ( ) ; dIn2 . setValue ( ) ; in2 . add ( dIn2 ) ; final In < Ex1 > pMst = mst . flow ( ) ; final In < Ex1 > pIn1 = in1 . flow ( ) ; final In < Ex1 > pIn2 = in2 . flow ( ) ; final Out < ExJoined > pOut = out . flow ( ) ; FlowDescription flow = new FlowDescription ( ) { @ Override protected void describe ( ) { CoreOperatorFactory c = new CoreOperatorFactory ( ) ; Restructure < Ex2 > r1 = c . restructure ( pIn1 , Ex2 . class ) ; Restructure < Ex2 > r2 = c . restructure ( pIn2 , Ex2 . class ) ; MasterJoinFlowFactory f = new MasterJoinFlowFactory ( ) ; Join join = f . join ( pMst , c . confluent ( r1 , r2 ) ) ; c . stop ( join . missed ) ; pOut . add ( join . joined ) ; } } ; assertThat ( tester . runFlow ( flow ) , is ( true ) ) ; assertThat ( out . toList ( ) . size ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . lang . reflect . Constructor ; import java . lang . reflect . Field ; import java . lang . reflect . Method ; import java . util . List ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . apache . hadoop . io . Writable ; import org . junit . After ; import org . junit . Before ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . plan . StagePlanner ; import com . asakusafw . compiler . flow . stage . CompiledShuffle ; import com . asakusafw . compiler . flow . stage . CompiledType ; import com . asakusafw . compiler . flow . stage . MapFragmentEmitter ; import com . asakusafw . compiler . flow . stage . ReduceFragmentEmitter ; import com . asakusafw . compiler . flow . stage . ShuffleAnalyzer ; import com . asakusafw . compiler . flow . stage . ShuffleGroupingComparatorEmitter ; import com . asakusafw . compiler . flow . stage . ShuffleKeyEmitter ; import com . asakusafw . compiler . flow . stage . ShuffleModel ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . ShufflePartitionerEmitter ; import com . asakusafw . compiler . flow . stage . ShuffleSortComparatorEmitter ; import com . asakusafw . compiler . flow . stage . ShuffleValueEmitter ; import com . asakusafw . compiler . flow . stage . StageAnalyzer ; import com . asakusafw . compiler . flow . stage . StageCompiler ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . MapUnit ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . compiler . repository . SpiDataClassRepository ; import com . asakusafw . compiler . repository . SpiExternalIoDescriptionProcessorRepository ; import com . asakusafw . compiler . repository . SpiFlowElementProcessorRepository ; import com . asakusafw . compiler . repository . SpiFlowGraphRewriterRepository ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class JobflowCompilerTestRoot { protected boolean dump = true ; private final VolatileCompiler javaCompiler = new VolatileCompiler ( ) ; private VolatilePackager packager = new VolatilePackager ( ) ; protected FlowCompilingEnvironment environment ; @ Before public void setUp ( ) throws Exception { packager = new VolatilePackager ( ) ; FlowCompilerConfiguration config = new FlowCompilerConfiguration ( ) ; config . setBatchId ( "" ) ; config . setFlowId ( "" ) ; config . setFactory ( Models . getModelFactory ( ) ) ; config . setProcessors ( new SpiFlowElementProcessorRepository ( ) ) ; config . setExternals ( new SpiExternalIoDescriptionProcessorRepository ( ) ) ; config . setDataClasses ( new SpiDataClassRepository ( ) ) ; config . setGraphRewriters ( new SpiFlowGraphRewriterRepository ( ) ) ; config . setPackager ( packager ) ; config . setRootPackageName ( "" ) ; config . setRootLocation ( Location . fromPath ( "" , '' ) ) ; config . setServiceClassLoader ( getClass ( ) . getClassLoader ( ) ) ; config . setOptions ( new FlowCompilerOptions ( ) ) ; config . setBuildId ( "" ) ; environment = new FlowCompilingEnvironment ( config ) ; environment . bless ( ) ; } @ After public void tearDown ( ) throws Exception { javaCompiler . close ( ) ; } protected List < StageModel > compile ( Class < ? extends FlowDescription > aClass ) { assert aClass != null ; StageGraph graph = jfToStageGraph ( aClass ) ; return compileStages ( graph ) ; } protected StageGraph jfToStageGraph ( Class < ? extends FlowDescription > aClass ) { assert aClass != null ; JobFlowDriver analyzed = JobFlowDriver . analyze ( aClass ) ; assertThat ( analyzed . getDiagnostics ( ) . toString ( ) , analyzed . hasError ( ) , is ( false ) ) ; JobFlowClass flow = analyzed . getJobFlowClass ( ) ; FlowGraph flowGraph = flow . getGraph ( ) ; return flowToStageGraph ( flowGraph ) ; } private StageGraph flowToStageGraph ( FlowGraph flowGraph ) { assert flowGraph != null ; StagePlanner planner = new StagePlanner ( environment . getGraphRewriters ( ) . getRewriters ( ) , environment . getOptions ( ) ) ; StageGraph planned = planner . plan ( flowGraph ) ; assertThat ( planner . getDiagnostics ( ) . toString ( ) , planner . getDiagnostics ( ) . isEmpty ( ) , is ( true ) ) ; return planned ; } protected List < StageModel > compileStages ( StageGraph graph ) { try { return new StageCompiler ( environment ) . compile ( graph ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } protected StageModel compileFragments ( StageBlock block ) throws IOException { ShuffleModel shuffle = compileShuffle ( block ) ; StageModel stage = new StageAnalyzer ( environment ) . analyze ( block , shuffle ) ; for ( MapUnit unit : stage . getMapUnits ( ) ) { for ( Fragment fragment : unit . getFragments ( ) ) { compile ( fragment , stage ) ; } } for ( ReduceUnit unit : stage . getReduceUnits ( ) ) { for ( Fragment fragment : unit . getFragments ( ) ) { compile ( fragment , stage ) ; } } return stage ; } private void compile ( Fragment fragment , StageModel stage ) throws IOException { if ( fragment . isRendezvous ( ) ) { CompiledType compiled = new ReduceFragmentEmitter ( environment ) . emit ( fragment , stage . getShuffleModel ( ) , stage . getStageBlock ( ) ) ; fragment . setCompiled ( compiled ) ; } else { CompiledType compiled = new MapFragmentEmitter ( environment ) . emit ( fragment , stage . getStageBlock ( ) ) ; fragment . setCompiled ( compiled ) ; } } protected ShuffleModel compileShuffle ( StageBlock block ) throws IOException { ShuffleModel shuffle = new ShuffleAnalyzer ( environment ) . analyze ( block ) ; assertThat ( environment . hasError ( ) , is ( false ) ) ; if ( shuffle == null ) { return null ; } Name keyTypeName = new ShuffleKeyEmitter ( environment ) . emit ( shuffle ) ; Name valueTypeName = new ShuffleValueEmitter ( environment ) . emit ( shuffle ) ; Name groupComparatorTypeName = new ShuffleGroupingComparatorEmitter ( environment ) . emit ( shuffle , keyTypeName ) ; Name sortComparatorTypeName = new ShuffleSortComparatorEmitter ( environment ) . emit ( shuffle , keyTypeName ) ; Name partitionerTypeName = new ShufflePartitionerEmitter ( environment ) . emit ( shuffle , keyTypeName , valueTypeName ) ; CompiledShuffle compiled = new CompiledShuffle ( keyTypeName , valueTypeName , groupComparatorTypeName , sortComparatorTypeName , partitionerTypeName ) ; shuffle . setCompiled ( compiled ) ; return shuffle ; } protected Object create ( ClassLoader loader , Name name , Object ... arguments ) { try { Class < ? > loaded = loader . loadClass ( name . toNameString ( ) ) ; for ( Constructor < ? > ctor : loaded . getConstructors ( ) ) { if ( ctor . getParameterTypes ( ) . length == arguments . length ) { return ctor . newInstance ( arguments ) ; } } throw new AssertionError ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ SuppressWarnings ( "" ) protected < T > Result < T > createResult ( ClassLoader loader , Name name , Object ... arguments ) { return ( Result < T > ) create ( loader , name , arguments ) ; } @ SuppressWarnings ( "" ) protected < K extends Writable , V extends Writable > Rendezvous < V > createRendezvous ( ClassLoader loader , Name name , Object ... arguments ) { return ( Rendezvous < V > ) create ( loader , name , arguments ) ; } protected Object invoke ( Object object , String name , Object ... arguments ) { try { for ( Method method : object . getClass ( ) . getMethods ( ) ) { if ( method . getName ( ) . equals ( name ) ) { return method . invoke ( object , arguments ) ; } } } catch ( Exception e ) { throw new AssertionError ( e ) ; } throw new AssertionError ( name ) ; } protected Object access ( Object object , String name ) { try { for ( Field field : object . getClass ( ) . getFields ( ) ) { if ( field . getName ( ) . equals ( name ) ) { return field . get ( object ) ; } } } catch ( Exception e ) { throw new AssertionError ( e ) ; } throw new AssertionError ( name ) ; } protected SegmentedWritable createShuffleKey ( ClassLoader loader , StageModel stage ) { assertThat ( stage . getShuffleModel ( ) , not ( nullValue ( ) ) ) ; Name name = stage . getShuffleModel ( ) . getCompiled ( ) . getKeyTypeName ( ) ; return ( SegmentedWritable ) create ( loader , name ) ; } protected SegmentedWritable createShuffleValue ( ClassLoader loader , StageModel stage ) { assertThat ( stage . getShuffleModel ( ) , not ( nullValue ( ) ) ) ; Name name = stage . getShuffleModel ( ) . getCompiled ( ) . getValueTypeName ( ) ; return ( SegmentedWritable ) create ( loader , name ) ; } protected void setShuffleKey ( Segment segment , SegmentedWritable key , Object toSet ) { String name = Naming . getShuffleKeySetter ( segment . getPortId ( ) ) ; try { Method method = key . getClass ( ) . getMethod ( name , toSet . getClass ( ) ) ; method . invoke ( key , toSet ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected void setShuffleValue ( Segment segment , SegmentedWritable value , Object toSet ) { String name = Naming . getShuffleValueSetter ( segment . getPortId ( ) ) ; try { Method method = value . getClass ( ) . getMethod ( name , toSet . getClass ( ) ) ; method . invoke ( value , toSet ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected void setShuffleKeyValue ( Segment segment , SegmentedWritable key , SegmentedWritable value , Object toSet ) { setShuffleKey ( segment , key , toSet ) ; setShuffleValue ( segment , value , toSet ) ; } protected Object getShuffleValue ( Segment segment , SegmentedWritable value ) { String name = Naming . getShuffleValueGetter ( segment . getPortId ( ) ) ; try { Method method = value . getClass ( ) . getMethod ( name ) ; return method . invoke ( value ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected ClassLoader start ( ) { List < Diagnostic < ? extends JavaFileObject > > diagnostics = doCompile ( ) ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) != Diagnostic . Kind . NOTE ) { throw new AssertionError ( diagnostics ) ; } } return javaCompiler . getClassLoader ( ) ; } private List < Diagnostic < ? extends JavaFileObject > > doCompile ( ) { List < VolatileJavaFile > sources = packager . getEmitter ( ) . getEmitted ( ) ; if ( dump ) { for ( JavaFileObject java : sources ) { try { System . out . println ( "" + java . getName ( ) ) ; System . out . println ( java . getCharContent ( true ) ) ; } catch ( IOException e ) { } } } for ( JavaFileObject java : sources ) { javaCompiler . addSource ( java ) ; } if ( sources . isEmpty ( ) ) { javaCompiler . addSource ( new VolatileJavaFile ( "" , "" ) ) ; } List < Diagnostic < ? extends JavaFileObject > > diagnostics = javaCompiler . doCompile ( ) ; if ( dump ) { for ( Diagnostic < ? extends JavaFileObject > d : diagnostics ) { System . out . println ( "" ) ; System . out . println ( d ) ; } } return diagnostics ; } } package com . asakusafw . compiler . flow . plan ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . compiler . flow . FlowGraphGenerator ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; public class StageBlockTest { @ Test public void isEmpty_true ( ) { StageBlock stage = new StageBlock ( set ( ) , set ( ) ) ; assertThat ( stage . isEmpty ( ) , is ( true ) ) ; } @ Test public void isEmpty_hasMapper ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; StageBlock stage = new StageBlock ( set ( b1 ) , set ( ) ) ; assertThat ( stage . isEmpty ( ) , is ( false ) ) ; } @ Test public void isEmpty_hasReducer ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b2 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , b2 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b2 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; b2 . detach ( ) ; bout . detach ( ) ; StageBlock stage = new StageBlock ( set ( b1 ) , set ( b2 ) ) ; assertThat ( stage . isEmpty ( ) , is ( false ) ) ; } @ Test public void compaction_stable ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; StageBlock stage = new StageBlock ( set ( b1 ) , set ( ) ) ; assertThat ( stage . isEmpty ( ) , is ( false ) ) ; } @ Test public void compaction_hasReducer ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b2 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , b2 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b2 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; b2 . detach ( ) ; bout . detach ( ) ; StageBlock stage = new StageBlock ( set ( b1 ) , set ( b2 ) ) ; assertThat ( stage . compaction ( ) , is ( false ) ) ; } @ Test public void compaction_bypass ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) , gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) , gen . output ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; StageBlock stage = new StageBlock ( set ( b1 ) , set ( ) ) ; assertThat ( stage . compaction ( ) , is ( true ) ) ; assertThat ( stage . getMapBlocks ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockInputs ( ) . get ( ) . getElementPort ( ) . getDescription ( ) , is ( gen . input ( "" ) . getDescription ( ) ) ) ; assertThat ( b1 . getBlockOutputs ( ) . get ( ) . getElementPort ( ) . getDescription ( ) , is ( gen . output ( "" ) . getDescription ( ) ) ) ; FlowBlock . Output binOut = bin . getBlockOutputs ( ) . get ( ) ; FlowBlock . Input boutIn = bout . getBlockInputs ( ) . get ( ) ; assertThat ( binOut . getConnections ( ) . size ( ) , is ( ) ) ; assertThat ( boutIn . getConnections ( ) . size ( ) , is ( ) ) ; assertThat ( FlowBlock . isConnected ( binOut , boutIn ) , is ( true ) ) ; } @ Test public void compaction_removeBlock ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; StageBlock stage = new StageBlock ( set ( b1 ) , set ( ) ) ; assertThat ( stage . compaction ( ) , is ( true ) ) ; assertThat ( stage . getMapBlocks ( ) . size ( ) , is ( ) ) ; } private Set < FlowBlock > set ( FlowBlock ... blocks ) { Set < FlowBlock > results = Sets . create ( ) ; Collections . addAll ( results , blocks ) ; return results ; } } package com . asakusafw . compiler . flow . plan ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . junit . runners . Parameterized ; import org . junit . runners . Parameterized . Parameters ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowCompilerOptions . GenericOptionValue ; import com . asakusafw . compiler . flow . FlowGraphGenerator ; import com . asakusafw . compiler . flow . FlowGraphRewriter ; import com . asakusafw . vocabulary . flow . graph . Connectivity ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; @ RunWith ( Parameterized . class ) public class StagePlannerTest { private final FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; private final GenericOptionValue opt ; @ Parameters public static List < Object [ ] > parameters ( ) { return Arrays . asList ( new Object [ ] [ ] { { GenericOptionValue . DISABLED } , { GenericOptionValue . ENABLED } , } ) ; } public StagePlannerTest ( GenericOptionValue opt ) { this . opt = opt ; } private StagePlanner getPlanner ( ) { FlowCompilerOptions options = new FlowCompilerOptions ( ) ; options . setCompressConcurrentStage ( false ) ; options . setCompressFlowPart ( false ) ; options . setEnableCombiner ( false ) ; options . setEnableDebugLogging ( true ) ; options . setHashJoinForSmall ( false ) ; options . setHashJoinForTiny ( false ) ; options . putExtraAttribute ( StagePlanner . KEY_COMPRESS_FLOW_BLOCK_GROUP , opt . getSymbol ( ) ) ; return new StagePlanner ( Collections . < FlowGraphRewriter > emptyList ( ) , options ) ; } @ Test public void validate_ok ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; assertThat ( getPlanner ( ) . validate ( graph ) , is ( true ) ) ; } @ Test public void validate_notInConnected ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; assertThat ( getPlanner ( ) . validate ( graph ) , is ( false ) ) ; } @ Test public void validate_notOutConnected ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; assertThat ( getPlanner ( ) . validate ( graph ) , is ( false ) ) ; } @ Test public void validate_notOutConnected_butOptional ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" , Connectivity . OPTIONAL ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; assertThat ( getPlanner ( ) . validate ( graph ) , is ( true ) ) ; } @ Test public void validate_looped ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; assertThat ( getPlanner ( ) . validate ( graph ) , is ( false ) ) ; } @ Test public void validate_componentError ( ) { FlowGraphGenerator comp = new FlowGraphGenerator ( ) ; comp . defineInput ( "" ) ; comp . defineOperator ( "" , "" , "" ) ; comp . defineOutput ( "" ) ; comp . connect ( "" , "" ) . connect ( "" , "" ) ; gen . defineInput ( "" ) ; gen . defineFlowPart ( "" , comp . toGraph ( ) ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; assertThat ( getPlanner ( ) . validate ( graph ) , is ( false ) ) ; } @ Test public void insertCheckpoints_insert ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . insertCheckpoints ( graph ) ; assertThat ( FlowGraphUtil . collectBoundaries ( graph ) , not ( gen . getAsSet ( "" , "" , "" , "" , "" ) ) ) ; Set < FlowElement > a = FlowGraphUtil . getSucceedingBoundaries ( gen . output ( "" ) ) ; Set < FlowElement > b = FlowGraphUtil . getSucceedingBoundaries ( gen . output ( "" ) ) ; assertThat ( a . isEmpty ( ) , is ( false ) ) ; assertThat ( b . isEmpty ( ) , is ( false ) ) ; for ( FlowElement elem : a ) { assertThat ( FlowGraphUtil . isStageBoundary ( elem ) , is ( true ) ) ; } for ( FlowElement elem : b ) { assertThat ( FlowGraphUtil . isStageBoundary ( elem ) , is ( true ) ) ; } } @ Test public void insertCheckpoints_nothing ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . insertCheckpoints ( graph ) ; assertThat ( FlowGraphUtil . collectBoundaries ( graph ) , is ( gen . getAsSet ( "" , "" , "" , "" ) ) ) ; } @ Test public void insertIdentities_nothing ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . insertIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; } @ Test public void insertIdentities_stage_shuffle ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . insertIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , not ( gen . getAsSet ( "" , "" , "" , "" ) ) ) ; FlowElement id = succ ( gen . get ( "" ) ) ; assertThat ( FlowGraphUtil . isIdentity ( id ) , is ( true ) ) ; FlowElement op1 = succ ( id ) ; assertThat ( op1 , is ( gen . get ( "" ) ) ) ; FlowElement op2 = succ ( op1 ) ; assertThat ( op2 , is ( gen . get ( "" ) ) ) ; FlowElement out = succ ( op2 ) ; assertThat ( out , is ( gen . get ( "" ) ) ) ; } @ Test public void insertIdentities_stage_stage ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . STAGE ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . insertIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , not ( gen . getAsSet ( "" , "" , "" , "" ) ) ) ; FlowElement id = succ ( gen . get ( "" ) ) ; assertThat ( FlowGraphUtil . isIdentity ( id ) , is ( true ) ) ; FlowElement op1 = succ ( id ) ; assertThat ( op1 , is ( gen . get ( "" ) ) ) ; FlowElement op2 = succ ( op1 ) ; assertThat ( op2 , is ( gen . get ( "" ) ) ) ; FlowElement out = succ ( op2 ) ; assertThat ( out , is ( gen . get ( "" ) ) ) ; } @ Test public void insertIdentities_shuffle_stage ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . insertIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" , "" ) ) ) ; } @ Test public void splitIdentities_nothing ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . splitIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; } @ Test public void splitIdentities_split ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . splitIdentities ( graph ) ; Set < FlowElement > succ1 = FlowGraphUtil . getSuccessors ( gen . get ( "" ) ) ; Set < FlowElement > succ2 = FlowGraphUtil . getSuccessors ( gen . get ( "" ) ) ; assertThat ( succ1 . size ( ) , is ( ) ) ; assertThat ( succ2 . size ( ) , is ( ) ) ; Iterator < FlowElement > iter1 = succ1 . iterator ( ) ; FlowElement elem1 = iter1 . next ( ) ; FlowElement elem2 = iter1 . next ( ) ; Iterator < FlowElement > iter2 = succ2 . iterator ( ) ; FlowElement elem3 = iter2 . next ( ) ; FlowElement elem4 = iter2 . next ( ) ; assertThat ( FlowGraphUtil . getSuccessors ( elem1 ) . size ( ) , is ( ) ) ; assertThat ( FlowGraphUtil . getSuccessors ( elem2 ) . size ( ) , is ( ) ) ; assertThat ( FlowGraphUtil . getSuccessors ( elem3 ) . size ( ) , is ( ) ) ; assertThat ( FlowGraphUtil . getSuccessors ( elem4 ) . size ( ) , is ( ) ) ; assertThat ( FlowGraphUtil . getPredecessors ( elem1 ) . size ( ) , is ( ) ) ; assertThat ( FlowGraphUtil . getPredecessors ( elem2 ) . size ( ) , is ( ) ) ; assertThat ( FlowGraphUtil . getPredecessors ( elem3 ) . size ( ) , is ( ) ) ; assertThat ( FlowGraphUtil . getPredecessors ( elem4 ) . size ( ) , is ( ) ) ; assertThat ( elem1 , not ( sameInstance ( elem3 ) ) ) ; assertThat ( elem1 , not ( sameInstance ( elem4 ) ) ) ; assertThat ( elem2 , not ( sameInstance ( elem3 ) ) ) ; assertThat ( elem2 , not ( sameInstance ( elem4 ) ) ) ; } @ Test public void splitIdentities_yetSplitted ( ) { gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . splitIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" , "" , "" ) ) ) ; } @ Test public void reduceIdentities_op_op ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . reduceIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" , "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; } @ Test public void reduceIdentities_op_id ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . reduceIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; } @ Test public void reduceIdentities_id_op ( ) { gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . reduceIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; } @ Test public void reduceIdentities_mapBody ( ) { gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . reduceIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; } @ Test public void reduceIdentities_reduceBody ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . reduceIdentities ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; } @ Test public void normalizeFlowGraph ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . normalizeFlowGraph ( graph ) ; assertThat ( FlowGraphUtil . collectElements ( graph ) , is ( gen . getAsSet ( "" , "" , "" , "" ) ) ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( FlowGraphUtil . getSuccessors ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( pred ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( pred ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( pred ( gen . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; } @ Test public void normalizeFlowGraph_component ( ) { FlowGraphGenerator comp = new FlowGraphGenerator ( ) ; comp . defineInput ( "" ) ; comp . defineOperator ( "" , "" , "" ) ; comp . definePseud ( "" ) ; comp . defineOutput ( "" ) ; comp . defineOutput ( "" ) ; comp . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; comp . connect ( "" , "" ) ; gen . defineInput ( "" ) ; gen . defineFlowPart ( "" , comp . toGraph ( ) ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; getPlanner ( ) . normalizeFlowGraph ( graph ) ; deletePseuds ( graph ) ; assertThat ( succ ( gen . get ( "" ) ) , is ( comp . get ( "" ) ) ) ; assertThat ( succ ( comp . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; assertThat ( pred ( gen . get ( "" ) ) , is ( comp . get ( "" ) ) ) ; assertThat ( pred ( comp . get ( "" ) ) , is ( gen . get ( "" ) ) ) ; } @ Test public void plan_through ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; StageGraph stages = getPlanner ( ) . plan ( gen . toGraph ( ) ) ; assertThat ( stages . getInput ( ) . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getOutput ( ) . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getStages ( ) . size ( ) , is ( ) ) ; assertThat ( FlowBlock . isConnected ( stages . getInput ( ) . getBlockOutputs ( ) . get ( ) , stages . getOutput ( ) . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; } @ Test public void plan_singleMapper ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; StageGraph stages = getPlanner ( ) . plan ( gen . toGraph ( ) ) ; assertThat ( stages . getInput ( ) . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getOutput ( ) . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getStages ( ) . size ( ) , is ( ) ) ; StageBlock mr = stages . getStages ( ) . get ( ) ; assertThat ( mr . getMapBlocks ( ) . size ( ) , is ( ) ) ; assertThat ( mr . hasReduceBlocks ( ) , is ( false ) ) ; FlowBlock mapper = single ( mr . getMapBlocks ( ) ) ; assertThat ( FlowBlock . isConnected ( stages . getInput ( ) . getBlockOutputs ( ) . get ( ) , mapper . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( mapper . getBlockOutputs ( ) . get ( ) , stages . getOutput ( ) . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( mapper . getElements ( ) . size ( ) , is ( ) ) ; FlowElement mapperOp = single ( mapper . getElements ( ) ) ; assertThat ( mapperOp . getDescription ( ) , is ( gen . desc ( "" ) ) ) ; } @ Test public void plan_singleReducer ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; StageGraph stages = getPlanner ( ) . plan ( gen . toGraph ( ) ) ; assertThat ( stages . getInput ( ) . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getOutput ( ) . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getStages ( ) . size ( ) , is ( ) ) ; StageBlock mr = stages . getStages ( ) . get ( ) ; assertThat ( mr . getMapBlocks ( ) . size ( ) , is ( ) ) ; assertThat ( mr . getReduceBlocks ( ) . isEmpty ( ) , is ( false ) ) ; FlowBlock mapper = single ( mr . getMapBlocks ( ) ) ; FlowBlock reducer = single ( mr . getReduceBlocks ( ) ) ; assertThat ( FlowBlock . isConnected ( stages . getInput ( ) . getBlockOutputs ( ) . get ( ) , mapper . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( mapper . getBlockOutputs ( ) . get ( ) , reducer . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( reducer . getBlockOutputs ( ) . get ( ) , stages . getOutput ( ) . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( mapper . getElements ( ) . size ( ) , is ( ) ) ; FlowElement mapperOp = single ( mapper . getElements ( ) ) ; assertThat ( FlowGraphUtil . isIdentity ( mapperOp ) , is ( true ) ) ; assertThat ( reducer . getElements ( ) . size ( ) , is ( ) ) ; FlowElement reducerOp = single ( reducer . getElements ( ) ) ; assertThat ( reducerOp . getDescription ( ) , is ( gen . desc ( "" ) ) ) ; } @ Test public void plan_singleMapReduce ( ) { gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; StageGraph stages = getPlanner ( ) . plan ( gen . toGraph ( ) ) ; assertThat ( stages . getInput ( ) . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getOutput ( ) . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getStages ( ) . size ( ) , is ( ) ) ; StageBlock mr = stages . getStages ( ) . get ( ) ; assertThat ( mr . getMapBlocks ( ) . size ( ) , is ( ) ) ; assertThat ( mr . getReduceBlocks ( ) . isEmpty ( ) , is ( false ) ) ; FlowBlock mapper = single ( mr . getMapBlocks ( ) ) ; FlowBlock reducer = single ( mr . getReduceBlocks ( ) ) ; assertThat ( FlowBlock . isConnected ( stages . getInput ( ) . getBlockOutputs ( ) . get ( ) , mapper . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( mapper . getBlockOutputs ( ) . get ( ) , reducer . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( reducer . getBlockOutputs ( ) . get ( ) , stages . getOutput ( ) . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( mapper . getElements ( ) . size ( ) , is ( ) ) ; FlowElement mapperOp = single ( mapper . getElements ( ) ) ; assertThat ( mapperOp . getDescription ( ) , is ( gen . desc ( "" ) ) ) ; assertThat ( reducer . getElements ( ) . size ( ) , is ( ) ) ; FlowElement reducerOp = single ( reducer . getElements ( ) ) ; assertThat ( reducerOp . getDescription ( ) , is ( gen . desc ( "" ) ) ) ; } @ Test public void plan_flowpart ( ) { FlowGraphGenerator comp = new FlowGraphGenerator ( ) ; comp . defineInput ( "" ) ; comp . defineOperator ( "" , "" , "" ) ; comp . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; comp . defineOutput ( "" ) ; comp . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . defineInput ( "" ) ; gen . defineFlowPart ( "" , comp . toGraph ( ) ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; StageGraph stages = getPlanner ( ) . plan ( gen . toGraph ( ) ) ; assertThat ( stages . getInput ( ) . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getOutput ( ) . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getStages ( ) . size ( ) , is ( ) ) ; StageBlock mr = stages . getStages ( ) . get ( ) ; assertThat ( mr . getMapBlocks ( ) . size ( ) , is ( ) ) ; assertThat ( mr . getReduceBlocks ( ) . isEmpty ( ) , is ( false ) ) ; FlowBlock mapper = single ( mr . getMapBlocks ( ) ) ; FlowBlock reducer = single ( mr . getReduceBlocks ( ) ) ; assertThat ( FlowBlock . isConnected ( stages . getInput ( ) . getBlockOutputs ( ) . get ( ) , mapper . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( mapper . getBlockOutputs ( ) . get ( ) , reducer . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( reducer . getBlockOutputs ( ) . get ( ) , stages . getOutput ( ) . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( mapper . getElements ( ) . size ( ) , is ( ) ) ; FlowElement mapperOp = single ( mapper . getElements ( ) ) ; assertThat ( mapperOp . getDescription ( ) , is ( comp . desc ( "" ) ) ) ; assertThat ( reducer . getElements ( ) . size ( ) , is ( ) ) ; FlowElement reducerOp = single ( reducer . getElements ( ) ) ; assertThat ( reducerOp . getDescription ( ) , is ( comp . desc ( "" ) ) ) ; } @ Test public void plan_flowpart_nested ( ) { FlowGraphGenerator fp2 = new FlowGraphGenerator ( ) ; fp2 . defineInput ( "" ) ; fp2 . defineOperator ( "" , "" , "" ) ; fp2 . defineOutput ( "" ) ; fp2 . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraphGenerator fp1 = new FlowGraphGenerator ( ) ; fp1 . defineInput ( "" ) ; fp1 . defineFlowPart ( "" , fp2 . toGraph ( ) ) ; fp1 . defineOutput ( "" ) ; fp1 . connect ( "" , "" ) . connect ( "" , "" ) ; gen . defineInput ( "" ) ; gen . defineFlowPart ( "" , fp1 . toGraph ( ) ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; StageGraph stages = getPlanner ( ) . plan ( gen . toGraph ( ) ) ; assertThat ( stages . getInput ( ) . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getOutput ( ) . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getStages ( ) . size ( ) , is ( ) ) ; StageBlock mr = stages . getStages ( ) . get ( ) ; assertThat ( mr . getMapBlocks ( ) . size ( ) , is ( ) ) ; assertThat ( mr . getReduceBlocks ( ) . isEmpty ( ) , is ( true ) ) ; FlowBlock mapper = single ( mr . getMapBlocks ( ) ) ; assertThat ( FlowBlock . isConnected ( stages . getInput ( ) . getBlockOutputs ( ) . get ( ) , mapper . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( mapper . getBlockOutputs ( ) . get ( ) , stages . getOutput ( ) . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( mapper . getElements ( ) . size ( ) , is ( ) ) ; FlowElement mapperOp = single ( mapper . getElements ( ) ) ; assertThat ( mapperOp . getDescription ( ) , is ( fp2 . desc ( "" ) ) ) ; } @ Test public void plan_flowpart_deep ( ) { FlowGraphGenerator fp4 = new FlowGraphGenerator ( ) ; fp4 . defineInput ( "" ) ; fp4 . defineOperator ( "" , "" , "" ) ; fp4 . defineOutput ( "" ) ; fp4 . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraphGenerator fp3 = new FlowGraphGenerator ( ) ; fp3 . defineInput ( "" ) ; fp3 . defineFlowPart ( "" , fp4 . toGraph ( ) ) ; fp3 . defineOutput ( "" ) ; fp3 . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraphGenerator fp2 = new FlowGraphGenerator ( ) ; fp2 . defineInput ( "" ) ; fp2 . defineFlowPart ( "" , fp3 . toGraph ( ) ) ; fp2 . defineOutput ( "" ) ; fp2 . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraphGenerator fp1 = new FlowGraphGenerator ( ) ; fp1 . defineInput ( "" ) ; fp1 . defineFlowPart ( "" , fp2 . toGraph ( ) ) ; fp1 . defineOutput ( "" ) ; fp1 . connect ( "" , "" ) . connect ( "" , "" ) ; gen . defineInput ( "" ) ; gen . defineFlowPart ( "" , fp1 . toGraph ( ) ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; StageGraph stages = getPlanner ( ) . plan ( gen . toGraph ( ) ) ; assertThat ( stages . getInput ( ) . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getOutput ( ) . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getStages ( ) . size ( ) , is ( ) ) ; StageBlock mr = stages . getStages ( ) . get ( ) ; assertThat ( mr . getMapBlocks ( ) . size ( ) , is ( ) ) ; assertThat ( mr . getReduceBlocks ( ) . isEmpty ( ) , is ( true ) ) ; FlowBlock mapper = single ( mr . getMapBlocks ( ) ) ; assertThat ( FlowBlock . isConnected ( stages . getInput ( ) . getBlockOutputs ( ) . get ( ) , mapper . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( mapper . getBlockOutputs ( ) . get ( ) , stages . getOutput ( ) . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( mapper . getElements ( ) . size ( ) , is ( ) ) ; FlowElement mapperOp = single ( mapper . getElements ( ) ) ; assertThat ( mapperOp . getDescription ( ) , is ( fp4 . desc ( "" ) ) ) ; } @ Test public void plan_flowpart_wide ( ) { FlowGraphGenerator fp2a = new FlowGraphGenerator ( ) ; fp2a . defineInput ( "" ) ; fp2a . defineOperator ( "" , "" , "" ) ; fp2a . defineOutput ( "" ) ; fp2a . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraphGenerator fp2b = new FlowGraphGenerator ( ) ; fp2b . defineInput ( "" ) ; fp2b . defineOperator ( "" , "" , "" ) ; fp2b . defineOutput ( "" ) ; fp2b . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraphGenerator fp1 = new FlowGraphGenerator ( ) ; fp1 . defineInput ( "" ) ; fp1 . defineFlowPart ( "" , fp2a . toGraph ( ) ) ; fp1 . defineFlowPart ( "" , fp2b . toGraph ( ) ) ; fp1 . defineOutput ( "" ) ; fp1 . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . defineInput ( "" ) ; gen . defineFlowPart ( "" , fp1 . toGraph ( ) ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowCompilerOptions options = new FlowCompilerOptions ( ) ; options . setCompressFlowPart ( true ) ; StagePlanner planner = new StagePlanner ( Collections . < FlowGraphRewriter > emptyList ( ) , options ) ; StageGraph stages = planner . plan ( gen . toGraph ( ) ) ; assertThat ( stages . getInput ( ) . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getOutput ( ) . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( stages . getStages ( ) . size ( ) , is ( ) ) ; StageBlock mr = stages . getStages ( ) . get ( ) ; assertThat ( mr . getMapBlocks ( ) . size ( ) , is ( ) ) ; assertThat ( mr . getReduceBlocks ( ) . isEmpty ( ) , is ( true ) ) ; FlowBlock mapper = single ( mr . getMapBlocks ( ) ) ; assertThat ( FlowBlock . isConnected ( stages . getInput ( ) . getBlockOutputs ( ) . get ( ) , mapper . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( FlowBlock . isConnected ( mapper . getBlockOutputs ( ) . get ( ) , stages . getOutput ( ) . getBlockInputs ( ) . get ( ) ) , is ( true ) ) ; assertThat ( mapper . getElements ( ) . size ( ) , is ( ) ) ; FlowElement op1 = single ( mapper . getBlockInputs ( ) ) . getElementPort ( ) . getOwner ( ) ; assertThat ( op1 . getDescription ( ) , is ( fp2a . get ( "" ) . getDescription ( ) ) ) ; assertThat ( succ ( op1 ) . getDescription ( ) , is ( fp2b . get ( "" ) . getDescription ( ) ) ) ; } private void deletePseuds ( FlowGraph graph ) { for ( FlowElement element : FlowGraphUtil . collectElements ( graph ) ) { if ( element . getDescription ( ) . getKind ( ) == FlowElementKind . PSEUD ) { FlowGraphUtil . skip ( element ) ; } } } private FlowElement pred ( FlowElement elem ) { return single ( FlowGraphUtil . getPredecessors ( elem ) ) ; } private FlowElement succ ( FlowElement elem ) { return single ( FlowGraphUtil . getSuccessors ( elem ) ) ; } private < T > T single ( Iterable < T > collection ) { Iterator < T > iter = collection . iterator ( ) ; assert iter . hasNext ( ) : collection ; T result = iter . next ( ) ; assert iter . hasNext ( ) == false : collection ; return result ; } } package com . asakusafw . compiler . flow . plan ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . Arrays ; import org . junit . Test ; import com . asakusafw . compiler . flow . FlowGraphGenerator ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; public class FlowBlockTest { @ Test public void isEmpty ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock block = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; assertThat ( block . isEmpty ( ) , is ( true ) ) ; } @ Test public void isEmpty_input ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock block = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; assertThat ( block . isEmpty ( ) , is ( false ) ) ; } @ Test public void isEmpty_output ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock block = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; assertThat ( block . isEmpty ( ) , is ( false ) ) ; } @ Test public void isReduceBlock_true ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock block = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; assertThat ( block . isReduceBlock ( ) , is ( true ) ) ; } @ Test public void isReduceBlock_false ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock block = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; assertThat ( block . isReduceBlock ( ) , is ( false ) ) ; } @ Test public void detach_1 ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock block = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; block . detach ( ) ; assertThat ( block . getElements ( ) . size ( ) , is ( ) ) ; assertThat ( block . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( block . getBlockOutputs ( ) . size ( ) , is ( ) ) ; FlowElement op = block . getElements ( ) . iterator ( ) . next ( ) ; FlowBlock . Input input = block . getBlockInputs ( ) . get ( ) ; FlowBlock . Output output = block . getBlockOutputs ( ) . get ( ) ; assertThat ( op , not ( sameInstance ( gen . get ( "" ) ) ) ) ; assertThat ( input . getElementPort ( ) , not ( sameInstance ( gen . input ( "" ) ) ) ) ; assertThat ( output . getElementPort ( ) , not ( sameInstance ( gen . output ( "" ) ) ) ) ; assertThat ( input . getElementPort ( ) . getOwner ( ) , is ( op ) ) ; assertThat ( output . getElementPort ( ) . getOwner ( ) , is ( op ) ) ; assertThat ( input . getConnections ( ) . isEmpty ( ) , is ( true ) ) ; assertThat ( output . getConnections ( ) . isEmpty ( ) , is ( true ) ) ; } @ Test public void detach_2 ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock block = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; block . detach ( ) ; assertThat ( block . getElements ( ) . size ( ) , is ( ) ) ; assertThat ( block . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( block . getBlockOutputs ( ) . size ( ) , is ( ) ) ; FlowBlock . Input input = block . getBlockInputs ( ) . get ( ) ; FlowBlock . Output output = block . getBlockOutputs ( ) . get ( ) ; assertThat ( input . getElementPort ( ) , not ( sameInstance ( gen . input ( "" ) ) ) ) ; assertThat ( output . getElementPort ( ) , not ( sameInstance ( gen . output ( "" ) ) ) ) ; FlowElement op1 = input . getElementPort ( ) . getOwner ( ) ; FlowElement op2 = output . getElementPort ( ) . getOwner ( ) ; assertThat ( op1 . getInputPorts ( ) . get ( ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( op1 . getOutputPorts ( ) . get ( ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( op2 . getInputPorts ( ) . get ( ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( op2 . getOutputPorts ( ) . get ( ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( op1 . getOutputPorts ( ) . get ( ) . getConnected ( ) , is ( op2 . getInputPorts ( ) . get ( ) . getConnected ( ) ) ) ; } @ Test public void connect ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b2 = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , b2 . getBlockInputs ( ) . get ( ) ) ; b1 . detach ( ) ; b2 . detach ( ) ; assertThat ( b1 . getBlockInputs ( ) . get ( ) . getConnections ( ) . size ( ) , is ( ) ) ; assertThat ( b2 . getBlockInputs ( ) . get ( ) . getConnections ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . get ( ) . getConnections ( ) . size ( ) , is ( ) ) ; assertThat ( b2 . getBlockOutputs ( ) . get ( ) . getConnections ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . get ( ) . getConnections ( ) . get ( ) . getUpstream ( ) , is ( b1 . getBlockOutputs ( ) . get ( ) ) ) ; assertThat ( b1 . getBlockOutputs ( ) . get ( ) . getConnections ( ) . get ( ) . getDownstream ( ) , is ( b2 . getBlockInputs ( ) . get ( ) ) ) ; assertThat ( b2 . getBlockInputs ( ) . get ( ) . getConnections ( ) . get ( ) . getDownstream ( ) , is ( b2 . getBlockInputs ( ) . get ( ) ) ) ; assertThat ( b2 . getBlockInputs ( ) . get ( ) . getConnections ( ) . get ( ) . getUpstream ( ) , is ( b1 . getBlockOutputs ( ) . get ( ) ) ) ; } @ Test public void isSucceedingReduceBlock_true ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b2 = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , b2 . getBlockInputs ( ) . get ( ) ) ; b1 . detach ( ) ; b2 . detach ( ) ; assertThat ( b1 . isSucceedingReduceBlock ( ) , is ( true ) ) ; } @ Test public void isSucceedingReduceBlock_false ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b2 = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , b2 . getBlockInputs ( ) . get ( ) ) ; b1 . detach ( ) ; b2 . detach ( ) ; assertThat ( b1 . isSucceedingReduceBlock ( ) , is ( false ) ) ; } @ Test public void isSucceedingReduceBlock_empty ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b2 = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( "" ) ) , gen . getAsSet ( "" ) ) ; b1 . detach ( ) ; b2 . detach ( ) ; assertThat ( b1 . isSucceedingReduceBlock ( ) , is ( false ) ) ; } @ Test public void compaction_deadIn ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) , gen . output ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) , gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) , gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) , gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; assertThat ( b1 . compaction ( ) , is ( true ) ) ; assertThat ( b1 . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getElements ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockInputs ( ) . get ( ) . getElementPort ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; } @ Test public void compaction_deadOut ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) , gen . output ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) , gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) , gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) , gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; assertThat ( b1 . compaction ( ) , is ( true ) ) ; assertThat ( b1 . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getElements ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . get ( ) . getElementPort ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; } @ Test public void compaction_emptyIn ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; assertThat ( b1 . compaction ( ) , is ( true ) ) ; assertThat ( b1 . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getElements ( ) . size ( ) , is ( ) ) ; } @ Test public void compaction_stopOut ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; assertThat ( b1 . compaction ( ) , is ( true ) ) ; assertThat ( b1 . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getElements ( ) . size ( ) , is ( ) ) ; } @ Test public void compaction_mandatoryStop ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , ObservationCount . AT_LEAST_ONCE ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; assertThat ( b1 . compaction ( ) , is ( true ) ) ; assertThat ( b1 . getBlockInputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getBlockOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( b1 . getElements ( ) . size ( ) , is ( ) ) ; } @ Test public void compaction_stable ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; FlowBlock bin = FlowBlock . fromPorts ( , gen . toGraph ( ) , new ArrayList < FlowElementInput > ( gen . inputs ( ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" ) ) ; FlowBlock b1 = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , Arrays . asList ( gen . output ( "" ) ) , gen . getAsSet ( "" , "" ) ) ; FlowBlock bout = FlowBlock . fromPorts ( , gen . toGraph ( ) , Arrays . asList ( gen . input ( "" ) ) , new ArrayList < FlowElementOutput > ( gen . outputs ( ) ) , gen . getAsSet ( "" ) ) ; FlowBlock . connect ( b1 . getBlockOutputs ( ) . get ( ) , bout . getBlockInputs ( ) . get ( ) ) ; FlowBlock . connect ( bin . getBlockOutputs ( ) . get ( ) , b1 . getBlockInputs ( ) . get ( ) ) ; bin . detach ( ) ; b1 . detach ( ) ; bout . detach ( ) ; assertThat ( b1 . compaction ( ) , is ( false ) ) ; } } package com . asakusafw . compiler . flow . plan ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . junit . runners . Parameterized ; import org . junit . runners . Parameterized . Parameters ; import com . asakusafw . compiler . flow . FlowCompilerOptions . GenericOptionValue ; import com . asakusafw . compiler . flow . example . BranchStage ; import com . asakusafw . compiler . flow . example . CombineStage ; import com . asakusafw . compiler . flow . example . DuplicateStage ; import com . asakusafw . compiler . flow . example . SplitStage ; import com . asakusafw . compiler . flow . example . StickyStage ; import com . asakusafw . compiler . flow . example . TwinCogroupStage ; import com . asakusafw . compiler . flow . example . VolatileStage ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Branch ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Cogroup ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . CogroupAdd ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Checkpoint ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Confluent ; @ RunWith ( Parameterized . class ) public class StagePlannerRunTest { @ Rule public final CompilerTester tester ; @ Parameters public static List < Object [ ] > parameters ( ) { return Arrays . asList ( new Object [ ] [ ] { { GenericOptionValue . DISABLED } , { GenericOptionValue . ENABLED } , } ) ; } public StagePlannerRunTest ( GenericOptionValue opt ) { tester = new CompilerTester ( ) ; tester . options ( ) . putExtraAttribute ( StagePlanner . KEY_COMPRESS_FLOW_BLOCK_GROUP , opt . getSymbol ( ) ) ; } @ Test public void keep_sticky ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; in . add ( new Ex1 ( ) ) ; boolean result = tester . runFlow ( new StickyStage ( in . flow ( ) ) ) ; assertThat ( result , is ( false ) ) ; } @ Test public void unify_volatile ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; in . add ( new Ex1 ( ) ) ; boolean result = tester . runFlow ( new VolatileStage ( in . flow ( ) , out . flow ( ) ) ) ; assertThat ( result , is ( true ) ) ; List < Ex1 > outputs = out . toList ( ) ; assertThat ( outputs . size ( ) , is ( ) ) ; assertThat ( outputs . get ( ) , equalTo ( outputs . get ( ) ) ) ; } @ Test public void duplicate ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; in . add ( new Ex1 ( ) ) ; boolean result = tester . runFlow ( new DuplicateStage ( in . flow ( ) , out . flow ( ) ) ) ; assertThat ( result , is ( true ) ) ; List < Ex1 > outputs = out . toList ( ) ; assertThat ( outputs . size ( ) , is ( ) ) ; assertThat ( outputs . get ( ) , equalTo ( outputs . get ( ) ) ) ; } @ Test public void confluent ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; boolean result = tester . runFlow ( new TwinCogroupStage ( in . flow ( ) , out . flow ( ) ) ) ; assertThat ( result , is ( true ) ) ; List < Ex1 > outputs = out . toList ( ) ; assertThat ( outputs . size ( ) , is ( ) ) ; assertThat ( outputs . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void branch ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out1 = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > out2 = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > out3 = tester . output ( Ex1 . class , "" ) ; Ex1 model = new Ex1 ( ) ; model . setValue ( ) ; in . add ( model ) ; model . setValue ( ) ; in . add ( model ) ; boolean result = tester . runFlow ( new BranchStage ( in . flow ( ) , out1 . flow ( ) , out2 . flow ( ) , out3 . flow ( ) ) ) ; assertThat ( result , is ( true ) ) ; assertThat ( out1 . toList ( ) . size ( ) , is ( ) ) ; assertThat ( out2 . toList ( ) . size ( ) , is ( ) ) ; assertThat ( out3 . toList ( ) . size ( ) , is ( ) ) ; } @ Test public void split_unify ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out1 = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > out2 = tester . output ( Ex1 . class , "" ) ; Ex1 model = new Ex1 ( ) ; model . setValue ( ) ; in . add ( model ) ; boolean result = tester . runFlow ( new SplitStage ( in . flow ( ) , out1 . flow ( ) , out2 . flow ( ) ) ) ; assertThat ( result , is ( true ) ) ; assertThat ( out1 . toList ( ) . size ( ) , is ( ) ) ; assertThat ( out2 . toList ( ) . size ( ) , is ( ) ) ; } @ Test public void ident_unify ( ) throws Exception { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex1 > in2 = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out1 = tester . output ( Ex1 . class , "" ) ; Ex1 model = new Ex1 ( ) ; model . setValue ( ) ; in1 . add ( model ) ; model . setValue ( ) ; in2 . add ( model ) ; final In < Ex1 > pIn1 = in1 . flow ( ) ; final In < Ex1 > pIn2 = in2 . flow ( ) ; final Out < Ex1 > pOut1 = out1 . flow ( ) ; boolean result = tester . runFlow ( new FlowDescription ( ) { @ Override protected void describe ( ) { UpdateFlowFactory uf = new UpdateFlowFactory ( ) ; ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory c = new CoreOperatorFactory ( ) ; Confluent < Ex1 > in = c . confluent ( pIn1 , pIn2 ) ; Simple simple = uf . simple ( in ) ; Checkpoint < Ex1 > cp = c . checkpoint ( simple . out ) ; Cogroup cog = f . cogroup ( cp , c . empty ( Ex2 . class ) ) ; c . stop ( cog . r2 ) ; pOut1 . add ( cog . r1 ) ; } } ) ; assertThat ( result , is ( true ) ) ; assertThat ( out1 . toList ( ) . size ( ) , is ( ) ) ; } @ Test public void combine ( ) throws Exception { tester . options ( ) . setEnableCombiner ( true ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out1 = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > out2 = tester . output ( Ex1 . class , "" ) ; Ex1 model = new Ex1 ( ) ; model . setStringAsString ( "" ) ; model . setValue ( ) ; in . add ( model ) ; model . setStringAsString ( "" ) ; model . setValue ( ) ; in . add ( model ) ; model . setValue ( ) ; in . add ( model ) ; model . setStringAsString ( "" ) ; model . setValue ( ) ; in . add ( model ) ; model . setValue ( ) ; in . add ( model ) ; model . setValue ( ) ; in . add ( model ) ; boolean result = tester . runFlow ( new CombineStage ( in . flow ( ) , out1 . flow ( ) , out2 . flow ( ) ) ) ; assertThat ( result , is ( true ) ) ; List < Ex1 > list1 = out1 . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; List < Ex1 > list2 = out2 . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( list1 . size ( ) , is ( ) ) ; assertThat ( list1 . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( list1 . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( list1 . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( list1 . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( list1 . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( list1 . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( list1 , is ( list2 ) ) ; } @ Test public void compress_flow_block ( ) throws Exception { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out1 = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > out2 = tester . output ( Ex1 . class , "" ) ; Ex1 model = new Ex1 ( ) ; model . setValue ( ) ; model . setStringAsString ( "" ) ; in1 . add ( model ) ; final In < Ex1 > pIn1 = in1 . flow ( ) ; final Out < Ex1 > pOut1 = out1 . flow ( ) ; final Out < Ex1 > pOut2 = out2 . flow ( ) ; boolean result = tester . runFlow ( new FlowDescription ( ) { @ Override protected void describe ( ) { CoreOperatorFactory c = new CoreOperatorFactory ( ) ; ExOperatorFactory f = new ExOperatorFactory ( ) ; Update u1 = f . update ( pIn1 , ) ; Update u2 = f . update ( pIn1 , ) ; CogroupAdd c1 = f . cogroupAdd ( c . confluent ( u1 . out , u2 . out ) ) ; CogroupAdd c2 = f . cogroupAdd ( c . confluent ( u1 . out , u2 . out ) ) ; pOut1 . add ( c1 . result ) ; pOut2 . add ( c2 . result ) ; } } ) ; assertThat ( result , is ( true ) ) ; List < Ex1 > r1 = out1 . toList ( ) ; List < Ex1 > r2 = out2 . toList ( ) ; assertThat ( r1 . size ( ) , is ( ) ) ; assertThat ( r2 . size ( ) , is ( ) ) ; assertThat ( r1 . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( r2 . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void branch_pushdown ( ) throws Exception { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out1 = tester . output ( Ex1 . class , "" ) ; Ex1 model = new Ex1 ( ) ; model . setValue ( ) ; in1 . add ( model ) ; model . setValue ( ) ; in1 . add ( model ) ; model . setValue ( ) ; in1 . add ( model ) ; final In < Ex1 > pIn1 = in1 . flow ( ) ; final Out < Ex1 > pOut1 = out1 . flow ( ) ; boolean result = tester . runFlow ( new FlowDescription ( ) { @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory c = new CoreOperatorFactory ( ) ; Cogroup cog1 = f . cogroup ( pIn1 , c . empty ( Ex2 . class ) ) ; c . stop ( cog1 . r2 ) ; Branch bra = f . branch ( cog1 . r1 ) ; c . stop ( bra . cancel ) ; c . stop ( bra . no ) ; Cogroup cog2 = f . cogroup ( bra . yes , c . empty ( Ex2 . class ) ) ; c . stop ( cog2 . r2 ) ; pOut1 . add ( cog2 . r1 ) ; } } ) ; assertThat ( result , is ( true ) ) ; assertThat ( out1 . toList ( ) . size ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . plan ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . compiler . flow . FlowGraphGenerator ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; public class FlowGraphUtilTest { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; @ Test public void collectElements ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; Set < FlowElement > elements = FlowGraphUtil . collectElements ( gen . toGraph ( ) ) ; assertThat ( elements , hasItem ( gen . get ( "" ) ) ) ; assertThat ( elements , hasItem ( gen . get ( "" ) ) ) ; assertThat ( elements , hasItem ( gen . get ( "" ) ) ) ; assertThat ( elements , hasItem ( gen . get ( "" ) ) ) ; assertThat ( elements , hasItem ( gen . get ( "" ) ) ) ; assertThat ( elements , not ( hasItem ( gen . get ( "" ) ) ) ) ; } @ Test public void toElementGraph ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; Graph < FlowElement > graph = FlowGraphUtil . toElementGraph ( gen . toGraph ( ) ) ; assertThat ( graph . getNodeSet ( ) , is ( gen . all ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" , "" ) ) ) ; } @ Test public void copy ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; FlowGraph copy = FlowGraphUtil . deepCopy ( graph ) ; assertThat ( toDescription ( FlowGraphUtil . toElementGraph ( copy ) ) , is ( toDescription ( FlowGraphUtil . toElementGraph ( graph ) ) ) ) ; } @ Test public void copyDeeply ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraph component = gen . toGraph ( ) ; gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineFlowPart ( "" , component ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraph graph = gen . toGraph ( ) ; FlowGraph copy = FlowGraphUtil . deepCopy ( graph ) ; Set < FlowElement > allComponents = FlowGraphUtil . collectFlowParts ( copy ) ; assertThat ( allComponents . size ( ) , is ( ) ) ; FlowElement compElem = allComponents . iterator ( ) . next ( ) ; FlowPartDescription copyComponent = ( FlowPartDescription ) compElem . getDescription ( ) ; assertThat ( toDescription ( FlowGraphUtil . toElementGraph ( copyComponent . getFlowGraph ( ) ) ) , is ( toDescription ( FlowGraphUtil . toElementGraph ( component ) ) ) ) ; assertThat ( copyComponent . getFlowGraph ( ) , not ( sameInstance ( component ) ) ) ; } private Graph < FlowElementDescription > toDescription ( Graph < FlowElement > graph ) { Graph < FlowElementDescription > descriptions = Graphs . newInstance ( ) ; for ( Graph . Vertex < FlowElement > vertex : graph ) { FlowElementDescription from = vertex . getNode ( ) . getDescription ( ) ; for ( FlowElement to : vertex . getConnected ( ) ) { descriptions . addEdge ( from , to . getDescription ( ) ) ; } } return descriptions ; } @ Test public void hasMandatorySideEffect ( ) { gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , ObservationCount . AT_LEAST_ONCE ) ; gen . defineOperator ( "" , "" , "" , ObservationCount . AT_MOST_ONCE ) ; assertThat ( FlowGraphUtil . hasMandatorySideEffect ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . hasMandatorySideEffect ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . hasMandatorySideEffect ( gen . get ( "" ) ) , is ( false ) ) ; } @ Test public void isAlwaysEmpty ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; assertThat ( FlowGraphUtil . isAlwaysEmpty ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysEmpty ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysEmpty ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysEmpty ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysEmpty ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysEmpty ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isAlwaysEmpty ( gen . get ( "" ) ) , is ( false ) ) ; } @ Test public void isAlwaysStop ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; assertThat ( FlowGraphUtil . isAlwaysStop ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysStop ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysStop ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysStop ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysStop ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysStop ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isAlwaysStop ( gen . get ( "" ) ) , is ( true ) ) ; } @ Test public void isIdentity ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; assertThat ( FlowGraphUtil . isIdentity ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isIdentity ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isIdentity ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isIdentity ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isIdentity ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isIdentity ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isIdentity ( gen . get ( "" ) ) , is ( false ) ) ; } @ Test public void splitIdentity_1_2 ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . definePseud ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . splitIdentity ( gen . get ( "" ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; } @ Test public void splitIdentity_2_1 ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . definePseud ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . splitIdentity ( gen . get ( "" ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; } @ Test public void splitIdentity_2_2 ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . definePseud ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . splitIdentity ( gen . get ( "" ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; } @ Test public void splitIdentity_1_1 ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . definePseud ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . splitIdentity ( gen . get ( "" ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . output ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; assertThat ( gen . input ( "" ) . getConnected ( ) . size ( ) , is ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void splitIdentity_notIdentity ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . splitIdentity ( gen . get ( "" ) ) ; } @ Test public void testSkip_1_1 ( ) { gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . skip ( gen . get ( "" ) ) ; Graph < FlowElement > graph = FlowGraphUtil . toElementGraph ( gen . toGraph ( ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; } @ Test public void testSkip_1_2 ( ) { gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . skip ( gen . get ( "" ) ) ; Graph < FlowElement > graph = FlowGraphUtil . toElementGraph ( gen . toGraph ( ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; } @ Test public void testSkip_2_1 ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . skip ( gen . get ( "" ) ) ; Graph < FlowElement > graph = FlowGraphUtil . toElementGraph ( gen . toGraph ( ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; } @ Test public void testSkip_2_2 ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . skip ( gen . get ( "" ) ) ; Graph < FlowElement > graph = FlowGraphUtil . toElementGraph ( gen . toGraph ( ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; } @ Test public void isBoundary ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; assertThat ( FlowGraphUtil . isBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isBoundary ( gen . get ( "" ) ) , is ( true ) ) ; } @ Test public void isShuffleBoundary ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; assertThat ( FlowGraphUtil . isShuffleBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isShuffleBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isShuffleBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isShuffleBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isShuffleBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isShuffleBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isShuffleBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isShuffleBoundary ( gen . get ( "" ) ) , is ( false ) ) ; } @ Test public void isStageBoundary ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; assertThat ( FlowGraphUtil . isStageBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isStageBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isStageBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isStageBoundary ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isStageBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isStageBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isStageBoundary ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isStageBoundary ( gen . get ( "" ) ) , is ( true ) ) ; } @ Test public void isStagePadding ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineEmpty ( "" ) ; gen . defineStop ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" , FlowBoundary . SHUFFLE ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; assertThat ( FlowGraphUtil . isStagePadding ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isStagePadding ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isStagePadding ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isStagePadding ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . isStagePadding ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isStagePadding ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isStagePadding ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . isStagePadding ( gen . get ( "" ) ) , is ( true ) ) ; } @ Test public void getSucceedBoundaryPath_direct ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; FlowPath path = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; assertThat ( path . getDirection ( ) , is ( FlowPath . Direction . FORWARD ) ) ; assertThat ( path . getStartings ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( path . getPassings ( ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( path . getArrivals ( ) , is ( gen . getAsSet ( "" ) ) ) ; } @ Test public void getSucceedBoundaryPath_hop ( ) { gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowPath path = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; assertThat ( path . getDirection ( ) , is ( FlowPath . Direction . FORWARD ) ) ; assertThat ( path . getStartings ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( path . getPassings ( ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( path . getArrivals ( ) , is ( gen . getAsSet ( "" ) ) ) ; } @ Test public void getSucceedBoundaryPath_many ( ) { gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowPath path = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; assertThat ( path . getDirection ( ) , is ( FlowPath . Direction . FORWARD ) ) ; assertThat ( path . getStartings ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( path . getPassings ( ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; assertThat ( path . getArrivals ( ) , is ( gen . getAsSet ( "" , "" ) ) ) ; } @ Test public void getPredeceaseBoundaryPath_direct ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; FlowPath path = FlowGraphUtil . getPredeceaseBoundaryPath ( gen . get ( "" ) ) ; assertThat ( path . getDirection ( ) , is ( FlowPath . Direction . BACKWORD ) ) ; assertThat ( path . getStartings ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( path . getPassings ( ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( path . getArrivals ( ) , is ( gen . getAsSet ( "" ) ) ) ; } @ Test public void getPredeceaseBoundaryPath_hop ( ) { gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowPath path = FlowGraphUtil . getPredeceaseBoundaryPath ( gen . get ( "" ) ) ; assertThat ( path . getDirection ( ) , is ( FlowPath . Direction . BACKWORD ) ) ; assertThat ( path . getStartings ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( path . getPassings ( ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( path . getArrivals ( ) , is ( gen . getAsSet ( "" ) ) ) ; } @ Test public void getPredeceaseBoundaryPath_many ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowPath path = FlowGraphUtil . getPredeceaseBoundaryPath ( gen . get ( "" ) ) ; assertThat ( path . getDirection ( ) , is ( FlowPath . Direction . BACKWORD ) ) ; assertThat ( path . getStartings ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( path . getPassings ( ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; assertThat ( path . getArrivals ( ) , is ( gen . getAsSet ( "" , "" ) ) ) ; } @ Test public void hasSuccessors ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; assertThat ( FlowGraphUtil . hasSuccessors ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . hasSuccessors ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . hasSuccessors ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . hasSuccessors ( gen . get ( "" ) ) , is ( false ) ) ; } @ Test public void hasPredecessors ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; assertThat ( FlowGraphUtil . hasPredecessors ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . hasPredecessors ( gen . get ( "" ) ) , is ( false ) ) ; assertThat ( FlowGraphUtil . hasPredecessors ( gen . get ( "" ) ) , is ( true ) ) ; assertThat ( FlowGraphUtil . hasPredecessors ( gen . get ( "" ) ) , is ( false ) ) ; } @ Test public void getSuccessors ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; assertThat ( FlowGraphUtil . getSuccessors ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; } @ Test public void getPredecessors ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; assertThat ( FlowGraphUtil . getPredecessors ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; } @ Test public void getSucceedingBoundaries ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; assertThat ( FlowGraphUtil . getSucceedingBoundaries ( gen . output ( "" ) ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( FlowGraphUtil . getSucceedingBoundaries ( gen . output ( "" ) ) , is ( gen . getAsSet ( "" , "" ) ) ) ; } @ Test public void insertCheckpoint ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . insertCheckpoint ( gen . output ( "" ) ) ; Set < FlowElement > succ = FlowGraphUtil . getSuccessors ( gen . get ( "" ) ) ; assertThat ( succ . size ( ) , is ( ) ) ; FlowElement elem = succ . iterator ( ) . next ( ) ; assertThat ( FlowGraphUtil . isStagePadding ( elem ) , is ( true ) ) ; assertThat ( FlowGraphUtil . getSuccessors ( elem ) , is ( gen . getAsSet ( "" ) ) ) ; } @ Test public void insertCheckpoint_3 ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . insertCheckpoint ( gen . output ( "" ) ) ; Set < FlowElement > succ = FlowGraphUtil . getSuccessors ( gen . get ( "" ) ) ; assertThat ( succ . size ( ) , is ( ) ) ; FlowElement elem = succ . iterator ( ) . next ( ) ; assertThat ( FlowGraphUtil . isStagePadding ( elem ) , is ( true ) ) ; assertThat ( FlowGraphUtil . getSuccessors ( elem ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; } @ Test public void insertIdentity ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . insertIdentity ( gen . output ( "" ) ) ; Set < FlowElement > succ = FlowGraphUtil . getSuccessors ( gen . get ( "" ) ) ; assertThat ( succ . size ( ) , is ( ) ) ; FlowElement elem = succ . iterator ( ) . next ( ) ; assertThat ( FlowGraphUtil . isIdentity ( elem ) , is ( true ) ) ; assertThat ( FlowGraphUtil . getSuccessors ( elem ) , is ( gen . getAsSet ( "" ) ) ) ; } @ Test public void insertIdentity_3 ( ) { gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . insertIdentity ( gen . output ( "" ) ) ; Set < FlowElement > succ = FlowGraphUtil . getSuccessors ( gen . get ( "" ) ) ; assertThat ( succ . size ( ) , is ( ) ) ; FlowElement elem = succ . iterator ( ) . next ( ) ; assertThat ( FlowGraphUtil . isIdentity ( elem ) , is ( true ) ) ; assertThat ( FlowGraphUtil . getSuccessors ( elem ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; } @ Test public void disconnect ( ) { gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowGraphUtil . disconnect ( gen . get ( "" ) ) ; Graph < FlowElement > graph = FlowGraphUtil . toElementGraph ( gen . toGraph ( ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; assertThat ( graph . getConnected ( gen . get ( "" ) ) , is ( gen . getAsSet ( ) ) ) ; } @ Test public void inlineFlowPart ( ) { FlowGraphGenerator cgen = new FlowGraphGenerator ( ) ; cgen . defineInput ( "" ) ; cgen . defineOutput ( "" ) ; cgen . defineOperator ( "" , "" , "" ) ; cgen . connect ( "" , "" ) ; cgen . connect ( "" , "" ) ; FlowGraph component = cgen . toGraph ( ) ; gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; FlowElement fc = gen . defineFlowPart ( "" , component ) ; gen . connect ( "" , "" ) ; gen . connect ( "" , "" ) ; FlowGraphUtil . inlineFlowPart ( fc ) ; Graph < FlowElement > graph = FlowGraphUtil . toElementGraph ( gen . toGraph ( ) ) ; assertThat ( graph . contains ( gen . get ( "" ) ) , is ( false ) ) ; Set < FlowElement > path = Graphs . collectAllConnected ( graph , gen . getAsSet ( "" ) ) ; assertThat ( path , hasItems ( cgen . get ( "" ) , gen . get ( "" ) ) ) ; assertThat ( path , not ( hasItem ( cgen . get ( "" ) ) ) ) ; assertThat ( path , not ( hasItem ( cgen . get ( "" ) ) ) ) ; } } package com . asakusafw . compiler . flow . plan ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Collection ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . compiler . flow . FlowGraphGenerator ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class FlowPathTest { @ Test public void union ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowPath a = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath b = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath path = a . union ( b ) ; assertThat ( path . getStartings ( ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( path . getPassings ( ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( path . getArrivals ( ) , is ( gen . getAsSet ( "" , "" , "" ) ) ) ; } @ Test public void transposeIntersect ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; FlowPath a = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath b = FlowGraphUtil . getPredeceaseBoundaryPath ( gen . get ( "" ) ) ; FlowPath path = a . transposeIntersect ( b ) ; assertThat ( path . getStartings ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( path . getPassings ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( path . getArrivals ( ) , is ( gen . getAsSet ( "" ) ) ) ; } @ Test public void createBlock_includeIn_includeOut ( ) { FlowGraphGenerator gen = graph ( ) ; FlowPath a = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath b = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath c = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath in3 = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath path = a . union ( b ) . union ( c ) . union ( in3 ) ; FlowBlock block = path . createBlock ( gen . toGraph ( ) , , true , true ) ; assertThat ( block . getElements ( ) , is ( gen . getAsSet ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) ) ) ; Set < FlowElementInput > inputs = input ( block . getBlockInputs ( ) ) ; Set < FlowElementOutput > outputs = output ( block . getBlockOutputs ( ) ) ; assertThat ( inputs , is ( gen . inputs ( "" , "" , "" ) ) ) ; assertThat ( outputs , is ( gen . outputs ( "" , "" , "" ) ) ) ; } @ Test public void createBlock_excludeIn_includeOut ( ) { FlowGraphGenerator gen = graph ( ) ; FlowPath a = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath b = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath c = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath in3 = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath path = a . union ( b ) . union ( c ) . union ( in3 ) ; FlowBlock block = path . createBlock ( gen . toGraph ( ) , , false , true ) ; assertThat ( block . getElements ( ) , is ( gen . getAsSet ( "" , "" , "" , "" , "" , "" ) ) ) ; Set < FlowElementInput > inputs = input ( block . getBlockInputs ( ) ) ; Set < FlowElementOutput > outputs = output ( block . getBlockOutputs ( ) ) ; assertThat ( inputs , is ( gen . inputs ( "" , "" ) ) ) ; assertThat ( outputs , is ( gen . outputs ( "" , "" , "" ) ) ) ; } @ Test public void createBlock_includeIn_excludeOut ( ) { FlowGraphGenerator gen = graph ( ) ; FlowPath a = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath b = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath c = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath in3 = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath path = a . union ( b ) . union ( c ) . union ( in3 ) ; FlowBlock block = path . createBlock ( gen . toGraph ( ) , , true , false ) ; assertThat ( block . getElements ( ) , is ( gen . getAsSet ( "" , "" , "" , "" , "" , "" ) ) ) ; Set < FlowElementInput > inputs = input ( block . getBlockInputs ( ) ) ; Set < FlowElementOutput > outputs = output ( block . getBlockOutputs ( ) ) ; assertThat ( inputs , is ( gen . inputs ( "" , "" , "" ) ) ) ; assertThat ( outputs , is ( gen . outputs ( "" , "" ) ) ) ; } @ Test public void createBlock_excludeIn_excludeOut ( ) { FlowGraphGenerator gen = graph ( ) ; FlowPath a = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath b = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath c = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath in3 = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowPath path = a . union ( b ) . union ( c ) . union ( in3 ) ; FlowBlock block = path . createBlock ( gen . toGraph ( ) , , false , false ) ; assertThat ( block . getElements ( ) , is ( gen . getAsSet ( "" , "" ) ) ) ; Set < FlowElementInput > inputs = input ( block . getBlockInputs ( ) ) ; Set < FlowElementOutput > outputs = output ( block . getBlockOutputs ( ) ) ; assertThat ( inputs , is ( gen . inputs ( "" , "" ) ) ) ; assertThat ( outputs , is ( gen . outputs ( "" , "" ) ) ) ; } @ Test public void createBlock_empty ( ) { FlowGraphGenerator gen = graph ( ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . connect ( "" , "" ) ; FlowPath path = FlowGraphUtil . getSucceedBoundaryPath ( gen . get ( "" ) ) ; FlowBlock b0 = path . createBlock ( gen . toGraph ( ) , , true , true ) ; assertThat ( b0 . getElements ( ) , is ( gen . getAsSet ( "" , "" ) ) ) ; assertThat ( input ( b0 . getBlockInputs ( ) ) , is ( gen . inputs ( ) ) ) ; assertThat ( output ( b0 . getBlockOutputs ( ) ) , is ( gen . outputs ( ) ) ) ; FlowBlock b1 = path . createBlock ( gen . toGraph ( ) , , false , true ) ; assertThat ( b1 . getElements ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( input ( b1 . getBlockInputs ( ) ) , is ( gen . inputs ( "" ) ) ) ; assertThat ( output ( b1 . getBlockOutputs ( ) ) , is ( gen . outputs ( ) ) ) ; FlowBlock b2 = path . createBlock ( gen . toGraph ( ) , , true , false ) ; assertThat ( b2 . getElements ( ) , is ( gen . getAsSet ( "" ) ) ) ; assertThat ( input ( b2 . getBlockInputs ( ) ) , is ( gen . inputs ( ) ) ) ; assertThat ( output ( b2 . getBlockOutputs ( ) ) , is ( gen . outputs ( "" ) ) ) ; try { path . createBlock ( gen . toGraph ( ) , , false , false ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } private FlowGraphGenerator graph ( ) { FlowGraphGenerator gen = new FlowGraphGenerator ( ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineInput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . defineOutput ( "" ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . definePseud ( "" , FlowBoundary . STAGE ) ; gen . defineOperator ( "" , "" , "" ) ; gen . defineOperator ( "" , "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) . connect ( "" , "" ) ; gen . connect ( "" , "" ) . connect ( "" , "" ) ; return gen ; } private Set < FlowElementInput > input ( Collection < FlowBlock . Input > inputs ) { Set < FlowElementInput > results = Sets . create ( ) ; for ( FlowBlock . Input port : inputs ) { results . add ( port . getElementPort ( ) ) ; } return results ; } private Set < FlowElementOutput > output ( Collection < FlowBlock . Output > outputs ) { Set < FlowElementOutput > results = Sets . create ( ) ; for ( FlowBlock . Output port : outputs ) { results . add ( port . getElementPort ( ) ) ; } return results ; } } package com . asakusafw . compiler . flow ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import com . asakusafw . compiler . flow . plan . FlowPath ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . FlowOut ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; import com . asakusafw . vocabulary . flow . graph . PortDirection ; import com . asakusafw . vocabulary . flow . util . PseudElementDescription ; import com . asakusafw . vocabulary . operator . Identity ; public class FlowGraphGenerator { private static final Class < String > TYPE = String . class ; private List < FlowIn < ? > > flowInputs = Lists . create ( ) ; private List < FlowOut < ? > > flowOutputs = Lists . create ( ) ; private Map < String , FlowElement > elements = Maps . create ( ) ; public FlowElement defineInput ( String name ) { InputDescription desc = new InputDescription ( name , TYPE ) ; FlowIn < ? > node = new FlowIn < Object > ( desc ) ; flowInputs . add ( node ) ; return register ( name , node . getFlowElement ( ) ) ; } public FlowElement defineOutput ( String name ) { OutputDescription desc = new OutputDescription ( name , TYPE ) ; FlowOut < ? > node = new FlowOut < Object > ( desc ) ; flowOutputs . add ( node ) ; return register ( name , node . getFlowElement ( ) ) ; } public FlowElement defineOperator ( String name , String inputList , String outputList , FlowElementAttribute ... attributes ) { List < FlowElementPortDescription > inputs = parsePorts ( PortDirection . INPUT , inputList ) ; List < FlowElementPortDescription > outputs = parsePorts ( PortDirection . OUTPUT , outputList ) ; FlowElementDescription desc = new OperatorDescription ( new OperatorDescription . Declaration ( Identity . class , TYPE , TYPE , name , Collections . < Class < ? > > emptyList ( ) ) , inputs , outputs , Collections . < FlowResourceDescription > emptyList ( ) , Collections . < OperatorDescription . Parameter > emptyList ( ) , Arrays . asList ( attributes ) ) ; return register ( name , desc ) ; } public FlowElement defineFlowPart ( String name , FlowGraph graph ) { FlowElementDescription desc = new FlowPartDescription ( graph ) ; return register ( name , desc ) ; } public FlowElement defineEmpty ( String name ) { return register ( name , new PseudElementDescription ( name , TYPE , false , true , FlowBoundary . STAGE ) ) ; } public FlowElement defineStop ( String name ) { return register ( name , new PseudElementDescription ( name , TYPE , true , false , FlowBoundary . STAGE ) ) ; } public FlowElement definePseud ( String name , FlowElementAttribute ... attributes ) { return register ( name , new PseudElementDescription ( name , TYPE , true , true , attributes ) ) ; } public FlowGraphGenerator connect ( String upstream , String downstream ) { FlowElementOutput output = findOutput ( upstream ) ; FlowElementInput input = findInput ( downstream ) ; PortConnection . connect ( output , input ) ; return this ; } public FlowElement get ( String name ) { FlowElement found = elements . get ( name ) ; if ( found == null ) { throw new AssertionError ( name + elements . keySet ( ) ) ; } return found ; } public FlowElementDescription desc ( String name ) { FlowElement found = elements . get ( name ) ; if ( found == null ) { throw new AssertionError ( name + elements . keySet ( ) ) ; } return found . getDescription ( ) ; } public FlowElementInput input ( String input ) { return findInput ( input ) ; } public Set < FlowElementInput > inputs ( String ... inputs ) { Set < FlowElementInput > results = Sets . create ( ) ; for ( String input : inputs ) { results . add ( input ( input ) ) ; } return results ; } public FlowElementOutput output ( String output ) { return findOutput ( output ) ; } public Set < FlowElementOutput > outputs ( String ... outputs ) { Set < FlowElementOutput > results = Sets . create ( ) ; for ( String output : outputs ) { results . add ( output ( output ) ) ; } return results ; } public Set < FlowElement > getAsSet ( String ... names ) { Set < FlowElement > results = Sets . create ( ) ; for ( String name : names ) { results . add ( get ( name ) ) ; } return results ; } public Set < FlowElement > all ( ) { return new HashSet < FlowElement > ( elements . values ( ) ) ; } public FlowGraph toGraph ( ) { return new FlowGraph ( Testing . class , flowInputs , flowOutputs ) ; } public FlowPath toPath ( FlowPath . Direction direction ) { Set < FlowElement > inputs = Sets . create ( ) ; Set < FlowElement > passings = Sets . create ( ) ; Set < FlowElement > outputs = Sets . create ( ) ; for ( FlowIn < ? > node : flowInputs ) { inputs . add ( node . getFlowElement ( ) ) ; } for ( FlowOut < ? > node : flowOutputs ) { outputs . add ( node . getFlowElement ( ) ) ; } passings . removeAll ( inputs ) ; passings . removeAll ( outputs ) ; return new FlowPath ( direction , direction == FlowPath . Direction . FORWARD ? inputs : outputs , passings , direction == FlowPath . Direction . FORWARD ? outputs : inputs ) ; } private static final Pattern PORT = Pattern . compile ( "" ) ; private FlowElementInput findInput ( String spec ) { Matcher matcher = PORT . matcher ( spec ) ; if ( matcher . matches ( ) == false ) { throw new AssertionError ( spec ) ; } String elementName = matcher . group ( ) ; FlowElement element = elements . get ( elementName ) ; if ( element == null ) { throw new AssertionError ( elementName + elements . keySet ( ) ) ; } String portName = matcher . group ( ) ; if ( portName == null ) { if ( element . getInputPorts ( ) . size ( ) != ) { throw new AssertionError ( element . getInputPorts ( ) ) ; } return element . getInputPorts ( ) . get ( ) ; } FlowElementInput port = null ; for ( FlowElementInput finding : element . getInputPorts ( ) ) { if ( portName . equals ( finding . getDescription ( ) . getName ( ) ) ) { port = finding ; break ; } } if ( port == null ) { throw new AssertionError ( elementName + "" + portName + elements . keySet ( ) ) ; } return port ; } private FlowElementOutput findOutput ( String spec ) { Matcher matcher = PORT . matcher ( spec ) ; if ( matcher . matches ( ) == false ) { throw new AssertionError ( spec ) ; } String elementName = matcher . group ( ) ; FlowElement element = elements . get ( elementName ) ; if ( element == null ) { throw new AssertionError ( elementName + elements . keySet ( ) ) ; } String portName = matcher . group ( ) ; if ( portName == null ) { if ( element . getOutputPorts ( ) . size ( ) != ) { throw new AssertionError ( element . getOutputPorts ( ) ) ; } return element . getOutputPorts ( ) . get ( ) ; } FlowElementOutput port = null ; for ( FlowElementOutput finding : element . getOutputPorts ( ) ) { if ( portName . equals ( finding . getDescription ( ) . getName ( ) ) ) { port = finding ; break ; } } if ( port == null ) { throw new AssertionError ( elementName + "" + portName + elements . keySet ( ) ) ; } return port ; } private FlowElement register ( String name , FlowElementDescription desc ) { FlowElement element = new FlowElement ( desc ) ; return register ( name , element ) ; } private FlowElement register ( String name , FlowElement element ) { if ( elements . containsKey ( name ) ) { throw new AssertionError ( name + elements . keySet ( ) ) ; } elements . put ( name , element ) ; return element ; } private List < FlowElementPortDescription > parsePorts ( PortDirection direction , String nameList ) { String [ ] names = nameList . trim ( ) . split ( "" ) ; List < FlowElementPortDescription > results = Lists . create ( ) ; for ( String name : names ) { results . add ( new FlowElementPortDescription ( name , TYPE , direction ) ) ; } return results ; } private static class Testing extends FlowDescription { @ Override protected void describe ( ) { return ; } } } package com . asakusafw . compiler . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; public class DataClassTest { ModelFactory f = Models . getModelFactory ( ) ; @ Test public void unresolved_getType ( ) { DataClass dc = new DataClass . Unresolved ( f , Void . class ) ; assertThat ( dc . getType ( ) , is ( ( Object ) Void . class ) ) ; } @ Test public void unresolved_findProperty ( ) { DataClass dc = new DataClass . Unresolved ( f , Void . class ) ; assertThat ( dc . findProperty ( "" ) , is ( nullValue ( ) ) ) ; } @ Test public void unresolved_createNewInstance ( ) { DataClass dc = new DataClass . Unresolved ( f , Void . class ) ; assertThat ( dc . createNewInstance ( Models . toType ( f , Void . class ) ) , not ( nullValue ( ) ) ) ; } @ Test public void unresolved_assign ( ) { DataClass dc = new DataClass . Unresolved ( f , Void . class ) ; assertThat ( dc . assign ( f . newSimpleName ( "" ) , f . newSimpleName ( "" ) ) , not ( nullValue ( ) ) ) ; } @ Test public void unresolved_createReader ( ) { DataClass dc = new DataClass . Unresolved ( f , Void . class ) ; assertThat ( dc . createReader ( f . newThis ( ) , Models . toNullLiteral ( f ) ) , not ( nullValue ( ) ) ) ; } @ Test public void unresolved_createWriter ( ) { DataClass dc = new DataClass . Unresolved ( f , Void . class ) ; assertThat ( dc . createWriter ( f . newThis ( ) , Models . toNullLiteral ( f ) ) , not ( nullValue ( ) ) ) ; } } package com . asakusafw . compiler . flow . jobflow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . NoShuffleStage ; import com . asakusafw . compiler . flow . example . SequentialMultiStage ; import com . asakusafw . compiler . flow . example . SimpleShuffleStage ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Delivery ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Export ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Import ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Process ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Stage ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . ExSummarizedMockExporterDescription ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; public class JobflowAnalyzerTest extends JobflowCompilerTestRoot { @ Test public void mapperOnly ( ) { StageGraph graph = jfToStageGraph ( NoShuffleStage . class ) ; List < StageModel > stages = compileStages ( graph ) ; JobflowAnalyzer analyzer = new JobflowAnalyzer ( environment ) ; JobflowModel jobflow = analyzer . analyze ( graph , stages ) ; assertThat ( jobflow . getStages ( ) . size ( ) , is ( ) ) ; assertThat ( jobflow . getImports ( ) . size ( ) , is ( ) ) ; assertThat ( jobflow . getExports ( ) . size ( ) , is ( ) ) ; Import prologue = jobflow . getImports ( ) . get ( ) ; assertThat ( prologue . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( prologue . getDescription ( ) . getImporterDescription ( ) . getClass ( ) , is ( ( Object ) Ex1MockImporterDescription . class ) ) ; Export epilogue = jobflow . getExports ( ) . get ( ) ; assertThat ( epilogue . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( epilogue . getDescription ( ) . getExporterDescription ( ) . getClass ( ) , is ( ( Object ) Ex1MockExporterDescription . class ) ) ; Stage stage = jobflow . getStages ( ) . get ( ) ; assertThat ( stage . getProcesses ( ) . size ( ) , is ( ) ) ; assertThat ( stage . getReduceOrNull ( ) , is ( nullValue ( ) ) ) ; } @ Test public void single ( ) { StageGraph graph = jfToStageGraph ( SimpleShuffleStage . class ) ; List < StageModel > stages = compileStages ( graph ) ; JobflowAnalyzer analyzer = new JobflowAnalyzer ( environment ) ; JobflowModel jobflow = analyzer . analyze ( graph , stages ) ; assertThat ( jobflow . getStages ( ) . size ( ) , is ( ) ) ; assertThat ( jobflow . getImports ( ) . size ( ) , is ( ) ) ; assertThat ( jobflow . getExports ( ) . size ( ) , is ( ) ) ; Import prologue = jobflow . getImports ( ) . get ( ) ; assertThat ( prologue . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( prologue . getDescription ( ) . getImporterDescription ( ) . getClass ( ) , is ( ( Object ) Ex1MockImporterDescription . class ) ) ; Export epilogue = jobflow . getExports ( ) . get ( ) ; assertThat ( epilogue . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( epilogue . getDescription ( ) . getExporterDescription ( ) . getClass ( ) , is ( ( Object ) ExSummarizedMockExporterDescription . class ) ) ; Stage stage = jobflow . getStages ( ) . get ( ) ; assertThat ( stage . getProcesses ( ) . size ( ) , is ( ) ) ; assertThat ( stage . getReduceOrNull ( ) , not ( nullValue ( ) ) ) ; } @ Test public void multi ( ) { StageGraph graph = jfToStageGraph ( SequentialMultiStage . class ) ; List < StageModel > stages = compileStages ( graph ) ; JobflowAnalyzer analyzer = new JobflowAnalyzer ( environment ) ; JobflowModel jobflow = analyzer . analyze ( graph , stages ) ; assertThat ( jobflow . getStages ( ) . size ( ) , is ( ) ) ; assertThat ( jobflow . getImports ( ) . size ( ) , is ( ) ) ; assertThat ( jobflow . getExports ( ) . size ( ) , is ( ) ) ; Import prologue = jobflow . getImports ( ) . get ( ) ; assertThat ( prologue . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( prologue . getDescription ( ) . getImporterDescription ( ) . getClass ( ) , is ( ( Object ) Ex1MockImporterDescription . class ) ) ; Export epilogue = jobflow . getExports ( ) . get ( ) ; assertThat ( epilogue . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( epilogue . getDescription ( ) . getExporterDescription ( ) . getClass ( ) , is ( ( Object ) Ex1MockExporterDescription . class ) ) ; Graph < Stage > dep = jobflow . getDependencyGraph ( ) ; Set < Stage > heads = Graphs . collectHeads ( dep ) ; Set < Stage > tails = Graphs . collectTails ( dep ) ; assertThat ( heads . size ( ) , is ( ) ) ; assertThat ( tails . size ( ) , is ( ) ) ; Stage st1 = tails . iterator ( ) . next ( ) ; Stage st2 = heads . iterator ( ) . next ( ) ; assertThat ( st1 , not ( equalTo ( st2 ) ) ) ; List < Process > st1p = st1 . getProcesses ( ) ; assertThat ( st1p . size ( ) , is ( ) ) ; assertThat ( st1p . get ( ) . getResolvedSources ( ) . contains ( prologue ) , is ( true ) ) ; List < Delivery > st2d = st2 . getDeliveries ( ) ; assertThat ( st2d . size ( ) , is ( ) ) ; assertThat ( epilogue . getResolvedSources ( ) . contains ( st2d . get ( ) ) , is ( true ) ) ; } } package com . asakusafw . compiler . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . flow . example . * ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . FlowOut ; public class JobFlowDriverTest { @ Test public void simple ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( SimpleJobFlow . class ) ; assertThat ( analyzed . hasError ( ) , is ( false ) ) ; JobFlowClass jf = analyzed . getJobFlowClass ( ) ; FlowGraph graph = jf . getGraph ( ) ; assertThat ( graph . getDescription ( ) , is ( ( Object ) SimpleJobFlow . class ) ) ; assertThat ( graph . getFlowInputs ( ) . size ( ) , is ( ) ) ; assertThat ( graph . getFlowOutputs ( ) . size ( ) , is ( ) ) ; FlowIn < ? > in = graph . getFlowInputs ( ) . get ( ) ; assertThat ( in . getDescription ( ) . getName ( ) , is ( "" ) ) ; FlowOut < ? > out = graph . getFlowOutputs ( ) . get ( ) ; assertThat ( out . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( in . toOutputPort ( ) . getConnected ( ) , is ( out . toInputPort ( ) . getConnected ( ) ) ) ; } @ Test public void Class_NotTopLevel ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( TopLevelJobFlow . Inner . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Class_NotPublic ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( NotPublicJobFlow . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Class_Abstract ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( AbstractJobFlow . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Class_NotAnnotated ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( NotAnnotatedJobFlow . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Constructor_None ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( NoPublicConstructors . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Constructor_Multi ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( MultiPublicConstructor . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Constructor_InvalidParameter ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( InvalidParameter . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Input_NotTyped ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( NotTypedInput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Input_WithInvalidAnnotation ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( WithExportInput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Input_WithEmptyInputName ( ) { JobFlowDriver driver = JobFlowDriver . analyze ( WithEmptyInputName . class ) ; assertThat ( driver . hasError ( ) , is ( true ) ) ; assertThat ( driver . getDiagnostics ( ) . size ( ) , greaterThan ( ) ) ; } @ Test public void Input_WithInvalidInputName ( ) { JobFlowDriver driver = JobFlowDriver . analyze ( WithInvalidInputName . class ) ; assertThat ( driver . hasError ( ) , is ( true ) ) ; assertThat ( driver . getDiagnostics ( ) . size ( ) , greaterThan ( ) ) ; } @ Test public void Input_WithoudMandatoryAnnotation ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( NoImportInput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Input_InconsistentAnnotation ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( InconsistentImportInput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Input_AbstractDescription ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( WithAbstractImportInput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Input_InvalidTypeDescription ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( WithMissTypedInput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Output_NotTyped ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( NotTypedOutput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Output_WithInvalidAnnotation ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( WithImportOutput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Output_WithEmptyOutputName ( ) { JobFlowDriver driver = JobFlowDriver . analyze ( WithEmptyOutputName . class ) ; assertThat ( driver . hasError ( ) , is ( true ) ) ; assertThat ( driver . getDiagnostics ( ) . size ( ) , greaterThan ( ) ) ; } @ Test public void Output_WithInvalidOutputName ( ) { JobFlowDriver driver = JobFlowDriver . analyze ( WithInvalidOutputName . class ) ; assertThat ( driver . hasError ( ) , is ( true ) ) ; assertThat ( driver . getDiagnostics ( ) . size ( ) , greaterThan ( ) ) ; } @ Test public void Output_WithoudMandatoryAnnotation ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( NoExportOutput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Output_InconsistentAnnotation ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( InconsistentExportOutput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Output_InvalidDescription ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( WithAbstractExportOutput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void Output_InvalidTypeDescription ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( WithMissTypedOutput . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void InstantiateFailure ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( InstantiateFailJobFlow . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } @ Test public void DescribeFailure ( ) { JobFlowDriver analyzed = JobFlowDriver . analyze ( DescribeFailJobFlow . class ) ; assertThat ( analyzed . hasError ( ) , is ( true ) ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class NotTypedOutput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; @ SuppressWarnings ( { "" , "" } ) public NotTypedOutput ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class InconsistentImportInput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public InconsistentImportInput ( @ Import ( name = "" , description = MockFooImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Error ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ FlowPart public class StickyStage extends FlowDescription { private In < Ex1 > in ; public StickyStage ( In < Ex1 > in ) { this . in = in ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Error error = f . error ( in ) ; core . stop ( error . out ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Cogroup ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ SuppressWarnings ( "" ) @ JobFlow ( name = "" ) public class CoGroupStage extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > out1 ; private Out < Ex2 > out2 ; public CoGroupStage ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; Cogroup cog = f . cogroup ( in1 , in2 ) ; out1 . add ( cog . r1 ) ; out2 . add ( cog . r2 ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithAbstractImportInput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public WithAbstractImportInput ( @ Import ( name = "" , description = AbstractImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class NoImportInput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public NoImportInput ( In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; public class TopLevelJobFlow { @ JobFlow ( name = "" ) public static class Inner extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public Inner ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . vocabulary . external . ImporterDescription ; public abstract class AbstractImporterDescription implements ImporterDescription { @ Override public Class < ? > getModelType ( ) { return null ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . CogroupAdd ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . FoldAdd ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; @ SuppressWarnings ( "" ) @ FlowPart public class CombineStage extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; public CombineStage ( In < Ex1 > in1 , Out < Ex1 > out1 , Out < Ex1 > out2 ) { this . in1 = in1 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; FoldAdd fold = f . foldAdd ( in1 ) ; CogroupAdd cogroup = f . cogroupAdd ( in1 ) ; out1 . add ( fold . out ) ; out2 . add ( cogroup . result ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class InvalidTypeImporterDescription implements ImporterDescription { @ Override public Class < ? > getModelType ( ) { return null ; } @ Override public DataSize getDataSize ( ) { return DataSize . UNKNOWN ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Branch ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ FlowPart public class BranchStage extends FlowDescription { private In < Ex1 > in ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; private Out < Ex1 > out3 ; public BranchStage ( In < Ex1 > in , Out < Ex1 > out1 , Out < Ex1 > out2 , Out < Ex1 > out3 ) { this . in = in ; this . out1 = out1 ; this . out2 = out2 ; this . out3 = out3 ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Branch branch = f . branch ( in ) ; out1 . add ( branch . yes ) ; out2 . add ( branch . yes ) ; out2 . add ( branch . no ) ; out3 . add ( branch . no ) ; core . stop ( branch . cancel ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithEmptyOutputName extends FlowDescription { private final In < MockHoge > in ; private final Out < MockHoge > out ; public WithEmptyOutputName ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . ExSummarizedMockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Summarize ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ SuppressWarnings ( "" ) @ JobFlow ( name = "" ) public class SimpleShuffleStage extends FlowDescription { private In < Ex1 > in ; private Out < ExSummarized > out ; public SimpleShuffleStage ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = ExSummarizedMockExporterDescription . class ) Out < ExSummarized > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; Summarize summarized = f . summarize ( in ) ; out . add ( summarized . out ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class MockHogeExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return MockHoge . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithMissTypedOutput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public WithMissTypedOutput ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = InvalidTypeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class MockFooExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return MockFoo . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class NoExportOutput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public NoExportOutput ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithInvalidInputName extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public WithInvalidInputName ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Branch ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Cogroup ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ SuppressWarnings ( "" ) @ JobFlow ( name = "" ) public class ComplexStage extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > out1 ; private Out < Ex2 > out2 ; public ComplexStage ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Update update = f . update ( in1 , ) ; Branch bra = f . branch ( update . out ) ; Cogroup cog = f . cogroup ( core . confluent ( bra . yes , bra . cancel ) , in2 ) ; core . stop ( bra . no ) ; out1 . add ( cog . r1 ) ; out2 . add ( cog . r2 ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class InconsistentExportOutput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public InconsistentExportOutput ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockFooExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class InvalidParameter extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public InvalidParameter ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out , int odd ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithExportInput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public WithExportInput ( @ Export ( name = "" , description = MockHogeExporterDescription . class ) @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Cogroup ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ FlowPart public class DuplicateStage extends FlowDescription { private In < Ex1 > in ; private Out < Ex1 > out ; public DuplicateStage ( In < Ex1 > in , Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Update update = f . update ( in , ) ; Cogroup cog1 = f . cogroup ( update . out , core . empty ( Ex2 . class ) ) ; Cogroup cog2 = f . cogroup ( update . out , core . empty ( Ex2 . class ) ) ; out . add ( cog1 . r1 ) ; out . add ( cog2 . r1 ) ; core . stop ( cog1 . r2 ) ; core . stop ( cog2 . r2 ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . vocabulary . external . ExporterDescription ; public abstract class AbstractExporterDescription implements ExporterDescription { @ Override public Class < ? > getModelType ( ) { return null ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class NoPublicConstructors extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; NoPublicConstructors ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Cogroup ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Random ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ FlowPart public class VolatileStage extends FlowDescription { private In < Ex1 > in ; private Out < Ex1 > out ; public VolatileStage ( In < Ex1 > in , Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Random rand = f . random ( in ) ; Cogroup cog1 = f . cogroup ( rand . out , core . empty ( Ex2 . class ) ) ; Cogroup cog2 = f . cogroup ( rand . out , core . empty ( Ex2 . class ) ) ; out . add ( cog1 . r1 ) ; out . add ( cog2 . r1 ) ; core . stop ( cog1 . r2 ) ; core . stop ( cog2 . r2 ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory . Op1 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ SuppressWarnings ( "" ) @ JobFlow ( name = "" ) public class SequentialMultiStage extends FlowDescription { private In < Ex1 > in ; private Out < Ex1 > out ; public SequentialMultiStage ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoGroupFlowFactory f = new CoGroupFlowFactory ( ) ; Op1 st1 = f . op1 ( in ) ; Op1 st2 = f . op1 ( st1 . r1 ) ; out . add ( st2 . r1 ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class InvalidTypeExporterDescription implements ExporterDescription { @ Override public Class < ? > getModelType ( ) { return null ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MultiPublicConstructor extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public MultiPublicConstructor ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } public MultiPublicConstructor ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out , @ Export ( name = "" , description = MockFooExporterDescription . class ) Out < MockFoo > odd ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . processor . operator . FoldFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . FoldFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Cogroup ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Confluent ; @ SuppressWarnings ( "" ) @ FlowPart public class TwinCogroupStage extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public TwinCogroupStage ( In < Ex1 > in1 , Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Cogroup cog1 = f . cogroup ( in1 , core . empty ( Ex2 . class ) ) ; Cogroup cog2 = f . cogroup ( in1 , core . empty ( Ex2 . class ) ) ; core . stop ( cog1 . r2 ) ; core . stop ( cog2 . r2 ) ; FoldFlowFactory fff = new FoldFlowFactory ( ) ; Confluent < Ex1 > con1 = core . confluent ( cog1 . r1 , cog2 . r1 ) ; Simple fold = fff . simple ( con1 ) ; out1 . add ( fold . out ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithEmptyInputName extends FlowDescription { private final In < MockHoge > in ; private final Out < MockHoge > out ; public WithEmptyInputName ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ SuppressWarnings ( "" ) @ JobFlow ( name = "" ) public class MultipleUpdateStage extends FlowDescription { private In < Ex1 > in ; private Out < Ex1 > out ; public MultipleUpdateStage ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; Update u1 = f . update ( in , ) ; Update u2 = f . update ( u1 . out , ) ; Update u3 = f . update ( u2 . out , ) ; out . add ( u3 . out ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithMissTypedInput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public WithMissTypedInput ( @ Import ( name = "" , description = InvalidTypeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class MockHogeImporterDescription extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return MockHoge . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" + getModelType ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class NotAnnotatedJobFlow extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public NotAnnotatedJobFlow ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Cogroup ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ SuppressWarnings ( "" ) @ FlowPart public class SplitStage extends FlowDescription { private final In < Ex1 > in1 ; private final Out < Ex1 > out1 ; private final Out < Ex1 > out2 ; public SplitStage ( In < Ex1 > in1 , Out < Ex1 > out1 , Out < Ex1 > out2 ) { this . in1 = in1 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Update update0 = f . update ( in1 , ) ; Update update1 = f . update ( core . checkpoint ( update0 . out ) , ) ; Cogroup cog1 = f . cogroup ( update1 . out , core . empty ( Ex2 . class ) ) ; core . stop ( cog1 . r2 ) ; Cogroup cog2 = f . cogroup ( update1 . out , core . empty ( Ex2 . class ) ) ; core . stop ( cog2 . r2 ) ; out1 . add ( cog1 . r1 ) ; out2 . add ( cog2 . r1 ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithAbstractExportOutput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public WithAbstractExportOutput ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = AbstractExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class NotTypedInput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; @ SuppressWarnings ( { "" , "" } ) public NotTypedInput ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithInvalidOutputName extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public WithInvalidOutputName ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class DescribeFailJobFlow extends FlowDescription { public DescribeFailJobFlow ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { return ; } @ Override protected void describe ( ) { throw new RuntimeException ( ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public abstract class AbstractJobFlow extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public AbstractJobFlow ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class MockFooImporterDescription extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return MockFoo . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" + getModelType ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class WithImportOutput extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public WithImportOutput ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Import ( name = "" , description = MockHogeImporterDescription . class ) @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory ; import com . asakusafw . compiler . flow . testing . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ SuppressWarnings ( "" ) @ JobFlow ( name = "" ) public class NoShuffleStage extends FlowDescription { private In < Ex1 > in ; private Out < Ex1 > out ; public NoShuffleStage ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { ExOperatorFactory f = new ExOperatorFactory ( ) ; Update update = f . update ( in , ) ; out . add ( update . out ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SimpleJobFlow extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public SimpleJobFlow ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . example ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class InstantiateFailJobFlow extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public InstantiateFailJobFlow ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; throw new RuntimeException ( ) ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; public class LocationTest { @ Test public void root ( ) { Location location = new Location ( null , "" ) ; assertThat ( location . getParent ( ) , is ( nullValue ( ) ) ) ; assertThat ( location . getName ( ) , is ( "" ) ) ; } @ Test public void child ( ) { Location parent = new Location ( null , "" ) ; Location location = new Location ( parent , "" ) ; assertThat ( location . getParent ( ) , is ( parent ) ) ; assertThat ( location . getName ( ) , is ( "" ) ) ; } @ Test public void prefix ( ) { Location location = new Location ( null , "" ) ; assertThat ( location . isPrefix ( ) , is ( false ) ) ; Location prefix = location . asPrefix ( ) ; assertThat ( location . isPrefix ( ) , is ( false ) ) ; assertThat ( prefix . isPrefix ( ) , is ( true ) ) ; } @ Test public void appendString ( ) { Location root = new Location ( null , "" ) ; Location append = root . append ( "" ) ; assertThat ( append . getParent ( ) , is ( root ) ) ; assertThat ( append . getName ( ) , is ( "" ) ) ; } @ Test public void appendLocation ( ) { Location branch = new Location ( null , "" ) ; Location last = new Location ( branch , "" ) ; Location root = new Location ( null , "" ) ; Location append = root . append ( last ) ; Location rootBranch = new Location ( root , "" ) ; assertThat ( append . getParent ( ) , is ( rootBranch ) ) ; assertThat ( append . getName ( ) , is ( "" ) ) ; } @ Test public void convert_trivial ( ) { Location root = Location . fromPath ( "" , '' ) ; assertThat ( root . toPath ( '' ) , is ( "" ) ) ; } @ Test public void convert_path ( ) { Location root = Location . fromPath ( "" , '>' ) ; assertThat ( root . toPath ( '' ) , is ( "" ) ) ; } @ Test public void convert_normalize ( ) { Location root = Location . fromPath ( "" , '' ) ; assertThat ( root . toPath ( '' ) , is ( "" ) ) ; } @ Test public void convert_prefix ( ) { Location root = Location . fromPath ( "" , '' ) ; assertThat ( root . toPath ( '' ) , is ( "" ) ) ; } @ Test public void isPrefixOf_same ( ) { assertThat ( loc ( "" ) . isPrefixOf ( loc ( "" ) ) , is ( true ) ) ; } @ Test public void isPrefixOf_truth ( ) { assertThat ( loc ( "" ) . isPrefixOf ( loc ( "" ) ) , is ( true ) ) ; } @ Test public void isPrefixOf_reverse ( ) { assertThat ( loc ( "" ) . isPrefixOf ( loc ( "" ) ) , is ( false ) ) ; } @ Test public void isPrefixOf_otherRoot ( ) { assertThat ( loc ( "" ) . isPrefixOf ( loc ( "" ) ) , is ( false ) ) ; } private Location loc ( String path ) { return Location . fromPath ( path , '' ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . Part2Input ; import com . asakusafw . compiler . flow . testing . io . Part2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Part2Input . class ) @ ModelOutputLocation ( Part2Output . class ) public class Part2 implements DataModel < Part2 > , Writable { private final LongOption sid = new LongOption ( ) ; private final StringOption string = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . string . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Part2 other ) { this . sid . copyFrom ( other . sid ) ; this . string . copyFrom ( other . string ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value ) { this . sid . modify ( value ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value ) { this . string . modify ( value ) ; } public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + string . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Part2 other = ( Part2 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . string . equals ( other . string ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; string . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; string . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . ExJoinedInput ; import com . asakusafw . compiler . flow . testing . io . ExJoinedOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; @ DataModelKind ( "" ) @ Joined ( terms = { @ Joined . Term ( source = Ex1 . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) , @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) , @ Joined . Term ( source = Ex2 . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) , @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) } ) @ ModelInputLocation ( ExJoinedInput . class ) @ ModelOutputLocation ( ExJoinedOutput . class ) public class ExJoined implements DataModel < ExJoined > , Writable { private final LongOption sid1 = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; private final LongOption sid2 = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid1 . setNull ( ) ; this . value . setNull ( ) ; this . sid2 . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( ExJoined other ) { this . sid1 . copyFrom ( other . sid1 ) ; this . value . copyFrom ( other . value ) ; this . sid2 . copyFrom ( other . sid2 ) ; } public long getSid1 ( ) { return this . sid1 . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid1 ( long value0 ) { this . sid1 . modify ( value0 ) ; } public LongOption getSid1Option ( ) { return this . sid1 ; } @ SuppressWarnings ( "" ) public void setSid1Option ( LongOption option ) { this . sid1 . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } public long getSid2 ( ) { return this . sid2 . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid2 ( long value0 ) { this . sid2 . modify ( value0 ) ; } public LongOption getSid2Option ( ) { return this . sid2 ; } @ SuppressWarnings ( "" ) public void setSid2Option ( LongOption option ) { this . sid2 . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid1 ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . sid2 ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid1 . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + sid2 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExJoined other = ( ExJoined ) obj ; if ( this . sid1 . equals ( other . sid1 ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . sid2 . equals ( other . sid2 ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { sid1 . write ( out ) ; value . write ( out ) ; sid2 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid1 . readFields ( in ) ; value . readFields ( in ) ; sid2 . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . Part1Input ; import com . asakusafw . compiler . flow . testing . io . Part1Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Part1Input . class ) @ ModelOutputLocation ( Part1Output . class ) public class Part1 implements DataModel < Part1 > , Writable { private final LongOption sid = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Part1 other ) { this . sid . copyFrom ( other . sid ) ; this . value . copyFrom ( other . value ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value0 ) { this . sid . modify ( value0 ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Part1 other = ( Part1 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; value . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . ExJoined2Input ; import com . asakusafw . compiler . flow . testing . io . ExJoined2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; @ DataModelKind ( "" ) @ Joined ( terms = { @ Joined . Term ( source = Ex1 . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) , @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) , @ Joined . Term ( source = Ex2 . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) , @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) } ) @ ModelInputLocation ( ExJoined2Input . class ) @ ModelOutputLocation ( ExJoined2Output . class ) public class ExJoined2 implements DataModel < ExJoined2 > , Writable { private final LongOption sid1 = new LongOption ( ) ; private final IntOption key = new IntOption ( ) ; private final LongOption sid2 = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid1 . setNull ( ) ; this . key . setNull ( ) ; this . sid2 . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( ExJoined2 other ) { this . sid1 . copyFrom ( other . sid1 ) ; this . key . copyFrom ( other . key ) ; this . sid2 . copyFrom ( other . sid2 ) ; } public long getSid1 ( ) { return this . sid1 . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid1 ( long value ) { this . sid1 . modify ( value ) ; } public LongOption getSid1Option ( ) { return this . sid1 ; } @ SuppressWarnings ( "" ) public void setSid1Option ( LongOption option ) { this . sid1 . copyFrom ( option ) ; } public int getKey ( ) { return this . key . get ( ) ; } @ SuppressWarnings ( "" ) public void setKey ( int value ) { this . key . modify ( value ) ; } public IntOption getKeyOption ( ) { return this . key ; } @ SuppressWarnings ( "" ) public void setKeyOption ( IntOption option ) { this . key . copyFrom ( option ) ; } public long getSid2 ( ) { return this . sid2 . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid2 ( long value ) { this . sid2 . modify ( value ) ; } public LongOption getSid2Option ( ) { return this . sid2 ; } @ SuppressWarnings ( "" ) public void setSid2Option ( LongOption option ) { this . sid2 . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid1 ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . sid2 ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid1 . hashCode ( ) ; result = prime * result + key . hashCode ( ) ; result = prime * result + sid2 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExJoined2 other = ( ExJoined2 ) obj ; if ( this . sid1 . equals ( other . sid1 ) == false ) { return false ; } if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . sid2 . equals ( other . sid2 ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { sid1 . write ( out ) ; key . write ( out ) ; sid2 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid1 . readFields ( in ) ; key . readFields ( in ) ; sid2 . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . Ex2Input ; import com . asakusafw . compiler . flow . testing . io . Ex2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Ex2Input . class ) @ ModelOutputLocation ( Ex2Output . class ) public class Ex2 implements DataModel < Ex2 > , Writable { private final LongOption sid = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; private final StringOption string = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . value . setNull ( ) ; this . string . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Ex2 other ) { this . sid . copyFrom ( other . sid ) ; this . value . copyFrom ( other . value ) ; this . string . copyFrom ( other . string ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value0 ) { this . sid . modify ( value0 ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value0 ) { this . string . modify ( value0 ) ; } public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + string . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Ex2 other = ( Ex2 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . string . equals ( other . string ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; value . write ( out ) ; string . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; value . readFields ( in ) ; string . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . Ex1Input ; import com . asakusafw . compiler . flow . testing . io . Ex1Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Ex1Input . class ) @ ModelOutputLocation ( Ex1Output . class ) public class Ex1 implements DataModel < Ex1 > , Writable { private final LongOption sid = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; private final StringOption string = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . value . setNull ( ) ; this . string . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Ex1 other ) { this . sid . copyFrom ( other . sid ) ; this . value . copyFrom ( other . value ) ; this . string . copyFrom ( other . string ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value0 ) { this . sid . modify ( value0 ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value0 ) { this . string . modify ( value0 ) ; } public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + string . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Ex1 other = ( Ex1 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . string . equals ( other . string ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; value . write ( out ) ; string . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; value . readFields ( in ) ; string . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . ExSummarizedInput ; import com . asakusafw . compiler . flow . testing . io . ExSummarizedOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; @ DataModelKind ( "" ) @ ModelInputLocation ( ExSummarizedInput . class ) @ ModelOutputLocation ( ExSummarizedOutput . class ) @ Summarized ( term = @ Summarized . Term ( source = Ex1 . class , foldings = { @ Summarized . Folding ( aggregator = Summarized . Aggregator . ANY , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . SUM , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . COUNT , source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) ) public class ExSummarized implements DataModel < ExSummarized > , Writable { private final StringOption string = new StringOption ( ) ; private final LongOption value = new LongOption ( ) ; private final LongOption count = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . string . setNull ( ) ; this . value . setNull ( ) ; this . count . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( ExSummarized other ) { this . string . copyFrom ( other . string ) ; this . value . copyFrom ( other . value ) ; this . count . copyFrom ( other . count ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value0 ) { this . string . modify ( value0 ) ; } public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } public long getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( long value0 ) { this . value . modify ( value0 ) ; } public LongOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( LongOption option ) { this . value . copyFrom ( option ) ; } public long getCount ( ) { return this . count . get ( ) ; } @ SuppressWarnings ( "" ) public void setCount ( long value0 ) { this . count . modify ( value0 ) ; } public LongOption getCountOption ( ) { return this . count ; } @ SuppressWarnings ( "" ) public void setCountOption ( LongOption option ) { this . count . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . count ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + string . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + count . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExSummarized other = ( ExSummarized ) obj ; if ( this . string . equals ( other . string ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . count . equals ( other . count ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { string . write ( out ) ; value . write ( out ) ; count . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { string . readFields ( in ) ; value . readFields ( in ) ; count . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . ExSummarized2Input ; import com . asakusafw . compiler . flow . testing . io . ExSummarized2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; @ DataModelKind ( "" ) @ ModelInputLocation ( ExSummarized2Input . class ) @ ModelOutputLocation ( ExSummarized2Output . class ) @ Summarized ( term = @ Summarized . Term ( source = Ex1 . class , foldings = { @ Summarized . Folding ( aggregator = Summarized . Aggregator . ANY , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . SUM , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . COUNT , source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) ) public class ExSummarized2 implements DataModel < ExSummarized2 > , Writable { private final StringOption key = new StringOption ( ) ; private final LongOption value = new LongOption ( ) ; private final LongOption count = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . key . setNull ( ) ; this . value . setNull ( ) ; this . count . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( ExSummarized2 other ) { this . key . copyFrom ( other . key ) ; this . value . copyFrom ( other . value ) ; this . count . copyFrom ( other . count ) ; } public Text getKey ( ) { return this . key . get ( ) ; } @ SuppressWarnings ( "" ) public void setKey ( Text value0 ) { this . key . modify ( value0 ) ; } public StringOption getKeyOption ( ) { return this . key ; } @ SuppressWarnings ( "" ) public void setKeyOption ( StringOption option ) { this . key . copyFrom ( option ) ; } public long getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( long value0 ) { this . value . modify ( value0 ) ; } public LongOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( LongOption option ) { this . value . copyFrom ( option ) ; } public long getCount ( ) { return this . count . get ( ) ; } @ SuppressWarnings ( "" ) public void setCount ( long value0 ) { this . count . modify ( value0 ) ; } public LongOption getCountOption ( ) { return this . count ; } @ SuppressWarnings ( "" ) public void setCountOption ( LongOption option ) { this . count . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . count ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + key . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + count . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExSummarized2 other = ( ExSummarized2 ) obj ; if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . count . equals ( other . count ) == false ) { return false ; } return true ; } public String getKeyAsString ( ) { return this . key . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setKeyAsString ( String key0 ) { this . key . modify ( key0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; value . write ( out ) ; count . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { key . readFields ( in ) ; value . readFields ( in ) ; count . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . flow . testing . io . KeyConflictInput ; import com . asakusafw . compiler . flow . testing . io . KeyConflictOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; @ DataModelKind ( "" ) @ ModelInputLocation ( KeyConflictInput . class ) @ ModelOutputLocation ( KeyConflictOutput . class ) @ Summarized ( term = @ Summarized . Term ( source = Ex1 . class , foldings = { @ Summarized . Folding ( aggregator = Summarized . Aggregator . ANY , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . COUNT , source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) ) public class KeyConflict implements DataModel < KeyConflict > , Writable { private final StringOption key = new StringOption ( ) ; private final LongOption count = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . key . setNull ( ) ; this . count . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( KeyConflict other ) { this . key . copyFrom ( other . key ) ; this . count . copyFrom ( other . count ) ; } public Text getKey ( ) { return this . key . get ( ) ; } @ SuppressWarnings ( "" ) public void setKey ( Text value ) { this . key . modify ( value ) ; } public StringOption getKeyOption ( ) { return this . key ; } @ SuppressWarnings ( "" ) public void setKeyOption ( StringOption option ) { this . key . copyFrom ( option ) ; } public long getCount ( ) { return this . count . get ( ) ; } @ SuppressWarnings ( "" ) public void setCount ( long value ) { this . count . modify ( value ) ; } public LongOption getCountOption ( ) { return this . count ; } @ SuppressWarnings ( "" ) public void setCountOption ( LongOption option ) { this . count . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . count ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + key . hashCode ( ) ; result = prime * result + count . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } KeyConflict other = ( KeyConflict ) obj ; if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . count . equals ( other . count ) == false ) { return false ; } return true ; } public String getKeyAsString ( ) { return this . key . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setKeyAsString ( String key0 ) { this . key . modify ( key0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; count . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { key . readFields ( in ) ; count . readFields ( in ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . ExJoined2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class ExJoined2Output implements ModelOutput < ExJoined2 > { private final RecordEmitter emitter ; public ExJoined2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExJoined2 model ) throws IOException { emitter . emit ( model . getSid1Option ( ) ) ; emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getSid2Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Ex1Input implements ModelInput < Ex1 > { private final RecordParser parser ; public Ex1Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Ex1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getStringOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class ExSummarizedOutput implements ModelOutput < ExSummarized > { private final RecordEmitter emitter ; public ExSummarizedOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExSummarized model ) throws IOException { emitter . emit ( model . getStringOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getCountOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Ex2Input implements ModelInput < Ex2 > { private final RecordParser parser ; public Ex2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Ex2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getStringOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Ex1Output implements ModelOutput < Ex1 > { private final RecordEmitter emitter ; public Ex1Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Ex1 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getStringOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Ex2Output implements ModelOutput < Ex2 > { private final RecordEmitter emitter ; public Ex2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Ex2 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getStringOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . ExSummarized2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class ExSummarized2Input implements ModelInput < ExSummarized2 > { private final RecordParser parser ; public ExSummarized2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExSummarized2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getCountOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . Part2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Part2Output implements ModelOutput < Part2 > { private final RecordEmitter emitter ; public Part2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Part2 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getStringOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class ExJoinedOutput implements ModelOutput < ExJoined > { private final RecordEmitter emitter ; public ExJoinedOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExJoined model ) throws IOException { emitter . emit ( model . getSid1Option ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getSid2Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class ExJoinedInput implements ModelInput < ExJoined > { private final RecordParser parser ; public ExJoinedInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExJoined model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSid1Option ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getSid2Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . KeyConflict ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class KeyConflictOutput implements ModelOutput < KeyConflict > { private final RecordEmitter emitter ; public KeyConflictOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( KeyConflict model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getCountOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . KeyConflict ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class KeyConflictInput implements ModelInput < KeyConflict > { private final RecordParser parser ; public KeyConflictInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( KeyConflict model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getCountOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Part1Output implements ModelOutput < Part1 > { private final RecordEmitter emitter ; public Part1Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Part1 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . ExSummarized2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class ExSummarized2Output implements ModelOutput < ExSummarized2 > { private final RecordEmitter emitter ; public ExSummarized2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExSummarized2 model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getCountOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Part1Input implements ModelInput < Part1 > { private final RecordParser parser ; public Part1Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Part1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . Part2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Part2Input implements ModelInput < Part2 > { private final RecordParser parser ; public Part2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Part2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getStringOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . ExJoined2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class ExJoined2Input implements ModelInput < ExJoined2 > { private final RecordParser parser ; public ExJoined2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExJoined2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSid1Option ( ) ) ; parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getSid2Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class ExSummarizedInput implements ModelInput < ExSummarized > { private final RecordParser parser ; public ExSummarizedInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExSummarized model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getStringOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getCountOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . KeyConflict ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class KeyConflictMockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return KeyConflict . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Part1MockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Part1 . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class ExSummarizedMockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return ExSummarized . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . ExSummarized2 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class ExSummarized2MockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return ExSummarized2 . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Ex1MockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; public class Ex1MockImporterDescription extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" + getModelType ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . ExJoined2 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class ExJoined2MockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return ExJoined2 . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . flow . testing . model . Part2 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; public class Part2MockImporterDescription extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Part2 . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" + getModelType ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . compiler . flow . testing . external ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; public class ExJoinedMockImporterDescription extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return ExJoined . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" + getModelType ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Ex2MockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex2 . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; public class Ex2MockImporterDescription extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Ex2 . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" + getModelType ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . Part2 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Part2MockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Part2 . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class ExJoinedMockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return ExJoined . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . flow . testing . external ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; public class Part1MockImporterDescription extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Part1 . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" + getModelType ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . compiler . flow . testing . operator ; import java . util . Arrays ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . Connectivity ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; import com . asakusafw . vocabulary . flow . processor . PartialAggregation ; import com . asakusafw . vocabulary . operator . CoGroup ; import com . asakusafw . vocabulary . operator . Fold ; @ Generated ( "" ) public class ExOperatorFactory { public static final class FoldAdd implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; FoldAdd ( Source < Ex1 > in ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Fold . class ) ; builder . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , in , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addOutput ( "" , in ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( ObservationCount . DONT_CARE ) ; builder . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder . toResolver ( ) ; this . $ . resolveInput ( "" , in ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . FoldAdd as ( String newName ) { this . $ . setName ( newName ) ; return this ; } } public ExOperatorFactory . FoldAdd foldAdd ( Source < Ex1 > in ) { return new ExOperatorFactory . FoldAdd ( in ) ; } public static final class Update implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Update ( Source < Ex1 > model , int value ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Update . class ) ; builder0 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( int . class ) ; builder0 . addInput ( "" , model ) ; builder0 . addOutput ( "" , model ) ; builder0 . addParameter ( "" , int . class , value ) ; builder0 . addAttribute ( ObservationCount . DONT_CARE ) ; this . $ = builder0 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Update as ( String newName0 ) { this . $ . setName ( newName0 ) ; return this ; } } public ExOperatorFactory . Update update ( Source < Ex1 > model , int value ) { return new ExOperatorFactory . Update ( model , value ) ; } public static final class Random implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Random ( Source < Ex1 > model ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Update . class ) ; builder1 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder1 . declareParameter ( Ex1 . class ) ; builder1 . addInput ( "" , model ) ; builder1 . addOutput ( "" , model ) ; builder1 . addAttribute ( ObservationCount . AT_MOST_ONCE ) ; this . $ = builder1 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Random as ( String newName1 ) { this . $ . setName ( newName1 ) ; return this ; } } public ExOperatorFactory . Random random ( Source < Ex1 > model ) { return new ExOperatorFactory . Random ( model ) ; } public static final class Error implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Error ( Source < Ex1 > model ) { OperatorDescription . Builder builder2 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Update . class ) ; builder2 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder2 . declareParameter ( Ex1 . class ) ; builder2 . addInput ( "" , model ) ; builder2 . addOutput ( "" , model ) ; builder2 . addAttribute ( ObservationCount . AT_LEAST_ONCE ) ; this . $ = builder2 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Error as ( String newName2 ) { this . $ . setName ( newName2 ) ; return this ; } } public ExOperatorFactory . Error error ( Source < Ex1 > model ) { return new ExOperatorFactory . Error ( model ) ; } public static final class Logging implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Logging ( Source < Ex1 > ex1 ) { OperatorDescription . Builder builder3 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Logging . class ) ; builder3 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder3 . declareParameter ( Ex1 . class ) ; builder3 . addInput ( "" , ex1 ) ; builder3 . addOutput ( "" , ex1 ) ; builder3 . addAttribute ( ObservationCount . AT_LEAST_ONCE ) ; builder3 . addAttribute ( Connectivity . OPTIONAL ) ; builder3 . addAttribute ( com . asakusafw . vocabulary . operator . Logging . Level . INFO ) ; this . $ = builder3 . toResolver ( ) ; this . $ . resolveInput ( "" , ex1 ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Logging as ( String newName3 ) { this . $ . setName ( newName3 ) ; return this ; } } public ExOperatorFactory . Logging logging ( Source < Ex1 > ex1 ) { return new ExOperatorFactory . Logging ( ex1 ) ; } public static final class Branch implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > yes ; public final Source < Ex1 > no ; public final Source < Ex1 > cancel ; Branch ( Source < Ex1 > model ) { OperatorDescription . Builder builder4 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Branch . class ) ; builder4 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder4 . declareParameter ( Ex1 . class ) ; builder4 . addInput ( "" , model ) ; builder4 . addOutput ( "" , model ) ; builder4 . addOutput ( "" , model ) ; builder4 . addOutput ( "" , model ) ; builder4 . addAttribute ( ObservationCount . DONT_CARE ) ; this . $ = builder4 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . yes = this . $ . resolveOutput ( "" ) ; this . no = this . $ . resolveOutput ( "" ) ; this . cancel = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Branch as ( String newName4 ) { this . $ . setName ( newName4 ) ; return this ; } } public ExOperatorFactory . Branch branch ( Source < Ex1 > model ) { return new ExOperatorFactory . Branch ( model ) ; } public static final class CogroupAdd implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > result ; CogroupAdd ( Source < Ex1 > list ) { OperatorDescription . Builder builder5 = new OperatorDescription . Builder ( CoGroup . class ) ; builder5 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder5 . declareParameter ( List . class ) ; builder5 . declareParameter ( Result . class ) ; builder5 . addInput ( "" , list , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . ASC ) } ) ) ) ; builder5 . addOutput ( "" , Ex1 . class ) ; builder5 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder5 . addAttribute ( ObservationCount . DONT_CARE ) ; builder5 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder5 . toResolver ( ) ; this . $ . resolveInput ( "" , list ) ; this . result = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . CogroupAdd as ( String newName5 ) { this . $ . setName ( newName5 ) ; return this ; } } public ExOperatorFactory . CogroupAdd cogroupAdd ( Source < Ex1 > list ) { return new ExOperatorFactory . CogroupAdd ( list ) ; } public static final class Cogroup implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; public final Source < Ex2 > r2 ; Cogroup ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { OperatorDescription . Builder builder6 = new OperatorDescription . Builder ( CoGroup . class ) ; builder6 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder6 . declareParameter ( List . class ) ; builder6 . declareParameter ( List . class ) ; builder6 . declareParameter ( Result . class ) ; builder6 . declareParameter ( Result . class ) ; builder6 . addInput ( "" , ex1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . ASC ) } ) ) ) ; builder6 . addInput ( "" , ex2 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . DESC ) } ) ) ) ; builder6 . addOutput ( "" , Ex1 . class ) ; builder6 . addOutput ( "" , Ex2 . class ) ; builder6 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder6 . addAttribute ( ObservationCount . DONT_CARE ) ; builder6 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder6 . toResolver ( ) ; this . $ . resolveInput ( "" , ex1 ) ; this . $ . resolveInput ( "" , ex2 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; this . r2 = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Cogroup as ( String newName6 ) { this . $ . setName ( newName6 ) ; return this ; } } public ExOperatorFactory . Cogroup cogroup ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { return new ExOperatorFactory . Cogroup ( ex1 , ex2 ) ; } public static final class Summarize implements Operator { private final FlowElementResolver $ ; public final Source < ExSummarized > out ; Summarize ( Source < Ex1 > model ) { OperatorDescription . Builder builder7 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Summarize . class ) ; builder7 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder7 . declareParameter ( Ex1 . class ) ; builder7 . addInput ( "" , model , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder7 . addOutput ( "" , ExSummarized . class ) ; builder7 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder7 . addAttribute ( ObservationCount . DONT_CARE ) ; builder7 . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder7 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Summarize as ( String newName7 ) { this . $ . setName ( newName7 ) ; return this ; } } public ExOperatorFactory . Summarize summarize ( Source < Ex1 > model ) { return new ExOperatorFactory . Summarize ( model ) ; } } package com . asakusafw . compiler . flow . testing . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; @ Generated ( "" ) public class ExOperatorImpl extends ExOperator { public ExOperatorImpl ( ) { return ; } @ Override public ExSummarized summarize ( Ex1 model ) { throw new UnsupportedOperationException ( "" ) ; } } package com . asakusafw . compiler . flow . testing . operator ; import java . util . Iterator ; import java . util . List ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . Branch ; import com . asakusafw . vocabulary . operator . CoGroup ; import com . asakusafw . vocabulary . operator . Fold ; import com . asakusafw . vocabulary . operator . Logging ; import com . asakusafw . vocabulary . operator . Sticky ; import com . asakusafw . vocabulary . operator . Summarize ; import com . asakusafw . vocabulary . operator . Update ; import com . asakusafw . vocabulary . operator . Volatile ; public abstract class ExOperator { @ Update public void update ( Ex1 model , int value ) { model . setValue ( value ) ; } @ Volatile @ Update public void random ( Ex1 model ) { model . setValue ( ( int ) ( Math . random ( ) * Integer . MAX_VALUE ) ) ; } @ Sticky @ Update public void error ( Ex1 model ) { throw new IllegalStateException ( ) ; } @ Fold public void foldAdd ( @ Key ( group = "" ) Ex1 a , Ex1 b ) { a . getValueOption ( ) . add ( b . getValueOption ( ) ) ; } @ CoGroup public void cogroupAdd ( @ Key ( group = "" , order = "" ) List < Ex1 > list , Result < Ex1 > result ) { Iterator < Ex1 > iter = list . iterator ( ) ; Ex1 first = iter . next ( ) ; while ( iter . hasNext ( ) ) { Ex1 next = iter . next ( ) ; first . getValueOption ( ) . add ( next . getValueOption ( ) ) ; } result . add ( first ) ; } @ Branch public Answer branch ( Ex1 model ) { int value = model . getValueOption ( ) . get ( ) ; if ( value == ) { return Answer . YES ; } if ( value == ) { return Answer . NO ; } return Answer . CANCEL ; } @ Summarize public abstract ExSummarized summarize ( Ex1 model ) ; @ CoGroup public void cogroup ( @ Key ( group = "" , order = "" ) List < Ex1 > ex1 , @ Key ( group = "" , order = "" ) List < Ex2 > ex2 , Result < Ex1 > r1 , Result < Ex2 > r2 ) { if ( ex1 . isEmpty ( ) == false ) { r1 . add ( ex1 . get ( ) ) ; } if ( ex2 . isEmpty ( ) == false ) { r2 . add ( ex2 . get ( ) ) ; } } @ Logging public String logging ( Ex1 ex1 ) { return ex1 . getStringOption ( ) . toString ( ) ; } public enum Answer { YES , NO , CANCEL , } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . apache . hadoop . io . RawComparator ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . CoGroupStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class ShuffleSortComparatorEmitterTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) throws Exception { ShuffleModel analyzed = shuffle ( CoGroupStage . class ) ; ShuffleSortComparatorEmitter emitter = new ShuffleSortComparatorEmitter ( environment ) ; Name key = emitKey ( analyzed ) ; Name name = emitter . emit ( analyzed , key ) ; ClassLoader loader = start ( ) ; @ SuppressWarnings ( "" ) RawComparator < Writable > cmp = ( RawComparator < Writable > ) create ( loader , name ) ; SegmentedWritable k1 = ( SegmentedWritable ) create ( loader , key ) ; SegmentedWritable k2 = ( SegmentedWritable ) create ( loader , key ) ; List < Segment > segments = analyzed . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; Segment seg1 = segments . get ( ) ; Segment seg2 = segments . get ( ) ; assertThat ( seg1 . getTerms ( ) . size ( ) , is ( ) ) ; assertThat ( seg2 . getTerms ( ) . size ( ) , is ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; setShuffleKey ( seg1 , k1 , ex1 ) ; ex1 . setStringAsString ( "" ) ; setShuffleKey ( seg1 , k2 , ex1 ) ; assertThat ( cmp . compare ( k1 , k2 ) , is ( ) ) ; assertThat ( cmp . compare ( k2 , k1 ) , is ( ) ) ; setShuffleKey ( seg1 , k1 , ex1 ) ; ex1 . setSid ( ) ; setShuffleKey ( seg1 , k2 , ex1 ) ; assertThat ( cmp . compare ( k1 , k2 ) , greaterThan ( ) ) ; assertThat ( cmp . compare ( k2 , k1 ) , lessThan ( ) ) ; setShuffleKey ( seg1 , k1 , ex1 ) ; ex1 . setSid ( Integer . MIN_VALUE ) ; setShuffleKey ( seg1 , k2 , ex1 ) ; assertThat ( cmp . compare ( k1 , k2 ) , greaterThan ( ) ) ; assertThat ( cmp . compare ( k2 , k1 ) , lessThan ( ) ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; setShuffleKey ( seg2 , k1 , ex2 ) ; ex2 . setSid ( ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , is ( ) ) ; assertThat ( cmp . compare ( k2 , k1 ) , is ( ) ) ; setShuffleKey ( seg2 , k1 , ex2 ) ; ex2 . setStringAsString ( "" ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , greaterThan ( ) ) ; assertThat ( cmp . compare ( k2 , k1 ) , lessThan ( ) ) ; setShuffleKey ( seg2 , k1 , ex2 ) ; ex2 . setStringAsString ( "" ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , lessThan ( ) ) ; assertThat ( cmp . compare ( k2 , k1 ) , greaterThan ( ) ) ; setShuffleKey ( seg2 , k1 , ex2 ) ; ex2 . setString ( null ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , lessThan ( ) ) ; assertThat ( cmp . compare ( k2 , k1 ) , greaterThan ( ) ) ; setShuffleKey ( seg1 , k1 , ex1 ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , lessThan ( ) ) ; assertThat ( cmp . compare ( k2 , k1 ) , greaterThan ( ) ) ; } private ShuffleModel shuffle ( Class < ? extends FlowDescription > aClass ) { StageGraph graph = jfToStageGraph ( aClass ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; ShuffleAnalyzer analyzer = new ShuffleAnalyzer ( environment ) ; ShuffleModel analyzed = analyzer . analyze ( target ) ; return analyzed ; } private Name emitKey ( ShuffleModel model ) throws IOException { ShuffleKeyEmitter emitter = new ShuffleKeyEmitter ( environment ) ; Name name = emitter . emit ( model ) ; return name ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . lang . reflect . Type ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . NoShuffleStage ; import com . asakusafw . compiler . flow . example . SimpleShuffleStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Arrangement ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Term ; import com . asakusafw . runtime . value . StringOption ; public class ShuffleAnalyzerTest extends JobflowCompilerTestRoot { @ Test public void nothing ( ) { StageGraph graph = jfToStageGraph ( NoShuffleStage . class ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; ShuffleAnalyzer analyzer = new ShuffleAnalyzer ( environment ) ; ShuffleModel analyzed = analyzer . analyze ( target ) ; assertThat ( analyzed , is ( nullValue ( ) ) ) ; } @ Test public void simple ( ) { StageGraph graph = jfToStageGraph ( SimpleShuffleStage . class ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; ShuffleAnalyzer analyzer = new ShuffleAnalyzer ( environment ) ; ShuffleModel analyzed = analyzer . analyze ( target ) ; assertThat ( analyzed , not ( nullValue ( ) ) ) ; List < Segment > segments = analyzed . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; Segment segment = segments . get ( ) ; assertThat ( segment . getTerms ( ) . size ( ) , is ( ) ) ; Term grouping = segment . getTerms ( ) . get ( ) ; assertThat ( grouping . getArrangement ( ) , is ( Arrangement . GROUPING ) ) ; assertThat ( grouping . getSource ( ) . getName ( ) , is ( "" ) ) ; assertThat ( grouping . getSource ( ) . getType ( ) , equalTo ( ( Type ) StringOption . class ) ) ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . CoGroupStage ; import com . asakusafw . compiler . flow . example . SimpleShuffleStage ; import com . asakusafw . compiler . flow . mock . MockOutput ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class ShuffleFragmentEmitterTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) throws Exception { ShuffleModel analyzed = shuffle ( SimpleShuffleStage . class ) ; ShuffleFragmentEmitter emitter = new ShuffleFragmentEmitter ( environment ) ; Name key = emitKey ( analyzed ) ; Name value = emitValue ( analyzed ) ; Segment segment = analyzed . getSegments ( ) . get ( ) ; CompiledShuffleFragment compiled = emitter . emit ( segment , key , value , analyzed . getStageBlock ( ) ) ; ClassLoader loader = start ( ) ; MockResult < ? extends SegmentedWritable > keys = MockResult . create ( ) ; MockResult < ? extends SegmentedWritable > values = MockResult . create ( ) ; @ SuppressWarnings ( "" ) Result < Ex1 > output = ( Result < Ex1 > ) create ( loader , compiled . getMapOutputType ( ) . getQualifiedName ( ) , MockOutput . create ( keys , values ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; output . add ( ex1 ) ; List < ? extends SegmentedWritable > keyList = keys . getResults ( ) ; List < ? extends SegmentedWritable > valueList = values . getResults ( ) ; assertThat ( keyList . size ( ) , is ( ) ) ; assertThat ( valueList . size ( ) , is ( ) ) ; SegmentedWritable sKey = keyList . get ( ) ; SegmentedWritable sValue = valueList . get ( ) ; assertThat ( sKey . getSegmentId ( ) , is ( segment . getPortId ( ) ) ) ; assertThat ( sValue . getSegmentId ( ) , is ( segment . getPortId ( ) ) ) ; ExSummarized mapped = ( ExSummarized ) getShuffleValue ( segment , sValue ) ; assertThat ( mapped . getCount ( ) , is ( ) ) ; assertThat ( mapped . getValue ( ) , is ( ) ) ; } @ Test public void identity ( ) throws Exception { ShuffleModel analyzed = shuffle ( CoGroupStage . class ) ; ShuffleFragmentEmitter emitter = new ShuffleFragmentEmitter ( environment ) ; Name key = emitKey ( analyzed ) ; Name value = emitValue ( analyzed ) ; Segment segment = analyzed . getSegments ( ) . get ( ) ; CompiledShuffleFragment compiled = emitter . emit ( segment , key , value , analyzed . getStageBlock ( ) ) ; ClassLoader loader = start ( ) ; MockResult < ? extends SegmentedWritable > keys = MockResult . create ( ) ; MockResult < ? extends SegmentedWritable > values = MockResult . create ( ) ; @ SuppressWarnings ( "" ) Result < Ex1 > output = ( Result < Ex1 > ) create ( loader , compiled . getMapOutputType ( ) . getQualifiedName ( ) , MockOutput . create ( keys , values ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; output . add ( ex1 ) ; List < ? extends SegmentedWritable > keyList = keys . getResults ( ) ; List < ? extends SegmentedWritable > valueList = values . getResults ( ) ; assertThat ( keyList . size ( ) , is ( ) ) ; assertThat ( valueList . size ( ) , is ( ) ) ; SegmentedWritable sKey = keyList . get ( ) ; SegmentedWritable sValue = valueList . get ( ) ; assertThat ( sKey . getSegmentId ( ) , is ( segment . getPortId ( ) ) ) ; assertThat ( sValue . getSegmentId ( ) , is ( segment . getPortId ( ) ) ) ; Object shuffled = getShuffleValue ( segment , sValue ) ; assertThat ( shuffled , is ( ( Object ) ex1 ) ) ; } private ShuffleModel shuffle ( Class < ? extends FlowDescription > aClass ) { StageGraph graph = jfToStageGraph ( aClass ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; ShuffleAnalyzer analyzer = new ShuffleAnalyzer ( environment ) ; ShuffleModel analyzed = analyzer . analyze ( target ) ; assertThat ( environment . hasError ( ) , is ( false ) ) ; return analyzed ; } private Name emitKey ( ShuffleModel model ) throws IOException { ShuffleKeyEmitter emitter = new ShuffleKeyEmitter ( environment ) ; Name name = emitter . emit ( model ) ; return name ; } private Name emitValue ( ShuffleModel model ) throws IOException { ShuffleValueEmitter emitter = new ShuffleValueEmitter ( environment ) ; Name name = emitter . emit ( model ) ; return name ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . apache . hadoop . io . RawComparator ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . CoGroupStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class ShuffleGroupingComparatorEmitterTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) throws Exception { ShuffleModel analyzed = shuffle ( CoGroupStage . class ) ; ShuffleGroupingComparatorEmitter emitter = new ShuffleGroupingComparatorEmitter ( environment ) ; Name key = emitKey ( analyzed ) ; Name name = emitter . emit ( analyzed , key ) ; ClassLoader loader = start ( ) ; @ SuppressWarnings ( "" ) RawComparator < Writable > cmp = ( RawComparator < Writable > ) create ( loader , name ) ; SegmentedWritable k1 = ( SegmentedWritable ) create ( loader , key ) ; SegmentedWritable k2 = ( SegmentedWritable ) create ( loader , key ) ; List < Segment > segments = analyzed . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; Segment seg1 = segments . get ( ) ; Segment seg2 = segments . get ( ) ; assertThat ( seg1 . getTerms ( ) . size ( ) , is ( ) ) ; assertThat ( seg2 . getTerms ( ) . size ( ) , is ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; setShuffleKey ( seg1 , k1 , ex1 ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , is ( ) ) ; ex1 . setSid ( ) ; setShuffleKey ( seg1 , k1 , ex1 ) ; assertThat ( cmp . compare ( k1 , k2 ) , is ( ) ) ; ex2 . setStringAsString ( "" ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , is ( ) ) ; ex1 . setValue ( ) ; setShuffleKey ( seg1 , k1 , ex1 ) ; assertThat ( cmp . compare ( k1 , k2 ) , not ( ) ) ; ex2 . setValue ( ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , is ( ) ) ; ex2 . setValue ( ) ; setShuffleKey ( seg2 , k2 , ex2 ) ; assertThat ( cmp . compare ( k1 , k2 ) , not ( ) ) ; } private ShuffleModel shuffle ( Class < ? extends FlowDescription > aClass ) { StageGraph graph = jfToStageGraph ( aClass ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; ShuffleAnalyzer analyzer = new ShuffleAnalyzer ( environment ) ; ShuffleModel analyzed = analyzer . analyze ( target ) ; return analyzed ; } private Name emitKey ( ShuffleModel model ) throws IOException { ShuffleKeyEmitter emitter = new ShuffleKeyEmitter ( environment ) ; Name name = emitter . emit ( model ) ; return name ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . CoGroupStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class ShuffleValueEmitterTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) throws Exception { ShuffleModel analyzed = shuffle ( CoGroupStage . class ) ; ShuffleValueEmitter emitter = new ShuffleValueEmitter ( environment ) ; Name name = emitter . emit ( analyzed ) ; ClassLoader loader = start ( ) ; SegmentedWritable value = ( SegmentedWritable ) create ( loader , name ) ; List < Segment > segments = analyzed . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; Segment seg1 = segments . get ( ) ; Segment seg2 = segments . get ( ) ; assertThat ( seg1 . getTerms ( ) . size ( ) , is ( ) ) ; assertThat ( seg2 . getTerms ( ) . size ( ) , is ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; setShuffleValue ( seg1 , value , ex1 ) ; assertThat ( value . getSegmentId ( ) , is ( seg1 . getPortId ( ) ) ) ; Object r1 = getShuffleValue ( seg1 , value ) ; assertThat ( r1 , is ( ( Object ) ex1 ) ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; setShuffleValue ( seg2 , value , ex2 ) ; assertThat ( value . getSegmentId ( ) , is ( seg2 . getPortId ( ) ) ) ; Object r2 = getShuffleValue ( seg2 , value ) ; assertThat ( r2 , is ( ( Object ) ex2 ) ) ; } private ShuffleModel shuffle ( Class < ? extends FlowDescription > aClass ) { StageGraph graph = jfToStageGraph ( aClass ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; ShuffleAnalyzer analyzer = new ShuffleAnalyzer ( environment ) ; ShuffleModel analyzed = analyzer . analyze ( target ) ; assertThat ( environment . hasError ( ) , is ( false ) ) ; return analyzed ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . NoShuffleStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . MapUnit ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class MapFragmentEmitterTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) throws Exception { StageModel analyzed = mr ( NoShuffleStage . class ) ; MapUnit map = analyzed . getMapUnits ( ) . get ( ) ; assertThat ( map . getFragments ( ) . size ( ) , is ( ) ) ; Fragment fragment = map . getFragments ( ) . get ( ) ; MapFragmentEmitter emitter = new MapFragmentEmitter ( environment ) ; CompiledType name = emitter . emit ( fragment , analyzed . getStageBlock ( ) ) ; ClassLoader loader = start ( ) ; MockResult < Ex1 > result = MockResult . create ( ) ; Result < Ex1 > object = createResult ( loader , name . getQualifiedName ( ) , result ) ; object . add ( new Ex1 ( ) ) ; List < Ex1 > results = result . getResults ( ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValueOption ( ) . get ( ) , is ( ) ) ; } private StageModel mr ( Class < ? extends FlowDescription > aClass ) throws IOException { StageGraph graph = jfToStageGraph ( aClass ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; StageAnalyzer analyzer = new StageAnalyzer ( environment ) ; StageModel analyzed = analyzer . analyze ( target , compileShuffle ( target ) ) ; return analyzed ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . CoGroupStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Term ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class ShuffleKeyEmitterTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) throws Exception { ShuffleModel analyzed = shuffle ( CoGroupStage . class ) ; ShuffleKeyEmitter emitter = new ShuffleKeyEmitter ( environment ) ; Name name = emitter . emit ( analyzed ) ; ClassLoader loader = start ( ) ; SegmentedWritable key = ( SegmentedWritable ) create ( loader , name ) ; List < Segment > segments = analyzed . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; Segment seg1 = segments . get ( ) ; Segment seg2 = segments . get ( ) ; assertThat ( seg1 . getTerms ( ) . size ( ) , is ( ) ) ; assertThat ( seg2 . getTerms ( ) . size ( ) , is ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; setShuffleKey ( seg1 , key , ex1 ) ; assertThat ( key . getSegmentId ( ) , is ( seg1 . getPortId ( ) ) ) ; Object k1value = getKeyGroupField ( seg1 , "" , key ) ; assertThat ( k1value , is ( ( Object ) ex1 . getValueOption ( ) ) ) ; Object k1sid = getKeySortField ( seg1 , "" , key ) ; assertThat ( k1sid , is ( ( Object ) ex1 . getSidOption ( ) ) ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; setShuffleKey ( seg2 , key , ex2 ) ; assertThat ( key . getSegmentId ( ) , is ( seg2 . getPortId ( ) ) ) ; Object k2value = getKeyGroupField ( seg2 , "" , key ) ; assertThat ( k2value , is ( ( Object ) ex2 . getValueOption ( ) ) ) ; Object k2string = getKeySortField ( seg2 , "" , key ) ; assertThat ( k2string , is ( ( Object ) ex2 . getStringOption ( ) ) ) ; } private Object getKeyGroupField ( Segment segment , String propertyName , SegmentedWritable key ) { Term term = segment . findTerm ( propertyName ) ; assertThat ( propertyName , term , not ( nullValue ( ) ) ) ; String fieldName = Naming . getShuffleKeyGroupProperty ( segment . getElementId ( ) , term . getTermId ( ) ) ; return access ( key , fieldName ) ; } private Object getKeySortField ( Segment segment , String propertyName , SegmentedWritable key ) { Term term = segment . findTerm ( propertyName ) ; assertThat ( propertyName , term , not ( nullValue ( ) ) ) ; String fieldName = Naming . getShuffleKeySortProperty ( segment . getPortId ( ) , term . getTermId ( ) ) ; return access ( key , fieldName ) ; } private ShuffleModel shuffle ( Class < ? extends FlowDescription > aClass ) { StageGraph graph = jfToStageGraph ( aClass ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; ShuffleAnalyzer analyzer = new ShuffleAnalyzer ( environment ) ; ShuffleModel analyzed = analyzer . analyze ( target ) ; assertThat ( environment . hasError ( ) , is ( false ) ) ; return analyzed ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . apache . hadoop . mapreduce . Partitioner ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . CoGroupStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class ShufflePartitionerEmitterTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) throws Exception { ShuffleModel analyzed = shuffle ( CoGroupStage . class ) ; ShufflePartitionerEmitter emitter = new ShufflePartitionerEmitter ( environment ) ; Name key = emitKey ( analyzed ) ; Name value = emitValue ( analyzed ) ; Name name = emitter . emit ( analyzed , key , value ) ; ClassLoader loader = start ( ) ; @ SuppressWarnings ( "" ) Partitioner < Object , Object > part = ( Partitioner < Object , Object > ) create ( loader , name ) ; SegmentedWritable k = ( SegmentedWritable ) create ( loader , key ) ; SegmentedWritable v = ( SegmentedWritable ) create ( loader , value ) ; List < Segment > segments = analyzed . getSegments ( ) ; assertThat ( segments . size ( ) , is ( ) ) ; Segment seg1 = segments . get ( ) ; Segment seg2 = segments . get ( ) ; assertThat ( seg1 . getTerms ( ) . size ( ) , is ( ) ) ; assertThat ( seg2 . getTerms ( ) . size ( ) , is ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; int p01 , p02 ; setShuffleKeyValue ( seg1 , k , v , ex1 ) ; p01 = part . getPartition ( k , v , ) ; setShuffleKeyValue ( seg2 , k , v , ex2 ) ; p02 = part . getPartition ( k , v , ) ; assertThat ( p01 , is ( p02 ) ) ; setShuffleKeyValue ( seg1 , k , v , ex1 ) ; p01 = part . getPartition ( k , v , ) ; ex1 . setValue ( ) ; setShuffleKeyValue ( seg1 , k , v , ex1 ) ; p02 = part . getPartition ( k , v , ) ; assertThat ( p01 , not ( p02 ) ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; setShuffleKeyValue ( seg1 , k , v , ex1 ) ; p01 = part . getPartition ( k , v , ) ; setShuffleKeyValue ( seg2 , k , v , ex2 ) ; p02 = part . getPartition ( k , v , ) ; assertThat ( p01 , is ( p02 ) ) ; ex2 . setStringAsString ( "" ) ; setShuffleKeyValue ( seg1 , k , v , ex1 ) ; p01 = part . getPartition ( k , v , ) ; setShuffleKeyValue ( seg2 , k , v , ex2 ) ; p02 = part . getPartition ( k , v , ) ; assertThat ( p01 , is ( p02 ) ) ; ex1 . setValue ( ) ; setShuffleKeyValue ( seg1 , k , v , ex1 ) ; p01 = part . getPartition ( k , v , ) ; setShuffleKeyValue ( seg2 , k , v , ex2 ) ; p02 = part . getPartition ( k , v , ) ; assertThat ( p01 , not ( p02 ) ) ; ex2 . setValue ( ) ; setShuffleKeyValue ( seg1 , k , v , ex1 ) ; p01 = part . getPartition ( k , v , ) ; setShuffleKeyValue ( seg2 , k , v , ex2 ) ; p02 = part . getPartition ( k , v , ) ; assertThat ( p01 , is ( p02 ) ) ; ex2 . setValue ( ) ; setShuffleKeyValue ( seg1 , k , v , ex1 ) ; p01 = part . getPartition ( k , v , ) ; setShuffleKeyValue ( seg2 , k , v , ex2 ) ; p02 = part . getPartition ( k , v , ) ; assertThat ( p01 , not ( p02 ) ) ; } private ShuffleModel shuffle ( Class < ? extends FlowDescription > aClass ) { StageGraph graph = jfToStageGraph ( aClass ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; ShuffleAnalyzer analyzer = new ShuffleAnalyzer ( environment ) ; ShuffleModel analyzed = analyzer . analyze ( target ) ; return analyzed ; } private Name emitKey ( ShuffleModel model ) throws IOException { ShuffleKeyEmitter emitter = new ShuffleKeyEmitter ( environment ) ; Name name = emitter . emit ( model ) ; return name ; } private Name emitValue ( ShuffleModel model ) throws IOException { ShuffleValueEmitter emitter = new ShuffleValueEmitter ( environment ) ; Name name = emitter . emit ( model ) ; return name ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . MultipleUpdateStage ; import com . asakusafw . compiler . flow . example . NoShuffleStage ; import com . asakusafw . compiler . flow . example . SimpleShuffleStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . StageModel . Factor ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . MapUnit ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . compiler . flow . testing . operator . ExOperator ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; public class StageAnalyzerTest extends JobflowCompilerTestRoot { @ Test public void mapOnly ( ) { StageGraph graph = jfToStageGraph ( NoShuffleStage . class ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; StageAnalyzer analyzer = new StageAnalyzer ( environment ) ; StageModel analyzed = analyzer . analyze ( target , null ) ; assertThat ( analyzed . getMapUnits ( ) . size ( ) , is ( ) ) ; assertThat ( analyzed . getReduceUnits ( ) . size ( ) , is ( ) ) ; MapUnit map = analyzed . getMapUnits ( ) . get ( ) ; assertThat ( map . getFragments ( ) . size ( ) , is ( ) ) ; Fragment fragment = map . getFragments ( ) . get ( ) ; assertThat ( fragment . isRendezvous ( ) , is ( false ) ) ; assertThat ( fragment . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( fragment . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( fragment . getFactors ( ) . size ( ) , is ( ) ) ; Factor factor = fragment . getFactors ( ) . get ( ) ; assertThat ( factor . getElement ( ) . getDescription ( ) , instanceOf ( OperatorDescription . class ) ) ; OperatorDescription op = ( OperatorDescription ) factor . getElement ( ) . getDescription ( ) ; assertThat ( op . getDeclaration ( ) . getDeclaring ( ) , is ( ( Object ) ExOperator . class ) ) ; } @ Test public void withReduce ( ) { StageGraph graph = jfToStageGraph ( SimpleShuffleStage . class ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; StageAnalyzer analyzer = new StageAnalyzer ( environment ) ; StageModel analyzed = analyzer . analyze ( target , null ) ; assertThat ( analyzed . getMapUnits ( ) . size ( ) , is ( ) ) ; assertThat ( analyzed . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = analyzed . getReduceUnits ( ) . get ( ) ; assertThat ( reduce . getInputs ( ) . size ( ) , is ( ) ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; assertThat ( fragment . isRendezvous ( ) , is ( true ) ) ; assertThat ( fragment . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( fragment . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( fragment . getFactors ( ) . size ( ) , is ( ) ) ; Factor factor = fragment . getFactors ( ) . get ( ) ; assertThat ( factor . getElement ( ) . getDescription ( ) , instanceOf ( OperatorDescription . class ) ) ; OperatorDescription op = ( OperatorDescription ) factor . getElement ( ) . getDescription ( ) ; assertThat ( op . getDeclaration ( ) . getDeclaring ( ) , is ( ( Object ) ExOperator . class ) ) ; } @ Test public void sequencialFactors ( ) { StageGraph graph = jfToStageGraph ( MultipleUpdateStage . class ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; StageAnalyzer analyzer = new StageAnalyzer ( environment ) ; StageModel analyzed = analyzer . analyze ( target , null ) ; assertThat ( analyzed . getMapUnits ( ) . size ( ) , is ( ) ) ; assertThat ( analyzed . getReduceUnits ( ) . size ( ) , is ( ) ) ; MapUnit map = analyzed . getMapUnits ( ) . get ( ) ; assertThat ( map . getFragments ( ) . size ( ) , is ( ) ) ; Fragment fragment = map . getFragments ( ) . get ( ) ; assertThat ( fragment . isRendezvous ( ) , is ( false ) ) ; assertThat ( fragment . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( fragment . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( fragment . getFactors ( ) . size ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . stage ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . example . SimpleShuffleStage ; import com . asakusafw . compiler . flow . plan . StageBlock ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class ReduceFragmentEmitterTest extends JobflowCompilerTestRoot { @ SuppressWarnings ( "" ) @ Test public void simple ( ) throws Exception { StageModel analyzed = mr ( SimpleShuffleStage . class ) ; ReduceUnit red = analyzed . getReduceUnits ( ) . get ( ) ; assertThat ( red . getFragments ( ) . size ( ) , is ( ) ) ; Fragment fragment = red . getFragments ( ) . get ( ) ; ReduceFragmentEmitter emitter = new ReduceFragmentEmitter ( environment ) ; ShuffleModel shuffle = analyzed . getShuffleModel ( ) ; CompiledType name = emitter . emit ( fragment , shuffle , analyzed . getStageBlock ( ) ) ; ClassLoader loader = start ( ) ; MockResult < ExSummarized > result = MockResult . create ( ) ; Rendezvous < Writable > object = createRendezvous ( loader , name . getQualifiedName ( ) , result ) ; Writable key = ( Writable ) create ( loader , shuffle . getCompiled ( ) . getKeyTypeName ( ) ) ; Writable value = ( Writable ) create ( loader , shuffle . getCompiled ( ) . getValueTypeName ( ) ) ; Ex1 orig = new Ex1 ( ) ; orig . setValueOption ( new IntOption ( ) . modify ( ) ) ; ExSummarized model = new ExSummarized ( ) ; model . setValue ( ) ; model . setCount ( ) ; invoke ( key , Naming . getShuffleKeySetter ( ) , model ) ; invoke ( value , Naming . getShuffleValueSetter ( ) , model ) ; object . begin ( ) ; object . process ( value ) ; object . process ( value ) ; object . process ( value ) ; object . end ( ) ; List < ExSummarized > results = result . getResults ( ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getCount ( ) , is ( ) ) ; } private StageModel mr ( Class < ? extends FlowDescription > aClass ) throws IOException { StageGraph graph = jfToStageGraph ( aClass ) ; assertThat ( graph . getStages ( ) . size ( ) , is ( ) ) ; StageBlock target = graph . getStages ( ) . get ( ) ; StageAnalyzer analyzer = new StageAnalyzer ( environment ) ; StageModel analyzed = analyzer . analyze ( target , compileShuffle ( target ) ) ; return analyzed ; } } package com . asakusafw . compiler . flow . mapreduce . parallel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . compiler . testing . flow . IndependentOutExporterDesc ; import com . asakusafw . compiler . testing . flow . IndependentOutputJob ; import com . asakusafw . compiler . testing . flow . MultipleOutputJob ; import com . asakusafw . compiler . testing . flow . NestedOutExporterDesc ; import com . asakusafw . compiler . testing . flow . NestedOutputJob ; import com . asakusafw . compiler . testing . flow . Out1ExporterDesc ; import com . asakusafw . compiler . testing . flow . Out2ExporterDesc ; import com . asakusafw . compiler . testing . flow . Out3ExporterDesc ; import com . asakusafw . compiler . testing . flow . Out4ExporterDesc ; import com . asakusafw . compiler . testing . flow . SingleOutputJob ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . value . IntOption ; public class ParallelSortClientEmitterTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void single ( ) throws Exception { single0 ( ) ; } @ Test public void single_legacy ( ) throws Exception { tester . options ( ) . putExtraAttribute ( ParallelSortClientEmitter . ATTRIBUTE_LEGACY , "" ) ; single0 ( ) ; } private void single0 ( ) throws IOException { JobflowInfo info = tester . compileJobflow ( SingleOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; } @ Test public void multiple ( ) throws Exception { multiple0 ( ) ; } @ Test public void multiple_legacy ( ) throws Exception { tester . options ( ) . putExtraAttribute ( ParallelSortClientEmitter . ATTRIBUTE_LEGACY , "" ) ; multiple0 ( ) ; } private void multiple0 ( ) throws IOException { JobflowInfo info = tester . compileJobflow ( MultipleOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( Out2ExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; List < Ex1 > out3 = getList ( Out3ExporterDesc . class ) ; checkSids ( out3 ) ; checlValues ( out3 , ) ; List < Ex1 > out4 = getList ( Out4ExporterDesc . class ) ; checkSids ( out4 ) ; checlValues ( out4 , ) ; } @ Test public void independent ( ) throws Exception { independent0 ( ) ; } @ Test public void independent_legacy ( ) throws Exception { tester . options ( ) . putExtraAttribute ( ParallelSortClientEmitter . ATTRIBUTE_LEGACY , "" ) ; independent0 ( ) ; } private void independent0 ( ) throws IOException { JobflowInfo info = tester . compileJobflow ( IndependentOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( IndependentOutExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; } @ Test public void nested ( ) throws Exception { nested0 ( ) ; } @ Test public void nested_legacy ( ) throws Exception { tester . options ( ) . putExtraAttribute ( ParallelSortClientEmitter . ATTRIBUTE_LEGACY , "" ) ; nested0 ( ) ; } private void nested0 ( ) throws IOException { JobflowInfo info = tester . compileJobflow ( NestedOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( NestedOutExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; } private void checkSids ( List < Ex1 > results ) { assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getSidOption ( ) . isNull ( ) , is ( true ) ) ; for ( int i = ; i < ; i ++ ) { assertThat ( results . get ( i ) . getSid ( ) , is ( ( long ) i ) ) ; } } private void checlValues ( List < Ex1 > results , int value ) { for ( Ex1 ex1 : results ) { assertThat ( ex1 . getValueOption ( ) , is ( new IntOption ( value ) ) ) ; } } private void writeTestData ( ModelOutput < Ex1 > source ) throws IOException { Ex1 value = new Ex1 ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; } private List < Ex1 > getList ( Class < ? extends TemporaryOutputDescription > exporter ) { try { TemporaryOutputDescription instance = exporter . newInstance ( ) ; return tester . getList ( Ex1 . class , Location . fromPath ( instance . getPathPrefix ( ) , '' ) , new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . compiler . flow . mapreduce . parallel ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . DataClass . Property ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor . SourceInfo ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; public class SlotResolverTest extends JobflowCompilerTestRoot { @ Test public void single ( ) { SlotResolver resolver = new SlotResolver ( environment ) ; Slot slot = new Slot ( "" , Ex1 . class , Arrays . asList ( "" ) , Arrays . asList ( input ( "" ) ) , TemporaryOutputFormat . class ) ; List < ResolvedSlot > resolved = resolver . resolve ( Arrays . asList ( slot ) ) ; assertThat ( environment . hasError ( ) , is ( false ) ) ; assertThat ( resolved . size ( ) , is ( ) ) ; ResolvedSlot slot0 = resolved . get ( ) ; assertThat ( slot0 . getSource ( ) , is ( slot ) ) ; assertThat ( slot0 . getValueClass ( ) . getType ( ) , equalTo ( ( Object ) Ex1 . class ) ) ; assertThat ( slot0 . getSortProperties ( ) . size ( ) , is ( ) ) ; Property prop = slot0 . getSortProperties ( ) . get ( ) ; assertThat ( prop . getName ( ) , is ( "" ) ) ; } @ Test public void multiple ( ) { SlotResolver resolver = new SlotResolver ( environment ) ; List < Slot > slots = Arrays . asList ( new Slot [ ] { new Slot ( "" , Ex1 . class , Arrays . asList ( "" ) , Arrays . asList ( input ( "" ) ) , TemporaryOutputFormat . class ) , new Slot ( "" , Ex2 . class , Arrays . asList ( "" ) , Arrays . asList ( input ( "" ) ) , TemporaryOutputFormat . class ) , new Slot ( "" , Ex1 . class , Arrays . asList ( "" ) , Arrays . asList ( input ( "" ) ) , TemporaryOutputFormat . class ) , } ) ; List < ResolvedSlot > resolved = resolver . resolve ( slots ) ; assertThat ( environment . hasError ( ) , is ( false ) ) ; assertThat ( resolved . size ( ) , is ( ) ) ; assertThat ( resolved . get ( ) . getSlotNumber ( ) , is ( ) ) ; assertThat ( resolved . get ( ) . getSlotNumber ( ) , is ( ) ) ; assertThat ( resolved . get ( ) . getSlotNumber ( ) , is ( ) ) ; assertThat ( resolved . get ( ) . getValueClass ( ) . getType ( ) , equalTo ( ( Object ) Ex1 . class ) ) ; assertThat ( resolved . get ( ) . getValueClass ( ) . getType ( ) , equalTo ( ( Object ) Ex2 . class ) ) ; assertThat ( resolved . get ( ) . getValueClass ( ) . getType ( ) , equalTo ( ( Object ) Ex1 . class ) ) ; } @ Test public void invalid_class ( ) { SlotResolver resolver = new SlotResolver ( environment ) ; Slot slot = new Slot ( "" , Void . class , Arrays . asList ( "" ) , Arrays . asList ( input ( "" ) ) , TemporaryOutputFormat . class ) ; resolver . resolve ( Arrays . asList ( slot ) ) ; assertThat ( environment . hasError ( ) , is ( true ) ) ; } @ Test public void invalid_property ( ) { SlotResolver resolver = new SlotResolver ( environment ) ; Slot slot = new Slot ( "" , Ex1 . class , Arrays . asList ( "" ) , Arrays . asList ( input ( "" ) ) , TemporaryOutputFormat . class ) ; resolver . resolve ( Arrays . asList ( slot ) ) ; assertThat ( environment . hasError ( ) , is ( true ) ) ; } private SourceInfo input ( String path ) { return new SourceInfo ( Collections . singleton ( Location . fromPath ( path , '' ) ) , TemporaryInputFormat . class ) ; } } package com . asakusafw . compiler . flow ; import com . asakusafw . compiler . flow . example . MockHogeExporterDescription ; import com . asakusafw . compiler . flow . example . MockHogeImporterDescription ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) class NotPublicJobFlow extends FlowDescription { private In < MockHoge > in ; private Out < MockHoge > out ; public NotPublicJobFlow ( @ Import ( name = "" , description = MockHogeImporterDescription . class ) In < MockHoge > in , @ Export ( name = "" , description = MockHogeExporterDescription . class ) Out < MockHoge > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . ExtractFlowOp1 ; import com . asakusafw . compiler . flow . processor . flow . ExtractFlowOp2 ; import com . asakusafw . compiler . flow . processor . flow . ExtractFlowOp3 ; import com . asakusafw . compiler . flow . processor . flow . ExtractFlowWithParameter ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class ExtractFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void op1 ( ) { List < StageModel > stages = compile ( ExtractFlowOp1 . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > out1 = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( out1 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out1 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void op2 ( ) { List < StageModel > stages = compile ( ExtractFlowOp2 . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > out1 = mapper . create ( "" ) ; MockResult < Ex2 > out2 = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( out1 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out1 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( out2 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out2 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void op3 ( ) { List < StageModel > stages = compile ( ExtractFlowOp3 . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > out1 = mapper . create ( "" ) ; MockResult < Ex2 > out2 = mapper . create ( "" ) ; MockResult < Ex1 > out3 = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( out1 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out1 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( out2 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out2 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( out3 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out3 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void withParameter ( ) { List < StageModel > stages = compile ( ExtractFlowWithParameter . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex2 > out2 = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( out2 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out2 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Comparator ; import java . util . List ; import org . apache . hadoop . io . Writable ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . SummarizeFlowKeyConflict ; import com . asakusafw . compiler . flow . processor . flow . SummarizeFlowRenameKey ; import com . asakusafw . compiler . flow . processor . flow . SummarizeFlowTrivial ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . compiler . flow . testing . model . ExSummarized2 ; import com . asakusafw . compiler . flow . testing . model . KeyConflict ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class SummarizeFlowProcessorTest extends JobflowCompilerTestRoot { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void trivial ( ) { run ( false ) ; } @ Test public void combine ( ) { run ( true ) ; } @ Test public void renameKey ( ) throws Exception { runRenameKey ( false ) ; } @ Test public void combineRenameKey ( ) throws Exception { runRenameKey ( true ) ; } @ Test public void conflictKey ( ) throws Exception { runKeyConflict ( false ) ; } @ Test public void combineConflictKey ( ) throws Exception { runKeyConflict ( true ) ; } private void run ( boolean combine ) { environment . getOptions ( ) . setEnableCombiner ( combine ) ; List < StageModel > stages = compile ( SummarizeFlowTrivial . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < ExSummarized > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment segment = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; ExSummarized ex1 = new ExSummarized ( ) ; ex1 . setCount ( ) ; f . begin ( ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; f . end ( ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getCount ( ) , is ( ) ) ; } private void runRenameKey ( boolean combine ) throws Exception { environment . getOptions ( ) . setEnableCombiner ( combine ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < ExSummarized2 > summarized = tester . output ( ExSummarized2 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; assertThat ( tester . runFlow ( new SummarizeFlowRenameKey ( in . flow ( ) , summarized . flow ( ) ) ) , is ( true ) ) ; List < ExSummarized2 > results = summarized . toList ( new Comparator < ExSummarized2 > ( ) { @ Override public int compare ( ExSummarized2 o1 , ExSummarized2 o2 ) { return o1 . getKeyOption ( ) . compareTo ( o2 . getKeyOption ( ) ) ; } } ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getKeyAsString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . getCount ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getKeyAsString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . getCount ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; } private void runKeyConflict ( boolean combine ) throws Exception { environment . getOptions ( ) . setEnableCombiner ( combine ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < KeyConflict > summarized = tester . output ( KeyConflict . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in . add ( ex1 ) ; ex1 . setSid ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in . add ( ex1 ) ; ex1 . setSid ( ) ; in . add ( ex1 ) ; ex1 . setSid ( ) ; in . add ( ex1 ) ; assertThat ( tester . runFlow ( new SummarizeFlowKeyConflict ( in . flow ( ) , summarized . flow ( ) ) ) , is ( true ) ) ; List < KeyConflict > results = summarized . toList ( new Comparator < KeyConflict > ( ) { @ Override public int compare ( KeyConflict o1 , KeyConflict o2 ) { return o1 . getKeyOption ( ) . compareTo ( o2 . getKeyOption ( ) ) ; } } ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getKeyAsString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . getCount ( ) , is ( ) ) ; assertThat ( results . get ( ) . getKeyAsString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . getCount ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . apache . hadoop . io . Writable ; import org . junit . Assume ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . CoGroupFlowOp1 ; import com . asakusafw . compiler . flow . processor . flow . CoGroupFlowOp2 ; import com . asakusafw . compiler . flow . processor . flow . CoGroupFlowOp3 ; import com . asakusafw . compiler . flow . processor . flow . CoGroupFlowSwap ; import com . asakusafw . compiler . flow . processor . flow . CoGroupFlowWithParameter ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class CoGroupFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void op1 ( ) { List < StageModel > stages = compile ( CoGroupFlowOp1 . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment segment = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; f . begin ( ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; f . end ( ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void op2 ( ) { List < StageModel > stages = compile ( CoGroupFlowOp2 . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > r1 = mapper . create ( "" ) ; MockResult < Ex2 > r2 = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment s1 = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; Segment s2 = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setStringAsString ( "" ) ; ex2 . setStringAsString ( "" ) ; f . begin ( ) ; ex1 . setValue ( ) ; setShuffleValue ( s1 , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( s1 , value , ex1 ) ; f . process ( value ) ; ex2 . setValue ( ) ; setShuffleValue ( s2 , value , ex2 ) ; f . process ( value ) ; ex2 . setValue ( ) ; setShuffleValue ( s2 , value , ex2 ) ; f . process ( value ) ; f . end ( ) ; assertThat ( r1 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r1 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void op3 ( ) { List < StageModel > stages = compile ( CoGroupFlowOp3 . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > r1 = mapper . create ( "" ) ; MockResult < Ex1 > r2 = mapper . create ( "" ) ; MockResult < Ex1 > r3 = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment s1 = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; Segment s2 = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; Segment s3 = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; f . begin ( ) ; ex1 . setValue ( ) ; setShuffleValue ( s1 , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( s1 , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( s2 , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( s2 , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( s3 , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( s3 , value , ex1 ) ; f . process ( value ) ; f . end ( ) ; assertThat ( r1 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r1 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( r3 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r3 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void withParameter ( ) { List < StageModel > stages = compile ( CoGroupFlowWithParameter . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment segment = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; f . begin ( ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; f . end ( ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void swap ( ) { List < StageModel > stages = compile ( CoGroupFlowSwap . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment segment = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; f . begin ( ) ; for ( int i = ; i < ; i ++ ) { ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; } f . end ( ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( * ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . RestructureFlowExtend ; import com . asakusafw . compiler . flow . processor . flow . RestructureFlowProject ; import com . asakusafw . compiler . flow . processor . flow . RestructureFlowSame ; import com . asakusafw . compiler . flow . processor . flow . RestructureFlowSimple ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . compiler . flow . testing . model . Part2 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class RestructureFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void Part_Ex1 ( ) { List < StageModel > stages = compile ( RestructureFlowExtend . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Part1 > f = ( Result < Part1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Part1 in = new Part1 ( ) ; in . setSid ( ) ; in . setValue ( ) ; f . add ( in ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; Ex1 out = result . getResults ( ) . get ( ) ; assertThat ( out . getSid ( ) , is ( ) ) ; assertThat ( out . getValue ( ) , is ( ) ) ; assertThat ( out . getStringOption ( ) . isNull ( ) , is ( true ) ) ; } @ Test public void Ex1_Part ( ) { List < StageModel > stages = compile ( RestructureFlowProject . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Part1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 in = new Ex1 ( ) ; in . setSid ( ) ; in . setValue ( ) ; in . setStringAsString ( "" ) ; f . add ( in ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; Part1 out = result . getResults ( ) . get ( ) ; assertThat ( out . getSid ( ) , is ( ) ) ; assertThat ( out . getValue ( ) , is ( ) ) ; } @ Test public void Ex1_Ex2 ( ) { List < StageModel > stages = compile ( RestructureFlowSame . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex2 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 in = new Ex1 ( ) ; in . setSid ( ) ; in . setValue ( ) ; in . setStringAsString ( "" ) ; f . add ( in ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; Ex2 out = result . getResults ( ) . get ( ) ; assertThat ( out . getSid ( ) , is ( ) ) ; assertThat ( out . getValue ( ) , is ( ) ) ; assertThat ( out . getStringAsString ( ) , is ( "" ) ) ; } @ Test public void Part1_Part2 ( ) { List < StageModel > stages = compile ( RestructureFlowSimple . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Part2 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Part1 > f = ( Result < Part1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Part1 in = new Part1 ( ) ; in . setSid ( ) ; in . setValue ( ) ; f . add ( in ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; Part2 out = result . getResults ( ) . get ( ) ; assertThat ( out . getSid ( ) , is ( ) ) ; assertThat ( out . getStringOption ( ) . isNull ( ) , is ( true ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . UpdateFlowSimple ; import com . asakusafw . compiler . flow . processor . flow . UpdateFlowWithParameter ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class UpdateFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) { List < StageModel > stages = compile ( UpdateFlowSimple . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void withParameter ( ) { List < StageModel > stages = compile ( UpdateFlowWithParameter . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . BranchFlowSimple ; import com . asakusafw . compiler . flow . processor . flow . BranchFlowWithParameter ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class BranchFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) { List < StageModel > stages = compile ( BranchFlowSimple . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > high = mapper . create ( "" ) ; MockResult < Ex1 > low = mapper . create ( "" ) ; MockResult < Ex1 > stop = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( - ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . get ( ) , is ( ex1 ) ) ; stop . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . get ( ) , is ( ex1 ) ) ; stop . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . get ( ) , is ( ex1 ) ) ; low . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . get ( ) , is ( ex1 ) ) ; low . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . get ( ) , is ( ex1 ) ) ; low . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( high . getResults ( ) . get ( ) , is ( ex1 ) ) ; high . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( high . getResults ( ) . get ( ) , is ( ex1 ) ) ; high . getResults ( ) . clear ( ) ; } @ Test public void withParameter ( ) { List < StageModel > stages = compile ( BranchFlowWithParameter . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > high = mapper . create ( "" ) ; MockResult < Ex1 > low = mapper . create ( "" ) ; MockResult < Ex1 > stop = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( - ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . get ( ) , is ( ex1 ) ) ; stop . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . get ( ) , is ( ex1 ) ) ; stop . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . get ( ) , is ( ex1 ) ) ; low . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . get ( ) , is ( ex1 ) ) ; low . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . get ( ) , is ( ex1 ) ) ; low . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( high . getResults ( ) . get ( ) , is ( ex1 ) ) ; high . getResults ( ) . clear ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( high . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( low . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( stop . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( high . getResults ( ) . get ( ) , is ( ex1 ) ) ; high . getResults ( ) . clear ( ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . apache . hadoop . io . Writable ; import org . junit . Assume ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . GroupSortFlowMax ; import com . asakusafw . compiler . flow . processor . flow . GroupSortFlowMin ; import com . asakusafw . compiler . flow . processor . flow . GroupSortFlowWithParameter ; import com . asakusafw . compiler . flow . stage . ShuffleModel . Segment ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . stage . StageModel . ReduceUnit ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . flow . Rendezvous ; import com . asakusafw . runtime . flow . SegmentedWritable ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . vocabulary . operator . GroupSort ; public class GroupSortFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void max ( ) { List < StageModel > stages = compile ( GroupSortFlowMax . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . add ( "" , new Ex1Copier ( ) ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment segment = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; Ex1 ex1 = new Ex1 ( ) ; f . begin ( ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; f . end ( ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void min ( ) { List < StageModel > stages = compile ( GroupSortFlowMin . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . add ( "" , new Ex1Copier ( ) ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment segment = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; Ex1 ex1 = new Ex1 ( ) ; f . begin ( ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; f . end ( ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void withParameter ( ) { List < StageModel > stages = compile ( GroupSortFlowWithParameter . class ) ; StageModel stage = stages . get ( ) ; Assume . assumeThat ( stage . getReduceUnits ( ) . size ( ) , is ( ) ) ; ReduceUnit reduce = stage . getReduceUnits ( ) . get ( ) ; Fragment fragment = reduce . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > r1 = mapper . add ( "" , new Ex1Copier ( ) ) ; MockResult < Ex1 > r2 = mapper . add ( "" , new Ex1Copier ( ) ) ; @ SuppressWarnings ( "" ) Rendezvous < Writable > f = ( Rendezvous < Writable > ) create ( loader , name , mapper . toArguments ( ) ) ; Segment segment = stage . getShuffleModel ( ) . findSegment ( fragment . getInputPorts ( ) . get ( ) ) ; SegmentedWritable value = createShuffleValue ( loader , stage ) ; Ex1 ex1 = new Ex1 ( ) ; f . begin ( ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; ex1 . setValue ( ) ; setShuffleValue ( segment , value , ex1 ) ; f . process ( value ) ; f . end ( ) ; assertThat ( r1 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r1 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( r1 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } static class Ex1Copier extends MockResult < Ex1 > { @ Override protected Ex1 bless ( Ex1 result ) { Ex1 copy = new Ex1 ( ) ; copy . copyFrom ( result ) ; return copy ; } } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . processor . flow . MasterJoinFlowRenameKey ; import com . asakusafw . compiler . flow . processor . flow . MasterJoinFlowSelection ; import com . asakusafw . compiler . flow . processor . flow . MasterJoinFlowTrivial ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . compiler . flow . testing . model . ExJoined2 ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; public class MasterJoinFlowProcessorTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void trivial ( ) throws Exception { runEquality ( DataSize . UNKNOWN ) ; } @ Test public void tiny ( ) throws Exception { runEquality ( DataSize . TINY ) ; } private void runEquality ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" , dataSize ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" ) ; TestOutput < ExJoined > joined = tester . output ( ExJoined . class , "" ) ; TestOutput < Ex2 > missing = tester . output ( Ex2 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; assertThat ( tester . runFlow ( new MasterJoinFlowTrivial ( in1 . flow ( ) , in2 . flow ( ) , joined . flow ( ) , missing . flow ( ) ) ) , is ( true ) ) ; List < ExJoined > joinedList = joined . toList ( new Comparator < ExJoined > ( ) { @ Override public int compare ( ExJoined o1 , ExJoined o2 ) { return o1 . getSid2Option ( ) . compareTo ( o2 . getSid2Option ( ) ) ; } } ) ; List < Ex2 > missingList = missing . toList ( new Comparator < Ex2 > ( ) { @ Override public int compare ( Ex2 o1 , Ex2 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( joinedList . size ( ) , is ( ) ) ; assertThat ( missingList . size ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; } @ Test public void renameKey ( ) throws Exception { runRenameKey ( DataSize . UNKNOWN ) ; } @ Test public void renameKeyTiny ( ) throws Exception { runRenameKey ( DataSize . TINY ) ; } private void runRenameKey ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" , dataSize ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" ) ; TestOutput < ExJoined2 > joined = tester . output ( ExJoined2 . class , "" ) ; TestOutput < Ex2 > missing = tester . output ( Ex2 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; assertThat ( tester . runFlow ( new MasterJoinFlowRenameKey ( in1 . flow ( ) , in2 . flow ( ) , joined . flow ( ) , missing . flow ( ) ) ) , is ( true ) ) ; List < ExJoined2 > joinedList = joined . toList ( new Comparator < ExJoined2 > ( ) { @ Override public int compare ( ExJoined2 o1 , ExJoined2 o2 ) { return o1 . getSid2Option ( ) . compareTo ( o2 . getSid2Option ( ) ) ; } } ) ; List < Ex2 > missingList = missing . toList ( new Comparator < Ex2 > ( ) { @ Override public int compare ( Ex2 o1 , Ex2 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( joinedList . size ( ) , is ( ) ) ; assertThat ( missingList . size ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; } @ Test public void selection ( ) throws Exception { runNoEquality ( DataSize . UNKNOWN ) ; } @ Test public void tinySelection ( ) throws Exception { runNoEquality ( DataSize . TINY ) ; } private void runNoEquality ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" , dataSize ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" ) ; TestOutput < ExJoined > joined = tester . output ( ExJoined . class , "" ) ; TestOutput < Ex2 > missing = tester . output ( Ex2 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setSid ( ) ; ex2 . setStringAsString ( "" ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setValue ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; assertThat ( tester . runFlow ( new MasterJoinFlowSelection ( in1 . flow ( ) , in2 . flow ( ) , joined . flow ( ) , missing . flow ( ) ) ) , is ( true ) ) ; List < ExJoined > joinedList = joined . toList ( new Comparator < ExJoined > ( ) { @ Override public int compare ( ExJoined o1 , ExJoined o2 ) { return o1 . getSid2Option ( ) . compareTo ( o2 . getSid2Option ( ) ) ; } } ) ; List < Ex2 > missingList = missing . toList ( new Comparator < Ex2 > ( ) { @ Override public int compare ( Ex2 o1 , Ex2 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( joinedList . size ( ) , is ( ) ) ; assertThat ( missingList . size ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid1 ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid1 ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid2 ( ) , is ( ) ) ; assertThat ( joinedList . get ( ) . getSid1 ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class GroupSortFlowImpl extends GroupSortFlow { public GroupSortFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class ConvertFlowImpl extends ConvertFlow { public ConvertFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import com . asakusafw . compiler . flow . processor . UpdateFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . operator . Update ; public abstract class UpdateFlow { @ Update public void simple ( Ex1 model ) { withParameter ( model , ) ; } @ Update public void withParameter ( Ex1 model , int parameter ) { model . setValue ( model . getValue ( ) + parameter ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class LoggingFlowImpl extends LoggingFlow { public LoggingFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . Arrays ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . compiler . flow . testing . model . ExSummarized2 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . flow . processor . PartialAggregation ; import com . asakusafw . vocabulary . operator . Summarize ; @ Generated ( "" ) public class SummarizeFlowFactory { public static final class Simple implements Operator { private final FlowElementResolver $ ; public final Source < ExSummarized > out ; Simple ( Source < Ex1 > model ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Summarize . class ) ; builder . declare ( SummarizeFlow . class , SummarizeFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , model , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addOutput ( "" , ExSummarized . class ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( ObservationCount . DONT_CARE ) ; builder . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public SummarizeFlowFactory . Simple as ( String newName ) { this . $ . setName ( newName ) ; return this ; } } public SummarizeFlowFactory . Simple simple ( Source < Ex1 > model ) { return new SummarizeFlowFactory . Simple ( model ) ; } public static final class RenameKey implements Operator { private final FlowElementResolver $ ; public final Source < ExSummarized2 > out ; RenameKey ( Source < Ex1 > model ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( Summarize . class ) ; builder0 . declare ( SummarizeFlow . class , SummarizeFlowImpl . class , "" ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . addInput ( "" , model , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addOutput ( "" , ExSummarized2 . class ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder0 . addAttribute ( ObservationCount . DONT_CARE ) ; builder0 . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder0 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public SummarizeFlowFactory . RenameKey as ( String newName0 ) { this . $ . setName ( newName0 ) ; return this ; } } public SummarizeFlowFactory . RenameKey renameKey ( Source < Ex1 > model ) { return new SummarizeFlowFactory . RenameKey ( model ) ; } public static final class KeyConflict implements Operator { private final FlowElementResolver $ ; public final Source < com . asakusafw . compiler . flow . testing . model . KeyConflict > out ; KeyConflict ( Source < Ex1 > model ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( Summarize . class ) ; builder1 . declare ( SummarizeFlow . class , SummarizeFlowImpl . class , "" ) ; builder1 . declareParameter ( Ex1 . class ) ; builder1 . addInput ( "" , model , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder1 . addOutput ( "" , com . asakusafw . compiler . flow . testing . model . KeyConflict . class ) ; builder1 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder1 . addAttribute ( ObservationCount . DONT_CARE ) ; builder1 . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder1 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public SummarizeFlowFactory . KeyConflict as ( String newName1 ) { this . $ . setName ( newName1 ) ; return this ; } } public SummarizeFlowFactory . KeyConflict keyConflict ( Source < Ex1 > model ) { return new SummarizeFlowFactory . KeyConflict ( model ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import com . asakusafw . compiler . flow . processor . ConvertFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . operator . Convert ; public abstract class ConvertFlow { private Ex2 ex2 = new Ex2 ( ) ; @ Convert public Ex2 simple ( Ex1 model ) { return withParameter ( model , ) ; } @ Convert public Ex2 withParameter ( Ex1 model , int parameter ) { ex2 . setValue ( model . getValue ( ) + parameter ) ; return ex2 ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . Arrays ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; import com . asakusafw . vocabulary . operator . CoGroup ; @ Generated ( "" ) public class GroupSortFlowFactory { public static final class WithParameter implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; public final Source < Ex1 > r2 ; WithParameter ( Source < Ex1 > a1 , int parameter ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( CoGroup . class ) ; builder . declare ( GroupSortFlow . class , GroupSortFlowImpl . class , "" ) ; builder . declareParameter ( List . class ) ; builder . declareParameter ( Result . class ) ; builder . declareParameter ( Result . class ) ; builder . declareParameter ( int . class ) ; builder . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . ASC ) } ) ) ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addParameter ( "" , int . class , parameter ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( ObservationCount . DONT_CARE ) ; builder . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; this . r2 = this . $ . resolveOutput ( "" ) ; } public GroupSortFlowFactory . WithParameter as ( String newName ) { this . $ . setName ( newName ) ; return this ; } } public GroupSortFlowFactory . WithParameter withParameter ( Source < Ex1 > a1 , int parameter ) { return new GroupSortFlowFactory . WithParameter ( a1 , parameter ) ; } public static final class Min implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; Min ( Source < Ex1 > a1 ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( CoGroup . class ) ; builder0 . declare ( GroupSortFlow . class , GroupSortFlowImpl . class , "" ) ; builder0 . declareParameter ( List . class ) ; builder0 . declareParameter ( Result . class ) ; builder0 . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . ASC ) } ) ) ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder0 . addAttribute ( ObservationCount . DONT_CARE ) ; builder0 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder0 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; } public GroupSortFlowFactory . Min as ( String newName0 ) { this . $ . setName ( newName0 ) ; return this ; } } public GroupSortFlowFactory . Min min ( Source < Ex1 > a1 ) { return new GroupSortFlowFactory . Min ( a1 ) ; } public static final class Max implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; Max ( Source < Ex1 > a1 ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( CoGroup . class ) ; builder1 . declare ( GroupSortFlow . class , GroupSortFlowImpl . class , "" ) ; builder1 . declareParameter ( List . class ) ; builder1 . declareParameter ( Result . class ) ; builder1 . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . DESC ) } ) ) ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder1 . addAttribute ( ObservationCount . DONT_CARE ) ; builder1 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder1 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; } public GroupSortFlowFactory . Max as ( String newName1 ) { this . $ . setName ( newName1 ) ; return this ; } } public GroupSortFlowFactory . Max max ( Source < Ex1 > a1 ) { return new GroupSortFlowFactory . Max ( a1 ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Branch ; @ Generated ( "" ) public class BranchFlowFactory { public static final class Simple implements Operator { public final Source < Ex1 > high ; public final Source < Ex1 > low ; public final Source < Ex1 > stop ; Simple ( Source < Ex1 > model ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Branch . class ) ; builder . declare ( BranchFlow . class , BranchFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , model ) ; this . high = resolver . resolveOutput ( "" ) ; this . low = resolver . resolveOutput ( "" ) ; this . stop = resolver . resolveOutput ( "" ) ; } } public BranchFlowFactory . Simple simple ( Source < Ex1 > model ) { return new BranchFlowFactory . Simple ( model ) ; } public static final class WithParameter implements Operator { public final Source < Ex1 > high ; public final Source < Ex1 > low ; public final Source < Ex1 > stop ; WithParameter ( Source < Ex1 > model , int parameter ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Branch . class ) ; builder . declare ( BranchFlow . class , BranchFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . declareParameter ( int . class ) ; builder . addInput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addParameter ( "" , int . class , parameter ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , model ) ; this . high = resolver . resolveOutput ( "" ) ; this . low = resolver . resolveOutput ( "" ) ; this . stop = resolver . resolveOutput ( "" ) ; } } public BranchFlowFactory . WithParameter withParameter ( Source < Ex1 > model , int parameter ) { return new BranchFlowFactory . WithParameter ( model , parameter ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Convert ; @ Generated ( "" ) public class ConvertFlowFactory { public static final class WithParameter implements Operator { public final Source < Ex1 > original ; public final Source < Ex2 > out ; WithParameter ( Source < Ex1 > model , int parameter ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Convert . class ) ; builder . declare ( ConvertFlow . class , ConvertFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . declareParameter ( int . class ) ; builder . addInput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex2 . class ) ; builder . addParameter ( "" , int . class , parameter ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , model ) ; this . original = resolver . resolveOutput ( "" ) ; this . out = resolver . resolveOutput ( "" ) ; } } public ConvertFlowFactory . WithParameter withParameter ( Source < Ex1 > model , int parameter ) { return new ConvertFlowFactory . WithParameter ( model , parameter ) ; } public static final class Simple implements Operator { public final Source < Ex1 > original ; public final Source < Ex2 > out ; Simple ( Source < Ex1 > model ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Convert . class ) ; builder . declare ( ConvertFlow . class , ConvertFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex2 . class ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , model ) ; this . original = resolver . resolveOutput ( "" ) ; this . out = resolver . resolveOutput ( "" ) ; } } public ConvertFlowFactory . Simple simple ( Source < Ex1 > model ) { return new ConvertFlowFactory . Simple ( model ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import com . asakusafw . compiler . flow . processor . BranchFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . operator . Branch ; public abstract class BranchFlow { @ Branch public Speed simple ( Ex1 model ) { return withParameter ( model , ) ; } @ Branch public Speed withParameter ( Ex1 model , int parameter ) { if ( model . getValue ( ) > parameter ) { return Speed . HIGH ; } if ( model . getValue ( ) <= ) { return Speed . STOP ; } return Speed . LOW ; } public enum Speed { HIGH , LOW , STOP , } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . List ; import com . asakusafw . compiler . flow . processor . MasterCheckFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . MasterJoinUpdate ; import com . asakusafw . vocabulary . operator . MasterSelection ; public abstract class MasterJoinUpdateFlow { @ MasterJoinUpdate public void simple ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model ) { withParameter ( master , model , ) ; } @ MasterJoinUpdate public void withParameter ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model , int parameter ) { model . setValue ( ( int ) master . getSid ( ) + parameter ) ; } @ MasterJoinUpdate ( selection = "" ) public void selection ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model ) { withParameter ( master , model , ) ; } @ MasterSelection public Ex2 selector ( List < Ex2 > masters , Ex1 model ) { for ( Ex2 master : masters ) { if ( master . getValueOption ( ) . equals ( model . getValueOption ( ) ) ) { return master ; } } return null ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . Arrays ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; import com . asakusafw . vocabulary . operator . CoGroup ; @ Generated ( "" ) public class CoGroupFlowFactory { public static final class Op1 implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; Op1 ( Source < Ex1 > a1 ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( CoGroup . class ) ; builder . declare ( CoGroupFlow . class , CoGroupFlowImpl . class , "" ) ; builder . declareParameter ( List . class ) ; builder . declareParameter ( Result . class ) ; builder . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( ObservationCount . DONT_CARE ) ; builder . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; } public CoGroupFlowFactory . Op1 as ( String newName ) { this . $ . setName ( newName ) ; return this ; } } public CoGroupFlowFactory . Op1 op1 ( Source < Ex1 > a1 ) { return new CoGroupFlowFactory . Op1 ( a1 ) ; } public static final class Swap implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; Swap ( Source < Ex1 > a1 ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( CoGroup . class ) ; builder0 . declare ( CoGroupFlow . class , CoGroupFlowImpl . class , "" ) ; builder0 . declareParameter ( List . class ) ; builder0 . declareParameter ( Result . class ) ; builder0 . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder0 . addAttribute ( ObservationCount . DONT_CARE ) ; builder0 . addAttribute ( InputBuffer . ESCAPE ) ; this . $ = builder0 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; } public CoGroupFlowFactory . Swap as ( String newName0 ) { this . $ . setName ( newName0 ) ; return this ; } } public CoGroupFlowFactory . Swap swap ( Source < Ex1 > a1 ) { return new CoGroupFlowFactory . Swap ( a1 ) ; } public static final class Sorted implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; Sorted ( Source < Ex1 > a1 ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( CoGroup . class ) ; builder1 . declare ( CoGroupFlow . class , CoGroupFlowImpl . class , "" ) ; builder1 . declareParameter ( List . class ) ; builder1 . declareParameter ( Result . class ) ; builder1 . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . DESC ) } ) ) ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder1 . addAttribute ( ObservationCount . DONT_CARE ) ; builder1 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder1 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; } public CoGroupFlowFactory . Sorted as ( String newName1 ) { this . $ . setName ( newName1 ) ; return this ; } } public CoGroupFlowFactory . Sorted sorted ( Source < Ex1 > a1 ) { return new CoGroupFlowFactory . Sorted ( a1 ) ; } public static final class Op2 implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; public final Source < Ex2 > r2 ; Op2 ( Source < Ex1 > a1 , Source < Ex2 > a2 ) { OperatorDescription . Builder builder2 = new OperatorDescription . Builder ( CoGroup . class ) ; builder2 . declare ( CoGroupFlow . class , CoGroupFlowImpl . class , "" ) ; builder2 . declareParameter ( List . class ) ; builder2 . declareParameter ( List . class ) ; builder2 . declareParameter ( Result . class ) ; builder2 . declareParameter ( Result . class ) ; builder2 . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder2 . addInput ( "" , a2 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder2 . addOutput ( "" , Ex1 . class ) ; builder2 . addOutput ( "" , Ex2 . class ) ; builder2 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder2 . addAttribute ( ObservationCount . DONT_CARE ) ; builder2 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder2 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . $ . resolveInput ( "" , a2 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; this . r2 = this . $ . resolveOutput ( "" ) ; } public CoGroupFlowFactory . Op2 as ( String newName2 ) { this . $ . setName ( newName2 ) ; return this ; } } public CoGroupFlowFactory . Op2 op2 ( Source < Ex1 > a1 , Source < Ex2 > a2 ) { return new CoGroupFlowFactory . Op2 ( a1 , a2 ) ; } public static final class Op3 implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; public final Source < Ex1 > r2 ; public final Source < Ex1 > r3 ; Op3 ( Source < Ex1 > a1 , Source < Ex1 > a2 , Source < Ex1 > a3 ) { OperatorDescription . Builder builder3 = new OperatorDescription . Builder ( CoGroup . class ) ; builder3 . declare ( CoGroupFlow . class , CoGroupFlowImpl . class , "" ) ; builder3 . declareParameter ( List . class ) ; builder3 . declareParameter ( List . class ) ; builder3 . declareParameter ( List . class ) ; builder3 . declareParameter ( Result . class ) ; builder3 . declareParameter ( Result . class ) ; builder3 . declareParameter ( Result . class ) ; builder3 . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder3 . addInput ( "" , a2 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder3 . addInput ( "" , a3 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder3 . addOutput ( "" , Ex1 . class ) ; builder3 . addOutput ( "" , Ex1 . class ) ; builder3 . addOutput ( "" , Ex1 . class ) ; builder3 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder3 . addAttribute ( ObservationCount . DONT_CARE ) ; builder3 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder3 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . $ . resolveInput ( "" , a2 ) ; this . $ . resolveInput ( "" , a3 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; this . r2 = this . $ . resolveOutput ( "" ) ; this . r3 = this . $ . resolveOutput ( "" ) ; } public CoGroupFlowFactory . Op3 as ( String newName3 ) { this . $ . setName ( newName3 ) ; return this ; } } public CoGroupFlowFactory . Op3 op3 ( Source < Ex1 > a1 , Source < Ex1 > a2 , Source < Ex1 > a3 ) { return new CoGroupFlowFactory . Op3 ( a1 , a2 , a3 ) ; } public static final class WithParameter implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; WithParameter ( Source < Ex1 > a1 , int parameter ) { OperatorDescription . Builder builder4 = new OperatorDescription . Builder ( CoGroup . class ) ; builder4 . declare ( CoGroupFlow . class , CoGroupFlowImpl . class , "" ) ; builder4 . declareParameter ( List . class ) ; builder4 . declareParameter ( Result . class ) ; builder4 . declareParameter ( int . class ) ; builder4 . addInput ( "" , a1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder4 . addOutput ( "" , Ex1 . class ) ; builder4 . addParameter ( "" , int . class , parameter ) ; builder4 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder4 . addAttribute ( ObservationCount . DONT_CARE ) ; builder4 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder4 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; } public CoGroupFlowFactory . WithParameter as ( String newName4 ) { this . $ . setName ( newName4 ) ; return this ; } } public CoGroupFlowFactory . WithParameter withParameter ( Source < Ex1 > a1 , int parameter ) { return new CoGroupFlowFactory . WithParameter ( a1 , parameter ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class MasterJoinUpdateFlowImpl extends MasterJoinUpdateFlow { public MasterJoinUpdateFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; @ Generated ( "" ) public class MasterCheckFlowImpl extends MasterCheckFlow { public MasterCheckFlowImpl ( ) { return ; } @ Override public boolean simple ( Ex2 master , Ex1 model ) { throw new UnsupportedOperationException ( "" ) ; } @ Override public boolean selection ( Ex2 master , Ex1 model ) { throw new UnsupportedOperationException ( "" ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Logging ; @ Generated ( "" ) public class LoggingFlowFactory { public static final class WithParameter implements Operator { public final Source < Ex1 > out ; WithParameter ( Source < Ex1 > model , String parameter ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Logging . class ) ; builder . declare ( LoggingFlow . class , LoggingFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . declareParameter ( String . class ) ; builder . addInput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addParameter ( "" , String . class , parameter ) ; builder . addAttribute ( ObservationCount . AT_LEAST_ONCE ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , model ) ; this . out = resolver . resolveOutput ( "" ) ; } } public LoggingFlowFactory . WithParameter withParameter ( Source < Ex1 > model , String parameter ) { return new LoggingFlowFactory . WithParameter ( model , parameter ) ; } public static final class Simple implements Operator { public final Source < Ex1 > out ; Simple ( Source < Ex1 > model ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Logging . class ) ; builder . declare ( LoggingFlow . class , LoggingFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addAttribute ( ObservationCount . AT_LEAST_ONCE ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , model ) ; this . out = resolver . resolveOutput ( "" ) ; } } public LoggingFlowFactory . Simple simple ( Source < Ex1 > model ) { return new LoggingFlowFactory . Simple ( model ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class MasterBranchFlowImpl extends MasterBranchFlow { public MasterBranchFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class UpdateFlowImpl extends UpdateFlow { public UpdateFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . List ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . CoGroup ; import com . asakusafw . vocabulary . operator . GroupSort ; public abstract class GroupSortFlow { @ GroupSort public void min ( @ Key ( group = "" , order = "" ) List < Ex1 > a1 , Result < Ex1 > r1 ) { r1 . add ( a1 . get ( ) ) ; } @ GroupSort public void max ( @ Key ( group = "" , order = "" ) List < Ex1 > a1 , Result < Ex1 > r1 ) { r1 . add ( a1 . get ( ) ) ; } @ CoGroup public void withParameter ( @ Key ( group = "" , order = "" ) List < Ex1 > a1 , Result < Ex1 > r1 , Result < Ex1 > r2 , int parameter ) { boolean over = false ; for ( Ex1 e : a1 ) { over |= ( e . getValue ( ) > parameter ) ; if ( over ) { r2 . add ( e ) ; } else { r1 . add ( e ) ; } } } } package com . asakusafw . compiler . flow . processor . operator ; import com . asakusafw . compiler . flow . processor . FoldFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . Fold ; public abstract class FoldFlow { @ Fold public void simple ( @ Key ( group = "" ) Ex1 context , Ex1 right ) { withParameter ( context , right , ) ; } @ Fold public void withParameter ( @ Key ( group = "" ) Ex1 context , Ex1 right , int parameter ) { context . getValueOption ( ) . add ( right . getValueOption ( ) . or ( ) + parameter ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . List ; import com . asakusafw . compiler . flow . processor . MasterBranchFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . MasterBranch ; import com . asakusafw . vocabulary . operator . MasterSelection ; public abstract class MasterBranchFlow { @ MasterBranch public Speed simple ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model ) { return withParameter ( master , model , ) ; } @ MasterBranch public Speed withParameter ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model , int parameter ) { if ( master == null ) { return Speed . STOP ; } if ( master . getValue ( ) + model . getValue ( ) > parameter ) { return Speed . HIGH ; } if ( master . getValue ( ) + model . getValue ( ) <= ) { return Speed . STOP ; } return Speed . LOW ; } @ MasterBranch ( selection = "" ) public Speed selection ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model ) { return withParameter ( master , model , ) ; } @ MasterBranch ( selection = "" ) public Speed selectionWithParameter0 ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model , int parameter ) { return withParameter ( master , model , parameter ) ; } @ MasterBranch ( selection = "" ) public Speed selectionWithParameter1 ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model , int parameter ) { return withParameter ( master , model , parameter ) ; } @ MasterSelection public Ex2 selector ( List < Ex2 > masters , Ex1 model ) { for ( Ex2 master : masters ) { if ( master . getValueOption ( ) . equals ( model . getValueOption ( ) ) ) { return master ; } } return null ; } @ MasterSelection public Ex2 selectorWithParameter ( List < Ex2 > masters , Ex1 model , int parameter ) { for ( Ex2 master : masters ) { if ( master . getValueOption ( ) . has ( parameter ) ) { return master ; } } return null ; } public enum Speed { HIGH , LOW , STOP , } } package com . asakusafw . compiler . flow . processor . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import com . asakusafw . compiler . flow . processor . CoGroupFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . CoGroup ; public abstract class CoGroupFlow { @ CoGroup public void op1 ( @ Key ( group = "" ) List < Ex1 > a1 , Result < Ex1 > r1 ) { withParameter ( a1 , r1 , ) ; } @ CoGroup ( inputBuffer = InputBuffer . ESCAPE ) public void swap ( @ Key ( group = "" ) List < Ex1 > a1 , Result < Ex1 > r1 ) { withParameter ( a1 , r1 , ) ; } @ CoGroup public void sorted ( @ Key ( group = "" , order = "" ) List < Ex1 > a1 , Result < Ex1 > r1 ) { int current = a1 . get ( ) . getValue ( ) ; for ( Ex1 e : a1 ) { assertThat ( current , lessThanOrEqualTo ( e . getValue ( ) ) ) ; current = e . getValue ( ) ; } } @ CoGroup public void op2 ( @ Key ( group = "" ) List < Ex1 > a1 , @ Key ( group = "" ) List < Ex2 > a2 , Result < Ex1 > r1 , Result < Ex2 > r2 ) { String string = "" ; int value1 = ; int value2 = ; for ( Ex1 e : a1 ) { value1 += e . getValue ( ) ; string = e . getStringAsString ( ) ; } for ( Ex2 e : a2 ) { value2 += e . getValue ( ) ; string = e . getStringAsString ( ) ; } Ex1 re1 = new Ex1 ( ) ; Ex2 re2 = new Ex2 ( ) ; re1 . setValue ( value2 ) ; re2 . setValue ( value1 ) ; re1 . setStringAsString ( string ) ; re2 . setStringAsString ( string ) ; r1 . add ( re1 ) ; r2 . add ( re2 ) ; } @ CoGroup public void op3 ( @ Key ( group = "" ) List < Ex1 > a1 , @ Key ( group = "" ) List < Ex1 > a2 , @ Key ( group = "" ) List < Ex1 > a3 , Result < Ex1 > r1 , Result < Ex1 > r2 , Result < Ex1 > r3 ) { withParameter ( a1 , r2 , ) ; withParameter ( a2 , r3 , ) ; withParameter ( a3 , r1 , ) ; } @ CoGroup public void withParameter ( @ Key ( group = "" ) List < Ex1 > a1 , Result < Ex1 > r1 , int parameter ) { String string = "" ; int value = ; for ( Ex1 e : a1 ) { value += e . getValue ( ) + parameter ; string = e . getStringAsString ( ) ; } Ex1 re = new Ex1 ( ) ; re . setValue ( value ) ; re . setStringAsString ( string ) ; r1 . add ( re ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . List ; import com . asakusafw . compiler . flow . processor . MasterJoinFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . operator . MasterJoin ; import com . asakusafw . vocabulary . operator . MasterSelection ; import com . asakusafw . vocabulary . operator . Split ; public abstract class MasterJoinFlow { @ MasterJoin public abstract ExJoined join ( Ex1 ex1 , Ex2 ex2 ) ; @ MasterJoin ( selection = "" ) public abstract ExJoined selection ( Ex1 ex1 , Ex2 ex2 ) ; @ MasterSelection public Ex1 selector ( List < Ex1 > masters , Ex2 model ) { for ( Ex1 master : masters ) { if ( master . getStringOption ( ) . equals ( model . getStringOption ( ) ) ) { return master ; } } return null ; } @ Split public abstract void split ( ExJoined joined , Result < Ex1 > ex1 , Result < Ex2 > ex2 ) ; } package com . asakusafw . compiler . flow . processor . operator ; import com . asakusafw . compiler . flow . processor . ExtractFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . operator . Extract ; public abstract class ExtractFlow { @ Extract public void op1 ( Ex1 a1 , Result < Ex1 > r1 ) { withParameterEx1 ( a1 , r1 , ) ; } @ Extract public void op2 ( Ex1 a1 , Result < Ex1 > r1 , Result < Ex2 > r2 ) { withParameterEx1 ( a1 , r1 , ) ; withParameter ( a1 , r2 , ) ; } @ Extract public void op3 ( Ex1 a1 , Result < Ex1 > r1 , Result < Ex2 > r2 , Result < Ex1 > r3 ) { withParameterEx1 ( a1 , r1 , ) ; withParameter ( a1 , r2 , ) ; withParameterEx1 ( a1 , r3 , ) ; } @ Extract public void withParameter ( Ex1 a1 , Result < Ex2 > r1 , int parameter ) { Ex2 copy = new Ex2 ( ) ; copy . setSidOption ( a1 . getSidOption ( ) ) ; copy . setStringOption ( a1 . getStringOption ( ) ) ; copy . setValue ( a1 . getValue ( ) + parameter ) ; r1 . add ( copy ) ; } private void withParameterEx1 ( Ex1 a1 , Result < Ex1 > r1 , int parameter ) { Ex1 copy = new Ex1 ( ) ; copy . setSidOption ( a1 . getSidOption ( ) ) ; copy . setStringOption ( a1 . getStringOption ( ) ) ; copy . setValue ( a1 . getValue ( ) + parameter ) ; r1 . add ( copy ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . Arrays ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . compiler . flow . testing . model . ExJoined2 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorHelper ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterJoin ; @ Generated ( "" ) public class MasterJoinFlowFactory { public static final class Split implements Operator { public final Source < Ex1 > ex1 ; public final Source < Ex2 > ex2 ; Split ( Source < ExJoined > joined ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Split . class ) ; builder . declare ( MasterJoinFlow . class , MasterJoinFlowImpl . class , "" ) ; builder . declareParameter ( ExJoined . class ) ; builder . declareParameter ( Result . class ) ; builder . declareParameter ( Result . class ) ; builder . addInput ( "" , ExJoined . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex2 . class ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , joined ) ; this . ex1 = resolver . resolveOutput ( "" ) ; this . ex2 = resolver . resolveOutput ( "" ) ; } } public MasterJoinFlowFactory . Split split ( Source < ExJoined > joined ) { return new MasterJoinFlowFactory . Split ( joined ) ; } public static final class Join implements Operator { public final Source < ExJoined > joined ; public final Source < Ex2 > missed ; Join ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( MasterJoin . class ) ; builder0 . declare ( MasterJoinFlow . class , MasterJoinFlowImpl . class , "" ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( Ex2 . class ) ; builder0 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addOutput ( "" , ExJoined . class ) ; builder0 . addOutput ( "" , Ex2 . class ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver0 = builder0 . toResolver ( ) ; resolver0 . resolveInput ( "" , ex1 ) ; resolver0 . resolveInput ( "" , ex2 ) ; this . joined = resolver0 . resolveOutput ( "" ) ; this . missed = resolver0 . resolveOutput ( "" ) ; } } public MasterJoinFlowFactory . Join join ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { return new MasterJoinFlowFactory . Join ( ex1 , ex2 ) ; } public static final class RenameKey implements Operator { public final Source < ExJoined2 > joined ; public final Source < Ex2 > missed ; RenameKey ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( MasterJoin . class ) ; builder0 . declare ( MasterJoinFlow . class , MasterJoinFlowImpl . class , "" ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( Ex2 . class ) ; builder0 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addOutput ( "" , ExJoined2 . class ) ; builder0 . addOutput ( "" , Ex2 . class ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver0 = builder0 . toResolver ( ) ; resolver0 . resolveInput ( "" , ex1 ) ; resolver0 . resolveInput ( "" , ex2 ) ; this . joined = resolver0 . resolveOutput ( "" ) ; this . missed = resolver0 . resolveOutput ( "" ) ; } } public MasterJoinFlowFactory . RenameKey renameKey ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { return new MasterJoinFlowFactory . RenameKey ( ex1 , ex2 ) ; } public static final class Selection implements Operator { public final Source < ExJoined > joined ; public final Source < Ex2 > missed ; Selection ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( MasterJoin . class ) ; builder1 . declare ( MasterJoinFlow . class , MasterJoinFlowImpl . class , "" ) ; builder1 . declareParameter ( Ex1 . class ) ; builder1 . declareParameter ( Ex2 . class ) ; builder1 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder1 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder1 . addOutput ( "" , ExJoined . class ) ; builder1 . addOutput ( "" , Ex2 . class ) ; builder1 . addAttribute ( new OperatorHelper ( "" , Arrays . asList ( new Class < ? > [ ] { List . class , Ex2 . class } ) ) ) ; builder1 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver1 = builder1 . toResolver ( ) ; resolver1 . resolveInput ( "" , ex1 ) ; resolver1 . resolveInput ( "" , ex2 ) ; this . joined = resolver1 . resolveOutput ( "" ) ; this . missed = resolver1 . resolveOutput ( "" ) ; } } public MasterJoinFlowFactory . Selection selection ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { return new MasterJoinFlowFactory . Selection ( ex1 , ex2 ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . Arrays ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorHelper ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterCheck ; @ Generated ( "" ) public class MasterCheckFlowFactory { public static final class Simple implements Operator { public final Source < Ex1 > found ; public final Source < Ex1 > missed ; Simple ( Source < Ex2 > master , Source < Ex1 > model ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( MasterCheck . class ) ; builder . declare ( MasterCheckFlow . class , MasterCheckFlowImpl . class , "" ) ; builder . declareParameter ( Ex2 . class ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , master ) ; resolver . resolveInput ( "" , model ) ; this . found = resolver . resolveOutput ( "" ) ; this . missed = resolver . resolveOutput ( "" ) ; } } public MasterCheckFlowFactory . Simple simple ( Source < Ex2 > master , Source < Ex1 > model ) { return new MasterCheckFlowFactory . Simple ( master , model ) ; } public static final class Selection implements Operator { public final Source < Ex1 > found ; public final Source < Ex1 > missed ; Selection ( Source < Ex2 > master , Source < Ex1 > model ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( MasterCheck . class ) ; builder0 . declare ( MasterCheckFlow . class , MasterCheckFlowImpl . class , "" ) ; builder0 . declareParameter ( Ex2 . class ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addAttribute ( new OperatorHelper ( "" , Arrays . asList ( new Class < ? > [ ] { List . class , Ex1 . class } ) ) ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver0 = builder0 . toResolver ( ) ; resolver0 . resolveInput ( "" , master ) ; resolver0 . resolveInput ( "" , model ) ; this . found = resolver0 . resolveOutput ( "" ) ; this . missed = resolver0 . resolveOutput ( "" ) ; } } public MasterCheckFlowFactory . Selection selection ( Source < Ex2 > master , Source < Ex1 > model ) { return new MasterCheckFlowFactory . Selection ( master , model ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import com . asakusafw . compiler . flow . processor . LoggingFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . operator . Logging ; public abstract class LoggingFlow { @ Logging public String simple ( Ex1 model ) { return withParameter ( model , model . getStringAsString ( ) ) ; } @ Logging public String withParameter ( Ex1 model , String parameter ) { return parameter ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . compiler . flow . testing . model . ExSummarized2 ; import com . asakusafw . compiler . flow . testing . model . KeyConflict ; @ Generated ( "" ) public class SummarizeFlowImpl extends SummarizeFlow { public SummarizeFlowImpl ( ) { return ; } @ Override public ExSummarized simple ( Ex1 model ) { throw new UnsupportedOperationException ( "" ) ; } @ Override public ExSummarized2 renameKey ( Ex1 model ) { throw new UnsupportedOperationException ( "" ) ; } @ Override public KeyConflict keyConflict ( Ex1 model ) { throw new UnsupportedOperationException ( "" ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . Arrays ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorHelper ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterBranch ; @ Generated ( "" ) public class MasterBranchFlowFactory { public static final class Simple implements Operator { public final Source < Ex1 > high ; public final Source < Ex1 > low ; public final Source < Ex1 > stop ; Simple ( Source < Ex2 > master , Source < Ex1 > model ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( MasterBranch . class ) ; builder . declare ( MasterBranchFlow . class , MasterBranchFlowImpl . class , "" ) ; builder . declareParameter ( Ex2 . class ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , master ) ; resolver . resolveInput ( "" , model ) ; this . high = resolver . resolveOutput ( "" ) ; this . low = resolver . resolveOutput ( "" ) ; this . stop = resolver . resolveOutput ( "" ) ; } } public MasterBranchFlowFactory . Simple simple ( Source < Ex2 > master , Source < Ex1 > model ) { return new MasterBranchFlowFactory . Simple ( master , model ) ; } public static final class WithParameter implements Operator { public final Source < Ex1 > high ; public final Source < Ex1 > low ; public final Source < Ex1 > stop ; WithParameter ( Source < Ex2 > master , Source < Ex1 > model , int parameter ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( MasterBranch . class ) ; builder0 . declare ( MasterBranchFlow . class , MasterBranchFlowImpl . class , "" ) ; builder0 . declareParameter ( Ex2 . class ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( int . class ) ; builder0 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addParameter ( "" , int . class , parameter ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver0 = builder0 . toResolver ( ) ; resolver0 . resolveInput ( "" , master ) ; resolver0 . resolveInput ( "" , model ) ; this . high = resolver0 . resolveOutput ( "" ) ; this . low = resolver0 . resolveOutput ( "" ) ; this . stop = resolver0 . resolveOutput ( "" ) ; } } public MasterBranchFlowFactory . WithParameter withParameter ( Source < Ex2 > master , Source < Ex1 > model , int parameter ) { return new MasterBranchFlowFactory . WithParameter ( master , model , parameter ) ; } public static final class Selection implements Operator { public final Source < Ex1 > high ; public final Source < Ex1 > low ; public final Source < Ex1 > stop ; Selection ( Source < Ex2 > master , Source < Ex1 > model ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( MasterBranch . class ) ; builder1 . declare ( MasterBranchFlow . class , MasterBranchFlowImpl . class , "" ) ; builder1 . declareParameter ( Ex2 . class ) ; builder1 . declareParameter ( Ex1 . class ) ; builder1 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder1 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addAttribute ( new OperatorHelper ( "" , Arrays . asList ( new Class < ? > [ ] { List . class , Ex1 . class } ) ) ) ; builder1 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver1 = builder1 . toResolver ( ) ; resolver1 . resolveInput ( "" , master ) ; resolver1 . resolveInput ( "" , model ) ; this . high = resolver1 . resolveOutput ( "" ) ; this . low = resolver1 . resolveOutput ( "" ) ; this . stop = resolver1 . resolveOutput ( "" ) ; } } public MasterBranchFlowFactory . Selection selection ( Source < Ex2 > master , Source < Ex1 > model ) { return new MasterBranchFlowFactory . Selection ( master , model ) ; } public static final class SelectionWithParameter0 implements Operator { public final Source < Ex1 > high ; public final Source < Ex1 > low ; public final Source < Ex1 > stop ; SelectionWithParameter0 ( Source < Ex2 > master , Source < Ex1 > model , int parameter ) { OperatorDescription . Builder builder2 = new OperatorDescription . Builder ( MasterBranch . class ) ; builder2 . declare ( MasterBranchFlow . class , MasterBranchFlowImpl . class , "" ) ; builder2 . declareParameter ( Ex2 . class ) ; builder2 . declareParameter ( Ex1 . class ) ; builder2 . declareParameter ( int . class ) ; builder2 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder2 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder2 . addOutput ( "" , Ex1 . class ) ; builder2 . addOutput ( "" , Ex1 . class ) ; builder2 . addOutput ( "" , Ex1 . class ) ; builder2 . addParameter ( "" , int . class , parameter ) ; builder2 . addAttribute ( new OperatorHelper ( "" , Arrays . asList ( new Class < ? > [ ] { List . class , Ex1 . class } ) ) ) ; builder2 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver2 = builder2 . toResolver ( ) ; resolver2 . resolveInput ( "" , master ) ; resolver2 . resolveInput ( "" , model ) ; this . high = resolver2 . resolveOutput ( "" ) ; this . low = resolver2 . resolveOutput ( "" ) ; this . stop = resolver2 . resolveOutput ( "" ) ; } } public MasterBranchFlowFactory . SelectionWithParameter0 selectionWithParameter0 ( Source < Ex2 > master , Source < Ex1 > model , int parameter ) { return new MasterBranchFlowFactory . SelectionWithParameter0 ( master , model , parameter ) ; } public static final class SelectionWithParameter1 implements Operator { public final Source < Ex1 > high ; public final Source < Ex1 > low ; public final Source < Ex1 > stop ; SelectionWithParameter1 ( Source < Ex2 > master , Source < Ex1 > model , int parameter ) { OperatorDescription . Builder builder3 = new OperatorDescription . Builder ( MasterBranch . class ) ; builder3 . declare ( MasterBranchFlow . class , MasterBranchFlowImpl . class , "" ) ; builder3 . declareParameter ( Ex2 . class ) ; builder3 . declareParameter ( Ex1 . class ) ; builder3 . declareParameter ( int . class ) ; builder3 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder3 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder3 . addOutput ( "" , Ex1 . class ) ; builder3 . addOutput ( "" , Ex1 . class ) ; builder3 . addOutput ( "" , Ex1 . class ) ; builder3 . addParameter ( "" , int . class , parameter ) ; builder3 . addAttribute ( new OperatorHelper ( "" , Arrays . asList ( new Class < ? > [ ] { List . class , Ex1 . class , int . class } ) ) ) ; builder3 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver3 = builder3 . toResolver ( ) ; resolver3 . resolveInput ( "" , master ) ; resolver3 . resolveInput ( "" , model ) ; this . high = resolver3 . resolveOutput ( "" ) ; this . low = resolver3 . resolveOutput ( "" ) ; this . stop = resolver3 . resolveOutput ( "" ) ; } } public MasterBranchFlowFactory . SelectionWithParameter1 selectionWithParameter1 ( Source < Ex2 > master , Source < Ex1 > model , int parameter ) { return new MasterBranchFlowFactory . SelectionWithParameter1 ( master , model , parameter ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . runtime . core . Result ; @ Generated ( "" ) public class MasterJoinFlowImpl extends MasterJoinFlow { public MasterJoinFlowImpl ( ) { return ; } @ Override public void split ( ExJoined joined , Result < Ex1 > ex1 , Result < Ex2 > ex2 ) { throw new UnsupportedOperationException ( ) ; } @ Override public ExJoined join ( Ex1 ex1 , Ex2 ex2 ) { throw new UnsupportedOperationException ( ) ; } @ Override public ExJoined selection ( Ex1 ex1 , Ex2 ex2 ) { throw new UnsupportedOperationException ( ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . Arrays ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorHelper ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . operator . MasterJoinUpdate ; @ Generated ( "" ) public class MasterJoinUpdateFlowFactory { public static final class Simple implements Operator { public final Source < Ex1 > updated ; public final Source < Ex1 > missed ; Simple ( Source < Ex2 > master , Source < Ex1 > model ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( MasterJoinUpdate . class ) ; builder . declare ( MasterJoinUpdateFlow . class , MasterJoinUpdateFlowImpl . class , "" ) ; builder . declareParameter ( Ex2 . class ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , master ) ; resolver . resolveInput ( "" , model ) ; this . updated = resolver . resolveOutput ( "" ) ; this . missed = resolver . resolveOutput ( "" ) ; } } public MasterJoinUpdateFlowFactory . Simple simple ( Source < Ex2 > master , Source < Ex1 > model ) { return new MasterJoinUpdateFlowFactory . Simple ( master , model ) ; } public static final class WithParameter implements Operator { public final Source < Ex1 > updated ; public final Source < Ex1 > missed ; WithParameter ( Source < Ex2 > master , Source < Ex1 > model , int parameter ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( MasterJoinUpdate . class ) ; builder0 . declare ( MasterJoinUpdateFlow . class , MasterJoinUpdateFlowImpl . class , "" ) ; builder0 . declareParameter ( Ex2 . class ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( int . class ) ; builder0 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addParameter ( "" , int . class , parameter ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver0 = builder0 . toResolver ( ) ; resolver0 . resolveInput ( "" , master ) ; resolver0 . resolveInput ( "" , model ) ; this . updated = resolver0 . resolveOutput ( "" ) ; this . missed = resolver0 . resolveOutput ( "" ) ; } } public MasterJoinUpdateFlowFactory . WithParameter withParameter ( Source < Ex2 > master , Source < Ex1 > model , int parameter ) { return new MasterJoinUpdateFlowFactory . WithParameter ( master , model , parameter ) ; } public static final class Selection implements Operator { public final Source < Ex1 > updated ; public final Source < Ex1 > missed ; Selection ( Source < Ex2 > master , Source < Ex1 > model ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( MasterJoinUpdate . class ) ; builder1 . declare ( MasterJoinUpdateFlow . class , MasterJoinUpdateFlowImpl . class , "" ) ; builder1 . declareParameter ( Ex2 . class ) ; builder1 . declareParameter ( Ex1 . class ) ; builder1 . addInput ( "" , Ex2 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder1 . addInput ( "" , Ex1 . class , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addAttribute ( new OperatorHelper ( "" , Arrays . asList ( new Class < ? > [ ] { List . class , Ex1 . class } ) ) ) ; builder1 . addAttribute ( FlowBoundary . SHUFFLE ) ; FlowElementResolver resolver1 = builder1 . toResolver ( ) ; resolver1 . resolveInput ( "" , master ) ; resolver1 . resolveInput ( "" , model ) ; this . updated = resolver1 . resolveOutput ( "" ) ; this . missed = resolver1 . resolveOutput ( "" ) ; } } public MasterJoinUpdateFlowFactory . Selection selection ( Source < Ex2 > master , Source < Ex1 > model ) { return new MasterJoinUpdateFlowFactory . Selection ( master , model ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import com . asakusafw . compiler . flow . processor . SummarizeFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . compiler . flow . testing . model . ExSummarized2 ; import com . asakusafw . compiler . flow . testing . model . KeyConflict ; import com . asakusafw . vocabulary . operator . Summarize ; public abstract class SummarizeFlow { @ Summarize public abstract ExSummarized simple ( Ex1 model ) ; @ Summarize public abstract ExSummarized2 renameKey ( Ex1 model ) ; @ Summarize public abstract KeyConflict keyConflict ( Ex1 model ) ; } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class FoldFlowImpl extends FoldFlow { public FoldFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class BranchFlowImpl extends BranchFlow { } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class ExtractFlowImpl extends ExtractFlow { public ExtractFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; @ Generated ( "" ) public class CoGroupFlowImpl extends CoGroupFlow { public CoGroupFlowImpl ( ) { return ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . Arrays ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . flow . processor . PartialAggregation ; import com . asakusafw . vocabulary . operator . Fold ; @ Generated ( "" ) public class FoldFlowFactory { public static final class Simple implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Simple ( Source < Ex1 > in ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Fold . class ) ; builder . declare ( FoldFlow . class , FoldFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , in , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addOutput ( "" , in ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( ObservationCount . DONT_CARE ) ; builder . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder . toResolver ( ) ; this . $ . resolveInput ( "" , in ) ; this . out = this . $ . resolveOutput ( "" ) ; } public FoldFlowFactory . Simple as ( String newName ) { this . $ . setName ( newName ) ; return this ; } } public FoldFlowFactory . Simple simple ( Source < Ex1 > in ) { return new FoldFlowFactory . Simple ( in ) ; } public static final class WithParameter implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; WithParameter ( Source < Ex1 > in , int parameter ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( Fold . class ) ; builder0 . declare ( FoldFlow . class , FoldFlowImpl . class , "" ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( int . class ) ; builder0 . addInput ( "" , in , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder0 . addOutput ( "" , in ) ; builder0 . addParameter ( "" , int . class , parameter ) ; builder0 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder0 . addAttribute ( ObservationCount . DONT_CARE ) ; builder0 . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder0 . toResolver ( ) ; this . $ . resolveInput ( "" , in ) ; this . out = this . $ . resolveOutput ( "" ) ; } public FoldFlowFactory . WithParameter as ( String newName0 ) { this . $ . setName ( newName0 ) ; return this ; } } public FoldFlowFactory . WithParameter withParameter ( Source < Ex1 > in , int parameter ) { return new FoldFlowFactory . WithParameter ( in , parameter ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Extract ; @ Generated ( "" ) public class ExtractFlowFactory { public static final class Op1 implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; Op1 ( Source < Ex1 > a1 ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Extract . class ) ; builder . declare ( ExtractFlow . class , ExtractFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . declareParameter ( Result . class ) ; builder . addInput ( "" , a1 ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addAttribute ( ObservationCount . DONT_CARE ) ; this . $ = builder . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; } public ExtractFlowFactory . Op1 as ( String newName ) { this . $ . setName ( newName ) ; return this ; } } public ExtractFlowFactory . Op1 op1 ( Source < Ex1 > a1 ) { return new ExtractFlowFactory . Op1 ( a1 ) ; } public static final class Op2 implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; public final Source < Ex2 > r2 ; Op2 ( Source < Ex1 > a1 ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( Extract . class ) ; builder0 . declare ( ExtractFlow . class , ExtractFlowImpl . class , "" ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( Result . class ) ; builder0 . declareParameter ( Result . class ) ; builder0 . addInput ( "" , a1 ) ; builder0 . addOutput ( "" , Ex1 . class ) ; builder0 . addOutput ( "" , Ex2 . class ) ; builder0 . addAttribute ( ObservationCount . DONT_CARE ) ; this . $ = builder0 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; this . r2 = this . $ . resolveOutput ( "" ) ; } public ExtractFlowFactory . Op2 as ( String newName0 ) { this . $ . setName ( newName0 ) ; return this ; } } public ExtractFlowFactory . Op2 op2 ( Source < Ex1 > a1 ) { return new ExtractFlowFactory . Op2 ( a1 ) ; } public static final class Op3 implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; public final Source < Ex2 > r2 ; public final Source < Ex1 > r3 ; Op3 ( Source < Ex1 > a1 ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( Extract . class ) ; builder1 . declare ( ExtractFlow . class , ExtractFlowImpl . class , "" ) ; builder1 . declareParameter ( Ex1 . class ) ; builder1 . declareParameter ( Result . class ) ; builder1 . declareParameter ( Result . class ) ; builder1 . declareParameter ( Result . class ) ; builder1 . addInput ( "" , a1 ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addOutput ( "" , Ex2 . class ) ; builder1 . addOutput ( "" , Ex1 . class ) ; builder1 . addAttribute ( ObservationCount . DONT_CARE ) ; this . $ = builder1 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; this . r2 = this . $ . resolveOutput ( "" ) ; this . r3 = this . $ . resolveOutput ( "" ) ; } public ExtractFlowFactory . Op3 as ( String newName1 ) { this . $ . setName ( newName1 ) ; return this ; } } public ExtractFlowFactory . Op3 op3 ( Source < Ex1 > a1 ) { return new ExtractFlowFactory . Op3 ( a1 ) ; } public static final class WithParameter implements Operator { private final FlowElementResolver $ ; public final Source < Ex2 > r1 ; WithParameter ( Source < Ex1 > a1 , int parameter ) { OperatorDescription . Builder builder2 = new OperatorDescription . Builder ( Extract . class ) ; builder2 . declare ( ExtractFlow . class , ExtractFlowImpl . class , "" ) ; builder2 . declareParameter ( Ex1 . class ) ; builder2 . declareParameter ( Result . class ) ; builder2 . declareParameter ( int . class ) ; builder2 . addInput ( "" , a1 ) ; builder2 . addOutput ( "" , Ex2 . class ) ; builder2 . addParameter ( "" , int . class , parameter ) ; builder2 . addAttribute ( ObservationCount . DONT_CARE ) ; this . $ = builder2 . toResolver ( ) ; this . $ . resolveInput ( "" , a1 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; } public ExtractFlowFactory . WithParameter as ( String newName2 ) { this . $ . setName ( newName2 ) ; return this ; } } public ExtractFlowFactory . WithParameter withParameter ( Source < Ex1 > a1 , int parameter ) { return new ExtractFlowFactory . WithParameter ( a1 , parameter ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . operator . Update ; @ Generated ( "" ) public class UpdateFlowFactory { public static final class Simple implements Operator { public final Source < Ex1 > out ; Simple ( Source < Ex1 > model ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Update . class ) ; builder . declare ( UpdateFlow . class , UpdateFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , model ) ; this . out = resolver . resolveOutput ( "" ) ; } } public UpdateFlowFactory . Simple simple ( Source < Ex1 > model ) { return new UpdateFlowFactory . Simple ( model ) ; } public static final class WithParameter implements Operator { public final Source < Ex1 > out ; WithParameter ( Source < Ex1 > model , int parameter ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Update . class ) ; builder . declare ( UpdateFlow . class , UpdateFlowImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . declareParameter ( int . class ) ; builder . addInput ( "" , Ex1 . class ) ; builder . addOutput ( "" , Ex1 . class ) ; builder . addParameter ( "" , int . class , parameter ) ; FlowElementResolver resolver = builder . toResolver ( ) ; resolver . resolveInput ( "" , model ) ; this . out = resolver . resolveOutput ( "" ) ; } } public UpdateFlowFactory . WithParameter withParameter ( Source < Ex1 > model , int parameter ) { return new UpdateFlowFactory . WithParameter ( model , parameter ) ; } } package com . asakusafw . compiler . flow . processor . operator ; import java . util . List ; import com . asakusafw . compiler . flow . processor . MasterCheckFlowProcessor ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . MasterCheck ; import com . asakusafw . vocabulary . operator . MasterSelection ; public abstract class MasterCheckFlow { @ MasterCheck public abstract boolean simple ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model ) ; @ MasterCheck ( selection = "" ) public abstract boolean selection ( @ Key ( group = "" ) Ex2 master , @ Key ( group = "" ) Ex1 model ) ; @ MasterSelection public Ex2 selector ( List < Ex2 > masters , Ex1 model ) { for ( Ex2 master : masters ) { if ( master . getValueOption ( ) . equals ( model . getValueOption ( ) ) ) { return master ; } } return null ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . processor . flow . ProjectFlowInvalid ; import com . asakusafw . compiler . flow . processor . flow . ProjectFlowSame ; import com . asakusafw . compiler . flow . processor . flow . ProjectFlowSimple ; import com . asakusafw . compiler . flow . stage . StageCompiler ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class ProjectFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void Ex1_Part ( ) { List < StageModel > stages = compile ( ProjectFlowSimple . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Part1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 in = new Ex1 ( ) ; in . setSid ( ) ; in . setValue ( ) ; in . setStringAsString ( "" ) ; f . add ( in ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; Part1 out = result . getResults ( ) . get ( ) ; assertThat ( out . getSid ( ) , is ( ) ) ; assertThat ( out . getValue ( ) , is ( ) ) ; } @ Test public void Ex1_Ex2 ( ) { List < StageModel > stages = compile ( ProjectFlowSame . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex2 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 in = new Ex1 ( ) ; in . setSid ( ) ; in . setValue ( ) ; in . setStringAsString ( "" ) ; f . add ( in ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; Ex2 out = result . getResults ( ) . get ( ) ; assertThat ( out . getSid ( ) , is ( ) ) ; assertThat ( out . getValue ( ) , is ( ) ) ; assertThat ( out . getStringAsString ( ) , is ( "" ) ) ; } @ Test public void Part_Ex1 ( ) { StageGraph graph = jfToStageGraph ( ProjectFlowInvalid . class ) ; try { new StageCompiler ( environment ) . compile ( graph ) ; assertThat ( environment . hasError ( ) , is ( true ) ) ; } catch ( IOException e ) { } } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . plan . StageGraph ; import com . asakusafw . compiler . flow . processor . flow . ExtendFlowInvalid ; import com . asakusafw . compiler . flow . processor . flow . ExtendFlowSame ; import com . asakusafw . compiler . flow . processor . flow . ExtendFlowSimple ; import com . asakusafw . compiler . flow . stage . StageCompiler ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class ExtendFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void Part_Ex1 ( ) { List < StageModel > stages = compile ( ExtendFlowSimple . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Part1 > f = ( Result < Part1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Part1 in = new Part1 ( ) ; in . setSid ( ) ; in . setValue ( ) ; f . add ( in ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; Ex1 out = result . getResults ( ) . get ( ) ; assertThat ( out . getSid ( ) , is ( ) ) ; assertThat ( out . getValue ( ) , is ( ) ) ; assertThat ( out . getStringOption ( ) . isNull ( ) , is ( true ) ) ; } @ Test public void Ex1_Ex2 ( ) { List < StageModel > stages = compile ( ExtendFlowSame . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex2 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 in = new Ex1 ( ) ; in . setSid ( ) ; in . setValue ( ) ; in . setStringAsString ( "" ) ; f . add ( in ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; Ex2 out = result . getResults ( ) . get ( ) ; assertThat ( out . getSid ( ) , is ( ) ) ; assertThat ( out . getValue ( ) , is ( ) ) ; assertThat ( out . getStringAsString ( ) , is ( "" ) ) ; } @ Test public void Ex1_Part ( ) { StageGraph graph = jfToStageGraph ( ExtendFlowInvalid . class ) ; try { new StageCompiler ( environment ) . compile ( graph ) ; assertThat ( environment . hasError ( ) , is ( true ) ) ; } catch ( IOException e ) { } } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . processor . flow . MasterCheckFlowSelection ; import com . asakusafw . compiler . flow . processor . flow . MasterCheckFlowTrivial ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; public class MasterCheckFlowProcessorTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void trivial ( ) throws Exception { runEq ( DataSize . UNKNOWN ) ; } @ Test public void tiny ( ) throws Exception { runEq ( DataSize . TINY ) ; } private void runEq ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > found = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > missing = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setStringAsString ( "" ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; assertThat ( tester . runFlow ( new MasterCheckFlowTrivial ( in1 . flow ( ) , in2 . flow ( ) , found . flow ( ) , missing . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > foundList = found . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; List < Ex1 > missingList = missing . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( foundList . size ( ) , is ( ) ) ; assertThat ( missingList . size ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; } @ Test public void selection ( ) throws Exception { runNoEq ( DataSize . UNKNOWN ) ; } @ Test public void tinySelection ( ) throws Exception { runNoEq ( DataSize . TINY ) ; } private void runNoEq ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > found = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > missing = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; assertThat ( tester . runFlow ( new MasterCheckFlowSelection ( in1 . flow ( ) , in2 . flow ( ) , found . flow ( ) , missing . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > foundList = found . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; List < Ex1 > missingList = missing . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( foundList . size ( ) , is ( ) ) ; assertThat ( missingList . size ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . processor . flow . MasterJoinUpdateFlowSelection ; import com . asakusafw . compiler . flow . processor . flow . MasterJoinUpdateFlowSimple ; import com . asakusafw . compiler . flow . processor . flow . MasterJoinUpdateFlowWithParameter ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; public class MasterJoinUpdateFlowProcessorTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void simple ( ) throws Exception { runEq ( DataSize . UNKNOWN ) ; } @ Test public void tiny ( ) throws Exception { runEq ( DataSize . TINY ) ; } private void runEq ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > found = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > missing = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; assertThat ( tester . runFlow ( new MasterJoinUpdateFlowSimple ( in1 . flow ( ) , in2 . flow ( ) , found . flow ( ) , missing . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > foundList = found . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; List < Ex1 > missingList = missing . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( foundList . size ( ) , is ( ) ) ; assertThat ( missingList . size ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void withParameter ( ) throws Exception { runParam ( DataSize . UNKNOWN ) ; } @ Test public void tinyWithParameter ( ) throws Exception { runParam ( DataSize . TINY ) ; } private void runParam ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > found = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > missing = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; assertThat ( tester . runFlow ( new MasterJoinUpdateFlowWithParameter ( in1 . flow ( ) , in2 . flow ( ) , found . flow ( ) , missing . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > foundList = found . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; List < Ex1 > missingList = missing . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( foundList . size ( ) , is ( ) ) ; assertThat ( missingList . size ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void selection ( ) throws Exception { runNoEq ( DataSize . UNKNOWN ) ; } @ Test public void tinySelection ( ) throws Exception { runNoEq ( DataSize . TINY ) ; } private void runNoEq ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > found = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > missing = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setSid ( ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; ex1 . setValue ( ) ; ex1 . setSid ( ) ; in1 . add ( ex1 ) ; assertThat ( tester . runFlow ( new MasterJoinUpdateFlowSelection ( in1 . flow ( ) , in2 . flow ( ) , found . flow ( ) , missing . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > foundList = found . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; List < Ex1 > missingList = missing . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( foundList . size ( ) , is ( ) ) ; assertThat ( missingList . size ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( foundList . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( missingList . get ( ) . getSid ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . processor . flow . MasterBranchFlowSelection ; import com . asakusafw . compiler . flow . processor . flow . MasterBranchFlowSelectionWithParameter0 ; import com . asakusafw . compiler . flow . processor . flow . MasterBranchFlowSelectionWithParameter1 ; import com . asakusafw . compiler . flow . processor . flow . MasterBranchFlowSimple ; import com . asakusafw . compiler . flow . processor . flow . MasterBranchFlowWithParameter ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; public class MasterBranchFlowProcessorTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void simple ( ) throws Exception { runEq ( DataSize . UNKNOWN ) ; } @ Test public void tiny ( ) throws Exception { runEq ( DataSize . TINY ) ; } private void runEq ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > high = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > low = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > stop = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( ) ; in1 . add ( ex1 ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in1 . add ( ex1 ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in1 . add ( ex1 ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in1 . add ( ex1 ) ; in2 . add ( ex2 ) ; assertThat ( tester . runFlow ( new MasterBranchFlowSimple ( in1 . flow ( ) , in2 . flow ( ) , high . flow ( ) , low . flow ( ) , stop . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > highList = high . toList ( ) ; List < Ex1 > lowList = low . toList ( ) ; List < Ex1 > stopList = stop . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( highList . size ( ) , is ( ) ) ; assertThat ( lowList . size ( ) , is ( ) ) ; assertThat ( stopList . size ( ) , is ( ) ) ; assertThat ( highList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( lowList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; } @ Test public void withParameter ( ) throws Exception { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" ) ; TestOutput < Ex1 > high = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > low = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > stop = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( ) ; in1 . add ( ex1 ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in1 . add ( ex1 ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in1 . add ( ex1 ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; assertThat ( tester . runFlow ( new MasterBranchFlowWithParameter ( in1 . flow ( ) , in2 . flow ( ) , high . flow ( ) , low . flow ( ) , stop . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > highList = high . toList ( ) ; List < Ex1 > lowList = low . toList ( ) ; List < Ex1 > stopList = stop . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( highList . size ( ) , is ( ) ) ; assertThat ( lowList . size ( ) , is ( ) ) ; assertThat ( stopList . size ( ) , is ( ) ) ; assertThat ( highList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( lowList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; } @ Test public void selection ( ) throws Exception { runNoEq ( DataSize . UNKNOWN ) ; } @ Test public void tinySelection ( ) throws Exception { runNoEq ( DataSize . TINY ) ; } private void runNoEq ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > high = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > low = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > stop = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( + ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( + ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; assertThat ( tester . runFlow ( new MasterBranchFlowSelection ( in1 . flow ( ) , in2 . flow ( ) , high . flow ( ) , low . flow ( ) , stop . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > highList = high . toList ( ) ; List < Ex1 > lowList = low . toList ( ) ; List < Ex1 > stopList = stop . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( highList . size ( ) , is ( ) ) ; assertThat ( lowList . size ( ) , is ( ) ) ; assertThat ( stopList . size ( ) , is ( ) ) ; assertThat ( highList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( lowList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; } @ Test public void selectionWithParameter0 ( ) throws Exception { runNoEqWithParameter0 ( DataSize . UNKNOWN ) ; } @ Test public void tinySelectionWithParameter0 ( ) throws Exception { runNoEqWithParameter0 ( DataSize . TINY ) ; } private void runNoEqWithParameter0 ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > high = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > low = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > stop = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( + ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( + ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; assertThat ( tester . runFlow ( new MasterBranchFlowSelectionWithParameter0 ( in1 . flow ( ) , in2 . flow ( ) , high . flow ( ) , low . flow ( ) , stop . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > highList = high . toList ( ) ; List < Ex1 > lowList = low . toList ( ) ; List < Ex1 > stopList = stop . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( highList . size ( ) , is ( ) ) ; assertThat ( lowList . size ( ) , is ( ) ) ; assertThat ( stopList . size ( ) , is ( ) ) ; assertThat ( highList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( lowList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; } @ Test public void selectionWithParameter1 ( ) throws Exception { runNoEqWithParameter1 ( DataSize . UNKNOWN ) ; } @ Test public void tinySelectionWithParameter1 ( ) throws Exception { runNoEqWithParameter1 ( DataSize . TINY ) ; } private void runNoEqWithParameter1 ( DataSize dataSize ) throws IOException { TestInput < Ex1 > in1 = tester . input ( Ex1 . class , "" ) ; TestInput < Ex2 > in2 = tester . input ( Ex2 . class , "" , dataSize ) ; TestOutput < Ex1 > high = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > low = tester . output ( Ex1 . class , "" ) ; TestOutput < Ex1 > stop = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; Ex2 ex2 = new Ex2 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( - ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( + ) ; in2 . add ( ex2 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in1 . add ( ex1 ) ; ex2 . setStringAsString ( "" ) ; ex2 . setValue ( - ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; ex2 . setValue ( ) ; in2 . add ( ex2 ) ; assertThat ( tester . runFlow ( new MasterBranchFlowSelectionWithParameter1 ( in1 . flow ( ) , in2 . flow ( ) , high . flow ( ) , low . flow ( ) , stop . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > highList = high . toList ( ) ; List < Ex1 > lowList = low . toList ( ) ; List < Ex1 > stopList = stop . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( highList . size ( ) , is ( ) ) ; assertThat ( lowList . size ( ) , is ( ) ) ; assertThat ( stopList . size ( ) , is ( ) ) ; assertThat ( highList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( lowList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; assertThat ( stopList . get ( ) . getStringAsString ( ) , is ( "" ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . FoldFlowSimple ; import com . asakusafw . compiler . flow . processor . flow . FoldFlowWithParameter ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . util . tester . CompilerTester . TestInput ; import com . asakusafw . compiler . util . tester . CompilerTester . TestOutput ; public class FoldFlowProcessorTest extends JobflowCompilerTestRoot { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void simple ( ) throws Exception { tester . options ( ) . setEnableCombiner ( false ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; assertThat ( tester . runFlow ( new FoldFlowSimple ( in . flow ( ) , out . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > results = out . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void withParameter ( ) throws Exception { TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; assertThat ( tester . runFlow ( new FoldFlowWithParameter ( in . flow ( ) , out . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > results = out . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void combine ( ) throws Exception { tester . options ( ) . setEnableCombiner ( true ) ; TestInput < Ex1 > in = tester . input ( Ex1 . class , "" ) ; TestOutput < Ex1 > out = tester . output ( Ex1 . class , "" ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; ex1 . setValue ( ) ; in . add ( ex1 ) ; assertThat ( tester . runFlow ( new FoldFlowSimple ( in . flow ( ) , out . flow ( ) ) ) , is ( true ) ) ; List < Ex1 > results = out . toList ( new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getStringOption ( ) . compareTo ( o2 . getStringOption ( ) ) ; } } ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getStringOption ( ) . has ( "" ) , is ( true ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . RestructureFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Part1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; @ JobFlow ( name = "" ) public class RestructureFlowExtend extends FlowDescription { private final In < Part1 > in ; private final Out < Ex1 > out ; public RestructureFlowExtend ( @ Import ( name = "" , description = Part1MockImporterDescription . class ) In < Part1 > in , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Restructure < Ex1 > project = core . restructure ( in , Ex1 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . FoldFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . FoldFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . FoldFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class FoldFlowSimple extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public FoldFlowSimple ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { FoldFlowFactory f = new FoldFlowFactory ( ) ; Simple op = f . simple ( in1 ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ProjectFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Part1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Project ; @ JobFlow ( name = "" ) public class ProjectFlowSimple extends FlowDescription { private final In < Ex1 > in ; private final Out < Part1 > out ; public ProjectFlowSimple ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Part1MockExporterDescription . class ) Out < Part1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Project < Part1 > project = core . project ( in , Part1 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . RestructureFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; @ JobFlow ( name = "" ) public class RestructureFlowSame extends FlowDescription { private final In < Ex1 > in ; private final Out < Ex2 > out ; public RestructureFlowSame ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Restructure < Ex2 > project = core . restructure ( in , Ex2 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ConvertFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . ConvertFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . ConvertFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class ConvertFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; private Out < Ex2 > out2 ; public ConvertFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { ConvertFlowFactory f = new ConvertFlowFactory ( ) ; WithParameter op = f . withParameter ( in1 , ) ; out1 . add ( op . original ) ; out2 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . operator . GroupSortFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . GroupSortFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . operator . GroupSort ; @ JobFlow ( name = "" ) public class GroupSortFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; public GroupSortFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out2 ) { this . in1 = in1 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { GroupSortFlowFactory f = new GroupSortFlowFactory ( ) ; WithParameter op = f . withParameter ( in1 , ) ; out1 . add ( op . r1 ) ; out2 . add ( op . r2 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . SummarizeFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . SummarizeFlowFactory ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . KeyConflictMockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . KeyConflict ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SummarizeFlowKeyConflict extends FlowDescription { private final In < Ex1 > in1 ; private final Out < KeyConflict > out1 ; public SummarizeFlowKeyConflict ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = KeyConflictMockExporterDescription . class ) Out < KeyConflict > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { SummarizeFlowFactory f = new SummarizeFlowFactory ( ) ; SummarizeFlowFactory . KeyConflict op = f . keyConflict ( in1 ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ExtractFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . ExtractFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . ExtractFlowFactory . Op2 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class ExtractFlowOp2 extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; private Out < Ex2 > out2 ; public ExtractFlowOp2 ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { ExtractFlowFactory f = new ExtractFlowFactory ( ) ; Op2 op = f . op2 ( in1 ) ; out1 . add ( op . r1 ) ; out2 . add ( op . r2 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . UpdateFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class UpdateFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public UpdateFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { UpdateFlowFactory f = new UpdateFlowFactory ( ) ; WithParameter op = f . withParameter ( in1 , ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . SummarizeFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . SummarizeFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . SummarizeFlowFactory . RenameKey ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . ExSummarized2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SummarizeFlowRenameKey extends FlowDescription { private In < Ex1 > in1 ; private Out < ExSummarized2 > out1 ; public SummarizeFlowRenameKey ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = ExSummarized2MockExporterDescription . class ) Out < ExSummarized2 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { SummarizeFlowFactory f = new SummarizeFlowFactory ( ) ; RenameKey op = f . renameKey ( in1 ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . LoggingFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . LoggingFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . LoggingFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class LoggingFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public LoggingFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { LoggingFlowFactory f = new LoggingFlowFactory ( ) ; WithParameter op = f . withParameter ( in1 , "" ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . CoGroupFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory . Op3 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class CoGroupFlowOp3 extends FlowDescription { private In < Ex1 > in1 ; private In < Ex1 > in2 ; private In < Ex1 > in3 ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; private Out < Ex1 > out3 ; public CoGroupFlowOp3 ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in2 , @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in3 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out3 ) { this . in1 = in1 ; this . in2 = in2 ; this . in3 = in3 ; this . out1 = out1 ; this . out2 = out2 ; this . out3 = out3 ; } @ Override protected void describe ( ) { CoGroupFlowFactory f = new CoGroupFlowFactory ( ) ; Op3 op = f . op3 ( in1 , in2 , in3 ) ; out1 . add ( op . r1 ) ; out2 . add ( op . r2 ) ; out3 . add ( op . r3 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . SplitFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory . Split ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . ExJoinedMockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SplitFlowTrivial extends FlowDescription { private In < ExJoined > in1 ; private Out < Ex1 > out1 ; private Out < Ex2 > out2 ; public SplitFlowTrivial ( @ Import ( name = "" , description = ExJoinedMockImporterDescription . class ) In < ExJoined > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterJoinFlowFactory f = new MasterJoinFlowFactory ( ) ; Split op = f . split ( in1 ) ; out1 . add ( op . ex1 ) ; out2 . add ( op . ex2 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ExtractFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . ExtractFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . ExtractFlowFactory . Op3 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class ExtractFlowOp3 extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; private Out < Ex2 > out2 ; private Out < Ex1 > out3 ; public ExtractFlowOp3 ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out3 ) { this . in1 = in1 ; this . out1 = out1 ; this . out2 = out2 ; this . out3 = out3 ; } @ Override protected void describe ( ) { ExtractFlowFactory f = new ExtractFlowFactory ( ) ; Op3 op = f . op3 ( in1 ) ; out1 . add ( op . r1 ) ; out2 . add ( op . r2 ) ; out3 . add ( op . r3 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterJoinUpdateFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinUpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinUpdateFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterJoinUpdateFlowSimple extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; public MasterJoinUpdateFlowSimple ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterJoinUpdateFlowFactory f = new MasterJoinUpdateFlowFactory ( ) ; Simple op = f . simple ( in2 , in1 ) ; out1 . add ( op . updated ) ; out2 . add ( op . missed ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterBranchFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory . Selection ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterBranchFlowSelection extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > outHigh ; private Out < Ex1 > outLow ; private Out < Ex1 > outStop ; public MasterBranchFlowSelection ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outHigh , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outLow , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outStop ) { this . in1 = in1 ; this . in2 = in2 ; this . outHigh = outHigh ; this . outLow = outLow ; this . outStop = outStop ; } @ Override protected void describe ( ) { MasterBranchFlowFactory f = new MasterBranchFlowFactory ( ) ; Selection op = f . selection ( in2 , in1 ) ; outHigh . add ( op . high ) ; outLow . add ( op . low ) ; outStop . add ( op . stop ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . operator . GroupSortFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . GroupSortFlowFactory . Min ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . operator . GroupSort ; @ JobFlow ( name = "" ) public class GroupSortFlowMin extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public GroupSortFlowMin ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { GroupSortFlowFactory f = new GroupSortFlowFactory ( ) ; Min op = f . min ( in1 ) ; out1 . add ( op . r1 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . BranchFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . BranchFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . BranchFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class BranchFlowSimple extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > outHigh ; private Out < Ex1 > outLow ; private Out < Ex1 > outStop ; public BranchFlowSimple ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outHigh , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outLow , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outStop ) { this . in1 = in1 ; this . outHigh = outHigh ; this . outLow = outLow ; this . outStop = outStop ; } @ Override protected void describe ( ) { BranchFlowFactory f = new BranchFlowFactory ( ) ; Simple op = f . simple ( in1 ) ; outHigh . add ( op . high ) ; outLow . add ( op . low ) ; outStop . add ( op . stop ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . CoGroupFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory . Op1 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class CoGroupFlowOp1 extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public CoGroupFlowOp1 ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { CoGroupFlowFactory f = new CoGroupFlowFactory ( ) ; Op1 op = f . op1 ( in1 ) ; out1 . add ( op . r1 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ExtendFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Part1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Extend ; @ JobFlow ( name = "" ) public class ExtendFlowInvalid extends FlowDescription { private final In < Ex1 > in ; private final Out < Part1 > out ; public ExtendFlowInvalid ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Part1MockExporterDescription . class ) Out < Part1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Extend < Part1 > project = core . extend ( in , Part1 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterJoinFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory . Join ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . ExJoinedMockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterJoinFlowTrivial extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < ExJoined > out1 ; private Out < Ex2 > out2 ; public MasterJoinFlowTrivial ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = ExJoinedMockExporterDescription . class ) Out < ExJoined > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterJoinFlowFactory f = new MasterJoinFlowFactory ( ) ; Join join = f . join ( in1 , in2 ) ; out1 . add ( join . joined ) ; out2 . add ( join . missed ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ConvertFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . ConvertFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . ConvertFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class ConvertFlowSimple extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; private Out < Ex2 > out2 ; public ConvertFlowSimple ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { ConvertFlowFactory f = new ConvertFlowFactory ( ) ; Simple op = f . simple ( in1 ) ; out1 . add ( op . original ) ; out2 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . CoGroupFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class CoGroupFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public CoGroupFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { CoGroupFlowFactory f = new CoGroupFlowFactory ( ) ; WithParameter op = f . withParameter ( in1 , ) ; out1 . add ( op . r1 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterJoinFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory . Selection ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . ExJoinedMockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterJoinFlowSelection extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < ExJoined > out1 ; private Out < Ex2 > out2 ; public MasterJoinFlowSelection ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = ExJoinedMockExporterDescription . class ) Out < ExJoined > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterJoinFlowFactory f = new MasterJoinFlowFactory ( ) ; Selection op = f . selection ( in1 , in2 ) ; out1 . add ( op . joined ) ; out2 . add ( op . missed ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterCheckFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterCheckFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterCheckFlowFactory . Selection ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterCheckFlowSelection extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; public MasterCheckFlowSelection ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterCheckFlowFactory f = new MasterCheckFlowFactory ( ) ; Selection op = f . selection ( in2 , in1 ) ; out1 . add ( op . found ) ; out2 . add ( op . missed ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ExtendFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Part1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Extend ; @ JobFlow ( name = "" ) public class ExtendFlowSimple extends FlowDescription { private final In < Part1 > in ; private final Out < Ex1 > out ; public ExtendFlowSimple ( @ Import ( name = "" , description = Part1MockImporterDescription . class ) In < Part1 > in , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Extend < Ex1 > project = core . extend ( in , Ex1 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterBranchFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterBranchFlowSimple extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > outHigh ; private Out < Ex1 > outLow ; private Out < Ex1 > outStop ; public MasterBranchFlowSimple ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outHigh , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outLow , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outStop ) { this . in1 = in1 ; this . in2 = in2 ; this . outHigh = outHigh ; this . outLow = outLow ; this . outStop = outStop ; } @ Override protected void describe ( ) { MasterBranchFlowFactory f = new MasterBranchFlowFactory ( ) ; Simple op = f . simple ( in2 , in1 ) ; outHigh . add ( op . high ) ; outLow . add ( op . low ) ; outStop . add ( op . stop ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . SummarizeFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . SummarizeFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . SummarizeFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . ExSummarizedMockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . ExSummarized ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SummarizeFlowTrivial extends FlowDescription { private In < Ex1 > in1 ; private Out < ExSummarized > out1 ; public SummarizeFlowTrivial ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = ExSummarizedMockExporterDescription . class ) Out < ExSummarized > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { SummarizeFlowFactory f = new SummarizeFlowFactory ( ) ; Simple op = f . simple ( in1 ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . CoGroupFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory . Swap ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class CoGroupFlowSwap extends FlowDescription { private final In < Ex1 > in1 ; private final Out < Ex1 > out1 ; public CoGroupFlowSwap ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { CoGroupFlowFactory f = new CoGroupFlowFactory ( ) ; Swap op = f . swap ( in1 ) ; out1 . add ( op . r1 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . FoldFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . FoldFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . FoldFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class FoldFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public FoldFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { FoldFlowFactory f = new FoldFlowFactory ( ) ; WithParameter op = f . withParameter ( in1 , ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ExtractFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . ExtractFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . ExtractFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class ExtractFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex2 > out1 ; public ExtractFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { ExtractFlowFactory f = new ExtractFlowFactory ( ) ; WithParameter op = f . withParameter ( in1 , ) ; out1 . add ( op . r1 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterJoinFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinFlowFactory . RenameKey ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . ExJoined2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterJoinFlowRenameKey extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < ExJoined2 > out1 ; private Out < Ex2 > out2 ; public MasterJoinFlowRenameKey ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = ExJoined2MockExporterDescription . class ) Out < ExJoined2 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterJoinFlowFactory f = new MasterJoinFlowFactory ( ) ; RenameKey join = f . renameKey ( in1 , in2 ) ; out1 . add ( join . joined ) ; out2 . add ( join . missed ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterBranchFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory . SelectionWithParameter0 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterBranchFlowSelectionWithParameter0 extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > outHigh ; private Out < Ex1 > outLow ; private Out < Ex1 > outStop ; public MasterBranchFlowSelectionWithParameter0 ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outHigh , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outLow , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outStop ) { this . in1 = in1 ; this . in2 = in2 ; this . outHigh = outHigh ; this . outLow = outLow ; this . outStop = outStop ; } @ Override protected void describe ( ) { MasterBranchFlowFactory f = new MasterBranchFlowFactory ( ) ; SelectionWithParameter0 op = f . selectionWithParameter0 ( in2 , in1 , ) ; outHigh . add ( op . high ) ; outLow . add ( op . low ) ; outStop . add ( op . stop ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterCheckFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterCheckFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterCheckFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterCheckFlowTrivial extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; public MasterCheckFlowTrivial ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterCheckFlowFactory f = new MasterCheckFlowFactory ( ) ; Simple op = f . simple ( in2 , in1 ) ; out1 . add ( op . found ) ; out2 . add ( op . missed ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ExtendFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Extend ; @ JobFlow ( name = "" ) public class ExtendFlowSame extends FlowDescription { private final In < Ex1 > in ; private final Out < Ex2 > out ; public ExtendFlowSame ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Extend < Ex2 > project = core . extend ( in , Ex2 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . BranchFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterBranchFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > outHigh ; private Out < Ex1 > outLow ; private Out < Ex1 > outStop ; public MasterBranchFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outHigh , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outLow , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outStop ) { this . in1 = in1 ; this . in2 = in2 ; this . outHigh = outHigh ; this . outLow = outLow ; this . outStop = outStop ; } @ Override protected void describe ( ) { MasterBranchFlowFactory f = new MasterBranchFlowFactory ( ) ; WithParameter op = f . withParameter ( in2 , in1 , ) ; outHigh . add ( op . high ) ; outLow . add ( op . low ) ; outStop . add ( op . stop ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterBranchFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterBranchFlowFactory . SelectionWithParameter1 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterBranchFlowSelectionWithParameter1 extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > outHigh ; private Out < Ex1 > outLow ; private Out < Ex1 > outStop ; public MasterBranchFlowSelectionWithParameter1 ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outHigh , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outLow , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outStop ) { this . in1 = in1 ; this . in2 = in2 ; this . outHigh = outHigh ; this . outLow = outLow ; this . outStop = outStop ; } @ Override protected void describe ( ) { MasterBranchFlowFactory f = new MasterBranchFlowFactory ( ) ; SelectionWithParameter1 op = f . selectionWithParameter1 ( in2 , in1 , ) ; outHigh . add ( op . high ) ; outLow . add ( op . low ) ; outStop . add ( op . stop ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . UpdateFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class UpdateFlowSimple extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public UpdateFlowSimple ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { UpdateFlowFactory f = new UpdateFlowFactory ( ) ; Simple op = f . simple ( in1 ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . RestructureFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Part1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Part2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . compiler . flow . testing . model . Part2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; @ JobFlow ( name = "" ) public class RestructureFlowSimple extends FlowDescription { private final In < Part1 > in ; private final Out < Part2 > out ; public RestructureFlowSimple ( @ Import ( name = "" , description = Part1MockImporterDescription . class ) In < Part1 > in , @ Export ( name = "" , description = Part2MockExporterDescription . class ) Out < Part2 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Restructure < Part2 > project = core . restructure ( in , Part2 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ExtractFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . ExtractFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . ExtractFlowFactory . Op1 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class ExtractFlowOp1 extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public ExtractFlowOp1 ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { ExtractFlowFactory f = new ExtractFlowFactory ( ) ; Op1 op = f . op1 ( in1 ) ; out1 . add ( op . r1 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterJoinUpdateFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinUpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinUpdateFlowFactory . Selection ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterJoinUpdateFlowSelection extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; public MasterJoinUpdateFlowSelection ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterJoinUpdateFlowFactory f = new MasterJoinUpdateFlowFactory ( ) ; Selection op = f . selection ( in2 , in1 ) ; out1 . add ( op . updated ) ; out2 . add ( op . missed ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ProjectFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Part1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Project ; @ JobFlow ( name = "" ) public class ProjectFlowInvalid extends FlowDescription { private final In < Part1 > in ; private final Out < Ex1 > out ; public ProjectFlowInvalid ( @ Import ( name = "" , description = Part1MockImporterDescription . class ) In < Part1 > in , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Project < Ex1 > project = core . project ( in , Ex1 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . RestructureFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Part1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Part1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; @ JobFlow ( name = "" ) public class RestructureFlowProject extends FlowDescription { private final In < Ex1 > in ; private final Out < Part1 > out ; public RestructureFlowProject ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Part1MockExporterDescription . class ) Out < Part1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Restructure < Part1 > project = core . restructure ( in , Part1 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . CoGroupFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . CoGroupFlowFactory . Op2 ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class CoGroupFlowOp2 extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > out1 ; private Out < Ex2 > out2 ; public CoGroupFlowOp2 ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { CoGroupFlowFactory f = new CoGroupFlowFactory ( ) ; Op2 op = f . op2 ( in1 , in2 ) ; out1 . add ( op . r1 ) ; out2 . add ( op . r2 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . operator . GroupSortFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . GroupSortFlowFactory . Max ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . operator . GroupSort ; @ JobFlow ( name = "" ) public class GroupSortFlowMax extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public GroupSortFlowMax ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { GroupSortFlowFactory f = new GroupSortFlowFactory ( ) ; Max op = f . max ( in1 ) ; out1 . add ( op . r1 ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . MasterJoinUpdateFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinUpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . MasterJoinUpdateFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MasterJoinUpdateFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private In < Ex2 > in2 ; private Out < Ex1 > out1 ; private Out < Ex1 > out2 ; public MasterJoinUpdateFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Import ( name = "" , description = Ex2MockImporterDescription . class ) In < Ex2 > in2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { MasterJoinUpdateFlowFactory f = new MasterJoinUpdateFlowFactory ( ) ; WithParameter op = f . withParameter ( in2 , in1 , ) ; out1 . add ( op . updated ) ; out2 . add ( op . missed ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . LoggingFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . LoggingFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . LoggingFlowFactory . Simple ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class LoggingFlowSimple extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > out1 ; public LoggingFlowSimple ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out1 ) { this . in1 = in1 ; this . out1 = out1 ; } @ Override protected void describe ( ) { LoggingFlowFactory f = new LoggingFlowFactory ( ) ; Simple op = f . simple ( in1 ) ; out1 . add ( op . out ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . ProjectFlowProcessor ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex2MockExporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Project ; @ JobFlow ( name = "" ) public class ProjectFlowSame extends FlowDescription { private final In < Ex1 > in ; private final Out < Ex2 > out ; public ProjectFlowSame ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Ex2MockExporterDescription . class ) Out < Ex2 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { CoreOperatorFactory core = new CoreOperatorFactory ( ) ; Project < Ex2 > project = core . project ( in , Ex2 . class ) ; out . add ( project ) ; } } package com . asakusafw . compiler . flow . processor . flow ; import com . asakusafw . compiler . flow . processor . BranchFlowProcessor ; import com . asakusafw . compiler . flow . processor . operator . BranchFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . BranchFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class BranchFlowWithParameter extends FlowDescription { private In < Ex1 > in1 ; private Out < Ex1 > outHigh ; private Out < Ex1 > outLow ; private Out < Ex1 > outStop ; public BranchFlowWithParameter ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in1 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outHigh , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outLow , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > outStop ) { this . in1 = in1 ; this . outHigh = outHigh ; this . outLow = outLow ; this . outStop = outStop ; } @ Override protected void describe ( ) { BranchFlowFactory f = new BranchFlowFactory ( ) ; WithParameter op = f . withParameter ( in1 , ) ; outHigh . add ( op . high ) ; outLow . add ( op . low ) ; outStop . add ( op . stop ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . ConvertFlowSimple ; import com . asakusafw . compiler . flow . processor . flow . ConvertFlowWithParameter ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class ConvertFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void simple ( ) { List < StageModel > stages = compile ( ConvertFlowSimple . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex2 > out = mapper . create ( "" ) ; MockResult < Ex1 > orig = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( out . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( orig . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( orig . getResults ( ) . get ( ) , is ( ex1 ) ) ; } @ Test public void withParameter ( ) { List < StageModel > stages = compile ( ConvertFlowWithParameter . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex2 > out = mapper . create ( "" ) ; MockResult < Ex1 > orig = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( out . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( out . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( orig . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( orig . getResults ( ) . get ( ) , is ( ex1 ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . LoggingFlowSimple ; import com . asakusafw . compiler . flow . processor . flow . LoggingFlowWithParameter ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . runtime . core . Report ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class LoggingFlowProcessorTest extends JobflowCompilerTestRoot { @ Override @ Before public void setUp ( ) throws Exception { super . setUp ( ) ; Report . setDelegate ( new Report . Default ( ) ) ; } @ Override @ After public void tearDown ( ) throws Exception { Report . setDelegate ( null ) ; super . tearDown ( ) ; } @ Test public void simple ( ) { List < StageModel > stages = compile ( LoggingFlowSimple . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setStringAsString ( "" ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void withParameter ( ) { List < StageModel > stages = compile ( LoggingFlowWithParameter . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > result = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < Ex1 > f = ( Result < Ex1 > ) create ( loader , name , mapper . toArguments ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; f . add ( ex1 ) ; assertThat ( result . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( result . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import java . util . Map ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; class PortMapper { private Fragment fragment ; private Map < String , Result < ? > > created = Maps . create ( ) ; public PortMapper ( Fragment fragment ) { this . fragment = fragment ; } public < T > MockResult < T > create ( String name ) { MockResult < T > result = MockResult . create ( ) ; return add ( name , result ) ; } public < T extends Result < ? > > T add ( String name , T result ) { created . put ( name , result ) ; return result ; } public Object [ ] toArguments ( ) { List < Result < ? > > results = Lists . create ( ) ; for ( FlowElementOutput out : fragment . getOutputPorts ( ) ) { String name = out . getDescription ( ) . getName ( ) ; Result < ? > port = created . get ( name ) ; assertThat ( name + created , port , not ( nullValue ( ) ) ) ; results . add ( port ) ; } return results . toArray ( ) ; } } package com . asakusafw . compiler . flow . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . processor . flow . SplitFlowTrivial ; import com . asakusafw . compiler . flow . stage . StageModel ; import com . asakusafw . compiler . flow . stage . StageModel . Fragment ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . flow . testing . model . Ex2 ; import com . asakusafw . compiler . flow . testing . model . ExJoined ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . runtime . testing . MockResult ; import com . asakusafw . utils . java . model . syntax . Name ; public class SplitFlowProcessorTest extends JobflowCompilerTestRoot { @ Test public void trivial ( ) { List < StageModel > stages = compile ( SplitFlowTrivial . class ) ; Fragment fragment = stages . get ( ) . getMapUnits ( ) . get ( ) . getFragments ( ) . get ( ) ; Name name = fragment . getCompiled ( ) . getQualifiedName ( ) ; ClassLoader loader = start ( ) ; PortMapper mapper = new PortMapper ( fragment ) ; MockResult < Ex1 > r1 = mapper . create ( "" ) ; MockResult < Ex2 > r2 = mapper . create ( "" ) ; @ SuppressWarnings ( "" ) Result < ExJoined > f = ( Result < ExJoined > ) create ( loader , name , mapper . toArguments ( ) ) ; ExJoined joined = new ExJoined ( ) ; joined . setSid1 ( ) ; joined . setSid2 ( ) ; joined . setValue ( ) ; f . add ( joined ) ; assertThat ( r1 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . size ( ) , is ( ) ) ; assertThat ( r1 . getResults ( ) . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( r1 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . get ( ) . getSid ( ) , is ( ) ) ; assertThat ( r2 . getResults ( ) . get ( ) . getValue ( ) , is ( ) ) ; } } package com . asakusafw . compiler . flow . packager ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . io . PrintWriter ; import java . util . Arrays ; import java . util . Collections ; import java . util . Set ; import java . util . jar . JarEntry ; import java . util . jar . JarInputStream ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . ResourceRepository ; import com . asakusafw . compiler . flow . JobflowCompilerTestRoot ; import com . asakusafw . compiler . flow . Packager ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ImportDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . Models ; public class FilePackagerTest extends JobflowCompilerTestRoot { static final Logger LOG = LoggerFactory . getLogger ( FilePackagerTest . class ) ; @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void build_java ( ) throws Exception { Set < String > entries = Sets . create ( ) ; FilePackager packager = new FilePackager ( folder . newFolder ( ) , Arrays . < ResourceRepository > asList ( ) ) ; packager . initialize ( environment ) ; emit ( packager , java ( "" ) ) ; build ( entries , packager ) ; assertThat ( entries , hasItem ( "" ) ) ; } @ Test public void build_resource ( ) throws Exception { Set < String > entries = Sets . create ( ) ; FilePackager packager = new FilePackager ( folder . newFolder ( ) , Arrays . < ResourceRepository > asList ( ) ) ; packager . initialize ( environment ) ; write ( packager , "" , "" , "" ) ; build ( entries , packager ) ; assertThat ( entries , hasItem ( "" ) ) ; } @ Test public void build_mixed ( ) throws Exception { Set < String > entries = Sets . create ( ) ; FilePackager packager = new FilePackager ( folder . newFolder ( ) , Arrays . < ResourceRepository > asList ( ) ) ; packager . initialize ( environment ) ; emit ( packager , java ( "" ) ) ; emit ( packager , java ( "" ) ) ; write ( packager , "" , "" , "" ) ; write ( packager , null , "" , "" ) ; build ( entries , packager ) ; assertThat ( entries , hasItem ( "" ) ) ; assertThat ( entries , hasItem ( "" ) ) ; assertThat ( entries , hasItem ( "" ) ) ; assertThat ( entries , hasItem ( "" ) ) ; } @ Test public void build_error ( ) throws Exception { Set < String > entries = Sets . create ( ) ; FilePackager packager = new FilePackager ( folder . newFolder ( ) , Arrays . < ResourceRepository > asList ( ) ) ; packager . initialize ( environment ) ; ModelFactory f = Models . getModelFactory ( ) ; CompilationUnit cu = f . newCompilationUnit ( f . newPackageDeclaration ( Models . toName ( f , "" ) ) , Collections . < ImportDeclaration > emptyList ( ) , Collections . singletonList ( f . newClassDeclaration ( null , new AttributeBuilder ( f ) . Public ( ) . Private ( ) . toAttributes ( ) , f . newSimpleName ( "" ) , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . < Type > emptyList ( ) , Collections . < TypeBodyDeclaration > emptyList ( ) ) ) , Collections . < Comment > emptyList ( ) ) ; emit ( packager , cu ) ; try { build ( entries , packager ) ; fail ( ) ; } catch ( IOException e ) { assertThat ( environment . hasError ( ) , is ( true ) ) ; } } private void build ( Set < String > entries , FilePackager packager ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; packager . build ( output ) ; output . close ( ) ; ByteArrayInputStream input = new ByteArrayInputStream ( output . toByteArray ( ) ) ; JarInputStream jar = new JarInputStream ( input ) ; try { while ( true ) { JarEntry entry = jar . getNextJarEntry ( ) ; if ( entry == null ) { break ; } entries . add ( entry . getName ( ) ) ; } } finally { jar . close ( ) ; } } private void emit ( Packager packager , CompilationUnit java ) throws IOException { PrintWriter writer = packager . openWriter ( java ) ; try { Models . emit ( java , writer ) ; } finally { writer . close ( ) ; } } private void write ( Packager packager , String pkg , String rel , String value ) throws IOException { ModelFactory f = Models . getModelFactory ( ) ; OutputStream output = packager . openStream ( pkg == null ? null : Models . toName ( f , pkg ) , rel ) ; try { output . write ( value . getBytes ( "" ) ) ; } finally { output . close ( ) ; } } private CompilationUnit java ( String name ) { ModelFactory f = Models . getModelFactory ( ) ; return f . newCompilationUnit ( f . newPackageDeclaration ( Models . toName ( f , "" ) ) , Collections . < ImportDeclaration > emptyList ( ) , Collections . singletonList ( f . newClassDeclaration ( null , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , f . newSimpleName ( name ) , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . < Type > emptyList ( ) , Collections . < TypeBodyDeclaration > emptyList ( ) ) ) , Collections . < Comment > emptyList ( ) ) ; } } package com . asakusafw . compiler . batch ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SideJobFlow extends FlowDescription { private final In < Ex1 > in ; private final Out < Ex1 > out ; public SideJobFlow ( @ Import ( name = "" , description = Importer . class ) In < Ex1 > in , @ Export ( name = "" , description = Exporter . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { UpdateFlowFactory f = new UpdateFlowFactory ( ) ; WithParameter op = f . withParameter ( in , ) ; out . add ( op . out ) ; } public static class Importer extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" ) ; } } public static class Exporter extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } } package com . asakusafw . compiler . batch ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Export ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . BatchInfo ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class BatchCompilerTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void simple ( ) throws Exception { BatchInfo info = tester . compileBatch ( SimpleBatch . class ) ; ModelOutput < Ex1 > output = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; output . write ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; output . write ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; output . write ( ex1 ) ; output . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > input = tester . getList ( Ex1 . class , seqfile ( tester . getExporter ( info , "" ) ) . asPrefix ( ) , new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( input . size ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void ordered ( ) throws Exception { BatchInfo info = tester . compileBatch ( OrderedBatch . class ) ; ModelOutput < Ex1 > output = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; output . write ( ex1 ) ; output . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > input = tester . getList ( Ex1 . class , seqfile ( tester . getExporter ( info , "" ) ) . asPrefix ( ) ) ; assertThat ( input . size ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; } @ Test public void join ( ) throws Exception { BatchInfo info = tester . compileBatch ( JoinBatch . class ) ; ModelOutput < Ex1 > output = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setValue ( ) ; output . write ( ex1 ) ; output . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > input = tester . getList ( Ex1 . class , seqfile ( tester . getExporter ( info , "" ) ) . asPrefix ( ) , new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getValueOption ( ) . compareTo ( o2 . getValueOption ( ) ) ; } } ) ; assertThat ( input . size ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; } private Location seqfile ( Export exporter ) { ExporterDescription desc = exporter . getDescription ( ) . getExporterDescription ( ) ; assertThat ( desc , instanceOf ( TemporaryOutputDescription . class ) ) ; TemporaryOutputDescription d = ( TemporaryOutputDescription ) desc ; return Location . fromPath ( d . getPathPrefix ( ) , '' ) ; } } package com . asakusafw . compiler . batch . batch ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . List ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . util . Emitter ; public class MockEmitter extends Emitter { private List < VolatileJavaFile > emitted = Lists . create ( ) ; @ Override public PrintWriter openFor ( PackageDeclaration packageDeclOrNull , String subPath ) throws IOException { StringBuilder buf = new StringBuilder ( ) ; if ( packageDeclOrNull != null ) { buf . append ( packageDeclOrNull . getName ( ) . toNameString ( ) . replace ( '' , '' ) ) ; buf . append ( "" ) ; } assert subPath . endsWith ( "" ) ; buf . append ( subPath . substring ( , subPath . length ( ) - ) ) ; VolatileJavaFile file = new VolatileJavaFile ( buf . toString ( ) ) ; register ( file ) ; return new PrintWriter ( file . openWriter ( ) ) ; } private void register ( VolatileJavaFile file ) { emitted . add ( file ) ; } public List < VolatileJavaFile > getEmitted ( ) { return emitted ; } } package com . asakusafw . compiler . batch . batch ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . JobFlow ; @ JobFlow ( name = "" ) public class JobFlow1 extends FlowDescription { @ Override protected void describe ( ) { return ; } } package com . asakusafw . compiler . batch . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public abstract class Abstract extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; } } package com . asakusafw . compiler . batch . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class TopLevel { @ Batch ( name = "" ) public static class Inner extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; } } } package com . asakusafw . compiler . batch . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class InstantiateFailBatch extends BatchDescription { public InstantiateFailBatch ( ) { throw new RuntimeException ( ) ; } @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; } } package com . asakusafw . compiler . batch . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class NoEmptyParameterConstructor extends BatchDescription { public NoEmptyParameterConstructor ( int odd ) { return ; } @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; } } package com . asakusafw . compiler . batch . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class SimpleBatch extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; } } package com . asakusafw . compiler . batch . batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; public class NotAnnotated extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; } } package com . asakusafw . compiler . batch . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class DescribeFailBatch extends BatchDescription { @ Override protected void describe ( ) { throw new RuntimeException ( ) ; } } package com . asakusafw . compiler . batch ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Collection ; import org . junit . Test ; import com . asakusafw . compiler . batch . batch . Abstract ; import com . asakusafw . compiler . batch . batch . DescribeFailBatch ; import com . asakusafw . compiler . batch . batch . InstantiateFailBatch ; import com . asakusafw . compiler . batch . batch . JobFlow1 ; import com . asakusafw . compiler . batch . batch . NoEmptyParameterConstructor ; import com . asakusafw . compiler . batch . batch . NotAnnotated ; import com . asakusafw . compiler . batch . batch . SimpleBatch ; import com . asakusafw . compiler . batch . batch . TopLevel ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . batch . Work ; public class BatchDriverTest { @ Test public void simple ( ) { BatchDriver analyze = BatchDriver . analyze ( SimpleBatch . class ) ; assertThat ( analyze . hasError ( ) , is ( false ) ) ; BatchClass batch = analyze . getBatchClass ( ) ; Collection < Work > works = batch . getDescription ( ) . getWorks ( ) ; assertThat ( works . size ( ) , is ( ) ) ; Work work = works . iterator ( ) . next ( ) ; assertThat ( work . getDeclaring ( ) , is ( batch . getDescription ( ) ) ) ; assertThat ( work . getDependencies ( ) . size ( ) , is ( ) ) ; assertThat ( work . getDescription ( ) , is ( ( Object ) new JobFlowWorkDescription ( JobFlow1 . class ) ) ) ; } @ Test public void Abstract ( ) { BatchDriver analyze = BatchDriver . analyze ( Abstract . class ) ; assertThat ( analyze . hasError ( ) , is ( true ) ) ; } @ Test public void NotPublic ( ) { BatchDriver analyze = BatchDriver . analyze ( NotPublic . class ) ; assertThat ( analyze . hasError ( ) , is ( true ) ) ; } @ Test public void NotTopLevel ( ) { BatchDriver analyze = BatchDriver . analyze ( TopLevel . Inner . class ) ; assertThat ( analyze . hasError ( ) , is ( true ) ) ; } @ Test public void NotAnnotated ( ) { BatchDriver analyze = BatchDriver . analyze ( NotAnnotated . class ) ; assertThat ( analyze . hasError ( ) , is ( true ) ) ; } @ Test public void NoEmptyParameterConstructor ( ) { BatchDriver analyze = BatchDriver . analyze ( NoEmptyParameterConstructor . class ) ; assertThat ( analyze . hasError ( ) , is ( true ) ) ; } @ Test public void InstantiateFailure ( ) { BatchDriver analyze = BatchDriver . analyze ( InstantiateFailBatch . class ) ; assertThat ( analyze . hasError ( ) , is ( true ) ) ; } @ Test public void DescribeFailure ( ) { BatchDriver analyze = BatchDriver . analyze ( DescribeFailBatch . class ) ; assertThat ( analyze . hasError ( ) , is ( true ) ) ; } } package com . asakusafw . compiler . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . batch . Work ; @ Batch ( name = "" ) public class JoinBatch extends BatchDescription { @ Override protected void describe ( ) { Work first = run ( FirstJobFlow . class ) . soon ( ) ; Work second = run ( SecondJobFlow . class ) . after ( first ) ; Work side = run ( SideJobFlow . class ) . after ( first ) ; run ( JoinJobFlow . class ) . after ( second , side ) ; } } package com . asakusafw . compiler . batch ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import org . junit . rules . TestRule ; import org . junit . runner . Description ; import org . junit . runners . model . Statement ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectBatchCompiler ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . runtime . stage . StageConstants ; public class BatchCompilerEnvironmentProvider implements TestRule { private BatchCompilerConfiguration config ; private BatchCompilingEnvironment environment ; @ Override public Statement apply ( Statement base , Description description ) { try { config = DirectBatchCompiler . createConfig ( description . getMethodName ( ) , "" , Location . fromPath ( String . format ( "" , description . getTestClass ( ) . getName ( ) , description . getMethodName ( ) ) , '' ) , new File ( String . format ( "" , description . getTestClass ( ) . getName ( ) , description . getMethodName ( ) ) ) , new File ( String . format ( "" , description . getTestClass ( ) . getName ( ) , description . getMethodName ( ) ) ) , Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( getClass ( ) ) , DirectFlowCompiler . toLibraryPath ( StageConstants . class ) , } ) , description . getTestClass ( ) . getClassLoader ( ) , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } return base ; } public BatchCompilerConfiguration getConfig ( ) { return config ; } public BatchCompilingEnvironment getEnvironment ( ) { if ( environment == null ) { environment = new BatchCompilingEnvironment ( config ) . bless ( ) ; } return environment ; } } package com . asakusafw . compiler . batch ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SecondJobFlow extends FlowDescription { private final In < Ex1 > in ; private final Out < Ex1 > out ; public SecondJobFlow ( @ Import ( name = "" , description = Importer . class ) In < Ex1 > in , @ Export ( name = "" , description = Exporter . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { UpdateFlowFactory f = new UpdateFlowFactory ( ) ; WithParameter op = f . withParameter ( in , ) ; out . add ( op . out ) ; } public static class Importer extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" ) ; } } public static class Exporter extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } } package com . asakusafw . compiler . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . batch . Work ; @ Batch ( name = "" ) public class OrderedBatch extends BatchDescription { @ Override protected void describe ( ) { Work first = run ( FirstJobFlow . class ) . soon ( ) ; run ( SecondJobFlow . class ) . after ( first ) ; } } package com . asakusafw . compiler . batch ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class FirstJobFlow extends FlowDescription { private final In < Ex1 > in ; private final Out < Ex1 > out ; public FirstJobFlow ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Exporter . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { UpdateFlowFactory f = new UpdateFlowFactory ( ) ; WithParameter op = f . withParameter ( in , ) ; out . add ( op . out ) ; } public static class Exporter extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } } package com . asakusafw . compiler . batch ; import com . asakusafw . compiler . batch . batch . JobFlow1 ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) class NotPublic extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; } } package com . asakusafw . compiler . batch ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class JoinJobFlow extends FlowDescription { private final In < Ex1 > in ; private final Out < Ex1 > out ; public JoinJobFlow ( @ Import ( name = "" , description = Importer . class ) In < Ex1 > in , @ Export ( name = "" , description = Exporter . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { UpdateFlowFactory f = new UpdateFlowFactory ( ) ; WithParameter op = f . withParameter ( in , ) ; out . add ( op . out ) ; } public static class Importer extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public Set < String > getPaths ( ) { return new HashSet < String > ( Arrays . asList ( "" , "" ) ) ; } } public static class Exporter extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } } package com . asakusafw . compiler . batch ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . flow . testing . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SimpleJobFlow extends FlowDescription { private In < Ex1 > in ; private Out < Ex1 > out ; public SimpleJobFlow ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > in , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { UpdateFlowFactory f = new UpdateFlowFactory ( ) ; WithParameter op = f . withParameter ( in , ) ; out . add ( op . out ) ; } } package com . asakusafw . compiler . batch ; import com . asakusafw . vocabulary . batch . Batch ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ Batch ( name = "" ) public class SimpleBatch extends BatchDescription { @ Override protected void describe ( ) { run ( SimpleJobFlow . class ) . soon ( ) ; } } package com . asakusafw . compiler . batch . processor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . batch . BatchCompilerEnvironmentProvider ; import com . asakusafw . compiler . batch . BatchCompilingEnvironment ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; public class JobFlowWorkDescriptionProcessorTest { @ Rule public BatchCompilerEnvironmentProvider prov = new BatchCompilerEnvironmentProvider ( ) ; @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void simple ( ) throws Exception { BatchCompilingEnvironment env = prov . getEnvironment ( ) ; JobFlowWorkDescriptionProcessor proc = new JobFlowWorkDescriptionProcessor ( ) ; proc . initialize ( env ) ; JobFlowWorkDescription jobflow = new JobFlowWorkDescription ( SimpleJobFlow . class ) ; JobflowModel model = proc . process ( jobflow ) ; File jar = JobFlowWorkDescriptionProcessor . getPackageLocation ( env . getConfiguration ( ) . getOutputDirectory ( ) , model . getFlowId ( ) ) ; JobflowInfo info = DirectFlowCompiler . toInfo ( model , jar , jar ) ; ModelOutput < Ex1 > output = tester . openOutput ( Ex1 . class , Location . fromPath ( "" , '' ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; output . write ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; output . write ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; output . write ( ex1 ) ; output . close ( ) ; tester . run ( info ) ; List < Ex1 > input = tester . getList ( Ex1 . class , Location . fromPath ( "" , '' ) , new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; assertThat ( input . size ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( input . get ( ) . getValue ( ) , is ( ) ) ; } } package com . asakusafw . compiler . batch . processor ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory ; import com . asakusafw . compiler . flow . processor . operator . UpdateFlowFactory . WithParameter ; import com . asakusafw . compiler . flow . testing . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SimpleJobFlow extends FlowDescription { private final In < Ex1 > in ; private final Out < Ex1 > out ; public SimpleJobFlow ( @ Import ( name = "" , description = Importer . class ) In < Ex1 > in , @ Export ( name = "" , description = Exporter . class ) Out < Ex1 > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { UpdateFlowFactory f = new UpdateFlowFactory ( ) ; WithParameter op = f . withParameter ( in , ) ; out . add ( op . out ) ; } public static class Importer extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" ) ; } } public static class Exporter extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } } package com . asakusafw . compiler . util . tester ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . Closeable ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . UUID ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . Writable ; import org . junit . Assume ; import org . junit . rules . TestRule ; import org . junit . runner . Description ; import org . junit . runners . model . Statement ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowDescriptionDriver ; import com . asakusafw . compiler . flow . JobFlowDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Export ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Import ; import com . asakusafw . compiler . testing . BatchInfo ; import com . asakusafw . compiler . testing . DirectBatchCompiler ; import com . asakusafw . compiler . testing . DirectExporterDescription ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . DirectImporterDescription ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . testing . StageInfo ; import com . asakusafw . runtime . configuration . FrameworkDeployer ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . AbstractCleanupStageClient ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . runtime . util . VariableTable . RedefineStrategy ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . vocabulary . batch . BatchDescription ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; public class CompilerTester implements TestRule { static final Logger LOG = LoggerFactory . getLogger ( CompilerTester . class ) ; protected final HadoopDriver hadoopDriver ; protected final FrameworkDeployer frameworkDeployer ; final FlowDescriptionDriver flow ; Class < ? > testClass ; String testName ; private final VariableTable variables ; private final FlowCompilerOptions options ; private final List < File > libraries ; public CompilerTester ( ) { this ( true ) ; } public CompilerTester ( boolean createFramework ) { this . hadoopDriver = HadoopDriver . createInstance ( ) ; this . frameworkDeployer = new FrameworkDeployer ( createFramework ) ; this . flow = new FlowDescriptionDriver ( ) ; this . testClass = getClass ( ) ; this . testName = "" ; this . variables = new VariableTable ( RedefineStrategy . ERROR ) ; this . options = new FlowCompilerOptions ( ) ; this . libraries = new ArrayList < File > ( ) ; } @ Override public Statement apply ( final Statement base , final Description description ) { Statement stmt = new Statement ( ) { @ Override public void evaluate ( ) throws Throwable { Assume . assumeNotNull ( hadoopDriver ) ; try { testClass = description . getTestClass ( ) ; testName = MessageFormat . format ( "" , description . getTestClass ( ) . getSimpleName ( ) , description . getMethodName ( ) . replaceAll ( "" , "" ) ) ; hadoopDriver . setLogger ( LoggerFactory . getLogger ( testClass ) ) ; hadoopDriver . clean ( ) ; configure ( description ) ; base . evaluate ( ) ; } finally { hadoopDriver . close ( ) ; } } } ; return frameworkDeployer . apply ( stmt , description ) ; } protected void configure ( Description description ) { return ; } public VariableTable variables ( ) { return variables ; } public FlowCompilerOptions options ( ) { return options ; } public Configuration configuration ( ) { return hadoopDriver . getConfiguration ( ) ; } public List < File > libraries ( ) { return libraries ; } public FrameworkDeployer framework ( ) { return frameworkDeployer ; } public boolean runFlow ( FlowDescription description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } return run ( compileFlow ( description ) ) ; } public FlowGraph analyzeFlow ( FlowDescription description ) { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } return flow . createFlowGraph ( description ) ; } public JobflowInfo compileFlow ( FlowDescription description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } FlowGraph graph = flow . createFlowGraph ( description ) ; List < File > classPath = buildClassPath ( description . getClass ( ) ) ; return DirectFlowCompiler . compile ( graph , "" , description . getClass ( ) . getName ( ) , "" , hadoopDriver . toPath ( path ( "" , "" ) ) , new File ( "" , testName ) , classPath , getClass ( ) . getClassLoader ( ) , options ) ; } public JobflowInfo compileJobflow ( Class < ? extends FlowDescription > description ) throws IOException { JobFlowDriver driver = JobFlowDriver . analyze ( description ) ; assertThat ( driver . getDiagnostics ( ) . toString ( ) , driver . hasError ( ) , is ( false ) ) ; List < File > classPath = buildClassPath ( description ) ; JobflowInfo info = DirectFlowCompiler . compile ( driver . getJobFlowClass ( ) . getGraph ( ) , "" , driver . getJobFlowClass ( ) . getConfig ( ) . name ( ) , "" , hadoopDriver . toPath ( path ( "" , "" ) ) , new File ( "" , testName ) , classPath , getClass ( ) . getClassLoader ( ) , options ) ; return info ; } public boolean runJobflow ( Class < ? extends FlowDescription > description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } JobflowInfo info = compileJobflow ( description ) ; return run ( info ) ; } public BatchInfo compileBatch ( Class < ? extends BatchDescription > description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } List < File > classPath = buildClassPath ( description ) ; BatchInfo info = DirectBatchCompiler . compile ( description , "" , hadoopDriver . toPath ( path ( "" , "" ) ) , new File ( "" + testName + "" ) , new File ( "" + testName + "" ) , classPath , getClass ( ) . getClassLoader ( ) , options ) ; return info ; } public boolean runBatch ( Class < ? extends BatchDescription > description ) throws IOException { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } return run ( compileBatch ( description ) ) ; } public boolean run ( BatchInfo info ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } for ( JobflowInfo jobflow : info . getJobflows ( ) ) { boolean succeed = run ( jobflow ) ; if ( succeed == false ) { return false ; } } return true ; } public boolean run ( JobflowInfo info ) throws IOException { return run ( info , true , true ) ; } public boolean runStages ( JobflowInfo info ) throws IOException { return run ( info , true , false ) ; } private boolean run ( JobflowInfo info , boolean stages , boolean cleanup ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } File confFile = frameworkDeployer . getCoreConfigurationFile ( ) ; if ( confFile == null ) { LOG . info ( "" ) ; } else { LOG . warn ( "" , confFile . getAbsolutePath ( ) ) ; } Map < String , String > definitions = new HashMap < String , String > ( ) ; definitions . put ( StageConstants . PROP_USER , System . getProperty ( "" ) ) ; definitions . put ( StageConstants . PROP_EXECUTION_ID , UUID . randomUUID ( ) . toString ( ) ) ; definitions . put ( StageConstants . PROP_ASAKUSA_BATCH_ARGS , variables . toSerialString ( ) ) ; List < File > libjars = new ArrayList < File > ( ) ; libjars . add ( info . getPackageFile ( ) ) ; libjars . addAll ( libraries ) ; if ( stages ) { if ( executeStage ( info , confFile , definitions , libjars ) == false ) { return false ; } } if ( cleanup ) { if ( executeCleanup ( info , confFile , definitions , libjars ) == false ) { return false ; } } return true ; } private boolean executeStage ( JobflowInfo info , File confFile , Map < String , String > definitions , List < File > libjars ) throws IOException { assert info != null ; assert definitions != null ; assert libjars != null ; for ( StageInfo stage : info . getStages ( ) ) { boolean succeed = hadoopDriver . runJob ( frameworkDeployer . getCoreRuntimeLibrary ( ) , libjars , stage . getClassName ( ) , confFile , definitions ) ; if ( succeed == false ) { return false ; } } return true ; } private boolean executeCleanup ( JobflowInfo info , File confFile , Map < String , String > definitions , List < File > libjars ) throws IOException { assert info != null ; assert definitions != null ; assert libjars != null ; if ( info . getStages ( ) . isEmpty ( ) == false ) { boolean succeed = hadoopDriver . runJob ( frameworkDeployer . getCoreRuntimeLibrary ( ) , libjars , AbstractCleanupStageClient . IMPLEMENTATION , confFile , definitions ) ; if ( succeed == false ) { return false ; } } return true ; } private List < File > buildClassPath ( Class < ? > ... libraryClasses ) { List < File > classPath = Lists . create ( ) ; classPath . add ( findClassPathFromClass ( testClass ) ) ; for ( Class < ? > libraryClass : libraryClasses ) { classPath . add ( findClassPathFromClass ( libraryClass ) ) ; } return classPath ; } private File findClassPathFromClass ( Class < ? > aClass ) { assert aClass != null ; File path = DirectFlowCompiler . toLibraryPath ( aClass ) ; assertThat ( aClass . getName ( ) , path , not ( nullValue ( ) ) ) ; return path ; } public < T extends Writable > TestInput < T > input ( Class < T > type , String name ) throws IOException { return input ( type , name , DataSize . UNKNOWN ) ; } public < T extends Writable > TestInput < T > input ( Class < T > type , String name , DataSize dataSize ) throws IOException { Location path = hadoopDriver . toPath ( path ( "" , JavaName . of ( name ) . toMemberName ( ) ) ) ; return new TestInput < T > ( type , name , path , dataSize ) ; } public < T > In < T > input ( String name , ImporterDescription importer ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( importer == null ) { throw new IllegalArgumentException ( "" ) ; } return flow . createIn ( name , importer ) ; } public < T > Out < T > output ( String name , ExporterDescription exporter ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( exporter == null ) { throw new IllegalArgumentException ( "" ) ; } return flow . createOut ( name , exporter ) ; } public < T extends Writable > TestOutput < T > output ( Class < T > type , String name ) throws IOException { Location path = hadoopDriver . toPath ( testName , "" , name ) . asPrefix ( ) ; return new TestOutput < T > ( type , name , path ) ; } public < T extends Writable > ModelOutput < T > openOutput ( Class < T > type , Location location ) throws IOException { return hadoopDriver . openOutput ( type , location ) ; } public < T extends Writable > ModelOutput < T > openOutput ( Class < T > type , Import importer ) throws IOException { Iterator < Location > iter = importer . getInputInfo ( ) . getLocations ( ) . iterator ( ) ; assert iter . hasNext ( ) ; Location location = iter . next ( ) ; return hadoopDriver . openOutput ( type , location ) ; } public < T extends Writable > ModelInput < T > openInput ( Class < T > type , Location location ) throws IOException { return hadoopDriver . openInput ( type , location ) ; } public Import getImporter ( BatchInfo info , String name ) { for ( JobflowInfo jf : info . getJobflows ( ) ) { for ( Import in : jf . getJobflow ( ) . getImports ( ) ) { if ( in . getDescription ( ) . getName ( ) . equals ( name ) ) { return in ; } } } throw new AssertionError ( name ) ; } public Export getExporter ( BatchInfo info , String name ) { for ( JobflowInfo jf : info . getJobflows ( ) ) { for ( Export out : jf . getJobflow ( ) . getExports ( ) ) { if ( out . getDescription ( ) . getName ( ) . equals ( name ) ) { return out ; } } } throw new AssertionError ( name ) ; } public Import getImporter ( JobflowInfo info , String name ) { for ( Import in : info . getJobflow ( ) . getImports ( ) ) { if ( in . getDescription ( ) . getName ( ) . equals ( name ) ) { return in ; } } throw new AssertionError ( name ) ; } public Export getExporter ( JobflowInfo info , String name ) { for ( Export out : info . getJobflow ( ) . getExports ( ) ) { if ( out . getDescription ( ) . getName ( ) . equals ( name ) ) { return out ; } } throw new AssertionError ( name ) ; } public < T extends Writable > List < T > getList ( Class < T > type , Location location ) throws IOException { ModelInput < T > input = hadoopDriver . openInput ( type , location ) ; try { List < T > results = Lists . create ( ) ; while ( true ) { T target = type . newInstance ( ) ; if ( input . readTo ( target ) == false ) { break ; } results . add ( target ) ; } return results ; } catch ( IOException e ) { throw e ; } catch ( Exception e ) { throw new IOException ( e ) ; } finally { input . close ( ) ; } } public < T extends Writable > List < T > getList ( Class < T > type , Location location , Comparator < ? super T > comparator ) throws IOException { List < T > list = getList ( type , location ) ; Collections . sort ( list , comparator ) ; return list ; } private String path ( String prefix , String name ) { if ( testName == null ) { return prefix + "" + name ; } else { return testName + "" + prefix + "" + name ; } } public class TestInput < T extends Writable > implements Closeable { private final Class < T > type ; private final ModelOutput < T > output ; private final String name ; private final Location path ; private final DataSize dataSize ; TestInput ( Class < T > type , String name , Location path , DataSize dataSize ) throws IOException { assert type != null ; assert name != null ; assert path != null ; this . type = type ; this . name = name ; this . path = path ; this . output = hadoopDriver . openOutput ( type , path ) ; this . dataSize = dataSize ; } public void add ( T model ) throws IOException { output . write ( model ) ; } public In < T > flow ( ) throws IOException { close ( ) ; DirectImporterDescription description = new DirectImporterDescription ( type , path . toPath ( '' ) ) ; description . setDataSize ( dataSize ) ; return flow . createIn ( name , description ) ; } @ Override public void close ( ) throws IOException { output . close ( ) ; } } public class TestOutput < T extends Writable > { private final Class < T > type ; private final String name ; private final Location pathPrefix ; TestOutput ( Class < T > type , String name , Location pathPrefix ) { assert type != null ; assert name != null ; assert pathPrefix != null ; this . type = type ; this . name = name ; this . pathPrefix = pathPrefix ; } public Out < T > flow ( ) throws IOException { return flow . createOut ( name , new DirectExporterDescription ( type , pathPrefix . getParent ( ) . append ( pathPrefix . getName ( ) ) . asPrefix ( ) . toPath ( '' ) ) ) ; } public List < T > toList ( ) throws IOException { ModelInput < T > input = hadoopDriver . openInput ( type , pathPrefix ) ; try { List < T > results = Lists . create ( ) ; while ( true ) { T target = type . newInstance ( ) ; if ( input . readTo ( target ) == false ) { break ; } results . add ( target ) ; } return results ; } catch ( IOException e ) { throw e ; } catch ( Exception e ) { throw new IOException ( e ) ; } finally { input . close ( ) ; } } public List < T > toList ( Comparator < ? super T > cmp ) throws IOException { List < T > results = toList ( ) ; Collections . sort ( results , cmp ) ; return results ; } } } package com . asakusafw . compiler . util . tester ; import java . io . Closeable ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Scanner ; import java . util . concurrent . atomic . AtomicBoolean ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Writable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . MultipleModelInput ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . ToolLauncher ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; import com . asakusafw . utils . collections . Lists ; public final class HadoopDriver implements Closeable { static final Logger LOG = LoggerFactory . getLogger ( HadoopDriver . class ) ; private volatile Logger logger ; public static final String RUNTIME_WORK_ROOT = "" ; private final File command ; private final Configuration configuration ; private HadoopDriver ( ) { this . command = ConfigurationProvider . findHadoopCommand ( ) ; this . configuration = new ConfigurationProvider ( ) . newInstance ( ) ; this . logger = LOG ; } public void setLogger ( Logger logger ) { if ( logger == null ) { throw new IllegalArgumentException ( "" ) ; } this . logger = logger ; } public Configuration getConfiguration ( ) { return configuration ; } public Location toPath ( String ... segments ) { if ( segments == null ) { throw new IllegalArgumentException ( "" ) ; } Location path = Location . fromPath ( RUNTIME_WORK_ROOT , '' ) ; for ( String segment : segments ) { path = path . append ( segment ) ; } return path ; } public static HadoopDriver createInstance ( ) { return new HadoopDriver ( ) ; } public < T extends Writable > ModelInput < T > openInput ( Class < T > modelType , final Location location ) throws IOException { if ( modelType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( location == null ) { throw new IllegalArgumentException ( "" ) ; } final File temp = createTempFile ( modelType ) ; if ( temp . delete ( ) == false ) { logger . debug ( "" , temp ) ; } if ( temp . mkdirs ( ) == false ) { throw new IOException ( temp . getAbsolutePath ( ) ) ; } copyFromHadoop ( location . toPath ( '' ) , temp ) ; List < ModelInput < T > > sources = Lists . create ( ) ; if ( location . isPrefix ( ) ) { for ( File file : temp . listFiles ( ) ) { if ( file . isFile ( ) && file . getName ( ) . startsWith ( "" ) == false ) { sources . add ( TemporaryStorage . openInput ( configuration , modelType , new Path ( file . toURI ( ) ) ) ) ; } } } else { for ( File folder : temp . listFiles ( ) ) { for ( File file : folder . listFiles ( ) ) { if ( file . isFile ( ) && file . getName ( ) . startsWith ( "" ) == false ) { sources . add ( TemporaryStorage . openInput ( configuration , modelType , new Path ( file . toURI ( ) ) ) ) ; } } } } return new MultipleModelInput < T > ( sources ) { final AtomicBoolean closed = new AtomicBoolean ( ) ; @ Override public void close ( ) throws IOException { if ( closed . compareAndSet ( false , true ) == false ) { return ; } super . close ( ) ; onInputCompleted ( temp , location ) ; } } ; } public < T extends Writable > ModelOutput < T > openOutput ( Class < T > modelType , final Location path ) throws IOException { return TemporaryStorage . openOutput ( configuration , modelType , new Path ( path . toPath ( '' ) ) ) ; } private < T > File createTempFile ( Class < T > modelType ) throws IOException { assert modelType != null ; return File . createTempFile ( modelType . getSimpleName ( ) + "" , "" ) ; } void onInputCompleted ( File temp , Location path ) { assert temp != null ; assert path != null ; logger . debug ( "" , path , temp ) ; if ( delete ( temp ) == false ) { logger . warn ( "" , temp ) ; } } private boolean delete ( File temp ) { boolean success = true ; if ( temp . isDirectory ( ) ) { for ( File child : temp . listFiles ( ) ) { success &= delete ( child ) ; } } success &= temp . delete ( ) ; return success ; } public boolean runJob ( File runtimeLib , List < File > libjars , String className , File conf , Map < String , String > properties ) throws IOException { if ( runtimeLib == null ) { throw new IllegalArgumentException ( "" ) ; } if ( className == null ) { throw new IllegalArgumentException ( "" ) ; } if ( libjars == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } logger . info ( "" , className , libjars ) ; List < String > arguments = Lists . create ( ) ; arguments . add ( "" ) ; arguments . add ( runtimeLib . getAbsolutePath ( ) ) ; arguments . add ( ToolLauncher . class . getName ( ) ) ; arguments . add ( className ) ; if ( libjars . isEmpty ( ) == false ) { StringBuilder buf = new StringBuilder ( ) ; for ( File f : libjars ) { buf . append ( f . getAbsolutePath ( ) ) ; buf . append ( "" ) ; } buf . deleteCharAt ( buf . length ( ) - ) ; arguments . add ( "" ) ; arguments . add ( buf . toString ( ) ) ; } if ( conf != null ) { arguments . add ( "" ) ; arguments . add ( conf . getCanonicalPath ( ) ) ; } for ( Map . Entry < String , String > entry : properties . entrySet ( ) ) { arguments . add ( "" ) ; arguments . add ( MessageFormat . format ( "" , entry . getKey ( ) , entry . getValue ( ) ) ) ; } int ret = invoke ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; if ( ret != ) { logger . info ( "" , className , ret ) ; return false ; } return true ; } private void copyFromHadoop ( String source , File destination ) throws IOException { if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } if ( destination == null ) { throw new IllegalArgumentException ( "" ) ; } logger . info ( "" , source , destination ) ; int ret = invoke ( "" , "" , source , destination . getAbsolutePath ( ) ) ; if ( ret != ) { throw new IOException ( MessageFormat . format ( "" , String . valueOf ( ret ) , source , destination . getAbsolutePath ( ) ) ) ; } } public void clean ( ) throws IOException { logger . info ( "" ) ; int ret = invoke ( "" , "" , toPath ( ) . toPath ( '' ) ) ; if ( ret != ) { logger . info ( MessageFormat . format ( "" , toPath ( ) , String . valueOf ( ret ) ) ) ; } } private int invoke ( String ... arguments ) throws IOException { String hadoop = getHadoopCommand ( ) ; List < String > commands = Lists . create ( ) ; commands . add ( hadoop ) ; Collections . addAll ( commands , arguments ) ; logger . info ( "" , commands ) ; ProcessBuilder builder = new ProcessBuilder ( ) . command ( commands ) . redirectErrorStream ( true ) ; Process process = builder . start ( ) ; try { InputStream stream = process . getInputStream ( ) ; Scanner scanner = new Scanner ( stream ) ; while ( scanner . hasNextLine ( ) ) { logger . info ( scanner . nextLine ( ) ) ; } return process . waitFor ( ) ; } catch ( InterruptedException e ) { throw new IOException ( e ) ; } finally { process . destroy ( ) ; } } private String getHadoopCommand ( ) { return command . getAbsolutePath ( ) ; } @ Override public void close ( ) throws IOException { } } package com . asakusafw . compiler . operator . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . operator . io . MockFooInput ; import com . asakusafw . compiler . operator . io . MockFooOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( MockFooInput . class ) @ ModelOutputLocation ( MockFooOutput . class ) public class MockFoo implements DataModel < MockFoo > , MockProjection , Writable { private final IntOption value = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockFoo other ) { this . value . copyFrom ( other . value ) ; } @ Override public int getValue ( ) { return this . value . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } @ Override public IntOption getValueOption ( ) { return this . value ; } @ Override @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockFoo other = ( MockFoo ) obj ; if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { value . readFields ( in ) ; } } package com . asakusafw . compiler . operator . model ; import com . asakusafw . compiler . operator . io . MockProjectionInput ; import com . asakusafw . compiler . operator . io . MockProjectionOutput ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( MockProjectionInput . class ) @ ModelOutputLocation ( MockProjectionOutput . class ) public interface MockProjection { int getValue ( ) ; void setValue ( int value0 ) ; IntOption getValueOption ( ) ; void setValueOption ( IntOption option ) ; } package com . asakusafw . compiler . operator . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . operator . io . MockJoinedInput ; import com . asakusafw . compiler . operator . io . MockJoinedOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; @ DataModelKind ( "" ) @ Joined ( terms = { @ Joined . Term ( source = MockHoge . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) , @ Joined . Term ( source = MockFoo . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) } ) @ ModelInputLocation ( MockJoinedInput . class ) @ ModelOutputLocation ( MockJoinedOutput . class ) public class MockJoined implements DataModel < MockJoined > , Writable { private final IntOption hogeValue = new IntOption ( ) ; private final IntOption fooValue = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . hogeValue . setNull ( ) ; this . fooValue . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockJoined other ) { this . hogeValue . copyFrom ( other . hogeValue ) ; this . fooValue . copyFrom ( other . fooValue ) ; } public int getHogeValue ( ) { return this . hogeValue . get ( ) ; } @ SuppressWarnings ( "" ) public void setHogeValue ( int value ) { this . hogeValue . modify ( value ) ; } public IntOption getHogeValueOption ( ) { return this . hogeValue ; } @ SuppressWarnings ( "" ) public void setHogeValueOption ( IntOption option ) { this . hogeValue . copyFrom ( option ) ; } public int getFooValue ( ) { return this . fooValue . get ( ) ; } @ SuppressWarnings ( "" ) public void setFooValue ( int value ) { this . fooValue . modify ( value ) ; } public IntOption getFooValueOption ( ) { return this . fooValue ; } @ SuppressWarnings ( "" ) public void setFooValueOption ( IntOption option ) { this . fooValue . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . hogeValue ) ; result . append ( "" ) ; result . append ( this . fooValue ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + hogeValue . hashCode ( ) ; result = prime * result + fooValue . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockJoined other = ( MockJoined ) obj ; if ( this . hogeValue . equals ( other . hogeValue ) == false ) { return false ; } if ( this . fooValue . equals ( other . fooValue ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { hogeValue . write ( out ) ; fooValue . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { hogeValue . readFields ( in ) ; fooValue . readFields ( in ) ; } } package com . asakusafw . compiler . operator . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . operator . io . MockKeyValue1Input ; import com . asakusafw . compiler . operator . io . MockKeyValue1Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( MockKeyValue1Input . class ) @ ModelOutputLocation ( MockKeyValue1Output . class ) public class MockKeyValue1 implements DataModel < MockKeyValue1 > , MockKey , MockProjection , Writable { private final StringOption key = new StringOption ( ) ; private final IntOption value = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . key . setNull ( ) ; this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockKeyValue1 other ) { this . key . copyFrom ( other . key ) ; this . value . copyFrom ( other . value ) ; } @ Override public Text getKey ( ) { return this . key . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setKey ( Text value0 ) { this . key . modify ( value0 ) ; } @ Override public StringOption getKeyOption ( ) { return this . key ; } @ Override @ SuppressWarnings ( "" ) public void setKeyOption ( StringOption option ) { this . key . copyFrom ( option ) ; } @ Override public int getValue ( ) { return this . value . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } @ Override public IntOption getValueOption ( ) { return this . value ; } @ Override @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + key . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockKeyValue1 other = ( MockKeyValue1 ) obj ; if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } @ Override public String getKeyAsString ( ) { return this . key . getAsString ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setKeyAsString ( String key0 ) { this . key . modify ( key0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { key . readFields ( in ) ; value . readFields ( in ) ; } } package com . asakusafw . compiler . operator . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . operator . io . MockHogeInput ; import com . asakusafw . compiler . operator . io . MockHogeOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( MockHogeInput . class ) @ ModelOutputLocation ( MockHogeOutput . class ) public class MockHoge implements DataModel < MockHoge > , MockProjection , Writable { private final IntOption value = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockHoge other ) { this . value . copyFrom ( other . value ) ; } @ Override public int getValue ( ) { return this . value . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } @ Override public IntOption getValueOption ( ) { return this . value ; } @ Override @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockHoge other = ( MockHoge ) obj ; if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { value . readFields ( in ) ; } } package com . asakusafw . compiler . operator . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . operator . io . MockKeyValue2Input ; import com . asakusafw . compiler . operator . io . MockKeyValue2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( MockKeyValue2Input . class ) @ ModelOutputLocation ( MockKeyValue2Output . class ) public class MockKeyValue2 implements DataModel < MockKeyValue2 > , MockKey , MockProjection , Writable { private final StringOption key = new StringOption ( ) ; private final IntOption value = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . key . setNull ( ) ; this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockKeyValue2 other ) { this . key . copyFrom ( other . key ) ; this . value . copyFrom ( other . value ) ; } @ Override public Text getKey ( ) { return this . key . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setKey ( Text value0 ) { this . key . modify ( value0 ) ; } @ Override public StringOption getKeyOption ( ) { return this . key ; } @ Override @ SuppressWarnings ( "" ) public void setKeyOption ( StringOption option ) { this . key . copyFrom ( option ) ; } @ Override public int getValue ( ) { return this . value . get ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } @ Override public IntOption getValueOption ( ) { return this . value ; } @ Override @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + key . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockKeyValue2 other = ( MockKeyValue2 ) obj ; if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } @ Override public String getKeyAsString ( ) { return this . key . getAsString ( ) ; } @ Override @ SuppressWarnings ( "" ) public void setKeyAsString ( String key0 ) { this . key . modify ( key0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { key . readFields ( in ) ; value . readFields ( in ) ; } } package com . asakusafw . compiler . operator . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . operator . io . MockSummarizedInput ; import com . asakusafw . compiler . operator . io . MockSummarizedOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; @ DataModelKind ( "" ) @ ModelInputLocation ( MockSummarizedInput . class ) @ ModelOutputLocation ( MockSummarizedOutput . class ) @ Summarized ( term = @ Summarized . Term ( source = MockHoge . class , foldings = { @ Summarized . Folding ( aggregator = Summarized . Aggregator . ANY , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . COUNT , source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) ) public class MockSummarized implements DataModel < MockSummarized > , Writable { private final IntOption key = new IntOption ( ) ; private final LongOption count = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . key . setNull ( ) ; this . count . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockSummarized other ) { this . key . copyFrom ( other . key ) ; this . count . copyFrom ( other . count ) ; } public int getKey ( ) { return this . key . get ( ) ; } @ SuppressWarnings ( "" ) public void setKey ( int value ) { this . key . modify ( value ) ; } public IntOption getKeyOption ( ) { return this . key ; } @ SuppressWarnings ( "" ) public void setKeyOption ( IntOption option ) { this . key . copyFrom ( option ) ; } public long getCount ( ) { return this . count . get ( ) ; } @ SuppressWarnings ( "" ) public void setCount ( long value ) { this . count . modify ( value ) ; } public LongOption getCountOption ( ) { return this . count ; } @ SuppressWarnings ( "" ) public void setCountOption ( LongOption option ) { this . count . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . count ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + key . hashCode ( ) ; result = prime * result + count . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockSummarized other = ( MockSummarized ) obj ; if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . count . equals ( other . count ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; count . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { key . readFields ( in ) ; count . readFields ( in ) ; } } package com . asakusafw . compiler . operator . model ; import org . apache . hadoop . io . Text ; import com . asakusafw . compiler . operator . io . MockKeyInput ; import com . asakusafw . compiler . operator . io . MockKeyOutput ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( MockKeyInput . class ) @ ModelOutputLocation ( MockKeyOutput . class ) public interface MockKey { Text getKey ( ) ; void setKey ( Text value ) ; StringOption getKeyOption ( ) ; void setKeyOption ( StringOption option ) ; String getKeyAsString ( ) ; void setKeyAsString ( String key0 ) ; } package com . asakusafw . compiler . operator ; import static com . asakusafw . utils . java . model . syntax . ModifierKind . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import javax . lang . model . element . PackageElement ; import org . junit . Test ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; import com . asakusafw . utils . java . model . util . Models ; public class OperatorFactoryClassGeneratorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; TypeDeclaration tree = generate ( new MockOperatorProcessor ( ) ) ; assertThat ( tree . getName ( ) . getToken ( ) , is ( "" ) ) ; assertThat ( Find . modifiers ( tree ) , hasItem ( PUBLIC ) ) ; assertThat ( Find . modifiers ( tree ) , not ( hasItem ( ABSTRACT ) ) ) ; TypeDeclaration type = Find . type ( tree , "" ) ; assertThat ( type . getModelKind ( ) , is ( ModelKind . CLASS_DECLARATION ) ) ; assertThat ( Find . modifiers ( type ) , hasItem ( PUBLIC ) ) ; FieldDeclaration field = Find . field ( type , "" ) ; assertThat ( Find . modifiers ( field ) , hasItems ( PUBLIC , FINAL ) ) ; assertThat ( field . getType ( ) . toString ( ) , is ( "" ) ) ; MethodDeclaration method = Find . method ( tree , "" ) ; assertThat ( Find . modifiers ( method ) , hasItem ( PUBLIC ) ) ; assertThat ( method . getReturnType ( ) . toString ( ) , is ( "" ) ) ; List < ? extends FormalParameterDeclaration > params = method . getFormalParameters ( ) ; assertThat ( params . size ( ) , is ( ) ) ; assertThat ( params . get ( ) . getType ( ) . toString ( ) , is ( "" ) ) ; assertThat ( params . get ( ) . getName ( ) . getToken ( ) , is ( "" ) ) ; assertThat ( params . get ( ) . getType ( ) . toString ( ) , is ( "" ) ) ; assertThat ( params . get ( ) . getName ( ) . getToken ( ) , is ( "" ) ) ; } private TypeDeclaration generate ( OperatorProcessor ... procs ) { Engine engine = new Engine ( procs ) ; start ( engine ) ; assertThat ( engine . collected , not ( nullValue ( ) ) ) ; return engine . collected ; } private static class Engine extends Callback { private OperatorProcessor [ ] procs ; TypeDeclaration collected ; Engine ( OperatorProcessor ... procs ) { this . procs = procs ; } @ Override protected final void test ( ) { OperatorClassCollector collector = new OperatorClassCollector ( env , round ) ; for ( OperatorProcessor proc : procs ) { proc . initialize ( env ) ; collector . add ( proc ) ; } List < OperatorClass > classes = collector . collect ( ) ; if ( classes . isEmpty ( ) ) { return ; } assertThat ( classes . size ( ) , is ( ) ) ; assertThat ( collected , is ( nullValue ( ) ) ) ; this . collected = collected ( classes . get ( ) ) ; } protected TypeDeclaration collected ( OperatorClass operatorClass ) { ModelFactory factory = Models . getModelFactory ( ) ; PackageElement pkg = ( PackageElement ) operatorClass . getElement ( ) . getEnclosingElement ( ) ; OperatorClassGenerator generator = new OperatorFactoryClassGenerator ( env , factory , new ImportBuilder ( factory , new Jsr269 ( factory ) . convert ( pkg ) , Strategy . TOP_LEVEL ) , operatorClass ) ; return generator . generate ( ) ; } } } package com . asakusafw . compiler . operator ; import java . util . List ; import javax . lang . model . type . TypeKind ; import javax . tools . Diagnostic ; import com . asakusafw . compiler . common . TargetOperator ; import com . asakusafw . compiler . operator . OperatorMethodDescriptor . Builder ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; @ TargetOperator ( MockOperator . class ) public class MockOperatorProcessor extends AbstractOperatorProcessor { @ Override public OperatorMethodDescriptor describe ( Context context ) { if ( context . element . getParameters ( ) . size ( ) != ) { context . environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , "" ) ; return null ; } if ( context . element . getReturnType ( ) . getKind ( ) == TypeKind . VOID ) { context . environment . getMessager ( ) . printMessage ( Diagnostic . Kind . ERROR , "" ) ; return null ; } ExecutableAnalyzer a = new ExecutableAnalyzer ( context . environment , context . element ) ; if ( a . countParameters ( ) != ) { return null ; } if ( a . getReturnType ( ) . isVoid ( ) ) { return null ; } Builder builder = new Builder ( MockOperator . class , context ) ; builder . addInput ( a . getParameterDocument ( ) , "" , a . getParameterType ( ) . getType ( ) , ) ; builder . addParameter ( a . getParameterDocument ( ) , "" , a . getParameterType ( ) . getType ( ) , ) ; builder . addOutput ( a . getReturnDocument ( ) , "" , a . getReturnType ( ) . getType ( ) , null , null ) ; return builder . toDescriptor ( ) ; } @ Override protected List < ? extends TypeBodyDeclaration > override ( Context context ) { ModelFactory factory = context . environment . getFactory ( ) ; ImplementationBuilder builder = new ImplementationBuilder ( context ) ; builder . addStatement ( new ExpressionBuilder ( factory , builder . getParameterName ( ) ) . apply ( InfixOperator . PLUS , builder . getParameterName ( ) ) . apply ( InfixOperator . PLUS , Models . toLiteral ( factory , "" ) ) . toReturnStatement ( ) ) ; return builder . toImplementation ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockKeyValue2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockKeyValue2Output implements ModelOutput < MockKeyValue2 > { private final RecordEmitter emitter ; public MockKeyValue2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockKeyValue2 model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockKey ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockKeyInput implements ModelInput < MockKey > { private final RecordParser parser ; public MockKeyInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockKey model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockProjection ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockProjectionInput implements ModelInput < MockProjection > { private final RecordParser parser ; public MockProjectionInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockProjection model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockJoined ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockJoinedOutput implements ModelOutput < MockJoined > { private final RecordEmitter emitter ; public MockJoinedOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockJoined model ) throws IOException { emitter . emit ( model . getHogeValueOption ( ) ) ; emitter . emit ( model . getFooValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockSummarized ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockSummarizedOutput implements ModelOutput < MockSummarized > { private final RecordEmitter emitter ; public MockSummarizedOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockSummarized model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getCountOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockKeyValue1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockKeyValue1Input implements ModelInput < MockKeyValue1 > { private final RecordParser parser ; public MockKeyValue1Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockKeyValue1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockFooOutput implements ModelOutput < MockFoo > { private final RecordEmitter emitter ; public MockFooOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockFoo model ) throws IOException { emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockJoined ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockJoinedInput implements ModelInput < MockJoined > { private final RecordParser parser ; public MockJoinedInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockJoined model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getHogeValueOption ( ) ) ; parser . fill ( model . getFooValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockKeyValue1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockKeyValue1Output implements ModelOutput < MockKeyValue1 > { private final RecordEmitter emitter ; public MockKeyValue1Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockKeyValue1 model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockKey ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockKeyOutput implements ModelOutput < MockKey > { private final RecordEmitter emitter ; public MockKeyOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockKey model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockFooInput implements ModelInput < MockFoo > { private final RecordParser parser ; public MockFooInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockFoo model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockHogeOutput implements ModelOutput < MockHoge > { private final RecordEmitter emitter ; public MockHogeOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockHoge model ) throws IOException { emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockHogeInput implements ModelInput < MockHoge > { private final RecordParser parser ; public MockHogeInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockHoge model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockSummarized ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockSummarizedInput implements ModelInput < MockSummarized > { private final RecordParser parser ; public MockSummarizedInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockSummarized model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getCountOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockKeyValue2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockKeyValue2Input implements ModelInput < MockKeyValue2 > { private final RecordParser parser ; public MockKeyValue2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockKeyValue2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . operator . io ; import java . io . IOException ; import com . asakusafw . compiler . operator . model . MockProjection ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockProjectionOutput implements ModelOutput < MockProjection > { private final RecordEmitter emitter ; public MockProjectionOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockProjection model ) throws IOException { emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . lang . reflect . Type ; import java . util . Arrays ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription . Declaration ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription . Parameter ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; import com . asakusafw . vocabulary . operator . Branch ; import com . asakusafw . vocabulary . operator . CoGroup ; import com . asakusafw . vocabulary . operator . Convert ; import com . asakusafw . vocabulary . operator . Fold ; import com . asakusafw . vocabulary . operator . GroupSort ; import com . asakusafw . vocabulary . operator . Logging ; import com . asakusafw . vocabulary . operator . MasterBranch ; import com . asakusafw . vocabulary . operator . MasterCheck ; import com . asakusafw . vocabulary . operator . MasterJoin ; import com . asakusafw . vocabulary . operator . MasterJoinUpdate ; import com . asakusafw . vocabulary . operator . Split ; import com . asakusafw . vocabulary . operator . Summarize ; import com . asakusafw . vocabulary . operator . Update ; public class OperatorCompilerTest extends OperatorCompilerTestRoot { @ Test public void types ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { OperatorCompiler compiler = new OperatorCompiler ( ) ; compiler . init ( env . getProcessingEnvironment ( ) ) ; Set < String > supported = compiler . getSupportedAnnotationTypes ( ) ; assertThat ( supported , hasItem ( Branch . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( CoGroup . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( Convert . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( Fold . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( GroupSort . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( Logging . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( MasterBranch . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( MasterCheck . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( MasterJoin . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( MasterJoinUpdate . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( Split . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( Summarize . class . getName ( ) ) ) ; assertThat ( supported , hasItem ( Update . class . getName ( ) ) ) ; } } ) ; } @ Test public void simple_Factory ( ) { add ( "" ) ; ClassLoader loader = start ( new MockOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < String > in = new MockIn < String > ( String . class , "" ) ; Object example = invoke ( factory , "" , in , ) ; Source < CharSequence > op = output ( CharSequence . class , example , "" ) ; MockOut < CharSequence > out = new MockOut < CharSequence > ( CharSequence . class , "" ) ; out . add ( op ) ; FlowElementOutput port = op . toOutputPort ( ) ; FlowElement element = port . getOwner ( ) ; OperatorDescription desc = ( OperatorDescription ) element . getDescription ( ) ; List < Parameter > params = desc . getParameters ( ) ; assertThat ( params . size ( ) , is ( ) ) ; assertThat ( params . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( params . get ( ) . getType ( ) , is ( ( Type ) int . class ) ) ; assertThat ( params . get ( ) . getValue ( ) , is ( ( Object ) ) ) ; Declaration decl = desc . getDeclaration ( ) ; assertThat ( decl . getAnnotationType ( ) , is ( ( Type ) MockOperator . class ) ) ; assertThat ( decl . getDeclaring ( ) . getName ( ) , is ( "" ) ) ; assertThat ( decl . getImplementing ( ) . getName ( ) , is ( "" ) ) ; assertThat ( decl . getName ( ) , is ( "" ) ) ; assertThat ( decl . getParameterTypes ( ) , is ( ( Object ) Arrays . < Object > asList ( String . class , int . class ) ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( desc . getName ( ) ) ) ; assertThat ( graph . getConnected ( desc . getName ( ) ) , isJust ( "" ) ) ; } @ Test public void simple_Impl ( ) { add ( "" ) ; ClassLoader loader = start ( new MockOperatorProcessor ( ) ) ; Object impl = create ( loader , "" ) ; Object result = invoke ( impl , "" , "" , ) ; assertThat ( result , is ( ( Object ) "" ) ) ; } } package com . asakusafw . compiler . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import com . asakusafw . vocabulary . operator . OperatorHelper ; @ OperatorHelper @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface MockHelper { } package com . asakusafw . compiler . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Collections ; import java . util . List ; import org . junit . Test ; import com . asakusafw . compiler . operator . processor . UpdateOperatorProcessor ; import com . asakusafw . utils . collections . Lists ; public class OperatorClassCollectorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; start ( new Collector ( new MockOperatorProcessor ( ) ) { @ Override protected void onCollected ( List < OperatorClass > classes ) { assertThat ( classes . size ( ) , is ( ) ) ; OperatorClass aClass = classes . get ( ) ; assertThat ( aClass . getElement ( ) . getQualifiedName ( ) . toString ( ) , is ( "" ) ) ; List < OperatorMethod > methods = aClass . getMethods ( ) ; assertThat ( methods . size ( ) , is ( ) ) ; OperatorMethod method = methods . get ( ) ; assertThat ( method . getElement ( ) . getSimpleName ( ) . toString ( ) , is ( "" ) ) ; assertThat ( method . getProcessor ( ) . getTargetAnnotationType ( ) , is ( ( Object ) MockOperator . class ) ) ; } } ) ; } @ Test public void withHelper ( ) { add ( "" ) ; start ( new Collector ( new MockOperatorProcessor ( ) ) { @ Override protected void onCollected ( List < OperatorClass > classes ) { assertThat ( classes . size ( ) , is ( ) ) ; } } ) ; } @ Test public void methodValidate_notMethod ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void methodValidate_notPublic ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void methodValidate_Static ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void methodValidate_duplicateOperator ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) , new UpdateOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_notClass ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_noSimpleConstructor ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_notPublic ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_notAbstract ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_generic ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_enclosing ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_notCovered ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_methodConflicted ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) , new UpdateOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_memberConflicted ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) , new UpdateOperatorProcessor ( ) ) ) ; } @ Test public void classValidate_withHelper ( ) { add ( "" ) ; error ( new Collector ( new MockOperatorProcessor ( ) , new MockOperatorProcessor ( ) ) ) ; } private static class Collector extends Callback { List < OperatorProcessor > processors ; Collector ( OperatorProcessor ... processors ) { this . processors = Lists . create ( ) ; Collections . addAll ( this . processors , processors ) ; } @ Override protected final void test ( ) { if ( round . getRootElements ( ) . isEmpty ( ) ) { return ; } try { OperatorClassCollector collector = new OperatorClassCollector ( env , round ) ; for ( OperatorProcessor proc : processors ) { proc . initialize ( env ) ; collector . add ( proc ) ; } List < OperatorClass > results = collector . collect ( ) ; onCollected ( results ) ; } catch ( OperatorCompilerException e ) { } } protected void onCollected ( List < OperatorClass > classes ) { return ; } } } package com . asakusafw . compiler . operator ; import java . util . Set ; import javax . annotation . processing . AbstractProcessor ; import javax . annotation . processing . RoundEnvironment ; import javax . annotation . processing . SupportedAnnotationTypes ; import javax . annotation . processing . SupportedSourceVersion ; import javax . lang . model . SourceVersion ; import javax . lang . model . element . TypeElement ; @ SupportedAnnotationTypes ( { "" } ) @ SupportedSourceVersion ( SourceVersion . RELEASE_6 ) public class DelegateProcessor extends AbstractProcessor { private Callback callback ; public DelegateProcessor ( Callback callback ) { this . callback = callback ; } @ Override public boolean process ( Set < ? extends TypeElement > annotations , RoundEnvironment env ) { callback . run ( processingEnv , env ) ; return true ; } } package com . asakusafw . compiler . operator ; import java . util . EnumSet ; import java . util . Set ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Modifier ; import com . asakusafw . utils . java . model . syntax . ModifierKind ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . VariableDeclarator ; public class Find { public static Set < ModifierKind > modifiers ( TypeBodyDeclaration decl ) { Set < ModifierKind > results = EnumSet . noneOf ( ModifierKind . class ) ; for ( Attribute attribute : decl . getModifiers ( ) ) { if ( attribute . getModelKind ( ) != ModelKind . MODIFIER ) { continue ; } Modifier modifier = ( Modifier ) attribute ; results . add ( modifier . getModifierKind ( ) ) ; } return results ; } public static MethodDeclaration method ( TypeDeclaration type , String name ) { for ( TypeBodyDeclaration member : type . getBodyDeclarations ( ) ) { if ( member . getModelKind ( ) != ModelKind . METHOD_DECLARATION ) { continue ; } MethodDeclaration method = ( MethodDeclaration ) member ; if ( method . getName ( ) . getToken ( ) . equals ( name ) ) { return method ; } } return null ; } public static FieldDeclaration field ( TypeDeclaration type , String name ) { for ( TypeBodyDeclaration member : type . getBodyDeclarations ( ) ) { if ( member . getModelKind ( ) != ModelKind . FIELD_DECLARATION ) { continue ; } FieldDeclaration field = ( FieldDeclaration ) member ; for ( VariableDeclarator var : field . getVariableDeclarators ( ) ) { if ( var . getName ( ) . getToken ( ) . equals ( name ) ) { return field ; } } } return null ; } public static ConstructorDeclaration constructor ( TypeDeclaration type ) { for ( TypeBodyDeclaration member : type . getBodyDeclarations ( ) ) { if ( member . getModelKind ( ) != ModelKind . CONSTRUCTOR_DECLARATION ) { continue ; } return ( ConstructorDeclaration ) member ; } return null ; } public static TypeDeclaration type ( TypeDeclaration type , String name ) { for ( TypeBodyDeclaration member : type . getBodyDeclarations ( ) ) { if ( ( member instanceof TypeDeclaration ) == false ) { continue ; } TypeDeclaration inner = ( TypeDeclaration ) member ; if ( inner . getName ( ) . getToken ( ) . equals ( name ) ) { return inner ; } } return null ; } } package com . asakusafw . compiler . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . lang . reflect . Field ; import java . lang . reflect . Method ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . LinkedList ; import java . util . List ; import java . util . Set ; import javax . annotation . processing . Processor ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . hamcrest . Matcher ; import org . hamcrest . Matchers ; import org . junit . After ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . utils . java . jsr199 . testing . SafeProcessor ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowIn ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; import com . asakusafw . vocabulary . flow . testing . MockIn ; public class OperatorCompilerTestRoot { ModelFactory f = Models . getModelFactory ( ) ; private final VolatileCompiler compiler = new VolatileCompiler ( ) ; private final List < JavaFileObject > sources = Lists . create ( ) ; protected boolean dump = true ; @ After public void tearDown ( ) throws Exception { compiler . close ( ) ; } protected Object create ( ClassLoader loader , String name ) { try { Class < ? > loaded = loader . loadClass ( name ) ; return loaded . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected Object invoke ( Object object , String name , Object ... arguments ) { try { for ( Method method : object . getClass ( ) . getMethods ( ) ) { if ( method . getName ( ) . equals ( name ) ) { return method . invoke ( object , arguments ) ; } } } catch ( Exception e ) { throw new AssertionError ( e ) ; } throw new AssertionError ( name ) ; } protected Object access ( Object object , String name ) { try { for ( Field field : object . getClass ( ) . getFields ( ) ) { if ( field . getName ( ) . equals ( name ) ) { return field . get ( object ) ; } } } catch ( Exception e ) { throw new AssertionError ( e ) ; } throw new AssertionError ( name ) ; } @ SuppressWarnings ( "" ) protected < T > Source < T > output ( Class < T > dataType , Object object , String name ) { try { for ( Field field : object . getClass ( ) . getFields ( ) ) { if ( field . getName ( ) . equals ( name ) ) { return ( Source < T > ) field . get ( object ) ; } } } catch ( Exception e ) { throw new AssertionError ( e ) ; } throw new AssertionError ( name ) ; } protected Matcher < ? super Set < String > > isJust ( String ... names ) { return Matchers . < Set < String > > is ( Sets . from ( names ) ) ; } protected Graph < String > toGraph ( MockIn < ? > ... inputs ) { FlowElement [ ] elements = new FlowElement [ inputs . length ] ; for ( int i = ; i < inputs . length ; i ++ ) { elements [ i ] = inputs [ i ] . toElement ( ) ; } return toGraph ( elements ) ; } protected Graph < String > toGraph ( List < FlowIn < ? > > inputs ) { FlowElement [ ] elements = new FlowElement [ inputs . size ( ) ] ; for ( int i = , n = inputs . size ( ) ; i < n ; i ++ ) { elements [ i ] = inputs . get ( i ) . getFlowElement ( ) ; } return toGraph ( elements ) ; } protected Graph < String > toGraph ( FlowElement ... startingElements ) { Set < String > saw = Sets . create ( ) ; LinkedList < FlowElement > work = new LinkedList < FlowElement > ( ) ; for ( FlowElement elem : startingElements ) { work . add ( elem ) ; } Graph < String > graph = Graphs . newInstance ( ) ; while ( work . isEmpty ( ) == false ) { FlowElement elem = work . removeFirst ( ) ; String self = elem . getDescription ( ) . getName ( ) ; if ( saw . contains ( self ) ) { continue ; } saw . add ( self ) ; for ( FlowElementInput input : elem . getInputPorts ( ) ) { for ( PortConnection conn : input . getConnected ( ) ) { work . add ( conn . getUpstream ( ) . getOwner ( ) ) ; } } for ( FlowElementOutput output : elem . getOutputPorts ( ) ) { for ( PortConnection conn : output . getConnected ( ) ) { FlowElement opposite = conn . getDownstream ( ) . getOwner ( ) ; work . add ( opposite ) ; String dest = opposite . getDescription ( ) . getName ( ) ; graph . addEdge ( self , dest ) ; } } } return graph ; } protected void add ( String name ) { Class < ? > aClass = getClass ( ) ; String file = MessageFormat . format ( "" , aClass . getSimpleName ( ) , name . replace ( '' , '' ) ) ; StringBuilder buf = new StringBuilder ( ) ; InputStream in = aClass . getResourceAsStream ( file ) ; assertThat ( file , in , not ( nullValue ( ) ) ) ; try { Reader reader = new BufferedReader ( new InputStreamReader ( in , "" ) ) ; while ( true ) { int c = reader . read ( ) ; if ( c == - ) { break ; } buf . append ( ( char ) c ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } finally { try { in . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } sources . add ( new VolatileJavaFile ( name . replace ( '' , '' ) , buf . toString ( ) ) ) ; } protected ClassLoader start ( Processor processor ) { SafeProcessor safe = new SafeProcessor ( processor ) ; compiler . addProcessor ( safe ) ; ClassLoader loader = start ( ) ; safe . rethrow ( ) ; return loader ; } protected ClassLoader start ( Callback callback ) { compiler . addProcessor ( new DelegateProcessor ( callback ) ) ; ClassLoader loader = start ( ) ; callback . rethrow ( ) ; return loader ; } protected ClassLoader start ( final OperatorProcessor ... procs ) { return start ( new OperatorCompiler ( ) { @ Override protected Iterable < OperatorProcessor > findOperatorProcessors ( OperatorCompilingEnvironment env ) { return Arrays . asList ( procs ) ; } } ) ; } protected void error ( final OperatorProcessor ... procs ) { SafeProcessor proc = new SafeProcessor ( new OperatorCompiler ( ) { @ Override protected Iterable < OperatorProcessor > findOperatorProcessors ( OperatorCompilingEnvironment env ) { return Arrays . asList ( procs ) ; } } ) ; compiler . addProcessor ( proc ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = doCompile ( ) ; proc . rethrow ( ) ; assertThat ( diagnostics . isEmpty ( ) , is ( false ) ) ; } protected void error ( Callback callback ) { compiler . addProcessor ( new DelegateProcessor ( callback ) ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = doCompile ( ) ; callback . rethrow ( ) ; assertThat ( diagnostics . isEmpty ( ) , is ( false ) ) ; } private ClassLoader start ( ) { List < Diagnostic < ? extends JavaFileObject > > diagnostics = doCompile ( ) ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) != Diagnostic . Kind . NOTE ) { throw new AssertionError ( diagnostics ) ; } } return compiler . getClassLoader ( ) ; } private List < Diagnostic < ? extends JavaFileObject > > doCompile ( ) { if ( dump ) { for ( JavaFileObject java : sources ) { try { System . out . println ( "" + java . getName ( ) ) ; System . out . println ( java . getCharContent ( true ) ) ; } catch ( IOException e ) { } } } compiler . addArguments ( "" ) ; for ( JavaFileObject java : sources ) { compiler . addSource ( java ) ; } if ( sources . isEmpty ( ) ) { compiler . addSource ( new VolatileJavaFile ( "" , "" ) ) ; } List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; for ( JavaFileObject java : compiler . getSources ( ) ) { try { System . out . println ( "" + java . getName ( ) ) ; System . out . println ( java . getCharContent ( true ) ) ; } catch ( IOException e ) { } } if ( dump ) { for ( Diagnostic < ? extends JavaFileObject > d : diagnostics ) { System . out . println ( "" ) ; System . out . println ( d ) ; } } return diagnostics ; } } package com . asakusafw . compiler . operator ; import static com . asakusafw . utils . java . model . syntax . ModifierKind . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . List ; import javax . lang . model . element . PackageElement ; import org . junit . Test ; import com . asakusafw . utils . java . jsr269 . bridge . Jsr269 ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; import com . asakusafw . utils . java . model . util . Models ; public class OperatorImplementationClassGeneratorTest extends OperatorCompilerTestRoot { @ Test public void concrete ( ) { add ( "" ) ; ClassDeclaration tree = generate ( new MockOperatorProcessor ( ) ) ; assertThat ( Find . modifiers ( tree ) , hasItem ( PUBLIC ) ) ; assertThat ( Find . modifiers ( tree ) , not ( hasItem ( ABSTRACT ) ) ) ; assertThat ( tree . getName ( ) . getToken ( ) , is ( "" ) ) ; assertThat ( tree . getSuperClass ( ) . toString ( ) , is ( "" ) ) ; assertThat ( Find . method ( tree , "" ) , is ( nullValue ( ) ) ) ; } @ Test public void skeleton ( ) { add ( "" ) ; ClassDeclaration tree = generate ( new MockOperatorProcessor ( ) ) ; assertThat ( Find . modifiers ( tree ) , hasItem ( PUBLIC ) ) ; assertThat ( Find . modifiers ( tree ) , not ( hasItem ( ABSTRACT ) ) ) ; assertThat ( tree . getName ( ) . getToken ( ) , is ( "" ) ) ; assertThat ( tree . getSuperClass ( ) . toString ( ) , is ( "" ) ) ; MethodDeclaration method = Find . method ( tree , "" ) ; assertThat ( method , not ( nullValue ( ) ) ) ; assertThat ( Find . modifiers ( method ) , hasItem ( PUBLIC ) ) ; assertThat ( Find . modifiers ( method ) , not ( hasItems ( ABSTRACT , STATIC ) ) ) ; assertThat ( method . getReturnType ( ) . toString ( ) , is ( "" ) ) ; List < ? extends FormalParameterDeclaration > params = method . getFormalParameters ( ) ; assertThat ( params . size ( ) , is ( ) ) ; assertThat ( params . get ( ) . getType ( ) . toString ( ) , is ( "" ) ) ; assertThat ( params . get ( ) . getName ( ) . toString ( ) , is ( "" ) ) ; assertThat ( params . get ( ) . getType ( ) . toString ( ) , is ( "" ) ) ; assertThat ( params . get ( ) . getName ( ) . toString ( ) , is ( "" ) ) ; } private ClassDeclaration generate ( OperatorProcessor ... procs ) { Engine engine = new Engine ( procs ) ; start ( engine ) ; assertThat ( engine . collected , not ( nullValue ( ) ) ) ; return ( ClassDeclaration ) engine . collected ; } private static class Engine extends Callback { private OperatorProcessor [ ] procs ; TypeDeclaration collected ; Engine ( OperatorProcessor ... procs ) { this . procs = procs ; } @ Override protected final void test ( ) { OperatorClassCollector collector = new OperatorClassCollector ( env , round ) ; for ( OperatorProcessor proc : procs ) { proc . initialize ( env ) ; collector . add ( proc ) ; } List < OperatorClass > classes = collector . collect ( ) ; if ( classes . isEmpty ( ) ) { return ; } assertThat ( classes . size ( ) , is ( ) ) ; assertThat ( collected , is ( nullValue ( ) ) ) ; this . collected = collected ( classes . get ( ) ) ; } protected TypeDeclaration collected ( OperatorClass operatorClass ) { ModelFactory factory = Models . getModelFactory ( ) ; PackageElement pkg = ( PackageElement ) operatorClass . getElement ( ) . getEnclosingElement ( ) ; OperatorClassGenerator generator = new OperatorImplementationClassGenerator ( env , factory , new ImportBuilder ( factory , new Jsr269 ( factory ) . convert ( pkg ) , Strategy . TOP_LEVEL ) , operatorClass ) ; return generator . generate ( ) ; } } } package com . asakusafw . compiler . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . lang . reflect . Type ; import java . util . Arrays ; import java . util . List ; import org . junit . Test ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription . Declaration ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription . Parameter ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class OperatorClassEmitterTest extends OperatorCompilerTestRoot { @ Test public void emitFactory ( ) { add ( "" ) ; ClassLoader loader = compile ( new MockOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < String > in = new MockIn < String > ( String . class , "" ) ; Object example = invoke ( factory , "" , in , ) ; @ SuppressWarnings ( "" ) Source < CharSequence > op = ( Source < CharSequence > ) access ( example , "" ) ; MockOut < CharSequence > out = new MockOut < CharSequence > ( CharSequence . class , "" ) ; out . add ( op ) ; FlowElementOutput port = op . toOutputPort ( ) ; FlowElement element = port . getOwner ( ) ; OperatorDescription desc = ( OperatorDescription ) element . getDescription ( ) ; List < Parameter > params = desc . getParameters ( ) ; assertThat ( params . size ( ) , is ( ) ) ; assertThat ( params . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( params . get ( ) . getType ( ) , is ( ( Type ) int . class ) ) ; assertThat ( params . get ( ) . getValue ( ) , is ( ( Object ) ) ) ; Declaration decl = desc . getDeclaration ( ) ; assertThat ( decl . getAnnotationType ( ) , is ( ( Type ) MockOperator . class ) ) ; assertThat ( decl . getDeclaring ( ) . getName ( ) , is ( "" ) ) ; assertThat ( decl . getImplementing ( ) . getName ( ) , is ( "" ) ) ; assertThat ( decl . getName ( ) , is ( "" ) ) ; assertThat ( decl . getParameterTypes ( ) , is ( ( Object ) Arrays . < Object > asList ( String . class , int . class ) ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( desc . getName ( ) ) ) ; assertThat ( graph . getConnected ( desc . getName ( ) ) , isJust ( "" ) ) ; } @ Test public void emitFactory_annotationNameConflict ( ) { add ( "" ) ; compile ( new MockOperatorProcessor ( ) ) ; } @ Test public void emitConcreteImpl ( ) { add ( "" ) ; ClassLoader loader = compile ( new MockOperatorProcessor ( ) ) ; Object impl = create ( loader , "" ) ; Object result = invoke ( impl , "" , "" , ) ; assertThat ( result , is ( ( Object ) "" ) ) ; } @ Test public void emitAbstractImpl ( ) { add ( "" ) ; ClassLoader loader = compile ( new MockOperatorProcessor ( ) ) ; Object impl = create ( loader , "" ) ; Object result = invoke ( impl , "" , "" , ) ; assertThat ( result , is ( ( Object ) "" ) ) ; } private ClassLoader compile ( final OperatorProcessor ... procs ) { return start ( new Callback ( ) { @ Override protected void test ( ) { OperatorClassCollector collector = new OperatorClassCollector ( env , round ) ; for ( OperatorProcessor proc : procs ) { proc . initialize ( env ) ; collector . add ( proc ) ; } List < OperatorClass > classes = collector . collect ( ) ; OperatorClassEmitter emitter = new OperatorClassEmitter ( env ) ; for ( OperatorClass aClass : classes ) { emitter . emit ( aClass ) ; } } } ) ; } } package com . asakusafw . compiler . operator . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class FlowOperatorCompilerTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) throws Exception { add ( "" ) ; ClassLoader loader = start ( new FlowOperatorCompiler ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object operator = invoke ( factory , "" , in ) ; Source < MockHoge > flowOut = output ( MockHoge . class , operator , "" ) ; out . add ( flowOut ) ; FlowPartDescription desc = ( FlowPartDescription ) flowOut . toOutputPort ( ) . getOwner ( ) . getDescription ( ) ; assertThat ( desc . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( desc . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; FlowGraph flow = desc . getFlowGraph ( ) ; assertThat ( flow . getDescription ( ) , is ( ( Object ) loader . loadClass ( "" ) ) ) ; assertThat ( flow . getFlowInputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( flow . getFlowOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; Graph < String > inner = toGraph ( flow . getFlowInputs ( ) ) ; assertThat ( inner . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void generics ( ) throws Exception { add ( "" ) ; ClassLoader loader = start ( new FlowOperatorCompiler ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object operator = invoke ( factory , "" , in ) ; Source < MockHoge > flowOut = output ( MockHoge . class , operator , "" ) ; out . add ( flowOut ) ; FlowPartDescription desc = ( FlowPartDescription ) flowOut . toOutputPort ( ) . getOwner ( ) . getDescription ( ) ; assertThat ( desc . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( desc . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; FlowGraph flow = desc . getFlowGraph ( ) ; assertThat ( flow . getDescription ( ) , is ( ( Object ) loader . loadClass ( "" ) ) ) ; assertThat ( flow . getFlowInputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( flow . getFlowOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; Graph < String > inner = toGraph ( flow . getFlowInputs ( ) ) ; assertThat ( inner . getConnected ( "" ) , isJust ( "" ) ) ; } } package com . asakusafw . compiler . operator . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Collection ; import java . util . List ; import javax . lang . model . element . Element ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . TypeKind ; import javax . lang . model . type . TypeMirror ; import org . junit . Test ; import com . asakusafw . compiler . operator . Callback ; import com . asakusafw . compiler . operator . OperatorCompilerException ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . OperatorCompilingEnvironment ; import com . asakusafw . compiler . operator . OperatorPortDeclaration ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . vocabulary . flow . FlowPart ; public class FlowPartClassCollectorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; start ( new Collector ( ) { @ Override protected void onCollected ( List < FlowPartClass > results ) { assertThat ( results . isEmpty ( ) , is ( false ) ) ; FlowPartClass aClass = results . get ( ) ; assertThat ( aClass . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( aClass . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( aClass . getParameters ( ) . size ( ) , is ( ) ) ; OperatorPortDeclaration in = find ( "" , aClass . getInputPorts ( ) ) ; OperatorPortDeclaration out = find ( "" , aClass . getOutputPorts ( ) ) ; assertTypeEquals ( env , in . getType ( ) . getRepresentation ( ) , MockHoge . class ) ; assertThat ( in . getParameterPosition ( ) , is ( ) ) ; assertTypeEquals ( env , out . getType ( ) . getRepresentation ( ) , MockHoge . class ) ; assertThat ( out . getParameterPosition ( ) , is ( ) ) ; } } ) ; } @ Test public void parameterized ( ) { add ( "" ) ; start ( new Collector ( ) { @ Override protected void onCollected ( List < FlowPartClass > results ) { assertThat ( results . isEmpty ( ) , is ( false ) ) ; FlowPartClass aClass = results . get ( ) ; assertThat ( aClass . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( aClass . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( aClass . getParameters ( ) . size ( ) , is ( ) ) ; OperatorPortDeclaration in1 = find ( "" , aClass . getInputPorts ( ) ) ; OperatorPortDeclaration in2 = find ( "" , aClass . getInputPorts ( ) ) ; OperatorPortDeclaration out1 = find ( "" , aClass . getOutputPorts ( ) ) ; OperatorPortDeclaration out2 = find ( "" , aClass . getOutputPorts ( ) ) ; OperatorPortDeclaration param1 = find ( "" , aClass . getParameters ( ) ) ; OperatorPortDeclaration param2 = find ( "" , aClass . getParameters ( ) ) ; assertTypeEquals ( env , in1 . getType ( ) . getRepresentation ( ) , MockHoge . class ) ; assertThat ( in1 . getParameterPosition ( ) , is ( ) ) ; assertTypeEquals ( env , out1 . getType ( ) . getRepresentation ( ) , MockHoge . class ) ; assertThat ( out1 . getParameterPosition ( ) , is ( ) ) ; assertThat ( param1 . getType ( ) . getRepresentation ( ) . getKind ( ) , is ( TypeKind . INT ) ) ; assertThat ( param1 . getParameterPosition ( ) , is ( ) ) ; assertTypeEquals ( env , in2 . getType ( ) . getRepresentation ( ) , MockFoo . class ) ; assertThat ( in2 . getParameterPosition ( ) , is ( ) ) ; assertTypeEquals ( env , out2 . getType ( ) . getRepresentation ( ) , MockFoo . class ) ; assertThat ( out2 . getParameterPosition ( ) , is ( ) ) ; assertTypeEquals ( env , param2 . getType ( ) . getRepresentation ( ) , String . class ) ; assertThat ( param2 . getParameterPosition ( ) , is ( ) ) ; } } ) ; } @ Test public void generics ( ) { add ( "" ) ; start ( new Collector ( ) { @ Override protected void onCollected ( List < FlowPartClass > results ) { assertThat ( results . isEmpty ( ) , is ( false ) ) ; FlowPartClass aClass = results . get ( ) ; assertThat ( aClass . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( aClass . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( aClass . getParameters ( ) . size ( ) , is ( ) ) ; OperatorPortDeclaration in = find ( "" , aClass . getInputPorts ( ) ) ; OperatorPortDeclaration out = find ( "" , aClass . getOutputPorts ( ) ) ; assertThat ( "" , env . getTypeUtils ( ) . isSameType ( in . getType ( ) . getRepresentation ( ) , out . getType ( ) . getRepresentation ( ) ) , is ( true ) ) ; assertThat ( "" , in . getType ( ) . getRepresentation ( ) . getKind ( ) , is ( TypeKind . TYPEVAR ) ) ; assertThat ( in . getParameterPosition ( ) , is ( ) ) ; assertThat ( out . getParameterPosition ( ) , is ( ) ) ; } } ) ; } @ Test public void genericWithClass ( ) { add ( "" ) ; start ( new Collector ( ) { @ Override protected void onCollected ( List < FlowPartClass > results ) { assertThat ( results . isEmpty ( ) , is ( false ) ) ; FlowPartClass aClass = results . get ( ) ; assertThat ( aClass . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( aClass . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( aClass . getParameters ( ) . size ( ) , is ( ) ) ; OperatorPortDeclaration in = find ( "" , aClass . getInputPorts ( ) ) ; OperatorPortDeclaration out = find ( "" , aClass . getOutputPorts ( ) ) ; OperatorPortDeclaration param = aClass . getParameters ( ) . get ( ) ; assertThat ( "" , env . getTypeUtils ( ) . isSameType ( env . getErasure ( param . getType ( ) . getRepresentation ( ) ) , env . getDeclaredType ( Class . class ) ) , is ( true ) ) ; assertThat ( "" , env . getTypeUtils ( ) . isSameType ( out . getType ( ) . getRepresentation ( ) , ( ( DeclaredType ) param . getType ( ) . getRepresentation ( ) ) . getTypeArguments ( ) . get ( ) ) , is ( true ) ) ; assertThat ( "" , in . getType ( ) . getRepresentation ( ) . getKind ( ) , is ( TypeKind . TYPEVAR ) ) ; assertThat ( in . getParameterPosition ( ) , is ( ) ) ; assertThat ( out . getParameterPosition ( ) , is ( ) ) ; assertThat ( param . getParameterPosition ( ) , is ( ) ) ; } } ) ; } @ Test public void Abstract ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void Enclosing ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void NoPublicCtors ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void NotInherited ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void NotPublic ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void ThrownCtor ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void TooManyCtors ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void TypeParametersCtor ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void NoIoCtor ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } @ Test public void UnboundGenerics ( ) { add ( "" ) ; error ( new Collector ( ) ) ; } void assertTypeEquals ( OperatorCompilingEnvironment env , TypeMirror type , Class < ? > expected ) { TypeElement elem = env . getElementUtils ( ) . getTypeElement ( expected . getName ( ) ) ; TypeMirror exType = env . getTypeUtils ( ) . getDeclaredType ( elem ) ; assertTrue ( env . getTypeUtils ( ) . isSameType ( type , exType ) ) ; } OperatorPortDeclaration find ( String name , Collection < OperatorPortDeclaration > ports ) { for ( OperatorPortDeclaration port : ports ) { if ( port . getName ( ) . equals ( name ) ) { return port ; } } throw new AssertionError ( name ) ; } private static class Collector extends Callback { Collector ( ) { return ; } @ Override protected final void test ( ) { if ( round . getRootElements ( ) . isEmpty ( ) ) { return ; } try { FlowPartClassCollector collector = new FlowPartClassCollector ( env ) ; for ( Element elem : round . getElementsAnnotatedWith ( FlowPart . class ) ) { collector . add ( elem ) ; } List < FlowPartClass > results = collector . collect ( ) ; onCollected ( results ) ; } catch ( OperatorCompilerException e ) { } } protected void onCollected ( List < FlowPartClass > results ) { return ; } } } package com . asakusafw . compiler . operator . flow ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . lang . reflect . Field ; import java . util . List ; import java . util . Set ; import javax . lang . model . element . Element ; import org . junit . Test ; import com . asakusafw . compiler . operator . Callback ; import com . asakusafw . compiler . operator . OperatorCompilerException ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . FlowPart ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; import com . asakusafw . vocabulary . flow . graph . FlowPartDescription ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; public class FlowClassEmitterTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) throws Exception { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new Collector ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object operator = invoke ( factory , "" , in ) ; assertStored ( loader , "" ) ; Source < MockHoge > flowOut = output ( MockHoge . class , operator , "" ) ; out . add ( flowOut ) ; FlowPartDescription desc = ( FlowPartDescription ) flowOut . toOutputPort ( ) . getOwner ( ) . getDescription ( ) ; assertThat ( desc . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( desc . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; FlowGraph flow = desc . getFlowGraph ( ) ; assertThat ( flow . getDescription ( ) , is ( ( Object ) loader . loadClass ( "" ) ) ) ; assertThat ( flow . getFlowInputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( flow . getFlowOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; Graph < String > inner = toGraph ( flow . getFlowInputs ( ) ) ; assertThat ( inner . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void parameterized ( ) throws Exception { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new Collector ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockHoge > c = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockFoo > d = MockOut . of ( MockFoo . class , "" ) ; Object operator = invoke ( factory , "" , a , b , , "" ) ; assertStored ( loader , "" ) ; Source < MockHoge > flowC = output ( MockHoge . class , operator , "" ) ; Source < MockFoo > flowD = output ( MockFoo . class , operator , "" ) ; c . add ( flowC ) ; d . add ( flowD ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void generics ( ) throws Exception { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new Collector ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object operator = invoke ( factory , "" , in ) ; assertStored ( loader , "" ) ; Source < MockHoge > flowOut = output ( MockHoge . class , operator , "" ) ; out . add ( flowOut ) ; FlowPartDescription desc = ( FlowPartDescription ) flowOut . toOutputPort ( ) . getOwner ( ) . getDescription ( ) ; assertThat ( desc . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( desc . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; FlowGraph flow = desc . getFlowGraph ( ) ; assertThat ( flow . getDescription ( ) , is ( ( Object ) loader . loadClass ( "" ) ) ) ; assertThat ( flow . getFlowInputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( flow . getFlowOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; Graph < String > inner = toGraph ( flow . getFlowInputs ( ) ) ; assertThat ( inner . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void genericWithClass ( ) throws Exception { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new Collector ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockFoo > out = MockOut . of ( MockFoo . class , "" ) ; Object operator = invoke ( factory , "" , in , MockFoo . class ) ; assertStored ( loader , "" ) ; Source < MockFoo > flowOut = output ( MockFoo . class , operator , "" ) ; out . add ( flowOut ) ; FlowPartDescription desc = ( FlowPartDescription ) flowOut . toOutputPort ( ) . getOwner ( ) . getDescription ( ) ; assertThat ( desc . getInputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getInputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( desc . getOutputPorts ( ) . size ( ) , is ( ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getName ( ) , is ( "" ) ) ; assertThat ( desc . getOutputPorts ( ) . get ( ) . getDataType ( ) , is ( ( Object ) MockFoo . class ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; FlowGraph flow = desc . getFlowGraph ( ) ; assertThat ( flow . getDescription ( ) , is ( ( Object ) loader . loadClass ( "" ) ) ) ; assertThat ( flow . getFlowInputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowInputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockHoge . class ) ) ; assertThat ( flow . getFlowOutputs ( ) . size ( ) , is ( ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getName ( ) , is ( "" ) ) ; assertThat ( flow . getFlowOutputs ( ) . get ( ) . getDescription ( ) . getDataType ( ) , is ( ( Object ) MockFoo . class ) ) ; Graph < String > inner = toGraph ( flow . getFlowInputs ( ) ) ; assertThat ( inner . getConnected ( "" ) , isJust ( CoreOperatorFactory . PROJECT_NAME ) ) ; assertThat ( inner . getConnected ( CoreOperatorFactory . PROJECT_NAME ) , isJust ( "" ) ) ; } private static void assertStored ( ClassLoader loader , Object expected ) { try { Class < ? > store = loader . loadClass ( "" ) ; Field field = store . getDeclaredField ( "" ) ; Object result = field . get ( null ) ; assertThat ( result , is ( expected ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private static class Collector extends Callback { Collector ( ) { return ; } @ Override protected final void test ( ) { try { FlowPartClassCollector collector = new FlowPartClassCollector ( env ) ; Set < ? extends Element > annotated = round . getElementsAnnotatedWith ( FlowPart . class ) ; if ( annotated . isEmpty ( ) ) { return ; } for ( Element elem : annotated ) { collector . add ( elem ) ; } List < FlowPartClass > results = collector . collect ( ) ; assertThat ( results . size ( ) , is ( ) ) ; FlowClassEmitter emitter = new FlowClassEmitter ( env ) ; emitter . emit ( results . get ( ) ) ; } catch ( OperatorCompilerException e ) { } } } } package com . asakusafw . compiler . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface MockOperator { } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . compiler . operator . model . MockKeyValue1 ; import com . asakusafw . compiler . operator . model . MockKeyValue2 ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class MasterBranchOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new MasterBranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > unknown = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > high = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > middle = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > low = MockOut . of ( MockFoo . class , "" ) ; Object masterBranch = invoke ( factory , "" , a , b ) ; unknown . add ( output ( MockFoo . class , masterBranch , "" ) ) ; high . add ( output ( MockFoo . class , masterBranch , "" ) ) ; middle . add ( output ( MockFoo . class , masterBranch , "" ) ) ; low . add ( output ( MockFoo . class , masterBranch , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" , "" ) ) ; } @ Test public void selector ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new MasterBranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > unknown = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > high = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > middle = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > low = MockOut . of ( MockFoo . class , "" ) ; Object masterBranch = invoke ( factory , "" , a , b ) ; unknown . add ( output ( MockFoo . class , masterBranch , "" ) ) ; high . add ( output ( MockFoo . class , masterBranch , "" ) ) ; middle . add ( output ( MockFoo . class , masterBranch , "" ) ) ; low . add ( output ( MockFoo . class , masterBranch , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" , "" ) ) ; } @ Test public void parameterized ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new MasterBranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > unknown = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > high = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > middle = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > low = MockOut . of ( MockFoo . class , "" ) ; Object masterBranch = invoke ( factory , "" , a , b , ) ; unknown . add ( output ( MockFoo . class , masterBranch , "" ) ) ; high . add ( output ( MockFoo . class , masterBranch , "" ) ) ; middle . add ( output ( MockFoo . class , masterBranch , "" ) ) ; low . add ( output ( MockFoo . class , masterBranch , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" , "" ) ) ; } @ Test public void parameterizedSelector1 ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new MasterBranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > unknown = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > high = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > middle = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > low = MockOut . of ( MockFoo . class , "" ) ; Object masterBranch = invoke ( factory , "" , a , b , ) ; unknown . add ( output ( MockFoo . class , masterBranch , "" ) ) ; high . add ( output ( MockFoo . class , masterBranch , "" ) ) ; middle . add ( output ( MockFoo . class , masterBranch , "" ) ) ; low . add ( output ( MockFoo . class , masterBranch , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" , "" ) ) ; } @ Test public void parameterizedSelector2 ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new MasterBranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > unknown = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > high = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > middle = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > low = MockOut . of ( MockFoo . class , "" ) ; Object masterBranch = invoke ( factory , "" , a , b , ) ; unknown . add ( output ( MockFoo . class , masterBranch , "" ) ) ; high . add ( output ( MockFoo . class , masterBranch , "" ) ) ; middle . add ( output ( MockFoo . class , masterBranch , "" ) ) ; low . add ( output ( MockFoo . class , masterBranch , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" , "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new MasterBranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockKeyValue1 > a = MockIn . of ( MockKeyValue1 . class , "" ) ; MockIn < MockKeyValue2 > b = MockIn . of ( MockKeyValue2 . class , "" ) ; MockOut < MockKeyValue2 > unknown = MockOut . of ( MockKeyValue2 . class , "" ) ; MockOut < MockKeyValue2 > high = MockOut . of ( MockKeyValue2 . class , "" ) ; MockOut < MockKeyValue2 > middle = MockOut . of ( MockKeyValue2 . class , "" ) ; MockOut < MockKeyValue2 > low = MockOut . of ( MockKeyValue2 . class , "" ) ; Object masterBranch = invoke ( factory , "" , a , b ) ; unknown . add ( output ( MockKeyValue2 . class , masterBranch , "" ) ) ; high . add ( output ( MockKeyValue2 . class , masterBranch , "" ) ) ; middle . add ( output ( MockKeyValue2 . class , masterBranch , "" ) ) ; low . add ( output ( MockKeyValue2 . class , masterBranch , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" , "" ) ) ; } @ Test public void Abstract ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void Empty ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void NotEnum ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void NotUserParameter ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void NoKey ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void SelectorWithTooMatchParameters ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void SelectorWithInvalidMaster ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void SelectorWithInvalidTx ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void SelectorWithInvalidReturn ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void SelectorWithoutMethod ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } @ Test public void SelectorWithoutAnnotated ( ) { add ( "" ) ; add ( "" ) ; add ( "" ) ; error ( new MasterBranchOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class MasterJoinUpdateOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinUpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > updated = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoinUpdate = invoke ( factory , "" , a , b ) ; updated . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void selector ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinUpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > updated = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoinUpdate = invoke ( factory , "" , a , b ) ; updated . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void parameterized ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinUpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > updated = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoinUpdate = invoke ( factory , "" , a , b , ) ; updated . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void parameterizedSelector ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinUpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > updated = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoinUpdate = invoke ( factory , "" , a , b , ) ; updated . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinUpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > updated = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoinUpdate = invoke ( factory , "" , a , b ) ; updated . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void genericSelector ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinUpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > updated = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoinUpdate = invoke ( factory , "" , a , b ) ; updated . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void genericSelector_plainOperator ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinUpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > updated = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoinUpdate = invoke ( factory , "" , a , b ) ; updated . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoinUpdate , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void Abstract ( ) { add ( "" ) ; error ( new MasterJoinUpdateOperatorProcessor ( ) ) ; } @ Test public void Returns ( ) { add ( "" ) ; error ( new MasterJoinUpdateOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new MasterJoinUpdateOperatorProcessor ( ) ) ; } @ Test public void NotUserParameter ( ) { add ( "" ) ; error ( new MasterJoinUpdateOperatorProcessor ( ) ) ; } @ Test public void NoKey ( ) { add ( "" ) ; error ( new MasterJoinUpdateOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class UpdateOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new UpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object update = invoke ( factory , "" , in , ) ; out . add ( output ( MockHoge . class , update , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new UpdateOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object update = invoke ( factory , "" , in , ) ; out . add ( output ( MockHoge . class , update , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void isAbstract ( ) { add ( "" ) ; error ( new UpdateOperatorProcessor ( ) ) ; } @ Test public void returns ( ) { add ( "" ) ; error ( new UpdateOperatorProcessor ( ) ) ; } @ Test public void noParameters ( ) { add ( "" ) ; error ( new UpdateOperatorProcessor ( ) ) ; } @ Test public void tooManyInput ( ) { add ( "" ) ; error ( new UpdateOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . compiler . operator . model . MockSummarized ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class SummarizeOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new SummarizeOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockSummarized > out = MockOut . of ( MockSummarized . class , "" ) ; Object summarize = invoke ( factory , "" , in ) ; out . add ( output ( MockSummarized . class , summarize , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void NotAbstract ( ) { add ( "" ) ; error ( new SummarizeOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new SummarizeOperatorProcessor ( ) ) ; } @ Test public void NotSummarized ( ) { add ( "" ) ; error ( new SummarizeOperatorProcessor ( ) ) ; } @ Test public void Parameterized ( ) { add ( "" ) ; error ( new SummarizeOperatorProcessor ( ) ) ; } @ Test public void Generic ( ) { add ( "" ) ; error ( new SummarizeOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class ExtractOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new ExtractOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > a = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > b = MockOut . of ( MockHoge . class , "" ) ; Object gs = invoke ( factory , "" , in ) ; a . add ( output ( MockHoge . class , gs , "" ) ) ; b . add ( output ( MockHoge . class , gs , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void parameterized ( ) { add ( "" ) ; ClassLoader loader = start ( new ExtractOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > a = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > b = MockOut . of ( MockHoge . class , "" ) ; Object gs = invoke ( factory , "" , in , ) ; a . add ( output ( MockHoge . class , gs , "" ) ) ; b . add ( output ( MockHoge . class , gs , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new ExtractOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > a = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > b = MockOut . of ( MockHoge . class , "" ) ; Object gs = invoke ( factory , "" , in ) ; a . add ( output ( MockHoge . class , gs , "" ) ) ; b . add ( output ( MockHoge . class , gs , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void Abstract ( ) { add ( "" ) ; error ( new ExtractOperatorProcessor ( ) ) ; } @ Test public void NoResults ( ) { add ( "" ) ; error ( new ExtractOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new ExtractOperatorProcessor ( ) ) ; } @ Test public void NotResult ( ) { add ( "" ) ; error ( new ExtractOperatorProcessor ( ) ) ; } @ Test public void NotUserParameter ( ) { add ( "" ) ; error ( new ExtractOperatorProcessor ( ) ) ; } @ Test public void NotVoid ( ) { add ( "" ) ; error ( new ExtractOperatorProcessor ( ) ) ; } @ Test public void UnboundGenerics ( ) { add ( "" ) ; error ( new ExtractOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class FoldOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new FoldOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object fold = invoke ( factory , "" , in , ) ; out . add ( output ( MockHoge . class , fold , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new FoldOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object fold = invoke ( factory , "" , in , ) ; out . add ( output ( MockHoge . class , fold , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void isAbstract ( ) { add ( "" ) ; error ( new FoldOperatorProcessor ( ) ) ; } @ Test public void returns ( ) { add ( "" ) ; error ( new FoldOperatorProcessor ( ) ) ; } @ Test public void noParameters ( ) { add ( "" ) ; error ( new FoldOperatorProcessor ( ) ) ; } @ Test public void lessParameters ( ) { add ( "" ) ; error ( new FoldOperatorProcessor ( ) ) ; } @ Test public void tooManyInput ( ) { add ( "" ) ; error ( new FoldOperatorProcessor ( ) ) ; } @ Test public void inconsistentType ( ) { add ( "" ) ; error ( new FoldOperatorProcessor ( ) ) ; } @ Test public void noKey ( ) { add ( "" ) ; error ( new FoldOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . compiler . operator . model . MockKeyValue1 ; import com . asakusafw . compiler . operator . model . MockKeyValue2 ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class MasterCheckOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterCheckOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > found = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterCheck = invoke ( factory , "" , a , b ) ; found . add ( output ( MockFoo . class , masterCheck , "" ) ) ; missed . add ( output ( MockFoo . class , masterCheck , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void selector ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterCheckOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockFoo > found = MockOut . of ( MockFoo . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterCheck = invoke ( factory , "" , a , b ) ; found . add ( output ( MockFoo . class , masterCheck , "" ) ) ; missed . add ( output ( MockFoo . class , masterCheck , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterCheckOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockKeyValue1 > a = MockIn . of ( MockKeyValue1 . class , "" ) ; MockIn < MockKeyValue2 > b = MockIn . of ( MockKeyValue2 . class , "" ) ; MockOut < MockKeyValue2 > found = MockOut . of ( MockKeyValue2 . class , "" ) ; MockOut < MockKeyValue2 > missed = MockOut . of ( MockKeyValue2 . class , "" ) ; Object masterCheck = invoke ( factory , "" , a , b ) ; found . add ( output ( MockKeyValue2 . class , masterCheck , "" ) ) ; missed . add ( output ( MockKeyValue2 . class , masterCheck , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void NoKeys ( ) { add ( "" ) ; error ( new MasterCheckOperatorProcessor ( ) ) ; } @ Test public void NotAbstract ( ) { add ( "" ) ; error ( new MasterCheckOperatorProcessor ( ) ) ; } @ Test public void NotBoolean ( ) { add ( "" ) ; error ( new MasterCheckOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new MasterCheckOperatorProcessor ( ) ) ; } @ Test public void Parameterized ( ) { add ( "" ) ; error ( new MasterCheckOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class BranchOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new BranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > high = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > middle = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > low = MockOut . of ( MockHoge . class , "" ) ; Object branch = invoke ( factory , "" , in ) ; high . add ( output ( MockHoge . class , branch , "" ) ) ; middle . add ( output ( MockHoge . class , branch , "" ) ) ; low . add ( output ( MockHoge . class , branch , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" ) ) ; } @ Test public void parameterized ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new BranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > high = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > middle = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > low = MockOut . of ( MockHoge . class , "" ) ; Object branch = invoke ( factory , "" , in , , ) ; high . add ( output ( MockHoge . class , branch , "" ) ) ; middle . add ( output ( MockHoge . class , branch , "" ) ) ; low . add ( output ( MockHoge . class , branch , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new BranchOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > high = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > middle = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > low = MockOut . of ( MockHoge . class , "" ) ; Object branch = invoke ( factory , "" , in ) ; high . add ( output ( MockHoge . class , branch , "" ) ) ; middle . add ( output ( MockHoge . class , branch , "" ) ) ; low . add ( output ( MockHoge . class , branch , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" , "" ) ) ; } @ Test public void special_words ( ) { add ( "" ) ; add ( "" ) ; ClassLoader loader = start ( new BranchOperatorProcessor ( ) ) ; create ( loader , "" ) ; } @ Test public void emptyEnum ( ) { add ( "" ) ; add ( "" ) ; error ( new BranchOperatorProcessor ( ) ) ; } @ Test public void notEnum ( ) { add ( "" ) ; add ( "" ) ; error ( new BranchOperatorProcessor ( ) ) ; } @ Test public void notModel ( ) { add ( "" ) ; add ( "" ) ; error ( new BranchOperatorProcessor ( ) ) ; } @ Test public void _abstract ( ) { add ( "" ) ; add ( "" ) ; error ( new BranchOperatorProcessor ( ) ) ; } @ Test public void notUserParameter ( ) { add ( "" ) ; add ( "" ) ; error ( new BranchOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; @ SuppressWarnings ( "" ) public class UniqueOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new UniqueOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > a = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > b = MockOut . of ( MockHoge . class , "" ) ; Object unique = invoke ( factory , "" , in ) ; a . add ( output ( MockHoge . class , unique , "" ) ) ; b . add ( output ( MockHoge . class , unique , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class ConvertOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new ConvertOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > orig = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockFoo > out = MockOut . of ( MockFoo . class , "" ) ; Object update = invoke ( factory , "" , in ) ; orig . add ( output ( MockHoge . class , update , "" ) ) ; out . add ( output ( MockFoo . class , update , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void parameterized ( ) { add ( "" ) ; ClassLoader loader = start ( new ConvertOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > orig = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockFoo > out = MockOut . of ( MockFoo . class , "" ) ; Object update = invoke ( factory , "" , in , ) ; orig . add ( output ( MockHoge . class , update , "" ) ) ; out . add ( output ( MockFoo . class , update , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new ConvertOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > orig = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockFoo > out = MockOut . of ( MockFoo . class , "" ) ; Object update = invoke ( factory , "" , in ) ; orig . add ( output ( MockHoge . class , update , "" ) ) ; out . add ( output ( MockFoo . class , update , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void _abstract ( ) { add ( "" ) ; error ( new ConvertOperatorProcessor ( ) ) ; } @ Test public void notUserParameter ( ) { add ( "" ) ; error ( new ConvertOperatorProcessor ( ) ) ; } @ Test public void returnsVoid ( ) { add ( "" ) ; error ( new ConvertOperatorProcessor ( ) ) ; } @ Test public void notModel ( ) { add ( "" ) ; error ( new ConvertOperatorProcessor ( ) ) ; } @ Test public void returnsTypeVariable ( ) { add ( "" ) ; error ( new ConvertOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . compiler . operator . model . MockJoined ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class MasterJoinOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockJoined > joined = MockOut . of ( MockJoined . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoin = invoke ( factory , "" , a , b ) ; joined . add ( output ( MockJoined . class , masterJoin , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoin , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void selector ( ) { add ( "" ) ; ClassLoader loader = start ( new MasterJoinOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockJoined > joined = MockOut . of ( MockJoined . class , "" ) ; MockOut < MockFoo > missed = MockOut . of ( MockFoo . class , "" ) ; Object masterJoin = invoke ( factory , "" , a , b ) ; joined . add ( output ( MockJoined . class , masterJoin , "" ) ) ; missed . add ( output ( MockFoo . class , masterJoin , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void NotAbstract ( ) { add ( "" ) ; error ( new MasterJoinOperatorProcessor ( ) ) ; } @ Test public void NotJoined ( ) { add ( "" ) ; error ( new MasterJoinOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new MasterJoinOperatorProcessor ( ) ) ; } @ Test public void Parameterized ( ) { add ( "" ) ; error ( new MasterJoinOperatorProcessor ( ) ) ; } @ Test public void Generic ( ) { add ( "" ) ; error ( new MasterJoinOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class CoGroupOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new CoGroupOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockHoge > r1 = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockFoo > r2 = MockOut . of ( MockFoo . class , "" ) ; Object coGroup = invoke ( factory , "" , a , b ) ; r1 . add ( output ( MockHoge . class , coGroup , "" ) ) ; r2 . add ( output ( MockFoo . class , coGroup , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void parameterized ( ) { add ( "" ) ; ClassLoader loader = start ( new CoGroupOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockHoge > r1 = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockFoo > r2 = MockOut . of ( MockFoo . class , "" ) ; Object coGroup = invoke ( factory , "" , a , b , ) ; r1 . add ( output ( MockHoge . class , coGroup , "" ) ) ; r2 . add ( output ( MockFoo . class , coGroup , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new CoGroupOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > a = MockIn . of ( MockHoge . class , "" ) ; MockIn < MockFoo > b = MockIn . of ( MockFoo . class , "" ) ; MockOut < MockHoge > r1 = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockFoo > r2 = MockOut . of ( MockFoo . class , "" ) ; Object coGroup = invoke ( factory , "" , a , b ) ; r1 . add ( output ( MockHoge . class , coGroup , "" ) ) ; r2 . add ( output ( MockFoo . class , coGroup , "" ) ) ; Graph < String > graph = toGraph ( a , b ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void _abstract ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void noResult ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void notList ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void notResult ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void notModel ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void notVoid ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void noKey ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void emptyStringGroup ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void emptyStringOrder ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void notUserParameter ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } @ Test public void unboundGenerics ( ) { add ( "" ) ; error ( new CoGroupOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class GroupSortOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new GroupSortOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > a = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > b = MockOut . of ( MockHoge . class , "" ) ; Object gs = invoke ( factory , "" , in ) ; a . add ( output ( MockHoge . class , gs , "" ) ) ; b . add ( output ( MockHoge . class , gs , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void parameterized ( ) { add ( "" ) ; ClassLoader loader = start ( new GroupSortOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > a = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > b = MockOut . of ( MockHoge . class , "" ) ; Object gs = invoke ( factory , "" , in , ) ; a . add ( output ( MockHoge . class , gs , "" ) ) ; b . add ( output ( MockHoge . class , gs , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new GroupSortOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > a = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockHoge > b = MockOut . of ( MockHoge . class , "" ) ; Object gs = invoke ( factory , "" , in ) ; a . add ( output ( MockHoge . class , gs , "" ) ) ; b . add ( output ( MockHoge . class , gs , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void Abstract ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } @ Test public void NoKey ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } @ Test public void NoResults ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } @ Test public void NotList ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } @ Test public void NotResult ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } @ Test public void NotUserParameter ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } @ Test public void NotVoid ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } @ Test public void UnboundGenerics ( ) { add ( "" ) ; error ( new GroupSortOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class LoggingOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new LoggingOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object logging = invoke ( factory , "" , in ) ; out . add ( output ( MockHoge . class , logging , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void parameterized ( ) { add ( "" ) ; ClassLoader loader = start ( new LoggingOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object logging = invoke ( factory , "" , in , ) ; out . add ( output ( MockHoge . class , logging , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void generics ( ) { add ( "" ) ; ClassLoader loader = start ( new LoggingOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockHoge > in = MockIn . of ( MockHoge . class , "" ) ; MockOut < MockHoge > out = MockOut . of ( MockHoge . class , "" ) ; Object logging = invoke ( factory , "" , in ) ; out . add ( output ( MockHoge . class , logging , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; } @ Test public void Abstract ( ) { add ( "" ) ; error ( new LoggingOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new LoggingOperatorProcessor ( ) ) ; } @ Test public void NotString ( ) { add ( "" ) ; error ( new LoggingOperatorProcessor ( ) ) ; } @ Test public void NotUserParameter ( ) { add ( "" ) ; error ( new LoggingOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator . processor ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . compiler . operator . OperatorCompilerTestRoot ; import com . asakusafw . compiler . operator . model . MockFoo ; import com . asakusafw . compiler . operator . model . MockHoge ; import com . asakusafw . compiler . operator . model . MockJoined ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; public class SplitOperatorProcessorTest extends OperatorCompilerTestRoot { @ Test public void simple ( ) { add ( "" ) ; ClassLoader loader = start ( new SplitOperatorProcessor ( ) ) ; Object factory = create ( loader , "" ) ; MockIn < MockJoined > in = MockIn . of ( MockJoined . class , "" ) ; MockOut < MockHoge > a = MockOut . of ( MockHoge . class , "" ) ; MockOut < MockFoo > b = MockOut . of ( MockFoo . class , "" ) ; Object update = invoke ( factory , "" , in ) ; a . add ( output ( MockHoge . class , update , "" ) ) ; b . add ( output ( MockFoo . class , update , "" ) ) ; Graph < String > graph = toGraph ( in ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" ) ) ; assertThat ( graph . getConnected ( "" ) , isJust ( "" , "" ) ) ; } @ Test public void NotAbstract ( ) { add ( "" ) ; error ( new SplitOperatorProcessor ( ) ) ; } @ Test public void NotJoined ( ) { add ( "" ) ; error ( new SplitOperatorProcessor ( ) ) ; } @ Test public void NotModel ( ) { add ( "" ) ; error ( new SplitOperatorProcessor ( ) ) ; } @ Test public void NotResult ( ) { add ( "" ) ; error ( new SplitOperatorProcessor ( ) ) ; } @ Test public void NotVoid ( ) { add ( "" ) ; error ( new SplitOperatorProcessor ( ) ) ; } @ Test public void Parameterized ( ) { add ( "" ) ; error ( new SplitOperatorProcessor ( ) ) ; } @ Test public void Generic ( ) { add ( "" ) ; error ( new SplitOperatorProcessor ( ) ) ; } } package com . asakusafw . compiler . operator ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import javax . annotation . processing . ProcessingEnvironment ; import javax . annotation . processing . RoundEnvironment ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Elements ; import javax . lang . model . util . Types ; import com . asakusafw . utils . java . model . util . Models ; public abstract class Callback { private RuntimeException runtimeException ; private Error error ; protected OperatorCompilingEnvironment env ; protected Types types ; protected Elements elements ; protected RoundEnvironment round ; public void run ( ProcessingEnvironment pEnv , RoundEnvironment rEnv ) { this . env = new OperatorCompilingEnvironment ( pEnv , Models . getModelFactory ( ) , OperatorCompilerOptions . parse ( pEnv . getOptions ( ) ) ) ; this . round = rEnv ; this . types = pEnv . getTypeUtils ( ) ; this . elements = pEnv . getElementUtils ( ) ; try { test ( ) ; } catch ( RuntimeException e ) { this . runtimeException = e ; } catch ( Error e ) { this . error = e ; } } public void rethrow ( ) { if ( runtimeException != null ) { throw runtimeException ; } else if ( error != null ) { throw error ; } } protected abstract void test ( ) ; protected TypeMirror getType ( Class < ? > klass , TypeMirror ... arguments ) { TypeElement type = elements . getTypeElement ( klass . getName ( ) ) ; assertThat ( klass . getName ( ) , type , not ( nullValue ( ) ) ) ; if ( arguments . length == ) { return types . erasure ( type . asType ( ) ) ; } else { return types . getDeclaredType ( type , arguments ) ; } } } package com . asakusafw . compiler . common ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import java . util . Scanner ; import java . util . TreeMap ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . batch . ResourceRepository . Cursor ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . runtime . configuration . FrameworkDeployer ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public class ZipRepositoryTest { @ Rule public FrameworkDeployer framework = new FrameworkDeployer ( false ) ; @ Test public void single ( ) throws Exception { ZipRepository repository = new ZipRepository ( open ( "" ) ) ; Cursor cur = repository . createCursor ( ) ; Map < String , List < String > > entries = drain ( cur ) ; Map < String , List < String > > expected = Maps . create ( ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; assertThat ( entries , is ( expected ) ) ; } @ Test public void multiple ( ) throws Exception { ZipRepository repository = new ZipRepository ( open ( "" ) ) ; Cursor cur = repository . createCursor ( ) ; Map < String , List < String > > entries = drain ( cur ) ; Map < String , List < String > > expected = Maps . create ( ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; assertThat ( entries , is ( expected ) ) ; } @ Test public void structured ( ) throws Exception { ZipRepository repository = new ZipRepository ( open ( "" ) ) ; Cursor cur = repository . createCursor ( ) ; Map < String , List < String > > entries = drain ( cur ) ; Map < String , List < String > > expected = Maps . create ( ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; assertThat ( entries , is ( expected ) ) ; } @ Test ( expected = IOException . class ) public void notarchive ( ) throws Exception { ZipRepository repository = new ZipRepository ( open ( "" ) ) ; Cursor cur = repository . createCursor ( ) ; drain ( cur ) ; } private File open ( String name ) { String path = getClass ( ) . getSimpleName ( ) + "" + name ; InputStream input = getClass ( ) . getResourceAsStream ( path ) ; assertThat ( path , input , not ( nullValue ( ) ) ) ; try { try { File file = new File ( framework . getWork ( "" ) , name ) ; framework . dump ( input , file ) ; return file ; } finally { input . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } private Map < String , List < String > > drain ( Cursor cur ) throws IOException { try { Map < String , List < String > > entries = new TreeMap < String , List < String > > ( ) ; while ( cur . next ( ) ) { Location location = cur . getLocation ( ) ; InputStream input = cur . openResource ( ) ; try { List < String > contents = Lists . create ( ) ; Scanner scanner = new Scanner ( input , "" ) ; while ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) ; contents . add ( line ) ; } entries . put ( location . toPath ( '' ) , contents ) ; } finally { input . close ( ) ; } } return entries ; } finally { cur . close ( ) ; } } } package com . asakusafw . compiler . common ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import java . util . Scanner ; import java . util . TreeMap ; import java . util . zip . ZipInputStream ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . batch . ResourceRepository . Cursor ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . runtime . configuration . FrameworkDeployer ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public class FileRepositoryTest { @ Rule public FrameworkDeployer framework = new FrameworkDeployer ( false ) ; @ Test public void single ( ) throws Exception { FileRepository repository = new FileRepository ( open ( "" ) ) ; Cursor cur = repository . createCursor ( ) ; Map < String , List < String > > entries = drain ( cur ) ; Map < String , List < String > > expected = Maps . create ( ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; assertThat ( entries , is ( expected ) ) ; } @ Test public void multiple ( ) throws Exception { FileRepository repository = new FileRepository ( open ( "" ) ) ; Cursor cur = repository . createCursor ( ) ; Map < String , List < String > > entries = drain ( cur ) ; Map < String , List < String > > expected = Maps . create ( ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; assertThat ( entries , is ( expected ) ) ; } @ Test public void structured ( ) throws Exception { FileRepository repository = new FileRepository ( open ( "" ) ) ; Cursor cur = repository . createCursor ( ) ; Map < String , List < String > > entries = drain ( cur ) ; Map < String , List < String > > expected = Maps . create ( ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; expected . put ( "" , Arrays . asList ( "" ) ) ; assertThat ( entries , is ( expected ) ) ; } @ Test public void empty ( ) throws Exception { FileRepository repository = new FileRepository ( framework . getWork ( "" ) ) ; Cursor cur = repository . createCursor ( ) ; Map < String , List < String > > entries = drain ( cur ) ; Map < String , List < String > > expected = Maps . create ( ) ; assertThat ( entries , is ( expected ) ) ; } private File open ( String name ) { String path = getClass ( ) . getSimpleName ( ) + "" + name ; InputStream input = getClass ( ) . getResourceAsStream ( path ) ; assertThat ( path , input , not ( nullValue ( ) ) ) ; try { try { ZipInputStream zip = new ZipInputStream ( input ) ; File result = new File ( framework . getWork ( "" ) , name ) ; framework . extract ( zip , result ) ; zip . close ( ) ; return result ; } finally { input . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } private Map < String , List < String > > drain ( Cursor cur ) throws IOException { try { Map < String , List < String > > entries = new TreeMap < String , List < String > > ( ) ; while ( cur . next ( ) ) { Location location = cur . getLocation ( ) ; InputStream input = cur . openResource ( ) ; try { List < String > contents = Lists . create ( ) ; Scanner scanner = new Scanner ( input , "" ) ; while ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) ; contents . add ( line ) ; } entries . put ( location . toPath ( '' ) , contents ) ; } finally { input . close ( ) ; } } return entries ; } finally { cur . close ( ) ; } } } package com . asakusafw . compiler . common ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import org . hamcrest . Matcher ; import org . junit . Test ; public class JavaNameTest { @ Test public void snake_name_of ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void CONSTANT_NAME_OF ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void memberNameOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void TypeNameOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void constantSingleWordOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" ) ) ; } @ Test public void capitalSingleWordOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" ) ) ; } @ Test public void lowerSingleWordOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void of_empty ( ) { JavaName . of ( "" ) ; } @ Test public void of_underscore ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) . size ( ) , is ( ) ) ; assertThat ( name . toConstantName ( ) , is ( "" ) ) ; assertThat ( name . toTypeName ( ) , is ( "" ) ) ; assertThat ( name . toMemberName ( ) , is ( "" ) ) ; } @ Test public void of_reduplicate_underscore ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void of_starts_with_underscore ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" ) ) ; } @ Test public void toTypeName ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . toTypeName ( ) , is ( "" ) ) ; } @ Test public void toMemberName ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . toMemberName ( ) , is ( "" ) ) ; } @ Test public void toConstantName ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . toConstantName ( ) , is ( "" ) ) ; } @ Test public void addFirst ( ) { JavaName name = JavaName . of ( "" ) ; name . addFirst ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" , "" , "" , "" ) ) ; } @ Test public void addLast ( ) { JavaName name = JavaName . of ( "" ) ; name . addLast ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" , "" , "" , "" ) ) ; } private < T > Matcher < ? super List < T > > contains ( T ... values ) { return is ( Arrays . asList ( values ) ) ; } } package com . asakusafw . vocabulary . external ; public interface ExporterDescription { Class < ? > getModelType ( ) ; } package com . asakusafw . vocabulary . external ; package com . asakusafw . vocabulary . external ; public interface ImporterDescription { Class < ? > getModelType ( ) ; DataSize getDataSize ( ) ; public enum DataSize { UNKNOWN , TINY , SMALL , LARGE , } } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Checkpoint { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Extend { int ID_INPUT = ; int ID_OUTPUT = ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Duplicate { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . processor . PartialAggregation ; import com . asakusafw . vocabulary . model . Summarized ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Summarize { int ID_INPUT = ; int ID_OUTPUT = ; PartialAggregation partialAggregation ( ) default PartialAggregation . PARTIAL ; String summarizedPort ( ) default "" ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Convert { int ID_INPUT = ; int ID_OUTPUT_ORIGINAL = ; int ID_OUTPUT_CONVERTED = ; String originalPort ( ) default "" ; String convertedPort ( ) default "" ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . model . Key ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface MasterJoinUpdate { int ID_INPUT_MASTER = ; int ID_INPUT_TRANSACTION = ; int ID_OUTPUT_UPDATED = ; int ID_OUTPUT_MISSED = ; String updatedPort ( ) default "" ; String missedPort ( ) default "" ; String selection ( ) default MasterSelection . NO_SELECTION ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Stop { } package com . asakusafw . vocabulary . operator ; package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Extract { int ID_INPUT = ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . processor . PartialAggregation ; import com . asakusafw . vocabulary . model . Key ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Fold { int ID_INPUT = ; int ID_OUTPUT = ; String INPUT = "" ; PartialAggregation partialAggregation ( ) default PartialAggregation . DEFAULT ; String outputPort ( ) default "" ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Logging { int ID_INPUT = ; int ID_OUTPUT = ; String outputPort ( ) default "" ; Level value ( ) default Level . INFO ; enum Level implements FlowElementAttribute { ERROR , WARN , INFO , DEBUG , ; public static Level getDefault ( ) { return INFO ; } } } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Identity { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . ANNOTATION_TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface OperatorHelper { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import java . util . List ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; import com . asakusafw . vocabulary . model . Key ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface CoGroup { InputBuffer inputBuffer ( ) default InputBuffer . EXPAND ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . model . Joined ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface MasterJoin { int ID_INPUT_MASTER = ; int ID_INPUT_TRANSACTION = ; int ID_OUTPUT_JOINED = ; int ID_OUTPUT_MISSED = ; String joinedPort ( ) default "" ; String missedPort ( ) default "" ; String selection ( ) default MasterSelection . NO_SELECTION ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Split { int ID_INPUT = ; int ID_OUTPUT_LEFT = ; int ID_OUTPUT_RIGHT = ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Update { int ID_INPUT = ; int ID_OUTPUT = ; String outputPort ( ) default "" ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . model . Key ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface MasterCheck { int ID_INPUT_MASTER = ; int ID_INPUT_TRANSACTION = ; int ID_OUTPUT_FOUND = ; int ID_OUTPUT_MISSED = ; String foundPort ( ) default "" ; String missedPort ( ) default "" ; String selection ( ) default MasterSelection . NO_SELECTION ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Sticky { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Empty { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . model . Key ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented @ Deprecated public @ interface Unique { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import java . util . List ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; import com . asakusafw . vocabulary . model . Key ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface GroupSort { InputBuffer inputBuffer ( ) default InputBuffer . EXPAND ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Volatile { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . model . Key ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface MasterBranch { int ID_INPUT_MASTER = ; int ID_INPUT_TRANSACTION = ; String selection ( ) default MasterSelection . NO_SELECTION ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import java . util . List ; import com . asakusafw . vocabulary . model . Key ; @ OperatorHelper @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface MasterSelection { String NO_SELECTION = "" ; String ELEMENT_NAME = "" ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Project { int ID_INPUT = ; int ID_OUTPUT = ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Confluent { } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ Target ( { } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Restructure { int ID_INPUT = ; int ID_OUTPUT = ; } package com . asakusafw . vocabulary . operator ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . METHOD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Branch { int ID_INPUT = ; } package com . asakusafw . vocabulary . flow ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface FlowPart { } package com . asakusafw . vocabulary . flow ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . external . ExporterDescription ; @ Target ( ElementType . PARAMETER ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Export { String name ( ) ; Class < ? extends ExporterDescription > description ( ) ; } package com . asakusafw . vocabulary . flow ; public interface Out < T > { void add ( Source < T > source ) ; } package com . asakusafw . vocabulary . flow ; public interface In < T > extends Source < T > { } package com . asakusafw . vocabulary . flow ; package com . asakusafw . vocabulary . flow . util ; package com . asakusafw . vocabulary . flow . util ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Checkpoint ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Confluent ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Empty ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Extend ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Project ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Restructure ; public final class CoreOperators { private static final CoreOperatorFactory FACTORY = new CoreOperatorFactory ( ) ; private CoreOperators ( ) { return ; } public static < T > Empty < T > empty ( Class < T > type ) { return FACTORY . empty ( type ) ; } public static void stop ( Source < ? > in ) { FACTORY . stop ( in ) ; } public static < T > Confluent < T > confluent ( Source < T > a , Source < T > b ) { return FACTORY . confluent ( a , b ) ; } public static < T > Confluent < T > confluent ( Source < T > a , Source < T > b , Source < T > c ) { return FACTORY . confluent ( a , b , c ) ; } public static < T > Confluent < T > confluent ( Source < T > a , Source < T > b , Source < T > c , Source < T > d ) { return FACTORY . confluent ( a , b , c , d ) ; } public static < T > Confluent < T > confluent ( Iterable < ? extends Source < T > > inputs ) { return FACTORY . confluent ( inputs ) ; } public static < T > Checkpoint < T > checkpoint ( Source < T > in ) { return FACTORY . checkpoint ( in ) ; } public static < T > Project < T > project ( Source < ? > in , Class < T > targetType ) { return FACTORY . project ( in , targetType ) ; } public static < T > Extend < T > extend ( Source < ? > in , Class < T > targetType ) { return FACTORY . extend ( in , targetType ) ; } public static < T > Restructure < T > restructure ( Source < ? > in , Class < T > targetType ) { return FACTORY . restructure ( in , targetType ) ; } } package com . asakusafw . vocabulary . flow . util ; import static com . asakusafw . vocabulary . flow . util . PseudElementDescription . * ; import java . lang . reflect . Type ; import java . util . ArrayList ; import java . util . List ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; public class CoreOperatorFactory { public static final String EMPTY_NAME = "" ; public static final String STOP_NAME = "" ; public static final String CONFLUENT_NAME = "" ; public static final String CHECKPOINT_NAME = "" ; public static final String PROJECT_NAME = "" ; public static final String EXTEND_NAME = "" ; public static final String RESTRUCTURE_NAME = "" ; public < T > Empty < T > empty ( Class < T > type ) { return empty ( ( Type ) type ) ; } public < T > Empty < T > empty ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return new Empty < T > ( type ) ; } public void stop ( Source < ? > in ) { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } PseudElementDescription desc = new PseudElementDescription ( STOP_NAME , getPortType ( in ) , true , false , FlowBoundary . STAGE ) ; FlowElementResolver resolver = new FlowElementResolver ( desc ) ; resolver . resolveInput ( INPUT_PORT_NAME , in ) ; } public < T > Confluent < T > confluent ( Source < T > a , Source < T > b ) { if ( a == null ) { throw new IllegalArgumentException ( "" ) ; } if ( b == null ) { throw new IllegalArgumentException ( "" ) ; } Type type = getPortType ( a ) ; List < Source < T > > input = new ArrayList < Source < T > > ( ) ; input . add ( a ) ; input . add ( b ) ; return new Confluent < T > ( type , input ) ; } public < T > Confluent < T > confluent ( Source < T > a , Source < T > b , Source < T > c ) { if ( a == null ) { throw new IllegalArgumentException ( "" ) ; } if ( b == null ) { throw new IllegalArgumentException ( "" ) ; } if ( c == null ) { throw new IllegalArgumentException ( "" ) ; } Type type = getPortType ( a ) ; List < Source < T > > input = new ArrayList < Source < T > > ( ) ; input . add ( a ) ; input . add ( b ) ; input . add ( c ) ; return new Confluent < T > ( type , input ) ; } public < T > Confluent < T > confluent ( Source < T > a , Source < T > b , Source < T > c , Source < T > d ) { if ( a == null ) { throw new IllegalArgumentException ( "" ) ; } if ( b == null ) { throw new IllegalArgumentException ( "" ) ; } if ( c == null ) { throw new IllegalArgumentException ( "" ) ; } if ( d == null ) { throw new IllegalArgumentException ( "" ) ; } Type type = getPortType ( a ) ; List < Source < T > > input = new ArrayList < Source < T > > ( ) ; input . add ( a ) ; input . add ( b ) ; input . add ( c ) ; input . add ( d ) ; return new Confluent < T > ( type , input ) ; } public < T > Confluent < T > confluent ( Iterable < ? extends Source < T > > inputs ) { if ( inputs == null ) { throw new IllegalArgumentException ( "" ) ; } List < Source < T > > input = new ArrayList < Source < T > > ( ) ; for ( Source < T > in : inputs ) { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } input . add ( in ) ; } if ( input . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } Type type = getPortType ( input . get ( ) ) ; return new Confluent < T > ( type , input ) ; } public < T > Checkpoint < T > checkpoint ( Source < T > in ) { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } Type type = getPortType ( in ) ; return new Checkpoint < T > ( type , in ) ; } public < T > Project < T > project ( Source < ? > in , Class < T > targetType ) { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetType == null ) { throw new IllegalArgumentException ( "" ) ; } return new Project < T > ( in , targetType ) ; } public < T > Extend < T > extend ( Source < ? > in , Class < T > targetType ) { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetType == null ) { throw new IllegalArgumentException ( "" ) ; } return new Extend < T > ( in , targetType ) ; } public < T > Restructure < T > restructure ( Source < ? > in , Class < T > targetType ) { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetType == null ) { throw new IllegalArgumentException ( "" ) ; } return new Restructure < T > ( in , targetType ) ; } private < T > Type getPortType ( Source < T > source ) { assert source != null ; FlowElementOutput port = source . toOutputPort ( ) ; Type type = port . getDescription ( ) . getDataType ( ) ; return type ; } public static final class Empty < T > implements Source < T > { public final Source < T > out ; private final FlowElementResolver resolver ; Empty ( Type type ) { assert type != null ; this . out = this ; PseudElementDescription desc = new PseudElementDescription ( EMPTY_NAME , type , false , true , FlowBoundary . STAGE ) ; this . resolver = new FlowElementResolver ( desc ) ; } @ Override public FlowElementOutput toOutputPort ( ) { return resolver . getOutput ( OUTPUT_PORT_NAME ) ; } } public static final class Confluent < T > implements Source < T > { public final Source < T > out ; private final FlowElementResolver resolver ; Confluent ( Type type , List < Source < T > > input ) { assert type != null ; assert input != null ; this . out = this ; PseudElementDescription desc = new PseudElementDescription ( CONFLUENT_NAME , type , true , true ) ; resolver = new FlowElementResolver ( desc ) ; for ( Source < T > in : input ) { resolver . resolveInput ( INPUT_PORT_NAME , in ) ; } } @ Override public FlowElementOutput toOutputPort ( ) { return resolver . getOutput ( OUTPUT_PORT_NAME ) ; } } public static final class Checkpoint < T > implements Source < T > { public final Source < T > out ; private final FlowElementResolver resolver ; Checkpoint ( Type type , Source < T > in ) { assert type != null ; assert in != null ; this . out = this ; PseudElementDescription desc = new PseudElementDescription ( CHECKPOINT_NAME , type , true , true , FlowBoundary . STAGE ) ; this . resolver = new FlowElementResolver ( desc ) ; resolver . resolveInput ( INPUT_PORT_NAME , in ) ; } @ Override public FlowElementOutput toOutputPort ( ) { return resolver . getOutput ( OUTPUT_PORT_NAME ) ; } } public static final class Project < T > implements Operator , Source < T > { public final Source < T > out ; private final FlowElementResolver resolver ; Project ( Source < ? > in , Class < T > targetClass ) { assert in != null ; assert targetClass != null ; OperatorDescription . Builder builder = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Project . class ) ; builder . declare ( Project . class , Project . class , "" ) ; builder . addInput ( INPUT_PORT_NAME , in ) ; builder . addOutput ( OUTPUT_PORT_NAME , targetClass ) ; this . resolver = builder . toResolver ( ) ; this . resolver . resolveInput ( INPUT_PORT_NAME , in ) ; this . resolver . setName ( PROJECT_NAME ) ; this . out = this . resolver . resolveOutput ( OUTPUT_PORT_NAME ) ; } @ Override public FlowElementOutput toOutputPort ( ) { return resolver . getOutput ( OUTPUT_PORT_NAME ) ; } } public static final class Extend < T > implements Operator , Source < T > { public final Source < T > out ; private final FlowElementResolver resolver ; Extend ( Source < ? > in , Class < T > targetClass ) { assert in != null ; assert targetClass != null ; OperatorDescription . Builder builder = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Extend . class ) ; builder . declare ( Extend . class , Extend . class , "" ) ; builder . addInput ( INPUT_PORT_NAME , in ) ; builder . addOutput ( OUTPUT_PORT_NAME , targetClass ) ; this . resolver = builder . toResolver ( ) ; this . resolver . resolveInput ( INPUT_PORT_NAME , in ) ; this . resolver . setName ( EXTEND_NAME ) ; this . out = this . resolver . resolveOutput ( OUTPUT_PORT_NAME ) ; } @ Override public FlowElementOutput toOutputPort ( ) { return resolver . getOutput ( OUTPUT_PORT_NAME ) ; } } public static final class Restructure < T > implements Operator , Source < T > { public final Source < T > out ; private final FlowElementResolver resolver ; Restructure ( Source < ? > in , Class < T > targetClass ) { assert in != null ; assert targetClass != null ; OperatorDescription . Builder builder = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Restructure . class ) ; builder . declare ( Restructure . class , Restructure . class , "" ) ; builder . addInput ( INPUT_PORT_NAME , in ) ; builder . addOutput ( OUTPUT_PORT_NAME , targetClass ) ; this . resolver = builder . toResolver ( ) ; this . resolver . resolveInput ( INPUT_PORT_NAME , in ) ; this . resolver . setName ( RESTRUCTURE_NAME ) ; this . out = this . resolver . resolveOutput ( OUTPUT_PORT_NAME ) ; } @ Override public FlowElementOutput toOutputPort ( ) { return resolver . getOutput ( OUTPUT_PORT_NAME ) ; } } } package com . asakusafw . vocabulary . flow . util ; import java . lang . reflect . Type ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; import com . asakusafw . vocabulary . flow . graph . FlowElementDescription ; import com . asakusafw . vocabulary . flow . graph . FlowElementKind ; import com . asakusafw . vocabulary . flow . graph . FlowElementPortDescription ; import com . asakusafw . vocabulary . flow . graph . FlowResourceDescription ; import com . asakusafw . vocabulary . flow . graph . PortDirection ; public class PseudElementDescription implements FlowElementDescription { public static final String INPUT_PORT_NAME = "" ; public static final String OUTPUT_PORT_NAME = "" ; private String name ; private final List < FlowElementPortDescription > inputPorts ; private final List < FlowElementPortDescription > outputPorts ; private final Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > attributes ; public PseudElementDescription ( String name , Type type , boolean hasInput , boolean hasOutput , FlowElementAttribute ... attributes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . inputPorts = create ( hasInput , INPUT_PORT_NAME , type , PortDirection . INPUT ) ; this . outputPorts = create ( hasOutput , OUTPUT_PORT_NAME , type , PortDirection . OUTPUT ) ; this . attributes = new HashMap < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ( ) ; for ( FlowElementAttribute attribute : attributes ) { this . attributes . put ( attribute . getDeclaringClass ( ) , attribute ) ; } } private List < FlowElementPortDescription > create ( boolean doCreate , String portName , Type portType , PortDirection direction ) { assert portName != null ; assert direction != null ; if ( doCreate == false ) { return Collections . emptyList ( ) ; } else { return Collections . singletonList ( new FlowElementPortDescription ( portName , portType , direction ) ) ; } } @ Override public FlowElementKind getKind ( ) { return FlowElementKind . PSEUD ; } @ Override public String getName ( ) { return name ; } @ Override public void setName ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } @ Override public List < FlowElementPortDescription > getInputPorts ( ) { return inputPorts ; } @ Override public List < FlowElementPortDescription > getOutputPorts ( ) { return outputPorts ; } @ Override public List < FlowResourceDescription > getResources ( ) { return Collections . emptyList ( ) ; } @ Override public < T extends FlowElementAttribute > T getAttribute ( Class < T > attributeClass ) { if ( attributeClass == null ) { throw new IllegalArgumentException ( "" ) ; } Object attribute = attributes . get ( attributeClass ) ; return attributeClass . cast ( attribute ) ; } } package com . asakusafw . vocabulary . flow ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; public interface Source < T > { FlowElementOutput toOutputPort ( ) ; } package com . asakusafw . vocabulary . flow ; public interface Operator { } package com . asakusafw . vocabulary . flow . graph ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; public abstract class FlowElementPort { private FlowElement owner ; private FlowElementPortDescription description ; private Set < PortConnection > connected ; public FlowElementPort ( FlowElementPortDescription description , FlowElement owner ) { if ( owner == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } this . owner = owner ; this . description = description ; this . connected = new HashSet < PortConnection > ( ) ; } public FlowElement getOwner ( ) { return owner ; } public FlowElementPortDescription getDescription ( ) { return description ; } public Set < PortConnection > getConnected ( ) { return Collections . unmodifiableSet ( connected ) ; } void register ( PortConnection connection ) { if ( connection == null ) { throw new IllegalArgumentException ( "" ) ; } connected . add ( connection ) ; } void unregister ( PortConnection connection ) { if ( connection == null ) { throw new IllegalArgumentException ( "" ) ; } boolean removed = connected . remove ( connection ) ; if ( removed == false ) { throw new IllegalStateException ( ) ; } } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; public enum FlowBoundary implements FlowElementAttribute { STAGE , SHUFFLE , DEFAULT , ; @ Override public String toString ( ) { return MessageFormat . format ( "" , getDeclaringClass ( ) . getSimpleName ( ) , name ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . lang . reflect . Type ; import java . text . MessageFormat ; public class FlowElementPortDescription { private String name ; private Type dataType ; private PortDirection direction ; private ShuffleKey shuffleKey ; public FlowElementPortDescription ( String name , Type dataType , PortDirection direction ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . dataType = dataType ; this . direction = direction ; this . shuffleKey = null ; } public FlowElementPortDescription ( String name , Type dataType , ShuffleKey shuffleKey ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( shuffleKey == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . dataType = dataType ; this . direction = PortDirection . INPUT ; this . shuffleKey = shuffleKey ; } public String getName ( ) { return name ; } public Type getDataType ( ) { return dataType ; } public PortDirection getDirection ( ) { return direction ; } public ShuffleKey getShuffleKey ( ) { return shuffleKey ; } @ Override public String toString ( ) { if ( direction == PortDirection . INPUT ) { return MessageFormat . format ( "" , getName ( ) , getDataType ( ) ) ; } else { return MessageFormat . format ( "" , getName ( ) , getDataType ( ) ) ; } } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; import com . asakusafw . vocabulary . flow . In ; public final class FlowIn < T > implements In < T > { private InputDescription description ; private FlowElementResolver resolver ; public FlowIn ( InputDescription description ) { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } this . description = description ; this . resolver = new FlowElementResolver ( description ) ; } public static < T > FlowIn < T > newInstance ( InputDescription description ) { return new FlowIn < T > ( description ) ; } public InputDescription getDescription ( ) { return description ; } public FlowElement getFlowElement ( ) { return resolver . getElement ( ) ; } @ Override public FlowElementOutput toOutputPort ( ) { return resolver . getOutput ( InputDescription . OUTPUT_PORT_NAME ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getDescription ( ) , getFlowElement ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; public enum Connectivity implements FlowElementAttribute { OPTIONAL , MANDATORY , ; public static Connectivity getDefault ( ) { return MANDATORY ; } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class FlowGraph { private final Class < ? extends FlowDescription > description ; private final List < FlowIn < ? > > flowInputs ; private final List < FlowOut < ? > > flowOutputs ; private FlowGraph origin ; public FlowGraph ( Class < ? extends FlowDescription > description , List < ? extends FlowIn < ? > > flowInputs , List < ? extends FlowOut < ? > > flowOutputs ) { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flowInputs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( flowOutputs == null ) { throw new IllegalArgumentException ( "" ) ; } this . description = description ; this . flowInputs = Collections . unmodifiableList ( new ArrayList < FlowIn < ? > > ( flowInputs ) ) ; this . flowOutputs = Collections . unmodifiableList ( new ArrayList < FlowOut < ? > > ( flowOutputs ) ) ; this . origin = this ; } public void setOrigin ( FlowGraph origin ) { if ( origin == null ) { this . origin = this ; } else { this . origin = origin ; } } public FlowGraph getOrigin ( ) { return origin ; } public Class < ? extends FlowDescription > getDescription ( ) { return description ; } public List < FlowIn < ? > > getFlowInputs ( ) { return flowInputs ; } public List < FlowOut < ? > > getFlowOutputs ( ) { return flowOutputs ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getDescription ( ) . getName ( ) , getFlowInputs ( ) , getFlowOutputs ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . util . Set ; public interface FlowResourceDescription { Set < InputDescription > getSideDataInputs ( ) ; } package com . asakusafw . vocabulary . flow . graph ; package com . asakusafw . vocabulary . flow . graph ; public enum FlowElementKind { INPUT , OUTPUT , OPERATOR , FLOW_COMPONENT , PSEUD , } package com . asakusafw . vocabulary . flow . graph ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . vocabulary . external . ExporterDescription ; public class OutputDescription implements FlowElementDescription { public static final String INPUT_PORT_NAME = "" ; private static final Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ATTRIBUTES ; static { Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > map = new HashMap < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ( ) ; map . put ( FlowBoundary . class , FlowBoundary . STAGE ) ; ATTRIBUTES = Collections . unmodifiableMap ( map ) ; } private String name ; private FlowElementPortDescription port ; private ExporterDescription exporterDescription ; public OutputDescription ( String name , Type type ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . port = createPort ( type ) ; this . exporterDescription = null ; } public OutputDescription ( String name , ExporterDescription exporter ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( exporter == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . port = createPort ( exporter . getModelType ( ) ) ; this . exporterDescription = exporter ; } private FlowElementPortDescription createPort ( Type type ) { assert type != null ; return new FlowElementPortDescription ( INPUT_PORT_NAME , type , PortDirection . INPUT ) ; } @ Override public String getName ( ) { return name ; } @ Override public void setName ( String newName ) { if ( newName == null ) { throw new IllegalArgumentException ( "" ) ; } throw new UnsupportedOperationException ( "" ) ; } @ Override public FlowElementKind getKind ( ) { return FlowElementKind . OUTPUT ; } public Type getDataType ( ) { return port . getDataType ( ) ; } public ExporterDescription getExporterDescription ( ) { return this . exporterDescription ; } @ Override public List < FlowElementPortDescription > getInputPorts ( ) { return Collections . singletonList ( port ) ; } @ Override public List < FlowElementPortDescription > getOutputPorts ( ) { return Collections . emptyList ( ) ; } @ Override public List < FlowResourceDescription > getResources ( ) { return Collections . emptyList ( ) ; } @ Override public < T extends FlowElementAttribute > T getAttribute ( Class < T > attributeClass ) { if ( attributeClass == null ) { throw new IllegalArgumentException ( "" ) ; } Object attribute = ATTRIBUTES . get ( attributeClass ) ; return attributeClass . cast ( attribute ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , name , port . getDataType ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; public enum ObservationCount implements FlowElementAttribute { DONT_CARE ( false , false ) { @ Override public ObservationCount and ( ObservationCount other ) { if ( other == null ) { throw new IllegalArgumentException ( "" ) ; } return other ; } } , AT_MOST_ONCE ( true , false ) { @ Override public ObservationCount and ( ObservationCount other ) { if ( other == null ) { throw new IllegalArgumentException ( "" ) ; } if ( other . atLeastOnce ) { return EXACTLY_ONCE ; } return AT_MOST_ONCE ; } } , AT_LEAST_ONCE ( false , true ) { @ Override public ObservationCount and ( ObservationCount other ) { if ( other == null ) { throw new IllegalArgumentException ( "" ) ; } if ( other . atMostOnce ) { return EXACTLY_ONCE ; } return AT_LEAST_ONCE ; } } , EXACTLY_ONCE ( true , true ) { @ Override public ObservationCount and ( ObservationCount other ) { if ( other == null ) { throw new IllegalArgumentException ( "" ) ; } return EXACTLY_ONCE ; } } , ; public final boolean atMostOnce ; public final boolean atLeastOnce ; private ObservationCount ( boolean atMostOnce , boolean atLeastOnce ) { this . atMostOnce = atMostOnce ; this . atLeastOnce = atLeastOnce ; } public abstract ObservationCount and ( ObservationCount other ) ; @ Override public String toString ( ) { return MessageFormat . format ( "" , getDeclaringClass ( ) . getSimpleName ( ) , name ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; public final class FlowElementInput extends FlowElementPort { public FlowElementInput ( FlowElementPortDescription description , FlowElement owner ) { super ( description , owner ) ; } public Collection < FlowElementOutput > getOpposites ( ) { Collection < FlowElementOutput > results = new ArrayList < FlowElementOutput > ( ) ; for ( PortConnection conn : getConnected ( ) ) { results . add ( conn . getUpstream ( ) ) ; } return results ; } public Collection < FlowElementOutput > disconnectAll ( ) { Collection < FlowElementOutput > results = new ArrayList < FlowElementOutput > ( ) ; for ( PortConnection conn : new ArrayList < PortConnection > ( getConnected ( ) ) ) { results . add ( conn . getUpstream ( ) ) ; conn . disconnect ( ) ; } return results ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getDescription ( ) . getName ( ) , getOwner ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; public interface FlowElementAttributeProvider { < T extends FlowElementAttribute > T getAttribute ( Class < T > attributeClass ) ; } package com . asakusafw . vocabulary . flow . graph ; public enum PortDirection { INPUT , OUTPUT , } package com . asakusafw . vocabulary . flow . graph ; import java . lang . reflect . Type ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Source ; public class FlowPartDescription implements FlowElementDescription { private static final Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ATTRIBUTES ; static { Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > map = new HashMap < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ( ) ; map . put ( FlowBoundary . class , FlowBoundary . STAGE ) ; ATTRIBUTES = Collections . unmodifiableMap ( map ) ; } private FlowGraph flowGraph ; private List < FlowElementPortDescription > inputPorts ; private List < FlowElementPortDescription > outputPorts ; private String name ; public FlowPartDescription ( FlowGraph flowGraph ) { if ( flowGraph == null ) { throw new IllegalArgumentException ( "" ) ; } this . flowGraph = flowGraph ; List < FlowElementPortDescription > inputs = new ArrayList < FlowElementPortDescription > ( ) ; List < FlowElementPortDescription > outputs = new ArrayList < FlowElementPortDescription > ( ) ; this . inputPorts = Collections . unmodifiableList ( inputs ) ; this . outputPorts = Collections . unmodifiableList ( outputs ) ; for ( FlowIn < ? > in : flowGraph . getFlowInputs ( ) ) { inputs . add ( new FlowElementPortDescription ( in . getDescription ( ) . getName ( ) , in . getDescription ( ) . getDataType ( ) , PortDirection . INPUT ) ) ; } for ( FlowOut < ? > out : flowGraph . getFlowOutputs ( ) ) { outputs . add ( new FlowElementPortDescription ( out . getDescription ( ) . getName ( ) , out . getDescription ( ) . getDataType ( ) , PortDirection . OUTPUT ) ) ; } } public FlowGraph getFlowGraph ( ) { return flowGraph ; } @ Override public FlowElementKind getKind ( ) { return FlowElementKind . FLOW_COMPONENT ; } @ Override public String getName ( ) { if ( name == null ) { return flowGraph . getDescription ( ) . getSimpleName ( ) ; } return name ; } @ Override public void setName ( String newName ) { if ( newName == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = newName ; } @ Override public List < FlowElementPortDescription > getInputPorts ( ) { return inputPorts ; } @ Override public List < FlowElementPortDescription > getOutputPorts ( ) { return outputPorts ; } public FlowIn < ? > getInternalInputPort ( FlowElementPortDescription externalInput ) { if ( externalInput == null ) { throw new IllegalArgumentException ( "" ) ; } assert inputPorts . size ( ) == flowGraph . getFlowInputs ( ) . size ( ) ; int index = inputPorts . indexOf ( externalInput ) ; if ( index < ) { throw new IllegalArgumentException ( ) ; } return flowGraph . getFlowInputs ( ) . get ( index ) ; } public FlowOut < ? > getInternalOutputPort ( FlowElementPortDescription externalOutput ) { if ( externalOutput == null ) { throw new IllegalArgumentException ( "" ) ; } assert outputPorts . size ( ) == flowGraph . getFlowOutputs ( ) . size ( ) ; int index = outputPorts . indexOf ( externalOutput ) ; if ( index < ) { throw new IllegalArgumentException ( ) ; } return flowGraph . getFlowOutputs ( ) . get ( index ) ; } @ Override public List < FlowResourceDescription > getResources ( ) { return Collections . emptyList ( ) ; } @ Override public < T extends FlowElementAttribute > T getAttribute ( Class < T > attributeClass ) { if ( attributeClass == null ) { throw new IllegalArgumentException ( "" ) ; } Object attribute = ATTRIBUTES . get ( attributeClass ) ; return attributeClass . cast ( attribute ) ; } public static class Builder { private Class < ? extends FlowDescription > declaring ; private List < FlowIn < ? > > flowInputs ; private List < FlowOut < ? > > flowOutputs ; public Builder ( Class < ? extends FlowDescription > declaring ) { if ( declaring == null ) { throw new IllegalArgumentException ( "" ) ; } this . declaring = declaring ; this . flowInputs = new ArrayList < FlowIn < ? > > ( ) ; this . flowOutputs = new ArrayList < FlowOut < ? > > ( ) ; } public < T > FlowIn < T > addInput ( String name , Type type ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } FlowIn < T > in = new FlowIn < T > ( new InputDescription ( name , type ) ) ; flowInputs . add ( in ) ; return in ; } public < T > FlowOut < T > addOutput ( String name , Type type ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } FlowOut < T > out = new FlowOut < T > ( new OutputDescription ( name , type ) ) ; flowOutputs . add ( out ) ; return out ; } public < T > FlowIn < T > addInput ( String name , Source < T > typeReference ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( typeReference == null ) { throw new IllegalArgumentException ( "" ) ; } FlowIn < T > in = new FlowIn < T > ( new InputDescription ( name , typeReference . toOutputPort ( ) . getDescription ( ) . getDataType ( ) ) ) ; flowInputs . add ( in ) ; return in ; } public < T > FlowOut < T > addOutput ( String name , Source < T > typeReference ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( typeReference == null ) { throw new IllegalArgumentException ( "" ) ; } FlowOut < T > out = new FlowOut < T > ( new OutputDescription ( name , typeReference . toOutputPort ( ) . getDescription ( ) . getDataType ( ) ) ) ; flowOutputs . add ( out ) ; return out ; } public FlowPartDescription toDescription ( ) { FlowGraph graph = new FlowGraph ( declaring , flowInputs , flowOutputs ) ; return new FlowPartDescription ( graph ) ; } public FlowElementResolver toResolver ( FlowDescription desc ) { if ( desc == null ) { throw new IllegalArgumentException ( "" ) ; } desc . start ( ) ; return new FlowElementResolver ( toDescription ( ) ) ; } } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; public final class FlowElement implements FlowElementAttributeProvider { private final Object identity ; private final FlowElementDescription description ; private final List < FlowElementInput > inputPorts ; private final List < FlowElementOutput > outputPorts ; private final Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > attributeOverride ; public FlowElement ( FlowElementDescription description ) { this ( new Object ( ) , description , Collections . < FlowElementAttribute > emptyList ( ) ) ; } public FlowElement ( FlowElementDescription description , Collection < ? extends FlowElementAttribute > attributeOverride ) { this ( new Object ( ) , description , attributeOverride ) ; } private FlowElement ( Object identity , FlowElementDescription description , Collection < ? extends FlowElementAttribute > attributeOverride ) { assert identity != null ; assert description != null ; assert attributeOverride != null ; this . identity = identity ; this . description = description ; this . inputPorts = new ArrayList < FlowElementInput > ( ) ; for ( FlowElementPortDescription port : description . getInputPorts ( ) ) { if ( port . getDirection ( ) != PortDirection . INPUT ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , port ) ) ; } inputPorts . add ( new FlowElementInput ( port , this ) ) ; } this . outputPorts = new ArrayList < FlowElementOutput > ( ) ; for ( FlowElementPortDescription port : description . getOutputPorts ( ) ) { if ( port . getDirection ( ) != PortDirection . OUTPUT ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , port ) ) ; } outputPorts . add ( new FlowElementOutput ( port , this ) ) ; } this . attributeOverride = new HashMap < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ( ) ; for ( FlowElementAttribute attribute : attributeOverride ) { this . attributeOverride . put ( attribute . getDeclaringClass ( ) , attribute ) ; } } public FlowElement copy ( ) { return new FlowElement ( identity , description , getAttributeOverride ( ) ) ; } public Object getIdentity ( ) { return identity ; } public FlowElementDescription getDescription ( ) { return description ; } public List < FlowElementInput > getInputPorts ( ) { return inputPorts ; } public List < FlowElementOutput > getOutputPorts ( ) { return outputPorts ; } public boolean hasAttribute ( FlowElementAttribute attribute ) { if ( attribute == null ) { throw new IllegalArgumentException ( "" ) ; } FlowElementAttribute own = getAttribute ( attribute . getDeclaringClass ( ) ) ; if ( own == null ) { return false ; } return own . equals ( attribute ) ; } @ Override public < T extends FlowElementAttribute > T getAttribute ( Class < T > attributeClass ) { if ( attributeClass == null ) { throw new IllegalArgumentException ( "" ) ; } FlowElementAttribute override = attributeOverride . get ( attributeClass ) ; if ( override != null ) { return attributeClass . cast ( override ) ; } return getDescription ( ) . getAttribute ( attributeClass ) ; } public void override ( FlowElementAttribute attribute ) { if ( attribute == null ) { throw new IllegalArgumentException ( "" ) ; } attributeOverride . put ( attribute . getDeclaringClass ( ) , attribute ) ; } public Collection < FlowElementAttribute > getAttributeOverride ( ) { return new ArrayList < FlowElementAttribute > ( attributeOverride . values ( ) ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getDescription ( ) . getName ( ) , getDescription ( ) . getKind ( ) . name ( ) . toLowerCase ( ) , String . valueOf ( hashCode ( ) ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . util . HashMap ; import java . util . Map ; import java . util . NoSuchElementException ; import com . asakusafw . vocabulary . flow . Source ; public class FlowElementResolver { private final FlowElement element ; private final Map < String , FlowElementInput > inputPorts ; private final Map < String , FlowElementOutput > outputPorts ; public FlowElementResolver ( FlowElement element ) { if ( element == null ) { throw new IllegalArgumentException ( "" ) ; } this . element = element ; this . inputPorts = new HashMap < String , FlowElementInput > ( ) ; this . outputPorts = new HashMap < String , FlowElementOutput > ( ) ; for ( FlowElementInput input : element . getInputPorts ( ) ) { inputPorts . put ( input . getDescription ( ) . getName ( ) , input ) ; } for ( FlowElementOutput output : element . getOutputPorts ( ) ) { outputPorts . put ( output . getDescription ( ) . getName ( ) , output ) ; } } public FlowElementResolver ( FlowElementDescription description ) { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } this . inputPorts = new HashMap < String , FlowElementInput > ( ) ; this . outputPorts = new HashMap < String , FlowElementOutput > ( ) ; this . element = new FlowElement ( description ) ; for ( FlowElementInput port : element . getInputPorts ( ) ) { inputPorts . put ( port . getDescription ( ) . getName ( ) , port ) ; } for ( FlowElementOutput port : element . getOutputPorts ( ) ) { outputPorts . put ( port . getDescription ( ) . getName ( ) , port ) ; } } public FlowElement getElement ( ) { return element ; } public FlowElementInput getInput ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } FlowElementInput port = inputPorts . get ( name ) ; if ( port == null ) { throw new NoSuchElementException ( name ) ; } return port ; } public FlowElementOutput getOutput ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } FlowElementOutput port = outputPorts . get ( name ) ; if ( port == null ) { throw new NoSuchElementException ( name ) ; } return port ; } public void resolveInput ( String name , Source < ? > source ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } FlowElementInput port = getInput ( name ) ; PortConnection . connect ( source . toOutputPort ( ) , port ) ; } public < T > Source < T > resolveOutput ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } FlowElementOutput port = getOutput ( name ) ; return new OutputDriver < T > ( port ) ; } public void setName ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } FlowElementDescription desc = element . getDescription ( ) ; desc . setName ( name ) ; } public static class OutputDriver < T > implements Source < T > { private final FlowElementOutput outputPort ; public OutputDriver ( FlowElementOutput outputPort ) { if ( outputPort == null ) { throw new IllegalArgumentException ( "" ) ; } this . outputPort = outputPort ; } @ Override public FlowElementOutput toOutputPort ( ) { return outputPort ; } } } package com . asakusafw . vocabulary . flow . graph ; public interface FlowElementAttribute { Class < ? extends FlowElementAttribute > getDeclaringClass ( ) ; } package com . asakusafw . vocabulary . flow . graph ; public enum Inline implements FlowElementAttribute { FORCE_AGGREGATE , KEEP_SEGREGATED , DEFAULT , } package com . asakusafw . vocabulary . flow . graph ; import java . lang . reflect . Method ; import java . text . MessageFormat ; import java . util . List ; public final class OperatorHelper implements FlowElementAttribute { private String name ; private List < Class < ? > > parameterTypes ; public OperatorHelper ( String name , List < Class < ? > > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . parameterTypes = parameterTypes ; } @ Override public Class < ? extends FlowElementAttribute > getDeclaringClass ( ) { return OperatorHelper . class ; } public String getName ( ) { return name ; } public List < Class < ? > > getParameterTypes ( ) { return parameterTypes ; } public Method toMethod ( OperatorDescription . Declaration owner ) { if ( owner == null ) { throw new IllegalArgumentException ( "" ) ; } Class < ? > [ ] params = parameterTypes . toArray ( new Class < ? > [ parameterTypes . size ( ) ] ) ; try { return owner . getDeclaring ( ) . getMethod ( name , params ) ; } catch ( Exception e ) { return null ; } } @ Override public String toString ( ) { return MessageFormat . format ( "" , name , parameterTypes ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; public class PortConnection { private final FlowElementOutput upstream ; private final FlowElementInput downstream ; private boolean connected ; PortConnection ( FlowElementOutput upstream , FlowElementInput downstream ) { if ( upstream == null ) { throw new IllegalArgumentException ( "" ) ; } if ( downstream == null ) { throw new IllegalArgumentException ( "" ) ; } FlowElementPortDescription up = upstream . getDescription ( ) ; FlowElementPortDescription down = downstream . getDescription ( ) ; if ( down . getDataType ( ) . equals ( up . getDataType ( ) ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , up . getName ( ) , up . getDataType ( ) , down . getName ( ) , down . getDataType ( ) ) ) ; } this . upstream = upstream ; this . downstream = downstream ; } public static void connect ( FlowElementOutput upstream , FlowElementInput downstream ) { if ( upstream == null ) { throw new IllegalArgumentException ( "" ) ; } if ( downstream == null ) { throw new IllegalArgumentException ( "" ) ; } if ( isConnected ( upstream , downstream ) ) { return ; } connect0 ( upstream , downstream ) ; } private static boolean isConnected ( FlowElementOutput upstream , FlowElementInput downstream ) { assert upstream != null ; assert downstream != null ; if ( upstream . getConnected ( ) . size ( ) > downstream . getConnected ( ) . size ( ) ) { for ( PortConnection c : downstream . getConnected ( ) ) { if ( c . getUpstream ( ) == upstream ) { return true ; } } } else { for ( PortConnection c : upstream . getConnected ( ) ) { if ( c . getDownstream ( ) == downstream ) { return true ; } } } return false ; } private static void connect0 ( FlowElementOutput upstream , FlowElementInput downstream ) { assert upstream != null ; assert downstream != null ; PortConnection connection = new PortConnection ( upstream , downstream ) ; upstream . register ( connection ) ; downstream . register ( connection ) ; connection . connected = true ; } public void disconnect ( ) { if ( isValid ( ) == false ) { return ; } upstream . unregister ( this ) ; downstream . unregister ( this ) ; } public boolean isValid ( ) { return connected ; } public FlowElementOutput getUpstream ( ) { return upstream ; } public FlowElementInput getDownstream ( ) { return downstream ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getUpstream ( ) , getDownstream ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . vocabulary . external . ImporterDescription ; public class InputDescription implements FlowElementDescription { public static final String OUTPUT_PORT_NAME = "" ; private static final Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ATTRIBUTES ; static { Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > map = new HashMap < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ( ) ; map . put ( FlowBoundary . class , FlowBoundary . STAGE ) ; ATTRIBUTES = Collections . unmodifiableMap ( map ) ; } private String name ; private FlowElementPortDescription port ; private ImporterDescription importerDescription ; public InputDescription ( String name , Type type ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . port = createPort ( type ) ; this . importerDescription = null ; } public InputDescription ( String name , ImporterDescription importer ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( importer == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . port = createPort ( importer . getModelType ( ) ) ; this . importerDescription = importer ; } private FlowElementPortDescription createPort ( Type type ) { assert type != null ; return new FlowElementPortDescription ( OUTPUT_PORT_NAME , type , PortDirection . OUTPUT ) ; } @ Override public String getName ( ) { return name ; } @ Override public void setName ( String newName ) { if ( newName == null ) { throw new IllegalArgumentException ( "" ) ; } throw new UnsupportedOperationException ( "" ) ; } public ImporterDescription getImporterDescription ( ) { return this . importerDescription ; } @ Override public FlowElementKind getKind ( ) { return FlowElementKind . INPUT ; } public Type getDataType ( ) { return port . getDataType ( ) ; } @ Override public List < FlowElementPortDescription > getInputPorts ( ) { return Collections . emptyList ( ) ; } @ Override public List < FlowElementPortDescription > getOutputPorts ( ) { return Collections . singletonList ( port ) ; } @ Override public List < FlowResourceDescription > getResources ( ) { return Collections . emptyList ( ) ; } @ Override public < T extends FlowElementAttribute > T getAttribute ( Class < T > attributeClass ) { if ( attributeClass == null ) { throw new IllegalArgumentException ( "" ) ; } Object attribute = ATTRIBUTES . get ( attributeClass ) ; return attributeClass . cast ( attribute ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , name , port . getDataType ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class ShuffleKey { static final Pattern ORDER_PATTERN = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE ) ; private List < String > groupProperties ; private List < Order > orderings ; public ShuffleKey ( List < String > groupProperties , List < Order > orderings ) { if ( groupProperties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( orderings == null ) { throw new IllegalArgumentException ( "" ) ; } this . groupProperties = Collections . unmodifiableList ( new ArrayList < String > ( groupProperties ) ) ; this . orderings = Collections . unmodifiableList ( new ArrayList < Order > ( orderings ) ) ; } public List < String > getGroupProperties ( ) { return groupProperties ; } public List < Order > getOrderings ( ) { return orderings ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + groupProperties . hashCode ( ) ; result = prime * result + orderings . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ShuffleKey other = ( ShuffleKey ) obj ; if ( ! groupProperties . equals ( other . groupProperties ) ) { return false ; } if ( ! orderings . equals ( other . orderings ) ) { return false ; } return true ; } public static class Order { private String property ; private Direction direction ; public Order ( String property , Direction direction ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } this . property = property ; this . direction = direction ; } public String getProperty ( ) { return property ; } public Direction getDirection ( ) { return direction ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + direction . hashCode ( ) ; result = prime * result + property . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Order other = ( Order ) obj ; if ( direction != other . direction ) { return false ; } if ( ! property . equals ( other . property ) ) { return false ; } return true ; } public static Order parse ( String string ) { if ( string == null ) { throw new IllegalArgumentException ( "" ) ; } Matcher matcher = ORDER_PATTERN . matcher ( string . trim ( ) ) ; if ( matcher . matches ( ) == false ) { return null ; } String property = matcher . group ( ) ; String directionString = matcher . group ( ) ; if ( directionString == null ) { return new Order ( property , Direction . ASC ) ; } directionString = directionString . trim ( ) ; if ( directionString . equalsIgnoreCase ( Direction . ASC . name ( ) ) ) { return new Order ( property , Direction . ASC ) ; } if ( directionString . equalsIgnoreCase ( Direction . DESC . name ( ) ) ) { return new Order ( property , Direction . DESC ) ; } return null ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getProperty ( ) , getDirection ( ) . name ( ) ) ; } } public enum Direction { ASC , DESC , } } package com . asakusafw . vocabulary . flow . graph ; import java . lang . annotation . Annotation ; import java . lang . reflect . Method ; import java . lang . reflect . Type ; import java . text . MessageFormat ; import java . util . ArrayList ; 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 com . asakusafw . vocabulary . flow . Source ; public class OperatorDescription implements FlowElementDescription { private final Declaration declaration ; private final List < FlowElementPortDescription > inputPorts ; private final List < FlowElementPortDescription > outputPorts ; private final List < FlowResourceDescription > resources ; private final List < Parameter > parameters ; private final Map < Class < ? extends FlowElementAttribute > , FlowElementAttribute > attributes ; private String name ; public OperatorDescription ( Declaration declaration , List < FlowElementPortDescription > inputPorts , List < FlowElementPortDescription > outputPorts , List < FlowResourceDescription > resources , List < Parameter > parameters , List < FlowElementAttribute > attributes ) { if ( declaration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( inputPorts == null ) { throw new IllegalArgumentException ( "" ) ; } if ( outputPorts == null ) { throw new IllegalArgumentException ( "" ) ; } if ( resources == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameters == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } this . declaration = declaration ; this . inputPorts = Collections . unmodifiableList ( new ArrayList < FlowElementPortDescription > ( inputPorts ) ) ; this . outputPorts = Collections . unmodifiableList ( new ArrayList < FlowElementPortDescription > ( outputPorts ) ) ; this . resources = Collections . unmodifiableList ( new ArrayList < FlowResourceDescription > ( resources ) ) ; this . parameters = Collections . unmodifiableList ( new ArrayList < Parameter > ( parameters ) ) ; this . attributes = new HashMap < Class < ? extends FlowElementAttribute > , FlowElementAttribute > ( ) ; for ( FlowElementAttribute attribute : attributes ) { this . attributes . put ( attribute . getDeclaringClass ( ) , attribute ) ; } } @ Override public FlowElementKind getKind ( ) { return FlowElementKind . OPERATOR ; } public Declaration getDeclaration ( ) { return declaration ; } @ Override public String getName ( ) { if ( name == null ) { return MessageFormat . format ( "" , declaration . getDeclaring ( ) . getSimpleName ( ) , declaration . getName ( ) ) ; } return name ; } @ Override public void setName ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } @ Override public List < FlowElementPortDescription > getInputPorts ( ) { return inputPorts ; } @ Override public List < FlowElementPortDescription > getOutputPorts ( ) { return outputPorts ; } @ Override public List < FlowResourceDescription > getResources ( ) { return resources ; } public List < Parameter > getParameters ( ) { return parameters ; } @ Override public < T extends FlowElementAttribute > T getAttribute ( Class < T > attributeClass ) { if ( attributeClass == null ) { throw new IllegalArgumentException ( "" ) ; } Object attribute = attributes . get ( attributeClass ) ; return attributeClass . cast ( attribute ) ; } public Set < FlowElementAttribute > getAttributes ( ) { return new HashSet < FlowElementAttribute > ( attributes . values ( ) ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getDeclaration ( ) , getParameters ( ) ) ; } public static class Declaration { private final Class < ? extends Annotation > annotationType ; private final Class < ? > declaring ; private final Class < ? > implementing ; private final String name ; private final List < Class < ? > > parameterTypes ; public Declaration ( Class < ? extends Annotation > annotationType , Class < ? > declaring , Class < ? > implementing , String name , List < Class < ? > > parameterTypes ) { if ( annotationType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( declaring == null ) { throw new IllegalArgumentException ( "" ) ; } if ( implementing == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } this . annotationType = annotationType ; this . declaring = declaring ; this . implementing = implementing ; this . name = name ; this . parameterTypes = parameterTypes ; } public Class < ? extends Annotation > getAnnotationType ( ) { return annotationType ; } public Class < ? > getDeclaring ( ) { return declaring ; } public Class < ? > getImplementing ( ) { return implementing ; } public String getName ( ) { return name ; } public List < Class < ? > > getParameterTypes ( ) { return parameterTypes ; } public Method toMethod ( ) { Class < ? > [ ] params = parameterTypes . toArray ( new Class < ? > [ parameterTypes . size ( ) ] ) ; try { return declaring . getMethod ( name , params ) ; } catch ( Exception e ) { return null ; } } @ Override public String toString ( ) { return MessageFormat . format ( "" , declaring . getName ( ) , name , parameterTypes ) ; } } public static class Parameter { private final String name ; private final Type type ; private final Object value ; public Parameter ( String name , Type type , Object value ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . type = type ; this . value = value ; } public String getName ( ) { return name ; } public Type getType ( ) { return type ; } public Object getValue ( ) { return value ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getName ( ) , getType ( ) , getValue ( ) ) ; } } public static class Builder { private final Class < ? extends Annotation > annotationType ; private Class < ? > declaring ; private Class < ? > implementing ; private String name ; private final List < Class < ? > > parameterTypes ; private final List < FlowElementPortDescription > inputPorts ; private final List < FlowElementPortDescription > outputPorts ; private final List < FlowResourceDescription > resources ; private final List < Parameter > parameters ; private final List < FlowElementAttribute > attributes ; public Builder ( Class < ? extends Annotation > annotationType ) { if ( annotationType == null ) { throw new IllegalArgumentException ( "" ) ; } this . annotationType = annotationType ; this . parameterTypes = new ArrayList < Class < ? > > ( ) ; this . inputPorts = new ArrayList < FlowElementPortDescription > ( ) ; this . outputPorts = new ArrayList < FlowElementPortDescription > ( ) ; this . resources = new ArrayList < FlowResourceDescription > ( ) ; this . parameters = new ArrayList < OperatorDescription . Parameter > ( ) ; this . attributes = new ArrayList < FlowElementAttribute > ( ) ; } public Builder declare ( Class < ? > operatorClass , Class < ? > implementorClass , String methodName ) { if ( operatorClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( implementorClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( methodName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( this . declaring != null ) { throw new IllegalStateException ( ) ; } this . declaring = operatorClass ; this . implementing = implementorClass ; this . name = methodName ; return this ; } public Builder declareParameter ( Class < ? > parameterType ) { if ( parameterType == null ) { throw new IllegalArgumentException ( "" ) ; } this . parameterTypes . add ( parameterType ) ; return this ; } public Builder addInput ( String portName , Type dataType ) { if ( portName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } inputPorts . add ( new FlowElementPortDescription ( portName , dataType , PortDirection . INPUT ) ) ; return this ; } public Builder addInput ( String portName , Source < ? > typeReference ) { if ( portName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( typeReference == null ) { throw new IllegalArgumentException ( "" ) ; } return addInput ( portName , typeReference . toOutputPort ( ) . getDescription ( ) . getDataType ( ) ) ; } public Builder addInput ( String portName , Type dataType , ShuffleKey key ) { if ( portName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } inputPorts . add ( new FlowElementPortDescription ( portName , dataType , key ) ) ; return this ; } public Builder addInput ( String portName , Source < ? > typeReference , ShuffleKey key ) { if ( portName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( typeReference == null ) { throw new IllegalArgumentException ( "" ) ; } if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } return addInput ( portName , typeReference . toOutputPort ( ) . getDescription ( ) . getDataType ( ) , key ) ; } public Builder addOutput ( String portName , Type dataType ) { if ( portName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataType == null ) { throw new IllegalArgumentException ( "" ) ; } outputPorts . add ( new FlowElementPortDescription ( portName , dataType , PortDirection . OUTPUT ) ) ; return this ; } public Builder addOutput ( String portName , Source < ? > typeReference ) { if ( portName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( typeReference == null ) { throw new IllegalArgumentException ( "" ) ; } return addOutput ( portName , typeReference . toOutputPort ( ) . getDescription ( ) . getDataType ( ) ) ; } public Builder addResource ( FlowResourceDescription resource ) { if ( resource == null ) { throw new IllegalArgumentException ( "" ) ; } resources . add ( resource ) ; return this ; } public Builder addParameter ( String parameterName , Type parameterType , Object argument ) { if ( parameterName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterType == null ) { throw new IllegalArgumentException ( "" ) ; } parameters . add ( new Parameter ( parameterName , parameterType , argument ) ) ; return this ; } public Builder addAttribute ( FlowElementAttribute attribute ) { if ( attribute == null ) { throw new IllegalArgumentException ( "" ) ; } attributes . add ( attribute ) ; return this ; } public OperatorDescription toDescription ( ) { return new OperatorDescription ( new Declaration ( annotationType , declaring , implementing , name , parameterTypes ) , inputPorts , outputPorts , resources , parameters , attributes ) ; } public FlowElementResolver toResolver ( ) { return new FlowElementResolver ( toDescription ( ) ) ; } } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; public final class FlowElementOutput extends FlowElementPort { public FlowElementOutput ( FlowElementPortDescription description , FlowElement owner ) { super ( description , owner ) ; } public Collection < FlowElementInput > getOpposites ( ) { Collection < FlowElementInput > results = new ArrayList < FlowElementInput > ( ) ; for ( PortConnection conn : getConnected ( ) ) { results . add ( conn . getDownstream ( ) ) ; } return results ; } public Collection < FlowElementInput > disconnectAll ( ) { Collection < FlowElementInput > results = new ArrayList < FlowElementInput > ( ) ; for ( PortConnection conn : new ArrayList < PortConnection > ( getConnected ( ) ) ) { results . add ( conn . getDownstream ( ) ) ; conn . disconnect ( ) ; } return results ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getDescription ( ) . getName ( ) , getOwner ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . text . MessageFormat ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . Source ; public final class FlowOut < T > implements Out < T > { private OutputDescription description ; private FlowElementResolver resolver ; public FlowOut ( OutputDescription description ) { if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } this . description = description ; this . resolver = new FlowElementResolver ( description ) ; } public static < T > FlowOut < T > newInstance ( OutputDescription description ) { return new FlowOut < T > ( description ) ; } public OutputDescription getDescription ( ) { return description ; } public FlowElement getFlowElement ( ) { return resolver . getElement ( ) ; } @ Override public void add ( Source < T > source ) { PortConnection . connect ( source . toOutputPort ( ) , this . toInputPort ( ) ) ; } public FlowElementInput toInputPort ( ) { return resolver . getInput ( OutputDescription . INPUT_PORT_NAME ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getDescription ( ) , getFlowElement ( ) ) ; } } package com . asakusafw . vocabulary . flow . graph ; import java . util . List ; public interface FlowElementDescription extends FlowElementAttributeProvider { FlowElementKind getKind ( ) ; String getName ( ) ; void setName ( String newName ) ; List < FlowElementPortDescription > getInputPorts ( ) ; List < FlowElementPortDescription > getOutputPorts ( ) ; List < FlowResourceDescription > getResources ( ) ; } package com . asakusafw . vocabulary . flow ; import java . util . concurrent . atomic . AtomicBoolean ; public abstract class FlowDescription { private final AtomicBoolean described = new AtomicBoolean ( false ) ; public final void start ( ) { if ( described . compareAndSet ( false , true ) == false ) { return ; } describe ( ) ; } protected abstract void describe ( ) ; public boolean isJobFlow ( ) { return isJobFlow ( getClass ( ) ) ; } public boolean isFlowPart ( ) { return isFlowPart ( getClass ( ) ) ; } public static boolean isJobFlow ( Class < ? extends FlowDescription > aClass ) { if ( aClass == null ) { throw new IllegalArgumentException ( "" ) ; } return aClass . isAnnotationPresent ( JobFlow . class ) ; } public static String getJobFlowName ( Class < ? extends FlowDescription > aClass ) { if ( aClass == null ) { throw new IllegalArgumentException ( "" ) ; } JobFlow jobflow = aClass . getAnnotation ( JobFlow . class ) ; if ( jobflow == null ) { return null ; } return jobflow . name ( ) ; } public boolean isFlowPart ( Class < ? extends FlowDescription > aClass ) { if ( aClass == null ) { throw new IllegalArgumentException ( "" ) ; } return aClass . isAnnotationPresent ( FlowPart . class ) ; } } package com . asakusafw . vocabulary . flow ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface JobFlow { String name ( ) ; } package com . asakusafw . vocabulary . flow ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import com . asakusafw . vocabulary . external . ImporterDescription ; @ Target ( ElementType . PARAMETER ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Import { String name ( ) ; Class < ? extends ImporterDescription > description ( ) ; } package com . asakusafw . vocabulary . flow . testing ; package com . asakusafw . vocabulary . flow . testing ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; public class MockOut < T > implements Out < T > { private FlowElementResolver resolver ; public MockOut ( Class < T > type , String name ) { OutputDescription desc = new OutputDescription ( name , type ) ; resolver = new FlowElementResolver ( desc ) ; } public static < T > MockOut < T > of ( Class < T > type , String name ) { return new MockOut < T > ( type , name ) ; } @ Override public void add ( Source < T > source ) { PortConnection . connect ( source . toOutputPort ( ) , resolver . getInput ( OutputDescription . INPUT_PORT_NAME ) ) ; } public FlowElement toElement ( ) { return resolver . getElement ( ) ; } } package com . asakusafw . vocabulary . flow . testing ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; public class MockIn < T > implements In < T > { private FlowElementResolver resolver ; public MockIn ( Class < T > type , String name ) { InputDescription desc = new InputDescription ( name , type ) ; resolver = new FlowElementResolver ( desc ) ; } public static < T > MockIn < T > of ( Class < T > type , String name ) { return new MockIn < T > ( type , name ) ; } @ Override public FlowElementOutput toOutputPort ( ) { return resolver . getOutput ( InputDescription . OUTPUT_PORT_NAME ) ; } public FlowElement toElement ( ) { return resolver . getElement ( ) ; } } package com . asakusafw . vocabulary . flow . processor ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; public enum InputBuffer implements FlowElementAttribute { EXPAND , ESCAPE , } package com . asakusafw . vocabulary . flow . processor ; package com . asakusafw . vocabulary . flow . processor ; import com . asakusafw . vocabulary . flow . graph . FlowElementAttribute ; public enum PartialAggregation implements FlowElementAttribute { TOTAL , PARTIAL , DEFAULT , } package com . asakusafw . vocabulary . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Summarized { Term term ( ) ; @ Target ( { } ) public @ interface Term { Class < ? > source ( ) ; Folding [ ] foldings ( ) ; Key shuffle ( ) ; } @ Target ( { } ) public @ interface Folding { Aggregator aggregator ( ) ; String source ( ) ; String destination ( ) ; } public enum Aggregator { ANY , SUM , COUNT , MAX , MIN , } } package com . asakusafw . vocabulary . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Deprecated @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface DataModel { interface Interface < T > { String METHOD_NAME_COPY_FROM = "" ; void copyFrom ( T source ) ; } } package com . asakusafw . vocabulary . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Deprecated @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface JoinedModel { ModelRef from ( ) ; ModelRef join ( ) ; interface Interface < T , A , B > extends DataModel . Interface < T > { String METHOD_NAME_JOIN_FROM = "" ; String METHOD_NAME_SPLIT_INTO = "" ; void joinFrom ( A left , B right ) ; void splitInto ( A left , B right ) ; } } package com . asakusafw . vocabulary . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Deprecated @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface SummarizedModel { ModelRef from ( ) ; interface Interface < T , O > extends DataModel . Interface < T > { String METHOD_NAME_START_SUMMARIZATION = "" ; String METHOD_NAME_COMBINE_SUMMARIZATION = "" ; void startSummarization ( O original ) ; void combineSummarization ( T original ) ; } } package com . asakusafw . vocabulary . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( { ElementType . PARAMETER } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Key { String [ ] group ( ) ; String [ ] order ( ) default { } ; } package com . asakusafw . vocabulary . model ; package com . asakusafw . vocabulary . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Joined { Term [ ] terms ( ) ; @ Target ( { } ) public @ interface Term { Class < ? > source ( ) ; Mapping [ ] mappings ( ) ; Key shuffle ( ) ; } @ Target ( { } ) public @ interface Mapping { String source ( ) ; String destination ( ) ; } } package com . asakusafw . vocabulary . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . FIELD ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface ModelRef { Class < ? > type ( ) ; Key key ( ) ; } package com . asakusafw . vocabulary . model ; public @ interface Property { String name ( ) default "" ; Source from ( ) default @ Source ( declaring = void . class , name = "" ) ; Source join ( ) default @ Source ( declaring = void . class , name = "" ) ; Aggregator aggregator ( ) default Aggregator . IDENT ; public @ interface Source { Class < ? > declaring ( ) ; String name ( ) ; } public enum Aggregator { IDENT , SUM , COUNT , MAX , MIN , ; } } package com . asakusafw . vocabulary . model ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Deprecated @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface TableModel { String name ( ) ; String [ ] columns ( ) default "" ; String [ ] primary ( ) ; interface Interface < T > extends DataModel . Interface < T > { } } package com . asakusafw . vocabulary . batch ; package com . asakusafw . vocabulary . batch ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface Batch { String name ( ) ; } package com . asakusafw . vocabulary . batch ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import java . util . TreeMap ; public class ScriptWorkDescription extends WorkDescription { public static final String K_NAME = "" ; public static final String K_COMMAND = "" ; public static final String K_PROFILE = "" ; public static final String K_ENVIRONMENT_PREFIX = "" ; private String name ; private String command ; private String profileName ; private Map < String , String > variables ; public ScriptWorkDescription ( String name , String command , String profileName , Map < String , String > variables ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( command == null ) { throw new IllegalArgumentException ( "" ) ; } if ( profileName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( variables == null ) { throw new IllegalArgumentException ( "" ) ; } if ( isValidName ( name ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , command ) ) ; } this . name = name ; this . command = command ; this . profileName = profileName ; this . variables = Collections . unmodifiableSortedMap ( new TreeMap < String , String > ( variables ) ) ; } @ Override public String getName ( ) { return name ; } public String getCommand ( ) { return command ; } public String getProfileName ( ) { return profileName ; } public Map < String , String > getVariables ( ) { return variables ; } public static ScriptWorkDescription load ( Class < ? > context , String path ) throws IOException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } InputStream stream = context . getResourceAsStream ( path ) ; if ( stream == null ) { throw new FileNotFoundException ( path ) ; } Properties properties = new Properties ( ) ; try { properties . load ( stream ) ; } finally { stream . close ( ) ; } return load ( properties ) ; } private static ScriptWorkDescription load ( Properties properties ) { assert properties != null ; String name = properties . getProperty ( K_NAME ) ; String command = properties . getProperty ( K_COMMAND ) ; String profile = properties . getProperty ( K_PROFILE ) ; properties . remove ( K_COMMAND ) ; properties . remove ( K_PROFILE ) ; Map < String , String > env = new HashMap < String , String > ( ) ; for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { if ( ( entry . getKey ( ) instanceof String ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , entry . getKey ( ) , entry . getKey ( ) . getClass ( ) . getName ( ) ) ) ; } if ( ( entry . getValue ( ) instanceof String ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , entry . getValue ( ) , entry . getValue ( ) . getClass ( ) . getName ( ) ) ) ; } String key = ( String ) entry . getKey ( ) ; if ( key . startsWith ( K_ENVIRONMENT_PREFIX ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , entry . getKey ( ) , K_ENVIRONMENT_PREFIX ) ) ; } key = key . substring ( K_ENVIRONMENT_PREFIX . length ( ) ) ; String value = ( String ) entry . getValue ( ) ; env . put ( key , value ) ; } return new ScriptWorkDescription ( name , command , profile , env ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + name . hashCode ( ) ; result = prime * result + command . hashCode ( ) ; result = prime * result + profileName . hashCode ( ) ; result = prime * result + variables . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ScriptWorkDescription other = ( ScriptWorkDescription ) obj ; if ( name . equals ( other . name ) == false ) { return false ; } if ( command . equals ( other . command ) == false ) { return false ; } if ( profileName . equals ( other . profileName ) == false ) { return false ; } if ( variables . equals ( other . variables ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getCommand ( ) , getProfileName ( ) ) ; } } package com . asakusafw . vocabulary . batch ; import java . text . MessageFormat ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . JobFlow ; public class JobFlowWorkDescription extends WorkDescription { private String name ; private Class < ? extends FlowDescription > flowClass ; public JobFlowWorkDescription ( Class < ? extends FlowDescription > flowClass ) { if ( flowClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( FlowDescription . isJobFlow ( flowClass ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , flowClass . getName ( ) , JobFlow . class . getSimpleName ( ) ) ) ; } this . name = FlowDescription . getJobFlowName ( flowClass ) ; if ( isValidName ( name ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , flowClass . getName ( ) ) ) ; } this . flowClass = flowClass ; } @ Override public String getName ( ) { return name ; } public Class < ? extends FlowDescription > getFlowClass ( ) { return flowClass ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + flowClass . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } JobFlowWorkDescription other = ( JobFlowWorkDescription ) obj ; if ( flowClass . equals ( other . flowClass ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getFlowClass ( ) . getName ( ) ) ; } } package com . asakusafw . vocabulary . batch ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public final class Work { private BatchDescription declaring ; private WorkDescription description ; private List < Work > dependencies ; public Work ( BatchDescription declaring , WorkDescription description , List < Work > dependencies ) { if ( declaring == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dependencies == null ) { throw new IllegalArgumentException ( "" ) ; } this . declaring = declaring ; this . description = description ; this . dependencies = Collections . unmodifiableList ( new ArrayList < Work > ( dependencies ) ) ; } public BatchDescription getDeclaring ( ) { return declaring ; } public WorkDescription getDescription ( ) { return description ; } public List < Work > getDependencies ( ) { return dependencies ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , description , declaring . getClass ( ) . getName ( ) , dependencies ) ; } } package com . asakusafw . vocabulary . batch ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . concurrent . atomic . AtomicBoolean ; import com . asakusafw . vocabulary . flow . FlowDescription ; public abstract class BatchDescription { static final Work [ ] NOTHING = new Work [ ] ; private Map < String , Work > works = new LinkedHashMap < String , Work > ( ) ; private DependencyBuilder adding ; private final AtomicBoolean described = new AtomicBoolean ( false ) ; public final void start ( ) { if ( described . compareAndSet ( false , true ) == false ) { return ; } describe ( ) ; checkFlushed ( ) ; } protected abstract void describe ( ) ; protected DependencyBuilder run ( String scriptDefinition ) { if ( scriptDefinition == null ) { throw new IllegalArgumentException ( "" ) ; } ScriptWorkDescription desc ; try { desc = ScriptWorkDescription . load ( getClass ( ) , scriptDefinition ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , scriptDefinition , getClass ( ) . getName ( ) ) , e ) ; } return run0 ( desc ) ; } protected DependencyBuilder run ( Class < ? extends FlowDescription > jobflow ) { if ( jobflow == null ) { throw new IllegalArgumentException ( "" ) ; } return run0 ( new JobFlowWorkDescription ( jobflow ) ) ; } private DependencyBuilder run0 ( WorkDescription description ) { assert description != null ; checkFlushed ( ) ; DependencyBuilder builder = new DependencyBuilder ( description ) ; adding = builder ; return builder ; } private void checkFlushed ( ) { if ( adding != null ) { throw new IllegalStateException ( MessageFormat . format ( "" , adding . description ) ) ; } } public Collection < Work > getWorks ( ) { return new ArrayList < Work > ( works . values ( ) ) ; } Work register ( Work work ) { assert work != null ; String name = work . getDescription ( ) . getName ( ) ; if ( works . containsKey ( name ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , name , work . getDescription ( ) , works . get ( name ) . getDescription ( ) ) ) ; } works . put ( name , work ) ; adding = null ; return work ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getClass ( ) . getName ( ) , works ) ; } protected class DependencyBuilder { final WorkDescription description ; DependencyBuilder ( WorkDescription description ) { assert description != null ; this . description = description ; } public Work soon ( ) { return register ( new Work ( BatchDescription . this , description , Collections . < Work > emptyList ( ) ) ) ; } public Work after ( Work dependency , Work ... rest ) { if ( dependency == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rest == null ) { throw new IllegalArgumentException ( "" ) ; } List < Work > dependencies = new ArrayList < Work > ( ) ; dependencies . add ( dependency ) ; Collections . addAll ( dependencies , rest ) ; for ( Work p : dependencies ) { if ( dependency . getDeclaring ( ) != BatchDescription . this ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , p ) ) ; } } return register ( new Work ( BatchDescription . this , description , dependencies ) ) ; } } } package com . asakusafw . vocabulary . batch ; import java . util . regex . Pattern ; public abstract class WorkDescription { public abstract String getName ( ) ; private static final Pattern VALID_NAME = Pattern . compile ( "" ) ; protected static boolean isValidName ( String name ) { if ( name == null ) { return false ; } return VALID_NAME . matcher ( name ) . matches ( ) ; } } package com . asakusafw . vocabulary . flow . util ; import static com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . HashSet ; import java . util . LinkedList ; import java . util . Set ; import org . hamcrest . Matcher ; import org . hamcrest . Matchers ; import org . junit . Test ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . FlowElement ; import com . asakusafw . vocabulary . flow . graph . FlowElementInput ; import com . asakusafw . vocabulary . flow . graph . FlowElementOutput ; import com . asakusafw . vocabulary . flow . graph . PortConnection ; import com . asakusafw . vocabulary . flow . testing . MockIn ; import com . asakusafw . vocabulary . flow . testing . MockOut ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Checkpoint ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory . Empty ; public class CoreOperatorFactoryTest { MockIn < String > in = new MockIn < String > ( String . class , "" ) ; MockIn < String > in2 = new MockIn < String > ( String . class , "" ) ; MockOut < String > out = new MockOut < String > ( String . class , "" ) ; @ Test public void empty ( ) { CoreOperatorFactory f = new CoreOperatorFactory ( ) ; Empty < String > empty = f . empty ( String . class ) ; out . add ( empty ) ; Graph < String > graph = toGraph ( ) ; assertThat ( graph . getConnected ( "" ) , connected ( ) ) ; assertThat ( graph . getConnected ( "" ) , connected ( ) ) ; assertThat ( graph . getConnected ( EMPTY_NAME ) , connected ( "" ) ) ; } @ Test public void stop ( ) { CoreOperatorFactory f = new CoreOperatorFactory ( ) ; f . stop ( in ) ; Graph < String > graph = toGraph ( ) ; assertThat ( graph . getConnected ( "" ) , connected ( STOP_NAME ) ) ; assertThat ( graph . getConnected ( "" ) , connected ( ) ) ; } @ Test public void confluent ( ) { CoreOperatorFactory f = new CoreOperatorFactory ( ) ; out . add ( f . confluent ( in , in2 ) ) ; Graph < String > graph = toGraph ( ) ; assertThat ( graph . getConnected ( "" ) , connected ( CONFLUENT_NAME ) ) ; assertThat ( graph . getConnected ( "" ) , connected ( CONFLUENT_NAME ) ) ; assertThat ( graph . getConnected ( CONFLUENT_NAME ) , connected ( "" ) ) ; } @ Test public void checkpoint ( ) { CoreOperatorFactory f = new CoreOperatorFactory ( ) ; Checkpoint < String > cp = f . checkpoint ( in ) ; out . add ( cp ) ; Graph < String > graph = toGraph ( ) ; assertThat ( graph . getConnected ( "" ) , connected ( CHECKPOINT_NAME ) ) ; assertThat ( graph . getConnected ( "" ) , connected ( ) ) ; assertThat ( graph . getConnected ( CHECKPOINT_NAME ) , connected ( "" ) ) ; } private Matcher < ? super Set < String > > connected ( String ... names ) { return Matchers . < Set < String > > is ( new HashSet < String > ( Arrays . asList ( names ) ) ) ; } private Graph < String > toGraph ( ) { Set < String > saw = new HashSet < String > ( ) ; LinkedList < FlowElement > work = new LinkedList < FlowElement > ( ) ; work . add ( in . toElement ( ) ) ; work . add ( in2 . toElement ( ) ) ; work . add ( out . toElement ( ) ) ; Graph < String > graph = Graphs . newInstance ( ) ; while ( work . isEmpty ( ) == false ) { FlowElement elem = work . removeFirst ( ) ; String self = elem . getDescription ( ) . getName ( ) ; if ( saw . contains ( self ) ) { continue ; } saw . add ( self ) ; for ( FlowElementInput input : elem . getInputPorts ( ) ) { for ( PortConnection conn : input . getConnected ( ) ) { work . add ( conn . getUpstream ( ) . getOwner ( ) ) ; } } for ( FlowElementOutput output : elem . getOutputPorts ( ) ) { for ( PortConnection conn : output . getConnected ( ) ) { FlowElement opposite = conn . getDownstream ( ) . getOwner ( ) ; work . add ( opposite ) ; String dest = opposite . getDescription ( ) . getName ( ) ; graph . addEdge ( self , dest ) ; } } } return graph ; } } package com . asakusafw . vocabulary . batch ; public class InvalidNameBatch extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlowInvalidName . class ) . soon ( ) ; } } package com . asakusafw . vocabulary . batch ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . JobFlow ; @ JobFlow ( name = "" ) public class JobFlow4 extends FlowDescription { @ Override protected void describe ( ) { return ; } } package com . asakusafw . vocabulary . batch ; public class NameConflictBatch extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; run ( JobFlow1Copy . class ) . soon ( ) ; } } package com . asakusafw . vocabulary . batch ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class JobFlowNotAnnotated extends FlowDescription { @ Override protected void describe ( ) { return ; } } package com . asakusafw . vocabulary . batch ; public class MiddleUnderConstructionBatch extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; run ( JobFlow2 . class ) ; run ( JobFlow3 . class ) . soon ( ) ; } } package com . asakusafw . vocabulary . batch ; public class NotAnnotatedJobFlowBatch extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlowNotAnnotated . class ) . soon ( ) ; } } package com . asakusafw . vocabulary . batch ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . JobFlow ; @ JobFlow ( name = "" ) public class JobFlow3 extends FlowDescription { @ Override protected void describe ( ) { return ; } } package com . asakusafw . vocabulary . batch ; public class LastUnderConstructionBatch extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; run ( JobFlow2 . class ) . soon ( ) ; run ( JobFlow3 . class ) ; } } package com . asakusafw . vocabulary . batch ; public class ListBatch extends BatchDescription { @ Override protected void describe ( ) { Work jf1 = run ( JobFlow1 . class ) . soon ( ) ; Work jf2 = run ( JobFlow2 . class ) . after ( jf1 ) ; run ( JobFlow3 . class ) . after ( jf2 ) ; } } package com . asakusafw . vocabulary . batch ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . JobFlow ; @ JobFlow ( name = "" ) public class JobFlow2 extends FlowDescription { @ Override protected void describe ( ) { return ; } } package com . asakusafw . vocabulary . batch ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . JobFlow ; @ JobFlow ( name = "" ) public class JobFlow1Copy extends FlowDescription { @ Override protected void describe ( ) { return ; } } package com . asakusafw . vocabulary . batch ; public class SimpleBatch extends BatchDescription { @ Override protected void describe ( ) { run ( JobFlow1 . class ) . soon ( ) ; } } package com . asakusafw . vocabulary . batch ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . JobFlow ; @ JobFlow ( name = "" ) public class JobFlowInvalidName extends FlowDescription { @ Override protected void describe ( ) { return ; } } package com . asakusafw . vocabulary . batch ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import org . hamcrest . Matcher ; import org . junit . Test ; import com . asakusafw . vocabulary . flow . FlowDescription ; public class BatchDescriptionTest { @ Test public void simple ( ) { Collection < Work > works = exec ( new SimpleBatch ( ) ) . getWorks ( ) ; assertThat ( works . size ( ) , is ( ) ) ; assertThat ( dependencies ( works , JobFlow1 . class ) , isJust ( ) ) ; } @ Test public void list ( ) { Collection < Work > works = exec ( new ListBatch ( ) ) . getWorks ( ) ; assertThat ( works . size ( ) , is ( ) ) ; assertThat ( dependencies ( works , JobFlow1 . class ) , isJust ( ) ) ; assertThat ( dependencies ( works , JobFlow2 . class ) , isJust ( JobFlow1 . class ) ) ; assertThat ( dependencies ( works , JobFlow3 . class ) , isJust ( JobFlow2 . class ) ) ; } @ Test public void graph ( ) { Collection < Work > works = exec ( new GraphBatch ( ) ) . getWorks ( ) ; assertThat ( works . size ( ) , is ( ) ) ; assertThat ( dependencies ( works , JobFlow1 . class ) , isJust ( ) ) ; assertThat ( dependencies ( works , JobFlow2 . class ) , isJust ( JobFlow1 . class ) ) ; assertThat ( dependencies ( works , JobFlow3 . class ) , isJust ( JobFlow1 . class ) ) ; assertThat ( dependencies ( works , JobFlow4 . class ) , isJust ( JobFlow2 . class , JobFlow3 . class ) ) ; } @ Test ( expected = IllegalStateException . class ) public void nameConflict ( ) { exec ( new NameConflictBatch ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void invalidName ( ) { exec ( new InvalidNameBatch ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void notAnnotatedJobFlow ( ) { exec ( new NotAnnotatedJobFlowBatch ( ) ) ; } @ Test ( expected = IllegalStateException . class ) public void underConstruction_middle ( ) { exec ( new MiddleUnderConstructionBatch ( ) ) ; } @ Test ( expected = IllegalStateException . class ) public void underConstruction_last ( ) { exec ( new LastUnderConstructionBatch ( ) ) ; } private Set < Class < ? > > dependencies ( Collection < Work > works , Class < ? extends FlowDescription > target ) { Work found = findWork ( works , target ) ; Set < Class < ? > > result = new HashSet < Class < ? > > ( ) ; for ( Work work : found . getDependencies ( ) ) { result . add ( asJobFlow ( work ) ) ; } return result ; } private Class < ? > asJobFlow ( Work work ) { assertThat ( work . getDescription ( ) , instanceOf ( JobFlowWorkDescription . class ) ) ; return ( ( JobFlowWorkDescription ) work . getDescription ( ) ) . getFlowClass ( ) ; } private Work findWork ( Collection < Work > works , Class < ? extends FlowDescription > target ) { JobFlowWorkDescription desc = new JobFlowWorkDescription ( target ) ; for ( Work work : works ) { if ( work . getDescription ( ) . equals ( desc ) ) { return work ; } } throw new AssertionError ( target + "" + works ) ; } private Matcher < ? super Set < Class < ? > > > isJust ( Class < ? > ... classes ) { Set < Class < ? > > result = new HashSet < Class < ? > > ( ) ; Collections . addAll ( result , classes ) ; return is ( result ) ; } private BatchDescription exec ( BatchDescription batch ) { batch . start ( ) ; return batch ; } } package com . asakusafw . vocabulary . batch ; public class GraphBatch extends BatchDescription { @ Override protected void describe ( ) { Work jf1 = run ( JobFlow1 . class ) . soon ( ) ; Work jf2 = run ( JobFlow2 . class ) . after ( jf1 ) ; Work jf3 = run ( JobFlow3 . class ) . after ( jf1 ) ; run ( JobFlow4 . class ) . after ( jf2 , jf3 ) ; } } package com . asakusafw . vocabulary . batch ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . JobFlow ; @ JobFlow ( name = "" ) public class JobFlow1 extends FlowDescription { @ Override protected void describe ( ) { return ; } } package com . asakusafw . vocabulary . bulkloader ; @ ColumnOrder ( value = { "" , "" , "" } ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) public class MockTableModel { } package com . asakusafw . vocabulary . bulkloader ; public class NoErrorModel { } package com . asakusafw . vocabulary . bulkloader ; @ ColumnOrder ( value = { "" , "" , "" , "" , "" } ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) public class MockErrorModel { } package com . asakusafw . vocabulary . bulkloader ; public class MockDbExporterDescription extends DbExporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return MockTableModel . class ; } } package com . asakusafw . vocabulary . bulkloader ; @ ColumnOrder ( value = { "" , "" , "" , "" , "" } ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) public class MockUnionModel { } package com . asakusafw . vocabulary . bulkloader ; import java . util . Arrays ; import java . util . List ; public class MockDupCheckDbExporterDescription extends DupCheckDbExporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return MockUnionModel . class ; } @ Override protected Class < ? > getNormalModelType ( ) { return MockTableModel . class ; } @ Override protected Class < ? > getErrorModelType ( ) { return MockErrorModel . class ; } @ Override protected List < String > getCheckColumnNames ( ) { return Arrays . asList ( "" ) ; } @ Override protected String getErrorCodeColumnName ( ) { return "" ; } @ Override protected String getErrorCodeValue ( ) { return "" ; } } package com . asakusafw . vocabulary . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import org . junit . Test ; public class DbExporterDescriptionTest { @ Test public void tableName ( ) { DbExporterDescription desc = new MockDbExporterDescription ( ) ; assertThat ( desc . getTableName ( ) , is ( "" ) ) ; } @ Test ( expected = RuntimeException . class ) public void tableName_invalid ( ) { DbExporterDescription desc = new InvalidDbExporterDescription ( ) ; desc . getTableName ( ) ; } @ Test public void columnNames ( ) { DbExporterDescription desc = new MockDbExporterDescription ( ) ; assertThat ( desc . getColumnNames ( ) , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test ( expected = RuntimeException . class ) public void columnNames_invalid ( ) { DbExporterDescription desc = new InvalidDbExporterDescription ( ) ; desc . getColumnNames ( ) ; } @ Test public void normalColumnNames ( ) { DbExporterDescription desc = new MockDbExporterDescription ( ) ; assertThat ( desc . getTargetColumnNames ( ) , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test ( expected = RuntimeException . class ) public void normalCames_invalid ( ) { DbExporterDescription desc = new InvalidDbExporterDescription ( ) ; desc . getTargetColumnNames ( ) ; } @ Test public void primaryKeyNames ( ) { DbExporterDescription desc = new MockDbExporterDescription ( ) ; assertThat ( desc . getPrimaryKeyNames ( ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test ( expected = RuntimeException . class ) public void primaryKeyNames_invalid ( ) { DbExporterDescription desc = new InvalidDbExporterDescription ( ) ; desc . getPrimaryKeyNames ( ) ; } @ Test public void duplicateRecordCheck ( ) { DbExporterDescription desc = new MockDbExporterDescription ( ) ; assertThat ( desc . getDuplicateRecordCheck ( ) , is ( nullValue ( ) ) ) ; } } package com . asakusafw . vocabulary . bulkloader ; public class InvalidDbExporterDescription extends DbExporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return NoTableModel . class ; } } package com . asakusafw . vocabulary . bulkloader ; public class NoTableModel { } package com . asakusafw . vocabulary . bulkloader ; import java . util . Arrays ; import java . util . List ; public class InvalidDupCheckDbExporterDescription extends DupCheckDbExporterDescription { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return NoTableModel . class ; } @ Override protected Class < ? > getNormalModelType ( ) { return NoTableModel . class ; } @ Override protected Class < ? > getErrorModelType ( ) { return NoErrorModel . class ; } @ Override protected List < String > getCheckColumnNames ( ) { return Arrays . asList ( "" ) ; } @ Override protected String getErrorCodeColumnName ( ) { return "" ; } @ Override protected String getErrorCodeValue ( ) { return "" ; } } package com . asakusafw . vocabulary . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import org . junit . Test ; import com . asakusafw . vocabulary . bulkloader . BulkLoadExporterDescription . DuplicateRecordCheck ; public class DupCheckDbExporterDescriptionTest { @ Test public void modelType ( ) { BulkLoadExporterDescription desc = new MockDupCheckDbExporterDescription ( ) ; assertThat ( desc . getModelType ( ) , equalTo ( ( Object ) MockUnionModel . class ) ) ; } @ Test public void tableName ( ) { BulkLoadExporterDescription desc = new MockDupCheckDbExporterDescription ( ) ; assertThat ( desc . getTableName ( ) , is ( "" ) ) ; } @ Test ( expected = RuntimeException . class ) public void tableName_invalid ( ) { BulkLoadExporterDescription desc = new InvalidDupCheckDbExporterDescription ( ) ; desc . getTableName ( ) ; } @ Test public void columnNames ( ) { BulkLoadExporterDescription desc = new MockDupCheckDbExporterDescription ( ) ; assertThat ( desc . getColumnNames ( ) , is ( Arrays . asList ( "" , "" , "" , "" , "" ) ) ) ; } @ Test ( expected = RuntimeException . class ) public void columnNames_invalid ( ) { BulkLoadExporterDescription desc = new InvalidDupCheckDbExporterDescription ( ) ; desc . getColumnNames ( ) ; } @ Test public void normalColumnNames ( ) { BulkLoadExporterDescription desc = new MockDupCheckDbExporterDescription ( ) ; assertThat ( desc . getTargetColumnNames ( ) , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test ( expected = RuntimeException . class ) public void normalColumnNames_invalid ( ) { BulkLoadExporterDescription desc = new InvalidDupCheckDbExporterDescription ( ) ; desc . getTargetColumnNames ( ) ; } @ Test public void primaryKeyNames ( ) { BulkLoadExporterDescription desc = new MockDupCheckDbExporterDescription ( ) ; assertThat ( desc . getPrimaryKeyNames ( ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test ( expected = RuntimeException . class ) public void primaryKeyNames_invalid ( ) { BulkLoadExporterDescription desc = new InvalidDupCheckDbExporterDescription ( ) ; desc . getPrimaryKeyNames ( ) ; } @ Test public void duplicateRecordCheck ( ) { BulkLoadExporterDescription desc = new MockDupCheckDbExporterDescription ( ) ; DuplicateRecordCheck dup = desc . getDuplicateRecordCheck ( ) ; assertThat ( dup , not ( nullValue ( ) ) ) ; assertThat ( dup . getTableName ( ) , is ( "" ) ) ; assertThat ( dup . getColumnNames ( ) , is ( Arrays . asList ( "" , "" , "" , "" ) ) ) ; assertThat ( dup . getCheckColumnNames ( ) , is ( Arrays . asList ( "" ) ) ) ; assertThat ( dup . getErrorCodeColumnName ( ) , is ( "" ) ) ; assertThat ( dup . getErrorCodeValue ( ) , is ( "" ) ) ; } @ Test ( expected = RuntimeException . class ) public void duplicateRecordCheck_invalid ( ) { BulkLoadExporterDescription desc = new InvalidDupCheckDbExporterDescription ( ) ; desc . getDuplicateRecordCheck ( ) ; } } package com . asakusafw . vocabulary . bulkloader ; import java . util . ArrayList ; import java . util . List ; public abstract class DupCheckDbExporterDescription extends BulkLoadExporterDescription { protected abstract Class < ? > getNormalModelType ( ) ; protected abstract Class < ? > getErrorModelType ( ) ; protected abstract List < String > getCheckColumnNames ( ) ; protected abstract String getErrorCodeColumnName ( ) ; protected abstract String getErrorCodeValue ( ) ; @ Override public final Class < ? > getTableModelClass ( ) { return getNormalModelType ( ) ; } @ Override public String getTableName ( ) { return getNormalTableName ( ) ; } protected String getNormalTableName ( ) { return AttributeHelper . getTableName ( getNormalModelType ( ) ) ; } protected String getErrorTableName ( ) { return AttributeHelper . getTableName ( getErrorModelType ( ) ) ; } @ Override public final List < String > getColumnNames ( ) { return AttributeHelper . getColumnNames ( getModelType ( ) ) ; } @ Override public List < String > getTargetColumnNames ( ) { return AttributeHelper . getColumnNames ( getNormalModelType ( ) ) ; } protected List < String > getErrorColumnNames ( ) { return AttributeHelper . getColumnNames ( getErrorModelType ( ) ) ; } @ Override public List < String > getPrimaryKeyNames ( ) { return AttributeHelper . getPrimaryKeyNames ( getNormalModelType ( ) ) ; } @ Override public final DuplicateRecordCheck getDuplicateRecordCheck ( ) { String errorTableName = getErrorTableName ( ) ; List < String > errorColumnNames = new ArrayList < String > ( getErrorColumnNames ( ) ) ; String errorCodeColumnName = getErrorCodeColumnName ( ) ; errorColumnNames . remove ( errorCodeColumnName ) ; return new DuplicateRecordCheck ( getErrorModelType ( ) , errorTableName , errorColumnNames , getCheckColumnNames ( ) , errorCodeColumnName , getErrorCodeValue ( ) ) ; } } package com . asakusafw . vocabulary . bulkloader ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( { ElementType . TYPE , ElementType . FIELD , ElementType . METHOD } ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface OriginalName { String value ( ) ; } package com . asakusafw . vocabulary . bulkloader ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface ColumnOrder { String [ ] value ( ) ; } package com . asakusafw . vocabulary . bulkloader ; import java . util . List ; import com . asakusafw . vocabulary . external . ExporterDescription ; public abstract class BulkLoadExporterDescription implements ExporterDescription { public abstract String getTargetName ( ) ; public abstract Class < ? > getTableModelClass ( ) ; public abstract String getTableName ( ) ; public abstract List < String > getColumnNames ( ) ; public abstract List < String > getTargetColumnNames ( ) ; public abstract List < String > getPrimaryKeyNames ( ) ; public DuplicateRecordCheck getDuplicateRecordCheck ( ) { return null ; } public static class DuplicateRecordCheck { private final Class < ? > tableModelClass ; private final String tableName ; private final List < String > columnNames ; private final List < String > checkColumnNames ; private final String errorCodeColumnName ; private final String errorCodeValue ; public DuplicateRecordCheck ( Class < ? > tableModelClass , String tableName , List < String > columnNames , List < String > checkColumnNames , String errorCodeColumnName , String errorCodeValue ) { if ( tableModelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } if ( checkColumnNames == null ) { throw new IllegalArgumentException ( "" ) ; } if ( errorCodeColumnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( errorCodeValue == null ) { throw new IllegalArgumentException ( "" ) ; } this . tableModelClass = tableModelClass ; this . tableName = tableName ; this . columnNames = columnNames ; this . checkColumnNames = checkColumnNames ; this . errorCodeColumnName = errorCodeColumnName ; this . errorCodeValue = errorCodeValue ; } public Class < ? > getTableModelClass ( ) { return tableModelClass ; } public String getTableName ( ) { return tableName ; } public List < String > getColumnNames ( ) { return columnNames ; } public List < String > getCheckColumnNames ( ) { return checkColumnNames ; } public String getErrorCodeColumnName ( ) { return errorCodeColumnName ; } public String getErrorCodeValue ( ) { return errorCodeValue ; } } } package com . asakusafw . vocabulary . bulkloader ; import java . util . List ; public abstract class DbExporterDescription extends BulkLoadExporterDescription { @ Override public final Class < ? > getTableModelClass ( ) { return getModelType ( ) ; } @ Override public String getTableName ( ) { return AttributeHelper . getTableName ( getTableModelClass ( ) ) ; } @ Override public List < String > getColumnNames ( ) { return AttributeHelper . getColumnNames ( getTableModelClass ( ) ) ; } @ Override public final List < String > getTargetColumnNames ( ) { return getColumnNames ( ) ; } @ Override public List < String > getPrimaryKeyNames ( ) { return AttributeHelper . getPrimaryKeyNames ( getTableModelClass ( ) ) ; } @ Override public final DuplicateRecordCheck getDuplicateRecordCheck ( ) { return null ; } } package com . asakusafw . vocabulary . bulkloader ; import java . lang . annotation . Documented ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) @ Documented public @ interface PrimaryKey { String [ ] value ( ) ; } package com . asakusafw . vocabulary . bulkloader ; import java . util . HashSet ; import java . util . List ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; import com . asakusafw . vocabulary . external . ImporterDescription ; public abstract class BulkLoadImporterDescription implements ImporterDescription { public abstract Mode getMode ( ) ; public abstract String getTargetName ( ) ; public String getWhere ( ) { return null ; } public abstract String getTableName ( ) ; public abstract List < String > getColumnNames ( ) ; public abstract LockType getLockType ( ) ; public abstract boolean isCacheEnabled ( ) ; public String calculateCacheId ( ) { final long prime = ; long hash = ; hash = hash * prime + hash ( getTargetName ( ) ) ; hash = hash * prime + hash ( getModelType ( ) . getName ( ) ) ; hash = hash * prime + hash ( getTableName ( ) ) ; hash = hash * prime + hash ( new HashSet < String > ( getColumnNames ( ) ) ) ; hash = hash * prime + hash ( getWhere ( ) ) ; return String . format ( "" , hash ) ; } private int hash ( Object object ) { if ( object == null ) { return ; } return object . hashCode ( ) ; } @ Override public DataSize getDataSize ( ) { return DataSize . UNKNOWN ; } public enum Mode { PRIMARY , SECONDARY , } public enum LockType { TABLE , ROW , ROW_OR_SKIP , CHECK , UNUSED , } } package com . asakusafw . vocabulary . bulkloader ; package com . asakusafw . vocabulary . bulkloader ; import java . util . List ; public abstract class SecondaryImporterDescription extends BulkLoadImporterDescription { @ Override public final Mode getMode ( ) { return Mode . SECONDARY ; } @ Override public final LockType getLockType ( ) { return LockType . UNUSED ; } @ Override public String getTableName ( ) { return AttributeHelper . getTableName ( getModelType ( ) ) ; } @ Override public List < String > getColumnNames ( ) { return AttributeHelper . getColumnNames ( getModelType ( ) ) ; } @ Override public boolean isCacheEnabled ( ) { return false ; } } package com . asakusafw . vocabulary . bulkloader ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import com . asakusafw . vocabulary . model . TableModel ; @ SuppressWarnings ( "" ) final class AttributeHelper { static String getTableName ( Class < ? > modelType ) { OriginalName original = modelType . getAnnotation ( OriginalName . class ) ; if ( original != null ) { return original . value ( ) ; } TableModel meta = modelType . getAnnotation ( TableModel . class ) ; if ( meta != null ) { return meta . name ( ) ; } StackTraceElement caller = getCaller ( ) ; throw new UnsupportedOperationException ( MessageFormat . format ( "" , caller . getClassName ( ) , OriginalName . class . getSimpleName ( ) , caller . getMethodName ( ) ) ) ; } static List < String > getColumnNames ( Class < ? > modelType ) { ColumnOrder original = modelType . getAnnotation ( ColumnOrder . class ) ; if ( original != null ) { return new ArrayList < String > ( Arrays . asList ( original . value ( ) ) ) ; } TableModel meta = modelType . getAnnotation ( TableModel . class ) ; if ( meta != null ) { return Arrays . asList ( meta . columns ( ) ) ; } StackTraceElement caller = getCaller ( ) ; throw new UnsupportedOperationException ( MessageFormat . format ( "" , caller . getClassName ( ) , ColumnOrder . class . getSimpleName ( ) , caller . getMethodName ( ) ) ) ; } static List < String > getPrimaryKeyNames ( Class < ? > modelType ) { PrimaryKey original = modelType . getAnnotation ( PrimaryKey . class ) ; if ( original != null ) { return new ArrayList < String > ( Arrays . asList ( original . value ( ) ) ) ; } TableModel meta = modelType . getAnnotation ( TableModel . class ) ; if ( meta != null ) { return Arrays . asList ( meta . primary ( ) ) ; } StackTraceElement caller = getCaller ( ) ; throw new UnsupportedOperationException ( MessageFormat . format ( "" , caller . getClassName ( ) , PrimaryKey . class . getSimpleName ( ) , caller . getMethodName ( ) ) ) ; } private static StackTraceElement getCaller ( ) { StackTraceElement [ ] trace = new Throwable ( ) . getStackTrace ( ) ; if ( trace == null || trace . length < ) { return new StackTraceElement ( "" , "" , "" , - ) ; } return trace [ ] ; } private AttributeHelper ( ) { return ; } } package com . asakusafw . vocabulary . bulkloader ; import java . util . List ; public abstract class DbImporterDescription extends BulkLoadImporterDescription { @ Override public final Mode getMode ( ) { return Mode . PRIMARY ; } @ Override public String getTableName ( ) { return AttributeHelper . getTableName ( getModelType ( ) ) ; } @ Override public List < String > getColumnNames ( ) { return AttributeHelper . getColumnNames ( getModelType ( ) ) ; } @ Override public boolean isCacheEnabled ( ) { return false ; } } package com . asakusafw . compiler . bulkloader ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class DualIdentityFlow < T > extends FlowDescription { private In < T > in1 ; private In < T > in2 ; private Out < T > out1 ; private Out < T > out2 ; public DualIdentityFlow ( In < T > in1 , In < T > in2 , Out < T > out1 , Out < T > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { out1 . add ( in1 ) ; out2 . add ( in2 ) ; } } package com . asakusafw . compiler . bulkloader ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class IdentityFlow < T > extends FlowDescription { private In < T > in ; private Out < T > out ; public IdentityFlow ( In < T > in , Out < T > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . compiler . bulkloader . testing . model . Cached ; import com . asakusafw . compiler . bulkloader . testing . model . Ex1 ; import com . asakusafw . compiler . bulkloader . testing . model . MockErrorModel ; import com . asakusafw . compiler . bulkloader . testing . model . MockTableModel ; import com . asakusafw . compiler . bulkloader . testing . model . MockUnionModel ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . CommandContext ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowDescriptionDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectExporterDescription ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . DirectImporterDescription ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . vocabulary . bulkloader . BulkLoadExporterDescription ; import com . asakusafw . vocabulary . bulkloader . BulkLoadImporterDescription ; import com . asakusafw . vocabulary . bulkloader . BulkLoadImporterDescription . LockType ; import com . asakusafw . vocabulary . bulkloader . BulkLoadImporterDescription . Mode ; import com . asakusafw . vocabulary . bulkloader . DupCheckDbExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class BulkLoaderIoProcessorTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void ok ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW ) ) ; In < Ex1 > in2 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW_OR_SKIP ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new Export ( "" ) ) ; Out < Ex1 > out2 = flow . createOut ( "" , new Export ( "" ) ) ; FlowDescription desc = new DualIdentityFlow < Ex1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void dupCheck ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in = flow . createIn ( "" , new DirectImporterDescription ( MockUnionModel . class , "" ) ) ; Out < Ex1 > out = flow . createOut ( "" , new DupCheckDbExporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return MockUnionModel . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override protected Class < ? > getNormalModelType ( ) { return MockTableModel . class ; } @ Override protected Class < ? > getErrorModelType ( ) { return MockErrorModel . class ; } @ Override protected String getErrorCodeValue ( ) { return "" ; } @ Override protected String getErrorCodeColumnName ( ) { return "" ; } @ Override protected List < String > getCheckColumnNames ( ) { return Arrays . asList ( "" ) ; } } ) ; FlowDescription desc = new IdentityFlow < Ex1 > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void invalidNormalTargetColumns ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < MockUnionModel > in = flow . createIn ( "" , new DirectImporterDescription ( MockUnionModel . class , "" ) ) ; Out < MockUnionModel > out = flow . createOut ( "" , new DupCheckDbExporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return MockUnionModel . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override protected Class < ? > getNormalModelType ( ) { return MockTableModel . class ; } @ Override protected Class < ? > getErrorModelType ( ) { return MockErrorModel . class ; } @ Override protected String getErrorCodeValue ( ) { return "" ; } @ Override protected String getErrorCodeColumnName ( ) { return "" ; } @ Override public List < String > getTargetColumnNames ( ) { return Arrays . asList ( "" ) ; } @ Override protected List < String > getCheckColumnNames ( ) { return Arrays . asList ( "" , "" ) ; } } ) ; FlowDescription desc = new IdentityFlow < MockUnionModel > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalidErrorTargetColumns ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < MockUnionModel > in = flow . createIn ( "" , new DirectImporterDescription ( MockUnionModel . class , "" ) ) ; Out < MockUnionModel > out = flow . createOut ( "" , new DupCheckDbExporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return MockUnionModel . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override protected Class < ? > getNormalModelType ( ) { return MockTableModel . class ; } @ Override protected Class < ? > getErrorModelType ( ) { return MockErrorModel . class ; } @ Override protected String getErrorCodeValue ( ) { return "" ; } @ Override protected String getErrorCodeColumnName ( ) { return "" ; } @ Override protected List < String > getErrorColumnNames ( ) { return Arrays . asList ( "" ) ; } @ Override protected List < String > getCheckColumnNames ( ) { return Arrays . asList ( "" , "" ) ; } } ) ; FlowDescription desc = new IdentityFlow < MockUnionModel > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalidCheckColumns ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < MockUnionModel > in = flow . createIn ( "" , new DirectImporterDescription ( MockUnionModel . class , "" ) ) ; Out < MockUnionModel > out = flow . createOut ( "" , new DupCheckDbExporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return MockUnionModel . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override protected Class < ? > getNormalModelType ( ) { return MockTableModel . class ; } @ Override protected Class < ? > getErrorModelType ( ) { return MockErrorModel . class ; } @ Override protected String getErrorCodeValue ( ) { return "" ; } @ Override protected String getErrorCodeColumnName ( ) { return "" ; } @ Override protected List < String > getCheckColumnNames ( ) { return Arrays . asList ( "" ) ; } } ) ; FlowDescription desc = new IdentityFlow < MockUnionModel > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void using_secondary ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . CHECK ) ) ; In < Ex1 > in2 = flow . createIn ( "" , new Import ( Mode . SECONDARY , "" , LockType . UNUSED ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new Export ( "" ) ) ; Out < Ex1 > out2 = flow . createOut ( "" , new Export ( "" ) ) ; FlowDescription desc = new DualIdentityFlow < Ex1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void no_primary_importers ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new DirectImporterDescription ( Ex1 . class , "" ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new Export ( "" ) ) ; FlowDescription desc = new IdentityFlow < Ex1 > ( in1 , out1 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void no_exporters ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . TABLE ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new DirectExporterDescription ( Ex1 . class , "" ) ) ; FlowDescription desc = new IdentityFlow < Ex1 > ( in1 , out1 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void only_secondary ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . SECONDARY , "" , LockType . UNUSED ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new DirectExporterDescription ( Ex1 . class , "" ) ) ; FlowDescription desc = new IdentityFlow < Ex1 > ( in1 , out1 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void lock_in_secondary ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . SECONDARY , "" , LockType . ROW ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new Export ( "" ) ) ; FlowDescription desc = new IdentityFlow < Ex1 > ( in1 , out1 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void mutiple_primary ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW ) ) ; In < Ex1 > in2 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new Export ( "" ) ) ; Out < Ex1 > out2 = flow . createOut ( "" , new Export ( "" ) ) ; FlowDescription desc = new DualIdentityFlow < Ex1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void inconsistent_exporter ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW ) ) ; In < Ex1 > in2 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new Export ( "" ) ) ; Out < Ex1 > out2 = flow . createOut ( "" , new Export ( "" ) ) ; FlowDescription desc = new DualIdentityFlow < Ex1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void multiple_exporter ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW ) ) ; In < Ex1 > in2 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new Export ( "" ) ) ; Out < Ex1 > out2 = flow . createOut ( "" , new Export ( "" ) ) ; FlowDescription desc = new DualIdentityFlow < Ex1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void upgrade_secondary ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Ex1 > in1 = flow . createIn ( "" , new Import ( Mode . PRIMARY , "" , LockType . ROW ) ) ; In < Ex1 > in2 = flow . createIn ( "" , new Import ( Mode . SECONDARY , "" , LockType . UNUSED ) ) ; Out < Ex1 > out1 = flow . createOut ( "" , new Export ( "" ) ) ; Out < Ex1 > out2 = flow . createOut ( "" , new Export ( "" ) ) ; FlowDescription desc = new DualIdentityFlow < Ex1 > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( "" , provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void cached ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . UNUSED , null , DataSize . UNKNOWN ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void cached_conditional ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . UNUSED , "" , DataSize . UNKNOWN ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void cached_unsupported ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . UNUSED , null , DataSize . UNKNOWN , Ex1 . class ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Ex1 . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void cached_tablelock ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . TABLE , null , DataSize . UNKNOWN ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; } @ Test public void cached_rowcheck ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . CHECK , null , DataSize . UNKNOWN ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; } @ Test public void cached_rowlock ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . ROW , null , DataSize . UNKNOWN ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void cached_rowskip ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . ROW_OR_SKIP , null , DataSize . UNKNOWN ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void cached_tiny ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . UNUSED , null , DataSize . TINY ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void cached_small ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . UNUSED , null , DataSize . SMALL ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void cached_large ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Cached > in = flow . createIn ( "" , new ImportCached ( "" , LockType . UNUSED , null , DataSize . LARGE ) ) ; Out < Cached > out = flow . createOut ( "" , new Export ( "" , Cached . class ) ) ; FlowDescription desc = new IdentityFlow < Cached > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; } JobflowInfo compile ( FlowDescriptionDriver flow , FlowDescription desc ) { try { return DirectFlowCompiler . compile ( flow . createFlowGraph ( desc ) , "" , "" , "" , Location . fromPath ( "" , '' ) , folder . newFolder ( "" ) , Collections . < File > emptyList ( ) , getClass ( ) . getClassLoader ( ) , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } } static class Import extends BulkLoadImporterDescription { private final Mode mode ; private final String target ; private final LockType lock ; Import ( Mode mode , String target , LockType lock ) { this . mode = mode ; this . target = target ; this . lock = lock ; } @ Override public Mode getMode ( ) { return mode ; } @ Override public String getTargetName ( ) { return target ; } @ Override public LockType getLockType ( ) { return lock ; } @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getTableName ( ) { return "" ; } @ Override public List < String > getColumnNames ( ) { return Arrays . asList ( "" ) ; } @ Override public String getWhere ( ) { return null ; } @ Override public boolean isCacheEnabled ( ) { return false ; } } static class ImportCached extends BulkLoadImporterDescription { private final String target ; private final LockType lock ; private final String where ; private final DataSize size ; private final Class < ? > modelType ; ImportCached ( String target , LockType lock , String where , DataSize size ) { this ( target , lock , where , size , Cached . class ) ; } ImportCached ( String target , LockType lock , String where , DataSize size , Class < ? > modelType ) { this . target = target ; this . lock = lock ; this . where = where ; this . size = size ; this . modelType = modelType ; } @ Override public Mode getMode ( ) { return Mode . PRIMARY ; } @ Override public String getTargetName ( ) { return target ; } @ Override public LockType getLockType ( ) { return lock ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getTableName ( ) { return "" ; } @ Override public List < String > getColumnNames ( ) { return Arrays . asList ( "" ) ; } @ Override public String getWhere ( ) { return where ; } @ Override public boolean isCacheEnabled ( ) { return true ; } @ Override public DataSize getDataSize ( ) { return size ; } } static class Export extends BulkLoadExporterDescription { private final String target ; private final Class < ? > modelType ; Export ( String target ) { this ( target , Ex1 . class ) ; } Export ( String target , Class < ? > modelType ) { this . target = target ; this . modelType = modelType ; } @ Override public Class < ? > getTableModelClass ( ) { return getModelType ( ) ; } @ Override public String getTargetName ( ) { return target ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getTableName ( ) { return "" ; } @ Override public List < String > getColumnNames ( ) { return Arrays . asList ( "" ) ; } @ Override public List < String > getTargetColumnNames ( ) { return Arrays . asList ( "" ) ; } @ Override public List < String > getPrimaryKeyNames ( ) { return Arrays . asList ( "" ) ; } } } package com . asakusafw . compiler . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . Properties ; import org . junit . Test ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . DuplicateRecordErrorTable ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . ExportTable ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . ImportTable ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . LockType ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . LockedOperation ; import com . asakusafw . compiler . bulkloader . testing . model . Ex1 ; import com . asakusafw . compiler . bulkloader . testing . model . Ex2 ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . utils . collections . Lists ; public class BulkLoaderScriptTest { @ Test public void importers ( ) { List < ImportTable > importers = Lists . create ( ) ; List < ExportTable > exporters = Lists . create ( ) ; importers . add ( new ImportTable ( Ex1 . class , "" , Arrays . asList ( "" , "" , "" , "" , "" , "" ) , "" , "" , LockType . ROW , LockedOperation . ERROR , Location . fromPath ( "" , '' ) ) ) ; importers . add ( new ImportTable ( Ex2 . class , "" , Arrays . asList ( "" , "" , "" , "" , "" , "" ) , "" , null , LockType . UNLOCKED , LockedOperation . FORCE , Location . fromPath ( "" , '' ) ) ) ; BulkLoaderScript script = new BulkLoaderScript ( importers , exporters ) ; Properties properties = script . getImporterProperties ( ) ; List < ImportTable > restored = ImportTable . fromProperties ( properties , getClass ( ) . getClassLoader ( ) ) ; assertThat ( restored , is ( importers ) ) ; } @ Test public void exporters ( ) { List < ImportTable > importers = Lists . create ( ) ; List < ExportTable > exporters = Lists . create ( ) ; exporters . add ( new ExportTable ( Ex1 . class , "" , Arrays . asList ( "" , "" , "" , "" , "" , "" ) , Arrays . asList ( "" , "" ) , null , Collections . singletonList ( Location . fromPath ( "" , '' ) ) ) ) ; exporters . add ( new ExportTable ( Ex2 . class , "" , Arrays . asList ( "" , "" , "" , "" , "" , "" , "" ) , Arrays . asList ( "" , "" ) , new DuplicateRecordErrorTable ( "" , Arrays . asList ( "" , "" , "" ) , Arrays . asList ( "" ) , "" , "" ) , Arrays . asList ( Location . fromPath ( "" , '' ) , Location . fromPath ( "" , '' ) ) ) ) ; BulkLoaderScript script = new BulkLoaderScript ( importers , exporters ) ; Properties properties = script . getExporterProperties ( ) ; List < ExportTable > restored = ExportTable . fromProperties ( properties , getClass ( ) . getClassLoader ( ) ) ; assertThat ( restored , is ( exporters ) ) ; } } package com . asakusafw . compiler . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . ExportTable ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . ImportTable ; import com . asakusafw . compiler . bulkloader . testing . model . Ex1 ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . CommandContext ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . thundergate . runtime . property . PropertyLoader ; import com . asakusafw . vocabulary . bulkloader . DbExporterDescription ; import com . asakusafw . vocabulary . bulkloader . DbImporterDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class BulkLoaderIoProcessorRunTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void identity ( ) throws Exception { In < Ex1 > in = tester . input ( "" , new DbImporterDescription ( ) { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public LockType getLockType ( ) { return LockType . TABLE ; } } ) ; Out < Ex1 > out = tester . output ( "" , new DbExporterDescription ( ) { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } } ) ; JobflowInfo info = tester . compileFlow ( new IdentityFlow < Ex1 > ( in , out ) ) ; BulkLoaderScript script = loadScript ( info ) ; assertThat ( script . getImportTargetTables ( ) . size ( ) , is ( ) ) ; assertThat ( script . getExportTargetTables ( ) . size ( ) , is ( ) ) ; ImportTable itable = script . getImportTargetTables ( ) . get ( ) ; ExportTable etable = script . getExportTargetTables ( ) . get ( ) ; assertThat ( etable . getSources ( ) . size ( ) , is ( ) ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , itable . getDestination ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; source . write ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; source . write ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; source . write ( ex1 ) ; source . close ( ) ; assertThat ( tester . runStages ( info ) , is ( true ) ) ; Location resultLocation = etable . getSources ( ) . get ( ) ; assertThat ( resultLocation . isPrefix ( ) , is ( true ) ) ; List < Ex1 > results = tester . getList ( Ex1 . class , resultLocation ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } @ Test public void capital ( ) throws Exception { In < Ex1 > in = tester . input ( "" , new DbImporterDescription ( ) { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public LockType getLockType ( ) { return LockType . TABLE ; } } ) ; Out < Ex1 > out = tester . output ( "" , new DbExporterDescription ( ) { @ Override public String getTargetName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } } ) ; JobflowInfo info = tester . compileFlow ( new IdentityFlow < Ex1 > ( in , out ) ) ; BulkLoaderScript script = loadScript ( info ) ; assertThat ( script . getImportTargetTables ( ) . size ( ) , is ( ) ) ; assertThat ( script . getExportTargetTables ( ) . size ( ) , is ( ) ) ; ImportTable itable = script . getImportTargetTables ( ) . get ( ) ; ExportTable etable = script . getExportTargetTables ( ) . get ( ) ; assertThat ( etable . getSources ( ) . size ( ) , is ( ) ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , itable . getDestination ( ) ) ; Ex1 ex1 = new Ex1 ( ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; source . write ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; source . write ( ex1 ) ; ex1 . setSid ( ) ; ex1 . setValue ( ) ; source . write ( ex1 ) ; source . close ( ) ; assertThat ( tester . runStages ( info ) , is ( true ) ) ; Location resultLocation = etable . getSources ( ) . get ( ) ; assertThat ( resultLocation . isPrefix ( ) , is ( true ) ) ; List < Ex1 > results = tester . getList ( Ex1 . class , resultLocation ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; assertThat ( results . get ( ) . getValue ( ) , is ( ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = BulkLoaderIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; assertThat ( provider . getImportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getExportCommand ( context ) . size ( ) , is ( ) ) ; assertThat ( provider . getFinalizeCommand ( context ) . size ( ) , is ( ) ) ; } private BulkLoaderScript loadScript ( JobflowInfo info ) throws IOException { PropertyLoader loader = new PropertyLoader ( info . getPackageFile ( ) , "" ) ; BulkLoaderScript script ; try { List < ImportTable > importers = ImportTable . fromProperties ( loader . loadImporterProperties ( ) , getClass ( ) . getClassLoader ( ) ) ; List < ExportTable > exporters = ExportTable . fromProperties ( loader . loadExporterProperties ( ) , getClass ( ) . getClassLoader ( ) ) ; script = new BulkLoaderScript ( importers , exporters ) ; } finally { loader . close ( ) ; } return script ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . MockTableModel ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockTableModelInput implements ModelInput < MockTableModel > { private final RecordParser parser ; public MockTableModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockTableModel model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getAOption ( ) ) ; parser . fill ( model . getBOption ( ) ) ; parser . fill ( model . getCOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . MockUnionModel ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockUnionModelOutput implements ModelOutput < MockUnionModel > { private final RecordEmitter emitter ; public MockUnionModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockUnionModel model ) throws IOException { emitter . emit ( model . getAOption ( ) ) ; emitter . emit ( model . getBOption ( ) ) ; emitter . emit ( model . getCOption ( ) ) ; emitter . emit ( model . getDOption ( ) ) ; emitter . emit ( model . getXOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . MockErrorModel ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockErrorModelOutput implements ModelOutput < MockErrorModel > { private final RecordEmitter emitter ; public MockErrorModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockErrorModel model ) throws IOException { emitter . emit ( model . getAOption ( ) ) ; emitter . emit ( model . getBOption ( ) ) ; emitter . emit ( model . getCOption ( ) ) ; emitter . emit ( model . getDOption ( ) ) ; emitter . emit ( model . getEOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . MockTableModel ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class MockTableModelOutput implements ModelOutput < MockTableModel > { private final RecordEmitter emitter ; public MockTableModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( MockTableModel model ) throws IOException { emitter . emit ( model . getAOption ( ) ) ; emitter . emit ( model . getBOption ( ) ) ; emitter . emit ( model . getCOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . SystemColumns ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class SystemColumnsInput implements ModelInput < SystemColumns > { private final RecordParser parser ; public SystemColumnsInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( SystemColumns model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . Ex1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Ex1Input implements ModelInput < Ex1 > { private final RecordParser parser ; public Ex1Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Ex1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getStringOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . Ex1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Ex1Output implements ModelOutput < Ex1 > { private final RecordEmitter emitter ; public Ex1Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Ex1 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getStringOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . MockErrorModel ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockErrorModelInput implements ModelInput < MockErrorModel > { private final RecordParser parser ; public MockErrorModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockErrorModel model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getAOption ( ) ) ; parser . fill ( model . getBOption ( ) ) ; parser . fill ( model . getCOption ( ) ) ; parser . fill ( model . getDOption ( ) ) ; parser . fill ( model . getEOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . Cached ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class CachedOutput implements ModelOutput < Cached > { private final RecordEmitter emitter ; public CachedOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Cached model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getTimestampOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . Ex2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Ex2Output implements ModelOutput < Ex2 > { private final RecordEmitter emitter ; public Ex2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Ex2 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getStringOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . Ex2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Ex2Input implements ModelInput < Ex2 > { private final RecordParser parser ; public Ex2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Ex2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getStringOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . Cached ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class CachedInput implements ModelInput < Cached > { private final RecordParser parser ; public CachedInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Cached model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getTimestampOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . SystemColumns ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class SystemColumnsOutput implements ModelOutput < SystemColumns > { private final RecordEmitter emitter ; public SystemColumnsOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( SystemColumns model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . bulkloader . testing . model . MockUnionModel ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class MockUnionModelInput implements ModelInput < MockUnionModel > { private final RecordParser parser ; public MockUnionModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( MockUnionModel model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getAOption ( ) ) ; parser . fill ( model . getBOption ( ) ) ; parser . fill ( model . getCOption ( ) ) ; parser . fill ( model . getDOption ( ) ) ; parser . fill ( model . getXOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . bulkloader . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . bulkloader . testing . io . MockErrorModelInput ; import com . asakusafw . compiler . bulkloader . testing . io . MockErrorModelOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ ColumnOrder ( value = { "" , "" , "" , "" , "" } ) @ DataModelKind ( "" ) @ ModelInputLocation ( MockErrorModelInput . class ) @ ModelOutputLocation ( MockErrorModelOutput . class ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) @ PropertyOrder ( { "" , "" , "" , "" , "" } ) public class MockErrorModel implements DataModel < MockErrorModel > , Writable { private final IntOption a = new IntOption ( ) ; private final IntOption b = new IntOption ( ) ; private final IntOption c = new IntOption ( ) ; private final IntOption d = new IntOption ( ) ; private final IntOption e = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . a . setNull ( ) ; this . b . setNull ( ) ; this . c . setNull ( ) ; this . d . setNull ( ) ; this . e . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockErrorModel other ) { this . a . copyFrom ( other . a ) ; this . b . copyFrom ( other . b ) ; this . c . copyFrom ( other . c ) ; this . d . copyFrom ( other . d ) ; this . e . copyFrom ( other . e ) ; } public int getA ( ) { return this . a . get ( ) ; } @ SuppressWarnings ( "" ) public void setA ( int value ) { this . a . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getAOption ( ) { return this . a ; } @ SuppressWarnings ( "" ) public void setAOption ( IntOption option ) { this . a . copyFrom ( option ) ; } public int getB ( ) { return this . b . get ( ) ; } @ SuppressWarnings ( "" ) public void setB ( int value ) { this . b . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getBOption ( ) { return this . b ; } @ SuppressWarnings ( "" ) public void setBOption ( IntOption option ) { this . b . copyFrom ( option ) ; } public int getC ( ) { return this . c . get ( ) ; } @ SuppressWarnings ( "" ) public void setC ( int value ) { this . c . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getCOption ( ) { return this . c ; } @ SuppressWarnings ( "" ) public void setCOption ( IntOption option ) { this . c . copyFrom ( option ) ; } public int getD ( ) { return this . d . get ( ) ; } @ SuppressWarnings ( "" ) public void setD ( int value ) { this . d . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getDOption ( ) { return this . d ; } @ SuppressWarnings ( "" ) public void setDOption ( IntOption option ) { this . d . copyFrom ( option ) ; } public int getE ( ) { return this . e . get ( ) ; } @ SuppressWarnings ( "" ) public void setE ( int value ) { this . e . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getEOption ( ) { return this . e ; } @ SuppressWarnings ( "" ) public void setEOption ( IntOption option ) { this . e . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . a ) ; result . append ( "" ) ; result . append ( this . b ) ; result . append ( "" ) ; result . append ( this . c ) ; result . append ( "" ) ; result . append ( this . d ) ; result . append ( "" ) ; result . append ( this . e ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + a . hashCode ( ) ; result = prime * result + b . hashCode ( ) ; result = prime * result + c . hashCode ( ) ; result = prime * result + d . hashCode ( ) ; result = prime * result + e . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockErrorModel other = ( MockErrorModel ) obj ; if ( this . a . equals ( other . a ) == false ) { return false ; } if ( this . b . equals ( other . b ) == false ) { return false ; } if ( this . c . equals ( other . c ) == false ) { return false ; } if ( this . d . equals ( other . d ) == false ) { return false ; } if ( this . e . equals ( other . e ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { a . write ( out ) ; b . write ( out ) ; c . write ( out ) ; d . write ( out ) ; e . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { a . readFields ( in ) ; b . readFields ( in ) ; c . readFields ( in ) ; d . readFields ( in ) ; e . readFields ( in ) ; } } package com . asakusafw . compiler . bulkloader . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . bulkloader . testing . io . SystemColumnsInput ; import com . asakusafw . compiler . bulkloader . testing . io . SystemColumnsOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; @ ColumnOrder ( value = { "" } ) @ DataModelKind ( "" ) @ ModelInputLocation ( SystemColumnsInput . class ) @ ModelOutputLocation ( SystemColumnsOutput . class ) @ OriginalName ( value = "" ) @ PropertyOrder ( { "" } ) public class SystemColumns implements DataModel < SystemColumns > , Writable { private final LongOption sid = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( SystemColumns other ) { this . sid . copyFrom ( other . sid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value ) { this . sid . modify ( value ) ; } @ OriginalName ( value = "" ) public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } SystemColumns other = ( SystemColumns ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; } } package com . asakusafw . compiler . bulkloader . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . bulkloader . testing . io . Ex1Input ; import com . asakusafw . compiler . bulkloader . testing . io . Ex1Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ ColumnOrder ( value = { "" , "" , "" } ) @ DataModelKind ( "" ) @ ModelInputLocation ( Ex1Input . class ) @ ModelOutputLocation ( Ex1Output . class ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) @ PropertyOrder ( { "" , "" , "" } ) public class Ex1 implements DataModel < Ex1 > , Writable { private final LongOption sid = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; private final StringOption string = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . value . setNull ( ) ; this . string . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Ex1 other ) { this . sid . copyFrom ( other . sid ) ; this . value . copyFrom ( other . value ) ; this . string . copyFrom ( other . string ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value0 ) { this . sid . modify ( value0 ) ; } @ OriginalName ( value = "" ) public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } @ OriginalName ( value = "" ) public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value0 ) { this . string . modify ( value0 ) ; } @ OriginalName ( value = "" ) public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + string . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Ex1 other = ( Ex1 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . string . equals ( other . string ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; value . write ( out ) ; string . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; value . readFields ( in ) ; string . readFields ( in ) ; } } package com . asakusafw . compiler . bulkloader . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . bulkloader . testing . io . Ex2Input ; import com . asakusafw . compiler . bulkloader . testing . io . Ex2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ ColumnOrder ( value = { "" , "" , "" } ) @ DataModelKind ( "" ) @ ModelInputLocation ( Ex2Input . class ) @ ModelOutputLocation ( Ex2Output . class ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) @ PropertyOrder ( { "" , "" , "" } ) public class Ex2 implements DataModel < Ex2 > , Writable { private final LongOption sid = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; private final StringOption string = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . value . setNull ( ) ; this . string . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Ex2 other ) { this . sid . copyFrom ( other . sid ) ; this . value . copyFrom ( other . value ) ; this . string . copyFrom ( other . string ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value0 ) { this . sid . modify ( value0 ) ; } @ OriginalName ( value = "" ) public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } @ OriginalName ( value = "" ) public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value0 ) { this . string . modify ( value0 ) ; } @ OriginalName ( value = "" ) public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + string . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Ex2 other = ( Ex2 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . string . equals ( other . string ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; value . write ( out ) ; string . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; value . readFields ( in ) ; string . readFields ( in ) ; } } package com . asakusafw . compiler . bulkloader . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . bulkloader . testing . io . MockUnionModelInput ; import com . asakusafw . compiler . bulkloader . testing . io . MockUnionModelOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ ColumnOrder ( value = { "" , "" , "" , "" , "" } ) @ DataModelKind ( "" ) @ ModelInputLocation ( MockUnionModelInput . class ) @ ModelOutputLocation ( MockUnionModelOutput . class ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) @ PropertyOrder ( { "" , "" , "" , "" , "" } ) public class MockUnionModel implements DataModel < MockUnionModel > , Writable { private final IntOption a = new IntOption ( ) ; private final IntOption b = new IntOption ( ) ; private final IntOption c = new IntOption ( ) ; private final IntOption d = new IntOption ( ) ; private final IntOption x = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . a . setNull ( ) ; this . b . setNull ( ) ; this . c . setNull ( ) ; this . d . setNull ( ) ; this . x . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockUnionModel other ) { this . a . copyFrom ( other . a ) ; this . b . copyFrom ( other . b ) ; this . c . copyFrom ( other . c ) ; this . d . copyFrom ( other . d ) ; this . x . copyFrom ( other . x ) ; } public int getA ( ) { return this . a . get ( ) ; } @ SuppressWarnings ( "" ) public void setA ( int value ) { this . a . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getAOption ( ) { return this . a ; } @ SuppressWarnings ( "" ) public void setAOption ( IntOption option ) { this . a . copyFrom ( option ) ; } public int getB ( ) { return this . b . get ( ) ; } @ SuppressWarnings ( "" ) public void setB ( int value ) { this . b . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getBOption ( ) { return this . b ; } @ SuppressWarnings ( "" ) public void setBOption ( IntOption option ) { this . b . copyFrom ( option ) ; } public int getC ( ) { return this . c . get ( ) ; } @ SuppressWarnings ( "" ) public void setC ( int value ) { this . c . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getCOption ( ) { return this . c ; } @ SuppressWarnings ( "" ) public void setCOption ( IntOption option ) { this . c . copyFrom ( option ) ; } public int getD ( ) { return this . d . get ( ) ; } @ SuppressWarnings ( "" ) public void setD ( int value ) { this . d . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getDOption ( ) { return this . d ; } @ SuppressWarnings ( "" ) public void setDOption ( IntOption option ) { this . d . copyFrom ( option ) ; } public int getX ( ) { return this . x . get ( ) ; } @ SuppressWarnings ( "" ) public void setX ( int value ) { this . x . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getXOption ( ) { return this . x ; } @ SuppressWarnings ( "" ) public void setXOption ( IntOption option ) { this . x . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . a ) ; result . append ( "" ) ; result . append ( this . b ) ; result . append ( "" ) ; result . append ( this . c ) ; result . append ( "" ) ; result . append ( this . d ) ; result . append ( "" ) ; result . append ( this . x ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + a . hashCode ( ) ; result = prime * result + b . hashCode ( ) ; result = prime * result + c . hashCode ( ) ; result = prime * result + d . hashCode ( ) ; result = prime * result + x . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockUnionModel other = ( MockUnionModel ) obj ; if ( this . a . equals ( other . a ) == false ) { return false ; } if ( this . b . equals ( other . b ) == false ) { return false ; } if ( this . c . equals ( other . c ) == false ) { return false ; } if ( this . d . equals ( other . d ) == false ) { return false ; } if ( this . x . equals ( other . x ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { a . write ( out ) ; b . write ( out ) ; c . write ( out ) ; d . write ( out ) ; x . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { a . readFields ( in ) ; b . readFields ( in ) ; c . readFields ( in ) ; d . readFields ( in ) ; x . readFields ( in ) ; } } package com . asakusafw . compiler . bulkloader . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . bulkloader . testing . io . CachedInput ; import com . asakusafw . compiler . bulkloader . testing . io . CachedOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ ColumnOrder ( value = { "" , "" } ) @ DataModelKind ( "" ) @ ModelInputLocation ( CachedInput . class ) @ ModelOutputLocation ( CachedOutput . class ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) @ PropertyOrder ( { "" , "" } ) public class Cached implements DataModel < Cached > , ThunderGateCacheSupport , Writable { private final LongOption sid = new LongOption ( ) ; private final DateTimeOption timestamp = new DateTimeOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . timestamp . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Cached other ) { this . sid . copyFrom ( other . sid ) ; this . timestamp . copyFrom ( other . timestamp ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value ) { this . sid . modify ( value ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public DateTime getTimestamp ( ) { return this . timestamp . get ( ) ; } @ SuppressWarnings ( "" ) public void setTimestamp ( DateTime value ) { this . timestamp . modify ( value ) ; } public DateTimeOption getTimestampOption ( ) { return this . timestamp ; } @ SuppressWarnings ( "" ) public void setTimestampOption ( DateTimeOption option ) { this . timestamp . copyFrom ( option ) ; } @ Override public long __tgc__DataModelVersion ( ) { return - ; } @ Override public String __tgc__TimestampColumn ( ) { return "" ; } @ Override public long __tgc__SystemId ( ) { return this . getSid ( ) ; } @ Override public boolean __tgc__Deleted ( ) { return false ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . timestamp ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + timestamp . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Cached other = ( Cached ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . timestamp . equals ( other . timestamp ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; timestamp . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; timestamp . readFields ( in ) ; } } package com . asakusafw . compiler . bulkloader . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . bulkloader . testing . io . MockTableModelInput ; import com . asakusafw . compiler . bulkloader . testing . io . MockTableModelOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . model . PropertyOrder ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ ColumnOrder ( value = { "" , "" , "" } ) @ DataModelKind ( "" ) @ ModelInputLocation ( MockTableModelInput . class ) @ ModelOutputLocation ( MockTableModelOutput . class ) @ OriginalName ( value = "" ) @ PrimaryKey ( value = { "" } ) @ PropertyOrder ( { "" , "" , "" } ) public class MockTableModel implements DataModel < MockTableModel > , Writable { private final IntOption a = new IntOption ( ) ; private final IntOption b = new IntOption ( ) ; private final IntOption c = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . a . setNull ( ) ; this . b . setNull ( ) ; this . c . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( MockTableModel other ) { this . a . copyFrom ( other . a ) ; this . b . copyFrom ( other . b ) ; this . c . copyFrom ( other . c ) ; } public int getA ( ) { return this . a . get ( ) ; } @ SuppressWarnings ( "" ) public void setA ( int value ) { this . a . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getAOption ( ) { return this . a ; } @ SuppressWarnings ( "" ) public void setAOption ( IntOption option ) { this . a . copyFrom ( option ) ; } public int getB ( ) { return this . b . get ( ) ; } @ SuppressWarnings ( "" ) public void setB ( int value ) { this . b . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getBOption ( ) { return this . b ; } @ SuppressWarnings ( "" ) public void setBOption ( IntOption option ) { this . b . copyFrom ( option ) ; } public int getC ( ) { return this . c . get ( ) ; } @ SuppressWarnings ( "" ) public void setC ( int value ) { this . c . modify ( value ) ; } @ OriginalName ( value = "" ) public IntOption getCOption ( ) { return this . c ; } @ SuppressWarnings ( "" ) public void setCOption ( IntOption option ) { this . c . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . a ) ; result . append ( "" ) ; result . append ( this . b ) ; result . append ( "" ) ; result . append ( this . c ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + a . hashCode ( ) ; result = prime * result + b . hashCode ( ) ; result = prime * result + c . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } MockTableModel other = ( MockTableModel ) obj ; if ( this . a . equals ( other . a ) == false ) { return false ; } if ( this . b . equals ( other . b ) == false ) { return false ; } if ( this . c . equals ( other . c ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { a . write ( out ) ; b . write ( out ) ; c . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { a . readFields ( in ) ; b . readFields ( in ) ; c . readFields ( in ) ; } } package com . asakusafw . compiler . bulkloader ; package com . asakusafw . compiler . bulkloader ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Properties ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . utils . collections . Lists ; public class BulkLoaderScript { private final List < ImportTable > importTargetTables ; private final List < ExportTable > exportTargetTables ; public BulkLoaderScript ( List < ImportTable > importTargetTables , List < ExportTable > exportTargetTables ) { if ( importTargetTables == null ) { throw new IllegalArgumentException ( "" ) ; } if ( exportTargetTables == null ) { throw new IllegalArgumentException ( "" ) ; } this . importTargetTables = importTargetTables ; this . exportTargetTables = exportTargetTables ; } public List < ImportTable > getImportTargetTables ( ) { return importTargetTables ; } public List < ExportTable > getExportTargetTables ( ) { return exportTargetTables ; } public Properties getImporterProperties ( ) { return ImportTable . toProperties ( importTargetTables ) ; } public Properties getExporterProperties ( ) { return ExportTable . toProperties ( exportTargetTables ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + exportTargetTables . hashCode ( ) ; result = prime * result + importTargetTables . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } BulkLoaderScript other = ( BulkLoaderScript ) obj ; if ( exportTargetTables . equals ( other . exportTargetTables ) == false ) { return false ; } if ( importTargetTables . equals ( other . importTargetTables ) == false ) { return false ; } return true ; } static List < String > toNames ( List < ? extends Table > tables ) { assert tables != null ; List < String > results = Lists . create ( ) ; for ( Table table : tables ) { results . add ( table . getName ( ) ) ; } return results ; } static String toPath ( Location location ) { assert location != null ; return location . toPath ( '' ) ; } static Location fromPath ( String path ) { assert path != null ; return Location . fromPath ( path , '' ) ; } static List < String > toPaths ( List < Location > locations ) { assert locations != null ; List < String > results = Lists . create ( ) ; for ( Location location : locations ) { results . add ( toPath ( location ) ) ; } return results ; } static List < Location > fromPaths ( List < String > paths ) { assert paths != null ; List < Location > results = Lists . create ( ) ; for ( String path : paths ) { results . add ( fromPath ( path ) ) ; } return results ; } static String join ( List < String > fields ) { assert fields != null ; if ( fields . isEmpty ( ) ) { return "" ; } if ( fields . size ( ) == ) { return fields . get ( ) ; } StringBuilder buf = new StringBuilder ( ) ; Iterator < String > iter = fields . iterator ( ) ; assert iter . hasNext ( ) ; buf . append ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( '' ) ; buf . append ( iter . next ( ) ) ; } return buf . toString ( ) ; } static List < String > split ( String fields ) { assert fields != null ; if ( fields . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < String > results = Lists . create ( ) ; int start = ; while ( true ) { int end = fields . indexOf ( '' , start ) ; if ( end < ) { break ; } results . add ( fields . substring ( start , end ) ) ; start = end + ; } results . add ( fields . substring ( start ) ) ; return results ; } static String get ( Properties properties , String keyName , boolean mandatory ) { assert properties != null ; assert keyName != null ; String value = properties . getProperty ( keyName ) ; if ( value == null && mandatory ) { throw new IllegalArgumentException ( keyName ) ; } return value ; } public abstract static class Table { private final Class < ? > modelClass ; private final String name ; private final List < String > targetColumns ; protected Table ( Class < ? > modelClass , String name , List < String > targetColumns ) { if ( modelClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetColumns == null ) { throw new IllegalArgumentException ( "" ) ; } this . modelClass = modelClass ; this . name = name ; this . targetColumns = targetColumns ; } public String getName ( ) { return name ; } public Class < ? > getModelClass ( ) { return modelClass ; } public List < String > getTsvColumns ( ) { return targetColumns ; } public abstract Properties toProperties ( ) ; } public static class ImportTable extends Table { private static final String K_TARGET_TABLES = "" ; private static final String P_TSV_COLUMNS = "" ; private static final String P_SEARCH_CONDITION = "" ; private static final String P_CACHE_ID = "" ; private static final String P_LOCK_TYPE = "" ; private static final String P_LOCKED_OPERATION = "" ; private static final String P_BEAN_NAME = "" ; private static final String P_DESTINATION = "" ; private final String searchConditionOrNull ; private final String cacheId ; private final LockType lockType ; private final LockedOperation lockedOperation ; private final Location destination ; public ImportTable ( Class < ? > modelClass , String name , List < String > targetColumns , String searchConditionOrNull , String cacheId , LockType lockType , LockedOperation lockedOperation , Location destination ) { super ( modelClass , name , targetColumns ) ; if ( lockType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( lockedOperation == null ) { throw new IllegalArgumentException ( "" ) ; } if ( destination == null ) { throw new IllegalArgumentException ( "" ) ; } this . searchConditionOrNull = searchConditionOrNull ; this . cacheId = cacheId ; this . lockType = lockType ; this . lockedOperation = lockedOperation ; this . destination = destination ; } public Location getDestination ( ) { return destination ; } static Properties toProperties ( List < ImportTable > list ) { assert list != null ; Properties properties = new Properties ( ) ; properties . setProperty ( K_TARGET_TABLES , join ( toNames ( list ) ) ) ; for ( ImportTable table : list ) { properties . putAll ( table . toProperties ( ) ) ; } return properties ; } @ Override public Properties toProperties ( ) { String prefix = getName ( ) ; Properties p = new Properties ( ) ; p . setProperty ( prefix + P_TSV_COLUMNS , join ( getTsvColumns ( ) ) ) ; if ( searchConditionOrNull != null ) { p . setProperty ( prefix + P_SEARCH_CONDITION , searchConditionOrNull ) ; } if ( cacheId != null ) { p . setProperty ( prefix + P_CACHE_ID , String . valueOf ( cacheId ) ) ; } p . setProperty ( prefix + P_LOCK_TYPE , String . valueOf ( lockType . id ) ) ; p . setProperty ( prefix + P_LOCKED_OPERATION , String . valueOf ( lockedOperation . id ) ) ; p . setProperty ( prefix + P_BEAN_NAME , String . valueOf ( getModelClass ( ) . getName ( ) ) ) ; p . setProperty ( prefix + P_DESTINATION , String . valueOf ( toPath ( destination ) ) ) ; return p ; } public static List < ImportTable > fromProperties ( Properties properties , ClassLoader loaderOrNull ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } ClassLoader loader = ( loaderOrNull == null ) ? BulkLoaderScript . class . getClassLoader ( ) : loaderOrNull ; List < ImportTable > results = Lists . create ( ) ; for ( String prefix : split ( get ( properties , K_TARGET_TABLES , true ) ) ) { results . add ( fromProperties ( properties , prefix , loader ) ) ; } return results ; } private static ImportTable fromProperties ( Properties p , String name , ClassLoader loader ) { assert p != null ; assert name != null ; assert loader != null ; Class < ? > modelClass ; try { modelClass = Class . forName ( get ( p , name + P_BEAN_NAME , true ) , false , loader ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( e ) ; } List < String > targetColumns = split ( get ( p , name + P_TSV_COLUMNS , true ) ) ; String searchConditionOrNull = get ( p , name + P_SEARCH_CONDITION , false ) ; String cacheId = get ( p , name + P_CACHE_ID , false ) ; LockType lockType = LockType . idOf ( get ( p , name + P_LOCK_TYPE , true ) ) ; LockedOperation lockedOperation = LockedOperation . idOf ( get ( p , name + P_LOCKED_OPERATION , true ) ) ; Location destination = fromPath ( get ( p , name + P_DESTINATION , true ) ) ; return new ImportTable ( modelClass , name , targetColumns , searchConditionOrNull , cacheId , lockType , lockedOperation , destination ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + getModelClass ( ) . hashCode ( ) ; result = prime * result + getName ( ) . hashCode ( ) ; result = prime * result + getTsvColumns ( ) . hashCode ( ) ; result = prime * result + destination . hashCode ( ) ; result = prime * result + lockType . hashCode ( ) ; result = prime * result + lockedOperation . hashCode ( ) ; result = prime * result + ( ( searchConditionOrNull == null ) ? : searchConditionOrNull . hashCode ( ) ) ; result = prime * result + ( ( cacheId == null ) ? : cacheId . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ImportTable other = ( ImportTable ) obj ; if ( getModelClass ( ) != other . getModelClass ( ) ) { return false ; } if ( getName ( ) . equals ( other . getName ( ) ) == false ) { return false ; } if ( getTsvColumns ( ) . equals ( other . getTsvColumns ( ) ) == false ) { return false ; } if ( destination . equals ( other . destination ) == false ) { return false ; } if ( lockType != other . lockType ) { return false ; } if ( lockedOperation != other . lockedOperation ) { return false ; } if ( searchConditionOrNull == null ) { if ( other . searchConditionOrNull != null ) { return false ; } } else if ( searchConditionOrNull . equals ( other . searchConditionOrNull ) == false ) { return false ; } if ( cacheId == null ) { if ( other . cacheId != null ) { return false ; } } else if ( cacheId . equals ( other . cacheId ) == false ) { return false ; } return true ; } } public static class ExportTable extends Table { private static final String K_TARGET_TABLES = "" ; private static final String P_BEAN_NAME = "" ; private static final String P_TSV_COLUMNS = "" ; private static final String P_TARGET_COLUMNS = "" ; private static final String P_SOURCES = "" ; private final List < String > exportColumns ; private final List < Location > sources ; private final DuplicateRecordErrorTable duplicateRecordError ; public ExportTable ( Class < ? > modelClass , String name , List < String > tsvColumns , List < String > exportColumns , DuplicateRecordErrorTable duplicateRecordError , List < Location > sources ) { super ( modelClass , name , tsvColumns ) ; this . sources = sources ; this . exportColumns = exportColumns ; this . duplicateRecordError = duplicateRecordError ; } public List < Location > getSources ( ) { return sources ; } static Properties toProperties ( List < ExportTable > list ) { assert list != null ; Properties properties = new Properties ( ) ; properties . setProperty ( K_TARGET_TABLES , join ( toNames ( list ) ) ) ; for ( ExportTable table : list ) { properties . putAll ( table . toProperties ( ) ) ; } return properties ; } @ Override public Properties toProperties ( ) { String prefix = getName ( ) ; Properties p = new Properties ( ) ; p . setProperty ( prefix + P_TSV_COLUMNS , join ( getTsvColumns ( ) ) ) ; p . setProperty ( prefix + P_TARGET_COLUMNS , join ( exportColumns ) ) ; p . setProperty ( prefix + P_BEAN_NAME , String . valueOf ( getModelClass ( ) . getName ( ) ) ) ; p . setProperty ( prefix + P_SOURCES , String . valueOf ( join ( toPaths ( sources ) ) ) ) ; if ( duplicateRecordError != null ) { Properties sub = duplicateRecordError . toProperties ( prefix ) ; p . putAll ( sub ) ; } return p ; } public static List < ExportTable > fromProperties ( Properties properties , ClassLoader loaderOrNull ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } ClassLoader loader = ( loaderOrNull == null ) ? BulkLoaderScript . class . getClassLoader ( ) : loaderOrNull ; List < ExportTable > results = Lists . create ( ) ; for ( String prefix : split ( get ( properties , K_TARGET_TABLES , true ) ) ) { results . add ( fromProperties ( properties , prefix , loader ) ) ; } return results ; } private static ExportTable fromProperties ( Properties p , String name , ClassLoader loader ) { assert p != null ; assert name != null ; assert loader != null ; Class < ? > modelClass ; try { modelClass = Class . forName ( get ( p , name + P_BEAN_NAME , true ) , false , loader ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( e ) ; } List < String > tsvColumns = split ( get ( p , name + P_TSV_COLUMNS , true ) ) ; List < String > exportColumns = split ( get ( p , name + P_TARGET_COLUMNS , true ) ) ; List < Location > sources = fromPaths ( split ( get ( p , name + P_SOURCES , true ) ) ) ; DuplicateRecordErrorTable ucError = DuplicateRecordErrorTable . fromProperties ( p , name ) ; return new ExportTable ( modelClass , name , tsvColumns , exportColumns , ucError , sources ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + getModelClass ( ) . hashCode ( ) ; result = prime * result + getName ( ) . hashCode ( ) ; result = prime * result + getTsvColumns ( ) . hashCode ( ) ; result = prime * result + exportColumns . hashCode ( ) ; result = prime * result + ( duplicateRecordError == null ? : duplicateRecordError . hashCode ( ) ) ; result = prime * result + sources . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTable other = ( ExportTable ) obj ; if ( getModelClass ( ) != other . getModelClass ( ) ) { return false ; } if ( getName ( ) . equals ( other . getName ( ) ) == false ) { return false ; } if ( getTsvColumns ( ) . equals ( other . getTsvColumns ( ) ) == false ) { return false ; } if ( exportColumns . equals ( other . exportColumns ) == false ) { return false ; } if ( duplicateRecordError == null ) { if ( other . duplicateRecordError != null ) { return false ; } } else if ( duplicateRecordError . equals ( other . duplicateRecordError ) == false ) { return false ; } if ( sources . equals ( other . sources ) == false ) { return false ; } return true ; } } public static class DuplicateRecordErrorTable { private static final String P_TABLE_NAME = "" ; private static final String P_TARGET_COLUMNS = "" ; private static final String P_KEY_COLUMNS = "" ; private static final String P_ERROR_CODE_COLUMN = "" ; private static final String P_ERROR_CODE_VALUE = "" ; private final List < String > targetColumns ; private final List < String > keyColumns ; private final String errorCodeColumn ; private final String errorCodeValue ; private final String tableName ; public DuplicateRecordErrorTable ( String tableName , List < String > targetColumns , List < String > keyColumns , String errorCodeColumn , String errorCodeValue ) { if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetColumns == null ) { throw new IllegalArgumentException ( "" ) ; } if ( keyColumns == null ) { throw new IllegalArgumentException ( "" ) ; } if ( errorCodeColumn == null ) { throw new IllegalArgumentException ( "" ) ; } if ( errorCodeValue == null ) { throw new IllegalArgumentException ( "" ) ; } this . tableName = tableName ; this . targetColumns = targetColumns ; this . keyColumns = keyColumns ; this . errorCodeColumn = errorCodeColumn ; this . errorCodeValue = errorCodeValue ; } public Properties toProperties ( String prefix ) { if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } Properties p = new Properties ( ) ; p . setProperty ( prefix + P_TABLE_NAME , tableName ) ; p . setProperty ( prefix + P_TARGET_COLUMNS , join ( targetColumns ) ) ; p . setProperty ( prefix + P_KEY_COLUMNS , join ( keyColumns ) ) ; p . setProperty ( prefix + P_ERROR_CODE_COLUMN , errorCodeColumn ) ; p . setProperty ( prefix + P_ERROR_CODE_VALUE , errorCodeValue ) ; return p ; } static DuplicateRecordErrorTable fromProperties ( Properties p , String name ) { assert p != null ; assert name != null ; String tableName = get ( p , name + P_TABLE_NAME , false ) ; String rawTargetColumns = get ( p , name + P_TARGET_COLUMNS , false ) ; String rawKeyColumns = get ( p , name + P_KEY_COLUMNS , false ) ; String errorColumn = get ( p , name + P_ERROR_CODE_COLUMN , false ) ; String errorCode = get ( p , name + P_ERROR_CODE_VALUE , false ) ; if ( tableName == null || tableName . isEmpty ( ) ) { return null ; } checkProperties ( name , rawTargetColumns , rawKeyColumns , errorColumn , errorCode ) ; List < String > targetColumns = split ( rawTargetColumns ) ; List < String > keyColumns = split ( rawKeyColumns ) ; return new DuplicateRecordErrorTable ( tableName , targetColumns , keyColumns , errorColumn , errorCode ) ; } private static void checkProperties ( String name , String rawTargetColumns , String rawKeyColumns , String errorColumn , String errorCode ) { if ( rawTargetColumns == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , P_TARGET_COLUMNS ) ) ; } if ( rawKeyColumns == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , P_KEY_COLUMNS ) ) ; } if ( errorColumn == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , P_ERROR_CODE_COLUMN ) ) ; } if ( errorCode == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , P_ERROR_CODE_VALUE ) ) ; } } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + tableName . hashCode ( ) ; result = prime * result + targetColumns . hashCode ( ) ; result = prime * result + keyColumns . hashCode ( ) ; result = prime * result + errorCodeColumn . hashCode ( ) ; result = prime * result + errorCodeValue . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DuplicateRecordErrorTable other = ( DuplicateRecordErrorTable ) obj ; if ( ! tableName . equals ( other . tableName ) ) { return false ; } if ( ! targetColumns . equals ( other . targetColumns ) ) { return false ; } if ( ! keyColumns . equals ( other . keyColumns ) ) { return false ; } if ( ! errorCodeColumn . equals ( other . errorCodeColumn ) ) { return false ; } if ( ! errorCodeValue . equals ( other . errorCodeValue ) ) { return false ; } return true ; } } public enum LockType { TABLE ( ) , ROW ( ) , UNLOCKED ( ) , ; public final int id ; private LockType ( int identifier ) { this . id = identifier ; } static LockType idOf ( String id ) { assert id != null ; int idNum ; try { idNum = Integer . parseInt ( id ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( id ) ; } for ( LockType constant : values ( ) ) { if ( constant . id == idNum ) { return constant ; } } throw new IllegalArgumentException ( id ) ; } } public enum LockedOperation { SKIP ( ) , FORCE ( ) , ERROR ( ) , ; public final int id ; private LockedOperation ( int identifier ) { this . id = identifier ; } static LockedOperation idOf ( String id ) { assert id != null ; int idNum ; try { idNum = Integer . parseInt ( id ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( id ) ; } for ( LockedOperation constant : values ( ) ) { if ( constant . id == idNum ) { return constant ; } } throw new IllegalArgumentException ( id ) ; } } } package com . asakusafw . compiler . bulkloader ; import java . io . IOException ; import java . io . OutputStream ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . TreeSet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . DuplicateRecordErrorTable ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . ExportTable ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . ImportTable ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . LockType ; import com . asakusafw . compiler . bulkloader . BulkLoaderScript . LockedOperation ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . mapreduce . parallel . ParallelSortClientEmitter ; import com . asakusafw . compiler . flow . mapreduce . parallel . ResolvedSlot ; import com . asakusafw . compiler . flow . mapreduce . parallel . Slot ; import com . asakusafw . compiler . flow . mapreduce . parallel . SlotResolver ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; import com . asakusafw . thundergate . runtime . property . PathConstants ; import com . asakusafw . thundergate . runtime . property . PropertyLoader ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . bulkloader . BulkLoadExporterDescription ; import com . asakusafw . vocabulary . bulkloader . BulkLoadExporterDescription . DuplicateRecordCheck ; import com . asakusafw . vocabulary . bulkloader . BulkLoadImporterDescription ; import com . asakusafw . vocabulary . bulkloader . BulkLoadImporterDescription . Mode ; import com . asakusafw . vocabulary . bulkloader . SecondaryImporterDescription ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription . DataSize ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class BulkLoaderIoProcessor extends ExternalIoDescriptionProcessor { static final Logger LOG = LoggerFactory . getLogger ( BulkLoaderIoProcessor . class ) ; private static final String CMD_IMPORTER = PathConstants . PATH_IMPORTER ; private static final String CMD_EXPORTER = PathConstants . PATH_EXPORTER ; private static final String CMD_FINALIZER = PathConstants . PATH_FINALIZER ; private static final String CMD_CACHE_FINALIZER = PathConstants . PATH_CACHE_FINALIZER ; private static final String CMD_ARG_PRIMARY = "" ; private static final String CMD_ARG_SECONDARY = "" ; private static final String MODULE_NAME = "" ; private static final String MODULE_NAME_PREFIX = "" ; private static final String CACHE_FEATURE_PREFIX = "" ; private static final Location CACHE_HEAD_CONTENTS = new Location ( null , CacheStorage . HEAD_DIRECTORY_NAME ) . append ( TemporaryOutputFormat . DEFAULT_FILE_NAME ) . asPrefix ( ) ; @ Override public Class < ? extends ImporterDescription > getImporterDescriptionType ( ) { return BulkLoadImporterDescription . class ; } @ Override public Class < ? extends ExporterDescription > getExporterDescriptionType ( ) { return BulkLoadExporterDescription . class ; } @ Override public boolean validate ( List < InputDescription > inputs , List < OutputDescription > outputs ) { LOG . debug ( "" , inputs , outputs ) ; boolean valid = true ; valid &= checkImports ( inputs ) ; valid &= checkExports ( outputs ) ; valid &= checkAssignment ( inputs , outputs ) ; return valid ; } private boolean checkImports ( List < InputDescription > inputs ) { assert inputs != null ; boolean valid = true ; for ( InputDescription input : inputs ) { BulkLoadImporterDescription desc = extract ( input ) ; boolean cacheEnabled = desc . isCacheEnabled ( ) ; if ( cacheEnabled ) { if ( ThunderGateCacheSupport . class . isAssignableFrom ( desc . getModelType ( ) ) == false ) { getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , desc . getModelType ( ) . getName ( ) ) ; valid = false ; } if ( desc . getWhere ( ) != null && desc . getWhere ( ) . trim ( ) . isEmpty ( ) == false ) { getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , desc . getWhere ( ) ) ; valid = false ; } if ( desc . getLockType ( ) == BulkLoadImporterDescription . LockType . ROW || desc . getLockType ( ) == BulkLoadImporterDescription . LockType . ROW_OR_SKIP ) { getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , desc . getLockType ( ) ) ; valid = false ; } if ( desc . getDataSize ( ) == DataSize . TINY || desc . getDataSize ( ) == DataSize . SMALL ) { getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , desc . getDataSize ( ) ) ; valid = false ; } } } return valid ; } private boolean checkExports ( List < OutputDescription > outputs ) { assert outputs != null ; boolean valid = true ; for ( OutputDescription output : outputs ) { BulkLoadExporterDescription desc = extract ( output ) ; Set < String > columns = Sets . from ( desc . getColumnNames ( ) ) ; if ( columns . containsAll ( desc . getTargetColumnNames ( ) ) == false ) { getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , diff ( desc . getTargetColumnNames ( ) , columns ) ) ; valid = false ; } DuplicateRecordCheck dupCheck = desc . getDuplicateRecordCheck ( ) ; if ( dupCheck != null ) { if ( columns . containsAll ( dupCheck . getColumnNames ( ) ) == false ) { getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , diff ( dupCheck . getColumnNames ( ) , columns ) ) ; valid = false ; } if ( columns . containsAll ( dupCheck . getCheckColumnNames ( ) ) == false ) { getEnvironment ( ) . error ( "" , diff ( dupCheck . getCheckColumnNames ( ) , columns ) ) ; valid = false ; } } } return valid ; } private Set < String > diff ( Collection < String > a , Collection < String > b ) { assert a != null ; assert b != null ; Set < String > diff = new TreeSet < String > ( a ) ; diff . removeAll ( b ) ; return diff ; } private boolean checkAssignment ( List < InputDescription > inputs , List < OutputDescription > outputs ) { assert inputs != null ; assert outputs != null ; Set < String > primaryTargets = Sets . create ( ) ; Set < String > secondaryTargets = Sets . create ( ) ; for ( InputDescription description : inputs ) { BulkLoadImporterDescription desc = extract ( description ) ; if ( desc . getMode ( ) == Mode . PRIMARY ) { primaryTargets . add ( desc . getTargetName ( ) ) ; } else { secondaryTargets . add ( desc . getTargetName ( ) ) ; if ( desc . getLockType ( ) != BulkLoadImporterDescription . LockType . UNUSED ) { getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) ) ; return false ; } } } if ( primaryTargets . size ( ) >= ) { getEnvironment ( ) . error ( "" , primaryTargets , SecondaryImporterDescription . class . getSimpleName ( ) ) ; return false ; } for ( String primary : primaryTargets ) { if ( secondaryTargets . contains ( primary ) ) { LOG . warn ( "" , primary ) ; } } Set < String > exportTargets = Sets . create ( ) ; for ( OutputDescription description : outputs ) { BulkLoadExporterDescription desc = extract ( description ) ; exportTargets . add ( desc . getTargetName ( ) ) ; } if ( exportTargets . size ( ) >= ) { getEnvironment ( ) . error ( "" , primaryTargets ) ; return false ; } if ( primaryTargets . isEmpty ( ) || exportTargets . isEmpty ( ) ) { return true ; } if ( primaryTargets . equals ( exportTargets ) == false ) { getEnvironment ( ) . error ( "" , primaryTargets , exportTargets ) ; return false ; } return true ; } @ Override public SourceInfo getInputInfo ( InputDescription description ) { Set < Location > locations = Collections . singleton ( getInputLocation ( description ) ) ; return new SourceInfo ( locations , TemporaryInputFormat . class ) ; } @ Override public List < CompiledStage > emitEpilogue ( IoContext context ) throws IOException { if ( context . getOutputs ( ) . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < Slot > slots = Lists . create ( ) ; for ( Output output : context . getOutputs ( ) ) { Slot slot = toSlot ( output ) ; slots . add ( slot ) ; } List < ResolvedSlot > resolved = new SlotResolver ( getEnvironment ( ) ) . resolve ( slots ) ; if ( getEnvironment ( ) . hasError ( ) ) { return Collections . emptyList ( ) ; } ParallelSortClientEmitter emitter = new ParallelSortClientEmitter ( getEnvironment ( ) ) ; CompiledStage stage = emitter . emit ( MODULE_NAME , resolved , getEnvironment ( ) . getEpilogueLocation ( MODULE_NAME ) ) ; return Collections . singletonList ( stage ) ; } private Slot toSlot ( Output output ) { BulkLoadExporterDescription desc = extract ( output . getDescription ( ) ) ; String name = normalize ( output . getDescription ( ) . getName ( ) ) ; return new Slot ( name , output . getDescription ( ) . getDataType ( ) , desc . getPrimaryKeyNames ( ) , output . getSources ( ) , TemporaryOutputFormat . class ) ; } private Location getImporterDestination ( InputDescription input ) { assert input != null ; if ( isCacheEnabled ( input ) ) { BulkLoadImporterDescription desc = extract ( input ) ; return computeCacheDirectory ( desc . calculateCacheId ( ) , desc . getTargetName ( ) , desc . getTableName ( ) ) ; } else { String name = normalize ( input . getName ( ) ) ; return getEnvironment ( ) . getPrologueLocation ( MODULE_NAME ) . append ( name ) ; } } private Location getInputLocation ( InputDescription input ) { assert input != null ; if ( isCacheEnabled ( input ) ) { return getImporterDestination ( input ) . append ( CACHE_HEAD_CONTENTS ) ; } else { return getImporterDestination ( input ) ; } } private Location getOutputLocation ( OutputDescription output ) { assert output != null ; String name = normalize ( output . getName ( ) ) ; return getEnvironment ( ) . getEpilogueLocation ( MODULE_NAME ) . append ( name ) . asPrefix ( ) ; } private boolean isCacheEnabled ( InputDescription description ) { assert description != null ; return extract ( description ) . isCacheEnabled ( ) ; } public static Location computeCacheDirectory ( String cacheId , String targetName , String tableName ) { if ( cacheId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } return new Location ( null , "" ) . append ( "" ) . append ( targetName ) . append ( tableName ) . append ( cacheId ) ; } private String normalize ( String name ) { assert name != null ; assert name . trim ( ) . isEmpty ( ) == false ; String memberName = JavaName . of ( name ) . toMemberName ( ) ; StringBuilder buf = new StringBuilder ( ) ; for ( char c : memberName . toCharArray ( ) ) { if ( ( '' <= c && c <= '' ) || ( '' <= c && c <= '' ) || ( '' <= c && c <= '' ) ) { buf . append ( c ) ; } } if ( buf . length ( ) == ) { buf . append ( "" ) ; } return buf . toString ( ) ; } @ Override public void emitPackage ( IoContext context ) throws IOException { Map < String , BulkLoaderScript > scripts = toScripts ( context ) ; for ( Map . Entry < String , BulkLoaderScript > entry : scripts . entrySet ( ) ) { String targetName = entry . getKey ( ) ; BulkLoaderScript script = entry . getValue ( ) ; emitProperties ( PropertyLoader . getImporterPropertiesPath ( targetName ) , script . getImporterProperties ( ) ) ; emitProperties ( PropertyLoader . getExporterPropertiesPath ( targetName ) , script . getExporterProperties ( ) ) ; } } private Map < String , BulkLoaderScript > toScripts ( IoContext context ) { assert context != null ; Map < String , List < Input > > inputs = Maps . create ( ) ; for ( Input input : context . getInputs ( ) ) { String target = extract ( input . getDescription ( ) ) . getTargetName ( ) ; Maps . addToList ( inputs , target , input ) ; } Map < String , List < Output > > outputs = Maps . create ( ) ; for ( Output output : context . getOutputs ( ) ) { String target = extract ( output . getDescription ( ) ) . getTargetName ( ) ; Maps . addToList ( outputs , target , output ) ; } Set < String > targets = Sets . create ( ) ; targets . addAll ( inputs . keySet ( ) ) ; targets . addAll ( outputs . keySet ( ) ) ; Map < String , BulkLoaderScript > results = Maps . create ( ) ; for ( String target : targets ) { List < Input > in = inputs . get ( target ) ; List < Output > out = outputs . get ( target ) ; in = ( in == null ) ? Collections . < Input > emptyList ( ) : in ; out = ( out == null ) ? Collections . < Output > emptyList ( ) : out ; results . put ( target , toScript ( in , out ) ) ; } return results ; } private BulkLoaderScript toScript ( List < Input > inputs , List < Output > outputs ) { List < ImportTable > imports = Lists . create ( ) ; List < ExportTable > exports = Lists . create ( ) ; for ( Input input : inputs ) { imports . add ( convert ( input . getDescription ( ) ) ) ; } for ( Output output : outputs ) { exports . add ( convert ( output . getDescription ( ) ) ) ; } BulkLoaderScript script = new BulkLoaderScript ( imports , exports ) ; return script ; } private ImportTable convert ( InputDescription input ) { assert input != null ; BulkLoadImporterDescription desc = extract ( input ) ; LockType lockType ; LockedOperation lockedOperation ; switch ( desc . getLockType ( ) ) { case CHECK : lockType = LockType . UNLOCKED ; lockedOperation = LockedOperation . ERROR ; break ; case ROW : lockType = LockType . ROW ; lockedOperation = LockedOperation . ERROR ; break ; case ROW_OR_SKIP : lockType = LockType . ROW ; lockedOperation = LockedOperation . SKIP ; break ; case TABLE : lockType = LockType . TABLE ; lockedOperation = LockedOperation . ERROR ; break ; case UNUSED : lockType = LockType . UNLOCKED ; lockedOperation = LockedOperation . FORCE ; break ; default : throw new AssertionError ( desc . getLockType ( ) ) ; } return new ImportTable ( desc . getModelType ( ) , desc . getTableName ( ) , desc . getColumnNames ( ) , desc . getWhere ( ) , desc . isCacheEnabled ( ) ? desc . calculateCacheId ( ) : null , lockType , lockedOperation , getImporterDestination ( input ) ) ; } private ExportTable convert ( OutputDescription output ) { assert output != null ; BulkLoadExporterDescription desc = extract ( output ) ; DuplicateRecordCheck duplicate = desc . getDuplicateRecordCheck ( ) ; if ( duplicate == null ) { return new ExportTable ( desc . getModelType ( ) , desc . getTableName ( ) , desc . getColumnNames ( ) , desc . getTargetColumnNames ( ) , null , Collections . singletonList ( getOutputLocation ( output ) ) ) ; } else { return new ExportTable ( desc . getModelType ( ) , desc . getTableName ( ) , desc . getColumnNames ( ) , desc . getTargetColumnNames ( ) , new DuplicateRecordErrorTable ( duplicate . getTableName ( ) , duplicate . getColumnNames ( ) , duplicate . getCheckColumnNames ( ) , duplicate . getErrorCodeColumnName ( ) , duplicate . getErrorCodeValue ( ) ) , Collections . singletonList ( getOutputLocation ( output ) ) ) ; } } private void emitProperties ( String path , Properties properties ) throws IOException { assert path != null ; assert properties != null ; OutputStream output = getEnvironment ( ) . openResource ( null , path ) ; try { properties . store ( output , getEnvironment ( ) . getTargetId ( ) ) ; } finally { output . close ( ) ; } } private BulkLoadImporterDescription extract ( InputDescription description ) { assert description != null ; ImporterDescription importer = description . getImporterDescription ( ) ; assert importer != null ; assert importer instanceof BulkLoadImporterDescription ; return ( BulkLoadImporterDescription ) importer ; } private BulkLoadExporterDescription extract ( OutputDescription description ) { assert description != null ; ExporterDescription exporter = description . getExporterDescription ( ) ; assert exporter != null ; assert exporter instanceof BulkLoadExporterDescription ; return ( BulkLoadExporterDescription ) exporter ; } @ Override public ExternalIoCommandProvider createCommandProvider ( IoContext context ) { String primary = null ; Set < String > targets = new TreeSet < String > ( ) ; Set < String > cacheUsers = new TreeSet < String > ( ) ; for ( Input input : context . getInputs ( ) ) { BulkLoadImporterDescription desc = extract ( input . getDescription ( ) ) ; String target = desc . getTargetName ( ) ; if ( desc . getMode ( ) == Mode . PRIMARY ) { assert primary == null || primary . equals ( target ) ; primary = target ; } targets . add ( target ) ; if ( isCacheEnabled ( input . getDescription ( ) ) ) { cacheUsers . add ( target ) ; } } for ( Output output : context . getOutputs ( ) ) { BulkLoadExporterDescription desc = extract ( output . getDescription ( ) ) ; String target = desc . getTargetName ( ) ; assert primary == null || primary . equals ( target ) ; primary = target ; targets . add ( target ) ; } if ( primary != null ) { targets . remove ( primary ) ; } return new CommandProvider ( getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) , primary , Lists . from ( targets ) , Lists . from ( cacheUsers ) ) ; } static ExternalIoCommandProvider findRelated ( List < ExternalIoCommandProvider > commands ) { for ( ExternalIoCommandProvider provider : commands ) { if ( provider instanceof CommandProvider ) { return provider ; } } return null ; } static String getProfileName ( String targetName ) { assert targetName != null ; return targetName ; } public static class CommandProvider extends ExternalIoCommandProvider { private static final long serialVersionUID = ; private final String batchId ; private final String flowId ; private final String primary ; private final List < String > secondaries ; private final List < String > cacheUsers ; CommandProvider ( String batchId , String flowId , String primary , List < String > secondaries , List < String > cacheUsers ) { assert batchId != null ; assert flowId != null ; assert secondaries != null ; assert cacheUsers != null ; this . batchId = batchId ; this . flowId = flowId ; this . primary = primary ; this . secondaries = Lists . from ( secondaries ) ; this . cacheUsers = Lists . from ( cacheUsers ) ; } @ Override public String getName ( ) { return MODULE_NAME ; } @ Override public List < Command > getImportCommand ( CommandContext context ) { List < Command > results = Lists . create ( ) ; if ( primary != null ) { results . add ( new Command ( Arrays . asList ( new String [ ] { context . getHomePathPrefix ( ) + CMD_IMPORTER , CMD_ARG_PRIMARY , primary , batchId , flowId , context . getExecutionId ( ) , "" , context . getVariableList ( ) , } ) , MODULE_NAME_PREFIX + primary , getProfileName ( primary ) , getEnvironment ( context ) ) ) ; } for ( String secondary : secondaries ) { results . add ( new Command ( Arrays . asList ( new String [ ] { context . getHomePathPrefix ( ) + CMD_IMPORTER , CMD_ARG_SECONDARY , secondary , batchId , flowId , context . getExecutionId ( ) , "" , context . getVariableList ( ) , } ) , MODULE_NAME_PREFIX + secondary , getProfileName ( secondary ) , getEnvironment ( context ) ) ) ; } return results ; } @ Override public List < Command > getExportCommand ( CommandContext context ) { List < Command > results = Lists . create ( ) ; if ( primary != null ) { results . add ( new Command ( Arrays . asList ( new String [ ] { context . getHomePathPrefix ( ) + CMD_EXPORTER , primary , batchId , flowId , context . getExecutionId ( ) , context . getVariableList ( ) , } ) , MODULE_NAME_PREFIX + primary , getProfileName ( primary ) , getEnvironment ( context ) ) ) ; } return results ; } @ Override public List < Command > getFinalizeCommand ( CommandContext context ) { List < Command > results = Lists . create ( ) ; if ( primary != null ) { results . add ( new Command ( Arrays . asList ( new String [ ] { context . getHomePathPrefix ( ) + CMD_FINALIZER , primary , batchId , flowId , context . getExecutionId ( ) , } ) , MODULE_NAME_PREFIX + primary , getProfileName ( primary ) , getEnvironment ( context ) ) ) ; } for ( String cacheUser : cacheUsers ) { results . add ( new Command ( Arrays . asList ( new String [ ] { context . getHomePathPrefix ( ) + CMD_CACHE_FINALIZER , cacheUser , context . getExecutionId ( ) , } ) , CACHE_FEATURE_PREFIX + cacheUser , getProfileName ( cacheUser ) , getEnvironment ( context ) ) ) ; } return results ; } private Map < String , String > getEnvironment ( CommandContext context ) { return Collections . emptyMap ( ) ; } } } package com . asakusafw . thundergate . runtime . cache ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . File ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Collections ; import java . util . Date ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . IOUtils ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class CacheStorageTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void deleteHead ( ) throws Exception { File dir = folder . newFolder ( "" ) ; dir . delete ( ) ; CacheStorage storage = new CacheStorage ( new Configuration ( ) , dir . toURI ( ) ) ; try { Path content = storage . getHeadContents ( "" ) ; FSDataOutputStream output = storage . getFileSystem ( ) . create ( content ) ; try { IOUtils . copyBytes ( new ByteArrayInputStream ( "" . getBytes ( ) ) , output , storage . getConfiguration ( ) ) ; } finally { output . close ( ) ; } assertThat ( storage . getFileSystem ( ) . exists ( storage . getHeadDirectory ( ) ) , is ( true ) ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getPatchDirectory ( ) ) , is ( false ) ) ; storage . deleteHead ( ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getHeadDirectory ( ) ) , is ( false ) ) ; } finally { storage . close ( ) ; } } @ Test public void deletePatch ( ) throws Exception { File dir = folder . newFolder ( "" ) ; dir . delete ( ) ; CacheStorage storage = new CacheStorage ( new Configuration ( ) , dir . toURI ( ) ) ; try { Path content = storage . getPatchContents ( "" ) ; FSDataOutputStream output = storage . getFileSystem ( ) . create ( content ) ; try { IOUtils . copyBytes ( new ByteArrayInputStream ( "" . getBytes ( ) ) , output , storage . getConfiguration ( ) ) ; } finally { output . close ( ) ; } assertThat ( storage . getFileSystem ( ) . exists ( storage . getPatchDirectory ( ) ) , is ( true ) ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getHeadDirectory ( ) ) , is ( false ) ) ; storage . deletePatch ( ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getPatchDirectory ( ) ) , is ( false ) ) ; } finally { storage . close ( ) ; } } @ Test public void deleteAll ( ) throws Exception { File dir = folder . newFolder ( "" ) ; dir . delete ( ) ; CacheStorage storage = new CacheStorage ( new Configuration ( ) , dir . toURI ( ) ) ; try { Path headContent = storage . getHeadContents ( "" ) ; FSDataOutputStream headOutput = storage . getFileSystem ( ) . create ( headContent ) ; try { IOUtils . copyBytes ( new ByteArrayInputStream ( "" . getBytes ( ) ) , headOutput , storage . getConfiguration ( ) ) ; } finally { headOutput . close ( ) ; } Path patchContent = storage . getPatchContents ( "" ) ; FSDataOutputStream patchOutput = storage . getFileSystem ( ) . create ( patchContent ) ; try { IOUtils . copyBytes ( new ByteArrayInputStream ( "" . getBytes ( ) ) , patchOutput , storage . getConfiguration ( ) ) ; } finally { patchOutput . close ( ) ; } assertThat ( storage . getFileSystem ( ) . exists ( storage . getHeadDirectory ( ) ) , is ( true ) ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getPatchDirectory ( ) ) , is ( true ) ) ; assertThat ( storage . deleteAll ( ) , is ( true ) ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getHeadDirectory ( ) ) , is ( false ) ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getPatchDirectory ( ) ) , is ( false ) ) ; } finally { storage . close ( ) ; } } @ Test public void deleteAll_missing ( ) throws Exception { File dir = folder . newFolder ( "" ) ; Assume . assumeTrue ( dir . delete ( ) ) ; CacheStorage storage = new CacheStorage ( new Configuration ( ) , dir . toURI ( ) ) ; try { assertThat ( storage . deleteAll ( ) , is ( false ) ) ; } finally { storage . close ( ) ; } } @ Test public void putPatchCacheInfo ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; File dir = folder . newFolder ( "" ) ; dir . delete ( ) ; CacheStorage storage = new CacheStorage ( new Configuration ( ) , dir . toURI ( ) ) ; try { storage . putPatchCacheInfo ( info ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getPatchDirectory ( ) ) , is ( true ) ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getHeadDirectory ( ) ) , is ( false ) ) ; CacheInfo restored = storage . getPatchCacheInfo ( ) ; assertThat ( restored . getFeatureVersion ( ) , is ( info . getFeatureVersion ( ) ) ) ; assertThat ( restored . getId ( ) , is ( info . getId ( ) ) ) ; assertThat ( tos ( restored . getTimestamp ( ) ) , is ( tos ( info . getTimestamp ( ) ) ) ) ; assertThat ( restored . getTableName ( ) , is ( info . getTableName ( ) ) ) ; assertThat ( restored . getColumnNames ( ) , is ( info . getColumnNames ( ) ) ) ; assertThat ( restored . getModelClassName ( ) , is ( info . getModelClassName ( ) ) ) ; assertThat ( restored . getModelClassVersion ( ) , is ( info . getModelClassVersion ( ) ) ) ; } finally { storage . close ( ) ; } } @ Test public void putHeadCacheInfo ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; File dir = folder . newFolder ( "" ) ; dir . delete ( ) ; CacheStorage storage = new CacheStorage ( new Configuration ( ) , dir . toURI ( ) ) ; try { storage . putHeadCacheInfo ( info ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getPatchDirectory ( ) ) , is ( false ) ) ; assertThat ( storage . getFileSystem ( ) . exists ( storage . getHeadDirectory ( ) ) , is ( true ) ) ; CacheInfo restored = storage . getHeadCacheInfo ( ) ; assertThat ( restored . getFeatureVersion ( ) , is ( info . getFeatureVersion ( ) ) ) ; assertThat ( restored . getId ( ) , is ( info . getId ( ) ) ) ; assertThat ( tos ( restored . getTimestamp ( ) ) , is ( tos ( info . getTimestamp ( ) ) ) ) ; assertThat ( restored . getTableName ( ) , is ( info . getTableName ( ) ) ) ; assertThat ( restored . getColumnNames ( ) , is ( info . getColumnNames ( ) ) ) ; assertThat ( restored . getModelClassName ( ) , is ( info . getModelClassName ( ) ) ) ; assertThat ( restored . getModelClassVersion ( ) , is ( info . getModelClassVersion ( ) ) ) ; } finally { storage . close ( ) ; } } private String tos ( Calendar calendar ) { return new SimpleDateFormat ( "" ) . format ( calendar . getTime ( ) ) ; } private Calendar calendar ( String string ) { Date date ; try { date = new SimpleDateFormat ( "" ) . parse ( string ) ; } catch ( ParseException e ) { throw new AssertionError ( e ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( date ) ; calendar . set ( Calendar . MILLISECOND , ) ; return calendar ; } } package com . asakusafw . thundergate . runtime . property ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . util . Properties ; import java . util . zip . ZipOutputStream ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; public class PropertyLoaderTest { private File zip ; @ Before public void setUp ( ) throws Exception { zip = File . createTempFile ( getClass ( ) . getSimpleName ( ) , "" ) ; } @ After public void tearDown ( ) throws Exception { if ( zip != null && zip . exists ( ) ) { assertThat ( zip . delete ( ) , is ( true ) ) ; } } @ Test public void loadImporterProperties ( ) throws Exception { Properties source = new Properties ( ) ; source . setProperty ( "" , "" ) ; OutputStream out = new FileOutputStream ( zip ) ; try { ZipOutputStream archive = new ZipOutputStream ( out ) ; PropertyLoader . saveImporterProperties ( archive , "" , source ) ; archive . close ( ) ; } finally { out . close ( ) ; } PropertyLoader loader = new PropertyLoader ( zip , "" ) ; try { Properties importer = loader . loadImporterProperties ( ) ; assertThat ( importer , is ( source ) ) ; try { loader . loadExporterProperties ( ) ; fail ( ) ; } catch ( IOException e ) { } } finally { loader . close ( ) ; } } @ Test public void loadExporterProperties ( ) throws Exception { Properties source = new Properties ( ) ; source . setProperty ( "" , "" ) ; OutputStream out = new FileOutputStream ( zip ) ; try { ZipOutputStream archive = new ZipOutputStream ( out ) ; PropertyLoader . saveExporterProperties ( archive , "" , source ) ; archive . close ( ) ; } finally { out . close ( ) ; } PropertyLoader loader = new PropertyLoader ( zip , "" ) ; try { Properties exporter = loader . loadExporterProperties ( ) ; assertThat ( exporter , is ( source ) ) ; try { loader . loadImporterProperties ( ) ; fail ( ) ; } catch ( IOException e ) { } } finally { loader . close ( ) ; } } } package com . asakusafw . thundergate . runtime . cache ; import java . text . MessageFormat ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Collection ; import java . util . Collections ; import java . util . Date ; import java . util . Iterator ; import java . util . Properties ; import java . util . Set ; import java . util . TreeSet ; public class CacheInfo { private static final String COLUMN_SEPARATOR = "" ; public static final String FEATURE_VERSION = "" ; public static final String KEY_FEATURE_VERSION = "" ; public static final String KEY_ID = "" ; public static final String KEY_TIMESTAMP = "" ; public static final String KEY_TABLE_NAME = "" ; public static final String KEY_COLUMN_NAMES = "" ; public static final String KEY_MODEL_CLASS_NAME = "" ; public static final String KEY_MODEL_CLASS_VERSION = "" ; public static final String FORMAT_TIMESTAMP = "" ; private final String featureVersion ; private final String id ; private final Calendar timestamp ; private final String tableName ; private final Set < String > columnNames ; private final String modelClassName ; private final long modelClassVersion ; public CacheInfo ( String featureVersion , String id , Calendar timestamp , String tableName , Collection < String > columnNames , String modelClassName , long modelClassVersion ) { if ( featureVersion == null ) { throw new IllegalArgumentException ( "" ) ; } if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } if ( timestamp == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } if ( modelClassName == null ) { throw new IllegalArgumentException ( "" ) ; } this . featureVersion = featureVersion ; this . id = id ; this . timestamp = ( Calendar ) timestamp . clone ( ) ; this . timestamp . set ( Calendar . MILLISECOND , ) ; this . tableName = tableName ; this . columnNames = new TreeSet < String > ( columnNames ) ; this . modelClassName = modelClassName ; this . modelClassVersion = modelClassVersion ; } public String getFeatureVersion ( ) { return featureVersion ; } public String getId ( ) { return id ; } public Calendar getTimestamp ( ) { return ( Calendar ) timestamp . clone ( ) ; } public String getTableName ( ) { return tableName ; } public Set < String > getColumnNames ( ) { return columnNames ; } public String getModelClassName ( ) { return modelClassName ; } public long getModelClassVersion ( ) { return modelClassVersion ; } public static CacheInfo loadFrom ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } String featureVersion = loadProperty ( properties , KEY_FEATURE_VERSION ) ; String id = loadProperty ( properties , KEY_ID ) ; String timestampString = loadProperty ( properties , KEY_TIMESTAMP ) ; String tableName = loadProperty ( properties , KEY_TABLE_NAME ) ; String columnNamesString = loadProperty ( properties , KEY_COLUMN_NAMES ) ; String modelClassName = loadProperty ( properties , KEY_MODEL_CLASS_NAME ) ; String modelClassVersionString = loadProperty ( properties , KEY_MODEL_CLASS_VERSION ) ; Calendar timestamp ; try { Date date = new SimpleDateFormat ( FORMAT_TIMESTAMP ) . parse ( timestampString ) ; timestamp = Calendar . getInstance ( ) ; timestamp . setTime ( date ) ; } catch ( ParseException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , KEY_TIMESTAMP , FORMAT_TIMESTAMP , timestampString ) , e ) ; } Set < String > columnNames = split ( columnNamesString ) ; long modelClassVersion ; try { modelClassVersion = Long . parseLong ( modelClassVersionString ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , KEY_MODEL_CLASS_VERSION , modelClassVersionString ) , e ) ; } return new CacheInfo ( featureVersion , id , timestamp , tableName , columnNames , modelClassName , modelClassVersion ) ; } private static String loadProperty ( Properties properties , String key ) { assert properties != null ; assert key != null ; String property = properties . getProperty ( key ) ; if ( property == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , key ) ) ; } return property . trim ( ) ; } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } properties . setProperty ( KEY_FEATURE_VERSION , featureVersion ) ; properties . setProperty ( KEY_ID , id ) ; properties . setProperty ( KEY_TIMESTAMP , new SimpleDateFormat ( FORMAT_TIMESTAMP ) . format ( timestamp . getTime ( ) ) ) ; properties . setProperty ( KEY_TABLE_NAME , tableName ) ; properties . setProperty ( KEY_COLUMN_NAMES , join ( columnNames ) ) ; properties . setProperty ( KEY_MODEL_CLASS_NAME , modelClassName ) ; properties . setProperty ( KEY_MODEL_CLASS_VERSION , String . valueOf ( modelClassVersion ) ) ; } private static Set < String > split ( String packed ) { assert packed != null ; Set < String > results = new TreeSet < String > ( ) ; String [ ] entries = packed . split ( COLUMN_SEPARATOR ) ; Collections . addAll ( results , entries ) ; return results ; } private static String join ( Collection < String > strings ) { assert strings != null ; StringBuilder buf = new StringBuilder ( ) ; Iterator < String > iter = strings . iterator ( ) ; assert iter . hasNext ( ) ; buf . append ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( COLUMN_SEPARATOR ) ; buf . append ( iter . next ( ) ) ; } return buf . toString ( ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + columnNames . hashCode ( ) ; result = prime * result + featureVersion . hashCode ( ) ; result = prime * result + id . hashCode ( ) ; result = prime * result + modelClassName . hashCode ( ) ; result = prime * result + ( int ) ( modelClassVersion ^ ( modelClassVersion > > > ) ) ; result = prime * result + tableName . hashCode ( ) ; result = prime * result + timestamp . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } CacheInfo other = ( CacheInfo ) obj ; if ( ! columnNames . equals ( other . columnNames ) ) { return false ; } if ( ! featureVersion . equals ( other . featureVersion ) ) { return false ; } if ( ! id . equals ( other . id ) ) { return false ; } if ( ! modelClassName . equals ( other . modelClassName ) ) { return false ; } if ( modelClassVersion != other . modelClassVersion ) { return false ; } if ( ! tableName . equals ( other . tableName ) ) { return false ; } if ( ! timestamp . equals ( other . timestamp ) ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( featureVersion ) ; builder . append ( "" ) ; builder . append ( id ) ; builder . append ( "" ) ; builder . append ( timestamp ) ; builder . append ( "" ) ; builder . append ( tableName ) ; builder . append ( "" ) ; builder . append ( columnNames ) ; builder . append ( "" ) ; builder . append ( modelClassName ) ; builder . append ( "" ) ; builder . append ( modelClassVersion ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . thundergate . runtime . cache ; import java . io . Closeable ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import java . util . Properties ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; public class CacheStorage implements Closeable { public static final String HEAD_DIRECTORY_NAME = "" ; public static final String PATCH_DIRECTORY_NAME = "" ; public static final String TEMP_DIRECTORY_NAME = "" ; public static final String META_FILE_NAME = "" ; public static final String CONTENT_FILE_PREFIX = TemporaryOutputFormat . DEFAULT_FILE_NAME + "" ; public static final String CONTENT_FILE_GLOB = CONTENT_FILE_PREFIX + "" ; private final FileSystem fs ; private final Path cacheDir ; public CacheStorage ( Configuration configuration , URI cacheDir ) throws IOException { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( cacheDir == null ) { throw new IllegalArgumentException ( "" ) ; } this . cacheDir = new Path ( cacheDir ) ; this . fs = this . cacheDir . getFileSystem ( configuration ) ; } public FileSystem getFileSystem ( ) { return fs ; } public Configuration getConfiguration ( ) { return fs . getConf ( ) ; } public void deleteHead ( ) throws IOException { fs . delete ( getHeadDirectory ( ) , true ) ; } public void deletePatch ( ) throws IOException { fs . delete ( getPatchDirectory ( ) , true ) ; } public CacheInfo getHeadCacheInfo ( ) throws IOException { return getCacheInfo ( getHeadProperties ( ) ) ; } public CacheInfo getPatchCacheInfo ( ) throws IOException { return getCacheInfo ( getPatchProperties ( ) ) ; } private CacheInfo getCacheInfo ( Path path ) throws IOException { assert path != null ; if ( fs . exists ( path ) == false ) { return null ; } Properties properties = new Properties ( ) ; FSDataInputStream in = fs . open ( path ) ; try { properties . load ( in ) ; } finally { in . close ( ) ; } try { return CacheInfo . loadFrom ( properties ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , path ) , e ) ; } } public void putHeadCacheInfo ( CacheInfo info ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } putCacheInfo ( info , getHeadProperties ( ) ) ; } public void putPatchCacheInfo ( CacheInfo info ) throws IOException { if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } putCacheInfo ( info , getPatchProperties ( ) ) ; } private void putCacheInfo ( CacheInfo info , Path path ) throws IOException { assert info != null ; assert path != null ; Properties properties = new Properties ( ) ; info . storeTo ( properties ) ; FSDataOutputStream out = fs . create ( path ) ; try { properties . store ( out , MessageFormat . format ( "" , info . getId ( ) ) ) ; } finally { out . close ( ) ; } } public boolean deleteAll ( ) throws IOException { if ( fs . exists ( cacheDir ) == false ) { return false ; } return fs . delete ( cacheDir , true ) ; } public Path getTempoaryDirectory ( ) { return cacheDir ; } public Path getHeadDirectory ( ) { return new Path ( cacheDir , HEAD_DIRECTORY_NAME ) ; } public Path getHeadProperties ( ) { return new Path ( getHeadDirectory ( ) , META_FILE_NAME ) ; } public Path getHeadContents ( String suffix ) { return new Path ( getHeadDirectory ( ) , CONTENT_FILE_PREFIX + suffix ) ; } public Path getPatchDirectory ( ) { return new Path ( cacheDir , PATCH_DIRECTORY_NAME ) ; } public Path getPatchProperties ( ) { return new Path ( getPatchDirectory ( ) , META_FILE_NAME ) ; } public Path getPatchContents ( String suffix ) { if ( suffix == null ) { throw new IllegalArgumentException ( "" ) ; } return new Path ( getPatchDirectory ( ) , CONTENT_FILE_PREFIX + suffix ) ; } @ Override public void close ( ) throws IOException { return ; } } package com . asakusafw . thundergate . runtime . cache ; package com . asakusafw . thundergate . runtime . cache ; public interface ThunderGateCacheSupport { long __tgc__DataModelVersion ( ) ; String __tgc__TimestampColumn ( ) ; long __tgc__SystemId ( ) ; boolean __tgc__Deleted ( ) ; } package com . asakusafw . thundergate . runtime . cache . mapreduce ; import java . io . IOException ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . Mapper ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class DeleteMapper extends Mapper < NullWritable , ThunderGateCacheSupport , NullWritable , ThunderGateCacheSupport > { @ Override protected void map ( NullWritable key , ThunderGateCacheSupport value , Context context ) throws IOException , InterruptedException { if ( value . __tgc__Deleted ( ) == false ) { context . write ( key , value ) ; } } } package com . asakusafw . thundergate . runtime . cache . mapreduce ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . fs . FileUtil ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . util . Tool ; import com . asakusafw . runtime . stage . StageInput ; import com . asakusafw . runtime . stage . input . StageInputDriver ; import com . asakusafw . runtime . stage . input . StageInputFormat ; import com . asakusafw . runtime . stage . input . StageInputMapper ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . output . LegacyBridgeOutputCommitter ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; public class CacheBuildClient extends Configured implements Tool { public static final String SUBCOMMAND_CREATE = "" ; public static final String SUBCOMMAND_UPDATE = "" ; private static final String NEXT_DIRECTORY_NAME = "" ; private static final String ESCAPE_DIRECTORY_NAME = "" ; static final Log LOG = LogFactory . getLog ( CacheBuildClient . class ) ; private CacheStorage storage ; private Class < ? > modelClass ; @ Override public int run ( String [ ] args ) throws Exception { if ( args . length != ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; } String subcommand = args [ ] ; boolean create ; if ( subcommand . equals ( SUBCOMMAND_CREATE ) ) { create = true ; } else if ( subcommand . equals ( SUBCOMMAND_UPDATE ) ) { create = false ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; } Path cacheDirectory = new Path ( args [ ] ) ; modelClass = getConf ( ) . getClassByName ( args [ ] ) ; this . storage = new CacheStorage ( getConf ( ) , cacheDirectory . toUri ( ) ) ; try { clearNext ( ) ; if ( create ) { create ( ) ; } else { update ( ) ; } switchHead ( ) ; } finally { storage . close ( ) ; } return ; } private void clearNext ( ) throws IOException { LOG . info ( MessageFormat . format ( "" , getNextDirectory ( ) ) ) ; storage . getFileSystem ( ) . delete ( getNextDirectory ( ) , true ) ; } private void update ( ) throws IOException , InterruptedException { Job job = new Job ( getConf ( ) ) ; job . setJobName ( "" + storage . getPatchDirectory ( ) ) ; List < StageInput > inputList = new ArrayList < StageInput > ( ) ; inputList . add ( new StageInput ( storage . getHeadContents ( "" ) . toString ( ) , TemporaryInputFormat . class , BaseMapper . class ) ) ; inputList . add ( new StageInput ( storage . getPatchContents ( "" ) . toString ( ) , TemporaryInputFormat . class , PatchMapper . class ) ) ; StageInputDriver . set ( job , inputList ) ; job . setInputFormatClass ( StageInputFormat . class ) ; job . setMapperClass ( StageInputMapper . class ) ; job . setMapOutputKeyClass ( PatchApplyKey . class ) ; job . setMapOutputValueClass ( modelClass ) ; job . setReducerClass ( PatchApplyReducer . class ) ; job . setOutputKeyClass ( NullWritable . class ) ; job . setOutputValueClass ( modelClass ) ; job . setPartitionerClass ( PatchApplyKey . Partitioner . class ) ; job . setSortComparatorClass ( PatchApplyKey . SortComparator . class ) ; job . setGroupingComparatorClass ( PatchApplyKey . GroupComparator . class ) ; TemporaryOutputFormat . setOutputPath ( job , getNextDirectory ( ) ) ; job . setOutputFormatClass ( TemporaryOutputFormat . class ) ; job . getConfiguration ( ) . setClass ( "" , LegacyBridgeOutputCommitter . class , org . apache . hadoop . mapred . OutputCommitter . class ) ; LOG . info ( MessageFormat . format ( "" , storage . getPatchContents ( "" ) , storage . getHeadContents ( "" ) , getNextContents ( ) ) ) ; try { boolean succeed = job . waitForCompletion ( true ) ; LOG . info ( MessageFormat . format ( "" , succeed , storage . getPatchContents ( "" ) , storage . getHeadContents ( "" ) , getNextContents ( ) ) ) ; if ( succeed == false ) { throw new IOException ( MessageFormat . format ( "" , storage . getPatchContents ( "" ) , storage . getHeadContents ( "" ) , getNextContents ( ) ) ) ; } } catch ( ClassNotFoundException e ) { throw new IOException ( e ) ; } LOG . info ( MessageFormat . format ( "" , storage . getPatchProperties ( ) , getNextDirectory ( ) ) ) ; FileUtil . copy ( storage . getFileSystem ( ) , storage . getPatchProperties ( ) , storage . getFileSystem ( ) , getNextProperties ( ) , false , storage . getConfiguration ( ) ) ; } private void create ( ) throws InterruptedException , IOException { Job job = new Job ( getConf ( ) ) ; job . setJobName ( "" + storage . getPatchDirectory ( ) ) ; List < StageInput > inputList = new ArrayList < StageInput > ( ) ; inputList . add ( new StageInput ( storage . getPatchContents ( "" ) . toString ( ) , TemporaryInputFormat . class , DeleteMapper . class ) ) ; StageInputDriver . set ( job , inputList ) ; job . setInputFormatClass ( StageInputFormat . class ) ; job . setMapperClass ( StageInputMapper . class ) ; job . setMapOutputKeyClass ( NullWritable . class ) ; job . setMapOutputValueClass ( modelClass ) ; job . setOutputKeyClass ( NullWritable . class ) ; job . setOutputValueClass ( modelClass ) ; TemporaryOutputFormat . setOutputPath ( job , getNextDirectory ( ) ) ; job . setOutputFormatClass ( TemporaryOutputFormat . class ) ; job . getConfiguration ( ) . setClass ( "" , LegacyBridgeOutputCommitter . class , org . apache . hadoop . mapred . OutputCommitter . class ) ; job . setNumReduceTasks ( ) ; LOG . info ( MessageFormat . format ( "" , storage . getPatchContents ( "" ) , storage . getHeadContents ( "" ) , getNextContents ( ) ) ) ; try { boolean succeed = job . waitForCompletion ( true ) ; LOG . info ( MessageFormat . format ( "" , succeed , storage . getPatchContents ( "" ) , storage . getHeadContents ( "" ) , getNextContents ( ) ) ) ; if ( succeed == false ) { throw new IOException ( MessageFormat . format ( "" , storage . getPatchContents ( "" ) , storage . getHeadContents ( "" ) , getNextContents ( ) ) ) ; } } catch ( ClassNotFoundException e ) { throw new IOException ( e ) ; } LOG . info ( MessageFormat . format ( "" , storage . getPatchProperties ( ) , getNextDirectory ( ) ) ) ; FileUtil . copy ( storage . getFileSystem ( ) , storage . getPatchProperties ( ) , storage . getFileSystem ( ) , getNextProperties ( ) , false , storage . getConfiguration ( ) ) ; } private void switchHead ( ) throws IOException { boolean hasHead = storage . getFileSystem ( ) . exists ( storage . getHeadDirectory ( ) ) ; if ( hasHead ) { LOG . info ( MessageFormat . format ( "" , storage . getHeadDirectory ( ) , getEscapeDir ( ) ) ) ; storage . getFileSystem ( ) . delete ( getEscapeDir ( ) , true ) ; storage . getFileSystem ( ) . rename ( storage . getHeadDirectory ( ) , getEscapeDir ( ) ) ; } LOG . info ( MessageFormat . format ( "" , getNextDirectory ( ) , storage . getHeadDirectory ( ) ) ) ; storage . getFileSystem ( ) . rename ( getNextDirectory ( ) , storage . getHeadDirectory ( ) ) ; if ( hasHead ) { LOG . info ( MessageFormat . format ( "" , storage . getHeadDirectory ( ) ) ) ; storage . getFileSystem ( ) . delete ( getEscapeDir ( ) , true ) ; } } private Path getNextDirectory ( ) { return new Path ( storage . getTempoaryDirectory ( ) , NEXT_DIRECTORY_NAME ) ; } private Path getNextProperties ( ) { return new Path ( getNextDirectory ( ) , CacheStorage . META_FILE_NAME ) ; } private Path getNextContents ( ) { return new Path ( getNextDirectory ( ) , CacheStorage . CONTENT_FILE_GLOB ) ; } private Path getEscapeDir ( ) { return new Path ( storage . getTempoaryDirectory ( ) , ESCAPE_DIRECTORY_NAME ) ; } } package com . asakusafw . thundergate . runtime . cache . mapreduce ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . Externalizable ; import java . io . IOException ; import java . io . ObjectInput ; import java . io . ObjectOutput ; import org . apache . hadoop . io . VIntWritable ; import org . apache . hadoop . io . VLongWritable ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . io . WritableComparable ; import org . apache . hadoop . io . WritableComparator ; import org . apache . hadoop . io . WritableFactories ; import org . apache . hadoop . io . WritableFactory ; import org . apache . hadoop . io . WritableUtils ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class PatchApplyKey implements WritableComparable < PatchApplyKey > { static final int POSITION_PATCH = ; static final int POSITION_BASE = ; final VLongWritable systemId = new VLongWritable ( ) ; final VIntWritable position = new VIntWritable ( ) ; public void setPatch ( ThunderGateCacheSupport model ) { systemId . set ( model . __tgc__SystemId ( ) ) ; position . set ( POSITION_PATCH ) ; } public void setBase ( ThunderGateCacheSupport model ) { systemId . set ( model . __tgc__SystemId ( ) ) ; position . set ( POSITION_BASE ) ; } @ Override public void write ( DataOutput out ) throws IOException { systemId . write ( out ) ; position . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { systemId . readFields ( in ) ; position . readFields ( in ) ; } @ Override public int compareTo ( PatchApplyKey other ) { int diffSystemId = systemId . compareTo ( other . systemId ) ; if ( diffSystemId != ) { return diffSystemId ; } int diffPosition = position . compareTo ( other . position ) ; if ( diffPosition != ) { return diffPosition ; } return ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + position . hashCode ( ) ; result = prime * result + systemId . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } PatchApplyKey other = ( PatchApplyKey ) obj ; if ( ! position . equals ( other . position ) ) { return false ; } if ( ! systemId . equals ( other . systemId ) ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( systemId ) ; builder . append ( "" ) ; builder . append ( position ) ; builder . append ( "" ) ; return builder . toString ( ) ; } public static final class SortComparator extends WritableComparator implements Externalizable { public SortComparator ( ) { super ( PatchApplyKey . class ) ; } @ Override public int compare ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { try { long id1 = readVLong ( b1 , s1 ) ; long id2 = readVLong ( b2 , s2 ) ; if ( id1 < id2 ) { return - ; } else if ( id1 > id2 ) { return + ; } int offset1 = WritableUtils . decodeVIntSize ( b1 [ s1 ] ) ; int offset2 = WritableUtils . decodeVIntSize ( b2 [ s2 ] ) ; long pos1 = readVLong ( b1 , s1 + offset1 ) ; long pos2 = readVLong ( b2 , s2 + offset2 ) ; if ( pos1 < pos2 ) { return - ; } else if ( pos1 > pos2 ) { return + ; } return ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { return ; } @ Override public void writeExternal ( ObjectOutput out ) throws IOException { return ; } private Object readResolve ( ) { return new SortComparator ( ) ; } } @ SuppressWarnings ( "" ) public static final class GroupComparator extends WritableComparator implements Externalizable { public GroupComparator ( ) { super ( PatchApplyKey . class ) ; } @ Override public int compare ( WritableComparable a , WritableComparable b ) { PatchApplyKey w1 = ( PatchApplyKey ) a ; PatchApplyKey w2 = ( PatchApplyKey ) b ; return w1 . systemId . compareTo ( w2 . systemId ) ; } @ Override public int compare ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) { try { long id1 = WritableComparator . readVLong ( b1 , s1 ) ; long id2 = WritableComparator . readVLong ( b2 , s2 ) ; if ( id1 < id2 ) { return - ; } else if ( id1 > id2 ) { return + ; } else { return ; } } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { return ; } @ Override public void writeExternal ( ObjectOutput out ) throws IOException { return ; } private Object readResolve ( ) { return new GroupComparator ( ) ; } } public static final class Partitioner extends org . apache . hadoop . mapreduce . Partitioner < PatchApplyKey , Object > { @ Override public int getPartition ( PatchApplyKey key , Object value , int numPartitions ) { int hash = key . systemId . hashCode ( ) & Integer . MAX_VALUE ; return hash % numPartitions ; } } static { WritableComparator . define ( PatchApplyKey . class , new SortComparator ( ) ) ; WritableFactories . setFactory ( PatchApplyKey . class , new WritableFactory ( ) { @ Override public Writable newInstance ( ) { return new PatchApplyKey ( ) ; } } ) ; } } package com . asakusafw . thundergate . runtime . cache . mapreduce ; import java . io . IOException ; import java . util . Iterator ; import org . apache . hadoop . mapreduce . Reducer ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class PatchApplyCombiner extends Reducer < PatchApplyKey , ThunderGateCacheSupport , PatchApplyKey , ThunderGateCacheSupport > { @ Override protected void reduce ( PatchApplyKey key , Iterable < ThunderGateCacheSupport > values , Context context ) throws IOException , InterruptedException { Iterator < ThunderGateCacheSupport > iter = values . iterator ( ) ; if ( iter . hasNext ( ) ) { ThunderGateCacheSupport first = iter . next ( ) ; context . write ( key , first ) ; } } } package com . asakusafw . thundergate . runtime . cache . mapreduce ; package com . asakusafw . thundergate . runtime . cache . mapreduce ; import java . io . IOException ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . Mapper ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class PatchMapper extends Mapper < NullWritable , ThunderGateCacheSupport , PatchApplyKey , ThunderGateCacheSupport > { private final PatchApplyKey shuffleKey = new PatchApplyKey ( ) ; @ Override protected void map ( NullWritable key , ThunderGateCacheSupport value , Context context ) throws IOException , InterruptedException { shuffleKey . setPatch ( value ) ; context . write ( shuffleKey , value ) ; } } package com . asakusafw . thundergate . runtime . cache . mapreduce ; import java . io . IOException ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . Mapper ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class BaseMapper extends Mapper < NullWritable , ThunderGateCacheSupport , PatchApplyKey , ThunderGateCacheSupport > { private final PatchApplyKey shuffleKey = new PatchApplyKey ( ) ; @ Override protected void map ( NullWritable key , ThunderGateCacheSupport value , Context context ) throws IOException , InterruptedException { shuffleKey . setBase ( value ) ; context . write ( shuffleKey , value ) ; } } package com . asakusafw . thundergate . runtime . cache . mapreduce ; import java . io . IOException ; import java . util . Iterator ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . Reducer ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class PatchApplyReducer extends Reducer < PatchApplyKey , ThunderGateCacheSupport , NullWritable , ThunderGateCacheSupport > { private static final NullWritable KEY = NullWritable . get ( ) ; @ Override protected void reduce ( PatchApplyKey key , Iterable < ThunderGateCacheSupport > values , Context context ) throws IOException , InterruptedException { Iterator < ThunderGateCacheSupport > iter = values . iterator ( ) ; if ( iter . hasNext ( ) ) { ThunderGateCacheSupport first = iter . next ( ) ; if ( first . __tgc__Deleted ( ) ) { } else { context . write ( KEY , first ) ; } } } } package com . asakusafw . thundergate . runtime . property ; public final class PathConstants { public static final String PATH_IMPORTER = "" ; public static final String PATH_EXPORTER = "" ; public static final String PATH_FINALIZER = "" ; public static final String PATH_CACHE_FINALIZER = "" ; private PathConstants ( ) { return ; } } package com . asakusafw . thundergate . runtime . property ; import java . io . Closeable ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . Properties ; import java . util . zip . ZipEntry ; import java . util . zip . ZipFile ; import java . util . zip . ZipOutputStream ; public class PropertyLoader implements Closeable { private static final String IMPORTER_PATH = "" ; private static final String EXPORTER_PATH = "" ; private final ZipFile zip ; private final String targetName ; public PropertyLoader ( File file , String targetName ) throws IOException { if ( file == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } this . zip = new ZipFile ( file ) ; this . targetName = targetName ; } @ Override public void close ( ) throws IOException { zip . close ( ) ; } public Properties loadImporterProperties ( ) throws IOException { String path = getImporterPropertiesPath ( targetName ) ; return loadProperties ( path ) ; } public Properties loadExporterProperties ( ) throws IOException { String path = getExporterPropertiesPath ( targetName ) ; return loadProperties ( path ) ; } public static String getImporterPropertiesPath ( String targetName ) { if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } String path = resolvePath ( IMPORTER_PATH , targetName ) ; return path ; } public static String getExporterPropertiesPath ( String targetName ) { if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } String path = resolvePath ( EXPORTER_PATH , targetName ) ; return path ; } public static void saveImporterProperties ( ZipOutputStream output , String targetName , Properties properties ) throws IOException { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } String path = getImporterPropertiesPath ( targetName ) ; saveProperties ( path , output , properties ) ; } public static void saveExporterProperties ( ZipOutputStream output , String targetName , Properties properties ) throws IOException { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } String path = getExporterPropertiesPath ( targetName ) ; saveProperties ( path , output , properties ) ; } private static String resolvePath ( String path , String targetName ) { assert path != null ; assert targetName != null ; return MessageFormat . format ( path , targetName ) ; } private static void saveProperties ( String path , ZipOutputStream target , Properties properties ) throws IOException { assert path != null ; assert target != null ; assert properties != null ; ZipEntry entry = new ZipEntry ( path ) ; target . putNextEntry ( entry ) ; properties . store ( target , path ) ; } private Properties loadProperties ( String path ) throws IOException { assert path != null ; Properties result = new Properties ( ) ; InputStream input = open ( path ) ; try { result . load ( input ) ; } finally { input . close ( ) ; } return result ; } private InputStream open ( String path ) throws IOException { assert path != null ; ZipEntry entry = zip . getEntry ( path ) ; if ( entry == null ) { throw new FileNotFoundException ( path ) ; } return zip . getInputStream ( entry ) ; } } package com . asakusafw . thundergate . runtime . property ; package com . asakusafw . bulkloader . recoverer ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . List ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . exporter . ExportDataCopy ; import com . asakusafw . bulkloader . exporter . LockRelease ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . testtools . inspect . Cause ; public class RecovererTest { static final Log LOG = new Log ( RecovererTest . class ) ; private static String targetName = "" ; private static List < String > PROPERTYS = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , PROPERTYS , targetName ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , PROPERTYS , targetName ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { createTable ( ) ; UnitTestUtil . tearDown ( ) ; } private void createTable ( ) throws Exception { String dropTemp1Sql = "" ; String dropTemp2Sql = "" ; String dropDup1Sql = "" ; String dropDup2Sql = "" ; StringBuilder temp1Sql = new StringBuilder ( ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; StringBuilder temp2Sql = new StringBuilder ( ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; StringBuilder dup1Sql = new StringBuilder ( ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; StringBuilder dup2Sql = new StringBuilder ( ) ; dup2Sql . append ( "" ) ; dup2Sql . append ( "" ) ; dup2Sql . append ( "" ) ; UnitTestUtil . executeUpdate ( dropTemp1Sql ) ; UnitTestUtil . executeUpdate ( dropTemp2Sql ) ; UnitTestUtil . executeUpdate ( dropDup1Sql ) ; UnitTestUtil . executeUpdate ( dropDup2Sql ) ; UnitTestUtil . executeUpdate ( temp1Sql . toString ( ) ) ; UnitTestUtil . executeUpdate ( temp2Sql . toString ( ) ) ; UnitTestUtil . executeUpdate ( dup1Sql . toString ( ) ) ; UnitTestUtil . executeUpdate ( dup2Sql . toString ( ) ) ; } @ Test public void executeTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void executeTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void executeTest03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void executeTest04 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest05 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest06 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest07 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest08 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest09 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest10 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest11 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest12 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest13 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest14 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest15 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest16 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest17 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest18 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest19 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest20 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest21 ( ) throws Exception { String dropSql1 = "" ; String dropSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void executeTest22 ( ) throws Exception { String dropSql1 = "" ; String dropSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void executeTest23 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest24 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest26 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void executeTest27 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest28 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void executeTest29 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new StubRecoverer ( ) { @ Override protected List < ExporterBean > selectRunningJobFlow ( String executionId ) throws BulkLoaderSystemException { ExporterBean bean = new ExporterBean ( ) ; bean . setExecutionId ( executionId ) ; bean . setBatchId ( "" ) ; bean . setJobflowId ( "" ) ; bean . setJobflowSid ( "" ) ; return Arrays . asList ( new ExporterBean [ ] { bean } ) ; } @ Override protected boolean isExecRecovery ( ExporterBean exporterBean , boolean hasParam ) throws BulkLoaderSystemException { return false ; } } ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void executeTest30 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; assertTrue ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; } @ Test public void executeTest31 ( ) throws Exception { String [ ] args = new String [ ] { "" , "" } ; Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest32 ( ) throws Exception { String [ ] args = new String [ ] { targetName } ; Recoverer recoverer = new StubRecoverer ( ) { @ Override protected List < ExporterBean > selectRunningJobFlow ( String executionId ) throws BulkLoaderSystemException { throw new BulkLoaderSystemException ( this . getClass ( ) , "" ) ; } } ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest33 ( ) throws Exception { String [ ] args = new String [ ] { targetName } ; Recoverer recoverer = new StubRecoverer ( ) { @ Override protected List < ExporterBean > selectRunningJobFlow ( String executionId ) throws BulkLoaderSystemException { throw new NullPointerException ( ) ; } } ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest34 ( ) throws Exception { String dropSql1 = "" ; String createSql1 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName } ; Recoverer recoverer = new StubRecoverer ( ) { @ Override protected ExportDataCopy createExportDataCopy ( ) { ExportDataCopy copy = new ExportDataCopy ( ) { @ Override public boolean copyData ( ExporterBean bean ) { return false ; } } ; return copy ; } } ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest35 ( ) throws Exception { String dropSql1 = "" ; String createSql1 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName } ; Recoverer recoverer = new StubRecoverer ( ) { @ Override protected LockRelease createLockRelease ( ) { LockRelease lock = new LockRelease ( ) { @ Override public boolean releaseLock ( ExporterBean bean , boolean isEndJobFlow ) { return false ; } } ; return lock ; } } ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest36 ( ) throws Exception { String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] { targetName , executionId } ; Recoverer recoverer = new Recoverer ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; return loder ; } } ; int result = recoverer . execute ( args ) ; assertEquals ( , result ) ; util = new TestUtils ( new File ( "" ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; } @ Test public void executeTest37 ( ) throws Exception { Recoverer recoverer = new StubRecoverer ( ) ; int result = recoverer . execute ( new String [ ] { targetName , executionId , "" } ) ; assertEquals ( , result ) ; } @ Test public void isExecRecoveryTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExecutionId ( "" ) ; bean . setJobflowId ( "" ) ; bean . setBatchId ( "" ) ; bean . setJobflowSid ( "" ) ; Recoverer recoverer = new StubRecoverer ( ) ; try { recoverer . isExecRecovery ( bean , false ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { e . printStackTrace ( ) ; assertTrue ( true ) ; } } @ Test public void isExecRecoveryTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExecutionId ( "" ) ; bean . setJobflowId ( "" ) ; bean . setBatchId ( "" ) ; bean . setJobflowSid ( "" ) ; Recoverer recoverer = new StubRecoverer ( ) { @ Override protected boolean isRunningJobFlow ( String executionId ) { return true ; } } ; boolean result = recoverer . isExecRecovery ( bean , false ) ; assertFalse ( result ) ; } @ Test public void loadParamTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExecutionId ( "" ) ; bean . setJobflowId ( "" ) ; bean . setBatchId ( "" ) ; bean . setJobflowSid ( "" ) ; Recoverer recoverer = new StubRecoverer ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loader = new JobFlowParamLoader ( ) { @ Override public boolean loadRecoveryParam ( String targetName , String batchId , String jobflowId ) { return false ; } } ; return loader ; } } ; try { recoverer . loadParam ( bean ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } @ Test public void loadParamTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_EXP_RETRY_COUNT , "" ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExecutionId ( "" ) ; bean . setJobflowId ( "" ) ; bean . setBatchId ( "" ) ; bean . setJobflowSid ( "" ) ; Recoverer recoverer = new StubRecoverer ( ) ; try { recoverer . loadParam ( bean ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } @ Test public void judgeRollBackTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExecutionId ( "" ) ; bean . setJobflowId ( "" ) ; bean . setBatchId ( "" ) ; bean . setJobflowSid ( "" ) ; Recoverer recoverer = new StubRecoverer ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { throw new BulkLoaderSystemException ( this . getClass ( ) , "" ) ; } } ; try { recoverer . judgeRollBack ( bean ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } } class StubRecoverer extends Recoverer { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File file , String targetName ) throws IOException { File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } @ Override protected Properties getImportProp ( File file , String targetName ) throws IOException { System . out . println ( file ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } } package com . asakusafw . bulkloader . collector ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . net . URI ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . Writable ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import test . modelgen . table . model . ImportTarget1 ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileList ; public class ExportFileSendTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" , "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void sendExportFileTest01 ( ) throws Exception { Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; table1 . setExportTargetType ( NullWritable . class ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; List < String > list2 = new ArrayList < String > ( ) ; list2 . add ( "" ) ; table2 . setDfsFilePaths ( list2 ) ; table2 . setExportTargetType ( NullWritable . class ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; DummyExportFileSend send = new DummyExportFileSend ( ) ; boolean result = send . sendExportFile ( bean , "" ) ; assertTrue ( result ) ; List < String > dirs = send . getDirs ( ) ; assertEquals ( , dirs . size ( ) ) ; assertEquals ( "" , dirs . get ( ) ) ; assertEquals ( "" , dirs . get ( ) ) ; assertEquals ( "" , dirs . get ( ) ) ; } @ Test public void sendExportFileTest05 ( ) throws Exception { Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; table1 . setExportTargetType ( NullWritable . class ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; List < String > list2 = new ArrayList < String > ( ) ; list2 . add ( "" ) ; table2 . setDfsFilePaths ( list2 ) ; table2 . setExportTargetType ( NullWritable . class ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; DummyExportFileSend send = new DummyExportFileSend ( ) { @ Override protected < T extends Writable > long send ( Class < T > targetTableModel , String dir , FileList . Writer writer , String tableName ) throws BulkLoaderSystemException { return - ; } } ; boolean result = send . sendExportFile ( bean , "" ) ; assertTrue ( result ) ; } @ Test public void sendTest01 ( ) throws Exception { File inFile = new File ( "" ) ; File outFile = new File ( "" ) ; Class < ImportTarget1 > targetTableModel = ImportTarget1 . class ; String tableName = "" ; try { FileList . Writer writer = FileList . createWriter ( new FileOutputStream ( outFile ) , true ) ; ExportFileSend send = new ExportFileSend ( ) ; URI inUri = inFile . toURI ( ) ; String inStr = inUri . toString ( ) ; send . send ( targetTableModel , inStr , writer , tableName ) ; writer . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } assertTrue ( outFile . exists ( ) ) ; outFile . delete ( ) ; } @ Test public void sendTest02 ( ) throws Exception { File inFile = new File ( "" ) ; File outFile = new File ( "" ) ; Class < ImportTarget1 > targetTableModel = ImportTarget1 . class ; String tableName = "" ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXP_LOAD_MAX_SIZE , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { FileList . Writer writer = FileList . createWriter ( new FileOutputStream ( outFile ) , true ) ; ExportFileSend send = new ExportFileSend ( ) ; URI inUri = inFile . toURI ( ) ; String inStr = inUri . toString ( ) ; send . send ( targetTableModel , inStr , writer , tableName ) ; writer . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } assertTrue ( outFile . exists ( ) ) ; outFile . delete ( ) ; } @ Test public void sendTest03 ( ) throws Exception { File inFile = new File ( "" ) ; File outFile = new File ( "" ) ; Class < ImportTarget1 > targetTableModel = ImportTarget1 . class ; String tableName = "" ; try { FileList . Writer writer = FileList . createWriter ( new FileOutputStream ( outFile ) , true ) ; ExportFileSend send = new ExportFileSend ( ) ; URI inUri = inFile . toURI ( ) ; String inStr = inUri . toString ( ) ; send . send ( targetTableModel , inStr , writer , tableName ) ; writer . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } assertTrue ( outFile . exists ( ) ) ; outFile . delete ( ) ; } @ Test public void sendTest04 ( ) throws Exception { File inFile = new File ( "" ) ; File outFile = new File ( "" ) ; Class < ImportTarget1 > targetTableModel = ImportTarget1 . class ; String tableName = "" ; try { FileList . Writer writer = FileList . createWriter ( new FileOutputStream ( outFile ) , true ) ; ExportFileSend send = new ExportFileSend ( ) ; URI inUri = inFile . toURI ( ) ; String inStr = inUri . toString ( ) ; send . send ( targetTableModel , inStr , writer , tableName ) ; writer . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } assertTrue ( outFile . exists ( ) ) ; outFile . delete ( ) ; } @ Test public void sendTest05 ( ) throws Exception { File inFile = new File ( "" ) ; File outFile = new File ( "" ) ; Class < ImportTarget1 > targetTableModel = ImportTarget1 . class ; String tableName = "" ; try { FileList . Writer writer = FileList . createWriter ( new FileOutputStream ( outFile ) , true ) ; ExportFileSend send = new ExportFileSend ( ) ; URI inUri = inFile . toURI ( ) ; String inStr = inUri . toString ( ) ; send . send ( targetTableModel , inStr , writer , tableName ) ; writer . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } assertTrue ( outFile . exists ( ) ) ; outFile . delete ( ) ; } @ Test public void sendTest06 ( ) throws Exception { File inFile = new File ( "" ) ; File outFile = new File ( "" ) ; Class < ImportTarget1 > targetTableModel = ImportTarget1 . class ; String tableName = "" ; try { FileList . Writer writer = FileList . createWriter ( new FileOutputStream ( outFile ) , true ) ; ExportFileSend send = new ExportFileSend ( ) ; URI inUri = inFile . toURI ( ) ; String inStr = inUri . toString ( ) ; send . send ( targetTableModel , inStr , writer , tableName ) ; writer . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } assertTrue ( outFile . exists ( ) ) ; outFile . delete ( ) ; } } class DummyExportFileSend extends ExportFileSend { List < String > dirs = new ArrayList < String > ( ) ; @ Override protected < T extends Writable > long send ( Class < T > targetTableModel , String filePath , FileList . Writer writer , String tableName ) throws BulkLoaderSystemException { dirs . add ( filePath ) ; return ; } public List < String > getDirs ( ) { return dirs ; } } package com . asakusafw . bulkloader . collector ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class CollectorTest { @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { } @ After public void tearDown ( ) throws Exception { } @ Test public void executeTest01 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Collector collector = new StubCollector ( ) ; int result = collector . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest02 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Collector collector = new StubCollector ( ) { @ Override protected ExportFileSend createExportFileSend ( ) { return new StubExportFileSend ( false ) ; } } ; int result = collector . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest03 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Collector collector = new StubCollector ( ) { @ Override protected ExportFileSend createExportFileSend ( ) { throw new NullPointerException ( ) ; } } ; int result = collector . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest04 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; Collector collector = new StubCollector ( ) ; int result = collector . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest05 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Collector collector = new StubCollector ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override public boolean loadExportParam ( String targetName , String batchId , String jobflowId ) { return false ; } } ; return loder ; } } ; int result = collector . execute ( args ) ; assertEquals ( , result ) ; } } class StubCollector extends Collector { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File file , String targetName ) throws IOException { File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } @ Override protected ExportFileSend createExportFileSend ( ) { return new StubExportFileSend ( ) ; } } class StubExportFileSend extends ExportFileSend { boolean result = true ; public StubExportFileSend ( ) { } public StubExportFileSend ( boolean result ) { this . result = result ; } @ Override public boolean sendExportFile ( ExporterBean bean , String user ) { return result ; } } package com . asakusafw . bulkloader . testutil ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . Enumeration ; import java . util . Properties ; import java . util . zip . ZipEntry ; import java . util . zip . ZipFile ; import java . util . zip . ZipInputStream ; import org . apache . commons . io . FileUtils ; import org . apache . commons . lang . SystemUtils ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . transfer . FileList ; public class UnitTestUtil { private static final String DELIM = "" ; private static final String SQLFILE_ENCODING = "" ; private static final String PATH_DIST_MAIN = "" ; private static final String PATH_DIST_TEST = "" ; private static final File targetDir = new File ( "" ) ; public static void setUpEnv ( ) throws Exception { Properties p = System . getProperties ( ) ; p . setProperty ( Constants . ASAKUSA_HOME , new File ( "" ) . getCanonicalPath ( ) ) ; p . setProperty ( Constants . THUNDER_GATE_HOME , new File ( PATH_DIST_TEST ) . getCanonicalPath ( ) ) ; ConfigurationLoader . setSysProp ( p ) ; System . setProperties ( p ) ; } public static void tearDownEnv ( ) throws Exception { Properties p = System . getProperties ( ) ; p . remove ( Constants . ASAKUSA_HOME ) ; p . remove ( Constants . THUNDER_GATE_HOME ) ; ConfigurationLoader . setSysProp ( p ) ; System . setProperties ( p ) ; } public static void setUpBeforeClass ( ) throws Exception { targetDir . mkdir ( ) ; if ( ! SystemUtils . IS_OS_WINDOWS ) { ProcessBuilder pb = new ProcessBuilder ( "" , "" , targetDir . getAbsolutePath ( ) ) ; pb . start ( ) ; } } public static void tearDownAfterClass ( ) throws Exception { FileUtils . deleteDirectory ( targetDir ) ; } private static File getHomeDir ( ) { return new File ( ConfigurationLoader . getEnvProperty ( Constants . ASAKUSA_HOME ) ) ; } private static File getHomeFile ( String path ) { File home = getHomeDir ( ) ; return new File ( home , path ) ; } public static void setUpDB ( ) throws Exception { File mainDir = getHomeFile ( PATH_DIST_MAIN ) ; File testDir = getHomeFile ( PATH_DIST_TEST ) ; File createSysTableSql = new File ( mainDir , "" ) ; File insertImportTableLockSql = new File ( testDir , "" ) ; File createUtestTableSql = new File ( testDir , "" ) ; File dropSysTableSql = new File ( mainDir , "" ) ; File dropUtestTableSql = new File ( testDir , "" ) ; executeWithFile ( dropUtestTableSql . getAbsolutePath ( ) ) ; executeWithFile ( dropSysTableSql . getAbsolutePath ( ) ) ; executeWithFile ( createSysTableSql . getAbsolutePath ( ) ) ; executeWithFile ( insertImportTableLockSql . getAbsolutePath ( ) ) ; executeWithFile ( createUtestTableSql . getAbsolutePath ( ) ) ; } public static void tearDownDB ( ) throws Exception { File mainDir = getHomeFile ( PATH_DIST_MAIN ) ; File testDir = getHomeFile ( PATH_DIST_TEST ) ; File dropSysTableSql = new File ( mainDir , "" ) ; File dropUtestTableSql = new File ( testDir , "" ) ; executeWithFile ( dropUtestTableSql . getAbsolutePath ( ) ) ; executeWithFile ( dropSysTableSql . getAbsolutePath ( ) ) ; } public static void startUp ( ) throws Exception { } public static void tearDown ( ) throws Exception { } public static boolean assertFile ( File expected , File actual ) throws FileNotFoundException , IOException { byte [ ] b1 = new byte [ ( int ) expected . length ( ) ] ; byte [ ] b2 = new byte [ ( int ) actual . length ( ) ] ; new FileInputStream ( expected ) . read ( b1 ) ; new FileInputStream ( actual ) . read ( b2 ) ; if ( b1 . length != b2 . length ) { return false ; } for ( int i = ; i < b1 . length ; i ++ ) { if ( b1 [ i ] != b2 [ i ] ) { return false ; } } return true ; } public static void createFileList ( File originalZipFile , File targetFileList ) throws IOException { ZipFile zip = new ZipFile ( originalZipFile ) ; try { FileOutputStream output = new FileOutputStream ( targetFileList ) ; try { FileList . Writer writer = FileList . createWriter ( output , true ) ; Enumeration < ? extends ZipEntry > entries = zip . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry next = entries . nextElement ( ) ; InputStream input = zip . getInputStream ( next ) ; try { OutputStream target = writer . openNext ( FileList . content ( next . getName ( ) . replace ( '' , '' ) ) ) ; try { IOUtils . pipingAndClose ( input , target ) ; } finally { target . close ( ) ; } } finally { input . close ( ) ; } } writer . close ( ) ; } finally { output . close ( ) ; } } finally { zip . close ( ) ; } } public static void assertSameFileList ( File fileList , File ... expected ) throws IOException { FileInputStream source = new FileInputStream ( fileList ) ; try { FileList . Reader reader = FileList . createReader ( source ) ; for ( File file : expected ) { assertThat ( "" + file , reader . next ( ) , is ( true ) ) ; InputStream expectedInput = null ; InputStream actualInput = null ; try { expectedInput = new FileInputStream ( file ) ; actualInput = reader . openContent ( ) ; } finally { StreamCloseLogic . closeGently ( expectedInput ) ; StreamCloseLogic . closeGently ( actualInput ) ; } } assertThat ( "" , reader . next ( ) , is ( false ) ) ; reader . close ( ) ; } finally { source . close ( ) ; } } public static boolean assertZipFile ( File [ ] expectedFile , File zipFile ) throws IOException { ZipInputStream zipIs = new ZipInputStream ( new FileInputStream ( zipFile ) ) ; ZipEntry zipEntry = null ; int i = ; while ( ( zipEntry = zipIs . getNextEntry ( ) ) != null ) { if ( zipEntry . isDirectory ( ) ) { continue ; } i ++ ; File tempFile = new File ( "" + String . valueOf ( i ) ) ; FileOutputStream fos = new FileOutputStream ( tempFile ) ; byte [ ] b = new byte [ ] ; while ( true ) { int read = zipIs . read ( b ) ; if ( read == - ) { break ; } fos . write ( b , , read ) ; } if ( ! assertFile ( expectedFile [ i - ] , tempFile ) ) { tempFile . delete ( ) ; return false ; } tempFile . delete ( ) ; } return true ; } public static int executeUpdate ( String sql ) throws Exception { Connection conn = null ; PreparedStatement stmt = null ; try { printLog ( "" + sql , "" ) ; conn = DBConnection . getConnection ( ) ; stmt = conn . prepareStatement ( sql ) ; int result = stmt . executeUpdate ( ) ; printLog ( "" + result , "" ) ; return result ; } finally { DBConnection . closePs ( stmt ) ; DBConnection . closeConn ( conn ) ; } } public static boolean isExistTable ( String tableName ) throws Exception { String url = ConfigurationLoader . getProperty ( Constants . PROP_KEY_DB_URL ) ; String schema = url . substring ( url . lastIndexOf ( "" ) + , url . length ( ) ) ; String sql = "" ; Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; try { printLog ( "" + sql + "" + tableName + "" + schema , "" ) ; conn = DBConnection . getConnection ( ) ; stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , tableName ) ; stmt . setString ( , schema ) ; rs = stmt . executeQuery ( ) ; if ( rs . next ( ) ) { int count = rs . getInt ( "" ) ; if ( count > ) { printLog ( "" + tableName , "" ) ; return true ; } else { printLog ( "" + tableName , "" ) ; return false ; } } else { printLog ( "" + tableName , "" ) ; return false ; } } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; DBConnection . closeConn ( conn ) ; } } public static boolean countAssert ( String tableName , int expected ) throws Exception { String sql = "" + tableName ; Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; try { printLog ( "" + sql , "" ) ; conn = DBConnection . getConnection ( ) ; stmt = conn . prepareStatement ( sql ) ; rs = stmt . executeQuery ( ) ; if ( rs . next ( ) ) { int count = rs . getInt ( "" ) ; if ( expected == count ) { printLog ( "" + count , "" ) ; return true ; } else { printLog ( "" + tableName , "" ) ; return false ; } } else { printLog ( "" + tableName , "" ) ; return false ; } } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; DBConnection . closeConn ( conn ) ; } } public static void executeWithFile ( String sqlFile ) throws Exception { BufferedReader reader = null ; FileInputStream fs = new FileInputStream ( sqlFile ) ; StringBuilder sb = new StringBuilder ( ) ; try { reader = new BufferedReader ( new InputStreamReader ( fs , SQLFILE_ENCODING ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . startsWith ( "" ) ) { continue ; } if ( line . startsWith ( "" ) ) { continue ; } sb . append ( line ) ; } } finally { fs . close ( ) ; if ( reader != null ) { reader . close ( ) ; } } String sql = sb . toString ( ) ; int beginIndex = ; int endIndex = ; String workSql = complementDelimiter ( sql ) ; while ( ( endIndex = workSql . indexOf ( DELIM , beginIndex ) ) != - ) { String oneStatement = workSql . substring ( beginIndex , endIndex ) ; if ( "" . equals ( oneStatement . trim ( ) ) ) { continue ; } executeUpdate ( oneStatement ) ; beginIndex = endIndex + ; } } private static String complementDelimiter ( String sql ) { if ( ! ( sql . trim ( ) . endsWith ( DELIM ) ) ) { return sql + DELIM ; } else { return sql ; } } public static void printLog ( String message , String method ) { } private static String getDate ( ) { SimpleDateFormat sdf = new SimpleDateFormat ( "" ) ; return sdf . format ( new Date ( ) ) ; } } package com . asakusafw . bulkloader . testutil ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . Reader ; import java . io . Writer ; public class IOUtils extends StreamCloseLogic { protected IOUtils ( ) { } public static long pipingAndClose ( final InputStream src , final OutputStream dest ) throws IOException { return pipingAndClose ( src , dest , - ) ; } public static long pipingAndClose ( final InputStream src , final OutputStream dest , final long len ) throws IOException { return pipingAndClose ( src , dest , , len ) ; } public static long pipingAndClose ( final InputStream src , final OutputStream dest , final long off , final long len ) throws IOException { return pipingAndClose ( src , dest , off , len , DEFAULT_BUFFER_SIZE ) ; } public static long pipingAndClose ( final InputStream src , final OutputStream dest , final long off , final long len , final int bufSize ) throws IOException { check ( src , dest , off , bufSize ) ; long result = ; try { result = piping ( src , dest , off , len , bufSize ) ; } finally { closeGently ( src ) ; closeGently ( dest ) ; } return result ; } } class StreamPipingLogic { static final int DEFAULT_BUFFER_SIZE = ; static final int EOF = - ; public static long piping ( final InputStream src , final OutputStream dest ) throws IOException { return piping ( src , dest , - ) ; } public static long piping ( final InputStream src , final OutputStream dest , final long len ) throws IOException { return piping ( src , dest , , len ) ; } public static long piping ( final InputStream src , final OutputStream dest , final long off , final long len ) throws IOException { return piping ( src , dest , off , len , DEFAULT_BUFFER_SIZE ) ; } public static long piping ( final InputStream src , final OutputStream dest , final long off , long len , final int bufSize ) throws IOException { check ( src , dest , off , bufSize ) ; if ( len < ) { len = Long . MAX_VALUE ; } skip ( src , off ) ; final byte [ ] buf = new byte [ bufSize ] ; long wroteBytes = ; while ( true ) { final long rest = len - wroteBytes ; if ( rest <= ) { break ; } final int readableLength ; if ( rest <= Integer . MAX_VALUE ) { readableLength = Math . min ( bufSize , ( int ) rest ) ; } else { readableLength = bufSize ; } final int readLength = src . read ( buf , , readableLength ) ; if ( readLength < ) { break ; } dest . write ( buf , , readLength ) ; wroteBytes += readLength ; } return wroteBytes ; } public static void skip ( final InputStream src , final long len ) throws IOException { for ( long rest = len ; < rest ; ) { final long skipped = src . skip ( rest ) ; if ( skipped <= ) { throw new IOException ( "" + len + "" + rest + "" ) ; } rest -= skipped ; } } static void check ( final InputStream src , final OutputStream dest , final long off , final int bufSize ) { if ( src == null ) { throw new NullPointerException ( "" ) ; } else if ( dest == null ) { throw new NullPointerException ( "" ) ; } else if ( off < ) { throw new IllegalArgumentException ( "" ) ; } else if ( bufSize <= ) { throw new IllegalArgumentException ( "" ) ; } } } class StreamCloseLogic extends StreamPipingLogic { public static void closeGently ( final InputStream src ) { ExceptionHandler . handle ( close ( src ) ) ; } public static void closeGently ( final OutputStream dest ) { ExceptionHandler . handle ( close ( dest ) ) ; } public static Throwable close ( final InputStream src ) { if ( src != null ) { try { src . close ( ) ; } catch ( final Throwable t ) { return t ; } } return null ; } public static Throwable close ( final OutputStream dest ) { if ( dest != null ) { try { dest . close ( ) ; } catch ( final Throwable t ) { return t ; } } return null ; } public static void closeGently ( final Reader src ) { ExceptionHandler . handle ( close ( src ) ) ; } public static void closeGently ( final Writer dest ) { ExceptionHandler . handle ( close ( dest ) ) ; } public static Throwable close ( final Reader src ) { if ( src != null ) { try { src . close ( ) ; } catch ( final Throwable t ) { return t ; } } return null ; } public static Throwable close ( final Writer dest ) { if ( dest != null ) { try { dest . close ( ) ; } catch ( final Throwable t ) { return t ; } } return null ; } } abstract class ExceptionHandler { private static final ExceptionHandler DEFAULT_HANDLER = new ExceptionHandler ( ) { @ Override public void handleThrowable ( final Throwable t ) { t . printStackTrace ( ) ; } } ; private static volatile ExceptionHandler handler = DEFAULT_HANDLER ; protected ExceptionHandler ( ) { } public abstract void handleThrowable ( final Throwable t ) ; public static ExceptionHandler getHandler ( ) { return handler ; } public static void setHandler ( ExceptionHandler handler ) { if ( handler == null ) { handler = DEFAULT_HANDLER ; } ExceptionHandler . handler = handler ; } public static void handle ( final Throwable t ) { if ( t == null ) { return ; } try { handler . handleThrowable ( t ) ; } catch ( final Throwable error ) { error . printStackTrace ( ) ; } } } package com . asakusafw . bulkloader . tools ; import static org . junit . Assert . * ; import java . io . File ; import java . util . Arrays ; import java . util . List ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . testtools . inspect . Cause ; public class DBCleanerTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; private static String targetName = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , targetName ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . setUpEnv ( ) ; UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void executeTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; createTempTable1 ( ) ; createTempTable2 ( ) ; String [ ] args = new String [ ] { targetName } ; DBCleaner cleaner = new DBCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; } @ Test public void executeTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; createTempTable1 ( ) ; createTempTable2 ( ) ; String [ ] args = new String [ ] { targetName } ; DBCleaner cleaner = new DBCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . isExistTable ( "" ) ) ; assertTrue ( UnitTestUtil . isExistTable ( "" ) ) ; assertTrue ( UnitTestUtil . isExistTable ( "" ) ) ; dropTable ( ) ; } @ Test public void executeTest03 ( ) throws Exception { String [ ] args = new String [ ] { "" } ; DBCleaner cleaner = new DBCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; result = cleaner . execute ( new String [ ] { } ) ; assertEquals ( , result ) ; } @ Test public void executeTest04 ( ) throws Exception { Properties p = System . getProperties ( ) ; p . setProperty ( Constants . ASAKUSA_HOME , "" ) ; ConfigurationLoader . setSysProp ( p ) ; String [ ] args = new String [ ] { targetName } ; DBCleaner cleaner = new DBCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; p . setProperty ( Constants . ASAKUSA_HOME , "" ) ; ConfigurationLoader . setSysProp ( p ) ; System . setProperties ( p ) ; } @ Test public void executeTest05 ( ) throws Exception { String [ ] args = new String [ ] { "" } ; DBCleaner cleaner = new DBCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest06 ( ) throws Exception { String [ ] args = new String [ ] { "" } ; DBCleaner cleaner = new DBCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; args = new String [ ] { targetName } ; cleaner . execute ( args ) ; } @ Test public void executeTest07 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; createTempTable1 ( ) ; createTempTable2 ( ) ; String [ ] args = new String [ ] { targetName } ; DBCleaner cleaner = new DBCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; } private void createTempTable1 ( ) throws Exception { String dropTemp1Sql = "" ; String dropDup1Sql = "" ; StringBuilder temp1Sql = new StringBuilder ( ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; temp1Sql . append ( "" ) ; StringBuilder dup1Sql = new StringBuilder ( ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; UnitTestUtil . executeUpdate ( dropTemp1Sql ) ; UnitTestUtil . executeUpdate ( dropDup1Sql ) ; UnitTestUtil . executeUpdate ( temp1Sql . toString ( ) ) ; UnitTestUtil . executeUpdate ( dup1Sql . toString ( ) ) ; } private void createTempTable2 ( ) throws Exception { String dropTemp2Sql = "" ; StringBuilder temp2Sql = new StringBuilder ( ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; temp2Sql . append ( "" ) ; UnitTestUtil . executeUpdate ( dropTemp2Sql ) ; UnitTestUtil . executeUpdate ( temp2Sql . toString ( ) ) ; } private void dropTable ( ) throws Exception { String dropTemp1Sql = "" ; String dropDup1Sql = "" ; String dropTemp2Sql = "" ; UnitTestUtil . executeUpdate ( dropTemp1Sql ) ; UnitTestUtil . executeUpdate ( dropTemp2Sql ) ; UnitTestUtil . executeUpdate ( dropTemp2Sql ) ; } } package com . asakusafw . bulkloader . exporter ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . ExportTempTableStatus ; import com . asakusafw . bulkloader . common . TsvDeleteType ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class JudgeExecProcessTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; } @ After public void tearDown ( ) throws Exception { } @ Test public void judgeTest01 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . TRUE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertTrue ( result ) ; assertFalse ( judge . isExecTempTableDelete ( ) ) ; assertTrue ( judge . isExecReceive ( ) ) ; assertTrue ( judge . isExecLoad ( ) ) ; assertTrue ( judge . isExecCopy ( ) ) ; assertTrue ( judge . isExecLockRelease ( ) ) ; assertTrue ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest02 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . FALSE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertTrue ( result ) ; assertFalse ( judge . isExecTempTableDelete ( ) ) ; assertTrue ( judge . isExecReceive ( ) ) ; assertTrue ( judge . isExecLoad ( ) ) ; assertTrue ( judge . isExecCopy ( ) ) ; assertTrue ( judge . isExecLockRelease ( ) ) ; assertFalse ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest03 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . TRUE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( null ) ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( null ) ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertTrue ( result ) ; assertTrue ( judge . isExecTempTableDelete ( ) ) ; assertTrue ( judge . isExecReceive ( ) ) ; assertTrue ( judge . isExecLoad ( ) ) ; assertTrue ( judge . isExecCopy ( ) ) ; assertTrue ( judge . isExecLockRelease ( ) ) ; assertTrue ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest04 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . FALSE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( null ) ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( null ) ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertTrue ( result ) ; assertTrue ( judge . isExecTempTableDelete ( ) ) ; assertTrue ( judge . isExecReceive ( ) ) ; assertTrue ( judge . isExecLoad ( ) ) ; assertTrue ( judge . isExecCopy ( ) ) ; assertTrue ( judge . isExecLockRelease ( ) ) ; assertFalse ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest05 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . TRUE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertTrue ( result ) ; assertTrue ( judge . isExecTempTableDelete ( ) ) ; assertTrue ( judge . isExecReceive ( ) ) ; assertTrue ( judge . isExecLoad ( ) ) ; assertTrue ( judge . isExecCopy ( ) ) ; assertTrue ( judge . isExecLockRelease ( ) ) ; assertTrue ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest06 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . FALSE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertTrue ( result ) ; assertTrue ( judge . isExecTempTableDelete ( ) ) ; assertTrue ( judge . isExecReceive ( ) ) ; assertTrue ( judge . isExecLoad ( ) ) ; assertTrue ( judge . isExecCopy ( ) ) ; assertTrue ( judge . isExecLockRelease ( ) ) ; assertFalse ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest07 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . TRUE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertTrue ( result ) ; assertFalse ( judge . isExecTempTableDelete ( ) ) ; assertFalse ( judge . isExecReceive ( ) ) ; assertFalse ( judge . isExecLoad ( ) ) ; assertTrue ( judge . isExecCopy ( ) ) ; assertTrue ( judge . isExecLockRelease ( ) ) ; assertFalse ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest08 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . TRUE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertTrue ( result ) ; assertFalse ( judge . isExecTempTableDelete ( ) ) ; assertFalse ( judge . isExecReceive ( ) ) ; assertFalse ( judge . isExecLoad ( ) ) ; assertFalse ( judge . isExecCopy ( ) ) ; assertTrue ( judge . isExecLockRelease ( ) ) ; assertFalse ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest09 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( null ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . TRUE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; return Arrays . asList ( tempBean ) ; } } ; boolean result = judge . judge ( bean ) ; assertFalse ( result ) ; assertFalse ( judge . isExecTempTableDelete ( ) ) ; assertFalse ( judge . isExecReceive ( ) ) ; assertFalse ( judge . isExecLoad ( ) ) ; assertFalse ( judge . isExecCopy ( ) ) ; assertFalse ( judge . isExecLockRelease ( ) ) ; assertFalse ( judge . isExecFileDelete ( ) ) ; } @ Test public void judgeTest10 ( ) throws Exception { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; Map < String , ExportTargetTableBean > targetTable = new HashMap < String , ExportTargetTableBean > ( ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; targetTable . put ( "" , new ExportTargetTableBean ( ) ) ; bean . setExportTargetTable ( targetTable ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , TsvDeleteType . TRUE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; JudgeExecProcess judge = new JudgeExecProcess ( ) { @ Override protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { throw new BulkLoaderSystemException ( this . getClass ( ) , "" ) ; } } ; boolean result = judge . judge ( bean ) ; assertFalse ( result ) ; assertFalse ( judge . isExecTempTableDelete ( ) ) ; assertFalse ( judge . isExecReceive ( ) ) ; assertFalse ( judge . isExecLoad ( ) ) ; assertFalse ( judge . isExecCopy ( ) ) ; assertFalse ( judge . isExecLockRelease ( ) ) ; assertFalse ( judge . isExecFileDelete ( ) ) ; } } package com . asakusafw . bulkloader . exporter ; import static org . junit . Assert . * ; import java . io . File ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class ExportFileDeleteTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void deleteFileTest01 ( ) throws Exception { File dumpDir = new File ( "" ) ; File importFile1 = new File ( dumpDir , "" ) ; File importFile2 = new File ( dumpDir , "" ) ; File importFile3 = new File ( dumpDir , "" ) ; importFile1 . createNewFile ( ) ; importFile2 . createNewFile ( ) ; importFile3 . createNewFile ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean bean1 = new ExportTargetTableBean ( ) ; bean1 . addExportFile ( importFile1 ) ; bean1 . addExportFile ( importFile2 ) ; targetTable . put ( "" , bean1 ) ; ExportTargetTableBean bean2 = new ExportTargetTableBean ( ) ; bean2 . addExportFile ( importFile3 ) ; targetTable . put ( "" , bean2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; ExportFileDelete delete = new ExportFileDelete ( ) ; delete . deleteFile ( bean ) ; assertFalse ( importFile1 . exists ( ) ) ; assertFalse ( importFile2 . exists ( ) ) ; assertFalse ( importFile3 . exists ( ) ) ; assertTrue ( dumpDir . exists ( ) ) ; } @ Test public void deleteFileTest02 ( ) throws Exception { File dumpDir = new File ( "" ) ; File importFile1 = new File ( dumpDir , "" ) ; File importFile2 = new File ( dumpDir , "" ) ; File importFile3 = new File ( dumpDir , "" ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean bean1 = new ExportTargetTableBean ( ) ; bean1 . addExportFile ( importFile1 ) ; bean1 . addExportFile ( importFile2 ) ; targetTable . put ( "" , bean1 ) ; ExportTargetTableBean bean2 = new ExportTargetTableBean ( ) ; bean2 . addExportFile ( importFile3 ) ; targetTable . put ( "" , bean2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; ExportFileDelete delete = new ExportFileDelete ( ) ; delete . deleteFile ( bean ) ; assertFalse ( importFile1 . exists ( ) ) ; assertFalse ( importFile2 . exists ( ) ) ; assertFalse ( importFile3 . exists ( ) ) ; assertTrue ( dumpDir . exists ( ) ) ; } @ Test public void deleteFileTest03 ( ) throws Exception { File importFile1 = null ; File importFile2 = null ; File importFile3 = null ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean bean1 = new ExportTargetTableBean ( ) ; bean1 . addExportFile ( importFile1 ) ; bean1 . addExportFile ( importFile2 ) ; targetTable . put ( "" , bean1 ) ; ExportTargetTableBean bean2 = new ExportTargetTableBean ( ) ; bean2 . addExportFile ( importFile3 ) ; targetTable . put ( "" , bean2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; ExportFileDelete delete = new ExportFileDelete ( ) ; delete . deleteFile ( bean ) ; } } package com . asakusafw . bulkloader . exporter ; import static org . junit . Assert . * ; import java . io . File ; import java . sql . Connection ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Ignore ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . testtools . inspect . Cause ; public class ExportFileLoadTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void loadFileTest01 ( ) throws Exception { Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( true ) ; table2 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table2 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table2 . setErrorTableName ( "" ) ; table2 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportFileLoad load = new ExportFileLoad ( ) { @ Override protected long getTempSeq ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { return ; } } ; try { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; TestUtils util1 = new TestUtils ( new File ( "" ) ) ; util1 . storeToDatabase ( false ) ; boolean result = load . loadFile ( bean ) ; assertTrue ( result ) ; TestUtils util2 = new TestUtils ( new File ( "" ) ) ; util2 . loadFromDatabase ( ) ; if ( ! util2 . inspect ( ) ) { for ( Cause cause : util2 . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util2 . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } finally { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; } } @ Test public void loadFileTest02 ( ) throws Exception { TestUtils util1 = new TestUtils ( new File ( "" ) ) ; util1 . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( false ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( false ) ; table2 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table2 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportFileLoad load = new ExportFileLoad ( ) { @ Override protected long getTempSeq ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { return ; } } ; try { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; boolean result = load . loadFile ( bean ) ; assertTrue ( result ) ; TestUtils util2 = new TestUtils ( new File ( "" ) ) ; util2 . loadFromDatabase ( ) ; if ( ! util2 . inspect ( ) ) { for ( Cause cause : util2 . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util2 . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } finally { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; } } @ Test public void loadFileTest03 ( ) throws Exception { TestUtils util1 = new TestUtils ( new File ( "" ) ) ; util1 . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( false ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( false ) ; table2 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table2 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportFileLoad load = new ExportFileLoad ( ) { @ Override protected long getTempSeq ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { throw new BulkLoaderSystemException ( this . getClass ( ) , "" ) ; } } ; boolean result = load . loadFile ( bean ) ; assertFalse ( result ) ; } @ Test public void loadFileTest04 ( ) throws Exception { TestUtils util1 = new TestUtils ( new File ( "" ) ) ; util1 . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; targetTable . put ( "" , table1 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportFileLoad load = new ExportFileLoad ( ) { @ Override protected long getTempSeq ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { return ; } } ; try { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; boolean result = load . loadFile ( bean ) ; assertTrue ( result ) ; TestUtils util2 = new TestUtils ( new File ( "" ) ) ; util2 . loadFromDatabase ( ) ; if ( ! util2 . inspect ( ) ) { for ( Cause cause : util2 . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util2 . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } finally { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; } } @ Test public void loadFileTest05 ( ) throws Exception { TestUtils util1 = new TestUtils ( new File ( "" ) ) ; util1 . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; targetTable . put ( "" , table1 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportFileLoad load = new ExportFileLoad ( ) { @ Override protected long getTempSeq ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { return ; } } ; try { boolean result = load . loadFile ( bean ) ; assertFalse ( result ) ; } finally { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; } } @ Test public void loadFileTest_DupCheckTableUnion ( ) throws Exception { TestUtils util1 = new TestUtils ( new File ( "" ) ) ; util1 . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . addExportFile ( new File ( new File ( "" ) . getAbsolutePath ( ) ) ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" } ) ) ; targetTable . put ( "" , table1 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportFileLoad load = new ExportFileLoad ( ) { @ Override protected long getTempSeq ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { return ; } } ; try { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; boolean result = load . loadFile ( bean ) ; assertTrue ( result ) ; TestUtils util2 = new TestUtils ( new File ( "" ) ) ; util2 . loadFromDatabase ( ) ; if ( ! util2 . inspect ( ) ) { for ( Cause cause : util2 . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util2 . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } finally { UnitTestUtil . executeUpdate ( "" ) ; UnitTestUtil . executeUpdate ( "" ) ; } } @ Test public void createTempTableName01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Connection conn = null ; String result = null ; try { conn = DBConnection . getConnection ( ) ; ExportFileLoad load = new ExportFileLoad ( ) ; result = load . createTempTableName ( "" , "" , conn ) ; } finally { DBConnection . closeConn ( conn ) ; } assertEquals ( "" , result ) ; } @ Test public void createTempTableName02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Connection conn = null ; String result = null ; try { conn = DBConnection . getConnection ( ) ; ExportFileLoad load = new ExportFileLoad ( ) ; result = load . createTempTableName ( "" , "" , conn ) ; } finally { DBConnection . closeConn ( conn ) ; } assertEquals ( "" , result ) ; } @ Test public void createTempTableName03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Connection conn = null ; try { conn = DBConnection . getConnection ( ) ; ExportFileLoad load = new ExportFileLoad ( ) ; load . createTempTableName ( "" , "" , conn ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } finally { DBConnection . closeConn ( conn ) ; } } @ Ignore @ Test public void createTableSql01 ( ) throws Exception { ExportTargetTableBean tableBean = new ExportTargetTableBean ( ) ; tableBean . setDuplicateCheck ( true ) ; tableBean . setErrorTableName ( "" ) ; tableBean . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ) ; ExportFileLoad load = new ExportFileLoad ( ) ; String result = load . createTableSql ( "" , "" , tableBean ) ; assertEquals ( "" , result ) ; } @ Ignore @ Test public void createTableSql02 ( ) throws Exception { ExportTargetTableBean tableBean = new ExportTargetTableBean ( ) ; tableBean . setDuplicateCheck ( false ) ; tableBean . setErrorTableName ( "" ) ; tableBean . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; ExportFileLoad load = new ExportFileLoad ( ) ; String result = load . createTableSql ( "" , "" , tableBean ) ; assertEquals ( "" , result ) ; } } package com . asakusafw . bulkloader . exporter ; import static org . junit . Assert . * ; import java . io . File ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . testtools . inspect . Cause ; public class ExportDataCopyTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void copyDataTest01 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setExportTempTableName ( "" ) ; table1 . setDuplicateFlagTableName ( "" ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( true ) ; table2 . setExportTempTableName ( "" ) ; table2 . setDuplicateFlagTableName ( "" ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorTableName ( "" ) ; table2 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorCodeColumn ( "" ) ; table2 . setErrorCode ( "" ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertTrue ( result ) ; assertTrue ( copy . isUpdateEnd ( ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } @ Test public void copyDataTest02 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD , "" ) ; ConfigurationLoader . setProperty ( prop ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setExportTempTableName ( "" ) ; table1 . setDuplicateFlagTableName ( "" ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; targetTable . put ( "" , table1 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertTrue ( result ) ; assertTrue ( copy . isUpdateEnd ( ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } @ Test public void copyDataTest03 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD , "" ) ; ConfigurationLoader . setProperty ( prop ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setExportTempTableName ( "" ) ; table1 . setDuplicateFlagTableName ( "" ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; targetTable . put ( "" , table1 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertTrue ( result ) ; assertTrue ( copy . isUpdateEnd ( ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } @ Test public void copyDataTest04 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD , "" ) ; ConfigurationLoader . setProperty ( prop ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setExportTempTableName ( "" ) ; table1 . setDuplicateFlagTableName ( "" ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; targetTable . put ( "" , table1 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertTrue ( result ) ; assertTrue ( copy . isUpdateEnd ( ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } @ Test public void copyDataTest05 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setExportTempTableName ( "" ) ; table1 . setDuplicateFlagTableName ( "" ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( true ) ; table2 . setExportTempTableName ( "" ) ; table2 . setDuplicateFlagTableName ( "" ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorTableName ( "" ) ; table2 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorCodeColumn ( "" ) ; table2 . setErrorCode ( "" ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertFalse ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertTrue ( UnitTestUtil . countAssert ( "" , ) ) ; } @ Test public void copyDataTest06 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setExportTempTableName ( "" ) ; table1 . setDuplicateFlagTableName ( "" ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( true ) ; table2 . setExportTempTableName ( "" ) ; table2 . setDuplicateFlagTableName ( "" ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorTableName ( "" ) ; table2 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorCodeColumn ( "" ) ; table2 . setErrorCode ( "" ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertTrue ( result ) ; assertTrue ( copy . isUpdateEnd ( ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void copyDataTest07 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD , "" ) ; ConfigurationLoader . setProperty ( prop ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setExportTempTableName ( "" ) ; table1 . setDuplicateFlagTableName ( "" ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( true ) ; table2 . setExportTempTableName ( "" ) ; table2 . setDuplicateFlagTableName ( "" ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorTableName ( "" ) ; table2 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorCodeColumn ( "" ) ; table2 . setErrorCode ( "" ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertTrue ( result ) ; assertFalse ( copy . isUpdateEnd ( ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void copyDataTest08 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( false ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( false ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertTrue ( result ) ; assertTrue ( copy . isUpdateEnd ( ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void copyDataTest09 ( ) throws Exception { TestUtils util = new TestUtils ( new File ( "" ) ) ; util . storeToDatabase ( false ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD , "" ) ; ConfigurationLoader . setProperty ( prop ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setExportTempTableName ( "" ) ; table1 . setDuplicateFlagTableName ( "" ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( true ) ; table2 . setExportTempTableName ( "" ) ; table2 . setDuplicateFlagTableName ( "" ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorTableName ( "" ) ; table2 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setErrorCodeColumn ( "" ) ; table2 . setErrorCode ( "" ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowSid ( "" ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; ExportDataCopy copy = new ExportDataCopy ( ) ; boolean result = copy . copyData ( bean ) ; assertTrue ( result ) ; assertTrue ( copy . isUpdateEnd ( ) ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } } package com . asakusafw . bulkloader . exporter ; import static org . junit . Assert . * ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Assume ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . StreamFileListProvider ; import com . asakusafw . testtools . TestUtils ; public class ExportFileReceiveTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private static List < String > properties = Arrays . asList ( new String [ ] { "" } ) ; private static String testBatchId = "" ; private static String testJobflowId1 = "" ; private static String testJobflowId2 = "" ; private static String testExecutionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( testJobflowId1 , testExecutionId , properties , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( testJobflowId1 , testExecutionId , properties , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void receiveFileTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowId ( testJobflowId1 ) ; bean . setExecutionId ( testExecutionId ) ; bean . setBatchId ( testBatchId ) ; bean . setTargetName ( "" ) ; File testFile = folder . newFile ( "" ) ; ExportFileReceive receive = new Mock ( testFile , "" ) ; boolean result = receive . receiveFile ( bean ) ; assertTrue ( result ) ; List < File > target1 = bean . getExportTargetTable ( "" ) . getExportFiles ( ) ; List < File > target2 = bean . getExportTargetTable ( "" ) . getExportFiles ( ) ; UnitTestUtil . assertSameFileList ( testFile , target1 . get ( ) , target1 . get ( ) , target2 . get ( ) ) ; } @ SuppressWarnings ( "" ) @ Test public void receiveFileTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowId ( testJobflowId2 ) ; bean . setExecutionId ( testExecutionId ) ; bean . setBatchId ( testBatchId ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_EXP_FILE_DIR , "" ) ; ConfigurationLoader . setProperty ( prop ) ; File testFile = folder . newFile ( "" ) ; ExportFileReceive receive = new Mock ( testFile , "" ) ; boolean result = receive . receiveFile ( bean ) ; assertTrue ( result ) ; List < File > target1 = bean . getExportTargetTable ( "" ) . getExportFiles ( ) ; UnitTestUtil . assertSameFileList ( testFile , target1 . get ( ) ) ; } @ SuppressWarnings ( "" ) @ Test public void receiveFileTest03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowId ( testJobflowId2 ) ; bean . setExecutionId ( testExecutionId ) ; bean . setBatchId ( testBatchId ) ; File missing = folder . newFolder ( "" ) ; Assume . assumeTrue ( missing . delete ( ) ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_EXP_FILE_DIR , missing . getAbsolutePath ( ) ) ; ConfigurationLoader . setProperty ( prop ) ; File testFile = folder . newFile ( "" ) ; ExportFileReceive receive = new Mock ( testFile , "" ) ; boolean result = receive . receiveFile ( bean ) ; assertFalse ( result ) ; } @ Test public void receiveFileTest04 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowId ( testJobflowId1 ) ; bean . setExecutionId ( testExecutionId ) ; File testFile = folder . newFile ( "" ) ; ExportFileReceive receive = new Mock ( testFile , "" ) ; boolean result = receive . receiveFile ( bean ) ; assertFalse ( result ) ; } @ Test public void receiveFileTest05 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowId ( testJobflowId1 ) ; bean . setExecutionId ( testExecutionId ) ; File testFile = folder . newFile ( "" ) ; ExportFileReceive receive = new Mock ( testFile , "" ) { @ Override protected FileListProvider openFileList ( String targetName , String batchId , String jobflowId , String executionId ) throws IOException { throw new IOException ( ) ; } } ; boolean result = receive . receiveFile ( bean ) ; assertFalse ( result ) ; } @ Test public void receiveFileTest06 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; targetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( targetTable ) ; bean . setJobflowId ( testJobflowId1 ) ; bean . setExecutionId ( testExecutionId ) ; File testFile = folder . newFile ( "" ) ; ExportFileReceive receive = new Mock ( testFile , "" , false ) ; boolean result = receive . receiveFile ( bean ) ; assertFalse ( result ) ; } static class Mock extends ExportFileReceive { final File target ; final String testFile ; final boolean success ; Mock ( File target , String testFile ) { this ( target , testFile , true ) ; } Mock ( File target , String testFile , boolean success ) { this . target = target ; this . testFile = testFile ; this . success = success ; } @ Override protected FileListProvider openFileList ( String targetName , String batchId , String jobflowId , String executionId ) throws IOException { return new StreamFileListProvider ( ) { @ Override protected InputStream getInputStream ( ) throws IOException { UnitTestUtil . createFileList ( new File ( testFile ) , target ) ; return new FileInputStream ( target ) ; } @ Override protected OutputStream getOutputStream ( ) throws IOException { return new ByteArrayOutputStream ( ) ; } @ Override protected void waitForDone ( ) throws IOException , InterruptedException { if ( success == false ) { throw new IOException ( ) ; } } @ Override public void close ( ) throws IOException { return ; } } ; } } } package com . asakusafw . bulkloader . exporter ; import static org . junit . Assert . * ; import java . io . File ; import java . sql . Connection ; import java . util . Arrays ; import java . util . List ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . ExportTempTableStatus ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . testtools . inspect . Cause ; public class TempTableDeleteTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void deleteTest01 ( ) throws Exception { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; TempTableDelete delete = new TempTableDelete ( ) { @ Override public void deleteTempInfoRecord ( String jobflowSid , String tableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } @ Override public void deleteTempTable ( String exportTempName , String duplicateFlagTableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } } ; boolean resutlt = delete . delete ( Arrays . asList ( tempBean ) , true ) ; assertTrue ( resutlt ) ; } @ Test public void deleteTest02 ( ) throws Exception { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; TempTableDelete delete = new TempTableDelete ( ) { @ Override public void deleteTempInfoRecord ( String jobflowSid , String tableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } @ Override public void deleteTempTable ( String exportTempName , String duplicateFlagTableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } } ; boolean resutlt = delete . delete ( Arrays . asList ( tempBean ) , true ) ; assertTrue ( resutlt ) ; } @ Test public void deleteTest03 ( ) throws Exception { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; TempTableDelete delete = new TempTableDelete ( ) { @ Override public void deleteTempInfoRecord ( String jobflowSid , String tableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } @ Override public void deleteTempTable ( String exportTempName , String duplicateFlagTableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { throw new BulkLoaderSystemException ( this . getClass ( ) , "" ) ; } } ; boolean resutlt = delete . delete ( Arrays . asList ( tempBean ) , true ) ; assertFalse ( resutlt ) ; } @ Test public void deleteTest04 ( ) throws Exception { ExportTempTableBean [ ] tempBean = new ExportTempTableBean [ ] ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; tempBean [ ] = new ExportTempTableBean ( ) ; tempBean [ ] . setJobflowSid ( "" ) ; tempBean [ ] . setExportTableName ( "" ) ; tempBean [ ] . setTemporaryTableName ( "" ) ; tempBean [ ] . setTempTableStatus ( ExportTempTableStatus . find ( "" ) ) ; TempTableDelete delete = new TempTableDelete ( ) { @ Override public void deleteTempInfoRecord ( String jobflowSid , String tableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { throw new BulkLoaderSystemException ( this . getClass ( ) , "" ) ; } @ Override public void deleteTempTable ( String exportTempName , String duplicateFlagTableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } } ; boolean resutlt = delete . delete ( Arrays . asList ( tempBean ) , true ) ; assertFalse ( resutlt ) ; } @ Test public void deleteTempInfoRecordTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; TempTableDelete delete = new TempTableDelete ( ) ; Connection conn = DBConnection . getConnection ( ) ; try { delete . deleteTempInfoRecord ( "" , "" , true , conn ) ; DBConnection . commit ( conn ) ; } catch ( Exception e ) { DBConnection . rollback ( conn ) ; e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void deleteTempInfoRecordTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; TempTableDelete delete = new TempTableDelete ( ) ; Connection conn = DBConnection . getConnection ( ) ; try { delete . deleteTempInfoRecord ( "" , "" , true , conn ) ; DBConnection . commit ( conn ) ; } catch ( Exception e ) { DBConnection . rollback ( conn ) ; e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void deleteTempInfoRecordTest03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; TempTableDelete delete = new TempTableDelete ( ) ; Connection conn = DBConnection . getConnection ( ) ; try { delete . deleteTempInfoRecord ( "" , "" , false , conn ) ; DBConnection . commit ( conn ) ; } catch ( Exception e ) { DBConnection . rollback ( conn ) ; e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void deleteTempTableTest01 ( ) throws Exception { String tempTable = "" ; String dropSql = "" ; String createSql = "" ; UnitTestUtil . executeUpdate ( dropSql ) ; UnitTestUtil . executeUpdate ( createSql ) ; String dropDup1Sql = "" ; StringBuilder dup1Sql = new StringBuilder ( ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; UnitTestUtil . executeUpdate ( dropDup1Sql ) ; UnitTestUtil . executeUpdate ( dup1Sql . toString ( ) ) ; TempTableDelete delete = new TempTableDelete ( ) ; Connection conn = DBConnection . getConnection ( ) ; try { delete . deleteTempTable ( tempTable , "" , true , conn ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; UnitTestUtil . executeUpdate ( dropSql ) ; UnitTestUtil . executeUpdate ( dropDup1Sql ) ; } @ Test public void deleteTempTableTest02 ( ) throws Exception { String tempTable = "" ; String dropSql = "" ; String dropDup1Sql = "" ; UnitTestUtil . executeUpdate ( dropSql ) ; TempTableDelete delete = new TempTableDelete ( ) ; Connection conn = DBConnection . getConnection ( ) ; try { delete . deleteTempTable ( tempTable , "" , true , conn ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; UnitTestUtil . executeUpdate ( dropSql ) ; UnitTestUtil . executeUpdate ( dropDup1Sql ) ; } @ Test public void deleteTempTableTest03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String tempTable = "" ; String dropSql = "" ; String createSql = "" ; UnitTestUtil . executeUpdate ( dropSql ) ; UnitTestUtil . executeUpdate ( createSql ) ; TempTableDelete delete = new TempTableDelete ( ) ; Connection conn = DBConnection . getConnection ( ) ; try { delete . deleteTempTable ( tempTable , "" , false , conn ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } assertTrue ( UnitTestUtil . isExistTable ( tempTable ) ) ; UnitTestUtil . executeUpdate ( dropSql ) ; } } package com . asakusafw . bulkloader . exporter ; import static org . junit . Assert . * ; import java . io . File ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Ignore ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . testtools . inspect . Cause ; public class LockReleaseTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void releaseLockTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; String dropDup1Sql = "" ; String dropDup2Sql = "" ; StringBuilder dup1Sql = new StringBuilder ( ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; StringBuilder dup2Sql = new StringBuilder ( ) ; dup2Sql . append ( "" ) ; dup2Sql . append ( "" ) ; dup2Sql . append ( "" ) ; UnitTestUtil . executeUpdate ( dropDup1Sql ) ; UnitTestUtil . executeUpdate ( dropDup2Sql ) ; UnitTestUtil . executeUpdate ( dup1Sql . toString ( ) ) ; UnitTestUtil . executeUpdate ( dup2Sql . toString ( ) ) ; Map < String , ExportTargetTableBean > exportTargetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setExportTempTableName ( tempTable1 ) ; table1 . setDuplicateFlagTableName ( "" ) ; exportTargetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setExportTempTableName ( tempTable2 ) ; table2 . setDuplicateFlagTableName ( "" ) ; exportTargetTable . put ( "" , table2 ) ; Map < String , ImportTargetTableBean > importTargetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table3 = new ImportTargetTableBean ( ) ; importTargetTable . put ( "" , table3 ) ; ImportTargetTableBean table4 = new ImportTargetTableBean ( ) ; importTargetTable . put ( "" , table4 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( exportTargetTable ) ; bean . setImportTargetTable ( importTargetTable ) ; bean . setRetryCount ( ) ; bean . setRetryInterval ( ) ; LockRelease lock = new LockRelease ( ) ; boolean result = lock . releaseLock ( bean , true ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; } @ Ignore @ Test public void releaseLockTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > exportTargetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; Map < String , ImportTargetTableBean > importTargetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table1 = new ImportTargetTableBean ( ) ; importTargetTable . put ( "" , table1 ) ; ImportTargetTableBean table2 = new ImportTargetTableBean ( ) ; importTargetTable . put ( "" , table2 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( exportTargetTable ) ; bean . setImportTargetTable ( importTargetTable ) ; bean . setRetryCount ( ) ; bean . setRetryInterval ( ) ; Connection conn = null ; PreparedStatement stmt = null ; try { conn = DBConnection . getConnection ( ) ; stmt = conn . prepareStatement ( "" ) ; stmt . executeUpdate ( ) ; LockRelease lock = new LockRelease ( ) { @ Override protected TempTableDelete createTempTableDelete ( ) { return new TempTableDelete ( ) { @ Override public boolean delete ( List < ExportTempTableBean > exportTempTableBean , boolean copyNotEnd ) { return true ; } @ Override public void deleteTempInfoRecord ( String jobflowSid , String tableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } @ Override public void deleteTempTable ( String exportTempName , String duplicateFlagTableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } } ; } } ; boolean result = lock . releaseLock ( bean , true ) ; assertFalse ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } finally { DBConnection . rollback ( conn ) ; DBConnection . closePs ( stmt ) ; DBConnection . closeConn ( conn ) ; } } @ Test public void releaseLockTest04 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ExportTargetTableBean > exportTargetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; exportTargetTable . put ( "" , table1 ) ; Map < String , ImportTargetTableBean > importTargetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table4 = new ImportTargetTableBean ( ) ; importTargetTable . put ( "" , table4 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( exportTargetTable ) ; bean . setImportTargetTable ( importTargetTable ) ; bean . setRetryCount ( ) ; bean . setRetryInterval ( ) ; LockRelease lock = new LockRelease ( ) { @ Override protected TempTableDelete createTempTableDelete ( ) { return new TempTableDelete ( ) { @ Override public boolean delete ( List < ExportTempTableBean > exportTempTableBean , boolean copyNotEnd ) { return true ; } @ Override public void deleteTempInfoRecord ( String jobflowSid , String tableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } @ Override public void deleteTempTable ( String exportTempName , String duplicateFlagTableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } } ; } } ; boolean result = lock . releaseLock ( bean , true ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void releaseLockTest05 ( ) throws Exception { Map < String , ExportTargetTableBean > exportTargetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; Map < String , ImportTargetTableBean > importTargetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setExportTargetTable ( exportTargetTable ) ; bean . setImportTargetTable ( importTargetTable ) ; bean . setRetryCount ( ) ; bean . setRetryInterval ( ) ; LockRelease lock = new LockRelease ( ) ; boolean result = lock . releaseLock ( bean , true ) ; assertTrue ( result ) ; } @ Test public void releaseLockTest06 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String tempTable1 = "" ; String dropSql1 = "" ; String createSql1 = "" ; String tempTable2 = "" ; String dropSql2 = "" ; String createSql2 = "" ; UnitTestUtil . executeUpdate ( dropSql1 ) ; UnitTestUtil . executeUpdate ( createSql1 ) ; UnitTestUtil . executeUpdate ( dropSql2 ) ; UnitTestUtil . executeUpdate ( createSql2 ) ; String dropDup1Sql = "" ; String dropDup2Sql = "" ; StringBuilder dup1Sql = new StringBuilder ( ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; dup1Sql . append ( "" ) ; StringBuilder dup2Sql = new StringBuilder ( ) ; dup2Sql . append ( "" ) ; dup2Sql . append ( "" ) ; dup2Sql . append ( "" ) ; UnitTestUtil . executeUpdate ( dropDup1Sql ) ; UnitTestUtil . executeUpdate ( dropDup2Sql ) ; UnitTestUtil . executeUpdate ( dup1Sql . toString ( ) ) ; UnitTestUtil . executeUpdate ( dup2Sql . toString ( ) ) ; Map < String , ExportTargetTableBean > exportTargetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setExportTempTableName ( tempTable1 ) ; table1 . setDuplicateFlagTableName ( "" ) ; exportTargetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setExportTempTableName ( tempTable2 ) ; table2 . setDuplicateFlagTableName ( "" ) ; exportTargetTable . put ( "" , table2 ) ; Map < String , ImportTargetTableBean > importTargetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table3 = new ImportTargetTableBean ( ) ; importTargetTable . put ( "" , table3 ) ; ImportTargetTableBean table4 = new ImportTargetTableBean ( ) ; importTargetTable . put ( "" , table4 ) ; ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( "" ) ; bean . setExportTargetTable ( exportTargetTable ) ; bean . setImportTargetTable ( importTargetTable ) ; bean . setRetryCount ( ) ; bean . setRetryInterval ( ) ; LockRelease lock = new LockRelease ( ) ; boolean result = lock . releaseLock ( bean , false ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } assertFalse ( UnitTestUtil . isExistTable ( tempTable1 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( tempTable2 ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; assertFalse ( UnitTestUtil . isExistTable ( "" ) ) ; } } package com . asakusafw . bulkloader . exporter ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . sql . Connection ; import java . util . Arrays ; import java . util . List ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; public class ExporterTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { } @ After public void tearDown ( ) throws Exception { } @ Test public void executeTest01 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JudgeExecProcess createJudgeExecProcess ( ) { StubJudgeExecProcess stub = new StubJudgeExecProcess ( ) ; stub . setExecTempTableDelete ( false ) ; return stub ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest02 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JudgeExecProcess createJudgeExecProcess ( ) { StubJudgeExecProcess stub = new StubJudgeExecProcess ( ) ; stub . setExecTempTableDelete ( false ) ; stub . setExecReceive ( false ) ; stub . setExecLoad ( false ) ; stub . setExecFileDelete ( false ) ; return stub ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest03 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest04 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JudgeExecProcess createJudgeExecProcess ( ) { StubJudgeExecProcess stub = new StubJudgeExecProcess ( ) ; stub . setExecTempTableDelete ( false ) ; stub . setExecReceive ( false ) ; stub . setExecLoad ( false ) ; stub . setExecCopy ( false ) ; stub . setExecFileDelete ( false ) ; return stub ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest05 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JudgeExecProcess createJudgeExecProcess ( ) { return new StubJudgeExecProcess ( false ) ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest06 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected TempTableDelete createTempTableDelete ( ) { return new StubTempTableDelete ( false ) ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest07 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected ExportFileReceive createExportFileReceive ( ) { return new StubExportFileReceive ( false ) ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest08 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected ExportFileLoad createExportFileLoad ( ) { return new StubExportFileLoad ( false ) ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest09 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected ExportDataCopy createExportDataCopy ( ) { return new StubExportDataCopy ( false , true ) ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest10 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected LockRelease createLockRelease ( ) { return new StubLockRelease ( false ) ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest11 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected ExportFileReceive createExportFileReceive ( ) { throw new NullPointerException ( ) ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest12 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest13 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override public boolean loadExportParam ( String targetName , String batchId , String jobflowId ) { return false ; } } ; return loder ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest14 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override public boolean loadImportParam ( String targetName , String batchId , String jobflowId , boolean isPrimary ) { return false ; } @ Override public boolean loadExportParam ( String targetName , String batchId , String jobflowId ) { return true ; } } ; return loder ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest15 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File file , String targetName ) throws IOException { File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } @ Override protected Properties getImportProp ( File file , String targetName ) throws IOException { System . out . println ( file ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest16 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override public boolean loadImportParam ( String targetName , String batchId , String jobflowId , boolean isPrimary ) { return true ; } @ Override public boolean loadExportParam ( String targetName , String batchId , String jobflowId ) { return false ; } } ; return loder ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest17 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected ExportDataCopy createExportDataCopy ( ) { return new StubExportDataCopy ( true , false ) ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest18 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Exporter exporter = new StubExporter ( ) { @ Override protected JudgeExecProcess createJudgeExecProcess ( ) { StubJudgeExecProcess stub = new StubJudgeExecProcess ( ) ; stub . setExecTempTableDelete ( false ) ; return stub ; } } ; int result = exporter . execute ( args ) ; assertEquals ( , result ) ; } } class StubExporter extends Exporter { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File file , String targetNam ) throws IOException { File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } @ Override protected Properties getImportProp ( File file , String targetName ) throws IOException { System . out . println ( file ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } @ Override protected ExportFileDelete createExportFileDelete ( ) { return new StubExportFileDelete ( ) ; } @ Override protected LockRelease createLockRelease ( ) { return new StubLockRelease ( ) ; } @ Override protected ExportFileLoad createExportFileLoad ( ) { return new StubExportFileLoad ( ) ; } @ Override protected ExportFileReceive createExportFileReceive ( ) { return new StubExportFileReceive ( ) ; } @ Override protected JudgeExecProcess createJudgeExecProcess ( ) { return new StubJudgeExecProcess ( ) ; } @ Override protected TempTableDelete createTempTableDelete ( ) { return new StubTempTableDelete ( ) ; } @ Override protected ExportDataCopy createExportDataCopy ( ) { return new StubExportDataCopy ( ) ; } } class StubExportFileDelete extends ExportFileDelete { } class StubLockRelease extends LockRelease { boolean result = true ; public StubLockRelease ( ) { } public StubLockRelease ( boolean b ) { this . result = b ; } @ Override public boolean releaseLock ( ExporterBean bean , boolean isEndJobFlow ) { return result ; } } class StubExportFileLoad extends ExportFileLoad { boolean result = true ; public StubExportFileLoad ( ) { } public StubExportFileLoad ( boolean b ) { this . result = b ; } @ Override public boolean loadFile ( ExporterBean bean ) { return result ; } } class StubExportFileReceive extends ExportFileReceive { boolean result = true ; String sid = "" ; public StubExportFileReceive ( ) { } public StubExportFileReceive ( boolean b ) { this . result = b ; } public StubExportFileReceive ( boolean b , String sid ) { this . result = b ; this . sid = sid ; } @ Override public boolean receiveFile ( ExporterBean bean ) { return result ; } } class StubTempTableDelete extends TempTableDelete { boolean result = true ; public StubTempTableDelete ( ) { } public StubTempTableDelete ( boolean b ) { this . result = b ; } @ Override public boolean delete ( List < ExportTempTableBean > exportTempTableBean , boolean copyNotEnd ) { return result ; } @ Override public void deleteTempInfoRecord ( String jobflowSid , String tableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } @ Override public void deleteTempTable ( String exportTempName , String duplicateFlagTableName , boolean copyNotEnd , Connection conn ) throws BulkLoaderSystemException { } } class StubExportDataCopy extends ExportDataCopy { boolean result = true ; private boolean updateEnd = true ; public StubExportDataCopy ( ) { } public StubExportDataCopy ( boolean result , boolean updateEnd ) { this . result = result ; this . updateEnd = updateEnd ; } @ Override public boolean copyData ( ExporterBean bean ) { return result ; } @ Override public boolean isUpdateEnd ( ) { return updateEnd ; } } class StubJudgeExecProcess extends JudgeExecProcess { boolean result = true ; private boolean execTempTableDelete = true ; private boolean execReceive = true ; private boolean execLoad = true ; private boolean execCopy = true ; private boolean execLockRelease = true ; private boolean execFileDelete = true ; List < ExportTempTableBean > exportTempTableBean = null ; public StubJudgeExecProcess ( ) { } public StubJudgeExecProcess ( boolean b ) { this . result = b ; } @ Override public boolean judge ( ExporterBean bean ) { return result ; } @ Override public boolean isExecReceive ( ) { return execReceive ; } @ Override public boolean isExecLoad ( ) { return execLoad ; } @ Override public boolean isExecCopy ( ) { return execCopy ; } @ Override public boolean isExecLockRelease ( ) { return execLockRelease ; } @ Override public boolean isExecFileDelete ( ) { return execFileDelete ; } @ Override public boolean isExecTempTableDelete ( ) { return execTempTableDelete ; } @ Override public List < ExportTempTableBean > getExportTempTableBean ( ) { return exportTempTableBean ; } public void setResult ( boolean result ) { this . result = result ; } public void setExecTempTableDelete ( boolean execTempTableDelete ) { this . execTempTableDelete = execTempTableDelete ; } public void setExecReceive ( boolean execReceive ) { this . execReceive = execReceive ; } public void setExecLoad ( boolean execLoad ) { this . execLoad = execLoad ; } public void setExecCopy ( boolean execCopy ) { this . execCopy = execCopy ; } public void setExecLockRelease ( boolean execLockRelease ) { this . execLockRelease = execLockRelease ; } public void setExecFileDelete ( boolean execFileDelete ) { this . execFileDelete = execFileDelete ; } public void setExportTempTableBean ( List < ExportTempTableBean > exportTempTableBean ) { this . exportTempTableBean = exportTempTableBean ; } } package com . asakusafw . bulkloader . importer ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . sql . Connection ; import java . sql . Statement ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Arrays ; import java . util . Calendar ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import test . modelgen . table . model . ImportTarget1 ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . cache . LocalCacheInfo ; import com . asakusafw . bulkloader . cache . LocalCacheInfoRepository ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderReRunnableException ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; public class ImportProtocolDecideTest { private static List < String > properties = Arrays . asList ( new String [ ] { "" } ) ; private static String testJobflowId = "" ; private static String testExecutionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownEnv ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( testJobflowId , testExecutionId , properties , "" ) ; UnitTestUtil . setUpDB ( ) ; UnitTestUtil . startUp ( ) ; Connection connection = DBConnection . getConnection ( ) ; Statement statement = null ; try { statement = connection . createStatement ( ) ; statement . execute ( "" ) ; statement . execute ( "" ) ; statement . execute ( "" ) ; statement . execute ( "" ) ; } finally { DBConnection . closeStmt ( statement ) ; DBConnection . closeConn ( connection ) ; } } @ Test public void contents ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( null ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . CONTENT ) ) ; assertThat ( tb1 . getStartTimestamp ( ) , is ( nullValue ( ) ) ) ; } @ Test public void create_cache ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . emptyMap ( ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . CREATE_CACHE ) ) ; assertThat ( tb1 . getImportProtocol ( ) . getLocation ( ) , is ( tb1 . getDfsFilePath ( ) ) ) ; assertThat ( tb1 . getStartTimestamp ( ) , is ( nullValue ( ) ) ) ; CacheInfo info = tb1 . getImportProtocol ( ) . getInfo ( ) ; assertThat ( info , is ( notNullValue ( ) ) ) ; assertThat ( info . getId ( ) , is ( "" ) ) ; assertThat ( info . getFeatureVersion ( ) , is ( CacheInfo . FEATURE_VERSION ) ) ; assertThat ( info . getTimestamp ( ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( info . getTableName ( ) , is ( "" ) ) ; assertThat ( info . getColumnNames ( ) , is ( ( Object ) new HashSet < String > ( tb1 . getImportTargetColumns ( ) ) ) ) ; assertThat ( info . getModelClassName ( ) , is ( ImportTarget1 . class . getName ( ) ) ) ; assertThat ( info . getModelClassVersion ( ) , is ( new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } @ Test public void update_cache ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; final ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; Connection conn = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( conn ) ; repo . putCacheInfo ( new LocalCacheInfo ( tb1 . getCacheId ( ) , null , null , "" , tb1 . getDfsFilePath ( ) ) ) ; } finally { DBConnection . closeConn ( conn ) ; } bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . singletonMap ( "" , new CacheInfo ( CacheInfo . FEATURE_VERSION , tb1 . getCacheId ( ) , offset ( - ) , "" , tb1 . getImportTargetColumns ( ) , tb1 . getImportTargetType ( ) . getName ( ) , new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . UPDATE_CACHE ) ) ; assertThat ( tb1 . getImportProtocol ( ) . getLocation ( ) , is ( tb1 . getDfsFilePath ( ) ) ) ; assertThat ( tb1 . getStartTimestamp ( ) , is ( notNullValue ( ) ) ) ; CacheInfo info = tb1 . getImportProtocol ( ) . getInfo ( ) ; assertThat ( info , is ( notNullValue ( ) ) ) ; assertThat ( info . getId ( ) , is ( "" ) ) ; assertThat ( info . getFeatureVersion ( ) , is ( CacheInfo . FEATURE_VERSION ) ) ; assertThat ( info . getTimestamp ( ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( info . getTableName ( ) , is ( "" ) ) ; assertThat ( info . getColumnNames ( ) , is ( ( Object ) new HashSet < String > ( tb1 . getImportTargetColumns ( ) ) ) ) ; assertThat ( info . getModelClassName ( ) , is ( ImportTarget1 . class . getName ( ) ) ) ; assertThat ( info . getModelClassVersion ( ) , is ( new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } @ Test public void update_cache_rebuild ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; final ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; Connection conn = DBConnection . getConnection ( ) ; final Calendar last = offset ( - ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( conn ) ; repo . putCacheInfo ( new LocalCacheInfo ( tb1 . getCacheId ( ) , null , last , "" , tb1 . getDfsFilePath ( ) ) ) ; } finally { DBConnection . closeConn ( conn ) ; } bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . singletonMap ( "" , new CacheInfo ( CacheInfo . FEATURE_VERSION , tb1 . getCacheId ( ) , last , "" , tb1 . getImportTargetColumns ( ) , tb1 . getImportTargetType ( ) . getName ( ) , new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . UPDATE_CACHE ) ) ; assertThat ( tb1 . getImportProtocol ( ) . getLocation ( ) , is ( tb1 . getDfsFilePath ( ) ) ) ; assertThat ( tb1 . getStartTimestamp ( ) , is ( notNullValue ( ) ) ) ; CacheInfo info = tb1 . getImportProtocol ( ) . getInfo ( ) ; assertThat ( info , is ( notNullValue ( ) ) ) ; assertThat ( info . getId ( ) , is ( "" ) ) ; assertThat ( info . getFeatureVersion ( ) , is ( CacheInfo . FEATURE_VERSION ) ) ; assertThat ( info . getTimestamp ( ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( info . getTableName ( ) , is ( "" ) ) ; assertThat ( info . getColumnNames ( ) , is ( ( Object ) new HashSet < String > ( tb1 . getImportTargetColumns ( ) ) ) ) ; assertThat ( info . getModelClassName ( ) , is ( ImportTarget1 . class . getName ( ) ) ) ; assertThat ( info . getModelClassVersion ( ) , is ( new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } @ Test public void update_cache_db_rollback ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; final ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; Connection conn = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( conn ) ; repo . putCacheInfo ( new LocalCacheInfo ( tb1 . getCacheId ( ) , null , null , "" , tb1 . getDfsFilePath ( ) ) ) ; } finally { DBConnection . closeConn ( conn ) ; } bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . singletonMap ( "" , new CacheInfo ( CacheInfo . FEATURE_VERSION , tb1 . getCacheId ( ) , offset ( + ) , "" , tb1 . getImportTargetColumns ( ) , tb1 . getImportTargetType ( ) . getName ( ) , new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . CREATE_CACHE ) ) ; } @ Test public void update_cache_dfs_rollback ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; final ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; Connection conn = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( conn ) ; repo . putCacheInfo ( new LocalCacheInfo ( tb1 . getCacheId ( ) , null , offset ( - ) , "" , tb1 . getDfsFilePath ( ) ) ) ; } finally { DBConnection . closeConn ( conn ) ; } bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . singletonMap ( "" , new CacheInfo ( CacheInfo . FEATURE_VERSION , tb1 . getCacheId ( ) , offset ( - ) , "" , tb1 . getImportTargetColumns ( ) , tb1 . getImportTargetType ( ) . getName ( ) , new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . CREATE_CACHE ) ) ; } @ Test public void update_cache_broken_local ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; final ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . singletonMap ( "" , new CacheInfo ( CacheInfo . FEATURE_VERSION , tb1 . getCacheId ( ) , offset ( - ) , "" , tb1 . getImportTargetColumns ( ) , tb1 . getImportTargetType ( ) . getName ( ) , new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . CREATE_CACHE ) ) ; } @ Test public void update_cache_broken_remote ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; final ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; Connection conn = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( conn ) ; repo . putCacheInfo ( new LocalCacheInfo ( tb1 . getCacheId ( ) , null , null , "" , tb1 . getDfsFilePath ( ) ) ) ; } finally { DBConnection . closeConn ( conn ) ; } bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . emptyMap ( ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . CREATE_CACHE ) ) ; } @ Test public void update_cache_feature_changed ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; final ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; Connection conn = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( conn ) ; repo . putCacheInfo ( new LocalCacheInfo ( tb1 . getCacheId ( ) , null , null , "" , tb1 . getDfsFilePath ( ) ) ) ; } finally { DBConnection . closeConn ( conn ) ; } bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . singletonMap ( "" , new CacheInfo ( CacheInfo . FEATURE_VERSION + "" , tb1 . getCacheId ( ) , offset ( - ) , "" , tb1 . getImportTargetColumns ( ) , tb1 . getImportTargetType ( ) . getName ( ) , new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) ) ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . CREATE_CACHE ) ) ; } @ Test public void update_cache_inconsistent_model ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable = new HashMap < String , ImportTargetTableBean > ( ) ; final ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable . put ( "" , tb1 ) ; Connection conn = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( conn ) ; repo . putCacheInfo ( new LocalCacheInfo ( tb1 . getCacheId ( ) , null , null , "" , tb1 . getDfsFilePath ( ) ) ) ; } finally { DBConnection . closeConn ( conn ) ; } bean . setTargetTable ( targetTable ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . singletonMap ( "" , new CacheInfo ( CacheInfo . FEATURE_VERSION , tb1 . getCacheId ( ) , offset ( - ) , "" , tb1 . getImportTargetColumns ( ) , tb1 . getImportTargetType ( ) . getName ( ) , new ImportTarget1 ( ) . __tgc__DataModelVersion ( ) + ) ) ; } } ; service . execute ( bean ) ; assertThat ( tb1 . getImportProtocol ( ) . getKind ( ) , is ( FileProtocol . Kind . CREATE_CACHE ) ) ; } @ Test public void conflict_lock ( ) throws Exception { ImportBean bean1 = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable1 = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable1 . put ( "" , tb1 ) ; bean1 . setTargetTable ( targetTable1 ) ; ImportBean bean2 = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable2 = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tb2 = new ImportTargetTableBean ( ) ; tb2 . setCacheId ( "" ) ; tb2 . setDfsFilePath ( "" ) ; tb2 . setImportTargetType ( ImportTarget1 . class ) ; tb2 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb2 . setSearchCondition ( "" ) ; targetTable2 . put ( "" , tb2 ) ; bean2 . setTargetTable ( targetTable2 ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . emptyMap ( ) ; } } ; service . execute ( bean1 ) ; try { service . execute ( bean2 ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } } @ Test public void release_lock ( ) throws Exception { ImportBean bean1 = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable1 = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tb1 = new ImportTargetTableBean ( ) ; tb1 . setCacheId ( "" ) ; tb1 . setDfsFilePath ( "" ) ; tb1 . setImportTargetType ( ImportTarget1 . class ) ; tb1 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb1 . setSearchCondition ( "" ) ; targetTable1 . put ( "" , tb1 ) ; bean1 . setTargetTable ( targetTable1 ) ; ImportBean bean2 = createBean ( ) ; Map < String , ImportTargetTableBean > targetTable2 = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tb2 = new ImportTargetTableBean ( ) ; tb2 . setCacheId ( "" ) ; tb2 . setDfsFilePath ( "" ) ; tb2 . setImportTargetType ( ImportTarget1 . class ) ; tb2 . setImportTargetColumns ( Arrays . asList ( "" ) ) ; tb2 . setSearchCondition ( "" ) ; targetTable2 . put ( "" , tb2 ) ; bean2 . setTargetTable ( targetTable2 ) ; ImportProtocolDecide service = new ImportProtocolDecide ( ) { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean _ ) throws BulkLoaderSystemException { return Collections . emptyMap ( ) ; } } ; service . execute ( bean1 ) ; service . cleanUpForRetry ( bean1 ) ; service . execute ( bean2 ) ; } private ImportBean createBean ( ) { ImportBean bean = new ImportBean ( ) ; bean . setTargetName ( "" ) ; bean . setBatchId ( "" ) ; bean . setJobflowId ( testJobflowId ) ; bean . setExecutionId ( testExecutionId ) ; return bean ; } static Calendar offset ( int days ) { Calendar c = Calendar . getInstance ( ) ; c . add ( Calendar . DATE , days ) ; return c ; } static Calendar calendar ( String timeString ) throws AssertionError { Calendar timestamp = Calendar . getInstance ( ) ; try { timestamp . setTime ( new SimpleDateFormat ( "" ) . parse ( timeString ) ) ; } catch ( ParseException e ) { throw new AssertionError ( e ) ; } return timestamp ; } class Mock extends ImportProtocolDecide { } } package com . asakusafw . bulkloader . importer ; import static org . junit . Assert . * ; import java . io . File ; import java . util . Arrays ; import java . util . Calendar ; import java . util . Date ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ImportTableLockType ; import com . asakusafw . bulkloader . common . ImportTableLockedOperation ; import com . asakusafw . bulkloader . exception . BulkLoaderReRunnableException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . testtools . inspect . Cause ; public class TargetDataLockTest { private static List < String > PROPERTYS = Arrays . asList ( new String [ ] { "" } ) ; private static String targetName = "" ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , PROPERTYS , targetName ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , PROPERTYS , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void lockTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; boolean result = lock . lock ( bean ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . NONE ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . FORCE ) ; tableBean1 . setImportTargetType ( null ) ; tableBean1 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean2 . setSearchCondition ( "" ) ; tableBean2 . setUseCache ( false ) ; tableBean2 . setLockType ( ImportTableLockType . RECORD ) ; tableBean2 . setLockedOperation ( ImportTableLockedOperation . OFF ) ; tableBean2 . setImportTargetType ( null ) ; tableBean2 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; boolean result = lock . lock ( bean ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( "" ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . RECORD ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; try { lock . lock ( bean ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest04 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . RECORD ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean1 . setImportTargetType ( null ) ; tableBean1 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean2 . setSearchCondition ( "" ) ; tableBean2 . setUseCache ( false ) ; tableBean2 . setLockType ( ImportTableLockType . NONE ) ; tableBean2 . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean2 . setImportTargetType ( null ) ; tableBean2 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; boolean result = lock . lock ( bean ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest05 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; boolean result = lock . lock ( bean ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest06 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . NONE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . FORCE ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; boolean result = lock . lock ( bean ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest07 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . RECORD ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . OFF ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; boolean result = lock . lock ( bean ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest08 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( "" ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . RECORD ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; try { lock . lock ( bean ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest09 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; try { lock . lock ( bean ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest10 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; try { lock . lock ( bean ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest11 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( "" ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . RECORD ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; try { lock . lock ( bean ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest12 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( "" ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . RECORD ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; try { lock . lock ( bean ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest13 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( "" ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . NONE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; try { lock . lock ( bean ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest14 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( "" ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . NONE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; try { lock . lock ( bean ) ; fail ( ) ; } catch ( BulkLoaderReRunnableException e ) { } util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest15 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; TargetDataLock lock = new TargetDataLock ( ) ; String result = lock . insertRunningJobFlow ( "" , "" , jobflowId , executionId , new Date ( ) ) ; assertNotNull ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } @ Test public void lockTest16 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . RECORD ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . OFF ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; TargetDataLock lock = new TargetDataLock ( ) ; boolean result = lock . lock ( bean ) ; assertTrue ( result ) ; util . loadFromDatabase ( ) ; if ( ! util . inspect ( ) ) { for ( Cause cause : util . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } fail ( util . getCauseMessage ( ) ) ; } } private static ImportBean createBean ( String [ ] args , Map < String , ImportTargetTableBean > targetTable ) { ImportBean bean = new ImportBean ( ) ; bean . setTargetName ( targetName ) ; bean . setBatchId ( "" ) ; bean . setJobflowId ( args [ ] ) ; bean . setExecutionId ( args [ ] ) ; String date = args [ ] ; Calendar cal = Calendar . getInstance ( ) ; cal . clear ( ) ; cal . set ( Calendar . YEAR , Integer . parseInt ( date . substring ( , ) ) ) ; cal . set ( Calendar . MONTH , Integer . parseInt ( date . substring ( , ) ) - ) ; cal . set ( Calendar . DATE , Integer . parseInt ( date . substring ( , ) ) ) ; cal . set ( Calendar . HOUR , Integer . parseInt ( date . substring ( , ) ) ) ; cal . set ( Calendar . MINUTE , Integer . parseInt ( date . substring ( , ) ) ) ; cal . set ( Calendar . SECOND , Integer . parseInt ( date . substring ( , ) ) ) ; bean . setJobnetEndTime ( cal . getTime ( ) ) ; bean . setRetryCount ( Integer . parseInt ( args [ ] ) ) ; bean . setRetryInterval ( Integer . parseInt ( args [ ] ) ) ; bean . setTargetTable ( targetTable ) ; return bean ; } } package com . asakusafw . bulkloader . importer ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . Date ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . concurrent . atomic . AtomicBoolean ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . common . TsvDeleteType ; import com . asakusafw . bulkloader . exception . BulkLoaderReRunnableException ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; @ SuppressWarnings ( "" ) public class ImporterTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; private static String targetName = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , targetName ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { } @ After public void tearDown ( ) throws Exception { } @ Test public void executeTest01 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest02 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest03 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected TargetDataLock createTargetDataLock ( ) { return new StubTargetDataLock ( false ) ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest04 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected ImportFileCreate createImportFileCreate ( ) { return new StubImportFileCreate ( false ) ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest05 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected ImportFileSend createImportFileSend ( ) { return new StubImportFileSend ( false ) ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest06 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected TargetDataLock createTargetDataLock ( ) { throw new NullPointerException ( ) ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest07 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest08 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest09 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest10 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override public boolean loadImportParam ( String targetName , String batchId , String jobflowId , boolean isPrimary ) { return false ; } } ; return loder ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest11 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File file , String targetName ) throws IOException { System . out . println ( file ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest12 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File file , String targetName ) throws IOException { System . out . println ( file ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } @ Override protected TargetDataLock createTargetDataLock ( ) { return new StubTargetDataLock ( true , null ) ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest13 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest14 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest15 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File file , String targetName ) throws IOException { System . out . println ( file ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest16 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected TargetDataLock createTargetDataLock ( ) { return new StubTargetDataLock ( ) { @ Override public boolean lock ( ImportBean bean ) throws BulkLoaderReRunnableException { Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_IMPORT_TSV_DELETE , TsvDeleteType . TRUE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; return super . lock ( bean ) ; } } ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest17 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected TargetDataLock createTargetDataLock ( ) { return new StubTargetDataLock ( ) { @ Override public boolean lock ( ImportBean bean ) throws BulkLoaderReRunnableException { Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_IMPORT_TSV_DELETE , TsvDeleteType . FALSE . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; return super . lock ( bean ) ; } } ; } } ; int result = importer . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void execute_cache_lock_conflict ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Importer importer = new StubImporter ( ) { @ Override protected ImportProtocolDecide createImportProtocolDecide ( ) { return new ImportProtocolDecide ( ) { @ Override public void execute ( ImportBean bean ) throws BulkLoaderReRunnableException { throw new BulkLoaderReRunnableException ( ImporterTest . class , "" , "" , "" ) ; } } ; } } ; int result = importer . execute ( args ) ; assertEquals ( Constants . EXIT_CODE_RETRYABLE , result ) ; } @ Test public void execute_data_lock_conflict ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = targetName ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; final AtomicBoolean cacheReleased = new AtomicBoolean ( false ) ; Importer importer = new StubImporter ( ) { @ Override protected ImportProtocolDecide createImportProtocolDecide ( ) { return new ImportProtocolDecide ( ) { @ Override public void execute ( ImportBean bean ) throws BulkLoaderReRunnableException { cacheReleased . set ( false ) ; } @ Override public void cleanUpForRetry ( ImportBean bean ) throws BulkLoaderSystemException { cacheReleased . set ( true ) ; } } ; } @ Override protected TargetDataLock createTargetDataLock ( ) { return new StubTargetDataLock ( ) { @ Override public boolean lock ( ImportBean bean ) throws BulkLoaderReRunnableException { throw new BulkLoaderReRunnableException ( ImporterTest . class , "" , "" , "" ) ; } } ; } } ; int result = importer . execute ( args ) ; assertEquals ( Constants . EXIT_CODE_RETRYABLE , result ) ; assertTrue ( cacheReleased . get ( ) ) ; } } class StubImporter extends Importer { @ Override protected ImportFileDelete createImportFileDelete ( ) { return new StubImportFileDelete ( ) ; } @ Override protected ImportFileSend createImportFileSend ( ) { return new StubImportFileSend ( ) ; } @ Override protected ImportFileCreate createImportFileCreate ( ) { return new StubImportFileCreate ( ) ; } @ Override protected TargetDataLock createTargetDataLock ( ) { return new StubTargetDataLock ( ) ; } @ Override protected ImportProtocolDecide createImportProtocolDecide ( ) { return new StubImportProtocolDecide ( ) ; } @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File file , String targetName ) throws IOException { System . out . println ( file ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } } class StubImportFileDelete extends ImportFileDelete { public StubImportFileDelete ( ) { return ; } @ Override public void deleteFile ( ImportBean bean ) { return ; } } class StubImportFileSend extends ImportFileSend { boolean result = true ; public StubImportFileSend ( boolean result ) { this . result = result ; } public StubImportFileSend ( ) { return ; } @ Override public boolean sendImportFile ( ImportBean bean ) { return result ; } } class StubImportFileCreate extends ImportFileCreate { boolean result = true ; public StubImportFileCreate ( boolean result ) { this . result = result ; } public StubImportFileCreate ( ) { return ; } @ Override public boolean createImportFile ( ImportBean bean , String jobFlowSid ) { return result ; } } class StubTargetDataLock extends TargetDataLock { boolean result = true ; String sid = "" ; public StubTargetDataLock ( boolean result ) { this . result = result ; } public StubTargetDataLock ( boolean result , String sid ) { this . result = result ; this . sid = sid ; } public StubTargetDataLock ( ) { return ; } @ Override public boolean lock ( ImportBean bean ) throws BulkLoaderReRunnableException { return result ; } @ Override public String insertRunningJobFlow ( String targetName , String batchId , String jobflowId , String executionId , Date jobnetEndTime ) { return sid ; } } class StubImportProtocolDecide extends ImportProtocolDecide { @ Override protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean bean ) throws BulkLoaderSystemException { return Collections . emptyMap ( ) ; } } package com . asakusafw . bulkloader . importer ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . Calendar ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . ImportTableLockType ; import com . asakusafw . bulkloader . common . ImportTableLockedOperation ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; public class ImportFileCreateTest { private static String targetName = "" ; private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void createImportFileTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; String jobflowSid = "" ; ImportFileCreate create = new ImportFileCreate ( ) ; boolean result = create . createImportFile ( bean , jobflowSid ) ; File [ ] file = createFile ( targetName , jobflowId , executionId , "" ) ; assertTrue ( result ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , file [ ] ) ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } @ Test public void createImportFileTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , "" , "" , "" , "" } , targetTable ) ; String jobflowSid = "" ; ImportFileCreate create = new ImportFileCreate ( ) ; boolean result = create . createImportFile ( bean , jobflowSid ) ; File [ ] file = createFile ( targetName , jobflowId , "" , "" ) ; assertTrue ( result ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , file [ ] ) ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } @ Test public void createImportFileTest03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . NONE ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . FORCE ) ; tableBean1 . setImportTargetType ( null ) ; tableBean1 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; tableBean2 . setSearchCondition ( "" ) ; tableBean2 . setUseCache ( false ) ; tableBean2 . setLockType ( ImportTableLockType . RECORD ) ; tableBean2 . setLockedOperation ( ImportTableLockedOperation . OFF ) ; tableBean2 . setImportTargetType ( null ) ; tableBean2 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , "" , "" , "" , "" } , targetTable ) ; String jobflowSid = "" ; ImportFileCreate create = new ImportFileCreate ( ) ; boolean result = create . createImportFile ( bean , jobflowSid ) ; File [ ] file1 = createFile ( targetName , jobflowId , "" , "" ) ; File [ ] file2 = createFile ( targetName , jobflowId , "" , "" ) ; assertTrue ( result ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , file1 [ ] ) ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , file2 [ ] ) ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } @ Test public void createImportFileTest04 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; tableBean1 . setSearchCondition ( null ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . RECORD ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean1 . setImportTargetType ( null ) ; tableBean1 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean1 ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , "" , "" , "" , "" } , targetTable ) ; String jobflowSid = "" ; ImportFileCreate create = new ImportFileCreate ( ) ; boolean result = create . createImportFile ( bean , jobflowSid ) ; File [ ] file1 = createFile ( targetName , jobflowId , "" , "" ) ; assertTrue ( result ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , file1 [ ] ) ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } public void createImportFileTest05 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; FileOutputStream fos = null ; try { String jobflowSid = "" ; File [ ] file = createFile ( targetName , jobflowId , executionId , "" ) ; file [ ] . mkdirs ( ) ; fos = new FileOutputStream ( file [ ] ) ; fos . write ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; tableBean1 . setSearchCondition ( null ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . RECORD ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean1 . setImportTargetType ( null ) ; tableBean1 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean1 ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; ImportFileCreate create = new ImportFileCreate ( ) ; boolean result = create . createImportFile ( bean , jobflowSid ) ; assertFalse ( result ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } finally { if ( fos != null ) { fos . close ( ) ; } } } @ Test public void createImportFileTest06 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; String jobflowSid = "" ; ImportFileCreate create = new ImportFileCreate ( ) ; boolean result = create . createImportFile ( bean , jobflowSid ) ; File [ ] file = createFile ( targetName , jobflowId , executionId , "" ) ; assertFalse ( result ) ; assertFalse ( file [ ] . exists ( ) ) ; assertTrue ( file [ ] . exists ( ) ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } @ Test public void createImportFileTest07 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( "" ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; String jobflowSid = "" ; ImportFileCreate create = new ImportFileCreate ( ) ; boolean result = create . createImportFile ( bean , jobflowSid ) ; File [ ] file = createFile ( targetName , jobflowId , executionId , "" ) ; assertTrue ( result ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , file [ ] ) ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } @ Test public void createImportFileTest08 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean . setSearchCondition ( null ) ; tableBean . setUseCache ( false ) ; tableBean . setLockType ( ImportTableLockType . TABLE ) ; tableBean . setLockedOperation ( ImportTableLockedOperation . ERROR ) ; tableBean . setImportTargetType ( null ) ; tableBean . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = createBean ( new String [ ] { jobflowId , executionId , "" , "" , "" } , targetTable ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_IMP_FILE_DIR , "" ) ; ConfigurationLoader . setProperty ( prop ) ; String jobflowSid = "" ; ImportFileCreate create = new ImportFileCreate ( ) ; boolean result = create . createImportFile ( bean , jobflowSid ) ; File [ ] file = createFile ( targetName , jobflowId , executionId , "" ) ; assertFalse ( result ) ; } private static ImportBean createBean ( String [ ] args , Map < String , ImportTargetTableBean > targetTable ) { ImportBean bean = new ImportBean ( ) ; bean . setTargetName ( targetName ) ; bean . setJobflowId ( args [ ] ) ; bean . setExecutionId ( args [ ] ) ; String date = args [ ] ; Calendar cal = Calendar . getInstance ( ) ; cal . clear ( ) ; cal . set ( Calendar . YEAR , Integer . parseInt ( date . substring ( , ) ) ) ; cal . set ( Calendar . MONTH , Integer . parseInt ( date . substring ( , ) ) - ) ; cal . set ( Calendar . DATE , Integer . parseInt ( date . substring ( , ) ) ) ; cal . set ( Calendar . HOUR , Integer . parseInt ( date . substring ( , ) ) ) ; cal . set ( Calendar . MINUTE , Integer . parseInt ( date . substring ( , ) ) ) ; cal . set ( Calendar . SECOND , Integer . parseInt ( date . substring ( , ) ) ) ; bean . setJobnetEndTime ( cal . getTime ( ) ) ; bean . setRetryCount ( Integer . parseInt ( args [ ] ) ) ; bean . setRetryInterval ( Integer . parseInt ( args [ ] ) ) ; bean . setTargetTable ( targetTable ) ; return bean ; } private File [ ] createFile ( String targetName , String jobflowId , String executionId , String tableName ) throws IOException { File fileDirectry = new File ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_FILE_DIR ) ) ; StringBuffer strFileNmae = new StringBuffer ( Constants . IMPORT_FILE_PREFIX ) ; strFileNmae . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileNmae . append ( targetName ) ; strFileNmae . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileNmae . append ( jobflowId ) ; strFileNmae . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileNmae . append ( executionId ) ; strFileNmae . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileNmae . append ( tableName ) ; strFileNmae . append ( Constants . IMPORT_FILE_EXTENSION ) ; File file = new File ( fileDirectry , strFileNmae . toString ( ) ) ; File [ ] dirFile = new File [ ] ; dirFile [ ] = fileDirectry ; dirFile [ ] = file ; return dirFile ; } } package com . asakusafw . bulkloader . importer ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileCompType ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . StreamFileListProvider ; @ SuppressWarnings ( "" ) public class ImportFileSendTest { private static List < String > properties = Arrays . asList ( new String [ ] { "" } ) ; private static String testTargetName = "" ; private static String testBatchId = "" ; private static String testJobflowId = "" ; private static String testExecutionId = "" ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( testJobflowId , testExecutionId , properties , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( testJobflowId , testExecutionId , properties , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void sendImportFileTtest01 ( ) throws Exception { File importFile = new File ( "" ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportProtocol ( FileList . content ( "" ) ) ; tableBean . setImportFile ( importFile ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; bean . setBatchId ( testBatchId ) ; bean . setTargetName ( testTargetName ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_IMP_FILE_COMP_TYPE , FileCompType . STORED . getSymbol ( ) ) ; ConfigurationLoader . setProperty ( p ) ; ImportFileSend send = new Mock ( "" ) ; boolean result = send . sendImportFile ( bean ) ; assertTrue ( result ) ; File resultFile = new File ( "" ) ; UnitTestUtil . assertSameFileList ( resultFile , importFile ) ; } @ Test public void sendImportFileTtest02 ( ) throws Exception { File importFile1 = new File ( "" ) ; File importFile2 = new File ( "" ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportProtocol ( FileList . content ( "" ) ) ; tableBean1 . setImportFile ( importFile1 ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportProtocol ( FileList . content ( "" ) ) ; tableBean2 . setImportFile ( importFile2 ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; bean . setTargetName ( testTargetName ) ; ImportFileSend send = new Mock ( "" ) ; boolean result = send . sendImportFile ( bean ) ; assertTrue ( result ) ; File resultFile = new File ( "" ) ; assertThat ( resultFile . length ( ) , is ( lessThan ( importFile1 . length ( ) + importFile2 . length ( ) ) ) ) ; UnitTestUtil . assertSameFileList ( resultFile , importFile1 , importFile2 ) ; } @ Test public void sendImportFileTtest03 ( ) throws Exception { File importFile = new File ( "" ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportProtocol ( FileList . content ( "" ) ) ; tableBean . setImportFile ( importFile ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; bean . setTargetName ( testTargetName ) ; ImportFileSend send = new ImportFileSend ( ) { @ Override protected FileListProvider openFileList ( String targetName , String batchId , String jobflowId , String executionId ) throws IOException { throw new IOException ( ) ; } } ; boolean result = send . sendImportFile ( bean ) ; assertFalse ( result ) ; } @ Test public void sendImportFileTtest04 ( ) throws Exception { File importFile = new File ( "" ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportProtocol ( FileList . content ( "" ) ) ; tableBean . setImportFile ( importFile ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; bean . setBatchId ( testBatchId ) ; bean . setTargetName ( testTargetName ) ; ImportFileSend send = new Mock ( "" ) ; boolean result = send . sendImportFile ( bean ) ; assertFalse ( result ) ; } @ Test public void sendImportFileTtest05 ( ) throws Exception { File importFile = new File ( "" ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean = new ImportTargetTableBean ( ) ; tableBean . setImportProtocol ( FileList . content ( "" ) ) ; tableBean . setImportFile ( importFile ) ; targetTable . put ( "" , tableBean ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; bean . setBatchId ( testBatchId ) ; bean . setTargetName ( testTargetName ) ; ImportFileSend send = new Mock ( "" , false ) ; boolean result = send . sendImportFile ( bean ) ; assertFalse ( result ) ; } class Mock extends ImportFileSend { final String testFile ; final boolean success ; Mock ( String testFile ) { this ( testFile , true ) ; } Mock ( String testFile , boolean success ) { this . testFile = testFile ; this . success = success ; } @ Override protected FileListProvider openFileList ( String targetName , String batchId , String jobflowId , String executionId ) throws IOException { return new StreamFileListProvider ( ) { @ Override protected InputStream getInputStream ( ) throws IOException { return new ByteArrayInputStream ( new byte [ ] ) ; } @ Override protected OutputStream getOutputStream ( ) throws IOException { File file = new File ( testFile ) ; return new FileOutputStream ( file ) ; } @ Override protected void waitForDone ( ) throws IOException , InterruptedException { if ( success == false ) { throw new IOException ( ) ; } } @ Override public void close ( ) throws IOException { return ; } } ; } } } package com . asakusafw . bulkloader . importer ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class ImportFileDeleteTest { private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void deleteFileTest01 ( ) throws Exception { File dumpDir = new File ( "" ) ; File importFile1 = new File ( dumpDir , "" ) ; File importFile2 = new File ( dumpDir , "" ) ; File importFile3 = new File ( dumpDir , "" ) ; importFile1 . createNewFile ( ) ; importFile2 . createNewFile ( ) ; importFile3 . createNewFile ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportFile ( importFile1 ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportFile ( importFile2 ) ; targetTable . put ( "" , tableBean2 ) ; ImportTargetTableBean tableBean3 = new ImportTargetTableBean ( ) ; tableBean3 . setImportFile ( importFile3 ) ; targetTable . put ( "" , tableBean3 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; assertFalse ( importFile1 . exists ( ) ) ; assertFalse ( importFile2 . exists ( ) ) ; assertFalse ( importFile3 . exists ( ) ) ; assertTrue ( dumpDir . exists ( ) ) ; } @ Test public void deleteFileTest02 ( ) throws Exception { File dumpDir = new File ( "" ) ; File importFile1 = new File ( dumpDir , "" ) ; File importFile2 = new File ( dumpDir , "" ) ; File importFile3 = new File ( dumpDir , "" ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportFile ( importFile1 ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportFile ( importFile2 ) ; targetTable . put ( "" , tableBean2 ) ; ImportTargetTableBean tableBean3 = new ImportTargetTableBean ( ) ; tableBean3 . setImportFile ( importFile3 ) ; targetTable . put ( "" , tableBean3 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; assertFalse ( importFile1 . exists ( ) ) ; assertFalse ( importFile2 . exists ( ) ) ; assertFalse ( importFile3 . exists ( ) ) ; assertTrue ( dumpDir . exists ( ) ) ; } @ Test public void deleteFileTest03 ( ) throws Exception { File importFile1 = null ; File importFile2 = null ; File importFile3 = null ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportFile ( importFile1 ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportFile ( importFile2 ) ; targetTable . put ( "" , tableBean2 ) ; ImportTargetTableBean tableBean3 = new ImportTargetTableBean ( ) ; tableBean3 . setImportFile ( importFile3 ) ; targetTable . put ( "" , tableBean3 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } public void deleteFileTest05 ( ) throws Exception { File dumpDir = new File ( "" ) ; File importFile1 = new File ( dumpDir , "" ) ; File importFile2 = new File ( dumpDir , "" ) ; File importFile3 = new File ( dumpDir , "" ) ; importFile1 . createNewFile ( ) ; importFile2 . createNewFile ( ) ; FileOutputStream fos = null ; try { fos = new FileOutputStream ( importFile3 ) ; fos . write ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportFile ( importFile1 ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportFile ( importFile2 ) ; targetTable . put ( "" , tableBean2 ) ; ImportTargetTableBean tableBean3 = new ImportTargetTableBean ( ) ; tableBean3 . setImportFile ( importFile3 ) ; targetTable . put ( "" , tableBean3 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; ImportFileDelete delete = new ImportFileDelete ( ) ; delete . deleteFile ( bean ) ; } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { } } } assertFalse ( importFile1 . exists ( ) ) ; assertFalse ( importFile2 . exists ( ) ) ; assertTrue ( importFile3 . exists ( ) ) ; assertTrue ( dumpDir . exists ( ) ) ; importFile3 . delete ( ) ; } } package com . asakusafw . bulkloader . common ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . runtime . util . VariableTable ; @ SuppressWarnings ( { "" , "" } ) public class JobFlowParamLoaderTest { private static String targetName = "" ; private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , "" ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , targetName ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void loadImportParamTest01 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadImportParam ( targetName , "" , "" , true ) ; Map < String , ImportTargetTableBean > importTargetTable = loder . getImportTargetTables ( ) ; assertTrue ( result ) ; ImportTargetTableBean table1 = importTargetTable . get ( "" ) ; assertEquals ( , table1 . getImportTargetColumns ( ) . size ( ) ) ; assertEquals ( "" , table1 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getSearchCondition ( ) ) ; assertEquals ( ImportTableLockType . find ( "" ) , table1 . getLockType ( ) ) ; assertEquals ( ImportTableLockedOperation . find ( "" ) , table1 . getLockedOperation ( ) ) ; assertEquals ( "" , table1 . getImportTargetType ( ) . getName ( ) ) ; assertEquals ( "" , table1 . getDfsFilePath ( ) ) ; ImportTargetTableBean table2 = importTargetTable . get ( "" ) ; assertEquals ( , table2 . getImportTargetColumns ( ) . size ( ) ) ; assertEquals ( "" , table2 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , table2 . getSearchCondition ( ) ) ; assertEquals ( ImportTableLockType . find ( "" ) , table2 . getLockType ( ) ) ; assertEquals ( ImportTableLockedOperation . find ( "" ) , table2 . getLockedOperation ( ) ) ; assertEquals ( "" , table2 . getImportTargetType ( ) . getName ( ) ) ; assertEquals ( "" , table2 . getDfsFilePath ( ) ) ; ImportTargetTableBean table3 = importTargetTable . get ( "" ) ; assertEquals ( , table3 . getImportTargetColumns ( ) . size ( ) ) ; assertEquals ( "" , table3 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , table3 . getImportTargetColumns ( ) . get ( ) ) ; assertNull ( table3 . getSearchCondition ( ) ) ; assertEquals ( ImportTableLockType . find ( "" ) , table3 . getLockType ( ) ) ; assertEquals ( ImportTableLockedOperation . find ( "" ) , table3 . getLockedOperation ( ) ) ; assertEquals ( "" , table3 . getImportTargetType ( ) . getName ( ) ) ; assertEquals ( "" , table3 . getDfsFilePath ( ) ) ; } @ Test public void loadImportParamTest02 ( ) throws Exception { VariableTable table = new VariableTable ( ) ; table . defineVariable ( "" , "" ) ; table . defineVariable ( "" , "" ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . put ( Constants . THUNDER_GATE_HOME , System . getenv ( Constants . THUNDER_GATE_HOME ) ) ; env . put ( Constants . ENV_ARGS , table . toSerialString ( ) ) ; ConfigurationLoader . setEnv ( env ) ; JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadImportParam ( targetName , "" , "" , true ) ; Map < String , ImportTargetTableBean > importTargetTable = loder . getImportTargetTables ( ) ; assertTrue ( result ) ; ImportTargetTableBean table1 = importTargetTable . get ( "" ) ; assertEquals ( "" , table1 . getSearchCondition ( ) ) ; } @ Test public void loadImportParamTest03 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadImportParam ( targetName , "" , "" , true ) ; Map < String , ImportTargetTableBean > importTargetTable = loder . getImportTargetTables ( ) ; assertTrue ( result ) ; assertEquals ( , importTargetTable . size ( ) ) ; } @ Test public void loadImportParamTest04 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadImportParam ( targetName , "" , "" , true ) ; Map < String , ImportTargetTableBean > importTargetTable = loder . getImportTargetTables ( ) ; assertFalse ( result ) ; assertNull ( importTargetTable ) ; } @ Test public void loadImportParamTest05 ( ) throws Exception { VariableTable table = new VariableTable ( ) ; table . defineVariable ( "" , "" ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . put ( Constants . THUNDER_GATE_HOME , System . getenv ( Constants . THUNDER_GATE_HOME ) ) ; env . put ( Constants . ENV_ARGS , table . toSerialString ( ) ) ; ConfigurationLoader . setEnv ( env ) ; JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadImportParam ( targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void loadImportParamTest06 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadImportParam ( targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void loadImportParamTest07 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadImportParam ( targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void loadImportParamTest08 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadImportParam ( targetName , "" , "" , true ) ; Map < String , ImportTargetTableBean > importTargetTable = loder . getImportTargetTables ( ) ; assertTrue ( result ) ; Iterator < String > it = importTargetTable . keySet ( ) . iterator ( ) ; assertEquals ( "" , it . next ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertEquals ( "" , it . next ( ) ) ; } @ Test public void loadExportParamTest01 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadExportParam ( targetName , "" , "" ) ; Map < String , ExportTargetTableBean > exportTargetTable = loder . getExportTargetTables ( ) ; assertTrue ( result ) ; ExportTargetTableBean table1 = exportTargetTable . get ( "" ) ; assertTrue ( table1 . isDuplicateCheck ( ) ) ; assertEquals ( "" , table1 . getErrorTableName ( ) ) ; assertEquals ( , table1 . getExportTsvColumn ( ) . size ( ) ) ; assertEquals ( "" , table1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , table1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , table1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , table1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , table1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( , table1 . getExportTableColumns ( ) . size ( ) ) ; assertEquals ( "" , table1 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( , table1 . getErrorTableColumns ( ) . size ( ) ) ; assertEquals ( "" , table1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( , table1 . getKeyColumns ( ) . size ( ) ) ; assertEquals ( "" , table1 . getKeyColumns ( ) . get ( ) ) ; assertEquals ( "" , table1 . getErrorCodeColumn ( ) ) ; assertEquals ( "" , table1 . getErrorCode ( ) ) ; assertEquals ( "" , table1 . getExportTargetType ( ) . getName ( ) ) ; List < String > path1 = table1 . getDfsFilePaths ( ) ; assertEquals ( , path1 . size ( ) ) ; assertEquals ( "" , path1 . get ( ) ) ; assertEquals ( "" , path1 . get ( ) ) ; ExportTargetTableBean table2 = exportTargetTable . get ( "" ) ; assertFalse ( table2 . isDuplicateCheck ( ) ) ; assertNull ( table2 . getErrorTableName ( ) ) ; assertEquals ( , table2 . getExportTsvColumn ( ) . size ( ) ) ; assertEquals ( "" , table2 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , table2 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , table2 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( , table2 . getExportTableColumns ( ) . size ( ) ) ; assertEquals ( "" , table2 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( "" , table2 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( "" , table2 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( , table2 . getErrorTableColumns ( ) . size ( ) ) ; assertEquals ( , table2 . getKeyColumns ( ) . size ( ) ) ; assertNull ( table2 . getErrorCodeColumn ( ) ) ; assertNull ( table2 . getErrorCode ( ) ) ; assertEquals ( "" , table2 . getExportTargetType ( ) . getName ( ) ) ; List < String > path2 = table2 . getDfsFilePaths ( ) ; assertEquals ( , path2 . size ( ) ) ; assertEquals ( "" , path2 . get ( ) ) ; ExportTargetTableBean table3 = exportTargetTable . get ( "" ) ; assertFalse ( table3 . isDuplicateCheck ( ) ) ; assertNull ( table3 . getErrorTableName ( ) ) ; assertEquals ( , table3 . getExportTsvColumn ( ) . size ( ) ) ; assertEquals ( "" , table3 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( , table3 . getExportTableColumns ( ) . size ( ) ) ; assertEquals ( "" , table3 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( , table3 . getErrorTableColumns ( ) . size ( ) ) ; assertEquals ( , table3 . getKeyColumns ( ) . size ( ) ) ; assertNull ( table3 . getErrorCodeColumn ( ) ) ; assertNull ( table3 . getErrorCode ( ) ) ; assertEquals ( "" , table3 . getExportTargetType ( ) . getName ( ) ) ; List < String > path3 = table3 . getDfsFilePaths ( ) ; assertEquals ( , path3 . size ( ) ) ; assertEquals ( "" , path3 . get ( ) ) ; } @ Test public void loadExportParamTest02 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadExportParam ( targetName , "" , "" ) ; Map < String , ExportTargetTableBean > exportTargetTable = loder . getExportTargetTables ( ) ; assertTrue ( result ) ; assertEquals ( , exportTargetTable . size ( ) ) ; } @ Test public void loadExportParamTest03 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadExportParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadExportParamTest04 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadExportParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadExportParamTest05 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadExportParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadExportParamTest06 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadExportParam ( targetName , "" , "" ) ; Map < String , ExportTargetTableBean > exportTargetTable = loder . getExportTargetTables ( ) ; assertTrue ( result ) ; Iterator < String > it = exportTargetTable . keySet ( ) . iterator ( ) ; assertEquals ( "" , it . next ( ) ) ; assertEquals ( "" , it . next ( ) ) ; assertEquals ( "" , it . next ( ) ) ; } @ Test public void checkImportParamTest01 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean2 . setSearchCondition ( "" ) ; tableBean2 . setUseCache ( false ) ; tableBean2 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean2 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean2 . setImportTargetType ( this . getClass ( ) ) ; tableBean2 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean2 ) ; ImportTargetTableBean tableBean3 = new ImportTargetTableBean ( ) ; tableBean3 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean3 . setSearchCondition ( "" ) ; tableBean3 . setUseCache ( false ) ; tableBean3 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean3 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean3 . setImportTargetType ( this . getClass ( ) ) ; tableBean3 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean3 ) ; ImportTargetTableBean tableBean4 = new ImportTargetTableBean ( ) ; tableBean4 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean4 . setSearchCondition ( "" ) ; tableBean4 . setUseCache ( false ) ; tableBean4 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean4 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean4 . setImportTargetType ( this . getClass ( ) ) ; tableBean4 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean4 ) ; ImportTargetTableBean tableBean5 = new ImportTargetTableBean ( ) ; tableBean5 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean5 . setSearchCondition ( "" ) ; tableBean5 . setUseCache ( false ) ; tableBean5 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean5 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean5 . setImportTargetType ( this . getClass ( ) ) ; tableBean5 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean5 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertTrue ( result ) ; } @ Test public void checkImportParamTest02 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . NONE ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . FORCE ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean2 . setSearchCondition ( "" ) ; tableBean2 . setUseCache ( false ) ; tableBean2 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean2 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean2 . setImportTargetType ( this . getClass ( ) ) ; tableBean2 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean2 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , null } ) ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; tableBean2 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest03 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; tableBean1 . setLockType ( null ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest04 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; tableBean1 . setLockedOperation ( null ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest05 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( null ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest06 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( null ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest07 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; tableBean1 . setLockedOperation ( null ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest08 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; tableBean1 . setLockedOperation ( null ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest09 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; tableBean1 . setLockedOperation ( null ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest10 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; tableBean1 . setLockedOperation ( null ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , true ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest11 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean2 . setSearchCondition ( "" ) ; tableBean2 . setUseCache ( false ) ; tableBean2 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean2 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean2 . setImportTargetType ( this . getClass ( ) ) ; tableBean2 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean2 ) ; ImportTargetTableBean tableBean3 = new ImportTargetTableBean ( ) ; tableBean3 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean3 . setSearchCondition ( "" ) ; tableBean3 . setUseCache ( false ) ; tableBean3 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean3 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean3 . setImportTargetType ( this . getClass ( ) ) ; tableBean3 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean3 ) ; ImportTargetTableBean tableBean4 = new ImportTargetTableBean ( ) ; tableBean4 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean4 . setSearchCondition ( "" ) ; tableBean4 . setUseCache ( false ) ; tableBean4 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean4 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean4 . setImportTargetType ( this . getClass ( ) ) ; tableBean4 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean4 ) ; ImportTargetTableBean tableBean5 = new ImportTargetTableBean ( ) ; tableBean5 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; tableBean5 . setSearchCondition ( "" ) ; tableBean5 . setUseCache ( false ) ; tableBean5 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean5 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean5 . setImportTargetType ( this . getClass ( ) ) ; tableBean5 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean5 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , false ) ; assertTrue ( result ) ; } @ Test public void checkImportParamTest12 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , false ) ; assertFalse ( result ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , false ) ; assertFalse ( result ) ; } @ Test public void checkImportParamTest13 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setImportTargetColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; tableBean1 . setSearchCondition ( "" ) ; tableBean1 . setUseCache ( false ) ; tableBean1 . setLockType ( ImportTableLockType . find ( "" ) ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; tableBean1 . setDfsFilePath ( "" ) ; targetTable . put ( "" , tableBean1 ) ; boolean result = loader . checkImportParam ( targetTable , targetName , "" , "" , false ) ; assertFalse ( result ) ; tableBean1 . setLockedOperation ( ImportTableLockedOperation . find ( "" ) ) ; result = loader . checkImportParam ( targetTable , targetName , "" , "" , false ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest01 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( false ) ; table1 . setErrorTableName ( null ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { } ) ) ; table1 . setErrorCodeColumn ( null ) ; table1 . setErrorCode ( null ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( false ) ; table2 . setErrorTableName ( null ) ; table2 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table2 . setErrorTableColumns ( Arrays . asList ( new String [ ] { } ) ) ; table2 . setKeyColumns ( Arrays . asList ( new String [ ] { } ) ) ; table2 . setErrorCodeColumn ( null ) ; table2 . setErrorCode ( null ) ; table2 . setExportTargetType ( this . getClass ( ) ) ; List < String > list2 = new ArrayList < String > ( ) ; list2 . add ( "" ) ; table2 . setDfsFilePaths ( list2 ) ; targetTable . put ( "" , table2 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertTrue ( result ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertTrue ( result ) ; } @ Test public void checkExportParamTest02 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setDuplicateCheck ( false ) ; table2 . setErrorTableName ( null ) ; table2 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table2 . setErrorTableColumns ( Arrays . asList ( new String [ ] { } ) ) ; table2 . setKeyColumns ( Arrays . asList ( new String [ ] { } ) ) ; table2 . setErrorCodeColumn ( null ) ; table2 . setErrorCode ( null ) ; table2 . setExportTargetType ( this . getClass ( ) ) ; List < String > list2 = new ArrayList < String > ( ) ; list2 . add ( "" ) ; table2 . setDfsFilePaths ( list2 ) ; targetTable . put ( "" , table2 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertTrue ( result ) ; } @ Test public void checkExportParamTest03 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( null ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , null } ) ) ; result = loader . checkExportParam ( targetTable , "" , targetName , "" ) ; assertFalse ( result ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; result = loader . checkExportParam ( targetTable , "" , targetName , "" ) ; assertFalse ( result ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { } ) ) ; result = loader . checkExportParam ( targetTable , "" , targetName , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest04 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , null } ) ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest05 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , null } ) ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest06 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" , "" , null } ) ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest07 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( null ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setErrorCodeColumn ( "" ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest08 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest09 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest10 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( null ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; table1 . setErrorCode ( "" ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest11 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table2 . setExportTargetType ( null ) ; List < String > list2 = new ArrayList < String > ( ) ; list2 . add ( "" ) ; table2 . setDfsFilePaths ( list2 ) ; targetTable . put ( "" , table2 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest12 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , table1 ) ; ExportTargetTableBean table2 = new ExportTargetTableBean ( ) ; table2 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table2 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table2 . setExportTargetType ( this . getClass ( ) ) ; List < String > list2 = new ArrayList < String > ( ) ; list2 . add ( "" ) ; table2 . setDfsFilePaths ( list2 ) ; targetTable . put ( "" , table2 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( null ) ; table1 . setDfsFilePaths ( list1 ) ; result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest13 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableName ( "" ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { "" } ) ) ; table1 . setErrorCodeColumn ( "" ) ; table1 . setErrorCode ( "" ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest14 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( false ) ; table1 . setErrorTableName ( null ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { } ) ) ; table1 . setErrorCodeColumn ( null ) ; table1 . setErrorCode ( null ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void checkExportParamTest15 ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; Map < String , ExportTargetTableBean > targetTable = new LinkedHashMap < String , ExportTargetTableBean > ( ) ; ExportTargetTableBean table1 = new ExportTargetTableBean ( ) ; table1 . setDuplicateCheck ( false ) ; table1 . setErrorTableName ( null ) ; table1 . setExportTsvColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setExportTableColumns ( Arrays . asList ( new String [ ] { "" , "" } ) ) ; table1 . setErrorTableName ( "" ) ; table1 . setDuplicateCheck ( true ) ; table1 . setErrorTableColumns ( Arrays . asList ( new String [ ] { "" , "" , "" } ) ) ; table1 . setKeyColumns ( Arrays . asList ( new String [ ] { } ) ) ; table1 . setErrorCodeColumn ( null ) ; table1 . setErrorCode ( null ) ; table1 . setExportTargetType ( this . getClass ( ) ) ; List < String > list1 = new ArrayList < String > ( ) ; list1 . add ( "" ) ; table1 . setDfsFilePaths ( list1 ) ; targetTable . put ( "" , table1 ) ; boolean result = loader . checkExportParam ( targetTable , targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam01 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; Map < String , ImportTargetTableBean > importTargetTable = loder . getImportTargetTables ( ) ; Map < String , ExportTargetTableBean > exportTargetTable = loder . getExportTargetTables ( ) ; assertTrue ( result ) ; assertTrue ( result ) ; ImportTargetTableBean impTable1 = importTargetTable . get ( "" ) ; assertEquals ( , impTable1 . getImportTargetColumns ( ) . size ( ) ) ; assertEquals ( "" , impTable1 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , impTable1 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , impTable1 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , impTable1 . getSearchCondition ( ) ) ; assertEquals ( ImportTableLockType . find ( "" ) , impTable1 . getLockType ( ) ) ; assertEquals ( ImportTableLockedOperation . find ( "" ) , impTable1 . getLockedOperation ( ) ) ; assertEquals ( "" , impTable1 . getImportTargetType ( ) . getName ( ) ) ; assertEquals ( "" , impTable1 . getDfsFilePath ( ) ) ; ImportTargetTableBean impTable2 = importTargetTable . get ( "" ) ; assertEquals ( , impTable2 . getImportTargetColumns ( ) . size ( ) ) ; assertEquals ( "" , impTable2 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , impTable2 . getSearchCondition ( ) ) ; assertEquals ( false , impTable2 . isUseCache ( ) ) ; assertEquals ( ImportTableLockType . find ( "" ) , impTable2 . getLockType ( ) ) ; assertEquals ( ImportTableLockedOperation . find ( "" ) , impTable2 . getLockedOperation ( ) ) ; assertEquals ( "" , impTable2 . getImportTargetType ( ) . getName ( ) ) ; assertEquals ( "" , impTable2 . getDfsFilePath ( ) ) ; ImportTargetTableBean impTable3 = importTargetTable . get ( "" ) ; assertEquals ( , impTable3 . getImportTargetColumns ( ) . size ( ) ) ; assertEquals ( "" , impTable3 . getImportTargetColumns ( ) . get ( ) ) ; assertEquals ( "" , impTable3 . getImportTargetColumns ( ) . get ( ) ) ; assertNull ( impTable3 . getSearchCondition ( ) ) ; assertEquals ( false , impTable3 . isUseCache ( ) ) ; assertEquals ( ImportTableLockType . find ( "" ) , impTable3 . getLockType ( ) ) ; assertEquals ( ImportTableLockedOperation . find ( "" ) , impTable3 . getLockedOperation ( ) ) ; assertEquals ( "" , impTable3 . getImportTargetType ( ) . getName ( ) ) ; assertEquals ( "" , impTable3 . getDfsFilePath ( ) ) ; ExportTargetTableBean expTable1 = exportTargetTable . get ( "" ) ; assertTrue ( expTable1 . isDuplicateCheck ( ) ) ; assertEquals ( "" , expTable1 . getErrorTableName ( ) ) ; assertEquals ( , expTable1 . getExportTsvColumn ( ) . size ( ) ) ; assertEquals ( "" , expTable1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( , expTable1 . getExportTableColumns ( ) . size ( ) ) ; assertEquals ( "" , expTable1 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( , expTable1 . getErrorTableColumns ( ) . size ( ) ) ; assertEquals ( "" , expTable1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getErrorTableColumns ( ) . get ( ) ) ; assertEquals ( , expTable1 . getKeyColumns ( ) . size ( ) ) ; assertEquals ( "" , expTable1 . getKeyColumns ( ) . get ( ) ) ; assertEquals ( "" , expTable1 . getErrorCodeColumn ( ) ) ; assertEquals ( "" , expTable1 . getErrorCode ( ) ) ; assertEquals ( "" , expTable1 . getExportTargetType ( ) . getName ( ) ) ; List < String > path1 = expTable1 . getDfsFilePaths ( ) ; assertEquals ( , path1 . size ( ) ) ; assertEquals ( "" , path1 . get ( ) ) ; assertEquals ( "" , path1 . get ( ) ) ; ExportTargetTableBean expTable2 = exportTargetTable . get ( "" ) ; assertFalse ( expTable2 . isDuplicateCheck ( ) ) ; assertNull ( expTable2 . getErrorTableName ( ) ) ; assertEquals ( , expTable2 . getExportTsvColumn ( ) . size ( ) ) ; assertEquals ( "" , expTable2 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , expTable2 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( "" , expTable2 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( , expTable2 . getExportTableColumns ( ) . size ( ) ) ; assertEquals ( "" , expTable2 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( "" , expTable2 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( "" , expTable2 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( , expTable2 . getErrorTableColumns ( ) . size ( ) ) ; assertEquals ( , expTable2 . getKeyColumns ( ) . size ( ) ) ; assertNull ( expTable2 . getErrorCodeColumn ( ) ) ; assertNull ( expTable2 . getErrorCode ( ) ) ; assertEquals ( "" , expTable2 . getExportTargetType ( ) . getName ( ) ) ; List < String > path2 = expTable2 . getDfsFilePaths ( ) ; assertEquals ( , path2 . size ( ) ) ; assertEquals ( "" , path2 . get ( ) ) ; ExportTargetTableBean expTable3 = exportTargetTable . get ( "" ) ; assertFalse ( expTable3 . isDuplicateCheck ( ) ) ; assertNull ( expTable3 . getErrorTableName ( ) ) ; assertEquals ( , expTable3 . getExportTsvColumn ( ) . size ( ) ) ; assertEquals ( "" , expTable3 . getExportTsvColumn ( ) . get ( ) ) ; assertEquals ( , expTable3 . getExportTableColumns ( ) . size ( ) ) ; assertEquals ( "" , expTable3 . getExportTableColumns ( ) . get ( ) ) ; assertEquals ( , expTable3 . getErrorTableColumns ( ) . size ( ) ) ; assertEquals ( , expTable3 . getKeyColumns ( ) . size ( ) ) ; assertNull ( expTable3 . getErrorCodeColumn ( ) ) ; assertNull ( expTable3 . getErrorCode ( ) ) ; assertEquals ( "" , expTable3 . getExportTargetType ( ) . getName ( ) ) ; List < String > path3 = expTable3 . getDfsFilePaths ( ) ; assertEquals ( , path3 . size ( ) ) ; assertEquals ( "" , path3 . get ( ) ) ; } @ Test public void loadRecoveryParam02 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertTrue ( result ) ; } @ Test public void loadRecoveryParam03 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertTrue ( result ) ; } @ Test public void loadRecoveryParam04 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam05 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam06 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam07 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam08 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam09 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam10 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam11 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam12 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadRecoveryParam13 ( ) throws Exception { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; return prop ; } @ Override protected Properties getExportProp ( File dslFile , String targetName ) throws IOException { Properties prop = new Properties ( ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; prop . setProperty ( "" , "" ) ; return prop ; } } ; boolean result = loder . loadRecoveryParam ( targetName , "" , "" ) ; assertFalse ( result ) ; } @ Test public void loadCacheBuildParam ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loader . loadCacheBuildParam ( targetName , "" , "" ) ; assertThat ( result , is ( true ) ) ; assertThat ( loader . getImportTargetTables ( ) . size ( ) , is ( ) ) ; ImportTargetTableBean target = loader . getImportTargetTables ( ) . get ( "" ) ; assertThat ( target . getCacheId ( ) , is ( notNullValue ( ) ) ) ; assertThat ( target . getLockType ( ) , is ( ImportTableLockType . NONE ) ) ; } @ Test public void loadCacheBuildParam_invalid ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loader . loadCacheBuildParam ( targetName , "" , "" ) ; assertThat ( result , is ( false ) ) ; } @ Test public void loadExtractParam ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loader . loadExtractParam ( targetName , "" , "" ) ; assertThat ( result , is ( true ) ) ; assertThat ( loader . getImportTargetTables ( ) . size ( ) , is ( ) ) ; } @ Test public void loadExtractParam_invalid ( ) throws Exception { JobFlowParamLoader loader = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File dslFile , String targetName ) throws IOException { System . out . println ( dslFile ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; boolean result = loader . loadExtractParam ( targetName , "" , "" ) ; assertThat ( result , is ( false ) ) ; } } package com . asakusafw . bulkloader . common ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class BulkLoaderInitializerTest { private static String targetName = "" ; private static List < String > propertys_db = Arrays . asList ( new String [ ] { "" } ) ; private static List < String > propertys_hc = Arrays . asList ( new String [ ] { "" } ) ; private static List < String > propertys_er1 = Arrays . asList ( new String [ ] { "" } ) ; private static List < String > propertys_er2 = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { ConfigurationLoader . setProperty ( new Properties ( ) ) ; } @ After public void tearDown ( ) throws Exception { } @ Test public void initHCTest01 ( ) throws Exception { boolean result = BulkLoaderInitializer . initHadoopCluster ( jobflowId , executionId , propertys_hc ) ; assertTrue ( result ) ; } @ Test public void initDBTest01 ( ) throws Exception { boolean result = BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys_db , targetName ) ; assertTrue ( result ) ; } @ Test public void initDBTest02 ( ) throws Exception { boolean result = BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys_hc , targetName ) ; assertFalse ( result ) ; } @ Test public void initDBTest03 ( ) throws Exception { boolean result = BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys_er1 , targetName ) ; assertFalse ( result ) ; } @ Test public void initDBTest04 ( ) throws Exception { boolean result = BulkLoaderInitializer . initDBServer ( jobflowId , executionId , Arrays . asList ( new String [ ] { "" } ) , targetName ) ; assertFalse ( result ) ; } @ Test public void initDBTest05 ( ) throws Exception { boolean result = BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys_er2 , targetName ) ; assertFalse ( result ) ; } @ Test public void initDBTest07 ( ) throws Exception { boolean result = BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys_db , "" ) ; assertFalse ( result ) ; } } package com . asakusafw . bulkloader . common ; import static org . junit . Assert . * ; import java . sql . Connection ; import java . sql . SQLException ; import java . util . Arrays ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class DBConnectionTest { private static String targetName = "" ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { } @ After public void tearDown ( ) throws Exception { } @ Test public void getConnectionTest01 ( ) throws Exception { Connection conn = null ; try { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , Arrays . asList ( new String [ ] { "" } ) , targetName ) ; UnitTestUtil . startUp ( ) ; conn = DBConnection . getConnection ( ) ; DBConnection . closePs ( null ) ; DBConnection . closeRs ( null ) ; DBConnection . closeConn ( null ) ; DBConnection . closeConn ( conn ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } } @ Test public void getConnectionTest02 ( ) throws Exception { Connection conn = null ; try { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , Arrays . asList ( new String [ ] { "" } ) , targetName ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_NAME_DB_PRAM , "" ) ; ConfigurationLoader . setProperty ( p ) ; conn = DBConnection . getConnection ( ) ; DBConnection . closeConn ( conn ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } } @ Test public void getConnectionTest03 ( ) throws Exception { Connection conn = null ; try { String appHome = System . getProperty ( Constants . THUNDER_GATE_HOME ) ; String propDir = appHome + "" ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , Arrays . asList ( new String [ ] { "" } ) , targetName ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_NAME_DB_PRAM , propDir ) ; ConfigurationLoader . setProperty ( p ) ; conn = DBConnection . getConnection ( ) ; DBConnection . closeConn ( conn ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } finally { DBConnection . closeConn ( conn ) ; } } @ Test public void getConnectionTest04 ( ) throws Exception { Connection conn = null ; try { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , Arrays . asList ( new String [ ] { "" } ) , targetName ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_DB_USER , "" ) ; p . setProperty ( Constants . PROP_KEY_DB_PASSWORD , "" ) ; ConfigurationLoader . setProperty ( p ) ; conn = DBConnection . getConnection ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; assertTrue ( e . getCause ( ) instanceof SQLException ) ; } finally { DBConnection . closeConn ( conn ) ; } } } package com . asakusafw . bulkloader . common ; import static org . junit . Assert . * ; import java . io . File ; import java . sql . Connection ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Ignore ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . testtools . TestUtils ; public class DBAccessUtilTest { private static String targetName = "" ; private static List < String > propertys = Arrays . asList ( new String [ ] { "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , targetName ) ; UnitTestUtil . setUpDB ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownDB ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( jobflowId , executionId , propertys , targetName ) ; UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void createRecordLockTableNameTest01 ( ) throws Exception { String name = DBAccessUtil . createRecordLockTableName ( "" ) ; assertEquals ( "" , name ) ; } @ Test public void selectJobFlowSidTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String jobFlowSid = DBAccessUtil . selectJobFlowSid ( "" ) ; assertEquals ( "" , jobFlowSid ) ; } @ Test public void selectJobFlowSidTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String jobFlowSid = DBAccessUtil . selectJobFlowSid ( "" ) ; assertNull ( jobFlowSid ) ; } @ Test public void selectJobFlowSidTest03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; String jobFlowSid = DBAccessUtil . selectJobFlowSid ( "" ) ; assertEquals ( "" , jobFlowSid ) ; } @ Test public void getExportTempTable01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; List < ExportTempTableBean > bean = DBAccessUtil . getExportTempTable ( "" ) ; assertEquals ( , bean . size ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowSid ( ) ) ; assertEquals ( "" , bean . get ( ) . getExportTableName ( ) ) ; assertEquals ( "" , bean . get ( ) . getTemporaryTableName ( ) ) ; assertEquals ( "" , bean . get ( ) . getDuplicateFlagTableName ( ) ) ; assertEquals ( null , bean . get ( ) . getTempTableStatus ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowSid ( ) ) ; assertEquals ( "" , bean . get ( ) . getExportTableName ( ) ) ; assertEquals ( "" , bean . get ( ) . getTemporaryTableName ( ) ) ; assertEquals ( "" , bean . get ( ) . getDuplicateFlagTableName ( ) ) ; assertEquals ( ExportTempTableStatus . find ( "" ) , bean . get ( ) . getTempTableStatus ( ) ) ; } @ Test public void getExportTempTable02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; List < ExportTempTableBean > bean = DBAccessUtil . getExportTempTable ( "" ) ; assertEquals ( , bean . size ( ) ) ; } @ Test public void delSystemColumn01 ( ) throws Exception { List < String > list = new ArrayList < String > ( ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; List < String > result = DBAccessUtil . delSystemColumn ( list ) ; assertEquals ( , result . size ( ) ) ; assertEquals ( "" , result . get ( ) ) ; assertEquals ( "" , result . get ( ) ) ; assertEquals ( "" , result . get ( ) ) ; } @ Test public void delSystemColumn02 ( ) throws Exception { List < String > list = new ArrayList < String > ( ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; List < String > result = DBAccessUtil . delSystemColumn ( list ) ; assertEquals ( , result . size ( ) ) ; assertEquals ( "" , result . get ( ) ) ; assertEquals ( "" , result . get ( ) ) ; assertEquals ( "" , result . get ( ) ) ; } @ Test public void delErrorSystemColumn01 ( ) throws Exception { List < String > list = new ArrayList < String > ( ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; List < String > result = DBAccessUtil . delErrorSystemColumn ( list , "" ) ; assertEquals ( , result . size ( ) ) ; assertEquals ( "" , result . get ( ) ) ; assertEquals ( "" , result . get ( ) ) ; assertEquals ( "" , result . get ( ) ) ; } @ Test public void joinColumnArray01 ( ) throws Exception { List < String > list = new ArrayList < String > ( ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; String result = DBAccessUtil . joinColumnArray ( list ) ; assertEquals ( "" , result ) ; } @ Test public void selectRunningJobFlowTest01 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; List < ExporterBean > bean = DBAccessUtil . selectRunningJobFlow ( "" ) ; assertEquals ( , bean . size ( ) ) ; assertEquals ( "" , bean . get ( ) . getBatchId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowSid ( ) ) ; assertEquals ( "" , bean . get ( ) . getTargetName ( ) ) ; assertEquals ( "" , bean . get ( ) . getExecutionId ( ) ) ; } @ Test public void selectRunningJobFlowTest02 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; List < ExporterBean > bean = DBAccessUtil . selectRunningJobFlow ( "" ) ; assertEquals ( , bean . size ( ) ) ; } @ Test public void selectRunningJobFlowTest03 ( ) throws Exception { File testDataDir = new File ( "" ) ; TestUtils util = new TestUtils ( testDataDir ) ; util . storeToDatabase ( false ) ; List < ExporterBean > bean = DBAccessUtil . selectRunningJobFlow ( null ) ; assertEquals ( , bean . size ( ) ) ; assertEquals ( "" , bean . get ( ) . getBatchId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowSid ( ) ) ; assertEquals ( "" , bean . get ( ) . getTargetName ( ) ) ; assertEquals ( "" , bean . get ( ) . getExecutionId ( ) ) ; assertEquals ( "" , bean . get ( ) . getBatchId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowSid ( ) ) ; assertEquals ( "" , bean . get ( ) . getTargetName ( ) ) ; assertEquals ( "" , bean . get ( ) . getExecutionId ( ) ) ; assertEquals ( "" , bean . get ( ) . getBatchId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowSid ( ) ) ; assertEquals ( "" , bean . get ( ) . getTargetName ( ) ) ; assertEquals ( "" , bean . get ( ) . getExecutionId ( ) ) ; assertEquals ( "" , bean . get ( ) . getBatchId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowSid ( ) ) ; assertEquals ( "" , bean . get ( ) . getTargetName ( ) ) ; assertEquals ( "" , bean . get ( ) . getExecutionId ( ) ) ; assertEquals ( "" , bean . get ( ) . getBatchId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowId ( ) ) ; assertEquals ( "" , bean . get ( ) . getJobflowSid ( ) ) ; assertEquals ( "" , bean . get ( ) . getTargetName ( ) ) ; assertEquals ( "" , bean . get ( ) . getExecutionId ( ) ) ; } @ Test public void getJobflowInstanceLockTest01 ( ) throws Exception { Connection conn = DBConnection . getConnection ( ) ; boolean result = DBAccessUtil . getJobflowInstanceLock ( "" , conn ) ; assertTrue ( result ) ; DBAccessUtil . releaseJobflowInstanceLock ( conn ) ; } @ Test @ Ignore public void getJobflowInstanceLockTest02 ( ) throws Exception { Connection conn1 = DBConnection . getConnection ( ) ; boolean result = DBAccessUtil . getJobflowInstanceLock ( "" , conn1 ) ; assertTrue ( result ) ; Connection conn2 = DBConnection . getConnection ( ) ; result = DBAccessUtil . getJobflowInstanceLock ( "" , conn2 ) ; assertFalse ( result ) ; DBAccessUtil . releaseJobflowInstanceLock ( conn2 ) ; DBAccessUtil . releaseJobflowInstanceLock ( conn1 ) ; } } package com . asakusafw . bulkloader . common ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Ignore ; import org . junit . Test ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class ConfigurationLoaderTest { static final Log LOG = new Log ( ConfigurationLoaderTest . class ) ; private static final String PATH_DB_PARAMETER = "" ; private static List < String > propertys_db = Arrays . asList ( new String [ ] { "" } ) ; private static List < String > properties_hc = Arrays . asList ( new String [ ] { "" } ) ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { UnitTestUtil . setUpEnv ( ) ; ConfigurationLoader . cleanProp ( ) ; } @ After public void tearDown ( ) throws Exception { } @ Test public void initTest01 ( ) throws Exception { try { ConfigurationLoader . init ( propertys_db , true , false ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } } @ Test public void initTest02 ( ) throws Exception { try { ConfigurationLoader . init ( properties_hc , false , true ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } } @ Test public void initTest03 ( ) throws Exception { try { ConfigurationLoader . init ( Arrays . asList ( new String [ ] { "" } ) , true , false ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof IOException ) ; e . printStackTrace ( ) ; } } @ Test public void checkEnvTest01 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Map < String , String > m = new HashMap < String , String > ( ) ; m . put ( Constants . ASAKUSA_HOME , ConfigurationLoader . getEnvProperty ( Constants . ASAKUSA_HOME ) ) ; m . put ( Constants . THUNDER_GATE_HOME , null ) ; ConfigurationLoader . setEnv ( m ) ; UnitTestUtil . tearDownEnv ( ) ; try { ConfigurationLoader . checkEnv ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof Exception ) ; System . out . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } } @ Test public void checkEnvTest02 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Map < String , String > m = new HashMap < String , String > ( ) ; m . put ( Constants . ASAKUSA_HOME , ConfigurationLoader . getEnvProperty ( Constants . ASAKUSA_HOME ) ) ; m . put ( Constants . THUNDER_GATE_HOME , "" ) ; ConfigurationLoader . setEnv ( m ) ; Properties p = System . getProperties ( ) ; p . setProperty ( Constants . ASAKUSA_HOME , "" ) ; p . setProperty ( Constants . THUNDER_GATE_HOME , "" ) ; ConfigurationLoader . setSysProp ( p ) ; System . setProperties ( p ) ; try { ConfigurationLoader . checkEnv ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof Exception ) ; System . out . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } } @ Test public void checkEnvTest03 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Map < String , String > m = new HashMap < String , String > ( ) ; m . put ( Constants . ASAKUSA_HOME , null ) ; m . put ( Constants . THUNDER_GATE_HOME , ConfigurationLoader . getEnvProperty ( Constants . THUNDER_GATE_HOME ) ) ; ConfigurationLoader . setEnv ( m ) ; UnitTestUtil . tearDownEnv ( ) ; try { ConfigurationLoader . checkEnv ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof Exception ) ; System . out . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } } @ Test public void checkEnvTest04 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Map < String , String > m = new HashMap < String , String > ( ) ; m . put ( Constants . ASAKUSA_HOME , "" ) ; m . put ( Constants . THUNDER_GATE_HOME , ConfigurationLoader . getEnvProperty ( Constants . THUNDER_GATE_HOME ) ) ; ConfigurationLoader . setEnv ( m ) ; Properties p = System . getProperties ( ) ; p . setProperty ( Constants . ASAKUSA_HOME , "" ) ; p . setProperty ( Constants . THUNDER_GATE_HOME , "" ) ; ConfigurationLoader . setSysProp ( p ) ; System . setProperties ( p ) ; try { ConfigurationLoader . checkEnv ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof Exception ) ; System . out . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } } @ Test public void checkAndSetParamHC01 ( ) throws Exception { ConfigurationLoader . init ( properties_hc , false , true ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamHC ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( FileCompType . STORED , FileCompType . find ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_FILE_COMP_TYPE ) ) ) ; } @ Test public void checkAndSetParamHC02 ( ) throws Exception { ConfigurationLoader . init ( properties_hc , false , true ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamHC ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Ignore ( "" ) @ Test public void checkAndSetParamHC03 ( ) throws Exception { ConfigurationLoader . init ( properties_hc , false , true ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamHC ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_WORKINGDIR_USE ) ) ; } @ Ignore ( "" ) @ Test public void checkAndSetParamHC04 ( ) throws Exception { ConfigurationLoader . init ( properties_hc , false , true ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamHC ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamHC05 ( ) throws Exception { ConfigurationLoader . init ( properties_hc , false , true ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamHC ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_LOAD_MAX_SIZE ) ) ; } @ Test public void checkAndSetParamHC06 ( ) throws Exception { ConfigurationLoader . init ( properties_hc , false , true ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamHC ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamHC07 ( ) throws Exception { ConfigurationLoader . init ( properties_hc , false , true ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamHC ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_SEQ_FILE_COMP_TYPE ) ) ; } @ Test public void checkAndSetParam01 ( ) throws Exception { ConfigurationLoader . init ( properties_hc , false , true ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParam ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( new File ( "" ) . getCanonicalPath ( ) , ConfigurationLoader . getProperty ( Constants . PROP_KEY_LOG_CONF_PATH ) ) ; } @ Test public void checkAndSetParamDB02 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( FileCompType . STORED , FileCompType . find ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_FILE_COMP_TYPE ) ) ) ; } @ Test public void checkAndSetParamDB03 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB04 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_FILE_COMP_BUFSIZE ) ) ; } @ Test public void checkAndSetParamDB05 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB06 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_RETRY_COUNT ) ) ; } @ Test public void checkAndSetParamDB07 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB08 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_RETRY_INTERVAL ) ) ; } @ Test public void checkAndSetParamDB09 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB10 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_FILE_COMP_BUFSIZE ) ) ; } @ Test public void checkAndSetParamDB11 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB12 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_RETRY_COUNT ) ) ; } @ Test public void checkAndSetParamDB13 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB14 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_RETRY_INTERVAL ) ) ; } @ Test public void checkAndSetParamDB15 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB18 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD ) ) ; } @ Test public void checkAndSetParamDB19 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB21 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof BulkLoaderSystemException ) ; e . printStackTrace ( ) ; } } @ Test public void checkAndSetParamDB22 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof BulkLoaderSystemException ) ; e . printStackTrace ( ) ; } } @ Test public void checkAndSetParamDB23 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof BulkLoaderSystemException ) ; e . printStackTrace ( ) ; } } @ Test public void checkAndSetParamDB24 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof BulkLoaderSystemException ) ; e . printStackTrace ( ) ; } } @ Ignore ( Constants . PROP_KEY_EXT_SHELL_NAME + "" ) @ Test public void checkAndSetParamDB25 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_EXT_SHELL_NAME , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof BulkLoaderSystemException ) ; e . printStackTrace ( ) ; } } @ Test public void checkAndSetParamDB26 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof BulkLoaderSystemException ) ; e . printStackTrace ( ) ; } } @ Ignore ( Constants . PROP_KEY_COL_SHELL_NAME + "" ) @ Test public void checkAndSetParamDB27 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( Constants . PROP_KEY_COL_SHELL_NAME , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { assertTrue ( e instanceof BulkLoaderSystemException ) ; e . printStackTrace ( ) ; } } @ Test public void checkAndSetParamDB28 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( TsvDeleteType . find ( Constants . PROP_DEFAULT_IMPORT_TSV_DELETE ) , TsvDeleteType . find ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMPORT_TSV_DELETE ) ) ) ; } @ Test public void checkAndSetParamDB29 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void checkAndSetParamDB30 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; } catch ( Exception e ) { fail ( ) ; e . printStackTrace ( ) ; } assertEquals ( TsvDeleteType . find ( Constants . PROP_DEFAULT_EXPORT_TSV_DELETE ) , TsvDeleteType . find ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE ) ) ) ; } @ Test public void checkAndSetParamDB31 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . checkAndSetParamDB ( ) ; fail ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; assertTrue ( e instanceof BulkLoaderSystemException ) ; } } @ Test public void getPropStartWithString01 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , false , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; List < String > list = ConfigurationLoader . getPropStartWithString ( "" ) ; assertEquals ( , list . size ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; } @ Test public void getNoEmptyList01 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , false , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; ConfigurationLoader . setProperty ( p ) ; List < String > list = new ArrayList < String > ( ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; list . add ( "" ) ; List < String > resultList = ConfigurationLoader . getExistValueList ( list ) ; assertEquals ( , resultList . size ( ) ) ; assertEquals ( "" , resultList . get ( ) ) ; assertEquals ( "" , resultList . get ( ) ) ; resultList = ConfigurationLoader . getExistValueList ( null ) ; assertEquals ( , resultList . size ( ) ) ; resultList = ConfigurationLoader . getExistValueList ( new ArrayList < String > ( ) ) ; assertEquals ( , resultList . size ( ) ) ; } @ Test public void loadJDBCProp01 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; try { ConfigurationLoader . loadJDBCProp ( "" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } assertEquals ( "" , ConfigurationLoader . getProperty ( "" ) ) ; assertEquals ( "" , ConfigurationLoader . getProperty ( "" ) ) ; assertEquals ( "" , ConfigurationLoader . getProperty ( "" ) ) ; assertEquals ( "" , ConfigurationLoader . getProperty ( "" ) ) ; assertEquals ( PATH_DB_PARAMETER , ConfigurationLoader . getProperty ( "" ) ) ; } @ Test public void loadJDBCProp02 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , true , false ) ; try { ConfigurationLoader . loadJDBCProp ( "" ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } @ Test public void loadJDBCProp03 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , false , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , PATH_DB_PARAMETER ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . loadJDBCProp ( "" ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } @ Test public void loadJDBCProp04 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , false , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , PATH_DB_PARAMETER ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . loadJDBCProp ( "" ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } @ Test public void loadJDBCProp05 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , false , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , PATH_DB_PARAMETER ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . loadJDBCProp ( "" ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } @ Test public void loadJDBCProp06 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , false , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , PATH_DB_PARAMETER ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . loadJDBCProp ( "" ) ; fail ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } @ Test public void loadJDBCProp07 ( ) throws Exception { ConfigurationLoader . init ( propertys_db , false , false ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , "" ) ; p . setProperty ( "" , PATH_DB_PARAMETER ) ; ConfigurationLoader . setProperty ( p ) ; try { ConfigurationLoader . loadJDBCProp ( "" ) ; } catch ( BulkLoaderSystemException e ) { LOG . info ( e . getCause ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; } } } package com . asakusafw . bulkloader . common ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import org . junit . Test ; public class StreamRedirectThreadTest { private static final byte [ ] BYTES = new byte [ ] ; static { for ( int i = ; i < BYTES . length ; i ++ ) { BYTES [ i ] = ( byte ) ( ( i > > ) ^ i ) ; } } private final TestInputStream in = new TestInputStream ( BYTES ) ; private final TestOutputStream out = new TestOutputStream ( ) ; @ Test ( timeout = ) public void redirect ( ) { StreamRedirectThread t = new StreamRedirectThread ( in , out ) ; t . run ( ) ; assertThat ( out . toByteArray ( ) , is ( BYTES ) ) ; assertThat ( in . read ( ) , is ( - ) ) ; assertThat ( in . closed , is ( false ) ) ; assertThat ( out . closed , is ( false ) ) ; } @ Test ( timeout = ) public void quietExitOnInputError ( ) throws Exception { StreamRedirectThread t = new StreamRedirectThread ( new ErroneousInputStream ( ) , out ) ; t . run ( ) ; } @ Test ( timeout = ) public void quietExitOnOutputError ( ) throws Exception { StreamRedirectThread t = new StreamRedirectThread ( in , new ErroneousOutputStream ( ) ) ; t . run ( ) ; assertThat ( "" , in . read ( ) , is ( - ) ) ; } @ Test ( timeout = ) public void consumeInputOnOutputError ( ) throws Exception { StreamRedirectThread t = new StreamRedirectThread ( in , new ErroneousOutputStream ( ) ) ; t . run ( ) ; assertThat ( "" , in . read ( ) , is ( - ) ) ; } @ Test ( timeout = ) public void closeInput ( ) { StreamRedirectThread t = new StreamRedirectThread ( in , out , true , false ) ; t . run ( ) ; assertThat ( out . toByteArray ( ) , is ( BYTES ) ) ; assertThat ( in . closed , is ( true ) ) ; assertThat ( out . closed , is ( false ) ) ; } @ Test ( timeout = ) public void closeOutput ( ) { StreamRedirectThread t = new StreamRedirectThread ( in , out , false , true ) ; t . run ( ) ; assertThat ( out . toByteArray ( ) , is ( BYTES ) ) ; assertThat ( in . closed , is ( false ) ) ; assertThat ( out . closed , is ( true ) ) ; } static class ErroneousInputStream extends InputStream { private volatile int rest ; ErroneousInputStream ( int rest ) { this . rest = rest ; } @ Override public int read ( ) throws IOException { if ( -- rest < ) { throw new IOException ( ) ; } return ; } } static class ErroneousOutputStream extends OutputStream { private volatile int rest ; ErroneousOutputStream ( int rest ) { this . rest = rest ; } @ Override public void write ( int b ) throws IOException { if ( -- rest < ) { throw new IOException ( ) ; } } } static class TestInputStream extends ByteArrayInputStream { boolean closed ; TestInputStream ( byte [ ] buf ) { super ( buf ) ; } @ Override public void close ( ) throws IOException { this . closed = true ; } } static class TestOutputStream extends ByteArrayOutputStream { boolean closed ; @ Override public void close ( ) throws IOException { this . closed = true ; } } } package com . asakusafw . bulkloader . transfer ; import java . util . Arrays ; import java . util . Collections ; import org . junit . Assume ; import org . junit . Test ; public class OpenSshFileListProviderTest { @ Test public void simple ( ) { try { OpenSshFileListProvider provider = new OpenSshFileListProvider ( "" , System . getProperty ( "" ) , "" , Arrays . asList ( "" , "" , "" ) , Collections . singletonMap ( "" , "" ) ) ; try { provider . discardWriter ( ) ; provider . discardReader ( ) ; provider . waitForComplete ( ) ; } finally { provider . close ( ) ; } } catch ( Exception e ) { Assume . assumeNoException ( e ) ; } } } package com . asakusafw . bulkloader . cache ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . net . URI ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collections ; import java . util . Date ; import java . util . List ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; public class DeleteCacheStorageRemoteTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private final DeleteCacheStorageRemote service = new DeleteCacheStorageRemote ( ) ; private final ByteArrayOutputStream writerBuffer = new ByteArrayOutputStream ( ) ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownEnv ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ SuppressWarnings ( "" ) @ Before public void setUp ( ) throws Exception { UnitTestUtil . startUp ( ) ; service . initialize ( "" , "" ) ; service . setConf ( new ConfigurationProvider ( ) . newInstance ( ) ) ; ConfigurationLoader . getProperty ( ) . setProperty ( Constants . PROP_KEY_BASE_PATH , folder . getRoot ( ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; } @ Test public void nothing ( ) throws Exception { FileList . Reader reader = prepare ( "" ) ; FileList . Writer writer = FileList . createWriter ( writerBuffer , false ) ; service . execute ( reader , writer ) ; writer . close ( ) ; List < FileProtocol > results = collect ( writerBuffer . toByteArray ( ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; } @ Test public void found ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; CacheStorage storage = new CacheStorage ( service . getConf ( ) , uri ( "" ) ) ; try { storage . putHeadCacheInfo ( info ) ; assertThat ( storage . getHeadCacheInfo ( ) , is ( notNullValue ( ) ) ) ; FileList . Reader reader = prepare ( "" ) ; FileList . Writer writer = FileList . createWriter ( writerBuffer , false ) ; service . execute ( reader , writer ) ; writer . close ( ) ; List < FileProtocol > results = collect ( writerBuffer . toByteArray ( ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_DELETED ) ) ; assertThat ( storage . getHeadCacheInfo ( ) , is ( nullValue ( ) ) ) ; } finally { storage . close ( ) ; } } @ Test public void mixed ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; CacheStorage storage = new CacheStorage ( service . getConf ( ) , uri ( "" ) ) ; try { storage . putHeadCacheInfo ( info ) ; assertThat ( storage . getHeadCacheInfo ( ) , is ( notNullValue ( ) ) ) ; FileList . Reader reader = prepare ( "" , "" , "" , "" ) ; FileList . Writer writer = FileList . createWriter ( writerBuffer , false ) ; service . execute ( reader , writer ) ; writer . close ( ) ; List < FileProtocol > results = collect ( writerBuffer . toByteArray ( ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_DELETED ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; assertThat ( storage . getHeadCacheInfo ( ) , is ( nullValue ( ) ) ) ; } finally { storage . close ( ) ; } } private URI uri ( String string ) { try { return FileNameUtil . createPath ( service . getConf ( ) , string , "" , "" ) . toUri ( ) ; } catch ( BulkLoaderSystemException e ) { throw new AssertionError ( e ) ; } } private FileList . Reader prepare ( String ... locations ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( output , false ) ; for ( String location : locations ) { writer . openNext ( new FileProtocol ( FileProtocol . Kind . DELETE_CACHE , location , null ) ) . close ( ) ; } writer . close ( ) ; return FileList . createReader ( new ByteArrayInputStream ( output . toByteArray ( ) ) ) ; } private List < FileProtocol > collect ( byte [ ] byteArray ) throws IOException { List < FileProtocol > results = new ArrayList < FileProtocol > ( ) ; ByteArrayInputStream input = new ByteArrayInputStream ( byteArray ) ; FileList . Reader reader = FileList . createReader ( input ) ; while ( reader . next ( ) ) { results . add ( reader . getCurrentProtocol ( ) ) ; reader . openContent ( ) . close ( ) ; } return results ; } private Calendar calendar ( String string ) { Date date ; try { date = new SimpleDateFormat ( "" ) . parse ( string ) ; } catch ( ParseException e ) { throw new AssertionError ( e ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( date ) ; return calendar ; } } package com . asakusafw . bulkloader . cache ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . PipedInputStream ; import java . io . PipedOutputStream ; import java . net . URI ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Collections ; import java . util . Date ; import java . util . HashMap ; import java . util . Map ; import java . util . concurrent . Callable ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import org . apache . commons . io . IOUtils ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileList . Reader ; import com . asakusafw . bulkloader . transfer . FileList . Writer ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . StreamFileListProvider ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; public class GetCacheInfoLocalTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; final GetCacheInfoRemote remote = new GetCacheInfoRemote ( ) ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownEnv ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ SuppressWarnings ( "" ) @ Before public void setUp ( ) throws Exception { UnitTestUtil . startUp ( ) ; remote . initialize ( "" , "" , "" , "" , "" ) ; remote . setConf ( new ConfigurationProvider ( ) . newInstance ( ) ) ; ConfigurationLoader . getProperty ( ) . setProperty ( Constants . PROP_KEY_BASE_PATH , folder . getRoot ( ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; } @ Test ( timeout = ) public void withoutCache ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > map = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table = new ImportTargetTableBean ( ) ; table . setDfsFilePath ( "" ) ; map . put ( "" , table ) ; bean . setTargetTable ( map ) ; GetCacheInfoLocal service = new Mock ( ) ; Map < String , CacheInfo > results = service . get ( bean ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test ( timeout = ) public void nothing ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > map = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table = new ImportTargetTableBean ( ) ; table . setDfsFilePath ( "" ) ; table . setCacheId ( "" ) ; map . put ( "" , table ) ; bean . setTargetTable ( map ) ; GetCacheInfoLocal service = new Mock ( ) ; Map < String , CacheInfo > results = service . get ( bean ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test ( timeout = ) public void found ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; CacheStorage storage = new CacheStorage ( remote . getConf ( ) , uri ( "" ) ) ; try { storage . putHeadCacheInfo ( info ) ; } finally { storage . close ( ) ; } ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > map = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table = new ImportTargetTableBean ( ) ; table . setDfsFilePath ( "" ) ; table . setCacheId ( "" ) ; map . put ( "" , table ) ; bean . setTargetTable ( map ) ; GetCacheInfoLocal service = new Mock ( ) ; Map < String , CacheInfo > results = service . get ( bean ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( "" ) , is ( info ) ) ; } @ Test ( timeout = ) public void mixed ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; CacheStorage storage = new CacheStorage ( remote . getConf ( ) , uri ( "" ) ) ; try { storage . putHeadCacheInfo ( info ) ; } finally { storage . close ( ) ; } ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > map = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table1 = new ImportTargetTableBean ( ) ; table1 . setDfsFilePath ( "" ) ; table1 . setCacheId ( "" ) ; map . put ( "" , table1 ) ; bean . setTargetTable ( map ) ; ImportTargetTableBean table2 = new ImportTargetTableBean ( ) ; table2 . setDfsFilePath ( "" ) ; table2 . setCacheId ( "" ) ; map . put ( "" , table2 ) ; bean . setTargetTable ( map ) ; ImportTargetTableBean table3 = new ImportTargetTableBean ( ) ; table3 . setDfsFilePath ( "" ) ; table3 . setCacheId ( "" ) ; map . put ( "" , table3 ) ; bean . setTargetTable ( map ) ; ImportTargetTableBean table4 = new ImportTargetTableBean ( ) ; table4 . setDfsFilePath ( "" ) ; map . put ( "" , table4 ) ; bean . setTargetTable ( map ) ; GetCacheInfoLocal service = new Mock ( ) ; Map < String , CacheInfo > results = service . get ( bean ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( "" ) , is ( info ) ) ; } private ImportBean createBean ( ) { ImportBean bean = new ImportBean ( ) ; bean . setTargetName ( "" ) ; bean . setBatchId ( "" ) ; bean . setJobflowId ( "" ) ; bean . setExecutionId ( "" ) ; return bean ; } @ Test ( timeout = ) public void fail ( ) throws Exception { ImportBean bean = createBean ( ) ; Map < String , ImportTargetTableBean > map = new HashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean table = new ImportTargetTableBean ( ) ; table . setDfsFilePath ( "" ) ; table . setCacheId ( "" ) ; map . put ( "" , table ) ; bean . setTargetTable ( map ) ; GetCacheInfoLocal service = new Mock ( ) . willFail ( ) ; try { service . get ( bean ) ; org . junit . Assert . fail ( ) ; } catch ( Exception e ) { } } private URI uri ( String string ) { try { return FileNameUtil . createPath ( remote . getConf ( ) , string , "" , "" ) . toUri ( ) ; } catch ( BulkLoaderSystemException e ) { throw new AssertionError ( e ) ; } } private Calendar calendar ( String string ) { Date date ; try { date = new SimpleDateFormat ( "" ) . parse ( string ) ; } catch ( ParseException e ) { throw new AssertionError ( e ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( date ) ; return calendar ; } class Mock extends GetCacheInfoLocal { boolean fail = false ; Mock willFail ( ) { fail = true ; return this ; } @ Override protected FileListProvider openFileList ( String targetName , String batchId , String jobflowId , String executionId ) throws IOException { final PipedInputStream remoteStdin = new PipedInputStream ( ) ; final PipedOutputStream remoteStdout = new PipedOutputStream ( ) ; final PipedOutputStream upstream = new PipedOutputStream ( remoteStdin ) ; final PipedInputStream downstream = new PipedInputStream ( remoteStdout ) ; final Future < Void > future = Executors . newFixedThreadPool ( ) . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { Writer writer = FileList . createWriter ( remoteStdout , false ) ; Reader reader = FileList . createReader ( remoteStdin ) ; try { remote . execute ( reader , writer ) ; } finally { IOUtils . closeQuietly ( writer ) ; IOUtils . closeQuietly ( reader ) ; } return null ; } } ) ; return new StreamFileListProvider ( ) { @ Override protected OutputStream getOutputStream ( ) throws IOException { return upstream ; } @ Override protected InputStream getInputStream ( ) throws IOException { return downstream ; } @ Override protected void waitForDone ( ) throws IOException , InterruptedException { try { future . get ( ) ; } catch ( Exception e ) { throw new AssertionError ( e . getCause ( ) ) ; } if ( fail ) { throw new IOException ( ) ; } } @ Override public void close ( ) throws IOException { remoteStdin . close ( ) ; remoteStdout . close ( ) ; } } ; } } } package com . asakusafw . bulkloader . cache ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collection ; import java . util . Collections ; import java . util . Date ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . ProcessFileListProvider ; import com . asakusafw . runtime . configuration . FrameworkDeployer ; import com . asakusafw . runtime . configuration . HadoopEnvironmentChecker ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; import com . asakusafw . thundergate . runtime . cache . mapreduce . CacheBuildClient ; public class CacheBuildTest { @ Rule public HadoopEnvironmentChecker check = new HadoopEnvironmentChecker ( false ) ; @ Rule public final FrameworkDeployer framework = new FrameworkDeployer ( ) { @ Override protected void deploy ( ) throws IOException { deployLibrary ( CacheInfo . class , "" ) ; } } ; @ Before public void setUp ( ) throws Exception { URI uri = getTargetUri ( ) ; FileSystem fs = FileSystem . get ( uri , getConfiguration ( ) ) ; fs . delete ( new Path ( uri ) , true ) ; } @ Test public void create ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; framework . deployLibrary ( TestDataModel . class , "" ) ; CacheStorage storage = new CacheStorage ( getConfiguration ( ) , getTargetUri ( ) ) ; try { storage . putPatchCacheInfo ( info ) ; ModelOutput < TestDataModel > output = create ( storage , storage . getPatchContents ( "" ) ) ; try { TestDataModel model = new TestDataModel ( ) ; model . systemId . set ( ) ; model . value . set ( "" ) ; model . deleted . set ( false ) ; output . write ( model ) ; } finally { output . close ( ) ; } execute ( CacheBuildClient . SUBCOMMAND_CREATE ) ; assertThat ( storage . getHeadCacheInfo ( ) , is ( info ) ) ; List < TestDataModel > results = collect ( storage , storage . getHeadContents ( "" ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; } finally { storage . close ( ) ; } } @ Test public void create_deleted ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; framework . deployLibrary ( TestDataModel . class , "" ) ; CacheStorage storage = new CacheStorage ( getConfiguration ( ) , getTargetUri ( ) ) ; try { storage . putPatchCacheInfo ( info ) ; ModelOutput < TestDataModel > output = create ( storage , storage . getPatchContents ( "" ) ) ; try { TestDataModel model = new TestDataModel ( ) ; for ( int i = ; i < ; i ++ ) { model . systemId . set ( i ) ; model . deleted . set ( i % != ) ; output . write ( model ) ; } } finally { output . close ( ) ; } execute ( CacheBuildClient . SUBCOMMAND_CREATE ) ; assertThat ( storage . getHeadCacheInfo ( ) , is ( info ) ) ; List < TestDataModel > results = collect ( storage , storage . getHeadContents ( "" ) ) ; assertThat ( results . size ( ) , is ( ) ) ; for ( int i = ; i < ; i ++ ) { assertThat ( results . get ( i ) . systemId . get ( ) , is ( i * ) ) ; } } finally { storage . close ( ) ; } } @ Test public void update ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; framework . deployLibrary ( TestDataModel . class , "" ) ; CacheStorage storage = new CacheStorage ( getConfiguration ( ) , getTargetUri ( ) ) ; try { storage . putPatchCacheInfo ( info ) ; ModelOutput < TestDataModel > head = create ( storage , storage . getHeadContents ( "" ) ) ; try { TestDataModel model = new TestDataModel ( ) ; model . systemId . set ( ) ; model . value . set ( "" ) ; model . deleted . set ( false ) ; head . write ( model ) ; model . systemId . set ( ) ; model . value . set ( "" ) ; model . deleted . set ( false ) ; head . write ( model ) ; } finally { head . close ( ) ; } ModelOutput < TestDataModel > patch = create ( storage , storage . getPatchContents ( "" ) ) ; try { TestDataModel model = new TestDataModel ( ) ; model . systemId . set ( ) ; model . value . set ( "" ) ; model . deleted . set ( false ) ; patch . write ( model ) ; model . systemId . set ( ) ; model . value . set ( "" ) ; model . deleted . set ( false ) ; patch . write ( model ) ; } finally { patch . close ( ) ; } execute ( CacheBuildClient . SUBCOMMAND_UPDATE ) ; assertThat ( storage . getHeadCacheInfo ( ) , is ( info ) ) ; List < TestDataModel > results = collect ( storage , storage . getHeadContents ( "" ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; } finally { storage . close ( ) ; } } @ Test public void update_delete ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; framework . deployLibrary ( TestDataModel . class , "" ) ; CacheStorage storage = new CacheStorage ( getConfiguration ( ) , getTargetUri ( ) ) ; try { storage . putPatchCacheInfo ( info ) ; ModelOutput < TestDataModel > head = create ( storage , storage . getHeadContents ( "" ) ) ; try { TestDataModel model = new TestDataModel ( ) ; for ( int i = ; i < ; i ++ ) { model . systemId . set ( i ) ; model . value . set ( "" ) ; model . deleted . set ( false ) ; head . write ( model ) ; } } finally { head . close ( ) ; } ModelOutput < TestDataModel > patch = create ( storage , storage . getPatchContents ( "" ) ) ; try { TestDataModel model = new TestDataModel ( ) ; for ( int i = ; i < ; i += ) { model . systemId . set ( i ) ; model . value . set ( "" ) ; model . deleted . set ( i % == ) ; patch . write ( model ) ; } } finally { patch . close ( ) ; } execute ( CacheBuildClient . SUBCOMMAND_UPDATE ) ; assertThat ( storage . getHeadCacheInfo ( ) , is ( info ) ) ; List < TestDataModel > results = collect ( storage , storage . getHeadContents ( "" ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . systemId . get ( ) , is ( ) ) ; assertThat ( results . get ( ) . value . toString ( ) , is ( "" ) ) ; } finally { storage . close ( ) ; } } private void execute ( String subcommand ) throws IOException , InterruptedException { FileListProvider provider = execute ( Constants . PATH_REMOTE_ROOT + Constants . PATH_LOCAL_CACHE_BUILD , subcommand , "" , "" , "" , getTargetUri ( ) . toString ( ) , TestDataModel . class . getName ( ) ) ; try { provider . discardReader ( ) ; provider . discardWriter ( ) ; provider . waitForComplete ( ) ; } finally { provider . close ( ) ; } } private FileListProvider execute ( String scriptPath , String ... arguments ) throws IOException { List < String > command = new ArrayList < String > ( ) ; command . add ( new File ( framework . getHome ( ) , scriptPath ) . getAbsolutePath ( ) ) ; Collections . addAll ( command , arguments ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . put ( "" , framework . getHome ( ) . getAbsolutePath ( ) ) ; return new ProcessFileListProvider ( command , env ) ; } private URI getTargetUri ( ) { try { return FileNameUtil . createPath ( getConfiguration ( ) , "" + getClass ( ) . getSimpleName ( ) , "" , "" ) . toUri ( ) ; } catch ( BulkLoaderSystemException e ) { throw new AssertionError ( e ) ; } } private Configuration getConfiguration ( ) { return new ConfigurationProvider ( ) . newInstance ( ) ; } private List < TestDataModel > collect ( CacheStorage storage , Path contents ) throws IOException { List < TestDataModel > results = new ArrayList < TestDataModel > ( ) ; FileSystem fs = storage . getFileSystem ( ) ; for ( FileStatus status : fs . globStatus ( contents ) ) { results . addAll ( collectContent ( fs , status ) ) ; } Collections . sort ( results ) ; return results ; } private Collection < TestDataModel > collectContent ( FileSystem fs , FileStatus status ) throws IOException { Collection < TestDataModel > results = new ArrayList < TestDataModel > ( ) ; ModelInput < TestDataModel > input = TemporaryStorage . openInput ( fs . getConf ( ) , TestDataModel . class , status . getPath ( ) ) ; try { TestDataModel model = new TestDataModel ( ) ; while ( input . readTo ( model ) ) { results . add ( model . copy ( ) ) ; } } finally { input . close ( ) ; } return results ; } private ModelOutput < TestDataModel > create ( CacheStorage storage , Path path ) throws IOException { return TemporaryStorage . openOutput ( storage . getFileSystem ( ) . getConf ( ) , TestDataModel . class , path ) ; } private Calendar calendar ( String string ) { Date date ; try { date = new SimpleDateFormat ( "" ) . parse ( string ) ; } catch ( ParseException e ) { throw new AssertionError ( e ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( date ) ; return calendar ; } } package com . asakusafw . bulkloader . cache ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . PipedInputStream ; import java . io . PipedOutputStream ; import java . net . URI ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import java . util . concurrent . Callable ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import org . apache . commons . io . IOUtils ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileList . Reader ; import com . asakusafw . bulkloader . transfer . FileList . Writer ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . FileProtocol . Kind ; import com . asakusafw . bulkloader . transfer . StreamFileListProvider ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; public class DeleteCacheStorageLocalTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; final DeleteCacheStorageRemote remote = new DeleteCacheStorageRemote ( ) ; LocalCacheInfo info1 , info2 , info3 ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownEnv ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ SuppressWarnings ( "" ) @ Before public void setUp ( ) throws Exception { UnitTestUtil . startUp ( ) ; remote . initialize ( "" , "" ) ; remote . setConf ( new ConfigurationProvider ( ) . newInstance ( ) ) ; ConfigurationLoader . getProperty ( ) . setProperty ( Constants . PROP_KEY_BASE_PATH , folder . getRoot ( ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; info1 = new LocalCacheInfo ( "" , null , null , "" , "" ) ; info2 = new LocalCacheInfo ( "" , null , null , "" , "" ) ; info3 = new LocalCacheInfo ( "" , null , null , "" , "" ) ; } @ Test ( timeout = ) public void nothing ( ) throws Exception { List < LocalCacheInfo > list = new ArrayList < LocalCacheInfo > ( ) ; Map < String , Kind > results = new Mock ( ) . delete ( list , "" ) ; assertThat ( results . size ( ) , is ( ) ) ; } @ Test ( timeout = ) public void delete ( ) throws Exception { prepare ( info1 ) ; List < LocalCacheInfo > list = new ArrayList < LocalCacheInfo > ( ) ; list . add ( info1 ) ; Map < String , Kind > results = new Mock ( ) . delete ( list , "" ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( info1 . getPath ( ) ) , is ( Kind . RESPONSE_DELETED ) ) ; } @ Test ( timeout = ) public void delete_missing ( ) throws Exception { List < LocalCacheInfo > list = new ArrayList < LocalCacheInfo > ( ) ; list . add ( info1 ) ; Map < String , Kind > results = new Mock ( ) . delete ( list , "" ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( info1 . getPath ( ) ) , is ( Kind . RESPONSE_NOT_FOUND ) ) ; } @ Test ( timeout = ) public void delete_multiple ( ) throws Exception { prepare ( info1 , info3 ) ; List < LocalCacheInfo > list = new ArrayList < LocalCacheInfo > ( ) ; list . add ( info1 ) ; list . add ( info2 ) ; list . add ( info3 ) ; Map < String , Kind > results = new Mock ( ) . delete ( list , "" ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( info1 . getPath ( ) ) , is ( Kind . RESPONSE_DELETED ) ) ; assertThat ( results . get ( info2 . getPath ( ) ) , is ( Kind . RESPONSE_NOT_FOUND ) ) ; assertThat ( results . get ( info3 . getPath ( ) ) , is ( Kind . RESPONSE_DELETED ) ) ; } private void prepare ( LocalCacheInfo ... caches ) throws IOException { for ( LocalCacheInfo info : caches ) { CacheStorage storage = new CacheStorage ( remote . getConf ( ) , uri ( info . getId ( ) ) ) ; try { storage . getFileSystem ( ) . create ( storage . getHeadContents ( "" ) ) . close ( ) ; } finally { storage . close ( ) ; } } } private URI uri ( String string ) { try { return FileNameUtil . createPath ( remote . getConf ( ) , string , "" , "" ) . toUri ( ) ; } catch ( BulkLoaderSystemException e ) { throw new AssertionError ( e ) ; } } class Mock extends DeleteCacheStorageLocal { boolean fail = false ; Mock willFail ( ) { fail = true ; return this ; } @ Override protected FileListProvider openFileList ( String targetName ) throws IOException { final PipedInputStream remoteStdin = new PipedInputStream ( ) ; final PipedOutputStream remoteStdout = new PipedOutputStream ( ) ; final PipedOutputStream upstream = new PipedOutputStream ( remoteStdin ) ; final PipedInputStream downstream = new PipedInputStream ( remoteStdout ) ; final Future < Void > future = Executors . newFixedThreadPool ( ) . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { Writer writer = FileList . createWriter ( remoteStdout , false ) ; Reader reader = FileList . createReader ( remoteStdin ) ; try { remote . execute ( reader , writer ) ; } finally { IOUtils . closeQuietly ( writer ) ; IOUtils . closeQuietly ( reader ) ; } return null ; } } ) ; return new StreamFileListProvider ( ) { @ Override protected OutputStream getOutputStream ( ) throws IOException { return upstream ; } @ Override protected InputStream getInputStream ( ) throws IOException { return downstream ; } @ Override protected void waitForDone ( ) throws IOException , InterruptedException { try { future . get ( ) ; } catch ( Exception e ) { throw new AssertionError ( e . getCause ( ) ) ; } if ( fail ) { throw new IOException ( ) ; } } @ Override public void close ( ) throws IOException { remoteStdin . close ( ) ; remoteStdout . close ( ) ; } } ; } } } package com . asakusafw . bulkloader . cache ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . sql . Connection ; import java . sql . Statement ; import java . util . Arrays ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . bulkloader . transfer . FileProtocol . Kind ; public class GcCacheStorageTest { private static List < String > properties = Arrays . asList ( new String [ ] { "" } ) ; private static String testJobflowId = "" ; private static String testExecutionId = "" ; static final LocalCacheInfo INFO1 = new LocalCacheInfo ( "" , null , null , "" , "" ) ; static final LocalCacheInfo INFO2 = new LocalCacheInfo ( "" , null , null , "" , "" ) ; static final LocalCacheInfo INFO3 = new LocalCacheInfo ( "" , null , null , "" , "" ) ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownEnv ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( testJobflowId , testExecutionId , properties , "" ) ; UnitTestUtil . setUpDB ( ) ; UnitTestUtil . startUp ( ) ; Connection connection = DBConnection . getConnection ( ) ; Statement statement = null ; try { statement = connection . createStatement ( ) ; statement . execute ( "" ) ; statement . execute ( "" ) ; LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . putCacheInfo ( INFO1 ) ; repo . putCacheInfo ( INFO2 ) ; repo . putCacheInfo ( INFO3 ) ; } finally { DBConnection . closeStmt ( statement ) ; DBConnection . closeConn ( connection ) ; } } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void empty ( ) throws Exception { int code = new Mock ( ) . execute ( "" , testExecutionId ) ; assertThat ( code , is ( Constants . EXIT_CODE_SUCCESS ) ) ; } @ Test public void delete ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . deleteCacheInfo ( INFO1 . getId ( ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; int code = new Mock ( ) . put ( INFO1 , Kind . RESPONSE_DELETED ) . execute ( "" , testExecutionId ) ; assertThat ( code , is ( Constants . EXIT_CODE_SUCCESS ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_already ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . deleteCacheInfo ( INFO1 . getId ( ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; int code = new Mock ( ) . put ( INFO1 , Kind . RESPONSE_NOT_FOUND ) . execute ( "" , testExecutionId ) ; assertThat ( code , is ( Constants . EXIT_CODE_SUCCESS ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_error ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . deleteCacheInfo ( INFO1 . getId ( ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; int code = new Mock ( ) . put ( INFO1 , Kind . RESPONSE_ERROR ) . execute ( "" , testExecutionId ) ; assertThat ( code , not ( Constants . EXIT_CODE_SUCCESS ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_omitted ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . deleteCacheInfo ( INFO1 . getId ( ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; int code = new Mock ( ) . execute ( "" , testExecutionId ) ; assertThat ( code , not ( Constants . EXIT_CODE_SUCCESS ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_locked ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . tryLock ( testExecutionId + "" , INFO1 . getId ( ) , INFO1 . getTableName ( ) ) ; repo . deleteCacheInfo ( INFO1 . getId ( ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; int code = new Mock ( ) . put ( INFO1 , Kind . RESPONSE_DELETED ) . execute ( "" , testExecutionId ) ; assertThat ( code , not ( Constants . EXIT_CODE_SUCCESS ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_mixed ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . deleteCacheInfo ( INFO1 . getId ( ) ) ; repo . deleteCacheInfo ( INFO2 . getId ( ) ) ; repo . deleteCacheInfo ( INFO3 . getId ( ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; int code = new Mock ( ) . put ( INFO1 , Kind . RESPONSE_DELETED ) . put ( INFO2 , Kind . RESPONSE_NOT_FOUND ) . put ( INFO3 , Kind . RESPONSE_ERROR ) . execute ( "" , testExecutionId ) ; assertThat ( code , not ( Constants . EXIT_CODE_SUCCESS ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_crash ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . deleteCacheInfo ( INFO1 . getId ( ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; int code = new Mock ( ) { @ Override protected DeleteCacheStorageLocal getClient ( ) { return new DeleteCacheStorageLocal ( ) { @ Override public Map < String , Kind > delete ( List < LocalCacheInfo > list , String targetName ) throws BulkLoaderSystemException { throw new BulkLoaderSystemException ( getClass ( ) , "" , "" ) ; } } ; } } . execute ( "" , testExecutionId ) ; assertThat ( code , is ( Constants . EXIT_CODE_ERROR ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } static class Mock extends GcCacheStorage { final Map < String , FileProtocol . Kind > results = new LinkedHashMap < String , FileProtocol . Kind > ( ) ; Mock put ( LocalCacheInfo info , FileProtocol . Kind kind ) { results . put ( info . getPath ( ) , kind ) ; return this ; } @ Override protected DeleteCacheStorageLocal getClient ( ) { return new DeleteCacheStorageLocal ( ) { @ Override public Map < String , Kind > delete ( List < LocalCacheInfo > list , String targetName ) throws BulkLoaderSystemException { return results ; } } ; } } } package com . asakusafw . bulkloader . cache ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . BooleanWritable ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . VLongWritable ; import org . apache . hadoop . io . Writable ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class TestDataModel implements Writable , ThunderGateCacheSupport , Comparable < TestDataModel > { public final VLongWritable systemId = new VLongWritable ( ) ; public final Text value = new Text ( ) ; public final BooleanWritable deleted = new BooleanWritable ( ) ; public TestDataModel copy ( ) { TestDataModel copy = new TestDataModel ( ) ; copy . systemId . set ( systemId . get ( ) ) ; copy . value . set ( value ) ; copy . deleted . set ( deleted . get ( ) ) ; return copy ; } @ Override public long __tgc__DataModelVersion ( ) { return ; } @ Override public String __tgc__TimestampColumn ( ) { return "" ; } @ Override public long __tgc__SystemId ( ) { return systemId . get ( ) ; } @ Override public boolean __tgc__Deleted ( ) { return deleted . get ( ) ; } @ Override public void write ( DataOutput out ) throws IOException { systemId . write ( out ) ; value . write ( out ) ; deleted . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { systemId . readFields ( in ) ; value . readFields ( in ) ; deleted . readFields ( in ) ; } @ Override public int compareTo ( TestDataModel o ) { return systemId . compareTo ( o . systemId ) ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( systemId ) ; builder . append ( "" ) ; builder . append ( value ) ; builder . append ( "" ) ; builder . append ( deleted ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . bulkloader . cache ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . net . URI ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collections ; import java . util . Date ; import java . util . List ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; public class GetCacheInfoRemoteTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private final GetCacheInfoRemote service = new GetCacheInfoRemote ( ) ; private final ByteArrayOutputStream writerBuffer = new ByteArrayOutputStream ( ) ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownEnv ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ SuppressWarnings ( "" ) @ Before public void setUp ( ) throws Exception { UnitTestUtil . startUp ( ) ; service . initialize ( "" , "" , "" , "" , "" ) ; service . setConf ( new ConfigurationProvider ( ) . newInstance ( ) ) ; ConfigurationLoader . getProperty ( ) . setProperty ( Constants . PROP_KEY_BASE_PATH , folder . getRoot ( ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; } @ Test public void nothing ( ) throws Exception { FileList . Reader reader = prepare ( "" ) ; FileList . Writer writer = FileList . createWriter ( writerBuffer , false ) ; service . execute ( reader , writer ) ; writer . close ( ) ; List < FileProtocol > results = collect ( writerBuffer . toByteArray ( ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; } @ Test public void found ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; CacheStorage storage = new CacheStorage ( service . getConf ( ) , uri ( "" ) ) ; try { storage . putHeadCacheInfo ( info ) ; } finally { storage . close ( ) ; } FileList . Reader reader = prepare ( "" ) ; FileList . Writer writer = FileList . createWriter ( writerBuffer , false ) ; service . execute ( reader , writer ) ; writer . close ( ) ; List < FileProtocol > results = collect ( writerBuffer . toByteArray ( ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_CACHE_INFO ) ) ; assertThat ( results . get ( ) . getInfo ( ) , is ( info ) ) ; } @ Test public void mixed ( ) throws Exception { CacheInfo info = new CacheInfo ( "" , "" , calendar ( "" ) , "" , Collections . singleton ( "" ) , "" , ) ; CacheStorage storage = new CacheStorage ( service . getConf ( ) , uri ( "" ) ) ; try { storage . putHeadCacheInfo ( info ) ; } finally { storage . close ( ) ; } FileList . Reader reader = prepare ( "" , "" , "" , "" ) ; FileList . Writer writer = FileList . createWriter ( writerBuffer , false ) ; service . execute ( reader , writer ) ; writer . close ( ) ; List < FileProtocol > results = collect ( writerBuffer . toByteArray ( ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_CACHE_INFO ) ) ; assertThat ( results . get ( ) . getInfo ( ) , is ( info ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; } @ Test public void broken ( ) throws Exception { CacheStorage storage = new CacheStorage ( service . getConf ( ) , uri ( "" ) ) ; try { FSDataOutputStream file = storage . getFileSystem ( ) . create ( storage . getHeadProperties ( ) ) ; file . close ( ) ; } finally { storage . close ( ) ; } FileList . Reader reader = prepare ( "" ) ; FileList . Writer writer = FileList . createWriter ( writerBuffer , false ) ; service . execute ( reader , writer ) ; writer . close ( ) ; List < FileProtocol > results = collect ( writerBuffer . toByteArray ( ) ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getLocation ( ) , endsWith ( "" ) ) ; assertThat ( results . get ( ) . getKind ( ) , is ( FileProtocol . Kind . RESPONSE_NOT_FOUND ) ) ; } private URI uri ( String string ) { try { return FileNameUtil . createPath ( service . getConf ( ) , string , "" , "" ) . toUri ( ) ; } catch ( BulkLoaderSystemException e ) { throw new AssertionError ( e ) ; } } private FileList . Reader prepare ( String ... locations ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( output , false ) ; for ( String location : locations ) { writer . openNext ( new FileProtocol ( FileProtocol . Kind . GET_CACHE_INFO , location , null ) ) . close ( ) ; } writer . close ( ) ; return FileList . createReader ( new ByteArrayInputStream ( output . toByteArray ( ) ) ) ; } private List < FileProtocol > collect ( byte [ ] byteArray ) throws IOException { List < FileProtocol > results = new ArrayList < FileProtocol > ( ) ; ByteArrayInputStream input = new ByteArrayInputStream ( byteArray ) ; FileList . Reader reader = FileList . createReader ( input ) ; while ( reader . next ( ) ) { results . add ( reader . getCurrentProtocol ( ) ) ; reader . openContent ( ) . close ( ) ; } return results ; } private Calendar calendar ( String string ) { Date date ; try { date = new SimpleDateFormat ( "" ) . parse ( string ) ; } catch ( ParseException e ) { throw new AssertionError ( e ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( date ) ; return calendar ; } } package com . asakusafw . bulkloader . cache ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . sql . Connection ; import java . sql . ResultSet ; import java . sql . Statement ; import java . sql . Timestamp ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Arrays ; import java . util . Calendar ; import java . util . Date ; import java . util . List ; import java . util . concurrent . Callable ; import java . util . concurrent . CountDownLatch ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class LocalCacheInfoRepositoryTest { private static List < String > properties = Arrays . asList ( new String [ ] { "" } ) ; private static String testJobflowId = "" ; private static String testExecutionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownEnv ( ) ; UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { BulkLoaderInitializer . initDBServer ( testJobflowId , testExecutionId , properties , "" ) ; UnitTestUtil . setUpDB ( ) ; UnitTestUtil . startUp ( ) ; Connection connection = DBConnection . getConnection ( ) ; Statement statement = null ; try { statement = connection . createStatement ( ) ; statement . execute ( "" ) ; statement . execute ( "" ) ; statement . execute ( "" ) ; statement . execute ( "" ) ; } finally { DBConnection . closeStmt ( statement ) ; DBConnection . closeConn ( connection ) ; } } @ After public void tearDown ( ) throws Exception { new ReleaseCacheLock ( ) . execute ( "" , testExecutionId ) ; UnitTestUtil . tearDown ( ) ; } @ Test public void create ( ) throws Exception { LocalCacheInfo info = new LocalCacheInfo ( "" , null , null , "" , "" ) ; Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . putCacheInfo ( info ) ; LocalCacheInfo restored = repo . getCacheInfo ( "" ) ; assertThat ( restored . getId ( ) , is ( info . getId ( ) ) ) ; assertThat ( restored . getLocalTimestamp ( ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( restored . getRemoteTimestamp ( ) , is ( nullValue ( ) ) ) ; assertThat ( restored . getTableName ( ) , is ( info . getTableName ( ) ) ) ; assertThat ( restored . getPath ( ) , is ( info . getPath ( ) ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void create_duplicated ( ) throws Exception { LocalCacheInfo info1 = new LocalCacheInfo ( "" , null , null , "" , "" ) ; LocalCacheInfo info2 = new LocalCacheInfo ( "" , null , calendar ( "" ) , "" , "" ) ; Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . putCacheInfo ( info1 ) ; Calendar timestamp = repo . putCacheInfo ( info2 ) ; LocalCacheInfo restored = repo . getCacheInfo ( "" ) ; assertThat ( restored . getId ( ) , is ( info2 . getId ( ) ) ) ; assertThat ( restored . getLocalTimestamp ( ) , is ( timestamp ) ) ; assertThat ( restored . getRemoteTimestamp ( ) , is ( info2 . getRemoteTimestamp ( ) ) ) ; assertThat ( restored . getTableName ( ) , is ( info2 . getTableName ( ) ) ) ; assertThat ( restored . getPath ( ) , is ( info2 . getPath ( ) ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void put_with_blocking ( ) throws Exception { LocalCacheInfo info = new LocalCacheInfo ( "" , calendar ( "" ) , calendar ( "" ) , "" , "" ) ; Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; final CountDownLatch latch = new CountDownLatch ( ) ; Future < Calendar > future = Executors . newFixedThreadPool ( ) . submit ( new Callable < Calendar > ( ) { @ Override public Calendar call ( ) throws Exception { Connection inner = DBConnection . getConnection ( ) ; Statement statement = null ; ResultSet rs = null ; try { statement = inner . createStatement ( ) ; statement . execute ( "" ) ; latch . countDown ( ) ; System . out . println ( "" ) ; Thread . sleep ( ) ; rs = statement . executeQuery ( "" ) ; assertThat ( rs . next ( ) , is ( true ) ) ; Timestamp timestamp = rs . getTimestamp ( ) ; DBConnection . closeRs ( rs ) ; statement . execute ( "" ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( timestamp ) ; return calendar ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closeStmt ( statement ) ; DBConnection . closeConn ( inner ) ; } } } ) ; latch . await ( ) ; Calendar updated = repo . putCacheInfo ( info ) ; assertThat ( tos ( updated ) + "" + tos ( future . get ( ) ) , updated , greaterThanOrEqualTo ( future . get ( ) ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void update_with_blocking_other ( ) throws Exception { LocalCacheInfo info = new LocalCacheInfo ( "" , calendar ( "" ) , calendar ( "" ) , "" , "" ) ; Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; final CountDownLatch latch = new CountDownLatch ( ) ; Future < Calendar > future = Executors . newFixedThreadPool ( ) . submit ( new Callable < Calendar > ( ) { @ Override public Calendar call ( ) throws Exception { Connection inner = DBConnection . getConnection ( ) ; Statement statement = null ; ResultSet rs = null ; try { statement = inner . createStatement ( ) ; statement . execute ( "" ) ; latch . countDown ( ) ; System . out . println ( "" ) ; Thread . sleep ( ) ; rs = statement . executeQuery ( "" ) ; assertThat ( rs . next ( ) , is ( true ) ) ; Timestamp timestamp = rs . getTimestamp ( ) ; DBConnection . closeRs ( rs ) ; statement . execute ( "" ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( timestamp ) ; return calendar ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closeStmt ( statement ) ; DBConnection . closeConn ( inner ) ; } } } ) ; latch . await ( ) ; Calendar updated = repo . putCacheInfo ( info ) ; assertThat ( tos ( updated ) + "" + tos ( future . get ( ) ) , updated , lessThanOrEqualTo ( future . get ( ) ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete ( ) throws Exception { LocalCacheInfo info = new LocalCacheInfo ( "" , calendar ( "" ) , calendar ( "" ) , "" , "" ) ; Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . putCacheInfo ( info ) ; assertThat ( repo . deleteCacheInfo ( "" ) , is ( true ) ) ; LocalCacheInfo restored = repo . getCacheInfo ( "" ) ; assertThat ( restored , is ( nullValue ( ) ) ) ; assertThat ( repo . deleteCacheInfo ( "" ) , is ( false ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_missing ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; assertThat ( repo . deleteCacheInfo ( "" ) , is ( false ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_table ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; assertThat ( repo . deleteTableCacheInfo ( "" ) , is ( ) ) ; assertThat ( repo . getCacheInfo ( "" ) , is ( nullValue ( ) ) ) ; assertThat ( repo . getCacheInfo ( "" ) , is ( nullValue ( ) ) ) ; assertThat ( repo . getCacheInfo ( "" ) , is ( notNullValue ( ) ) ) ; assertThat ( repo . getCacheInfo ( "" ) , is ( notNullValue ( ) ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_table_nothing ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; assertThat ( repo . deleteTableCacheInfo ( "" ) , is ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void delete_all ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; repo . putCacheInfo ( info ( "" , "" ) ) ; repo . deleteAllCacheInfo ( ) ; assertThat ( repo . getCacheInfo ( "" ) , is ( nullValue ( ) ) ) ; assertThat ( repo . getCacheInfo ( "" ) , is ( nullValue ( ) ) ) ; assertThat ( repo . getCacheInfo ( "" ) , is ( nullValue ( ) ) ) ; assertThat ( repo . getCacheInfo ( "" ) , is ( nullValue ( ) ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void listDeleted ( ) throws Exception { LocalCacheInfo info = new LocalCacheInfo ( "" , calendar ( "" ) , calendar ( "" ) , "" , "" ) ; Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; repo . putCacheInfo ( info ) ; assertThat ( repo . deleteCacheInfo ( "" ) , is ( true ) ) ; List < LocalCacheInfo > deleted = repo . listDeletedCacheInfo ( ) ; assertThat ( deleted . size ( ) , is ( ) ) ; LocalCacheInfo restored = deleted . get ( ) ; assertThat ( restored . getId ( ) , is ( info . getId ( ) ) ) ; assertThat ( restored . getTableName ( ) , is ( info . getTableName ( ) ) ) ; assertThat ( restored . getPath ( ) , is ( info . getPath ( ) ) ) ; assertThat ( repo . deleteCacheInfoCompletely ( "" ) , is ( true ) ) ; assertThat ( repo . listDeletedCacheInfo ( ) . size ( ) , is ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } private LocalCacheInfo info ( String id , String tableName ) { LocalCacheInfo info = new LocalCacheInfo ( id , calendar ( "" ) , calendar ( "" ) , tableName , "" ) ; return info ; } @ Test public void tryLock ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( false ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void releaseLock ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; repo . releaseLock ( "" ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( false ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } @ Test public void releaseAllLock ( ) throws Exception { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; repo . releaseAllLock ( ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; assertThat ( repo . tryLock ( "" , "" , "" ) , is ( true ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } private String tos ( Calendar calendar ) { return new SimpleDateFormat ( "" ) . format ( calendar . getTime ( ) ) ; } private Calendar calendar ( String string ) { Date date ; try { date = new SimpleDateFormat ( "" ) . parse ( string ) ; } catch ( ParseException e ) { throw new AssertionError ( e ) ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( date ) ; return calendar ; } } package com . asakusafw . bulkloader . extractor ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . util . Properties ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; public class ExtractorTest { @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { } @ After public void tearDown ( ) throws Exception { } @ Test public void executeTest01 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Extractor extractor = new StubExtractor ( ) ; int result = extractor . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest02 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Extractor extractor = new StubExtractor ( ) { @ Override protected DfsFileImport createDfsFileImport ( ) { return new StubHdfsFileImport ( false ) ; } } ; int result = extractor . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest03 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; Extractor extractor = new StubExtractor ( ) ; int result = extractor . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest04 ( ) throws Exception { String [ ] args = new String [ ] ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; args [ ] = "" ; Extractor extractor = new StubExtractor ( ) { @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override public boolean loadImportParam ( String targetName , String batchId , String jobflowId , boolean isPrimary ) { return false ; } } ; return loder ; } } ; int result = extractor . execute ( args ) ; assertEquals ( , result ) ; } } class StubExtractor extends Extractor { @ Override protected DfsFileImport createDfsFileImport ( ) { return new StubHdfsFileImport ( ) ; } @ Override protected JobFlowParamLoader createJobFlowParamLoader ( ) { JobFlowParamLoader loder = new JobFlowParamLoader ( ) { @ Override protected Properties getImportProp ( File file , String targetName ) throws IOException { System . out . println ( file ) ; File propFile = new File ( "" ) ; FileInputStream fis = new FileInputStream ( propFile ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; return prop ; } } ; return loder ; } } class StubHdfsFileImport extends DfsFileImport { boolean result = true ; public StubHdfsFileImport ( ) { } public StubHdfsFileImport ( boolean result ) { this . result = result ; } @ Override public boolean importFile ( ImportBean bean , String user ) { return result ; } } package com . asakusafw . bulkloader . extractor ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . URI ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Calendar ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . concurrent . Callable ; import java . util . zip . ZipEntry ; import java . util . zip . ZipInputStream ; import org . apache . hadoop . io . SequenceFile . CompressionType ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import test . modelgen . table . model . ImportTarget1 ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . testutil . UnitTestUtil ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . runtime . io . util . ZipEntryInputStream ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; import com . asakusafw . thundergate . runtime . cache . mapreduce . CacheBuildClient ; public class DfsFileImportTest { @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private static List < String > properties = Arrays . asList ( new String [ ] { "" , "" } ) ; private static String jobflowId = "" ; private static String executionId = "" ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; BulkLoaderInitializer . initHadoopCluster ( jobflowId , executionId , properties ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { BulkLoaderInitializer . initHadoopCluster ( jobflowId , executionId , properties ) ; UnitTestUtil . tearDownAfterClass ( ) ; UnitTestUtil . tearDownEnv ( ) ; } @ Before public void setUp ( ) throws Exception { UnitTestUtil . startUp ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; } @ Test public void importFileTest01 ( ) throws Exception { Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setDfsFilePath ( "" ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setDfsFilePath ( "" ) ; tableBean2 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; DummyHdfsFileImport fileImport = new DummyHdfsFileImport ( ) { int count = ; @ Override protected InputStream getInputStream ( ) { return open ( "" ) ; } @ Override protected < T > long write ( Class < T > targetTableModel , URI hdfsFilePath , InputStream zipEntryInputStream ) throws BulkLoaderSystemException { FileOutputStream fos = null ; try { uri [ count ] = hdfsFilePath ; count ++ ; File file = new File ( "" + String . valueOf ( count ) + "" ) ; file . createNewFile ( ) ; fos = new FileOutputStream ( file ) ; byte [ ] b = new byte [ ] ; while ( true ) { int read = zipEntryInputStream . read ( b ) ; if ( read == - ) { break ; } fos . write ( b , , read ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return ; } } ; boolean result = fileImport . importFile ( bean , "" ) ; assertTrue ( result ) ; assertEquals ( "" , fileImport . getUri ( ) [ ] . toString ( ) ) ; assertEquals ( "" , fileImport . getUri ( ) [ ] . toString ( ) ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , new File ( "" ) ) ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , new File ( "" ) ) ) ; } @ Test public void importFileTest02 ( ) throws Exception { Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setDfsFilePath ( "" ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setDfsFilePath ( "" ) ; tableBean2 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; DfsFileImport fileImport = new DfsFileImport ( ) { int count = ; @ Override protected InputStream getInputStream ( ) { return open ( "" ) ; } @ Override protected < T > long write ( Class < T > targetTableModel , URI hdfsFilePath , InputStream zipEntryInputStream ) throws BulkLoaderSystemException { FileOutputStream fos = null ; try { count ++ ; File file = new File ( "" + String . valueOf ( count ) + "" ) ; file . createNewFile ( ) ; fos = new FileOutputStream ( file ) ; byte [ ] b = new byte [ ] ; while ( true ) { int read = zipEntryInputStream . read ( b ) ; if ( read == - ) { break ; } fos . write ( b , , read ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return ; } } ; boolean result = fileImport . importFile ( bean , "" ) ; assertTrue ( result ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , new File ( "" ) ) ) ; assertTrue ( UnitTestUtil . assertFile ( new File ( "" ) , new File ( "" ) ) ) ; } @ Test public void create_cache ( ) throws Exception { Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setDfsFilePath ( "" ) ; tableBean1 . setImportTargetType ( ImportTarget1 . class ) ; tableBean1 . setCacheId ( "" ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setDfsFilePath ( "" ) ; tableBean2 . setImportTargetType ( ImportTarget1 . class ) ; tableBean2 . setCacheId ( "" ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; final ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( buffer , true ) ; final CacheInfo info = new CacheInfo ( "" , "" , Calendar . getInstance ( ) , "" , Arrays . asList ( "" , "" ) , "" , ) ; writer . openNext ( new FileProtocol ( FileProtocol . Kind . CREATE_CACHE , tableBean1 . getDfsFilePath ( ) , info ) ) . close ( ) ; writer . openNext ( new FileProtocol ( FileProtocol . Kind . CONTENT , FileNameUtil . createSendImportFileName ( "" ) , null ) ) . close ( ) ; writer . close ( ) ; final File output = folder . newFolder ( "" ) ; final List < String > files = new ArrayList < String > ( ) ; final List < String > builders = new ArrayList < String > ( ) ; DummyHdfsFileImport fileImport = new DummyHdfsFileImport ( ) { @ Override protected InputStream getInputStream ( ) { return new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; } @ Override protected URI resolveLocation ( ImportBean _ , String user , String location ) throws BulkLoaderSystemException { return new File ( output , location ) . toURI ( ) ; } @ Override protected < T > long write ( Class < T > targetTableModel , URI dfsFilePath , InputStream inputStream ) throws BulkLoaderSystemException { try { inputStream . close ( ) ; files . add ( new File ( dfsFilePath ) . getPath ( ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } return ; } @ Override protected Callable < ? > createCacheBuilder ( String subcommand , ImportBean _ , URI location , final CacheInfo target ) throws IOException { assertThat ( subcommand , is ( CacheBuildClient . SUBCOMMAND_CREATE ) ) ; assertThat ( target , is ( info ) ) ; return new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { builders . add ( target . getId ( ) ) ; return null ; } } ; } } ; boolean result = fileImport . importFile ( bean , "" ) ; assertTrue ( result ) ; assertThat ( files . size ( ) , is ( ) ) ; assertThat ( files . get ( ) , endsWith ( "" ) ) ; assertThat ( files . get ( ) , endsWith ( tableBean2 . getDfsFilePath ( ) ) ) ; Collections . sort ( builders ) ; assertThat ( builders . size ( ) , is ( ) ) ; assertThat ( builders . get ( ) , is ( "" ) ) ; } @ Test public void update_cache ( ) throws Exception { Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setDfsFilePath ( "" ) ; tableBean1 . setImportTargetType ( ImportTarget1 . class ) ; tableBean1 . setCacheId ( "" ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setDfsFilePath ( "" ) ; tableBean2 . setImportTargetType ( ImportTarget1 . class ) ; tableBean2 . setCacheId ( "" ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; final ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( buffer , true ) ; final CacheInfo info = new CacheInfo ( "" , "" , Calendar . getInstance ( ) , "" , Arrays . asList ( "" , "" ) , "" , ) ; writer . openNext ( new FileProtocol ( FileProtocol . Kind . UPDATE_CACHE , tableBean1 . getDfsFilePath ( ) , info ) ) . close ( ) ; writer . openNext ( new FileProtocol ( FileProtocol . Kind . CONTENT , FileNameUtil . createSendImportFileName ( "" ) , null ) ) . close ( ) ; writer . close ( ) ; final File output = folder . newFolder ( "" ) ; final List < String > files = new ArrayList < String > ( ) ; final List < String > builders = new ArrayList < String > ( ) ; DummyHdfsFileImport fileImport = new DummyHdfsFileImport ( ) { @ Override protected InputStream getInputStream ( ) { return new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; } @ Override protected URI resolveLocation ( ImportBean _ , String user , String location ) throws BulkLoaderSystemException { return new File ( output , location ) . toURI ( ) ; } @ Override protected < T > long write ( Class < T > targetTableModel , URI dfsFilePath , InputStream inputStream ) throws BulkLoaderSystemException { try { inputStream . close ( ) ; files . add ( new File ( dfsFilePath ) . getPath ( ) ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } return ; } @ Override protected Callable < ? > createCacheBuilder ( String subcommand , ImportBean _ , URI location , final CacheInfo target ) throws IOException { assertThat ( subcommand , is ( CacheBuildClient . SUBCOMMAND_UPDATE ) ) ; assertThat ( target , is ( info ) ) ; return new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { builders . add ( target . getId ( ) ) ; return null ; } } ; } } ; boolean result = fileImport . importFile ( bean , "" ) ; assertTrue ( result ) ; assertThat ( files . size ( ) , is ( ) ) ; assertThat ( files . get ( ) , endsWith ( "" ) ) ; assertThat ( files . get ( ) , endsWith ( tableBean2 . getDfsFilePath ( ) ) ) ; Collections . sort ( builders ) ; assertThat ( builders . size ( ) , is ( ) ) ; assertThat ( builders . get ( ) , is ( "" ) ) ; } @ Test public void extract_broken ( ) throws Exception { Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setDfsFilePath ( "" ) ; tableBean1 . setImportTargetType ( ImportTarget1 . class ) ; targetTable . put ( "" , tableBean1 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; final File target = folder . newFile ( "" ) ; DfsFileImport fileImport = new DfsFileImport ( ) { @ Override protected InputStream getInputStream ( ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( output , false ) ; String name = FileNameUtil . createSendImportFileName ( "" ) ; OutputStream content = writer . openNext ( FileList . content ( name ) ) ; content . close ( ) ; output . close ( ) ; return new ByteArrayInputStream ( output . toByteArray ( ) ) ; } @ Override protected URI resolveLocation ( ImportBean _ , String user , String location ) { return target . toURI ( ) ; } } ; boolean result = fileImport . importFile ( bean , "" ) ; assertThat ( result , is ( false ) ) ; } @ Test public void importFileTest03 ( ) throws Exception { Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setDfsFilePath ( "" ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setDfsFilePath ( "" ) ; tableBean2 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; DfsFileImport fileImport = new DfsFileImport ( ) { int count = ; @ Override protected InputStream getInputStream ( ) { return open ( "" ) ; } @ Override protected < T > long write ( Class < T > targetTableModel , URI hdfsFilePath , InputStream zipEntryInputStream ) throws BulkLoaderSystemException { FileOutputStream fos = null ; try { count ++ ; File file = new File ( "" + String . valueOf ( count ) + "" ) ; file . createNewFile ( ) ; fos = new FileOutputStream ( file ) ; byte [ ] b = new byte [ ] ; while ( true ) { int read = zipEntryInputStream . read ( b ) ; if ( read == - ) { break ; } fos . write ( b , , read ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return ; } } ; boolean result = fileImport . importFile ( bean , "" ) ; assertFalse ( result ) ; } @ Test public void importFileTest04 ( ) throws Exception { Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setDfsFilePath ( "" ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setDfsFilePath ( "" ) ; tableBean2 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; DfsFileImport fileImport = new DfsFileImport ( ) { @ Override protected InputStream getInputStream ( ) { return open ( "" ) ; } @ Override protected < T > long write ( Class < T > targetTableModel , URI hdfsFilePath , InputStream zipEntryInputStream ) throws BulkLoaderSystemException { throw new BulkLoaderSystemException ( new NullPointerException ( ) , this . getClass ( ) , "" ) ; } } ; boolean result = fileImport . importFile ( bean , "" ) ; assertFalse ( result ) ; } @ SuppressWarnings ( "" ) @ Test public void importFileTest05 ( ) throws Exception { Map < String , ImportTargetTableBean > targetTable = new LinkedHashMap < String , ImportTargetTableBean > ( ) ; ImportTargetTableBean tableBean1 = new ImportTargetTableBean ( ) ; tableBean1 . setDfsFilePath ( "" ) ; tableBean1 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean1 ) ; ImportTargetTableBean tableBean2 = new ImportTargetTableBean ( ) ; tableBean2 . setDfsFilePath ( "" ) ; tableBean2 . setImportTargetType ( this . getClass ( ) ) ; targetTable . put ( "" , tableBean2 ) ; ImportBean bean = new ImportBean ( ) ; bean . setTargetTable ( targetTable ) ; bean . setExecutionId ( executionId ) ; Properties prop = ConfigurationLoader . getProperty ( ) ; prop . setProperty ( Constants . PROP_KEY_BASE_PATH , "" ) ; DfsFileImport fileImport = new DfsFileImport ( ) { int count = ; @ Override protected InputStream getInputStream ( ) { return open ( "" ) ; } @ Override protected < T > long write ( Class < T > targetTableModel , URI hdfsFilePath , InputStream zipEntryInputStream ) throws BulkLoaderSystemException { FileOutputStream fos = null ; try { count ++ ; File file = new File ( "" + String . valueOf ( count ) + "" ) ; file . createNewFile ( ) ; fos = new FileOutputStream ( file ) ; byte [ ] b = new byte [ ] ; while ( true ) { int read = zipEntryInputStream . read ( b ) ; if ( read == - ) { break ; } fos . write ( b , , read ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return ; } } ; boolean result = fileImport . importFile ( bean , "" ) ; assertFalse ( result ) ; } @ Test public void writeTest01 ( ) throws Exception { File inFile = new File ( "" ) ; File outFile = new File ( "" ) ; Class < ImportTarget1 > targetTableModel = ImportTarget1 . class ; DfsFileImport fileImport = new DfsFileImport ( ) ; try { ZipInputStream zipIs = new ZipInputStream ( new FileInputStream ( inFile ) ) ; ZipEntry zipEntry = null ; while ( ( zipEntry = zipIs . getNextEntry ( ) ) != null ) { if ( zipEntry . isDirectory ( ) ) { continue ; } else { break ; } } fileImport . write ( targetTableModel , outFile . toURI ( ) , new ZipEntryInputStream ( zipIs ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; fail ( ) ; } assertTrue ( outFile . exists ( ) ) ; outFile . delete ( ) ; } @ Test public void getCompType01 ( ) throws Exception { DfsFileImport fileImport = new DfsFileImport ( ) ; CompressionType compType = fileImport . getCompType ( "" ) ; assertEquals ( CompressionType . NONE , compType ) ; } @ Test public void getCompType02 ( ) throws Exception { DfsFileImport fileImport = new DfsFileImport ( ) ; CompressionType compType = fileImport . getCompType ( "" ) ; assertEquals ( CompressionType . BLOCK , compType ) ; } @ Test public void getCompType03 ( ) throws Exception { DfsFileImport fileImport = new DfsFileImport ( ) ; CompressionType compType = fileImport . getCompType ( "" ) ; assertEquals ( CompressionType . RECORD , compType ) ; } @ Test public void getCompType04 ( ) throws Exception { DfsFileImport fileImport = new DfsFileImport ( ) ; CompressionType compType = fileImport . getCompType ( "" ) ; assertEquals ( CompressionType . NONE , compType ) ; } InputStream open ( String file ) { try { File temp = folder . newFile ( "" ) ; UnitTestUtil . createFileList ( new File ( file ) , temp ) ; return new FileInputStream ( temp ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } class DummyHdfsFileImport extends DfsFileImport { URI [ ] uri = null ; DummyHdfsFileImport ( int tableCount ) { uri = new URI [ tableCount ] ; } public URI [ ] getUri ( ) { return uri ; } @ Override protected Callable < ? > createCacheBuilder ( String subcommand , ImportBean bean , URI location , CacheInfo info ) throws IOException { return null ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ImportTableLock implements Writable { @ Property ( name = "" ) private StringOption tableName = new StringOption ( ) ; @ Property ( name = "" ) private LongOption jobflowSid = new LongOption ( ) ; public Text getTableName ( ) { return this . tableName . get ( ) ; } public void setTableName ( Text tableName ) { this . tableName . modify ( tableName ) ; } public String getTableNameAsString ( ) { return this . tableName . getAsString ( ) ; } public void setTableNameAsString ( String tableName ) { this . tableName . modify ( tableName ) ; } public StringOption getTableNameOption ( ) { return this . tableName ; } public void setTableNameOption ( StringOption tableName ) { this . tableName . copyFrom ( tableName ) ; } public long getJobflowSid ( ) { return this . jobflowSid . get ( ) ; } public void setJobflowSid ( long jobflowSid ) { this . jobflowSid . modify ( jobflowSid ) ; } public LongOption getJobflowSidOption ( ) { return this . jobflowSid ; } public void setJobflowSidOption ( LongOption jobflowSid ) { this . jobflowSid . copyFrom ( jobflowSid ) ; } public void copyFrom ( ImportTableLock source ) { this . tableName . copyFrom ( source . tableName ) ; this . jobflowSid . copyFrom ( source . jobflowSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { tableName . write ( out ) ; jobflowSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tableName . readFields ( in ) ; jobflowSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tableName . hashCode ( ) ; result = prime * result + jobflowSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ImportTableLock other = ( ImportTableLock ) obj ; if ( this . tableName . equals ( other . tableName ) == false ) { return false ; } if ( this . jobflowSid . equals ( other . jobflowSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tableName ) ; result . append ( "" ) ; result . append ( this . jobflowSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class PurchaseTranError2 implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private LongOption lineNo = new LongOption ( ) ; @ Property ( name = "" ) private DateOption deliveryDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption storeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tenantCode = new StringOption ( ) ; @ Property ( name = "" ) private LongOption netPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sellingPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private StringOption shipmentStoreCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption shipmentSalesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption deductionCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption accountCode = new StringOption ( ) ; @ Property ( name = "" ) private DateOption ownershipDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption ownershipFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption errorCause = new StringOption ( ) ; @ Property ( name = "" ) private StringOption errorCode = new StringOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDatetime ( ) { return this . rgstDatetime . get ( ) ; } public void setRgstDatetime ( DateTime rgstDatetime ) { this . rgstDatetime . modify ( rgstDatetime ) ; } public DateTimeOption getRgstDatetimeOption ( ) { return this . rgstDatetime ; } public void setRgstDatetimeOption ( DateTimeOption rgstDatetime ) { this . rgstDatetime . copyFrom ( rgstDatetime ) ; } public DateTime getUpdtDatetime ( ) { return this . updtDatetime . get ( ) ; } public void setUpdtDatetime ( DateTime updtDatetime ) { this . updtDatetime . modify ( updtDatetime ) ; } public DateTimeOption getUpdtDatetimeOption ( ) { return this . updtDatetime ; } public void setUpdtDatetimeOption ( DateTimeOption updtDatetime ) { this . updtDatetime . copyFrom ( updtDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public long getLineNo ( ) { return this . lineNo . get ( ) ; } public void setLineNo ( long lineNo ) { this . lineNo . modify ( lineNo ) ; } public LongOption getLineNoOption ( ) { return this . lineNo ; } public void setLineNoOption ( LongOption lineNo ) { this . lineNo . copyFrom ( lineNo ) ; } public Date getDeliveryDate ( ) { return this . deliveryDate . get ( ) ; } public void setDeliveryDate ( Date deliveryDate ) { this . deliveryDate . modify ( deliveryDate ) ; } public DateOption getDeliveryDateOption ( ) { return this . deliveryDate ; } public void setDeliveryDateOption ( DateOption deliveryDate ) { this . deliveryDate . copyFrom ( deliveryDate ) ; } public Text getStoreCode ( ) { return this . storeCode . get ( ) ; } public void setStoreCode ( Text storeCode ) { this . storeCode . modify ( storeCode ) ; } public String getStoreCodeAsString ( ) { return this . storeCode . getAsString ( ) ; } public void setStoreCodeAsString ( String storeCode ) { this . storeCode . modify ( storeCode ) ; } public StringOption getStoreCodeOption ( ) { return this . storeCode ; } public void setStoreCodeOption ( StringOption storeCode ) { this . storeCode . copyFrom ( storeCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Text getPurchaseTypeCode ( ) { return this . purchaseTypeCode . get ( ) ; } public void setPurchaseTypeCode ( Text purchaseTypeCode ) { this . purchaseTypeCode . modify ( purchaseTypeCode ) ; } public String getPurchaseTypeCodeAsString ( ) { return this . purchaseTypeCode . getAsString ( ) ; } public void setPurchaseTypeCodeAsString ( String purchaseTypeCode ) { this . purchaseTypeCode . modify ( purchaseTypeCode ) ; } public StringOption getPurchaseTypeCodeOption ( ) { return this . purchaseTypeCode ; } public void setPurchaseTypeCodeOption ( StringOption purchaseTypeCode ) { this . purchaseTypeCode . copyFrom ( purchaseTypeCode ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getTenantCode ( ) { return this . tenantCode . get ( ) ; } public void setTenantCode ( Text tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public String getTenantCodeAsString ( ) { return this . tenantCode . getAsString ( ) ; } public void setTenantCodeAsString ( String tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public StringOption getTenantCodeOption ( ) { return this . tenantCode ; } public void setTenantCodeOption ( StringOption tenantCode ) { this . tenantCode . copyFrom ( tenantCode ) ; } public long getNetPriceTotal ( ) { return this . netPriceTotal . get ( ) ; } public void setNetPriceTotal ( long netPriceTotal ) { this . netPriceTotal . modify ( netPriceTotal ) ; } public LongOption getNetPriceTotalOption ( ) { return this . netPriceTotal ; } public void setNetPriceTotalOption ( LongOption netPriceTotal ) { this . netPriceTotal . copyFrom ( netPriceTotal ) ; } public long getSellingPriceTotal ( ) { return this . sellingPriceTotal . get ( ) ; } public void setSellingPriceTotal ( long sellingPriceTotal ) { this . sellingPriceTotal . modify ( sellingPriceTotal ) ; } public LongOption getSellingPriceTotalOption ( ) { return this . sellingPriceTotal ; } public void setSellingPriceTotalOption ( LongOption sellingPriceTotal ) { this . sellingPriceTotal . copyFrom ( sellingPriceTotal ) ; } public Text getShipmentStoreCode ( ) { return this . shipmentStoreCode . get ( ) ; } public void setShipmentStoreCode ( Text shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public String getShipmentStoreCodeAsString ( ) { return this . shipmentStoreCode . getAsString ( ) ; } public void setShipmentStoreCodeAsString ( String shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public StringOption getShipmentStoreCodeOption ( ) { return this . shipmentStoreCode ; } public void setShipmentStoreCodeOption ( StringOption shipmentStoreCode ) { this . shipmentStoreCode . copyFrom ( shipmentStoreCode ) ; } public Text getShipmentSalesTypeCode ( ) { return this . shipmentSalesTypeCode . get ( ) ; } public void setShipmentSalesTypeCode ( Text shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public String getShipmentSalesTypeCodeAsString ( ) { return this . shipmentSalesTypeCode . getAsString ( ) ; } public void setShipmentSalesTypeCodeAsString ( String shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public StringOption getShipmentSalesTypeCodeOption ( ) { return this . shipmentSalesTypeCode ; } public void setShipmentSalesTypeCodeOption ( StringOption shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . copyFrom ( shipmentSalesTypeCode ) ; } public Text getDeductionCode ( ) { return this . deductionCode . get ( ) ; } public void setDeductionCode ( Text deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public String getDeductionCodeAsString ( ) { return this . deductionCode . getAsString ( ) ; } public void setDeductionCodeAsString ( String deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public StringOption getDeductionCodeOption ( ) { return this . deductionCode ; } public void setDeductionCodeOption ( StringOption deductionCode ) { this . deductionCode . copyFrom ( deductionCode ) ; } public Text getAccountCode ( ) { return this . accountCode . get ( ) ; } public void setAccountCode ( Text accountCode ) { this . accountCode . modify ( accountCode ) ; } public String getAccountCodeAsString ( ) { return this . accountCode . getAsString ( ) ; } public void setAccountCodeAsString ( String accountCode ) { this . accountCode . modify ( accountCode ) ; } public StringOption getAccountCodeOption ( ) { return this . accountCode ; } public void setAccountCodeOption ( StringOption accountCode ) { this . accountCode . copyFrom ( accountCode ) ; } public Date getOwnershipDate ( ) { return this . ownershipDate . get ( ) ; } public void setOwnershipDate ( Date ownershipDate ) { this . ownershipDate . modify ( ownershipDate ) ; } public DateOption getOwnershipDateOption ( ) { return this . ownershipDate ; } public void setOwnershipDateOption ( DateOption ownershipDate ) { this . ownershipDate . copyFrom ( ownershipDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public Text getOwnershipFlag ( ) { return this . ownershipFlag . get ( ) ; } public void setOwnershipFlag ( Text ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public String getOwnershipFlagAsString ( ) { return this . ownershipFlag . getAsString ( ) ; } public void setOwnershipFlagAsString ( String ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public StringOption getOwnershipFlagOption ( ) { return this . ownershipFlag ; } public void setOwnershipFlagOption ( StringOption ownershipFlag ) { this . ownershipFlag . copyFrom ( ownershipFlag ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public Text getErrorCause ( ) { return this . errorCause . get ( ) ; } public void setErrorCause ( Text errorCause ) { this . errorCause . modify ( errorCause ) ; } public String getErrorCauseAsString ( ) { return this . errorCause . getAsString ( ) ; } public void setErrorCauseAsString ( String errorCause ) { this . errorCause . modify ( errorCause ) ; } public StringOption getErrorCauseOption ( ) { return this . errorCause ; } public void setErrorCauseOption ( StringOption errorCause ) { this . errorCause . copyFrom ( errorCause ) ; } public Text getErrorCode ( ) { return this . errorCode . get ( ) ; } public void setErrorCode ( Text errorCode ) { this . errorCode . modify ( errorCode ) ; } public String getErrorCodeAsString ( ) { return this . errorCode . getAsString ( ) ; } public void setErrorCodeAsString ( String errorCode ) { this . errorCode . modify ( errorCode ) ; } public StringOption getErrorCodeOption ( ) { return this . errorCode ; } public void setErrorCodeOption ( StringOption errorCode ) { this . errorCode . copyFrom ( errorCode ) ; } public void copyFrom ( PurchaseTranError2 source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDatetime . copyFrom ( source . rgstDatetime ) ; this . updtDatetime . copyFrom ( source . updtDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . lineNo . copyFrom ( source . lineNo ) ; this . deliveryDate . copyFrom ( source . deliveryDate ) ; this . storeCode . copyFrom ( source . storeCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . purchaseTypeCode . copyFrom ( source . purchaseTypeCode ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . tenantCode . copyFrom ( source . tenantCode ) ; this . netPriceTotal . copyFrom ( source . netPriceTotal ) ; this . sellingPriceTotal . copyFrom ( source . sellingPriceTotal ) ; this . shipmentStoreCode . copyFrom ( source . shipmentStoreCode ) ; this . shipmentSalesTypeCode . copyFrom ( source . shipmentSalesTypeCode ) ; this . deductionCode . copyFrom ( source . deductionCode ) ; this . accountCode . copyFrom ( source . accountCode ) ; this . ownershipDate . copyFrom ( source . ownershipDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . ownershipFlag . copyFrom ( source . ownershipFlag ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; this . errorCause . copyFrom ( source . errorCause ) ; this . errorCode . copyFrom ( source . errorCode ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; rgstDatetime . write ( out ) ; updtDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; lineNo . write ( out ) ; deliveryDate . write ( out ) ; storeCode . write ( out ) ; buyerCode . write ( out ) ; purchaseTypeCode . write ( out ) ; sellerCode . write ( out ) ; tenantCode . write ( out ) ; netPriceTotal . write ( out ) ; sellingPriceTotal . write ( out ) ; shipmentStoreCode . write ( out ) ; shipmentSalesTypeCode . write ( out ) ; deductionCode . write ( out ) ; accountCode . write ( out ) ; ownershipDate . write ( out ) ; cutoffDate . write ( out ) ; payoutDate . write ( out ) ; ownershipFlag . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; errorCause . write ( out ) ; errorCode . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDatetime . readFields ( in ) ; updtDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; lineNo . readFields ( in ) ; deliveryDate . readFields ( in ) ; storeCode . readFields ( in ) ; buyerCode . readFields ( in ) ; purchaseTypeCode . readFields ( in ) ; sellerCode . readFields ( in ) ; tenantCode . readFields ( in ) ; netPriceTotal . readFields ( in ) ; sellingPriceTotal . readFields ( in ) ; shipmentStoreCode . readFields ( in ) ; shipmentSalesTypeCode . readFields ( in ) ; deductionCode . readFields ( in ) ; accountCode . readFields ( in ) ; ownershipDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; ownershipFlag . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; errorCause . readFields ( in ) ; errorCode . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + rgstDatetime . hashCode ( ) ; result = prime * result + updtDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + lineNo . hashCode ( ) ; result = prime * result + deliveryDate . hashCode ( ) ; result = prime * result + storeCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + purchaseTypeCode . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + tenantCode . hashCode ( ) ; result = prime * result + netPriceTotal . hashCode ( ) ; result = prime * result + sellingPriceTotal . hashCode ( ) ; result = prime * result + shipmentStoreCode . hashCode ( ) ; result = prime * result + shipmentSalesTypeCode . hashCode ( ) ; result = prime * result + deductionCode . hashCode ( ) ; result = prime * result + accountCode . hashCode ( ) ; result = prime * result + ownershipDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + ownershipFlag . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; result = prime * result + errorCause . hashCode ( ) ; result = prime * result + errorCode . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } PurchaseTranError2 other = ( PurchaseTranError2 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDatetime . equals ( other . rgstDatetime ) == false ) { return false ; } if ( this . updtDatetime . equals ( other . updtDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . lineNo . equals ( other . lineNo ) == false ) { return false ; } if ( this . deliveryDate . equals ( other . deliveryDate ) == false ) { return false ; } if ( this . storeCode . equals ( other . storeCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . purchaseTypeCode . equals ( other . purchaseTypeCode ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . tenantCode . equals ( other . tenantCode ) == false ) { return false ; } if ( this . netPriceTotal . equals ( other . netPriceTotal ) == false ) { return false ; } if ( this . sellingPriceTotal . equals ( other . sellingPriceTotal ) == false ) { return false ; } if ( this . shipmentStoreCode . equals ( other . shipmentStoreCode ) == false ) { return false ; } if ( this . shipmentSalesTypeCode . equals ( other . shipmentSalesTypeCode ) == false ) { return false ; } if ( this . deductionCode . equals ( other . deductionCode ) == false ) { return false ; } if ( this . accountCode . equals ( other . accountCode ) == false ) { return false ; } if ( this . ownershipDate . equals ( other . ownershipDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . ownershipFlag . equals ( other . ownershipFlag ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } if ( this . errorCause . equals ( other . errorCause ) == false ) { return false ; } if ( this . errorCode . equals ( other . errorCode ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . rgstDatetime ) ; result . append ( "" ) ; result . append ( this . updtDatetime ) ; result . append ( "" ) ; result . append ( this . purchaseNo ) ; result . append ( "" ) ; result . append ( this . purchaseType ) ; result . append ( "" ) ; result . append ( this . tradeType ) ; result . append ( "" ) ; result . append ( this . tradeNo ) ; result . append ( "" ) ; result . append ( this . lineNo ) ; result . append ( "" ) ; result . append ( this . deliveryDate ) ; result . append ( "" ) ; result . append ( this . storeCode ) ; result . append ( "" ) ; result . append ( this . buyerCode ) ; result . append ( "" ) ; result . append ( this . purchaseTypeCode ) ; result . append ( "" ) ; result . append ( this . sellerCode ) ; result . append ( "" ) ; result . append ( this . tenantCode ) ; result . append ( "" ) ; result . append ( this . netPriceTotal ) ; result . append ( "" ) ; result . append ( this . sellingPriceTotal ) ; result . append ( "" ) ; result . append ( this . shipmentStoreCode ) ; result . append ( "" ) ; result . append ( this . shipmentSalesTypeCode ) ; result . append ( "" ) ; result . append ( this . deductionCode ) ; result . append ( "" ) ; result . append ( this . accountCode ) ; result . append ( "" ) ; result . append ( this . ownershipDate ) ; result . append ( "" ) ; result . append ( this . cutoffDate ) ; result . append ( "" ) ; result . append ( this . payoutDate ) ; result . append ( "" ) ; result . append ( this . ownershipFlag ) ; result . append ( "" ) ; result . append ( this . cutoffFlag ) ; result . append ( "" ) ; result . append ( this . payoutFlag ) ; result . append ( "" ) ; result . append ( this . disposeNo ) ; result . append ( "" ) ; result . append ( this . disposeDate ) ; result . append ( "" ) ; result . append ( this . errorCause ) ; result . append ( "" ) ; result . append ( this . errorCode ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempImportTarget11Df implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public void copyFrom ( ExportTempImportTarget11Df source ) { this . tempSid . copyFrom ( source . tempSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempImportTarget11Df other = ( ExportTempImportTarget11Df ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class TempImportTarget2Df implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public void copyFrom ( TempImportTarget2Df source ) { this . tempSid . copyFrom ( source . tempSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } TempImportTarget2Df other = ( TempImportTarget2Df ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class DeductionTran implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption deductionNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private DateOption closedDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; @ Property ( name = "" ) private LongOption detailCount = new LongOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDatetime ( ) { return this . rgstDatetime . get ( ) ; } public void setRgstDatetime ( DateTime rgstDatetime ) { this . rgstDatetime . modify ( rgstDatetime ) ; } public DateTimeOption getRgstDatetimeOption ( ) { return this . rgstDatetime ; } public void setRgstDatetimeOption ( DateTimeOption rgstDatetime ) { this . rgstDatetime . copyFrom ( rgstDatetime ) ; } public DateTime getUpdtDatetime ( ) { return this . updtDatetime . get ( ) ; } public void setUpdtDatetime ( DateTime updtDatetime ) { this . updtDatetime . modify ( updtDatetime ) ; } public DateTimeOption getUpdtDatetimeOption ( ) { return this . updtDatetime ; } public void setUpdtDatetimeOption ( DateTimeOption updtDatetime ) { this . updtDatetime . copyFrom ( updtDatetime ) ; } public Text getDeductionNo ( ) { return this . deductionNo . get ( ) ; } public void setDeductionNo ( Text deductionNo ) { this . deductionNo . modify ( deductionNo ) ; } public String getDeductionNoAsString ( ) { return this . deductionNo . getAsString ( ) ; } public void setDeductionNoAsString ( String deductionNo ) { this . deductionNo . modify ( deductionNo ) ; } public StringOption getDeductionNoOption ( ) { return this . deductionNo ; } public void setDeductionNoOption ( StringOption deductionNo ) { this . deductionNo . copyFrom ( deductionNo ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Date getClosedDate ( ) { return this . closedDate . get ( ) ; } public void setClosedDate ( Date closedDate ) { this . closedDate . modify ( closedDate ) ; } public DateOption getClosedDateOption ( ) { return this . closedDate ; } public void setClosedDateOption ( DateOption closedDate ) { this . closedDate . copyFrom ( closedDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public long getDetailCount ( ) { return this . detailCount . get ( ) ; } public void setDetailCount ( long detailCount ) { this . detailCount . modify ( detailCount ) ; } public LongOption getDetailCountOption ( ) { return this . detailCount ; } public void setDetailCountOption ( LongOption detailCount ) { this . detailCount . copyFrom ( detailCount ) ; } public void copyFrom ( DeductionTran source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDatetime . copyFrom ( source . rgstDatetime ) ; this . updtDatetime . copyFrom ( source . updtDatetime ) ; this . deductionNo . copyFrom ( source . deductionNo ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . closedDate . copyFrom ( source . closedDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; this . detailCount . copyFrom ( source . detailCount ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; rgstDatetime . write ( out ) ; updtDatetime . write ( out ) ; deductionNo . write ( out ) ; sellerCode . write ( out ) ; buyerCode . write ( out ) ; closedDate . write ( out ) ; cutoffDate . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; detailCount . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDatetime . readFields ( in ) ; updtDatetime . readFields ( in ) ; deductionNo . readFields ( in ) ; sellerCode . readFields ( in ) ; buyerCode . readFields ( in ) ; closedDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; detailCount . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + rgstDatetime . hashCode ( ) ; result = prime * result + updtDatetime . hashCode ( ) ; result = prime * result + deductionNo . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + closedDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; result = prime * result + detailCount . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } DeductionTran other = ( DeductionTran ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDatetime . equals ( other . rgstDatetime ) == false ) { return false ; } if ( this . updtDatetime . equals ( other . updtDatetime ) == false ) { return false ; } if ( this . deductionNo . equals ( other . deductionNo ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . closedDate . equals ( other . closedDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } if ( this . detailCount . equals ( other . detailCount ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . rgstDatetime ) ; result . append ( "" ) ; result . append ( this . updtDatetime ) ; result . append ( "" ) ; result . append ( this . deductionNo ) ; result . append ( "" ) ; result . append ( this . sellerCode ) ; result . append ( "" ) ; result . append ( this . buyerCode ) ; result . append ( "" ) ; result . append ( this . closedDate ) ; result . append ( "" ) ; result . append ( this . cutoffDate ) ; result . append ( "" ) ; result . append ( this . cutoffFlag ) ; result . append ( "" ) ; result . append ( this . payoutFlag ) ; result . append ( "" ) ; result . append ( this . disposeNo ) ; result . append ( "" ) ; result . append ( this . disposeDate ) ; result . append ( "" ) ; result . append ( this . detailCount ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ImportTarget1Rl implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption jobflowSid = new LongOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getJobflowSid ( ) { return this . jobflowSid . get ( ) ; } public void setJobflowSid ( long jobflowSid ) { this . jobflowSid . modify ( jobflowSid ) ; } public LongOption getJobflowSidOption ( ) { return this . jobflowSid ; } public void setJobflowSidOption ( LongOption jobflowSid ) { this . jobflowSid . copyFrom ( jobflowSid ) ; } public void copyFrom ( ImportTarget1Rl source ) { this . sid . copyFrom ( source . sid ) ; this . jobflowSid . copyFrom ( source . jobflowSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; jobflowSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; jobflowSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + jobflowSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ImportTarget1Rl other = ( ImportTarget1Rl ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . jobflowSid . equals ( other . jobflowSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . jobflowSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempTest02 implements Writable { @ Property ( name = "" ) private StringOption textdata1 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata1 = new IntOption ( ) ; public Text getTextdata1 ( ) { return this . textdata1 . get ( ) ; } public void setTextdata1 ( Text textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public String getTextdata1AsString ( ) { return this . textdata1 . getAsString ( ) ; } public void setTextdata1AsString ( String textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public StringOption getTextdata1Option ( ) { return this . textdata1 ; } public void setTextdata1Option ( StringOption textdata1 ) { this . textdata1 . copyFrom ( textdata1 ) ; } public int getIntdata1 ( ) { return this . intdata1 . get ( ) ; } public void setIntdata1 ( int intdata1 ) { this . intdata1 . modify ( intdata1 ) ; } public IntOption getIntdata1Option ( ) { return this . intdata1 ; } public void setIntdata1Option ( IntOption intdata1 ) { this . intdata1 . copyFrom ( intdata1 ) ; } public void copyFrom ( ExportTempTest02 source ) { this . textdata1 . copyFrom ( source . textdata1 ) ; this . intdata1 . copyFrom ( source . intdata1 ) ; } @ Override public void write ( DataOutput out ) throws IOException { textdata1 . write ( out ) ; intdata1 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { textdata1 . readFields ( in ) ; intdata1 . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + textdata1 . hashCode ( ) ; result = prime * result + intdata1 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempTest02 other = ( ExportTempTest02 ) obj ; if ( this . textdata1 . equals ( other . textdata1 ) == false ) { return false ; } if ( this . intdata1 . equals ( other . intdata1 ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . textdata1 ) ; result . append ( "" ) ; result . append ( this . intdata1 ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempImportTarget19Df implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public void copyFrom ( ExportTempImportTarget19Df source ) { this . tempSid . copyFrom ( source . tempSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempImportTarget19Df other = ( ExportTempImportTarget19Df ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class Temp7 implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private StringOption textdata2 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata2 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata2 = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption duplicateFlg = new StringOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public Text getTextdata2 ( ) { return this . textdata2 . get ( ) ; } public void setTextdata2 ( Text textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public String getTextdata2AsString ( ) { return this . textdata2 . getAsString ( ) ; } public void setTextdata2AsString ( String textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public StringOption getTextdata2Option ( ) { return this . textdata2 ; } public void setTextdata2Option ( StringOption textdata2 ) { this . textdata2 . copyFrom ( textdata2 ) ; } public int getIntdata2 ( ) { return this . intdata2 . get ( ) ; } public void setIntdata2 ( int intdata2 ) { this . intdata2 . modify ( intdata2 ) ; } public IntOption getIntdata2Option ( ) { return this . intdata2 ; } public void setIntdata2Option ( IntOption intdata2 ) { this . intdata2 . copyFrom ( intdata2 ) ; } public DateTime getDatedata2 ( ) { return this . datedata2 . get ( ) ; } public void setDatedata2 ( DateTime datedata2 ) { this . datedata2 . modify ( datedata2 ) ; } public DateTimeOption getDatedata2Option ( ) { return this . datedata2 ; } public void setDatedata2Option ( DateTimeOption datedata2 ) { this . datedata2 . copyFrom ( datedata2 ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getDuplicateFlg ( ) { return this . duplicateFlg . get ( ) ; } public void setDuplicateFlg ( Text duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public String getDuplicateFlgAsString ( ) { return this . duplicateFlg . getAsString ( ) ; } public void setDuplicateFlgAsString ( String duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public StringOption getDuplicateFlgOption ( ) { return this . duplicateFlg ; } public void setDuplicateFlgOption ( StringOption duplicateFlg ) { this . duplicateFlg . copyFrom ( duplicateFlg ) ; } public void copyFrom ( Temp7 source ) { this . tempSid . copyFrom ( source . tempSid ) ; this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . textdata2 . copyFrom ( source . textdata2 ) ; this . intdata2 . copyFrom ( source . intdata2 ) ; this . datedata2 . copyFrom ( source . datedata2 ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . duplicateFlg . copyFrom ( source . duplicateFlg ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; sid . write ( out ) ; versionNo . write ( out ) ; textdata2 . write ( out ) ; intdata2 . write ( out ) ; datedata2 . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; duplicateFlg . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; sid . readFields ( in ) ; versionNo . readFields ( in ) ; textdata2 . readFields ( in ) ; intdata2 . readFields ( in ) ; datedata2 . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; duplicateFlg . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + textdata2 . hashCode ( ) ; result = prime * result + intdata2 . hashCode ( ) ; result = prime * result + datedata2 . hashCode ( ) ; result = prime * result + rgstDate . hashCode ( ) ; result = prime * result + updtDate . hashCode ( ) ; result = prime * result + duplicateFlg . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Temp7 other = ( Temp7 ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . textdata2 . equals ( other . textdata2 ) == false ) { return false ; } if ( this . intdata2 . equals ( other . intdata2 ) == false ) { return false ; } if ( this . datedata2 . equals ( other . datedata2 ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . duplicateFlg . equals ( other . duplicateFlg ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . textdata2 ) ; result . append ( "" ) ; result . append ( this . intdata2 ) ; result . append ( "" ) ; result . append ( this . datedata2 ) ; result . append ( "" ) ; result . append ( this . rgstDate ) ; result . append ( "" ) ; result . append ( this . updtDate ) ; result . append ( "" ) ; result . append ( this . duplicateFlg ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class TempImportTarget1Df implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public void copyFrom ( TempImportTarget1Df source ) { this . tempSid . copyFrom ( source . tempSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } TempImportTarget1Df other = ( TempImportTarget1Df ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempPurchaseTran1 implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private LongOption lineNo = new LongOption ( ) ; @ Property ( name = "" ) private DateOption deliveryDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption storeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tenantCode = new StringOption ( ) ; @ Property ( name = "" ) private LongOption netPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sellingPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private StringOption shipmentStoreCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption shipmentSalesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption deductionCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption accountCode = new StringOption ( ) ; @ Property ( name = "" ) private DateOption ownershipDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption ownershipFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDatetime ( ) { return this . rgstDatetime . get ( ) ; } public void setRgstDatetime ( DateTime rgstDatetime ) { this . rgstDatetime . modify ( rgstDatetime ) ; } public DateTimeOption getRgstDatetimeOption ( ) { return this . rgstDatetime ; } public void setRgstDatetimeOption ( DateTimeOption rgstDatetime ) { this . rgstDatetime . copyFrom ( rgstDatetime ) ; } public DateTime getUpdtDatetime ( ) { return this . updtDatetime . get ( ) ; } public void setUpdtDatetime ( DateTime updtDatetime ) { this . updtDatetime . modify ( updtDatetime ) ; } public DateTimeOption getUpdtDatetimeOption ( ) { return this . updtDatetime ; } public void setUpdtDatetimeOption ( DateTimeOption updtDatetime ) { this . updtDatetime . copyFrom ( updtDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public long getLineNo ( ) { return this . lineNo . get ( ) ; } public void setLineNo ( long lineNo ) { this . lineNo . modify ( lineNo ) ; } public LongOption getLineNoOption ( ) { return this . lineNo ; } public void setLineNoOption ( LongOption lineNo ) { this . lineNo . copyFrom ( lineNo ) ; } public Date getDeliveryDate ( ) { return this . deliveryDate . get ( ) ; } public void setDeliveryDate ( Date deliveryDate ) { this . deliveryDate . modify ( deliveryDate ) ; } public DateOption getDeliveryDateOption ( ) { return this . deliveryDate ; } public void setDeliveryDateOption ( DateOption deliveryDate ) { this . deliveryDate . copyFrom ( deliveryDate ) ; } public Text getStoreCode ( ) { return this . storeCode . get ( ) ; } public void setStoreCode ( Text storeCode ) { this . storeCode . modify ( storeCode ) ; } public String getStoreCodeAsString ( ) { return this . storeCode . getAsString ( ) ; } public void setStoreCodeAsString ( String storeCode ) { this . storeCode . modify ( storeCode ) ; } public StringOption getStoreCodeOption ( ) { return this . storeCode ; } public void setStoreCodeOption ( StringOption storeCode ) { this . storeCode . copyFrom ( storeCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Text getPurchaseTypeCode ( ) { return this . purchaseTypeCode . get ( ) ; } public void setPurchaseTypeCode ( Text purchaseTypeCode ) { this . purchaseTypeCode . modify ( purchaseTypeCode ) ; } public String getPurchaseTypeCodeAsString ( ) { return this . purchaseTypeCode . getAsString ( ) ; } public void setPurchaseTypeCodeAsString ( String purchaseTypeCode ) { this . purchaseTypeCode . modify ( purchaseTypeCode ) ; } public StringOption getPurchaseTypeCodeOption ( ) { return this . purchaseTypeCode ; } public void setPurchaseTypeCodeOption ( StringOption purchaseTypeCode ) { this . purchaseTypeCode . copyFrom ( purchaseTypeCode ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getTenantCode ( ) { return this . tenantCode . get ( ) ; } public void setTenantCode ( Text tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public String getTenantCodeAsString ( ) { return this . tenantCode . getAsString ( ) ; } public void setTenantCodeAsString ( String tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public StringOption getTenantCodeOption ( ) { return this . tenantCode ; } public void setTenantCodeOption ( StringOption tenantCode ) { this . tenantCode . copyFrom ( tenantCode ) ; } public long getNetPriceTotal ( ) { return this . netPriceTotal . get ( ) ; } public void setNetPriceTotal ( long netPriceTotal ) { this . netPriceTotal . modify ( netPriceTotal ) ; } public LongOption getNetPriceTotalOption ( ) { return this . netPriceTotal ; } public void setNetPriceTotalOption ( LongOption netPriceTotal ) { this . netPriceTotal . copyFrom ( netPriceTotal ) ; } public long getSellingPriceTotal ( ) { return this . sellingPriceTotal . get ( ) ; } public void setSellingPriceTotal ( long sellingPriceTotal ) { this . sellingPriceTotal . modify ( sellingPriceTotal ) ; } public LongOption getSellingPriceTotalOption ( ) { return this . sellingPriceTotal ; } public void setSellingPriceTotalOption ( LongOption sellingPriceTotal ) { this . sellingPriceTotal . copyFrom ( sellingPriceTotal ) ; } public Text getShipmentStoreCode ( ) { return this . shipmentStoreCode . get ( ) ; } public void setShipmentStoreCode ( Text shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public String getShipmentStoreCodeAsString ( ) { return this . shipmentStoreCode . getAsString ( ) ; } public void setShipmentStoreCodeAsString ( String shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public StringOption getShipmentStoreCodeOption ( ) { return this . shipmentStoreCode ; } public void setShipmentStoreCodeOption ( StringOption shipmentStoreCode ) { this . shipmentStoreCode . copyFrom ( shipmentStoreCode ) ; } public Text getShipmentSalesTypeCode ( ) { return this . shipmentSalesTypeCode . get ( ) ; } public void setShipmentSalesTypeCode ( Text shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public String getShipmentSalesTypeCodeAsString ( ) { return this . shipmentSalesTypeCode . getAsString ( ) ; } public void setShipmentSalesTypeCodeAsString ( String shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public StringOption getShipmentSalesTypeCodeOption ( ) { return this . shipmentSalesTypeCode ; } public void setShipmentSalesTypeCodeOption ( StringOption shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . copyFrom ( shipmentSalesTypeCode ) ; } public Text getDeductionCode ( ) { return this . deductionCode . get ( ) ; } public void setDeductionCode ( Text deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public String getDeductionCodeAsString ( ) { return this . deductionCode . getAsString ( ) ; } public void setDeductionCodeAsString ( String deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public StringOption getDeductionCodeOption ( ) { return this . deductionCode ; } public void setDeductionCodeOption ( StringOption deductionCode ) { this . deductionCode . copyFrom ( deductionCode ) ; } public Text getAccountCode ( ) { return this . accountCode . get ( ) ; } public void setAccountCode ( Text accountCode ) { this . accountCode . modify ( accountCode ) ; } public String getAccountCodeAsString ( ) { return this . accountCode . getAsString ( ) ; } public void setAccountCodeAsString ( String accountCode ) { this . accountCode . modify ( accountCode ) ; } public StringOption getAccountCodeOption ( ) { return this . accountCode ; } public void setAccountCodeOption ( StringOption accountCode ) { this . accountCode . copyFrom ( accountCode ) ; } public Date getOwnershipDate ( ) { return this . ownershipDate . get ( ) ; } public void setOwnershipDate ( Date ownershipDate ) { this . ownershipDate . modify ( ownershipDate ) ; } public DateOption getOwnershipDateOption ( ) { return this . ownershipDate ; } public void setOwnershipDateOption ( DateOption ownershipDate ) { this . ownershipDate . copyFrom ( ownershipDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public Text getOwnershipFlag ( ) { return this . ownershipFlag . get ( ) ; } public void setOwnershipFlag ( Text ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public String getOwnershipFlagAsString ( ) { return this . ownershipFlag . getAsString ( ) ; } public void setOwnershipFlagAsString ( String ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public StringOption getOwnershipFlagOption ( ) { return this . ownershipFlag ; } public void setOwnershipFlagOption ( StringOption ownershipFlag ) { this . ownershipFlag . copyFrom ( ownershipFlag ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public void copyFrom ( ExportTempPurchaseTran1 source ) { this . tempSid . copyFrom ( source . tempSid ) ; this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDatetime . copyFrom ( source . rgstDatetime ) ; this . updtDatetime . copyFrom ( source . updtDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . lineNo . copyFrom ( source . lineNo ) ; this . deliveryDate . copyFrom ( source . deliveryDate ) ; this . storeCode . copyFrom ( source . storeCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . purchaseTypeCode . copyFrom ( source . purchaseTypeCode ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . tenantCode . copyFrom ( source . tenantCode ) ; this . netPriceTotal . copyFrom ( source . netPriceTotal ) ; this . sellingPriceTotal . copyFrom ( source . sellingPriceTotal ) ; this . shipmentStoreCode . copyFrom ( source . shipmentStoreCode ) ; this . shipmentSalesTypeCode . copyFrom ( source . shipmentSalesTypeCode ) ; this . deductionCode . copyFrom ( source . deductionCode ) ; this . accountCode . copyFrom ( source . accountCode ) ; this . ownershipDate . copyFrom ( source . ownershipDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . ownershipFlag . copyFrom ( source . ownershipFlag ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; sid . write ( out ) ; versionNo . write ( out ) ; rgstDatetime . write ( out ) ; updtDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; lineNo . write ( out ) ; deliveryDate . write ( out ) ; storeCode . write ( out ) ; buyerCode . write ( out ) ; purchaseTypeCode . write ( out ) ; sellerCode . write ( out ) ; tenantCode . write ( out ) ; netPriceTotal . write ( out ) ; sellingPriceTotal . write ( out ) ; shipmentStoreCode . write ( out ) ; shipmentSalesTypeCode . write ( out ) ; deductionCode . write ( out ) ; accountCode . write ( out ) ; ownershipDate . write ( out ) ; cutoffDate . write ( out ) ; payoutDate . write ( out ) ; ownershipFlag . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDatetime . readFields ( in ) ; updtDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; lineNo . readFields ( in ) ; deliveryDate . readFields ( in ) ; storeCode . readFields ( in ) ; buyerCode . readFields ( in ) ; purchaseTypeCode . readFields ( in ) ; sellerCode . readFields ( in ) ; tenantCode . readFields ( in ) ; netPriceTotal . readFields ( in ) ; sellingPriceTotal . readFields ( in ) ; shipmentStoreCode . readFields ( in ) ; shipmentSalesTypeCode . readFields ( in ) ; deductionCode . readFields ( in ) ; accountCode . readFields ( in ) ; ownershipDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; ownershipFlag . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + rgstDatetime . hashCode ( ) ; result = prime * result + updtDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + lineNo . hashCode ( ) ; result = prime * result + deliveryDate . hashCode ( ) ; result = prime * result + storeCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + purchaseTypeCode . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + tenantCode . hashCode ( ) ; result = prime * result + netPriceTotal . hashCode ( ) ; result = prime * result + sellingPriceTotal . hashCode ( ) ; result = prime * result + shipmentStoreCode . hashCode ( ) ; result = prime * result + shipmentSalesTypeCode . hashCode ( ) ; result = prime * result + deductionCode . hashCode ( ) ; result = prime * result + accountCode . hashCode ( ) ; result = prime * result + ownershipDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + ownershipFlag . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempPurchaseTran1 other = ( ExportTempPurchaseTran1 ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDatetime . equals ( other . rgstDatetime ) == false ) { return false ; } if ( this . updtDatetime . equals ( other . updtDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . lineNo . equals ( other . lineNo ) == false ) { return false ; } if ( this . deliveryDate . equals ( other . deliveryDate ) == false ) { return false ; } if ( this . storeCode . equals ( other . storeCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . purchaseTypeCode . equals ( other . purchaseTypeCode ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . tenantCode . equals ( other . tenantCode ) == false ) { return false ; } if ( this . netPriceTotal . equals ( other . netPriceTotal ) == false ) { return false ; } if ( this . sellingPriceTotal . equals ( other . sellingPriceTotal ) == false ) { return false ; } if ( this . shipmentStoreCode . equals ( other . shipmentStoreCode ) == false ) { return false ; } if ( this . shipmentSalesTypeCode . equals ( other . shipmentSalesTypeCode ) == false ) { return false ; } if ( this . deductionCode . equals ( other . deductionCode ) == false ) { return false ; } if ( this . accountCode . equals ( other . accountCode ) == false ) { return false ; } if ( this . ownershipDate . equals ( other . ownershipDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . ownershipFlag . equals ( other . ownershipFlag ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . rgstDatetime ) ; result . append ( "" ) ; result . append ( this . updtDatetime ) ; result . append ( "" ) ; result . append ( this . purchaseNo ) ; result . append ( "" ) ; result . append ( this . purchaseType ) ; result . append ( "" ) ; result . append ( this . tradeType ) ; result . append ( "" ) ; result . append ( this . tradeNo ) ; result . append ( "" ) ; result . append ( this . lineNo ) ; result . append ( "" ) ; result . append ( this . deliveryDate ) ; result . append ( "" ) ; result . append ( this . storeCode ) ; result . append ( "" ) ; result . append ( this . buyerCode ) ; result . append ( "" ) ; result . append ( this . purchaseTypeCode ) ; result . append ( "" ) ; result . append ( this . sellerCode ) ; result . append ( "" ) ; result . append ( this . tenantCode ) ; result . append ( "" ) ; result . append ( this . netPriceTotal ) ; result . append ( "" ) ; result . append ( this . sellingPriceTotal ) ; result . append ( "" ) ; result . append ( this . shipmentStoreCode ) ; result . append ( "" ) ; result . append ( this . shipmentSalesTypeCode ) ; result . append ( "" ) ; result . append ( this . deductionCode ) ; result . append ( "" ) ; result . append ( this . accountCode ) ; result . append ( "" ) ; result . append ( this . ownershipDate ) ; result . append ( "" ) ; result . append ( this . cutoffDate ) ; result . append ( "" ) ; result . append ( this . payoutDate ) ; result . append ( "" ) ; result . append ( this . ownershipFlag ) ; result . append ( "" ) ; result . append ( this . cutoffFlag ) ; result . append ( "" ) ; result . append ( this . payoutFlag ) ; result . append ( "" ) ; result . append ( this . disposeNo ) ; result . append ( "" ) ; result . append ( this . disposeDate ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ImportTarget1 implements Writable , ThunderGateCacheSupport { @ Override public long __tgc__DataModelVersion ( ) { return ; } @ Override public long __tgc__SystemId ( ) { return sid . get ( ) ; } @ Override public String __tgc__TimestampColumn ( ) { return "" ; } @ Override public boolean __tgc__Deleted ( ) { return false ; } @ Property ( name = "" ) private final LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private final LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private final StringOption textdata1 = new StringOption ( ) ; @ Property ( name = "" ) private final IntOption intdata1 = new IntOption ( ) ; @ Property ( name = "" ) private final DateTimeOption datedata1 = new DateTimeOption ( ) ; @ Property ( name = "" ) private final DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private final DateTimeOption updtDate = new DateTimeOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public Text getTextdata1 ( ) { return this . textdata1 . get ( ) ; } public void setTextdata1 ( Text textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public String getTextdata1AsString ( ) { return this . textdata1 . getAsString ( ) ; } public void setTextdata1AsString ( String textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public StringOption getTextdata1Option ( ) { return this . textdata1 ; } public void setTextdata1Option ( StringOption textdata1 ) { this . textdata1 . copyFrom ( textdata1 ) ; } public int getIntdata1 ( ) { return this . intdata1 . get ( ) ; } public void setIntdata1 ( int intdata1 ) { this . intdata1 . modify ( intdata1 ) ; } public IntOption getIntdata1Option ( ) { return this . intdata1 ; } public void setIntdata1Option ( IntOption intdata1 ) { this . intdata1 . copyFrom ( intdata1 ) ; } public DateTime getDatedata1 ( ) { return this . datedata1 . get ( ) ; } public void setDatedata1 ( DateTime datedata1 ) { this . datedata1 . modify ( datedata1 ) ; } public DateTimeOption getDatedata1Option ( ) { return this . datedata1 ; } public void setDatedata1Option ( DateTimeOption datedata1 ) { this . datedata1 . copyFrom ( datedata1 ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public void copyFrom ( ImportTarget1 source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . textdata1 . copyFrom ( source . textdata1 ) ; this . intdata1 . copyFrom ( source . intdata1 ) ; this . datedata1 . copyFrom ( source . datedata1 ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; textdata1 . write ( out ) ; intdata1 . write ( out ) ; datedata1 . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; textdata1 . readFields ( in ) ; intdata1 . readFields ( in ) ; datedata1 . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + textdata1 . hashCode ( ) ; result = prime * result + intdata1 . hashCode ( ) ; result = prime * result + datedata1 . hashCode ( ) ; result = prime * result + rgstDate . hashCode ( ) ; result = prime * result + updtDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ImportTarget1 other = ( ImportTarget1 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . textdata1 . equals ( other . textdata1 ) == false ) { return false ; } if ( this . intdata1 . equals ( other . intdata1 ) == false ) { return false ; } if ( this . datedata1 . equals ( other . datedata1 ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . textdata1 ) ; result . append ( "" ) ; result . append ( this . intdata1 ) ; result . append ( "" ) ; result . append ( this . datedata1 ) ; result . append ( "" ) ; result . append ( this . rgstDate ) ; result . append ( "" ) ; result . append ( this . updtDate ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" } , primary = { "" , "" } ) @ SuppressWarnings ( "" ) public class LockedTable implements Writable { @ Property ( name = "" ) private IntOption jobflowSid = new IntOption ( ) ; @ Property ( name = "" ) private StringOption tableName = new StringOption ( ) ; public int getJobflowSid ( ) { return this . jobflowSid . get ( ) ; } public void setJobflowSid ( int jobflowSid ) { this . jobflowSid . modify ( jobflowSid ) ; } public IntOption getJobflowSidOption ( ) { return this . jobflowSid ; } public void setJobflowSidOption ( IntOption jobflowSid ) { this . jobflowSid . copyFrom ( jobflowSid ) ; } public Text getTableName ( ) { return this . tableName . get ( ) ; } public void setTableName ( Text tableName ) { this . tableName . modify ( tableName ) ; } public String getTableNameAsString ( ) { return this . tableName . getAsString ( ) ; } public void setTableNameAsString ( String tableName ) { this . tableName . modify ( tableName ) ; } public StringOption getTableNameOption ( ) { return this . tableName ; } public void setTableNameOption ( StringOption tableName ) { this . tableName . copyFrom ( tableName ) ; } public void copyFrom ( LockedTable source ) { this . jobflowSid . copyFrom ( source . jobflowSid ) ; this . tableName . copyFrom ( source . tableName ) ; } @ Override public void write ( DataOutput out ) throws IOException { jobflowSid . write ( out ) ; tableName . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { jobflowSid . readFields ( in ) ; tableName . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + jobflowSid . hashCode ( ) ; result = prime * result + tableName . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } LockedTable other = ( LockedTable ) obj ; if ( this . jobflowSid . equals ( other . jobflowSid ) == false ) { return false ; } if ( this . tableName . equals ( other . tableName ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . jobflowSid ) ; result . append ( "" ) ; result . append ( this . tableName ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class PurchaseTranError3 implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption errorCause = new StringOption ( ) ; @ Property ( name = "" ) private StringOption errorCode = new StringOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDatetime ( ) { return this . rgstDatetime . get ( ) ; } public void setRgstDatetime ( DateTime rgstDatetime ) { this . rgstDatetime . modify ( rgstDatetime ) ; } public DateTimeOption getRgstDatetimeOption ( ) { return this . rgstDatetime ; } public void setRgstDatetimeOption ( DateTimeOption rgstDatetime ) { this . rgstDatetime . copyFrom ( rgstDatetime ) ; } public DateTime getUpdtDatetime ( ) { return this . updtDatetime . get ( ) ; } public void setUpdtDatetime ( DateTime updtDatetime ) { this . updtDatetime . modify ( updtDatetime ) ; } public DateTimeOption getUpdtDatetimeOption ( ) { return this . updtDatetime ; } public void setUpdtDatetimeOption ( DateTimeOption updtDatetime ) { this . updtDatetime . copyFrom ( updtDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public Text getErrorCause ( ) { return this . errorCause . get ( ) ; } public void setErrorCause ( Text errorCause ) { this . errorCause . modify ( errorCause ) ; } public String getErrorCauseAsString ( ) { return this . errorCause . getAsString ( ) ; } public void setErrorCauseAsString ( String errorCause ) { this . errorCause . modify ( errorCause ) ; } public StringOption getErrorCauseOption ( ) { return this . errorCause ; } public void setErrorCauseOption ( StringOption errorCause ) { this . errorCause . copyFrom ( errorCause ) ; } public Text getErrorCode ( ) { return this . errorCode . get ( ) ; } public void setErrorCode ( Text errorCode ) { this . errorCode . modify ( errorCode ) ; } public String getErrorCodeAsString ( ) { return this . errorCode . getAsString ( ) ; } public void setErrorCodeAsString ( String errorCode ) { this . errorCode . modify ( errorCode ) ; } public StringOption getErrorCodeOption ( ) { return this . errorCode ; } public void setErrorCodeOption ( StringOption errorCode ) { this . errorCode . copyFrom ( errorCode ) ; } public void copyFrom ( PurchaseTranError3 source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDatetime . copyFrom ( source . rgstDatetime ) ; this . updtDatetime . copyFrom ( source . updtDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . errorCause . copyFrom ( source . errorCause ) ; this . errorCode . copyFrom ( source . errorCode ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; rgstDatetime . write ( out ) ; updtDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; errorCause . write ( out ) ; errorCode . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDatetime . readFields ( in ) ; updtDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; errorCause . readFields ( in ) ; errorCode . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + rgstDatetime . hashCode ( ) ; result = prime * result + updtDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + errorCause . hashCode ( ) ; result = prime * result + errorCode . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } PurchaseTranError3 other = ( PurchaseTranError3 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDatetime . equals ( other . rgstDatetime ) == false ) { return false ; } if ( this . updtDatetime . equals ( other . updtDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . errorCause . equals ( other . errorCause ) == false ) { return false ; } if ( this . errorCode . equals ( other . errorCode ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . rgstDatetime ) ; result . append ( "" ) ; result . append ( this . updtDatetime ) ; result . append ( "" ) ; result . append ( this . purchaseNo ) ; result . append ( "" ) ; result . append ( this . purchaseType ) ; result . append ( "" ) ; result . append ( this . tradeType ) ; result . append ( "" ) ; result . append ( this . tradeNo ) ; result . append ( "" ) ; result . append ( this . errorCause ) ; result . append ( "" ) ; result . append ( this . errorCode ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ImportTarget2 implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private StringOption textdata2 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata2 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata2 = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public Text getTextdata2 ( ) { return this . textdata2 . get ( ) ; } public void setTextdata2 ( Text textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public String getTextdata2AsString ( ) { return this . textdata2 . getAsString ( ) ; } public void setTextdata2AsString ( String textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public StringOption getTextdata2Option ( ) { return this . textdata2 ; } public void setTextdata2Option ( StringOption textdata2 ) { this . textdata2 . copyFrom ( textdata2 ) ; } public int getIntdata2 ( ) { return this . intdata2 . get ( ) ; } public void setIntdata2 ( int intdata2 ) { this . intdata2 . modify ( intdata2 ) ; } public IntOption getIntdata2Option ( ) { return this . intdata2 ; } public void setIntdata2Option ( IntOption intdata2 ) { this . intdata2 . copyFrom ( intdata2 ) ; } public DateTime getDatedata2 ( ) { return this . datedata2 . get ( ) ; } public void setDatedata2 ( DateTime datedata2 ) { this . datedata2 . modify ( datedata2 ) ; } public DateTimeOption getDatedata2Option ( ) { return this . datedata2 ; } public void setDatedata2Option ( DateTimeOption datedata2 ) { this . datedata2 . copyFrom ( datedata2 ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public void copyFrom ( ImportTarget2 source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . textdata2 . copyFrom ( source . textdata2 ) ; this . intdata2 . copyFrom ( source . intdata2 ) ; this . datedata2 . copyFrom ( source . datedata2 ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; textdata2 . write ( out ) ; intdata2 . write ( out ) ; datedata2 . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; textdata2 . readFields ( in ) ; intdata2 . readFields ( in ) ; datedata2 . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + textdata2 . hashCode ( ) ; result = prime * result + intdata2 . hashCode ( ) ; result = prime * result + datedata2 . hashCode ( ) ; result = prime * result + rgstDate . hashCode ( ) ; result = prime * result + updtDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ImportTarget2 other = ( ImportTarget2 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . textdata2 . equals ( other . textdata2 ) == false ) { return false ; } if ( this . intdata2 . equals ( other . intdata2 ) == false ) { return false ; } if ( this . datedata2 . equals ( other . datedata2 ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . textdata2 ) ; result . append ( "" ) ; result . append ( this . intdata2 ) ; result . append ( "" ) ; result . append ( this . datedata2 ) ; result . append ( "" ) ; result . append ( this . rgstDate ) ; result . append ( "" ) ; result . append ( this . updtDate ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" } , primary = { } ) @ SuppressWarnings ( "" ) public class ImportTarget1Error implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private StringOption textdata1 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata1 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata1 = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption errorCode = new StringOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public Text getTextdata1 ( ) { return this . textdata1 . get ( ) ; } public void setTextdata1 ( Text textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public String getTextdata1AsString ( ) { return this . textdata1 . getAsString ( ) ; } public void setTextdata1AsString ( String textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public StringOption getTextdata1Option ( ) { return this . textdata1 ; } public void setTextdata1Option ( StringOption textdata1 ) { this . textdata1 . copyFrom ( textdata1 ) ; } public int getIntdata1 ( ) { return this . intdata1 . get ( ) ; } public void setIntdata1 ( int intdata1 ) { this . intdata1 . modify ( intdata1 ) ; } public IntOption getIntdata1Option ( ) { return this . intdata1 ; } public void setIntdata1Option ( IntOption intdata1 ) { this . intdata1 . copyFrom ( intdata1 ) ; } public DateTime getDatedata1 ( ) { return this . datedata1 . get ( ) ; } public void setDatedata1 ( DateTime datedata1 ) { this . datedata1 . modify ( datedata1 ) ; } public DateTimeOption getDatedata1Option ( ) { return this . datedata1 ; } public void setDatedata1Option ( DateTimeOption datedata1 ) { this . datedata1 . copyFrom ( datedata1 ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getErrorCode ( ) { return this . errorCode . get ( ) ; } public void setErrorCode ( Text errorCode ) { this . errorCode . modify ( errorCode ) ; } public String getErrorCodeAsString ( ) { return this . errorCode . getAsString ( ) ; } public void setErrorCodeAsString ( String errorCode ) { this . errorCode . modify ( errorCode ) ; } public StringOption getErrorCodeOption ( ) { return this . errorCode ; } public void setErrorCodeOption ( StringOption errorCode ) { this . errorCode . copyFrom ( errorCode ) ; } public void copyFrom ( ImportTarget1Error source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . textdata1 . copyFrom ( source . textdata1 ) ; this . intdata1 . copyFrom ( source . intdata1 ) ; this . datedata1 . copyFrom ( source . datedata1 ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . errorCode . copyFrom ( source . errorCode ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; textdata1 . write ( out ) ; intdata1 . write ( out ) ; datedata1 . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; errorCode . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; textdata1 . readFields ( in ) ; intdata1 . readFields ( in ) ; datedata1 . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; errorCode . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + textdata1 . hashCode ( ) ; result = prime * result + intdata1 . hashCode ( ) ; result = prime * result + datedata1 . hashCode ( ) ; result = prime * result + rgstDate . hashCode ( ) ; result = prime * result + updtDate . hashCode ( ) ; result = prime * result + errorCode . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ImportTarget1Error other = ( ImportTarget1Error ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . textdata1 . equals ( other . textdata1 ) == false ) { return false ; } if ( this . intdata1 . equals ( other . intdata1 ) == false ) { return false ; } if ( this . datedata1 . equals ( other . datedata1 ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . errorCode . equals ( other . errorCode ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . textdata1 ) ; result . append ( "" ) ; result . append ( this . intdata1 ) ; result . append ( "" ) ; result . append ( this . datedata1 ) ; result . append ( "" ) ; result . append ( this . rgstDate ) ; result . append ( "" ) ; result . append ( this . updtDate ) ; result . append ( "" ) ; result . append ( this . errorCode ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class PurchaseTranError implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private LongOption lineNo = new LongOption ( ) ; @ Property ( name = "" ) private DateOption deliveryDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption storeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tenantCode = new StringOption ( ) ; @ Property ( name = "" ) private LongOption netPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sellingPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private StringOption shipmentStoreCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption shipmentSalesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption deductionCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption accountCode = new StringOption ( ) ; @ Property ( name = "" ) private DateOption ownershipDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption ownershipFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDatetime ( ) { return this . rgstDatetime . get ( ) ; } public void setRgstDatetime ( DateTime rgstDatetime ) { this . rgstDatetime . modify ( rgstDatetime ) ; } public DateTimeOption getRgstDatetimeOption ( ) { return this . rgstDatetime ; } public void setRgstDatetimeOption ( DateTimeOption rgstDatetime ) { this . rgstDatetime . copyFrom ( rgstDatetime ) ; } public DateTime getUpdtDatetime ( ) { return this . updtDatetime . get ( ) ; } public void setUpdtDatetime ( DateTime updtDatetime ) { this . updtDatetime . modify ( updtDatetime ) ; } public DateTimeOption getUpdtDatetimeOption ( ) { return this . updtDatetime ; } public void setUpdtDatetimeOption ( DateTimeOption updtDatetime ) { this . updtDatetime . copyFrom ( updtDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public long getLineNo ( ) { return this . lineNo . get ( ) ; } public void setLineNo ( long lineNo ) { this . lineNo . modify ( lineNo ) ; } public LongOption getLineNoOption ( ) { return this . lineNo ; } public void setLineNoOption ( LongOption lineNo ) { this . lineNo . copyFrom ( lineNo ) ; } public Date getDeliveryDate ( ) { return this . deliveryDate . get ( ) ; } public void setDeliveryDate ( Date deliveryDate ) { this . deliveryDate . modify ( deliveryDate ) ; } public DateOption getDeliveryDateOption ( ) { return this . deliveryDate ; } public void setDeliveryDateOption ( DateOption deliveryDate ) { this . deliveryDate . copyFrom ( deliveryDate ) ; } public Text getStoreCode ( ) { return this . storeCode . get ( ) ; } public void setStoreCode ( Text storeCode ) { this . storeCode . modify ( storeCode ) ; } public String getStoreCodeAsString ( ) { return this . storeCode . getAsString ( ) ; } public void setStoreCodeAsString ( String storeCode ) { this . storeCode . modify ( storeCode ) ; } public StringOption getStoreCodeOption ( ) { return this . storeCode ; } public void setStoreCodeOption ( StringOption storeCode ) { this . storeCode . copyFrom ( storeCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Text getPurchaseTypeCode ( ) { return this . purchaseTypeCode . get ( ) ; } public void setPurchaseTypeCode ( Text purchaseTypeCode ) { this . purchaseTypeCode . modify ( purchaseTypeCode ) ; } public String getPurchaseTypeCodeAsString ( ) { return this . purchaseTypeCode . getAsString ( ) ; } public void setPurchaseTypeCodeAsString ( String purchaseTypeCode ) { this . purchaseTypeCode . modify ( purchaseTypeCode ) ; } public StringOption getPurchaseTypeCodeOption ( ) { return this . purchaseTypeCode ; } public void setPurchaseTypeCodeOption ( StringOption purchaseTypeCode ) { this . purchaseTypeCode . copyFrom ( purchaseTypeCode ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getTenantCode ( ) { return this . tenantCode . get ( ) ; } public void setTenantCode ( Text tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public String getTenantCodeAsString ( ) { return this . tenantCode . getAsString ( ) ; } public void setTenantCodeAsString ( String tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public StringOption getTenantCodeOption ( ) { return this . tenantCode ; } public void setTenantCodeOption ( StringOption tenantCode ) { this . tenantCode . copyFrom ( tenantCode ) ; } public long getNetPriceTotal ( ) { return this . netPriceTotal . get ( ) ; } public void setNetPriceTotal ( long netPriceTotal ) { this . netPriceTotal . modify ( netPriceTotal ) ; } public LongOption getNetPriceTotalOption ( ) { return this . netPriceTotal ; } public void setNetPriceTotalOption ( LongOption netPriceTotal ) { this . netPriceTotal . copyFrom ( netPriceTotal ) ; } public long getSellingPriceTotal ( ) { return this . sellingPriceTotal . get ( ) ; } public void setSellingPriceTotal ( long sellingPriceTotal ) { this . sellingPriceTotal . modify ( sellingPriceTotal ) ; } public LongOption getSellingPriceTotalOption ( ) { return this . sellingPriceTotal ; } public void setSellingPriceTotalOption ( LongOption sellingPriceTotal ) { this . sellingPriceTotal . copyFrom ( sellingPriceTotal ) ; } public Text getShipmentStoreCode ( ) { return this . shipmentStoreCode . get ( ) ; } public void setShipmentStoreCode ( Text shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public String getShipmentStoreCodeAsString ( ) { return this . shipmentStoreCode . getAsString ( ) ; } public void setShipmentStoreCodeAsString ( String shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public StringOption getShipmentStoreCodeOption ( ) { return this . shipmentStoreCode ; } public void setShipmentStoreCodeOption ( StringOption shipmentStoreCode ) { this . shipmentStoreCode . copyFrom ( shipmentStoreCode ) ; } public Text getShipmentSalesTypeCode ( ) { return this . shipmentSalesTypeCode . get ( ) ; } public void setShipmentSalesTypeCode ( Text shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public String getShipmentSalesTypeCodeAsString ( ) { return this . shipmentSalesTypeCode . getAsString ( ) ; } public void setShipmentSalesTypeCodeAsString ( String shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public StringOption getShipmentSalesTypeCodeOption ( ) { return this . shipmentSalesTypeCode ; } public void setShipmentSalesTypeCodeOption ( StringOption shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . copyFrom ( shipmentSalesTypeCode ) ; } public Text getDeductionCode ( ) { return this . deductionCode . get ( ) ; } public void setDeductionCode ( Text deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public String getDeductionCodeAsString ( ) { return this . deductionCode . getAsString ( ) ; } public void setDeductionCodeAsString ( String deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public StringOption getDeductionCodeOption ( ) { return this . deductionCode ; } public void setDeductionCodeOption ( StringOption deductionCode ) { this . deductionCode . copyFrom ( deductionCode ) ; } public Text getAccountCode ( ) { return this . accountCode . get ( ) ; } public void setAccountCode ( Text accountCode ) { this . accountCode . modify ( accountCode ) ; } public String getAccountCodeAsString ( ) { return this . accountCode . getAsString ( ) ; } public void setAccountCodeAsString ( String accountCode ) { this . accountCode . modify ( accountCode ) ; } public StringOption getAccountCodeOption ( ) { return this . accountCode ; } public void setAccountCodeOption ( StringOption accountCode ) { this . accountCode . copyFrom ( accountCode ) ; } public Date getOwnershipDate ( ) { return this . ownershipDate . get ( ) ; } public void setOwnershipDate ( Date ownershipDate ) { this . ownershipDate . modify ( ownershipDate ) ; } public DateOption getOwnershipDateOption ( ) { return this . ownershipDate ; } public void setOwnershipDateOption ( DateOption ownershipDate ) { this . ownershipDate . copyFrom ( ownershipDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public Text getOwnershipFlag ( ) { return this . ownershipFlag . get ( ) ; } public void setOwnershipFlag ( Text ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public String getOwnershipFlagAsString ( ) { return this . ownershipFlag . getAsString ( ) ; } public void setOwnershipFlagAsString ( String ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public StringOption getOwnershipFlagOption ( ) { return this . ownershipFlag ; } public void setOwnershipFlagOption ( StringOption ownershipFlag ) { this . ownershipFlag . copyFrom ( ownershipFlag ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public void copyFrom ( PurchaseTranError source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDatetime . copyFrom ( source . rgstDatetime ) ; this . updtDatetime . copyFrom ( source . updtDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . lineNo . copyFrom ( source . lineNo ) ; this . deliveryDate . copyFrom ( source . deliveryDate ) ; this . storeCode . copyFrom ( source . storeCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . purchaseTypeCode . copyFrom ( source . purchaseTypeCode ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . tenantCode . copyFrom ( source . tenantCode ) ; this . netPriceTotal . copyFrom ( source . netPriceTotal ) ; this . sellingPriceTotal . copyFrom ( source . sellingPriceTotal ) ; this . shipmentStoreCode . copyFrom ( source . shipmentStoreCode ) ; this . shipmentSalesTypeCode . copyFrom ( source . shipmentSalesTypeCode ) ; this . deductionCode . copyFrom ( source . deductionCode ) ; this . accountCode . copyFrom ( source . accountCode ) ; this . ownershipDate . copyFrom ( source . ownershipDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . ownershipFlag . copyFrom ( source . ownershipFlag ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; rgstDatetime . write ( out ) ; updtDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; lineNo . write ( out ) ; deliveryDate . write ( out ) ; storeCode . write ( out ) ; buyerCode . write ( out ) ; purchaseTypeCode . write ( out ) ; sellerCode . write ( out ) ; tenantCode . write ( out ) ; netPriceTotal . write ( out ) ; sellingPriceTotal . write ( out ) ; shipmentStoreCode . write ( out ) ; shipmentSalesTypeCode . write ( out ) ; deductionCode . write ( out ) ; accountCode . write ( out ) ; ownershipDate . write ( out ) ; cutoffDate . write ( out ) ; payoutDate . write ( out ) ; ownershipFlag . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDatetime . readFields ( in ) ; updtDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; lineNo . readFields ( in ) ; deliveryDate . readFields ( in ) ; storeCode . readFields ( in ) ; buyerCode . readFields ( in ) ; purchaseTypeCode . readFields ( in ) ; sellerCode . readFields ( in ) ; tenantCode . readFields ( in ) ; netPriceTotal . readFields ( in ) ; sellingPriceTotal . readFields ( in ) ; shipmentStoreCode . readFields ( in ) ; shipmentSalesTypeCode . readFields ( in ) ; deductionCode . readFields ( in ) ; accountCode . readFields ( in ) ; ownershipDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; ownershipFlag . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + rgstDatetime . hashCode ( ) ; result = prime * result + updtDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + lineNo . hashCode ( ) ; result = prime * result + deliveryDate . hashCode ( ) ; result = prime * result + storeCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + purchaseTypeCode . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + tenantCode . hashCode ( ) ; result = prime * result + netPriceTotal . hashCode ( ) ; result = prime * result + sellingPriceTotal . hashCode ( ) ; result = prime * result + shipmentStoreCode . hashCode ( ) ; result = prime * result + shipmentSalesTypeCode . hashCode ( ) ; result = prime * result + deductionCode . hashCode ( ) ; result = prime * result + accountCode . hashCode ( ) ; result = prime * result + ownershipDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + ownershipFlag . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } PurchaseTranError other = ( PurchaseTranError ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDatetime . equals ( other . rgstDatetime ) == false ) { return false ; } if ( this . updtDatetime . equals ( other . updtDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . lineNo . equals ( other . lineNo ) == false ) { return false ; } if ( this . deliveryDate . equals ( other . deliveryDate ) == false ) { return false ; } if ( this . storeCode . equals ( other . storeCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . purchaseTypeCode . equals ( other . purchaseTypeCode ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . tenantCode . equals ( other . tenantCode ) == false ) { return false ; } if ( this . netPriceTotal . equals ( other . netPriceTotal ) == false ) { return false ; } if ( this . sellingPriceTotal . equals ( other . sellingPriceTotal ) == false ) { return false ; } if ( this . shipmentStoreCode . equals ( other . shipmentStoreCode ) == false ) { return false ; } if ( this . shipmentSalesTypeCode . equals ( other . shipmentSalesTypeCode ) == false ) { return false ; } if ( this . deductionCode . equals ( other . deductionCode ) == false ) { return false ; } if ( this . accountCode . equals ( other . accountCode ) == false ) { return false ; } if ( this . ownershipDate . equals ( other . ownershipDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . ownershipFlag . equals ( other . ownershipFlag ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . rgstDatetime ) ; result . append ( "" ) ; result . append ( this . updtDatetime ) ; result . append ( "" ) ; result . append ( this . purchaseNo ) ; result . append ( "" ) ; result . append ( this . purchaseType ) ; result . append ( "" ) ; result . append ( this . tradeType ) ; result . append ( "" ) ; result . append ( this . tradeNo ) ; result . append ( "" ) ; result . append ( this . lineNo ) ; result . append ( "" ) ; result . append ( this . deliveryDate ) ; result . append ( "" ) ; result . append ( this . storeCode ) ; result . append ( "" ) ; result . append ( this . buyerCode ) ; result . append ( "" ) ; result . append ( this . purchaseTypeCode ) ; result . append ( "" ) ; result . append ( this . sellerCode ) ; result . append ( "" ) ; result . append ( this . tenantCode ) ; result . append ( "" ) ; result . append ( this . netPriceTotal ) ; result . append ( "" ) ; result . append ( this . sellingPriceTotal ) ; result . append ( "" ) ; result . append ( this . shipmentStoreCode ) ; result . append ( "" ) ; result . append ( this . shipmentSalesTypeCode ) ; result . append ( "" ) ; result . append ( this . deductionCode ) ; result . append ( "" ) ; result . append ( this . accountCode ) ; result . append ( "" ) ; result . append ( this . ownershipDate ) ; result . append ( "" ) ; result . append ( this . cutoffDate ) ; result . append ( "" ) ; result . append ( this . payoutDate ) ; result . append ( "" ) ; result . append ( this . ownershipFlag ) ; result . append ( "" ) ; result . append ( this . cutoffFlag ) ; result . append ( "" ) ; result . append ( this . payoutFlag ) ; result . append ( "" ) ; result . append ( this . disposeNo ) ; result . append ( "" ) ; result . append ( this . disposeDate ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" } , primary = { } ) @ SuppressWarnings ( "" ) public class ImportTarget2Error implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private StringOption textdata2 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata2 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata2 = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption errorCode = new StringOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public Text getTextdata2 ( ) { return this . textdata2 . get ( ) ; } public void setTextdata2 ( Text textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public String getTextdata2AsString ( ) { return this . textdata2 . getAsString ( ) ; } public void setTextdata2AsString ( String textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public StringOption getTextdata2Option ( ) { return this . textdata2 ; } public void setTextdata2Option ( StringOption textdata2 ) { this . textdata2 . copyFrom ( textdata2 ) ; } public int getIntdata2 ( ) { return this . intdata2 . get ( ) ; } public void setIntdata2 ( int intdata2 ) { this . intdata2 . modify ( intdata2 ) ; } public IntOption getIntdata2Option ( ) { return this . intdata2 ; } public void setIntdata2Option ( IntOption intdata2 ) { this . intdata2 . copyFrom ( intdata2 ) ; } public DateTime getDatedata2 ( ) { return this . datedata2 . get ( ) ; } public void setDatedata2 ( DateTime datedata2 ) { this . datedata2 . modify ( datedata2 ) ; } public DateTimeOption getDatedata2Option ( ) { return this . datedata2 ; } public void setDatedata2Option ( DateTimeOption datedata2 ) { this . datedata2 . copyFrom ( datedata2 ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getErrorCode ( ) { return this . errorCode . get ( ) ; } public void setErrorCode ( Text errorCode ) { this . errorCode . modify ( errorCode ) ; } public String getErrorCodeAsString ( ) { return this . errorCode . getAsString ( ) ; } public void setErrorCodeAsString ( String errorCode ) { this . errorCode . modify ( errorCode ) ; } public StringOption getErrorCodeOption ( ) { return this . errorCode ; } public void setErrorCodeOption ( StringOption errorCode ) { this . errorCode . copyFrom ( errorCode ) ; } public void copyFrom ( ImportTarget2Error source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . textdata2 . copyFrom ( source . textdata2 ) ; this . intdata2 . copyFrom ( source . intdata2 ) ; this . datedata2 . copyFrom ( source . datedata2 ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . errorCode . copyFrom ( source . errorCode ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; textdata2 . write ( out ) ; intdata2 . write ( out ) ; datedata2 . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; errorCode . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; textdata2 . readFields ( in ) ; intdata2 . readFields ( in ) ; datedata2 . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; errorCode . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + textdata2 . hashCode ( ) ; result = prime * result + intdata2 . hashCode ( ) ; result = prime * result + datedata2 . hashCode ( ) ; result = prime * result + rgstDate . hashCode ( ) ; result = prime * result + updtDate . hashCode ( ) ; result = prime * result + errorCode . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ImportTarget2Error other = ( ImportTarget2Error ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . textdata2 . equals ( other . textdata2 ) == false ) { return false ; } if ( this . intdata2 . equals ( other . intdata2 ) == false ) { return false ; } if ( this . datedata2 . equals ( other . datedata2 ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . errorCode . equals ( other . errorCode ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . textdata2 ) ; result . append ( "" ) ; result . append ( this . intdata2 ) ; result . append ( "" ) ; result . append ( this . datedata2 ) ; result . append ( "" ) ; result . append ( this . rgstDate ) ; result . append ( "" ) ; result . append ( this . updtDate ) ; result . append ( "" ) ; result . append ( this . errorCode ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class TempImportTarget2 implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private StringOption textdata2 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata2 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata2 = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption duplicateFlg = new StringOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public Text getTextdata2 ( ) { return this . textdata2 . get ( ) ; } public void setTextdata2 ( Text textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public String getTextdata2AsString ( ) { return this . textdata2 . getAsString ( ) ; } public void setTextdata2AsString ( String textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public StringOption getTextdata2Option ( ) { return this . textdata2 ; } public void setTextdata2Option ( StringOption textdata2 ) { this . textdata2 . copyFrom ( textdata2 ) ; } public int getIntdata2 ( ) { return this . intdata2 . get ( ) ; } public void setIntdata2 ( int intdata2 ) { this . intdata2 . modify ( intdata2 ) ; } public IntOption getIntdata2Option ( ) { return this . intdata2 ; } public void setIntdata2Option ( IntOption intdata2 ) { this . intdata2 . copyFrom ( intdata2 ) ; } public DateTime getDatedata2 ( ) { return this . datedata2 . get ( ) ; } public void setDatedata2 ( DateTime datedata2 ) { this . datedata2 . modify ( datedata2 ) ; } public DateTimeOption getDatedata2Option ( ) { return this . datedata2 ; } public void setDatedata2Option ( DateTimeOption datedata2 ) { this . datedata2 . copyFrom ( datedata2 ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getDuplicateFlg ( ) { return this . duplicateFlg . get ( ) ; } public void setDuplicateFlg ( Text duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public String getDuplicateFlgAsString ( ) { return this . duplicateFlg . getAsString ( ) ; } public void setDuplicateFlgAsString ( String duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public StringOption getDuplicateFlgOption ( ) { return this . duplicateFlg ; } public void setDuplicateFlgOption ( StringOption duplicateFlg ) { this . duplicateFlg . copyFrom ( duplicateFlg ) ; } public void copyFrom ( TempImportTarget2 source ) { this . tempSid . copyFrom ( source . tempSid ) ; this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . textdata2 . copyFrom ( source . textdata2 ) ; this . intdata2 . copyFrom ( source . intdata2 ) ; this . datedata2 . copyFrom ( source . datedata2 ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . duplicateFlg . copyFrom ( source . duplicateFlg ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; sid . write ( out ) ; versionNo . write ( out ) ; textdata2 . write ( out ) ; intdata2 . write ( out ) ; datedata2 . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; duplicateFlg . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; sid . readFields ( in ) ; versionNo . readFields ( in ) ; textdata2 . readFields ( in ) ; intdata2 . readFields ( in ) ; datedata2 . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; duplicateFlg . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + textdata2 . hashCode ( ) ; result = prime * result + intdata2 . hashCode ( ) ; result = prime * result + datedata2 . hashCode ( ) ; result = prime * result + rgstDate . hashCode ( ) ; result = prime * result + updtDate . hashCode ( ) ; result = prime * result + duplicateFlg . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } TempImportTarget2 other = ( TempImportTarget2 ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . textdata2 . equals ( other . textdata2 ) == false ) { return false ; } if ( this . intdata2 . equals ( other . intdata2 ) == false ) { return false ; } if ( this . datedata2 . equals ( other . datedata2 ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . duplicateFlg . equals ( other . duplicateFlg ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . textdata2 ) ; result . append ( "" ) ; result . append ( this . intdata2 ) ; result . append ( "" ) ; result . append ( this . datedata2 ) ; result . append ( "" ) ; result . append ( this . rgstDate ) ; result . append ( "" ) ; result . append ( this . updtDate ) ; result . append ( "" ) ; result . append ( this . duplicateFlg ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class CacheFiles implements Writable { @ Property ( name = "" ) private LongOption cacheFileSid = new LongOption ( ) ; @ Property ( name = "" ) private StringOption filePath = new StringOption ( ) ; @ Property ( name = "" ) private DateTimeOption expirationDatetime = new DateTimeOption ( ) ; public long getCacheFileSid ( ) { return this . cacheFileSid . get ( ) ; } public void setCacheFileSid ( long cacheFileSid ) { this . cacheFileSid . modify ( cacheFileSid ) ; } public LongOption getCacheFileSidOption ( ) { return this . cacheFileSid ; } public void setCacheFileSidOption ( LongOption cacheFileSid ) { this . cacheFileSid . copyFrom ( cacheFileSid ) ; } public Text getFilePath ( ) { return this . filePath . get ( ) ; } public void setFilePath ( Text filePath ) { this . filePath . modify ( filePath ) ; } public String getFilePathAsString ( ) { return this . filePath . getAsString ( ) ; } public void setFilePathAsString ( String filePath ) { this . filePath . modify ( filePath ) ; } public StringOption getFilePathOption ( ) { return this . filePath ; } public void setFilePathOption ( StringOption filePath ) { this . filePath . copyFrom ( filePath ) ; } public DateTime getExpirationDatetime ( ) { return this . expirationDatetime . get ( ) ; } public void setExpirationDatetime ( DateTime expirationDatetime ) { this . expirationDatetime . modify ( expirationDatetime ) ; } public DateTimeOption getExpirationDatetimeOption ( ) { return this . expirationDatetime ; } public void setExpirationDatetimeOption ( DateTimeOption expirationDatetime ) { this . expirationDatetime . copyFrom ( expirationDatetime ) ; } public void copyFrom ( CacheFiles source ) { this . cacheFileSid . copyFrom ( source . cacheFileSid ) ; this . filePath . copyFrom ( source . filePath ) ; this . expirationDatetime . copyFrom ( source . expirationDatetime ) ; } @ Override public void write ( DataOutput out ) throws IOException { cacheFileSid . write ( out ) ; filePath . write ( out ) ; expirationDatetime . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { cacheFileSid . readFields ( in ) ; filePath . readFields ( in ) ; expirationDatetime . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + cacheFileSid . hashCode ( ) ; result = prime * result + filePath . hashCode ( ) ; result = prime * result + expirationDatetime . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } CacheFiles other = ( CacheFiles ) obj ; if ( this . cacheFileSid . equals ( other . cacheFileSid ) == false ) { return false ; } if ( this . filePath . equals ( other . filePath ) == false ) { return false ; } if ( this . expirationDatetime . equals ( other . expirationDatetime ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . cacheFileSid ) ; result . append ( "" ) ; result . append ( this . filePath ) ; result . append ( "" ) ; result . append ( this . expirationDatetime ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class RunningJobflows implements Writable { @ Property ( name = "" ) private LongOption jobflowSid = new LongOption ( ) ; @ Property ( name = "" ) private StringOption batchId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption jobflowId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption targetName = new StringOption ( ) ; @ Property ( name = "" ) private StringOption executionId = new StringOption ( ) ; @ Property ( name = "" ) private DateTimeOption expectedCompletionDatetime = new DateTimeOption ( ) ; public long getJobflowSid ( ) { return this . jobflowSid . get ( ) ; } public void setJobflowSid ( long jobflowSid ) { this . jobflowSid . modify ( jobflowSid ) ; } public LongOption getJobflowSidOption ( ) { return this . jobflowSid ; } public void setJobflowSidOption ( LongOption jobflowSid ) { this . jobflowSid . copyFrom ( jobflowSid ) ; } public Text getBatchId ( ) { return this . batchId . get ( ) ; } public void setBatchId ( Text batchId ) { this . batchId . modify ( batchId ) ; } public String getBatchIdAsString ( ) { return this . batchId . getAsString ( ) ; } public void setBatchIdAsString ( String batchId ) { this . batchId . modify ( batchId ) ; } public StringOption getBatchIdOption ( ) { return this . batchId ; } public void setBatchIdOption ( StringOption batchId ) { this . batchId . copyFrom ( batchId ) ; } public Text getJobflowId ( ) { return this . jobflowId . get ( ) ; } public void setJobflowId ( Text jobflowId ) { this . jobflowId . modify ( jobflowId ) ; } public String getJobflowIdAsString ( ) { return this . jobflowId . getAsString ( ) ; } public void setJobflowIdAsString ( String jobflowId ) { this . jobflowId . modify ( jobflowId ) ; } public StringOption getJobflowIdOption ( ) { return this . jobflowId ; } public void setJobflowIdOption ( StringOption jobflowId ) { this . jobflowId . copyFrom ( jobflowId ) ; } public Text getTargetName ( ) { return this . targetName . get ( ) ; } public void setTargetName ( Text targetName ) { this . targetName . modify ( targetName ) ; } public String getTargetNameAsString ( ) { return this . targetName . getAsString ( ) ; } public void setTargetNameAsString ( String targetName ) { this . targetName . modify ( targetName ) ; } public StringOption getTargetNameOption ( ) { return this . targetName ; } public void setTargetNameOption ( StringOption targetName ) { this . targetName . copyFrom ( targetName ) ; } public Text getExecutionId ( ) { return this . executionId . get ( ) ; } public void setExecutionId ( Text executionId ) { this . executionId . modify ( executionId ) ; } public String getExecutionIdAsString ( ) { return this . executionId . getAsString ( ) ; } public void setExecutionIdAsString ( String executionId ) { this . executionId . modify ( executionId ) ; } public StringOption getExecutionIdOption ( ) { return this . executionId ; } public void setExecutionIdOption ( StringOption executionId ) { this . executionId . copyFrom ( executionId ) ; } public DateTime getExpectedCompletionDatetime ( ) { return this . expectedCompletionDatetime . get ( ) ; } public void setExpectedCompletionDatetime ( DateTime expectedCompletionDatetime ) { this . expectedCompletionDatetime . modify ( expectedCompletionDatetime ) ; } public DateTimeOption getExpectedCompletionDatetimeOption ( ) { return this . expectedCompletionDatetime ; } public void setExpectedCompletionDatetimeOption ( DateTimeOption expectedCompletionDatetime ) { this . expectedCompletionDatetime . copyFrom ( expectedCompletionDatetime ) ; } public void copyFrom ( RunningJobflows source ) { this . jobflowSid . copyFrom ( source . jobflowSid ) ; this . batchId . copyFrom ( source . batchId ) ; this . jobflowId . copyFrom ( source . jobflowId ) ; this . targetName . copyFrom ( source . targetName ) ; this . executionId . copyFrom ( source . executionId ) ; this . expectedCompletionDatetime . copyFrom ( source . expectedCompletionDatetime ) ; } @ Override public void write ( DataOutput out ) throws IOException { jobflowSid . write ( out ) ; batchId . write ( out ) ; jobflowId . write ( out ) ; targetName . write ( out ) ; executionId . write ( out ) ; expectedCompletionDatetime . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { jobflowSid . readFields ( in ) ; batchId . readFields ( in ) ; jobflowId . readFields ( in ) ; targetName . readFields ( in ) ; executionId . readFields ( in ) ; expectedCompletionDatetime . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + jobflowSid . hashCode ( ) ; result = prime * result + batchId . hashCode ( ) ; result = prime * result + jobflowId . hashCode ( ) ; result = prime * result + targetName . hashCode ( ) ; result = prime * result + executionId . hashCode ( ) ; result = prime * result + expectedCompletionDatetime . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } RunningJobflows other = ( RunningJobflows ) obj ; if ( this . jobflowSid . equals ( other . jobflowSid ) == false ) { return false ; } if ( this . batchId . equals ( other . batchId ) == false ) { return false ; } if ( this . jobflowId . equals ( other . jobflowId ) == false ) { return false ; } if ( this . targetName . equals ( other . targetName ) == false ) { return false ; } if ( this . executionId . equals ( other . executionId ) == false ) { return false ; } if ( this . expectedCompletionDatetime . equals ( other . expectedCompletionDatetime ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . jobflowSid ) ; result . append ( "" ) ; result . append ( this . batchId ) ; result . append ( "" ) ; result . append ( this . jobflowId ) ; result . append ( "" ) ; result . append ( this . targetName ) ; result . append ( "" ) ; result . append ( this . executionId ) ; result . append ( "" ) ; result . append ( this . expectedCompletionDatetime ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempImportTarget19 implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption duplicateFlg = new StringOption ( ) ; @ Property ( name = "" ) private StringOption textdata1 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata2 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata2 = new DateTimeOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getDuplicateFlg ( ) { return this . duplicateFlg . get ( ) ; } public void setDuplicateFlg ( Text duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public String getDuplicateFlgAsString ( ) { return this . duplicateFlg . getAsString ( ) ; } public void setDuplicateFlgAsString ( String duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public StringOption getDuplicateFlgOption ( ) { return this . duplicateFlg ; } public void setDuplicateFlgOption ( StringOption duplicateFlg ) { this . duplicateFlg . copyFrom ( duplicateFlg ) ; } public Text getTextdata1 ( ) { return this . textdata1 . get ( ) ; } public void setTextdata1 ( Text textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public String getTextdata1AsString ( ) { return this . textdata1 . getAsString ( ) ; } public void setTextdata1AsString ( String textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public StringOption getTextdata1Option ( ) { return this . textdata1 ; } public void setTextdata1Option ( StringOption textdata1 ) { this . textdata1 . copyFrom ( textdata1 ) ; } public int getIntdata2 ( ) { return this . intdata2 . get ( ) ; } public void setIntdata2 ( int intdata2 ) { this . intdata2 . modify ( intdata2 ) ; } public IntOption getIntdata2Option ( ) { return this . intdata2 ; } public void setIntdata2Option ( IntOption intdata2 ) { this . intdata2 . copyFrom ( intdata2 ) ; } public DateTime getDatedata2 ( ) { return this . datedata2 . get ( ) ; } public void setDatedata2 ( DateTime datedata2 ) { this . datedata2 . modify ( datedata2 ) ; } public DateTimeOption getDatedata2Option ( ) { return this . datedata2 ; } public void setDatedata2Option ( DateTimeOption datedata2 ) { this . datedata2 . copyFrom ( datedata2 ) ; } public void copyFrom ( ExportTempImportTarget19 source ) { this . tempSid . copyFrom ( source . tempSid ) ; this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . duplicateFlg . copyFrom ( source . duplicateFlg ) ; this . textdata1 . copyFrom ( source . textdata1 ) ; this . intdata2 . copyFrom ( source . intdata2 ) ; this . datedata2 . copyFrom ( source . datedata2 ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; sid . write ( out ) ; versionNo . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; duplicateFlg . write ( out ) ; textdata1 . write ( out ) ; intdata2 . write ( out ) ; datedata2 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; duplicateFlg . readFields ( in ) ; textdata1 . readFields ( in ) ; intdata2 . readFields ( in ) ; datedata2 . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result += prime * result + tempSid . hashCode ( ) ; result += prime * result + sid . hashCode ( ) ; result += prime * result + versionNo . hashCode ( ) ; result += prime * result + rgstDate . hashCode ( ) ; result += prime * result + updtDate . hashCode ( ) ; result += prime * result + duplicateFlg . hashCode ( ) ; result += prime * result + textdata1 . hashCode ( ) ; result += prime * result + intdata2 . hashCode ( ) ; result += prime * result + datedata2 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempImportTarget19 other = ( ExportTempImportTarget19 ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . duplicateFlg . equals ( other . duplicateFlg ) == false ) { return false ; } if ( this . textdata1 . equals ( other . textdata1 ) == false ) { return false ; } if ( this . intdata2 . equals ( other . intdata2 ) == false ) { return false ; } if ( this . datedata2 . equals ( other . datedata2 ) == false ) { return false ; } return true ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class JobflowInstanceLock implements Writable { @ Property ( name = "" ) private StringOption executionId = new StringOption ( ) ; public Text getExecutionId ( ) { return this . executionId . get ( ) ; } public void setExecutionId ( Text executionId ) { this . executionId . modify ( executionId ) ; } public String getExecutionIdAsString ( ) { return this . executionId . getAsString ( ) ; } public void setExecutionIdAsString ( String executionId ) { this . executionId . modify ( executionId ) ; } public StringOption getExecutionIdOption ( ) { return this . executionId ; } public void setExecutionIdOption ( StringOption executionId ) { this . executionId . copyFrom ( executionId ) ; } public void copyFrom ( JobflowInstanceLock source ) { this . executionId . copyFrom ( source . executionId ) ; } @ Override public void write ( DataOutput out ) throws IOException { executionId . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { executionId . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + executionId . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } JobflowInstanceLock other = ( JobflowInstanceLock ) obj ; if ( this . executionId . equals ( other . executionId ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . executionId ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { } ) @ SuppressWarnings ( "" ) public class BalanceTranError implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private DateOption previousCutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption nextCutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private LongOption carried = new LongOption ( ) ; @ Property ( name = "" ) private LongOption purchase = new LongOption ( ) ; @ Property ( name = "" ) private LongOption rtn = new LongOption ( ) ; @ Property ( name = "" ) private LongOption discount = new LongOption ( ) ; @ Property ( name = "" ) private LongOption tax = new LongOption ( ) ; @ Property ( name = "" ) private LongOption payable = new LongOption ( ) ; @ Property ( name = "" ) private LongOption mutual = new LongOption ( ) ; @ Property ( name = "" ) private LongOption reserves = new LongOption ( ) ; @ Property ( name = "" ) private LongOption cancel = new LongOption ( ) ; @ Property ( name = "" ) private LongOption payment = new LongOption ( ) ; @ Property ( name = "" ) private LongOption nextPurchase = new LongOption ( ) ; @ Property ( name = "" ) private LongOption nextReturn = new LongOption ( ) ; @ Property ( name = "" ) private LongOption nextDiscount = new LongOption ( ) ; @ Property ( name = "" ) private LongOption nextTax = new LongOption ( ) ; @ Property ( name = "" ) private StringOption errorCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption paymentFlag = new StringOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDatetime ( ) { return this . rgstDatetime . get ( ) ; } public void setRgstDatetime ( DateTime rgstDatetime ) { this . rgstDatetime . modify ( rgstDatetime ) ; } public DateTimeOption getRgstDatetimeOption ( ) { return this . rgstDatetime ; } public void setRgstDatetimeOption ( DateTimeOption rgstDatetime ) { this . rgstDatetime . copyFrom ( rgstDatetime ) ; } public DateTime getUpdtDatetime ( ) { return this . updtDatetime . get ( ) ; } public void setUpdtDatetime ( DateTime updtDatetime ) { this . updtDatetime . modify ( updtDatetime ) ; } public DateTimeOption getUpdtDatetimeOption ( ) { return this . updtDatetime ; } public void setUpdtDatetimeOption ( DateTimeOption updtDatetime ) { this . updtDatetime . copyFrom ( updtDatetime ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Date getPreviousCutoffDate ( ) { return this . previousCutoffDate . get ( ) ; } public void setPreviousCutoffDate ( Date previousCutoffDate ) { this . previousCutoffDate . modify ( previousCutoffDate ) ; } public DateOption getPreviousCutoffDateOption ( ) { return this . previousCutoffDate ; } public void setPreviousCutoffDateOption ( DateOption previousCutoffDate ) { this . previousCutoffDate . copyFrom ( previousCutoffDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getNextCutoffDate ( ) { return this . nextCutoffDate . get ( ) ; } public void setNextCutoffDate ( Date nextCutoffDate ) { this . nextCutoffDate . modify ( nextCutoffDate ) ; } public DateOption getNextCutoffDateOption ( ) { return this . nextCutoffDate ; } public void setNextCutoffDateOption ( DateOption nextCutoffDate ) { this . nextCutoffDate . copyFrom ( nextCutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public long getCarried ( ) { return this . carried . get ( ) ; } public void setCarried ( long carried ) { this . carried . modify ( carried ) ; } public LongOption getCarriedOption ( ) { return this . carried ; } public void setCarriedOption ( LongOption carried ) { this . carried . copyFrom ( carried ) ; } public long getPurchase ( ) { return this . purchase . get ( ) ; } public void setPurchase ( long purchase ) { this . purchase . modify ( purchase ) ; } public LongOption getPurchaseOption ( ) { return this . purchase ; } public void setPurchaseOption ( LongOption purchase ) { this . purchase . copyFrom ( purchase ) ; } public long getRtn ( ) { return this . rtn . get ( ) ; } public void setRtn ( long rtn ) { this . rtn . modify ( rtn ) ; } public LongOption getRtnOption ( ) { return this . rtn ; } public void setRtnOption ( LongOption rtn ) { this . rtn . copyFrom ( rtn ) ; } public long getDiscount ( ) { return this . discount . get ( ) ; } public void setDiscount ( long discount ) { this . discount . modify ( discount ) ; } public LongOption getDiscountOption ( ) { return this . discount ; } public void setDiscountOption ( LongOption discount ) { this . discount . copyFrom ( discount ) ; } public long getTax ( ) { return this . tax . get ( ) ; } public void setTax ( long tax ) { this . tax . modify ( tax ) ; } public LongOption getTaxOption ( ) { return this . tax ; } public void setTaxOption ( LongOption tax ) { this . tax . copyFrom ( tax ) ; } public long getPayable ( ) { return this . payable . get ( ) ; } public void setPayable ( long payable ) { this . payable . modify ( payable ) ; } public LongOption getPayableOption ( ) { return this . payable ; } public void setPayableOption ( LongOption payable ) { this . payable . copyFrom ( payable ) ; } public long getMutual ( ) { return this . mutual . get ( ) ; } public void setMutual ( long mutual ) { this . mutual . modify ( mutual ) ; } public LongOption getMutualOption ( ) { return this . mutual ; } public void setMutualOption ( LongOption mutual ) { this . mutual . copyFrom ( mutual ) ; } public long getReserves ( ) { return this . reserves . get ( ) ; } public void setReserves ( long reserves ) { this . reserves . modify ( reserves ) ; } public LongOption getReservesOption ( ) { return this . reserves ; } public void setReservesOption ( LongOption reserves ) { this . reserves . copyFrom ( reserves ) ; } public long getCancel ( ) { return this . cancel . get ( ) ; } public void setCancel ( long cancel ) { this . cancel . modify ( cancel ) ; } public LongOption getCancelOption ( ) { return this . cancel ; } public void setCancelOption ( LongOption cancel ) { this . cancel . copyFrom ( cancel ) ; } public long getPayment ( ) { return this . payment . get ( ) ; } public void setPayment ( long payment ) { this . payment . modify ( payment ) ; } public LongOption getPaymentOption ( ) { return this . payment ; } public void setPaymentOption ( LongOption payment ) { this . payment . copyFrom ( payment ) ; } public long getNextPurchase ( ) { return this . nextPurchase . get ( ) ; } public void setNextPurchase ( long nextPurchase ) { this . nextPurchase . modify ( nextPurchase ) ; } public LongOption getNextPurchaseOption ( ) { return this . nextPurchase ; } public void setNextPurchaseOption ( LongOption nextPurchase ) { this . nextPurchase . copyFrom ( nextPurchase ) ; } public long getNextReturn ( ) { return this . nextReturn . get ( ) ; } public void setNextReturn ( long nextReturn ) { this . nextReturn . modify ( nextReturn ) ; } public LongOption getNextReturnOption ( ) { return this . nextReturn ; } public void setNextReturnOption ( LongOption nextReturn ) { this . nextReturn . copyFrom ( nextReturn ) ; } public long getNextDiscount ( ) { return this . nextDiscount . get ( ) ; } public void setNextDiscount ( long nextDiscount ) { this . nextDiscount . modify ( nextDiscount ) ; } public LongOption getNextDiscountOption ( ) { return this . nextDiscount ; } public void setNextDiscountOption ( LongOption nextDiscount ) { this . nextDiscount . copyFrom ( nextDiscount ) ; } public long getNextTax ( ) { return this . nextTax . get ( ) ; } public void setNextTax ( long nextTax ) { this . nextTax . modify ( nextTax ) ; } public LongOption getNextTaxOption ( ) { return this . nextTax ; } public void setNextTaxOption ( LongOption nextTax ) { this . nextTax . copyFrom ( nextTax ) ; } public Text getErrorCode ( ) { return this . errorCode . get ( ) ; } public void setErrorCode ( Text errorCode ) { this . errorCode . modify ( errorCode ) ; } public String getErrorCodeAsString ( ) { return this . errorCode . getAsString ( ) ; } public void setErrorCodeAsString ( String errorCode ) { this . errorCode . modify ( errorCode ) ; } public StringOption getErrorCodeOption ( ) { return this . errorCode ; } public void setErrorCodeOption ( StringOption errorCode ) { this . errorCode . copyFrom ( errorCode ) ; } public Text getPaymentFlag ( ) { return this . paymentFlag . get ( ) ; } public void setPaymentFlag ( Text paymentFlag ) { this . paymentFlag . modify ( paymentFlag ) ; } public String getPaymentFlagAsString ( ) { return this . paymentFlag . getAsString ( ) ; } public void setPaymentFlagAsString ( String paymentFlag ) { this . paymentFlag . modify ( paymentFlag ) ; } public StringOption getPaymentFlagOption ( ) { return this . paymentFlag ; } public void setPaymentFlagOption ( StringOption paymentFlag ) { this . paymentFlag . copyFrom ( paymentFlag ) ; } public void copyFrom ( BalanceTranError source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDatetime . copyFrom ( source . rgstDatetime ) ; this . updtDatetime . copyFrom ( source . updtDatetime ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . previousCutoffDate . copyFrom ( source . previousCutoffDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . nextCutoffDate . copyFrom ( source . nextCutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . carried . copyFrom ( source . carried ) ; this . purchase . copyFrom ( source . purchase ) ; this . rtn . copyFrom ( source . rtn ) ; this . discount . copyFrom ( source . discount ) ; this . tax . copyFrom ( source . tax ) ; this . payable . copyFrom ( source . payable ) ; this . mutual . copyFrom ( source . mutual ) ; this . reserves . copyFrom ( source . reserves ) ; this . cancel . copyFrom ( source . cancel ) ; this . payment . copyFrom ( source . payment ) ; this . nextPurchase . copyFrom ( source . nextPurchase ) ; this . nextReturn . copyFrom ( source . nextReturn ) ; this . nextDiscount . copyFrom ( source . nextDiscount ) ; this . nextTax . copyFrom ( source . nextTax ) ; this . errorCode . copyFrom ( source . errorCode ) ; this . paymentFlag . copyFrom ( source . paymentFlag ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; rgstDatetime . write ( out ) ; updtDatetime . write ( out ) ; sellerCode . write ( out ) ; previousCutoffDate . write ( out ) ; cutoffDate . write ( out ) ; nextCutoffDate . write ( out ) ; payoutDate . write ( out ) ; carried . write ( out ) ; purchase . write ( out ) ; rtn . write ( out ) ; discount . write ( out ) ; tax . write ( out ) ; payable . write ( out ) ; mutual . write ( out ) ; reserves . write ( out ) ; cancel . write ( out ) ; payment . write ( out ) ; nextPurchase . write ( out ) ; nextReturn . write ( out ) ; nextDiscount . write ( out ) ; nextTax . write ( out ) ; errorCode . write ( out ) ; paymentFlag . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDatetime . readFields ( in ) ; updtDatetime . readFields ( in ) ; sellerCode . readFields ( in ) ; previousCutoffDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; nextCutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; carried . readFields ( in ) ; purchase . readFields ( in ) ; rtn . readFields ( in ) ; discount . readFields ( in ) ; tax . readFields ( in ) ; payable . readFields ( in ) ; mutual . readFields ( in ) ; reserves . readFields ( in ) ; cancel . readFields ( in ) ; payment . readFields ( in ) ; nextPurchase . readFields ( in ) ; nextReturn . readFields ( in ) ; nextDiscount . readFields ( in ) ; nextTax . readFields ( in ) ; errorCode . readFields ( in ) ; paymentFlag . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + rgstDatetime . hashCode ( ) ; result = prime * result + updtDatetime . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + previousCutoffDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + nextCutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + carried . hashCode ( ) ; result = prime * result + purchase . hashCode ( ) ; result = prime * result + rtn . hashCode ( ) ; result = prime * result + discount . hashCode ( ) ; result = prime * result + tax . hashCode ( ) ; result = prime * result + payable . hashCode ( ) ; result = prime * result + mutual . hashCode ( ) ; result = prime * result + reserves . hashCode ( ) ; result = prime * result + cancel . hashCode ( ) ; result = prime * result + payment . hashCode ( ) ; result = prime * result + nextPurchase . hashCode ( ) ; result = prime * result + nextReturn . hashCode ( ) ; result = prime * result + nextDiscount . hashCode ( ) ; result = prime * result + nextTax . hashCode ( ) ; result = prime * result + errorCode . hashCode ( ) ; result = prime * result + paymentFlag . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } BalanceTranError other = ( BalanceTranError ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDatetime . equals ( other . rgstDatetime ) == false ) { return false ; } if ( this . updtDatetime . equals ( other . updtDatetime ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . previousCutoffDate . equals ( other . previousCutoffDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . nextCutoffDate . equals ( other . nextCutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . carried . equals ( other . carried ) == false ) { return false ; } if ( this . purchase . equals ( other . purchase ) == false ) { return false ; } if ( this . rtn . equals ( other . rtn ) == false ) { return false ; } if ( this . discount . equals ( other . discount ) == false ) { return false ; } if ( this . tax . equals ( other . tax ) == false ) { return false ; } if ( this . payable . equals ( other . payable ) == false ) { return false ; } if ( this . mutual . equals ( other . mutual ) == false ) { return false ; } if ( this . reserves . equals ( other . reserves ) == false ) { return false ; } if ( this . cancel . equals ( other . cancel ) == false ) { return false ; } if ( this . payment . equals ( other . payment ) == false ) { return false ; } if ( this . nextPurchase . equals ( other . nextPurchase ) == false ) { return false ; } if ( this . nextReturn . equals ( other . nextReturn ) == false ) { return false ; } if ( this . nextDiscount . equals ( other . nextDiscount ) == false ) { return false ; } if ( this . nextTax . equals ( other . nextTax ) == false ) { return false ; } if ( this . errorCode . equals ( other . errorCode ) == false ) { return false ; } if ( this . paymentFlag . equals ( other . paymentFlag ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . rgstDatetime ) ; result . append ( "" ) ; result . append ( this . updtDatetime ) ; result . append ( "" ) ; result . append ( this . sellerCode ) ; result . append ( "" ) ; result . append ( this . previousCutoffDate ) ; result . append ( "" ) ; result . append ( this . cutoffDate ) ; result . append ( "" ) ; result . append ( this . nextCutoffDate ) ; result . append ( "" ) ; result . append ( this . payoutDate ) ; result . append ( "" ) ; result . append ( this . carried ) ; result . append ( "" ) ; result . append ( this . purchase ) ; result . append ( "" ) ; result . append ( this . rtn ) ; result . append ( "" ) ; result . append ( this . discount ) ; result . append ( "" ) ; result . append ( this . tax ) ; result . append ( "" ) ; result . append ( this . payable ) ; result . append ( "" ) ; result . append ( this . mutual ) ; result . append ( "" ) ; result . append ( this . reserves ) ; result . append ( "" ) ; result . append ( this . cancel ) ; result . append ( "" ) ; result . append ( this . payment ) ; result . append ( "" ) ; result . append ( this . nextPurchase ) ; result . append ( "" ) ; result . append ( this . nextReturn ) ; result . append ( "" ) ; result . append ( this . nextDiscount ) ; result . append ( "" ) ; result . append ( this . nextTax ) ; result . append ( "" ) ; result . append ( this . errorCode ) ; result . append ( "" ) ; result . append ( this . paymentFlag ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class PurchaseTran implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private LongOption lineNo = new LongOption ( ) ; @ Property ( name = "" ) private DateOption deliveryDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption storeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tenantCode = new StringOption ( ) ; @ Property ( name = "" ) private LongOption netPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sellingPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private StringOption shipmentStoreCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption shipmentSalesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption deductionCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption accountCode = new StringOption ( ) ; @ Property ( name = "" ) private DateOption ownershipDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption ownershipFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDatetime ( ) { return this . rgstDatetime . get ( ) ; } public void setRgstDatetime ( DateTime rgstDatetime ) { this . rgstDatetime . modify ( rgstDatetime ) ; } public DateTimeOption getRgstDatetimeOption ( ) { return this . rgstDatetime ; } public void setRgstDatetimeOption ( DateTimeOption rgstDatetime ) { this . rgstDatetime . copyFrom ( rgstDatetime ) ; } public DateTime getUpdtDatetime ( ) { return this . updtDatetime . get ( ) ; } public void setUpdtDatetime ( DateTime updtDatetime ) { this . updtDatetime . modify ( updtDatetime ) ; } public DateTimeOption getUpdtDatetimeOption ( ) { return this . updtDatetime ; } public void setUpdtDatetimeOption ( DateTimeOption updtDatetime ) { this . updtDatetime . copyFrom ( updtDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public long getLineNo ( ) { return this . lineNo . get ( ) ; } public void setLineNo ( long lineNo ) { this . lineNo . modify ( lineNo ) ; } public LongOption getLineNoOption ( ) { return this . lineNo ; } public void setLineNoOption ( LongOption lineNo ) { this . lineNo . copyFrom ( lineNo ) ; } public Date getDeliveryDate ( ) { return this . deliveryDate . get ( ) ; } public void setDeliveryDate ( Date deliveryDate ) { this . deliveryDate . modify ( deliveryDate ) ; } public DateOption getDeliveryDateOption ( ) { return this . deliveryDate ; } public void setDeliveryDateOption ( DateOption deliveryDate ) { this . deliveryDate . copyFrom ( deliveryDate ) ; } public Text getStoreCode ( ) { return this . storeCode . get ( ) ; } public void setStoreCode ( Text storeCode ) { this . storeCode . modify ( storeCode ) ; } public String getStoreCodeAsString ( ) { return this . storeCode . getAsString ( ) ; } public void setStoreCodeAsString ( String storeCode ) { this . storeCode . modify ( storeCode ) ; } public StringOption getStoreCodeOption ( ) { return this . storeCode ; } public void setStoreCodeOption ( StringOption storeCode ) { this . storeCode . copyFrom ( storeCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Text getPurchaseTypeCode ( ) { return this . purchaseTypeCode . get ( ) ; } public void setPurchaseTypeCode ( Text purchaseTypeCode ) { this . purchaseTypeCode . modify ( purchaseTypeCode ) ; } public String getPurchaseTypeCodeAsString ( ) { return this . purchaseTypeCode . getAsString ( ) ; } public void setPurchaseTypeCodeAsString ( String purchaseTypeCode ) { this . purchaseTypeCode . modify ( purchaseTypeCode ) ; } public StringOption getPurchaseTypeCodeOption ( ) { return this . purchaseTypeCode ; } public void setPurchaseTypeCodeOption ( StringOption purchaseTypeCode ) { this . purchaseTypeCode . copyFrom ( purchaseTypeCode ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getTenantCode ( ) { return this . tenantCode . get ( ) ; } public void setTenantCode ( Text tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public String getTenantCodeAsString ( ) { return this . tenantCode . getAsString ( ) ; } public void setTenantCodeAsString ( String tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public StringOption getTenantCodeOption ( ) { return this . tenantCode ; } public void setTenantCodeOption ( StringOption tenantCode ) { this . tenantCode . copyFrom ( tenantCode ) ; } public long getNetPriceTotal ( ) { return this . netPriceTotal . get ( ) ; } public void setNetPriceTotal ( long netPriceTotal ) { this . netPriceTotal . modify ( netPriceTotal ) ; } public LongOption getNetPriceTotalOption ( ) { return this . netPriceTotal ; } public void setNetPriceTotalOption ( LongOption netPriceTotal ) { this . netPriceTotal . copyFrom ( netPriceTotal ) ; } public long getSellingPriceTotal ( ) { return this . sellingPriceTotal . get ( ) ; } public void setSellingPriceTotal ( long sellingPriceTotal ) { this . sellingPriceTotal . modify ( sellingPriceTotal ) ; } public LongOption getSellingPriceTotalOption ( ) { return this . sellingPriceTotal ; } public void setSellingPriceTotalOption ( LongOption sellingPriceTotal ) { this . sellingPriceTotal . copyFrom ( sellingPriceTotal ) ; } public Text getShipmentStoreCode ( ) { return this . shipmentStoreCode . get ( ) ; } public void setShipmentStoreCode ( Text shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public String getShipmentStoreCodeAsString ( ) { return this . shipmentStoreCode . getAsString ( ) ; } public void setShipmentStoreCodeAsString ( String shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public StringOption getShipmentStoreCodeOption ( ) { return this . shipmentStoreCode ; } public void setShipmentStoreCodeOption ( StringOption shipmentStoreCode ) { this . shipmentStoreCode . copyFrom ( shipmentStoreCode ) ; } public Text getShipmentSalesTypeCode ( ) { return this . shipmentSalesTypeCode . get ( ) ; } public void setShipmentSalesTypeCode ( Text shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public String getShipmentSalesTypeCodeAsString ( ) { return this . shipmentSalesTypeCode . getAsString ( ) ; } public void setShipmentSalesTypeCodeAsString ( String shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public StringOption getShipmentSalesTypeCodeOption ( ) { return this . shipmentSalesTypeCode ; } public void setShipmentSalesTypeCodeOption ( StringOption shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . copyFrom ( shipmentSalesTypeCode ) ; } public Text getDeductionCode ( ) { return this . deductionCode . get ( ) ; } public void setDeductionCode ( Text deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public String getDeductionCodeAsString ( ) { return this . deductionCode . getAsString ( ) ; } public void setDeductionCodeAsString ( String deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public StringOption getDeductionCodeOption ( ) { return this . deductionCode ; } public void setDeductionCodeOption ( StringOption deductionCode ) { this . deductionCode . copyFrom ( deductionCode ) ; } public Text getAccountCode ( ) { return this . accountCode . get ( ) ; } public void setAccountCode ( Text accountCode ) { this . accountCode . modify ( accountCode ) ; } public String getAccountCodeAsString ( ) { return this . accountCode . getAsString ( ) ; } public void setAccountCodeAsString ( String accountCode ) { this . accountCode . modify ( accountCode ) ; } public StringOption getAccountCodeOption ( ) { return this . accountCode ; } public void setAccountCodeOption ( StringOption accountCode ) { this . accountCode . copyFrom ( accountCode ) ; } public Date getOwnershipDate ( ) { return this . ownershipDate . get ( ) ; } public void setOwnershipDate ( Date ownershipDate ) { this . ownershipDate . modify ( ownershipDate ) ; } public DateOption getOwnershipDateOption ( ) { return this . ownershipDate ; } public void setOwnershipDateOption ( DateOption ownershipDate ) { this . ownershipDate . copyFrom ( ownershipDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public Text getOwnershipFlag ( ) { return this . ownershipFlag . get ( ) ; } public void setOwnershipFlag ( Text ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public String getOwnershipFlagAsString ( ) { return this . ownershipFlag . getAsString ( ) ; } public void setOwnershipFlagAsString ( String ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public StringOption getOwnershipFlagOption ( ) { return this . ownershipFlag ; } public void setOwnershipFlagOption ( StringOption ownershipFlag ) { this . ownershipFlag . copyFrom ( ownershipFlag ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public void copyFrom ( PurchaseTran source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDatetime . copyFrom ( source . rgstDatetime ) ; this . updtDatetime . copyFrom ( source . updtDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . lineNo . copyFrom ( source . lineNo ) ; this . deliveryDate . copyFrom ( source . deliveryDate ) ; this . storeCode . copyFrom ( source . storeCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . purchaseTypeCode . copyFrom ( source . purchaseTypeCode ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . tenantCode . copyFrom ( source . tenantCode ) ; this . netPriceTotal . copyFrom ( source . netPriceTotal ) ; this . sellingPriceTotal . copyFrom ( source . sellingPriceTotal ) ; this . shipmentStoreCode . copyFrom ( source . shipmentStoreCode ) ; this . shipmentSalesTypeCode . copyFrom ( source . shipmentSalesTypeCode ) ; this . deductionCode . copyFrom ( source . deductionCode ) ; this . accountCode . copyFrom ( source . accountCode ) ; this . ownershipDate . copyFrom ( source . ownershipDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . ownershipFlag . copyFrom ( source . ownershipFlag ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; rgstDatetime . write ( out ) ; updtDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; lineNo . write ( out ) ; deliveryDate . write ( out ) ; storeCode . write ( out ) ; buyerCode . write ( out ) ; purchaseTypeCode . write ( out ) ; sellerCode . write ( out ) ; tenantCode . write ( out ) ; netPriceTotal . write ( out ) ; sellingPriceTotal . write ( out ) ; shipmentStoreCode . write ( out ) ; shipmentSalesTypeCode . write ( out ) ; deductionCode . write ( out ) ; accountCode . write ( out ) ; ownershipDate . write ( out ) ; cutoffDate . write ( out ) ; payoutDate . write ( out ) ; ownershipFlag . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDatetime . readFields ( in ) ; updtDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; lineNo . readFields ( in ) ; deliveryDate . readFields ( in ) ; storeCode . readFields ( in ) ; buyerCode . readFields ( in ) ; purchaseTypeCode . readFields ( in ) ; sellerCode . readFields ( in ) ; tenantCode . readFields ( in ) ; netPriceTotal . readFields ( in ) ; sellingPriceTotal . readFields ( in ) ; shipmentStoreCode . readFields ( in ) ; shipmentSalesTypeCode . readFields ( in ) ; deductionCode . readFields ( in ) ; accountCode . readFields ( in ) ; ownershipDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; ownershipFlag . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + rgstDatetime . hashCode ( ) ; result = prime * result + updtDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + lineNo . hashCode ( ) ; result = prime * result + deliveryDate . hashCode ( ) ; result = prime * result + storeCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + purchaseTypeCode . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + tenantCode . hashCode ( ) ; result = prime * result + netPriceTotal . hashCode ( ) ; result = prime * result + sellingPriceTotal . hashCode ( ) ; result = prime * result + shipmentStoreCode . hashCode ( ) ; result = prime * result + shipmentSalesTypeCode . hashCode ( ) ; result = prime * result + deductionCode . hashCode ( ) ; result = prime * result + accountCode . hashCode ( ) ; result = prime * result + ownershipDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + ownershipFlag . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } PurchaseTran other = ( PurchaseTran ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDatetime . equals ( other . rgstDatetime ) == false ) { return false ; } if ( this . updtDatetime . equals ( other . updtDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . lineNo . equals ( other . lineNo ) == false ) { return false ; } if ( this . deliveryDate . equals ( other . deliveryDate ) == false ) { return false ; } if ( this . storeCode . equals ( other . storeCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . purchaseTypeCode . equals ( other . purchaseTypeCode ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . tenantCode . equals ( other . tenantCode ) == false ) { return false ; } if ( this . netPriceTotal . equals ( other . netPriceTotal ) == false ) { return false ; } if ( this . sellingPriceTotal . equals ( other . sellingPriceTotal ) == false ) { return false ; } if ( this . shipmentStoreCode . equals ( other . shipmentStoreCode ) == false ) { return false ; } if ( this . shipmentSalesTypeCode . equals ( other . shipmentSalesTypeCode ) == false ) { return false ; } if ( this . deductionCode . equals ( other . deductionCode ) == false ) { return false ; } if ( this . accountCode . equals ( other . accountCode ) == false ) { return false ; } if ( this . ownershipDate . equals ( other . ownershipDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . ownershipFlag . equals ( other . ownershipFlag ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . rgstDatetime ) ; result . append ( "" ) ; result . append ( this . updtDatetime ) ; result . append ( "" ) ; result . append ( this . purchaseNo ) ; result . append ( "" ) ; result . append ( this . purchaseType ) ; result . append ( "" ) ; result . append ( this . tradeType ) ; result . append ( "" ) ; result . append ( this . tradeNo ) ; result . append ( "" ) ; result . append ( this . lineNo ) ; result . append ( "" ) ; result . append ( this . deliveryDate ) ; result . append ( "" ) ; result . append ( this . storeCode ) ; result . append ( "" ) ; result . append ( this . buyerCode ) ; result . append ( "" ) ; result . append ( this . purchaseTypeCode ) ; result . append ( "" ) ; result . append ( this . sellerCode ) ; result . append ( "" ) ; result . append ( this . tenantCode ) ; result . append ( "" ) ; result . append ( this . netPriceTotal ) ; result . append ( "" ) ; result . append ( this . sellingPriceTotal ) ; result . append ( "" ) ; result . append ( this . shipmentStoreCode ) ; result . append ( "" ) ; result . append ( this . shipmentSalesTypeCode ) ; result . append ( "" ) ; result . append ( this . deductionCode ) ; result . append ( "" ) ; result . append ( this . accountCode ) ; result . append ( "" ) ; result . append ( this . ownershipDate ) ; result . append ( "" ) ; result . append ( this . cutoffDate ) ; result . append ( "" ) ; result . append ( this . payoutDate ) ; result . append ( "" ) ; result . append ( this . ownershipFlag ) ; result . append ( "" ) ; result . append ( this . cutoffFlag ) ; result . append ( "" ) ; result . append ( this . payoutFlag ) ; result . append ( "" ) ; result . append ( this . disposeNo ) ; result . append ( "" ) ; result . append ( this . disposeDate ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempPurchaseTran1Df implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public void copyFrom ( ExportTempPurchaseTran1Df source ) { this . tempSid . copyFrom ( source . tempSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempPurchaseTran1Df other = ( ExportTempPurchaseTran1Df ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ImportTarget2Rl implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption jobflowSid = new LongOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getJobflowSid ( ) { return this . jobflowSid . get ( ) ; } public void setJobflowSid ( long jobflowSid ) { this . jobflowSid . modify ( jobflowSid ) ; } public LongOption getJobflowSidOption ( ) { return this . jobflowSid ; } public void setJobflowSidOption ( LongOption jobflowSid ) { this . jobflowSid . copyFrom ( jobflowSid ) ; } public void copyFrom ( ImportTarget2Rl source ) { this . sid . copyFrom ( source . sid ) ; this . jobflowSid . copyFrom ( source . jobflowSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; jobflowSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; jobflowSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + jobflowSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ImportTarget2Rl other = ( ImportTarget2Rl ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . jobflowSid . equals ( other . jobflowSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . jobflowSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempImportTarget11 implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption duplicateFlg = new StringOption ( ) ; @ Property ( name = "" ) private StringOption textdata1 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata1 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata1 = new DateTimeOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getDuplicateFlg ( ) { return this . duplicateFlg . get ( ) ; } public void setDuplicateFlg ( Text duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public String getDuplicateFlgAsString ( ) { return this . duplicateFlg . getAsString ( ) ; } public void setDuplicateFlgAsString ( String duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public StringOption getDuplicateFlgOption ( ) { return this . duplicateFlg ; } public void setDuplicateFlgOption ( StringOption duplicateFlg ) { this . duplicateFlg . copyFrom ( duplicateFlg ) ; } public Text getTextdata1 ( ) { return this . textdata1 . get ( ) ; } public void setTextdata1 ( Text textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public String getTextdata1AsString ( ) { return this . textdata1 . getAsString ( ) ; } public void setTextdata1AsString ( String textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public StringOption getTextdata1Option ( ) { return this . textdata1 ; } public void setTextdata1Option ( StringOption textdata1 ) { this . textdata1 . copyFrom ( textdata1 ) ; } public int getIntdata1 ( ) { return this . intdata1 . get ( ) ; } public void setIntdata1 ( int intdata1 ) { this . intdata1 . modify ( intdata1 ) ; } public IntOption getIntdata1Option ( ) { return this . intdata1 ; } public void setIntdata1Option ( IntOption intdata1 ) { this . intdata1 . copyFrom ( intdata1 ) ; } public DateTime getDatedata1 ( ) { return this . datedata1 . get ( ) ; } public void setDatedata1 ( DateTime datedata1 ) { this . datedata1 . modify ( datedata1 ) ; } public DateTimeOption getDatedata1Option ( ) { return this . datedata1 ; } public void setDatedata1Option ( DateTimeOption datedata1 ) { this . datedata1 . copyFrom ( datedata1 ) ; } public void copyFrom ( ExportTempImportTarget11 source ) { this . tempSid . copyFrom ( source . tempSid ) ; this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . duplicateFlg . copyFrom ( source . duplicateFlg ) ; this . textdata1 . copyFrom ( source . textdata1 ) ; this . intdata1 . copyFrom ( source . intdata1 ) ; this . datedata1 . copyFrom ( source . datedata1 ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; sid . write ( out ) ; versionNo . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; duplicateFlg . write ( out ) ; textdata1 . write ( out ) ; intdata1 . write ( out ) ; datedata1 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; duplicateFlg . readFields ( in ) ; textdata1 . readFields ( in ) ; intdata1 . readFields ( in ) ; datedata1 . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result += prime * result + tempSid . hashCode ( ) ; result += prime * result + sid . hashCode ( ) ; result += prime * result + versionNo . hashCode ( ) ; result += prime * result + rgstDate . hashCode ( ) ; result += prime * result + updtDate . hashCode ( ) ; result += prime * result + duplicateFlg . hashCode ( ) ; result += prime * result + textdata1 . hashCode ( ) ; result += prime * result + intdata1 . hashCode ( ) ; result += prime * result + datedata1 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempImportTarget11 other = ( ExportTempImportTarget11 ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . duplicateFlg . equals ( other . duplicateFlg ) == false ) { return false ; } if ( this . textdata1 . equals ( other . textdata1 ) == false ) { return false ; } if ( this . intdata1 . equals ( other . intdata1 ) == false ) { return false ; } if ( this . datedata1 . equals ( other . datedata1 ) == false ) { return false ; } return true ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempImportTarget21 implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption duplicateFlg = new StringOption ( ) ; @ Property ( name = "" ) private StringOption textdata2 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata2 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata2 = new DateTimeOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getDuplicateFlg ( ) { return this . duplicateFlg . get ( ) ; } public void setDuplicateFlg ( Text duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public String getDuplicateFlgAsString ( ) { return this . duplicateFlg . getAsString ( ) ; } public void setDuplicateFlgAsString ( String duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public StringOption getDuplicateFlgOption ( ) { return this . duplicateFlg ; } public void setDuplicateFlgOption ( StringOption duplicateFlg ) { this . duplicateFlg . copyFrom ( duplicateFlg ) ; } public Text getTextdata2 ( ) { return this . textdata2 . get ( ) ; } public void setTextdata2 ( Text textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public String getTextdata2AsString ( ) { return this . textdata2 . getAsString ( ) ; } public void setTextdata2AsString ( String textdata2 ) { this . textdata2 . modify ( textdata2 ) ; } public StringOption getTextdata2Option ( ) { return this . textdata2 ; } public void setTextdata2Option ( StringOption textdata2 ) { this . textdata2 . copyFrom ( textdata2 ) ; } public int getIntdata2 ( ) { return this . intdata2 . get ( ) ; } public void setIntdata2 ( int intdata2 ) { this . intdata2 . modify ( intdata2 ) ; } public IntOption getIntdata2Option ( ) { return this . intdata2 ; } public void setIntdata2Option ( IntOption intdata2 ) { this . intdata2 . copyFrom ( intdata2 ) ; } public DateTime getDatedata2 ( ) { return this . datedata2 . get ( ) ; } public void setDatedata2 ( DateTime datedata2 ) { this . datedata2 . modify ( datedata2 ) ; } public DateTimeOption getDatedata2Option ( ) { return this . datedata2 ; } public void setDatedata2Option ( DateTimeOption datedata2 ) { this . datedata2 . copyFrom ( datedata2 ) ; } public void copyFrom ( ExportTempImportTarget21 source ) { this . tempSid . copyFrom ( source . tempSid ) ; this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . duplicateFlg . copyFrom ( source . duplicateFlg ) ; this . textdata2 . copyFrom ( source . textdata2 ) ; this . intdata2 . copyFrom ( source . intdata2 ) ; this . datedata2 . copyFrom ( source . datedata2 ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; sid . write ( out ) ; versionNo . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; duplicateFlg . write ( out ) ; textdata2 . write ( out ) ; intdata2 . write ( out ) ; datedata2 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; duplicateFlg . readFields ( in ) ; textdata2 . readFields ( in ) ; intdata2 . readFields ( in ) ; datedata2 . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result += prime * result + tempSid . hashCode ( ) ; result += prime * result + sid . hashCode ( ) ; result += prime * result + versionNo . hashCode ( ) ; result += prime * result + rgstDate . hashCode ( ) ; result += prime * result + updtDate . hashCode ( ) ; result += prime * result + duplicateFlg . hashCode ( ) ; result += prime * result + textdata2 . hashCode ( ) ; result += prime * result + intdata2 . hashCode ( ) ; result += prime * result + datedata2 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempImportTarget21 other = ( ExportTempImportTarget21 ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . duplicateFlg . equals ( other . duplicateFlg ) == false ) { return false ; } if ( this . textdata2 . equals ( other . textdata2 ) == false ) { return false ; } if ( this . intdata2 . equals ( other . intdata2 ) == false ) { return false ; } if ( this . datedata2 . equals ( other . datedata2 ) == false ) { return false ; } return true ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class BalanceTran implements Writable { @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private DateOption previousCutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption nextCutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private LongOption carried = new LongOption ( ) ; @ Property ( name = "" ) private LongOption purchase = new LongOption ( ) ; @ Property ( name = "" ) private LongOption rtn = new LongOption ( ) ; @ Property ( name = "" ) private LongOption discount = new LongOption ( ) ; @ Property ( name = "" ) private LongOption tax = new LongOption ( ) ; @ Property ( name = "" ) private LongOption payable = new LongOption ( ) ; @ Property ( name = "" ) private LongOption mutual = new LongOption ( ) ; @ Property ( name = "" ) private LongOption reserves = new LongOption ( ) ; @ Property ( name = "" ) private LongOption cancel = new LongOption ( ) ; @ Property ( name = "" ) private LongOption payment = new LongOption ( ) ; @ Property ( name = "" ) private LongOption nextPurchase = new LongOption ( ) ; @ Property ( name = "" ) private LongOption nextReturn = new LongOption ( ) ; @ Property ( name = "" ) private LongOption nextDiscount = new LongOption ( ) ; @ Property ( name = "" ) private LongOption nextTax = new LongOption ( ) ; @ Property ( name = "" ) private StringOption paymentFlag = new StringOption ( ) ; public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public DateTime getRgstDatetime ( ) { return this . rgstDatetime . get ( ) ; } public void setRgstDatetime ( DateTime rgstDatetime ) { this . rgstDatetime . modify ( rgstDatetime ) ; } public DateTimeOption getRgstDatetimeOption ( ) { return this . rgstDatetime ; } public void setRgstDatetimeOption ( DateTimeOption rgstDatetime ) { this . rgstDatetime . copyFrom ( rgstDatetime ) ; } public DateTime getUpdtDatetime ( ) { return this . updtDatetime . get ( ) ; } public void setUpdtDatetime ( DateTime updtDatetime ) { this . updtDatetime . modify ( updtDatetime ) ; } public DateTimeOption getUpdtDatetimeOption ( ) { return this . updtDatetime ; } public void setUpdtDatetimeOption ( DateTimeOption updtDatetime ) { this . updtDatetime . copyFrom ( updtDatetime ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Date getPreviousCutoffDate ( ) { return this . previousCutoffDate . get ( ) ; } public void setPreviousCutoffDate ( Date previousCutoffDate ) { this . previousCutoffDate . modify ( previousCutoffDate ) ; } public DateOption getPreviousCutoffDateOption ( ) { return this . previousCutoffDate ; } public void setPreviousCutoffDateOption ( DateOption previousCutoffDate ) { this . previousCutoffDate . copyFrom ( previousCutoffDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getNextCutoffDate ( ) { return this . nextCutoffDate . get ( ) ; } public void setNextCutoffDate ( Date nextCutoffDate ) { this . nextCutoffDate . modify ( nextCutoffDate ) ; } public DateOption getNextCutoffDateOption ( ) { return this . nextCutoffDate ; } public void setNextCutoffDateOption ( DateOption nextCutoffDate ) { this . nextCutoffDate . copyFrom ( nextCutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public long getCarried ( ) { return this . carried . get ( ) ; } public void setCarried ( long carried ) { this . carried . modify ( carried ) ; } public LongOption getCarriedOption ( ) { return this . carried ; } public void setCarriedOption ( LongOption carried ) { this . carried . copyFrom ( carried ) ; } public long getPurchase ( ) { return this . purchase . get ( ) ; } public void setPurchase ( long purchase ) { this . purchase . modify ( purchase ) ; } public LongOption getPurchaseOption ( ) { return this . purchase ; } public void setPurchaseOption ( LongOption purchase ) { this . purchase . copyFrom ( purchase ) ; } public long getRtn ( ) { return this . rtn . get ( ) ; } public void setRtn ( long rtn ) { this . rtn . modify ( rtn ) ; } public LongOption getRtnOption ( ) { return this . rtn ; } public void setRtnOption ( LongOption rtn ) { this . rtn . copyFrom ( rtn ) ; } public long getDiscount ( ) { return this . discount . get ( ) ; } public void setDiscount ( long discount ) { this . discount . modify ( discount ) ; } public LongOption getDiscountOption ( ) { return this . discount ; } public void setDiscountOption ( LongOption discount ) { this . discount . copyFrom ( discount ) ; } public long getTax ( ) { return this . tax . get ( ) ; } public void setTax ( long tax ) { this . tax . modify ( tax ) ; } public LongOption getTaxOption ( ) { return this . tax ; } public void setTaxOption ( LongOption tax ) { this . tax . copyFrom ( tax ) ; } public long getPayable ( ) { return this . payable . get ( ) ; } public void setPayable ( long payable ) { this . payable . modify ( payable ) ; } public LongOption getPayableOption ( ) { return this . payable ; } public void setPayableOption ( LongOption payable ) { this . payable . copyFrom ( payable ) ; } public long getMutual ( ) { return this . mutual . get ( ) ; } public void setMutual ( long mutual ) { this . mutual . modify ( mutual ) ; } public LongOption getMutualOption ( ) { return this . mutual ; } public void setMutualOption ( LongOption mutual ) { this . mutual . copyFrom ( mutual ) ; } public long getReserves ( ) { return this . reserves . get ( ) ; } public void setReserves ( long reserves ) { this . reserves . modify ( reserves ) ; } public LongOption getReservesOption ( ) { return this . reserves ; } public void setReservesOption ( LongOption reserves ) { this . reserves . copyFrom ( reserves ) ; } public long getCancel ( ) { return this . cancel . get ( ) ; } public void setCancel ( long cancel ) { this . cancel . modify ( cancel ) ; } public LongOption getCancelOption ( ) { return this . cancel ; } public void setCancelOption ( LongOption cancel ) { this . cancel . copyFrom ( cancel ) ; } public long getPayment ( ) { return this . payment . get ( ) ; } public void setPayment ( long payment ) { this . payment . modify ( payment ) ; } public LongOption getPaymentOption ( ) { return this . payment ; } public void setPaymentOption ( LongOption payment ) { this . payment . copyFrom ( payment ) ; } public long getNextPurchase ( ) { return this . nextPurchase . get ( ) ; } public void setNextPurchase ( long nextPurchase ) { this . nextPurchase . modify ( nextPurchase ) ; } public LongOption getNextPurchaseOption ( ) { return this . nextPurchase ; } public void setNextPurchaseOption ( LongOption nextPurchase ) { this . nextPurchase . copyFrom ( nextPurchase ) ; } public long getNextReturn ( ) { return this . nextReturn . get ( ) ; } public void setNextReturn ( long nextReturn ) { this . nextReturn . modify ( nextReturn ) ; } public LongOption getNextReturnOption ( ) { return this . nextReturn ; } public void setNextReturnOption ( LongOption nextReturn ) { this . nextReturn . copyFrom ( nextReturn ) ; } public long getNextDiscount ( ) { return this . nextDiscount . get ( ) ; } public void setNextDiscount ( long nextDiscount ) { this . nextDiscount . modify ( nextDiscount ) ; } public LongOption getNextDiscountOption ( ) { return this . nextDiscount ; } public void setNextDiscountOption ( LongOption nextDiscount ) { this . nextDiscount . copyFrom ( nextDiscount ) ; } public long getNextTax ( ) { return this . nextTax . get ( ) ; } public void setNextTax ( long nextTax ) { this . nextTax . modify ( nextTax ) ; } public LongOption getNextTaxOption ( ) { return this . nextTax ; } public void setNextTaxOption ( LongOption nextTax ) { this . nextTax . copyFrom ( nextTax ) ; } public Text getPaymentFlag ( ) { return this . paymentFlag . get ( ) ; } public void setPaymentFlag ( Text paymentFlag ) { this . paymentFlag . modify ( paymentFlag ) ; } public String getPaymentFlagAsString ( ) { return this . paymentFlag . getAsString ( ) ; } public void setPaymentFlagAsString ( String paymentFlag ) { this . paymentFlag . modify ( paymentFlag ) ; } public StringOption getPaymentFlagOption ( ) { return this . paymentFlag ; } public void setPaymentFlagOption ( StringOption paymentFlag ) { this . paymentFlag . copyFrom ( paymentFlag ) ; } public void copyFrom ( BalanceTran source ) { this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . rgstDatetime . copyFrom ( source . rgstDatetime ) ; this . updtDatetime . copyFrom ( source . updtDatetime ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . previousCutoffDate . copyFrom ( source . previousCutoffDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . nextCutoffDate . copyFrom ( source . nextCutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . carried . copyFrom ( source . carried ) ; this . purchase . copyFrom ( source . purchase ) ; this . rtn . copyFrom ( source . rtn ) ; this . discount . copyFrom ( source . discount ) ; this . tax . copyFrom ( source . tax ) ; this . payable . copyFrom ( source . payable ) ; this . mutual . copyFrom ( source . mutual ) ; this . reserves . copyFrom ( source . reserves ) ; this . cancel . copyFrom ( source . cancel ) ; this . payment . copyFrom ( source . payment ) ; this . nextPurchase . copyFrom ( source . nextPurchase ) ; this . nextReturn . copyFrom ( source . nextReturn ) ; this . nextDiscount . copyFrom ( source . nextDiscount ) ; this . nextTax . copyFrom ( source . nextTax ) ; this . paymentFlag . copyFrom ( source . paymentFlag ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; versionNo . write ( out ) ; rgstDatetime . write ( out ) ; updtDatetime . write ( out ) ; sellerCode . write ( out ) ; previousCutoffDate . write ( out ) ; cutoffDate . write ( out ) ; nextCutoffDate . write ( out ) ; payoutDate . write ( out ) ; carried . write ( out ) ; purchase . write ( out ) ; rtn . write ( out ) ; discount . write ( out ) ; tax . write ( out ) ; payable . write ( out ) ; mutual . write ( out ) ; reserves . write ( out ) ; cancel . write ( out ) ; payment . write ( out ) ; nextPurchase . write ( out ) ; nextReturn . write ( out ) ; nextDiscount . write ( out ) ; nextTax . write ( out ) ; paymentFlag . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; versionNo . readFields ( in ) ; rgstDatetime . readFields ( in ) ; updtDatetime . readFields ( in ) ; sellerCode . readFields ( in ) ; previousCutoffDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; nextCutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; carried . readFields ( in ) ; purchase . readFields ( in ) ; rtn . readFields ( in ) ; discount . readFields ( in ) ; tax . readFields ( in ) ; payable . readFields ( in ) ; mutual . readFields ( in ) ; reserves . readFields ( in ) ; cancel . readFields ( in ) ; payment . readFields ( in ) ; nextPurchase . readFields ( in ) ; nextReturn . readFields ( in ) ; nextDiscount . readFields ( in ) ; nextTax . readFields ( in ) ; paymentFlag . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + rgstDatetime . hashCode ( ) ; result = prime * result + updtDatetime . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + previousCutoffDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + nextCutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + carried . hashCode ( ) ; result = prime * result + purchase . hashCode ( ) ; result = prime * result + rtn . hashCode ( ) ; result = prime * result + discount . hashCode ( ) ; result = prime * result + tax . hashCode ( ) ; result = prime * result + payable . hashCode ( ) ; result = prime * result + mutual . hashCode ( ) ; result = prime * result + reserves . hashCode ( ) ; result = prime * result + cancel . hashCode ( ) ; result = prime * result + payment . hashCode ( ) ; result = prime * result + nextPurchase . hashCode ( ) ; result = prime * result + nextReturn . hashCode ( ) ; result = prime * result + nextDiscount . hashCode ( ) ; result = prime * result + nextTax . hashCode ( ) ; result = prime * result + paymentFlag . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } BalanceTran other = ( BalanceTran ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . rgstDatetime . equals ( other . rgstDatetime ) == false ) { return false ; } if ( this . updtDatetime . equals ( other . updtDatetime ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . previousCutoffDate . equals ( other . previousCutoffDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . nextCutoffDate . equals ( other . nextCutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . carried . equals ( other . carried ) == false ) { return false ; } if ( this . purchase . equals ( other . purchase ) == false ) { return false ; } if ( this . rtn . equals ( other . rtn ) == false ) { return false ; } if ( this . discount . equals ( other . discount ) == false ) { return false ; } if ( this . tax . equals ( other . tax ) == false ) { return false ; } if ( this . payable . equals ( other . payable ) == false ) { return false ; } if ( this . mutual . equals ( other . mutual ) == false ) { return false ; } if ( this . reserves . equals ( other . reserves ) == false ) { return false ; } if ( this . cancel . equals ( other . cancel ) == false ) { return false ; } if ( this . payment . equals ( other . payment ) == false ) { return false ; } if ( this . nextPurchase . equals ( other . nextPurchase ) == false ) { return false ; } if ( this . nextReturn . equals ( other . nextReturn ) == false ) { return false ; } if ( this . nextDiscount . equals ( other . nextDiscount ) == false ) { return false ; } if ( this . nextTax . equals ( other . nextTax ) == false ) { return false ; } if ( this . paymentFlag . equals ( other . paymentFlag ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . rgstDatetime ) ; result . append ( "" ) ; result . append ( this . updtDatetime ) ; result . append ( "" ) ; result . append ( this . sellerCode ) ; result . append ( "" ) ; result . append ( this . previousCutoffDate ) ; result . append ( "" ) ; result . append ( this . cutoffDate ) ; result . append ( "" ) ; result . append ( this . nextCutoffDate ) ; result . append ( "" ) ; result . append ( this . payoutDate ) ; result . append ( "" ) ; result . append ( this . carried ) ; result . append ( "" ) ; result . append ( this . purchase ) ; result . append ( "" ) ; result . append ( this . rtn ) ; result . append ( "" ) ; result . append ( this . discount ) ; result . append ( "" ) ; result . append ( this . tax ) ; result . append ( "" ) ; result . append ( this . payable ) ; result . append ( "" ) ; result . append ( this . mutual ) ; result . append ( "" ) ; result . append ( this . reserves ) ; result . append ( "" ) ; result . append ( this . cancel ) ; result . append ( "" ) ; result . append ( this . payment ) ; result . append ( "" ) ; result . append ( this . nextPurchase ) ; result . append ( "" ) ; result . append ( this . nextReturn ) ; result . append ( "" ) ; result . append ( this . nextDiscount ) ; result . append ( "" ) ; result . append ( this . nextTax ) ; result . append ( "" ) ; result . append ( this . paymentFlag ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempImportTarget13 implements Writable { @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption duplicateFlg = new StringOption ( ) ; @ Property ( name = "" ) private StringOption textdata1 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata1 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata1 = new DateTimeOption ( ) ; public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getDuplicateFlg ( ) { return this . duplicateFlg . get ( ) ; } public void setDuplicateFlg ( Text duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public String getDuplicateFlgAsString ( ) { return this . duplicateFlg . getAsString ( ) ; } public void setDuplicateFlgAsString ( String duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public StringOption getDuplicateFlgOption ( ) { return this . duplicateFlg ; } public void setDuplicateFlgOption ( StringOption duplicateFlg ) { this . duplicateFlg . copyFrom ( duplicateFlg ) ; } public Text getTextdata1 ( ) { return this . textdata1 . get ( ) ; } public void setTextdata1 ( Text textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public String getTextdata1AsString ( ) { return this . textdata1 . getAsString ( ) ; } public void setTextdata1AsString ( String textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public StringOption getTextdata1Option ( ) { return this . textdata1 ; } public void setTextdata1Option ( StringOption textdata1 ) { this . textdata1 . copyFrom ( textdata1 ) ; } public int getIntdata1 ( ) { return this . intdata1 . get ( ) ; } public void setIntdata1 ( int intdata1 ) { this . intdata1 . modify ( intdata1 ) ; } public IntOption getIntdata1Option ( ) { return this . intdata1 ; } public void setIntdata1Option ( IntOption intdata1 ) { this . intdata1 . copyFrom ( intdata1 ) ; } public DateTime getDatedata1 ( ) { return this . datedata1 . get ( ) ; } public void setDatedata1 ( DateTime datedata1 ) { this . datedata1 . modify ( datedata1 ) ; } public DateTimeOption getDatedata1Option ( ) { return this . datedata1 ; } public void setDatedata1Option ( DateTimeOption datedata1 ) { this . datedata1 . copyFrom ( datedata1 ) ; } public void copyFrom ( ExportTempImportTarget13 source ) { this . versionNo . copyFrom ( source . versionNo ) ; this . tempSid . copyFrom ( source . tempSid ) ; this . sid . copyFrom ( source . sid ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . duplicateFlg . copyFrom ( source . duplicateFlg ) ; this . textdata1 . copyFrom ( source . textdata1 ) ; this . intdata1 . copyFrom ( source . intdata1 ) ; this . datedata1 . copyFrom ( source . datedata1 ) ; } @ Override public void write ( DataOutput out ) throws IOException { versionNo . write ( out ) ; tempSid . write ( out ) ; sid . write ( out ) ; updtDate . write ( out ) ; duplicateFlg . write ( out ) ; textdata1 . write ( out ) ; intdata1 . write ( out ) ; datedata1 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { versionNo . readFields ( in ) ; tempSid . readFields ( in ) ; sid . readFields ( in ) ; updtDate . readFields ( in ) ; duplicateFlg . readFields ( in ) ; textdata1 . readFields ( in ) ; intdata1 . readFields ( in ) ; datedata1 . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result += prime * result + versionNo . hashCode ( ) ; result += prime * result + tempSid . hashCode ( ) ; result += prime * result + sid . hashCode ( ) ; result += prime * result + updtDate . hashCode ( ) ; result += prime * result + duplicateFlg . hashCode ( ) ; result += prime * result + textdata1 . hashCode ( ) ; result += prime * result + intdata1 . hashCode ( ) ; result += prime * result + datedata1 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempImportTarget13 other = ( ExportTempImportTarget13 ) obj ; if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . duplicateFlg . equals ( other . duplicateFlg ) == false ) { return false ; } if ( this . textdata1 . equals ( other . textdata1 ) == false ) { return false ; } if ( this . intdata1 . equals ( other . intdata1 ) == false ) { return false ; } if ( this . datedata1 . equals ( other . datedata1 ) == false ) { return false ; } return true ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class ExportTempImportTarget21Df implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public void copyFrom ( ExportTempImportTarget21Df source ) { this . tempSid . copyFrom ( source . tempSid ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempImportTarget21Df other = ( ExportTempImportTarget21Df ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" } , primary = { "" , "" } ) @ SuppressWarnings ( "" ) public class ExportTempTable implements Writable { @ Property ( name = "" ) private LongOption jobflowSid = new LongOption ( ) ; @ Property ( name = "" ) private StringOption tableName = new StringOption ( ) ; @ Property ( name = "" ) private LongOption exportTempSeq = new LongOption ( ) ; @ Property ( name = "" ) private StringOption exportTempName = new StringOption ( ) ; @ Property ( name = "" ) private StringOption duplicateFlgName = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tempTableStatus = new StringOption ( ) ; public long getJobflowSid ( ) { return this . jobflowSid . get ( ) ; } public void setJobflowSid ( long jobflowSid ) { this . jobflowSid . modify ( jobflowSid ) ; } public LongOption getJobflowSidOption ( ) { return this . jobflowSid ; } public void setJobflowSidOption ( LongOption jobflowSid ) { this . jobflowSid . copyFrom ( jobflowSid ) ; } public Text getTableName ( ) { return this . tableName . get ( ) ; } public void setTableName ( Text tableName ) { this . tableName . modify ( tableName ) ; } public String getTableNameAsString ( ) { return this . tableName . getAsString ( ) ; } public void setTableNameAsString ( String tableName ) { this . tableName . modify ( tableName ) ; } public StringOption getTableNameOption ( ) { return this . tableName ; } public void setTableNameOption ( StringOption tableName ) { this . tableName . copyFrom ( tableName ) ; } public long getExportTempSeq ( ) { return this . exportTempSeq . get ( ) ; } public void setExportTempSeq ( long exportTempSeq ) { this . exportTempSeq . modify ( exportTempSeq ) ; } public LongOption getExportTempSeqOption ( ) { return this . exportTempSeq ; } public void setExportTempSeqOption ( LongOption exportTempSeq ) { this . exportTempSeq . copyFrom ( exportTempSeq ) ; } public Text getExportTempName ( ) { return this . exportTempName . get ( ) ; } public void setExportTempName ( Text exportTempName ) { this . exportTempName . modify ( exportTempName ) ; } public String getExportTempNameAsString ( ) { return this . exportTempName . getAsString ( ) ; } public void setExportTempNameAsString ( String exportTempName ) { this . exportTempName . modify ( exportTempName ) ; } public StringOption getExportTempNameOption ( ) { return this . exportTempName ; } public void setExportTempNameOption ( StringOption exportTempName ) { this . exportTempName . copyFrom ( exportTempName ) ; } public Text getDuplicateFlgName ( ) { return this . duplicateFlgName . get ( ) ; } public void setDuplicateFlgName ( Text duplicateFlgName ) { this . duplicateFlgName . modify ( duplicateFlgName ) ; } public String getDuplicateFlgNameAsString ( ) { return this . duplicateFlgName . getAsString ( ) ; } public void setDuplicateFlgNameAsString ( String duplicateFlgName ) { this . duplicateFlgName . modify ( duplicateFlgName ) ; } public StringOption getDuplicateFlgNameOption ( ) { return this . duplicateFlgName ; } public void setDuplicateFlgNameOption ( StringOption duplicateFlgName ) { this . duplicateFlgName . copyFrom ( duplicateFlgName ) ; } public Text getTempTableStatus ( ) { return this . tempTableStatus . get ( ) ; } public void setTempTableStatus ( Text tempTableStatus ) { this . tempTableStatus . modify ( tempTableStatus ) ; } public String getTempTableStatusAsString ( ) { return this . tempTableStatus . getAsString ( ) ; } public void setTempTableStatusAsString ( String tempTableStatus ) { this . tempTableStatus . modify ( tempTableStatus ) ; } public StringOption getTempTableStatusOption ( ) { return this . tempTableStatus ; } public void setTempTableStatusOption ( StringOption tempTableStatus ) { this . tempTableStatus . copyFrom ( tempTableStatus ) ; } public void copyFrom ( ExportTempTable source ) { this . jobflowSid . copyFrom ( source . jobflowSid ) ; this . tableName . copyFrom ( source . tableName ) ; this . exportTempSeq . copyFrom ( source . exportTempSeq ) ; this . exportTempName . copyFrom ( source . exportTempName ) ; this . duplicateFlgName . copyFrom ( source . duplicateFlgName ) ; this . tempTableStatus . copyFrom ( source . tempTableStatus ) ; } @ Override public void write ( DataOutput out ) throws IOException { jobflowSid . write ( out ) ; tableName . write ( out ) ; exportTempSeq . write ( out ) ; exportTempName . write ( out ) ; duplicateFlgName . write ( out ) ; tempTableStatus . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { jobflowSid . readFields ( in ) ; tableName . readFields ( in ) ; exportTempSeq . readFields ( in ) ; exportTempName . readFields ( in ) ; duplicateFlgName . readFields ( in ) ; tempTableStatus . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + jobflowSid . hashCode ( ) ; result = prime * result + tableName . hashCode ( ) ; result = prime * result + exportTempSeq . hashCode ( ) ; result = prime * result + exportTempName . hashCode ( ) ; result = prime * result + duplicateFlgName . hashCode ( ) ; result = prime * result + tempTableStatus . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExportTempTable other = ( ExportTempTable ) obj ; if ( this . jobflowSid . equals ( other . jobflowSid ) == false ) { return false ; } if ( this . tableName . equals ( other . tableName ) == false ) { return false ; } if ( this . exportTempSeq . equals ( other . exportTempSeq ) == false ) { return false ; } if ( this . exportTempName . equals ( other . exportTempName ) == false ) { return false ; } if ( this . duplicateFlgName . equals ( other . duplicateFlgName ) == false ) { return false ; } if ( this . tempTableStatus . equals ( other . tempTableStatus ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . jobflowSid ) ; result . append ( "" ) ; result . append ( this . tableName ) ; result . append ( "" ) ; result . append ( this . exportTempSeq ) ; result . append ( "" ) ; result . append ( this . exportTempName ) ; result . append ( "" ) ; result . append ( this . duplicateFlgName ) ; result . append ( "" ) ; result . append ( this . tempTableStatus ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" } , primary = { "" , "" } ) @ SuppressWarnings ( "" ) public class ImportRecordLock implements Writable { @ Property ( name = "" ) private LongOption jobflowSid = new LongOption ( ) ; @ Property ( name = "" ) private StringOption tableName = new StringOption ( ) ; public long getJobflowSid ( ) { return this . jobflowSid . get ( ) ; } public void setJobflowSid ( long jobflowSid ) { this . jobflowSid . modify ( jobflowSid ) ; } public LongOption getJobflowSidOption ( ) { return this . jobflowSid ; } public void setJobflowSidOption ( LongOption jobflowSid ) { this . jobflowSid . copyFrom ( jobflowSid ) ; } public Text getTableName ( ) { return this . tableName . get ( ) ; } public void setTableName ( Text tableName ) { this . tableName . modify ( tableName ) ; } public String getTableNameAsString ( ) { return this . tableName . getAsString ( ) ; } public void setTableNameAsString ( String tableName ) { this . tableName . modify ( tableName ) ; } public StringOption getTableNameOption ( ) { return this . tableName ; } public void setTableNameOption ( StringOption tableName ) { this . tableName . copyFrom ( tableName ) ; } public void copyFrom ( ImportRecordLock source ) { this . jobflowSid . copyFrom ( source . jobflowSid ) ; this . tableName . copyFrom ( source . tableName ) ; } @ Override public void write ( DataOutput out ) throws IOException { jobflowSid . write ( out ) ; tableName . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { jobflowSid . readFields ( in ) ; tableName . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + jobflowSid . hashCode ( ) ; result = prime * result + tableName . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ImportRecordLock other = ( ImportRecordLock ) obj ; if ( this . jobflowSid . equals ( other . jobflowSid ) == false ) { return false ; } if ( this . tableName . equals ( other . tableName ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . jobflowSid ) ; result . append ( "" ) ; result . append ( this . tableName ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ Generated ( "" ) @ DataModel @ TableModel ( name = "" , columns = { "" , "" , "" , "" , "" , "" , "" , "" , "" } , primary = { "" } ) @ SuppressWarnings ( "" ) public class TempImportTarget1 implements Writable { @ Property ( name = "" ) private LongOption tempSid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sid = new LongOption ( ) ; @ Property ( name = "" ) private LongOption versionNo = new LongOption ( ) ; @ Property ( name = "" ) private StringOption textdata1 = new StringOption ( ) ; @ Property ( name = "" ) private IntOption intdata1 = new IntOption ( ) ; @ Property ( name = "" ) private DateTimeOption datedata1 = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption rgstDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateTimeOption updtDate = new DateTimeOption ( ) ; @ Property ( name = "" ) private StringOption duplicateFlg = new StringOption ( ) ; public long getTempSid ( ) { return this . tempSid . get ( ) ; } public void setTempSid ( long tempSid ) { this . tempSid . modify ( tempSid ) ; } public LongOption getTempSidOption ( ) { return this . tempSid ; } public void setTempSidOption ( LongOption tempSid ) { this . tempSid . copyFrom ( tempSid ) ; } public long getSid ( ) { return this . sid . get ( ) ; } public void setSid ( long sid ) { this . sid . modify ( sid ) ; } public LongOption getSidOption ( ) { return this . sid ; } public void setSidOption ( LongOption sid ) { this . sid . copyFrom ( sid ) ; } public long getVersionNo ( ) { return this . versionNo . get ( ) ; } public void setVersionNo ( long versionNo ) { this . versionNo . modify ( versionNo ) ; } public LongOption getVersionNoOption ( ) { return this . versionNo ; } public void setVersionNoOption ( LongOption versionNo ) { this . versionNo . copyFrom ( versionNo ) ; } public Text getTextdata1 ( ) { return this . textdata1 . get ( ) ; } public void setTextdata1 ( Text textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public String getTextdata1AsString ( ) { return this . textdata1 . getAsString ( ) ; } public void setTextdata1AsString ( String textdata1 ) { this . textdata1 . modify ( textdata1 ) ; } public StringOption getTextdata1Option ( ) { return this . textdata1 ; } public void setTextdata1Option ( StringOption textdata1 ) { this . textdata1 . copyFrom ( textdata1 ) ; } public int getIntdata1 ( ) { return this . intdata1 . get ( ) ; } public void setIntdata1 ( int intdata1 ) { this . intdata1 . modify ( intdata1 ) ; } public IntOption getIntdata1Option ( ) { return this . intdata1 ; } public void setIntdata1Option ( IntOption intdata1 ) { this . intdata1 . copyFrom ( intdata1 ) ; } public DateTime getDatedata1 ( ) { return this . datedata1 . get ( ) ; } public void setDatedata1 ( DateTime datedata1 ) { this . datedata1 . modify ( datedata1 ) ; } public DateTimeOption getDatedata1Option ( ) { return this . datedata1 ; } public void setDatedata1Option ( DateTimeOption datedata1 ) { this . datedata1 . copyFrom ( datedata1 ) ; } public DateTime getRgstDate ( ) { return this . rgstDate . get ( ) ; } public void setRgstDate ( DateTime rgstDate ) { this . rgstDate . modify ( rgstDate ) ; } public DateTimeOption getRgstDateOption ( ) { return this . rgstDate ; } public void setRgstDateOption ( DateTimeOption rgstDate ) { this . rgstDate . copyFrom ( rgstDate ) ; } public DateTime getUpdtDate ( ) { return this . updtDate . get ( ) ; } public void setUpdtDate ( DateTime updtDate ) { this . updtDate . modify ( updtDate ) ; } public DateTimeOption getUpdtDateOption ( ) { return this . updtDate ; } public void setUpdtDateOption ( DateTimeOption updtDate ) { this . updtDate . copyFrom ( updtDate ) ; } public Text getDuplicateFlg ( ) { return this . duplicateFlg . get ( ) ; } public void setDuplicateFlg ( Text duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public String getDuplicateFlgAsString ( ) { return this . duplicateFlg . getAsString ( ) ; } public void setDuplicateFlgAsString ( String duplicateFlg ) { this . duplicateFlg . modify ( duplicateFlg ) ; } public StringOption getDuplicateFlgOption ( ) { return this . duplicateFlg ; } public void setDuplicateFlgOption ( StringOption duplicateFlg ) { this . duplicateFlg . copyFrom ( duplicateFlg ) ; } public void copyFrom ( TempImportTarget1 source ) { this . tempSid . copyFrom ( source . tempSid ) ; this . sid . copyFrom ( source . sid ) ; this . versionNo . copyFrom ( source . versionNo ) ; this . textdata1 . copyFrom ( source . textdata1 ) ; this . intdata1 . copyFrom ( source . intdata1 ) ; this . datedata1 . copyFrom ( source . datedata1 ) ; this . rgstDate . copyFrom ( source . rgstDate ) ; this . updtDate . copyFrom ( source . updtDate ) ; this . duplicateFlg . copyFrom ( source . duplicateFlg ) ; } @ Override public void write ( DataOutput out ) throws IOException { tempSid . write ( out ) ; sid . write ( out ) ; versionNo . write ( out ) ; textdata1 . write ( out ) ; intdata1 . write ( out ) ; datedata1 . write ( out ) ; rgstDate . write ( out ) ; updtDate . write ( out ) ; duplicateFlg . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { tempSid . readFields ( in ) ; sid . readFields ( in ) ; versionNo . readFields ( in ) ; textdata1 . readFields ( in ) ; intdata1 . readFields ( in ) ; datedata1 . readFields ( in ) ; rgstDate . readFields ( in ) ; updtDate . readFields ( in ) ; duplicateFlg . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + tempSid . hashCode ( ) ; result = prime * result + sid . hashCode ( ) ; result = prime * result + versionNo . hashCode ( ) ; result = prime * result + textdata1 . hashCode ( ) ; result = prime * result + intdata1 . hashCode ( ) ; result = prime * result + datedata1 . hashCode ( ) ; result = prime * result + rgstDate . hashCode ( ) ; result = prime * result + updtDate . hashCode ( ) ; result = prime * result + duplicateFlg . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } TempImportTarget1 other = ( TempImportTarget1 ) obj ; if ( this . tempSid . equals ( other . tempSid ) == false ) { return false ; } if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . versionNo . equals ( other . versionNo ) == false ) { return false ; } if ( this . textdata1 . equals ( other . textdata1 ) == false ) { return false ; } if ( this . intdata1 . equals ( other . intdata1 ) == false ) { return false ; } if ( this . datedata1 . equals ( other . datedata1 ) == false ) { return false ; } if ( this . rgstDate . equals ( other . rgstDate ) == false ) { return false ; } if ( this . updtDate . equals ( other . updtDate ) == false ) { return false ; } if ( this . duplicateFlg . equals ( other . duplicateFlg ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . tempSid ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . versionNo ) ; result . append ( "" ) ; result . append ( this . textdata1 ) ; result . append ( "" ) ; result . append ( this . intdata1 ) ; result . append ( "" ) ; result . append ( this . datedata1 ) ; result . append ( "" ) ; result . append ( this . rgstDate ) ; result . append ( "" ) ; result . append ( this . updtDate ) ; result . append ( "" ) ; result . append ( this . duplicateFlg ) ; result . append ( "" ) ; return result . toString ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget2ModelOutput implements ModelOutput < ImportTarget2 > { private final RecordEmitter emitter ; public ImportTarget2ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ImportTarget2 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getTextdata2Option ( ) ) ; emitter . emit ( model . getIntdata2Option ( ) ) ; emitter . emit ( model . getDatedata2Option ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget19 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget19ModelInput implements ModelInput < ExportTempImportTarget19 > { private final RecordParser parser ; public ExportTempImportTarget19ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempImportTarget19 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getDuplicateFlgOption ( ) ) ; parser . fill ( model . getTextdata1Option ( ) ) ; parser . fill ( model . getIntdata2Option ( ) ) ; parser . fill ( model . getDatedata2Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget2Rl ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget2RlModelOutput implements ModelOutput < ImportTarget2Rl > { private final RecordEmitter emitter ; public ImportTarget2RlModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ImportTarget2Rl model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getJobflowSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . PurchaseTranError2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class PurchaseTranError2ModelOutput implements ModelOutput < PurchaseTranError2 > { private final RecordEmitter emitter ; public PurchaseTranError2ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( PurchaseTranError2 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDatetimeOption ( ) ) ; emitter . emit ( model . getUpdtDatetimeOption ( ) ) ; emitter . emit ( model . getPurchaseNoOption ( ) ) ; emitter . emit ( model . getPurchaseTypeOption ( ) ) ; emitter . emit ( model . getTradeTypeOption ( ) ) ; emitter . emit ( model . getTradeNoOption ( ) ) ; emitter . emit ( model . getLineNoOption ( ) ) ; emitter . emit ( model . getDeliveryDateOption ( ) ) ; emitter . emit ( model . getStoreCodeOption ( ) ) ; emitter . emit ( model . getBuyerCodeOption ( ) ) ; emitter . emit ( model . getPurchaseTypeCodeOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getTenantCodeOption ( ) ) ; emitter . emit ( model . getNetPriceTotalOption ( ) ) ; emitter . emit ( model . getSellingPriceTotalOption ( ) ) ; emitter . emit ( model . getShipmentStoreCodeOption ( ) ) ; emitter . emit ( model . getShipmentSalesTypeCodeOption ( ) ) ; emitter . emit ( model . getDeductionCodeOption ( ) ) ; emitter . emit ( model . getAccountCodeOption ( ) ) ; emitter . emit ( model . getOwnershipDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getPayoutDateOption ( ) ) ; emitter . emit ( model . getOwnershipFlagOption ( ) ) ; emitter . emit ( model . getCutoffFlagOption ( ) ) ; emitter . emit ( model . getPayoutFlagOption ( ) ) ; emitter . emit ( model . getDisposeNoOption ( ) ) ; emitter . emit ( model . getDisposeDateOption ( ) ) ; emitter . emit ( model . getErrorCauseOption ( ) ) ; emitter . emit ( model . getErrorCodeOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . BalanceTran ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class BalanceTranModelInput implements ModelInput < BalanceTran > { private final RecordParser parser ; public BalanceTranModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( BalanceTran model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDatetimeOption ( ) ) ; parser . fill ( model . getUpdtDatetimeOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getPreviousCutoffDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getNextCutoffDateOption ( ) ) ; parser . fill ( model . getPayoutDateOption ( ) ) ; parser . fill ( model . getCarriedOption ( ) ) ; parser . fill ( model . getPurchaseOption ( ) ) ; parser . fill ( model . getRtnOption ( ) ) ; parser . fill ( model . getDiscountOption ( ) ) ; parser . fill ( model . getTaxOption ( ) ) ; parser . fill ( model . getPayableOption ( ) ) ; parser . fill ( model . getMutualOption ( ) ) ; parser . fill ( model . getReservesOption ( ) ) ; parser . fill ( model . getCancelOption ( ) ) ; parser . fill ( model . getPaymentOption ( ) ) ; parser . fill ( model . getNextPurchaseOption ( ) ) ; parser . fill ( model . getNextReturnOption ( ) ) ; parser . fill ( model . getNextDiscountOption ( ) ) ; parser . fill ( model . getNextTaxOption ( ) ) ; parser . fill ( model . getPaymentFlagOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget21Df ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget21DfModelInput implements ModelInput < ExportTempImportTarget21Df > { private final RecordParser parser ; public ExportTempImportTarget21DfModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempImportTarget21Df model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget13 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget13ModelInput implements ModelInput < ExportTempImportTarget13 > { private final RecordParser parser ; public ExportTempImportTarget13ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempImportTarget13 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getTempSidOption ( ) ) ; parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getDuplicateFlgOption ( ) ) ; parser . fill ( model . getTextdata1Option ( ) ) ; parser . fill ( model . getIntdata1Option ( ) ) ; parser . fill ( model . getDatedata1Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget1ModelOutput implements ModelOutput < ImportTarget1 > { private final RecordEmitter emitter ; public ImportTarget1ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ImportTarget1 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getTextdata1Option ( ) ) ; emitter . emit ( model . getIntdata1Option ( ) ) ; emitter . emit ( model . getDatedata1Option ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget21 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget21ModelInput implements ModelInput < ExportTempImportTarget21 > { private final RecordParser parser ; public ExportTempImportTarget21ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempImportTarget21 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getDuplicateFlgOption ( ) ) ; parser . fill ( model . getTextdata2Option ( ) ) ; parser . fill ( model . getIntdata2Option ( ) ) ; parser . fill ( model . getDatedata2Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . Temp7 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class Temp7ModelInput implements ModelInput < Temp7 > { private final RecordParser parser ; public Temp7ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( Temp7 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getTextdata2Option ( ) ) ; parser . fill ( model . getIntdata2Option ( ) ) ; parser . fill ( model . getDatedata2Option ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getDuplicateFlgOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportRecordLock ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportRecordLockModelOutput implements ModelOutput < ImportRecordLock > { private final RecordEmitter emitter ; public ImportRecordLockModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ImportRecordLock model ) throws IOException { emitter . emit ( model . getJobflowSidOption ( ) ) ; emitter . emit ( model . getTableNameOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . DeductionTran ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class DeductionTranModelOutput implements ModelOutput < DeductionTran > { private final RecordEmitter emitter ; public DeductionTranModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( DeductionTran model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDatetimeOption ( ) ) ; emitter . emit ( model . getUpdtDatetimeOption ( ) ) ; emitter . emit ( model . getDeductionNoOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getBuyerCodeOption ( ) ) ; emitter . emit ( model . getClosedDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getCutoffFlagOption ( ) ) ; emitter . emit ( model . getPayoutFlagOption ( ) ) ; emitter . emit ( model . getDisposeNoOption ( ) ) ; emitter . emit ( model . getDisposeDateOption ( ) ) ; emitter . emit ( model . getDetailCountOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget2ModelInput implements ModelInput < ImportTarget2 > { private final RecordParser parser ; public ImportTarget2ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ImportTarget2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getTextdata2Option ( ) ) ; parser . fill ( model . getIntdata2Option ( ) ) ; parser . fill ( model . getDatedata2Option ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . PurchaseTranError ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class PurchaseTranErrorModelOutput implements ModelOutput < PurchaseTranError > { private final RecordEmitter emitter ; public PurchaseTranErrorModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( PurchaseTranError model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDatetimeOption ( ) ) ; emitter . emit ( model . getUpdtDatetimeOption ( ) ) ; emitter . emit ( model . getPurchaseNoOption ( ) ) ; emitter . emit ( model . getPurchaseTypeOption ( ) ) ; emitter . emit ( model . getTradeTypeOption ( ) ) ; emitter . emit ( model . getTradeNoOption ( ) ) ; emitter . emit ( model . getLineNoOption ( ) ) ; emitter . emit ( model . getDeliveryDateOption ( ) ) ; emitter . emit ( model . getStoreCodeOption ( ) ) ; emitter . emit ( model . getBuyerCodeOption ( ) ) ; emitter . emit ( model . getPurchaseTypeCodeOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getTenantCodeOption ( ) ) ; emitter . emit ( model . getNetPriceTotalOption ( ) ) ; emitter . emit ( model . getSellingPriceTotalOption ( ) ) ; emitter . emit ( model . getShipmentStoreCodeOption ( ) ) ; emitter . emit ( model . getShipmentSalesTypeCodeOption ( ) ) ; emitter . emit ( model . getDeductionCodeOption ( ) ) ; emitter . emit ( model . getAccountCodeOption ( ) ) ; emitter . emit ( model . getOwnershipDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getPayoutDateOption ( ) ) ; emitter . emit ( model . getOwnershipFlagOption ( ) ) ; emitter . emit ( model . getCutoffFlagOption ( ) ) ; emitter . emit ( model . getPayoutFlagOption ( ) ) ; emitter . emit ( model . getDisposeNoOption ( ) ) ; emitter . emit ( model . getDisposeDateOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . DeductionTran ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class DeductionTranModelInput implements ModelInput < DeductionTran > { private final RecordParser parser ; public DeductionTranModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( DeductionTran model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDatetimeOption ( ) ) ; parser . fill ( model . getUpdtDatetimeOption ( ) ) ; parser . fill ( model . getDeductionNoOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getBuyerCodeOption ( ) ) ; parser . fill ( model . getClosedDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getCutoffFlagOption ( ) ) ; parser . fill ( model . getPayoutFlagOption ( ) ) ; parser . fill ( model . getDisposeNoOption ( ) ) ; parser . fill ( model . getDisposeDateOption ( ) ) ; parser . fill ( model . getDetailCountOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTableLock ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTableLockModelOutput implements ModelOutput < ImportTableLock > { private final RecordEmitter emitter ; public ImportTableLockModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ImportTableLock model ) throws IOException { emitter . emit ( model . getTableNameOption ( ) ) ; emitter . emit ( model . getJobflowSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget2Error ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget2ErrorModelOutput implements ModelOutput < ImportTarget2Error > { private final RecordEmitter emitter ; public ImportTarget2ErrorModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ImportTarget2Error model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getTextdata2Option ( ) ) ; emitter . emit ( model . getIntdata2Option ( ) ) ; emitter . emit ( model . getDatedata2Option ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getErrorCodeOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . PurchaseTranError ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class PurchaseTranErrorModelInput implements ModelInput < PurchaseTranError > { private final RecordParser parser ; public PurchaseTranErrorModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( PurchaseTranError model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDatetimeOption ( ) ) ; parser . fill ( model . getUpdtDatetimeOption ( ) ) ; parser . fill ( model . getPurchaseNoOption ( ) ) ; parser . fill ( model . getPurchaseTypeOption ( ) ) ; parser . fill ( model . getTradeTypeOption ( ) ) ; parser . fill ( model . getTradeNoOption ( ) ) ; parser . fill ( model . getLineNoOption ( ) ) ; parser . fill ( model . getDeliveryDateOption ( ) ) ; parser . fill ( model . getStoreCodeOption ( ) ) ; parser . fill ( model . getBuyerCodeOption ( ) ) ; parser . fill ( model . getPurchaseTypeCodeOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getTenantCodeOption ( ) ) ; parser . fill ( model . getNetPriceTotalOption ( ) ) ; parser . fill ( model . getSellingPriceTotalOption ( ) ) ; parser . fill ( model . getShipmentStoreCodeOption ( ) ) ; parser . fill ( model . getShipmentSalesTypeCodeOption ( ) ) ; parser . fill ( model . getDeductionCodeOption ( ) ) ; parser . fill ( model . getAccountCodeOption ( ) ) ; parser . fill ( model . getOwnershipDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getPayoutDateOption ( ) ) ; parser . fill ( model . getOwnershipFlagOption ( ) ) ; parser . fill ( model . getCutoffFlagOption ( ) ) ; parser . fill ( model . getPayoutFlagOption ( ) ) ; parser . fill ( model . getDisposeNoOption ( ) ) ; parser . fill ( model . getDisposeDateOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempTable ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempTableModelOutput implements ModelOutput < ExportTempTable > { private final RecordEmitter emitter ; public ExportTempTableModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempTable model ) throws IOException { emitter . emit ( model . getJobflowSidOption ( ) ) ; emitter . emit ( model . getTableNameOption ( ) ) ; emitter . emit ( model . getExportTempSeqOption ( ) ) ; emitter . emit ( model . getExportTempNameOption ( ) ) ; emitter . emit ( model . getDuplicateFlgNameOption ( ) ) ; emitter . emit ( model . getTempTableStatusOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . PurchaseTran ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class PurchaseTranModelOutput implements ModelOutput < PurchaseTran > { private final RecordEmitter emitter ; public PurchaseTranModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( PurchaseTran model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDatetimeOption ( ) ) ; emitter . emit ( model . getUpdtDatetimeOption ( ) ) ; emitter . emit ( model . getPurchaseNoOption ( ) ) ; emitter . emit ( model . getPurchaseTypeOption ( ) ) ; emitter . emit ( model . getTradeTypeOption ( ) ) ; emitter . emit ( model . getTradeNoOption ( ) ) ; emitter . emit ( model . getLineNoOption ( ) ) ; emitter . emit ( model . getDeliveryDateOption ( ) ) ; emitter . emit ( model . getStoreCodeOption ( ) ) ; emitter . emit ( model . getBuyerCodeOption ( ) ) ; emitter . emit ( model . getPurchaseTypeCodeOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getTenantCodeOption ( ) ) ; emitter . emit ( model . getNetPriceTotalOption ( ) ) ; emitter . emit ( model . getSellingPriceTotalOption ( ) ) ; emitter . emit ( model . getShipmentStoreCodeOption ( ) ) ; emitter . emit ( model . getShipmentSalesTypeCodeOption ( ) ) ; emitter . emit ( model . getDeductionCodeOption ( ) ) ; emitter . emit ( model . getAccountCodeOption ( ) ) ; emitter . emit ( model . getOwnershipDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getPayoutDateOption ( ) ) ; emitter . emit ( model . getOwnershipFlagOption ( ) ) ; emitter . emit ( model . getCutoffFlagOption ( ) ) ; emitter . emit ( model . getPayoutFlagOption ( ) ) ; emitter . emit ( model . getDisposeNoOption ( ) ) ; emitter . emit ( model . getDisposeDateOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . PurchaseTranError3 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class PurchaseTranError3ModelInput implements ModelInput < PurchaseTranError3 > { private final RecordParser parser ; public PurchaseTranError3ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( PurchaseTranError3 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDatetimeOption ( ) ) ; parser . fill ( model . getUpdtDatetimeOption ( ) ) ; parser . fill ( model . getPurchaseNoOption ( ) ) ; parser . fill ( model . getPurchaseTypeOption ( ) ) ; parser . fill ( model . getTradeTypeOption ( ) ) ; parser . fill ( model . getTradeNoOption ( ) ) ; parser . fill ( model . getErrorCauseOption ( ) ) ; parser . fill ( model . getErrorCodeOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget2Error ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget2ErrorModelInput implements ModelInput < ImportTarget2Error > { private final RecordParser parser ; public ImportTarget2ErrorModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ImportTarget2Error model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getTextdata2Option ( ) ) ; parser . fill ( model . getIntdata2Option ( ) ) ; parser . fill ( model . getDatedata2Option ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getErrorCodeOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget19 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget19ModelOutput implements ModelOutput < ExportTempImportTarget19 > { private final RecordEmitter emitter ; public ExportTempImportTarget19ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempImportTarget19 model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getDuplicateFlgOption ( ) ) ; emitter . emit ( model . getTextdata1Option ( ) ) ; emitter . emit ( model . getIntdata2Option ( ) ) ; emitter . emit ( model . getDatedata2Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . TempImportTarget2Df ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class TempImportTarget2DfModelOutput implements ModelOutput < TempImportTarget2Df > { private final RecordEmitter emitter ; public TempImportTarget2DfModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( TempImportTarget2Df model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . RunningJobflows ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class RunningJobflowsModelInput implements ModelInput < RunningJobflows > { private final RecordParser parser ; public RunningJobflowsModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( RunningJobflows model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getJobflowSidOption ( ) ) ; parser . fill ( model . getBatchIdOption ( ) ) ; parser . fill ( model . getJobflowIdOption ( ) ) ; parser . fill ( model . getTargetNameOption ( ) ) ; parser . fill ( model . getExecutionIdOption ( ) ) ; parser . fill ( model . getExpectedCompletionDatetimeOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget21Df ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget21DfModelOutput implements ModelOutput < ExportTempImportTarget21Df > { private final RecordEmitter emitter ; public ExportTempImportTarget21DfModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempImportTarget21Df model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget11Df ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget11DfModelOutput implements ModelOutput < ExportTempImportTarget11Df > { private final RecordEmitter emitter ; public ExportTempImportTarget11DfModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempImportTarget11Df model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . BalanceTranError ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class BalanceTranErrorModelOutput implements ModelOutput < BalanceTranError > { private final RecordEmitter emitter ; public BalanceTranErrorModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( BalanceTranError model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDatetimeOption ( ) ) ; emitter . emit ( model . getUpdtDatetimeOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getPreviousCutoffDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getNextCutoffDateOption ( ) ) ; emitter . emit ( model . getPayoutDateOption ( ) ) ; emitter . emit ( model . getCarriedOption ( ) ) ; emitter . emit ( model . getPurchaseOption ( ) ) ; emitter . emit ( model . getRtnOption ( ) ) ; emitter . emit ( model . getDiscountOption ( ) ) ; emitter . emit ( model . getTaxOption ( ) ) ; emitter . emit ( model . getPayableOption ( ) ) ; emitter . emit ( model . getMutualOption ( ) ) ; emitter . emit ( model . getReservesOption ( ) ) ; emitter . emit ( model . getCancelOption ( ) ) ; emitter . emit ( model . getPaymentOption ( ) ) ; emitter . emit ( model . getNextPurchaseOption ( ) ) ; emitter . emit ( model . getNextReturnOption ( ) ) ; emitter . emit ( model . getNextDiscountOption ( ) ) ; emitter . emit ( model . getNextTaxOption ( ) ) ; emitter . emit ( model . getErrorCodeOption ( ) ) ; emitter . emit ( model . getPaymentFlagOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . TempImportTarget1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class TempImportTarget1ModelInput implements ModelInput < TempImportTarget1 > { private final RecordParser parser ; public TempImportTarget1ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( TempImportTarget1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getTextdata1Option ( ) ) ; parser . fill ( model . getIntdata1Option ( ) ) ; parser . fill ( model . getDatedata1Option ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getDuplicateFlgOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTableLock ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTableLockModelInput implements ModelInput < ImportTableLock > { private final RecordParser parser ; public ImportTableLockModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ImportTableLock model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTableNameOption ( ) ) ; parser . fill ( model . getJobflowSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempPurchaseTran1Df ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempPurchaseTran1DfModelOutput implements ModelOutput < ExportTempPurchaseTran1Df > { private final RecordEmitter emitter ; public ExportTempPurchaseTran1DfModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempPurchaseTran1Df model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . BalanceTran ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class BalanceTranModelOutput implements ModelOutput < BalanceTran > { private final RecordEmitter emitter ; public BalanceTranModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( BalanceTran model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDatetimeOption ( ) ) ; emitter . emit ( model . getUpdtDatetimeOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getPreviousCutoffDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getNextCutoffDateOption ( ) ) ; emitter . emit ( model . getPayoutDateOption ( ) ) ; emitter . emit ( model . getCarriedOption ( ) ) ; emitter . emit ( model . getPurchaseOption ( ) ) ; emitter . emit ( model . getRtnOption ( ) ) ; emitter . emit ( model . getDiscountOption ( ) ) ; emitter . emit ( model . getTaxOption ( ) ) ; emitter . emit ( model . getPayableOption ( ) ) ; emitter . emit ( model . getMutualOption ( ) ) ; emitter . emit ( model . getReservesOption ( ) ) ; emitter . emit ( model . getCancelOption ( ) ) ; emitter . emit ( model . getPaymentOption ( ) ) ; emitter . emit ( model . getNextPurchaseOption ( ) ) ; emitter . emit ( model . getNextReturnOption ( ) ) ; emitter . emit ( model . getNextDiscountOption ( ) ) ; emitter . emit ( model . getNextTaxOption ( ) ) ; emitter . emit ( model . getPaymentFlagOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . JobflowInstanceLock ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class JobflowInstanceLockModelOutput implements ModelOutput < JobflowInstanceLock > { private final RecordEmitter emitter ; public JobflowInstanceLockModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( JobflowInstanceLock model ) throws IOException { emitter . emit ( model . getExecutionIdOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget1Rl ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget1RlModelOutput implements ModelOutput < ImportTarget1Rl > { private final RecordEmitter emitter ; public ImportTarget1RlModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ImportTarget1Rl model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getJobflowSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . TempImportTarget2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class TempImportTarget2ModelInput implements ModelInput < TempImportTarget2 > { private final RecordParser parser ; public TempImportTarget2ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( TempImportTarget2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getTextdata2Option ( ) ) ; parser . fill ( model . getIntdata2Option ( ) ) ; parser . fill ( model . getDatedata2Option ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getDuplicateFlgOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget11 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget11ModelOutput implements ModelOutput < ExportTempImportTarget11 > { private final RecordEmitter emitter ; public ExportTempImportTarget11ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempImportTarget11 model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getDuplicateFlgOption ( ) ) ; emitter . emit ( model . getTextdata1Option ( ) ) ; emitter . emit ( model . getIntdata1Option ( ) ) ; emitter . emit ( model . getDatedata1Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget19Df ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget19DfModelInput implements ModelInput < ExportTempImportTarget19Df > { private final RecordParser parser ; public ExportTempImportTarget19DfModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempImportTarget19Df model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget1Rl ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget1RlModelInput implements ModelInput < ImportTarget1Rl > { private final RecordParser parser ; public ImportTarget1RlModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ImportTarget1Rl model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getJobflowSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . PurchaseTran ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class PurchaseTranModelInput implements ModelInput < PurchaseTran > { private final RecordParser parser ; public PurchaseTranModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( PurchaseTran model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDatetimeOption ( ) ) ; parser . fill ( model . getUpdtDatetimeOption ( ) ) ; parser . fill ( model . getPurchaseNoOption ( ) ) ; parser . fill ( model . getPurchaseTypeOption ( ) ) ; parser . fill ( model . getTradeTypeOption ( ) ) ; parser . fill ( model . getTradeNoOption ( ) ) ; parser . fill ( model . getLineNoOption ( ) ) ; parser . fill ( model . getDeliveryDateOption ( ) ) ; parser . fill ( model . getStoreCodeOption ( ) ) ; parser . fill ( model . getBuyerCodeOption ( ) ) ; parser . fill ( model . getPurchaseTypeCodeOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getTenantCodeOption ( ) ) ; parser . fill ( model . getNetPriceTotalOption ( ) ) ; parser . fill ( model . getSellingPriceTotalOption ( ) ) ; parser . fill ( model . getShipmentStoreCodeOption ( ) ) ; parser . fill ( model . getShipmentSalesTypeCodeOption ( ) ) ; parser . fill ( model . getDeductionCodeOption ( ) ) ; parser . fill ( model . getAccountCodeOption ( ) ) ; parser . fill ( model . getOwnershipDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getPayoutDateOption ( ) ) ; parser . fill ( model . getOwnershipFlagOption ( ) ) ; parser . fill ( model . getCutoffFlagOption ( ) ) ; parser . fill ( model . getPayoutFlagOption ( ) ) ; parser . fill ( model . getDisposeNoOption ( ) ) ; parser . fill ( model . getDisposeDateOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . PurchaseTranError3 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class PurchaseTranError3ModelOutput implements ModelOutput < PurchaseTranError3 > { private final RecordEmitter emitter ; public PurchaseTranError3ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( PurchaseTranError3 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDatetimeOption ( ) ) ; emitter . emit ( model . getUpdtDatetimeOption ( ) ) ; emitter . emit ( model . getPurchaseNoOption ( ) ) ; emitter . emit ( model . getPurchaseTypeOption ( ) ) ; emitter . emit ( model . getTradeTypeOption ( ) ) ; emitter . emit ( model . getTradeNoOption ( ) ) ; emitter . emit ( model . getErrorCauseOption ( ) ) ; emitter . emit ( model . getErrorCodeOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . TempImportTarget1Df ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class TempImportTarget1DfModelOutput implements ModelOutput < TempImportTarget1Df > { private final RecordEmitter emitter ; public TempImportTarget1DfModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( TempImportTarget1Df model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . CacheFiles ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class CacheFilesModelOutput implements ModelOutput < CacheFiles > { private final RecordEmitter emitter ; public CacheFilesModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( CacheFiles model ) throws IOException { emitter . emit ( model . getCacheFileSidOption ( ) ) ; emitter . emit ( model . getFilePathOption ( ) ) ; emitter . emit ( model . getExpirationDatetimeOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempTest02 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempTest02ModelInput implements ModelInput < ExportTempTest02 > { private final RecordParser parser ; public ExportTempTest02ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempTest02 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTextdata1Option ( ) ) ; parser . fill ( model . getIntdata1Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . TempImportTarget1Df ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class TempImportTarget1DfModelInput implements ModelInput < TempImportTarget1Df > { private final RecordParser parser ; public TempImportTarget1DfModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( TempImportTarget1Df model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget13 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget13ModelOutput implements ModelOutput < ExportTempImportTarget13 > { private final RecordEmitter emitter ; public ExportTempImportTarget13ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempImportTarget13 model ) throws IOException { emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getTempSidOption ( ) ) ; emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getDuplicateFlgOption ( ) ) ; emitter . emit ( model . getTextdata1Option ( ) ) ; emitter . emit ( model . getIntdata1Option ( ) ) ; emitter . emit ( model . getDatedata1Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempPurchaseTran1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempPurchaseTran1ModelInput implements ModelInput < ExportTempPurchaseTran1 > { private final RecordParser parser ; public ExportTempPurchaseTran1ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempPurchaseTran1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDatetimeOption ( ) ) ; parser . fill ( model . getUpdtDatetimeOption ( ) ) ; parser . fill ( model . getPurchaseNoOption ( ) ) ; parser . fill ( model . getPurchaseTypeOption ( ) ) ; parser . fill ( model . getTradeTypeOption ( ) ) ; parser . fill ( model . getTradeNoOption ( ) ) ; parser . fill ( model . getLineNoOption ( ) ) ; parser . fill ( model . getDeliveryDateOption ( ) ) ; parser . fill ( model . getStoreCodeOption ( ) ) ; parser . fill ( model . getBuyerCodeOption ( ) ) ; parser . fill ( model . getPurchaseTypeCodeOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getTenantCodeOption ( ) ) ; parser . fill ( model . getNetPriceTotalOption ( ) ) ; parser . fill ( model . getSellingPriceTotalOption ( ) ) ; parser . fill ( model . getShipmentStoreCodeOption ( ) ) ; parser . fill ( model . getShipmentSalesTypeCodeOption ( ) ) ; parser . fill ( model . getDeductionCodeOption ( ) ) ; parser . fill ( model . getAccountCodeOption ( ) ) ; parser . fill ( model . getOwnershipDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getPayoutDateOption ( ) ) ; parser . fill ( model . getOwnershipFlagOption ( ) ) ; parser . fill ( model . getCutoffFlagOption ( ) ) ; parser . fill ( model . getPayoutFlagOption ( ) ) ; parser . fill ( model . getDisposeNoOption ( ) ) ; parser . fill ( model . getDisposeDateOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . JobflowInstanceLock ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class JobflowInstanceLockModelInput implements ModelInput < JobflowInstanceLock > { private final RecordParser parser ; public JobflowInstanceLockModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( JobflowInstanceLock model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getExecutionIdOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget21 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget21ModelOutput implements ModelOutput < ExportTempImportTarget21 > { private final RecordEmitter emitter ; public ExportTempImportTarget21ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempImportTarget21 model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getDuplicateFlgOption ( ) ) ; emitter . emit ( model . getTextdata2Option ( ) ) ; emitter . emit ( model . getIntdata2Option ( ) ) ; emitter . emit ( model . getDatedata2Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . TempImportTarget1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class TempImportTarget1ModelOutput implements ModelOutput < TempImportTarget1 > { private final RecordEmitter emitter ; public TempImportTarget1ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( TempImportTarget1 model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getTextdata1Option ( ) ) ; emitter . emit ( model . getIntdata1Option ( ) ) ; emitter . emit ( model . getDatedata1Option ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getDuplicateFlgOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportRecordLock ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportRecordLockModelInput implements ModelInput < ImportRecordLock > { private final RecordParser parser ; public ImportRecordLockModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ImportRecordLock model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getJobflowSidOption ( ) ) ; parser . fill ( model . getTableNameOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempPurchaseTran1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempPurchaseTran1ModelOutput implements ModelOutput < ExportTempPurchaseTran1 > { private final RecordEmitter emitter ; public ExportTempPurchaseTran1ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempPurchaseTran1 model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getRgstDatetimeOption ( ) ) ; emitter . emit ( model . getUpdtDatetimeOption ( ) ) ; emitter . emit ( model . getPurchaseNoOption ( ) ) ; emitter . emit ( model . getPurchaseTypeOption ( ) ) ; emitter . emit ( model . getTradeTypeOption ( ) ) ; emitter . emit ( model . getTradeNoOption ( ) ) ; emitter . emit ( model . getLineNoOption ( ) ) ; emitter . emit ( model . getDeliveryDateOption ( ) ) ; emitter . emit ( model . getStoreCodeOption ( ) ) ; emitter . emit ( model . getBuyerCodeOption ( ) ) ; emitter . emit ( model . getPurchaseTypeCodeOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getTenantCodeOption ( ) ) ; emitter . emit ( model . getNetPriceTotalOption ( ) ) ; emitter . emit ( model . getSellingPriceTotalOption ( ) ) ; emitter . emit ( model . getShipmentStoreCodeOption ( ) ) ; emitter . emit ( model . getShipmentSalesTypeCodeOption ( ) ) ; emitter . emit ( model . getDeductionCodeOption ( ) ) ; emitter . emit ( model . getAccountCodeOption ( ) ) ; emitter . emit ( model . getOwnershipDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getPayoutDateOption ( ) ) ; emitter . emit ( model . getOwnershipFlagOption ( ) ) ; emitter . emit ( model . getCutoffFlagOption ( ) ) ; emitter . emit ( model . getPayoutFlagOption ( ) ) ; emitter . emit ( model . getDisposeNoOption ( ) ) ; emitter . emit ( model . getDisposeDateOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget19Df ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget19DfModelOutput implements ModelOutput < ExportTempImportTarget19Df > { private final RecordEmitter emitter ; public ExportTempImportTarget19DfModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempImportTarget19Df model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . CacheFiles ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class CacheFilesModelInput implements ModelInput < CacheFiles > { private final RecordParser parser ; public CacheFilesModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( CacheFiles model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getCacheFileSidOption ( ) ) ; parser . fill ( model . getFilePathOption ( ) ) ; parser . fill ( model . getExpirationDatetimeOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . PurchaseTranError2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class PurchaseTranError2ModelInput implements ModelInput < PurchaseTranError2 > { private final RecordParser parser ; public PurchaseTranError2ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( PurchaseTranError2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDatetimeOption ( ) ) ; parser . fill ( model . getUpdtDatetimeOption ( ) ) ; parser . fill ( model . getPurchaseNoOption ( ) ) ; parser . fill ( model . getPurchaseTypeOption ( ) ) ; parser . fill ( model . getTradeTypeOption ( ) ) ; parser . fill ( model . getTradeNoOption ( ) ) ; parser . fill ( model . getLineNoOption ( ) ) ; parser . fill ( model . getDeliveryDateOption ( ) ) ; parser . fill ( model . getStoreCodeOption ( ) ) ; parser . fill ( model . getBuyerCodeOption ( ) ) ; parser . fill ( model . getPurchaseTypeCodeOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getTenantCodeOption ( ) ) ; parser . fill ( model . getNetPriceTotalOption ( ) ) ; parser . fill ( model . getSellingPriceTotalOption ( ) ) ; parser . fill ( model . getShipmentStoreCodeOption ( ) ) ; parser . fill ( model . getShipmentSalesTypeCodeOption ( ) ) ; parser . fill ( model . getDeductionCodeOption ( ) ) ; parser . fill ( model . getAccountCodeOption ( ) ) ; parser . fill ( model . getOwnershipDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getPayoutDateOption ( ) ) ; parser . fill ( model . getOwnershipFlagOption ( ) ) ; parser . fill ( model . getCutoffFlagOption ( ) ) ; parser . fill ( model . getPayoutFlagOption ( ) ) ; parser . fill ( model . getDisposeNoOption ( ) ) ; parser . fill ( model . getDisposeDateOption ( ) ) ; parser . fill ( model . getErrorCauseOption ( ) ) ; parser . fill ( model . getErrorCodeOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempTest02 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempTest02ModelOutput implements ModelOutput < ExportTempTest02 > { private final RecordEmitter emitter ; public ExportTempTest02ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExportTempTest02 model ) throws IOException { emitter . emit ( model . getTextdata1Option ( ) ) ; emitter . emit ( model . getIntdata1Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget11 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget11ModelInput implements ModelInput < ExportTempImportTarget11 > { private final RecordParser parser ; public ExportTempImportTarget11ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempImportTarget11 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getDuplicateFlgOption ( ) ) ; parser . fill ( model . getTextdata1Option ( ) ) ; parser . fill ( model . getIntdata1Option ( ) ) ; parser . fill ( model . getDatedata1Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget1Error ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget1ErrorModelInput implements ModelInput < ImportTarget1Error > { private final RecordParser parser ; public ImportTarget1ErrorModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ImportTarget1Error model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getTextdata1Option ( ) ) ; parser . fill ( model . getIntdata1Option ( ) ) ; parser . fill ( model . getDatedata1Option ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; parser . fill ( model . getErrorCodeOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . Temp7 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class Temp7ModelOutput implements ModelOutput < Temp7 > { private final RecordEmitter emitter ; public Temp7ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Temp7 model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getTextdata2Option ( ) ) ; emitter . emit ( model . getIntdata2Option ( ) ) ; emitter . emit ( model . getDatedata2Option ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getDuplicateFlgOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempPurchaseTran1Df ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempPurchaseTran1DfModelInput implements ModelInput < ExportTempPurchaseTran1Df > { private final RecordParser parser ; public ExportTempPurchaseTran1DfModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempPurchaseTran1Df model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . LockedTable ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class LockedTableModelOutput implements ModelOutput < LockedTable > { private final RecordEmitter emitter ; public LockedTableModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( LockedTable model ) throws IOException { emitter . emit ( model . getJobflowSidOption ( ) ) ; emitter . emit ( model . getTableNameOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . RunningJobflows ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class RunningJobflowsModelOutput implements ModelOutput < RunningJobflows > { private final RecordEmitter emitter ; public RunningJobflowsModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( RunningJobflows model ) throws IOException { emitter . emit ( model . getJobflowSidOption ( ) ) ; emitter . emit ( model . getBatchIdOption ( ) ) ; emitter . emit ( model . getJobflowIdOption ( ) ) ; emitter . emit ( model . getTargetNameOption ( ) ) ; emitter . emit ( model . getExecutionIdOption ( ) ) ; emitter . emit ( model . getExpectedCompletionDatetimeOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget2Rl ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget2RlModelInput implements ModelInput < ImportTarget2Rl > { private final RecordParser parser ; public ImportTarget2RlModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ImportTarget2Rl model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getJobflowSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempImportTarget11Df ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempImportTarget11DfModelInput implements ModelInput < ExportTempImportTarget11Df > { private final RecordParser parser ; public ExportTempImportTarget11DfModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempImportTarget11Df model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget1Error ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget1ErrorModelOutput implements ModelOutput < ImportTarget1Error > { private final RecordEmitter emitter ; public ImportTarget1ErrorModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ImportTarget1Error model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getTextdata1Option ( ) ) ; emitter . emit ( model . getIntdata1Option ( ) ) ; emitter . emit ( model . getDatedata1Option ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getErrorCodeOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . TempImportTarget2Df ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class TempImportTarget2DfModelInput implements ModelInput < TempImportTarget2Df > { private final RecordParser parser ; public TempImportTarget2DfModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( TempImportTarget2Df model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getTempSidOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . TempImportTarget2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class TempImportTarget2ModelOutput implements ModelOutput < TempImportTarget2 > { private final RecordEmitter emitter ; public TempImportTarget2ModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( TempImportTarget2 model ) throws IOException { emitter . emit ( model . getTempSidOption ( ) ) ; emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getVersionNoOption ( ) ) ; emitter . emit ( model . getTextdata2Option ( ) ) ; emitter . emit ( model . getIntdata2Option ( ) ) ; emitter . emit ( model . getDatedata2Option ( ) ) ; emitter . emit ( model . getRgstDateOption ( ) ) ; emitter . emit ( model . getUpdtDateOption ( ) ) ; emitter . emit ( model . getDuplicateFlgOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . BalanceTranError ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class BalanceTranErrorModelInput implements ModelInput < BalanceTranError > { private final RecordParser parser ; public BalanceTranErrorModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( BalanceTranError model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getRgstDatetimeOption ( ) ) ; parser . fill ( model . getUpdtDatetimeOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getPreviousCutoffDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getNextCutoffDateOption ( ) ) ; parser . fill ( model . getPayoutDateOption ( ) ) ; parser . fill ( model . getCarriedOption ( ) ) ; parser . fill ( model . getPurchaseOption ( ) ) ; parser . fill ( model . getRtnOption ( ) ) ; parser . fill ( model . getDiscountOption ( ) ) ; parser . fill ( model . getTaxOption ( ) ) ; parser . fill ( model . getPayableOption ( ) ) ; parser . fill ( model . getMutualOption ( ) ) ; parser . fill ( model . getReservesOption ( ) ) ; parser . fill ( model . getCancelOption ( ) ) ; parser . fill ( model . getPaymentOption ( ) ) ; parser . fill ( model . getNextPurchaseOption ( ) ) ; parser . fill ( model . getNextReturnOption ( ) ) ; parser . fill ( model . getNextDiscountOption ( ) ) ; parser . fill ( model . getNextTaxOption ( ) ) ; parser . fill ( model . getErrorCodeOption ( ) ) ; parser . fill ( model . getPaymentFlagOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ImportTarget1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ImportTarget1ModelInput implements ModelInput < ImportTarget1 > { private final RecordParser parser ; public ImportTarget1ModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ImportTarget1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getVersionNoOption ( ) ) ; parser . fill ( model . getTextdata1Option ( ) ) ; parser . fill ( model . getIntdata1Option ( ) ) ; parser . fill ( model . getDatedata1Option ( ) ) ; parser . fill ( model . getRgstDateOption ( ) ) ; parser . fill ( model . getUpdtDateOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . ExportTempTable ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class ExportTempTableModelInput implements ModelInput < ExportTempTable > { private final RecordParser parser ; public ExportTempTableModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExportTempTable model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getJobflowSidOption ( ) ) ; parser . fill ( model . getTableNameOption ( ) ) ; parser . fill ( model . getExportTempSeqOption ( ) ) ; parser . fill ( model . getExportTempNameOption ( ) ) ; parser . fill ( model . getDuplicateFlgNameOption ( ) ) ; parser . fill ( model . getTempTableStatusOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . table . io ; import java . io . IOException ; import javax . annotation . Generated ; import test . modelgen . table . model . LockedTable ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; @ Generated ( "" ) @ SuppressWarnings ( "" ) public final class LockedTableModelInput implements ModelInput < LockedTable > { private final RecordParser parser ; public LockedTableModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( LockedTable model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getJobflowSidOption ( ) ) ; parser . fill ( model . getTableNameOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . bulkloader . extractor ; package com . asakusafw . bulkloader . extractor ; import java . util . Date ; import java . util . List ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class Extractor { static final Log LOG = new Log ( Extractor . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_HC ; public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( Extractor . class . getClassLoader ( ) ) ; Extractor extractor = new Extractor ( ) ; int result = extractor . execute ( args ) ; System . exit ( result ) ; } protected int execute ( String [ ] args ) { if ( args . length != ) { System . err . println ( "" + args . length ) ; return Constants . EXIT_CODE_ERROR ; } String targetName = args [ ] ; String batchId = args [ ] ; String jobFlowId = args [ ] ; String executionId = args [ ] ; String user = args [ ] ; try { if ( ! BulkLoaderInitializer . initHadoopCluster ( jobFlowId , executionId , PROPERTIES ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobFlowId , executionId , user ) ; return Constants . EXIT_CODE_ERROR ; } LOG . info ( "" , new Date ( ) , targetName , batchId , jobFlowId , executionId , user ) ; ImportBean bean = createBean ( targetName , batchId , jobFlowId , executionId ) ; if ( bean == null ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobFlowId , executionId , user ) ; return Constants . EXIT_CODE_ERROR ; } LOG . info ( "" , targetName , batchId , jobFlowId , executionId , user ) ; DfsFileImport fileImport = createDfsFileImport ( ) ; if ( RuntimeContext . get ( ) . canExecute ( fileImport ) ) { if ( ! fileImport . importFile ( bean , user ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobFlowId , executionId , user ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , targetName , batchId , jobFlowId , executionId , user ) ; } } LOG . info ( "" , new Date ( ) , targetName , batchId , jobFlowId , executionId , user ) ; return Constants . EXIT_CODE_SUCCESS ; } catch ( Exception e ) { try { LOG . error ( e , "" , new Date ( ) , targetName , batchId , jobFlowId , executionId , user ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e1 ) { System . err . print ( "" ) ; e1 . printStackTrace ( ) ; return Constants . EXIT_CODE_ERROR ; } } } private ImportBean createBean ( String targetName , String batchId , String jobFlowId , String executionId ) { ImportBean bean = new ImportBean ( ) ; bean . setTargetName ( targetName ) ; bean . setBatchId ( batchId ) ; bean . setJobflowId ( jobFlowId ) ; bean . setExecutionId ( executionId ) ; JobFlowParamLoader dslLoader = createJobFlowParamLoader ( ) ; if ( ! dslLoader . loadExtractParam ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) ) ) { return null ; } bean . setTargetTable ( dslLoader . getImportTargetTables ( ) ) ; return bean ; } protected DfsFileImport createDfsFileImport ( ) { return new DfsFileImport ( ) ; } protected JobFlowParamLoader createJobFlowParamLoader ( ) { return new JobFlowParamLoader ( ) ; } } package com . asakusafw . bulkloader . extractor ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . net . URI ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedList ; import java . util . List ; import java . util . concurrent . Callable ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . SequenceFile . CompressionType ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . common . MultiThreadedCopier ; import com . asakusafw . bulkloader . common . StreamRedirectThread ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . TsvIoFactory ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; import com . asakusafw . thundergate . runtime . cache . mapreduce . CacheBuildClient ; public class DfsFileImport { static final Log LOG = new Log ( DfsFileImport . class ) ; private static final int INPUT_BUFFER_BYTES = * ; private static final int COPY_BUFFER_RECORDS = ; private final ExecutorService executor ; private final String cacheBuildCommand ; public DfsFileImport ( ) { File cmd = ConfigurationLoader . getLocalScriptPath ( Constants . PATH_LOCAL_CACHE_BUILD ) ; this . cacheBuildCommand = cmd . getAbsolutePath ( ) ; int parallel = Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_CACHE_BUILDER_PARALLEL ) ) ; LOG . debugMessage ( "" , parallel ) ; this . executor = Executors . newFixedThreadPool ( parallel ) ; } public boolean importFile ( ImportBean bean , String user ) { FileList . Reader reader ; try { reader = FileList . createReader ( getInputStream ( ) ) ; } catch ( IOException e ) { LOG . error ( e , "" , "" ) ; return false ; } try { List < Future < ? > > running = new ArrayList < Future < ? > > ( ) ; while ( reader . next ( ) ) { FileProtocol protocol = reader . getCurrentProtocol ( ) ; InputStream content = reader . openContent ( ) ; try { switch ( protocol . getKind ( ) ) { case CONTENT : importContent ( protocol , content , bean , user ) ; break ; case CREATE_CACHE : case UPDATE_CACHE : long recordCount = putCachePatch ( protocol , content , bean , user ) ; Callable < ? > builder = createCacheBuilder ( protocol , bean , user , recordCount ) ; if ( builder != null ) { LOG . debugMessage ( "" , protocol . getKind ( ) , protocol . getInfo ( ) . getTableName ( ) ) ; running . add ( executor . submit ( builder ) ) ; } break ; default : throw new AssertionError ( protocol . getKind ( ) ) ; } } finally { content . close ( ) ; } } waitForCompleteTasks ( bean , running ) ; return true ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; } catch ( IOException e ) { LOG . error ( e , "" , "" ) ; } finally { try { reader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return false ; } private void importContent ( FileProtocol protocol , InputStream content , ImportBean bean , String user ) throws BulkLoaderSystemException { assert protocol != null ; assert content != null ; assert bean != null ; assert user != null ; String tableName = FileNameUtil . getImportTableName ( protocol . getLocation ( ) ) ; ImportTargetTableBean targetTableBean = bean . getTargetTable ( tableName ) ; if ( targetTableBean == null ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , MessageFormat . format ( "" , tableName ) ) ; } URI dfsFilePath = resolveLocation ( bean , user , targetTableBean . getDfsFilePath ( ) ) ; Class < ? > targetTableModel = targetTableBean . getImportTargetType ( ) ; LOG . info ( "" , tableName , dfsFilePath . toString ( ) , targetTableModel . toString ( ) ) ; long recordCount = write ( targetTableModel , dfsFilePath , content ) ; LOG . info ( "" , tableName , dfsFilePath . toString ( ) , targetTableModel . toString ( ) ) ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , tableName , recordCount ) ; } private long putCachePatch ( FileProtocol protocol , InputStream content , ImportBean bean , String user ) throws BulkLoaderSystemException { assert protocol != null ; assert content != null ; assert bean != null ; assert user != null ; assert protocol . getKind ( ) == FileProtocol . Kind . CREATE_CACHE || protocol . getKind ( ) == FileProtocol . Kind . UPDATE_CACHE ; CacheInfo info = protocol . getInfo ( ) ; assert info != null ; ImportTargetTableBean targetTableBean = bean . getTargetTable ( info . getTableName ( ) ) ; if ( targetTableBean == null ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , MessageFormat . format ( "" , info . getTableName ( ) ) ) ; } URI dfsFilePath = resolveLocation ( bean , user , protocol . getLocation ( ) ) ; try { CacheStorage storage = new CacheStorage ( new Configuration ( ) , dfsFilePath ) ; try { LOG . info ( "" , info . getId ( ) , info . getTableName ( ) , storage . getPatchProperties ( ) ) ; storage . putPatchCacheInfo ( info ) ; LOG . info ( "" , info . getId ( ) , info . getTableName ( ) , storage . getPatchProperties ( ) ) ; Class < ? > targetTableModel = targetTableBean . getImportTargetType ( ) ; Path targetUri = storage . getPatchContents ( "" ) ; LOG . info ( "" , info . getId ( ) , info . getTableName ( ) , targetUri ) ; long recordCount = write ( targetTableModel , targetUri . toUri ( ) , content ) ; LOG . info ( "" , info . getId ( ) , info . getTableName ( ) , targetUri , recordCount ) ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , info . getTableName ( ) , recordCount ) ; return recordCount ; } finally { storage . close ( ) ; } } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , info . getId ( ) , info . getTableName ( ) , dfsFilePath ) ; } } private Callable < ? > createCacheBuilder ( FileProtocol protocol , ImportBean bean , String user , long recordCount ) throws BulkLoaderSystemException { assert protocol != null ; assert bean != null ; assert user != null ; CacheInfo info = protocol . getInfo ( ) ; URI location = resolveLocation ( bean , user , protocol . getLocation ( ) ) ; assert info != null ; try { switch ( protocol . getKind ( ) ) { case CREATE_CACHE : return createCacheBuilder ( CacheBuildClient . SUBCOMMAND_CREATE , bean , location , info ) ; case UPDATE_CACHE : if ( recordCount > ) { return createCacheBuilder ( CacheBuildClient . SUBCOMMAND_UPDATE , bean , location , info ) ; } else { return null ; } default : throw new AssertionError ( protocol ) ; } } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , protocol . getKind ( ) , info . getId ( ) , info . getTableName ( ) , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } } protected Callable < ? > createCacheBuilder ( final String subcommand , ImportBean bean , final URI location , final CacheInfo info ) throws IOException { assert subcommand != null ; assert bean != null ; assert location != null ; assert info != null ; List < String > command = new ArrayList < String > ( ) ; command . add ( cacheBuildCommand ) ; command . add ( subcommand ) ; command . add ( bean . getBatchId ( ) ) ; command . add ( bean . getJobflowId ( ) ) ; command . add ( bean . getExecutionId ( ) ) ; command . add ( location . toString ( ) ) ; command . add ( info . getModelClassName ( ) ) ; LOG . info ( "" , subcommand , info . getId ( ) , info . getTableName ( ) , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , command ) ; final ProcessBuilder builder = new ProcessBuilder ( command ) ; builder . directory ( new File ( System . getProperty ( "" , "" ) ) ) ; return new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { LOG . info ( "" , subcommand , info . getId ( ) , info . getTableName ( ) ) ; Process process = builder . start ( ) ; try { Thread stdout = new StreamRedirectThread ( process . getInputStream ( ) , System . out ) ; stdout . setDaemon ( true ) ; stdout . start ( ) ; Thread stderr = new StreamRedirectThread ( process . getErrorStream ( ) , System . err ) ; stderr . setDaemon ( true ) ; stderr . start ( ) ; stdout . join ( ) ; stderr . join ( ) ; int exitCode = process . waitFor ( ) ; if ( exitCode != ) { throw new IOException ( MessageFormat . format ( "" , exitCode ) ) ; } LOG . info ( "" , subcommand , info . getId ( ) , info . getTableName ( ) ) ; } catch ( Exception e ) { throw new BulkLoaderSystemException ( e , DfsFileImport . class , "" , subcommand , info . getId ( ) , info . getTableName ( ) ) ; } finally { process . destroy ( ) ; } return null ; } } ; } protected URI resolveLocation ( ImportBean bean , String user , String location ) throws BulkLoaderSystemException { Configuration conf = new Configuration ( ) ; URI dfsFilePath = FileNameUtil . createPath ( conf , location , bean . getExecutionId ( ) , user ) . toUri ( ) ; return dfsFilePath ; } private void waitForCompleteTasks ( ImportBean bean , List < Future < ? > > running ) throws BulkLoaderSystemException { assert bean != null ; assert running != null ; if ( running . isEmpty ( ) ) { return ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; boolean sawError = false ; LinkedList < Future < ? > > rest = new LinkedList < Future < ? > > ( running ) ; while ( rest . isEmpty ( ) == false ) { Future < ? > future = rest . removeFirst ( ) ; try { future . get ( , TimeUnit . SECONDS ) ; } catch ( TimeoutException e ) { rest . addLast ( future ) ; } catch ( InterruptedException e ) { cancel ( rest ) ; throw new BulkLoaderSystemException ( e , getClass ( ) , "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } catch ( ExecutionException e ) { cancel ( rest ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else if ( cause instanceof Error ) { throw ( Error ) cause ; } else if ( cause instanceof BulkLoaderSystemException ) { LOG . log ( ( BulkLoaderSystemException ) cause ) ; sawError = true ; } else { LOG . error ( e , "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; sawError = true ; } } } if ( sawError ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } else { LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } } private void cancel ( List < Future < ? > > futures ) { assert futures != null ; for ( Future < ? > future : futures ) { future . cancel ( true ) ; } } protected < T > long write ( Class < T > targetTableModel , URI dfsFilePath , InputStream inputStream ) throws BulkLoaderSystemException { ModelInput < T > input = null ; ModelOutput < T > output = null ; try { TsvIoFactory < T > factory = new TsvIoFactory < T > ( targetTableModel ) ; input = factory . createModelInput ( inputStream ) ; Configuration conf = new Configuration ( ) ; Collection < T > working = new ArrayList < T > ( COPY_BUFFER_RECORDS ) ; for ( int i = ; i < COPY_BUFFER_RECORDS ; i ++ ) { working . add ( factory . createModelObject ( ) ) ; } String strCompType = ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_SEQ_FILE_COMP_TYPE ) ; CompressionType compType = getCompType ( strCompType ) ; if ( compType == CompressionType . NONE ) { output = TemporaryStorage . openOutput ( conf , targetTableModel , new Path ( dfsFilePath ) , null ) ; } else { output = TemporaryStorage . openOutput ( conf , targetTableModel , new Path ( dfsFilePath ) ) ; } return MultiThreadedCopier . copy ( input , output , working ) ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , "" + dfsFilePath ) ; } catch ( InterruptedException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , "" + dfsFilePath ) ; } finally { if ( output != null ) { try { output . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } if ( input != null ) { try { input . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } protected CompressionType getCompType ( String strCompType ) { CompressionType compType = null ; try { compType = CompressionType . valueOf ( strCompType ) ; } catch ( Exception e ) { compType = CompressionType . NONE ; LOG . warn ( "" , strCompType ) ; } return compType ; } protected InputStream getInputStream ( ) throws IOException { return new BufferedInputStream ( System . in , INPUT_BUFFER_BYTES ) ; } } package com . asakusafw . bulkloader . collector ; package com . asakusafw . bulkloader . collector ; import java . util . Date ; import java . util . List ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class Collector { static final Log LOG = new Log ( Collector . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_HC ; public static void main ( String [ ] args ) { SystemOutManager . changeSystemOutToSystemErr ( ) ; RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( Collector . class . getClassLoader ( ) ) ; Collector collector = new Collector ( ) ; int result = collector . execute ( args ) ; System . exit ( result ) ; } protected int execute ( String [ ] args ) { if ( args . length != ) { System . err . println ( "" + args . length ) ; return Constants . EXIT_CODE_ERROR ; } String targetName = args [ ] ; String batchId = args [ ] ; String jobflowId = args [ ] ; String executionId = args [ ] ; String user = args [ ] ; try { if ( ! BulkLoaderInitializer . initHadoopCluster ( jobflowId , executionId , PROPERTIES ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId , user ) ; return Constants . EXIT_CODE_ERROR ; } LOG . info ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId , user ) ; ExporterBean bean = createBean ( targetName , batchId , jobflowId , executionId ) ; if ( bean == null ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId , user ) ; return Constants . EXIT_CODE_ERROR ; } LOG . info ( "" , targetName , batchId , jobflowId , executionId , user ) ; ExportFileSend fileSend = createExportFileSend ( ) ; if ( RuntimeContext . get ( ) . canExecute ( fileSend ) ) { if ( ! fileSend . sendExportFile ( bean , user ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId , user ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , targetName , batchId , jobflowId , executionId , user ) ; } } LOG . info ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId , user ) ; return Constants . EXIT_CODE_SUCCESS ; } catch ( Exception e ) { try { LOG . error ( e , "" , new Date ( ) , targetName , batchId , jobflowId , executionId , user ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e1 ) { System . err . print ( "" ) ; e1 . printStackTrace ( ) ; return Constants . EXIT_CODE_ERROR ; } } } private ExporterBean createBean ( String targetName , String batchId , String jobFlowId , String jobnetInctanceId ) { ExporterBean bean = new ExporterBean ( ) ; bean . setTargetName ( targetName ) ; bean . setBatchId ( batchId ) ; bean . setJobflowId ( jobFlowId ) ; bean . setExecutionId ( jobnetInctanceId ) ; JobFlowParamLoader dslLoader = createJobFlowParamLoader ( ) ; if ( ! dslLoader . loadExportParam ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) ) ) { return null ; } bean . setExportTargetTable ( dslLoader . getExportTargetTables ( ) ) ; return bean ; } protected JobFlowParamLoader createJobFlowParamLoader ( ) { return new JobFlowParamLoader ( ) ; } protected ExportFileSend createExportFileSend ( ) { return new ExportFileSend ( ) ; } } package com . asakusafw . bulkloader . collector ; import java . io . IOException ; import java . io . OutputStream ; import java . net . URI ; import java . net . URISyntaxException ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . commons . io . output . CountingOutputStream ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . FileUtil ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Writable ; import org . apache . hadoop . mapreduce . lib . output . FileOutputCommitter ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileCompType ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . TsvIoFactory ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; public class ExportFileSend { static final Log LOG = new Log ( ExportFileSend . class ) ; Map < String , Integer > fileNameMap = new HashMap < String , Integer > ( ) ; public boolean sendExportFile ( ExporterBean bean , String user ) { String strCompType = ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_FILE_COMP_TYPE ) ; FileCompType compType = FileCompType . find ( strCompType ) ; OutputStream output = getOutputStream ( ) ; try { FileList . Writer writer ; try { writer = FileList . createWriter ( output , compType == FileCompType . DEFLATED ) ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , "" ) ; } Configuration conf = new Configuration ( ) ; List < String > l = bean . getExportTargetTableList ( ) ; for ( String tableName : l ) { ExportTargetTableBean targetTable = bean . getExportTargetTable ( tableName ) ; Class < ? extends Writable > targetTableModel = targetTable . getExportTargetType ( ) . asSubclass ( Writable . class ) ; List < Path > filePath = FileNameUtil . createPaths ( conf , targetTable . getDfsFilePaths ( ) , bean . getExecutionId ( ) , user ) ; int fileCount = filePath . size ( ) ; long recordCount = ; for ( int i = ; i < fileCount ; i ++ ) { LOG . info ( "" , tableName , filePath . get ( i ) , compType . getSymbol ( ) , targetTableModel . toString ( ) ) ; long countInFile = send ( targetTableModel , filePath . get ( i ) . toString ( ) , writer , tableName ) ; if ( countInFile >= ) { recordCount += countInFile ; } LOG . info ( "" , tableName , filePath . get ( i ) , compType . getSymbol ( ) , targetTableModel . toString ( ) ) ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , tableName , recordCount ) ; } try { writer . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return true ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return false ; } finally { try { output . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } protected < T extends Writable > long send ( Class < T > targetTableModel , String filePath , FileList . Writer writer , String tableName ) throws BulkLoaderSystemException { FileSystem fs = null ; String fileName = null ; long maxSize = Long . parseLong ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_LOAD_MAX_SIZE ) ) ; try { TsvIoFactory < T > factory = new TsvIoFactory < T > ( targetTableModel ) ; Configuration conf = new Configuration ( ) ; fs = FileSystem . get ( new URI ( filePath ) , conf ) ; FileStatus [ ] status = fs . globStatus ( new Path ( filePath ) ) ; Path [ ] listedPaths = FileUtil . stat2Paths ( status ) ; if ( listedPaths == null ) { LOG . info ( "" , tableName , filePath ) ; return - ; } else { LOG . info ( "" , listedPaths . length , tableName , filePath ) ; } long count = ; boolean addEntry = false ; for ( Path path : listedPaths ) { if ( isSystemFile ( path ) ) { continue ; } ModelInput < T > input = TemporaryStorage . openInput ( conf , targetTableModel , path ) ; try { while ( true ) { addEntry = true ; fileName = FileNameUtil . createSendExportFileName ( tableName , fileNameMap ) ; OutputStream output = writer . openNext ( FileList . content ( fileName ) ) ; try { CountingOutputStream counter = new CountingOutputStream ( output ) ; ModelOutput < T > modelOut = factory . createModelOutput ( counter ) ; T model = factory . createModelObject ( ) ; LOG . info ( "" , tableName , path . toString ( ) , fileName ) ; boolean nextFile = false ; while ( input . readTo ( model ) ) { modelOut . write ( model ) ; count ++ ; if ( counter . getByteCount ( ) > maxSize ) { nextFile = true ; break ; } } modelOut . close ( ) ; LOG . info ( "" , tableName , path . toString ( ) , fileName ) ; if ( nextFile ) { continue ; } else { break ; } } finally { output . close ( ) ; } } } finally { input . close ( ) ; } } if ( addEntry ) { return count ; } else { assert count == ; return - ; } } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , MessageFormat . format ( "" , filePath , fileName ) ) ; } catch ( URISyntaxException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , MessageFormat . format ( "" , filePath ) ) ; } finally { if ( fs != null ) { try { fs . close ( ) ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , this . getClass ( ) , "" , MessageFormat . format ( "" , filePath ) ) ; } } } } private boolean isSystemFile ( Path path ) { assert path != null ; String name = path . getName ( ) ; return name . equals ( FileOutputCommitter . SUCCEEDED_FILE_NAME ) || name . equals ( "" ) ; } protected OutputStream getOutputStream ( ) { return SystemOutManager . getOut ( ) ; } } package com . asakusafw . bulkloader . collector ; import java . io . PrintStream ; public final class SystemOutManager { private static final PrintStream OUT = System . out ; private static final PrintStream ERR = System . err ; private static boolean systemOut = true ; private static boolean systemErr = false ; public static synchronized void changeSystemOutToSystemErr ( ) { System . setOut ( ERR ) ; systemOut = false ; systemErr = true ; } public static synchronized void changeSystemOutToSystemOut ( ) { System . setOut ( OUT ) ; systemOut = true ; systemErr = false ; } public static synchronized boolean isSystemOut ( ) { return systemOut ; } public static synchronized boolean isSystemErr ( ) { return systemErr ; } public static synchronized PrintStream getOut ( ) { return OUT ; } public static synchronized PrintStream getErr ( ) { return ERR ; } private SystemOutManager ( ) { return ; } } package com . asakusafw . bulkloader . tools ; package com . asakusafw . bulkloader . tools ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . runtime . core . context . RuntimeContext ; public final class DBCleaner { public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; DBCleaner cleaner = new DBCleaner ( ) ; int result = cleaner . execute ( args ) ; System . exit ( result ) ; } protected int execute ( String [ ] args ) { String targetName = null ; printLog ( "" ) ; if ( args . length == ) { targetName = args [ ] ; if ( isEmpty ( targetName ) ) { printErr ( "" ) ; return Constants . EXIT_CODE_ERROR ; } } else { printErr ( "" ) ; return Constants . EXIT_CODE_ERROR ; } Connection conn = null ; try { try { ConfigurationLoader . checkEnv ( ) ; ConfigurationLoader . loadJDBCProp ( targetName ) ; } catch ( IllegalStateException e ) { throw new SystemException ( e , e . getMessage ( ) ) ; } catch ( BulkLoaderSystemException e ) { throw new SystemException ( e . getCause ( ) , MessageFormat . format ( "" , targetName ) ) ; } try { DBConnection . init ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_JDBC_DRIVER ) ) ; } catch ( BulkLoaderSystemException e ) { throw new SystemException ( e . getCause ( ) , MessageFormat . format ( "" , targetName ) ) ; } try { conn = DBConnection . getConnection ( ) ; } catch ( BulkLoaderSystemException e ) { throw new SystemException ( e . getCause ( ) , MessageFormat . format ( "" , targetName ) ) ; } if ( RuntimeContext . get ( ) . isSimulation ( ) ) { return Constants . EXIT_CODE_SUCCESS ; } deleteTempTable ( conn ) ; lockRelease ( conn ) ; deleteRunningJobflows ( conn ) ; releaseCacheLock ( conn ) ; printLog ( "" ) ; return Constants . EXIT_CODE_SUCCESS ; } catch ( SystemException e ) { if ( conn != null ) { try { conn . rollback ( ) ; } catch ( SQLException e1 ) { e1 . printStackTrace ( ) ; } } printErr ( e . getCause ( ) , e . getMessage ( ) ) ; printErr ( "" ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e ) { if ( conn != null ) { try { conn . rollback ( ) ; } catch ( SQLException e1 ) { e1 . printStackTrace ( ) ; } } printErr ( e , "" ) ; printErr ( "" ) ; return Constants . EXIT_CODE_ERROR ; } } private static void deleteRunningJobflows ( Connection conn ) throws SystemException { String delRunningJobflowSql = "" ; String delInstanceLockSql = "" ; PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( delRunningJobflowSql ) ; int delCount = stmt . executeUpdate ( ) ; printLog ( MessageFormat . format ( "" , delCount ) ) ; } catch ( SQLException e ) { throw new SystemException ( e , MessageFormat . format ( "" , delRunningJobflowSql ) ) ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } try { stmt = conn . prepareStatement ( delInstanceLockSql ) ; int delCount = stmt . executeUpdate ( ) ; printLog ( MessageFormat . format ( "" , delCount ) ) ; } catch ( SQLException e ) { throw new SystemException ( e , MessageFormat . format ( "" , delRunningJobflowSql ) ) ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } try { conn . commit ( ) ; } catch ( SQLException e ) { throw new SystemException ( e , "" ) ; } } private static void lockRelease ( Connection conn ) throws SystemException { String tableLockSql = "" ; String selSql = "" ; String recordLockSql = "" ; String rlSql = "" ; List < String > rlList = new ArrayList < String > ( ) ; PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( selSql ) ; rs = stmt . executeQuery ( ) ; while ( rs . next ( ) ) { rlList . add ( rs . getString ( "" ) ) ; } } catch ( SQLException e ) { throw new SystemException ( e , MessageFormat . format ( "" , selSql ) ) ; } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } StringBuilder sql = null ; try { for ( String tableName : rlList ) { String lockedTable = DBAccessUtil . createRecordLockTableName ( tableName ) ; sql = new StringBuilder ( rlSql ) ; sql . append ( lockedTable ) ; stmt = conn . prepareStatement ( sql . toString ( ) ) ; int delCount = stmt . executeUpdate ( ) ; printLog ( MessageFormat . format ( "" , lockedTable , delCount ) ) ; } } catch ( SQLException e ) { throw new SystemException ( e , MessageFormat . format ( "" , sql ) ) ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } try { stmt = conn . prepareStatement ( recordLockSql ) ; int delCount = stmt . executeUpdate ( ) ; printLog ( MessageFormat . format ( "" , delCount ) ) ; } catch ( SQLException e ) { throw new SystemException ( e , MessageFormat . format ( "" , recordLockSql ) ) ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } try { stmt = conn . prepareStatement ( tableLockSql ) ; int upCount = stmt . executeUpdate ( ) ; printLog ( MessageFormat . format ( "" , upCount ) ) ; } catch ( SQLException e ) { throw new SystemException ( e , MessageFormat . format ( "" , tableLockSql ) ) ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } try { conn . commit ( ) ; } catch ( SQLException e ) { throw new SystemException ( e , "" ) ; } } private static void deleteTempTable ( Connection conn ) throws SystemException { String selSql = "" ; String dropSql = "" ; String delSql = "" ; List < String > tempTableList = new ArrayList < String > ( ) ; List < String > dupTableList = new ArrayList < String > ( ) ; PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( selSql ) ; rs = stmt . executeQuery ( ) ; while ( rs . next ( ) ) { tempTableList . add ( rs . getString ( "" ) ) ; dupTableList . add ( rs . getString ( "" ) ) ; } } catch ( SQLException e ) { throw new SystemException ( e , "" + selSql ) ; } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } StringBuilder sql = null ; try { for ( int i = , n = tempTableList . size ( ) ; i < n ; i ++ ) { String tempTableName = tempTableList . get ( i ) ; if ( ! isEmpty ( tempTableName ) ) { sql = new StringBuilder ( dropSql ) ; sql . append ( tempTableName ) ; stmt = conn . prepareStatement ( sql . toString ( ) ) ; stmt . executeUpdate ( ) ; printLog ( MessageFormat . format ( "" , tempTableName ) ) ; } String dupTableName = dupTableList . get ( i ) ; if ( ! isEmpty ( dupTableName ) ) { sql = new StringBuilder ( dropSql ) ; sql . append ( dupTableName ) ; stmt = conn . prepareStatement ( sql . toString ( ) ) ; stmt . executeUpdate ( ) ; printLog ( MessageFormat . format ( "" , dupTableName ) ) ; } } } catch ( SQLException e ) { throw new SystemException ( e , MessageFormat . format ( "" , sql ) ) ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } try { stmt = conn . prepareStatement ( delSql ) ; int delCount = stmt . executeUpdate ( ) ; printLog ( MessageFormat . format ( "" , delCount ) ) ; } catch ( SQLException e ) { throw new SystemException ( e , MessageFormat . format ( "" , delSql ) ) ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } try { conn . commit ( ) ; } catch ( SQLException e ) { throw new SystemException ( e , "" ) ; } } private void releaseCacheLock ( Connection conn ) { assert conn != null ; Statement stmt = null ; boolean committed = false ; try { stmt = conn . createStatement ( ) ; int count = stmt . executeUpdate ( "" ) ; conn . commit ( ) ; printLog ( MessageFormat . format ( "" , count ) ) ; committed = false ; } catch ( SQLException e ) { printLog ( "" ) ; e . printStackTrace ( ) ; } finally { if ( committed == false ) { try { conn . rollback ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } } if ( stmt != null ) { try { stmt . close ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } } } } private static boolean isEmpty ( String str ) { if ( str == null ) { return true ; } if ( str . isEmpty ( ) ) { return true ; } return false ; } private static void printErr ( Throwable e , String message ) { printErr ( message ) ; e . printStackTrace ( ) ; } private static void printErr ( String message ) { String strDate = getDate ( ) ; System . out . println ( "" + strDate + "" + message ) ; } private static void printLog ( String message ) { String strDate = getDate ( ) ; System . out . println ( "" + strDate + "" + message ) ; } private static String getDate ( ) { SimpleDateFormat sdf = new SimpleDateFormat ( "" ) ; return sdf . format ( new Date ( ) ) ; } } package com . asakusafw . bulkloader . tools ; class SystemException extends Exception { private static final long serialVersionUID = ; SystemException ( Throwable cause , String message ) { super ( message , cause ) ; } @ Override public Throwable getCause ( ) { return super . getCause ( ) ; } } package com . asakusafw . bulkloader . recoverer ; package com . asakusafw . bulkloader . recoverer ; import java . sql . Connection ; import java . text . MessageFormat ; import java . util . Date ; import java . util . List ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . ExportTempTableStatus ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . exporter . ExportDataCopy ; import com . asakusafw . bulkloader . exporter . LockRelease ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class Recoverer { static final Log LOG = new Log ( Recoverer . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_DB ; private boolean hasExecutionId = false ; private boolean isExistJobFlowInstance = false ; private boolean isExistRollBack = false ; private boolean isExistExecOthProcess = false ; private boolean isExistRecoveryFail = false ; public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; Recoverer recoverer = new Recoverer ( ) ; int result = recoverer . execute ( args ) ; System . exit ( result ) ; } protected int execute ( String [ ] args ) { if ( args . length > ) { System . err . println ( "" + args . length ) ; return Constants . EXIT_CODE_ERROR ; } String targetName = args [ ] ; String executionId ; if ( args . length == ) { executionId = args [ ] ; hasExecutionId = true ; } else { executionId = null ; hasExecutionId = false ; } try { if ( ! BulkLoaderInitializer . initDBServer ( "" , executionId , PROPERTIES , targetName ) ) { LOG . error ( "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } LOG . info ( "" , new Date ( ) , targetName , executionId ) ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { DBConnection . getConnection ( ) . close ( ) ; return Constants . EXIT_CODE_SUCCESS ; } List < ExporterBean > beans ; try { beans = selectRunningJobFlow ( executionId ) ; if ( beans != null && beans . size ( ) > ) { isExistJobFlowInstance = true ; } } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; LOG . error ( "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } if ( isExistJobFlowInstance ) { assert beans != null && beans . size ( ) >= ; for ( ExporterBean bean : beans ) { LOG . info ( "" , targetName , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getJobflowSid ( ) , bean . getExecutionId ( ) ) ; try { recovery ( bean ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; isExistRecoveryFail = true ; } } } return judgeExitCode ( targetName , executionId ) ; } catch ( Exception e ) { try { LOG . error ( e , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e1 ) { System . err . print ( "" ) ; e1 . printStackTrace ( ) ; return Constants . EXIT_CODE_ERROR ; } } } private int judgeExitCode ( String targetName , String executionId ) { if ( hasExecutionId ) { if ( ! isExistJobFlowInstance ) { LOG . info ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_SUCCESS ; } else if ( isExistRecoveryFail ) { LOG . error ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else if ( isExistExecOthProcess ) { LOG . error ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else if ( isExistRollBack ) { LOG . info ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_WARNING ; } else { LOG . info ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_SUCCESS ; } } else { if ( ! isExistJobFlowInstance ) { LOG . info ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_SUCCESS ; } else if ( isExistRecoveryFail ) { LOG . error ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else if ( isExistExecOthProcess ) { LOG . error ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else if ( isExistRollBack ) { LOG . info ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_WARNING ; } else { LOG . info ( "" , "" , new Date ( ) , targetName , executionId ) ; return Constants . EXIT_CODE_SUCCESS ; } } } private void recovery ( ExporterBean exporterBean ) throws BulkLoaderSystemException { String executionId = exporterBean . getExecutionId ( ) ; Connection lockConn = null ; try { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; lockConn = DBConnection . getConnection ( ) ; if ( ! DBAccessUtil . getJobflowInstanceLock ( executionId , lockConn ) ) { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; isExistExecOthProcess = true ; return ; } else { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; } if ( ! isExecRecovery ( exporterBean , hasExecutionId ) ) { return ; } loadParam ( exporterBean ) ; boolean rollBack = judgeRollBack ( exporterBean ) ; if ( rollBack ) { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) , "" ) ; } else { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) , "" ) ; } boolean updateEnd = true ; if ( ! rollBack ) { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; ExportDataCopy copy = createExportDataCopy ( ) ; if ( ! copy . copyData ( exporterBean ) ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; } else { updateEnd = copy . isUpdateEnd ( ) ; LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; } } LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; LockRelease lock = createLockRelease ( ) ; if ( ! lock . releaseLock ( exporterBean , updateEnd ) ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; } else { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; } if ( rollBack ) { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) , "" ) ; } else { if ( updateEnd ) { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) , "" ) ; } else { throw new BulkLoaderSystemException ( getClass ( ) , "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) , "" ) ; } } if ( rollBack ) { isExistRollBack = true ; } } finally { DBAccessUtil . releaseJobflowInstanceLock ( lockConn ) ; } } protected boolean isExecRecovery ( ExporterBean exporterBean , boolean hasParam ) throws BulkLoaderSystemException { String executionId = exporterBean . getExecutionId ( ) ; List < ExporterBean > beans = selectRunningJobFlow ( executionId ) ; if ( beans . size ( ) == ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; } if ( ! hasParam ) { if ( isRunningJobFlow ( executionId ) ) { LOG . info ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; return false ; } } return true ; } protected void loadParam ( ExporterBean exporterBean ) throws BulkLoaderSystemException { JobFlowParamLoader paramLoader = createJobFlowParamLoader ( ) ; if ( ! paramLoader . loadRecoveryParam ( exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) ) ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , "" , MessageFormat . format ( "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) ) , exporterBean . getExecutionId ( ) ) ; } exporterBean . setExportTargetTable ( paramLoader . getExportTargetTables ( ) ) ; exporterBean . setImportTargetTable ( paramLoader . getImportTargetTables ( ) ) ; String count = ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_RETRY_COUNT ) ; String interval = ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_RETRY_INTERVAL ) ; try { exporterBean . setRetryCount ( Integer . parseInt ( count ) ) ; exporterBean . setRetryInterval ( Integer . parseInt ( interval ) ) ; } catch ( NumberFormatException e ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , "" , count + "" + interval , exporterBean . getExecutionId ( ) ) ; } } protected boolean judgeRollBack ( ExporterBean exporterBean ) throws BulkLoaderSystemException { List < ExportTempTableBean > tempBean = null ; try { tempBean = getExportTempTable ( exporterBean . getJobflowSid ( ) ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; throw new BulkLoaderSystemException ( getClass ( ) , "" , exporterBean . getTargetName ( ) , exporterBean . getBatchId ( ) , exporterBean . getJobflowId ( ) , exporterBean . getJobflowSid ( ) , exporterBean . getExecutionId ( ) ) ; } if ( tempBean == null || tempBean . size ( ) == ) { return true ; } boolean result = false ; for ( ExportTempTableBean tempTable : tempBean ) { ExportTargetTableBean tableBean = exporterBean . getExportTargetTable ( tempTable . getExportTableName ( ) ) ; if ( tableBean != null ) { tableBean . setExportTempTableName ( tempTable . getTemporaryTableName ( ) ) ; tableBean . setDuplicateFlagTableName ( tempTable . getDuplicateFlagTableName ( ) ) ; } if ( tempTable . getTempTableStatus ( ) == null || tempTable . getTempTableStatus ( ) . equals ( ExportTempTableStatus . LOAD_EXIT ) ) { result = true ; } } return result ; } protected boolean isRunningJobFlow ( String executionId ) { return false ; } protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { return DBAccessUtil . getExportTempTable ( jobflowSid ) ; } protected List < ExporterBean > selectRunningJobFlow ( String executionId ) throws BulkLoaderSystemException { List < ExporterBean > beans = DBAccessUtil . selectRunningJobFlow ( executionId ) ; return beans ; } protected JobFlowParamLoader createJobFlowParamLoader ( ) { return new JobFlowParamLoader ( ) ; } protected ExportDataCopy createExportDataCopy ( ) { return new ExportDataCopy ( ) ; } protected LockRelease createLockRelease ( ) { return new LockRelease ( ) ; } } package com . asakusafw . bulkloader . exporter ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . SQLException ; import java . util . Iterator ; import java . util . LinkedHashSet ; import java . util . List ; import java . util . Set ; import java . util . concurrent . TimeUnit ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderReRunnableException ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public class LockRelease { static final Log LOG = new Log ( LockRelease . class ) ; public boolean releaseLock ( ExporterBean bean , boolean isEndJobFlow ) { int retryCount = bean . getRetryCount ( ) ; int retryInterval = bean . getRetryInterval ( ) ; int retry = ; Set < String > tableSet = mergingIOTable ( bean . getExportTargetTableList ( ) , bean . getImportTargetTableList ( ) ) ; Connection conn = null ; try { conn = DBConnection . getConnection ( ) ; if ( tableSet . isEmpty ( ) ) { if ( isEndJobFlow ) { endJobFlow ( conn , bean . getJobflowSid ( ) ) ; DBConnection . commit ( conn ) ; } return true ; } deleteTempTable ( bean , isEndJobFlow , conn ) ; deleteTempInfoRecord ( bean , isEndJobFlow , conn ) ; while ( true ) { retry ++ ; try { getImportTableLock ( conn , tableSet . iterator ( ) ) ; break ; } catch ( BulkLoaderReRunnableException e ) { LOG . log ( e ) ; if ( retry <= retryCount ) { try { DBConnection . rollback ( conn ) ; Thread . sleep ( TimeUnit . SECONDS . toMillis ( retryInterval ) ) ; continue ; } catch ( InterruptedException e1 ) { throw new BulkLoaderSystemException ( e1 , getClass ( ) , "" , "" ) ; } } else { throw new BulkLoaderSystemException ( getClass ( ) , "" , "" ) ; } } } releaseTableLock ( conn , bean . getJobflowSid ( ) ) ; for ( String tableName : tableSet ) { releaseLineLock ( conn , tableName , bean . getJobflowSid ( ) ) ; } if ( isEndJobFlow ) { endJobFlow ( conn , bean . getJobflowSid ( ) ) ; } DBConnection . commit ( conn ) ; return true ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; try { DBConnection . rollback ( conn ) ; } catch ( BulkLoaderSystemException e1 ) { LOG . log ( e1 ) ; } return false ; } finally { DBConnection . closeConn ( conn ) ; } } private void endJobFlow ( Connection conn , String jobflowSid ) throws BulkLoaderSystemException { String sql = "" ; PreparedStatement stmt = null ; LOG . info ( "" , sql , jobflowSid ) ; try { stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , jobflowSid ) ; DBConnection . executeUpdate ( stmt , sql , new String [ ] { jobflowSid } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , sql , new String [ ] { jobflowSid } ) ; } finally { DBConnection . closePs ( stmt ) ; } } private void deleteTempInfoRecord ( ExporterBean bean , boolean deleteTempTableForce , Connection conn ) throws BulkLoaderSystemException { List < String > list = bean . getExportTargetTableList ( ) ; TempTableDelete delete = createTempTableDelete ( ) ; for ( String tableName : list ) { delete . deleteTempInfoRecord ( bean . getJobflowSid ( ) , tableName , deleteTempTableForce , conn ) ; } } private void deleteTempTable ( ExporterBean bean , boolean deleteTempTableForce , Connection conn ) throws BulkLoaderSystemException { List < String > list = bean . getExportTargetTableList ( ) ; TempTableDelete delete = createTempTableDelete ( ) ; for ( String tableName : list ) { ExportTargetTableBean table = bean . getExportTargetTable ( tableName ) ; String tempTable = table . getExportTempTableName ( ) ; String dupTalbe = table . getDuplicateFlagTableName ( ) ; if ( tempTable != null ) { delete . deleteTempTable ( tempTable , dupTalbe , deleteTempTableForce , conn ) ; } } } private Set < String > mergingIOTable ( List < String > exportTargetTableList , List < String > importTargetTableList ) { Set < String > set = new LinkedHashSet < String > ( ) ; for ( String exportTable : exportTargetTableList ) { set . add ( exportTable ) ; } for ( String importTable : importTargetTableList ) { set . add ( importTable ) ; } return set ; } private void getImportTableLock ( Connection conn , Iterator < String > importTargetTable ) throws BulkLoaderReRunnableException , BulkLoaderSystemException { String selectSql1 = "" ; String selectSql2 = "" ; StringBuffer selectSql = new StringBuffer ( selectSql1 ) ; PreparedStatement stmt = null ; try { while ( importTargetTable . hasNext ( ) ) { selectSql . append ( "" ) ; selectSql . append ( importTargetTable . next ( ) ) ; selectSql . append ( "" ) ; if ( importTargetTable . hasNext ( ) ) { selectSql . append ( "" ) ; } } selectSql . append ( selectSql2 ) ; LOG . info ( "" , selectSql . toString ( ) ) ; stmt = conn . prepareStatement ( selectSql . toString ( ) ) ; DBConnection . executeQuery ( stmt , selectSql . toString ( ) , new String [ ] ) ; } catch ( SQLException e ) { throw new BulkLoaderReRunnableException ( e , this . getClass ( ) , "" , "" ) ; } finally { DBConnection . closePs ( stmt ) ; } } private void releaseTableLock ( Connection conn , String jobFlowSid ) throws BulkLoaderSystemException { String sql = "" + "" + "" ; PreparedStatement stmt = null ; LOG . info ( "" , sql , jobFlowSid ) ; try { stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , jobFlowSid ) ; DBConnection . executeUpdate ( stmt , sql , new String [ ] { jobFlowSid } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , sql , new String [ ] { jobFlowSid } ) ; } finally { DBConnection . closePs ( stmt ) ; } } private void releaseLineLock ( Connection conn , String tableName , String jobflowSid ) throws BulkLoaderSystemException { String recordLockSql = "" + "" ; PreparedStatement stmt = null ; int count = ; try { stmt = conn . prepareStatement ( recordLockSql ) ; stmt . setString ( , jobflowSid ) ; stmt . setString ( , tableName ) ; count = DBConnection . executeUpdate ( stmt , recordLockSql , new String [ ] { jobflowSid , tableName } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , recordLockSql , new String [ ] { jobflowSid , tableName } ) ; } finally { DBConnection . closePs ( stmt ) ; } if ( count > ) { String rlTableName = DBAccessUtil . createRecordLockTableName ( tableName ) ; StringBuffer rlSql = new StringBuffer ( "" ) ; rlSql . append ( rlTableName ) ; rlSql . append ( "" ) ; LOG . info ( "" , rlSql . toString ( ) , recordLockSql , jobflowSid , tableName ) ; try { stmt = conn . prepareStatement ( rlSql . toString ( ) ) ; stmt . setString ( , jobflowSid ) ; DBConnection . executeUpdate ( stmt , rlSql . toString ( ) , new String [ ] { jobflowSid } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , rlSql . toString ( ) , new String [ ] { jobflowSid } ) ; } finally { DBConnection . closePs ( stmt ) ; } } } protected TempTableDelete createTempTableDelete ( ) { return new TempTableDelete ( ) ; } } package com . asakusafw . bulkloader . exporter ; package com . asakusafw . bulkloader . exporter ; import java . io . File ; import java . util . List ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . log . Log ; public class ExportFileDelete { static final Log LOG = new Log ( ExportFileDelete . class ) ; public void deleteFile ( ExporterBean bean ) { List < String > list = bean . getExportTargetTableList ( ) ; for ( String tableName : list ) { ExportTargetTableBean targetTable = bean . getExportTargetTable ( tableName ) ; List < File > files = targetTable . getExportFiles ( ) ; for ( File file : files ) { if ( file != null && file . exists ( ) ) { if ( ! file . delete ( ) ) { LOG . warn ( "" , file . getPath ( ) ) ; } } } } } } package com . asakusafw . bulkloader . exporter ; import java . sql . Connection ; import java . util . Date ; import java . util . List ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class Exporter { static final Log LOG = new Log ( Exporter . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_DB ; public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( Exporter . class . getClassLoader ( ) ) ; Exporter exporter = new Exporter ( ) ; int result = exporter . execute ( args ) ; System . exit ( result ) ; } protected int execute ( String [ ] args ) { if ( args . length != ) { System . err . println ( "" + args . length ) ; return Constants . EXIT_CODE_ERROR ; } String targetName = args [ ] ; String batchId = args [ ] ; String jobflowId = args [ ] ; String executionId = args [ ] ; Connection lockConn = null ; try { if ( ! BulkLoaderInitializer . initDBServer ( jobflowId , executionId , PROPERTIES , targetName ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } LOG . info ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; ExporterBean bean = createBean ( targetName , batchId , jobflowId , executionId ) ; if ( bean == null ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } if ( RuntimeContext . get ( ) . isSimulation ( ) ) { DBConnection . getConnection ( ) . close ( ) ; return Constants . EXIT_CODE_SUCCESS ; } LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; try { lockConn = DBConnection . getConnection ( ) ; if ( ! DBAccessUtil . getJobflowInstanceLock ( bean . getExecutionId ( ) , lockConn ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; } } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } try { String jobflowSid = DBAccessUtil . selectJobFlowSid ( bean . getExecutionId ( ) ) ; bean . setJobflowSid ( jobflowSid ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } JudgeExecProcess judge = createJudgeExecProcess ( ) ; if ( ! judge . judge ( bean ) ) { return Constants . EXIT_CODE_ERROR ; } if ( judge . isExecTempTableDelete ( ) ) { LOG . info ( "" , targetName , batchId , jobflowId , executionId , bean . getJobflowSid ( ) ) ; TempTableDelete tempDelete = createTempTableDelete ( ) ; if ( ! tempDelete . delete ( judge . getExportTempTableBean ( ) , true ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId , bean . getJobflowSid ( ) ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , targetName , batchId , jobflowId , executionId , bean . getJobflowSid ( ) ) ; } } if ( judge . isExecReceive ( ) ) { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; ExportFileReceive receive = createExportFileReceive ( ) ; if ( ! receive . receiveFile ( bean ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; } } if ( judge . isExecLoad ( ) ) { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; ExportFileLoad road = createExportFileLoad ( ) ; if ( ! road . loadFile ( bean ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; } } boolean updateEnd = true ; if ( judge . isExecCopy ( ) ) { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; ExportDataCopy copy = createExportDataCopy ( ) ; if ( ! copy . copyData ( bean ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { updateEnd = copy . isUpdateEnd ( ) ; LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; } } if ( judge . isExecLockRelease ( ) ) { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; LockRelease lock = createLockRelease ( ) ; if ( ! lock . releaseLock ( bean , updateEnd ) ) { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; } } if ( judge . isExecFileDelete ( ) ) { LOG . info ( "" , targetName , batchId , jobflowId , executionId ) ; ExportFileDelete delete = createExportFileDelete ( ) ; delete . deleteFile ( bean ) ; } if ( updateEnd ) { LOG . info ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_SUCCESS ; } else { LOG . error ( "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } } catch ( Exception e ) { try { LOG . error ( e , "" , new Date ( ) , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e1 ) { System . err . print ( "" ) ; e1 . printStackTrace ( ) ; return Constants . EXIT_CODE_ERROR ; } } finally { DBAccessUtil . releaseJobflowInstanceLock ( lockConn ) ; } } private ExporterBean createBean ( String targetName , String batchId , String jobFlowId , String executionId ) { ExporterBean bean = new ExporterBean ( ) ; bean . setTargetName ( targetName ) ; bean . setBatchId ( batchId ) ; bean . setJobflowId ( jobFlowId ) ; bean . setExecutionId ( executionId ) ; bean . setRetryCount ( Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_RETRY_COUNT ) ) ) ; bean . setRetryInterval ( Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_RETRY_INTERVAL ) ) ) ; JobFlowParamLoader dslLoader = createJobFlowParamLoader ( ) ; if ( ! dslLoader . loadExportParam ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) ) ) { return null ; } bean . setExportTargetTable ( dslLoader . getExportTargetTables ( ) ) ; if ( ! dslLoader . loadImportParam ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , true ) ) { return null ; } bean . setImportTargetTable ( dslLoader . getImportTargetTables ( ) ) ; return bean ; } protected JobFlowParamLoader createJobFlowParamLoader ( ) { return new JobFlowParamLoader ( ) ; } protected ExportFileDelete createExportFileDelete ( ) { return new ExportFileDelete ( ) ; } protected LockRelease createLockRelease ( ) { return new LockRelease ( ) ; } protected ExportFileLoad createExportFileLoad ( ) { return new ExportFileLoad ( ) ; } protected ExportFileReceive createExportFileReceive ( ) { return new ExportFileReceive ( ) ; } protected JudgeExecProcess createJudgeExecProcess ( ) { return new JudgeExecProcess ( ) ; } protected TempTableDelete createTempTableDelete ( ) { return new TempTableDelete ( ) ; } protected ExportDataCopy createExportDataCopy ( ) { return new ExportDataCopy ( ) ; } } package com . asakusafw . bulkloader . exporter ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . bulkloader . transfer . OpenSshFileListProvider ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class ExportFileReceive { static final Log LOG = new Log ( ExportFileReceive . class ) ; public boolean receiveFile ( ExporterBean bean ) { File fileDirectry = new File ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_FILE_DIR ) ) ; if ( ! fileDirectry . exists ( ) ) { LOG . error ( "" , fileDirectry . getAbsolutePath ( ) ) ; return false ; } FileListProvider provider = null ; FileList . Reader reader = null ; long totalStartTime = System . currentTimeMillis ( ) ; try { provider = openFileList ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; provider . discardWriter ( ) ; reader = provider . openReader ( ) ; int fileSeq = ; Map < String , TableTransferProfile > profiles = new TreeMap < String , TableTransferProfile > ( ) ; while ( reader . next ( ) ) { FileProtocol protocol = reader . getCurrentProtocol ( ) ; assert protocol . getKind ( ) == FileProtocol . Kind . CONTENT ; String fileName = protocol . getLocation ( ) ; String tableName = FileNameUtil . getExportTableName ( fileName ) ; if ( tableName == null ) { LOG . error ( "" , fileName , "" ) ; return false ; } else if ( bean . getExportTargetTable ( tableName ) == null ) { LOG . error ( "" , fileName , tableName ) ; return false ; } TableTransferProfile profile = profiles . get ( tableName ) ; if ( profile == null ) { profile = new TableTransferProfile ( tableName ) ; profiles . put ( tableName , profile ) ; } File file = FileNameUtil . createExportFilePath ( fileDirectry , bean . getTargetName ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , tableName , fileSeq ++ ) ; LOG . info ( "" , tableName , file . getAbsolutePath ( ) ) ; long dumpStartTime = System . currentTimeMillis ( ) ; long dumpFileSize = ; int byteSize = Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_FILE_COMP_BUFSIZE ) ) ; byte [ ] b = new byte [ byteSize ] ; InputStream content = reader . openContent ( ) ; OutputStream fos = null ; try { fos = createFos ( file ) ; while ( true ) { int read ; try { read = content . read ( b ) ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , "" + protocol . getLocation ( ) ) ; } if ( read < ) { break ; } dumpFileSize += read ; try { fos . write ( b , , read ) ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , "" + file . getName ( ) ) ; } } bean . getExportTargetTable ( tableName ) . addExportFile ( file ) ; profile . elapsedTime += System . currentTimeMillis ( ) - dumpStartTime ; profile . fileSize += dumpFileSize ; LOG . info ( "" , tableName , file . getAbsolutePath ( ) ) ; } finally { try { content . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } for ( TableTransferProfile profile : profiles . values ( ) ) { LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , profile . tableName , profile . fileSize , profile . elapsedTime ) ; } reader . close ( ) ; provider . waitForComplete ( ) ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , reader . getByteCount ( ) , System . currentTimeMillis ( ) - totalStartTime ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return false ; } catch ( Exception e ) { LOG . error ( e , "" , "" ) ; return false ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException ignored ) { ignored . printStackTrace ( ) ; } } if ( provider != null ) { try { provider . close ( ) ; } catch ( IOException ignored ) { ignored . printStackTrace ( ) ; } } } return true ; } private OutputStream createFos ( File file ) throws BulkLoaderSystemException { if ( file . exists ( ) ) { if ( ! file . delete ( ) ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , file . getName ( ) ) ; } } FileOutputStream fos = null ; try { fos = new FileOutputStream ( file ) ; } catch ( FileNotFoundException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , "" + file . getName ( ) ) ; } return fos ; } protected FileListProvider openFileList ( String targetName , String batchId , String jobflowId , String executionId ) throws IOException { if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( jobflowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } String sshPath = ConfigurationLoader . getProperty ( Constants . PROP_KEY_SSH_PATH ) ; String hostName = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAMENODE_HOST ) ; String userName = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAMENODE_USER ) ; String scriptPath = ConfigurationLoader . getRemoteScriptPath ( Constants . PATH_REMOTE_COLLECTOR ) ; String variableTable = Constants . createVariableTable ( ) . toSerialString ( ) ; List < String > command = new ArrayList < String > ( ) ; command . add ( scriptPath ) ; command . add ( targetName ) ; command . add ( batchId ) ; command . add ( jobflowId ) ; command . add ( executionId ) ; command . add ( variableTable ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . putAll ( ConfigurationLoader . getPropSubMap ( Constants . PROP_PREFIX_HC_ENV ) ) ; env . putAll ( RuntimeContext . get ( ) . unapply ( ) ) ; LOG . info ( "" , sshPath , hostName , userName , scriptPath , targetName , batchId , jobflowId , executionId ) ; return new OpenSshFileListProvider ( sshPath , userName , hostName , command , env ) ; } private static final class TableTransferProfile { TableTransferProfile ( String tableName ) { assert tableName != null ; this . tableName = tableName ; } String tableName ; long fileSize ; long elapsedTime ; } } package com . asakusafw . bulkloader . exporter ; import java . util . Date ; import java . util . List ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . ExportTempTableStatus ; import com . asakusafw . bulkloader . common . TsvDeleteType ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public class JudgeExecProcess { static final Log LOG = new Log ( JudgeExecProcess . class ) ; private boolean execTempTableDelete = false ; private boolean execReceive = false ; private boolean execLoad = false ; private boolean execCopy = false ; private boolean execLockRelease = false ; private boolean execFileDelete = false ; List < ExportTempTableBean > exportTempTableBean = null ; public boolean judge ( ExporterBean bean ) { if ( bean . getJobflowSid ( ) == null || bean . getJobflowSid ( ) . isEmpty ( ) ) { LOG . error ( "" , new Date ( ) , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; return false ; } String deleteTsv = ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE ) ; TsvDeleteType delType = TsvDeleteType . find ( deleteTsv ) ; boolean isDeleteTsv = false ; if ( TsvDeleteType . TRUE . equals ( delType ) ) { isDeleteTsv = true ; } List < String > list = bean . getExportTargetTableList ( ) ; if ( list == null || list . size ( ) == ) { execLockRelease = true ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , execTempTableDelete , execReceive , execLoad , execCopy , execLockRelease , execFileDelete ) ; return true ; } try { exportTempTableBean = getExportTempTable ( bean . getJobflowSid ( ) ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; LOG . error ( "" , new Date ( ) , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; return false ; } if ( exportTempTableBean == null || exportTempTableBean . size ( ) == ) { execReceive = true ; execLoad = true ; execCopy = true ; execLockRelease = true ; execFileDelete = isDeleteTsv ; if ( ! isDeleteTsv ) { LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , execTempTableDelete , execReceive , execLoad , execCopy , execLockRelease , execFileDelete ) ; return true ; } if ( isCopyStart ( exportTempTableBean ) ) { execCopy = true ; execLockRelease = true ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , execTempTableDelete , execReceive , execLoad , execCopy , execLockRelease , execFileDelete ) ; return true ; } else { execTempTableDelete = true ; execReceive = true ; execLoad = true ; execCopy = true ; execLockRelease = true ; execFileDelete = isDeleteTsv ; if ( ! isDeleteTsv ) { LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , execTempTableDelete , execReceive , execLoad , execCopy , execLockRelease , execFileDelete ) ; return true ; } } private boolean isCopyStart ( List < ExportTempTableBean > tempBean ) { boolean isCopyStart = true ; for ( ExportTempTableBean element : tempBean ) { if ( element . getTempTableStatus ( ) == null || element . getTempTableStatus ( ) . equals ( ExportTempTableStatus . LOAD_EXIT ) ) { isCopyStart = false ; break ; } } return isCopyStart ; } protected List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { return DBAccessUtil . getExportTempTable ( jobflowSid ) ; } public boolean isExecReceive ( ) { return execReceive ; } public boolean isExecLoad ( ) { return execLoad ; } public boolean isExecCopy ( ) { return execCopy ; } public boolean isExecLockRelease ( ) { return execLockRelease ; } public boolean isExecFileDelete ( ) { return execFileDelete ; } public boolean isExecTempTableDelete ( ) { return execTempTableDelete ; } public List < ExportTempTableBean > getExportTempTableBean ( ) { return exportTempTableBean ; } } package com . asakusafw . bulkloader . exporter ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . List ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . ExportTempTableStatus ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public class ExportDataCopy { static final Log LOG = new Log ( ExportDataCopy . class ) ; private boolean copyEnd = true ; public boolean copyData ( ExporterBean bean ) { long maxRecord = Long . parseLong ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD ) ) ; Connection conn = null ; try { conn = DBConnection . getConnection ( ) ; List < ExportTempTableBean > tempBean = DBAccessUtil . getExportTempTable ( bean . getJobflowSid ( ) ) ; List < String > l = bean . getExportTargetTableList ( ) ; for ( String tableName : l ) { ExportTargetTableBean expTableBean = bean . getExportTargetTable ( tableName ) ; LOG . info ( "" , bean . getJobflowSid ( ) , tableName , expTableBean . getExportTempTableName ( ) ) ; if ( isCopyEnd ( tempBean , expTableBean , tableName ) ) { LOG . info ( "" , bean . getJobflowSid ( ) , tableName , expTableBean . getExportTempTableName ( ) ) ; continue ; } if ( expTableBean . getExportTempTableName ( ) == null ) { LOG . info ( "" , bean . getJobflowSid ( ) , tableName , expTableBean . getExportTempTableName ( ) ) ; continue ; } boolean isGetRecordLock = getRecordLock ( bean . getJobflowSid ( ) , tableName , conn ) ; copyNonDuplicateData ( expTableBean , tableName , maxRecord , bean . getJobflowSid ( ) , isGetRecordLock , conn ) ; if ( expTableBean . isDuplicateCheck ( ) ) { copyDuplicateData ( expTableBean , maxRecord , conn ) ; } boolean tableCopyEnd = copyUpdateData ( expTableBean , tableName , maxRecord , bean . getJobflowSid ( ) , conn ) ; if ( tableCopyEnd ) { copyExit ( bean . getJobflowSid ( ) , tableName , conn ) ; } else { copyEnd = false ; } LOG . info ( "" , bean . getJobflowSid ( ) , tableName , expTableBean . getExportTempTableName ( ) , tableCopyEnd ) ; } return true ; } catch ( BulkLoaderSystemException e ) { try { DBConnection . rollback ( conn ) ; } catch ( BulkLoaderSystemException e1 ) { LOG . log ( e ) ; } LOG . log ( e ) ; return false ; } finally { DBConnection . closeConn ( conn ) ; } } private boolean isCopyEnd ( List < ExportTempTableBean > tempBeans , ExportTargetTableBean tableBean , String tableName ) { if ( tempBeans == null || tempBeans . size ( ) == ) { return false ; } else { for ( ExportTempTableBean tempBean : tempBeans ) { if ( tempBean . getExportTableName ( ) . equals ( tableName ) ) { if ( tableBean . getExportTempTableName ( ) == null ) { tableBean . setExportTempTableName ( tempBean . getTemporaryTableName ( ) ) ; tableBean . setDuplicateFlagTableName ( tempBean . getDuplicateFlagTableName ( ) ) ; } boolean completed = ExportTempTableStatus . COPY_EXIT . equals ( tempBean . getTempTableStatus ( ) ) ; return completed ; } } } return false ; } private void copyExit ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { String loadExitSql = "" + "" + "" ; PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( loadExitSql ) ; stmt . setString ( , ExportTempTableStatus . COPY_EXIT . getStatus ( ) ) ; stmt . setString ( , jobflowSid ) ; stmt . setString ( , tableName ) ; DBConnection . executeUpdate ( stmt , loadExitSql , new String [ ] { ExportTempTableStatus . COPY_EXIT . getStatus ( ) , jobflowSid , tableName } ) ; DBConnection . commit ( conn ) ; LOG . info ( "" , jobflowSid , tableName ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , loadExitSql , new String [ ] { ExportTempTableStatus . COPY_EXIT . getStatus ( ) , jobflowSid , tableName } ) ; } finally { DBConnection . closePs ( stmt ) ; } } private void copyDuplicateData ( ExportTargetTableBean expTableBean , long maxRecord , Connection conn ) throws BulkLoaderSystemException { String selectCondition = createDupSelectCondition ( expTableBean , maxRecord ) ; String copySql = createDupInsertSql ( expTableBean , selectCondition ) ; String delSql = createDupCopyDelSql ( expTableBean , selectCondition ) ; PreparedStatement stmt = null ; while ( true ) { int copyCount = ; try { stmt = conn . prepareStatement ( copySql . toString ( ) ) ; copyCount = DBConnection . executeUpdate ( stmt , copySql . toString ( ) ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , copySql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } if ( copyCount == ) { DBConnection . commit ( conn ) ; break ; } try { stmt = conn . prepareStatement ( delSql ) ; DBConnection . executeUpdate ( stmt , delSql , new String [ ] ) ; DBConnection . commit ( conn ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , delSql , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } LOG . info ( "" , expTableBean . getErrorTableName ( ) , expTableBean . getExportTempTableName ( ) , copySql . toString ( ) , delSql ) ; } } private String createDupCopyDelSql ( ExportTargetTableBean expTableBean , String selectCondition ) { StringBuilder delSqll = new StringBuilder ( "" ) ; delSqll . append ( expTableBean . getExportTempTableName ( ) ) ; delSqll . append ( selectCondition ) ; return delSqll . toString ( ) ; } private String createDupInsertSql ( ExportTargetTableBean expTableBean , String selectCondition ) { List < String > columnList = DBAccessUtil . delErrorSystemColumn ( expTableBean . getErrorTableColumns ( ) , expTableBean . getErrorCodeColumn ( ) ) ; String column = DBAccessUtil . joinColumnArray ( columnList ) ; StringBuilder copySql = new StringBuilder ( "" ) ; copySql . append ( expTableBean . getErrorTableName ( ) ) ; copySql . append ( "" ) ; copySql . append ( column ) ; copySql . append ( "" ) ; copySql . append ( Constants . getRegisteredDateTimeColumnName ( ) ) ; copySql . append ( "" ) ; copySql . append ( Constants . getUpdatedDateTimeColumnName ( ) ) ; copySql . append ( "" ) ; copySql . append ( expTableBean . getErrorCodeColumn ( ) ) ; copySql . append ( "" ) ; copySql . append ( column ) ; copySql . append ( "" ) ; copySql . append ( expTableBean . getErrorCode ( ) ) ; copySql . append ( "" ) ; copySql . append ( expTableBean . getExportTempTableName ( ) ) ; copySql . append ( selectCondition ) ; return copySql . toString ( ) ; } private String createDupSelectCondition ( ExportTargetTableBean expTableBean , long maxRecord ) { StringBuilder selectCondition = new StringBuilder ( "" ) ; selectCondition . append ( Constants . getSidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( expTableBean . getDuplicateFlagTableName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( expTableBean . getDuplicateFlagTableName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( expTableBean . getDuplicateFlagTableName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( expTableBean . getExportTempTableName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( maxRecord ) ; return selectCondition . toString ( ) ; } private boolean copyUpdateData ( ExportTargetTableBean tableBean , String tableName , long maxRecord , String jobflowSid , Connection conn ) throws BulkLoaderSystemException { String tempTableName = tableBean . getExportTempTableName ( ) ; String minTempSidSql = createMinTempSidSql ( Constants . getTemporarySidColumnName ( ) , tempTableName ) ; String maxTempSidSql = createMaxTempSidSql ( Constants . getTemporarySidColumnName ( ) , tempTableName ) ; String countTempSql = createCountTempSql ( tempTableName ) ; String selectCondition = createUpdateSelectCondition ( tableName , tempTableName ) ; String copySql = createUpdateCopySql ( tableName , tempTableName , selectCondition , tableBean . getExportTableColumns ( ) ) ; String delSql = createUpdateRecordDelSql ( tableName , tempTableName ) ; String errTempSql = createSelectErrTempRecordSql ( tempTableName ) ; PreparedStatement stmt = null ; long minTempSid = ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( minTempSidSql ) ; rs = DBConnection . executeQuery ( stmt , minTempSidSql , new String [ ] ) ; rs . next ( ) ; minTempSid = rs . getLong ( ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , minTempSidSql , new String [ ] ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } long maxTempSid = ; try { stmt = conn . prepareStatement ( maxTempSidSql ) ; rs = DBConnection . executeQuery ( stmt , maxTempSidSql , new String [ ] ) ; rs . next ( ) ; maxTempSid = rs . getLong ( ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , maxTempSidSql , new String [ ] ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } long currentCount = minTempSid ; while ( true ) { Long maxCount = currentCount + maxRecord ; int copyCount = ; try { stmt = conn . prepareStatement ( copySql ) ; stmt . setLong ( , currentCount ) ; stmt . setLong ( , maxCount ) ; copyCount = DBConnection . executeUpdate ( stmt , copySql , new String [ ] { String . valueOf ( currentCount ) , String . valueOf ( maxCount ) } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , copySql , new String [ ] { String . valueOf ( currentCount ) , String . valueOf ( maxCount ) } ) ; } finally { DBConnection . closePs ( stmt ) ; } if ( copyCount > ) { try { stmt = conn . prepareStatement ( delSql ) ; stmt . setLong ( , currentCount ) ; stmt . setLong ( , maxCount ) ; DBConnection . executeUpdate ( stmt , delSql , new String [ ] { String . valueOf ( currentCount ) , String . valueOf ( maxCount ) } ) ; DBConnection . commit ( conn ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , delSql , new String [ ] { String . valueOf ( currentCount ) , String . valueOf ( maxCount ) } ) ; } finally { DBConnection . closePs ( stmt ) ; } } LOG . info ( "" , tableName , tableBean . getExportTempTableName ( ) , copySql , delSql , currentCount , maxCount ) ; currentCount = maxCount + ; if ( currentCount > maxTempSid ) { DBConnection . commit ( conn ) ; break ; } } long tempCount = ; try { stmt = conn . prepareStatement ( countTempSql ) ; rs = DBConnection . executeQuery ( stmt , countTempSql , new String [ ] ) ; rs . next ( ) ; tempCount = rs . getLong ( ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , countTempSql , new String [ ] ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } if ( tempCount == ) { LOG . info ( "" , tableName , tableBean . getExportTempTableName ( ) ) ; return true ; } else { StringBuilder errSid = new StringBuilder ( ) ; try { stmt = conn . prepareStatement ( errTempSql ) ; rs = DBConnection . executeQuery ( stmt , errTempSql , new String [ ] ) ; while ( rs . next ( ) ) { errSid . append ( Constants . getSidColumnName ( ) ) ; errSid . append ( "" ) ; errSid . append ( rs . getLong ( Constants . getSidColumnName ( ) ) ) ; errSid . append ( "" ) ; errSid . append ( Constants . getTemporarySidColumnName ( ) ) ; errSid . append ( "" ) ; errSid . append ( rs . getLong ( Constants . getTemporarySidColumnName ( ) ) ) ; errSid . append ( "" ) ; } } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , errTempSql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } LOG . error ( "" , tableName , tempTableName , errSid . toString ( ) ) ; return false ; } } private String createSelectErrTempRecordSql ( String tempTableName ) { StringBuilder errTempSql = new StringBuilder ( "" ) ; errTempSql . append ( Constants . getTemporarySidColumnName ( ) ) ; errTempSql . append ( "" ) ; errTempSql . append ( Constants . getSidColumnName ( ) ) ; errTempSql . append ( "" ) ; errTempSql . append ( tempTableName ) ; return errTempSql . toString ( ) ; } private String createUpdateRecordDelSql ( String tableName , String tempTableName ) { StringBuilder delSql = new StringBuilder ( "" ) ; delSql . append ( tempTableName ) ; delSql . append ( "" ) ; delSql . append ( Constants . getTemporarySidColumnName ( ) ) ; delSql . append ( "" ) ; delSql . append ( tableName ) ; delSql . append ( "" ) ; delSql . append ( tableName ) ; delSql . append ( "" ) ; delSql . append ( Constants . getSidColumnName ( ) ) ; delSql . append ( "" ) ; delSql . append ( tempTableName ) ; delSql . append ( "" ) ; delSql . append ( Constants . getSidColumnName ( ) ) ; delSql . append ( "" ) ; delSql . append ( Constants . getSidColumnName ( ) ) ; delSql . append ( "" ) ; delSql . append ( Constants . getTemporarySidColumnName ( ) ) ; delSql . append ( "" ) ; return delSql . toString ( ) ; } private String createUpdateCopySql ( String tableName , String tempTableName , String selectCondition , List < String > exportTableColumns ) { List < String > updateColumnList = DBAccessUtil . delSystemColumn ( exportTableColumns ) ; StringBuilder copySql = new StringBuilder ( "" ) ; copySql . append ( tableName ) ; copySql . append ( "" ) ; copySql . append ( tempTableName ) ; copySql . append ( "" ) ; copySql . append ( tableName ) ; copySql . append ( "" ) ; copySql . append ( Constants . getSidColumnName ( ) ) ; copySql . append ( "" ) ; copySql . append ( tempTableName ) ; copySql . append ( "" ) ; copySql . append ( Constants . getSidColumnName ( ) ) ; copySql . append ( "" ) ; copySql . append ( tableName ) ; copySql . append ( "" ) ; copySql . append ( Constants . getVersionColumnName ( ) ) ; copySql . append ( "" ) ; copySql . append ( tableName ) ; copySql . append ( "" ) ; copySql . append ( Constants . getVersionColumnName ( ) ) ; copySql . append ( "" ) ; copySql . append ( Constants . SYS_COLUMN_INCREMENT_VERSION_NO ) ; copySql . append ( "" ) ; copySql . append ( tableName ) ; copySql . append ( "" ) ; copySql . append ( Constants . getUpdatedDateTimeColumnName ( ) ) ; copySql . append ( "" ) ; int updateColumnSize = updateColumnList . size ( ) ; for ( int i = ; i < updateColumnSize ; i ++ ) { copySql . append ( tableName ) ; copySql . append ( "" ) ; copySql . append ( updateColumnList . get ( i ) ) ; copySql . append ( "" ) ; copySql . append ( tempTableName ) ; copySql . append ( "" ) ; copySql . append ( updateColumnList . get ( i ) ) ; if ( i + < updateColumnSize ) { copySql . append ( "" ) ; } } copySql . append ( selectCondition ) ; return copySql . toString ( ) ; } private String createUpdateSelectCondition ( String tableName , String tempTableName ) { StringBuilder selectCondition = new StringBuilder ( "" ) ; selectCondition . append ( tableName ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getSidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( tempTableName ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getSidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( tempTableName ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getSidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( tempTableName ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; return selectCondition . toString ( ) ; } private String createCountTempSql ( String tempTableName ) { StringBuilder countTempSql = new StringBuilder ( "" ) ; countTempSql . append ( tempTableName ) ; return countTempSql . toString ( ) ; } private String createMaxTempSidSql ( String temporarySidColumnName , String tempTableName ) { StringBuilder maxTempSidSql = new StringBuilder ( "" ) ; maxTempSidSql . append ( Constants . getTemporarySidColumnName ( ) ) ; maxTempSidSql . append ( "" ) ; maxTempSidSql . append ( tempTableName ) ; return maxTempSidSql . toString ( ) ; } private String createMinTempSidSql ( String temporarySidColumnName , String tempTableName ) { StringBuilder minTempSidSql = new StringBuilder ( "" ) ; minTempSidSql . append ( Constants . getTemporarySidColumnName ( ) ) ; minTempSidSql . append ( "" ) ; minTempSidSql . append ( tempTableName ) ; return minTempSidSql . toString ( ) ; } private void copyNonDuplicateData ( ExportTargetTableBean expTableBean , String tableName , long maxRecord , String jobflowSid , boolean isGetRecordLock , Connection conn ) throws BulkLoaderSystemException { String recordLockSql = null ; String selectCondition = createInsertselectcondition ( expTableBean , maxRecord ) ; String copySql = createInsertCopySql ( tableName , expTableBean , selectCondition ) ; String delSql = createInsertDelSql ( expTableBean , selectCondition ) ; PreparedStatement stmt = null ; while ( true ) { int copyCount = ; try { stmt = conn . prepareStatement ( copySql . toString ( ) ) ; copyCount = DBConnection . executeUpdate ( stmt , copySql . toString ( ) , new String [ ] ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , copySql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } if ( copyCount == ) { DBConnection . commit ( conn ) ; break ; } if ( isGetRecordLock ) { String selectSidSql = "" ; StringBuilder userParam = new StringBuilder ( "" ) ; userParam . append ( tableName ) ; userParam . append ( "" ) ; String setUserParamSql = createSetUserParamSql ( tableName , userParam ) ; recordLockSql = createRecordLockSql ( tableName , expTableBean , jobflowSid , userParam , selectCondition ) ; ResultSet rs = null ; String sid = null ; try { stmt = conn . prepareStatement ( selectSidSql ) ; rs = DBConnection . executeQuery ( stmt , selectSidSql , new String [ ] ) ; rs . next ( ) ; sid = rs . getString ( ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , selectSidSql , new String [ ] ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } try { stmt = conn . prepareStatement ( setUserParamSql ) ; long param = Long . valueOf ( sid ) - ; stmt . setLong ( , param ) ; copyCount = DBConnection . executeUpdate ( stmt , setUserParamSql , new String [ ] { String . valueOf ( param ) } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , setUserParamSql , new String [ ] { sid } ) ; } finally { DBConnection . closePs ( stmt ) ; } try { stmt = conn . prepareStatement ( recordLockSql . toString ( ) ) ; copyCount = DBConnection . executeUpdate ( stmt , recordLockSql . toString ( ) , new String [ ] ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , recordLockSql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } } try { stmt = conn . prepareStatement ( delSql ) ; DBConnection . executeUpdate ( stmt , delSql , new String [ ] ) ; DBConnection . commit ( conn ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , delSql , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } LOG . info ( "" , tableName , expTableBean . getExportTempTableName ( ) , copySql , recordLockSql , delSql ) ; } } private String createRecordLockSql ( String tableName , ExportTargetTableBean expTableBean , String jobflowSid , StringBuilder userParam , String selectCondition ) { String rlTableName = DBAccessUtil . createRecordLockTableName ( tableName ) ; StringBuilder recordLockSql = new StringBuilder ( ) ; recordLockSql . append ( "" ) ; recordLockSql . append ( rlTableName ) ; recordLockSql . append ( "" ) ; recordLockSql . append ( Constants . getSidColumnName ( ) ) ; recordLockSql . append ( "" ) ; recordLockSql . append ( userParam ) ; recordLockSql . append ( "" ) ; recordLockSql . append ( userParam ) ; recordLockSql . append ( "" ) ; recordLockSql . append ( jobflowSid ) ; recordLockSql . append ( "" ) ; recordLockSql . append ( expTableBean . getExportTempTableName ( ) ) ; recordLockSql . append ( selectCondition ) ; return recordLockSql . toString ( ) ; } private String createSetUserParamSql ( String tableName , StringBuilder userParam ) { StringBuilder setUserParamSql = new StringBuilder ( "" ) ; setUserParamSql . append ( userParam ) ; setUserParamSql . append ( "" ) ; return setUserParamSql . toString ( ) ; } private String createInsertDelSql ( ExportTargetTableBean expTableBean , String selectCondition ) { StringBuilder delSql = new StringBuilder ( "" ) ; delSql . append ( expTableBean . getExportTempTableName ( ) ) ; delSql . append ( selectCondition ) ; return delSql . toString ( ) ; } private String createInsertCopySql ( String tableName , ExportTargetTableBean expTableBean , String selectCondition ) { List < String > columnList = DBAccessUtil . delSystemColumn ( expTableBean . getExportTableColumns ( ) ) ; String column = DBAccessUtil . joinColumnArray ( columnList ) ; StringBuilder copySql = new StringBuilder ( "" ) ; copySql . append ( tableName ) ; copySql . append ( "" ) ; copySql . append ( column ) ; copySql . append ( "" ) ; copySql . append ( Constants . getRegisteredDateTimeColumnName ( ) ) ; copySql . append ( "" ) ; copySql . append ( Constants . getUpdatedDateTimeColumnName ( ) ) ; copySql . append ( "" ) ; copySql . append ( column ) ; copySql . append ( "" ) ; copySql . append ( expTableBean . getExportTempTableName ( ) ) ; copySql . append ( selectCondition ) ; return copySql . toString ( ) ; } private String createInsertselectcondition ( ExportTargetTableBean expTableBean , long maxRecord ) { StringBuilder selectCondition = new StringBuilder ( "" ) ; selectCondition . append ( Constants . getSidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( expTableBean . getDuplicateFlagTableName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( expTableBean . getDuplicateFlagTableName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( expTableBean . getExportTempTableName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( "" ) ; selectCondition . append ( Constants . getTemporarySidColumnName ( ) ) ; selectCondition . append ( "" ) ; selectCondition . append ( maxRecord ) ; return selectCondition . toString ( ) ; } private boolean getRecordLock ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { String checkRecordLockSql = "" + "" + "" ; boolean isRecordLock = false ; PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( checkRecordLockSql ) ; stmt . setString ( , jobflowSid ) ; stmt . setString ( , tableName ) ; rs = DBConnection . executeQuery ( stmt , checkRecordLockSql , new String [ ] { jobflowSid , tableName } ) ; rs . next ( ) ; int count = rs . getInt ( "" ) ; if ( count > ) { isRecordLock = true ; } } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , checkRecordLockSql , new String [ ] { jobflowSid , tableName } ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } return isRecordLock ; } public boolean isUpdateEnd ( ) { return copyEnd ; } } package com . asakusafw . bulkloader . exporter ; import java . io . File ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . ExportTempTableStatus ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public class ExportFileLoad { static final Log LOG = new Log ( ExportFileLoad . class ) ; private static final int MAX_TABLE_NAME_LENGTH = ; private static final int MAX_TEMP_SID_LENGTH = ; public boolean loadFile ( ExporterBean bean ) { Connection conn = null ; try { conn = DBConnection . getConnection ( ) ; insertTempInfo ( bean , conn ) ; createTempTable ( bean , conn ) ; loadFile ( bean , conn ) ; updateStatus ( bean . getJobflowSid ( ) , conn ) ; return true ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; try { DBConnection . rollback ( conn ) ; } catch ( BulkLoaderSystemException e1 ) { LOG . log ( e1 ) ; } return false ; } finally { DBConnection . closeConn ( conn ) ; } } private void updateStatus ( String jobflowSid , Connection conn ) throws BulkLoaderSystemException { String beforeCopySql = "" + "" + "" ; PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( beforeCopySql ) ; stmt . setString ( , ExportTempTableStatus . BEFORE_COPY . getStatus ( ) ) ; stmt . setString ( , jobflowSid ) ; stmt . setString ( , ExportTempTableStatus . LOAD_EXIT . getStatus ( ) ) ; DBConnection . executeUpdate ( stmt , beforeCopySql , new String [ ] { ExportTempTableStatus . BEFORE_COPY . getStatus ( ) , jobflowSid , ExportTempTableStatus . LOAD_EXIT . getStatus ( ) } ) ; DBConnection . commit ( conn ) ; LOG . info ( "" , jobflowSid ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , beforeCopySql , new String [ ] { ExportTempTableStatus . BEFORE_COPY . getStatus ( ) , jobflowSid , ExportTempTableStatus . LOAD_EXIT . getStatus ( ) } ) ; } finally { DBConnection . closePs ( stmt ) ; } } private void loadFile ( ExporterBean bean , Connection conn ) throws BulkLoaderSystemException { String loadExitSql = "" + "" + "" ; List < String > list = bean . getExportTargetTableList ( ) ; for ( String tableName : list ) { ExportTargetTableBean tableBean = bean . getExportTargetTable ( tableName ) ; List < File > exportFileList = tableBean . getExportFiles ( ) ; long recordCount = ; for ( File file : exportFileList ) { recordCount += load ( tableBean . getExportTempTableName ( ) , file , tableBean . getExportTsvColumn ( ) , conn ) ; LOG . info ( "" , bean . getJobflowSid ( ) , tableName , tableBean . getExportTempTableName ( ) , file . getAbsolutePath ( ) ) ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , tableName , recordCount ) ; PreparedStatement stmt = null ; if ( tableBean . isDuplicateCheck ( ) ) { StringBuilder duplicateCheckSql = new StringBuilder ( "" ) ; duplicateCheckSql . append ( tableBean . getDuplicateFlagTableName ( ) ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( Constants . getTemporarySidColumnName ( ) ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( Constants . getTemporarySidColumnName ( ) ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( tableBean . getExportTempTableName ( ) ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( tableName ) ; String forceIndex = ConfigurationLoader . getForceIndexName ( bean . getBatchId ( ) , bean . getJobflowId ( ) , tableName ) ; if ( forceIndex != null ) { duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( forceIndex ) ; duplicateCheckSql . append ( "" ) ; } duplicateCheckSql . append ( "" ) ; List < String > key = tableBean . getKeyColumns ( ) ; int keySize = key . size ( ) ; for ( int i = ; i < keySize ; i ++ ) { duplicateCheckSql . append ( tableName ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( key . get ( i ) ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( tableBean . getExportTempTableName ( ) ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( key . get ( i ) ) ; if ( i < keySize - ) { duplicateCheckSql . append ( "" ) ; } } duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( tableBean . getExportTempTableName ( ) ) ; duplicateCheckSql . append ( "" ) ; duplicateCheckSql . append ( Constants . getSidColumnName ( ) ) ; duplicateCheckSql . append ( "" ) ; try { stmt = conn . prepareStatement ( duplicateCheckSql . toString ( ) ) ; DBConnection . executeUpdate ( stmt , duplicateCheckSql . toString ( ) , new String [ ] ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , duplicateCheckSql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } } try { stmt = conn . prepareStatement ( loadExitSql ) ; stmt . setString ( , ExportTempTableStatus . LOAD_EXIT . getStatus ( ) ) ; stmt . setString ( , bean . getJobflowSid ( ) ) ; stmt . setString ( , tableName ) ; int updateCount = DBConnection . executeUpdate ( stmt , loadExitSql , new String [ ] { ExportTempTableStatus . LOAD_EXIT . getStatus ( ) , bean . getJobflowSid ( ) , tableName } ) ; if ( updateCount == ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , "" + bean . getJobflowSid ( ) , "" + tableName ) ; } DBConnection . commit ( conn ) ; LOG . info ( "" , bean . getJobflowSid ( ) , tableName , tableBean . getExportTempTableName ( ) ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , loadExitSql , new String [ ] { ExportTempTableStatus . LOAD_EXIT . getStatus ( ) , bean . getJobflowSid ( ) , tableName } ) ; } finally { DBConnection . closePs ( stmt ) ; } } } private void createTempTable ( ExporterBean bean , Connection conn ) throws BulkLoaderSystemException { List < String > list = bean . getExportTargetTableList ( ) ; for ( String tableName : list ) { String tempTableName = bean . getExportTargetTable ( tableName ) . getExportTempTableName ( ) ; String duplicateTableName = bean . getExportTargetTable ( tableName ) . getDuplicateFlagTableName ( ) ; String createSql = createTableSql ( tableName , tempTableName , bean . getExportTargetTable ( tableName ) ) ; StringBuilder dupSql = new StringBuilder ( ) ; dupSql . append ( "" ) ; dupSql . append ( duplicateTableName ) ; dupSql . append ( "" ) ; dupSql . append ( Constants . getTemporarySidColumnName ( ) ) ; dupSql . append ( "" ) ; dupSql . append ( "" ) ; dupSql . append ( Constants . getTemporarySidColumnName ( ) ) ; dupSql . append ( "" ) ; PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( createSql . toString ( ) ) ; DBConnection . executeUpdate ( stmt , createSql . toString ( ) , new String [ ] ) ; LOG . info ( "" , bean . getJobflowSid ( ) , tableName , tempTableName , createSql . toString ( ) ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , createSql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } try { stmt = conn . prepareStatement ( dupSql . toString ( ) ) ; DBConnection . executeUpdate ( stmt , dupSql . toString ( ) , new String [ ] ) ; LOG . info ( "" , bean . getJobflowSid ( ) , tempTableName , duplicateTableName , dupSql . toString ( ) ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , dupSql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } } } protected String createTempTableName ( String tableName , String jobflowSid , Connection conn ) throws BulkLoaderSystemException { long seq = getTempSeq ( jobflowSid , tableName , conn ) ; int maxLength = MAX_TABLE_NAME_LENGTH - Constants . EXP_TEMP_TABLE_PREIX . length ( ) - Constants . EXPORT_TEMP_TABLE_DELIMITER . length ( ) - MAX_TEMP_SID_LENGTH - Constants . DUPLECATE_FLG_TABLE_END . length ( ) ; StringBuilder tempTableName = new StringBuilder ( Constants . EXP_TEMP_TABLE_PREIX ) ; if ( tableName . length ( ) > maxLength ) { tempTableName . append ( tableName . substring ( , maxLength ) ) ; } else { tempTableName . append ( tableName ) ; } tempTableName . append ( Constants . EXPORT_TEMP_TABLE_DELIMITER ) ; tempTableName . append ( seq ) ; return tempTableName . toString ( ) ; } protected long getTempSeq ( String jobflowSid , String tableName , Connection conn ) throws BulkLoaderSystemException { String selectSql = "" + "" + "" ; PreparedStatement stmt = null ; ResultSet rs = null ; long seq = ; try { stmt = conn . prepareStatement ( selectSql ) ; stmt . setString ( , jobflowSid ) ; stmt . setString ( , tableName ) ; rs = DBConnection . executeQuery ( stmt , selectSql , new String [ ] { jobflowSid , tableName } ) ; if ( rs . next ( ) ) { seq = rs . getLong ( "" ) ; } else { throw new BulkLoaderSystemException ( getClass ( ) , "" , "" + jobflowSid , "" + tableName ) ; } } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , selectSql , new String [ ] { jobflowSid , tableName } ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } return seq ; } protected String createTableSql ( String tableName , String tempTableName , ExportTargetTableBean tableBean ) throws BulkLoaderSystemException { List < String > sourceTables = computeSourceTables ( tableName , tableBean ) ; List < String > sourceColumns = computeCopyColumns ( tableName , tableBean ) ; StringBuilder createSql = new StringBuilder ( ) ; createSql . append ( createTempTableSqlHead ( tableName , tempTableName ) ) ; createSql . append ( DBAccessUtil . joinColumnArray ( sourceColumns ) ) ; createSql . append ( "" ) ; createSql . append ( DBAccessUtil . joinColumnArray ( sourceTables ) ) ; createSql . append ( "" ) ; return createSql . toString ( ) ; } private List < String > computeSourceTables ( String tableName , ExportTargetTableBean tableBean ) { assert tableName != null ; assert tableBean != null ; if ( tableBean . isDuplicateCheck ( ) ) { return Arrays . asList ( new String [ ] { tableName , tableBean . getErrorTableName ( ) } ) ; } else { return Arrays . asList ( new String [ ] { tableName } ) ; } } private List < String > computeCopyColumns ( String tableName , ExportTargetTableBean tableBean ) throws BulkLoaderSystemException { assert tableName != null ; assert tableBean != null ; List < String > columns = tableBean . getExportTsvColumn ( ) ; columns = DBAccessUtil . delSystemColumn ( columns ) ; columns = new ArrayList < String > ( columns ) ; if ( tableBean . isDuplicateCheck ( ) == false ) { int columnSize = columns . size ( ) ; for ( int i = ; i < columnSize ; i ++ ) { columns . set ( i , String . format ( "" , tableName , columns . get ( i ) , columns . get ( i ) ) ) ; } } else { Map < String , String > columnMap = new HashMap < String , String > ( ) ; for ( String columnName : tableBean . getErrorTableColumns ( ) ) { columnMap . put ( columnName , tableBean . getErrorTableName ( ) ) ; } columnMap . put ( tableBean . getErrorCodeColumn ( ) , tableBean . getErrorTableName ( ) ) ; for ( String columnName : tableBean . getExportTableColumns ( ) ) { columnMap . put ( columnName , tableName ) ; } int columnSize = columns . size ( ) ; for ( int i = ; i < columnSize ; i ++ ) { String owner = columnMap . get ( columns . get ( i ) ) ; if ( owner != null ) { columns . set ( i , String . format ( "" , owner , columns . get ( i ) , columns . get ( i ) ) ) ; } else { throw new BulkLoaderSystemException ( getClass ( ) , "" , columns . get ( i ) ) ; } } } return columns ; } private String createTempTableSqlHead ( String tableName , String tempTableName ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "" ) ; buf . append ( tempTableName ) ; buf . append ( "" ) ; buf . append ( Constants . getTemporarySidColumnName ( ) ) ; buf . append ( "" ) ; buf . append ( Constants . getSidColumnName ( ) ) ; buf . append ( "" ) ; buf . append ( Constants . getVersionColumnName ( ) ) ; buf . append ( "" ) ; buf . append ( Constants . getRegisteredDateTimeColumnName ( ) ) ; buf . append ( "" ) ; buf . append ( Constants . getUpdatedDateTimeColumnName ( ) ) ; buf . append ( "" ) ; buf . append ( "" ) ; buf . append ( Constants . getTemporarySidColumnName ( ) ) ; buf . append ( "" ) ; buf . append ( "" ) ; buf . append ( "" ) ; buf . append ( Constants . getTemporarySidColumnName ( ) ) ; buf . append ( "" ) ; buf . append ( createSystemColumn ( tableName , Constants . getSidColumnName ( ) ) ) ; buf . append ( "" ) ; buf . append ( createSystemColumn ( tableName , Constants . getVersionColumnName ( ) ) ) ; buf . append ( "" ) ; buf . append ( createSystemColumn ( tableName , Constants . getRegisteredDateTimeColumnName ( ) ) ) ; buf . append ( "" ) ; buf . append ( createSystemColumn ( tableName , Constants . getUpdatedDateTimeColumnName ( ) ) ) ; buf . append ( "" ) ; return buf . toString ( ) ; } private CharSequence createSystemColumn ( String tableName , String columnName ) { assert tableName != null ; assert columnName != null ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( tableName ) ; buf . append ( "" ) ; buf . append ( columnName ) ; buf . append ( "" ) ; buf . append ( columnName ) ; return buf ; } private void insertTempInfo ( ExporterBean bean , Connection conn ) throws BulkLoaderSystemException { String insertSql = "" + "" ; String updateSql = "" + "" + "" ; PreparedStatement stmt = null ; String jobflowSid = null ; jobflowSid = bean . getJobflowSid ( ) ; List < String > list = bean . getExportTargetTableList ( ) ; for ( String tableName : list ) { try { stmt = conn . prepareStatement ( insertSql ) ; stmt . setString ( , jobflowSid ) ; stmt . setString ( , tableName ) ; DBConnection . executeUpdate ( stmt , insertSql , new String [ ] { jobflowSid , tableName } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , insertSql , new String [ ] { jobflowSid , tableName } ) ; } finally { DBConnection . closePs ( stmt ) ; } String tempTableName = createTempTableName ( tableName , bean . getJobflowSid ( ) , conn ) ; bean . getExportTargetTable ( tableName ) . setExportTempTableName ( tempTableName ) ; String duplicateFlgTableName = DBAccessUtil . createDuplicateFlgTableName ( tempTableName ) ; bean . getExportTargetTable ( tableName ) . setDuplicateFlagTableName ( duplicateFlgTableName ) ; try { stmt = conn . prepareStatement ( updateSql ) ; stmt . setString ( , tempTableName ) ; stmt . setString ( , duplicateFlgTableName ) ; stmt . setString ( , jobflowSid ) ; stmt . setString ( , tableName ) ; DBConnection . executeUpdate ( stmt , updateSql , new String [ ] { tempTableName , jobflowSid , tableName } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , updateSql , new String [ ] { tempTableName , jobflowSid , tableName } ) ; } finally { DBConnection . closePs ( stmt ) ; } } DBConnection . commit ( conn ) ; LOG . info ( "" , bean . getJobflowSid ( ) ) ; } private long load ( String tempTableName , File file , List < String > exportTsvColumn , Connection conn ) throws BulkLoaderSystemException { if ( isEmpty ( file ) ) { return ; } StringBuilder sql = new StringBuilder ( "" ) ; sql . append ( file . getAbsolutePath ( ) . replace ( File . separatorChar , '' ) ) ; sql . append ( "" ) ; sql . append ( tempTableName ) ; sql . append ( DBAccessUtil . getTSVFileFormat ( ) ) ; sql . append ( "" ) ; sql . append ( DBAccessUtil . joinColumnArray ( exportTsvColumn ) ) ; sql . append ( "" ) ; PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( sql . toString ( ) ) ; long count = DBConnection . executeUpdate ( stmt , sql . toString ( ) , new String [ ] ) ; DBConnection . commit ( conn ) ; return count ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , sql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closePs ( stmt ) ; } } private boolean isEmpty ( File file ) { return file . exists ( ) && file . length ( ) == ; } } package com . asakusafw . bulkloader . exporter ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . List ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . ExportTempTableStatus ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public class TempTableDelete { static final Log LOG = new Log ( TempTableDelete . class ) ; public boolean delete ( List < ExportTempTableBean > exportTempTableBean , boolean isDeleteCopyIncomplete ) { Connection conn = null ; try { conn = DBConnection . getConnection ( ) ; int beanSize = exportTempTableBean . size ( ) ; for ( int i = ; i < beanSize ; i ++ ) { deleteTempTable ( exportTempTableBean . get ( i ) . getTemporaryTableName ( ) , exportTempTableBean . get ( i ) . getDuplicateFlagTableName ( ) , isDeleteCopyIncomplete , conn ) ; } for ( int i = ; i < beanSize ; i ++ ) { deleteTempInfoRecord ( exportTempTableBean . get ( i ) . getJobflowSid ( ) , exportTempTableBean . get ( i ) . getExportTableName ( ) , isDeleteCopyIncomplete , conn ) ; } DBConnection . commit ( conn ) ; return true ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; try { DBConnection . rollback ( conn ) ; } catch ( BulkLoaderSystemException e1 ) { e1 . printStackTrace ( ) ; } return false ; } finally { DBConnection . closeConn ( conn ) ; } } public void deleteTempInfoRecord ( String jobflowSid , String tableName , boolean isDeleteCopyIncomplete , Connection conn ) throws BulkLoaderSystemException { StringBuilder sql = new StringBuilder ( "" + "" ) ; if ( ! isDeleteCopyIncomplete ) { sql . append ( "" ) ; sql . append ( ExportTempTableStatus . COPY_EXIT . getStatus ( ) ) ; } PreparedStatement stmt = null ; try { LOG . info ( "" , sql . toString ( ) , jobflowSid , tableName ) ; stmt = conn . prepareStatement ( sql . toString ( ) ) ; stmt . setString ( , jobflowSid ) ; stmt . setString ( , tableName ) ; DBConnection . executeUpdate ( stmt , sql . toString ( ) , new String [ ] { jobflowSid , tableName } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , DBAccessUtil . class , sql . toString ( ) , new String [ ] { jobflowSid , tableName } ) ; } finally { DBConnection . closePs ( stmt ) ; } } public void deleteTempTable ( String exportTempName , String duplicateFlagTableName , boolean isDeleteCopyIncomplete , Connection conn ) throws BulkLoaderSystemException { String checkSql = "" + "" + "" ; StringBuilder tempDelSql = new StringBuilder ( "" ) ; tempDelSql . append ( exportTempName ) ; StringBuilder dupDelSql = new StringBuilder ( "" ) ; dupDelSql . append ( duplicateFlagTableName ) ; if ( ! isDeleteCopyIncomplete ) { PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( checkSql ) ; stmt . setString ( , exportTempName ) ; rs = DBConnection . executeQuery ( stmt , checkSql , new String [ ] { exportTempName } ) ; if ( rs . next ( ) ) { ExportTempTableStatus status = ExportTempTableStatus . find ( rs . getString ( "" ) ) ; if ( ! ExportTempTableStatus . COPY_EXIT . equals ( status ) ) { LOG . info ( "" , exportTempName , status . getStatus ( ) ) ; return ; } } } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , DBAccessUtil . class , checkSql , new String [ ] { exportTempName } ) ; } finally { DBConnection . closePs ( stmt ) ; DBConnection . closeRs ( rs ) ; } } PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( tempDelSql . toString ( ) ) ; DBConnection . executeUpdate ( stmt , tempDelSql . toString ( ) , new String [ ] ) ; LOG . info ( "" , tempDelSql ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , DBAccessUtil . class , tempDelSql . toString ( ) , new String [ ] { exportTempName } ) ; } finally { DBConnection . closePs ( stmt ) ; } try { stmt = conn . prepareStatement ( dupDelSql . toString ( ) ) ; DBConnection . executeUpdate ( stmt , dupDelSql . toString ( ) , new String [ ] ) ; LOG . info ( "" , dupDelSql ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , DBAccessUtil . class , dupDelSql . toString ( ) , new String [ ] { duplicateFlagTableName } ) ; } finally { DBConnection . closePs ( stmt ) ; } } } package com . asakusafw . bulkloader . bean ; import com . asakusafw . bulkloader . common . ExportTempTableStatus ; public class ExportTempTableBean { private String jobflowSid ; private String exportTableName ; private String temporaryTableName ; private String duplicateFlagTableName = null ; private ExportTempTableStatus tempTableStatus ; public String getJobflowSid ( ) { return jobflowSid ; } public void setJobflowSid ( String jobflowSid ) { this . jobflowSid = jobflowSid ; } public String getExportTableName ( ) { return exportTableName ; } public void setExportTableName ( String tableName ) { this . exportTableName = tableName ; } public String getTemporaryTableName ( ) { return temporaryTableName ; } public void setTemporaryTableName ( String exportTempName ) { this . temporaryTableName = exportTempName ; } public ExportTempTableStatus getTempTableStatus ( ) { return tempTableStatus ; } public void setTempTableStatus ( ExportTempTableStatus tempTableStatus ) { this . tempTableStatus = tempTableStatus ; } public String getDuplicateFlagTableName ( ) { return duplicateFlagTableName ; } public void setDuplicateFlagTableName ( String duplicateFlagTableName ) { this . duplicateFlagTableName = duplicateFlagTableName ; } } package com . asakusafw . bulkloader . bean ; import java . io . File ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . List ; import com . asakusafw . bulkloader . common . ImportTableLockType ; import com . asakusafw . bulkloader . common . ImportTableLockedOperation ; import com . asakusafw . bulkloader . transfer . FileProtocol ; public class ImportTargetTableBean { private List < String > importTargetColumns = new ArrayList < String > ( ) ; private String searchCondition ; private boolean useCache ; private ImportTableLockType lockType ; private ImportTableLockedOperation lockedOperation ; private Class < ? > importTargetType ; private String dfsFilePath ; private String cacheId ; private Calendar startTimestamp ; private FileProtocol importProtocol ; private File importFile ; public String getDfsFilePath ( ) { return dfsFilePath ; } public void setDfsFilePath ( String hdfsFilePath ) { this . dfsFilePath = hdfsFilePath ; } public List < String > getImportTargetColumns ( ) { if ( importTargetColumns == null ) { return null ; } else { return importTargetColumns ; } } public void setImportTargetColumns ( List < String > importTargetColumns ) { if ( importTargetColumns == null ) { this . importTargetColumns = null ; } else { this . importTargetColumns = importTargetColumns ; } } public String getSearchCondition ( ) { return searchCondition ; } public void setSearchCondition ( String searchCondition ) { this . searchCondition = searchCondition ; } @ Deprecated public boolean isUseCache ( ) { return useCache ; } @ Deprecated public void setUseCache ( boolean isUseCache ) { this . useCache = isUseCache ; } public ImportTableLockType getLockType ( ) { return lockType ; } public void setLockType ( ImportTableLockType lockType ) { this . lockType = lockType ; } public ImportTableLockedOperation getLockedOperation ( ) { return lockedOperation ; } public void setLockedOperation ( ImportTableLockedOperation lockedOperation ) { this . lockedOperation = lockedOperation ; } public Class < ? > getImportTargetType ( ) { return importTargetType ; } public void setImportTargetType ( Class < ? > importTargetTableBean ) { this . importTargetType = importTargetTableBean ; } public String getCacheId ( ) { return cacheId ; } public void setCacheId ( String cacheId ) { this . cacheId = cacheId ; } public Calendar getStartTimestamp ( ) { return startTimestamp == null ? null : ( Calendar ) startTimestamp . clone ( ) ; } public void setStartTimestamp ( Calendar startTimestamp ) { this . startTimestamp = startTimestamp == null ? null : ( Calendar ) startTimestamp . clone ( ) ; } public FileProtocol getImportProtocol ( ) { return importProtocol ; } public void setImportProtocol ( FileProtocol importProtocol ) { this . importProtocol = importProtocol ; } public File getImportFile ( ) { return importFile ; } public void setImportFile ( File importFile ) { this . importFile = importFile ; } } package com . asakusafw . bulkloader . bean ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; public class ExporterBean { private int retryCount ; private int retryInterval ; private String targetName ; private String batchId ; private String jobflowId ; private String executionId ; private String jobflowSid ; private Map < String , ExportTargetTableBean > exportTargetTable ; private Map < String , ImportTargetTableBean > importTargetTable ; public ExportTargetTableBean getExportTargetTable ( String tableName ) { return exportTargetTable . get ( tableName ) ; } public List < String > getExportTargetTableList ( ) { return new ArrayList < String > ( exportTargetTable . keySet ( ) ) ; } public void setExportTargetTable ( Map < String , ExportTargetTableBean > targetTable ) { this . exportTargetTable = targetTable ; } public ImportTargetTableBean getImportTargetTable ( String tableName ) { return importTargetTable . get ( tableName ) ; } public List < String > getImportTargetTableList ( ) { return new ArrayList < String > ( importTargetTable . keySet ( ) ) ; } public void setImportTargetTable ( Map < String , ImportTargetTableBean > targetTable ) { this . importTargetTable = targetTable ; } public int getRetryCount ( ) { return retryCount ; } public void setRetryCount ( int retryCount ) { this . retryCount = retryCount ; } public int getRetryInterval ( ) { return retryInterval ; } public void setRetryInterval ( int retryInterval ) { this . retryInterval = retryInterval ; } public String getJobflowId ( ) { return jobflowId ; } public void setJobflowId ( String jobflowId ) { this . jobflowId = jobflowId ; } public String getExecutionId ( ) { return executionId ; } public void setExecutionId ( String executionId ) { this . executionId = executionId ; } public String getBatchId ( ) { return batchId ; } public void setBatchId ( String batchId ) { this . batchId = batchId ; } public String getJobflowSid ( ) { return jobflowSid ; } public void setJobflowSid ( String jobflowSid ) { this . jobflowSid = jobflowSid ; } public String getTargetName ( ) { return targetName ; } public void setTargetName ( String targetName ) { this . targetName = targetName ; } } package com . asakusafw . bulkloader . bean ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; public class ExportTargetTableBean { private boolean duplicateCheck = false ; private String errorTableName = null ; private List < String > exportTsvColumns = new ArrayList < String > ( ) ; private List < String > exportTableColumns = new ArrayList < String > ( ) ; private List < String > errorTableColumns = new ArrayList < String > ( ) ; private List < String > keyColumns = new ArrayList < String > ( ) ; private String errorCodeColumn = null ; private String errorCode = null ; private Class < ? > exportTargetType ; private List < String > dfsFilePaths = new ArrayList < String > ( ) ; private List < File > exportFiles = new ArrayList < File > ( ) ; private String exportTempTableName = null ; private String duplicateFlagTableName = null ; public List < String > getExportTsvColumn ( ) { if ( exportTsvColumns == null ) { return null ; } else { return exportTsvColumns ; } } public void setExportTsvColumns ( List < String > exportTsvColumns ) { if ( exportTsvColumns == null ) { this . exportTsvColumns = null ; } else { this . exportTsvColumns = exportTsvColumns ; } } public List < String > getDfsFilePaths ( ) { return dfsFilePaths ; } public void setDfsFilePaths ( List < String > hdfsFilPaths ) { this . dfsFilePaths = hdfsFilPaths ; } public Class < ? > getExportTargetType ( ) { return exportTargetType ; } public void setExportTargetType ( Class < ? > exportTargetTableBean ) { this . exportTargetType = exportTargetTableBean ; } public List < File > getExportFiles ( ) { return exportFiles ; } public void addExportFile ( File file ) { this . exportFiles . add ( file ) ; } public String getErrorTableName ( ) { return errorTableName ; } public void setErrorTableName ( String errorTableName ) { this . errorTableName = errorTableName ; } public List < String > getExportTableColumns ( ) { return exportTableColumns ; } public void setExportTableColumns ( List < String > exportTableColumns ) { this . exportTableColumns = exportTableColumns ; } public List < String > getErrorTableColumns ( ) { return errorTableColumns ; } public void setErrorTableColumns ( List < String > errorTableColumns ) { this . errorTableColumns = errorTableColumns ; } public List < String > getKeyColumns ( ) { return keyColumns ; } public void setKeyColumns ( List < String > keyColumns ) { this . keyColumns = keyColumns ; } public String getErrorCodeColumn ( ) { return errorCodeColumn ; } public void setErrorCodeColumn ( String errorCodeColumn ) { this . errorCodeColumn = errorCodeColumn ; } public String getErrorCode ( ) { return errorCode ; } public void setErrorCode ( String errorCode ) { this . errorCode = errorCode ; } public boolean isDuplicateCheck ( ) { return duplicateCheck ; } public void setDuplicateCheck ( boolean duplicateCheck ) { this . duplicateCheck = duplicateCheck ; } public String getExportTempTableName ( ) { return exportTempTableName ; } public void setExportTempTableName ( String exportTempTableName ) { this . exportTempTableName = exportTempTableName ; } public String getDuplicateFlagTableName ( ) { return duplicateFlagTableName ; } public void setDuplicateFlagTableName ( String tableName ) { this . duplicateFlagTableName = tableName ; } } package com . asakusafw . bulkloader . bean ; package com . asakusafw . bulkloader . bean ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . Map ; public class ImportBean { private int retryCount ; private int retryInterval ; private boolean primary ; private String targetName ; private String batchId ; private String jobflowId ; private String executionId ; private Date jobnetEndTime ; private List < String > recoveryTables ; private Map < String , ImportTargetTableBean > targetTable ; public ImportTargetTableBean getTargetTable ( String tableName ) { return targetTable . get ( tableName ) ; } public List < String > getImportTargetTableList ( ) { return new ArrayList < String > ( targetTable . keySet ( ) ) ; } public void setTargetTable ( Map < String , ImportTargetTableBean > targetTable ) { this . targetTable = targetTable ; } public List < String > getRecoveryTables ( ) { return recoveryTables ; } public void setRecoveryTables ( List < String > recoveryTables ) { this . recoveryTables = recoveryTables ; } public int getRetryCount ( ) { return retryCount ; } public void setRetryCount ( int retryCount ) { this . retryCount = retryCount ; } public int getRetryInterval ( ) { return retryInterval ; } public void setRetryInterval ( int retryInterval ) { this . retryInterval = retryInterval ; } public String getJobflowId ( ) { return jobflowId ; } public void setJobflowId ( String jobflowId ) { this . jobflowId = jobflowId ; } public String getExecutionId ( ) { return executionId ; } public void setExecutionId ( String executionId ) { this . executionId = executionId ; } public String getBatchId ( ) { return batchId ; } public void setBatchId ( String batchId ) { this . batchId = batchId ; } public Date getJobnetEndTime ( ) { if ( jobnetEndTime == null ) { return null ; } else { return ( Date ) jobnetEndTime . clone ( ) ; } } public void setJobnetEndTime ( Date jobnetEndTime ) { if ( jobnetEndTime == null ) { this . jobnetEndTime = null ; } else { this . jobnetEndTime = ( Date ) jobnetEndTime . clone ( ) ; } } public String getTargetName ( ) { return targetName ; } public void setTargetName ( String targetName ) { this . targetName = targetName ; } public boolean isPrimary ( ) { return primary ; } public void setPrimary ( boolean primary ) { this . primary = primary ; } } package com . asakusafw . bulkloader . exception ; package com . asakusafw . bulkloader . exception ; import java . sql . SQLException ; public class BulkLoaderSystemException extends Exception { private final Class < ? > clazz ; private final String messageId ; private final Object [ ] messageArgs ; private static final long serialVersionUID = ; public BulkLoaderSystemException ( Throwable cause , Class < ? > clazz , String messageId , Object ... messageArgs ) { super ( cause ) ; this . clazz = clazz ; this . messageId = messageId ; this . messageArgs = messageArgs . clone ( ) ; } public BulkLoaderSystemException ( Class < ? > clazz , String messageId , Object ... messageArgs ) { this . clazz = clazz ; this . messageId = messageId ; this . messageArgs = messageArgs . clone ( ) ; } public Class < ? > getClazz ( ) { return clazz ; } public String getMessageId ( ) { return messageId ; } public Object [ ] getMessageArgs ( ) { return messageArgs . clone ( ) ; } public static BulkLoaderSystemException createInstanceCauseBySQLException ( SQLException e , Class < ? > clazz , String sql , String ... params ) { String param = null ; if ( params != null && params . length != ) { StringBuffer sb = new StringBuffer ( ) ; for ( int i = ; i < params . length ; i ++ ) { sb . append ( params [ i ] ) ; if ( i != params . length ) { sb . append ( "" ) ; } } param = sb . toString ( ) ; } return new BulkLoaderSystemException ( e , clazz , "" , sql , param ) ; } public static BulkLoaderSystemException createInstanceCauseBySQLException ( SQLException e , Class < ? > clazz , String sql , Object ... params ) { String param = null ; if ( params != null && params . length != ) { StringBuffer sb = new StringBuffer ( ) ; for ( int i = ; i < params . length ; i ++ ) { sb . append ( params [ i ] ) ; if ( i != params . length ) { sb . append ( "" ) ; } } param = sb . toString ( ) ; } return new BulkLoaderSystemException ( e , clazz , "" , sql , param ) ; } } package com . asakusafw . bulkloader . exception ; public class BulkLoaderReRunnableException extends Exception { private Class < ? > clazz ; private String messageId ; private Object [ ] messageArgs ; private static final long serialVersionUID = ; public BulkLoaderReRunnableException ( Throwable cause , Class < ? > clazz , String messageId , Object ... messageArgs ) { super ( cause ) ; this . clazz = clazz ; this . messageId = messageId ; this . messageArgs = messageArgs . clone ( ) ; } public BulkLoaderReRunnableException ( Class < ? > clazz , String messageId , Object ... messageArgs ) { this . clazz = clazz ; this . messageId = messageId ; this . messageArgs = messageArgs . clone ( ) ; } public Class < ? > getClazz ( ) { return clazz ; } public String getMessageId ( ) { return messageId ; } public Object [ ] getMessageArgs ( ) { return messageArgs . clone ( ) ; } } package com . asakusafw . bulkloader . log ; import java . sql . Timestamp ; import java . text . DateFormat ; import java . text . MessageFormat ; import java . text . SimpleDateFormat ; import java . util . ResourceBundle ; import org . apache . log4j . Logger ; import org . apache . log4j . MDC ; import com . asakusafw . bulkloader . exception . BulkLoaderReRunnableException ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; public class Log { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; private static final String LOG_MESSAGE_ID_NULL_STR = "" ; private final Logger internal ; public Log ( Class < ? > base ) { if ( base == null ) { throw new IllegalArgumentException ( "" ) ; } this . internal = Logger . getLogger ( base ) ; } public void debugMessage ( String format , Object ... arguments ) { if ( internal . isDebugEnabled ( ) ) { setMessageCode ( "" ) ; internal . debug ( MessageFormat . format ( format , arguments ) ) ; clearMessageCode ( ) ; } } public void info ( String code , Object ... arguments ) { if ( internal . isInfoEnabled ( ) ) { String message = message ( code , arguments ) ; setMessageCode ( code ) ; internal . info ( message ) ; clearMessageCode ( ) ; } } public void info ( Throwable exception , String code , Object ... arguments ) { if ( internal . isInfoEnabled ( ) ) { String message = message ( code , arguments ) ; setMessageCode ( code ) ; internal . info ( message , exception ) ; clearMessageCode ( ) ; } } public void warn ( String code , Object ... arguments ) { String message = message ( code , arguments ) ; setMessageCode ( code ) ; internal . warn ( message ) ; clearMessageCode ( ) ; } public void warn ( Throwable exception , String code , Object ... arguments ) { String message = message ( code , arguments ) ; setMessageCode ( code ) ; internal . warn ( message , exception ) ; clearMessageCode ( ) ; } public void log ( BulkLoaderReRunnableException exception ) { String code = exception . getMessageId ( ) ; String message = message ( code , exception . getMessageArgs ( ) ) ; setMessageCode ( code ) ; Logger . getLogger ( exception . getClazz ( ) ) . warn ( message , exception . getCause ( ) ) ; clearMessageCode ( ) ; } public void log ( BulkLoaderSystemException exception ) { String code = exception . getMessageId ( ) ; String message = message ( code , exception . getMessageArgs ( ) ) ; try { setMessageCode ( code ) ; Logger . getLogger ( exception . getClazz ( ) ) . error ( message , exception . getCause ( ) ) ; clearMessageCode ( ) ; } catch ( RuntimeException e ) { System . err . printf ( "" , message ) ; e . printStackTrace ( ) ; throw e ; } } public void error ( String code , Object ... arguments ) { String message = message ( code , arguments ) ; try { setMessageCode ( code ) ; internal . error ( message ) ; clearMessageCode ( ) ; } catch ( RuntimeException e ) { System . err . printf ( "" , message ) ; e . printStackTrace ( ) ; throw e ; } } public void error ( Throwable exception , String code , Object ... arguments ) { String message = message ( code , arguments ) ; try { setMessageCode ( code ) ; internal . error ( message , exception ) ; clearMessageCode ( ) ; } catch ( RuntimeException e ) { System . err . printf ( "" , message ) ; e . printStackTrace ( ) ; throw e ; } } private String message ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } private void setMessageCode ( String messageId ) { Timestamp logTime = new Timestamp ( System . currentTimeMillis ( ) ) ; DateFormat dateFormat = new SimpleDateFormat ( "" ) ; MDC . put ( "" , dateFormat . format ( logTime ) ) ; MDC . put ( "" , messageId ) ; } private void clearMessageCode ( ) { MDC . put ( "" , LOG_MESSAGE_ID_NULL_STR ) ; } } package com . asakusafw . bulkloader . log ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . apache . log4j . xml . DOMConfigurator ; public final class LogInitializer { private static boolean isInitialized = false ; private LogInitializer ( ) { return ; } public static void execute ( String logConfFilePath ) throws IOException { loadFile ( logConfFilePath ) ; isInitialized = true ; } static void loadFile ( String filePath ) throws FileNotFoundException { File file = new File ( filePath ) ; if ( ! file . exists ( ) ) { throw new FileNotFoundException ( filePath ) ; } DOMConfigurator . configure ( filePath ) ; } public static boolean isInitialized ( ) { return isInitialized ; } } package com . asakusafw . bulkloader . log ; package com . asakusafw . bulkloader . transfer ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . apache . commons . io . IOUtils ; import com . asakusafw . bulkloader . common . StreamRedirectThread ; public abstract class StreamFileListProvider implements FileListProvider { private final List < Thread > running = new ArrayList < Thread > ( ) ; @ Override public FileList . Reader openReader ( ) throws IOException { InputStream stream = getInputStream ( ) ; boolean succeed = false ; try { FileList . Reader channel = FileList . createReader ( stream ) ; succeed = true ; return channel ; } finally { if ( succeed == false ) { IOUtils . closeQuietly ( stream ) ; } } } @ Override public FileList . Writer openWriter ( boolean compress ) throws IOException { OutputStream stream = getOutputStream ( ) ; boolean succeed = false ; try { FileList . Writer channel = FileList . createWriter ( stream , compress ) ; succeed = true ; return channel ; } finally { if ( succeed == false ) { IOUtils . closeQuietly ( stream ) ; } } } @ Override public void discardReader ( ) throws IOException { redirect ( getInputStream ( ) , System . out ) ; } @ Override public void discardWriter ( ) throws IOException { getOutputStream ( ) . close ( ) ; } @ Override public final void waitForComplete ( ) throws IOException , InterruptedException { synchronized ( running ) { for ( Iterator < Thread > iter = running . iterator ( ) ; iter . hasNext ( ) ; ) { Thread next = iter . next ( ) ; if ( next . isAlive ( ) ) { next . join ( ) ; } iter . remove ( ) ; } } waitForDone ( ) ; } protected final void redirect ( InputStream in , OutputStream out ) { if ( in == null ) { throw new IllegalArgumentException ( "" ) ; } if ( out == null ) { throw new IllegalArgumentException ( "" ) ; } Thread t = new StreamRedirectThread ( in , out ) ; t . setDaemon ( true ) ; t . start ( ) ; synchronized ( running ) { running . add ( t ) ; } } protected abstract InputStream getInputStream ( ) throws IOException ; protected abstract OutputStream getOutputStream ( ) throws IOException ; protected abstract void waitForDone ( ) throws IOException , InterruptedException ; } package com . asakusafw . bulkloader . transfer ; import java . text . MessageFormat ; import java . util . Properties ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; public class FileProtocol { public static final String KEY_KIND = "" ; public static final String KEY_LOCATION = "" ; private final Kind kind ; private final String location ; private final CacheInfo info ; public FileProtocol ( Kind kind , String location , CacheInfo info ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( location == null ) { throw new IllegalArgumentException ( "" ) ; } if ( kind . hasCacheInfo ( ) && info == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , kind ) ) ; } this . kind = kind ; this . location = location ; this . info = info ; } public Kind getKind ( ) { return kind ; } public String getLocation ( ) { return location ; } public CacheInfo getInfo ( ) { return info ; } public static FileProtocol loadFrom ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } String kindString = loadProperty ( properties , KEY_KIND ) ; String location = loadProperty ( properties , KEY_LOCATION ) ; Kind kind ; try { kind = Kind . valueOf ( kindString ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , KEY_KIND , kindString ) , e ) ; } CacheInfo info ; if ( kind . hasCacheInfo ( ) ) { info = CacheInfo . loadFrom ( properties ) ; } else { info = null ; } return new FileProtocol ( kind , location , info ) ; } private static String loadProperty ( Properties properties , String key ) { assert properties != null ; assert key != null ; String property = properties . getProperty ( key ) ; if ( property == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , key ) ) ; } return property . trim ( ) ; } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } properties . setProperty ( KEY_KIND , kind . name ( ) ) ; properties . setProperty ( KEY_LOCATION , location ) ; if ( kind . hasCacheInfo ( ) ) { assert info != null ; info . storeTo ( properties ) ; } } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( kind ) ; builder . append ( "" ) ; builder . append ( location ) ; builder . append ( "" ) ; builder . append ( info ) ; builder . append ( "" ) ; return builder . toString ( ) ; } public enum Kind { GET_CACHE_INFO ( false ) , DELETE_CACHE ( false ) , RESPONSE_CACHE_INFO ( true ) , RESPONSE_DELETED ( false ) , RESPONSE_NOT_FOUND ( false ) , RESPONSE_ERROR ( false ) , CONTENT ( false ) , CREATE_CACHE ( true ) , UPDATE_CACHE ( true ) , ; private final boolean hasCacheInfo ; private Kind ( boolean hasCacheInfo ) { this . hasCacheInfo = hasCacheInfo ; } public boolean hasCacheInfo ( ) { return hasCacheInfo ; } } } package com . asakusafw . bulkloader . transfer ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; public class ProcessFileListProvider extends StreamFileListProvider { private final List < String > command ; private final Process process ; public ProcessFileListProvider ( List < String > command , Map < String , String > extraEnv ) throws IOException { if ( command == null ) { throw new IllegalArgumentException ( "" ) ; } if ( extraEnv == null ) { throw new IllegalArgumentException ( "" ) ; } this . command = command ; this . process = createProcess ( command , extraEnv ) ; boolean succeed = false ; try { redirect ( process . getErrorStream ( ) , System . err ) ; succeed = true ; } finally { if ( succeed == false ) { process . destroy ( ) ; } } } private Process createProcess ( List < String > localCommand , Map < String , String > extraEnv ) throws IOException { assert localCommand != null ; assert extraEnv != null ; ProcessBuilder builder = new ProcessBuilder ( localCommand ) ; builder . directory ( new File ( System . getProperty ( "" , "" ) ) ) ; builder . environment ( ) . putAll ( extraEnv ) ; return builder . start ( ) ; } @ Override protected InputStream getInputStream ( ) throws IOException { return process . getInputStream ( ) ; } @ Override protected OutputStream getOutputStream ( ) throws IOException { return process . getOutputStream ( ) ; } @ Override protected void waitForDone ( ) throws IOException , InterruptedException { int exitCode = process . waitFor ( ) ; if ( exitCode != ) { throw new IOException ( MessageFormat . format ( "" , exitCode , command ) ) ; } } @ Override public void close ( ) { process . destroy ( ) ; } } package com . asakusafw . bulkloader . transfer ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import java . util . regex . Pattern ; public class OpenSshFileListProvider extends StreamFileListProvider { private static final Pattern SH_NAME = Pattern . compile ( "" ) ; private static final Pattern SH_METACHARACTERS = Pattern . compile ( "" ) ; private final List < String > command ; private final Process process ; public OpenSshFileListProvider ( String sshExec , String userName , String hostName , List < String > command , Map < String , String > env ) throws IOException { if ( sshExec == null ) { throw new IllegalArgumentException ( "" ) ; } if ( userName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( hostName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( command == null ) { throw new IllegalArgumentException ( "" ) ; } if ( env == null ) { throw new IllegalArgumentException ( "" ) ; } this . command = command ; this . process = createProcess ( sshExec , userName , hostName , command , env ) ; boolean succeed = false ; try { redirect ( process . getErrorStream ( ) , System . err ) ; succeed = true ; } finally { if ( succeed == false ) { process . destroy ( ) ; } } } private Process createProcess ( String sshExec , String userName , String hostName , List < String > remoteCommand , Map < String , String > remoteEnv ) throws IOException { assert sshExec != null ; assert userName != null ; assert hostName != null ; assert remoteCommand != null ; assert remoteEnv != null ; List < String > localCommand = new ArrayList < String > ( ) ; localCommand . add ( sshExec ) ; localCommand . add ( "" ) ; localCommand . add ( userName ) ; localCommand . add ( hostName ) ; localCommand . add ( buildCommand ( remoteCommand , remoteEnv ) ) ; ProcessBuilder builder = new ProcessBuilder ( localCommand ) ; return builder . start ( ) ; } @ Override protected InputStream getInputStream ( ) throws IOException { return process . getInputStream ( ) ; } @ Override protected OutputStream getOutputStream ( ) throws IOException { return process . getOutputStream ( ) ; } @ Override protected void waitForDone ( ) throws IOException , InterruptedException { int exitCode = process . waitFor ( ) ; if ( exitCode != ) { throw new IOException ( MessageFormat . format ( "" , exitCode , command ) ) ; } } @ Override public void close ( ) { process . destroy ( ) ; } private String buildCommand ( List < String > commandLineTokens , Map < String , String > environmentVariables ) { assert commandLineTokens != null ; assert environmentVariables != null ; StringBuilder buf = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : environmentVariables . entrySet ( ) ) { if ( SH_NAME . matcher ( entry . getKey ( ) ) . matches ( ) == false ) { continue ; } if ( buf . length ( ) > ) { buf . append ( '' ) ; } buf . append ( entry . getKey ( ) ) ; String replaced = SH_METACHARACTERS . matcher ( entry . getValue ( ) ) . replaceAll ( "" ) ; buf . append ( '' ) ; buf . append ( '' ) ; buf . append ( replaced ) ; buf . append ( '' ) ; } for ( String token : commandLineTokens ) { if ( buf . length ( ) > ) { buf . append ( '' ) ; } String replaced = SH_METACHARACTERS . matcher ( token ) . replaceAll ( "" ) ; buf . append ( '' ) ; buf . append ( replaced ) ; buf . append ( '' ) ; } return buf . toString ( ) ; } } package com . asakusafw . bulkloader . transfer ; import java . io . Closeable ; import java . io . IOException ; public interface FileListProvider extends Closeable { FileList . Reader openReader ( ) throws IOException ; FileList . Writer openWriter ( boolean compress ) throws IOException ; void discardReader ( ) throws IOException ; void discardWriter ( ) throws IOException ; void waitForComplete ( ) throws IOException , InterruptedException ; } package com . asakusafw . bulkloader . transfer ; package com . asakusafw . bulkloader . transfer ; import java . io . Closeable ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Properties ; import java . util . zip . ZipEntry ; import java . util . zip . ZipInputStream ; import java . util . zip . ZipOutputStream ; import org . apache . commons . io . input . CountingInputStream ; import org . apache . commons . io . output . CountingOutputStream ; import org . apache . hadoop . io . InputBuffer ; import org . apache . hadoop . io . OutputBuffer ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . io . util . ZipEntryInputStream ; import com . asakusafw . runtime . io . util . ZipEntryOutputStream ; public final class FileList { static final Log LOG = new Log ( FileList . class ) ; static final String FIRST_ENTRY_NAME = "" ; static final String LAST_ENTRY_NAME = "" ; public static FileProtocol content ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return new FileProtocol ( FileProtocol . Kind . CONTENT , name , null ) ; } public static FileList . Reader createReader ( InputStream input ) throws IOException { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debugMessage ( "" ) ; return new Reader ( input ) ; } public static FileList . Writer createWriter ( OutputStream output , boolean compress ) throws IOException { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debugMessage ( "" ) ; return new Writer ( output , compress ) ; } private FileList ( ) { return ; } public static class Reader implements Closeable { private final CountingInputStream counter ; private final ZipInputStream input ; private FileProtocol current ; private final InputBuffer buffer = new InputBuffer ( ) ; private boolean sawNext ; private boolean sawEof ; Reader ( InputStream input ) throws IOException { assert input != null ; this . counter = new CountingInputStream ( input ) ; this . input = new ZipInputStream ( counter ) ; ZipEntry first = this . input . getNextEntry ( ) ; if ( first == null || first . getName ( ) . equals ( FIRST_ENTRY_NAME ) == false ) { throw new IOException ( "" ) ; } } public boolean next ( ) throws IOException { while ( sawEof == false ) { ZipEntry entry = input . getNextEntry ( ) ; if ( entry == null ) { throw new IOException ( "" ) ; } LOG . debugMessage ( "" , entry . getName ( ) ) ; if ( entry . getName ( ) . equals ( LAST_ENTRY_NAME ) ) { sawEof = true ; sawNext = false ; consume ( ) ; return false ; } if ( entry . isDirectory ( ) ) { continue ; } LOG . debugMessage ( "" , entry . getName ( ) ) ; restoreExtra ( entry ) ; sawNext = true ; return true ; } return false ; } private void consume ( ) throws IOException { byte [ ] buf = new byte [ ] ; int rest = ; while ( true ) { int read = counter . read ( buf ) ; if ( read < ) { break ; } rest += read ; } LOG . debugMessage ( "" , rest ) ; } private void restoreExtra ( ZipEntry entry ) throws IOException { assert entry != null ; byte [ ] extra = entry . getExtra ( ) ; if ( extra == null ) { throw new IOException ( MessageFormat . format ( "" , entry . getName ( ) ) ) ; } buffer . reset ( extra , extra . length ) ; try { Properties properties = new Properties ( ) ; properties . load ( buffer ) ; current = FileProtocol . loadFrom ( properties ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , entry . getName ( ) ) , e ) ; } } public FileProtocol getCurrentProtocol ( ) throws IOException { checkCurrent ( ) ; return current ; } public InputStream openContent ( ) throws IOException { checkCurrent ( ) ; return new ZipEntryInputStream ( input ) ; } private void checkCurrent ( ) throws IOException { if ( sawNext == false ) { throw new IOException ( "" ) ; } } public long getByteCount ( ) { return counter . getByteCount ( ) ; } @ Override public void close ( ) throws IOException { LOG . debugMessage ( "" ) ; sawNext = false ; input . close ( ) ; } } public static class Writer implements Closeable { private final CountingOutputStream counter ; private final ZipOutputStream output ; private final OutputBuffer buffer = new OutputBuffer ( ) ; private boolean closed = false ; Writer ( OutputStream output , boolean compress ) throws IOException { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . counter = new CountingOutputStream ( output ) ; this . output = new ZipOutputStream ( counter ) ; this . output . setMethod ( ZipOutputStream . DEFLATED ) ; if ( compress == false ) { this . output . setLevel ( ) ; } this . output . putNextEntry ( new ZipEntry ( FIRST_ENTRY_NAME ) ) ; this . output . closeEntry ( ) ; } public OutputStream openNext ( FileProtocol protocol ) throws IOException { if ( protocol == null ) { throw new IllegalArgumentException ( "" ) ; } ZipEntry entry = createEntryFromProtocol ( protocol ) ; LOG . debugMessage ( "" , entry . getName ( ) ) ; output . putNextEntry ( entry ) ; return new ZipEntryOutputStream ( output ) ; } private ZipEntry createEntryFromProtocol ( FileProtocol protocol ) throws IOException { assert protocol != null ; Properties properties = new Properties ( ) ; protocol . storeTo ( properties ) ; buffer . reset ( ) ; properties . store ( buffer , protocol . getLocation ( ) ) ; ZipEntry entry = new ZipEntry ( protocol . getLocation ( ) ) ; entry . setExtra ( Arrays . copyOfRange ( buffer . getData ( ) , , buffer . getLength ( ) ) ) ; return entry ; } public long getByteCount ( ) { return counter . getByteCount ( ) ; } @ Override public void close ( ) throws IOException { if ( closed == false ) { LOG . debugMessage ( "" ) ; output . putNextEntry ( new ZipEntry ( LAST_ENTRY_NAME ) ) ; output . closeEntry ( ) ; output . close ( ) ; } closed = true ; } } } package com . asakusafw . bulkloader . importer ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileCompType ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . bulkloader . transfer . OpenSshFileListProvider ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class ImportFileSend { static final Log LOG = new Log ( ImportFileSend . class ) ; public boolean sendImportFile ( ImportBean bean ) { String strCompType = ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_FILE_COMP_TYPE ) ; FileCompType compType = FileCompType . find ( strCompType ) ; FileListProvider provider = null ; FileList . Writer writer = null ; long totalStartTime = System . currentTimeMillis ( ) ; try { provider = openFileList ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; provider . discardReader ( ) ; writer = provider . openWriter ( compType == FileCompType . DEFLATED ) ; List < String > list = arrangeSendOrder ( bean ) ; for ( String tableName : list ) { long tableStartTime = System . currentTimeMillis ( ) ; ImportTargetTableBean targetTable = bean . getTargetTable ( tableName ) ; LOG . info ( "" , tableName , targetTable . getImportFile ( ) . getAbsolutePath ( ) , compType . getSymbol ( ) ) ; long dumpFileSize = sendTableFile ( writer , tableName , targetTable ) ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , tableName , dumpFileSize , System . currentTimeMillis ( ) - tableStartTime ) ; LOG . info ( "" , tableName , targetTable . getImportFile ( ) . getAbsolutePath ( ) , compType . getSymbol ( ) ) ; } writer . close ( ) ; provider . waitForComplete ( ) ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , writer . getByteCount ( ) , System . currentTimeMillis ( ) - totalStartTime ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return false ; } catch ( Exception e ) { LOG . error ( e , "" ) ; return false ; } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( IOException ignored ) { ignored . printStackTrace ( ) ; } } if ( provider != null ) { try { provider . close ( ) ; } catch ( IOException ignored ) { ignored . printStackTrace ( ) ; } } } return true ; } private List < String > arrangeSendOrder ( ImportBean bean ) { assert bean != null ; final Map < String , ImportTargetTableBean > tables = new HashMap < String , ImportTargetTableBean > ( ) ; final Map < String , Long > sizes = new HashMap < String , Long > ( ) ; List < String > tableNames = new ArrayList < String > ( bean . getImportTargetTableList ( ) ) ; for ( String tableName : tableNames ) { ImportTargetTableBean tableBean = bean . getTargetTable ( tableName ) ; tables . put ( tableName , tableBean ) ; sizes . put ( tableName , tableBean . getImportFile ( ) . length ( ) ) ; } Collections . sort ( tableNames , new Comparator < String > ( ) { @ Override public int compare ( String o1 , String o2 ) { ImportTargetTableBean t1 = tables . get ( o1 ) ; ImportTargetTableBean t2 = tables . get ( o2 ) ; if ( t1 . getCacheId ( ) != null && t2 . getCacheId ( ) == null ) { return - ; } else if ( t1 . getCacheId ( ) == null && t2 . getCacheId ( ) != null ) { return + ; } long s1 = sizes . get ( o1 ) ; long s2 = sizes . get ( o2 ) ; if ( s1 > s2 ) { return - ; } else if ( s1 < s2 ) { return + ; } return o1 . compareTo ( o2 ) ; } } ) ; return tableNames ; } private long sendTableFile ( FileList . Writer writer , String tableName , ImportTargetTableBean targetTable ) throws BulkLoaderSystemException { assert writer != null ; assert tableName != null ; assert targetTable != null ; File localFile = targetTable . getImportFile ( ) ; int buffSize = Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_FILE_COMP_BUFSIZE ) ) ; byte [ ] buf = new byte [ buffSize ] ; long dumpFileSize = ; try { InputStream input = new FileInputStream ( localFile ) ; try { FileProtocol protocol = targetTable . getImportProtocol ( ) ; assert protocol != null ; OutputStream output = writer . openNext ( protocol ) ; try { while ( true ) { int read = input . read ( buf ) ; if ( read < ) { break ; } dumpFileSize += read ; output . write ( buf , , read ) ; } } finally { output . close ( ) ; } } finally { input . close ( ) ; } } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , MessageFormat . format ( "" , tableName , localFile . getPath ( ) ) ) ; } return dumpFileSize ; } protected FileListProvider openFileList ( String targetName , String batchId , String jobflowId , String executionId ) throws IOException { if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( jobflowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } String sshPath = ConfigurationLoader . getProperty ( Constants . PROP_KEY_SSH_PATH ) ; String hostName = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAMENODE_HOST ) ; String userName = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAMENODE_USER ) ; String scriptPath = ConfigurationLoader . getRemoteScriptPath ( Constants . PATH_REMOTE_EXTRACTOR ) ; String variableTable = Constants . createVariableTable ( ) . toSerialString ( ) ; List < String > command = new ArrayList < String > ( ) ; command . add ( scriptPath ) ; command . add ( targetName ) ; command . add ( batchId ) ; command . add ( jobflowId ) ; command . add ( executionId ) ; command . add ( variableTable ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . putAll ( ConfigurationLoader . getPropSubMap ( Constants . PROP_PREFIX_HC_ENV ) ) ; env . putAll ( RuntimeContext . get ( ) . unapply ( ) ) ; LOG . info ( "" , sshPath , hostName , userName , scriptPath , targetName , batchId , jobflowId , executionId ) ; return new OpenSshFileListProvider ( sshPath , userName , hostName , command , env ) ; } } package com . asakusafw . bulkloader . importer ; import java . sql . Connection ; import java . text . MessageFormat ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Date ; import java . util . HashSet ; import java . util . Map ; import java . util . TreeSet ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . cache . GetCacheInfoLocal ; import com . asakusafw . bulkloader . cache . LocalCacheInfo ; import com . asakusafw . bulkloader . cache . LocalCacheInfoRepository ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderReRunnableException ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class ImportProtocolDecide { static final Log LOG = new Log ( ImportProtocolDecide . class ) ; public void execute ( ImportBean bean ) throws BulkLoaderSystemException , BulkLoaderReRunnableException { if ( bean == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; boolean findCache = false ; for ( String tableName : bean . getImportTargetTableList ( ) ) { ImportTargetTableBean table = bean . getTargetTable ( tableName ) ; if ( table . getCacheId ( ) == null ) { setContentProtocol ( tableName , table ) ; } else { findCache = true ; } } if ( findCache == false ) { LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } else { prepareForCache ( bean ) ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } public void cleanUpForRetry ( ImportBean bean ) throws BulkLoaderSystemException { if ( bean == null ) { throw new IllegalArgumentException ( "" ) ; } boolean findCache = false ; for ( String tableName : bean . getImportTargetTableList ( ) ) { ImportTargetTableBean table = bean . getTargetTable ( tableName ) ; if ( table . getCacheId ( ) != null ) { findCache = true ; } } if ( findCache == false ) { return ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; Connection connection = DBConnection . getConnection ( ) ; LocalCacheInfoRepository repository = new LocalCacheInfoRepository ( connection ) ; try { repository . releaseLock ( bean . getExecutionId ( ) ) ; } finally { DBConnection . closeConn ( connection ) ; } } private void prepareForCache ( ImportBean bean ) throws BulkLoaderSystemException , BulkLoaderReRunnableException { assert bean != null ; boolean succeed = false ; Connection connection = DBConnection . getConnection ( ) ; LocalCacheInfoRepository repository = new LocalCacheInfoRepository ( connection ) ; try { LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; acquireCacheLock ( bean , repository ) ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; Map < String , CacheInfo > map = collectRemoteCacheInfo ( bean ) ; for ( String tableName : bean . getImportTargetTableList ( ) ) { ImportTargetTableBean tableInfo = bean . getTargetTable ( tableName ) ; String cacheId = tableInfo . getCacheId ( ) ; if ( cacheId == null ) { assert tableInfo . getImportProtocol ( ) != null ; continue ; } CacheInfo currentRemoteInfo = map . get ( tableInfo . getDfsFilePath ( ) ) ; Calendar startTimestamp = computeStartTimestamp ( currentRemoteInfo , repository , tableName , tableInfo ) ; tableInfo . setStartTimestamp ( startTimestamp ) ; LocalCacheInfo nextLocalInfo = new LocalCacheInfo ( cacheId , null , startTimestamp , tableName , tableInfo . getDfsFilePath ( ) ) ; ThunderGateCacheSupport model = createDataModelObject ( tableName , tableInfo ) ; Calendar nextTimestamp = repository . putCacheInfo ( nextLocalInfo ) ; CacheInfo nextRemoteInfo = new CacheInfo ( CacheInfo . FEATURE_VERSION , cacheId , nextTimestamp , tableName , tableInfo . getImportTargetColumns ( ) , model . getClass ( ) . getName ( ) , model . __tgc__DataModelVersion ( ) ) ; FileProtocol . Kind kind = startTimestamp == null ? FileProtocol . Kind . CREATE_CACHE : FileProtocol . Kind . UPDATE_CACHE ; FileProtocol protocol = new FileProtocol ( kind , tableInfo . getDfsFilePath ( ) , nextRemoteInfo ) ; tableInfo . setImportProtocol ( protocol ) ; } succeed = true ; } finally { if ( succeed == false ) { repository . releaseLock ( bean . getExecutionId ( ) ) ; } DBConnection . closeConn ( connection ) ; } } private void acquireCacheLock ( ImportBean bean , LocalCacheInfoRepository repository ) throws BulkLoaderSystemException , BulkLoaderReRunnableException { assert bean != null ; assert repository != null ; for ( String tableName : bean . getImportTargetTableList ( ) ) { ImportTargetTableBean tableInfo = bean . getTargetTable ( tableName ) ; if ( tableInfo . getCacheId ( ) == null ) { assert tableInfo . getImportProtocol ( ) != null ; continue ; } boolean locked = repository . tryLock ( bean . getExecutionId ( ) , tableInfo . getCacheId ( ) , tableName ) ; if ( locked == false ) { throw new BulkLoaderReRunnableException ( getClass ( ) , "" , tableName , tableInfo . getCacheId ( ) ) ; } } } private Calendar computeStartTimestamp ( CacheInfo remoteInfo , LocalCacheInfoRepository repository , String tableName , ImportTargetTableBean tableInfo ) throws BulkLoaderSystemException { assert repository != null ; assert tableName != null ; assert tableInfo != null ; String cacheId = tableInfo . getCacheId ( ) ; assert cacheId != null ; if ( remoteInfo == null ) { LOG . info ( "" , tableName , cacheId ) ; return null ; } if ( remoteInfo . getFeatureVersion ( ) . equals ( CacheInfo . FEATURE_VERSION ) == false ) { LOG . warn ( "" , tableName , cacheId , MessageFormat . format ( "" , CacheInfo . FEATURE_VERSION , remoteInfo . getFeatureVersion ( ) ) ) ; return null ; } if ( remoteInfo . getId ( ) . equals ( cacheId ) == false ) { LOG . warn ( "" , tableName , cacheId , MessageFormat . format ( "" , cacheId , remoteInfo . getId ( ) ) ) ; return null ; } if ( remoteInfo . getTableName ( ) . equals ( tableName ) == false ) { LOG . warn ( "" , tableName , cacheId , MessageFormat . format ( "" , tableName , remoteInfo . getTableName ( ) ) ) ; return null ; } if ( remoteInfo . getColumnNames ( ) . equals ( new HashSet < String > ( tableInfo . getImportTargetColumns ( ) ) ) == false ) { LOG . warn ( "" , tableName , cacheId , MessageFormat . format ( "" , new TreeSet < String > ( tableInfo . getImportTargetColumns ( ) ) , remoteInfo . getColumnNames ( ) ) ) ; return null ; } ThunderGateCacheSupport model = createDataModelObject ( tableName , tableInfo ) ; if ( remoteInfo . getModelClassName ( ) . equals ( model . getClass ( ) . getName ( ) ) == false ) { LOG . warn ( "" , tableName , cacheId , MessageFormat . format ( "" , model . getClass ( ) . getName ( ) , remoteInfo . getModelClassName ( ) ) ) ; return null ; } if ( remoteInfo . getModelClassVersion ( ) != model . __tgc__DataModelVersion ( ) ) { LOG . warn ( "" , tableName , cacheId , MessageFormat . format ( "" , model . __tgc__DataModelVersion ( ) , remoteInfo . getModelClassVersion ( ) ) ) ; return null ; } LocalCacheInfo local = repository . getCacheInfo ( remoteInfo . getId ( ) ) ; if ( local == null ) { LOG . info ( "" , tableName , cacheId ) ; return null ; } Calendar timestamp = remoteInfo . getTimestamp ( ) ; Calendar localTimestamp = local . getLocalTimestamp ( ) ; if ( localTimestamp == null || timestamp . compareTo ( localTimestamp ) > ) { LOG . warn ( "" , tableName , cacheId , MessageFormat . format ( "" , format ( localTimestamp ) , format ( timestamp ) ) ) ; return null ; } Calendar createdTimestamp = local . getRemoteTimestamp ( ) ; if ( createdTimestamp != null && timestamp . compareTo ( createdTimestamp ) < ) { LOG . warn ( "" , tableName , cacheId , MessageFormat . format ( "" , format ( createdTimestamp ) , format ( timestamp ) ) ) ; return null ; } LOG . info ( "" , tableName , cacheId , format ( timestamp ) ) ; return timestamp ; } private String format ( Calendar calendar ) { SimpleDateFormat formatter = new SimpleDateFormat ( "" ) ; if ( calendar == null ) { return formatter . format ( new Date ( ) ) ; } else { return formatter . format ( calendar . getTime ( ) ) ; } } private ThunderGateCacheSupport createDataModelObject ( String tableName , ImportTargetTableBean tableInfo ) throws BulkLoaderSystemException { assert tableName != null ; assert tableInfo != null ; try { return tableInfo . getImportTargetType ( ) . asSubclass ( ThunderGateCacheSupport . class ) . newInstance ( ) ; } catch ( Exception e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , tableName , tableInfo . getCacheId ( ) , tableInfo . getImportTargetType ( ) . getName ( ) ) ; } } private void setContentProtocol ( String tableName , ImportTargetTableBean table ) { assert tableName != null ; assert table != null ; String remoteLocation = FileNameUtil . createSendImportFileName ( tableName ) ; FileProtocol protocol = new FileProtocol ( FileProtocol . Kind . CONTENT , remoteLocation , null ) ; table . setImportProtocol ( protocol ) ; } protected Map < String , CacheInfo > collectRemoteCacheInfo ( ImportBean bean ) throws BulkLoaderSystemException { if ( bean == null ) { throw new IllegalArgumentException ( "" ) ; } GetCacheInfoLocal client = new GetCacheInfoLocal ( ) ; return client . get ( bean ) ; } } package com . asakusafw . bulkloader . importer ; import java . io . File ; import java . io . IOException ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . SQLException ; import java . sql . Timestamp ; import java . text . MessageFormat ; import java . util . Calendar ; import java . util . List ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . common . ImportTableLockType ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class ImportFileCreate { static final Log LOG = new Log ( ImportFileCreate . class ) ; private static final String [ ] EMPTY = new String [ ] ; public boolean createImportFile ( ImportBean bean , String jobflowSid ) { Connection conn = null ; try { conn = DBConnection . getConnection ( ) ; List < String > list = bean . getImportTargetTableList ( ) ; for ( String tableName : list ) { ImportTargetTableBean targetTable = bean . getTargetTable ( tableName ) ; ImportTableLockType lockType = targetTable . getLockType ( ) ; File importFile = FileNameUtil . createImportFilePath ( bean . getTargetName ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , tableName ) ; LOG . info ( "" , tableName , lockType , importFile . getAbsolutePath ( ) ) ; if ( importFile . exists ( ) ) { if ( ! importFile . delete ( ) ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , importFile . getName ( ) ) ; } } if ( ImportTableLockType . TABLE . equals ( lockType ) ) { createFileWithCondition ( conn , tableName , targetTable , importFile ) ; } else if ( ImportTableLockType . RECORD . equals ( lockType ) ) { createFileWithJobFlowSid ( conn , tableName , targetTable , jobflowSid , importFile ) ; } else if ( ImportTableLockType . NONE . equals ( lockType ) ) { createFileWithCondition ( conn , tableName , targetTable , importFile ) ; } if ( ! importFile . exists ( ) ) { try { if ( ! importFile . createNewFile ( ) ) { throw new BulkLoaderSystemException ( getClass ( ) , "" ) ; } LOG . info ( "" , tableName , lockType , importFile . getAbsolutePath ( ) ) ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( getClass ( ) , "" ) ; } } else { LOG . info ( "" , tableName , lockType , importFile . getAbsolutePath ( ) ) ; } targetTable . setImportFile ( importFile ) ; } return true ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return false ; } finally { DBConnection . closeConn ( conn ) ; } } private void createFileWithJobFlowSid ( Connection conn , String tableName , ImportTargetTableBean tableInfo , String jobflowSid , File importFileName ) throws BulkLoaderSystemException { String sql = createSQLWithJobFlowSid ( tableName , tableInfo , importFileName ) ; PreparedStatement stmt = null ; String [ ] parameters = EMPTY ; LOG . info ( "" , sql , jobflowSid ) ; try { stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , jobflowSid ) ; if ( tableInfo . getStartTimestamp ( ) != null ) { Calendar beginning = tableInfo . getStartTimestamp ( ) ; Timestamp timestamp = new Timestamp ( beginning . getTimeInMillis ( ) ) ; LOG . info ( "" , tableName , tableInfo . getCacheId ( ) , timestamp ) ; stmt . setTimestamp ( , timestamp , beginning ) ; parameters = new String [ ] { jobflowSid , String . valueOf ( timestamp ) } ; } else { parameters = new String [ ] { jobflowSid } ; } DBConnection . executeQuery ( stmt , sql , parameters ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , parameters ) ; } finally { DBConnection . closePs ( stmt ) ; } } private String createSQLWithJobFlowSid ( String tableName , ImportTargetTableBean tableInfo , File importFileName ) throws BulkLoaderSystemException { String rlTableName = DBAccessUtil . createRecordLockTableName ( tableName ) ; String baseSearchCondition = MessageFormat . format ( "" , tableName , rlTableName , Constants . getSidColumnName ( ) ) ; String searchCondition = resolveSearchCondition ( tableName , tableInfo , baseSearchCondition ) ; StringBuilder sql = new StringBuilder ( ) ; sql . append ( "" ) ; sql . append ( DBAccessUtil . joinColumnArray ( tableInfo . getImportTargetColumns ( ) ) ) ; sql . append ( "" ) ; sql . append ( tableName ) ; sql . append ( "" ) ; sql . append ( searchCondition ) ; sql . append ( "" ) ; sql . append ( "" ) ; sql . append ( importFileName . getAbsolutePath ( ) . replace ( File . separatorChar , '' ) ) ; sql . append ( "" ) ; sql . append ( DBAccessUtil . getTSVFileFormat ( ) ) ; return sql . toString ( ) ; } private void createFileWithCondition ( Connection conn , String tableName , ImportTargetTableBean tableInfo , File importFileName ) throws BulkLoaderSystemException { String sql = createSQLWithCondition ( tableName , tableInfo , importFileName ) ; PreparedStatement stmt = null ; LOG . info ( "" , sql ) ; String [ ] parameters = EMPTY ; try { stmt = conn . prepareStatement ( sql ) ; if ( tableInfo . getStartTimestamp ( ) != null ) { Calendar beginning = tableInfo . getStartTimestamp ( ) ; Timestamp timestamp = new Timestamp ( beginning . getTimeInMillis ( ) ) ; LOG . info ( "" , tableName , tableInfo . getCacheId ( ) , timestamp ) ; stmt . setTimestamp ( , timestamp , beginning ) ; parameters = new String [ ] { String . valueOf ( timestamp ) } ; } DBConnection . executeQuery ( stmt , sql , parameters ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , parameters ) ; } finally { DBConnection . closePs ( stmt ) ; } } private String createSQLWithCondition ( String tableName , ImportTargetTableBean tableInfo , File importFileName ) throws BulkLoaderSystemException { StringBuilder sql = new StringBuilder ( ) ; sql . append ( "" ) ; sql . append ( DBAccessUtil . joinColumnArray ( tableInfo . getImportTargetColumns ( ) ) ) ; sql . append ( "" ) ; sql . append ( tableName ) ; String searchCondition = resolveSearchCondition ( tableName , tableInfo , tableInfo . getSearchCondition ( ) ) ; if ( searchCondition != null && ! searchCondition . isEmpty ( ) ) { sql . append ( "" ) ; sql . append ( searchCondition ) ; } sql . append ( "" ) ; sql . append ( "" ) ; sql . append ( importFileName . getAbsolutePath ( ) . replace ( File . separatorChar , '' ) ) ; sql . append ( "" ) ; sql . append ( DBAccessUtil . getTSVFileFormat ( ) ) ; return sql . toString ( ) ; } private String resolveSearchCondition ( String tableName , ImportTargetTableBean tableInfo , String expression ) throws BulkLoaderSystemException { assert tableName != null ; assert tableInfo != null ; String original = expression ; if ( original == null || original . trim ( ) . isEmpty ( ) ) { original = null ; } if ( tableInfo . getStartTimestamp ( ) == null ) { return original ; } else { ThunderGateCacheSupport support ; try { support = tableInfo . getImportTargetType ( ) . asSubclass ( ThunderGateCacheSupport . class ) . newInstance ( ) ; } catch ( Exception e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , tableName , tableInfo . getCacheId ( ) , tableInfo . getImportTargetType ( ) . getName ( ) ) ; } String timestampColumn = support . __tgc__TimestampColumn ( ) ; if ( original == null ) { return MessageFormat . format ( "" , tableName , timestampColumn ) ; } else { return MessageFormat . format ( "" , original , tableName , timestampColumn ) ; } } } } package com . asakusafw . bulkloader . importer ; import java . io . File ; import java . util . List ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . log . Log ; public class ImportFileDelete { static final Log LOG = new Log ( ImportFileDelete . class ) ; public void deleteFile ( ImportBean bean ) { List < String > list = bean . getImportTargetTableList ( ) ; for ( String tableName : list ) { ImportTargetTableBean targetTable = bean . getTargetTable ( tableName ) ; File file = targetTable . getImportFile ( ) ; if ( file != null && file . exists ( ) ) { if ( ! file . delete ( ) ) { LOG . warn ( "" , file . getPath ( ) ) ; } } } } } package com . asakusafw . bulkloader . importer ; package com . asakusafw . bulkloader . importer ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . Date ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . concurrent . TimeUnit ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . ImportTableLockType ; import com . asakusafw . bulkloader . common . ImportTableLockedOperation ; import com . asakusafw . bulkloader . exception . BulkLoaderReRunnableException ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public class TargetDataLock { static final Log LOG = new Log ( TargetDataLock . class ) ; private static final String NOT_EXISTS_JOBFLOW_SID = "" ; private String jobflowSid ; public boolean lock ( ImportBean bean ) throws BulkLoaderReRunnableException { int retryCount = bean . getRetryCount ( ) ; int retryInterval = bean . getRetryInterval ( ) ; int retry = ; Connection conn = null ; try { conn = DBConnection . getConnection ( ) ; jobflowSid = checkExecutionId ( conn , bean . getExecutionId ( ) ) ; if ( ! jobflowSid . equals ( NOT_EXISTS_JOBFLOW_SID ) ) { LOG . info ( "" , bean . getTargetName ( ) , bean . getExecutionId ( ) , jobflowSid ) ; return true ; } while ( true ) { retry ++ ; try { LOG . info ( "" , bean . getTargetName ( ) , bean . getExecutionId ( ) ) ; execTran ( conn , bean ) ; DBConnection . commit ( conn ) ; LOG . info ( "" , bean . getTargetName ( ) , bean . getExecutionId ( ) ) ; return true ; } catch ( BulkLoaderReRunnableException e ) { LOG . log ( e ) ; if ( retry <= retryCount ) { try { DBConnection . rollback ( conn ) ; Thread . sleep ( TimeUnit . SECONDS . toMillis ( retryInterval ) ) ; continue ; } catch ( InterruptedException e2 ) { throw new BulkLoaderSystemException ( e2 , getClass ( ) , "" ) ; } } else { throw new BulkLoaderReRunnableException ( e , getClass ( ) , "" ) ; } } } } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; try { DBConnection . rollback ( conn ) ; } catch ( BulkLoaderSystemException e1 ) { e1 . printStackTrace ( ) ; } return false ; } finally { DBConnection . closeConn ( conn ) ; } } private void execTran ( Connection conn , ImportBean bean ) throws BulkLoaderReRunnableException , BulkLoaderSystemException { jobflowSid = insertRunningJobFlow ( conn , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , bean . getJobnetEndTime ( ) ) ; Map < String , String > tableLock ; try { tableLock = getImportTableLock ( conn , bean . getImportTargetTableList ( ) . iterator ( ) ) ; } catch ( BulkLoaderSystemException e ) { throw new BulkLoaderReRunnableException ( e . getCause ( ) , getClass ( ) , "" , "" , "" ) ; } List < String > list = bean . getImportTargetTableList ( ) ; for ( String tableName : list ) { ImportTargetTableBean targetTable = bean . getTargetTable ( tableName ) ; ImportTableLockType lockType = targetTable . getLockType ( ) ; ImportTableLockedOperation operation = targetTable . getLockedOperation ( ) ; String serchCondition = targetTable . getSearchCondition ( ) ; LOG . info ( "" , tableName , lockType , operation , serchCondition ) ; if ( ImportTableLockType . NONE . equals ( lockType ) && ImportTableLockedOperation . FORCE . equals ( operation ) ) { LOG . info ( "" , tableName ) ; continue ; } String targetSid = tableLock . get ( tableName ) ; if ( targetSid != null && ! targetSid . isEmpty ( ) ) { if ( ImportTableLockType . RECORD . equals ( lockType ) && ImportTableLockedOperation . OFF . equals ( operation ) ) { LOG . info ( "" , tableName ) ; continue ; } else { throw new BulkLoaderReRunnableException ( getClass ( ) , "" , "" , tableName ) ; } } if ( ImportTableLockType . TABLE . equals ( lockType ) ) { if ( ! checkRecordLock ( conn , tableName ) ) { throw new BulkLoaderReRunnableException ( getClass ( ) , "" , "" , tableName ) ; } else { tableLock ( conn , tableName , jobflowSid ) ; continue ; } } else if ( ImportTableLockType . RECORD . equals ( lockType ) ) { if ( ImportTableLockedOperation . OFF . equals ( operation ) ) { recordLock ( conn , tableName , serchCondition , jobflowSid ) ; continue ; } else if ( ImportTableLockedOperation . ERROR . equals ( operation ) ) { if ( ! checkRecordLock ( conn , tableName , serchCondition ) ) { throw new BulkLoaderReRunnableException ( getClass ( ) , "" , "" , tableName ) ; } else { recordLock ( conn , tableName , serchCondition , jobflowSid ) ; continue ; } } } else if ( ImportTableLockType . NONE . equals ( lockType ) ) { if ( ! checkRecordLock ( conn , tableName , serchCondition ) ) { throw new BulkLoaderReRunnableException ( getClass ( ) , "" , "" , tableName ) ; } else { LOG . info ( "" , tableName ) ; continue ; } } LOG . info ( "" , tableName , lockType , operation , serchCondition ) ; } } private String checkExecutionId ( Connection conn , String executionId ) throws BulkLoaderSystemException { String sql = "" + "" + "" ; PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , executionId ) ; rs = DBConnection . executeQuery ( stmt , sql , new String [ ] { executionId } ) ; if ( rs . next ( ) ) { return rs . getString ( "" ) ; } else { return NOT_EXISTS_JOBFLOW_SID ; } } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , sql , new String [ ] { executionId } ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } } private String insertRunningJobFlow ( Connection conn , String targetName , String batchId , String jobflowId , String executionId , Date jobnetEndTime ) throws BulkLoaderSystemException { String insertSql = "" + "" + "" ; String selectSql = "" ; PreparedStatement stmt = null ; ResultSet rs = null ; LOG . info ( "" , insertSql , batchId , jobflowId , targetName , executionId , jobnetEndTime ) ; try { try { stmt = conn . prepareStatement ( insertSql ) ; stmt . setString ( , batchId ) ; stmt . setString ( , jobflowId ) ; stmt . setString ( , targetName ) ; stmt . setString ( , executionId ) ; stmt . setTimestamp ( , new java . sql . Timestamp ( jobnetEndTime . getTime ( ) ) ) ; DBConnection . executeUpdate ( stmt , insertSql , new String [ ] { batchId , jobflowId , targetName , executionId } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , insertSql , new String [ ] { batchId , jobflowId , executionId , jobnetEndTime . toString ( ) } ) ; } try { stmt = conn . prepareStatement ( selectSql ) ; rs = DBConnection . executeQuery ( stmt , selectSql , new String [ ] ) ; rs . next ( ) ; return rs . getString ( ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , selectSql , new String [ ] ) ; } } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } } private Map < String , String > getImportTableLock ( Connection conn , Iterator < String > importTargetTable ) throws BulkLoaderSystemException { String selectSql1 = "" + "" + "" ; String selectSql2 = "" ; StringBuilder selectSql = new StringBuilder ( selectSql1 ) ; PreparedStatement stmt = null ; ResultSet rs = null ; int tableCount = ; try { while ( importTargetTable . hasNext ( ) ) { selectSql . append ( "" ) ; selectSql . append ( importTargetTable . next ( ) ) ; selectSql . append ( "" ) ; tableCount ++ ; if ( importTargetTable . hasNext ( ) ) { selectSql . append ( "" ) ; } } selectSql . append ( selectSql2 ) ; LOG . info ( "" , selectSql . toString ( ) ) ; stmt = conn . prepareStatement ( selectSql . toString ( ) ) ; rs = DBConnection . executeQuery ( stmt , selectSql . toString ( ) , new String [ ] ) ; Map < String , String > tableLockStatus = new HashMap < String , String > ( ) ; while ( rs . next ( ) ) { String key = rs . getString ( "" ) ; String value = rs . getString ( "" ) ; tableLockStatus . put ( key , value ) ; } if ( tableLockStatus . size ( ) != tableCount ) { throw new SQLException ( "" + tableCount + "" + tableLockStatus . size ( ) ) ; } return tableLockStatus ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , selectSql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } } private boolean checkRecordLock ( Connection conn , String tableName ) throws BulkLoaderSystemException { String sql = "" + "" + "" ; PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , tableName ) ; rs = DBConnection . executeQuery ( stmt , sql , new String [ ] { tableName } ) ; if ( rs . next ( ) ) { String targetJobflowSid = rs . getString ( "" ) ; return targetJobflowSid == null || targetJobflowSid . isEmpty ( ) ; } else { return true ; } } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , sql , new String [ ] { tableName } ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } } private boolean checkRecordLock ( Connection conn , String tableName , String serchCondition ) throws BulkLoaderSystemException { String rlTableName = DBAccessUtil . createRecordLockTableName ( tableName ) ; StringBuilder sql = new StringBuilder ( "" ) ; sql . append ( tableName ) ; sql . append ( "" ) ; if ( serchCondition != null && ! serchCondition . isEmpty ( ) ) { sql . append ( "" ) ; sql . append ( serchCondition ) ; sql . append ( "" ) ; sql . append ( "" ) ; } sql . append ( "" ) ; sql . append ( rlTableName ) ; sql . append ( "" ) ; sql . append ( rlTableName ) ; sql . append ( "" ) ; sql . append ( tableName ) ; sql . append ( "" ) ; PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( sql . toString ( ) ) ; rs = DBConnection . executeQuery ( stmt , sql . toString ( ) , new String [ ] ) ; boolean hasResult = rs . next ( ) ; return hasResult == false ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , sql . toString ( ) , new String [ ] ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; } } private void tableLock ( Connection conn , String tableName , String targetJobflowSid ) throws BulkLoaderSystemException { String sql = "" + "" + "" ; PreparedStatement stmt = null ; LOG . info ( "" , sql , targetJobflowSid , tableName ) ; try { stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , targetJobflowSid ) ; stmt . setString ( , tableName ) ; DBConnection . executeUpdate ( stmt , sql , new String [ ] { targetJobflowSid , tableName } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , sql , new String [ ] { targetJobflowSid , tableName } ) ; } finally { DBConnection . closePs ( stmt ) ; } } private void recordLock ( Connection conn , String tableName , String searchCondition , String targetJobflowSid ) throws BulkLoaderSystemException { String rlTableName = DBAccessUtil . createRecordLockTableName ( tableName ) ; StringBuilder sql = new StringBuilder ( "" ) ; sql . append ( rlTableName ) ; sql . append ( "" ) ; sql . append ( tableName ) ; sql . append ( "" ) ; if ( searchCondition != null && ! searchCondition . equals ( "" ) ) { sql . append ( "" ) ; sql . append ( searchCondition ) ; sql . append ( "" ) ; } sql . append ( "" ) ; sql . append ( rlTableName ) ; sql . append ( "" ) ; sql . append ( rlTableName ) ; sql . append ( "" ) ; sql . append ( tableName ) ; sql . append ( "" ) ; LOG . info ( "" , sql . toString ( ) , targetJobflowSid ) ; PreparedStatement stmt = null ; try { int count = ; try { stmt = conn . prepareStatement ( sql . toString ( ) ) ; stmt . setString ( , targetJobflowSid ) ; count = DBConnection . executeUpdate ( stmt , sql . toString ( ) , new String [ ] { targetJobflowSid } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , sql . toString ( ) , new String [ ] { targetJobflowSid } ) ; } if ( count > ) { String updateSql = null ; try { updateSql = "" ; stmt = conn . prepareStatement ( updateSql ) ; stmt . setString ( , targetJobflowSid ) ; stmt . setString ( , tableName ) ; DBConnection . executeUpdate ( stmt , updateSql , new String [ ] { targetJobflowSid , tableName } ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , this . getClass ( ) , updateSql , new String [ ] { targetJobflowSid , tableName } ) ; } } } finally { DBConnection . closePs ( stmt ) ; } } public String insertRunningJobFlow ( String targetName , String batchId , String jobflowId , String executionId , Date jobnetEndTime ) { Connection conn = null ; try { conn = DBConnection . getConnection ( ) ; jobflowSid = insertRunningJobFlow ( conn , targetName , batchId , jobflowId , executionId , jobnetEndTime ) ; DBConnection . commit ( conn ) ; return jobflowSid ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; try { DBConnection . rollback ( conn ) ; } catch ( BulkLoaderSystemException e1 ) { e1 . printStackTrace ( ) ; } return null ; } finally { DBConnection . closeConn ( conn ) ; } } public String getJobFlowSid ( ) { return jobflowSid ; } } package com . asakusafw . bulkloader . importer ; import java . sql . Connection ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . List ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBAccessUtil ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . common . ImportType ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . common . TsvDeleteType ; import com . asakusafw . bulkloader . exception . BulkLoaderReRunnableException ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class Importer { static final Log LOG = new Log ( Importer . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_DB ; public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( Importer . class . getClassLoader ( ) ) ; Importer importer = new Importer ( ) ; int result = importer . execute ( args ) ; System . exit ( result ) ; } protected int execute ( String [ ] args ) { if ( args . length != && args . length != ) { System . err . println ( "" + args . length ) ; return Constants . EXIT_CODE_ERROR ; } String importerType = args [ ] ; String targetName = args [ ] ; String batchId = args [ ] ; String jobflowId = args [ ] ; String executionId = args [ ] ; String endDate = args [ ] ; String recoveryTable = null ; if ( args . length == ) { recoveryTable = args [ ] ; } try { if ( ! BulkLoaderInitializer . initDBServer ( jobflowId , executionId , PROPERTIES , targetName ) ) { LOG . error ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } LOG . info ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; ImportBean bean = createBean ( importerType , targetName , batchId , jobflowId , executionId , endDate , recoveryTable ) ; if ( bean == null ) { LOG . error ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } if ( RuntimeContext . get ( ) . isSimulation ( ) ) { DBConnection . getConnection ( ) . close ( ) ; return Constants . EXIT_CODE_SUCCESS ; } int exitCode = importTables ( bean ) ; return exitCode ; } catch ( BulkLoaderReRunnableException e ) { LOG . log ( e ) ; return Constants . EXIT_CODE_RETRYABLE ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e ) { try { LOG . error ( e , "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e1 ) { System . err . print ( "" ) ; e1 . printStackTrace ( ) ; return Constants . EXIT_CODE_ERROR ; } } } public int importTables ( ImportBean bean ) throws BulkLoaderSystemException , BulkLoaderReRunnableException { if ( bean == null ) { throw new IllegalArgumentException ( "" ) ; } String importerType = ( bean . isPrimary ( ) ? ImportType . PRIMARY : ImportType . SECONDARY ) . toString ( ) ; String targetName = bean . getTargetName ( ) ; String batchId = bean . getBatchId ( ) ; String jobflowId = bean . getJobflowId ( ) ; String executionId = bean . getExecutionId ( ) ; Connection lockConn = null ; boolean protocolDecided = false ; try { String jobflowSid ; if ( bean . isPrimary ( ) ) { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; try { lockConn = DBConnection . getConnection ( ) ; if ( ! DBAccessUtil . getJobflowInstanceLock ( bean . getExecutionId ( ) , lockConn ) ) { LOG . error ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; } } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; LOG . error ( e , "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } ImportProtocolDecide protocolDecide = createImportProtocolDecide ( ) ; protocolDecide . execute ( bean ) ; protocolDecided = true ; TargetDataLock targetLock = createTargetDataLock ( ) ; List < String > list = bean . getImportTargetTableList ( ) ; if ( list != null && list . size ( ) > ) { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; if ( ! targetLock . lock ( bean ) ) { LOG . error ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; jobflowSid = targetLock . getJobFlowSid ( ) ; } } else { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; jobflowSid = targetLock . insertRunningJobFlow ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , bean . getJobnetEndTime ( ) ) ; if ( jobflowSid != null ) { LOG . info ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_SUCCESS ; } else { LOG . error ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } } } else { List < String > list = bean . getImportTargetTableList ( ) ; if ( list == null || list . size ( ) == ) { LOG . info ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_SUCCESS ; } else { ImportProtocolDecide protocolDecide = createImportProtocolDecide ( ) ; protocolDecide . execute ( bean ) ; jobflowSid = null ; } } LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; ImportFileCreate fileCreate = createImportFileCreate ( ) ; if ( ! fileCreate . createImportFile ( bean , jobflowSid ) ) { LOG . error ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; } LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; ImportFileSend fileSend = createImportFileSend ( ) ; if ( ! fileSend . sendImportFile ( bean ) ) { LOG . error ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } else { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; } String deleteTsv = ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMPORT_TSV_DELETE ) ; TsvDeleteType delType = TsvDeleteType . find ( deleteTsv ) ; if ( TsvDeleteType . TRUE . equals ( delType ) ) { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; ImportFileDelete fileDelete = createImportFileDelete ( ) ; fileDelete . deleteFile ( bean ) ; } else { LOG . info ( "" , importerType , targetName , batchId , jobflowId , executionId ) ; } LOG . info ( "" , new Date ( ) , importerType , targetName , batchId , jobflowId , executionId ) ; return Constants . EXIT_CODE_SUCCESS ; } catch ( BulkLoaderReRunnableException e ) { ImportProtocolDecide protocolDecide = createImportProtocolDecide ( ) ; try { if ( protocolDecided ) { protocolDecide . cleanUpForRetry ( bean ) ; } throw e ; } catch ( BulkLoaderSystemException inner ) { LOG . log ( e ) ; throw inner ; } } finally { if ( lockConn != null ) { DBAccessUtil . releaseJobflowInstanceLock ( lockConn ) ; } } } private ImportBean createBean ( String importerType , String targetName , String batchId , String jobflowId , String executionId , String strEndDate , String recoveryTable ) { ImportBean bean = new ImportBean ( ) ; ImportType importType = ImportType . find ( importerType ) ; if ( ImportType . PRIMARY . equals ( importType ) ) { bean . setPrimary ( true ) ; } else if ( ImportType . SECONDARY . equals ( importType ) ) { bean . setPrimary ( false ) ; } else { LOG . error ( "" , "" , importerType ) ; return null ; } bean . setTargetName ( targetName ) ; bean . setBatchId ( batchId ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; if ( strEndDate . length ( ) != ) { LOG . error ( "" , "" , strEndDate ) ; return null ; } SimpleDateFormat sdf = new SimpleDateFormat ( "" ) ; Date endDate = null ; try { Long . parseLong ( strEndDate ) ; endDate = sdf . parse ( strEndDate ) ; } catch ( NumberFormatException e ) { LOG . error ( e , "" , "" , strEndDate ) ; return null ; } catch ( ParseException e ) { Integer . parseInt ( strEndDate ) ; LOG . error ( e , "" , "" , strEndDate ) ; return null ; } bean . setJobnetEndTime ( endDate ) ; bean . setRetryCount ( Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_RETRY_COUNT ) ) ) ; bean . setRetryInterval ( Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_RETRY_INTERVAL ) ) ) ; JobFlowParamLoader paramLoader = createJobFlowParamLoader ( ) ; if ( ! paramLoader . loadImportParam ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . isPrimary ( ) ) ) { return null ; } bean . setTargetTable ( paramLoader . getImportTargetTables ( ) ) ; return bean ; } protected JobFlowParamLoader createJobFlowParamLoader ( ) { return new JobFlowParamLoader ( ) ; } protected ImportFileDelete createImportFileDelete ( ) { return new ImportFileDelete ( ) ; } protected ImportFileSend createImportFileSend ( ) { return new ImportFileSend ( ) ; } protected ImportFileCreate createImportFileCreate ( ) { return new ImportFileCreate ( ) ; } protected TargetDataLock createTargetDataLock ( ) { return new TargetDataLock ( ) ; } protected ImportProtocolDecide createImportProtocolDecide ( ) { return new ImportProtocolDecide ( ) ; } } package com . asakusafw . bulkloader . cache ; package com . asakusafw . bulkloader . cache ; import java . sql . Connection ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import java . util . UUID ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class GcCacheStorage { static final Log LOG = new Log ( GcCacheStorage . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_DB ; public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; if ( args . length != ) { LOG . error ( "" , Arrays . toString ( args ) ) ; System . exit ( Constants . EXIT_CODE_ERROR ) ; return ; } String targetName = args [ ] ; String executionId = UUID . randomUUID ( ) . toString ( ) ; int initExit = initialize ( targetName , executionId ) ; if ( initExit != Constants . EXIT_CODE_SUCCESS ) { System . exit ( initExit ) ; } LOG . info ( "" , targetName , executionId ) ; int exitCode = new GcCacheStorage ( ) . execute ( targetName , executionId ) ; LOG . info ( "" , targetName , executionId ) ; System . exit ( exitCode ) ; } private static int initialize ( String targetName , String executionId ) { if ( ! BulkLoaderInitializer . initDBServer ( "" , executionId , PROPERTIES , targetName ) ) { LOG . error ( "" , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } return Constants . EXIT_CODE_SUCCESS ; } public int execute ( String targetName , String executionId ) { if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } try { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; boolean succeed ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { succeed = true ; } else { succeed = execute ( repo , targetName , executionId ) ; } if ( succeed ) { LOG . info ( "" , targetName ) ; return Constants . EXIT_CODE_SUCCESS ; } else { LOG . warn ( "" , targetName ) ; return Constants . EXIT_CODE_WARNING ; } } finally { DBConnection . closeConn ( connection ) ; } } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; LOG . error ( "" , targetName ) ; return Constants . EXIT_CODE_ERROR ; } } private boolean execute ( LocalCacheInfoRepository repo , String targetName , String executionId ) throws BulkLoaderSystemException { assert repo != null ; assert targetName != null ; assert executionId != null ; LOG . info ( "" , targetName ) ; List < LocalCacheInfo > deleted = repo . listDeletedCacheInfo ( ) ; if ( deleted . isEmpty ( ) ) { LOG . info ( "" , targetName ) ; return true ; } boolean green = true ; try { LOG . info ( "" , targetName , executionId ) ; List < LocalCacheInfo > locked = new ArrayList < LocalCacheInfo > ( ) ; for ( LocalCacheInfo info : deleted ) { LOG . debugMessage ( "" , info . getId ( ) , targetName , executionId ) ; if ( repo . tryLock ( executionId , info . getId ( ) , info . getTableName ( ) ) ) { locked . add ( info ) ; } else { LOG . info ( "" , targetName , info . getId ( ) , info . getTableName ( ) ) ; green = false ; } } DeleteCacheStorageLocal client = getClient ( ) ; Map < String , FileProtocol . Kind > results = client . delete ( locked , targetName ) ; int count = ; for ( LocalCacheInfo info : locked ) { FileProtocol . Kind result = results . get ( info . getPath ( ) ) ; if ( result == FileProtocol . Kind . RESPONSE_DELETED || result == FileProtocol . Kind . RESPONSE_NOT_FOUND ) { LOG . info ( "" , targetName , info . getId ( ) , info . getTableName ( ) ) ; repo . deleteCacheInfoCompletely ( info . getId ( ) ) ; count ++ ; } else { LOG . info ( "" , targetName , info . getId ( ) , info . getTableName ( ) , info . getPath ( ) ) ; green = false ; } } LOG . info ( "" , targetName , count ) ; } finally { LOG . info ( "" , targetName , executionId ) ; repo . releaseLock ( executionId ) ; } return green ; } protected DeleteCacheStorageLocal getClient ( ) { return new DeleteCacheStorageLocal ( ) ; } } package com . asakusafw . bulkloader . cache ; import java . sql . Connection ; import java . util . Arrays ; import java . util . List ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class DeleteCacheInfo { static final Log LOG = new Log ( DeleteCacheInfo . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_DB ; public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; if ( args . length < ) { LOG . error ( "" , "" , Arrays . toString ( args ) ) ; System . exit ( Constants . EXIT_CODE_ERROR ) ; return ; } String subCommandName = args [ ] ; SubCommand subCommand = SubCommand . find ( subCommandName ) ; if ( subCommand == null ) { LOG . error ( "" , "" , Arrays . toString ( args ) ) ; System . exit ( Constants . EXIT_CODE_ERROR ) ; return ; } String targetName = args [ ] ; if ( initialize ( subCommand , targetName ) == false ) { System . exit ( Constants . EXIT_CODE_ERROR ) ; } List < String > subArguments = Arrays . asList ( args ) . subList ( , args . length ) ; int exitCode = new DeleteCacheInfo ( ) . execute ( subCommand , targetName , subArguments ) ; System . exit ( exitCode ) ; } private static boolean initialize ( SubCommand subCommand , String targetName ) { if ( ! BulkLoaderInitializer . initDBServer ( "" , subCommand . name ( ) , PROPERTIES , targetName ) ) { LOG . error ( "" , targetName ) ; return false ; } return true ; } public int execute ( SubCommand subCommand , String targetName , List < String > subArguments ) { if ( subCommand == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( subArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( subCommand . arity != subArguments . size ( ) ) { LOG . error ( "" , "" , subArguments ) ; return Constants . EXIT_CODE_ERROR ; } try { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; if ( subCommand == SubCommand . CACHE ) { String cacheId = subArguments . get ( ) ; LOG . info ( "" , targetName , cacheId ) ; boolean deleted ; if ( RuntimeContext . get ( ) . canExecute ( repo ) ) { deleted = repo . deleteCacheInfo ( cacheId ) ; } else { deleted = true ; } if ( deleted ) { LOG . info ( "" , targetName , cacheId ) ; } else { LOG . info ( "" , targetName , cacheId ) ; } } else if ( subCommand == SubCommand . TABLE ) { String tableName = subArguments . get ( ) ; LOG . info ( "" , targetName , tableName ) ; int deleted ; if ( RuntimeContext . get ( ) . canExecute ( repo ) ) { deleted = repo . deleteTableCacheInfo ( tableName ) ; } else { deleted = ; } if ( deleted > ) { LOG . info ( "" , targetName , tableName , deleted ) ; } else { LOG . info ( "" , targetName , tableName ) ; } } else if ( subCommand == SubCommand . ALL ) { LOG . info ( "" , targetName ) ; if ( RuntimeContext . get ( ) . canExecute ( repo ) ) { repo . deleteAllCacheInfo ( ) ; } LOG . info ( "" , targetName ) ; } else { throw new AssertionError ( subCommand ) ; } } finally { DBConnection . closeConn ( connection ) ; } return Constants . EXIT_CODE_SUCCESS ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return Constants . EXIT_CODE_ERROR ; } } public enum SubCommand { CACHE ( ) , TABLE ( ) , ALL ( ) , ; public final int arity ; final String symbol ; private SubCommand ( int arity ) { this . arity = arity ; this . symbol = name ( ) . toLowerCase ( ) ; } static SubCommand find ( String name ) { assert name != null ; for ( SubCommand kind : values ( ) ) { if ( kind . symbol . equals ( name ) ) { return kind ; } } return null ; } } } package com . asakusafw . bulkloader . cache ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . concurrent . Callable ; import java . util . concurrent . CancellationException ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . ThreadFactory ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import java . util . concurrent . atomic . AtomicInteger ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . bulkloader . transfer . OpenSshFileListProvider ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; public class GetCacheInfoLocal { static final Log LOG = new Log ( GetCacheInfoLocal . class ) ; private final ExecutorService executor = Executors . newCachedThreadPool ( new ThreadFactory ( ) { final AtomicInteger counter = new AtomicInteger ( ) ; @ Override public Thread newThread ( Runnable r ) { Thread t = new Thread ( r ) ; t . setDaemon ( true ) ; t . setName ( String . format ( "" , counter . incrementAndGet ( ) ) ) ; return t ; } } ) ; public Map < String , CacheInfo > get ( ImportBean bean ) throws BulkLoaderSystemException { if ( bean == null ) { throw new IllegalArgumentException ( "" ) ; } if ( hasCacheUser ( bean ) == false ) { return Collections . emptyMap ( ) ; } LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; FileListProvider provider = null ; try { provider = openFileList ( bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; Future < Void > upstream = submitUpstream ( bean , provider ) ; Future < Map < String , CacheInfo > > downstream = submitDownstream ( provider ) ; Map < String , CacheInfo > result ; while ( true ) { try { if ( upstream . isDone ( ) ) { upstream . get ( ) ; } result = downstream . get ( , TimeUnit . SECONDS ) ; break ; } catch ( TimeoutException e ) { } catch ( CancellationException e ) { upstream . cancel ( true ) ; downstream . cancel ( true ) ; throw new IOException ( "" , e ) ; } catch ( ExecutionException e ) { upstream . cancel ( true ) ; downstream . cancel ( true ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof Error ) { throw ( Error ) cause ; } else if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else { throw new AssertionError ( cause ) ; } } } provider . waitForComplete ( ) ; LOG . info ( "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) , result . size ( ) ) ; return result ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } catch ( InterruptedException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , bean . getTargetName ( ) , bean . getBatchId ( ) , bean . getJobflowId ( ) , bean . getExecutionId ( ) ) ; } finally { if ( provider != null ) { try { provider . close ( ) ; } catch ( IOException ignored ) { ignored . printStackTrace ( ) ; } } } } private boolean hasCacheUser ( ImportBean bean ) { assert bean != null ; for ( String tableName : bean . getImportTargetTableList ( ) ) { ImportTargetTableBean table = bean . getTargetTable ( tableName ) ; if ( table . getCacheId ( ) != null ) { return true ; } } return false ; } private Future < Void > submitUpstream ( final ImportBean bean , final FileListProvider provider ) { return executor . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws IOException { FileList . Writer writer = provider . openWriter ( false ) ; try { for ( String tableName : bean . getImportTargetTableList ( ) ) { ImportTargetTableBean table = bean . getTargetTable ( tableName ) ; if ( table . getCacheId ( ) == null || table . getDfsFilePath ( ) == null ) { continue ; } FileProtocol protocol = new FileProtocol ( FileProtocol . Kind . GET_CACHE_INFO , table . getDfsFilePath ( ) , null ) ; writer . openNext ( protocol ) . close ( ) ; } } finally { writer . close ( ) ; } return null ; } } ) ; } private Future < Map < String , CacheInfo > > submitDownstream ( final FileListProvider provider ) { assert provider != null ; return executor . submit ( new Callable < Map < String , CacheInfo > > ( ) { @ Override public Map < String , CacheInfo > call ( ) throws IOException { Map < String , CacheInfo > results = new HashMap < String , CacheInfo > ( ) ; FileList . Reader reader = provider . openReader ( ) ; try { while ( reader . next ( ) ) { FileProtocol protocol = reader . getCurrentProtocol ( ) ; reader . openContent ( ) . close ( ) ; if ( protocol . getKind ( ) == FileProtocol . Kind . RESPONSE_CACHE_INFO ) { assert protocol . getInfo ( ) != null ; results . put ( protocol . getLocation ( ) , protocol . getInfo ( ) ) ; } else if ( protocol . getKind ( ) != FileProtocol . Kind . RESPONSE_NOT_FOUND && protocol . getKind ( ) != FileProtocol . Kind . RESPONSE_ERROR ) { throw new IOException ( MessageFormat . format ( "" , protocol ) ) ; } } } finally { reader . close ( ) ; } return results ; } } ) ; } protected FileListProvider openFileList ( String targetName , String batchId , String jobflowId , String executionId ) throws IOException { if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( batchId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( jobflowId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } String sshPath = ConfigurationLoader . getProperty ( Constants . PROP_KEY_SSH_PATH ) ; String hostName = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAMENODE_HOST ) ; String userName = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAMENODE_USER ) ; String scriptPath = ConfigurationLoader . getRemoteScriptPath ( Constants . PATH_REMOTE_CACHE_INFO ) ; List < String > command = new ArrayList < String > ( ) ; command . add ( scriptPath ) ; command . add ( targetName ) ; command . add ( batchId ) ; command . add ( jobflowId ) ; command . add ( executionId ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . putAll ( ConfigurationLoader . getPropSubMap ( Constants . PROP_PREFIX_HC_ENV ) ) ; env . putAll ( RuntimeContext . get ( ) . unapply ( ) ) ; LOG . info ( "" , sshPath , hostName , userName , scriptPath , targetName , batchId , jobflowId , executionId ) ; return new OpenSshFileListProvider ( sshPath , userName , hostName , command , env ) ; } } package com . asakusafw . bulkloader . cache ; import java . sql . Connection ; import java . util . Arrays ; import java . util . List ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class ReleaseCacheLock { static final Log LOG = new Log ( ReleaseCacheLock . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_DB ; public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; if ( args . length != && args . length != ) { LOG . error ( "" , Arrays . toString ( args ) ) ; System . exit ( Constants . EXIT_CODE_ERROR ) ; return ; } String targetName = args [ ] ; String executionId = args . length == ? args [ ] : null ; int initExit = initialize ( targetName , executionId ) ; if ( initExit != Constants . EXIT_CODE_SUCCESS ) { System . exit ( initExit ) ; } LOG . info ( "" , targetName , executionId ) ; int exitCode = new ReleaseCacheLock ( ) . execute ( targetName , executionId ) ; LOG . info ( "" , targetName , executionId ) ; System . exit ( exitCode ) ; } private static int initialize ( String targetName , String executionId ) { if ( ! BulkLoaderInitializer . initDBServer ( "" , executionId , PROPERTIES , targetName ) ) { LOG . error ( "" , targetName , executionId ) ; return Constants . EXIT_CODE_ERROR ; } return Constants . EXIT_CODE_SUCCESS ; } public int execute ( String targetName , String executionId ) { try { Connection connection = DBConnection . getConnection ( ) ; try { LocalCacheInfoRepository repo = new LocalCacheInfoRepository ( connection ) ; if ( executionId != null ) { LOG . info ( "" , targetName , executionId ) ; if ( RuntimeContext . get ( ) . canExecute ( repo ) ) { repo . releaseLock ( executionId ) ; } } else { LOG . info ( "" , targetName ) ; if ( RuntimeContext . get ( ) . canExecute ( repo ) ) { repo . releaseAllLock ( ) ; } } } finally { DBConnection . closeConn ( connection ) ; } return Constants . EXIT_CODE_SUCCESS ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return Constants . EXIT_CODE_ERROR ; } } } package com . asakusafw . bulkloader . cache ; import java . util . Arrays ; import java . util . Collections ; import java . util . Date ; import java . util . List ; import java . util . Map ; import java . util . UUID ; import java . util . concurrent . TimeUnit ; import com . asakusafw . bulkloader . bean . ImportBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . JobFlowParamLoader ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . importer . Importer ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . core . context . RuntimeContext ; public final class BuildCache { static final Log LOG = new Log ( BuildCache . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_DB ; private BuildCache ( ) { return ; } public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( BuildCache . class . getClassLoader ( ) ) ; if ( args . length != && args . length != ) { LOG . error ( "" , Arrays . toString ( args ) ) ; System . exit ( Constants . EXIT_CODE_ERROR ) ; return ; } String targetName = args [ ] ; String batchId = args [ ] ; String flowId = args [ ] ; String tableName = args [ ] ; String executionId = args . length == ? args [ ] : UUID . randomUUID ( ) . toString ( ) ; int initExit = initialize ( targetName , flowId , executionId ) ; if ( initExit != Constants . EXIT_CODE_SUCCESS ) { System . exit ( initExit ) ; } LOG . info ( "" , targetName , batchId , flowId , executionId , tableName ) ; int exitCode = new BuildCache ( ) . execute ( targetName , batchId , flowId , tableName , executionId ) ; LOG . info ( "" , targetName , batchId , flowId , executionId , tableName , exitCode ) ; System . exit ( exitCode ) ; } private static int initialize ( String targetName , String flowId , String executionId ) { if ( ! BulkLoaderInitializer . initDBServer ( flowId , executionId , PROPERTIES , targetName ) ) { LOG . error ( "" , targetName , flowId , executionId ) ; return Constants . EXIT_CODE_ERROR ; } return Constants . EXIT_CODE_SUCCESS ; } private int execute ( String targetName , String batchId , String flowId , String tableName , String executionId ) { assert targetName != null ; assert batchId != null ; assert flowId != null ; assert tableName != null ; assert executionId != null ; try { ImportBean bean = createBean ( targetName , batchId , flowId , executionId , tableName ) ; if ( bean == null ) { return Constants . EXIT_CODE_ERROR ; } if ( RuntimeContext . get ( ) . isSimulation ( ) ) { return Constants . EXIT_CODE_SUCCESS ; } Importer importer = new Importer ( ) ; int exitCode = importer . importTables ( bean ) ; if ( exitCode == Constants . EXIT_CODE_SUCCESS ) { LOG . info ( "" , targetName , batchId , flowId , executionId , tableName ) ; int releaseExit = new ReleaseCacheLock ( ) . execute ( targetName , executionId ) ; if ( releaseExit != Constants . EXIT_CODE_SUCCESS ) { LOG . error ( "" , targetName , batchId , flowId , executionId , tableName ) ; exitCode = Constants . EXIT_CODE_WARNING ; } } else { LOG . info ( "" , targetName , batchId , flowId , executionId , tableName ) ; } return exitCode ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e ) { try { LOG . error ( e , "" , targetName , batchId , flowId , executionId , tableName ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e1 ) { System . err . print ( "" ) ; e1 . printStackTrace ( ) ; return Constants . EXIT_CODE_ERROR ; } } } private ImportBean createBean ( String targetName , String batchId , String jobflowId , String executionId , String tableName ) { assert targetName != null ; assert batchId != null ; assert jobflowId != null ; assert executionId != null ; assert tableName != null ; ImportBean bean = new ImportBean ( ) ; bean . setPrimary ( false ) ; bean . setTargetName ( targetName ) ; bean . setBatchId ( batchId ) ; bean . setJobflowId ( jobflowId ) ; bean . setExecutionId ( executionId ) ; bean . setJobnetEndTime ( new Date ( System . currentTimeMillis ( ) + TimeUnit . DAYS . toMillis ( ) ) ) ; bean . setRetryCount ( Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_RETRY_COUNT ) ) ) ; bean . setRetryInterval ( Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_RETRY_INTERVAL ) ) ) ; JobFlowParamLoader loader = new JobFlowParamLoader ( ) ; if ( loader . loadCacheBuildParam ( targetName , batchId , jobflowId ) == false ) { return null ; } ImportTargetTableBean table = null ; for ( Map . Entry < String , ImportTargetTableBean > entry : loader . getImportTargetTables ( ) . entrySet ( ) ) { if ( entry . getKey ( ) . equals ( tableName ) ) { table = entry . getValue ( ) ; break ; } } if ( table == null ) { LOG . error ( "" , targetName , batchId , jobflowId , executionId , tableName ) ; return null ; } if ( table . getCacheId ( ) == null ) { LOG . error ( "" , targetName , batchId , jobflowId , executionId , tableName ) ; return null ; } bean . setTargetTable ( Collections . singletonMap ( tableName , table ) ) ; return bean ; } } package com . asakusafw . bulkloader . cache ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . sql . Timestamp ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . List ; import com . asakusafw . bulkloader . common . DBConnection ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public class LocalCacheInfoRepository { static final Log LOG = new Log ( LocalCacheInfoRepository . class ) ; private final Connection connection ; public LocalCacheInfoRepository ( Connection connection ) { if ( connection == null ) { throw new IllegalArgumentException ( "" ) ; } this . connection = connection ; } public LocalCacheInfo getCacheInfo ( String cacheId ) throws BulkLoaderSystemException { if ( cacheId == null ) { throw new IllegalArgumentException ( "" ) ; } final String sql = "" + "" + "" ; PreparedStatement statement = null ; ResultSet resultSet = null ; try { LOG . debugMessage ( "" , cacheId ) ; statement = connection . prepareStatement ( sql ) ; statement . setString ( , cacheId ) ; resultSet = statement . executeQuery ( ) ; if ( resultSet . next ( ) == false ) { LOG . debugMessage ( "" , cacheId ) ; return null ; } LocalCacheInfo result = toCacheInfoObject ( resultSet ) ; assert resultSet . next ( ) == false ; LOG . debugMessage ( "" , cacheId ) ; return result ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , cacheId ) ; } finally { DBConnection . closeRs ( resultSet ) ; DBConnection . closePs ( statement ) ; } } public Calendar putCacheInfo ( LocalCacheInfo current ) throws BulkLoaderSystemException { if ( current == null ) { throw new IllegalArgumentException ( "" ) ; } final String sql = "" + "" + "" ; boolean succeed = false ; PreparedStatement statement = null ; Calendar last = null ; try { LOG . debugMessage ( "" , current ) ; last = getLastUpdated ( current . getTableName ( ) ) ; if ( last == null ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , current ) ; } statement = connection . prepareStatement ( sql ) ; statement . setString ( , current . getId ( ) ) ; statement . setTimestamp ( , toTimestamp ( last ) ) ; statement . setTimestamp ( , toTimestamp ( current . getRemoteTimestamp ( ) ) ) ; statement . setString ( , current . getTableName ( ) ) ; statement . setString ( , current . getPath ( ) ) ; int rows = statement . executeUpdate ( ) ; if ( rows == ) { throw new BulkLoaderSystemException ( getClass ( ) , "" , current ) ; } DBConnection . commit ( connection ) ; succeed = true ; LOG . debugMessage ( "" , toTimestamp ( last ) ) ; return last ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , current . getId ( ) , toTimestamp ( last ) , toTimestamp ( current . getRemoteTimestamp ( ) ) , current . getTableName ( ) , current . getPath ( ) ) ; } finally { DBConnection . closePs ( statement ) ; if ( succeed == false ) { DBConnection . rollback ( connection ) ; } } } private Calendar getLastUpdated ( String tableName ) throws SQLException { assert connection != null ; assert tableName != null ; Statement statement = connection . createStatement ( ) ; ResultSet resultSet = null ; try { LOG . debugMessage ( "" , tableName ) ; statement . execute ( MessageFormat . format ( "" , tableName ) ) ; resultSet = statement . executeQuery ( "" ) ; if ( resultSet . next ( ) == false ) { return null ; } Calendar calendar = Calendar . getInstance ( ) ; Timestamp timestamp = resultSet . getTimestamp ( , calendar ) ; calendar . setTime ( timestamp ) ; resultSet . close ( ) ; statement . execute ( "" ) ; LOG . debugMessage ( "" , tableName , timestamp ) ; return calendar ; } finally { DBConnection . closeRs ( resultSet ) ; DBConnection . closeStmt ( statement ) ; } } public boolean deleteCacheInfo ( String cacheId ) throws BulkLoaderSystemException { if ( cacheId == null ) { throw new IllegalArgumentException ( "" ) ; } final String sql = "" + "" + "" ; boolean succeed = false ; PreparedStatement statement = null ; try { LOG . debugMessage ( "" , cacheId ) ; statement = connection . prepareStatement ( sql ) ; statement . setString ( , cacheId ) ; int rows = statement . executeUpdate ( ) ; DBConnection . commit ( connection ) ; succeed = true ; LOG . debugMessage ( "" , cacheId , rows ) ; return rows > ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , cacheId ) ; } finally { DBConnection . closePs ( statement ) ; if ( succeed == false ) { DBConnection . rollback ( connection ) ; } } } public int deleteTableCacheInfo ( String tableName ) throws BulkLoaderSystemException { if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } final String sql = "" + "" + "" ; boolean succeed = false ; PreparedStatement statement = null ; try { LOG . debugMessage ( "" , tableName ) ; statement = connection . prepareStatement ( sql ) ; statement . setString ( , tableName ) ; int rows = statement . executeUpdate ( ) ; DBConnection . commit ( connection ) ; succeed = true ; LOG . debugMessage ( "" , tableName , rows ) ; return rows ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , tableName ) ; } finally { DBConnection . closePs ( statement ) ; if ( succeed == false ) { DBConnection . rollback ( connection ) ; } } } public void deleteAllCacheInfo ( ) throws BulkLoaderSystemException { final String sql = "" + "" + "" ; boolean succeed = false ; PreparedStatement statement = null ; try { LOG . debugMessage ( "" ) ; statement = connection . prepareStatement ( sql ) ; statement . executeUpdate ( ) ; DBConnection . commit ( connection ) ; succeed = true ; LOG . debugMessage ( "" ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql ) ; } finally { DBConnection . closePs ( statement ) ; if ( succeed == false ) { DBConnection . rollback ( connection ) ; } } } public List < LocalCacheInfo > listDeletedCacheInfo ( ) throws BulkLoaderSystemException { final String sql = "" + "" + "" ; PreparedStatement statement = null ; ResultSet resultSet = null ; try { LOG . debugMessage ( "" ) ; statement = connection . prepareStatement ( sql ) ; resultSet = statement . executeQuery ( ) ; List < LocalCacheInfo > results = new ArrayList < LocalCacheInfo > ( ) ; while ( resultSet . next ( ) ) { LocalCacheInfo found = toCacheInfoObject ( resultSet ) ; LOG . debugMessage ( "" , found . getId ( ) ) ; results . add ( found ) ; } LOG . debugMessage ( "" , results . size ( ) ) ; return results ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql ) ; } finally { DBConnection . closeRs ( resultSet ) ; DBConnection . closePs ( statement ) ; } } public boolean deleteCacheInfoCompletely ( String cacheId ) throws BulkLoaderSystemException { if ( cacheId == null ) { throw new IllegalArgumentException ( "" ) ; } final String sql = "" + "" + "" ; boolean succeed = false ; PreparedStatement statement = null ; try { LOG . debugMessage ( "" , cacheId ) ; statement = connection . prepareStatement ( sql ) ; statement . setString ( , cacheId ) ; int rows = statement . executeUpdate ( ) ; DBConnection . commit ( connection ) ; succeed = true ; LOG . debugMessage ( "" , cacheId , rows ) ; return rows > ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , cacheId ) ; } finally { DBConnection . closePs ( statement ) ; if ( succeed == false ) { DBConnection . rollback ( connection ) ; } } } private LocalCacheInfo toCacheInfoObject ( ResultSet resultSet ) throws SQLException { assert resultSet != null ; String id = resultSet . getString ( ) ; Calendar localTimestamp = Calendar . getInstance ( ) ; Timestamp local = resultSet . getTimestamp ( , localTimestamp ) ; if ( local == null || local . getTime ( ) == ) { localTimestamp = null ; } else { localTimestamp . setTime ( local ) ; } Calendar remoteTimestamp = Calendar . getInstance ( ) ; Timestamp remote = resultSet . getTimestamp ( , remoteTimestamp ) ; if ( remote == null || remote . getTime ( ) == ) { remoteTimestamp = null ; } else { remoteTimestamp . setTime ( remote ) ; } String tableName = resultSet . getString ( ) ; String path = resultSet . getString ( ) ; return new LocalCacheInfo ( id , localTimestamp , remoteTimestamp , tableName , path ) ; } public boolean tryLock ( String executionId , String cacheId , String tableName ) throws BulkLoaderSystemException { if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( cacheId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } final String sql = "" + "" + "" ; boolean succeed = false ; PreparedStatement statement = null ; try { LOG . debugMessage ( "" , cacheId , executionId ) ; statement = connection . prepareStatement ( sql ) ; statement . setString ( , cacheId ) ; statement . setString ( , executionId ) ; int rows = statement . executeUpdate ( ) ; DBConnection . commit ( connection ) ; succeed = true ; LOG . debugMessage ( "" , cacheId , rows ) ; return rows > ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , cacheId , executionId ) ; } finally { DBConnection . closePs ( statement ) ; if ( succeed == false ) { DBConnection . rollback ( connection ) ; } } } public void releaseLock ( String executionId ) throws BulkLoaderSystemException { if ( executionId == null ) { throw new IllegalArgumentException ( "" ) ; } final String sql = "" + "" + "" ; boolean succeed = false ; PreparedStatement statement = null ; try { LOG . debugMessage ( "" , executionId ) ; statement = connection . prepareStatement ( sql ) ; statement . setString ( , executionId ) ; int rows = statement . executeUpdate ( ) ; DBConnection . commit ( connection ) ; succeed = true ; LOG . debugMessage ( "" , executionId , rows ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql , executionId ) ; } finally { DBConnection . closePs ( statement ) ; if ( succeed == false ) { DBConnection . rollback ( connection ) ; } } } public void releaseAllLock ( ) throws BulkLoaderSystemException { final String sql = "" + "" ; boolean succeed = false ; PreparedStatement statement = null ; try { LOG . debugMessage ( "" ) ; statement = connection . prepareStatement ( sql ) ; statement . executeUpdate ( ) ; DBConnection . commit ( connection ) ; succeed = true ; LOG . debugMessage ( "" ) ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , getClass ( ) , sql ) ; } finally { DBConnection . closePs ( statement ) ; if ( succeed == false ) { DBConnection . rollback ( connection ) ; } } } private Timestamp toTimestamp ( Calendar calendar ) { if ( calendar == null ) { return new Timestamp ( ) ; } return new Timestamp ( calendar . getTimeInMillis ( ) ) ; } } package com . asakusafw . bulkloader . cache ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import org . apache . commons . io . IOUtils ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . util . Tool ; import com . asakusafw . bulkloader . collector . SystemOutManager ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . thundergate . runtime . cache . CacheInfo ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; public class GetCacheInfoRemote extends Configured implements Tool { static final Log LOG = new Log ( GetCacheInfoRemote . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_HC ; String targetName ; String batchId ; String flowId ; String executionId ; String userName ; public static void main ( String [ ] args ) throws Exception { SystemOutManager . changeSystemOutToSystemErr ( ) ; RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; GetCacheInfoRemote service = new GetCacheInfoRemote ( ) ; service . setConf ( new Configuration ( ) ) ; int exitCode = service . run ( args ) ; System . exit ( exitCode ) ; } @ Override public int run ( String [ ] args ) throws Exception { initialize ( args ) ; LOG . info ( "" , targetName , batchId , flowId , executionId , userName ) ; FileList . Reader in = null ; FileList . Writer out = null ; try { in = FileList . createReader ( System . in ) ; out = FileList . createWriter ( SystemOutManager . getOut ( ) , false ) ; execute ( in , out ) ; out . close ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return Constants . EXIT_CODE_ERROR ; } finally { IOUtils . closeQuietly ( in ) ; IOUtils . closeQuietly ( out ) ; } LOG . info ( "" , targetName , batchId , flowId , executionId , userName ) ; return Constants . EXIT_CODE_SUCCESS ; } void initialize ( String ... args ) { assert args != null ; if ( args . length != ) { LOG . error ( "" , Arrays . toString ( args ) ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; } this . targetName = args [ ] ; this . batchId = args [ ] ; this . flowId = args [ ] ; this . executionId = args [ ] ; this . userName = args [ ] ; if ( BulkLoaderInitializer . initHadoopCluster ( flowId , executionId , PROPERTIES ) == false ) { LOG . error ( "" , targetName , batchId , flowId , executionId , userName ) ; throw new IllegalStateException ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; } } void execute ( FileList . Reader input , FileList . Writer output ) throws IOException , BulkLoaderSystemException { assert input != null ; assert output != null ; try { while ( input . next ( ) ) { FileProtocol protocol = input . getCurrentProtocol ( ) ; if ( protocol . getKind ( ) != FileProtocol . Kind . GET_CACHE_INFO ) { throw new IOException ( MessageFormat . format ( "" , protocol . getKind ( ) , protocol . getLocation ( ) ) ) ; } LOG . info ( "" , protocol . getLocation ( ) ) ; CacheInfo info = getCacheInfo ( protocol . getLocation ( ) ) ; FileProtocol result ; if ( info == null ) { result = new FileProtocol ( FileProtocol . Kind . RESPONSE_NOT_FOUND , protocol . getLocation ( ) , null ) ; LOG . info ( "" , protocol . getLocation ( ) ) ; } else { result = new FileProtocol ( FileProtocol . Kind . RESPONSE_CACHE_INFO , protocol . getLocation ( ) , info ) ; LOG . info ( "" , protocol . getLocation ( ) , info . getId ( ) , info . getTableName ( ) , info . getTimestamp ( ) . getTime ( ) ) ; } if ( RuntimeContext . get ( ) . isSimulation ( ) == false ) { output . openNext ( result ) . close ( ) ; } } } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , targetName , batchId , flowId , executionId , userName ) ; } } private CacheInfo getCacheInfo ( String location ) throws BulkLoaderSystemException { assert location != null ; URI cacheBaseUri = FileNameUtil . createPath ( getConf ( ) , location , executionId , userName ) . toUri ( ) ; try { CacheStorage storage = new CacheStorage ( getConf ( ) , cacheBaseUri ) ; try { if ( RuntimeContext . get ( ) . canExecute ( storage ) ) { return storage . getHeadCacheInfo ( ) ; } else { return null ; } } finally { IOUtils . closeQuietly ( storage ) ; } } catch ( IOException e ) { LOG . warn ( e , "" , location ) ; return null ; } } } package com . asakusafw . bulkloader . cache ; import java . text . SimpleDateFormat ; import java . util . Calendar ; public class LocalCacheInfo { private final String id ; private final Calendar localTimestamp ; private final Calendar remoteTimestamp ; private final String tableName ; private final String path ; public LocalCacheInfo ( String id , Calendar localTimestamp , Calendar remoteTimestamp , String tableName , String path ) { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = id ; this . localTimestamp = copy ( localTimestamp ) ; this . remoteTimestamp = copy ( remoteTimestamp ) ; this . tableName = tableName ; this . path = path ; } public String getId ( ) { return id ; } public String getPath ( ) { return path ; } public String getTableName ( ) { return tableName ; } public Calendar getLocalTimestamp ( ) { return copy ( localTimestamp ) ; } public Calendar getRemoteTimestamp ( ) { return copy ( remoteTimestamp ) ; } private Calendar copy ( Calendar timestamp ) { if ( timestamp == null ) { return null ; } Calendar copy = ( Calendar ) timestamp . clone ( ) ; copy . set ( Calendar . MILLISECOND , ) ; return copy ; } @ Override public String toString ( ) { SimpleDateFormat formatter = new SimpleDateFormat ( "" ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( id ) ; builder . append ( "" ) ; builder . append ( localTimestamp == null ? null : formatter . format ( localTimestamp . getTime ( ) ) ) ; builder . append ( "" ) ; builder . append ( remoteTimestamp == null ? null : formatter . format ( remoteTimestamp . getTime ( ) ) ) ; builder . append ( "" ) ; builder . append ( tableName ) ; builder . append ( "" ) ; builder . append ( path ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . bulkloader . cache ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import org . apache . commons . io . IOUtils ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . util . Tool ; import com . asakusafw . bulkloader . collector . SystemOutManager ; import com . asakusafw . bulkloader . common . BulkLoaderInitializer ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . common . FileNameUtil ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . thundergate . runtime . cache . CacheStorage ; public class DeleteCacheStorageRemote extends Configured implements Tool { private static final String SURROGATE_EXECUTION_ID = "" ; static final Log LOG = new Log ( DeleteCacheStorageRemote . class ) ; private static final List < String > PROPERTIES = Constants . PROPERTIES_HC ; String targetName ; String userName ; public static void main ( String [ ] args ) throws Exception { SystemOutManager . changeSystemOutToSystemErr ( ) ; RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; DeleteCacheStorageRemote service = new DeleteCacheStorageRemote ( ) ; service . setConf ( new Configuration ( ) ) ; int exitCode = service . run ( args ) ; System . exit ( exitCode ) ; } @ Override public int run ( String [ ] args ) throws Exception { initialize ( args ) ; LOG . info ( "" , targetName , userName ) ; FileList . Reader in = null ; FileList . Writer out = null ; try { in = FileList . createReader ( System . in ) ; out = FileList . createWriter ( SystemOutManager . getOut ( ) , false ) ; execute ( in , out ) ; out . close ( ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return Constants . EXIT_CODE_ERROR ; } finally { IOUtils . closeQuietly ( in ) ; IOUtils . closeQuietly ( out ) ; } LOG . info ( "" , targetName , userName ) ; return Constants . EXIT_CODE_SUCCESS ; } void initialize ( String ... args ) { assert args != null ; if ( args . length != ) { LOG . error ( "" , Arrays . toString ( args ) ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; } this . targetName = args [ ] ; this . userName = args [ ] ; if ( BulkLoaderInitializer . initHadoopCluster ( "" , SURROGATE_EXECUTION_ID , PROPERTIES ) == false ) { LOG . error ( "" , targetName , userName ) ; throw new IllegalStateException ( MessageFormat . format ( "" , Arrays . toString ( args ) ) ) ; } } void execute ( FileList . Reader input , FileList . Writer output ) throws IOException , BulkLoaderSystemException { assert input != null ; assert output != null ; try { while ( input . next ( ) ) { FileProtocol protocol = input . getCurrentProtocol ( ) ; if ( protocol . getKind ( ) != FileProtocol . Kind . DELETE_CACHE ) { throw new IOException ( MessageFormat . format ( "" , protocol . getKind ( ) , protocol . getLocation ( ) ) ) ; } LOG . info ( "" , protocol . getLocation ( ) ) ; FileProtocol . Kind result = deleteCacheData ( protocol . getLocation ( ) ) ; LOG . info ( "" , protocol . getLocation ( ) , result ) ; FileProtocol response = new FileProtocol ( result , protocol . getLocation ( ) , null ) ; output . openNext ( response ) . close ( ) ; } } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , targetName , userName ) ; } } private FileProtocol . Kind deleteCacheData ( String location ) throws BulkLoaderSystemException { assert location != null ; URI cacheBaseUri = FileNameUtil . createPath ( getConf ( ) , location , SURROGATE_EXECUTION_ID , userName ) . toUri ( ) ; try { CacheStorage storage = new CacheStorage ( getConf ( ) , cacheBaseUri ) ; try { boolean succeed ; if ( RuntimeContext . get ( ) . canExecute ( storage ) ) { succeed = storage . deleteAll ( ) ; } else { succeed = true ; } return succeed ? FileProtocol . Kind . RESPONSE_DELETED : FileProtocol . Kind . RESPONSE_NOT_FOUND ; } finally { IOUtils . closeQuietly ( storage ) ; } } catch ( IOException e ) { LOG . warn ( e , "" , location ) ; return FileProtocol . Kind . RESPONSE_ERROR ; } } } package com . asakusafw . bulkloader . cache ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . concurrent . Callable ; import java . util . concurrent . CancellationException ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . ThreadFactory ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import java . util . concurrent . atomic . AtomicInteger ; import com . asakusafw . bulkloader . common . ConfigurationLoader ; import com . asakusafw . bulkloader . common . Constants ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . transfer . FileList ; import com . asakusafw . bulkloader . transfer . FileListProvider ; import com . asakusafw . bulkloader . transfer . FileProtocol ; import com . asakusafw . bulkloader . transfer . OpenSshFileListProvider ; import com . asakusafw . runtime . core . context . RuntimeContext ; public class DeleteCacheStorageLocal { static final Log LOG = new Log ( DeleteCacheStorageLocal . class ) ; private final ExecutorService executor = Executors . newCachedThreadPool ( new ThreadFactory ( ) { final AtomicInteger counter = new AtomicInteger ( ) ; @ Override public Thread newThread ( Runnable r ) { Thread t = new Thread ( r ) ; t . setDaemon ( true ) ; t . setName ( String . format ( "" , counter . incrementAndGet ( ) ) ) ; return t ; } } ) ; public Map < String , FileProtocol . Kind > delete ( List < LocalCacheInfo > list , String targetName ) throws BulkLoaderSystemException { if ( list == null ) { throw new IllegalArgumentException ( "" ) ; } if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( list . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } LOG . info ( "" , targetName , list . size ( ) ) ; FileListProvider provider = null ; try { provider = openFileList ( targetName ) ; Future < Void > upstream = submitUpstream ( list , provider ) ; Future < Map < String , FileProtocol . Kind > > downstream = submitDownstream ( provider ) ; Map < String , FileProtocol . Kind > results ; while ( true ) { try { if ( upstream . isDone ( ) ) { upstream . get ( ) ; } results = downstream . get ( , TimeUnit . SECONDS ) ; break ; } catch ( TimeoutException e ) { } catch ( CancellationException e ) { upstream . cancel ( true ) ; downstream . cancel ( true ) ; throw new IOException ( "" , e ) ; } catch ( ExecutionException e ) { upstream . cancel ( true ) ; downstream . cancel ( true ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof Error ) { throw ( Error ) cause ; } else if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else { throw new AssertionError ( cause ) ; } } } provider . waitForComplete ( ) ; reportResults ( targetName , results ) ; return results ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , targetName ) ; } catch ( InterruptedException e ) { throw new BulkLoaderSystemException ( e , getClass ( ) , "" , targetName ) ; } finally { if ( provider != null ) { try { provider . close ( ) ; } catch ( IOException ignored ) { ignored . printStackTrace ( ) ; } } } } private void reportResults ( String targetName , Map < String , FileProtocol . Kind > results ) { assert targetName != null ; assert results != null ; int succeed = ; int missing = ; int error = ; for ( Map . Entry < String , FileProtocol . Kind > entry : results . entrySet ( ) ) { switch ( entry . getValue ( ) ) { case RESPONSE_DELETED : succeed ++ ; break ; case RESPONSE_NOT_FOUND : missing ++ ; break ; case RESPONSE_ERROR : error ++ ; break ; default : throw new AssertionError ( entry ) ; } } LOG . info ( "" , targetName , succeed , missing , error ) ; } private Future < Void > submitUpstream ( final List < LocalCacheInfo > list , final FileListProvider provider ) { assert list != null ; assert provider != null ; return executor . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws IOException { FileList . Writer writer = provider . openWriter ( false ) ; try { for ( LocalCacheInfo info : list ) { FileProtocol protocol = new FileProtocol ( FileProtocol . Kind . DELETE_CACHE , info . getPath ( ) , null ) ; writer . openNext ( protocol ) . close ( ) ; } } finally { writer . close ( ) ; } return null ; } } ) ; } private Future < Map < String , FileProtocol . Kind > > submitDownstream ( final FileListProvider provider ) { assert provider != null ; return executor . submit ( new Callable < Map < String , FileProtocol . Kind > > ( ) { @ Override public Map < String , FileProtocol . Kind > call ( ) throws IOException { Map < String , FileProtocol . Kind > results = new HashMap < String , FileProtocol . Kind > ( ) ; FileList . Reader reader = provider . openReader ( ) ; try { while ( reader . next ( ) ) { FileProtocol protocol = reader . getCurrentProtocol ( ) ; reader . openContent ( ) . close ( ) ; switch ( protocol . getKind ( ) ) { case RESPONSE_DELETED : case RESPONSE_NOT_FOUND : case RESPONSE_ERROR : results . put ( protocol . getLocation ( ) , protocol . getKind ( ) ) ; break ; default : throw new IOException ( MessageFormat . format ( "" , protocol ) ) ; } } } finally { reader . close ( ) ; } return results ; } } ) ; } protected FileListProvider openFileList ( String targetName ) throws IOException { if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } String sshPath = ConfigurationLoader . getProperty ( Constants . PROP_KEY_SSH_PATH ) ; String hostName = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAMENODE_HOST ) ; String userName = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAMENODE_USER ) ; String scriptPath = ConfigurationLoader . getRemoteScriptPath ( Constants . PATH_REMOTE_CACHE_DELETE ) ; List < String > command = new ArrayList < String > ( ) ; command . add ( scriptPath ) ; command . add ( targetName ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . putAll ( ConfigurationLoader . getPropSubMap ( Constants . PROP_PREFIX_HC_ENV ) ) ; env . putAll ( RuntimeContext . get ( ) . unapply ( ) ) ; LOG . info ( "" , sshPath , hostName , userName , scriptPath , targetName ) ; return new OpenSshFileListProvider ( sshPath , userName , hostName , command , env ) ; } } package com . asakusafw . bulkloader . common ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public enum ImportType { PRIMARY ( "" ) , SECONDARY ( "" ) ; private String importType ; public String getImportType ( ) { return importType ; } private ImportType ( String type ) { this . importType = type ; } public static ImportType find ( String key ) { return ImportTypeToImportType . REVERSE_DICTIONARY . get ( key ) ; } @ Override public String toString ( ) { return importType ; } private static class ImportTypeToImportType { static final Map < String , ImportType > REVERSE_DICTIONARY ; static { Map < String , ImportType > map = new HashMap < String , ImportType > ( ) ; for ( ImportType elem : ImportType . values ( ) ) { map . put ( elem . getImportType ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } } } package com . asakusafw . bulkloader . common ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . runtime . util . VariableTable ; public final class FileNameUtil { private static final Class < ? > CLASS = FileNameUtil . class ; private FileNameUtil ( ) { return ; } public static File createImportFilePath ( String targetName , String jobflowId , String executionId , String tableName ) throws BulkLoaderSystemException { File fileDirectry = new File ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_IMP_FILE_DIR ) ) ; if ( ! fileDirectry . exists ( ) ) { throw new BulkLoaderSystemException ( CLASS , "" , fileDirectry . getAbsolutePath ( ) ) ; } StringBuilder strFileName = new StringBuilder ( Constants . IMPORT_FILE_PREFIX ) ; strFileName . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileName . append ( targetName ) ; strFileName . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileName . append ( jobflowId ) ; strFileName . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileName . append ( executionId ) ; strFileName . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileName . append ( tableName ) ; strFileName . append ( Constants . IMPORT_FILE_EXTENSION ) ; return new File ( fileDirectry , strFileName . toString ( ) ) ; } public static String createSendImportFileName ( String tableName ) { StringBuilder strFileNmae = new StringBuilder ( Constants . IMPORT_FILE_PREFIX ) ; strFileNmae . append ( Constants . IMPORT_FILE_DELIMITER ) ; strFileNmae . append ( tableName ) ; strFileNmae . append ( Constants . EXPORT_FILE_EXTENSION ) ; return strFileNmae . toString ( ) ; } public static String getImportTableName ( String fileName ) { String normalized = new File ( fileName ) . getName ( ) . replace ( File . separatorChar , '' ) ; int start = Constants . IMPORT_FILE_PREFIX . length ( ) + Constants . IMPORT_FILE_DELIMITER . length ( ) ; int end = normalized . length ( ) - Constants . IMPORT_FILE_EXTENSION . length ( ) ; return normalized . substring ( start , end ) ; } public static Path createPath ( Configuration conf , String rawPath , String executionId , String user ) throws BulkLoaderSystemException { return createPaths ( conf , Collections . singletonList ( rawPath ) , executionId , user ) . get ( ) ; } public static List < Path > createPaths ( Configuration conf , List < String > rawPaths , String executionId , String user ) throws BulkLoaderSystemException { String basePathString = ConfigurationLoader . getProperty ( Constants . PROP_KEY_BASE_PATH ) ; Path basePath ; if ( basePathString == null || basePathString . isEmpty ( ) ) { basePath = null ; } else { basePath = new Path ( basePathString ) ; } VariableTable variables = Constants . createVariableTable ( ) ; variables . defineVariable ( Constants . HDFS_PATH_VARIABLE_USER , user ) ; variables . defineVariable ( Constants . HDFS_PATH_VARIABLE_EXECUTION_ID , executionId ) ; FileSystem fs ; try { if ( basePath == null ) { fs = FileSystem . get ( conf ) ; } else { fs = FileSystem . get ( basePath . toUri ( ) , conf ) ; basePath = fs . makeQualified ( basePath ) ; } } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" , rawPaths ) ; } List < Path > results = new ArrayList < Path > ( ) ; for ( String rawPath : rawPaths ) { String resolved = variables . parse ( rawPath , false ) ; Path fullPath ; if ( basePath == null ) { fullPath = fs . makeQualified ( new Path ( resolved ) ) ; } else { fullPath = new Path ( basePath , resolved ) ; } results . add ( fullPath ) ; } return results ; } public static String createSendExportFileName ( String tableName , Map < String , Integer > fileNameMap ) { Integer seq = fileNameMap . get ( tableName ) ; if ( seq == null ) { seq = Integer . valueOf ( ) ; } else { seq ++ ; } fileNameMap . put ( tableName , seq ) ; StringBuilder strFileNmae = new StringBuilder ( Constants . EXPORT_FILE_PREFIX ) ; strFileNmae . append ( Constants . EXPORT_FILE_DELIMITER ) ; strFileNmae . append ( tableName ) ; strFileNmae . append ( Constants . EXPORT_FILE_DELIMITER ) ; strFileNmae . append ( seq . toString ( ) ) ; strFileNmae . append ( Constants . EXPORT_FILE_EXTENSION ) ; return strFileNmae . toString ( ) ; } public static String getExportTableName ( String fileName ) { String normalized = new File ( fileName ) . getName ( ) . replace ( File . separatorChar , '' ) ; int start = Constants . EXPORT_FILE_PREFIX . length ( ) + Constants . EXPORT_FILE_DELIMITER . length ( ) ; int end = normalized . lastIndexOf ( Constants . EXPORT_FILE_DELIMITER ) ; try { return normalized . substring ( start , end ) ; } catch ( Exception e ) { return null ; } } public static File createExportFilePath ( File fileDirectry , String targetName , String jobflowId , String executionId , String tableName , int seq ) { StringBuilder strFileName = new StringBuilder ( Constants . EXPORT_FILE_PREFIX ) ; strFileName . append ( Constants . EXPORT_FILE_DELIMITER ) ; strFileName . append ( targetName ) ; strFileName . append ( Constants . EXPORT_FILE_DELIMITER ) ; strFileName . append ( jobflowId ) ; strFileName . append ( Constants . EXPORT_FILE_DELIMITER ) ; strFileName . append ( executionId ) ; strFileName . append ( Constants . EXPORT_FILE_DELIMITER ) ; strFileName . append ( tableName ) ; strFileName . append ( Constants . EXPORT_FILE_DELIMITER ) ; strFileName . append ( String . valueOf ( seq ) ) ; strFileName . append ( Constants . EXPORT_FILE_EXTENSION ) ; return new File ( fileDirectry , strFileName . toString ( ) ) ; } } package com . asakusafw . bulkloader . common ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . Properties ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public final class DBConnection { static final Log LOG = new Log ( DBConnection . class ) ; private static final Class < ? > CLASS = DBConnection . class ; private static volatile boolean initialized = false ; private DBConnection ( ) { return ; } public static void init ( String jdbcDriverName ) throws BulkLoaderSystemException { try { Class . forName ( jdbcDriverName ) . newInstance ( ) ; initialized = true ; } catch ( NullPointerException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" , jdbcDriverName ) ; } catch ( InstantiationException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" , jdbcDriverName ) ; } catch ( IllegalAccessException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" , jdbcDriverName ) ; } catch ( ClassNotFoundException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" , jdbcDriverName ) ; } } public static Connection getConnection ( ) throws BulkLoaderSystemException { Connection conn = null ; FileInputStream fis = null ; if ( ! initialized ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } String url = ConfigurationLoader . getProperty ( Constants . PROP_KEY_DB_URL ) ; String user = ConfigurationLoader . getProperty ( Constants . PROP_KEY_DB_USER ) ; String password = ConfigurationLoader . getProperty ( Constants . PROP_KEY_DB_PASSWORD ) ; String param = ConfigurationLoader . getProperty ( Constants . PROP_KEY_NAME_DB_PRAM ) ; try { if ( param != null && ! param . isEmpty ( ) ) { fis = new FileInputStream ( new File ( param ) ) ; Properties prop = new Properties ( ) ; prop . load ( fis ) ; prop . setProperty ( "" , user ) ; prop . setProperty ( "" , password ) ; conn = DriverManager . getConnection ( url , prop ) ; } else { conn = DriverManager . getConnection ( url , user , password ) ; } conn . setTransactionIsolation ( Connection . TRANSACTION_READ_COMMITTED ) ; conn . setAutoCommit ( false ) ; return conn ; } catch ( SQLException e ) { if ( conn != null ) { try { conn . close ( ) ; } catch ( SQLException e1 ) { e1 . printStackTrace ( ) ; } } throw new BulkLoaderSystemException ( e , CLASS , "" , "" ) ; } catch ( FileNotFoundException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" , MessageFormat . format ( "" , param ) ) ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" , MessageFormat . format ( "" , param ) ) ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } public static void closePs ( PreparedStatement stmt ) { closeStmt ( stmt ) ; } public static void closeStmt ( Statement stmt ) { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void closeRs ( ResultSet rs ) { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void closeConn ( Connection conn ) { if ( conn != null ) { try { conn . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void commit ( Connection conn ) throws BulkLoaderSystemException { if ( conn != null ) { try { LOG . debugMessage ( "" ) ; long before = System . currentTimeMillis ( ) ; conn . commit ( ) ; long time = System . currentTimeMillis ( ) - before ; LOG . debugMessage ( "" , time ) ; } catch ( SQLException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" ) ; } } } public static void rollback ( Connection conn ) throws BulkLoaderSystemException { if ( conn != null ) { try { LOG . debugMessage ( "" ) ; long before = System . currentTimeMillis ( ) ; conn . rollback ( ) ; long time = System . currentTimeMillis ( ) - before ; LOG . debugMessage ( "" , time ) ; } catch ( SQLException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" ) ; } } } public static int executeUpdate ( PreparedStatement stmt , String sql , String ... param ) throws SQLException { String args = arrayToString ( param ) ; LOG . debugMessage ( "" , sql , args ) ; long before = System . currentTimeMillis ( ) ; int result = stmt . executeUpdate ( ) ; long time = System . currentTimeMillis ( ) - before ; LOG . debugMessage ( "" , time , result , sql , args ) ; return result ; } public static ResultSet executeQuery ( PreparedStatement stmt , String sql , String ... param ) throws SQLException { String args = arrayToString ( param ) ; LOG . debugMessage ( "" , sql , args ) ; long before = System . currentTimeMillis ( ) ; ResultSet results = stmt . executeQuery ( ) ; long time = System . currentTimeMillis ( ) - before ; LOG . debugMessage ( "" , time , "" , sql , args ) ; return results ; } private static String arrayToString ( String ... param ) { if ( param == null ) { return null ; } StringBuilder strParam = new StringBuilder ( ) ; for ( int i = ; i < param . length ; i ++ ) { strParam . append ( param [ i ] ) ; if ( i < param . length - ) { strParam . append ( "" ) ; } } return strParam . toString ( ) ; } } package com . asakusafw . bulkloader . common ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; @ Deprecated public enum CacheUseType { USE ( "" ) , NONE ( "" ) ; private String cacheUseType ; public String getCacheUseType ( ) { return cacheUseType ; } private CacheUseType ( String type ) { this . cacheUseType = type ; } public static CacheUseType find ( String key ) { return CacheUseTypeToCacheUseType . REVERSE_DICTIONARY . get ( key ) ; } private static class CacheUseTypeToCacheUseType { static final Map < String , CacheUseType > REVERSE_DICTIONARY ; static { Map < String , CacheUseType > map = new HashMap < String , CacheUseType > ( ) ; for ( CacheUseType elem : CacheUseType . values ( ) ) { map . put ( elem . getCacheUseType ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } } } package com . asakusafw . bulkloader . common ; import java . io . Closeable ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import com . asakusafw . bulkloader . log . Log ; public class StreamRedirectThread extends Thread { static final Log LOG = new Log ( StreamRedirectThread . class ) ; private final InputStream input ; private final OutputStream output ; private final boolean closeInput ; private final boolean closeOutput ; public StreamRedirectThread ( InputStream input , OutputStream output ) { this ( input , output , false , false ) ; } public StreamRedirectThread ( InputStream input , OutputStream output , boolean closeInput , boolean closeOutput ) { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . input = input ; this . output = output ; this . closeInput = closeInput ; this . closeOutput = closeOutput ; } @ Override public void run ( ) { boolean outputFailed = false ; try { InputStream in = input ; OutputStream out = output ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = in . read ( buf ) ; if ( read == - ) { break ; } if ( outputFailed == false ) { try { out . write ( buf , , read ) ; } catch ( IOException e ) { outputFailed = true ; LOG . warn ( e , "" ) ; } } } } catch ( IOException e ) { LOG . warn ( e , "" ) ; } finally { if ( closeInput ) { close ( input ) ; } if ( closeOutput ) { close ( output ) ; } } } private static void close ( Closeable c ) { try { c . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } package com . asakusafw . bulkloader . common ; import java . util . Collections ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; public enum TsvDeleteType { FALSE ( "" , "" , "" ) , TRUE ( "" , "" , "" ) ; private String symbol ; Set < String > keys ; private TsvDeleteType ( String symbol , String ... alternatives ) { this . symbol = symbol ; this . keys = new HashSet < String > ( ) ; this . keys . add ( symbol ) ; Collections . addAll ( this . keys , alternatives ) ; } public String getSymbol ( ) { return symbol ; } public static TsvDeleteType find ( String key ) { return DeleteTypeToTsvDeleteType . REVERSE_DICTIONARY . get ( key ) ; } private static class DeleteTypeToTsvDeleteType { static final Map < String , TsvDeleteType > REVERSE_DICTIONARY ; static { Map < String , TsvDeleteType > map = new TreeMap < String , TsvDeleteType > ( String . CASE_INSENSITIVE_ORDER ) ; for ( TsvDeleteType elem : TsvDeleteType . values ( ) ) { for ( String key : elem . keys ) { map . put ( key , elem ) ; } } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } } } package com . asakusafw . bulkloader . common ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . net . URLClassLoader ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . TreeMap ; import com . asakusafw . bulkloader . bean . ExportTargetTableBean ; import com . asakusafw . bulkloader . bean . ImportTargetTableBean ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; import com . asakusafw . thundergate . runtime . property . PropertyLoader ; public class JobFlowParamLoader { static final Log LOG = new Log ( JobFlowParamLoader . class ) ; private static final String IMP_TARGET_TABLE = "" ; private static final String IMP_TARGET_COLUMN = "" ; private static final String IMP_SEARCH_CONDITION = "" ; private static final String IMP_CACHE_ID = "" ; private static final String IMP_LOCK_TYPE = "" ; private static final String IMP_LOCKED_OPERATION = "" ; private static final String IMP_BEAN_NAME = "" ; private static final String IMP_HDFS_IMPORT_FILE = "" ; private static final String EXP_TARGET_TABLE = "" ; private static final String EXP_ERROR_TABLE = "" ; private static final String EXP_TSV_COLUMN = "" ; private static final String EXP_EXPORT_TABLE_COLUMN = "" ; private static final String EXP_ERROR_TABLE_COLUMN = "" ; private static final String EXP_KEY_COLUMN = "" ; private static final String EXP_ERROR_COLUMN = "" ; private static final String EXP_ERROR_CODE = "" ; private static final String EXP_BEAN_NAME = "" ; private static final String EXP_HDFS_EXPORT_FILE = "" ; private Map < String , ImportTargetTableBean > importTargetTables ; private Map < String , ExportTargetTableBean > exportTargetTables ; public boolean loadImportParam ( String targetName , String batchId , String jobflowId , boolean isPrimary ) { File propFile = createJobFlowConfFile ( jobflowId , batchId ) ; if ( fetchImporterParams ( targetName , jobflowId , propFile ) == false ) { return false ; } if ( importTargetTables . isEmpty ( ) ) { return true ; } return checkImportParam ( importTargetTables , targetName , jobflowId , propFile . getPath ( ) , isPrimary ) ; } public boolean loadExtractParam ( String targetName , String batchId , String jobflowId ) { File propFile = createJobFlowConfFile ( jobflowId , batchId ) ; if ( fetchImporterParams ( targetName , jobflowId , propFile ) == false ) { return false ; } if ( importTargetTables . isEmpty ( ) ) { return true ; } for ( Map . Entry < String , ImportTargetTableBean > entry : importTargetTables . entrySet ( ) ) { ImportTargetTableBean tableInfo = entry . getValue ( ) ; tableInfo . setSearchCondition ( null ) ; } boolean result = checkImportParam ( importTargetTables , targetName , jobflowId , propFile . getPath ( ) , true ) ; return result ; } public boolean loadCacheBuildParam ( String targetName , String batchId , String jobflowId ) { File propFile = createJobFlowConfFile ( jobflowId , batchId ) ; if ( fetchImporterParams ( targetName , jobflowId , propFile ) == false ) { return false ; } Map < String , ImportTargetTableBean > cacheTables = new HashMap < String , ImportTargetTableBean > ( ) ; for ( Map . Entry < String , ImportTargetTableBean > entry : importTargetTables . entrySet ( ) ) { String tableName = entry . getKey ( ) ; ImportTargetTableBean tableInfo = entry . getValue ( ) ; if ( tableInfo . getCacheId ( ) == null ) { LOG . debugMessage ( "" , tableName ) ; continue ; } tableInfo . setLockType ( ImportTableLockType . NONE ) ; tableInfo . setLockedOperation ( ImportTableLockedOperation . FORCE ) ; cacheTables . put ( tableName , tableInfo ) ; } if ( cacheTables . isEmpty ( ) ) { return true ; } boolean result = checkImportParam ( cacheTables , targetName , jobflowId , propFile . getPath ( ) , false ) ; return result ; } private boolean fetchImporterParams ( String targetName , String jobflowId , File propFile ) { Properties properties ; try { properties = getImportProp ( propFile , targetName ) ; } catch ( IOException e ) { LOG . error ( e , "" , "" , targetName , jobflowId , propFile . getPath ( ) ) ; return false ; } if ( ! createImportTargetTableBean ( properties , targetName , jobflowId , propFile . getPath ( ) ) ) { return false ; } return true ; } private boolean createImportTargetTableBean ( Properties importProp , String targetName , String jobflowId , String propFilePath ) { importTargetTables = new TreeMap < String , ImportTargetTableBean > ( ) ; String strTargetTable = importProp . getProperty ( IMP_TARGET_TABLE ) ; if ( strTargetTable == null || strTargetTable . isEmpty ( ) ) { return true ; } List < String > targetTable = spritComma ( strTargetTable ) ; for ( String element : targetTable ) { importTargetTables . put ( element , new ImportTargetTableBean ( ) ) ; } Set < ? > set = importProp . keySet ( ) ; for ( Object objKey : set ) { String key = ( String ) objKey ; if ( ! IMP_TARGET_TABLE . equals ( key ) ) { String tableName = key . substring ( , key . indexOf ( '' ) ) ; int start = tableName . length ( ) + ; int end = key . indexOf ( '' , start ) - ; String keyMeans = key . substring ( start + end ) ; ImportTargetTableBean bean = importTargetTables . get ( tableName ) ; if ( bean == null ) { continue ; } String value = importProp . getProperty ( key ) ; if ( value == null || value . equals ( "" ) ) { continue ; } if ( IMP_TARGET_COLUMN . equals ( keyMeans ) ) { bean . setImportTargetColumns ( spritComma ( value ) ) ; } else if ( IMP_SEARCH_CONDITION . equals ( keyMeans ) ) { bean . setSearchCondition ( value ) ; } else if ( IMP_CACHE_ID . equals ( keyMeans ) ) { if ( value . trim ( ) . isEmpty ( ) == false ) { bean . setCacheId ( value ) ; } } else if ( IMP_LOCK_TYPE . equals ( keyMeans ) ) { bean . setLockType ( ImportTableLockType . find ( value ) ) ; } else if ( IMP_LOCKED_OPERATION . equals ( keyMeans ) ) { bean . setLockedOperation ( ImportTableLockedOperation . find ( value ) ) ; } else if ( IMP_BEAN_NAME . equals ( keyMeans ) ) { try { bean . setImportTargetType ( loadClass ( value ) ) ; } catch ( ClassNotFoundException e ) { LOG . error ( e , "" , "" , targetName , jobflowId , propFilePath ) ; return false ; } } else if ( IMP_HDFS_IMPORT_FILE . equals ( keyMeans ) ) { bean . setDfsFilePath ( value ) ; } else { LOG . warn ( "" , "" + key , targetName , jobflowId , tableName , propFilePath ) ; continue ; } } } for ( Map . Entry < String , ImportTargetTableBean > entry : importTargetTables . entrySet ( ) ) { ImportTargetTableBean bean = entry . getValue ( ) ; if ( bean . getCacheId ( ) != null ) { if ( ThunderGateCacheSupport . class . isAssignableFrom ( bean . getImportTargetType ( ) ) == false ) { LOG . error ( "" , MessageFormat . format ( "" , ThunderGateCacheSupport . class . getName ( ) , bean . getImportTargetType ( ) . getName ( ) ) , targetName , jobflowId , propFilePath ) ; return false ; } if ( bean . getSearchCondition ( ) != null && bean . getSearchCondition ( ) . trim ( ) . isEmpty ( ) == false ) { LOG . error ( "" , MessageFormat . format ( "" , bean . getLockedOperation ( ) ) , targetName , jobflowId , propFilePath ) ; return false ; } if ( bean . getLockedOperation ( ) == ImportTableLockedOperation . OFF ) { LOG . error ( "" , MessageFormat . format ( "" , bean . getLockedOperation ( ) ) , targetName , jobflowId , propFilePath ) ; return false ; } } } return true ; } public boolean loadExportParam ( String targetName , String batchId , String jobflowId ) { File propFile = createJobFlowConfFile ( jobflowId , batchId ) ; Properties exportProp = null ; try { exportProp = getExportProp ( propFile , targetName ) ; } catch ( IOException e ) { LOG . error ( e , "" , "" , targetName , jobflowId , propFile . getPath ( ) ) ; return false ; } if ( ! createExportTargetTableBean ( exportProp , targetName , jobflowId , propFile . getPath ( ) ) ) { return false ; } else { if ( exportTargetTables . isEmpty ( ) ) { return true ; } } return checkExportParam ( exportTargetTables , targetName , jobflowId , propFile . getPath ( ) ) ; } private boolean createExportTargetTableBean ( Properties exportProp , String targetName , String jobflowId , String propFilePath ) { exportTargetTables = new TreeMap < String , ExportTargetTableBean > ( ) ; String strTargetTable = exportProp . getProperty ( EXP_TARGET_TABLE ) ; if ( strTargetTable == null || strTargetTable . equals ( "" ) ) { return true ; } List < String > targetTable = spritComma ( strTargetTable ) ; for ( String element : targetTable ) { exportTargetTables . put ( element , new ExportTargetTableBean ( ) ) ; } Iterator < ? > it = exportProp . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { String key = ( String ) it . next ( ) ; if ( ! EXP_TARGET_TABLE . equals ( key ) ) { String tableName = key . substring ( , key . indexOf ( '' ) ) ; int start = tableName . length ( ) + ; int end = key . indexOf ( '' , start ) - ; String keyMeans = key . substring ( start + end ) ; ExportTargetTableBean bean = exportTargetTables . get ( tableName ) ; if ( bean == null ) { continue ; } String value = exportProp . getProperty ( key ) ; if ( value == null || value . equals ( "" ) ) { continue ; } if ( EXP_ERROR_TABLE . equals ( keyMeans ) ) { bean . setErrorTableName ( value ) ; if ( ! value . isEmpty ( ) ) { bean . setDuplicateCheck ( true ) ; } } else if ( EXP_TSV_COLUMN . equals ( keyMeans ) ) { bean . setExportTsvColumns ( spritComma ( value ) ) ; } else if ( EXP_EXPORT_TABLE_COLUMN . equals ( keyMeans ) ) { bean . setExportTableColumns ( spritComma ( value ) ) ; } else if ( EXP_ERROR_TABLE_COLUMN . equals ( keyMeans ) ) { bean . setErrorTableColumns ( spritComma ( value ) ) ; } else if ( EXP_KEY_COLUMN . equals ( keyMeans ) ) { bean . setKeyColumns ( spritComma ( value ) ) ; } else if ( EXP_ERROR_COLUMN . equals ( keyMeans ) ) { bean . setErrorCodeColumn ( value ) ; } else if ( EXP_ERROR_CODE . equals ( keyMeans ) ) { bean . setErrorCode ( value ) ; } else if ( EXP_BEAN_NAME . equals ( keyMeans ) ) { try { bean . setExportTargetType ( loadClass ( value ) ) ; } catch ( ClassNotFoundException e ) { LOG . error ( e , "" , "" , targetName , jobflowId , propFilePath ) ; return false ; } } else if ( EXP_HDFS_EXPORT_FILE . equals ( keyMeans ) ) { List < String > path = spritComma ( value ) ; List < String > pathList = new ArrayList < String > ( path ) ; bean . setDfsFilePaths ( pathList ) ; } else { LOG . warn ( "" , "" + key , targetName , jobflowId , tableName , propFilePath ) ; continue ; } } } return true ; } private Class < ? > loadClass ( String className ) throws ClassNotFoundException { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( classLoader != null ) { return Class . forName ( className , false , classLoader ) ; } else { return Class . forName ( className ) ; } } public boolean loadRecoveryParam ( String targetName , String batchId , String jobflowId ) { File propFile = createJobFlowConfFile ( jobflowId , batchId ) ; Properties importProp = null ; Properties exportProp = null ; try { importProp = getImportProp ( propFile , targetName ) ; exportProp = getExportProp ( propFile , targetName ) ; } catch ( IOException e ) { LOG . error ( e , "" , "" , targetName , jobflowId , propFile . getPath ( ) ) ; return false ; } ClassLoader jobflowLoader ; try { final URL jarLocation = propFile . getAbsoluteFile ( ) . getCanonicalFile ( ) . toURI ( ) . toURL ( ) ; jobflowLoader = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) { URLClassLoader loader = new URLClassLoader ( new URL [ ] { jarLocation } , getClass ( ) . getClassLoader ( ) ) ; return loader ; } } ) ; } catch ( IOException e ) { LOG . debugMessage ( "" , propFile ) ; jobflowLoader = getClass ( ) . getClassLoader ( ) ; } ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( jobflowLoader ) ; if ( ! createImportTargetTableBean ( importProp , targetName , jobflowId , propFile . getPath ( ) ) ) { return false ; } if ( ! createExportTargetTableBean ( exportProp , targetName , jobflowId , propFile . getPath ( ) ) ) { return false ; } return checkRecoveryParam ( exportTargetTables , targetName , jobflowId , propFile . getPath ( ) ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( contextClassLoader ) ; } } private boolean checkRecoveryParam ( Map < String , ExportTargetTableBean > tables , String targetName , String jobflowId , String fileName ) { for ( Map . Entry < String , ExportTargetTableBean > entry : tables . entrySet ( ) ) { String tableName = entry . getKey ( ) ; ExportTargetTableBean bean = entry . getValue ( ) ; if ( isEmptyOrHasEmptyString ( bean . getExportTsvColumn ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( isEmptyOrHasEmptyString ( bean . getExportTableColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( columnCheck ( bean . getExportTableColumns ( ) , Constants . getTemporarySidColumnName ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( bean . isDuplicateCheck ( ) ) { if ( isEmptyOrHasEmptyString ( bean . getErrorTableColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } String errCodeColumn = bean . getErrorCodeColumn ( ) ; if ( isEmpty ( errCodeColumn ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } else { if ( findArray ( errCodeColumn , bean . getExportTableColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( findArray ( errCodeColumn , bean . getErrorTableColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } } if ( isEmpty ( bean . getErrorCode ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } } } return true ; } private List < String > spritComma ( String str ) { String [ ] array = str . split ( "" ) ; return Arrays . asList ( array ) ; } private String createSearchCondition ( String serchCondition , String targetName , String jobflowId , String fileName ) { VariableTable variables = Constants . createVariableTable ( ) ; try { return variables . parse ( serchCondition , true ) ; } catch ( IllegalArgumentException e ) { LOG . error ( "" , "" + serchCondition , targetName , jobflowId , fileName ) ; return null ; } } public boolean checkImportParam ( Map < String , ImportTargetTableBean > tables , String targetName , String jobflowId , String fileName , boolean isPrimary ) { for ( Map . Entry < String , ImportTargetTableBean > entry : tables . entrySet ( ) ) { String tableName = entry . getKey ( ) ; ImportTargetTableBean bean = entry . getValue ( ) ; if ( isEmptyOrHasEmptyString ( bean . getImportTargetColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } ImportTableLockType lockType = bean . getLockType ( ) ; if ( lockType == null ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } else { if ( ! isPrimary && ! ImportTableLockType . NONE . equals ( lockType ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } } ImportTableLockedOperation operation = bean . getLockedOperation ( ) ; if ( operation == null ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } else { if ( ! isPrimary && ! ImportTableLockedOperation . FORCE . equals ( operation ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } } if ( lockType . equals ( ImportTableLockType . TABLE ) && operation . equals ( ImportTableLockedOperation . OFF ) || lockType . equals ( ImportTableLockType . TABLE ) && operation . equals ( ImportTableLockedOperation . FORCE ) || lockType . equals ( ImportTableLockType . RECORD ) && operation . equals ( ImportTableLockedOperation . FORCE ) || lockType . equals ( ImportTableLockType . NONE ) && operation . equals ( ImportTableLockedOperation . OFF ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } Class < ? > beanClass = bean . getImportTargetType ( ) ; if ( beanClass == null ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } String path = bean . getDfsFilePath ( ) ; if ( isEmpty ( path ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } else { try { VariableTable variables = Constants . createVariableTable ( ) ; variables . defineVariable ( Constants . HDFS_PATH_VARIABLE_USER , "" ) ; variables . defineVariable ( Constants . HDFS_PATH_VARIABLE_EXECUTION_ID , "" ) ; String dummyPath = variables . parse ( path , false ) ; new URI ( dummyPath ) . normalize ( ) ; } catch ( URISyntaxException e ) { LOG . error ( e , "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } } String condition = bean . getSearchCondition ( ) ; if ( condition != null ) { condition = createSearchCondition ( condition , targetName , jobflowId , fileName ) ; if ( condition == null ) { return false ; } else { bean . setSearchCondition ( condition ) ; } } } return true ; } public boolean checkExportParam ( Map < String , ExportTargetTableBean > tables , String targetName , String jobflowId , String fileName ) { for ( Map . Entry < String , ExportTargetTableBean > entry : tables . entrySet ( ) ) { String tableName = entry . getKey ( ) ; ExportTargetTableBean bean = entry . getValue ( ) ; if ( isEmptyOrHasEmptyString ( bean . getExportTsvColumn ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( isEmptyOrHasEmptyString ( bean . getExportTableColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( columnCheck ( bean . getExportTableColumns ( ) , Constants . getTemporarySidColumnName ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } List < String > systemColumns = Constants . getSystemColumns ( ) ; List < String > allColumn = new ArrayList < String > ( bean . getExportTsvColumn ( ) ) ; allColumn . addAll ( systemColumns ) ; if ( ! includeColumnCheck ( bean . getExportTableColumns ( ) , allColumn ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( bean . isDuplicateCheck ( ) ) { if ( isEmptyOrHasEmptyString ( bean . getErrorTableColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( ! includeColumnCheck ( bean . getErrorTableColumns ( ) , allColumn ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( isEmptyOrHasEmptyString ( bean . getKeyColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } String errCodeColumn = bean . getErrorCodeColumn ( ) ; if ( isEmpty ( errCodeColumn ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } else { if ( findArray ( errCodeColumn , bean . getExportTableColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } if ( findArray ( errCodeColumn , bean . getErrorTableColumns ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } } if ( isEmpty ( bean . getErrorCode ( ) ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } } Class < ? > beanClass = bean . getExportTargetType ( ) ; if ( beanClass == null ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } List < String > path = bean . getDfsFilePaths ( ) ; if ( path == null || path . isEmpty ( ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } else { for ( String element : path ) { if ( isEmpty ( element ) ) { LOG . error ( "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } else { try { VariableTable variables = Constants . createVariableTable ( ) ; variables . defineVariable ( Constants . HDFS_PATH_VARIABLE_USER , "" ) ; variables . defineVariable ( Constants . HDFS_PATH_VARIABLE_EXECUTION_ID , "" ) ; String dummyPath = variables . parse ( element , false ) ; new URI ( dummyPath ) . normalize ( ) ; } catch ( URISyntaxException e ) { LOG . error ( e , "" , "" , targetName , jobflowId , tableName , fileName ) ; return false ; } } } } } return true ; } private boolean includeColumnCheck ( List < String > includeColumn , List < String > allColumn ) { boolean result = true ; for ( String including : includeColumn ) { boolean search = false ; for ( String column : allColumn ) { if ( including . equals ( column ) ) { search = true ; break ; } } if ( ! search ) { LOG . error ( "" , including ) ; result = false ; } } return result ; } private boolean columnCheck ( List < String > exportTableColumn , String propKeySysColumnTempSid ) { if ( exportTableColumn == null || exportTableColumn . size ( ) == ) { return false ; } return exportTableColumn . contains ( propKeySysColumnTempSid ) ; } private boolean findArray ( String str , List < String > list ) { return list . contains ( str ) ; } private boolean isEmptyOrHasEmptyString ( List < String > tsvColumn ) { if ( tsvColumn == null || tsvColumn . size ( ) == ) { return true ; } else { for ( String element : tsvColumn ) { if ( isEmpty ( element ) ) { return true ; } } } return false ; } private boolean isEmpty ( String str ) { if ( str == null ) { return true ; } if ( str . isEmpty ( ) ) { return true ; } return false ; } public Map < String , ImportTargetTableBean > getImportTargetTables ( ) { return importTargetTables ; } public Map < String , ExportTargetTableBean > getExportTargetTables ( ) { return exportTargetTables ; } protected Properties getImportProp ( File file , String targetName ) throws IOException { PropertyLoader loader = new PropertyLoader ( file , targetName ) ; try { return loader . loadImporterProperties ( ) ; } finally { loader . close ( ) ; } } protected Properties getExportProp ( File file , String targetName ) throws IOException { PropertyLoader loader = new PropertyLoader ( file , targetName ) ; try { return loader . loadExporterProperties ( ) ; } finally { loader . close ( ) ; } } protected static File createJobFlowConfFile ( String jobflowId , String batchId ) { StringBuffer fileName = new StringBuffer ( Constants . DSL_PROP_PREFIX ) ; fileName . append ( jobflowId ) ; fileName . append ( Constants . DSL_PROP_EXTENSION ) ; String appHome = ConfigurationLoader . getEnvProperty ( Constants . ASAKUSA_HOME ) ; File file1 = new File ( appHome , Constants . JOBFLOW_PACKAGE_PATH_BEFORE ) ; File file2 = new File ( file1 , batchId ) ; File file3 = new File ( file2 , Constants . JOBFLOW_PACKAGE_PATH_AFTER ) ; File file4 = new File ( file3 , fileName . toString ( ) ) ; return file4 ; } } package com . asakusafw . bulkloader . common ; import java . io . File ; import java . util . List ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; import com . asakusafw . bulkloader . log . LogInitializer ; public final class BulkLoaderInitializer { static final Log LOG = new Log ( BulkLoaderInitializer . class ) ; private BulkLoaderInitializer ( ) { return ; } public static boolean initDBServer ( String jobflowId , String executionId , List < String > properties , String targetName ) { return initialize ( jobflowId , executionId , properties , true , false , true , targetName ) ; } public static boolean initHadoopCluster ( String jobflowId , String executionId , List < String > properties ) { return initialize ( jobflowId , executionId , properties , false , true , false , null ) ; } private static boolean initialize ( String jobflowId , String executionId , List < String > properties , boolean doDBPropCheck , boolean doHCPropCheck , boolean doDbConnInit , String targetName ) { try { ConfigurationLoader . init ( properties , doDBPropCheck , doHCPropCheck ) ; Constants . setSystemColumn ( ) ; } catch ( BulkLoaderSystemException e ) { if ( initLog ( jobflowId , executionId , targetName ) ) { LOG . log ( e ) ; return false ; } else { printPropLoadError ( jobflowId , executionId , targetName , properties , e ) ; return false ; } } catch ( Exception e ) { printPropLoadError ( jobflowId , executionId , targetName , properties , e ) ; return false ; } if ( ! initLog ( jobflowId , executionId , targetName ) ) { return false ; } if ( doDbConnInit ) { try { ConfigurationLoader . loadJDBCProp ( targetName ) ; DBConnection . init ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_JDBC_DRIVER ) ) ; } catch ( BulkLoaderSystemException e ) { LOG . log ( e ) ; return false ; } } return true ; } private static boolean initLog ( String jobflowId , String executionId , String targetName ) { String logConfFilePath = null ; try { logConfFilePath = ConfigurationLoader . getProperty ( Constants . PROP_KEY_LOG_CONF_PATH ) ; if ( new File ( logConfFilePath ) . exists ( ) == false ) { String home = ConfigurationLoader . getEnvProperty ( Constants . ASAKUSA_HOME ) ; if ( home != null ) { File file = new File ( new File ( home ) , logConfFilePath ) ; if ( file . exists ( ) ) { logConfFilePath = file . getPath ( ) ; } } } LogInitializer . execute ( logConfFilePath ) ; return true ; } catch ( Exception e ) { System . err . println ( "" + e . getMessage ( ) + "" + jobflowId + "" + executionId + "" + targetName ) ; System . err . println ( "" + logConfFilePath ) ; e . printStackTrace ( ) ; return false ; } } private static void printPropLoadError ( String jobflowId , String executionId , String targetName , List < String > properties , Exception e ) { System . err . println ( "" + e . getMessage ( ) + "" + jobflowId + "" + executionId + "" + targetName ) ; System . err . println ( "" + System . getenv ( ) ) ; if ( properties == null ) { System . err . println ( "" ) ; } else { for ( int i = ; i < properties . size ( ) ; i ++ ) { System . err . println ( "" + i + "" + properties . get ( i ) ) ; } } e . printStackTrace ( ) ; } } package com . asakusafw . bulkloader . common ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public enum ImportTableLockedOperation { OFF ( "" ) , FORCE ( "" ) , ERROR ( "" ) ; private String lockedOperation ; public String getLockedOperation ( ) { return lockedOperation ; } private ImportTableLockedOperation ( String ope ) { this . lockedOperation = ope ; } public static ImportTableLockedOperation find ( String key ) { return LockedOperationToImportTableLockedOperation . REVERSE_DICTIONARY . get ( key ) ; } private static class LockedOperationToImportTableLockedOperation { static final Map < String , ImportTableLockedOperation > REVERSE_DICTIONARY ; static { Map < String , ImportTableLockedOperation > map = new HashMap < String , ImportTableLockedOperation > ( ) ; for ( ImportTableLockedOperation elem : ImportTableLockedOperation . values ( ) ) { map . put ( elem . getLockedOperation ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } } } package com . asakusafw . bulkloader . common ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . List ; import com . asakusafw . bulkloader . bean . ExportTempTableBean ; import com . asakusafw . bulkloader . bean . ExporterBean ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . bulkloader . log . Log ; public final class DBAccessUtil { static final Log LOG = new Log ( DBAccessUtil . class ) ; private DBAccessUtil ( ) { return ; } public static String createRecordLockTableName ( String tableName ) { StringBuilder sb = new StringBuilder ( tableName ) ; sb . append ( "" ) ; return sb . toString ( ) ; } public static String createDuplicateFlgTableName ( String tempTableName ) { StringBuilder sb = new StringBuilder ( tempTableName ) ; sb . append ( Constants . DUPLECATE_FLG_TABLE_END ) ; return sb . toString ( ) ; } public static String selectJobFlowSid ( String executionId ) throws BulkLoaderSystemException { String sql = "" + "" + "" ; Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; String jobflowSid = null ; try { conn = DBConnection . getConnection ( ) ; stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , executionId ) ; rs = DBConnection . executeQuery ( stmt , sql , new String [ ] { executionId } ) ; if ( rs . next ( ) ) { jobflowSid = rs . getString ( "" ) ; } return jobflowSid ; } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , DBAccessUtil . class , sql , executionId ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; DBConnection . closeConn ( conn ) ; } } public static List < ExporterBean > selectRunningJobFlow ( String executionId ) throws BulkLoaderSystemException { boolean hasCondition = false ; if ( executionId != null ) { hasCondition = true ; } String sql = "" + "" ; if ( hasCondition ) { sql = sql + "" ; } Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; try { conn = DBConnection . getConnection ( ) ; stmt = conn . prepareStatement ( sql ) ; if ( hasCondition ) { stmt . setString ( , executionId ) ; } rs = DBConnection . executeQuery ( stmt , sql , new String [ ] { executionId } ) ; List < ExporterBean > beanList = new ArrayList < ExporterBean > ( ) ; while ( rs . next ( ) ) { ExporterBean bean = new ExporterBean ( ) ; bean . setJobflowSid ( rs . getString ( "" ) ) ; bean . setBatchId ( rs . getString ( "" ) ) ; bean . setJobflowId ( rs . getString ( "" ) ) ; bean . setTargetName ( rs . getString ( "" ) ) ; bean . setExecutionId ( rs . getString ( "" ) ) ; beanList . add ( bean ) ; } return beanList ; } catch ( SQLException e ) { if ( hasCondition ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , DBAccessUtil . class , sql , executionId ) ; } else { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , DBAccessUtil . class , sql ) ; } } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; DBConnection . closeConn ( conn ) ; } } public static List < ExportTempTableBean > getExportTempTable ( String jobflowSid ) throws BulkLoaderSystemException { String sql = "" + "" + "" ; Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; List < ExportTempTableBean > beanList = new ArrayList < ExportTempTableBean > ( ) ; try { conn = DBConnection . getConnection ( ) ; stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , jobflowSid ) ; rs = DBConnection . executeQuery ( stmt , sql , new String [ ] { jobflowSid } ) ; while ( rs . next ( ) ) { ExportTempTableBean bean = new ExportTempTableBean ( ) ; bean . setJobflowSid ( jobflowSid ) ; bean . setExportTableName ( rs . getString ( "" ) ) ; bean . setTemporaryTableName ( rs . getString ( "" ) ) ; bean . setDuplicateFlagTableName ( rs . getString ( "" ) ) ; bean . setTempTableStatus ( ExportTempTableStatus . find ( rs . getString ( "" ) ) ) ; beanList . add ( bean ) ; } } catch ( SQLException e ) { throw BulkLoaderSystemException . createInstanceCauseBySQLException ( e , DBAccessUtil . class , sql , jobflowSid ) ; } finally { DBConnection . closeRs ( rs ) ; DBConnection . closePs ( stmt ) ; DBConnection . closeConn ( conn ) ; } return beanList ; } public static List < String > delSystemColumn ( List < String > tableColumn ) { return delColumn ( tableColumn , Constants . getSystemColumns ( ) ) ; } public static List < String > delErrorSystemColumn ( List < String > tableColumn , String errorCodeColumn ) { List < String > errorSystemColumns = Constants . getErrorSystemColumns ( ) ; List < String > sysColumn = new ArrayList < String > ( errorSystemColumns ) ; sysColumn . add ( errorCodeColumn ) ; return delColumn ( tableColumn , sysColumn ) ; } private static List < String > delColumn ( List < String > tableColumn , List < String > delColumn ) { List < String > resultList = new ArrayList < String > ( ) ; int tableCount = tableColumn . size ( ) ; for ( int i = ; i < tableCount ; i ++ ) { boolean isSystemColumn = false ; int columnCount = delColumn . size ( ) ; for ( int j = ; j < columnCount ; j ++ ) { if ( delColumn . get ( j ) . equals ( tableColumn . get ( i ) ) ) { isSystemColumn = true ; break ; } } if ( ! isSystemColumn ) { resultList . add ( tableColumn . get ( i ) ) ; } } return resultList ; } public static String joinColumnArray ( List < String > columnArray ) { if ( columnArray == null || columnArray . size ( ) == ) { return null ; } StringBuilder column = new StringBuilder ( ) ; int columnSize = columnArray . size ( ) ; for ( int i = ; i < columnSize ; i ++ ) { column . append ( columnArray . get ( i ) ) ; if ( i + < columnSize ) { column . append ( "" ) ; } } return column . toString ( ) ; } public static boolean getJobflowInstanceLock ( String executionId , Connection conn ) { String sql = "" ; PreparedStatement stmt = null ; LOG . info ( "" , sql , executionId ) ; try { stmt = conn . prepareStatement ( sql ) ; stmt . setString ( , executionId ) ; DBConnection . executeUpdate ( stmt , sql , executionId ) ; return true ; } catch ( SQLException e ) { try { DBConnection . rollback ( conn ) ; } catch ( BulkLoaderSystemException e1 ) { e1 . printStackTrace ( ) ; } return false ; } finally { DBConnection . closePs ( stmt ) ; } } public static void releaseJobflowInstanceLock ( Connection conn ) { LOG . info ( "" ) ; try { DBConnection . rollback ( conn ) ; } catch ( BulkLoaderSystemException e ) { e . printStackTrace ( ) ; } finally { DBConnection . closeConn ( conn ) ; } } public static String getTSVFileFormat ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "" ) ; sb . append ( "" ) ; sb . append ( "" ) ; sb . append ( "" ) ; sb . append ( "" ) ; return sb . toString ( ) ; } } package com . asakusafw . bulkloader . common ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . hadoop . io . SequenceFile . CompressionType ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . runtime . util . VariableTable . RedefineStrategy ; public final class Constants { public static final String ASAKUSA_HOME = "" ; public static final String THUNDER_GATE_HOME = "" ; public static final String ENV_ARGS = "" ; public static final int EXIT_CODE_SUCCESS = ; public static final int EXIT_CODE_ERROR = ; public static final int EXIT_CODE_WARNING = ; public static final int EXIT_CODE_RETRYABLE = ; public static final List < String > PROPERTIES_DB = Arrays . asList ( new String [ ] { "" } ) ; public static final List < String > PROPERTIES_HC = Arrays . asList ( new String [ ] { "" } ) ; public static final String PROP_KEY_LOG_CONF_PATH = "" ; @ Deprecated public static final String PROP_KEY_HDFS_PROTCOL_HOST = "" ; public static final String PROP_PREFIX_HC_ENV = "" ; public static final String PROP_KEY_BASE_PATH = "" ; public static final String PROP_KEY_SSH_PATH = "" ; public static final String PROP_KEY_NAMENODE_HOST = "" ; public static final String PROP_KEY_NAMENODE_USER = "" ; public static final String PROP_KEY_IMP_FILE_DIR = "" ; @ Deprecated public static final String PROP_KEY_EXT_SHELL_NAME = "" ; @ Deprecated public static final String PROP_KEY_CACHE_INFO_SHELL_NAME = "" ; @ Deprecated public static final String PROP_KEY_DELETE_CACHE_SHELL_NAME = "" ; public static final String PROP_KEY_IMP_FILE_COMP_TYPE = "" ; public static final String PROP_KEY_IMP_FILE_COMP_BUFSIZE = "" ; public static final String PROP_KEY_IMP_RETRY_COUNT = "" ; public static final String PROP_KEY_IMP_RETRY_INTERVAL = "" ; public static final String PROP_KEY_EXP_FILE_DIR = "" ; @ Deprecated public static final String PROP_KEY_COL_SHELL_NAME = "" ; public static final String PROP_KEY_EXP_FILE_COMP_BUFSIZE = "" ; public static final String PROP_KEY_EXP_RETRY_COUNT = "" ; public static final String PROP_KEY_EXP_RETRY_INTERVAL = "" ; public static final String PROP_KEY_EXP_COPY_MAX_RECORD = "" ; public static final String PROP_KEY_SYS_COLUMN_SID = "" ; public static final String PROP_KEY_SYS_COLUMN_VERSION_NO = "" ; public static final String PROP_KEY_SYS_COLUMN_RGST_DATE = "" ; public static final String PROP_KEY_SYS_COLUMN_UPDT_DATE = "" ; public static final String PROP_KEY_SYS_COLUMN_TEMP_SID = "" ; public static final String PROP_KEY_IMPORT_TSV_DELETE = "" ; public static final String PROP_KEY_EXPORT_TSV_DELETE = "" ; public static final String PROP_KEY_JDBC_DRIVER = "" ; public static final String PROP_KEY_DB_URL = "" ; public static final String PROP_KEY_DB_USER = "" ; public static final String PROP_KEY_DB_PASSWORD = "" ; public static final String PROP_KEY_NAME_DB_PRAM = "" ; public static final String PROP_KEY_IMP_SEQ_FILE_COMP_TYPE = "" ; @ Deprecated public static final String PROP_KEY_CACHE_BUILDER_SHELL_NAME = "" ; public static final String PROP_KEY_CACHE_BUILDER_PARALLEL = "" ; public static final String PROP_KEY_EXP_FILE_COMP_TYPE = "" ; public static final String PROP_KEY_EXP_LOAD_MAX_SIZE = "" ; @ Deprecated public static final String PROP_KEY_WORKINGDIR_USE = "" ; public static final String PROP_DEFAULT_LOG_CONF_PATH = "" ; public static final String PROP_DEFAULT_IMP_FILE_COMP_TYPE = FileCompType . STORED . getSymbol ( ) ; public static final String PROP_DEFAULT_IMP_FILE_COMP_BUFSIZE = "" ; public static final String PROP_DEFAULT_IMP_RETRY_COUNT = "" ; public static final String PROP_DEFAULT_IMP_RETRY_INTERVAL = "" ; public static final String PROP_DEFAULT_EXP_FILE_COMP_TYPE = FileCompType . STORED . getSymbol ( ) ; public static final String PROP_DEFAULT_EXP_FILE_COMP_BUFSIZE = "" ; public static final String PROP_DEFAULT_EXP_RETRY_COUNT = "" ; public static final String PROP_DEFAULT_EXP_RETRY_INTERVAL = "" ; public static final String PROP_DEFAULT_EXP_LOAD_MAX_SIZE = "" ; public static final String PROP_DEFAULT_EXP_COPY_MAX_RECORD = "" ; public static final String PROP_DEFAULT_WORKINGDIR_USE = "" ; public static final String PROP_DEFAULT_IMPORT_TSV_DELETE = TsvDeleteType . TRUE . getSymbol ( ) ; public static final String PROP_DEFAULT_EXPORT_TSV_DELETE = TsvDeleteType . TRUE . getSymbol ( ) ; public static final String PROP_DEFAULT_IMP_SEQ_FILE_COMP_TYPE = CompressionType . NONE . name ( ) ; public static final String PROP_DEFAULT_CACHE_BUILDER_PARALLEL = "" ; public static final String PATH_REMOTE_ROOT = "" ; public static final String PATH_REMOTE_EXTRACTOR = "" ; public static final String PATH_REMOTE_COLLECTOR = "" ; public static final String PATH_REMOTE_CACHE_INFO = "" ; public static final String PATH_REMOTE_CACHE_DELETE = "" ; public static final String PATH_LOCAL_CACHE_BUILD = "" ; public static final String JDBC_PROP_NAME = "" ; public static final String LOG_MESSAGE_FILE = "" ; public static final String PROP_FILE_PATH = "" ; public static final String JOBFLOW_PACKAGE_PATH_BEFORE = "" ; public static final String JOBFLOW_PACKAGE_PATH_AFTER = "" ; public static final String IMPORT_FILE_PREFIX = "" ; public static final String IMPORT_FILE_EXTENSION = "" ; public static final String IMPORT_FILE_DELIMITER = "" ; public static final String EXPORT_FILE_PREFIX = "" ; public static final String EXPORT_FILE_DELIMITER = "" ; public static final String EXPORT_FILE_EXTENSION = "" ; public static final String DSL_PROP_PREFIX = "" ; public static final String DSL_PROP_EXTENSION = "" ; @ Deprecated public static final String HDFSFIXED_PATH = "" ; public static final String HDFS_PATH_VARIABLE_USER = "" ; public static final String HDFS_PATH_VARIABLE_EXECUTION_ID = "" ; public static final String EXP_TEMP_TABLE_PREIX = "" ; public static final String EXPORT_TEMP_TABLE_DELIMITER = "" ; public static final String DUPLECATE_FLG_TABLE_END = "" ; public static List < String > getSystemColumns ( ) { List < String > list = new ArrayList < String > ( ) ; list . add ( Constants . getSidColumnName ( ) ) ; list . add ( Constants . getVersionColumnName ( ) ) ; list . add ( Constants . getRegisteredDateTimeColumnName ( ) ) ; list . add ( Constants . getUpdatedDateTimeColumnName ( ) ) ; return list ; } public static List < String > getErrorSystemColumns ( ) { List < String > list = new ArrayList < String > ( ) ; list . add ( Constants . getSidColumnName ( ) ) ; list . add ( Constants . getVersionColumnName ( ) ) ; list . add ( Constants . getRegisteredDateTimeColumnName ( ) ) ; list . add ( Constants . getUpdatedDateTimeColumnName ( ) ) ; return list ; } private static String sidColumnName = "" ; private static String versionColumnName = "" ; private static String registeredDateTimeColumnName = "" ; private static String updatedDateTimeColumnName = "" ; private static String temporarySidColumnName = "" ; public static final long SYS_COLUMN_DEFAULT_VERSION_NO = ; public static final long SYS_COLUMN_INCREMENT_VERSION_NO = ; public static final String SUB_PROCESS_CHAR_SET = "" ; private Constants ( ) { return ; } public static void setSystemColumn ( ) { String sid = ConfigurationLoader . getProperty ( PROP_KEY_SYS_COLUMN_SID ) ; if ( ! isEmpty ( sid ) ) { setSidColumnName ( sid ) ; } String versionNo = ConfigurationLoader . getProperty ( PROP_KEY_SYS_COLUMN_VERSION_NO ) ; if ( ! isEmpty ( versionNo ) ) { setVersionColumnName ( versionNo ) ; } String rgstDate = ConfigurationLoader . getProperty ( PROP_KEY_SYS_COLUMN_RGST_DATE ) ; if ( ! isEmpty ( rgstDate ) ) { setRegisteredDateTimeColumnName ( rgstDate ) ; } String updtDateDate = ConfigurationLoader . getProperty ( PROP_KEY_SYS_COLUMN_UPDT_DATE ) ; if ( ! isEmpty ( updtDateDate ) ) { setUpdatedDateTimeColumnName ( updtDateDate ) ; } String tempSid = ConfigurationLoader . getProperty ( PROP_KEY_SYS_COLUMN_TEMP_SID ) ; if ( ! isEmpty ( tempSid ) ) { setTemporarySidColumnName ( tempSid ) ; } } private static boolean isEmpty ( String str ) { if ( str == null ) { return true ; } if ( str . isEmpty ( ) ) { return true ; } return false ; } public static VariableTable createVariableTable ( ) { VariableTable variables = new VariableTable ( RedefineStrategy . OVERWRITE ) ; variables . defineVariable ( "" , String . valueOf ( ConfigurationLoader . getEnvProperty ( "" ) ) ) ; String args = ConfigurationLoader . getEnvProperty ( ENV_ARGS ) ; if ( args != null ) { variables . defineVariables ( args ) ; } return variables ; } public static void setSidColumnName ( String name ) { sidColumnName = name ; } public static String getSidColumnName ( ) { return sidColumnName ; } public static void setVersionColumnName ( String name ) { versionColumnName = name ; } public static String getVersionColumnName ( ) { return versionColumnName ; } public static void setRegisteredDateTimeColumnName ( String name ) { registeredDateTimeColumnName = name ; } public static String getRegisteredDateTimeColumnName ( ) { return registeredDateTimeColumnName ; } public static void setUpdatedDateTimeColumnName ( String name ) { updatedDateTimeColumnName = name ; } public static String getUpdatedDateTimeColumnName ( ) { return updatedDateTimeColumnName ; } public static void setTemporarySidColumnName ( String name ) { temporarySidColumnName = name ; } public static String getTemporarySidColumnName ( ) { return temporarySidColumnName ; } } package com . asakusafw . bulkloader . common ; import java . net . URL ; import java . net . URLStreamHandlerFactory ; import org . apache . hadoop . fs . FsUrlStreamHandlerFactory ; public final class UrlStreamHandlerFactoryRegisterer { private static volatile boolean registered ; public static synchronized void register ( ) { if ( registered ) { return ; } FsUrlStreamHandlerFactory factory = new FsUrlStreamHandlerFactory ( ) ; try { URL . setURLStreamHandlerFactory ( factory ) ; } catch ( Error e ) { if ( e . getClass ( ) . equals ( Error . class ) ) { return ; } throw e ; } registered = true ; } private UrlStreamHandlerFactoryRegisterer ( ) { return ; } } package com . asakusafw . bulkloader . common ; package com . asakusafw . bulkloader . common ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . text . MessageFormat ; 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 . Properties ; import java . util . Set ; import com . asakusafw . bulkloader . exception . BulkLoaderSystemException ; import com . asakusafw . runtime . util . VariableTable ; public final class ConfigurationLoader { private static final Set < String > KEY_PATHS ; static { Set < String > keys = new HashSet < String > ( ) ; keys . add ( Constants . PROP_KEY_LOG_CONF_PATH ) ; keys . add ( Constants . PROP_KEY_SSH_PATH ) ; keys . add ( Constants . PROP_KEY_IMP_FILE_DIR ) ; keys . add ( Constants . PROP_KEY_EXP_FILE_DIR ) ; KEY_PATHS = Collections . unmodifiableSet ( keys ) ; } private static final Class < ConfigurationLoader > CLASS = ConfigurationLoader . class ; private static volatile Properties prop = new Properties ( ) ; private static volatile Map < String , String > env = null ; private static volatile Properties sysProp = null ; private ConfigurationLoader ( ) { return ; } static { env = System . getenv ( ) ; sysProp = System . getProperties ( ) ; } public static void cleanProp ( ) { prop = new Properties ( ) ; } public static void init ( List < String > properties , boolean doDBPropCheck , boolean doHCPropCheck ) throws BulkLoaderSystemException , IOException { checkEnv ( ) ; loadProperties ( properties ) ; checkAndSetParam ( ) ; if ( doDBPropCheck ) { checkAndSetParamDB ( ) ; } if ( doHCPropCheck ) { checkAndSetParamHC ( ) ; } } public static void checkEnv ( ) { checkDirectory ( Constants . ASAKUSA_HOME ) ; checkDirectory ( Constants . THUNDER_GATE_HOME ) ; } private static void checkDirectory ( String variableName ) { assert variableName != null ; String variable = ConfigurationLoader . getEnvProperty ( variableName ) ; if ( isEmpty ( variable ) ) { System . err . println ( MessageFormat . format ( "" , variableName ) ) ; throw new IllegalStateException ( MessageFormat . format ( "" , variableName ) ) ; } File path = new File ( variable ) ; if ( ! path . exists ( ) ) { System . err . println ( MessageFormat . format ( "" , variableName , variable ) ) ; throw new IllegalStateException ( MessageFormat . format ( "" , variableName , variable ) ) ; } } protected static void checkAndSetParamHC ( ) throws BulkLoaderSystemException { String strCompType = prop . getProperty ( Constants . PROP_KEY_EXP_FILE_COMP_TYPE ) ; FileCompType compType = FileCompType . find ( strCompType ) ; if ( isEmpty ( strCompType ) ) { prop . setProperty ( Constants . PROP_KEY_EXP_FILE_COMP_TYPE , Constants . PROP_DEFAULT_EXP_FILE_COMP_TYPE ) ; } else if ( compType == null ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + null ) ; } String loadMaxSize = prop . getProperty ( Constants . PROP_KEY_EXP_LOAD_MAX_SIZE ) ; if ( isEmpty ( loadMaxSize ) ) { prop . setProperty ( Constants . PROP_KEY_EXP_LOAD_MAX_SIZE , Constants . PROP_DEFAULT_EXP_LOAD_MAX_SIZE ) ; } else { if ( ! isNumber ( loadMaxSize , ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + loadMaxSize ) ; } } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_IMP_SEQ_FILE_COMP_TYPE ) ) ) { prop . setProperty ( Constants . PROP_KEY_IMP_SEQ_FILE_COMP_TYPE , Constants . PROP_DEFAULT_IMP_SEQ_FILE_COMP_TYPE ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_CACHE_BUILDER_PARALLEL ) ) ) { prop . setProperty ( Constants . PROP_KEY_CACHE_BUILDER_PARALLEL , Constants . PROP_DEFAULT_CACHE_BUILDER_PARALLEL ) ; } } protected static void checkAndSetParamDB ( ) throws BulkLoaderSystemException { String strCompType = prop . getProperty ( Constants . PROP_KEY_IMP_FILE_COMP_TYPE ) ; FileCompType compType = FileCompType . find ( strCompType ) ; if ( isEmpty ( strCompType ) ) { prop . setProperty ( Constants . PROP_KEY_IMP_FILE_COMP_TYPE , Constants . PROP_DEFAULT_IMP_FILE_COMP_TYPE ) ; } else if ( compType == null ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + null ) ; } String impBufSize = prop . getProperty ( Constants . PROP_KEY_IMP_FILE_COMP_BUFSIZE ) ; if ( isEmpty ( impBufSize ) ) { prop . setProperty ( Constants . PROP_KEY_IMP_FILE_COMP_BUFSIZE , Constants . PROP_DEFAULT_IMP_FILE_COMP_BUFSIZE ) ; } else { if ( ! isNumber ( impBufSize , ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + impBufSize ) ; } } String impRetryCount = prop . getProperty ( Constants . PROP_KEY_IMP_RETRY_COUNT ) ; if ( isEmpty ( impRetryCount ) ) { prop . setProperty ( Constants . PROP_KEY_IMP_RETRY_COUNT , Constants . PROP_DEFAULT_IMP_RETRY_COUNT ) ; } else { if ( ! isNumber ( impRetryCount , ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + impRetryCount ) ; } } String impRetryInterval = prop . getProperty ( Constants . PROP_KEY_IMP_RETRY_INTERVAL ) ; if ( isEmpty ( impRetryInterval ) ) { prop . setProperty ( Constants . PROP_KEY_IMP_RETRY_INTERVAL , Constants . PROP_DEFAULT_IMP_RETRY_INTERVAL ) ; } else { if ( ! isNumber ( impRetryInterval , ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + impRetryInterval ) ; } } String expBufSize = prop . getProperty ( Constants . PROP_KEY_EXP_FILE_COMP_BUFSIZE ) ; if ( isEmpty ( expBufSize ) ) { prop . setProperty ( Constants . PROP_KEY_EXP_FILE_COMP_BUFSIZE , Constants . PROP_DEFAULT_EXP_FILE_COMP_BUFSIZE ) ; } else { if ( ! isNumber ( expBufSize , ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + expBufSize ) ; } } String expRetryCount = prop . getProperty ( Constants . PROP_KEY_EXP_RETRY_COUNT ) ; if ( isEmpty ( expRetryCount ) ) { prop . setProperty ( Constants . PROP_KEY_EXP_RETRY_COUNT , Constants . PROP_DEFAULT_EXP_RETRY_COUNT ) ; } else { if ( ! isNumber ( expRetryCount , ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + expRetryCount ) ; } } String expRetryInterval = prop . getProperty ( Constants . PROP_KEY_EXP_RETRY_INTERVAL ) ; if ( isEmpty ( expRetryInterval ) ) { prop . setProperty ( Constants . PROP_KEY_EXP_RETRY_INTERVAL , Constants . PROP_DEFAULT_EXP_RETRY_INTERVAL ) ; } else { if ( ! isNumber ( expRetryInterval , ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + expRetryInterval ) ; } } String copyMaxRecord = prop . getProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD ) ; if ( isEmpty ( copyMaxRecord ) ) { prop . setProperty ( Constants . PROP_KEY_EXP_COPY_MAX_RECORD , Constants . PROP_DEFAULT_EXP_COPY_MAX_RECORD ) ; } else { if ( ! isNumber ( copyMaxRecord , ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + copyMaxRecord ) ; } } String deleteImportTsv = prop . getProperty ( Constants . PROP_KEY_IMPORT_TSV_DELETE ) ; TsvDeleteType delImpType = TsvDeleteType . find ( deleteImportTsv ) ; if ( isEmpty ( deleteImportTsv ) ) { prop . setProperty ( Constants . PROP_KEY_IMPORT_TSV_DELETE , Constants . PROP_DEFAULT_IMPORT_TSV_DELETE ) ; } else if ( delImpType == null ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + deleteImportTsv ) ; } String deleteExportTsv = prop . getProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE ) ; TsvDeleteType delExpType = TsvDeleteType . find ( deleteExportTsv ) ; if ( isEmpty ( deleteExportTsv ) ) { prop . setProperty ( Constants . PROP_KEY_EXPORT_TSV_DELETE , Constants . PROP_DEFAULT_EXPORT_TSV_DELETE ) ; } else if ( delExpType == null ) { throw new BulkLoaderSystemException ( CLASS , "" , "" + deleteExportTsv ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_PREFIX_HC_ENV + Constants . ASAKUSA_HOME ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , MessageFormat . format ( "" , Constants . PROP_PREFIX_HC_ENV , Constants . ASAKUSA_HOME ) ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_SSH_PATH ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_NAMENODE_HOST ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_NAMENODE_USER ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_IMP_FILE_DIR ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_EXP_FILE_DIR ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } } protected static void checkAndSetParam ( ) { if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_LOG_CONF_PATH ) ) ) { prop . setProperty ( Constants . PROP_KEY_LOG_CONF_PATH , resolvePath ( Constants . PROP_DEFAULT_LOG_CONF_PATH ) ) ; } } private static void loadProperties ( List < String > propertyPaths ) throws IOException { assert propertyPaths != null ; Properties properties = loadRawProperties ( propertyPaths ) ; VariableTable variables = new VariableTable ( ) ; variables . defineVariables ( System . getenv ( ) ) ; prop . putAll ( resolveProperties ( variables , properties ) ) ; } private static Properties loadRawProperties ( List < String > propertyPaths ) throws IOException { assert propertyPaths != null ; Properties properties = new Properties ( ) ; for ( String strProp : propertyPaths ) { File propFile = createPropFileName ( strProp ) ; FileInputStream fis = null ; try { fis = new FileInputStream ( propFile ) ; properties . load ( fis ) ; } catch ( IOException e ) { System . err . println ( "" + propFile . getAbsolutePath ( ) ) ; e . printStackTrace ( ) ; throw e ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } return properties ; } private static Properties resolveProperties ( VariableTable variables , Properties properties ) { assert variables != null ; assert properties != null ; Properties results = new Properties ( ) ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { if ( entry . getKey ( ) instanceof String && entry . getValue ( ) instanceof String ) { String key = ( String ) entry . getKey ( ) ; String value = ( String ) entry . getValue ( ) ; if ( canResolveVariables ( key ) ) { value = resolveVariables ( variables , key , value ) ; } else if ( canResolvePath ( key ) ) { value = resolvePath ( value ) ; } results . setProperty ( key , value ) ; } } return results ; } private static String resolveVariables ( VariableTable variables , String key , String value ) { assert variables != null ; assert key != null ; assert value != null ; try { return variables . parse ( value , true ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , key , value ) , e ) ; } } private static boolean canResolveVariables ( String key ) { return true ; } private static boolean canResolvePath ( String key ) { assert key != null ; return KEY_PATHS . contains ( key ) ; } private static String resolvePath ( String value ) { assert value != null ; File raw = new File ( value ) ; if ( raw . isAbsolute ( ) ) { return value ; } String basePath = ConfigurationLoader . getEnvProperty ( Constants . ASAKUSA_HOME ) ; File base = new File ( basePath ) ; File target = new File ( base , value ) ; return target . getAbsolutePath ( ) ; } public static void loadJDBCProp ( String targetName ) throws BulkLoaderSystemException { String propName = targetName + Constants . JDBC_PROP_NAME ; try { loadProperties ( Arrays . asList ( new String [ ] { propName } ) ) ; } catch ( IOException e ) { throw new BulkLoaderSystemException ( e , CLASS , "" , propName ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_JDBC_DRIVER ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_DB_URL ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_DB_USER ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_DB_PASSWORD ) ) ) { throw new BulkLoaderSystemException ( CLASS , "" , "" ) ; } } private static File createPropFileName ( String propFileName ) { File tempFile = new File ( propFileName ) ; if ( tempFile . isAbsolute ( ) ) { return tempFile ; } String applHome = ConfigurationLoader . getEnvProperty ( Constants . THUNDER_GATE_HOME ) ; File file1 = new File ( applHome , Constants . PROP_FILE_PATH ) ; File file2 = new File ( file1 , propFileName ) ; return file2 ; } public static Map < String , String > getPropSubMap ( String prefix ) { if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } Map < String , String > results = new HashMap < String , String > ( ) ; for ( Map . Entry < Object , Object > entry : prop . entrySet ( ) ) { if ( entry . getKey ( ) instanceof String && entry . getValue ( ) instanceof String ) { String key = ( String ) entry . getKey ( ) ; if ( key . startsWith ( prefix ) ) { results . put ( key . substring ( prefix . length ( ) ) , ( String ) entry . getValue ( ) ) ; } } } return results ; } public static List < String > getPropStartWithString ( String startString ) { Set < Object > propSet = prop . keySet ( ) ; List < String > list = new ArrayList < String > ( ) ; for ( Object o : propSet ) { String key = ( String ) o ; if ( key . startsWith ( startString ) ) { list . add ( key ) ; } } return list ; } public static List < String > getExistValueList ( List < String > list ) { List < String > resultList = new ArrayList < String > ( ) ; if ( list == null || list . size ( ) == ) { return resultList ; } int listSize = list . size ( ) ; for ( int i = ; i < listSize ; i ++ ) { String key = list . get ( i ) ; String value = prop . getProperty ( key ) ; if ( ! isEmpty ( value ) ) { resultList . add ( key ) ; } } return resultList ; } private static boolean isEmpty ( String str ) { if ( str == null ) { return true ; } if ( str . isEmpty ( ) ) { return true ; } return false ; } private static boolean isNumber ( String str , int min ) { try { long parsed = Long . parseLong ( str ) ; return parsed >= min ; } catch ( NumberFormatException e ) { return false ; } } public static File getLocalScriptPath ( String relativePath ) { if ( relativePath == null ) { throw new IllegalArgumentException ( "" ) ; } File base = new File ( getEnvProperty ( Constants . THUNDER_GATE_HOME ) ) ; return new File ( base , relativePath ) ; } public static String getRemoteScriptPath ( String relativePath ) { if ( relativePath == null ) { throw new IllegalArgumentException ( "" ) ; } String remoteHome = getProperty ( Constants . PROP_PREFIX_HC_ENV + Constants . ASAKUSA_HOME ) ; if ( remoteHome . endsWith ( "" ) == false ) { remoteHome = remoteHome + "" ; } return remoteHome + Constants . PATH_REMOTE_ROOT + relativePath ; } public static String getProperty ( String key ) { return prop . getProperty ( key ) ; } public static String getEnvProperty ( String key ) { String strSysProp = sysProp . getProperty ( key ) ; String strEnv = env . get ( key ) ; if ( strSysProp != null ) { return strSysProp ; } else if ( strEnv != null ) { return strEnv ; } else { return null ; } } public static String getForceIndexName ( String batchId , String jobflowId , String tableName ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "" ) ; buf . append ( batchId ) ; buf . append ( "" ) ; buf . append ( jobflowId ) ; buf . append ( "" ) ; buf . append ( tableName ) ; String indexName = prop . getProperty ( buf . toString ( ) ) ; return indexName ; } @ Deprecated public static void setProperty ( Properties p ) { prop = p ; } @ Deprecated public static Properties getProperty ( ) { return prop ; } @ Deprecated public static void setSysProp ( Properties p ) { sysProp = p ; } @ Deprecated public static void setEnv ( Map < String , String > m ) { env = m ; } } package com . asakusafw . bulkloader . common ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public enum ExportTempTableStatus { LOAD_EXIT ( "" ) , BEFORE_COPY ( "" ) , COPY_EXIT ( "" ) ; private String status ; public String getStatus ( ) { return status ; } private ExportTempTableStatus ( String status ) { this . status = status ; } public static ExportTempTableStatus find ( String key ) { return StatusToExportTempTableStatus . REVERSE_DICTIONARY . get ( key ) ; } private static class StatusToExportTempTableStatus { static final Map < String , ExportTempTableStatus > REVERSE_DICTIONARY ; static { Map < String , ExportTempTableStatus > map = new HashMap < String , ExportTempTableStatus > ( ) ; for ( ExportTempTableStatus elem : ExportTempTableStatus . values ( ) ) { map . put ( elem . getStatus ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } } } package com . asakusafw . bulkloader . common ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public enum ImportTableLockType { TABLE ( "" ) , RECORD ( "" ) , NONE ( "" ) ; private String lockType ; public String getLockType ( ) { return lockType ; } private ImportTableLockType ( String type ) { this . lockType = type ; } public static ImportTableLockType find ( String key ) { return LockTypeToImportTableLockType . REVERSE_DICTIONARY . get ( key ) ; } private static class LockTypeToImportTableLockType { static final Map < String , ImportTableLockType > REVERSE_DICTIONARY ; static { Map < String , ImportTableLockType > map = new HashMap < String , ImportTableLockType > ( ) ; for ( ImportTableLockType elem : ImportTableLockType . values ( ) ) { map . put ( elem . getLockType ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } } } package com . asakusafw . bulkloader . common ; import java . util . Collections ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; public enum FileCompType { DEFLATED ( "" , "" , "" ) , STORED ( "" , "" , "" ) , ; private String symbol ; Set < String > keys ; private FileCompType ( String symbol , String ... alternatives ) { this . symbol = symbol ; this . keys = new HashSet < String > ( ) ; this . keys . add ( symbol ) ; Collections . addAll ( this . keys , alternatives ) ; } public String getSymbol ( ) { return symbol ; } public static FileCompType find ( String key ) { return CompTypeToFileCompType . REVERSE_DICTIONARY . get ( key ) ; } private static class CompTypeToFileCompType { static final Map < String , FileCompType > REVERSE_DICTIONARY ; static { Map < String , FileCompType > map = new TreeMap < String , FileCompType > ( String . CASE_INSENSITIVE_ORDER ) ; for ( FileCompType elem : FileCompType . values ( ) ) { for ( String key : elem . keys ) { map . put ( key , elem ) ; } } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } } } package com . asakusafw . bulkloader . common ; import java . io . IOException ; import java . util . Collection ; import java . util . concurrent . ArrayBlockingQueue ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . atomic . AtomicBoolean ; import java . util . concurrent . atomic . AtomicReference ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; public final class MultiThreadedCopier < T > { static final long POLL_BREAK_INTERVAL = ; private final BlockingQueue < T > outputChannel ; private final BlockingQueue < T > buffer ; private final ModelInput < T > input ; private final OutputTask < T > task ; private MultiThreadedCopier ( ModelInput < T > input , ModelOutput < T > output , Collection < T > working ) { assert input != null ; assert output != null ; assert working != null ; this . outputChannel = new ArrayBlockingQueue < T > ( working . size ( ) + ) ; this . buffer = new ArrayBlockingQueue < T > ( working . size ( ) + , false , working ) ; this . input = input ; this . task = new OutputTask < T > ( outputChannel , buffer , output ) ; this . task . setDaemon ( true ) ; } public static < T > long copy ( ModelInput < T > input , ModelOutput < T > output , Collection < T > working ) throws IOException , InterruptedException { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } if ( working == null ) { throw new IllegalArgumentException ( "" ) ; } if ( working . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } return new MultiThreadedCopier < T > ( input , output , working ) . process ( ) ; } private long process ( ) throws IOException , InterruptedException { task . start ( ) ; while ( true ) { T model = takeBuffer ( ) ; if ( input . readTo ( model ) == false ) { break ; } outputChannel . put ( model ) ; } task . finished . set ( true ) ; task . join ( ) ; checkException ( ) ; return task . count ; } private T takeBuffer ( ) throws IOException , InterruptedException { while ( true ) { T model = buffer . poll ( POLL_BREAK_INTERVAL , TimeUnit . MILLISECONDS ) ; if ( model == null ) { if ( task . finished . get ( ) ) { throw new IllegalStateException ( ) ; } checkException ( ) ; } else { return model ; } } } private void checkException ( ) throws InterruptedException , IOException { Throwable exception = task . occurred . get ( ) ; if ( exception != null ) { if ( exception instanceof InterruptedException ) { throw ( InterruptedException ) exception ; } if ( exception instanceof IOException ) { throw ( IOException ) exception ; } if ( exception instanceof Error ) { throw ( Error ) exception ; } if ( exception instanceof RuntimeException ) { throw ( RuntimeException ) exception ; } throw new IOException ( exception ) ; } } static class OutputTask < T > extends Thread { private final BlockingQueue < T > source ; private final BlockingQueue < T > buffer ; private final ModelOutput < T > sink ; final AtomicBoolean finished = new AtomicBoolean ( ) ; final AtomicReference < Throwable > occurred = new AtomicReference < Throwable > ( ) ; long count ; OutputTask ( BlockingQueue < T > source , BlockingQueue < T > buffer , ModelOutput < T > sink ) { assert source != null ; assert buffer != null ; assert sink != null ; this . source = source ; this . buffer = buffer ; this . sink = sink ; this . count = ; } @ Override public void run ( ) { try { drain ( ) ; } catch ( Error e ) { occurred . set ( e ) ; throw e ; } catch ( InterruptedException e ) { if ( finished . get ( ) ) { return ; } occurred . set ( e ) ; } catch ( Throwable e ) { occurred . set ( e ) ; } } private void drain ( ) throws InterruptedException , IOException { while ( true ) { T next = source . poll ( POLL_BREAK_INTERVAL , TimeUnit . MILLISECONDS ) ; if ( next == null ) { if ( finished . get ( ) ) { break ; } } else { sink . write ( next ) ; buffer . add ( next ) ; count ++ ; } } } } } package com . asakusafw . dmdl . thundergate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . lang . reflect . Method ; import java . net . URL ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Locale ; import java . util . regex . Pattern ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . junit . After ; import org . junit . Rule ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . java . emitter . NameConstants ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . java . util . JavaName ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstScript ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . parser . DmdlEmitter ; import com . asakusafw . dmdl . source . DmdlSourceDirectory ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . dmdl . source . DmdlSourceResource ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; public class GeneratorTesterRoot { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; protected final VolatileCompiler compiler = new VolatileCompiler ( ) ; protected final List < JavaDataModelDriver > emitDrivers = Lists . create ( ) ; @ After public void tearDown ( ) throws Exception { compiler . close ( ) ; } protected void emitDmdl ( AstModelDefinition < ? > model ) { AstScript script = new AstScript ( null , Collections . singletonList ( model ) ) ; StringWriter buffer = new StringWriter ( ) ; PrintWriter output = new PrintWriter ( buffer ) ; DmdlEmitter . emit ( script , output ) ; output . close ( ) ; try { File file = folder . newFile ( model . name . identifier + "" ) ; System . out . println ( "" + file . getName ( ) ) ; System . out . println ( buffer . toString ( ) ) ; PrintWriter writer = new PrintWriter ( file , "" ) ; try { writer . print ( buffer . toString ( ) ) ; } finally { writer . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } protected ModelLoader generateJava ( ) { try { List < VolatileJavaFile > files = emit ( new DmdlSourceDirectory ( folder . getRoot ( ) , Charset . forName ( "" ) , Pattern . compile ( "" ) , Pattern . compile ( "" ) ) ) ; ClassLoader loaded = compile ( files ) ; return new ModelLoader ( loaded ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected ModelLoader generateJava ( String name ) { try { List < VolatileJavaFile > files = emit ( collectInput ( name ) ) ; ClassLoader loaded = compile ( files ) ; return new ModelLoader ( loaded ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected void shouldSemanticError ( String name ) { try { emit ( collectInput ( name ) ) ; throw new AssertionError ( "" ) ; } catch ( IOException e ) { } } private ClassLoader compile ( List < VolatileJavaFile > files ) { if ( files . isEmpty ( ) ) { throw new AssertionError ( ) ; } for ( JavaFileObject java : files ) { try { System . out . println ( "" + java . getName ( ) ) ; System . out . println ( java . getCharContent ( true ) ) ; System . out . println ( ) ; System . out . println ( ) ; } catch ( IOException e ) { } compiler . addSource ( java ) ; } compiler . addArguments ( "" ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; boolean hasWrong = false ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) == Diagnostic . Kind . ERROR || d . getKind ( ) == Diagnostic . Kind . WARNING ) { System . out . println ( "" ) ; System . out . println ( d . getMessage ( Locale . getDefault ( ) ) ) ; hasWrong = true ; } } if ( hasWrong ) { throw new AssertionError ( diagnostics ) ; } return compiler . getClassLoader ( ) ; } private List < VolatileJavaFile > emit ( DmdlSourceRepository source ) throws IOException { ModelFactory factory = Models . getModelFactory ( ) ; VolatileEmitter emitter = new VolatileEmitter ( ) ; com . asakusafw . dmdl . java . Configuration conf = new com . asakusafw . dmdl . java . Configuration ( factory , source , Models . toName ( factory , "" ) , emitter , getClass ( ) . getClassLoader ( ) , Locale . getDefault ( ) ) ; com . asakusafw . dmdl . java . GenerateTask task = new com . asakusafw . dmdl . java . GenerateTask ( conf ) ; task . process ( new CompositeDataModelDriver ( emitDrivers ) ) ; return emitter . getEmitted ( ) ; } private DmdlSourceRepository collectInput ( String name ) { URL url = getClass ( ) . getResource ( name + "" ) ; assertThat ( name , url , not ( nullValue ( ) ) ) ; return new DmdlSourceResource ( Collections . singletonList ( url ) , Charset . forName ( "" ) ) ; } protected static class ModelLoader { private final ClassLoader classLoader ; private String namespace ; ModelLoader ( ClassLoader loaded ) { assert loaded != null ; this . classLoader = loaded ; this . namespace = NameConstants . DEFAULT_NAMESPACE ; } public final void setNamespace ( String namespace ) { this . namespace = namespace ; } public Class < ? > modelType ( String name ) { return type ( NameConstants . CATEGORY_DATA_MODEL , name ) ; } public ModelWrapper newModel ( String name ) { try { Class < ? > loaded = modelType ( name ) ; Object instance = loaded . newInstance ( ) ; return new ModelWrapper ( instance ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public Object newObject ( String category , String name ) { try { Class < ? > loaded = type ( category , name ) ; Object instance = loaded . newInstance ( ) ; return instance ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Class < ? > type ( String category , String name ) { try { return classLoader . loadClass ( MessageFormat . format ( "" , "" , namespace , category , name ) ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } } } @ SuppressWarnings ( "" ) protected static class ModelWrapper { private final DataModel instance ; private Class < ? > interfaceType ; ModelWrapper ( Object instance ) { this . instance = ( DataModel ) instance ; this . interfaceType = instance . getClass ( ) ; } public Object unwrap ( ) { return instance ; } public void setInterfaceType ( Class < ? > interfaceType ) { this . interfaceType = interfaceType ; } public boolean is ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; Object result = invoke ( jn . toMemberName ( ) ) ; return ( Boolean ) result ; } public Object get ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; return invoke ( jn . toMemberName ( ) ) ; } public void set ( String name , Object value ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; invoke ( jn . toMemberName ( ) , value ) ; } public ValueOption < ? > getOption ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; jn . addLast ( "" ) ; return ( ValueOption < ? > ) invoke ( jn . toMemberName ( ) ) ; } public void setOption ( String name , ValueOption < ? > option ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; jn . addLast ( "" ) ; invoke ( jn . toMemberName ( ) , option ) ; } public void reset ( ) { instance . reset ( ) ; } @ SuppressWarnings ( "" ) public void copyFrom ( ModelWrapper wrapper ) { instance . copyFrom ( wrapper . instance ) ; } public Object invoke ( String name , Object ... arguments ) { for ( Method method : interfaceType . getMethods ( ) ) { if ( method . getName ( ) . equals ( name ) ) { try { return method . invoke ( instance , arguments ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } throw new AssertionError ( name ) ; } } } package com . asakusafw . dmdl . thundergate . view ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import org . junit . Test ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; import com . asakusafw . dmdl . thundergate . view . model . CreateView ; import com . asakusafw . dmdl . thundergate . view . model . From ; import com . asakusafw . dmdl . thundergate . view . model . Join ; import com . asakusafw . dmdl . thundergate . view . model . Name ; import com . asakusafw . dmdl . thundergate . view . model . On ; import com . asakusafw . dmdl . thundergate . view . model . Select ; public class ViewParserTest { @ Test public void parseJoin ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , } ) , new From ( n ( "" ) , null , new Join ( n ( "" ) , null , Arrays . asList ( new On ( n ( "" ) , n ( "" ) ) ) ) ) , Arrays . < Name > asList ( ) ) ) ) ; } @ Test public void parseJoin_withAlias ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , } ) , new From ( n ( "" ) , "" , new Join ( n ( "" ) , "" , Arrays . asList ( new On ( n ( "" ) , n ( "" ) ) ) ) ) , Arrays . < Name > asList ( ) ) ) ) ; } @ Test public void parseSummarize ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . COUNT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . MAX , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . SUM , n ( "" ) ) , } ) , new From ( n ( "" ) , null , null ) , Arrays . < Name > asList ( n ( "" ) ) ) ) ) ; } @ Test public void parseSummarize_withAlias ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . COUNT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . MAX , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . SUM , n ( "" ) ) , } ) , new From ( n ( "" ) , "" , null ) , Arrays . < Name > asList ( n ( "" ) ) ) ) ) ; } @ Test public void parseSummarize_multiGroupCoulmns ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . COUNT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . MAX , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . SUM , n ( "" ) ) , } ) , new From ( n ( "" ) , null , null ) , Arrays . < Name > asList ( n ( "" ) , n ( "" ) ) ) ) ) ; } private Name n ( String name ) { return new Name ( name ) ; } private ViewDefinition def ( String statement ) { return new ViewDefinition ( "" , statement ) ; } } package com . asakusafw . dmdl . thundergate . util ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . dmdl . thundergate . model . JoinedModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . dmdl . thundergate . model . StringType ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; public class JoinedModelBuilderTest { @ Test public void simple ( ) { TableModelDescription a = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; TableModelDescription b = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; JoinedModelBuilder target = new JoinedModelBuilder ( "" , a , "" , b , "" ) ; target . on ( "" , "" ) ; target . add ( "" , "" ) ; target . add ( "" , "" ) ; target . add ( "" , "" ) ; JoinedModelDescription desc = target . toDescription ( ) ; assertThat ( desc . getFromModel ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( desc . getJoinModel ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( desc . getFromCondition ( ) , is ( sources ( a , "" ) ) ) ; assertThat ( desc . getJoinCondition ( ) , is ( sources ( b , "" ) ) ) ; List < ModelProperty > props = desc . getProperties ( ) ; assertThat ( props . size ( ) , is ( ) ) ; ModelProperty id = props . get ( ) ; assertThat ( id . getName ( ) , is ( "" ) ) ; assertThat ( id . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( id . getFrom ( ) , is ( source ( a , "" ) ) ) ; assertThat ( id . getJoined ( ) , is ( source ( b , "" ) ) ) ; ModelProperty hoge = props . get ( ) ; assertThat ( hoge . getName ( ) , is ( "" ) ) ; assertThat ( hoge . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; assertThat ( hoge . getFrom ( ) , is ( source ( a , "" ) ) ) ; assertThat ( hoge . getJoined ( ) , is ( nullValue ( ) ) ) ; ModelProperty bar = props . get ( ) ; assertThat ( bar . getName ( ) , is ( "" ) ) ; assertThat ( bar . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; assertThat ( bar . getFrom ( ) , is ( nullValue ( ) ) ) ; assertThat ( bar . getJoined ( ) , is ( source ( b , "" ) ) ) ; } private Source source ( ModelDescription model , String name ) { for ( Source s : model . getPropertiesAsSources ( ) ) { if ( name . equals ( s . getName ( ) ) ) { return s ; } } throw new AssertionError ( name ) ; } private List < Source > sources ( ModelDescription model , String ... names ) { List < Source > results = Lists . create ( ) ; Set < String > targets = Sets . create ( ) ; Collections . addAll ( targets , names ) ; for ( Source s : model . getPropertiesAsSources ( ) ) { if ( targets . contains ( s . getName ( ) ) ) { results . add ( s ) ; } } return results ; } } package com . asakusafw . dmdl . thundergate . util ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . dmdl . thundergate . model . StringType ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; public class TableModelBuilderTest { @ Test public void simple ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . INT ) . toDescription ( ) ; assertThat ( desc . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; List < ModelProperty > properties = desc . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty value = properties . get ( ) ; assertThat ( value . getName ( ) , is ( "" ) ) ; assertThat ( value . getType ( ) . getKind ( ) , is ( PropertyTypeKind . INT ) ) ; assertThat ( value . getJoined ( ) , is ( nullValue ( ) ) ) ; Source valueSrc = value . getFrom ( ) ; assertThat ( valueSrc . getAggregator ( ) , is ( Aggregator . IDENT ) ) ; assertThat ( valueSrc . getDeclaring ( ) , is ( desc . getReference ( ) ) ) ; assertThat ( valueSrc . getName ( ) , is ( "" ) ) ; assertThat ( valueSrc . getType ( ) . getKind ( ) , is ( PropertyTypeKind . INT ) ) ; assertThat ( valueSrc . getAttributes ( ) . size ( ) , is ( ) ) ; } @ Test public void multi ( ) { TableModelBuilder target = new TableModelBuilder ( "" ) ; target . add ( null , "" , PropertyTypeKind . INT ) ; target . add ( null , "" , new StringType ( ) ) ; target . add ( null , "" , PropertyTypeKind . DATETIME ) ; TableModelDescription desc = target . toDescription ( ) ; assertThat ( desc . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; List < ModelProperty > properties = desc . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty a = properties . get ( ) ; assertThat ( a . getName ( ) , is ( "" ) ) ; assertThat ( a . getType ( ) . getKind ( ) , is ( PropertyTypeKind . INT ) ) ; ModelProperty b = properties . get ( ) ; assertThat ( b . getName ( ) , is ( "" ) ) ; assertThat ( b . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; ModelProperty c = properties . get ( ) ; assertThat ( c . getName ( ) , is ( "" ) ) ; assertThat ( c . getType ( ) . getKind ( ) , is ( PropertyTypeKind . DATETIME ) ) ; } @ Test public void attributes ( ) { TableModelBuilder target = new TableModelBuilder ( "" ) ; target . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) ; target . add ( null , "" , new StringType ( ) , Attribute . UNIQUE , Attribute . NOT_NULL ) ; TableModelDescription desc = target . toDescription ( ) ; assertThat ( desc . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; List < ModelProperty > properties = desc . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty a = properties . get ( ) ; assertThat ( a . getName ( ) , is ( "" ) ) ; assertThat ( a . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; Set < Attribute > aAttr = a . getFrom ( ) . getAttributes ( ) ; assertThat ( aAttr . size ( ) , is ( ) ) ; assertThat ( aAttr . contains ( Attribute . PRIMARY_KEY ) , is ( true ) ) ; ModelProperty b = properties . get ( ) ; assertThat ( b . getName ( ) , is ( "" ) ) ; assertThat ( b . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; Set < Attribute > bAttr = b . getFrom ( ) . getAttributes ( ) ; assertThat ( bAttr . size ( ) , is ( ) ) ; assertThat ( bAttr . containsAll ( list ( Attribute . UNIQUE , Attribute . NOT_NULL ) ) , is ( true ) ) ; } private < T > List < T > list ( T ... values ) { return Arrays . asList ( values ) ; } } package com . asakusafw . dmdl . thundergate . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . dmdl . thundergate . model . StringType ; import com . asakusafw . dmdl . thundergate . model . SummarizedModelDescription ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; public class SummarizedModelBuilderTest { @ Test public void simple ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . COUNT , "" ) . groupBy ( "" ) . toDescription ( ) ; assertThat ( model . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( model . getGroupBy ( ) , is ( sources ( desc , "" ) ) ) ; List < ModelProperty > properties = model . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty word = properties . get ( ) ; assertThat ( word . getName ( ) , is ( "" ) ) ; assertThat ( word . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; assertThat ( word . getJoined ( ) , is ( nullValue ( ) ) ) ; assertThat ( word . getFrom ( ) , is ( source ( desc , "" , Aggregator . IDENT ) ) ) ; ModelProperty count = properties . get ( ) ; assertThat ( count . getName ( ) , is ( "" ) ) ; assertThat ( count . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( count . getJoined ( ) , is ( nullValue ( ) ) ) ; assertThat ( count . getFrom ( ) , is ( source ( desc , "" , Aggregator . COUNT ) ) ) ; } @ Test public void singleGroup ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . COUNT , "" ) . toDescription ( ) ; assertThat ( model . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( model . getGroupBy ( ) , is ( sources ( desc ) ) ) ; List < ModelProperty > properties = model . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty count = properties . get ( ) ; assertThat ( count . getName ( ) , is ( "" ) ) ; assertThat ( count . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( count . getFrom ( ) , is ( source ( desc , "" , Aggregator . COUNT ) ) ) ; } @ Test public void multiGroupKey ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . BYTE ) . add ( null , "" , PropertyTypeKind . SHORT ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . COUNT , "" ) . groupBy ( "" , "" ) . toDescription ( ) ; assertThat ( model . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( model . getGroupBy ( ) , is ( sources ( desc , "" , "" ) ) ) ; List < ModelProperty > properties = model . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty sex = properties . get ( ) ; assertThat ( sex . getName ( ) , is ( "" ) ) ; assertThat ( sex . getType ( ) . getKind ( ) , is ( PropertyTypeKind . BYTE ) ) ; assertThat ( sex . getFrom ( ) , is ( source ( desc , "" , Aggregator . IDENT ) ) ) ; ModelProperty age = properties . get ( ) ; assertThat ( age . getName ( ) , is ( "" ) ) ; assertThat ( age . getType ( ) . getKind ( ) , is ( PropertyTypeKind . SHORT ) ) ; assertThat ( age . getFrom ( ) , is ( source ( desc , "" , Aggregator . IDENT ) ) ) ; ModelProperty count = properties . get ( ) ; assertThat ( count . getName ( ) , is ( "" ) ) ; assertThat ( count . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( count . getFrom ( ) , is ( source ( desc , "" , Aggregator . COUNT ) ) ) ; } @ Test ( expected = RuntimeException . class ) public void empty ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . toDescription ( ) ; } @ Test ( expected = RuntimeException . class ) public void missingAggregatingColumn ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . IDENT , "" ) ; } @ Test ( expected = RuntimeException . class ) public void missingGroupingColumn ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . groupBy ( "" ) ; } @ Test ( expected = RuntimeException . class ) public void invalidIdent ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . add ( null , "" , PropertyTypeKind . INT ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . IDENT , "" ) . groupBy ( "" ) . toDescription ( ) ; } @ Test ( expected = RuntimeException . class ) public void invalidAggregation ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . SUM , "" ) ; } @ Test ( expected = RuntimeException . class ) public void noGroupColumn ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . COUNT , "" ) . groupBy ( "" ) . toDescription ( ) ; } private Source source ( ModelDescription model , String name , Aggregator aggr ) { for ( Source s : model . getPropertiesAsSources ( ) ) { if ( name . equals ( s . getName ( ) ) ) { return new Source ( aggr , s . getDeclaring ( ) , s . getName ( ) , s . getType ( ) , s . getAttributes ( ) ) ; } } throw new AssertionError ( name ) ; } private List < Source > sources ( ModelDescription model , String ... names ) { List < Source > results = Lists . create ( ) ; Set < String > targets = Sets . create ( ) ; Collections . addAll ( targets , names ) ; for ( Source s : model . getPropertiesAsSources ( ) ) { if ( targets . contains ( s . getName ( ) ) ) { results . add ( s ) ; } } return results ; } } package com . asakusafw . dmdl . thundergate ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . List ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . util . Emitter ; public class VolatileEmitter extends Emitter { private final List < VolatileJavaFile > emitted = Lists . create ( ) ; @ Override public PrintWriter openFor ( PackageDeclaration packageDeclOrNull , String subPath ) throws IOException { StringBuilder buf = new StringBuilder ( ) ; if ( packageDeclOrNull != null ) { buf . append ( packageDeclOrNull . getName ( ) . toNameString ( ) . replace ( '' , '' ) ) ; buf . append ( "" ) ; } assert subPath . endsWith ( "" ) ; buf . append ( subPath . substring ( , subPath . length ( ) - ) ) ; VolatileJavaFile file = new VolatileJavaFile ( buf . toString ( ) ) ; register ( file ) ; return new PrintWriter ( file . openWriter ( ) ) ; } private void register ( VolatileJavaFile file ) { emitted . add ( file ) ; } public List < VolatileJavaFile > getEmitted ( ) { return emitted ; } } package com . asakusafw . dmdl . thundergate . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; public class AstBuilderTest { @ Test public void toDmdlName ( ) { assertThat ( AstBuilder . toDmdlName ( "" ) . identifier , is ( "" ) ) ; assertThat ( AstBuilder . toDmdlName ( "" ) . identifier , is ( "" ) ) ; assertThat ( AstBuilder . toDmdlName ( "" ) . identifier , is ( "" ) ) ; } } package com . asakusafw . dmdl . thundergate . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . nio . charset . Charset ; import org . apache . hadoop . io . Text ; import org . hamcrest . Matcher ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . LiteralKind ; import com . asakusafw . dmdl . thundergate . Configuration ; import com . asakusafw . dmdl . thundergate . Constants ; import com . asakusafw . dmdl . thundergate . GeneratorTesterRoot ; import com . asakusafw . dmdl . thundergate . ModelMatcher ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . BasicType ; import com . asakusafw . dmdl . thundergate . model . JoinedModelDescription ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . StringType ; import com . asakusafw . dmdl . thundergate . model . SummarizedModelDescription ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . dmdl . thundergate . util . JoinedModelBuilder ; import com . asakusafw . dmdl . thundergate . util . SummarizedModelBuilder ; import com . asakusafw . dmdl . thundergate . util . TableModelBuilder ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class ThunderGateModelEmitterTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new CompositeDataModelDriver ( getClass ( ) . getClassLoader ( ) ) ) ; } private Configuration config ( ) { Configuration config = new Configuration ( ) ; config . setJdbcDriver ( "" ) ; config . setJdbcUrl ( "" ) ; config . setJdbcUser ( "" ) ; config . setJdbcPassword ( "" ) ; config . setDatabaseName ( "" ) ; config . setMatcher ( ModelMatcher . NOTHING ) ; config . setOutput ( folder . getRoot ( ) ) ; config . setEncoding ( Charset . forName ( "" ) ) ; return config ; } @ Test public void table ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new StringType ( ) ) . toDescription ( ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ( ) ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; } @ Test public void join ( ) throws Exception { TableModelDescription left = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; TableModelDescription right = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; JoinedModelDescription join = new JoinedModelBuilder ( "" , left , "" , right , "" ) . on ( "" , "" ) . add ( "" , "" ) . add ( "" , "" ) . add ( "" , "" ) . toDescription ( ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ( ) ) ; emitter . emit ( left ) ; emitter . emit ( right ) ; emitter . emit ( join ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_VIEW ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; } @ Test public void summarize ( ) throws Exception { TableModelDescription target = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , PropertyTypeKind . INT ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , PropertyTypeKind . DATE ) . toDescription ( ) ; SummarizedModelDescription summarize = new SummarizedModelBuilder ( "" , target , "" ) . groupBy ( "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . IDENT , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . SUM , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . COUNT , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . MAX , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . MIN , "" ) . toDescription ( ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ( ) ) ; emitter . emit ( target ) ; emitter . emit ( summarize ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_VIEW ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , new Date ( , , ) ) ; assertThat ( object . get ( "" ) , eq ( new Date ( , , ) ) ) ; object . set ( "" , new Date ( , , ) ) ; assertThat ( object . get ( "" ) , eq ( new Date ( , , ) ) ) ; } @ Test public void table_cached ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new BasicType ( PropertyTypeKind . LONG ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . DATETIME ) ) . toDescription ( ) ; Configuration config = config ( ) ; config . setSidColumn ( "" ) ; config . setTimestampColumn ( "" ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; ModelWrapper object = loader . newModel ( "" ) ; assertThat ( object . unwrap ( ) , instanceOf ( ThunderGateCacheSupport . class ) ) ; ThunderGateCacheSupport support = ( ThunderGateCacheSupport ) object . unwrap ( ) ; object . set ( "" , ) ; assertThat ( support . __tgc__SystemId ( ) , is ( ) ) ; assertThat ( support . __tgc__TimestampColumn ( ) , is ( "" ) ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; } @ Test public void table_cached_with_delete ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new BasicType ( PropertyTypeKind . LONG ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . DATETIME ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . BOOLEAN ) ) . toDescription ( ) ; Configuration config = config ( ) ; config . setSidColumn ( "" ) ; config . setTimestampColumn ( "" ) ; config . setDeleteFlagColumn ( "" ) ; config . setDeleteFlagValue ( new AstLiteral ( null , "" , LiteralKind . BOOLEAN ) ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; ModelWrapper object = loader . newModel ( "" ) ; assertThat ( object . unwrap ( ) , instanceOf ( ThunderGateCacheSupport . class ) ) ; ThunderGateCacheSupport support = ( ThunderGateCacheSupport ) object . unwrap ( ) ; object . set ( "" , true ) ; assertThat ( support . __tgc__Deleted ( ) , is ( true ) ) ; object . set ( "" , false ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; object . setOption ( "" , null ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; } @ Test public void table_cached_no_sid ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new BasicType ( PropertyTypeKind . DATETIME ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . BOOLEAN ) ) . toDescription ( ) ; Configuration config = config ( ) ; config . setSidColumn ( "" ) ; config . setTimestampColumn ( "" ) ; config . setDeleteFlagColumn ( "" ) ; config . setDeleteFlagValue ( new AstLiteral ( null , "" , LiteralKind . BOOLEAN ) ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; assertThat ( loader . newModel ( "" ) . unwrap ( ) , not ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; } @ Test public void table_cached_invalid_sid ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new BasicType ( PropertyTypeKind . INT ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . DATETIME ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . BOOLEAN ) ) . toDescription ( ) ; Configuration config = config ( ) ; config . setSidColumn ( "" ) ; config . setTimestampColumn ( "" ) ; config . setDeleteFlagColumn ( "" ) ; config . setDeleteFlagValue ( new AstLiteral ( null , "" , LiteralKind . BOOLEAN ) ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; assertThat ( loader . newModel ( "" ) . unwrap ( ) , not ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; } @ Test public void table_cached_no_timestamp ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new BasicType ( PropertyTypeKind . LONG ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . BOOLEAN ) ) . toDescription ( ) ; Configuration config = config ( ) ; config . setSidColumn ( "" ) ; config . setTimestampColumn ( "" ) ; config . setDeleteFlagColumn ( "" ) ; config . setDeleteFlagValue ( new AstLiteral ( null , "" , LiteralKind . BOOLEAN ) ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; assertThat ( loader . newModel ( "" ) . unwrap ( ) , not ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; } @ Test public void table_cached_invalid_timestamp ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new BasicType ( PropertyTypeKind . LONG ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . LONG ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . BOOLEAN ) ) . toDescription ( ) ; Configuration config = config ( ) ; config . setSidColumn ( "" ) ; config . setTimestampColumn ( "" ) ; config . setDeleteFlagColumn ( "" ) ; config . setDeleteFlagValue ( new AstLiteral ( null , "" , LiteralKind . BOOLEAN ) ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; assertThat ( loader . newModel ( "" ) . unwrap ( ) , not ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; } @ Test public void table_cached_no_delete ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new BasicType ( PropertyTypeKind . LONG ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . DATETIME ) ) . toDescription ( ) ; Configuration config = config ( ) ; config . setSidColumn ( "" ) ; config . setTimestampColumn ( "" ) ; config . setDeleteFlagColumn ( "" ) ; config . setDeleteFlagValue ( new AstLiteral ( null , "" , LiteralKind . BOOLEAN ) ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; assertThat ( loader . newModel ( "" ) . unwrap ( ) , instanceOf ( ThunderGateCacheSupport . class ) ) ; } @ Test public void table_cached_invalid_delete ( ) throws Exception { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new BasicType ( PropertyTypeKind . LONG ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . DATETIME ) ) . add ( "" , "" , new BasicType ( PropertyTypeKind . LONG ) ) . toDescription ( ) ; Configuration config = config ( ) ; config . setSidColumn ( "" ) ; config . setTimestampColumn ( "" ) ; config . setDeleteFlagColumn ( "" ) ; config . setDeleteFlagValue ( new AstLiteral ( null , "" , LiteralKind . BOOLEAN ) ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( config ) ; emitter . emit ( table ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; assertThat ( loader . newModel ( "" ) . unwrap ( ) , not ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; } private Matcher < Object > eq ( Object object ) { return is ( object ) ; } } package com . asakusafw . dmdl . thundergate . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . math . BigDecimal ; import org . apache . hadoop . io . Text ; import org . hamcrest . Matcher ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . thundergate . Constants ; import com . asakusafw . dmdl . thundergate . GeneratorTesterRoot ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . DecimalType ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . StringType ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . dmdl . thundergate . util . TableModelBuilder ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; public class RecordModelGeneratorTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new CompositeDataModelDriver ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test public void simple ( ) { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , new StringType ( ) ) . toDescription ( ) ; emitDmdl ( RecordModelGenerator . generate ( table ) ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; } @ Test public void primitives ( ) { TableModelDescription table = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . BOOLEAN ) . add ( null , "" , PropertyTypeKind . BYTE ) . add ( null , "" , PropertyTypeKind . SHORT ) . add ( null , "" , PropertyTypeKind . INT ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , PropertyTypeKind . DATE ) . add ( null , "" , PropertyTypeKind . DATETIME ) . add ( null , "" , new StringType ( ) ) . add ( null , "" , new DecimalType ( , ) ) . toDescription ( ) ; emitDmdl ( RecordModelGenerator . generate ( table ) ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , true ) ; assertThat ( object . is ( "" ) , eq ( true ) ) ; object . set ( "" , ( byte ) ) ; assertThat ( object . get ( "" ) , eq ( ( byte ) ) ) ; object . set ( "" , ( short ) ) ; assertThat ( object . get ( "" ) , eq ( ( short ) ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , new BigDecimal ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new BigDecimal ( "" ) ) ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; object . set ( "" , new Date ( , , ) ) ; assertThat ( object . get ( "" ) , eq ( new Date ( , , ) ) ) ; object . set ( "" , new DateTime ( , , , , , ) ) ; assertThat ( object . get ( "" ) , eq ( new DateTime ( , , , , , ) ) ) ; } @ Test public void primary_keys ( ) { TableModelDescription table = new TableModelBuilder ( "" ) . add ( "" , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( "" , "" , new StringType ( ) ) . toDescription ( ) ; emitDmdl ( RecordModelGenerator . generate ( table ) ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; PrimaryKey pk = object . unwrap ( ) . getClass ( ) . getAnnotation ( PrimaryKey . class ) ; assertThat ( pk , not ( nullValue ( ) ) ) ; assertThat ( pk . value ( ) , is ( new String [ ] { "" } ) ) ; } private Matcher < Object > eq ( final Object value ) { return is ( value ) ; } } package com . asakusafw . dmdl . thundergate . emitter ; import static com . asakusafw . vocabulary . model . Summarized . Aggregator . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . thundergate . Constants ; import com . asakusafw . dmdl . thundergate . GeneratorTesterRoot ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . SummarizedModelDescription ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . dmdl . thundergate . util . SummarizedModelBuilder ; import com . asakusafw . dmdl . thundergate . util . TableModelBuilder ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; import com . asakusafw . vocabulary . model . Summarized . Aggregator ; import com . asakusafw . vocabulary . model . Summarized . Term ; public class SummarizedModelGeneratorTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new CompositeDataModelDriver ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test public void simple ( ) { TableModelDescription target = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , PropertyTypeKind . INT ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , PropertyTypeKind . DATE ) . toDescription ( ) ; SummarizedModelDescription summarize = new SummarizedModelBuilder ( "" , target , "" ) . groupBy ( "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . IDENT , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . SUM , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . COUNT , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . MAX , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . MIN , "" ) . toDescription ( ) ; emitDmdl ( RecordModelGenerator . generate ( target ) ) ; emitDmdl ( SummarizedModelGenerator . generate ( summarize ) ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_VIEW ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , new Date ( , , ) ) ; assertThat ( object . get ( "" ) , eq ( new Date ( , , ) ) ) ; object . set ( "" , new Date ( , , ) ) ; assertThat ( object . get ( "" ) , eq ( new Date ( , , ) ) ) ; Summarized annotation = object . unwrap ( ) . getClass ( ) . getAnnotation ( Summarized . class ) ; assertThat ( annotation , not ( nullValue ( ) ) ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; Term term = annotation . term ( ) ; assertThat ( term . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( term . foldings ( ) . length , is ( ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( ANY , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( SUM , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( COUNT , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( MAX , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( MIN , "" , "" ) ) ) ; assertThat ( term . shuffle ( ) , is ( grouping ( "" ) ) ) ; } @ Test public void conflict_key ( ) { TableModelDescription target = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , PropertyTypeKind . INT ) . toDescription ( ) ; SummarizedModelDescription summarize = new SummarizedModelBuilder ( "" , target , "" ) . groupBy ( "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . IDENT , "" ) . add ( "" , com . asakusafw . dmdl . thundergate . model . Aggregator . COUNT , "" ) . toDescription ( ) ; emitDmdl ( RecordModelGenerator . generate ( target ) ) ; emitDmdl ( SummarizedModelGenerator . generate ( summarize ) ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_VIEW ) ; ModelWrapper object = loader . newModel ( "" ) ; Summarized annotation = object . unwrap ( ) . getClass ( ) . getAnnotation ( Summarized . class ) ; assertThat ( annotation , not ( nullValue ( ) ) ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; Term term = annotation . term ( ) ; assertThat ( term . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( term . foldings ( ) . length , is ( ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( ANY , "" , "" ) ) ) ; assertThat ( term . foldings ( ) , hasItemInArray ( mapping ( COUNT , "" , "" ) ) ) ; assertThat ( term . shuffle ( ) , is ( grouping ( "" ) ) ) ; } private Matcher < Key > grouping ( final String ... properties ) { return new BaseMatcher < Key > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Key ) { Key elem = ( Key ) object ; if ( Arrays . equals ( elem . group ( ) , properties ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( Arrays . toString ( properties ) ) ; } } ; } private Matcher < Summarized . Folding > mapping ( final Aggregator aggregator , final String src , final String dst ) { return new BaseMatcher < Summarized . Folding > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Summarized . Folding ) { Summarized . Folding elem = ( Summarized . Folding ) object ; if ( aggregator != elem . aggregator ( ) ) { return false ; } if ( src . equals ( elem . source ( ) ) == false ) { return false ; } if ( dst . equals ( elem . destination ( ) ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( aggregator + "" + src + "" + dst ) ; } } ; } private Matcher < Object > eq ( Object object ) { return is ( object ) ; } } package com . asakusafw . dmdl . thundergate . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import org . apache . hadoop . io . Text ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . thundergate . Constants ; import com . asakusafw . dmdl . thundergate . GeneratorTesterRoot ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . JoinedModelDescription ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . StringType ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . dmdl . thundergate . util . JoinedModelBuilder ; import com . asakusafw . dmdl . thundergate . util . TableModelBuilder ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; public class JoinedModelGeneratorTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new CompositeDataModelDriver ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test public void simple ( ) { TableModelDescription left = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; TableModelDescription right = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; JoinedModelDescription join = new JoinedModelBuilder ( "" , left , "" , right , "" ) . on ( "" , "" ) . add ( "" , "" ) . add ( "" , "" ) . add ( "" , "" ) . toDescription ( ) ; emitDmdl ( RecordModelGenerator . generate ( left ) ) ; emitDmdl ( RecordModelGenerator . generate ( right ) ) ; emitDmdl ( JoinedModelGenerator . generate ( join ) ) ; ModelLoader loader = generateJava ( ) ; loader . setNamespace ( Constants . SOURCE_VIEW ) ; ModelWrapper object = loader . newModel ( "" ) ; object . set ( "" , ) ; assertThat ( object . get ( "" ) , eq ( ) ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; object . set ( "" , new Text ( "" ) ) ; assertThat ( object . get ( "" ) , eq ( new Text ( "" ) ) ) ; Joined annotation = object . unwrap ( ) . getClass ( ) . getAnnotation ( Joined . class ) ; assertThat ( annotation , not ( nullValue ( ) ) ) ; assertThat ( annotation . terms ( ) . length , is ( ) ) ; loader . setNamespace ( Constants . SOURCE_TABLE ) ; Joined . Term a = annotation . terms ( ) [ ] ; assertThat ( a . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( a . mappings ( ) . length , is ( ) ) ; assertThat ( a . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( a . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( a . shuffle ( ) , is ( grouping ( "" ) ) ) ; Joined . Term b = annotation . terms ( ) [ ] ; assertThat ( b . source ( ) , eq ( loader . modelType ( "" ) ) ) ; assertThat ( b . mappings ( ) . length , is ( ) ) ; assertThat ( b . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( b . mappings ( ) , hasItemInArray ( mapping ( "" , "" ) ) ) ; assertThat ( b . shuffle ( ) , is ( grouping ( "" ) ) ) ; } private Matcher < Key > grouping ( final String ... properties ) { return new BaseMatcher < Key > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Key ) { Key elem = ( Key ) object ; if ( Arrays . equals ( elem . group ( ) , properties ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( Arrays . toString ( properties ) ) ; } } ; } private Matcher < Joined . Mapping > mapping ( final String src , final String dst ) { return new BaseMatcher < Joined . Mapping > ( ) { @ Override public boolean matches ( Object object ) { if ( object instanceof Joined . Mapping ) { Joined . Mapping elem = ( Joined . Mapping ) object ; if ( src . equals ( elem . source ( ) ) == false ) { return false ; } if ( dst . equals ( elem . destination ( ) ) == false ) { return false ; } } return true ; } @ Override public void describeTo ( Description desc ) { desc . appendText ( src + "" + dst ) ; } } ; } private Matcher < Object > eq ( final Object value ) { return is ( value ) ; } } package com . asakusafw . dmdl . thundergate . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . thundergate . GeneratorTesterRoot ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; public class ColumnOrderEmitterTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new OriginalNameEmitter ( ) ) ; emitDrivers . add ( new ColumnOrderEmitter ( ) ) ; } @ Test public void explicit ( ) { ModelLoader loaded = generateJava ( "" ) ; Class < ? > type = loaded . modelType ( "" ) ; assertThat ( type . isAnnotationPresent ( ColumnOrder . class ) , is ( true ) ) ; String [ ] order = type . getAnnotation ( ColumnOrder . class ) . value ( ) ; assertThat ( order , is ( new String [ ] { "" , "" , "" } ) ) ; } @ Test public void implicit ( ) { ModelLoader loaded = generateJava ( "" ) ; Class < ? > type = loaded . modelType ( "" ) ; assertThat ( type . isAnnotationPresent ( ColumnOrder . class ) , is ( true ) ) ; String [ ] order = type . getAnnotation ( ColumnOrder . class ) . value ( ) ; assertThat ( order , is ( new String [ ] { "" , "" , "" } ) ) ; } } package com . asakusafw . dmdl . thundergate . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . thundergate . GeneratorTesterRoot ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; public class PrimaryKeyEmitterTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new PrimaryKeyEmitter ( ) ) ; } @ Test public void pk ( ) { ModelLoader loaded = generateJava ( "" ) ; Class < ? > type = loaded . modelType ( "" ) ; assertThat ( type . isAnnotationPresent ( PrimaryKey . class ) , is ( true ) ) ; String [ ] properties = type . getAnnotation ( PrimaryKey . class ) . value ( ) ; assertThat ( properties , is ( new String [ ] { "" , "" } ) ) ; } @ Test public void invalid_empty ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_extra ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_scalar ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_type ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_unbound ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_location ( ) { shouldSemanticError ( "" ) ; } } package com . asakusafw . dmdl . thundergate . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . lang . reflect . Method ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . thundergate . GeneratorTesterRoot ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; public class OriginalNameEmitterTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new OriginalNameEmitter ( ) ) ; } @ Test public void explicit ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; Class < ? > type = loaded . modelType ( "" ) ; assertThat ( type . isAnnotationPresent ( OriginalName . class ) , is ( true ) ) ; assertThat ( type . getAnnotation ( OriginalName . class ) . value ( ) , is ( "" ) ) ; Method method = type . getMethod ( "" ) ; assertThat ( method . isAnnotationPresent ( OriginalName . class ) , is ( true ) ) ; assertThat ( method . getAnnotation ( OriginalName . class ) . value ( ) , is ( "" ) ) ; } @ Test public void simple ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; Class < ? > type = loaded . modelType ( "" ) ; assertThat ( type . isAnnotationPresent ( OriginalName . class ) , is ( true ) ) ; assertThat ( type . getAnnotation ( OriginalName . class ) . value ( ) , is ( "" ) ) ; } @ Test public void invalid_name_empty ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_name_extra ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_name_type ( ) { shouldSemanticError ( "" ) ; } } package com . asakusafw . dmdl . thundergate . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . io . Text ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . thundergate . GeneratorTesterRoot ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; public class CacheSupportEmitterTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new CacheSupportEmitter ( ) ) ; } @ Test public void cache ( ) { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; assertThat ( model . unwrap ( ) , is ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; ThunderGateCacheSupport support = ( ThunderGateCacheSupport ) model . unwrap ( ) ; model . set ( "" , ) ; assertThat ( support . __tgc__SystemId ( ) , is ( ) ) ; assertThat ( support . __tgc__TimestampColumn ( ) , is ( "" ) ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; } @ Test public void cache_no ( ) { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; assertThat ( model . unwrap ( ) , not ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; } @ Test public void cache_delete ( ) { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; assertThat ( model . unwrap ( ) , is ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; ThunderGateCacheSupport support = ( ThunderGateCacheSupport ) model . unwrap ( ) ; model . set ( "" , new Text ( "" ) ) ; assertThat ( support . __tgc__Deleted ( ) , is ( true ) ) ; model . set ( "" , new Text ( "" ) ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; model . set ( "" , null ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; } @ Test public void cache_delete_boolean ( ) { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; assertThat ( model . unwrap ( ) , is ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; ThunderGateCacheSupport support = ( ThunderGateCacheSupport ) model . unwrap ( ) ; model . set ( "" , true ) ; assertThat ( support . __tgc__Deleted ( ) , is ( true ) ) ; model . set ( "" , false ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; model . setOption ( "" , null ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; } @ Test public void cache_delete_integer ( ) { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; assertThat ( model . unwrap ( ) , is ( instanceOf ( ThunderGateCacheSupport . class ) ) ) ; ThunderGateCacheSupport support = ( ThunderGateCacheSupport ) model . unwrap ( ) ; model . set ( "" , ( byte ) ) ; assertThat ( support . __tgc__Deleted ( ) , is ( true ) ) ; model . set ( "" , ( byte ) ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; model . set ( "" , ( byte ) ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; model . setOption ( "" , null ) ; assertThat ( support . __tgc__Deleted ( ) , is ( false ) ) ; } @ Test public void invalid_cache_location ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_cache_projective ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_cache_empty ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_cache_extra ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_cache_type ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_cache_type_text ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_cache_type_boolean ( ) { shouldSemanticError ( "" ) ; } @ Test public void invalid_cache_type_integer ( ) { shouldSemanticError ( "" ) ; } } package com . asakusafw . dmdl . thundergate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . nio . charset . Charset ; import java . util . Collections ; import java . util . List ; import java . util . Properties ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . utils . collections . Lists ; public class MainTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { List < String > arguments = Lists . create ( ) ; File jdbc = jdbc ( ) ; File output = folder . newFolder ( "" ) . getCanonicalFile ( ) . getAbsoluteFile ( ) ; Collections . addAll ( arguments , "" , jdbc . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration conf = Main . loadConfigurationFromArguments ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . getJdbcDriver ( ) , is ( "" ) ) ; assertThat ( conf . getJdbcUrl ( ) , is ( "" ) ) ; assertThat ( conf . getJdbcUser ( ) , is ( "" ) ) ; assertThat ( conf . getJdbcPassword ( ) , is ( "" ) ) ; assertThat ( conf . getDatabaseName ( ) , is ( "" ) ) ; assertThat ( conf . getEncoding ( ) , is ( Charset . forName ( "" ) ) ) ; assertThat ( conf . getOutput ( ) , is ( output ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( true ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; } @ Test public void encoding_empty ( ) throws Exception { List < String > arguments = Lists . create ( ) ; File jdbc = jdbc ( ) ; File output = folder . newFolder ( "" ) . getCanonicalFile ( ) . getAbsoluteFile ( ) ; Collections . addAll ( arguments , "" , jdbc . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , output . getAbsolutePath ( ) ) ; Configuration conf = Main . loadConfigurationFromArguments ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . getEncoding ( ) , is ( Charset . forName ( "" ) ) ) ; } @ Test public void matcher_empty ( ) throws Exception { List < String > arguments = Lists . create ( ) ; File jdbc = jdbc ( ) ; File output = folder . newFolder ( "" ) . getCanonicalFile ( ) . getAbsoluteFile ( ) ; Collections . addAll ( arguments , "" , jdbc . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration conf = Main . loadConfigurationFromArguments ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( true ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( true ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; } @ Test public void matcher_only_includes ( ) throws Exception { List < String > arguments = Lists . create ( ) ; File jdbc = jdbc ( ) ; File output = folder . newFolder ( "" ) . getCanonicalFile ( ) . getAbsoluteFile ( ) ; Collections . addAll ( arguments , "" , jdbc . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration conf = Main . loadConfigurationFromArguments ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( true ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( true ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; } @ Test public void matcher_only_excludes ( ) throws Exception { List < String > arguments = Lists . create ( ) ; File jdbc = jdbc ( ) ; File output = folder . newFolder ( "" ) . getCanonicalFile ( ) . getAbsoluteFile ( ) ; Collections . addAll ( arguments , "" , jdbc . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration conf = Main . loadConfigurationFromArguments ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( true ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( true ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; } @ Test public void with_cache ( ) throws Exception { List < String > arguments = Lists . create ( ) ; File jdbc = jdbc ( ) ; File output = folder . newFolder ( "" ) . getCanonicalFile ( ) . getAbsoluteFile ( ) ; Collections . addAll ( arguments , "" , jdbc . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , output . getAbsolutePath ( ) ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Configuration conf = Main . loadConfigurationFromArguments ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; assertThat ( conf . getJdbcDriver ( ) , is ( "" ) ) ; assertThat ( conf . getJdbcUrl ( ) , is ( "" ) ) ; assertThat ( conf . getJdbcUser ( ) , is ( "" ) ) ; assertThat ( conf . getJdbcPassword ( ) , is ( "" ) ) ; assertThat ( conf . getDatabaseName ( ) , is ( "" ) ) ; assertThat ( conf . getEncoding ( ) , is ( Charset . forName ( "" ) ) ) ; assertThat ( conf . getOutput ( ) , is ( output ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( true ) ) ; assertThat ( conf . getMatcher ( ) . acceptModel ( "" ) , is ( false ) ) ; assertThat ( conf . getSidColumn ( ) , is ( "" ) ) ; assertThat ( conf . getTimestampColumn ( ) , is ( "" ) ) ; assertThat ( conf . getDeleteFlagColumn ( ) , is ( "" ) ) ; assertThat ( conf . getDeleteFlagValue ( ) . toStringValue ( ) , is ( "" ) ) ; } private File jdbc ( ) throws IOException { Properties jdbcProperties = new Properties ( ) ; jdbcProperties . setProperty ( Constants . K_JDBC_DRIVER , "" ) ; jdbcProperties . setProperty ( Constants . K_JDBC_URL , "" ) ; jdbcProperties . setProperty ( Constants . K_JDBC_USER , "" ) ; jdbcProperties . setProperty ( Constants . K_JDBC_PASSWORD , "" ) ; jdbcProperties . setProperty ( Constants . K_DATABASE_NAME , "" ) ; File jdbc = jdbc ( jdbcProperties ) ; return jdbc ; } private File jdbc ( Properties jdbcProperties ) throws IOException { File jdbc = folder . newFile ( "" ) ; FileOutputStream out = new FileOutputStream ( jdbc ) ; try { jdbcProperties . store ( out , "" ) ; } finally { out . close ( ) ; } return jdbc ; } } package com . asakusafw . dmdl . thundergate ; import java . io . File ; import java . nio . charset . Charset ; import com . asakusafw . dmdl . model . AstLiteral ; public class Configuration { private String jdbcDriver ; private String jdbcUrl ; private String jdbcUser ; private String jdbcPassword ; private String databaseName ; private File output ; private ModelMatcher matcher ; private Charset encoding ; private String sidColumn ; private String timestampColumn ; private String deleteFlagColumn ; private AstLiteral deleteFlagValue ; public String getJdbcDriver ( ) { return jdbcDriver ; } public void setJdbcDriver ( String jdbcDriver ) { this . jdbcDriver = jdbcDriver ; } public String getJdbcUrl ( ) { return jdbcUrl ; } public void setJdbcUrl ( String jdbcUrl ) { this . jdbcUrl = jdbcUrl ; } public String getJdbcUser ( ) { return jdbcUser ; } public void setJdbcUser ( String jdbcUser ) { this . jdbcUser = jdbcUser ; } public String getJdbcPassword ( ) { return jdbcPassword ; } public void setJdbcPassword ( String jdbcPassword ) { this . jdbcPassword = jdbcPassword ; } public String getDatabaseName ( ) { return databaseName ; } public void setDatabaseName ( String databaseName ) { this . databaseName = databaseName ; } public File getOutput ( ) { return output ; } public void setOutput ( File output ) { this . output = output ; } public ModelMatcher getMatcher ( ) { return matcher ; } public void setMatcher ( ModelMatcher matcher ) { this . matcher = matcher ; } public Charset getEncoding ( ) { return encoding ; } public void setEncoding ( Charset encoding ) { this . encoding = encoding ; } public String getSidColumn ( ) { return sidColumn ; } public void setSidColumn ( String sidColumn ) { this . sidColumn = sidColumn ; } public String getTimestampColumn ( ) { return timestampColumn ; } public void setTimestampColumn ( String timestampColumn ) { this . timestampColumn = timestampColumn ; } public String getDeleteFlagColumn ( ) { return deleteFlagColumn ; } public void setDeleteFlagColumn ( String deleteFlagColumn ) { this . deleteFlagColumn = deleteFlagColumn ; } public AstLiteral getDeleteFlagValue ( ) { return deleteFlagValue ; } public void setDeleteFlagValue ( AstLiteral deleteFlagValue ) { this . deleteFlagValue = deleteFlagValue ; } } package com . asakusafw . dmdl . thundergate ; package com . asakusafw . dmdl . thundergate ; import java . nio . charset . Charset ; import java . util . Collections ; import java . util . Set ; import java . util . TreeSet ; public final class Constants { public static final String VERSION = "" ; public static final Charset OUTPUT_ENCODING = Charset . forName ( "" ) ; public static final String SOURCE_TABLE = "" ; public static final String SOURCE_VIEW = "" ; public static final String K_JDBC_DRIVER = "" ; public static final String K_JDBC_URL = "" ; public static final String K_JDBC_USER = "" ; public static final String K_JDBC_PASSWORD = "" ; public static final String K_DATABASE_NAME = "" ; public static final String DMDL_LIKE_EXTENSION = "" ; public static final Set < String > SYSTEM_TABLE_NAMES ; static { Set < String > set = new TreeSet < String > ( ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; SYSTEM_TABLE_NAMES = Collections . unmodifiableSet ( set ) ; } private Constants ( ) { return ; } } package com . asakusafw . dmdl . thundergate . util ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . LinkedHashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . dmdl . thundergate . model . SummarizedModelDescription ; import com . asakusafw . utils . collections . Lists ; public class SummarizedModelBuilder extends ModelBuilder < SummarizedModelBuilder > { private String alias ; private Map < String , Source > sources ; private List < Source > groupProperties ; private List < Column > columns ; public SummarizedModelBuilder ( String tableName , ModelDescription model , String alias ) { super ( tableName ) ; this . alias = ( alias == null ) ? model . getReference ( ) . getSimpleName ( ) : alias ; this . sources = new TreeMap < String , Source > ( ) ; this . groupProperties = Lists . create ( ) ; this . columns = Lists . create ( ) ; for ( Source s : model . getPropertiesAsSources ( ) ) { sources . put ( s . getName ( ) , s ) ; } } public SummarizedModelBuilder groupBy ( String ... sourceProperties ) { if ( sourceProperties == null ) { throw new IllegalArgumentException ( "" ) ; } for ( String s : sourceProperties ) { groupProperties . add ( find ( s ) ) ; } return this ; } private Source find ( String sourceProperty ) { assert sourceProperty != null ; int qualified = sourceProperty . indexOf ( '' ) ; String simpleName ; if ( qualified < ) { simpleName = sourceProperty ; } else { String qualifier = sourceProperty . substring ( , qualified ) ; if ( alias . equals ( qualifier ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , sourceProperty , getReference ( ) ) ) ; } simpleName = sourceProperty . substring ( qualified + ) ; } Source source = sources . get ( simpleName ) ; if ( source == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , simpleName , getReference ( ) ) ) ; } return source ; } public SummarizedModelBuilder add ( String columnName , Aggregator aggregator , String sourceProperty ) { if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( aggregator == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sourceProperty == null ) { throw new IllegalArgumentException ( "" ) ; } Source source = find ( sourceProperty ) ; Column column = new Column ( columnName , aggregator , source ) ; columns . add ( column ) ; return this ; } @ Override public SummarizedModelDescription toDescription ( ) { if ( columns . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , getReference ( ) ) ) ; } List < ModelProperty > properties = Lists . create ( ) ; for ( Column column : columns ) { Aggregator aggregator = column . aggregator ; Source source = column . source ; if ( aggregator == Aggregator . IDENT && groupProperties . contains ( source ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , source . getDeclaring ( ) , source . getName ( ) , getReference ( ) ) ) ; } ModelProperty property = toProperty ( column ) ; properties . add ( property ) ; } validate ( ) ; return new SummarizedModelDescription ( getReference ( ) , properties , groupProperties ) ; } private void validate ( ) { if ( groupProperties . isEmpty ( ) ) { return ; } Set < String > rest = new LinkedHashSet < String > ( ) ; for ( Source source : groupProperties ) { rest . add ( source . getName ( ) ) ; } for ( Column column : columns ) { if ( column . aggregator == Aggregator . IDENT ) { rest . remove ( column . source . getName ( ) ) ; } } if ( rest . isEmpty ( ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , groupProperties . get ( ) . getDeclaring ( ) , rest , getReference ( ) ) ) ; } } private ModelProperty toProperty ( Column column ) { assert column != null ; Source source = new Source ( column . aggregator , column . source . getDeclaring ( ) , column . source . getName ( ) , column . source . getType ( ) , Collections . < Attribute > emptySet ( ) ) ; return new ModelProperty ( column . name , source ) ; } private static class Column { String name ; Aggregator aggregator ; Source source ; Column ( String name , Aggregator aggregator , Source source ) { assert name != null ; assert aggregator != null ; assert source != null ; this . name = name ; this . aggregator = aggregator ; this . source = source ; } } } package com . asakusafw . dmdl . thundergate . util ; import java . text . MessageFormat ; import java . util . EnumSet ; import java . util . List ; import java . util . Set ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . BasicType ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . PropertyType ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . utils . collections . Lists ; public class TableModelBuilder extends ModelBuilder < TableModelBuilder > { private List < Column > columns ; public TableModelBuilder ( String tableName ) { super ( tableName ) ; this . columns = Lists . create ( ) ; } public TableModelBuilder add ( String comment , String columnName , PropertyTypeKind basicTypeKind , Attribute ... attributes ) { if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( basicTypeKind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } Column column = new Column ( columnName , new BasicType ( basicTypeKind ) , attributes ) ; columns . add ( column ) ; return this ; } public TableModelBuilder add ( String comment , String columnName , PropertyType columnType , Attribute ... attributes ) { if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } Column column = new Column ( columnName , columnType , attributes ) ; columns . add ( column ) ; return this ; } @ Override public TableModelDescription toDescription ( ) { if ( columns . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , getReference ( ) ) ) ; } List < ModelProperty > properties = Lists . create ( ) ; for ( Column column : columns ) { ModelProperty property = toProperty ( column ) ; properties . add ( property ) ; } return new TableModelDescription ( getReference ( ) , properties ) ; } private ModelProperty toProperty ( Column column ) { assert column != null ; Source source = new Source ( Aggregator . IDENT , getReference ( ) , column . name , column . type , column . attributes ) ; return new ModelProperty ( column . name , source ) ; } private static class Column { String name ; PropertyType type ; Set < Attribute > attributes ; Column ( String name , PropertyType type , Attribute [ ] attributes ) { assert name != null ; assert type != null ; assert attributes != null ; this . name = name ; this . type = type ; this . attributes = EnumSet . noneOf ( Attribute . class ) ; for ( Attribute attr : attributes ) { this . attributes . add ( attr ) ; } } } } package com . asakusafw . dmdl . thundergate . util ; package com . asakusafw . dmdl . thundergate . util ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelReference ; public abstract class ModelBuilder < T extends ModelBuilder < T > > { private String simpleName ; public ModelBuilder ( String simpleName ) { if ( simpleName == null ) { throw new IllegalArgumentException ( "" ) ; } this . simpleName = simpleName ; } public ModelReference getReference ( ) { return new ModelReference ( simpleName ) ; } public abstract ModelDescription toDescription ( ) ; } package com . asakusafw . dmdl . thundergate . util ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import com . asakusafw . dmdl . thundergate . model . JoinedModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . utils . collections . Lists ; public class JoinedModelBuilder extends ModelBuilder < JoinedModelBuilder > { private final List < String > columns ; private final Side left ; private final Side right ; public JoinedModelBuilder ( String name , ModelDescription left , String leftAlias , ModelDescription right , String rightAlias ) { super ( name ) ; if ( left == null ) { throw new IllegalArgumentException ( "" ) ; } if ( right == null ) { throw new IllegalArgumentException ( "" ) ; } this . columns = Lists . create ( ) ; this . left = new Side ( left ) ; this . right = new Side ( right ) ; if ( leftAlias != null ) { this . left . alias = leftAlias ; } if ( rightAlias != null ) { this . right . alias = rightAlias ; } if ( this . left . alias . equals ( this . right . alias ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , this . left . alias ) ) ; } } public JoinedModelBuilder on ( String aProperty , String bProperty ) { if ( aProperty == null ) { throw new IllegalArgumentException ( "" ) ; } if ( bProperty == null ) { throw new IllegalArgumentException ( "" ) ; } Ref a = resolve ( aProperty ) ; Ref b = resolve ( bProperty ) ; if ( a . side == b . side ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , aProperty , bProperty ) ) ; } a . side . condition . add ( a . side . find ( a . name ) ) ; b . side . condition . add ( b . side . find ( b . name ) ) ; return this ; } public JoinedModelBuilder add ( String columnName , String sourceProperty ) { if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sourceProperty == null ) { throw new IllegalArgumentException ( "" ) ; } Ref source = resolve ( sourceProperty ) ; columns . add ( columnName ) ; source . side . mapping . put ( source . name , columnName ) ; return this ; } @ Override public JoinedModelDescription toDescription ( ) { if ( left . condition . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , getReference ( ) ) ) ; } if ( columns . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , getReference ( ) ) ) ; } pairingTrivialSource ( left , right ) ; pairingTrivialSource ( right , left ) ; return new JoinedModelDescription ( getReference ( ) , buildProperties ( ) , left . condition , right . condition ) ; } private void pairingTrivialSource ( Side a , Side b ) { assert a != null ; assert b != null ; for ( int i = , n = a . condition . size ( ) ; i < n ; i ++ ) { Source as = a . condition . get ( i ) ; Source bs = b . condition . get ( i ) ; if ( a . mapping . get ( as . getName ( ) ) != null && b . mapping . get ( bs . getName ( ) ) == null ) { String column = a . mapping . get ( as . getName ( ) ) ; b . mapping . put ( bs . getName ( ) , column ) ; } } } private List < ModelProperty > buildProperties ( ) { Map < String , SourcePair > pairs = new TreeMap < String , SourcePair > ( ) ; for ( String mapTo : columns ) { pairs . put ( mapTo , new SourcePair ( ) ) ; } for ( Map . Entry < String , String > entry : left . mapping . entrySet ( ) ) { String mapTo = entry . getValue ( ) ; assert mapTo == null || pairs . containsKey ( mapTo ) ; if ( mapTo == null ) { continue ; } Source source = left . sources . get ( entry . getKey ( ) ) ; pairs . get ( mapTo ) . left = source ; } for ( Map . Entry < String , String > entry : right . mapping . entrySet ( ) ) { String mapTo = entry . getValue ( ) ; assert mapTo == null || pairs . containsKey ( mapTo ) ; if ( mapTo == null ) { continue ; } Source source = right . sources . get ( entry . getKey ( ) ) ; pairs . get ( mapTo ) . right = source ; } List < ModelProperty > properties = Lists . create ( ) ; for ( String mapTo : columns ) { SourcePair sources = pairs . get ( mapTo ) ; assert sources != null ; assert sources . left != null || sources . right != null ; ModelProperty property = new ModelProperty ( mapTo , sources . left , sources . right ) ; properties . add ( property ) ; } return properties ; } private Ref resolve ( String source ) { assert source != null ; int qualified = source . indexOf ( '' ) ; if ( qualified < ) { boolean leftHit = left . mapping . containsKey ( source ) ; boolean rightHit = right . mapping . containsKey ( source ) ; if ( leftHit && rightHit ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , source , getReference ( ) ) ) ; } if ( leftHit == false && rightHit == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , source , getReference ( ) ) ) ; } if ( leftHit ) { return new Ref ( left , source ) ; } else { return new Ref ( right , source ) ; } } else { String qualifier = source . substring ( , qualified ) ; String column = source . substring ( qualified + ) ; if ( left . alias . equals ( qualifier ) ) { return new Ref ( left , column ) ; } else if ( right . alias . equals ( qualifier ) ) { return new Ref ( right , column ) ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , qualifier , source ) ) ; } } } private static class Side { ModelDescription model ; Map < String , Source > sources ; String alias ; List < Source > condition ; Map < String , String > mapping ; Side ( ModelDescription model ) { assert model != null ; this . model = model ; this . sources = new TreeMap < String , Source > ( ) ; this . alias = model . getReference ( ) . getSimpleName ( ) ; this . condition = Lists . create ( ) ; this . mapping = new TreeMap < String , String > ( ) ; for ( Source s : model . getPropertiesAsSources ( ) ) { sources . put ( s . getName ( ) , s ) ; mapping . put ( s . getName ( ) , null ) ; } } Source find ( String columnName ) { assert columnName != null ; if ( sources . containsKey ( columnName ) ) { return sources . get ( columnName ) ; } throw new IllegalArgumentException ( MessageFormat . format ( "" , model . getReference ( ) , columnName ) ) ; } } private static class Ref { Side side ; String name ; public Ref ( Side side , String name ) { assert side != null ; assert name != null ; this . side = side ; this . name = name ; } } private static class SourcePair { Source left ; Source right ; SourcePair ( ) { return ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , left == null ? "" : left . getName ( ) , right == null ? "" : right . getName ( ) ) ; } } } package com . asakusafw . dmdl . thundergate . driver ; import java . util . List ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . semantics . Trait ; import com . asakusafw . utils . collections . Lists ; public class PrimaryKeyTrait implements Trait < PrimaryKeyTrait > { private final AstNode originalAst ; private final List < PropertySymbol > properties ; public PrimaryKeyTrait ( AstNode originalAst , List < PropertySymbol > properties ) { this . originalAst = originalAst ; this . properties = Lists . freeze ( properties ) ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public List < PropertySymbol > getProperties ( ) { return properties ; } } package com . asakusafw . dmdl . thundergate . driver ; package com . asakusafw . dmdl . thundergate . driver ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . AstAttributeValue ; import com . asakusafw . dmdl . model . AstAttributeValueArray ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . spi . ModelAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . utils . collections . Lists ; public class PrimaryKeyDriver extends ModelAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { List < PropertySymbol > properties = getProperties ( environment , declaration , attribute ) ; declaration . putTrait ( PrimaryKeyTrait . class , new PrimaryKeyTrait ( attribute , properties ) ) ; } private List < PropertySymbol > getProperties ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { assert environment != null ; assert declaration != null ; assert attribute != null ; Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; AstAttributeElement nameElement = elements . remove ( ELEMENT_NAME ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; if ( nameElement == null ) { environment . report ( new Diagnostic ( Level . ERROR , attribute . name , "" , TARGET_NAME , ELEMENT_NAME ) ) ; return Collections . emptyList ( ) ; } else if ( ( nameElement . value instanceof AstAttributeValueArray ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , nameElement , "" , TARGET_NAME , ELEMENT_NAME ) ) ; return Collections . emptyList ( ) ; } AstAttributeValueArray array = ( AstAttributeValueArray ) nameElement . value ; List < PropertySymbol > properties = Lists . create ( ) ; for ( AstAttributeValue value : array . elements ) { if ( ( value instanceof AstSimpleName ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , value , "" , TARGET_NAME , ELEMENT_NAME ) ) ; continue ; } PropertySymbol property = declaration . createPropertySymbol ( ( AstSimpleName ) value ) ; if ( property . findDeclaration ( ) == null ) { environment . report ( new Diagnostic ( Level . ERROR , value , "" , value , declaration . getName ( ) ) ) ; continue ; } properties . add ( property ) ; } return properties ; } } package com . asakusafw . dmdl . thundergate . driver ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . LiteralKind ; import com . asakusafw . dmdl . semantics . Declaration ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . spi . AttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class OriginalNameDriver extends AttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , Declaration declaration , AstAttribute attribute ) { assert attribute . name . toString ( ) . equals ( TARGET_NAME ) ; String value = getString ( environment , attribute ) ; if ( value != null ) { declaration . putTrait ( OriginalNameTrait . class , new OriginalNameTrait ( attribute , value ) ) ; } } private String getString ( DmdlSemantics environment , AstAttribute attribute ) { assert environment != null ; assert attribute != null ; Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; AstAttributeElement target = elements . remove ( ELEMENT_NAME ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; if ( target == null ) { environment . report ( new Diagnostic ( Level . ERROR , attribute . name , "" , TARGET_NAME , ELEMENT_NAME ) ) ; return null ; } else if ( ( target . value instanceof AstLiteral ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , target , "" , TARGET_NAME , ELEMENT_NAME ) ) ; return null ; } else { AstLiteral literal = ( AstLiteral ) target . value ; if ( literal . kind != LiteralKind . STRING ) { environment . report ( new Diagnostic ( Level . ERROR , target , "" , TARGET_NAME , ELEMENT_NAME ) ) ; return null ; } return literal . toStringValue ( ) ; } } } package com . asakusafw . dmdl . thundergate . driver ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . semantics . Trait ; public class CacheSupportTrait implements Trait < CacheSupportTrait > { private final AstNode originalAst ; private final PropertySymbol sid ; private final PropertySymbol timestamp ; private final PropertySymbol deleteFlag ; private final AstLiteral deleteFlagValue ; public CacheSupportTrait ( AstNode originalAst , PropertySymbol sid , PropertySymbol timestamp , PropertySymbol deleteFlag , AstLiteral deleteFlagValue ) { if ( sid == null ) { throw new IllegalArgumentException ( "" ) ; } if ( timestamp == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . sid = sid ; this . timestamp = timestamp ; this . deleteFlag = deleteFlag ; this . deleteFlagValue = deleteFlagValue ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public PropertySymbol getSid ( ) { return sid ; } public PropertySymbol getTimestamp ( ) { return timestamp ; } public PropertySymbol getDeleteFlag ( ) { return deleteFlag ; } public AstLiteral getDeleteFlagValue ( ) { return deleteFlagValue ; } } package com . asakusafw . dmdl . thundergate . driver ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . Declaration ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; public class OriginalNameEmitter extends JavaDataModelDriver { @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) { ModelFactory f = context . getModelFactory ( ) ; Expression value = Models . toLiteral ( f , getOriginalName ( model ) ) ; return new AttributeBuilder ( f ) . annotation ( context . resolve ( OriginalName . class ) , "" , value ) . toAnnotations ( ) ; } @ Override public List < Annotation > getMemberAnnotations ( EmitContext context , PropertyDeclaration property ) { OriginalNameTrait trait = property . getTrait ( OriginalNameTrait . class ) ; if ( trait == null ) { return Collections . emptyList ( ) ; } ModelFactory f = context . getModelFactory ( ) ; Expression value = Models . toLiteral ( f , trait . getName ( ) ) ; return new AttributeBuilder ( f ) . annotation ( context . resolve ( OriginalName . class ) , "" , value ) . toAnnotations ( ) ; } public static String getOriginalName ( Declaration declaration ) { if ( declaration == null ) { throw new IllegalArgumentException ( "" ) ; } OriginalNameTrait trait = declaration . getTrait ( OriginalNameTrait . class ) ; if ( trait == null ) { return declaration . getName ( ) . getSimpleName ( ) . identifier . toUpperCase ( ) ; } else { return trait . getName ( ) ; } } } package com . asakusafw . dmdl . thundergate . driver ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; public class ColumnOrderEmitter extends JavaDataModelDriver { @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) { ModelFactory f = context . getModelFactory ( ) ; List < Expression > columns = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { columns . add ( Models . toLiteral ( f , OriginalNameEmitter . getOriginalName ( property ) ) ) ; } return new AttributeBuilder ( f ) . annotation ( context . resolve ( ColumnOrder . class ) , "" , f . newArrayInitializer ( columns ) ) . toAnnotations ( ) ; } } package com . asakusafw . dmdl . thundergate . driver ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . dmdl . spi . ModelAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class CacheSupportDriver extends ModelAttributeDriver { public static final String TARGET_NAME = "" ; public static final String SID_ELEMENT_NAME = "" ; public static final String TIMESTAMP_ELEMENT_NAME = "" ; public static final String DELETE_FLAG_ELEMENT_NAME = "" ; public static final String DELETE_FLAG_VALUE_ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { if ( declaration . getOriginalAst ( ) . kind != ModelDefinitionKind . RECORD ) { environment . report ( new Diagnostic ( Level . ERROR , declaration . getOriginalAst ( ) , "" , TARGET_NAME ) ) ; return ; } Holder holder = new Holder ( environment , declaration , attribute ) ; PropertySymbol sid = holder . takeProperty ( SID_ELEMENT_NAME ) ; PropertySymbol timestamp = holder . takeProperty ( TIMESTAMP_ELEMENT_NAME ) ; PropertySymbol delete = holder . takeProperty ( DELETE_FLAG_ELEMENT_NAME ) ; AstLiteral deleteValue = holder . takeLiteral ( DELETE_FLAG_VALUE_ELEMENT_NAME ) ; holder . checkEmpty ( ) ; if ( holder . sawError ) { return ; } holder . checkDefined ( SID_ELEMENT_NAME , sid ) ; holder . checkDefined ( TIMESTAMP_ELEMENT_NAME , timestamp ) ; if ( delete != null || deleteValue != null ) { holder . checkDefined ( DELETE_FLAG_ELEMENT_NAME , delete ) ; holder . checkDefined ( DELETE_FLAG_VALUE_ELEMENT_NAME , deleteValue ) ; } if ( holder . sawError ) { return ; } if ( type ( sid ) != BasicTypeKind . LONG ) { holder . error ( sid . getName ( ) , "" , sid . getName ( ) . identifier ) ; } if ( type ( timestamp ) != BasicTypeKind . DATETIME ) { holder . error ( timestamp . getName ( ) , "" , timestamp . getName ( ) . identifier ) ; } checkDeleteFlag ( holder , delete , deleteValue ) ; if ( holder . sawError ) { return ; } declaration . putTrait ( CacheSupportTrait . class , new CacheSupportTrait ( attribute , sid , timestamp , delete , deleteValue ) ) ; } private void checkDeleteFlag ( Holder holder , PropertySymbol delete , AstLiteral deleteValue ) { assert holder != null ; if ( delete != null ) { assert deleteValue != null ; BasicTypeKind deleteType = type ( delete ) ; switch ( deleteValue . getKind ( ) ) { case BOOLEAN : if ( deleteType != BasicTypeKind . BOOLEAN ) { holder . error ( delete . getName ( ) , "" , delete . getName ( ) . identifier ) ; } break ; case INTEGER : if ( deleteType != BasicTypeKind . BYTE && deleteType != BasicTypeKind . SHORT && deleteType != BasicTypeKind . INT && deleteType != BasicTypeKind . LONG ) { holder . error ( delete . getName ( ) , "" , delete . getName ( ) . identifier ) ; } break ; case STRING : if ( deleteType != BasicTypeKind . TEXT ) { holder . error ( delete . getName ( ) , "" , delete . getName ( ) . identifier ) ; } break ; default : holder . error ( deleteValue , "" , deleteValue ) ; } } } private BasicTypeKind type ( PropertySymbol symbol ) { assert symbol != null ; PropertyDeclaration decl = symbol . findDeclaration ( ) ; assert decl != null ; Type type = decl . getType ( ) ; if ( ( type instanceof BasicType ) == false ) { return null ; } return ( ( BasicType ) type ) . getKind ( ) ; } private static class Holder { private final DmdlSemantics environment ; private final ModelDeclaration model ; private final AstAttribute attribute ; private final Map < String , AstAttributeElement > elements ; boolean sawError ; public Holder ( DmdlSemantics environment , ModelDeclaration model , AstAttribute attribute ) { assert environment != null ; assert model != null ; assert attribute != null ; this . environment = environment ; this . model = model ; this . attribute = attribute ; this . elements = AttributeUtil . getElementMap ( attribute ) ; this . sawError = false ; } public void checkEmpty ( ) { if ( elements . isEmpty ( ) == false ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; sawError = true ; } } public void checkDefined ( String elementName , Object value ) { assert elementName != null ; if ( value == null ) { error ( attribute . name , "" , TARGET_NAME , elementName ) ; } } PropertySymbol takeProperty ( String elementName ) { assert elementName != null ; AstAttributeElement nameElement = elements . remove ( elementName ) ; if ( nameElement == null ) { return null ; } else if ( ( nameElement . value instanceof AstSimpleName ) == false ) { error ( nameElement , "" , TARGET_NAME , elementName ) ; return null ; } AstSimpleName value = ( AstSimpleName ) nameElement . value ; PropertySymbol property = model . createPropertySymbol ( value ) ; if ( property . findDeclaration ( ) == null ) { error ( value , "" , value , model . getName ( ) ) ; return null ; } return property ; } AstLiteral takeLiteral ( String elementName ) { assert elementName != null ; AstAttributeElement nameElement = elements . remove ( elementName ) ; if ( nameElement == null ) { return null ; } else if ( ( nameElement . value instanceof AstLiteral ) == false ) { error ( nameElement , "" , TARGET_NAME , elementName ) ; return null ; } return ( AstLiteral ) nameElement . value ; } void error ( AstNode elemenet , String format , Object ... arguments ) { environment . report ( new Diagnostic ( Level . ERROR , attribute , format , arguments ) ) ; sawError = true ; } } } package com . asakusafw . dmdl . thundergate . driver ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; public class PrimaryKeyEmitter extends JavaDataModelDriver { @ Override public List < Annotation > getTypeAnnotations ( EmitContext context , ModelDeclaration model ) { PrimaryKeyTrait trait = model . getTrait ( PrimaryKeyTrait . class ) ; if ( trait == null ) { return Collections . emptyList ( ) ; } ModelFactory f = context . getModelFactory ( ) ; List < Expression > properties = Lists . create ( ) ; for ( PropertySymbol property : trait . getProperties ( ) ) { String name = context . getFieldName ( property . findDeclaration ( ) ) . getToken ( ) ; properties . add ( Models . toLiteral ( f , name ) ) ; } return new AttributeBuilder ( f ) . annotation ( context . resolve ( PrimaryKey . class ) , "" , f . newArrayInitializer ( properties ) ) . toAnnotations ( ) ; } } package com . asakusafw . dmdl . thundergate . driver ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . Trait ; public class OriginalNameTrait implements Trait < OriginalNameTrait > { private final AstNode originalAst ; private final String originalName ; public OriginalNameTrait ( AstNode originalAst , String originalName ) { this . originalAst = originalAst ; this . originalName = originalName ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public String getName ( ) { return originalName ; } } package com . asakusafw . dmdl . thundergate . driver ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . Text ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . PropertySymbol ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class CacheSupportEmitter extends JavaDataModelDriver { private static final String FIELD_DELETE_FLAG_VALUE = "" ; @ Override public List < Type > getInterfaces ( EmitContext context , ModelDeclaration model ) throws IOException { if ( isTarget ( model ) == false ) { return Collections . emptyList ( ) ; } return Arrays . asList ( context . resolve ( ThunderGateCacheSupport . class ) ) ; } @ Override public List < FieldDeclaration > getFields ( EmitContext context , ModelDeclaration model ) throws IOException { if ( isTarget ( model ) == false ) { return Collections . emptyList ( ) ; } CacheSupportTrait trait = model . getTrait ( CacheSupportTrait . class ) ; assert trait != null ; List < FieldDeclaration > results = Lists . create ( ) ; if ( trait . getDeleteFlagValue ( ) != null ) { results . add ( createDeleteFlagValueField ( context , model , trait . getDeleteFlagValue ( ) ) ) ; } return results ; } @ Override public List < MethodDeclaration > getMethods ( EmitContext context , ModelDeclaration model ) throws IOException { if ( isTarget ( model ) == false ) { return Collections . emptyList ( ) ; } CacheSupportTrait trait = model . getTrait ( CacheSupportTrait . class ) ; assert trait != null ; List < MethodDeclaration > results = Lists . create ( ) ; results . add ( createModelVersionMethod ( context , model , trait ) ) ; results . add ( createTimestampColumnMethod ( context , model , trait . getTimestamp ( ) ) ) ; results . add ( createSystemIdMethod ( context , model , trait . getSid ( ) ) ) ; results . add ( createDeletedMethod ( context , model , trait . getDeleteFlag ( ) ) ) ; return results ; } private FieldDeclaration createDeleteFlagValueField ( EmitContext context , ModelDeclaration model , AstLiteral deleteFlagValue ) { assert context != null ; assert model != null ; assert deleteFlagValue != null ; ModelFactory f = context . getModelFactory ( ) ; Type type ; Expression value ; switch ( deleteFlagValue . kind ) { case BOOLEAN : type = context . resolve ( boolean . class ) ; value = Models . toLiteral ( f , deleteFlagValue . toBooleanValue ( ) ) ; break ; case INTEGER : type = context . resolve ( int . class ) ; value = Models . toLiteral ( f , deleteFlagValue . toIntegerValue ( ) . intValue ( ) ) ; break ; case STRING : type = context . resolve ( Text . class ) ; value = new TypeBuilder ( f , context . resolve ( Text . class ) ) . newObject ( Models . toLiteral ( f , deleteFlagValue . toStringValue ( ) ) ) . toExpression ( ) ; break ; default : throw new AssertionError ( deleteFlagValue ) ; } return f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Static ( ) . Final ( ) . toAttributes ( ) , type , f . newSimpleName ( FIELD_DELETE_FLAG_VALUE ) , value ) ; } private MethodDeclaration createModelVersionMethod ( EmitContext context , ModelDeclaration model , CacheSupportTrait trait ) { assert context != null ; assert model != null ; assert trait != null ; ModelFactory f = context . getModelFactory ( ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , computeModelVersion ( context , model , trait ) ) ) . toReturnStatement ( ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( long . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private long computeModelVersion ( EmitContext context , ModelDeclaration model , CacheSupportTrait trait ) { assert context != null ; assert model != null ; assert trait != null ; long hash = ; final long prime = ; hash = hash * prime + context . getQualifiedTypeName ( ) . toNameString ( ) . hashCode ( ) ; hash = hash * prime + trait . getSid ( ) . getName ( ) . identifier . hashCode ( ) ; hash = hash * prime + trait . getTimestamp ( ) . getName ( ) . identifier . hashCode ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { hash = hash * prime + property . getName ( ) . identifier . hashCode ( ) ; com . asakusafw . dmdl . semantics . Type type = property . getType ( ) ; assert type instanceof BasicType ; hash = hash * prime + ( ( BasicType ) type ) . getKind ( ) . name ( ) . hashCode ( ) ; } return hash ; } private MethodDeclaration createTimestampColumnMethod ( EmitContext context , ModelDeclaration model , PropertySymbol timestamp ) { assert context != null ; assert model != null ; assert timestamp != null ; ModelFactory f = context . getModelFactory ( ) ; String name = OriginalNameEmitter . getOriginalName ( timestamp . findDeclaration ( ) ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , name ) ) . toReturnStatement ( ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( String . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createSystemIdMethod ( EmitContext context , ModelDeclaration model , PropertySymbol sid ) { assert context != null ; assert model != null ; assert sid != null ; ModelFactory f = context . getModelFactory ( ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new ExpressionBuilder ( f , f . newThis ( ) ) . method ( context . getValueGetterName ( sid . findDeclaration ( ) ) ) . toReturnStatement ( ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( long . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createDeletedMethod ( EmitContext context , ModelDeclaration model , PropertySymbol deleteFlagOrNull ) { assert context != null ; assert model != null ; ModelFactory f = context . getModelFactory ( ) ; List < Statement > statements = Lists . create ( ) ; if ( deleteFlagOrNull == null ) { statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , false ) ) . toReturnStatement ( ) ) ; } else { statements . add ( new ExpressionBuilder ( f , f . newThis ( ) ) . method ( context . getOptionGetterName ( deleteFlagOrNull . findDeclaration ( ) ) ) . method ( "" , f . newSimpleName ( FIELD_DELETE_FLAG_VALUE ) ) . toReturnStatement ( ) ) ; } return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( boolean . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private boolean isTarget ( ModelDeclaration model ) { assert model != null ; return model . getTrait ( CacheSupportTrait . class ) != null ; } } package com . asakusafw . dmdl . thundergate ; import java . io . IOException ; import java . sql . SQLException ; import java . text . MessageFormat ; import java . util . List ; import java . util . concurrent . Callable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . thundergate . emitter . ThunderGateModelEmitter ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelRepository ; import com . asakusafw . dmdl . thundergate . source . DatabaseSource ; public class GenerateTask implements Callable < ModelRepository > { static final Logger LOG = LoggerFactory . getLogger ( GenerateTask . class ) ; private final Configuration configuration ; public GenerateTask ( Configuration configuration ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . configuration = configuration ; } @ Override public ModelRepository call ( ) { ModelRepository repository = new ModelRepository ( ) ; try { collectFromDb ( repository ) ; } catch ( IOException e ) { LOG . error ( "" , e ) ; return null ; } catch ( SQLException e ) { LOG . error ( "" , e ) ; e . printStackTrace ( ) ; } try { collectFromViews ( repository ) ; } catch ( IOException e ) { LOG . error ( "" , e ) ; return null ; } catch ( SQLException e ) { LOG . error ( "" , e ) ; e . printStackTrace ( ) ; } emit ( repository ) ; return repository ; } private void collectFromDb ( ModelRepository repository ) throws IOException , SQLException { LOG . info ( "" , configuration . getJdbcUrl ( ) ) ; DatabaseSource source = new DatabaseSource ( configuration . getJdbcDriver ( ) , configuration . getJdbcUrl ( ) , configuration . getJdbcUser ( ) , configuration . getJdbcPassword ( ) , configuration . getDatabaseName ( ) ) ; try { List < ModelDescription > collected = source . collectTables ( configuration . getMatcher ( ) ) ; for ( ModelDescription model : collected ) { LOG . info ( "" , model . getReference ( ) ) ; repository . add ( model ) ; } LOG . info ( "" , collected . size ( ) ) ; } finally { source . close ( ) ; } } private void collectFromViews ( ModelRepository repository ) throws IOException , SQLException { LOG . info ( "" , configuration . getJdbcUrl ( ) ) ; DatabaseSource source = new DatabaseSource ( configuration . getJdbcDriver ( ) , configuration . getJdbcUrl ( ) , configuration . getJdbcUser ( ) , configuration . getJdbcPassword ( ) , configuration . getDatabaseName ( ) ) ; try { List < ModelDescription > collected = source . collectViews ( repository , configuration . getMatcher ( ) ) ; for ( ModelDescription model : collected ) { LOG . info ( "" , model . getReference ( ) ) ; repository . add ( model ) ; } LOG . info ( "" , collected . size ( ) ) ; } finally { source . close ( ) ; } } private void emit ( ModelRepository repository ) { List < ModelDescription > models = repository . all ( ) ; int total = models . size ( ) ; LOG . info ( "" , total , configuration . getOutput ( ) ) ; ThunderGateModelEmitter emitter = new ThunderGateModelEmitter ( configuration ) ; int successCount = ; int failedCount = ; for ( ModelDescription model : models ) { LOG . info ( "" , model . getReference ( ) , ( total - successCount - failedCount ) ) ; try { emitter . emit ( model ) ; successCount ++ ; } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , model . getReference ( ) ) , e ) ; failedCount ++ ; } } if ( failedCount >= ) { LOG . error ( "" , failedCount ) ; } else { LOG . info ( "" , total ) ; } } } package com . asakusafw . dmdl . thundergate . source ; import java . util . Map ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . utils . collections . Maps ; public enum MySqlDataType { TINY_INT ( "" , PropertyTypeKind . BYTE ) , SMALL_INT ( "" , PropertyTypeKind . SHORT ) , INT ( "" , PropertyTypeKind . INT ) , LONG ( "" , PropertyTypeKind . LONG ) , FLOAT ( "" , PropertyTypeKind . FLOAT ) , DOUBLE ( "" , PropertyTypeKind . DOUBLE ) , DECIMAL ( "" , PropertyTypeKind . BIG_DECIMAL ) , DATE ( "" , PropertyTypeKind . DATE ) , DATETIME ( "" , PropertyTypeKind . DATETIME ) , TIMESTAMP ( "" , PropertyTypeKind . DATETIME ) , CHAR ( "" , PropertyTypeKind . STRING ) , VARCHAR ( "" , PropertyTypeKind . STRING ) , TINYTEXT ( "" , PropertyTypeKind . STRING ) , TEXT ( "" , PropertyTypeKind . STRING ) , MEDIUMTEXT ( "" , PropertyTypeKind . STRING ) , LONGTEXT ( "" , PropertyTypeKind . STRING ) , ; private String dataTypeString ; private PropertyTypeKind propertyTypeKind ; private MySqlDataType ( String str , PropertyTypeKind type ) { assert str != null ; assert type != null ; this . dataTypeString = str ; this . propertyTypeKind = type ; } private static Map < String , MySqlDataType > dataTypeMap = Maps . create ( ) ; static { for ( MySqlDataType type : MySqlDataType . values ( ) ) { String mySqlStr = type . getDataTypeString ( ) ; if ( dataTypeMap . containsKey ( mySqlStr ) ) { throw new RuntimeException ( "" ) ; } dataTypeMap . put ( mySqlStr , type ) ; } } private static Map < String , PropertyTypeKind > propertyMap = Maps . create ( ) ; static { for ( MySqlDataType type : MySqlDataType . values ( ) ) { String mySqlStr = type . getDataTypeString ( ) ; if ( propertyMap . containsKey ( mySqlStr ) ) { throw new RuntimeException ( "" ) ; } propertyMap . put ( mySqlStr , type . getPropertyType ( ) ) ; } } public static MySqlDataType getDataTypeByString ( String str ) { return dataTypeMap . get ( str ) ; } public static PropertyTypeKind getPropertyTypeByString ( String str ) { return propertyMap . get ( str ) ; } public String getDataTypeString ( ) { return dataTypeString ; } public PropertyTypeKind getPropertyType ( ) { return propertyTypeKind ; } } package com . asakusafw . dmdl . thundergate . source ; import java . io . Closeable ; import java . io . IOException ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . thundergate . ModelMatcher ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . DecimalType ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelRepository ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . StringType ; import com . asakusafw . dmdl . thundergate . util . TableModelBuilder ; import com . asakusafw . dmdl . thundergate . view . ViewAnalyzer ; import com . asakusafw . dmdl . thundergate . view . ViewDefinition ; import com . asakusafw . dmdl . thundergate . view . ViewParser ; import com . asakusafw . dmdl . thundergate . view . model . CreateView ; import com . asakusafw . utils . collections . Lists ; public class DatabaseSource implements Closeable { @ SuppressWarnings ( "" ) private static final String STR_IS_PK = "" ; private static final String STR_NOT_NULL = "" ; static final Logger LOG = LoggerFactory . getLogger ( DatabaseSource . class ) ; private final Connection conn ; private final String databaseName ; public DatabaseSource ( String jdbcDriver , String jdbcUrl , String user , String password , String databaseName ) throws IOException , SQLException { if ( jdbcDriver == null ) { throw new IllegalArgumentException ( "" ) ; } if ( jdbcUrl == null ) { throw new IllegalArgumentException ( "" ) ; } if ( user == null ) { throw new IllegalArgumentException ( "" ) ; } if ( password == null ) { throw new IllegalArgumentException ( "" ) ; } if ( databaseName == null ) { throw new IllegalArgumentException ( "" ) ; } this . databaseName = databaseName ; try { Class . forName ( jdbcDriver ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( "" , e ) ; } conn = DriverManager . getConnection ( jdbcUrl , user , password ) ; } public List < ModelDescription > collectTables ( ModelMatcher filter ) throws IOException , SQLException { String sql = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; List < ModelDescription > results = Lists . create ( ) ; PreparedStatement ps = null ; ResultSet rs = null ; try { ps = conn . prepareStatement ( sql ) ; ps . setString ( , databaseName ) ; rs = ps . executeQuery ( ) ; String prevTableName = null ; TableModelBuilder builder = null ; while ( rs . next ( ) ) { String tableName = rs . getString ( ) ; String columnName = rs . getString ( ) ; String columnComment = rs . getString ( ) ; String dataType = rs . getString ( ) ; long characterMaximumLength = rs . getLong ( ) ; int numericPrecision = rs . getInt ( ) ; int numericScale = rs . getInt ( ) ; String isNullable = rs . getString ( ) ; String columnKey = rs . getString ( ) ; if ( filter . acceptModel ( tableName ) == false ) { if ( tableName . equals ( prevTableName ) == false ) { LOG . info ( "" , tableName ) ; prevTableName = tableName ; } continue ; } if ( builder == null || prevTableName == null || prevTableName . equals ( tableName ) == false ) { if ( builder != null ) { results . add ( builder . toDescription ( ) ) ; } builder = new TableModelBuilder ( tableName ) ; prevTableName = tableName ; } PropertyTypeKind propertyType = MySqlDataType . getPropertyTypeByString ( dataType ) ; if ( propertyType == null ) { LOG . error ( "" , new Object [ ] { dataType , tableName , columnName , } ) ; continue ; } List < Attribute > attributeList = Lists . create ( ) ; if ( isNullable != null && isNullable . equals ( STR_NOT_NULL ) ) { attributeList . add ( Attribute . NOT_NULL ) ; } if ( columnKey != null && columnKey . equals ( MySQLConstants . STR_IS_PK ) ) { attributeList . add ( Attribute . PRIMARY_KEY ) ; } Attribute [ ] attributes = attributeList . toArray ( new Attribute [ attributeList . size ( ) ] ) ; switch ( propertyType ) { case BIG_DECIMAL : DecimalType decimalType = new DecimalType ( numericPrecision , numericScale ) ; builder . add ( columnComment , columnName , decimalType , attributes ) ; break ; case STRING : StringType stringType = new StringType ( ( int ) characterMaximumLength ) ; builder . add ( columnComment , columnName , stringType , attributes ) ; break ; default : builder . add ( columnComment , columnName , propertyType , attributes ) ; break ; } } if ( builder != null ) { results . add ( builder . toDescription ( ) ) ; } } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } if ( ps != null ) { try { ps . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } } return results ; } public List < ModelDescription > collectViews ( ModelRepository repository , ModelMatcher filter ) throws IOException , SQLException { List < ViewDefinition > definitions = collectViewDefinitions ( filter ) ; LOG . info ( "" , definitions . size ( ) ) ; ViewAnalyzer analyzer = new ViewAnalyzer ( ) ; for ( ViewDefinition definition : definitions ) { LOG . info ( "" , definition . name ) ; CreateView tree = ViewParser . parse ( definition ) ; analyzer . add ( tree ) ; } List < ModelDescription > results = analyzer . analyze ( repository ) ; return results ; } private List < ViewDefinition > collectViewDefinitions ( ModelMatcher filter ) throws IOException , SQLException { String sql = "" + "" + "" ; PreparedStatement ps = null ; ResultSet rs = null ; List < ViewDefinition > results = Lists . create ( ) ; try { ps = conn . prepareStatement ( sql ) ; ps . setString ( , databaseName ) ; rs = ps . executeQuery ( ) ; while ( rs . next ( ) ) { String viewName = rs . getString ( ) ; if ( filter . acceptModel ( viewName ) == false ) { LOG . info ( "" , viewName ) ; continue ; } String statement = rs . getString ( ) ; results . add ( new ViewDefinition ( viewName , statement ) ) ; } } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } if ( ps != null ) { try { ps . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } } return results ; } @ Override public void close ( ) throws IOException { if ( conn != null ) { try { conn . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } } } package com . asakusafw . dmdl . thundergate . source ; package com . asakusafw . dmdl . thundergate . source ; public final class MySQLConstants { public static final String STR_IS_PK = "" ; public static final String STR_NOT_NULL = "" ; private MySQLConstants ( ) { return ; } } package com . asakusafw . dmdl . thundergate . emitter ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Map ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstScript ; import com . asakusafw . dmdl . model . LiteralKind ; import com . asakusafw . dmdl . parser . DmdlEmitter ; import com . asakusafw . dmdl . thundergate . Configuration ; import com . asakusafw . dmdl . thundergate . Constants ; import com . asakusafw . dmdl . thundergate . model . JoinedModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . PropertyType ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . SummarizedModelDescription ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; public class ThunderGateModelEmitter { static final Logger LOG = LoggerFactory . getLogger ( ThunderGateModelEmitter . class ) ; private final Configuration config ; public ThunderGateModelEmitter ( Configuration config ) { if ( config == null ) { throw new IllegalArgumentException ( "" ) ; } this . config = config ; } public void emit ( ModelDescription model ) throws IOException { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } AstScript script = convert ( model ) ; String name = model . getReference ( ) . getSimpleName ( ) ; emit ( name , script ) ; } private AstScript convert ( ModelDescription model ) { assert model != null ; AstModelDefinition < ? > def ; if ( model instanceof TableModelDescription ) { TableModelDescription tableModel = ( TableModelDescription ) model ; AstAttribute cacheSupport = generateCacheSupport ( tableModel ) ; if ( cacheSupport == null ) { def = RecordModelGenerator . generate ( tableModel ) ; } else { def = RecordModelGenerator . generate ( tableModel , cacheSupport ) ; } } else if ( model instanceof JoinedModelDescription ) { def = JoinedModelGenerator . generate ( ( JoinedModelDescription ) model ) ; } else if ( model instanceof SummarizedModelDescription ) { def = SummarizedModelGenerator . generate ( ( SummarizedModelDescription ) model ) ; } else { throw new AssertionError ( model ) ; } return new AstScript ( null , Collections . singletonList ( def ) ) ; } private AstAttribute generateCacheSupport ( TableModelDescription model ) { assert model != null ; if ( config . getSidColumn ( ) == null ) { return null ; } Map < String , ModelProperty > properties = new TreeMap < String , ModelProperty > ( String . CASE_INSENSITIVE_ORDER ) ; for ( ModelProperty property : model . getProperties ( ) ) { properties . put ( property . getSource ( ) . getName ( ) , property ) ; } ModelProperty sid = properties . get ( config . getSidColumn ( ) ) ; if ( sid == null ) { LOG . warn ( "" , model . getReference ( ) . getSimpleName ( ) , config . getSidColumn ( ) ) ; return null ; } if ( sid . getType ( ) . getKind ( ) != PropertyTypeKind . LONG ) { LOG . warn ( "" , model . getReference ( ) . getSimpleName ( ) , config . getSidColumn ( ) ) ; return null ; } ModelProperty timestamp = properties . get ( config . getTimestampColumn ( ) ) ; if ( timestamp == null ) { LOG . warn ( "" , model . getReference ( ) . getSimpleName ( ) , config . getTimestampColumn ( ) ) ; return null ; } if ( timestamp . getType ( ) . getKind ( ) != PropertyTypeKind . DATETIME ) { LOG . warn ( "" , model . getReference ( ) . getSimpleName ( ) , config . getTimestampColumn ( ) ) ; return null ; } if ( config . getDeleteFlagColumn ( ) != null ) { ModelProperty deleteFlag = properties . get ( config . getDeleteFlagColumn ( ) ) ; if ( deleteFlag == null ) { LOG . info ( "" , model . getReference ( ) . getSimpleName ( ) , config . getDeleteFlagColumn ( ) ) ; } else if ( acceptsLiteral ( deleteFlag . getType ( ) , config . getDeleteFlagValue ( ) ) == false ) { LOG . warn ( "" , new Object [ ] { model . getReference ( ) . getSimpleName ( ) , config . getDeleteFlagColumn ( ) , config . getDeleteFlagValue ( ) , } ) ; return null ; } else { return AstBuilder . getCacheSupport ( sid , timestamp , deleteFlag , config . getDeleteFlagValue ( ) ) ; } } return AstBuilder . getCacheSupport ( sid , timestamp ) ; } private boolean acceptsLiteral ( PropertyType type , AstLiteral value ) { assert type != null ; assert value != null ; LiteralKind literalKind = value . getKind ( ) ; switch ( type . getKind ( ) ) { case BOOLEAN : return literalKind == LiteralKind . BOOLEAN ; case BYTE : case SHORT : case INT : case LONG : return literalKind == LiteralKind . INTEGER ; case STRING : return literalKind == LiteralKind . STRING ; default : return false ; } } private void emit ( String name , AstScript script ) throws IOException { assert name != null ; assert script != null ; PrintWriter output = open ( name ) ; try { DmdlEmitter . emit ( script , output ) ; if ( output . checkError ( ) ) { throw new IOException ( MessageFormat . format ( "" , name ) ) ; } } finally { output . close ( ) ; } } private PrintWriter open ( String name ) throws IOException { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } File file = new File ( config . getOutput ( ) , name + Constants . DMDL_LIKE_EXTENSION ) ; File directory = file . getParentFile ( ) ; if ( directory . exists ( ) == false && directory . mkdirs ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , directory ) ) ; } PrintWriter writer = new PrintWriter ( file , config . getEncoding ( ) . name ( ) ) ; return writer ; } } package com . asakusafw . dmdl . thundergate . emitter ; package com . asakusafw . dmdl . thundergate . emitter ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstGrouping ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstModelFolding ; import com . asakusafw . dmdl . model . AstModelReference ; import com . asakusafw . dmdl . model . AstPropertyFolding ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . model . AstSummarize ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . thundergate . Constants ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . ModelReference ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . dmdl . thundergate . model . SummarizedModelDescription ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public final class SummarizedModelGenerator { private final SummarizedModelDescription model ; private SummarizedModelGenerator ( SummarizedModelDescription model ) { assert model != null ; this . model = model ; } public static AstModelDefinition < AstSummarize > generate ( SummarizedModelDescription model ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } return new AstModelDefinition < AstSummarize > ( null , ModelDefinitionKind . SUMMARIZED , AstBuilder . getDesciption ( "" , model . getOriginalModel ( ) . getSimpleName ( ) ) , Arrays . asList ( new AstAttribute [ ] { AstBuilder . getAutoProjection ( ) , AstBuilder . getNamespace ( AstBuilder . toDmdlName ( Constants . SOURCE_VIEW ) ) , AstBuilder . getOriginalName ( model . getReference ( ) . getSimpleName ( ) ) , } ) , AstBuilder . toName ( model . getReference ( ) ) , new SummarizedModelGenerator ( model ) . generateExpression ( ) ) ; } private AstSummarize generateExpression ( ) { return generateTerm ( model . getOriginalModel ( ) , model . getGroupBy ( ) ) ; } private AstSummarize generateTerm ( ModelReference sourceModel , List < Source > group ) { Map < String , ModelProperty > resolver = Maps . create ( ) ; List < AstPropertyFolding > foldings = Lists . create ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { Source source = property . getSource ( ) ; assert source . getDeclaring ( ) . equals ( sourceModel ) ; resolver . put ( source . getName ( ) , property ) ; foldings . add ( new AstPropertyFolding ( null , AstBuilder . getDesciption ( "" , source . getAggregator ( ) . name ( ) , source . getName ( ) ) , Arrays . asList ( new AstAttribute [ ] { AstBuilder . getOriginalName ( property . getName ( ) ) , } ) , AstBuilder . toName ( source . getAggregator ( ) ) , AstBuilder . toName ( source ) , AstBuilder . toName ( property ) ) ) ; } List < AstSimpleName > grouping = Lists . create ( ) ; for ( Source source : group ) { ModelProperty property = resolver . get ( source . getName ( ) ) ; assert property != null : source ; grouping . add ( AstBuilder . toName ( property ) ) ; } return new AstSummarize ( null , new AstModelReference ( null , AstBuilder . toName ( sourceModel ) ) , new AstModelFolding ( null , foldings ) , grouping . isEmpty ( ) ? null : new AstGrouping ( null , grouping ) ) ; } } package com . asakusafw . dmdl . thundergate . emitter ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstExpression ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstPropertyDefinition ; import com . asakusafw . dmdl . model . AstRecord ; import com . asakusafw . dmdl . model . AstRecordDefinition ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . thundergate . Constants ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . utils . collections . Lists ; public final class RecordModelGenerator { private final TableModelDescription model ; private RecordModelGenerator ( TableModelDescription model ) { assert model != null ; this . model = model ; } public static AstModelDefinition < AstRecord > generate ( TableModelDescription model ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } return generate ( model , new AstAttribute [ ] ) ; } public static AstModelDefinition < AstRecord > generate ( TableModelDescription model , AstAttribute ... extra ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } if ( extra == null ) { throw new IllegalArgumentException ( "" ) ; } List < AstAttribute > attrs = Lists . create ( ) ; attrs . add ( AstBuilder . getAutoProjection ( ) ) ; attrs . add ( AstBuilder . getNamespace ( AstBuilder . toDmdlName ( Constants . SOURCE_TABLE ) ) ) ; attrs . add ( AstBuilder . getOriginalName ( model . getReference ( ) . getSimpleName ( ) ) ) ; attrs . add ( AstBuilder . getPrimaryKey ( model ) ) ; Collections . addAll ( attrs , extra ) ; return new AstModelDefinition < AstRecord > ( null , ModelDefinitionKind . RECORD , AstBuilder . getDesciption ( "" , model . getReference ( ) . getSimpleName ( ) ) , attrs , AstBuilder . toName ( model . getReference ( ) ) , new RecordModelGenerator ( model ) . generateExpression ( ) ) ; } private AstExpression < AstRecord > generateExpression ( ) { return generateTerm ( ) ; } private AstRecord generateTerm ( ) { List < AstPropertyDefinition > properties = Lists . create ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { properties . add ( new AstPropertyDefinition ( null , AstBuilder . getDesciption ( "" , property . getName ( ) ) , Arrays . asList ( new AstAttribute [ ] { AstBuilder . getOriginalName ( property . getName ( ) ) , } ) , AstBuilder . toName ( property ) , AstBuilder . toType ( property . getType ( ) ) ) ) ; } return new AstRecordDefinition ( null , properties ) ; } } package com . asakusafw . dmdl . thundergate . emitter ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . dmdl . analyzer . driver . AutoProjectionDriver ; import com . asakusafw . dmdl . analyzer . driver . NamespaceDriver ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . AstAttributeValueArray ; import com . asakusafw . dmdl . model . AstBasicType ; import com . asakusafw . dmdl . model . AstDescription ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . AstName ; import com . asakusafw . dmdl . model . AstQualifiedName ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . model . AstType ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . model . LiteralKind ; import com . asakusafw . dmdl . semantics . PropertyMappingKind ; import com . asakusafw . dmdl . thundergate . driver . CacheSupportDriver ; import com . asakusafw . dmdl . thundergate . driver . OriginalNameDriver ; import com . asakusafw . dmdl . thundergate . driver . PrimaryKeyDriver ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; import com . asakusafw . dmdl . thundergate . model . Attribute ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . ModelReference ; import com . asakusafw . dmdl . thundergate . model . PropertyType ; import com . asakusafw . dmdl . thundergate . model . PropertyTypeKind ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . dmdl . thundergate . model . TableModelDescription ; import com . asakusafw . utils . collections . Lists ; public final class AstBuilder { public static AstSimpleName toDmdlName ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } boolean requestSeparated = false ; StringBuilder buf = new StringBuilder ( ) ; for ( char c : name . toCharArray ( ) ) { if ( Character . isJavaIdentifierPart ( c ) && c != '' ) { if ( requestSeparated ) { buf . append ( '' ) ; } buf . append ( Character . toLowerCase ( c ) ) ; requestSeparated = false ; } else if ( buf . length ( ) > ) { requestSeparated = true ; } } if ( buf . length ( ) == ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } return new AstSimpleName ( null , buf . toString ( ) ) ; } private static AstName toName ( String name ) { assert name != null ; String [ ] segments = name . split ( "" ) ; AstName current = toSimpleName ( segments [ ] ) ; for ( int i = ; i < segments . length ; i ++ ) { current = new AstQualifiedName ( null , current , toSimpleName ( segments [ i ] ) ) ; } return current ; } private static AstSimpleName toSimpleName ( String name ) { assert name != null ; return new AstSimpleName ( null , name ) ; } public static AstSimpleName toName ( ModelReference model ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } return toDmdlName ( model . getSimpleName ( ) ) ; } public static AstSimpleName toName ( ModelProperty property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } return toDmdlName ( property . getName ( ) ) ; } public static AstSimpleName toName ( Source source ) { if ( source == null ) { throw new IllegalArgumentException ( "" ) ; } return toDmdlName ( source . getName ( ) ) ; } public static AstName toName ( Aggregator aggregator ) { if ( aggregator == null ) { throw new IllegalArgumentException ( "" ) ; } return toDmdlName ( convert ( aggregator ) . name ( ) ) ; } private static PropertyMappingKind convert ( Aggregator aggregator ) { assert aggregator != null ; switch ( aggregator ) { case IDENT : return PropertyMappingKind . ANY ; case COUNT : return PropertyMappingKind . COUNT ; case MAX : return PropertyMappingKind . MAX ; case MIN : return PropertyMappingKind . MIN ; case SUM : return PropertyMappingKind . SUM ; default : throw new AssertionError ( aggregator ) ; } } public static AstType toType ( PropertyType type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } BasicTypeKind kind = convert ( type . getKind ( ) ) ; return new AstBasicType ( null , kind ) ; } private static BasicTypeKind convert ( PropertyTypeKind kind ) { assert kind != null ; switch ( kind ) { case BIG_DECIMAL : return BasicTypeKind . DECIMAL ; case BOOLEAN : return BasicTypeKind . BOOLEAN ; case BYTE : return BasicTypeKind . BYTE ; case DATE : return BasicTypeKind . DATE ; case DATETIME : return BasicTypeKind . DATETIME ; case INT : return BasicTypeKind . INT ; case LONG : return BasicTypeKind . LONG ; case SHORT : return BasicTypeKind . SHORT ; case STRING : return BasicTypeKind . TEXT ; default : throw new AssertionError ( kind ) ; } } public static AstDescription getDesciption ( String pattern , String ... arguments ) { if ( pattern == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return new AstDescription ( null , AstLiteral . quote ( MessageFormat . format ( pattern , ( Object [ ] ) arguments ) ) ) ; } public static AstAttribute getAutoProjection ( ) { return new AstAttribute ( null , toName ( AutoProjectionDriver . TARGET_NAME ) ) ; } public static AstAttribute getNamespace ( AstName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return new AstAttribute ( null , toName ( NamespaceDriver . TARGET_NAME ) , new AstAttributeElement ( null , toSimpleName ( NamespaceDriver . ELEMENT_NAME ) , name ) ) ; } public static AstAttribute getOriginalName ( String name ) { return new AstAttribute ( null , toName ( OriginalNameDriver . TARGET_NAME ) , new AstAttributeElement ( null , toSimpleName ( OriginalNameDriver . ELEMENT_NAME ) , new AstLiteral ( null , AstLiteral . quote ( name ) , LiteralKind . STRING ) ) ) ; } public static AstAttribute getPrimaryKey ( TableModelDescription model ) { List < AstSimpleName > primaryKeys = Lists . create ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { if ( property . getSource ( ) . getAttributes ( ) . contains ( Attribute . PRIMARY_KEY ) ) { primaryKeys . add ( toName ( property ) ) ; } } return new AstAttribute ( null , toName ( PrimaryKeyDriver . TARGET_NAME ) , new AstAttributeElement ( null , toSimpleName ( PrimaryKeyDriver . ELEMENT_NAME ) , new AstAttributeValueArray ( null , primaryKeys ) ) ) ; } public static AstAttribute getCacheSupport ( ModelProperty sid , ModelProperty timestamp ) { if ( sid == null ) { throw new IllegalArgumentException ( "" ) ; } if ( timestamp == null ) { throw new IllegalArgumentException ( "" ) ; } return new AstAttribute ( null , toName ( CacheSupportDriver . TARGET_NAME ) , new AstAttributeElement ( null , toSimpleName ( CacheSupportDriver . SID_ELEMENT_NAME ) , toName ( sid ) ) , new AstAttributeElement ( null , toSimpleName ( CacheSupportDriver . TIMESTAMP_ELEMENT_NAME ) , toName ( timestamp ) ) ) ; } public static AstAttribute getCacheSupport ( ModelProperty sid , ModelProperty timestamp , ModelProperty deleteFlag , AstLiteral deleteFlagValue ) { if ( sid == null ) { throw new IllegalArgumentException ( "" ) ; } if ( timestamp == null ) { throw new IllegalArgumentException ( "" ) ; } if ( deleteFlag == null ) { throw new IllegalArgumentException ( "" ) ; } if ( deleteFlagValue == null ) { throw new IllegalArgumentException ( "" ) ; } return new AstAttribute ( null , toName ( CacheSupportDriver . TARGET_NAME ) , new AstAttributeElement ( null , toSimpleName ( CacheSupportDriver . SID_ELEMENT_NAME ) , toName ( sid ) ) , new AstAttributeElement ( null , toSimpleName ( CacheSupportDriver . TIMESTAMP_ELEMENT_NAME ) , toName ( timestamp ) ) , new AstAttributeElement ( null , toSimpleName ( CacheSupportDriver . DELETE_FLAG_ELEMENT_NAME ) , toName ( deleteFlag ) ) , new AstAttributeElement ( null , toSimpleName ( CacheSupportDriver . DELETE_FLAG_VALUE_ELEMENT_NAME ) , deleteFlagValue ) ) ; } private AstBuilder ( ) { return ; } } package com . asakusafw . dmdl . thundergate . emitter ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstExpression ; import com . asakusafw . dmdl . model . AstGrouping ; import com . asakusafw . dmdl . model . AstJoin ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstModelMapping ; import com . asakusafw . dmdl . model . AstModelReference ; import com . asakusafw . dmdl . model . AstPropertyMapping ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . model . AstUnionExpression ; import com . asakusafw . dmdl . model . ModelDefinitionKind ; import com . asakusafw . dmdl . thundergate . Constants ; import com . asakusafw . dmdl . thundergate . model . JoinedModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelProperty ; import com . asakusafw . dmdl . thundergate . model . ModelReference ; import com . asakusafw . dmdl . thundergate . model . Source ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public final class JoinedModelGenerator { private final JoinedModelDescription model ; private JoinedModelGenerator ( JoinedModelDescription model ) { assert model != null ; this . model = model ; } public static AstModelDefinition < AstJoin > generate ( JoinedModelDescription model ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } return new AstModelDefinition < AstJoin > ( null , ModelDefinitionKind . JOINED , AstBuilder . getDesciption ( "" , model . getFromModel ( ) . getSimpleName ( ) , model . getJoinModel ( ) . getSimpleName ( ) ) , Arrays . asList ( new AstAttribute [ ] { AstBuilder . getAutoProjection ( ) , AstBuilder . getNamespace ( AstBuilder . toDmdlName ( Constants . SOURCE_VIEW ) ) , AstBuilder . getOriginalName ( model . getReference ( ) . getSimpleName ( ) ) , } ) , AstBuilder . toName ( model . getReference ( ) ) , new JoinedModelGenerator ( model ) . generateExpression ( ) ) ; } private AstExpression < AstJoin > generateExpression ( ) { AstJoin from = generateTerm ( model . getFromModel ( ) , model . getFromCondition ( ) , true ) ; AstJoin join = generateTerm ( model . getJoinModel ( ) , model . getJoinCondition ( ) , false ) ; return new AstUnionExpression < AstJoin > ( null , Arrays . asList ( from , join ) ) ; } private AstJoin generateTerm ( ModelReference sourceModel , List < Source > group , boolean from ) { Map < String , ModelProperty > resolver = Maps . create ( ) ; List < AstPropertyMapping > mappings = Lists . create ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { Source source = from ? property . getFrom ( ) : property . getJoined ( ) ; if ( source == null ) { continue ; } resolver . put ( source . getName ( ) , property ) ; mappings . add ( new AstPropertyMapping ( null , AstBuilder . getDesciption ( "" , sourceModel . getSimpleName ( ) , source . getName ( ) ) , Arrays . asList ( new AstAttribute [ ] { AstBuilder . getOriginalName ( property . getName ( ) ) , } ) , AstBuilder . toName ( source ) , AstBuilder . toName ( property ) ) ) ; } List < AstSimpleName > grouping = Lists . create ( ) ; for ( Source source : group ) { ModelProperty property = resolver . get ( source . getName ( ) ) ; assert property != null : source ; grouping . add ( AstBuilder . toName ( property ) ) ; } return new AstJoin ( null , new AstModelReference ( null , AstBuilder . toName ( sourceModel ) ) , new AstModelMapping ( null , mappings ) , grouping . isEmpty ( ) ? null : new AstGrouping ( null , grouping ) ) ; } } package com . asakusafw . dmdl . thundergate ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import java . util . Properties ; import java . util . regex . Pattern ; import java . util . regex . PatternSyntaxException ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . apache . commons . cli . ParseException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . parser . DmdlParser ; import com . asakusafw . dmdl . parser . DmdlSyntaxException ; public final class Main { static final Logger LOG = LoggerFactory . getLogger ( Main . class ) ; private static final Option OPT_OUTPUT ; private static final Option OPT_JDBC_CONFIG ; private static final Option OPT_ENCODING ; private static final Option OPT_INCLUDES ; private static final Option OPT_EXCLUDES ; private static final Option OPT_SID_COLUMN ; private static final Option OPT_TIMESTAMP_COLUMN ; private static final Option OPT_DELETE_FLAG_COLUMN ; private static final Option OPT_DELETE_FLAG_VALUE ; private static final Options OPTIONS ; static { OPT_JDBC_CONFIG = new Option ( "" , true , "" ) ; OPT_JDBC_CONFIG . setArgName ( "" ) ; OPT_JDBC_CONFIG . setRequired ( true ) ; OPT_OUTPUT = new Option ( "" , true , "" ) ; OPT_OUTPUT . setArgName ( "" ) ; OPT_OUTPUT . setRequired ( true ) ; OPT_ENCODING = new Option ( "" , true , "" ) ; OPT_ENCODING . setArgName ( "" ) ; OPT_ENCODING . setRequired ( false ) ; OPT_INCLUDES = new Option ( "" , true , "" ) ; OPT_INCLUDES . setArgName ( "" ) ; OPT_INCLUDES . setRequired ( false ) ; OPT_EXCLUDES = new Option ( "" , true , "" ) ; OPT_EXCLUDES . setArgName ( "" ) ; OPT_EXCLUDES . setRequired ( false ) ; OPT_SID_COLUMN = new Option ( "" , true , "" ) ; OPT_SID_COLUMN . setArgName ( "" ) ; OPT_SID_COLUMN . setRequired ( false ) ; OPT_TIMESTAMP_COLUMN = new Option ( "" , true , "" ) ; OPT_TIMESTAMP_COLUMN . setArgName ( "" ) ; OPT_TIMESTAMP_COLUMN . setRequired ( false ) ; OPT_DELETE_FLAG_COLUMN = new Option ( "" , true , "" ) ; OPT_DELETE_FLAG_COLUMN . setArgName ( "" ) ; OPT_DELETE_FLAG_COLUMN . setRequired ( false ) ; OPT_DELETE_FLAG_VALUE = new Option ( "" , true , "" ) ; OPT_DELETE_FLAG_VALUE . setArgName ( "" ) ; OPT_DELETE_FLAG_VALUE . setRequired ( false ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_OUTPUT ) ; OPTIONS . addOption ( OPT_JDBC_CONFIG ) ; OPTIONS . addOption ( OPT_ENCODING ) ; OPTIONS . addOption ( OPT_INCLUDES ) ; OPTIONS . addOption ( OPT_EXCLUDES ) ; OPTIONS . addOption ( OPT_SID_COLUMN ) ; OPTIONS . addOption ( OPT_TIMESTAMP_COLUMN ) ; OPTIONS . addOption ( OPT_DELETE_FLAG_COLUMN ) ; OPTIONS . addOption ( OPT_DELETE_FLAG_VALUE ) ; } private Main ( ) { return ; } public static void main ( String ... args ) { GenerateTask task ; try { Configuration conf = loadConfigurationFromArguments ( args ) ; task = new GenerateTask ( conf ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , Main . class . getName ( ) ) , OPTIONS , true ) ; e . printStackTrace ( System . out ) ; System . exit ( ) ; return ; } try { task . call ( ) ; } catch ( Exception e ) { e . printStackTrace ( System . out ) ; System . exit ( ) ; return ; } } public static Configuration loadConfigurationFromArguments ( String [ ] args ) { assert args != null ; CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd ; try { cmd = parser . parse ( OPTIONS , args ) ; } catch ( ParseException e ) { throw new IllegalStateException ( e ) ; } Configuration result = new Configuration ( ) ; String jdbc = getOption ( cmd , OPT_JDBC_CONFIG , true ) ; try { Properties jdbcProps = loadProperties ( jdbc ) ; result . setJdbcDriver ( findProperty ( jdbcProps , Constants . K_JDBC_DRIVER ) ) ; result . setJdbcUrl ( findProperty ( jdbcProps , Constants . K_JDBC_URL ) ) ; result . setJdbcUser ( findProperty ( jdbcProps , Constants . K_JDBC_USER ) ) ; result . setJdbcPassword ( findProperty ( jdbcProps , Constants . K_JDBC_PASSWORD ) ) ; result . setDatabaseName ( findProperty ( jdbcProps , Constants . K_DATABASE_NAME ) ) ; LOG . info ( "" , jdbcProps ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , OPT_JDBC_CONFIG . getOpt ( ) , jdbc ) , e ) ; } String output = getOption ( cmd , OPT_OUTPUT , true ) ; result . setOutput ( new File ( output ) ) ; LOG . info ( "" , output ) ; String includes = getOption ( cmd , OPT_INCLUDES , false ) ; if ( includes != null && includes . isEmpty ( ) == false ) { try { Pattern pattern = Pattern . compile ( includes , Pattern . CASE_INSENSITIVE ) ; result . setMatcher ( new ModelMatcher . Regex ( pattern ) ) ; LOG . info ( "" , pattern ) ; } catch ( PatternSyntaxException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , includes ) , e ) ; } } else { result . setMatcher ( ModelMatcher . ALL ) ; } String excludes = getOption ( cmd , OPT_EXCLUDES , false ) ; if ( excludes != null && excludes . isEmpty ( ) == false ) { try { Pattern pattern = Pattern . compile ( excludes , Pattern . CASE_INSENSITIVE ) ; result . setMatcher ( new ModelMatcher . And ( result . getMatcher ( ) , new ModelMatcher . Not ( new ModelMatcher . ConstantTable ( Constants . SYSTEM_TABLE_NAMES ) ) , new ModelMatcher . Not ( new ModelMatcher . Regex ( pattern ) ) ) ) ; LOG . info ( "" , pattern ) ; } catch ( PatternSyntaxException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , excludes ) , e ) ; } } else { result . setMatcher ( new ModelMatcher . And ( result . getMatcher ( ) , new ModelMatcher . Not ( new ModelMatcher . ConstantTable ( Constants . SYSTEM_TABLE_NAMES ) ) ) ) ; } String encoding = getOption ( cmd , OPT_ENCODING , false ) ; if ( encoding != null ) { try { Charset charset = Charset . forName ( encoding ) ; result . setEncoding ( charset ) ; LOG . info ( "" , charset ) ; } catch ( Exception e ) { result . setEncoding ( Constants . OUTPUT_ENCODING ) ; } } else { result . setEncoding ( Constants . OUTPUT_ENCODING ) ; } checkIf ( cmd , OPT_SID_COLUMN , OPT_TIMESTAMP_COLUMN ) ; checkIf ( cmd , OPT_TIMESTAMP_COLUMN , OPT_SID_COLUMN ) ; checkIf ( cmd , OPT_SID_COLUMN , OPT_DELETE_FLAG_COLUMN ) ; checkIf ( cmd , OPT_SID_COLUMN , OPT_DELETE_FLAG_VALUE ) ; checkIf ( cmd , OPT_DELETE_FLAG_COLUMN , OPT_DELETE_FLAG_VALUE ) ; checkIf ( cmd , OPT_DELETE_FLAG_VALUE , OPT_DELETE_FLAG_COLUMN ) ; String sidColumn = trim ( getOption ( cmd , OPT_SID_COLUMN , false ) ) ; String timestampColumn = trim ( getOption ( cmd , OPT_TIMESTAMP_COLUMN , false ) ) ; String deleteFlagColumn = trim ( getOption ( cmd , OPT_DELETE_FLAG_COLUMN , false ) ) ; String deleteFlagValue = trim ( getOption ( cmd , OPT_DELETE_FLAG_VALUE , false ) ) ; if ( deleteFlagValue != null ) { List < String > arguments = Arrays . asList ( args ) ; int index = arguments . indexOf ( '' + OPT_DELETE_FLAG_VALUE . getOpt ( ) ) ; assert index >= ; assert arguments . size ( ) > index + ; deleteFlagValue = trim ( arguments . get ( index + ) ) ; } result . setSidColumn ( sidColumn ) ; result . setTimestampColumn ( timestampColumn ) ; result . setDeleteFlagColumn ( deleteFlagColumn ) ; if ( deleteFlagValue != null ) { try { DmdlParser dmdl = new DmdlParser ( ) ; AstLiteral literal = dmdl . parseLiteral ( deleteFlagValue ) ; result . setDeleteFlagValue ( literal ) ; } catch ( DmdlSyntaxException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , deleteFlagValue ) , e ) ; } } return result ; } private static void checkIf ( CommandLine cmd , Option target , Option condition ) { String conditionValue = getOption ( cmd , condition , false ) ; if ( trim ( conditionValue ) == null ) { return ; } String targetValue = getOption ( cmd , target , false ) ; if ( trim ( targetValue ) == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , target . getOpt ( ) , condition . getOpt ( ) ) ) ; } } private static String trim ( String string ) { if ( string == null ) { return null ; } String trimmed = string . trim ( ) ; if ( trimmed . isEmpty ( ) ) { return null ; } return trimmed ; } private static String getOption ( CommandLine cmd , Option option , boolean mandatory ) { assert cmd != null ; assert option != null ; LOG . debug ( "" , cmd . getArgList ( ) ) ; String value = cmd . getOptionValue ( option . getOpt ( ) ) ; if ( mandatory && value == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , option . getOpt ( ) ) ) ; } LOG . debug ( "" , option . getOpt ( ) , value ) ; return value ; } private static Properties loadProperties ( String path ) throws IOException { assert path != null ; LOG . debug ( "" , path ) ; InputStream in = new FileInputStream ( path ) ; try { Properties result = new Properties ( ) ; result . load ( in ) ; return result ; } finally { in . close ( ) ; } } private static String findProperty ( Properties properties , String key ) { assert properties != null ; assert key != null ; LOG . debug ( "" , key ) ; String value = properties . getProperty ( key ) ; if ( value == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , key ) ) ; } return value ; } } package com . asakusafw . dmdl . thundergate ; import java . util . Collection ; import java . util . Set ; import java . util . regex . Pattern ; import com . asakusafw . utils . collections . Sets ; public interface ModelMatcher { ModelMatcher ALL = new ModelMatcher ( ) { @ Override public boolean acceptModel ( String name ) { return true ; } } ; ModelMatcher NOTHING = new ModelMatcher ( ) { @ Override public boolean acceptModel ( String name ) { return false ; } } ; boolean acceptModel ( String name ) ; public class And implements ModelMatcher { private final ModelMatcher [ ] matchers ; public And ( ModelMatcher ... matchers ) { if ( matchers == null ) { throw new IllegalArgumentException ( "" ) ; } this . matchers = matchers . clone ( ) ; } @ Override public boolean acceptModel ( String name ) { for ( ModelMatcher m : matchers ) { if ( m . acceptModel ( name ) == false ) { return false ; } } return true ; } } public class Not implements ModelMatcher { private final ModelMatcher term ; public Not ( ModelMatcher term ) { if ( term == null ) { throw new IllegalArgumentException ( "" ) ; } this . term = term ; } @ Override public boolean acceptModel ( String name ) { return term . acceptModel ( name ) == false ; } } public class Regex implements ModelMatcher { private final Pattern pattern ; public Regex ( Pattern pattern ) { if ( pattern == null ) { throw new IllegalArgumentException ( "" ) ; } this . pattern = pattern ; } @ Override public boolean acceptModel ( String name ) { return pattern . matcher ( name ) . matches ( ) ; } } public class ConstantTable implements ModelMatcher { private final Set < String > constants ; public ConstantTable ( Collection < String > constants ) { if ( constants == null ) { throw new IllegalArgumentException ( "" ) ; } this . constants = Sets . from ( constants ) ; } @ Override public boolean acceptModel ( String name ) { return constants . contains ( name ) ; } } } package com . asakusafw . dmdl . thundergate . model ; public enum Attribute { PRIMARY_KEY , UNIQUE , NOT_NULL , } package com . asakusafw . dmdl . thundergate . model ; import java . text . MessageFormat ; public class StringType implements PropertyType { private int capacity ; public StringType ( int capacity ) { this . capacity = capacity ; } public int getCapacity ( ) { return capacity ; } @ Override public PropertyTypeKind getKind ( ) { return PropertyTypeKind . STRING ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + capacity ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } StringType other = ( StringType ) obj ; if ( capacity != other . capacity ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , String . valueOf ( capacity ) ) ; } } package com . asakusafw . dmdl . thundergate . model ; import java . text . MessageFormat ; import java . util . List ; public class TableModelDescription extends ModelDescription { public TableModelDescription ( ModelReference reference , List < ModelProperty > properties ) { super ( reference , properties ) ; for ( ModelProperty property : properties ) { if ( property . getJoined ( ) != null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } Source source = property . getFrom ( ) ; if ( source . getAggregator ( ) != Aggregator . IDENT ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } } } @ Override protected Source convertPropertyToSource ( ModelProperty property ) { Source source = property . getFrom ( ) ; return new Source ( Aggregator . IDENT , getReference ( ) , property . getName ( ) , source . getType ( ) , source . getAttributes ( ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result += result * prime + getReference ( ) . hashCode ( ) ; result += result * prime + getProperties ( ) . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } TableModelDescription other = ( TableModelDescription ) obj ; if ( getReference ( ) . equals ( other . getReference ( ) ) == false ) { return false ; } if ( getProperties ( ) . equals ( other . getProperties ( ) ) == false ) { return false ; } return true ; } } package com . asakusafw . dmdl . thundergate . model ; package com . asakusafw . dmdl . thundergate . model ; import java . text . MessageFormat ; public class ModelProperty { private String name ; private Source from ; private Source joined ; public ModelProperty ( String name , Source from ) { this . name = name ; this . from = from ; } public ModelProperty ( String name , Source from , Source joined ) { this . name = name ; if ( from == null && joined == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } this . from = from ; this . joined = joined ; } public String getName ( ) { return name ; } public PropertyType getType ( ) { Source source = getSource ( ) ; return source . getAggregator ( ) . inferType ( source . getType ( ) ) ; } public Source getSource ( ) { if ( from != null ) { return from ; } assert joined != null ; return joined ; } public Source getFrom ( ) { return from ; } public Source getJoined ( ) { return joined ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( from == null ) ? : from . hashCode ( ) ) ; result = prime * result + ( ( joined == null ) ? : joined . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ModelProperty other = ( ModelProperty ) obj ; if ( name . equals ( other . name ) == false ) { return false ; } if ( from == null ) { if ( other . from != null ) { return false ; } } else if ( from . equals ( other . from ) == false ) { return false ; } if ( joined == null ) { if ( other . joined != null ) { return false ; } } else if ( joined . equals ( other . joined ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( name ) ; builder . append ( "" ) ; builder . append ( from ) ; builder . append ( "" ) ; builder . append ( joined ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . dmdl . thundergate . model ; public enum Aggregator { IDENT { @ Override public PropertyType inferType ( PropertyType original ) { return original ; } } , SUM { @ Override public PropertyType inferType ( PropertyType original ) { switch ( original . getKind ( ) ) { case BYTE : case SHORT : case INT : case LONG : return new BasicType ( PropertyTypeKind . LONG ) ; case BIG_DECIMAL : return original ; default : return null ; } } } , COUNT { @ Override public PropertyType inferType ( PropertyType original ) { return new BasicType ( PropertyTypeKind . LONG ) ; } } , MAX { @ Override public PropertyType inferType ( PropertyType original ) { switch ( original . getKind ( ) ) { case INT : case LONG : case BIG_DECIMAL : case DATE : case DATETIME : return original ; default : return null ; } } } , MIN { @ Override public PropertyType inferType ( PropertyType original ) { return MAX . inferType ( original ) ; } } , ; public abstract PropertyType inferType ( PropertyType original ) ; } package com . asakusafw . dmdl . thundergate . model ; import java . util . Set ; import com . asakusafw . utils . collections . Sets ; public class Source { private Aggregator aggregator ; private ModelReference declaring ; private String name ; private PropertyType type ; private Set < Attribute > attributes ; public Source ( Aggregator aggregator , ModelReference declaring , String name , PropertyType type , Set < Attribute > attributes ) { this . aggregator = aggregator ; this . declaring = declaring ; this . name = name ; this . type = type ; this . attributes = Sets . freeze ( attributes ) ; } public Aggregator getAggregator ( ) { return aggregator ; } public ModelReference getDeclaring ( ) { return declaring ; } public String getName ( ) { return name ; } public PropertyType getType ( ) { return type ; } public Set < Attribute > getAttributes ( ) { return attributes ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + aggregator . hashCode ( ) ; result = prime * result + attributes . hashCode ( ) ; result = prime * result + declaring . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; result = prime * result + type . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Source other = ( Source ) obj ; if ( aggregator != other . aggregator ) { return false ; } if ( attributes . equals ( other . attributes ) == false ) { return false ; } if ( declaring . equals ( other . declaring ) == false ) { return false ; } if ( name . equals ( other . name ) == false ) { return false ; } if ( type . equals ( other . type ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( declaring ) ; builder . append ( "" ) ; builder . append ( aggregator ) ; builder . append ( "" ) ; builder . append ( name ) ; builder . append ( "" ) ; builder . append ( type ) ; builder . append ( "" ) ; builder . append ( attributes ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . dmdl . thundergate . model ; public interface PropertyType { PropertyTypeKind getKind ( ) ; } package com . asakusafw . dmdl . thundergate . model ; public enum PropertyTypeKind { BYTE ( false ) , SHORT ( false ) , INT ( false ) , LONG ( false ) , FLOAT ( false ) , DOUBLE ( false ) , BIG_DECIMAL ( true ) , BOOLEAN ( false ) , STRING ( true ) , DATE ( false ) , DATETIME ( false ) , ; public final boolean variant ; private PropertyTypeKind ( boolean variant ) { this . variant = variant ; } } package com . asakusafw . dmdl . thundergate . model ; import java . util . List ; import com . asakusafw . utils . collections . Lists ; public abstract class ModelDescription { private ModelReference reference ; private List < ModelProperty > properties ; public ModelDescription ( ModelReference reference , List < ModelProperty > properties ) { if ( reference == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } this . reference = reference ; this . properties = Lists . freeze ( properties ) ; } public ModelReference getReference ( ) { return reference ; } public List < ModelProperty > getProperties ( ) { return properties ; } public List < Source > getPropertiesAsSources ( ) { List < Source > results = Lists . create ( ) ; for ( ModelProperty property : getProperties ( ) ) { Source source = convertPropertyToSource ( property ) ; results . add ( source ) ; } return results ; } protected abstract Source convertPropertyToSource ( ModelProperty property ) ; } package com . asakusafw . dmdl . thundergate . model ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import com . asakusafw . utils . collections . Lists ; public class JoinedModelDescription extends ModelDescription { private List < Source > leftCondition ; private List < Source > rightCondition ; public JoinedModelDescription ( ModelReference reference , List < ModelProperty > properties , List < Source > leftCondition , List < Source > rightCondition ) { super ( reference , properties ) ; if ( leftCondition . isEmpty ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference ) ) ; } if ( leftCondition . size ( ) != rightCondition . size ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference ) ) ; } this . leftCondition = Lists . freeze ( leftCondition ) ; this . rightCondition = Lists . freeze ( rightCondition ) ; } @ Override protected Source convertPropertyToSource ( ModelProperty property ) { return new Source ( Aggregator . IDENT , getReference ( ) , property . getName ( ) , property . getType ( ) , Collections . < Attribute > emptySet ( ) ) ; } public ModelReference getFromModel ( ) { return leftCondition . get ( ) . getDeclaring ( ) ; } public ModelReference getJoinModel ( ) { return rightCondition . get ( ) . getDeclaring ( ) ; } public List < Source > getFromCondition ( ) { return leftCondition ; } public List < Source > getJoinCondition ( ) { return rightCondition ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result += result * prime + getReference ( ) . hashCode ( ) ; result += result * prime + getProperties ( ) . hashCode ( ) ; result += result * prime + leftCondition . hashCode ( ) ; result += result * prime + rightCondition . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } JoinedModelDescription other = ( JoinedModelDescription ) obj ; if ( getReference ( ) . equals ( other . getReference ( ) ) == false ) { return false ; } if ( getProperties ( ) . equals ( other . getProperties ( ) ) == false ) { return false ; } if ( leftCondition . equals ( other . leftCondition ) == false ) { return false ; } if ( rightCondition . equals ( other . rightCondition ) == false ) { return false ; } return true ; } } package com . asakusafw . dmdl . thundergate . model ; import java . text . MessageFormat ; public class ModelReference { private String simpleName ; public ModelReference ( String simpleName ) { if ( simpleName == null ) { throw new IllegalArgumentException ( "" ) ; } this . simpleName = simpleName ; } public String getSimpleName ( ) { return simpleName ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + simpleName . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ModelReference other = ( ModelReference ) obj ; if ( simpleName . equals ( other . simpleName ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , simpleName ) ; } } package com . asakusafw . dmdl . thundergate . model ; public class BasicType implements PropertyType { private PropertyTypeKind kind ; public BasicType ( PropertyTypeKind kind ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( kind . variant ) { throw new IllegalArgumentException ( "" ) ; } this . kind = kind ; } @ Override public PropertyTypeKind getKind ( ) { return kind ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + kind . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } BasicType other = ( BasicType ) obj ; if ( kind != other . kind ) { return false ; } return true ; } @ Override public String toString ( ) { return kind . toString ( ) ; } } package com . asakusafw . dmdl . thundergate . model ; import java . text . MessageFormat ; import java . util . List ; import java . util . Set ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; public class SummarizedModelDescription extends ModelDescription { private final List < Source > groupBy ; public SummarizedModelDescription ( ModelReference reference , List < ModelProperty > properties , List < Source > groupBy ) { super ( reference , properties ) ; this . groupBy = Lists . freeze ( groupBy ) ; Set < String > groupKeys = Sets . create ( ) ; for ( Source source : groupBy ) { groupKeys . add ( source . getName ( ) ) ; } for ( ModelProperty property : properties ) { if ( property . getJoined ( ) != null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } Source source = property . getFrom ( ) ; if ( source . getAggregator ( ) == Aggregator . IDENT ) { if ( groupKeys . contains ( source . getName ( ) ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } } else if ( source . getAggregator ( ) != Aggregator . COUNT ) { if ( groupKeys . contains ( source . getName ( ) ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } } } } public ModelReference getOriginalModel ( ) { return getProperties ( ) . get ( ) . getFrom ( ) . getDeclaring ( ) ; } public List < Source > getGroupBy ( ) { return groupBy ; } @ Override protected Source convertPropertyToSource ( ModelProperty property ) { Source source = property . getFrom ( ) ; return new Source ( Aggregator . IDENT , getReference ( ) , property . getName ( ) , source . getType ( ) , source . getAttributes ( ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result += result * prime + getReference ( ) . hashCode ( ) ; result += result * prime + getProperties ( ) . hashCode ( ) ; result += result * prime + groupBy . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } SummarizedModelDescription other = ( SummarizedModelDescription ) obj ; if ( getReference ( ) . equals ( other . getReference ( ) ) == false ) { return false ; } if ( getProperties ( ) . equals ( other . getProperties ( ) ) == false ) { return false ; } if ( getGroupBy ( ) . equals ( other . getGroupBy ( ) ) == false ) { return false ; } return true ; } } package com . asakusafw . dmdl . thundergate . model ; import java . text . MessageFormat ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; public class ModelRepository { private final LinkedHashMap < ModelReference , ModelDescription > models = new LinkedHashMap < ModelReference , ModelDescription > ( ) ; private final Map < String , ModelDescription > simpleNames = Maps . create ( ) ; public void add ( ModelDescription model ) { ModelReference ref = model . getReference ( ) ; if ( models . containsKey ( ref ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , ref ) ) ; } models . put ( ref , model ) ; if ( simpleNames . containsKey ( ref . getSimpleName ( ) ) ) { simpleNames . put ( ref . getSimpleName ( ) , null ) ; } else { simpleNames . put ( ref . getSimpleName ( ) , model ) ; } } public ModelDescription find ( ModelReference reference ) { if ( reference == null ) { throw new IllegalArgumentException ( "" ) ; } return models . get ( reference ) ; } public ModelDescription find ( String simpleName ) { if ( simpleName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( simpleNames . containsKey ( simpleName ) == false ) { return null ; } ModelDescription model = simpleNames . get ( simpleName ) ; if ( model == null ) { List < ModelReference > conflicted = Lists . create ( ) ; for ( ModelReference ref : models . keySet ( ) ) { if ( simpleName . equals ( ref . getSimpleName ( ) ) ) { conflicted . add ( ref ) ; } } throw new IllegalStateException ( MessageFormat . format ( "" , simpleName , conflicted ) ) ; } return model ; } public List < ModelDescription > all ( ) { return Lists . from ( models . values ( ) ) ; } public List < TableModelDescription > allTables ( ) { List < TableModelDescription > results = Lists . create ( ) ; for ( ModelDescription model : models . values ( ) ) { if ( model instanceof TableModelDescription ) { results . add ( ( TableModelDescription ) model ) ; } } return results ; } } package com . asakusafw . dmdl . thundergate . model ; import java . text . MessageFormat ; public class DecimalType implements PropertyType { private int precision ; private int scale ; public DecimalType ( int precision , int scale ) { this . precision = precision ; this . scale = scale ; } public int getPrecision ( ) { return precision ; } public int getScale ( ) { return scale ; } @ Override public PropertyTypeKind getKind ( ) { return PropertyTypeKind . BIG_DECIMAL ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + precision ; result = prime * result + scale ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DecimalType other = ( DecimalType ) obj ; if ( precision != other . precision ) { return false ; } if ( scale != other . scale ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , String . valueOf ( precision ) , String . valueOf ( scale ) ) ; } } package com . asakusafw . dmdl . thundergate . view ; public class ViewDefinition { public final String name ; public final String statement ; public ViewDefinition ( String name , String statement ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( statement == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . statement = statement ; } } package com . asakusafw . dmdl . thundergate . view ; package com . asakusafw . dmdl . thundergate . view ; import java . io . IOException ; import java . io . StringReader ; import java . text . MessageFormat ; import com . asakusafw . dmdl . thundergate . view . model . CreateView ; public final class ViewParser { public static CreateView parse ( ViewDefinition definition ) throws IOException { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } StringReader stream = new StringReader ( definition . statement ) ; JjViewParser parser = new JjViewParser ( stream ) ; try { CreateView parsed = parser . parse ( definition . name ) ; return parsed ; } catch ( ParseException e ) { throw new IOException ( MessageFormat . format ( "" , definition . name , definition . statement ) , e ) ; } } private ViewParser ( ) { return ; } } package com . asakusafw . dmdl . thundergate . view ; import java . text . MessageFormat ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; import com . asakusafw . dmdl . thundergate . model . JoinedModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelDescription ; import com . asakusafw . dmdl . thundergate . model . ModelRepository ; import com . asakusafw . dmdl . thundergate . util . JoinedModelBuilder ; import com . asakusafw . dmdl . thundergate . util . SummarizedModelBuilder ; import com . asakusafw . dmdl . thundergate . view . model . CreateView ; import com . asakusafw . dmdl . thundergate . view . model . CreateView . Kind ; import com . asakusafw . dmdl . thundergate . view . model . Name ; import com . asakusafw . dmdl . thundergate . view . model . On ; import com . asakusafw . dmdl . thundergate . view . model . Select ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; public class ViewAnalyzer { static final Logger LOG = LoggerFactory . getLogger ( ViewAnalyzer . class ) ; private final List < CreateView > added = Lists . create ( ) ; public void add ( CreateView view ) { if ( view == null ) { throw new IllegalArgumentException ( "" ) ; } added . add ( view ) ; } public List < ModelDescription > analyze ( ModelRepository repository ) { if ( repository == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( "" , added . size ( ) ) ; List < CreateView > sorted = sort ( ) ; Map < Name , ModelDescription > context = Maps . create ( ) ; List < ModelDescription > analyzed = Lists . create ( ) ; for ( CreateView view : sorted ) { LOG . info ( "" , view . name ) ; ModelDescription model = transform ( view , repository , context ) ; context . put ( view . name , model ) ; if ( model != null ) { analyzed . add ( model ) ; } } if ( analyzed . size ( ) != added . size ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , analyzed . size ( ) , added . size ( ) ) ) ; } return analyzed ; } private ModelDescription transform ( CreateView target , ModelRepository repository , Map < Name , ModelDescription > context ) { assert target != null ; assert repository != null ; assert context != null ; if ( resolveDependency ( target , repository , context ) == false ) { return null ; } Kind kind = target . getKind ( ) ; if ( kind == Kind . JOINED ) { return transformJoined ( target , context ) ; } else if ( kind == Kind . SUMMARIZED ) { return transformSummarized ( target , context ) ; } else { LOG . error ( "" , target . name , target ) ; return null ; } } private JoinedModelDescription transformJoined ( CreateView target , Map < Name , ModelDescription > context ) { assert target != null ; assert target . getKind ( ) == CreateView . Kind . JOINED ; assert context != null ; assert context . get ( target . from . table ) != null ; assert context . get ( target . from . join . table ) != null ; JoinedModelBuilder builder = new JoinedModelBuilder ( target . name . token , context . get ( target . from . table ) , target . from . alias , context . get ( target . from . join . table ) , target . from . join . alias ) ; for ( On on : target . from . join . condition ) { builder . on ( on . left . token , on . right . token ) ; } for ( Select select : target . selectList ) { assert select . aggregator == Aggregator . IDENT ; builder . add ( select . alias . token , select . name . token ) ; } return builder . toDescription ( ) ; } private ModelDescription transformSummarized ( CreateView target , Map < Name , ModelDescription > context ) { assert target != null ; assert target . getKind ( ) == CreateView . Kind . SUMMARIZED ; assert context . get ( target . from . table ) != null ; SummarizedModelBuilder builder = new SummarizedModelBuilder ( target . name . token , context . get ( target . from . table ) , target . from . alias ) ; for ( Name name : target . groupBy ) { builder . groupBy ( name . token ) ; } for ( Select select : target . selectList ) { builder . add ( select . alias . token , select . aggregator , select . name . token ) ; } return builder . toDescription ( ) ; } private boolean resolveDependency ( CreateView target , ModelRepository repository , Map < Name , ModelDescription > context ) { boolean success = true ; for ( Name dependency : target . getDependencies ( ) ) { LOG . debug ( "" , target . name , dependency ) ; if ( context . containsKey ( dependency ) ) { if ( context . get ( dependency ) == null ) { LOG . warn ( "" , target . name , dependency ) ; return false ; } } else { ModelDescription resolved = repository . find ( dependency . token ) ; if ( resolved == null ) { LOG . error ( "" , target . name , dependency ) ; success = false ; } else { context . put ( dependency , resolved ) ; } } } return success ; } private List < CreateView > sort ( ) { Map < Name , CreateView > map = Maps . create ( ) ; Graph < Name > dependencies = Graphs . newInstance ( ) ; for ( CreateView view : added ) { Name name = view . name ; map . put ( name , view ) ; for ( Name dependTo : view . getDependencies ( ) ) { dependencies . addEdge ( name , dependTo ) ; } } Set < Set < Name > > circuit = Graphs . findCircuit ( dependencies ) ; if ( circuit . isEmpty ( ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , circuit ) ) ; } List < Name > sorted = Graphs . sortPostOrder ( dependencies ) ; List < CreateView > results = Lists . create ( ) ; for ( Name name : sorted ) { CreateView view = map . get ( name ) ; if ( view != null ) { results . add ( view ) ; } } return results ; } } package com . asakusafw . dmdl . thundergate . view . model ; import java . text . MessageFormat ; public class From { public final Name table ; public final String alias ; public final Join join ; public From ( Name table , String alias ) { this ( table , alias , null ) ; } public From ( Name table , String alias , Join join ) { if ( table == null ) { throw new IllegalArgumentException ( "" ) ; } this . table = table ; this . alias = alias ; this . join = join ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + table . hashCode ( ) ; result = prime * result + ( ( join == null ) ? : join . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } From other = ( From ) obj ; if ( ! table . equals ( other . table ) ) { return false ; } if ( join == null ) { if ( other . join != null ) { return false ; } } else if ( ! join . equals ( other . join ) ) { return false ; } return true ; } @ Override public String toString ( ) { if ( join == null ) { return MessageFormat . format ( "" , table ) ; } else { return MessageFormat . format ( "" , table , join ) ; } } } package com . asakusafw . dmdl . thundergate . view . model ; import java . text . MessageFormat ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; public class Select { public final Name name ; public final Aggregator aggregator ; public final Name alias ; public Select ( Name name , Aggregator aggregator , Name alias ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( aggregator == null ) { throw new IllegalArgumentException ( "" ) ; } if ( alias == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . aggregator = aggregator ; this . alias = alias ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + aggregator . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; result = prime * result + alias . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Select other = ( Select ) obj ; if ( aggregator != other . aggregator ) { return false ; } if ( ! name . equals ( other . name ) ) { return false ; } if ( ! alias . equals ( other . alias ) ) { return false ; } return true ; } @ Override public String toString ( ) { if ( aggregator == Aggregator . IDENT ) { return MessageFormat . format ( "" , name , alias ) ; } else { return MessageFormat . format ( "" , name , aggregator , alias ) ; } } } package com . asakusafw . dmdl . thundergate . view . model ; package com . asakusafw . dmdl . thundergate . view . model ; public class Name { public final String token ; public Name ( String token ) { if ( token == null ) { throw new IllegalArgumentException ( "" ) ; } this . token = token ; } public Name ( Name qualifier , Name rest ) { if ( qualifier == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rest == null ) { throw new IllegalArgumentException ( "" ) ; } this . token = qualifier . token + "" + rest . token ; } public Name getLastSegment ( ) { int last = token . lastIndexOf ( '' ) ; if ( last >= ) { return new Name ( token . substring ( last + ) ) ; } return this ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + token . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Name other = ( Name ) obj ; if ( ! token . equals ( other . token ) ) { return false ; } return true ; } @ Override public String toString ( ) { return token ; } } package com . asakusafw . dmdl . thundergate . view . model ; import java . text . MessageFormat ; public class On { public final Name left ; public final Name right ; public On ( Name left , Name right ) { if ( left == null ) { throw new IllegalArgumentException ( "" ) ; } if ( right == null ) { throw new IllegalArgumentException ( "" ) ; } this . left = left ; this . right = right ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + left . hashCode ( ) ; result = prime * result + right . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } On other = ( On ) obj ; if ( ! left . equals ( other . left ) ) { return false ; } if ( ! right . equals ( other . right ) ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , left , right ) ; } } package com . asakusafw . dmdl . thundergate . view . model ; import java . text . MessageFormat ; import java . util . List ; import java . util . Set ; import com . asakusafw . dmdl . thundergate . model . Aggregator ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Sets ; public class CreateView { public final Name name ; public final List < Select > selectList ; public final From from ; public final List < Name > groupBy ; public CreateView ( Name name , List < Select > selectList , From from , List < Name > groupBy ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( selectList == null ) { throw new IllegalArgumentException ( "" ) ; } if ( from == null ) { throw new IllegalArgumentException ( "" ) ; } if ( groupBy == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . selectList = Lists . freeze ( selectList ) ; this . from = from ; this . groupBy = Lists . freeze ( groupBy ) ; } public CreateView . Kind getKind ( ) { boolean join = ( from . join != null ) ; boolean summarize = ( groupBy . isEmpty ( ) == false ) ; if ( summarize == false ) { for ( Select select : selectList ) { if ( select . aggregator != Aggregator . IDENT ) { summarize = true ; break ; } } } if ( join && summarize == false ) { return Kind . JOINED ; } if ( summarize && join == false ) { return Kind . SUMMARIZED ; } return Kind . UNKNOWN ; } public Set < Name > getDependencies ( ) { Set < Name > results = Sets . create ( ) ; results . add ( from . table ) ; if ( from . join != null ) { results . add ( from . join . table ) ; } return results ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + from . hashCode ( ) ; result = prime * result + groupBy . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; result = prime * result + selectList . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } CreateView other = ( CreateView ) obj ; if ( ! from . equals ( other . from ) ) { return false ; } if ( ! groupBy . equals ( other . groupBy ) ) { return false ; } if ( ! name . equals ( other . name ) ) { return false ; } if ( ! selectList . equals ( other . selectList ) ) { return false ; } return true ; } @ Override public String toString ( ) { if ( groupBy . isEmpty ( ) ) { return MessageFormat . format ( "" , name , selectList , from ) ; } else { return MessageFormat . format ( "" , name , selectList , from , groupBy ) ; } } public enum Kind { JOINED , SUMMARIZED , UNKNOWN , } } package com . asakusafw . dmdl . thundergate . view . model ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . utils . collections . Lists ; public class Join { public final Name table ; public final String alias ; public final List < On > condition ; public Join ( Name table , String alias , List < On > condition ) { if ( table == null ) { throw new IllegalArgumentException ( "" ) ; } if ( condition == null ) { throw new IllegalArgumentException ( "" ) ; } this . table = table ; this . alias = alias ; this . condition = Lists . freeze ( condition ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( alias == null ) ? : alias . hashCode ( ) ) ; result = prime * result + condition . hashCode ( ) ; result = prime * result + table . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Join other = ( Join ) obj ; if ( ! table . equals ( other . table ) ) { return false ; } if ( alias == null ) { if ( other . alias != null ) { return false ; } } else if ( ! alias . equals ( other . alias ) ) { return false ; } if ( ! condition . equals ( other . condition ) ) { return false ; } return true ; } @ Override public String toString ( ) { if ( alias != null ) { return MessageFormat . format ( "" , table , condition , alias ) ; } else { return MessageFormat . format ( "" , table , condition ) ; } } } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . net . URI ; import java . util . Arrays ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class TableSourceProviderTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; executeFile ( "" ) ; } } ; @ Rule public ConfigurationContext context = new ConfigurationContext ( ) ; @ Test public void single ( ) throws Exception { context . put ( "" , "" ) ; Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; insert ( simple , SIMPLE , "" ) ; TableSourceProvider provider = new TableSourceProvider ( ) ; DataModelSource source = provider . open ( SIMPLE , new URI ( "" ) , new TestContext . Empty ( ) ) ; try { assertThat ( next ( source ) , is ( simple ) ) ; assertThat ( next ( source ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void multiple ( ) throws Exception { context . put ( "" , "" ) ; Simple s1 = new Simple ( ) ; s1 . number = ; s1 . text = "" ; insert ( s1 , SIMPLE , "" ) ; Simple s2 = new Simple ( ) ; s2 . number = ; s2 . text = "" ; insert ( s2 , SIMPLE , "" ) ; TableSourceProvider provider = new TableSourceProvider ( ) ; DataModelSource source = provider . open ( SIMPLE , new URI ( "" ) , new TestContext . Empty ( ) ) ; try { assertThat ( next ( source ) , is ( s1 ) ) ; assertThat ( next ( source ) , is ( s2 ) ) ; assertThat ( next ( source ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void zero ( ) throws Exception { context . put ( "" , "" ) ; TableSourceProvider provider = new TableSourceProvider ( ) ; DataModelSource source = provider . open ( SIMPLE , new URI ( "" ) , new TestContext . Empty ( ) ) ; try { assertThat ( next ( source ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void invalid_scheme ( ) throws Exception { context . put ( "" , "" ) ; TableSourceProvider provider = new TableSourceProvider ( ) ; DataModelSource source = provider . open ( SIMPLE , new URI ( "" ) , new TestContext . Empty ( ) ) ; assertThat ( source , is ( nullValue ( ) ) ) ; } private < T > void insert ( T simple , DataModelDefinition < T > def , String table ) { try { TableInfo < T > info = new TableInfo < T > ( def , table , Arrays . asList ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) ) ; TableOutput < T > output = new TableOutput < T > ( info , h2 . open ( ) ) ; try { output . write ( simple ) ; } finally { output . close ( ) ; } } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Simple next ( DataModelSource source ) throws IOException { DataModelReflection next = source . next ( ) ; if ( next != null ) { return SIMPLE . toObject ( next ) ; } return null ; } } package com . asakusafw . testdriver . bulkloader ; import java . util . Calendar ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ PrimaryKey ( "" ) @ OriginalName ( "" ) @ ColumnOrder ( { "" , "" , "" , "" } ) public class CacheSupport implements ThunderGateCacheSupport { @ OriginalName ( "" ) public Integer number ; @ OriginalName ( "" ) public String text ; @ OriginalName ( "" ) public Boolean booleanValue ; @ OriginalName ( "" ) public Calendar datetimeValue ; public Integer inferOriginalName ; @ Override public long __tgc__DataModelVersion ( ) { return ; } @ Override public boolean __tgc__Deleted ( ) { return Boolean . TRUE . equals ( booleanValue ) ; } @ Override public long __tgc__SystemId ( ) { return number ; } @ Override public String __tgc__TimestampColumn ( ) { return "" ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( booleanValue == null ) ? : booleanValue . hashCode ( ) ) ; result = prime * result + ( ( datetimeValue == null ) ? : datetimeValue . hashCode ( ) ) ; result = prime * result + ( ( number == null ) ? : number . hashCode ( ) ) ; result = prime * result + ( ( text == null ) ? : text . hashCode ( ) ) ; result = prime * result + ( ( inferOriginalName == null ) ? : inferOriginalName . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } CacheSupport other = ( CacheSupport ) obj ; if ( booleanValue == null ) { if ( other . booleanValue != null ) { return false ; } } else if ( ! booleanValue . equals ( other . booleanValue ) ) { return false ; } if ( datetimeValue == null ) { if ( other . datetimeValue != null ) { return false ; } } else if ( ! datetimeValue . equals ( other . datetimeValue ) ) { return false ; } if ( inferOriginalName == null ) { if ( other . inferOriginalName != null ) { return false ; } } else if ( ! inferOriginalName . equals ( other . inferOriginalName ) ) { return false ; } if ( number == null ) { if ( other . number != null ) { return false ; } } else if ( ! number . equals ( other . number ) ) { return false ; } if ( text == null ) { if ( other . text != null ) { return false ; } } else if ( ! text . equals ( other . text ) ) { return false ; } return true ; } @ Override public String toString ( ) { return new SimpleDataModelDefinition < CacheSupport > ( CacheSupport . class ) . toReflection ( this ) . toString ( ) ; } } package com . asakusafw . testdriver . bulkloader ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . net . URL ; import java . net . URLClassLoader ; import java . security . AccessController ; import java . security . PrivilegedExceptionAction ; import java . text . MessageFormat ; import java . util . Properties ; import org . junit . rules . ExternalResource ; import org . junit . rules . TemporaryFolder ; public class ConfigurationContext extends ExternalResource { private final TemporaryFolder folder = new TemporaryFolder ( ) ; private ClassLoader context ; @ Override protected void before ( ) throws Throwable { folder . create ( ) ; final File root = folder . getRoot ( ) ; ClassLoader classLoader = AccessController . doPrivileged ( new PrivilegedExceptionAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) throws Exception { return new URLClassLoader ( new URL [ ] { root . toURI ( ) . toURL ( ) } , getClass ( ) . getClassLoader ( ) ) ; } } ) ; context = Thread . currentThread ( ) . getContextClassLoader ( ) ; boolean green = false ; try { Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; green = true ; } finally { if ( green == false ) { after ( ) ; } } } @ Override protected void after ( ) { try { Thread . currentThread ( ) . setContextClassLoader ( context ) ; System . gc ( ) ; } finally { folder . delete ( ) ; } } public void put ( String targetName , String simpleName ) { Properties p = new Properties ( ) ; p . setProperty ( "" , org . h2 . Driver . class . getName ( ) ) ; p . setProperty ( "" , "" + simpleName ) ; put ( targetName , p ) ; } public void put ( String targetName , Properties properties ) { try { File file ; if ( targetName == null ) { file = folder . newFile ( Configuration . COMMON_FILE ) ; } else { file = folder . newFile ( MessageFormat . format ( Configuration . FILE_PATTERN , targetName ) ) ; } FileOutputStream out = new FileOutputStream ( file ) ; try { properties . store ( out , "" ) ; } finally { out . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; import com . asakusafw . vocabulary . bulkloader . BulkLoadExporterDescription ; import com . asakusafw . vocabulary . bulkloader . DupCheckDbExporterDescription ; public class BulkLoadExporterRetrieverTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; static final DataModelDefinition < DupCheck > DUP_CHECK = new SimpleDataModelDefinition < DupCheck > ( DupCheck . class ) ; static final BulkLoadExporterDescription NORMAL = new DupCheckDbExporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return Simple . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override protected Class < ? > getNormalModelType ( ) { return Simple . class ; } @ Override protected Class < ? > getErrorModelType ( ) { return DupCheck . class ; } @ Override protected String getErrorCodeValue ( ) { return "" ; } @ Override protected String getErrorCodeColumnName ( ) { return "" ; } @ Override protected List < String > getCheckColumnNames ( ) { return Arrays . asList ( "" ) ; } } ; static final BulkLoadExporterDescription MISSING = new DupCheckDbExporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return Simple . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override protected Class < ? > getNormalModelType ( ) { return Simple . class ; } @ Override protected Class < ? > getErrorModelType ( ) { return DupCheck . class ; } @ Override protected String getNormalTableName ( ) { return "" ; } @ Override protected String getErrorTableName ( ) { return "" ; } @ Override protected String getErrorCodeValue ( ) { return "" ; } @ Override protected String getErrorCodeColumnName ( ) { return "" ; } @ Override protected List < String > getCheckColumnNames ( ) { return Arrays . asList ( "" ) ; } } ; @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; executeFile ( "" ) ; } } ; @ Rule public ConfigurationContext context = new ConfigurationContext ( ) ; @ Test public void truncate ( ) throws Exception { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; insert ( simple , SIMPLE , "" ) ; DupCheck dc = new DupCheck ( ) ; dc . number = ; dc . text = "" ; insert ( dc , DUP_CHECK , "" ) ; context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; exporter . truncate ( NORMAL ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void output ( ) throws Exception { Simple object = new Simple ( ) ; object . number = ; object . text = "" ; context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; ModelOutput < Simple > output = exporter . createOutput ( SIMPLE , NORMAL ) ; try { output . write ( object ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; List < Simple > list = retrieve ( SIMPLE , "" ) ; assertThat ( list , is ( Arrays . asList ( object ) ) ) ; } @ Test public void output_dupcheck ( ) throws Exception { DupCheck object = new DupCheck ( ) ; object . number = ; object . text = "" ; context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; ModelOutput < DupCheck > output = exporter . createOutput ( DUP_CHECK , NORMAL ) ; try { output . write ( object ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; List < DupCheck > list = retrieve ( DUP_CHECK , "" ) ; assertThat ( list , is ( Arrays . asList ( object ) ) ) ; } @ Test ( expected = IOException . class ) public void output_invalid ( ) throws Exception { context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; ModelOutput < ? > output = exporter . createOutput ( new SimpleDataModelDefinition < Invalid > ( Invalid . class ) , NORMAL ) ; output . close ( ) ; } @ Test ( expected = IOException . class ) public void output_missing ( ) throws Exception { context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; ModelOutput < ? > output = exporter . createOutput ( SIMPLE , MISSING ) ; output . close ( ) ; } @ Test public void source ( ) throws Exception { Simple object = new Simple ( ) ; object . number = ; object . text = "" ; insert ( object , SIMPLE , "" ) ; context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; DataModelSource source = exporter . createSource ( SIMPLE , NORMAL ) ; try { List < Simple > results = drain ( SIMPLE , source ) ; assertThat ( results , is ( Arrays . asList ( object ) ) ) ; } finally { source . close ( ) ; } } @ Test public void source_dupcheck ( ) throws Exception { DupCheck object = new DupCheck ( ) ; object . number = ; object . text = "" ; insert ( object , DUP_CHECK , "" ) ; context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; DataModelSource source = exporter . createSource ( DUP_CHECK , NORMAL ) ; try { List < DupCheck > results = drain ( DUP_CHECK , source ) ; assertThat ( results , is ( Arrays . asList ( object ) ) ) ; } finally { source . close ( ) ; } } @ Test ( expected = IOException . class ) public void source_invalid ( ) throws Exception { context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; DataModelSource source = exporter . createSource ( new SimpleDataModelDefinition < Invalid > ( Invalid . class ) , NORMAL ) ; source . close ( ) ; } @ Test ( expected = IOException . class ) public void source_missing ( ) throws Exception { context . put ( "" , "" ) ; BulkLoadExporterRetriever exporter = new BulkLoadExporterRetriever ( ) ; DataModelSource source = exporter . createSource ( SIMPLE , MISSING ) ; source . close ( ) ; } private < T > void insert ( T simple , DataModelDefinition < T > def , String table ) { try { TableInfo < T > info = new TableInfo < T > ( def , table , Arrays . asList ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) ) ; TableOutput < T > output = new TableOutput < T > ( info , h2 . open ( ) ) ; try { output . write ( simple ) ; } finally { output . close ( ) ; } } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private < T > List < T > retrieve ( DataModelDefinition < T > def , String table ) { try { TableInfo < T > info = new TableInfo < T > ( def , table , Arrays . asList ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) ) ; TableSource < T > source = new TableSource < T > ( info , h2 . open ( ) ) ; return drain ( def , source ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private < T > List < T > drain ( DataModelDefinition < T > def , DataModelSource source ) throws IOException { try { List < DataModelReflection > retrieved = new ArrayList < DataModelReflection > ( ) ; while ( true ) { DataModelReflection next = source . next ( ) ; if ( next == null ) { break ; } retrieved . add ( next ) ; } Collections . sort ( retrieved , new Comparator < DataModelReflection > ( ) { @ Override public int compare ( DataModelReflection o1 , DataModelReflection o2 ) { PropertyName name = PropertyName . newInstance ( "" ) ; Integer i1 = ( Integer ) o1 . getValue ( name ) ; Integer i2 = ( Integer ) o2 . getValue ( name ) ; return i1 . compareTo ( i2 ) ; } } ) ; List < T > results = new ArrayList < T > ( ) ; for ( DataModelReflection r : retrieved ) { results . add ( def . toObject ( r ) ) ; } return results ; } finally { source . close ( ) ; } } } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . math . BigDecimal ; import java . sql . Connection ; import java . sql . Timestamp ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Calendar ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class TableOutputTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; static final DataModelDefinition < CacheSupport > CACHE = new SimpleDataModelDefinition < CacheSupport > ( CacheSupport . class ) ; @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; } } ; @ Test public void empty ( ) throws Exception { TableOutput < Simple > output = new TableOutput < Simple > ( info ( "" , "" ) , h2 . open ( ) ) ; output . close ( ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void single ( ) throws Exception { TableOutput < Simple > output = new TableOutput < Simple > ( info ( "" , "" ) , h2 . open ( ) ) ; try { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; output . write ( simple ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; List < List < Object > > results = h2 . query ( "" ) ; assertThat ( results , is ( table ( row ( , "" ) ) ) ) ; } @ Test public void multiple ( ) throws Exception { TableOutput < Simple > output = new TableOutput < Simple > ( info ( "" , "" ) , h2 . open ( ) ) ; try { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; output . write ( simple ) ; simple . number = ; simple . text = "" ; output . write ( simple ) ; simple . number = ; simple . text = "" ; output . write ( simple ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; List < List < Object > > results = h2 . query ( "" ) ; assertThat ( results , is ( table ( row ( , "" ) , row ( , "" ) , row ( , "" ) ) ) ) ; } @ Test public void allType ( ) throws Exception { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; simple . booleanValue = true ; simple . byteValue = ; simple . shortValue = ; simple . longValue = ; simple . floatValue = ; simple . doubleValue = ; simple . bigDecimalValue = new BigDecimal ( "" ) ; simple . dateValue = Calendar . getInstance ( ) ; simple . dateValue . clear ( ) ; simple . dateValue . set ( , , ) ; simple . timeValue = Calendar . getInstance ( ) ; simple . timeValue . clear ( ) ; simple . timeValue . set ( Calendar . HOUR_OF_DAY , ) ; simple . timeValue . set ( Calendar . MINUTE , ) ; simple . timeValue . set ( Calendar . SECOND , ) ; simple . datetimeValue = Calendar . getInstance ( ) ; simple . datetimeValue . clear ( ) ; simple . datetimeValue . set ( , , , , , ) ; TableOutput < Simple > output = new TableOutput < Simple > ( info ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) , h2 . open ( ) ) ; try { output . write ( simple ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; List < List < Object > > results = h2 . query ( "" ) ; List < Object > row = results . get ( ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . number ) ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . text ) ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . booleanValue ) ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . byteValue ) ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . shortValue ) ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . longValue ) ) ; assertThat ( row . get ( ) , isOneOf ( ( Object ) simple . floatValue , ( Object ) simple . floatValue . doubleValue ( ) ) ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . doubleValue ) ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . bigDecimalValue ) ) ; assertThat ( row . get ( ) , is ( ( Object ) new java . sql . Date ( simple . dateValue . getTimeInMillis ( ) ) ) ) ; assertThat ( row . get ( ) , is ( ( Object ) new java . sql . Time ( simple . timeValue . getTimeInMillis ( ) ) ) ) ; assertThat ( row . get ( ) , is ( ( Object ) new java . sql . Timestamp ( simple . datetimeValue . getTimeInMillis ( ) ) ) ) ; } @ Test public void nullValues ( ) throws Exception { Simple simple = new Simple ( ) ; simple . number = ; TableOutput < Simple > output = new TableOutput < Simple > ( info ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) , h2 . open ( ) ) ; try { output . write ( simple ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; List < List < Object > > results = h2 . query ( "" ) ; List < Object > row = results . get ( ) ; assertThat ( row . get ( ) , is ( ( Object ) simple . number ) ) ; for ( int i = , n = row . size ( ) ; i < n ; i ++ ) { assertThat ( String . valueOf ( i ) , row . get ( i ) , is ( nullValue ( ) ) ) ; } } @ Test public void timestamp ( ) throws Exception { TableOutput < CacheSupport > output = new TableOutput < CacheSupport > ( new TableInfo < CacheSupport > ( CACHE , "" , Arrays . asList ( "" , "" ) ) , h2 . open ( ) ) ; try { CacheSupport simple = new CacheSupport ( ) ; simple . number = ; simple . text = "" ; output . write ( simple ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; List < List < Object > > results = h2 . query ( "" ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . get ( ) , is ( notNullValue ( ) ) ) ; } @ Test public void timestamp_overwrite ( ) throws Exception { TableOutput < CacheSupport > output = new TableOutput < CacheSupport > ( new TableInfo < CacheSupport > ( CACHE , "" , Arrays . asList ( "" , "" , "" ) ) , h2 . open ( ) ) ; try { CacheSupport simple = new CacheSupport ( ) ; simple . number = ; simple . text = "" ; simple . datetimeValue = Calendar . getInstance ( ) ; simple . datetimeValue . setTimeInMillis ( ) ; output . write ( simple ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; List < List < Object > > results = h2 . query ( "" ) ; assertThat ( results . size ( ) , is ( ) ) ; Timestamp timestamp = ( Timestamp ) results . get ( ) . get ( ) ; assertThat ( timestamp , is ( notNullValue ( ) ) ) ; assertThat ( timestamp . getTime ( ) , is ( ) ) ; } @ Test public void timestamp_suppress_overwrite ( ) throws Exception { TableOutput < CacheSupport > output = new TableOutput < CacheSupport > ( new TableInfo < CacheSupport > ( CACHE , "" , Arrays . asList ( "" , "" , "" ) , false ) , h2 . open ( ) ) ; try { CacheSupport simple = new CacheSupport ( ) ; simple . number = ; simple . text = "" ; simple . datetimeValue = Calendar . getInstance ( ) ; simple . datetimeValue . setTimeInMillis ( ) ; output . write ( simple ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; List < List < Object > > results = h2 . query ( "" ) ; assertThat ( results . size ( ) , is ( ) ) ; Timestamp timestamp = ( Timestamp ) results . get ( ) . get ( ) ; assertThat ( timestamp , is ( notNullValue ( ) ) ) ; assertThat ( timestamp . getTime ( ) , is ( ) ) ; } @ Test public void reclose ( ) throws Exception { TableOutput < Simple > output = new TableOutput < Simple > ( info ( "" , "" ) , h2 . open ( ) ) ; output . close ( ) ; output . close ( ) ; } @ Test ( expected = IOException . class ) public void dropCtor ( ) throws Exception { h2 . execute ( "" ) ; Connection conn = h2 . open ( ) ; try { TableOutput < Simple > output = new TableOutput < Simple > ( info ( "" , "" ) , conn ) ; try { Simple simple = new Simple ( ) ; simple . number = ; output . write ( simple ) ; } finally { output . close ( ) ; } } finally { conn . close ( ) ; } } @ Test ( expected = IOException . class ) public void dropWrite ( ) throws Exception { Connection conn = h2 . open ( ) ; try { TableOutput < Simple > output = new TableOutput < Simple > ( info ( "" , "" ) , conn ) ; try { h2 . execute ( "" ) ; Simple simple = new Simple ( ) ; simple . number = ; output . write ( simple ) ; } finally { output . close ( ) ; } } finally { conn . close ( ) ; } } private TableInfo < Simple > info ( String ... columns ) { return new TableInfo < Simple > ( SIMPLE , "" , Arrays . asList ( columns ) ) ; } private List < List < Object > > table ( Object [ ] ... rows ) { List < List < Object > > results = new ArrayList < List < Object > > ( ) ; for ( Object [ ] row : rows ) { results . add ( Arrays . asList ( row ) ) ; } return results ; } private Object [ ] row ( Object ... cells ) { return cells ; } } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import org . hamcrest . BaseMatcher ; import org . hamcrest . Description ; import org . hamcrest . Matcher ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class TableInfoTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; static final DataModelDefinition < CacheSupport > CACHE = new SimpleDataModelDefinition < CacheSupport > ( CacheSupport . class ) ; @ Test public void simple ( ) { TableInfo < Simple > info = new TableInfo < Simple > ( SIMPLE , "" , Arrays . asList ( new String [ ] { "" } ) ) ; assertThat ( info . getDefinition ( ) , is ( SIMPLE ) ) ; assertThat ( info . getTableName ( ) , is ( "" ) ) ; assertThat ( info . getTimestampColumn ( ) , is ( nullValue ( ) ) ) ; Map < String , PropertyName > map = info . getColumnsToProperties ( ) ; assertThat ( map . size ( ) , is ( ) ) ; assertThat ( map . get ( "" ) , is ( name ( "" ) ) ) ; } @ Test public void ordered ( ) { TableInfo < Simple > info = new TableInfo < Simple > ( SIMPLE , "" , Arrays . asList ( new String [ ] { "" , "" , "" , "" , } ) ) ; assertThat ( info . getDefinition ( ) , is ( SIMPLE ) ) ; assertThat ( info . getTableName ( ) , is ( "" ) ) ; Map < String , PropertyName > map = info . getColumnsToProperties ( ) ; assertThat ( map . size ( ) , is ( ) ) ; assertThat ( map . get ( "" ) , is ( name ( "" ) ) ) ; assertThat ( map . get ( "" ) , is ( name ( "" ) ) ) ; assertThat ( map . get ( "" ) , is ( name ( "" ) ) ) ; assertThat ( map . get ( "" ) , is ( name ( "" ) ) ) ; List < String > names = new ArrayList < String > ( map . keySet ( ) ) ; assertThat ( names , is ( Arrays . asList ( "" , "" , "" , "" ) ) ) ; } @ Test public void infer ( ) { TableInfo < Simple > info = new TableInfo < Simple > ( SIMPLE , "" , Arrays . asList ( new String [ ] { "" } ) ) ; assertThat ( info . getDefinition ( ) , is ( SIMPLE ) ) ; assertThat ( info . getTableName ( ) , is ( "" ) ) ; Map < String , PropertyName > map = info . getColumnsToProperties ( ) ; assertThat ( map . size ( ) , is ( ) ) ; assertThat ( map . get ( "" ) , is ( name ( "" ) ) ) ; } @ Test public void skip ( ) { TableInfo < Simple > info = new TableInfo < Simple > ( SIMPLE , "" , Arrays . asList ( new String [ ] { "" } ) ) ; assertThat ( info . getDefinition ( ) , is ( SIMPLE ) ) ; assertThat ( info . getTableName ( ) , is ( "" ) ) ; Map < String , PropertyName > map = info . getColumnsToProperties ( ) ; assertThat ( map . size ( ) , is ( ) ) ; } @ Test public void unknown ( ) { TableInfo < Simple > info = new TableInfo < Simple > ( SIMPLE , "" , Arrays . asList ( new String [ ] { "" } ) ) ; assertThat ( info . getDefinition ( ) , is ( SIMPLE ) ) ; assertThat ( info . getTableName ( ) , is ( "" ) ) ; Map < String , PropertyName > map = info . getColumnsToProperties ( ) ; assertThat ( map . size ( ) , is ( ) ) ; } @ Test public void timestamp ( ) { TableInfo < CacheSupport > info = new TableInfo < CacheSupport > ( CACHE , "" , Arrays . asList ( new String [ ] { "" } ) ) ; assertThat ( info . getTimestampColumn ( ) , is ( "" ) ) ; } private Matcher < PropertyName > name ( final String words ) { return new BaseMatcher < PropertyName > ( ) { @ Override public boolean matches ( Object o ) { if ( o instanceof PropertyName ) { PropertyName other = ( PropertyName ) o ; PropertyName name = PropertyName . newInstance ( words . split ( "" ) ) ; return other . equals ( name ) ; } return false ; } @ Override public void describeTo ( Description d ) { d . appendText ( words ) ; } } ; } } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . ResultSet ; import java . sql . Statement ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; public class H2ResourceTest { @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { execute ( "" + "" + "" + "" + "" ) ; } } ; @ Test public void execute_resource ( ) throws Exception { h2 . execute ( "" ) ; List < List < Object > > results = h2 . query ( "" ) ; assertThat ( results . size ( ) , is ( ) ) ; List < Object > columns = results . get ( ) ; assertThat ( columns . size ( ) , is ( ) ) ; assertThat ( columns . get ( ) , is ( ( Object ) ) ) ; assertThat ( columns . get ( ) , is ( ( Object ) "" ) ) ; } @ Test public void execute_direct ( ) throws Exception { h2 . execute ( "" ) ; Connection conn = DriverManager . getConnection ( "" ) ; try { Statement stmt = conn . createStatement ( ) ; try { ResultSet rs = stmt . executeQuery ( "" ) ; assertThat ( rs . next ( ) , is ( true ) ) ; assertThat ( rs . getObject ( ) , is ( ( Object ) ) ) ; assertThat ( rs . getObject ( ) , is ( ( Object ) "" ) ) ; assertThat ( rs . next ( ) , is ( false ) ) ; } finally { stmt . close ( ) ; } } finally { conn . close ( ) ; } } } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; import com . asakusafw . vocabulary . bulkloader . DbImporterDescription ; public class BulkLoadImporterPreparatorTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; static final DbImporterDescription NORMAL = new DbImporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return Simple . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override public LockType getLockType ( ) { return LockType . UNUSED ; } } ; static final DbImporterDescription CACHED = new DbImporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return Simple . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override public LockType getLockType ( ) { return LockType . UNUSED ; } @ Override public boolean isCacheEnabled ( ) { return true ; } @ Override public String calculateCacheId ( ) { return "" ; } } ; static final DbImporterDescription MISSING = new DbImporterDescription ( ) { @ Override public Class < ? > getModelType ( ) { return Simple . class ; } @ Override public String getTargetName ( ) { return "" ; } @ Override public String getTableName ( ) { return "" ; } @ Override public LockType getLockType ( ) { return LockType . UNUSED ; } } ; @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; } } ; @ Rule public ConfigurationContext context = new ConfigurationContext ( ) ; @ Test public void truncate ( ) throws Exception { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; insert ( simple ) ; context . put ( "" , "" ) ; BulkLoadImporterPreparator prep = new BulkLoadImporterPreparator ( ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; prep . truncate ( NORMAL ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void truncateWithCache ( ) throws Exception { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; insert ( simple ) ; context . put ( "" , "" ) ; h2 . executeFile ( "" ) ; h2 . execute ( "" + "" + "" ) ; h2 . execute ( "" + "" + "" ) ; h2 . execute ( "" + "" + "" ) ; h2 . execute ( "" + "" + "" ) ; BulkLoadImporterPreparator prep = new BulkLoadImporterPreparator ( ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; prep . truncate ( CACHED ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void truncateWithCache_butNoCacheFeature ( ) throws Exception { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; insert ( simple ) ; context . put ( "" , "" ) ; BulkLoadImporterPreparator prep = new BulkLoadImporterPreparator ( ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; prep . truncate ( CACHED ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void output ( ) throws IOException { context . put ( "" , "" ) ; BulkLoadImporterPreparator prep = new BulkLoadImporterPreparator ( ) ; ModelOutput < Simple > output = prep . createOutput ( SIMPLE , NORMAL ) ; try { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; output . write ( simple ) ; } finally { output . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; List < Object > row = h2 . single ( "" ) ; assertThat ( row , is ( Arrays . < Object > asList ( , "" ) ) ) ; } @ Test ( expected = IOException . class ) public void output_missing ( ) throws IOException { context . put ( "" , "" ) ; BulkLoadImporterPreparator prep = new BulkLoadImporterPreparator ( ) ; ModelOutput < Simple > output = prep . createOutput ( SIMPLE , MISSING ) ; output . close ( ) ; } private void insert ( Simple simple ) { try { TableOutput < Simple > output = new TableOutput < Simple > ( all ( ) , h2 . open ( ) ) ; try { output . write ( simple ) ; } finally { output . close ( ) ; } } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private TableInfo < Simple > all ( ) { return info ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) ; } private TableInfo < Simple > info ( String ... columns ) { return new TableInfo < Simple > ( SIMPLE , "" , Arrays . asList ( columns ) ) ; } } package com . asakusafw . testdriver . bulkloader ; import java . math . BigDecimal ; import java . util . Calendar ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ PrimaryKey ( "" ) @ OriginalName ( "" ) @ ColumnOrder ( { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ) public class DupCheck { @ OriginalName ( "" ) public Integer number ; @ OriginalName ( "" ) public String text ; @ OriginalName ( "" ) public Boolean booleanValue ; @ OriginalName ( "" ) public Byte byteValue ; @ OriginalName ( "" ) public Short shortValue ; @ OriginalName ( "" ) public Long longValue ; @ OriginalName ( "" ) public Float floatValue ; @ OriginalName ( "" ) public Double doubleValue ; @ OriginalName ( "" ) public BigDecimal bigDecimalValue ; @ OriginalName ( "" ) public Calendar dateValue ; @ OriginalName ( "" ) public Calendar timeValue ; @ OriginalName ( "" ) public Calendar datetimeValue ; public Integer inferOriginalName ; @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( bigDecimalValue == null ) ? : bigDecimalValue . hashCode ( ) ) ; result = prime * result + ( ( booleanValue == null ) ? : booleanValue . hashCode ( ) ) ; result = prime * result + ( ( byteValue == null ) ? : byteValue . hashCode ( ) ) ; result = prime * result + ( ( dateValue == null ) ? : dateValue . hashCode ( ) ) ; result = prime * result + ( ( datetimeValue == null ) ? : datetimeValue . hashCode ( ) ) ; result = prime * result + ( ( doubleValue == null ) ? : doubleValue . hashCode ( ) ) ; result = prime * result + ( ( floatValue == null ) ? : floatValue . hashCode ( ) ) ; result = prime * result + ( ( inferOriginalName == null ) ? : inferOriginalName . hashCode ( ) ) ; result = prime * result + ( ( longValue == null ) ? : longValue . hashCode ( ) ) ; result = prime * result + ( ( number == null ) ? : number . hashCode ( ) ) ; result = prime * result + ( ( shortValue == null ) ? : shortValue . hashCode ( ) ) ; result = prime * result + ( ( text == null ) ? : text . hashCode ( ) ) ; result = prime * result + ( ( timeValue == null ) ? : timeValue . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DupCheck other = ( DupCheck ) obj ; if ( bigDecimalValue == null ) { if ( other . bigDecimalValue != null ) { return false ; } } else if ( ! bigDecimalValue . equals ( other . bigDecimalValue ) ) { return false ; } if ( booleanValue == null ) { if ( other . booleanValue != null ) { return false ; } } else if ( ! booleanValue . equals ( other . booleanValue ) ) { return false ; } if ( byteValue == null ) { if ( other . byteValue != null ) { return false ; } } else if ( ! byteValue . equals ( other . byteValue ) ) { return false ; } if ( dateValue == null ) { if ( other . dateValue != null ) { return false ; } } else if ( ! dateValue . equals ( other . dateValue ) ) { return false ; } if ( datetimeValue == null ) { if ( other . datetimeValue != null ) { return false ; } } else if ( ! datetimeValue . equals ( other . datetimeValue ) ) { return false ; } if ( doubleValue == null ) { if ( other . doubleValue != null ) { return false ; } } else if ( ! doubleValue . equals ( other . doubleValue ) ) { return false ; } if ( floatValue == null ) { if ( other . floatValue != null ) { return false ; } } else if ( ! floatValue . equals ( other . floatValue ) ) { return false ; } if ( inferOriginalName == null ) { if ( other . inferOriginalName != null ) { return false ; } } else if ( ! inferOriginalName . equals ( other . inferOriginalName ) ) { return false ; } if ( longValue == null ) { if ( other . longValue != null ) { return false ; } } else if ( ! longValue . equals ( other . longValue ) ) { return false ; } if ( number == null ) { if ( other . number != null ) { return false ; } } else if ( ! number . equals ( other . number ) ) { return false ; } if ( shortValue == null ) { if ( other . shortValue != null ) { return false ; } } else if ( ! shortValue . equals ( other . shortValue ) ) { return false ; } if ( text == null ) { if ( other . text != null ) { return false ; } } else if ( ! text . equals ( other . text ) ) { return false ; } if ( timeValue == null ) { if ( other . timeValue != null ) { return false ; } } else if ( ! timeValue . equals ( other . timeValue ) ) { return false ; } return true ; } @ Override public String toString ( ) { return new SimpleDataModelDefinition < DupCheck > ( DupCheck . class ) . toReflection ( this ) . toString ( ) ; } } package com . asakusafw . testdriver . bulkloader ; import java . math . BigDecimal ; import java . util . Calendar ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ PrimaryKey ( "" ) @ OriginalName ( "" ) @ ColumnOrder ( { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ) public class Simple { @ OriginalName ( "" ) public Integer number ; @ OriginalName ( "" ) public String text ; @ OriginalName ( "" ) public Boolean booleanValue ; @ OriginalName ( "" ) public Byte byteValue ; @ OriginalName ( "" ) public Short shortValue ; @ OriginalName ( "" ) public Long longValue ; @ OriginalName ( "" ) public Float floatValue ; @ OriginalName ( "" ) public Double doubleValue ; @ OriginalName ( "" ) public BigDecimal bigDecimalValue ; @ OriginalName ( "" ) public Calendar dateValue ; @ OriginalName ( "" ) public Calendar timeValue ; @ OriginalName ( "" ) public Calendar datetimeValue ; public Integer inferOriginalName ; @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( bigDecimalValue == null ) ? : bigDecimalValue . hashCode ( ) ) ; result = prime * result + ( ( booleanValue == null ) ? : booleanValue . hashCode ( ) ) ; result = prime * result + ( ( byteValue == null ) ? : byteValue . hashCode ( ) ) ; result = prime * result + ( ( dateValue == null ) ? : dateValue . hashCode ( ) ) ; result = prime * result + ( ( datetimeValue == null ) ? : datetimeValue . hashCode ( ) ) ; result = prime * result + ( ( doubleValue == null ) ? : doubleValue . hashCode ( ) ) ; result = prime * result + ( ( floatValue == null ) ? : floatValue . hashCode ( ) ) ; result = prime * result + ( ( inferOriginalName == null ) ? : inferOriginalName . hashCode ( ) ) ; result = prime * result + ( ( longValue == null ) ? : longValue . hashCode ( ) ) ; result = prime * result + ( ( number == null ) ? : number . hashCode ( ) ) ; result = prime * result + ( ( shortValue == null ) ? : shortValue . hashCode ( ) ) ; result = prime * result + ( ( text == null ) ? : text . hashCode ( ) ) ; result = prime * result + ( ( timeValue == null ) ? : timeValue . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Simple other = ( Simple ) obj ; if ( bigDecimalValue == null ) { if ( other . bigDecimalValue != null ) { return false ; } } else if ( ! bigDecimalValue . equals ( other . bigDecimalValue ) ) { return false ; } if ( booleanValue == null ) { if ( other . booleanValue != null ) { return false ; } } else if ( ! booleanValue . equals ( other . booleanValue ) ) { return false ; } if ( byteValue == null ) { if ( other . byteValue != null ) { return false ; } } else if ( ! byteValue . equals ( other . byteValue ) ) { return false ; } if ( dateValue == null ) { if ( other . dateValue != null ) { return false ; } } else if ( ! dateValue . equals ( other . dateValue ) ) { return false ; } if ( datetimeValue == null ) { if ( other . datetimeValue != null ) { return false ; } } else if ( ! datetimeValue . equals ( other . datetimeValue ) ) { return false ; } if ( doubleValue == null ) { if ( other . doubleValue != null ) { return false ; } } else if ( ! doubleValue . equals ( other . doubleValue ) ) { return false ; } if ( floatValue == null ) { if ( other . floatValue != null ) { return false ; } } else if ( ! floatValue . equals ( other . floatValue ) ) { return false ; } if ( inferOriginalName == null ) { if ( other . inferOriginalName != null ) { return false ; } } else if ( ! inferOriginalName . equals ( other . inferOriginalName ) ) { return false ; } if ( longValue == null ) { if ( other . longValue != null ) { return false ; } } else if ( ! longValue . equals ( other . longValue ) ) { return false ; } if ( number == null ) { if ( other . number != null ) { return false ; } } else if ( ! number . equals ( other . number ) ) { return false ; } if ( shortValue == null ) { if ( other . shortValue != null ) { return false ; } } else if ( ! shortValue . equals ( other . shortValue ) ) { return false ; } if ( text == null ) { if ( other . text != null ) { return false ; } } else if ( ! text . equals ( other . text ) ) { return false ; } if ( timeValue == null ) { if ( other . timeValue != null ) { return false ; } } else if ( ! timeValue . equals ( other . timeValue ) ) { return false ; } return true ; } @ Override public String toString ( ) { return new SimpleDataModelDefinition < Simple > ( Simple . class ) . toReflection ( this ) . toString ( ) ; } } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . ResultSetMetaData ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . junit . rules . TestWatcher ; import org . junit . runner . Description ; public class H2Resource extends TestWatcher { private final String name ; private Class < ? > context ; private Connection connection ; public H2Resource ( String name ) { this . name = name ; } @ Override protected void starting ( Description description ) { org . h2 . Driver . load ( ) ; this . context = description . getTestClass ( ) ; this . connection = open ( ) ; boolean green = false ; try { leakcheck ( ) ; before ( ) ; green = true ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } finally { if ( green == false ) { finished ( description ) ; } } } private void leakcheck ( ) { try { execute0 ( "" ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } protected void before ( ) throws Exception { return ; } public Connection open ( ) { try { return DriverManager . getConnection ( "" + name ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } public List < List < Object > > query ( String sql ) { try { return query0 ( sql ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public List < Object > single ( String sql ) { try { List < List < Object > > query = query0 ( sql ) ; assertThat ( sql , query . size ( ) , is ( ) ) ; return query . get ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public int count ( String table ) { try { List < List < Object > > r = query0 ( MessageFormat . format ( "" , table ) ) ; if ( r . size ( ) != ) { return - ; } return ( ( Number ) r . get ( ) . get ( ) ) . intValue ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return - ; } } private List < List < Object > > query0 ( String sql ) throws SQLException { Statement s = connection . createStatement ( ) ; try { ResultSet rs = s . executeQuery ( sql ) ; ResultSetMetaData meta = rs . getMetaData ( ) ; int size = meta . getColumnCount ( ) ; List < List < Object > > results = new ArrayList < List < Object > > ( ) ; while ( rs . next ( ) ) { Object [ ] columns = new Object [ size ] ; for ( int i = ; i < size ; i ++ ) { columns [ i ] = rs . getObject ( i + ) ; } results . add ( Arrays . asList ( columns ) ) ; } return results ; } finally { s . close ( ) ; } } public void execute ( String sql ) { try { execute0 ( sql ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private void execute0 ( String sql ) throws SQLException { PreparedStatement ps = connection . prepareStatement ( sql ) ; try { ps . execute ( ) ; connection . commit ( ) ; } finally { ps . close ( ) ; } } public void executeFile ( String sqlFile ) { String content = load ( sqlFile ) ; execute ( content ) ; } private String load ( String resource ) { InputStream source = context . getResourceAsStream ( resource ) ; assertThat ( resource , source , is ( not ( nullValue ( ) ) ) ) ; try { StringBuilder buf = new StringBuilder ( ) ; Reader reader = new InputStreamReader ( source , "" ) ; char [ ] cbuf = new char [ ] ; while ( true ) { int read = reader . read ( cbuf ) ; if ( read < ) { break ; } buf . append ( cbuf , , read ) ; } return buf . toString ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } finally { try { source . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } @ Override public void finished ( Description description ) { if ( connection != null ) { try { connection . close ( ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } } } package com . asakusafw . testdriver . bulkloader ; import com . asakusafw . vocabulary . bulkloader . ColumnOrder ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; import com . asakusafw . vocabulary . bulkloader . PrimaryKey ; @ PrimaryKey ( "" ) @ OriginalName ( "" ) @ ColumnOrder ( { "" } ) public class Invalid { @ OriginalName ( "" ) public Integer number ; } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . sql . Connection ; import org . junit . Rule ; import org . junit . Test ; public class ConfigurationTest { @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { execute ( "" + "" + "" + "" + "" ) ; } } ; @ Rule public ConfigurationContext context = new ConfigurationContext ( ) ; @ Test ( expected = IOException . class ) public void missing ( ) throws Exception { Configuration . load ( "" ) ; } @ Test ( expected = IOException . class ) public void mismatch ( ) throws Exception { context . put ( "" , "" ) ; Configuration . load ( "" ) ; } @ Test public void target ( ) throws Exception { context . put ( "" , "" ) ; Configuration conf = Configuration . load ( "" ) ; Connection conn = conf . open ( ) ; try { conn . createStatement ( ) . execute ( "" ) ; conn . commit ( ) ; } finally { conn . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void common ( ) throws Exception { context . put ( null , "" ) ; Configuration conf = Configuration . load ( "" ) ; Connection conn = conf . open ( ) ; try { conn . createStatement ( ) . execute ( "" ) ; conn . commit ( ) ; } finally { conn . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; } } package com . asakusafw . testdriver . bulkloader ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . math . BigDecimal ; import java . sql . Connection ; import java . util . Arrays ; import java . util . Calendar ; import java . util . Collections ; import java . util . Comparator ; import java . util . LinkedList ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class TableSourceTest { static final DataModelDefinition < Simple > SIMPLE = new SimpleDataModelDefinition < Simple > ( Simple . class ) ; @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; } } ; @ Test public void empty ( ) throws Exception { TableSource < Simple > source = new TableSource < Simple > ( info ( "" , "" ) , h2 . open ( ) ) ; try { assertThat ( next ( source ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void single ( ) throws Exception { Simple s1 = new Simple ( ) ; s1 . number = ; s1 . text = "" ; insert ( s1 ) ; TableSource < Simple > source = new TableSource < Simple > ( info ( "" , "" ) , h2 . open ( ) ) ; try { assertThat ( next ( source ) , is ( s1 ) ) ; assertThat ( next ( source ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void multiple ( ) throws Exception { Simple s1 = new Simple ( ) ; s1 . number = ; s1 . text = "" ; insert ( s1 ) ; Simple s2 = new Simple ( ) ; s2 . number = ; s2 . text = "" ; insert ( s2 ) ; Simple s3 = new Simple ( ) ; s3 . number = ; s3 . text = "" ; insert ( s3 ) ; TableSource < Simple > source = new TableSource < Simple > ( info ( "" , "" ) , h2 . open ( ) ) ; try { LinkedList < Simple > results = new LinkedList < Simple > ( ) ; results . addLast ( next ( source ) ) ; assertThat ( results . getLast ( ) , not ( nullValue ( ) ) ) ; results . addLast ( next ( source ) ) ; assertThat ( results . getLast ( ) , not ( nullValue ( ) ) ) ; results . addLast ( next ( source ) ) ; assertThat ( results . getLast ( ) , not ( nullValue ( ) ) ) ; assertThat ( next ( source ) , is ( nullValue ( ) ) ) ; Collections . sort ( results , new Comparator < Simple > ( ) { @ Override public int compare ( Simple o1 , Simple o2 ) { return o1 . number . compareTo ( o2 . number ) ; } } ) ; assertThat ( results , is ( Arrays . asList ( s1 , s2 , s3 ) ) ) ; } finally { source . close ( ) ; } } @ Test public void allTypes ( ) throws Exception { Simple simple = new Simple ( ) ; simple . number = ; simple . text = "" ; simple . booleanValue = true ; simple . byteValue = ; simple . shortValue = ; simple . longValue = ; simple . floatValue = ; simple . doubleValue = ; simple . bigDecimalValue = new BigDecimal ( "" ) ; simple . dateValue = Calendar . getInstance ( ) ; simple . dateValue . clear ( ) ; simple . dateValue . set ( , , ) ; simple . timeValue = Calendar . getInstance ( ) ; simple . timeValue . clear ( ) ; simple . timeValue . set ( Calendar . HOUR_OF_DAY , ) ; simple . timeValue . set ( Calendar . MINUTE , ) ; simple . timeValue . set ( Calendar . SECOND , ) ; simple . datetimeValue = Calendar . getInstance ( ) ; simple . datetimeValue . clear ( ) ; simple . datetimeValue . set ( , , , , , ) ; insert ( simple ) ; TableSource < Simple > source = new TableSource < Simple > ( all ( ) , h2 . open ( ) ) ; try { assertThat ( next ( source ) , is ( simple ) ) ; assertThat ( next ( source ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void nullValues ( ) throws Exception { Simple simple = new Simple ( ) ; simple . number = ; insert ( simple ) ; TableSource < Simple > source = new TableSource < Simple > ( all ( ) , h2 . open ( ) ) ; try { assertThat ( next ( source ) , is ( simple ) ) ; assertThat ( next ( source ) , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void reclose ( ) throws Exception { TableSource < Simple > source = new TableSource < Simple > ( info ( "" , "" ) , h2 . open ( ) ) ; source . close ( ) ; source . close ( ) ; } @ Test ( expected = IOException . class ) public void dropCtor ( ) throws Exception { h2 . execute ( "" ) ; Connection conn = h2 . open ( ) ; try { TableSource < Simple > source = new TableSource < Simple > ( info ( "" , "" ) , conn ) ; try { source . next ( ) ; source . close ( ) ; } finally { source . close ( ) ; } } finally { conn . close ( ) ; } } @ Test ( expected = IOException . class ) public void dropNext ( ) throws Exception { h2 . execute ( "" ) ; Connection conn = h2 . open ( ) ; try { TableSource < Simple > source = new TableSource < Simple > ( info ( "" , "" ) , conn ) ; try { h2 . execute ( "" ) ; source . next ( ) ; source . close ( ) ; } finally { source . close ( ) ; } } finally { conn . close ( ) ; } } private void insert ( Simple simple ) { try { TableOutput < Simple > output = new TableOutput < Simple > ( all ( ) , h2 . open ( ) ) ; try { output . write ( simple ) ; } finally { output . close ( ) ; } } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private TableInfo < Simple > all ( ) { return info ( "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ) ; } private Simple next ( DataModelSource source ) throws IOException { DataModelReflection next = source . next ( ) ; if ( next != null ) { return SIMPLE . toObject ( next ) ; } return null ; } private TableInfo < Simple > info ( String ... columns ) { return new TableInfo < Simple > ( SIMPLE , "" , Arrays . asList ( columns ) ) ; } } package com . asakusafw . testdriver . bulkloader ; import java . io . IOException ; import java . sql . Connection ; import java . sql . SQLException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . AbstractImporterPreparator ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . ImporterPreparator ; import com . asakusafw . vocabulary . bulkloader . BulkLoadImporterDescription ; public class BulkLoadImporterPreparator extends AbstractImporterPreparator < BulkLoadImporterDescription > { static final Logger LOG = LoggerFactory . getLogger ( BulkLoadImporterPreparator . class ) ; @ Override public void truncate ( BulkLoadImporterDescription description ) throws IOException { Configuration conf = Configuration . load ( description . getTargetName ( ) ) ; String tableName = description . getTableName ( ) ; LOG . info ( "" , tableName ) ; Util . truncate ( conf , tableName ) ; String cacheId = description . calculateCacheId ( ) ; if ( description . isCacheEnabled ( ) && cacheId != null ) { LOG . info ( "" , cacheId , description . getClass ( ) . getName ( ) ) ; Util . clearCache ( conf , cacheId ) ; } } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , BulkLoadImporterDescription description ) throws IOException { Configuration conf = Configuration . load ( description . getTargetName ( ) ) ; TableInfo < V > info = buildTableInfo ( definition , description ) ; LOG . info ( "" , info . getTableName ( ) ) ; LOG . debug ( "" , info ) ; Connection conn = conf . open ( ) ; boolean green = false ; try { ModelOutput < V > output = new TableOutput < V > ( info , conn ) ; green = true ; return output ; } finally { if ( green == false ) { try { conn . close ( ) ; } catch ( SQLException e ) { } } } } private < V > TableInfo < V > buildTableInfo ( DataModelDefinition < V > definition , BulkLoadImporterDescription description ) { assert definition != null ; assert description != null ; return new TableInfo < V > ( definition , description . getTableName ( ) , description . getColumnNames ( ) , description . isCacheEnabled ( ) ) ; } } package com . asakusafw . testdriver . bulkloader ; import java . io . IOException ; import java . math . BigDecimal ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . SQLException ; import java . sql . Timestamp ; import java . sql . Types ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelScanner ; import com . asakusafw . testdriver . core . PropertyName ; public class TableOutput < T > implements ModelOutput < T > { static final Logger LOG = LoggerFactory . getLogger ( TableOutput . class ) ; private final DataModelDefinition < T > definition ; private final DmlDriver driver ; public TableOutput ( TableInfo < T > table , Connection connection ) throws IOException { if ( table == null ) { throw new IllegalArgumentException ( "" ) ; } if ( connection == null ) { throw new IllegalArgumentException ( "" ) ; } this . definition = table . getDefinition ( ) ; try { this . driver = new DmlDriver ( table , connection ) ; } catch ( SQLException e ) { throw new IOException ( MessageFormat . format ( "" , table . getTableName ( ) ) , e ) ; } } @ Override public void write ( T model ) throws IOException { DataModelReflection ref = definition . toReflection ( model ) ; try { driver . insert ( ref ) ; } catch ( SQLException e ) { throw new IOException ( MessageFormat . format ( "" , driver . table . getTableName ( ) , ref ) , e ) ; } } @ Override public void close ( ) throws IOException { try { driver . close ( ) ; } catch ( SQLException e ) { throw new IOException ( e ) ; } } private static class DmlDriver extends DataModelScanner < DataModelReflection , SQLException > { final TableInfo < ? > table ; private final Connection connection ; private final PreparedStatement statement ; private int index = ; DmlDriver ( TableInfo < ? > table , Connection connection ) throws SQLException { assert table != null ; assert connection != null ; this . table = table ; this . connection = connection ; this . statement = createStatement ( ) ; } private PreparedStatement createStatement ( ) throws SQLException { assert table != null ; assert connection != null ; LOG . debug ( "" , table ) ; String timestamp = table . getTimestampColumn ( ) ; List < String > columns = new ArrayList < String > ( table . getColumnsToProperties ( ) . keySet ( ) ) ; if ( timestamp != null ) { columns . remove ( timestamp ) ; columns . add ( timestamp ) ; } return connection . prepareStatement ( MessageFormat . format ( "" , table . getTableName ( ) , Util . join ( columns ) , Util . join ( Collections . nCopies ( columns . size ( ) , "" ) ) ) ) ; } public void insert ( DataModelReflection ref ) throws SQLException { assert ref != null ; statement . clearParameters ( ) ; index = ; String timestamp = table . getTimestampColumn ( ) ; DataModelDefinition < ? > def = table . getDefinition ( ) ; for ( Map . Entry < String , PropertyName > entry : table . getColumnsToProperties ( ) . entrySet ( ) ) { if ( entry . getKey ( ) . equals ( timestamp ) == false ) { scan ( def , entry . getValue ( ) , ref ) ; index ++ ; } } if ( timestamp != null ) { statement . setTimestamp ( index , new Timestamp ( ) ) ; } statement . executeUpdate ( ) ; } public void close ( ) throws SQLException { try { statement . close ( ) ; } finally { connection . close ( ) ; } } @ Override public void booleanProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Boolean value = ( Boolean ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . BOOLEAN ) ; } else { statement . setBoolean ( index , value ) ; } } @ Override public void byteProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Byte value = ( Byte ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . TINYINT ) ; } else { statement . setByte ( index , value ) ; } } @ Override public void shortProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Short value = ( Short ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . SMALLINT ) ; } else { statement . setShort ( index , value ) ; } } @ Override public void intProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Integer value = ( Integer ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . INTEGER ) ; } else { statement . setInt ( index , value ) ; } } @ Override public void longProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Long value = ( Long ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . BIGINT ) ; } else { statement . setLong ( index , value ) ; } } @ Override public void floatProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Float value = ( Float ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . FLOAT ) ; } else { statement . setFloat ( index , value ) ; } } @ Override public void doubleProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Double value = ( Double ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . DOUBLE ) ; } else { statement . setDouble ( index , value ) ; } } @ Override public void decimalProperty ( PropertyName name , DataModelReflection context ) throws SQLException { BigDecimal value = ( BigDecimal ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . DECIMAL ) ; } else { statement . setBigDecimal ( index , value ) ; } } @ Override public void stringProperty ( PropertyName name , DataModelReflection context ) throws SQLException { String value = ( String ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . VARCHAR ) ; } else { statement . setString ( index , value ) ; } } @ Override public void dateProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Calendar value = ( Calendar ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . DATE ) ; } else { java . sql . Date date = new java . sql . Date ( value . getTimeInMillis ( ) ) ; statement . setDate ( index , date ) ; } } @ Override public void timeProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Calendar value = ( Calendar ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . TIME ) ; } else { java . sql . Time time = new java . sql . Time ( value . getTimeInMillis ( ) ) ; statement . setTime ( index , time ) ; } } @ Override public void datetimeProperty ( PropertyName name , DataModelReflection context ) throws SQLException { Calendar value = ( Calendar ) context . getValue ( name ) ; if ( value == null ) { statement . setNull ( index , Types . TIME ) ; } else { java . sql . Timestamp timestamp = new java . sql . Timestamp ( value . getTimeInMillis ( ) ) ; statement . setTimestamp ( index , timestamp ) ; } } @ Override public void anyProperty ( PropertyName name , DataModelReflection context ) throws SQLException { throw new SQLException ( MessageFormat . format ( "" , table . getTableName ( ) , table . getDefinition ( ) . getModelClass ( ) . getName ( ) , name , table . getDefinition ( ) . getType ( name ) ) ) ; } } } package com . asakusafw . testdriver . bulkloader ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . sql . Connection ; import java . sql . DriverManager ; import java . text . MessageFormat ; import java . util . Properties ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . vocabulary . bulkloader . BulkLoadImporterDescription ; public class Configuration { static final Logger LOG = LoggerFactory . getLogger ( Configuration . class ) ; public static final String FILE_PATTERN = "" ; public static final String COMMON_FILE = "" ; private static final String [ ] PREFIX = { "" , "" , } ; public static final String K_DRIVER = "" ; public static final String K_URL = "" ; public static final String K_USER = "" ; public static final String K_PASSWORD = "" ; private final String driver ; private final String url ; private final String user ; private final String password ; public Configuration ( String driver , String url , String user , String password ) { if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } if ( url == null ) { throw new IllegalArgumentException ( "" ) ; } this . driver = driver ; this . url = url ; this . user = user ; this . password = password ; } public static Configuration load ( String targetName ) throws IOException { if ( targetName == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , targetName ) ; String path = MessageFormat . format ( FILE_PATTERN , targetName ) ; URL resource = findResource ( path ) ; if ( resource == null ) { throw new FileNotFoundException ( path ) ; } LOG . debug ( "" , resource ) ; return load ( resource ) ; } private static URL findResource ( String path ) { assert path != null ; URL specifiedResource = findResourceOnClassPath ( path ) ; if ( specifiedResource != null ) { return specifiedResource ; } URL defaultResource = findResourceOnClassPath ( COMMON_FILE ) ; if ( defaultResource != null ) { return defaultResource ; } URL contextResource = findResourceOnHomePath ( path ) ; if ( contextResource != null ) { return contextResource ; } return null ; } private static URL findResourceOnClassPath ( String path ) { assert path != null ; ClassLoader loader = getClassLoader ( ) ; URL classPath = loader . getResource ( path ) ; return classPath ; } private static URL findResourceOnHomePath ( String path ) { assert path != null ; String home = System . getenv ( "" ) ; if ( home != null ) { File file = new File ( home , "" + path ) ; if ( file . isFile ( ) != false ) { try { return file . toURI ( ) . toURL ( ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , file ) , e ) ; return null ; } } } return null ; } private static ClassLoader getClassLoader ( ) { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( loader != null ) { return loader ; } return Configuration . class . getClassLoader ( ) ; } public static Configuration load ( URL resource ) throws IOException { if ( resource == null ) { throw new IllegalArgumentException ( "" ) ; } Properties properties = loadProperties ( resource ) ; String driver = extract ( K_DRIVER , properties , true , resource ) ; String url = extract ( K_URL , properties , true , resource ) ; String user = extract ( K_USER , properties , false , resource ) ; String password = extract ( K_PASSWORD , properties , false , resource ) ; Configuration configuration = new Configuration ( driver , url , user , password ) ; LOG . debug ( "" , configuration ) ; return configuration ; } private static String extract ( String name , Properties properties , boolean mandatory , URL source ) throws IOException { assert name != null ; assert properties != null ; assert source != null ; for ( String prefix : PREFIX ) { String key = prefix + name ; String value = properties . getProperty ( key ) ; if ( value != null ) { return value ; } } if ( mandatory ) { throw new IOException ( MessageFormat . format ( "" , source , PREFIX [ ] + name ) ) ; } return null ; } private static Properties loadProperties ( URL resource ) throws IOException { assert resource != null ; InputStream in = resource . openStream ( ) ; try { Properties p = new Properties ( ) ; p . load ( in ) ; return p ; } finally { in . close ( ) ; } } public Connection open ( ) throws IOException { try { Class . forName ( driver ) ; return DriverManager . getConnection ( url , user , password ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , url ) , e ) ; } } @ Override public String toString ( ) { return MessageFormat . format ( "" , driver , url , user , password != null ) ; } } package com . asakusafw . testdriver . bulkloader ; package com . asakusafw . testdriver . bulkloader ; import java . io . IOException ; import java . net . URI ; import java . sql . Connection ; import java . sql . DatabaseMetaData ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . DataModelSourceProvider ; import com . asakusafw . testdriver . core . TestContext ; public class TableSourceProvider implements DataModelSourceProvider { static final Logger LOG = LoggerFactory . getLogger ( TableSourceProvider . class ) ; private static final String SCHEME = "" ; @ Override public < T > DataModelSource open ( DataModelDefinition < T > definition , URI source , TestContext context ) throws IOException { String scheme = source . getScheme ( ) ; if ( scheme == null || ! scheme . equals ( SCHEME ) ) { LOG . debug ( "" , source ) ; return null ; } LOG . info ( "" , source ) ; String [ ] pathArray = source . toString ( ) . split ( "" ) ; String targetName = pathArray [ ] ; String tableName = pathArray [ ] ; Configuration conf = Configuration . load ( targetName ) ; Connection conn = null ; ResultSet res = null ; try { conn = conf . open ( ) ; DatabaseMetaData meta = conn . getMetaData ( ) ; res = meta . getColumns ( null , null , tableName , "" ) ; List < String > columnList = new ArrayList < String > ( ) ; while ( res . next ( ) ) { columnList . add ( res . getString ( "" ) ) ; } TableInfo < T > table = new TableInfo < T > ( definition , tableName , columnList ) ; return new TableSource < T > ( table , conn ) ; } catch ( SQLException e ) { throw new IOException ( e ) ; } } } package com . asakusafw . testdriver . bulkloader ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . EnumSet ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; import com . asakusafw . vocabulary . bulkloader . OriginalName ; public class TableInfo < T > { static final Logger LOG = LoggerFactory . getLogger ( TableInfo . class ) ; private static final Set < PropertyType > SUPPORTED_TYPES ; static { Set < PropertyType > set = EnumSet . allOf ( PropertyType . class ) ; set . remove ( PropertyType . OBJECT ) ; set . remove ( PropertyType . SEQUENCE ) ; SUPPORTED_TYPES = Collections . unmodifiableSet ( set ) ; } private final DataModelDefinition < T > definition ; private final String tableName ; private final Map < String , PropertyName > columnsToProperties ; private final String timestampColumn ; public TableInfo ( DataModelDefinition < T > definition , String tableName , List < String > columnNames ) { this ( definition , tableName , columnNames , true ) ; } public TableInfo ( DataModelDefinition < T > definition , String tableName , List < String > columnNames , boolean extractTimestamp ) { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } this . definition = definition ; this . tableName = tableName ; this . columnsToProperties = createMappings ( columnNames ) ; if ( extractTimestamp ) { this . timestampColumn = extractTimestampColumn ( ) ; } else { this . timestampColumn = null ; } } public DataModelDefinition < T > getDefinition ( ) { return definition ; } public String getTableName ( ) { return tableName ; } public String getTimestampColumn ( ) { return timestampColumn ; } public Map < String , PropertyName > getColumnsToProperties ( ) { return columnsToProperties ; } private String extractTimestampColumn ( ) { assert definition != null ; if ( ThunderGateCacheSupport . class . isAssignableFrom ( definition . getModelClass ( ) ) == false ) { return null ; } String columnName ; try { ThunderGateCacheSupport support = definition . getModelClass ( ) . asSubclass ( ThunderGateCacheSupport . class ) . newInstance ( ) ; columnName = support . __tgc__TimestampColumn ( ) ; } catch ( Exception e ) { LOG . warn ( MessageFormat . format ( "" , tableName ) , e ) ; return null ; } return columnName ; } private Map < String , PropertyName > createMappings ( List < String > columnNames ) { assert definition != null ; assert columnNames != null ; Map < String , PropertyName > allMapping = extractAllMappings ( ) ; Map < String , PropertyName > results = new LinkedHashMap < String , PropertyName > ( ) ; for ( String column : columnNames ) { PropertyName propertyName = allMapping . get ( column ) ; if ( propertyName == null ) { LOG . warn ( MessageFormat . format ( "" , tableName , column , definition . getModelClass ( ) . getName ( ) ) ) ; continue ; } results . put ( column , propertyName ) ; } return Collections . unmodifiableMap ( results ) ; } private Map < String , PropertyName > extractAllMappings ( ) { assert definition != null ; Map < String , PropertyName > results = new TreeMap < String , PropertyName > ( String . CASE_INSENSITIVE_ORDER ) ; for ( PropertyName name : definition . getProperties ( ) ) { PropertyType type = definition . getType ( name ) ; assert type != null ; if ( acceptsType ( name , type ) == false ) { continue ; } String columnName = getOriginalName ( name ) ; if ( columnName == null ) { continue ; } results . put ( columnName , name ) ; } return results ; } private String getOriginalName ( PropertyName name ) { assert name != null ; assert definition . getType ( name ) != null ; OriginalName a = definition . getAnnotation ( name , OriginalName . class ) ; if ( a != null ) { return a . value ( ) ; } Iterator < String > iter = name . getWords ( ) . iterator ( ) ; assert iter . hasNext ( ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( '' ) ; buf . append ( iter . next ( ) ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , definition . getModelClass ( ) . getName ( ) , name , OriginalName . class . getSimpleName ( ) , buf ) ) ; } return buf . toString ( ) ; } private boolean acceptsType ( PropertyName name , PropertyType type ) { assert name != null ; assert type != null ; return SUPPORTED_TYPES . contains ( type ) ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , tableName , definition . getModelClass ( ) . getName ( ) , columnsToProperties ) ; } } package com . asakusafw . testdriver . bulkloader ; import java . io . IOException ; import java . sql . Connection ; import java . sql . SQLException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . AbstractExporterRetriever ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . ExporterRetriever ; import com . asakusafw . vocabulary . bulkloader . BulkLoadExporterDescription ; import com . asakusafw . vocabulary . bulkloader . BulkLoadExporterDescription . DuplicateRecordCheck ; public class BulkLoadExporterRetriever extends AbstractExporterRetriever < BulkLoadExporterDescription > { static final Logger LOG = LoggerFactory . getLogger ( BulkLoadExporterRetriever . class ) ; @ Override public void truncate ( BulkLoadExporterDescription description ) throws IOException { Configuration conf = Configuration . load ( description . getTargetName ( ) ) ; truncate ( conf , description . getTableName ( ) ) ; if ( description . getDuplicateRecordCheck ( ) != null ) { truncate ( conf , description . getDuplicateRecordCheck ( ) . getTableName ( ) ) ; } } private void truncate ( Configuration conf , String tableName ) throws IOException { assert conf != null ; assert tableName != null ; LOG . info ( "" , tableName ) ; Util . truncate ( conf , tableName ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , BulkLoadExporterDescription description ) throws IOException { Configuration conf = Configuration . load ( description . getTargetName ( ) ) ; TableInfo < V > info = buildTableInfo ( definition , description ) ; LOG . info ( "" , info . getTableName ( ) ) ; LOG . debug ( "" , info ) ; Connection conn = conf . open ( ) ; boolean green = false ; try { ModelOutput < V > output = new TableOutput < V > ( info , conn ) ; green = true ; return output ; } finally { if ( green == false ) { try { conn . close ( ) ; } catch ( SQLException e ) { } } } } @ Override public < V > DataModelSource createSource ( DataModelDefinition < V > definition , BulkLoadExporterDescription description ) throws IOException { Configuration conf = Configuration . load ( description . getTargetName ( ) ) ; TableInfo < V > info = buildTableInfo ( definition , description ) ; LOG . info ( "" , info . getTableName ( ) ) ; LOG . debug ( "" , info ) ; Connection conn = conf . open ( ) ; boolean green = false ; try { DataModelSource source = new TableSource < V > ( info , conn ) ; green = true ; return source ; } finally { if ( green == false ) { try { conn . close ( ) ; } catch ( SQLException e ) { } } } } private < V > TableInfo < V > buildTableInfo ( DataModelDefinition < V > definition , BulkLoadExporterDescription description ) throws IOException { assert definition != null ; assert description != null ; if ( isNormalTarget ( definition , description ) ) { return new TableInfo < V > ( definition , description . getTableName ( ) , description . getTargetColumnNames ( ) ) ; } else { DuplicateRecordCheck dup = description . getDuplicateRecordCheck ( ) ; List < String > columns = dup . getColumnNames ( ) ; if ( columns . contains ( dup . getErrorCodeColumnName ( ) ) == false ) { columns = new ArrayList < String > ( columns ) ; columns . add ( dup . getErrorCodeColumnName ( ) ) ; } return new TableInfo < V > ( definition , dup . getTableName ( ) , columns ) ; } } private boolean isNormalTarget ( DataModelDefinition < ? > definition , BulkLoadExporterDescription description ) throws IOException { assert definition != null ; assert description != null ; LOG . debug ( "" ) ; Class < ? > modelClass = definition . getModelClass ( ) ; DuplicateRecordCheck dupcheck = description . getDuplicateRecordCheck ( ) ; if ( dupcheck != null && modelClass == dupcheck . getTableModelClass ( ) ) { return false ; } else if ( modelClass == description . getTableModelClass ( ) ) { return true ; } else { throw new IOException ( MessageFormat . format ( "" , description . getClass ( ) . getName ( ) , modelClass . getName ( ) ) ) ; } } } package com . asakusafw . testdriver . bulkloader ; import java . io . IOException ; import java . sql . Connection ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . Iterator ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; final class Util { static final Logger LOG = LoggerFactory . getLogger ( Util . class ) ; static void truncate ( Configuration config , String tableName ) throws IOException { assert config != null ; assert tableName != null ; try { Connection conn = config . open ( ) ; try { Statement statement = conn . createStatement ( ) ; try { statement . execute ( MessageFormat . format ( "" , tableName ) ) ; } finally { statement . close ( ) ; } } finally { conn . close ( ) ; } } catch ( SQLException e ) { LOG . warn ( MessageFormat . format ( "" , tableName ) , e ) ; } } static void clearCache ( Configuration config , String cacheId ) throws IOException { assert config != null ; assert cacheId != null ; try { boolean committed = false ; Connection conn = config . open ( ) ; try { Statement statement = conn . createStatement ( ) ; try { statement . execute ( MessageFormat . format ( "" , cacheId ) ) ; statement . execute ( MessageFormat . format ( "" , cacheId ) ) ; if ( conn . getAutoCommit ( ) == false ) { conn . commit ( ) ; } committed = true ; } finally { statement . close ( ) ; } } finally { if ( committed == false && conn . getAutoCommit ( ) == false ) { conn . rollback ( ) ; } conn . close ( ) ; } } catch ( SQLException e ) { LOG . warn ( MessageFormat . format ( "" , cacheId ) , e ) ; } } static String join ( Iterable < String > list ) { assert list != null ; Iterator < String > iterator = list . iterator ( ) ; assert iterator . hasNext ( ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( iterator . next ( ) ) ; while ( iterator . hasNext ( ) ) { buf . append ( "" ) ; buf . append ( iterator . next ( ) ) ; } return buf . toString ( ) ; } private Util ( ) { return ; } } package com . asakusafw . testdriver . bulkloader ; import java . io . IOException ; import java . math . BigDecimal ; import java . sql . Connection ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . Calendar ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelDefinition . Builder ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelScanner ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . PropertyName ; public class TableSource < T > implements DataModelSource { static final Logger LOG = LoggerFactory . getLogger ( TableSource . class ) ; private final SqlDriver driver ; public TableSource ( TableInfo < T > table , Connection connection ) throws IOException { if ( table == null ) { throw new IllegalArgumentException ( "" ) ; } if ( connection == null ) { throw new IllegalArgumentException ( "" ) ; } try { this . driver = new SqlDriver ( table , connection ) ; } catch ( SQLException e ) { throw new IOException ( MessageFormat . format ( "" , table . getTableName ( ) ) , e ) ; } } @ Override public DataModelReflection next ( ) throws IOException { try { return driver . next ( ) ; } catch ( SQLException e ) { throw new IOException ( MessageFormat . format ( "" , driver . table . getTableName ( ) ) , e ) ; } } @ Override public void close ( ) throws IOException { try { driver . close ( ) ; } catch ( SQLException e ) { throw new IOException ( e ) ; } } private static class SqlDriver extends DataModelScanner < Builder < ? > , SQLException > { final TableInfo < ? > table ; private final Connection connection ; private final Statement statement ; private final ResultSet resultSet ; private int index = ; SqlDriver ( TableInfo < ? > table , Connection connection ) throws SQLException { assert table != null ; assert connection != null ; this . table = table ; this . connection = connection ; this . statement = connection . createStatement ( ) ; this . resultSet = select ( ) ; } private ResultSet select ( ) throws SQLException { assert table != null ; assert connection != null ; LOG . debug ( "" , table ) ; Set < String > columns = table . getColumnsToProperties ( ) . keySet ( ) ; boolean green = false ; try { ResultSet rs = statement . executeQuery ( MessageFormat . format ( "" , table . getTableName ( ) , Util . join ( columns ) ) ) ; green = true ; return rs ; } finally { if ( green == false ) { statement . close ( ) ; } } } public DataModelReflection next ( ) throws SQLException { if ( resultSet . next ( ) == false ) { return null ; } index = ; DataModelDefinition < ? > def = table . getDefinition ( ) ; Builder < ? > builder = def . newReflection ( ) ; for ( PropertyName name : table . getColumnsToProperties ( ) . values ( ) ) { scan ( def , name , builder ) ; index ++ ; } DataModelReflection ref = builder . build ( ) ; return ref ; } public void close ( ) throws SQLException { try { try { resultSet . close ( ) ; } finally { statement . close ( ) ; } } finally { connection . close ( ) ; } } @ Override public void booleanProperty ( PropertyName name , Builder < ? > context ) throws SQLException { boolean value = resultSet . getBoolean ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void byteProperty ( PropertyName name , Builder < ? > context ) throws SQLException { byte value = resultSet . getByte ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void shortProperty ( PropertyName name , Builder < ? > context ) throws SQLException { short value = resultSet . getShort ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void intProperty ( PropertyName name , Builder < ? > context ) throws SQLException { int value = resultSet . getInt ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void longProperty ( PropertyName name , Builder < ? > context ) throws SQLException { long value = resultSet . getLong ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void floatProperty ( PropertyName name , Builder < ? > context ) throws SQLException { float value = resultSet . getFloat ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void doubleProperty ( PropertyName name , Builder < ? > context ) throws SQLException { double value = resultSet . getDouble ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void decimalProperty ( PropertyName name , Builder < ? > context ) throws SQLException { BigDecimal value = resultSet . getBigDecimal ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void stringProperty ( PropertyName name , Builder < ? > context ) throws SQLException { String value = resultSet . getString ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } context . add ( name , value ) ; } @ Override public void dateProperty ( PropertyName name , Builder < ? > context ) throws SQLException { java . sql . Date value = resultSet . getDate ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( value ) ; Calendar trimmed = Calendar . getInstance ( ) ; trimmed . clear ( ) ; copyField ( calendar , trimmed , Calendar . YEAR ) ; copyField ( calendar , trimmed , Calendar . MONTH ) ; copyField ( calendar , trimmed , Calendar . DATE ) ; context . add ( name , trimmed ) ; } @ Override public void timeProperty ( PropertyName name , Builder < ? > context ) throws SQLException { java . sql . Time value = resultSet . getTime ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( value ) ; Calendar trimmed = Calendar . getInstance ( ) ; trimmed . clear ( ) ; copyField ( calendar , trimmed , Calendar . HOUR_OF_DAY ) ; copyField ( calendar , trimmed , Calendar . MINUTE ) ; copyField ( calendar , trimmed , Calendar . SECOND ) ; context . add ( name , trimmed ) ; } @ Override public void datetimeProperty ( PropertyName name , Builder < ? > context ) throws SQLException { java . sql . Timestamp value = resultSet . getTimestamp ( index ) ; if ( resultSet . wasNull ( ) ) { return ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( value ) ; Calendar trimmed = Calendar . getInstance ( ) ; trimmed . clear ( ) ; copyField ( calendar , trimmed , Calendar . YEAR ) ; copyField ( calendar , trimmed , Calendar . MONTH ) ; copyField ( calendar , trimmed , Calendar . DATE ) ; copyField ( calendar , trimmed , Calendar . HOUR_OF_DAY ) ; copyField ( calendar , trimmed , Calendar . MINUTE ) ; copyField ( calendar , trimmed , Calendar . SECOND ) ; context . add ( name , trimmed ) ; } private void copyField ( Calendar from , Calendar to , int field ) { assert from != null ; assert to != null ; to . set ( field , from . get ( field ) ) ; } @ Override public void anyProperty ( PropertyName name , Builder < ? > context ) throws SQLException { throw new SQLException ( MessageFormat . format ( "" , table . getTableName ( ) , table . getDefinition ( ) . getModelClass ( ) . getName ( ) , name , table . getDefinition ( ) . getType ( name ) ) ) ; } } } package com . asakusafw . utils . graph ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . junit . Test ; public class GraphsTest { @ Test public void copy_Empty ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; Graph < Integer > copy = Graphs . copy ( graph ) ; assertThat ( copy . isEmpty ( ) , is ( true ) ) ; } @ Test public void copy_normal ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , ) ; addPath ( graph , , ) ; addPath ( graph , , ) ; Graph < Integer > copy = Graphs . copy ( graph ) ; assertThat ( copy . getNodeSet ( ) , is ( set ( , , , ) ) ) ; assertThat ( copy . getConnected ( ) , is ( set ( ) ) ) ; assertThat ( copy . getConnected ( ) , is ( set ( , ) ) ) ; assertThat ( copy . getConnected ( ) , is ( set ( , ) ) ) ; assertThat ( copy . getConnected ( ) , is ( set ( ) ) ) ; } @ Test public void subgraph ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , , ) ; addPath ( graph , , , , , , ) ; Graph < Integer > sub = Graphs . subgraph ( graph , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object != ; } } ) ; Graph < Integer > expect = Graphs . newInstance ( ) ; addPath ( expect , , , , , ) ; addPath ( expect , , ) ; addPath ( expect , , ) ; assertThat ( sub , is ( expect ) ) ; } @ Test public void subgraph_empty ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , , ) ; addPath ( graph , , , , , , ) ; Graph < Integer > sub = Graphs . subgraph ( graph , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return false ; } } ) ; assertThat ( sub . isEmpty ( ) , is ( true ) ) ; } @ Test public void subgraph_all ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , , ) ; addPath ( graph , , , , , , ) ; Graph < Integer > sub = Graphs . subgraph ( graph , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return true ; } } ) ; assertThat ( sub , is ( graph ) ) ; } @ Test public void testCollectAllConnected_Cyclic ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , ) ; addPath ( graph , , ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( , , , ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( , , , ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( , , , ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( , , , ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( ) ) ) ; } @ Test public void testCollectAllConnected_Multi ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; addPath ( graph , , ) ; addPath ( graph , , ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( , ) ) , is ( set ( , , ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( , ) ) , is ( set ( , , ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( , ) ) , is ( set ( ) ) ) ; } @ Test public void testCollectAllConnected_Single ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; addPath ( graph , , ) ; addPath ( graph , , ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( , , ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( , ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( ) ) ) ; assertThat ( Graphs . collectAllConnected ( graph , set ( ) ) , is ( set ( , , ) ) ) ; } @ Test public void findNearest_simple ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , - , - ) ; Set < Integer > results = Graphs . findNearest ( graph , set ( ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - ) ) ) ; } @ Test public void findNearest_hop ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , - ) ; Set < Integer > results = Graphs . findNearest ( graph , set ( ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - ) ) ) ; } @ Test public void findNearest_ignoreItself ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , - , , - ) ; Set < Integer > results = Graphs . findNearest ( graph , set ( - ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - ) ) ) ; } @ Test public void findNearest_dominants ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , - , , - , - ) ; addPath ( graph , , , ) ; Set < Integer > results = Graphs . findNearest ( graph , set ( ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - , - ) ) ) ; } @ Test public void findNearest_multipath ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , - , - ) ; addPath ( graph , , - , - ) ; addPath ( graph , , , - ) ; addPath ( graph , , - , - ) ; Set < Integer > results = Graphs . findNearest ( graph , set ( , ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - , - , - ) ) ) ; } @ Test public void findNearest_overlap ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , - , , - , ) ; Set < Integer > results = Graphs . findNearest ( graph , set ( , - ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - , - ) ) ) ; } @ Test public void collectNearest_simple ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , - , - ) ; Set < Integer > results = Graphs . collectNearest ( graph , set ( ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - ) ) ) ; } @ Test public void collectNearest_hop ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , - ) ; Set < Integer > results = Graphs . collectNearest ( graph , set ( ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( , - ) ) ) ; } @ Test public void collectNearest_ignoreItself ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , - , , - ) ; Set < Integer > results = Graphs . collectNearest ( graph , set ( - ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( , - ) ) ) ; } @ Test public void collectNearest_dominants ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , - , , - , - ) ; addPath ( graph , , , ) ; Set < Integer > results = Graphs . collectNearest ( graph , set ( ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - , , , - ) ) ) ; } @ Test public void collectNearest_multipath ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , - , - ) ; addPath ( graph , , - , - ) ; addPath ( graph , , , - ) ; addPath ( graph , , - , - ) ; Set < Integer > results = Graphs . collectNearest ( graph , set ( , ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - , - , , - ) ) ) ; } @ Test public void collectNearest_overlap ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , - , , - , ) ; Set < Integer > results = Graphs . collectNearest ( graph , set ( , - ) , new Matcher < Integer > ( ) { @ Override public boolean matches ( Integer object ) { return object < ; } } ) ; assertThat ( results , is ( set ( - , , - ) ) ) ; } @ Test public void testFindCircuit_Circuit ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , ) ; Set < Set < Integer > > circuits = Graphs . findCircuit ( graph ) ; Integer [ ] [ ] expect = { { , , } } ; assertThat ( circuits , is ( toPartition ( expect ) ) ) ; } @ Test public void testFindCircuit_Complex ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , ) ; addPath ( graph , , , ) ; addPath ( graph , , , , ) ; Set < Set < Integer > > circuits = Graphs . findCircuit ( graph ) ; Integer [ ] [ ] expect = { { , , } } ; assertThat ( circuits , is ( toPartition ( expect ) ) ) ; } @ Test public void testFindCircuit_Self ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , ) ; Set < Set < Integer > > circuits = Graphs . findCircuit ( graph ) ; Integer [ ] [ ] expect = { { } } ; assertThat ( circuits , is ( toPartition ( expect ) ) ) ; } @ Test public void testFindCircuit_Tree ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; addPath ( graph , , ) ; addPath ( graph , , , ) ; addPath ( graph , , ) ; Set < Set < Integer > > circuits = Graphs . findCircuit ( graph ) ; Integer [ ] [ ] expect = { } ; assertThat ( circuits , is ( toPartition ( expect ) ) ) ; } @ Test public void testFindStronglyConnectedComponents_Circuit ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , ) ; Set < Set < Integer > > scc = Graphs . findStronglyConnectedComponents ( graph ) ; Integer [ ] [ ] expect = { { , , } } ; assertThat ( scc , is ( toPartition ( expect ) ) ) ; } @ Test public void testFindStronglyConnectedComponents_Complex ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , ) ; addPath ( graph , , , ) ; addPath ( graph , , , , ) ; Set < Set < Integer > > scc = Graphs . findStronglyConnectedComponents ( graph ) ; Integer [ ] [ ] expect = { { } , { } , { } , { } , { , , } } ; assertThat ( scc , is ( toPartition ( expect ) ) ) ; } @ Test public void testFindStronglyConnectedComponents_Tree ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; addPath ( graph , , ) ; addPath ( graph , , , ) ; addPath ( graph , , ) ; Set < Set < Integer > > scc = Graphs . findStronglyConnectedComponents ( graph ) ; Integer [ ] [ ] expect = { { } , { } , { } , { } , { } , { } , { } } ; assertThat ( scc , is ( toPartition ( expect ) ) ) ; } @ Test public void testNewInstance ( ) { Graph < String > graph = Graphs . newInstance ( ) ; assertThat ( graph . getNodeSet ( ) . isEmpty ( ) , is ( true ) ) ; } @ Test public void testSortPostOrder_Circuit ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , , ) ; List < Integer > sorted = Graphs . sortPostOrder ( graph ) ; assertThat ( sorted . size ( ) , is ( ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; sorted . remove ( ( Integer ) ) ; sorted . remove ( ( Integer ) ) ; sorted . remove ( ( Integer ) ) ; assertThat ( sorted , is ( Arrays . asList ( , ) ) ) ; } @ Test public void testSortPostOrder_List ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , ) ; List < Integer > sorted = Graphs . sortPostOrder ( graph ) ; assertThat ( sorted , is ( Arrays . asList ( , , , , ) ) ) ; } @ Test public void testSortPostOrder_Tree ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; addPath ( graph , , , ) ; addPath ( graph , , , ) ; addPath ( graph , , , ) ; List < Integer > sorted = Graphs . sortPostOrder ( graph ) ; assertThat ( sorted . size ( ) , is ( ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( , isIn ( sorted ) ) ; assertThat ( "" , sorted . get ( ) , is ( ) ) ; assertPostOrdered ( graph , sorted ) ; } @ Test public void testTransposeGraph_noEdges ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; prepare ( graph , ) ; Graph < Integer > expect = Graphs . newInstance ( ) ; prepare ( expect , ) ; assertThat ( Graphs . transpose ( graph ) , is ( expect ) ) ; } @ Test public void testTransposeGraph ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; prepare ( graph , ) ; prepare ( graph , , ) ; prepare ( graph , , , , ) ; prepare ( graph , , , ) ; prepare ( graph , , , ) ; Graph < Integer > expect = Graphs . newInstance ( ) ; prepare ( expect , , ) ; prepare ( expect , , ) ; prepare ( expect , , ) ; prepare ( expect , , ) ; prepare ( expect , , ) ; prepare ( expect , , , ) ; prepare ( expect , , ) ; assertThat ( Graphs . transpose ( graph ) , is ( expect ) ) ; } @ Test public void testCollectHeads_empty ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; assertThat ( Graphs . collectHeads ( graph ) , is ( set ( ) ) ) ; } @ Test public void testCollectHeads_single ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , ) ; assertThat ( Graphs . collectHeads ( graph ) , is ( set ( ) ) ) ; } @ Test public void testCollectHeads_connected ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; assertThat ( Graphs . collectHeads ( graph ) , is ( set ( ) ) ) ; } @ Test public void testCollectHeads_disconnected ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , ) ; addPath ( graph , ) ; addPath ( graph , ) ; addPath ( graph , ) ; assertThat ( Graphs . collectHeads ( graph ) , is ( set ( , , , ) ) ) ; } @ Test public void testCollectHeads_multi ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; addPath ( graph , , , ) ; assertThat ( Graphs . collectHeads ( graph ) , is ( set ( , ) ) ) ; } @ Test public void testCollectHeads_cyclic ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , ) ; assertThat ( Graphs . collectHeads ( graph ) , is ( set ( ) ) ) ; } @ Test public void testCollectTails_empty ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; assertThat ( Graphs . collectTails ( graph ) , is ( set ( ) ) ) ; } @ Test public void testCollectTails_single ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , ) ; assertThat ( Graphs . collectTails ( graph ) , is ( set ( ) ) ) ; } @ Test public void testCollectTails_connected ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; assertThat ( Graphs . collectTails ( graph ) , is ( set ( ) ) ) ; } @ Test public void testCollectTails_disconnected ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , ) ; addPath ( graph , ) ; addPath ( graph , ) ; addPath ( graph , ) ; assertThat ( Graphs . collectTails ( graph ) , is ( set ( , , , ) ) ) ; } @ Test public void testCollectTails_multi ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , ) ; addPath ( graph , , , ) ; assertThat ( Graphs . collectTails ( graph ) , is ( set ( , ) ) ) ; } @ Test public void testCollectTails_cyclic ( ) { Graph < Integer > graph = Graphs . newInstance ( ) ; addPath ( graph , , , , , ) ; assertThat ( Graphs . collectTails ( graph ) , is ( set ( ) ) ) ; } private < V > void addPath ( Graph < V > graph , V first , V ... vertexes ) { graph . addNode ( first ) ; V current = first ; for ( V v : vertexes ) { graph . addEdge ( current , v ) ; current = v ; } } private void assertPostOrdered ( Graph < ? > graph , List < ? > list ) { for ( int i = , n = list . size ( ) ; i < n ; i ++ ) { Object from = list . get ( i ) ; for ( int j = i + ; j < n ; j ++ ) { Object to = list . get ( j ) ; assertThat ( from + "" + to , graph . isConnected ( from , to ) , is ( false ) ) ; } } } private < T > void prepare ( Graph < T > graph , T from , T ... to ) { graph . addNode ( from ) ; for ( T t : to ) { graph . addEdge ( from , t ) ; } } private Set < Integer > set ( Integer ... values ) { return new HashSet < Integer > ( Arrays . asList ( values ) ) ; } private < T > Set < Set < T > > toPartition ( T [ ] [ ] tss ) { Set < Set < T > > results = new HashSet < Set < T > > ( ) ; for ( T [ ] ts : tss ) { Set < T > part = new HashSet < T > ( ) ; for ( T t : ts ) { part . add ( t ) ; } results . add ( part ) ; } return results ; } } package com . asakusafw . utils . graph ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import com . asakusafw . utils . graph . Graph . Vertex ; public final class Graphs { public static < V > Graph < V > newInstance ( ) { return new HashGraph < V > ( ) ; } public static < V > Graph < V > copy ( Graph < ? extends V > graph ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } Graph < V > copy = newInstance ( ) ; for ( Graph . Vertex < ? extends V > vertex : graph ) { copy . addEdges ( vertex . getNode ( ) , vertex . getConnected ( ) ) ; } return copy ; } public static < V > Set < V > collectHeads ( Graph < ? extends V > graph ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } Set < V > results = new HashSet < V > ( graph . getNodeSet ( ) ) ; for ( Vertex < ? extends V > vertex : graph ) { results . removeAll ( vertex . getConnected ( ) ) ; } return results ; } public static < V > Set < V > collectTails ( Graph < ? extends V > graph ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } Set < V > results = new HashSet < V > ( ) ; for ( Vertex < ? extends V > vertex : graph ) { if ( vertex . getConnected ( ) . isEmpty ( ) ) { results . add ( vertex . getNode ( ) ) ; } } return results ; } public static < V > Set < V > collectAllConnected ( Graph < ? extends V > graph , Collection < ? extends V > startNodes ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } if ( startNodes == null ) { throw new IllegalArgumentException ( "" ) ; } Set < V > connected = new HashSet < V > ( ) ; for ( V start : startNodes ) { findAllConnected ( graph , start , connected ) ; } return connected ; } public static < V > Set < V > findNearest ( Graph < ? extends V > graph , Collection < ? extends V > startNodes , Matcher < ? super V > acceptor ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } if ( startNodes == null ) { throw new IllegalArgumentException ( "" ) ; } if ( acceptor == null ) { throw new IllegalArgumentException ( "" ) ; } LinkedList < V > queue = new LinkedList < V > ( ) ; for ( V start : startNodes ) { queue . addAll ( graph . getConnected ( start ) ) ; } Set < V > saw = new HashSet < V > ( ) ; Set < V > results = new HashSet < V > ( ) ; while ( queue . isEmpty ( ) == false ) { V first = queue . removeFirst ( ) ; if ( saw . contains ( first ) ) { continue ; } saw . add ( first ) ; boolean accepted = acceptor . matches ( first ) ; if ( accepted ) { results . add ( first ) ; } else { queue . addAll ( graph . getConnected ( first ) ) ; } } return results ; } public static < V > Set < V > collectNearest ( Graph < ? extends V > graph , Collection < ? extends V > startNodes , Matcher < ? super V > acceptor ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } if ( startNodes == null ) { throw new IllegalArgumentException ( "" ) ; } if ( acceptor == null ) { throw new IllegalArgumentException ( "" ) ; } LinkedList < V > queue = new LinkedList < V > ( ) ; for ( V start : startNodes ) { queue . addAll ( graph . getConnected ( start ) ) ; } Set < V > saw = new HashSet < V > ( ) ; Set < V > results = new HashSet < V > ( ) ; while ( queue . isEmpty ( ) == false ) { V first = queue . removeFirst ( ) ; if ( saw . contains ( first ) ) { continue ; } saw . add ( first ) ; boolean accepted = acceptor . matches ( first ) ; if ( accepted ) { results . add ( first ) ; } else { results . add ( first ) ; queue . addAll ( graph . getConnected ( first ) ) ; } } return results ; } public static < V > Set < Set < V > > findCircuit ( Graph < ? extends V > graph ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } Set < Set < V > > results = new HashSet < Set < V > > ( ) ; Set < Set < V > > sccs = Graphs . findStronglyConnectedComponents ( graph ) ; for ( Set < V > scc : sccs ) { if ( scc . size ( ) >= ) { results . add ( scc ) ; } else if ( scc . size ( ) == ) { V vertex = scc . iterator ( ) . next ( ) ; if ( graph . isConnected ( vertex , vertex ) ) { results . add ( scc ) ; } } } return results ; } public static < V > Set < Set < V > > findStronglyConnectedComponents ( Graph < ? extends V > graph ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } List < ? extends V > postorder = computePostOrderByDepth ( graph ) ; Graph < ? extends V > tgraph = transpose ( graph ) ; List < Set < V > > results = new ArrayList < Set < V > > ( ) ; Set < V > saw = new HashSet < V > ( ) ; for ( int i = postorder . size ( ) - ; i >= ; -- i ) { V start = postorder . get ( i ) ; if ( saw . contains ( start ) ) { continue ; } saw . add ( start ) ; Set < V > connected = new HashSet < V > ( ) ; connected . add ( start ) ; VisitFrame < V > top = VisitFrame . build ( tgraph , start ) ; while ( top != null ) { while ( top . branches . hasNext ( ) ) { V node = top . branches . next ( ) ; if ( saw . contains ( node ) ) { continue ; } saw . add ( node ) ; connected . add ( node ) ; top = top . push ( node ) ; } top = top . previous ; } results . add ( connected ) ; } return new HashSet < Set < V > > ( results ) ; } public static < V > List < V > sortPostOrder ( Graph < ? extends V > graph ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } List < ? extends V > postorder = computePostOrderByDepth ( graph ) ; return new ArrayList < V > ( postorder ) ; } public static < V > Graph < V > transpose ( Graph < V > graph ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } Graph < V > results = new HashGraph < V > ( ) ; for ( Graph . Vertex < V > vertex : graph ) { V from = vertex . getNode ( ) ; results . addNode ( from ) ; for ( V to : vertex . getConnected ( ) ) { results . addEdge ( to , from ) ; } } return results ; } public static < V > Graph < V > subgraph ( Graph < ? extends V > graph , Matcher < ? super V > acceptor ) { if ( graph == null ) { throw new IllegalArgumentException ( "" ) ; } if ( acceptor == null ) { throw new IllegalArgumentException ( "" ) ; } Graph < V > subgraph = newInstance ( ) ; Map < V , Boolean > accepted = new HashMap < V , Boolean > ( ) ; for ( V vertex : graph . getNodeSet ( ) ) { boolean matched = acceptor . matches ( vertex ) ; if ( matched ) { subgraph . addNode ( vertex ) ; } accepted . put ( vertex , matched ) ; } if ( subgraph . isEmpty ( ) ) { return subgraph ; } for ( Graph . Vertex < ? extends V > vertex : graph ) { V from = vertex . getNode ( ) ; assert accepted . containsKey ( from ) ; if ( Boolean . FALSE . equals ( accepted . get ( from ) ) ) { continue ; } for ( V to : vertex . getConnected ( ) ) { assert accepted . containsKey ( to ) ; if ( Boolean . FALSE . equals ( accepted . get ( to ) ) ) { continue ; } subgraph . addEdge ( from , to ) ; } } return subgraph ; } private static < V > List < V > computePostOrderByDepth ( Graph < ? extends V > graph ) { assert graph != null ; List < V > results = new ArrayList < V > ( ) ; Set < V > saw = new HashSet < V > ( ) ; for ( Graph . Vertex < ? extends V > start : graph ) { if ( saw . contains ( start . getNode ( ) ) ) { continue ; } saw . add ( start . getNode ( ) ) ; VisitFrame < V > top = VisitFrame . build ( graph , start . getNode ( ) ) ; while ( top != null ) { while ( top . branches . hasNext ( ) ) { V node = top . branches . next ( ) ; if ( saw . contains ( node ) ) { continue ; } saw . add ( node ) ; top = top . push ( node ) ; } results . add ( top . node ) ; top = top . previous ; } } return results ; } private static < V > void findAllConnected ( Graph < ? extends V > graph , V start , Set < V > connected ) { assert graph != null ; assert connected != null ; if ( connected . contains ( start ) ) { return ; } if ( graph . contains ( start ) == false ) { return ; } VisitFrame < V > top = VisitFrame . build ( graph , start ) ; while ( top != null ) { while ( top . branches . hasNext ( ) ) { V node = top . branches . next ( ) ; if ( connected . contains ( node ) ) { continue ; } connected . add ( node ) ; top = top . push ( node ) ; } top = top . previous ; } } private Graphs ( ) { throw new AssertionError ( ) ; } private static final class VisitFrame < V > { private final Graph < ? extends V > graph ; final VisitFrame < V > previous ; final V node ; final Iterator < ? extends V > branches ; VisitFrame ( VisitFrame < V > previous , Graph < ? extends V > graph , V node , Iterator < ? extends V > branch ) { assert graph != null ; assert branch != null ; this . graph = graph ; this . previous = previous ; this . node = node ; this . branches = branch ; } static < V > VisitFrame < V > build ( Graph < ? extends V > graph , V node ) { assert graph != null ; Iterator < ? extends V > branch = graph . getConnected ( node ) . iterator ( ) ; return new VisitFrame < V > ( null , graph , node , branch ) ; } VisitFrame < V > push ( V nextNode ) { Iterator < ? extends V > nextBranch = graph . getConnected ( nextNode ) . iterator ( ) ; return new VisitFrame < V > ( this , graph , nextNode , nextBranch ) ; } } } package com . asakusafw . utils . graph ; public interface Matcher < T > { boolean matches ( T object ) ; } package com . asakusafw . utils . graph ; import java . util . Collection ; import java . util . Set ; public interface Graph < V > extends Iterable < Graph . Vertex < V > > { void addEdge ( V from , V to ) ; void addEdges ( V from , Collection < ? extends V > to ) ; void addNode ( V node ) ; void clear ( ) ; boolean contains ( Object node ) ; Set < V > getConnected ( Object key ) ; Set < V > getNodeSet ( ) ; boolean isConnected ( Object from , Object to ) ; boolean isEmpty ( ) ; void removeEdge ( Object from , Object to ) ; void removeNode ( Object node ) ; void removeNodes ( Collection < ? > nodes ) ; public interface Vertex < V > { Set < V > getConnected ( ) ; V getNode ( ) ; } } package com . asakusafw . utils . graph ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; public class HashGraph < V > implements Graph < V > { private final HashMap < V , HashVertex < V > > entity ; public HashGraph ( ) { this . entity = new HashMap < V , HashVertex < V > > ( ) ; } @ Override public void addEdge ( V from , V to ) { HashVertex < V > vertex = prepare ( from ) ; prepare ( to ) ; vertex . to . add ( to ) ; } @ Override public void addEdges ( V from , Collection < ? extends V > to ) { if ( to == null ) { throw new IllegalArgumentException ( "" ) ; } HashVertex < V > vertex = prepare ( from ) ; for ( V v : to ) { prepare ( v ) ; vertex . to . add ( v ) ; } } @ Override public void addNode ( V node ) { prepare ( node ) ; } @ Override public void clear ( ) { entity . clear ( ) ; } @ Override public boolean contains ( Object node ) { return entity . containsKey ( node ) ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } HashGraph < ? > other = ( HashGraph < ? > ) obj ; if ( ( this . entity . equals ( other . entity ) ) == false ) { return false ; } return true ; } @ Override public Set < V > getConnected ( Object key ) { HashVertex < V > vertex = entity . get ( key ) ; if ( vertex != null ) { return vertex . to ; } return Collections . emptySet ( ) ; } @ Override public Set < V > getNodeSet ( ) { return entity . keySet ( ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + this . entity . hashCode ( ) ; return result ; } @ Override public boolean isConnected ( Object from , Object to ) { HashVertex < V > vertex = entity . get ( from ) ; if ( vertex == null ) { return false ; } return vertex . to . contains ( to ) ; } @ Override public boolean isEmpty ( ) { return entity . isEmpty ( ) ; } @ Override public Iterator < Graph . Vertex < V > > iterator ( ) { return new IteratorWrapper < Vertex < V > > ( entity . values ( ) . iterator ( ) ) ; } @ Override public void removeEdge ( Object from , Object to ) { HashVertex < V > vertex = entity . get ( from ) ; if ( vertex != null ) { vertex . to . remove ( to ) ; } } @ Override public void removeNode ( Object node ) { if ( entity . remove ( node ) == null ) { return ; } for ( HashVertex < V > vertex : entity . values ( ) ) { vertex . to . remove ( node ) ; } } @ Override public void removeNodes ( Collection < ? > nodes ) { if ( nodes == null ) { throw new IllegalArgumentException ( "" ) ; } if ( entity . keySet ( ) . removeAll ( nodes ) == false ) { return ; } for ( HashVertex < V > vertex : entity . values ( ) ) { vertex . to . removeAll ( nodes ) ; } } @ Override public String toString ( ) { return entity . values ( ) . toString ( ) ; } private HashVertex < V > prepare ( V node ) { HashVertex < V > vertex = entity . get ( node ) ; if ( vertex == null ) { vertex = new HashVertex < V > ( node ) ; entity . put ( node , vertex ) ; } return vertex ; } private static class HashVertex < V > implements Vertex < V > { final V from ; final Set < V > to ; public HashVertex ( V node ) { super ( ) ; this . from = node ; this . to = new HashSet < V > ( ) ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } HashVertex < ? > other = ( HashVertex < ? > ) obj ; if ( this . from == null ) { if ( other . from != null ) { return false ; } } else if ( ( this . from . equals ( other . from ) ) == false ) { return false ; } if ( ( this . to . equals ( other . to ) ) == false ) { return false ; } return true ; } @ Override public Set < V > getConnected ( ) { return to ; } @ Override public V getNode ( ) { return from ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( this . from == null ) ? : this . from . hashCode ( ) ) ; result = prime * result + this . to . hashCode ( ) ; return result ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , from , to ) ; } } private static final class IteratorWrapper < V > implements Iterator < V > { private final Iterator < ? extends V > iterator ; public IteratorWrapper ( Iterator < ? extends V > iterator ) { assert iterator != null ; this . iterator = iterator ; } @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public V next ( ) { return iterator . next ( ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } } package com . asakusafw . utils . graph ; package com . asakusafw . utils . java . model . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collections ; import java . util . Date ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import org . junit . Test ; import com . asakusafw . utils . java . model . syntax . ImportDeclaration ; import com . asakusafw . utils . java . model . syntax . ImportKind ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . QualifiedType ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . ImportBuilder . Strategy ; public class ImportBuilderTest { ModelFactory f = Models . getModelFactory ( ) ; @ Test public void primitive ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . toType ( int . class ) , is ( type ( int . class ) ) ) ; assertImported ( importer ) ; } @ Test public void aClass ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . toType ( Date . class ) , is ( type ( Date . class . getSimpleName ( ) ) ) ) ; assertImported ( importer , Date . class ) ; } @ Test public void array ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . toType ( int [ ] . class ) , is ( type ( int [ ] . class ) ) ) ; assertThat ( importer . toType ( Date [ ] . class ) , is ( ( Type ) f . newArrayType ( type ( "" ) ) ) ) ; assertImported ( importer , Date . class ) ; } @ Test public void parameterized ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . resolve ( type ( Map . class , Date . class , Calendar . class ) ) , is ( type ( "" , "" , "" ) ) ) ; assertImported ( importer , Map . class , Calendar . class , Date . class ) ; } @ Test public void qualified ( ) { QualifiedType type = f . newQualifiedType ( type ( List . class , Date . class ) , f . newSimpleName ( "" ) ) ; QualifiedType imported = f . newQualifiedType ( type ( "" , "" ) , f . newSimpleName ( "" ) ) ; ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . resolve ( type ) , is ( ( Type ) imported ) ) ; assertImported ( importer , List . class , Date . class ) ; } @ Test public void javaLang ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . toType ( String . class ) , is ( type ( String . class . getSimpleName ( ) ) ) ) ; assertImported ( importer ) ; } @ Test public void current ( ) { PackageDeclaration pkg = f . newPackageDeclaration ( Models . toName ( f , "" ) ) ; ImportBuilder importer = new ImportBuilder ( f , pkg , Strategy . TOP_LEVEL ) ; assertThat ( importer . resolve ( type ( "" ) ) , is ( type ( "" ) ) ) ; assertImported ( importer ) ; } @ Test public void enclosing ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . toType ( Map . Entry . class ) , is ( type ( "" ) ) ) ; assertImported ( importer , Map . class ) ; } @ Test public void enclosing_just ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . ENCLOSING ) ; assertThat ( importer . toType ( Map . Entry . class ) , is ( type ( "" ) ) ) ; assertImported ( importer , Map . Entry . class ) ; } @ Test public void defaultPackage ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . resolve ( type ( "" ) ) , is ( type ( "" ) ) ) ; assertThat ( importer . resolve ( type ( "" ) ) , is ( type ( "" ) ) ) ; assertImportedNames ( importer ) ; } @ Test public void duplicate ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . resolve ( type ( Date . class ) ) , is ( type ( "" ) ) ) ; assertThat ( importer . resolve ( type ( Date . class ) ) , is ( type ( "" ) ) ) ; assertThat ( importer . resolve ( type ( Date . class ) ) , is ( type ( "" ) ) ) ; assertImported ( importer , Date . class ) ; } @ Test public void conflict ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . resolve ( type ( Date . class ) ) , is ( type ( "" ) ) ) ; assertThat ( importer . resolve ( type ( java . sql . Date . class ) ) , is ( type ( java . sql . Date . class ) ) ) ; assertImported ( importer , Date . class ) ; } @ Test public void conflictInDefaultPackage ( ) { ImportBuilder importer = new ImportBuilder ( f , null , Strategy . TOP_LEVEL ) ; assertThat ( importer . resolve ( type ( "" ) ) , is ( type ( "" ) ) ) ; assertThat ( importer . resolve ( type ( "" ) ) , is ( type ( "" ) ) ) ; assertImported ( importer ) ; } private Type type ( java . lang . reflect . Type type , java . lang . reflect . Type ... arguments ) { Type result = Models . toType ( f , type ) ; if ( arguments . length != ) { List < Type > args = new ArrayList < Type > ( ) ; for ( java . lang . reflect . Type t : arguments ) { args . add ( Models . toType ( f , t ) ) ; } result = f . newParameterizedType ( result , args ) ; } return result ; } private Type type ( String name , String ... arguments ) { Type result = f . newNamedType ( Models . toName ( f , name ) ) ; if ( arguments . length != ) { List < Type > args = new ArrayList < Type > ( ) ; for ( String t : arguments ) { args . add ( f . newNamedType ( Models . toName ( f , t ) ) ) ; } result = f . newParameterizedType ( result , args ) ; } return result ; } private void assertImported ( ImportBuilder importer , Class < ? > ... types ) { String [ ] expect = new String [ types . length ] ; for ( int i = ; i < types . length ; i ++ ) { expect [ i ] = types [ i ] . getName ( ) . replace ( '' , '' ) ; } assertImportedNames ( importer , expect ) ; } private void assertImportedNames ( ImportBuilder importer , String ... types ) { List < ImportDeclaration > decls = importer . toImportDeclarations ( ) ; Set < String > actual = new TreeSet < String > ( ) ; for ( ImportDeclaration d : decls ) { assertThat ( d . getImportKind ( ) , is ( ImportKind . SINGLE_TYPE ) ) ; String name = d . getName ( ) . toNameString ( ) ; assertThat ( actual , not ( hasItem ( name ) ) ) ; actual . add ( name ) ; } Set < String > expect = new TreeSet < String > ( ) ; Collections . addAll ( expect , types ) ; assertThat ( actual , is ( expect ) ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import org . junit . Test ; public class SimpleNameImplTest { @ Test public void camel ( ) { SimpleNameImpl name = new SimpleNameImpl ( ) ; name . setToken ( "" ) ; } @ Test public void singleChar ( ) { SimpleNameImpl name = new SimpleNameImpl ( ) ; name . setToken ( "" ) ; } @ Test public void trailingNumbers ( ) { SimpleNameImpl name = new SimpleNameImpl ( ) ; name . setToken ( "" ) ; } @ Test public void dollar ( ) { SimpleNameImpl name = new SimpleNameImpl ( ) ; name . setToken ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void empty ( ) { SimpleNameImpl name = new SimpleNameImpl ( ) ; name . setToken ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void isNumber ( ) { SimpleNameImpl name = new SimpleNameImpl ( ) ; name . setToken ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void hasInvalid ( ) { SimpleNameImpl name = new SimpleNameImpl ( ) ; name . setToken ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void keyword ( ) { SimpleNameImpl name = new SimpleNameImpl ( ) ; name . setToken ( "" ) ; } } package com . asakusafw . utils . java . internal . model . util ; import java . net . URI ; import java . net . URISyntaxException ; import javax . tools . JavaFileObject ; import javax . tools . SimpleJavaFileObject ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Modifier ; import com . asakusafw . utils . java . model . syntax . ModifierKind ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; public class CompilationUnitJavaFile extends SimpleJavaFileObject { public static final String URI_SCHEME = CompilationUnitJavaFile . class . getName ( ) ; private CompilationUnit unit ; public CompilationUnitJavaFile ( CompilationUnit unit ) { super ( toUri ( unit ) , JavaFileObject . Kind . SOURCE ) ; this . unit = unit ; } @ Override public CharSequence getCharContent ( boolean ignoreEncodingErrors ) { return unit . toString ( ) ; } private static URI toUri ( CompilationUnit unit ) { if ( unit == null ) { throw new IllegalArgumentException ( "" ) ; } String path = toPath ( unit ) ; try { return new URI ( URI_SCHEME , null , "" + path , null ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } } private static String toPath ( CompilationUnit unit ) { assert unit != null ; StringBuilder buf = new StringBuilder ( ) ; PackageDeclaration packageDeclaration = unit . getPackageDeclaration ( ) ; if ( packageDeclaration != null ) { String pkg = packageDeclaration . getName ( ) . toNameString ( ) . replace ( '' , '' ) ; buf . append ( pkg ) ; buf . append ( '' ) ; } TypeDeclaration primaryType = findPrimaryType ( unit ) ; if ( primaryType != null ) { buf . append ( primaryType . getName ( ) . toNameString ( ) ) ; } else { buf . append ( "" ) ; } buf . append ( "" ) ; return buf . toString ( ) ; } private static TypeDeclaration findPrimaryType ( CompilationUnit unit ) { assert unit != null ; TypeDeclaration first = null ; for ( TypeDeclaration decl : unit . getTypeDeclarations ( ) ) { if ( first == null ) { first = decl ; } for ( Attribute attribute : decl . getModifiers ( ) ) { if ( attribute instanceof Modifier ) { Modifier modifier = ( Modifier ) attribute ; if ( modifier . getModifierKind ( ) == ModifierKind . PUBLIC ) { return decl ; } } } } return first ; } } package com . asakusafw . utils . java . internal . model . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . Serializable ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . reflect . Constructor ; import java . lang . reflect . Field ; import java . lang . reflect . GenericArrayType ; import java . lang . reflect . Method ; import java . lang . reflect . TypeVariable ; import java . lang . reflect . WildcardType ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Date ; import java . util . List ; import java . util . RandomAccess ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . junit . After ; import org . junit . Test ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . model . syntax . * ; import com . asakusafw . utils . java . model . util . CommentEmitTrait ; import com . asakusafw . utils . java . model . util . Models ; public class ModelEmitterTest { private ModelFactory f = Models . getModelFactory ( ) ; private PackageDeclaration packageDecl = null ; private List < ImportDeclaration > importDecls = new ArrayList < ImportDeclaration > ( ) ; private VolatileCompiler compiler = new VolatileCompiler ( ) ; @ After public void tearDown ( ) throws Exception { compiler . close ( ) ; } @ Test public void simple ( ) { assertToString ( fromExpr ( "" , f . newLiteral ( "" ) ) , "" , "" ) ; } @ Test public void Literal_String ( ) { assertToString ( fromExpr ( "" , f . newLiteral ( "" ) ) , "" , "" ) ; } @ Test public void Literal_Int ( ) { assertToString ( fromExpr ( "" , f . newLiteral ( "" ) ) , "" , "" ) ; } @ Test public void Literal_Float ( ) { assertToString ( fromExpr ( "" , f . newLiteral ( "" ) ) , "" , "" ) ; } @ Test public void Literal_Char ( ) { assertToString ( fromExpr ( "" , f . newLiteral ( "" ) ) , "" , "" ) ; } @ Test public void Literal_Boolean ( ) { assertToString ( fromExpr ( "" , f . newLiteral ( "" ) ) , "" , "" ) ; } @ Test public void Type_void ( ) { assertType ( f . newBasicType ( BasicTypeKind . VOID ) , void . class ) ; } @ Test public void Type_primitive ( ) { assertType ( f . newBasicType ( BasicTypeKind . INT ) , int . class ) ; } @ Test public void Type_ClassOrInterface ( ) { assertType ( f . newNamedType ( f . newSimpleName ( "" ) ) , Runnable . class ) ; } @ Test public void Type_Array ( ) { assertType ( f . newArrayType ( f . newBasicType ( BasicTypeKind . INT ) ) , int [ ] . class ) ; } @ Test public void Type_variable ( ) { java . lang . reflect . Type type = getType ( f . newNamedType ( f . newSimpleName ( "" ) ) ) ; assertThat ( type , instanceOf ( TypeVariable . class ) ) ; TypeVariable < ? > typeVar = ( TypeVariable < ? > ) type ; assertThat ( typeVar . getName ( ) , is ( "" ) ) ; } @ Test public void Type_parameterized ( ) { java . lang . reflect . Type type = getType ( f . newParameterizedType ( f . newNamedType ( f . newSimpleName ( "" ) ) , Arrays . asList ( new Type [ ] { f . newNamedType ( f . newSimpleName ( "" ) ) } ) ) ) ; assertThat ( type , instanceOf ( java . lang . reflect . ParameterizedType . class ) ) ; java . lang . reflect . ParameterizedType p = ( java . lang . reflect . ParameterizedType ) type ; assertThat ( p . getRawType ( ) , is ( ( java . lang . reflect . Type ) Comparable . class ) ) ; assertThat ( p . getActualTypeArguments ( ) [ ] , is ( ( java . lang . reflect . Type ) String . class ) ) ; } @ Test public void Type_wildcard ( ) { java . lang . reflect . Type type = getType ( f . newParameterizedType ( f . newNamedType ( f . newSimpleName ( "" ) ) , Arrays . asList ( new Type [ ] { f . newWildcard ( ) } ) ) ) ; assertThat ( type , instanceOf ( java . lang . reflect . ParameterizedType . class ) ) ; java . lang . reflect . Type p = ( ( java . lang . reflect . ParameterizedType ) type ) . getActualTypeArguments ( ) [ ] ; assertThat ( p , instanceOf ( WildcardType . class ) ) ; WildcardType w = ( WildcardType ) p ; assertThat ( w . getLowerBounds ( ) . length , is ( ) ) ; assertThat ( w . getUpperBounds ( ) . length , is ( ) ) ; assertThat ( w . getUpperBounds ( ) [ ] , is ( ( java . lang . reflect . Type ) Object . class ) ) ; } @ Test public void Type_wildcard_upperBounded ( ) { java . lang . reflect . Type type = getType ( f . newParameterizedType ( f . newNamedType ( f . newSimpleName ( "" ) ) , Arrays . asList ( new Type [ ] { f . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , f . newNamedType ( f . newSimpleName ( "" ) ) ) } ) ) ) ; assertThat ( type , instanceOf ( java . lang . reflect . ParameterizedType . class ) ) ; java . lang . reflect . Type p = ( ( java . lang . reflect . ParameterizedType ) type ) . getActualTypeArguments ( ) [ ] ; assertThat ( p , instanceOf ( WildcardType . class ) ) ; WildcardType w = ( WildcardType ) p ; assertThat ( w . getLowerBounds ( ) . length , is ( ) ) ; assertThat ( w . getUpperBounds ( ) . length , is ( ) ) ; assertThat ( w . getUpperBounds ( ) [ ] , is ( ( java . lang . reflect . Type ) CharSequence . class ) ) ; } @ Test public void Type_wildcard_lowerBounded ( ) { java . lang . reflect . Type type = getType ( f . newParameterizedType ( f . newNamedType ( f . newSimpleName ( "" ) ) , Arrays . asList ( new Type [ ] { f . newWildcard ( WildcardBoundKind . LOWER_BOUNDED , f . newNamedType ( f . newSimpleName ( "" ) ) ) } ) ) ) ; assertThat ( type , instanceOf ( java . lang . reflect . ParameterizedType . class ) ) ; java . lang . reflect . Type p = ( ( java . lang . reflect . ParameterizedType ) type ) . getActualTypeArguments ( ) [ ] ; assertThat ( p , instanceOf ( WildcardType . class ) ) ; WildcardType w = ( WildcardType ) p ; assertThat ( w . getLowerBounds ( ) . length , is ( ) ) ; assertThat ( w . getLowerBounds ( ) [ ] , is ( ( java . lang . reflect . Type ) CharSequence . class ) ) ; assertThat ( w . getUpperBounds ( ) . length , is ( ) ) ; assertThat ( w . getUpperBounds ( ) [ ] , is ( ( java . lang . reflect . Type ) Object . class ) ) ; } @ Test public void Unary ( ) { assertToString ( fromExpr ( "" , f . newUnaryExpression ( UnaryOperator . NOT , Models . toLiteral ( f , true ) ) ) , "" , "" ) ; } @ Test public void Cast_Basic ( ) { assertToString ( fromExpr ( "" , f . newCastExpression ( f . newBasicType ( BasicTypeKind . INT ) , Models . toLiteral ( f , '' ) ) ) , "" , "" ) ; } @ Test public void Cast_Reference ( ) { assertToString ( fromExpr ( "" , f . newCastExpression ( f . newNamedType ( f . newSimpleName ( "" ) ) , Models . toLiteral ( f , ) ) ) , "" , "" ) ; } @ Test public void Infix ( ) { assertToString ( fromExpr ( "" , f . newInfixExpression ( Models . toLiteral ( f , ) , InfixOperator . PLUS , Models . toLiteral ( f , ) ) ) , "" , "" ) ; } @ Test public void Instanceof ( ) { assertToString ( fromExpr ( "" , f . newInstanceofExpression ( f . newCastExpression ( f . newNamedType ( f . newSimpleName ( "" ) ) , Models . toLiteral ( f , "" ) ) , f . newNamedType ( f . newSimpleName ( "" ) ) ) ) , "" , "" ) ; } @ Test public void Conditional ( ) { assertToString ( fromExpr ( "" , f . newConditionalExpression ( Models . toLiteral ( f , false ) , Models . toLiteral ( f , ) , Models . toLiteral ( f , ) ) ) , "" , "" ) ; } @ Test public void Parenthesize ( ) { assertToString ( fromExpr ( "" , f . newInfixExpression ( Models . toLiteral ( f , ) , InfixOperator . MINUS , f . newParenthesizedExpression ( f . newInfixExpression ( Models . toLiteral ( f , ) , InfixOperator . MINUS , Models . toLiteral ( f , ) ) ) ) ) , "" , "" ) ; } @ Test public void ExpressionNamme ( ) { assertToString ( fromExpr ( "" , Models . toName ( f , "" ) ) , "" , String . valueOf ( Math . PI ) ) ; } @ Test public void FieldAccess ( ) { assertToString ( fromExpr ( "" , f . newFieldAccessExpression ( f . newClassInstanceCreationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newNamedType ( Models . toName ( f , "" ) ) , Arrays . asList ( Models . toLiteral ( f , ) , Models . toLiteral ( f , ) ) , null ) , f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void ArrayCreation_Single ( ) { assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( Models . toName ( f , "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newArrayCreationExpression ( f . newArrayType ( f . newBasicType ( BasicTypeKind . INT ) ) , Arrays . asList ( Models . toLiteral ( f , ) ) , null ) ) ) ) , "" , "" ) ; } @ Test public void ArrayCreation_Multi ( ) { assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( Models . toName ( f , "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newArrayCreationExpression ( f . newArrayType ( f . newArrayType ( f . newBasicType ( BasicTypeKind . INT ) ) ) , Arrays . asList ( Models . toLiteral ( f , ) , Models . toLiteral ( f , ) ) , null ) ) ) ) , "" , "" ) ; } @ Test public void ArrayCreation_MultiPartial ( ) { assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( Models . toName ( f , "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newArrayCreationExpression ( f . newArrayType ( f . newArrayType ( f . newBasicType ( BasicTypeKind . INT ) ) ) , Arrays . asList ( Models . toLiteral ( f , ) ) , null ) ) ) ) , "" , "" ) ; } @ Test public void ArrayInitializer ( ) { assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( Models . toName ( f , "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newArrayCreationExpression ( f . newArrayType ( f . newBasicType ( BasicTypeKind . INT ) ) , Arrays . < Expression > asList ( ) , f . newArrayInitializer ( Arrays . asList ( Models . toLiteral ( f , ) , Models . toLiteral ( f , ) , Models . toLiteral ( f , ) ) ) ) ) ) ) , "" , "" ) ; } @ Test public void ArrayAccess ( ) { assertToString ( fromExpr ( "" , f . newArrayAccessExpression ( f . newParenthesizedExpression ( f . newArrayCreationExpression ( f . newArrayType ( f . newBasicType ( BasicTypeKind . INT ) ) , Arrays . < Expression > asList ( ) , f . newArrayInitializer ( Arrays . asList ( Models . toLiteral ( f , ) , Models . toLiteral ( f , ) , Models . toLiteral ( f , ) ) ) ) ) , Models . toLiteral ( f , ) ) ) , "" , "" ) ; } @ Test public void ClassLiteral ( ) { assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( f . newClassLiteral ( f . newNamedType ( f . newSimpleName ( "" ) ) ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) ) ) , "" , "" ) ; } @ Test public void ClassInstanceCreation ( ) { assertToString ( fromExpr ( "" , f . newClassInstanceCreationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newNamedType ( f . newSimpleName ( "" ) ) , Arrays . asList ( Models . toLiteral ( f , "" ) ) , null ) ) , "" , "" ) ; } @ Test public void ClassInstanceCreation_Anonymous ( ) { assertToString ( fromExpr ( "" , f . newClassInstanceCreationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newNamedType ( f . newSimpleName ( "" ) ) , Arrays . asList ( new Expression [ ] { } ) , f . newClassBody ( Arrays . asList ( new TypeBodyDeclaration [ ] { toString ( f . newReturnStatement ( Models . toLiteral ( f , "" ) ) ) } ) ) ) ) , "" , "" ) ; } @ Test public void Assert ( ) { assertRaise ( fromStmt ( "" , f . newAssertStatement ( Models . toLiteral ( f , false ) , null ) , returnAsString ( Models . toLiteral ( f , "" ) ) ) , "" , AssertionError . class ) ; } @ Test public void Assert_WithMessage ( ) { assertRaise ( fromStmt ( "" , f . newAssertStatement ( Models . toLiteral ( f , false ) , Models . toLiteral ( f , "" ) ) , returnAsString ( Models . toLiteral ( f , "" ) ) ) , "" , AssertionError . class ) ; } @ Test public void LocalVariable ( ) { assertToString ( fromStmt ( "" , f . newLocalVariableDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , f . newBasicType ( BasicTypeKind . INT ) , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( "" ) , , Models . toLiteral ( f , ) ) } ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void LocalVariable_Multiple ( ) { assertToString ( fromStmt ( "" , f . newLocalVariableDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , f . newBasicType ( BasicTypeKind . INT ) , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( "" ) , , Models . toLiteral ( f , ) ) , f . newVariableDeclarator ( f . newSimpleName ( "" ) , , Models . toLiteral ( f , ) ) , f . newVariableDeclarator ( f . newSimpleName ( "" ) , , Models . toLiteral ( f , ) ) } ) ) , returnAsString ( f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . PLUS , f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . TIMES , f . newSimpleName ( "" ) ) ) ) ) , "" , "" ) ; } @ Test public void Assignment ( ) { assertToString ( fromStmt ( "" , f . newLocalVariableDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , f . newBasicType ( BasicTypeKind . INT ) , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( "" ) , , null ) } ) ) , f . newExpressionStatement ( f . newAssignmentExpression ( f . newSimpleName ( "" ) , InfixOperator . ASSIGN , Models . toLiteral ( f , ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void Empty ( ) { assertToString ( fromStmt ( "" , f . newEmptyStatement ( ) , returnAsString ( Models . toLiteral ( f , ) ) ) , "" , "" ) ; } @ Test public void If_true ( ) { assertToString ( fromStmt ( "" , f . newIfStatement ( Models . toLiteral ( f , true ) , returnAsString ( Models . toLiteral ( f , ) ) , null ) , returnAsString ( Models . toLiteral ( f , ) ) ) , "" , "" ) ; } @ Test public void If_false ( ) { assertToString ( fromStmt ( "" , f . newIfStatement ( Models . toLiteral ( f , false ) , returnAsString ( Models . toLiteral ( f , ) ) , null ) , returnAsString ( Models . toLiteral ( f , ) ) ) , "" , "" ) ; } @ Test public void If_else ( ) { assertToString ( fromStmt ( "" , f . newIfStatement ( Models . toLiteral ( f , false ) , returnAsString ( Models . toLiteral ( f , ) ) , returnAsString ( Models . toLiteral ( f , ) ) ) ) , "" , "" ) ; } @ Test public void If_elseIf ( ) { assertToString ( fromStmt ( "" , f . newIfStatement ( Models . toLiteral ( f , false ) , returnAsString ( Models . toLiteral ( f , ) ) , f . newIfStatement ( Models . toLiteral ( f , false ) , returnAsString ( Models . toLiteral ( f , ) ) , returnAsString ( Models . toLiteral ( f , ) ) ) ) ) , "" , "" ) ; } @ Test public void While ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , var ( f . newBasicType ( BasicTypeKind . INT ) , "" , Models . toLiteral ( f , ) ) , f . newWhileStatement ( f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . GREATER_EQUALS , Models . toLiteral ( f , ) ) , f . newBlock ( Arrays . asList ( new Statement [ ] { append ( "" , f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . DECREMENT ) ) , } ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void For ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , f . newForStatement ( var ( f . newBasicType ( BasicTypeKind . INT ) , "" , Models . toLiteral ( f , ) ) , f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . LESS , Models . toLiteral ( f , ) ) , f . newStatementExpressionList ( Arrays . asList ( f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . INCREMENT ) ) ) , append ( "" , f . newSimpleName ( "" ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void For_noVar ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , var ( f . newBasicType ( BasicTypeKind . INT ) , "" , null ) , f . newForStatement ( f . newStatementExpressionList ( Arrays . asList ( f . newAssignmentExpression ( f . newSimpleName ( "" ) , InfixOperator . ASSIGN , Models . toLiteral ( f , ) ) ) ) , f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . GREATER , Models . toLiteral ( f , ) ) , f . newStatementExpressionList ( Arrays . asList ( f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . DECREMENT ) ) ) , append ( "" , f . newSimpleName ( "" ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void ForEach ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , f . newEnhancedForStatement ( f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , f . newBasicType ( BasicTypeKind . INT ) , false , f . newSimpleName ( "" ) , ) , f . newArrayCreationExpression ( f . newArrayType ( f . newBasicType ( BasicTypeKind . INT ) ) , Arrays . asList ( new Expression [ ] { } ) , f . newArrayInitializer ( Arrays . asList ( new Expression [ ] { Models . toLiteral ( f , ) , Models . toLiteral ( f , ) , Models . toLiteral ( f , ) , } ) ) ) , append ( "" , f . newSimpleName ( "" ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void DoWhile ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , var ( f . newBasicType ( BasicTypeKind . INT ) , "" , Models . toLiteral ( f , ) ) , f . newDoStatement ( f . newBlock ( Arrays . asList ( new Statement [ ] { append ( "" , f . newSimpleName ( "" ) ) , } ) ) , f . newInfixExpression ( f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . DECREMENT ) , InfixOperator . GREATER_EQUALS , Models . toLiteral ( f , ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void Break ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , var ( f . newBasicType ( BasicTypeKind . INT ) , "" , Models . toLiteral ( f , ) ) , f . newWhileStatement ( f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . GREATER_EQUALS , Models . toLiteral ( f , ) ) , f . newBlock ( Arrays . asList ( new Statement [ ] { append ( "" , f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . DECREMENT ) ) , f . newBreakStatement ( null ) , } ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void Break_Labeled ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , var ( f . newBasicType ( BasicTypeKind . INT ) , "" , Models . toLiteral ( f , ) ) , f . newLabeledStatement ( f . newSimpleName ( "" ) , f . newWhileStatement ( Models . toLiteral ( f , true ) , f . newWhileStatement ( f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . GREATER_EQUALS , Models . toLiteral ( f , ) ) , f . newBlock ( Arrays . asList ( new Statement [ ] { append ( "" , f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . DECREMENT ) ) , f . newBreakStatement ( f . newSimpleName ( "" ) ) , } ) ) ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void Continue ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , f . newForStatement ( var ( f . newBasicType ( BasicTypeKind . INT ) , "" , Models . toLiteral ( f , ) ) , f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . LESS , Models . toLiteral ( f , ) ) , f . newStatementExpressionList ( Arrays . asList ( f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . INCREMENT ) ) ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newIfStatement ( f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . GREATER , Models . toLiteral ( f , ) ) , f . newContinueStatement ( null ) , null ) , append ( "" , f . newSimpleName ( "" ) ) } ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void Continue_Labeled ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , f . newLabeledStatement ( f . newSimpleName ( "" ) , f . newForStatement ( var ( f . newBasicType ( BasicTypeKind . INT ) , "" , Models . toLiteral ( f , ) ) , f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . LESS , Models . toLiteral ( f , ) ) , f . newStatementExpressionList ( Arrays . asList ( f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . INCREMENT ) ) ) , f . newForStatement ( var ( f . newBasicType ( BasicTypeKind . INT ) , "" , Models . toLiteral ( f , ) ) , f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . LESS , Models . toLiteral ( f , ) ) , f . newStatementExpressionList ( Arrays . asList ( f . newPostfixExpression ( f . newSimpleName ( "" ) , PostfixOperator . INCREMENT ) ) ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newIfStatement ( f . newInfixExpression ( f . newSimpleName ( "" ) , InfixOperator . GREATER , Models . toLiteral ( f , ) ) , f . newContinueStatement ( f . newSimpleName ( "" ) ) , null ) , append ( "" , f . newSimpleName ( "" ) ) , append ( "" , f . newSimpleName ( "" ) ) , } ) ) ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void Switch_Case ( ) { assertToString ( fromStmt ( "" , f . newSwitchStatement ( Models . toLiteral ( f , ) , Arrays . asList ( new Statement [ ] { f . newSwitchCaseLabel ( Models . toLiteral ( f , ) ) , returnAsString ( Models . toLiteral ( f , "" ) ) , f . newSwitchCaseLabel ( Models . toLiteral ( f , ) ) , returnAsString ( Models . toLiteral ( f , "" ) ) , f . newSwitchDefaultLabel ( ) , returnAsString ( Models . toLiteral ( f , "" ) ) , } ) ) ) , "" , "" ) ; } @ Test public void Switch_Default ( ) { assertToString ( fromStmt ( "" , f . newSwitchStatement ( Models . toLiteral ( f , ) , Arrays . asList ( new Statement [ ] { f . newSwitchCaseLabel ( Models . toLiteral ( f , ) ) , returnAsString ( Models . toLiteral ( f , "" ) ) , f . newSwitchCaseLabel ( Models . toLiteral ( f , ) ) , returnAsString ( Models . toLiteral ( f , "" ) ) , f . newSwitchDefaultLabel ( ) , returnAsString ( Models . toLiteral ( f , "" ) ) , } ) ) ) , "" , "" ) ; } @ Test public void Throw ( ) { assertRaise ( fromStmt ( "" , f . newThrowStatement ( f . newClassInstanceCreationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newNamedType ( Models . toName ( f , "" ) ) , Arrays . asList ( new Expression [ ] { } ) , null ) ) ) , "" , UnsupportedOperationException . class ) ; } @ Test public void Try_Catch ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , f . newTryStatement ( f . newBlock ( Arrays . asList ( new Statement [ ] { f . newThrowStatement ( f . newClassInstanceCreationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newNamedType ( Models . toName ( f , "" ) ) , Arrays . asList ( new Expression [ ] { Models . toLiteral ( f , "" ) } ) , null ) ) } ) ) , Arrays . asList ( new CatchClause [ ] { f . newCatchClause ( f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , f . newNamedType ( f . newSimpleName ( "" ) ) , false , f . newSimpleName ( "" ) , ) , f . newBlock ( Arrays . asList ( new Statement [ ] { } ) ) ) , f . newCatchClause ( f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , f . newNamedType ( f . newSimpleName ( "" ) ) , false , f . newSimpleName ( "" ) , ) , f . newBlock ( Arrays . asList ( new Statement [ ] { append ( "" , f . newMethodInvocationExpression ( f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) ) ) } ) ) ) } ) , null ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void Try_Finally ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , f . newTryStatement ( f . newBlock ( Arrays . asList ( new Statement [ ] { f . newThrowStatement ( f . newClassInstanceCreationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newNamedType ( Models . toName ( f , "" ) ) , Arrays . asList ( new Expression [ ] { Models . toLiteral ( f , "" ) } ) , null ) ) } ) ) , Arrays . asList ( new CatchClause [ ] { f . newCatchClause ( f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , f . newNamedType ( f . newSimpleName ( "" ) ) , false , f . newSimpleName ( "" ) , ) , f . newBlock ( Arrays . asList ( new Statement [ ] { append ( "" , f . newMethodInvocationExpression ( f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) ) ) } ) ) ) } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { append ( "" , Models . toLiteral ( f , "" ) ) } ) ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void Synchronized ( ) { assertToString ( fromStmt ( "" , newStringBuilder ( "" ) , f . newSynchronizedStatement ( f . newThis ( ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newExpressionStatement ( f . newMethodInvocationExpression ( f . newThis ( ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) ) ) , } ) ) ) , append ( "" , Models . toLiteral ( f , "" ) ) , returnAsString ( f . newSimpleName ( "" ) ) ) , "" , "" ) ; } @ Test public void ClassDeclaration ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; assertThat ( klass . getAnnotations ( ) . length , is ( ) ) ; assertThat ( klass . getName ( ) , equalTo ( "" ) ) ; assertThat ( klass . getTypeParameters ( ) . length , is ( ) ) ; assertThat ( klass . getSuperclass ( ) , is ( ( Object ) Object . class ) ) ; assertThat ( klass . getInterfaces ( ) . length , is ( ) ) ; } @ Test public void ClassDeclaration_modifiers ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) , f . newModifier ( ModifierKind . ABSTRACT ) , } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; assertThat ( java . lang . reflect . Modifier . isPublic ( klass . getModifiers ( ) ) , is ( true ) ) ; assertThat ( java . lang . reflect . Modifier . isAbstract ( klass . getModifiers ( ) ) , is ( true ) ) ; } @ Test public void ClassDeclaration_markerAnnotation ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newMarkerAnnotation ( ( NamedType ) Models . toType ( f , Deprecated . class ) ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; assertThat ( klass . getAnnotation ( Deprecated . class ) , not ( nullValue ( ) ) ) ; } @ Test public void ClassDeclaration_singleElementAnnotation ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newSingleElementAnnotation ( f . newNamedType ( f . newSimpleName ( "" ) ) , f . newArrayInitializer ( Arrays . asList ( new Expression [ ] { Models . toLiteral ( f , "" ) , Models . toLiteral ( f , "" ) , } ) ) ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) , createAnnotation ( "" ) ) ; String [ ] value = ( String [ ] ) getAnnotationValue ( klass , "" , "" ) ; assertThat ( value . length , is ( ) ) ; assertThat ( value [ ] , is ( "" ) ) ; assertThat ( value [ ] , is ( "" ) ) ; Integer option = ( Integer ) getAnnotationValue ( klass , "" , "" ) ; assertThat ( option , is ( ) ) ; } @ Test public void ClassDeclaration_normalAnnotation ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newNormalAnnotation ( f . newNamedType ( f . newSimpleName ( "" ) ) , Arrays . asList ( new AnnotationElement [ ] { f . newAnnotationElement ( f . newSimpleName ( "" ) , Models . toLiteral ( f , "" ) ) , f . newAnnotationElement ( f . newSimpleName ( "" ) , Models . toLiteral ( f , ) ) , } ) ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) , createAnnotation ( "" ) ) ; String [ ] value = ( String [ ] ) getAnnotationValue ( klass , "" , "" ) ; assertThat ( value . length , is ( ) ) ; assertThat ( value [ ] , is ( "" ) ) ; Integer option = ( Integer ) getAnnotationValue ( klass , "" , "" ) ; assertThat ( option , is ( ) ) ; } @ Test public void ClassDeclaration_typeParameter ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { f . newTypeParameterDeclaration ( f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { } ) ) } ) , null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; TypeVariable < ? > [ ] tps = klass . getTypeParameters ( ) ; assertThat ( tps . length , is ( ) ) ; assertThat ( tps [ ] . getName ( ) , is ( "" ) ) ; java . lang . reflect . Type [ ] bounds = tps [ ] . getBounds ( ) ; if ( bounds . length == ) { assertThat ( bounds [ ] , is ( ( Object ) Object . class ) ) ; } } @ Test public void ClassDeclaration_boundedTypeParameter ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { f . newTypeParameterDeclaration ( f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { Models . toType ( f , CharSequence . class ) } ) ) } ) , null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; TypeVariable < ? > [ ] tps = klass . getTypeParameters ( ) ; assertThat ( tps . length , is ( ) ) ; assertThat ( tps [ ] . getName ( ) , is ( "" ) ) ; java . lang . reflect . Type [ ] bounds = tps [ ] . getBounds ( ) ; assertThat ( bounds . length , is ( ) ) ; assertThat ( bounds [ ] , is ( ( Object ) CharSequence . class ) ) ; } @ Test public void ClassDeclaration_superClass ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , Models . toType ( f , Date . class ) , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; assertThat ( klass . getSuperclass ( ) , is ( ( Object ) Date . class ) ) ; } @ Test public void ClassDeclaration_superInterfaces ( ) { Class < ? > klass = getTypeDeclaration ( f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . ABSTRACT ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , null , Arrays . asList ( new Type [ ] { Models . toType ( f , Serializable . class ) , Models . toType ( f , RandomAccess . class ) , } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; Class < ? > [ ] interfaces = klass . getInterfaces ( ) ; assertThat ( interfaces . length , is ( ) ) ; assertThat ( interfaces , hasItemInArray ( ( Object ) Serializable . class ) ) ; assertThat ( interfaces , hasItemInArray ( ( Object ) RandomAccess . class ) ) ; } @ Test public void InterfaceDeclaration ( ) { Class < ? > klass = getTypeDeclaration ( f . newInterfaceDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new TypeParameterDeclaration [ ] { f . newTypeParameterDeclaration ( f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { } ) ) } ) , Arrays . asList ( new Type [ ] { Models . toType ( f , Serializable . class ) , Models . toType ( f , RandomAccess . class ) , } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; assertThat ( klass . isInterface ( ) , is ( true ) ) ; assertThat ( klass . getName ( ) , equalTo ( "" ) ) ; TypeVariable < ? > [ ] tps = klass . getTypeParameters ( ) ; assertThat ( tps . length , is ( ) ) ; assertThat ( tps [ ] . getName ( ) , is ( "" ) ) ; Class < ? > [ ] interfaces = klass . getInterfaces ( ) ; assertThat ( interfaces . length , is ( ) ) ; assertThat ( interfaces , hasItemInArray ( ( Object ) Serializable . class ) ) ; assertThat ( interfaces , hasItemInArray ( ( Object ) RandomAccess . class ) ) ; } @ Test public void EnumDeclaration ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( f . newEnumDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { Models . toType ( f , RandomAccess . class ) , } ) , Arrays . asList ( new EnumConstantDeclaration [ ] { f . newEnumConstantDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) , null ) , f . newEnumConstantDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) , null ) , } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { f . newMethodDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , Models . toType ( f , void . class ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { } ) , , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { } ) ) ) } ) ) ) ; assertThat ( klass . isEnum ( ) , is ( true ) ) ; assertThat ( klass . getName ( ) , equalTo ( "" ) ) ; Object [ ] constants = klass . getEnumConstants ( ) ; assertThat ( constants . length , is ( ) ) ; assertThat ( ( ( Enum < ? > ) constants [ ] ) . name ( ) , is ( "" ) ) ; assertThat ( ( ( Enum < ? > ) constants [ ] ) . name ( ) , is ( "" ) ) ; klass . getDeclaredMethod ( "" ) ; Class < ? > [ ] interfaces = klass . getInterfaces ( ) ; assertThat ( interfaces . length , is ( ) ) ; assertThat ( interfaces , hasItemInArray ( ( Object ) RandomAccess . class ) ) ; } @ Test public void FieldDeclaration ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newFieldDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Models . toType ( f , int . class ) , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( "" ) , , null ) , f . newVariableDeclarator ( f . newSimpleName ( "" ) , , f . newArrayInitializer ( Arrays . asList ( new Expression [ ] { Models . toLiteral ( f , ) } ) ) ) , } ) ) ) ) ; Object obj = create ( klass ) ; Field a = klass . getDeclaredField ( "" ) ; assertThat ( a . get ( obj ) , is ( ( Object ) ) ) ; Field b = klass . getDeclaredField ( "" ) ; assertThat ( b . get ( obj ) , is ( ( Object ) new int [ ] { } ) ) ; } @ Test public void InitializerDeclaration ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newFieldDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) , f . newModifier ( ModifierKind . STATIC ) , } ) , Models . toType ( f , int . class ) , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( "" ) , , null ) , } ) ) , f . newInitializerDeclaration ( null , Arrays . asList ( new Modifier [ ] { f . newModifier ( ModifierKind . STATIC ) } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newExpressionStatement ( f . newAssignmentExpression ( f . newSimpleName ( "" ) , InfixOperator . ASSIGN , Models . toLiteral ( f , ) ) ) } ) ) ) ) ) ; Class . forName ( klass . getName ( ) , true , klass . getClassLoader ( ) ) ; Field a = klass . getDeclaredField ( "" ) ; assertThat ( a . get ( null ) , is ( ( Object ) ) ) ; } @ Test public void ConstructorDeclaration ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newFieldDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) , } ) , Models . toType ( f , int . class ) , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( "" ) , , null ) , } ) ) , f . newConstructorDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { } ) , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newExpressionStatement ( f . newAssignmentExpression ( f . newSimpleName ( "" ) , InfixOperator . ASSIGN , Models . toLiteral ( f , ) ) ) } ) ) ) ) ) ; Object obj = create ( klass ) ; Field a = klass . getDeclaredField ( "" ) ; assertThat ( a . get ( obj ) , is ( ( Object ) ) ) ; } @ Test public void ConstructorDeclaration_delegate ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newFieldDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) , } ) , Models . toType ( f , int . class ) , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( "" ) , , null ) , } ) ) , f . newConstructorDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { } ) , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newAlternateConstructorInvocation ( Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new Expression [ ] { Models . toLiteral ( f , ) , } ) ) , f . newExpressionStatement ( f . newAssignmentExpression ( f . newSimpleName ( "" ) , InfixOperator . PLUS , Models . toLiteral ( f , ) ) ) } ) ) ) , f . newConstructorDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PRIVATE ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , Models . toType ( f , int . class ) , false , f . newSimpleName ( "" ) , ) } ) , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newSuperConstructorInvocation ( null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new Expression [ ] { } ) ) , f . newExpressionStatement ( f . newAssignmentExpression ( f . newSimpleName ( "" ) , InfixOperator . ASSIGN , f . newSimpleName ( "" ) ) ) } ) ) ) ) ) ; Object obj = create ( klass ) ; Field a = klass . getDeclaredField ( "" ) ; assertThat ( a . get ( obj ) , is ( ( Object ) ) ) ; } @ Test public void ConstructorDeclaration_throws ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newConstructorDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { } ) , Arrays . asList ( new Type [ ] { Models . toType ( f , Exception . class ) } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newThrowStatement ( f . newClassInstanceCreationExpression ( null , Arrays . asList ( new Type [ ] { } ) , Models . toType ( f , IOException . class ) , Arrays . asList ( new Expression [ ] { } ) , null ) ) } ) ) ) ) ) ; Constructor < ? > ctor = klass . getDeclaredConstructor ( ) ; assertThat ( ctor . getExceptionTypes ( ) , is ( ( Object ) new Class < ? > [ ] { Exception . class } ) ) ; try { klass . newInstance ( ) ; } catch ( Exception e ) { assertThat ( e , instanceOf ( IOException . class ) ) ; } } @ Test public void MethodDeclaration ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newMethodDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , Models . toType ( f , String . class ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { } ) , , Arrays . asList ( new Type [ ] { Models . toType ( f , Exception . class ) } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newReturnStatement ( Models . toLiteral ( f , "" ) ) } ) ) ) ) ) ; Object obj = create ( klass ) ; Method method = klass . getDeclaredMethod ( "" ) ; assertThat ( method . invoke ( obj ) , is ( ( Object ) "" ) ) ; } @ Test public void MethodDeclaration_parameter ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newMethodDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , Models . toType ( f , String . class ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , Models . toType ( f , String . class ) , false , f . newSimpleName ( "" ) , ) } ) , , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newReturnStatement ( f . newSimpleName ( "" ) ) } ) ) ) ) ) ; Object obj = create ( klass ) ; Method method = klass . getDeclaredMethod ( "" , String . class ) ; assertThat ( method . invoke ( obj , "" ) , is ( ( Object ) "" ) ) ; } @ Test public void MethodDeclaration_varargs ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newMethodDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , Models . toType ( f , String [ ] . class ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , Models . toType ( f , String . class ) , true , f . newSimpleName ( "" ) , ) } ) , , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newReturnStatement ( f . newSimpleName ( "" ) ) } ) ) ) ) ) ; Object obj = create ( klass ) ; Method method = klass . getDeclaredMethod ( "" , String [ ] . class ) ; assertThat ( method . isVarArgs ( ) , is ( true ) ) ; assertThat ( method . invoke ( obj , ( Object ) new String [ ] { "" , "" , "" } ) , is ( ( Object ) new String [ ] { "" , "" , "" } ) ) ; } @ Test public void MethodDeclaration_extraDims ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( klass ( "" , f . newMethodDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , Models . toType ( f , String . class ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , Models . toType ( f , String . class ) , false , f . newSimpleName ( "" ) , ) } ) , , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newReturnStatement ( f . newSimpleName ( "" ) ) } ) ) ) ) ) ; Object obj = create ( klass ) ; Method method = klass . getDeclaredMethod ( "" , String [ ] . class ) ; assertThat ( method . invoke ( obj , ( Object ) new String [ ] { "" , "" , "" } ) , is ( ( Object ) new String [ ] { "" , "" , "" } ) ) ; } @ Test public void EnumConstantDeclaration_arguments ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( f . newEnumDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new EnumConstantDeclaration [ ] { f . newEnumConstantDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { Models . toLiteral ( f , ) , Models . toLiteral ( f , "" ) , } ) , null ) , } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { f . newFieldDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) , } ) , Models . toType ( f , Object [ ] . class ) , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( "" ) , , null ) , } ) ) , f . newConstructorDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PRIVATE ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , Models . toType ( f , Object . class ) , true , f . newSimpleName ( "" ) , ) } ) , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( new Statement [ ] { f . newExpressionStatement ( f . newAssignmentExpression ( f . newSimpleName ( "" ) , InfixOperator . ASSIGN , f . newSimpleName ( "" ) ) ) , } ) ) ) } ) ) ) ; @ SuppressWarnings ( "" ) Enum < ? > constant = Enum . valueOf ( klass . asSubclass ( Enum . class ) , "" ) ; Field field = klass . getDeclaredField ( "" ) ; assertThat ( field . get ( constant ) , is ( ( Object ) new Object [ ] { , "" } ) ) ; } @ Test public void EnumConstantDeclaration_body ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( f . newEnumDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new EnumConstantDeclaration [ ] { f . newEnumConstantDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) , f . newClassBody ( Arrays . asList ( new TypeBodyDeclaration [ ] { toString ( returnAsString ( Models . toLiteral ( f , "" ) ) ) } ) ) ) , } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; @ SuppressWarnings ( "" ) Enum < ? > constant = Enum . valueOf ( klass . asSubclass ( Enum . class ) , "" ) ; assertThat ( constant . toString ( ) , is ( "" ) ) ; } @ Test public void Super ( ) throws Exception { Class < ? > klass = getTypeDeclaration ( f . newEnumDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( new EnumConstantDeclaration [ ] { f . newEnumConstantDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) , f . newClassBody ( Arrays . asList ( new TypeBodyDeclaration [ ] { toString ( returnAsString ( f . newMethodInvocationExpression ( f . newSuper ( null ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( new Expression [ ] { } ) ) ) ) } ) ) ) , } ) , Arrays . asList ( new TypeBodyDeclaration [ ] { } ) ) ) ; @ SuppressWarnings ( "" ) Enum < ? > constant = Enum . valueOf ( klass . asSubclass ( Enum . class ) , "" ) ; assertThat ( constant . toString ( ) , is ( "" ) ) ; } @ Test public void PackageDeclaration ( ) { packageDecl = f . newPackageDeclaration ( null , Arrays . asList ( new Annotation [ ] { } ) , Models . toName ( f , "" ) ) ; assertToString ( fromExpr ( "" , Models . toLiteral ( f , "" ) ) , "" , "" ) ; } @ Test public void ImportDeclaration_type ( ) { importDecls . add ( f . newImportDeclaration ( ImportKind . SINGLE_TYPE , Models . toName ( f , "" ) ) ) ; assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( Models . toName ( f , "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( Models . toLiteral ( f , "" ) ) ) ) , "" , "" ) ; } @ Test public void ImportDeclaration_onDemand ( ) { importDecls . add ( f . newImportDeclaration ( ImportKind . TYPE_ON_DEMAND , Models . toName ( f , "" ) ) ) ; assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( Models . toName ( f , "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( Models . toLiteral ( f , "" ) ) ) ) , "" , "" ) ; } @ Test public void ImportDeclaration_singleStatic ( ) { importDecls . add ( f . newImportDeclaration ( ImportKind . SINGLE_STATIC , Models . toName ( f , "" ) ) ) ; assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( Models . toLiteral ( f , "" ) ) ) ) , "" , "" ) ; } @ Test public void ImportDeclaration_staticOnDemand ( ) { importDecls . add ( f . newImportDeclaration ( ImportKind . STATIC_ON_DEMAND , Models . toName ( f , "" ) ) ) ; assertToString ( fromExpr ( "" , f . newMethodInvocationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( Models . toLiteral ( f , "" ) ) ) ) , "" , "" ) ; } @ Test public void autoParenthesize_infixLeft ( ) { assertToString ( fromExpr ( "" , f . newInfixExpression ( f . newInfixExpression ( Models . toLiteral ( f , ) , InfixOperator . MINUS , Models . toLiteral ( f , ) ) , InfixOperator . TIMES , Models . toLiteral ( f , ) ) ) , "" , "" ) ; } @ Test public void autoParenthesize_infixRight ( ) { assertToString ( fromExpr ( "" , f . newInfixExpression ( Models . toLiteral ( f , ) , InfixOperator . MINUS , f . newInfixExpression ( Models . toLiteral ( f , ) , InfixOperator . MINUS , Models . toLiteral ( f , ) ) ) ) , "" , "" ) ; } private LocalVariableDeclaration var ( Type type , String name , Expression init ) { return f . newLocalVariableDeclaration ( Arrays . asList ( new Attribute [ ] { } ) , type , Arrays . asList ( new VariableDeclarator [ ] { f . newVariableDeclarator ( f . newSimpleName ( name ) , , init ) } ) ) ; } private Statement newStringBuilder ( String name ) { return var ( f . newNamedType ( f . newSimpleName ( "" ) ) , name , f . newClassInstanceCreationExpression ( null , Arrays . asList ( new Type [ ] { } ) , f . newNamedType ( f . newSimpleName ( "" ) ) , Arrays . asList ( new Expression [ ] { } ) , null ) ) ; } private Statement append ( String name , Expression value ) { return f . newExpressionStatement ( f . newMethodInvocationExpression ( f . newSimpleName ( name ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( value ) ) ) ; } private CompilationUnit unit ( TypeDeclaration ... types ) { return f . newCompilationUnit ( packageDecl , importDecls , Arrays . asList ( types ) , Arrays . asList ( new Comment [ ] { } ) ) ; } private ClassDeclaration klass ( String name , TypeBodyDeclaration ... elems ) { return f . newClassDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , f . newSimpleName ( name ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , null , Arrays . asList ( new Type [ ] { } ) , Arrays . asList ( elems ) ) ; } private MethodDeclaration toString ( Statement ... statements ) { return f . newMethodDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { } ) , f . newNamedType ( Models . toName ( f , "" ) ) , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { } ) , , Arrays . asList ( new Type [ ] { } ) , f . newBlock ( Arrays . asList ( statements ) ) ) ; } private CompilationUnit fromExpr ( String name , Expression expr ) { return unit ( klass ( name , toString ( returnAsString ( expr ) ) ) ) ; } private ReturnStatement returnAsString ( Expression expr ) { return f . newReturnStatement ( f . newMethodInvocationExpression ( Models . toName ( f , "" ) , Arrays . asList ( new Type [ ] { } ) , f . newSimpleName ( "" ) , Arrays . asList ( expr ) ) ) ; } private CompilationUnit fromStmt ( String name , Statement ... stmts ) { return unit ( klass ( name , toString ( stmts ) ) ) ; } private void assertToString ( CompilationUnit unit , String name , String actual ) { Class < ? > klass = compile ( unit , name ) ; Object object = create ( klass ) ; assertThat ( object . toString ( ) , is ( actual ) ) ; } private void assertRaise ( CompilationUnit unit , String name , Class < ? > exception ) { Class < ? > klass = compile ( unit , name ) ; Object object = create ( klass ) ; try { object . toString ( ) ; } catch ( Throwable t ) { assertThat ( t , instanceOf ( exception ) ) ; } } private AnnotationDeclaration createAnnotation ( String name ) { return f . newAnnotationDeclaration ( null , Arrays . asList ( new Annotation [ ] { f . newSingleElementAnnotation ( ( NamedType ) Models . toType ( f , Retention . class ) , Models . toName ( f , RetentionPolicy . RUNTIME ) ) } ) , f . newSimpleName ( name ) , Arrays . asList ( new TypeBodyDeclaration [ ] { f . newAnnotationElementDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , Models . toType ( f , String [ ] . class ) , f . newSimpleName ( "" ) , null ) , f . newAnnotationElementDeclaration ( null , Arrays . asList ( new Attribute [ ] { } ) , Models . toType ( f , int . class ) , f . newSimpleName ( "" ) , Models . toLiteral ( f , ) ) , } ) ) ; } private Object getAnnotationValue ( Class < ? > klass , String annotationTypeName , String annotationElementName ) { for ( java . lang . annotation . Annotation a : klass . getDeclaredAnnotations ( ) ) { Class < ? > annotationType = a . annotationType ( ) ; if ( annotationType . getName ( ) . equals ( annotationTypeName ) ) { try { Method element = annotationType . getDeclaredMethod ( annotationElementName ) ; element . setAccessible ( true ) ; return element . invoke ( a ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } throw new AssertionError ( klass ) ; } private void assertType ( Type type , java . lang . reflect . Type expect ) { assertThat ( getType ( type ) , is ( expect ) ) ; } private Class < ? > getTypeDeclaration ( TypeDeclaration ... decls ) { CompilationUnit unit = unit ( decls ) ; Class < ? > klass = compile ( unit , decls [ ] . getName ( ) . getToken ( ) ) ; return klass ; } private java . lang . reflect . Type getType ( Type type ) { CompilationUnit unit = unit ( klass ( "" , f . newMethodDeclaration ( null , Arrays . asList ( new Attribute [ ] { f . newModifier ( ModifierKind . PUBLIC ) , f . newModifier ( ModifierKind . NATIVE ) , } ) , Arrays . asList ( new TypeParameterDeclaration [ ] { f . newTypeParameterDeclaration ( f . newSimpleName ( "" ) , Arrays . asList ( new Type [ ] { } ) ) } ) , type , f . newSimpleName ( "" ) , Arrays . asList ( new FormalParameterDeclaration [ ] { } ) , , Arrays . asList ( new Type [ ] { } ) , null ) ) ) ; Class < ? > klass = compile ( unit , "" ) ; try { Method method = klass . getDeclaredMethod ( "" ) ; java . lang . reflect . Type result = method . getGenericReturnType ( ) ; if ( result instanceof GenericArrayType ) { GenericArrayType array = ( GenericArrayType ) result ; if ( array . getGenericComponentType ( ) instanceof Class < ? > ) { return method . getReturnType ( ) ; } return method . getReturnType ( ) ; } return result ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Class < ? > compile ( CompilationUnit unit , String name ) { List < String > lines = new ArrayList < String > ( ) ; StackTraceElement [ ] elements = Thread . currentThread ( ) . getStackTrace ( ) ; for ( int i = ; i < elements . length ; i ++ ) { if ( getClass ( ) . getName ( ) . equals ( elements [ i ] . getClassName ( ) ) == false ) { break ; } lines . add ( elements [ i ] . toString ( ) ) ; } unit . putModelTrait ( CommentEmitTrait . class , new CommentEmitTrait ( lines ) ) ; System . out . println ( unit ) ; compiler . addSource ( new CompilationUnitJavaFile ( unit ) ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; if ( diagnostics . isEmpty ( ) == false ) { throw new AssertionError ( diagnostics + "" + unit ) ; } try { return compiler . getClassLoader ( ) . loadClass ( name ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } } @ SuppressWarnings ( "" ) private < T > T create ( Class < ? > target , Object ... args ) { Class < ? > [ ] argTypes = new Class < ? > [ args . length ] ; for ( int i = ; i < args . length ; i ++ ) { argTypes [ i ] = args [ i ] . getClass ( ) ; } try { return ( T ) target . getConstructor ( argTypes ) . newInstance ( args ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . utils . java . model . syntax ; public interface ExpressionStatement extends Statement { Expression getExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface ConstructorInvocation extends Statement , Invocation { List < ? extends Type > getTypeArguments ( ) ; List < ? extends Expression > getArguments ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface EnhancedForStatement extends Statement { FormalParameterDeclaration getParameter ( ) ; Expression getExpression ( ) ; Statement getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface Statement extends Model { } package com . asakusafw . utils . java . model . syntax ; public interface AssignmentExpression extends Expression { Expression getLeftHandSide ( ) ; InfixOperator getOperator ( ) ; Expression getRightHandSide ( ) ; } package com . asakusafw . utils . java . model . syntax ; public enum ImportKind { SINGLE_TYPE ( Target . TYPE , Range . SINGLE ) , TYPE_ON_DEMAND ( Target . TYPE , Range . ON_DEMAND ) , SINGLE_STATIC ( Target . MEMBER , Range . SINGLE ) , STATIC_ON_DEMAND ( Target . MEMBER , Range . ON_DEMAND ) , ; private Target target ; private Range range ; private ImportKind ( Target target , Range range ) { assert target != null ; assert range != null ; this . target = target ; this . range = range ; } public Target getTarget ( ) { return target ; } public Range getRange ( ) { return range ; } public static ImportKind valueOf ( Target target , Range range ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( range == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == Target . TYPE ) { if ( range == Range . SINGLE ) { return SINGLE_TYPE ; } else { return TYPE_ON_DEMAND ; } } else { if ( range == Range . SINGLE ) { return SINGLE_STATIC ; } else { return STATIC_ON_DEMAND ; } } } public enum Target { TYPE , MEMBER , } public enum Range { SINGLE , ON_DEMAND , } } package com . asakusafw . utils . java . model . syntax ; public interface LocalClassDeclaration extends Statement { ClassDeclaration getDeclaration ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface BlockComment extends Comment { String getString ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface ClassDeclaration extends TypeDeclaration { List < ? extends TypeParameterDeclaration > getTypeParameters ( ) ; Type getSuperClass ( ) ; List < ? extends Type > getSuperInterfaceTypes ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface FieldAccessExpression extends Expression { Expression getQualifier ( ) ; SimpleName getName ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface MethodDeclaration extends MethodOrConstructorDeclaration , TypedElement { Type getReturnType ( ) ; int getExtraDimensions ( ) ; } package com . asakusafw . utils . java . model . syntax ; public enum WildcardBoundKind { UNBOUNDED ( "" ) , UPPER_BOUNDED ( "" ) , LOWER_BOUNDED ( "" ) , ; private final String representation ; private WildcardBoundKind ( String representation ) { assert representation != null ; this . representation = representation ; } public String getRepresentation ( ) { return representation ; } public WildcardBoundKind normalize ( ) { return this == UNBOUNDED ? UPPER_BOUNDED : this ; } } package com . asakusafw . utils . java . model . syntax ; public interface ClassLiteral extends Expression { Type getType ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface EmptyStatement extends Statement { } package com . asakusafw . utils . java . model . syntax ; public interface PostfixExpression extends Expression { Expression getOperand ( ) ; PostfixOperator getOperator ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface InfixExpression extends Expression { Expression getLeftOperand ( ) ; InfixOperator getOperator ( ) ; Expression getRightOperand ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface SuperConstructorInvocation extends ConstructorInvocation { Expression getQualifier ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface MethodOrConstructorDeclaration extends TypeBodyDeclaration { List < ? extends TypeParameterDeclaration > getTypeParameters ( ) ; SimpleName getName ( ) ; List < ? extends FormalParameterDeclaration > getFormalParameters ( ) ; List < ? extends Type > getExceptionTypes ( ) ; Block getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface InterfaceDeclaration extends TypeDeclaration { List < ? extends TypeParameterDeclaration > getTypeParameters ( ) ; List < ? extends Type > getSuperInterfaceTypes ( ) ; } package com . asakusafw . utils . java . model . syntax ; import static com . asakusafw . utils . java . model . syntax . ExecutableKind . * ; import static com . asakusafw . utils . java . model . syntax . FieldKind . * ; import static com . asakusafw . utils . java . model . syntax . ObjectTypeKind . * ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Collections ; import java . util . EnumSet ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; public enum ModifierKind { PUBLIC ( of ( CLASS , INTERFACE , ENUM , ANNOTATION , FIELD , CONSTRUCTOR , METHOD ) , of ( ANNOTATION_ELEMENT , ENUM_CONSTANT ) ) , PROTECTED ( of ( CLASS , INTERFACE , ENUM , ANNOTATION , FIELD , CONSTRUCTOR , METHOD ) , Collections . < DeclarationKind > emptySet ( ) ) , PRIVATE ( of ( CLASS , INTERFACE , ENUM , ANNOTATION , FIELD , CONSTRUCTOR , METHOD ) , Collections . < DeclarationKind > emptySet ( ) ) , STATIC ( of ( CLASS , INTERFACE , ENUM , ANNOTATION , FIELD , METHOD ) , of ( ENUM_CONSTANT ) ) , ABSTRACT ( of ( CLASS , INTERFACE , ENUM , ANNOTATION , FIELD , METHOD ) , of ( ANNOTATION_ELEMENT ) ) , NATIVE ( of ( METHOD ) , Collections . < DeclarationKind > emptySet ( ) ) , FINAL ( of ( CLASS , FIELD , METHOD ) , of ( ENUM , ENUM_CONSTANT ) ) , SYNCHRONIZED ( of ( METHOD ) , Collections . < DeclarationKind > emptySet ( ) ) , TRANSIENT ( of ( FIELD ) , Collections . < DeclarationKind > emptySet ( ) ) , VOLATILE ( of ( FIELD ) , Collections . < DeclarationKind > emptySet ( ) ) , STRICTFP ( of ( CLASS , INTERFACE , ENUM , ANNOTATION , METHOD ) , Collections . < DeclarationKind > emptySet ( ) ) , SUPER ( Collections . < DeclarationKind > emptySet ( ) , of ( CLASS , INTERFACE , ENUM , ANNOTATION ) ) , BRIDGE ( Collections . < DeclarationKind > emptySet ( ) , of ( METHOD ) ) , VARARGS ( Collections . < DeclarationKind > emptySet ( ) , of ( METHOD , CONSTRUCTOR ) ) , SYNTHETIC ( Collections . < DeclarationKind > emptySet ( ) , of ( CLASS , INTERFACE , ENUM , ANNOTATION , FIELD , CONSTRUCTOR , METHOD , ANNOTATION_ELEMENT , ENUM_CONSTANT ) ) , ; private final Set < DeclarationKind > declarable ; private final Set < DeclarationKind > grantable ; private ModifierKind ( Set < DeclarationKind > declarable , Set < DeclarationKind > grant ) { assert declarable != null ; assert grant != null ; this . declarable = Collections . unmodifiableSet ( declarable ) ; Set < DeclarationKind > allGrants ; if ( grant . isEmpty ( ) ) { allGrants = declarable ; } else { allGrants = new HashSet < DeclarationKind > ( grant ) ; allGrants . addAll ( declarable ) ; } this . grantable = Collections . unmodifiableSet ( allGrants ) ; } public boolean isImplicit ( ) { return declarable . isEmpty ( ) ; } public boolean canBeDeclaredIn ( DeclarationKind kind ) { return declarable . contains ( kind ) ; } public boolean canBeGrantedIn ( DeclarationKind kind ) { return grantable . contains ( kind ) ; } public static String toStringAll ( Set < ModifierKind > modifiers ) { if ( modifiers == null ) { throw new IllegalArgumentException ( "" ) ; } StringBuilder buf = new StringBuilder ( ) ; Iterator < ModifierKind > iter = modifiers . iterator ( ) ; if ( iter . hasNext ( ) ) { buf . append ( iter . next ( ) . name ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( '' ) ; buf . append ( iter . next ( ) . name ( ) ) ; } } return buf . toString ( ) ; } public static Set < ModifierKind > allValueOf ( String values ) { if ( values == null ) { throw new IllegalArgumentException ( "" ) ; } if ( values . length ( ) == ) { return Collections . emptySet ( ) ; } EnumSet < ModifierKind > results = EnumSet . noneOf ( ModifierKind . class ) ; int start = ; while ( true ) { int index = values . indexOf ( '' , start ) ; if ( index < ) { break ; } String token = values . substring ( start , index ) ; results . add ( ModifierKind . valueOf ( token ) ) ; start = index + ; } results . add ( ModifierKind . valueOf ( values . substring ( start ) ) ) ; return results ; } public String getKeyword ( ) { if ( isImplicit ( ) ) { return MessageFormat . format ( "" , name ( ) ) ; } else { return name ( ) . toLowerCase ( ) ; } } @ Override public String toString ( ) { return getKeyword ( ) ; } private static Set < DeclarationKind > of ( DeclarationKind ... kinds ) { return new HashSet < DeclarationKind > ( Arrays . asList ( kinds ) ) ; } } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface SwitchStatement extends Statement , TypedElement { Expression getExpression ( ) ; List < ? extends Statement > getStatements ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface SwitchCaseLabel extends SwitchLabel { Expression getExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface DocBlock extends DocElement { String getTag ( ) ; List < ? extends DocElement > getElements ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface SynchronizedStatement extends Statement { Expression getExpression ( ) ; Block getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface Expression extends TypedElement { } package com . asakusafw . utils . java . model . syntax ; public interface TypedElement extends Model { } package com . asakusafw . utils . java . model . syntax ; public interface InstanceofExpression extends Expression { Expression getExpression ( ) ; Type getType ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface ParameterizedType extends Type { Type getType ( ) ; List < ? extends Type > getTypeArguments ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ForStatement extends Statement { ForInitializer getInitialization ( ) ; Expression getCondition ( ) ; StatementExpressionList getUpdate ( ) ; Statement getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface NormalAnnotation extends Annotation { List < ? extends AnnotationElement > getElements ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface AssertStatement extends Statement { Expression getExpression ( ) ; Expression getMessage ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface StatementExpressionList extends ForInitializer { List < ? extends Expression > getExpressions ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ConditionalExpression extends Expression { Expression getCondition ( ) ; Expression getThenExpression ( ) ; Expression getElseExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface EnumDeclaration extends TypeDeclaration { List < ? extends Type > getSuperInterfaceTypes ( ) ; List < ? extends EnumConstantDeclaration > getConstantDeclarations ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface FormalParameterDeclaration extends TypedElement { List < ? extends Attribute > getModifiers ( ) ; Type getType ( ) ; boolean isVariableArity ( ) ; SimpleName getName ( ) ; int getExtraDimensions ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface ModelFactory { AlternateConstructorInvocation newAlternateConstructorInvocation ( Expression ... arguments ) ; AlternateConstructorInvocation newAlternateConstructorInvocation ( List < ? extends Expression > arguments ) ; AlternateConstructorInvocation newAlternateConstructorInvocation ( List < ? extends Type > typeArguments , List < ? extends Expression > arguments ) ; AnnotationDeclaration newAnnotationDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeBodyDeclaration > bodyDeclarations ) ; AnnotationElement newAnnotationElement ( SimpleName name , Expression expression ) ; AnnotationElementDeclaration newAnnotationElementDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type type , SimpleName name , Expression defaultExpression ) ; ArrayAccessExpression newArrayAccessExpression ( Expression array , Expression index ) ; ArrayCreationExpression newArrayCreationExpression ( ArrayType type , ArrayInitializer arrayInitializer ) ; ArrayCreationExpression newArrayCreationExpression ( ArrayType type , List < ? extends Expression > dimensionExpressions , ArrayInitializer arrayInitializer ) ; ArrayInitializer newArrayInitializer ( Expression ... elements ) ; ArrayInitializer newArrayInitializer ( List < ? extends Expression > elements ) ; ArrayType newArrayType ( Type componentType ) ; AssertStatement newAssertStatement ( Expression expression ) ; AssertStatement newAssertStatement ( Expression expression , Expression message ) ; AssignmentExpression newAssignmentExpression ( Expression leftHandSide , Expression rightHandSide ) ; AssignmentExpression newAssignmentExpression ( Expression leftHandSide , InfixOperator operator , Expression rightHandSide ) ; BasicType newBasicType ( BasicTypeKind typeKind ) ; Block newBlock ( Statement ... statements ) ; Block newBlock ( List < ? extends Statement > statements ) ; BlockComment newBlockComment ( String string ) ; BreakStatement newBreakStatement ( ) ; BreakStatement newBreakStatement ( SimpleName target ) ; CastExpression newCastExpression ( Type type , Expression expression ) ; CatchClause newCatchClause ( FormalParameterDeclaration parameter , Block body ) ; ClassBody newClassBody ( List < ? extends TypeBodyDeclaration > bodyDeclarations ) ; ClassDeclaration newClassDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , Type superClass , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) ; ClassDeclaration newClassDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeParameterDeclaration > typeParameters , Type superClass , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) ; ClassInstanceCreationExpression newClassInstanceCreationExpression ( Type type , Expression ... arguments ) ; ClassInstanceCreationExpression newClassInstanceCreationExpression ( Type type , List < ? extends Expression > arguments ) ; ClassInstanceCreationExpression newClassInstanceCreationExpression ( Expression qualifier , List < ? extends Type > typeArguments , Type type , List < ? extends Expression > arguments , ClassBody body ) ; ClassLiteral newClassLiteral ( Type type ) ; CompilationUnit newCompilationUnit ( PackageDeclaration packageDeclaration , List < ? extends ImportDeclaration > importDeclarations , List < ? extends TypeDeclaration > typeDeclarations , List < ? extends Comment > comments ) ; ConditionalExpression newConditionalExpression ( Expression condition , Expression thenExpression , Expression elseExpression ) ; ConstructorDeclaration newConstructorDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , List < ? extends Statement > statements ) ; ConstructorDeclaration newConstructorDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , List < ? extends TypeParameterDeclaration > typeParameters , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , List < ? extends Type > exceptionTypes , Block body ) ; ContinueStatement newContinueStatement ( ) ; ContinueStatement newContinueStatement ( SimpleName target ) ; DoStatement newDoStatement ( Statement body , Expression condition ) ; DocBlock newDocBlock ( String tag , List < ? extends DocElement > elements ) ; DocField newDocField ( Type type , SimpleName name ) ; DocMethod newDocMethod ( Type type , SimpleName name , List < ? extends DocMethodParameter > formalParameters ) ; DocMethodParameter newDocMethodParameter ( Type type , SimpleName name , boolean variableArity ) ; DocText newDocText ( String string ) ; EmptyStatement newEmptyStatement ( ) ; EnhancedForStatement newEnhancedForStatement ( FormalParameterDeclaration parameter , Expression expression , Statement body ) ; EnumConstantDeclaration newEnumConstantDeclaration ( Javadoc javadoc , SimpleName name , Expression ... arguments ) ; EnumConstantDeclaration newEnumConstantDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends Expression > arguments , ClassBody body ) ; EnumDeclaration newEnumDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends EnumConstantDeclaration > constantDeclarations , TypeBodyDeclaration ... bodyDeclarations ) ; EnumDeclaration newEnumDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends Type > superInterfaceTypes , List < ? extends EnumConstantDeclaration > constantDeclarations , List < ? extends TypeBodyDeclaration > bodyDeclarations ) ; ExpressionStatement newExpressionStatement ( Expression expression ) ; FieldAccessExpression newFieldAccessExpression ( Expression qualifier , SimpleName name ) ; FieldDeclaration newFieldDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type type , SimpleName name , Expression initializer ) ; FieldDeclaration newFieldDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type type , List < ? extends VariableDeclarator > variableDeclarators ) ; ForStatement newForStatement ( ForInitializer initialization , Expression condition , StatementExpressionList update , Statement body ) ; FormalParameterDeclaration newFormalParameterDeclaration ( Type type , SimpleName name ) ; FormalParameterDeclaration newFormalParameterDeclaration ( List < ? extends Attribute > modifiers , Type type , boolean variableArity , SimpleName name , int extraDimensions ) ; IfStatement newIfStatement ( Expression condition , Statement thenStatement ) ; IfStatement newIfStatement ( Expression condition , Statement thenStatement , Statement elseStatement ) ; ImportDeclaration newImportDeclaration ( ImportKind importKind , Name name ) ; InfixExpression newInfixExpression ( Expression leftOperand , InfixOperator operator , Expression rightOperand ) ; InitializerDeclaration newInitializerDeclaration ( List < ? extends Statement > body ) ; InitializerDeclaration newInitializerDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Block body ) ; InstanceofExpression newInstanceofExpression ( Expression expression , Type type ) ; InterfaceDeclaration newInterfaceDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) ; InterfaceDeclaration newInterfaceDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeParameterDeclaration > typeParameters , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) ; Javadoc newJavadoc ( List < ? extends DocBlock > blocks ) ; LabeledStatement newLabeledStatement ( SimpleName label , Statement body ) ; LineComment newLineComment ( String string ) ; Literal newLiteral ( String token ) ; LocalClassDeclaration newLocalClassDeclaration ( ClassDeclaration declaration ) ; LocalVariableDeclaration newLocalVariableDeclaration ( Type type , SimpleName name , Expression initializer ) ; LocalVariableDeclaration newLocalVariableDeclaration ( List < ? extends Attribute > modifiers , Type type , List < ? extends VariableDeclarator > variableDeclarators ) ; MarkerAnnotation newMarkerAnnotation ( NamedType type ) ; MethodDeclaration newMethodDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type returnType , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , List < ? extends Statement > statements ) ; MethodDeclaration newMethodDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , List < ? extends TypeParameterDeclaration > typeParameters , Type returnType , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , int extraDimensions , List < ? extends Type > exceptionTypes , Block body ) ; MethodInvocationExpression newMethodInvocationExpression ( Expression qualifier , SimpleName name , Expression ... arguments ) ; MethodInvocationExpression newMethodInvocationExpression ( Expression qualifier , SimpleName name , List < ? extends Expression > arguments ) ; MethodInvocationExpression newMethodInvocationExpression ( Expression qualifier , List < ? extends Type > typeArguments , SimpleName name , List < ? extends Expression > arguments ) ; Modifier newModifier ( ModifierKind modifierKind ) ; NamedType newNamedType ( Name name ) ; NormalAnnotation newNormalAnnotation ( NamedType type , List < ? extends AnnotationElement > elements ) ; PackageDeclaration newPackageDeclaration ( Name name ) ; PackageDeclaration newPackageDeclaration ( Javadoc javadoc , List < ? extends Annotation > annotations , Name name ) ; ParameterizedType newParameterizedType ( Type type , Type ... typeArguments ) ; ParameterizedType newParameterizedType ( Type type , List < ? extends Type > typeArguments ) ; ParenthesizedExpression newParenthesizedExpression ( Expression expression ) ; PostfixExpression newPostfixExpression ( Expression operand , PostfixOperator operator ) ; QualifiedName newQualifiedName ( Name qualifier , SimpleName simpleName ) ; QualifiedType newQualifiedType ( Type qualifier , SimpleName simpleName ) ; ReturnStatement newReturnStatement ( ) ; ReturnStatement newReturnStatement ( Expression expression ) ; SimpleName newSimpleName ( String string ) ; SingleElementAnnotation newSingleElementAnnotation ( NamedType type , Expression expression ) ; StatementExpressionList newStatementExpressionList ( Expression ... expressions ) ; StatementExpressionList newStatementExpressionList ( List < ? extends Expression > expressions ) ; Super newSuper ( ) ; Super newSuper ( NamedType qualifier ) ; SuperConstructorInvocation newSuperConstructorInvocation ( Expression ... arguments ) ; SuperConstructorInvocation newSuperConstructorInvocation ( List < ? extends Expression > arguments ) ; SuperConstructorInvocation newSuperConstructorInvocation ( Expression qualifier , List < ? extends Type > typeArguments , List < ? extends Expression > arguments ) ; SwitchCaseLabel newSwitchCaseLabel ( Expression expression ) ; SwitchDefaultLabel newSwitchDefaultLabel ( ) ; SwitchStatement newSwitchStatement ( Expression expression , List < ? extends Statement > statements ) ; SynchronizedStatement newSynchronizedStatement ( Expression expression , Block body ) ; This newThis ( ) ; This newThis ( NamedType qualifier ) ; ThrowStatement newThrowStatement ( Expression expression ) ; TryStatement newTryStatement ( Block tryBlock , List < ? extends CatchClause > catchClauses , Block finallyBlock ) ; TypeParameterDeclaration newTypeParameterDeclaration ( SimpleName name , Type ... typeBounds ) ; TypeParameterDeclaration newTypeParameterDeclaration ( SimpleName name , List < ? extends Type > typeBounds ) ; UnaryExpression newUnaryExpression ( UnaryOperator operator , Expression operand ) ; VariableDeclarator newVariableDeclarator ( SimpleName name , Expression initializer ) ; VariableDeclarator newVariableDeclarator ( SimpleName name , int extraDimensions , Expression initializer ) ; WhileStatement newWhileStatement ( Expression condition , Statement body ) ; Wildcard newWildcard ( ) ; Wildcard newWildcard ( WildcardBoundKind boundKind , Type typeBound ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface CompilationUnit extends Model { PackageDeclaration getPackageDeclaration ( ) ; List < ? extends ImportDeclaration > getImportDeclarations ( ) ; List < ? extends TypeDeclaration > getTypeDeclarations ( ) ; List < ? extends Comment > getComments ( ) ; } package com . asakusafw . utils . java . model . syntax ; public enum ObjectTypeKind implements DeclarationKind { CLASS ( true ) , INTERFACE ( false ) , ENUM ( true ) , ANNOTATION ( false ) , ; private final boolean classLike ; private ObjectTypeKind ( boolean classLike ) { this . classLike = classLike ; } public boolean isClassLike ( ) { return classLike ; } } package com . asakusafw . utils . java . model . syntax ; public interface Type extends TypedElement { } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface Block extends Statement { List < ? extends Statement > getStatements ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface Attribute extends Model { } package com . asakusafw . utils . java . model . syntax ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public enum BasicTypeKind { VOID ( '' , void . class ) , INT ( '' , int . class ) , LONG ( '' , long . class ) , FLOAT ( '' , float . class ) , DOUBLE ( '' , double . class ) , SHORT ( '' , short . class ) , CHAR ( '' , char . class ) , BYTE ( '' , byte . class ) , BOOLEAN ( '' , boolean . class ) , ; private final char descriptor ; private Class < ? > javaRepresentation ; private BasicTypeKind ( char descriptor , Class < ? > klass ) { assert klass != null ; assert klass . isPrimitive ( ) ; this . descriptor = descriptor ; this . javaRepresentation = klass ; } public static BasicTypeKind descriptorOf ( char descriptor ) { return DescriptorToBasicTypeKind . get ( descriptor ) ; } public char getDescriptor ( ) { return descriptor ; } public Class < ? > getJavaRepresentation ( ) { return javaRepresentation ; } public static BasicTypeKind valueOf ( Class < ? > klass ) { if ( klass == null ) { throw new IllegalArgumentException ( "" ) ; } return ClassToBasicTypeKind . get ( klass ) ; } public String getKeyword ( ) { return name ( ) . toLowerCase ( ) ; } public static BasicTypeKind keywordOf ( String keyword ) { if ( keyword == null ) { throw new IllegalArgumentException ( "" ) ; } return KeywordToBasicTypeKind . get ( keyword ) ; } @ Override public String toString ( ) { return getKeyword ( ) ; } private static class ClassToBasicTypeKind { private static final Map < Class < ? > , BasicTypeKind > REVERSE_DICTIONARY ; static { Map < Class < ? > , BasicTypeKind > map = new HashMap < Class < ? > , BasicTypeKind > ( ) ; for ( BasicTypeKind elem : BasicTypeKind . values ( ) ) { map . put ( elem . getJavaRepresentation ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } static BasicTypeKind get ( Class < ? > key ) { return REVERSE_DICTIONARY . get ( key ) ; } } private static class DescriptorToBasicTypeKind { private static final Map < Character , BasicTypeKind > REVERSE_DICTIONARY ; static { Map < Character , BasicTypeKind > map = new HashMap < Character , BasicTypeKind > ( ) ; for ( BasicTypeKind elem : BasicTypeKind . values ( ) ) { map . put ( elem . getDescriptor ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } static BasicTypeKind get ( char key ) { return REVERSE_DICTIONARY . get ( key ) ; } } private static class KeywordToBasicTypeKind { private static final Map < String , BasicTypeKind > REVERSE_DICTIONARY ; static { Map < String , BasicTypeKind > map = new HashMap < String , BasicTypeKind > ( ) ; for ( BasicTypeKind elem : BasicTypeKind . values ( ) ) { map . put ( elem . getKeyword ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } static BasicTypeKind get ( String key ) { return REVERSE_DICTIONARY . get ( key ) ; } } } package com . asakusafw . utils . java . model . syntax ; public interface ImportDeclaration extends Model { ImportKind getImportKind ( ) ; Name getName ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface ArrayCreationExpression extends Expression { ArrayType getType ( ) ; List < ? extends Expression > getDimensionExpressions ( ) ; ArrayInitializer getArrayInitializer ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ContinueStatement extends BranchStatement { } package com . asakusafw . utils . java . model . syntax ; public interface InitializerDeclaration extends TypeBodyDeclaration { @ Override Javadoc getJavadoc ( ) ; Block getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface AlternateConstructorInvocation extends ConstructorInvocation { } package com . asakusafw . utils . java . model . syntax ; public interface Comment extends Model { } package com . asakusafw . utils . java . model . syntax ; public interface QualifiedType extends Type { Type getQualifier ( ) ; SimpleName getSimpleName ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface Model { ModelKind getModelKind ( ) ; < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E ; @ Override int hashCode ( ) ; @ Override boolean equals ( Object other ) ; < T > T findModelTrait ( Class < T > traitClass ) ; < T > void putModelTrait ( Class < T > traitClass , T traitObject ) ; } package com . asakusafw . utils . java . model . syntax ; public interface DocText extends DocElement { String getString ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface SingleElementAnnotation extends Annotation , Invocation { Expression getExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ThrowStatement extends Statement , TypedElement { Expression getExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface This extends Keyword { } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface MethodInvocationExpression extends Expression , Invocation { Expression getQualifier ( ) ; List < ? extends Type > getTypeArguments ( ) ; SimpleName getName ( ) ; List < ? extends Expression > getArguments ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface BranchStatement extends Statement { SimpleName getTarget ( ) ; } package com . asakusafw . utils . java . model . syntax ; public enum FieldKind implements DeclarationKind { FIELD , ENUM_CONSTANT , } package com . asakusafw . utils . java . model . syntax ; public interface ReturnStatement extends Statement , TypedElement { Expression getExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface VariableDeclarator extends TypedElement { SimpleName getName ( ) ; int getExtraDimensions ( ) ; Expression getInitializer ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface WhileStatement extends Statement { Expression getCondition ( ) ; Statement getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface Wildcard extends Type { WildcardBoundKind getBoundKind ( ) ; Type getTypeBound ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface DocMethod extends DocElement { Type getType ( ) ; SimpleName getName ( ) ; List < ? extends DocMethodParameter > getFormalParameters ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . Collections ; import java . util . EnumSet ; import java . util . HashMap ; import java . util . Map ; import java . util . Set ; public enum InfixOperator { ASSIGN ( "" , EnumSet . of ( Context . ASSIGNMENT ) , Category . ASSIGNMENT ) , PLUS ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . ADDITIVE ) , MINUS ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . ADDITIVE ) , TIMES ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . MULTIPLICATIVE ) , DIVIDE ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . MULTIPLICATIVE ) , REMAINDER ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . MULTIPLICATIVE ) , LEFT_SHIFT ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . SHIFT ) , RIGHT_SHIFT_SIGNED ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . SHIFT ) , RIGHT_SHIFT_UNSIGNED ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . SHIFT ) , OR ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . BITWISE ) , AND ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . BITWISE ) , XOR ( "" , EnumSet . of ( Context . INFIX , Context . ASSIGNMENT ) , Category . BITWISE ) , EQUALS ( "" , EnumSet . of ( Context . INFIX ) , Category . EQUALITY ) , NOT_EQUALS ( "" , EnumSet . of ( Context . INFIX ) , Category . EQUALITY ) , GREATER ( ">" , EnumSet . of ( Context . INFIX ) , Category . RELATIONAL ) , LESS ( "" , EnumSet . of ( Context . INFIX ) , Category . RELATIONAL ) , GREATER_EQUALS ( "" , EnumSet . of ( Context . INFIX ) , Category . RELATIONAL ) , LESS_EQUALS ( "" , EnumSet . of ( Context . INFIX ) , Category . RELATIONAL ) , CONDITIONAL_OR ( "" , EnumSet . of ( Context . INFIX ) , Category . CONDITIONAL ) , CONDITIONAL_AND ( "" , EnumSet . of ( Context . INFIX ) , Category . CONDITIONAL ) , ; private final String symbol ; private final Set < Context > permittedContexts ; private final Category category ; private InfixOperator ( String symbol , EnumSet < Context > permitted , Category category ) { assert symbol != null ; assert permitted != null ; assert category != null ; this . symbol = symbol ; this . permittedContexts = Collections . unmodifiableSet ( permitted ) ; this . category = category ; } public String getSymbol ( ) { return this . symbol ; } public String getAssignmentSymbol ( ) { if ( this == ASSIGN ) { return ASSIGN . getSymbol ( ) ; } else { return getSymbol ( ) + ASSIGN . getSymbol ( ) ; } } public static InfixOperator fromSymbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } return SymbolToInfixOperator . get ( symbol ) ; } public boolean isPermitted ( Context context ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } return permittedContexts . contains ( context ) ; } public InfixOperator . Category getCategory ( ) { return this . category ; } public static enum Context { INFIX , ASSIGNMENT , } public static enum Category { MULTIPLICATIVE , ADDITIVE , SHIFT , RELATIONAL , EQUALITY , BITWISE , CONDITIONAL , ASSIGNMENT , } private static class SymbolToInfixOperator { private static final Map < String , InfixOperator > REVERSE_DICTIONARY ; static { Map < String , InfixOperator > map = new HashMap < String , InfixOperator > ( ) ; for ( InfixOperator elem : InfixOperator . values ( ) ) { map . put ( elem . getSymbol ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } static InfixOperator get ( String key ) { return REVERSE_DICTIONARY . get ( key ) ; } } } package com . asakusafw . utils . java . model . syntax ; public interface AnnotationElementDeclaration extends TypeBodyDeclaration , TypedElement { Type getType ( ) ; SimpleName getName ( ) ; Expression getDefaultExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface AnnotationElement extends Invocation { SimpleName getName ( ) ; Expression getExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface DoStatement extends Statement { Statement getBody ( ) ; Expression getCondition ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface SimpleName extends Name { String getToken ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface TypeDeclaration extends TypeBodyDeclaration , TypedElement { SimpleName getName ( ) ; List < ? extends TypeBodyDeclaration > getBodyDeclarations ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface DeclarationKind { } package com . asakusafw . utils . java . model . syntax ; public enum LiteralKind { INT , LONG , FLOAT , DOUBLE , CHAR , BOOLEAN , STRING , NULL , ; public static final String TOKEN_NULL = "" ; public static final String TOKEN_TRUE = "" ; public static final String TOKEN_FALSE = "" ; } package com . asakusafw . utils . java . model . syntax ; public interface BreakStatement extends BranchStatement { } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface PackageDeclaration extends Model { Javadoc getJavadoc ( ) ; List < ? extends Annotation > getAnnotations ( ) ; Name getName ( ) ; } package com . asakusafw . utils . java . model . syntax ; package com . asakusafw . utils . java . model . syntax ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public enum UnaryOperator { PLUS ( "" , Category . SIGN ) , MINUS ( "" , Category . SIGN ) , COMPLEMENT ( "" , Category . BITWISE ) , NOT ( "" , Category . LOGICAL ) , INCREMENT ( "" , Category . INCREMENT_DECREMENT ) , DECREMENT ( "" , Category . INCREMENT_DECREMENT ) , ; private final String symbol ; private final Category category ; private UnaryOperator ( String symbol , Category category ) { assert symbol != null ; assert category != null ; this . symbol = symbol ; this . category = category ; } public String getSymbol ( ) { return this . symbol ; } public Category getCategory ( ) { return category ; } public static UnaryOperator fromSymbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } return SymbolToUnaryOperator . get ( symbol ) ; } public enum Category { INCREMENT_DECREMENT , SIGN , BITWISE , LOGICAL , } private static class SymbolToUnaryOperator { private static final Map < String , UnaryOperator > REVERSE_DICTIONARY ; static { Map < String , UnaryOperator > map = new HashMap < String , UnaryOperator > ( ) ; for ( UnaryOperator elem : UnaryOperator . values ( ) ) { map . put ( elem . getSymbol ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } static UnaryOperator get ( String key ) { return REVERSE_DICTIONARY . get ( key ) ; } } } package com . asakusafw . utils . java . model . syntax ; public interface AnnotationDeclaration extends TypeDeclaration { } package com . asakusafw . utils . java . model . syntax ; public interface LabeledStatement extends Statement { SimpleName getLabel ( ) ; Statement getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface Super extends Keyword { } package com . asakusafw . utils . java . model . syntax ; public interface MarkerAnnotation extends Annotation { } package com . asakusafw . utils . java . model . syntax ; public interface DocMethodParameter extends Model { Type getType ( ) ; SimpleName getName ( ) ; boolean isVariableArity ( ) ; } package com . asakusafw . utils . java . model . syntax ; public enum ExecutableKind implements DeclarationKind { CONSTRUCTOR , METHOD , ANNOTATION_ELEMENT , } package com . asakusafw . utils . java . model . syntax ; public interface CatchClause extends TypedElement { FormalParameterDeclaration getParameter ( ) ; Block getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ParenthesizedExpression extends Expression { Expression getExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ConstructorDeclaration extends MethodOrConstructorDeclaration , TypedElement { @ Override Block getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface ClassInstanceCreationExpression extends Expression , Invocation { Expression getQualifier ( ) ; List < ? extends Type > getTypeArguments ( ) ; Type getType ( ) ; List < ? extends Expression > getArguments ( ) ; ClassBody getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface ClassBody extends TypedElement { List < ? extends TypeBodyDeclaration > getBodyDeclarations ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface DocField extends DocElement { Type getType ( ) ; SimpleName getName ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface Name extends Expression , DocElement { SimpleName getLastSegment ( ) ; List < SimpleName > toNameList ( ) ; String toNameString ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface SwitchLabel extends Statement , TypedElement { } package com . asakusafw . utils . java . model . syntax ; public interface SwitchDefaultLabel extends SwitchLabel { } package com . asakusafw . utils . java . model . syntax ; public interface Keyword extends Expression { NamedType getQualifier ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface Annotation extends Attribute , Expression { NamedType getType ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface TypeParameterDeclaration extends Model { SimpleName getName ( ) ; List < ? extends Type > getTypeBounds ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface CastExpression extends Expression { Type getType ( ) ; Expression getExpression ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface Invocation extends TypedElement { } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface EnumConstantDeclaration extends TypeBodyDeclaration , TypedElement , Invocation { SimpleName getName ( ) ; List < ? extends Expression > getArguments ( ) ; ClassBody getBody ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ForInitializer extends Model { } package com . asakusafw . utils . java . model . syntax ; public interface Literal extends Expression { String getToken ( ) ; LiteralKind getLiteralKind ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface LineComment extends Comment { String getString ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface BasicType extends Type { BasicTypeKind getTypeKind ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface FieldDeclaration extends TypeBodyDeclaration { Type getType ( ) ; List < ? extends VariableDeclarator > getVariableDeclarators ( ) ; } package com . asakusafw . utils . java . model . syntax ; public abstract class Visitor < R , C , E extends Throwable > { public R visitAlternateConstructorInvocation ( AlternateConstructorInvocation elem , C context ) throws E { return null ; } public R visitAnnotationDeclaration ( AnnotationDeclaration elem , C context ) throws E { return null ; } public R visitAnnotationElement ( AnnotationElement elem , C context ) throws E { return null ; } public R visitAnnotationElementDeclaration ( AnnotationElementDeclaration elem , C context ) throws E { return null ; } public R visitArrayAccessExpression ( ArrayAccessExpression elem , C context ) throws E { return null ; } public R visitArrayCreationExpression ( ArrayCreationExpression elem , C context ) throws E { return null ; } public R visitArrayInitializer ( ArrayInitializer elem , C context ) throws E { return null ; } public R visitArrayType ( ArrayType elem , C context ) throws E { return null ; } public R visitAssertStatement ( AssertStatement elem , C context ) throws E { return null ; } public R visitAssignmentExpression ( AssignmentExpression elem , C context ) throws E { return null ; } public R visitBasicType ( BasicType elem , C context ) throws E { return null ; } public R visitBlock ( Block elem , C context ) throws E { return null ; } public R visitBlockComment ( BlockComment elem , C context ) throws E { return null ; } public R visitBreakStatement ( BreakStatement elem , C context ) throws E { return null ; } public R visitCastExpression ( CastExpression elem , C context ) throws E { return null ; } public R visitCatchClause ( CatchClause elem , C context ) throws E { return null ; } public R visitClassBody ( ClassBody elem , C context ) throws E { return null ; } public R visitClassDeclaration ( ClassDeclaration elem , C context ) throws E { return null ; } public R visitClassInstanceCreationExpression ( ClassInstanceCreationExpression elem , C context ) throws E { return null ; } public R visitClassLiteral ( ClassLiteral elem , C context ) throws E { return null ; } public R visitCompilationUnit ( CompilationUnit elem , C context ) throws E { return null ; } public R visitConditionalExpression ( ConditionalExpression elem , C context ) throws E { return null ; } public R visitConstructorDeclaration ( ConstructorDeclaration elem , C context ) throws E { return null ; } public R visitContinueStatement ( ContinueStatement elem , C context ) throws E { return null ; } public R visitDoStatement ( DoStatement elem , C context ) throws E { return null ; } public R visitDocBlock ( DocBlock elem , C context ) throws E { return null ; } public R visitDocField ( DocField elem , C context ) throws E { return null ; } public R visitDocMethod ( DocMethod elem , C context ) throws E { return null ; } public R visitDocMethodParameter ( DocMethodParameter elem , C context ) throws E { return null ; } public R visitDocText ( DocText elem , C context ) throws E { return null ; } public R visitEmptyStatement ( EmptyStatement elem , C context ) throws E { return null ; } public R visitEnhancedForStatement ( EnhancedForStatement elem , C context ) throws E { return null ; } public R visitEnumConstantDeclaration ( EnumConstantDeclaration elem , C context ) throws E { return null ; } public R visitEnumDeclaration ( EnumDeclaration elem , C context ) throws E { return null ; } public R visitExpressionStatement ( ExpressionStatement elem , C context ) throws E { return null ; } public R visitFieldAccessExpression ( FieldAccessExpression elem , C context ) throws E { return null ; } public R visitFieldDeclaration ( FieldDeclaration elem , C context ) throws E { return null ; } public R visitForStatement ( ForStatement elem , C context ) throws E { return null ; } public R visitFormalParameterDeclaration ( FormalParameterDeclaration elem , C context ) throws E { return null ; } public R visitIfStatement ( IfStatement elem , C context ) throws E { return null ; } public R visitImportDeclaration ( ImportDeclaration elem , C context ) throws E { return null ; } public R visitInfixExpression ( InfixExpression elem , C context ) throws E { return null ; } public R visitInitializerDeclaration ( InitializerDeclaration elem , C context ) throws E { return null ; } public R visitInstanceofExpression ( InstanceofExpression elem , C context ) throws E { return null ; } public R visitInterfaceDeclaration ( InterfaceDeclaration elem , C context ) throws E { return null ; } public R visitJavadoc ( Javadoc elem , C context ) throws E { return null ; } public R visitLabeledStatement ( LabeledStatement elem , C context ) throws E { return null ; } public R visitLineComment ( LineComment elem , C context ) throws E { return null ; } public R visitLiteral ( Literal elem , C context ) throws E { return null ; } public R visitLocalClassDeclaration ( LocalClassDeclaration elem , C context ) throws E { return null ; } public R visitLocalVariableDeclaration ( LocalVariableDeclaration elem , C context ) throws E { return null ; } public R visitMarkerAnnotation ( MarkerAnnotation elem , C context ) throws E { return null ; } public R visitMethodDeclaration ( MethodDeclaration elem , C context ) throws E { return null ; } public R visitMethodInvocationExpression ( MethodInvocationExpression elem , C context ) throws E { return null ; } public R visitModifier ( Modifier elem , C context ) throws E { return null ; } public R visitNamedType ( NamedType elem , C context ) throws E { return null ; } public R visitNormalAnnotation ( NormalAnnotation elem , C context ) throws E { return null ; } public R visitPackageDeclaration ( PackageDeclaration elem , C context ) throws E { return null ; } public R visitParameterizedType ( ParameterizedType elem , C context ) throws E { return null ; } public R visitParenthesizedExpression ( ParenthesizedExpression elem , C context ) throws E { return null ; } public R visitPostfixExpression ( PostfixExpression elem , C context ) throws E { return null ; } public R visitQualifiedName ( QualifiedName elem , C context ) throws E { return null ; } public R visitQualifiedType ( QualifiedType elem , C context ) throws E { return null ; } public R visitReturnStatement ( ReturnStatement elem , C context ) throws E { return null ; } public R visitSimpleName ( SimpleName elem , C context ) throws E { return null ; } public R visitSingleElementAnnotation ( SingleElementAnnotation elem , C context ) throws E { return null ; } public R visitStatementExpressionList ( StatementExpressionList elem , C context ) throws E { return null ; } public R visitSuper ( Super elem , C context ) throws E { return null ; } public R visitSuperConstructorInvocation ( SuperConstructorInvocation elem , C context ) throws E { return null ; } public R visitSwitchCaseLabel ( SwitchCaseLabel elem , C context ) throws E { return null ; } public R visitSwitchDefaultLabel ( SwitchDefaultLabel elem , C context ) throws E { return null ; } public R visitSwitchStatement ( SwitchStatement elem , C context ) throws E { return null ; } public R visitSynchronizedStatement ( SynchronizedStatement elem , C context ) throws E { return null ; } public R visitThis ( This elem , C context ) throws E { return null ; } public R visitThrowStatement ( ThrowStatement elem , C context ) throws E { return null ; } public R visitTryStatement ( TryStatement elem , C context ) throws E { return null ; } public R visitTypeParameterDeclaration ( TypeParameterDeclaration elem , C context ) throws E { return null ; } public R visitUnaryExpression ( UnaryExpression elem , C context ) throws E { return null ; } public R visitVariableDeclarator ( VariableDeclarator elem , C context ) throws E { return null ; } public R visitWhileStatement ( WhileStatement elem , C context ) throws E { return null ; } public R visitWildcard ( Wildcard elem , C context ) throws E { return null ; } } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface LocalVariableDeclaration extends Statement , ForInitializer { List < ? extends Attribute > getModifiers ( ) ; Type getType ( ) ; List < ? extends VariableDeclarator > getVariableDeclarators ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface QualifiedName extends Name { Name getQualifier ( ) ; SimpleName getSimpleName ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ArrayType extends Type { Type getComponentType ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public enum PostfixOperator { INCREMENT ( "" ) , DECREMENT ( "" ) , ; private final String symbol ; private PostfixOperator ( String symbol ) { assert symbol != null ; this . symbol = symbol ; } public String getSymbol ( ) { return this . symbol ; } public static PostfixOperator fromSymbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } return SymbolToPostfixOperator . get ( symbol ) ; } private static class SymbolToPostfixOperator { private static final Map < String , PostfixOperator > REVERSE_DICTIONARY ; static { Map < String , PostfixOperator > map = new HashMap < String , PostfixOperator > ( ) ; for ( PostfixOperator elem : PostfixOperator . values ( ) ) { map . put ( elem . getSymbol ( ) , elem ) ; } REVERSE_DICTIONARY = Collections . unmodifiableMap ( map ) ; } static PostfixOperator get ( String key ) { return REVERSE_DICTIONARY . get ( key ) ; } } } package com . asakusafw . utils . java . model . syntax ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; public enum ModelKind { ALTERNATE_CONSTRUCTOR_INVOCATION ( AlternateConstructorInvocation . class , new PropertyKind [ ] { PropertyKind . CONSTRUCTOR_INVOCATION_TYPE_ARGUMENTS , PropertyKind . CONSTRUCTOR_INVOCATION_ARGUMENTS , } ) , ANNOTATION_DECLARATION ( AnnotationDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . TYPE_DECLARATION_NAME , PropertyKind . TYPE_DECLARATION_BODY_DECLARATIONS , } ) , ANNOTATION_ELEMENT ( AnnotationElement . class , new PropertyKind [ ] { PropertyKind . ANNOTATION_ELEMENT_NAME , PropertyKind . ANNOTATION_ELEMENT_EXPRESSION , } ) , ANNOTATION_ELEMENT_DECLARATION ( AnnotationElementDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . ANNOTATION_ELEMENT_DECLARATION_TYPE , PropertyKind . ANNOTATION_ELEMENT_DECLARATION_NAME , PropertyKind . ANNOTATION_ELEMENT_DECLARATION_DEFAULT_EXPRESSION , } ) , ARRAY_ACCESS_EXPRESSION ( ArrayAccessExpression . class , new PropertyKind [ ] { PropertyKind . ARRAY_ACCESS_EXPRESSION_ARRAY , PropertyKind . ARRAY_ACCESS_EXPRESSION_INDEX , } ) , ARRAY_CREATION_EXPRESSION ( ArrayCreationExpression . class , new PropertyKind [ ] { PropertyKind . ARRAY_CREATION_EXPRESSION_TYPE , PropertyKind . ARRAY_CREATION_EXPRESSION_DIMENSION_EXPRESSIONS , PropertyKind . ARRAY_CREATION_EXPRESSION_ARRAY_INITIALIZER , } ) , ARRAY_INITIALIZER ( ArrayInitializer . class , new PropertyKind [ ] { PropertyKind . ARRAY_INITIALIZER_ELEMENTS , } ) , ARRAY_TYPE ( ArrayType . class , new PropertyKind [ ] { PropertyKind . ARRAY_TYPE_COMPONENT_TYPE , } ) , ASSERT_STATEMENT ( AssertStatement . class , new PropertyKind [ ] { PropertyKind . ASSERT_STATEMENT_EXPRESSION , PropertyKind . ASSERT_STATEMENT_MESSAGE , } ) , ASSIGNMENT_EXPRESSION ( AssignmentExpression . class , new PropertyKind [ ] { PropertyKind . ASSIGNMENT_EXPRESSION_LEFT_HAND_SIDE , PropertyKind . ASSIGNMENT_EXPRESSION_OPERATOR , PropertyKind . ASSIGNMENT_EXPRESSION_RIGHT_HAND_SIDE , } ) , BASIC_TYPE ( BasicType . class , new PropertyKind [ ] { PropertyKind . BASIC_TYPE_TYPE_KIND , } ) , BLOCK ( Block . class , new PropertyKind [ ] { PropertyKind . BLOCK_STATEMENTS , } ) , BLOCK_COMMENT ( BlockComment . class , new PropertyKind [ ] { PropertyKind . BLOCK_COMMENT_STRING , } ) , BREAK_STATEMENT ( BreakStatement . class , new PropertyKind [ ] { PropertyKind . BRANCH_STATEMENT_TARGET , } ) , CAST_EXPRESSION ( CastExpression . class , new PropertyKind [ ] { PropertyKind . CAST_EXPRESSION_TYPE , PropertyKind . CAST_EXPRESSION_EXPRESSION , } ) , CATCH_CLAUSE ( CatchClause . class , new PropertyKind [ ] { PropertyKind . CATCH_CLAUSE_PARAMETER , PropertyKind . CATCH_CLAUSE_BODY , } ) , CLASS_BODY ( ClassBody . class , new PropertyKind [ ] { PropertyKind . CLASS_BODY_BODY_DECLARATIONS , } ) , CLASS_DECLARATION ( ClassDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . TYPE_DECLARATION_NAME , PropertyKind . CLASS_DECLARATION_TYPE_PARAMETERS , PropertyKind . CLASS_DECLARATION_SUPER_CLASS , PropertyKind . CLASS_DECLARATION_SUPER_INTERFACE_TYPES , PropertyKind . TYPE_DECLARATION_BODY_DECLARATIONS , } ) , CLASS_INSTANCE_CREATION_EXPRESSION ( ClassInstanceCreationExpression . class , new PropertyKind [ ] { PropertyKind . CLASS_INSTANCE_CREATION_EXPRESSION_QUALIFIER , PropertyKind . CLASS_INSTANCE_CREATION_EXPRESSION_TYPE_ARGUMENTS , PropertyKind . CLASS_INSTANCE_CREATION_EXPRESSION_TYPE , PropertyKind . CLASS_INSTANCE_CREATION_EXPRESSION_ARGUMENTS , PropertyKind . CLASS_INSTANCE_CREATION_EXPRESSION_BODY , } ) , CLASS_LITERAL ( ClassLiteral . class , new PropertyKind [ ] { PropertyKind . CLASS_LITERAL_TYPE , } ) , COMPILATION_UNIT ( CompilationUnit . class , new PropertyKind [ ] { PropertyKind . COMPILATION_UNIT_PACKAGE_DECLARATION , PropertyKind . COMPILATION_UNIT_IMPORT_DECLARATIONS , PropertyKind . COMPILATION_UNIT_TYPE_DECLARATIONS , PropertyKind . COMPILATION_UNIT_COMMENTS , } ) , CONDITIONAL_EXPRESSION ( ConditionalExpression . class , new PropertyKind [ ] { PropertyKind . CONDITIONAL_EXPRESSION_CONDITION , PropertyKind . CONDITIONAL_EXPRESSION_THEN_EXPRESSION , PropertyKind . CONDITIONAL_EXPRESSION_ELSE_EXPRESSION , } ) , CONSTRUCTOR_DECLARATION ( ConstructorDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_TYPE_PARAMETERS , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_NAME , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_FORMAL_PARAMETERS , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_EXCEPTION_TYPES , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_BODY , } ) , CONTINUE_STATEMENT ( ContinueStatement . class , new PropertyKind [ ] { PropertyKind . BRANCH_STATEMENT_TARGET , } ) , DO_STATEMENT ( DoStatement . class , new PropertyKind [ ] { PropertyKind . DO_STATEMENT_BODY , PropertyKind . DO_STATEMENT_CONDITION , } ) , DOC_BLOCK ( DocBlock . class , new PropertyKind [ ] { PropertyKind . DOC_BLOCK_TAG , PropertyKind . DOC_BLOCK_ELEMENTS , } ) , DOC_FIELD ( DocField . class , new PropertyKind [ ] { PropertyKind . DOC_FIELD_TYPE , PropertyKind . DOC_FIELD_NAME , } ) , DOC_METHOD ( DocMethod . class , new PropertyKind [ ] { PropertyKind . DOC_METHOD_TYPE , PropertyKind . DOC_METHOD_NAME , PropertyKind . DOC_METHOD_FORMAL_PARAMETERS , } ) , DOC_METHOD_PARAMETER ( DocMethodParameter . class , new PropertyKind [ ] { PropertyKind . DOC_METHOD_PARAMETER_TYPE , PropertyKind . DOC_METHOD_PARAMETER_NAME , PropertyKind . DOC_METHOD_PARAMETER_VARIABLE_ARITY , } ) , DOC_TEXT ( DocText . class , new PropertyKind [ ] { PropertyKind . DOC_TEXT_STRING , } ) , EMPTY_STATEMENT ( EmptyStatement . class , new PropertyKind [ ] { } ) , ENHANCED_FOR_STATEMENT ( EnhancedForStatement . class , new PropertyKind [ ] { PropertyKind . ENHANCED_FOR_STATEMENT_PARAMETER , PropertyKind . ENHANCED_FOR_STATEMENT_EXPRESSION , PropertyKind . ENHANCED_FOR_STATEMENT_BODY , } ) , ENUM_CONSTANT_DECLARATION ( EnumConstantDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . ENUM_CONSTANT_DECLARATION_NAME , PropertyKind . ENUM_CONSTANT_DECLARATION_ARGUMENTS , PropertyKind . ENUM_CONSTANT_DECLARATION_BODY , } ) , ENUM_DECLARATION ( EnumDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . TYPE_DECLARATION_NAME , PropertyKind . ENUM_DECLARATION_SUPER_INTERFACE_TYPES , PropertyKind . ENUM_DECLARATION_CONSTANT_DECLARATIONS , PropertyKind . TYPE_DECLARATION_BODY_DECLARATIONS , } ) , EXPRESSION_STATEMENT ( ExpressionStatement . class , new PropertyKind [ ] { PropertyKind . EXPRESSION_STATEMENT_EXPRESSION , } ) , FIELD_ACCESS_EXPRESSION ( FieldAccessExpression . class , new PropertyKind [ ] { PropertyKind . FIELD_ACCESS_EXPRESSION_QUALIFIER , PropertyKind . FIELD_ACCESS_EXPRESSION_NAME , } ) , FIELD_DECLARATION ( FieldDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . FIELD_DECLARATION_TYPE , PropertyKind . FIELD_DECLARATION_VARIABLE_DECLARATORS , } ) , FOR_STATEMENT ( ForStatement . class , new PropertyKind [ ] { PropertyKind . FOR_STATEMENT_INITIALIZATION , PropertyKind . FOR_STATEMENT_CONDITION , PropertyKind . FOR_STATEMENT_UPDATE , PropertyKind . FOR_STATEMENT_BODY , } ) , FORMAL_PARAMETER_DECLARATION ( FormalParameterDeclaration . class , new PropertyKind [ ] { PropertyKind . FORMAL_PARAMETER_DECLARATION_MODIFIERS , PropertyKind . FORMAL_PARAMETER_DECLARATION_TYPE , PropertyKind . FORMAL_PARAMETER_DECLARATION_VARIABLE_ARITY , PropertyKind . FORMAL_PARAMETER_DECLARATION_NAME , PropertyKind . FORMAL_PARAMETER_DECLARATION_EXTRA_DIMENSIONS , } ) , IF_STATEMENT ( IfStatement . class , new PropertyKind [ ] { PropertyKind . IF_STATEMENT_CONDITION , PropertyKind . IF_STATEMENT_THEN_STATEMENT , PropertyKind . IF_STATEMENT_ELSE_STATEMENT , } ) , IMPORT_DECLARATION ( ImportDeclaration . class , new PropertyKind [ ] { PropertyKind . IMPORT_DECLARATION_IMPORT_KIND , PropertyKind . IMPORT_DECLARATION_NAME , } ) , INFIX_EXPRESSION ( InfixExpression . class , new PropertyKind [ ] { PropertyKind . INFIX_EXPRESSION_LEFT_OPERAND , PropertyKind . INFIX_EXPRESSION_OPERATOR , PropertyKind . INFIX_EXPRESSION_RIGHT_OPERAND , } ) , INITIALIZER_DECLARATION ( InitializerDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . INITIALIZER_DECLARATION_BODY , } ) , INSTANCEOF_EXPRESSION ( InstanceofExpression . class , new PropertyKind [ ] { PropertyKind . INSTANCEOF_EXPRESSION_EXPRESSION , PropertyKind . INSTANCEOF_EXPRESSION_TYPE , } ) , INTERFACE_DECLARATION ( InterfaceDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . TYPE_DECLARATION_NAME , PropertyKind . INTERFACE_DECLARATION_TYPE_PARAMETERS , PropertyKind . INTERFACE_DECLARATION_SUPER_INTERFACE_TYPES , PropertyKind . TYPE_DECLARATION_BODY_DECLARATIONS , } ) , JAVADOC ( Javadoc . class , new PropertyKind [ ] { PropertyKind . JAVADOC_BLOCKS , } ) , LABELED_STATEMENT ( LabeledStatement . class , new PropertyKind [ ] { PropertyKind . LABELED_STATEMENT_LABEL , PropertyKind . LABELED_STATEMENT_BODY , } ) , LINE_COMMENT ( LineComment . class , new PropertyKind [ ] { PropertyKind . LINE_COMMENT_STRING , } ) , LITERAL ( Literal . class , new PropertyKind [ ] { PropertyKind . LITERAL_TOKEN , } ) , LOCAL_CLASS_DECLARATION ( LocalClassDeclaration . class , new PropertyKind [ ] { PropertyKind . LOCAL_CLASS_DECLARATION_DECLARATION , } ) , LOCAL_VARIABLE_DECLARATION ( LocalVariableDeclaration . class , new PropertyKind [ ] { PropertyKind . LOCAL_VARIABLE_DECLARATION_MODIFIERS , PropertyKind . LOCAL_VARIABLE_DECLARATION_TYPE , PropertyKind . LOCAL_VARIABLE_DECLARATION_VARIABLE_DECLARATORS , } ) , MARKER_ANNOTATION ( MarkerAnnotation . class , new PropertyKind [ ] { PropertyKind . ANNOTATION_TYPE , } ) , METHOD_DECLARATION ( MethodDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_BODY_DECLARATION_JAVADOC , PropertyKind . TYPE_BODY_DECLARATION_MODIFIERS , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_TYPE_PARAMETERS , PropertyKind . METHOD_DECLARATION_RETURN_TYPE , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_NAME , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_FORMAL_PARAMETERS , PropertyKind . METHOD_DECLARATION_EXTRA_DIMENSIONS , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_EXCEPTION_TYPES , PropertyKind . METHOD_OR_CONSTRUCTOR_DECLARATION_BODY , } ) , METHOD_INVOCATION_EXPRESSION ( MethodInvocationExpression . class , new PropertyKind [ ] { PropertyKind . METHOD_INVOCATION_EXPRESSION_QUALIFIER , PropertyKind . METHOD_INVOCATION_EXPRESSION_TYPE_ARGUMENTS , PropertyKind . METHOD_INVOCATION_EXPRESSION_NAME , PropertyKind . METHOD_INVOCATION_EXPRESSION_ARGUMENTS , } ) , MODIFIER ( Modifier . class , new PropertyKind [ ] { PropertyKind . MODIFIER_MODIFIER_KIND , } ) , NAMED_TYPE ( NamedType . class , new PropertyKind [ ] { PropertyKind . NAMED_TYPE_NAME , } ) , NORMAL_ANNOTATION ( NormalAnnotation . class , new PropertyKind [ ] { PropertyKind . ANNOTATION_TYPE , PropertyKind . NORMAL_ANNOTATION_ELEMENTS , } ) , PACKAGE_DECLARATION ( PackageDeclaration . class , new PropertyKind [ ] { PropertyKind . PACKAGE_DECLARATION_JAVADOC , PropertyKind . PACKAGE_DECLARATION_ANNOTATIONS , PropertyKind . PACKAGE_DECLARATION_NAME , } ) , PARAMETERIZED_TYPE ( ParameterizedType . class , new PropertyKind [ ] { PropertyKind . PARAMETERIZED_TYPE_TYPE , PropertyKind . PARAMETERIZED_TYPE_TYPE_ARGUMENTS , } ) , PARENTHESIZED_EXPRESSION ( ParenthesizedExpression . class , new PropertyKind [ ] { PropertyKind . PARENTHESIZED_EXPRESSION_EXPRESSION , } ) , POSTFIX_EXPRESSION ( PostfixExpression . class , new PropertyKind [ ] { PropertyKind . POSTFIX_EXPRESSION_OPERAND , PropertyKind . POSTFIX_EXPRESSION_OPERATOR , } ) , QUALIFIED_NAME ( QualifiedName . class , new PropertyKind [ ] { PropertyKind . QUALIFIED_NAME_QUALIFIER , PropertyKind . QUALIFIED_NAME_SIMPLE_NAME , } ) , QUALIFIED_TYPE ( QualifiedType . class , new PropertyKind [ ] { PropertyKind . QUALIFIED_TYPE_QUALIFIER , PropertyKind . QUALIFIED_TYPE_SIMPLE_NAME , } ) , RETURN_STATEMENT ( ReturnStatement . class , new PropertyKind [ ] { PropertyKind . RETURN_STATEMENT_EXPRESSION , } ) , SIMPLE_NAME ( SimpleName . class , new PropertyKind [ ] { PropertyKind . SIMPLE_NAME_STRING , } ) , SINGLE_ELEMENT_ANNOTATION ( SingleElementAnnotation . class , new PropertyKind [ ] { PropertyKind . ANNOTATION_TYPE , PropertyKind . SINGLE_ELEMENT_ANNOTATION_EXPRESSION , } ) , STATEMENT_EXPRESSION_LIST ( StatementExpressionList . class , new PropertyKind [ ] { PropertyKind . STATEMENT_EXPRESSION_LIST_EXPRESSIONS , } ) , SUPER ( Super . class , new PropertyKind [ ] { PropertyKind . KEYWORD_QUALIFIER , } ) , SUPER_CONSTRUCTOR_INVOCATION ( SuperConstructorInvocation . class , new PropertyKind [ ] { PropertyKind . SUPER_CONSTRUCTOR_INVOCATION_QUALIFIER , PropertyKind . CONSTRUCTOR_INVOCATION_TYPE_ARGUMENTS , PropertyKind . CONSTRUCTOR_INVOCATION_ARGUMENTS , } ) , SWITCH_CASE_LABEL ( SwitchCaseLabel . class , new PropertyKind [ ] { PropertyKind . SWITCH_CASE_LABEL_EXPRESSION , } ) , SWITCH_DEFAULT_LABEL ( SwitchDefaultLabel . class , new PropertyKind [ ] { } ) , SWITCH_STATEMENT ( SwitchStatement . class , new PropertyKind [ ] { PropertyKind . SWITCH_STATEMENT_EXPRESSION , PropertyKind . SWITCH_STATEMENT_STATEMENTS , } ) , SYNCHRONIZED_STATEMENT ( SynchronizedStatement . class , new PropertyKind [ ] { PropertyKind . SYNCHRONIZED_STATEMENT_EXPRESSION , PropertyKind . SYNCHRONIZED_STATEMENT_BODY , } ) , THIS ( This . class , new PropertyKind [ ] { PropertyKind . KEYWORD_QUALIFIER , } ) , THROW_STATEMENT ( ThrowStatement . class , new PropertyKind [ ] { PropertyKind . THROW_STATEMENT_EXPRESSION , } ) , TRY_STATEMENT ( TryStatement . class , new PropertyKind [ ] { PropertyKind . TRY_STATEMENT_TRY_BLOCK , PropertyKind . TRY_STATEMENT_CATCH_CLAUSES , PropertyKind . TRY_STATEMENT_FINALLY_BLOCK , } ) , TYPE_PARAMETER_DECLARATION ( TypeParameterDeclaration . class , new PropertyKind [ ] { PropertyKind . TYPE_PARAMETER_DECLARATION_NAME , PropertyKind . TYPE_PARAMETER_DECLARATION_TYPE_BOUNDS , } ) , UNARY_EXPRESSION ( UnaryExpression . class , new PropertyKind [ ] { PropertyKind . UNARY_EXPRESSION_OPERATOR , PropertyKind . UNARY_EXPRESSION_OPERAND , } ) , VARIABLE_DECLARATOR ( VariableDeclarator . class , new PropertyKind [ ] { PropertyKind . VARIABLE_DECLARATOR_NAME , PropertyKind . VARIABLE_DECLARATOR_EXTRA_DIMENSIONS , PropertyKind . VARIABLE_DECLARATOR_INITIALIZER , } ) , WHILE_STATEMENT ( WhileStatement . class , new PropertyKind [ ] { PropertyKind . WHILE_STATEMENT_CONDITION , PropertyKind . WHILE_STATEMENT_BODY , } ) , WILDCARD ( Wildcard . class , new PropertyKind [ ] { PropertyKind . WILDCARD_BOUND_KIND , PropertyKind . WILDCARD_TYPE_BOUND , } ) , ; private Class < ? extends Model > interfaceType ; private List < PropertyKind > properties ; private ModelKind ( Class < ? extends Model > interfaceType , PropertyKind [ ] properties ) { assert interfaceType != null ; assert properties != null ; this . interfaceType = interfaceType ; this . properties = Collections . unmodifiableList ( Arrays . asList ( properties ) ) ; } public Class < ? extends Model > getInterfaceType ( ) { return interfaceType ; } public List < PropertyKind > getProperties ( ) { return properties ; } } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface Javadoc extends Comment { List < ? extends DocBlock > getBlocks ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface NamedType extends Type , DocElement { Name getName ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface ArrayAccessExpression extends Expression { Expression getArray ( ) ; Expression getIndex ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface TypeBodyDeclaration extends Model { Javadoc getJavadoc ( ) ; List < ? extends Attribute > getModifiers ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface IfStatement extends Statement { Expression getCondition ( ) ; Statement getThenStatement ( ) ; Statement getElseStatement ( ) ; } package com . asakusafw . utils . java . model . syntax ; public abstract class StrictVisitor < R , C , E extends Throwable > extends Visitor < R , C , E > { @ Override public R visitAlternateConstructorInvocation ( AlternateConstructorInvocation elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitAnnotationDeclaration ( AnnotationDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitAnnotationElement ( AnnotationElement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitAnnotationElementDeclaration ( AnnotationElementDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitArrayAccessExpression ( ArrayAccessExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitArrayCreationExpression ( ArrayCreationExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitArrayInitializer ( ArrayInitializer elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitArrayType ( ArrayType elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitAssertStatement ( AssertStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitAssignmentExpression ( AssignmentExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitBasicType ( BasicType elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitBlock ( Block elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitBlockComment ( BlockComment elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitBreakStatement ( BreakStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitCastExpression ( CastExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitCatchClause ( CatchClause elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitClassBody ( ClassBody elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitClassDeclaration ( ClassDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitClassInstanceCreationExpression ( ClassInstanceCreationExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitClassLiteral ( ClassLiteral elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitCompilationUnit ( CompilationUnit elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitConditionalExpression ( ConditionalExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitConstructorDeclaration ( ConstructorDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitContinueStatement ( ContinueStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitDoStatement ( DoStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitDocBlock ( DocBlock elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitDocField ( DocField elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitDocMethod ( DocMethod elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitDocMethodParameter ( DocMethodParameter elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitDocText ( DocText elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitEmptyStatement ( EmptyStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitEnhancedForStatement ( EnhancedForStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitEnumConstantDeclaration ( EnumConstantDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitEnumDeclaration ( EnumDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitExpressionStatement ( ExpressionStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitFieldAccessExpression ( FieldAccessExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitFieldDeclaration ( FieldDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitForStatement ( ForStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitFormalParameterDeclaration ( FormalParameterDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitIfStatement ( IfStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitImportDeclaration ( ImportDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitInfixExpression ( InfixExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitInitializerDeclaration ( InitializerDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitInstanceofExpression ( InstanceofExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitInterfaceDeclaration ( InterfaceDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitJavadoc ( Javadoc elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitLabeledStatement ( LabeledStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitLineComment ( LineComment elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitLiteral ( Literal elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitLocalClassDeclaration ( LocalClassDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitLocalVariableDeclaration ( LocalVariableDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitMarkerAnnotation ( MarkerAnnotation elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitMethodDeclaration ( MethodDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitMethodInvocationExpression ( MethodInvocationExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitModifier ( Modifier elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitNamedType ( NamedType elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitNormalAnnotation ( NormalAnnotation elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitPackageDeclaration ( PackageDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitParameterizedType ( ParameterizedType elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitParenthesizedExpression ( ParenthesizedExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitPostfixExpression ( PostfixExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitQualifiedName ( QualifiedName elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitQualifiedType ( QualifiedType elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitReturnStatement ( ReturnStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitSimpleName ( SimpleName elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitSingleElementAnnotation ( SingleElementAnnotation elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitStatementExpressionList ( StatementExpressionList elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitSuper ( Super elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitSuperConstructorInvocation ( SuperConstructorInvocation elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitSwitchCaseLabel ( SwitchCaseLabel elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitSwitchDefaultLabel ( SwitchDefaultLabel elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitSwitchStatement ( SwitchStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitSynchronizedStatement ( SynchronizedStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitThis ( This elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitThrowStatement ( ThrowStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitTryStatement ( TryStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitTypeParameterDeclaration ( TypeParameterDeclaration elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitUnaryExpression ( UnaryExpression elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitVariableDeclarator ( VariableDeclarator elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitWhileStatement ( WhileStatement elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } @ Override public R visitWildcard ( Wildcard elem , C context ) throws E { throw new UnsupportedOperationException ( "" ) ; } } package com . asakusafw . utils . java . model . syntax ; public interface UnaryExpression extends Expression { UnaryOperator getOperator ( ) ; Expression getOperand ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface ArrayInitializer extends Expression { List < ? extends Expression > getElements ( ) ; } package com . asakusafw . utils . java . model . syntax ; import java . util . List ; public interface TryStatement extends Statement { Block getTryBlock ( ) ; List < ? extends CatchClause > getCatchClauses ( ) ; Block getFinallyBlock ( ) ; } package com . asakusafw . utils . java . model . syntax ; public interface DocElement extends Model { } package com . asakusafw . utils . java . model . syntax ; public enum PropertyKind { ANNOTATION_TYPE ( Annotation . class , "" ) , ANNOTATION_ELEMENT_NAME ( AnnotationElement . class , "" ) , ANNOTATION_ELEMENT_EXPRESSION ( AnnotationElement . class , "" ) , ANNOTATION_ELEMENT_DECLARATION_TYPE ( AnnotationElementDeclaration . class , "" ) , ANNOTATION_ELEMENT_DECLARATION_NAME ( AnnotationElementDeclaration . class , "" ) , ANNOTATION_ELEMENT_DECLARATION_DEFAULT_EXPRESSION ( AnnotationElementDeclaration . class , "" ) , ARRAY_ACCESS_EXPRESSION_ARRAY ( ArrayAccessExpression . class , "" ) , ARRAY_ACCESS_EXPRESSION_INDEX ( ArrayAccessExpression . class , "" ) , ARRAY_CREATION_EXPRESSION_TYPE ( ArrayCreationExpression . class , "" ) , ARRAY_CREATION_EXPRESSION_DIMENSION_EXPRESSIONS ( ArrayCreationExpression . class , "" ) , ARRAY_CREATION_EXPRESSION_ARRAY_INITIALIZER ( ArrayCreationExpression . class , "" ) , ARRAY_INITIALIZER_ELEMENTS ( ArrayInitializer . class , "" ) , ARRAY_TYPE_COMPONENT_TYPE ( ArrayType . class , "" ) , ASSERT_STATEMENT_EXPRESSION ( AssertStatement . class , "" ) , ASSERT_STATEMENT_MESSAGE ( AssertStatement . class , "" ) , ASSIGNMENT_EXPRESSION_LEFT_HAND_SIDE ( AssignmentExpression . class , "" ) , ASSIGNMENT_EXPRESSION_OPERATOR ( AssignmentExpression . class , "" ) , ASSIGNMENT_EXPRESSION_RIGHT_HAND_SIDE ( AssignmentExpression . class , "" ) , BASIC_TYPE_TYPE_KIND ( BasicType . class , "" ) , BLOCK_STATEMENTS ( Block . class , "" ) , BLOCK_COMMENT_STRING ( BlockComment . class , "" ) , BRANCH_STATEMENT_TARGET ( BranchStatement . class , "" ) , CAST_EXPRESSION_TYPE ( CastExpression . class , "" ) , CAST_EXPRESSION_EXPRESSION ( CastExpression . class , "" ) , CATCH_CLAUSE_PARAMETER ( CatchClause . class , "" ) , CATCH_CLAUSE_BODY ( CatchClause . class , "" ) , CLASS_BODY_BODY_DECLARATIONS ( ClassBody . class , "" ) , CLASS_DECLARATION_TYPE_PARAMETERS ( ClassDeclaration . class , "" ) , CLASS_DECLARATION_SUPER_CLASS ( ClassDeclaration . class , "" ) , CLASS_DECLARATION_SUPER_INTERFACE_TYPES ( ClassDeclaration . class , "" ) , CLASS_INSTANCE_CREATION_EXPRESSION_QUALIFIER ( ClassInstanceCreationExpression . class , "" ) , CLASS_INSTANCE_CREATION_EXPRESSION_TYPE_ARGUMENTS ( ClassInstanceCreationExpression . class , "" ) , CLASS_INSTANCE_CREATION_EXPRESSION_TYPE ( ClassInstanceCreationExpression . class , "" ) , CLASS_INSTANCE_CREATION_EXPRESSION_ARGUMENTS ( ClassInstanceCreationExpression . class , "" ) , CLASS_INSTANCE_CREATION_EXPRESSION_BODY ( ClassInstanceCreationExpression . class , "" ) , CLASS_LITERAL_TYPE ( ClassLiteral . class , "" ) , COMPILATION_UNIT_PACKAGE_DECLARATION ( CompilationUnit . class , "" ) , COMPILATION_UNIT_IMPORT_DECLARATIONS ( CompilationUnit . class , "" ) , COMPILATION_UNIT_TYPE_DECLARATIONS ( CompilationUnit . class , "" ) , COMPILATION_UNIT_COMMENTS ( CompilationUnit . class , "" ) , CONDITIONAL_EXPRESSION_CONDITION ( ConditionalExpression . class , "" ) , CONDITIONAL_EXPRESSION_THEN_EXPRESSION ( ConditionalExpression . class , "" ) , CONDITIONAL_EXPRESSION_ELSE_EXPRESSION ( ConditionalExpression . class , "" ) , CONSTRUCTOR_INVOCATION_TYPE_ARGUMENTS ( ConstructorInvocation . class , "" ) , CONSTRUCTOR_INVOCATION_ARGUMENTS ( ConstructorInvocation . class , "" ) , DO_STATEMENT_BODY ( DoStatement . class , "" ) , DO_STATEMENT_CONDITION ( DoStatement . class , "" ) , DOC_BLOCK_TAG ( DocBlock . class , "" ) , DOC_BLOCK_ELEMENTS ( DocBlock . class , "" ) , DOC_FIELD_TYPE ( DocField . class , "" ) , DOC_FIELD_NAME ( DocField . class , "" ) , DOC_METHOD_TYPE ( DocMethod . class , "" ) , DOC_METHOD_NAME ( DocMethod . class , "" ) , DOC_METHOD_FORMAL_PARAMETERS ( DocMethod . class , "" ) , DOC_METHOD_PARAMETER_TYPE ( DocMethodParameter . class , "" ) , DOC_METHOD_PARAMETER_NAME ( DocMethodParameter . class , "" ) , DOC_METHOD_PARAMETER_VARIABLE_ARITY ( DocMethodParameter . class , "" ) , DOC_TEXT_STRING ( DocText . class , "" ) , ENHANCED_FOR_STATEMENT_PARAMETER ( EnhancedForStatement . class , "" ) , ENHANCED_FOR_STATEMENT_EXPRESSION ( EnhancedForStatement . class , "" ) , ENHANCED_FOR_STATEMENT_BODY ( EnhancedForStatement . class , "" ) , ENUM_CONSTANT_DECLARATION_NAME ( EnumConstantDeclaration . class , "" ) , ENUM_CONSTANT_DECLARATION_ARGUMENTS ( EnumConstantDeclaration . class , "" ) , ENUM_CONSTANT_DECLARATION_BODY ( EnumConstantDeclaration . class , "" ) , ENUM_DECLARATION_SUPER_INTERFACE_TYPES ( EnumDeclaration . class , "" ) , ENUM_DECLARATION_CONSTANT_DECLARATIONS ( EnumDeclaration . class , "" ) , EXPRESSION_STATEMENT_EXPRESSION ( ExpressionStatement . class , "" ) , FIELD_ACCESS_EXPRESSION_QUALIFIER ( FieldAccessExpression . class , "" ) , FIELD_ACCESS_EXPRESSION_NAME ( FieldAccessExpression . class , "" ) , FIELD_DECLARATION_TYPE ( FieldDeclaration . class , "" ) , FIELD_DECLARATION_VARIABLE_DECLARATORS ( FieldDeclaration . class , "" ) , FOR_STATEMENT_INITIALIZATION ( ForStatement . class , "" ) , FOR_STATEMENT_CONDITION ( ForStatement . class , "" ) , FOR_STATEMENT_UPDATE ( ForStatement . class , "" ) , FOR_STATEMENT_BODY ( ForStatement . class , "" ) , FORMAL_PARAMETER_DECLARATION_MODIFIERS ( FormalParameterDeclaration . class , "" ) , FORMAL_PARAMETER_DECLARATION_TYPE ( FormalParameterDeclaration . class , "" ) , FORMAL_PARAMETER_DECLARATION_VARIABLE_ARITY ( FormalParameterDeclaration . class , "" ) , FORMAL_PARAMETER_DECLARATION_NAME ( FormalParameterDeclaration . class , "" ) , FORMAL_PARAMETER_DECLARATION_EXTRA_DIMENSIONS ( FormalParameterDeclaration . class , "" ) , IF_STATEMENT_CONDITION ( IfStatement . class , "" ) , IF_STATEMENT_THEN_STATEMENT ( IfStatement . class , "" ) , IF_STATEMENT_ELSE_STATEMENT ( IfStatement . class , "" ) , IMPORT_DECLARATION_IMPORT_KIND ( ImportDeclaration . class , "" ) , IMPORT_DECLARATION_NAME ( ImportDeclaration . class , "" ) , INFIX_EXPRESSION_LEFT_OPERAND ( InfixExpression . class , "" ) , INFIX_EXPRESSION_OPERATOR ( InfixExpression . class , "" ) , INFIX_EXPRESSION_RIGHT_OPERAND ( InfixExpression . class , "" ) , INITIALIZER_DECLARATION_BODY ( InitializerDeclaration . class , "" ) , INSTANCEOF_EXPRESSION_EXPRESSION ( InstanceofExpression . class , "" ) , INSTANCEOF_EXPRESSION_TYPE ( InstanceofExpression . class , "" ) , INTERFACE_DECLARATION_TYPE_PARAMETERS ( InterfaceDeclaration . class , "" ) , INTERFACE_DECLARATION_SUPER_INTERFACE_TYPES ( InterfaceDeclaration . class , "" ) , JAVADOC_BLOCKS ( Javadoc . class , "" ) , KEYWORD_QUALIFIER ( Keyword . class , "" ) , LABELED_STATEMENT_LABEL ( LabeledStatement . class , "" ) , LABELED_STATEMENT_BODY ( LabeledStatement . class , "" ) , LINE_COMMENT_STRING ( LineComment . class , "" ) , LITERAL_TOKEN ( Literal . class , "" ) , LOCAL_CLASS_DECLARATION_DECLARATION ( LocalClassDeclaration . class , "" ) , LOCAL_VARIABLE_DECLARATION_MODIFIERS ( LocalVariableDeclaration . class , "" ) , LOCAL_VARIABLE_DECLARATION_TYPE ( LocalVariableDeclaration . class , "" ) , LOCAL_VARIABLE_DECLARATION_VARIABLE_DECLARATORS ( LocalVariableDeclaration . class , "" ) , METHOD_DECLARATION_RETURN_TYPE ( MethodDeclaration . class , "" ) , METHOD_DECLARATION_EXTRA_DIMENSIONS ( MethodDeclaration . class , "" ) , METHOD_INVOCATION_EXPRESSION_QUALIFIER ( MethodInvocationExpression . class , "" ) , METHOD_INVOCATION_EXPRESSION_TYPE_ARGUMENTS ( MethodInvocationExpression . class , "" ) , METHOD_INVOCATION_EXPRESSION_NAME ( MethodInvocationExpression . class , "" ) , METHOD_INVOCATION_EXPRESSION_ARGUMENTS ( MethodInvocationExpression . class , "" ) , METHOD_OR_CONSTRUCTOR_DECLARATION_TYPE_PARAMETERS ( MethodOrConstructorDeclaration . class , "" ) , METHOD_OR_CONSTRUCTOR_DECLARATION_NAME ( MethodOrConstructorDeclaration . class , "" ) , METHOD_OR_CONSTRUCTOR_DECLARATION_FORMAL_PARAMETERS ( MethodOrConstructorDeclaration . class , "" ) , METHOD_OR_CONSTRUCTOR_DECLARATION_EXCEPTION_TYPES ( MethodOrConstructorDeclaration . class , "" ) , METHOD_OR_CONSTRUCTOR_DECLARATION_BODY ( MethodOrConstructorDeclaration . class , "" ) , MODIFIER_MODIFIER_KIND ( Modifier . class , "" ) , NAMED_TYPE_NAME ( NamedType . class , "" ) , NORMAL_ANNOTATION_ELEMENTS ( NormalAnnotation . class , "" ) , PACKAGE_DECLARATION_JAVADOC ( PackageDeclaration . class , "" ) , PACKAGE_DECLARATION_ANNOTATIONS ( PackageDeclaration . class , "" ) , PACKAGE_DECLARATION_NAME ( PackageDeclaration . class , "" ) , PARAMETERIZED_TYPE_TYPE ( ParameterizedType . class , "" ) , PARAMETERIZED_TYPE_TYPE_ARGUMENTS ( ParameterizedType . class , "" ) , PARENTHESIZED_EXPRESSION_EXPRESSION ( ParenthesizedExpression . class , "" ) , POSTFIX_EXPRESSION_OPERAND ( PostfixExpression . class , "" ) , POSTFIX_EXPRESSION_OPERATOR ( PostfixExpression . class , "" ) , QUALIFIED_NAME_QUALIFIER ( QualifiedName . class , "" ) , QUALIFIED_NAME_SIMPLE_NAME ( QualifiedName . class , "" ) , QUALIFIED_TYPE_QUALIFIER ( QualifiedType . class , "" ) , QUALIFIED_TYPE_SIMPLE_NAME ( QualifiedType . class , "" ) , RETURN_STATEMENT_EXPRESSION ( ReturnStatement . class , "" ) , SIMPLE_NAME_STRING ( SimpleName . class , "" ) , SINGLE_ELEMENT_ANNOTATION_EXPRESSION ( SingleElementAnnotation . class , "" ) , STATEMENT_EXPRESSION_LIST_EXPRESSIONS ( StatementExpressionList . class , "" ) , SUPER_CONSTRUCTOR_INVOCATION_QUALIFIER ( SuperConstructorInvocation . class , "" ) , SWITCH_CASE_LABEL_EXPRESSION ( SwitchCaseLabel . class , "" ) , SWITCH_STATEMENT_EXPRESSION ( SwitchStatement . class , "" ) , SWITCH_STATEMENT_STATEMENTS ( SwitchStatement . class , "" ) , SYNCHRONIZED_STATEMENT_EXPRESSION ( SynchronizedStatement . class , "" ) , SYNCHRONIZED_STATEMENT_BODY ( SynchronizedStatement . class , "" ) , THROW_STATEMENT_EXPRESSION ( ThrowStatement . class , "" ) , TRY_STATEMENT_TRY_BLOCK ( TryStatement . class , "" ) , TRY_STATEMENT_CATCH_CLAUSES ( TryStatement . class , "" ) , TRY_STATEMENT_FINALLY_BLOCK ( TryStatement . class , "" ) , TYPE_BODY_DECLARATION_JAVADOC ( TypeBodyDeclaration . class , "" ) , TYPE_BODY_DECLARATION_MODIFIERS ( TypeBodyDeclaration . class , "" ) , TYPE_DECLARATION_NAME ( TypeDeclaration . class , "" ) , TYPE_DECLARATION_BODY_DECLARATIONS ( TypeDeclaration . class , "" ) , TYPE_PARAMETER_DECLARATION_NAME ( TypeParameterDeclaration . class , "" ) , TYPE_PARAMETER_DECLARATION_TYPE_BOUNDS ( TypeParameterDeclaration . class , "" ) , UNARY_EXPRESSION_OPERATOR ( UnaryExpression . class , "" ) , UNARY_EXPRESSION_OPERAND ( UnaryExpression . class , "" ) , VARIABLE_DECLARATOR_NAME ( VariableDeclarator . class , "" ) , VARIABLE_DECLARATOR_EXTRA_DIMENSIONS ( VariableDeclarator . class , "" ) , VARIABLE_DECLARATOR_INITIALIZER ( VariableDeclarator . class , "" ) , WHILE_STATEMENT_CONDITION ( WhileStatement . class , "" ) , WHILE_STATEMENT_BODY ( WhileStatement . class , "" ) , WILDCARD_BOUND_KIND ( Wildcard . class , "" ) , WILDCARD_TYPE_BOUND ( Wildcard . class , "" ) , ; private Class < ? extends Model > ownerType ; private String name ; private PropertyKind ( Class < ? extends Model > ownerType , String name ) { assert ownerType != null ; assert name != null ; this . ownerType = ownerType ; this . name = name ; } public Class < ? extends Model > getOwnerType ( ) { return ownerType ; } public String getPropertyName ( ) { return name ; } @ Override public String toString ( ) { return java . text . MessageFormat . format ( "" , getOwnerType ( ) . getName ( ) , getPropertyName ( ) ) ; } } package com . asakusafw . utils . java . model . syntax ; public interface Modifier extends Attribute { ModifierKind getModifierKind ( ) ; } package com . asakusafw . utils . java . model . util ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . regex . Pattern ; import com . asakusafw . utils . java . model . syntax . DocBlock ; import com . asakusafw . utils . java . model . syntax . DocElement ; import com . asakusafw . utils . java . model . syntax . DocMethodParameter ; import com . asakusafw . utils . java . model . syntax . DocText ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; public class JavadocBuilder { private static final Pattern ESCAPE = Pattern . compile ( "" ) ; private ModelFactory f ; private List < DocBlock > blocks ; private String currentTag ; private List < DocElement > elements ; public JavadocBuilder ( ModelFactory factory ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } this . f = factory ; this . blocks = new ArrayList < DocBlock > ( ) ; this . currentTag = "" ; this . elements = new ArrayList < DocElement > ( ) ; } public JavadocBuilder copy ( ) { JavadocBuilder copy = new JavadocBuilder ( f ) ; copy . blocks = new ArrayList < DocBlock > ( blocks ) ; copy . currentTag = currentTag ; copy . elements = new ArrayList < DocElement > ( elements ) ; return copy ; } public Javadoc toJavadoc ( ) { flushBlock ( "" ) ; return f . newJavadoc ( blocks ) ; } public JavadocBuilder block ( String tag ) { if ( tag == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tag . startsWith ( "" ) ) { flushBlock ( tag ) ; } else { flushBlock ( "" + tag ) ; } return this ; } public JavadocBuilder inline ( DocElement element ) { if ( element == null ) { throw new IllegalArgumentException ( "" ) ; } elements . add ( element ) ; return this ; } public JavadocBuilder inline ( List < ? extends DocElement > elems ) { if ( elems == null ) { throw new IllegalArgumentException ( "" ) ; } elements . addAll ( elems ) ; return this ; } public JavadocBuilder param ( String name ) { return param ( f . newSimpleName ( name ) ) ; } public JavadocBuilder param ( SimpleName name ) { block ( "" ) ; elements . add ( name ) ; return this ; } public JavadocBuilder typeParam ( String name ) { return typeParam ( f . newSimpleName ( name ) ) ; } public JavadocBuilder typeParam ( SimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } block ( "" ) ; elements . add ( f . newDocText ( "" ) ) ; elements . add ( name ) ; elements . add ( f . newDocText ( ">" ) ) ; return this ; } public JavadocBuilder typeParam ( Type typeVariable ) { if ( typeVariable == null ) { throw new IllegalArgumentException ( "" ) ; } if ( typeVariable . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } NamedType named = ( NamedType ) typeVariable ; if ( named . getModelKind ( ) != ModelKind . SIMPLE_NAME ) { throw new IllegalArgumentException ( "" ) ; } return typeParam ( ( SimpleName ) named . getName ( ) ) ; } public JavadocBuilder returns ( ) { block ( "" ) ; return this ; } public JavadocBuilder exception ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } block ( "" ) ; elements . add ( ( ( NamedType ) type ) . getName ( ) ) ; return this ; } public JavadocBuilder seeType ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } return see ( ( ( NamedType ) type ) . getName ( ) ) ; } public JavadocBuilder seeField ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return seeField ( null , f . newSimpleName ( name ) ) ; } public JavadocBuilder seeField ( Type type , String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return seeField ( type , f . newSimpleName ( name ) ) ; } public JavadocBuilder seeField ( SimpleName name ) { return seeField ( null , name ) ; } public JavadocBuilder seeField ( Type type , SimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return see ( f . newDocField ( type , name ) ) ; } public JavadocBuilder seeMethod ( String name , Type ... parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return seeMethod ( null , f . newSimpleName ( name ) , Arrays . asList ( parameterTypes ) ) ; } public JavadocBuilder seeMethod ( String name , List < ? extends Type > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return seeMethod ( null , f . newSimpleName ( name ) , parameterTypes ) ; } public JavadocBuilder seeMethod ( SimpleName name , Type ... parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return seeMethod ( null , name , Arrays . asList ( parameterTypes ) ) ; } public JavadocBuilder seeMethod ( SimpleName name , List < ? extends Type > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return seeMethod ( null , name , parameterTypes ) ; } public JavadocBuilder seeMethod ( Type type , String name , Type ... parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return seeMethod ( type , f . newSimpleName ( name ) , Arrays . asList ( parameterTypes ) ) ; } public JavadocBuilder seeMethod ( Type type , String name , List < ? extends Type > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return seeMethod ( type , f . newSimpleName ( name ) , parameterTypes ) ; } public JavadocBuilder seeMethod ( Type type , SimpleName name , Type ... parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return seeMethod ( type , name , Arrays . asList ( parameterTypes ) ) ; } public JavadocBuilder seeMethod ( Type type , SimpleName name , List < ? extends Type > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } List < DocMethodParameter > parameters = new ArrayList < DocMethodParameter > ( ) ; for ( Type parameterType : parameterTypes ) { parameters . add ( f . newDocMethodParameter ( parameterType , null , false ) ) ; } return see ( f . newDocMethod ( type , name , parameters ) ) ; } public JavadocBuilder see ( DocElement element ) { if ( element == null ) { throw new IllegalArgumentException ( "" ) ; } block ( "" ) ; elements . add ( element ) ; return this ; } public JavadocBuilder text ( String pattern , Object ... arguments ) { elements . add ( escape ( pattern , arguments ) ) ; return this ; } public JavadocBuilder code ( String pattern , Object ... arguments ) { elements . add ( f . newDocBlock ( "" , Collections . singletonList ( escape ( pattern , arguments ) ) ) ) ; return this ; } public JavadocBuilder linkType ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } return link ( ( ( NamedType ) type ) . getName ( ) ) ; } public JavadocBuilder linkField ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return linkField ( null , f . newSimpleName ( name ) ) ; } public JavadocBuilder linkField ( Type type , String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return linkField ( type , f . newSimpleName ( name ) ) ; } public JavadocBuilder linkField ( SimpleName name ) { return linkField ( null , name ) ; } public JavadocBuilder linkField ( Type type , SimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return link ( f . newDocField ( type , name ) ) ; } public JavadocBuilder linkMethod ( String name , Type ... parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return linkMethod ( null , f . newSimpleName ( name ) , Arrays . asList ( parameterTypes ) ) ; } public JavadocBuilder linkMethod ( String name , List < ? extends Type > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return linkMethod ( null , f . newSimpleName ( name ) , parameterTypes ) ; } public JavadocBuilder linkMethod ( SimpleName name , Type ... parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return linkMethod ( null , name , Arrays . asList ( parameterTypes ) ) ; } public JavadocBuilder linkMethod ( SimpleName name , List < ? extends Type > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return linkMethod ( null , name , parameterTypes ) ; } public JavadocBuilder linkMethod ( Type type , String name , Type ... parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return linkMethod ( type , f . newSimpleName ( name ) , Arrays . asList ( parameterTypes ) ) ; } public JavadocBuilder linkMethod ( Type type , String name , List < ? extends Type > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return linkMethod ( type , f . newSimpleName ( name ) , parameterTypes ) ; } public JavadocBuilder linkMethod ( Type type , SimpleName name , Type ... parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } return linkMethod ( type , name , Arrays . asList ( parameterTypes ) ) ; } public JavadocBuilder linkMethod ( Type type , SimpleName name , List < ? extends Type > parameterTypes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( parameterTypes == null ) { throw new IllegalArgumentException ( "" ) ; } List < DocMethodParameter > parameters = new ArrayList < DocMethodParameter > ( ) ; for ( Type parameterType : parameterTypes ) { parameters . add ( f . newDocMethodParameter ( parameterType , null , false ) ) ; } return link ( f . newDocMethod ( type , name , parameters ) ) ; } public JavadocBuilder link ( DocElement element ) { if ( element == null ) { throw new IllegalArgumentException ( "" ) ; } elements . add ( f . newDocBlock ( "" , Collections . singletonList ( element ) ) ) ; return this ; } private DocText escape ( String pattern , Object ... arguments ) { String text = MessageFormat . format ( pattern , arguments ) ; String escaped = ESCAPE . matcher ( text ) . replaceAll ( "" ) ; return f . newDocText ( escaped ) ; } private void flushBlock ( String nextTag ) { if ( currentTag . length ( ) >= || elements . isEmpty ( ) == false ) { blocks . add ( f . newDocBlock ( currentTag , elements ) ) ; elements . clear ( ) ; } this . currentTag = nextTag ; } } package com . asakusafw . utils . java . model . util ; import java . util . ArrayList ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . AnnotationElement ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Modifier ; import com . asakusafw . utils . java . model . syntax . ModifierKind ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . Type ; public class AttributeBuilder { private final ModelFactory f ; private final List < Attribute > attributes ; public AttributeBuilder ( ModelFactory factory ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } this . f = factory ; this . attributes = new ArrayList < Attribute > ( ) ; } public AttributeBuilder copy ( ) { AttributeBuilder copy = new AttributeBuilder ( f ) ; copy . attributes . addAll ( attributes ) ; return copy ; } public List < Attribute > toAttributes ( ) { return new ArrayList < Attribute > ( attributes ) ; } public List < Modifier > toModifiers ( ) { List < Modifier > results = new ArrayList < Modifier > ( ) ; for ( Attribute attribute : toAttributes ( ) ) { if ( attribute instanceof Modifier ) { results . add ( ( Modifier ) attribute ) ; } } return results ; } public List < Annotation > toAnnotations ( ) { List < Annotation > results = new ArrayList < Annotation > ( ) ; for ( Attribute attribute : toAttributes ( ) ) { if ( attribute instanceof Annotation ) { results . add ( ( Annotation ) attribute ) ; } } return results ; } public AttributeBuilder Public ( ) { return modifier ( ModifierKind . PUBLIC ) ; } public AttributeBuilder Protected ( ) { return modifier ( ModifierKind . PROTECTED ) ; } public AttributeBuilder Private ( ) { return modifier ( ModifierKind . PRIVATE ) ; } public AttributeBuilder Static ( ) { return modifier ( ModifierKind . STATIC ) ; } public AttributeBuilder Abstract ( ) { return modifier ( ModifierKind . ABSTRACT ) ; } public AttributeBuilder Native ( ) { return modifier ( ModifierKind . NATIVE ) ; } public AttributeBuilder Final ( ) { return modifier ( ModifierKind . FINAL ) ; } public AttributeBuilder Synchronized ( ) { return modifier ( ModifierKind . SYNCHRONIZED ) ; } public AttributeBuilder Transient ( ) { return modifier ( ModifierKind . TRANSIENT ) ; } public AttributeBuilder Volatile ( ) { return modifier ( ModifierKind . VOLATILE ) ; } public AttributeBuilder Strictfp ( ) { return modifier ( ModifierKind . STRICTFP ) ; } public AttributeBuilder modifier ( ModifierKind modifier ) { if ( modifier == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newModifier ( modifier ) ) ; } public AttributeBuilder annotation ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } return annotation ( f . newMarkerAnnotation ( ( NamedType ) type ) ) ; } public AttributeBuilder annotation ( java . lang . reflect . Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return annotation ( Models . toType ( f , type ) ) ; } public AttributeBuilder annotation ( Type type , Expression value ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } return annotation ( f . newSingleElementAnnotation ( ( NamedType ) type , value ) ) ; } public AttributeBuilder annotation ( java . lang . reflect . Type type , Expression value ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return annotation ( Models . toType ( f , type ) , value ) ; } public AttributeBuilder annotation ( Type type , String elementName , Expression elementValue ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue == null ) { throw new IllegalArgumentException ( "" ) ; } List < AnnotationElement > elements = new ArrayList < AnnotationElement > ( ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName ) , elementValue ) ) ; return annotation ( f . newNormalAnnotation ( ( NamedType ) type , elements ) ) ; } public AttributeBuilder annotation ( Type type , String elementName1 , Expression elementValue1 , String elementName2 , Expression elementValue2 ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName1 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue1 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName2 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue2 == null ) { throw new IllegalArgumentException ( "" ) ; } List < AnnotationElement > elements = new ArrayList < AnnotationElement > ( ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName1 ) , elementValue1 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName2 ) , elementValue2 ) ) ; return annotation ( f . newNormalAnnotation ( ( NamedType ) type , elements ) ) ; } public AttributeBuilder annotation ( Type type , String elementName1 , Expression elementValue1 , String elementName2 , Expression elementValue2 , String elementName3 , Expression elementValue3 ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName1 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue1 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName2 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue2 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName3 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue3 == null ) { throw new IllegalArgumentException ( "" ) ; } List < AnnotationElement > elements = new ArrayList < AnnotationElement > ( ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName1 ) , elementValue1 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName2 ) , elementValue2 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName3 ) , elementValue3 ) ) ; return annotation ( f . newNormalAnnotation ( ( NamedType ) type , elements ) ) ; } public AttributeBuilder annotation ( Type type , String elementName1 , Expression elementValue1 , String elementName2 , Expression elementValue2 , String elementName3 , Expression elementValue3 , String elementName4 , Expression elementValue4 ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName1 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue1 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName2 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue2 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName3 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue3 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName4 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue4 == null ) { throw new IllegalArgumentException ( "" ) ; } List < AnnotationElement > elements = new ArrayList < AnnotationElement > ( ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName1 ) , elementValue1 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName2 ) , elementValue2 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName3 ) , elementValue3 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName4 ) , elementValue4 ) ) ; return annotation ( f . newNormalAnnotation ( ( NamedType ) type , elements ) ) ; } public AttributeBuilder annotation ( Type type , String elementName1 , Expression elementValue1 , String elementName2 , Expression elementValue2 , String elementName3 , Expression elementValue3 , String elementName4 , Expression elementValue4 , String elementName5 , Expression elementValue5 ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName1 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue1 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName2 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue2 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName3 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue3 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName4 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue4 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementName5 == null ) { throw new IllegalArgumentException ( "" ) ; } if ( elementValue5 == null ) { throw new IllegalArgumentException ( "" ) ; } List < AnnotationElement > elements = new ArrayList < AnnotationElement > ( ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName1 ) , elementValue1 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName2 ) , elementValue2 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName3 ) , elementValue3 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName4 ) , elementValue4 ) ) ; elements . add ( f . newAnnotationElement ( f . newSimpleName ( elementName5 ) , elementValue5 ) ) ; return annotation ( f . newNormalAnnotation ( ( NamedType ) type , elements ) ) ; } public AttributeBuilder annotation ( Annotation annotation ) { if ( annotation == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( annotation ) ; } private AttributeBuilder chain ( Attribute attribute ) { assert attribute != null ; attributes . add ( attribute ) ; return this ; } } package com . asakusafw . utils . java . model . util ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . SimpleName ; public class Filer extends Emitter { private final File outputPath ; private final Charset encoding ; public Filer ( File outputPath , Charset encoding ) { if ( outputPath == null ) { throw new IllegalArgumentException ( "" ) ; } if ( encoding == null ) { throw new IllegalArgumentException ( "" ) ; } this . outputPath = outputPath ; this . encoding = encoding ; } public File getFolderFor ( PackageDeclaration packageDeclOrNull ) { if ( packageDeclOrNull == null ) { return outputPath ; } return getFolderFor ( packageDeclOrNull . getName ( ) ) ; } public File getFolderFor ( Name packageNameOrNull ) { if ( packageNameOrNull == null ) { return outputPath ; } File path = outputPath ; for ( SimpleName segment : Models . toList ( packageNameOrNull ) ) { path = new File ( path , segment . getToken ( ) ) ; } return path ; } @ Override public PrintWriter openFor ( PackageDeclaration packageDeclOrNull , String subPath ) throws IOException { if ( subPath == null ) { throw new IllegalArgumentException ( "" ) ; } File folder = getFolderFor ( packageDeclOrNull ) ; File file = new File ( folder , subPath ) ; return open ( file ) ; } private PrintWriter open ( File file ) throws IOException { assert file != null ; File parent = file . getParentFile ( ) ; if ( parent != null ) { if ( parent . mkdirs ( ) == false && parent . exists ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , file ) ) ; } } return new PrintWriter ( file , encoding . name ( ) ) ; } } package com . asakusafw . utils . java . model . util ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public final class CommentEmitTrait { private static final String REGEX_LINE_DELIMITER = "" ; private List < String > contents ; public CommentEmitTrait ( List < String > contents ) { if ( contents == null ) { throw new IllegalArgumentException ( "" ) ; } this . contents = new ArrayList < String > ( contents . size ( ) ) ; for ( String line : contents ) { String [ ] splitted = line . split ( REGEX_LINE_DELIMITER ) ; for ( String s : splitted ) { this . contents . add ( s ) ; } } this . contents = Collections . unmodifiableList ( this . contents ) ; } public List < String > getContents ( ) { return this . contents ; } } package com . asakusafw . utils . java . model . util ; package com . asakusafw . utils . java . model . util ; import java . io . PrintWriter ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import com . asakusafw . utils . java . internal . model . syntax . ModelFactoryImpl ; import com . asakusafw . utils . java . internal . model . util . LiteralAnalyzer ; import com . asakusafw . utils . java . internal . model . util . ModelEmitter ; import com . asakusafw . utils . java . internal . model . util . ReflectionTypeMapper ; import com . asakusafw . utils . java . model . syntax . ArrayInitializer ; import com . asakusafw . utils . java . model . syntax . BasicTypeKind ; import com . asakusafw . utils . java . model . syntax . ClassLiteral ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . Literal ; import com . asakusafw . utils . java . model . syntax . Model ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; public final class Models { private static final Map < Class < ? > , BasicTypeKind > WRAPPER_TYPE_KINDS ; static { Map < Class < ? > , BasicTypeKind > map = new HashMap < Class < ? > , BasicTypeKind > ( ) ; map . put ( Byte . class , BasicTypeKind . BYTE ) ; map . put ( Short . class , BasicTypeKind . SHORT ) ; map . put ( Integer . class , BasicTypeKind . INT ) ; map . put ( Long . class , BasicTypeKind . LONG ) ; map . put ( Float . class , BasicTypeKind . FLOAT ) ; map . put ( Double . class , BasicTypeKind . DOUBLE ) ; map . put ( Character . class , BasicTypeKind . CHAR ) ; map . put ( Boolean . class , BasicTypeKind . BOOLEAN ) ; WRAPPER_TYPE_KINDS = map ; } public static ModelFactory getModelFactory ( ) { return new ModelFactoryImpl ( ) ; } public static List < SimpleName > toList ( Name name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } ModelKind kind = name . getModelKind ( ) ; if ( kind == ModelKind . SIMPLE_NAME ) { return Collections . singletonList ( ( SimpleName ) name ) ; } else { LinkedList < SimpleName > result = new LinkedList < SimpleName > ( ) ; Name current = name ; do { QualifiedName qname = ( QualifiedName ) current ; result . addFirst ( qname . getSimpleName ( ) ) ; current = qname . getQualifier ( ) ; } while ( current . getModelKind ( ) == ModelKind . QUALIFIED_NAME ) ; assert current . getModelKind ( ) == ModelKind . SIMPLE_NAME ; result . addFirst ( ( SimpleName ) current ) ; return result ; } } public static Name append ( ModelFactory factory , Name prefix , String rest ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rest == null ) { throw new IllegalArgumentException ( "" ) ; } Name name = Models . toName ( factory , rest ) ; return append ( factory , prefix , name ) ; } public static Name append ( ModelFactory factory , Name ... names ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( names == null ) { throw new IllegalArgumentException ( "" ) ; } if ( names . length == ) { throw new IllegalArgumentException ( "" ) ; } if ( names . length == ) { return names [ ] ; } Name current = names [ ] ; for ( int i = ; i < names . length ; i ++ ) { for ( SimpleName segment : toList ( names [ i ] ) ) { current = factory . newQualifiedName ( current , segment ) ; } } return current ; } public static void emit ( Model model , PrintWriter writer ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } if ( writer == null ) { throw new IllegalArgumentException ( "" ) ; } ModelEmitter emitter = new ModelEmitter ( writer ) ; emitter . emit ( model ) ; } public static Type toType ( ModelFactory factory , java . lang . reflect . Type type ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return new ReflectionTypeMapper ( ) . dispatch ( type , factory ) ; } public static Name toName ( ModelFactory factory , String nameString ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( nameString == null ) { throw new IllegalArgumentException ( "" ) ; } String [ ] segments = nameString . trim ( ) . split ( "" ) ; if ( segments . length == || segments [ ] . length ( ) == ) { throw new IllegalArgumentException ( "" ) ; } Name left = factory . newSimpleName ( segments [ ] ) ; for ( int i = ; i < segments . length ; i ++ ) { SimpleName right = factory . newSimpleName ( segments [ i ] ) ; left = factory . newQualifiedName ( left , right ) ; } return left ; } public static Name toName ( ModelFactory factory , Enum < ? > constant ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( constant == null ) { throw new IllegalArgumentException ( "" ) ; } Name typeName = toName ( factory , constant . getDeclaringClass ( ) . getName ( ) ) ; return factory . newQualifiedName ( typeName , factory . newSimpleName ( constant . name ( ) ) ) ; } public static Expression toLiteral ( ModelFactory factory , byte value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . intLiteralOf ( value ) ; return factory . newCastExpression ( factory . newBasicType ( BasicTypeKind . BYTE ) , factory . newLiteral ( token ) ) ; } public static Expression toLiteral ( ModelFactory factory , short value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . intLiteralOf ( value ) ; return factory . newCastExpression ( factory . newBasicType ( BasicTypeKind . SHORT ) , factory . newLiteral ( token ) ) ; } public static Literal toLiteral ( ModelFactory factory , int value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . intLiteralOf ( value ) ; return factory . newLiteral ( token ) ; } public static Literal toLiteral ( ModelFactory factory , long value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . longLiteralOf ( value ) ; return factory . newLiteral ( token ) ; } public static Literal toLiteral ( ModelFactory factory , float value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . floatLiteralOf ( value ) ; return factory . newLiteral ( token ) ; } public static Literal toLiteral ( ModelFactory factory , double value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . doubleLiteralOf ( value ) ; return factory . newLiteral ( token ) ; } public static Literal toLiteral ( ModelFactory factory , boolean value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . booleanLiteralOf ( value ) ; return factory . newLiteral ( token ) ; } public static Literal toLiteral ( ModelFactory factory , char value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . charLiteralOf ( value ) ; return factory . newLiteral ( token ) ; } public static Literal toLiteral ( ModelFactory factory , String value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . stringLiteralOf ( value ) ; return factory . newLiteral ( token ) ; } public static Expression toLiteral ( ModelFactory factory , Object value ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value == null ) { return toNullLiteral ( factory ) ; } Class < ? extends Object > valueClass = value . getClass ( ) ; BasicTypeKind kind = WRAPPER_TYPE_KINDS . get ( valueClass ) ; if ( kind != null ) { switch ( kind ) { case BYTE : return toLiteral ( factory , ( byte ) ( Byte ) value ) ; case SHORT : return toLiteral ( factory , ( short ) ( Short ) value ) ; case INT : return toLiteral ( factory , ( int ) ( Integer ) value ) ; case LONG : return toLiteral ( factory , ( long ) ( Long ) value ) ; case FLOAT : return toLiteral ( factory , ( float ) ( Float ) value ) ; case DOUBLE : return toLiteral ( factory , ( double ) ( Double ) value ) ; case CHAR : return toLiteral ( factory , ( char ) ( Character ) value ) ; case BOOLEAN : return toLiteral ( factory , ( boolean ) ( Boolean ) value ) ; default : throw new AssertionError ( kind ) ; } } else if ( valueClass == String . class ) { return toLiteral ( factory , ( String ) value ) ; } else if ( value instanceof java . lang . reflect . Type ) { return toClassLiteral ( factory , ( java . lang . reflect . Type ) value ) ; } throw new IllegalArgumentException ( MessageFormat . format ( "" , value , valueClass ) ) ; } public static ClassLiteral toClassLiteral ( ModelFactory factory , java . lang . reflect . Type type ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return factory . newClassLiteral ( Models . toType ( factory , type ) ) ; } public static Literal toNullLiteral ( ModelFactory factory ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } String token = LiteralAnalyzer . nullLiteral ( ) ; return factory . newLiteral ( token ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , int [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( int value : array ) { literals . add ( Models . toLiteral ( factory , value ) ) ; } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , float [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( float value : array ) { literals . add ( Models . toLiteral ( factory , value ) ) ; } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , long [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( long value : array ) { literals . add ( Models . toLiteral ( factory , value ) ) ; } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , double [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( double value : array ) { literals . add ( Models . toLiteral ( factory , value ) ) ; } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , char [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( char value : array ) { literals . add ( Models . toLiteral ( factory , value ) ) ; } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , boolean [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( boolean value : array ) { literals . add ( Models . toLiteral ( factory , value ) ) ; } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , byte [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( byte value : array ) { literals . add ( Models . toLiteral ( factory , value ) ) ; } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , short [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( short value : array ) { literals . add ( Models . toLiteral ( factory , value ) ) ; } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , String [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( String value : array ) { if ( value == null ) { literals . add ( Models . toNullLiteral ( factory ) ) ; } else { literals . add ( Models . toLiteral ( factory , value ) ) ; } } return factory . newArrayInitializer ( literals ) ; } public static ArrayInitializer toArrayInitializer ( ModelFactory factory , java . lang . reflect . Type [ ] array ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( array == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > literals = new ArrayList < Expression > ( ) ; for ( java . lang . reflect . Type value : array ) { if ( value == null ) { literals . add ( Models . toNullLiteral ( factory ) ) ; } else { literals . add ( Models . toClassLiteral ( factory , value ) ) ; } } return factory . newArrayInitializer ( literals ) ; } private Models ( ) { throw new AssertionError ( ) ; } } package com . asakusafw . utils . java . model . util ; public final class NoThrow extends RuntimeException { private static final long serialVersionUID = - ; private NoThrow ( ) { throw new AssertionError ( ) ; } } package com . asakusafw . utils . java . model . util ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ExpressionStatement ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . LocalVariableDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . PostfixOperator ; import com . asakusafw . utils . java . model . syntax . ReturnStatement ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . ThrowStatement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . UnaryOperator ; public class ExpressionBuilder { private ModelFactory f ; private Expression context ; public ExpressionBuilder ( ModelFactory factory , Expression context ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } this . f = factory ; this . context = context ; } public ExpressionBuilder copy ( ) { return new ExpressionBuilder ( f , context ) ; } public Expression toExpression ( ) { return context ; } public ExpressionStatement toStatement ( ) { return f . newExpressionStatement ( toExpression ( ) ) ; } public ThrowStatement toThrowStatement ( ) { return f . newThrowStatement ( toExpression ( ) ) ; } public ReturnStatement toReturnStatement ( ) { return f . newReturnStatement ( toExpression ( ) ) ; } public LocalVariableDeclaration toLocalVariableDeclaration ( Type type , String name ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return toLocalVariableDeclaration ( type , f . newSimpleName ( name ) ) ; } public LocalVariableDeclaration toLocalVariableDeclaration ( Type type , SimpleName name ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return f . newLocalVariableDeclaration ( type , name , context ) ; } public ExpressionBuilder apply ( InfixOperator operator , Expression right ) { if ( operator == null ) { throw new IllegalArgumentException ( "" ) ; } if ( right == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newInfixExpression ( context , operator , right ) ) ; } public ExpressionBuilder apply ( UnaryOperator operator ) { if ( operator == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newUnaryExpression ( operator , context ) ) ; } public ExpressionBuilder apply ( PostfixOperator operator ) { if ( operator == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newPostfixExpression ( context , operator ) ) ; } public ExpressionBuilder assignFrom ( Expression rightHandSide ) { if ( rightHandSide == null ) { throw new IllegalArgumentException ( "" ) ; } return assignFrom ( InfixOperator . ASSIGN , rightHandSide ) ; } public ExpressionBuilder assignFrom ( InfixOperator operator , Expression rightHandSide ) { if ( operator == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rightHandSide == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newAssignmentExpression ( context , operator , rightHandSide ) ) ; } public ExpressionBuilder castTo ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newCastExpression ( type , context ) ) ; } public ExpressionBuilder castTo ( java . lang . reflect . Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return castTo ( Models . toType ( f , type ) ) ; } public ExpressionBuilder instanceOf ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newInstanceofExpression ( context , type ) ) ; } public ExpressionBuilder instanceOf ( java . lang . reflect . Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return instanceOf ( Models . toType ( f , type ) ) ; } public ExpressionBuilder field ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return field ( f . newSimpleName ( name ) ) ; } public ExpressionBuilder field ( SimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newFieldAccessExpression ( context , name ) ) ; } public ExpressionBuilder array ( int index ) { return array ( Models . toLiteral ( f , index ) ) ; } public ExpressionBuilder array ( String index ) { if ( index == null ) { throw new IllegalArgumentException ( "" ) ; } return array ( Models . toName ( f , index ) ) ; } public ExpressionBuilder array ( Expression index ) { if ( index == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newArrayAccessExpression ( context , index ) ) ; } public ExpressionBuilder method ( String name , Expression ... arguments ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( Collections . < Type > emptyList ( ) , name , Arrays . asList ( arguments ) ) ; } public ExpressionBuilder method ( List < ? extends Type > typeArguments , String name , Expression ... arguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( typeArguments , name , Arrays . asList ( arguments ) ) ; } public ExpressionBuilder method ( String name , List < ? extends Expression > arguments ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( Collections . < Type > emptyList ( ) , name , arguments ) ; } public ExpressionBuilder method ( List < ? extends Type > typeArguments , String name , List < ? extends Expression > arguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( typeArguments , f . newSimpleName ( name ) , arguments ) ; } public ExpressionBuilder method ( SimpleName name , Expression ... arguments ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( Collections . < Type > emptyList ( ) , name , Arrays . asList ( arguments ) ) ; } public ExpressionBuilder method ( List < ? extends Type > typeArguments , SimpleName name , Expression ... arguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( typeArguments , name , Arrays . asList ( arguments ) ) ; } public ExpressionBuilder method ( SimpleName name , List < ? extends Expression > arguments ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( Collections . < Type > emptyList ( ) , name , arguments ) ; } public ExpressionBuilder method ( List < ? extends Type > typeArguments , SimpleName name , List < ? extends Expression > arguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newMethodInvocationExpression ( context , typeArguments , name , arguments ) ) ; } private ExpressionBuilder chain ( Expression expression ) { assert expression != null ; context = expression ; return this ; } } package com . asakusafw . utils . java . model . util ; import java . io . IOException ; import java . io . PrintWriter ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . Modifier ; import com . asakusafw . utils . java . model . syntax . ModifierKind ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; public abstract class Emitter { private static final String EXTENSION = "" ; private static final String PACKAGE_INFO = "" + EXTENSION ; public PrintWriter openFor ( CompilationUnit unit ) throws IOException { if ( unit == null ) { throw new IllegalArgumentException ( "" ) ; } TypeDeclaration primary = findPrimaryType ( unit ) ; if ( primary == null ) { return openFor ( unit . getPackageDeclaration ( ) , PACKAGE_INFO ) ; } return openFor ( unit . getPackageDeclaration ( ) , primary ) ; } public static TypeDeclaration findPrimaryType ( CompilationUnit unit ) { if ( unit == null ) { throw new IllegalArgumentException ( "" ) ; } TypeDeclaration first = null ; for ( TypeDeclaration decl : unit . getTypeDeclarations ( ) ) { if ( first == null ) { first = decl ; } for ( Attribute attribute : decl . getModifiers ( ) ) { if ( attribute instanceof Modifier ) { Modifier modifier = ( Modifier ) attribute ; if ( modifier . getModifierKind ( ) == ModifierKind . PUBLIC ) { return decl ; } } } } return first ; } private PrintWriter openFor ( PackageDeclaration packageDecl , TypeDeclaration typeDecl ) throws IOException { assert typeDecl != null ; String fileName = typeDecl . getName ( ) . getToken ( ) + EXTENSION ; return openFor ( packageDecl , fileName ) ; } public abstract PrintWriter openFor ( PackageDeclaration packageDeclOrNull , String subPath ) throws IOException ; } package com . asakusafw . utils . java . model . util ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import com . asakusafw . utils . java . model . syntax . ArrayType ; import com . asakusafw . utils . java . model . syntax . BasicType ; import com . asakusafw . utils . java . model . syntax . ImportDeclaration ; import com . asakusafw . utils . java . model . syntax . ImportKind ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . ParameterizedType ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . QualifiedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . StrictVisitor ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Wildcard ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; public class ImportBuilder { private final PackageDeclaration packageDecl ; private final Resolver resolver ; public ImportBuilder ( ModelFactory factory , PackageDeclaration packageDecl , Strategy strategy ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( strategy == null ) { throw new IllegalArgumentException ( "" ) ; } this . resolver = new Resolver ( factory , strategy , packageDecl ) ; this . packageDecl = packageDecl ; } public Type resolvePackageMember ( Name name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } Type type ; if ( name . getModelKind ( ) == ModelKind . SIMPLE_NAME ) { type = reservePackageMember ( ( SimpleName ) name ) ; } else { type = reservePackageMember ( ( QualifiedName ) name ) ; } return resolve ( type ) ; } private Type reservePackageMember ( SimpleName name ) { assert name != null ; if ( packageDecl == null ) { return resolver . factory . newNamedType ( name ) ; } else { Name qualified = Models . append ( resolver . factory , packageDecl . getName ( ) , name ) ; return resolver . factory . newNamedType ( qualified ) ; } } private Type reservePackageMember ( QualifiedName name ) { assert name != null ; List < SimpleName > list = name . toNameList ( ) ; Name current ; Iterator < SimpleName > iter = list . iterator ( ) ; assert iter . hasNext ( ) ; SimpleName first = iter . next ( ) ; if ( packageDecl == null ) { current = first ; } else { current = resolver . factory . newQualifiedName ( packageDecl . getName ( ) , first ) ; } resolver . reserved . put ( first , current ) ; while ( iter . hasNext ( ) ) { SimpleName next = iter . next ( ) ; current = resolver . factory . newQualifiedName ( current , next ) ; resolver . reserved . put ( next , current ) ; } return resolver . factory . newNamedType ( current ) ; } public Type resolve ( Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return type . accept ( resolver , null ) ; } public Type toType ( Name name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return resolve ( resolver . factory . newNamedType ( name ) ) ; } public Type toType ( java . lang . reflect . Type type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return resolve ( Models . toType ( resolver . factory , type ) ) ; } public List < ImportDeclaration > toImportDeclarations ( ) { ModelFactory f = resolver . factory ; Map < QualifiedName , SimpleName > imported = resolver . imported ; Set < Name > implicit = createImplicit ( ) ; List < ImportDeclaration > results = new ArrayList < ImportDeclaration > ( ) ; for ( QualifiedName name : imported . keySet ( ) ) { if ( implicit . contains ( name . getQualifier ( ) ) ) { continue ; } results . add ( f . newImportDeclaration ( ImportKind . SINGLE_TYPE , name ) ) ; } Collections . sort ( results , ImportComparator . INSTANCE ) ; return results ; } public PackageDeclaration getPackageDeclaration ( ) { return this . packageDecl ; } private Set < Name > createImplicit ( ) { Set < Name > implicit = new HashSet < Name > ( ) ; implicit . add ( Models . toName ( resolver . factory , "" ) ) ; if ( packageDecl != null ) { implicit . add ( packageDecl . getName ( ) ) ; } return implicit ; } private enum ImportComparator implements Comparator < ImportDeclaration > { INSTANCE , ; @ Override public int compare ( ImportDeclaration o1 , ImportDeclaration o2 ) { if ( o1 . getImportKind ( ) != o2 . getImportKind ( ) ) { return o1 . getImportKind ( ) . compareTo ( o2 . getImportKind ( ) ) ; } return o1 . getName ( ) . toNameString ( ) . compareTo ( o2 . getName ( ) . toNameString ( ) ) ; } } private static class Resolver extends StrictVisitor < Type , Void , NoThrow > { final Strategy strategy ; final Map < QualifiedName , SimpleName > imported ; final Map < SimpleName , Name > reserved ; private Set < Name > knownPackageNames = new HashSet < Name > ( ) ; final ModelFactory factory ; Resolver ( ModelFactory factory , Strategy strategy , PackageDeclaration packageDecl ) { this . factory = factory ; this . strategy = strategy ; this . knownPackageNames = new HashSet < Name > ( ) ; if ( packageDecl != null ) { Name current = packageDecl . getName ( ) ; while ( current instanceof QualifiedName ) { this . knownPackageNames . add ( current ) ; current = ( ( QualifiedName ) current ) . getQualifier ( ) ; } this . knownPackageNames . add ( current ) ; } this . imported = new HashMap < QualifiedName , SimpleName > ( ) ; this . reserved = new HashMap < SimpleName , Name > ( ) ; } @ Override public Type visitArrayType ( ArrayType elem , Void _ ) { Type component = elem . getComponentType ( ) . accept ( this , _ ) ; if ( elem . getComponentType ( ) . equals ( component ) ) { return elem ; } return factory . newArrayType ( component ) ; } @ Override public Type visitBasicType ( BasicType elem , Void _ ) { return elem ; } @ Override public Type visitNamedType ( NamedType elem , Void _ ) { Name name = elem . getName ( ) ; if ( name . getModelKind ( ) == ModelKind . SIMPLE_NAME ) { reserved . put ( ( SimpleName ) name , elem . getName ( ) ) ; return elem ; } LinkedList < SimpleName > segments = new LinkedList < SimpleName > ( ) ; name = normalize ( name , segments ) ; if ( name . getModelKind ( ) == ModelKind . SIMPLE_NAME ) { reserved . put ( ( SimpleName ) name , elem . getName ( ) ) ; return elem ; } QualifiedName qname = ( QualifiedName ) name ; SimpleName renamed = imported . get ( qname ) ; if ( renamed == null ) { if ( reserved . containsKey ( qname . getSimpleName ( ) ) && reserved . get ( qname . getSimpleName ( ) ) . equals ( qname ) == false ) { return elem ; } imported . put ( qname , qname . getSimpleName ( ) ) ; reserved . put ( qname . getSimpleName ( ) , qname ) ; } return factory . newNamedType ( Models . append ( factory , segments . toArray ( new Name [ segments . size ( ) ] ) ) ) ; } private Name normalize ( Name name , LinkedList < SimpleName > segments ) { Name current = name ; if ( strategy == Strategy . TOP_LEVEL ) { while ( isLikeEnclosingType ( current ) ) { QualifiedName qname = ( QualifiedName ) current ; segments . addFirst ( qname . getSimpleName ( ) ) ; current = qname . getQualifier ( ) ; } } if ( current . getModelKind ( ) == ModelKind . QUALIFIED_NAME ) { segments . addFirst ( ( ( QualifiedName ) current ) . getSimpleName ( ) ) ; } else { segments . addFirst ( ( SimpleName ) current ) ; } return current ; } private boolean isLikeEnclosingType ( Name name ) { assert name != null ; if ( name . getModelKind ( ) != ModelKind . QUALIFIED_NAME ) { return false ; } Name qualifier = ( ( QualifiedName ) name ) . getQualifier ( ) ; if ( knownPackageNames . contains ( qualifier ) ) { return false ; } SimpleName parent ; if ( qualifier . getModelKind ( ) == ModelKind . QUALIFIED_NAME ) { parent = ( ( QualifiedName ) qualifier ) . getSimpleName ( ) ; } else { parent = ( SimpleName ) qualifier ; } return isClassName ( parent ) ; } private boolean isClassName ( SimpleName name ) { assert name != null ; char first = name . getToken ( ) . charAt ( ) ; return Character . isUpperCase ( first ) ; } @ Override public Type visitParameterizedType ( ParameterizedType elem , Void _ ) { Type nonparameterized = elem . getType ( ) . accept ( this , _ ) ; List < Type > arguments = new ArrayList < Type > ( ) ; for ( Type t : elem . getTypeArguments ( ) ) { arguments . add ( t . accept ( this , _ ) ) ; } if ( nonparameterized . equals ( elem . getType ( ) ) && arguments . equals ( elem . getTypeArguments ( ) ) ) { return elem ; } return factory . newParameterizedType ( nonparameterized , arguments ) ; } @ Override public Type visitQualifiedType ( QualifiedType elem , Void _ ) { Type qualifier = elem . getQualifier ( ) . accept ( this , _ ) ; if ( qualifier . equals ( elem . getQualifier ( ) ) ) { return elem ; } return factory . newQualifiedType ( qualifier , elem . getSimpleName ( ) ) ; } @ Override public Type visitWildcard ( Wildcard elem , Void _ ) { if ( elem . getBoundKind ( ) == WildcardBoundKind . UNBOUNDED ) { return elem ; } Type bound = elem . getTypeBound ( ) . accept ( this , _ ) ; if ( bound . equals ( elem . getTypeBound ( ) ) ) { return elem ; } return factory . newWildcard ( elem . getBoundKind ( ) , bound ) ; } } public enum Strategy { TOP_LEVEL , ENCLOSING , } } package com . asakusafw . utils . java . model . util ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . ArrayInitializer ; import com . asakusafw . utils . java . model . syntax . ArrayType ; import com . asakusafw . utils . java . model . syntax . ClassBody ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; public class TypeBuilder { private ModelFactory f ; private Type context ; public TypeBuilder ( ModelFactory factory , Type context ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } this . f = factory ; this . context = context ; } public TypeBuilder copy ( ) { return new TypeBuilder ( f , context ) ; } public Type toType ( ) { return context ; } public NamedType toNamedType ( ) { if ( context . getModelKind ( ) != ModelKind . NAMED_TYPE ) { throw new IllegalStateException ( "" ) ; } return ( NamedType ) context ; } public ArrayType toArrayType ( ) { if ( context . getModelKind ( ) != ModelKind . ARRAY_TYPE ) { throw new IllegalStateException ( "" ) ; } return ( ArrayType ) context ; } public TypeBuilder parameterize ( Type ... typeArguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } return parameterize ( Arrays . asList ( typeArguments ) ) ; } public TypeBuilder parameterize ( List < ? extends Type > typeArguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( typeArguments . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } return chain ( f . newParameterizedType ( context , typeArguments ) ) ; } public TypeBuilder parameterize ( java . lang . reflect . Type ... typeArguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } List < Type > args = new ArrayList < Type > ( ) ; for ( java . lang . reflect . Type type : typeArguments ) { args . add ( Models . toType ( f , type ) ) ; } return parameterize ( args ) ; } public TypeBuilder enclose ( Name name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context . getModelKind ( ) == ModelKind . NAMED_TYPE ) { Name enclosed = Models . append ( f , toNamedType ( ) . getName ( ) , name ) ; return chain ( f . newNamedType ( enclosed ) ) ; } else { Type current = context ; for ( SimpleName segment : Models . toList ( name ) ) { current = f . newQualifiedType ( current , segment ) ; } return chain ( current ) ; } } public TypeBuilder enclose ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return enclose ( Models . toName ( f , name ) ) ; } public TypeBuilder array ( int dimensions ) { if ( dimensions < ) { throw new IllegalArgumentException ( "" ) ; } Type current = context ; for ( int i = ; i < dimensions ; i ++ ) { current = f . newArrayType ( current ) ; } return chain ( current ) ; } public ExpressionBuilder dotClass ( ) { return expr ( f . newClassLiteral ( context ) ) ; } public ExpressionBuilder newArray ( int ... dimensions ) { if ( dimensions == null ) { throw new IllegalArgumentException ( "" ) ; } List < Expression > exprs = new ArrayList < Expression > ( ) ; for ( int dim : dimensions ) { exprs . add ( Models . toLiteral ( f , dim ) ) ; } return newArray ( exprs ) ; } public ExpressionBuilder newArray ( Expression ... dimensions ) { if ( dimensions == null ) { throw new IllegalArgumentException ( "" ) ; } return newArray ( Arrays . asList ( dimensions ) ) ; } public ExpressionBuilder newArray ( List < ? extends Expression > dimensions ) { if ( dimensions == null ) { throw new IllegalArgumentException ( "" ) ; } return expr ( f . newArrayCreationExpression ( toArrayType ( ) , dimensions , null ) ) ; } public ExpressionBuilder newArray ( ArrayInitializer initializer ) { if ( initializer == null ) { throw new IllegalArgumentException ( "" ) ; } return expr ( f . newArrayCreationExpression ( toArrayType ( ) , Collections . < Expression > emptyList ( ) , initializer ) ) ; } public ExpressionBuilder newObject ( Expression ... arguments ) { if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return newObject ( Arrays . asList ( arguments ) , null ) ; } public ExpressionBuilder newObject ( List < ? extends Expression > arguments ) { return newObject ( arguments , null ) ; } public ExpressionBuilder newObject ( List < ? extends Expression > arguments , ClassBody anonymousClassBlock ) { if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return expr ( f . newClassInstanceCreationExpression ( null , Collections . < Type > emptyList ( ) , context , arguments , anonymousClassBlock ) ) ; } public ExpressionBuilder field ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return field ( f . newSimpleName ( name ) ) ; } public ExpressionBuilder field ( SimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return expr ( f . newQualifiedName ( toNamedType ( ) . getName ( ) , name ) ) ; } public ExpressionBuilder method ( String name , Expression ... arguments ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( Collections . < Type > emptyList ( ) , name , Arrays . asList ( arguments ) ) ; } public ExpressionBuilder method ( List < ? extends Type > typeArguments , String name , Expression ... arguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( typeArguments , name , Arrays . asList ( arguments ) ) ; } public ExpressionBuilder method ( String name , List < ? extends Expression > arguments ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( Collections . < Type > emptyList ( ) , name , arguments ) ; } public ExpressionBuilder method ( List < ? extends Type > typeArguments , String name , List < ? extends Expression > arguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( typeArguments , f . newSimpleName ( name ) , arguments ) ; } public ExpressionBuilder method ( SimpleName name , Expression ... arguments ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( Collections . < Type > emptyList ( ) , name , Arrays . asList ( arguments ) ) ; } public ExpressionBuilder method ( List < ? extends Type > typeArguments , SimpleName name , Expression ... arguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( typeArguments , name , Arrays . asList ( arguments ) ) ; } public ExpressionBuilder method ( SimpleName name , List < ? extends Expression > arguments ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return method ( Collections . < Type > emptyList ( ) , name , arguments ) ; } public ExpressionBuilder method ( List < ? extends Type > typeArguments , SimpleName name , List < ? extends Expression > arguments ) { if ( typeArguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } return expr ( f . newMethodInvocationExpression ( toNamedType ( ) . getName ( ) , typeArguments , name , arguments ) ) ; } private TypeBuilder chain ( Type type ) { assert type != null ; this . context = type ; return this ; } private ExpressionBuilder expr ( Expression expression ) { assert expression != null ; return new ExpressionBuilder ( f , expression ) ; } } package com . asakusafw . utils . java . internal . model . util ; import java . lang . reflect . GenericArrayType ; import java . lang . reflect . ParameterizedType ; import java . lang . reflect . Type ; import java . lang . reflect . TypeVariable ; import java . lang . reflect . WildcardType ; import java . text . MessageFormat ; public abstract class ReflectionTypeVisitor < R , C , E extends Throwable > { public final R dispatch ( Type type , C context ) throws E { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( type instanceof Class < ? > ) { return visitClass ( ( Class < ? > ) type , context ) ; } else if ( type instanceof GenericArrayType ) { return visitGenericArrayType ( ( GenericArrayType ) type , context ) ; } else if ( type instanceof ParameterizedType ) { return visitParameterizedType ( ( ParameterizedType ) type , context ) ; } else if ( type instanceof TypeVariable < ? > ) { return visitTypeVariable ( ( TypeVariable < ? > ) type , context ) ; } else if ( type instanceof WildcardType ) { return visitWildcardType ( ( WildcardType ) type , context ) ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , type , type . getClass ( ) . getSimpleName ( ) ) ) ; } } protected R visitClass ( Class < ? > type , C context ) throws E { return null ; } protected R visitGenericArrayType ( GenericArrayType type , C context ) throws E { return null ; } protected R visitParameterizedType ( ParameterizedType type , C context ) throws E { return null ; } protected R visitTypeVariable ( TypeVariable < ? > type , C context ) throws E { return null ; } protected R visitWildcardType ( WildcardType type , C context ) throws E { return null ; } } package com . asakusafw . utils . java . internal . model . util ; public enum LiteralTokenKind { INT , LONG , FLOAT , DOUBLE , BOOLEAN , CHAR , STRING , NULL , UNKNOWN , } package com . asakusafw . utils . java . internal . model . util ; import java . io . Serializable ; public class LiteralToken implements Serializable { private static final long serialVersionUID = ; public static final String TOKEN_TRUE = "" ; public static final String TOKEN_FALSE = "" ; public static final String TOKEN_NULL = "" ; private String text ; private transient LiteralTokenKind kind ; private transient Object value ; LiteralToken ( String text , LiteralTokenKind kind , Object value ) { if ( text == null ) { throw new IllegalArgumentException ( "" ) ; } if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value == null && kind != LiteralTokenKind . NULL ) { throw new IllegalArgumentException ( "" ) ; } this . text = text . intern ( ) ; this . kind = kind ; this . value = value ; } public LiteralTokenKind getKind ( ) { return this . kind ; } public String getText ( ) { return this . text ; } public Object getValue ( ) { return this . value ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + text . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final LiteralToken other = ( LiteralToken ) obj ; if ( text . equals ( other . text ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { return text ; } private Object readResolve ( ) { return LiteralAnalyzer . parse ( text ) ; } } package com . asakusafw . utils . java . internal . model . util ; package com . asakusafw . utils . java . internal . model . util ; import java . io . PrintWriter ; import java . util . Iterator ; import java . util . List ; import java . util . Map . Entry ; import java . util . SortedMap ; import java . util . TreeMap ; public class PrintEmitContext implements EmitContext { private static final String INDENT = "" ; private PrintWriter writer ; private State state ; private int indentation ; private boolean inDocComment ; private boolean inComment ; private int column ; private int bodyColumn ; private SortedMap < Integer , String > commentPool ; public PrintEmitContext ( PrintWriter writer ) { if ( writer == null ) { throw new IllegalArgumentException ( "" ) ; } this . writer = writer ; this . state = State . INIT ; this . indentation = ; this . inDocComment = false ; this . column = ; this . bodyColumn = ; this . commentPool = new TreeMap < Integer , String > ( ) ; } @ Override public void flushComments ( ) { flushComments ( commentPool ) ; } @ Override public void flushComments ( int location ) { SortedMap < Integer , String > head = commentPool . headMap ( location ) ; flushComments ( head ) ; } private void flushComments ( SortedMap < Integer , String > comments ) { assert comments != null ; if ( comments . isEmpty ( ) ) { return ; } inComment = true ; Iterator < Entry < Integer , String > > iter = comments . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Entry < Integer , String > next = iter . next ( ) ; before ( State . BLOCK_COMMENT ) ; putToken ( next . getValue ( ) ) ; iter . remove ( ) ; } inComment = false ; } @ Override public void keyword ( String keyword ) { if ( keyword == null ) { throw new IllegalArgumentException ( "" ) ; } before ( State . KEYWORD ) ; putToken ( keyword ) ; } @ Override public void symbol ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } before ( State . SYMBOL ) ; putToken ( symbol ) ; } @ Override public void immediate ( String immediate ) { if ( immediate == null ) { throw new IllegalArgumentException ( "" ) ; } before ( State . IMMEDIATE ) ; putToken ( immediate ) ; } @ Override public void operator ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } before ( State . OPERATOR ) ; putToken ( symbol ) ; } @ Override public void separator ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } before ( State . SEPARATOR ) ; putToken ( symbol ) ; } @ Override public void padding ( ) { before ( State . PADDING ) ; } @ Override public void comment ( int location , String content ) { if ( content == null ) { throw new IllegalArgumentException ( "" ) ; } commentPool . put ( location , content ) ; } @ Override public void classBlock ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } genericBlock ( direction ) ; } @ Override public void arrayInitializerBlock ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == EmitDirection . BEGIN ) { before ( State . SYMBOL ) ; putToken ( "" ) ; push ( ) ; } else { pop ( ) ; before ( State . SEPARATOR ) ; putToken ( "" ) ; } } @ Override public void statementBlock ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } genericBlock ( direction ) ; } @ Override public void switchLabel ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == EmitDirection . BEGIN ) { push ( ) ; } else { pop ( ) ; } } @ Override public void statement ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == EmitDirection . END ) { before ( State . LINE_END ) ; } } @ Override public void declaration ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == EmitDirection . END ) { before ( State . LINE_END ) ; } } @ Override public void docComment ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == EmitDirection . BEGIN ) { before ( State . LINE_END ) ; before ( State . BLOCK_START ) ; putToken ( "" ) ; this . inDocComment = true ; } else { this . inDocComment = false ; before ( State . BLOCK_END ) ; putToken ( "" ) ; } } @ Override public void docBlock ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } statement ( direction ) ; } @ Override public void docInlineBlock ( EmitDirection direction ) { if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == EmitDirection . BEGIN ) { before ( State . SYMBOL ) ; putToken ( "" ) ; } else { before ( State . SYMBOL ) ; putToken ( "" ) ; } } @ Override public void putBlockComment ( List < String > contents ) { if ( contents == null ) { throw new IllegalArgumentException ( "" ) ; } before ( State . BLOCK_COMMENT ) ; inComment = true ; putToken ( "" ) ; before ( State . LINE_END ) ; for ( String line : contents ) { before ( State . BLOCK_COMMENT ) ; putToken ( "" ) ; putToken ( line ) ; before ( State . LINE_END ) ; } before ( State . BLOCK_COMMENT ) ; putToken ( "" ) ; inComment = false ; before ( State . LINE_END ) ; } @ Override public void putLineComment ( String content ) { if ( content == null ) { throw new IllegalArgumentException ( "" ) ; } before ( State . BLOCK_COMMENT ) ; inComment = true ; putToken ( "" ) ; putToken ( content ) ; inComment = false ; before ( State . LINE_END ) ; } @ Override public void putInlineComment ( String content ) { if ( content == null ) { throw new IllegalArgumentException ( "" ) ; } before ( State . INLINE_COMMENT ) ; inComment = true ; putToken ( "" ) ; putToken ( content ) ; putToken ( "" ) ; inComment = false ; before ( State . SEPARATOR ) ; } private void genericBlock ( EmitDirection direction ) { assert direction != null ; if ( direction == EmitDirection . BEGIN ) { before ( State . BLOCK_START ) ; putToken ( "" ) ; push ( ) ; } else { pop ( ) ; before ( State . BLOCK_END ) ; putToken ( "" ) ; } } private void before ( State next ) { assert next != null ; State prev = state ; state = next ; switch ( prev ) { case INIT : { if ( next == State . LINE_END ) { state = State . INIT ; } break ; } case IMMEDIATE : case KEYWORD : { if ( next != State . PADDING && next != State . SYMBOL && next != State . SEPARATOR && next != State . LINE_END ) { putPadding ( ) ; } break ; } case OPERATOR : { if ( next != State . PADDING && next != State . SEPARATOR && next != State . LINE_END ) { putPadding ( ) ; } break ; } case SEPARATOR : { if ( next != State . PADDING && next != State . SYMBOL && next != State . SEPARATOR && next != State . LINE_END ) { putPadding ( ) ; } break ; } case SYMBOL : { break ; } case PADDING : { if ( next != State . PADDING ) { putPadding ( ) ; } break ; } case BLOCK_START : { if ( next != State . LINE_END ) { putLineBreak ( ) ; } break ; } case BLOCK_END : { if ( next == State . SEPARATOR ) { state = State . LINE_END ; } else if ( next == State . BLOCK_START ) { state = State . LINE_END ; } else if ( next != State . LINE_END ) { putLineBreak ( ) ; } break ; } case BLOCK_COMMENT : { if ( next != State . LINE_END ) { putLineBreak ( ) ; } break ; } case INLINE_COMMENT : { if ( next != State . LINE_END ) { putPadding ( ) ; } break ; } case LINE_END : { if ( next != State . LINE_END ) { putLineBreak ( ) ; } break ; } default : throw new AssertionError ( prev ) ; } } private void push ( ) { indentation ++ ; } private void pop ( ) { indentation -- ; } private void putToken ( String token ) { assert token != null ; int length = token . length ( ) ; if ( inComment == false && column + length > && bodyColumn + length > ) { putLineBreak ( true ) ; } writer . print ( token ) ; column += length ; bodyColumn += length ; } private void putPadding ( ) { writer . print ( "" ) ; column += ; bodyColumn += ; } private void putLineBreak ( ) { putLineBreak ( false ) ; } private void putLineBreak ( boolean wrap ) { writer . println ( ) ; column = ; for ( int i = ; i < indentation ; i ++ ) { writer . print ( INDENT ) ; column += INDENT . length ( ) ; } if ( wrap ) { writer . print ( INDENT ) ; writer . print ( INDENT ) ; column += INDENT . length ( ) * ; } if ( inDocComment ) { writer . print ( "" ) ; column += ; bodyColumn += ; } } private enum State { INIT , SYMBOL , IMMEDIATE , KEYWORD , OPERATOR , SEPARATOR , PADDING , BLOCK_START , BLOCK_END , BLOCK_COMMENT , INLINE_COMMENT , LINE_END , } } package com . asakusafw . utils . java . internal . model . util ; import java . util . List ; public interface EmitContext { void flushComments ( ) ; void flushComments ( int location ) ; void keyword ( String keyword ) ; void symbol ( String symbol ) ; void immediate ( String immediate ) ; void operator ( String symbol ) ; void separator ( String symbol ) ; void padding ( ) ; void comment ( int location , String content ) ; void classBlock ( EmitDirection direction ) ; void arrayInitializerBlock ( EmitDirection direction ) ; void statementBlock ( EmitDirection direction ) ; void switchLabel ( EmitDirection direction ) ; void statement ( EmitDirection direction ) ; void declaration ( EmitDirection direction ) ; void docComment ( EmitDirection direction ) ; void docBlock ( EmitDirection direction ) ; void docInlineBlock ( EmitDirection direction ) ; void putBlockComment ( List < String > contents ) ; void putLineComment ( String content ) ; void putInlineComment ( String content ) ; } package com . asakusafw . utils . java . internal . model . util ; import java . lang . reflect . GenericArrayType ; import java . lang . reflect . ParameterizedType ; import java . lang . reflect . TypeVariable ; import java . lang . reflect . WildcardType ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . utils . java . model . syntax . BasicTypeKind ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . NoThrow ; public class ReflectionTypeMapper extends ReflectionTypeVisitor < Type , ModelFactory , NoThrow > { private static final Map < Class < ? > , BasicTypeKind > BASIC_TYPES ; static { Map < Class < ? > , BasicTypeKind > map = new HashMap < Class < ? > , BasicTypeKind > ( ) ; for ( BasicTypeKind kind : BasicTypeKind . values ( ) ) { map . put ( kind . getJavaRepresentation ( ) , kind ) ; } BASIC_TYPES = Collections . unmodifiableMap ( map ) ; } @ Override protected Type visitClass ( Class < ? > type , ModelFactory context ) { if ( BASIC_TYPES . containsKey ( type ) ) { return context . newBasicType ( BASIC_TYPES . get ( type ) ) ; } if ( type . isArray ( ) ) { return context . newArrayType ( visitClass ( type . getComponentType ( ) , context ) ) ; } String name = type . getName ( ) . replace ( '' , '' ) ; return context . newNamedType ( Models . toName ( context , name ) ) ; } @ Override protected Type visitGenericArrayType ( GenericArrayType type , ModelFactory context ) { Type component = dispatch ( type . getGenericComponentType ( ) , context ) ; return context . newArrayType ( component ) ; } @ Override protected Type visitParameterizedType ( ParameterizedType type , ModelFactory context ) { java . lang . reflect . Type owner = type . getOwnerType ( ) ; java . lang . reflect . Type rawType = type . getRawType ( ) ; Type candidate ; if ( owner == null || owner instanceof Class < ? > ) { candidate = dispatch ( rawType , context ) ; } else { Type enclosing = dispatch ( owner , context ) ; assert rawType instanceof Class < ? > : rawType ; candidate = context . newQualifiedType ( enclosing , context . newSimpleName ( ( ( Class < ? > ) rawType ) . getSimpleName ( ) ) ) ; } List < Type > typeArguments = new ArrayList < Type > ( ) ; for ( java . lang . reflect . Type t : type . getActualTypeArguments ( ) ) { typeArguments . add ( dispatch ( t , context ) ) ; } return context . newParameterizedType ( candidate , typeArguments ) ; } @ Override protected Type visitTypeVariable ( TypeVariable < ? > type , ModelFactory context ) { return context . newNamedType ( context . newSimpleName ( type . getName ( ) ) ) ; } @ Override protected Type visitWildcardType ( WildcardType type , ModelFactory context ) { java . lang . reflect . Type [ ] lower = type . getLowerBounds ( ) ; if ( lower . length == ) { return context . newWildcard ( WildcardBoundKind . LOWER_BOUNDED , dispatch ( lower [ ] , context ) ) ; } java . lang . reflect . Type [ ] upper = type . getUpperBounds ( ) ; if ( upper . length == && upper [ ] != Object . class ) { return context . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , dispatch ( upper [ ] , context ) ) ; } return context . newWildcard ( WildcardBoundKind . UNBOUNDED , null ) ; } } package com . asakusafw . utils . java . internal . model . util ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . * ; import com . asakusafw . utils . java . model . util . NoThrow ; public final class ModelDigester extends StrictVisitor < Void , DigestContext , NoThrow > { public static final ModelDigester INSTANCE = new ModelDigester ( ) ; private ModelDigester ( ) { } public static int compute ( Model model ) { if ( model == null ) { throw new IllegalArgumentException ( "" ) ; } DigestContext digest = new DigestContext ( ) ; model . accept ( INSTANCE , digest ) ; return digest . total ; } @ Override public Void visitAlternateConstructorInvocation ( AlternateConstructorInvocation elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getTypeArguments ( ) , context ) ; digest ( elem . getArguments ( ) , context ) ; return null ; } @ Override public Void visitAnnotationDeclaration ( AnnotationDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getBodyDeclarations ( ) , context ) ; return null ; } @ Override public Void visitAnnotationElement ( AnnotationElement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitAnnotationElementDeclaration ( AnnotationElementDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getDefaultExpression ( ) , context ) ; return null ; } @ Override public Void visitArrayAccessExpression ( ArrayAccessExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getArray ( ) , context ) ; digest ( elem . getIndex ( ) , context ) ; return null ; } @ Override public Void visitArrayCreationExpression ( ArrayCreationExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getDimensionExpressions ( ) , context ) ; digest ( elem . getArrayInitializer ( ) , context ) ; return null ; } @ Override public Void visitArrayInitializer ( ArrayInitializer elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getElements ( ) , context ) ; return null ; } @ Override public Void visitArrayType ( ArrayType elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getComponentType ( ) , context ) ; return null ; } @ Override public Void visitAssertStatement ( AssertStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; digest ( elem . getMessage ( ) , context ) ; return null ; } @ Override public Void visitAssignmentExpression ( AssignmentExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getLeftHandSide ( ) , context ) ; digest ( elem . getOperator ( ) , context ) ; digest ( elem . getRightHandSide ( ) , context ) ; return null ; } @ Override public Void visitBasicType ( BasicType elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getTypeKind ( ) , context ) ; return null ; } @ Override public Void visitBlock ( Block elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getStatements ( ) , context ) ; return null ; } @ Override public Void visitBlockComment ( BlockComment elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getString ( ) , context ) ; return null ; } @ Override public Void visitBreakStatement ( BreakStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getTarget ( ) , context ) ; return null ; } @ Override public Void visitCastExpression ( CastExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitCatchClause ( CatchClause elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getParameter ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitClassBody ( ClassBody elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getBodyDeclarations ( ) , context ) ; return null ; } @ Override public Void visitClassDeclaration ( ClassDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getTypeParameters ( ) , context ) ; digest ( elem . getSuperClass ( ) , context ) ; digest ( elem . getSuperInterfaceTypes ( ) , context ) ; digest ( elem . getBodyDeclarations ( ) , context ) ; return null ; } @ Override public Void visitClassInstanceCreationExpression ( ClassInstanceCreationExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getQualifier ( ) , context ) ; digest ( elem . getTypeArguments ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getArguments ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitClassLiteral ( ClassLiteral elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; return null ; } @ Override public Void visitCompilationUnit ( CompilationUnit elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getPackageDeclaration ( ) , context ) ; digest ( elem . getImportDeclarations ( ) , context ) ; digest ( elem . getTypeDeclarations ( ) , context ) ; digest ( elem . getComments ( ) , context ) ; return null ; } @ Override public Void visitConditionalExpression ( ConditionalExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getCondition ( ) , context ) ; digest ( elem . getThenExpression ( ) , context ) ; digest ( elem . getElseExpression ( ) , context ) ; return null ; } @ Override public Void visitConstructorDeclaration ( ConstructorDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getTypeParameters ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getFormalParameters ( ) , context ) ; digest ( elem . getExceptionTypes ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitContinueStatement ( ContinueStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getTarget ( ) , context ) ; return null ; } @ Override public Void visitDoStatement ( DoStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; digest ( elem . getCondition ( ) , context ) ; return null ; } @ Override public Void visitDocBlock ( DocBlock elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getTag ( ) , context ) ; digest ( elem . getElements ( ) , context ) ; return null ; } @ Override public Void visitDocField ( DocField elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitDocMethod ( DocMethod elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getFormalParameters ( ) , context ) ; return null ; } @ Override public Void visitDocMethodParameter ( DocMethodParameter elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . isVariableArity ( ) , context ) ; return null ; } @ Override public Void visitDocText ( DocText elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getString ( ) , context ) ; return null ; } @ Override public Void visitEmptyStatement ( EmptyStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; return null ; } @ Override public Void visitEnhancedForStatement ( EnhancedForStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getParameter ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitEnumConstantDeclaration ( EnumConstantDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getArguments ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitEnumDeclaration ( EnumDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getSuperInterfaceTypes ( ) , context ) ; digest ( elem . getConstantDeclarations ( ) , context ) ; digest ( elem . getBodyDeclarations ( ) , context ) ; return null ; } @ Override public Void visitExpressionStatement ( ExpressionStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitFieldAccessExpression ( FieldAccessExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getQualifier ( ) , context ) ; digest ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitFieldDeclaration ( FieldDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getVariableDeclarators ( ) , context ) ; return null ; } @ Override public Void visitForStatement ( ForStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getInitialization ( ) , context ) ; digest ( elem . getCondition ( ) , context ) ; digest ( elem . getUpdate ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitFormalParameterDeclaration ( FormalParameterDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . isVariableArity ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getExtraDimensions ( ) , context ) ; return null ; } @ Override public Void visitIfStatement ( IfStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getCondition ( ) , context ) ; digest ( elem . getThenStatement ( ) , context ) ; digest ( elem . getElseStatement ( ) , context ) ; return null ; } @ Override public Void visitImportDeclaration ( ImportDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getImportKind ( ) , context ) ; digest ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitInfixExpression ( InfixExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getLeftOperand ( ) , context ) ; digest ( elem . getOperator ( ) , context ) ; digest ( elem . getRightOperand ( ) , context ) ; return null ; } @ Override public Void visitInitializerDeclaration ( InitializerDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitInstanceofExpression ( InstanceofExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; digest ( elem . getType ( ) , context ) ; return null ; } @ Override public Void visitInterfaceDeclaration ( InterfaceDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getTypeParameters ( ) , context ) ; digest ( elem . getSuperInterfaceTypes ( ) , context ) ; digest ( elem . getBodyDeclarations ( ) , context ) ; return null ; } @ Override public Void visitJavadoc ( Javadoc elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getBlocks ( ) , context ) ; return null ; } @ Override public Void visitLabeledStatement ( LabeledStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getLabel ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitLineComment ( LineComment elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getString ( ) , context ) ; return null ; } @ Override public Void visitLiteral ( Literal elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getToken ( ) , context ) ; return null ; } @ Override public Void visitLocalClassDeclaration ( LocalClassDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getDeclaration ( ) , context ) ; return null ; } @ Override public Void visitLocalVariableDeclaration ( LocalVariableDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getVariableDeclarators ( ) , context ) ; return null ; } @ Override public Void visitMarkerAnnotation ( MarkerAnnotation elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; return null ; } @ Override public Void visitMethodDeclaration ( MethodDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getModifiers ( ) , context ) ; digest ( elem . getTypeParameters ( ) , context ) ; digest ( elem . getReturnType ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getFormalParameters ( ) , context ) ; digest ( elem . getExtraDimensions ( ) , context ) ; digest ( elem . getExceptionTypes ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitMethodInvocationExpression ( MethodInvocationExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getQualifier ( ) , context ) ; digest ( elem . getTypeArguments ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getArguments ( ) , context ) ; return null ; } @ Override public Void visitModifier ( Modifier elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getModifierKind ( ) , context ) ; return null ; } @ Override public Void visitNamedType ( NamedType elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitNormalAnnotation ( NormalAnnotation elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getElements ( ) , context ) ; return null ; } @ Override public Void visitPackageDeclaration ( PackageDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getJavadoc ( ) , context ) ; digest ( elem . getAnnotations ( ) , context ) ; digest ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitParameterizedType ( ParameterizedType elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getTypeArguments ( ) , context ) ; return null ; } @ Override public Void visitParenthesizedExpression ( ParenthesizedExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitPostfixExpression ( PostfixExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getOperand ( ) , context ) ; digest ( elem . getOperator ( ) , context ) ; return null ; } @ Override public Void visitQualifiedName ( QualifiedName elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getQualifier ( ) , context ) ; digest ( elem . getSimpleName ( ) , context ) ; return null ; } @ Override public Void visitQualifiedType ( QualifiedType elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getQualifier ( ) , context ) ; digest ( elem . getSimpleName ( ) , context ) ; return null ; } @ Override public Void visitReturnStatement ( ReturnStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitSimpleName ( SimpleName elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getToken ( ) , context ) ; return null ; } @ Override public Void visitSingleElementAnnotation ( SingleElementAnnotation elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getType ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitStatementExpressionList ( StatementExpressionList elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpressions ( ) , context ) ; return null ; } @ Override public Void visitSuper ( Super elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getQualifier ( ) , context ) ; return null ; } @ Override public Void visitSuperConstructorInvocation ( SuperConstructorInvocation elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getQualifier ( ) , context ) ; digest ( elem . getTypeArguments ( ) , context ) ; digest ( elem . getArguments ( ) , context ) ; return null ; } @ Override public Void visitSwitchCaseLabel ( SwitchCaseLabel elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitSwitchDefaultLabel ( SwitchDefaultLabel elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; return null ; } @ Override public Void visitSwitchStatement ( SwitchStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; digest ( elem . getStatements ( ) , context ) ; return null ; } @ Override public Void visitSynchronizedStatement ( SynchronizedStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitThis ( This elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getQualifier ( ) , context ) ; return null ; } @ Override public Void visitThrowStatement ( ThrowStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitTryStatement ( TryStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getTryBlock ( ) , context ) ; digest ( elem . getCatchClauses ( ) , context ) ; digest ( elem . getFinallyBlock ( ) , context ) ; return null ; } @ Override public Void visitTypeParameterDeclaration ( TypeParameterDeclaration elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getTypeBounds ( ) , context ) ; return null ; } @ Override public Void visitUnaryExpression ( UnaryExpression elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getOperator ( ) , context ) ; digest ( elem . getOperand ( ) , context ) ; return null ; } @ Override public Void visitVariableDeclarator ( VariableDeclarator elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getName ( ) , context ) ; digest ( elem . getExtraDimensions ( ) , context ) ; digest ( elem . getInitializer ( ) , context ) ; return null ; } @ Override public Void visitWhileStatement ( WhileStatement elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getCondition ( ) , context ) ; digest ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitWildcard ( Wildcard elem , DigestContext context ) { digest ( elem . getModelKind ( ) , context ) ; digest ( elem . getBoundKind ( ) , context ) ; digest ( elem . getTypeBound ( ) , context ) ; return null ; } private void digest ( Model model , DigestContext context ) { if ( model == null ) { context . add ( ) ; } else { model . accept ( this , context ) ; } } private void digest ( List < ? extends Model > models , DigestContext context ) { context . add ( models . size ( ) ) ; for ( int i = , n = models . size ( ) ; i < n ; i ++ ) { models . get ( i ) . accept ( this , context ) ; } } private void digest ( boolean value , DigestContext context ) { context . add ( value ? : ) ; } private void digest ( int value , DigestContext context ) { context . add ( value ) ; } private void digest ( String value , DigestContext context ) { if ( value == null ) { context . add ( ) ; } else { context . add ( value . hashCode ( ) ) ; } } private void digest ( Enum < ? > value , DigestContext context ) { if ( value == null ) { context . add ( ) ; } else { context . add ( value . hashCode ( ) ) ; } } } class DigestContext { int total = ; void add ( int digest ) { total = total * + digest ; } } package com . asakusafw . utils . java . internal . model . util ; import com . asakusafw . utils . java . model . syntax . ArrayCreationExpression ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . InfixExpression ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; public enum ExpressionPriority { PRIMARY , ARRAY_INITIALIZER , UNARY , CAST , MULTIPLICATIVE , ADDITIVE , SHIFT , RELATIONAL , EQUALITY , LOGICAL , CONDITIONAL_AND , CONDITIONAL_OR , CONDITIONAL , ASSIGNMENT , ; public static ExpressionPriority valueOf ( InfixOperator operator ) { if ( operator == null ) { throw new IllegalArgumentException ( "" ) ; } switch ( operator ) { case TIMES : case DIVIDE : case REMAINDER : return MULTIPLICATIVE ; case PLUS : case MINUS : return ADDITIVE ; case LEFT_SHIFT : case RIGHT_SHIFT_SIGNED : case RIGHT_SHIFT_UNSIGNED : return SHIFT ; case GREATER : case GREATER_EQUALS : case LESS : case LESS_EQUALS : return RELATIONAL ; case EQUALS : case NOT_EQUALS : return EQUALITY ; case AND : case OR : case XOR : return LOGICAL ; case CONDITIONAL_AND : return CONDITIONAL_AND ; case CONDITIONAL_OR : return CONDITIONAL_OR ; default : throw new IllegalArgumentException ( operator . toString ( ) ) ; } } public static ExpressionPriority valueOf ( Expression expression ) { if ( expression == null ) { throw new IllegalArgumentException ( "" ) ; } switch ( expression . getModelKind ( ) ) { case ARRAY_CREATION_EXPRESSION : if ( ( ( ArrayCreationExpression ) expression ) . getArrayInitializer ( ) == null ) { return PRIMARY ; } else { return ARRAY_INITIALIZER ; } case ASSIGNMENT_EXPRESSION : return ASSIGNMENT ; case CAST_EXPRESSION : return CAST ; case CONDITIONAL_EXPRESSION : return CONDITIONAL ; case INFIX_EXPRESSION : return valueOf ( ( ( InfixExpression ) expression ) . getOperator ( ) ) ; case INSTANCEOF_EXPRESSION : return RELATIONAL ; case POSTFIX_EXPRESSION : return UNARY ; case UNARY_EXPRESSION : return UNARY ; default : return PRIMARY ; } } public static boolean isParenthesesRequired ( ExpressionPriority required , boolean requiredInRight , ExpressionPriority priority ) { if ( required == null ) { throw new IllegalArgumentException ( "" ) ; } if ( priority == null ) { throw new NullPointerException ( "" ) ; } int contextOrder = required . ordinal ( ) * ; int priorityOrder = priority . ordinal ( ) * ; if ( requiredInRight ) { contextOrder -- ; } return ( contextOrder < priorityOrder ) ; } } package com . asakusafw . utils . java . internal . model . util ; import java . math . BigInteger ; public final class LiteralAnalyzer { private static final BigInteger MAX_INT = BigInteger . valueOf ( Integer . MAX_VALUE ) . add ( BigInteger . ONE ) ; private static final BigInteger MAX_LONG = BigInteger . valueOf ( Long . MAX_VALUE ) . add ( BigInteger . ONE ) ; private LiteralAnalyzer ( ) { return ; } public static LiteralToken parse ( String literal ) { if ( literal == null ) { throw new IllegalArgumentException ( "" ) ; } LiteralTokenKind kind = LiteralParser . scan ( literal ) ; Object value = valueOf ( kind , literal ) ; return new LiteralToken ( literal , kind , value ) ; } private static Object valueOf ( LiteralTokenKind kind , String literal ) { switch ( kind ) { case BOOLEAN : return booleanValueOf ( literal ) ; case CHAR : return charValueOf ( literal ) ; case DOUBLE : return doubleValueOf ( literal ) ; case FLOAT : return floatValueOf ( literal ) ; case INT : return intValueOf ( literal ) ; case LONG : return longValueOf ( literal ) ; case NULL : return null ; case STRING : return stringValueOf ( literal ) ; case UNKNOWN : return LiteralTokenKind . UNKNOWN ; default : throw new AssertionError ( literal ) ; } } public static boolean booleanValueOf ( String literal ) { if ( LiteralToken . TOKEN_TRUE . equals ( literal ) ) { return true ; } else if ( LiteralToken . TOKEN_FALSE . equals ( literal ) ) { return false ; } else { throw new IllegalArgumentException ( literal ) ; } } public static char charValueOf ( String literal ) { int length = literal . length ( ) ; if ( length < || literal . charAt ( ) != '' || literal . charAt ( length - ) != '' ) { throw new IllegalArgumentException ( literal ) ; } String unescaped = JavaEscape . unescape ( literal . substring ( , length - ) ) ; if ( unescaped . length ( ) != ) { throw new IllegalArgumentException ( literal ) ; } return unescaped . charAt ( ) ; } public static double doubleValueOf ( String literal ) { return Double . parseDouble ( literal ) ; } public static float floatValueOf ( String literal ) { return Float . parseFloat ( literal ) ; } public static int intValueOf ( String literal ) { IntegerHolder h = parseInteger ( literal ) ; BigInteger number = h . toBigInteger ( ) ; if ( h . radix != ) { if ( number . bitLength ( ) > ) { throw new NumberFormatException ( literal ) ; } } else { if ( number . bitLength ( ) > && ! number . equals ( MAX_INT ) ) { throw new NumberFormatException ( literal ) ; } } return number . intValue ( ) ; } public static long longValueOf ( String literal ) { String target ; if ( literal . endsWith ( "" ) || literal . endsWith ( "" ) ) { target = literal . substring ( , literal . length ( ) - ) ; } else { target = literal ; } IntegerHolder h = parseInteger ( target ) ; BigInteger number = h . toBigInteger ( ) ; if ( h . radix != ) { if ( number . bitLength ( ) > ) { throw new NumberFormatException ( literal ) ; } } else { if ( number . bitLength ( ) > && ! number . equals ( MAX_LONG ) ) { throw new NumberFormatException ( literal ) ; } } return number . longValue ( ) ; } public static String stringValueOf ( String literal ) { int length = literal . length ( ) ; if ( length < || literal . charAt ( ) != '' || literal . charAt ( length - ) != '' ) { throw new IllegalArgumentException ( literal ) ; } return JavaEscape . unescape ( literal . substring ( , length - ) ) ; } public static String literalOf ( Object value ) { if ( value == null ) { return nullLiteral ( ) ; } Class < ? extends Object > klass = value . getClass ( ) ; if ( klass == Boolean . class ) { return booleanLiteralOf ( ( Boolean ) value ) ; } else if ( klass == Character . class ) { return charLiteralOf ( ( Character ) value ) ; } else if ( klass == Double . class ) { return doubleLiteralOf ( ( Double ) value ) ; } else if ( klass == Float . class ) { return floatLiteralOf ( ( Float ) value ) ; } else if ( klass == Integer . class ) { return intLiteralOf ( ( Integer ) value ) ; } else if ( klass == Long . class ) { return longLiteralOf ( ( Long ) value ) ; } else if ( klass == String . class ) { return stringLiteralOf ( ( String ) value ) ; } else { throw new IllegalArgumentException ( value . toString ( ) ) ; } } public static String booleanLiteralOf ( boolean value ) { return String . valueOf ( value ) ; } public static String charLiteralOf ( char value ) { return '' + JavaEscape . escape ( String . valueOf ( value ) , true , false ) + '' ; } public static String doubleLiteralOf ( double value ) { return String . valueOf ( value ) ; } public static String floatLiteralOf ( float value ) { if ( Float . isInfinite ( value ) || Float . isNaN ( value ) ) { return String . valueOf ( value ) ; } else { return String . valueOf ( value ) + "" ; } } public static String intLiteralOf ( int value ) { return String . valueOf ( value ) ; } public static String longLiteralOf ( long value ) { return String . valueOf ( value ) + '' ; } public static String stringLiteralOf ( String value ) { return '' + JavaEscape . escape ( value , false , false ) + '' ; } public static String nullLiteral ( ) { return LiteralToken . TOKEN_NULL ; } private static IntegerHolder parseInteger ( String literal ) { assert literal != null ; String target ; boolean positive ; if ( literal . startsWith ( "" ) ) { target = literal . substring ( ) . trim ( ) ; positive = false ; } else { target = literal ; positive = true ; } if ( target . length ( ) > && ( target . startsWith ( "" ) || target . startsWith ( "" ) ) ) { return new IntegerHolder ( positive , target . substring ( ) , ) ; } else if ( target . length ( ) > && target . startsWith ( "" ) ) { return new IntegerHolder ( positive , target . substring ( ) , ) ; } else { return new IntegerHolder ( positive , target , ) ; } } private static class IntegerHolder { private final boolean positive ; private final String literal ; final int radix ; IntegerHolder ( boolean positive , String literal , int radix ) { this . positive = positive ; this . literal = literal ; this . radix = radix ; } BigInteger toBigInteger ( ) { BigInteger bint = new BigInteger ( this . literal , this . radix ) ; if ( this . positive ) { return bint ; } else { return bint . negate ( ) ; } } } } package com . asakusafw . utils . java . internal . model . util ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import com . asakusafw . utils . java . model . syntax . * ; import com . asakusafw . utils . java . model . syntax . ImportKind . Range ; import com . asakusafw . utils . java . model . syntax . ImportKind . Target ; import com . asakusafw . utils . java . model . util . CommentEmitTrait ; import com . asakusafw . utils . java . model . util . NoThrow ; public class ModelEmitter { private static final EmitEngine ENGINE = new EmitEngine ( ) ; private PrintWriter writer ; public ModelEmitter ( PrintWriter writer ) { if ( writer == null ) { throw new IllegalArgumentException ( "" ) ; } this . writer = writer ; } public void emit ( Model element ) { if ( element == null ) { throw new IllegalArgumentException ( "" ) ; } PrintEmitContext context = new PrintEmitContext ( writer ) ; emit ( element , context ) ; context . flushComments ( ) ; } public static void emit ( Model element , EmitContext context ) { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } element . accept ( ENGINE , context ) ; } } class EmitEngine extends StrictVisitor < Void , EmitContext , NoThrow > { @ Override public Void visitAlternateConstructorInvocation ( AlternateConstructorInvocation elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; processTypeParameters ( elem . getTypeArguments ( ) , context ) ; context . keyword ( "" ) ; processParameters ( elem . getArguments ( ) , context ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitAnnotationDeclaration ( AnnotationDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; context . symbol ( "" ) ; context . keyword ( "" ) ; process ( elem . getName ( ) , context ) ; context . classBlock ( EmitDirection . BEGIN ) ; process ( elem . getBodyDeclarations ( ) , context ) ; context . classBlock ( EmitDirection . END ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitAnnotationElement ( AnnotationElement elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getName ( ) , context ) ; context . operator ( "" ) ; process ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitAnnotationElementDeclaration ( AnnotationElementDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . END ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; process ( elem . getType ( ) , context ) ; process ( elem . getName ( ) , context ) ; processParameters ( Collections . < Model > emptyList ( ) , context ) ; if ( appears ( elem . getDefaultExpression ( ) ) ) { context . keyword ( "" ) ; process ( elem . getDefaultExpression ( ) , context ) ; } context . separator ( "" ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitArrayAccessExpression ( ArrayAccessExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getArray ( ) , context ) ; context . symbol ( "" ) ; process ( elem . getIndex ( ) , context ) ; context . separator ( "" ) ; return null ; } @ Override public Void visitArrayCreationExpression ( ArrayCreationExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; Type scalar ; int dim = ; { Type current = elem . getType ( ) ; while ( current instanceof ArrayType ) { dim ++ ; current = ( ( ArrayType ) current ) . getComponentType ( ) ; } scalar = current ; } context . keyword ( "" ) ; process ( scalar , context ) ; for ( Expression expr : elem . getDimensionExpressions ( ) ) { context . symbol ( "" ) ; process ( expr , context ) ; context . separator ( "" ) ; dim -- ; } for ( int i = ; i < dim ; i ++ ) { context . symbol ( "" ) ; context . separator ( "" ) ; } process ( elem . getArrayInitializer ( ) , context ) ; return null ; } @ Override public Void visitArrayInitializer ( ArrayInitializer elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . arrayInitializerBlock ( EmitDirection . BEGIN ) ; processJoinWithComma ( elem . getElements ( ) , context ) ; context . arrayInitializerBlock ( EmitDirection . END ) ; return null ; } @ Override public Void visitArrayType ( ArrayType elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getComponentType ( ) , context ) ; context . symbol ( "" ) ; context . separator ( "" ) ; return null ; } @ Override public Void visitAssertStatement ( AssertStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; process ( elem . getExpression ( ) , context ) ; if ( appears ( elem . getMessage ( ) ) ) { context . separator ( "" ) ; process ( elem . getMessage ( ) , context ) ; } context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitAssignmentExpression ( AssignmentExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getLeftHandSide ( ) , context ) ; context . operator ( elem . getOperator ( ) . getAssignmentSymbol ( ) ) ; process ( elem . getRightHandSide ( ) , context ) ; return null ; } @ Override public Void visitBasicType ( BasicType elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . keyword ( elem . getTypeKind ( ) . getKeyword ( ) ) ; return null ; } @ Override public Void visitBlock ( Block elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statementBlock ( EmitDirection . BEGIN ) ; process ( elem . getStatements ( ) , context ) ; context . statementBlock ( EmitDirection . END ) ; return null ; } private static final Pattern HEAD_ASTER = Pattern . compile ( "" ) ; @ Override public Void visitBlockComment ( BlockComment elem , EmitContext context ) { String content = elem . getString ( ) ; if ( content . startsWith ( "" ) ) { content = content . substring ( ) ; } if ( content . endsWith ( "" ) ) { content = content . substring ( , content . length ( ) - ) ; } List < String > results = new ArrayList < String > ( ) ; String [ ] lines = content . split ( "" ) ; for ( String line : lines ) { if ( line . startsWith ( "" ) ) { Matcher m = HEAD_ASTER . matcher ( line ) ; if ( m . find ( ) ) { results . add ( line . substring ( m . end ( ) ) ) ; } else { results . add ( line ) ; } } } context . putBlockComment ( results ) ; return null ; } @ Override public Void visitBreakStatement ( BreakStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; process ( elem . getTarget ( ) , context ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitCastExpression ( CastExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . symbol ( "" ) ; process ( elem . getType ( ) , context ) ; context . separator ( "" ) ; process ( elem . getExpression ( ) , context ) ; return null ; } @ Override public Void visitCatchClause ( CatchClause elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; process ( elem . getParameter ( ) , context ) ; context . separator ( "" ) ; process ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitClassBody ( ClassBody elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . classBlock ( EmitDirection . BEGIN ) ; process ( elem . getBodyDeclarations ( ) , context ) ; context . classBlock ( EmitDirection . END ) ; return null ; } @ Override public Void visitClassDeclaration ( ClassDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; context . keyword ( "" ) ; process ( elem . getName ( ) , context ) ; processTypeParameters ( elem . getTypeParameters ( ) , context ) ; if ( appears ( elem . getSuperClass ( ) ) ) { context . keyword ( "" ) ; process ( elem . getSuperClass ( ) , context ) ; } if ( appears ( elem . getSuperInterfaceTypes ( ) ) ) { context . keyword ( "" ) ; processJoinWithComma ( elem . getSuperInterfaceTypes ( ) , context ) ; } context . classBlock ( EmitDirection . BEGIN ) ; process ( elem . getBodyDeclarations ( ) , context ) ; context . classBlock ( EmitDirection . END ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitClassInstanceCreationExpression ( ClassInstanceCreationExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; if ( process ( elem . getQualifier ( ) , context ) ) { context . symbol ( "" ) ; } context . keyword ( "" ) ; processTypeParameters ( elem . getTypeArguments ( ) , context ) ; process ( elem . getType ( ) , context ) ; processParameters ( elem . getArguments ( ) , context ) ; process ( elem . getBody ( ) , context ) ; return null ; } @ Override public Void visitClassLiteral ( ClassLiteral elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getType ( ) , context ) ; context . symbol ( "" ) ; context . keyword ( "" ) ; return null ; } @ Override public Void visitCompilationUnit ( CompilationUnit elem , EmitContext context ) { begin ( elem , context ) ; processCompilationUnitComment ( elem , context ) ; process ( elem . getPackageDeclaration ( ) , context ) ; process ( elem . getImportDeclarations ( ) , context ) ; process ( elem . getTypeDeclarations ( ) , context ) ; return null ; } @ Override public Void visitConditionalExpression ( ConditionalExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getCondition ( ) , context ) ; context . operator ( "" ) ; process ( elem . getThenExpression ( ) , context ) ; context . operator ( "" ) ; process ( elem . getElseExpression ( ) , context ) ; return null ; } @ Override public Void visitConstructorDeclaration ( ConstructorDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; processTypeParameters ( elem . getTypeParameters ( ) , context ) ; process ( elem . getName ( ) , context ) ; processParameters ( elem . getFormalParameters ( ) , context ) ; if ( appears ( elem . getExceptionTypes ( ) ) ) { context . keyword ( "" ) ; processJoinWithComma ( elem . getExceptionTypes ( ) , context ) ; } process ( elem . getBody ( ) , context ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitContinueStatement ( ContinueStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; process ( elem . getTarget ( ) , context ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitDoStatement ( DoStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; process ( elem . getBody ( ) , context ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; process ( elem . getCondition ( ) , context ) ; context . separator ( "" ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitEmptyStatement ( EmptyStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitEnhancedForStatement ( EnhancedForStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; process ( elem . getParameter ( ) , context ) ; context . separator ( "" ) ; process ( elem . getExpression ( ) , context ) ; context . separator ( "" ) ; process ( elem . getBody ( ) , context ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitEnumConstantDeclaration ( EnumConstantDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; process ( elem . getName ( ) , context ) ; if ( appears ( elem . getArguments ( ) ) ) { processParameters ( elem . getArguments ( ) , context ) ; } process ( elem . getBody ( ) , context ) ; context . separator ( "" ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitEnumDeclaration ( EnumDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; context . keyword ( "" ) ; process ( elem . getName ( ) , context ) ; if ( appears ( elem . getSuperInterfaceTypes ( ) ) ) { context . keyword ( "" ) ; processJoinWithComma ( elem . getSuperInterfaceTypes ( ) , context ) ; } context . classBlock ( EmitDirection . BEGIN ) ; process ( elem . getConstantDeclarations ( ) , context ) ; if ( appears ( elem . getBodyDeclarations ( ) ) ) { context . declaration ( EmitDirection . BEGIN ) ; context . separator ( "" ) ; context . declaration ( EmitDirection . END ) ; process ( elem . getBodyDeclarations ( ) , context ) ; } context . classBlock ( EmitDirection . END ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitExpressionStatement ( ExpressionStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; process ( elem . getExpression ( ) , context ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitFieldAccessExpression ( FieldAccessExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getQualifier ( ) , context ) ; context . symbol ( "" ) ; process ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitFieldDeclaration ( FieldDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; process ( elem . getType ( ) , context ) ; processJoinWithComma ( elem . getVariableDeclarators ( ) , context ) ; context . separator ( "" ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitFormalParameterDeclaration ( FormalParameterDeclaration elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; process ( elem . getType ( ) , context ) ; if ( elem . isVariableArity ( ) ) { context . separator ( "" ) ; } process ( elem . getName ( ) , context ) ; for ( int i = , n = elem . getExtraDimensions ( ) ; i < n ; i ++ ) { context . symbol ( "" ) ; context . separator ( "" ) ; } return null ; } @ Override public Void visitForStatement ( ForStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; if ( elem . getInitialization ( ) instanceof LocalVariableDeclaration ) { LocalVariableDeclaration decl = ( LocalVariableDeclaration ) elem . getInitialization ( ) ; processLocalVaribale ( decl , context ) ; } else { process ( elem . getInitialization ( ) , context ) ; } context . separator ( "" ) ; process ( elem . getCondition ( ) , context ) ; context . separator ( "" ) ; process ( elem . getUpdate ( ) , context ) ; context . separator ( "" ) ; process ( elem . getBody ( ) , context ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitIfStatement ( IfStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; process ( elem . getCondition ( ) , context ) ; context . separator ( "" ) ; process ( elem . getThenStatement ( ) , context ) ; if ( appears ( elem . getElseStatement ( ) ) ) { context . keyword ( "" ) ; process ( elem . getElseStatement ( ) , context ) ; } context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitImportDeclaration ( ImportDeclaration elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; if ( elem . getImportKind ( ) . getTarget ( ) == Target . MEMBER ) { context . keyword ( "" ) ; } process ( elem . getName ( ) , context ) ; if ( elem . getImportKind ( ) . getRange ( ) == Range . ON_DEMAND ) { context . symbol ( "" ) ; context . symbol ( "" ) ; } context . separator ( "" ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitInfixExpression ( InfixExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getLeftOperand ( ) , context ) ; context . operator ( elem . getOperator ( ) . getSymbol ( ) ) ; process ( elem . getRightOperand ( ) , context ) ; return null ; } @ Override public Void visitInitializerDeclaration ( InitializerDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; process ( elem . getBody ( ) , context ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitInstanceofExpression ( InstanceofExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getExpression ( ) , context ) ; context . keyword ( "" ) ; process ( elem . getType ( ) , context ) ; return null ; } @ Override public Void visitInterfaceDeclaration ( InterfaceDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; context . keyword ( "" ) ; process ( elem . getName ( ) , context ) ; processTypeParameters ( elem . getTypeParameters ( ) , context ) ; if ( appears ( elem . getSuperInterfaceTypes ( ) ) ) { context . keyword ( "" ) ; processJoinWithComma ( elem . getSuperInterfaceTypes ( ) , context ) ; } context . classBlock ( EmitDirection . BEGIN ) ; process ( elem . getBodyDeclarations ( ) , context ) ; context . classBlock ( EmitDirection . END ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitLabeledStatement ( LabeledStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; process ( elem . getLabel ( ) , context ) ; context . separator ( "" ) ; process ( elem . getBody ( ) , context ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitLineComment ( LineComment elem , EmitContext context ) { String body = elem . getString ( ) ; if ( body . startsWith ( "" ) ) { body = body . substring ( ) ; } if ( body . startsWith ( "" ) ) { body = body . substring ( ) ; } context . putLineComment ( body ) ; return null ; } @ Override public Void visitLiteral ( Literal elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . immediate ( elem . getToken ( ) ) ; return null ; } @ Override public Void visitLocalClassDeclaration ( LocalClassDeclaration elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; process ( elem . getDeclaration ( ) , context ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitLocalVariableDeclaration ( LocalVariableDeclaration elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; processLocalVaribale ( elem , context ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } private void processLocalVaribale ( LocalVariableDeclaration elem , EmitContext context ) { begin ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; process ( elem . getType ( ) , context ) ; processJoinWithComma ( elem . getVariableDeclarators ( ) , context ) ; } @ Override public Void visitMarkerAnnotation ( MarkerAnnotation elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . symbol ( "" ) ; process ( elem . getType ( ) , context ) ; return null ; } @ Override public Void visitMethodDeclaration ( MethodDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; process ( elem . getModifiers ( ) , context ) ; processTypeParameters ( elem . getTypeParameters ( ) , context ) ; process ( elem . getReturnType ( ) , context ) ; process ( elem . getName ( ) , context ) ; processParameters ( elem . getFormalParameters ( ) , context ) ; for ( int i = , n = elem . getExtraDimensions ( ) ; i < n ; i ++ ) { context . symbol ( "" ) ; context . separator ( "" ) ; } if ( appears ( elem . getExceptionTypes ( ) ) ) { context . keyword ( "" ) ; processJoinWithComma ( elem . getExceptionTypes ( ) , context ) ; } if ( appears ( elem . getBody ( ) ) ) { process ( elem . getBody ( ) , context ) ; } else { context . separator ( "" ) ; } context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitMethodInvocationExpression ( MethodInvocationExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; if ( process ( elem . getQualifier ( ) , context ) ) { context . symbol ( "" ) ; } processTypeParameters ( elem . getTypeArguments ( ) , context ) ; process ( elem . getName ( ) , context ) ; processParameters ( elem . getArguments ( ) , context ) ; return null ; } @ Override public Void visitModifier ( Modifier elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . keyword ( elem . getModifierKind ( ) . getKeyword ( ) ) ; return null ; } @ Override public Void visitNamedType ( NamedType elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitNormalAnnotation ( NormalAnnotation elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . symbol ( "" ) ; process ( elem . getType ( ) , context ) ; processParameters ( elem . getElements ( ) , context ) ; return null ; } @ Override public Void visitPackageDeclaration ( PackageDeclaration elem , EmitContext context ) { begin ( elem , context ) ; context . declaration ( EmitDirection . BEGIN ) ; process ( elem . getJavadoc ( ) , context ) ; processBlockComment ( elem , context ) ; context . keyword ( "" ) ; process ( elem . getName ( ) , context ) ; context . separator ( "" ) ; context . declaration ( EmitDirection . END ) ; return null ; } @ Override public Void visitParameterizedType ( ParameterizedType elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getType ( ) , context ) ; processTypeParameters ( elem . getTypeArguments ( ) , context ) ; return null ; } @ Override public Void visitParenthesizedExpression ( ParenthesizedExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . symbol ( "" ) ; process ( elem . getExpression ( ) , context ) ; context . separator ( "" ) ; return null ; } @ Override public Void visitPostfixExpression ( PostfixExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getOperand ( ) , context ) ; context . operator ( elem . getOperator ( ) . getSymbol ( ) ) ; return null ; } @ Override public Void visitQualifiedName ( QualifiedName elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getQualifier ( ) , context ) ; context . symbol ( "" ) ; process ( elem . getSimpleName ( ) , context ) ; return null ; } @ Override public Void visitQualifiedType ( QualifiedType elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getQualifier ( ) , context ) ; context . symbol ( "" ) ; process ( elem . getSimpleName ( ) , context ) ; return null ; } @ Override public Void visitReturnStatement ( ReturnStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; process ( elem . getExpression ( ) , context ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitSimpleName ( SimpleName elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . immediate ( elem . getToken ( ) ) ; return null ; } @ Override public Void visitSingleElementAnnotation ( SingleElementAnnotation elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . symbol ( "" ) ; process ( elem . getType ( ) , context ) ; context . symbol ( "" ) ; process ( elem . getExpression ( ) , context ) ; context . separator ( "" ) ; return null ; } @ Override public Void visitStatementExpressionList ( StatementExpressionList elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; processJoinWithComma ( elem . getExpressions ( ) , context ) ; return null ; } @ Override public Void visitSuper ( Super elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; if ( process ( elem . getQualifier ( ) , context ) ) { context . symbol ( "" ) ; } context . keyword ( "" ) ; return null ; } @ Override public Void visitSuperConstructorInvocation ( SuperConstructorInvocation elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; if ( process ( elem . getQualifier ( ) , context ) ) { context . symbol ( "" ) ; } processTypeParameters ( elem . getTypeArguments ( ) , context ) ; context . keyword ( "" ) ; processParameters ( elem . getArguments ( ) , context ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitSwitchCaseLabel ( SwitchCaseLabel elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; process ( elem . getExpression ( ) , context ) ; context . symbol ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitSwitchDefaultLabel ( SwitchDefaultLabel elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitSwitchStatement ( SwitchStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; process ( elem . getExpression ( ) , context ) ; context . separator ( "" ) ; context . statementBlock ( EmitDirection . BEGIN ) ; processSwitchBody ( elem , context ) ; context . statementBlock ( EmitDirection . END ) ; context . statement ( EmitDirection . END ) ; return null ; } private void processSwitchBody ( SwitchStatement elem , EmitContext context ) { if ( appears ( elem . getStatements ( ) ) == false ) { return ; } boolean inLabel = false ; for ( Statement stmt : elem . getStatements ( ) ) { if ( stmt instanceof SwitchLabel ) { if ( inLabel ) { context . switchLabel ( EmitDirection . END ) ; } process ( stmt , context ) ; context . switchLabel ( EmitDirection . BEGIN ) ; inLabel = true ; } else { process ( stmt , context ) ; } } if ( inLabel ) { context . switchLabel ( EmitDirection . END ) ; } } @ Override public Void visitSynchronizedStatement ( SynchronizedStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; process ( elem . getExpression ( ) , context ) ; context . separator ( "" ) ; process ( elem . getBody ( ) , context ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitThis ( This elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; if ( process ( elem . getQualifier ( ) , context ) ) { context . symbol ( "" ) ; } context . keyword ( "" ) ; return null ; } @ Override public Void visitThrowStatement ( ThrowStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; process ( elem . getExpression ( ) , context ) ; context . separator ( "" ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitTryStatement ( TryStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; process ( elem . getTryBlock ( ) , context ) ; process ( elem . getCatchClauses ( ) , context ) ; if ( appears ( elem . getFinallyBlock ( ) ) ) { context . keyword ( "" ) ; process ( elem . getFinallyBlock ( ) , context ) ; } context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitTypeParameterDeclaration ( TypeParameterDeclaration elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getName ( ) , context ) ; Iterator < ? extends Type > iter = elem . getTypeBounds ( ) . iterator ( ) ; if ( iter . hasNext ( ) ) { context . keyword ( "" ) ; process ( iter . next ( ) , context ) ; while ( iter . hasNext ( ) ) { context . separator ( "" ) ; process ( iter . next ( ) , context ) ; } } return null ; } @ Override public Void visitUnaryExpression ( UnaryExpression elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . operator ( elem . getOperator ( ) . getSymbol ( ) ) ; process ( elem . getOperand ( ) , context ) ; return null ; } @ Override public Void visitVariableDeclarator ( VariableDeclarator elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; process ( elem . getName ( ) , context ) ; for ( int i = , n = elem . getExtraDimensions ( ) ; i < n ; i ++ ) { context . symbol ( "" ) ; context . separator ( "" ) ; } if ( appears ( elem . getInitializer ( ) ) ) { context . operator ( "" ) ; process ( elem . getInitializer ( ) , context ) ; } return null ; } @ Override public Void visitWhileStatement ( WhileStatement elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . statement ( EmitDirection . BEGIN ) ; context . keyword ( "" ) ; context . symbol ( "" ) ; process ( elem . getCondition ( ) , context ) ; context . separator ( "" ) ; process ( elem . getBody ( ) , context ) ; context . statement ( EmitDirection . END ) ; return null ; } @ Override public Void visitWildcard ( Wildcard elem , EmitContext context ) { begin ( elem , context ) ; processInlineComment ( elem , context ) ; context . keyword ( "" ) ; if ( elem . getBoundKind ( ) == WildcardBoundKind . UPPER_BOUNDED ) { context . keyword ( "" ) ; process ( elem . getTypeBound ( ) , context ) ; } else if ( elem . getBoundKind ( ) == WildcardBoundKind . LOWER_BOUNDED ) { context . keyword ( "" ) ; process ( elem . getTypeBound ( ) , context ) ; } return null ; } @ Override public Void visitJavadoc ( Javadoc elem , EmitContext context ) { begin ( elem , context ) ; processBlockComment ( elem , context ) ; context . docComment ( EmitDirection . BEGIN ) ; for ( DocBlock block : elem . getBlocks ( ) ) { context . docBlock ( EmitDirection . BEGIN ) ; process ( block , context ) ; context . docBlock ( EmitDirection . END ) ; } context . docComment ( EmitDirection . END ) ; return null ; } @ Override public Void visitDocBlock ( DocBlock elem , EmitContext context ) { begin ( elem , context ) ; String tag = elem . getTag ( ) ; if ( tag . length ( ) != ) { context . separator ( tag ) ; context . padding ( ) ; } int offset = ; List < ? extends DocElement > elements = elem . getElements ( ) ; if ( tag . equals ( "" ) && isDocTypeParameter ( elements ) ) { context . symbol ( "" ) ; context . symbol ( ( ( SimpleName ) elements . get ( ) ) . getToken ( ) ) ; context . symbol ( ">" ) ; context . padding ( ) ; offset = ; } for ( int i = offset , n = elements . size ( ) ; i < n ; i ++ ) { processDocInlineElement ( elements . get ( i ) , i == n - , context ) ; } return null ; } private boolean isDocTypeParameter ( List < ? extends DocElement > elements ) { if ( elements . size ( ) < ) { return false ; } if ( elements . get ( ) . getModelKind ( ) != ModelKind . DOC_TEXT ) { return false ; } if ( elements . get ( ) . getModelKind ( ) != ModelKind . SIMPLE_NAME ) { return false ; } if ( elements . get ( ) . getModelKind ( ) != ModelKind . DOC_TEXT ) { return false ; } if ( ( ( DocText ) elements . get ( ) ) . getString ( ) . equals ( "" ) == false ) { return false ; } if ( ( ( DocText ) elements . get ( ) ) . getString ( ) . equals ( ">" ) == false ) { return false ; } return true ; } private void processDocInlineElement ( DocElement elem , boolean last , EmitContext context ) { if ( elem . getModelKind ( ) == ModelKind . DOC_BLOCK ) { context . docInlineBlock ( EmitDirection . BEGIN ) ; process ( elem , context ) ; context . docInlineBlock ( EmitDirection . END ) ; } else if ( elem . getModelKind ( ) == ModelKind . DOC_TEXT ) { process ( elem , context ) ; } else { context . padding ( ) ; process ( elem , context ) ; if ( last == false ) { context . padding ( ) ; } } } @ Override public Void visitDocField ( DocField elem , EmitContext context ) { begin ( elem , context ) ; process ( elem . getType ( ) , context ) ; context . symbol ( "" ) ; process ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitDocMethod ( DocMethod elem , EmitContext context ) { begin ( elem , context ) ; process ( elem . getType ( ) , context ) ; context . symbol ( "" ) ; process ( elem . getName ( ) , context ) ; context . symbol ( "" ) ; processJoinWithComma ( elem . getFormalParameters ( ) , context ) ; context . separator ( "" ) ; return null ; } @ Override public Void visitDocMethodParameter ( DocMethodParameter elem , EmitContext context ) { begin ( elem , context ) ; process ( elem . getType ( ) , context ) ; if ( elem . isVariableArity ( ) ) { context . separator ( "" ) ; } process ( elem . getName ( ) , context ) ; return null ; } @ Override public Void visitDocText ( DocText elem , EmitContext context ) { begin ( elem , context ) ; if ( elem . getString ( ) . startsWith ( "" ) ) { context . symbol ( elem . getString ( ) ) ; } else { context . immediate ( elem . getString ( ) ) ; } return null ; } private void begin ( Model elem , EmitContext context ) { return ; } private boolean appears ( Model element ) { return element != null ; } private boolean appears ( List < ? extends Model > elements ) { return elements . isEmpty ( ) == false ; } private boolean process ( Model element , EmitContext context ) { if ( element == null ) { return false ; } element . accept ( this , context ) ; return true ; } private boolean process ( List < ? extends Model > elements , EmitContext context ) { for ( Model element : elements ) { element . accept ( this , context ) ; } return true ; } private void processJoinWithComma ( List < ? extends Model > elements , EmitContext context ) { Iterator < ? extends Model > iter = elements . iterator ( ) ; if ( iter . hasNext ( ) ) { process ( iter . next ( ) , context ) ; while ( iter . hasNext ( ) ) { context . separator ( "" ) ; process ( iter . next ( ) , context ) ; } } } private void processParameters ( List < ? extends Model > elements , EmitContext context ) { context . symbol ( "" ) ; processJoinWithComma ( elements , context ) ; context . separator ( "" ) ; } private void processTypeParameters ( List < ? extends Model > elements , EmitContext context ) { if ( appears ( elements ) ) { context . symbol ( "" ) ; processJoinWithComma ( elements , context ) ; context . separator ( ">" ) ; } } private void processCompilationUnitComment ( CompilationUnit elem , EmitContext context ) { CommentEmitTrait comment = elem . findModelTrait ( CommentEmitTrait . class ) ; if ( comment == null ) { return ; } context . putBlockComment ( comment . getContents ( ) ) ; } private void processBlockComment ( Model elem , EmitContext context ) { CommentEmitTrait comment = elem . findModelTrait ( CommentEmitTrait . class ) ; if ( comment == null ) { return ; } for ( String line : comment . getContents ( ) ) { context . putLineComment ( line ) ; } } private void processInlineComment ( Model elem , EmitContext context ) { CommentEmitTrait comment = elem . findModelTrait ( CommentEmitTrait . class ) ; if ( comment == null ) { return ; } for ( String line : comment . getContents ( ) ) { context . putInlineComment ( line ) ; } } } package com . asakusafw . utils . java . internal . model . util ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . * ; import com . asakusafw . utils . java . model . util . NoThrow ; public final class ModelMatcher extends StrictVisitor < Boolean , Model , NoThrow > { public static final ModelMatcher INSTANCE = new ModelMatcher ( ) ; private ModelMatcher ( ) { } @ Override public Boolean visitAlternateConstructorInvocation ( AlternateConstructorInvocation elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } AlternateConstructorInvocation that = ( AlternateConstructorInvocation ) context ; if ( Boolean . FALSE . equals ( match ( elem . getTypeArguments ( ) , that . getTypeArguments ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getArguments ( ) , that . getArguments ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitAnnotationDeclaration ( AnnotationDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } AnnotationDeclaration that = ( AnnotationDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBodyDeclarations ( ) , that . getBodyDeclarations ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitAnnotationElement ( AnnotationElement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } AnnotationElement that = ( AnnotationElement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitAnnotationElementDeclaration ( AnnotationElementDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } AnnotationElementDeclaration that = ( AnnotationElementDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getDefaultExpression ( ) , that . getDefaultExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitArrayAccessExpression ( ArrayAccessExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ArrayAccessExpression that = ( ArrayAccessExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getArray ( ) , that . getArray ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getIndex ( ) , that . getIndex ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitArrayCreationExpression ( ArrayCreationExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ArrayCreationExpression that = ( ArrayCreationExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getDimensionExpressions ( ) , that . getDimensionExpressions ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getArrayInitializer ( ) , that . getArrayInitializer ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitArrayInitializer ( ArrayInitializer elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ArrayInitializer that = ( ArrayInitializer ) context ; if ( Boolean . FALSE . equals ( match ( elem . getElements ( ) , that . getElements ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitArrayType ( ArrayType elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ArrayType that = ( ArrayType ) context ; if ( Boolean . FALSE . equals ( match ( elem . getComponentType ( ) , that . getComponentType ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitAssertStatement ( AssertStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } AssertStatement that = ( AssertStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getMessage ( ) , that . getMessage ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitAssignmentExpression ( AssignmentExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } AssignmentExpression that = ( AssignmentExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getLeftHandSide ( ) , that . getLeftHandSide ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getOperator ( ) , that . getOperator ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getRightHandSide ( ) , that . getRightHandSide ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitBasicType ( BasicType elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } BasicType that = ( BasicType ) context ; if ( Boolean . FALSE . equals ( match ( elem . getTypeKind ( ) , that . getTypeKind ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitBlock ( Block elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } Block that = ( Block ) context ; if ( Boolean . FALSE . equals ( match ( elem . getStatements ( ) , that . getStatements ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitBlockComment ( BlockComment elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } BlockComment that = ( BlockComment ) context ; if ( Boolean . FALSE . equals ( match ( elem . getString ( ) , that . getString ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitBreakStatement ( BreakStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } BreakStatement that = ( BreakStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getTarget ( ) , that . getTarget ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitCastExpression ( CastExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } CastExpression that = ( CastExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitCatchClause ( CatchClause elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } CatchClause that = ( CatchClause ) context ; if ( Boolean . FALSE . equals ( match ( elem . getParameter ( ) , that . getParameter ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitClassBody ( ClassBody elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ClassBody that = ( ClassBody ) context ; if ( Boolean . FALSE . equals ( match ( elem . getBodyDeclarations ( ) , that . getBodyDeclarations ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitClassDeclaration ( ClassDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ClassDeclaration that = ( ClassDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeParameters ( ) , that . getTypeParameters ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getSuperClass ( ) , that . getSuperClass ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getSuperInterfaceTypes ( ) , that . getSuperInterfaceTypes ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBodyDeclarations ( ) , that . getBodyDeclarations ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitClassInstanceCreationExpression ( ClassInstanceCreationExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ClassInstanceCreationExpression that = ( ClassInstanceCreationExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getQualifier ( ) , that . getQualifier ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeArguments ( ) , that . getTypeArguments ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getArguments ( ) , that . getArguments ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitClassLiteral ( ClassLiteral elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ClassLiteral that = ( ClassLiteral ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitCompilationUnit ( CompilationUnit elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } CompilationUnit that = ( CompilationUnit ) context ; if ( Boolean . FALSE . equals ( match ( elem . getPackageDeclaration ( ) , that . getPackageDeclaration ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getImportDeclarations ( ) , that . getImportDeclarations ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeDeclarations ( ) , that . getTypeDeclarations ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getComments ( ) , that . getComments ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitConditionalExpression ( ConditionalExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ConditionalExpression that = ( ConditionalExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getCondition ( ) , that . getCondition ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getThenExpression ( ) , that . getThenExpression ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getElseExpression ( ) , that . getElseExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitConstructorDeclaration ( ConstructorDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ConstructorDeclaration that = ( ConstructorDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeParameters ( ) , that . getTypeParameters ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getFormalParameters ( ) , that . getFormalParameters ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExceptionTypes ( ) , that . getExceptionTypes ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitContinueStatement ( ContinueStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ContinueStatement that = ( ContinueStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getTarget ( ) , that . getTarget ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitDoStatement ( DoStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } DoStatement that = ( DoStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getCondition ( ) , that . getCondition ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitDocBlock ( DocBlock elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } DocBlock that = ( DocBlock ) context ; if ( Boolean . FALSE . equals ( match ( elem . getTag ( ) , that . getTag ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getElements ( ) , that . getElements ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitDocField ( DocField elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } DocField that = ( DocField ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitDocMethod ( DocMethod elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } DocMethod that = ( DocMethod ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getFormalParameters ( ) , that . getFormalParameters ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitDocMethodParameter ( DocMethodParameter elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } DocMethodParameter that = ( DocMethodParameter ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . isVariableArity ( ) , that . isVariableArity ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitDocText ( DocText elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } DocText that = ( DocText ) context ; if ( Boolean . FALSE . equals ( match ( elem . getString ( ) , that . getString ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitEmptyStatement ( EmptyStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitEnhancedForStatement ( EnhancedForStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } EnhancedForStatement that = ( EnhancedForStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getParameter ( ) , that . getParameter ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitEnumConstantDeclaration ( EnumConstantDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } EnumConstantDeclaration that = ( EnumConstantDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getArguments ( ) , that . getArguments ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitEnumDeclaration ( EnumDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } EnumDeclaration that = ( EnumDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getSuperInterfaceTypes ( ) , that . getSuperInterfaceTypes ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getConstantDeclarations ( ) , that . getConstantDeclarations ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBodyDeclarations ( ) , that . getBodyDeclarations ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitExpressionStatement ( ExpressionStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ExpressionStatement that = ( ExpressionStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitFieldAccessExpression ( FieldAccessExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } FieldAccessExpression that = ( FieldAccessExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getQualifier ( ) , that . getQualifier ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitFieldDeclaration ( FieldDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } FieldDeclaration that = ( FieldDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getVariableDeclarators ( ) , that . getVariableDeclarators ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitForStatement ( ForStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ForStatement that = ( ForStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getInitialization ( ) , that . getInitialization ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getCondition ( ) , that . getCondition ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getUpdate ( ) , that . getUpdate ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitFormalParameterDeclaration ( FormalParameterDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } FormalParameterDeclaration that = ( FormalParameterDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . isVariableArity ( ) , that . isVariableArity ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExtraDimensions ( ) , that . getExtraDimensions ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitIfStatement ( IfStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } IfStatement that = ( IfStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getCondition ( ) , that . getCondition ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getThenStatement ( ) , that . getThenStatement ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getElseStatement ( ) , that . getElseStatement ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitImportDeclaration ( ImportDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ImportDeclaration that = ( ImportDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getImportKind ( ) , that . getImportKind ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitInfixExpression ( InfixExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } InfixExpression that = ( InfixExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getLeftOperand ( ) , that . getLeftOperand ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getOperator ( ) , that . getOperator ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getRightOperand ( ) , that . getRightOperand ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitInitializerDeclaration ( InitializerDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } InitializerDeclaration that = ( InitializerDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitInstanceofExpression ( InstanceofExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } InstanceofExpression that = ( InstanceofExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitInterfaceDeclaration ( InterfaceDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } InterfaceDeclaration that = ( InterfaceDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeParameters ( ) , that . getTypeParameters ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getSuperInterfaceTypes ( ) , that . getSuperInterfaceTypes ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBodyDeclarations ( ) , that . getBodyDeclarations ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitJavadoc ( Javadoc elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } Javadoc that = ( Javadoc ) context ; if ( Boolean . FALSE . equals ( match ( elem . getBlocks ( ) , that . getBlocks ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitLabeledStatement ( LabeledStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } LabeledStatement that = ( LabeledStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getLabel ( ) , that . getLabel ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitLineComment ( LineComment elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } LineComment that = ( LineComment ) context ; if ( Boolean . FALSE . equals ( match ( elem . getString ( ) , that . getString ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitLiteral ( Literal elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } Literal that = ( Literal ) context ; if ( Boolean . FALSE . equals ( match ( elem . getToken ( ) , that . getToken ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitLocalClassDeclaration ( LocalClassDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } LocalClassDeclaration that = ( LocalClassDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getDeclaration ( ) , that . getDeclaration ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitLocalVariableDeclaration ( LocalVariableDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } LocalVariableDeclaration that = ( LocalVariableDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getVariableDeclarators ( ) , that . getVariableDeclarators ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitMarkerAnnotation ( MarkerAnnotation elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } MarkerAnnotation that = ( MarkerAnnotation ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitMethodDeclaration ( MethodDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } MethodDeclaration that = ( MethodDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getModifiers ( ) , that . getModifiers ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeParameters ( ) , that . getTypeParameters ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getReturnType ( ) , that . getReturnType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getFormalParameters ( ) , that . getFormalParameters ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExtraDimensions ( ) , that . getExtraDimensions ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExceptionTypes ( ) , that . getExceptionTypes ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitMethodInvocationExpression ( MethodInvocationExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } MethodInvocationExpression that = ( MethodInvocationExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getQualifier ( ) , that . getQualifier ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeArguments ( ) , that . getTypeArguments ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getArguments ( ) , that . getArguments ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitModifier ( Modifier elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } Modifier that = ( Modifier ) context ; if ( Boolean . FALSE . equals ( match ( elem . getModifierKind ( ) , that . getModifierKind ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitNamedType ( NamedType elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } NamedType that = ( NamedType ) context ; if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitNormalAnnotation ( NormalAnnotation elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } NormalAnnotation that = ( NormalAnnotation ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getElements ( ) , that . getElements ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitPackageDeclaration ( PackageDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } PackageDeclaration that = ( PackageDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getJavadoc ( ) , that . getJavadoc ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getAnnotations ( ) , that . getAnnotations ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitParameterizedType ( ParameterizedType elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ParameterizedType that = ( ParameterizedType ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeArguments ( ) , that . getTypeArguments ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitParenthesizedExpression ( ParenthesizedExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ParenthesizedExpression that = ( ParenthesizedExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitPostfixExpression ( PostfixExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } PostfixExpression that = ( PostfixExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getOperand ( ) , that . getOperand ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getOperator ( ) , that . getOperator ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitQualifiedName ( QualifiedName elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } QualifiedName that = ( QualifiedName ) context ; if ( Boolean . FALSE . equals ( match ( elem . getQualifier ( ) , that . getQualifier ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getSimpleName ( ) , that . getSimpleName ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitQualifiedType ( QualifiedType elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } QualifiedType that = ( QualifiedType ) context ; if ( Boolean . FALSE . equals ( match ( elem . getQualifier ( ) , that . getQualifier ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getSimpleName ( ) , that . getSimpleName ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitReturnStatement ( ReturnStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ReturnStatement that = ( ReturnStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitSimpleName ( SimpleName elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } SimpleName that = ( SimpleName ) context ; if ( Boolean . FALSE . equals ( match ( elem . getToken ( ) , that . getToken ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitSingleElementAnnotation ( SingleElementAnnotation elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } SingleElementAnnotation that = ( SingleElementAnnotation ) context ; if ( Boolean . FALSE . equals ( match ( elem . getType ( ) , that . getType ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitStatementExpressionList ( StatementExpressionList elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } StatementExpressionList that = ( StatementExpressionList ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpressions ( ) , that . getExpressions ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitSuper ( Super elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } Super that = ( Super ) context ; if ( Boolean . FALSE . equals ( match ( elem . getQualifier ( ) , that . getQualifier ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitSuperConstructorInvocation ( SuperConstructorInvocation elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } SuperConstructorInvocation that = ( SuperConstructorInvocation ) context ; if ( Boolean . FALSE . equals ( match ( elem . getQualifier ( ) , that . getQualifier ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeArguments ( ) , that . getTypeArguments ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getArguments ( ) , that . getArguments ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitSwitchCaseLabel ( SwitchCaseLabel elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } SwitchCaseLabel that = ( SwitchCaseLabel ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitSwitchDefaultLabel ( SwitchDefaultLabel elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitSwitchStatement ( SwitchStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } SwitchStatement that = ( SwitchStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getStatements ( ) , that . getStatements ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitSynchronizedStatement ( SynchronizedStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } SynchronizedStatement that = ( SynchronizedStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitThis ( This elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } This that = ( This ) context ; if ( Boolean . FALSE . equals ( match ( elem . getQualifier ( ) , that . getQualifier ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitThrowStatement ( ThrowStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } ThrowStatement that = ( ThrowStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getExpression ( ) , that . getExpression ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitTryStatement ( TryStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } TryStatement that = ( TryStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getTryBlock ( ) , that . getTryBlock ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getCatchClauses ( ) , that . getCatchClauses ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getFinallyBlock ( ) , that . getFinallyBlock ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitTypeParameterDeclaration ( TypeParameterDeclaration elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } TypeParameterDeclaration that = ( TypeParameterDeclaration ) context ; if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeBounds ( ) , that . getTypeBounds ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitUnaryExpression ( UnaryExpression elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } UnaryExpression that = ( UnaryExpression ) context ; if ( Boolean . FALSE . equals ( match ( elem . getOperator ( ) , that . getOperator ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getOperand ( ) , that . getOperand ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitVariableDeclarator ( VariableDeclarator elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } VariableDeclarator that = ( VariableDeclarator ) context ; if ( Boolean . FALSE . equals ( match ( elem . getName ( ) , that . getName ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getExtraDimensions ( ) , that . getExtraDimensions ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getInitializer ( ) , that . getInitializer ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitWhileStatement ( WhileStatement elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } WhileStatement that = ( WhileStatement ) context ; if ( Boolean . FALSE . equals ( match ( elem . getCondition ( ) , that . getCondition ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getBody ( ) , that . getBody ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } @ Override public Boolean visitWildcard ( Wildcard elem , Model context ) { if ( elem . getModelKind ( ) != context . getModelKind ( ) ) { return Boolean . FALSE ; } Wildcard that = ( Wildcard ) context ; if ( Boolean . FALSE . equals ( match ( elem . getBoundKind ( ) , that . getBoundKind ( ) ) ) ) { return Boolean . FALSE ; } if ( Boolean . FALSE . equals ( match ( elem . getTypeBound ( ) , that . getTypeBound ( ) ) ) ) { return Boolean . FALSE ; } return Boolean . TRUE ; } private Boolean match ( Model a , Model b ) { if ( a == b ) { return true ; } if ( a == null || b == null ) { return Boolean . FALSE ; } if ( a . getModelKind ( ) != b . getModelKind ( ) ) { return Boolean . FALSE ; } return a . accept ( this , b ) ; } private Boolean match ( List < ? extends Model > a , List < ? extends Model > b ) { if ( a . size ( ) != b . size ( ) ) { return Boolean . FALSE ; } for ( int i = , n = a . size ( ) ; i < n ; i ++ ) { if ( Boolean . FALSE . equals ( a . get ( i ) . accept ( this , b . get ( i ) ) ) ) { return Boolean . FALSE ; } } return Boolean . TRUE ; } private Boolean match ( boolean a , boolean b ) { return a == b ; } private Boolean match ( int a , int b ) { return a == b ; } private Boolean match ( String a , String b ) { if ( a == null ) { return b == null ; } return a . equals ( b ) ; } private < T extends Enum < T > > Boolean match ( T a , T b ) { return a == b ; } } package com . asakusafw . utils . java . internal . model . util ; public enum EmitDirection { BEGIN , END , } package com . asakusafw . utils . java . internal . model . util ; public final class JavaEscape { private static final char [ ] ASCII_SPECIAL_ESCAPE = new char [ ] ; static { ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; ASCII_SPECIAL_ESCAPE [ '' ] = '' ; } private JavaEscape ( ) { super ( ) ; } public static String escape ( String string , boolean charValue , boolean unicodeEscape ) { StringBuilder buf = new StringBuilder ( ) ; for ( char c : string . toCharArray ( ) ) { if ( c <= && ASCII_SPECIAL_ESCAPE [ c ] != ) { buf . append ( '' ) ; buf . append ( ASCII_SPECIAL_ESCAPE [ c ] ) ; } else if ( ( charValue && c == '' ) || ( ! charValue && c == '' ) ) { buf . append ( '' ) ; buf . append ( c ) ; } else if ( unicodeEscape || Character . isISOControl ( c ) || ! Character . isDefined ( c ) ) { addCodePoint ( buf , c ) ; } else { buf . append ( c ) ; } } return buf . toString ( ) ; } public static String unescape ( String string ) { return EscapeDecoder . scan ( string ) ; } private static void addCodePoint ( StringBuilder target , char c ) { target . append ( String . format ( "" , ( int ) c ) ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . EnumConstantDeclaration ; import com . asakusafw . utils . java . model . syntax . EnumDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class EnumDeclarationImpl extends ModelRoot implements EnumDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private SimpleName name ; private List < ? extends Type > superInterfaceTypes ; private List < ? extends EnumConstantDeclaration > constantDeclarations ; private List < ? extends TypeBodyDeclaration > bodyDeclarations ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends Type > getSuperInterfaceTypes ( ) { return this . superInterfaceTypes ; } public void setSuperInterfaceTypes ( List < ? extends Type > superInterfaceTypes ) { Util . notNull ( superInterfaceTypes , "" ) ; Util . notContainNull ( superInterfaceTypes , "" ) ; this . superInterfaceTypes = Util . freeze ( superInterfaceTypes ) ; } @ Override public List < ? extends EnumConstantDeclaration > getConstantDeclarations ( ) { return this . constantDeclarations ; } public void setConstantDeclarations ( List < ? extends EnumConstantDeclaration > constantDeclarations ) { Util . notNull ( constantDeclarations , "" ) ; Util . notContainNull ( constantDeclarations , "" ) ; this . constantDeclarations = Util . freeze ( constantDeclarations ) ; } @ Override public List < ? extends TypeBodyDeclaration > getBodyDeclarations ( ) { return this . bodyDeclarations ; } public void setBodyDeclarations ( List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; this . bodyDeclarations = Util . freeze ( bodyDeclarations ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ENUM_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitEnumDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class NamedTypeImpl extends ModelRoot implements NamedType { private Name name ; @ Override public Name getName ( ) { return this . name ; } public void setName ( Name name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . NAMED_TYPE ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitNamedType ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Block ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class BlockImpl extends ModelRoot implements Block { private List < ? extends Statement > statements ; @ Override public List < ? extends Statement > getStatements ( ) { return this . statements ; } public void setStatements ( List < ? extends Statement > statements ) { Util . notNull ( statements , "" ) ; Util . notContainNull ( statements , "" ) ; this . statements = Util . freeze ( statements ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . BLOCK ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitBlock ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . This ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ThisImpl extends ModelRoot implements This { private NamedType qualifier ; @ Override public NamedType getQualifier ( ) { return this . qualifier ; } public void setQualifier ( NamedType qualifier ) { this . qualifier = qualifier ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . THIS ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitThis ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . InfixExpression ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class InfixExpressionImpl extends ModelRoot implements InfixExpression { private Expression leftOperand ; private InfixOperator operator ; private Expression rightOperand ; @ Override public Expression getLeftOperand ( ) { return this . leftOperand ; } public void setLeftOperand ( Expression leftOperand ) { Util . notNull ( leftOperand , "" ) ; this . leftOperand = leftOperand ; } @ Override public InfixOperator getOperator ( ) { return this . operator ; } public void setOperator ( InfixOperator operator ) { Util . notNull ( operator , "" ) ; this . operator = operator ; } @ Override public Expression getRightOperand ( ) { return this . rightOperand ; } public void setRightOperand ( Expression rightOperand ) { Util . notNull ( rightOperand , "" ) ; this . rightOperand = rightOperand ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . INFIX_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitInfixExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . AnnotationElementDeclaration ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class AnnotationElementDeclarationImpl extends ModelRoot implements AnnotationElementDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private Type type ; private SimpleName name ; private Expression defaultExpression ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public Expression getDefaultExpression ( ) { return this . defaultExpression ; } public void setDefaultExpression ( Expression defaultExpression ) { this . defaultExpression = defaultExpression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ANNOTATION_ELEMENT_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitAnnotationElementDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . ClassBody ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ClassBodyImpl extends ModelRoot implements ClassBody { private List < ? extends TypeBodyDeclaration > bodyDeclarations ; @ Override public List < ? extends TypeBodyDeclaration > getBodyDeclarations ( ) { return this . bodyDeclarations ; } public void setBodyDeclarations ( List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; this . bodyDeclarations = Util . freeze ( bodyDeclarations ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CLASS_BODY ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitClassBody ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import com . asakusafw . utils . java . internal . model . util . LiteralAnalyzer ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class SimpleNameImpl extends ModelRoot implements SimpleName { private static final Set < String > RESERVED ; static { Set < String > set = new HashSet < String > ( ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; set . add ( "" ) ; RESERVED = Collections . unmodifiableSet ( set ) ; } private String token ; @ Override public String getToken ( ) { return this . token ; } public void setToken ( String token ) { Util . notNull ( token , "" ) ; if ( token . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } if ( Character . isJavaIdentifierStart ( token . charAt ( ) ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , LiteralAnalyzer . stringLiteralOf ( token ) ) ) ; } for ( int i = , n = token . length ( ) ; i < n ; i ++ ) { if ( Character . isJavaIdentifierPart ( token . charAt ( i ) ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , LiteralAnalyzer . stringLiteralOf ( token ) ) ) ; } } if ( RESERVED . contains ( token ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , LiteralAnalyzer . stringLiteralOf ( token ) ) ) ; } this . token = token ; } @ Override public SimpleName getLastSegment ( ) { return this ; } @ Override public List < SimpleName > toNameList ( ) { return Collections . < SimpleName > singletonList ( this ) ; } @ Override public String toNameString ( ) { return getToken ( ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . SIMPLE_NAME ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitSimpleName ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ImportDeclaration ; import com . asakusafw . utils . java . model . syntax . ImportKind ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ImportDeclarationImpl extends ModelRoot implements ImportDeclaration { private ImportKind importKind ; private Name name ; @ Override public ImportKind getImportKind ( ) { return this . importKind ; } public void setImportKind ( ImportKind importKind ) { Util . notNull ( importKind , "" ) ; this . importKind = importKind ; } @ Override public Name getName ( ) { return this . name ; } public void setName ( Name name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . IMPORT_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitImportDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class FormalParameterDeclarationImpl extends ModelRoot implements FormalParameterDeclaration { private List < ? extends Attribute > modifiers ; private Type type ; private boolean variableArity ; private SimpleName name ; private int extraDimensions ; @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public boolean isVariableArity ( ) { return this . variableArity ; } public void setVariableArity ( boolean variableArity ) { this . variableArity = variableArity ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public int getExtraDimensions ( ) { return this . extraDimensions ; } public void setExtraDimensions ( int extraDimensions ) { this . extraDimensions = extraDimensions ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . FORMAL_PARAMETER_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitFormalParameterDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ClassDeclarationImpl extends ModelRoot implements ClassDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private SimpleName name ; private List < ? extends TypeParameterDeclaration > typeParameters ; private Type superClass ; private List < ? extends Type > superInterfaceTypes ; private List < ? extends TypeBodyDeclaration > bodyDeclarations ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends TypeParameterDeclaration > getTypeParameters ( ) { return this . typeParameters ; } public void setTypeParameters ( List < ? extends TypeParameterDeclaration > typeParameters ) { Util . notNull ( typeParameters , "" ) ; Util . notContainNull ( typeParameters , "" ) ; this . typeParameters = Util . freeze ( typeParameters ) ; } @ Override public Type getSuperClass ( ) { return this . superClass ; } public void setSuperClass ( Type superClass ) { this . superClass = superClass ; } @ Override public List < ? extends Type > getSuperInterfaceTypes ( ) { return this . superInterfaceTypes ; } public void setSuperInterfaceTypes ( List < ? extends Type > superInterfaceTypes ) { Util . notNull ( superInterfaceTypes , "" ) ; Util . notContainNull ( superInterfaceTypes , "" ) ; this . superInterfaceTypes = Util . freeze ( superInterfaceTypes ) ; } @ Override public List < ? extends TypeBodyDeclaration > getBodyDeclarations ( ) { return this . bodyDeclarations ; } public void setBodyDeclarations ( List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; this . bodyDeclarations = Util . freeze ( bodyDeclarations ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CLASS_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitClassDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . VariableDeclarator ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class FieldDeclarationImpl extends ModelRoot implements FieldDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private Type type ; private List < ? extends VariableDeclarator > variableDeclarators ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public List < ? extends VariableDeclarator > getVariableDeclarators ( ) { return this . variableDeclarators ; } public void setVariableDeclarators ( List < ? extends VariableDeclarator > variableDeclarators ) { Util . notNull ( variableDeclarators , "" ) ; Util . notContainNull ( variableDeclarators , "" ) ; Util . notEmpty ( variableDeclarators , "" ) ; this . variableDeclarators = Util . freeze ( variableDeclarators ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . FIELD_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitFieldDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ImportDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class CompilationUnitImpl extends ModelRoot implements CompilationUnit { private PackageDeclaration packageDeclaration ; private List < ? extends ImportDeclaration > importDeclarations ; private List < ? extends TypeDeclaration > typeDeclarations ; private List < ? extends Comment > comments ; @ Override public PackageDeclaration getPackageDeclaration ( ) { return this . packageDeclaration ; } public void setPackageDeclaration ( PackageDeclaration packageDeclaration ) { this . packageDeclaration = packageDeclaration ; } @ Override public List < ? extends ImportDeclaration > getImportDeclarations ( ) { return this . importDeclarations ; } public void setImportDeclarations ( List < ? extends ImportDeclaration > importDeclarations ) { Util . notNull ( importDeclarations , "" ) ; Util . notContainNull ( importDeclarations , "" ) ; this . importDeclarations = Util . freeze ( importDeclarations ) ; } @ Override public List < ? extends TypeDeclaration > getTypeDeclarations ( ) { return this . typeDeclarations ; } public void setTypeDeclarations ( List < ? extends TypeDeclaration > typeDeclarations ) { Util . notNull ( typeDeclarations , "" ) ; Util . notContainNull ( typeDeclarations , "" ) ; this . typeDeclarations = Util . freeze ( typeDeclarations ) ; } @ Override public List < ? extends Comment > getComments ( ) { return this . comments ; } public void setComments ( List < ? extends Comment > comments ) { Util . notNull ( comments , "" ) ; Util . notContainNull ( comments , "" ) ; this . comments = Util . freeze ( comments ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . COMPILATION_UNIT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitCompilationUnit ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; import com . asakusafw . utils . java . model . syntax . Wildcard ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; public final class WildcardImpl extends ModelRoot implements Wildcard { private WildcardBoundKind boundKind ; private Type typeBound ; @ Override public WildcardBoundKind getBoundKind ( ) { return this . boundKind ; } public void setBoundKind ( WildcardBoundKind boundKind ) { Util . notNull ( boundKind , "" ) ; this . boundKind = boundKind ; } @ Override public Type getTypeBound ( ) { return this . typeBound ; } public void setTypeBound ( Type typeBound ) { this . typeBound = typeBound ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . WILDCARD ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitWildcard ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . DocMethodParameter ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class DocMethodParameterImpl extends ModelRoot implements DocMethodParameter { private Type type ; private SimpleName name ; private boolean variableArity ; @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { this . name = name ; } @ Override public boolean isVariableArity ( ) { return this . variableArity ; } public void setVariableArity ( boolean variableArity ) { this . variableArity = variableArity ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . DOC_METHOD_PARAMETER ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitDocMethodParameter ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SwitchDefaultLabel ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class SwitchDefaultLabelImpl extends ModelRoot implements SwitchDefaultLabel { @ Override public ModelKind getModelKind ( ) { return ModelKind . SWITCH_DEFAULT_LABEL ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitSwitchDefaultLabel ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . IfStatement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class IfStatementImpl extends ModelRoot implements IfStatement { private Expression condition ; private Statement thenStatement ; private Statement elseStatement ; @ Override public Expression getCondition ( ) { return this . condition ; } public void setCondition ( Expression condition ) { Util . notNull ( condition , "" ) ; this . condition = condition ; } @ Override public Statement getThenStatement ( ) { return this . thenStatement ; } public void setThenStatement ( Statement thenStatement ) { Util . notNull ( thenStatement , "" ) ; this . thenStatement = thenStatement ; } @ Override public Statement getElseStatement ( ) { return this . elseStatement ; } public void setElseStatement ( Statement elseStatement ) { this . elseStatement = elseStatement ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . IF_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitIfStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Block ; import com . asakusafw . utils . java . model . syntax . CatchClause ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class CatchClauseImpl extends ModelRoot implements CatchClause { private FormalParameterDeclaration parameter ; private Block body ; @ Override public FormalParameterDeclaration getParameter ( ) { return this . parameter ; } public void setParameter ( FormalParameterDeclaration parameter ) { Util . notNull ( parameter , "" ) ; this . parameter = parameter ; } @ Override public Block getBody ( ) { return this . body ; } public void setBody ( Block body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CATCH_CLAUSE ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitCatchClause ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . utils . java . internal . model . util . ExpressionPriority ; import com . asakusafw . utils . java . model . syntax . * ; public class ModelFactoryImpl implements ModelFactory { @ Override public AlternateConstructorInvocation newAlternateConstructorInvocation ( Expression ... arguments ) { Util . notNull ( arguments , "" ) ; return this . newAlternateConstructorInvocation0 ( Collections . < Type > emptyList ( ) , Arrays . asList ( arguments ) ) ; } @ Override public AlternateConstructorInvocation newAlternateConstructorInvocation ( List < ? extends Expression > arguments ) { return this . newAlternateConstructorInvocation0 ( Collections . < Type > emptyList ( ) , arguments ) ; } @ Override public AlternateConstructorInvocation newAlternateConstructorInvocation ( List < ? extends Type > typeArguments , List < ? extends Expression > arguments ) { return this . newAlternateConstructorInvocation0 ( typeArguments , arguments ) ; } private AlternateConstructorInvocationImpl newAlternateConstructorInvocation0 ( List < ? extends Type > typeArguments , List < ? extends Expression > arguments ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; AlternateConstructorInvocationImpl result = new AlternateConstructorInvocationImpl ( ) ; result . setTypeArguments ( typeArguments ) ; result . setArguments ( arguments ) ; return result ; } @ Override public AnnotationDeclaration newAnnotationDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { return this . newAnnotationDeclaration0 ( javadoc , modifiers , name , bodyDeclarations ) ; } private AnnotationDeclarationImpl newAnnotationDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( name , "" ) ; Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; AnnotationDeclarationImpl result = new AnnotationDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setName ( name ) ; result . setBodyDeclarations ( bodyDeclarations ) ; return result ; } @ Override public AnnotationElement newAnnotationElement ( SimpleName name , Expression expression ) { return this . newAnnotationElement0 ( name , expression ) ; } private AnnotationElementImpl newAnnotationElement0 ( SimpleName name , Expression expression ) { Util . notNull ( name , "" ) ; Util . notNull ( expression , "" ) ; AnnotationElementImpl result = new AnnotationElementImpl ( ) ; result . setName ( name ) ; result . setExpression ( expression ) ; return result ; } @ Override public AnnotationElementDeclaration newAnnotationElementDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type type , SimpleName name , Expression defaultExpression ) { return this . newAnnotationElementDeclaration0 ( javadoc , modifiers , type , name , defaultExpression ) ; } private AnnotationElementDeclarationImpl newAnnotationElementDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type type , SimpleName name , Expression defaultExpression ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( type , "" ) ; Util . notNull ( name , "" ) ; AnnotationElementDeclarationImpl result = new AnnotationElementDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setType ( type ) ; result . setName ( name ) ; result . setDefaultExpression ( defaultExpression ) ; return result ; } @ Override public ArrayAccessExpression newArrayAccessExpression ( Expression array , Expression index ) { return this . newArrayAccessExpression0 ( array , index ) ; } private ArrayAccessExpressionImpl newArrayAccessExpression0 ( Expression array , Expression index ) { Util . notNull ( array , "" ) ; Util . notNull ( index , "" ) ; ArrayAccessExpressionImpl result = new ArrayAccessExpressionImpl ( ) ; result . setArray ( parenthesize ( array , ExpressionPriority . PRIMARY ) ) ; result . setIndex ( index ) ; return result ; } @ Override public ArrayCreationExpression newArrayCreationExpression ( ArrayType type , ArrayInitializer arrayInitializer ) { return this . newArrayCreationExpression0 ( type , Collections . < Expression > emptyList ( ) , arrayInitializer ) ; } @ Override public ArrayCreationExpression newArrayCreationExpression ( ArrayType type , List < ? extends Expression > dimensionExpressions , ArrayInitializer arrayInitializer ) { return this . newArrayCreationExpression0 ( type , dimensionExpressions , arrayInitializer ) ; } private ArrayCreationExpressionImpl newArrayCreationExpression0 ( ArrayType type , List < ? extends Expression > dimensionExpressions , ArrayInitializer arrayInitializer ) { Util . notNull ( type , "" ) ; Util . notNull ( dimensionExpressions , "" ) ; Util . notContainNull ( dimensionExpressions , "" ) ; ArrayCreationExpressionImpl result = new ArrayCreationExpressionImpl ( ) ; result . setType ( type ) ; result . setDimensionExpressions ( dimensionExpressions ) ; result . setArrayInitializer ( arrayInitializer ) ; return result ; } @ Override public ArrayInitializer newArrayInitializer ( Expression ... elements ) { Util . notNull ( elements , "" ) ; return this . newArrayInitializer0 ( Arrays . asList ( elements ) ) ; } @ Override public ArrayInitializer newArrayInitializer ( List < ? extends Expression > elements ) { return this . newArrayInitializer0 ( elements ) ; } private ArrayInitializerImpl newArrayInitializer0 ( List < ? extends Expression > elements ) { Util . notNull ( elements , "" ) ; Util . notContainNull ( elements , "" ) ; ArrayInitializerImpl result = new ArrayInitializerImpl ( ) ; result . setElements ( elements ) ; return result ; } @ Override public ArrayType newArrayType ( Type componentType ) { return this . newArrayType0 ( componentType ) ; } private ArrayTypeImpl newArrayType0 ( Type componentType ) { Util . notNull ( componentType , "" ) ; ArrayTypeImpl result = new ArrayTypeImpl ( ) ; result . setComponentType ( componentType ) ; return result ; } @ Override public AssertStatement newAssertStatement ( Expression expression ) { return this . newAssertStatement0 ( expression , null ) ; } @ Override public AssertStatement newAssertStatement ( Expression expression , Expression message ) { return this . newAssertStatement0 ( expression , message ) ; } private AssertStatementImpl newAssertStatement0 ( Expression expression , Expression message ) { Util . notNull ( expression , "" ) ; AssertStatementImpl result = new AssertStatementImpl ( ) ; result . setExpression ( expression ) ; result . setMessage ( message ) ; return result ; } @ Override public AssignmentExpression newAssignmentExpression ( Expression leftHandSide , Expression rightHandSide ) { return this . newAssignmentExpression0 ( leftHandSide , InfixOperator . ASSIGN , rightHandSide ) ; } @ Override public AssignmentExpression newAssignmentExpression ( Expression leftHandSide , InfixOperator operator , Expression rightHandSide ) { return this . newAssignmentExpression0 ( leftHandSide , operator , rightHandSide ) ; } private AssignmentExpressionImpl newAssignmentExpression0 ( Expression leftHandSide , InfixOperator operator , Expression rightHandSide ) { Util . notNull ( leftHandSide , "" ) ; Util . notNull ( operator , "" ) ; Util . notNull ( rightHandSide , "" ) ; AssignmentExpressionImpl result = new AssignmentExpressionImpl ( ) ; result . setLeftHandSide ( parenthesize ( leftHandSide , ExpressionPriority . ASSIGNMENT ) ) ; result . setOperator ( operator ) ; result . setRightHandSide ( parenthesizeRight ( rightHandSide , ExpressionPriority . ASSIGNMENT ) ) ; return result ; } @ Override public BasicType newBasicType ( BasicTypeKind typeKind ) { return this . newBasicType0 ( typeKind ) ; } private BasicTypeImpl newBasicType0 ( BasicTypeKind typeKind ) { Util . notNull ( typeKind , "" ) ; BasicTypeImpl result = new BasicTypeImpl ( ) ; result . setTypeKind ( typeKind ) ; return result ; } @ Override public Block newBlock ( Statement ... statements ) { Util . notNull ( statements , "" ) ; return this . newBlock0 ( Arrays . asList ( statements ) ) ; } @ Override public Block newBlock ( List < ? extends Statement > statements ) { return this . newBlock0 ( statements ) ; } private BlockImpl newBlock0 ( List < ? extends Statement > statements ) { Util . notNull ( statements , "" ) ; Util . notContainNull ( statements , "" ) ; BlockImpl result = new BlockImpl ( ) ; result . setStatements ( statements ) ; return result ; } @ Override public BlockComment newBlockComment ( String string ) { return this . newBlockComment0 ( string ) ; } private BlockCommentImpl newBlockComment0 ( String string ) { Util . notNull ( string , "" ) ; BlockCommentImpl result = new BlockCommentImpl ( ) ; result . setString ( string ) ; return result ; } @ Override public BreakStatement newBreakStatement ( ) { return this . newBreakStatement0 ( null ) ; } @ Override public BreakStatement newBreakStatement ( SimpleName target ) { return this . newBreakStatement0 ( target ) ; } private BreakStatementImpl newBreakStatement0 ( SimpleName target ) { BreakStatementImpl result = new BreakStatementImpl ( ) ; result . setTarget ( target ) ; return result ; } @ Override public CastExpression newCastExpression ( Type type , Expression expression ) { return this . newCastExpression0 ( type , expression ) ; } private CastExpressionImpl newCastExpression0 ( Type type , Expression expression ) { Util . notNull ( type , "" ) ; Util . notNull ( expression , "" ) ; CastExpressionImpl result = new CastExpressionImpl ( ) ; result . setType ( type ) ; result . setExpression ( parenthesize ( expression , ExpressionPriority . CAST ) ) ; return result ; } @ Override public CatchClause newCatchClause ( FormalParameterDeclaration parameter , Block body ) { return this . newCatchClause0 ( parameter , body ) ; } private CatchClauseImpl newCatchClause0 ( FormalParameterDeclaration parameter , Block body ) { Util . notNull ( parameter , "" ) ; Util . notNull ( body , "" ) ; CatchClauseImpl result = new CatchClauseImpl ( ) ; result . setParameter ( parameter ) ; result . setBody ( body ) ; return result ; } @ Override public ClassBody newClassBody ( List < ? extends TypeBodyDeclaration > bodyDeclarations ) { return this . newClassBody0 ( bodyDeclarations ) ; } private ClassBodyImpl newClassBody0 ( List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; ClassBodyImpl result = new ClassBodyImpl ( ) ; result . setBodyDeclarations ( bodyDeclarations ) ; return result ; } @ Override public ClassDeclaration newClassDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , Type superClass , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { return this . newClassDeclaration0 ( javadoc , modifiers , name , Collections . < TypeParameterDeclaration > emptyList ( ) , superClass , superInterfaceTypes , bodyDeclarations ) ; } @ Override public ClassDeclaration newClassDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeParameterDeclaration > typeParameters , Type superClass , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { return this . newClassDeclaration0 ( javadoc , modifiers , name , typeParameters , superClass , superInterfaceTypes , bodyDeclarations ) ; } private ClassDeclarationImpl newClassDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeParameterDeclaration > typeParameters , Type superClass , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( name , "" ) ; Util . notNull ( typeParameters , "" ) ; Util . notContainNull ( typeParameters , "" ) ; Util . notNull ( superInterfaceTypes , "" ) ; Util . notContainNull ( superInterfaceTypes , "" ) ; Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; ClassDeclarationImpl result = new ClassDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setName ( name ) ; result . setTypeParameters ( typeParameters ) ; result . setSuperClass ( superClass ) ; result . setSuperInterfaceTypes ( superInterfaceTypes ) ; result . setBodyDeclarations ( bodyDeclarations ) ; return result ; } @ Override public ClassInstanceCreationExpression newClassInstanceCreationExpression ( Type type , Expression ... arguments ) { Util . notNull ( arguments , "" ) ; return this . newClassInstanceCreationExpression0 ( null , Collections . < Type > emptyList ( ) , type , Arrays . asList ( arguments ) , null ) ; } @ Override public ClassInstanceCreationExpression newClassInstanceCreationExpression ( Type type , List < ? extends Expression > arguments ) { return this . newClassInstanceCreationExpression0 ( null , Collections . < Type > emptyList ( ) , type , arguments , null ) ; } @ Override public ClassInstanceCreationExpression newClassInstanceCreationExpression ( Expression qualifier , List < ? extends Type > typeArguments , Type type , List < ? extends Expression > arguments , ClassBody body ) { return this . newClassInstanceCreationExpression0 ( qualifier , typeArguments , type , arguments , body ) ; } private ClassInstanceCreationExpressionImpl newClassInstanceCreationExpression0 ( Expression qualifier , List < ? extends Type > typeArguments , Type type , List < ? extends Expression > arguments , ClassBody body ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; Util . notNull ( type , "" ) ; Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; ClassInstanceCreationExpressionImpl result = new ClassInstanceCreationExpressionImpl ( ) ; result . setQualifier ( parenthesize ( qualifier , ExpressionPriority . PRIMARY ) ) ; result . setTypeArguments ( typeArguments ) ; result . setType ( type ) ; result . setArguments ( arguments ) ; result . setBody ( body ) ; return result ; } @ Override public ClassLiteral newClassLiteral ( Type type ) { return this . newClassLiteral0 ( type ) ; } private ClassLiteralImpl newClassLiteral0 ( Type type ) { Util . notNull ( type , "" ) ; ClassLiteralImpl result = new ClassLiteralImpl ( ) ; result . setType ( type ) ; return result ; } @ Override public CompilationUnit newCompilationUnit ( PackageDeclaration packageDeclaration , List < ? extends ImportDeclaration > importDeclarations , List < ? extends TypeDeclaration > typeDeclarations , List < ? extends Comment > comments ) { return this . newCompilationUnit0 ( packageDeclaration , importDeclarations , typeDeclarations , comments ) ; } private CompilationUnitImpl newCompilationUnit0 ( PackageDeclaration packageDeclaration , List < ? extends ImportDeclaration > importDeclarations , List < ? extends TypeDeclaration > typeDeclarations , List < ? extends Comment > comments ) { Util . notNull ( importDeclarations , "" ) ; Util . notContainNull ( importDeclarations , "" ) ; Util . notNull ( typeDeclarations , "" ) ; Util . notContainNull ( typeDeclarations , "" ) ; Util . notNull ( comments , "" ) ; Util . notContainNull ( comments , "" ) ; CompilationUnitImpl result = new CompilationUnitImpl ( ) ; result . setPackageDeclaration ( packageDeclaration ) ; result . setImportDeclarations ( importDeclarations ) ; result . setTypeDeclarations ( typeDeclarations ) ; result . setComments ( comments ) ; return result ; } @ Override public ConditionalExpression newConditionalExpression ( Expression condition , Expression thenExpression , Expression elseExpression ) { return this . newConditionalExpression0 ( condition , thenExpression , elseExpression ) ; } private ConditionalExpressionImpl newConditionalExpression0 ( Expression condition , Expression thenExpression , Expression elseExpression ) { Util . notNull ( condition , "" ) ; Util . notNull ( thenExpression , "" ) ; Util . notNull ( elseExpression , "" ) ; ConditionalExpressionImpl result = new ConditionalExpressionImpl ( ) ; result . setCondition ( parenthesize ( condition , ExpressionPriority . CONDITIONAL ) ) ; result . setThenExpression ( parenthesize ( thenExpression , ExpressionPriority . CONDITIONAL ) ) ; result . setElseExpression ( parenthesize ( elseExpression , ExpressionPriority . CONDITIONAL ) ) ; return result ; } @ Override public ConstructorDeclaration newConstructorDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , List < ? extends Statement > statements ) { Util . notNull ( statements , "" ) ; return this . newConstructorDeclaration0 ( javadoc , modifiers , Collections . < TypeParameterDeclaration > emptyList ( ) , name , formalParameters , Collections . < Type > emptyList ( ) , newBlock ( statements ) ) ; } @ Override public ConstructorDeclaration newConstructorDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , List < ? extends TypeParameterDeclaration > typeParameters , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , List < ? extends Type > exceptionTypes , Block body ) { return this . newConstructorDeclaration0 ( javadoc , modifiers , typeParameters , name , formalParameters , exceptionTypes , body ) ; } private ConstructorDeclarationImpl newConstructorDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , List < ? extends TypeParameterDeclaration > typeParameters , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , List < ? extends Type > exceptionTypes , Block body ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( typeParameters , "" ) ; Util . notContainNull ( typeParameters , "" ) ; Util . notNull ( name , "" ) ; Util . notNull ( formalParameters , "" ) ; Util . notContainNull ( formalParameters , "" ) ; Util . notNull ( exceptionTypes , "" ) ; Util . notContainNull ( exceptionTypes , "" ) ; Util . notNull ( body , "" ) ; ConstructorDeclarationImpl result = new ConstructorDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setTypeParameters ( typeParameters ) ; result . setName ( name ) ; result . setFormalParameters ( formalParameters ) ; result . setExceptionTypes ( exceptionTypes ) ; result . setBody ( body ) ; return result ; } @ Override public ContinueStatement newContinueStatement ( ) { return this . newContinueStatement0 ( null ) ; } @ Override public ContinueStatement newContinueStatement ( SimpleName target ) { return this . newContinueStatement0 ( target ) ; } private ContinueStatementImpl newContinueStatement0 ( SimpleName target ) { ContinueStatementImpl result = new ContinueStatementImpl ( ) ; result . setTarget ( target ) ; return result ; } @ Override public DoStatement newDoStatement ( Statement body , Expression condition ) { return this . newDoStatement0 ( body , condition ) ; } private DoStatementImpl newDoStatement0 ( Statement body , Expression condition ) { Util . notNull ( body , "" ) ; Util . notNull ( condition , "" ) ; DoStatementImpl result = new DoStatementImpl ( ) ; result . setBody ( body ) ; result . setCondition ( condition ) ; return result ; } @ Override public DocBlock newDocBlock ( String tag , List < ? extends DocElement > elements ) { return this . newDocBlock0 ( tag , elements ) ; } private DocBlockImpl newDocBlock0 ( String tag , List < ? extends DocElement > elements ) { Util . notNull ( tag , "" ) ; Util . notNull ( elements , "" ) ; Util . notContainNull ( elements , "" ) ; DocBlockImpl result = new DocBlockImpl ( ) ; result . setTag ( tag ) ; result . setElements ( elements ) ; return result ; } @ Override public DocField newDocField ( Type type , SimpleName name ) { return this . newDocField0 ( type , name ) ; } private DocFieldImpl newDocField0 ( Type type , SimpleName name ) { Util . notNull ( name , "" ) ; DocFieldImpl result = new DocFieldImpl ( ) ; result . setType ( type ) ; result . setName ( name ) ; return result ; } @ Override public DocMethod newDocMethod ( Type type , SimpleName name , List < ? extends DocMethodParameter > formalParameters ) { return this . newDocMethod0 ( type , name , formalParameters ) ; } private DocMethodImpl newDocMethod0 ( Type type , SimpleName name , List < ? extends DocMethodParameter > formalParameters ) { Util . notNull ( name , "" ) ; Util . notNull ( formalParameters , "" ) ; Util . notContainNull ( formalParameters , "" ) ; DocMethodImpl result = new DocMethodImpl ( ) ; result . setType ( type ) ; result . setName ( name ) ; result . setFormalParameters ( formalParameters ) ; return result ; } @ Override public DocMethodParameter newDocMethodParameter ( Type type , SimpleName name , boolean variableArity ) { return this . newDocMethodParameter0 ( type , name , variableArity ) ; } private DocMethodParameterImpl newDocMethodParameter0 ( Type type , SimpleName name , boolean variableArity ) { Util . notNull ( type , "" ) ; DocMethodParameterImpl result = new DocMethodParameterImpl ( ) ; result . setType ( type ) ; result . setName ( name ) ; result . setVariableArity ( variableArity ) ; return result ; } @ Override public DocText newDocText ( String string ) { return this . newDocText0 ( string ) ; } private DocTextImpl newDocText0 ( String string ) { Util . notNull ( string , "" ) ; DocTextImpl result = new DocTextImpl ( ) ; result . setString ( string ) ; return result ; } @ Override public EmptyStatement newEmptyStatement ( ) { return this . newEmptyStatement0 ( ) ; } private EmptyStatementImpl newEmptyStatement0 ( ) { EmptyStatementImpl result = new EmptyStatementImpl ( ) ; return result ; } @ Override public EnhancedForStatement newEnhancedForStatement ( FormalParameterDeclaration parameter , Expression expression , Statement body ) { return this . newEnhancedForStatement0 ( parameter , expression , body ) ; } private EnhancedForStatementImpl newEnhancedForStatement0 ( FormalParameterDeclaration parameter , Expression expression , Statement body ) { Util . notNull ( parameter , "" ) ; Util . notNull ( expression , "" ) ; Util . notNull ( body , "" ) ; EnhancedForStatementImpl result = new EnhancedForStatementImpl ( ) ; result . setParameter ( parameter ) ; result . setExpression ( expression ) ; result . setBody ( body ) ; return result ; } @ Override public EnumConstantDeclaration newEnumConstantDeclaration ( Javadoc javadoc , SimpleName name , Expression ... arguments ) { Util . notNull ( arguments , "" ) ; return this . newEnumConstantDeclaration0 ( javadoc , Collections . < Attribute > emptyList ( ) , name , Arrays . asList ( arguments ) , null ) ; } @ Override public EnumConstantDeclaration newEnumConstantDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends Expression > arguments , ClassBody body ) { return this . newEnumConstantDeclaration0 ( javadoc , modifiers , name , arguments , body ) ; } private EnumConstantDeclarationImpl newEnumConstantDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends Expression > arguments , ClassBody body ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( name , "" ) ; Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; EnumConstantDeclarationImpl result = new EnumConstantDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setName ( name ) ; result . setArguments ( arguments ) ; result . setBody ( body ) ; return result ; } @ Override public EnumDeclaration newEnumDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends EnumConstantDeclaration > constantDeclarations , TypeBodyDeclaration ... bodyDeclarations ) { Util . notNull ( bodyDeclarations , "" ) ; return this . newEnumDeclaration0 ( javadoc , modifiers , name , Collections . < Type > emptyList ( ) , constantDeclarations , Arrays . asList ( bodyDeclarations ) ) ; } @ Override public EnumDeclaration newEnumDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends Type > superInterfaceTypes , List < ? extends EnumConstantDeclaration > constantDeclarations , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { return this . newEnumDeclaration0 ( javadoc , modifiers , name , superInterfaceTypes , constantDeclarations , bodyDeclarations ) ; } private EnumDeclarationImpl newEnumDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends Type > superInterfaceTypes , List < ? extends EnumConstantDeclaration > constantDeclarations , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( name , "" ) ; Util . notNull ( superInterfaceTypes , "" ) ; Util . notContainNull ( superInterfaceTypes , "" ) ; Util . notNull ( constantDeclarations , "" ) ; Util . notContainNull ( constantDeclarations , "" ) ; Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; EnumDeclarationImpl result = new EnumDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setName ( name ) ; result . setSuperInterfaceTypes ( superInterfaceTypes ) ; result . setConstantDeclarations ( constantDeclarations ) ; result . setBodyDeclarations ( bodyDeclarations ) ; return result ; } @ Override public ExpressionStatement newExpressionStatement ( Expression expression ) { return this . newExpressionStatement0 ( expression ) ; } private ExpressionStatementImpl newExpressionStatement0 ( Expression expression ) { Util . notNull ( expression , "" ) ; ExpressionStatementImpl result = new ExpressionStatementImpl ( ) ; result . setExpression ( expression ) ; return result ; } @ Override public FieldAccessExpression newFieldAccessExpression ( Expression qualifier , SimpleName name ) { return this . newFieldAccessExpression0 ( qualifier , name ) ; } private FieldAccessExpressionImpl newFieldAccessExpression0 ( Expression qualifier , SimpleName name ) { Util . notNull ( qualifier , "" ) ; Util . notNull ( name , "" ) ; FieldAccessExpressionImpl result = new FieldAccessExpressionImpl ( ) ; result . setQualifier ( parenthesize ( qualifier , ExpressionPriority . PRIMARY ) ) ; result . setName ( name ) ; return result ; } @ Override public FieldDeclaration newFieldDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type type , SimpleName name , Expression initializer ) { return this . newFieldDeclaration0 ( javadoc , modifiers , type , Collections . singletonList ( newVariableDeclarator ( name , , initializer ) ) ) ; } @ Override public FieldDeclaration newFieldDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type type , List < ? extends VariableDeclarator > variableDeclarators ) { return this . newFieldDeclaration0 ( javadoc , modifiers , type , variableDeclarators ) ; } private FieldDeclarationImpl newFieldDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type type , List < ? extends VariableDeclarator > variableDeclarators ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( type , "" ) ; Util . notNull ( variableDeclarators , "" ) ; Util . notContainNull ( variableDeclarators , "" ) ; Util . notEmpty ( variableDeclarators , "" ) ; FieldDeclarationImpl result = new FieldDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setType ( type ) ; result . setVariableDeclarators ( variableDeclarators ) ; return result ; } @ Override public ForStatement newForStatement ( ForInitializer initialization , Expression condition , StatementExpressionList update , Statement body ) { return this . newForStatement0 ( initialization , condition , update , body ) ; } private ForStatementImpl newForStatement0 ( ForInitializer initialization , Expression condition , StatementExpressionList update , Statement body ) { Util . notNull ( body , "" ) ; ForStatementImpl result = new ForStatementImpl ( ) ; result . setInitialization ( initialization ) ; result . setCondition ( condition ) ; result . setUpdate ( update ) ; result . setBody ( body ) ; return result ; } @ Override public FormalParameterDeclaration newFormalParameterDeclaration ( Type type , SimpleName name ) { return this . newFormalParameterDeclaration0 ( Collections . < Attribute > emptyList ( ) , type , false , name , ) ; } @ Override public FormalParameterDeclaration newFormalParameterDeclaration ( List < ? extends Attribute > modifiers , Type type , boolean variableArity , SimpleName name , int extraDimensions ) { return this . newFormalParameterDeclaration0 ( modifiers , type , variableArity , name , extraDimensions ) ; } private FormalParameterDeclarationImpl newFormalParameterDeclaration0 ( List < ? extends Attribute > modifiers , Type type , boolean variableArity , SimpleName name , int extraDimensions ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( type , "" ) ; Util . notNull ( name , "" ) ; FormalParameterDeclarationImpl result = new FormalParameterDeclarationImpl ( ) ; result . setModifiers ( modifiers ) ; result . setType ( type ) ; result . setVariableArity ( variableArity ) ; result . setName ( name ) ; result . setExtraDimensions ( extraDimensions ) ; return result ; } @ Override public IfStatement newIfStatement ( Expression condition , Statement thenStatement ) { return this . newIfStatement0 ( condition , thenStatement , null ) ; } @ Override public IfStatement newIfStatement ( Expression condition , Statement thenStatement , Statement elseStatement ) { return this . newIfStatement0 ( condition , thenStatement , elseStatement ) ; } private IfStatementImpl newIfStatement0 ( Expression condition , Statement thenStatement , Statement elseStatement ) { Util . notNull ( condition , "" ) ; Util . notNull ( thenStatement , "" ) ; IfStatementImpl result = new IfStatementImpl ( ) ; result . setCondition ( condition ) ; result . setThenStatement ( thenStatement ) ; result . setElseStatement ( elseStatement ) ; return result ; } @ Override public ImportDeclaration newImportDeclaration ( ImportKind importKind , Name name ) { return this . newImportDeclaration0 ( importKind , name ) ; } private ImportDeclarationImpl newImportDeclaration0 ( ImportKind importKind , Name name ) { Util . notNull ( importKind , "" ) ; Util . notNull ( name , "" ) ; ImportDeclarationImpl result = new ImportDeclarationImpl ( ) ; result . setImportKind ( importKind ) ; result . setName ( name ) ; return result ; } @ Override public InfixExpression newInfixExpression ( Expression leftOperand , InfixOperator operator , Expression rightOperand ) { return this . newInfixExpression0 ( leftOperand , operator , rightOperand ) ; } private InfixExpressionImpl newInfixExpression0 ( Expression leftOperand , InfixOperator operator , Expression rightOperand ) { Util . notNull ( leftOperand , "" ) ; Util . notNull ( operator , "" ) ; Util . notNull ( rightOperand , "" ) ; InfixExpressionImpl result = new InfixExpressionImpl ( ) ; result . setLeftOperand ( parenthesize ( leftOperand , ExpressionPriority . valueOf ( operator ) ) ) ; result . setOperator ( operator ) ; result . setRightOperand ( parenthesizeRight ( rightOperand , ExpressionPriority . valueOf ( operator ) ) ) ; return result ; } @ Override public InitializerDeclaration newInitializerDeclaration ( List < ? extends Statement > statements ) { Util . notNull ( statements , "" ) ; return this . newInitializerDeclaration0 ( null , Collections . < Attribute > emptyList ( ) , newBlock ( statements ) ) ; } @ Override public InitializerDeclaration newInitializerDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Block body ) { return this . newInitializerDeclaration0 ( javadoc , modifiers , body ) ; } private InitializerDeclarationImpl newInitializerDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , Block body ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( body , "" ) ; InitializerDeclarationImpl result = new InitializerDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setBody ( body ) ; return result ; } @ Override public InstanceofExpression newInstanceofExpression ( Expression expression , Type type ) { return this . newInstanceofExpression0 ( expression , type ) ; } private InstanceofExpressionImpl newInstanceofExpression0 ( Expression expression , Type type ) { Util . notNull ( expression , "" ) ; Util . notNull ( type , "" ) ; InstanceofExpressionImpl result = new InstanceofExpressionImpl ( ) ; result . setExpression ( parenthesize ( expression , ExpressionPriority . RELATIONAL ) ) ; result . setType ( type ) ; return result ; } @ Override public InterfaceDeclaration newInterfaceDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { return this . newInterfaceDeclaration0 ( javadoc , modifiers , name , Collections . < TypeParameterDeclaration > emptyList ( ) , superInterfaceTypes , bodyDeclarations ) ; } @ Override public InterfaceDeclaration newInterfaceDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeParameterDeclaration > typeParameters , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { return this . newInterfaceDeclaration0 ( javadoc , modifiers , name , typeParameters , superInterfaceTypes , bodyDeclarations ) ; } private InterfaceDeclarationImpl newInterfaceDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , SimpleName name , List < ? extends TypeParameterDeclaration > typeParameters , List < ? extends Type > superInterfaceTypes , List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( name , "" ) ; Util . notNull ( typeParameters , "" ) ; Util . notContainNull ( typeParameters , "" ) ; Util . notNull ( superInterfaceTypes , "" ) ; Util . notContainNull ( superInterfaceTypes , "" ) ; Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; InterfaceDeclarationImpl result = new InterfaceDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setName ( name ) ; result . setTypeParameters ( typeParameters ) ; result . setSuperInterfaceTypes ( superInterfaceTypes ) ; result . setBodyDeclarations ( bodyDeclarations ) ; return result ; } @ Override public Javadoc newJavadoc ( List < ? extends DocBlock > blocks ) { return this . newJavadoc0 ( blocks ) ; } private JavadocImpl newJavadoc0 ( List < ? extends DocBlock > blocks ) { Util . notNull ( blocks , "" ) ; Util . notContainNull ( blocks , "" ) ; JavadocImpl result = new JavadocImpl ( ) ; result . setBlocks ( blocks ) ; return result ; } @ Override public LabeledStatement newLabeledStatement ( SimpleName label , Statement body ) { return this . newLabeledStatement0 ( label , body ) ; } private LabeledStatementImpl newLabeledStatement0 ( SimpleName label , Statement body ) { Util . notNull ( label , "" ) ; Util . notNull ( body , "" ) ; LabeledStatementImpl result = new LabeledStatementImpl ( ) ; result . setLabel ( label ) ; result . setBody ( body ) ; return result ; } @ Override public LineComment newLineComment ( String string ) { return this . newLineComment0 ( string ) ; } private LineCommentImpl newLineComment0 ( String string ) { Util . notNull ( string , "" ) ; LineCommentImpl result = new LineCommentImpl ( ) ; result . setString ( string ) ; return result ; } @ Override public Literal newLiteral ( String token ) { return this . newLiteral0 ( token ) ; } private LiteralImpl newLiteral0 ( String token ) { Util . notNull ( token , "" ) ; LiteralImpl result = new LiteralImpl ( ) ; result . setToken ( token ) ; return result ; } @ Override public LocalClassDeclaration newLocalClassDeclaration ( ClassDeclaration declaration ) { return this . newLocalClassDeclaration0 ( declaration ) ; } private LocalClassDeclarationImpl newLocalClassDeclaration0 ( ClassDeclaration declaration ) { Util . notNull ( declaration , "" ) ; LocalClassDeclarationImpl result = new LocalClassDeclarationImpl ( ) ; result . setDeclaration ( declaration ) ; return result ; } @ Override public LocalVariableDeclaration newLocalVariableDeclaration ( Type type , SimpleName name , Expression initializer ) { return this . newLocalVariableDeclaration0 ( Collections . < Attribute > emptyList ( ) , type , Collections . singletonList ( newVariableDeclarator ( name , , initializer ) ) ) ; } @ Override public LocalVariableDeclaration newLocalVariableDeclaration ( List < ? extends Attribute > modifiers , Type type , List < ? extends VariableDeclarator > variableDeclarators ) { return this . newLocalVariableDeclaration0 ( modifiers , type , variableDeclarators ) ; } private LocalVariableDeclarationImpl newLocalVariableDeclaration0 ( List < ? extends Attribute > modifiers , Type type , List < ? extends VariableDeclarator > variableDeclarators ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( type , "" ) ; Util . notNull ( variableDeclarators , "" ) ; Util . notContainNull ( variableDeclarators , "" ) ; Util . notEmpty ( variableDeclarators , "" ) ; LocalVariableDeclarationImpl result = new LocalVariableDeclarationImpl ( ) ; result . setModifiers ( modifiers ) ; result . setType ( type ) ; result . setVariableDeclarators ( variableDeclarators ) ; return result ; } @ Override public MarkerAnnotation newMarkerAnnotation ( NamedType type ) { return this . newMarkerAnnotation0 ( type ) ; } private MarkerAnnotationImpl newMarkerAnnotation0 ( NamedType type ) { Util . notNull ( type , "" ) ; MarkerAnnotationImpl result = new MarkerAnnotationImpl ( ) ; result . setType ( type ) ; return result ; } @ Override public MethodDeclaration newMethodDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , Type returnType , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , List < ? extends Statement > statements ) { Util . notNull ( statements , "" ) ; return this . newMethodDeclaration0 ( javadoc , modifiers , Collections . < TypeParameterDeclaration > emptyList ( ) , returnType , name , formalParameters , , Collections . < Type > emptyList ( ) , newBlock ( statements ) ) ; } @ Override public MethodDeclaration newMethodDeclaration ( Javadoc javadoc , List < ? extends Attribute > modifiers , List < ? extends TypeParameterDeclaration > typeParameters , Type returnType , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , int extraDimensions , List < ? extends Type > exceptionTypes , Block body ) { return this . newMethodDeclaration0 ( javadoc , modifiers , typeParameters , returnType , name , formalParameters , extraDimensions , exceptionTypes , body ) ; } private MethodDeclarationImpl newMethodDeclaration0 ( Javadoc javadoc , List < ? extends Attribute > modifiers , List < ? extends TypeParameterDeclaration > typeParameters , Type returnType , SimpleName name , List < ? extends FormalParameterDeclaration > formalParameters , int extraDimensions , List < ? extends Type > exceptionTypes , Block body ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; Util . notNull ( typeParameters , "" ) ; Util . notContainNull ( typeParameters , "" ) ; Util . notNull ( returnType , "" ) ; Util . notNull ( name , "" ) ; Util . notNull ( formalParameters , "" ) ; Util . notContainNull ( formalParameters , "" ) ; Util . notNull ( exceptionTypes , "" ) ; Util . notContainNull ( exceptionTypes , "" ) ; MethodDeclarationImpl result = new MethodDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setModifiers ( modifiers ) ; result . setTypeParameters ( typeParameters ) ; result . setReturnType ( returnType ) ; result . setName ( name ) ; result . setFormalParameters ( formalParameters ) ; result . setExtraDimensions ( extraDimensions ) ; result . setExceptionTypes ( exceptionTypes ) ; result . setBody ( body ) ; return result ; } @ Override public MethodInvocationExpression newMethodInvocationExpression ( Expression qualifier , SimpleName name , Expression ... arguments ) { Util . notNull ( arguments , "" ) ; return this . newMethodInvocationExpression0 ( qualifier , Collections . < Type > emptyList ( ) , name , Arrays . asList ( arguments ) ) ; } @ Override public MethodInvocationExpression newMethodInvocationExpression ( Expression qualifier , SimpleName name , List < ? extends Expression > arguments ) { return this . newMethodInvocationExpression0 ( qualifier , Collections . < Type > emptyList ( ) , name , arguments ) ; } @ Override public MethodInvocationExpression newMethodInvocationExpression ( Expression qualifier , List < ? extends Type > typeArguments , SimpleName name , List < ? extends Expression > arguments ) { return this . newMethodInvocationExpression0 ( qualifier , typeArguments , name , arguments ) ; } private MethodInvocationExpressionImpl newMethodInvocationExpression0 ( Expression qualifier , List < ? extends Type > typeArguments , SimpleName name , List < ? extends Expression > arguments ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; Util . notNull ( name , "" ) ; Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; MethodInvocationExpressionImpl result = new MethodInvocationExpressionImpl ( ) ; result . setQualifier ( qualifier ) ; result . setTypeArguments ( typeArguments ) ; result . setName ( name ) ; result . setArguments ( arguments ) ; return result ; } @ Override public Modifier newModifier ( ModifierKind modifierKind ) { return this . newModifier0 ( modifierKind ) ; } private ModifierImpl newModifier0 ( ModifierKind modifierKind ) { Util . notNull ( modifierKind , "" ) ; ModifierImpl result = new ModifierImpl ( ) ; result . setModifierKind ( modifierKind ) ; return result ; } @ Override public NamedType newNamedType ( Name name ) { return this . newNamedType0 ( name ) ; } private NamedTypeImpl newNamedType0 ( Name name ) { Util . notNull ( name , "" ) ; NamedTypeImpl result = new NamedTypeImpl ( ) ; result . setName ( name ) ; return result ; } @ Override public NormalAnnotation newNormalAnnotation ( NamedType type , List < ? extends AnnotationElement > elements ) { return this . newNormalAnnotation0 ( type , elements ) ; } private NormalAnnotationImpl newNormalAnnotation0 ( NamedType type , List < ? extends AnnotationElement > elements ) { Util . notNull ( type , "" ) ; Util . notNull ( elements , "" ) ; Util . notContainNull ( elements , "" ) ; NormalAnnotationImpl result = new NormalAnnotationImpl ( ) ; result . setType ( type ) ; result . setElements ( elements ) ; return result ; } @ Override public PackageDeclaration newPackageDeclaration ( Name name ) { return this . newPackageDeclaration0 ( null , Collections . < Annotation > emptyList ( ) , name ) ; } @ Override public PackageDeclaration newPackageDeclaration ( Javadoc javadoc , List < ? extends Annotation > annotations , Name name ) { return this . newPackageDeclaration0 ( javadoc , annotations , name ) ; } private PackageDeclarationImpl newPackageDeclaration0 ( Javadoc javadoc , List < ? extends Annotation > annotations , Name name ) { Util . notNull ( annotations , "" ) ; Util . notContainNull ( annotations , "" ) ; Util . notNull ( name , "" ) ; PackageDeclarationImpl result = new PackageDeclarationImpl ( ) ; result . setJavadoc ( javadoc ) ; result . setAnnotations ( annotations ) ; result . setName ( name ) ; return result ; } @ Override public ParameterizedType newParameterizedType ( Type type , Type ... typeArguments ) { Util . notNull ( typeArguments , "" ) ; return this . newParameterizedType0 ( type , Arrays . asList ( typeArguments ) ) ; } @ Override public ParameterizedType newParameterizedType ( Type type , List < ? extends Type > typeArguments ) { return this . newParameterizedType0 ( type , typeArguments ) ; } private ParameterizedTypeImpl newParameterizedType0 ( Type type , List < ? extends Type > typeArguments ) { Util . notNull ( type , "" ) ; Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; Util . notEmpty ( typeArguments , "" ) ; ParameterizedTypeImpl result = new ParameterizedTypeImpl ( ) ; result . setType ( type ) ; result . setTypeArguments ( typeArguments ) ; return result ; } @ Override public ParenthesizedExpression newParenthesizedExpression ( Expression expression ) { return this . newParenthesizedExpression0 ( expression ) ; } private ParenthesizedExpressionImpl newParenthesizedExpression0 ( Expression expression ) { Util . notNull ( expression , "" ) ; ParenthesizedExpressionImpl result = new ParenthesizedExpressionImpl ( ) ; result . setExpression ( expression ) ; return result ; } @ Override public PostfixExpression newPostfixExpression ( Expression operand , PostfixOperator operator ) { return this . newPostfixExpression0 ( operand , operator ) ; } private PostfixExpressionImpl newPostfixExpression0 ( Expression operand , PostfixOperator operator ) { Util . notNull ( operand , "" ) ; Util . notNull ( operator , "" ) ; PostfixExpressionImpl result = new PostfixExpressionImpl ( ) ; result . setOperand ( parenthesize ( operand , ExpressionPriority . UNARY ) ) ; result . setOperator ( operator ) ; return result ; } @ Override public QualifiedName newQualifiedName ( Name qualifier , SimpleName simpleName ) { return this . newQualifiedName0 ( qualifier , simpleName ) ; } private QualifiedNameImpl newQualifiedName0 ( Name qualifier , SimpleName simpleName ) { Util . notNull ( qualifier , "" ) ; Util . notNull ( simpleName , "" ) ; QualifiedNameImpl result = new QualifiedNameImpl ( ) ; result . setQualifier ( qualifier ) ; result . setSimpleName ( simpleName ) ; return result ; } @ Override public QualifiedType newQualifiedType ( Type qualifier , SimpleName simpleName ) { return this . newQualifiedType0 ( qualifier , simpleName ) ; } private QualifiedTypeImpl newQualifiedType0 ( Type qualifier , SimpleName simpleName ) { Util . notNull ( qualifier , "" ) ; Util . notNull ( simpleName , "" ) ; QualifiedTypeImpl result = new QualifiedTypeImpl ( ) ; result . setQualifier ( qualifier ) ; result . setSimpleName ( simpleName ) ; return result ; } @ Override public ReturnStatement newReturnStatement ( ) { return this . newReturnStatement0 ( null ) ; } @ Override public ReturnStatement newReturnStatement ( Expression expression ) { return this . newReturnStatement0 ( expression ) ; } private ReturnStatementImpl newReturnStatement0 ( Expression expression ) { ReturnStatementImpl result = new ReturnStatementImpl ( ) ; result . setExpression ( expression ) ; return result ; } @ Override public SimpleName newSimpleName ( String string ) { return this . newSimpleName0 ( string ) ; } private SimpleNameImpl newSimpleName0 ( String string ) { Util . notNull ( string , "" ) ; SimpleNameImpl result = new SimpleNameImpl ( ) ; result . setToken ( string ) ; return result ; } @ Override public SingleElementAnnotation newSingleElementAnnotation ( NamedType type , Expression expression ) { return this . newSingleElementAnnotation0 ( type , expression ) ; } private SingleElementAnnotationImpl newSingleElementAnnotation0 ( NamedType type , Expression expression ) { Util . notNull ( type , "" ) ; Util . notNull ( expression , "" ) ; SingleElementAnnotationImpl result = new SingleElementAnnotationImpl ( ) ; result . setType ( type ) ; result . setExpression ( expression ) ; return result ; } @ Override public StatementExpressionList newStatementExpressionList ( Expression ... expressions ) { Util . notNull ( expressions , "" ) ; return this . newStatementExpressionList0 ( Arrays . asList ( expressions ) ) ; } @ Override public StatementExpressionList newStatementExpressionList ( List < ? extends Expression > expressions ) { return this . newStatementExpressionList0 ( expressions ) ; } private StatementExpressionListImpl newStatementExpressionList0 ( List < ? extends Expression > expressions ) { Util . notNull ( expressions , "" ) ; Util . notContainNull ( expressions , "" ) ; Util . notEmpty ( expressions , "" ) ; StatementExpressionListImpl result = new StatementExpressionListImpl ( ) ; result . setExpressions ( expressions ) ; return result ; } @ Override public Super newSuper ( ) { return this . newSuper0 ( null ) ; } @ Override public Super newSuper ( NamedType qualifier ) { return this . newSuper0 ( qualifier ) ; } private SuperImpl newSuper0 ( NamedType qualifier ) { SuperImpl result = new SuperImpl ( ) ; result . setQualifier ( qualifier ) ; return result ; } @ Override public SuperConstructorInvocation newSuperConstructorInvocation ( Expression ... arguments ) { Util . notNull ( arguments , "" ) ; return this . newSuperConstructorInvocation0 ( null , Collections . < Type > emptyList ( ) , Arrays . asList ( arguments ) ) ; } @ Override public SuperConstructorInvocation newSuperConstructorInvocation ( List < ? extends Expression > arguments ) { return this . newSuperConstructorInvocation0 ( null , Collections . < Type > emptyList ( ) , arguments ) ; } @ Override public SuperConstructorInvocation newSuperConstructorInvocation ( Expression qualifier , List < ? extends Type > typeArguments , List < ? extends Expression > arguments ) { return this . newSuperConstructorInvocation0 ( qualifier , typeArguments , arguments ) ; } private SuperConstructorInvocationImpl newSuperConstructorInvocation0 ( Expression qualifier , List < ? extends Type > typeArguments , List < ? extends Expression > arguments ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; SuperConstructorInvocationImpl result = new SuperConstructorInvocationImpl ( ) ; result . setQualifier ( parenthesize ( qualifier , ExpressionPriority . PRIMARY ) ) ; result . setTypeArguments ( typeArguments ) ; result . setArguments ( arguments ) ; return result ; } @ Override public SwitchCaseLabel newSwitchCaseLabel ( Expression expression ) { return this . newSwitchCaseLabel0 ( expression ) ; } private SwitchCaseLabelImpl newSwitchCaseLabel0 ( Expression expression ) { Util . notNull ( expression , "" ) ; SwitchCaseLabelImpl result = new SwitchCaseLabelImpl ( ) ; result . setExpression ( expression ) ; return result ; } @ Override public SwitchDefaultLabel newSwitchDefaultLabel ( ) { return this . newSwitchDefaultLabel0 ( ) ; } private SwitchDefaultLabelImpl newSwitchDefaultLabel0 ( ) { SwitchDefaultLabelImpl result = new SwitchDefaultLabelImpl ( ) ; return result ; } @ Override public SwitchStatement newSwitchStatement ( Expression expression , List < ? extends Statement > statements ) { return this . newSwitchStatement0 ( expression , statements ) ; } private SwitchStatementImpl newSwitchStatement0 ( Expression expression , List < ? extends Statement > statements ) { Util . notNull ( expression , "" ) ; Util . notNull ( statements , "" ) ; Util . notContainNull ( statements , "" ) ; SwitchStatementImpl result = new SwitchStatementImpl ( ) ; result . setExpression ( expression ) ; result . setStatements ( statements ) ; return result ; } @ Override public SynchronizedStatement newSynchronizedStatement ( Expression expression , Block body ) { return this . newSynchronizedStatement0 ( expression , body ) ; } private SynchronizedStatementImpl newSynchronizedStatement0 ( Expression expression , Block body ) { Util . notNull ( expression , "" ) ; Util . notNull ( body , "" ) ; SynchronizedStatementImpl result = new SynchronizedStatementImpl ( ) ; result . setExpression ( expression ) ; result . setBody ( body ) ; return result ; } @ Override public This newThis ( ) { return this . newThis0 ( null ) ; } @ Override public This newThis ( NamedType qualifier ) { return this . newThis0 ( qualifier ) ; } private ThisImpl newThis0 ( NamedType qualifier ) { ThisImpl result = new ThisImpl ( ) ; result . setQualifier ( qualifier ) ; return result ; } @ Override public ThrowStatement newThrowStatement ( Expression expression ) { return this . newThrowStatement0 ( expression ) ; } private ThrowStatementImpl newThrowStatement0 ( Expression expression ) { Util . notNull ( expression , "" ) ; ThrowStatementImpl result = new ThrowStatementImpl ( ) ; result . setExpression ( expression ) ; return result ; } @ Override public TryStatement newTryStatement ( Block tryBlock , List < ? extends CatchClause > catchClauses , Block finallyBlock ) { return this . newTryStatement0 ( tryBlock , catchClauses , finallyBlock ) ; } private TryStatementImpl newTryStatement0 ( Block tryBlock , List < ? extends CatchClause > catchClauses , Block finallyBlock ) { Util . notNull ( tryBlock , "" ) ; Util . notNull ( catchClauses , "" ) ; Util . notContainNull ( catchClauses , "" ) ; TryStatementImpl result = new TryStatementImpl ( ) ; result . setTryBlock ( tryBlock ) ; result . setCatchClauses ( catchClauses ) ; result . setFinallyBlock ( finallyBlock ) ; return result ; } @ Override public TypeParameterDeclaration newTypeParameterDeclaration ( SimpleName name , Type ... typeBounds ) { Util . notNull ( typeBounds , "" ) ; return this . newTypeParameterDeclaration0 ( name , Arrays . asList ( typeBounds ) ) ; } @ Override public TypeParameterDeclaration newTypeParameterDeclaration ( SimpleName name , List < ? extends Type > typeBounds ) { return this . newTypeParameterDeclaration0 ( name , typeBounds ) ; } private TypeParameterDeclarationImpl newTypeParameterDeclaration0 ( SimpleName name , List < ? extends Type > typeBounds ) { Util . notNull ( name , "" ) ; Util . notNull ( typeBounds , "" ) ; Util . notContainNull ( typeBounds , "" ) ; TypeParameterDeclarationImpl result = new TypeParameterDeclarationImpl ( ) ; result . setName ( name ) ; result . setTypeBounds ( typeBounds ) ; return result ; } @ Override public UnaryExpression newUnaryExpression ( UnaryOperator operator , Expression operand ) { return this . newUnaryExpression0 ( operator , operand ) ; } private UnaryExpressionImpl newUnaryExpression0 ( UnaryOperator operator , Expression operand ) { Util . notNull ( operator , "" ) ; Util . notNull ( operand , "" ) ; UnaryExpressionImpl result = new UnaryExpressionImpl ( ) ; result . setOperator ( operator ) ; result . setOperand ( parenthesize ( operand , ExpressionPriority . UNARY ) ) ; return result ; } @ Override public VariableDeclarator newVariableDeclarator ( SimpleName name , Expression initializer ) { return this . newVariableDeclarator0 ( name , , initializer ) ; } @ Override public VariableDeclarator newVariableDeclarator ( SimpleName name , int extraDimensions , Expression initializer ) { return this . newVariableDeclarator0 ( name , extraDimensions , initializer ) ; } private VariableDeclaratorImpl newVariableDeclarator0 ( SimpleName name , int extraDimensions , Expression initializer ) { Util . notNull ( name , "" ) ; VariableDeclaratorImpl result = new VariableDeclaratorImpl ( ) ; result . setName ( name ) ; result . setExtraDimensions ( extraDimensions ) ; result . setInitializer ( initializer ) ; return result ; } @ Override public WhileStatement newWhileStatement ( Expression condition , Statement body ) { return this . newWhileStatement0 ( condition , body ) ; } private WhileStatementImpl newWhileStatement0 ( Expression condition , Statement body ) { Util . notNull ( condition , "" ) ; Util . notNull ( body , "" ) ; WhileStatementImpl result = new WhileStatementImpl ( ) ; result . setCondition ( condition ) ; result . setBody ( body ) ; return result ; } @ Override public Wildcard newWildcard ( ) { return this . newWildcard0 ( WildcardBoundKind . UNBOUNDED , null ) ; } @ Override public Wildcard newWildcard ( WildcardBoundKind boundKind , Type typeBound ) { return this . newWildcard0 ( boundKind , typeBound ) ; } private WildcardImpl newWildcard0 ( WildcardBoundKind boundKind , Type typeBound ) { Util . notNull ( boundKind , "" ) ; WildcardImpl result = new WildcardImpl ( ) ; result . setBoundKind ( boundKind ) ; result . setTypeBound ( typeBound ) ; return result ; } private Expression parenthesize ( Expression expression , ExpressionPriority context ) { if ( expression == null ) { return null ; } ExpressionPriority priority = ExpressionPriority . valueOf ( expression ) ; if ( ExpressionPriority . isParenthesesRequired ( context , false , priority ) ) { return newParenthesizedExpression0 ( expression ) ; } else { return expression ; } } private Expression parenthesizeRight ( Expression expression , ExpressionPriority context ) { if ( expression == null ) { return null ; } ExpressionPriority priority = ExpressionPriority . valueOf ( expression ) ; if ( ExpressionPriority . isParenthesesRequired ( context , true , priority ) ) { return newParenthesizedExpression0 ( expression ) ; } else { return expression ; } } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ExpressionStatement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ExpressionStatementImpl extends ModelRoot implements ExpressionStatement { private Expression expression ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . EXPRESSION_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitExpressionStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SuperConstructorInvocation ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class SuperConstructorInvocationImpl extends ModelRoot implements SuperConstructorInvocation { private Expression qualifier ; private List < ? extends Type > typeArguments ; private List < ? extends Expression > arguments ; @ Override public Expression getQualifier ( ) { return this . qualifier ; } public void setQualifier ( Expression qualifier ) { this . qualifier = qualifier ; } @ Override public List < ? extends Type > getTypeArguments ( ) { return this . typeArguments ; } public void setTypeArguments ( List < ? extends Type > typeArguments ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; this . typeArguments = Util . freeze ( typeArguments ) ; } @ Override public List < ? extends Expression > getArguments ( ) { return this . arguments ; } public void setArguments ( List < ? extends Expression > arguments ) { Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; this . arguments = Util . freeze ( arguments ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . SUPER_CONSTRUCTOR_INVOCATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitSuperConstructorInvocation ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . BlockComment ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class BlockCommentImpl extends ModelRoot implements BlockComment { private String string ; @ Override public String getString ( ) { return this . string ; } public void setString ( String string ) { Util . notNull ( string , "" ) ; this . string = string ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . BLOCK_COMMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitBlockComment ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . BasicType ; import com . asakusafw . utils . java . model . syntax . BasicTypeKind ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class BasicTypeImpl extends ModelRoot implements BasicType { private BasicTypeKind typeKind ; @ Override public BasicTypeKind getTypeKind ( ) { return this . typeKind ; } public void setTypeKind ( BasicTypeKind typeKind ) { Util . notNull ( typeKind , "" ) ; this . typeKind = typeKind ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . BASIC_TYPE ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitBasicType ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . Block ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class MethodDeclarationImpl extends ModelRoot implements MethodDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private List < ? extends TypeParameterDeclaration > typeParameters ; private Type returnType ; private SimpleName name ; private List < ? extends FormalParameterDeclaration > formalParameters ; private int extraDimensions ; private List < ? extends Type > exceptionTypes ; private Block body ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public List < ? extends TypeParameterDeclaration > getTypeParameters ( ) { return this . typeParameters ; } public void setTypeParameters ( List < ? extends TypeParameterDeclaration > typeParameters ) { Util . notNull ( typeParameters , "" ) ; Util . notContainNull ( typeParameters , "" ) ; this . typeParameters = Util . freeze ( typeParameters ) ; } @ Override public Type getReturnType ( ) { return this . returnType ; } public void setReturnType ( Type returnType ) { Util . notNull ( returnType , "" ) ; this . returnType = returnType ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends FormalParameterDeclaration > getFormalParameters ( ) { return this . formalParameters ; } public void setFormalParameters ( List < ? extends FormalParameterDeclaration > formalParameters ) { Util . notNull ( formalParameters , "" ) ; Util . notContainNull ( formalParameters , "" ) ; this . formalParameters = Util . freeze ( formalParameters ) ; } @ Override public int getExtraDimensions ( ) { return this . extraDimensions ; } public void setExtraDimensions ( int extraDimensions ) { this . extraDimensions = extraDimensions ; } @ Override public List < ? extends Type > getExceptionTypes ( ) { return this . exceptionTypes ; } public void setExceptionTypes ( List < ? extends Type > exceptionTypes ) { Util . notNull ( exceptionTypes , "" ) ; Util . notContainNull ( exceptionTypes , "" ) ; this . exceptionTypes = Util . freeze ( exceptionTypes ) ; } @ Override public Block getBody ( ) { return this . body ; } public void setBody ( Block body ) { this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . METHOD_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitMethodDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . AlternateConstructorInvocation ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class AlternateConstructorInvocationImpl extends ModelRoot implements AlternateConstructorInvocation { private List < ? extends Type > typeArguments ; private List < ? extends Expression > arguments ; @ Override public List < ? extends Type > getTypeArguments ( ) { return this . typeArguments ; } public void setTypeArguments ( List < ? extends Type > typeArguments ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; this . typeArguments = Util . freeze ( typeArguments ) ; } @ Override public List < ? extends Expression > getArguments ( ) { return this . arguments ; } public void setArguments ( List < ? extends Expression > arguments ) { Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; this . arguments = Util . freeze ( arguments ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ALTERNATE_CONSTRUCTOR_INVOCATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitAlternateConstructorInvocation ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . ThrowStatement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ThrowStatementImpl extends ModelRoot implements ThrowStatement { private Expression expression ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . THROW_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitThrowStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . DocField ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class DocFieldImpl extends ModelRoot implements DocField { private Type type ; private SimpleName name ; @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { this . type = type ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . DOC_FIELD ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitDocField ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . Super ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class SuperImpl extends ModelRoot implements Super { private NamedType qualifier ; @ Override public NamedType getQualifier ( ) { return this . qualifier ; } public void setQualifier ( NamedType qualifier ) { this . qualifier = qualifier ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . SUPER ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitSuper ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Block ; import com . asakusafw . utils . java . model . syntax . CatchClause ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . TryStatement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class TryStatementImpl extends ModelRoot implements TryStatement { private Block tryBlock ; private List < ? extends CatchClause > catchClauses ; private Block finallyBlock ; @ Override public Block getTryBlock ( ) { return this . tryBlock ; } public void setTryBlock ( Block tryBlock ) { Util . notNull ( tryBlock , "" ) ; this . tryBlock = tryBlock ; } @ Override public List < ? extends CatchClause > getCatchClauses ( ) { return this . catchClauses ; } public void setCatchClauses ( List < ? extends CatchClause > catchClauses ) { Util . notNull ( catchClauses , "" ) ; Util . notContainNull ( catchClauses , "" ) ; this . catchClauses = Util . freeze ( catchClauses ) ; } @ Override public Block getFinallyBlock ( ) { return this . finallyBlock ; } public void setFinallyBlock ( Block finallyBlock ) { this . finallyBlock = finallyBlock ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . TRY_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitTryStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Block ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SynchronizedStatement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class SynchronizedStatementImpl extends ModelRoot implements SynchronizedStatement { private Expression expression ; private Block body ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public Block getBody ( ) { return this . body ; } public void setBody ( Block body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . SYNCHRONIZED_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitSynchronizedStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . AnnotationElement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . NormalAnnotation ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class NormalAnnotationImpl extends ModelRoot implements NormalAnnotation { private NamedType type ; private List < ? extends AnnotationElement > elements ; @ Override public NamedType getType ( ) { return this . type ; } public void setType ( NamedType type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public List < ? extends AnnotationElement > getElements ( ) { return this . elements ; } public void setElements ( List < ? extends AnnotationElement > elements ) { Util . notNull ( elements , "" ) ; Util . notContainNull ( elements , "" ) ; this . elements = Util . freeze ( elements ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . NORMAL_ANNOTATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitNormalAnnotation ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class TypeParameterDeclarationImpl extends ModelRoot implements TypeParameterDeclaration { private SimpleName name ; private List < ? extends Type > typeBounds ; @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends Type > getTypeBounds ( ) { return this . typeBounds ; } public void setTypeBounds ( List < ? extends Type > typeBounds ) { Util . notNull ( typeBounds , "" ) ; Util . notContainNull ( typeBounds , "" ) ; this . typeBounds = Util . freeze ( typeBounds ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . TYPE_PARAMETER_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitTypeParameterDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . ClassBody ; import com . asakusafw . utils . java . model . syntax . ClassInstanceCreationExpression ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ClassInstanceCreationExpressionImpl extends ModelRoot implements ClassInstanceCreationExpression { private Expression qualifier ; private List < ? extends Type > typeArguments ; private Type type ; private List < ? extends Expression > arguments ; private ClassBody body ; @ Override public Expression getQualifier ( ) { return this . qualifier ; } public void setQualifier ( Expression qualifier ) { this . qualifier = qualifier ; } @ Override public List < ? extends Type > getTypeArguments ( ) { return this . typeArguments ; } public void setTypeArguments ( List < ? extends Type > typeArguments ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; this . typeArguments = Util . freeze ( typeArguments ) ; } @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public List < ? extends Expression > getArguments ( ) { return this . arguments ; } public void setArguments ( List < ? extends Expression > arguments ) { Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; this . arguments = Util . freeze ( arguments ) ; } @ Override public ClassBody getBody ( ) { return this . body ; } public void setBody ( ClassBody body ) { this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CLASS_INSTANCE_CREATION_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitClassInstanceCreationExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . EmptyStatement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class EmptyStatementImpl extends ModelRoot implements EmptyStatement { @ Override public ModelKind getModelKind ( ) { return ModelKind . EMPTY_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitEmptyStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . LineComment ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class LineCommentImpl extends ModelRoot implements LineComment { private String string ; @ Override public String getString ( ) { return this . string ; } public void setString ( String string ) { Util . notNull ( string , "" ) ; this . string = string ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . LINE_COMMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitLineComment ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . DocText ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class DocTextImpl extends ModelRoot implements DocText { private String string ; @ Override public String getString ( ) { return this . string ; } public void setString ( String string ) { Util . notNull ( string , "" ) ; this . string = string ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . DOC_TEXT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitDocText ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Visitor ; import com . asakusafw . utils . java . model . syntax . WhileStatement ; public final class WhileStatementImpl extends ModelRoot implements WhileStatement { private Expression condition ; private Statement body ; @ Override public Expression getCondition ( ) { return this . condition ; } public void setCondition ( Expression condition ) { Util . notNull ( condition , "" ) ; this . condition = condition ; } @ Override public Statement getBody ( ) { return this . body ; } public void setBody ( Statement body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . WHILE_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitWhileStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ConditionalExpression ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ConditionalExpressionImpl extends ModelRoot implements ConditionalExpression { private Expression condition ; private Expression thenExpression ; private Expression elseExpression ; @ Override public Expression getCondition ( ) { return this . condition ; } public void setCondition ( Expression condition ) { Util . notNull ( condition , "" ) ; this . condition = condition ; } @ Override public Expression getThenExpression ( ) { return this . thenExpression ; } public void setThenExpression ( Expression thenExpression ) { Util . notNull ( thenExpression , "" ) ; this . thenExpression = thenExpression ; } @ Override public Expression getElseExpression ( ) { return this . elseExpression ; } public void setElseExpression ( Expression elseExpression ) { Util . notNull ( elseExpression , "" ) ; this . elseExpression = elseExpression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CONDITIONAL_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitConditionalExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . DocBlock ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class JavadocImpl extends ModelRoot implements Javadoc { private List < ? extends DocBlock > blocks ; @ Override public List < ? extends DocBlock > getBlocks ( ) { return this . blocks ; } public void setBlocks ( List < ? extends DocBlock > blocks ) { Util . notNull ( blocks , "" ) ; Util . notContainNull ( blocks , "" ) ; this . blocks = Util . freeze ( blocks ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . JAVADOC ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitJavadoc ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . DocMethod ; import com . asakusafw . utils . java . model . syntax . DocMethodParameter ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class DocMethodImpl extends ModelRoot implements DocMethod { private Type type ; private SimpleName name ; private List < ? extends DocMethodParameter > formalParameters ; @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { this . type = type ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends DocMethodParameter > getFormalParameters ( ) { return this . formalParameters ; } public void setFormalParameters ( List < ? extends DocMethodParameter > formalParameters ) { Util . notNull ( formalParameters , "" ) ; Util . notContainNull ( formalParameters , "" ) ; this . formalParameters = Util . freeze ( formalParameters ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . DOC_METHOD ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitDocMethod ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . SwitchStatement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class SwitchStatementImpl extends ModelRoot implements SwitchStatement { private Expression expression ; private List < ? extends Statement > statements ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public List < ? extends Statement > getStatements ( ) { return this . statements ; } public void setStatements ( List < ? extends Statement > statements ) { Util . notNull ( statements , "" ) ; Util . notContainNull ( statements , "" ) ; this . statements = Util . freeze ( statements ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . SWITCH_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitSwitchStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . VariableDeclarator ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class VariableDeclaratorImpl extends ModelRoot implements VariableDeclarator { private SimpleName name ; private int extraDimensions ; private Expression initializer ; @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public int getExtraDimensions ( ) { return this . extraDimensions ; } public void setExtraDimensions ( int extraDimensions ) { this . extraDimensions = extraDimensions ; } @ Override public Expression getInitializer ( ) { return this . initializer ; } public void setInitializer ( Expression initializer ) { this . initializer = initializer ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . VARIABLE_DECLARATOR ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitVariableDeclarator ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . ArrayInitializer ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ArrayInitializerImpl extends ModelRoot implements ArrayInitializer { private List < ? extends Expression > elements ; @ Override public List < ? extends Expression > getElements ( ) { return this . elements ; } public void setElements ( List < ? extends Expression > elements ) { Util . notNull ( elements , "" ) ; Util . notContainNull ( elements , "" ) ; this . elements = Util . freeze ( elements ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ARRAY_INITIALIZER ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitArrayInitializer ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Modifier ; import com . asakusafw . utils . java . model . syntax . ModifierKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ModifierImpl extends ModelRoot implements Modifier { private ModifierKind modifierKind ; @ Override public ModifierKind getModifierKind ( ) { return this . modifierKind ; } public void setModifierKind ( ModifierKind modifierKind ) { Util . notNull ( modifierKind , "" ) ; this . modifierKind = modifierKind ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . MODIFIER ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitModifier ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class PackageDeclarationImpl extends ModelRoot implements PackageDeclaration { private Javadoc javadoc ; private List < ? extends Annotation > annotations ; private Name name ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Annotation > getAnnotations ( ) { return this . annotations ; } public void setAnnotations ( List < ? extends Annotation > annotations ) { Util . notNull ( annotations , "" ) ; Util . notContainNull ( annotations , "" ) ; this . annotations = Util . freeze ( annotations ) ; } @ Override public Name getName ( ) { return this . name ; } public void setName ( Name name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . PACKAGE_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitPackageDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . SingleElementAnnotation ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class SingleElementAnnotationImpl extends ModelRoot implements SingleElementAnnotation { private NamedType type ; private Expression expression ; @ Override public NamedType getType ( ) { return this . type ; } public void setType ( NamedType type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . SINGLE_ELEMENT_ANNOTATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitSingleElementAnnotation ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . Block ; import com . asakusafw . utils . java . model . syntax . ConstructorDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ConstructorDeclarationImpl extends ModelRoot implements ConstructorDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private List < ? extends TypeParameterDeclaration > typeParameters ; private SimpleName name ; private List < ? extends FormalParameterDeclaration > formalParameters ; private List < ? extends Type > exceptionTypes ; private Block body ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public List < ? extends TypeParameterDeclaration > getTypeParameters ( ) { return this . typeParameters ; } public void setTypeParameters ( List < ? extends TypeParameterDeclaration > typeParameters ) { Util . notNull ( typeParameters , "" ) ; Util . notContainNull ( typeParameters , "" ) ; this . typeParameters = Util . freeze ( typeParameters ) ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends FormalParameterDeclaration > getFormalParameters ( ) { return this . formalParameters ; } public void setFormalParameters ( List < ? extends FormalParameterDeclaration > formalParameters ) { Util . notNull ( formalParameters , "" ) ; Util . notContainNull ( formalParameters , "" ) ; this . formalParameters = Util . freeze ( formalParameters ) ; } @ Override public List < ? extends Type > getExceptionTypes ( ) { return this . exceptionTypes ; } public void setExceptionTypes ( List < ? extends Type > exceptionTypes ) { Util . notNull ( exceptionTypes , "" ) ; Util . notContainNull ( exceptionTypes , "" ) ; this . exceptionTypes = Util . freeze ( exceptionTypes ) ; } @ Override public Block getBody ( ) { return this . body ; } public void setBody ( Block body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CONSTRUCTOR_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitConstructorDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . InterfaceDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class InterfaceDeclarationImpl extends ModelRoot implements InterfaceDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private SimpleName name ; private List < ? extends TypeParameterDeclaration > typeParameters ; private List < ? extends Type > superInterfaceTypes ; private List < ? extends TypeBodyDeclaration > bodyDeclarations ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends TypeParameterDeclaration > getTypeParameters ( ) { return this . typeParameters ; } public void setTypeParameters ( List < ? extends TypeParameterDeclaration > typeParameters ) { Util . notNull ( typeParameters , "" ) ; Util . notContainNull ( typeParameters , "" ) ; this . typeParameters = Util . freeze ( typeParameters ) ; } @ Override public List < ? extends Type > getSuperInterfaceTypes ( ) { return this . superInterfaceTypes ; } public void setSuperInterfaceTypes ( List < ? extends Type > superInterfaceTypes ) { Util . notNull ( superInterfaceTypes , "" ) ; Util . notContainNull ( superInterfaceTypes , "" ) ; this . superInterfaceTypes = Util . freeze ( superInterfaceTypes ) ; } @ Override public List < ? extends TypeBodyDeclaration > getBodyDeclarations ( ) { return this . bodyDeclarations ; } public void setBodyDeclarations ( List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; this . bodyDeclarations = Util . freeze ( bodyDeclarations ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . INTERFACE_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitInterfaceDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . DoStatement ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class DoStatementImpl extends ModelRoot implements DoStatement { private Statement body ; private Expression condition ; @ Override public Statement getBody ( ) { return this . body ; } public void setBody ( Statement body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public Expression getCondition ( ) { return this . condition ; } public void setCondition ( Expression condition ) { Util . notNull ( condition , "" ) ; this . condition = condition ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . DO_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitDoStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ContinueStatement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ContinueStatementImpl extends ModelRoot implements ContinueStatement { private SimpleName target ; @ Override public SimpleName getTarget ( ) { return this . target ; } public void setTarget ( SimpleName target ) { this . target = target ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CONTINUE_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitContinueStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . AnnotationElement ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class AnnotationElementImpl extends ModelRoot implements AnnotationElement { private SimpleName name ; private Expression expression ; @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ANNOTATION_ELEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitAnnotationElement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . MethodInvocationExpression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class MethodInvocationExpressionImpl extends ModelRoot implements MethodInvocationExpression { private Expression qualifier ; private List < ? extends Type > typeArguments ; private SimpleName name ; private List < ? extends Expression > arguments ; @ Override public Expression getQualifier ( ) { return this . qualifier ; } public void setQualifier ( Expression qualifier ) { this . qualifier = qualifier ; } @ Override public List < ? extends Type > getTypeArguments ( ) { return this . typeArguments ; } public void setTypeArguments ( List < ? extends Type > typeArguments ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; this . typeArguments = Util . freeze ( typeArguments ) ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends Expression > getArguments ( ) { return this . arguments ; } public void setArguments ( List < ? extends Expression > arguments ) { Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; this . arguments = Util . freeze ( arguments ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . METHOD_INVOCATION_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitMethodInvocationExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . PostfixExpression ; import com . asakusafw . utils . java . model . syntax . PostfixOperator ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class PostfixExpressionImpl extends ModelRoot implements PostfixExpression { private Expression operand ; private PostfixOperator operator ; @ Override public Expression getOperand ( ) { return this . operand ; } public void setOperand ( Expression operand ) { Util . notNull ( operand , "" ) ; this . operand = operand ; } @ Override public PostfixOperator getOperator ( ) { return this . operator ; } public void setOperator ( PostfixOperator operator ) { Util . notNull ( operator , "" ) ; this . operator = operator ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . POSTFIX_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitPostfixExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . AssertStatement ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class AssertStatementImpl extends ModelRoot implements AssertStatement { private Expression expression ; private Expression message ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public Expression getMessage ( ) { return this . message ; } public void setMessage ( Expression message ) { this . message = message ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ASSERT_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitAssertStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; final class Util { private Util ( ) { return ; } static void notNull ( Object reference , String name ) { if ( reference == null ) { throw new IllegalArgumentException ( name + "" ) ; } } static void notContainNull ( Iterable < ? > references , String name ) { for ( Object o : references ) { notNull ( o , name ) ; } } static < T > List < T > freeze ( List < ? extends T > list ) { return Collections . unmodifiableList ( new ArrayList < T > ( list ) ) ; } static void notEmpty ( Collection < ? > collection , String name ) { if ( collection . isEmpty ( ) ) { throw new IllegalArgumentException ( name + "" ) ; } } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . LabeledStatement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class LabeledStatementImpl extends ModelRoot implements LabeledStatement { private SimpleName label ; private Statement body ; @ Override public SimpleName getLabel ( ) { return this . label ; } public void setLabel ( SimpleName label ) { Util . notNull ( label , "" ) ; this . label = label ; } @ Override public Statement getBody ( ) { return this . body ; } public void setBody ( Statement body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . LABELED_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitLabeledStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . EnhancedForStatement ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class EnhancedForStatementImpl extends ModelRoot implements EnhancedForStatement { private FormalParameterDeclaration parameter ; private Expression expression ; private Statement body ; @ Override public FormalParameterDeclaration getParameter ( ) { return this . parameter ; } public void setParameter ( FormalParameterDeclaration parameter ) { Util . notNull ( parameter , "" ) ; this . parameter = parameter ; } @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public Statement getBody ( ) { return this . body ; } public void setBody ( Statement body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ENHANCED_FOR_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitEnhancedForStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . ClassBody ; import com . asakusafw . utils . java . model . syntax . EnumConstantDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class EnumConstantDeclarationImpl extends ModelRoot implements EnumConstantDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private SimpleName name ; private List < ? extends Expression > arguments ; private ClassBody body ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends Expression > getArguments ( ) { return this . arguments ; } public void setArguments ( List < ? extends Expression > arguments ) { Util . notNull ( arguments , "" ) ; Util . notContainNull ( arguments , "" ) ; this . arguments = Util . freeze ( arguments ) ; } @ Override public ClassBody getBody ( ) { return this . body ; } public void setBody ( ClassBody body ) { this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ENUM_CONSTANT_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitEnumConstantDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . LocalClassDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class LocalClassDeclarationImpl extends ModelRoot implements LocalClassDeclaration { private ClassDeclaration declaration ; @ Override public ClassDeclaration getDeclaration ( ) { return this . declaration ; } public void setDeclaration ( ClassDeclaration declaration ) { Util . notNull ( declaration , "" ) ; this . declaration = declaration ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . LOCAL_CLASS_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitLocalClassDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . AnnotationDeclaration ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class AnnotationDeclarationImpl extends ModelRoot implements AnnotationDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private SimpleName name ; private List < ? extends TypeBodyDeclaration > bodyDeclarations ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public List < ? extends TypeBodyDeclaration > getBodyDeclarations ( ) { return this . bodyDeclarations ; } public void setBodyDeclarations ( List < ? extends TypeBodyDeclaration > bodyDeclarations ) { Util . notNull ( bodyDeclarations , "" ) ; Util . notContainNull ( bodyDeclarations , "" ) ; this . bodyDeclarations = Util . freeze ( bodyDeclarations ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ANNOTATION_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitAnnotationDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . QualifiedName ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class QualifiedNameImpl extends ModelRoot implements QualifiedName { private Name qualifier ; private SimpleName simpleName ; @ Override public Name getQualifier ( ) { return this . qualifier ; } public void setQualifier ( Name qualifier ) { Util . notNull ( qualifier , "" ) ; this . qualifier = qualifier ; } @ Override public SimpleName getSimpleName ( ) { return this . simpleName ; } public void setSimpleName ( SimpleName simpleName ) { Util . notNull ( simpleName , "" ) ; this . simpleName = simpleName ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . QUALIFIED_NAME ; } @ Override public SimpleName getLastSegment ( ) { return getSimpleName ( ) ; } @ Override public String toNameString ( ) { Iterator < SimpleName > iter = toNameList ( ) . iterator ( ) ; assert iter . hasNext ( ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( iter . next ( ) ) ; while ( iter . hasNext ( ) ) { buf . append ( '' ) ; buf . append ( iter . next ( ) ) ; } return buf . toString ( ) ; } @ Override public List < SimpleName > toNameList ( ) { LinkedList < SimpleName > result = new LinkedList < SimpleName > ( ) ; result . addFirst ( getSimpleName ( ) ) ; Name current = getQualifier ( ) ; while ( current . getModelKind ( ) == ModelKind . QUALIFIED_NAME ) { QualifiedName qname = ( QualifiedName ) current ; result . addFirst ( qname . getSimpleName ( ) ) ; current = qname . getQualifier ( ) ; } assert current . getModelKind ( ) == ModelKind . SIMPLE_NAME ; result . addFirst ( ( SimpleName ) current ) ; return result ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitQualifiedName ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . CastExpression ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class CastExpressionImpl extends ModelRoot implements CastExpression { private Type type ; private Expression expression ; @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CAST_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitCastExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . ParenthesizedExpression ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ParenthesizedExpressionImpl extends ModelRoot implements ParenthesizedExpression { private Expression expression ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . PARENTHESIZED_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitParenthesizedExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . BreakStatement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class BreakStatementImpl extends ModelRoot implements BreakStatement { private SimpleName target ; @ Override public SimpleName getTarget ( ) { return this . target ; } public void setTarget ( SimpleName target ) { this . target = target ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . BREAK_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitBreakStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . ReturnStatement ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ReturnStatementImpl extends ModelRoot implements ReturnStatement { private Expression expression ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { this . expression = expression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . RETURN_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitReturnStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . ParameterizedType ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ParameterizedTypeImpl extends ModelRoot implements ParameterizedType { private Type type ; private List < ? extends Type > typeArguments ; @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public List < ? extends Type > getTypeArguments ( ) { return this . typeArguments ; } public void setTypeArguments ( List < ? extends Type > typeArguments ) { Util . notNull ( typeArguments , "" ) ; Util . notContainNull ( typeArguments , "" ) ; Util . notEmpty ( typeArguments , "" ) ; this . typeArguments = Util . freeze ( typeArguments ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . PARAMETERIZED_TYPE ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitParameterizedType ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ForInitializer ; import com . asakusafw . utils . java . model . syntax . ForStatement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . StatementExpressionList ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ForStatementImpl extends ModelRoot implements ForStatement { private ForInitializer initialization ; private Expression condition ; private StatementExpressionList update ; private Statement body ; @ Override public ForInitializer getInitialization ( ) { return this . initialization ; } public void setInitialization ( ForInitializer initialization ) { this . initialization = initialization ; } @ Override public Expression getCondition ( ) { return this . condition ; } public void setCondition ( Expression condition ) { this . condition = condition ; } @ Override public StatementExpressionList getUpdate ( ) { return this . update ; } public void setUpdate ( StatementExpressionList update ) { this . update = update ; } @ Override public Statement getBody ( ) { return this . body ; } public void setBody ( Statement body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . FOR_STATEMENT ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitForStatement ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . DocBlock ; import com . asakusafw . utils . java . model . syntax . DocElement ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class DocBlockImpl extends ModelRoot implements DocBlock { private String tag ; private List < ? extends DocElement > elements ; @ Override public String getTag ( ) { return this . tag ; } public void setTag ( String tag ) { Util . notNull ( tag , "" ) ; this . tag = tag ; } @ Override public List < ? extends DocElement > getElements ( ) { return this . elements ; } public void setElements ( List < ? extends DocElement > elements ) { Util . notNull ( elements , "" ) ; Util . notContainNull ( elements , "" ) ; this . elements = Util . freeze ( elements ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . DOC_BLOCK ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitDocBlock ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldAccessExpression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class FieldAccessExpressionImpl extends ModelRoot implements FieldAccessExpression { private Expression qualifier ; private SimpleName name ; @ Override public Expression getQualifier ( ) { return this . qualifier ; } public void setQualifier ( Expression qualifier ) { Util . notNull ( qualifier , "" ) ; this . qualifier = qualifier ; } @ Override public SimpleName getName ( ) { return this . name ; } public void setName ( SimpleName name ) { Util . notNull ( name , "" ) ; this . name = name ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . FIELD_ACCESS_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitFieldAccessExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . MarkerAnnotation ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class MarkerAnnotationImpl extends ModelRoot implements MarkerAnnotation { private NamedType type ; @ Override public NamedType getType ( ) { return this . type ; } public void setType ( NamedType type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . MARKER_ANNOTATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitMarkerAnnotation ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . QualifiedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class QualifiedTypeImpl extends ModelRoot implements QualifiedType { private Type qualifier ; private SimpleName simpleName ; @ Override public Type getQualifier ( ) { return this . qualifier ; } public void setQualifier ( Type qualifier ) { Util . notNull ( qualifier , "" ) ; this . qualifier = qualifier ; } @ Override public SimpleName getSimpleName ( ) { return this . simpleName ; } public void setSimpleName ( SimpleName simpleName ) { Util . notNull ( simpleName , "" ) ; this . simpleName = simpleName ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . QUALIFIED_TYPE ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitQualifiedType ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . AssignmentExpression ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class AssignmentExpressionImpl extends ModelRoot implements AssignmentExpression { private Expression leftHandSide ; private InfixOperator operator ; private Expression rightHandSide ; @ Override public Expression getLeftHandSide ( ) { return this . leftHandSide ; } public void setLeftHandSide ( Expression leftHandSide ) { Util . notNull ( leftHandSide , "" ) ; this . leftHandSide = leftHandSide ; } @ Override public InfixOperator getOperator ( ) { return this . operator ; } public void setOperator ( InfixOperator operator ) { Util . notNull ( operator , "" ) ; this . operator = operator ; } @ Override public Expression getRightHandSide ( ) { return this . rightHandSide ; } public void setRightHandSide ( Expression rightHandSide ) { Util . notNull ( rightHandSide , "" ) ; this . rightHandSide = rightHandSide ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ASSIGNMENT_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitAssignmentExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . util . Map ; import java . util . WeakHashMap ; import com . asakusafw . utils . java . internal . model . util . ModelDigester ; import com . asakusafw . utils . java . internal . model . util . ModelEmitter ; import com . asakusafw . utils . java . internal . model . util . ModelMatcher ; import com . asakusafw . utils . java . internal . model . util . PrintEmitContext ; import com . asakusafw . utils . java . model . syntax . Model ; abstract class ModelRoot implements Model { private final Map < Class < ? > , Object > traits = new WeakHashMap < Class < ? > , Object > ( ) ; @ Override public < T > T findModelTrait ( Class < T > traitClass ) { if ( traitClass == null ) { throw new IllegalArgumentException ( "" ) ; } Object adapter = traits . get ( traitClass ) ; if ( adapter == null ) { return null ; } return traitClass . cast ( adapter ) ; } @ Override public < T > void putModelTrait ( Class < T > traitClass , T traitObject ) { if ( traitClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( traitObject == null ) { traits . remove ( traitClass ) ; } else { assert traitClass . isInstance ( traitObject ) ; traits . put ( traitClass , traitObject ) ; } } @ Override public int hashCode ( ) { return ModelDigester . compute ( this ) ; } @ Override public boolean equals ( Object obj ) { if ( obj == null ) { return false ; } if ( ( obj instanceof Model ) == false ) { return false ; } return accept ( ModelMatcher . INSTANCE , ( Model ) obj ) ; } @ Override public String toString ( ) { StringWriter buffer = new StringWriter ( ) ; PrintWriter output = new PrintWriter ( buffer ) ; try { ModelEmitter . emit ( this , new PrintEmitContext ( output ) ) ; } catch ( RuntimeException e ) { e . printStackTrace ( output ) ; } output . flush ( ) ; return buffer . toString ( ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . text . MessageFormat ; import com . asakusafw . utils . java . internal . model . util . LiteralAnalyzer ; import com . asakusafw . utils . java . internal . model . util . LiteralToken ; import com . asakusafw . utils . java . model . syntax . Literal ; import com . asakusafw . utils . java . model . syntax . LiteralKind ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class LiteralImpl extends ModelRoot implements Literal { private String token ; private LiteralKind literalKind ; @ Override public String getToken ( ) { return this . token ; } public void setToken ( String token ) { Util . notNull ( token , "" ) ; LiteralKind kind = computeLiteralKind ( token ) ; if ( kind == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , LiteralAnalyzer . stringLiteralOf ( token ) ) ) ; } this . token = token ; this . literalKind = kind ; } private static LiteralKind computeLiteralKind ( String tokenString ) { LiteralToken token = LiteralAnalyzer . parse ( tokenString ) ; switch ( token . getKind ( ) ) { case INT : return LiteralKind . INT ; case LONG : return LiteralKind . LONG ; case FLOAT : return LiteralKind . FLOAT ; case DOUBLE : return LiteralKind . DOUBLE ; case CHAR : return LiteralKind . CHAR ; case STRING : return LiteralKind . STRING ; case BOOLEAN : return LiteralKind . BOOLEAN ; case NULL : return LiteralKind . NULL ; default : return null ; } } @ Override public LiteralKind getLiteralKind ( ) { return literalKind ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . LITERAL ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitLiteral ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . StatementExpressionList ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class StatementExpressionListImpl extends ModelRoot implements StatementExpressionList { private List < ? extends Expression > expressions ; @ Override public List < ? extends Expression > getExpressions ( ) { return this . expressions ; } public void setExpressions ( List < ? extends Expression > expressions ) { Util . notNull ( expressions , "" ) ; Util . notContainNull ( expressions , "" ) ; Util . notEmpty ( expressions , "" ) ; this . expressions = Util . freeze ( expressions ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . STATEMENT_EXPRESSION_LIST ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitStatementExpressionList ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ClassLiteral ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ClassLiteralImpl extends ModelRoot implements ClassLiteral { private Type type ; @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . CLASS_LITERAL ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitClassLiteral ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ArrayAccessExpression ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ArrayAccessExpressionImpl extends ModelRoot implements ArrayAccessExpression { private Expression array ; private Expression index ; @ Override public Expression getArray ( ) { return this . array ; } public void setArray ( Expression array ) { Util . notNull ( array , "" ) ; this . array = array ; } @ Override public Expression getIndex ( ) { return this . index ; } public void setIndex ( Expression index ) { Util . notNull ( index , "" ) ; this . index = index ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ARRAY_ACCESS_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitArrayAccessExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . SwitchCaseLabel ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class SwitchCaseLabelImpl extends ModelRoot implements SwitchCaseLabel { private Expression expression ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . SWITCH_CASE_LABEL ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitSwitchCaseLabel ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . ArrayType ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ArrayTypeImpl extends ModelRoot implements ArrayType { private Type componentType ; @ Override public Type getComponentType ( ) { return this . componentType ; } public void setComponentType ( Type componentType ) { Util . notNull ( componentType , "" ) ; this . componentType = componentType ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ARRAY_TYPE ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitArrayType ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . LocalVariableDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . VariableDeclarator ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class LocalVariableDeclarationImpl extends ModelRoot implements LocalVariableDeclaration { private List < ? extends Attribute > modifiers ; private Type type ; private List < ? extends VariableDeclarator > variableDeclarators ; @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public List < ? extends VariableDeclarator > getVariableDeclarators ( ) { return this . variableDeclarators ; } public void setVariableDeclarators ( List < ? extends VariableDeclarator > variableDeclarators ) { Util . notNull ( variableDeclarators , "" ) ; Util . notContainNull ( variableDeclarators , "" ) ; Util . notEmpty ( variableDeclarators , "" ) ; this . variableDeclarators = Util . freeze ( variableDeclarators ) ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . LOCAL_VARIABLE_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitLocalVariableDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . UnaryExpression ; import com . asakusafw . utils . java . model . syntax . UnaryOperator ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class UnaryExpressionImpl extends ModelRoot implements UnaryExpression { private UnaryOperator operator ; private Expression operand ; @ Override public UnaryOperator getOperator ( ) { return this . operator ; } public void setOperator ( UnaryOperator operator ) { Util . notNull ( operator , "" ) ; this . operator = operator ; } @ Override public Expression getOperand ( ) { return this . operand ; } public void setOperand ( Expression operand ) { Util . notNull ( operand , "" ) ; this . operand = operand ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . UNARY_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitUnaryExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . ArrayCreationExpression ; import com . asakusafw . utils . java . model . syntax . ArrayInitializer ; import com . asakusafw . utils . java . model . syntax . ArrayType ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class ArrayCreationExpressionImpl extends ModelRoot implements ArrayCreationExpression { private ArrayType type ; private List < ? extends Expression > dimensionExpressions ; private ArrayInitializer arrayInitializer ; @ Override public ArrayType getType ( ) { return this . type ; } public void setType ( ArrayType type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public List < ? extends Expression > getDimensionExpressions ( ) { return this . dimensionExpressions ; } public void setDimensionExpressions ( List < ? extends Expression > dimensionExpressions ) { Util . notNull ( dimensionExpressions , "" ) ; Util . notContainNull ( dimensionExpressions , "" ) ; this . dimensionExpressions = Util . freeze ( dimensionExpressions ) ; } @ Override public ArrayInitializer getArrayInitializer ( ) { return this . arrayInitializer ; } public void setArrayInitializer ( ArrayInitializer arrayInitializer ) { this . arrayInitializer = arrayInitializer ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . ARRAY_CREATION_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitArrayCreationExpression ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import java . util . List ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . Block ; import com . asakusafw . utils . java . model . syntax . InitializerDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class InitializerDeclarationImpl extends ModelRoot implements InitializerDeclaration { private Javadoc javadoc ; private List < ? extends Attribute > modifiers ; private Block body ; @ Override public Javadoc getJavadoc ( ) { return this . javadoc ; } public void setJavadoc ( Javadoc javadoc ) { this . javadoc = javadoc ; } @ Override public List < ? extends Attribute > getModifiers ( ) { return this . modifiers ; } public void setModifiers ( List < ? extends Attribute > modifiers ) { Util . notNull ( modifiers , "" ) ; Util . notContainNull ( modifiers , "" ) ; this . modifiers = Util . freeze ( modifiers ) ; } @ Override public Block getBody ( ) { return this . body ; } public void setBody ( Block body ) { Util . notNull ( body , "" ) ; this . body = body ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . INITIALIZER_DECLARATION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitInitializerDeclaration ( this , context ) ; } } package com . asakusafw . utils . java . internal . model . syntax ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . InstanceofExpression ; import com . asakusafw . utils . java . model . syntax . ModelKind ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . Visitor ; public final class InstanceofExpressionImpl extends ModelRoot implements InstanceofExpression { private Expression expression ; private Type type ; @ Override public Expression getExpression ( ) { return this . expression ; } public void setExpression ( Expression expression ) { Util . notNull ( expression , "" ) ; this . expression = expression ; } @ Override public Type getType ( ) { return this . type ; } public void setType ( Type type ) { Util . notNull ( type , "" ) ; this . type = type ; } @ Override public ModelKind getModelKind ( ) { return ModelKind . INSTANCEOF_EXPRESSION ; } @ Override public < R , C , E extends Throwable > R accept ( Visitor < R , C , E > visitor , C context ) throws E { Util . notNull ( visitor , "" ) ; return visitor . visitInstanceofExpression ( this , context ) ; } } package com . asakusafw . utils . collections ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . NoSuchElementException ; import java . util . Set ; import org . junit . Test ; public class SingleLinkedListTest { @ Test public void new_empty ( ) { SingleLinkedList < String > list = new SingleLinkedList < String > ( ) ; assertThat ( list . size ( ) , is ( ) ) ; } @ Test public void new_list ( ) { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; } @ Test public void new_collection ( ) { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( new HashSet < String > ( from ) ) ; assertThat ( list . size ( ) , is ( ) ) ; Set < String > to = new HashSet < String > ( ) ; to . add ( list . get ( ) ) ; to . add ( list . get ( ) ) ; to . add ( list . get ( ) ) ; assertThat ( to , is ( ( Object ) new HashSet < String > ( from ) ) ) ; } @ Test public void isEmpty ( ) { { SingleLinkedList < String > list = new SingleLinkedList < String > ( ) ; assertTrue ( list . isEmpty ( ) ) ; } { List < String > from = Arrays . asList ( "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; assertFalse ( list . isEmpty ( ) ) ; } { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; assertFalse ( list . isEmpty ( ) ) ; } } @ Test public void size ( ) { { SingleLinkedList < String > list = new SingleLinkedList < String > ( ) ; assertThat ( list . size ( ) , is ( ) ) ; } { List < String > from = Arrays . asList ( "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; assertThat ( list . size ( ) , is ( ) ) ; } { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; assertThat ( list . size ( ) , is ( ) ) ; } } @ Test public void concat ( ) { { SingleLinkedList < String > list0 = new SingleLinkedList < String > ( ) ; assertThat ( list0 . size ( ) , is ( ) ) ; SingleLinkedList < String > list1 = list0 . concat ( "" ) ; assertThat ( list0 . size ( ) , is ( ) ) ; assertThat ( list1 . size ( ) , is ( ) ) ; assertThat ( list1 . get ( ) , is ( "" ) ) ; SingleLinkedList < String > list2 = list1 . concat ( "" ) ; assertThat ( list0 . size ( ) , is ( ) ) ; assertThat ( list1 . size ( ) , is ( ) ) ; assertThat ( list1 . get ( ) , is ( "" ) ) ; assertThat ( list2 . size ( ) , is ( ) ) ; assertThat ( list2 . get ( ) , is ( "" ) ) ; assertThat ( list2 . get ( ) , is ( "" ) ) ; SingleLinkedList < String > list3 = list2 . concat ( "" ) ; assertThat ( list0 . size ( ) , is ( ) ) ; assertThat ( list1 . size ( ) , is ( ) ) ; assertThat ( list1 . get ( ) , is ( "" ) ) ; assertThat ( list2 . size ( ) , is ( ) ) ; assertThat ( list2 . get ( ) , is ( "" ) ) ; assertThat ( list2 . get ( ) , is ( "" ) ) ; assertThat ( list3 . size ( ) , is ( ) ) ; assertThat ( list3 . get ( ) , is ( "" ) ) ; assertThat ( list3 . get ( ) , is ( "" ) ) ; assertThat ( list3 . get ( ) , is ( "" ) ) ; } { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; SingleLinkedList < String > concat = list . concat ( "" ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( concat . size ( ) , is ( ) ) ; assertThat ( concat . get ( ) , is ( "" ) ) ; assertThat ( concat . get ( ) , is ( "" ) ) ; assertThat ( concat . get ( ) , is ( "" ) ) ; assertThat ( concat . get ( ) , is ( "" ) ) ; } } @ Test public void first ( ) { { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; assertThat ( list . first ( ) , is ( "" ) ) ; } { SingleLinkedList < String > list = new SingleLinkedList < String > ( ) ; try { list . first ( ) ; fail ( ) ; } catch ( NoSuchElementException e ) { } } } @ Test public void rest ( ) { { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; SingleLinkedList < String > rest = list . rest ( ) ; assertThat ( rest . size ( ) , is ( ) ) ; assertThat ( rest . get ( ) , is ( "" ) ) ; assertThat ( rest . get ( ) , is ( "" ) ) ; } { SingleLinkedList < String > list = new SingleLinkedList < String > ( ) ; try { list . rest ( ) ; fail ( ) ; } catch ( NoSuchElementException e ) { } } } @ Test public void iterator ( ) { { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; Iterator < String > iter = list . iterator ( ) ; assertTrue ( iter . hasNext ( ) ) ; assertThat ( iter . next ( ) , is ( "" ) ) ; assertTrue ( iter . hasNext ( ) ) ; assertThat ( iter . next ( ) , is ( "" ) ) ; assertTrue ( iter . hasNext ( ) ) ; assertThat ( iter . next ( ) , is ( "" ) ) ; assertFalse ( iter . hasNext ( ) ) ; try { iter . next ( ) ; fail ( ) ; } catch ( NoSuchElementException e ) { } } { SingleLinkedList < String > list = new SingleLinkedList < String > ( ) ; Iterator < String > iter = list . iterator ( ) ; assertFalse ( iter . hasNext ( ) ) ; try { iter . next ( ) ; fail ( ) ; } catch ( NoSuchElementException e ) { } } } @ Test public void fill ( ) { { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; List < String > to = new ArrayList < String > ( ) ; list . fill ( to ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( list . get ( ) , is ( "" ) ) ; assertThat ( to , is ( from ) ) ; } { SingleLinkedList < String > list = new SingleLinkedList < String > ( ) ; List < String > to = new ArrayList < String > ( ) ; list . fill ( to ) ; assertThat ( list . size ( ) , is ( ) ) ; assertThat ( to . size ( ) , is ( ) ) ; } } @ Test public void equals ( ) { { SingleLinkedList < ? > a = new SingleLinkedList < String > ( Arrays . < String > asList ( ) ) ; SingleLinkedList < ? > b = new SingleLinkedList < String > ( Arrays . < String > asList ( ) ) ; assertTrue ( a . equals ( b ) ) ; assertTrue ( b . equals ( a ) ) ; } { SingleLinkedList < ? > a = new SingleLinkedList < String > ( Arrays . asList ( "" ) ) ; SingleLinkedList < ? > b = new SingleLinkedList < String > ( Arrays . < String > asList ( ) ) ; assertFalse ( a . equals ( b ) ) ; assertFalse ( b . equals ( a ) ) ; } { SingleLinkedList < ? > a = new SingleLinkedList < String > ( Arrays . asList ( "" ) ) ; SingleLinkedList < ? > b = new SingleLinkedList < String > ( Arrays . asList ( "" ) ) ; assertTrue ( a . equals ( b ) ) ; assertTrue ( b . equals ( a ) ) ; } { SingleLinkedList < ? > a = new SingleLinkedList < String > ( Arrays . asList ( "" ) ) ; SingleLinkedList < ? > b = new SingleLinkedList < String > ( Arrays . asList ( "" ) ) ; assertFalse ( a . equals ( b ) ) ; assertFalse ( b . equals ( a ) ) ; } { SingleLinkedList < ? > a = new SingleLinkedList < String > ( Arrays . asList ( "" , "" ) ) ; SingleLinkedList < ? > b = new SingleLinkedList < String > ( Arrays . asList ( "" ) ) ; assertFalse ( a . equals ( b ) ) ; assertFalse ( b . equals ( a ) ) ; } { SingleLinkedList < ? > a = new SingleLinkedList < String > ( Arrays . asList ( "" , "" ) ) ; SingleLinkedList < ? > b = new SingleLinkedList < String > ( Arrays . asList ( "" , "" ) ) ; assertTrue ( a . equals ( b ) ) ; assertTrue ( b . equals ( a ) ) ; } { SingleLinkedList < ? > a = new SingleLinkedList < String > ( Arrays . asList ( "" , "" , "" ) ) ; SingleLinkedList < ? > b = new SingleLinkedList < String > ( Arrays . asList ( "" , "" ) ) ; assertFalse ( a . equals ( b ) ) ; assertFalse ( b . equals ( a ) ) ; } { SingleLinkedList < ? > a = new SingleLinkedList < String > ( Arrays . asList ( "" , "" , "" ) ) ; SingleLinkedList < ? > b = new SingleLinkedList < String > ( Arrays . asList ( "" , "" , "" ) ) ; assertTrue ( a . equals ( b ) ) ; assertTrue ( b . equals ( a ) ) ; } } @ Test public void serialize ( ) throws Exception { { SingleLinkedList < String > list = new SingleLinkedList < String > ( ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; ObjectOutputStream oo = new ObjectOutputStream ( out ) ; oo . writeObject ( list ) ; oo . close ( ) ; ByteArrayInputStream in = new ByteArrayInputStream ( out . toByteArray ( ) ) ; ObjectInputStream oi = new ObjectInputStream ( in ) ; SingleLinkedList < ? > serialized = ( SingleLinkedList < ? > ) oi . readObject ( ) ; assertThat ( serialized . size ( ) , is ( ) ) ; } { List < String > from = Arrays . asList ( "" , "" , "" ) ; SingleLinkedList < String > list = new SingleLinkedList < String > ( from ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; ObjectOutputStream oo = new ObjectOutputStream ( out ) ; oo . writeObject ( list ) ; oo . close ( ) ; ByteArrayInputStream in = new ByteArrayInputStream ( out . toByteArray ( ) ) ; ObjectInputStream oi = new ObjectInputStream ( in ) ; SingleLinkedList < ? > serialized = ( SingleLinkedList < ? > ) oi . readObject ( ) ; assertThat ( serialized . size ( ) , is ( ) ) ; assertThat ( serialized . get ( ) , is ( ( Object ) "" ) ) ; assertThat ( serialized . get ( ) , is ( ( Object ) "" ) ) ; assertThat ( serialized . get ( ) , is ( ( Object ) "" ) ) ; } } } package com . asakusafw . utils . collections ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; public final class Maps { public static < K , V > Map < K , V > create ( ) { return new HashMap < K , V > ( ) ; } public static < K , V > Map < K , V > from ( Map < ? extends K , ? extends V > map ) { return new HashMap < K , V > ( map ) ; } public static < K , V > Map < K , V > freeze ( Map < ? extends K , ? extends V > map ) { return Collections . unmodifiableMap ( from ( map ) ) ; } public static < K , V > Map < V , List < K > > transpose ( Map < ? extends K , ? extends V > map ) { if ( map == null ) { throw new IllegalArgumentException ( "" ) ; } Map < V , List < K > > results = create ( ) ; for ( Map . Entry < ? extends K , ? extends V > entry : map . entrySet ( ) ) { addToList ( results , entry . getValue ( ) , entry . getKey ( ) ) ; } return results ; } public static < T > Map < T , T > pairs ( T ... pairs ) { if ( pairs == null ) { throw new IllegalArgumentException ( "" ) ; } if ( pairs . length % != ) { throw new IllegalArgumentException ( "" ) ; } Map < T , T > result = new HashMap < T , T > ( ) ; for ( int i = ; i < pairs . length ; i += ) { result . put ( pairs [ i + ] , pairs [ i + ] ) ; } return result ; } public static < K , V > void addToList ( Map < ? super K , List < V > > map , K key , V value ) { if ( map == null ) { throw new IllegalArgumentException ( "" ) ; } List < V > list = map . get ( key ) ; if ( list == null ) { list = Lists . create ( ) ; map . put ( key , list ) ; } list . add ( value ) ; } public static < K , V > void addToSet ( Map < ? super K , Set < V > > map , K key , V value ) { if ( map == null ) { throw new IllegalArgumentException ( "" ) ; } Set < V > set = map . get ( key ) ; if ( set == null ) { set = new HashSet < V > ( ) ; map . put ( key , set ) ; } set . add ( value ) ; } private Maps ( ) { return ; } } package com . asakusafw . utils . collections ; public final class Tuples { public static < T1 , T2 > Tuple2 < T1 , T2 > of ( T1 first , T2 second ) { return Tuple2 . of ( first , second ) ; } private Tuples ( ) { throw new AssertionError ( ) ; } } package com . asakusafw . utils . collections ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Iterator ; import java . util . List ; import java . util . ListIterator ; import java . util . NoSuchElementException ; public class SingleLinkedList < E > implements Iterable < E > , Serializable { private static final long serialVersionUID = ; private transient Node < E > head ; public SingleLinkedList ( ) { head = null ; } public SingleLinkedList ( List < ? extends E > list ) { if ( list == null ) { throw new IllegalArgumentException ( "" ) ; } head = restoreFromList ( list ) ; } public SingleLinkedList ( Iterable < ? extends E > iterable ) { if ( iterable == null ) { throw new IllegalArgumentException ( "" ) ; } head = restoreFromList ( Lists . from ( iterable ) ) ; } private SingleLinkedList ( Node < E > head ) { this . head = head ; } public boolean isEmpty ( ) { return head == null ; } public int size ( ) { int size = ; for ( Node < E > node = head ; node != null ; node = node . next ) { size ++ ; } return size ; } public SingleLinkedList < E > concat ( E element ) { Node < E > next = new Node < E > ( element , head ) ; return new SingleLinkedList < E > ( next ) ; } public E first ( ) { if ( isEmpty ( ) ) { throw new NoSuchElementException ( ) ; } return head . value ; } public SingleLinkedList < E > rest ( ) { if ( isEmpty ( ) ) { throw new NoSuchElementException ( ) ; } return new SingleLinkedList < E > ( head . next ) ; } public E get ( int index ) { if ( index < ) { throw new IndexOutOfBoundsException ( ) ; } Node < E > node = head ; for ( int i = ; i < index && node != null ; i ++ ) { node = node . next ; } if ( node == null ) { throw new IndexOutOfBoundsException ( ) ; } return node . value ; } @ Override public Iterator < E > iterator ( ) { return new NodeIterator < E > ( head ) ; } public < C extends Collection < ? super E > > C fill ( C target ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } for ( Node < E > node = head ; node != null ; node = node . next ) { target . add ( node . value ) ; } return target ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; for ( Node < E > node = head ; node != null ; node = node . next ) { result = prime * result + ( node . value == null ? : node . value . hashCode ( ) ) ; } return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } SingleLinkedList < ? > other = ( SingleLinkedList < ? > ) obj ; Node < E > thisNode = head ; Node < ? > thatNode = other . head ; while ( true ) { if ( thisNode == null ) { return thatNode == null ; } else if ( thatNode == null ) { return false ; } else { if ( thisNode . value == null ) { return thatNode . value == null ; } if ( thisNode . value . equals ( thatNode . value ) == false ) { return false ; } thisNode = thisNode . next ; thatNode = thatNode . next ; } } } @ Override public String toString ( ) { return fill ( new ArrayList < E > ( ) ) . toString ( ) ; } private static final class Node < E > { E value ; Node < E > next ; Node ( E value , Node < E > next ) { this . value = value ; this . next = next ; } } private static final class NodeIterator < E > implements Iterator < E > { private Node < E > current ; NodeIterator ( Node < E > node ) { this . current = node ; } @ Override public boolean hasNext ( ) { return current != null ; } @ Override public E next ( ) { if ( current == null ) { throw new NoSuchElementException ( ) ; } E value = current . value ; current = current . next ; return value ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } private void writeObject ( ObjectOutputStream stream ) throws IOException { stream . defaultWriteObject ( ) ; stream . writeInt ( size ( ) ) ; for ( Node < E > node = head ; node != null ; node = node . next ) { stream . writeObject ( node . value ) ; } } private void readObject ( ObjectInputStream stream ) throws IOException , ClassNotFoundException { stream . defaultReadObject ( ) ; int size = stream . readInt ( ) ; if ( size == ) { head = null ; } else { List < E > store = new ArrayList < E > ( size ) ; for ( int i = ; i < size ; i ++ ) { @ SuppressWarnings ( "" ) E value = ( E ) stream . readObject ( ) ; store . add ( value ) ; } Node < E > node = restoreFromList ( store ) ; head = node ; } } private Node < E > restoreFromList ( List < ? extends E > store ) { Node < E > node = null ; for ( ListIterator < ? extends E > iter = store . listIterator ( store . size ( ) ) ; iter . hasPrevious ( ) ; ) { E value = iter . previous ( ) ; Node < E > prev = new Node < E > ( value , node ) ; node = prev ; } return node ; } } package com . asakusafw . utils . collections ; package com . asakusafw . utils . collections ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; public final class Sets { public static < E > Set < E > create ( ) { return new HashSet < E > ( ) ; } public static < E > Set < E > of ( E elem ) { HashSet < E > result = new HashSet < E > ( ) ; result . add ( elem ) ; return result ; } public static < E > Set < E > of ( E elem1 , E elem2 ) { HashSet < E > result = new HashSet < E > ( ) ; result . add ( elem1 ) ; result . add ( elem2 ) ; return result ; } public static < E > Set < E > of ( E elem1 , E elem2 , E elem3 ) { HashSet < E > result = new HashSet < E > ( ) ; result . add ( elem1 ) ; result . add ( elem2 ) ; result . add ( elem3 ) ; return result ; } public static < E > Set < E > of ( E elem1 , E elem2 , E elem3 , E elem4 , E ... rest ) { if ( rest == null ) { throw new IllegalArgumentException ( "" ) ; } HashSet < E > result = new HashSet < E > ( ) ; result . add ( elem1 ) ; result . add ( elem2 ) ; result . add ( elem3 ) ; result . add ( elem4 ) ; Collections . addAll ( result , rest ) ; return result ; } public static < E > Set < E > from ( E [ ] elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } HashSet < E > result = new HashSet < E > ( ) ; Collections . addAll ( result , elements ) ; return result ; } public static < E > Set < E > from ( Iterable < ? extends E > elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } HashSet < E > copy = new HashSet < E > ( ) ; for ( E element : elements ) { copy . add ( element ) ; } return copy ; } public static < E > Set < E > freeze ( Iterable < ? extends E > elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } Iterator < ? extends E > iter = elements . iterator ( ) ; if ( iter . hasNext ( ) == false ) { return Collections . emptySet ( ) ; } E first = iter . next ( ) ; if ( iter . hasNext ( ) == false ) { return Collections . singleton ( first ) ; } HashSet < E > copy = new HashSet < E > ( ) ; copy . add ( first ) ; while ( iter . hasNext ( ) ) { copy . add ( iter . next ( ) ) ; } return Collections . unmodifiableSet ( copy ) ; } public static < E > Set < E > freeze ( E [ ] elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } return Collections . unmodifiableSet ( from ( elements ) ) ; } private Sets ( ) { return ; } } package com . asakusafw . utils . collections ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; public final class Lists { public static < E > List < E > create ( ) { return new ArrayList < E > ( ) ; } public static < E > List < E > of ( E elem ) { ArrayList < E > result = new ArrayList < E > ( ) ; result . add ( elem ) ; return result ; } public static < E > List < E > of ( E elem1 , E elem2 ) { ArrayList < E > result = new ArrayList < E > ( ) ; result . add ( elem1 ) ; result . add ( elem2 ) ; return result ; } public static < E > List < E > of ( E elem1 , E elem2 , E elem3 ) { ArrayList < E > result = new ArrayList < E > ( ) ; result . add ( elem1 ) ; result . add ( elem2 ) ; result . add ( elem3 ) ; return result ; } public static < E > List < E > of ( E elem1 , E elem2 , E elem3 , E elem4 , E ... rest ) { if ( rest == null ) { throw new IllegalArgumentException ( "" ) ; } ArrayList < E > result = new ArrayList < E > ( ) ; result . add ( elem1 ) ; result . add ( elem2 ) ; result . add ( elem3 ) ; result . add ( elem4 ) ; Collections . addAll ( result , rest ) ; return result ; } public static < E > List < E > from ( E [ ] elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } ArrayList < E > result = new ArrayList < E > ( ) ; Collections . addAll ( result , elements ) ; return result ; } public static < E > List < E > from ( Iterable < ? extends E > elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } ArrayList < E > copy = new ArrayList < E > ( ) ; for ( E element : elements ) { copy . add ( element ) ; } return copy ; } public static < E > List < E > freeze ( Iterable < ? extends E > elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } Iterator < ? extends E > iter = elements . iterator ( ) ; if ( iter . hasNext ( ) == false ) { return Collections . emptyList ( ) ; } E first = iter . next ( ) ; if ( iter . hasNext ( ) == false ) { return Collections . singletonList ( first ) ; } ArrayList < E > copy = new ArrayList < E > ( ) ; copy . add ( first ) ; while ( iter . hasNext ( ) ) { copy . add ( iter . next ( ) ) ; } copy . trimToSize ( ) ; return Collections . unmodifiableList ( copy ) ; } public static < E > List < E > freeze ( E [ ] elements ) { if ( elements == null ) { throw new IllegalArgumentException ( "" ) ; } E [ ] copy = elements . clone ( ) ; return Collections . unmodifiableList ( Arrays . asList ( copy ) ) ; } private Lists ( ) { return ; } } package com . asakusafw . utils . collections ; public class Tuple2 < T1 , T2 > { public final T1 first ; public final T2 second ; public Tuple2 ( T1 first , T2 second ) { this . first = first ; this . second = second ; } public static < T1 , T2 > Tuple2 < T1 , T2 > of ( T1 first , T2 second ) { return new Tuple2 < T1 , T2 > ( first , second ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( first == null ) ? : first . hashCode ( ) ) ; result = prime * result + ( ( second == null ) ? : second . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Tuple2 < ? , ? > other = ( Tuple2 < ? , ? > ) obj ; if ( first == null ) { if ( other . first != null ) { return false ; } } else if ( first . equals ( other . first ) == false ) { return false ; } if ( second == null ) { if ( other . second != null ) { return false ; } } else if ( second . equals ( other . second ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { return String . format ( "" , first , second ) ; } } package com . asakusafw . utils . java . jsr199 . testing ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . Writer ; import java . lang . reflect . Field ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import javax . annotation . processing . AbstractProcessor ; import javax . annotation . processing . RoundEnvironment ; import javax . annotation . processing . SupportedAnnotationTypes ; import javax . annotation . processing . SupportedSourceVersion ; import javax . lang . model . SourceVersion ; import javax . lang . model . element . Element ; import javax . lang . model . element . TypeElement ; import javax . tools . FileObject ; import javax . tools . JavaFileObject ; import javax . tools . StandardLocation ; @ SupportedAnnotationTypes ( { "" } ) @ SupportedSourceVersion ( SourceVersion . RELEASE_6 ) public class MockProcessor extends AbstractProcessor { @ Override public boolean process ( Set < ? extends TypeElement > annotations , RoundEnvironment env ) { Set < Element > elements = new HashSet < Element > ( ) ; for ( TypeElement annotationType : annotations ) { Set < ? extends Element > annotated = env . getElementsAnnotatedWith ( annotationType ) ; elements . addAll ( annotated ) ; } if ( elements . isEmpty ( ) == false ) { try { JavaFileObject file = processingEnv . getFiler ( ) . createSourceFile ( "" ) ; Writer writer = file . openWriter ( ) ; PrintWriter pw = new PrintWriter ( writer ) ; pw . println ( "" ) ; pw . println ( "" ) ; for ( Element element : elements ) { pw . println ( "" + element . getSimpleName ( ) + "" ) ; } pw . println ( "" ) ; pw . println ( "" ) ; pw . close ( ) ; FileObject resource = processingEnv . getFiler ( ) . createResource ( StandardLocation . CLASS_OUTPUT , "" , "" ) ; Writer rw = resource . openWriter ( ) ; rw . write ( "" ) ; rw . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } return false ; } static final Set < String > load ( ClassLoader loader ) { try { Class < ? > klass = Class . forName ( "" , true , loader ) ; Field field = klass . getDeclaredField ( "" ) ; return new HashSet < String > ( Arrays . asList ( ( String [ ] ) field . get ( null ) ) ) ; } catch ( ClassNotFoundException e ) { return Collections . emptySet ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . utils . java . jsr199 . testing ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . util . List ; import java . util . Set ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; public class VolatileCompilerTest { private VolatileCompiler compiler ; @ Before public void setUp ( ) throws Exception { compiler = new VolatileCompiler ( ) ; } @ After public void tearDown ( ) throws Exception { if ( compiler != null ) { compiler . close ( ) ; } } @ Test public void annotated ( ) { compiler . addSource ( load ( "" ) ) ; compiler . addProcessor ( new MockProcessor ( ) ) ; ClassLoader compiled = compile ( ) ; Set < String > elements = MockProcessor . load ( compiled ) ; assertThat ( elements . size ( ) , is ( ) ) ; assertThat ( elements , hasItem ( "" ) ) ; } @ Test public void noAnnotated ( ) { compiler . addSource ( load ( "" ) ) ; compiler . addProcessor ( new MockProcessor ( ) ) ; ClassLoader compiled = compile ( ) ; Set < String > elements = MockProcessor . load ( compiled ) ; assertThat ( elements . size ( ) , is ( ) ) ; } @ Test public void multiAnnotated ( ) { compiler . addSource ( load ( "" ) ) ; compiler . addSource ( load ( "" ) ) ; compiler . addSource ( load ( "" ) ) ; compiler . addProcessor ( new MockProcessor ( ) ) ; ClassLoader compiled = compile ( ) ; Set < String > elements = MockProcessor . load ( compiled ) ; assertThat ( elements . size ( ) , is ( ) ) ; assertThat ( elements , hasItem ( "" ) ) ; assertThat ( elements , hasItem ( "" ) ) ; assertThat ( elements , hasItem ( "" ) ) ; } private ClassLoader compile ( ) { List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) == Diagnostic . Kind . ERROR ) { throw new AssertionError ( diagnostics ) ; } } for ( Diagnostic < ? > d : diagnostics ) { System . err . println ( d ) ; } return compiler . getClassLoader ( ) ; } private JavaFileObject load ( String path ) { Class < ? > klass = getClass ( ) ; String name = klass . getSimpleName ( ) + "" + path + "" ; InputStream in = klass . getResourceAsStream ( name ) ; assertThat ( name , in , not ( nullValue ( ) ) ) ; StringBuilder content = new StringBuilder ( ) ; try { char [ ] buf = new char [ ] ; Reader r = new InputStreamReader ( in , "" ) ; try { while ( true ) { int read = r . read ( buf ) ; if ( read < ) { break ; } content . append ( buf , , read ) ; } } finally { in . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } return new VolatileJavaFile ( path , content . toString ( ) ) ; } } package com . asakusafw . utils . java . jsr199 . testing ; import java . util . HashMap ; import java . util . Map ; public class DirectClassLoader extends ClassLoader { private Map < String , byte [ ] > classes ; public DirectClassLoader ( ClassLoader parent ) { super ( parent ) ; this . classes = new HashMap < String , byte [ ] > ( ) ; } public synchronized void add ( String name , byte [ ] content ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( content == null ) { throw new IllegalArgumentException ( "" ) ; } classes . put ( name , content ) ; } @ Override protected synchronized Class < ? > findClass ( String name ) throws ClassNotFoundException { byte [ ] bytes = classes . remove ( name ) ; if ( bytes == null ) { return super . findClass ( name ) ; } return defineClass ( name , bytes , , bytes . length , null ) ; } } package com . asakusafw . utils . java . jsr199 . testing ; import java . util . Set ; import javax . annotation . processing . Completion ; import javax . annotation . processing . ProcessingEnvironment ; import javax . annotation . processing . Processor ; import javax . annotation . processing . RoundEnvironment ; import javax . lang . model . SourceVersion ; import javax . lang . model . element . AnnotationMirror ; import javax . lang . model . element . Element ; import javax . lang . model . element . ExecutableElement ; import javax . lang . model . element . TypeElement ; public class SafeProcessor implements Processor { private Processor delegate ; private RuntimeException runtimeException ; private Error error ; public SafeProcessor ( Processor delegate ) { if ( delegate == null ) { throw new IllegalArgumentException ( "" ) ; } this . delegate = delegate ; } public void rethrow ( ) { if ( runtimeException != null ) { throw runtimeException ; } else if ( error != null ) { throw error ; } } @ Override public void init ( ProcessingEnvironment processingEnv ) { this . delegate . init ( processingEnv ) ; } @ Override public Set < String > getSupportedOptions ( ) { return this . delegate . getSupportedOptions ( ) ; } @ Override public Set < String > getSupportedAnnotationTypes ( ) { return this . delegate . getSupportedAnnotationTypes ( ) ; } @ Override public SourceVersion getSupportedSourceVersion ( ) { return this . delegate . getSupportedSourceVersion ( ) ; } @ Override public boolean process ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv ) { try { return this . delegate . process ( annotations , roundEnv ) ; } catch ( RuntimeException e ) { runtimeException = e ; throw e ; } catch ( Error e ) { error = e ; throw e ; } } @ Override public Iterable < ? extends Completion > getCompletions ( Element element , AnnotationMirror annotation , ExecutableElement member , String userText ) { return this . delegate . getCompletions ( element , annotation , member , userText ) ; } } package com . asakusafw . utils . java . jsr199 . testing ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . URI ; import java . net . URISyntaxException ; import java . text . MessageFormat ; import javax . tools . JavaFileObject ; import javax . tools . SimpleJavaFileObject ; public class VolatileClassFile extends SimpleJavaFileObject { public static final String SCHEME = VolatileClassFile . class . getName ( ) ; private String binaryName ; volatile byte [ ] contents ; public VolatileClassFile ( String binaryName ) { this ( binaryName , new byte [ ] ) ; } public VolatileClassFile ( String binaryName , byte [ ] contents ) { super ( toUri ( binaryName ) , JavaFileObject . Kind . CLASS ) ; assert binaryName != null ; if ( contents == null ) { throw new IllegalArgumentException ( "" ) ; } this . binaryName = binaryName ; this . contents = contents . clone ( ) ; } private static URI toUri ( String binaryName ) { if ( binaryName == null ) { throw new IllegalArgumentException ( "" ) ; } String path = toPath ( binaryName ) ; try { return new URI ( SCHEME , null , "" + path , null ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , binaryName ) , e ) ; } } private static String toPath ( String binaryName ) { assert binaryName != null ; String path = binaryName . replace ( '' , '' ) ; return path + JavaFileObject . Kind . CLASS . extension ; } @ Override public InputStream openInputStream ( ) { return new ByteArrayInputStream ( contents ) ; } @ Override public OutputStream openOutputStream ( ) { contents = new byte [ ] ; return new ByteArrayOutputStream ( ) { @ Override public void close ( ) { contents = toByteArray ( ) ; } } ; } public String getBinaryName ( ) { return binaryName ; } public byte [ ] getBinaryContent ( ) { return contents . clone ( ) ; } } package com . asakusafw . utils . java . jsr199 . testing ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . Reader ; import java . io . Writer ; import java . net . URI ; import java . net . URISyntaxException ; import java . nio . charset . Charset ; import javax . tools . FileObject ; public class VolatileResourceFile implements FileObject { public static final String URI_SCHEME = VolatileResourceFile . class . getName ( ) ; private static final Charset CHARSET = Charset . forName ( "" ) ; private URI uri ; volatile byte [ ] contents ; volatile long lastModified ; public VolatileResourceFile ( String path ) { this . uri = toUriFromPath ( path ) ; } @ Override public URI toUri ( ) { return uri ; } @ Override public String getName ( ) { String path = uri . getPath ( ) ; return path . substring ( path . lastIndexOf ( '' ) + ) ; } @ Override public InputStream openInputStream ( ) throws IOException { if ( contents == null ) { throw new IOException ( ) ; } return new ByteArrayInputStream ( contents ) ; } @ Override public OutputStream openOutputStream ( ) throws IOException { return new ByteArrayOutputStream ( ) { @ Override public void close ( ) throws IOException { super . close ( ) ; contents = toByteArray ( ) ; lastModified = System . currentTimeMillis ( ) ; } } ; } @ Override public Reader openReader ( boolean ignoreEncodingErrors ) throws IOException { return new InputStreamReader ( openInputStream ( ) , CHARSET ) ; } @ Override public CharSequence getCharContent ( boolean ignoreEncodingErrors ) throws IOException { return new String ( contents , CHARSET ) ; } @ Override public Writer openWriter ( ) throws IOException { return new OutputStreamWriter ( openOutputStream ( ) , CHARSET ) ; } @ Override public long getLastModified ( ) { if ( contents == null ) { return ; } return lastModified ; } @ Override public boolean delete ( ) { if ( contents == null ) { return false ; } contents = null ; return true ; } private static URI toUriFromPath ( String path ) { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } try { return new URI ( URI_SCHEME , null , "" + path . replace ( '' , '' ) , null ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } } } package com . asakusafw . utils . java . jsr199 . testing ; package com . asakusafw . utils . java . jsr199 . testing ; import java . io . Reader ; import java . io . StringReader ; import java . io . StringWriter ; import java . io . Writer ; import java . net . URI ; import java . net . URISyntaxException ; import javax . tools . JavaFileObject ; import javax . tools . SimpleJavaFileObject ; public class VolatileJavaFile extends SimpleJavaFileObject { public static final String URI_SCHEME = VolatileJavaFile . class . getName ( ) ; volatile String contents ; public VolatileJavaFile ( String path ) { this ( path , "" ) ; } public VolatileJavaFile ( String path , String contents ) { super ( toUriFromPath ( path ) , JavaFileObject . Kind . SOURCE ) ; if ( contents == null ) { throw new IllegalArgumentException ( "" ) ; } this . contents = contents ; } @ Override public CharSequence getCharContent ( boolean ignoreEncodingErrors ) { return contents ; } @ Override public Reader openReader ( boolean ignoreEncodingErrors ) { return new StringReader ( contents ) ; } @ Override public Writer openWriter ( ) { this . contents = "" ; return new StringWriter ( ) { @ Override public void close ( ) { contents = toString ( ) ; } } ; } private static URI toUriFromPath ( String path ) { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } try { return new URI ( URI_SCHEME , null , "" + path . replace ( '' , '' ) + JavaFileObject . Kind . SOURCE . extension , null ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } } } package com . asakusafw . utils . java . jsr199 . testing ; import java . io . IOException ; import java . lang . instrument . ClassDefinition ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . SortedMap ; import java . util . TreeMap ; import javax . tools . FileObject ; import javax . tools . ForwardingJavaFileManager ; import javax . tools . JavaFileManager ; import javax . tools . JavaFileObject ; import javax . tools . JavaFileObject . Kind ; import javax . tools . StandardLocation ; public class VolatileClassOutputManager extends ForwardingJavaFileManager < JavaFileManager > { public static final char NAME_SEPARATOR = '' ; public static final char SEGMENT_SEPARATOR = '' ; private static final char NAME_SEPARATOR_NEXT = NAME_SEPARATOR + ; private SortedMap < String , VolatileClassFile > classMap ; private SortedMap < String , VolatileJavaFile > sourceMap ; private SortedMap < String , VolatileResourceFile > resourceMap ; public VolatileClassOutputManager ( JavaFileManager fileManager ) { super ( fileManager ) ; this . classMap = new TreeMap < String , VolatileClassFile > ( ) ; this . sourceMap = new TreeMap < String , VolatileJavaFile > ( ) ; this . resourceMap = new TreeMap < String , VolatileResourceFile > ( ) ; } public Collection < VolatileJavaFile > getSources ( ) { return new ArrayList < VolatileJavaFile > ( sourceMap . values ( ) ) ; } public Collection < VolatileResourceFile > getResources ( ) { return new ArrayList < VolatileResourceFile > ( resourceMap . values ( ) ) ; } public Collection < VolatileClassFile > getCompiled ( ) { return new ArrayList < VolatileClassFile > ( classMap . values ( ) ) ; } @ Override public void close ( ) throws IOException { try { super . close ( ) ; } finally { this . sourceMap = new TreeMap < String , VolatileJavaFile > ( ) ; this . classMap = new TreeMap < String , VolatileClassFile > ( ) ; this . resourceMap = new TreeMap < String , VolatileResourceFile > ( ) ; } } @ Override public boolean hasLocation ( Location location ) { if ( location == StandardLocation . CLASS_OUTPUT ) { return true ; } else { return super . hasLocation ( location ) ; } } @ Override public FileObject getFileForInput ( Location location , String packageName , String relativeName ) throws IOException { if ( location == StandardLocation . CLASS_OUTPUT ) { String binaryName = normalizePath ( packageName , relativeName , JavaFileObject . Kind . CLASS ) ; if ( binaryName == null ) { String path = toPath ( packageName , relativeName ) ; return resourceMap . get ( path ) ; } return getJavaFileForInput ( location , binaryName , JavaFileObject . Kind . CLASS ) ; } else if ( location == StandardLocation . SOURCE_OUTPUT ) { String binaryName = normalizePath ( packageName , relativeName , JavaFileObject . Kind . SOURCE ) ; if ( binaryName == null ) { String path = toPath ( packageName , relativeName ) ; return resourceMap . get ( path ) ; } return getJavaFileForInput ( location , binaryName , JavaFileObject . Kind . SOURCE ) ; } else { return super . getFileForInput ( location , packageName , relativeName ) ; } } @ Override public FileObject getFileForOutput ( Location location , String packageName , String relativeName , FileObject sibling ) throws IOException { if ( location == StandardLocation . CLASS_OUTPUT ) { String binaryName = normalizePath ( packageName , relativeName , JavaFileObject . Kind . CLASS ) ; if ( binaryName == null ) { String path = toPath ( packageName , relativeName ) ; VolatileResourceFile file = resourceMap . get ( path ) ; if ( file == null ) { file = new VolatileResourceFile ( path ) ; resourceMap . put ( path , file ) ; } return file ; } return getJavaFileForOutput ( location , binaryName , JavaFileObject . Kind . CLASS , sibling ) ; } else if ( location == StandardLocation . SOURCE_OUTPUT ) { String binaryName = normalizePath ( packageName , relativeName , JavaFileObject . Kind . SOURCE ) ; if ( binaryName == null ) { String path = toPath ( packageName , relativeName ) ; VolatileResourceFile file = resourceMap . get ( path ) ; if ( file == null ) { file = new VolatileResourceFile ( path ) ; resourceMap . put ( path , file ) ; } return file ; } return getJavaFileForOutput ( location , binaryName , JavaFileObject . Kind . SOURCE , sibling ) ; } else { return super . getFileForOutput ( location , packageName , relativeName , sibling ) ; } } @ Override public JavaFileObject getJavaFileForInput ( Location location , String className , Kind kind ) throws IOException { if ( location == StandardLocation . CLASS_OUTPUT ) { String binaryName = normalizeClassName ( className ) ; if ( classMap . containsKey ( binaryName ) ) { return classMap . get ( binaryName ) ; } return null ; } else if ( location == StandardLocation . SOURCE_OUTPUT ) { String binaryName = normalizeClassName ( className ) ; if ( sourceMap . containsKey ( binaryName ) ) { return sourceMap . get ( binaryName ) ; } return null ; } else { return super . getJavaFileForInput ( location , className , kind ) ; } } @ Override public JavaFileObject getJavaFileForOutput ( Location location , String className , Kind kind , FileObject sibling ) throws IOException { if ( location == StandardLocation . CLASS_OUTPUT ) { String binaryName = normalizeClassName ( className ) ; if ( classMap . containsKey ( binaryName ) ) { return classMap . get ( binaryName ) ; } VolatileClassFile classFile = new VolatileClassFile ( binaryName ) ; classMap . put ( binaryName , classFile ) ; return classFile ; } else if ( location == StandardLocation . SOURCE_OUTPUT ) { String binaryName = normalizeClassName ( className ) ; if ( sourceMap . containsKey ( binaryName ) ) { return sourceMap . get ( binaryName ) ; } VolatileJavaFile javaFile = new VolatileJavaFile ( className . replace ( '' , '' ) ) ; sourceMap . put ( binaryName , javaFile ) ; return javaFile ; } else { return super . getJavaFileForOutput ( location , className , kind , sibling ) ; } } @ Override public Iterable < JavaFileObject > list ( Location location , String packageName , Set < Kind > kinds , boolean recurse ) throws IOException { if ( location == StandardLocation . CLASS_OUTPUT ) { if ( kinds . contains ( JavaFileObject . Kind . CLASS ) == false ) { return Collections . emptySet ( ) ; } return inPackage ( classMap , packageName , recurse ) ; } else if ( location == StandardLocation . SOURCE_OUTPUT ) { if ( kinds . contains ( JavaFileObject . Kind . SOURCE ) == false ) { return Collections . emptySet ( ) ; } return inPackage ( sourceMap , packageName , recurse ) ; } else { return super . list ( location , packageName , kinds , recurse ) ; } } @ Override public boolean isSameFile ( FileObject a , FileObject b ) { if ( a instanceof VolatileJavaFile || a instanceof VolatileClassFile ) { return a . toUri ( ) . equals ( b . toUri ( ) ) ; } if ( b instanceof VolatileJavaFile || b instanceof VolatileClassFile ) { return b . toUri ( ) . equals ( a . toUri ( ) ) ; } return super . isSameFile ( a , b ) ; } private Collection < JavaFileObject > inPackage ( SortedMap < String , ? extends JavaFileObject > all , String packageName , boolean recurse ) { assert all != null ; assert packageName != null ; Map < String , ? extends JavaFileObject > map ; int prefix ; if ( packageName . isEmpty ( ) ) { map = all ; prefix = ; } else { String binaryName = normalizeClassName ( packageName ) ; map = all . subMap ( binaryName + NAME_SEPARATOR , binaryName + NAME_SEPARATOR_NEXT ) ; prefix = binaryName . length ( ) + ; } if ( recurse ) { return new ArrayList < JavaFileObject > ( map . values ( ) ) ; } List < JavaFileObject > results = new ArrayList < JavaFileObject > ( ) ; for ( Map . Entry < String , ? extends JavaFileObject > entry : map . entrySet ( ) ) { String className = entry . getKey ( ) ; if ( className . indexOf ( NAME_SEPARATOR , prefix ) < ) { results . add ( entry . getValue ( ) ) ; } } return results ; } private String normalizePath ( String packageName , String relativeName , JavaFileObject . Kind kind ) { assert packageName != null ; assert relativeName != null ; if ( relativeName . endsWith ( kind . extension ) == false ) { return null ; } String strippedRelativeName = relativeName . substring ( , relativeName . length ( ) - kind . extension . length ( ) ) ; if ( packageName . isEmpty ( ) ) { return normalizeClassName ( strippedRelativeName ) ; } String className = packageName + SEGMENT_SEPARATOR + strippedRelativeName ; return normalizeClassName ( className ) ; } private static String normalizeClassName ( String className ) { assert className != null ; return className . replace ( SEGMENT_SEPARATOR , NAME_SEPARATOR ) ; } private String toPath ( String packageName , String relativeName ) { assert packageName != null ; assert relativeName != null ; if ( packageName . isEmpty ( ) ) { return relativeName ; } return packageName + SEGMENT_SEPARATOR + relativeName ; } } package com . asakusafw . utils . java . jsr199 . testing ; import java . io . Closeable ; import java . io . IOException ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Locale ; import javax . annotation . processing . Processor ; import javax . tools . Diagnostic ; import javax . tools . DiagnosticCollector ; import javax . tools . JavaCompiler ; import javax . tools . JavaCompiler . CompilationTask ; import javax . tools . JavaFileObject ; import javax . tools . ToolProvider ; public class VolatileCompiler implements Closeable { private final JavaCompiler compiler ; private final VolatileClassOutputManager files ; private final List < String > arguments ; private final List < JavaFileObject > targets ; private final List < Processor > processors ; public VolatileCompiler ( ) { this . compiler = ToolProvider . getSystemJavaCompiler ( ) ; if ( compiler == null ) { throw new IllegalStateException ( "" ) ; } this . files = new VolatileClassOutputManager ( compiler . getStandardFileManager ( null , Locale . ENGLISH , Charset . forName ( "" ) ) ) ; this . arguments = new ArrayList < String > ( ) ; this . targets = new ArrayList < JavaFileObject > ( ) ; this . processors = new ArrayList < Processor > ( ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; Collections . addAll ( arguments , "" , "" ) ; } public VolatileCompiler addSource ( JavaFileObject java ) { if ( java == null ) { throw new IllegalArgumentException ( "" ) ; } targets . add ( java ) ; return this ; } public VolatileCompiler addProcessor ( Processor processor ) { if ( processor == null ) { throw new IllegalArgumentException ( "" ) ; } processors . add ( processor ) ; return this ; } public VolatileCompiler resetArguments ( ) { arguments . clear ( ) ; return this ; } public VolatileCompiler addArguments ( String ... compilerArguments ) { if ( compilerArguments == null ) { throw new IllegalArgumentException ( "" ) ; } Collections . addAll ( arguments , compilerArguments ) ; return this ; } public List < Diagnostic < ? extends JavaFileObject > > doCompile ( ) { DiagnosticCollector < JavaFileObject > collector = new DiagnosticCollector < JavaFileObject > ( ) ; CompilationTask task = compiler . getTask ( new PrintWriter ( new OutputStreamWriter ( System . err , Charset . defaultCharset ( ) ) , true ) , files , collector , arguments , Arrays . < String > asList ( ) , targets ) ; task . setProcessors ( processors ) ; task . call ( ) ; return collector . getDiagnostics ( ) ; } public ClassLoader getClassLoader ( ) { DirectClassLoader loader = AccessController . doPrivileged ( new PrivilegedAction < DirectClassLoader > ( ) { @ Override public DirectClassLoader run ( ) { return new DirectClassLoader ( VolatileCompiler . this . getClass ( ) . getClassLoader ( ) ) ; } } ) ; loader . setDefaultAssertionStatus ( true ) ; for ( VolatileClassFile klass : files . getCompiled ( ) ) { loader . add ( klass . getBinaryName ( ) , klass . getBinaryContent ( ) ) ; } return loader ; } public Collection < VolatileJavaFile > getSources ( ) { return files . getSources ( ) ; } public Collection < VolatileResourceFile > getResources ( ) { return files . getResources ( ) ; } public Collection < VolatileClassFile > getCompiled ( ) { return files . getCompiled ( ) ; } @ Override public void close ( ) throws IOException { files . close ( ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . regex . Pattern ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocText ; public class MockJavadocBlockParser extends JavadocBlockParser { private String identifier = "" ; private Pattern acceptable ; public MockJavadocBlockParser ( ) { super ( ) ; this . acceptable = null ; } public MockJavadocBlockParser ( JavadocBlockParser inline , JavadocBlockParser ... inlineRest ) { super ( list ( inline , inlineRest ) ) ; this . acceptable = null ; } private static < T > List < T > list ( T t , T ... rest ) { List < T > list = new ArrayList < T > ( rest . length + ) ; list . add ( t ) ; for ( T r : rest ) { list . add ( r ) ; } return list ; } @ Override public boolean canAccept ( String tag ) { if ( acceptable == null ) { return true ; } else { return acceptable . matcher ( tag == null ? "" : tag ) . matches ( ) ; } } public void setAcceptable ( Pattern acceptable ) { this . acceptable = acceptable ; } public void setIdentifier ( String identifier ) { if ( identifier == null ) { throw new IllegalArgumentException ( "" ) ; } this . identifier = identifier ; } public String getIdentifier ( ) { return this . identifier ; } @ Override public IrDocBlock parse ( String tag , JavadocScanner scanner ) { IrDocBlock block = new IrDocBlock ( ) ; block . setTag ( tag ) ; block . setFragments ( Arrays . asList ( new IrDocText ( identifier ) ) ) ; return block ; } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . regex . Pattern ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocText ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; public class JavadocBlockParserTest extends JavadocTestRoot { @ Test public void testNewBlock ( ) { MockJavadocBlockParser parser = new MockJavadocBlockParser ( ) ; { IrDocBlock block = parser . newBlock ( null , Collections . < IrDocFragment > emptyList ( ) ) ; assertNull ( block . getTag ( ) ) ; assertEquals ( , block . getFragments ( ) . size ( ) ) ; } { IrDocText f0 = new IrDocText ( "" ) ; IrDocBlock block = parser . newBlock ( "" , Arrays . asList ( f0 ) ) ; assertEquals ( "" , block . getTag ( ) ) ; assertEquals ( , block . getFragments ( ) . size ( ) ) ; assertEquals ( f0 , block . getFragments ( ) . get ( ) ) ; } { IrDocSimpleName f0 = new IrDocSimpleName ( "" ) ; IrDocText f1 = new IrDocText ( "" ) ; IrDocText f2 = new IrDocText ( "" ) ; IrDocBlock block = parser . newBlock ( "" , Arrays . < IrDocFragment > asList ( f0 , f1 , f2 ) ) ; assertEquals ( "" , block . getTag ( ) ) ; assertEquals ( , block . getFragments ( ) . size ( ) ) ; assertEquals ( f0 , block . getFragments ( ) . get ( ) ) ; assertEquals ( f1 , block . getFragments ( ) . get ( ) ) ; assertEquals ( f2 , block . getFragments ( ) . get ( ) ) ; } } @ Test public void testParseBlock ( ) throws Exception { MockJavadocBlockParser i1 = new MockJavadocBlockParser ( ) ; i1 . setAcceptable ( Pattern . compile ( "" ) ) ; i1 . setIdentifier ( "" ) ; MockJavadocBlockParser i2 = new MockJavadocBlockParser ( ) ; i2 . setAcceptable ( Pattern . compile ( "" ) ) ; i2 . setIdentifier ( "" ) ; MockJavadocBlockParser i3 = new MockJavadocBlockParser ( ) ; i3 . setAcceptable ( Pattern . compile ( "" ) ) ; i3 . setIdentifier ( "" ) ; MockJavadocBlockParser i4 = new MockJavadocBlockParser ( ) ; i4 . setAcceptable ( Pattern . compile ( "" ) ) ; i4 . setIdentifier ( "" ) ; MockJavadocBlockParser parser = new MockJavadocBlockParser ( i1 , i2 , i3 , i4 ) ; { JavadocBlockInfo block = new JavadocBlockInfo ( "" , string ( "" ) , new IrLocation ( , ) ) ; IrDocBlock parsed = parser . parseBlock ( block ) ; assertEquals ( new IrLocation ( , ) , parsed . getLocation ( ) ) ; List < ? extends IrDocFragment > fragments = parsed . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { JavadocBlockInfo block = new JavadocBlockInfo ( "" , string ( "" ) , new IrLocation ( , ) ) ; IrDocBlock parsed = parser . parseBlock ( block ) ; assertEquals ( new IrLocation ( , ) , parsed . getLocation ( ) ) ; List < ? extends IrDocFragment > fragments = parsed . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { JavadocBlockInfo block = new JavadocBlockInfo ( "" , string ( "" ) , new IrLocation ( , ) ) ; IrDocBlock parsed = parser . parseBlock ( block ) ; assertEquals ( new IrLocation ( , ) , parsed . getLocation ( ) ) ; List < ? extends IrDocFragment > fragments = parsed . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { JavadocBlockInfo block = new JavadocBlockInfo ( "" , string ( "" ) , new IrLocation ( , ) ) ; IrDocBlock parsed = parser . parseBlock ( block ) ; assertEquals ( new IrLocation ( , ) , parsed . getLocation ( ) ) ; List < ? extends IrDocFragment > fragments = parsed . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { JavadocBlockInfo block = new JavadocBlockInfo ( "" , string ( "" ) , new IrLocation ( , ) ) ; try { parser . parseBlock ( block ) ; fail ( ) ; } catch ( MissingJavadocBlockParserException e ) { assertEquals ( "" , e . getTagName ( ) ) ; } } { JavadocBlockInfo block = new JavadocBlockInfo ( null , string ( "" ) , new IrLocation ( , ) ) ; IrDocBlock parsed = parser . parseBlock ( block ) ; assertEquals ( new IrLocation ( , ) , parsed . getLocation ( ) ) ; List < ? extends IrDocFragment > fragments = parsed . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } } @ Test public void testFetchRestFragments ( ) throws Exception { MockJavadocBlockParser inline = new MockJavadocBlockParser ( ) ; inline . setIdentifier ( "" ) ; MockJavadocBlockParser parser = new MockJavadocBlockParser ( inline ) ; { DefaultJavadocScanner scanner = string ( "" ) ; List < IrDocFragment > fragments = parser . fetchRestFragments ( scanner ) ; assertEquals ( , fragments . size ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; List < IrDocFragment > fragments = parser . fetchRestFragments ( scanner ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" ) ; List < IrDocFragment > fragments = parser . fetchRestFragments ( scanner ) ; assertKinds ( fragments , TEXT , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" ) ; List < IrDocFragment > fragments = parser . fetchRestFragments ( scanner ) ; assertKinds ( fragments , TEXT , TEXT , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; List < IrDocFragment > fragments = parser . fetchRestFragments ( scanner ) ; assertKinds ( fragments , BLOCK ) ; { IrDocBlock block = ( IrDocBlock ) fragments . get ( ) ; assertEquals ( , block . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( "" . length ( ) , block . getLocation ( ) . getLength ( ) ) ; assertEquals ( "" , block . getTag ( ) ) ; assertMockBlockEquals ( inline , "" , block ) ; } } { DefaultJavadocScanner scanner = string ( "" ) ; List < IrDocFragment > fragments = parser . fetchRestFragments ( scanner ) ; assertKinds ( fragments , BLOCK , BLOCK ) ; { IrDocBlock block = ( IrDocBlock ) fragments . get ( ) ; assertEquals ( , block . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( "" . length ( ) , block . getLocation ( ) . getLength ( ) ) ; assertEquals ( "" , block . getTag ( ) ) ; assertMockBlockEquals ( inline , "" , block ) ; } { IrDocBlock block = ( IrDocBlock ) fragments . get ( ) ; assertEquals ( "" . length ( ) , block . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( "" . length ( ) , block . getLocation ( ) . getLength ( ) ) ; assertMockBlockEquals ( inline , "" , block ) ; } } { DefaultJavadocScanner scanner = string ( "" + "" ) ; List < IrDocFragment > fragments = parser . fetchRestFragments ( scanner ) ; assertKinds ( fragments , TEXT , BLOCK , TEXT , BLOCK , BLOCK ) ; assertTextEquals ( "" , fragments . get ( ) ) ; assertMockBlockEquals ( inline , "" , fragments . get ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; assertMockBlockEquals ( inline , "" , fragments . get ( ) ) ; assertMockBlockEquals ( inline , "" , fragments . get ( ) ) ; } } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrBasicTypeKind ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBasicType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocField ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethod ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethodParameter ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocNamedType ; public class FollowsReferenceBlockParserTest extends JavadocTestRoot { @ Test public void testParseType ( ) throws Exception { { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , NAMED_TYPE ) ; assertEquals ( "" , ( ( IrDocNamedType ) fragments . get ( ) ) . getName ( ) . asString ( ) ) ; } { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , NAMED_TYPE ) ; assertEquals ( "" , ( ( IrDocNamedType ) fragments . get ( ) ) . getName ( ) . asString ( ) ) ; } { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" + "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , NAMED_TYPE ) ; assertEquals ( "" , ( ( IrDocNamedType ) fragments . get ( ) ) . getName ( ) . asString ( ) ) ; } { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" + "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , NAMED_TYPE , TEXT ) ; assertEquals ( "" , ( ( IrDocNamedType ) fragments . get ( ) ) . getName ( ) . asString ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } } @ Test public void testParseField ( ) throws Exception { { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , FIELD ) ; IrDocField field = ( IrDocField ) fragments . get ( ) ; assertNull ( field . getDeclaringType ( ) ) ; assertEquals ( "" , field . getName ( ) . getIdentifier ( ) ) ; } { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , FIELD ) ; IrDocField field = ( IrDocField ) fragments . get ( ) ; assertEquals ( "" , field . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , field . getName ( ) . getIdentifier ( ) ) ; } { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , FIELD ) ; IrDocField field = ( IrDocField ) fragments . get ( ) ; assertEquals ( "" , field . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , field . getName ( ) . getIdentifier ( ) ) ; } { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , FIELD ) ; IrDocField field = ( IrDocField ) fragments . get ( ) ; assertEquals ( "" , field . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , field . getName ( ) . getIdentifier ( ) ) ; } } @ Test public void testParseMethod ( ) throws Exception { { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , METHOD ) ; IrDocMethod method = ( IrDocMethod ) fragments . get ( ) ; assertNull ( method . getDeclaringType ( ) ) ; assertEquals ( "" , method . getName ( ) . getIdentifier ( ) ) ; assertEquals ( , method . getParameters ( ) . size ( ) ) ; } { FollowsReferenceBlockParser parser = new FollowsReferenceBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( null , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , METHOD ) ; IrDocMethod method = ( IrDocMethod ) fragments . get ( ) ; assertNull ( method . getDeclaringType ( ) ) ; assertEquals ( "" , method . getName ( ) . getIdentifier ( ) ) ; assertEquals ( , method . getParameters ( ) . size ( ) ) ; { IrDocMethodParameter param = method . getParameters ( ) . get ( ) ; assertEquals ( BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; } } } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocNamedType ; public class FollowsNamedTypeBlockParserTest extends JavadocTestRoot { @ Test public void testParseJust ( ) throws Exception { FollowsNamedTypeBlockParser parser = new FollowsNamedTypeBlockParser ( "" ) ; IrDocBlock block = parser . parse ( "" , string ( "" ) ) ; assertEquals ( "" , block . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , NAMED_TYPE ) ; assertEquals ( "" , ( ( IrDocNamedType ) fragments . get ( ) ) . getName ( ) . asString ( ) ) ; } @ Test public void testParseTrails ( ) throws Exception { FollowsNamedTypeBlockParser parser = new FollowsNamedTypeBlockParser ( "" ) ; IrDocBlock block = parser . parse ( "" , string ( "" ) ) ; assertEquals ( "" , block . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , NAMED_TYPE , TEXT ) ; assertEquals ( "" , ( ( IrDocNamedType ) fragments . get ( ) ) . getName ( ) . asString ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } @ Test public void testParseMissing ( ) throws Exception { FollowsNamedTypeBlockParser parser = new FollowsNamedTypeBlockParser ( "" ) ; IrDocBlock block = parser . parse ( "" , string ( "" ) ) ; assertEquals ( "" , block . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocNamedType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; public class SerialFieldBlockParserTest extends JavadocTestRoot { @ Test public void testParse ( ) throws Exception { SerialFieldBlockParser parser = new SerialFieldBlockParser ( ) ; { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( "" , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , SIMPLE_NAME , BASIC_TYPE ) ; assertEquals ( "" , ( ( IrDocSimpleName ) fragments . get ( ) ) . asString ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( "" , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , SIMPLE_NAME , NAMED_TYPE ) ; assertEquals ( "" , ( ( IrDocSimpleName ) fragments . get ( ) ) . asString ( ) ) ; assertEquals ( "" , ( ( IrDocNamedType ) fragments . get ( ) ) . getName ( ) . asString ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( "" , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , SIMPLE_NAME , NAMED_TYPE , TEXT ) ; assertEquals ( "" , ( ( IrDocSimpleName ) fragments . get ( ) ) . asString ( ) ) ; assertEquals ( "" , ( ( IrDocNamedType ) fragments . get ( ) ) . getName ( ) . asString ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( "" , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind . * ; import static org . junit . Assert . * ; import org . junit . Test ; public class DefaultJavadocTokenStreamTest extends JavadocTestRoot { @ Test public void testPeek ( ) { DefaultJavadocTokenStream stream = stream ( "" ) ; assertEquals ( "" , stream . peek ( ) . getText ( ) ) ; assertEquals ( "" , stream . peek ( ) . getText ( ) ) ; assertEquals ( "" , stream . peek ( ) . getText ( ) ) ; stream . nextToken ( ) ; assertEquals ( "" , stream . peek ( ) . getText ( ) ) ; assertEquals ( "" , stream . peek ( ) . getText ( ) ) ; assertEquals ( "" , stream . peek ( ) . getText ( ) ) ; } @ Test public void testLookahead ( ) { DefaultJavadocTokenStream stream = stream ( "" ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; stream . nextToken ( ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; assertEquals ( "" , stream . lookahead ( ) . getText ( ) ) ; } @ Test public void testNextTokenSimple ( ) { DefaultJavadocTokenStream stream = stream ( "" ) ; for ( char c = '' ; c <= '' ; c ++ ) { assertEquals ( String . valueOf ( c ) , stream . nextToken ( ) . getText ( ) ) ; } assertEquals ( EOF , stream . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , stream . nextToken ( ) . getKind ( ) ) ; } @ Test public void testNextTokenLines ( ) { DefaultJavadocTokenStream stream = stream ( "" ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; assertEquals ( EOF , stream . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , stream . nextToken ( ) . getKind ( ) ) ; } @ Test public void testMark ( ) { DefaultJavadocTokenStream stream = stream ( "" ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . rewind ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . rewind ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . rewind ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . rewind ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; } @ Test public void testRewind ( ) { DefaultJavadocTokenStream stream = stream ( "" ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . rewind ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . rewind ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; try { stream . rewind ( ) ; fail ( ) ; } catch ( IllegalStateException e ) { } } @ Test public void testDiscard ( ) { DefaultJavadocTokenStream stream = stream ( "" ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . mark ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . discard ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . rewind ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; stream . discard ( ) ; assertEquals ( "" , stream . nextToken ( ) . getText ( ) ) ; try { stream . discard ( ) ; fail ( ) ; } catch ( IllegalStateException e ) { } } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocComment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; public class JavadocParserTest extends JavadocTestRoot { @ Test public void testParse ( ) throws Exception { JavadocParserBuilder builder = new JavadocParserBuilder ( ) ; JavadocParser parser = builder . build ( ) ; { DefaultJavadocScanner scanner = string ( "" ) ; IrDocComment doc = parser . parse ( scanner ) ; List < ? extends IrDocBlock > blocks = doc . getBlocks ( ) ; assertEquals ( , blocks . size ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocComment doc = parser . parse ( scanner ) ; List < ? extends IrDocBlock > blocks = doc . getBlocks ( ) ; assertEquals ( , blocks . size ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" ) ; IrDocComment doc = parser . parse ( scanner ) ; List < ? extends IrDocBlock > blocks = doc . getBlocks ( ) ; assertEquals ( , blocks . size ( ) ) ; assertNull ( blocks . get ( ) . getTag ( ) ) ; assertEquals ( "" , blocks . get ( ) . getTag ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" + "" ) ; IrDocComment doc = parser . parse ( scanner ) ; List < ? extends IrDocBlock > blocks = doc . getBlocks ( ) ; assertEquals ( , blocks . size ( ) ) ; assertNull ( blocks . get ( ) . getTag ( ) ) ; assertEquals ( "" , blocks . get ( ) . getTag ( ) ) ; assertEquals ( "" , blocks . get ( ) . getTag ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" ) ; try { parser . parse ( scanner ) ; fail ( ) ; } catch ( IllegalDocCommentFormatException e ) { } } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" ) ; try { parser . parse ( scanner ) ; fail ( ) ; } catch ( IllegalDocCommentFormatException e ) { } } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" ) ; try { parser . parse ( scanner ) ; fail ( ) ; } catch ( IllegalDocCommentFormatException e ) { } } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" ) ; try { parser . parse ( scanner ) ; fail ( ) ; } catch ( IllegalDocCommentFormatException e ) { } } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" ) ; parser . parse ( scanner ) ; } } @ Test public void testParseDetails ( ) throws Exception { JavadocParserBuilder builder = new JavadocParserBuilder ( ) ; builder . addSpecialStandAloneBlockParser ( new ParamBlockParser ( ) ) ; builder . addSpecialStandAloneBlockParser ( new FollowsNamedTypeBlockParser ( "" ) ) ; builder . addSpecialInlineBlockParser ( new FollowsReferenceBlockParser ( "" ) ) ; JavadocParser parser = builder . build ( ) ; { DefaultJavadocScanner scanner = string ( "" ) ; IrDocComment doc = parser . parse ( scanner ) ; List < ? extends IrDocBlock > blocks = doc . getBlocks ( ) ; assertEquals ( , blocks . size ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" + "" + "" ) ; IrDocComment doc = parser . parse ( scanner ) ; List < ? extends IrDocBlock > blocks = doc . getBlocks ( ) ; assertEquals ( , blocks . size ( ) ) ; { IrDocBlock b = blocks . get ( ) ; assertNull ( b . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = b . getFragments ( ) ; assertKinds ( fragments , TEXT , BLOCK , TEXT , TEXT ) ; } { IrDocBlock b = blocks . get ( ) ; assertEquals ( "" , b . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = b . getFragments ( ) ; assertKinds ( fragments , SIMPLE_NAME , TEXT , BLOCK ) ; IrDocBlock inner = ( IrDocBlock ) fragments . get ( ) ; assertKinds ( inner . getFragments ( ) , NAMED_TYPE ) ; } { IrDocBlock b = blocks . get ( ) ; assertEquals ( "" , b . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = b . getFragments ( ) ; assertKinds ( fragments , NAMED_TYPE , TEXT ) ; } } } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind . * ; import static org . junit . Assert . * ; import java . util . EnumSet ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrBasicTypeKind ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocArrayType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBasicType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElement ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocField ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethod ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethodParameter ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocNamedType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocText ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public class JavadocBlockParserUtilTest extends JavadocTestRoot { @ Test public void testSetLocationToken ( ) { { IrDocElement elem = new IrDocText ( "" ) ; JavadocToken start = new JavadocToken ( JavadocTokenKind . IDENTIFIER , "" , ) ; JavadocToken stop = new JavadocToken ( JavadocTokenKind . IDENTIFIER , "" , ) ; JavadocBlockParserUtil . setLocation ( elem , start , stop ) ; assertEquals ( , elem . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( , elem . getLocation ( ) . getLength ( ) ) ; } { IrDocElement elem = new IrDocText ( "" ) ; JavadocToken start = new JavadocToken ( JavadocTokenKind . IDENTIFIER , "" , ) ; JavadocBlockParserUtil . setLocation ( elem , start , start ) ; assertEquals ( , elem . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( , elem . getLocation ( ) . getLength ( ) ) ; } } @ Test public void testSetLocationLocation ( ) { { IrDocElement elem = new IrDocText ( "" ) ; IrLocation start = new IrLocation ( , ) ; IrLocation stop = new IrLocation ( , ) ; JavadocBlockParserUtil . setLocation ( elem , start , stop ) ; assertEquals ( , elem . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( , elem . getLocation ( ) . getLength ( ) ) ; } { IrDocElement elem = new IrDocText ( "" ) ; IrLocation start = new IrLocation ( , ) ; JavadocBlockParserUtil . setLocation ( elem , start , start ) ; assertEquals ( , elem . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( , elem . getLocation ( ) . getLength ( ) ) ; } { IrDocElement elem = new IrDocText ( "" ) ; IrLocation fragment = new IrLocation ( , ) ; JavadocBlockParserUtil . setLocation ( elem , null , fragment ) ; assertNull ( elem . getLocation ( ) ) ; } { IrDocElement elem = new IrDocText ( "" ) ; IrLocation fragment = new IrLocation ( , ) ; JavadocBlockParserUtil . setLocation ( elem , fragment , null ) ; assertNull ( elem . getLocation ( ) ) ; } } @ Test public void testFetchText ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; { int offset = scanner . lookahead ( ) . getStartPosition ( ) ; IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , false , false ) ; assertEquals ( "" , text . getContent ( ) ) ; assertNotNull ( text . getLocation ( ) ) ; assertEquals ( offset , text . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( text . getContent ( ) . length ( ) , text . getLocation ( ) . getLength ( ) ) ; assertEquals ( JavadocTokenKind . LINE_BREAK , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ) ; } { int offset = scanner . lookahead ( ) . getStartPosition ( ) ; IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , false , false ) ; assertEquals ( "" , text . getContent ( ) ) ; assertNotNull ( text . getLocation ( ) ) ; assertEquals ( offset , text . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( text . getContent ( ) . length ( ) , text . getLocation ( ) . getLength ( ) ) ; assertEquals ( JavadocTokenKind . LINE_BREAK , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ) ; } { IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , false , false ) ; assertNull ( text ) ; scanner . consume ( JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ) ; } { int offset = scanner . lookahead ( ) . getStartPosition ( ) ; IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , false , false ) ; assertEquals ( "" , text . getContent ( ) ) ; assertNotNull ( text . getLocation ( ) ) ; assertEquals ( offset , text . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( text . getContent ( ) . length ( ) , text . getLocation ( ) . getLength ( ) ) ; assertEquals ( JavadocTokenKind . LEFT_BRACE , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( JavadocScannerUtil . countUntil ( EnumSet . of ( JavadocTokenKind . RIGHT_BRACE ) , scanner , ) + ) ; offset = scanner . lookahead ( ) . getStartPosition ( ) ; text = JavadocBlockParserUtil . fetchText ( scanner , false , false ) ; assertEquals ( "" , text . getContent ( ) ) ; assertNotNull ( text . getLocation ( ) ) ; assertEquals ( offset , text . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( text . getContent ( ) . length ( ) , text . getLocation ( ) . getLength ( ) ) ; assertEquals ( JavadocTokenKind . LINE_BREAK , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ) ; } { int offset = scanner . lookahead ( ) . getStartPosition ( ) ; IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , false , false ) ; assertEquals ( "" , text . getContent ( ) ) ; assertNotNull ( text . getLocation ( ) ) ; assertEquals ( offset , text . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( text . getContent ( ) . length ( ) , text . getLocation ( ) . getLength ( ) ) ; assertEquals ( JavadocTokenKind . LINE_BREAK , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ) ; } { int offset = scanner . lookahead ( ) . getStartPosition ( ) ; IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , true , false ) ; assertEquals ( "" , text . getContent ( ) ) ; assertNotNull ( text . getLocation ( ) ) ; assertEquals ( offset + , text . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( text . getContent ( ) . length ( ) , text . getLocation ( ) . getLength ( ) ) ; assertEquals ( JavadocTokenKind . LINE_BREAK , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ) ; } { int offset = scanner . lookahead ( ) . getStartPosition ( ) ; IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , false , true ) ; assertEquals ( "" , text . getContent ( ) ) ; assertNotNull ( text . getLocation ( ) ) ; assertEquals ( offset , text . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( text . getContent ( ) . length ( ) , text . getLocation ( ) . getLength ( ) ) ; assertEquals ( JavadocTokenKind . LINE_BREAK , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ) ; } { int offset = scanner . lookahead ( ) . getStartPosition ( ) ; IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , true , true ) ; assertEquals ( "" , text . getContent ( ) ) ; assertNotNull ( text . getLocation ( ) ) ; assertEquals ( offset + , text . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( text . getContent ( ) . length ( ) , text . getLocation ( ) . getLength ( ) ) ; assertEquals ( JavadocTokenKind . LINE_BREAK , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ) ; } { IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , false , false ) ; assertNull ( text ) ; } } @ Test public void testFetchBlockInfoEmpty ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; JavadocBlockInfo block = JavadocBlockParserUtil . fetchBlockInfo ( scanner ) ; assertEquals ( JavadocTokenKind . EOF , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( "" , block . getTagName ( ) ) ; assertEquals ( , block . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( scanner . lookahead ( ) . getStartPosition ( ) , block . getLocation ( ) . getLength ( ) ) ; JavadocScanner bScanner = block . getBlockScanner ( ) ; assertEquals ( JavadocTokenKind . EOF , bScanner . lookahead ( ) . getKind ( ) ) ; } @ Test public void testFetchBlockInfoSimple ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; JavadocBlockInfo block = JavadocBlockParserUtil . fetchBlockInfo ( scanner ) ; assertEquals ( JavadocTokenKind . EOF , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( "" , block . getTagName ( ) ) ; assertEquals ( , block . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( scanner . lookahead ( ) . getStartPosition ( ) , block . getLocation ( ) . getLength ( ) ) ; JavadocScanner bScanner = block . getBlockScanner ( ) ; IrDocText inline = JavadocBlockParserUtil . fetchText ( bScanner , false , false ) ; assertEquals ( "" , inline . getContent ( ) ) ; assertEquals ( JavadocTokenKind . EOF , bScanner . lookahead ( ) . getKind ( ) ) ; } @ Test public void testFetchBlockInfoBroken ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; JavadocBlockInfo block = JavadocBlockParserUtil . fetchBlockInfo ( scanner ) ; assertEquals ( JavadocTokenKind . EOF , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( "" , block . getTagName ( ) ) ; assertEquals ( , block . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( scanner . lookahead ( ) . getStartPosition ( ) , block . getLocation ( ) . getLength ( ) ) ; JavadocScanner bScanner = block . getBlockScanner ( ) ; IrDocText inline = JavadocBlockParserUtil . fetchText ( bScanner , false , false ) ; assertEquals ( "" , inline . getContent ( ) ) ; assertEquals ( JavadocTokenKind . EOF , bScanner . lookahead ( ) . getKind ( ) ) ; } @ Test public void testFetchSimpleName ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocSimpleName elem = JavadocBlockParserUtil . fetchSimpleName ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getIdentifier ( ) ) ; assertEquals ( , elem . getLocation ( ) . getStartPosition ( ) ) ; assertEquals ( "" . length ( ) , elem . getLocation ( ) . getLength ( ) ) ; assertEquals ( DOT , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocSimpleName elem = JavadocBlockParserUtil . fetchSimpleName ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( DOT , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocSimpleName elem = JavadocBlockParserUtil . fetchSimpleName ( scanner , EnumSet . of ( WHITE_SPACES ) ) ; assertNull ( elem ) ; assertEquals ( IDENTIFIER , scanner . lookahead ( ) . getKind ( ) ) ; } } @ Test public void testFetchName ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocName elem = JavadocBlockParserUtil . fetchName ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . asString ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( IrDocElementKind . QUALIFIED_NAME , elem . getKind ( ) ) ; assertEquals ( , elem . asSimpleNameList ( ) . size ( ) ) ; assertSameLocation ( "" . length ( ) , "" . length ( ) , elem . asSimpleNameList ( ) . get ( ) . getLocation ( ) ) ; assertSameLocation ( "" . length ( ) , "" . length ( ) , elem . asSimpleNameList ( ) . get ( ) . getLocation ( ) ) ; assertSameLocation ( "" . length ( ) , "" . length ( ) , elem . asSimpleNameList ( ) . get ( ) . getLocation ( ) ) ; assertEquals ( SHARP , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocName elem = JavadocBlockParserUtil . fetchName ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( DOT , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocName elem = JavadocBlockParserUtil . fetchName ( scanner , EnumSet . of ( WHITE_SPACES ) ) ; assertNull ( elem ) ; assertEquals ( IDENTIFIER , scanner . lookahead ( ) . getKind ( ) ) ; } } @ Test public void testFetchBasicType ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBasicType elem = JavadocBlockParserUtil . fetchBasicType ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( IrBasicTypeKind . INT , elem . getTypeKind ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBasicType elem = JavadocBlockParserUtil . fetchBasicType ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( IrBasicTypeKind . VOID , elem . getTypeKind ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBasicType elem = JavadocBlockParserUtil . fetchBasicType ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( IrBasicTypeKind . INT , elem . getTypeKind ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( LEFT_BRACKET , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBasicType elem = JavadocBlockParserUtil . fetchBasicType ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( SHARP , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBasicType elem = JavadocBlockParserUtil . fetchBasicType ( scanner , EnumSet . of ( WHITE_SPACES ) ) ; assertNull ( elem ) ; assertEquals ( IDENTIFIER , scanner . lookahead ( ) . getKind ( ) ) ; } } @ Test public void testFetchPrimitiveType ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBasicType elem = JavadocBlockParserUtil . fetchPrimitiveType ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( IrBasicTypeKind . INT , elem . getTypeKind ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocBasicType elem = JavadocBlockParserUtil . fetchPrimitiveType ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( IDENTIFIER , scanner . lookahead ( ) . getKind ( ) ) ; } } @ Test public void testFetchNamedType ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocNamedType elem = JavadocBlockParserUtil . fetchNamedType ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( SHARP , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocNamedType elem = JavadocBlockParserUtil . fetchNamedType ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( SHARP , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocNamedType elem = JavadocBlockParserUtil . fetchNamedType ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( SLASH , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocNamedType elem = JavadocBlockParserUtil . fetchNamedType ( scanner , EnumSet . of ( WHITE_SPACES ) ) ; assertNull ( elem ) ; assertEquals ( IDENTIFIER , scanner . lookahead ( ) . getKind ( ) ) ; } } @ Test public void testFetchType ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocType type = JavadocBlockParserUtil . fetchType ( scanner , null ) ; assertNotNull ( type ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , type . getKind ( ) ) ; IrDocBasicType elem = ( IrDocBasicType ) type ; assertEquals ( IrBasicTypeKind . DOUBLE , elem . getTypeKind ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocType type = JavadocBlockParserUtil . fetchType ( scanner , null ) ; assertNotNull ( type ) ; assertEquals ( IrDocElementKind . ARRAY_TYPE , type . getKind ( ) ) ; IrDocArrayType array = ( IrDocArrayType ) type ; assertSameLocation ( , "" . length ( ) , array . getLocation ( ) ) ; IrDocBasicType elem = ( IrDocBasicType ) array . getComponentType ( ) ; assertEquals ( IrBasicTypeKind . FLOAT , elem . getTypeKind ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocType type = JavadocBlockParserUtil . fetchType ( scanner , null ) ; assertNotNull ( type ) ; assertEquals ( IrDocElementKind . ARRAY_TYPE , type . getKind ( ) ) ; IrDocArrayType array = ( IrDocArrayType ) type ; assertSameLocation ( , "" . length ( ) , array . getLocation ( ) ) ; IrDocType component = array . getComponentType ( ) ; assertEquals ( IrDocElementKind . ARRAY_TYPE , component . getKind ( ) ) ; IrDocArrayType array2 = ( IrDocArrayType ) component ; assertSameLocation ( , "" . length ( ) , array2 . getLocation ( ) ) ; IrDocBasicType elem = ( IrDocBasicType ) array2 . getComponentType ( ) ; assertEquals ( IrBasicTypeKind . CHAR , elem . getTypeKind ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocType type = JavadocBlockParserUtil . fetchType ( scanner , null ) ; assertNotNull ( type ) ; assertEquals ( IrDocElementKind . NAMED_TYPE , type . getKind ( ) ) ; IrDocNamedType elem = ( IrDocNamedType ) type ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocType type = JavadocBlockParserUtil . fetchType ( scanner , null ) ; assertNotNull ( type ) ; assertEquals ( IrDocElementKind . ARRAY_TYPE , type . getKind ( ) ) ; IrDocArrayType array = ( IrDocArrayType ) type ; assertSameLocation ( , "" . length ( ) , array . getLocation ( ) ) ; IrDocNamedType elem = ( IrDocNamedType ) array . getComponentType ( ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } } @ Test public void testFetchField ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocField elem = JavadocBlockParserUtil . fetchField ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . getIdentifier ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( LEFT_BRACE , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocField elem = JavadocBlockParserUtil . fetchField ( scanner , null ) ; assertNotNull ( elem ) ; assertNull ( elem . getDeclaringType ( ) ) ; assertEquals ( "" , elem . getName ( ) . getIdentifier ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( LEFT_BRACE , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocField elem = JavadocBlockParserUtil . fetchField ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocField elem = JavadocBlockParserUtil . fetchField ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocField elem = JavadocBlockParserUtil . fetchField ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocField elem = JavadocBlockParserUtil . fetchField ( scanner , EnumSet . of ( WHITE_SPACES ) ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } } @ Test public void testFetchMethod ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; assertEquals ( LEFT_BRACE , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNotNull ( elem ) ; assertNull ( elem . getDeclaringType ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; assertEquals ( LEFT_BRACE , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; assertNull ( param . getName ( ) ) ; } assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; assertFalse ( param . isVariableArity ( ) ) ; assertNotNull ( param . getName ( ) ) ; assertEquals ( "" , param . getName ( ) . getIdentifier ( ) ) ; } assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . NAMED_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( "" , ( ( IrDocNamedType ) param . getType ( ) ) . getName ( ) . asString ( ) ) ; assertTrue ( param . isVariableArity ( ) ) ; assertNull ( param . getName ( ) ) ; } assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . NAMED_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( "" , ( ( IrDocNamedType ) param . getType ( ) ) . getName ( ) . asString ( ) ) ; assertTrue ( param . isVariableArity ( ) ) ; assertNotNull ( param . getName ( ) ) ; assertEquals ( "" , param . getName ( ) . getIdentifier ( ) ) ; } assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; assertFalse ( param . isVariableArity ( ) ) ; assertNull ( param . getName ( ) ) ; } { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; assertFalse ( param . isVariableArity ( ) ) ; assertNull ( param . getName ( ) ) ; } assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNotNull ( elem ) ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; assertFalse ( param . isVariableArity ( ) ) ; assertNotNull ( param . getName ( ) ) ; assertEquals ( "" , param . getName ( ) . getIdentifier ( ) ) ; } { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; assertFalse ( param . isVariableArity ( ) ) ; assertNotNull ( param . getName ( ) ) ; assertEquals ( "" , param . getName ( ) . getIdentifier ( ) ) ; } assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , null ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocMethod elem = JavadocBlockParserUtil . fetchMethod ( scanner , EnumSet . of ( WHITE_SPACES ) ) ; assertNull ( elem ) ; assertEquals ( , scanner . getIndex ( ) ) ; } } @ Test public void testFetchLinkTarget ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; IrDocFragment target = JavadocBlockParserUtil . fetchLinkTarget ( scanner , null ) ; assertNotNull ( target ) ; assertEquals ( IrDocElementKind . NAMED_TYPE , target . getKind ( ) ) ; IrDocNamedType elem = ( IrDocNamedType ) target ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocFragment target = JavadocBlockParserUtil . fetchLinkTarget ( scanner , null ) ; assertNotNull ( target ) ; assertEquals ( IrDocElementKind . FIELD , target . getKind ( ) ) ; IrDocField elem = ( IrDocField ) target ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . getIdentifier ( ) ) ; assertSameLocation ( , "" . length ( ) , elem . getLocation ( ) ) ; assertEquals ( LEFT_BRACE , scanner . lookahead ( ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; IrDocFragment target = JavadocBlockParserUtil . fetchLinkTarget ( scanner , null ) ; assertNotNull ( target ) ; assertEquals ( IrDocElementKind . METHOD , target . getKind ( ) ) ; IrDocMethod elem = ( IrDocMethod ) target ; assertEquals ( "" , elem . getDeclaringType ( ) . getName ( ) . asString ( ) ) ; assertEquals ( "" , elem . getName ( ) . asString ( ) ) ; assertEquals ( , elem . getParameters ( ) . size ( ) ) ; { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; assertFalse ( param . isVariableArity ( ) ) ; assertNotNull ( param . getName ( ) ) ; assertEquals ( "" , param . getName ( ) . getIdentifier ( ) ) ; } { IrDocMethodParameter param = elem . getParameters ( ) . get ( ) ; assertEquals ( IrDocElementKind . BASIC_TYPE , param . getType ( ) . getKind ( ) ) ; assertEquals ( IrBasicTypeKind . INT , ( ( IrDocBasicType ) param . getType ( ) ) . getTypeKind ( ) ) ; assertFalse ( param . isVariableArity ( ) ) ; assertNotNull ( param . getName ( ) ) ; assertEquals ( "" , param . getName ( ) . getIdentifier ( ) ) ; } assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } } private void assertSameLocation ( int start , int length , IrLocation location ) { assertEquals ( start , location . getStartPosition ( ) ) ; assertEquals ( length , location . getLength ( ) ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind . * ; import static org . junit . Assert . * ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . junit . Assert ; import com . asakusafw . utils . java . internal . model . util . JavaEscape ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElement ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocText ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; public class JavadocTestRoot { public static String load ( String name ) { InputStream in = JavadocTestRoot . class . getResourceAsStream ( name ) ; Assert . assertNotNull ( name , in ) ; try { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = in . read ( buf ) ; if ( read == - ) { break ; } out . write ( buf , , read ) ; } String content = new String ( out . toByteArray ( ) , "" ) ; content = content . replaceAll ( "" , "" ) ; return content ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } finally { try { in . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } public static DefaultJavadocScanner string ( String text ) { Assert . assertNotNull ( text ) ; return DefaultJavadocScanner . newInstance ( text ) ; } public static DefaultJavadocScanner scanner ( String name ) { String resource = load ( name ) ; return string ( resource ) ; } public static DefaultJavadocTokenStream stream ( String name ) { return new DefaultJavadocTokenStream ( scanner ( name ) ) ; } public static void assertTextSequence ( List < ? extends JavadocToken > tokens , String ... expected ) { if ( tokens . size ( ) != expected . length ) { Assert . fail ( MessageFormat . format ( "" , format ( expected ) , format ( tokens ) ) ) ; } for ( int i = , n = tokens . size ( ) ; i < n ; i ++ ) { if ( ! tokens . get ( i ) . getText ( ) . equals ( expected [ i ] ) ) { Assert . fail ( MessageFormat . format ( "" , i , format ( expected [ i ] ) , format ( tokens . get ( i ) . getText ( ) ) ) ) ; } } } public static String toString ( List < ? extends JavadocToken > tokens ) { StringBuilder buf = new StringBuilder ( ) ; for ( JavadocToken t : tokens ) { buf . append ( t . getText ( ) ) ; } return buf . toString ( ) ; } public static void assertKinds ( List < ? extends IrDocElement > elements , IrDocElementKind ... expected ) { if ( elements . size ( ) != expected . length ) { Assert . fail ( MessageFormat . format ( "" , Arrays . deepToString ( expected ) , elements ) ) ; } for ( int i = , n = elements . size ( ) ; i < n ; i ++ ) { if ( ! elements . get ( i ) . getKind ( ) . equals ( expected [ i ] ) ) { Assert . fail ( MessageFormat . format ( "" , i , expected [ i ] , elements . get ( i ) ) ) ; } } } public static void assertTextEquals ( String content , IrDocFragment fragment ) { Assert . assertEquals ( IrDocElementKind . TEXT , fragment . getKind ( ) ) ; Assert . assertEquals ( content , ( ( IrDocText ) fragment ) . getContent ( ) ) ; } public static void assertMockBlockEquals ( MockJavadocBlockParser parser , String tag , IrDocFragment fragment ) { assertEquals ( BLOCK , fragment . getKind ( ) ) ; IrDocBlock block = ( IrDocBlock ) fragment ; assertEquals ( tag , block . getTag ( ) ) ; List < ? extends IrDocFragment > inlines = block . getFragments ( ) ; assertKinds ( inlines , TEXT ) ; assertEquals ( parser . getIdentifier ( ) , ( ( IrDocText ) inlines . get ( ) ) . getContent ( ) ) ; } private static String format ( String string ) { return '' + JavaEscape . escape ( string , false , false ) + '' ; } private static List < String > format ( String ... list ) { List < String > formatted = new ArrayList < String > ( list . length ) ; for ( String s : list ) { formatted . add ( format ( s ) ) ; } return formatted ; } private static List < String > format ( List < ? extends JavadocToken > list ) { List < String > formatted = new ArrayList < String > ( list . size ( ) ) ; for ( JavadocToken t : list ) { formatted . add ( format ( t . getText ( ) ) ) ; } return formatted ; } } package com . asakusafw . utils . java . parser . javadoc ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; public class AcceptableJavadocBlockParserTest { @ Test public void testCanAccept ( ) { AcceptableJavadocBlockParser parser = new AcceptableJavadocBlockParser ( "" , "" , "" ) { @ Override public IrDocBlock parse ( String tag , JavadocScanner scanner ) { return null ; } } ; assertTrue ( parser . canAccept ( "" ) ) ; assertTrue ( parser . canAccept ( "" ) ) ; assertTrue ( parser . canAccept ( "" ) ) ; assertFalse ( parser . canAccept ( "" ) ) ; assertFalse ( parser . canAccept ( "" ) ) ; assertFalse ( parser . canAccept ( "" ) ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind . * ; import static org . junit . Assert . * ; import java . util . List ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; public class ParamBlockParserTest extends JavadocTestRoot { @ Test public void testParse ( ) throws Exception { { ParamBlockParser parser = new ParamBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( "" , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , SIMPLE_NAME ) ; assertEquals ( "" , ( ( IrDocSimpleName ) fragments . get ( ) ) . getIdentifier ( ) ) ; } { ParamBlockParser parser = new ParamBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( "" , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , SIMPLE_NAME , TEXT ) ; assertEquals ( "" , ( ( IrDocSimpleName ) fragments . get ( ) ) . getIdentifier ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { ParamBlockParser parser = new ParamBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( "" , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , TEXT , SIMPLE_NAME , TEXT , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; assertEquals ( "" , ( ( IrDocSimpleName ) fragments . get ( ) ) . getIdentifier ( ) ) ; assertTextEquals ( ">" , fragments . get ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { ParamBlockParser parser = new ParamBlockParser ( ) ; DefaultJavadocScanner scanner = string ( "" ) ; IrDocBlock block = parser . parse ( "" , scanner ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; public class DefaultJavadocScannerTest extends JavadocTestRoot { @ Test public void testNewInstanceEmpty ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; } @ Test public void testNewInstanceSingleSpace ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( WHITE_SPACES , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; } @ Test public void testNewInstance3Lines ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( LINE_BREAK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( WHITE_SPACES , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( LINE_BREAK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( WHITE_SPACES , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; } @ Test public void testNewInstanceSynopsis ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( LINE_BREAK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( WHITE_SPACES , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( WHITE_SPACES , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( IDENTIFIER , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( COMMA , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( WHITE_SPACES , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( IDENTIFIER , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( TEXT , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( LINE_BREAK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( WHITE_SPACES , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; } @ Test public void testGetIndex ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; int index = ; while ( true ) { assertEquals ( index , scanner . getIndex ( ) ) ; JavadocToken t = scanner . nextToken ( ) ; if ( t . getKind ( ) == EOF ) { break ; } index ++ ; } assertEquals ( index , scanner . getIndex ( ) ) ; scanner . nextToken ( ) ; assertEquals ( index , scanner . getIndex ( ) ) ; } @ Test public void testSeek ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; scanner . seek ( ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; scanner . seek ( ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; scanner . seek ( ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; } @ Test public void testConsume ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; scanner . consume ( ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; } @ Test public void testNextToken ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( SLASH , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . nextToken ( ) . getKind ( ) ) ; } @ Test public void testLookahead ( ) { String text = load ( "" ) ; DefaultJavadocScanner scanner = DefaultJavadocScanner . newInstance ( text ) ; assertEquals ( SLASH , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( SLASH , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; scanner . consume ( ) ; assertEquals ( SLASH , scanner . lookahead ( - ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . lookahead ( - ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . lookahead ( - ) . getKind ( ) ) ; assertEquals ( ASTERISK , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( SLASH , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; assertEquals ( EOF , scanner . lookahead ( ) . getKind ( ) ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementKind . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import java . util . regex . Pattern ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; public class DefaultJavadocBlockParserTest extends JavadocTestRoot { @ Test public void testDefaultJavadocBlockParser ( ) { DefaultJavadocBlockParser parser = new DefaultJavadocBlockParser ( ) ; assertEquals ( , parser . getBlockParsers ( ) . size ( ) ) ; } @ Test public void testDefaultJavadocBlockParserInlines ( ) { MockJavadocBlockParser m1 = new MockJavadocBlockParser ( ) ; MockJavadocBlockParser m2 = new MockJavadocBlockParser ( ) ; MockJavadocBlockParser m3 = new MockJavadocBlockParser ( ) ; DefaultJavadocBlockParser parser = new DefaultJavadocBlockParser ( Arrays . asList ( m1 , m2 , m3 ) ) ; List < ? extends JavadocBlockParser > parsers = parser . getBlockParsers ( ) ; assertEquals ( , parsers . size ( ) ) ; assertSame ( m1 , parsers . get ( ) ) ; assertSame ( m2 , parsers . get ( ) ) ; assertSame ( m3 , parsers . get ( ) ) ; } @ Test public void testCanAccept ( ) { DefaultJavadocBlockParser parser = new DefaultJavadocBlockParser ( ) ; assertTrue ( parser . canAccept ( null ) ) ; assertTrue ( parser . canAccept ( "" ) ) ; assertTrue ( parser . canAccept ( "" ) ) ; assertTrue ( parser . canAccept ( "" ) ) ; } @ Test public void testParse ( ) throws Exception { MockJavadocBlockParser i1 = new MockJavadocBlockParser ( ) ; i1 . setIdentifier ( "" ) ; i1 . setAcceptable ( Pattern . compile ( "" ) ) ; DefaultJavadocBlockParser parser = new DefaultJavadocBlockParser ( Arrays . asList ( i1 ) ) ; { IrDocBlock block = parser . parse ( null , string ( "" ) ) ; assertNull ( block . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , TEXT ) ; } { IrDocBlock block = parser . parse ( null , string ( "" ) ) ; assertNull ( block . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , BLOCK ) ; assertMockBlockEquals ( i1 , "" , fragments . get ( ) ) ; } { IrDocBlock block = parser . parse ( null , string ( "" ) ) ; assertNull ( block . getTag ( ) ) ; List < ? extends IrDocFragment > fragments = block . getFragments ( ) ; assertKinds ( fragments , TEXT , BLOCK , TEXT ) ; assertTextEquals ( "" , fragments . get ( ) ) ; assertMockBlockEquals ( i1 , "" , fragments . get ( ) ) ; assertTextEquals ( "" , fragments . get ( ) ) ; } { try { parser . parse ( null , string ( "" ) ) ; fail ( ) ; } catch ( MissingJavadocBlockParserException e ) { assertEquals ( "" , e . getTagName ( ) ) ; } } } } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind . * ; import static org . junit . Assert . * ; import java . util . EnumSet ; import java . util . List ; import org . junit . Test ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public class JavadocScannerUtilTest extends JavadocTestRoot { @ Test public void testLookaheadTokens ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; { List < JavadocToken > tokens = JavadocScannerUtil . lookaheadTokens ( scanner , , ) ; assertTextSequence ( tokens ) ; } { List < JavadocToken > tokens = JavadocScannerUtil . lookaheadTokens ( scanner , , ) ; assertTextSequence ( tokens , "" ) ; } { List < JavadocToken > tokens = JavadocScannerUtil . lookaheadTokens ( scanner , , ) ; assertTextSequence ( tokens , "" , "" , "" ) ; } { List < JavadocToken > tokens = JavadocScannerUtil . lookaheadTokens ( scanner , , ) ; assertTextSequence ( tokens , "" , "" , "" ) ; } { List < JavadocToken > tokens = JavadocScannerUtil . lookaheadTokens ( scanner , , ) ; assertTextSequence ( tokens , "" , "" , "" , "" , "" ) ; } } @ Test public void testCountWhileVoid ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } } @ Test public void testCountWhileSingle ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; { EnumSet < JavadocTokenKind > set = EnumSet . of ( ASTERISK ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( ASTERISK ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( ASTERISK ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( ASTERISK ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( IDENTIFIER ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( IDENTIFIER ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } } @ Test public void testCountWhileMulti ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; { EnumSet < JavadocTokenKind > set = EnumSet . of ( ASTERISK , IDENTIFIER ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( ASTERISK , IDENTIFIER , QUESTION ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( QUESTION , WHITE_SPACES ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( QUESTION , WHITE_SPACES ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . allOf ( JavadocTokenKind . class ) ; int count = JavadocScannerUtil . countWhile ( set , scanner , ) ; assertEquals ( scanner . getTokens ( ) . size ( ) , count ) ; } } @ Test public void testCountUntilVoid ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( scanner . getTokens ( ) . size ( ) , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( scanner . getTokens ( ) . size ( ) - , count ) ; } } @ Test public void testCountUntilSingle ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; { EnumSet < JavadocTokenKind > set = EnumSet . of ( ASTERISK ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( IDENTIFIER ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( QUESTION ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( WHITE_SPACES ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( AT ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( , count ) ; } } @ Test public void testCountUntilMulti ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; { EnumSet < JavadocTokenKind > set = EnumSet . of ( IDENTIFIER , AT ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( , count ) ; } { EnumSet < JavadocTokenKind > set = EnumSet . of ( IDENTIFIER , AT ) ; int count = JavadocScannerUtil . countUntil ( set , scanner , ) ; assertEquals ( , count ) ; } } @ Test public void testCountUntilBlockEnd ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; int count = JavadocScannerUtil . countUntilBlockEnd ( scanner , ) ; assertEquals ( EOF , scanner . lookahead ( count ) . getKind ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" ) ; int count = JavadocScannerUtil . countUntilBlockEnd ( scanner , ) ; assertEquals ( AT , scanner . lookahead ( count ) . getKind ( ) ) ; assertEquals ( "" , scanner . lookahead ( count + ) . getText ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" ) ; int count = JavadocScannerUtil . countUntilBlockEnd ( scanner , ) ; assertEquals ( AT , scanner . lookahead ( count ) . getKind ( ) ) ; assertEquals ( "" , scanner . lookahead ( count + ) . getText ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" ) ; int count = JavadocScannerUtil . countUntilBlockEnd ( scanner , ) ; assertEquals ( AT , scanner . lookahead ( count ) . getKind ( ) ) ; assertEquals ( "" , scanner . lookahead ( count + ) . getText ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" + "" ) ; int count = JavadocScannerUtil . countUntilBlockEnd ( scanner , ) ; assertEquals ( AT , scanner . lookahead ( count ) . getKind ( ) ) ; assertEquals ( "" , scanner . lookahead ( count + ) . getText ( ) ) ; } { DefaultJavadocScanner scanner = string ( "" + "" + "" + "" + "" + "" ) ; int count = JavadocScannerUtil . countUntilBlockEnd ( scanner , ) ; assertEquals ( AT , scanner . lookahead ( + count ) . getKind ( ) ) ; assertEquals ( "" , scanner . lookahead ( + count + ) . getText ( ) ) ; } } @ Test public void testCountUntilCommentEnd ( ) { { DefaultJavadocScanner scanner = string ( "" ) ; int count = JavadocScannerUtil . countUntilCommentEnd ( scanner , true , ) ; assertEquals ( , count ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; int count = JavadocScannerUtil . countUntilCommentEnd ( scanner , true , ) ; assertEquals ( , count ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; int count = JavadocScannerUtil . countUntilCommentEnd ( scanner , true , ) ; assertEquals ( , count ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; int count = JavadocScannerUtil . countUntilCommentEnd ( scanner , false , ) ; assertEquals ( , count ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; int count = JavadocScannerUtil . countUntilCommentEnd ( scanner , true , ) ; assertEquals ( , count ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; int count = JavadocScannerUtil . countUntilCommentEnd ( scanner , true , ) ; assertEquals ( - , count ) ; } { DefaultJavadocScanner scanner = string ( "" ) ; int count = JavadocScannerUtil . countUntilCommentEnd ( scanner , false , ) ; assertEquals ( scanner . getTokens ( ) . size ( ) , count ) ; } } @ Test public void testCountUntilNextLineStart ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; int offset = ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; assertEquals ( LINE_BREAK , scanner . lookahead ( offset ) . getKind ( ) ) ; offset += JavadocScannerUtil . countUntilNextLineStart ( scanner , offset ) ; assertEquals ( WHITE_SPACES , scanner . lookahead ( offset ) . getKind ( ) ) ; assertEquals ( "" , scanner . lookahead ( offset + ) . getText ( ) ) ; offset += ; assertEquals ( LINE_BREAK , scanner . lookahead ( offset ) . getKind ( ) ) ; offset += JavadocScannerUtil . countUntilNextLineStart ( scanner , offset ) ; assertEquals ( WHITE_SPACES , scanner . lookahead ( offset ) . getKind ( ) ) ; assertEquals ( "" , scanner . lookahead ( offset + ) . getText ( ) ) ; offset += ; assertEquals ( EOF , scanner . lookahead ( offset ) . getKind ( ) ) ; } @ Test public void testCountUntilNextPrintableGeneral ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; int offset = ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; assertEquals ( WHITE_SPACES , scanner . lookahead ( offset ) . getKind ( ) ) ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; assertEquals ( WHITE_SPACES , scanner . lookahead ( offset ) . getKind ( ) ) ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; } @ Test public void testCountUntilNextPrintableBeyondLines ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; int offset = ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( EOF , scanner . lookahead ( offset ) . getKind ( ) ) ; } @ Test public void testCountUntilNextPrintableBeyondBlankLines ( ) { DefaultJavadocScanner scanner = scanner ( "" ) ; int offset = ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( "" , scanner . lookahead ( offset ) . getText ( ) ) ; offset ++ ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; assertEquals ( EOF , scanner . lookahead ( offset ) . getKind ( ) ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public enum JavadocTokenKind { WHITE_SPACES , LINE_BREAK , ASTERISK , IDENTIFIER , AT , DOT , COMMA , SHARP , LEFT_BRACKET , RIGHT_BRACKET , LEFT_BRACE , RIGHT_BRACE , LEFT_PAREN , RIGHT_PAREN , LESS , GREATER , SLASH , QUESTION , TEXT , EOF , } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public abstract class IrDocElementVisitor < R , P > { public R visitComment ( IrDocComment elem , P context ) { return null ; } public R visitBlock ( IrDocBlock elem , P context ) { return null ; } public R visitSimpleName ( IrDocSimpleName elem , P context ) { return null ; } public R visitQualifiedName ( IrDocQualifiedName elem , P context ) { return null ; } public R visitField ( IrDocField elem , P context ) { return null ; } public R visitMethod ( IrDocMethod elem , P context ) { return null ; } public R visitText ( IrDocText elem , P context ) { return null ; } public R visitMethodParameter ( IrDocMethodParameter elem , P context ) { return null ; } public R visitBasicType ( IrDocBasicType elem , P context ) { return null ; } public R visitNamedType ( IrDocNamedType elem , P context ) { return null ; } public R visitArrayType ( IrDocArrayType elem , P context ) { return null ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . io . Serializable ; public final class JavadocToken implements Serializable { private static final long serialVersionUID = ; private final JavadocTokenKind kind ; private final String text ; private final int start ; public JavadocToken ( JavadocTokenKind kind , String text , int start ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( text == null ) { throw new IllegalArgumentException ( "" ) ; } this . kind = kind ; this . text = text ; this . start = start ; } public JavadocTokenKind getKind ( ) { return this . kind ; } public String getText ( ) { return this . text ; } public int getStartPosition ( ) { return this . start ; } public IrLocation getLocation ( ) { return new IrLocation ( getStartPosition ( ) , getText ( ) . length ( ) ) ; } @ Override public String toString ( ) { return getText ( ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . util . ArrayList ; import java . util . LinkedList ; import java . util . List ; public class IrDocQualifiedName extends IrDocName { private static final long serialVersionUID = ; private IrDocName qualifier ; private IrDocSimpleName name ; public IrDocQualifiedName ( IrDocName qualifier , IrDocSimpleName name ) { super ( ) ; if ( qualifier == null ) { throw new IllegalArgumentException ( "" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . qualifier = qualifier ; this . name = name ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . QUALIFIED_NAME ; } public IrDocName getQualifier ( ) { return this . qualifier ; } public void setQualifier ( IrDocName qualifier ) { if ( qualifier == null ) { throw new IllegalArgumentException ( "" ) ; } checkCyclic ( qualifier ) ; this . qualifier = qualifier ; } private void checkCyclic ( IrDocName target ) { IrDocName current = target ; while ( current . getKind ( ) == IrDocElementKind . QUALIFIED_NAME ) { if ( current == this ) { throw new IllegalArgumentException ( target . toString ( ) ) ; } current = ( ( IrDocQualifiedName ) target ) . getQualifier ( ) ; } } public IrDocSimpleName getName ( ) { return this . name ; } public void setName ( IrDocSimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } @ Override public String asString ( ) { LinkedList < IrDocSimpleName > names = new LinkedList < IrDocSimpleName > ( ) ; IrDocName current = getQualifier ( ) ; while ( current . getKind ( ) == IrDocElementKind . QUALIFIED_NAME ) { IrDocQualifiedName qName = ( IrDocQualifiedName ) current ; names . addFirst ( qName . getName ( ) ) ; current = qName . getQualifier ( ) ; } names . addFirst ( ( IrDocSimpleName ) current ) ; StringBuilder buf = new StringBuilder ( ) ; for ( IrDocSimpleName n : names ) { buf . append ( n . getIdentifier ( ) ) ; buf . append ( '' ) ; } buf . append ( getName ( ) . getIdentifier ( ) ) ; return buf . toString ( ) ; } @ Override public List < IrDocSimpleName > asSimpleNameList ( ) { LinkedList < IrDocSimpleName > names = new LinkedList < IrDocSimpleName > ( ) ; names . addFirst ( getName ( ) ) ; IrDocName current = this . getQualifier ( ) ; while ( current . getKind ( ) == IrDocElementKind . QUALIFIED_NAME ) { IrDocQualifiedName q = ( IrDocQualifiedName ) current ; names . addFirst ( q . getName ( ) ) ; current = q . getQualifier ( ) ; } names . addFirst ( ( IrDocSimpleName ) current ) ; return new ArrayList < IrDocSimpleName > ( names ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + name . hashCode ( ) ; result = prime * result + qualifier . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocQualifiedName other = ( IrDocQualifiedName ) obj ; if ( ! name . equals ( other . name ) ) { return false ; } if ( ! qualifier . equals ( other . qualifier ) ) { return false ; } return true ; } @ Override public String toString ( ) { return asString ( ) ; } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitQualifiedName ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public class IrDocMethod extends IrDocMember { private static final long serialVersionUID = ; private List < ? extends IrDocMethodParameter > parameters ; public IrDocMethod ( ) { super ( ) ; this . parameters = Collections . emptyList ( ) ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . METHOD ; } public List < ? extends IrDocMethodParameter > getParameters ( ) { return this . parameters ; } public void setParameters ( List < ? extends IrDocMethodParameter > parameters ) { if ( parameters == null ) { throw new IllegalArgumentException ( "" ) ; } this . parameters = Collections . unmodifiableList ( new ArrayList < IrDocMethodParameter > ( parameters ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; IrDocNamedType type = getDeclaringType ( ) ; result = prime * result + ( type == null ? : type . hashCode ( ) ) ; IrDocSimpleName name = getName ( ) ; result = prime * result + ( name == null ? : name . hashCode ( ) ) ; result = prime * result + ( parameters == null ? : parameters . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocMethod other = ( IrDocMethod ) obj ; IrDocNamedType type = getDeclaringType ( ) ; IrDocNamedType oType = other . getDeclaringType ( ) ; if ( type == null ) { if ( oType != null ) { return false ; } } else if ( type . equals ( oType ) == false ) { return false ; } IrDocSimpleName name = getName ( ) ; IrDocSimpleName oName = other . getName ( ) ; if ( name == null ) { if ( oName != null ) { return false ; } } else if ( name . equals ( oName ) == false ) { return false ; } if ( parameters == null ) { if ( other . parameters != null ) { return false ; } } else if ( parameters . equals ( other . parameters ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { if ( getDeclaringType ( ) == null ) { return MessageFormat . format ( "" , getDeclaringType ( ) , getName ( ) , parameters ) ; } else { return MessageFormat . format ( "" , getDeclaringType ( ) , getName ( ) , parameters ) ; } } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitMethod ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public class IrDocBasicType extends AbstractIrDocElement implements IrDocType { private static final long serialVersionUID = ; private IrBasicTypeKind typeKind ; public IrDocBasicType ( IrBasicTypeKind typeKind ) { super ( ) ; if ( typeKind == null ) { throw new IllegalArgumentException ( "" ) ; } this . typeKind = typeKind ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . BASIC_TYPE ; } public IrBasicTypeKind getTypeKind ( ) { return this . typeKind ; } public void setTypeKind ( IrBasicTypeKind typeKind ) { if ( typeKind == null ) { throw new IllegalArgumentException ( "" ) ; } this . typeKind = typeKind ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + typeKind . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocBasicType other = ( IrDocBasicType ) obj ; if ( ! typeKind . equals ( other . typeKind ) ) { return false ; } return true ; } @ Override public String toString ( ) { return getTypeKind ( ) . getSymbol ( ) ; } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitBasicType ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public class IrDocText extends AbstractIrDocElement implements IrDocFragment { private static final long serialVersionUID = ; private String content ; public IrDocText ( String content ) { super ( ) ; this . content = content ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . TEXT ; } public String getContent ( ) { return this . content ; } public void setContent ( String content ) { if ( content == null ) { throw new IllegalArgumentException ( "" ) ; } checkContent ( content ) ; this . content = content ; } private void checkContent ( String text ) { if ( text . indexOf ( "" ) >= ) { throw new IllegalArgumentException ( text ) ; } } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( content == null ) ? : content . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocText other = ( IrDocText ) obj ; if ( content == null ) { if ( other . content != null ) { return false ; } } else if ( ! content . equals ( other . content ) ) { return false ; } return true ; } @ Override public String toString ( ) { return getContent ( ) ; } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitText ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public class IrDocArrayType extends AbstractIrDocElement implements IrDocType { private static final long serialVersionUID = ; private IrDocType componentType ; public IrDocArrayType ( IrDocType componentType ) { super ( ) ; if ( componentType == null ) { throw new IllegalArgumentException ( "" ) ; } this . componentType = componentType ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . ARRAY_TYPE ; } public IrDocType getComponentType ( ) { return this . componentType ; } public void setComponentType ( IrDocType componentType ) { if ( componentType == null ) { throw new IllegalArgumentException ( "" ) ; } checkCyclic ( componentType ) ; this . componentType = componentType ; } private void checkCyclic ( IrDocType t ) { IrDocType current = t ; while ( t . getKind ( ) == IrDocElementKind . ARRAY_TYPE ) { if ( current == this ) { throw new IllegalArgumentException ( t . toString ( ) ) ; } } } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( componentType == null ) ? : componentType . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocArrayType other = ( IrDocArrayType ) obj ; if ( componentType == null ) { if ( other . componentType != null ) { return false ; } } else if ( ! componentType . equals ( other . componentType ) ) { return false ; } return true ; } @ Override public String toString ( ) { return getComponentType ( ) + "" ; } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitArrayType ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public class IrDocBlock extends AbstractIrDocElement implements IrDocFragment { private static final long serialVersionUID = ; private String tag ; private List < ? extends IrDocFragment > fragments ; public IrDocBlock ( ) { super ( ) ; this . tag = null ; this . fragments = Collections . emptyList ( ) ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . BLOCK ; } public String getTag ( ) { return this . tag ; } public void setTag ( String tag ) { if ( tag == null ) { this . tag = null ; } else { if ( tag . length ( ) == || tag . charAt ( ) != '' ) { this . tag = ( '' + tag ) . intern ( ) ; } else { this . tag = tag ; } } } public List < ? extends IrDocFragment > getFragments ( ) { return this . fragments ; } public void setFragments ( List < ? extends IrDocFragment > fragments ) { if ( fragments == null ) { throw new IllegalArgumentException ( "" ) ; } this . fragments = Collections . unmodifiableList ( new ArrayList < IrDocFragment > ( fragments ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + fragments . hashCode ( ) ; result = prime * result + ( ( tag == null ) ? : tag . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocBlock other = ( IrDocBlock ) obj ; if ( ! fragments . equals ( other . fragments ) ) { return false ; } if ( tag == null ) { if ( other . tag != null ) { return false ; } } else if ( ! tag . equals ( other . tag ) ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder buf = new StringBuilder ( ) ; if ( getTag ( ) != null ) { buf . append ( getTag ( ) ) ; buf . append ( "" ) ; } for ( IrDocFragment f : getFragments ( ) ) { buf . append ( f ) ; buf . append ( "" ) ; } return buf . toString ( ) ; } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitBlock ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . io . Serializable ; public abstract class AbstractIrDocElement implements IrDocElement , Serializable { private static final long serialVersionUID = ; private IrLocation location ; @ Override public IrLocation getLocation ( ) { return this . location ; } @ Override public void setLocation ( IrLocation location ) { this . location = location ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public enum IrDocElementKind { COMMENT , BLOCK , SIMPLE_NAME , QUALIFIED_NAME , FIELD , METHOD , TEXT , METHOD_PARAMETER , BASIC_TYPE , NAMED_TYPE , ARRAY_TYPE , } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public interface IrDocType extends IrDocFragment { } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public class IrDocNamedType extends AbstractIrDocElement implements IrDocFragment , IrDocType { private static final long serialVersionUID = ; private IrDocName name ; public IrDocNamedType ( IrDocName name ) { super ( ) ; if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . NAMED_TYPE ; } public IrDocName getName ( ) { return this . name ; } public void setName ( IrDocName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocNamedType other = ( IrDocNamedType ) obj ; if ( name == null ) { if ( other . name != null ) { return false ; } } else if ( ! name . equals ( other . name ) ) { return false ; } return true ; } @ Override public String toString ( ) { return getName ( ) . toString ( ) ; } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitNamedType ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . io . Serializable ; import java . text . MessageFormat ; public class IrLocation implements Serializable { private static final long serialVersionUID = ; private final int startPosition ; private final int length ; public IrLocation ( int startPosition , int length ) { super ( ) ; if ( startPosition < || length < ) { throw new IllegalArgumentException ( ) ; } this . startPosition = startPosition ; this . length = length ; } public int getStartPosition ( ) { return this . startPosition ; } public int getLength ( ) { return this . length ; } public static IrLocation move ( IrLocation base , int offset ) { if ( base == null ) { return null ; } int fixed = base . getStartPosition ( ) + offset ; return new IrLocation ( fixed , base . length ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + length ; result = prime * result + startPosition ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrLocation other = ( IrLocation ) obj ; if ( length != other . length ) { return false ; } if ( startPosition != other . startPosition ) { return false ; } return true ; } @ Override public String toString ( ) { int s = getStartPosition ( ) ; return MessageFormat . format ( "" , s , s + getLength ( ) ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public class IrDocComment extends AbstractIrDocElement { private static final long serialVersionUID = ; private List < ? extends IrDocBlock > blocks ; public IrDocComment ( ) { super ( ) ; this . blocks = Collections . emptyList ( ) ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . COMMENT ; } public List < ? extends IrDocBlock > getBlocks ( ) { return this . blocks ; } public void setBlocks ( List < ? extends IrDocBlock > blocks ) { if ( blocks == null ) { throw new IllegalArgumentException ( "" ) ; } this . blocks = Collections . unmodifiableList ( new ArrayList < IrDocBlock > ( blocks ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( blocks == null ) ? : blocks . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocComment other = ( IrDocComment ) obj ; if ( blocks == null ) { if ( other . blocks != null ) { return false ; } } else if ( ! blocks . equals ( other . blocks ) ) { return false ; } return true ; } @ Override public String toString ( ) { StringWriter sw = new StringWriter ( ) ; PrintWriter w = new PrintWriter ( sw ) ; w . println ( "" ) ; for ( IrDocBlock b : getBlocks ( ) ) { w . print ( "" ) ; w . print ( b ) ; w . println ( ) ; } w . println ( "" ) ; w . flush ( ) ; return sw . toString ( ) ; } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitComment ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public abstract class IrDocMember extends AbstractIrDocElement implements IrDocFragment { private static final long serialVersionUID = - ; private IrDocNamedType declaringType ; private IrDocSimpleName name ; public IrDocMember ( ) { super ( ) ; } public IrDocNamedType getDeclaringType ( ) { return this . declaringType ; } public void setDeclaringType ( IrDocNamedType declaringType ) { this . declaringType = declaringType ; } public IrDocSimpleName getName ( ) { return this . name ; } public void setName ( IrDocSimpleName name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; public final class IrDocSimpleName extends IrDocName { private static final long serialVersionUID = ; private String identifier ; public IrDocSimpleName ( String identifier ) { super ( ) ; setIdentifier0 ( identifier ) ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . SIMPLE_NAME ; } public String getIdentifier ( ) { return this . identifier ; } public void setIdentifier ( String identifier ) { setIdentifier0 ( identifier ) ; } private void setIdentifier0 ( String id ) { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } if ( id . length ( ) == ) { throw new IllegalArgumentException ( "" ) ; } if ( ! Character . isJavaIdentifierStart ( id . charAt ( ) ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , id . charAt ( ) ) ) ; } for ( int i = , n = id . length ( ) ; i < n ; i ++ ) { if ( ! Character . isJavaIdentifierPart ( id . charAt ( i ) ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , i , id . charAt ( ) ) ) ; } } this . identifier = id ; } @ Override public String asString ( ) { return getIdentifier ( ) ; } @ Override public List < IrDocSimpleName > asSimpleNameList ( ) { return Collections . singletonList ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + identifier . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocSimpleName other = ( IrDocSimpleName ) obj ; if ( ! identifier . equals ( other . identifier ) ) { return false ; } return true ; } @ Override public String toString ( ) { return getIdentifier ( ) ; } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitSimpleName ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public interface IrDocFragment extends IrDocElement { } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . util . List ; public abstract class IrDocName extends AbstractIrDocElement implements IrDocFragment { private static final long serialVersionUID = - ; public abstract String asString ( ) ; public abstract List < IrDocSimpleName > asSimpleNameList ( ) ; } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . text . MessageFormat ; public class IrDocField extends IrDocMember { private static final long serialVersionUID = ; public IrDocField ( ) { super ( ) ; } @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . FIELD ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; IrDocNamedType type = getDeclaringType ( ) ; result = prime * result + ( type == null ? : type . hashCode ( ) ) ; IrDocSimpleName name = getName ( ) ; result = prime * result + ( name == null ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocField other = ( IrDocField ) obj ; IrDocNamedType type = getDeclaringType ( ) ; IrDocNamedType oType = other . getDeclaringType ( ) ; if ( type == null ) { if ( oType != null ) { return false ; } } else if ( type . equals ( oType ) == false ) { return false ; } IrDocSimpleName name = getName ( ) ; IrDocSimpleName oName = other . getName ( ) ; if ( name == null ) { if ( oName != null ) { return false ; } } else if ( name . equals ( oName ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { if ( getDeclaringType ( ) == null ) { return MessageFormat . format ( "" , getDeclaringType ( ) , getName ( ) ) ; } else { return MessageFormat . format ( "" , getDeclaringType ( ) , getName ( ) ) ; } } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitField ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public enum IrBasicTypeKind { INT , LONG , FLOAT , DOUBLE , BYTE , SHORT , CHAR , BOOLEAN , VOID , ; public String getSymbol ( ) { return name ( ) . toLowerCase ( ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; import java . text . MessageFormat ; public class IrDocMethodParameter extends AbstractIrDocElement { private static final long serialVersionUID = ; private IrDocType type ; private boolean variableArity ; private IrDocSimpleName name ; @ Override public IrDocElementKind getKind ( ) { return IrDocElementKind . METHOD_PARAMETER ; } public IrDocType getType ( ) { return this . type ; } public void setType ( IrDocType type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . type = type ; } public boolean isVariableArity ( ) { return this . variableArity ; } public void setVariableArity ( boolean variableArity ) { this . variableArity = variableArity ; } public IrDocSimpleName getName ( ) { return this . name ; } public void setName ( IrDocSimpleName name ) { this . name = name ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; result = prime * result + ( ( type == null ) ? : type . hashCode ( ) ) ; result = prime * result + ( variableArity ? : ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } final IrDocMethodParameter other = ( IrDocMethodParameter ) obj ; if ( name == null ) { if ( other . name != null ) { return false ; } } else if ( ! name . equals ( other . name ) ) { return false ; } if ( type == null ) { if ( other . type != null ) { return false ; } } else if ( ! type . equals ( other . type ) ) { return false ; } if ( variableArity != other . variableArity ) { return false ; } return true ; } @ Override public String toString ( ) { if ( getName ( ) == null ) { if ( isVariableArity ( ) ) { return getType ( ) + "" ; } else { return getType ( ) . toString ( ) ; } } else { return MessageFormat . format ( "" , getType ( ) , isVariableArity ( ) ? "" : "" , getName ( ) ) ; } } @ Override public < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) { if ( visitor == null ) { throw new IllegalArgumentException ( "" ) ; } return visitor . visitMethodParameter ( this , context ) ; } } package com . asakusafw . utils . java . internal . parser . javadoc . ir ; public interface IrDocElement { IrDocElementKind getKind ( ) ; IrLocation getLocation ( ) ; void setLocation ( IrLocation location ) ; < R , P > R accept ( IrDocElementVisitor < R , P > visitor , P context ) ; } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; public class FollowsReferenceBlockParser extends AcceptableJavadocBlockParser { public FollowsReferenceBlockParser ( String ... tagNames ) { super ( tagNames ) ; } @ Override public IrDocBlock parse ( String tag , JavadocScanner scanner ) throws JavadocParseException { ArrayList < IrDocFragment > fragments = new ArrayList < IrDocFragment > ( ) ; IrDocFragment first = fetchLinkTarget ( scanner ) ; if ( first != null ) { fragments . add ( first ) ; } fragments . addAll ( fetchRestFragments ( scanner ) ) ; fragments . trimToSize ( ) ; return newBlock ( tag , fragments ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; public abstract class AcceptableJavadocBlockParser extends JavadocBlockParser { private Set < String > acceptable ; public AcceptableJavadocBlockParser ( ) { super ( ) ; this . acceptable = Collections . emptySet ( ) ; } public AcceptableJavadocBlockParser ( String tagName , String ... tagNames ) { super ( ) ; this . acceptable = new HashSet < String > ( ) ; this . acceptable . add ( tagName ) ; this . acceptable . addAll ( Arrays . asList ( tagNames ) ) ; } public AcceptableJavadocBlockParser ( String [ ] tagNames ) { super ( ) ; this . acceptable = new HashSet < String > ( ) ; this . acceptable . addAll ( Arrays . asList ( tagNames ) ) ; } @ Override public boolean canAccept ( String tag ) { return acceptable . contains ( tag ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocText ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public class ParamBlockParser extends AcceptableJavadocBlockParser { public ParamBlockParser ( ) { super ( "" ) ; } public ParamBlockParser ( String tagName , String ... tagNames ) { super ( tagName , tagNames ) ; } @ Override public IrDocBlock parse ( String tag , JavadocScanner scanner ) throws JavadocParseException { ArrayList < IrDocFragment > fragments = new ArrayList < IrDocFragment > ( ) ; IrDocSimpleName name = fetchSimpleName ( scanner ) ; if ( name != null ) { fragments . add ( name ) ; } else { consumeIfTypeParameter ( scanner , fragments ) ; } fragments . addAll ( fetchRestFragments ( scanner ) ) ; fragments . trimToSize ( ) ; return newBlock ( tag , fragments ) ; } private void consumeIfTypeParameter ( JavadocScanner scanner , ArrayList < IrDocFragment > fragments ) { JavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; JavadocToken first = stream . nextToken ( ) ; if ( first . getKind ( ) != JavadocTokenKind . LESS ) { stream . rewind ( ) ; return ; } JavadocToken second = stream . nextToken ( ) ; if ( second . getKind ( ) != JavadocTokenKind . IDENTIFIER ) { stream . rewind ( ) ; return ; } JavadocToken third = stream . nextToken ( ) ; if ( third . getKind ( ) != JavadocTokenKind . GREATER ) { stream . rewind ( ) ; return ; } stream . discard ( ) ; IrDocText open = new IrDocText ( first . getText ( ) ) ; open . setLocation ( first . getLocation ( ) ) ; IrDocSimpleName name = new IrDocSimpleName ( second . getText ( ) ) ; name . setLocation ( second . getLocation ( ) ) ; IrDocText close = new IrDocText ( third . getText ( ) ) ; close . setLocation ( third . getLocation ( ) ) ; fragments . add ( open ) ; fragments . add ( name ) ; fragments . add ( close ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; public class JavadocParseException extends Exception { private static final long serialVersionUID = ; private IrLocation location ; public JavadocParseException ( String message , IrLocation location , Throwable cause ) { super ( message , cause ) ; this . location = location ; } public IrLocation getLocation ( ) { return this . location ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . io . IOException ; import java . io . StringReader ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . utils . java . internal . model . util . JavaEscape ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public class DefaultJavadocScanner implements JavadocScanner { private int index ; private List < JavadocToken > tokens ; private JavadocToken eof ; public DefaultJavadocScanner ( List < JavadocToken > tokens , int successorStartsAt ) { super ( ) ; this . index = ; this . tokens = tokens ; this . eof = eof ( successorStartsAt ) ; } public static DefaultJavadocScanner newInstance ( String text ) { if ( text == null ) { throw new IllegalArgumentException ( "" ) ; } JavadocTokenizer tokenizer = new JavadocTokenizer ( new StringReader ( text ) ) ; try { while ( tokenizer . yylex ( ) != - ) { } } catch ( IOException e ) { throw ( AssertionError ) new AssertionError ( tokenizer . getStore ( ) ) . initCause ( e ) ; } ArrayList < JavadocToken > list = new ArrayList < JavadocToken > ( tokenizer . getStore ( ) ) ; list . trimToSize ( ) ; return new DefaultJavadocScanner ( list , text . length ( ) ) ; } private static JavadocToken eof ( int offset ) { return new JavadocToken ( JavadocTokenKind . EOF , "" , offset ) ; } @ Override public List < JavadocToken > getTokens ( ) { return Collections . unmodifiableList ( tokens ) ; } @ Override public int getIndex ( ) { return this . index ; } @ Override public void seek ( int position ) { setIndex ( position ) ; } @ Override public void consume ( int count ) { if ( count < ) { throw new IllegalArgumentException ( ) ; } setIndex ( index + count ) ; } @ Override public JavadocToken nextToken ( ) { int position = lookahead0 ( ) ; JavadocToken token = token ( position ) ; setIndex ( position + ) ; return token ; } @ Override public JavadocToken lookahead ( int offset ) { int position = lookahead0 ( offset ) ; JavadocToken token = token ( position ) ; return token ; } private void setIndex ( int position ) { if ( position > tokens . size ( ) ) { index = tokens . size ( ) ; } else { index = position ; } } private int lookahead0 ( int i ) { int pos = index + i ; checkPositive ( index , i ) ; int size = tokens . size ( ) ; if ( pos >= size ) { return size ; } else { return pos ; } } private JavadocToken token ( int position ) { if ( position == tokens . size ( ) ) { return eof ; } else { return tokens . get ( position ) ; } } private void checkPositive ( int base , int offset ) { if ( base + offset < ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , tokens , base , offset >= ? '' : '' , offset ) ) ; } } @ Override public String toString ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( '' ) ; for ( int i = , n = Math . min ( index , tokens . size ( ) ) ; i < n ; i ++ ) { buf . append ( '' ) ; buf . append ( escape ( tokens . get ( i ) . getText ( ) ) ) ; buf . append ( '' ) ; buf . append ( "" ) ; } buf . append ( '>' ) ; for ( int i = index , n = tokens . size ( ) ; i < n ; i ++ ) { buf . append ( '' ) ; buf . append ( escape ( tokens . get ( i ) . getText ( ) ) ) ; buf . append ( '' ) ; buf . append ( "" ) ; } int len = buf . length ( ) ; if ( index != tokens . size ( ) && len >= ) { buf . delete ( len - , len ) ; } buf . append ( '' ) ; return buf . toString ( ) ; } private String escape ( String s ) { return JavaEscape . escape ( s , false , false ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . List ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; public class DefaultJavadocBlockParser extends JavadocBlockParser { public DefaultJavadocBlockParser ( ) { super ( ) ; } public DefaultJavadocBlockParser ( List < ? extends JavadocBlockParser > blockParsers ) { super ( blockParsers ) ; } @ Override public boolean canAccept ( String tag ) { return true ; } @ Override public IrDocBlock parse ( String tag , JavadocScanner scanner ) throws JavadocParseException { List < IrDocFragment > fragments = fetchRestFragments ( scanner ) ; return newBlock ( tag , fragments ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; public class IllegalDocCommentFormatException extends JavadocParseException { private static final long serialVersionUID = ; private boolean head ; public IllegalDocCommentFormatException ( boolean head , IrLocation location , Throwable cause ) { super ( buildMessage ( head ) , location , cause ) ; this . head = head ; } public boolean isMissingHead ( ) { return head ; } public boolean isMissingTail ( ) { return ! isMissingHead ( ) ; } private static String buildMessage ( boolean head ) { if ( head ) { return Messages . getString ( "" ) ; } else { return Messages . getString ( "" ) ; } } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocNamedType ; public class FollowsNamedTypeBlockParser extends AcceptableJavadocBlockParser { public FollowsNamedTypeBlockParser ( String ... tagNames ) { super ( tagNames ) ; } @ Override public IrDocBlock parse ( String tag , JavadocScanner scanner ) throws JavadocParseException { ArrayList < IrDocFragment > fragments = new ArrayList < IrDocFragment > ( ) ; IrDocNamedType namedType = fetchNamedType ( scanner ) ; if ( namedType != null ) { fragments . add ( namedType ) ; } fragments . addAll ( fetchRestFragments ( scanner ) ) ; fragments . trimToSize ( ) ; return newBlock ( tag , fragments ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import java . util . List ; public class JavadocParserBuilder { private boolean generated ; private List < JavadocBlockParser > inlines ; private List < JavadocBlockParser > toplevels ; public JavadocParserBuilder ( ) { super ( ) ; this . generated = false ; this . inlines = new ArrayList < JavadocBlockParser > ( ) ; this . toplevels = new ArrayList < JavadocBlockParser > ( ) ; } public synchronized void addSpecialInlineBlockParser ( JavadocBlockParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } if ( generated ) { throw new IllegalStateException ( ) ; } inlines . add ( parser ) ; } public synchronized void addSpecialStandAloneBlockParser ( JavadocBlockParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } if ( generated ) { throw new IllegalStateException ( ) ; } toplevels . add ( parser ) ; } public synchronized JavadocParser build ( ) { if ( generated ) { throw new IllegalStateException ( ) ; } generated = true ; inlines . add ( new DefaultJavadocBlockParser ( ) ) ; for ( JavadocBlockParser p : toplevels ) { p . setBlockParsers ( inlines ) ; } toplevels . add ( new DefaultJavadocBlockParser ( inlines ) ) ; JavadocParser parser = new JavadocParser ( toplevels ) ; return parser ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; public abstract class JavadocBaseParser { private List < ? extends JavadocBlockParser > blockParsers ; public JavadocBaseParser ( List < ? extends JavadocBlockParser > blockParsers ) { super ( ) ; setBlockParsers ( blockParsers ) ; } public final List < ? extends JavadocBlockParser > getBlockParsers ( ) { return this . blockParsers ; } public final void setBlockParsers ( List < ? extends JavadocBlockParser > blockParsers ) { if ( blockParsers == null ) { throw new IllegalArgumentException ( "" ) ; } this . blockParsers = Collections . unmodifiableList ( new ArrayList < JavadocBlockParser > ( blockParsers ) ) ; } public IrDocBlock parseBlock ( JavadocBlockInfo block ) throws JavadocParseException { if ( block == null ) { throw new IllegalArgumentException ( "" ) ; } String tag = block . getTagName ( ) ; for ( JavadocBlockParser parser : getBlockParsers ( ) ) { if ( parser . canAccept ( tag ) ) { IrDocBlock result = parser . parse ( tag , block . getBlockScanner ( ) ) ; result . setLocation ( block . getLocation ( ) ) ; return result ; } } throw new MissingJavadocBlockParserException ( tag , block . getLocation ( ) , null ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocType ; public class SerialFieldBlockParser extends AcceptableJavadocBlockParser { public SerialFieldBlockParser ( ) { super ( "" ) ; } public SerialFieldBlockParser ( String tagName , String ... tagNames ) { super ( tagName , tagNames ) ; } @ Override public IrDocBlock parse ( String tag , JavadocScanner scanner ) throws JavadocParseException { ArrayList < IrDocFragment > fragments = new ArrayList < IrDocFragment > ( ) ; IrDocSimpleName name = fetchSimpleName ( scanner ) ; if ( name != null ) { fragments . add ( name ) ; IrDocType type = fetchType ( scanner ) ; if ( type != null ) { fragments . add ( type ) ; } } fragments . addAll ( fetchRestFragments ( scanner ) ) ; fragments . trimToSize ( ) ; return newBlock ( tag , fragments ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import java . util . Collections ; import java . util . EnumSet ; import java . util . List ; import java . util . Set ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBasicType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocField ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethod ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocNamedType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocText ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public abstract class JavadocBlockParser extends JavadocBaseParser { private static final Set < JavadocTokenKind > S_FOLLOW ; static { Set < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; set . add ( JavadocTokenKind . WHITE_SPACES ) ; set . add ( JavadocTokenKind . LINE_BREAK ) ; set . add ( JavadocTokenKind . EOF ) ; S_FOLLOW = Collections . unmodifiableSet ( set ) ; } protected JavadocBlockParser ( ) { this ( Collections . < JavadocBlockParser > emptyList ( ) ) ; } protected JavadocBlockParser ( List < ? extends JavadocBlockParser > blockParsers ) { super ( blockParsers ) ; } public abstract boolean canAccept ( String tag ) ; public abstract IrDocBlock parse ( String tag , JavadocScanner scanner ) throws JavadocParseException ; public IrDocBlock newBlock ( String tag , List < ? extends IrDocFragment > fragments ) { if ( fragments == null ) { throw new IllegalArgumentException ( "" ) ; } IrDocBlock block = new IrDocBlock ( ) ; block . setTag ( tag ) ; block . setFragments ( fragments ) ; return block ; } public List < IrDocFragment > fetchRestFragments ( JavadocScanner scanner ) throws JavadocParseException { int index = scanner . getIndex ( ) ; try { ArrayList < IrDocFragment > fragments = new ArrayList < IrDocFragment > ( ) ; while ( true ) { JavadocTokenKind la = scanner . lookahead ( ) . getKind ( ) ; if ( la == JavadocTokenKind . LINE_BREAK ) { int count = JavadocScannerUtil . countUntilNextPrintable ( scanner , ) ; scanner . consume ( count ) ; } else if ( la == JavadocTokenKind . LEFT_BRACE ) { JavadocBlockInfo info = JavadocBlockParserUtil . fetchBlockInfo ( scanner ) ; IrDocBlock inline = parseBlock ( info ) ; fragments . add ( inline ) ; } else if ( la == JavadocTokenKind . EOF ) { break ; } else { IrDocText text = JavadocBlockParserUtil . fetchText ( scanner , false , false ) ; fragments . add ( text ) ; } } fragments . trimToSize ( ) ; return fragments ; } catch ( JavadocParseException e ) { scanner . seek ( index ) ; throw e ; } } public IrDocSimpleName fetchSimpleName ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchSimpleName ( scanner , S_FOLLOW ) ; } public IrDocName fetchName ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchName ( scanner , S_FOLLOW ) ; } public IrDocBasicType fetchBasicType ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchBasicType ( scanner , S_FOLLOW ) ; } public IrDocBasicType fetchPrimitiveType ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchPrimitiveType ( scanner , S_FOLLOW ) ; } public IrDocNamedType fetchNamedType ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchNamedType ( scanner , S_FOLLOW ) ; } public IrDocType fetchType ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchType ( scanner , S_FOLLOW ) ; } public IrDocField fetchField ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchField ( scanner , S_FOLLOW ) ; } public IrDocMethod fetchMethod ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchMethod ( scanner , S_FOLLOW ) ; } public IrDocFragment fetchLinkTarget ( JavadocScanner scanner ) { return JavadocBlockParserUtil . fetchLinkTarget ( scanner , S_FOLLOW ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public final class JavadocScannerUtil { private static final Set < JavadocTokenKind > S_LINE_BREAK = Collections . singleton ( JavadocTokenKind . LINE_BREAK ) ; private static final Set < JavadocTokenKind > S_WHITE_SPACES = Collections . singleton ( JavadocTokenKind . WHITE_SPACES ) ; private static final Set < JavadocTokenKind > S_ASTERISK = Collections . singleton ( JavadocTokenKind . ASTERISK ) ; private static final Set < JavadocTokenKind > S_RIGHT_BRACE = Collections . singleton ( JavadocTokenKind . RIGHT_BRACE ) ; private JavadocScannerUtil ( ) { return ; } public static List < JavadocToken > lookaheadTokens ( JavadocScanner scanner , int start , int count ) { if ( count < ) { throw new IllegalArgumentException ( ) ; } List < JavadocToken > tokens = new ArrayList < JavadocToken > ( count ) ; for ( int i = ; i < count ; i ++ ) { JavadocToken token = scanner . lookahead ( start + i ) ; if ( token . getKind ( ) == JavadocTokenKind . EOF ) { break ; } tokens . add ( token ) ; } return tokens ; } public static int countWhile ( Collection < JavadocTokenKind > kinds , JavadocScanner scanner , int start ) { return countWhileUntil ( kinds , scanner , start , false ) ; } public static int countUntil ( Collection < JavadocTokenKind > kinds , JavadocScanner scanner , int start ) { return countWhileUntil ( kinds , scanner , start , true ) ; } public static int countUntilBlockEnd ( JavadocScanner scanner , int start ) { int offset = ; while ( true ) { JavadocTokenKind kind = scanner . lookahead ( start + offset ) . getKind ( ) ; if ( kind == JavadocTokenKind . LEFT_BRACE ) { offset ++ ; JavadocTokenKind la = scanner . lookahead ( start + offset ) . getKind ( ) ; if ( la == JavadocTokenKind . AT ) { offset ++ ; offset += countUntil ( S_RIGHT_BRACE , scanner , start + offset ) ; } } else if ( kind == JavadocTokenKind . LINE_BREAK ) { offset += countUntilNextPrintable ( scanner , start + offset ) ; JavadocTokenKind la = scanner . lookahead ( start + offset ) . getKind ( ) ; if ( la == JavadocTokenKind . AT ) { return offset ; } } else if ( kind == JavadocTokenKind . EOF ) { return offset ; } else { offset ++ ; } } } public static int countUntilCommentEnd ( JavadocScanner scanner , boolean returnMinusIfMissing , int start ) { JavadocToken token = scanner . lookahead ( start ) ; if ( token . getKind ( ) == JavadocTokenKind . EOF ) { return ( returnMinusIfMissing ? - : ) ; } int offset = ; boolean sawAster = ( token . getKind ( ) == JavadocTokenKind . ASTERISK ) ; while ( true ) { JavadocToken la = scanner . lookahead ( start + offset ) ; JavadocTokenKind kind = la . getKind ( ) ; if ( kind == JavadocTokenKind . EOF ) { return ( returnMinusIfMissing ? - : offset ) ; } else if ( sawAster && kind == JavadocTokenKind . SLASH ) { offset -- ; return offset ; } else if ( kind == JavadocTokenKind . ASTERISK ) { sawAster = true ; offset ++ ; } else { sawAster = false ; offset ++ ; } } } private static int countWhileUntil ( Collection < JavadocTokenKind > kinds , JavadocScanner scanner , int start , boolean breakOnFound ) { int offset = ; while ( true ) { JavadocToken token = scanner . lookahead ( start + offset ) ; JavadocTokenKind kind = token . getKind ( ) ; if ( kind == JavadocTokenKind . EOF || kinds . contains ( kind ) == breakOnFound ) { return offset ; } else { offset ++ ; } } } public static int countUntilNextPrintable ( JavadocScanner scanner , int start ) { int offset = ; while ( true ) { offset += countWhile ( S_WHITE_SPACES , scanner , start + offset ) ; JavadocToken token = scanner . lookahead ( start + offset ) ; JavadocTokenKind kind = token . getKind ( ) ; if ( kind == JavadocTokenKind . EOF ) { return offset ; } else if ( kind != JavadocTokenKind . LINE_BREAK ) { return offset ; } offset += countUntilNextLineStart ( scanner , start + offset ) ; } } public static int countUntilNextLineStart ( JavadocScanner scanner , int start ) { int offset = ; offset += countUntil ( S_LINE_BREAK , scanner , start + offset ) ; JavadocToken token = scanner . lookahead ( start + offset ) ; if ( token . getKind ( ) == JavadocTokenKind . EOF ) { return offset ; } else { offset ++ ; } offset += countWhile ( S_WHITE_SPACES , scanner , start + offset ) ; offset += countWhile ( S_ASTERISK , scanner , start + offset ) ; return offset ; } public static int consumeLineEnd ( JavadocScanner scanner , boolean multiline ) { int consumed = ; do { int offset = countUntilNextLineStart ( scanner , ) ; if ( offset == ) { break ; } else { scanner . consume ( offset ) ; consumed ++ ; } int ws = countUntil ( S_WHITE_SPACES , scanner , ) ; if ( ws != ) { scanner . consume ( ws ) ; } } while ( multiline ) ; return consumed ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . ArrayList ; import java . util . List ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrBasicTypeKind ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocArrayType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBasicType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocComment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElementVisitor ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocField ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethod ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethodParameter ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocNamedType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocQualifiedName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocText ; import com . asakusafw . utils . java . model . syntax . BasicTypeKind ; import com . asakusafw . utils . java . model . syntax . DocBlock ; import com . asakusafw . utils . java . model . syntax . DocElement ; import com . asakusafw . utils . java . model . syntax . DocMethodParameter ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; public class JavadocConverter { private final ModelFactory factory ; private final JavadocParser parser ; public JavadocConverter ( ModelFactory factory ) { super ( ) ; this . factory = factory ; JavadocParserBuilder builder = new JavadocParserBuilder ( ) ; builder . addSpecialStandAloneBlockParser ( new FollowsNamedTypeBlockParser ( "" , "" ) ) ; builder . addSpecialStandAloneBlockParser ( new FollowsReferenceBlockParser ( "" ) ) ; builder . addSpecialStandAloneBlockParser ( new ParamBlockParser ( "" ) ) ; builder . addSpecialStandAloneBlockParser ( new SerialFieldBlockParser ( "" ) ) ; builder . addSpecialInlineBlockParser ( new FollowsReferenceBlockParser ( "" , "" ) ) ; this . parser = builder . build ( ) ; } public Javadoc convert ( String content , int offset ) throws JavadocParseException { if ( content == null ) { throw new IllegalArgumentException ( "" ) ; } JavadocScanner scanner = DefaultJavadocScanner . newInstance ( content ) ; IrDocComment ir = parser . parse ( scanner ) ; return convert ( ir , offset ) ; } private Javadoc convert ( IrDocComment comment , int offset ) { assert comment != null ; Mapper mapper = new Mapper ( factory , offset ) ; List < DocBlock > blocks = new ArrayList < DocBlock > ( ) ; for ( IrDocBlock block : comment . getBlocks ( ) ) { blocks . add ( ( DocBlock ) block . accept ( mapper , null ) ) ; } return factory . newJavadoc ( blocks ) ; } private static class Mapper extends IrDocElementVisitor < DocElement , Void > { final ModelFactory factory ; private final TypeMapper types ; Mapper ( ModelFactory factory , int offset ) { assert factory != null ; this . factory = factory ; this . types = new TypeMapper ( ) ; } @ Override public DocElement visitBlock ( IrDocBlock elem , Void _ ) { String tag = elem . getTag ( ) ; List < DocElement > elements = new ArrayList < DocElement > ( ) ; for ( IrDocFragment f : elem . getFragments ( ) ) { elements . add ( f . accept ( this , null ) ) ; } return factory . newDocBlock ( tag == null ? "" : tag , elements ) ; } @ Override public DocElement visitText ( IrDocText elem , Void _ ) { return factory . newDocText ( elem . getContent ( ) ) ; } @ Override public DocElement visitSimpleName ( IrDocSimpleName elem , Void _ ) { return factory . newSimpleName ( elem . getIdentifier ( ) ) ; } @ Override public DocElement visitQualifiedName ( IrDocQualifiedName elem , Void _ ) { Name qualifier = ( Name ) elem . getQualifier ( ) . accept ( this , null ) ; SimpleName simple = ( SimpleName ) elem . getName ( ) . accept ( this , null ) ; return factory . newQualifiedName ( qualifier , simple ) ; } @ Override public DocElement visitField ( IrDocField elem , Void _ ) { Type type = declaring ( elem . getDeclaringType ( ) ) ; SimpleName name = ( SimpleName ) elem . getName ( ) . accept ( this , null ) ; return factory . newDocField ( type , name ) ; } @ Override public DocElement visitMethod ( IrDocMethod elem , Void _ ) { Type type = declaring ( elem . getDeclaringType ( ) ) ; SimpleName name = ( SimpleName ) elem . getName ( ) . accept ( this , null ) ; List < DocMethodParameter > params = new ArrayList < DocMethodParameter > ( ) ; for ( IrDocMethodParameter p : elem . getParameters ( ) ) { params . add ( convert ( p ) ) ; } return factory . newDocMethod ( type , name , params ) ; } private DocMethodParameter convert ( IrDocMethodParameter elem ) { Type type = elem . getType ( ) . accept ( types , this ) ; SimpleName name ; if ( elem . getName ( ) != null ) { name = ( SimpleName ) elem . getName ( ) . accept ( this , null ) ; } else { name = null ; } return factory . newDocMethodParameter ( type , name , elem . isVariableArity ( ) ) ; } @ Override public DocElement visitNamedType ( IrDocNamedType elem , Void _ ) { Name name = ( Name ) elem . getName ( ) . accept ( this , null ) ; return factory . newNamedType ( name ) ; } private NamedType declaring ( IrDocNamedType declaringType ) { if ( declaringType == null ) { return null ; } return ( NamedType ) visitNamedType ( declaringType , null ) ; } } private static class TypeMapper extends IrDocElementVisitor < Type , Mapper > { TypeMapper ( ) { return ; } @ Override public Type visitArrayType ( IrDocArrayType elem , Mapper context ) { Type component = elem . getComponentType ( ) . accept ( this , context ) ; return context . factory . newArrayType ( component ) ; } @ Override public Type visitBasicType ( IrDocBasicType elem , Mapper context ) { BasicTypeKind kind = convert ( elem . getTypeKind ( ) ) ; return context . factory . newBasicType ( kind ) ; } @ Override public Type visitNamedType ( IrDocNamedType elem , Mapper context ) { Name name = ( Name ) elem . getName ( ) . accept ( context , null ) ; return context . factory . newNamedType ( name ) ; } private static BasicTypeKind convert ( IrBasicTypeKind kind ) { switch ( kind ) { case BOOLEAN : return BasicTypeKind . BOOLEAN ; case BYTE : return BasicTypeKind . BYTE ; case CHAR : return BasicTypeKind . CHAR ; case DOUBLE : return BasicTypeKind . DOUBLE ; case FLOAT : return BasicTypeKind . FLOAT ; case INT : return BasicTypeKind . INT ; case LONG : return BasicTypeKind . LONG ; case SHORT : return BasicTypeKind . SHORT ; case VOID : return BasicTypeKind . VOID ; default : throw new AssertionError ( kind ) ; } } } } package com . asakusafw . utils . java . parser . javadoc ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . EnumSet ; import java . util . List ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBlock ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocComment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public final class JavadocParser extends JavadocBaseParser { public JavadocParser ( List < ? extends JavadocBlockParser > blockParsers ) { super ( blockParsers ) ; } public IrDocComment parse ( JavadocScanner scanner ) throws JavadocParseException { if ( scanner == null ) { throw new IllegalArgumentException ( "" ) ; } int index = scanner . getIndex ( ) ; try { JavadocInfo info = fetchJavadocInfo ( scanner ) ; List < IrDocBlock > blocks = new ArrayList < IrDocBlock > ( info . getBlocks ( ) . size ( ) ) ; for ( JavadocBlockInfo b : info . getBlocks ( ) ) { IrDocBlock block = parseBlock ( b ) ; blocks . add ( block ) ; } IrDocComment elem = new IrDocComment ( ) ; elem . setBlocks ( blocks ) ; elem . setLocation ( info . getLocation ( ) ) ; return elem ; } catch ( JavadocParseException e ) { scanner . seek ( index ) ; throw e ; } } public IrDocBlock parseBlock ( JavadocScanner scanner ) throws JavadocParseException { if ( scanner == null ) { throw new IllegalArgumentException ( "" ) ; } int eoc = JavadocScannerUtil . countUntilCommentEnd ( scanner , true , ) ; if ( eoc >= ) { throw new IllegalEndOfCommentException ( scanner . lookahead ( ) . getLocation ( ) , null ) ; } JavadocTokenKind kind = scanner . lookahead ( ) . getKind ( ) ; int index = scanner . getIndex ( ) ; try { JavadocBlockInfo info ; if ( kind == JavadocTokenKind . AT ) { info = fetchStandAloneBlock ( scanner , scanner . getTokens ( ) ) ; } else { info = fetchSynopsisBlock ( scanner ) ; } if ( info == null ) { throw new IllegalArgumentException ( "" ) ; } return parseBlock ( info ) ; } catch ( JavadocParseException e ) { scanner . seek ( index ) ; throw e ; } } private static JavadocInfo fetchJavadocInfo ( JavadocScanner scanner ) throws IllegalDocCommentFormatException { int offset = ; IrLocation firstLocation = scanner . lookahead ( ) . getLocation ( ) ; if ( ! hasJavadocHead ( scanner , offset ) ) { throw new IllegalDocCommentFormatException ( true , scanner . lookahead ( ) . getLocation ( ) , null ) ; } offset += ; if ( scanner . lookahead ( offset ) . getKind ( ) == JavadocTokenKind . SLASH ) { throw new IllegalDocCommentFormatException ( true , scanner . lookahead ( ) . getLocation ( ) , null ) ; } int bodyStart = offset ; offset += JavadocScannerUtil . countUntilCommentEnd ( scanner , false , offset ) ; int bodyEnd = offset ; if ( ! hasJavadocTail ( scanner , offset ) ) { throw new IllegalDocCommentFormatException ( false , scanner . lookahead ( ) . getLocation ( ) , null ) ; } IrLocation lastLocation = scanner . lookahead ( offset + ) . getLocation ( ) ; int base = scanner . getIndex ( ) ; JavadocScanner bodyScanner = new DefaultJavadocScanner ( scanner . getTokens ( ) . subList ( base + bodyStart , base + bodyEnd ) , scanner . lookahead ( offset ) . getStartPosition ( ) ) ; List < JavadocBlockInfo > blockScanners = splitBlocks ( bodyScanner ) ; int locStart = firstLocation . getStartPosition ( ) ; int locEnd = lastLocation . getStartPosition ( ) + lastLocation . getLength ( ) ; IrLocation location = new IrLocation ( locStart , locEnd - locStart ) ; scanner . consume ( offset ) ; return new JavadocInfo ( location , blockScanners ) ; } private static List < JavadocBlockInfo > splitBlocks ( JavadocScanner scanner ) { List < JavadocBlockInfo > blocks = new ArrayList < JavadocBlockInfo > ( ) ; JavadocBlockInfo synopsis = fetchSynopsisBlock ( scanner ) ; if ( synopsis != null ) { blocks . add ( synopsis ) ; } List < JavadocToken > tokens = scanner . getTokens ( ) ; while ( true ) { JavadocBlockInfo info = fetchStandAloneBlock ( scanner , tokens ) ; if ( info == null ) { break ; } blocks . add ( info ) ; } return blocks ; } private static JavadocBlockInfo fetchStandAloneBlock ( JavadocScanner scanner , List < JavadocToken > tokens ) { JavadocToken first = scanner . lookahead ( ) ; JavadocTokenKind kind = first . getKind ( ) ; if ( kind == JavadocTokenKind . EOF ) { return null ; } if ( kind != JavadocTokenKind . AT ) { throw new AssertionError ( MessageFormat . format ( "" , first , first . getKind ( ) , first . getLocation ( ) ) ) ; } scanner . consume ( ) ; int tagCount = JavadocBlockParserUtil . countWhileTagName ( scanner , ) ; List < JavadocToken > tagNames = new ArrayList < JavadocToken > ( tagCount ) ; for ( int i = ; i < tagCount ; i ++ ) { tagNames . add ( scanner . nextToken ( ) ) ; } String tagName = JavadocBlockParserUtil . buildString ( tagNames ) ; int bodyStart = scanner . getIndex ( ) ; int count = JavadocScannerUtil . countUntilBlockEnd ( scanner , ) ; int success = scanner . lookahead ( count ) . getStartPosition ( ) ; DefaultJavadocScanner bs = new DefaultJavadocScanner ( new ArrayList < JavadocToken > ( tokens . subList ( bodyStart , bodyStart + count ) ) , success ) ; int init = first . getStartPosition ( ) ; IrLocation location = new IrLocation ( init , success - init ) ; JavadocBlockInfo info = new JavadocBlockInfo ( tagName , bs , location ) ; scanner . consume ( count ) ; return info ; } private static JavadocBlockInfo fetchSynopsisBlock ( JavadocScanner scanner ) { int start = scanner . getIndex ( ) ; List < JavadocToken > tokens = scanner . getTokens ( ) ; int offset = ; offset += JavadocScannerUtil . countWhile ( EnumSet . of ( JavadocTokenKind . ASTERISK ) , scanner , offset ) ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; JavadocTokenKind kind = scanner . lookahead ( offset ) . getKind ( ) ; if ( kind == JavadocTokenKind . AT || kind == JavadocTokenKind . EOF ) { scanner . consume ( offset ) ; return null ; } else { int count = JavadocScannerUtil . countUntilBlockEnd ( scanner , offset ) ; int success = scanner . lookahead ( offset + count ) . getStartPosition ( ) ; DefaultJavadocScanner bs = new DefaultJavadocScanner ( new ArrayList < JavadocToken > ( tokens . subList ( start + offset , start + offset + count ) ) , success ) ; JavadocToken first = scanner . lookahead ( offset ) ; int init = first . getStartPosition ( ) ; IrLocation location = new IrLocation ( init , success - init ) ; JavadocBlockInfo info = new JavadocBlockInfo ( null , bs , location ) ; scanner . consume ( offset + count ) ; return info ; } } private static boolean hasJavadocHead ( JavadocScanner scanner , int start ) { if ( scanner . lookahead ( start + ) . getKind ( ) != JavadocTokenKind . SLASH ) { return false ; } if ( scanner . lookahead ( start + ) . getKind ( ) != JavadocTokenKind . ASTERISK ) { return false ; } if ( scanner . lookahead ( start + ) . getKind ( ) != JavadocTokenKind . ASTERISK ) { return false ; } return true ; } private static boolean hasJavadocTail ( JavadocScanner scanner , int start ) { if ( scanner . lookahead ( start + ) . getKind ( ) != JavadocTokenKind . ASTERISK ) { return false ; } if ( scanner . lookahead ( start + ) . getKind ( ) != JavadocTokenKind . SLASH ) { return false ; } return true ; } private static class JavadocInfo { private final IrLocation location ; private final List < JavadocBlockInfo > blockScanners ; JavadocInfo ( IrLocation location , List < JavadocBlockInfo > blockScanners ) { super ( ) ; this . location = location ; this . blockScanners = blockScanners ; } public IrLocation getLocation ( ) { return this . location ; } public List < JavadocBlockInfo > getBlocks ( ) { return this . blockScanners ; } } } package com . asakusafw . utils . java . parser . javadoc ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; public class IllegalEndOfCommentException extends JavadocParseException { private static final long serialVersionUID = ; public IllegalEndOfCommentException ( IrLocation location , Throwable cause ) { super ( buildMessage ( ) , location , cause ) ; } private static String buildMessage ( ) { return "" ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; final class Messages { private static final String BUNDLE_NAME = "" ; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle . getBundle ( BUNDLE_NAME ) ; private Messages ( ) { super ( ) ; } static String getString ( String key ) { try { return RESOURCE_BUNDLE . getString ( key ) ; } catch ( MissingResourceException e ) { return '' + key + '' ; } } } package com . asakusafw . utils . java . parser . javadoc ; import java . text . MessageFormat ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; public class JavadocBlockInfo { private IrLocation location ; private String tagName ; private JavadocScanner blockScanner ; JavadocBlockInfo ( String tagName , JavadocScanner blockScanner , IrLocation location ) { super ( ) ; this . tagName = tagName ; this . blockScanner = blockScanner ; this . location = location ; } public IrLocation getLocation ( ) { return this . location ; } public String getTagName ( ) { return this . tagName ; } public JavadocScanner getBlockScanner ( ) { return this . blockScanner ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getTagName ( ) , getBlockScanner ( ) , getLocation ( ) ) ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . text . MessageFormat ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; public class MissingJavadocBlockParserException extends JavadocParseException { private static final long serialVersionUID = ; private final String tagName ; public MissingJavadocBlockParserException ( String tagName , IrLocation location , Throwable cause ) { super ( buildMessage ( tagName ) , location , cause ) ; this . tagName = tagName ; } private static String buildMessage ( String tag ) { String blockName = ( tag == null ? Messages . getString ( "" ) : tag ) ; return MessageFormat . format ( Messages . getString ( "" ) , blockName ) ; } public String getTagName ( ) { return this . tagName ; } } package com . asakusafw . utils . java . parser . javadoc ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; public interface JavadocTokenStream { JavadocToken nextToken ( ) ; JavadocToken peek ( ) ; JavadocToken lookahead ( int k ) ; void mark ( ) ; void rewind ( ) ; void discard ( ) ; } package com . asakusafw . utils . java . parser . javadoc ; package com . asakusafw . utils . java . parser . javadoc ; import java . util . List ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; public interface JavadocScanner { List < JavadocToken > getTokens ( ) ; void consume ( int count ) ; JavadocToken nextToken ( ) ; JavadocToken lookahead ( int offset ) ; int getIndex ( ) ; void seek ( int position ) ; } package com . asakusafw . utils . java . parser . javadoc ; import static com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind . * ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . EnumSet ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrBasicTypeKind ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocArrayType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocBasicType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocElement ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocField ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocFragment ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethod ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocMethodParameter ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocNamedType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocQualifiedName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocSimpleName ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocText ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrDocType ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . IrLocation ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public final class JavadocBlockParserUtil { public static final Set < JavadocTokenKind > S_WHITE ; static { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; set . add ( WHITE_SPACES ) ; set . add ( LINE_BREAK ) ; set . add ( EOF ) ; S_WHITE = Collections . unmodifiableSet ( set ) ; } private static final Set < JavadocTokenKind > S_TEXT_DELIM ; static { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; set . add ( LINE_BREAK ) ; set . add ( LEFT_BRACE ) ; S_TEXT_DELIM = Collections . unmodifiableSet ( set ) ; } private static final Set < JavadocTokenKind > S_TAG_NAME_DELIM ; static { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; set . add ( WHITE_SPACES ) ; set . add ( LINE_BREAK ) ; set . add ( AT ) ; set . add ( RIGHT_BRACE ) ; S_TAG_NAME_DELIM = Collections . unmodifiableSet ( set ) ; } private static final Set < JavadocTokenKind > S_INLINE_BLOCK_DELIM ; static { EnumSet < JavadocTokenKind > set = EnumSet . noneOf ( JavadocTokenKind . class ) ; set . add ( LEFT_BRACE ) ; set . add ( RIGHT_BRACE ) ; S_INLINE_BLOCK_DELIM = Collections . unmodifiableSet ( set ) ; } private static final Map < String , IrBasicTypeKind > BASIC_TYPE_NAMES ; static { Map < String , IrBasicTypeKind > map = new HashMap < String , IrBasicTypeKind > ( ) ; for ( IrBasicTypeKind k : IrBasicTypeKind . values ( ) ) { map . put ( k . getSymbol ( ) . intern ( ) , k ) ; } BASIC_TYPE_NAMES = Collections . unmodifiableMap ( map ) ; } private JavadocBlockParserUtil ( ) { return ; } public static < T extends IrDocElement > T setLocation ( T elem , JavadocToken start , JavadocToken stop ) { int s = start . getStartPosition ( ) ; int e = stop . getStartPosition ( ) + stop . getText ( ) . length ( ) ; IrLocation location = new IrLocation ( s , e - s ) ; elem . setLocation ( location ) ; return elem ; } public static < T extends IrDocElement > T setLocation ( T elem , IrLocation start , IrLocation stop ) { if ( start == null || stop == null ) { return elem ; } int s = start . getStartPosition ( ) ; int e = stop . getStartPosition ( ) + stop . getLength ( ) ; IrLocation location = new IrLocation ( s , e - s ) ; elem . setLocation ( location ) ; return elem ; } public static IrDocText fetchText ( JavadocScanner scanner , boolean trimHead , boolean trimTail ) { if ( scanner == null ) { throw new IllegalArgumentException ( "" ) ; } int offset = ; while ( true ) { offset += JavadocScannerUtil . countUntil ( S_TEXT_DELIM , scanner , offset ) ; JavadocTokenKind kind = scanner . lookahead ( offset ) . getKind ( ) ; if ( kind == LEFT_BRACE ) { JavadocToken la = scanner . lookahead ( offset + ) ; if ( la . getKind ( ) == JavadocTokenKind . AT ) { break ; } offset ++ ; } else { break ; } } return consumeAsText ( scanner , offset , trimHead , trimTail ) ; } public static JavadocBlockInfo fetchBlockInfo ( JavadocScanner scanner ) { if ( scanner == null ) { throw new IllegalArgumentException ( "" ) ; } int offset = ; offset += JavadocScannerUtil . countUntilNextPrintable ( scanner , offset ) ; JavadocToken head = scanner . lookahead ( offset ) ; if ( head . getKind ( ) != LEFT_BRACE ) { return null ; } offset ++ ; JavadocToken at = scanner . lookahead ( offset ) ; if ( at . getKind ( ) != AT ) { return null ; } offset ++ ; int nameCount = countWhileTagName ( scanner , offset ) ; String tagName = buildString ( JavadocScannerUtil . lookaheadTokens ( scanner , offset , nameCount ) ) ; offset += nameCount ; int blockEnd = JavadocScannerUtil . countUntil ( S_INLINE_BLOCK_DELIM , scanner , offset ) ; JavadocToken token = scanner . lookahead ( offset + blockEnd ) ; JavadocTokenKind kind = token . getKind ( ) ; if ( kind == LEFT_BRACE ) { blockEnd = ; } boolean legalBlock = ( kind == JavadocTokenKind . RIGHT_BRACE ) ; JavadocToken tail = scanner . lookahead ( offset + blockEnd ) ; int startIndex = scanner . getIndex ( ) + offset ; int stopIndex = startIndex + blockEnd ; int startPos = head . getStartPosition ( ) ; int endPos = tail . getStartPosition ( ) ; if ( legalBlock ) { endPos += tail . getText ( ) . length ( ) ; } IrLocation blockLocation = new IrLocation ( startPos , endPos - startPos ) ; DefaultJavadocScanner blockScanner = new DefaultJavadocScanner ( new ArrayList < JavadocToken > ( scanner . getTokens ( ) . subList ( startIndex , stopIndex ) ) , endPos ) ; scanner . consume ( offset + blockEnd ) ; if ( legalBlock ) { scanner . consume ( ) ; } return new JavadocBlockInfo ( tagName , blockScanner , blockLocation ) ; } public static int countWhileTagName ( JavadocScanner scanner , int start ) { return JavadocScannerUtil . countUntil ( S_TAG_NAME_DELIM , scanner , start ) ; } public static IrDocSimpleName fetchSimpleName ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { DefaultJavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; IrDocSimpleName elem = fetchSimpleName ( stream ) ; if ( elem == null ) { return null ; } if ( ! follows ( stream , follow ) ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; return elem ; } } public static IrDocName fetchName ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { DefaultJavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; IrDocName elem = fetchName ( stream ) ; if ( elem == null ) { return null ; } if ( ! follows ( stream , follow ) ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; return elem ; } } public static IrDocBasicType fetchBasicType ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { JavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; IrDocBasicType elem = fetchBasicType ( stream ) ; if ( ! follows ( stream , follow ) ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; return elem ; } } public static IrDocBasicType fetchPrimitiveType ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { JavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; IrDocBasicType elem = fetchBasicType ( stream ) ; if ( elem . getTypeKind ( ) == IrBasicTypeKind . VOID ) { stream . rewind ( ) ; return null ; } if ( ! follows ( stream , follow ) ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; return elem ; } } public static IrDocNamedType fetchNamedType ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { JavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; IrDocNamedType elem = fetchNamedType ( stream ) ; if ( ! follows ( stream , follow ) ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; return elem ; } } public static IrDocType fetchType ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { JavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; IrDocType elem = fetchType ( stream ) ; if ( ! follows ( stream , follow ) ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; return elem ; } } public static IrDocField fetchField ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { JavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; IrDocField elem = fetchField ( stream ) ; if ( ! follows ( stream , follow ) ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; return elem ; } } public static IrDocMethod fetchMethod ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { JavadocTokenStream stream = new DefaultJavadocTokenStream ( scanner ) ; stream . mark ( ) ; IrDocMethod elem = fetchMethod ( stream ) ; if ( ! follows ( stream , follow ) ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; return elem ; } } public static IrDocFragment fetchLinkTarget ( JavadocScanner scanner , Set < JavadocTokenKind > follow ) { IrDocMethod method = fetchMethod ( scanner , follow ) ; if ( method != null ) { return method ; } IrDocField field = fetchField ( scanner , follow ) ; if ( field != null ) { return field ; } IrDocNamedType type = fetchNamedType ( scanner , follow ) ; if ( type != null ) { return type ; } return null ; } private static IrDocMethod fetchMethod ( JavadocTokenStream stream ) { stream . mark ( ) ; IrDocField field = fetchField ( stream ) ; if ( field == null ) { stream . rewind ( ) ; return null ; } if ( consumeIfMatch ( stream , LEFT_PAREN ) == null ) { stream . rewind ( ) ; return null ; } JavadocToken delim ; List < IrDocMethodParameter > parameters ; IrDocMethodParameter first = fetchMethodParameter ( stream ) ; if ( first == null ) { delim = consumeIfMatch ( stream , RIGHT_PAREN ) ; if ( delim == null ) { stream . rewind ( ) ; return null ; } parameters = Collections . emptyList ( ) ; } else { parameters = new ArrayList < IrDocMethodParameter > ( ) ; parameters . add ( first ) ; while ( true ) { delim = stream . nextToken ( ) ; if ( delim . getKind ( ) == RIGHT_PAREN ) { break ; } else if ( delim . getKind ( ) == COMMA ) { IrDocMethodParameter p = fetchMethodParameter ( stream ) ; if ( p == null ) { stream . rewind ( ) ; return null ; } parameters . add ( p ) ; } else { stream . rewind ( ) ; return null ; } } } stream . discard ( ) ; IrDocMethod elem = new IrDocMethod ( ) ; elem . setDeclaringType ( field . getDeclaringType ( ) ) ; elem . setName ( field . getName ( ) ) ; elem . setParameters ( parameters ) ; setLocation ( elem , field . getLocation ( ) , delim . getLocation ( ) ) ; return elem ; } private static IrDocMethodParameter fetchMethodParameter ( JavadocTokenStream stream ) { stream . mark ( ) ; IrDocType type = fetchType ( stream ) ; if ( type == null ) { stream . rewind ( ) ; return null ; } else { stream . discard ( ) ; } IrLocation delim = type . getLocation ( ) ; boolean varargs ; if ( consumeIfMatch ( stream , DOT ) != null ) { if ( ( stream . lookahead ( ) . getKind ( ) != DOT ) || ( stream . lookahead ( ) . getKind ( ) != DOT ) ) { stream . rewind ( ) ; return null ; } stream . nextToken ( ) ; JavadocToken lastDot = stream . nextToken ( ) ; delim = lastDot . getLocation ( ) ; varargs = true ; } else { varargs = false ; } IrDocSimpleName name = fetchSimpleName ( stream ) ; if ( name != null ) { delim = name . getLocation ( ) ; } IrDocMethodParameter elem = new IrDocMethodParameter ( ) ; elem . setType ( type ) ; elem . setVariableArity ( varargs ) ; elem . setName ( name ) ; setLocation ( elem , type . getLocation ( ) , delim ) ; return elem ; } private static IrDocField fetchField ( JavadocTokenStream stream ) { stream . mark ( ) ; IrDocNamedType decl = fetchNamedType ( stream ) ; JavadocToken sharp = consumeIfMatch ( stream , SHARP ) ; if ( sharp == null ) { stream . rewind ( ) ; return null ; } IrDocSimpleName name = fetchSimpleName ( stream ) ; if ( name == null ) { stream . rewind ( ) ; return null ; } IrDocField elem = new IrDocField ( ) ; elem . setDeclaringType ( decl ) ; elem . setName ( name ) ; setLocation ( elem , decl == null ? sharp . getLocation ( ) : decl . getLocation ( ) , name . getLocation ( ) ) ; return elem ; } private static IrDocNamedType fetchNamedType ( JavadocTokenStream stream ) { IrDocName name = fetchName ( stream ) ; if ( name == null ) { return null ; } IrDocNamedType elem = new IrDocNamedType ( name ) ; setLocation ( elem , name . getLocation ( ) , name . getLocation ( ) ) ; return elem ; } private static IrDocType fetchType ( JavadocTokenStream stream ) { stream . mark ( ) ; IrDocType elem = fetchBasicType ( stream ) ; if ( elem == null ) { IrDocName name = fetchName ( stream ) ; if ( name == null ) { stream . rewind ( ) ; return null ; } elem = new IrDocNamedType ( name ) ; elem . setLocation ( name . getLocation ( ) ) ; } while ( true ) { stream . mark ( ) ; if ( consumeIfMatch ( stream , JavadocTokenKind . LEFT_BRACKET ) == null ) { stream . rewind ( ) ; break ; } JavadocToken stop = consumeIfMatch ( stream , JavadocTokenKind . RIGHT_BRACKET ) ; if ( stop == null ) { stream . rewind ( ) ; break ; } else { stream . discard ( ) ; IrDocArrayType t = new IrDocArrayType ( elem ) ; setLocation ( t , elem . getLocation ( ) , stop . getLocation ( ) ) ; elem = t ; } } stream . discard ( ) ; return elem ; } private static IrDocName fetchName ( JavadocTokenStream stream ) { IrDocName name = fetchSimpleName ( stream ) ; if ( name == null ) { return null ; } while ( true ) { stream . mark ( ) ; if ( consumeIfMatch ( stream , JavadocTokenKind . DOT ) == null ) { stream . rewind ( ) ; break ; } IrDocSimpleName simple = fetchSimpleName ( stream ) ; if ( simple == null ) { stream . rewind ( ) ; break ; } else { IrDocQualifiedName qualified = new IrDocQualifiedName ( name , simple ) ; setLocation ( qualified , name . getLocation ( ) , simple . getLocation ( ) ) ; name = qualified ; stream . discard ( ) ; } } return name ; } private static IrDocBasicType fetchBasicType ( JavadocTokenStream stream ) { JavadocToken token = stream . peek ( ) ; if ( token . getKind ( ) == JavadocTokenKind . IDENTIFIER ) { if ( BASIC_TYPE_NAMES . containsKey ( token . getText ( ) ) ) { stream . nextToken ( ) ; IrBasicTypeKind k = BASIC_TYPE_NAMES . get ( token . getText ( ) ) ; IrDocBasicType elem = new IrDocBasicType ( k ) ; setLocation ( elem , token , token ) ; return elem ; } } return null ; } private static IrDocSimpleName fetchSimpleName ( JavadocTokenStream stream ) { JavadocToken token = consumeIfMatch ( stream , JavadocTokenKind . IDENTIFIER ) ; if ( token != null ) { IrDocSimpleName name = new IrDocSimpleName ( token . getText ( ) ) ; setLocation ( name , token , token ) ; return name ; } else { return null ; } } private static boolean follows ( JavadocTokenStream stream , Collection < JavadocTokenKind > set ) { if ( set == null ) { return true ; } JavadocTokenKind kind = stream . lookahead ( ) . getKind ( ) ; return set . contains ( kind ) ; } private static JavadocToken consumeIfMatch ( JavadocTokenStream stream , JavadocTokenKind kind ) { JavadocToken token = stream . peek ( ) ; if ( token . getKind ( ) == kind ) { return stream . nextToken ( ) ; } return null ; } private static IrDocText consumeAsText ( JavadocScanner scanner , int count , boolean trimHead , boolean trimTail ) { assert scanner != null ; assert count >= ; int mark = scanner . getIndex ( ) ; List < JavadocToken > tokens = consumeTokens ( scanner , count , trimHead , trimTail ) ; IrDocText elem = buildText ( tokens ) ; if ( elem == null ) { scanner . seek ( mark ) ; return null ; } else { return elem ; } } private static IrDocText buildText ( List < ? extends JavadocToken > tokens ) { assert tokens != null ; if ( tokens . isEmpty ( ) ) { return null ; } String text = buildString ( tokens ) ; IrDocText elem = new IrDocText ( text ) ; JavadocToken start = tokens . get ( ) ; JavadocToken stop = tokens . get ( tokens . size ( ) - ) ; setLocation ( elem , start , stop ) ; return elem ; } public static String buildString ( List < ? extends JavadocToken > tokens ) { if ( tokens == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tokens . isEmpty ( ) ) { return "" ; } StringBuilder buf = new StringBuilder ( ) ; for ( JavadocToken t : tokens ) { buf . append ( t . getText ( ) ) ; } return buf . toString ( ) ; } private static List < JavadocToken > consumeTokens ( JavadocScanner scanner , int count , boolean trimHead , boolean trimTail ) { if ( count == ) { return Collections . emptyList ( ) ; } int rest = count ; if ( trimHead ) { int offset = JavadocScannerUtil . countWhile ( S_WHITE , scanner , ) ; scanner . consume ( offset ) ; rest -= offset ; if ( rest == ) { return Collections . emptyList ( ) ; } } List < JavadocToken > tokens = new ArrayList < JavadocToken > ( rest ) ; for ( int i = ; i < rest ; i ++ ) { JavadocToken t = scanner . nextToken ( ) ; if ( t . getKind ( ) == JavadocTokenKind . EOF ) { break ; } tokens . add ( t ) ; } if ( trimTail ) { int lastWs = tokens . size ( ) ; while ( lastWs >= ) { JavadocToken t = tokens . get ( lastWs - ) ; if ( t . getKind ( ) != WHITE_SPACES ) { break ; } lastWs -- ; } if ( lastWs != tokens . size ( ) ) { tokens = tokens . subList ( , lastWs ) ; } } return tokens ; } } package com . asakusafw . utils . java . parser . javadoc ; import java . util . LinkedList ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocToken ; import com . asakusafw . utils . java . internal . parser . javadoc . ir . JavadocTokenKind ; public class DefaultJavadocTokenStream implements JavadocTokenStream { private JavadocScanner scanner ; private LinkedList < Integer > marks ; public DefaultJavadocTokenStream ( JavadocScanner scanner ) { super ( ) ; if ( scanner == null ) { throw new IllegalArgumentException ( "" ) ; } this . scanner = scanner ; this . marks = new LinkedList < Integer > ( ) ; } @ Override public JavadocToken peek ( ) { int index = scanner . getIndex ( ) ; try { return nextToken ( ) ; } finally { scanner . seek ( index ) ; } } @ Override public JavadocToken lookahead ( int k ) { return scanner . lookahead ( k ) ; } @ Override public JavadocToken nextToken ( ) { while ( true ) { JavadocToken token = scanner . lookahead ( ) ; JavadocTokenKind kind = token . getKind ( ) ; if ( kind == JavadocTokenKind . LINE_BREAK ) { int offset = JavadocScannerUtil . countUntilNextLineStart ( scanner , ) ; scanner . consume ( offset ) ; } else if ( kind == JavadocTokenKind . WHITE_SPACES ) { scanner . consume ( ) ; } else { scanner . consume ( ) ; return token ; } } } @ Override public void mark ( ) { marks . addFirst ( scanner . getIndex ( ) ) ; } @ Override public void rewind ( ) { int mark = fetchMark ( ) ; scanner . seek ( mark ) ; } @ Override public void discard ( ) { fetchMark ( ) ; } private Integer fetchMark ( ) { if ( marks . isEmpty ( ) ) { throw new IllegalStateException ( ) ; } return marks . removeFirst ( ) ; } } package com . asakusafw . utils . java . jsr269 . bridge ; package com . asakusafw . utils . java . jsr269 . bridge ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . Writer ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . EnumMap ; import java . util . List ; import javax . annotation . processing . Filer ; import javax . lang . model . element . Element ; import javax . lang . model . element . PackageElement ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . DeclaredType ; import javax . lang . model . type . NoType ; import javax . lang . model . type . PrimitiveType ; import javax . lang . model . type . TypeKind ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . type . TypeVariable ; import javax . lang . model . type . WildcardType ; import javax . tools . JavaFileObject ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . ArrayType ; import com . asakusafw . utils . java . model . syntax . BasicType ; import com . asakusafw . utils . java . model . syntax . BasicTypeKind ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModifierKind ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . Wildcard ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; import com . asakusafw . utils . java . model . util . Emitter ; import com . asakusafw . utils . java . model . util . Models ; public class Jsr269 { private static final EnumMap < javax . lang . model . element . Modifier , ModifierKind > MODIFIERS ; static { MODIFIERS = new EnumMap < javax . lang . model . element . Modifier , ModifierKind > ( javax . lang . model . element . Modifier . class ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . ABSTRACT , ModifierKind . ABSTRACT ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . FINAL , ModifierKind . FINAL ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . NATIVE , ModifierKind . NATIVE ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . PRIVATE , ModifierKind . PRIVATE ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . PROTECTED , ModifierKind . PROTECTED ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . PUBLIC , ModifierKind . PUBLIC ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . STATIC , ModifierKind . STATIC ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . STRICTFP , ModifierKind . STRICTFP ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . SYNCHRONIZED , ModifierKind . SYNCHRONIZED ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . TRANSIENT , ModifierKind . TRANSIENT ) ; MODIFIERS . put ( javax . lang . model . element . Modifier . VOLATILE , ModifierKind . VOLATILE ) ; } private final ModelFactory factory ; public Jsr269 ( ModelFactory factory ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } this . factory = factory ; } public PackageDeclaration convert ( PackageElement packageElement ) { if ( packageElement == null ) { throw new IllegalArgumentException ( "" ) ; } if ( packageElement . isUnnamed ( ) ) { return null ; } return factory . newPackageDeclaration ( null , Collections . < Annotation > emptyList ( ) , convert ( packageElement . getQualifiedName ( ) ) ) ; } public Name convert ( javax . lang . model . element . Name name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return Models . toName ( factory , name . toString ( ) ) ; } public Type convert ( TypeMirror type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } return convert0 ( type ) ; } public ArrayType convert ( javax . lang . model . type . ArrayType type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } int dimensions = ; TypeMirror component = type . getComponentType ( ) ; while ( component . getKind ( ) == TypeKind . ARRAY ) { component = ( ( javax . lang . model . type . ArrayType ) component ) . getComponentType ( ) ; dimensions ++ ; } Type result = convert0 ( component ) ; if ( result == null ) { return null ; } assert ( result instanceof ArrayType ) == false ; for ( int i = ; i < dimensions ; i ++ ) { result = factory . newArrayType ( result ) ; } assert result instanceof ArrayType ; return ( ArrayType ) result ; } public Type convert ( DeclaredType type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } NamedType raw = convertToRawType ( type ) ; if ( raw == null ) { return null ; } List < ? extends TypeMirror > typeArguments = type . getTypeArguments ( ) ; if ( typeArguments . isEmpty ( ) ) { return raw ; } List < Type > arguments = new ArrayList < Type > ( ) ; for ( TypeMirror mirror : typeArguments ) { Type argument = convert0 ( mirror ) ; if ( argument == null ) { return null ; } arguments . add ( argument ) ; } return factory . newParameterizedType ( raw , arguments ) ; } public Type convert ( NoType type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } switch ( type . getKind ( ) ) { case VOID : return factory . newBasicType ( BasicTypeKind . VOID ) ; case PACKAGE : case NONE : return null ; default : throw new AssertionError ( type ) ; } } public BasicType convert ( PrimitiveType type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } switch ( type . getKind ( ) ) { case BOOLEAN : return factory . newBasicType ( BasicTypeKind . BOOLEAN ) ; case BYTE : return factory . newBasicType ( BasicTypeKind . BYTE ) ; case CHAR : return factory . newBasicType ( BasicTypeKind . CHAR ) ; case DOUBLE : return factory . newBasicType ( BasicTypeKind . DOUBLE ) ; case FLOAT : return factory . newBasicType ( BasicTypeKind . FLOAT ) ; case INT : return factory . newBasicType ( BasicTypeKind . INT ) ; case LONG : return factory . newBasicType ( BasicTypeKind . LONG ) ; case SHORT : return factory . newBasicType ( BasicTypeKind . SHORT ) ; default : throw new AssertionError ( type ) ; } } public NamedType convert ( TypeVariable type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } SimpleName name = asSimpleName ( type . asElement ( ) . getSimpleName ( ) ) ; return factory . newNamedType ( name ) ; } public Wildcard convert ( WildcardType type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } TypeMirror upper = type . getExtendsBound ( ) ; if ( upper != null ) { if ( type . getSuperBound ( ) != null ) { return null ; } Type bound = convert0 ( upper ) ; if ( bound == null ) { return null ; } return factory . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , bound ) ; } TypeMirror lower = type . getSuperBound ( ) ; if ( lower != null ) { Type bound = convert0 ( lower ) ; if ( bound == null ) { return null ; } return factory . newWildcard ( WildcardBoundKind . LOWER_BOUNDED , bound ) ; } return factory . newWildcard ( WildcardBoundKind . UNBOUNDED , null ) ; } private SimpleName asSimpleName ( javax . lang . model . element . Name simpleName ) { assert simpleName != null ; return factory . newSimpleName ( simpleName . toString ( ) ) ; } private NamedType convertToRawType ( DeclaredType type ) { assert type != null ; Element element = type . asElement ( ) ; if ( element == null ) { return null ; } switch ( element . getKind ( ) ) { case CLASS : case INTERFACE : case ENUM : case ANNOTATION_TYPE : { Name name = asName ( ( ( TypeElement ) element ) . getQualifiedName ( ) ) ; return factory . newNamedType ( name ) ; } default : throw new AssertionError ( type ) ; } } private Name asName ( javax . lang . model . element . Name qualifiedName ) { assert qualifiedName != null ; return Models . toName ( factory , qualifiedName . toString ( ) ) ; } private Type convert0 ( TypeMirror type ) { assert type != null ; switch ( type . getKind ( ) ) { case ARRAY : return convert ( ( javax . lang . model . type . ArrayType ) type ) ; case DECLARED : case ERROR : return convert ( ( DeclaredType ) type ) ; case BOOLEAN : case BYTE : case CHAR : case DOUBLE : case FLOAT : case INT : case LONG : case SHORT : return convert ( ( PrimitiveType ) type ) ; case VOID : case PACKAGE : case NONE : return convert ( ( NoType ) type ) ; case TYPEVAR : return convert ( ( TypeVariable ) type ) ; case WILDCARD : return convert ( ( WildcardType ) type ) ; default : return null ; } } public List < ModifierKind > convert ( Collection < javax . lang . model . element . Modifier > modifiers ) { if ( modifiers == null ) { throw new IllegalArgumentException ( "" ) ; } List < ModifierKind > results = new ArrayList < ModifierKind > ( ) ; for ( javax . lang . model . element . Modifier modifier : modifiers ) { ModifierKind kind = MODIFIERS . get ( modifier ) ; if ( kind != null ) { results . add ( kind ) ; } } return results ; } public void emit ( Filer filer , CompilationUnit unit ) throws IOException { if ( filer == null ) { throw new IllegalArgumentException ( "" ) ; } if ( unit == null ) { throw new IllegalArgumentException ( "" ) ; } StringBuilder name = new StringBuilder ( ) ; if ( unit . getPackageDeclaration ( ) != null ) { name . append ( unit . getPackageDeclaration ( ) . getName ( ) ) ; name . append ( '' ) ; } TypeDeclaration primary = Emitter . findPrimaryType ( unit ) ; if ( primary == null ) { name . append ( "" ) ; } else { name . append ( primary . getName ( ) ) ; } JavaFileObject source = filer . createSourceFile ( name ) ; Writer writer = source . openWriter ( ) ; try { PrintWriter output = new PrintWriter ( writer ) ; Models . emit ( unit , output ) ; output . close ( ) ; } finally { writer . close ( ) ; } } } package com . asakusafw . utils . java . jsr269 . bridge ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import javax . lang . model . element . TypeElement ; import javax . lang . model . element . TypeParameterElement ; import javax . lang . model . type . TypeKind ; import javax . lang . model . type . TypeMirror ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; import com . asakusafw . utils . java . model . util . Models ; public class Jsr269Test { ModelFactory f ; Jsr269 target ; private VolatileCompiler compiler ; @ Before public void setUp ( ) throws Exception { f = Models . getModelFactory ( ) ; compiler = new VolatileCompiler ( ) ; target = new Jsr269 ( f ) ; } @ After public void tearDown ( ) throws Exception { if ( compiler != null ) { compiler . close ( ) ; } } @ Test public void name ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { assertThat ( target . convert ( elements . getName ( "" ) ) , is ( Models . toName ( f , "" ) ) ) ; assertThat ( target . convert ( elements . getName ( "" ) ) , is ( Models . toName ( f , "" ) ) ) ; } } ) ; } @ Test public void primitiveTypes ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { assertThat ( target . convert ( ( TypeMirror ) types . getPrimitiveType ( TypeKind . INT ) ) , is ( Models . toType ( f , int . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getPrimitiveType ( TypeKind . LONG ) ) , is ( Models . toType ( f , long . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getPrimitiveType ( TypeKind . FLOAT ) ) , is ( Models . toType ( f , float . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getPrimitiveType ( TypeKind . DOUBLE ) ) , is ( Models . toType ( f , double . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getPrimitiveType ( TypeKind . BYTE ) ) , is ( Models . toType ( f , byte . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getPrimitiveType ( TypeKind . SHORT ) ) , is ( Models . toType ( f , short . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getPrimitiveType ( TypeKind . CHAR ) ) , is ( Models . toType ( f , char . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getPrimitiveType ( TypeKind . BOOLEAN ) ) , is ( Models . toType ( f , boolean . class ) ) ) ; } } ) ; } @ Test public void declaredType ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { assertThat ( target . convert ( getType ( Object . class ) ) , is ( Models . toType ( f , Object . class ) ) ) ; assertThat ( target . convert ( getType ( String . class ) ) , is ( Models . toType ( f , String . class ) ) ) ; assertThat ( target . convert ( getType ( List . class ) ) , is ( Models . toType ( f , List . class ) ) ) ; } } ) ; } @ Test public void parameterizedType ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { assertThat ( target . convert ( getType ( List . class , getType ( String . class ) ) ) , is ( ( Type ) f . newParameterizedType ( Models . toType ( f , List . class ) , Arrays . asList ( new Type [ ] { Models . toType ( f , String . class ) } ) ) ) ) ; assertThat ( target . convert ( getType ( Map . class , getType ( Integer . class ) , getType ( Object . class ) ) ) , is ( ( Type ) f . newParameterizedType ( Models . toType ( f , Map . class ) , Arrays . asList ( new Type [ ] { Models . toType ( f , Integer . class ) , Models . toType ( f , Object . class ) , } ) ) ) ) ; } } ) ; } @ Test public void noType ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { assertThat ( target . convert ( ( TypeMirror ) types . getNoType ( TypeKind . VOID ) ) , is ( Models . toType ( f , void . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getNoType ( TypeKind . NONE ) ) , is ( nullValue ( ) ) ) ; } } ) ; } @ Test public void typeVariable ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { TypeElement map = elements . getTypeElement ( Map . class . getName ( ) ) ; TypeParameterElement k = map . getTypeParameters ( ) . get ( ) ; assertThat ( target . convert ( k . asType ( ) ) , is ( ( Type ) f . newNamedType ( f . newSimpleName ( "" ) ) ) ) ; TypeElement list = elements . getTypeElement ( List . class . getName ( ) ) ; TypeParameterElement e = list . getTypeParameters ( ) . get ( ) ; assertThat ( target . convert ( e . asType ( ) ) , is ( ( Type ) f . newNamedType ( f . newSimpleName ( "" ) ) ) ) ; } } ) ; } @ Test public void arrayTypes ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { assertThat ( target . convert ( ( TypeMirror ) types . getArrayType ( types . getPrimitiveType ( TypeKind . INT ) ) ) , is ( Models . toType ( f , int [ ] . class ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getArrayType ( types . getArrayType ( getType ( String . class ) ) ) ) , is ( Models . toType ( f , String [ ] [ ] . class ) ) ) ; } } ) ; } @ Test public void wildcard ( ) { start ( new Callback ( ) { @ Override protected void test ( ) { assertThat ( target . convert ( ( TypeMirror ) types . getWildcardType ( null , null ) ) , is ( ( Type ) f . newWildcard ( WildcardBoundKind . UNBOUNDED , null ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getWildcardType ( getType ( CharSequence . class ) , null ) ) , is ( ( Type ) f . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , Models . toType ( f , CharSequence . class ) ) ) ) ; assertThat ( target . convert ( ( TypeMirror ) types . getWildcardType ( null , getType ( CharSequence . class ) ) ) , is ( ( Type ) f . newWildcard ( WildcardBoundKind . LOWER_BOUNDED , Models . toType ( f , CharSequence . class ) ) ) ) ; } } ) ; } private void start ( Callback callback , JavaFileObject ... sources ) { for ( JavaFileObject java : sources ) { compiler . addSource ( java ) ; } if ( sources . length == ) { compiler . addSource ( new VolatileJavaFile ( "" , "" ) ) ; } compiler . addProcessor ( new DelegateProcessor ( callback ) ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) == Diagnostic . Kind . ERROR ) { throw new AssertionError ( diagnostics ) ; } } callback . rethrow ( ) ; } } package com . asakusafw . utils . java . jsr269 . bridge ; import java . util . Set ; import javax . annotation . processing . AbstractProcessor ; import javax . annotation . processing . RoundEnvironment ; import javax . annotation . processing . SupportedAnnotationTypes ; import javax . annotation . processing . SupportedSourceVersion ; import javax . lang . model . SourceVersion ; import javax . lang . model . element . TypeElement ; @ SupportedAnnotationTypes ( { "" } ) @ SupportedSourceVersion ( SourceVersion . RELEASE_6 ) public class DelegateProcessor extends AbstractProcessor { private Callback callback ; public DelegateProcessor ( Callback callback ) { this . callback = callback ; } @ Override public boolean process ( Set < ? extends TypeElement > annotations , RoundEnvironment env ) { callback . run ( processingEnv , env ) ; return true ; } } package com . asakusafw . utils . java . jsr269 . bridge ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import javax . annotation . processing . ProcessingEnvironment ; import javax . annotation . processing . RoundEnvironment ; import javax . lang . model . element . TypeElement ; import javax . lang . model . type . TypeMirror ; import javax . lang . model . util . Elements ; import javax . lang . model . util . Types ; public abstract class Callback { private RuntimeException runtimeException ; private Error error ; protected ProcessingEnvironment env ; protected Types types ; protected Elements elements ; protected RoundEnvironment round ; @ SuppressWarnings ( "" ) public void run ( ProcessingEnvironment env , RoundEnvironment round ) { this . env = env ; this . round = round ; this . types = env . getTypeUtils ( ) ; this . elements = env . getElementUtils ( ) ; try { test ( ) ; } catch ( RuntimeException e ) { this . runtimeException = e ; } catch ( Error e ) { this . error = e ; } } public void rethrow ( ) { if ( runtimeException != null ) { throw runtimeException ; } else if ( error != null ) { throw error ; } } protected abstract void test ( ) ; protected TypeMirror getType ( Class < ? > klass , TypeMirror ... arguments ) { TypeElement type = elements . getTypeElement ( klass . getName ( ) ) ; assertThat ( klass . getName ( ) , type , not ( nullValue ( ) ) ) ; if ( arguments . length == ) { return types . erasure ( type . asType ( ) ) ; } else { return types . getDeclaredType ( type , arguments ) ; } } } package com . asakusafw . testdriver ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . commons . io . FileUtils ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . FileUtil ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . mapreduce . lib . output . FileOutputCommitter ; import org . junit . Assert ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . flow . FlowDescriptionDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectExporterDescription ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . DirectImporterDescription ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; @ SuppressWarnings ( "" ) public class FlowPartTestDriver extends TestDriverTestToolsBase { private static final Logger LOG = LoggerFactory . getLogger ( FlowPartTestDriver . class ) ; private final FlowDescriptionDriver flowDescriptionDriver = new FlowDescriptionDriver ( ) ; private final Map < String , List < String > > createInMap = new HashMap < String , List < String > > ( ) ; private final Map < String , List < String > > createOutMap = new HashMap < String , List < String > > ( ) ; private boolean createIndividually = false ; private boolean loadIndividually = false ; public FlowPartTestDriver ( ) { super ( ) ; } public FlowPartTestDriver ( List < File > testDataFileList ) { super ( testDataFileList ) ; } public void runTest ( FlowDescription flowDescription ) { try { String batchId = "" ; String flowId = "" ; File compileWorkDir = driverContext . getCompilerWorkingDirectory ( ) ; if ( compileWorkDir . exists ( ) ) { FileUtils . forceDelete ( compileWorkDir ) ; } FlowGraph flowGraph = flowDescriptionDriver . createFlowGraph ( flowDescription ) ; JobflowInfo jobflowInfo = DirectFlowCompiler . compile ( flowGraph , batchId , flowId , "" , FlowPartDriverUtils . createWorkingLocation ( driverContext ) , compileWorkDir , Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( flowDescription . getClass ( ) ) } ) , flowDescription . getClass ( ) . getClassLoader ( ) , driverContext . getOptions ( ) ) ; JobflowExecutor executor = new JobflowExecutor ( driverContext ) ; driverContext . prepareCurrentJobflow ( jobflowInfo ) ; executor . cleanWorkingDirectory ( ) ; if ( createIndividually ) { prepareIndividually ( ) ; } else { createAllInput ( ) ; } executor . runJobflow ( jobflowInfo ) ; if ( loadIndividually ) { loadAndInspectResultsIndividually ( ) ; } else { loadAndInspectResults ( ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } @ SuppressWarnings ( "" ) public < T > In < T > createIn ( String tableName ) { Class < ? > modelType = testUtils . getClassByTablename ( tableName ) ; return ( In < T > ) createIn ( modelType ) ; } public < T > In < T > createIn ( Class < T > modelType ) { String tableName = testUtils . getTablenameByClass ( modelType ) ; addCreateIn ( tableName , tableName ) ; String path = FlowPartDriverUtils . createInputLocation ( driverContext , tableName ) . toPath ( '' ) ; LOG . info ( "" + path ) ; ImporterDescription desc = new DirectImporterDescription ( modelType , path ) ; return flowDescriptionDriver . createIn ( tableName , desc ) ; } @ SuppressWarnings ( "" ) public < T > In < T > createIn ( String tableName , String excelFileName ) { Class < ? > modelType = testUtils . getClassByTablename ( tableName ) ; return ( In < T > ) createIn ( modelType , excelFileName ) ; } public < T > In < T > createIn ( Class < T > modelType , String excelFileName ) { String tableName = testUtils . getTablenameByClass ( modelType ) ; createIndividually = true ; loadIndividually = true ; addCreateIn ( tableName , excelFileName ) ; String path = FlowPartDriverUtils . createInputLocation ( driverContext , excelFileName ) . toPath ( '' ) ; LOG . info ( "" + excelFileName ) ; DirectImporterDescription desc = new DirectImporterDescription ( modelType , path ) ; String inName ; int offset = excelFileName . lastIndexOf ( '' ) ; if ( offset > - ) { inName = excelFileName . substring ( offset + ) ; } else { inName = excelFileName ; } return flowDescriptionDriver . createIn ( inName , desc ) ; } @ SuppressWarnings ( "" ) public < T > Out < T > createOut ( String tableName ) { Class < ? > modelType = testUtils . getClassByTablename ( tableName ) ; return ( Out < T > ) createOut ( modelType ) ; } public < T > Out < T > createOut ( Class < T > modelType ) { String tableName = testUtils . getTablenameByClass ( modelType ) ; addCreateOut ( tableName , tableName ) ; String path = FlowPartDriverUtils . createOutputLocation ( driverContext , tableName ) . toPath ( '' ) ; LOG . info ( "" + path ) ; ExporterDescription desc = new DirectExporterDescription ( modelType , path ) ; return flowDescriptionDriver . createOut ( tableName , desc ) ; } @ SuppressWarnings ( "" ) public < T > Out < T > createOut ( String tableName , String excelFileName ) { Class < ? > modelType = testUtils . getClassByTablename ( tableName ) ; return ( Out < T > ) createOut ( modelType , excelFileName ) ; } public < T > Out < T > createOut ( Class < T > modelType , String excelFileName ) { String tableName = testUtils . getTablenameByClass ( modelType ) ; loadIndividually = true ; addCreateOut ( tableName , excelFileName ) ; String path = FlowPartDriverUtils . createOutputLocation ( driverContext , excelFileName ) . toPath ( '' ) ; LOG . info ( "" + excelFileName ) ; DirectExporterDescription desc = new DirectExporterDescription ( modelType , path ) ; String outName ; int offset = excelFileName . lastIndexOf ( System . getProperty ( "" ) ) ; if ( offset > - ) { outName = excelFileName . substring ( offset + ) ; } else { outName = excelFileName ; } return flowDescriptionDriver . createOut ( outName , desc ) ; } private void addCreateIn ( String tableName , String fileName ) { List < String > fileListPerTable = createInMap . get ( tableName ) ; if ( fileListPerTable == null ) { fileListPerTable = new ArrayList < String > ( ) ; createInMap . put ( tableName , fileListPerTable ) ; } fileListPerTable . add ( fileName ) ; } private void addCreateOut ( String tableName , String fileName ) { List < String > fileListPerTable = createOutMap . get ( tableName ) ; if ( fileListPerTable == null ) { fileListPerTable = new ArrayList < String > ( ) ; createOutMap . put ( tableName , fileListPerTable ) ; } fileListPerTable . add ( fileName ) ; } private void createAllInput ( ) { for ( String table : testUtils . getTablenames ( ) ) { createInput ( table , table ) ; } } private void prepareIndividually ( ) { for ( Map . Entry < String , List < String > > entry : createInMap . entrySet ( ) ) { String tablename = entry . getKey ( ) ; List < String > fileList = entry . getValue ( ) ; for ( String excelFileName : fileList ) { List < File > inFileList = new ArrayList < File > ( ) ; if ( testDataDir != null ) { inFileList . add ( new File ( testDataDir , excelFileName + "" ) ) ; } else { for ( File file : testDataFileList ) { if ( file . getPath ( ) . endsWith ( excelFileName + "" ) ) { inFileList . add ( file ) ; break ; } } } try { testUtils = new TestUtils ( inFileList ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } createInput ( tablename , excelFileName ) ; } } } private void createInput ( String tablename , String excelFileName ) { FileSystem fs = null ; try { Configuration conf = ConfigurationFactory . getDefault ( ) . newInstance ( ) ; fs = FileSystem . get ( conf ) ; URI inputPath = new URI ( computeInputPath ( fs , excelFileName ) ) ; LOG . info ( "" + inputPath ) ; testUtils . storeToTemporary ( tablename , conf , new Path ( inputPath ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; } } private void loadAndInspectResults ( ) throws IOException { for ( String table : testUtils . getTablenames ( ) ) { loadResult ( table , table ) ; } if ( ! testUtils . inspect ( ) ) { Assert . fail ( testUtils . getCauseMessage ( ) ) ; } } private void loadAndInspectResultsIndividually ( ) throws IOException { for ( Map . Entry < String , List < String > > entry : createOutMap . entrySet ( ) ) { String tablename = entry . getKey ( ) ; List < String > fileList = entry . getValue ( ) ; for ( String excelFileName : fileList ) { List < File > outFileList = new ArrayList < File > ( ) ; if ( testDataDir != null ) { outFileList . add ( new File ( testDataDir , excelFileName + "" ) ) ; } else { for ( File file : testDataFileList ) { if ( file . getPath ( ) . endsWith ( excelFileName + "" ) ) { outFileList . add ( file ) ; break ; } } } try { testUtils = new TestUtils ( outFileList ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } loadResult ( tablename , excelFileName ) ; if ( ! testUtils . inspect ( ) ) { Assert . fail ( testUtils . getCauseMessage ( ) ) ; return ; } } } } private void loadResult ( String tablename , String excelFileName ) throws IOException { Configuration conf = ConfigurationFactory . getDefault ( ) . newInstance ( ) ; FileSystem fs = FileSystem . get ( conf ) ; FileStatus [ ] status = fs . globStatus ( new Path ( computeOutputPath ( fs , excelFileName ) ) ) ; Path [ ] listedPaths = FileUtil . stat2Paths ( status ) ; for ( Path path : listedPaths ) { if ( isSystemFile ( path ) ) { continue ; } LOG . info ( "" + path ) ; testUtils . loadFromTemporary ( tablename , conf , path ) ; } } private boolean isSystemFile ( Path path ) { assert path != null ; String name = path . getName ( ) ; return name . equals ( FileOutputCommitter . SUCCEEDED_FILE_NAME ) || name . equals ( "" ) ; } private String computeInputPath ( FileSystem fs , String tableName ) { Location location = FlowPartDriverUtils . createInputLocation ( driverContext , tableName ) ; String path = new Path ( fs . getWorkingDirectory ( ) , location . toPath ( '' ) ) . toString ( ) ; return resolvePath ( path ) ; } private String computeOutputPath ( FileSystem fs , String tableName ) { Location location = FlowPartDriverUtils . createOutputLocation ( driverContext , tableName ) ; String path = new Path ( fs . getWorkingDirectory ( ) , location . toPath ( '' ) ) . toString ( ) ; return resolvePath ( path ) ; } private String resolvePath ( String path ) { assert path != null ; Map < String , String > arguments = driverContext . getArguments ( ) ; VariableTable variables = new VariableTable ( ) ; variables . defineVariables ( arguments ) ; return variables . parse ( path , false ) ; } } package com . asakusafw . testdriver ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . sql . Timestamp ; import java . util . Arrays ; import java . util . List ; import org . apache . commons . io . FileUtils ; import org . junit . Assert ; import com . asakusafw . compiler . flow . JobFlowClass ; import com . asakusafw . compiler . flow . JobFlowDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . graph . FlowGraph ; @ SuppressWarnings ( "" ) public class JobFlowTestDriver extends TestDriverTestToolsBase { private final String batchId ; public JobFlowTestDriver ( ) { super ( ) ; this . batchId = "" ; } public JobFlowTestDriver ( String batchId ) { super ( ) ; this . batchId = batchId ; } public JobFlowTestDriver ( List < File > testDataFileList ) { super ( testDataFileList ) ; this . batchId = "" ; } public JobFlowTestDriver ( List < File > testDataFileList , String batchId ) { super ( testDataFileList ) ; this . batchId = batchId ; } public void runTest ( Class < ? extends FlowDescription > jobFlowDescriptionClass ) { try { JobflowExecutor executor = new JobflowExecutor ( driverContext ) ; executor . cleanWorkingDirectory ( ) ; storeDatabase ( ) ; setLastModifiedTimestamp ( new Timestamp ( ) ) ; JobFlowDriver jobFlowDriver = JobFlowDriver . analyze ( jobFlowDescriptionClass ) ; assertFalse ( jobFlowDriver . getDiagnostics ( ) . toString ( ) , jobFlowDriver . hasError ( ) ) ; JobFlowClass jobFlowClass = jobFlowDriver . getJobFlowClass ( ) ; String flowId = jobFlowClass . getConfig ( ) . name ( ) ; File compileWorkDir = driverContext . getCompilerWorkingDirectory ( ) ; if ( compileWorkDir . exists ( ) ) { FileUtils . forceDelete ( compileWorkDir ) ; } FlowGraph flowGraph = jobFlowClass . getGraph ( ) ; JobflowInfo jobflowInfo = DirectFlowCompiler . compile ( flowGraph , batchId , flowId , "" , Location . fromPath ( driverContext . getClusterWorkDir ( ) , '' ) , compileWorkDir , Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( jobFlowDescriptionClass ) } ) , jobFlowDescriptionClass . getClassLoader ( ) , driverContext . getOptions ( ) ) ; driverContext . prepareCurrentJobflow ( jobflowInfo ) ; executor . runJobflow ( jobflowInfo ) ; loadDatabase ( ) ; if ( ! testUtils . inspect ( ) ) { Assert . fail ( testUtils . getCauseMessage ( ) ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } private void storeDatabase ( ) { testUtils . storeToDatabase ( false ) ; } private void loadDatabase ( ) { testUtils . loadFromDatabase ( ) ; } } package com . asakusafw . testdriver ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . lang . reflect . Method ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . SQLException ; import java . sql . Timestamp ; import java . text . MessageFormat ; import java . util . List ; import java . util . Properties ; import org . apache . commons . io . IOUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testtools . TestUtils ; import com . asakusafw . testtools . db . DbUtils ; import com . asakusafw . thundergate . runtime . cache . ThunderGateCacheSupport ; @ SuppressWarnings ( "" ) public class TestDriverTestToolsBase extends TestDriverBase { private static final Logger LOG = LoggerFactory . getLogger ( TestDriverTestToolsBase . class ) ; private static final String BUILD_PROPERTIES_FILE = "" ; protected static final String TESTDATA_DIR_DEFAULT = "" ; protected TestUtils testUtils ; protected List < File > testDataFileList ; protected File testDataDir ; protected Properties buildProperties ; public TestDriverTestToolsBase ( ) { super ( findCaller ( ) . getDeclaringClass ( ) ) ; initialize ( findCaller ( ) ) ; } public TestDriverTestToolsBase ( List < File > testDataFileList ) { super ( findCaller ( ) . getDeclaringClass ( ) ) ; this . testDataFileList = testDataFileList ; initialize ( findCaller ( ) ) ; } private static Method findCaller ( ) { StackTraceElement [ ] trace = new Throwable ( ) . getStackTrace ( ) ; for ( StackTraceElement element : trace ) { try { Class < ? > aClass = Class . forName ( element . getClassName ( ) ) ; if ( TestDriverTestToolsBase . class . isAssignableFrom ( aClass ) ) { continue ; } Method method = aClass . getDeclaredMethod ( element . getMethodName ( ) ) ; return method ; } catch ( Exception e ) { continue ; } } throw new IllegalStateException ( "" ) ; } private void initialize ( Method caller ) { assert caller != null ; try { File buildPropertiesFile = new File ( BUILD_PROPERTIES_FILE ) ; if ( buildPropertiesFile . exists ( ) ) { LOG . info ( "" , buildPropertiesFile ) ; FileInputStream fis = null ; try { fis = new FileInputStream ( buildPropertiesFile ) ; buildProperties = new Properties ( ) ; buildProperties . load ( fis ) ; System . setProperty ( "" , buildProperties . getProperty ( "" ) ) ; System . setProperty ( "" , buildProperties . getProperty ( "" ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } finally { IOUtils . closeQuietly ( fis ) ; } } else { LOG . info ( "" , BUILD_PROPERTIES_FILE ) ; } System . setProperty ( "" , String . format ( "" , System . getenv ( "" ) , buildProperties . getProperty ( "" ) ) ) ; System . setProperty ( "" , buildProperties . getProperty ( "" ) ) ; String testDataDirPath = buildProperties . getProperty ( "" ) ; if ( testDataDirPath == null ) { testDataDirPath = TESTDATA_DIR_DEFAULT ; } if ( testDataFileList == null ) { testDataDir = new File ( testDataDirPath + File . separatorChar + caller . getDeclaringClass ( ) . getSimpleName ( ) + File . separatorChar + caller . getName ( ) ) ; testUtils = new TestUtils ( testDataDir ) ; } else { testUtils = new TestUtils ( testDataFileList ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } protected void setLastModifiedTimestamp ( Timestamp timestamp ) { for ( String tableName : testUtils . getTablenames ( ) ) { String timestampColumn = findTimestampColumn ( tableName ) ; if ( timestampColumn != null ) { updateTimestamp ( tableName , timestampColumn , timestamp ) ; } } } private String findTimestampColumn ( String tableName ) { Class < ? > tableClass = testUtils . getClassByTablename ( tableName ) ; if ( tableClass == null ) { return null ; } if ( ThunderGateCacheSupport . class . isAssignableFrom ( tableClass ) ) { try { ThunderGateCacheSupport instance = tableClass . asSubclass ( ThunderGateCacheSupport . class ) . newInstance ( ) ; return instance . __tgc__TimestampColumn ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return null ; } private void updateTimestamp ( String tableName , String timestampColumn , Timestamp timestamp ) { LOG . info ( "" , tableName , timestampColumn ) ; Connection conn = null ; PreparedStatement stmt = null ; try { conn = DbUtils . getConnection ( ) ; stmt = conn . prepareStatement ( MessageFormat . format ( "" , tableName , timestampColumn ) ) ; stmt . setTimestamp ( , timestamp ) ; int rows = stmt . executeUpdate ( ) ; LOG . info ( "" , new Object [ ] { tableName , timestampColumn , rows } ) ; if ( conn . getAutoCommit ( ) == false ) { conn . commit ( ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } finally { DbUtils . closeQuietly ( stmt ) ; DbUtils . closeQuietly ( conn ) ; } } } package com . asakusafw . testdriver ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . sql . Timestamp ; import java . util . Arrays ; import org . apache . commons . io . FileUtils ; import org . junit . Assert ; import com . asakusafw . compiler . batch . BatchDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . BatchInfo ; import com . asakusafw . compiler . testing . DirectBatchCompiler ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . vocabulary . batch . BatchDescription ; @ SuppressWarnings ( "" ) public class BatchTestDriver extends TestDriverTestToolsBase { public BatchTestDriver ( ) throws RuntimeException { super ( ) ; } public void runTest ( Class < ? extends BatchDescription > batchDescriptionClass ) { try { JobflowExecutor executor = new JobflowExecutor ( driverContext ) ; executor . cleanWorkingDirectory ( ) ; storeDatabase ( ) ; setLastModifiedTimestamp ( new Timestamp ( ) ) ; BatchDriver batchDriver = BatchDriver . analyze ( batchDescriptionClass ) ; assertFalse ( batchDriver . getDiagnostics ( ) . toString ( ) , batchDriver . hasError ( ) ) ; File compileWorkDir = driverContext . getCompilerWorkingDirectory ( ) ; if ( compileWorkDir . exists ( ) ) { FileUtils . forceDelete ( compileWorkDir ) ; } File compilerOutputDir = new File ( compileWorkDir , "" ) ; File compilerLocalWorkingDir = new File ( compileWorkDir , "" ) ; BatchInfo batchInfo = DirectBatchCompiler . compile ( batchDescriptionClass , "" , Location . fromPath ( driverContext . getClusterWorkDir ( ) , '' ) , compilerOutputDir , compilerLocalWorkingDir , Arrays . asList ( new File [ ] { DirectFlowCompiler . toLibraryPath ( batchDescriptionClass ) } ) , batchDescriptionClass . getClassLoader ( ) , driverContext . getOptions ( ) ) ; for ( JobflowInfo jobflowInfo : batchInfo . getJobflows ( ) ) { driverContext . prepareCurrentJobflow ( jobflowInfo ) ; executor . runJobflow ( jobflowInfo ) ; } loadDatabase ( ) ; if ( ! testUtils . inspect ( ) ) { Assert . fail ( testUtils . getCauseMessage ( ) ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } private void storeDatabase ( ) { testUtils . storeToDatabase ( false ) ; } private void loadDatabase ( ) { testUtils . loadFromDatabase ( ) ; } } package com . asakusafw . generator ; import java . io . File ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; @ SuppressWarnings ( "" ) public final class ModelSheetGenerator { static final Logger LOG = LoggerFactory . getLogger ( ModelSheetGenerator . class ) ; public static void main ( String [ ] args ) throws Exception { com . asakusafw . dmdl . thundergate . Configuration dmdlTgConf = com . asakusafw . dmdl . thundergate . Main . loadConfigurationFromArguments ( args ) ; com . asakusafw . dmdl . thundergate . model . ModelRepository repository = new com . asakusafw . dmdl . thundergate . GenerateTask ( dmdlTgConf ) . call ( ) ; List < com . asakusafw . dmdl . thundergate . model . TableModelDescription > tables = repository . allTables ( ) ; String [ ] tablesArray = new String [ tables . size ( ) ] ; int i = ; for ( com . asakusafw . dmdl . thundergate . model . TableModelDescription tableModelDescription : tables ) { tablesArray [ i ] = tableModelDescription . getReference ( ) . getSimpleName ( ) ; i ++ ; } System . setProperty ( "" , System . getProperty ( "" ) ) ; if ( "" . equals ( System . getProperty ( "" ) ) ) { String outputDir = System . getProperty ( "" ) + "" ; File dir = new File ( outputDir ) ; if ( dir . isDirectory ( ) == false && dir . mkdirs ( ) == false ) { if ( dir . isDirectory ( ) ) { LOG . warn ( "" , dir ) ; } } System . setProperty ( "" , outputDir ) ; com . asakusafw . testtools . templategen . Main . main ( tablesArray ) ; } HadoopBulkLoaderDDLGenerator . main ( tablesArray ) ; } private ModelSheetGenerator ( ) { return ; } } package com . asakusafw . generator ; package com . asakusafw . generator ; import java . io . File ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . commons . io . FileUtils ; import org . apache . commons . io . IOUtils ; public final class HadoopBulkLoaderDDLGenerator { private static final String [ ] ENV_PREFIX = { "" , "" } ; private static final List < String > ENV_BULKLOADER_GENDDL = buildEnvProperties ( "" ) ; private static final List < String > ENV_BULKLOADER_TABLES = buildEnvProperties ( "" ) ; private static final String TEMPLATE_DDL_FILENAME = "" ; private static final String TABLENAME_REPLACE_STRING = "" ; private static final String OUTPUT_TABLES_PROPERTY = "" ; public static void main ( String [ ] args ) throws Exception { String outputTablesString = findVariable ( ENV_BULKLOADER_TABLES , true ) ; List < String > outputTableList = null ; if ( outputTablesString != null && ! OUTPUT_TABLES_PROPERTY . equals ( outputTablesString ) ) { String [ ] outputTables = outputTablesString . trim ( ) . split ( "" ) ; outputTableList = Arrays . asList ( outputTables ) ; } String ddlTemplate ; InputStream in = HadoopBulkLoaderDDLGenerator . class . getResourceAsStream ( TEMPLATE_DDL_FILENAME ) ; try { ddlTemplate = IOUtils . toString ( in ) ; } finally { in . close ( ) ; } StringBuilder sb = new StringBuilder ( ) ; for ( String tableName : args ) { if ( outputTableList == null || outputTableList . contains ( tableName ) ) { String tableddl = ddlTemplate . replaceAll ( TABLENAME_REPLACE_STRING , tableName ) ; sb . append ( tableddl ) ; } } String outputFilePath = findVariable ( ENV_BULKLOADER_GENDDL , true ) ; if ( outputFilePath == null ) { throw new RuntimeException ( "" ) ; } FileUtils . write ( new File ( outputFilePath ) , sb ) ; } private HadoopBulkLoaderDDLGenerator ( ) { return ; } private static List < String > buildEnvProperties ( String suffix ) { assert suffix != null ; List < String > properties = new ArrayList < String > ( ENV_PREFIX . length ) ; for ( String prefix : ENV_PREFIX ) { properties . add ( prefix + suffix ) ; } return Collections . unmodifiableList ( properties ) ; } private static String findVariable ( List < String > variableNames , boolean mandatory ) { assert variableNames != null ; assert variableNames . isEmpty ( ) == false ; String value = null ; for ( String var : variableNames ) { value = System . getProperty ( var ) ; if ( value == null ) { value = System . getenv ( var ) ; } if ( value != null ) { break ; } } if ( mandatory && value == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , variableNames . get ( ) ) ) ; } return value ; } } package com . asakusafw . vocabulary . external ; import java . text . MessageFormat ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; import org . apache . hadoop . mapreduce . lib . output . SequenceFileOutputFormat ; public abstract class FileExporterDescription implements ExporterDescription { public abstract String getPathPrefix ( ) ; @ SuppressWarnings ( "" ) public Class < ? extends FileOutputFormat > getOutputFormat ( ) { return SequenceFileOutputFormat . class ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getPathPrefix ( ) , getOutputFormat ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . vocabulary . external ; import java . text . MessageFormat ; import java . util . Set ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . lib . input . FileInputFormat ; import org . apache . hadoop . mapreduce . lib . input . SequenceFileInputFormat ; public abstract class FileImporterDescription implements ImporterDescription { @ Override public DataSize getDataSize ( ) { return DataSize . UNKNOWN ; } public abstract Set < String > getPaths ( ) ; @ SuppressWarnings ( "" ) public Class < ? extends FileInputFormat > getInputFormat ( ) { return SequenceFileInputFormat . class ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , getPaths ( ) , getInputFormat ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . cleaner . main ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Date ; import java . util . Properties ; import org . apache . commons . io . FileUtils ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . cleaner . bean . LocalFileCleanerBean ; import com . asakusafw . cleaner . common . ConfigurationLoader ; import com . asakusafw . cleaner . testutil . UnitTestUtil ; public class LocalFileCleanerTest { private static final String propFile = "" ; private static final String propFile1 = "" ; private static final String propFile2 = "" ; private static final String propFile3 = "" ; private static final String propFile4 = "" ; private static final String propFile5 = "" ; private static final File cleanDir01 = new File ( "" ) ; private File tempDir = null ; private File logDir = null ; private File confFile = null ; private File readmeFile = null ; private File dir11_1 = null ; private File dir11_2 = null ; private File file11_3 = null ; private File fileData1 = null ; private File fileData2 = null ; private File dirData3 = null ; private static final File cleanDir02 = new File ( "" ) ; private File fileImportData1 = null ; private File fileImportData2 = null ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { UnitTestUtil . startUp ( ) ; cleanDir01 . mkdir ( ) ; cleanDir02 . mkdir ( ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . clear ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; cleanDir01 . delete ( ) ; cleanDir02 . delete ( ) ; } @ Test public void executeTest01 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , propFile } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertFalse ( confFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest02 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , propFile } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertFalse ( tempDir . exists ( ) ) ; assertFalse ( logDir . exists ( ) ) ; assertFalse ( confFile . exists ( ) ) ; assertFalse ( dir11_1 . exists ( ) ) ; assertFalse ( dir11_2 . exists ( ) ) ; assertFalse ( file11_3 . exists ( ) ) ; assertFalse ( fileData1 . exists ( ) ) ; assertFalse ( fileData2 . exists ( ) ) ; assertFalse ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest03 ( ) throws Exception { createCleanDir01 ( ) ; createCleanDir02 ( ) ; long now = new Date ( ) . getTime ( ) ; long past = now - ( * * * * ) ; confFile . setLastModified ( now ) ; file11_3 . setLastModified ( past ) ; fileData1 . setLastModified ( past ) ; fileData2 . setLastModified ( now ) ; fileImportData1 . setLastModified ( past ) ; fileImportData2 . setLastModified ( past ) ; tempDir . setLastModified ( past ) ; logDir . setLastModified ( past ) ; dir11_1 . setLastModified ( past ) ; dir11_2 . setLastModified ( past ) ; dirData3 . setLastModified ( past ) ; String [ ] args = new String [ ] { "" , propFile1 } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertFalse ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertFalse ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertFalse ( file11_3 . exists ( ) ) ; assertFalse ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertFalse ( dirData3 . exists ( ) ) ; assertTrue ( cleanDir02 . exists ( ) ) ; assertFalse ( fileImportData1 . exists ( ) ) ; assertFalse ( fileImportData2 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; cleanDir ( cleanDir02 ) ; } @ Test public void executeTest04 ( ) throws Exception { createCleanDir01 ( ) ; createCleanDir02 ( ) ; long now = new Date ( ) . getTime ( ) ; long past = now - ( * * * * ) ; confFile . setLastModified ( past ) ; file11_3 . setLastModified ( past ) ; fileData1 . setLastModified ( past ) ; fileData2 . setLastModified ( past ) ; fileImportData1 . setLastModified ( past ) ; fileImportData2 . setLastModified ( past ) ; tempDir . setLastModified ( past ) ; logDir . setLastModified ( now ) ; dir11_1 . setLastModified ( now ) ; dir11_2 . setLastModified ( past ) ; dirData3 . setLastModified ( past ) ; String [ ] args = new String [ ] { "" , propFile1 } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertFalse ( confFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertFalse ( dir11_2 . exists ( ) ) ; assertFalse ( file11_3 . exists ( ) ) ; assertFalse ( fileData1 . exists ( ) ) ; assertFalse ( fileData2 . exists ( ) ) ; assertFalse ( dirData3 . exists ( ) ) ; assertTrue ( cleanDir02 . exists ( ) ) ; assertFalse ( fileImportData1 . exists ( ) ) ; assertFalse ( fileImportData2 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; cleanDir ( cleanDir02 ) ; } @ Test public void executeTest05 ( ) throws Exception { String [ ] args = new String [ ] { "" , propFile1 , "" } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; args = new String [ ] { } ; result = cleaner . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest06 ( ) throws Exception { String [ ] args = new String [ ] { "" , propFile1 } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest07 ( ) throws Exception { createCleanDir02 ( ) ; String [ ] args = new String [ ] { "" , propFile2 } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; cleanDir ( cleanDir02 ) ; } @ Test public void executeTest08 ( ) throws Exception { String [ ] args = new String [ ] { "" , propFile } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) { @ Override protected LocalFileCleanerBean [ ] getCleanLocalDirs ( ) { throw new NullPointerException ( ) ; } } ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest09 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , propFile3 } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertFalse ( readmeFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest10 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , propFile3 } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertFalse ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertFalse ( readmeFile . exists ( ) ) ; assertFalse ( dir11_1 . exists ( ) ) ; assertFalse ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertFalse ( fileData1 . exists ( ) ) ; assertFalse ( fileData2 . exists ( ) ) ; assertFalse ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest11 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , propFile4 } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertTrue ( readmeFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest12 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , propFile5 } ; LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertTrue ( readmeFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } public void createCleanDir01 ( ) throws IOException { cleanDir01 . mkdir ( ) ; tempDir = new File ( cleanDir01 , "" ) ; tempDir . mkdir ( ) ; logDir = new File ( cleanDir01 , "" ) ; logDir . mkdir ( ) ; confFile = new File ( cleanDir01 , "" ) ; confFile . createNewFile ( ) ; readmeFile = new File ( cleanDir01 , "" ) ; readmeFile . createNewFile ( ) ; dir11_1 = new File ( tempDir , "" ) ; dir11_1 . mkdir ( ) ; dir11_2 = new File ( tempDir , "" ) ; dir11_2 . mkdir ( ) ; file11_3 = new File ( tempDir , "" ) ; file11_3 . createNewFile ( ) ; fileData1 = new File ( dir11_2 , "" ) ; fileData1 . createNewFile ( ) ; fileData2 = new File ( dir11_2 , "" ) ; fileData2 . createNewFile ( ) ; dirData3 = new File ( dir11_2 , "" ) ; dirData3 . mkdir ( ) ; } public void createCleanDir02 ( ) throws IOException { cleanDir02 . mkdir ( ) ; fileImportData1 = new File ( cleanDir02 , "" ) ; fileImportData1 . createNewFile ( ) ; fileImportData2 = new File ( cleanDir02 , "" ) ; fileImportData2 . createNewFile ( ) ; } public void cleanDir ( File cleandir ) throws IOException { File [ ] listFiles = cleandir . listFiles ( ) ; for ( File file : listFiles ) { if ( file . isFile ( ) ) { file . delete ( ) ; } if ( file . isDirectory ( ) ) { FileUtils . deleteDirectory ( file ) ; } } cleandir . delete ( ) ; } } package com . asakusafw . cleaner . main ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . net . URI ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Date ; import java . util . Properties ; import org . apache . commons . io . FileUtils ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . junit . After ; import org . junit . AfterClass ; import org . junit . Before ; import org . junit . BeforeClass ; import org . junit . Test ; import com . asakusafw . cleaner . common . ConfigurationLoader ; import com . asakusafw . cleaner . testutil . UnitTestUtil ; public class HDFSCleanerTest { private static final String propFile = "" ; private static final String propFile1 = "" ; private static final String propFile2 = "" ; private static final String propFile3 = "" ; private static final String propFile4 = "" ; private static final String propFile5 = "" ; private static final String propFile6 = "" ; private static final File cleanDir01 = new File ( "" ) ; private File tempDir = null ; private File logDir = null ; private File confFile = null ; private File readmeFile = null ; private File dir11_1 = null ; private File dir11_2 = null ; private File file11_3 = null ; private File fileData1 = null ; private File fileData2 = null ; private File dirData3 = null ; private static final File cleanDir02 = new File ( "" ) ; private File fileImportData1 = null ; private File fileImportData2 = null ; @ BeforeClass public static void setUpBeforeClass ( ) throws Exception { UnitTestUtil . setUpBeforeClass ( ) ; UnitTestUtil . setUpEnv ( ) ; } @ AfterClass public static void tearDownAfterClass ( ) throws Exception { UnitTestUtil . tearDownAfterClass ( ) ; } @ Before public void setUp ( ) throws Exception { UnitTestUtil . startUp ( ) ; cleanDir01 . mkdir ( ) ; cleanDir02 . mkdir ( ) ; Properties p = ConfigurationLoader . getProperty ( ) ; p . clear ( ) ; } @ After public void tearDown ( ) throws Exception { UnitTestUtil . tearDown ( ) ; cleanDir01 . delete ( ) ; cleanDir02 . delete ( ) ; } @ Test public void executeTest01 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , "" , propFile } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertFalse ( confFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest02 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , "" , propFile } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertFalse ( tempDir . exists ( ) ) ; assertFalse ( logDir . exists ( ) ) ; assertFalse ( confFile . exists ( ) ) ; assertFalse ( dir11_1 . exists ( ) ) ; assertFalse ( dir11_2 . exists ( ) ) ; assertFalse ( file11_3 . exists ( ) ) ; assertFalse ( fileData1 . exists ( ) ) ; assertFalse ( fileData2 . exists ( ) ) ; assertFalse ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest03 ( ) throws Exception { createCleanDir01 ( ) ; createCleanDir02 ( ) ; long now = new Date ( ) . getTime ( ) ; long past = now - ( * * * * ) ; confFile . setLastModified ( now ) ; file11_3 . setLastModified ( past ) ; fileData1 . setLastModified ( past ) ; fileData2 . setLastModified ( now ) ; fileImportData1 . setLastModified ( past ) ; fileImportData2 . setLastModified ( past ) ; tempDir . setLastModified ( past ) ; logDir . setLastModified ( past ) ; dir11_1 . setLastModified ( past ) ; dir11_2 . setLastModified ( past ) ; dirData3 . setLastModified ( past ) ; String [ ] args = new String [ ] { "" , "" , propFile1 } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertFalse ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertFalse ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertFalse ( file11_3 . exists ( ) ) ; assertFalse ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertFalse ( dirData3 . exists ( ) ) ; assertTrue ( cleanDir02 . exists ( ) ) ; assertFalse ( fileImportData1 . exists ( ) ) ; assertFalse ( fileImportData2 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; cleanDir ( cleanDir02 ) ; } @ Test public void executeTest04 ( ) throws Exception { createCleanDir01 ( ) ; createCleanDir02 ( ) ; long now = new Date ( ) . getTime ( ) ; long past = now - ( * * * * ) ; confFile . setLastModified ( past ) ; file11_3 . setLastModified ( past ) ; fileData1 . setLastModified ( past ) ; fileData2 . setLastModified ( past ) ; fileImportData1 . setLastModified ( past ) ; fileImportData2 . setLastModified ( past ) ; tempDir . setLastModified ( past ) ; logDir . setLastModified ( now ) ; dir11_1 . setLastModified ( now ) ; dir11_2 . setLastModified ( past ) ; dirData3 . setLastModified ( past ) ; String [ ] args = new String [ ] { "" , "" , propFile1 } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertFalse ( confFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertFalse ( dir11_2 . exists ( ) ) ; assertFalse ( file11_3 . exists ( ) ) ; assertFalse ( fileData1 . exists ( ) ) ; assertFalse ( fileData2 . exists ( ) ) ; assertFalse ( dirData3 . exists ( ) ) ; assertTrue ( cleanDir02 . exists ( ) ) ; assertFalse ( fileImportData1 . exists ( ) ) ; assertFalse ( fileImportData2 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; cleanDir ( cleanDir02 ) ; } @ Test public void executeTest05 ( ) throws Exception { String [ ] args = new String [ ] { "" , "" , propFile , "" } ; HDFSCleaner cleaner = new HDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; args = new String [ ] { } ; result = cleaner . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest06 ( ) throws Exception { String [ ] args = new String [ ] { "" , "" , propFile } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest07 ( ) throws Exception { createCleanDir02 ( ) ; String [ ] args = new String [ ] { "" , "" , propFile2 } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; cleanDir ( cleanDir02 ) ; } @ Test public void executeTest08 ( ) throws Exception { String [ ] args = new String [ ] { "" , "" , propFile } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) { @ Override protected Path createPath ( String strCleanPath ) { return new Path ( "" ) ; } } ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest09 ( ) throws Exception { String [ ] args = new String [ ] { "" , "" , propFile } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) { @ Override protected Path createPath ( String strCleanPath ) { throw new NullPointerException ( ) ; } } ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; } @ Test public void executeTest10 ( ) throws Exception { createCleanDir01 ( ) ; createCleanDir02 ( ) ; String [ ] args = new String [ ] { "" , "" , propFile3 } ; StubHDFSCleaner cleaner = new StubHDFSCleaner ( true ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; ArrayList < String > instanceId = cleaner . getInstanceId ( ) ; assertEquals ( , instanceId . size ( ) ) ; assertEquals ( "" , instanceId . get ( ) ) ; assertEquals ( "" , instanceId . get ( ) ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertFalse ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; assertTrue ( cleanDir02 . exists ( ) ) ; assertFalse ( fileImportData1 . exists ( ) ) ; assertFalse ( fileImportData2 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; cleanDir ( cleanDir02 ) ; } @ Test public void executeTest11 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , "" , propFile4 } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertFalse ( readmeFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest12 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , "" , propFile4 } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertFalse ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertFalse ( readmeFile . exists ( ) ) ; assertFalse ( dir11_1 . exists ( ) ) ; assertFalse ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertFalse ( fileData1 . exists ( ) ) ; assertFalse ( fileData2 . exists ( ) ) ; assertFalse ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest13 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , "" , propFile5 } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertTrue ( readmeFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } @ Test public void executeTest14 ( ) throws Exception { createCleanDir01 ( ) ; String [ ] args = new String [ ] { "" , "" , propFile6 } ; HDFSCleaner cleaner = new StubHDFSCleaner ( ) ; int result = cleaner . execute ( args ) ; assertEquals ( , result ) ; assertTrue ( cleanDir01 . exists ( ) ) ; assertTrue ( tempDir . exists ( ) ) ; assertTrue ( logDir . exists ( ) ) ; assertTrue ( confFile . exists ( ) ) ; assertTrue ( readmeFile . exists ( ) ) ; assertTrue ( dir11_1 . exists ( ) ) ; assertTrue ( dir11_2 . exists ( ) ) ; assertTrue ( file11_3 . exists ( ) ) ; assertTrue ( fileData1 . exists ( ) ) ; assertTrue ( fileData2 . exists ( ) ) ; assertTrue ( dirData3 . exists ( ) ) ; cleanDir ( cleanDir01 ) ; } private void createCleanDir01 ( ) throws IOException { cleanDir01 . mkdir ( ) ; tempDir = new File ( cleanDir01 , "" ) ; tempDir . mkdir ( ) ; logDir = new File ( cleanDir01 , "" ) ; logDir . mkdir ( ) ; confFile = new File ( cleanDir01 , "" ) ; confFile . createNewFile ( ) ; readmeFile = new File ( cleanDir01 , "" ) ; readmeFile . createNewFile ( ) ; dir11_1 = new File ( tempDir , "" ) ; dir11_1 . mkdir ( ) ; dir11_2 = new File ( tempDir , "" ) ; dir11_2 . mkdir ( ) ; file11_3 = new File ( tempDir , "" ) ; file11_3 . createNewFile ( ) ; fileData1 = new File ( dir11_2 , "" ) ; fileData1 . createNewFile ( ) ; fileData2 = new File ( dir11_2 , "" ) ; fileData2 . createNewFile ( ) ; dirData3 = new File ( dir11_2 , "" ) ; dirData3 . mkdir ( ) ; } private void createCleanDir02 ( ) throws IOException { cleanDir02 . mkdir ( ) ; fileImportData1 = new File ( cleanDir02 , "" ) ; fileImportData1 . createNewFile ( ) ; fileImportData2 = new File ( cleanDir02 , "" ) ; fileImportData2 . createNewFile ( ) ; } private void cleanDir ( File cleandir ) throws IOException { File [ ] listFiles = cleandir . listFiles ( ) ; for ( File file : listFiles ) { if ( file . isFile ( ) ) { file . delete ( ) ; } if ( file . isDirectory ( ) ) { FileUtils . deleteDirectory ( file ) ; } } cleandir . delete ( ) ; } } class StubHDFSCleaner extends HDFSCleaner { boolean exec = false ; public StubHDFSCleaner ( ) { super ( new Configuration ( ) ) ; } public StubHDFSCleaner ( boolean exec ) { super ( new Configuration ( ) ) ; this . exec = exec ; } ArrayList < String > instanceId = new ArrayList < String > ( ) ; @ Override protected Path createPath ( String strCleanPath ) { File file = new File ( strCleanPath ) ; URI uri = file . toURI ( ) ; return new Path ( uri . getPath ( ) ) ; } @ Override protected boolean isRunningJobFlow ( String executionId ) { instanceId . add ( executionId ) ; return exec ; } public ArrayList < String > getInstanceId ( ) { Collections . sort ( instanceId ) ; return instanceId ; } } package com . asakusafw . cleaner . testutil ; import java . io . File ; import java . util . Properties ; import org . apache . commons . io . FileUtils ; import com . asakusafw . cleaner . common . ConfigurationLoader ; import com . asakusafw . cleaner . common . Constants ; public class UnitTestUtil { private static final File targetDir = new File ( "" ) ; public static void setUpEnv ( ) throws Exception { Properties p = System . getProperties ( ) ; p . setProperty ( Constants . CLEAN_HOME , "" ) ; ConfigurationLoader . setSysProp ( p ) ; System . setProperties ( p ) ; } public static void tearDownEnv ( ) throws Exception { Properties p = System . getProperties ( ) ; p . clear ( ) ; ConfigurationLoader . setSysProp ( p ) ; System . setProperties ( p ) ; } public static void setUpBeforeClass ( ) throws Exception { targetDir . mkdir ( ) ; } public static void tearDownAfterClass ( ) throws Exception { FileUtils . deleteDirectory ( targetDir ) ; } public static void startUp ( ) throws Exception { } public static void tearDown ( ) throws Exception { } } package com . asakusafw . cleaner . log ; import java . sql . Timestamp ; import java . text . DateFormat ; import java . text . SimpleDateFormat ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . apache . log4j . MDC ; public final class Log { private static final String LOG_TSTAMP_NULL_STR = "" ; private static final String LOG_MESSAGE_ID_NULL_STR = "" ; private static final String LOG_MESSAGE_ARG_NULL_STR = "" ; private Log ( ) { return ; } public static String log ( Class < ? > clazz , String messageId , Object ... messageArgs ) { return Log . log ( null , clazz , messageId , messageArgs ) ; } public static String log ( Throwable t , Class < ? > clazz , String messageId , Object ... messageArgs ) { if ( ! LogInitializer . isInitialized ( ) ) { return null ; } String message = LogMessageManager . getInstance ( ) . createLogMessage ( messageId , Log . changeNullToStr ( messageArgs , LOG_MESSAGE_ARG_NULL_STR ) ) ; Level level = LogMessageManager . getInstance ( ) . getLogLevel ( messageId ) ; Timestamp logTime = new Timestamp ( System . currentTimeMillis ( ) ) ; Log . setMDC ( messageId , logTime ) ; Log . writeLog ( t , clazz , level , message ) ; Log . resetMDC ( ) ; return message ; } private static void setMDC ( String messageId , Timestamp logTime ) { DateFormat dateFormat = new SimpleDateFormat ( "" ) ; MDC . put ( "" , dateFormat . format ( logTime ) ) ; MDC . put ( "" , messageId ) ; } private static void resetMDC ( ) { MDC . put ( "" , LOG_TSTAMP_NULL_STR ) ; MDC . put ( "" , LOG_MESSAGE_ID_NULL_STR ) ; } private static void writeLog ( Throwable t , Class < ? > clazz , Level level , String message ) { Logger logger = Logger . getLogger ( clazz ) ; if ( logger . isEnabledFor ( level ) ) { if ( Level . DEBUG == level ) { logger . debug ( message , t ) ; } else if ( Level . INFO == level ) { logger . info ( message , t ) ; } else if ( Level . WARN == level ) { logger . warn ( message , t ) ; } else if ( Level . ERROR == level ) { logger . error ( message , t ) ; } else if ( Level . FATAL == level ) { logger . fatal ( message , t ) ; } } } private static Object [ ] changeNullToStr ( Object [ ] objects , String str ) { Object [ ] newObjects = new Object [ objects . length ] ; for ( int i = ; i < objects . length ; i ++ ) { if ( objects [ i ] == null ) { newObjects [ i ] = str ; } else { newObjects [ i ] = objects [ i ] ; } } return newObjects ; } } package com . asakusafw . cleaner . log ; import java . math . BigDecimal ; import java . text . MessageFormat ; import java . util . Date ; import java . util . HashMap ; import java . util . Map ; import org . apache . commons . lang . ArrayUtils ; import org . apache . commons . lang . ObjectUtils ; import org . apache . commons . lang . StringUtils ; import org . apache . log4j . Level ; public class LogMessageManager { private static final String MESSAGE_ID_NOT_FOUND = "" ; private static final String ILLEGAL_SIZE = "" ; private Map < String , Level > levelMap = new HashMap < String , Level > ( ) ; private Map < String , String > templateMap = new HashMap < String , String > ( ) ; private Map < String , Integer > sizeMap = new HashMap < String , Integer > ( ) ; private static LogMessageManager instance = new LogMessageManager ( ) ; protected LogMessageManager ( ) { return ; } public static LogMessageManager getInstance ( ) { return LogMessageManager . instance ; } public void putLevel ( String messageId , String level ) { levelMap . put ( messageId , Level . toLevel ( level ) ) ; } public void putTemplate ( String messageId , String templates ) { templateMap . put ( messageId , templates ) ; } public void putSize ( String messageId , Integer index ) { sizeMap . put ( messageId , index ) ; } public String createLogMessage ( String messageId , Object ... messageArgs ) { Object [ ] messageArgsConverted = toStringMessageArgs ( messageArgs ) ; String templateStr = templateMap . get ( messageId ) ; if ( templateStr == null ) { String message = MessageFormat . format ( MESSAGE_ID_NOT_FOUND , messageId , StringUtils . join ( messageArgsConverted , "" ) ) ; return message ; } Integer index = sizeMap . get ( messageId ) ; if ( index != null ) { if ( messageArgsConverted . length != index . intValue ( ) ) { String message = MessageFormat . format ( ILLEGAL_SIZE , new Date ( ) , messageId , StringUtils . join ( messageArgsConverted , "" ) ) ; System . err . println ( message ) ; } } return MessageFormat . format ( templateStr , messageArgsConverted ) ; } public Level getLogLevel ( String messageId ) { Level level = levelMap . get ( messageId ) ; if ( level == null ) { return Level . ERROR ; } return level ; } private Object [ ] toStringMessageArgs ( Object [ ] messageArgs ) { if ( messageArgs == null ) { return messageArgs ; } Object [ ] messageArgsConverted = new Object [ messageArgs . length ] ; for ( int i = ; i < messageArgs . length ; i ++ ) { Object obj = messageArgs [ i ] ; if ( obj == null ) { messageArgsConverted [ i ] = null ; } else if ( obj . getClass ( ) . isArray ( ) ) { messageArgsConverted [ i ] = ArrayUtils . toString ( obj ) ; } else if ( obj instanceof Long || obj instanceof Integer || obj instanceof BigDecimal ) { messageArgsConverted [ i ] = ObjectUtils . toString ( obj , "" ) ; } else { messageArgsConverted [ i ] = messageArgs [ i ] ; } } return messageArgsConverted ; } } package com . asakusafw . cleaner . log ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . apache . log4j . xml . DOMConfigurator ; public final class LogInitializer { private static boolean isInitialized = false ; private LogInitializer ( ) { return ; } public static void execute ( String logConfFilePath ) throws IOException { loadFile ( logConfFilePath ) ; LogMessageLoader . loadFile ( LogMessageManager . getInstance ( ) ) ; isInitialized = true ; } static void loadFile ( String filePath ) throws FileNotFoundException { File file = new File ( filePath ) ; if ( ! file . exists ( ) ) { throw new FileNotFoundException ( filePath ) ; } DOMConfigurator . configure ( filePath ) ; } public static boolean isInitialized ( ) { return isInitialized ; } } package com . asakusafw . cleaner . log ; package com . asakusafw . cleaner . log ; import java . io . IOException ; import java . io . InputStream ; import java . util . Enumeration ; import java . util . Properties ; import org . apache . commons . io . IOUtils ; import org . apache . commons . lang . math . NumberUtils ; import com . asakusafw . cleaner . common . Constants ; final class LogMessageLoader { private static final String LEVEL_KEY_END = "" ; private static final String TEMPLATE_KEY_END = "" ; private static final String SIZE_KEY_END = "" ; private LogMessageLoader ( ) { return ; } static void loadFile ( LogMessageManager manager ) throws IOException { InputStream in = null ; Properties props = new Properties ( ) ; try { in = LogMessageLoader . class . getClassLoader ( ) . getResourceAsStream ( Constants . LOG_MESSAGE_FILE ) ; props . load ( in ) ; Enumeration < ? > keys = props . propertyNames ( ) ; while ( keys . hasMoreElements ( ) ) { String key = ( String ) keys . nextElement ( ) ; if ( key . endsWith ( LEVEL_KEY_END ) ) { String messageId = LogMessageLoader . getMessageId ( key , LEVEL_KEY_END ) ; manager . putLevel ( messageId , props . getProperty ( key ) ) ; } else if ( key . endsWith ( TEMPLATE_KEY_END ) ) { String messageId = LogMessageLoader . getMessageId ( key , TEMPLATE_KEY_END ) ; manager . putTemplate ( messageId , props . getProperty ( key ) ) ; } else if ( key . endsWith ( SIZE_KEY_END ) ) { String messageId = LogMessageLoader . getMessageId ( key , SIZE_KEY_END ) ; String sizeStr = props . getProperty ( key ) ; if ( NumberUtils . isNumber ( sizeStr ) ) { manager . putSize ( messageId , Integer . valueOf ( sizeStr ) ) ; } } } } catch ( IOException ex ) { throw new IOException ( "" + Constants . LOG_MESSAGE_FILE , ex ) ; } finally { IOUtils . closeQuietly ( in ) ; } } private static String getMessageId ( String key , String endStr ) { String [ ] splits = key . split ( "" ) ; return splits [ ] ; } } package com . asakusafw . cleaner . common ; package com . asakusafw . cleaner . common ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import com . asakusafw . cleaner . exception . CleanerSystemException ; public final class ConfigurationLoader { private static Properties prop = new Properties ( ) ; private static Map < String , String > env = null ; private static Properties sysProp = null ; private ConfigurationLoader ( ) { return ; } public static void cleanProp ( ) { prop = new Properties ( ) ; } public static void init ( String [ ] propertys , boolean doLocalCleanPropCheck , boolean doHDFSCleanPropCheck ) throws CleanerSystemException , Exception { env = System . getenv ( ) ; sysProp = System . getProperties ( ) ; checkEnv ( ) ; loadPropertyes ( propertys ) ; if ( doLocalCleanPropCheck ) { checkAndSetParamLocalFileClean ( ) ; } if ( doHDFSCleanPropCheck ) { checkAndSetParamHDFSClean ( ) ; } } protected static void checkEnv ( ) throws Exception { String cleanHome = getEnvProperty ( Constants . CLEAN_HOME ) ; if ( isEmpty ( cleanHome ) ) { System . err . println ( MessageFormat . format ( "" , Constants . CLEAN_HOME ) ) ; throw new Exception ( MessageFormat . format ( "" , Constants . CLEAN_HOME ) ) ; } File cleanHomeDir = new File ( cleanHome ) ; if ( ! cleanHomeDir . exists ( ) ) { System . err . println ( MessageFormat . format ( "" , Constants . CLEAN_HOME , cleanHome ) ) ; throw new Exception ( MessageFormat . format ( "" , Constants . CLEAN_HOME , cleanHome ) ) ; } } protected static void checkAndSetParamLocalFileClean ( ) throws CleanerSystemException { String keepDate = prop . getProperty ( Constants . PROP_KEY_LOCAL_FILE_KEEP_DATE ) ; if ( isEmpty ( keepDate ) ) { prop . setProperty ( Constants . PROP_KEY_LOCAL_FILE_KEEP_DATE , Constants . PROP_DEFAULT_LOCAL_FILE_KEEP_DATE ) ; } else { if ( ! isNumber ( keepDate , ) ) { throw new CleanerSystemException ( ConfigurationLoader . class , MessageIdConst . CMN_PROP_CHECK_ERROR , "" + keepDate ) ; } } List < String > cleanDirList = getPropStartWithString ( Constants . PROP_KEY_LOCAL_FILE_CLEAN_DIR + "" ) ; List < String > noEmptyList = getNoEmptyList ( cleanDirList ) ; if ( noEmptyList . size ( ) == ) { throw new CleanerSystemException ( ConfigurationLoader . class , MessageIdConst . CMN_PROP_CHECK_ERROR , "" ) ; } } protected static void checkAndSetParamHDFSClean ( ) throws CleanerSystemException { String keepDate = prop . getProperty ( Constants . PROP_KEY_HDFS_FILE_KEEP_DATE ) ; if ( isEmpty ( keepDate ) ) { prop . setProperty ( Constants . PROP_KEY_HDFS_FILE_KEEP_DATE , Constants . PROP_DEFAULT_HDFS_FILE_KEEP_DATE ) ; } else { if ( ! isNumber ( keepDate , ) ) { throw new CleanerSystemException ( ConfigurationLoader . class , MessageIdConst . CMN_PROP_CHECK_ERROR , "" + keepDate ) ; } } if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_HDFS_PROTCOL_HOST ) ) ) { throw new CleanerSystemException ( ConfigurationLoader . class , MessageIdConst . CMN_PROP_CHECK_ERROR , "" ) ; } List < String > cleanDirList = getPropStartWithString ( Constants . PROP_KEY_HDFS_FILE_CLEAN_DIR + "" ) ; List < String > noEmptyList = getNoEmptyList ( cleanDirList ) ; if ( noEmptyList . size ( ) == ) { throw new CleanerSystemException ( ConfigurationLoader . class , MessageIdConst . CMN_PROP_CHECK_ERROR , "" ) ; } } protected static void checkAndSetParam ( ) { if ( isEmpty ( prop . getProperty ( Constants . PROP_KEY_LOG_CONF_PATH ) ) ) { prop . setProperty ( Constants . PROP_KEY_LOG_CONF_PATH , Constants . PROP_DEFAULT_LOG_CONF_PATH ) ; } } private static void loadPropertyes ( String [ ] propertys ) throws IOException { FileInputStream fis = null ; for ( String strProp : propertys ) { File propFile = createPropFileName ( strProp ) ; try { fis = new FileInputStream ( propFile ) ; prop . load ( fis ) ; } catch ( IOException e ) { System . err . println ( "" + propFile . getAbsolutePath ( ) ) ; e . printStackTrace ( ) ; throw e ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } } private static File createPropFileName ( String propFileName ) { String cleanHome = ConfigurationLoader . getEnvProperty ( Constants . CLEAN_HOME ) ; File file1 = new File ( cleanHome , Constants . PROP_FILE_PATH ) ; File file2 = new File ( file1 , propFileName ) ; return file2 ; } public static List < String > getPropStartWithString ( String startString ) { Set < Object > propSet = prop . keySet ( ) ; List < String > list = new ArrayList < String > ( ) ; for ( Object strKey : propSet ) { String key = ( String ) strKey ; if ( key . startsWith ( startString ) ) { list . add ( key ) ; } } return list ; } public static List < String > getNoEmptyList ( List < String > list ) { List < String > resultList = new ArrayList < String > ( ) ; if ( list == null || list . size ( ) == ) { return resultList ; } for ( String key : list ) { String value = prop . getProperty ( key ) ; if ( ! isEmpty ( value ) ) { resultList . add ( key ) ; } } return resultList ; } private static boolean isEmpty ( String str ) { if ( str == null ) { return true ; } if ( "" . equals ( str ) ) { return true ; } return false ; } private static boolean isNumber ( String str , int min ) { try { long l = Long . parseLong ( str ) ; return l >= min ; } catch ( NumberFormatException e ) { return false ; } } public static String getProperty ( String key ) { return prop . getProperty ( key ) ; } public static String getEnvProperty ( String key ) { String strSysProp = sysProp . getProperty ( key ) ; String strEnv = env . get ( key ) ; if ( strSysProp != null ) { return strSysProp ; } else if ( strEnv != null ) { return strEnv ; } else { return null ; } } @ Deprecated public static void setProperty ( Properties p ) { prop = p ; } @ Deprecated public static Properties getProperty ( ) { return prop ; } @ Deprecated public static void setSysProp ( Properties p ) { sysProp = p ; } @ Deprecated public static void setEnv ( Map < String , String > m ) { env = m ; } } package com . asakusafw . cleaner . common ; public final class Constants { public static final int EXIT_CODE_SUCCESS = ; public static final int EXIT_CODE_ERROR = ; public static final int EXIT_CODE_WARNING = ; public static final String CLEAN_MODE_NOMAL = "" ; public static final String CLEAN_MODE_RECURSIVE = "" ; public static final String CLEAN_HOME = "" ; public static final String PROP_KEY_LOG_CONF_PATH = "" ; public static final String PROP_KEY_LOCAL_FILE_CLEAN_DIR = "" ; public static final String PROP_KEY_LOCAL_FILE_CLEAN_PATTERN = "" ; public static final String PROP_KEY_LOCAL_FILE_KEEP_DATE = "" ; public static final String PROP_KEY_HDFS_PROTCOL_HOST = "" ; public static final String PROP_KEY_HDFS_FILE_CLEAN_DIR = "" ; public static final String PROP_KEY_HDFS_FILE_CLEAN_PATTERN = "" ; public static final String PROP_KEY_HDFS_FILE_KEEP_DATE = "" ; public static final String PROP_DEFAULT_LOG_CONF_PATH = "" ; public static final String PROP_DEFAULT_LOCAL_FILE_KEEP_DATE = "" ; public static final String PROP_DEFAULT_HDFS_FILE_KEEP_DATE = "" ; public static final String LOG_MESSAGE_FILE = "" ; public static final String PROP_FILE_PATH = "" ; public static final String HDFSFIXED_PATH = "" ; public static final String HDFS_PATH_REPLACE_STR_USER = "" ; public static final String HDFS_PATH_REPLACE_STR_ID = "" ; private Constants ( ) { return ; } } package com . asakusafw . cleaner . common ; import com . asakusafw . cleaner . exception . CleanerSystemException ; import com . asakusafw . cleaner . log . Log ; import com . asakusafw . cleaner . log . LogInitializer ; public final class CleanerInitializer { private CleanerInitializer ( ) { return ; } public static boolean initLocalFileCleaner ( String [ ] properties ) { return initialize ( properties , true , false ) ; } public static boolean initDFSCleaner ( String [ ] properties ) { return initialize ( properties , false , true ) ; } private static boolean initialize ( String [ ] properties , boolean doLocalCleanPropCheck , boolean doDFSCleanPropCheck ) { try { ConfigurationLoader . init ( properties , doLocalCleanPropCheck , doDFSCleanPropCheck ) ; } catch ( CleanerSystemException e ) { if ( initLog ( ) ) { Log . log ( e . getCause ( ) , e . getClazz ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; return false ; } else { printPropLoadError ( properties , e ) ; return false ; } } catch ( Exception e ) { printPropLoadError ( properties , e ) ; return false ; } if ( ! initLog ( ) ) { return false ; } return true ; } private static boolean initLog ( ) { String logConfFilePath = null ; try { logConfFilePath = ConfigurationLoader . getProperty ( Constants . PROP_KEY_LOG_CONF_PATH ) ; LogInitializer . execute ( logConfFilePath ) ; return true ; } catch ( Exception e ) { System . err . println ( "" + e . getMessage ( ) + "" ) ; System . err . println ( "" + logConfFilePath ) ; e . printStackTrace ( ) ; return false ; } } private static void printPropLoadError ( String [ ] properties , Exception e ) { System . err . println ( "" + e . getMessage ( ) + "" ) ; System . err . println ( "" + System . getenv ( ) ) ; if ( properties == null ) { System . err . println ( "" ) ; } else { for ( int i = ; i < properties . length ; i ++ ) { System . err . println ( "" + i + "" + properties [ i ] ) ; } } e . printStackTrace ( ) ; } } package com . asakusafw . cleaner . common ; public final class MessageIdConst { public static final String CMN_PROP_CHECK_ERROR = "" ; public static final String LCLN_START = "" ; public static final String LCLN_EXIT_SUCCESS = "" ; public static final String LCLN_EXIT_WARNING = "" ; public static final String LCLN_INIT_ERROR = "" ; public static final String LCLN_EXCEPRION = "" ; public static final String LCLN_PARAMCHECK_ERROR = "" ; public static final String LCLN_CLEN_DIR_SUCCESS = "" ; public static final String LCLN_CLEN_DIR_FAIL = "" ; public static final String LCLN_CLEN_DIR_ERROR = "" ; public static final String LCLN_CLEN_FAIL = "" ; public static final String LCLN_CLEN_FILE = "" ; public static final String LCLN_FILE_DELETE = "" ; public static final String LCLN_FILE_DELETE_SUCCESS = "" ; public static final String LCLN_DIR_DELETE = "" ; public static final String LCLN_PATTERN_FAIL = "" ; public static final String LCLN_DELETE_FILE = "" ; public static final String LCLN_PATTERN_NOT_FOUND = "" ; public static final String HCLN_START = "" ; public static final String HCLN_EXIT_SUCCESS = "" ; public static final String HCLN_EXIT_WARNING = "" ; public static final String HCLN_INIT_ERROR = "" ; public static final String HCLN_EXCEPRION = "" ; public static final String HCLN_PARAMCHECK_ERROR = "" ; public static final String HCLN_CLEN_DIR_SUCCESS = "" ; public static final String HCLN_CLEN_DIR_FAIL = "" ; public static final String HCLN_CLEN_DIR_ERROR = "" ; public static final String HCLN_CLEN_FAIL = "" ; public static final String HCLN_CLEN_DIR_EXCEPTION = "" ; public static final String HCLN_CLEN_DIR_EXEC = "" ; public static final String HCLN_CLEN_FILE = "" ; public static final String HCLN_FILE_DELETE = "" ; public static final String HCLN_FILE_DELETE_SUCCESS = "" ; public static final String HCLN_DIR_DELETE = "" ; public static final String HCLN_PATTERN_FAIL = "" ; public static final String HCLN_DELETE_FILE = "" ; public static final String HCLN_PATTERN_NOT_FOUND = "" ; private MessageIdConst ( ) { return ; } } package com . asakusafw . cleaner . main ; package com . asakusafw . cleaner . main ; import java . io . File ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import java . util . regex . PatternSyntaxException ; import com . asakusafw . cleaner . bean . LocalFileCleanerBean ; import com . asakusafw . cleaner . common . CleanerInitializer ; import com . asakusafw . cleaner . common . ConfigurationLoader ; import com . asakusafw . cleaner . common . Constants ; import com . asakusafw . cleaner . common . MessageIdConst ; import com . asakusafw . cleaner . exception . CleanerSystemException ; import com . asakusafw . cleaner . log . Log ; public class LocalFileCleaner { private static final Class < ? > CLASS = LocalFileCleaner . class ; public static void main ( String [ ] args ) { LocalFileCleaner cleaner = new LocalFileCleaner ( ) ; int result = cleaner . execute ( args ) ; System . exit ( result ) ; } protected int execute ( String [ ] args ) { String [ ] prop = new String [ ] ; String mode = null ; if ( args . length > ) { mode = args [ ] ; } if ( args . length > ) { prop [ ] = args [ ] ; } if ( args . length != ) { System . err . println ( "" + args . length + "" + mode + "" + prop [ ] ) ; return Constants . EXIT_CODE_ERROR ; } try { if ( ! CleanerInitializer . initLocalFileCleaner ( prop ) ) { Log . log ( CLASS , MessageIdConst . LCLN_INIT_ERROR , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_ERROR ; } Log . log ( CLASS , MessageIdConst . LCLN_START , new Date ( ) , mode , prop [ ] ) ; boolean recursive = false ; if ( Constants . CLEAN_MODE_NOMAL . equals ( mode ) ) { recursive = false ; } else if ( Constants . CLEAN_MODE_RECURSIVE . equals ( mode ) ) { recursive = true ; } else { Log . log ( CLASS , MessageIdConst . LCLN_PARAMCHECK_ERROR , "" , mode , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_ERROR ; } LocalFileCleanerBean [ ] bean = null ; try { bean = getCleanLocalDirs ( ) ; } catch ( CleanerSystemException e ) { Log . log ( e . getCause ( ) , e . getClazz ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; return Constants . EXIT_CODE_ERROR ; } int keepDate = getLocalFileKeepDate ( ) ; boolean cleanResult = true ; Date now = new Date ( ) ; for ( int i = ; i < bean . length ; i ++ ) { try { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_FILE , bean [ i ] . getCleanDir ( ) . getAbsolutePath ( ) , bean [ i ] . getPattern ( ) , keepDate , mode , now ) ; if ( cleanDir ( bean [ i ] . getCleanDir ( ) , bean [ i ] . getPattern ( ) , keepDate , now , recursive ) ) { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_DIR_SUCCESS , bean [ i ] . getCleanDir ( ) . getAbsolutePath ( ) , keepDate , mode ) ; } else { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_DIR_FAIL , bean [ i ] . getCleanDir ( ) . getAbsolutePath ( ) , keepDate , mode ) ; cleanResult = false ; } } catch ( CleanerSystemException e ) { Log . log ( e . getCause ( ) , e . getClazz ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; cleanResult = false ; } } if ( cleanResult ) { Log . log ( CLASS , MessageIdConst . LCLN_EXIT_SUCCESS , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_SUCCESS ; } else { Log . log ( CLASS , MessageIdConst . LCLN_EXIT_WARNING , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_WARNING ; } } catch ( Exception e ) { try { Log . log ( e , CLASS , MessageIdConst . LCLN_EXCEPRION , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e1 ) { System . err . print ( "" ) ; e1 . printStackTrace ( ) ; return Constants . EXIT_CODE_ERROR ; } } } private boolean cleanDir ( File creanDir , String pattern , int keepDate , Date now , boolean recursive ) throws CleanerSystemException { if ( creanDir == null || ! creanDir . exists ( ) ) { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_DIR_ERROR , "" , creanDir ) ; return false ; } if ( ! creanDir . isDirectory ( ) ) { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_DIR_ERROR , "" , creanDir ) ; return false ; } Log . log ( CLASS , MessageIdConst . LCLN_FILE_DELETE , creanDir . getAbsolutePath ( ) ) ; int cleanFileCount = ; int cleanDirCount = ; boolean result = true ; File [ ] files = getListFiles ( creanDir ) ; for ( int i = ; i < files . length ; i ++ ) { long lastModifiedTime = files [ i ] . lastModified ( ) ; if ( files [ i ] . isDirectory ( ) && recursive ) { File [ ] childFiles = getListFiles ( files [ i ] ) ; if ( childFiles . length == ) { if ( isExpired ( lastModifiedTime , keepDate , now ) ) { if ( ! files [ i ] . delete ( ) ) { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_FAIL , "" , files [ i ] . getAbsolutePath ( ) ) ; result = false ; } else { cleanDirCount ++ ; Log . log ( CLASS , MessageIdConst . LCLN_DIR_DELETE , files [ i ] . getAbsolutePath ( ) ) ; } } } else { if ( cleanDir ( files [ i ] , pattern , keepDate , now , recursive ) ) { childFiles = getListFiles ( files [ i ] ) ; if ( childFiles . length == ) { if ( isExpired ( lastModifiedTime , keepDate , now ) ) { if ( ! files [ i ] . delete ( ) ) { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_FAIL , "" , files [ i ] . getAbsolutePath ( ) ) ; result = false ; } else { cleanDirCount ++ ; Log . log ( CLASS , MessageIdConst . LCLN_DIR_DELETE , files [ i ] . getAbsolutePath ( ) ) ; } } } } else { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_FAIL , "" , files [ i ] . getAbsolutePath ( ) ) ; result = false ; } } } else if ( files [ i ] . isFile ( ) ) { if ( isExpired ( lastModifiedTime , keepDate , now ) && isMatchPattern ( files [ i ] , pattern ) ) { if ( ! files [ i ] . delete ( ) ) { Log . log ( CLASS , MessageIdConst . LCLN_CLEN_FAIL , "" , files [ i ] . getAbsolutePath ( ) ) ; result = false ; } else { Log . log ( CLASS , MessageIdConst . LCLN_DELETE_FILE , files [ i ] . getAbsolutePath ( ) ) ; cleanFileCount ++ ; } } } } Log . log ( CLASS , MessageIdConst . LCLN_FILE_DELETE_SUCCESS , creanDir . getAbsolutePath ( ) , cleanDirCount , cleanFileCount ) ; return result ; } private File [ ] getListFiles ( File dir ) { File [ ] child = dir . listFiles ( ) ; if ( child == null ) { child = new File [ ] ; } return child ; } private boolean isMatchPattern ( File file , String pattern ) throws CleanerSystemException { if ( pattern == null || pattern . equals ( "" ) ) { return true ; } else { String strFile = file . getAbsolutePath ( ) ; try { Matcher m = Pattern . compile ( pattern ) . matcher ( strFile ) ; return m . matches ( ) ; } catch ( PatternSyntaxException e ) { throw new CleanerSystemException ( e , this . getClass ( ) , MessageIdConst . LCLN_PATTERN_FAIL , pattern ) ; } } } private boolean isExpired ( long lastModifiedTime , int keepDate , Date now ) { long keepTime = ( keepDate ) * * * * ; long period = lastModifiedTime + keepTime ; return now . getTime ( ) > period ; } protected int getLocalFileKeepDate ( ) { return Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_LOCAL_FILE_KEEP_DATE ) ) ; } protected LocalFileCleanerBean [ ] getCleanLocalDirs ( ) throws CleanerSystemException { List < String > cleanDirList = ConfigurationLoader . getPropStartWithString ( Constants . PROP_KEY_LOCAL_FILE_CLEAN_DIR + "" ) ; List < String > noEmptyDirList = ConfigurationLoader . getNoEmptyList ( cleanDirList ) ; int listSize = noEmptyDirList . size ( ) ; List < LocalFileCleanerBean > list = new ArrayList < LocalFileCleanerBean > ( ) ; for ( int i = ; i < listSize ; i ++ ) { LocalFileCleanerBean bean = new LocalFileCleanerBean ( ) ; String dirKey = noEmptyDirList . get ( i ) ; String strDir = ConfigurationLoader . getProperty ( dirKey ) ; bean . setCleanDir ( new File ( strDir ) ) ; String number = dirKey . substring ( dirKey . lastIndexOf ( "" ) + , dirKey . length ( ) ) ; String pattarnKey = Constants . PROP_KEY_LOCAL_FILE_CLEAN_PATTERN + "" + number ; String pattern = ConfigurationLoader . getProperty ( pattarnKey ) ; if ( pattern == null || pattern . equals ( "" ) ) { throw new CleanerSystemException ( this . getClass ( ) , MessageIdConst . LCLN_PATTERN_NOT_FOUND , dirKey , strDir , pattarnKey ) ; } else { bean . setPattern ( pattern ) ; } list . add ( bean ) ; } return list . toArray ( new LocalFileCleanerBean [ list . size ( ) ] ) ; } } package com . asakusafw . cleaner . main ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import java . util . regex . PatternSyntaxException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . FileUtil ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . util . Tool ; import com . asakusafw . cleaner . bean . DFSCleanerBean ; import com . asakusafw . cleaner . common . CleanerInitializer ; import com . asakusafw . cleaner . common . ConfigurationLoader ; import com . asakusafw . cleaner . common . Constants ; import com . asakusafw . cleaner . common . MessageIdConst ; import com . asakusafw . cleaner . exception . CleanerSystemException ; import com . asakusafw . cleaner . log . Log ; public class HDFSCleaner extends Configured implements Tool { private static final Class < ? > CLASS = HDFSCleaner . class ; public HDFSCleaner ( ) { super ( ) ; } public HDFSCleaner ( Configuration conf ) { super ( conf ) ; } public static void main ( String [ ] args ) throws Exception { HDFSCleaner tool = new HDFSCleaner ( ) ; int result = tool . run ( args ) ; System . exit ( result ) ; } @ Override public int run ( String [ ] args ) throws Exception { return execute ( args ) ; } protected int execute ( String [ ] args ) { String [ ] prop = new String [ ] ; String mode = null ; String user = null ; FileSystem fs = null ; if ( args . length > ) { mode = args [ ] ; } if ( args . length > ) { user = args [ ] ; } if ( args . length > ) { prop [ ] = args [ ] ; } if ( args . length != ) { System . err . println ( "" + args . length + "" + mode + "" + user + "" + prop [ ] ) ; Log . log ( CLASS , MessageIdConst . HCLN_PARAMCHECK_ERROR , "" , args . length , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_ERROR ; } try { if ( ! CleanerInitializer . initDFSCleaner ( prop ) ) { Log . log ( CLASS , MessageIdConst . HCLN_INIT_ERROR , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_ERROR ; } Log . log ( CLASS , MessageIdConst . HCLN_START , new Date ( ) , mode , prop [ ] ) ; boolean recursive = false ; if ( Constants . CLEAN_MODE_NOMAL . equals ( mode ) ) { recursive = false ; } else if ( Constants . CLEAN_MODE_RECURSIVE . equals ( mode ) ) { recursive = true ; } else { Log . log ( CLASS , MessageIdConst . HCLN_PARAMCHECK_ERROR , "" , mode , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_ERROR ; } DFSCleanerBean [ ] bean = null ; try { bean = getCleanLocalPath ( user ) ; } catch ( CleanerSystemException e ) { Log . log ( e . getCause ( ) , e . getClazz ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; return Constants . EXIT_CODE_ERROR ; } int keepDate = getHDFSFileKeepDate ( ) ; boolean cleanResult = true ; Date now = new Date ( ) ; for ( int i = ; i < bean . length ; i ++ ) { try { Path cleanDir = bean [ i ] . getCleanDir ( ) ; try { Configuration conf = getConf ( ) ; fs = cleanDir . getFileSystem ( conf ) ; if ( fs == null ) { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_DIR_ERROR , "" , cleanDir . toString ( ) ) ; cleanResult = false ; continue ; } } catch ( IOException e ) { Log . log ( e , CLASS , MessageIdConst . HCLN_CLEN_DIR_ERROR , "" , cleanDir . toString ( ) ) ; cleanResult = false ; continue ; } boolean target = bean [ i ] . hasExecutionId ( ) ; String pattern = bean [ i ] . getPattern ( ) ; Log . log ( CLASS , MessageIdConst . HCLN_CLEN_FILE , cleanDir . toString ( ) , pattern , keepDate , mode , target , now ) ; if ( cleanDir ( fs , cleanDir , target , pattern , keepDate , now , recursive ) ) { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_DIR_SUCCESS , cleanDir . toString ( ) , keepDate , mode ) ; } else { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_DIR_FAIL , cleanDir . toString ( ) , keepDate , mode ) ; cleanResult = false ; } } catch ( CleanerSystemException e ) { Log . log ( e . getCause ( ) , e . getClazz ( ) , e . getMessageId ( ) , e . getMessageArgs ( ) ) ; cleanResult = false ; } finally { if ( fs != null ) { try { fs . close ( ) ; } catch ( IOException ignored ) { } } } } if ( cleanResult ) { Log . log ( CLASS , MessageIdConst . HCLN_EXIT_SUCCESS , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_SUCCESS ; } else { Log . log ( CLASS , MessageIdConst . HCLN_EXIT_WARNING , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_WARNING ; } } catch ( RuntimeException e ) { try { Log . log ( e , CLASS , MessageIdConst . HCLN_EXCEPRION , new Date ( ) , mode , prop [ ] ) ; return Constants . EXIT_CODE_ERROR ; } catch ( Exception e1 ) { System . err . print ( "" ) ; e1 . printStackTrace ( ) ; return Constants . EXIT_CODE_ERROR ; } } } private boolean cleanDir ( FileSystem fs , Path cleanPath , boolean isSetExecutionId , String pattern , int keepDate , Date now , boolean recursive ) throws CleanerSystemException { try { if ( ! fs . exists ( cleanPath ) ) { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_DIR_ERROR , "" , cleanPath . toString ( ) ) ; return false ; } if ( ! fs . getFileStatus ( cleanPath ) . isDir ( ) ) { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_DIR_ERROR , "" , cleanPath . toString ( ) ) ; return false ; } Log . log ( CLASS , MessageIdConst . HCLN_FILE_DELETE , cleanPath . toString ( ) ) ; int cleanFileCount = ; int cleanDirCount = ; boolean result = true ; FileStatus [ ] dirStatus = getListStatus ( fs , cleanPath ) ; Path [ ] listedPaths = FileUtil . stat2Paths ( dirStatus ) ; for ( Path path : listedPaths ) { FileStatus status = fs . getFileStatus ( path ) ; long lastModifiedTime = status . getModificationTime ( ) ; if ( status . isDir ( ) && recursive ) { if ( isSetExecutionId ) { String executionId = path . getName ( ) ; if ( isRunningJobFlow ( executionId ) ) { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_DIR_EXEC , path . toString ( ) ) ; continue ; } } FileStatus [ ] childdirStatus = getListStatus ( fs , path ) ; if ( childdirStatus . length == ) { if ( isExpired ( lastModifiedTime , keepDate , now ) ) { if ( ! fs . delete ( path , false ) ) { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_FAIL , "" , path . toString ( ) ) ; result = false ; } else { cleanDirCount ++ ; Log . log ( CLASS , MessageIdConst . HCLN_DIR_DELETE , path . toString ( ) ) ; } } } else { if ( cleanDir ( fs , path , false , pattern , keepDate , now , recursive ) ) { childdirStatus = getListStatus ( fs , path ) ; if ( childdirStatus . length == ) { if ( isExpired ( lastModifiedTime , keepDate , now ) ) { if ( ! fs . delete ( path , false ) ) { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_FAIL , "" , path . toString ( ) ) ; result = false ; } else { cleanDirCount ++ ; Log . log ( CLASS , MessageIdConst . HCLN_DIR_DELETE , path . toString ( ) ) ; } } } } else { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_FAIL , "" , path . toString ( ) ) ; result = false ; } } } else if ( ! status . isDir ( ) ) { if ( isExpired ( lastModifiedTime , keepDate , now ) && isMatchPattern ( path , pattern ) ) { if ( ! fs . delete ( path , false ) ) { Log . log ( CLASS , MessageIdConst . HCLN_CLEN_FAIL , "" , path . toString ( ) ) ; result = false ; } else { Log . log ( CLASS , MessageIdConst . HCLN_DELETE_FILE , path . toString ( ) ) ; cleanFileCount ++ ; } } } } Log . log ( CLASS , MessageIdConst . HCLN_FILE_DELETE_SUCCESS , cleanPath . toString ( ) , cleanDirCount , cleanFileCount ) ; return result ; } catch ( IOException e ) { Log . log ( e , CLASS , MessageIdConst . HCLN_CLEN_DIR_EXCEPTION , cleanPath . getName ( ) ) ; return false ; } } private FileStatus [ ] getListStatus ( FileSystem fs , Path path ) throws IOException { FileStatus [ ] status = fs . listStatus ( path ) ; if ( status == null ) { status = new FileStatus [ ] ; } return status ; } private boolean isMatchPattern ( Path path , String pattern ) throws CleanerSystemException { if ( pattern == null || pattern . equals ( "" ) ) { return true ; } else { String strFile = path . toString ( ) ; try { Matcher m = Pattern . compile ( pattern ) . matcher ( strFile ) ; return m . matches ( ) ; } catch ( PatternSyntaxException e ) { throw new CleanerSystemException ( e , this . getClass ( ) , MessageIdConst . HCLN_PATTERN_FAIL , pattern ) ; } } } private boolean isExpired ( long lastModifiedTime , int keepDate , Date now ) { long keepTime = ( keepDate ) * * * * ; long period = lastModifiedTime + keepTime ; return now . getTime ( ) > period ; } protected boolean isRunningJobFlow ( String executionId ) { return false ; } private int getHDFSFileKeepDate ( ) { return Integer . parseInt ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_HDFS_FILE_KEEP_DATE ) ) ; } private DFSCleanerBean [ ] getCleanLocalPath ( String user ) throws CleanerSystemException { List < String > cleanDirList = ConfigurationLoader . getPropStartWithString ( Constants . PROP_KEY_HDFS_FILE_CLEAN_DIR + "" ) ; List < String > noEmptyDirList = ConfigurationLoader . getNoEmptyList ( cleanDirList ) ; List < DFSCleanerBean > list = new ArrayList < DFSCleanerBean > ( ) ; int listSize = noEmptyDirList . size ( ) ; for ( int i = ; i < listSize ; i ++ ) { DFSCleanerBean bean = new DFSCleanerBean ( ) ; String dirKey = noEmptyDirList . get ( i ) ; String strPath = ConfigurationLoader . getProperty ( dirKey ) ; String strCleanPath = strPath . replace ( Constants . HDFS_PATH_REPLACE_STR_USER , user ) ; boolean isSetexecutionId = false ; if ( strCleanPath . endsWith ( Constants . HDFS_PATH_REPLACE_STR_ID ) ) { isSetexecutionId = true ; strCleanPath = strCleanPath . substring ( , strCleanPath . indexOf ( Constants . HDFS_PATH_REPLACE_STR_ID ) - ) ; } bean . setCleanDir ( createPath ( strCleanPath ) ) ; bean . setExecutionId ( isSetexecutionId ) ; String number = dirKey . substring ( dirKey . lastIndexOf ( "" ) + , dirKey . length ( ) ) ; String pattarnKey = Constants . PROP_KEY_HDFS_FILE_CLEAN_PATTERN + "" + number ; String pattern = ConfigurationLoader . getProperty ( pattarnKey ) ; if ( pattern == null || pattern . equals ( "" ) ) { throw new CleanerSystemException ( this . getClass ( ) , MessageIdConst . HCLN_PATTERN_NOT_FOUND , dirKey , strPath , pattarnKey ) ; } else { bean . setPattern ( pattern ) ; } list . add ( bean ) ; } return list . toArray ( new DFSCleanerBean [ list . size ( ) ] ) ; } protected Path createPath ( String strCleanPath ) { StringBuffer path = new StringBuffer ( ConfigurationLoader . getProperty ( Constants . PROP_KEY_HDFS_PROTCOL_HOST ) ) ; path . append ( Constants . HDFSFIXED_PATH ) ; path . append ( strCleanPath ) ; return new Path ( path . toString ( ) ) ; } } package com . asakusafw . cleaner . exception ; package com . asakusafw . cleaner . exception ; public class CleanerSystemException extends Exception { private Class < ? > clazz ; private String messageId ; private Object [ ] messageArgs ; private static final long serialVersionUID = ; public CleanerSystemException ( Throwable cause , Class < ? > clazz , String messageId , Object ... messageArgs ) { super ( cause ) ; this . clazz = clazz ; this . messageId = messageId ; this . messageArgs = messageArgs . clone ( ) ; } public CleanerSystemException ( Class < ? > clazz , String messageId , Object ... messageArgs ) { this . clazz = clazz ; this . messageId = messageId ; this . messageArgs = messageArgs . clone ( ) ; } public Class < ? > getClazz ( ) { return clazz ; } public String getMessageId ( ) { return messageId ; } public Object [ ] getMessageArgs ( ) { return messageArgs . clone ( ) ; } } package com . asakusafw . cleaner . bean ; import java . io . File ; public class LocalFileCleanerBean { private File cleanDir = null ; private String pattern = null ; public File getCleanDir ( ) { return cleanDir ; } public void setCleanDir ( File cleanDir ) { this . cleanDir = cleanDir ; } public String getPattern ( ) { return pattern ; } public void setPattern ( String pattern ) { this . pattern = pattern ; } } package com . asakusafw . cleaner . bean ; import org . apache . hadoop . fs . Path ; public class DFSCleanerBean { private Path cleanDir = null ; private String pattern = null ; private boolean executionId = false ; public Path getCleanDir ( ) { return cleanDir ; } public void setCleanDir ( Path cleanDir ) { this . cleanDir = cleanDir ; } public String getPattern ( ) { return pattern ; } public void setPattern ( String pattern ) { this . pattern = pattern ; } public boolean hasExecutionId ( ) { return executionId ; } public void setExecutionId ( boolean executionId ) { this . executionId = executionId ; } } package com . asakusafw . cleaner . bean ; package com . asakusafw . cleaner . common ; public final class MessageIdConst { public static final String CMN_PROP_CHECK_ERROR = "" ; public static final String LCLN_START = "" ; public static final String LCLN_EXIT_SUCCESS = "" ; public static final String LCLN_EXIT_WARNING = "" ; public static final String LCLN_INIT_ERROR = "" ; public static final String LCLN_EXCEPRION = "" ; public static final String LCLN_PARAMCHECK_ERROR = "" ; public static final String LCLN_CLEN_DIR_SUCCESS = "" ; public static final String LCLN_CLEN_DIR_FAIL = "" ; public static final String LCLN_CLEN_DIR_ERROR = "" ; public static final String LCLN_CLEN_FAIL = "" ; public static final String LCLN_CLEN_FILE = "" ; public static final String LCLN_FILE_DELETE = "" ; public static final String LCLN_FILE_DELETE_SUCCESS = "" ; public static final String LCLN_DIR_DELETE = "" ; public static final String LCLN_PATTERN_FAIL = "" ; public static final String LCLN_DELETE_FILE = "" ; public static final String LCLN_PATTERN_NOT_FOUND = "" ; public static final String HCLN_START = "" ; public static final String HCLN_EXIT_SUCCESS = "" ; public static final String HCLN_EXIT_WARNING = "" ; public static final String HCLN_INIT_ERROR = "" ; public static final String HCLN_EXCEPRION = "" ; public static final String HCLN_PARAMCHECK_ERROR = "" ; public static final String HCLN_CLEN_DIR_SUCCESS = "" ; public static final String HCLN_CLEN_DIR_FAIL = "" ; public static final String HCLN_CLEN_DIR_ERROR = "" ; public static final String HCLN_CLEN_FAIL = "" ; public static final String HCLN_CLEN_DIR_EXCEPTION = "" ; public static final String HCLN_CLEN_DIR_EXEC = "" ; public static final String HCLN_CLEN_FILE = "" ; public static final String HCLN_FILE_DELETE = "" ; public static final String HCLN_FILE_DELETE_SUCCESS = "" ; public static final String HCLN_DIR_DELETE = "" ; public static final String HCLN_PATTERN_FAIL = "" ; public static final String HCLN_DELETE_FILE = "" ; public static final String HCLN_PATTERN_NOT_FOUND = "" ; private MessageIdConst ( ) { } } package com . asakusafw . testdriver . file ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; import org . apache . hadoop . mapreduce . lib . output . SequenceFileOutputFormat ; import org . apache . hadoop . mapreduce . lib . output . TextOutputFormat ; import org . junit . After ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . configuration . HadoopEnvironmentChecker ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class FileExporterRetrieverTest { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Rule public HadoopEnvironmentChecker check = new HadoopEnvironmentChecker ( false ) ; private ConfigurationFactory factory ; private FileSystem fileSystem ; @ Before public void setUp ( ) throws Exception { factory = ConfigurationFactory . getDefault ( ) ; Configuration conf = factory . newInstance ( ) ; fileSystem = FileSystem . get ( conf ) ; } @ After public void tearDown ( ) throws Exception { if ( fileSystem != null ) { fileSystem . delete ( new Path ( "" ) , true ) ; } } @ Test public void simple ( ) throws Exception { MockFileExporter exporter = new MockFileExporter ( Text . class , TextOutputFormat . class , "" ) ; FileExporterRetriever retriever = new FileExporterRetriever ( factory ) ; putTextRaw ( "" , "" . getBytes ( "" ) ) ; MockTextDefinition definition = new MockTextDefinition ( ) ; DataModelSource result = retriever . createSource ( definition , exporter , EMPTY ) ; try { DataModelReflection ref ; ref = result . next ( ) ; assertThat ( ref , is ( not ( nullValue ( ) ) ) ) ; assertThat ( definition . toObject ( ref ) , is ( new Text ( "" ) ) ) ; ref = result . next ( ) ; assertThat ( ref , is ( not ( nullValue ( ) ) ) ) ; assertThat ( definition . toObject ( ref ) , is ( new Text ( "" ) ) ) ; ref = result . next ( ) ; assertThat ( ref , is ( nullValue ( ) ) ) ; } finally { result . close ( ) ; } } @ Test public void sequenceFile ( ) throws Exception { MockFileExporter exporter = new MockFileExporter ( Text . class , SequenceFileOutputFormat . class , "" ) ; FileExporterRetriever retriever = new FileExporterRetriever ( factory ) ; putTextSequenceFile ( "" , "" , "" ) ; MockTextDefinition definition = new MockTextDefinition ( ) ; DataModelSource result = retriever . createSource ( definition , exporter , EMPTY ) ; try { DataModelReflection ref ; ref = result . next ( ) ; assertThat ( ref , is ( not ( nullValue ( ) ) ) ) ; assertThat ( definition . toObject ( ref ) , is ( new Text ( "" ) ) ) ; ref = result . next ( ) ; assertThat ( ref , is ( not ( nullValue ( ) ) ) ) ; assertThat ( definition . toObject ( ref ) , is ( new Text ( "" ) ) ) ; ref = result . next ( ) ; assertThat ( ref , is ( nullValue ( ) ) ) ; } finally { result . close ( ) ; } } private void putTextRaw ( String path , byte [ ] bytes ) throws IOException { FSDataOutputStream output = fileSystem . create ( new Path ( path ) , true ) ; try { output . write ( bytes ) ; } finally { output . close ( ) ; } } private void putTextSequenceFile ( String path , String ... lines ) throws IOException { SequenceFile . Writer writer = new SequenceFile . Writer ( fileSystem , factory . newInstance ( ) , new Path ( path ) , NullWritable . class , Text . class ) ; try { for ( String s : lines ) { writer . append ( NullWritable . get ( ) , new Text ( s ) ) ; } } finally { writer . close ( ) ; } } @ SuppressWarnings ( "" ) private static class MockFileExporter extends FileExporterDescription { private final Class < ? > modelType ; private final Class < ? extends FileOutputFormat > format ; private final String pathPrefix ; MockFileExporter ( Class < ? > modelType , Class < ? extends FileOutputFormat > format , String pathPrefix ) { assert modelType != null ; assert format != null ; assert pathPrefix != null ; this . modelType = modelType ; this . format = format ; this . pathPrefix = pathPrefix ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public Class < ? extends FileOutputFormat > getOutputFormat ( ) { return format ; } @ Override public String getPathPrefix ( ) { return pathPrefix ; } } } package com . asakusafw . testdriver . file ; import java . lang . annotation . Annotation ; import java . util . Collection ; import java . util . Collections ; import org . apache . hadoop . io . Text ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; public class MockTextDefinition implements DataModelDefinition < Text > { static final PropertyName VALUE = PropertyName . newInstance ( "" ) ; @ Override public Class < Text > getModelClass ( ) { return Text . class ; } @ Override public < A extends Annotation > A getAnnotation ( Class < A > annotationType ) { return null ; } @ Override public Collection < PropertyName > getProperties ( ) { return Collections . singleton ( VALUE ) ; } @ Override public PropertyType getType ( PropertyName name ) { if ( VALUE . equals ( name ) ) { return PropertyType . STRING ; } return null ; } @ Override public < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) { return null ; } @ Override public Builder < Text > newReflection ( ) { return new Builder < Text > ( this ) ; } @ Override public DataModelReflection toReflection ( Text object ) { return newReflection ( ) . add ( VALUE , object . toString ( ) ) . build ( ) ; } @ Override public Text toObject ( DataModelReflection reflection ) { return new Text ( ( String ) reflection . getValue ( VALUE ) ) ; } } package com . asakusafw . testdriver . file ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Scanner ; import java . util . Set ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . mapreduce . lib . input . FileInputFormat ; import org . apache . hadoop . mapreduce . lib . input . SequenceFileInputFormat ; import org . apache . hadoop . mapreduce . lib . input . TextInputFormat ; import org . junit . After ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . configuration . HadoopEnvironmentChecker ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . vocabulary . external . FileImporterDescription ; public class FileImporterPreparatorTest { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Rule public HadoopEnvironmentChecker check = new HadoopEnvironmentChecker ( false ) ; private ConfigurationFactory factory ; private FileSystem fileSystem ; @ Before public void setUp ( ) throws Exception { factory = ConfigurationFactory . getDefault ( ) ; Configuration conf = factory . newInstance ( ) ; fileSystem = FileSystem . get ( conf ) ; } @ After public void tearDown ( ) throws Exception { if ( fileSystem != null ) { fileSystem . delete ( new Path ( "" ) , true ) ; } } @ Test public void simple ( ) throws Exception { FileImporterPreparator target = new FileImporterPreparator ( factory ) ; ModelOutput < Text > open = target . createOutput ( new MockTextDefinition ( ) , new MockFileImporter ( Text . class , TextInputFormat . class , "" ) , EMPTY ) ; try { open . write ( new Text ( "" ) ) ; } finally { open . close ( ) ; } InputStream result = loadResult ( "" ) ; Scanner scanner = new Scanner ( result , "" ) ; assertThat ( scanner . hasNextLine ( ) , is ( true ) ) ; assertThat ( scanner . nextLine ( ) , is ( "" ) ) ; assertThat ( scanner . hasNextLine ( ) , is ( false ) ) ; scanner . close ( ) ; } @ Test public void sequenceFile ( ) throws Exception { FileImporterPreparator target = new FileImporterPreparator ( factory ) ; ModelOutput < Text > open = target . createOutput ( new MockTextDefinition ( ) , new MockFileImporter ( Text . class , SequenceFileInputFormat . class , "" ) , EMPTY ) ; try { open . write ( new Text ( "" ) ) ; open . write ( new Text ( "" ) ) ; } finally { open . close ( ) ; } SequenceFile . Reader reader = new SequenceFile . Reader ( fileSystem , new Path ( "" ) , factory . newInstance ( ) ) ; try { Text text = new Text ( ) ; assertThat ( reader . next ( NullWritable . get ( ) , text ) , is ( true ) ) ; assertThat ( text . toString ( ) , is ( "" ) ) ; assertThat ( reader . next ( NullWritable . get ( ) , text ) , is ( true ) ) ; assertThat ( text . toString ( ) , is ( "" ) ) ; assertThat ( reader . next ( NullWritable . get ( ) , text ) , is ( false ) ) ; } finally { reader . close ( ) ; } } private InputStream loadResult ( String path ) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FSDataInputStream input = fileSystem . open ( new Path ( path ) ) ; try { byte [ ] bytes = new byte [ ] ; while ( true ) { int read = input . read ( bytes ) ; if ( read < ) { break ; } buffer . write ( bytes , , read ) ; } } finally { input . close ( ) ; } fileSystem . delete ( new Path ( path ) , true ) ; return new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; } @ SuppressWarnings ( "" ) private static class MockFileImporter extends FileImporterDescription { private final Class < ? > modelType ; private final Class < ? extends FileInputFormat > format ; private final Set < String > paths ; MockFileImporter ( Class < ? > modelType , Class < ? extends FileInputFormat > format , String ... paths ) { this . modelType = modelType ; this . format = format ; this . paths = new HashSet < String > ( Arrays . asList ( paths ) ) ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public Class < ? extends FileInputFormat > getInputFormat ( ) { return format ; } @ Override public Set < String > getPaths ( ) { return paths ; } } } package com . asakusafw . testdriver . file ; import java . io . IOException ; import java . io . InterruptedIOException ; import org . apache . hadoop . mapreduce . OutputCommitter ; import org . apache . hadoop . mapreduce . RecordWriter ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; class FileOutputFormatDriver < V > implements ModelOutput < V > { static final Logger LOG = LoggerFactory . getLogger ( FileOutputFormatDriver . class ) ; private final TaskAttemptContext context ; private final Object key ; private final FileOutputFormat < ? , ? > format ; @ SuppressWarnings ( "" ) private final RecordWriter writer ; public < K > FileOutputFormatDriver ( TaskAttemptContext context , FileOutputFormat < ? super K , ? super V > format , K key ) throws IOException { if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , format . getClass ( ) . getName ( ) ) ; this . context = context ; this . format = format ; this . key = key ; try { this . writer = format . getRecordWriter ( context ) ; } catch ( InterruptedException e ) { throw ( InterruptedIOException ) new InterruptedIOException ( ) . initCause ( e ) ; } } @ SuppressWarnings ( "" ) @ Override public void write ( V model ) throws IOException { try { writer . write ( key , model ) ; } catch ( InterruptedException e ) { throw ( InterruptedIOException ) new InterruptedIOException ( ) . initCause ( e ) ; } } @ Override public void close ( ) throws IOException { LOG . debug ( "" , format . getClass ( ) . getName ( ) ) ; try { writer . close ( context ) ; OutputCommitter comitter = format . getOutputCommitter ( context ) ; comitter . commitTask ( context ) ; comitter . commitJob ( context ) ; } catch ( InterruptedException e ) { throw ( InterruptedIOException ) new InterruptedIOException ( ) . initCause ( e ) ; } } } package com . asakusafw . testdriver . file ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . TaskAttemptID ; import org . apache . hadoop . mapreduce . lib . input . FileInputFormat ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; import org . apache . hadoop . util . ReflectionUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . testdriver . core . BaseExporterRetriever ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . ExporterRetriever ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . vocabulary . external . FileExporterDescription ; @ SuppressWarnings ( { "" , "" } ) public class FileExporterRetriever extends BaseExporterRetriever < FileExporterDescription > { static final Logger LOG = LoggerFactory . getLogger ( FileExporterRetriever . class ) ; private final ConfigurationFactory configurations ; public FileExporterRetriever ( ) { this ( ConfigurationFactory . getDefault ( ) ) ; } public FileExporterRetriever ( ConfigurationFactory configurations ) { if ( configurations == null ) { throw new IllegalArgumentException ( "" ) ; } this . configurations = configurations ; } @ Override public void truncate ( FileExporterDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; VariableTable variables = createVariables ( context ) ; Configuration config = configurations . newInstance ( ) ; String resolved = variables . parse ( description . getPathPrefix ( ) , false ) ; Path path = new Path ( resolved ) ; FileSystem fs = path . getFileSystem ( config ) ; Path output = path . getParent ( ) ; Path target ; if ( output == null ) { LOG . warn ( "" , path ) ; target = fs . makeQualified ( path ) ; } else { LOG . warn ( "" , output ) ; target = fs . makeQualified ( output ) ; } LOG . debug ( "" , target ) ; boolean succeed = fs . delete ( target , true ) ; LOG . debug ( "" , succeed , target ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , FileExporterDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; checkType ( definition , description ) ; VariableTable variables = createVariables ( context ) ; String destination = description . getPathPrefix ( ) . replace ( '' , '' ) ; String resolved = variables . parse ( destination , false ) ; Configuration conf = configurations . newInstance ( ) ; FileOutputFormat output = ReflectionUtils . newInstance ( description . getOutputFormat ( ) , conf ) ; FileDeployer deployer = new FileDeployer ( conf ) ; return deployer . openOutput ( definition , resolved , output ) ; } @ Override public < V > DataModelSource createSource ( DataModelDefinition < V > definition , FileExporterDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; VariableTable variables = createVariables ( context ) ; checkType ( definition , description ) ; Configuration conf = configurations . newInstance ( ) ; Job job = new Job ( conf ) ; String resolved = variables . parse ( description . getPathPrefix ( ) , false ) ; FileInputFormat . setInputPaths ( job , new Path ( resolved ) ) ; TaskAttemptContext taskContext = new TaskAttemptContext ( job . getConfiguration ( ) , new TaskAttemptID ( ) ) ; FileInputFormat < ? , V > format = getOpposite ( conf , description . getOutputFormat ( ) ) ; FileInputFormatDriver < V > result = new FileInputFormatDriver < V > ( definition , taskContext , format ) ; return result ; } private VariableTable createVariables ( TestContext context ) { assert context != null ; VariableTable result = new VariableTable ( ) ; result . defineVariables ( context . getArguments ( ) ) ; return result ; } private < V > void checkType ( DataModelDefinition < V > definition , FileExporterDescription description ) throws IOException { if ( definition . getModelClass ( ) != description . getModelType ( ) ) { throw new IOException ( MessageFormat . format ( "" , definition . getModelClass ( ) . getName ( ) , description . getModelType ( ) . getName ( ) , description ) ) ; } } private FileInputFormat getOpposite ( Configuration conf , Class < ? > outputFormat ) throws IOException { assert conf != null ; assert outputFormat != null ; LOG . debug ( "" , outputFormat . getName ( ) ) ; String outputFormatName = outputFormat . getName ( ) ; String inputFormatName = infer ( outputFormatName ) ; if ( inputFormatName == null ) { throw new IOException ( MessageFormat . format ( "" , outputFormat . getName ( ) ) ) ; } LOG . debug ( "" , inputFormatName ) ; try { Class < ? > loaded = outputFormat . getClassLoader ( ) . loadClass ( inputFormatName ) ; FileInputFormat instance = ( FileInputFormat ) ReflectionUtils . newInstance ( loaded , conf ) ; if ( instance instanceof Configurable ) { ( ( Configurable ) instance ) . setConf ( conf ) ; } return instance ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , outputFormat . getName ( ) ) , e ) ; } } private static final Pattern OUTPUT = Pattern . compile ( "" ) ; private String infer ( String outputFormatName ) { assert outputFormatName != null ; Matcher matcher = OUTPUT . matcher ( outputFormatName ) ; StringBuilder buf = new StringBuilder ( ) ; int start = ; while ( matcher . find ( ) ) { String group = matcher . group ( ) ; buf . append ( outputFormatName . substring ( start , matcher . start ( ) ) ) ; if ( group . equals ( "" ) ) { buf . append ( "" ) ; } else { buf . append ( "" ) ; } start = matcher . end ( ) ; } buf . append ( outputFormatName . substring ( start ) ) ; return buf . toString ( ) ; } } package com . asakusafw . testdriver . file ; import java . io . IOException ; import java . io . InterruptedIOException ; import java . util . LinkedList ; import org . apache . hadoop . mapreduce . InputSplit ; import org . apache . hadoop . mapreduce . RecordReader ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . lib . input . FileInputFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; class FileInputFormatDriver < V > implements DataModelSource { static final Logger LOG = LoggerFactory . getLogger ( FileInputFormatDriver . class ) ; private final DataModelDefinition < V > definition ; private final TaskAttemptContext context ; private final FileInputFormat < ? , V > format ; private final LinkedList < InputSplit > splits ; private RecordReader < ? , V > current ; public FileInputFormatDriver ( DataModelDefinition < V > definition , TaskAttemptContext context , FileInputFormat < ? , V > format ) throws IOException { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( format == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , format . getClass ( ) . getName ( ) ) ; this . definition = definition ; this . context = context ; this . format = format ; LOG . debug ( "" , format . getClass ( ) . getName ( ) ) ; this . splits = new LinkedList < InputSplit > ( format . getSplits ( context ) ) ; } @ Override public DataModelReflection next ( ) throws IOException { if ( prepare ( ) == false ) { return null ; } assert current != null ; while ( true ) { V model = getNext ( ) ; if ( model != null ) { return definition . toReflection ( model ) ; } disposeCurrent ( ) ; if ( prepareNext ( ) == false ) { break ; } } return null ; } private V getNext ( ) throws IOException { assert current != null ; try { if ( current . nextKeyValue ( ) == false ) { return null ; } return current . getCurrentValue ( ) ; } catch ( InterruptedException e ) { throw ( InterruptedIOException ) new InterruptedIOException ( ) . initCause ( e ) ; } } private void disposeCurrent ( ) throws IOException { assert current != null ; current . close ( ) ; current = null ; } private boolean prepare ( ) throws IOException { if ( current != null ) { return true ; } return prepareNext ( ) ; } private boolean prepareNext ( ) throws IOException { if ( splits . isEmpty ( ) ) { return false ; } InputSplit next = splits . removeFirst ( ) ; try { current = format . createRecordReader ( next , context ) ; current . initialize ( next , context ) ; } catch ( InterruptedException e ) { throw ( InterruptedIOException ) new InterruptedIOException ( ) . initCause ( e ) ; } return true ; } @ Override public void close ( ) throws IOException { if ( current != null ) { current . close ( ) ; } splits . clear ( ) ; } } package com . asakusafw . testdriver . file ; package com . asakusafw . testdriver . file ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Set ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . apache . hadoop . conf . Configurable ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; import org . apache . hadoop . util . ReflectionUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . testdriver . core . BaseImporterPreparator ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . ImporterPreparator ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . vocabulary . external . FileImporterDescription ; @ SuppressWarnings ( { "" , "" } ) public class FileImporterPreparator extends BaseImporterPreparator < FileImporterDescription > { static final Logger LOG = LoggerFactory . getLogger ( FileImporterPreparator . class ) ; private final ConfigurationFactory configurations ; public FileImporterPreparator ( ) { this ( ConfigurationFactory . getDefault ( ) ) ; } public FileImporterPreparator ( ConfigurationFactory configurations ) { if ( configurations == null ) { throw new IllegalArgumentException ( "" ) ; } this . configurations = configurations ; } @ Override public void truncate ( FileImporterDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; VariableTable variables = createVariables ( context ) ; Configuration config = configurations . newInstance ( ) ; FileSystem fs = FileSystem . get ( config ) ; for ( String path : description . getPaths ( ) ) { String resolved = variables . parse ( path , false ) ; Path target = fs . makeQualified ( new Path ( resolved ) ) ; LOG . debug ( "" , target ) ; boolean succeed = fs . delete ( target , true ) ; LOG . debug ( "" , succeed , target ) ; } } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , FileImporterDescription description , TestContext context ) throws IOException { LOG . info ( "" , description ) ; checkType ( definition , description ) ; Set < String > path = description . getPaths ( ) ; if ( path . isEmpty ( ) ) { return new ModelOutput < V > ( ) { @ Override public void close ( ) throws IOException { return ; } @ Override public void write ( V model ) throws IOException { return ; } } ; } VariableTable variables = createVariables ( context ) ; String destination = path . iterator ( ) . next ( ) . replace ( '' , '' ) ; String resolved = variables . parse ( destination , false ) ; Configuration conf = configurations . newInstance ( ) ; FileOutputFormat output = getOpposite ( conf , description . getInputFormat ( ) ) ; FileDeployer deployer = new FileDeployer ( conf ) ; return deployer . openOutput ( definition , resolved , output ) ; } private VariableTable createVariables ( TestContext context ) { assert context != null ; VariableTable result = new VariableTable ( ) ; result . defineVariables ( context . getArguments ( ) ) ; return result ; } private < V > void checkType ( DataModelDefinition < V > definition , FileImporterDescription description ) throws IOException { if ( definition . getModelClass ( ) != description . getModelType ( ) ) { throw new IOException ( MessageFormat . format ( "" , definition . getModelClass ( ) . getName ( ) , description . getModelType ( ) . getName ( ) , description ) ) ; } } private FileOutputFormat getOpposite ( Configuration conf , Class < ? > inputFormat ) throws IOException { assert conf != null ; assert inputFormat != null ; LOG . debug ( "" , inputFormat . getName ( ) ) ; String inputFormatName = inputFormat . getName ( ) ; String outputFormatName = infer ( inputFormatName ) ; if ( outputFormatName == null ) { throw new IOException ( MessageFormat . format ( "" , inputFormat . getName ( ) ) ) ; } LOG . debug ( "" , outputFormatName ) ; try { Class < ? > loaded = inputFormat . getClassLoader ( ) . loadClass ( outputFormatName ) ; FileOutputFormat instance = ( FileOutputFormat ) ReflectionUtils . newInstance ( loaded , conf ) ; if ( instance instanceof Configurable ) { ( ( Configurable ) instance ) . setConf ( conf ) ; } return instance ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , inputFormat . getName ( ) ) , e ) ; } } private static final Pattern INPUT = Pattern . compile ( "" ) ; private String infer ( String inputFormatName ) { assert inputFormatName != null ; Matcher matcher = INPUT . matcher ( inputFormatName ) ; StringBuilder buf = new StringBuilder ( ) ; int start = ; while ( matcher . find ( ) ) { String group = matcher . group ( ) ; buf . append ( inputFormatName . substring ( start , matcher . start ( ) ) ) ; if ( group . equals ( "" ) ) { buf . append ( "" ) ; } else { buf . append ( "" ) ; } start = matcher . end ( ) ; } buf . append ( inputFormatName . substring ( start ) ) ; return buf . toString ( ) ; } } package com . asakusafw . testdriver . file ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . net . URI ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . mapreduce . OutputFormat ; import org . apache . hadoop . mapreduce . TaskAttemptContext ; import org . apache . hadoop . mapreduce . TaskAttemptID ; import org . apache . hadoop . mapreduce . lib . output . FileOutputFormat ; import org . mortbay . log . Log ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . DataModelDefinition ; final class FileDeployer { static final Logger LOG = LoggerFactory . getLogger ( FileDeployer . class ) ; private final Configuration configuration ; public FileDeployer ( Configuration configuration ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . configuration = configuration ; } public < V > ModelOutput < V > openOutput ( DataModelDefinition < V > definition , final String destination , FileOutputFormat < ? super NullWritable , ? super V > output ) throws IOException { assert destination != null ; assert output != null ; LOG . debug ( "" , destination , output . getClass ( ) . getName ( ) ) ; Job job = new Job ( configuration ) ; job . setOutputKeyClass ( NullWritable . class ) ; job . setOutputValueClass ( definition . getModelClass ( ) ) ; final File temporaryDir = File . createTempFile ( "" , "" ) ; if ( temporaryDir . delete ( ) == false || temporaryDir . mkdirs ( ) == false ) { throw new IOException ( "" ) ; } LOG . debug ( "" , temporaryDir ) ; URI uri = temporaryDir . toURI ( ) ; FileOutputFormat . setOutputPath ( job , new Path ( uri ) ) ; TaskAttemptContext context = new TaskAttemptContext ( job . getConfiguration ( ) , new TaskAttemptID ( ) ) ; FileOutputFormatDriver < V > result = new FileOutputFormatDriver < V > ( context , output , NullWritable . get ( ) ) { @ Override public void close ( ) throws IOException { super . close ( ) ; deploy ( destination , temporaryDir ) ; } } ; return result ; } void deploy ( String destination , File temporaryDir ) throws IOException { assert destination != null ; assert temporaryDir != null ; LOG . debug ( "" , temporaryDir , destination ) ; try { File result = findResult ( temporaryDir ) ; copy ( result , destination ) ; } finally { delete ( temporaryDir ) ; } } private File findResult ( File temporaryDir ) throws IOException { assert temporaryDir != null ; for ( File file : temporaryDir . listFiles ( ) ) { if ( file . getName ( ) . startsWith ( "" ) ) { return file ; } } throw new FileNotFoundException ( "" ) ; } private void copy ( File result , String destination ) throws IOException { assert result != null ; assert destination != null ; Path target = new Path ( destination ) ; FileSystem fs = target . getFileSystem ( configuration ) ; fs . copyFromLocalFile ( new Path ( result . toURI ( ) ) , target ) ; } private void delete ( File target ) { assert target != null ; if ( target . isDirectory ( ) ) { for ( File child : target . listFiles ( ) ) { delete ( child ) ; } } if ( target . delete ( ) == false ) { Log . warn ( "" , target ) ; } } } package com . asakusafw . modelgen . view ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import org . junit . Test ; import com . asakusafw . modelgen . model . Aggregator ; import com . asakusafw . modelgen . view . model . CreateView ; import com . asakusafw . modelgen . view . model . From ; import com . asakusafw . modelgen . view . model . Join ; import com . asakusafw . modelgen . view . model . Name ; import com . asakusafw . modelgen . view . model . On ; import com . asakusafw . modelgen . view . model . Select ; public class ViewParserTest { @ Test public void parseJoin ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , } ) , new From ( n ( "" ) , null , new Join ( n ( "" ) , null , Arrays . asList ( new On ( n ( "" ) , n ( "" ) ) ) ) ) , Arrays . < Name > asList ( ) ) ) ) ; } @ Test public void parseJoin_withAlias ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , } ) , new From ( n ( "" ) , "" , new Join ( n ( "" ) , "" , Arrays . asList ( new On ( n ( "" ) , n ( "" ) ) ) ) ) , Arrays . < Name > asList ( ) ) ) ) ; } @ Test public void parseSummarize ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . COUNT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . MAX , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . SUM , n ( "" ) ) , } ) , new From ( n ( "" ) , null , null ) , Arrays . < Name > asList ( n ( "" ) ) ) ) ) ; } @ Test public void parseSummarize_withAlias ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . COUNT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . MAX , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . SUM , n ( "" ) ) , } ) , new From ( n ( "" ) , "" , null ) , Arrays . < Name > asList ( n ( "" ) ) ) ) ) ; } @ Test public void parseSummarize_multiGroupCoulmns ( ) throws Exception { ViewDefinition def = def ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; CreateView model = ViewParser . parse ( def ) ; assertThat ( model , is ( new CreateView ( n ( "" ) , Arrays . asList ( new Select [ ] { new Select ( n ( "" ) , Aggregator . IDENT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . COUNT , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . MAX , n ( "" ) ) , new Select ( n ( "" ) , Aggregator . SUM , n ( "" ) ) , } ) , new From ( n ( "" ) , null , null ) , Arrays . < Name > asList ( n ( "" ) , n ( "" ) ) ) ) ) ; } private Name n ( String name ) { return new Name ( name ) ; } private ViewDefinition def ( String statement ) { return new ViewDefinition ( "" , statement ) ; } } package com . asakusafw . modelgen . util ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . modelgen . model . JoinedModelDescription ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . Source ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . model . TableModelDescription ; public class JoinedModelBuilderTest { @ Test public void simple ( ) { TableModelDescription a = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; TableModelDescription b = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; JoinedModelBuilder target = new JoinedModelBuilder ( "" , a , "" , b , "" ) ; target . on ( "" , "" ) ; target . add ( "" , "" ) ; target . add ( "" , "" ) ; target . add ( "" , "" ) ; JoinedModelDescription desc = target . toDescription ( ) ; assertThat ( desc . getFromModel ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( desc . getJoinModel ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( desc . getFromCondition ( ) , is ( sources ( a , "" ) ) ) ; assertThat ( desc . getJoinCondition ( ) , is ( sources ( b , "" ) ) ) ; List < ModelProperty > props = desc . getProperties ( ) ; assertThat ( props . size ( ) , is ( ) ) ; ModelProperty id = props . get ( ) ; assertThat ( id . getName ( ) , is ( "" ) ) ; assertThat ( id . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( id . getFrom ( ) , is ( source ( a , "" ) ) ) ; assertThat ( id . getJoined ( ) , is ( source ( b , "" ) ) ) ; ModelProperty hoge = props . get ( ) ; assertThat ( hoge . getName ( ) , is ( "" ) ) ; assertThat ( hoge . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; assertThat ( hoge . getFrom ( ) , is ( source ( a , "" ) ) ) ; assertThat ( hoge . getJoined ( ) , is ( nullValue ( ) ) ) ; ModelProperty bar = props . get ( ) ; assertThat ( bar . getName ( ) , is ( "" ) ) ; assertThat ( bar . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; assertThat ( bar . getFrom ( ) , is ( nullValue ( ) ) ) ; assertThat ( bar . getJoined ( ) , is ( source ( b , "" ) ) ) ; } @ Test public void fill ( ) { TableModelDescription a = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; TableModelDescription b = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; JoinedModelBuilder target = new JoinedModelBuilder ( "" , a , "" , b , "" ) ; target . on ( "" , "" ) ; target . add ( "" , "" ) ; target . add ( "" , "" ) ; JoinedModelDescription desc = target . toDescription ( ) ; assertThat ( desc . getFromModel ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( desc . getJoinModel ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( desc . getFromCondition ( ) , is ( sources ( a , "" ) ) ) ; assertThat ( desc . getJoinCondition ( ) , is ( sources ( b , "" ) ) ) ; List < ModelProperty > props = desc . getProperties ( ) ; assertThat ( props . size ( ) , is ( ) ) ; ModelProperty id = props . get ( ) ; assertThat ( id . getName ( ) , is ( "" ) ) ; assertThat ( id . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( id . getFrom ( ) , is ( source ( a , "" ) ) ) ; assertThat ( id . getJoined ( ) , is ( source ( b , "" ) ) ) ; ModelProperty hoge = props . get ( ) ; assertThat ( hoge . getName ( ) , is ( "" ) ) ; assertThat ( hoge . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; assertThat ( hoge . getFrom ( ) , is ( source ( a , "" ) ) ) ; assertThat ( hoge . getJoined ( ) , is ( source ( b , "" ) ) ) ; } private Source source ( ModelDescription model , String name ) { for ( Source s : model . getPropertiesAsSources ( ) ) { if ( name . equals ( s . getName ( ) ) ) { return s ; } } throw new AssertionError ( name ) ; } private List < Source > sources ( ModelDescription model , String ... names ) { List < Source > results = new ArrayList < Source > ( ) ; Set < String > targets = new HashSet < String > ( ) ; Collections . addAll ( targets , names ) ; for ( Source s : model . getPropertiesAsSources ( ) ) { if ( targets . contains ( s . getName ( ) ) ) { results . add ( s ) ; } } return results ; } } package com . asakusafw . modelgen . util ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . modelgen . model . Aggregator ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . Source ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . model . TableModelDescription ; public class TableModelBuilderTest { @ Test public void simple ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . INT ) . toDescription ( ) ; assertThat ( desc . getReference ( ) . isDefaultNameSpace ( ) , is ( true ) ) ; assertThat ( desc . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; List < ModelProperty > properties = desc . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty value = properties . get ( ) ; assertThat ( value . getName ( ) , is ( "" ) ) ; assertThat ( value . getType ( ) . getKind ( ) , is ( PropertyTypeKind . INT ) ) ; assertThat ( value . getJoined ( ) , is ( nullValue ( ) ) ) ; Source valueSrc = value . getFrom ( ) ; assertThat ( valueSrc . getAggregator ( ) , is ( Aggregator . IDENT ) ) ; assertThat ( valueSrc . getDeclaring ( ) , is ( desc . getReference ( ) ) ) ; assertThat ( valueSrc . getName ( ) , is ( "" ) ) ; assertThat ( valueSrc . getType ( ) . getKind ( ) , is ( PropertyTypeKind . INT ) ) ; assertThat ( valueSrc . getAttributes ( ) . size ( ) , is ( ) ) ; } @ Test public void multi ( ) { TableModelBuilder target = new TableModelBuilder ( "" ) ; target . add ( null , "" , PropertyTypeKind . INT ) ; target . add ( null , "" , new StringType ( ) ) ; target . add ( null , "" , PropertyTypeKind . DATETIME ) ; TableModelDescription desc = target . toDescription ( ) ; assertThat ( desc . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; List < ModelProperty > properties = desc . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty a = properties . get ( ) ; assertThat ( a . getName ( ) , is ( "" ) ) ; assertThat ( a . getType ( ) . getKind ( ) , is ( PropertyTypeKind . INT ) ) ; ModelProperty b = properties . get ( ) ; assertThat ( b . getName ( ) , is ( "" ) ) ; assertThat ( b . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; ModelProperty c = properties . get ( ) ; assertThat ( c . getName ( ) , is ( "" ) ) ; assertThat ( c . getType ( ) . getKind ( ) , is ( PropertyTypeKind . DATETIME ) ) ; } @ Test public void attributes ( ) { TableModelBuilder target = new TableModelBuilder ( "" ) ; target . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) ; target . add ( null , "" , new StringType ( ) , Attribute . UNIQUE , Attribute . NOT_NULL ) ; TableModelDescription desc = target . toDescription ( ) ; assertThat ( desc . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; List < ModelProperty > properties = desc . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty a = properties . get ( ) ; assertThat ( a . getName ( ) , is ( "" ) ) ; assertThat ( a . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; Set < Attribute > aAttr = a . getFrom ( ) . getAttributes ( ) ; assertThat ( aAttr . size ( ) , is ( ) ) ; assertThat ( aAttr . contains ( Attribute . PRIMARY_KEY ) , is ( true ) ) ; ModelProperty b = properties . get ( ) ; assertThat ( b . getName ( ) , is ( "" ) ) ; assertThat ( b . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; Set < Attribute > bAttr = b . getFrom ( ) . getAttributes ( ) ; assertThat ( bAttr . size ( ) , is ( ) ) ; assertThat ( bAttr . containsAll ( list ( Attribute . UNIQUE , Attribute . NOT_NULL ) ) , is ( true ) ) ; } @ Test public void namespace ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . namespace ( "" , "" ) . add ( null , "" , PropertyTypeKind . INT ) . toDescription ( ) ; assertThat ( desc . getReference ( ) . getNamespace ( ) , is ( "" ) ) ; assertThat ( desc . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; } @ Test public void defaultNamespace ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . namespace ( ) . add ( null , "" , PropertyTypeKind . INT ) . toDescription ( ) ; assertThat ( desc . getReference ( ) . isDefaultNameSpace ( ) , is ( true ) ) ; assertThat ( desc . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; } private < T > List < T > list ( T ... values ) { return Arrays . asList ( values ) ; } } package com . asakusafw . modelgen . util ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . asakusafw . modelgen . model . Aggregator ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . Source ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . model . SummarizedModelDescription ; import com . asakusafw . modelgen . model . TableModelDescription ; public class SummarizedModelBuilderTest { @ Test public void simple ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . COUNT , "" ) . groupBy ( "" ) . toDescription ( ) ; assertThat ( model . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( model . getGroupBy ( ) , is ( sources ( desc , "" ) ) ) ; List < ModelProperty > properties = model . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty word = properties . get ( ) ; assertThat ( word . getName ( ) , is ( "" ) ) ; assertThat ( word . getType ( ) . getKind ( ) , is ( PropertyTypeKind . STRING ) ) ; assertThat ( word . getJoined ( ) , is ( nullValue ( ) ) ) ; assertThat ( word . getFrom ( ) , is ( source ( desc , "" , Aggregator . IDENT ) ) ) ; ModelProperty count = properties . get ( ) ; assertThat ( count . getName ( ) , is ( "" ) ) ; assertThat ( count . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( count . getJoined ( ) , is ( nullValue ( ) ) ) ; assertThat ( count . getFrom ( ) , is ( source ( desc , "" , Aggregator . COUNT ) ) ) ; } @ Test public void singleGroup ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . COUNT , "" ) . toDescription ( ) ; assertThat ( model . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( model . getGroupBy ( ) , is ( sources ( desc ) ) ) ; List < ModelProperty > properties = model . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty count = properties . get ( ) ; assertThat ( count . getName ( ) , is ( "" ) ) ; assertThat ( count . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( count . getFrom ( ) , is ( source ( desc , "" , Aggregator . COUNT ) ) ) ; } @ Test public void multiGroupKey ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . BYTE ) . add ( null , "" , PropertyTypeKind . SHORT ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . COUNT , "" ) . groupBy ( "" , "" ) . toDescription ( ) ; assertThat ( model . getReference ( ) . getSimpleName ( ) , is ( "" ) ) ; assertThat ( model . getGroupBy ( ) , is ( sources ( desc , "" , "" ) ) ) ; List < ModelProperty > properties = model . getProperties ( ) ; assertThat ( properties . size ( ) , is ( ) ) ; ModelProperty sex = properties . get ( ) ; assertThat ( sex . getName ( ) , is ( "" ) ) ; assertThat ( sex . getType ( ) . getKind ( ) , is ( PropertyTypeKind . BYTE ) ) ; assertThat ( sex . getFrom ( ) , is ( source ( desc , "" , Aggregator . IDENT ) ) ) ; ModelProperty age = properties . get ( ) ; assertThat ( age . getName ( ) , is ( "" ) ) ; assertThat ( age . getType ( ) . getKind ( ) , is ( PropertyTypeKind . SHORT ) ) ; assertThat ( age . getFrom ( ) , is ( source ( desc , "" , Aggregator . IDENT ) ) ) ; ModelProperty count = properties . get ( ) ; assertThat ( count . getName ( ) , is ( "" ) ) ; assertThat ( count . getType ( ) . getKind ( ) , is ( PropertyTypeKind . LONG ) ) ; assertThat ( count . getFrom ( ) , is ( source ( desc , "" , Aggregator . COUNT ) ) ) ; } @ Test ( expected = RuntimeException . class ) public void empty ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . toDescription ( ) ; } @ Test ( expected = RuntimeException . class ) public void missingAggregatingColumn ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . IDENT , "" ) ; } @ Test ( expected = RuntimeException . class ) public void missingGroupingColumn ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . groupBy ( "" ) ; } @ Test ( expected = RuntimeException . class ) public void invalidIdent ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . add ( null , "" , PropertyTypeKind . INT ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . IDENT , "" ) . groupBy ( "" ) . toDescription ( ) ; } @ Test ( expected = RuntimeException . class ) public void invalidAggregation ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . SUM , "" ) ; } @ Test ( expected = RuntimeException . class ) public void noGroupColumn ( ) { TableModelDescription desc = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . STRING ) . toDescription ( ) ; new SummarizedModelBuilder ( "" , desc , "" ) . add ( "" , Aggregator . COUNT , "" ) . groupBy ( "" ) . toDescription ( ) ; } private Source source ( ModelDescription model , String name , Aggregator aggr ) { for ( Source s : model . getPropertiesAsSources ( ) ) { if ( name . equals ( s . getName ( ) ) ) { return new Source ( aggr , s . getDeclaring ( ) , s . getName ( ) , s . getType ( ) , s . getAttributes ( ) ) ; } } throw new AssertionError ( name ) ; } private List < Source > sources ( ModelDescription model , String ... names ) { List < Source > results = new ArrayList < Source > ( ) ; Set < String > targets = new HashSet < String > ( ) ; Collections . addAll ( targets , names ) ; for ( Source s : model . getPropertiesAsSources ( ) ) { if ( targets . contains ( s . getName ( ) ) ) { results . add ( s ) ; } } return results ; } } package com . asakusafw . modelgen . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . StringReader ; import java . io . StringWriter ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . model . TableModelDescription ; import com . asakusafw . modelgen . util . TableModelBuilder ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . runtime . io . TsvEmitter ; import com . asakusafw . runtime . io . TsvParser ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateUtil ; public class ModelOutputEmitterTest extends EmitterTestRoot { private StringWriter buffer ; private RecordEmitter emitter ; private RecordParser parser ( ) throws IOException { return new TsvParser ( new StringReader ( buffer . toString ( ) ) ) ; } @ Override @ Before public void setUp ( ) throws Exception { super . setUp ( ) ; this . buffer = new StringWriter ( ) ; this . emitter = new TsvEmitter ( buffer ) ; } @ Test public void simple ( ) throws Throwable { TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; new TsvIn ( ) . emit ( model ) ; new TsvOut ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object obj = create ( loader , "" ) ; ModelOutput < Object > output = createOutput ( loader , emitter , "" ) ; set ( obj , "" , ) ; output . write ( obj ) ; set ( obj , "" , ) ; output . write ( obj ) ; set ( obj , "" , ) ; output . write ( obj ) ; output . close ( ) ; RecordParser parser = parser ( ) ; ModelInput < Object > input = createInput ( loader , parser , "" ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( input . readTo ( obj ) , is ( false ) ) ; input . close ( ) ; } @ Test public void complex ( ) throws Throwable { TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . add ( null , "" , PropertyTypeKind . DATE ) . add ( null , "" , PropertyTypeKind . INT ) . add ( null , "" , PropertyTypeKind . BOOLEAN ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; new TsvIn ( ) . emit ( model ) ; new TsvOut ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object obj = create ( loader , "" ) ; ModelOutput < Object > output = createOutput ( loader , emitter , "" ) ; set ( obj , "" , ) ; set ( obj , "" , "" ) ; set ( obj , "" , date ( , , ) ) ; set ( obj , "" , ) ; set ( obj , "" , true ) ; output . write ( obj ) ; set ( obj , "" , ) ; set ( obj , "" , "" ) ; set ( obj , "" , date ( , , ) ) ; set ( obj , "" , ) ; set ( obj , "" , false ) ; output . write ( obj ) ; set ( obj , "" , ) ; set ( obj , "" , "" ) ; set ( obj , "" , date ( , , ) ) ; set ( obj , "" , ) ; set ( obj , "" , true ) ; output . write ( obj ) ; output . close ( ) ; RecordParser parser = parser ( ) ; ModelInput < Object > input = createInput ( loader , parser , "" ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) date ( , , ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) true ) ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) date ( , , ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) false ) ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) date ( , , ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) true ) ) ; assertThat ( input . readTo ( obj ) , is ( false ) ) ; input . close ( ) ; } private Date date ( int year , int month , int day ) { Date date = new Date ( ) ; date . setElapsedDays ( DateUtil . getDayFromDate ( year , month , day ) ) ; return date ; } } package com . asakusafw . modelgen . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . modelgen . model . JoinedModelDescription ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . model . TableModelDescription ; import com . asakusafw . modelgen . util . JoinedModelBuilder ; import com . asakusafw . modelgen . util . TableModelBuilder ; public class JoinedModelEntityEmitterTest extends EmitterTestRoot { @ Test public void simple ( ) throws Throwable { TableModelDescription a = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; TableModelDescription b = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; JoinedModelDescription j = new JoinedModelBuilder ( "" , a , "" , b , "" ) . on ( "" , "" ) . add ( "" , "" ) . add ( "" , "" ) . add ( "" , "" ) . toDescription ( ) ; new Table ( ) . emit ( a ) ; new Table ( ) . emit ( b ) ; new Joined ( ) . emit ( j ) ; ClassLoader loader = compile ( ) ; Object jObj = loader . loadClass ( "" ) . newInstance ( ) ; set ( jObj , "" , ) ; set ( jObj , "" , "" ) ; set ( jObj , "" , "" ) ; assertThat ( get ( jObj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( jObj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( jObj , "" ) , is ( ( Object ) "" ) ) ; Object copy = loader . loadClass ( "" ) . newInstance ( ) ; copyFrom ( copy , jObj ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) "" ) ) ; Object aObj = loader . loadClass ( "" ) . newInstance ( ) ; Object bObj = loader . loadClass ( "" ) . newInstance ( ) ; set ( aObj , "" , ) ; set ( bObj , "" , ) ; set ( aObj , "" , "" ) ; set ( bObj , "" , "" ) ; joinFrom ( jObj , aObj , bObj ) ; assertThat ( get ( jObj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( jObj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( jObj , "" ) , is ( ( Object ) "" ) ) ; split ( copy , aObj , bObj ) ; assertThat ( get ( aObj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( aObj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( bObj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( bObj , "" ) , is ( ( Object ) "" ) ) ; } } package com . asakusafw . modelgen . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . modelgen . model . Aggregator ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . model . SummarizedModelDescription ; import com . asakusafw . modelgen . model . TableModelDescription ; import com . asakusafw . modelgen . util . SummarizedModelBuilder ; import com . asakusafw . modelgen . util . TableModelBuilder ; public class SummarizedModelEntityEmitterTest extends EmitterTestRoot { @ Test public void simple ( ) throws Throwable { TableModelDescription a = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , a , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . COUNT , "" ) . groupBy ( "" ) . toDescription ( ) ; new Table ( ) . emit ( a ) ; new Summarized ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object sObj = loader . loadClass ( "" ) . newInstance ( ) ; set ( sObj , "" , "" ) ; set ( sObj , "" , ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; Object copy = loader . loadClass ( "" ) . newInstance ( ) ; copyFrom ( copy , sObj ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) ) ) ; Object aObj = loader . loadClass ( "" ) . newInstance ( ) ; set ( aObj , "" , ) ; set ( aObj , "" , "" ) ; startSummarize ( sObj , aObj ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; set ( copy , "" , "" ) ; set ( copy , "" , ) ; combineSummarize ( sObj , copy ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; combineSummarize ( sObj , copy ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; } @ Test public void aggregators ( ) throws Throwable { TableModelDescription a = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , PropertyTypeKind . INT ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , a , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . SUM , "" ) . add ( "" , Aggregator . COUNT , "" ) . add ( "" , Aggregator . MAX , "" ) . add ( "" , Aggregator . MIN , "" ) . groupBy ( "" ) . toDescription ( ) ; new Table ( ) . emit ( a ) ; new Summarized ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object aObj = loader . loadClass ( "" ) . newInstance ( ) ; Object bObj = loader . loadClass ( "" ) . newInstance ( ) ; Object cObj = loader . loadClass ( "" ) . newInstance ( ) ; set ( aObj , "" , ) ; set ( aObj , "" , ) ; set ( bObj , "" , ) ; set ( bObj , "" , ) ; set ( cObj , "" , ) ; set ( cObj , "" , ) ; Object sObj = loader . loadClass ( "" ) . newInstance ( ) ; Object temp = loader . loadClass ( "" ) . newInstance ( ) ; startSummarize ( sObj , bObj ) ; startSummarize ( temp , aObj ) ; combineSummarize ( sObj , temp ) ; startSummarize ( temp , cObj ) ; combineSummarize ( sObj , temp ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( sObj , "" ) , is ( ( Object ) ) ) ; } @ Test public void booleanGetter ( ) throws Throwable { TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , PropertyTypeKind . BOOLEAN ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object hello = loader . loadClass ( "" ) . newInstance ( ) ; set ( hello , "" , ) ; set ( hello , "" , true ) ; assertThat ( get ( hello , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( hello , "" ) , is ( ( Object ) true ) ) ; } @ Test public void bad_name ( ) throws Throwable { TableModelDescription a = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; SummarizedModelDescription model = new SummarizedModelBuilder ( "" , a , "" ) . add ( "" , Aggregator . IDENT , "" ) . add ( "" , Aggregator . COUNT , "" ) . groupBy ( "" ) . toDescription ( ) ; new Table ( ) . emit ( a ) ; new Summarized ( ) . emit ( model ) ; } } package com . asakusafw . modelgen . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . model . TableModelDescription ; import com . asakusafw . modelgen . util . TableModelBuilder ; public class TableModelEntityEmitterTest extends EmitterTestRoot { @ Test public void simple ( ) throws Throwable { TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object hello = loader . loadClass ( "" ) . newInstance ( ) ; set ( hello , "" , ) ; set ( hello , "" , "" ) ; assertThat ( get ( hello , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( hello , "" ) , is ( ( Object ) "" ) ) ; Object copy = loader . loadClass ( "" ) . newInstance ( ) ; copyFrom ( copy , hello ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) "" ) ) ; } @ Test public void booleanGetter ( ) throws Throwable { TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , PropertyTypeKind . BOOLEAN ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object hello = loader . loadClass ( "" ) . newInstance ( ) ; set ( hello , "" , ) ; set ( hello , "" , true ) ; assertThat ( get ( hello , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( hello , "" ) , is ( ( Object ) true ) ) ; } @ Test public void writable ( ) throws Throwable { TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object hello = loader . loadClass ( "" ) . newInstance ( ) ; set ( hello , "" , ) ; set ( hello , "" , "" ) ; assertThat ( hello , instanceOf ( Writable . class ) ) ; Object restored = restore ( hello ) ; assertThat ( restored , not ( sameInstance ( hello ) ) ) ; assertThat ( restored , equalTo ( hello ) ) ; } @ Test public void namespace ( ) throws Throwable { TableModelDescription model = new TableModelBuilder ( "" ) . namespace ( "" , "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Class < ? > klass = loader . loadClass ( "" ) ; Object hello = klass . newInstance ( ) ; set ( hello , "" , ) ; set ( hello , "" , "" ) ; assertThat ( get ( hello , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( hello , "" ) , is ( ( Object ) "" ) ) ; Object copy = klass . newInstance ( ) ; copyFrom ( copy , hello ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( copy , "" ) , is ( ( Object ) "" ) ) ; } } package com . asakusafw . modelgen . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import org . hamcrest . Matcher ; import org . junit . Test ; public class JavaNameTest { @ Test public void snake_name_of ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void CONSTANT_NAME_OF ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void memberNameOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void TypeNameOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void constantSingleWordOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" ) ) ; } @ Test public void capitalSingleWordOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" ) ) ; } @ Test public void lowerSingleWordOf ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void of_empty ( ) { JavaName . of ( "" ) ; } @ Test ( expected = IllegalArgumentException . class ) public void of_underscore ( ) { JavaName . of ( "" ) ; } @ Test public void of_reduplicate_underscore ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" ) ) ; } @ Test public void of_starts_with_underscore ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" ) ) ; } @ Test public void toTypeName ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . toTypeName ( ) , is ( "" ) ) ; } @ Test public void toMemberName ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . toMemberName ( ) , is ( "" ) ) ; } @ Test public void toConstantName ( ) { JavaName name = JavaName . of ( "" ) ; assertThat ( name . toConstantName ( ) , is ( "" ) ) ; } @ Test public void addFirst ( ) { JavaName name = JavaName . of ( "" ) ; name . addFirst ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" , "" , "" , "" ) ) ; } @ Test public void addLast ( ) { JavaName name = JavaName . of ( "" ) ; name . addLast ( "" ) ; assertThat ( name . getSegments ( ) , contains ( "" , "" , "" , "" , "" ) ) ; } private < T > Matcher < ? super List < T > > contains ( T ... values ) { return is ( Arrays . asList ( values ) ) ; } } package com . asakusafw . modelgen . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . PrintWriter ; import java . lang . reflect . Constructor ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . apache . hadoop . io . Writable ; import org . junit . After ; import org . junit . Before ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . util . Emitter ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . JoinedModel ; import com . asakusafw . vocabulary . model . SummarizedModel ; public abstract class EmitterTestRoot { protected ModelFactory f ; List < VolatileJavaFile > files ; VolatileCompiler compiler ; @ Before public void setUp ( ) throws Exception { f = Models . getModelFactory ( ) ; files = new ArrayList < VolatileJavaFile > ( ) ; compiler = new VolatileCompiler ( ) ; } @ After public void tearDown ( ) throws Exception { if ( compiler != null ) { compiler . close ( ) ; } } protected PrintWriter createOutputFor ( CompilationUnit source ) { StringBuilder buf = new StringBuilder ( ) ; TypeDeclaration type = Emitter . findPrimaryType ( source ) ; if ( source . getPackageDeclaration ( ) != null ) { buf . append ( source . getPackageDeclaration ( ) . toString ( ) . replace ( '' , '' ) ) ; buf . append ( '' ) ; } buf . append ( type . getName ( ) . getToken ( ) ) ; VolatileJavaFile file = new VolatileJavaFile ( buf . toString ( ) ) ; files . add ( file ) ; return new PrintWriter ( file . openWriter ( ) ) ; } protected ClassLoader compile ( ) { if ( files . isEmpty ( ) ) { throw new AssertionError ( ) ; } for ( JavaFileObject java : files ) { try { System . out . println ( "" + java . getName ( ) ) ; System . out . println ( java . getCharContent ( true ) ) ; System . out . println ( ) ; System . out . println ( ) ; } catch ( IOException e ) { } compiler . addSource ( java ) ; } compiler . addArguments ( "" ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) == Diagnostic . Kind . ERROR || d . getKind ( ) == Diagnostic . Kind . WARNING ) { throw new AssertionError ( diagnostics ) ; } } return compiler . getClassLoader ( ) ; } protected Object create ( ClassLoader loader , String name ) { try { Class < ? > klass = loader . loadClass ( "" + name ) ; return klass . newInstance ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ SuppressWarnings ( "" ) protected ModelInput < Object > createInput ( ClassLoader loader , RecordParser parser , String name ) { try { Class < ? > klass = loader . loadClass ( "" + name ) ; Constructor < ? > ctor = klass . getConstructor ( RecordParser . class ) ; return ( ModelInput < Object > ) ctor . newInstance ( parser ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } @ SuppressWarnings ( "" ) protected ModelOutput < Object > createOutput ( ClassLoader loader , RecordEmitter emitter , String name ) { try { Class < ? > klass = loader . loadClass ( "" + name ) ; Constructor < ? > ctor = klass . getConstructor ( RecordEmitter . class ) ; return ( ModelOutput < Object > ) ctor . newInstance ( emitter ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public static Object get ( Object object , String name ) throws Throwable { try { return find ( object , name ) . invoke ( object ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public static void set ( Object object , String name , Object value ) throws Throwable { try { Method method = find ( object , name ) ; method . invoke ( object , value ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public static void copyFrom ( Object object , Object argument ) throws Throwable { try { Method method = find ( object , DataModel . Interface . METHOD_NAME_COPY_FROM ) ; method . invoke ( object , argument ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public static void joinFrom ( Object object , Object left , Object right ) throws Throwable { try { Method method = find ( object , JoinedModel . Interface . METHOD_NAME_JOIN_FROM ) ; method . invoke ( object , left , right ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public static void split ( Object object , Object left , Object right ) throws Throwable { try { Method method = find ( object , JoinedModel . Interface . METHOD_NAME_SPLIT_INTO ) ; method . invoke ( object , left , right ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public static void startSummarize ( Object object , Object argument ) throws Throwable { try { Method method = find ( object , SummarizedModel . Interface . METHOD_NAME_START_SUMMARIZATION ) ; method . invoke ( object , argument ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public static void combineSummarize ( Object object , Object argument ) throws Throwable { try { Method method = find ( object , SummarizedModel . Interface . METHOD_NAME_COMBINE_SUMMARIZATION ) ; method . invoke ( object , argument ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private static Method find ( Object object , String name ) { List < Method > found = new ArrayList < Method > ( ) ; for ( Method method : object . getClass ( ) . getMethods ( ) ) { if ( method . getName ( ) . equals ( name ) ) { found . add ( method ) ; } } if ( found . size ( ) != ) { throw new AssertionError ( name + found ) ; } return found . get ( ) ; } @ SuppressWarnings ( "" ) protected < T > T restore ( T value ) { assertThat ( value , instanceOf ( Writable . class ) ) ; Writable writable = ( Writable ) value ; try { ByteArrayOutputStream write = new ByteArrayOutputStream ( ) ; ObjectOutputStream out = new ObjectOutputStream ( write ) ; writable . write ( out ) ; out . close ( ) ; ByteArrayInputStream read = new ByteArrayInputStream ( write . toByteArray ( ) ) ; ObjectInputStream in = new ObjectInputStream ( read ) ; Writable copy = writable . getClass ( ) . newInstance ( ) ; copy . readFields ( in ) ; assertThat ( in . read ( ) , is ( - ) ) ; assertThat ( copy , is ( ( Writable ) value ) ) ; assertThat ( copy . hashCode ( ) , is ( value . hashCode ( ) ) ) ; return ( T ) copy ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected class Table extends TableModelEntityEmitter { Table ( ) { super ( Models . getModelFactory ( ) , new File ( "" ) , "" , Collections . singletonList ( "" ) ) ; } @ Override protected PrintWriter openOutputFor ( CompilationUnit source ) throws IOException { return createOutputFor ( source ) ; } } protected class Joined extends JoinedModelEntityEmitter { Joined ( ) { super ( Models . getModelFactory ( ) , new File ( "" ) , "" , Collections . singletonList ( "" ) ) ; } @ Override protected PrintWriter openOutputFor ( CompilationUnit source ) throws IOException { return createOutputFor ( source ) ; } } protected class Summarized extends SummarizedModelEntityEmitter { Summarized ( ) { super ( Models . getModelFactory ( ) , new File ( "" ) , "" , Collections . singletonList ( "" ) ) ; } @ Override protected PrintWriter openOutputFor ( CompilationUnit source ) throws IOException { return createOutputFor ( source ) ; } } protected class TsvIn extends ModelInputEmitter { TsvIn ( ) { super ( Models . getModelFactory ( ) , new File ( "" ) , "" , Collections . singletonList ( "" ) ) ; } @ Override protected PrintWriter openOutputFor ( CompilationUnit source ) throws IOException { return createOutputFor ( source ) ; } } protected class TsvOut extends ModelOutputEmitter { TsvOut ( ) { super ( Models . getModelFactory ( ) , new File ( "" ) , "" , Collections . singletonList ( "" ) ) ; } @ Override protected PrintWriter openOutputFor ( CompilationUnit source ) throws IOException { return createOutputFor ( source ) ; } } } package com . asakusafw . modelgen . emitter ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import org . junit . After ; import org . junit . Test ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . model . TableModelDescription ; import com . asakusafw . modelgen . util . TableModelBuilder ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . TsvParser ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateUtil ; public class ModelInputEmitterTest extends EmitterTestRoot { private TsvParser parser ; private void init ( String fileName ) throws IOException { InputStream in = ModelInputEmitterTest . class . getResourceAsStream ( "" + fileName ) ; assertThat ( fileName , in , is ( not ( nullValue ( ) ) ) ) ; parser = new TsvParser ( new InputStreamReader ( in , "" ) ) ; } @ Override @ After public void tearDown ( ) throws Exception { if ( parser != null ) { parser . close ( ) ; } super . tearDown ( ) ; } @ Test public void simple ( ) throws Throwable { init ( "" ) ; TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; new TsvIn ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object obj = create ( loader , "" ) ; ModelInput < Object > input = createInput ( loader , parser , "" ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( input . readTo ( obj ) , is ( false ) ) ; input . close ( ) ; } @ Test public void complex ( ) throws Throwable { init ( "" ) ; TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . add ( null , "" , new StringType ( ) ) . add ( null , "" , PropertyTypeKind . DATE ) . add ( null , "" , PropertyTypeKind . INT ) . add ( null , "" , PropertyTypeKind . BOOLEAN ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; new TsvIn ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object obj = create ( loader , "" ) ; ModelInput < Object > input = createInput ( loader , parser , "" ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) date ( , , ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) true ) ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) date ( , , ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) false ) ) ; assertThat ( input . readTo ( obj ) , is ( true ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) "" ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) date ( , , ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) ) ) ; assertThat ( get ( obj , "" ) , is ( ( Object ) true ) ) ; assertThat ( input . readTo ( obj ) , is ( false ) ) ; input . close ( ) ; } @ Test public void empty ( ) throws Throwable { init ( "" ) ; TableModelDescription model = new TableModelBuilder ( "" ) . add ( null , "" , PropertyTypeKind . LONG , Attribute . PRIMARY_KEY ) . toDescription ( ) ; new Table ( ) . emit ( model ) ; new TsvIn ( ) . emit ( model ) ; ClassLoader loader = compile ( ) ; Object obj = create ( loader , "" ) ; ModelInput < Object > input = createInput ( loader , parser , "" ) ; assertThat ( input . readTo ( obj ) , is ( false ) ) ; input . close ( ) ; } private Date date ( int year , int month , int day ) { Date date = new Date ( ) ; date . setElapsedDays ( DateUtil . getDayFromDate ( year , month , day ) ) ; return date ; } } package com . asakusafw . modelgen ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . sql . SQLException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . Properties ; import java . util . Scanner ; import java . util . concurrent . Callable ; import java . util . regex . Pattern ; import java . util . regex . PatternSyntaxException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . modelgen . emitter . AnyModelEntityEmitter ; import com . asakusafw . modelgen . emitter . ModelInputEmitter ; import com . asakusafw . modelgen . emitter . ModelOutputEmitter ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelRepository ; import com . asakusafw . modelgen . source . DatabaseSource ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; public class Main implements Callable < ModelRepository > { static final Logger LOG = LoggerFactory . getLogger ( Main . class ) ; private Configuration configuration ; public Main ( Configuration configuration ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . configuration = configuration ; } @ Override public ModelRepository call ( ) { ModelRepository repository = new ModelRepository ( ) ; try { collectFromDb ( repository ) ; } catch ( IOException e ) { LOG . error ( "" , e ) ; return null ; } catch ( SQLException e ) { LOG . error ( "" , e ) ; e . printStackTrace ( ) ; } try { collectFromViews ( repository ) ; } catch ( IOException e ) { LOG . error ( "" , e ) ; return null ; } catch ( SQLException e ) { LOG . error ( "" , e ) ; e . printStackTrace ( ) ; } emit ( repository ) ; return repository ; } private void collectFromDb ( ModelRepository repository ) throws IOException , SQLException { LOG . info ( "" , configuration . getJdbcUrl ( ) ) ; DatabaseSource source = new DatabaseSource ( configuration . getJdbcDriver ( ) , configuration . getJdbcUrl ( ) , configuration . getJdbcUser ( ) , configuration . getJdbcPassword ( ) , configuration . getDatabaseName ( ) ) ; try { List < ModelDescription > collected = source . collectTables ( configuration . getMatcher ( ) ) ; for ( ModelDescription model : collected ) { LOG . info ( "" , model . getReference ( ) ) ; repository . add ( model ) ; } LOG . info ( "" , collected . size ( ) ) ; } finally { source . close ( ) ; } } private void collectFromViews ( ModelRepository repository ) throws IOException , SQLException { LOG . info ( "" , configuration . getJdbcUrl ( ) ) ; DatabaseSource source = new DatabaseSource ( configuration . getJdbcDriver ( ) , configuration . getJdbcUrl ( ) , configuration . getJdbcUser ( ) , configuration . getJdbcPassword ( ) , configuration . getDatabaseName ( ) ) ; try { List < ModelDescription > collected = source . collectViews ( repository , configuration . getMatcher ( ) ) ; for ( ModelDescription model : collected ) { LOG . info ( "" , model . getReference ( ) ) ; repository . add ( model ) ; } LOG . info ( "" , collected . size ( ) ) ; } finally { source . close ( ) ; } } private void emit ( ModelRepository repository ) { List < ModelDescription > models = repository . all ( ) ; int total = models . size ( ) ; LOG . info ( "" , total , configuration . getOutput ( ) ) ; ModelFactory factory = Models . getModelFactory ( ) ; AnyModelEntityEmitter modelEmitter = new AnyModelEntityEmitter ( factory , configuration . getOutput ( ) , configuration . getBasePackage ( ) , configuration . getHeaderComments ( ) ) ; ModelInputEmitter tsvInEmitter = new ModelInputEmitter ( factory , configuration . getOutput ( ) , configuration . getBasePackage ( ) , configuration . getHeaderComments ( ) ) ; ModelOutputEmitter tsvOutEmitter = new ModelOutputEmitter ( factory , configuration . getOutput ( ) , configuration . getBasePackage ( ) , configuration . getHeaderComments ( ) ) ; int successCount = ; int failedCount = ; for ( ModelDescription model : models ) { LOG . info ( "" , model . getReference ( ) , ( total - successCount - failedCount ) ) ; try { modelEmitter . emit ( model ) ; tsvInEmitter . emit ( model ) ; tsvOutEmitter . emit ( model ) ; successCount ++ ; } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , model . getReference ( ) ) , e ) ; failedCount ++ ; } } if ( failedCount >= ) { LOG . error ( "" , failedCount ) ; } else { LOG . info ( "" , total ) ; } } public static void main ( String ... args ) { Configuration conf = loadConfigurationFromEnvironment ( ) ; new Main ( conf ) . call ( ) ; } public static Configuration loadConfigurationFromEnvironment ( ) { Configuration result = new Configuration ( ) ; String jdbc = findVariable ( Constants . ENV_JDBC_PROPERTIES , true ) ; try { Properties jdbcProps = loadProperties ( jdbc ) ; result . setJdbcDriver ( findProperty ( jdbcProps , Constants . K_JDBC_DRIVER ) ) ; result . setJdbcUrl ( findProperty ( jdbcProps , Constants . K_JDBC_URL ) ) ; result . setJdbcUser ( findProperty ( jdbcProps , Constants . K_JDBC_USER ) ) ; result . setJdbcPassword ( findProperty ( jdbcProps , Constants . K_JDBC_PASSWORD ) ) ; result . setDatabaseName ( findProperty ( jdbcProps , Constants . K_DATABASE_NAME ) ) ; LOG . info ( "" , jdbcProps ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , Constants . ENV_JDBC_PROPERTIES , jdbc ) , e ) ; } String pkg = findVariable ( Constants . ENV_BASE_PACKAGE , true ) ; try { Models . toName ( Models . getModelFactory ( ) , pkg ) ; } catch ( IllegalArgumentException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , Constants . ENV_BASE_PACKAGE , pkg ) ) ; } result . setBasePackage ( pkg ) ; LOG . info ( "" , pkg ) ; String output = findVariable ( Constants . ENV_OUTPUT , true ) ; result . setOutput ( new File ( output ) ) ; LOG . info ( "" , output ) ; String includes = findVariable ( Constants . ENV_MODEL_INCLUDES , false ) ; if ( includes != null && includes . isEmpty ( ) == false ) { try { Pattern pattern = Pattern . compile ( includes , Pattern . CASE_INSENSITIVE ) ; result . setMatcher ( new ModelMatcher . Regex ( pattern ) ) ; LOG . info ( "" , pattern ) ; } catch ( PatternSyntaxException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , includes ) , e ) ; } } else { result . setMatcher ( ModelMatcher . ALL ) ; } String excludes = findVariable ( Constants . ENV_MODEL_EXCLUDES , false ) ; if ( excludes != null && excludes . isEmpty ( ) == false ) { try { Pattern pattern = Pattern . compile ( excludes , Pattern . CASE_INSENSITIVE ) ; result . setMatcher ( new ModelMatcher . And ( result . getMatcher ( ) , new ModelMatcher . Not ( new ModelMatcher . Regex ( pattern ) ) ) ) ; LOG . info ( "" , pattern ) ; } catch ( PatternSyntaxException e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , excludes ) , e ) ; } } String comment = findVariable ( Constants . ENV_HEADER_COMENT , false ) ; if ( comment != null ) { try { List < String > commentLines = loadLines ( comment ) ; result . setHeaderComments ( commentLines ) ; LOG . info ( "" , commentLines ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , Constants . ENV_HEADER_COMENT , comment ) , e ) ; } } return result ; } private static String findVariable ( List < String > variableNames , boolean mandatory ) { assert variableNames != null ; assert variableNames . isEmpty ( ) == false ; LOG . debug ( "" , variableNames . get ( ) ) ; String value = null ; for ( String var : variableNames ) { value = System . getProperty ( var ) ; if ( value == null ) { value = System . getenv ( var ) ; } if ( value != null ) { break ; } } if ( mandatory && value == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , variableNames . get ( ) ) ) ; } LOG . debug ( "" , variableNames . get ( ) , value ) ; return value ; } private static Properties loadProperties ( String path ) throws IOException { assert path != null ; LOG . debug ( "" , path ) ; InputStream in = new FileInputStream ( path ) ; try { Properties result = new Properties ( ) ; result . load ( in ) ; return result ; } finally { in . close ( ) ; } } private static List < String > loadLines ( String path ) throws IOException { Scanner scanner = new Scanner ( new File ( path ) , "" ) ; List < String > result = new ArrayList < String > ( ) ; while ( scanner . hasNextLine ( ) ) { result . add ( scanner . nextLine ( ) ) ; } return result ; } private static String findProperty ( Properties properties , String key ) { assert properties != null ; assert key != null ; LOG . debug ( "" , key ) ; String value = properties . getProperty ( key ) ; if ( value == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , key ) ) ; } return value ; } } package com . asakusafw . modelgen . model ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; public class SummarizedModelDescription extends ModelDescription { private final List < Source > groupBy ; public SummarizedModelDescription ( ModelReference reference , List < ModelProperty > properties , List < Source > groupBy ) { super ( reference , properties ) ; this . groupBy = Collections . unmodifiableList ( new ArrayList < Source > ( groupBy ) ) ; Set < String > groupKeys = new HashSet < String > ( ) ; for ( Source source : groupBy ) { groupKeys . add ( source . getName ( ) ) ; } for ( ModelProperty property : properties ) { if ( property . getJoined ( ) != null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } Source source = property . getFrom ( ) ; if ( source . getAggregator ( ) == Aggregator . IDENT ) { if ( groupKeys . contains ( source . getName ( ) ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } } else if ( source . getAggregator ( ) != Aggregator . COUNT ) { if ( groupKeys . contains ( source . getName ( ) ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } } } } public ModelReference getOriginalModel ( ) { return getProperties ( ) . get ( ) . getFrom ( ) . getDeclaring ( ) ; } public List < Source > getGroupBy ( ) { return groupBy ; } @ Override protected Source convertPropertyToSource ( ModelProperty property ) { Source source = property . getFrom ( ) ; return new Source ( Aggregator . IDENT , getReference ( ) , property . getName ( ) , source . getType ( ) , source . getAttributes ( ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result += result * prime + getReference ( ) . hashCode ( ) ; result += result * prime + getProperties ( ) . hashCode ( ) ; result += result * prime + groupBy . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } SummarizedModelDescription other = ( SummarizedModelDescription ) obj ; if ( getReference ( ) . equals ( other . getReference ( ) ) == false ) { return false ; } if ( getProperties ( ) . equals ( other . getProperties ( ) ) == false ) { return false ; } if ( getGroupBy ( ) . equals ( other . getGroupBy ( ) ) == false ) { return false ; } return true ; } } package com . asakusafw . modelgen . model ; import java . text . MessageFormat ; public class DecimalType implements PropertyType { private int precision ; private int scale ; public DecimalType ( int precision , int scale ) { this . precision = precision ; this . scale = scale ; } public int getPrecision ( ) { return precision ; } public int getScale ( ) { return scale ; } @ Override public PropertyTypeKind getKind ( ) { return PropertyTypeKind . BIG_DECIMAL ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + precision ; result = prime * result + scale ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } DecimalType other = ( DecimalType ) obj ; if ( precision != other . precision ) { return false ; } if ( scale != other . scale ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , String . valueOf ( precision ) , String . valueOf ( scale ) ) ; } } package com . asakusafw . modelgen . model ; public enum Attribute { PRIMARY_KEY , UNIQUE , NOT_NULL , } package com . asakusafw . modelgen . model ; import java . text . MessageFormat ; public class StringType implements PropertyType { private int capacity ; public StringType ( int capacity ) { this . capacity = capacity ; } public int getCapacity ( ) { return capacity ; } @ Override public PropertyTypeKind getKind ( ) { return PropertyTypeKind . STRING ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + capacity ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } StringType other = ( StringType ) obj ; if ( capacity != other . capacity ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , String . valueOf ( capacity ) ) ; } } package com . asakusafw . modelgen . model ; import java . text . MessageFormat ; import java . util . List ; public class TableModelDescription extends ModelDescription { public TableModelDescription ( ModelReference reference , List < ModelProperty > properties ) { super ( reference , properties ) ; for ( ModelProperty property : properties ) { if ( property . getJoined ( ) != null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } Source source = property . getFrom ( ) ; if ( source . getAggregator ( ) != Aggregator . IDENT ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference , property . getName ( ) ) ) ; } } } @ Override protected Source convertPropertyToSource ( ModelProperty property ) { Source source = property . getFrom ( ) ; return new Source ( Aggregator . IDENT , getReference ( ) , property . getName ( ) , source . getType ( ) , source . getAttributes ( ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result += result * prime + getReference ( ) . hashCode ( ) ; result += result * prime + getProperties ( ) . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } TableModelDescription other = ( TableModelDescription ) obj ; if ( getReference ( ) . equals ( other . getReference ( ) ) == false ) { return false ; } if ( getProperties ( ) . equals ( other . getProperties ( ) ) == false ) { return false ; } return true ; } } package com . asakusafw . modelgen . model ; public enum Aggregator { IDENT { @ Override public PropertyType inferType ( PropertyType original ) { return original ; } } , SUM { @ Override public PropertyType inferType ( PropertyType original ) { switch ( original . getKind ( ) ) { case BYTE : case SHORT : case INT : case LONG : return new BasicType ( PropertyTypeKind . LONG ) ; case BIG_DECIMAL : return original ; default : return null ; } } } , COUNT { @ Override public PropertyType inferType ( PropertyType original ) { return new BasicType ( PropertyTypeKind . LONG ) ; } } , MAX { @ Override public PropertyType inferType ( PropertyType original ) { switch ( original . getKind ( ) ) { case INT : case LONG : case BIG_DECIMAL : case DATE : case DATETIME : return original ; default : return null ; } } } , MIN { @ Override public PropertyType inferType ( PropertyType original ) { return MAX . inferType ( original ) ; } } , ; public abstract PropertyType inferType ( PropertyType original ) ; } @ java . lang . Deprecated package com . asakusafw . modelgen . model ; package com . asakusafw . modelgen . model ; import java . text . MessageFormat ; public class ModelProperty { private String name ; private Source from ; private Source joined ; public ModelProperty ( String name , Source from ) { this . name = name ; this . from = from ; } public ModelProperty ( String name , Source from , Source joined ) { this . name = name ; if ( from == null && joined == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } this . from = from ; this . joined = joined ; } public String getName ( ) { return name ; } public PropertyType getType ( ) { Source source = getSource ( ) ; return source . getAggregator ( ) . inferType ( source . getType ( ) ) ; } public Source getSource ( ) { if ( from != null ) { return from ; } assert joined != null ; return joined ; } public Source getFrom ( ) { return from ; } public Source getJoined ( ) { return joined ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( from == null ) ? : from . hashCode ( ) ) ; result = prime * result + ( ( joined == null ) ? : joined . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ModelProperty other = ( ModelProperty ) obj ; if ( name . equals ( other . name ) == false ) { return false ; } if ( from == null ) { if ( other . from != null ) { return false ; } } else if ( from . equals ( other . from ) == false ) { return false ; } if ( joined == null ) { if ( other . joined != null ) { return false ; } } else if ( joined . equals ( other . joined ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( name ) ; builder . append ( "" ) ; builder . append ( from ) ; builder . append ( "" ) ; builder . append ( joined ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . modelgen . model ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public class JoinedModelDescription extends ModelDescription { private List < Source > leftCondition ; private List < Source > rightCondition ; public JoinedModelDescription ( ModelReference reference , List < ModelProperty > properties , List < Source > leftCondition , List < Source > rightCondition ) { super ( reference , properties ) ; if ( leftCondition . isEmpty ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference ) ) ; } if ( leftCondition . size ( ) != rightCondition . size ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , reference ) ) ; } this . leftCondition = Collections . unmodifiableList ( new ArrayList < Source > ( leftCondition ) ) ; this . rightCondition = Collections . unmodifiableList ( new ArrayList < Source > ( rightCondition ) ) ; } @ Override protected Source convertPropertyToSource ( ModelProperty property ) { return new Source ( Aggregator . IDENT , getReference ( ) , property . getName ( ) , property . getType ( ) , Collections . < Attribute > emptySet ( ) ) ; } public ModelReference getFromModel ( ) { return leftCondition . get ( ) . getDeclaring ( ) ; } public ModelReference getJoinModel ( ) { return rightCondition . get ( ) . getDeclaring ( ) ; } public List < Source > getFromCondition ( ) { return leftCondition ; } public List < Source > getJoinCondition ( ) { return rightCondition ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result += result * prime + getReference ( ) . hashCode ( ) ; result += result * prime + getProperties ( ) . hashCode ( ) ; result += result * prime + leftCondition . hashCode ( ) ; result += result * prime + rightCondition . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } JoinedModelDescription other = ( JoinedModelDescription ) obj ; if ( getReference ( ) . equals ( other . getReference ( ) ) == false ) { return false ; } if ( getProperties ( ) . equals ( other . getProperties ( ) ) == false ) { return false ; } if ( leftCondition . equals ( other . leftCondition ) == false ) { return false ; } if ( rightCondition . equals ( other . rightCondition ) == false ) { return false ; } return true ; } } package com . asakusafw . modelgen . model ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; public class Source { private Aggregator aggregator ; private ModelReference declaring ; private String name ; private PropertyType type ; private Set < Attribute > attributes ; public Source ( Aggregator aggregator , ModelReference declaring , String name , PropertyType type , Set < Attribute > attributes ) { this . aggregator = aggregator ; this . declaring = declaring ; this . name = name ; this . type = type ; this . attributes = Collections . unmodifiableSet ( new HashSet < Attribute > ( attributes ) ) ; } public Aggregator getAggregator ( ) { return aggregator ; } public ModelReference getDeclaring ( ) { return declaring ; } public String getName ( ) { return name ; } public PropertyType getType ( ) { return type ; } public Set < Attribute > getAttributes ( ) { return attributes ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + aggregator . hashCode ( ) ; result = prime * result + attributes . hashCode ( ) ; result = prime * result + declaring . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; result = prime * result + type . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Source other = ( Source ) obj ; if ( aggregator != other . aggregator ) { return false ; } if ( attributes . equals ( other . attributes ) == false ) { return false ; } if ( declaring . equals ( other . declaring ) == false ) { return false ; } if ( name . equals ( other . name ) == false ) { return false ; } if ( type . equals ( other . type ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; builder . append ( declaring ) ; builder . append ( "" ) ; builder . append ( aggregator ) ; builder . append ( "" ) ; builder . append ( name ) ; builder . append ( "" ) ; builder . append ( type ) ; builder . append ( "" ) ; builder . append ( attributes ) ; builder . append ( "" ) ; return builder . toString ( ) ; } } package com . asakusafw . modelgen . model ; public interface PropertyType { PropertyTypeKind getKind ( ) ; } package com . asakusafw . modelgen . model ; public class BasicType implements PropertyType { private PropertyTypeKind kind ; public BasicType ( PropertyTypeKind kind ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( kind . variant ) { throw new IllegalArgumentException ( "" ) ; } this . kind = kind ; } @ Override public PropertyTypeKind getKind ( ) { return kind ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + kind . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } BasicType other = ( BasicType ) obj ; if ( kind != other . kind ) { return false ; } return true ; } @ Override public String toString ( ) { return kind . toString ( ) ; } } package com . asakusafw . modelgen . model ; public enum PropertyTypeKind { BYTE ( false ) , SHORT ( false ) , INT ( false ) , LONG ( false ) , BIG_DECIMAL ( true ) , BOOLEAN ( false ) , STRING ( true ) , DATE ( false ) , DATETIME ( false ) , ; public final boolean variant ; private PropertyTypeKind ( boolean variant ) { this . variant = variant ; } } package com . asakusafw . modelgen . model ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public abstract class ModelDescription { private ModelReference reference ; private List < ModelProperty > properties ; public ModelDescription ( ModelReference reference , List < ModelProperty > properties ) { if ( reference == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } this . reference = reference ; this . properties = Collections . unmodifiableList ( new ArrayList < ModelProperty > ( properties ) ) ; } public ModelReference getReference ( ) { return reference ; } public List < ModelProperty > getProperties ( ) { return properties ; } public List < Source > getPropertiesAsSources ( ) { List < Source > results = new ArrayList < Source > ( ) ; for ( ModelProperty property : getProperties ( ) ) { Source source = convertPropertyToSource ( property ) ; results . add ( source ) ; } return results ; } protected abstract Source convertPropertyToSource ( ModelProperty property ) ; } package com . asakusafw . modelgen . model ; import java . text . MessageFormat ; public class ModelReference { private String namespace ; private String simpleName ; public ModelReference ( String namespace , String simpleName ) { if ( simpleName == null ) { throw new IllegalArgumentException ( "" ) ; } this . namespace = namespace ; this . simpleName = simpleName ; } public boolean isDefaultNameSpace ( ) { return namespace == null ; } public String getNamespace ( ) { return namespace ; } public String getSimpleName ( ) { return simpleName ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( namespace == null ) ? : namespace . hashCode ( ) ) ; result = prime * result + simpleName . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } ModelReference other = ( ModelReference ) obj ; if ( namespace == null ) { if ( other . namespace != null ) { return false ; } } else if ( namespace . equals ( other . namespace ) == false ) { return false ; } if ( simpleName . equals ( other . simpleName ) == false ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , namespace == null ? "" : namespace , simpleName ) ; } } package com . asakusafw . modelgen . model ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; public class ModelRepository { private LinkedHashMap < ModelReference , ModelDescription > models = new LinkedHashMap < ModelReference , ModelDescription > ( ) ; private Map < String , ModelDescription > simpleNames = new HashMap < String , ModelDescription > ( ) ; public void add ( ModelDescription model ) { ModelReference ref = model . getReference ( ) ; if ( models . containsKey ( ref ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , ref ) ) ; } models . put ( ref , model ) ; if ( simpleNames . containsKey ( ref . getSimpleName ( ) ) ) { simpleNames . put ( ref . getSimpleName ( ) , null ) ; } else { simpleNames . put ( ref . getSimpleName ( ) , model ) ; } } public ModelDescription find ( ModelReference reference ) { if ( reference == null ) { throw new IllegalArgumentException ( "" ) ; } return models . get ( reference ) ; } public ModelDescription find ( String simpleName ) { if ( simpleName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( simpleNames . containsKey ( simpleName ) == false ) { return null ; } ModelDescription model = simpleNames . get ( simpleName ) ; if ( model == null ) { List < ModelReference > conflicted = new ArrayList < ModelReference > ( ) ; for ( ModelReference ref : models . keySet ( ) ) { if ( simpleName . equals ( ref . getSimpleName ( ) ) ) { conflicted . add ( ref ) ; } } throw new IllegalStateException ( MessageFormat . format ( "" , simpleName , conflicted ) ) ; } return model ; } public List < ModelDescription > all ( ) { return new ArrayList < ModelDescription > ( models . values ( ) ) ; } public List < TableModelDescription > allTables ( ) { List < TableModelDescription > results = new ArrayList < TableModelDescription > ( ) ; for ( ModelDescription model : models . values ( ) ) { if ( model instanceof TableModelDescription ) { results . add ( ( TableModelDescription ) model ) ; } } return results ; } } package com . asakusafw . modelgen . view . model ; import java . text . MessageFormat ; import com . asakusafw . modelgen . model . Aggregator ; public class Select { public final Name name ; public final Aggregator aggregator ; public final Name alias ; public Select ( Name name , Aggregator aggregator , Name alias ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( aggregator == null ) { throw new IllegalArgumentException ( "" ) ; } if ( alias == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . aggregator = aggregator ; this . alias = alias ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + aggregator . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; result = prime * result + alias . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Select other = ( Select ) obj ; if ( aggregator != other . aggregator ) { return false ; } if ( ! name . equals ( other . name ) ) { return false ; } if ( ! alias . equals ( other . alias ) ) { return false ; } return true ; } @ Override public String toString ( ) { if ( aggregator == Aggregator . IDENT ) { return MessageFormat . format ( "" , name , alias ) ; } else { return MessageFormat . format ( "" , name , aggregator , alias ) ; } } } @ java . lang . Deprecated package com . asakusafw . modelgen . view . model ; package com . asakusafw . modelgen . view . model ; import java . text . MessageFormat ; public class On { public final Name left ; public final Name right ; public On ( Name left , Name right ) { if ( left == null ) { throw new IllegalArgumentException ( "" ) ; } if ( right == null ) { throw new IllegalArgumentException ( "" ) ; } this . left = left ; this . right = right ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + left . hashCode ( ) ; result = prime * result + right . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } On other = ( On ) obj ; if ( ! left . equals ( other . left ) ) { return false ; } if ( ! right . equals ( other . right ) ) { return false ; } return true ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , left , right ) ; } } package com . asakusafw . modelgen . view . model ; public class Name { public final String token ; public Name ( String token ) { if ( token == null ) { throw new IllegalArgumentException ( "" ) ; } this . token = token ; } public Name ( Name qualifier , Name rest ) { if ( qualifier == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rest == null ) { throw new IllegalArgumentException ( "" ) ; } this . token = qualifier . token + "" + rest . token ; } public Name getLastSegment ( ) { int last = token . lastIndexOf ( '' ) ; if ( last >= ) { return new Name ( token . substring ( last + ) ) ; } return this ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + token . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Name other = ( Name ) obj ; if ( ! token . equals ( other . token ) ) { return false ; } return true ; } @ Override public String toString ( ) { return token ; } } package com . asakusafw . modelgen . view . model ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public class Join { public final Name table ; public final String alias ; public final List < On > condition ; public Join ( Name table , String alias , List < On > condition ) { if ( table == null ) { throw new IllegalArgumentException ( "" ) ; } if ( condition == null ) { throw new IllegalArgumentException ( "" ) ; } this . table = table ; this . alias = alias ; this . condition = Collections . unmodifiableList ( new ArrayList < On > ( condition ) ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( alias == null ) ? : alias . hashCode ( ) ) ; result = prime * result + condition . hashCode ( ) ; result = prime * result + table . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } Join other = ( Join ) obj ; if ( ! table . equals ( other . table ) ) { return false ; } if ( alias == null ) { if ( other . alias != null ) { return false ; } } else if ( ! alias . equals ( other . alias ) ) { return false ; } if ( ! condition . equals ( other . condition ) ) { return false ; } return true ; } @ Override public String toString ( ) { if ( alias != null ) { return MessageFormat . format ( "" , table , condition , alias ) ; } else { return MessageFormat . format ( "" , table , condition ) ; } } } package com . asakusafw . modelgen . view . model ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import com . asakusafw . modelgen . model . Aggregator ; public class CreateView { public final Name name ; public final List < Select > selectList ; public final From from ; public final List < Name > groupBy ; public CreateView ( Name name , List < Select > selectList , From from , List < Name > groupBy ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( selectList == null ) { throw new IllegalArgumentException ( "" ) ; } if ( from == null ) { throw new IllegalArgumentException ( "" ) ; } if ( groupBy == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . selectList = Collections . unmodifiableList ( new ArrayList < Select > ( selectList ) ) ; this . from = from ; this . groupBy = Collections . unmodifiableList ( new ArrayList < Name > ( groupBy ) ) ; } public CreateView . Kind getKind ( ) { boolean join = ( from . join != null ) ; boolean summarize = ( groupBy . isEmpty ( ) == false ) ; if ( summarize == false ) { for ( Select select : selectList ) { if ( select . aggregator != Aggregator . IDENT ) { summarize = true ; break ; } } } if ( join && summarize == false ) { return Kind . JOINED ; } if ( summarize && join == false ) { return Kind . SUMMARIZED ; } return Kind . UNKNOWN ; } public Set < Name > getDependencies ( ) { Set < Name > results = new HashSet < Name > ( ) ; results . add ( from . table ) ; if ( from . join != null ) { results . add ( from . join . table ) ; } return results ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + from . hashCode ( ) ; result = prime * result + groupBy . hashCode ( ) ; result = prime * result + name . hashCode ( ) ; result = prime * result + selectList . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } CreateView other = ( CreateView ) obj ; if ( ! from . equals ( other . from ) ) { return false ; } if ( ! groupBy . equals ( other . groupBy ) ) { return false ; } if ( ! name . equals ( other . name ) ) { return false ; } if ( ! selectList . equals ( other . selectList ) ) { return false ; } return true ; } @ Override public String toString ( ) { if ( groupBy . isEmpty ( ) ) { return MessageFormat . format ( "" , name , selectList , from ) ; } else { return MessageFormat . format ( "" , name , selectList , from , groupBy ) ; } } public enum Kind { JOINED , SUMMARIZED , UNKNOWN , } } package com . asakusafw . modelgen . view . model ; import java . text . MessageFormat ; public class From { public final Name table ; public final String alias ; public final Join join ; public From ( Name table , String alias ) { this ( table , alias , null ) ; } public From ( Name table , String alias , Join join ) { if ( table == null ) { throw new IllegalArgumentException ( "" ) ; } this . table = table ; this . alias = alias ; this . join = join ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + table . hashCode ( ) ; result = prime * result + ( ( join == null ) ? : join . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( getClass ( ) != obj . getClass ( ) ) { return false ; } From other = ( From ) obj ; if ( ! table . equals ( other . table ) ) { return false ; } if ( join == null ) { if ( other . join != null ) { return false ; } } else if ( ! join . equals ( other . join ) ) { return false ; } return true ; } @ Override public String toString ( ) { if ( join == null ) { return MessageFormat . format ( "" , table ) ; } else { return MessageFormat . format ( "" , table , join ) ; } } } @ java . lang . Deprecated package com . asakusafw . modelgen . view ; package com . asakusafw . modelgen . view ; public class ViewDefinition { public final String name ; public final String statement ; public ViewDefinition ( String name , String statement ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( statement == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . statement = statement ; } } package com . asakusafw . modelgen . view ; import java . io . IOException ; import java . io . StringReader ; import java . text . MessageFormat ; import com . asakusafw . modelgen . view . model . CreateView ; public final class ViewParser { public static CreateView parse ( ViewDefinition definition ) throws IOException { if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } StringReader stream = new StringReader ( definition . statement ) ; JjViewParser parser = new JjViewParser ( stream ) ; try { CreateView parsed = parser . parse ( definition . name ) ; return parsed ; } catch ( TokenMgrError e ) { throw new IOException ( MessageFormat . format ( "" , definition . name , definition . statement ) , e ) ; } catch ( ParseException e ) { throw new IOException ( MessageFormat . format ( "" , definition . name , definition . statement ) , e ) ; } } private ViewParser ( ) { return ; } } package com . asakusafw . modelgen . view ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . modelgen . model . Aggregator ; import com . asakusafw . modelgen . model . JoinedModelDescription ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelRepository ; import com . asakusafw . modelgen . util . JoinedModelBuilder ; import com . asakusafw . modelgen . util . SummarizedModelBuilder ; import com . asakusafw . modelgen . view . model . CreateView ; import com . asakusafw . modelgen . view . model . CreateView . Kind ; import com . asakusafw . modelgen . view . model . Name ; import com . asakusafw . modelgen . view . model . On ; import com . asakusafw . modelgen . view . model . Select ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; public class ViewAnalyzer { static final Logger LOG = LoggerFactory . getLogger ( ViewAnalyzer . class ) ; private List < View > added = new ArrayList < View > ( ) ; public void add ( List < String > namespace , CreateView view ) { if ( namespace == null ) { throw new IllegalArgumentException ( "" ) ; } if ( view == null ) { throw new IllegalArgumentException ( "" ) ; } added . add ( new View ( namespace , view ) ) ; } public List < ModelDescription > analyze ( ModelRepository repository ) { if ( repository == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . info ( "" , added . size ( ) ) ; List < View > sorted = sort ( ) ; Map < Name , ModelDescription > context = new HashMap < Name , ModelDescription > ( ) ; List < ModelDescription > analyzed = new ArrayList < ModelDescription > ( ) ; for ( View view : sorted ) { LOG . info ( "" , view . ast . name ) ; ModelDescription model = transform ( view , repository , context ) ; context . put ( view . ast . name , model ) ; if ( model != null ) { analyzed . add ( model ) ; } } if ( analyzed . size ( ) != added . size ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , analyzed . size ( ) , added . size ( ) ) ) ; } return analyzed ; } private ModelDescription transform ( View target , ModelRepository repository , Map < Name , ModelDescription > context ) { assert target != null ; assert repository != null ; assert context != null ; CreateView ast = target . ast ; if ( resolveDependency ( ast , repository , context ) == false ) { return null ; } Kind kind = ast . getKind ( ) ; if ( kind == Kind . JOINED ) { return transformJoined ( target , context ) ; } else if ( kind == Kind . SUMMARIZED ) { return transformSummarized ( target , context ) ; } else { LOG . error ( "" , ast . name , ast ) ; return null ; } } private JoinedModelDescription transformJoined ( View target , Map < Name , ModelDescription > context ) { assert target != null ; assert target . ast . getKind ( ) == CreateView . Kind . JOINED ; assert context != null ; CreateView ast = target . ast ; assert context . get ( ast . from . table ) != null ; assert context . get ( ast . from . join . table ) != null ; JoinedModelBuilder builder = new JoinedModelBuilder ( ast . name . token , context . get ( ast . from . table ) , ast . from . alias , context . get ( ast . from . join . table ) , ast . from . join . alias ) ; builder . namespace ( target . namespace ) ; for ( On on : ast . from . join . condition ) { builder . on ( on . left . token , on . right . token ) ; } for ( Select select : ast . selectList ) { assert select . aggregator == Aggregator . IDENT ; builder . add ( select . alias . token , select . name . token ) ; } return builder . toDescription ( ) ; } private ModelDescription transformSummarized ( View target , Map < Name , ModelDescription > context ) { assert target != null ; assert target . ast . getKind ( ) == CreateView . Kind . SUMMARIZED ; CreateView ast = target . ast ; assert context . get ( ast . from . table ) != null ; SummarizedModelBuilder builder = new SummarizedModelBuilder ( ast . name . token , context . get ( ast . from . table ) , ast . from . alias ) ; builder . namespace ( target . namespace ) ; for ( Name name : ast . groupBy ) { builder . groupBy ( name . token ) ; } for ( Select select : ast . selectList ) { builder . add ( select . alias . token , select . aggregator , select . name . token ) ; } return builder . toDescription ( ) ; } private boolean resolveDependency ( CreateView target , ModelRepository repository , Map < Name , ModelDescription > context ) { boolean success = true ; for ( Name dependency : target . getDependencies ( ) ) { LOG . debug ( "" , target . name , dependency ) ; if ( context . containsKey ( dependency ) ) { if ( context . get ( dependency ) == null ) { LOG . warn ( "" , target . name , dependency ) ; return false ; } } else { ModelDescription resolved = repository . find ( dependency . token ) ; if ( resolved == null ) { LOG . error ( "" , target . name , dependency ) ; success = false ; } else { context . put ( dependency , resolved ) ; } } } return success ; } private List < View > sort ( ) { Map < Name , View > map = new HashMap < Name , View > ( ) ; Graph < Name > dependencies = Graphs . newInstance ( ) ; for ( View view : added ) { Name name = view . ast . name ; map . put ( name , view ) ; for ( Name dependTo : view . ast . getDependencies ( ) ) { dependencies . addEdge ( name , dependTo ) ; } } Set < Set < Name > > circuit = Graphs . findCircuit ( dependencies ) ; if ( circuit . isEmpty ( ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , circuit ) ) ; } List < Name > sorted = Graphs . sortPostOrder ( dependencies ) ; List < View > results = new ArrayList < View > ( ) ; for ( Name name : sorted ) { View view = map . get ( name ) ; if ( view != null ) { results . add ( view ) ; } } return results ; } private static class View { String [ ] namespace ; CreateView ast ; View ( List < String > namespace , CreateView ast ) { assert namespace != null ; assert ast != null ; this . namespace = namespace . toArray ( new String [ namespace . size ( ) ] ) ; this . ast = ast ; } } } package com . asakusafw . modelgen ; import java . util . regex . Pattern ; public interface ModelMatcher { ModelMatcher ALL = new ModelMatcher ( ) { @ Override public boolean acceptModel ( String name ) { return true ; } } ; ModelMatcher NOTHING = new ModelMatcher ( ) { @ Override public boolean acceptModel ( String name ) { return false ; } } ; boolean acceptModel ( String name ) ; public class And implements ModelMatcher { private final ModelMatcher [ ] matchers ; public And ( ModelMatcher ... matchers ) { if ( matchers == null ) { throw new IllegalArgumentException ( "" ) ; } this . matchers = matchers . clone ( ) ; } @ Override public boolean acceptModel ( String name ) { for ( ModelMatcher m : matchers ) { if ( m . acceptModel ( name ) == false ) { return false ; } } return true ; } } public class Not implements ModelMatcher { private final ModelMatcher term ; public Not ( ModelMatcher term ) { if ( term == null ) { throw new IllegalArgumentException ( "" ) ; } this . term = term ; } @ Override public boolean acceptModel ( String name ) { return term . acceptModel ( name ) == false ; } } public class Regex implements ModelMatcher { private final Pattern pattern ; public Regex ( Pattern pattern ) { if ( pattern == null ) { throw new IllegalArgumentException ( "" ) ; } this . pattern = pattern ; } @ Override public boolean acceptModel ( String name ) { return pattern . matcher ( name ) . matches ( ) ; } } } package com . asakusafw . modelgen ; import java . nio . charset . Charset ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public final class Constants { public static final String VERSION = "" ; public static final Charset OUTPUT_ENCODING = Charset . forName ( "" ) ; public static final String SOURCE_TABLE = "" ; public static final String SOURCE_VIEW = "" ; public static final String CATEGORY_MODEL = "" ; public static final String CATEGORY_IO = "" ; private static final String [ ] ENV_PREFIX = { "" , "" } ; public static final List < String > ENV_JDBC_PROPERTIES = buildEnvProperties ( "" ) ; public static final List < String > ENV_BASE_PACKAGE = buildEnvProperties ( "" ) ; public static final List < String > ENV_OUTPUT = buildEnvProperties ( "" ) ; public static final List < String > ENV_MODEL_INCLUDES = buildEnvProperties ( "" ) ; public static final List < String > ENV_MODEL_EXCLUDES = buildEnvProperties ( "" ) ; public static final List < String > ENV_HEADER_COMENT = buildEnvProperties ( "" ) ; public static final String K_JDBC_DRIVER = "" ; public static final String K_JDBC_URL = "" ; public static final String K_JDBC_USER = "" ; public static final String K_JDBC_PASSWORD = "" ; public static final String K_DATABASE_NAME = "" ; public static final String NAME_OPTION_COPIER = "" ; public static final String NAME_OPTION_MODIFIER = "" ; public static final String NAME_OPTION_EXTRACTOR = "" ; public static final String NAME_OPTION_ERASER = "" ; public static final String NAME_OPTION_ADDER = "" ; public static final String NAME_OPTION_MAX = "" ; public static final String NAME_OPTION_MIN = "" ; public static final String FORMAT_NAME_MODEL_INPUT = "" ; public static final String FORMAT_NAME_MODEL_OUTPUT = "" ; private static List < String > buildEnvProperties ( String suffix ) { assert suffix != null ; List < String > properties = new ArrayList < String > ( ENV_PREFIX . length ) ; for ( String prefix : ENV_PREFIX ) { properties . add ( prefix + suffix ) ; } return Collections . unmodifiableList ( properties ) ; } private Constants ( ) { return ; } } package com . asakusafw . modelgen ; import java . io . File ; import java . util . List ; public class Configuration { private String jdbcDriver ; private String jdbcUrl ; private String jdbcUser ; private String jdbcPassword ; private String databaseName ; private String basePackage ; private File output ; private List < String > headerComments ; private ModelMatcher matcher ; public String getJdbcDriver ( ) { return jdbcDriver ; } public void setJdbcDriver ( String jdbcDriver ) { this . jdbcDriver = jdbcDriver ; } public String getJdbcUrl ( ) { return jdbcUrl ; } public void setJdbcUrl ( String jdbcUrl ) { this . jdbcUrl = jdbcUrl ; } public String getJdbcUser ( ) { return jdbcUser ; } public void setJdbcUser ( String jdbcUser ) { this . jdbcUser = jdbcUser ; } public String getJdbcPassword ( ) { return jdbcPassword ; } public void setJdbcPassword ( String jdbcPassword ) { this . jdbcPassword = jdbcPassword ; } public String getDatabaseName ( ) { return databaseName ; } public void setDatabaseName ( String databaseName ) { this . databaseName = databaseName ; } public String getBasePackage ( ) { return basePackage ; } public void setBasePackage ( String basePackage ) { this . basePackage = basePackage ; } public File getOutput ( ) { return output ; } public void setOutput ( File output ) { this . output = output ; } public ModelMatcher getMatcher ( ) { return matcher ; } public void setMatcher ( ModelMatcher matcher ) { this . matcher = matcher ; } public List < String > getHeaderComments ( ) { return headerComments ; } public void setHeaderComments ( List < String > headerComments ) { this . headerComments = headerComments ; } } @ java . lang . Deprecated package com . asakusafw . modelgen ; package com . asakusafw . modelgen . util ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . LinkedHashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import com . asakusafw . modelgen . model . Aggregator ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . Source ; import com . asakusafw . modelgen . model . SummarizedModelDescription ; public class SummarizedModelBuilder extends ModelBuilder < SummarizedModelBuilder > { private String alias ; private Map < String , Source > sources ; private List < Source > groupProperties ; private List < Column > columns ; public SummarizedModelBuilder ( String tableName , ModelDescription model , String alias ) { super ( tableName ) ; this . alias = ( alias == null ) ? model . getReference ( ) . getSimpleName ( ) : alias ; this . sources = new TreeMap < String , Source > ( ) ; this . groupProperties = new ArrayList < Source > ( ) ; this . columns = new ArrayList < Column > ( ) ; for ( Source s : model . getPropertiesAsSources ( ) ) { sources . put ( s . getName ( ) , s ) ; } } public SummarizedModelBuilder groupBy ( String ... sourceProperties ) { if ( sourceProperties == null ) { throw new IllegalArgumentException ( "" ) ; } for ( String s : sourceProperties ) { groupProperties . add ( find ( s ) ) ; } return this ; } private Source find ( String sourceProperty ) { assert sourceProperty != null ; int qualified = sourceProperty . indexOf ( '' ) ; String simpleName ; if ( qualified < ) { simpleName = sourceProperty ; } else { String qualifier = sourceProperty . substring ( , qualified ) ; if ( alias . equals ( qualifier ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , sourceProperty , getReference ( ) ) ) ; } simpleName = sourceProperty . substring ( qualified + ) ; } Source source = sources . get ( simpleName ) ; if ( source == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , simpleName , getReference ( ) ) ) ; } return source ; } public SummarizedModelBuilder add ( String columnName , Aggregator aggregator , String sourceProperty ) { if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( aggregator == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sourceProperty == null ) { throw new IllegalArgumentException ( "" ) ; } Source source = find ( sourceProperty ) ; if ( aggregator . inferType ( source . getType ( ) ) == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , source . getDeclaring ( ) , source . getName ( ) , source . getType ( ) , aggregator . name ( ) , getReference ( ) ) ) ; } Column column = new Column ( columnName , aggregator , source ) ; columns . add ( column ) ; return this ; } @ Override public SummarizedModelDescription toDescription ( ) { if ( columns . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , getReference ( ) ) ) ; } List < ModelProperty > properties = new ArrayList < ModelProperty > ( ) ; for ( Column column : columns ) { Aggregator aggregator = column . aggregator ; Source source = column . source ; if ( aggregator == Aggregator . IDENT && groupProperties . contains ( source ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , source . getDeclaring ( ) , source . getName ( ) , getReference ( ) ) ) ; } ModelProperty property = toProperty ( column ) ; properties . add ( property ) ; } validate ( ) ; return new SummarizedModelDescription ( getReference ( ) , properties , groupProperties ) ; } private void validate ( ) { if ( groupProperties . isEmpty ( ) ) { return ; } Set < String > rest = new LinkedHashSet < String > ( ) ; for ( Source source : groupProperties ) { rest . add ( source . getName ( ) ) ; } for ( Column column : columns ) { if ( column . aggregator == Aggregator . IDENT ) { rest . remove ( column . source . getName ( ) ) ; } } if ( rest . isEmpty ( ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , groupProperties . get ( ) . getDeclaring ( ) , rest , getReference ( ) ) ) ; } } private ModelProperty toProperty ( Column column ) { assert column != null ; Source source = new Source ( column . aggregator , column . source . getDeclaring ( ) , column . source . getName ( ) , column . source . getType ( ) , Collections . < Attribute > emptySet ( ) ) ; return new ModelProperty ( column . name , source ) ; } private static class Column { String name ; Aggregator aggregator ; Source source ; Column ( String name , Aggregator aggregator , Source source ) { assert name != null ; assert aggregator != null ; assert source != null ; this . name = name ; this . aggregator = aggregator ; this . source = source ; } } } package com . asakusafw . modelgen . util ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . EnumSet ; import java . util . List ; import java . util . Set ; import com . asakusafw . modelgen . model . Aggregator ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . BasicType ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . PropertyType ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . Source ; import com . asakusafw . modelgen . model . TableModelDescription ; public class TableModelBuilder extends ModelBuilder < TableModelBuilder > { private List < Column > columns ; public TableModelBuilder ( String tableName ) { super ( tableName ) ; this . columns = new ArrayList < Column > ( ) ; } public TableModelBuilder add ( String comment , String columnName , PropertyTypeKind basicTypeKind , Attribute ... attributes ) { if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( basicTypeKind == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } Column column = new Column ( columnName , new BasicType ( basicTypeKind ) , attributes ) ; columns . add ( column ) ; return this ; } public TableModelBuilder add ( String comment , String columnName , PropertyType columnType , Attribute ... attributes ) { if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( attributes == null ) { throw new IllegalArgumentException ( "" ) ; } Column column = new Column ( columnName , columnType , attributes ) ; columns . add ( column ) ; return this ; } @ Override public TableModelDescription toDescription ( ) { if ( columns . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , getReference ( ) ) ) ; } List < ModelProperty > properties = new ArrayList < ModelProperty > ( ) ; for ( Column column : columns ) { ModelProperty property = toProperty ( column ) ; properties . add ( property ) ; } return new TableModelDescription ( getReference ( ) , properties ) ; } private ModelProperty toProperty ( Column column ) { assert column != null ; Source source = new Source ( Aggregator . IDENT , getReference ( ) , column . name , column . type , column . attributes ) ; return new ModelProperty ( column . name , source ) ; } private static class Column { String name ; PropertyType type ; Set < Attribute > attributes ; Column ( String name , PropertyType type , Attribute [ ] attributes ) { assert name != null ; assert type != null ; assert attributes != null ; this . name = name ; this . type = type ; this . attributes = EnumSet . noneOf ( Attribute . class ) ; for ( Attribute attr : attributes ) { this . attributes . add ( attr ) ; } } } } @ java . lang . Deprecated package com . asakusafw . modelgen . util ; package com . asakusafw . modelgen . util ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import com . asakusafw . modelgen . model . JoinedModelDescription ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . Source ; public class JoinedModelBuilder extends ModelBuilder < JoinedModelBuilder > { private List < String > columns ; private Side left ; private Side right ; public JoinedModelBuilder ( String name , ModelDescription left , String leftAlias , ModelDescription right , String rightAlias ) { super ( name ) ; if ( left == null ) { throw new IllegalArgumentException ( "" ) ; } if ( right == null ) { throw new IllegalArgumentException ( "" ) ; } this . columns = new ArrayList < String > ( ) ; this . left = new Side ( left ) ; this . right = new Side ( right ) ; if ( leftAlias != null ) { this . left . alias = leftAlias ; } if ( rightAlias != null ) { this . right . alias = rightAlias ; } if ( this . left . alias . equals ( this . right . alias ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , this . left . alias ) ) ; } } public JoinedModelBuilder on ( String aProperty , String bProperty ) { if ( aProperty == null ) { throw new IllegalArgumentException ( "" ) ; } if ( bProperty == null ) { throw new IllegalArgumentException ( "" ) ; } Ref a = resolve ( aProperty ) ; Ref b = resolve ( bProperty ) ; if ( a . side == b . side ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , aProperty , bProperty ) ) ; } a . side . condition . add ( a . side . find ( a . name ) ) ; b . side . condition . add ( b . side . find ( b . name ) ) ; return this ; } public JoinedModelBuilder add ( String columnName , String sourceProperty ) { if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sourceProperty == null ) { throw new IllegalArgumentException ( "" ) ; } Ref source = resolve ( sourceProperty ) ; columns . add ( columnName ) ; source . side . mapping . put ( source . name , columnName ) ; return this ; } @ Override public JoinedModelDescription toDescription ( ) { if ( left . condition . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , getReference ( ) ) ) ; } if ( columns . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , getReference ( ) ) ) ; } pairingTrivialSource ( left , right ) ; pairingTrivialSource ( right , left ) ; pairingSourceWithSameNamed ( left , right ) ; pairingSourceWithSameNamed ( right , left ) ; return new JoinedModelDescription ( getReference ( ) , buildProperties ( ) , left . condition , right . condition ) ; } private void pairingTrivialSource ( Side a , Side b ) { assert a != null ; assert b != null ; for ( int i = , n = a . condition . size ( ) ; i < n ; i ++ ) { Source as = a . condition . get ( i ) ; Source bs = b . condition . get ( i ) ; if ( a . mapping . containsKey ( as . getName ( ) ) && b . mapping . containsKey ( bs . getName ( ) ) == false ) { String column = a . mapping . get ( as . getName ( ) ) ; b . mapping . put ( bs . getName ( ) , column ) ; } } } private void pairingSourceWithSameNamed ( Side a , Side b ) { assert a != null ; assert b != null ; for ( Map . Entry < String , String > entry : a . mapping . entrySet ( ) ) { if ( entry . getValue ( ) != null ) { continue ; } String unmapped = entry . getKey ( ) ; String opposite = b . mapping . get ( unmapped ) ; if ( opposite == null ) { continue ; } Source as = a . sources . get ( unmapped ) ; Source bs = b . sources . get ( unmapped ) ; assert as != null ; assert bs != null ; if ( as . getType ( ) . equals ( bs . getType ( ) ) == false ) { continue ; } entry . setValue ( opposite ) ; } } private List < ModelProperty > buildProperties ( ) { Map < String , SourcePair > pairs = new TreeMap < String , SourcePair > ( ) ; for ( String mapTo : columns ) { pairs . put ( mapTo , new SourcePair ( ) ) ; } for ( Map . Entry < String , String > entry : left . mapping . entrySet ( ) ) { String mapTo = entry . getValue ( ) ; assert mapTo == null || pairs . containsKey ( mapTo ) ; if ( mapTo == null ) { continue ; } pairs . get ( mapTo ) . left = left . sources . get ( entry . getKey ( ) ) ; } for ( Map . Entry < String , String > entry : right . mapping . entrySet ( ) ) { String mapTo = entry . getValue ( ) ; assert mapTo == null || pairs . containsKey ( mapTo ) ; if ( mapTo == null ) { continue ; } pairs . get ( mapTo ) . right = right . sources . get ( entry . getKey ( ) ) ; } List < ModelProperty > properties = new ArrayList < ModelProperty > ( ) ; for ( String mapTo : columns ) { SourcePair sources = pairs . get ( mapTo ) ; assert sources != null ; assert sources . left != null || sources . right != null ; ModelProperty property = new ModelProperty ( mapTo , sources . left , sources . right ) ; properties . add ( property ) ; } return properties ; } private Ref resolve ( String source ) { assert source != null ; int qualified = source . indexOf ( '' ) ; if ( qualified < ) { boolean leftHit = left . mapping . containsKey ( source ) ; boolean rightHit = right . mapping . containsKey ( source ) ; if ( leftHit && rightHit ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , source , getReference ( ) ) ) ; } if ( leftHit == false && rightHit == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , source , getReference ( ) ) ) ; } if ( leftHit ) { return new Ref ( left , source ) ; } else { return new Ref ( right , source ) ; } } else { String qualifier = source . substring ( , qualified ) ; String column = source . substring ( qualified + ) ; if ( left . alias . equals ( qualifier ) ) { return new Ref ( left , column ) ; } else if ( right . alias . equals ( qualifier ) ) { return new Ref ( right , column ) ; } else { throw new IllegalArgumentException ( MessageFormat . format ( "" , qualifier , source ) ) ; } } } private static class Side { ModelDescription model ; Map < String , Source > sources ; String alias ; List < Source > condition ; Map < String , String > mapping ; Side ( ModelDescription model ) { assert model != null ; this . model = model ; this . sources = new TreeMap < String , Source > ( ) ; this . alias = model . getReference ( ) . getSimpleName ( ) ; this . condition = new ArrayList < Source > ( ) ; this . mapping = new TreeMap < String , String > ( ) ; for ( Source s : model . getPropertiesAsSources ( ) ) { sources . put ( s . getName ( ) , s ) ; mapping . put ( s . getName ( ) , null ) ; } } Source find ( String columnName ) { assert columnName != null ; if ( sources . containsKey ( columnName ) ) { return sources . get ( columnName ) ; } throw new IllegalArgumentException ( MessageFormat . format ( "" , model . getReference ( ) , columnName ) ) ; } } private static class Ref { Side side ; String name ; public Ref ( Side side , String name ) { assert side != null ; assert name != null ; this . side = side ; this . name = name ; } } private static class SourcePair { Source left ; Source right ; SourcePair ( ) { return ; } } } package com . asakusafw . modelgen . util ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelReference ; public abstract class ModelBuilder < T extends ModelBuilder < T > > { private String namespace ; private String simpleName ; public ModelBuilder ( String simpleName ) { if ( simpleName == null ) { throw new IllegalArgumentException ( "" ) ; } this . simpleName = simpleName ; } public ModelReference getReference ( ) { return new ModelReference ( namespace , simpleName ) ; } @ SuppressWarnings ( "" ) public T namespace ( String ... names ) { if ( names == null ) { throw new IllegalArgumentException ( "" ) ; } if ( names . length == ) { this . namespace = null ; } else { StringBuilder buf = new StringBuilder ( ) ; buf . append ( names [ ] ) ; for ( int i = ; i < names . length ; i ++ ) { buf . append ( "" ) ; buf . append ( names [ i ] ) ; } this . namespace = buf . toString ( ) ; } return ( T ) this ; } public abstract ModelDescription toDescription ( ) ; } package com . asakusafw . modelgen . source ; import java . io . Closeable ; import java . io . IOException ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . modelgen . Constants ; import com . asakusafw . modelgen . ModelMatcher ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . DecimalType ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelRepository ; import com . asakusafw . modelgen . model . PropertyTypeKind ; import com . asakusafw . modelgen . model . StringType ; import com . asakusafw . modelgen . util . TableModelBuilder ; import com . asakusafw . modelgen . view . ViewAnalyzer ; import com . asakusafw . modelgen . view . ViewDefinition ; import com . asakusafw . modelgen . view . ViewParser ; import com . asakusafw . modelgen . view . model . CreateView ; public class DatabaseSource implements Closeable { @ SuppressWarnings ( "" ) private static final String STR_IS_PK = "" ; private static final String STR_NOT_NULL = "" ; static final Logger LOG = LoggerFactory . getLogger ( DatabaseSource . class ) ; private Connection conn ; private String databaseName ; public DatabaseSource ( String jdbcDriver , String jdbcUrl , String user , String password , String databaseName ) throws IOException , SQLException { if ( jdbcDriver == null ) { throw new IllegalArgumentException ( "" ) ; } if ( jdbcUrl == null ) { throw new IllegalArgumentException ( "" ) ; } if ( user == null ) { throw new IllegalArgumentException ( "" ) ; } if ( password == null ) { throw new IllegalArgumentException ( "" ) ; } if ( databaseName == null ) { throw new IllegalArgumentException ( "" ) ; } this . databaseName = databaseName ; try { Class . forName ( jdbcDriver ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( "" , e ) ; } conn = DriverManager . getConnection ( jdbcUrl , user , password ) ; } public List < ModelDescription > collectTables ( ModelMatcher filter ) throws IOException , SQLException { String sql = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; List < ModelDescription > results = new ArrayList < ModelDescription > ( ) ; PreparedStatement ps = null ; ResultSet rs = null ; try { ps = conn . prepareStatement ( sql ) ; ps . setString ( , databaseName ) ; rs = ps . executeQuery ( ) ; String prevTableName = null ; TableModelBuilder builder = null ; while ( rs . next ( ) ) { String tableName = rs . getString ( ) ; String columnName = rs . getString ( ) ; String columnComment = rs . getString ( ) ; String dataType = rs . getString ( ) ; long characterMaximumLength = rs . getLong ( ) ; int numericPrecision = rs . getInt ( ) ; int numericScale = rs . getInt ( ) ; String isNullable = rs . getString ( ) ; String columnKey = rs . getString ( ) ; if ( filter . acceptModel ( tableName ) == false ) { if ( tableName . equals ( prevTableName ) == false ) { LOG . info ( "" , tableName ) ; prevTableName = tableName ; } continue ; } if ( builder == null || prevTableName == null || prevTableName . equals ( tableName ) == false ) { if ( builder != null ) { results . add ( builder . toDescription ( ) ) ; } builder = new TableModelBuilder ( tableName ) ; builder . namespace ( Constants . SOURCE_TABLE ) ; prevTableName = tableName ; } PropertyTypeKind propertyType = MySqlDataType . getPropertyTypeByString ( dataType ) ; if ( propertyType == null ) { LOG . error ( "" , new Object [ ] { dataType , tableName , columnName , } ) ; continue ; } ArrayList < Attribute > attributeList = new ArrayList < Attribute > ( ) ; if ( isNullable != null && isNullable . equals ( STR_NOT_NULL ) ) { attributeList . add ( Attribute . NOT_NULL ) ; } if ( columnKey != null && columnKey . equals ( MySQLConstants . STR_IS_PK ) ) { attributeList . add ( Attribute . PRIMARY_KEY ) ; } Attribute [ ] attributes = attributeList . toArray ( new Attribute [ attributeList . size ( ) ] ) ; switch ( propertyType ) { case BIG_DECIMAL : DecimalType decimalType = new DecimalType ( numericPrecision , numericScale ) ; builder . add ( columnComment , columnName , decimalType , attributes ) ; break ; case STRING : StringType stringType = new StringType ( ( int ) characterMaximumLength ) ; builder . add ( columnComment , columnName , stringType , attributes ) ; break ; default : builder . add ( columnComment , columnName , propertyType , attributes ) ; break ; } } if ( builder != null ) { results . add ( builder . toDescription ( ) ) ; } } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } if ( ps != null ) { try { ps . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } } return results ; } public List < ModelDescription > collectViews ( ModelRepository repository , ModelMatcher filter ) throws IOException , SQLException { List < ViewDefinition > definitions = collectViewDefinitions ( filter ) ; LOG . info ( "" , definitions . size ( ) ) ; ViewAnalyzer analyzer = new ViewAnalyzer ( ) ; for ( ViewDefinition definition : definitions ) { LOG . info ( "" , definition . name ) ; CreateView tree = ViewParser . parse ( definition ) ; analyzer . add ( Collections . singletonList ( Constants . SOURCE_VIEW ) , tree ) ; } List < ModelDescription > results = analyzer . analyze ( repository ) ; return results ; } private List < ViewDefinition > collectViewDefinitions ( ModelMatcher filter ) throws IOException , SQLException { String sql = "" + "" + "" ; PreparedStatement ps = null ; ResultSet rs = null ; List < ViewDefinition > results = new ArrayList < ViewDefinition > ( ) ; try { ps = conn . prepareStatement ( sql ) ; ps . setString ( , databaseName ) ; rs = ps . executeQuery ( ) ; while ( rs . next ( ) ) { String viewName = rs . getString ( ) ; if ( filter . acceptModel ( viewName ) == false ) { LOG . info ( "" , viewName ) ; continue ; } String statement = rs . getString ( ) ; results . add ( new ViewDefinition ( viewName , statement ) ) ; } } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } if ( ps != null ) { try { ps . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } } return results ; } @ Override public void close ( ) throws IOException { if ( conn != null ) { try { conn . close ( ) ; } catch ( Exception e ) { LOG . debug ( "" , e ) ; } } } } @ java . lang . Deprecated package com . asakusafw . modelgen . source ; package com . asakusafw . modelgen . source ; public final class MySQLConstants { public static final String STR_IS_PK = "" ; public static final String STR_NOT_NULL = "" ; private MySQLConstants ( ) { return ; } } package com . asakusafw . modelgen . source ; import java . util . HashMap ; import java . util . Map ; import com . asakusafw . modelgen . model . PropertyTypeKind ; public enum MySqlDataType { TINY_INT ( "" , PropertyTypeKind . BYTE ) , SMALL_INT ( "" , PropertyTypeKind . SHORT ) , INT ( "" , PropertyTypeKind . INT ) , LONG ( "" , PropertyTypeKind . LONG ) , DECIMAL ( "" , PropertyTypeKind . BIG_DECIMAL ) , DATE ( "" , PropertyTypeKind . DATE ) , DATETIME ( "" , PropertyTypeKind . DATETIME ) , TIMESTAMP ( "" , PropertyTypeKind . DATETIME ) , CHAR ( "" , PropertyTypeKind . STRING ) , VARCHAR ( "" , PropertyTypeKind . STRING ) ; private String dataTypeString ; private PropertyTypeKind propertyTypeKind ; private MySqlDataType ( String str , PropertyTypeKind type ) { assert str != null ; assert type != null ; this . dataTypeString = str ; this . propertyTypeKind = type ; } private static Map < String , MySqlDataType > dataTypeMap = new HashMap < String , MySqlDataType > ( ) ; static { for ( MySqlDataType type : MySqlDataType . values ( ) ) { String mySqlStr = type . getDataTypeString ( ) ; if ( dataTypeMap . containsKey ( mySqlStr ) ) { throw new RuntimeException ( "" ) ; } dataTypeMap . put ( mySqlStr , type ) ; } } private static Map < String , PropertyTypeKind > propertyMap = new HashMap < String , PropertyTypeKind > ( ) ; static { for ( MySqlDataType type : MySqlDataType . values ( ) ) { String mySqlStr = type . getDataTypeString ( ) ; if ( propertyMap . containsKey ( mySqlStr ) ) { throw new RuntimeException ( "" ) ; } propertyMap . put ( mySqlStr , type . getPropertyType ( ) ) ; } } public static MySqlDataType getDataTypeByString ( String str ) { return dataTypeMap . get ( str ) ; } public static PropertyTypeKind getPropertyTypeByString ( String str ) { return propertyMap . get ( str ) ; } public String getDataTypeString ( ) { return dataTypeString ; } public PropertyTypeKind getPropertyType ( ) { return propertyTypeKind ; } } package com . asakusafw . modelgen . emitter ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; public class AnyModelEntityEmitter { private Map < Class < ? extends ModelDescription > , ModelEntityEmitter < ? > > emitters = new HashMap < Class < ? extends ModelDescription > , ModelEntityEmitter < ? > > ( ) ; public AnyModelEntityEmitter ( ModelFactory factory , File output , String packageName , List < String > headerComment ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } if ( packageName == null ) { throw new IllegalArgumentException ( "" ) ; } add ( new TableModelEntityEmitter ( factory , output , packageName , headerComment ) ) ; add ( new JoinedModelEntityEmitter ( factory , output , packageName , headerComment ) ) ; add ( new SummarizedModelEntityEmitter ( factory , output , packageName , headerComment ) ) ; } private void add ( ModelEntityEmitter < ? > emitter ) { assert emitter != null ; assert emitters . containsKey ( emitter . getEmitTargetType ( ) ) == false ; emitters . put ( emitter . getEmitTargetType ( ) , emitter ) ; } public void emit ( ModelDescription target ) throws IOException { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } ModelEntityEmitter < ? > emitter = emitters . get ( target . getClass ( ) ) ; if ( emitter == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , target . getReference ( ) , target . getClass ( ) ) ) ; } emit ( target , emitter ) ; } private < T extends ModelDescription > void emit ( ModelDescription target , ModelEntityEmitter < T > emitter ) throws IOException { assert target != null ; assert emitter != null ; Class < T > type = emitter . getEmitTargetType ( ) ; assert type . isInstance ( target ) ; T model = type . cast ( target ) ; emitter . emit ( model ) ; } } package com . asakusafw . modelgen . emitter ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . modelgen . Constants ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ModelOutputEmitter extends BaseEmitter < ModelDescription > { public ModelOutputEmitter ( ModelFactory factory , File output , String packageName , List < String > headerComment ) { super ( factory , output , packageName , headerComment ) ; } @ Override protected PackageDeclaration createPackageDeclaration ( ModelDescription model ) { return f . newPackageDeclaration ( common . getPackageNameOf ( model . getReference ( ) , Constants . CATEGORY_IO ) ) ; } @ Override protected TypeDeclaration createTypeDeclaration ( ModelDescription model ) { SimpleName name = createTypeName ( model ) ; return f . newClassDeclaration ( new JavadocBuilder ( f ) . linkType ( createModelType ( model ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . annotation ( bless ( Generated . class ) , Models . toLiteral ( f , MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , Constants . VERSION ) ) ) . annotation ( bless ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( f . newParameterizedType ( bless ( ModelOutput . class ) , createModelType ( model ) ) ) , createBodyDeclarations ( model ) ) ; } private List < TypeBodyDeclaration > createBodyDeclarations ( ModelDescription model ) { List < TypeBodyDeclaration > results = new ArrayList < TypeBodyDeclaration > ( ) ; results . add ( createEmitterField ( model ) ) ; results . add ( createConstructor ( model ) ) ; results . add ( createWriter ( model ) ) ; results . add ( createCloser ( model ) ) ; return results ; } private TypeBodyDeclaration createEmitterField ( ModelDescription model ) { return f . newFieldDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , createEmitterType ( ) , createEmitterFieldName ( ) , null ) ; } private TypeBodyDeclaration createConstructor ( ModelDescription model ) { return f . newConstructorDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( createEmitterFieldName ( ) ) . text ( "" ) . exception ( createInvalidArgumentExceptionType ( ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , createTypeName ( model ) , Collections . singletonList ( f . newFormalParameterDeclaration ( createEmitterType ( ) , createEmitterFieldName ( ) ) ) , createConstructorBody ( model ) ) ; } private List < Statement > createConstructorBody ( ModelDescription model ) { List < Statement > results = new ArrayList < Statement > ( ) ; results . add ( f . newIfStatement ( new ExpressionBuilder ( f , createEmitterFieldName ( ) ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new TypeBuilder ( f , createInvalidArgumentExceptionType ( ) ) . newObject ( ) . toThrowStatement ( ) ) ) ) ; results . add ( new ExpressionBuilder ( f , f . newThis ( null ) ) . field ( createEmitterFieldName ( ) ) . assignFrom ( createEmitterFieldName ( ) ) . toStatement ( ) ) ; return results ; } private TypeBodyDeclaration createWriter ( ModelDescription model ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , bless ( void . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( createModelType ( model ) , createModelParameterName ( ) ) ) , , Collections . singletonList ( bless ( IOException . class ) ) , f . newBlock ( createWriterBody ( model ) ) ) ; } private List < Statement > createWriterBody ( ModelDescription model ) { List < Statement > results = new ArrayList < Statement > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { results . add ( createWriterStatement ( property ) ) ; } results . add ( new ExpressionBuilder ( f , createEmitterFieldName ( ) ) . method ( "" ) . toStatement ( ) ) ; return results ; } private Statement createWriterStatement ( ModelProperty property ) { SimpleName optionGetterName = common . getOptionGetterNameOf ( property . getName ( ) , property . getType ( ) ) ; Expression option = new ExpressionBuilder ( f , createModelParameterName ( ) ) . method ( optionGetterName ) . toExpression ( ) ; Statement fill = new ExpressionBuilder ( f , createEmitterFieldName ( ) ) . method ( "" , option ) . toStatement ( ) ; return fill ; } private TypeBodyDeclaration createCloser ( ModelDescription model ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , bless ( void . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . singletonList ( bless ( IOException . class ) ) , f . newBlock ( createCloserBody ( ) ) ) ; } private List < Statement > createCloserBody ( ) { List < Statement > results = new ArrayList < Statement > ( ) ; results . add ( new ExpressionBuilder ( f , createEmitterFieldName ( ) ) . method ( "" ) . toStatement ( ) ) ; return results ; } private SimpleName createTypeName ( ModelDescription model ) { SimpleName original = common . getTypeNameOf ( model . getReference ( ) ) ; SimpleName name = f . newSimpleName ( MessageFormat . format ( Constants . FORMAT_NAME_MODEL_OUTPUT , original . getToken ( ) ) ) ; return name ; } private Type createModelType ( ModelDescription model ) { return bless ( common . getModelType ( model . getReference ( ) ) ) ; } private Type createEmitterType ( ) { return bless ( RecordEmitter . class ) ; } private SimpleName createEmitterFieldName ( ) { return f . newSimpleName ( "" ) ; } private SimpleName createModelParameterName ( ) { return f . newSimpleName ( "" ) ; } private Type createInvalidArgumentExceptionType ( ) { return bless ( IllegalArgumentException . class ) ; } } package com . asakusafw . modelgen . emitter ; import java . math . BigDecimal ; import java . text . MessageFormat ; import java . util . HashSet ; import java . util . Set ; import org . apache . hadoop . io . Text ; import com . asakusafw . modelgen . Constants ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . ModelReference ; import com . asakusafw . modelgen . model . PropertyType ; import com . asakusafw . runtime . value . BooleanOption ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . JoinedModel ; import com . asakusafw . vocabulary . model . SummarizedModel ; public class CommonEmitter { private final ModelFactory f ; private final Name baseNamespace ; public CommonEmitter ( ModelFactory factory , String baseNamespace ) { this . f = factory ; this . baseNamespace = Models . toName ( f , baseNamespace ) ; } public Type getModelType ( ModelReference reference ) { Name pkg = getPackageNameOf ( reference , Constants . CATEGORY_MODEL ) ; if ( pkg == null ) { return f . newNamedType ( getTypeNameOf ( reference ) ) ; } else { return f . newNamedType ( f . newQualifiedName ( pkg , getTypeNameOf ( reference ) ) ) ; } } public Expression getInitialValue ( PropertyType type , ImportBuilder importer ) { switch ( type . getKind ( ) ) { case BOOLEAN : return newInstance ( importer , BooleanOption . class ) ; case BYTE : return newInstance ( importer , ByteOption . class ) ; case SHORT : return newInstance ( importer , ShortOption . class ) ; case INT : return newInstance ( importer , IntOption . class ) ; case LONG : return newInstance ( importer , LongOption . class ) ; case BIG_DECIMAL : return newInstance ( importer , DecimalOption . class ) ; case STRING : return newInstance ( importer , StringOption . class ) ; case DATE : return newInstance ( importer , DateOption . class ) ; case DATETIME : return newInstance ( importer , DateTimeOption . class ) ; default : throw new IllegalStateException ( MessageFormat . format ( "" , type ) ) ; } } private Expression newInstance ( ImportBuilder importer , Class < ? > klass , Expression ... arguments ) { Type type = Models . toType ( f , klass ) ; if ( importer != null ) { type = importer . resolve ( type ) ; } return types ( type ) . newObject ( arguments ) . toExpression ( ) ; } private TypeBuilder types ( Type type ) { assert type != null ; return new TypeBuilder ( f , type ) ; } public Type getOptionType ( PropertyType type ) { switch ( type . getKind ( ) ) { case BOOLEAN : return Models . toType ( f , BooleanOption . class ) ; case BYTE : return Models . toType ( f , ByteOption . class ) ; case SHORT : return Models . toType ( f , ShortOption . class ) ; case INT : return Models . toType ( f , IntOption . class ) ; case LONG : return Models . toType ( f , LongOption . class ) ; case BIG_DECIMAL : return Models . toType ( f , DecimalOption . class ) ; case STRING : return Models . toType ( f , StringOption . class ) ; case DATE : return Models . toType ( f , DateOption . class ) ; case DATETIME : return Models . toType ( f , DateTimeOption . class ) ; default : throw new IllegalStateException ( MessageFormat . format ( "" , type ) ) ; } } public Type getRawType ( PropertyType type ) { switch ( type . getKind ( ) ) { case BOOLEAN : return Models . toType ( f , boolean . class ) ; case BYTE : return Models . toType ( f , byte . class ) ; case SHORT : return Models . toType ( f , short . class ) ; case INT : return Models . toType ( f , int . class ) ; case LONG : return Models . toType ( f , long . class ) ; case BIG_DECIMAL : return Models . toType ( f , BigDecimal . class ) ; case STRING : return Models . toType ( f , Text . class ) ; case DATE : return Models . toType ( f , Date . class ) ; case DATETIME : return Models . toType ( f , DateTime . class ) ; default : throw new IllegalStateException ( MessageFormat . format ( "" , type ) ) ; } } public Type getAltType ( PropertyType type ) { switch ( type . getKind ( ) ) { case STRING : return Models . toType ( f , String . class ) ; case BOOLEAN : case BYTE : case SHORT : case INT : case LONG : case BIG_DECIMAL : case DATE : case DATETIME : return null ; default : throw new IllegalStateException ( MessageFormat . format ( "" , type ) ) ; } } public Name getPackageNameOf ( ModelReference reference , String categoryName ) { if ( reference . isDefaultNameSpace ( ) ) { return Models . append ( f , baseNamespace , categoryName ) ; } return Models . append ( f , baseNamespace , Models . toName ( f , reference . getNamespace ( ) ) , Models . toName ( f , categoryName ) ) ; } public SimpleName getTypeNameOf ( ModelReference reference ) { JavaName name = JavaName . of ( reference . getSimpleName ( ) ) ; return f . newSimpleName ( name . toTypeName ( ) ) ; } public SimpleName getFieldNameOf ( String propertyName , PropertyType type ) { JavaName name = JavaName . of ( propertyName ) ; return f . newSimpleName ( name . toMemberName ( ) ) ; } public SimpleName getGetterNameOf ( String propertyName , PropertyType type ) { JavaName name = JavaName . of ( propertyName ) ; switch ( type . getKind ( ) ) { case BOOLEAN : name . addFirst ( "" ) ; return f . newSimpleName ( name . toMemberName ( ) ) ; default : name . addFirst ( "" ) ; return f . newSimpleName ( name . toMemberName ( ) ) ; } } public SimpleName getSetterNameOf ( String propertyName , PropertyType type ) { JavaName name = JavaName . of ( propertyName ) ; switch ( type . getKind ( ) ) { default : name . addFirst ( "" ) ; return f . newSimpleName ( name . toMemberName ( ) ) ; } } public SimpleName getAltGetterNameOf ( String propertyName , PropertyType type ) { String original = getGetterNameOf ( propertyName , type ) . getToken ( ) ; return toAltMemberName ( original , type ) ; } public SimpleName getAltSetterNameOf ( String propertyName , PropertyType type ) { String original = getSetterNameOf ( propertyName , type ) . getToken ( ) ; return toAltMemberName ( original , type ) ; } public SimpleName toAltMemberName ( String original , PropertyType type ) { JavaName name = JavaName . of ( original ) ; switch ( type . getKind ( ) ) { case STRING : name . addLast ( "" ) ; name . addLast ( "" ) ; return f . newSimpleName ( name . toMemberName ( ) ) ; case BOOLEAN : case BYTE : case SHORT : case INT : case LONG : case BIG_DECIMAL : case DATE : case DATETIME : return null ; default : throw new IllegalStateException ( MessageFormat . format ( "" , type ) ) ; } } public SimpleName getOptionGetterNameOf ( String propertyName , PropertyType type ) { JavaName name = JavaName . of ( propertyName ) ; name . addFirst ( "" ) ; name . addLast ( "" ) ; return f . newSimpleName ( name . toMemberName ( ) ) ; } public SimpleName getOptionSetterNameOf ( String propertyName , PropertyType type ) { JavaName name = JavaName . of ( propertyName ) ; name . addFirst ( "" ) ; name . addLast ( "" ) ; return f . newSimpleName ( name . toMemberName ( ) ) ; } public SimpleName getCopierName ( ) { return f . newSimpleName ( DataModel . Interface . METHOD_NAME_COPY_FROM ) ; } public SimpleName getJoinerName ( ) { return f . newSimpleName ( JoinedModel . Interface . METHOD_NAME_JOIN_FROM ) ; } public SimpleName getSplitterName ( ) { return f . newSimpleName ( JoinedModel . Interface . METHOD_NAME_SPLIT_INTO ) ; } public SimpleName getStartSummarizerName ( ) { return f . newSimpleName ( SummarizedModel . Interface . METHOD_NAME_START_SUMMARIZATION ) ; } public SimpleName getCombineSummarizerName ( ) { return f . newSimpleName ( SummarizedModel . Interface . METHOD_NAME_COMBINE_SUMMARIZATION ) ; } public SimpleName getVariableNameOf ( ModelDescription model , String hint ) { Set < String > used = new HashSet < String > ( ) ; for ( ModelProperty p : model . getProperties ( ) ) { used . add ( getFieldNameOf ( p . getName ( ) , p . getType ( ) ) . getToken ( ) ) ; } StringBuilder name = new StringBuilder ( hint ) ; while ( used . contains ( name . toString ( ) ) ) { name . append ( '' ) ; } return f . newSimpleName ( name . toString ( ) ) ; } } package com . asakusafw . modelgen . emitter ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; public class JavaName { private final List < String > words ; JavaName ( List < ? extends String > words ) { if ( words == null ) { throw new NullPointerException ( "" ) ; } if ( words . isEmpty ( ) ) { throw new IllegalArgumentException ( "" ) ; } this . words = new ArrayList < String > ( ) ; for ( String word : words ) { this . words . add ( normalize ( word ) ) ; } } public static JavaName of ( String nameString ) { if ( nameString . indexOf ( '' ) >= || nameString . toUpperCase ( ) . equals ( nameString ) ) { String [ ] segments = nameString . split ( "" ) ; return new JavaName ( normalize ( Arrays . asList ( segments ) ) ) ; } else { List < String > segments = new ArrayList < String > ( ) ; int start = ; for ( int i = , n = nameString . length ( ) ; i < n ; i ++ ) { if ( Character . isUpperCase ( nameString . charAt ( i ) ) ) { segments . add ( nameString . substring ( start , i ) ) ; start = i ; } } segments . add ( nameString . substring ( start ) ) ; return new JavaName ( normalize ( segments ) ) ; } } public List < String > getSegments ( ) { return new ArrayList < String > ( words ) ; } public String toTypeName ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( capitalize ( words . get ( i ) ) ) ; } return buf . toString ( ) ; } public String toMemberName ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( words . get ( ) . toLowerCase ( ) ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( capitalize ( words . get ( i ) ) ) ; } return buf . toString ( ) ; } public String toConstantName ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( words . get ( ) . toUpperCase ( ) ) ; for ( int i = , n = words . size ( ) ; i < n ; i ++ ) { buf . append ( '' ) ; buf . append ( words . get ( i ) . toUpperCase ( ) ) ; } return buf . toString ( ) ; } public void addFirst ( String segment ) { words . add ( , normalize ( segment ) ) ; } public void addLast ( String segment ) { words . add ( normalize ( segment ) ) ; } private String capitalize ( String segment ) { assert segment != null ; StringBuilder buf = new StringBuilder ( segment . toLowerCase ( ) ) ; buf . setCharAt ( , Character . toUpperCase ( buf . charAt ( ) ) ) ; return buf . toString ( ) ; } private static String normalize ( String segment ) { if ( segment == null ) { throw new IllegalArgumentException ( "" ) ; } if ( segment . isEmpty ( ) ) { throw new IllegalArgumentException ( ) ; } return segment . toLowerCase ( ) ; } private static List < String > normalize ( List < String > segments ) { List < String > results = new ArrayList < String > ( ) ; for ( String segment : segments ) { if ( segment . isEmpty ( ) == false ) { results . add ( segment ) ; } } return results ; } } package com . asakusafw . modelgen . emitter ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . modelgen . Constants ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public class ModelInputEmitter extends BaseEmitter < ModelDescription > { public ModelInputEmitter ( ModelFactory factory , File output , String packageName , List < String > headerComment ) { super ( factory , output , packageName , headerComment ) ; } @ Override protected PackageDeclaration createPackageDeclaration ( ModelDescription model ) { return f . newPackageDeclaration ( common . getPackageNameOf ( model . getReference ( ) , Constants . CATEGORY_IO ) ) ; } @ Override protected TypeDeclaration createTypeDeclaration ( ModelDescription model ) { SimpleName name = createTypeName ( model ) ; return f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . linkType ( createModelType ( model ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . annotation ( bless ( Generated . class ) , Models . toLiteral ( f , MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , Constants . VERSION ) ) ) . annotation ( bless ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . Public ( ) . Final ( ) . toAttributes ( ) , name , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( f . newParameterizedType ( bless ( ModelInput . class ) , createModelType ( model ) ) ) , createBodyDeclarations ( model ) ) ; } private List < TypeBodyDeclaration > createBodyDeclarations ( ModelDescription model ) { List < TypeBodyDeclaration > results = new ArrayList < TypeBodyDeclaration > ( ) ; results . add ( createParserField ( model ) ) ; results . add ( createConstructor ( model ) ) ; results . add ( createReader ( model ) ) ; results . add ( createCloser ( model ) ) ; return results ; } private TypeBodyDeclaration createParserField ( ModelDescription model ) { return f . newFieldDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , createParserType ( ) , createParserFieldName ( ) , null ) ; } private TypeBodyDeclaration createConstructor ( ModelDescription model ) { return f . newConstructorDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( createParserFieldName ( ) ) . text ( "" ) . exception ( createInvalidArgumentExceptionType ( ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , createTypeName ( model ) , Collections . singletonList ( f . newFormalParameterDeclaration ( createParserType ( ) , createParserFieldName ( ) ) ) , createConstructorBody ( model ) ) ; } private List < Statement > createConstructorBody ( ModelDescription model ) { List < Statement > results = new ArrayList < Statement > ( ) ; results . add ( f . newIfStatement ( new ExpressionBuilder ( f , createParserFieldName ( ) ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new TypeBuilder ( f , createInvalidArgumentExceptionType ( ) ) . newObject ( ) . toThrowStatement ( ) ) ) ) ; results . add ( new ExpressionBuilder ( f , f . newThis ( null ) ) . field ( createParserFieldName ( ) ) . assignFrom ( createParserFieldName ( ) ) . toStatement ( ) ) ; return results ; } private TypeBodyDeclaration createReader ( ModelDescription model ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , bless ( boolean . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( createModelType ( model ) , createModelParameterName ( ) ) ) , , Collections . singletonList ( bless ( IOException . class ) ) , f . newBlock ( createReaderBody ( model ) ) ) ; } private List < Statement > createReaderBody ( ModelDescription model ) { List < Statement > results = new ArrayList < Statement > ( ) ; results . add ( f . newIfStatement ( new ExpressionBuilder ( f , createParserFieldName ( ) ) . method ( "" ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , Models . toLiteral ( f , false ) ) . toReturnStatement ( ) ) ) ) ; for ( ModelProperty property : model . getProperties ( ) ) { results . add ( createReaderStatement ( property ) ) ; } results . add ( f . newReturnStatement ( Models . toLiteral ( f , true ) ) ) ; return results ; } private Statement createReaderStatement ( ModelProperty property ) { SimpleName optionGetterName = common . getOptionGetterNameOf ( property . getName ( ) , property . getType ( ) ) ; Expression option = new ExpressionBuilder ( f , createModelParameterName ( ) ) . method ( optionGetterName ) . toExpression ( ) ; Statement fill = new ExpressionBuilder ( f , createParserFieldName ( ) ) . method ( "" , option ) . toStatement ( ) ; return fill ; } private TypeBodyDeclaration createCloser ( ModelDescription model ) { return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , bless ( void . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . singletonList ( bless ( IOException . class ) ) , f . newBlock ( createCloserBody ( ) ) ) ; } private List < Statement > createCloserBody ( ) { List < Statement > results = new ArrayList < Statement > ( ) ; results . add ( new ExpressionBuilder ( f , createParserFieldName ( ) ) . method ( "" ) . toStatement ( ) ) ; return results ; } private SimpleName createTypeName ( ModelDescription model ) { SimpleName original = common . getTypeNameOf ( model . getReference ( ) ) ; SimpleName name = f . newSimpleName ( MessageFormat . format ( Constants . FORMAT_NAME_MODEL_INPUT , original . getToken ( ) ) ) ; return name ; } private Type createModelType ( ModelDescription model ) { return bless ( common . getModelType ( model . getReference ( ) ) ) ; } private Type createParserType ( ) { return bless ( RecordParser . class ) ; } private SimpleName createParserFieldName ( ) { return f . newSimpleName ( "" ) ; } private SimpleName createModelParameterName ( ) { return f . newSimpleName ( "" ) ; } private Type createInvalidArgumentExceptionType ( ) { return bless ( IllegalArgumentException . class ) ; } } package com . asakusafw . modelgen . emitter ; import java . io . File ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . modelgen . model . JoinedModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . ModelReference ; import com . asakusafw . modelgen . model . Source ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . AnnotationElement ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . JoinedModel ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . ModelRef ; import com . asakusafw . vocabulary . model . Property ; public class JoinedModelEntityEmitter extends ModelEntityEmitter < JoinedModelDescription > { public JoinedModelEntityEmitter ( ModelFactory factory , File output , String packageName , List < String > headerComment ) { super ( factory , output , packageName , headerComment ) ; } @ Override public Class < JoinedModelDescription > getEmitTargetType ( ) { return JoinedModelDescription . class ; } @ Override protected List < Annotation > createAnnotationsForModel ( JoinedModelDescription model ) { return new AttributeBuilder ( f ) . annotation ( bless ( DataModel . class ) ) . annotation ( bless ( JoinedModel . class ) , "" , createModelRefAnnotation ( model . getFromModel ( ) , model . getFromCondition ( ) ) , "" , createModelRefAnnotation ( model . getJoinModel ( ) , model . getJoinCondition ( ) ) ) . annotation ( bless ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . toAnnotations ( ) ; } @ Override protected List < Annotation > createAnnotationsForField ( ModelProperty property ) { List < AnnotationElement > elements = new ArrayList < AnnotationElement > ( ) ; if ( property . getFrom ( ) != null ) { elements . add ( f . newAnnotationElement ( f . newSimpleName ( "" ) , createSourceAnnotation ( property . getFrom ( ) ) ) ) ; } if ( property . getJoined ( ) != null ) { elements . add ( f . newAnnotationElement ( f . newSimpleName ( "" ) , createSourceAnnotation ( property . getJoined ( ) ) ) ) ; } Annotation prop = f . newNormalAnnotation ( ( NamedType ) bless ( Property . class ) , elements ) ; return Collections . singletonList ( prop ) ; } private Annotation createModelRefAnnotation ( ModelReference reference , List < Source > joinCondition ) { List < String > groupKeys = new ArrayList < String > ( ) ; for ( Source s : joinCondition ) { groupKeys . add ( common . getFieldNameOf ( s . getName ( ) , s . getType ( ) ) . getToken ( ) ) ; } String [ ] group = groupKeys . toArray ( new String [ groupKeys . size ( ) ] ) ; Annotation key = f . newNormalAnnotation ( ( NamedType ) bless ( Key . class ) , Collections . singletonList ( f . newAnnotationElement ( f . newSimpleName ( "" ) , Models . toArrayInitializer ( f , group ) ) ) ) ; return f . newNormalAnnotation ( ( NamedType ) bless ( ModelRef . class ) , Arrays . asList ( new AnnotationElement [ ] { f . newAnnotationElement ( f . newSimpleName ( "" ) , f . newClassLiteral ( bless ( common . getModelType ( reference ) ) ) ) , f . newAnnotationElement ( f . newSimpleName ( "" ) , key ) , } ) ) ; } private Annotation createSourceAnnotation ( Source source ) { AnnotationElement declaring = f . newAnnotationElement ( f . newSimpleName ( "" ) , f . newClassLiteral ( bless ( common . getModelType ( source . getDeclaring ( ) ) ) ) ) ; AnnotationElement name = f . newAnnotationElement ( f . newSimpleName ( "" ) , Models . toLiteral ( f , common . getFieldNameOf ( source . getName ( ) , source . getType ( ) ) . getToken ( ) ) ) ; return f . newNormalAnnotation ( ( NamedType ) bless ( Property . Source . class ) , Arrays . asList ( declaring , name ) ) ; } @ Override protected List < TypeBodyDeclaration > createMembers ( JoinedModelDescription model ) { List < TypeBodyDeclaration > members = super . createMembers ( model ) ; members . add ( createJoiner ( model ) ) ; members . add ( createSplitter ( model ) ) ; return members ; } private TypeBodyDeclaration createJoiner ( JoinedModelDescription model ) { SimpleName left = common . getVariableNameOf ( model , "" ) ; SimpleName right = common . getVariableNameOf ( model , "" ) ; List < Statement > statements = new ArrayList < Statement > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { statements . add ( createJoinerFor ( model , property , left , right ) ) ; } return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( left ) . text ( "" ) . param ( right ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , Models . toType ( f , void . class ) , common . getJoinerName ( ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( bless ( common . getModelType ( model . getFromModel ( ) ) ) , left ) , f . newFormalParameterDeclaration ( bless ( common . getModelType ( model . getJoinModel ( ) ) ) , right ) , } ) , statements ) ; } private Statement createJoinerFor ( JoinedModelDescription model , ModelProperty property , SimpleName left , SimpleName right ) { if ( property . getFrom ( ) != null ) { return createImporterFor ( left , property . getFrom ( ) . getName ( ) , property . getName ( ) , property . getType ( ) ) ; } else { return createImporterFor ( right , property . getJoined ( ) . getName ( ) , property . getName ( ) , property . getType ( ) ) ; } } private TypeBodyDeclaration createSplitter ( JoinedModelDescription model ) { SimpleName left = common . getVariableNameOf ( model , "" ) ; SimpleName right = common . getVariableNameOf ( model , "" ) ; List < Statement > statements = new ArrayList < Statement > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { if ( property . getFrom ( ) != null ) { statements . add ( createSplitterFor ( model , property , property . getFrom ( ) , left ) ) ; } if ( property . getJoined ( ) != null ) { statements . add ( createSplitterFor ( model , property , property . getJoined ( ) , right ) ) ; } } return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( left ) . text ( "" ) . param ( right ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , Models . toType ( f , void . class ) , common . getSplitterName ( ) , Arrays . asList ( new FormalParameterDeclaration [ ] { f . newFormalParameterDeclaration ( bless ( common . getModelType ( model . getFromModel ( ) ) ) , left ) , f . newFormalParameterDeclaration ( bless ( common . getModelType ( model . getJoinModel ( ) ) ) , right ) , } ) , statements ) ; } private Statement createSplitterFor ( JoinedModelDescription model , ModelProperty property , Source original , SimpleName param ) { return createExporterFor ( property . getName ( ) , param , original . getName ( ) , property . getType ( ) ) ; } @ Override protected Javadoc createJavadocForModel ( JoinedModelDescription model ) { List < Source > left = model . getFromCondition ( ) ; List < Source > right = model . getJoinCondition ( ) ; assert left . size ( ) == right . size ( ) ; StringBuilder joinCond = new StringBuilder ( ) ; joinCond . append ( "" ) ; for ( int i = , n = left . size ( ) ; i < n ; i ++ ) { Source a = left . get ( i ) ; Source b = right . get ( i ) ; joinCond . append ( MessageFormat . format ( "" , a . getDeclaring ( ) . getSimpleName ( ) , a . getName ( ) , b . getDeclaring ( ) . getSimpleName ( ) , b . getName ( ) ) ) ; } joinCond . append ( "" ) ; return new JavadocBuilder ( f ) . text ( "" , model . getFromModel ( ) . getSimpleName ( ) , model . getJoinModel ( ) . getSimpleName ( ) ) . text ( "" ) . text ( joinCond . toString ( ) ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForField ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , getColumnDescription ( property ) ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForGetter ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , getColumnDescription ( property ) ) . returns ( ) . text ( getColumnDescription ( property ) ) . exception ( bless ( NullPointerException . class ) ) . text ( "" ) . code ( "" ) . text ( "" ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForSetter ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , getColumnDescription ( property ) ) . param ( createNameForParameter ( property ) ) . text ( "" ) . toJavadoc ( ) ; } private String getColumnDescription ( ModelProperty property ) { if ( property . getFrom ( ) == null || property . getJoined ( ) == null ) { Source first = property . getSource ( ) ; return MessageFormat . format ( "" , first . getDeclaring ( ) . getSimpleName ( ) , first . getName ( ) ) ; } else { Source first = property . getFrom ( ) ; Source second = property . getJoined ( ) ; return MessageFormat . format ( "" , first . getDeclaring ( ) . getSimpleName ( ) , first . getName ( ) , second . getDeclaring ( ) . getSimpleName ( ) , second . getName ( ) ) ; } } } package com . asakusafw . modelgen . emitter ; import java . io . File ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import com . asakusafw . modelgen . Constants ; import com . asakusafw . modelgen . model . Aggregator ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . ModelReference ; import com . asakusafw . modelgen . model . Source ; import com . asakusafw . modelgen . model . SummarizedModelDescription ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . AnnotationElement ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . NamedType ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . ModelRef ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . SummarizedModel ; public class SummarizedModelEntityEmitter extends ModelEntityEmitter < SummarizedModelDescription > { public SummarizedModelEntityEmitter ( ModelFactory factory , File output , String packageName , List < String > headerComment ) { super ( factory , output , packageName , headerComment ) ; } @ Override public Class < SummarizedModelDescription > getEmitTargetType ( ) { return SummarizedModelDescription . class ; } @ Override protected List < TypeBodyDeclaration > createMembers ( SummarizedModelDescription model ) { List < TypeBodyDeclaration > members = super . createMembers ( model ) ; members . add ( createStartSummarize ( model ) ) ; members . add ( createProcessSummarize ( model ) ) ; return members ; } private TypeBodyDeclaration createStartSummarize ( SummarizedModelDescription model ) { SimpleName param = common . getVariableNameOf ( model , "" ) ; List < Statement > statements = new ArrayList < Statement > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { statements . add ( createStartSummarizeFor ( param , property ) ) ; } return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( param ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , Models . toType ( f , void . class ) , common . getStartSummarizerName ( ) , Collections . singletonList ( f . newFormalParameterDeclaration ( bless ( common . getModelType ( model . getOriginalModel ( ) ) ) , param ) ) , statements ) ; } private Statement createStartSummarizeFor ( SimpleName parameterName , ModelProperty property ) { Source source = property . getFrom ( ) ; Expression to = f . newFieldAccessExpression ( f . newThis ( ) , common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ) ; switch ( source . getAggregator ( ) ) { case IDENT : case MAX : case MIN : case SUM : return new ExpressionBuilder ( f , to ) . method ( Constants . NAME_OPTION_MODIFIER , new ExpressionBuilder ( f , parameterName ) . method ( common . getGetterNameOf ( source . getName ( ) , source . getType ( ) ) ) . toExpression ( ) ) . toStatement ( ) ; case COUNT : return new ExpressionBuilder ( f , to ) . method ( Constants . NAME_OPTION_MODIFIER , Models . toLiteral ( f , ) ) . toStatement ( ) ; default : throw new AssertionError ( ) ; } } private TypeBodyDeclaration createProcessSummarize ( SummarizedModelDescription model ) { SimpleName param = common . getVariableNameOf ( model , "" ) ; List < Statement > statements = new ArrayList < Statement > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { if ( property . getFrom ( ) . getAggregator ( ) == Aggregator . IDENT ) { continue ; } statements . add ( createAddSummarizeFor ( param . getToken ( ) , property ) ) ; } return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( param ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , Models . toType ( f , void . class ) , common . getCombineSummarizerName ( ) , Collections . singletonList ( f . newFormalParameterDeclaration ( bless ( common . getModelType ( model . getReference ( ) ) ) , param ) ) , statements ) ; } private Statement createAddSummarizeFor ( String parameterName , ModelProperty property ) { Source source = property . getFrom ( ) ; Expression self = f . newFieldAccessExpression ( f . newThis ( ) , common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ) ; Expression other = f . newFieldAccessExpression ( f . newSimpleName ( parameterName ) , common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ) ; Aggregator aggregator = source . getAggregator ( ) ; switch ( aggregator ) { case MAX : case MIN : return new ExpressionBuilder ( f , self ) . method ( aggregator . name ( ) . toLowerCase ( ) , other ) . toStatement ( ) ; case SUM : case COUNT : return new ExpressionBuilder ( f , self ) . method ( Constants . NAME_OPTION_ADDER , other ) . toStatement ( ) ; default : throw new AssertionError ( ) ; } } @ Override protected List < Annotation > createAnnotationsForModel ( SummarizedModelDescription model ) { return new AttributeBuilder ( f ) . annotation ( bless ( DataModel . class ) ) . annotation ( bless ( SummarizedModel . class ) , "" , createModelRefAnnotation ( model . getOriginalModel ( ) , model . getGroupBy ( ) ) ) . annotation ( bless ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . toAnnotations ( ) ; } @ Override protected List < Annotation > createAnnotationsForField ( ModelProperty property ) { return new AttributeBuilder ( f ) . annotation ( bless ( Property . class ) , "" , createSourceAnnotation ( property . getFrom ( ) ) , "" , Models . append ( f , ( ( NamedType ) bless ( Property . Aggregator . class ) ) . getName ( ) , property . getFrom ( ) . getAggregator ( ) . name ( ) ) ) . toAnnotations ( ) ; } private Annotation createModelRefAnnotation ( ModelReference reference , List < Source > groupSources ) { List < String > groupKeys = new ArrayList < String > ( ) ; for ( Source s : groupSources ) { groupKeys . add ( common . getFieldNameOf ( s . getName ( ) , s . getType ( ) ) . getToken ( ) ) ; } String [ ] group = groupKeys . toArray ( new String [ groupKeys . size ( ) ] ) ; Annotation key = f . newNormalAnnotation ( ( NamedType ) bless ( Key . class ) , Collections . singletonList ( f . newAnnotationElement ( f . newSimpleName ( "" ) , Models . toArrayInitializer ( f , group ) ) ) ) ; return f . newNormalAnnotation ( ( NamedType ) bless ( ModelRef . class ) , Arrays . asList ( new AnnotationElement [ ] { f . newAnnotationElement ( f . newSimpleName ( "" ) , f . newClassLiteral ( bless ( common . getModelType ( reference ) ) ) ) , f . newAnnotationElement ( f . newSimpleName ( "" ) , key ) , } ) ) ; } private Annotation createSourceAnnotation ( Source source ) { AnnotationElement declaring = f . newAnnotationElement ( f . newSimpleName ( "" ) , f . newClassLiteral ( bless ( common . getModelType ( source . getDeclaring ( ) ) ) ) ) ; AnnotationElement name = f . newAnnotationElement ( f . newSimpleName ( "" ) , Models . toLiteral ( f , common . getFieldNameOf ( source . getName ( ) , source . getType ( ) ) . getToken ( ) ) ) ; return f . newNormalAnnotation ( ( NamedType ) bless ( Property . Source . class ) , Arrays . asList ( declaring , name ) ) ; } @ Override protected Javadoc createJavadocForModel ( SummarizedModelDescription model ) { List < String > groupByNames = new ArrayList < String > ( ) ; for ( Source source : model . getGroupBy ( ) ) { groupByNames . add ( source . getName ( ) ) ; } String groupByComment ; if ( groupByNames . isEmpty ( ) ) { groupByComment = "" ; } else { groupByComment = MessageFormat . format ( "" , groupByNames ) ; } return new JavadocBuilder ( f ) . text ( "" , model . getReference ( ) . getSimpleName ( ) ) . text ( groupByComment ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForField ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , getColumnDescription ( property ) ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForGetter ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , getColumnDescription ( property ) ) . returns ( ) . text ( getColumnDescription ( property ) ) . exception ( bless ( NullPointerException . class ) ) . text ( "" ) . code ( "" ) . text ( "" ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForSetter ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , getColumnDescription ( property ) ) . param ( createNameForParameter ( property ) ) . text ( "" ) . toJavadoc ( ) ; } private String getColumnDescription ( ModelProperty property ) { Source source = property . getFrom ( ) ; if ( source . getAggregator ( ) == Aggregator . IDENT ) { return MessageFormat . format ( "" , source . getName ( ) ) ; } else { return MessageFormat . format ( "" , source . getName ( ) , source . getAggregator ( ) ) ; } } } package com . asakusafw . modelgen . emitter ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . modelgen . Constants ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . utils . java . model . syntax . Comment ; import com . asakusafw . utils . java . model . syntax . CompilationUnit ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . util . CommentEmitTrait ; import com . asakusafw . utils . java . model . util . Emitter ; import com . asakusafw . utils . java . model . util . Filer ; import com . asakusafw . utils . java . model . util . ImportBuilder ; import com . asakusafw . utils . java . model . util . Models ; public abstract class BaseEmitter < T extends ModelDescription > { protected final ModelFactory f ; protected final CommonEmitter common ; private List < String > headerComment ; protected ImportBuilder imports ; private Emitter emitter ; public BaseEmitter ( ModelFactory factory , File output , String rootPackageName , List < String > headerComment ) { if ( factory == null ) { throw new IllegalArgumentException ( "" ) ; } if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } if ( rootPackageName == null ) { throw new IllegalArgumentException ( "" ) ; } this . emitter = new Filer ( output , Constants . OUTPUT_ENCODING ) ; this . f = factory ; this . common = new CommonEmitter ( factory , rootPackageName ) ; this . headerComment = headerComment == null ? null : new ArrayList < String > ( headerComment ) ; } public void emit ( T model ) throws IOException { CompilationUnit source = createSource ( model ) ; PrintWriter writer = openOutputFor ( source ) ; try { Models . emit ( source , writer ) ; } finally { writer . close ( ) ; } } protected CompilationUnit createSource ( T model ) { PackageDeclaration packageDecl = createPackageDeclaration ( model ) ; imports = new ImportBuilder ( f , packageDecl , ImportBuilder . Strategy . TOP_LEVEL ) ; TypeDeclaration type = createTypeDeclaration ( model ) ; CompilationUnit unit = f . newCompilationUnit ( packageDecl , imports . toImportDeclarations ( ) , Collections . singletonList ( type ) , Collections . < Comment > emptyList ( ) ) ; if ( headerComment != null ) { unit . putModelTrait ( CommentEmitTrait . class , new CommentEmitTrait ( headerComment ) ) ; } return unit ; } protected abstract PackageDeclaration createPackageDeclaration ( T model ) ; protected abstract TypeDeclaration createTypeDeclaration ( T model ) ; protected PrintWriter openOutputFor ( CompilationUnit source ) throws IOException { return emitter . openFor ( source ) ; } protected Type bless ( java . lang . reflect . Type type ) { return bless ( Models . toType ( f , type ) ) ; } protected Type bless ( Type type ) { return imports . resolve ( type ) ; } } @ java . lang . Deprecated package com . asakusafw . modelgen . emitter ; package com . asakusafw . modelgen . emitter ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import javax . annotation . Generated ; import org . apache . hadoop . io . Writable ; import com . asakusafw . modelgen . Constants ; import com . asakusafw . modelgen . model . ModelDescription ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . PropertyType ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . Attribute ; import com . asakusafw . utils . java . model . syntax . Block ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . ModifierKind ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . Type ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; public abstract class ModelEntityEmitter < T extends ModelDescription > extends BaseEmitter < T > { private static final int HASHCODE_PRIME = ; public ModelEntityEmitter ( ModelFactory factory , File output , String packageName , List < String > headerComment ) { super ( factory , output , packageName , headerComment ) ; } public abstract Class < T > getEmitTargetType ( ) ; @ Override protected PackageDeclaration createPackageDeclaration ( T model ) { return f . newPackageDeclaration ( common . getPackageNameOf ( model . getReference ( ) , Constants . CATEGORY_MODEL ) ) ; } @ Override protected TypeDeclaration createTypeDeclaration ( T model ) { bless ( common . getModelType ( model . getReference ( ) ) ) ; List < Annotation > annotations = createAnnotationsForModel ( model ) ; List < Attribute > modifiers = new ArrayList < Attribute > ( ) ; modifiers . addAll ( new AttributeBuilder ( f ) . annotation ( bless ( Generated . class ) , Models . toLiteral ( f , MessageFormat . format ( "" , getClass ( ) . getSimpleName ( ) , Constants . VERSION ) ) ) . toAnnotations ( ) ) ; modifiers . addAll ( annotations ) ; modifiers . add ( f . newModifier ( ModifierKind . PUBLIC ) ) ; return f . newClassDeclaration ( createJavadocForModel ( model ) , modifiers , common . getTypeNameOf ( model . getReference ( ) ) , Collections . < TypeParameterDeclaration > emptyList ( ) , null , createSuperInterfaces ( model ) , createMembers ( model ) ) ; } protected List < TypeBodyDeclaration > createMembers ( T model ) { List < ModelProperty > properties = model . getProperties ( ) ; List < TypeBodyDeclaration > body = new ArrayList < TypeBodyDeclaration > ( ) ; for ( ModelProperty property : properties ) { TypeBodyDeclaration member = createField ( property ) ; body . add ( member ) ; } for ( ModelProperty property : properties ) { TypeBodyDeclaration getter = createGetter ( property ) ; body . add ( getter ) ; TypeBodyDeclaration setter = createSetter ( property ) ; body . add ( setter ) ; TypeBodyDeclaration altGetter = createAltGetter ( property ) ; if ( altGetter != null ) { body . add ( altGetter ) ; } TypeBodyDeclaration altSetter = createAltSetter ( property ) ; if ( altSetter != null ) { body . add ( altSetter ) ; } TypeBodyDeclaration optionGetter = createOptionGetter ( property ) ; body . add ( optionGetter ) ; TypeBodyDeclaration optionSetter = createOptionSetter ( property ) ; body . add ( optionSetter ) ; } body . add ( createCopier ( model ) ) ; body . add ( createWritableWrite ( model ) ) ; body . add ( createWritableReadFields ( model ) ) ; body . add ( createHashCode ( model ) ) ; body . add ( createEquals ( model ) ) ; body . add ( createToString ( model ) ) ; return body ; } protected FieldDeclaration createField ( ModelProperty property ) { List < Annotation > annotations = createAnnotationsForField ( property ) ; List < Attribute > modifiers = new ArrayList < Attribute > ( ) ; modifiers . addAll ( annotations ) ; modifiers . add ( f . newModifier ( ModifierKind . PRIVATE ) ) ; return f . newFieldDeclaration ( createJavadocForField ( property ) , modifiers , bless ( common . getOptionType ( property . getType ( ) ) ) , common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) , createInitializerForField ( property ) ) ; } protected MethodDeclaration createGetter ( ModelProperty property ) { List < Annotation > annotations = createAnnotationsForGetter ( property ) ; List < Attribute > modifiers = new ArrayList < Attribute > ( ) ; modifiers . addAll ( annotations ) ; modifiers . add ( f . newModifier ( ModifierKind . PUBLIC ) ) ; return f . newMethodDeclaration ( createJavadocForGetter ( property ) , modifiers , Collections . < TypeParameterDeclaration > emptyList ( ) , bless ( common . getRawType ( property . getType ( ) ) ) , common . getGetterNameOf ( property . getName ( ) , property . getType ( ) ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . < Type > emptyList ( ) , createBodyForGetter ( property ) ) ; } protected MethodDeclaration createSetter ( ModelProperty property ) { List < Annotation > annotations = createAnnotationsForSetter ( property ) ; List < Attribute > modifiers = new ArrayList < Attribute > ( ) ; modifiers . addAll ( annotations ) ; modifiers . add ( f . newModifier ( ModifierKind . PUBLIC ) ) ; SimpleName parameterName = createNameForParameter ( property ) ; return f . newMethodDeclaration ( createJavadocForSetter ( property ) , modifiers , Collections . < TypeParameterDeclaration > emptyList ( ) , Models . toType ( f , void . class ) , common . getSetterNameOf ( property . getName ( ) , property . getType ( ) ) , Collections . singletonList ( f . newFormalParameterDeclaration ( bless ( common . getRawType ( property . getType ( ) ) ) , parameterName ) ) , , Collections . < Type > emptyList ( ) , createBodyForSetter ( property , parameterName ) ) ; } protected MethodDeclaration createAltGetter ( ModelProperty property ) { SimpleName name = common . getAltGetterNameOf ( property . getName ( ) , property . getType ( ) ) ; if ( name == null ) { return null ; } List < Annotation > annotations = createAnnotationsForGetter ( property ) ; List < Attribute > modifiers = new ArrayList < Attribute > ( ) ; modifiers . addAll ( annotations ) ; modifiers . add ( f . newModifier ( ModifierKind . PUBLIC ) ) ; return f . newMethodDeclaration ( createJavadocForGetter ( property ) , modifiers , Collections . < TypeParameterDeclaration > emptyList ( ) , bless ( common . getAltType ( property . getType ( ) ) ) , name , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . < Type > emptyList ( ) , createBodyForAltGetter ( property ) ) ; } protected MethodDeclaration createAltSetter ( ModelProperty property ) { SimpleName name = common . getAltSetterNameOf ( property . getName ( ) , property . getType ( ) ) ; if ( name == null ) { return null ; } List < Annotation > annotations = createAnnotationsForSetter ( property ) ; List < Attribute > modifiers = new ArrayList < Attribute > ( ) ; modifiers . addAll ( annotations ) ; modifiers . add ( f . newModifier ( ModifierKind . PUBLIC ) ) ; SimpleName parameterName = createNameForParameter ( property ) ; return f . newMethodDeclaration ( createJavadocForSetter ( property ) , modifiers , Collections . < TypeParameterDeclaration > emptyList ( ) , Models . toType ( f , void . class ) , common . getAltSetterNameOf ( property . getName ( ) , property . getType ( ) ) , Collections . singletonList ( f . newFormalParameterDeclaration ( bless ( common . getAltType ( property . getType ( ) ) ) , parameterName ) ) , , Collections . < Type > emptyList ( ) , createBodyForAltSetter ( property , parameterName ) ) ; } protected MethodDeclaration createOptionGetter ( ModelProperty property ) { List < Annotation > annotations = createAnnotationsForOptionGetter ( property ) ; List < Attribute > modifiers = new ArrayList < Attribute > ( ) ; modifiers . addAll ( annotations ) ; modifiers . add ( f . newModifier ( ModifierKind . PUBLIC ) ) ; return f . newMethodDeclaration ( createJavadocForOptionGetter ( property ) , modifiers , Collections . < TypeParameterDeclaration > emptyList ( ) , bless ( common . getOptionType ( property . getType ( ) ) ) , common . getOptionGetterNameOf ( property . getName ( ) , property . getType ( ) ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Collections . < Type > emptyList ( ) , createBodyForOptionGetter ( property ) ) ; } protected MethodDeclaration createOptionSetter ( ModelProperty property ) { List < Annotation > annotations = createAnnotationsForOptionSetter ( property ) ; List < Attribute > modifiers = new ArrayList < Attribute > ( ) ; modifiers . addAll ( annotations ) ; modifiers . add ( f . newModifier ( ModifierKind . PUBLIC ) ) ; SimpleName parameterName = createNameForParameter ( property ) ; return f . newMethodDeclaration ( createJavadocForOptionSetter ( property ) , modifiers , Collections . < TypeParameterDeclaration > emptyList ( ) , Models . toType ( f , void . class ) , common . getOptionSetterNameOf ( property . getName ( ) , property . getType ( ) ) , Collections . singletonList ( f . newFormalParameterDeclaration ( bless ( common . getOptionType ( property . getType ( ) ) ) , parameterName ) ) , , Collections . < Type > emptyList ( ) , createBodyForOptionSetter ( property , parameterName ) ) ; } protected TypeBodyDeclaration createCopier ( T model ) { SimpleName parameter = common . getVariableNameOf ( model , "" ) ; List < Statement > statements = new ArrayList < Statement > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { statements . add ( createCopierFor ( parameter , property . getName ( ) , property . getName ( ) , property . getType ( ) ) ) ; } return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . param ( parameter ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , Models . toType ( f , void . class ) , common . getCopierName ( ) , Collections . singletonList ( f . newFormalParameterDeclaration ( bless ( common . getModelType ( model . getReference ( ) ) ) , parameter ) ) , , Collections . < Type > emptyList ( ) , f . newBlock ( statements ) ) ; } private TypeBodyDeclaration createWritableWrite ( T model ) { SimpleName parameter = common . getVariableNameOf ( model , "" ) ; List < Statement > statements = new ArrayList < Statement > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { SimpleName fieldName = common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ; statements . add ( new ExpressionBuilder ( f , fieldName ) . method ( "" , parameter ) . toStatement ( ) ) ; } return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , Models . toType ( f , void . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( bless ( DataOutput . class ) , parameter ) ) , , Collections . singletonList ( bless ( IOException . class ) ) , f . newBlock ( statements ) ) ; } private TypeBodyDeclaration createWritableReadFields ( T model ) { SimpleName parameter = common . getVariableNameOf ( model , "" ) ; List < Statement > statements = new ArrayList < Statement > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { SimpleName fieldName = common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ; statements . add ( new ExpressionBuilder ( f , fieldName ) . method ( "" , parameter ) . toStatement ( ) ) ; } return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , Models . toType ( f , void . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( bless ( DataInput . class ) , parameter ) ) , , Collections . singletonList ( bless ( IOException . class ) ) , f . newBlock ( statements ) ) ; } private TypeBodyDeclaration createHashCode ( T model ) { List < Statement > statements = new ArrayList < Statement > ( ) ; SimpleName prime = common . getVariableNameOf ( model , "" ) ; SimpleName result = common . getVariableNameOf ( model , "" ) ; statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , HASHCODE_PRIME ) ) . toLocalVariableDeclaration ( Models . toType ( f , int . class ) , prime ) ) ; statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , ) ) . toLocalVariableDeclaration ( Models . toType ( f , int . class ) , result ) ) ; for ( ModelProperty property : model . getProperties ( ) ) { SimpleName field = common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ; statements . add ( new ExpressionBuilder ( f , result ) . assignFrom ( new ExpressionBuilder ( f , prime ) . apply ( InfixOperator . TIMES , result ) . apply ( InfixOperator . PLUS , new ExpressionBuilder ( f , field ) . method ( "" ) . toExpression ( ) ) . toExpression ( ) ) . toStatement ( ) ) ; } statements . add ( f . newReturnStatement ( result ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , Models . toType ( f , int . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private TypeBodyDeclaration createEquals ( T model ) { List < Statement > statements = new ArrayList < Statement > ( ) ; SimpleName obj = common . getVariableNameOf ( model , "" ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , f . newThis ( ) ) . apply ( InfixOperator . EQUALS , obj ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , true ) ) ) ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , obj ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , false ) ) ) ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , f . newThis ( ) ) . method ( "" ) . apply ( InfixOperator . NOT_EQUALS , new ExpressionBuilder ( f , obj ) . method ( "" ) . toExpression ( ) ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , false ) ) ) ) ) ; SimpleName other = common . getVariableNameOf ( model , "" ) ; statements . add ( new ExpressionBuilder ( f , obj ) . castTo ( bless ( common . getModelType ( model . getReference ( ) ) ) ) . toLocalVariableDeclaration ( bless ( common . getModelType ( model . getReference ( ) ) ) , other ) ) ; for ( ModelProperty property : model . getProperties ( ) ) { SimpleName field = common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , f . newThis ( ) ) . field ( field ) . method ( "" , new ExpressionBuilder ( f , other ) . field ( field ) . toExpression ( ) ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , false ) ) ) ) ) ; } statements . add ( f . newReturnStatement ( Models . toLiteral ( f , true ) ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , Models . toType ( f , boolean . class ) , f . newSimpleName ( "" ) , Collections . singletonList ( f . newFormalParameterDeclaration ( bless ( Object . class ) , obj ) ) , statements ) ; } private TypeBodyDeclaration createToString ( T model ) { List < Statement > statements = new ArrayList < Statement > ( ) ; SimpleName buffer = common . getVariableNameOf ( model , "" ) ; statements . add ( new TypeBuilder ( f , bless ( StringBuilder . class ) ) . newObject ( ) . toLocalVariableDeclaration ( bless ( StringBuilder . class ) , buffer ) ) ; statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , Models . toLiteral ( f , "" ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , Models . toLiteral ( f , "" + model . getReference ( ) . getSimpleName ( ) ) ) . toStatement ( ) ) ; for ( ModelProperty property : model . getProperties ( ) ) { statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , Models . toLiteral ( f , MessageFormat . format ( "" , common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ) ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , new ExpressionBuilder ( f , f . newThis ( ) ) . field ( common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ) . toExpression ( ) ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" , Models . toLiteral ( f , "" ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , buffer ) . method ( "" ) . toReturnStatement ( ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( bless ( Override . class ) ) . Public ( ) . toAttributes ( ) , bless ( String . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } protected Statement createCopierFor ( Expression fromObject , String fromName , String toName , PropertyType type ) { Expression to = new ExpressionBuilder ( f , f . newThis ( ) ) . field ( common . getFieldNameOf ( toName , type ) ) . toExpression ( ) ; Expression from = new ExpressionBuilder ( f , fromObject ) . field ( common . getFieldNameOf ( fromName , type ) ) . toExpression ( ) ; return new ExpressionBuilder ( f , to ) . method ( Constants . NAME_OPTION_COPIER , from ) . toStatement ( ) ; } protected Statement createImporterFor ( Expression fromObject , String fromName , String toName , PropertyType type ) { Expression to = f . newFieldAccessExpression ( f . newThis ( ) , common . getFieldNameOf ( toName , type ) ) ; if ( fromObject == null || fromName == null ) { return new ExpressionBuilder ( f , to ) . method ( Constants . NAME_OPTION_ERASER ) . toStatement ( ) ; } else { Expression from = new ExpressionBuilder ( f , fromObject ) . method ( common . getOptionGetterNameOf ( fromName , type ) ) . toExpression ( ) ; return new ExpressionBuilder ( f , to ) . method ( Constants . NAME_OPTION_COPIER , from ) . toStatement ( ) ; } } protected Statement createExporterFor ( String fromName , Expression toObject , String toName , PropertyType type ) { Expression from = new ExpressionBuilder ( f , f . newThis ( ) ) . field ( common . getFieldNameOf ( fromName , type ) ) . toExpression ( ) ; Expression to = new ExpressionBuilder ( f , toObject ) . method ( common . getOptionGetterNameOf ( toName , type ) ) . toExpression ( ) ; return new ExpressionBuilder ( f , to ) . method ( Constants . NAME_OPTION_COPIER , from ) . toStatement ( ) ; } protected List < Type > createSuperInterfaces ( T model ) { return Collections . singletonList ( bless ( Writable . class ) ) ; } protected final SimpleName createNameForParameter ( ModelProperty property ) { return common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ; } protected Expression createInitializerForField ( ModelProperty property ) { return common . getInitialValue ( property . getType ( ) , imports ) ; } protected Block createBodyForGetter ( ModelProperty property ) { List < Statement > statements = new ArrayList < Statement > ( ) ; statements . add ( thisFieldFor ( property ) . method ( Constants . NAME_OPTION_EXTRACTOR ) . toReturnStatement ( ) ) ; return f . newBlock ( statements ) ; } protected Block createBodyForSetter ( ModelProperty property , SimpleName parameterName ) { List < Statement > statements = new ArrayList < Statement > ( ) ; statements . add ( thisFieldFor ( property ) . method ( Constants . NAME_OPTION_MODIFIER , parameterName ) . toStatement ( ) ) ; return f . newBlock ( statements ) ; } protected Block createBodyForAltGetter ( ModelProperty property ) { List < Statement > statements = new ArrayList < Statement > ( ) ; statements . add ( thisFieldFor ( property ) . method ( common . toAltMemberName ( Constants . NAME_OPTION_EXTRACTOR , property . getType ( ) ) ) . toReturnStatement ( ) ) ; return f . newBlock ( statements ) ; } protected Block createBodyForAltSetter ( ModelProperty property , SimpleName parameterName ) { return createBodyForSetter ( property , parameterName ) ; } protected Block createBodyForOptionGetter ( ModelProperty property ) { Statement result = thisFieldFor ( property ) . toReturnStatement ( ) ; return f . newBlock ( Collections . singletonList ( result ) ) ; } protected Block createBodyForOptionSetter ( ModelProperty property , SimpleName parameterName ) { Statement result = thisFieldFor ( property ) . method ( Constants . NAME_OPTION_COPIER , parameterName ) . toStatement ( ) ; return f . newBlock ( Collections . singletonList ( result ) ) ; } private ExpressionBuilder thisFieldFor ( ModelProperty property ) { assert property != null ; SimpleName fieldName = common . getFieldNameOf ( property . getName ( ) , property . getType ( ) ) ; return new ExpressionBuilder ( f , f . newThis ( ) ) . field ( fieldName ) ; } protected Javadoc createJavadocForModel ( T model ) { return null ; } protected Javadoc createJavadocForField ( ModelProperty property ) { return null ; } protected Javadoc createJavadocForGetter ( ModelProperty property ) { return null ; } protected Javadoc createJavadocForSetter ( ModelProperty property ) { return null ; } protected Javadoc createJavadocForOptionGetter ( ModelProperty property ) { SimpleName getter = common . getGetterNameOf ( property . getName ( ) , property . getType ( ) ) ; return new JavadocBuilder ( f ) . linkMethod ( getter ) . text ( "" ) . code ( "" ) . text ( "" ) . returns ( ) . text ( "" ) . linkMethod ( getter ) . toJavadoc ( ) ; } protected Javadoc createJavadocForOptionSetter ( ModelProperty property ) { SimpleName setter = common . getSetterNameOf ( property . getName ( ) , property . getType ( ) ) ; return new JavadocBuilder ( f ) . linkMethod ( setter , bless ( common . getRawType ( property . getType ( ) ) ) ) . text ( "" ) . code ( "" ) . text ( "" ) . param ( createNameForParameter ( property ) ) . text ( "" ) . code ( "" ) . toJavadoc ( ) ; } protected List < Annotation > createAnnotationsForModel ( T model ) { return Collections . emptyList ( ) ; } protected List < Annotation > createAnnotationsForField ( ModelProperty property ) { return Collections . emptyList ( ) ; } protected List < Annotation > createAnnotationsForGetter ( ModelProperty property ) { return Collections . emptyList ( ) ; } protected List < Annotation > createAnnotationsForSetter ( ModelProperty property ) { return Collections . emptyList ( ) ; } protected List < Annotation > createAnnotationsForOptionGetter ( ModelProperty property ) { return Collections . emptyList ( ) ; } protected List < Annotation > createAnnotationsForOptionSetter ( ModelProperty property ) { return Collections . emptyList ( ) ; } } package com . asakusafw . modelgen . emitter ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import com . asakusafw . modelgen . model . Attribute ; import com . asakusafw . modelgen . model . ModelProperty ; import com . asakusafw . modelgen . model . TableModelDescription ; import com . asakusafw . utils . java . model . syntax . Annotation ; import com . asakusafw . utils . java . model . syntax . Javadoc ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . vocabulary . model . DataModel ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; public class TableModelEntityEmitter extends ModelEntityEmitter < TableModelDescription > { public TableModelEntityEmitter ( ModelFactory factory , File output , String packageName , List < String > headerComment ) { super ( factory , output , packageName , headerComment ) ; } @ Override public Class < TableModelDescription > getEmitTargetType ( ) { return TableModelDescription . class ; } @ Override protected List < Annotation > createAnnotationsForModel ( TableModelDescription model ) { String name = model . getReference ( ) . getSimpleName ( ) ; List < String > columnNames = new ArrayList < String > ( ) ; List < String > primaryKeys = new ArrayList < String > ( ) ; for ( ModelProperty property : model . getProperties ( ) ) { columnNames . add ( property . getName ( ) ) ; if ( property . getSource ( ) . getAttributes ( ) . contains ( Attribute . PRIMARY_KEY ) ) { primaryKeys . add ( property . getName ( ) ) ; } } String [ ] primary = primaryKeys . toArray ( new String [ primaryKeys . size ( ) ] ) ; String [ ] columns = columnNames . toArray ( new String [ columnNames . size ( ) ] ) ; return new AttributeBuilder ( f ) . annotation ( bless ( DataModel . class ) ) . annotation ( bless ( TableModel . class ) , "" , Models . toLiteral ( f , name ) , "" , Models . toArrayInitializer ( f , columns ) , "" , Models . toArrayInitializer ( f , primary ) ) . annotation ( bless ( SuppressWarnings . class ) , Models . toLiteral ( f , "" ) ) . toAnnotations ( ) ; } @ Override protected List < Annotation > createAnnotationsForField ( ModelProperty property ) { return new AttributeBuilder ( f ) . annotation ( bless ( Property . class ) , "" , Models . toLiteral ( f , property . getName ( ) ) ) . toAnnotations ( ) ; } @ Override protected Javadoc createJavadocForModel ( TableModelDescription model ) { return new JavadocBuilder ( f ) . text ( "" , model . getReference ( ) . getSimpleName ( ) ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForField ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , property . getName ( ) ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForGetter ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , property . getName ( ) ) . returns ( ) . text ( "" , property . getName ( ) ) . exception ( bless ( NullPointerException . class ) ) . text ( "" ) . code ( "" ) . text ( "" ) . toJavadoc ( ) ; } @ Override protected Javadoc createJavadocForSetter ( ModelProperty property ) { return new JavadocBuilder ( f ) . text ( "" , property . getName ( ) ) . param ( createNameForParameter ( property ) ) . text ( "" ) . toJavadoc ( ) ; } } package com . asakusafw . compiler . fileio ; package com . asakusafw . compiler . fileio ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import java . util . regex . Pattern ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . FlowCompilerOptions . GenericOptionValue ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . mapreduce . copy . CopierClientEmitter ; import com . asakusafw . compiler . flow . mapreduce . copy . CopyDescription ; import com . asakusafw . compiler . flow . mapreduce . parallel . ParallelSortClientEmitter ; import com . asakusafw . compiler . flow . mapreduce . parallel . ResolvedSlot ; import com . asakusafw . compiler . flow . mapreduce . parallel . Slot ; import com . asakusafw . compiler . flow . mapreduce . parallel . SlotResolver ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . FileExporterDescription ; import com . asakusafw . vocabulary . external . FileImporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; public class HadoopFileIoProcessor extends ExternalIoDescriptionProcessor { private static final Pattern VALID_OUTPUT_NAME = Pattern . compile ( "" ) ; private static final String MODULE_NAME = "" ; public static final String OPTION_EXPORTER_ENABLED = "" ; private static final GenericOptionValue DEFAULT_EXPORTER_ENABLED = GenericOptionValue . AUTO ; @ Override public Class < ? extends ImporterDescription > getImporterDescriptionType ( ) { return FileImporterDescription . class ; } @ Override public Class < ? extends ExporterDescription > getExporterDescriptionType ( ) { return FileExporterDescription . class ; } @ Override public boolean validate ( List < InputDescription > inputs , List < OutputDescription > outputs ) { boolean valid = validateOutputs ( outputs ) ; return valid ; } private boolean validateOutputs ( List < OutputDescription > outputs ) { assert outputs != null ; boolean valid = true ; GenericOptionValue exporterEnabled = getEnvironment ( ) . getOptions ( ) . getGenericExtraAttribute ( OPTION_EXPORTER_ENABLED , DEFAULT_EXPORTER_ENABLED ) ; if ( exporterEnabled == GenericOptionValue . INVALID ) { getEnvironment ( ) . error ( "" , getEnvironment ( ) . getOptions ( ) . getExtraAttributeKeyName ( OPTION_EXPORTER_ENABLED ) , getEnvironment ( ) . getOptions ( ) . getExtraAttribute ( OPTION_EXPORTER_ENABLED ) , GenericOptionValue . ENABLED . getSymbol ( ) + "" + GenericOptionValue . DISABLED . getSymbol ( ) ) ; exporterEnabled = DEFAULT_EXPORTER_ENABLED ; valid = false ; } boolean mr370applied = checkClassExists ( "" ) ; for ( OutputDescription output : outputs ) { FileExporterDescription desc = extract ( output ) ; if ( exporterEnabled == GenericOptionValue . DISABLED ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , getEnvironment ( ) . getOptions ( ) . getExtraAttributeKeyName ( OPTION_EXPORTER_ENABLED ) , GenericOptionValue . ENABLED . getSymbol ( ) ) ; } else if ( mr370applied == false && exporterEnabled == GenericOptionValue . AUTO ) { valid = false ; getEnvironment ( ) . error ( "" + "" , desc . getClass ( ) . getName ( ) , FileExporterDescription . class . getSimpleName ( ) , "" ) ; } String pathPrefix = desc . getPathPrefix ( ) ; if ( pathPrefix == null ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) ) ; } else { Location location = Location . fromPath ( pathPrefix , '' ) ; if ( location . isPrefix ( ) == false ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , pathPrefix ) ; } if ( location . getParent ( ) == null ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , pathPrefix ) ; } if ( VALID_OUTPUT_NAME . matcher ( location . getName ( ) ) . matches ( ) == false ) { valid = false ; getEnvironment ( ) . error ( "" , desc . getClass ( ) . getName ( ) , pathPrefix ) ; } } } return valid ; } private boolean checkClassExists ( String className ) { try { Class . forName ( className ) ; return true ; } catch ( ClassNotFoundException e ) { return false ; } } @ Override public SourceInfo getInputInfo ( InputDescription description ) { FileImporterDescription desc = extract ( description ) ; if ( isCacheTarget ( desc ) ) { String outputName = getProcessedInputName ( description ) ; Location location = getEnvironment ( ) . getPrologueLocation ( MODULE_NAME ) . append ( outputName ) . asPrefix ( ) ; return new SourceInfo ( Collections . singleton ( location ) , TemporaryInputFormat . class ) ; } else { return getOrifinalInputInfo ( desc ) ; } } private SourceInfo getOrifinalInputInfo ( FileImporterDescription desc ) { assert desc != null ; Set < Location > locations = Sets . create ( ) ; for ( String path : desc . getPaths ( ) ) { locations . add ( Location . fromPath ( path , '' ) ) ; } return new SourceInfo ( locations , desc . getInputFormat ( ) ) ; } private boolean isCacheTarget ( ImporterDescription desc ) { assert desc != null ; switch ( desc . getDataSize ( ) ) { case TINY : return getEnvironment ( ) . getOptions ( ) . isHashJoinForTiny ( ) ; case SMALL : return getEnvironment ( ) . getOptions ( ) . isHashJoinForSmall ( ) ; default : return false ; } } private String getProcessedInputName ( InputDescription description ) { assert description != null ; StringBuilder buf = new StringBuilder ( ) ; for ( char c : description . getName ( ) . toCharArray ( ) ) { if ( '' <= c && c <= '' || '' <= c && c <= '' || '' <= c && c <= '' ) { buf . append ( c ) ; } else if ( c <= ) { buf . append ( '' ) ; buf . append ( String . format ( "" , ( int ) c ) ) ; } else { buf . append ( "" ) ; buf . append ( String . format ( "" , ( int ) c ) ) ; } } return buf . toString ( ) ; } @ Override public List < CompiledStage > emitPrologue ( IoContext context ) throws IOException { List < CopyDescription > targets = Lists . create ( ) ; for ( Input input : context . getInputs ( ) ) { InputDescription description = input . getDescription ( ) ; FileImporterDescription desc = extract ( description ) ; if ( isCacheTarget ( desc ) ) { targets . add ( new CopyDescription ( getProcessedInputName ( description ) , getEnvironment ( ) . getDataClasses ( ) . load ( description . getDataType ( ) ) , getOrifinalInputInfo ( desc ) , TemporaryOutputFormat . class ) ) ; } } if ( targets . isEmpty ( ) ) { return Collections . emptyList ( ) ; } CopierClientEmitter emitter = new CopierClientEmitter ( getEnvironment ( ) ) ; CompiledStage stage = emitter . emitPrologue ( MODULE_NAME , targets , getEnvironment ( ) . getPrologueLocation ( MODULE_NAME ) ) ; return Collections . singletonList ( stage ) ; } @ Override public List < CompiledStage > emitEpilogue ( IoContext context ) throws IOException { Set < String > saw = Sets . create ( ) ; List < CompiledStage > results = Lists . create ( ) ; for ( Map . Entry < Location , List < Slot > > entry : groupByOutputLocation ( context ) . entrySet ( ) ) { List < Slot > slots = entry . getValue ( ) ; List < ResolvedSlot > resolved = new SlotResolver ( getEnvironment ( ) ) . resolve ( slots ) ; if ( getEnvironment ( ) . hasError ( ) ) { return Collections . emptyList ( ) ; } ParallelSortClientEmitter emitter = new ParallelSortClientEmitter ( getEnvironment ( ) ) ; String moduleId = generateModuleName ( saw , entry . getKey ( ) ) ; CompiledStage stage = emitter . emit ( moduleId , resolved , entry . getKey ( ) ) ; results . add ( stage ) ; } return results ; } private String generateModuleName ( Set < String > saw , Location target ) { assert saw != null ; assert target != null ; String simpleSuffix = generateSuffix ( target ) ; String baseModuleId = MessageFormat . format ( "" , MODULE_NAME , simpleSuffix ) ; if ( saw . contains ( baseModuleId ) == false ) { saw . add ( baseModuleId ) ; return baseModuleId ; } int index = ; while ( true ) { String moduleIdCandidate = baseModuleId + index ; if ( saw . contains ( moduleIdCandidate ) == false ) { saw . add ( moduleIdCandidate ) ; return moduleIdCandidate ; } index ++ ; } } private String generateSuffix ( Location target ) { assert target != null ; String name = target . getName ( ) ; if ( name . isEmpty ( ) ) { return "" ; } StringBuilder buf = new StringBuilder ( ) ; if ( Character . isJavaIdentifierStart ( name . charAt ( ) ) == false ) { buf . append ( '' ) ; } for ( char c : name . toCharArray ( ) ) { if ( Character . isJavaIdentifierPart ( c ) ) { buf . append ( c ) ; } } assert buf . length ( ) >= ; return buf . toString ( ) ; } private Map < Location , List < Slot > > groupByOutputLocation ( IoContext context ) { assert context != null ; Map < Location , List < Slot > > results = new TreeMap < Location , List < Slot > > ( new Comparator < Location > ( ) { @ Override public int compare ( Location o1 , Location o2 ) { String parentPath1 = ( o1 . getParent ( ) == null ) ? "" : o1 . getParent ( ) . toPath ( '' ) ; String parentPath2 = ( o2 . getParent ( ) == null ) ? "" : o2 . getParent ( ) . toPath ( '' ) ; int parentDiff = parentPath1 . compareTo ( parentPath2 ) ; if ( parentDiff != ) { return ( parentDiff > ) ? + : - ; } return o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; } } ) ; for ( Output output : context . getOutputs ( ) ) { FileExporterDescription desc = extract ( output . getDescription ( ) ) ; Location path = Location . fromPath ( desc . getPathPrefix ( ) , '' ) ; Location parent = path . getParent ( ) ; Maps . addToList ( results , parent , toSlot ( output , path . getName ( ) ) ) ; } return results ; } private Slot toSlot ( Output output , String name ) { assert output != null ; assert name != null ; return new Slot ( name , output . getDescription ( ) . getDataType ( ) , Collections . < String > emptyList ( ) , output . getSources ( ) , extract ( output . getDescription ( ) ) . getOutputFormat ( ) ) ; } private FileImporterDescription extract ( InputDescription description ) { assert description != null ; ImporterDescription importer = description . getImporterDescription ( ) ; assert importer != null ; assert importer instanceof FileImporterDescription ; return ( FileImporterDescription ) importer ; } private FileExporterDescription extract ( OutputDescription description ) { assert description != null ; ExporterDescription exporter = description . getExporterDescription ( ) ; assert exporter != null ; assert exporter instanceof FileExporterDescription ; return ( FileExporterDescription ) exporter ; } } package com . asakusafw . compiler . fileio . external ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryOutputDescription ; public class Ex1MockExporterDescription extends TemporaryOutputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" + getModelType ( ) . getSimpleName ( ) + "" ; } } package com . asakusafw . compiler . fileio . external ; import java . util . Collections ; import java . util . Set ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . testing . TemporaryInputDescription ; public class Ex1MockImporterDescription extends TemporaryInputDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public Set < String > getPaths ( ) { return Collections . singleton ( "" + getModelType ( ) . getSimpleName ( ) ) ; } } package com . asakusafw . compiler . fileio . operator ; import javax . annotation . Generated ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . model . ExSummarized ; @ Generated ( "" ) public class ExOperatorImpl extends ExOperator { public ExOperatorImpl ( ) { return ; } @ Override public ExSummarized summarize ( Ex1 model ) { throw new UnsupportedOperationException ( "" ) ; } } package com . asakusafw . compiler . fileio . operator ; import java . util . Iterator ; import java . util . List ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . model . Ex2 ; import com . asakusafw . compiler . fileio . model . ExSummarized ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . operator . Branch ; import com . asakusafw . vocabulary . operator . CoGroup ; import com . asakusafw . vocabulary . operator . Fold ; import com . asakusafw . vocabulary . operator . Logging ; import com . asakusafw . vocabulary . operator . Sticky ; import com . asakusafw . vocabulary . operator . Summarize ; import com . asakusafw . vocabulary . operator . Update ; import com . asakusafw . vocabulary . operator . Volatile ; public abstract class ExOperator { @ Update public void update ( Ex1 model , int value ) { model . setValue ( value ) ; } @ Volatile @ Update public void random ( Ex1 model ) { model . setValue ( ( int ) ( Math . random ( ) * Integer . MAX_VALUE ) ) ; } @ Sticky @ Update public void error ( Ex1 model ) { throw new IllegalStateException ( ) ; } @ Fold public void foldAdd ( @ Key ( group = "" ) Ex1 a , Ex1 b ) { a . getValueOption ( ) . add ( b . getValueOption ( ) ) ; } @ CoGroup public void cogroupAdd ( @ Key ( group = "" , order = "" ) List < Ex1 > list , Result < Ex1 > result ) { Iterator < Ex1 > iter = list . iterator ( ) ; Ex1 first = iter . next ( ) ; while ( iter . hasNext ( ) ) { Ex1 next = iter . next ( ) ; first . getValueOption ( ) . add ( next . getValueOption ( ) ) ; } result . add ( first ) ; } @ Branch public Answer branch ( Ex1 model ) { int value = model . getValueOption ( ) . get ( ) ; if ( value == ) { return Answer . YES ; } if ( value == ) { return Answer . NO ; } return Answer . CANCEL ; } @ Summarize public abstract ExSummarized summarize ( Ex1 model ) ; @ CoGroup public void cogroup ( @ Key ( group = "" , order = "" ) List < Ex1 > ex1 , @ Key ( group = "" , order = "" ) List < Ex2 > ex2 , Result < Ex1 > r1 , Result < Ex2 > r2 ) { if ( ex1 . isEmpty ( ) == false ) { r1 . add ( ex1 . get ( ) ) ; } if ( ex2 . isEmpty ( ) == false ) { r2 . add ( ex2 . get ( ) ) ; } } @ Logging public String logging ( Ex1 ex1 ) { return ex1 . getStringOption ( ) . toString ( ) ; } public enum Answer { YES , NO , CANCEL , } } package com . asakusafw . compiler . fileio . operator ; import java . util . Arrays ; import java . util . List ; import javax . annotation . Generated ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . model . Ex2 ; import com . asakusafw . compiler . fileio . model . ExSummarized ; import com . asakusafw . runtime . core . Result ; import com . asakusafw . vocabulary . flow . Operator ; import com . asakusafw . vocabulary . flow . Source ; import com . asakusafw . vocabulary . flow . graph . Connectivity ; import com . asakusafw . vocabulary . flow . graph . FlowBoundary ; import com . asakusafw . vocabulary . flow . graph . FlowElementResolver ; import com . asakusafw . vocabulary . flow . graph . ObservationCount ; import com . asakusafw . vocabulary . flow . graph . OperatorDescription ; import com . asakusafw . vocabulary . flow . graph . ShuffleKey ; import com . asakusafw . vocabulary . flow . processor . InputBuffer ; import com . asakusafw . vocabulary . flow . processor . PartialAggregation ; import com . asakusafw . vocabulary . operator . CoGroup ; import com . asakusafw . vocabulary . operator . Fold ; @ Generated ( "" ) public class ExOperatorFactory { public static final class FoldAdd implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; FoldAdd ( Source < Ex1 > in ) { OperatorDescription . Builder builder = new OperatorDescription . Builder ( Fold . class ) ; builder . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder . declareParameter ( Ex1 . class ) ; builder . declareParameter ( Ex1 . class ) ; builder . addInput ( "" , in , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder . addOutput ( "" , in ) ; builder . addAttribute ( FlowBoundary . SHUFFLE ) ; builder . addAttribute ( ObservationCount . DONT_CARE ) ; builder . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder . toResolver ( ) ; this . $ . resolveInput ( "" , in ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . FoldAdd as ( String newName ) { this . $ . setName ( newName ) ; return this ; } } public ExOperatorFactory . FoldAdd foldAdd ( Source < Ex1 > in ) { return new ExOperatorFactory . FoldAdd ( in ) ; } public static final class Update implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Update ( Source < Ex1 > model , int value ) { OperatorDescription . Builder builder0 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Update . class ) ; builder0 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder0 . declareParameter ( Ex1 . class ) ; builder0 . declareParameter ( int . class ) ; builder0 . addInput ( "" , model ) ; builder0 . addOutput ( "" , model ) ; builder0 . addParameter ( "" , int . class , value ) ; builder0 . addAttribute ( ObservationCount . DONT_CARE ) ; this . $ = builder0 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Update as ( String newName0 ) { this . $ . setName ( newName0 ) ; return this ; } } public ExOperatorFactory . Update update ( Source < Ex1 > model , int value ) { return new ExOperatorFactory . Update ( model , value ) ; } public static final class Random implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Random ( Source < Ex1 > model ) { OperatorDescription . Builder builder1 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Update . class ) ; builder1 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder1 . declareParameter ( Ex1 . class ) ; builder1 . addInput ( "" , model ) ; builder1 . addOutput ( "" , model ) ; builder1 . addAttribute ( ObservationCount . AT_MOST_ONCE ) ; this . $ = builder1 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Random as ( String newName1 ) { this . $ . setName ( newName1 ) ; return this ; } } public ExOperatorFactory . Random random ( Source < Ex1 > model ) { return new ExOperatorFactory . Random ( model ) ; } public static final class Error implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Error ( Source < Ex1 > model ) { OperatorDescription . Builder builder2 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Update . class ) ; builder2 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder2 . declareParameter ( Ex1 . class ) ; builder2 . addInput ( "" , model ) ; builder2 . addOutput ( "" , model ) ; builder2 . addAttribute ( ObservationCount . AT_LEAST_ONCE ) ; this . $ = builder2 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Error as ( String newName2 ) { this . $ . setName ( newName2 ) ; return this ; } } public ExOperatorFactory . Error error ( Source < Ex1 > model ) { return new ExOperatorFactory . Error ( model ) ; } public static final class Logging implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > out ; Logging ( Source < Ex1 > ex1 ) { OperatorDescription . Builder builder3 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Logging . class ) ; builder3 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder3 . declareParameter ( Ex1 . class ) ; builder3 . addInput ( "" , ex1 ) ; builder3 . addOutput ( "" , ex1 ) ; builder3 . addAttribute ( ObservationCount . AT_LEAST_ONCE ) ; builder3 . addAttribute ( Connectivity . OPTIONAL ) ; builder3 . addAttribute ( com . asakusafw . vocabulary . operator . Logging . Level . INFO ) ; this . $ = builder3 . toResolver ( ) ; this . $ . resolveInput ( "" , ex1 ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Logging as ( String newName3 ) { this . $ . setName ( newName3 ) ; return this ; } } public ExOperatorFactory . Logging logging ( Source < Ex1 > ex1 ) { return new ExOperatorFactory . Logging ( ex1 ) ; } public static final class Branch implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > yes ; public final Source < Ex1 > no ; public final Source < Ex1 > cancel ; Branch ( Source < Ex1 > model ) { OperatorDescription . Builder builder4 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Branch . class ) ; builder4 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder4 . declareParameter ( Ex1 . class ) ; builder4 . addInput ( "" , model ) ; builder4 . addOutput ( "" , model ) ; builder4 . addOutput ( "" , model ) ; builder4 . addOutput ( "" , model ) ; builder4 . addAttribute ( ObservationCount . DONT_CARE ) ; this . $ = builder4 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . yes = this . $ . resolveOutput ( "" ) ; this . no = this . $ . resolveOutput ( "" ) ; this . cancel = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Branch as ( String newName4 ) { this . $ . setName ( newName4 ) ; return this ; } } public ExOperatorFactory . Branch branch ( Source < Ex1 > model ) { return new ExOperatorFactory . Branch ( model ) ; } public static final class CogroupAdd implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > result ; CogroupAdd ( Source < Ex1 > list ) { OperatorDescription . Builder builder5 = new OperatorDescription . Builder ( CoGroup . class ) ; builder5 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder5 . declareParameter ( List . class ) ; builder5 . declareParameter ( Result . class ) ; builder5 . addInput ( "" , list , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . ASC ) } ) ) ) ; builder5 . addOutput ( "" , Ex1 . class ) ; builder5 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder5 . addAttribute ( ObservationCount . DONT_CARE ) ; builder5 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder5 . toResolver ( ) ; this . $ . resolveInput ( "" , list ) ; this . result = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . CogroupAdd as ( String newName5 ) { this . $ . setName ( newName5 ) ; return this ; } } public ExOperatorFactory . CogroupAdd cogroupAdd ( Source < Ex1 > list ) { return new ExOperatorFactory . CogroupAdd ( list ) ; } public static final class Cogroup implements Operator { private final FlowElementResolver $ ; public final Source < Ex1 > r1 ; public final Source < Ex2 > r2 ; Cogroup ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { OperatorDescription . Builder builder6 = new OperatorDescription . Builder ( CoGroup . class ) ; builder6 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder6 . declareParameter ( List . class ) ; builder6 . declareParameter ( List . class ) ; builder6 . declareParameter ( Result . class ) ; builder6 . declareParameter ( Result . class ) ; builder6 . addInput ( "" , ex1 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . ASC ) } ) ) ) ; builder6 . addInput ( "" , ex2 , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { new ShuffleKey . Order ( "" , ShuffleKey . Direction . DESC ) } ) ) ) ; builder6 . addOutput ( "" , Ex1 . class ) ; builder6 . addOutput ( "" , Ex2 . class ) ; builder6 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder6 . addAttribute ( ObservationCount . DONT_CARE ) ; builder6 . addAttribute ( InputBuffer . EXPAND ) ; this . $ = builder6 . toResolver ( ) ; this . $ . resolveInput ( "" , ex1 ) ; this . $ . resolveInput ( "" , ex2 ) ; this . r1 = this . $ . resolveOutput ( "" ) ; this . r2 = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Cogroup as ( String newName6 ) { this . $ . setName ( newName6 ) ; return this ; } } public ExOperatorFactory . Cogroup cogroup ( Source < Ex1 > ex1 , Source < Ex2 > ex2 ) { return new ExOperatorFactory . Cogroup ( ex1 , ex2 ) ; } public static final class Summarize implements Operator { private final FlowElementResolver $ ; public final Source < ExSummarized > out ; Summarize ( Source < Ex1 > model ) { OperatorDescription . Builder builder7 = new OperatorDescription . Builder ( com . asakusafw . vocabulary . operator . Summarize . class ) ; builder7 . declare ( ExOperator . class , ExOperatorImpl . class , "" ) ; builder7 . declareParameter ( Ex1 . class ) ; builder7 . addInput ( "" , model , new ShuffleKey ( Arrays . asList ( new String [ ] { "" } ) , Arrays . asList ( new ShuffleKey . Order [ ] { } ) ) ) ; builder7 . addOutput ( "" , ExSummarized . class ) ; builder7 . addAttribute ( FlowBoundary . SHUFFLE ) ; builder7 . addAttribute ( ObservationCount . DONT_CARE ) ; builder7 . addAttribute ( PartialAggregation . DEFAULT ) ; this . $ = builder7 . toResolver ( ) ; this . $ . resolveInput ( "" , model ) ; this . out = this . $ . resolveOutput ( "" ) ; } public ExOperatorFactory . Summarize as ( String newName7 ) { this . $ . setName ( newName7 ) ; return this ; } } public ExOperatorFactory . Summarize summarize ( Source < Ex1 > model ) { return new ExOperatorFactory . Summarize ( model ) ; } } package com . asakusafw . compiler . fileio ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Comparator ; import java . util . List ; import java . util . jar . JarFile ; import org . junit . Assume ; import org . junit . BeforeClass ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TestWatcher ; import org . junit . runner . Description ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . fileio . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . fileio . flow . IndependentOutExporterDesc ; import com . asakusafw . compiler . fileio . flow . IndependentOutputJob ; import com . asakusafw . compiler . fileio . flow . InvalidFileNameOutputJob ; import com . asakusafw . compiler . fileio . flow . MissingPathOutputJob ; import com . asakusafw . compiler . fileio . flow . MixedInputJob ; import com . asakusafw . compiler . fileio . flow . MultipleOutputJob ; import com . asakusafw . compiler . fileio . flow . NestedOutExporterDesc ; import com . asakusafw . compiler . fileio . flow . NestedOutputJob ; import com . asakusafw . compiler . fileio . flow . NormalInputJob ; import com . asakusafw . compiler . fileio . flow . Out1ExporterDesc ; import com . asakusafw . compiler . fileio . flow . Out2ExporterDesc ; import com . asakusafw . compiler . fileio . flow . Out3ExporterDesc ; import com . asakusafw . compiler . fileio . flow . Out4ExporterDesc ; import com . asakusafw . compiler . fileio . flow . RootOutputJob ; import com . asakusafw . compiler . fileio . flow . SingleOutputJob ; import com . asakusafw . compiler . fileio . flow . SingularOutputJob ; import com . asakusafw . compiler . fileio . flow . TinyInputJob ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . model . Ex2 ; import com . asakusafw . compiler . flow . FlowCompilerOptions . GenericOptionValue ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class HadoopFileIoProcessorTest { static final Logger LOG = LoggerFactory . getLogger ( HadoopFileIoProcessorTest . class ) ; static volatile boolean enableOutput = false ; @ Rule public final CompilerTester tester = new CompilerTester ( ) ; @ Rule public final TestWatcher check = new TestWatcher ( ) { @ Override protected void starting ( Description description ) { Assume . assumeTrue ( description . getMethodName ( ) . startsWith ( "" ) == false || enableOutput ) ; } } ; @ BeforeClass public static void checkHadoop ( ) { enableOutput = hasMapreduce370 ( ) ; } private static boolean hasMapreduce370 ( ) { try { File corelib = findHadoopCoreLib ( ) ; if ( corelib != null ) { String classFile = "" ; LOG . debug ( "" ) ; JarFile jar = new JarFile ( corelib ) ; try { boolean found = jar . getJarEntry ( classFile ) != null ; LOG . debug ( "" , found ) ; return found ; } finally { jar . close ( ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } return false ; } private static File findHadoopCoreLib ( ) { String hadoop = System . getenv ( "" ) ; if ( hadoop != null ) { File home = new File ( hadoop ) ; for ( File file : home . listFiles ( ) ) { String name = file . getName ( ) ; if ( name . startsWith ( "" ) && name . endsWith ( "" ) ) { LOG . debug ( "" , file . getAbsoluteFile ( ) ) ; return file ; } } } LOG . debug ( "" ) ; return null ; } @ Test public void validate ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; tester . compileJobflow ( SingleOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_invalid_compiler_option ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , "" ) ; tester . compileJobflow ( SingleOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_missing_path ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; tester . compileJobflow ( MissingPathOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_inavalid_file_name ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; tester . compileJobflow ( InvalidFileNameOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_singular_file ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; tester . compileJobflow ( SingularOutputJob . class ) ; } @ Test ( expected = IOException . class ) public void validate_root ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; tester . compileJobflow ( RootOutputJob . class ) ; } @ Test public void input_single ( ) throws Exception { JobflowInfo info = tester . compileJobflow ( NormalInputJob . class ) ; ModelOutput < Ex1 > s10 = tester . openOutput ( Ex1 . class , Location . fromPath ( "" , '' ) ) ; writeEx1 ( s10 , , ) ; ModelOutput < Ex1 > s20 = tester . openOutput ( Ex1 . class , Location . fromPath ( "" , '' ) ) ; writeEx1 ( s20 , , , ) ; ModelOutput < Ex1 > s21 = tester . openOutput ( Ex1 . class , Location . fromPath ( "" , '' ) ) ; writeEx1 ( s21 , , , , ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; checkResults ( , , , , , , , , ) ; } @ Test public void input_tiny ( ) throws Exception { tester . options ( ) . setHashJoinForTiny ( true ) ; JobflowInfo info = tester . compileJobflow ( TinyInputJob . class ) ; ModelOutput < Ex2 > s10 = tester . openOutput ( Ex2 . class , Location . fromPath ( "" , '' ) ) ; writeEx2 ( s10 , , ) ; ModelOutput < Ex2 > s20 = tester . openOutput ( Ex2 . class , Location . fromPath ( "" , '' ) ) ; writeEx2 ( s20 , , , ) ; ModelOutput < Ex2 > s21 = tester . openOutput ( Ex2 . class , Location . fromPath ( "" , '' ) ) ; writeEx2 ( s21 , , , , ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; checkResults ( , , , , , , , , ) ; } @ Test public void input_mixed ( ) throws Exception { tester . options ( ) . setHashJoinForTiny ( true ) ; JobflowInfo info = tester . compileJobflow ( MixedInputJob . class ) ; ModelOutput < Ex1 > s10 = tester . openOutput ( Ex1 . class , Location . fromPath ( "" , '' ) ) ; writeEx1 ( s10 , , ) ; ModelOutput < Ex1 > s20 = tester . openOutput ( Ex1 . class , Location . fromPath ( "" , '' ) ) ; writeEx1 ( s20 , , ) ; ModelOutput < Ex2 > t10 = tester . openOutput ( Ex2 . class , Location . fromPath ( "" , '' ) ) ; writeEx2 ( t10 , , ) ; ModelOutput < Ex2 > t20 = tester . openOutput ( Ex2 . class , Location . fromPath ( "" , '' ) ) ; writeEx2 ( t20 , , ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; checkResults ( , , , , , , , ) ; } private void writeEx1 ( ModelOutput < Ex1 > output , int ... sids ) throws IOException { try { Ex1 value = new Ex1 ( ) ; for ( int sid : sids ) { value . setSid ( sid ) ; value . setValue ( sid ) ; value . setStringAsString ( String . valueOf ( sid ) ) ; output . write ( value ) ; } } finally { output . close ( ) ; } } private void writeEx2 ( ModelOutput < Ex2 > output , int ... sids ) throws IOException { try { Ex2 value = new Ex2 ( ) ; for ( int sid : sids ) { value . setSid ( sid ) ; value . setValue ( sid ) ; value . setStringAsString ( String . valueOf ( sid ) ) ; output . write ( value ) ; } } finally { output . close ( ) ; } } private void checkResults ( int ... sids ) { List < Ex1 > list ; try { Ex1MockExporterDescription instance = new Ex1MockExporterDescription ( ) ; list = tester . getList ( Ex1 . class , Location . fromPath ( instance . getPathPrefix ( ) , '' ) , new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } assertThat ( list . size ( ) , is ( sids . length ) ) ; for ( int i = ; i < sids . length ; i ++ ) { assertThat ( list . get ( i ) . getSid ( ) , is ( ( long ) sids [ i ] ) ) ; } } @ Test ( expected = IOException . class ) public void mapreduce_370 ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . DISABLED . getSymbol ( ) ) ; tester . compileJobflow ( SingleOutputJob . class ) ; } @ Test public void output_single ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; JobflowInfo info = tester . compileJobflow ( SingleOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; } @ Test public void output_multiple ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; JobflowInfo info = tester . compileJobflow ( MultipleOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( Out2ExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; List < Ex1 > out3 = getList ( Out3ExporterDesc . class ) ; checkSids ( out3 ) ; checlValues ( out3 , ) ; List < Ex1 > out4 = getList ( Out4ExporterDesc . class ) ; checkSids ( out4 ) ; checlValues ( out4 , ) ; } @ Test public void output_independent ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; JobflowInfo info = tester . compileJobflow ( IndependentOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( IndependentOutExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; } @ Test public void output_nested ( ) throws Exception { tester . options ( ) . putExtraAttribute ( HadoopFileIoProcessor . OPTION_EXPORTER_ENABLED , GenericOptionValue . ENABLED . getSymbol ( ) ) ; JobflowInfo info = tester . compileJobflow ( NestedOutputJob . class ) ; ModelOutput < Ex1 > source = tester . openOutput ( Ex1 . class , tester . getImporter ( info , "" ) ) ; writeTestData ( source ) ; source . close ( ) ; assertThat ( tester . run ( info ) , is ( true ) ) ; List < Ex1 > out1 = getList ( Out1ExporterDesc . class ) ; checkSids ( out1 ) ; checlValues ( out1 , ) ; List < Ex1 > out2 = getList ( NestedOutExporterDesc . class ) ; checkSids ( out2 ) ; checlValues ( out2 , ) ; } private void checkSids ( List < Ex1 > results ) { assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( ) . getSidOption ( ) . isNull ( ) , is ( true ) ) ; for ( int i = ; i < ; i ++ ) { assertThat ( results . get ( i ) . getSid ( ) , is ( ( long ) i ) ) ; } } private void checlValues ( List < Ex1 > results , int value ) { for ( Ex1 ex1 : results ) { assertThat ( ex1 . getValueOption ( ) , is ( new IntOption ( value ) ) ) ; } } private void writeTestData ( ModelOutput < Ex1 > source ) throws IOException { Ex1 value = new Ex1 ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; value . setSid ( ) ; source . write ( value ) ; } private List < Ex1 > getList ( Class < ? extends FileExporterDescription > exporter ) { try { FileExporterDescription instance = exporter . newInstance ( ) ; return tester . getList ( Ex1 . class , Location . fromPath ( instance . getPathPrefix ( ) , '' ) , new Comparator < Ex1 > ( ) { @ Override public int compare ( Ex1 o1 , Ex1 o2 ) { return o1 . getSidOption ( ) . compareTo ( o2 . getSidOption ( ) ) ; } } ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class RootOutputExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class Out3ExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class IndependentOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; private final Out < Ex1 > independent ; public IndependentOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Out1ExporterDesc . class ) Out < Ex1 > output , @ Export ( name = "" , description = IndependentOutExporterDesc . class ) Out < Ex1 > independent ) { this . input = input ; this . output = output ; this . independent = independent ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result1 = op . update ( input , ) ; output . add ( result1 . out ) ; Update result2 = op . update ( input , ) ; independent . add ( result2 . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SingularOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public SingularOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = SingularOutputExporterDesc . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . model . Ex2 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . flow . util . CoreOperatorFactory ; @ JobFlow ( name = "" ) public class TinyInputJob extends FlowDescription { private final In < Ex2 > input ; private final Out < Ex1 > output ; public TinyInputJob ( @ Import ( name = "" , description = TinyImporterDescription . class ) In < Ex2 > input , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( new CoreOperatorFactory ( ) . restructure ( input , Ex1 . class ) , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class NestedOutExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class SingleOutputJob extends FlowDescription { private In < Ex1 > input ; private Out < Ex1 > output1 ; public SingleOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Out1ExporterDesc . class ) Out < Ex1 > output1 ) { this . input = input ; this . output1 = output1 ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output1 . add ( result . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class SingularOutputExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MissingPathOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public MissingPathOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = MissingPathExporterDesc . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MultipleOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output1 ; private final Out < Ex1 > output2 ; private final Out < Ex1 > output3 ; private final Out < Ex1 > output4 ; public MultipleOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Out1ExporterDesc . class ) Out < Ex1 > output1 , @ Export ( name = "" , description = Out2ExporterDesc . class ) Out < Ex1 > output2 , @ Export ( name = "" , description = Out3ExporterDesc . class ) Out < Ex1 > output3 , @ Export ( name = "" , description = Out4ExporterDesc . class ) Out < Ex1 > output4 ) { this . input = input ; this . output1 = output1 ; this . output2 = output2 ; this . output3 = output3 ; this . output4 = output4 ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result1 = op . update ( input , ) ; output1 . add ( result1 . out ) ; Update result2 = op . update ( input , ) ; output2 . add ( result2 . out ) ; Update result3 = op . update ( input , ) ; output3 . add ( result3 . out ) ; Update result4 = op . update ( input , ) ; output4 . add ( result4 . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class InvalidFileNameOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public InvalidFileNameOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = InvalidFileNameExporterDesc . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class NestedOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; private final Out < Ex1 > nested ; public NestedOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Out1ExporterDesc . class ) Out < Ex1 > output , @ Export ( name = "" , description = NestedOutExporterDesc . class ) Out < Ex1 > nested ) { this . input = input ; this . output = output ; this . nested = nested ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result1 = op . update ( input , ) ; output . add ( result1 . out ) ; Update result2 = op . update ( input , ) ; nested . add ( result2 . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class InvalidFileNameExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class NormalInputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public NormalInputJob ( @ Import ( name = "" , description = NormalImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . external . Ex1MockImporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory ; import com . asakusafw . compiler . fileio . operator . ExOperatorFactory . Update ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class RootOutputJob extends FlowDescription { private final In < Ex1 > input ; private final Out < Ex1 > output ; public RootOutputJob ( @ Import ( name = "" , description = Ex1MockImporterDescription . class ) In < Ex1 > input , @ Export ( name = "" , description = RootOutputExporterDesc . class ) Out < Ex1 > output ) { this . input = input ; this . output = output ; } @ Override protected void describe ( ) { ExOperatorFactory op = new ExOperatorFactory ( ) ; Update result = op . update ( input , ) ; output . add ( result . out ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class Out2ExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class IndependentOutExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . flow ; import static com . asakusafw . vocabulary . flow . util . CoreOperators . * ; import com . asakusafw . compiler . fileio . external . Ex1MockExporterDescription ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . compiler . fileio . model . Ex2 ; import com . asakusafw . vocabulary . flow . Export ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . Import ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . JobFlow ; import com . asakusafw . vocabulary . flow . Out ; @ JobFlow ( name = "" ) public class MixedInputJob extends FlowDescription { private final In < Ex1 > input1 ; private final In < Ex2 > input2 ; private final Out < Ex1 > output ; public MixedInputJob ( @ Import ( name = "" , description = NormalImporterDescription . class ) In < Ex1 > input1 , @ Import ( name = "" , description = TinyImporterDescription . class ) In < Ex2 > input2 , @ Export ( name = "" , description = Ex1MockExporterDescription . class ) Out < Ex1 > output ) { this . input1 = input1 ; this . input2 = input2 ; this . output = output ; } @ Override protected void describe ( ) { output . add ( input1 ) ; output . add ( restructure ( input2 , Ex1 . class ) ) ; } } package com . asakusafw . compiler . fileio . flow ; import java . util . Set ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . external . FileImporterDescription ; public class NormalImporterDescription extends FileImporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public Set < String > getPaths ( ) { return Sets . of ( "" , "" ) ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class MissingPathExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return null ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class Out1ExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . flow ; import java . util . Set ; import com . asakusafw . compiler . fileio . model . Ex2 ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . external . FileImporterDescription ; public class TinyImporterDescription extends FileImporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex2 . class ; } @ Override public Set < String > getPaths ( ) { return Sets . of ( "" , "" ) ; } @ Override public DataSize getDataSize ( ) { return DataSize . TINY ; } } package com . asakusafw . compiler . fileio . flow ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . vocabulary . external . FileExporterDescription ; public class Out4ExporterDesc extends FileExporterDescription { @ Override public Class < ? > getModelType ( ) { return Ex1 . class ; } @ Override public String getPathPrefix ( ) { return "" ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . ExJoinedInput ; import com . asakusafw . compiler . fileio . io . ExJoinedOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; @ DataModelKind ( "" ) @ Joined ( terms = { @ Joined . Term ( source = Ex1 . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) , @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) , @ Joined . Term ( source = Ex2 . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) , @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) } ) @ ModelInputLocation ( ExJoinedInput . class ) @ ModelOutputLocation ( ExJoinedOutput . class ) public class ExJoined implements DataModel < ExJoined > , Writable { private final LongOption sid1 = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; private final LongOption sid2 = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid1 . setNull ( ) ; this . value . setNull ( ) ; this . sid2 . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( ExJoined other ) { this . sid1 . copyFrom ( other . sid1 ) ; this . value . copyFrom ( other . value ) ; this . sid2 . copyFrom ( other . sid2 ) ; } public long getSid1 ( ) { return this . sid1 . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid1 ( long value0 ) { this . sid1 . modify ( value0 ) ; } public LongOption getSid1Option ( ) { return this . sid1 ; } @ SuppressWarnings ( "" ) public void setSid1Option ( LongOption option ) { this . sid1 . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } public long getSid2 ( ) { return this . sid2 . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid2 ( long value0 ) { this . sid2 . modify ( value0 ) ; } public LongOption getSid2Option ( ) { return this . sid2 ; } @ SuppressWarnings ( "" ) public void setSid2Option ( LongOption option ) { this . sid2 . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid1 ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . sid2 ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid1 . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + sid2 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExJoined other = ( ExJoined ) obj ; if ( this . sid1 . equals ( other . sid1 ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . sid2 . equals ( other . sid2 ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { sid1 . write ( out ) ; value . write ( out ) ; sid2 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid1 . readFields ( in ) ; value . readFields ( in ) ; sid2 . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . Part1Input ; import com . asakusafw . compiler . fileio . io . Part1Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Part1Input . class ) @ ModelOutputLocation ( Part1Output . class ) public class Part1 implements DataModel < Part1 > , Writable { private final LongOption sid = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Part1 other ) { this . sid . copyFrom ( other . sid ) ; this . value . copyFrom ( other . value ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value0 ) { this . sid . modify ( value0 ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Part1 other = ( Part1 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; value . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . ExJoined2Input ; import com . asakusafw . compiler . fileio . io . ExJoined2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . vocabulary . model . Joined ; import com . asakusafw . vocabulary . model . Key ; @ DataModelKind ( "" ) @ Joined ( terms = { @ Joined . Term ( source = Ex1 . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) , @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) , @ Joined . Term ( source = Ex2 . class , mappings = { @ Joined . Mapping ( source = "" , destination = "" ) , @ Joined . Mapping ( source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) } ) @ ModelInputLocation ( ExJoined2Input . class ) @ ModelOutputLocation ( ExJoined2Output . class ) public class ExJoined2 implements DataModel < ExJoined2 > , Writable { private final LongOption sid1 = new LongOption ( ) ; private final IntOption key = new IntOption ( ) ; private final LongOption sid2 = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid1 . setNull ( ) ; this . key . setNull ( ) ; this . sid2 . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( ExJoined2 other ) { this . sid1 . copyFrom ( other . sid1 ) ; this . key . copyFrom ( other . key ) ; this . sid2 . copyFrom ( other . sid2 ) ; } public long getSid1 ( ) { return this . sid1 . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid1 ( long value ) { this . sid1 . modify ( value ) ; } public LongOption getSid1Option ( ) { return this . sid1 ; } @ SuppressWarnings ( "" ) public void setSid1Option ( LongOption option ) { this . sid1 . copyFrom ( option ) ; } public int getKey ( ) { return this . key . get ( ) ; } @ SuppressWarnings ( "" ) public void setKey ( int value ) { this . key . modify ( value ) ; } public IntOption getKeyOption ( ) { return this . key ; } @ SuppressWarnings ( "" ) public void setKeyOption ( IntOption option ) { this . key . copyFrom ( option ) ; } public long getSid2 ( ) { return this . sid2 . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid2 ( long value ) { this . sid2 . modify ( value ) ; } public LongOption getSid2Option ( ) { return this . sid2 ; } @ SuppressWarnings ( "" ) public void setSid2Option ( LongOption option ) { this . sid2 . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid1 ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . sid2 ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid1 . hashCode ( ) ; result = prime * result + key . hashCode ( ) ; result = prime * result + sid2 . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExJoined2 other = ( ExJoined2 ) obj ; if ( this . sid1 . equals ( other . sid1 ) == false ) { return false ; } if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . sid2 . equals ( other . sid2 ) == false ) { return false ; } return true ; } @ Override public void write ( DataOutput out ) throws IOException { sid1 . write ( out ) ; key . write ( out ) ; sid2 . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid1 . readFields ( in ) ; key . readFields ( in ) ; sid2 . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . Ex2Input ; import com . asakusafw . compiler . fileio . io . Ex2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Ex2Input . class ) @ ModelOutputLocation ( Ex2Output . class ) public class Ex2 implements DataModel < Ex2 > , Writable { private final LongOption sid = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; private final StringOption string = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . value . setNull ( ) ; this . string . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Ex2 other ) { this . sid . copyFrom ( other . sid ) ; this . value . copyFrom ( other . value ) ; this . string . copyFrom ( other . string ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value0 ) { this . sid . modify ( value0 ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value0 ) { this . string . modify ( value0 ) ; } public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + string . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Ex2 other = ( Ex2 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . string . equals ( other . string ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; value . write ( out ) ; string . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; value . readFields ( in ) ; string . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . Ex1Input ; import com . asakusafw . compiler . fileio . io . Ex1Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Ex1Input . class ) @ ModelOutputLocation ( Ex1Output . class ) public class Ex1 implements DataModel < Ex1 > , Writable { private final LongOption sid = new LongOption ( ) ; private final IntOption value = new IntOption ( ) ; private final StringOption string = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . value . setNull ( ) ; this . string . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Ex1 other ) { this . sid . copyFrom ( other . sid ) ; this . value . copyFrom ( other . value ) ; this . string . copyFrom ( other . string ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value0 ) { this . sid . modify ( value0 ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public int getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( int value0 ) { this . value . modify ( value0 ) ; } public IntOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( IntOption option ) { this . value . copyFrom ( option ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value0 ) { this . string . modify ( value0 ) ; } public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + string . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Ex1 other = ( Ex1 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . string . equals ( other . string ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; value . write ( out ) ; string . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; value . readFields ( in ) ; string . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . ExSummarizedInput ; import com . asakusafw . compiler . fileio . io . ExSummarizedOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; @ DataModelKind ( "" ) @ ModelInputLocation ( ExSummarizedInput . class ) @ ModelOutputLocation ( ExSummarizedOutput . class ) @ Summarized ( term = @ Summarized . Term ( source = Ex1 . class , foldings = { @ Summarized . Folding ( aggregator = Summarized . Aggregator . ANY , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . SUM , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . COUNT , source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) ) public class ExSummarized implements DataModel < ExSummarized > , Writable { private final StringOption string = new StringOption ( ) ; private final LongOption value = new LongOption ( ) ; private final LongOption count = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . string . setNull ( ) ; this . value . setNull ( ) ; this . count . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( ExSummarized other ) { this . string . copyFrom ( other . string ) ; this . value . copyFrom ( other . value ) ; this . count . copyFrom ( other . count ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value0 ) { this . string . modify ( value0 ) ; } public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } public long getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( long value0 ) { this . value . modify ( value0 ) ; } public LongOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( LongOption option ) { this . value . copyFrom ( option ) ; } public long getCount ( ) { return this . count . get ( ) ; } @ SuppressWarnings ( "" ) public void setCount ( long value0 ) { this . count . modify ( value0 ) ; } public LongOption getCountOption ( ) { return this . count ; } @ SuppressWarnings ( "" ) public void setCountOption ( LongOption option ) { this . count . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . count ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + string . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + count . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExSummarized other = ( ExSummarized ) obj ; if ( this . string . equals ( other . string ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . count . equals ( other . count ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { string . write ( out ) ; value . write ( out ) ; count . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { string . readFields ( in ) ; value . readFields ( in ) ; count . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . Part2Input ; import com . asakusafw . compiler . fileio . io . Part2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( Part2Input . class ) @ ModelOutputLocation ( Part2Output . class ) public class Part2 implements DataModel < Part2 > , Writable { private final LongOption sid = new LongOption ( ) ; private final StringOption string = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . sid . setNull ( ) ; this . string . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Part2 other ) { this . sid . copyFrom ( other . sid ) ; this . string . copyFrom ( other . string ) ; } public long getSid ( ) { return this . sid . get ( ) ; } @ SuppressWarnings ( "" ) public void setSid ( long value ) { this . sid . modify ( value ) ; } public LongOption getSidOption ( ) { return this . sid ; } @ SuppressWarnings ( "" ) public void setSidOption ( LongOption option ) { this . sid . copyFrom ( option ) ; } public Text getString ( ) { return this . string . get ( ) ; } @ SuppressWarnings ( "" ) public void setString ( Text value ) { this . string . modify ( value ) ; } public StringOption getStringOption ( ) { return this . string ; } @ SuppressWarnings ( "" ) public void setStringOption ( StringOption option ) { this . string . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . sid ) ; result . append ( "" ) ; result . append ( this . string ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + sid . hashCode ( ) ; result = prime * result + string . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Part2 other = ( Part2 ) obj ; if ( this . sid . equals ( other . sid ) == false ) { return false ; } if ( this . string . equals ( other . string ) == false ) { return false ; } return true ; } public String getStringAsString ( ) { return this . string . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setStringAsString ( String string0 ) { this . string . modify ( string0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { sid . write ( out ) ; string . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { sid . readFields ( in ) ; string . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . ExSummarized2Input ; import com . asakusafw . compiler . fileio . io . ExSummarized2Output ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; @ DataModelKind ( "" ) @ ModelInputLocation ( ExSummarized2Input . class ) @ ModelOutputLocation ( ExSummarized2Output . class ) @ Summarized ( term = @ Summarized . Term ( source = Ex1 . class , foldings = { @ Summarized . Folding ( aggregator = Summarized . Aggregator . ANY , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . SUM , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . COUNT , source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) ) public class ExSummarized2 implements DataModel < ExSummarized2 > , Writable { private final StringOption key = new StringOption ( ) ; private final LongOption value = new LongOption ( ) ; private final LongOption count = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . key . setNull ( ) ; this . value . setNull ( ) ; this . count . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( ExSummarized2 other ) { this . key . copyFrom ( other . key ) ; this . value . copyFrom ( other . value ) ; this . count . copyFrom ( other . count ) ; } public Text getKey ( ) { return this . key . get ( ) ; } @ SuppressWarnings ( "" ) public void setKey ( Text value0 ) { this . key . modify ( value0 ) ; } public StringOption getKeyOption ( ) { return this . key ; } @ SuppressWarnings ( "" ) public void setKeyOption ( StringOption option ) { this . key . copyFrom ( option ) ; } public long getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( long value0 ) { this . value . modify ( value0 ) ; } public LongOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( LongOption option ) { this . value . copyFrom ( option ) ; } public long getCount ( ) { return this . count . get ( ) ; } @ SuppressWarnings ( "" ) public void setCount ( long value0 ) { this . count . modify ( value0 ) ; } public LongOption getCountOption ( ) { return this . count ; } @ SuppressWarnings ( "" ) public void setCountOption ( LongOption option ) { this . count . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; result . append ( this . count ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + key . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; result = prime * result + count . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } ExSummarized2 other = ( ExSummarized2 ) obj ; if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } if ( this . count . equals ( other . count ) == false ) { return false ; } return true ; } public String getKeyAsString ( ) { return this . key . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setKeyAsString ( String key0 ) { this . key . modify ( key0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; value . write ( out ) ; count . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { key . readFields ( in ) ; value . readFields ( in ) ; count . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . fileio . io . KeyConflictInput ; import com . asakusafw . compiler . fileio . io . KeyConflictOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Key ; import com . asakusafw . vocabulary . model . Summarized ; @ DataModelKind ( "" ) @ ModelInputLocation ( KeyConflictInput . class ) @ ModelOutputLocation ( KeyConflictOutput . class ) @ Summarized ( term = @ Summarized . Term ( source = Ex1 . class , foldings = { @ Summarized . Folding ( aggregator = Summarized . Aggregator . ANY , source = "" , destination = "" ) , @ Summarized . Folding ( aggregator = Summarized . Aggregator . COUNT , source = "" , destination = "" ) } , shuffle = @ Key ( group = { "" } ) ) ) public class KeyConflict implements DataModel < KeyConflict > , Writable { private final StringOption key = new StringOption ( ) ; private final LongOption count = new LongOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . key . setNull ( ) ; this . count . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( KeyConflict other ) { this . key . copyFrom ( other . key ) ; this . count . copyFrom ( other . count ) ; } public Text getKey ( ) { return this . key . get ( ) ; } @ SuppressWarnings ( "" ) public void setKey ( Text value ) { this . key . modify ( value ) ; } public StringOption getKeyOption ( ) { return this . key ; } @ SuppressWarnings ( "" ) public void setKeyOption ( StringOption option ) { this . key . copyFrom ( option ) ; } public long getCount ( ) { return this . count . get ( ) ; } @ SuppressWarnings ( "" ) public void setCount ( long value ) { this . count . modify ( value ) ; } public LongOption getCountOption ( ) { return this . count ; } @ SuppressWarnings ( "" ) public void setCountOption ( LongOption option ) { this . count . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . count ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + key . hashCode ( ) ; result = prime * result + count . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } KeyConflict other = ( KeyConflict ) obj ; if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . count . equals ( other . count ) == false ) { return false ; } return true ; } public String getKeyAsString ( ) { return this . key . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setKeyAsString ( String key0 ) { this . key . modify ( key0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; count . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { key . readFields ( in ) ; count . readFields ( in ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . ExSummarized2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class ExSummarized2Output implements ModelOutput < ExSummarized2 > { private final RecordEmitter emitter ; public ExSummarized2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExSummarized2 model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getCountOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . Part1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Part1Input implements ModelInput < Part1 > { private final RecordParser parser ; public Part1Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Part1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Ex1Input implements ModelInput < Ex1 > { private final RecordParser parser ; public Ex1Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Ex1 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getStringOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . Ex1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Ex1Output implements ModelOutput < Ex1 > { private final RecordEmitter emitter ; public Ex1Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Ex1 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getStringOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . Ex2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Ex2Input implements ModelInput < Ex2 > { private final RecordParser parser ; public Ex2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Ex2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getStringOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . ExJoined2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class ExJoined2Output implements ModelOutput < ExJoined2 > { private final RecordEmitter emitter ; public ExJoined2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExJoined2 model ) throws IOException { emitter . emit ( model . getSid1Option ( ) ) ; emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getSid2Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . ExSummarized ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class ExSummarizedOutput implements ModelOutput < ExSummarized > { private final RecordEmitter emitter ; public ExSummarizedOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExSummarized model ) throws IOException { emitter . emit ( model . getStringOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getCountOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . Ex2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Ex2Output implements ModelOutput < Ex2 > { private final RecordEmitter emitter ; public Ex2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Ex2 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getStringOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . Part2 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Part2Output implements ModelOutput < Part2 > { private final RecordEmitter emitter ; public Part2Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Part2 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getStringOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . ExSummarized2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class ExSummarized2Input implements ModelInput < ExSummarized2 > { private final RecordParser parser ; public ExSummarized2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExSummarized2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getCountOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . ExJoined ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class ExJoinedOutput implements ModelOutput < ExJoined > { private final RecordEmitter emitter ; public ExJoinedOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( ExJoined model ) throws IOException { emitter . emit ( model . getSid1Option ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . emit ( model . getSid2Option ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . ExJoined2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class ExJoined2Input implements ModelInput < ExJoined2 > { private final RecordParser parser ; public ExJoined2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExJoined2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSid1Option ( ) ) ; parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getSid2Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . ExSummarized ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class ExSummarizedInput implements ModelInput < ExSummarized > { private final RecordParser parser ; public ExSummarizedInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExSummarized model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getStringOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getCountOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . KeyConflict ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class KeyConflictInput implements ModelInput < KeyConflict > { private final RecordParser parser ; public KeyConflictInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( KeyConflict model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getCountOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . Part1 ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class Part1Output implements ModelOutput < Part1 > { private final RecordEmitter emitter ; public Part1Output ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Part1 model ) throws IOException { emitter . emit ( model . getSidOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . ExJoined ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class ExJoinedInput implements ModelInput < ExJoined > { private final RecordParser parser ; public ExJoinedInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( ExJoined model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSid1Option ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; parser . fill ( model . getSid2Option ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . Part2 ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class Part2Input implements ModelInput < Part2 > { private final RecordParser parser ; public Part2Input ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Part2 model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getSidOption ( ) ) ; parser . fill ( model . getStringOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . fileio . io ; import java . io . IOException ; import com . asakusafw . compiler . fileio . model . KeyConflict ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class KeyConflictOutput implements ModelOutput < KeyConflict > { private final RecordEmitter emitter ; public KeyConflictOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( KeyConflict model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getCountOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . testtools . db ; import static org . junit . Assert . * ; import java . sql . Connection ; import java . util . ArrayList ; import java . util . List ; import org . junit . Test ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . excel . ExcelUtils ; public class DbUtilTest { @ Test public void testCreateTable01 ( ) throws Exception { String filename = "" ; ExcelUtils excelUtils = new ExcelUtils ( filename ) ; List < ColumnInfo > list = excelUtils . getColumnInfos ( ) ; Connection conn = null ; try { conn = DbUtils . getConnection ( ) ; String tablename = list . get ( ) . getTableName ( ) ; DbUtils . dropTable ( conn , tablename ) ; DbUtils . createTable ( conn , list ) ; } finally { DbUtils . closeQuietly ( conn ) ; } } @ Test ( expected = RuntimeException . class ) public void testCreateTable02 ( ) throws Exception { List < ColumnInfo > list = new ArrayList < ColumnInfo > ( ) ; Connection conn = null ; try { conn = DbUtils . getConnection ( ) ; DbUtils . createTable ( conn , list ) ; } catch ( RuntimeException e ) { assertEquals ( "" , e . getMessage ( ) ) ; throw e ; } finally { DbUtils . closeQuietly ( conn ) ; } } @ Test public void testDropTable ( ) throws Exception { String filename = "" ; ExcelUtils excelUtils = new ExcelUtils ( filename ) ; List < ColumnInfo > list = excelUtils . getColumnInfos ( ) ; Connection conn = null ; try { String tablename = list . get ( ) . getTableName ( ) ; conn = DbUtils . getConnection ( ) ; DbUtils . dropTable ( conn , tablename ) ; DbUtils . createTable ( conn , list ) ; DbUtils . dropTable ( conn , tablename ) ; DbUtils . dropTable ( conn , tablename ) ; } finally { DbUtils . closeQuietly ( conn ) ; } } } package com . asakusafw . testtools . inspect ; import static org . junit . Assert . * ; import org . junit . Test ; import test . modelgen . model . AllTypesWNoerr ; import com . asakusafw . modelgen . source . MySqlDataType ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . NullValueCondition ; import com . asakusafw . testtools . inspect . Cause . Type ; public class CauseTest { private static final String MSG1 = "" ; private static final String MSG2 = "" ; private static AllTypesWNoerr expect = new AllTypesWNoerr ( ) ; private static AllTypesWNoerr actual = new AllTypesWNoerr ( ) ; private static ColumnInfo columnInfo = new ColumnInfo ( "" , "" , "" , MySqlDataType . CHAR , , , , true , false , null , NullValueCondition . NORMAL ) ; private static Cause cause1 = new Cause ( Type . COLUMN_VALUE_MISSMATCH , MSG1 , expect , actual ) ; ; private static Cause cause2 = new Cause ( Type . CONDITION_NOW_ON_INVALID_COLUMN , MSG2 , expect , actual , expect . getCBigintOption ( ) , actual . getCCharOption ( ) , columnInfo ) ; ; @ Test public void testGetType ( ) { assertEquals ( Type . COLUMN_VALUE_MISSMATCH , cause1 . getType ( ) ) ; assertEquals ( Type . CONDITION_NOW_ON_INVALID_COLUMN , cause2 . getType ( ) ) ; } @ Test public void testGetMessage ( ) { assertTrue ( cause1 . getMessage ( ) . contains ( MSG1 ) ) ; assertTrue ( cause2 . getMessage ( ) . contains ( MSG2 ) ) ; } @ Test public void testGetExpect ( ) { assertEquals ( expect , cause1 . getExpect ( ) ) ; assertEquals ( expect , cause2 . getExpect ( ) ) ; } @ Test public void testGetActual ( ) { assertEquals ( actual , cause1 . getActual ( ) ) ; assertEquals ( actual , cause2 . getActual ( ) ) ; } @ Test public void testGetColumnInfo ( ) { assertEquals ( null , cause1 . getColumnInfo ( ) ) ; assertEquals ( columnInfo , cause2 . getColumnInfo ( ) ) ; } @ Test public void testGetActualVal ( ) { assertNull ( cause1 . getActualVal ( ) ) ; assertEquals ( actual . getCCharOption ( ) , cause2 . getActualVal ( ) ) ; } @ Test public void testGetExpectVal ( ) { assertNull ( null , cause1 . getActualVal ( ) ) ; assertEquals ( actual . getCBigintOption ( ) , cause2 . getExpectVal ( ) ) ; } } package com . asakusafw . testtools . inspect ; import static org . junit . Assert . * ; import java . sql . Connection ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import test . modelgen . model . AllTypesWNoerr ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . testtools . RowMatchingCondition ; import com . asakusafw . testtools . TestDataHolder ; import com . asakusafw . testtools . db . DbUtils ; import com . asakusafw . testtools . excel . ExcelUtils ; import com . asakusafw . testtools . inspect . Cause . Type ; public class DefaultInspectorTest { private static final String TEST_FILE = "" ; private static final String TEST_FILE_NULL_NORMAL = "" ; private static final String TEST_FILE_NULL_OK = "" ; private static final String TEST_FILE_NULL_NG = "" ; private static final String TEST_FILE_NOT_NULL_OK = "" ; private static final String TEST_FILE_NOT_NULL_NG = "" ; private static final String TEST_FILE_INSPECT_NONE = "" ; private static final String TEST_FILE_INSPECT_NOW = "" ; private static final String TEST_FILE_INSPECT_TODAY = "" ; private static final String TEST_FILE_INSPECT_PARTIAL = "" ; private static final String TEST_FILE_INSPECT_PARTIAL2 = "" ; private static final int ROWNS_IN_TEST_FILE = ; private TestDataHolder dataHolder ; private void initDataHolder ( String filename ) throws Exception { ExcelUtils excelUtils = new ExcelUtils ( filename ) ; dataHolder = excelUtils . getTestDataHolder ( ) ; Connection conn = null ; try { conn = DbUtils . getConnection ( ) ; dataHolder . storeToDatabase ( conn , true ) ; dataHolder . loadFromDatabase ( conn ) ; } finally { DbUtils . closeQuietly ( conn ) ; } } @ Test public void testNormal ( ) throws Exception { initDataHolder ( TEST_FILE ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; } @ Test public void testNullExcepctList ( ) throws Exception { initDataHolder ( TEST_FILE ) ; List < Writable > expect = dataHolder . getExpect ( ) ; expect . clear ( ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; assertEquals ( "" , ROWNS_IN_TEST_FILE , inspector . getCauses ( ) . size ( ) ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . NO_EXPECT_RECORD , cause . getType ( ) ) ; } dataHolder . setRowMatchingCondition ( RowMatchingCondition . PARTIAL ) ; inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; dataHolder . setRowMatchingCondition ( RowMatchingCondition . PARTIAL ) ; inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; } @ Test public void testNullActualList ( ) throws Exception { initDataHolder ( TEST_FILE ) ; List < Writable > actual = dataHolder . getActual ( ) ; actual . clear ( ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; assertEquals ( "" , ROWNS_IN_TEST_FILE , inspector . getCauses ( ) . size ( ) ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . NO_ACTUAL_RECORD , cause . getType ( ) ) ; } dataHolder . setRowMatchingCondition ( RowMatchingCondition . PARTIAL ) ; inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; assertEquals ( "" , ROWNS_IN_TEST_FILE , inspector . getCauses ( ) . size ( ) ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . NO_ACTUAL_RECORD , cause . getType ( ) ) ; } dataHolder . setRowMatchingCondition ( RowMatchingCondition . NONE ) ; inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; } @ Test public void testDuplicatedRecords ( ) throws Exception { initDataHolder ( TEST_FILE ) ; dataHolder . sort ( ) ; List < Writable > expect = dataHolder . getExpect ( ) ; List < Writable > actual = dataHolder . getActual ( ) ; expect . set ( , expect . get ( ) ) ; actual . set ( , actual . get ( ) ) ; actual . set ( , actual . get ( ) ) ; expect . set ( , expect . get ( ) ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; Set < String > actualTags = new HashSet < String > ( ) ; Set < String > expectTags = new HashSet < String > ( ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; AllTypesWNoerr actualModelObject = ( AllTypesWNoerr ) cause . getActual ( ) ; AllTypesWNoerr expectModelObject = ( AllTypesWNoerr ) cause . getExpect ( ) ; if ( actualModelObject == null ) { assertEquals ( "" , Type . DUPLICATEED_KEY_IN_EXPECT_RECORDS , cause . getType ( ) ) ; assertNotNull ( "" , expectModelObject ) ; expectTags . add ( expectModelObject . getCTagAsString ( ) ) ; } if ( expectModelObject == null ) { assertEquals ( "" , Type . DUPLICATEED_KEY_IN_ACTUALT_RECORDS , cause . getType ( ) ) ; assertNotNull ( "" , actualModelObject ) ; actualTags . add ( actualModelObject . getCTagAsString ( ) ) ; } } assertEquals ( "" , , expectTags . size ( ) ) ; assertEquals ( "" , , actualTags . size ( ) ) ; assertTrue ( "" , expectTags . contains ( ( ( AllTypesWNoerr ) expect . get ( ) ) . getCTagAsString ( ) ) ) ; assertTrue ( "" , expectTags . contains ( ( ( AllTypesWNoerr ) expect . get ( ) ) . getCTagAsString ( ) ) ) ; assertTrue ( "" , actualTags . contains ( ( ( AllTypesWNoerr ) actual . get ( ) ) . getCTagAsString ( ) ) ) ; } @ Test public void testLackOfExpectRecord ( ) throws Exception { initDataHolder ( TEST_FILE ) ; dataHolder . sort ( ) ; List < Writable > expect = dataHolder . getExpect ( ) ; List < String > removedRecordTags = new ArrayList < String > ( ) ; int [ ] removeIndexs = { ( expect . size ( ) - ) , ( expect . size ( ) - ) , , , , , } ; for ( int index : removeIndexs ) { removedRecordTags . add ( ( ( AllTypesWNoerr ) expect . get ( index ) ) . getCTagAsString ( ) ) ; expect . remove ( index ) ; } DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . NO_EXPECT_RECORD , cause . getType ( ) ) ; AllTypesWNoerr model = ( AllTypesWNoerr ) cause . getActual ( ) ; String tag = model . getCTagAsString ( ) ; assertTrue ( "" , removedRecordTags . contains ( tag ) ) ; removedRecordTags . remove ( tag ) ; } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertTrue ( "" , removedRecordTags . size ( ) == ) ; } @ Test public void testLackOfActualRecord ( ) throws Exception { initDataHolder ( TEST_FILE ) ; dataHolder . sort ( ) ; List < Writable > actual = dataHolder . getActual ( ) ; List < String > removedRecordTags = new ArrayList < String > ( ) ; int [ ] removeIndexs = { ( actual . size ( ) - ) , ( actual . size ( ) - ) , , , , , } ; for ( int index : removeIndexs ) { removedRecordTags . add ( ( ( AllTypesWNoerr ) actual . get ( index ) ) . getCTagAsString ( ) ) ; actual . remove ( index ) ; } DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . NO_ACTUAL_RECORD , cause . getType ( ) ) ; AllTypesWNoerr model = ( AllTypesWNoerr ) cause . getExpect ( ) ; String tag = model . getCTagAsString ( ) ; assertTrue ( "" , removedRecordTags . contains ( tag ) ) ; removedRecordTags . remove ( tag ) ; } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertTrue ( "" , removedRecordTags . size ( ) == ) ; } @ Test public void testNullNormal ( ) throws Exception { initDataHolder ( TEST_FILE_NULL_NORMAL ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; Set < String > actualErrorSet = new HashSet < String > ( ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . COLUMN_VALUE_MISSMATCH , cause . getType ( ) ) ; AllTypesWNoerr expect = ( AllTypesWNoerr ) cause . getExpect ( ) ; AllTypesWNoerr actual = ( AllTypesWNoerr ) cause . getActual ( ) ; String ctag = expect . getCTagAsString ( ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; actualErrorSet . add ( ctag + "" + columnName ) ; if ( "" . equals ( ctag ) ) { assertFalse ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertTrue ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } } Set < String > expectErrorSet = new HashSet < String > ( ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; assertTrue ( "" , expectErrorSet . equals ( actualErrorSet ) ) ; } @ Test public void testNullOk ( ) throws Exception { initDataHolder ( TEST_FILE_NULL_OK ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; Set < String > actualErrorSet = new HashSet < String > ( ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . COLUMN_VALUE_MISSMATCH , cause . getType ( ) ) ; AllTypesWNoerr expect = ( AllTypesWNoerr ) cause . getExpect ( ) ; AllTypesWNoerr actual = ( AllTypesWNoerr ) cause . getActual ( ) ; String ctag = expect . getCTagAsString ( ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; actualErrorSet . add ( ctag + "" + columnName ) ; if ( "" . equals ( ctag ) ) { assertFalse ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } } Set < String > expectErrorSet = new HashSet < String > ( ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; assertTrue ( "" , expectErrorSet . equals ( actualErrorSet ) ) ; } @ Test public void testNullNg ( ) throws Exception { initDataHolder ( TEST_FILE_NULL_NG ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; Set < String > actualErrorSet = new HashSet < String > ( ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . COLUMN_VALUE_MISSMATCH , cause . getType ( ) ) ; AllTypesWNoerr expect = ( AllTypesWNoerr ) cause . getExpect ( ) ; AllTypesWNoerr actual = ( AllTypesWNoerr ) cause . getActual ( ) ; String ctag = expect . getCTagAsString ( ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; actualErrorSet . add ( ctag + "" + columnName ) ; if ( "" . equals ( ctag ) ) { assertTrue ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertFalse ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertTrue ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } } Set < String > expectErrorSet = new HashSet < String > ( ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; assertTrue ( "" , expectErrorSet . equals ( actualErrorSet ) ) ; } @ Test public void testNotNullOk ( ) throws Exception { initDataHolder ( TEST_FILE_NOT_NULL_OK ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; Set < String > actualErrorSet = new HashSet < String > ( ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . COLUMN_VALUE_MISSMATCH , cause . getType ( ) ) ; AllTypesWNoerr expect = ( AllTypesWNoerr ) cause . getExpect ( ) ; AllTypesWNoerr actual = ( AllTypesWNoerr ) cause . getActual ( ) ; String ctag = expect . getCTagAsString ( ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; actualErrorSet . add ( ctag + "" + columnName ) ; if ( "" . equals ( ctag ) ) { assertFalse ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertTrue ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertFalse ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertTrue ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } } Set < String > expectErrorSet = new HashSet < String > ( ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; assertTrue ( "" , expectErrorSet . equals ( actualErrorSet ) ) ; } @ Test public void testNotNullNg ( ) throws Exception { initDataHolder ( TEST_FILE_NOT_NULL_NG ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; Set < String > actualErrorSet = new HashSet < String > ( ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . COLUMN_VALUE_MISSMATCH , cause . getType ( ) ) ; AllTypesWNoerr expect = ( AllTypesWNoerr ) cause . getExpect ( ) ; AllTypesWNoerr actual = ( AllTypesWNoerr ) cause . getActual ( ) ; String ctag = expect . getCTagAsString ( ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; actualErrorSet . add ( ctag + "" + columnName ) ; if ( "" . equals ( ctag ) ) { assertFalse ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertTrue ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertFalse ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } else if ( "" . equals ( ctag ) ) { assertTrue ( "" , actual . getCBigintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCIntOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCSmallintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCTinyintOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCCharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCVcharOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDateOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDatetimeOption ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal200Option ( ) . isNull ( ) ) ; assertTrue ( "" , actual . getCDecimal255Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCBigintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCIntOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCSmallintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCTinyintOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCCharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCVcharOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDateOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDatetimeOption ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal200Option ( ) . isNull ( ) ) ; assertFalse ( "" , expect . getCDecimal255Option ( ) . isNull ( ) ) ; } } Set < String > expectErrorSet = new HashSet < String > ( ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; expectErrorSet . add ( "" ) ; assertTrue ( "" , expectErrorSet . equals ( actualErrorSet ) ) ; } @ Test public void tetstInspectNone ( ) throws Exception { initDataHolder ( TEST_FILE_INSPECT_NONE ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } assertTrue ( "" , inspector . isSuccess ( ) ) ; assertTrue ( "" , inspector . getCauses ( ) . size ( ) == ) ; } @ SuppressWarnings ( "" ) @ Test public void testInspectNow ( ) throws Exception { initDataHolder ( TEST_FILE_INSPECT_NOW ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; if ( "" . equals ( columnName ) ) { assertEquals ( "" , Type . NOT_IN_TESTING_TIME , cause . getType ( ) ) ; } else { assertEquals ( "" , Type . CONDITION_NOW_ON_INVALID_COLUMN , cause . getType ( ) ) ; } } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; for ( AllTypesWNoerr model : getActualList ( ) ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int h = cal . get ( Calendar . HOUR_OF_DAY ) ; int min = cal . get ( Calendar . MINUTE ) ; int s = cal . get ( Calendar . SECOND ) ; int days = DateUtil . getDayFromDate ( y , m + , d ) ; int secs = DateUtil . getSecondFromTime ( h , min , s ) ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * + secs ) ; model . getCDatetimeOption ( ) . modify ( dt ) ; Date date = new Date ( ) ; date . setElapsedDays ( days ) ; model . getCDateOption ( ) . modify ( date ) ; } inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { if ( cause . getType ( ) . equals ( Type . NOT_IN_TESTING_TIME ) ) { System . out . println ( cause . getMessage ( ) ) ; } assertEquals ( "" , Type . CONDITION_NOW_ON_INVALID_COLUMN , cause . getType ( ) ) ; } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; for ( AllTypesWNoerr model : getActualList ( ) ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int h = cal . get ( Calendar . HOUR_OF_DAY ) ; int min = cal . get ( Calendar . MINUTE ) ; int s = cal . get ( Calendar . SECOND ) ; int days = DateUtil . getDayFromDate ( y + , m + , d ) ; int secs = DateUtil . getSecondFromTime ( h , min , s ) ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * + secs ) ; model . getCDatetimeOption ( ) . modify ( dt ) ; Date date = new Date ( ) ; date . setElapsedDays ( days ) ; model . getCDateOption ( ) . modify ( date ) ; } inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; if ( "" . equals ( columnName ) ) { assertEquals ( "" , Type . NOT_IN_TESTING_TIME , cause . getType ( ) ) ; } else { assertEquals ( "" , Type . CONDITION_NOW_ON_INVALID_COLUMN , cause . getType ( ) ) ; } } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; } @ SuppressWarnings ( "" ) @ Test public void testInspectToday ( ) throws Exception { initDataHolder ( TEST_FILE_INSPECT_TODAY ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; if ( "" . equals ( columnName ) || "" . equals ( columnName ) ) { assertEquals ( "" , Type . NOT_IN_TEST_DAY , cause . getType ( ) ) ; } else { assertEquals ( "" , Type . CONDITION_TODAY_ON_INVALID_COLUMN , cause . getType ( ) ) ; } } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; for ( AllTypesWNoerr model : getActualList ( ) ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int h = cal . get ( Calendar . HOUR_OF_DAY ) ; int min = cal . get ( Calendar . MINUTE ) ; int s = cal . get ( Calendar . SECOND ) ; int days = DateUtil . getDayFromDate ( y , m + , d ) ; int secs = DateUtil . getSecondFromTime ( h , min , s ) ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * + secs ) ; model . getCDatetimeOption ( ) . modify ( dt ) ; Date date = new Date ( ) ; date . setElapsedDays ( days ) ; model . getCDateOption ( ) . modify ( date ) ; } inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . CONDITION_TODAY_ON_INVALID_COLUMN , cause . getType ( ) ) ; } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; for ( AllTypesWNoerr model : getActualList ( ) ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int days = DateUtil . getDayFromDate ( y , m + , d ) ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * ) ; model . getCDatetimeOption ( ) . modify ( dt ) ; Date date = new Date ( ) ; date . setElapsedDays ( days ) ; model . getCDateOption ( ) . modify ( date ) ; } inspector . clear ( ) ; inspector . setFinishTime ( inspector . getStartTime ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . CONDITION_TODAY_ON_INVALID_COLUMN , cause . getType ( ) ) ; } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; for ( AllTypesWNoerr model : getActualList ( ) ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int days = DateUtil . getDayFromDate ( y , m + , d ) + ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * ) ; model . getCDatetimeOption ( ) . modify ( dt ) ; Date date = new Date ( ) ; date . setElapsedDays ( days ) ; model . getCDateOption ( ) . modify ( date ) ; } inspector . clear ( ) ; inspector . setFinishTime ( inspector . getStartTime ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; if ( "" . equals ( columnName ) || "" . equals ( columnName ) ) { assertEquals ( "" , Type . NOT_IN_TEST_DAY , cause . getType ( ) ) ; } else { assertEquals ( "" , Type . CONDITION_TODAY_ON_INVALID_COLUMN , cause . getType ( ) ) ; } } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; for ( AllTypesWNoerr model : getActualList ( ) ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int days = DateUtil . getDayFromDate ( y , m + , d ) + ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * ) ; model . getCDatetimeOption ( ) . modify ( dt ) ; Date date = new Date ( ) ; date . setElapsedDays ( days ) ; model . getCDateOption ( ) . modify ( date ) ; } inspector . clear ( ) ; inspector . setFinishTime ( inspector . getStartTime ( ) + * ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; if ( "" . equals ( columnName ) || "" . equals ( columnName ) ) { assertEquals ( "" , Type . NOT_IN_TEST_DAY , cause . getType ( ) ) ; } else { assertEquals ( "" , Type . CONDITION_TODAY_ON_INVALID_COLUMN , cause . getType ( ) ) ; } } for ( AllTypesWNoerr model : getActualList ( ) ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int h = cal . get ( Calendar . HOUR_OF_DAY ) ; int min = cal . get ( Calendar . MINUTE ) ; int s = cal . get ( Calendar . SECOND ) ; int days = DateUtil . getDayFromDate ( y + , m + , d ) ; int secs = DateUtil . getSecondFromTime ( h , min , s ) ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * + secs ) ; model . getCDatetimeOption ( ) . modify ( dt ) ; Date date = new Date ( ) ; date . setElapsedDays ( days ) ; model . getCDateOption ( ) . modify ( date ) ; } inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; String columnName = cause . getColumnInfo ( ) . getColumnName ( ) ; if ( "" . equals ( columnName ) || "" . equals ( columnName ) ) { assertEquals ( "" , Type . NOT_IN_TEST_DAY , cause . getType ( ) ) ; } else { assertEquals ( "" , Type . CONDITION_TODAY_ON_INVALID_COLUMN , cause . getType ( ) ) ; } } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; for ( AllTypesWNoerr model : getActualList ( ) ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int days = DateUtil . getDayFromDate ( y , m + , d ) ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * ) ; model . getCDatetimeOption ( ) . modify ( dt ) ; Date date = new Date ( ) ; date . setElapsedDays ( days ) ; model . getCDateOption ( ) . modify ( date ) ; } inspector . clear ( ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; assertEquals ( "" , Type . CONDITION_TODAY_ON_INVALID_COLUMN , cause . getType ( ) ) ; } assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; assertFalse ( "" , inspector . isSuccess ( ) ) ; } @ Test public void tetstInspectPartial ( ) throws Exception { initDataHolder ( TEST_FILE_INSPECT_PARTIAL ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; if ( cause . getColumnInfo ( ) . getColumnName ( ) . equals ( "" ) || cause . getColumnInfo ( ) . getColumnName ( ) . equals ( "" ) ) { assertEquals ( "" , Type . COLUMN_VALUE_MISSMATCH , cause . getType ( ) ) ; } else { assertEquals ( "" , Type . CONDITION_PARTIAL_ON_INVALID_COLUMN , cause . getType ( ) ) ; } } assertFalse ( "" , inspector . isSuccess ( ) ) ; assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; } @ Test public void tetstInspectPartial2 ( ) throws Exception { initDataHolder ( TEST_FILE_INSPECT_PARTIAL2 ) ; DefaultInspector inspector = new DefaultInspector ( ) ; inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; for ( Cause cause : inspector . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; if ( cause . getColumnInfo ( ) . getColumnName ( ) . equals ( "" ) || cause . getColumnInfo ( ) . getColumnName ( ) . equals ( "" ) ) { assertEquals ( "" , Type . COLUMN_VALUE_MISSMATCH , cause . getType ( ) ) ; AllTypesWNoerr model = ( AllTypesWNoerr ) cause . getActual ( ) ; int tagNo = Integer . parseInt ( model . getCTagAsString ( ) ) ; assertTrue ( "" , ( <= tagNo && tagNo <= ) ) ; } else { fail ( "" ) ; } } assertFalse ( "" , inspector . isSuccess ( ) ) ; assertEquals ( "" , , inspector . getCauses ( ) . size ( ) ) ; } private List < AllTypesWNoerr > getActualList ( ) { List < AllTypesWNoerr > list = new ArrayList < AllTypesWNoerr > ( ) ; for ( Writable model : dataHolder . getActual ( ) ) { list . add ( ( AllTypesWNoerr ) model ) ; } return list ; } } package com . asakusafw . testtools ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . Assert ; import org . junit . Test ; import test . inspector . SuccessInspector ; import com . asakusafw . testtools . inspect . Cause ; public class TestUtilsTest { @ Test public void testNormal ( ) throws Exception { String TEST_FILE = "" ; File testFile = new File ( TEST_FILE ) ; List < File > testFileList = new ArrayList < File > ( ) ; testFileList . add ( testFile ) ; TestUtils testUtils = new TestUtils ( testFileList ) ; testUtils . storeToDatabase ( true ) ; testUtils . loadFromDatabase ( ) ; testUtils . inspect ( ) ; for ( Cause cause : testUtils . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } Assert . assertEquals ( "" , , testUtils . getCauses ( ) . size ( ) ) ; } @ Test public void testCustomInspector ( ) throws Exception { String TEST_FILE = "" ; File testFile = new File ( TEST_FILE ) ; List < File > testFileList = new ArrayList < File > ( ) ; testFileList . add ( testFile ) ; TestUtils testUtils = new TestUtils ( testFileList ) ; testUtils . storeToDatabase ( true ) ; testUtils . loadFromDatabase ( ) ; SuccessInspector successInspector = new SuccessInspector ( ) ; testUtils . setInspector ( "" , successInspector ) ; testUtils . inspect ( ) ; for ( Cause cause : testUtils . getCauses ( ) ) { System . out . println ( cause . getMessage ( ) ) ; } Assert . assertEquals ( "" , , testUtils . getCauses ( ) . size ( ) ) ; } } package com . asakusafw . testtools . excel ; import static org . junit . Assert . * ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . math . BigDecimal ; import java . util . List ; import org . apache . hadoop . io . Writable ; import org . apache . poi . hssf . usermodel . HSSFCell ; import org . apache . poi . hssf . usermodel . HSSFRow ; import org . apache . poi . hssf . usermodel . HSSFSheet ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . modelgen . source . MySqlDataType ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . ColumnMatchingCondition ; import com . asakusafw . testtools . Constants ; import com . asakusafw . testtools . NullValueCondition ; public class ExcelUtilsTest { @ Before public void setUp ( ) throws Exception { } @ After public void tearDown ( ) throws Exception { } @ Test public void testConstractor01 ( ) throws IOException { String filename = "" ; new ExcelUtils ( filename ) ; } @ Test ( expected = java . io . FileNotFoundException . class ) public void testConstractor02 ( ) throws IOException { String filename = "" ; new ExcelUtils ( filename ) ; } @ Test public void testConstractor03 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( IOException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testConstractor04 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( IOException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testConstractor05 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( IOException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testConstractor06 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( IOException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testConstractor07 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testConstractor08 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos01 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos02 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos03 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos04 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos05 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos06 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos07 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos08 ( ) throws IOException { String filename = "" ; ExcelUtils excelUtils = new ExcelUtils ( filename ) ; List < ColumnInfo > list = excelUtils . getColumnInfos ( ) ; assertEquals ( , list . size ( ) ) ; ColumnInfo info ; info = list . get ( ) ; assertEquals ( "" , info . getTableName ( ) ) ; assertEquals ( "" , info . getColumnName ( ) ) ; assertEquals ( "" , info . getColumnComment ( ) ) ; assertEquals ( MySqlDataType . LONG , info . getDataType ( ) ) ; assertTrue ( info . isKey ( ) ) ; assertFalse ( info . isNullable ( ) ) ; assertEquals ( ColumnMatchingCondition . NONE , info . getColumnMatchingCondition ( ) ) ; assertEquals ( NullValueCondition . NORMAL , info . getNullValueCondition ( ) ) ; info = list . get ( - ) ; assertEquals ( "" , info . getTableName ( ) ) ; assertEquals ( "" , info . getColumnName ( ) ) ; assertEquals ( "" , info . getColumnComment ( ) ) ; assertEquals ( MySqlDataType . VARCHAR , info . getDataType ( ) ) ; assertEquals ( , info . getCharacterMaximumLength ( ) ) ; assertFalse ( info . isKey ( ) ) ; assertFalse ( info . isNullable ( ) ) ; assertEquals ( ColumnMatchingCondition . PARTIAL , info . getColumnMatchingCondition ( ) ) ; assertEquals ( NullValueCondition . NULL_IS_NG , info . getNullValueCondition ( ) ) ; info = list . get ( - ) ; assertEquals ( "" , info . getTableName ( ) ) ; assertEquals ( "" , info . getColumnName ( ) ) ; assertEquals ( "" , info . getColumnComment ( ) ) ; assertEquals ( MySqlDataType . DECIMAL , info . getDataType ( ) ) ; assertEquals ( , info . getNumericPrecision ( ) ) ; assertEquals ( , info . getNumericScale ( ) ) ; assertFalse ( info . isKey ( ) ) ; assertTrue ( info . isNullable ( ) ) ; assertEquals ( ColumnMatchingCondition . EXACT , info . getColumnMatchingCondition ( ) ) ; assertEquals ( NullValueCondition . NULL_IS_OK , info . getNullValueCondition ( ) ) ; } @ Test public void testgetColumnInfos09 ( ) throws IOException { String filename = "" ; ExcelUtils excelUtils = new ExcelUtils ( filename ) ; List < ColumnInfo > list = excelUtils . getColumnInfos ( ) ; assertEquals ( , list . size ( ) ) ; ColumnInfo info ; info = list . get ( ) ; assertEquals ( "" , info . getTableName ( ) ) ; assertEquals ( "" , info . getColumnName ( ) ) ; assertEquals ( "" , info . getColumnComment ( ) ) ; assertEquals ( MySqlDataType . LONG , info . getDataType ( ) ) ; assertTrue ( info . isKey ( ) ) ; assertFalse ( info . isNullable ( ) ) ; assertEquals ( ColumnMatchingCondition . NONE , info . getColumnMatchingCondition ( ) ) ; assertEquals ( NullValueCondition . NORMAL , info . getNullValueCondition ( ) ) ; info = list . get ( - ) ; assertEquals ( "" , info . getTableName ( ) ) ; assertEquals ( "" , info . getColumnName ( ) ) ; assertEquals ( "" , info . getColumnComment ( ) ) ; assertEquals ( MySqlDataType . VARCHAR , info . getDataType ( ) ) ; assertEquals ( , info . getCharacterMaximumLength ( ) ) ; assertFalse ( info . isKey ( ) ) ; assertFalse ( info . isNullable ( ) ) ; assertEquals ( ColumnMatchingCondition . PARTIAL , info . getColumnMatchingCondition ( ) ) ; assertEquals ( NullValueCondition . NULL_IS_NG , info . getNullValueCondition ( ) ) ; info = list . get ( - ) ; assertEquals ( "" , info . getTableName ( ) ) ; assertEquals ( "" , info . getColumnName ( ) ) ; assertEquals ( "" , info . getColumnComment ( ) ) ; assertEquals ( MySqlDataType . DECIMAL , info . getDataType ( ) ) ; assertEquals ( , info . getNumericPrecision ( ) ) ; assertEquals ( , info . getNumericScale ( ) ) ; assertFalse ( info . isKey ( ) ) ; assertTrue ( info . isNullable ( ) ) ; assertEquals ( ColumnMatchingCondition . EXACT , info . getColumnMatchingCondition ( ) ) ; assertEquals ( NullValueCondition . NULL_IS_OK , info . getNullValueCondition ( ) ) ; } @ Test public void testgetColumnInfos10 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testgetColumnInfos11 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ Test public void testGetColumnInfos12 ( ) throws IOException { String filename = "" ; try { new ExcelUtils ( filename ) ; } catch ( InvalidExcelBookException e ) { String actual = e . getLocalizedMessage ( ) ; String expected = "" ; assertEquals ( expected , actual ) ; } } @ SuppressWarnings ( "" ) @ Test public void testGetXXXOption ( ) throws Exception { String filename = "" ; InputStream is = new FileInputStream ( filename ) ; HSSFWorkbook workbook = new HSSFWorkbook ( is ) ; HSSFSheet sheet = workbook . getSheet ( Constants . OUTPUT_DATA_SHEET_NAME ) ; ExcelUtils excelUtils = new ExcelUtils ( filename ) ; LongOption longOption = new LongOption ( ) ; longOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_0 , TYPES . BIGINT , longOption ) ; longOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_1 , TYPES . BIGINT , longOption ) ; longOption . modify ( - ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MINUS1 , TYPES . BIGINT , longOption ) ; longOption . modify ( ExcelUtils . EXCEL_MAX_LONG ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MAX , TYPES . BIGINT , longOption ) ; longOption . modify ( ExcelUtils . EXCEL_MIN_LONG ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MIN , TYPES . BIGINT , longOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DECIMAL , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_OVER_MAX , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_UNDER_MIN , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_BIG_VALUE , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; longOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_0 , TYPES . BIGINT , longOption ) ; longOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_1 , TYPES . BIGINT , longOption ) ; longOption . modify ( - ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MINUS1 , TYPES . BIGINT , longOption ) ; longOption . modify ( Long . MAX_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MAX , TYPES . BIGINT , longOption ) ; longOption . modify ( Long . MIN_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MIN , TYPES . BIGINT , longOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DECIMAL , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_OVER_MAX , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_UNDER_MIN , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_BIG_VALUE , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; longOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BLANK , TYPES . BIGINT , longOption ) ; longOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NULL_STRING , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; longOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_TRUE , TYPES . BIGINT , longOption ) ; longOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_FALSE , TYPES . BIGINT , longOption ) ; longOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATE , TYPES . BIGINT , longOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT1 , TYPES . BIGINT , longOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT2 , TYPES . BIGINT , longOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT1 , TYPES . BIGINT , longOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT2 , TYPES . BIGINT , longOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATE , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATETIME , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT1 , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT2 , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT1 , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT2 , TYPES . BIGINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATETIME , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . ERROR , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . FORMULA , TYPES . BIGINT , new CellTypeMismatchException ( "" ) ) ; IntOption intOption = new IntOption ( ) ; intOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_0 , TYPES . INT , intOption ) ; intOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_1 , TYPES . INT , intOption ) ; intOption . modify ( - ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MINUS1 , TYPES . INT , intOption ) ; intOption . modify ( Integer . MAX_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MAX , TYPES . INT , intOption ) ; intOption . modify ( Integer . MIN_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MIN , TYPES . INT , intOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DECIMAL , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_OVER_MAX , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_UNDER_MIN , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_BIG_VALUE , TYPES . INT , new NumberFormatException ( "" ) ) ; intOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_0 , TYPES . INT , intOption ) ; intOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_1 , TYPES . INT , intOption ) ; intOption . modify ( - ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MINUS1 , TYPES . INT , intOption ) ; intOption . modify ( Integer . MAX_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MAX , TYPES . INT , intOption ) ; intOption . modify ( Integer . MIN_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MIN , TYPES . INT , intOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DECIMAL , TYPES . INT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_OVER_MAX , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_UNDER_MIN , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_BIG_VALUE , TYPES . INT , new CellTypeMismatchException ( "" ) ) ; intOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BLANK , TYPES . INT , intOption ) ; longOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NULL_STRING , TYPES . INT , new CellTypeMismatchException ( "" ) ) ; intOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_TRUE , TYPES . INT , intOption ) ; intOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_FALSE , TYPES . INT , intOption ) ; intOption . modify ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATE , TYPES . INT , intOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT1 , TYPES . INT , intOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT2 , TYPES . INT , intOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT1 , TYPES . INT , intOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT2 , TYPES . INT , intOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATE , TYPES . INT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATETIME , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT1 , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT2 , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT1 , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT2 , TYPES . INT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATETIME , TYPES . INT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . ERROR , TYPES . INT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . FORMULA , TYPES . INT , new CellTypeMismatchException ( "" ) ) ; ShortOption shortOption = new ShortOption ( ) ; shortOption . modify ( ( short ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_0 , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( ( short ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_1 , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( ( short ) - ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MINUS1 , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( Short . MAX_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MAX , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( Short . MIN_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MIN , TYPES . SMALLINT , shortOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DECIMAL , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_OVER_MAX , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_UNDER_MIN , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_BIG_VALUE , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; shortOption . modify ( ( short ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_0 , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( ( short ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_1 , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( ( short ) - ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MINUS1 , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( Short . MAX_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MAX , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( Short . MIN_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MIN , TYPES . SMALLINT , shortOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DECIMAL , TYPES . SMALLINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_OVER_MAX , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_UNDER_MIN , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_BIG_VALUE , TYPES . SMALLINT , new CellTypeMismatchException ( "" ) ) ; shortOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BLANK , TYPES . SMALLINT , shortOption ) ; longOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NULL_STRING , TYPES . SMALLINT , new CellTypeMismatchException ( "" ) ) ; shortOption . modify ( ( short ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_TRUE , TYPES . SMALLINT , shortOption ) ; shortOption . modify ( ( short ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_FALSE , TYPES . SMALLINT , shortOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATE , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT1 , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT2 , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT1 , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT2 , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATE , TYPES . SMALLINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATETIME , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT1 , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT2 , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT1 , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT2 , TYPES . SMALLINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATETIME , TYPES . SMALLINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . ERROR , TYPES . SMALLINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . FORMULA , TYPES . SMALLINT , new CellTypeMismatchException ( "" ) ) ; ByteOption byteOption = new ByteOption ( ) ; byteOption . modify ( ( byte ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_0 , TYPES . TINYINT , byteOption ) ; byteOption . modify ( ( byte ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_1 , TYPES . TINYINT , byteOption ) ; byteOption . modify ( ( byte ) - ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MINUS1 , TYPES . TINYINT , byteOption ) ; byteOption . modify ( Byte . MAX_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MAX , TYPES . TINYINT , byteOption ) ; byteOption . modify ( Byte . MIN_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MIN , TYPES . TINYINT , byteOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DECIMAL , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_OVER_MAX , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_UNDER_MIN , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_BIG_VALUE , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; byteOption . modify ( ( byte ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_0 , TYPES . TINYINT , byteOption ) ; byteOption . modify ( ( byte ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_1 , TYPES . TINYINT , byteOption ) ; byteOption . modify ( ( byte ) - ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MINUS1 , TYPES . TINYINT , byteOption ) ; byteOption . modify ( Byte . MAX_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MAX , TYPES . TINYINT , byteOption ) ; byteOption . modify ( Byte . MIN_VALUE ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MIN , TYPES . TINYINT , byteOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DECIMAL , TYPES . TINYINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_OVER_MAX , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_UNDER_MIN , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_BIG_VALUE , TYPES . TINYINT , new CellTypeMismatchException ( "" ) ) ; byteOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BLANK , TYPES . TINYINT , byteOption ) ; longOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NULL_STRING , TYPES . TINYINT , new CellTypeMismatchException ( "" ) ) ; byteOption . modify ( ( byte ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_TRUE , TYPES . TINYINT , byteOption ) ; byteOption . modify ( ( byte ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_FALSE , TYPES . TINYINT , byteOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATE , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT1 , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT2 , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT1 , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT2 , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATE , TYPES . TINYINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATETIME , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT1 , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT2 , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT1 , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT2 , TYPES . TINYINT , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATETIME , TYPES . TINYINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . ERROR , TYPES . TINYINT , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . FORMULA , TYPES . TINYINT , new CellTypeMismatchException ( "" ) ) ; StringOption stringOption = new StringOption ( ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_0 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_1 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MINUS1 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DECIMAL , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_OVER_MAX , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_UNDER_MIN , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_BIG_VALUE , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_0 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_1 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MINUS1 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DECIMAL , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_OVER_MAX , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_UNDER_MIN , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_BIG_VALUE , TYPES . CHAR , stringOption ) ; stringOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BLANK , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NULL_STRING , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_TRUE , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_FALSE , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATE , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT1 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT2 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT1 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT2 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATE , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATETIME , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT1 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT2 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT1 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT2 , TYPES . CHAR , stringOption ) ; stringOption . modify ( "" ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATETIME , TYPES . CHAR , stringOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . ERROR , TYPES . CHAR , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . FORMULA , TYPES . CHAR , new CellTypeMismatchException ( "" ) ) ; DateOption dateOption = new DateOption ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_0 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_1 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MINUS1 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DECIMAL , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_OVER_MAX , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_UNDER_MIN , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_BIG_VALUE , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_0 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_1 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MINUS1 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DECIMAL , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_OVER_MAX , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_UNDER_MIN , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_BIG_VALUE , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; dateOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BLANK , TYPES . DATE , dateOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NULL_STRING , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_TRUE , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_FALSE , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATE , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; dateOption . modify ( DateUtil . getDayFromDate ( , , ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT1 , TYPES . DATE , dateOption ) ; dateOption . modify ( DateUtil . getDayFromDate ( , , ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT2 , TYPES . DATE , dateOption ) ; dateOption . modify ( DateUtil . getDayFromDate ( , , ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT1 , TYPES . DATE , dateOption ) ; dateOption . modify ( DateUtil . getDayFromDate ( , , ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT2 , TYPES . DATE , dateOption ) ; dateOption . modify ( DateUtil . getDayFromDate ( , , ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATE , TYPES . DATE , dateOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATETIME , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT1 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT2 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT1 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT2 , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATETIME , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . ERROR , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . FORMULA , TYPES . DATE , new CellTypeMismatchException ( "" ) ) ; DateTimeOption dateTimeOption = new DateTimeOption ( ) ; DateTime dateTime = new DateTime ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_0 , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_1 , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MINUS1 , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DECIMAL , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_OVER_MAX , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_UNDER_MIN , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_BIG_VALUE , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_0 , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_1 , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MINUS1 , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DECIMAL , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_OVER_MAX , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_UNDER_MIN , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_BIG_VALUE , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; dateTimeOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BLANK , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NULL_STRING , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_TRUE , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_FALSE , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATE , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; dateTime . setElapsedSeconds ( DateUtil . getDayFromDate ( , , ) * ) ; dateTimeOption . modify ( dateTime ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT1 , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT2 , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT1 , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT2 , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATE , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATETIME , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; dateTime . setElapsedSeconds ( DateUtil . getDayFromDate ( , , ) * + DateUtil . getSecondFromTime ( , , ) ) ; dateTimeOption . modify ( dateTime ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT1 , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT2 , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT1 , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT2 , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATETIME , TYPES . DATETIME , dateTimeOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . ERROR , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . FORMULA , TYPES . DATETIME , new CellTypeMismatchException ( "" ) ) ; DecimalOption decimalOption = new DecimalOption ( ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_0 , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_1 , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MINUS1 , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MAX , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_MIN , TYPES . DECIMAL , decimalOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DECIMAL , TYPES . DECIMAL , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_OVER_MAX , TYPES . DECIMAL , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_UNDER_MIN , TYPES . DECIMAL , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_BIG_VALUE , TYPES . DECIMAL , new NumberFormatException ( "" ) ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_0 , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_1 , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_MINUS1 , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DECIMAL , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_OVER_MAX , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_UNDER_MIN , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_BIG_VALUE , TYPES . DECIMAL , decimalOption ) ; decimalOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BLANK , TYPES . DECIMAL , decimalOption ) ; longOption . setNull ( ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NULL_STRING , TYPES . DECIMAL , new NumberFormatException ( "" ) ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_TRUE , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . BOOL_FALSE , TYPES . DECIMAL , decimalOption ) ; decimalOption . modify ( new BigDecimal ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATE , TYPES . DECIMAL , decimalOption ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT1 , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATE_FMT2 , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT1 , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATE_DATETIME_FIMT2 , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATE , TYPES . DECIMAL , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . NUMERIC_DATETIME , TYPES . DECIMAL , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT1 , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATE_FMT2 , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT1 , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . DATETIME_DATETIME_FIMT2 , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . STRING_DATETIME , TYPES . DECIMAL , new NumberFormatException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . ERROR , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; testGetXXXOptionDo ( excelUtils , sheet , DATA . FORMULA , TYPES . DECIMAL , new CellTypeMismatchException ( "" ) ) ; } public void testGetXXXOptionDo ( ExcelUtils excelUtils , HSSFSheet sheet , DATA data , TYPES types , Object expected ) throws Exception { int rownum = data . getRownum ( ) ; int colpos = types . getColpos ( ) ; HSSFCell cell = getCell ( sheet , rownum , colpos ) ; String methodName = types . getMethodName ( ) ; Method method = excelUtils . getClass ( ) . getDeclaredMethod ( methodName , HSSFCell . class ) ; method . setAccessible ( true ) ; Throwable t = null ; Object actual = null ; try { actual = method . invoke ( excelUtils , cell ) ; } catch ( InvocationTargetException e ) { t = e . getCause ( ) ; } String fmt = "" ; String assertMsg = String . format ( fmt , methodName , data . getComment ( ) ) ; if ( t instanceof RuntimeException ) { if ( expected instanceof RuntimeException ) { assertEquals ( assertMsg , expected . getClass ( ) , t . getClass ( ) ) ; String expectedMsg = ( ( RuntimeException ) expected ) . getMessage ( ) ; String actualMsg = t . getMessage ( ) ; assertTrue ( assertMsg , actualMsg . matches ( "" + expectedMsg + "" ) ) ; } else { throw ( RuntimeException ) t ; } } else if ( expected instanceof Writable ) { assertEquals ( assertMsg , expected , actual ) ; } else if ( expected instanceof Exception ) { throw new RuntimeException ( "" + expected . getClass ( ) . toString ( ) + "" ) ; } else { throw new RuntimeException ( "" + expected . getClass ( ) . toString ( ) ) ; } } private HSSFCell getCell ( HSSFSheet sheet , int rownum , int col ) { HSSFRow row = sheet . getRow ( rownum ) ; HSSFCell cell = row . getCell ( col ) ; return cell ; } private enum TYPES { BIGINT ( , "" ) , INT ( , "" ) , SMALLINT ( , "" ) , TINYINT ( , "" ) , CHAR ( , "" ) , DATETIME ( , "" ) , DATE ( , "" ) , DECIMAL ( , "" ) ; private int colpos ; private String methodName ; public int getColpos ( ) { return colpos ; } public String getMethodName ( ) { return methodName ; } private TYPES ( int colpos , String methodName ) { this . colpos = colpos ; this . methodName = methodName ; } } private enum DATA { NUMERIC_0 ( "" , ) , NUMERIC_1 ( "" , ) , NUMERIC_MINUS1 ( "" , ) , NUMERIC_MAX ( "" , ) , NUMERIC_MIN ( "" , ) , NUMERIC_DECIMAL ( "" , ) , NUMERIC_OVER_MAX ( "" , ) , NUMERIC_UNDER_MIN ( "" , ) , NUMERIC_BIG_VALUE ( "" , ) , STRING_0 ( "" , ) , STRING_1 ( "" , ) , STRING_MINUS1 ( "" , ) , STRING_MAX ( "" , ) , STRING_MIN ( "" , ) , STRING_DECIMAL ( "" , ) , STRING_OVER_MAX ( "" , ) , STRING_UNDER_MIN ( "" , ) , STRING_BIG_VALUE ( "" , ) , BLANK ( "" , ) , NULL_STRING ( "" , ) , BOOL_TRUE ( "" , ) , BOOL_FALSE ( "" , ) , NUMERIC_DATE ( "" , ) , DATE_DATE_FMT1 ( "" , ) , DATE_DATE_FMT2 ( "" , ) , DATE_DATETIME_FIMT1 ( "" , ) , DATE_DATETIME_FIMT2 ( "" , ) , STRING_DATE ( "" , ) , NUMERIC_DATETIME ( "" , ) , DATETIME_DATE_FMT1 ( "" , ) , DATETIME_DATE_FMT2 ( "" , ) , DATETIME_DATETIME_FIMT1 ( "" , ) , DATETIME_DATETIME_FIMT2 ( "" , ) , STRING_DATETIME ( "" , ) , ERROR ( "" , ) , FORMULA ( "" , ) ; private String comment ; private int rownum ; private DATA ( String comment , int rownum ) { this . comment = comment ; this . rownum = rownum ; } public String getComment ( ) { return comment ; } public int getRownum ( ) { return rownum ; } } } package com . asakusafw . testtools ; import org . junit . runner . RunWith ; import org . junit . runners . Suite ; import org . junit . runners . Suite . SuiteClasses ; import com . asakusafw . testtools . db . DbUtilTest ; import com . asakusafw . testtools . excel . ExcelUtilsTest ; import com . asakusafw . testtools . inspect . CauseTest ; import com . asakusafw . testtools . inspect . DefaultInspectorTest ; @ RunWith ( Suite . class ) @ SuiteClasses ( { DbUtilTest . class , TestDataHolderTest . class , ExcelUtilsTest . class , DefaultInspectorTest . class , TestUtilsTest . class , CauseTest . class } ) public class AllTests { } package com . asakusafw . testtools ; import static org . junit . Assert . * ; import java . io . IOException ; import java . lang . reflect . Method ; import java . math . BigDecimal ; import java . sql . Connection ; import java . util . List ; import org . apache . hadoop . io . Writable ; import org . junit . Test ; import test . modelgen . model . AllTypesWNoerr ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . testtools . db . DbUtils ; import com . asakusafw . testtools . excel . ExcelUtils ; public class TestDataHolderTest { @ Test public void testNormal ( ) throws Exception { String TEST_FILE = "" ; ExcelUtils excelUtils = new ExcelUtils ( TEST_FILE ) ; TestDataHolder dataHolder = excelUtils . getTestDataHolder ( ) ; List < Writable > sourceList = dataHolder . getSource ( ) ; List < Writable > expectList = dataHolder . getExpect ( ) ; testModelObjectList ( sourceList ) ; testModelObjectList ( expectList ) ; Connection conn = null ; try { conn = DbUtils . getConnection ( ) ; dataHolder . storeToDatabase ( conn , true ) ; dataHolder . loadFromDatabase ( conn ) ; dataHolder . storeToDatabase ( conn , false ) ; dataHolder . loadFromDatabase ( conn ) ; } finally { DbUtils . closeQuietly ( conn ) ; } } @ SuppressWarnings ( "" ) private void testModelObjectList ( List < Writable > list ) throws Exception { LongOption longOption = new LongOption ( ) ; testField ( list , "" , DATA . NUMERIC_0 , longOption . modify ( ) ) ; testField ( list , "" , DATA . NUMERIC_1 , longOption . modify ( ) ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , longOption . modify ( - ) ) ; testField ( list , "" , DATA . NUMERIC_MAX , longOption . modify ( ) ) ; testField ( list , "" , DATA . NUMERIC_MIN , longOption . modify ( - ) ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , longOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , longOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , longOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , longOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_0 , longOption . modify ( ) ) ; testField ( list , "" , DATA . STRING_1 , longOption . modify ( ) ) ; testField ( list , "" , DATA . STRING_MINUS1 , longOption . modify ( - ) ) ; testField ( list , "" , DATA . STRING_MAX , longOption . modify ( Long . MAX_VALUE ) ) ; testField ( list , "" , DATA . STRING_MIN , longOption . modify ( Long . MIN_VALUE ) ) ; testField ( list , "" , DATA . STRING_DECIMAL , longOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_OVER_MAX , longOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , longOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , longOption . setNull ( ) ) ; testField ( list , "" , DATA . BLANK , longOption . setNull ( ) ) ; testField ( list , "" , DATA . NULL_STRING , longOption . setNull ( ) ) ; testField ( list , "" , DATA . BOOL_TRUE , longOption . modify ( ) ) ; testField ( list , "" , DATA . BOOL_FALSE , longOption . modify ( ) ) ; testField ( list , "" , DATA . NUMERIC_DATE , longOption . modify ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , longOption . modify ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , longOption . modify ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , longOption . modify ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , longOption . modify ( ) ) ; testField ( list , "" , DATA . STRING_DATE , longOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , longOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , longOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , longOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , longOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , longOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATETIME , longOption . setNull ( ) ) ; IntOption intOption = new IntOption ( ) ; testField ( list , "" , DATA . NUMERIC_0 , intOption . modify ( ) ) ; testField ( list , "" , DATA . NUMERIC_1 , intOption . modify ( ) ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , intOption . modify ( - ) ) ; testField ( list , "" , DATA . NUMERIC_MAX , intOption . modify ( Integer . MAX_VALUE ) ) ; testField ( list , "" , DATA . NUMERIC_MIN , intOption . modify ( Integer . MIN_VALUE ) ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , intOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , intOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , intOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , intOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_0 , intOption . modify ( ) ) ; testField ( list , "" , DATA . STRING_1 , intOption . modify ( ) ) ; testField ( list , "" , DATA . STRING_MINUS1 , intOption . modify ( - ) ) ; testField ( list , "" , DATA . STRING_MAX , intOption . modify ( Integer . MAX_VALUE ) ) ; testField ( list , "" , DATA . STRING_MIN , intOption . modify ( Integer . MIN_VALUE ) ) ; testField ( list , "" , DATA . STRING_DECIMAL , intOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_OVER_MAX , intOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , intOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , intOption . setNull ( ) ) ; testField ( list , "" , DATA . BLANK , intOption . setNull ( ) ) ; testField ( list , "" , DATA . NULL_STRING , intOption . setNull ( ) ) ; testField ( list , "" , DATA . BOOL_TRUE , intOption . modify ( ) ) ; testField ( list , "" , DATA . BOOL_FALSE , intOption . modify ( ) ) ; testField ( list , "" , DATA . NUMERIC_DATE , intOption . modify ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , intOption . modify ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , intOption . modify ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , intOption . modify ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , intOption . modify ( ) ) ; testField ( list , "" , DATA . STRING_DATE , intOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , intOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , intOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , intOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , intOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , intOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATETIME , intOption . setNull ( ) ) ; ShortOption shortOption = new ShortOption ( ) ; testField ( list , "" , DATA . NUMERIC_0 , shortOption . modify ( ( short ) ) ) ; testField ( list , "" , DATA . NUMERIC_1 , shortOption . modify ( ( short ) ) ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , shortOption . modify ( ( short ) - ) ) ; testField ( list , "" , DATA . NUMERIC_MAX , shortOption . modify ( Short . MAX_VALUE ) ) ; testField ( list , "" , DATA . NUMERIC_MIN , shortOption . modify ( Short . MIN_VALUE ) ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_0 , shortOption . modify ( ( short ) ) ) ; testField ( list , "" , DATA . STRING_1 , shortOption . modify ( ( short ) ) ) ; testField ( list , "" , DATA . STRING_MINUS1 , shortOption . modify ( ( short ) - ) ) ; testField ( list , "" , DATA . STRING_MAX , shortOption . modify ( Short . MAX_VALUE ) ) ; testField ( list , "" , DATA . STRING_MIN , shortOption . modify ( Short . MIN_VALUE ) ) ; testField ( list , "" , DATA . STRING_DECIMAL , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_OVER_MAX , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . BLANK , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . NULL_STRING , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . BOOL_TRUE , shortOption . modify ( ( short ) ) ) ; testField ( list , "" , DATA . BOOL_FALSE , shortOption . modify ( ( short ) ) ) ; testField ( list , "" , DATA . NUMERIC_DATE , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATE , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , shortOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATETIME , shortOption . setNull ( ) ) ; ByteOption byteOption = new ByteOption ( ) ; testField ( list , "" , DATA . NUMERIC_0 , byteOption . modify ( ( byte ) ) ) ; testField ( list , "" , DATA . NUMERIC_1 , byteOption . modify ( ( byte ) ) ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , byteOption . modify ( ( byte ) - ) ) ; testField ( list , "" , DATA . NUMERIC_MAX , byteOption . modify ( Byte . MAX_VALUE ) ) ; testField ( list , "" , DATA . NUMERIC_MIN , byteOption . modify ( Byte . MIN_VALUE ) ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_0 , byteOption . modify ( ( byte ) ) ) ; testField ( list , "" , DATA . STRING_1 , byteOption . modify ( ( byte ) ) ) ; testField ( list , "" , DATA . STRING_MINUS1 , byteOption . modify ( ( byte ) - ) ) ; testField ( list , "" , DATA . STRING_MAX , byteOption . modify ( Byte . MAX_VALUE ) ) ; testField ( list , "" , DATA . STRING_MIN , byteOption . modify ( Byte . MIN_VALUE ) ) ; testField ( list , "" , DATA . STRING_DECIMAL , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_OVER_MAX , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . BLANK , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . NULL_STRING , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . BOOL_TRUE , byteOption . modify ( ( byte ) ) ) ; testField ( list , "" , DATA . BOOL_FALSE , byteOption . modify ( ( byte ) ) ) ; testField ( list , "" , DATA . NUMERIC_DATE , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATE , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , byteOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATETIME , byteOption . setNull ( ) ) ; StringOption stringOption = new StringOption ( ) ; testField ( list , "" , DATA . NUMERIC_0 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_MAX , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_MIN , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_0 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_MINUS1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_MAX , stringOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_MIN , stringOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DECIMAL , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_OVER_MAX , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . BLANK , stringOption . setNull ( ) ) ; testField ( list , "" , DATA . NULL_STRING , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . BOOL_TRUE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . BOOL_FALSE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_DATE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_DATE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_DATETIME , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_0 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_MAX , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_MIN , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_0 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_MINUS1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_MAX , stringOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_MIN , stringOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DECIMAL , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_OVER_MAX , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . BLANK , stringOption . setNull ( ) ) ; testField ( list , "" , DATA . NULL_STRING , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . BOOL_TRUE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . BOOL_FALSE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_DATE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_DATE , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , stringOption . modify ( "" ) ) ; testField ( list , "" , DATA . STRING_DATETIME , stringOption . modify ( "" ) ) ; DateTimeOption dateTimeOption = new DateTimeOption ( ) ; DateTime dateTime = new DateTime ( ) ; dateTimeOption . setNull ( ) ; testField ( list , "" , DATA . NUMERIC_0 , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_1 , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_MAX , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_MIN , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , dateTimeOption ) ; testField ( list , "" , DATA . STRING_0 , dateTimeOption ) ; testField ( list , "" , DATA . STRING_1 , dateTimeOption ) ; testField ( list , "" , DATA . STRING_MINUS1 , dateTimeOption ) ; testField ( list , "" , DATA . STRING_MAX , dateTimeOption ) ; testField ( list , "" , DATA . STRING_MIN , dateTimeOption ) ; testField ( list , "" , DATA . STRING_DECIMAL , dateTimeOption ) ; testField ( list , "" , DATA . STRING_OVER_MAX , dateTimeOption ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , dateTimeOption ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , dateTimeOption ) ; testField ( list , "" , DATA . BLANK , dateTimeOption ) ; testField ( list , "" , DATA . NULL_STRING , dateTimeOption ) ; testField ( list , "" , DATA . BOOL_TRUE , dateTimeOption ) ; testField ( list , "" , DATA . BOOL_FALSE , dateTimeOption ) ; testField ( list , "" , DATA . NUMERIC_DATE , dateTimeOption ) ; dateTime . setElapsedSeconds ( DateUtil . getDayFromDate ( , , ) * ) ; dateTimeOption . modify ( dateTime ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , dateTimeOption ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , dateTimeOption ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , dateTimeOption ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , dateTimeOption ) ; testField ( list , "" , DATA . STRING_DATE , dateTimeOption ) ; dateTimeOption . setNull ( ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , dateTimeOption ) ; dateTime . setElapsedSeconds ( DateUtil . getDayFromDate ( , , ) * + DateUtil . getSecondFromTime ( , , ) ) ; dateTimeOption . modify ( dateTime ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , dateTimeOption ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , dateTimeOption ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , dateTimeOption ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , dateTimeOption ) ; testField ( list , "" , DATA . STRING_DATETIME , dateTimeOption ) ; DateOption dateOption = new DateOption ( ) ; dateOption . setNull ( ) ; testField ( list , "" , DATA . NUMERIC_0 , dateOption ) ; testField ( list , "" , DATA . NUMERIC_1 , dateOption ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , dateOption ) ; testField ( list , "" , DATA . NUMERIC_MAX , dateOption ) ; testField ( list , "" , DATA . NUMERIC_MIN , dateOption ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , dateOption ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , dateOption ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , dateOption ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , dateOption ) ; testField ( list , "" , DATA . STRING_0 , dateOption ) ; testField ( list , "" , DATA . STRING_1 , dateOption ) ; testField ( list , "" , DATA . STRING_MINUS1 , dateOption ) ; testField ( list , "" , DATA . STRING_MAX , dateOption ) ; testField ( list , "" , DATA . STRING_MIN , dateOption ) ; testField ( list , "" , DATA . STRING_DECIMAL , dateOption ) ; testField ( list , "" , DATA . STRING_OVER_MAX , dateOption ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , dateOption ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , dateOption ) ; testField ( list , "" , DATA . BLANK , dateOption ) ; testField ( list , "" , DATA . NULL_STRING , dateOption ) ; testField ( list , "" , DATA . BOOL_TRUE , dateOption ) ; testField ( list , "" , DATA . BOOL_FALSE , dateOption ) ; testField ( list , "" , DATA . NUMERIC_DATE , dateOption ) ; dateOption . modify ( DateUtil . getDayFromDate ( , , ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , dateOption ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , dateOption ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , dateOption ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , dateOption ) ; testField ( list , "" , DATA . STRING_DATE , dateOption ) ; dateOption . setNull ( ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , dateOption ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , dateOption ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , dateOption ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , dateOption ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , dateOption ) ; testField ( list , "" , DATA . STRING_DATETIME , dateOption ) ; DecimalOption decimalOption = new DecimalOption ( ) ; testField ( list , "" , DATA . NUMERIC_0 , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . NUMERIC_1 , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , decimalOption . modify ( new BigDecimal ( - ) ) ) ; testField ( list , "" , DATA . NUMERIC_MAX , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . NUMERIC_MIN , decimalOption . modify ( new BigDecimal ( - ) ) ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_0 , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . STRING_1 , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . STRING_MINUS1 , decimalOption . modify ( new BigDecimal ( - ) ) ) ; testField ( list , "" , DATA . STRING_MAX , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_MIN , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DECIMAL , decimalOption . modify ( new BigDecimal ( "" ) ) ) ; testField ( list , "" , DATA . STRING_OVER_MAX , decimalOption . modify ( new BigDecimal ( "" ) ) ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , decimalOption . modify ( new BigDecimal ( "" ) ) ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , decimalOption . modify ( new BigDecimal ( "" ) ) ) ; testField ( list , "" , DATA . BLANK , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NULL_STRING , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . BOOL_TRUE , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . BOOL_FALSE , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . NUMERIC_DATE , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATE , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATETIME , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_0 , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . NUMERIC_1 , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . NUMERIC_MINUS1 , decimalOption . modify ( new BigDecimal ( - ) ) ) ; testField ( list , "" , DATA . NUMERIC_MAX , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . NUMERIC_MIN , decimalOption . modify ( new BigDecimal ( - ) ) ) ; testField ( list , "" , DATA . NUMERIC_DECIMAL , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_OVER_MAX , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_UNDER_MIN , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_BIG_VALUE , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_0 , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . STRING_1 , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . STRING_MINUS1 , decimalOption . modify ( new BigDecimal ( - ) ) ) ; testField ( list , "" , DATA . STRING_MAX , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_MIN , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DECIMAL , decimalOption . modify ( new BigDecimal ( "" ) ) ) ; testField ( list , "" , DATA . STRING_OVER_MAX , decimalOption . modify ( new BigDecimal ( "" ) ) ) ; testField ( list , "" , DATA . STRING_UNDER_MIN , decimalOption . modify ( new BigDecimal ( "" ) ) ) ; testField ( list , "" , DATA . STRING_BIG_VALUE , decimalOption . modify ( new BigDecimal ( "" ) ) ) ; testField ( list , "" , DATA . BLANK , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NULL_STRING , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . BOOL_TRUE , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . BOOL_FALSE , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . NUMERIC_DATE , decimalOption . modify ( new BigDecimal ( ) ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT1 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATE_FMT2 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT1 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATE_DATETIME_FIMT2 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATE , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . NUMERIC_DATETIME , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT1 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATE_FMT2 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT1 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . DATETIME_DATETIME_FIMT2 , decimalOption . setNull ( ) ) ; testField ( list , "" , DATA . STRING_DATETIME , decimalOption . setNull ( ) ) ; } private void testField ( List < Writable > list , String getterName , DATA data , Object expected ) throws Exception { int index = data . getRownum ( ) - ; Writable modelObject = list . get ( index ) ; Method method = modelObject . getClass ( ) . getMethod ( getterName ) ; Object actual = method . invoke ( modelObject ) ; String format = "" ; String message = String . format ( format , data . getComment ( ) , getterName ) ; assertEquals ( "" + message , expected . getClass ( ) , actual . getClass ( ) ) ; assertEquals ( "" + message , expected , actual ) ; } private enum DATA { NUMERIC_0 ( "" , ) , NUMERIC_1 ( "" , ) , NUMERIC_MINUS1 ( "" , ) , NUMERIC_MAX ( "" , ) , NUMERIC_MIN ( "" , ) , NUMERIC_DECIMAL ( "" , ) , NUMERIC_OVER_MAX ( "" , ) , NUMERIC_UNDER_MIN ( "" , ) , NUMERIC_BIG_VALUE ( "" , ) , STRING_0 ( "" , ) , STRING_1 ( "" , ) , STRING_MINUS1 ( "" , ) , STRING_MAX ( "" , ) , STRING_MIN ( "" , ) , STRING_DECIMAL ( "" , ) , STRING_OVER_MAX ( "" , ) , STRING_UNDER_MIN ( "" , ) , STRING_BIG_VALUE ( "" , ) , BLANK ( "" , ) , NULL_STRING ( "" , ) , BOOL_TRUE ( "" , ) , BOOL_FALSE ( "" , ) , NUMERIC_DATE ( "" , ) , DATE_DATE_FMT1 ( "" , ) , DATE_DATE_FMT2 ( "" , ) , DATE_DATETIME_FIMT1 ( "" , ) , DATE_DATETIME_FIMT2 ( "" , ) , STRING_DATE ( "" , ) , NUMERIC_DATETIME ( "" , ) , DATETIME_DATE_FMT1 ( "" , ) , DATETIME_DATE_FMT2 ( "" , ) , DATETIME_DATETIME_FIMT1 ( "" , ) , DATETIME_DATETIME_FIMT2 ( "" , ) , STRING_DATETIME ( "" , ) ; private final String comment ; private final int rownum ; private DATA ( String comment , int rownum ) { this . comment = comment ; this . rownum = rownum ; } public String getComment ( ) { return comment ; } public int getRownum ( ) { return rownum ; } } @ Test public void testSort ( ) throws Exception { String TEST_FILE = "" ; ExcelUtils excelUtils = new ExcelUtils ( TEST_FILE ) ; TestDataHolder dataHolder = excelUtils . getTestDataHolder ( ) ; dataHolder . sort ( ) ; List < Writable > expectList = dataHolder . getExpect ( ) ; int expectValue = ; for ( Writable modelObject : expectList ) { expectValue ++ ; AllTypesWNoerr a = ( AllTypesWNoerr ) modelObject ; int actual = Integer . parseInt ( a . getCTagOption ( ) . getAsString ( ) ) ; assertEquals ( expectValue , actual ) ; } } } package test . inspector ; import org . apache . hadoop . io . Writable ; import com . asakusafw . testtools . inspect . AbstractInspector ; public class SuccessInspector extends AbstractInspector { @ Override protected void inspect ( Writable expectRow , Writable actualRow ) { } } package test . modelgen . dummy . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . math . BigDecimal ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ TableModel ( name = "" , primary = { } ) @ Generated ( "" ) @ SuppressWarnings ( "" ) public class Foo implements Writable { @ Property ( name = "" ) private LongOption pk = new LongOption ( ) ; @ Property ( name = "" ) private StringOption detailGroupId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailSenderId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailReceiverId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailTestType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailStatus = new StringOption ( ) ; @ Property ( name = "" ) private IntOption detailLineNo = new IntOption ( ) ; @ Property ( name = "" ) private StringOption deleteFlg = new StringOption ( ) ; @ Property ( name = "" ) private DateOption insertDatetime = new DateOption ( ) ; @ Property ( name = "" ) private DateOption updateDatetime = new DateOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private ByteOption lineNo = new ByteOption ( ) ; @ Property ( name = "" ) private DateOption deliveryDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption storeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption salesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tenantCode = new StringOption ( ) ; @ Property ( name = "" ) private LongOption netPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sellingPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private StringOption shipmentStoreCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption shipmentSalesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption deductionCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption accountCode = new StringOption ( ) ; @ Property ( name = "" ) private DecimalOption decCol = new DecimalOption ( ) ; @ Property ( name = "" ) private DateOption ownershipDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption ownershipFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; public long getPk ( ) { return this . pk . get ( ) ; } public void setPk ( long pk ) { this . pk . modify ( pk ) ; } public LongOption getPkOption ( ) { return this . pk ; } public void setPkOption ( LongOption pk ) { this . pk . copyFrom ( pk ) ; } public Text getDetailGroupId ( ) { return this . detailGroupId . get ( ) ; } public void setDetailGroupId ( Text detailGroupId ) { this . detailGroupId . modify ( detailGroupId ) ; } public String getDetailGroupIdAsString ( ) { return this . detailGroupId . getAsString ( ) ; } public void setDetailGroupIdAsString ( String detailGroupId ) { this . detailGroupId . modify ( detailGroupId ) ; } public StringOption getDetailGroupIdOption ( ) { return this . detailGroupId ; } public void setDetailGroupIdOption ( StringOption detailGroupId ) { this . detailGroupId . copyFrom ( detailGroupId ) ; } public Text getDetailType ( ) { return this . detailType . get ( ) ; } public void setDetailType ( Text detailType ) { this . detailType . modify ( detailType ) ; } public String getDetailTypeAsString ( ) { return this . detailType . getAsString ( ) ; } public void setDetailTypeAsString ( String detailType ) { this . detailType . modify ( detailType ) ; } public StringOption getDetailTypeOption ( ) { return this . detailType ; } public void setDetailTypeOption ( StringOption detailType ) { this . detailType . copyFrom ( detailType ) ; } public Text getDetailSenderId ( ) { return this . detailSenderId . get ( ) ; } public void setDetailSenderId ( Text detailSenderId ) { this . detailSenderId . modify ( detailSenderId ) ; } public String getDetailSenderIdAsString ( ) { return this . detailSenderId . getAsString ( ) ; } public void setDetailSenderIdAsString ( String detailSenderId ) { this . detailSenderId . modify ( detailSenderId ) ; } public StringOption getDetailSenderIdOption ( ) { return this . detailSenderId ; } public void setDetailSenderIdOption ( StringOption detailSenderId ) { this . detailSenderId . copyFrom ( detailSenderId ) ; } public Text getDetailReceiverId ( ) { return this . detailReceiverId . get ( ) ; } public void setDetailReceiverId ( Text detailReceiverId ) { this . detailReceiverId . modify ( detailReceiverId ) ; } public String getDetailReceiverIdAsString ( ) { return this . detailReceiverId . getAsString ( ) ; } public void setDetailReceiverIdAsString ( String detailReceiverId ) { this . detailReceiverId . modify ( detailReceiverId ) ; } public StringOption getDetailReceiverIdOption ( ) { return this . detailReceiverId ; } public void setDetailReceiverIdOption ( StringOption detailReceiverId ) { this . detailReceiverId . copyFrom ( detailReceiverId ) ; } public Text getDetailTestType ( ) { return this . detailTestType . get ( ) ; } public void setDetailTestType ( Text detailTestType ) { this . detailTestType . modify ( detailTestType ) ; } public String getDetailTestTypeAsString ( ) { return this . detailTestType . getAsString ( ) ; } public void setDetailTestTypeAsString ( String detailTestType ) { this . detailTestType . modify ( detailTestType ) ; } public StringOption getDetailTestTypeOption ( ) { return this . detailTestType ; } public void setDetailTestTypeOption ( StringOption detailTestType ) { this . detailTestType . copyFrom ( detailTestType ) ; } public Text getDetailStatus ( ) { return this . detailStatus . get ( ) ; } public void setDetailStatus ( Text detailStatus ) { this . detailStatus . modify ( detailStatus ) ; } public String getDetailStatusAsString ( ) { return this . detailStatus . getAsString ( ) ; } public void setDetailStatusAsString ( String detailStatus ) { this . detailStatus . modify ( detailStatus ) ; } public StringOption getDetailStatusOption ( ) { return this . detailStatus ; } public void setDetailStatusOption ( StringOption detailStatus ) { this . detailStatus . copyFrom ( detailStatus ) ; } public int getDetailLineNo ( ) { return this . detailLineNo . get ( ) ; } public void setDetailLineNo ( int detailLineNo ) { this . detailLineNo . modify ( detailLineNo ) ; } public IntOption getDetailLineNoOption ( ) { return this . detailLineNo ; } public void setDetailLineNoOption ( IntOption detailLineNo ) { this . detailLineNo . copyFrom ( detailLineNo ) ; } public Text getDeleteFlg ( ) { return this . deleteFlg . get ( ) ; } public void setDeleteFlg ( Text deleteFlg ) { this . deleteFlg . modify ( deleteFlg ) ; } public String getDeleteFlgAsString ( ) { return this . deleteFlg . getAsString ( ) ; } public void setDeleteFlgAsString ( String deleteFlg ) { this . deleteFlg . modify ( deleteFlg ) ; } public StringOption getDeleteFlgOption ( ) { return this . deleteFlg ; } public void setDeleteFlgOption ( StringOption deleteFlg ) { this . deleteFlg . copyFrom ( deleteFlg ) ; } public Date getInsertDatetime ( ) { return this . insertDatetime . get ( ) ; } public void setInsertDatetime ( Date insertDatetime ) { this . insertDatetime . modify ( insertDatetime ) ; } public DateOption getInsertDatetimeOption ( ) { return this . insertDatetime ; } public void setInsertDatetimeOption ( DateOption insertDatetime ) { this . insertDatetime . copyFrom ( insertDatetime ) ; } public Date getUpdateDatetime ( ) { return this . updateDatetime . get ( ) ; } public void setUpdateDatetime ( Date updateDatetime ) { this . updateDatetime . modify ( updateDatetime ) ; } public DateOption getUpdateDatetimeOption ( ) { return this . updateDatetime ; } public void setUpdateDatetimeOption ( DateOption updateDatetime ) { this . updateDatetime . copyFrom ( updateDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public byte getLineNo ( ) { return this . lineNo . get ( ) ; } public void setLineNo ( byte lineNo ) { this . lineNo . modify ( lineNo ) ; } public ByteOption getLineNoOption ( ) { return this . lineNo ; } public void setLineNoOption ( ByteOption lineNo ) { this . lineNo . copyFrom ( lineNo ) ; } public Date getDeliveryDate ( ) { return this . deliveryDate . get ( ) ; } public void setDeliveryDate ( Date deliveryDate ) { this . deliveryDate . modify ( deliveryDate ) ; } public DateOption getDeliveryDateOption ( ) { return this . deliveryDate ; } public void setDeliveryDateOption ( DateOption deliveryDate ) { this . deliveryDate . copyFrom ( deliveryDate ) ; } public Text getStoreCode ( ) { return this . storeCode . get ( ) ; } public void setStoreCode ( Text storeCode ) { this . storeCode . modify ( storeCode ) ; } public String getStoreCodeAsString ( ) { return this . storeCode . getAsString ( ) ; } public void setStoreCodeAsString ( String storeCode ) { this . storeCode . modify ( storeCode ) ; } public StringOption getStoreCodeOption ( ) { return this . storeCode ; } public void setStoreCodeOption ( StringOption storeCode ) { this . storeCode . copyFrom ( storeCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Text getSalesTypeCode ( ) { return this . salesTypeCode . get ( ) ; } public void setSalesTypeCode ( Text salesTypeCode ) { this . salesTypeCode . modify ( salesTypeCode ) ; } public String getSalesTypeCodeAsString ( ) { return this . salesTypeCode . getAsString ( ) ; } public void setSalesTypeCodeAsString ( String salesTypeCode ) { this . salesTypeCode . modify ( salesTypeCode ) ; } public StringOption getSalesTypeCodeOption ( ) { return this . salesTypeCode ; } public void setSalesTypeCodeOption ( StringOption salesTypeCode ) { this . salesTypeCode . copyFrom ( salesTypeCode ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getTenantCode ( ) { return this . tenantCode . get ( ) ; } public void setTenantCode ( Text tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public String getTenantCodeAsString ( ) { return this . tenantCode . getAsString ( ) ; } public void setTenantCodeAsString ( String tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public StringOption getTenantCodeOption ( ) { return this . tenantCode ; } public void setTenantCodeOption ( StringOption tenantCode ) { this . tenantCode . copyFrom ( tenantCode ) ; } public long getNetPriceTotal ( ) { return this . netPriceTotal . get ( ) ; } public void setNetPriceTotal ( long netPriceTotal ) { this . netPriceTotal . modify ( netPriceTotal ) ; } public LongOption getNetPriceTotalOption ( ) { return this . netPriceTotal ; } public void setNetPriceTotalOption ( LongOption netPriceTotal ) { this . netPriceTotal . copyFrom ( netPriceTotal ) ; } public long getSellingPriceTotal ( ) { return this . sellingPriceTotal . get ( ) ; } public void setSellingPriceTotal ( long sellingPriceTotal ) { this . sellingPriceTotal . modify ( sellingPriceTotal ) ; } public LongOption getSellingPriceTotalOption ( ) { return this . sellingPriceTotal ; } public void setSellingPriceTotalOption ( LongOption sellingPriceTotal ) { this . sellingPriceTotal . copyFrom ( sellingPriceTotal ) ; } public Text getShipmentStoreCode ( ) { return this . shipmentStoreCode . get ( ) ; } public void setShipmentStoreCode ( Text shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public String getShipmentStoreCodeAsString ( ) { return this . shipmentStoreCode . getAsString ( ) ; } public void setShipmentStoreCodeAsString ( String shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public StringOption getShipmentStoreCodeOption ( ) { return this . shipmentStoreCode ; } public void setShipmentStoreCodeOption ( StringOption shipmentStoreCode ) { this . shipmentStoreCode . copyFrom ( shipmentStoreCode ) ; } public Text getShipmentSalesTypeCode ( ) { return this . shipmentSalesTypeCode . get ( ) ; } public void setShipmentSalesTypeCode ( Text shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public String getShipmentSalesTypeCodeAsString ( ) { return this . shipmentSalesTypeCode . getAsString ( ) ; } public void setShipmentSalesTypeCodeAsString ( String shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public StringOption getShipmentSalesTypeCodeOption ( ) { return this . shipmentSalesTypeCode ; } public void setShipmentSalesTypeCodeOption ( StringOption shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . copyFrom ( shipmentSalesTypeCode ) ; } public Text getDeductionCode ( ) { return this . deductionCode . get ( ) ; } public void setDeductionCode ( Text deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public String getDeductionCodeAsString ( ) { return this . deductionCode . getAsString ( ) ; } public void setDeductionCodeAsString ( String deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public StringOption getDeductionCodeOption ( ) { return this . deductionCode ; } public void setDeductionCodeOption ( StringOption deductionCode ) { this . deductionCode . copyFrom ( deductionCode ) ; } public Text getAccountCode ( ) { return this . accountCode . get ( ) ; } public void setAccountCode ( Text accountCode ) { this . accountCode . modify ( accountCode ) ; } public String getAccountCodeAsString ( ) { return this . accountCode . getAsString ( ) ; } public void setAccountCodeAsString ( String accountCode ) { this . accountCode . modify ( accountCode ) ; } public StringOption getAccountCodeOption ( ) { return this . accountCode ; } public void setAccountCodeOption ( StringOption accountCode ) { this . accountCode . copyFrom ( accountCode ) ; } public BigDecimal getDecCol ( ) { return this . decCol . get ( ) ; } public void setDecCol ( BigDecimal decCol ) { this . decCol . modify ( decCol ) ; } public DecimalOption getDecColOption ( ) { return this . decCol ; } public void setDecColOption ( DecimalOption decCol ) { this . decCol . copyFrom ( decCol ) ; } public Date getOwnershipDate ( ) { return this . ownershipDate . get ( ) ; } public void setOwnershipDate ( Date ownershipDate ) { this . ownershipDate . modify ( ownershipDate ) ; } public DateOption getOwnershipDateOption ( ) { return this . ownershipDate ; } public void setOwnershipDateOption ( DateOption ownershipDate ) { this . ownershipDate . copyFrom ( ownershipDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public Text getOwnershipFlag ( ) { return this . ownershipFlag . get ( ) ; } public void setOwnershipFlag ( Text ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public String getOwnershipFlagAsString ( ) { return this . ownershipFlag . getAsString ( ) ; } public void setOwnershipFlagAsString ( String ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public StringOption getOwnershipFlagOption ( ) { return this . ownershipFlag ; } public void setOwnershipFlagOption ( StringOption ownershipFlag ) { this . ownershipFlag . copyFrom ( ownershipFlag ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public void copyFrom ( Foo source ) { this . pk . copyFrom ( source . pk ) ; this . detailGroupId . copyFrom ( source . detailGroupId ) ; this . detailType . copyFrom ( source . detailType ) ; this . detailSenderId . copyFrom ( source . detailSenderId ) ; this . detailReceiverId . copyFrom ( source . detailReceiverId ) ; this . detailTestType . copyFrom ( source . detailTestType ) ; this . detailStatus . copyFrom ( source . detailStatus ) ; this . detailLineNo . copyFrom ( source . detailLineNo ) ; this . deleteFlg . copyFrom ( source . deleteFlg ) ; this . insertDatetime . copyFrom ( source . insertDatetime ) ; this . updateDatetime . copyFrom ( source . updateDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . lineNo . copyFrom ( source . lineNo ) ; this . deliveryDate . copyFrom ( source . deliveryDate ) ; this . storeCode . copyFrom ( source . storeCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . salesTypeCode . copyFrom ( source . salesTypeCode ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . tenantCode . copyFrom ( source . tenantCode ) ; this . netPriceTotal . copyFrom ( source . netPriceTotal ) ; this . sellingPriceTotal . copyFrom ( source . sellingPriceTotal ) ; this . shipmentStoreCode . copyFrom ( source . shipmentStoreCode ) ; this . shipmentSalesTypeCode . copyFrom ( source . shipmentSalesTypeCode ) ; this . deductionCode . copyFrom ( source . deductionCode ) ; this . accountCode . copyFrom ( source . accountCode ) ; this . decCol . copyFrom ( source . decCol ) ; this . ownershipDate . copyFrom ( source . ownershipDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . ownershipFlag . copyFrom ( source . ownershipFlag ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { pk . write ( out ) ; detailGroupId . write ( out ) ; detailType . write ( out ) ; detailSenderId . write ( out ) ; detailReceiverId . write ( out ) ; detailTestType . write ( out ) ; detailStatus . write ( out ) ; detailLineNo . write ( out ) ; deleteFlg . write ( out ) ; insertDatetime . write ( out ) ; updateDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; lineNo . write ( out ) ; deliveryDate . write ( out ) ; storeCode . write ( out ) ; buyerCode . write ( out ) ; salesTypeCode . write ( out ) ; sellerCode . write ( out ) ; tenantCode . write ( out ) ; netPriceTotal . write ( out ) ; sellingPriceTotal . write ( out ) ; shipmentStoreCode . write ( out ) ; shipmentSalesTypeCode . write ( out ) ; deductionCode . write ( out ) ; accountCode . write ( out ) ; decCol . write ( out ) ; ownershipDate . write ( out ) ; cutoffDate . write ( out ) ; payoutDate . write ( out ) ; ownershipFlag . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { pk . readFields ( in ) ; detailGroupId . readFields ( in ) ; detailType . readFields ( in ) ; detailSenderId . readFields ( in ) ; detailReceiverId . readFields ( in ) ; detailTestType . readFields ( in ) ; detailStatus . readFields ( in ) ; detailLineNo . readFields ( in ) ; deleteFlg . readFields ( in ) ; insertDatetime . readFields ( in ) ; updateDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; lineNo . readFields ( in ) ; deliveryDate . readFields ( in ) ; storeCode . readFields ( in ) ; buyerCode . readFields ( in ) ; salesTypeCode . readFields ( in ) ; sellerCode . readFields ( in ) ; tenantCode . readFields ( in ) ; netPriceTotal . readFields ( in ) ; sellingPriceTotal . readFields ( in ) ; shipmentStoreCode . readFields ( in ) ; shipmentSalesTypeCode . readFields ( in ) ; deductionCode . readFields ( in ) ; accountCode . readFields ( in ) ; decCol . readFields ( in ) ; ownershipDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; ownershipFlag . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + pk . hashCode ( ) ; result = prime * result + detailGroupId . hashCode ( ) ; result = prime * result + detailType . hashCode ( ) ; result = prime * result + detailSenderId . hashCode ( ) ; result = prime * result + detailReceiverId . hashCode ( ) ; result = prime * result + detailTestType . hashCode ( ) ; result = prime * result + detailStatus . hashCode ( ) ; result = prime * result + detailLineNo . hashCode ( ) ; result = prime * result + deleteFlg . hashCode ( ) ; result = prime * result + insertDatetime . hashCode ( ) ; result = prime * result + updateDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + lineNo . hashCode ( ) ; result = prime * result + deliveryDate . hashCode ( ) ; result = prime * result + storeCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + salesTypeCode . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + tenantCode . hashCode ( ) ; result = prime * result + netPriceTotal . hashCode ( ) ; result = prime * result + sellingPriceTotal . hashCode ( ) ; result = prime * result + shipmentStoreCode . hashCode ( ) ; result = prime * result + shipmentSalesTypeCode . hashCode ( ) ; result = prime * result + deductionCode . hashCode ( ) ; result = prime * result + accountCode . hashCode ( ) ; result = prime * result + decCol . hashCode ( ) ; result = prime * result + ownershipDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + ownershipFlag . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Foo other = ( Foo ) obj ; if ( this . pk . equals ( other . pk ) == false ) { return false ; } if ( this . detailGroupId . equals ( other . detailGroupId ) == false ) { return false ; } if ( this . detailType . equals ( other . detailType ) == false ) { return false ; } if ( this . detailSenderId . equals ( other . detailSenderId ) == false ) { return false ; } if ( this . detailReceiverId . equals ( other . detailReceiverId ) == false ) { return false ; } if ( this . detailTestType . equals ( other . detailTestType ) == false ) { return false ; } if ( this . detailStatus . equals ( other . detailStatus ) == false ) { return false ; } if ( this . detailLineNo . equals ( other . detailLineNo ) == false ) { return false ; } if ( this . deleteFlg . equals ( other . deleteFlg ) == false ) { return false ; } if ( this . insertDatetime . equals ( other . insertDatetime ) == false ) { return false ; } if ( this . updateDatetime . equals ( other . updateDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . lineNo . equals ( other . lineNo ) == false ) { return false ; } if ( this . deliveryDate . equals ( other . deliveryDate ) == false ) { return false ; } if ( this . storeCode . equals ( other . storeCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . salesTypeCode . equals ( other . salesTypeCode ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . tenantCode . equals ( other . tenantCode ) == false ) { return false ; } if ( this . netPriceTotal . equals ( other . netPriceTotal ) == false ) { return false ; } if ( this . sellingPriceTotal . equals ( other . sellingPriceTotal ) == false ) { return false ; } if ( this . shipmentStoreCode . equals ( other . shipmentStoreCode ) == false ) { return false ; } if ( this . shipmentSalesTypeCode . equals ( other . shipmentSalesTypeCode ) == false ) { return false ; } if ( this . deductionCode . equals ( other . deductionCode ) == false ) { return false ; } if ( this . accountCode . equals ( other . accountCode ) == false ) { return false ; } if ( this . decCol . equals ( other . decCol ) == false ) { return false ; } if ( this . ownershipDate . equals ( other . ownershipDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . ownershipFlag . equals ( other . ownershipFlag ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } return true ; } } package test . modelgen . dummy . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . math . BigDecimal ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ TableModel ( name = "" , primary = { } ) @ Generated ( "" ) @ SuppressWarnings ( "" ) public class Bar implements Writable { @ Property ( name = "" ) private LongOption pk = new LongOption ( ) ; @ Property ( name = "" ) private StringOption detailGroupId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailSenderId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailReceiverId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailTestType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailStatus = new StringOption ( ) ; @ Property ( name = "" ) private IntOption detailLineNo = new IntOption ( ) ; @ Property ( name = "" ) private StringOption deleteFlg = new StringOption ( ) ; @ Property ( name = "" ) private DateOption insertDatetime = new DateOption ( ) ; @ Property ( name = "" ) private DateOption updateDatetime = new DateOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private ByteOption lineNo = new ByteOption ( ) ; @ Property ( name = "" ) private DateOption deliveryDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption storeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption salesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tenantCode = new StringOption ( ) ; @ Property ( name = "" ) private LongOption netPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sellingPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private StringOption shipmentStoreCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption shipmentSalesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption deductionCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption accountCode = new StringOption ( ) ; @ Property ( name = "" ) private DecimalOption decCol = new DecimalOption ( ) ; @ Property ( name = "" ) private DateOption ownershipDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption ownershipFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; public long getPk ( ) { return this . pk . get ( ) ; } public void setPk ( long pk ) { this . pk . modify ( pk ) ; } public LongOption getPkOption ( ) { return this . pk ; } public void setPkOption ( LongOption pk ) { this . pk . copyFrom ( pk ) ; } public Text getDetailGroupId ( ) { return this . detailGroupId . get ( ) ; } public void setDetailGroupId ( Text detailGroupId ) { this . detailGroupId . modify ( detailGroupId ) ; } public String getDetailGroupIdAsString ( ) { return this . detailGroupId . getAsString ( ) ; } public void setDetailGroupIdAsString ( String detailGroupId ) { this . detailGroupId . modify ( detailGroupId ) ; } public StringOption getDetailGroupIdOption ( ) { return this . detailGroupId ; } public void setDetailGroupIdOption ( StringOption detailGroupId ) { this . detailGroupId . copyFrom ( detailGroupId ) ; } public Text getDetailType ( ) { return this . detailType . get ( ) ; } public void setDetailType ( Text detailType ) { this . detailType . modify ( detailType ) ; } public String getDetailTypeAsString ( ) { return this . detailType . getAsString ( ) ; } public void setDetailTypeAsString ( String detailType ) { this . detailType . modify ( detailType ) ; } public StringOption getDetailTypeOption ( ) { return this . detailType ; } public void setDetailTypeOption ( StringOption detailType ) { this . detailType . copyFrom ( detailType ) ; } public Text getDetailSenderId ( ) { return this . detailSenderId . get ( ) ; } public void setDetailSenderId ( Text detailSenderId ) { this . detailSenderId . modify ( detailSenderId ) ; } public String getDetailSenderIdAsString ( ) { return this . detailSenderId . getAsString ( ) ; } public void setDetailSenderIdAsString ( String detailSenderId ) { this . detailSenderId . modify ( detailSenderId ) ; } public StringOption getDetailSenderIdOption ( ) { return this . detailSenderId ; } public void setDetailSenderIdOption ( StringOption detailSenderId ) { this . detailSenderId . copyFrom ( detailSenderId ) ; } public Text getDetailReceiverId ( ) { return this . detailReceiverId . get ( ) ; } public void setDetailReceiverId ( Text detailReceiverId ) { this . detailReceiverId . modify ( detailReceiverId ) ; } public String getDetailReceiverIdAsString ( ) { return this . detailReceiverId . getAsString ( ) ; } public void setDetailReceiverIdAsString ( String detailReceiverId ) { this . detailReceiverId . modify ( detailReceiverId ) ; } public StringOption getDetailReceiverIdOption ( ) { return this . detailReceiverId ; } public void setDetailReceiverIdOption ( StringOption detailReceiverId ) { this . detailReceiverId . copyFrom ( detailReceiverId ) ; } public Text getDetailTestType ( ) { return this . detailTestType . get ( ) ; } public void setDetailTestType ( Text detailTestType ) { this . detailTestType . modify ( detailTestType ) ; } public String getDetailTestTypeAsString ( ) { return this . detailTestType . getAsString ( ) ; } public void setDetailTestTypeAsString ( String detailTestType ) { this . detailTestType . modify ( detailTestType ) ; } public StringOption getDetailTestTypeOption ( ) { return this . detailTestType ; } public void setDetailTestTypeOption ( StringOption detailTestType ) { this . detailTestType . copyFrom ( detailTestType ) ; } public Text getDetailStatus ( ) { return this . detailStatus . get ( ) ; } public void setDetailStatus ( Text detailStatus ) { this . detailStatus . modify ( detailStatus ) ; } public String getDetailStatusAsString ( ) { return this . detailStatus . getAsString ( ) ; } public void setDetailStatusAsString ( String detailStatus ) { this . detailStatus . modify ( detailStatus ) ; } public StringOption getDetailStatusOption ( ) { return this . detailStatus ; } public void setDetailStatusOption ( StringOption detailStatus ) { this . detailStatus . copyFrom ( detailStatus ) ; } public int getDetailLineNo ( ) { return this . detailLineNo . get ( ) ; } public void setDetailLineNo ( int detailLineNo ) { this . detailLineNo . modify ( detailLineNo ) ; } public IntOption getDetailLineNoOption ( ) { return this . detailLineNo ; } public void setDetailLineNoOption ( IntOption detailLineNo ) { this . detailLineNo . copyFrom ( detailLineNo ) ; } public Text getDeleteFlg ( ) { return this . deleteFlg . get ( ) ; } public void setDeleteFlg ( Text deleteFlg ) { this . deleteFlg . modify ( deleteFlg ) ; } public String getDeleteFlgAsString ( ) { return this . deleteFlg . getAsString ( ) ; } public void setDeleteFlgAsString ( String deleteFlg ) { this . deleteFlg . modify ( deleteFlg ) ; } public StringOption getDeleteFlgOption ( ) { return this . deleteFlg ; } public void setDeleteFlgOption ( StringOption deleteFlg ) { this . deleteFlg . copyFrom ( deleteFlg ) ; } public Date getInsertDatetime ( ) { return this . insertDatetime . get ( ) ; } public void setInsertDatetime ( Date insertDatetime ) { this . insertDatetime . modify ( insertDatetime ) ; } public DateOption getInsertDatetimeOption ( ) { return this . insertDatetime ; } public void setInsertDatetimeOption ( DateOption insertDatetime ) { this . insertDatetime . copyFrom ( insertDatetime ) ; } public Date getUpdateDatetime ( ) { return this . updateDatetime . get ( ) ; } public void setUpdateDatetime ( Date updateDatetime ) { this . updateDatetime . modify ( updateDatetime ) ; } public DateOption getUpdateDatetimeOption ( ) { return this . updateDatetime ; } public void setUpdateDatetimeOption ( DateOption updateDatetime ) { this . updateDatetime . copyFrom ( updateDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public byte getLineNo ( ) { return this . lineNo . get ( ) ; } public void setLineNo ( byte lineNo ) { this . lineNo . modify ( lineNo ) ; } public ByteOption getLineNoOption ( ) { return this . lineNo ; } public void setLineNoOption ( ByteOption lineNo ) { this . lineNo . copyFrom ( lineNo ) ; } public Date getDeliveryDate ( ) { return this . deliveryDate . get ( ) ; } public void setDeliveryDate ( Date deliveryDate ) { this . deliveryDate . modify ( deliveryDate ) ; } public DateOption getDeliveryDateOption ( ) { return this . deliveryDate ; } public void setDeliveryDateOption ( DateOption deliveryDate ) { this . deliveryDate . copyFrom ( deliveryDate ) ; } public Text getStoreCode ( ) { return this . storeCode . get ( ) ; } public void setStoreCode ( Text storeCode ) { this . storeCode . modify ( storeCode ) ; } public String getStoreCodeAsString ( ) { return this . storeCode . getAsString ( ) ; } public void setStoreCodeAsString ( String storeCode ) { this . storeCode . modify ( storeCode ) ; } public StringOption getStoreCodeOption ( ) { return this . storeCode ; } public void setStoreCodeOption ( StringOption storeCode ) { this . storeCode . copyFrom ( storeCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Text getSalesTypeCode ( ) { return this . salesTypeCode . get ( ) ; } public void setSalesTypeCode ( Text salesTypeCode ) { this . salesTypeCode . modify ( salesTypeCode ) ; } public String getSalesTypeCodeAsString ( ) { return this . salesTypeCode . getAsString ( ) ; } public void setSalesTypeCodeAsString ( String salesTypeCode ) { this . salesTypeCode . modify ( salesTypeCode ) ; } public StringOption getSalesTypeCodeOption ( ) { return this . salesTypeCode ; } public void setSalesTypeCodeOption ( StringOption salesTypeCode ) { this . salesTypeCode . copyFrom ( salesTypeCode ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getTenantCode ( ) { return this . tenantCode . get ( ) ; } public void setTenantCode ( Text tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public String getTenantCodeAsString ( ) { return this . tenantCode . getAsString ( ) ; } public void setTenantCodeAsString ( String tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public StringOption getTenantCodeOption ( ) { return this . tenantCode ; } public void setTenantCodeOption ( StringOption tenantCode ) { this . tenantCode . copyFrom ( tenantCode ) ; } public long getNetPriceTotal ( ) { return this . netPriceTotal . get ( ) ; } public void setNetPriceTotal ( long netPriceTotal ) { this . netPriceTotal . modify ( netPriceTotal ) ; } public LongOption getNetPriceTotalOption ( ) { return this . netPriceTotal ; } public void setNetPriceTotalOption ( LongOption netPriceTotal ) { this . netPriceTotal . copyFrom ( netPriceTotal ) ; } public long getSellingPriceTotal ( ) { return this . sellingPriceTotal . get ( ) ; } public void setSellingPriceTotal ( long sellingPriceTotal ) { this . sellingPriceTotal . modify ( sellingPriceTotal ) ; } public LongOption getSellingPriceTotalOption ( ) { return this . sellingPriceTotal ; } public void setSellingPriceTotalOption ( LongOption sellingPriceTotal ) { this . sellingPriceTotal . copyFrom ( sellingPriceTotal ) ; } public Text getShipmentStoreCode ( ) { return this . shipmentStoreCode . get ( ) ; } public void setShipmentStoreCode ( Text shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public String getShipmentStoreCodeAsString ( ) { return this . shipmentStoreCode . getAsString ( ) ; } public void setShipmentStoreCodeAsString ( String shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public StringOption getShipmentStoreCodeOption ( ) { return this . shipmentStoreCode ; } public void setShipmentStoreCodeOption ( StringOption shipmentStoreCode ) { this . shipmentStoreCode . copyFrom ( shipmentStoreCode ) ; } public Text getShipmentSalesTypeCode ( ) { return this . shipmentSalesTypeCode . get ( ) ; } public void setShipmentSalesTypeCode ( Text shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public String getShipmentSalesTypeCodeAsString ( ) { return this . shipmentSalesTypeCode . getAsString ( ) ; } public void setShipmentSalesTypeCodeAsString ( String shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public StringOption getShipmentSalesTypeCodeOption ( ) { return this . shipmentSalesTypeCode ; } public void setShipmentSalesTypeCodeOption ( StringOption shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . copyFrom ( shipmentSalesTypeCode ) ; } public Text getDeductionCode ( ) { return this . deductionCode . get ( ) ; } public void setDeductionCode ( Text deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public String getDeductionCodeAsString ( ) { return this . deductionCode . getAsString ( ) ; } public void setDeductionCodeAsString ( String deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public StringOption getDeductionCodeOption ( ) { return this . deductionCode ; } public void setDeductionCodeOption ( StringOption deductionCode ) { this . deductionCode . copyFrom ( deductionCode ) ; } public Text getAccountCode ( ) { return this . accountCode . get ( ) ; } public void setAccountCode ( Text accountCode ) { this . accountCode . modify ( accountCode ) ; } public String getAccountCodeAsString ( ) { return this . accountCode . getAsString ( ) ; } public void setAccountCodeAsString ( String accountCode ) { this . accountCode . modify ( accountCode ) ; } public StringOption getAccountCodeOption ( ) { return this . accountCode ; } public void setAccountCodeOption ( StringOption accountCode ) { this . accountCode . copyFrom ( accountCode ) ; } public BigDecimal getDecCol ( ) { return this . decCol . get ( ) ; } public void setDecCol ( BigDecimal decCol ) { this . decCol . modify ( decCol ) ; } public DecimalOption getDecColOption ( ) { return this . decCol ; } public void setDecColOption ( DecimalOption decCol ) { this . decCol . copyFrom ( decCol ) ; } public Date getOwnershipDate ( ) { return this . ownershipDate . get ( ) ; } public void setOwnershipDate ( Date ownershipDate ) { this . ownershipDate . modify ( ownershipDate ) ; } public DateOption getOwnershipDateOption ( ) { return this . ownershipDate ; } public void setOwnershipDateOption ( DateOption ownershipDate ) { this . ownershipDate . copyFrom ( ownershipDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public Text getOwnershipFlag ( ) { return this . ownershipFlag . get ( ) ; } public void setOwnershipFlag ( Text ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public String getOwnershipFlagAsString ( ) { return this . ownershipFlag . getAsString ( ) ; } public void setOwnershipFlagAsString ( String ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public StringOption getOwnershipFlagOption ( ) { return this . ownershipFlag ; } public void setOwnershipFlagOption ( StringOption ownershipFlag ) { this . ownershipFlag . copyFrom ( ownershipFlag ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public void copyFrom ( Bar source ) { this . pk . copyFrom ( source . pk ) ; this . detailGroupId . copyFrom ( source . detailGroupId ) ; this . detailType . copyFrom ( source . detailType ) ; this . detailSenderId . copyFrom ( source . detailSenderId ) ; this . detailReceiverId . copyFrom ( source . detailReceiverId ) ; this . detailTestType . copyFrom ( source . detailTestType ) ; this . detailStatus . copyFrom ( source . detailStatus ) ; this . detailLineNo . copyFrom ( source . detailLineNo ) ; this . deleteFlg . copyFrom ( source . deleteFlg ) ; this . insertDatetime . copyFrom ( source . insertDatetime ) ; this . updateDatetime . copyFrom ( source . updateDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . lineNo . copyFrom ( source . lineNo ) ; this . deliveryDate . copyFrom ( source . deliveryDate ) ; this . storeCode . copyFrom ( source . storeCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . salesTypeCode . copyFrom ( source . salesTypeCode ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . tenantCode . copyFrom ( source . tenantCode ) ; this . netPriceTotal . copyFrom ( source . netPriceTotal ) ; this . sellingPriceTotal . copyFrom ( source . sellingPriceTotal ) ; this . shipmentStoreCode . copyFrom ( source . shipmentStoreCode ) ; this . shipmentSalesTypeCode . copyFrom ( source . shipmentSalesTypeCode ) ; this . deductionCode . copyFrom ( source . deductionCode ) ; this . accountCode . copyFrom ( source . accountCode ) ; this . decCol . copyFrom ( source . decCol ) ; this . ownershipDate . copyFrom ( source . ownershipDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . ownershipFlag . copyFrom ( source . ownershipFlag ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { pk . write ( out ) ; detailGroupId . write ( out ) ; detailType . write ( out ) ; detailSenderId . write ( out ) ; detailReceiverId . write ( out ) ; detailTestType . write ( out ) ; detailStatus . write ( out ) ; detailLineNo . write ( out ) ; deleteFlg . write ( out ) ; insertDatetime . write ( out ) ; updateDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; lineNo . write ( out ) ; deliveryDate . write ( out ) ; storeCode . write ( out ) ; buyerCode . write ( out ) ; salesTypeCode . write ( out ) ; sellerCode . write ( out ) ; tenantCode . write ( out ) ; netPriceTotal . write ( out ) ; sellingPriceTotal . write ( out ) ; shipmentStoreCode . write ( out ) ; shipmentSalesTypeCode . write ( out ) ; deductionCode . write ( out ) ; accountCode . write ( out ) ; decCol . write ( out ) ; ownershipDate . write ( out ) ; cutoffDate . write ( out ) ; payoutDate . write ( out ) ; ownershipFlag . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { pk . readFields ( in ) ; detailGroupId . readFields ( in ) ; detailType . readFields ( in ) ; detailSenderId . readFields ( in ) ; detailReceiverId . readFields ( in ) ; detailTestType . readFields ( in ) ; detailStatus . readFields ( in ) ; detailLineNo . readFields ( in ) ; deleteFlg . readFields ( in ) ; insertDatetime . readFields ( in ) ; updateDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; lineNo . readFields ( in ) ; deliveryDate . readFields ( in ) ; storeCode . readFields ( in ) ; buyerCode . readFields ( in ) ; salesTypeCode . readFields ( in ) ; sellerCode . readFields ( in ) ; tenantCode . readFields ( in ) ; netPriceTotal . readFields ( in ) ; sellingPriceTotal . readFields ( in ) ; shipmentStoreCode . readFields ( in ) ; shipmentSalesTypeCode . readFields ( in ) ; deductionCode . readFields ( in ) ; accountCode . readFields ( in ) ; decCol . readFields ( in ) ; ownershipDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; ownershipFlag . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + pk . hashCode ( ) ; result = prime * result + detailGroupId . hashCode ( ) ; result = prime * result + detailType . hashCode ( ) ; result = prime * result + detailSenderId . hashCode ( ) ; result = prime * result + detailReceiverId . hashCode ( ) ; result = prime * result + detailTestType . hashCode ( ) ; result = prime * result + detailStatus . hashCode ( ) ; result = prime * result + detailLineNo . hashCode ( ) ; result = prime * result + deleteFlg . hashCode ( ) ; result = prime * result + insertDatetime . hashCode ( ) ; result = prime * result + updateDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + lineNo . hashCode ( ) ; result = prime * result + deliveryDate . hashCode ( ) ; result = prime * result + storeCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + salesTypeCode . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + tenantCode . hashCode ( ) ; result = prime * result + netPriceTotal . hashCode ( ) ; result = prime * result + sellingPriceTotal . hashCode ( ) ; result = prime * result + shipmentStoreCode . hashCode ( ) ; result = prime * result + shipmentSalesTypeCode . hashCode ( ) ; result = prime * result + deductionCode . hashCode ( ) ; result = prime * result + accountCode . hashCode ( ) ; result = prime * result + decCol . hashCode ( ) ; result = prime * result + ownershipDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + ownershipFlag . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Bar other = ( Bar ) obj ; if ( this . pk . equals ( other . pk ) == false ) { return false ; } if ( this . detailGroupId . equals ( other . detailGroupId ) == false ) { return false ; } if ( this . detailType . equals ( other . detailType ) == false ) { return false ; } if ( this . detailSenderId . equals ( other . detailSenderId ) == false ) { return false ; } if ( this . detailReceiverId . equals ( other . detailReceiverId ) == false ) { return false ; } if ( this . detailTestType . equals ( other . detailTestType ) == false ) { return false ; } if ( this . detailStatus . equals ( other . detailStatus ) == false ) { return false ; } if ( this . detailLineNo . equals ( other . detailLineNo ) == false ) { return false ; } if ( this . deleteFlg . equals ( other . deleteFlg ) == false ) { return false ; } if ( this . insertDatetime . equals ( other . insertDatetime ) == false ) { return false ; } if ( this . updateDatetime . equals ( other . updateDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . lineNo . equals ( other . lineNo ) == false ) { return false ; } if ( this . deliveryDate . equals ( other . deliveryDate ) == false ) { return false ; } if ( this . storeCode . equals ( other . storeCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . salesTypeCode . equals ( other . salesTypeCode ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . tenantCode . equals ( other . tenantCode ) == false ) { return false ; } if ( this . netPriceTotal . equals ( other . netPriceTotal ) == false ) { return false ; } if ( this . sellingPriceTotal . equals ( other . sellingPriceTotal ) == false ) { return false ; } if ( this . shipmentStoreCode . equals ( other . shipmentStoreCode ) == false ) { return false ; } if ( this . shipmentSalesTypeCode . equals ( other . shipmentSalesTypeCode ) == false ) { return false ; } if ( this . deductionCode . equals ( other . deductionCode ) == false ) { return false ; } if ( this . accountCode . equals ( other . accountCode ) == false ) { return false ; } if ( this . decCol . equals ( other . decCol ) == false ) { return false ; } if ( this . ownershipDate . equals ( other . ownershipDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . ownershipFlag . equals ( other . ownershipFlag ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } return true ; } } package test . modelgen . io ; import java . io . IOException ; import test . modelgen . model . Bar ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class BarModelInput implements ModelInput < Bar > { private final RecordParser parser ; public BarModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( Bar model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getPkOption ( ) ) ; parser . fill ( model . getDetailGroupIdOption ( ) ) ; parser . fill ( model . getDetailTypeOption ( ) ) ; parser . fill ( model . getDetailSenderIdOption ( ) ) ; parser . fill ( model . getDetailReceiverIdOption ( ) ) ; parser . fill ( model . getDetailTestTypeOption ( ) ) ; parser . fill ( model . getDetailStatusOption ( ) ) ; parser . fill ( model . getDetailLineNoOption ( ) ) ; parser . fill ( model . getDeleteFlgOption ( ) ) ; parser . fill ( model . getInsertDatetimeOption ( ) ) ; parser . fill ( model . getUpdateDatetimeOption ( ) ) ; parser . fill ( model . getPurchaseNoOption ( ) ) ; parser . fill ( model . getPurchaseTypeOption ( ) ) ; parser . fill ( model . getTradeTypeOption ( ) ) ; parser . fill ( model . getTradeNoOption ( ) ) ; parser . fill ( model . getLineNoOption ( ) ) ; parser . fill ( model . getDeliveryDateOption ( ) ) ; parser . fill ( model . getStoreCodeOption ( ) ) ; parser . fill ( model . getBuyerCodeOption ( ) ) ; parser . fill ( model . getSalesTypeCodeOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getTenantCodeOption ( ) ) ; parser . fill ( model . getNetPriceTotalOption ( ) ) ; parser . fill ( model . getSellingPriceTotalOption ( ) ) ; parser . fill ( model . getShipmentStoreCodeOption ( ) ) ; parser . fill ( model . getShipmentSalesTypeCodeOption ( ) ) ; parser . fill ( model . getDeductionCodeOption ( ) ) ; parser . fill ( model . getAccountCodeOption ( ) ) ; parser . fill ( model . getDecColOption ( ) ) ; parser . fill ( model . getOwnershipDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getPayoutDateOption ( ) ) ; parser . fill ( model . getOwnershipFlagOption ( ) ) ; parser . fill ( model . getCutoffFlagOption ( ) ) ; parser . fill ( model . getPayoutFlagOption ( ) ) ; parser . fill ( model . getDisposeNoOption ( ) ) ; parser . fill ( model . getDisposeDateOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . io ; import java . io . IOException ; import test . modelgen . model . AllTypesWNoerr ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class AllTypesWNoerrModelOutput implements ModelOutput < AllTypesWNoerr > { private final RecordEmitter emitter ; public AllTypesWNoerrModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( AllTypesWNoerr model ) throws IOException { emitter . emit ( model . getCTagOption ( ) ) ; emitter . emit ( model . getCCommentOption ( ) ) ; emitter . emit ( model . getCBigintOption ( ) ) ; emitter . emit ( model . getCIntOption ( ) ) ; emitter . emit ( model . getCSmallintOption ( ) ) ; emitter . emit ( model . getCTinyintOption ( ) ) ; emitter . emit ( model . getCCharOption ( ) ) ; emitter . emit ( model . getCDatetimeOption ( ) ) ; emitter . emit ( model . getCDateOption ( ) ) ; emitter . emit ( model . getCDecimal200Option ( ) ) ; emitter . emit ( model . getCDecimal255Option ( ) ) ; emitter . emit ( model . getCVcharOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . io ; import java . io . IOException ; import test . modelgen . model . Bar ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class BarModelOutput implements ModelOutput < Bar > { private final RecordEmitter emitter ; public BarModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Bar model ) throws IOException { emitter . emit ( model . getPkOption ( ) ) ; emitter . emit ( model . getDetailGroupIdOption ( ) ) ; emitter . emit ( model . getDetailTypeOption ( ) ) ; emitter . emit ( model . getDetailSenderIdOption ( ) ) ; emitter . emit ( model . getDetailReceiverIdOption ( ) ) ; emitter . emit ( model . getDetailTestTypeOption ( ) ) ; emitter . emit ( model . getDetailStatusOption ( ) ) ; emitter . emit ( model . getDetailLineNoOption ( ) ) ; emitter . emit ( model . getDeleteFlgOption ( ) ) ; emitter . emit ( model . getInsertDatetimeOption ( ) ) ; emitter . emit ( model . getUpdateDatetimeOption ( ) ) ; emitter . emit ( model . getPurchaseNoOption ( ) ) ; emitter . emit ( model . getPurchaseTypeOption ( ) ) ; emitter . emit ( model . getTradeTypeOption ( ) ) ; emitter . emit ( model . getTradeNoOption ( ) ) ; emitter . emit ( model . getLineNoOption ( ) ) ; emitter . emit ( model . getDeliveryDateOption ( ) ) ; emitter . emit ( model . getStoreCodeOption ( ) ) ; emitter . emit ( model . getBuyerCodeOption ( ) ) ; emitter . emit ( model . getSalesTypeCodeOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getTenantCodeOption ( ) ) ; emitter . emit ( model . getNetPriceTotalOption ( ) ) ; emitter . emit ( model . getSellingPriceTotalOption ( ) ) ; emitter . emit ( model . getShipmentStoreCodeOption ( ) ) ; emitter . emit ( model . getShipmentSalesTypeCodeOption ( ) ) ; emitter . emit ( model . getDeductionCodeOption ( ) ) ; emitter . emit ( model . getAccountCodeOption ( ) ) ; emitter . emit ( model . getDecColOption ( ) ) ; emitter . emit ( model . getOwnershipDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getPayoutDateOption ( ) ) ; emitter . emit ( model . getOwnershipFlagOption ( ) ) ; emitter . emit ( model . getCutoffFlagOption ( ) ) ; emitter . emit ( model . getPayoutFlagOption ( ) ) ; emitter . emit ( model . getDisposeNoOption ( ) ) ; emitter . emit ( model . getDisposeDateOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . io ; import java . io . IOException ; import test . modelgen . model . Foo ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class FooModelOutput implements ModelOutput < Foo > { private final RecordEmitter emitter ; public FooModelOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Foo model ) throws IOException { emitter . emit ( model . getPkOption ( ) ) ; emitter . emit ( model . getDetailGroupIdOption ( ) ) ; emitter . emit ( model . getDetailTypeOption ( ) ) ; emitter . emit ( model . getDetailSenderIdOption ( ) ) ; emitter . emit ( model . getDetailReceiverIdOption ( ) ) ; emitter . emit ( model . getDetailTestTypeOption ( ) ) ; emitter . emit ( model . getDetailStatusOption ( ) ) ; emitter . emit ( model . getDetailLineNoOption ( ) ) ; emitter . emit ( model . getDeleteFlgOption ( ) ) ; emitter . emit ( model . getInsertDatetimeOption ( ) ) ; emitter . emit ( model . getUpdateDatetimeOption ( ) ) ; emitter . emit ( model . getPurchaseNoOption ( ) ) ; emitter . emit ( model . getPurchaseTypeOption ( ) ) ; emitter . emit ( model . getTradeTypeOption ( ) ) ; emitter . emit ( model . getTradeNoOption ( ) ) ; emitter . emit ( model . getLineNoOption ( ) ) ; emitter . emit ( model . getDeliveryDateOption ( ) ) ; emitter . emit ( model . getStoreCodeOption ( ) ) ; emitter . emit ( model . getBuyerCodeOption ( ) ) ; emitter . emit ( model . getSalesTypeCodeOption ( ) ) ; emitter . emit ( model . getSellerCodeOption ( ) ) ; emitter . emit ( model . getTenantCodeOption ( ) ) ; emitter . emit ( model . getNetPriceTotalOption ( ) ) ; emitter . emit ( model . getSellingPriceTotalOption ( ) ) ; emitter . emit ( model . getShipmentStoreCodeOption ( ) ) ; emitter . emit ( model . getShipmentSalesTypeCodeOption ( ) ) ; emitter . emit ( model . getDeductionCodeOption ( ) ) ; emitter . emit ( model . getAccountCodeOption ( ) ) ; emitter . emit ( model . getDecColOption ( ) ) ; emitter . emit ( model . getOwnershipDateOption ( ) ) ; emitter . emit ( model . getCutoffDateOption ( ) ) ; emitter . emit ( model . getPayoutDateOption ( ) ) ; emitter . emit ( model . getOwnershipFlagOption ( ) ) ; emitter . emit ( model . getCutoffFlagOption ( ) ) ; emitter . emit ( model . getPayoutFlagOption ( ) ) ; emitter . emit ( model . getDisposeNoOption ( ) ) ; emitter . emit ( model . getDisposeDateOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package test . modelgen . io ; import java . io . IOException ; import test . modelgen . model . AllTypesWNoerr ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class AllTypesWNoerrModelInput implements ModelInput < AllTypesWNoerr > { private final RecordParser parser ; public AllTypesWNoerrModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( AllTypesWNoerr model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getCTagOption ( ) ) ; parser . fill ( model . getCCommentOption ( ) ) ; parser . fill ( model . getCBigintOption ( ) ) ; parser . fill ( model . getCIntOption ( ) ) ; parser . fill ( model . getCSmallintOption ( ) ) ; parser . fill ( model . getCTinyintOption ( ) ) ; parser . fill ( model . getCCharOption ( ) ) ; parser . fill ( model . getCDatetimeOption ( ) ) ; parser . fill ( model . getCDateOption ( ) ) ; parser . fill ( model . getCDecimal200Option ( ) ) ; parser . fill ( model . getCDecimal255Option ( ) ) ; parser . fill ( model . getCVcharOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . io ; import java . io . IOException ; import test . modelgen . model . Foo ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class FooModelInput implements ModelInput < Foo > { private final RecordParser parser ; public FooModelInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( ) ; } this . parser = parser ; } @ Override public boolean readTo ( Foo model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getPkOption ( ) ) ; parser . fill ( model . getDetailGroupIdOption ( ) ) ; parser . fill ( model . getDetailTypeOption ( ) ) ; parser . fill ( model . getDetailSenderIdOption ( ) ) ; parser . fill ( model . getDetailReceiverIdOption ( ) ) ; parser . fill ( model . getDetailTestTypeOption ( ) ) ; parser . fill ( model . getDetailStatusOption ( ) ) ; parser . fill ( model . getDetailLineNoOption ( ) ) ; parser . fill ( model . getDeleteFlgOption ( ) ) ; parser . fill ( model . getInsertDatetimeOption ( ) ) ; parser . fill ( model . getUpdateDatetimeOption ( ) ) ; parser . fill ( model . getPurchaseNoOption ( ) ) ; parser . fill ( model . getPurchaseTypeOption ( ) ) ; parser . fill ( model . getTradeTypeOption ( ) ) ; parser . fill ( model . getTradeNoOption ( ) ) ; parser . fill ( model . getLineNoOption ( ) ) ; parser . fill ( model . getDeliveryDateOption ( ) ) ; parser . fill ( model . getStoreCodeOption ( ) ) ; parser . fill ( model . getBuyerCodeOption ( ) ) ; parser . fill ( model . getSalesTypeCodeOption ( ) ) ; parser . fill ( model . getSellerCodeOption ( ) ) ; parser . fill ( model . getTenantCodeOption ( ) ) ; parser . fill ( model . getNetPriceTotalOption ( ) ) ; parser . fill ( model . getSellingPriceTotalOption ( ) ) ; parser . fill ( model . getShipmentStoreCodeOption ( ) ) ; parser . fill ( model . getShipmentSalesTypeCodeOption ( ) ) ; parser . fill ( model . getDeductionCodeOption ( ) ) ; parser . fill ( model . getAccountCodeOption ( ) ) ; parser . fill ( model . getDecColOption ( ) ) ; parser . fill ( model . getOwnershipDateOption ( ) ) ; parser . fill ( model . getCutoffDateOption ( ) ) ; parser . fill ( model . getPayoutDateOption ( ) ) ; parser . fill ( model . getOwnershipFlagOption ( ) ) ; parser . fill ( model . getCutoffFlagOption ( ) ) ; parser . fill ( model . getPayoutFlagOption ( ) ) ; parser . fill ( model . getDisposeNoOption ( ) ) ; parser . fill ( model . getDisposeDateOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package test . modelgen . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . math . BigDecimal ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ TableModel ( name = "" , primary = { } ) @ Generated ( "" ) @ SuppressWarnings ( "" ) public class Foo implements Writable { @ Property ( name = "" ) private LongOption pk = new LongOption ( ) ; @ Property ( name = "" ) private StringOption detailGroupId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailSenderId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailReceiverId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailTestType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailStatus = new StringOption ( ) ; @ Property ( name = "" ) private IntOption detailLineNo = new IntOption ( ) ; @ Property ( name = "" ) private StringOption deleteFlg = new StringOption ( ) ; @ Property ( name = "" ) private DateOption insertDatetime = new DateOption ( ) ; @ Property ( name = "" ) private DateOption updateDatetime = new DateOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private ByteOption lineNo = new ByteOption ( ) ; @ Property ( name = "" ) private DateOption deliveryDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption storeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption salesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tenantCode = new StringOption ( ) ; @ Property ( name = "" ) private LongOption netPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sellingPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private StringOption shipmentStoreCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption shipmentSalesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption deductionCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption accountCode = new StringOption ( ) ; @ Property ( name = "" ) private DecimalOption decCol = new DecimalOption ( ) ; @ Property ( name = "" ) private DateOption ownershipDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption ownershipFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; public long getPk ( ) { return this . pk . get ( ) ; } public void setPk ( long pk ) { this . pk . modify ( pk ) ; } public LongOption getPkOption ( ) { return this . pk ; } public void setPkOption ( LongOption pk ) { this . pk . copyFrom ( pk ) ; } public Text getDetailGroupId ( ) { return this . detailGroupId . get ( ) ; } public void setDetailGroupId ( Text detailGroupId ) { this . detailGroupId . modify ( detailGroupId ) ; } public String getDetailGroupIdAsString ( ) { return this . detailGroupId . getAsString ( ) ; } public void setDetailGroupIdAsString ( String detailGroupId ) { this . detailGroupId . modify ( detailGroupId ) ; } public StringOption getDetailGroupIdOption ( ) { return this . detailGroupId ; } public void setDetailGroupIdOption ( StringOption detailGroupId ) { this . detailGroupId . copyFrom ( detailGroupId ) ; } public Text getDetailType ( ) { return this . detailType . get ( ) ; } public void setDetailType ( Text detailType ) { this . detailType . modify ( detailType ) ; } public String getDetailTypeAsString ( ) { return this . detailType . getAsString ( ) ; } public void setDetailTypeAsString ( String detailType ) { this . detailType . modify ( detailType ) ; } public StringOption getDetailTypeOption ( ) { return this . detailType ; } public void setDetailTypeOption ( StringOption detailType ) { this . detailType . copyFrom ( detailType ) ; } public Text getDetailSenderId ( ) { return this . detailSenderId . get ( ) ; } public void setDetailSenderId ( Text detailSenderId ) { this . detailSenderId . modify ( detailSenderId ) ; } public String getDetailSenderIdAsString ( ) { return this . detailSenderId . getAsString ( ) ; } public void setDetailSenderIdAsString ( String detailSenderId ) { this . detailSenderId . modify ( detailSenderId ) ; } public StringOption getDetailSenderIdOption ( ) { return this . detailSenderId ; } public void setDetailSenderIdOption ( StringOption detailSenderId ) { this . detailSenderId . copyFrom ( detailSenderId ) ; } public Text getDetailReceiverId ( ) { return this . detailReceiverId . get ( ) ; } public void setDetailReceiverId ( Text detailReceiverId ) { this . detailReceiverId . modify ( detailReceiverId ) ; } public String getDetailReceiverIdAsString ( ) { return this . detailReceiverId . getAsString ( ) ; } public void setDetailReceiverIdAsString ( String detailReceiverId ) { this . detailReceiverId . modify ( detailReceiverId ) ; } public StringOption getDetailReceiverIdOption ( ) { return this . detailReceiverId ; } public void setDetailReceiverIdOption ( StringOption detailReceiverId ) { this . detailReceiverId . copyFrom ( detailReceiverId ) ; } public Text getDetailTestType ( ) { return this . detailTestType . get ( ) ; } public void setDetailTestType ( Text detailTestType ) { this . detailTestType . modify ( detailTestType ) ; } public String getDetailTestTypeAsString ( ) { return this . detailTestType . getAsString ( ) ; } public void setDetailTestTypeAsString ( String detailTestType ) { this . detailTestType . modify ( detailTestType ) ; } public StringOption getDetailTestTypeOption ( ) { return this . detailTestType ; } public void setDetailTestTypeOption ( StringOption detailTestType ) { this . detailTestType . copyFrom ( detailTestType ) ; } public Text getDetailStatus ( ) { return this . detailStatus . get ( ) ; } public void setDetailStatus ( Text detailStatus ) { this . detailStatus . modify ( detailStatus ) ; } public String getDetailStatusAsString ( ) { return this . detailStatus . getAsString ( ) ; } public void setDetailStatusAsString ( String detailStatus ) { this . detailStatus . modify ( detailStatus ) ; } public StringOption getDetailStatusOption ( ) { return this . detailStatus ; } public void setDetailStatusOption ( StringOption detailStatus ) { this . detailStatus . copyFrom ( detailStatus ) ; } public int getDetailLineNo ( ) { return this . detailLineNo . get ( ) ; } public void setDetailLineNo ( int detailLineNo ) { this . detailLineNo . modify ( detailLineNo ) ; } public IntOption getDetailLineNoOption ( ) { return this . detailLineNo ; } public void setDetailLineNoOption ( IntOption detailLineNo ) { this . detailLineNo . copyFrom ( detailLineNo ) ; } public Text getDeleteFlg ( ) { return this . deleteFlg . get ( ) ; } public void setDeleteFlg ( Text deleteFlg ) { this . deleteFlg . modify ( deleteFlg ) ; } public String getDeleteFlgAsString ( ) { return this . deleteFlg . getAsString ( ) ; } public void setDeleteFlgAsString ( String deleteFlg ) { this . deleteFlg . modify ( deleteFlg ) ; } public StringOption getDeleteFlgOption ( ) { return this . deleteFlg ; } public void setDeleteFlgOption ( StringOption deleteFlg ) { this . deleteFlg . copyFrom ( deleteFlg ) ; } public Date getInsertDatetime ( ) { return this . insertDatetime . get ( ) ; } public void setInsertDatetime ( Date insertDatetime ) { this . insertDatetime . modify ( insertDatetime ) ; } public DateOption getInsertDatetimeOption ( ) { return this . insertDatetime ; } public void setInsertDatetimeOption ( DateOption insertDatetime ) { this . insertDatetime . copyFrom ( insertDatetime ) ; } public Date getUpdateDatetime ( ) { return this . updateDatetime . get ( ) ; } public void setUpdateDatetime ( Date updateDatetime ) { this . updateDatetime . modify ( updateDatetime ) ; } public DateOption getUpdateDatetimeOption ( ) { return this . updateDatetime ; } public void setUpdateDatetimeOption ( DateOption updateDatetime ) { this . updateDatetime . copyFrom ( updateDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public byte getLineNo ( ) { return this . lineNo . get ( ) ; } public void setLineNo ( byte lineNo ) { this . lineNo . modify ( lineNo ) ; } public ByteOption getLineNoOption ( ) { return this . lineNo ; } public void setLineNoOption ( ByteOption lineNo ) { this . lineNo . copyFrom ( lineNo ) ; } public Date getDeliveryDate ( ) { return this . deliveryDate . get ( ) ; } public void setDeliveryDate ( Date deliveryDate ) { this . deliveryDate . modify ( deliveryDate ) ; } public DateOption getDeliveryDateOption ( ) { return this . deliveryDate ; } public void setDeliveryDateOption ( DateOption deliveryDate ) { this . deliveryDate . copyFrom ( deliveryDate ) ; } public Text getStoreCode ( ) { return this . storeCode . get ( ) ; } public void setStoreCode ( Text storeCode ) { this . storeCode . modify ( storeCode ) ; } public String getStoreCodeAsString ( ) { return this . storeCode . getAsString ( ) ; } public void setStoreCodeAsString ( String storeCode ) { this . storeCode . modify ( storeCode ) ; } public StringOption getStoreCodeOption ( ) { return this . storeCode ; } public void setStoreCodeOption ( StringOption storeCode ) { this . storeCode . copyFrom ( storeCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Text getSalesTypeCode ( ) { return this . salesTypeCode . get ( ) ; } public void setSalesTypeCode ( Text salesTypeCode ) { this . salesTypeCode . modify ( salesTypeCode ) ; } public String getSalesTypeCodeAsString ( ) { return this . salesTypeCode . getAsString ( ) ; } public void setSalesTypeCodeAsString ( String salesTypeCode ) { this . salesTypeCode . modify ( salesTypeCode ) ; } public StringOption getSalesTypeCodeOption ( ) { return this . salesTypeCode ; } public void setSalesTypeCodeOption ( StringOption salesTypeCode ) { this . salesTypeCode . copyFrom ( salesTypeCode ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getTenantCode ( ) { return this . tenantCode . get ( ) ; } public void setTenantCode ( Text tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public String getTenantCodeAsString ( ) { return this . tenantCode . getAsString ( ) ; } public void setTenantCodeAsString ( String tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public StringOption getTenantCodeOption ( ) { return this . tenantCode ; } public void setTenantCodeOption ( StringOption tenantCode ) { this . tenantCode . copyFrom ( tenantCode ) ; } public long getNetPriceTotal ( ) { return this . netPriceTotal . get ( ) ; } public void setNetPriceTotal ( long netPriceTotal ) { this . netPriceTotal . modify ( netPriceTotal ) ; } public LongOption getNetPriceTotalOption ( ) { return this . netPriceTotal ; } public void setNetPriceTotalOption ( LongOption netPriceTotal ) { this . netPriceTotal . copyFrom ( netPriceTotal ) ; } public long getSellingPriceTotal ( ) { return this . sellingPriceTotal . get ( ) ; } public void setSellingPriceTotal ( long sellingPriceTotal ) { this . sellingPriceTotal . modify ( sellingPriceTotal ) ; } public LongOption getSellingPriceTotalOption ( ) { return this . sellingPriceTotal ; } public void setSellingPriceTotalOption ( LongOption sellingPriceTotal ) { this . sellingPriceTotal . copyFrom ( sellingPriceTotal ) ; } public Text getShipmentStoreCode ( ) { return this . shipmentStoreCode . get ( ) ; } public void setShipmentStoreCode ( Text shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public String getShipmentStoreCodeAsString ( ) { return this . shipmentStoreCode . getAsString ( ) ; } public void setShipmentStoreCodeAsString ( String shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public StringOption getShipmentStoreCodeOption ( ) { return this . shipmentStoreCode ; } public void setShipmentStoreCodeOption ( StringOption shipmentStoreCode ) { this . shipmentStoreCode . copyFrom ( shipmentStoreCode ) ; } public Text getShipmentSalesTypeCode ( ) { return this . shipmentSalesTypeCode . get ( ) ; } public void setShipmentSalesTypeCode ( Text shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public String getShipmentSalesTypeCodeAsString ( ) { return this . shipmentSalesTypeCode . getAsString ( ) ; } public void setShipmentSalesTypeCodeAsString ( String shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public StringOption getShipmentSalesTypeCodeOption ( ) { return this . shipmentSalesTypeCode ; } public void setShipmentSalesTypeCodeOption ( StringOption shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . copyFrom ( shipmentSalesTypeCode ) ; } public Text getDeductionCode ( ) { return this . deductionCode . get ( ) ; } public void setDeductionCode ( Text deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public String getDeductionCodeAsString ( ) { return this . deductionCode . getAsString ( ) ; } public void setDeductionCodeAsString ( String deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public StringOption getDeductionCodeOption ( ) { return this . deductionCode ; } public void setDeductionCodeOption ( StringOption deductionCode ) { this . deductionCode . copyFrom ( deductionCode ) ; } public Text getAccountCode ( ) { return this . accountCode . get ( ) ; } public void setAccountCode ( Text accountCode ) { this . accountCode . modify ( accountCode ) ; } public String getAccountCodeAsString ( ) { return this . accountCode . getAsString ( ) ; } public void setAccountCodeAsString ( String accountCode ) { this . accountCode . modify ( accountCode ) ; } public StringOption getAccountCodeOption ( ) { return this . accountCode ; } public void setAccountCodeOption ( StringOption accountCode ) { this . accountCode . copyFrom ( accountCode ) ; } public BigDecimal getDecCol ( ) { return this . decCol . get ( ) ; } public void setDecCol ( BigDecimal decCol ) { this . decCol . modify ( decCol ) ; } public DecimalOption getDecColOption ( ) { return this . decCol ; } public void setDecColOption ( DecimalOption decCol ) { this . decCol . copyFrom ( decCol ) ; } public Date getOwnershipDate ( ) { return this . ownershipDate . get ( ) ; } public void setOwnershipDate ( Date ownershipDate ) { this . ownershipDate . modify ( ownershipDate ) ; } public DateOption getOwnershipDateOption ( ) { return this . ownershipDate ; } public void setOwnershipDateOption ( DateOption ownershipDate ) { this . ownershipDate . copyFrom ( ownershipDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public Text getOwnershipFlag ( ) { return this . ownershipFlag . get ( ) ; } public void setOwnershipFlag ( Text ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public String getOwnershipFlagAsString ( ) { return this . ownershipFlag . getAsString ( ) ; } public void setOwnershipFlagAsString ( String ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public StringOption getOwnershipFlagOption ( ) { return this . ownershipFlag ; } public void setOwnershipFlagOption ( StringOption ownershipFlag ) { this . ownershipFlag . copyFrom ( ownershipFlag ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public void copyFrom ( Foo source ) { this . pk . copyFrom ( source . pk ) ; this . detailGroupId . copyFrom ( source . detailGroupId ) ; this . detailType . copyFrom ( source . detailType ) ; this . detailSenderId . copyFrom ( source . detailSenderId ) ; this . detailReceiverId . copyFrom ( source . detailReceiverId ) ; this . detailTestType . copyFrom ( source . detailTestType ) ; this . detailStatus . copyFrom ( source . detailStatus ) ; this . detailLineNo . copyFrom ( source . detailLineNo ) ; this . deleteFlg . copyFrom ( source . deleteFlg ) ; this . insertDatetime . copyFrom ( source . insertDatetime ) ; this . updateDatetime . copyFrom ( source . updateDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . lineNo . copyFrom ( source . lineNo ) ; this . deliveryDate . copyFrom ( source . deliveryDate ) ; this . storeCode . copyFrom ( source . storeCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . salesTypeCode . copyFrom ( source . salesTypeCode ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . tenantCode . copyFrom ( source . tenantCode ) ; this . netPriceTotal . copyFrom ( source . netPriceTotal ) ; this . sellingPriceTotal . copyFrom ( source . sellingPriceTotal ) ; this . shipmentStoreCode . copyFrom ( source . shipmentStoreCode ) ; this . shipmentSalesTypeCode . copyFrom ( source . shipmentSalesTypeCode ) ; this . deductionCode . copyFrom ( source . deductionCode ) ; this . accountCode . copyFrom ( source . accountCode ) ; this . decCol . copyFrom ( source . decCol ) ; this . ownershipDate . copyFrom ( source . ownershipDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . ownershipFlag . copyFrom ( source . ownershipFlag ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { pk . write ( out ) ; detailGroupId . write ( out ) ; detailType . write ( out ) ; detailSenderId . write ( out ) ; detailReceiverId . write ( out ) ; detailTestType . write ( out ) ; detailStatus . write ( out ) ; detailLineNo . write ( out ) ; deleteFlg . write ( out ) ; insertDatetime . write ( out ) ; updateDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; lineNo . write ( out ) ; deliveryDate . write ( out ) ; storeCode . write ( out ) ; buyerCode . write ( out ) ; salesTypeCode . write ( out ) ; sellerCode . write ( out ) ; tenantCode . write ( out ) ; netPriceTotal . write ( out ) ; sellingPriceTotal . write ( out ) ; shipmentStoreCode . write ( out ) ; shipmentSalesTypeCode . write ( out ) ; deductionCode . write ( out ) ; accountCode . write ( out ) ; decCol . write ( out ) ; ownershipDate . write ( out ) ; cutoffDate . write ( out ) ; payoutDate . write ( out ) ; ownershipFlag . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { pk . readFields ( in ) ; detailGroupId . readFields ( in ) ; detailType . readFields ( in ) ; detailSenderId . readFields ( in ) ; detailReceiverId . readFields ( in ) ; detailTestType . readFields ( in ) ; detailStatus . readFields ( in ) ; detailLineNo . readFields ( in ) ; deleteFlg . readFields ( in ) ; insertDatetime . readFields ( in ) ; updateDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; lineNo . readFields ( in ) ; deliveryDate . readFields ( in ) ; storeCode . readFields ( in ) ; buyerCode . readFields ( in ) ; salesTypeCode . readFields ( in ) ; sellerCode . readFields ( in ) ; tenantCode . readFields ( in ) ; netPriceTotal . readFields ( in ) ; sellingPriceTotal . readFields ( in ) ; shipmentStoreCode . readFields ( in ) ; shipmentSalesTypeCode . readFields ( in ) ; deductionCode . readFields ( in ) ; accountCode . readFields ( in ) ; decCol . readFields ( in ) ; ownershipDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; ownershipFlag . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + pk . hashCode ( ) ; result = prime * result + detailGroupId . hashCode ( ) ; result = prime * result + detailType . hashCode ( ) ; result = prime * result + detailSenderId . hashCode ( ) ; result = prime * result + detailReceiverId . hashCode ( ) ; result = prime * result + detailTestType . hashCode ( ) ; result = prime * result + detailStatus . hashCode ( ) ; result = prime * result + detailLineNo . hashCode ( ) ; result = prime * result + deleteFlg . hashCode ( ) ; result = prime * result + insertDatetime . hashCode ( ) ; result = prime * result + updateDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + lineNo . hashCode ( ) ; result = prime * result + deliveryDate . hashCode ( ) ; result = prime * result + storeCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + salesTypeCode . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + tenantCode . hashCode ( ) ; result = prime * result + netPriceTotal . hashCode ( ) ; result = prime * result + sellingPriceTotal . hashCode ( ) ; result = prime * result + shipmentStoreCode . hashCode ( ) ; result = prime * result + shipmentSalesTypeCode . hashCode ( ) ; result = prime * result + deductionCode . hashCode ( ) ; result = prime * result + accountCode . hashCode ( ) ; result = prime * result + decCol . hashCode ( ) ; result = prime * result + ownershipDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + ownershipFlag . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Foo other = ( Foo ) obj ; if ( this . pk . equals ( other . pk ) == false ) { return false ; } if ( this . detailGroupId . equals ( other . detailGroupId ) == false ) { return false ; } if ( this . detailType . equals ( other . detailType ) == false ) { return false ; } if ( this . detailSenderId . equals ( other . detailSenderId ) == false ) { return false ; } if ( this . detailReceiverId . equals ( other . detailReceiverId ) == false ) { return false ; } if ( this . detailTestType . equals ( other . detailTestType ) == false ) { return false ; } if ( this . detailStatus . equals ( other . detailStatus ) == false ) { return false ; } if ( this . detailLineNo . equals ( other . detailLineNo ) == false ) { return false ; } if ( this . deleteFlg . equals ( other . deleteFlg ) == false ) { return false ; } if ( this . insertDatetime . equals ( other . insertDatetime ) == false ) { return false ; } if ( this . updateDatetime . equals ( other . updateDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . lineNo . equals ( other . lineNo ) == false ) { return false ; } if ( this . deliveryDate . equals ( other . deliveryDate ) == false ) { return false ; } if ( this . storeCode . equals ( other . storeCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . salesTypeCode . equals ( other . salesTypeCode ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . tenantCode . equals ( other . tenantCode ) == false ) { return false ; } if ( this . netPriceTotal . equals ( other . netPriceTotal ) == false ) { return false ; } if ( this . sellingPriceTotal . equals ( other . sellingPriceTotal ) == false ) { return false ; } if ( this . shipmentStoreCode . equals ( other . shipmentStoreCode ) == false ) { return false ; } if ( this . shipmentSalesTypeCode . equals ( other . shipmentSalesTypeCode ) == false ) { return false ; } if ( this . deductionCode . equals ( other . deductionCode ) == false ) { return false ; } if ( this . accountCode . equals ( other . accountCode ) == false ) { return false ; } if ( this . decCol . equals ( other . decCol ) == false ) { return false ; } if ( this . ownershipDate . equals ( other . ownershipDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . ownershipFlag . equals ( other . ownershipFlag ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } return true ; } } package test . modelgen . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . math . BigDecimal ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ TableModel ( name = "" , primary = { } ) @ Generated ( "" ) @ SuppressWarnings ( "" ) public class AllTypesWNoerr implements Writable { @ Property ( name = "" ) private StringOption cTag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cComment = new StringOption ( ) ; @ Property ( name = "" ) private LongOption cBigint = new LongOption ( ) ; @ Property ( name = "" ) private IntOption cInt = new IntOption ( ) ; @ Property ( name = "" ) private ShortOption cSmallint = new ShortOption ( ) ; @ Property ( name = "" ) private ByteOption cTinyint = new ByteOption ( ) ; @ Property ( name = "" ) private StringOption cChar = new StringOption ( ) ; @ Property ( name = "" ) private DateTimeOption cDatetime = new DateTimeOption ( ) ; @ Property ( name = "" ) private DateOption cDate = new DateOption ( ) ; @ Property ( name = "" ) private DecimalOption cDecimal200 = new DecimalOption ( ) ; @ Property ( name = "" ) private DecimalOption cDecimal255 = new DecimalOption ( ) ; @ Property ( name = "" ) private StringOption cVchar = new StringOption ( ) ; public Text getCTag ( ) { return this . cTag . get ( ) ; } public void setCTag ( Text cTag ) { this . cTag . modify ( cTag ) ; } public String getCTagAsString ( ) { return this . cTag . getAsString ( ) ; } public void setCTagAsString ( String cTag ) { this . cTag . modify ( cTag ) ; } public StringOption getCTagOption ( ) { return this . cTag ; } public void setCTagOption ( StringOption cTag ) { this . cTag . copyFrom ( cTag ) ; } public Text getCComment ( ) { return this . cComment . get ( ) ; } public void setCComment ( Text cComment ) { this . cComment . modify ( cComment ) ; } public String getCCommentAsString ( ) { return this . cComment . getAsString ( ) ; } public void setCCommentAsString ( String cComment ) { this . cComment . modify ( cComment ) ; } public StringOption getCCommentOption ( ) { return this . cComment ; } public void setCCommentOption ( StringOption cComment ) { this . cComment . copyFrom ( cComment ) ; } public long getCBigint ( ) { return this . cBigint . get ( ) ; } public void setCBigint ( long cBigint ) { this . cBigint . modify ( cBigint ) ; } public LongOption getCBigintOption ( ) { return this . cBigint ; } public void setCBigintOption ( LongOption cBigint ) { this . cBigint . copyFrom ( cBigint ) ; } public int getCInt ( ) { return this . cInt . get ( ) ; } public void setCInt ( int cInt ) { this . cInt . modify ( cInt ) ; } public IntOption getCIntOption ( ) { return this . cInt ; } public void setCIntOption ( IntOption cInt ) { this . cInt . copyFrom ( cInt ) ; } public short getCSmallint ( ) { return this . cSmallint . get ( ) ; } public void setCSmallint ( short cSmallint ) { this . cSmallint . modify ( cSmallint ) ; } public ShortOption getCSmallintOption ( ) { return this . cSmallint ; } public void setCSmallintOption ( ShortOption cSmallint ) { this . cSmallint . copyFrom ( cSmallint ) ; } public byte getCTinyint ( ) { return this . cTinyint . get ( ) ; } public void setCTinyint ( byte cTinyint ) { this . cTinyint . modify ( cTinyint ) ; } public ByteOption getCTinyintOption ( ) { return this . cTinyint ; } public void setCTinyintOption ( ByteOption cTinyint ) { this . cTinyint . copyFrom ( cTinyint ) ; } public Text getCChar ( ) { return this . cChar . get ( ) ; } public void setCChar ( Text cChar ) { this . cChar . modify ( cChar ) ; } public String getCCharAsString ( ) { return this . cChar . getAsString ( ) ; } public void setCCharAsString ( String cChar ) { this . cChar . modify ( cChar ) ; } public StringOption getCCharOption ( ) { return this . cChar ; } public void setCCharOption ( StringOption cChar ) { this . cChar . copyFrom ( cChar ) ; } public DateTime getCDatetime ( ) { return this . cDatetime . get ( ) ; } public void setCDatetime ( DateTime cDatetime ) { this . cDatetime . modify ( cDatetime ) ; } public DateTimeOption getCDatetimeOption ( ) { return this . cDatetime ; } public void setCDatetimeOption ( DateTimeOption cDatetime ) { this . cDatetime . copyFrom ( cDatetime ) ; } public Date getCDate ( ) { return this . cDate . get ( ) ; } public void setCDate ( Date cDate ) { this . cDate . modify ( cDate ) ; } public DateOption getCDateOption ( ) { return this . cDate ; } public void setCDateOption ( DateOption cDate ) { this . cDate . copyFrom ( cDate ) ; } public BigDecimal getCDecimal200 ( ) { return this . cDecimal200 . get ( ) ; } public void setCDecimal200 ( BigDecimal cDecimal200 ) { this . cDecimal200 . modify ( cDecimal200 ) ; } public DecimalOption getCDecimal200Option ( ) { return this . cDecimal200 ; } public void setCDecimal200Option ( DecimalOption cDecimal200 ) { this . cDecimal200 . copyFrom ( cDecimal200 ) ; } public BigDecimal getCDecimal255 ( ) { return this . cDecimal255 . get ( ) ; } public void setCDecimal255 ( BigDecimal cDecimal255 ) { this . cDecimal255 . modify ( cDecimal255 ) ; } public DecimalOption getCDecimal255Option ( ) { return this . cDecimal255 ; } public void setCDecimal255Option ( DecimalOption cDecimal255 ) { this . cDecimal255 . copyFrom ( cDecimal255 ) ; } public Text getCVchar ( ) { return this . cVchar . get ( ) ; } public void setCVchar ( Text cVchar ) { this . cVchar . modify ( cVchar ) ; } public String getCVcharAsString ( ) { return this . cVchar . getAsString ( ) ; } public void setCVcharAsString ( String cVchar ) { this . cVchar . modify ( cVchar ) ; } public StringOption getCVcharOption ( ) { return this . cVchar ; } public void setCVcharOption ( StringOption cVchar ) { this . cVchar . copyFrom ( cVchar ) ; } public void copyFrom ( AllTypesWNoerr source ) { this . cTag . copyFrom ( source . cTag ) ; this . cComment . copyFrom ( source . cComment ) ; this . cBigint . copyFrom ( source . cBigint ) ; this . cInt . copyFrom ( source . cInt ) ; this . cSmallint . copyFrom ( source . cSmallint ) ; this . cTinyint . copyFrom ( source . cTinyint ) ; this . cChar . copyFrom ( source . cChar ) ; this . cDatetime . copyFrom ( source . cDatetime ) ; this . cDate . copyFrom ( source . cDate ) ; this . cDecimal200 . copyFrom ( source . cDecimal200 ) ; this . cDecimal255 . copyFrom ( source . cDecimal255 ) ; this . cVchar . copyFrom ( source . cVchar ) ; } @ Override public void write ( DataOutput out ) throws IOException { cTag . write ( out ) ; cComment . write ( out ) ; cBigint . write ( out ) ; cInt . write ( out ) ; cSmallint . write ( out ) ; cTinyint . write ( out ) ; cChar . write ( out ) ; cDatetime . write ( out ) ; cDate . write ( out ) ; cDecimal200 . write ( out ) ; cDecimal255 . write ( out ) ; cVchar . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { cTag . readFields ( in ) ; cComment . readFields ( in ) ; cBigint . readFields ( in ) ; cInt . readFields ( in ) ; cSmallint . readFields ( in ) ; cTinyint . readFields ( in ) ; cChar . readFields ( in ) ; cDatetime . readFields ( in ) ; cDate . readFields ( in ) ; cDecimal200 . readFields ( in ) ; cDecimal255 . readFields ( in ) ; cVchar . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + cTag . hashCode ( ) ; result = prime * result + cComment . hashCode ( ) ; result = prime * result + cBigint . hashCode ( ) ; result = prime * result + cInt . hashCode ( ) ; result = prime * result + cSmallint . hashCode ( ) ; result = prime * result + cTinyint . hashCode ( ) ; result = prime * result + cChar . hashCode ( ) ; result = prime * result + cDatetime . hashCode ( ) ; result = prime * result + cDate . hashCode ( ) ; result = prime * result + cDecimal200 . hashCode ( ) ; result = prime * result + cDecimal255 . hashCode ( ) ; result = prime * result + cVchar . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } AllTypesWNoerr other = ( AllTypesWNoerr ) obj ; if ( this . cTag . equals ( other . cTag ) == false ) { return false ; } if ( this . cComment . equals ( other . cComment ) == false ) { return false ; } if ( this . cBigint . equals ( other . cBigint ) == false ) { return false ; } if ( this . cInt . equals ( other . cInt ) == false ) { return false ; } if ( this . cSmallint . equals ( other . cSmallint ) == false ) { return false ; } if ( this . cTinyint . equals ( other . cTinyint ) == false ) { return false ; } if ( this . cChar . equals ( other . cChar ) == false ) { return false ; } if ( this . cDatetime . equals ( other . cDatetime ) == false ) { return false ; } if ( this . cDate . equals ( other . cDate ) == false ) { return false ; } if ( this . cDecimal200 . equals ( other . cDecimal200 ) == false ) { return false ; } if ( this . cDecimal255 . equals ( other . cDecimal255 ) == false ) { return false ; } if ( this . cVchar . equals ( other . cVchar ) == false ) { return false ; } return true ; } } package test . modelgen . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . math . BigDecimal ; import javax . annotation . Generated ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . vocabulary . model . Property ; import com . asakusafw . vocabulary . model . TableModel ; @ TableModel ( name = "" , primary = { } ) @ Generated ( "" ) @ SuppressWarnings ( "" ) public class Bar implements Writable { @ Property ( name = "" ) private LongOption pk = new LongOption ( ) ; @ Property ( name = "" ) private StringOption detailGroupId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailSenderId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailReceiverId = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailTestType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption detailStatus = new StringOption ( ) ; @ Property ( name = "" ) private IntOption detailLineNo = new IntOption ( ) ; @ Property ( name = "" ) private StringOption deleteFlg = new StringOption ( ) ; @ Property ( name = "" ) private DateOption insertDatetime = new DateOption ( ) ; @ Property ( name = "" ) private DateOption updateDatetime = new DateOption ( ) ; @ Property ( name = "" ) private StringOption purchaseNo = new StringOption ( ) ; @ Property ( name = "" ) private StringOption purchaseType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeType = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tradeNo = new StringOption ( ) ; @ Property ( name = "" ) private ByteOption lineNo = new ByteOption ( ) ; @ Property ( name = "" ) private DateOption deliveryDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption storeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption buyerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption salesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption sellerCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption tenantCode = new StringOption ( ) ; @ Property ( name = "" ) private LongOption netPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private LongOption sellingPriceTotal = new LongOption ( ) ; @ Property ( name = "" ) private StringOption shipmentStoreCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption shipmentSalesTypeCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption deductionCode = new StringOption ( ) ; @ Property ( name = "" ) private StringOption accountCode = new StringOption ( ) ; @ Property ( name = "" ) private DecimalOption decCol = new DecimalOption ( ) ; @ Property ( name = "" ) private DateOption ownershipDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption cutoffDate = new DateOption ( ) ; @ Property ( name = "" ) private DateOption payoutDate = new DateOption ( ) ; @ Property ( name = "" ) private StringOption ownershipFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption cutoffFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption payoutFlag = new StringOption ( ) ; @ Property ( name = "" ) private StringOption disposeNo = new StringOption ( ) ; @ Property ( name = "" ) private DateOption disposeDate = new DateOption ( ) ; public long getPk ( ) { return this . pk . get ( ) ; } public void setPk ( long pk ) { this . pk . modify ( pk ) ; } public LongOption getPkOption ( ) { return this . pk ; } public void setPkOption ( LongOption pk ) { this . pk . copyFrom ( pk ) ; } public Text getDetailGroupId ( ) { return this . detailGroupId . get ( ) ; } public void setDetailGroupId ( Text detailGroupId ) { this . detailGroupId . modify ( detailGroupId ) ; } public String getDetailGroupIdAsString ( ) { return this . detailGroupId . getAsString ( ) ; } public void setDetailGroupIdAsString ( String detailGroupId ) { this . detailGroupId . modify ( detailGroupId ) ; } public StringOption getDetailGroupIdOption ( ) { return this . detailGroupId ; } public void setDetailGroupIdOption ( StringOption detailGroupId ) { this . detailGroupId . copyFrom ( detailGroupId ) ; } public Text getDetailType ( ) { return this . detailType . get ( ) ; } public void setDetailType ( Text detailType ) { this . detailType . modify ( detailType ) ; } public String getDetailTypeAsString ( ) { return this . detailType . getAsString ( ) ; } public void setDetailTypeAsString ( String detailType ) { this . detailType . modify ( detailType ) ; } public StringOption getDetailTypeOption ( ) { return this . detailType ; } public void setDetailTypeOption ( StringOption detailType ) { this . detailType . copyFrom ( detailType ) ; } public Text getDetailSenderId ( ) { return this . detailSenderId . get ( ) ; } public void setDetailSenderId ( Text detailSenderId ) { this . detailSenderId . modify ( detailSenderId ) ; } public String getDetailSenderIdAsString ( ) { return this . detailSenderId . getAsString ( ) ; } public void setDetailSenderIdAsString ( String detailSenderId ) { this . detailSenderId . modify ( detailSenderId ) ; } public StringOption getDetailSenderIdOption ( ) { return this . detailSenderId ; } public void setDetailSenderIdOption ( StringOption detailSenderId ) { this . detailSenderId . copyFrom ( detailSenderId ) ; } public Text getDetailReceiverId ( ) { return this . detailReceiverId . get ( ) ; } public void setDetailReceiverId ( Text detailReceiverId ) { this . detailReceiverId . modify ( detailReceiverId ) ; } public String getDetailReceiverIdAsString ( ) { return this . detailReceiverId . getAsString ( ) ; } public void setDetailReceiverIdAsString ( String detailReceiverId ) { this . detailReceiverId . modify ( detailReceiverId ) ; } public StringOption getDetailReceiverIdOption ( ) { return this . detailReceiverId ; } public void setDetailReceiverIdOption ( StringOption detailReceiverId ) { this . detailReceiverId . copyFrom ( detailReceiverId ) ; } public Text getDetailTestType ( ) { return this . detailTestType . get ( ) ; } public void setDetailTestType ( Text detailTestType ) { this . detailTestType . modify ( detailTestType ) ; } public String getDetailTestTypeAsString ( ) { return this . detailTestType . getAsString ( ) ; } public void setDetailTestTypeAsString ( String detailTestType ) { this . detailTestType . modify ( detailTestType ) ; } public StringOption getDetailTestTypeOption ( ) { return this . detailTestType ; } public void setDetailTestTypeOption ( StringOption detailTestType ) { this . detailTestType . copyFrom ( detailTestType ) ; } public Text getDetailStatus ( ) { return this . detailStatus . get ( ) ; } public void setDetailStatus ( Text detailStatus ) { this . detailStatus . modify ( detailStatus ) ; } public String getDetailStatusAsString ( ) { return this . detailStatus . getAsString ( ) ; } public void setDetailStatusAsString ( String detailStatus ) { this . detailStatus . modify ( detailStatus ) ; } public StringOption getDetailStatusOption ( ) { return this . detailStatus ; } public void setDetailStatusOption ( StringOption detailStatus ) { this . detailStatus . copyFrom ( detailStatus ) ; } public int getDetailLineNo ( ) { return this . detailLineNo . get ( ) ; } public void setDetailLineNo ( int detailLineNo ) { this . detailLineNo . modify ( detailLineNo ) ; } public IntOption getDetailLineNoOption ( ) { return this . detailLineNo ; } public void setDetailLineNoOption ( IntOption detailLineNo ) { this . detailLineNo . copyFrom ( detailLineNo ) ; } public Text getDeleteFlg ( ) { return this . deleteFlg . get ( ) ; } public void setDeleteFlg ( Text deleteFlg ) { this . deleteFlg . modify ( deleteFlg ) ; } public String getDeleteFlgAsString ( ) { return this . deleteFlg . getAsString ( ) ; } public void setDeleteFlgAsString ( String deleteFlg ) { this . deleteFlg . modify ( deleteFlg ) ; } public StringOption getDeleteFlgOption ( ) { return this . deleteFlg ; } public void setDeleteFlgOption ( StringOption deleteFlg ) { this . deleteFlg . copyFrom ( deleteFlg ) ; } public Date getInsertDatetime ( ) { return this . insertDatetime . get ( ) ; } public void setInsertDatetime ( Date insertDatetime ) { this . insertDatetime . modify ( insertDatetime ) ; } public DateOption getInsertDatetimeOption ( ) { return this . insertDatetime ; } public void setInsertDatetimeOption ( DateOption insertDatetime ) { this . insertDatetime . copyFrom ( insertDatetime ) ; } public Date getUpdateDatetime ( ) { return this . updateDatetime . get ( ) ; } public void setUpdateDatetime ( Date updateDatetime ) { this . updateDatetime . modify ( updateDatetime ) ; } public DateOption getUpdateDatetimeOption ( ) { return this . updateDatetime ; } public void setUpdateDatetimeOption ( DateOption updateDatetime ) { this . updateDatetime . copyFrom ( updateDatetime ) ; } public Text getPurchaseNo ( ) { return this . purchaseNo . get ( ) ; } public void setPurchaseNo ( Text purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public String getPurchaseNoAsString ( ) { return this . purchaseNo . getAsString ( ) ; } public void setPurchaseNoAsString ( String purchaseNo ) { this . purchaseNo . modify ( purchaseNo ) ; } public StringOption getPurchaseNoOption ( ) { return this . purchaseNo ; } public void setPurchaseNoOption ( StringOption purchaseNo ) { this . purchaseNo . copyFrom ( purchaseNo ) ; } public Text getPurchaseType ( ) { return this . purchaseType . get ( ) ; } public void setPurchaseType ( Text purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public String getPurchaseTypeAsString ( ) { return this . purchaseType . getAsString ( ) ; } public void setPurchaseTypeAsString ( String purchaseType ) { this . purchaseType . modify ( purchaseType ) ; } public StringOption getPurchaseTypeOption ( ) { return this . purchaseType ; } public void setPurchaseTypeOption ( StringOption purchaseType ) { this . purchaseType . copyFrom ( purchaseType ) ; } public Text getTradeType ( ) { return this . tradeType . get ( ) ; } public void setTradeType ( Text tradeType ) { this . tradeType . modify ( tradeType ) ; } public String getTradeTypeAsString ( ) { return this . tradeType . getAsString ( ) ; } public void setTradeTypeAsString ( String tradeType ) { this . tradeType . modify ( tradeType ) ; } public StringOption getTradeTypeOption ( ) { return this . tradeType ; } public void setTradeTypeOption ( StringOption tradeType ) { this . tradeType . copyFrom ( tradeType ) ; } public Text getTradeNo ( ) { return this . tradeNo . get ( ) ; } public void setTradeNo ( Text tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public String getTradeNoAsString ( ) { return this . tradeNo . getAsString ( ) ; } public void setTradeNoAsString ( String tradeNo ) { this . tradeNo . modify ( tradeNo ) ; } public StringOption getTradeNoOption ( ) { return this . tradeNo ; } public void setTradeNoOption ( StringOption tradeNo ) { this . tradeNo . copyFrom ( tradeNo ) ; } public byte getLineNo ( ) { return this . lineNo . get ( ) ; } public void setLineNo ( byte lineNo ) { this . lineNo . modify ( lineNo ) ; } public ByteOption getLineNoOption ( ) { return this . lineNo ; } public void setLineNoOption ( ByteOption lineNo ) { this . lineNo . copyFrom ( lineNo ) ; } public Date getDeliveryDate ( ) { return this . deliveryDate . get ( ) ; } public void setDeliveryDate ( Date deliveryDate ) { this . deliveryDate . modify ( deliveryDate ) ; } public DateOption getDeliveryDateOption ( ) { return this . deliveryDate ; } public void setDeliveryDateOption ( DateOption deliveryDate ) { this . deliveryDate . copyFrom ( deliveryDate ) ; } public Text getStoreCode ( ) { return this . storeCode . get ( ) ; } public void setStoreCode ( Text storeCode ) { this . storeCode . modify ( storeCode ) ; } public String getStoreCodeAsString ( ) { return this . storeCode . getAsString ( ) ; } public void setStoreCodeAsString ( String storeCode ) { this . storeCode . modify ( storeCode ) ; } public StringOption getStoreCodeOption ( ) { return this . storeCode ; } public void setStoreCodeOption ( StringOption storeCode ) { this . storeCode . copyFrom ( storeCode ) ; } public Text getBuyerCode ( ) { return this . buyerCode . get ( ) ; } public void setBuyerCode ( Text buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public String getBuyerCodeAsString ( ) { return this . buyerCode . getAsString ( ) ; } public void setBuyerCodeAsString ( String buyerCode ) { this . buyerCode . modify ( buyerCode ) ; } public StringOption getBuyerCodeOption ( ) { return this . buyerCode ; } public void setBuyerCodeOption ( StringOption buyerCode ) { this . buyerCode . copyFrom ( buyerCode ) ; } public Text getSalesTypeCode ( ) { return this . salesTypeCode . get ( ) ; } public void setSalesTypeCode ( Text salesTypeCode ) { this . salesTypeCode . modify ( salesTypeCode ) ; } public String getSalesTypeCodeAsString ( ) { return this . salesTypeCode . getAsString ( ) ; } public void setSalesTypeCodeAsString ( String salesTypeCode ) { this . salesTypeCode . modify ( salesTypeCode ) ; } public StringOption getSalesTypeCodeOption ( ) { return this . salesTypeCode ; } public void setSalesTypeCodeOption ( StringOption salesTypeCode ) { this . salesTypeCode . copyFrom ( salesTypeCode ) ; } public Text getSellerCode ( ) { return this . sellerCode . get ( ) ; } public void setSellerCode ( Text sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public String getSellerCodeAsString ( ) { return this . sellerCode . getAsString ( ) ; } public void setSellerCodeAsString ( String sellerCode ) { this . sellerCode . modify ( sellerCode ) ; } public StringOption getSellerCodeOption ( ) { return this . sellerCode ; } public void setSellerCodeOption ( StringOption sellerCode ) { this . sellerCode . copyFrom ( sellerCode ) ; } public Text getTenantCode ( ) { return this . tenantCode . get ( ) ; } public void setTenantCode ( Text tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public String getTenantCodeAsString ( ) { return this . tenantCode . getAsString ( ) ; } public void setTenantCodeAsString ( String tenantCode ) { this . tenantCode . modify ( tenantCode ) ; } public StringOption getTenantCodeOption ( ) { return this . tenantCode ; } public void setTenantCodeOption ( StringOption tenantCode ) { this . tenantCode . copyFrom ( tenantCode ) ; } public long getNetPriceTotal ( ) { return this . netPriceTotal . get ( ) ; } public void setNetPriceTotal ( long netPriceTotal ) { this . netPriceTotal . modify ( netPriceTotal ) ; } public LongOption getNetPriceTotalOption ( ) { return this . netPriceTotal ; } public void setNetPriceTotalOption ( LongOption netPriceTotal ) { this . netPriceTotal . copyFrom ( netPriceTotal ) ; } public long getSellingPriceTotal ( ) { return this . sellingPriceTotal . get ( ) ; } public void setSellingPriceTotal ( long sellingPriceTotal ) { this . sellingPriceTotal . modify ( sellingPriceTotal ) ; } public LongOption getSellingPriceTotalOption ( ) { return this . sellingPriceTotal ; } public void setSellingPriceTotalOption ( LongOption sellingPriceTotal ) { this . sellingPriceTotal . copyFrom ( sellingPriceTotal ) ; } public Text getShipmentStoreCode ( ) { return this . shipmentStoreCode . get ( ) ; } public void setShipmentStoreCode ( Text shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public String getShipmentStoreCodeAsString ( ) { return this . shipmentStoreCode . getAsString ( ) ; } public void setShipmentStoreCodeAsString ( String shipmentStoreCode ) { this . shipmentStoreCode . modify ( shipmentStoreCode ) ; } public StringOption getShipmentStoreCodeOption ( ) { return this . shipmentStoreCode ; } public void setShipmentStoreCodeOption ( StringOption shipmentStoreCode ) { this . shipmentStoreCode . copyFrom ( shipmentStoreCode ) ; } public Text getShipmentSalesTypeCode ( ) { return this . shipmentSalesTypeCode . get ( ) ; } public void setShipmentSalesTypeCode ( Text shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public String getShipmentSalesTypeCodeAsString ( ) { return this . shipmentSalesTypeCode . getAsString ( ) ; } public void setShipmentSalesTypeCodeAsString ( String shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . modify ( shipmentSalesTypeCode ) ; } public StringOption getShipmentSalesTypeCodeOption ( ) { return this . shipmentSalesTypeCode ; } public void setShipmentSalesTypeCodeOption ( StringOption shipmentSalesTypeCode ) { this . shipmentSalesTypeCode . copyFrom ( shipmentSalesTypeCode ) ; } public Text getDeductionCode ( ) { return this . deductionCode . get ( ) ; } public void setDeductionCode ( Text deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public String getDeductionCodeAsString ( ) { return this . deductionCode . getAsString ( ) ; } public void setDeductionCodeAsString ( String deductionCode ) { this . deductionCode . modify ( deductionCode ) ; } public StringOption getDeductionCodeOption ( ) { return this . deductionCode ; } public void setDeductionCodeOption ( StringOption deductionCode ) { this . deductionCode . copyFrom ( deductionCode ) ; } public Text getAccountCode ( ) { return this . accountCode . get ( ) ; } public void setAccountCode ( Text accountCode ) { this . accountCode . modify ( accountCode ) ; } public String getAccountCodeAsString ( ) { return this . accountCode . getAsString ( ) ; } public void setAccountCodeAsString ( String accountCode ) { this . accountCode . modify ( accountCode ) ; } public StringOption getAccountCodeOption ( ) { return this . accountCode ; } public void setAccountCodeOption ( StringOption accountCode ) { this . accountCode . copyFrom ( accountCode ) ; } public BigDecimal getDecCol ( ) { return this . decCol . get ( ) ; } public void setDecCol ( BigDecimal decCol ) { this . decCol . modify ( decCol ) ; } public DecimalOption getDecColOption ( ) { return this . decCol ; } public void setDecColOption ( DecimalOption decCol ) { this . decCol . copyFrom ( decCol ) ; } public Date getOwnershipDate ( ) { return this . ownershipDate . get ( ) ; } public void setOwnershipDate ( Date ownershipDate ) { this . ownershipDate . modify ( ownershipDate ) ; } public DateOption getOwnershipDateOption ( ) { return this . ownershipDate ; } public void setOwnershipDateOption ( DateOption ownershipDate ) { this . ownershipDate . copyFrom ( ownershipDate ) ; } public Date getCutoffDate ( ) { return this . cutoffDate . get ( ) ; } public void setCutoffDate ( Date cutoffDate ) { this . cutoffDate . modify ( cutoffDate ) ; } public DateOption getCutoffDateOption ( ) { return this . cutoffDate ; } public void setCutoffDateOption ( DateOption cutoffDate ) { this . cutoffDate . copyFrom ( cutoffDate ) ; } public Date getPayoutDate ( ) { return this . payoutDate . get ( ) ; } public void setPayoutDate ( Date payoutDate ) { this . payoutDate . modify ( payoutDate ) ; } public DateOption getPayoutDateOption ( ) { return this . payoutDate ; } public void setPayoutDateOption ( DateOption payoutDate ) { this . payoutDate . copyFrom ( payoutDate ) ; } public Text getOwnershipFlag ( ) { return this . ownershipFlag . get ( ) ; } public void setOwnershipFlag ( Text ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public String getOwnershipFlagAsString ( ) { return this . ownershipFlag . getAsString ( ) ; } public void setOwnershipFlagAsString ( String ownershipFlag ) { this . ownershipFlag . modify ( ownershipFlag ) ; } public StringOption getOwnershipFlagOption ( ) { return this . ownershipFlag ; } public void setOwnershipFlagOption ( StringOption ownershipFlag ) { this . ownershipFlag . copyFrom ( ownershipFlag ) ; } public Text getCutoffFlag ( ) { return this . cutoffFlag . get ( ) ; } public void setCutoffFlag ( Text cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public String getCutoffFlagAsString ( ) { return this . cutoffFlag . getAsString ( ) ; } public void setCutoffFlagAsString ( String cutoffFlag ) { this . cutoffFlag . modify ( cutoffFlag ) ; } public StringOption getCutoffFlagOption ( ) { return this . cutoffFlag ; } public void setCutoffFlagOption ( StringOption cutoffFlag ) { this . cutoffFlag . copyFrom ( cutoffFlag ) ; } public Text getPayoutFlag ( ) { return this . payoutFlag . get ( ) ; } public void setPayoutFlag ( Text payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public String getPayoutFlagAsString ( ) { return this . payoutFlag . getAsString ( ) ; } public void setPayoutFlagAsString ( String payoutFlag ) { this . payoutFlag . modify ( payoutFlag ) ; } public StringOption getPayoutFlagOption ( ) { return this . payoutFlag ; } public void setPayoutFlagOption ( StringOption payoutFlag ) { this . payoutFlag . copyFrom ( payoutFlag ) ; } public Text getDisposeNo ( ) { return this . disposeNo . get ( ) ; } public void setDisposeNo ( Text disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public String getDisposeNoAsString ( ) { return this . disposeNo . getAsString ( ) ; } public void setDisposeNoAsString ( String disposeNo ) { this . disposeNo . modify ( disposeNo ) ; } public StringOption getDisposeNoOption ( ) { return this . disposeNo ; } public void setDisposeNoOption ( StringOption disposeNo ) { this . disposeNo . copyFrom ( disposeNo ) ; } public Date getDisposeDate ( ) { return this . disposeDate . get ( ) ; } public void setDisposeDate ( Date disposeDate ) { this . disposeDate . modify ( disposeDate ) ; } public DateOption getDisposeDateOption ( ) { return this . disposeDate ; } public void setDisposeDateOption ( DateOption disposeDate ) { this . disposeDate . copyFrom ( disposeDate ) ; } public void copyFrom ( Bar source ) { this . pk . copyFrom ( source . pk ) ; this . detailGroupId . copyFrom ( source . detailGroupId ) ; this . detailType . copyFrom ( source . detailType ) ; this . detailSenderId . copyFrom ( source . detailSenderId ) ; this . detailReceiverId . copyFrom ( source . detailReceiverId ) ; this . detailTestType . copyFrom ( source . detailTestType ) ; this . detailStatus . copyFrom ( source . detailStatus ) ; this . detailLineNo . copyFrom ( source . detailLineNo ) ; this . deleteFlg . copyFrom ( source . deleteFlg ) ; this . insertDatetime . copyFrom ( source . insertDatetime ) ; this . updateDatetime . copyFrom ( source . updateDatetime ) ; this . purchaseNo . copyFrom ( source . purchaseNo ) ; this . purchaseType . copyFrom ( source . purchaseType ) ; this . tradeType . copyFrom ( source . tradeType ) ; this . tradeNo . copyFrom ( source . tradeNo ) ; this . lineNo . copyFrom ( source . lineNo ) ; this . deliveryDate . copyFrom ( source . deliveryDate ) ; this . storeCode . copyFrom ( source . storeCode ) ; this . buyerCode . copyFrom ( source . buyerCode ) ; this . salesTypeCode . copyFrom ( source . salesTypeCode ) ; this . sellerCode . copyFrom ( source . sellerCode ) ; this . tenantCode . copyFrom ( source . tenantCode ) ; this . netPriceTotal . copyFrom ( source . netPriceTotal ) ; this . sellingPriceTotal . copyFrom ( source . sellingPriceTotal ) ; this . shipmentStoreCode . copyFrom ( source . shipmentStoreCode ) ; this . shipmentSalesTypeCode . copyFrom ( source . shipmentSalesTypeCode ) ; this . deductionCode . copyFrom ( source . deductionCode ) ; this . accountCode . copyFrom ( source . accountCode ) ; this . decCol . copyFrom ( source . decCol ) ; this . ownershipDate . copyFrom ( source . ownershipDate ) ; this . cutoffDate . copyFrom ( source . cutoffDate ) ; this . payoutDate . copyFrom ( source . payoutDate ) ; this . ownershipFlag . copyFrom ( source . ownershipFlag ) ; this . cutoffFlag . copyFrom ( source . cutoffFlag ) ; this . payoutFlag . copyFrom ( source . payoutFlag ) ; this . disposeNo . copyFrom ( source . disposeNo ) ; this . disposeDate . copyFrom ( source . disposeDate ) ; } @ Override public void write ( DataOutput out ) throws IOException { pk . write ( out ) ; detailGroupId . write ( out ) ; detailType . write ( out ) ; detailSenderId . write ( out ) ; detailReceiverId . write ( out ) ; detailTestType . write ( out ) ; detailStatus . write ( out ) ; detailLineNo . write ( out ) ; deleteFlg . write ( out ) ; insertDatetime . write ( out ) ; updateDatetime . write ( out ) ; purchaseNo . write ( out ) ; purchaseType . write ( out ) ; tradeType . write ( out ) ; tradeNo . write ( out ) ; lineNo . write ( out ) ; deliveryDate . write ( out ) ; storeCode . write ( out ) ; buyerCode . write ( out ) ; salesTypeCode . write ( out ) ; sellerCode . write ( out ) ; tenantCode . write ( out ) ; netPriceTotal . write ( out ) ; sellingPriceTotal . write ( out ) ; shipmentStoreCode . write ( out ) ; shipmentSalesTypeCode . write ( out ) ; deductionCode . write ( out ) ; accountCode . write ( out ) ; decCol . write ( out ) ; ownershipDate . write ( out ) ; cutoffDate . write ( out ) ; payoutDate . write ( out ) ; ownershipFlag . write ( out ) ; cutoffFlag . write ( out ) ; payoutFlag . write ( out ) ; disposeNo . write ( out ) ; disposeDate . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { pk . readFields ( in ) ; detailGroupId . readFields ( in ) ; detailType . readFields ( in ) ; detailSenderId . readFields ( in ) ; detailReceiverId . readFields ( in ) ; detailTestType . readFields ( in ) ; detailStatus . readFields ( in ) ; detailLineNo . readFields ( in ) ; deleteFlg . readFields ( in ) ; insertDatetime . readFields ( in ) ; updateDatetime . readFields ( in ) ; purchaseNo . readFields ( in ) ; purchaseType . readFields ( in ) ; tradeType . readFields ( in ) ; tradeNo . readFields ( in ) ; lineNo . readFields ( in ) ; deliveryDate . readFields ( in ) ; storeCode . readFields ( in ) ; buyerCode . readFields ( in ) ; salesTypeCode . readFields ( in ) ; sellerCode . readFields ( in ) ; tenantCode . readFields ( in ) ; netPriceTotal . readFields ( in ) ; sellingPriceTotal . readFields ( in ) ; shipmentStoreCode . readFields ( in ) ; shipmentSalesTypeCode . readFields ( in ) ; deductionCode . readFields ( in ) ; accountCode . readFields ( in ) ; decCol . readFields ( in ) ; ownershipDate . readFields ( in ) ; cutoffDate . readFields ( in ) ; payoutDate . readFields ( in ) ; ownershipFlag . readFields ( in ) ; cutoffFlag . readFields ( in ) ; payoutFlag . readFields ( in ) ; disposeNo . readFields ( in ) ; disposeDate . readFields ( in ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + pk . hashCode ( ) ; result = prime * result + detailGroupId . hashCode ( ) ; result = prime * result + detailType . hashCode ( ) ; result = prime * result + detailSenderId . hashCode ( ) ; result = prime * result + detailReceiverId . hashCode ( ) ; result = prime * result + detailTestType . hashCode ( ) ; result = prime * result + detailStatus . hashCode ( ) ; result = prime * result + detailLineNo . hashCode ( ) ; result = prime * result + deleteFlg . hashCode ( ) ; result = prime * result + insertDatetime . hashCode ( ) ; result = prime * result + updateDatetime . hashCode ( ) ; result = prime * result + purchaseNo . hashCode ( ) ; result = prime * result + purchaseType . hashCode ( ) ; result = prime * result + tradeType . hashCode ( ) ; result = prime * result + tradeNo . hashCode ( ) ; result = prime * result + lineNo . hashCode ( ) ; result = prime * result + deliveryDate . hashCode ( ) ; result = prime * result + storeCode . hashCode ( ) ; result = prime * result + buyerCode . hashCode ( ) ; result = prime * result + salesTypeCode . hashCode ( ) ; result = prime * result + sellerCode . hashCode ( ) ; result = prime * result + tenantCode . hashCode ( ) ; result = prime * result + netPriceTotal . hashCode ( ) ; result = prime * result + sellingPriceTotal . hashCode ( ) ; result = prime * result + shipmentStoreCode . hashCode ( ) ; result = prime * result + shipmentSalesTypeCode . hashCode ( ) ; result = prime * result + deductionCode . hashCode ( ) ; result = prime * result + accountCode . hashCode ( ) ; result = prime * result + decCol . hashCode ( ) ; result = prime * result + ownershipDate . hashCode ( ) ; result = prime * result + cutoffDate . hashCode ( ) ; result = prime * result + payoutDate . hashCode ( ) ; result = prime * result + ownershipFlag . hashCode ( ) ; result = prime * result + cutoffFlag . hashCode ( ) ; result = prime * result + payoutFlag . hashCode ( ) ; result = prime * result + disposeNo . hashCode ( ) ; result = prime * result + disposeDate . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Bar other = ( Bar ) obj ; if ( this . pk . equals ( other . pk ) == false ) { return false ; } if ( this . detailGroupId . equals ( other . detailGroupId ) == false ) { return false ; } if ( this . detailType . equals ( other . detailType ) == false ) { return false ; } if ( this . detailSenderId . equals ( other . detailSenderId ) == false ) { return false ; } if ( this . detailReceiverId . equals ( other . detailReceiverId ) == false ) { return false ; } if ( this . detailTestType . equals ( other . detailTestType ) == false ) { return false ; } if ( this . detailStatus . equals ( other . detailStatus ) == false ) { return false ; } if ( this . detailLineNo . equals ( other . detailLineNo ) == false ) { return false ; } if ( this . deleteFlg . equals ( other . deleteFlg ) == false ) { return false ; } if ( this . insertDatetime . equals ( other . insertDatetime ) == false ) { return false ; } if ( this . updateDatetime . equals ( other . updateDatetime ) == false ) { return false ; } if ( this . purchaseNo . equals ( other . purchaseNo ) == false ) { return false ; } if ( this . purchaseType . equals ( other . purchaseType ) == false ) { return false ; } if ( this . tradeType . equals ( other . tradeType ) == false ) { return false ; } if ( this . tradeNo . equals ( other . tradeNo ) == false ) { return false ; } if ( this . lineNo . equals ( other . lineNo ) == false ) { return false ; } if ( this . deliveryDate . equals ( other . deliveryDate ) == false ) { return false ; } if ( this . storeCode . equals ( other . storeCode ) == false ) { return false ; } if ( this . buyerCode . equals ( other . buyerCode ) == false ) { return false ; } if ( this . salesTypeCode . equals ( other . salesTypeCode ) == false ) { return false ; } if ( this . sellerCode . equals ( other . sellerCode ) == false ) { return false ; } if ( this . tenantCode . equals ( other . tenantCode ) == false ) { return false ; } if ( this . netPriceTotal . equals ( other . netPriceTotal ) == false ) { return false ; } if ( this . sellingPriceTotal . equals ( other . sellingPriceTotal ) == false ) { return false ; } if ( this . shipmentStoreCode . equals ( other . shipmentStoreCode ) == false ) { return false ; } if ( this . shipmentSalesTypeCode . equals ( other . shipmentSalesTypeCode ) == false ) { return false ; } if ( this . deductionCode . equals ( other . deductionCode ) == false ) { return false ; } if ( this . accountCode . equals ( other . accountCode ) == false ) { return false ; } if ( this . decCol . equals ( other . decCol ) == false ) { return false ; } if ( this . ownershipDate . equals ( other . ownershipDate ) == false ) { return false ; } if ( this . cutoffDate . equals ( other . cutoffDate ) == false ) { return false ; } if ( this . payoutDate . equals ( other . payoutDate ) == false ) { return false ; } if ( this . ownershipFlag . equals ( other . ownershipFlag ) == false ) { return false ; } if ( this . cutoffFlag . equals ( other . cutoffFlag ) == false ) { return false ; } if ( this . payoutFlag . equals ( other . payoutFlag ) == false ) { return false ; } if ( this . disposeNo . equals ( other . disposeNo ) == false ) { return false ; } if ( this . disposeDate . equals ( other . disposeDate ) == false ) { return false ; } return true ; } } package com . asakusafw . testtools ; public enum ConditionSheetItem { NO ( "" , , , ItemType . COLUMN_ITEM ) , COLUMN_NAME ( "" , , , ItemType . COLUMN_ITEM ) , COLUMN_COMMENT ( "" , , , ItemType . COLUMN_ITEM ) , DATA_TYPE ( "" , , , ItemType . COLUMN_ITEM ) , WIDTH ( "" , , , ItemType . COLUMN_ITEM ) , SCALE ( "" , , , ItemType . COLUMN_ITEM ) , KEY_FLAG ( "" , , , ItemType . COLUMN_ITEM ) , NULLABLE ( "" , , , ItemType . COLUMN_ITEM ) , MATCHING_CONDITION ( "" , , , ItemType . COLUMN_ITEM ) , NULL_VALUE_CONDITION ( "" , , , ItemType . COLUMN_ITEM ) , TABLE_NAME ( "" , , , ItemType . TABLE_ITEM ) , ROW_MATCHING_CONDITION ( "" , , , ItemType . TABLE_ITEM ) ; private String name ; private int row ; private int col ; private ConditionSheetItem ( String name , int row , int col , ItemType itemType ) { this . name = name ; this . row = row ; this . col = col ; } public enum ItemType { TABLE_ITEM , COLUMN_ITEM , } public String getName ( ) { return name ; } public int getRow ( ) { return row ; } public int getCol ( ) { return col ; } } package com . asakusafw . testtools ; import java . io . File ; import java . io . IOException ; import java . sql . Connection ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . SequenceFile ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . testtools . db . DbUtils ; import com . asakusafw . testtools . excel . ExcelUtils ; import com . asakusafw . testtools . inspect . Cause ; import com . asakusafw . testtools . inspect . DefaultInspector ; import com . asakusafw . testtools . inspect . Inspector ; public class TestUtils { private final Map < String , TestDataHolder > dataHolderMap = new HashMap < String , TestDataHolder > ( ) ; private final Map < String , Inspector > inspectorMap = new HashMap < String , Inspector > ( ) ; private final List < Cause > causes = new ArrayList < Cause > ( ) ; long startTime ; public TestUtils ( File dir ) throws IOException { if ( ! dir . isDirectory ( ) ) { throw new IOException ( MessageFormat . format ( "" , dir . getAbsolutePath ( ) ) ) ; } List < File > excelFileList = collectExcelFileList ( dir ) ; init ( excelFileList ) ; } private List < File > collectExcelFileList ( File dir ) { File [ ] files = dir . listFiles ( ) ; List < File > excelFileList = new ArrayList < File > ( ) ; for ( File file : files ) { String filename = file . getAbsolutePath ( ) ; String lowcaseFilename = filename . toLowerCase ( ) ; if ( lowcaseFilename . endsWith ( "" ) ) { excelFileList . add ( file ) ; } } Collections . sort ( excelFileList ) ; return excelFileList ; } public TestUtils ( List < File > excelFileList ) throws IOException { init ( excelFileList ) ; } private void init ( List < File > excelFileList ) throws IOException { for ( File file : excelFileList ) { String filename = file . getAbsolutePath ( ) ; String lowcaseFilename = filename . toLowerCase ( ) ; if ( ! lowcaseFilename . endsWith ( "" ) ) { throw new IOException ( MessageFormat . format ( "" , file . getAbsolutePath ( ) ) ) ; } ExcelUtils excelUtils = new ExcelUtils ( filename ) ; TestDataHolder dataHolder = excelUtils . getTestDataHolder ( ) ; dataHolderMap . put ( dataHolder . getTablename ( ) , dataHolder ) ; } startTime = System . currentTimeMillis ( ) ; } public void storeToDatabase ( boolean createTable ) { Connection conn = null ; try { conn = DbUtils . getConnection ( ) ; clearCache ( conn ) ; for ( TestDataHolder dataHolder : dataHolderMap . values ( ) ) { dataHolder . storeToDatabase ( conn , createTable ) ; } } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } finally { DbUtils . closeQuietly ( conn ) ; } } private void clearCache ( Connection connection ) { assert connection != null ; try { Statement statement = connection . createStatement ( ) ; try { statement . execute ( "" ) ; statement . execute ( "" ) ; } finally { statement . close ( ) ; } } catch ( SQLException e ) { System . err . println ( "" ) ; e . printStackTrace ( ) ; } } public void loadFromDatabase ( ) { Connection conn = null ; try { conn = DbUtils . getConnection ( ) ; for ( TestDataHolder dataHolder : dataHolderMap . values ( ) ) { dataHolder . loadFromDatabase ( conn ) ; } } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } finally { DbUtils . closeQuietly ( conn ) ; } } @ Deprecated public void storeToSequenceFile ( String tablename , SequenceFile . Writer writer ) { TestDataHolder dataHolder = dataHolderMap . get ( tablename ) ; try { dataHolder . store ( writer ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } @ Deprecated public void loadFromSequenceFile ( String tablename , SequenceFile . Reader reader ) { TestDataHolder dataHolder = dataHolderMap . get ( tablename ) ; try { dataHolder . load ( reader ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } public void loadFromTemporary ( String tableName , Configuration conf , Path path ) throws IOException { if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } TestDataHolder dataHolder = dataHolderMap . get ( tableName ) ; ModelInput < ? > input = TemporaryStorage . openInput ( conf , dataHolder . getModelClass ( ) , path ) ; try { dataHolder . load ( input ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } finally { input . close ( ) ; } } public void storeToTemporary ( String tableName , Configuration conf , Path path ) throws IOException { if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } TestDataHolder dataHolder = dataHolderMap . get ( tableName ) ; ModelOutput < ? > output = TemporaryStorage . openOutput ( conf , dataHolder . getModelClass ( ) , path ) ; try { dataHolder . store ( output ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } finally { output . close ( ) ; } } public String getCauseMessage ( ) { StringBuilder sb = new StringBuilder ( String . format ( "" ) ) ; for ( Cause cause : causes ) { sb . append ( String . format ( "" , cause . getMessage ( ) ) ) ; } return sb . toString ( ) ; } public Set < String > getTablenames ( ) { return dataHolderMap . keySet ( ) ; } public Class < ? > getClassByTablename ( String tablename ) { TestDataHolder dataHolder = dataHolderMap . get ( tablename ) ; if ( dataHolder == null ) { throw new RuntimeException ( "" + tablename ) ; } return dataHolder . getModelClass ( ) ; } public String getTablenameByClass ( Class < ? > modelClass ) { for ( Map . Entry < String , TestDataHolder > entry : dataHolderMap . entrySet ( ) ) { if ( entry . getValue ( ) . getModelClass ( ) == modelClass ) { return entry . getKey ( ) ; } } throw new RuntimeException ( MessageFormat . format ( "" , modelClass . getName ( ) ) ) ; } public void setInspector ( String tablename , Inspector inspector ) { inspectorMap . put ( tablename , inspector ) ; } public List < Cause > getCauses ( ) { return causes ; } public boolean inspect ( ) { boolean success = true ; for ( String tablename : dataHolderMap . keySet ( ) ) { TestDataHolder dataHolder = dataHolderMap . get ( tablename ) ; Inspector inspector = inspectorMap . get ( tablename ) ; if ( inspector == null ) { inspector = new DefaultInspector ( ) ; } inspector . setColumnInfos ( dataHolder . getColumnInfos ( ) ) ; inspector . setStartTime ( startTime ) ; inspector . setFinishTime ( System . currentTimeMillis ( ) ) ; inspector . inspect ( dataHolder ) ; if ( ! inspector . isSuccess ( ) ) { success = false ; causes . addAll ( inspector . getCauses ( ) ) ; } } return success ; } } package com . asakusafw . testtools ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . List ; import java . util . Properties ; public final class Configuration { private static Configuration conf ; public static synchronized Configuration getInstance ( ) { if ( conf == null ) { loadConfigurationFromEnvironment ( ) ; } return conf ; } private Configuration ( ) { } private String jdbcDriver ; private String jdbcUrl ; private String jdbcUser ; private String jdbcPassword ; private String databaseName ; private String outputDirectory ; private String modelPackage ; public String getOutputDirectory ( ) { return outputDirectory ; } public void setOutputDirectory ( String outputDirectory ) { this . outputDirectory = outputDirectory ; } public String getJdbcDriver ( ) { return jdbcDriver ; } public void setJdbcDriver ( String jdbcDriver ) { this . jdbcDriver = jdbcDriver ; } public String getJdbcUrl ( ) { return jdbcUrl ; } public void setJdbcUrl ( String jdbcUrl ) { this . jdbcUrl = jdbcUrl ; } public String getJdbcUser ( ) { return jdbcUser ; } public void setJdbcUser ( String jdbcUser ) { this . jdbcUser = jdbcUser ; } public String getJdbcPassword ( ) { return jdbcPassword ; } public void setJdbcPassword ( String jdbcPassword ) { this . jdbcPassword = jdbcPassword ; } public String getDatabaseName ( ) { return databaseName ; } public void setDatabaseName ( String databaseName ) { this . databaseName = databaseName ; } private static void loadConfigurationFromEnvironment ( ) { conf = new Configuration ( ) ; String path = findVariable ( Constants . ENV_PROPERTIES , true ) ; try { Properties props = loadProperties ( path ) ; conf . setJdbcDriver ( findProperty ( props , Constants . K_JDBC_DRIVER ) ) ; conf . setJdbcUrl ( findProperty ( props , Constants . K_JDBC_URL ) ) ; conf . setJdbcUser ( findProperty ( props , Constants . K_JDBC_USER ) ) ; conf . setJdbcPassword ( findProperty ( props , Constants . K_JDBC_PASSWORD ) ) ; conf . setDatabaseName ( findProperty ( props , Constants . K_DATABASE_NAME ) ) ; String outputDir = findVariable ( Constants . ENV_TEMPLATEGEN_OUTPUT_DIR , false ) ; if ( outputDir == null ) { outputDir = findProperty ( props , Constants . K_OUTPUT_DIR ) ; } conf . setOutputDirectory ( outputDir ) ; } catch ( IOException e ) { throw new IllegalStateException ( MessageFormat . format ( "" , Constants . ENV_PROPERTIES , path ) , e ) ; } String modelPackage = findVariable ( Constants . ENV_BASE_PACKAGE , true ) ; conf . setModelPackage ( modelPackage ) ; } private static String findProperty ( Properties properties , String key ) { assert properties != null ; assert key != null ; String value = properties . getProperty ( key ) ; if ( value == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , key ) ) ; } return value ; } private static String findVariable ( List < String > variableNames , boolean mandatory ) { assert variableNames != null ; assert variableNames . isEmpty ( ) == false ; String value = null ; for ( String var : variableNames ) { value = System . getProperty ( var ) ; if ( value == null ) { value = System . getenv ( var ) ; } if ( value != null ) { break ; } } if ( mandatory && value == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , variableNames . get ( ) ) ) ; } return value ; } private static Properties loadProperties ( String path ) throws IOException { assert path != null ; InputStream in = new FileInputStream ( path ) ; try { Properties result = new Properties ( ) ; result . load ( in ) ; return result ; } finally { in . close ( ) ; } } public String getModelPackage ( ) { return modelPackage ; } public void setModelPackage ( String modelPackage ) { this . modelPackage = modelPackage ; } } @ java . lang . Deprecated package com . asakusafw . testtools ; @ java . lang . Deprecated package com . asakusafw . testtools . db ; package com . asakusafw . testtools . db ; import java . io . Closeable ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . List ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . Configuration ; public final class DbUtils { public static void createTable ( Connection conn , List < ColumnInfo > list ) throws SQLException { if ( list == null || list . size ( ) == ) { throw new RuntimeException ( "" ) ; } StringBuilder sb = new StringBuilder ( ) ; boolean firstElement = true ; for ( ColumnInfo info : list ) { if ( firstElement ) { firstElement = false ; sb . append ( "" ) ; sb . append ( info . getTableName ( ) ) ; sb . append ( "" ) ; } else { sb . append ( "" ) ; } sb . append ( "" ) ; sb . append ( String . format ( "" , info . getColumnName ( ) , info . getDataType ( ) . getDataTypeString ( ) ) ) ; switch ( info . getDataType ( ) ) { case CHAR : case VARCHAR : sb . append ( String . format ( "" , info . getCharacterMaximumLength ( ) ) ) ; break ; case DECIMAL : sb . append ( String . format ( "" , info . getNumericPrecision ( ) , info . getNumericScale ( ) ) ) ; break ; default : break ; } if ( info . getColumnComment ( ) != null && info . getColumnComment ( ) . length ( ) != ) { sb . append ( "" ) ; sb . append ( "" ) ; sb . append ( info . getColumnComment ( ) ) ; sb . append ( "" ) ; } } sb . append ( "" ) ; String sql = sb . toString ( ) ; Statement stmt = null ; try { stmt = conn . createStatement ( ) ; stmt . executeUpdate ( sql ) ; } finally { closeQuietly ( stmt ) ; } } public static void dropTable ( Connection conn , String tablename ) throws SQLException { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "" ) ; sb . append ( tablename ) ; String sql = sb . toString ( ) ; Statement stmt = null ; try { stmt = conn . createStatement ( ) ; stmt . executeUpdate ( sql ) ; } finally { closeQuietly ( stmt ) ; } } public static void truncateTable ( Connection conn , String tablename ) throws SQLException { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "" ) ; sb . append ( tablename ) ; String sql = sb . toString ( ) ; Statement stmt = null ; try { stmt = conn . createStatement ( ) ; stmt . executeUpdate ( sql ) ; } finally { closeQuietly ( stmt ) ; } } public static void closeQuietly ( Connection conn ) { if ( conn != null ) { try { conn . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void closeQuietly ( Statement stmt ) { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void closeQuietly ( ResultSet rs ) { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void closeQuietly ( Closeable closeable ) { if ( closeable != null ) { try { closeable . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static Connection getConnection ( ) throws SQLException { Configuration conf = Configuration . getInstance ( ) ; String driver = conf . getJdbcDriver ( ) ; String user = conf . getJdbcUser ( ) ; String password = conf . getJdbcPassword ( ) ; String url = conf . getJdbcUrl ( ) ; if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } if ( url == null ) { throw new IllegalArgumentException ( "" ) ; } if ( user == null ) { throw new IllegalArgumentException ( "" ) ; } if ( password == null ) { throw new IllegalArgumentException ( "" ) ; } try { Class . forName ( driver ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "" , e ) ; } return DriverManager . getConnection ( url , user , password ) ; } private DbUtils ( ) { return ; } } package com . asakusafw . testtools ; import java . io . IOException ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . math . BigDecimal ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Timestamp ; import java . sql . Types ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import org . apache . hadoop . io . NullWritable ; import org . apache . hadoop . io . SequenceFile ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . sequencefile . SequenceFileModelOutput ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . testtools . db . DbUtils ; public class TestDataHolder { private final List < Writable > source ; private final List < Writable > expect ; private final List < Writable > actual ; private final List < ColumnInfo > columnInfos ; private Class < ? extends Writable > modelClass ; private final String tablename ; private RowMatchingCondition rowMatchingCondition ; public TestDataHolder ( List < Writable > source , List < Writable > expect , List < ColumnInfo > columnInfos , Class < ? extends Writable > modelClass , RowMatchingCondition rowMatchingCondition ) { super ( ) ; this . source = source ; this . expect = expect ; this . actual = new ArrayList < Writable > ( ) ; this . columnInfos = columnInfos ; this . tablename = columnInfos . get ( ) . getTableName ( ) ; this . modelClass = modelClass ; this . rowMatchingCondition = rowMatchingCondition ; } public List < Writable > getSource ( ) { return source ; } public List < Writable > getExpect ( ) { return expect ; } public List < Writable > getActual ( ) { return actual ; } public List < ColumnInfo > getColumnInfos ( ) { return columnInfos ; } public void storeToDatabase ( Connection conn , boolean createTable ) throws SQLException { if ( createTable ) { DbUtils . dropTable ( conn , tablename ) ; DbUtils . createTable ( conn , columnInfos ) ; } else { DbUtils . truncateTable ( conn , tablename ) ; } StringBuilder sb = new StringBuilder ( ) ; sb . append ( "" ) ; sb . append ( tablename ) ; for ( int i = ; i < columnInfos . size ( ) ; i ++ ) { if ( i == ) { sb . append ( "" ) ; } else { sb . append ( "" ) ; } sb . append ( columnInfos . get ( i ) . getColumnName ( ) ) ; } sb . append ( "" ) ; for ( int i = ; i < columnInfos . size ( ) ; i ++ ) { if ( i == ) { sb . append ( "" ) ; } else { sb . append ( "" ) ; } } sb . append ( "" ) ; String sql = sb . toString ( ) ; PreparedStatement ps = null ; try { ps = conn . prepareStatement ( sql ) ; for ( Writable model : source ) { setModelValue ( ps , model ) ; ps . executeUpdate ( ) ; } } finally { DbUtils . closeQuietly ( ps ) ; } } private void setModelValue ( PreparedStatement ps , Writable model ) throws SQLException { int parameterIndex = ; for ( ColumnInfo info : columnInfos ) { parameterIndex ++ ; Object vo = null ; try { Method method = modelClass . getMethod ( info . getGetterName ( ) ) ; vo = method . invoke ( model ) ; } catch ( SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } switch ( info . getDataType ( ) ) { case LONG : LongOption longOption = ( LongOption ) vo ; if ( longOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . BIGINT ) ; } else { ps . setLong ( parameterIndex , longOption . get ( ) ) ; } break ; case INT : IntOption intOption = ( IntOption ) vo ; if ( intOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . INTEGER ) ; } else { ps . setInt ( parameterIndex , intOption . get ( ) ) ; } break ; case SMALL_INT : ShortOption shortOption = ( ShortOption ) vo ; if ( shortOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . SMALLINT ) ; } else { ps . setInt ( parameterIndex , shortOption . get ( ) ) ; } break ; case TINY_INT : ByteOption byteOption = ( ByteOption ) vo ; if ( byteOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . TINYINT ) ; } else { ps . setByte ( parameterIndex , byteOption . get ( ) ) ; } break ; case CHAR : StringOption charStringOption = ( StringOption ) vo ; if ( charStringOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . CHAR ) ; } else { ps . setString ( parameterIndex , charStringOption . getAsString ( ) ) ; } break ; case VARCHAR : StringOption vcharStringOption = ( StringOption ) vo ; if ( vcharStringOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . VARCHAR ) ; } else { ps . setString ( parameterIndex , vcharStringOption . getAsString ( ) ) ; } break ; case TIMESTAMP : case DATETIME : DateTimeOption dateTimeOption = ( DateTimeOption ) vo ; if ( dateTimeOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . TIMESTAMP ) ; } else { DateTime dateTime = dateTimeOption . get ( ) ; Calendar cal = Calendar . getInstance ( ) ; int y = dateTime . getYear ( ) ; int m = dateTime . getMonth ( ) ; int d = dateTime . getDay ( ) ; int h = dateTime . getHour ( ) ; int min = dateTime . getMinute ( ) ; int s = dateTime . getSecond ( ) ; cal . clear ( ) ; cal . set ( y , m - , d , h , min , s ) ; Timestamp ts = new Timestamp ( cal . getTimeInMillis ( ) ) ; ps . setTimestamp ( parameterIndex , ts ) ; } break ; case DATE : DateOption dateOption = ( DateOption ) vo ; if ( dateOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . DATE ) ; } else { Date date = dateOption . get ( ) ; Calendar cal = Calendar . getInstance ( ) ; int y = date . getYear ( ) ; int m = date . getMonth ( ) ; int d = date . getDay ( ) ; cal . clear ( ) ; cal . set ( y , m - , d , , , ) ; java . sql . Date sqlDate = new java . sql . Date ( cal . getTimeInMillis ( ) ) ; ps . setDate ( parameterIndex , sqlDate ) ; } break ; case DECIMAL : DecimalOption decimalOption = ( DecimalOption ) vo ; if ( decimalOption . isNull ( ) ) { ps . setNull ( parameterIndex , Types . DECIMAL ) ; } else { ps . setBigDecimal ( parameterIndex , decimalOption . get ( ) ) ; } break ; default : throw new RuntimeException ( "" + info . getDataType ( ) ) ; } } } public void loadFromDatabase ( Connection conn ) throws SQLException { StringBuilder sb = new StringBuilder ( ) ; for ( ColumnInfo info : columnInfos ) { if ( info == columnInfos . get ( ) ) { sb . append ( "" ) ; } else { sb . append ( "" ) ; } sb . append ( info . getColumnName ( ) ) ; } sb . append ( "" ) ; sb . append ( tablename ) ; String sql = sb . toString ( ) ; PreparedStatement ps = null ; ResultSet rs = null ; try { ps = conn . prepareStatement ( sql ) ; rs = ps . executeQuery ( ) ; actual . clear ( ) ; while ( rs . next ( ) ) { Writable model ; try { model = getModelFromResultSet ( rs ) ; actual . add ( model ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } } } finally { DbUtils . closeQuietly ( rs ) ; DbUtils . closeQuietly ( ps ) ; } } private Writable getModelFromResultSet ( ResultSet rs ) throws InstantiationException , IllegalAccessException , NoSuchMethodException , InvocationTargetException , SQLException { Writable model = modelClass . newInstance ( ) ; int columnIndex = ; for ( ColumnInfo info : columnInfos ) { columnIndex ++ ; String name = info . getSetterName ( ) ; switch ( info . getDataType ( ) ) { case LONG : LongOption longOption = new LongOption ( ) ; long l = rs . getLong ( columnIndex ) ; if ( rs . wasNull ( ) ) { longOption . setNull ( ) ; } else { longOption . modify ( l ) ; } modelClass . getMethod ( name , LongOption . class ) . invoke ( model , longOption ) ; break ; case INT : IntOption intOption = new IntOption ( ) ; int i = rs . getInt ( columnIndex ) ; if ( rs . wasNull ( ) ) { intOption . setNull ( ) ; } else { intOption . modify ( i ) ; } modelClass . getMethod ( name , IntOption . class ) . invoke ( model , intOption ) ; break ; case SMALL_INT : ShortOption shortOption = new ShortOption ( ) ; short sv = rs . getShort ( columnIndex ) ; if ( rs . wasNull ( ) ) { shortOption . setNull ( ) ; } else { shortOption . modify ( sv ) ; } modelClass . getMethod ( name , ShortOption . class ) . invoke ( model , shortOption ) ; break ; case TINY_INT : ByteOption byteOption = new ByteOption ( ) ; Byte b = rs . getByte ( columnIndex ) ; if ( rs . wasNull ( ) ) { byteOption . setNull ( ) ; } else { byteOption . modify ( b ) ; } modelClass . getMethod ( name , ByteOption . class ) . invoke ( model , byteOption ) ; break ; case CHAR : case VARCHAR : StringOption stringOption = new StringOption ( ) ; String str = rs . getString ( columnIndex ) ; if ( rs . wasNull ( ) ) { stringOption . setNull ( ) ; } else { stringOption . modify ( str ) ; } modelClass . getMethod ( name , StringOption . class ) . invoke ( model , stringOption ) ; break ; case TIMESTAMP : case DATETIME : DateTimeOption dateTimeOption = new DateTimeOption ( ) ; Timestamp timestamp = rs . getTimestamp ( columnIndex ) ; if ( rs . wasNull ( ) ) { dateTimeOption . setNull ( ) ; } else { Calendar dateTimeCal = Calendar . getInstance ( ) ; dateTimeCal . setTime ( timestamp ) ; int y = dateTimeCal . get ( Calendar . YEAR ) ; int m = dateTimeCal . get ( Calendar . MONTH ) ; int d = dateTimeCal . get ( Calendar . DAY_OF_MONTH ) ; int h = dateTimeCal . get ( Calendar . HOUR_OF_DAY ) ; int min = dateTimeCal . get ( Calendar . MINUTE ) ; int s = dateTimeCal . get ( Calendar . SECOND ) ; int days = com . asakusafw . runtime . value . DateUtil . getDayFromDate ( y , m + , d ) ; int secs = com . asakusafw . runtime . value . DateUtil . getSecondFromTime ( h , min , s ) ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * + secs ) ; dateTimeOption . modify ( dt ) ; } modelClass . getMethod ( name , DateTimeOption . class ) . invoke ( model , dateTimeOption ) ; break ; case DATE : DateOption dateOption = new DateOption ( ) ; java . sql . Date sqlDate = rs . getDate ( columnIndex ) ; if ( rs . wasNull ( ) ) { dateOption . setNull ( ) ; } else { Calendar dateCal = Calendar . getInstance ( ) ; dateCal . setTime ( sqlDate ) ; int y = dateCal . get ( Calendar . YEAR ) ; int m = dateCal . get ( Calendar . MONTH ) ; int d = dateCal . get ( Calendar . DAY_OF_MONTH ) ; int days = DateUtil . getDayFromDate ( y , m + , d ) ; dateOption . modify ( days ) ; } modelClass . getMethod ( name , DateOption . class ) . invoke ( model , dateOption ) ; break ; case DECIMAL : DecimalOption decimalOption = new DecimalOption ( ) ; BigDecimal bigDecimal = rs . getBigDecimal ( columnIndex ) ; if ( rs . wasNull ( ) ) { decimalOption . setNull ( ) ; } else { decimalOption . modify ( bigDecimal ) ; } modelClass . getMethod ( name , DecimalOption . class ) . invoke ( model , decimalOption ) ; break ; default : throw new RuntimeException ( "" + info . getDataType ( ) ) ; } } return model ; } @ Deprecated public void store ( SequenceFile . Writer writer ) throws IOException { store ( new SequenceFileModelOutput < Writable > ( writer ) ) ; } public void store ( ModelOutput < ? > output ) throws IOException { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } @ SuppressWarnings ( "" ) ModelOutput < Writable > unsafe = ( ModelOutput < Writable > ) output ; for ( Writable model : source ) { unsafe . write ( model ) ; } } @ Deprecated public void load ( SequenceFile . Reader reader ) throws IOException { NullWritable key = NullWritable . get ( ) ; for ( ; ; ) { Writable model ; try { model = modelClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } if ( reader . next ( key , model ) ) { actual . add ( model ) ; } else { break ; } } } public void load ( ModelInput < ? > input ) throws IOException { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } @ SuppressWarnings ( "" ) ModelInput < Writable > unsafe = ( ModelInput < Writable > ) input ; for ( ; ; ) { Writable model ; try { model = modelClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } if ( unsafe . readTo ( model ) ) { actual . add ( model ) ; } else { break ; } } } public void sort ( ) { Comparator < Writable > comparator = new ModelComparator < Writable > ( columnInfos , modelClass ) ; Collections . sort ( expect , comparator ) ; Collections . sort ( actual , comparator ) ; } public Class < ? extends Writable > getModelClass ( ) { return modelClass ; } public void setModelClass ( Class < ? extends Writable > modelClass ) { this . modelClass = modelClass ; } public String getTablename ( ) { return tablename ; } public RowMatchingCondition getRowMatchingCondition ( ) { return rowMatchingCondition ; } public void setRowMatchingCondition ( RowMatchingCondition rowMatchingCondition ) { this . rowMatchingCondition = rowMatchingCondition ; } } package com . asakusafw . testtools ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public final class Constants { public static final int MAX_ROWS = ; private static final String [ ] ENV_PREFIX = { "" , "" } ; public static final List < String > ENV_PROPERTIES = buildEnvProperties ( "" ) ; public static final List < String > ENV_BASE_PACKAGE = buildEnvProperties ( "" ) ; public static final List < String > ENV_TEMPLATEGEN_OUTPUT_DIR = buildEnvProperties ( "" ) ; public static final String K_JDBC_DRIVER = "" ; public static final String K_JDBC_URL = "" ; public static final String K_JDBC_USER = "" ; public static final String K_JDBC_PASSWORD = "" ; public static final String K_DATABASE_NAME = "" ; public static final String K_OUTPUT_DIR = "" ; public static final String INPUT_DATA_SHEET_NAME = "" ; public static final String OUTPUT_DATA_SHEET_NAME = "" ; public static final String TEST_CONDITION_SHEET_NAME = "" ; private static List < String > buildEnvProperties ( String suffix ) { assert suffix != null ; List < String > properties = new ArrayList < String > ( ENV_PREFIX . length ) ; for ( String prefix : ENV_PREFIX ) { properties . add ( prefix + suffix ) ; } return Collections . unmodifiableList ( properties ) ; } private Constants ( ) { return ; } } package com . asakusafw . testtools ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Comparator ; import java . util . List ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . ValueOption ; public class ModelComparator < T extends Writable > implements Comparator < T > , Serializable { private static final long serialVersionUID = ; private transient List < Method > getters ; public ModelComparator ( List < ColumnInfo > columnInfos , Class < ? > modelClass ) { getters = new ArrayList < Method > ( ) ; for ( ColumnInfo info : columnInfos ) { if ( info . isKey ( ) ) { try { Method method = modelClass . getMethod ( info . getGetterName ( ) ) ; getters . add ( method ) ; } catch ( SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } } } } @ Override public int compare ( T o1 , T o2 ) { for ( Method getter : getters ) { @ SuppressWarnings ( "" ) Comparable vo1 ; @ SuppressWarnings ( "" ) Comparable vo2 ; try { vo1 = ( ValueOption < ? > ) getter . invoke ( o1 ) ; vo2 = ( ValueOption < ? > ) getter . invoke ( o2 ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } @ SuppressWarnings ( "" ) int ret = vo1 . compareTo ( vo2 ) ; if ( ret != ) { return ret ; } } return ; } private void readObject ( ObjectInputStream stream ) throws IOException , ClassNotFoundException { stream . defaultReadObject ( ) ; Method [ ] methods = new Method [ stream . readInt ( ) ] ; for ( int i = ; i < methods . length ; i ++ ) { Class < ? > aClass = ( Class < ? > ) stream . readObject ( ) ; String methodName = stream . readUTF ( ) ; try { methods [ i ] = aClass . getDeclaredMethod ( methodName ) ; } catch ( SecurityException e ) { throw new IOException ( e ) ; } catch ( NoSuchMethodException e ) { throw new IOException ( e ) ; } } this . getters = Arrays . asList ( methods ) ; } private void writeObject ( ObjectOutputStream stream ) throws IOException { stream . defaultWriteObject ( ) ; stream . writeInt ( getters . size ( ) ) ; for ( Method method : getters ) { stream . writeObject ( method . getDeclaringClass ( ) ) ; stream . writeUTF ( method . getName ( ) ) ; } } } package com . asakusafw . testtools ; import com . asakusafw . modelgen . emitter . JavaName ; import com . asakusafw . modelgen . source . MySqlDataType ; public class ColumnInfo { public ColumnInfo ( String tableName , String columnName , String columnComment , MySqlDataType dataType , long characterMaximumLength , int numericPrecision , int numericScale , boolean nullable , boolean key , ColumnMatchingCondition columnMatchingCondition , NullValueCondition nullValueCondition ) { this . tableName = tableName ; this . columnName = columnName ; this . columnComment = columnComment ; this . dataType = dataType ; this . characterMaximumLength = characterMaximumLength ; this . numericPrecision = numericPrecision ; this . numericScale = numericScale ; this . nullable = nullable ; this . key = key ; this . columnMatchingCondition = columnMatchingCondition ; this . nullValueCondition = nullValueCondition ; JavaName javaName = JavaName . of ( columnName ) ; getterName = "" + javaName . toTypeName ( ) + "" ; setterName = "" + javaName . toTypeName ( ) + "" ; } private String tableName ; private String columnName ; private String columnComment ; private MySqlDataType dataType ; private long characterMaximumLength ; private int numericPrecision ; private int numericScale ; private boolean nullable ; private boolean key ; private ColumnMatchingCondition columnMatchingCondition ; private NullValueCondition nullValueCondition ; private String getterName ; private String setterName ; public String getTableName ( ) { return tableName ; } public String getColumnName ( ) { return columnName ; } public String getColumnComment ( ) { return columnComment ; } public MySqlDataType getDataType ( ) { return dataType ; } public long getCharacterMaximumLength ( ) { return characterMaximumLength ; } public int getNumericPrecision ( ) { return numericPrecision ; } public int getNumericScale ( ) { return numericScale ; } public boolean isNullable ( ) { return nullable ; } public boolean isKey ( ) { return key ; } public ColumnMatchingCondition getColumnMatchingCondition ( ) { return columnMatchingCondition ; } public NullValueCondition getNullValueCondition ( ) { return nullValueCondition ; } public String getGetterName ( ) { return getterName ; } public String getSetterName ( ) { return setterName ; } } @ java . lang . Deprecated package com . asakusafw . testtools . inspect ; package com . asakusafw . testtools . inspect ; import java . util . List ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . TestDataHolder ; public interface Inspector { List < Cause > getCauses ( ) ; boolean isSuccess ( ) ; boolean inspect ( TestDataHolder dataHolder ) ; void setColumnInfos ( List < ColumnInfo > columnInfos ) ; void setStartTime ( long startTime ) ; void setFinishTime ( long finishTime ) ; } package com . asakusafw . testtools . inspect ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . testtools . ColumnInfo ; public class Cause { public enum Type { NOT_STRING_COLUMN ( "" ) , CONDITION_NOW_ON_INVALID_COLUMN ( "" ) , CONDITION_TODAY_ON_INVALID_COLUMN ( "" ) , CONDITION_PARTIAL_ON_INVALID_COLUMN ( "" ) , NOT_IN_TESTING_TIME ( "" ) , NOT_IN_TEST_DAY ( "" ) , NULL_NOT_ALLOWD ( "" ) , NO_EXPECT_RECORD ( "" ) , NO_ACTUAL_RECORD ( "" ) , COLUMN_VALUE_MISSMATCH ( "" ) , DUPLICATEED_KEY_IN_EXPECT_RECORDS ( "" ) , DUPLICATEED_KEY_IN_ACTUALT_RECORDS ( "" ) ; private String message ; private Type ( String message ) { this . message = message ; } public String getMessage ( ) { return message ; } } private Type type ; private String message ; private Writable expect ; private Writable actual ; private ColumnInfo columnInfo ; private ValueOption < ? > actualVal ; private ValueOption < ? > expectVal ; public Type getType ( ) { return type ; } public String getMessage ( ) { return message ; } public Cause ( Type type , String additionalMessage , Writable expect , Writable actual , ValueOption < ? > expectVal , ValueOption < ? > actualVal , ColumnInfo columnInfo ) { this . type = type ; this . message = type . getMessage ( ) + additionalMessage ; this . expect = expect ; this . actual = actual ; this . expectVal = expectVal ; this . actualVal = actualVal ; this . columnInfo = columnInfo ; } public Cause ( Type type , String keyValueString , Writable expect , Writable actual ) { this . type = type ; this . message = type . getMessage ( ) + keyValueString ; this . expect = expect ; this . actual = actual ; } public Writable getExpect ( ) { return expect ; } public Writable getActual ( ) { return actual ; } public ColumnInfo getColumnInfo ( ) { return columnInfo ; } public ValueOption < ? > getActualVal ( ) { return actualVal ; } public ValueOption < ? > getExpectVal ( ) { return expectVal ; } } package com . asakusafw . testtools . inspect ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . Calendar ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . inspect . Cause . Type ; public final class DefaultInspector extends AbstractInspector { @ Override protected void inspect ( Writable expectRow , Writable actualRow ) { for ( ColumnInfo columnInfo : getColumnInfos ( ) ) { Method method ; try { method = expectRow . getClass ( ) . getMethod ( columnInfo . getGetterName ( ) ) ; ValueOption < ? > expectVal = ( ValueOption < ? > ) method . invoke ( expectRow ) ; ValueOption < ? > actualVal = ( ValueOption < ? > ) method . invoke ( actualRow ) ; inspect ( expectRow , actualRow , expectVal , actualVal , columnInfo ) ; } catch ( SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } } } private void inspect ( Writable expect , Writable actual , ValueOption < ? > expectVal , ValueOption < ? > actualVal , ColumnInfo columnInfo ) { if ( actualVal . isNull ( ) ) { switch ( columnInfo . getNullValueCondition ( ) ) { case NULL_IS_NG : fail ( Type . COLUMN_VALUE_MISSMATCH , expect , actual , expectVal , actualVal , columnInfo ) ; return ; case NULL_IS_OK : return ; case NORMAL : case NOT_NULL_IS_NG : case NOT_NULL_IS_OK : break ; default : throw new RuntimeException ( "" ) ; } } if ( ! actualVal . isNull ( ) ) { switch ( columnInfo . getNullValueCondition ( ) ) { case NOT_NULL_IS_NG : fail ( Type . COLUMN_VALUE_MISSMATCH , expect , actual , expectVal , actualVal , columnInfo ) ; return ; case NOT_NULL_IS_OK : return ; case NORMAL : case NULL_IS_OK : case NULL_IS_NG : break ; default : throw new RuntimeException ( "" ) ; } } switch ( columnInfo . getColumnMatchingCondition ( ) ) { case EXACT : inspectExact ( expect , actual , expectVal , actualVal , columnInfo ) ; break ; case NONE : return ; case NOW : inspectNow ( expect , actual , expectVal , actualVal , columnInfo ) ; break ; case TODAY : inspectToday ( expect , actual , expectVal , actualVal , columnInfo ) ; break ; case PARTIAL : inspectPartialt ( expect , actual , expectVal , actualVal , columnInfo ) ; break ; default : throw new RuntimeException ( "" ) ; } } private void inspectExact ( Writable expect , Writable actual , ValueOption < ? > expectVal , ValueOption < ? > actualVal , ColumnInfo columnInfo ) { if ( ! expectVal . equals ( actualVal ) ) { fail ( Type . COLUMN_VALUE_MISSMATCH , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } else { return ; } } private void inspectPartialt ( Writable expect , Writable actual , ValueOption < ? > expectVal , ValueOption < ? > actualVal , ColumnInfo columnInfo ) { StringOption actualStringOption ; StringOption expectStringOption ; if ( actualVal instanceof StringOption ) { actualStringOption = ( StringOption ) actualVal ; expectStringOption = ( StringOption ) expectVal ; } else { fail ( Type . CONDITION_PARTIAL_ON_INVALID_COLUMN , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } if ( actualStringOption . equals ( expectStringOption ) ) { return ; } if ( actualStringOption . isNull ( ) || expectStringOption . isNull ( ) || actualStringOption . getAsString ( ) . length ( ) == || expectStringOption . getAsString ( ) . length ( ) == ) { fail ( Type . COLUMN_VALUE_MISSMATCH , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } String actualString = actualStringOption . getAsString ( ) ; String expectString = expectStringOption . getAsString ( ) ; if ( actualString . indexOf ( expectString ) == - ) { fail ( Type . COLUMN_VALUE_MISSMATCH , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } else { return ; } } private void inspectNow ( Writable expect , Writable actual , ValueOption < ? > expectVal , ValueOption < ? > actualVal , ColumnInfo columnInfo ) { Calendar cal = Calendar . getInstance ( ) ; if ( actualVal instanceof DateTimeOption ) { if ( actualVal . isNull ( ) ) { fail ( Type . NOT_IN_TESTING_TIME , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } DateTimeOption dateTimeOption = ( DateTimeOption ) actualVal ; DateTime dateTime = dateTimeOption . get ( ) ; int y = dateTime . getYear ( ) ; int m = dateTime . getMonth ( ) ; int d = dateTime . getDay ( ) ; int h = dateTime . getHour ( ) ; int min = dateTime . getMinute ( ) ; int s = dateTime . getSecond ( ) ; cal . clear ( ) ; cal . set ( y , m - , d , h , min , s ) ; } else { fail ( Type . CONDITION_NOW_ON_INVALID_COLUMN , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } long time = cal . getTimeInMillis ( ) ; if ( getStartTime ( ) - <= time && time <= getFinishTime ( ) ) { return ; } else { fail ( Type . NOT_IN_TESTING_TIME , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } } private void inspectToday ( Writable expect , Writable actual , ValueOption < ? > expectVal , ValueOption < ? > actualVal , ColumnInfo columnInfo ) { Calendar cal = Calendar . getInstance ( ) ; if ( actualVal instanceof DateOption ) { if ( actualVal . isNull ( ) ) { fail ( Type . NOT_IN_TEST_DAY , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } DateOption dateOption = ( DateOption ) actualVal ; Date date = dateOption . get ( ) ; cal . clear ( ) ; cal . set ( date . getYear ( ) , date . getMonth ( ) - , date . getDay ( ) ) ; } else if ( actualVal instanceof DateTimeOption ) { if ( actualVal . isNull ( ) ) { fail ( Type . NOT_IN_TEST_DAY , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } DateTimeOption dateTimeOption = ( DateTimeOption ) actualVal ; DateTime dateTime = dateTimeOption . get ( ) ; int y = dateTime . getYear ( ) ; int m = dateTime . getMonth ( ) ; int d = dateTime . getDay ( ) ; int h = dateTime . getHour ( ) ; int min = dateTime . getMinute ( ) ; int s = dateTime . getSecond ( ) ; cal . clear ( ) ; cal . set ( y , m - , d , h , min , s ) ; } else { fail ( Type . CONDITION_TODAY_ON_INVALID_COLUMN , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } Calendar startDay = Calendar . getInstance ( ) ; startDay . setTimeInMillis ( getStartTime ( ) ) ; truncateCalendar ( startDay ) ; Calendar finishDay = Calendar . getInstance ( ) ; finishDay . setTimeInMillis ( getFinishTime ( ) ) ; truncateCalendar ( finishDay ) ; finishDay . add ( Calendar . DAY_OF_MONTH , ) ; long time = cal . getTimeInMillis ( ) ; if ( startDay . getTimeInMillis ( ) <= time && time < finishDay . getTimeInMillis ( ) ) { return ; } else { fail ( Type . NOT_IN_TEST_DAY , expect , actual , expectVal , actualVal , columnInfo ) ; return ; } } private void truncateCalendar ( Calendar cal ) { int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; cal . clear ( ) ; cal . set ( y , m , d ) ; } } package com . asakusafw . testtools . inspect ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . Comparator ; import java . util . Iterator ; import java . util . List ; import org . apache . hadoop . io . Writable ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . ModelComparator ; import com . asakusafw . testtools . RowMatchingCondition ; import com . asakusafw . testtools . TestDataHolder ; import com . asakusafw . testtools . inspect . Cause . Type ; public abstract class AbstractInspector implements Inspector { private List < ColumnInfo > columnInfos ; private List < ColumnInfo > keyColumnInfos = new ArrayList < ColumnInfo > ( ) ; private long startTime ; private long finishTime = ; private List < Cause > causes = new ArrayList < Cause > ( ) ; protected abstract void inspect ( Writable expectRow , Writable actualRow ) ; protected final void fail ( Type type , Writable expect , Writable actual ) { String tableNameString = "" + columnInfos . get ( ) . getTableName ( ) + "" ; String keyValueString ; if ( actual != null ) { keyValueString = getKeyValueString ( actual ) ; } else { keyValueString = getKeyValueString ( expect ) ; } Cause cause = new Cause ( type , tableNameString + keyValueString , expect , actual ) ; causes . add ( cause ) ; } protected final void fail ( Type type , Writable expect , Writable actual , ValueOption < ? > expectVal , ValueOption < ? > actualVal , ColumnInfo columnInfo ) { String format = "" ; String additionalMessage = String . format ( format , columnInfo . getTableName ( ) , getKeyValueString ( actual ) , columnInfo . getColumnName ( ) , expectVal . toString ( ) , actualVal . toString ( ) ) ; Cause cause = new Cause ( type , additionalMessage , expect , actual , expectVal , actualVal , columnInfo ) ; causes . add ( cause ) ; } private String getKeyValueString ( Writable model ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "" ) ; boolean first = true ; for ( ColumnInfo info : getKeyColumnInfos ( ) ) { if ( info . isKey ( ) ) { if ( first ) { first = false ; } else { sb . append ( "" ) ; } sb . append ( info . getColumnName ( ) ) ; sb . append ( "" ) ; sb . append ( getValue ( model , info ) . toString ( ) ) ; } } sb . append ( "" ) ; return sb . toString ( ) ; } protected final List < ColumnInfo > getColumnInfos ( ) { return columnInfos ; } @ Override public void setColumnInfos ( List < ColumnInfo > columnInfos ) { this . columnInfos = columnInfos ; for ( ColumnInfo info : columnInfos ) { keyColumnInfos . add ( info ) ; } } protected final List < ColumnInfo > getKeyColumnInfos ( ) { return keyColumnInfos ; } @ Override public void setStartTime ( long startTime ) { this . startTime = startTime ; } public long getFinishTime ( ) { return finishTime ; } @ Override public void setFinishTime ( long finishTime ) { this . finishTime = finishTime ; } @ Override public final List < Cause > getCauses ( ) { return causes ; } protected final ValueOption < ? > getValue ( Writable model , ColumnInfo info ) { ValueOption < ? > vo = null ; try { Method method = model . getClass ( ) . getMethod ( info . getGetterName ( ) ) ; vo = ( ValueOption < ? > ) method . invoke ( model ) ; } catch ( SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } return vo ; } @ Override public boolean isSuccess ( ) { if ( causes . size ( ) == ) { return true ; } else { return false ; } } protected long getStartTime ( ) { return startTime ; } @ Override public boolean inspect ( TestDataHolder dataHolder ) { if ( finishTime == ) { finishTime = System . currentTimeMillis ( ) ; } dataHolder . sort ( ) ; if ( dataHolder . getRowMatchingCondition ( ) == RowMatchingCondition . NONE ) { return true ; } Comparator < Writable > comparator = new ModelComparator < Writable > ( columnInfos , dataHolder . getModelClass ( ) ) ; List < Writable > expect = dataHolder . getExpect ( ) ; for ( int i = , n = expect . size ( ) ; i < n ; i ++ ) { if ( comparator . compare ( expect . get ( i - ) , expect . get ( i ) ) == ) { fail ( Type . DUPLICATEED_KEY_IN_EXPECT_RECORDS , expect . get ( i ) , null ) ; } } List < Writable > actual = dataHolder . getActual ( ) ; for ( int i = , n = actual . size ( ) ; i < n ; i ++ ) { if ( comparator . compare ( actual . get ( i - ) , actual . get ( i ) ) == ) { fail ( Type . DUPLICATEED_KEY_IN_ACTUALT_RECORDS , null , actual . get ( i ) ) ; } } if ( ! isSuccess ( ) ) { return false ; } Iterator < Writable > expectIterator = expect . iterator ( ) ; Iterator < Writable > actualIterator = actual . iterator ( ) ; Writable expectRow = null ; Writable actualRow = null ; for ( ; ; ) { if ( ! expectIterator . hasNext ( ) && expectRow == null ) { if ( actualRow != null ) { fail ( Type . NO_EXPECT_RECORD , null , actualRow ) ; } while ( actualIterator . hasNext ( ) ) { actualRow = actualIterator . next ( ) ; if ( dataHolder . getRowMatchingCondition ( ) == RowMatchingCondition . EXACT ) { fail ( Type . NO_EXPECT_RECORD , null , actualRow ) ; } } break ; } if ( ! actualIterator . hasNext ( ) && actualRow == null ) { if ( expectRow != null ) { fail ( Type . NO_ACTUAL_RECORD , expectRow , null ) ; } while ( expectIterator . hasNext ( ) ) { expectRow = expectIterator . next ( ) ; fail ( Type . NO_ACTUAL_RECORD , expectRow , null ) ; } break ; } if ( expectRow == null ) { expectRow = expectIterator . next ( ) ; } if ( actualRow == null ) { actualRow = actualIterator . next ( ) ; } int result = comparator . compare ( expectRow , actualRow ) ; if ( result < ) { fail ( Type . NO_ACTUAL_RECORD , expectRow , null ) ; expectRow = null ; } else if ( result == ) { inspect ( expectRow , actualRow ) ; expectRow = null ; actualRow = null ; } else { if ( dataHolder . getRowMatchingCondition ( ) == RowMatchingCondition . EXACT ) { fail ( Type . NO_EXPECT_RECORD , null , actualRow ) ; } actualRow = null ; } } return true ; } public void clear ( ) { finishTime = ; causes . clear ( ) ; } } package com . asakusafw . testtools ; import java . util . HashMap ; import java . util . Map ; public enum ColumnMatchingCondition { NONE ( "" ) , EXACT ( "" ) , PARTIAL ( "" ) , NOW ( "" ) , TODAY ( "" ) ; private String japaneseName ; private ColumnMatchingCondition ( String japaneseName ) { this . japaneseName = japaneseName ; } public String getJapaneseName ( ) { return japaneseName ; } private static Map < String , ColumnMatchingCondition > japaneseNameMap = new HashMap < String , ColumnMatchingCondition > ( ) ; static { for ( ColumnMatchingCondition conditon : ColumnMatchingCondition . values ( ) ) { String key = conditon . getJapaneseName ( ) ; if ( japaneseNameMap . containsKey ( key ) ) { throw new RuntimeException ( "" ) ; } japaneseNameMap . put ( key , conditon ) ; } } public static ColumnMatchingCondition getConditonByJapanseName ( String key ) { return japaneseNameMap . get ( key ) ; } public static String [ ] getJapaneseNames ( ) { ColumnMatchingCondition [ ] values = ColumnMatchingCondition . values ( ) ; String [ ] result = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { result [ i ] = values [ i ] . getJapaneseName ( ) ; } return result ; } } package com . asakusafw . testtools . excel ; public class InvalidExcelBookException extends RuntimeException { private static final long serialVersionUID = ; public InvalidExcelBookException ( String message ) { super ( message ) ; } } package com . asakusafw . testtools . excel ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . math . BigDecimal ; import java . text . DateFormat ; 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 org . apache . hadoop . io . Writable ; import org . apache . poi . hssf . usermodel . HSSFCell ; import org . apache . poi . hssf . usermodel . HSSFRow ; import org . apache . poi . hssf . usermodel . HSSFSheet ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . Cell ; import org . apache . poi . ss . usermodel . DateUtil ; import org . apache . poi . ss . usermodel . Row ; import com . asakusafw . modelgen . emitter . JavaName ; import com . asakusafw . modelgen . source . MySqlDataType ; import com . asakusafw . runtime . value . ByteOption ; import com . asakusafw . runtime . value . DateOption ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateTimeOption ; import com . asakusafw . runtime . value . DecimalOption ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . ShortOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . ColumnMatchingCondition ; import com . asakusafw . testtools . ConditionSheetItem ; import com . asakusafw . testtools . Configuration ; import com . asakusafw . testtools . Constants ; import com . asakusafw . testtools . NullValueCondition ; import com . asakusafw . testtools . RowMatchingCondition ; import com . asakusafw . testtools . TestDataHolder ; public class ExcelUtils { public static final long EXCEL_MAX_LONG = ; public static final long EXCEL_MIN_LONG = - ; private final String filename ; private final String tablename ; private final RowMatchingCondition rowMatchingCondition ; private final HSSFWorkbook workbook ; private final HSSFSheet inputDataSheet ; private final HSSFSheet outputDataSheet ; private final HSSFSheet testConditionSheet ; private final DateFormat dateFormat = new SimpleDateFormat ( com . asakusafw . runtime . value . Date . FORMAT ) ; private final DateFormat dateTimeFormat = new SimpleDateFormat ( DateTime . FORMAT ) ; private final List < ColumnInfo > columnInfos ; public ExcelUtils ( String filename ) throws IOException { this . filename = filename ; InputStream is = new FileInputStream ( filename ) ; workbook = new HSSFWorkbook ( is ) ; inputDataSheet = workbook . getSheet ( Constants . INPUT_DATA_SHEET_NAME ) ; if ( inputDataSheet == null ) { throw new IOException ( "" + filename + "" ) ; } outputDataSheet = workbook . getSheet ( Constants . OUTPUT_DATA_SHEET_NAME ) ; if ( outputDataSheet == null ) { throw new IOException ( "" + filename + "" ) ; } testConditionSheet = workbook . getSheet ( Constants . TEST_CONDITION_SHEET_NAME ) ; if ( testConditionSheet == null ) { throw new IOException ( "" + filename + "" ) ; } HSSFCell tableNameCell = getCell ( testConditionSheet , ConditionSheetItem . TABLE_NAME . getRow ( ) , ConditionSheetItem . TABLE_NAME . getCol ( ) + ) ; tablename = tableNameCell . getStringCellValue ( ) ; if ( tablename == null || tablename . length ( ) == ) { throw new IOException ( "" + filename + "" ) ; } HSSFCell rowMatchingConditionCell = getCell ( testConditionSheet , ConditionSheetItem . ROW_MATCHING_CONDITION . getRow ( ) , ConditionSheetItem . ROW_MATCHING_CONDITION . getCol ( ) + ) ; String rowMatchingConditionStr = rowMatchingConditionCell . getStringCellValue ( ) ; if ( rowMatchingConditionStr == null || rowMatchingConditionStr . length ( ) == ) { throw new IOException ( "" + filename + "" ) ; } rowMatchingCondition = RowMatchingCondition . getConditonByJapanseName ( rowMatchingConditionStr ) ; if ( rowMatchingCondition == null ) { throw new IOException ( "" + filename + "" ) ; } columnInfos = createColumnInfos ( ) ; } private HSSFCell getCell ( HSSFSheet sheet , HSSFRow row , int col ) { HSSFCell cell = row . getCell ( col ) ; if ( cell == null ) { String fmt = "" ; String msg = String . format ( fmt , filename , sheet . getSheetName ( ) , row . getRowNum ( ) + , col + ) ; throw new InvalidExcelBookException ( msg ) ; } return cell ; } private HSSFCell getCell ( HSSFSheet sheet , int rownum , int col ) { HSSFRow row = sheet . getRow ( rownum ) ; if ( isEmpty ( row ) ) { String fmt = "" ; String msg = String . format ( fmt , filename , sheet . getSheetName ( ) , rownum ) ; throw new InvalidExcelBookException ( msg ) ; } HSSFCell cell = getCell ( sheet , row , col ) ; return cell ; } private HSSFCell getCell ( ConditionSheetItem item , HSSFRow row ) { int col = item . getCol ( ) ; HSSFCell cell = getCell ( testConditionSheet , row , col ) ; return cell ; } private String getStringCellValue ( HSSFSheet sheet , ConditionSheetItem item , HSSFRow row ) { HSSFCell cell = getCell ( item , row ) ; String ret ; if ( cell . getCellType ( ) == Cell . CELL_TYPE_NUMERIC ) { double dval = cell . getNumericCellValue ( ) ; ret = Double . toString ( dval ) ; ret = ret . replaceAll ( "" , "" ) ; } else if ( cell . getCellType ( ) == Cell . CELL_TYPE_BLANK ) { ret = "" ; } else if ( cell . getCellType ( ) != Cell . CELL_TYPE_STRING ) { String fmt = "" ; int rownum = row . getRowNum ( ) + ; int col = item . getCol ( ) + ; String msg = String . format ( fmt , filename , sheet . getSheetName ( ) , rownum , col ) ; throw new InvalidExcelBookException ( msg ) ; } else { ret = cell . getStringCellValue ( ) ; } return ret ; } private Double getDubleCellValue ( HSSFSheet sheet , ConditionSheetItem item , HSSFRow row ) { HSSFCell cell = getCell ( item , row ) ; Double ret ; if ( cell . getCellType ( ) == Cell . CELL_TYPE_STRING ) { String str = cell . getStringCellValue ( ) ; if ( str == null || str . length ( ) == ) { ret = null ; } else { try { ret = Double . parseDouble ( str ) ; } catch ( NumberFormatException e ) { String fmt = "" ; int rownum = row . getRowNum ( ) + ; int col = item . getCol ( ) + ; String msg = String . format ( fmt , filename , sheet . getSheetName ( ) , rownum , col ) ; throw new InvalidExcelBookException ( msg ) ; } } } else if ( cell . getCellType ( ) == Cell . CELL_TYPE_BLANK ) { ret = null ; } else if ( cell . getCellType ( ) != Cell . CELL_TYPE_NUMERIC ) { String fmt = "" ; int rownum = row . getRowNum ( ) + ; int col = item . getCol ( ) + ; String msg = String . format ( fmt , filename , sheet . getSheetName ( ) , rownum , col ) ; throw new InvalidExcelBookException ( msg ) ; } else { ret = cell . getNumericCellValue ( ) ; } return ret ; } private String creaetExceptionMessage ( ConditionSheetItem item , HSSFRow row ) { String fmt = "" ; String msg = String . format ( fmt , filename , row . getRowNum ( ) + , item . getName ( ) ) ; return msg ; } private List < ColumnInfo > createColumnInfos ( ) throws IOException { List < ColumnInfo > list = new ArrayList < ColumnInfo > ( ) ; int rownum = ConditionSheetItem . NO . getRow ( ) ; for ( ; ; ) { rownum ++ ; HSSFRow row = testConditionSheet . getRow ( rownum ) ; if ( isEmpty ( row ) ) { break ; } String columnName = getStringCellValue ( testConditionSheet , ConditionSheetItem . COLUMN_NAME , row ) ; if ( columnName . length ( ) == ) { String msg = creaetExceptionMessage ( ConditionSheetItem . COLUMN_NAME , row ) ; throw new InvalidExcelBookException ( msg ) ; } String columnComment = getStringCellValue ( testConditionSheet , ConditionSheetItem . COLUMN_COMMENT , row ) ; String dataTypeStr = getStringCellValue ( testConditionSheet , ConditionSheetItem . DATA_TYPE , row ) ; MySqlDataType dataType = MySqlDataType . getDataTypeByString ( dataTypeStr ) ; if ( dataType == null ) { String msg = creaetExceptionMessage ( ConditionSheetItem . DATA_TYPE , row ) ; throw new InvalidExcelBookException ( msg ) ; } Double dWidth = getDubleCellValue ( testConditionSheet , ConditionSheetItem . WIDTH , row ) ; Double dScale = getDubleCellValue ( testConditionSheet , ConditionSheetItem . SCALE , row ) ; long characterMaximumLength = ; int numericPrecision = ; int numericScale = ; switch ( dataType ) { case CHAR : case VARCHAR : if ( dWidth == null ) { String msg = creaetExceptionMessage ( ConditionSheetItem . WIDTH , row ) ; throw new InvalidExcelBookException ( msg ) ; } characterMaximumLength = dWidth . longValue ( ) ; break ; case DECIMAL : if ( dWidth == null ) { String msg = creaetExceptionMessage ( ConditionSheetItem . WIDTH , row ) ; throw new InvalidExcelBookException ( msg ) ; } numericPrecision = dWidth . intValue ( ) ; if ( dScale == null ) { String msg = creaetExceptionMessage ( ConditionSheetItem . SCALE , row ) ; throw new InvalidExcelBookException ( msg ) ; } numericScale = dScale . intValue ( ) ; break ; default : break ; } String keyStr = getStringCellValue ( testConditionSheet , ConditionSheetItem . KEY_FLAG , row ) ; boolean key = true ; if ( keyStr . trim ( ) . length ( ) == ) { key = false ; } String nullableStr = getStringCellValue ( testConditionSheet , ConditionSheetItem . NULLABLE , row ) ; boolean nullable = true ; if ( nullableStr . trim ( ) . length ( ) == ) { nullable = false ; } String columnMatchingConditionStr = getStringCellValue ( testConditionSheet , ConditionSheetItem . MATCHING_CONDITION , row ) ; ColumnMatchingCondition columnMatchingCondition = ColumnMatchingCondition . getConditonByJapanseName ( columnMatchingConditionStr ) ; if ( columnMatchingCondition == null ) { String msg = creaetExceptionMessage ( ConditionSheetItem . MATCHING_CONDITION , row ) ; throw new InvalidExcelBookException ( msg ) ; } String nullValueConditionStr = getStringCellValue ( testConditionSheet , ConditionSheetItem . NULL_VALUE_CONDITION , row ) ; NullValueCondition nullValueCondition = NullValueCondition . getConditonByJapanseName ( nullValueConditionStr ) ; if ( nullValueCondition == null ) { String msg = creaetExceptionMessage ( ConditionSheetItem . NULL_VALUE_CONDITION , row ) ; throw new InvalidExcelBookException ( msg ) ; } ColumnInfo info = new ColumnInfo ( tablename , columnName , columnComment , dataType , characterMaximumLength , numericPrecision , numericScale , nullable , key , columnMatchingCondition , nullValueCondition ) ; list . add ( info ) ; } return list ; } public Class < ? extends Writable > getModelClass ( ) { Configuration conf = Configuration . getInstance ( ) ; String pkgName = conf . getModelPackage ( ) ; String simpleName = JavaName . of ( tablename ) . toTypeName ( ) ; Class < ? extends Writable > cl ; cl = findModelClass ( pkgName , null , simpleName ) ; if ( cl != null ) { return cl ; } cl = findModelClass ( pkgName , com . asakusafw . modelgen . Constants . SOURCE_TABLE , simpleName ) ; if ( cl != null ) { return cl ; } cl = findModelClass ( pkgName , com . asakusafw . modelgen . Constants . SOURCE_VIEW , simpleName ) ; if ( cl != null ) { return cl ; } throw new RuntimeException ( new ClassNotFoundException ( buildModelClassName ( pkgName , null , simpleName ) ) ) ; } private Class < ? extends Writable > findModelClass ( String pkgName , String sourceOrNull , String simpleName ) { assert pkgName != null ; assert simpleName != null ; String qualifiedName = buildModelClassName ( pkgName , sourceOrNull , simpleName ) ; Class < ? extends Writable > cl ; try { cl = Class . forName ( qualifiedName ) . asSubclass ( Writable . class ) ; } catch ( ClassNotFoundException e ) { return null ; } return cl ; } private String buildModelClassName ( String pkgName , String sourceOrNull , String simpleName ) { assert pkgName != null ; assert simpleName != null ; StringBuilder modelClassName = new StringBuilder ( ) ; modelClassName . append ( pkgName ) ; modelClassName . append ( '' ) ; if ( sourceOrNull != null ) { modelClassName . append ( sourceOrNull ) ; modelClassName . append ( '' ) ; } modelClassName . append ( com . asakusafw . modelgen . Constants . CATEGORY_MODEL ) ; modelClassName . append ( '' ) ; modelClassName . append ( simpleName ) ; String qualifiedName = modelClassName . toString ( ) ; return qualifiedName ; } private List < Writable > createDatalList ( HSSFSheet sheet ) { List < Writable > list = new ArrayList < Writable > ( ) ; Class < ? > modelClass = getModelClass ( ) ; int rownum = ; for ( ; ; ) { rownum ++ ; HSSFRow row = sheet . getRow ( rownum ) ; if ( isEmpty ( row ) ) { break ; } Writable model ; try { model = ( Writable ) modelClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } for ( int col = ; col < columnInfos . size ( ) ; col ++ ) { HSSFCell cell = row . getCell ( col , Row . CREATE_NULL_AS_BLANK ) ; MySqlDataType type = columnInfos . get ( col ) . getDataType ( ) ; ValueOption < ? > vo ; switch ( type ) { case CHAR : case VARCHAR : vo = getStringOption ( cell ) ; break ; case DATE : vo = getDateOption ( cell ) ; break ; case DATETIME : case TIMESTAMP : vo = getDateTimeOption ( cell ) ; break ; case DECIMAL : vo = getDecimalOption ( cell ) ; break ; case TINY_INT : vo = getByteOption ( cell ) ; break ; case SMALL_INT : vo = getShortOption ( cell ) ; break ; case INT : vo = getIntOption ( cell ) ; break ; case LONG : vo = getLongOption ( cell ) ; break ; default : throw new RuntimeException ( "" + type ) ; } try { String setterName = columnInfos . get ( col ) . getSetterName ( ) ; Method setter = model . getClass ( ) . getMethod ( setterName , vo . getClass ( ) ) ; setter . invoke ( model , vo ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } } list . add ( model ) ; } return list ; } private boolean isEmpty ( HSSFRow row ) { if ( row == null ) { return true ; } for ( Iterator < Cell > iter = row . cellIterator ( ) ; iter . hasNext ( ) ; ) { if ( iter . next ( ) . getCellType ( ) != Cell . CELL_TYPE_BLANK ) { return false ; } } return true ; } private ByteOption getByteOption ( HSSFCell cell ) { Long l = getLong ( cell ) ; ByteOption op = new ByteOption ( ) ; if ( l == null ) { op . setNull ( ) ; } else { if ( l < Byte . MIN_VALUE || Byte . MAX_VALUE < l ) { String msg = createExceptionMsg ( cell , "" + l + "" ) ; throw new NumberFormatException ( msg ) ; } op . modify ( l . byteValue ( ) ) ; } return op ; } private ShortOption getShortOption ( HSSFCell cell ) { Long l = getLong ( cell ) ; ShortOption op = new ShortOption ( ) ; if ( l == null ) { op . setNull ( ) ; } else { if ( l < Short . MIN_VALUE || Short . MAX_VALUE < l ) { String msg = createExceptionMsg ( cell , "" + l + "" ) ; throw new NumberFormatException ( msg ) ; } op . modify ( l . shortValue ( ) ) ; } return op ; } private IntOption getIntOption ( HSSFCell cell ) { Long l = getLong ( cell ) ; IntOption op = new IntOption ( ) ; if ( l == null ) { op . setNull ( ) ; } else { if ( l < Integer . MIN_VALUE || Integer . MAX_VALUE < l ) { String msg = createExceptionMsg ( cell , "" + l + "" ) ; throw new NumberFormatException ( msg ) ; } op . modify ( l . intValue ( ) ) ; } return op ; } private LongOption getLongOption ( HSSFCell cell ) { Long l = getLong ( cell ) ; LongOption op = new LongOption ( ) ; if ( l == null ) { op . setNull ( ) ; } else { op . modify ( l ) ; } return op ; } private DateOption getDateOption ( HSSFCell cell ) { Date date = getDate ( cell ) ; DateOption op = new DateOption ( ) ; if ( date == null ) { op . setNull ( ) ; } else { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int h = cal . get ( Calendar . HOUR_OF_DAY ) ; int min = cal . get ( Calendar . MINUTE ) ; int s = cal . get ( Calendar . SECOND ) ; if ( h != || min != || s != ) { String msg = createExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } int days = com . asakusafw . runtime . value . DateUtil . getDayFromDate ( y , m + , d ) ; op . modify ( days ) ; } return op ; } private DateTimeOption getDateTimeOption ( HSSFCell cell ) { Date date = getDate ( cell ) ; DateTimeOption op = new DateTimeOption ( ) ; if ( date == null ) { op . setNull ( ) ; } else { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; int y = cal . get ( Calendar . YEAR ) ; int m = cal . get ( Calendar . MONTH ) ; int d = cal . get ( Calendar . DAY_OF_MONTH ) ; int h = cal . get ( Calendar . HOUR_OF_DAY ) ; int min = cal . get ( Calendar . MINUTE ) ; int s = cal . get ( Calendar . SECOND ) ; int days = com . asakusafw . runtime . value . DateUtil . getDayFromDate ( y , m + , d ) ; int secs = com . asakusafw . runtime . value . DateUtil . getSecondFromTime ( h , min , s ) ; DateTime dt = new DateTime ( ) ; dt . setElapsedSeconds ( ( long ) days * + secs ) ; op . modify ( dt ) ; } return op ; } private StringOption getStringOption ( HSSFCell cell ) { String str ; switch ( cell . getCellType ( ) ) { case Cell . CELL_TYPE_BLANK : str = null ; break ; case Cell . CELL_TYPE_BOOLEAN : if ( cell . getBooleanCellValue ( ) ) { str = "" ; } else { str = "" ; } break ; case Cell . CELL_TYPE_NUMERIC : if ( DateUtil . isCellDateFormatted ( cell ) ) { double d = cell . getNumericCellValue ( ) ; Date date = DateUtil . getJavaDate ( d ) ; str = dateTimeFormat . format ( date ) ; } else { double d = cell . getNumericCellValue ( ) ; str = Double . toString ( d ) ; str = str . replaceAll ( "" , "" ) ; } break ; case Cell . CELL_TYPE_STRING : str = cell . getStringCellValue ( ) ; break ; case Cell . CELL_TYPE_ERROR : case Cell . CELL_TYPE_FORMULA : default : String msg = createCellTypeMismatchExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } StringOption stringOption = new StringOption ( ) ; stringOption . modify ( str ) ; return stringOption ; } private DecimalOption getDecimalOption ( HSSFCell cell ) { BigDecimal bigDecimal ; switch ( cell . getCellType ( ) ) { case Cell . CELL_TYPE_BLANK : bigDecimal = null ; break ; case Cell . CELL_TYPE_BOOLEAN : if ( cell . getBooleanCellValue ( ) ) { bigDecimal = new BigDecimal ( ) ; } else { bigDecimal = new BigDecimal ( ) ; } break ; case Cell . CELL_TYPE_NUMERIC : if ( DateUtil . isCellDateFormatted ( cell ) ) { String msg = createCellTypeMismatchExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } else { double d = cell . getNumericCellValue ( ) ; if ( d < EXCEL_MIN_LONG || EXCEL_MAX_LONG < d ) { String msg = createExceptionMsg ( cell , "" + d + "" ) ; throw new NumberFormatException ( msg ) ; } long l = ( long ) d ; if ( l != d ) { String msg = createExceptionMsg ( cell , "" ) ; throw new NumberFormatException ( msg ) ; } String str = Double . toString ( d ) ; str = str . replaceAll ( "" , "" ) ; bigDecimal = new BigDecimal ( str ) ; } break ; case Cell . CELL_TYPE_STRING : String str = cell . getStringCellValue ( ) ; try { bigDecimal = new BigDecimal ( str ) ; } catch ( NumberFormatException e ) { String msg = createExceptionMsg ( cell , "" ) ; throw new NumberFormatException ( msg ) ; } break ; case Cell . CELL_TYPE_ERROR : case Cell . CELL_TYPE_FORMULA : default : String msg = createCellTypeMismatchExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } DecimalOption decimalOption = new DecimalOption ( ) ; decimalOption . modify ( bigDecimal ) ; return decimalOption ; } private Date getDate ( HSSFCell cell ) { Date date ; switch ( cell . getCellType ( ) ) { case Cell . CELL_TYPE_BLANK : date = null ; break ; case Cell . CELL_TYPE_NUMERIC : if ( DateUtil . isCellDateFormatted ( cell ) ) { double d = cell . getNumericCellValue ( ) ; date = DateUtil . getJavaDate ( d ) ; } else { String msg = createCellTypeMismatchExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } break ; case Cell . CELL_TYPE_STRING : String str = cell . getStringCellValue ( ) ; try { date = dateTimeFormat . parse ( str ) ; } catch ( Exception e ) { try { date = dateFormat . parse ( str ) ; } catch ( Exception e2 ) { String msg = createCellTypeMismatchExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } } break ; case Cell . CELL_TYPE_BOOLEAN : case Cell . CELL_TYPE_ERROR : case Cell . CELL_TYPE_FORMULA : default : String msg = createCellTypeMismatchExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } return date ; } private Long getLong ( HSSFCell cell ) { Long l ; switch ( cell . getCellType ( ) ) { case Cell . CELL_TYPE_BLANK : l = null ; break ; case Cell . CELL_TYPE_BOOLEAN : if ( cell . getBooleanCellValue ( ) ) { l = ; } else { l = ; } break ; case Cell . CELL_TYPE_NUMERIC : double d = cell . getNumericCellValue ( ) ; if ( d < EXCEL_MIN_LONG || EXCEL_MAX_LONG < d ) { String msg = createExceptionMsg ( cell , "" + d + "" ) ; throw new NumberFormatException ( msg ) ; } l = ( long ) d ; if ( ( double ) l != d ) { String msg = createExceptionMsg ( cell , "" ) ; throw new NumberFormatException ( msg ) ; } break ; case Cell . CELL_TYPE_STRING : try { String str = cell . getStringCellValue ( ) ; l = Long . parseLong ( str ) ; } catch ( Exception e ) { String msg = createCellTypeMismatchExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } break ; case Cell . CELL_TYPE_ERROR : case Cell . CELL_TYPE_FORMULA : default : String msg = createCellTypeMismatchExceptionMsg ( cell , "" ) ; throw new CellTypeMismatchException ( msg ) ; } return l ; } private String createExceptionMsg ( HSSFCell cell , String msg ) { int col = cell . getColumnIndex ( ) ; int rownum = cell . getRowIndex ( ) ; String sheetName = cell . getSheet ( ) . getSheetName ( ) ; String fmt = "" ; String ret = String . format ( fmt , msg , filename , sheetName , rownum + , col + ) ; return ret ; } private String createCellTypeMismatchExceptionMsg ( HSSFCell cell , String expect ) { int col = cell . getColumnIndex ( ) ; int rownum = cell . getRowIndex ( ) ; String sheetName = cell . getSheet ( ) . getSheetName ( ) ; String actual ; switch ( cell . getCellType ( ) ) { case Cell . CELL_TYPE_BLANK : actual = "" ; break ; case Cell . CELL_TYPE_BOOLEAN : actual = "" ; break ; case Cell . CELL_TYPE_ERROR : actual = "" ; break ; case Cell . CELL_TYPE_FORMULA : actual = "" ; break ; case Cell . CELL_TYPE_NUMERIC : if ( DateUtil . isCellDateFormatted ( cell ) ) { actual = "" ; } else { actual = "" ; } break ; case Cell . CELL_TYPE_STRING : actual = "" ; break ; default : actual = "" ; break ; } String fmt = "" + "" ; String ret = String . format ( fmt , expect , actual , filename , sheetName , rownum + , col + ) ; return ret ; } public List < ColumnInfo > getColumnInfos ( ) { return columnInfos ; } public TestDataHolder getTestDataHolder ( ) { List < Writable > source = createDatalList ( inputDataSheet ) ; List < Writable > expect = createDatalList ( outputDataSheet ) ; Class < ? extends Writable > modelClass = getModelClass ( ) ; return new TestDataHolder ( source , expect , columnInfos , modelClass , rowMatchingCondition ) ; } } package com . asakusafw . testtools . excel ; public class CellTypeMismatchException extends RuntimeException { private static final long serialVersionUID = ; public CellTypeMismatchException ( String message ) { super ( message ) ; } } @ java . lang . Deprecated package com . asakusafw . testtools . excel ; package com . asakusafw . testtools ; import java . util . HashMap ; import java . util . Map ; public enum NullValueCondition { NORMAL ( "" ) , NULL_IS_OK ( "" ) , NULL_IS_NG ( "" ) , NOT_NULL_IS_OK ( "" ) , NOT_NULL_IS_NG ( "" ) ; private String japaneseName ; private NullValueCondition ( String japaneseName ) { this . japaneseName = japaneseName ; } public String getJapaneseName ( ) { return japaneseName ; } private static Map < String , NullValueCondition > japaneseNameMap = new HashMap < String , NullValueCondition > ( ) ; static { for ( NullValueCondition conditon : NullValueCondition . values ( ) ) { String key = conditon . getJapaneseName ( ) ; if ( japaneseNameMap . containsKey ( key ) ) { throw new RuntimeException ( "" ) ; } japaneseNameMap . put ( key , conditon ) ; } } public static NullValueCondition getConditonByJapanseName ( String key ) { return japaneseNameMap . get ( key ) ; } public static String [ ] getJapaneseNames ( ) { NullValueCondition [ ] values = NullValueCondition . values ( ) ; String [ ] result = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { result [ i ] = values [ i ] . getJapaneseName ( ) ; } return result ; } } package com . asakusafw . testtools ; import java . util . HashMap ; import java . util . Map ; public enum RowMatchingCondition { EXACT ( "" ) , PARTIAL ( "" ) , NONE ( "" ) ; private String japaneseName ; private RowMatchingCondition ( String japaneseName ) { this . japaneseName = japaneseName ; } public String getJapaneseName ( ) { return japaneseName ; } private static Map < String , RowMatchingCondition > japaneseNameMap = new HashMap < String , RowMatchingCondition > ( ) ; static { for ( RowMatchingCondition conditon : RowMatchingCondition . values ( ) ) { String key = conditon . getJapaneseName ( ) ; if ( japaneseNameMap . containsKey ( key ) ) { throw new RuntimeException ( "" ) ; } japaneseNameMap . put ( key , conditon ) ; } } public static RowMatchingCondition getConditonByJapanseName ( String key ) { return japaneseNameMap . get ( key ) ; } public static String [ ] getJapaneseNames ( ) { RowMatchingCondition [ ] values = RowMatchingCondition . values ( ) ; String [ ] result = new String [ values . length ] ; for ( int i = ; i < values . length ; i ++ ) { result [ i ] = values [ i ] . getJapaneseName ( ) ; } return result ; } } @ java . lang . Deprecated package com . asakusafw . testtools . templategen ; package com . asakusafw . testtools . templategen ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . List ; import com . asakusafw . modelgen . source . MySQLConstants ; import com . asakusafw . modelgen . source . MySqlDataType ; import com . asakusafw . testtools . ColumnInfo ; public final class DatabaseSchema { public static ColumnInfo [ ] collectColumns ( Connection conn , String databaseName , String tableName ) throws SQLException { String sql = "" + "" + "" + "" + "" + "" + "" + "" ; List < ColumnInfo > list = new ArrayList < ColumnInfo > ( ) ; PreparedStatement ps = null ; ResultSet rs = null ; try { ps = conn . prepareStatement ( sql ) ; ps . setString ( , databaseName ) ; ps . setString ( , tableName ) ; rs = ps . executeQuery ( ) ; while ( rs . next ( ) ) { String columnName = rs . getString ( ) ; String columnComment = rs . getString ( ) ; String dataTypeStr = rs . getString ( ) ; long characterMaximumLength = rs . getLong ( ) ; int numericPrecision = rs . getInt ( ) ; int numericScale = rs . getInt ( ) ; String isNullableStr = rs . getString ( ) ; String columnKeyStr = rs . getString ( ) ; MySqlDataType dataType = MySqlDataType . getDataTypeByString ( dataTypeStr ) ; if ( dataType == null ) { throw new RuntimeException ( "" + dataTypeStr + "" + "" ) ; } boolean nullable = true ; if ( isNullableStr != null && isNullableStr . equals ( MySQLConstants . STR_NOT_NULL ) ) { nullable = false ; } boolean pk = false ; if ( columnKeyStr != null && columnKeyStr . equals ( MySQLConstants . STR_IS_PK ) ) { pk = true ; } ColumnInfo info = new ColumnInfo ( tableName , columnName , columnComment , dataType , characterMaximumLength , numericPrecision , numericScale , nullable , pk , null , null ) ; list . add ( info ) ; } } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( ps != null ) { try { ps . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } if ( list . size ( ) == ) { throw new RuntimeException ( "" + tableName + "" + databaseName + "" ) ; } return list . toArray ( new ColumnInfo [ list . size ( ) ] ) ; } private DatabaseSchema ( ) { return ; } } package com . asakusafw . testtools . templategen ; import java . io . File ; import java . io . IOException ; import java . sql . Connection ; import java . sql . SQLException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import com . asakusafw . testtools . Configuration ; import com . asakusafw . testtools . db . DbUtils ; public final class Main { private Connection conn ; private List < String > tableList ; private String databaseName ; private File outputDirectory ; public static void main ( String [ ] args ) throws IOException , SQLException { Main main = new Main ( args ) ; main . run ( ) ; } private Main ( String [ ] args ) throws SQLException { if ( args . length == ) { throw new IllegalArgumentException ( "" ) ; } tableList = new ArrayList < String > ( args . length ) ; for ( String tablename : args ) { tableList . add ( tablename ) ; } Configuration conf = Configuration . getInstance ( ) ; String outputDirectoryName = conf . getOutputDirectory ( ) ; if ( outputDirectoryName == null ) { throw new IllegalArgumentException ( "" ) ; } outputDirectory = new File ( outputDirectoryName ) ; if ( ! outputDirectory . exists ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , outputDirectoryName ) ) ; } if ( ! outputDirectory . isDirectory ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , outputDirectoryName ) ) ; } if ( ! outputDirectory . canWrite ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , outputDirectoryName ) ) ; } databaseName = conf . getDatabaseName ( ) ; if ( databaseName == null ) { throw new IllegalArgumentException ( "" ) ; } conn = DbUtils . getConnection ( ) ; } private void run ( ) throws IOException , SQLException { for ( String tableName : tableList ) { ExcelBookBuilder ebb = new ExcelBookBuilder ( conn , tableName , databaseName ) ; ebb . build ( outputDirectory ) ; } } } package com . asakusafw . testtools . templategen ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . math . BigDecimal ; import java . sql . Connection ; import java . sql . Date ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Timestamp ; import java . text . MessageFormat ; import org . apache . poi . hssf . usermodel . DVConstraint ; import org . apache . poi . hssf . usermodel . HSSFCell ; import org . apache . poi . hssf . usermodel . HSSFCellStyle ; import org . apache . poi . hssf . usermodel . HSSFDataValidation ; import org . apache . poi . hssf . usermodel . HSSFFont ; import org . apache . poi . hssf . usermodel . HSSFRow ; import org . apache . poi . hssf . usermodel . HSSFSheet ; import org . apache . poi . hssf . usermodel . HSSFWorkbook ; import org . apache . poi . ss . usermodel . CellStyle ; import org . apache . poi . ss . usermodel . CreationHelper ; import org . apache . poi . ss . usermodel . DataFormat ; import org . apache . poi . ss . usermodel . IndexedColors ; import org . apache . poi . ss . util . CellRangeAddressList ; import com . asakusafw . testtools . ColumnInfo ; import com . asakusafw . testtools . ColumnMatchingCondition ; import com . asakusafw . testtools . ConditionSheetItem ; import com . asakusafw . testtools . Constants ; import com . asakusafw . testtools . NullValueCondition ; import com . asakusafw . testtools . RowMatchingCondition ; import com . asakusafw . testtools . db . DbUtils ; public class ExcelBookBuilder { private static final String CELL_TRUE = "" ; private static final String CELL_FALSE = "" ; private static final String CELL_EMPTY = "" ; private final Connection conn ; private final String tableName ; private final String databaseName ; private HSSFWorkbook workbook ; private ColumnInfo [ ] columnInfos ; private HSSFCellStyle commonStyle ; private HSSFCellStyle titleStyle ; private HSSFCellStyle centerAlignStyle ; private HSSFCellStyle fixedValueStyle ; private HSSFCellStyle centerAlignFixedValueStyle ; private HSSFCellStyle dateTimeStyle ; private HSSFCellStyle dateStyle ; public ExcelBookBuilder ( Connection conn , String tableName , String databaseName ) { this . conn = conn ; this . tableName = tableName ; this . databaseName = databaseName ; } public void build ( File outputDirectory ) throws IOException , SQLException { columnInfos = DatabaseSchema . collectColumns ( conn , databaseName , tableName ) ; workbook = new HSSFWorkbook ( ) ; configureColumnStyle ( ) ; HSSFSheet inputSheet = createInputDataSheet ( Constants . INPUT_DATA_SHEET_NAME ) ; int inputSheetIndex = workbook . getSheetIndex ( inputSheet ) ; HSSFSheet outputSheet = workbook . cloneSheet ( inputSheetIndex ) ; int outputSheetIndex = workbook . getSheetIndex ( outputSheet ) ; workbook . setSheetName ( outputSheetIndex , Constants . OUTPUT_DATA_SHEET_NAME ) ; createTestConditionSheet ( Constants . TEST_CONDITION_SHEET_NAME ) ; String bookName = tableName + "" ; File outputFile = new File ( outputDirectory , bookName ) ; OutputStream os = new FileOutputStream ( outputFile ) ; try { workbook . write ( os ) ; } finally { DbUtils . closeQuietly ( os ) ; } } private void configureColumnStyle ( ) { assert workbook != null ; HSSFFont font = workbook . createFont ( ) ; font . setFontName ( "" ) ; commonStyle = workbook . createCellStyle ( ) ; commonStyle . setFont ( font ) ; commonStyle . setBorderTop ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderBottom ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderLeft ( CellStyle . BORDER_THIN ) ; commonStyle . setBorderRight ( CellStyle . BORDER_THIN ) ; titleStyle = workbook . createCellStyle ( ) ; titleStyle . cloneStyleFrom ( commonStyle ) ; titleStyle . setFillPattern ( CellStyle . SOLID_FOREGROUND ) ; titleStyle . setFillForegroundColor ( IndexedColors . LIGHT_GREEN . getIndex ( ) ) ; titleStyle . setAlignment ( CellStyle . ALIGN_CENTER ) ; centerAlignStyle = workbook . createCellStyle ( ) ; centerAlignStyle . cloneStyleFrom ( commonStyle ) ; centerAlignStyle . setAlignment ( CellStyle . ALIGN_CENTER ) ; fixedValueStyle = workbook . createCellStyle ( ) ; fixedValueStyle . cloneStyleFrom ( commonStyle ) ; fixedValueStyle . setFillPattern ( CellStyle . SOLID_FOREGROUND ) ; fixedValueStyle . setFillForegroundColor ( IndexedColors . LEMON_CHIFFON . getIndex ( ) ) ; centerAlignFixedValueStyle = workbook . createCellStyle ( ) ; centerAlignFixedValueStyle . cloneStyleFrom ( fixedValueStyle ) ; centerAlignFixedValueStyle . setAlignment ( CellStyle . ALIGN_CENTER ) ; CreationHelper helper = workbook . getCreationHelper ( ) ; DataFormat df = helper . createDataFormat ( ) ; dateTimeStyle = workbook . createCellStyle ( ) ; dateTimeStyle . cloneStyleFrom ( commonStyle ) ; dateTimeStyle . setDataFormat ( df . getFormat ( "" ) ) ; dateStyle = workbook . createCellStyle ( ) ; dateStyle . cloneStyleFrom ( commonStyle ) ; dateStyle . setDataFormat ( df . getFormat ( "" ) ) ; } private HSSFCell getCell ( HSSFSheet sheet , int rownum , int col ) { HSSFRow row = sheet . getRow ( rownum ) ; if ( row == null ) { row = sheet . createRow ( rownum ) ; } HSSFCell cell = row . getCell ( col ) ; if ( cell == null ) { cell = row . createCell ( col ) ; } cell . setCellStyle ( commonStyle ) ; return cell ; } private HSSFSheet createTestConditionSheet ( String sheetName ) { int maxColumn = ; HSSFSheet sheet = workbook . createSheet ( sheetName ) ; for ( ConditionSheetItem item : ConditionSheetItem . values ( ) ) { HSSFCell cell = getCell ( sheet , item . getRow ( ) , item . getCol ( ) ) ; cell . setCellValue ( item . getName ( ) ) ; cell . setCellStyle ( titleStyle ) ; if ( maxColumn < item . getCol ( ) ) { maxColumn = item . getCol ( ) ; } } HSSFCell tableNameCell = getCell ( sheet , ConditionSheetItem . TABLE_NAME . getRow ( ) , ConditionSheetItem . TABLE_NAME . getCol ( ) + ) ; tableNameCell . setCellStyle ( fixedValueStyle ) ; tableNameCell . setCellValue ( tableName ) ; HSSFCell rowMatichingConditionCell = getCell ( sheet , ConditionSheetItem . ROW_MATCHING_CONDITION . getRow ( ) , ConditionSheetItem . ROW_MATCHING_CONDITION . getCol ( ) + ) ; rowMatichingConditionCell . setCellValue ( RowMatchingCondition . NONE . getJapaneseName ( ) ) ; int startRow = ConditionSheetItem . NO . getRow ( ) ; int endRow = configureColumns ( sheet , startRow ) ; setExplicitListConstraint ( sheet , RowMatchingCondition . getJapaneseNames ( ) , ConditionSheetItem . ROW_MATCHING_CONDITION . getRow ( ) , ConditionSheetItem . ROW_MATCHING_CONDITION . getRow ( ) , ConditionSheetItem . ROW_MATCHING_CONDITION . getCol ( ) + , ConditionSheetItem . ROW_MATCHING_CONDITION . getCol ( ) + ) ; setExplicitListConstraint ( sheet , ColumnMatchingCondition . getJapaneseNames ( ) , startRow + , endRow , ConditionSheetItem . MATCHING_CONDITION . getCol ( ) , ConditionSheetItem . MATCHING_CONDITION . getCol ( ) ) ; setExplicitListConstraint ( sheet , NullValueCondition . getJapaneseNames ( ) , startRow + , endRow , ConditionSheetItem . NULL_VALUE_CONDITION . getCol ( ) , ConditionSheetItem . NULL_VALUE_CONDITION . getCol ( ) ) ; for ( int i = ; i <= maxColumn + ; i ++ ) { sheet . autoSizeColumn ( i ) ; } return sheet ; } private int configureColumns ( HSSFSheet sheet , int startRow ) { assert columnInfos != null ; int row = startRow ; int no = ; for ( ColumnInfo info : columnInfos ) { row ++ ; no ++ ; HSSFCell noCell = getCell ( sheet , row , ConditionSheetItem . NO . getCol ( ) ) ; noCell . setCellStyle ( centerAlignFixedValueStyle ) ; noCell . setCellValue ( no ) ; HSSFCell columnNameCell = getCell ( sheet , row , ConditionSheetItem . COLUMN_NAME . getCol ( ) ) ; columnNameCell . setCellStyle ( fixedValueStyle ) ; columnNameCell . setCellValue ( info . getColumnName ( ) ) ; HSSFCell columnCommentCell = getCell ( sheet , row , ConditionSheetItem . COLUMN_COMMENT . getCol ( ) ) ; columnCommentCell . setCellStyle ( fixedValueStyle ) ; columnCommentCell . setCellValue ( info . getColumnComment ( ) ) ; HSSFCell dataTypeCell = getCell ( sheet , row , ConditionSheetItem . DATA_TYPE . getCol ( ) ) ; dataTypeCell . setCellStyle ( centerAlignFixedValueStyle ) ; dataTypeCell . setCellValue ( info . getDataType ( ) . getDataTypeString ( ) ) ; HSSFCell widthCell = getCell ( sheet , row , ConditionSheetItem . WIDTH . getCol ( ) ) ; widthCell . setCellStyle ( centerAlignFixedValueStyle ) ; switch ( info . getDataType ( ) ) { case CHAR : case VARCHAR : widthCell . setCellValue ( info . getCharacterMaximumLength ( ) ) ; break ; case DECIMAL : widthCell . setCellValue ( info . getNumericPrecision ( ) ) ; break ; case DATE : case DATETIME : case INT : case LONG : case SMALL_INT : case TIMESTAMP : case TINY_INT : widthCell . setCellValue ( CELL_EMPTY ) ; break ; default : throw new RuntimeException ( MessageFormat . format ( "" , info . getDataType ( ) . name ( ) ) ) ; } HSSFCell scaleCell = getCell ( sheet , row , ConditionSheetItem . SCALE . getCol ( ) ) ; scaleCell . setCellStyle ( centerAlignFixedValueStyle ) ; switch ( info . getDataType ( ) ) { case DECIMAL : scaleCell . setCellValue ( info . getNumericScale ( ) ) ; break ; case CHAR : case DATE : case DATETIME : case INT : case LONG : case SMALL_INT : case TIMESTAMP : case TINY_INT : case VARCHAR : scaleCell . setCellValue ( CELL_EMPTY ) ; break ; default : throw new RuntimeException ( MessageFormat . format ( "" , info . getDataType ( ) . name ( ) ) ) ; } HSSFCell nullableCell = getCell ( sheet , row , ConditionSheetItem . NULLABLE . getCol ( ) ) ; nullableCell . setCellStyle ( centerAlignFixedValueStyle ) ; if ( info . isNullable ( ) ) { nullableCell . setCellValue ( CELL_TRUE ) ; } else { nullableCell . setCellValue ( CELL_FALSE ) ; } HSSFCell pkCell = getCell ( sheet , row , ConditionSheetItem . KEY_FLAG . getCol ( ) ) ; pkCell . setCellStyle ( centerAlignStyle ) ; if ( info . isKey ( ) ) { pkCell . setCellValue ( CELL_TRUE ) ; } else { pkCell . setCellValue ( CELL_FALSE ) ; } HSSFCell machingCondtionCell = getCell ( sheet , row , ConditionSheetItem . MATCHING_CONDITION . getCol ( ) ) ; machingCondtionCell . setCellStyle ( centerAlignStyle ) ; machingCondtionCell . setCellValue ( ColumnMatchingCondition . NONE . getJapaneseName ( ) ) ; HSSFCell nullValueConditionCell = getCell ( sheet , row , ConditionSheetItem . NULL_VALUE_CONDITION . getCol ( ) ) ; nullValueConditionCell . setCellStyle ( centerAlignStyle ) ; nullValueConditionCell . setCellValue ( NullValueCondition . NORMAL . getJapaneseName ( ) ) ; } int endRow = row ; return endRow ; } private void setExplicitListConstraint ( HSSFSheet sheet , String [ ] list , int firstRow , int lastRow , int firstCol , int lastCol ) { CellRangeAddressList addressList = new CellRangeAddressList ( firstRow , lastRow , firstCol , lastCol ) ; DVConstraint constraint = DVConstraint . createExplicitListConstraint ( list ) ; HSSFDataValidation validation = new HSSFDataValidation ( addressList , constraint ) ; validation . setEmptyCellAllowed ( true ) ; validation . setSuppressDropDownArrow ( false ) ; sheet . addValidationData ( validation ) ; } private HSSFSheet createInputDataSheet ( String sheetName ) throws SQLException { HSSFSheet sheet = workbook . createSheet ( sheetName ) ; HSSFRow row = sheet . createRow ( ) ; for ( int i = ; i < columnInfos . length ; i ++ ) { HSSFCell cell = row . createCell ( i ) ; cell . setCellValue ( columnInfos [ i ] . getColumnName ( ) ) ; cell . setCellStyle ( titleStyle ) ; } PreparedStatement ps = null ; ResultSet rs = null ; String sql = "" + databaseName + "" + tableName + "" + Constants . MAX_ROWS ; try { ps = conn . prepareStatement ( sql ) ; rs = ps . executeQuery ( ) ; while ( rs . next ( ) ) { row = sheet . createRow ( row . getRowNum ( ) + ) ; for ( int i = ; i < columnInfos . length ; i ++ ) { ColumnInfo info = columnInfos [ i ] ; HSSFCell cell = row . createCell ( i ) ; cell . setCellStyle ( commonStyle ) ; switch ( info . getDataType ( ) ) { case CHAR : case VARCHAR : String str = rs . getString ( info . getColumnName ( ) ) ; if ( ! rs . wasNull ( ) ) { cell . setCellValue ( str ) ; } break ; case DATE : Date date = rs . getDate ( info . getColumnName ( ) ) ; if ( ! rs . wasNull ( ) ) { cell . setCellValue ( new java . util . Date ( date . getTime ( ) ) ) ; cell . setCellStyle ( dateStyle ) ; } break ; case DATETIME : case TIMESTAMP : Timestamp ts = rs . getTimestamp ( info . getColumnName ( ) ) ; if ( ! rs . wasNull ( ) ) { cell . setCellValue ( new java . util . Date ( ts . getTime ( ) ) ) ; cell . setCellStyle ( dateTimeStyle ) ; } break ; case DECIMAL : BigDecimal decimal = rs . getBigDecimal ( info . getColumnName ( ) ) ; if ( ! rs . wasNull ( ) ) { cell . setCellValue ( decimal . toPlainString ( ) ) ; } break ; case TINY_INT : case SMALL_INT : case INT : case LONG : long value = rs . getLong ( info . getColumnName ( ) ) ; if ( ! rs . wasNull ( ) ) { cell . setCellValue ( Long . toString ( value ) ) ; } break ; default : assert false ; break ; } } } } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( ps != null ) { try { ps . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } for ( int i = ; i < columnInfos . length ; i ++ ) { sheet . autoSizeColumn ( i ) ; } return sheet ; } } package com . asakusafw . compiler . legacy . workflow ; package com . asakusafw . compiler . legacy . workflow ; import java . io . Closeable ; import java . io . File ; import java . io . IOException ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . List ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . batch . AbstractWorkflowProcessor ; import com . asakusafw . compiler . batch . WorkDescriptionProcessor ; import com . asakusafw . compiler . batch . Workflow ; import com . asakusafw . compiler . batch . processor . JobFlowWorkDescriptionProcessor ; import com . asakusafw . compiler . batch . processor . ScriptWorkDescriptionProcessor ; import com . asakusafw . compiler . common . Naming ; import com . asakusafw . compiler . common . Precondition ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . Command ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . CommandContext ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . jobflow . JobflowModel ; import com . asakusafw . compiler . flow . jobflow . JobflowModel . Stage ; import com . asakusafw . runtime . stage . StageConstants ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . graph . Graph ; import com . asakusafw . utils . graph . Graphs ; import com . asakusafw . vocabulary . batch . JobFlowWorkDescription ; import com . asakusafw . vocabulary . batch . ScriptWorkDescription ; import com . asakusafw . vocabulary . batch . WorkDescription ; public class ExperimentalWorkflowProcessor extends AbstractWorkflowProcessor { public static final String VAR_BATCH_ARGS = "" ; static final Logger LOG = LoggerFactory . getLogger ( ExperimentalWorkflowProcessor . class ) ; static final Charset ENCODING = Charset . forName ( "" ) ; private static final Pattern SH_METACHARACTERS = Pattern . compile ( "" ) ; private static final String CMD_HADOOP_JOB = "" ; private static final String CMD_CLEANER = "" ; private static final String VAR_HOME = "" ; private static final String VAR_BATCH_ID = "" ; private static final String VAR_FLOW_ID = "" ; private static final String VAR_EXECUTION_ID = "" ; private static final String EXPR_EXECUTION_ID = "" + VAR_EXECUTION_ID ; private static final String EXPR_BATCH_ARGS = "" + VAR_BATCH_ARGS ; private static final String PREFIX_APP_HOME = MessageFormat . format ( "" , VAR_HOME ) ; private static final String JOBFLOW_LIB_SOURCE = JobFlowWorkDescriptionProcessor . JOBFLOW_PACKAGE ; private static final String JOBFLOW_LIB_DEST = MessageFormat . format ( "" , VAR_HOME , VAR_BATCH_ID ) ; public static final String PATH = "" ; public static final String K_OPTS = "" ; public static File getScriptOutput ( File outputDir ) { Precondition . checkMustNotBeNull ( outputDir , "" ) ; return new File ( outputDir , PATH ) ; } @ Override public Collection < Class < ? extends WorkDescriptionProcessor < ? > > > getDescriptionProcessors ( ) { List < Class < ? extends WorkDescriptionProcessor < ? > > > results = Lists . create ( ) ; results . add ( JobFlowWorkDescriptionProcessor . class ) ; results . add ( ScriptWorkDescriptionProcessor . class ) ; return results ; } @ Override public void process ( Workflow workflow ) throws IOException { OutputStream output = getEnvironment ( ) . openResource ( PATH ) ; try { Context context = new Context ( output ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; String batchId = getEnvironment ( ) . getConfiguration ( ) . getBatchId ( ) ; context . put ( "" , batchId ) ; context . put ( "" , toLiteral ( batchId ) ) ; context . put ( "" ) ; dump ( context , workflow . getGraph ( ) ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . close ( ) ; } finally { output . close ( ) ; } } private void dump ( Context context , Graph < Workflow . Unit > graph ) { assert context != null ; assert graph != null ; for ( Workflow . Unit unit : Graphs . sortPostOrder ( graph ) ) { dumpUnit ( context , unit ) ; } } private void dumpUnit ( Context context , Workflow . Unit unit ) { assert context != null ; assert unit != null ; WorkDescription desc = unit . getDescription ( ) ; if ( desc instanceof ScriptWorkDescription ) { dumpDescription ( context , ( ScriptWorkDescription ) desc ) ; } else if ( desc instanceof JobFlowWorkDescription ) { dumpDescription ( context , ( JobFlowWorkDescription ) desc , ( JobflowModel ) unit . getProcessed ( ) ) ; } else { throw new AssertionError ( desc ) ; } } private void dumpDescription ( Context context , ScriptWorkDescription desc ) { assert context != null ; assert desc != null ; context . put ( "" , desc . getCommand ( ) ) ; context . put ( "" , desc . getCommand ( ) ) ; dumpRun ( context , null , desc . getCommand ( ) ) ; context . put ( "" ) ; } private void dumpDescription ( Context context , JobFlowWorkDescription desc , JobflowModel model ) { assert context != null ; assert desc != null ; assert model != null ; context . put ( "" , model . getFlowId ( ) ) ; context . put ( "" , model . getFlowId ( ) ) ; context . put ( "" ) ; context . put ( "" , VAR_EXECUTION_ID ) ; context . put ( "" , VAR_BATCH_ID , toLiteral ( model . getBatchId ( ) ) ) ; context . put ( "" , VAR_FLOW_ID , toLiteral ( model . getFlowId ( ) ) ) ; context . put ( "" , VAR_EXECUTION_ID ) ; context . put ( "" , VAR_BATCH_ID ) ; context . put ( "" , VAR_FLOW_ID ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" , JOBFLOW_LIB_SOURCE , Naming . getJobflowClassPackageName ( model . getFlowId ( ) ) , JOBFLOW_LIB_DEST ) ; context . put ( "" , quote ( JOBFLOW_LIB_DEST ) ) ; context . put ( "" , quote ( JOBFLOW_LIB_SOURCE ) , toLiteral ( Naming . getJobflowClassPackageName ( model . getFlowId ( ) ) ) , quote ( JOBFLOW_LIB_DEST ) ) ; context . put ( "" ) ; dumpInitializer ( context , model ) ; dumpImporter ( context , model ) ; Graph < Stage > graph = model . getDependencyGraph ( ) ; for ( CompiledStage stage : model . getCompiled ( ) . getPrologueStages ( ) ) { dumpStage ( context , model , stage ) ; } for ( Stage stage : Graphs . sortPostOrder ( graph ) ) { dumpStage ( context , model , stage . getCompiled ( ) ) ; } for ( CompiledStage stage : model . getCompiled ( ) . getEpilogueStages ( ) ) { dumpStage ( context , model , stage ) ; } dumpExporter ( context , model ) ; dumpCleaner ( context , model ) ; dumpFinalizer ( context , model , "" ) ; context . put ( "" ) ; } private void dumpImporter ( Context context , JobflowModel model ) { assert context != null ; assert model != null ; List < ExternalIoCommandProvider > providers = model . getCompiled ( ) . getCommandProviders ( ) ; CommandContext cmdContext = createContext ( model ) ; for ( ExternalIoCommandProvider provider : providers ) { List < Command > commands = provider . getImportCommand ( cmdContext ) ; for ( Command cmd : commands ) { context . put ( "" , provider . getName ( ) ) ; context . put ( "" , provider . getName ( ) ) ; dumpRun ( context , model , cmd . getCommandLineString ( ) ) ; } } } private CommandContext createContext ( JobflowModel model ) { assert model != null ; return new CommandContext ( quote ( PREFIX_APP_HOME ) , quote ( EXPR_EXECUTION_ID ) , quote ( EXPR_BATCH_ARGS ) ) ; } private void dumpExporter ( Context context , JobflowModel model ) { assert context != null ; assert model != null ; List < ExternalIoCommandProvider > providers = model . getCompiled ( ) . getCommandProviders ( ) ; CommandContext cmdContext = createContext ( model ) ; for ( ExternalIoCommandProvider provider : providers ) { List < Command > commands = provider . getExportCommand ( cmdContext ) ; for ( Command cmd : commands ) { context . put ( "" , provider . getName ( ) ) ; context . put ( "" , provider . getName ( ) ) ; dumpRun ( context , model , cmd . getCommandLineString ( ) ) ; } } } private void dumpStage ( Context context , JobflowModel model , CompiledStage stage ) { assert context != null ; assert model != null ; if ( stage . getQualifiedName ( ) == null ) { return ; } String batchId = model . getBatchId ( ) ; String flowId = model . getFlowId ( ) ; String stageId = stage . getStageId ( ) ; context . put ( "" , stage . getQualifiedName ( ) . toNameString ( ) ) ; context . put ( "" , StageConstants . getDefinitionId ( batchId , flowId , stageId ) ) ; dumpRun ( context , model , toHadoopJob ( model , stage ) ) ; } private void dumpRun ( Context context , JobflowModel modelOrNull , String pattern , Object ... arguments ) { assert context != null ; assert pattern != null ; assert arguments != null ; String command ; if ( arguments . length == ) { command = pattern ; } else { command = MessageFormat . format ( pattern , arguments ) ; } context . put ( "" , VAR_HOME ) ; context . put ( "" , command ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" , command ) ; if ( modelOrNull != null ) { dumpFinalizer ( context , modelOrNull , "" ) ; } context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" ) ; } private void dumpInitializer ( Context context , JobflowModel model ) { assert context != null ; assert model != null ; List < ExternalIoCommandProvider > providers = model . getCompiled ( ) . getCommandProviders ( ) ; CommandContext cmdContext = createContext ( model ) ; for ( ExternalIoCommandProvider provider : providers ) { List < Command > commands = provider . getInitializeCommand ( cmdContext ) ; for ( Command cmd : commands ) { context . put ( "" , provider . getName ( ) ) ; context . put ( "" , provider . getName ( ) , model . getFlowId ( ) ) ; dumpRun ( context , model , cmd . getCommandLineString ( ) ) ; } } } private void dumpCleaner ( Context context , JobflowModel model ) { assert context != null ; assert model != null ; VariableTable variables = new VariableTable ( ) ; variables . defineVariable ( StageConstants . VAR_USER , "" ) ; variables . defineVariable ( StageConstants . VAR_BATCH_ID , "" + VAR_BATCH_ID ) ; variables . defineVariable ( StageConstants . VAR_FLOW_ID , "" + VAR_FLOW_ID ) ; variables . defineVariable ( StageConstants . VAR_EXECUTION_ID , EXPR_EXECUTION_ID ) ; String path = getEnvironment ( ) . getConfiguration ( ) . getRootLocation ( ) . toPath ( '' ) ; try { String parsed = variables . parse ( path , true ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" , quote ( PREFIX_APP_HOME + CMD_CLEANER ) , quote ( parsed ) , quote ( model . getBatchId ( ) ) , quote ( model . getFlowId ( ) ) , quote ( EXPR_EXECUTION_ID ) , quote ( EXPR_BATCH_ARGS ) ) ; context . put ( "" ) ; context . put ( "" ) ; context . put ( "" , parsed ) ; context . put ( "" ) ; } catch ( IllegalArgumentException e ) { LOG . warn ( MessageFormat . format ( "" , path ) , e ) ; } } private void dumpFinalizer ( Context context , JobflowModel model , String indent ) { assert context != null ; assert model != null ; List < ExternalIoCommandProvider > providers = model . getCompiled ( ) . getCommandProviders ( ) ; CommandContext cmdContext = createContext ( model ) ; for ( ExternalIoCommandProvider provider : providers ) { List < Command > commands = provider . getFinalizeCommand ( cmdContext ) ; for ( Command cmd : commands ) { context . put ( "" , indent , provider . getName ( ) ) ; context . put ( "" , indent , provider . getName ( ) , model . getFlowId ( ) ) ; context . put ( "" , indent , VAR_HOME ) ; context . put ( "" , indent , cmd . getCommandLineString ( ) ) ; context . put ( "" , indent ) ; } } } private String toHadoopJob ( JobflowModel model , CompiledStage stage ) { assert model != null ; assert stage != null ; return MessageFormat . format ( "" , CMD_HADOOP_JOB , toLiteral ( stage . getQualifiedName ( ) . toNameString ( ) ) , quote ( JOBFLOW_LIB_DEST ) , toLiteral ( Naming . getJobflowClassPackageName ( model . getFlowId ( ) ) ) , toLiteral ( StageConstants . PROP_EXECUTION_ID ) , VAR_EXECUTION_ID , toLiteral ( StageConstants . PROP_USER ) , getPluginProperties ( ) , K_OPTS ) ; } private String getPluginProperties ( ) { return join ( "" , new String [ ] { "" , MessageFormat . format ( "" , toLiteral ( StageConstants . PROP_ASAKUSA_BATCH_ARGS ) , quote ( EXPR_BATCH_ARGS ) ) } ) ; } private String quote ( String string ) { assert string != null ; return '' + string + '' ; } private String toLiteral ( String string ) { assert string != null ; return quote ( escape ( string ) ) ; } private String escape ( String string ) { assert string != null ; String replaced = SH_METACHARACTERS . matcher ( string ) . replaceAll ( "" ) ; return replaced ; } private String join ( String delim , String [ ] values ) { if ( values . length == ) { return "" ; } else if ( values . length == ) { return values [ ] ; } StringBuilder buf = new StringBuilder ( ) ; buf . append ( values [ ] ) ; for ( int i = ; i < values . length ; i ++ ) { buf . append ( delim ) ; buf . append ( values [ i ] ) ; } return buf . toString ( ) ; } private static class Context implements Closeable { private final PrintWriter writer ; public Context ( OutputStream output ) { assert output != null ; writer = new PrintWriter ( new OutputStreamWriter ( output , ENCODING ) ) ; } public void put ( String pattern , Object ... arguments ) { assert pattern != null ; assert arguments != null ; String text ; if ( arguments . length == ) { text = pattern ; } else { text = MessageFormat . format ( pattern , arguments ) ; } writer . println ( text ) ; LOG . debug ( text ) ; } @ Override public void close ( ) throws IOException { writer . close ( ) ; } } } package com . asakusafw . operation . tools . hadoop . fs ; import java . io . File ; import java . io . IOException ; import java . lang . reflect . Method ; import java . net . URI ; import java . sql . Date ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import java . util . concurrent . TimeUnit ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . apache . commons . cli . ParseException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . util . Tool ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class Clean extends Configured implements Tool { static final Logger LOG = LoggerFactory . getLogger ( Clean . class ) ; static final Option OPT_RECURSIVE ; static final Option OPT_DRY_RUN ; static final Option OPT_KEEP_DAYS ; private static final Options OPTIONS ; static { OPT_RECURSIVE = new Option ( "" , "" , false , "" ) ; OPT_DRY_RUN = new Option ( "" , "" , false , "" ) ; OPT_KEEP_DAYS = new Option ( "" , "" , true , "" ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_RECURSIVE ) ; OPTIONS . addOption ( OPT_DRY_RUN ) ; OPTIONS . addOption ( OPT_KEEP_DAYS ) ; } private final long currentTime ; public Clean ( ) { this ( System . currentTimeMillis ( ) ) ; } Clean ( long currentTime ) { this . currentTime = currentTime ; } public static void main ( String ... args ) throws Exception { LOG . info ( "" ) ; long start = System . currentTimeMillis ( ) ; Tool tool = new Clean ( ) ; tool . setConf ( new Configuration ( ) ) ; int exit = tool . run ( args ) ; long end = System . currentTimeMillis ( ) ; LOG . info ( MessageFormat . format ( "" , exit , end - start ) ) ; if ( exit != ) { System . exit ( exit ) ; } } @ Override public int run ( String [ ] args ) { if ( args == null ) { throw new IllegalArgumentException ( "" ) ; } Opts opts ; try { opts = parseOptions ( args ) ; if ( opts == null ) { return ; } } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , Arrays . toString ( args ) ) , e ) ; return ; } long period = currentTime - ( long ) ( opts . keepDays * TimeUnit . DAYS . toMillis ( ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , new Date ( period ) ) ; } Context context = new Context ( opts . recursive , period , opts . dryRun ) ; for ( Path path : opts . paths ) { remove ( path , context ) ; } if ( context . hasError ( ) ) { return ; } return ; } private Opts parseOptions ( String [ ] args ) throws ParseException { assert args != null ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , Arrays . toString ( args ) ) ; } CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; boolean recursive = cmd . hasOption ( OPT_RECURSIVE . getOpt ( ) ) ; String keepString = cmd . getOptionValue ( OPT_KEEP_DAYS . getOpt ( ) ) ; boolean dryRun = cmd . hasOption ( OPT_DRY_RUN . getOpt ( ) ) ; String [ ] rest = cmd . getArgs ( ) ; if ( keepString == null ) { LOG . error ( MessageFormat . format ( "" , OPT_KEEP_DAYS . getLongOpt ( ) ) ) ; return null ; } if ( rest == null ) { rest = new String [ ] ; } LOG . debug ( "" , OPT_RECURSIVE . getLongOpt ( ) , recursive ) ; double keepDays ; try { keepDays = Double . parseDouble ( keepString ) ; } catch ( NumberFormatException e ) { LOG . error ( MessageFormat . format ( "" , OPT_KEEP_DAYS . getLongOpt ( ) , keepString ) ) ; return null ; } LOG . debug ( "" , OPT_KEEP_DAYS . getLongOpt ( ) , keepDays ) ; LOG . debug ( "" , OPT_DRY_RUN . getLongOpt ( ) , dryRun ) ; List < Path > paths = new ArrayList < Path > ( ) ; for ( String pathString : rest ) { if ( pathString . trim ( ) . isEmpty ( ) ) { continue ; } try { Path path = new Path ( pathString ) ; paths . add ( path ) ; LOG . debug ( "" , path ) ; } catch ( RuntimeException e ) { LOG . error ( MessageFormat . format ( "" , pathString ) , e ) ; return null ; } } if ( paths . isEmpty ( ) ) { LOG . error ( MessageFormat . format ( "" , new Object [ ] ) ) ; return null ; } return new Opts ( recursive , keepDays , dryRun , paths ) ; } boolean remove ( Path path , Context context ) { LOG . info ( MessageFormat . format ( "" , path ) ) ; FileSystem fs ; try { fs = FileSystem . get ( path . toUri ( ) , getConf ( ) ) ; } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , path ) , e ) ; context . setError ( ) ; return false ; } List < FileStatus > files ; try { files = asList ( fs . globStatus ( path ) ) ; } catch ( Exception e ) { LOG . error ( MessageFormat . format ( "" , path ) , e ) ; context . setError ( ) ; return false ; } if ( files . isEmpty ( ) ) { LOG . warn ( MessageFormat . format ( "" , path ) ) ; context . setError ( ) ; return false ; } boolean removed = true ; long start = System . currentTimeMillis ( ) ; for ( FileStatus file : files ) { removed &= remove ( fs , file , context ) ; } long end = System . currentTimeMillis ( ) ; LOG . info ( MessageFormat . format ( "" , path , removed , end - start ) ) ; return removed ; } private boolean remove ( FileSystem fs , FileStatus file , Context context ) { LOG . debug ( "" , file . getPath ( ) ) ; boolean isSymlink = context . isSymlink ( fs , file ) ; if ( isSymlink ) { LOG . error ( MessageFormat . format ( "" , file . getPath ( ) ) ) ; context . setError ( ) ; return false ; } if ( file . isDir ( ) ) { if ( context . isRecursive ( ) ) { List < FileStatus > children ; try { children = asList ( fs . listStatus ( file . getPath ( ) ) ) ; } catch ( IOException e ) { LOG . error ( MessageFormat . format ( "" , file . getPath ( ) ) , e ) ; context . setError ( ) ; return false ; } boolean deleteChildren = true ; for ( FileStatus child : children ) { deleteChildren &= remove ( fs , child , context ) ; } if ( deleteChildren == false ) { LOG . info ( MessageFormat . format ( "" , file . getPath ( ) , new Date ( file . getModificationTime ( ) ) ) ) ; return false ; } } else { LOG . info ( MessageFormat . format ( "" , file . getPath ( ) , new Date ( file . getModificationTime ( ) ) ) ) ; return false ; } } if ( context . canDelete ( file ) ) { LOG . debug ( "" , file . getPath ( ) ) ; if ( context . isDryRun ( ) == false ) { try { boolean removed = fs . delete ( file . getPath ( ) , false ) ; if ( removed == false ) { LOG . error ( MessageFormat . format ( "" , file . getPath ( ) ) ) ; context . setError ( ) ; return false ; } } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , file . getPath ( ) ) , e ) ; context . setError ( ) ; return false ; } } LOG . info ( MessageFormat . format ( "" , file . getPath ( ) , new Date ( file . getModificationTime ( ) ) ) ) ; } else { LOG . info ( MessageFormat . format ( "" , file . getPath ( ) , new Date ( file . getModificationTime ( ) ) ) ) ; return false ; } return true ; } private List < FileStatus > asList ( FileStatus [ ] files ) { if ( files == null ) { return Collections . emptyList ( ) ; } else { return Arrays . asList ( files ) ; } } private static final class Opts { final boolean recursive ; final double keepDays ; final boolean dryRun ; final List < Path > paths ; public Opts ( boolean recursive , double keepDays , boolean dryRun , List < Path > paths ) { this . recursive = recursive ; this . keepDays = keepDays ; this . dryRun = dryRun ; this . paths = paths ; } } private static final class Context { private final boolean recursive ; private final long keepPeriod ; private final boolean dryRun ; private boolean sawError ; private static final Method FILE_STATUS_IS_SYMLINK ; static { Method m ; try { m = FileStatus . class . getMethod ( "" ) ; } catch ( Exception e ) { m = null ; LOG . debug ( "" ) ; } FILE_STATUS_IS_SYMLINK = m ; } public Context ( boolean recursive , long keepPeriod , boolean dryRun ) { this . recursive = recursive ; this . keepPeriod = keepPeriod ; this . dryRun = dryRun ; this . sawError = false ; } public boolean isSymlink ( FileSystem fs , FileStatus file ) { try { return isSymlink0 ( fs , file ) ; } catch ( Exception e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , file . getPath ( ) ) , e ) ; } return false ; } } private boolean isSymlink0 ( FileSystem fs , FileStatus file ) throws IOException { assert fs != null ; assert file != null ; if ( FILE_STATUS_IS_SYMLINK != null ) { try { return Boolean . TRUE . equals ( FILE_STATUS_IS_SYMLINK . invoke ( file ) ) ; } catch ( Exception e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( MessageFormat . format ( "" , FILE_STATUS_IS_SYMLINK . getName ( ) , file . getPath ( ) ) , e ) ; } return false ; } } URI uri = file . getPath ( ) . toUri ( ) ; if ( uri . getScheme ( ) == null ) { uri = fs . makeQualified ( file . getPath ( ) ) . toUri ( ) ; if ( uri == null ) { return false ; } } if ( uri . getScheme ( ) . equals ( "" ) ) { File f = new File ( uri ) ; File c = f . getCanonicalFile ( ) ; if ( f . equals ( c ) ) { return false ; } if ( f . getName ( ) . equals ( c . getName ( ) ) == false ) { return true ; } File p = f . getParentFile ( ) . getCanonicalFile ( ) ; if ( p . equals ( c . getParentFile ( ) ) == false ) { return true ; } } return false ; } public boolean isRecursive ( ) { return recursive ; } public boolean isDryRun ( ) { return dryRun ; } public boolean canDelete ( FileStatus file ) { long lastModified = file . getModificationTime ( ) ; return lastModified < keepPeriod ; } public void setError ( ) { this . sawError = true ; } public boolean hasError ( ) { return this . sawError ; } } } package com . asakusafw . operation . tools . hadoop . fs ; package com . asakusafw . operation . tools . hadoop . fs ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . concurrent . TimeUnit ; import org . apache . hadoop . conf . Configuration ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class CleanTest { private static final String OPT_KEEP = "" ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { File file = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( file . toString ( ) , file . exists ( ) , is ( false ) ) ; } @ Test public void keep ( ) throws Exception { File file = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( file . toString ( ) , file . exists ( ) , is ( true ) ) ; } @ Test public void folder ( ) throws Exception { File file = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( file . toString ( ) , file . exists ( ) , is ( true ) ) ; } @ Test public void recursive ( ) throws Exception { File file = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( file . toString ( ) , file . exists ( ) , is ( false ) ) ; } @ Test public void dry_run ( ) throws Exception { File file = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( file . toString ( ) , file . exists ( ) , is ( true ) ) ; } @ Test public void wildcard ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = touch ( "" , ) ; File f4 = touch ( "" , ) ; File f5 = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( true ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( false ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( true ) ) ; assertThat ( f4 . toString ( ) , f4 . exists ( ) , is ( false ) ) ; assertThat ( f5 . toString ( ) , f5 . exists ( ) , is ( true ) ) ; } @ Test public void multiple ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , path ( "" ) , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( false ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( true ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( false ) ) ; } @ Test public void deep_wildcard ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = touch ( "" , ) ; File f4 = touch ( "" , ) ; File f5 = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( true ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( false ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( true ) ) ; assertThat ( f4 . toString ( ) , f4 . exists ( ) , is ( false ) ) ; assertThat ( f5 . toString ( ) , f5 . exists ( ) , is ( true ) ) ; } @ Test public void skip_folder ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = touch ( "" , ) ; File f4 = touch ( "" , ) ; File f5 = touch ( "" , ) ; touch ( "" , ) ; touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( false ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( true ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( false ) ) ; assertThat ( f4 . toString ( ) , f4 . exists ( ) , is ( false ) ) ; assertThat ( f5 . toString ( ) , f5 . exists ( ) , is ( false ) ) ; assertThat ( "" , file ( "" ) . exists ( ) , is ( true ) ) ; assertThat ( "" , file ( "" ) . exists ( ) , is ( false ) ) ; } @ Test public void keep_folder ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = touch ( "" , ) ; File f4 = touch ( "" , ) ; File f5 = touch ( "" , ) ; touch ( "" , ) ; touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( false ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( false ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( false ) ) ; assertThat ( f4 . toString ( ) , f4 . exists ( ) , is ( false ) ) ; assertThat ( f5 . toString ( ) , f5 . exists ( ) , is ( false ) ) ; assertThat ( "" , file ( "" ) . exists ( ) , is ( true ) ) ; assertThat ( "" , file ( "" ) . exists ( ) , is ( false ) ) ; } @ Test public void minus_file ( ) throws Exception { File file = touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( ) ) ; assertThat ( file . toString ( ) , file . exists ( ) , is ( false ) ) ; } @ Test public void missing_path ( ) throws Exception { Clean c = createService ( ) ; int exit = c . run ( args ( , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void missing_wildcard ( ) throws Exception { Clean c = createService ( ) ; int exit = c . run ( args ( , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void missing_keep ( ) throws Exception { touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( new String [ ] { path ( "" ) } ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void invalid_keep ( ) throws Exception { touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( new String [ ] { OPT_KEEP , "" , path ( "" ) } ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void unknown_opts ( ) throws Exception { touch ( "" , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , "" , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void empty_path ( ) throws Exception { Clean c = createService ( ) ; int exit = c . run ( args ( ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void malformed_path ( ) throws Exception { Clean c = createService ( ) ; int exit = c . run ( args ( , "" ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void invalid_filesystem ( ) throws Exception { Clean c = createService ( ) ; int exit = c . run ( args ( , "" ) ) ; assertThat ( exit , is ( not ( ) ) ) ; } @ Test public void inaccessible_folder ( ) throws Exception { assumeAccessRestrictionAvailable ( ) ; File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = touch ( "" , ) ; file ( "" ) . setExecutable ( false , false ) ; int exit ; try { Clean c = createService ( ) ; exit = c . run ( args ( , "" , path ( "" ) ) ) ; } finally { file ( "" ) . setExecutable ( true , false ) ; } assertThat ( exit , is ( not ( ) ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( false ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( true ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( false ) ) ; assertThat ( "" , file ( "" ) . exists ( ) , is ( true ) ) ; } @ Test public void readonly_folder ( ) throws Exception { assumeAccessRestrictionAvailable ( ) ; File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = touch ( "" , ) ; file ( "" ) . setWritable ( false , false ) ; int exit ; try { Clean c = createService ( ) ; exit = c . run ( args ( , "" , path ( "" ) ) ) ; } finally { file ( "" ) . setWritable ( true , false ) ; } assertThat ( exit , is ( not ( ) ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( false ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( true ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( false ) ) ; assertThat ( "" , file ( "" ) . exists ( ) , is ( true ) ) ; } @ Test public void symlink_file ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = link ( "" , f1 , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( true ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( false ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( true ) ) ; } @ Test public void symlink_dir ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = link ( "" , file ( "" ) , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( true ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( false ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( true ) ) ; } @ Test public void symlink_on_same_name ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = link ( "" , f1 , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( true ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( false ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( true ) ) ; } @ Test public void symlink_on_same_dir ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = link ( "" , f2 , ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; assertThat ( f1 . toString ( ) , f1 . exists ( ) , is ( true ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( true ) ) ; assertThat ( f3 . toString ( ) , f3 . exists ( ) , is ( true ) ) ; } @ Test public void symlink_lost ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; link ( "" , f1 , ) ; Assume . assumeThat ( f1 . delete ( ) , is ( true ) ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( false ) ) ; } @ Test public void symlink_self ( ) throws Exception { File f1 = touch ( "" , ) ; File f2 = touch ( "" , ) ; File f3 = link ( "" , f1 , ) ; Assume . assumeThat ( f1 . delete ( ) , is ( true ) ) ; f3 . renameTo ( f1 ) ; Clean c = createService ( ) ; int exit = c . run ( args ( , "" , path ( "" ) ) ) ; assertThat ( exit , is ( not ( ) ) ) ; assertThat ( f2 . toString ( ) , f2 . exists ( ) , is ( false ) ) ; } private Clean createService ( long days ) { Clean service = new Clean ( TimeUnit . DAYS . toMillis ( days ) ) ; service . setConf ( new Configuration ( ) ) ; return service ; } private String [ ] args ( int keep , String ... args ) { List < String > list = new ArrayList < String > ( ) ; Collections . addAll ( list , OPT_KEEP , String . valueOf ( keep ) ) ; Collections . addAll ( list , args ) ; return list . toArray ( new String [ list . size ( ) ] ) ; } private String path ( String path ) { String uri = folder . getRoot ( ) . toURI ( ) . toString ( ) ; return uri + "" + path ; } private File link ( String path , File target , int day ) throws IOException { File link = file ( path ) ; link . getParentFile ( ) . mkdirs ( ) ; try { Process process = new ProcessBuilder ( ) . command ( "" , "" , target . getCanonicalPath ( ) , link . getAbsolutePath ( ) ) . redirectErrorStream ( true ) . start ( ) ; try { int exit = process . waitFor ( ) ; Assume . assumeThat ( exit , is ( ) ) ; } finally { process . destroy ( ) ; } } catch ( Exception e ) { Assume . assumeNoException ( e ) ; } touch ( path , day ) ; return link ; } private File touch ( String path , double day ) throws IOException { File file = file ( path ) ; if ( file . exists ( ) == false ) { file . getParentFile ( ) . mkdirs ( ) ; try { file . createNewFile ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } File root = folder . getRoot ( ) . getCanonicalFile ( ) ; File current = file ; while ( true ) { current = current . getCanonicalFile ( ) ; if ( root . equals ( current ) ) { break ; } boolean succeed = current . setLastModified ( ( long ) ( day * TimeUnit . DAYS . toMillis ( ) ) ) ; if ( succeed == false ) { break ; } current = current . getParentFile ( ) ; if ( current == null ) { break ; } } return file ; } private File file ( String path ) { File file = new File ( folder . getRoot ( ) , path ) ; return file ; } private void assumeAccessRestrictionAvailable ( ) throws IOException { File f = File . createTempFile ( "" , "" ) ; f . setReadable ( false , false ) ; try { if ( f . canRead ( ) ) { System . err . println ( "" ) ; Assume . assumeTrue ( false ) ; } } finally { f . setReadable ( true , true ) ; if ( f . delete ( ) == false ) { System . err . printf ( "" , f ) ; } } } } package com . asakusafw . compiler . windgate ; package com . asakusafw . compiler . windgate ; import java . io . IOException ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . SortedSet ; import java . util . TreeMap ; import java . util . TreeSet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . compiler . common . JavaName ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoDescriptionProcessor ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . flow . jobflow . CompiledStage ; import com . asakusafw . compiler . flow . mapreduce . parallel . ParallelSortClientEmitter ; import com . asakusafw . compiler . flow . mapreduce . parallel . ResolvedSlot ; import com . asakusafw . compiler . flow . mapreduce . parallel . Slot ; import com . asakusafw . compiler . flow . mapreduce . parallel . SlotResolver ; import com . asakusafw . runtime . stage . input . TemporaryInputFormat ; import com . asakusafw . runtime . stage . output . TemporaryOutputFormat ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . collections . Sets ; import com . asakusafw . vocabulary . external . ExporterDescription ; import com . asakusafw . vocabulary . external . ImporterDescription ; import com . asakusafw . vocabulary . flow . graph . InputDescription ; import com . asakusafw . vocabulary . flow . graph . OutputDescription ; import com . asakusafw . vocabulary . windgate . Constants ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; public class WindGateIoProcessor extends ExternalIoDescriptionProcessor { static final Logger LOG = LoggerFactory . getLogger ( WindGateIoProcessor . class ) ; public static final String MODULE_NAME = "" ; private static final String CMD_PROCESS = "" ; private static final String CMD_FINALIZE = "" ; private static final String OPT_IMPORT = "" ; private static final String OPT_EXPORT = "" ; private static final String PATTERN_SCRIPT_LOCATION = "" ; static final String OPT_BEGIN = "" ; static final String OPT_END = "" ; static final String OPT_ONESHOT = "" ; @ Override public Class < ? extends ImporterDescription > getImporterDescriptionType ( ) { return WindGateImporterDescription . class ; } @ Override public Class < ? extends ExporterDescription > getExporterDescriptionType ( ) { return WindGateExporterDescription . class ; } @ Override public boolean validate ( List < InputDescription > inputs , List < OutputDescription > outputs ) { LOG . debug ( "" , getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) ) ; boolean valid = true ; for ( InputDescription input : inputs ) { WindGateImporterDescription desc = extract ( input ) ; try { if ( desc . getDriverScript ( ) == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , desc . getClass ( ) . getName ( ) ) ) ; } } catch ( IllegalStateException e ) { getEnvironment ( ) . error ( "" , input . getName ( ) , getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) , e . getMessage ( ) ) ; valid = false ; } } for ( OutputDescription output : outputs ) { WindGateExporterDescription desc = extract ( output ) ; try { if ( desc . getDriverScript ( ) == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , desc . getClass ( ) . getName ( ) ) ) ; } } catch ( IllegalStateException e ) { getEnvironment ( ) . error ( "" , output . getName ( ) , getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) , e . getMessage ( ) ) ; valid = false ; } } return valid ; } @ Override public SourceInfo getInputInfo ( InputDescription description ) { Set < Location > locations = Collections . singleton ( getInputLocation ( description ) ) ; return new SourceInfo ( locations , TemporaryInputFormat . class ) ; } @ Override public List < CompiledStage > emitEpilogue ( IoContext context ) throws IOException { if ( context . getOutputs ( ) . isEmpty ( ) ) { return Collections . emptyList ( ) ; } LOG . debug ( "" , getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) ) ; List < Slot > slots = Lists . create ( ) ; for ( Output output : context . getOutputs ( ) ) { Slot slot = toSlot ( output ) ; slots . add ( slot ) ; } List < ResolvedSlot > resolved = new SlotResolver ( getEnvironment ( ) ) . resolve ( slots ) ; if ( getEnvironment ( ) . hasError ( ) ) { return Collections . emptyList ( ) ; } ParallelSortClientEmitter emitter = new ParallelSortClientEmitter ( getEnvironment ( ) ) ; CompiledStage stage = emitter . emit ( MODULE_NAME , resolved , getEnvironment ( ) . getEpilogueLocation ( MODULE_NAME ) ) ; return Collections . singletonList ( stage ) ; } private Slot toSlot ( Output output ) { assert output != null ; String name = normalize ( output . getDescription ( ) . getName ( ) ) ; return new Slot ( name , output . getDescription ( ) . getDataType ( ) , Collections . < String > emptyList ( ) , output . getSources ( ) , TemporaryOutputFormat . class ) ; } private Location getInputLocation ( InputDescription description ) { assert description != null ; String name = normalize ( description . getName ( ) ) ; return getEnvironment ( ) . getPrologueLocation ( MODULE_NAME ) . append ( name ) ; } private Location getOutputLocation ( OutputDescription description ) { assert description != null ; String name = normalize ( description . getName ( ) ) ; return getEnvironment ( ) . getEpilogueLocation ( MODULE_NAME ) . append ( name ) . asPrefix ( ) ; } private String normalize ( String name ) { assert name != null ; assert name . trim ( ) . isEmpty ( ) == false ; String memberName = JavaName . of ( name ) . toMemberName ( ) ; StringBuilder buf = new StringBuilder ( ) ; for ( char c : memberName . toCharArray ( ) ) { if ( ( '' <= c && c <= '' ) || ( '' <= c && c <= '' ) || ( '' <= c && c <= '' ) ) { buf . append ( c ) ; } } if ( buf . length ( ) == ) { buf . append ( "" ) ; } return buf . toString ( ) ; } @ Override public void emitPackage ( IoContext context ) throws IOException { LOG . debug ( "" , getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) ) ; Map < String , GateScript > importers = toImporterScripts ( context . getInputs ( ) ) ; Map < String , GateScript > exporters = toExporterScripts ( context . getOutputs ( ) ) ; for ( Map . Entry < String , GateScript > entry : importers . entrySet ( ) ) { String script = getScriptLocation ( true , entry . getKey ( ) ) ; LOG . debug ( "" , new Object [ ] { script , getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) , } ) ; emitScript ( script , entry . getValue ( ) ) ; } for ( Map . Entry < String , GateScript > entry : exporters . entrySet ( ) ) { String script = getScriptLocation ( false , entry . getKey ( ) ) ; LOG . debug ( "" , new Object [ ] { script , getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) , } ) ; emitScript ( script , entry . getValue ( ) ) ; } } static String getScriptLocation ( boolean importer , String profileName ) { assert profileName != null ; return MessageFormat . format ( PATTERN_SCRIPT_LOCATION , importer ? OPT_IMPORT : OPT_EXPORT , profileName ) ; } private Map < String , GateScript > toImporterScripts ( Collection < Input > inputs ) { assert inputs != null ; Map < String , List < ProcessScript < ? > > > processes = Maps . create ( ) ; for ( Input input : inputs ) { String profileName = extract ( input . getDescription ( ) ) . getProfileName ( ) ; ProcessScript < ? > process = toProcessScript ( input ) ; Maps . addToList ( processes , profileName , process ) ; } return toGateScripts ( processes ) ; } private Map < String , GateScript > toExporterScripts ( Collection < Output > outputs ) { assert outputs != null ; Map < String , List < ProcessScript < ? > > > processes = Maps . create ( ) ; for ( Output output : outputs ) { String profileName = extract ( output . getDescription ( ) ) . getProfileName ( ) ; ProcessScript < ? > process = toProcessScript ( output ) ; Maps . addToList ( processes , profileName , process ) ; } return toGateScripts ( processes ) ; } private ProcessScript < ? > toProcessScript ( Input input ) { assert input != null ; WindGateImporterDescription desc = extract ( input . getDescription ( ) ) ; String location = getInputLocation ( input . getDescription ( ) ) . toPath ( '' ) ; DriverScript drain = new DriverScript ( Constants . HADOOP_FILE_RESOURCE_NAME , Collections . singletonMap ( FileProcess . FILE . key ( ) , location ) ) ; return createProcessScript ( input . getDescription ( ) . getName ( ) , desc . getModelType ( ) , desc . getDriverScript ( ) , drain ) ; } private ProcessScript < ? > toProcessScript ( Output output ) { assert output != null ; WindGateExporterDescription desc = extract ( output . getDescription ( ) ) ; String location = getOutputLocation ( output . getDescription ( ) ) . toPath ( '' ) ; DriverScript source = new DriverScript ( Constants . HADOOP_FILE_RESOURCE_NAME , Collections . singletonMap ( FileProcess . FILE . key ( ) , location ) ) ; return createProcessScript ( output . getDescription ( ) . getName ( ) , desc . getModelType ( ) , source , desc . getDriverScript ( ) ) ; } private < T > ProcessScript < T > createProcessScript ( String profileName , Class < T > modelType , DriverScript source , DriverScript drain ) { assert profileName != null ; assert modelType != null ; assert source != null ; assert drain != null ; return new ProcessScript < T > ( profileName , Constants . DEFAULT_PROCESS_NAME , modelType , source , drain ) ; } private Map < String , GateScript > toGateScripts ( Map < String , List < ProcessScript < ? > > > processes ) { assert processes != null ; Map < String , GateScript > results = new TreeMap < String , GateScript > ( ) ; for ( Map . Entry < String , List < ProcessScript < ? > > > entry : processes . entrySet ( ) ) { results . put ( entry . getKey ( ) , new GateScript ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } return results ; } private void emitScript ( String path , GateScript script ) throws IOException { assert path != null ; assert script != null ; Properties properties = new Properties ( ) ; script . storeTo ( properties ) ; OutputStream output = getEnvironment ( ) . openResource ( null , path ) ; try { properties . store ( output , getEnvironment ( ) . getTargetId ( ) ) ; } finally { output . close ( ) ; } } private WindGateImporterDescription extract ( InputDescription description ) { assert description != null ; ImporterDescription importer = description . getImporterDescription ( ) ; assert importer != null ; assert importer instanceof WindGateImporterDescription ; return ( WindGateImporterDescription ) importer ; } private WindGateExporterDescription extract ( OutputDescription description ) { assert description != null ; ExporterDescription exporter = description . getExporterDescription ( ) ; assert exporter != null ; assert exporter instanceof WindGateExporterDescription ; return ( WindGateExporterDescription ) exporter ; } @ Override public ExternalIoCommandProvider createCommandProvider ( IoContext context ) { Set < String > importers = Sets . create ( ) ; for ( Input input : context . getInputs ( ) ) { WindGateImporterDescription desc = extract ( input . getDescription ( ) ) ; importers . add ( desc . getProfileName ( ) ) ; } Set < String > exporters = Sets . create ( ) ; for ( Output output : context . getOutputs ( ) ) { WindGateExporterDescription desc = extract ( output . getDescription ( ) ) ; exporters . add ( desc . getProfileName ( ) ) ; } return new CommandProvider ( getEnvironment ( ) . getBatchId ( ) , getEnvironment ( ) . getFlowId ( ) , importers , exporters ) ; } static ExternalIoCommandProvider findRelated ( List < ExternalIoCommandProvider > commands ) { for ( ExternalIoCommandProvider provider : commands ) { if ( provider instanceof CommandProvider ) { return provider ; } } return null ; } static String resolveProfileName ( String profileName ) { assert profileName != null ; return profileName ; } static String resolveModuleName ( String profileName ) { assert profileName != null ; return MessageFormat . format ( "" , MODULE_NAME , profileName ) ; } public static class CommandProvider extends ExternalIoCommandProvider { private static final long serialVersionUID = - ; private final String batchId ; private final String flowId ; private final Set < String > importers ; private final Set < String > exporters ; CommandProvider ( String batchId , String flowId , Set < String > importers , Set < String > exporters ) { assert batchId != null ; assert flowId != null ; assert importers != null ; assert exporters != null ; this . batchId = batchId ; this . flowId = flowId ; this . importers = new TreeSet < String > ( importers ) ; this . exporters = new TreeSet < String > ( exporters ) ; } @ Override public String getName ( ) { return MODULE_NAME ; } @ Override public List < Command > getImportCommand ( CommandContext context ) { List < Command > results = Lists . create ( ) ; for ( String profile : importers ) { List < String > commands = Lists . create ( ) ; commands . add ( context . getHomePathPrefix ( ) + CMD_PROCESS ) ; commands . add ( profile ) ; if ( exporters . contains ( profile ) ) { commands . add ( OPT_BEGIN ) ; } else { commands . add ( OPT_ONESHOT ) ; } commands . add ( "" + getScriptLocation ( true , profile ) ) ; commands . add ( batchId ) ; commands . add ( flowId ) ; commands . add ( context . getExecutionId ( ) ) ; commands . add ( context . getVariableList ( ) ) ; results . add ( new Command ( commands , resolveModuleName ( profile ) , resolveProfileName ( profile ) , getEnvironment ( context ) ) ) ; } return results ; } @ Override public List < Command > getExportCommand ( CommandContext context ) { List < Command > results = Lists . create ( ) ; for ( String profile : exporters ) { List < String > commands = Lists . create ( ) ; commands . add ( context . getHomePathPrefix ( ) + CMD_PROCESS ) ; commands . add ( profile ) ; if ( importers . contains ( profile ) ) { commands . add ( OPT_END ) ; } else { commands . add ( OPT_ONESHOT ) ; } commands . add ( "" + getScriptLocation ( false , profile ) ) ; commands . add ( batchId ) ; commands . add ( flowId ) ; commands . add ( context . getExecutionId ( ) ) ; commands . add ( context . getVariableList ( ) ) ; results . add ( new Command ( commands , resolveModuleName ( profile ) , resolveProfileName ( profile ) , getEnvironment ( context ) ) ) ; } return results ; } @ Override public List < Command > getFinalizeCommand ( CommandContext context ) { SortedSet < String > union = new TreeSet < String > ( ) ; union . addAll ( importers ) ; union . addAll ( exporters ) ; List < Command > results = Lists . create ( ) ; for ( String profile : union ) { List < String > commands = Lists . create ( ) ; commands . add ( context . getHomePathPrefix ( ) + CMD_FINALIZE ) ; commands . add ( profile ) ; commands . add ( batchId ) ; commands . add ( flowId ) ; commands . add ( context . getExecutionId ( ) ) ; results . add ( new Command ( commands , resolveModuleName ( profile ) , resolveProfileName ( profile ) , getEnvironment ( context ) ) ) ; } return results ; } private Map < String , String > getEnvironment ( CommandContext context ) { return Collections . emptyMap ( ) ; } } } package com . asakusafw . compiler . windgate ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class DualIdentityFlow < T > extends FlowDescription { private In < T > in1 ; private In < T > in2 ; private Out < T > out1 ; private Out < T > out2 ; public DualIdentityFlow ( In < T > in1 , In < T > in2 , Out < T > out1 , Out < T > out2 ) { this . in1 = in1 ; this . in2 = in2 ; this . out1 = out1 ; this . out2 = out2 ; } @ Override protected void describe ( ) { out1 . add ( in1 ) ; out2 . add ( in2 ) ; } } package com . asakusafw . compiler . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . Collections ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . Command ; import com . asakusafw . compiler . flow . ExternalIoCommandProvider . CommandContext ; import com . asakusafw . compiler . flow . FlowCompilerOptions ; import com . asakusafw . compiler . flow . FlowDescriptionDriver ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . DirectFlowCompiler ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . windgate . testing . model . Simple ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . DriverScript ; public class WindGateIoProcessorTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Simple > in = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; FlowDescription desc = new IdentityFlow < Simple > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = WindGateIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; List < Command > importer = provider . getImportCommand ( context ) ; List < Command > exporter = provider . getExportCommand ( context ) ; List < Command > finalizer = provider . getFinalizeCommand ( context ) ; assertThat ( importer . size ( ) , is ( ) ) ; assertThat ( exporter . size ( ) , is ( ) ) ; assertThat ( finalizer . size ( ) , is ( ) ) ; assertThat ( mode ( importer , "" ) , is ( WindGateIoProcessor . OPT_BEGIN ) ) ; assertThat ( mode ( exporter , "" ) , is ( WindGateIoProcessor . OPT_END ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; } @ Test public void different_profile ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Simple > in = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; FlowDescription desc = new IdentityFlow < Simple > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = WindGateIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; List < Command > importer = provider . getImportCommand ( context ) ; List < Command > exporter = provider . getExportCommand ( context ) ; List < Command > finalizer = provider . getFinalizeCommand ( context ) ; assertThat ( importer . size ( ) , is ( ) ) ; assertThat ( exporter . size ( ) , is ( ) ) ; assertThat ( finalizer . size ( ) , is ( ) ) ; assertThat ( mode ( importer , "" ) , is ( WindGateIoProcessor . OPT_ONESHOT ) ) ; assertThat ( mode ( exporter , "" ) , is ( WindGateIoProcessor . OPT_ONESHOT ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; } @ Test public void same_profile ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Simple > in1 = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; In < Simple > in2 = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out1 = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out2 = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; FlowDescription desc = new DualIdentityFlow < Simple > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = WindGateIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; List < Command > importer = provider . getImportCommand ( context ) ; List < Command > exporter = provider . getExportCommand ( context ) ; List < Command > finalizer = provider . getFinalizeCommand ( context ) ; assertThat ( importer . size ( ) , is ( ) ) ; assertThat ( exporter . size ( ) , is ( ) ) ; assertThat ( finalizer . size ( ) , is ( ) ) ; assertThat ( mode ( importer , "" ) , is ( WindGateIoProcessor . OPT_BEGIN ) ) ; assertThat ( mode ( exporter , "" ) , is ( WindGateIoProcessor . OPT_END ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; } @ Test public void mutlti_profile_input ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Simple > in1 = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; In < Simple > in2 = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out1 = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out2 = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; FlowDescription desc = new DualIdentityFlow < Simple > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = WindGateIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; List < Command > importer = provider . getImportCommand ( context ) ; List < Command > exporter = provider . getExportCommand ( context ) ; List < Command > finalizer = provider . getFinalizeCommand ( context ) ; assertThat ( importer . size ( ) , is ( ) ) ; assertThat ( exporter . size ( ) , is ( ) ) ; assertThat ( finalizer . size ( ) , is ( ) ) ; assertThat ( mode ( importer , "" ) , is ( WindGateIoProcessor . OPT_BEGIN ) ) ; assertThat ( mode ( importer , "" ) , is ( WindGateIoProcessor . OPT_ONESHOT ) ) ; assertThat ( mode ( exporter , "" ) , is ( WindGateIoProcessor . OPT_END ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; } @ Test public void multi_profile_output ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Simple > in1 = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; In < Simple > in2 = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out1 = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out2 = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; FlowDescription desc = new DualIdentityFlow < Simple > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = WindGateIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; List < Command > importer = provider . getImportCommand ( context ) ; List < Command > exporter = provider . getExportCommand ( context ) ; List < Command > finalizer = provider . getFinalizeCommand ( context ) ; assertThat ( importer . size ( ) , is ( ) ) ; assertThat ( exporter . size ( ) , is ( ) ) ; assertThat ( finalizer . size ( ) , is ( ) ) ; assertThat ( mode ( importer , "" ) , is ( WindGateIoProcessor . OPT_BEGIN ) ) ; assertThat ( mode ( exporter , "" ) , is ( WindGateIoProcessor . OPT_END ) ) ; assertThat ( mode ( exporter , "" ) , is ( WindGateIoProcessor . OPT_ONESHOT ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; } @ Test public void multi_profile_inout ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Simple > in1 = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; In < Simple > in2 = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out1 = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out2 = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; FlowDescription desc = new DualIdentityFlow < Simple > ( in1 , in2 , out1 , out2 ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , not ( nullValue ( ) ) ) ; List < ExternalIoCommandProvider > commands = info . getCommandProviders ( ) ; ExternalIoCommandProvider provider = WindGateIoProcessor . findRelated ( commands ) ; assertThat ( provider , not ( nullValue ( ) ) ) ; CommandContext context = new CommandContext ( "" , "" , "" ) ; List < Command > importer = provider . getImportCommand ( context ) ; List < Command > exporter = provider . getExportCommand ( context ) ; List < Command > finalizer = provider . getFinalizeCommand ( context ) ; assertThat ( importer . size ( ) , is ( ) ) ; assertThat ( exporter . size ( ) , is ( ) ) ; assertThat ( finalizer . size ( ) , is ( ) ) ; assertThat ( mode ( importer , "" ) , is ( WindGateIoProcessor . OPT_BEGIN ) ) ; assertThat ( mode ( importer , "" ) , is ( WindGateIoProcessor . OPT_BEGIN ) ) ; assertThat ( mode ( exporter , "" ) , is ( WindGateIoProcessor . OPT_END ) ) ; assertThat ( mode ( exporter , "" ) , is ( WindGateIoProcessor . OPT_END ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; assertThat ( find ( finalizer , "" ) , is ( notNullValue ( ) ) ) ; } @ Test public void invalid_script_importer ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Simple > in = flow . createIn ( "" , new Import ( Simple . class , "" , null ) ) ; Out < Simple > out = flow . createOut ( "" , new Export ( Simple . class , "" , dummy ( ) ) ) ; FlowDescription desc = new IdentityFlow < Simple > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } @ Test public void invalid_script_exporter ( ) throws Exception { FlowDescriptionDriver flow = new FlowDescriptionDriver ( ) ; In < Simple > in = flow . createIn ( "" , new Import ( Simple . class , "" , dummy ( ) ) ) ; Out < Simple > out = flow . createOut ( "" , new Export ( Simple . class , "" , null ) ) ; FlowDescription desc = new IdentityFlow < Simple > ( in , out ) ; JobflowInfo info = compile ( flow , desc ) ; assertThat ( info , is ( nullValue ( ) ) ) ; } JobflowInfo compile ( FlowDescriptionDriver flow , FlowDescription desc ) { try { return DirectFlowCompiler . compile ( flow . createFlowGraph ( desc ) , "" , "" , "" , Location . fromPath ( "" , '' ) , folder . newFolder ( "" ) , Collections . < File > emptyList ( ) , getClass ( ) . getClassLoader ( ) , FlowCompilerOptions . load ( System . getProperties ( ) ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } } private String mode ( List < Command > commands , String profile ) { Command found = find ( commands , profile ) ; assertThat ( profile , found , is ( notNullValue ( ) ) ) ; return found . getCommandTokens ( ) . get ( ) ; } private Command find ( List < Command > commands , String profile ) { for ( Command cmd : commands ) { List < String > tokens = cmd . getCommandTokens ( ) ; if ( tokens . get ( ) . equals ( profile ) ) { return cmd ; } } return null ; } private DriverScript dummy ( ) { return new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) ; } static final class Import extends WindGateImporterDescription { private final Class < ? > modelType ; private final String profileName ; private final DriverScript driverScript ; Import ( Class < ? > modelType , String profileName , DriverScript driverScript ) { this . modelType = modelType ; this . profileName = profileName ; this . driverScript = driverScript ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getProfileName ( ) { return profileName ; } @ Override public DriverScript getDriverScript ( ) { return driverScript ; } } static final class Export extends WindGateExporterDescription { private final Class < ? > modelType ; private final String profileName ; private final DriverScript driverScript ; Export ( Class < ? > modelType , String profileName , DriverScript driverScript ) { this . modelType = modelType ; this . profileName = profileName ; this . driverScript = driverScript ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getProfileName ( ) { return profileName ; } @ Override public DriverScript getDriverScript ( ) { return driverScript ; } } } package com . asakusafw . compiler . windgate ; import com . asakusafw . vocabulary . flow . FlowDescription ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; public class IdentityFlow < T > extends FlowDescription { private In < T > in ; private Out < T > out ; public IdentityFlow ( In < T > in , Out < T > out ) { this . in = in ; this . out = out ; } @ Override protected void describe ( ) { out . add ( in ) ; } } package com . asakusafw . compiler . windgate . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . windgate . testing . io . PairInput ; import com . asakusafw . compiler . windgate . testing . io . PairOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( PairInput . class ) @ ModelOutputLocation ( PairOutput . class ) public class Pair implements DataModel < Pair > , Writable { private final IntOption key = new IntOption ( ) ; private final StringOption value = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . key . setNull ( ) ; this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Pair other ) { this . key . copyFrom ( other . key ) ; this . value . copyFrom ( other . value ) ; } public int getKey ( ) { return this . key . get ( ) ; } @ SuppressWarnings ( "" ) public void setKey ( int value0 ) { this . key . modify ( value0 ) ; } public IntOption getKeyOption ( ) { return this . key ; } @ SuppressWarnings ( "" ) public void setKeyOption ( IntOption option ) { this . key . copyFrom ( option ) ; } public Text getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( Text value0 ) { this . value . modify ( value0 ) ; } public StringOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( StringOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . key ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + key . hashCode ( ) ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Pair other = ( Pair ) obj ; if ( this . key . equals ( other . key ) == false ) { return false ; } if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } public String getValueAsString ( ) { return this . value . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setValueAsString ( String value0 ) { this . value . modify ( value0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { key . readFields ( in ) ; value . readFields ( in ) ; } } package com . asakusafw . compiler . windgate . testing . model ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . Writable ; import com . asakusafw . compiler . windgate . testing . io . SimpleInput ; import com . asakusafw . compiler . windgate . testing . io . SimpleOutput ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . model . DataModelKind ; import com . asakusafw . runtime . model . ModelInputLocation ; import com . asakusafw . runtime . model . ModelOutputLocation ; import com . asakusafw . runtime . value . StringOption ; @ DataModelKind ( "" ) @ ModelInputLocation ( SimpleInput . class ) @ ModelOutputLocation ( SimpleOutput . class ) public class Simple implements DataModel < Simple > , Writable { private final StringOption value = new StringOption ( ) ; @ Override @ SuppressWarnings ( "" ) public void reset ( ) { this . value . setNull ( ) ; } @ Override @ SuppressWarnings ( "" ) public void copyFrom ( Simple other ) { this . value . copyFrom ( other . value ) ; } public Text getValue ( ) { return this . value . get ( ) ; } @ SuppressWarnings ( "" ) public void setValue ( Text value0 ) { this . value . modify ( value0 ) ; } public StringOption getValueOption ( ) { return this . value ; } @ SuppressWarnings ( "" ) public void setValueOption ( StringOption option ) { this . value . copyFrom ( option ) ; } @ Override public String toString ( ) { StringBuilder result = new StringBuilder ( ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( "" ) ; result . append ( this . value ) ; result . append ( "" ) ; return result . toString ( ) ; } @ Override public int hashCode ( ) { int prime = ; int result = ; result = prime * result + value . hashCode ( ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Simple other = ( Simple ) obj ; if ( this . value . equals ( other . value ) == false ) { return false ; } return true ; } public String getValueAsString ( ) { return this . value . getAsString ( ) ; } @ SuppressWarnings ( "" ) public void setValueAsString ( String value0 ) { this . value . modify ( value0 ) ; } @ Override public void write ( DataOutput out ) throws IOException { value . write ( out ) ; } @ Override public void readFields ( DataInput in ) throws IOException { value . readFields ( in ) ; } } package com . asakusafw . compiler . windgate . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . windgate . testing . model . Simple ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class SimpleInput implements ModelInput < Simple > { private final RecordParser parser ; public SimpleInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Simple model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . windgate . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . windgate . testing . model . Pair ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . RecordParser ; public final class PairInput implements ModelInput < Pair > { private final RecordParser parser ; public PairInput ( RecordParser parser ) { if ( parser == null ) { throw new IllegalArgumentException ( "" ) ; } this . parser = parser ; } @ Override public boolean readTo ( Pair model ) throws IOException { if ( parser . next ( ) == false ) { return false ; } parser . fill ( model . getKeyOption ( ) ) ; parser . fill ( model . getValueOption ( ) ) ; return true ; } @ Override public void close ( ) throws IOException { parser . close ( ) ; } } package com . asakusafw . compiler . windgate . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . windgate . testing . model . Pair ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class PairOutput implements ModelOutput < Pair > { private final RecordEmitter emitter ; public PairOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Pair model ) throws IOException { emitter . emit ( model . getKeyOption ( ) ) ; emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . windgate . testing . io ; import java . io . IOException ; import com . asakusafw . compiler . windgate . testing . model . Simple ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . RecordEmitter ; public final class SimpleOutput implements ModelOutput < Simple > { private final RecordEmitter emitter ; public SimpleOutput ( RecordEmitter emitter ) { if ( emitter == null ) { throw new IllegalArgumentException ( ) ; } this . emitter = emitter ; } @ Override public void write ( Simple model ) throws IOException { emitter . emit ( model . getValueOption ( ) ) ; emitter . endRecord ( ) ; } @ Override public void close ( ) throws IOException { emitter . close ( ) ; } } package com . asakusafw . compiler . windgate . testing . jdbc ; import java . sql . ParameterMetaData ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import org . apache . hadoop . io . Text ; import com . asakusafw . compiler . windgate . testing . model . Simple ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; public final class SimpleJdbcSupport implements DataModelJdbcSupport < Simple > { private static final Map < String , Integer > PROPERTY_POSITIONS ; static { Map < String , Integer > map = new TreeMap < String , Integer > ( ) ; map . put ( "" , ) ; PROPERTY_POSITIONS = map ; } @ Override public Class < Simple > getSupportedType ( ) { return Simple . class ; } @ Override public boolean isSupported ( List < String > columnNames ) { if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames . isEmpty ( ) ) { return false ; } try { this . createPropertyVector ( columnNames ) ; return true ; } catch ( IllegalArgumentException e ) { return false ; } } @ Override public DataModelJdbcSupport . DataModelResultSet < Simple > createResultSetSupport ( ResultSet resultSet , List < String > columnNames ) { if ( resultSet == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } int [ ] vector = this . createPropertyVector ( columnNames ) ; return new ResultSetSupport ( resultSet , vector ) ; } @ Override public DataModelJdbcSupport . DataModelPreparedStatement < Simple > createPreparedStatementSupport ( PreparedStatement statement , List < String > columnNames ) { if ( statement == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } int [ ] vector = this . createPropertyVector ( columnNames ) ; return new PreparedStatementSupport ( statement , vector ) ; } private int [ ] createPropertyVector ( List < String > columnNames ) { int [ ] vector = new int [ PROPERTY_POSITIONS . size ( ) ] ; for ( int i = , n = columnNames . size ( ) ; i < n ; i ++ ) { String column = columnNames . get ( i ) ; Integer position = PROPERTY_POSITIONS . get ( column ) ; if ( position == null || vector [ position ] != ) { throw new IllegalArgumentException ( column ) ; } vector [ position ] = i + ; } return vector ; } private static final class ResultSetSupport implements DataModelJdbcSupport . DataModelResultSet < Simple > { private final ResultSet resultSet ; private final int [ ] properties ; private final Text text = new Text ( ) ; ResultSetSupport ( ResultSet resultSet , int [ ] properties ) { this . resultSet = resultSet ; this . properties = properties ; } @ Override public boolean next ( Simple object ) throws SQLException { if ( resultSet . next ( ) == false ) { return false ; } if ( properties [ ] != ) { String value = resultSet . getString ( properties [ ] ) ; if ( value != null ) { text . set ( value ) ; object . setValue ( text ) ; } else { object . setValueOption ( null ) ; } } return true ; } } private static final class PreparedStatementSupport implements DataModelJdbcSupport . DataModelPreparedStatement < Simple > { private final PreparedStatement statement ; private final int [ ] properties ; private final int [ ] types ; PreparedStatementSupport ( PreparedStatement statement , int [ ] properties ) { this . statement = statement ; this . properties = properties ; types = new int [ properties . length ] ; try { ParameterMetaData meta = statement . getParameterMetaData ( ) ; for ( int i = ; i < types . length ; i ++ ) { if ( properties [ i ] != ) { types [ i ] = meta . getParameterType ( properties [ i ] ) ; } } } catch ( SQLException e ) { throw new IllegalArgumentException ( e ) ; } } @ Override public void setParameters ( Simple object ) throws SQLException { if ( properties [ ] != ) { if ( object . getValueOption ( ) . isNull ( ) ) { statement . setNull ( properties [ ] , types [ ] ) ; } else { statement . setString ( properties [ ] , object . getValue ( ) . toString ( ) ) ; } } } } } package com . asakusafw . compiler . windgate . testing . jdbc ; import java . sql . ParameterMetaData ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import org . apache . hadoop . io . Text ; import com . asakusafw . compiler . windgate . testing . model . Pair ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; public final class PairJdbcSupport implements DataModelJdbcSupport < Pair > { private static final Map < String , Integer > PROPERTY_POSITIONS ; static { Map < String , Integer > map = new TreeMap < String , Integer > ( ) ; map . put ( "" , ) ; map . put ( "" , ) ; PROPERTY_POSITIONS = map ; } @ Override public Class < Pair > getSupportedType ( ) { return Pair . class ; } @ Override public boolean isSupported ( List < String > columnNames ) { if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames . isEmpty ( ) ) { return false ; } try { this . createPropertyVector ( columnNames ) ; return true ; } catch ( IllegalArgumentException e ) { return false ; } } @ Override public DataModelJdbcSupport . DataModelResultSet < Pair > createResultSetSupport ( ResultSet resultSet , List < String > columnNames ) { if ( resultSet == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } int [ ] vector = this . createPropertyVector ( columnNames ) ; return new ResultSetSupport ( resultSet , vector ) ; } @ Override public DataModelJdbcSupport . DataModelPreparedStatement < Pair > createPreparedStatementSupport ( PreparedStatement statement , List < String > columnNames ) { if ( statement == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } int [ ] vector = this . createPropertyVector ( columnNames ) ; return new PreparedStatementSupport ( statement , vector ) ; } private int [ ] createPropertyVector ( List < String > columnNames ) { int [ ] vector = new int [ PROPERTY_POSITIONS . size ( ) ] ; for ( int i = , n = columnNames . size ( ) ; i < n ; i ++ ) { String column = columnNames . get ( i ) ; Integer position = PROPERTY_POSITIONS . get ( column ) ; if ( position == null || vector [ position ] != ) { throw new IllegalArgumentException ( column ) ; } vector [ position ] = i + ; } return vector ; } private static final class ResultSetSupport implements DataModelJdbcSupport . DataModelResultSet < Pair > { private final ResultSet resultSet ; private final int [ ] properties ; private final Text text = new Text ( ) ; ResultSetSupport ( ResultSet resultSet , int [ ] properties ) { this . resultSet = resultSet ; this . properties = properties ; } @ Override public boolean next ( Pair object ) throws SQLException { if ( resultSet . next ( ) == false ) { return false ; } if ( properties [ ] != ) { object . setKey ( resultSet . getInt ( properties [ ] ) ) ; if ( resultSet . wasNull ( ) ) { object . setKeyOption ( null ) ; } } if ( properties [ ] != ) { String value = resultSet . getString ( properties [ ] ) ; if ( value != null ) { text . set ( value ) ; object . setValue ( text ) ; } else { object . setValueOption ( null ) ; } } return true ; } } private static final class PreparedStatementSupport implements DataModelJdbcSupport . DataModelPreparedStatement < Pair > { private final PreparedStatement statement ; private final int [ ] properties ; private final int [ ] types ; PreparedStatementSupport ( PreparedStatement statement , int [ ] properties ) { this . statement = statement ; this . properties = properties ; types = new int [ properties . length ] ; try { ParameterMetaData meta = statement . getParameterMetaData ( ) ; for ( int i = ; i < types . length ; i ++ ) { if ( properties [ i ] != ) { types [ i ] = meta . getParameterType ( properties [ i ] ) ; } } } catch ( SQLException e ) { throw new IllegalArgumentException ( e ) ; } } @ Override public void setParameters ( Pair object ) throws SQLException { if ( properties [ ] != ) { if ( object . getKeyOption ( ) . isNull ( ) ) { statement . setNull ( properties [ ] , types [ ] ) ; } else { statement . setInt ( properties [ ] , object . getKey ( ) ) ; } } if ( properties [ ] != ) { if ( object . getValueOption ( ) . isNull ( ) ) { statement . setNull ( properties [ ] , types [ ] ) ; } else { statement . setString ( properties [ ] , object . getValue ( ) . toString ( ) ) ; } } } } } package com . asakusafw . compiler . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import java . util . Properties ; import java . util . zip . ZipEntry ; import java . util . zip . ZipFile ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . compiler . flow . Location ; import com . asakusafw . compiler . testing . JobflowInfo ; import com . asakusafw . compiler . util . tester . CompilerTester ; import com . asakusafw . compiler . windgate . testing . model . Simple ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . vocabulary . flow . In ; import com . asakusafw . vocabulary . flow . Out ; import com . asakusafw . vocabulary . windgate . Constants ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; public class WindGateIoProcessorRunTest { @ Rule public CompilerTester tester = new CompilerTester ( ) ; @ Test public void simple ( ) throws Exception { In < Simple > in = tester . input ( "" , new Import ( Simple . class , "" , dummy ( "" ) ) ) ; Out < Simple > out = tester . output ( "" , new Export ( Simple . class , "" , dummy ( "" ) ) ) ; JobflowInfo info = tester . compileFlow ( new IdentityFlow < Simple > ( in , out ) ) ; GateScript importerScript = loadScript ( info , "" , true ) ; assertThat ( importerScript . getProcesses ( ) . size ( ) , is ( ) ) ; ProcessScript < ? > importer = getProcess ( importerScript , "" ) ; assertThat ( importer . getSourceScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( importer . getDrainScript ( ) . getResourceName ( ) , is ( Constants . HADOOP_FILE_RESOURCE_NAME ) ) ; String importerPath = importer . getDrainScript ( ) . getConfiguration ( ) . get ( FileProcess . FILE . key ( ) ) ; assertThat ( importerPath , is ( notNullValue ( ) ) ) ; Location importerLocation = Location . fromPath ( importerPath , '' ) ; GateScript exporterScript = loadScript ( info , "" , false ) ; assertThat ( exporterScript . getProcesses ( ) . size ( ) , is ( ) ) ; ProcessScript < ? > exporter = getProcess ( exporterScript , "" ) ; assertThat ( exporter . getSourceScript ( ) . getResourceName ( ) , is ( Constants . HADOOP_FILE_RESOURCE_NAME ) ) ; assertThat ( exporter . getDrainScript ( ) . getResourceName ( ) , is ( "" ) ) ; String exporterPath = exporter . getSourceScript ( ) . getConfiguration ( ) . get ( FileProcess . FILE . key ( ) ) ; assertThat ( exporterPath , is ( notNullValue ( ) ) ) ; Location exporterLocation = Location . fromPath ( exporterPath , '' ) ; assertThat ( exporterLocation . isPrefix ( ) , is ( true ) ) ; ModelOutput < Simple > source = tester . openOutput ( Simple . class , importerLocation ) ; Simple model = new Simple ( ) ; model . setValueAsString ( "" ) ; source . write ( model ) ; model . setValueAsString ( "" ) ; source . write ( model ) ; model . setValueAsString ( "" ) ; source . write ( model ) ; source . close ( ) ; assertThat ( tester . runStages ( info ) , is ( true ) ) ; List < Simple > results = tester . getList ( Simple . class , exporterLocation ) ; assertThat ( results . size ( ) , is ( ) ) ; Collections . sort ( results , new Comparator < Simple > ( ) { @ Override public int compare ( Simple o1 , Simple o2 ) { return o1 . getValueOption ( ) . compareTo ( o2 . getValueOption ( ) ) ; } } ) ; assertThat ( results . get ( ) . getValueAsString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . getValueAsString ( ) , is ( "" ) ) ; assertThat ( results . get ( ) . getValueAsString ( ) , is ( "" ) ) ; } private GateScript loadScript ( JobflowInfo info , String profile , boolean importer ) throws IOException { File file = info . getPackageFile ( ) ; ZipFile zip = new ZipFile ( file ) ; try { String location = WindGateIoProcessor . getScriptLocation ( importer , profile ) ; ZipEntry entry = zip . getEntry ( location ) ; assertThat ( entry , is ( notNullValue ( ) ) ) ; InputStream input = zip . getInputStream ( entry ) ; Properties p = new Properties ( ) ; p . load ( input ) ; input . close ( ) ; return GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; } finally { zip . close ( ) ; } } private ProcessScript < ? > getProcess ( GateScript script , String name ) { for ( ProcessScript < ? > proc : script . getProcesses ( ) ) { if ( proc . getName ( ) . equals ( name ) ) { return proc ; } } throw new AssertionError ( name ) ; } private DriverScript dummy ( String resourceName ) { return new DriverScript ( resourceName , Collections . < String , String > emptyMap ( ) ) ; } static final class Import extends WindGateImporterDescription { private final Class < ? > modelType ; private final String profileName ; private final DriverScript driverScript ; Import ( Class < ? > modelType , String profileName , DriverScript driverScript ) { this . modelType = modelType ; this . profileName = profileName ; this . driverScript = driverScript ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getProfileName ( ) { return profileName ; } @ Override public DriverScript getDriverScript ( ) { return driverScript ; } } static final class Export extends WindGateExporterDescription { private final Class < ? > modelType ; private final String profileName ; private final DriverScript driverScript ; Export ( Class < ? > modelType , String profileName , DriverScript driverScript ) { this . modelType = modelType ; this . profileName = profileName ; this . driverScript = driverScript ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getProfileName ( ) { return profileName ; } @ Override public DriverScript getDriverScript ( ) { return driverScript ; } } } package com . asakusafw . dmdl . windgate . jdbc . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . math . BigDecimal ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . io . Text ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . dmdl . java . emitter . driver . ObjectDriver ; import com . asakusafw . dmdl . windgate . common . driver . GeneratorTesterRoot ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport . DataModelPreparedStatement ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport . DataModelResultSet ; public class JdbcSupportEmitterTest extends GeneratorTesterRoot { @ Rule public H2Resource h2 = new H2Resource ( "" ) ; @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new JdbcSupportEmitter ( ) ) ; emitDrivers . add ( new ObjectDriver ( ) ) ; } @ Test public void simple ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; DataModelJdbcSupport < ? > support = ( DataModelJdbcSupport < ? > ) loaded . newObject ( "" , "" ) ; assertThat ( support . getSupportedType ( ) , is ( ( Object ) model . unwrap ( ) . getClass ( ) ) ) ; assertThat ( support . isSupported ( list ( "" ) ) , is ( true ) ) ; assertThat ( support . isSupported ( list ( "" , "" ) ) , is ( false ) ) ; assertThat ( support . isSupported ( this . < String > list ( ) ) , is ( false ) ) ; assertThat ( support . isSupported ( list ( "" ) ) , is ( false ) ) ; assertThat ( support . isSupported ( list ( "" , "" ) ) , is ( false ) ) ; DataModelJdbcSupport < Object > unsafe = unsafe ( support ) ; h2 . executeFile ( "" ) ; Connection conn = h2 . open ( ) ; try { PreparedStatement ps = conn . prepareStatement ( "" ) ; DataModelPreparedStatement < Object > p = unsafe . createPreparedStatementSupport ( ps , list ( "" ) ) ; model . set ( "" , new Text ( "" ) ) ; p . setParameters ( model . unwrap ( ) ) ; ps . executeUpdate ( ) ; ps . close ( ) ; Statement s = conn . createStatement ( ) ; ResultSet rs = s . executeQuery ( "" ) ; DataModelResultSet < Object > r = unsafe . createResultSetSupport ( rs , list ( "" ) ) ; assertThat ( r . next ( model . unwrap ( ) ) , is ( true ) ) ; assertThat ( model . get ( "" ) , is ( ( Object ) new Text ( "" ) ) ) ; assertThat ( r . next ( model . unwrap ( ) ) , is ( false ) ) ; } finally { conn . close ( ) ; } } @ Test public void types ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; DataModelJdbcSupport < ? > support = ( DataModelJdbcSupport < ? > ) loaded . newObject ( "" , "" ) ; assertThat ( support . getSupportedType ( ) , is ( ( Object ) model . unwrap ( ) . getClass ( ) ) ) ; List < String > list = list ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , } ) ; assertThat ( support . isSupported ( list ) , is ( true ) ) ; DataModelJdbcSupport < Object > unsafe = unsafe ( support ) ; h2 . executeFile ( "" ) ; Connection conn = h2 . open ( ) ; try { PreparedStatement ps = conn . prepareStatement ( MessageFormat . format ( "" , join ( list ) , join ( Collections . nCopies ( list . size ( ) , "" ) ) ) ) ; DataModelPreparedStatement < Object > p = unsafe . createPreparedStatementSupport ( ps , list ) ; ModelWrapper nulls = loaded . newModel ( "" ) ; p . setParameters ( nulls . unwrap ( ) ) ; ps . executeUpdate ( ) ; ModelWrapper text = loaded . newModel ( "" ) ; text . set ( "" , new Text ( "" ) ) ; p . setParameters ( text . unwrap ( ) ) ; ps . executeUpdate ( ) ; ModelWrapper all = loaded . newModel ( "" ) ; all . set ( "" , ) ; all . set ( "" , new Text ( "" ) ) ; all . set ( "" , true ) ; all . set ( "" , ( byte ) ) ; all . set ( "" , ( short ) ) ; all . set ( "" , ) ; all . set ( "" , ) ; all . set ( "" , ) ; all . set ( "" , new BigDecimal ( "" ) ) ; all . set ( "" , new Date ( , , ) ) ; all . set ( "" , new DateTime ( , , , , , ) ) ; p . setParameters ( all . unwrap ( ) ) ; ps . executeUpdate ( ) ; ps . close ( ) ; Statement s = conn . createStatement ( ) ; ResultSet rs = s . executeQuery ( MessageFormat . format ( "" , join ( list ) ) ) ; DataModelResultSet < Object > r = unsafe . createResultSetSupport ( rs , list ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; assertThat ( r . next ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . unwrap ( ) , is ( nulls . unwrap ( ) ) ) ; assertThat ( r . next ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . unwrap ( ) , is ( text . unwrap ( ) ) ) ; assertThat ( r . next ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . unwrap ( ) , is ( all . unwrap ( ) ) ) ; assertThat ( r . next ( buffer . unwrap ( ) ) , is ( false ) ) ; } finally { conn . close ( ) ; } } @ Test public void no_attributes ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; assertThat ( loaded . exists ( "" , "" ) , is ( false ) ) ; } private String join ( List < String > list ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( list . get ( ) ) ; for ( int i = , n = list . size ( ) ; i < n ; i ++ ) { buf . append ( "" ) ; buf . append ( list . get ( i ) ) ; } return buf . toString ( ) ; } @ SuppressWarnings ( "" ) private DataModelJdbcSupport < Object > unsafe ( DataModelJdbcSupport < ? > support ) { return ( DataModelJdbcSupport < Object > ) support ; } private < T > List < T > list ( T ... values ) { return Arrays . asList ( values ) ; } } package com . asakusafw . dmdl . windgate . jdbc . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . ResultSetMetaData ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import org . junit . rules . TestWatcher ; import org . junit . runner . Description ; import com . asakusafw . utils . collections . Lists ; public class H2Resource extends TestWatcher { private final String name ; private Class < ? > context ; private Connection connection ; public H2Resource ( String name ) { this . name = name ; } @ Override protected void starting ( Description description ) { org . h2 . Driver . load ( ) ; this . context = description . getTestClass ( ) ; this . connection = open ( ) ; boolean green = false ; try { leakcheck ( ) ; before ( ) ; green = true ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } finally { if ( green == false ) { finished ( description ) ; } } } private void leakcheck ( ) { try { execute0 ( "" ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } protected void before ( ) throws Exception { return ; } public Connection open ( ) { try { return DriverManager . getConnection ( getJdbcUrl ( ) ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } public String getJdbcUrl ( ) { return "" + name ; } public List < List < Object > > query ( String sql ) { try { return query0 ( sql ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public List < Object > single ( String sql ) { try { List < List < Object > > query = query0 ( sql ) ; assertThat ( sql , query . size ( ) , is ( ) ) ; return query . get ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public int count ( String table ) { try { List < List < Object > > r = query0 ( MessageFormat . format ( "" , table ) ) ; if ( r . size ( ) != ) { return - ; } return ( ( Number ) r . get ( ) . get ( ) ) . intValue ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return - ; } } private List < List < Object > > query0 ( String sql ) throws SQLException { Statement s = connection . createStatement ( ) ; try { ResultSet rs = s . executeQuery ( sql ) ; ResultSetMetaData meta = rs . getMetaData ( ) ; int size = meta . getColumnCount ( ) ; List < List < Object > > results = Lists . create ( ) ; while ( rs . next ( ) ) { Object [ ] columns = new Object [ size ] ; for ( int i = ; i < size ; i ++ ) { columns [ i ] = rs . getObject ( i + ) ; } results . add ( Arrays . asList ( columns ) ) ; } return results ; } finally { s . close ( ) ; } } public void execute ( String sql ) { try { execute0 ( sql ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private void execute0 ( String sql ) throws SQLException { PreparedStatement ps = connection . prepareStatement ( sql ) ; try { ps . execute ( ) ; connection . commit ( ) ; } finally { ps . close ( ) ; } } public void executeFile ( String sqlFile ) { String content = load ( sqlFile ) ; execute ( content ) ; } private String load ( String resource ) { InputStream source = context . getResourceAsStream ( resource ) ; assertThat ( resource , source , is ( not ( nullValue ( ) ) ) ) ; try { StringBuilder buf = new StringBuilder ( ) ; Reader reader = new InputStreamReader ( source , "" ) ; char [ ] cbuf = new char [ ] ; while ( true ) { int read = reader . read ( cbuf ) ; if ( read < ) { break ; } buf . append ( cbuf , , read ) ; } return buf . toString ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } finally { try { source . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } @ Override public void finished ( Description description ) { if ( connection != null ) { try { connection . close ( ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } } } package com . asakusafw . dmdl . windgate . common . driver ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . List ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . PackageDeclaration ; import com . asakusafw . utils . java . model . util . Emitter ; public class VolatileEmitter extends Emitter { private final List < VolatileJavaFile > emitted = Lists . create ( ) ; @ Override public PrintWriter openFor ( PackageDeclaration packageDeclOrNull , String subPath ) throws IOException { StringBuilder buf = new StringBuilder ( ) ; if ( packageDeclOrNull != null ) { buf . append ( packageDeclOrNull . getName ( ) . toNameString ( ) . replace ( '' , '' ) ) ; buf . append ( "" ) ; } assert subPath . endsWith ( "" ) ; buf . append ( subPath . substring ( , subPath . length ( ) - ) ) ; VolatileJavaFile file = new VolatileJavaFile ( buf . toString ( ) ) ; register ( file ) ; return new PrintWriter ( file . openWriter ( ) ) ; } private void register ( VolatileJavaFile file ) { emitted . add ( file ) ; } public List < VolatileJavaFile > getEmitted ( ) { return emitted ; } } package com . asakusafw . dmdl . windgate . common . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . lang . reflect . Method ; import java . net . URL ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Locale ; import java . util . regex . Pattern ; import javax . tools . Diagnostic ; import javax . tools . JavaFileObject ; import org . junit . After ; import org . junit . Rule ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . dmdl . java . emitter . CompositeDataModelDriver ; import com . asakusafw . dmdl . java . emitter . NameConstants ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . java . util . JavaName ; import com . asakusafw . dmdl . model . AstModelDefinition ; import com . asakusafw . dmdl . model . AstScript ; import com . asakusafw . dmdl . model . AstSimpleName ; import com . asakusafw . dmdl . parser . DmdlEmitter ; import com . asakusafw . dmdl . source . DmdlSourceDirectory ; import com . asakusafw . dmdl . source . DmdlSourceRepository ; import com . asakusafw . dmdl . source . DmdlSourceResource ; import com . asakusafw . runtime . model . DataModel ; import com . asakusafw . runtime . value . ValueOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . jsr199 . testing . VolatileCompiler ; import com . asakusafw . utils . java . jsr199 . testing . VolatileJavaFile ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . util . Models ; public class GeneratorTesterRoot { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; protected final VolatileCompiler compiler = new VolatileCompiler ( ) ; protected final List < JavaDataModelDriver > emitDrivers = Lists . create ( ) ; @ After public void tearDown ( ) throws Exception { compiler . close ( ) ; } protected void emitDmdl ( AstModelDefinition < ? > model ) { AstScript script = new AstScript ( null , Collections . singletonList ( model ) ) ; StringWriter buffer = new StringWriter ( ) ; PrintWriter output = new PrintWriter ( buffer ) ; DmdlEmitter . emit ( script , output ) ; output . close ( ) ; try { File file = folder . newFile ( model . name . identifier + "" ) ; System . out . println ( "" + file . getName ( ) ) ; System . out . println ( buffer . toString ( ) ) ; PrintWriter writer = new PrintWriter ( file , "" ) ; try { writer . print ( buffer . toString ( ) ) ; } finally { writer . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } protected ModelLoader generateJava ( ) { try { List < VolatileJavaFile > files = emit ( new DmdlSourceDirectory ( folder . getRoot ( ) , Charset . forName ( "" ) , Pattern . compile ( "" ) , Pattern . compile ( "" ) ) ) ; ClassLoader loaded = compile ( files ) ; return new ModelLoader ( loaded ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected ModelLoader generateJava ( String name ) { try { List < VolatileJavaFile > files = emit ( collectInput ( name ) ) ; ClassLoader loaded = compile ( files ) ; return new ModelLoader ( loaded ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } protected void shouldSemanticError ( String name ) { try { emit ( collectInput ( name ) ) ; throw new AssertionError ( "" ) ; } catch ( IOException e ) { } } private ClassLoader compile ( List < VolatileJavaFile > files ) { if ( files . isEmpty ( ) ) { throw new AssertionError ( ) ; } for ( JavaFileObject java : files ) { try { System . out . println ( "" + java . getName ( ) ) ; System . out . println ( java . getCharContent ( true ) ) ; System . out . println ( ) ; System . out . println ( ) ; } catch ( IOException e ) { } compiler . addSource ( java ) ; } compiler . addArguments ( "" ) ; List < Diagnostic < ? extends JavaFileObject > > diagnostics = compiler . doCompile ( ) ; boolean hasWrong = false ; for ( Diagnostic < ? > d : diagnostics ) { if ( d . getKind ( ) == Diagnostic . Kind . ERROR || d . getKind ( ) == Diagnostic . Kind . WARNING ) { System . out . println ( "" ) ; System . out . println ( d . getMessage ( Locale . getDefault ( ) ) ) ; hasWrong = true ; } } if ( hasWrong ) { throw new AssertionError ( diagnostics ) ; } return compiler . getClassLoader ( ) ; } private List < VolatileJavaFile > emit ( DmdlSourceRepository source ) throws IOException { ModelFactory factory = Models . getModelFactory ( ) ; VolatileEmitter emitter = new VolatileEmitter ( ) ; com . asakusafw . dmdl . java . Configuration conf = new com . asakusafw . dmdl . java . Configuration ( factory , source , Models . toName ( factory , "" ) , emitter , getClass ( ) . getClassLoader ( ) , Locale . getDefault ( ) ) ; com . asakusafw . dmdl . java . GenerateTask task = new com . asakusafw . dmdl . java . GenerateTask ( conf ) ; task . process ( new CompositeDataModelDriver ( emitDrivers ) ) ; return emitter . getEmitted ( ) ; } private DmdlSourceRepository collectInput ( String name ) { URL url = getClass ( ) . getResource ( name + "" ) ; assertThat ( name , url , not ( nullValue ( ) ) ) ; return new DmdlSourceResource ( Collections . singletonList ( url ) , Charset . forName ( "" ) ) ; } protected static class ModelLoader { private final ClassLoader classLoader ; private String namespace ; ModelLoader ( ClassLoader loaded ) { assert loaded != null ; this . classLoader = loaded ; this . namespace = NameConstants . DEFAULT_NAMESPACE ; } public final void setNamespace ( String namespace ) { this . namespace = namespace ; } public Class < ? > modelType ( String name ) { try { return type ( NameConstants . CATEGORY_DATA_MODEL , name ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } } public ModelWrapper newModel ( String name ) { try { Class < ? > loaded = modelType ( name ) ; Object instance = loaded . newInstance ( ) ; return new ModelWrapper ( instance ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public boolean exists ( String category , String name ) { try { type ( category , name ) ; return true ; } catch ( Exception e ) { return false ; } } public Object newObject ( String category , String name ) { try { Class < ? > loaded = type ( category , name ) ; Object instance = loaded . newInstance ( ) ; return instance ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private Class < ? > type ( String category , String name ) throws ClassNotFoundException { return classLoader . loadClass ( MessageFormat . format ( "" , "" , namespace , category , name ) ) ; } } @ SuppressWarnings ( "" ) protected static class ModelWrapper { private final DataModel instance ; private Class < ? > interfaceType ; ModelWrapper ( Object instance ) { this . instance = ( DataModel ) instance ; this . interfaceType = instance . getClass ( ) ; } public Object unwrap ( ) { return instance ; } public void setInterfaceType ( Class < ? > interfaceType ) { this . interfaceType = interfaceType ; } public boolean is ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; Object result = invoke ( jn . toMemberName ( ) ) ; return ( Boolean ) result ; } public Object get ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; return invoke ( jn . toMemberName ( ) ) ; } public void set ( String name , Object value ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; invoke ( jn . toMemberName ( ) , value ) ; } public ValueOption < ? > getOption ( String name ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; jn . addLast ( "" ) ; return ( ValueOption < ? > ) invoke ( jn . toMemberName ( ) ) ; } public void setOption ( String name , ValueOption < ? > option ) { JavaName jn = JavaName . of ( new AstSimpleName ( null , name ) ) ; jn . addFirst ( "" ) ; jn . addLast ( "" ) ; invoke ( jn . toMemberName ( ) , option ) ; } public void reset ( ) { instance . reset ( ) ; } @ SuppressWarnings ( "" ) public void copyFrom ( ModelWrapper wrapper ) { instance . copyFrom ( wrapper . instance ) ; } public Object invoke ( String name , Object ... arguments ) { for ( Method method : interfaceType . getMethods ( ) ) { if ( method . getName ( ) . equals ( name ) ) { try { return method . invoke ( instance , arguments ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } } throw new AssertionError ( name ) ; } } } package com . asakusafw . dmdl . windgate . csv . driver ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . math . BigDecimal ; import java . util . List ; import org . apache . hadoop . io . Text ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . dmdl . java . emitter . driver . ObjectDriver ; import com . asakusafw . dmdl . windgate . common . driver . GeneratorTesterRoot ; import com . asakusafw . runtime . io . csv . CsvConfiguration ; import com . asakusafw . runtime . io . csv . CsvParser ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . IntOption ; import com . asakusafw . runtime . value . LongOption ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport . DataModelReader ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport . DataModelWriter ; public class CsvSupportEmitterTest extends GeneratorTesterRoot { @ Before public void setUp ( ) throws Exception { emitDrivers . add ( new CsvSupportEmitter ( ) ) ; emitDrivers . add ( new ObjectDriver ( ) ) ; } @ Test public void simple ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; DataModelStreamSupport < ? > support = ( DataModelStreamSupport < ? > ) loaded . newObject ( "" , "" ) ; assertThat ( support . getSupportedType ( ) , is ( ( Object ) model . unwrap ( ) . getClass ( ) ) ) ; DataModelStreamSupport < Object > unsafe = unsafe ( support ) ; model . set ( "" , new Text ( "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = unsafe . createWriter ( "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; Object buffer = loaded . newModel ( "" ) . unwrap ( ) ; DataModelReader < Object > reader = unsafe . createReader ( "" , new ByteArrayInputStream ( output . toByteArray ( ) ) ) ; assertThat ( reader . readTo ( buffer ) , is ( true ) ) ; assertThat ( buffer , is ( buffer ) ) ; assertThat ( reader . readTo ( buffer ) , is ( false ) ) ; } @ Test public void types ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; DataModelStreamSupport < ? > support = ( DataModelStreamSupport < ? > ) loaded . newObject ( "" , "" ) ; assertThat ( support . getSupportedType ( ) , is ( ( Object ) model . unwrap ( ) . getClass ( ) ) ) ; ModelWrapper empty = loaded . newModel ( "" ) ; ModelWrapper all = loaded . newModel ( "" ) ; all . set ( "" , ) ; all . set ( "" , new Text ( "" ) ) ; all . set ( "" , true ) ; all . set ( "" , ( byte ) ) ; all . set ( "" , ( short ) ) ; all . set ( "" , ) ; all . set ( "" , ) ; all . set ( "" , ) ; all . set ( "" , new BigDecimal ( "" ) ) ; all . set ( "" , new Date ( , , ) ) ; all . set ( "" , new DateTime ( , , , , , ) ) ; DataModelStreamSupport < Object > unsafe = unsafe ( support ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = unsafe . createWriter ( "" , output ) ; writer . write ( empty . unwrap ( ) ) ; writer . write ( all . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; Object buffer = loaded . newModel ( "" ) . unwrap ( ) ; DataModelReader < Object > reader = unsafe . createReader ( "" , new ByteArrayInputStream ( output . toByteArray ( ) ) ) ; assertThat ( reader . readTo ( buffer ) , is ( true ) ) ; assertThat ( buffer , is ( empty . unwrap ( ) ) ) ; assertThat ( reader . readTo ( buffer ) , is ( true ) ) ; assertThat ( buffer , is ( all . unwrap ( ) ) ) ; assertThat ( reader . readTo ( buffer ) , is ( false ) ) ; } @ Test public void attributes ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; model . set ( "" , new Text ( "" ) ) ; model . set ( "" , true ) ; model . set ( "" , false ) ; model . set ( "" , new Date ( , , ) ) ; model . set ( "" , new DateTime ( , , , , , ) ) ; DataModelStreamSupport < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = support . createWriter ( "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; String [ ] [ ] results = parse ( , new String ( output . toByteArray ( ) , "" ) ) ; assertThat ( results , is ( new String [ ] [ ] { { "" , "" , "" , "" , "" } , { "" , "" , "" , "" , "" } , } ) ) ; } @ Test public void header ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; DataModelStreamSupport < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = support . createWriter ( "" , output ) ; model . set ( "" , new Text ( "" ) ) ; writer . write ( model . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; String [ ] [ ] results = parse ( , new String ( output . toByteArray ( ) , "" ) ) ; assertThat ( results , is ( new String [ ] [ ] { { "" } , { "" } , } ) ) ; } @ Test public void implicit_field_name ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; DataModelStreamSupport < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = support . createWriter ( "" , output ) ; model . set ( "" , new Text ( "" ) ) ; writer . write ( model . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; String [ ] [ ] results = parse ( , new String ( output . toByteArray ( ) , "" ) ) ; assertThat ( results , is ( new String [ ] [ ] { { "" } , { "" } , } ) ) ; } @ Test public void file_name ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; DataModelStreamSupport < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = support . createWriter ( "" , output ) ; model . set ( "" , new Text ( "" ) ) ; writer . write ( model . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; DataModelReader < Object > reader = support . createReader ( "" , new ByteArrayInputStream ( output . toByteArray ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( false ) ) ; } @ Test public void line_number ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; model . set ( "" , new Text ( "" ) ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; DataModelStreamSupport < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = support . createWriter ( "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . write ( model . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; DataModelReader < Object > reader = support . createReader ( "" , new ByteArrayInputStream ( output . toByteArray ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new IntOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( false ) ) ; } @ Test public void record_number ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; model . set ( "" , new Text ( "" ) ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; DataModelStreamSupport < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = support . createWriter ( "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . write ( model . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; DataModelReader < Object > reader = support . createReader ( "" , new ByteArrayInputStream ( output . toByteArray ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new LongOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( false ) ) ; } @ Test public void ignore ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; ModelWrapper model = loaded . newModel ( "" ) ; model . set ( "" , new Text ( "" ) ) ; model . set ( "" , new Text ( "" ) ) ; ModelWrapper buffer = loaded . newModel ( "" ) ; DataModelStreamSupport < Object > support = unsafe ( loaded . newObject ( "" , "" ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; DataModelWriter < Object > writer = support . createWriter ( "" , output ) ; writer . write ( model . unwrap ( ) ) ; writer . flush ( ) ; output . close ( ) ; DataModelReader < Object > reader = support . createReader ( "" , new ByteArrayInputStream ( output . toByteArray ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( true ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( "" ) ) ) ; assertThat ( buffer . getOption ( "" ) , is ( ( Object ) new StringOption ( ) ) ) ; assertThat ( reader . readTo ( buffer . unwrap ( ) ) , is ( false ) ) ; } @ Test public void no_attributes ( ) throws Exception { ModelLoader loaded = generateJava ( "" ) ; assertThat ( loaded . exists ( "" , "" ) , is ( false ) ) ; } @ Test public void invalid_file_name ( ) throws Exception { shouldSemanticError ( "" ) ; } @ Test public void invalid_line_number ( ) throws Exception { shouldSemanticError ( "" ) ; } @ Test public void invalid_record_number ( ) throws Exception { shouldSemanticError ( "" ) ; } private String [ ] [ ] parse ( int columns , String string ) { CsvConfiguration conf = new CsvConfiguration ( CsvConfiguration . DEFAULT_CHARSET , CsvConfiguration . DEFAULT_HEADER_CELLS , CsvConfiguration . DEFAULT_TRUE_FORMAT , CsvConfiguration . DEFAULT_FALSE_FORMAT , CsvConfiguration . DEFAULT_DATE_FORMAT , CsvConfiguration . DEFAULT_DATE_TIME_FORMAT ) ; ByteArrayInputStream input = new ByteArrayInputStream ( string . getBytes ( conf . getCharset ( ) ) ) ; CsvParser parser = new CsvParser ( input , string , conf ) ; List < String [ ] > results = Lists . create ( ) ; try { StringOption buffer = new StringOption ( ) ; while ( parser . next ( ) ) { String [ ] line = new String [ columns ] ; for ( int i = ; i < columns ; i ++ ) { parser . fill ( buffer ) ; line [ i ] = buffer . or ( ( String ) null ) ; } parser . endRecord ( ) ; results . add ( line ) ; } parser . close ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } return results . toArray ( new String [ results . size ( ) ] [ ] ) ; } @ Test public void invalid_attribute ( ) throws Exception { shouldSemanticError ( "" ) ; } @ SuppressWarnings ( "" ) private DataModelStreamSupport < Object > unsafe ( Object support ) { return ( DataModelStreamSupport < Object > ) support ; } } package com . asakusafw . dmdl . windgate . csv . driver ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . dmdl . windgate . csv . driver . CsvFieldTrait . Kind ; public class CsvIgnoreDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . IGNORE , null ) ) ; } } } package com . asakusafw . dmdl . windgate . csv . driver ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . dmdl . windgate . csv . driver . CsvFieldTrait . Kind ; public class CsvFileNameDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; CsvFieldDriver . checkFieldType ( environment , declaration , attribute , BasicTypeKind . TEXT ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . FILE_NAME , null ) ) ; } } } package com . asakusafw . dmdl . windgate . csv . driver ; import java . text . SimpleDateFormat ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . Trait ; import com . asakusafw . runtime . io . csv . CsvConfiguration ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class CsvSupportTrait implements Trait < CsvSupportTrait > { private final AstNode originalAst ; private final Configuration configuration ; public CsvSupportTrait ( AstNode originalAst , Configuration configuration ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . configuration = configuration ; } public Configuration getConfiguration ( ) { return configuration ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public static class Configuration { private String charsetName = "" ; private boolean enableHeader = false ; private String trueFormat = CsvConfiguration . DEFAULT_TRUE_FORMAT ; private String falseFormat = CsvConfiguration . DEFAULT_FALSE_FORMAT ; private String dateFormat = CsvConfiguration . DEFAULT_DATE_FORMAT ; private String dateTimeFormat = CsvConfiguration . DEFAULT_DATE_TIME_FORMAT ; public String getCharsetName ( ) { return charsetName ; } public void setCharsetName ( String charsetName ) { this . charsetName = charsetName ; } public boolean isEnableHeader ( ) { return enableHeader ; } public void setEnableHeader ( boolean enableHeader ) { this . enableHeader = enableHeader ; } public String getTrueFormat ( ) { return trueFormat ; } public void setTrueFormat ( String format ) { this . trueFormat = format ; } public String getFalseFormat ( ) { return falseFormat ; } public void setFalseFormat ( String format ) { this . falseFormat = format ; } public String getDateFormat ( ) { return dateFormat ; } public void setDateFormat ( String format ) { this . dateFormat = format ; } public String getDateTimeFormat ( ) { return dateTimeFormat ; } public void setDateTimeFormat ( String format ) { this . dateTimeFormat = format ; } } } package com . asakusafw . dmdl . windgate . csv . driver ; package com . asakusafw . dmdl . windgate . csv . driver ; import java . util . Arrays ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . dmdl . windgate . csv . driver . CsvFieldTrait . Kind ; public class CsvFieldDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; String value = AttributeUtil . takeString ( environment , attribute , elements , ELEMENT_NAME , false ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; checkFieldType ( environment , declaration , attribute , BasicTypeKind . values ( ) ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . VALUE , value ) ) ; } } static boolean checkConflict ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { assert environment != null ; assert declaration != null ; assert attribute != null ; if ( declaration . getTrait ( CsvFieldTrait . class ) == null ) { return true ; } environment . report ( new Diagnostic ( Level . ERROR , attribute , "" , declaration . getOwner ( ) . getName ( ) . identifier , declaration . getName ( ) . identifier ) ) ; return false ; } static void checkFieldType ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute , BasicTypeKind ... types ) { assert environment != null ; assert declaration != null ; assert attribute != null ; assert types != null ; assert types . length > ; Type type = declaration . getType ( ) ; if ( type instanceof BasicType ) { BasicTypeKind kind = ( ( BasicType ) type ) . getKind ( ) ; for ( BasicTypeKind accept : types ) { if ( kind == accept ) { return ; } } } environment . report ( new Diagnostic ( Level . ERROR , attribute , "" , declaration . getOwner ( ) . getName ( ) . identifier , declaration . getName ( ) . identifier , attribute . name . toString ( ) , Arrays . asList ( types ) ) ) ; } } package com . asakusafw . dmdl . windgate . csv . driver ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . dmdl . windgate . csv . driver . CsvFieldTrait . Kind ; public class CsvRecordNumberDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; CsvFieldDriver . checkFieldType ( environment , declaration , attribute , BasicTypeKind . INT , BasicTypeKind . LONG ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . RECORD_NUMBER , null ) ) ; } } } package com . asakusafw . dmdl . windgate . csv . driver ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . dmdl . windgate . csv . driver . CsvFieldTrait . Kind ; import com . asakusafw . dmdl . windgate . csv . driver . CsvSupportTrait . Configuration ; import com . asakusafw . runtime . io . csv . CsvConfiguration ; import com . asakusafw . runtime . io . csv . CsvEmitter ; import com . asakusafw . runtime . io . csv . CsvParser ; import com . asakusafw . runtime . value . StringOption ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ExpressionStatement ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport . DataModelReader ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport . DataModelWriter ; public class CsvSupportEmitter extends JavaDataModelDriver { static final Logger LOG = LoggerFactory . getLogger ( CsvSupportEmitter . class ) ; public static final String CATEGORY_STREAM = "" ; @ Override public void generateResources ( EmitContext context , ModelDeclaration model ) throws IOException { if ( isTarget ( model ) == false ) { return ; } checkPropertyType ( model ) ; Name supportName = generateSupport ( context , model ) ; generateImporter ( context , model , supportName ) ; generateExporter ( context , model , supportName ) ; } private Name generateSupport ( EmitContext context , ModelDeclaration model ) throws IOException { assert context != null ; assert model != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; SupportGenerator . emit ( next , model , model . getTrait ( CsvSupportTrait . class ) . getConfiguration ( ) ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private Name generateImporter ( EmitContext context , ModelDeclaration model , Name supportName ) throws IOException { assert context != null ; assert model != null ; assert supportName != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; DescriptionGenerator . emitImporter ( next , model , supportName ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private Name generateExporter ( EmitContext context , ModelDeclaration model , Name supportName ) throws IOException { assert context != null ; assert model != null ; assert supportName != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_STREAM , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; DescriptionGenerator . emitExporter ( next , model , supportName ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private boolean isTarget ( ModelDeclaration model ) { assert model != null ; CsvSupportTrait trait = model . getTrait ( CsvSupportTrait . class ) ; return trait != null ; } private void checkPropertyType ( ModelDeclaration model ) throws IOException { assert model != null ; for ( PropertyDeclaration prop : model . getDeclaredProperties ( ) ) { if ( isValueField ( prop ) ) { Type type = prop . getType ( ) ; if ( ( type instanceof BasicType ) == false ) { throw new IOException ( MessageFormat . format ( "" , type , prop . getOwner ( ) . getName ( ) . identifier , prop . getName ( ) . identifier ) ) ; } } } } static boolean isValueField ( PropertyDeclaration property ) { assert property != null ; return CsvFieldTrait . getKind ( property , Kind . VALUE ) == Kind . VALUE ; } private static final class SupportGenerator { private static final String NAME_READER = "" ; private static final String NAME_WRITER = "" ; private static final String METHOD_CONFIG = "" ; private static final String FIELD_PATH_NAME = "" ; private final EmitContext context ; private final ModelDeclaration model ; private final Configuration conf ; private final ModelFactory f ; private SupportGenerator ( EmitContext context , ModelDeclaration model , Configuration configuration ) { assert context != null ; assert model != null ; assert configuration != null ; this . context = context ; this . model = model ; this . conf = configuration ; this . f = context . getModelFactory ( ) ; } static void emit ( EmitContext context , ModelDeclaration model , Configuration conf ) throws IOException { assert context != null ; assert model != null ; assert conf != null ; SupportGenerator emitter = new SupportGenerator ( context , model , conf ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . linkType ( context . resolve ( model . getSymbol ( ) ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . toAttributes ( ) , context . getTypeName ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( f . newParameterizedType ( context . resolve ( DataModelStreamSupport . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createGetConfiguration ( ) ) ; results . add ( createGetSupportedType ( ) ) ; results . add ( createCreateReader ( ) ) ; results . add ( createCreateWriter ( ) ) ; results . add ( createReaderClass ( ) ) ; results . add ( createWriterClass ( ) ) ; return results ; } private MethodDeclaration createGetConfiguration ( ) { List < Statement > statements = Lists . create ( ) ; List < Expression > arguments = Lists . create ( ) ; arguments . add ( new TypeBuilder ( f , context . resolve ( Charset . class ) ) . method ( "" , Models . toLiteral ( f , conf . getCharsetName ( ) ) ) . toExpression ( ) ) ; if ( conf . isEnableHeader ( ) ) { SimpleName headers = f . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( ArrayList . class ) ) . parameterize ( context . resolve ( String . class ) ) . newObject ( ) . toLocalVariableDeclaration ( new TypeBuilder ( f , context . resolve ( List . class ) ) . parameterize ( context . resolve ( String . class ) ) . toType ( ) , headers ) ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( isValueField ( property ) ) { String fieldName = CsvFieldTrait . getFieldName ( property ) ; statements . add ( new ExpressionBuilder ( f , headers ) . method ( "" , Models . toLiteral ( f , fieldName ) ) . toStatement ( ) ) ; } } arguments . add ( headers ) ; } else { arguments . add ( new TypeBuilder ( f , context . resolve ( CsvConfiguration . class ) ) . field ( "" ) . toExpression ( ) ) ; } arguments . add ( Models . toLiteral ( f , conf . getTrueFormat ( ) ) ) ; arguments . add ( Models . toLiteral ( f , conf . getFalseFormat ( ) ) ) ; arguments . add ( Models . toLiteral ( f , conf . getDateFormat ( ) ) ) ; arguments . add ( Models . toLiteral ( f , conf . getDateTimeFormat ( ) ) ) ; statements . add ( new TypeBuilder ( f , context . resolve ( CsvConfiguration . class ) ) . newObject ( arguments ) . toReturnStatement ( ) ) ; return f . newMethodDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . returns ( ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Protected ( ) . toAttributes ( ) , context . resolve ( CsvConfiguration . class ) , f . newSimpleName ( METHOD_CONFIG ) , Collections . < FormalParameterDeclaration > emptyList ( ) , statements ) ; } private MethodDeclaration createGetSupportedType ( ) { MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , f . newParameterizedType ( context . resolve ( Class . class ) , context . resolve ( model . getSymbol ( ) ) ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( new Statement [ ] { new TypeBuilder ( f , context . resolve ( model . getSymbol ( ) ) ) . dotClass ( ) . toReturnStatement ( ) } ) ) ; return decl ; } private MethodDeclaration createCreateReader ( ) { SimpleName path = f . newSimpleName ( "" ) ; SimpleName stream = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( createNullCheck ( path ) ) ; statements . add ( createNullCheck ( stream ) ) ; SimpleName parser = f . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( CsvParser . class ) ) . newObject ( stream , path , new ExpressionBuilder ( f , f . newThis ( ) ) . method ( METHOD_CONFIG ) . toExpression ( ) ) . toLocalVariableDeclaration ( context . resolve ( CsvParser . class ) , parser ) ) ; statements . add ( new TypeBuilder ( f , f . newNamedType ( f . newSimpleName ( NAME_READER ) ) ) . newObject ( parser ) . toReturnStatement ( ) ) ; MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( f . newParameterizedType ( context . resolve ( DataModelReader . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( String . class ) , path ) , f . newFormalParameterDeclaration ( context . resolve ( InputStream . class ) , stream ) ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ; return decl ; } private MethodDeclaration createCreateWriter ( ) { SimpleName path = f . newSimpleName ( "" ) ; SimpleName stream = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( createNullCheck ( path ) ) ; statements . add ( createNullCheck ( stream ) ) ; SimpleName emitter = f . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( CsvEmitter . class ) ) . newObject ( stream , path , new ExpressionBuilder ( f , f . newThis ( ) ) . method ( METHOD_CONFIG ) . toExpression ( ) ) . toLocalVariableDeclaration ( context . resolve ( CsvEmitter . class ) , emitter ) ) ; statements . add ( new TypeBuilder ( f , f . newNamedType ( f . newSimpleName ( NAME_WRITER ) ) ) . newObject ( emitter ) . toReturnStatement ( ) ) ; MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( f . newParameterizedType ( context . resolve ( DataModelWriter . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( String . class ) , path ) , f . newFormalParameterDeclaration ( context . resolve ( OutputStream . class ) , stream ) ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ; return decl ; } private Statement createNullCheck ( SimpleName parameter ) { assert parameter != null ; return f . newIfStatement ( new ExpressionBuilder ( f , parameter ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new TypeBuilder ( f , context . resolve ( IllegalArgumentException . class ) ) . newObject ( Models . toLiteral ( f , MessageFormat . format ( "" , parameter . getToken ( ) ) ) ) . toThrowStatement ( ) ) ) ; } private ClassDeclaration createReaderClass ( ) { SimpleName parser = f . newSimpleName ( "" ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createPrivateField ( CsvParser . class , parser ) ) ; List < ExpressionStatement > constructorStatements = Lists . create ( ) ; constructorStatements . add ( mapField ( parser ) ) ; if ( hasFileName ( ) ) { members . add ( createPrivateField ( StringOption . class , f . newSimpleName ( FIELD_PATH_NAME ) ) ) ; constructorStatements . add ( new ExpressionBuilder ( f , f . newSimpleName ( FIELD_PATH_NAME ) ) . assignFrom ( new TypeBuilder ( f , context . resolve ( StringOption . class ) ) . newObject ( new ExpressionBuilder ( f , parser ) . method ( "" ) . toExpression ( ) ) . toExpression ( ) ) . toStatement ( ) ) ; } members . add ( f . newConstructorDeclaration ( null , new AttributeBuilder ( f ) . toAttributes ( ) , f . newSimpleName ( NAME_READER ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( CsvParser . class ) , parser ) ) , constructorStatements ) ) ; SimpleName object = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , parser ) . method ( "" ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , Models . toLiteral ( f , false ) ) . toReturnStatement ( ) ) ) ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { switch ( CsvFieldTrait . getKind ( property , Kind . VALUE ) ) { case VALUE : statements . add ( new ExpressionBuilder ( f , parser ) . method ( "" , new ExpressionBuilder ( f , object ) . method ( context . getOptionGetterName ( property ) ) . toExpression ( ) ) . toStatement ( ) ) ; break ; case FILE_NAME : statements . add ( new ExpressionBuilder ( f , object ) . method ( context . getOptionSetterName ( property ) , f . newSimpleName ( FIELD_PATH_NAME ) ) . toStatement ( ) ) ; break ; case LINE_NUMBER : statements . add ( new ExpressionBuilder ( f , object ) . method ( context . getValueSetterName ( property ) , new ExpressionBuilder ( f , parser ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; break ; case RECORD_NUMBER : statements . add ( new ExpressionBuilder ( f , object ) . method ( context . getValueSetterName ( property ) , new ExpressionBuilder ( f , parser ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; break ; default : break ; } } statements . add ( new ExpressionBuilder ( f , parser ) . method ( "" ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , true ) ) . toReturnStatement ( ) ) ; members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( boolean . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , object ) ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ) ; return f . newClassDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Static ( ) . Final ( ) . toAttributes ( ) , f . newSimpleName ( NAME_READER ) , null , Arrays . asList ( f . newParameterizedType ( context . resolve ( DataModelReader . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , members ) ; } private ClassDeclaration createWriterClass ( ) { SimpleName emitter = f . newSimpleName ( "" ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createPrivateField ( CsvEmitter . class , emitter ) ) ; members . add ( f . newConstructorDeclaration ( null , new AttributeBuilder ( f ) . toAttributes ( ) , f . newSimpleName ( NAME_WRITER ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( CsvEmitter . class ) , emitter ) ) , Arrays . asList ( mapField ( emitter ) ) ) ) ; SimpleName object = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( isValueField ( property ) ) { statements . add ( new ExpressionBuilder ( f , emitter ) . method ( "" , new ExpressionBuilder ( f , object ) . method ( context . getOptionGetterName ( property ) ) . toExpression ( ) ) . toStatement ( ) ) ; } } statements . add ( new ExpressionBuilder ( f , emitter ) . method ( "" ) . toStatement ( ) ) ; members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , object ) ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( statements ) ) ) ; members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , , Arrays . asList ( context . resolve ( IOException . class ) ) , f . newBlock ( new ExpressionBuilder ( f , emitter ) . method ( "" ) . toStatement ( ) ) ) ) ; return f . newClassDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Static ( ) . Final ( ) . toAttributes ( ) , f . newSimpleName ( NAME_WRITER ) , null , Arrays . asList ( f . newParameterizedType ( context . resolve ( DataModelWriter . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , members ) ; } private boolean hasFileName ( ) { for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( CsvFieldTrait . getKind ( property , Kind . VALUE ) == Kind . FILE_NAME ) { return true ; } } return false ; } private ExpressionStatement mapField ( SimpleName name ) { return new ExpressionBuilder ( f , f . newThis ( ) ) . field ( name ) . assignFrom ( name ) . toStatement ( ) ; } private FieldDeclaration createPrivateField ( Class < ? > type , SimpleName name ) { return f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , context . resolve ( type ) , name , null ) ; } } private static final class DescriptionGenerator { private static final String IMPORTER_TYPE_NAME = "" ; private static final String EXPORTER_TYPE_NAME = "" ; private final EmitContext context ; private final ModelDeclaration model ; private final com . asakusafw . utils . java . model . syntax . Type supportClass ; private final ModelFactory f ; private final boolean importer ; private DescriptionGenerator ( EmitContext context , ModelDeclaration model , Name supportClassName , boolean importer ) { assert context != null ; assert model != null ; assert supportClassName != null ; this . context = context ; this . model = model ; this . f = context . getModelFactory ( ) ; this . importer = importer ; this . supportClass = context . resolve ( supportClassName ) ; } static void emitImporter ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; assert supportClassName != null ; DescriptionGenerator emitter = new DescriptionGenerator ( context , model , supportClassName , true ) ; emitter . emit ( ) ; } static void emitExporter ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; assert supportClassName != null ; DescriptionGenerator emitter = new DescriptionGenerator ( context , model , supportClassName , false ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . linkType ( context . resolve ( model . getSymbol ( ) ) ) . text ( "" , importer ? "" : "" ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Abstract ( ) . toAttributes ( ) , context . getTypeName ( ) , context . resolve ( Models . toName ( f , importer ? IMPORTER_TYPE_NAME : EXPORTER_TYPE_NAME ) ) , Collections . < com . asakusafw . utils . java . model . syntax . Type > emptyList ( ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createGetModelType ( ) ) ; results . add ( createGetStreamSupport ( ) ) ; return results ; } private MethodDeclaration createGetModelType ( ) { return createGetter ( new TypeBuilder ( f , context . resolve ( Class . class ) ) . parameterize ( f . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , context . resolve ( model . getSymbol ( ) ) ) ) . toType ( ) , "" , f . newClassLiteral ( context . resolve ( model . getSymbol ( ) ) ) ) ; } private MethodDeclaration createGetStreamSupport ( ) { return createGetter ( new TypeBuilder ( f , context . resolve ( Class . class ) ) . parameterize ( supportClass ) . toType ( ) , "" , f . newClassLiteral ( supportClass ) ) ; } private MethodDeclaration createGetter ( com . asakusafw . utils . java . model . syntax . Type type , String name , Expression value ) { assert type != null ; assert name != null ; assert value != null ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , type , f . newSimpleName ( name ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( new ExpressionBuilder ( f , value ) . toReturnStatement ( ) ) ) ; } } } package com . asakusafw . dmdl . windgate . csv . driver ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . dmdl . windgate . csv . driver . CsvFieldTrait . Kind ; public class CsvLineNumberDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , attribute . elements ) ) ; CsvFieldDriver . checkFieldType ( environment , declaration , attribute , BasicTypeKind . INT , BasicTypeKind . LONG ) ; if ( CsvFieldDriver . checkConflict ( environment , declaration , attribute ) ) { declaration . putTrait ( CsvFieldTrait . class , new CsvFieldTrait ( attribute , Kind . LINE_NUMBER , null ) ) ; } } } package com . asakusafw . dmdl . windgate . csv . driver ; import java . text . SimpleDateFormat ; import java . util . Map ; import com . asakusafw . dmdl . Diagnostic ; import com . asakusafw . dmdl . Diagnostic . Level ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . model . AstLiteral ; import com . asakusafw . dmdl . model . LiteralKind ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . spi . ModelAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; import com . asakusafw . dmdl . windgate . csv . driver . CsvSupportTrait . Configuration ; import com . asakusafw . runtime . io . csv . CsvConfiguration ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; public class CsvSupportDriver extends ModelAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_CHARSET_NAME = "" ; public static final String ELEMENT_HAS_HEADER_NAME = "" ; public static final String ELEMENT_TRUE_NAME = "" ; public static final String ELEMENT_FALSE_NAME = "" ; public static final String ELEMENT_DATE_NAME = "" ; public static final String ELEMENT_DATE_TIME_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; Configuration conf = analyzeConfig ( environment , attribute , elements ) ; if ( conf != null ) { declaration . putTrait ( CsvSupportTrait . class , new CsvSupportTrait ( attribute , conf ) ) ; } } private Configuration analyzeConfig ( DmdlSemantics environment , AstAttribute attribute , Map < String , AstAttributeElement > elements ) { AstLiteral charset = take ( environment , elements , ELEMENT_CHARSET_NAME , LiteralKind . STRING ) ; AstLiteral header = take ( environment , elements , ELEMENT_HAS_HEADER_NAME , LiteralKind . BOOLEAN ) ; AstLiteral trueRep = take ( environment , elements , ELEMENT_TRUE_NAME , LiteralKind . STRING ) ; AstLiteral falseRep = take ( environment , elements , ELEMENT_FALSE_NAME , LiteralKind . STRING ) ; AstLiteral dateFormat = take ( environment , elements , ELEMENT_DATE_NAME , LiteralKind . STRING ) ; AstLiteral dateTimeFormat = take ( environment , elements , ELEMENT_DATE_TIME_NAME , LiteralKind . STRING ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; Configuration result = new Configuration ( ) ; if ( charset != null && checkNotEmpty ( environment , ELEMENT_CHARSET_NAME , charset ) ) { result . setCharsetName ( charset . toStringValue ( ) ) ; } if ( header != null ) { result . setEnableHeader ( header . toBooleanValue ( ) ) ; } if ( trueRep != null && checkNotEmpty ( environment , ELEMENT_TRUE_NAME , trueRep ) ) { result . setTrueFormat ( trueRep . toStringValue ( ) ) ; } if ( falseRep != null && checkNotEmpty ( environment , ELEMENT_FALSE_NAME , falseRep ) ) { result . setFalseFormat ( falseRep . toStringValue ( ) ) ; } if ( dateFormat != null && checkDateFormat ( environment , ELEMENT_DATE_NAME , dateFormat ) ) { result . setDateFormat ( dateFormat . toStringValue ( ) ) ; } if ( dateTimeFormat != null && checkDateFormat ( environment , ELEMENT_DATE_TIME_NAME , dateTimeFormat ) ) { result . setDateTimeFormat ( dateTimeFormat . toStringValue ( ) ) ; } return result ; } private boolean checkNotEmpty ( DmdlSemantics environment , String name , AstLiteral stringLiteral ) { assert environment != null ; assert name != null ; assert stringLiteral != null ; assert stringLiteral . kind == LiteralKind . STRING ; if ( stringLiteral . toStringValue ( ) . isEmpty ( ) ) { environment . report ( new Diagnostic ( Level . ERROR , stringLiteral , "" , TARGET_NAME , name ) ) ; return false ; } return true ; } private boolean checkDateFormat ( DmdlSemantics environment , String name , AstLiteral stringLiteral ) { assert environment != null ; assert name != null ; assert stringLiteral != null ; assert stringLiteral . kind == LiteralKind . STRING ; if ( checkNotEmpty ( environment , name , stringLiteral ) == false ) { return false ; } try { SimpleDateFormat format = new SimpleDateFormat ( stringLiteral . toStringValue ( ) ) ; format . format ( new java . util . Date ( ) ) ; } catch ( IllegalArgumentException e ) { environment . report ( new Diagnostic ( Level . ERROR , stringLiteral , "" , TARGET_NAME , name ) ) ; return false ; } return true ; } private AstLiteral take ( DmdlSemantics environment , Map < String , AstAttributeElement > elements , String elementName , LiteralKind kind ) { assert environment != null ; assert elements != null ; assert elementName != null ; assert kind != null ; AstAttributeElement element = elements . remove ( elementName ) ; if ( element == null ) { return null ; } else if ( ( element . value instanceof AstLiteral ) == false ) { environment . report ( new Diagnostic ( Level . ERROR , element , "" , TARGET_NAME , elementName ) ) ; return null ; } else { AstLiteral literal = ( AstLiteral ) element . value ; if ( literal . kind != kind ) { environment . report ( new Diagnostic ( Level . ERROR , element , "" , TARGET_NAME , elementName ) ) ; return null ; } return literal ; } } } package com . asakusafw . dmdl . windgate . csv . driver ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . Trait ; public class CsvFieldTrait implements Trait < CsvFieldTrait > { private final AstNode originalAst ; private final Kind kind ; private final String name ; public CsvFieldTrait ( AstNode originalAst , Kind kind , String name ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . kind = kind ; this . name = name ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public static Kind getKind ( PropertyDeclaration property , Kind defaultKind ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } CsvFieldTrait trait = property . getTrait ( CsvFieldTrait . class ) ; if ( trait != null ) { return trait . kind ; } return defaultKind ; } public static String getFieldName ( PropertyDeclaration property ) { if ( property == null ) { throw new IllegalArgumentException ( "" ) ; } CsvFieldTrait trait = property . getTrait ( CsvFieldTrait . class ) ; if ( trait != null && trait . name != null ) { return trait . name ; } return property . getName ( ) . identifier ; } public enum Kind { VALUE , FILE_NAME , LINE_NUMBER , RECORD_NUMBER , IGNORE , } } package com . asakusafw . dmdl . windgate . jdbc . driver ; import java . util . Map ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class JdbcColumnDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; String value = AttributeUtil . takeString ( environment , attribute , elements , ELEMENT_NAME , true ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; if ( value != null ) { declaration . putTrait ( JdbcColumnTrait . class , new JdbcColumnTrait ( attribute , value ) ) ; } } } package com . asakusafw . dmdl . windgate . jdbc . driver ; import java . util . Map ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . spi . ModelAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class JdbcTableDriver extends ModelAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , ModelDeclaration declaration , AstAttribute attribute ) { Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; String name = AttributeUtil . takeString ( environment , attribute , elements , ELEMENT_NAME , true ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; if ( name != null ) { declaration . putTrait ( JdbcTableTrait . class , new JdbcTableTrait ( attribute , name ) ) ; } } } package com . asakusafw . dmdl . windgate . jdbc . driver ; package com . asakusafw . dmdl . windgate . jdbc . driver ; import java . io . IOException ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Types ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Calendar ; import java . util . Collections ; import java . util . EnumSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . TreeMap ; import org . apache . hadoop . io . Text ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . dmdl . java . emitter . EmitContext ; import com . asakusafw . dmdl . java . spi . JavaDataModelDriver ; import com . asakusafw . dmdl . model . BasicTypeKind ; import com . asakusafw . dmdl . semantics . ModelDeclaration ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . semantics . Type ; import com . asakusafw . dmdl . semantics . type . BasicType ; import com . asakusafw . runtime . value . Date ; import com . asakusafw . runtime . value . DateTime ; import com . asakusafw . runtime . value . DateUtil ; import com . asakusafw . utils . collections . Lists ; import com . asakusafw . utils . collections . Maps ; import com . asakusafw . utils . java . model . syntax . ClassDeclaration ; import com . asakusafw . utils . java . model . syntax . Expression ; import com . asakusafw . utils . java . model . syntax . ExpressionStatement ; import com . asakusafw . utils . java . model . syntax . FieldDeclaration ; import com . asakusafw . utils . java . model . syntax . FormalParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . InfixOperator ; import com . asakusafw . utils . java . model . syntax . MethodDeclaration ; import com . asakusafw . utils . java . model . syntax . ModelFactory ; import com . asakusafw . utils . java . model . syntax . Name ; import com . asakusafw . utils . java . model . syntax . PostfixOperator ; import com . asakusafw . utils . java . model . syntax . SimpleName ; import com . asakusafw . utils . java . model . syntax . Statement ; import com . asakusafw . utils . java . model . syntax . TypeBodyDeclaration ; import com . asakusafw . utils . java . model . syntax . TypeParameterDeclaration ; import com . asakusafw . utils . java . model . syntax . WildcardBoundKind ; import com . asakusafw . utils . java . model . util . AttributeBuilder ; import com . asakusafw . utils . java . model . util . ExpressionBuilder ; import com . asakusafw . utils . java . model . util . JavadocBuilder ; import com . asakusafw . utils . java . model . util . Models ; import com . asakusafw . utils . java . model . util . TypeBuilder ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport . DataModelPreparedStatement ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport . DataModelResultSet ; public class JdbcSupportEmitter extends JavaDataModelDriver { static final Logger LOG = LoggerFactory . getLogger ( JdbcSupportEmitter . class ) ; public static final String CATEGORY_JDBC = "" ; @ Override public void generateResources ( EmitContext context , ModelDeclaration model ) throws IOException { if ( isTarget ( model ) == false ) { return ; } checkColumnExists ( model ) ; checkColumnType ( model ) ; checkColumnConflict ( model ) ; Name supportClassName = generateSupport ( context , model ) ; if ( hasTableTrait ( model ) ) { generateImporterDescription ( context , model , supportClassName ) ; generateExporterDescription ( context , model , supportClassName ) ; } } private Name generateSupport ( EmitContext context , ModelDeclaration model ) throws IOException { assert context != null ; assert model != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_JDBC , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; SupportGenerator . emit ( next , model ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; return next . getQualifiedTypeName ( ) ; } private void generateImporterDescription ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_JDBC , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; DescriptionGenerator . emitImporter ( next , model , supportClassName ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; } private void generateExporterDescription ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; EmitContext next = new EmitContext ( context . getSemantics ( ) , context . getConfiguration ( ) , model , CATEGORY_JDBC , "" ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) ) ; DescriptionGenerator . emitExporter ( next , model , supportClassName ) ; LOG . debug ( "" , context . getQualifiedTypeName ( ) . toNameString ( ) , next . getQualifiedTypeName ( ) . toNameString ( ) ) ; } private boolean isTarget ( ModelDeclaration model ) { assert model != null ; return hasTableTrait ( model ) || hasColumnTrait ( model ) ; } private boolean hasTableTrait ( ModelDeclaration model ) { assert model != null ; return model . getTrait ( JdbcTableTrait . class ) != null ; } private boolean hasColumnTrait ( ModelDeclaration model ) { assert model != null ; boolean sawTrait = false ; for ( PropertyDeclaration prop : model . getDeclaredProperties ( ) ) { if ( prop . getTrait ( JdbcColumnTrait . class ) != null ) { sawTrait = true ; } } return sawTrait ; } private void checkColumnExists ( ModelDeclaration model ) throws IOException { assert model != null ; if ( hasColumnTrait ( model ) == false ) { throw new IOException ( MessageFormat . format ( "" , model . getName ( ) . identifier , JdbcColumnDriver . TARGET_NAME ) ) ; } } private void checkColumnType ( ModelDeclaration model ) throws IOException { assert model != null ; for ( PropertyDeclaration prop : model . getDeclaredProperties ( ) ) { if ( model . getTrait ( JdbcColumnTrait . class ) == null ) { continue ; } Type type = prop . getType ( ) ; if ( ( type instanceof BasicType ) == false ) { throw new IOException ( MessageFormat . format ( "" , type , model . getName ( ) . identifier , prop . getName ( ) . identifier ) ) ; } } } private void checkColumnConflict ( ModelDeclaration model ) throws IOException { assert model != null ; Map < String , PropertyDeclaration > saw = Maps . create ( ) ; for ( PropertyDeclaration prop : model . getDeclaredProperties ( ) ) { JdbcColumnTrait trait = prop . getTrait ( JdbcColumnTrait . class ) ; if ( trait == null ) { continue ; } String name = trait . getName ( ) ; if ( saw . containsKey ( name ) ) { PropertyDeclaration other = saw . get ( name ) ; throw new IOException ( MessageFormat . format ( "" , name , model . getName ( ) . identifier , prop . getName ( ) . identifier , other . getName ( ) . identifier ) ) ; } saw . put ( name , prop ) ; } } private static final class SupportGenerator { private static final String NAME_CALENDAR = "" ; private static final String NAME_DATETIME = "" ; private static final String NAME_DATE = "" ; private static final String NAME_TEXT = "" ; private static final String NAME_RESULT_SET_SUPPORT = "" ; private static final String NAME_PREPARED_STATEMENT_SUPPORT = "" ; private static final String NAME_PROPERTY_POSITIONS = "" ; private static final String NAME_CREATE_VECTOR = "" ; private final EmitContext context ; private final ModelDeclaration model ; private final ModelFactory f ; private SupportGenerator ( EmitContext context , ModelDeclaration model ) { assert context != null ; assert model != null ; this . context = context ; this . model = model ; this . f = context . getModelFactory ( ) ; } static void emit ( EmitContext context , ModelDeclaration model ) throws IOException { assert context != null ; assert model != null ; SupportGenerator emitter = new SupportGenerator ( context , model ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" , model . getName ( ) ) . linkType ( context . resolve ( model . getSymbol ( ) ) ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Final ( ) . toAttributes ( ) , context . getTypeName ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , null , Collections . singletonList ( f . newParameterizedType ( context . resolve ( DataModelJdbcSupport . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . addAll ( createMetaData ( ) ) ; results . add ( createGetSupportedType ( ) ) ; results . add ( createIsSupported ( ) ) ; results . add ( createCreateResultSetSupport ( ) ) ; results . add ( createCreatePreparedStatementSupport ( ) ) ; results . add ( createCreatePropertyVector ( ) ) ; results . add ( createResultSetSupportClass ( ) ) ; results . add ( createPreparedStatementSupportClass ( ) ) ; return results ; } private List < TypeBodyDeclaration > createMetaData ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Static ( ) . Final ( ) . toAttributes ( ) , f . newParameterizedType ( context . resolve ( Map . class ) , context . resolve ( String . class ) , context . resolve ( Integer . class ) ) , f . newSimpleName ( NAME_PROPERTY_POSITIONS ) , null ) ) ; List < Statement > statements = Lists . create ( ) ; SimpleName map = f . newSimpleName ( "" ) ; statements . add ( new TypeBuilder ( f , context . resolve ( TreeMap . class ) ) . parameterize ( context . resolve ( String . class ) , context . resolve ( Integer . class ) ) . newObject ( ) . toLocalVariableDeclaration ( f . newParameterizedType ( context . resolve ( Map . class ) , context . resolve ( String . class ) , context . resolve ( Integer . class ) ) , map ) ) ; List < PropertyDeclaration > properties = getProperties ( ) ; for ( int i = , n = properties . size ( ) ; i < n ; i ++ ) { PropertyDeclaration property = properties . get ( i ) ; JdbcColumnTrait trait = property . getTrait ( JdbcColumnTrait . class ) ; assert trait != null ; statements . add ( new ExpressionBuilder ( f , map ) . method ( "" , Models . toLiteral ( f , trait . getName ( ) ) , Models . toLiteral ( f , i ) ) . toStatement ( ) ) ; } statements . add ( new ExpressionBuilder ( f , f . newSimpleName ( NAME_PROPERTY_POSITIONS ) ) . assignFrom ( map ) . toStatement ( ) ) ; results . add ( f . newInitializerDeclaration ( null , new AttributeBuilder ( f ) . Static ( ) . toAttributes ( ) , f . newBlock ( statements ) ) ) ; return results ; } private MethodDeclaration createGetSupportedType ( ) { MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , f . newParameterizedType ( context . resolve ( Class . class ) , context . resolve ( model . getSymbol ( ) ) ) , f . newSimpleName ( "" ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( new Statement [ ] { new TypeBuilder ( f , context . resolve ( model . getSymbol ( ) ) ) . dotClass ( ) . toReturnStatement ( ) } ) ) ; return decl ; } private MethodDeclaration createIsSupported ( ) { SimpleName columnNames = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( createNullCheck ( columnNames ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , columnNames ) . method ( "" ) . toExpression ( ) , f . newBlock ( f . newReturnStatement ( Models . toLiteral ( f , false ) ) ) ) ) ; statements . add ( f . newTryStatement ( f . newBlock ( new ExpressionBuilder ( f , f . newThis ( ) ) . method ( NAME_CREATE_VECTOR , columnNames ) . toStatement ( ) , new ExpressionBuilder ( f , Models . toLiteral ( f , true ) ) . toReturnStatement ( ) ) , Arrays . asList ( f . newCatchClause ( f . newFormalParameterDeclaration ( context . resolve ( IllegalArgumentException . class ) , f . newSimpleName ( "" ) ) , f . newBlock ( new ExpressionBuilder ( f , Models . toLiteral ( f , false ) ) . toReturnStatement ( ) ) ) ) , null ) ) ; MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( boolean . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( f . newParameterizedType ( context . resolve ( List . class ) , context . resolve ( String . class ) ) , columnNames ) ) , statements ) ; return decl ; } private MethodDeclaration createCreateResultSetSupport ( ) { SimpleName resultSet = f . newSimpleName ( "" ) ; SimpleName columnNames = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( createNullCheck ( resultSet ) ) ; statements . add ( createNullCheck ( columnNames ) ) ; SimpleName vector = f . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( f , f . newThis ( ) ) . method ( NAME_CREATE_VECTOR , columnNames ) . toLocalVariableDeclaration ( context . resolve ( int [ ] . class ) , vector ) ) ; statements . add ( new TypeBuilder ( f , f . newNamedType ( f . newSimpleName ( NAME_RESULT_SET_SUPPORT ) ) ) . newObject ( resultSet , vector ) . toReturnStatement ( ) ) ; MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( f . newParameterizedType ( context . resolve ( DataModelResultSet . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( ResultSet . class ) , resultSet ) , f . newFormalParameterDeclaration ( f . newParameterizedType ( context . resolve ( List . class ) , context . resolve ( String . class ) ) , columnNames ) ) , statements ) ; return decl ; } private MethodDeclaration createCreatePreparedStatementSupport ( ) { SimpleName preparedStatement = f . newSimpleName ( "" ) ; SimpleName columnNames = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( createNullCheck ( preparedStatement ) ) ; statements . add ( createNullCheck ( columnNames ) ) ; SimpleName vector = f . newSimpleName ( "" ) ; statements . add ( new ExpressionBuilder ( f , f . newThis ( ) ) . method ( NAME_CREATE_VECTOR , columnNames ) . toLocalVariableDeclaration ( context . resolve ( int [ ] . class ) , vector ) ) ; statements . add ( new TypeBuilder ( f , f . newNamedType ( f . newSimpleName ( NAME_PREPARED_STATEMENT_SUPPORT ) ) ) . newObject ( preparedStatement , vector ) . toReturnStatement ( ) ) ; MethodDeclaration decl = f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , context . resolve ( f . newParameterizedType ( context . resolve ( DataModelPreparedStatement . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( PreparedStatement . class ) , preparedStatement ) , f . newFormalParameterDeclaration ( f . newParameterizedType ( context . resolve ( List . class ) , context . resolve ( String . class ) ) , columnNames ) ) , statements ) ; return decl ; } private Statement createNullCheck ( SimpleName parameter ) { assert parameter != null ; return f . newIfStatement ( new ExpressionBuilder ( f , parameter ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new TypeBuilder ( f , context . resolve ( IllegalArgumentException . class ) ) . newObject ( Models . toLiteral ( f , MessageFormat . format ( "" , parameter . getToken ( ) ) ) ) . toThrowStatement ( ) ) ) ; } private MethodDeclaration createCreatePropertyVector ( ) { SimpleName columnNames = f . newSimpleName ( "" ) ; SimpleName vector = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( new TypeBuilder ( f , context . resolve ( int [ ] . class ) ) . newArray ( new ExpressionBuilder ( f , f . newSimpleName ( NAME_PROPERTY_POSITIONS ) ) . method ( "" ) . toExpression ( ) ) . toLocalVariableDeclaration ( context . resolve ( int [ ] . class ) , vector ) ) ; SimpleName index = f . newSimpleName ( "" ) ; SimpleName column = f . newSimpleName ( "" ) ; SimpleName position = f . newSimpleName ( "" ) ; statements . add ( f . newForStatement ( f . newLocalVariableDeclaration ( new AttributeBuilder ( f ) . toAttributes ( ) , context . resolve ( int . class ) , Arrays . asList ( f . newVariableDeclarator ( index , Models . toLiteral ( f , ) ) , f . newVariableDeclarator ( f . newSimpleName ( "" ) , new ExpressionBuilder ( f , columnNames ) . method ( "" ) . toExpression ( ) ) ) ) , new ExpressionBuilder ( f , index ) . apply ( InfixOperator . LESS , f . newSimpleName ( "" ) ) . toExpression ( ) , f . newStatementExpressionList ( new ExpressionBuilder ( f , index ) . apply ( PostfixOperator . INCREMENT ) . toExpression ( ) ) , f . newBlock ( new Statement [ ] { new ExpressionBuilder ( f , columnNames ) . method ( "" , index ) . toLocalVariableDeclaration ( context . resolve ( String . class ) , column ) , new ExpressionBuilder ( f , f . newSimpleName ( NAME_PROPERTY_POSITIONS ) ) . method ( "" , column ) . toLocalVariableDeclaration ( context . resolve ( Integer . class ) , position ) , f . newIfStatement ( new ExpressionBuilder ( f , position ) . apply ( InfixOperator . EQUALS , Models . toNullLiteral ( f ) ) . apply ( InfixOperator . CONDITIONAL_OR , new ExpressionBuilder ( f , vector ) . array ( position ) . apply ( InfixOperator . NOT_EQUALS , Models . toLiteral ( f , ) ) . toExpression ( ) ) . toExpression ( ) , f . newBlock ( new TypeBuilder ( f , context . resolve ( IllegalArgumentException . class ) ) . newObject ( column ) . toThrowStatement ( ) ) ) , new ExpressionBuilder ( f , vector ) . array ( position ) . assignFrom ( new ExpressionBuilder ( f , index ) . apply ( InfixOperator . PLUS , Models . toLiteral ( f , ) ) . toExpression ( ) ) . toStatement ( ) } ) ) ) ; statements . add ( new ExpressionBuilder ( f , vector ) . toReturnStatement ( ) ) ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . toAttributes ( ) , context . resolve ( context . resolve ( int [ ] . class ) ) , f . newSimpleName ( NAME_CREATE_VECTOR ) , Arrays . asList ( f . newFormalParameterDeclaration ( f . newParameterizedType ( context . resolve ( List . class ) , context . resolve ( String . class ) ) , columnNames ) ) , statements ) ; } private ClassDeclaration createResultSetSupportClass ( ) { SimpleName resultSet = f . newSimpleName ( "" ) ; SimpleName properties = f . newSimpleName ( "" ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createPrivateField ( ResultSet . class , resultSet , false ) ) ; members . add ( createPrivateField ( int [ ] . class , properties , false ) ) ; Set < BasicTypeKind > kinds = collectTypeKinds ( ) ; if ( kinds . contains ( BasicTypeKind . TEXT ) ) { members . add ( createPrivateField ( Text . class , f . newSimpleName ( NAME_TEXT ) , true ) ) ; } if ( kinds . contains ( BasicTypeKind . DATE ) ) { members . add ( createPrivateField ( Date . class , f . newSimpleName ( NAME_DATE ) , true ) ) ; } if ( kinds . contains ( BasicTypeKind . DATETIME ) ) { members . add ( createPrivateField ( DateTime . class , f . newSimpleName ( NAME_DATETIME ) , true ) ) ; } if ( kinds . contains ( BasicTypeKind . DATE ) || kinds . contains ( BasicTypeKind . DATETIME ) ) { members . add ( createCalendarBuffer ( ) ) ; } members . add ( f . newConstructorDeclaration ( null , new AttributeBuilder ( f ) . toAttributes ( ) , f . newSimpleName ( NAME_RESULT_SET_SUPPORT ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( ResultSet . class ) , resultSet ) , f . newFormalParameterDeclaration ( context . resolve ( int [ ] . class ) , properties ) ) , Arrays . asList ( mapField ( resultSet ) , mapField ( properties ) ) ) ) ; SimpleName object = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , resultSet ) . method ( "" ) . apply ( InfixOperator . EQUALS , Models . toLiteral ( f , false ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , Models . toLiteral ( f , false ) ) . toReturnStatement ( ) ) ) ) ; List < PropertyDeclaration > declared = getProperties ( ) ; for ( int i = , n = declared . size ( ) ; i < n ; i ++ ) { statements . add ( createResultSetSupportStatement ( object , resultSet , f . newArrayAccessExpression ( properties , Models . toLiteral ( f , i ) ) , declared . get ( i ) ) ) ; } statements . add ( new ExpressionBuilder ( f , Models . toLiteral ( f , true ) ) . toReturnStatement ( ) ) ; members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( boolean . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , object ) ) , , Arrays . asList ( context . resolve ( SQLException . class ) ) , f . newBlock ( statements ) ) ) ; return f . newClassDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Static ( ) . Final ( ) . toAttributes ( ) , f . newSimpleName ( NAME_RESULT_SET_SUPPORT ) , null , Arrays . asList ( f . newParameterizedType ( context . resolve ( DataModelResultSet . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , members ) ; } private Set < BasicTypeKind > collectTypeKinds ( ) { EnumSet < BasicTypeKind > kinds = EnumSet . noneOf ( BasicTypeKind . class ) ; for ( PropertyDeclaration prop : getProperties ( ) ) { kinds . add ( toBasicKind ( prop . getType ( ) ) ) ; } return kinds ; } private FieldDeclaration createCalendarBuffer ( ) { return f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , context . resolve ( Calendar . class ) , f . newSimpleName ( NAME_CALENDAR ) , new TypeBuilder ( f , context . resolve ( Calendar . class ) ) . method ( "" ) . toExpression ( ) ) ; } private ClassDeclaration createPreparedStatementSupportClass ( ) { SimpleName preparedStatement = f . newSimpleName ( "" ) ; SimpleName properties = f . newSimpleName ( "" ) ; List < TypeBodyDeclaration > members = Lists . create ( ) ; members . add ( createPrivateField ( PreparedStatement . class , preparedStatement , false ) ) ; members . add ( createPrivateField ( int [ ] . class , properties , false ) ) ; Set < BasicTypeKind > kinds = collectTypeKinds ( ) ; if ( kinds . contains ( BasicTypeKind . DATE ) ) { members . add ( f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , context . resolve ( java . sql . Date . class ) , f . newSimpleName ( NAME_DATE ) , new TypeBuilder ( f , context . resolve ( java . sql . Date . class ) ) . newObject ( Models . toLiteral ( f , ) ) . toExpression ( ) ) ) ; } if ( kinds . contains ( BasicTypeKind . DATETIME ) ) { members . add ( f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , context . resolve ( java . sql . Timestamp . class ) , f . newSimpleName ( NAME_DATETIME ) , new TypeBuilder ( f , context . resolve ( java . sql . Timestamp . class ) ) . newObject ( Models . toLiteral ( f , ) ) . toExpression ( ) ) ) ; } if ( kinds . contains ( BasicTypeKind . DATE ) || kinds . contains ( BasicTypeKind . DATETIME ) ) { members . add ( createCalendarBuffer ( ) ) ; } members . add ( f . newConstructorDeclaration ( null , new AttributeBuilder ( f ) . toAttributes ( ) , f . newSimpleName ( NAME_PREPARED_STATEMENT_SUPPORT ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( PreparedStatement . class ) , preparedStatement ) , f . newFormalParameterDeclaration ( context . resolve ( int [ ] . class ) , properties ) ) , Arrays . asList ( mapField ( preparedStatement ) , mapField ( properties ) ) ) ) ; SimpleName object = f . newSimpleName ( "" ) ; List < Statement > statements = Lists . create ( ) ; List < PropertyDeclaration > declared = getProperties ( ) ; for ( int i = , n = declared . size ( ) ; i < n ; i ++ ) { statements . add ( createPreparedStatementSupportStatement ( object , preparedStatement , f . newArrayAccessExpression ( properties , Models . toLiteral ( f , i ) ) , declared . get ( i ) ) ) ; } members . add ( f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , Collections . < TypeParameterDeclaration > emptyList ( ) , context . resolve ( void . class ) , f . newSimpleName ( "" ) , Arrays . asList ( f . newFormalParameterDeclaration ( context . resolve ( model . getSymbol ( ) ) , object ) ) , , Arrays . asList ( context . resolve ( SQLException . class ) ) , f . newBlock ( statements ) ) ) ; return f . newClassDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Static ( ) . Final ( ) . toAttributes ( ) , f . newSimpleName ( NAME_PREPARED_STATEMENT_SUPPORT ) , null , Arrays . asList ( f . newParameterizedType ( context . resolve ( DataModelPreparedStatement . class ) , context . resolve ( model . getSymbol ( ) ) ) ) , members ) ; } private Statement createResultSetSupportStatement ( Expression object , Expression resultSet , Expression position , PropertyDeclaration property ) { List < Statement > statements = Lists . create ( ) ; SimpleName value = f . newSimpleName ( "" ) ; SimpleName calendar = f . newSimpleName ( NAME_CALENDAR ) ; SimpleName text = f . newSimpleName ( NAME_TEXT ) ; SimpleName date = f . newSimpleName ( NAME_DATE ) ; SimpleName datetime = f . newSimpleName ( NAME_DATETIME ) ; BasicTypeKind kind = toBasicKind ( property . getType ( ) ) ; switch ( kind ) { case INT : statements . add ( createResultSetMapping ( object , resultSet , position , property , "" ) ) ; statements . add ( createResultSetNullMapping ( object , resultSet , property ) ) ; break ; case LONG : statements . add ( createResultSetMapping ( object , resultSet , position , property , "" ) ) ; statements . add ( createResultSetNullMapping ( object , resultSet , property ) ) ; break ; case FLOAT : statements . add ( createResultSetMapping ( object , resultSet , position , property , "" ) ) ; statements . add ( createResultSetNullMapping ( object , resultSet , property ) ) ; break ; case DOUBLE : statements . add ( createResultSetMapping ( object , resultSet , position , property , "" ) ) ; statements . add ( createResultSetNullMapping ( object , resultSet , property ) ) ; break ; case BYTE : statements . add ( createResultSetMapping ( object , resultSet , position , property , "" ) ) ; statements . add ( createResultSetNullMapping ( object , resultSet , property ) ) ; break ; case SHORT : statements . add ( createResultSetMapping ( object , resultSet , position , property , "" ) ) ; statements . add ( createResultSetNullMapping ( object , resultSet , property ) ) ; break ; case BOOLEAN : statements . add ( createResultSetMapping ( object , resultSet , position , property , "" ) ) ; statements . add ( createResultSetNullMapping ( object , resultSet , property ) ) ; break ; case DECIMAL : statements . add ( createResultSetMapping ( object , resultSet , position , property , "" ) ) ; break ; case TEXT : statements . add ( new ExpressionBuilder ( f , resultSet ) . method ( "" , position ) . toLocalVariableDeclaration ( context . resolve ( String . class ) , value ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , value ) . apply ( InfixOperator . NOT_EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , text ) . method ( "" , value ) . toStatement ( ) , new ExpressionBuilder ( f , object ) . method ( context . getValueSetterName ( property ) , text ) . toStatement ( ) ) , f . newBlock ( setNullToProperty ( object , property ) ) ) ) ; break ; case DATE : statements . add ( new ExpressionBuilder ( f , resultSet ) . method ( "" , position , calendar ) . toLocalVariableDeclaration ( context . resolve ( java . sql . Date . class ) , value ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , value ) . apply ( InfixOperator . NOT_EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , calendar ) . method ( "" , value ) . toStatement ( ) , new ExpressionBuilder ( f , date ) . method ( "" , new TypeBuilder ( f , context . resolve ( DateUtil . class ) ) . method ( "" , calendar ) . toExpression ( ) ) . toStatement ( ) , new ExpressionBuilder ( f , object ) . method ( context . getValueSetterName ( property ) , date ) . toStatement ( ) ) , f . newBlock ( setNullToProperty ( object , property ) ) ) ) ; break ; case DATETIME : statements . add ( new ExpressionBuilder ( f , resultSet ) . method ( "" , position , calendar ) . toLocalVariableDeclaration ( context . resolve ( java . sql . Timestamp . class ) , value ) ) ; statements . add ( f . newIfStatement ( new ExpressionBuilder ( f , value ) . apply ( InfixOperator . NOT_EQUALS , Models . toNullLiteral ( f ) ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , calendar ) . method ( "" , value ) . toStatement ( ) , new ExpressionBuilder ( f , datetime ) . method ( "" , new TypeBuilder ( f , context . resolve ( DateUtil . class ) ) . method ( "" , calendar ) . toExpression ( ) ) . toStatement ( ) , new ExpressionBuilder ( f , object ) . method ( context . getValueSetterName ( property ) , datetime ) . toStatement ( ) ) , f . newBlock ( setNullToProperty ( object , property ) ) ) ) ; break ; default : throw new AssertionError ( kind ) ; } return f . newIfStatement ( new ExpressionBuilder ( f , position ) . apply ( InfixOperator . NOT_EQUALS , Models . toLiteral ( f , ) ) . toExpression ( ) , f . newBlock ( statements ) ) ; } private Statement createResultSetNullMapping ( Expression object , Expression resultSet , PropertyDeclaration property ) { return f . newIfStatement ( new ExpressionBuilder ( f , resultSet ) . method ( "" ) . toExpression ( ) , f . newBlock ( setNullToProperty ( object , property ) ) ) ; } private ExpressionStatement setNullToProperty ( Expression object , PropertyDeclaration property ) { assert object != null ; assert property != null ; return new ExpressionBuilder ( f , object ) . method ( context . getOptionSetterName ( property ) , Models . toNullLiteral ( f ) ) . toStatement ( ) ; } private Statement createPreparedStatementSupportStatement ( Expression object , Expression statement , Expression position , PropertyDeclaration property ) { assert object != null ; assert statement != null ; assert position != null ; assert property != null ; return f . newIfStatement ( new ExpressionBuilder ( f , position ) . apply ( InfixOperator . NOT_EQUALS , Models . toLiteral ( f , ) ) . toExpression ( ) , f . newBlock ( f . newIfStatement ( new ExpressionBuilder ( f , object ) . method ( context . getOptionGetterName ( property ) ) . method ( "" ) . toExpression ( ) , f . newBlock ( new ExpressionBuilder ( f , statement ) . method ( "" , position , createNullType ( property ) ) . toStatement ( ) ) , f . newBlock ( createParameterSetter ( object , statement , position , property ) ) ) ) ) ; } private List < Statement > createParameterSetter ( Expression object , Expression statement , Expression position , PropertyDeclaration property ) { assert object != null ; assert statement != null ; assert position != null ; assert property != null ; List < Statement > statements = Lists . create ( ) ; SimpleName date = f . newSimpleName ( NAME_DATE ) ; SimpleName calendar = f . newSimpleName ( NAME_CALENDAR ) ; SimpleName datetime = f . newSimpleName ( NAME_DATETIME ) ; BasicTypeKind kind = toBasicKind ( property . getType ( ) ) ; switch ( kind ) { case INT : statements . add ( createParameterMapping ( object , statement , position , property , "" ) ) ; break ; case LONG : statements . add ( createParameterMapping ( object , statement , position , property , "" ) ) ; break ; case FLOAT : statements . add ( createParameterMapping ( object , statement , position , property , "" ) ) ; break ; case DOUBLE : statements . add ( createParameterMapping ( object , statement , position , property , "" ) ) ; break ; case BYTE : statements . add ( createParameterMapping ( object , statement , position , property , "" ) ) ; break ; case SHORT : statements . add ( createParameterMapping ( object , statement , position , property , "" ) ) ; break ; case BOOLEAN : statements . add ( createParameterMapping ( object , statement , position , property , "" ) ) ; break ; case DECIMAL : statements . add ( createParameterMapping ( object , statement , position , property , "" ) ) ; break ; case TEXT : statements . add ( new ExpressionBuilder ( f , statement ) . method ( "" , position , new ExpressionBuilder ( f , object ) . method ( context . getValueGetterName ( property ) ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; break ; case DATE : statements . add ( new TypeBuilder ( f , context . resolve ( DateUtil . class ) ) . method ( "" , new ExpressionBuilder ( f , object ) . method ( context . getValueGetterName ( property ) ) . method ( "" ) . toExpression ( ) , calendar ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , date ) . method ( "" , new ExpressionBuilder ( f , calendar ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , statement ) . method ( "" , position , date ) . toStatement ( ) ) ; break ; case DATETIME : statements . add ( new TypeBuilder ( f , context . resolve ( DateUtil . class ) ) . method ( "" , new ExpressionBuilder ( f , object ) . method ( context . getValueGetterName ( property ) ) . method ( "" ) . toExpression ( ) , calendar ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , datetime ) . method ( "" , new ExpressionBuilder ( f , calendar ) . method ( "" ) . toExpression ( ) ) . toStatement ( ) ) ; statements . add ( new ExpressionBuilder ( f , statement ) . method ( "" , position , datetime ) . toStatement ( ) ) ; break ; default : throw new AssertionError ( kind ) ; } return statements ; } private Expression createNullType ( PropertyDeclaration property ) { assert property != null ; return new TypeBuilder ( f , context . resolve ( Types . class ) ) . field ( getJdbcTypeName ( property ) ) . toExpression ( ) ; } private String getJdbcTypeName ( PropertyDeclaration property ) { assert property != null ; BasicTypeKind kind = toBasicKind ( property . getType ( ) ) ; switch ( kind ) { case INT : return "" ; case LONG : return "" ; case FLOAT : return "" ; case DOUBLE : return "" ; case BYTE : return "" ; case SHORT : return "" ; case BOOLEAN : return "" ; case DECIMAL : return "" ; case TEXT : return "" ; case DATE : return "" ; case DATETIME : return "" ; default : throw new AssertionError ( kind ) ; } } private Statement createParameterMapping ( Expression object , Expression statement , Expression position , PropertyDeclaration property , String name ) { assert object != null ; assert statement != null ; assert position != null ; assert property != null ; assert name != null ; return new ExpressionBuilder ( f , statement ) . method ( name , position , new ExpressionBuilder ( f , object ) . method ( context . getValueGetterName ( property ) ) . toExpression ( ) ) . toStatement ( ) ; } private ExpressionStatement createResultSetMapping ( Expression object , Expression resultSet , Expression position , PropertyDeclaration property , String name ) { assert object != null ; assert resultSet != null ; assert position != null ; assert property != null ; assert name != null ; return new ExpressionBuilder ( f , object ) . method ( context . getValueSetterName ( property ) , new ExpressionBuilder ( f , resultSet ) . method ( name , position ) . toExpression ( ) ) . toStatement ( ) ; } private BasicTypeKind toBasicKind ( Type type ) { assert type instanceof BasicType ; BasicType basicType = ( BasicType ) type ; return basicType . getKind ( ) ; } private ExpressionStatement mapField ( SimpleName name ) { return new ExpressionBuilder ( f , f . newThis ( ) ) . field ( name ) . assignFrom ( name ) . toStatement ( ) ; } private FieldDeclaration createPrivateField ( Class < ? > type , SimpleName name , boolean newInstance ) { Expression initializer ; if ( newInstance ) { initializer = new TypeBuilder ( f , context . resolve ( type ) ) . newObject ( ) . toExpression ( ) ; } else { initializer = null ; } return f . newFieldDeclaration ( null , new AttributeBuilder ( f ) . Private ( ) . Final ( ) . toAttributes ( ) , context . resolve ( type ) , name , initializer ) ; } private List < PropertyDeclaration > getProperties ( ) { List < PropertyDeclaration > results = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { if ( property . getTrait ( JdbcColumnTrait . class ) != null ) { results . add ( property ) ; } } return results ; } } private static final class DescriptionGenerator { private static final String IMPORTER_TYPE_NAME = "" ; private static final String EXPORTER_TYPE_NAME = "" ; private final EmitContext context ; private final ModelDeclaration model ; private final com . asakusafw . utils . java . model . syntax . Type supportClass ; private final ModelFactory f ; private final boolean importer ; private final JdbcTableTrait tableTrait ; private DescriptionGenerator ( EmitContext context , ModelDeclaration model , Name supportClassName , boolean importer ) { assert context != null ; assert model != null ; assert supportClassName != null ; this . context = context ; this . model = model ; this . f = context . getModelFactory ( ) ; this . importer = importer ; this . tableTrait = model . getTrait ( JdbcTableTrait . class ) ; this . supportClass = context . resolve ( supportClassName ) ; assert tableTrait != null ; } static void emitImporter ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; assert supportClassName != null ; DescriptionGenerator emitter = new DescriptionGenerator ( context , model , supportClassName , true ) ; emitter . emit ( ) ; } static void emitExporter ( EmitContext context , ModelDeclaration model , Name supportClassName ) throws IOException { assert context != null ; assert model != null ; assert supportClassName != null ; DescriptionGenerator emitter = new DescriptionGenerator ( context , model , supportClassName , false ) ; emitter . emit ( ) ; } private void emit ( ) throws IOException { ClassDeclaration decl = f . newClassDeclaration ( new JavadocBuilder ( f ) . text ( "" ) . linkType ( context . resolve ( model . getSymbol ( ) ) ) . text ( "" , importer ? "" : "" ) . text ( "" ) . toJavadoc ( ) , new AttributeBuilder ( f ) . Public ( ) . Abstract ( ) . toAttributes ( ) , context . getTypeName ( ) , context . resolve ( Models . toName ( f , importer ? IMPORTER_TYPE_NAME : EXPORTER_TYPE_NAME ) ) , Collections . < com . asakusafw . utils . java . model . syntax . Type > emptyList ( ) , createMembers ( ) ) ; context . emit ( decl ) ; } private List < TypeBodyDeclaration > createMembers ( ) { List < TypeBodyDeclaration > results = Lists . create ( ) ; results . add ( createGetModelType ( ) ) ; results . add ( createGetJdbcSupport ( ) ) ; results . add ( createGetTableName ( ) ) ; results . add ( createGetColumnNames ( ) ) ; return results ; } private MethodDeclaration createGetModelType ( ) { return createGetter ( new TypeBuilder ( f , context . resolve ( Class . class ) ) . parameterize ( f . newWildcard ( WildcardBoundKind . UPPER_BOUNDED , context . resolve ( model . getSymbol ( ) ) ) ) . toType ( ) , "" , f . newClassLiteral ( context . resolve ( model . getSymbol ( ) ) ) ) ; } private MethodDeclaration createGetJdbcSupport ( ) { return createGetter ( new TypeBuilder ( f , context . resolve ( Class . class ) ) . parameterize ( supportClass ) . toType ( ) , "" , f . newClassLiteral ( supportClass ) ) ; } private MethodDeclaration createGetTableName ( ) { return createGetter ( context . resolve ( String . class ) , "" , Models . toLiteral ( f , tableTrait . getName ( ) ) ) ; } private MethodDeclaration createGetColumnNames ( ) { List < Expression > arguments = Lists . create ( ) ; for ( PropertyDeclaration property : model . getDeclaredProperties ( ) ) { JdbcColumnTrait columnTrait = property . getTrait ( JdbcColumnTrait . class ) ; if ( columnTrait != null ) { arguments . add ( Models . toLiteral ( f , columnTrait . getName ( ) ) ) ; } } return createGetter ( new TypeBuilder ( f , context . resolve ( List . class ) ) . parameterize ( context . resolve ( String . class ) ) . toType ( ) , "" , new TypeBuilder ( f , context . resolve ( Arrays . class ) ) . method ( "" , arguments ) . toExpression ( ) ) ; } private MethodDeclaration createGetter ( com . asakusafw . utils . java . model . syntax . Type type , String name , Expression value ) { assert type != null ; assert name != null ; assert value != null ; return f . newMethodDeclaration ( null , new AttributeBuilder ( f ) . annotation ( context . resolve ( Override . class ) ) . Public ( ) . toAttributes ( ) , type , f . newSimpleName ( name ) , Collections . < FormalParameterDeclaration > emptyList ( ) , Arrays . asList ( new ExpressionBuilder ( f , value ) . toReturnStatement ( ) ) ) ; } } } package com . asakusafw . dmdl . windgate . jdbc . driver ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . Trait ; public class JdbcTableTrait implements Trait < JdbcTableTrait > { private final AstNode originalAst ; private final String tableName ; public JdbcTableTrait ( AstNode originalAst , String tableName ) { if ( originalAst == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . tableName = tableName ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public String getName ( ) { return tableName ; } } package com . asakusafw . dmdl . windgate . jdbc . driver ; import java . util . Map ; import com . asakusafw . dmdl . model . AstAttribute ; import com . asakusafw . dmdl . model . AstAttributeElement ; import com . asakusafw . dmdl . semantics . DmdlSemantics ; import com . asakusafw . dmdl . semantics . PropertyDeclaration ; import com . asakusafw . dmdl . spi . PropertyAttributeDriver ; import com . asakusafw . dmdl . util . AttributeUtil ; public class ColumnDriver extends PropertyAttributeDriver { public static final String TARGET_NAME = "" ; public static final String ELEMENT_NAME = "" ; @ Override public String getTargetName ( ) { return TARGET_NAME ; } @ Override public void process ( DmdlSemantics environment , PropertyDeclaration declaration , AstAttribute attribute ) { Map < String , AstAttributeElement > elements = AttributeUtil . getElementMap ( attribute ) ; String value = AttributeUtil . takeString ( environment , attribute , elements , ELEMENT_NAME , true ) ; environment . reportAll ( AttributeUtil . reportInvalidElements ( attribute , elements . values ( ) ) ) ; if ( value != null ) { declaration . putTrait ( JdbcColumnTrait . class , new JdbcColumnTrait ( attribute , value ) ) ; } } } package com . asakusafw . dmdl . windgate . jdbc . driver ; import com . asakusafw . dmdl . model . AstNode ; import com . asakusafw . dmdl . semantics . Trait ; public class JdbcColumnTrait implements Trait < JdbcColumnTrait > { private final AstNode originalAst ; private final String columnName ; public JdbcColumnTrait ( AstNode originalAst , String columnName ) { if ( originalAst == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnName == null ) { throw new IllegalArgumentException ( "" ) ; } this . originalAst = originalAst ; this . columnName = columnName ; } @ Override public AstNode getOriginalAst ( ) { return originalAst ; } public String getName ( ) { return columnName ; } } package com . asakusafw . vocabulary . windgate ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; public abstract class MockStreamSupport < T > implements DataModelStreamSupport < T > { @ Override public DataModelReader < T > createReader ( String path , InputStream stream ) throws IOException { throw new AssertionError ( ) ; } @ Override public DataModelWriter < T > createWriter ( String path , OutputStream stream ) throws IOException { throw new AssertionError ( ) ; } } package com . asakusafw . vocabulary . windgate ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . util . List ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; public abstract class MockJdbcSupport < T > implements DataModelJdbcSupport < T > { @ Override public boolean isSupported ( List < String > columnNames ) { return true ; } @ Override public DataModelResultSet < T > createResultSetSupport ( ResultSet resultSet , List < String > columnNames ) { throw new UnsupportedOperationException ( ) ; } @ Override public DataModelPreparedStatement < T > createPreparedStatementSupport ( PreparedStatement statement , List < String > columnNames ) { throw new UnsupportedOperationException ( ) ; } } package com . asakusafw . vocabulary . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . core . vocabulary . StreamProcess ; public class FsExporterDescriptionTest { @ Test public void simple ( ) { Mock desc = new Mock ( "" , StringSupport . class ) ; DriverScript script = desc . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . LOCAL_FILE_RESOURCE_NAME ) ) ; assertThat ( script . getConfiguration ( ) . get ( FileProcess . FILE . key ( ) ) , is ( "" ) ) ; assertThat ( script . getConfiguration ( ) . get ( StreamProcess . STREAM_SUPPORT . key ( ) ) , is ( StringSupport . class . getName ( ) ) ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_path_null ( ) { Mock desc = new Mock ( null , StringSupport . class ) ; desc . getDriverScript ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_path_empty ( ) { Mock desc = new Mock ( "" , StringSupport . class ) ; desc . getDriverScript ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_support_null ( ) { Mock desc = new Mock ( "" , null ) ; desc . getDriverScript ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_support_inconsistent ( ) { Mock desc = new Mock ( "" , VoidSupport . class ) ; desc . getDriverScript ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_support_fail ( ) { Mock desc = new Mock ( "" , InvalidSupport . class ) ; desc . getDriverScript ( ) ; } public static class StringSupport extends MockStreamSupport < String > { @ Override public Class < String > getSupportedType ( ) { return String . class ; } } public static class VoidSupport extends MockStreamSupport < Void > { @ Override public Class < Void > getSupportedType ( ) { return Void . class ; } } private static class InvalidSupport extends MockStreamSupport < Object > { @ Override public Class < Object > getSupportedType ( ) { return Object . class ; } } private static final class Mock extends FsExporterDescription { private final String path ; private final Class < ? extends DataModelStreamSupport < ? > > supportClass ; Mock ( String path , Class < ? extends DataModelStreamSupport < ? > > supportClass ) { this . path = path ; this . supportClass = supportClass ; } @ Override public String getProfileName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return String . class ; } @ Override public String getPath ( ) { return path ; } @ Override public Class < ? extends DataModelStreamSupport < ? > > getStreamSupport ( ) { return supportClass ; } } } package com . asakusafw . vocabulary . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import org . junit . Test ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess ; public class JdbcExporterDescriptionTest { @ Test public void simple ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; Map < String , String > conf = script . getConfiguration ( ) ; assertThat ( conf . size ( ) , is ( ) ) ; assertThat ( conf . get ( JdbcProcess . TABLE . key ( ) ) , is ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . COLUMNS . key ( ) ) , equalToIgnoringWhiteSpace ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . JDBC_SUPPORT . key ( ) ) , is ( StringSupport . class . getName ( ) ) ) ; assertThat ( conf . get ( JdbcProcess . OPERATION . key ( ) ) , is ( not ( nullValue ( ) ) ) ) ; } @ Test public void multiple_columns ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , "" , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; Map < String , String > conf = script . getConfiguration ( ) ; assertThat ( conf . size ( ) , is ( ) ) ; assertThat ( conf . get ( JdbcProcess . TABLE . key ( ) ) , is ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . COLUMNS . key ( ) ) , equalToIgnoringWhiteSpace ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . JDBC_SUPPORT . key ( ) ) , is ( StringSupport . class . getName ( ) ) ) ; assertThat ( conf . get ( JdbcProcess . OPERATION . key ( ) ) , is ( not ( nullValue ( ) ) ) ) ; } @ Test ( expected = IllegalStateException . class ) public void no_tables ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void empty_table ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void no_columns ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , ( String [ ] ) null ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void empty_columns ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void has_empty_column ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void has_null_column ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , "" , null ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void no_support ( ) { Mock mock = new Mock ( String . class , "" , null , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_type_support ( ) { Mock mock = new Mock ( String . class , "" , VoidSupport . class , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_columns ( ) { Mock mock = new Mock ( String . class , "" , NullSupport . class , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_support_class ( ) { Mock mock = new Mock ( String . class , "" , InvalidSupport . class , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } public static class StringSupport extends MockJdbcSupport < String > { @ Override public Class < String > getSupportedType ( ) { return String . class ; } } public static class VoidSupport extends MockJdbcSupport < Void > { @ Override public Class < Void > getSupportedType ( ) { return Void . class ; } } public static class NullSupport extends MockJdbcSupport < Object > { @ Override public Class < Object > getSupportedType ( ) { return Object . class ; } @ Override public boolean isSupported ( List < String > columnNames ) { return false ; } } public static class InvalidSupport extends MockJdbcSupport < Object > { private InvalidSupport ( ) { return ; } @ Override public Class < Object > getSupportedType ( ) { return Object . class ; } } static class Mock extends JdbcExporterDescription { private final Class < ? > modelType ; private final String profileName ; private final Class < ? extends DataModelJdbcSupport < ? > > jdbcSupport ; private final String tableName ; private final List < String > columnNames ; Mock ( Class < ? > modelType , String profileName , Class < ? extends DataModelJdbcSupport < ? > > jdbcSupport , String tableName , String ... columnNames ) { this . modelType = modelType ; this . profileName = profileName ; this . jdbcSupport = jdbcSupport ; this . tableName = tableName ; if ( columnNames != null ) { this . columnNames = Arrays . asList ( columnNames ) ; } else { this . columnNames = null ; } } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getProfileName ( ) { return profileName ; } @ Override public Class < ? extends DataModelJdbcSupport < ? > > getJdbcSupport ( ) { return jdbcSupport ; } @ Override public String getTableName ( ) { return tableName ; } @ Override public List < String > getColumnNames ( ) { return columnNames ; } } } package com . asakusafw . vocabulary . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import org . junit . Test ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess ; public class JdbcImporterDescriptionTest { @ Test public void simple ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; Map < String , String > conf = script . getConfiguration ( ) ; assertThat ( conf . size ( ) , is ( ) ) ; assertThat ( conf . get ( JdbcProcess . TABLE . key ( ) ) , is ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . COLUMNS . key ( ) ) , equalToIgnoringWhiteSpace ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . JDBC_SUPPORT . key ( ) ) , is ( StringSupport . class . getName ( ) ) ) ; assertThat ( conf . get ( JdbcProcess . CONDITION . key ( ) ) , is ( nullValue ( ) ) ) ; } @ Test public void multiple_columns ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , null , "" , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; Map < String , String > conf = script . getConfiguration ( ) ; assertThat ( conf . size ( ) , is ( ) ) ; assertThat ( conf . get ( JdbcProcess . TABLE . key ( ) ) , is ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . COLUMNS . key ( ) ) , equalToIgnoringWhiteSpace ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . JDBC_SUPPORT . key ( ) ) , is ( StringSupport . class . getName ( ) ) ) ; assertThat ( conf . get ( JdbcProcess . CONDITION . key ( ) ) , is ( nullValue ( ) ) ) ; } @ Test public void condition ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , "" , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; Map < String , String > conf = script . getConfiguration ( ) ; assertThat ( conf . size ( ) , is ( ) ) ; assertThat ( conf . get ( JdbcProcess . TABLE . key ( ) ) , is ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . COLUMNS . key ( ) ) , equalToIgnoringWhiteSpace ( "" ) ) ; assertThat ( conf . get ( JdbcProcess . JDBC_SUPPORT . key ( ) ) , is ( StringSupport . class . getName ( ) ) ) ; assertThat ( conf . get ( JdbcProcess . CONDITION . key ( ) ) , equalToIgnoringWhiteSpace ( "" ) ) ; } @ Test ( expected = IllegalStateException . class ) public void no_tables ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , null , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void empty_table ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void no_columns ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , null , ( String [ ] ) null ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void empty_columns ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , null ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void has_empty_column ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void has_null_column ( ) { Mock mock = new Mock ( String . class , "" , StringSupport . class , "" , null , "" , null ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void no_support ( ) { Mock mock = new Mock ( String . class , "" , null , "" , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_type_support ( ) { Mock mock = new Mock ( String . class , "" , VoidSupport . class , "" , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_columns ( ) { Mock mock = new Mock ( String . class , "" , NullSupport . class , "" , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_support_class ( ) { Mock mock = new Mock ( String . class , "" , InvalidSupport . class , "" , null , "" ) ; DriverScript script = mock . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . JDBC_RESOURCE_NAME ) ) ; script . getConfiguration ( ) ; } public static class StringSupport extends MockJdbcSupport < String > { @ Override public Class < String > getSupportedType ( ) { return String . class ; } } public static class VoidSupport extends MockJdbcSupport < Void > { @ Override public Class < Void > getSupportedType ( ) { return Void . class ; } } public static class NullSupport extends MockJdbcSupport < Object > { @ Override public Class < Object > getSupportedType ( ) { return Object . class ; } @ Override public boolean isSupported ( List < String > columnNames ) { return false ; } } public static class InvalidSupport extends MockJdbcSupport < Object > { private InvalidSupport ( ) { return ; } @ Override public Class < Object > getSupportedType ( ) { return Object . class ; } } static class Mock extends JdbcImporterDescription { private final Class < ? > modelType ; private final String profileName ; private final Class < ? extends DataModelJdbcSupport < ? > > jdbcSupport ; private final String tableName ; private final String condition ; private final List < String > columnNames ; Mock ( Class < ? > modelType , String profileName , Class < ? extends DataModelJdbcSupport < ? > > jdbcSupport , String tableName , String condition , String ... columnNames ) { this . modelType = modelType ; this . profileName = profileName ; this . jdbcSupport = jdbcSupport ; this . tableName = tableName ; this . condition = condition ; if ( columnNames != null ) { this . columnNames = Arrays . asList ( columnNames ) ; } else { this . columnNames = null ; } } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getProfileName ( ) { return profileName ; } @ Override public Class < ? extends DataModelJdbcSupport < ? > > getJdbcSupport ( ) { return jdbcSupport ; } @ Override public String getTableName ( ) { return tableName ; } @ Override public List < String > getColumnNames ( ) { return columnNames ; } @ Override public String getCondition ( ) { if ( condition == null ) { return super . getCondition ( ) ; } return condition ; } } } package com . asakusafw . vocabulary . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . core . vocabulary . StreamProcess ; public class FsImporterDescriptionTest { @ Test public void simple ( ) { Mock desc = new Mock ( "" , StringSupport . class ) ; DriverScript script = desc . getDriverScript ( ) ; assertThat ( script . getResourceName ( ) , is ( Constants . LOCAL_FILE_RESOURCE_NAME ) ) ; assertThat ( script . getConfiguration ( ) . get ( FileProcess . FILE . key ( ) ) , is ( "" ) ) ; assertThat ( script . getConfiguration ( ) . get ( StreamProcess . STREAM_SUPPORT . key ( ) ) , is ( StringSupport . class . getName ( ) ) ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_path_null ( ) { Mock desc = new Mock ( null , StringSupport . class ) ; desc . getDriverScript ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_path_empty ( ) { Mock desc = new Mock ( "" , StringSupport . class ) ; desc . getDriverScript ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_support_null ( ) { Mock desc = new Mock ( "" , null ) ; desc . getDriverScript ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_support_inconsistent ( ) { Mock desc = new Mock ( "" , VoidSupport . class ) ; desc . getDriverScript ( ) ; } @ Test ( expected = IllegalStateException . class ) public void invalid_support_fail ( ) { Mock desc = new Mock ( "" , InvalidSupport . class ) ; desc . getDriverScript ( ) ; } public static class StringSupport extends MockStreamSupport < String > { @ Override public Class < String > getSupportedType ( ) { return String . class ; } } public static class VoidSupport extends MockStreamSupport < Void > { @ Override public Class < Void > getSupportedType ( ) { return Void . class ; } } private static class InvalidSupport extends MockStreamSupport < Object > { @ Override public Class < Object > getSupportedType ( ) { return Object . class ; } } private static final class Mock extends FsImporterDescription { private final String path ; private final Class < ? extends DataModelStreamSupport < ? > > supportClass ; Mock ( String path , Class < ? extends DataModelStreamSupport < ? > > supportClass ) { this . path = path ; this . supportClass = supportClass ; } @ Override public String getProfileName ( ) { return "" ; } @ Override public Class < ? > getModelType ( ) { return String . class ; } @ Override public String getPath ( ) { return path ; } @ Override public Class < ? extends DataModelStreamSupport < ? > > getStreamSupport ( ) { return supportClass ; } } } package com . asakusafw . vocabulary . windgate ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess ; public abstract class JdbcExporterDescription extends WindGateExporterDescription { public abstract Class < ? extends DataModelJdbcSupport < ? > > getJdbcSupport ( ) ; public abstract String getTableName ( ) ; public abstract List < String > getColumnNames ( ) ; @ Override public final DriverScript getDriverScript ( ) { String descriptionClass = getClass ( ) . getName ( ) ; Class < ? > modelType = getModelType ( ) ; Class < ? extends DataModelJdbcSupport < ? > > supportClass = getJdbcSupport ( ) ; String table = getTableName ( ) ; List < String > columns = getColumnNames ( ) ; JdbcDescriptionUtil . checkCommonConfig ( descriptionClass , modelType , supportClass , table , columns ) ; Map < String , String > configuration = new HashMap < String , String > ( ) ; configuration . put ( JdbcProcess . TABLE . key ( ) , table ) ; configuration . put ( JdbcProcess . COLUMNS . key ( ) , JdbcDescriptionUtil . join ( columns ) ) ; configuration . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , supportClass . getName ( ) ) ; configuration . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; return new DriverScript ( Constants . JDBC_RESOURCE_NAME , configuration ) ; } } package com . asakusafw . vocabulary . windgate ; package com . asakusafw . vocabulary . windgate ; import com . asakusafw . vocabulary . external . ExporterDescription ; public abstract class WindGateExporterDescription implements ExporterDescription , WindGateProcessDescription { } package com . asakusafw . vocabulary . windgate ; import java . util . HashMap ; import java . util . Map ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . core . vocabulary . StreamProcess ; public abstract class FsExporterDescription extends WindGateExporterDescription { public abstract String getPath ( ) ; public abstract Class < ? extends DataModelStreamSupport < ? > > getStreamSupport ( ) ; @ Override public final DriverScript getDriverScript ( ) { String descriptionClass = getClass ( ) . getName ( ) ; Class < ? > modelType = getModelType ( ) ; String path = getPath ( ) ; Class < ? extends DataModelStreamSupport < ? > > supportClass = getStreamSupport ( ) ; FsDescriptionUtil . checkCommonConfig ( descriptionClass , modelType , supportClass , path ) ; Map < String , String > configuration = new HashMap < String , String > ( ) ; configuration . put ( FileProcess . FILE . key ( ) , path ) ; configuration . put ( StreamProcess . STREAM_SUPPORT . key ( ) , supportClass . getName ( ) ) ; return new DriverScript ( Constants . LOCAL_FILE_RESOURCE_NAME , configuration ) ; } } package com . asakusafw . vocabulary . windgate ; public final class Constants { public static final String JDBC_RESOURCE_NAME = "" ; public static final String HADOOP_FILE_RESOURCE_NAME = "" ; public static final String LOCAL_FILE_RESOURCE_NAME = "" ; public static final String DEFAULT_PROCESS_NAME = "" ; private Constants ( ) { return ; } } package com . asakusafw . vocabulary . windgate ; import java . text . MessageFormat ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; final class FsDescriptionUtil { static void checkCommonConfig ( String descriptionClass , Class < ? > modelType , Class < ? extends DataModelStreamSupport < ? > > supportClass , String path ) { if ( path == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , "" ) ) ; } if ( path . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , "" ) ) ; } if ( supportClass == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , "" ) ) ; } DataModelStreamSupport < ? > support ; try { support = supportClass . newInstance ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , supportClass . getName ( ) ) , e ) ; } if ( support . getSupportedType ( ) . isAssignableFrom ( modelType ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , supportClass . getName ( ) , modelType . getName ( ) ) ) ; } } private FsDescriptionUtil ( ) { return ; } } package com . asakusafw . vocabulary . windgate ; import java . text . MessageFormat ; import java . util . List ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; final class JdbcDescriptionUtil { static void checkCommonConfig ( String descriptionClass , Class < ? > modelType , Class < ? extends DataModelJdbcSupport < ? > > supportClass , String table , List < String > columns ) { if ( isEmpty ( table ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , "" ) ) ; } if ( columns == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , "" ) ) ; } if ( columns . isEmpty ( ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , "" ) ) ; } for ( String column : columns ) { if ( isEmpty ( column ) ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , "" ) ) ; } } if ( supportClass == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , "" ) ) ; } DataModelJdbcSupport < ? > support ; try { support = supportClass . newInstance ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , supportClass . getName ( ) ) , e ) ; } if ( support . getSupportedType ( ) . isAssignableFrom ( modelType ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , supportClass . getName ( ) , modelType . getName ( ) ) ) ; } if ( support . isSupported ( columns ) == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , descriptionClass , supportClass . getName ( ) , columns ) ) ; } } static boolean isEmpty ( String string ) { return string == null || string . isEmpty ( ) ; } static String join ( List < String > columns ) { assert columns != null ; assert columns . isEmpty ( ) == false ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( columns . get ( ) ) ; for ( int i = , n = columns . size ( ) ; i < n ; i ++ ) { buf . append ( "" ) ; buf . append ( columns . get ( i ) ) ; } return buf . toString ( ) ; } private JdbcDescriptionUtil ( ) { return ; } } package com . asakusafw . vocabulary . windgate ; import com . asakusafw . windgate . core . DriverScript ; public interface WindGateProcessDescription { String getProfileName ( ) ; DriverScript getDriverScript ( ) ; } package com . asakusafw . vocabulary . windgate ; import java . util . HashMap ; import java . util . Map ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . core . vocabulary . StreamProcess ; public abstract class FsImporterDescription extends WindGateImporterDescription { public abstract String getPath ( ) ; public abstract Class < ? extends DataModelStreamSupport < ? > > getStreamSupport ( ) ; @ Override public final DriverScript getDriverScript ( ) { String descriptionClass = getClass ( ) . getName ( ) ; Class < ? > modelType = getModelType ( ) ; String path = getPath ( ) ; Class < ? extends DataModelStreamSupport < ? > > supportClass = getStreamSupport ( ) ; FsDescriptionUtil . checkCommonConfig ( descriptionClass , modelType , supportClass , path ) ; Map < String , String > configuration = new HashMap < String , String > ( ) ; configuration . put ( FileProcess . FILE . key ( ) , path ) ; configuration . put ( StreamProcess . STREAM_SUPPORT . key ( ) , supportClass . getName ( ) ) ; return new DriverScript ( Constants . LOCAL_FILE_RESOURCE_NAME , configuration ) ; } } package com . asakusafw . vocabulary . windgate ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess ; public abstract class JdbcImporterDescription extends WindGateImporterDescription { public abstract Class < ? extends DataModelJdbcSupport < ? > > getJdbcSupport ( ) ; public abstract String getTableName ( ) ; public abstract List < String > getColumnNames ( ) ; public String getCondition ( ) { return null ; } @ Override public final DriverScript getDriverScript ( ) { String descriptionClass = getClass ( ) . getName ( ) ; Class < ? > modelType = getModelType ( ) ; Class < ? extends DataModelJdbcSupport < ? > > supportClass = getJdbcSupport ( ) ; String table = getTableName ( ) ; List < String > columns = getColumnNames ( ) ; String condition = getCondition ( ) ; JdbcDescriptionUtil . checkCommonConfig ( descriptionClass , modelType , supportClass , table , columns ) ; Map < String , String > configuration = new HashMap < String , String > ( ) ; configuration . put ( JdbcProcess . TABLE . key ( ) , table ) ; configuration . put ( JdbcProcess . COLUMNS . key ( ) , JdbcDescriptionUtil . join ( columns ) ) ; configuration . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , supportClass . getName ( ) ) ; if ( JdbcDescriptionUtil . isEmpty ( condition ) == false ) { configuration . put ( JdbcProcess . CONDITION . key ( ) , condition ) ; } return new DriverScript ( Constants . JDBC_RESOURCE_NAME , configuration ) ; } } package com . asakusafw . vocabulary . windgate ; import com . asakusafw . vocabulary . external . ImporterDescription ; public abstract class WindGateImporterDescription implements ImporterDescription , WindGateProcessDescription { @ Override public DataSize getDataSize ( ) { return DataSize . UNKNOWN ; } } package com . asakusafw . windgate . retryable ; import static com . asakusafw . windgate . retryable . RetryableProcessProfile . * ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import org . junit . Test ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . process . ProcessProfile ; import com . asakusafw . windgate . core . process . ProcessProvider ; import com . asakusafw . windgate . core . resource . DriverFactory ; public class RetryableProcessProfileTest { @ Test public void convert_simple ( ) throws Exception { ProcessProfile profile = profile ( KEY_RETRY_COUNT , "" , KEY_COMPONENT , DummyProcess . class . getName ( ) ) ; RetryableProcessProfile result = RetryableProcessProfile . convert ( profile ) ; assertThat ( result . getComponent ( ) , instanceOf ( DummyProcess . class ) ) ; ProcessProfile inner = ( ( DummyProcess ) result . getComponent ( ) ) . inner ; assertThat ( inner . getName ( ) , is ( not ( profile . getName ( ) ) ) ) ; assertThat ( inner . getConfiguration ( ) , is ( map ( ) ) ) ; } @ Test public void convert_options ( ) throws Exception { ProcessProfile profile = profile ( KEY_RETRY_COUNT , "" , KEY_COMPONENT , DummyProcess . class . getName ( ) , PREFIX_COMPONENT + "" , "" , PREFIX_COMPONENT + "" , "" , PREFIX_COMPONENT + "" , "" ) ; RetryableProcessProfile result = RetryableProcessProfile . convert ( profile ) ; assertThat ( result . getComponent ( ) , instanceOf ( DummyProcess . class ) ) ; ProcessProfile inner = ( ( DummyProcess ) result . getComponent ( ) ) . inner ; assertThat ( inner . getName ( ) , is ( not ( profile . getName ( ) ) ) ) ; assertThat ( inner . getConfiguration ( ) , is ( map ( "" , "" , "" , "" , "" , "" ) ) ) ; } @ Test public void convert_count_unknown ( ) throws Exception { ProcessProfile profile = profile ( KEY_COMPONENT , DummyProcess . class . getName ( ) ) ; try { RetryableProcessProfile . convert ( profile ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } @ Test public void convert_count_invalid ( ) throws Exception { ProcessProfile profile = profile ( KEY_RETRY_COUNT , "" , KEY_COMPONENT , DummyProcess . class . getName ( ) ) ; try { RetryableProcessProfile . convert ( profile ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } @ Test public void convert_count_illegal ( ) throws Exception { ProcessProfile profile = profile ( KEY_RETRY_COUNT , "" , KEY_COMPONENT , DummyProcess . class . getName ( ) ) ; try { RetryableProcessProfile . convert ( profile ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } @ Test public void convert_component_missing ( ) throws Exception { ProcessProfile profile = profile ( KEY_RETRY_COUNT , "" ) ; try { RetryableProcessProfile . convert ( profile ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } @ Test public void convert_component_unknown ( ) throws Exception { ProcessProfile profile = profile ( KEY_RETRY_COUNT , "" , KEY_COMPONENT , "" ) ; try { RetryableProcessProfile . convert ( profile ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } @ Test public void convert_component_invalid ( ) throws Exception { ProcessProfile profile = profile ( KEY_RETRY_COUNT , "" , KEY_COMPONENT , String . class . getName ( ) ) ; try { RetryableProcessProfile . convert ( profile ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } @ Test public void convert_component_failed ( ) throws Exception { ProcessProfile profile = profile ( KEY_RETRY_COUNT , "" , KEY_COMPONENT , InvalidProcess . class . getName ( ) ) ; try { RetryableProcessProfile . convert ( profile ) ; fail ( ) ; } catch ( IOException e ) { } } private ProcessProfile profile ( String ... conf ) { ProcessProfile profile = new ProcessProfile ( "" , RetryableProcessProvider . class , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) , map ( conf ) ) ; return profile ; } private Map < String , String > map ( String ... keyValuePairs ) { assertThat ( keyValuePairs . length % , is ( ) ) ; Map < String , String > results = new HashMap < String , String > ( ) ; for ( int i = ; i < keyValuePairs . length ; i += ) { results . put ( keyValuePairs [ i ] , keyValuePairs [ i + ] ) ; } return results ; } public static class DummyProcess extends ProcessProvider { ProcessProfile inner ; @ Override protected void configure ( ProcessProfile profile ) throws IOException { this . inner = profile ; } @ Override public < T > void execute ( DriverFactory drivers , ProcessScript < T > script ) throws IOException { return ; } } public static class InvalidProcess extends ProcessProvider { @ Override protected void configure ( ProcessProfile profile ) throws IOException { throw new IOException ( ) ; } @ Override public < T > void execute ( DriverFactory drivers , ProcessScript < T > script ) throws IOException { return ; } } } package com . asakusafw . windgate . retryable ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InterruptedIOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . process . ProcessProfile ; import com . asakusafw . windgate . core . process . ProcessProvider ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . DriverFactory ; import com . asakusafw . windgate . core . resource . SourceDriver ; public class RetryableProcessProviderTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; @ Test public void execute_simple ( ) throws Exception { ProcessProfile profile = profile ( , Action . SUCCESS ) ; ProcessProvider provider = profile . createProvider ( ) ; provider . execute ( factory ( ) , script ( ) ) ; } @ Test public void execute_retry1 ( ) throws Exception { ProcessProfile profile = profile ( , Action . EXCEPTION , Action . SUCCESS ) ; ProcessProvider provider = profile . createProvider ( ) ; provider . execute ( factory ( ) , script ( ) ) ; } @ Test public void execute_retry2 ( ) throws Exception { ProcessProfile profile = profile ( , Action . EXCEPTION , Action . EXCEPTION , Action . SUCCESS ) ; ProcessProvider provider = profile . createProvider ( ) ; provider . execute ( factory ( ) , script ( ) ) ; } @ Test public void execute_retry_over ( ) throws Exception { ProcessProfile profile = profile ( , Action . EXCEPTION , Action . EXCEPTION , Action . EXCEPTION , Action . SUCCESS ) ; ProcessProvider provider = profile . createProvider ( ) ; try { provider . execute ( factory ( ) , script ( ) ) ; fail ( ) ; } catch ( IOException e ) { } } @ Test public void execute_interrupted ( ) throws Exception { ProcessProfile profile = profile ( , Action . INTERRUPT , Action . SUCCESS ) ; ProcessProvider provider = profile . createProvider ( ) ; try { provider . execute ( factory ( ) , script ( ) ) ; fail ( ) ; } catch ( IOException e ) { } } @ Test public void execute_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; ProcessProfile profile = profile ( , Action . SUCCESS ) ; ProcessProvider provider = profile . createProvider ( ) ; assertThat ( RuntimeContext . get ( ) . canExecute ( provider ) , is ( true ) ) ; } @ Test public void configure_invalid_container ( ) throws Exception { ProcessProfile profile = profile ( , Action . EXCEPTION , Action . SUCCESS ) ; try { profile . createProvider ( ) ; fail ( ) ; } catch ( IOException e ) { } } @ Test public void configure_invalid_component ( ) throws Exception { ProcessProfile profile = profile ( ) ; try { profile . createProvider ( ) ; fail ( ) ; } catch ( IOException e ) { } } private ProcessProfile profile ( int retryCount , Action ... actions ) { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( RetryableProcessProfile . KEY_RETRY_COUNT , String . valueOf ( retryCount ) ) ; conf . put ( RetryableProcessProfile . KEY_COMPONENT , Mock . class . getName ( ) ) ; if ( actions . length > ) { StringBuilder buf = new StringBuilder ( ) ; for ( Action action : actions ) { buf . append ( action . name ( ) ) ; buf . append ( '' ) ; } buf . append ( Action . FAIL . name ( ) ) ; conf . put ( RetryableProcessProfile . PREFIX_COMPONENT + Mock . KEY_ATTEMPTS , buf . toString ( ) ) ; } return new ProcessProfile ( "" , RetryableProcessProvider . class , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) , conf ) ; } private DriverFactory factory ( ) { return DummyDriverFactory . INSTANCE ; } private ProcessScript < String > script ( ) { return new ProcessScript < String > ( "" , "" , String . class , new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) , new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) ) ; } public static class Mock extends ProcessProvider { static final String KEY_ATTEMPTS = "" ; private volatile Iterator < Action > attempts ; @ Override protected void configure ( ProcessProfile profile ) throws IOException { String attemptsString = profile . getConfiguration ( ) . get ( KEY_ATTEMPTS ) ; if ( attemptsString == null ) { throw new IOException ( ) ; } List < Action > actions = new ArrayList < Action > ( ) ; for ( String string : attemptsString . split ( "" ) ) { actions . add ( Action . valueOf ( string ) ) ; } attempts = actions . iterator ( ) ; } @ Override public < T > void execute ( DriverFactory drivers , ProcessScript < T > script ) throws IOException { attempts . next ( ) . perform ( ) ; } } private enum Action { SUCCESS { @ Override public void perform ( ) throws IOException { return ; } } , EXCEPTION { @ Override public void perform ( ) throws IOException { throw new IOException ( ) ; } } , INTERRUPT { @ Override public void perform ( ) throws IOException { throw new InterruptedIOException ( ) ; } } , FAIL { @ Override public void perform ( ) throws IOException { throw new AssertionError ( ) ; } } , ; public abstract void perform ( ) throws IOException ; } private static class DummyDriverFactory implements DriverFactory { static final DriverFactory INSTANCE = new DummyDriverFactory ( ) ; @ Override public < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException { throw new UnsupportedOperationException ( ) ; } @ Override public < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException { throw new UnsupportedOperationException ( ) ; } } } package com . asakusafw . windgate . retryable ; package com . asakusafw . windgate . retryable ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Map ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . process . ProcessProfile ; import com . asakusafw . windgate . core . process . ProcessProvider ; import com . asakusafw . windgate . core . util . PropertiesUtil ; public class RetryableProcessProfile { static final WindGateLogger WGLOG = new RetryableProcessLogger ( RetryableProcessProfile . class ) ; private static final char SEPARATOR = '' ; public static final String KEY_RETRY_COUNT = "" ; public static final String KEY_COMPONENT = "" ; public static final String PREFIX_COMPONENT = KEY_COMPONENT + SEPARATOR ; private final ProcessProvider component ; private final int retryCount ; public RetryableProcessProfile ( ProcessProvider component , int retryCount ) { if ( component == null ) { throw new IllegalArgumentException ( "" ) ; } if ( retryCount <= ) { throw new IllegalArgumentException ( "" ) ; } this . component = component ; this . retryCount = retryCount ; } public static RetryableProcessProfile convert ( ProcessProfile profile ) throws IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } int retryCount = extractInt ( profile , KEY_RETRY_COUNT , ) ; String componentName = profile . getName ( ) + '' + KEY_COMPONENT ; String componentClassName = extract ( profile , KEY_COMPONENT , false ) ; Class < ? extends ProcessProvider > componentClass ; try { Class < ? > aClass = Class . forName ( componentClassName , false , profile . getContext ( ) . getClassLoader ( ) ) ; componentClass = aClass . asSubclass ( ProcessProvider . class ) ; } catch ( Exception e ) { WGLOG . error ( e , "" , profile . getName ( ) , KEY_COMPONENT , componentClassName ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , componentClassName ) , e ) ; } Map < String , String > conf = profile . getConfiguration ( ) ; Map < String , String > componentConf = PropertiesUtil . createPrefixMap ( conf , PREFIX_COMPONENT ) ; ProcessProfile componentProfile = new ProcessProfile ( componentName , componentClass , profile . getContext ( ) , componentConf ) ; ProcessProvider component ; try { component = componentProfile . createProvider ( ) ; } catch ( IOException e ) { WGLOG . error ( e , "" , profile . getName ( ) , KEY_COMPONENT , componentClassName ) ; throw e ; } return new RetryableProcessProfile ( component , retryCount ) ; } private static String extract ( ProcessProfile profile , String configKey , boolean mandatory ) { assert profile != null ; assert configKey != null ; String value = profile . getConfiguration ( ) . get ( configKey ) ; if ( value == null ) { if ( mandatory == false ) { return null ; } else { WGLOG . error ( "" , profile . getName ( ) , configKey , null ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey ) ) ; } } try { return profile . getContext ( ) . getContextParameters ( ) . replace ( value . trim ( ) , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , profile . getName ( ) , configKey , value ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey , value ) , e ) ; } } private static int extractInt ( ProcessProfile profile , String key , int minimumValue ) { assert profile != null ; assert key != null ; String valueString = extract ( profile , key , true ) ; int value ; try { value = Integer . parseInt ( valueString . trim ( ) ) ; } catch ( NumberFormatException e ) { WGLOG . error ( "" , profile . getName ( ) , key , valueString ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , key , valueString ) , e ) ; } if ( value < minimumValue ) { WGLOG . error ( "" , profile . getName ( ) , key , valueString ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , value , valueString ) ) ; } return value ; } public ProcessProvider getComponent ( ) { return component ; } public int getRetryCount ( ) { return retryCount ; } } package com . asakusafw . windgate . retryable ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . windgate . core . WindGateLogger ; public class RetryableProcessLogger extends WindGateLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public RetryableProcessLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . windgate . retryable ; import java . io . IOException ; import java . io . InterruptedIOException ; import java . text . MessageFormat ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . process . ProcessProfile ; import com . asakusafw . windgate . core . process . ProcessProvider ; import com . asakusafw . windgate . core . resource . DriverFactory ; @ SimulationSupport public class RetryableProcessProvider extends ProcessProvider { static final WindGateLogger WGLOG = new RetryableProcessLogger ( RetryableProcessProvider . class ) ; private volatile RetryableProcessProfile processProfile ; @ Override protected void configure ( ProcessProfile profile ) throws IOException { try { processProfile = RetryableProcessProfile . convert ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getName ( ) ) ) ; } } @ Override public < T > void execute ( DriverFactory drivers , ProcessScript < T > script ) throws IOException { int maxAttempts = processProfile . getRetryCount ( ) + ; WGLOG . info ( "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) , processProfile . getRetryCount ( ) ) ; long start = System . currentTimeMillis ( ) ; try { int attempt = ; while ( true ) { assert attempt <= maxAttempts ; try { processProfile . getComponent ( ) . execute ( drivers , script ) ; break ; } catch ( InterruptedIOException e ) { WGLOG . error ( e , "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) ) ; throw e ; } catch ( IOException e ) { if ( attempt < maxAttempts ) { WGLOG . warn ( e , "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) , attempt , processProfile . getRetryCount ( ) ) ; attempt ++ ; } else { WGLOG . error ( e , "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) , maxAttempts ) ; throw e ; } } } WGLOG . info ( "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) , attempt ) ; } finally { long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) , end - start ) ; } } } package com . asakusafw . testdriver . windgate ; package com . asakusafw . testdriver . windgate ; import java . io . IOException ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . windgate . core . resource . SourceDriver ; public class WindGateSource < T > implements DataModelSource { private final SourceDriver < T > driver ; private final DataModelDefinition < T > definition ; public WindGateSource ( SourceDriver < T > driver , DataModelDefinition < T > definition ) { if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } if ( definition == null ) { throw new IllegalArgumentException ( "" ) ; } this . driver = driver ; this . definition = definition ; } @ Override public DataModelReflection next ( ) throws IOException { if ( driver . next ( ) == false ) { return null ; } T object = driver . get ( ) ; return definition . toReflection ( object ) ; } @ Override public void close ( ) throws IOException { driver . close ( ) ; } } package com . asakusafw . testdriver . windgate ; import java . io . Closeable ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . net . URLClassLoader ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Properties ; import java . util . WeakHashMap ; import org . apache . hadoop . conf . Configurable ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . testdriver . hadoop . ConfigurationFactory ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateProcessDescription ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateProfile ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . resource . ResourceProvider ; import com . asakusafw . windgate . file . resource . Preparable ; public final class WindGateTestHelper { static final Logger LOG = LoggerFactory . getLogger ( WindGateTestHelper . class ) ; public static final String TESTING_PROFILE_PATH = "" ; public static final String PRODUCTION_PLUGIN_DIRECTORY = "" ; public static final String PRODUCTION_PROFILE_PATH = "" ; private static final String PLUGIN_EXTENSION = "" ; private static final String DUMMY_RESOURCE_NAME = "" ; private static final String DUMMY_PROCESS_NAME = "" ; private static File lastPluginDirectory ; private static final WeakHashMap < ClassLoader , ClassLoader > PLUGIN_REPOSITORY = new WeakHashMap < ClassLoader , ClassLoader > ( ) ; public static < T > ProcessScript < T > createProcessScript ( Class < T > modelType , WindGateImporterDescription description ) { if ( modelType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , description . getClass ( ) . getName ( ) ) ; return new ProcessScript < T > ( DUMMY_PROCESS_NAME , DUMMY_PROCESS_NAME , modelType , description . getDriverScript ( ) , createDummyDriverScript ( ) ) ; } public static < T > ProcessScript < T > createProcessScript ( Class < T > modelType , WindGateExporterDescription description ) { if ( modelType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , description . getClass ( ) . getName ( ) ) ; return new ProcessScript < T > ( DUMMY_PROCESS_NAME , DUMMY_PROCESS_NAME , modelType , createDummyDriverScript ( ) , description . getDriverScript ( ) ) ; } private static DriverScript createDummyDriverScript ( ) { return new DriverScript ( DUMMY_RESOURCE_NAME , Collections . < String , String > emptyMap ( ) ) ; } public static ResourceManipulator createResourceManipulator ( TestContext testContext , WindGateProcessDescription description , ParameterList arguments ) throws IOException { if ( testContext == null ) { throw new IllegalArgumentException ( "" ) ; } if ( description == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , description . getClass ( ) . getName ( ) ) ; GateProfile profile = loadProfile ( testContext , description ) ; String resourceName = description . getDriverScript ( ) . getResourceName ( ) ; for ( ResourceProfile resource : profile . getResources ( ) ) { if ( resource . getName ( ) . equals ( resourceName ) ) { return createManipulator ( description , resource , arguments ) ; } } throw new IOException ( MessageFormat . format ( "" , description . getClass ( ) . getName ( ) , description . getProfileName ( ) , resourceName ) ) ; } private static ResourceManipulator createManipulator ( WindGateProcessDescription description , ResourceProfile resource , ParameterList arguments ) throws IOException { assert description != null ; assert resource != null ; assert arguments != null ; ResourceProvider provider = resource . createProvider ( ) ; ResourceManipulator manipulator = provider . createManipulator ( arguments ) ; if ( manipulator instanceof Configurable ) { LOG . debug ( "" , manipulator ) ; ConfigurationFactory configuration = ConfigurationFactory . getDefault ( ) ; ( ( Configurable ) manipulator ) . setConf ( configuration . newInstance ( ) ) ; } return manipulator ; } private static GateProfile loadProfile ( TestContext testContext , WindGateProcessDescription description ) throws IOException { assert testContext != null ; assert description != null ; String profileName = description . getProfileName ( ) ; LOG . debug ( "" , profileName ) ; ClassLoader classLoader = findClassLoader ( testContext ) ; URL url = classLoader . getResource ( MessageFormat . format ( TESTING_PROFILE_PATH , profileName ) ) ; if ( url == null ) { url = findResourceOnHomePath ( testContext , MessageFormat . format ( PRODUCTION_PROFILE_PATH , profileName ) ) ; } if ( url == null ) { throw new IOException ( MessageFormat . format ( "" , description . getClass ( ) . getName ( ) , description . getProfileName ( ) ) ) ; } LOG . debug ( "" , url ) ; try { Properties p = new Properties ( ) ; InputStream input = url . openStream ( ) ; try { p . load ( input ) ; } finally { input . close ( ) ; } LOG . debug ( "" , url ) ; GateProfile profile = GateProfile . loadFrom ( profileName , p , new ProfileContext ( classLoader , new ParameterList ( testContext . getEnvironmentVariables ( ) ) ) ) ; return profile ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , description . getClass ( ) . getName ( ) , description . getProfileName ( ) , url ) , e ) ; } } private static URL findResourceOnHomePath ( TestContext testContext , String path ) { assert testContext != null ; assert path != null ; File file = findFileOnHomePath ( testContext , path ) ; if ( file != null && file . isFile ( ) != false ) { try { return file . toURI ( ) . toURL ( ) ; } catch ( IOException e ) { LOG . warn ( MessageFormat . format ( "" , file ) , e ) ; return null ; } } return null ; } private static File findFileOnHomePath ( TestContext testContext , String path ) { assert testContext != null ; assert path != null ; String home = testContext . getEnvironmentVariables ( ) . get ( "" ) ; if ( home != null ) { File file = new File ( home , path ) ; if ( file . exists ( ) ) { return file ; } } else { LOG . warn ( "" ) ; } return null ; } private static ClassLoader findClassLoader ( TestContext testContext ) { assert testContext != null ; File pluginDirectory = findFileOnHomePath ( testContext , PRODUCTION_PLUGIN_DIRECTORY ) ; final ClassLoader baseClassLoader = getBareClassLoader ( ) ; synchronized ( PLUGIN_REPOSITORY ) { if ( lastPluginDirectory != null && lastPluginDirectory . equals ( pluginDirectory ) == false ) { PLUGIN_REPOSITORY . clear ( ) ; lastPluginDirectory = pluginDirectory ; } ClassLoader plugins = PLUGIN_REPOSITORY . get ( baseClassLoader ) ; if ( plugins != null ) { return plugins ; } if ( pluginDirectory == null || pluginDirectory . isDirectory ( ) == false ) { return baseClassLoader ; } final List < URL > pluginLibraries = new ArrayList < URL > ( ) ; for ( File file : pluginDirectory . listFiles ( ) ) { if ( file . isFile ( ) && file . getName ( ) . endsWith ( PLUGIN_EXTENSION ) ) { try { URL url = file . toURI ( ) . toURL ( ) ; pluginLibraries . add ( url ) ; } catch ( Exception e ) { LOG . warn ( MessageFormat . format ( "" , file ) , e ) ; } } } if ( pluginLibraries . isEmpty ( ) ) { return baseClassLoader ; } ClassLoader pluginClassLoader = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) { URLClassLoader loader = new URLClassLoader ( pluginLibraries . toArray ( new URL [ pluginLibraries . size ( ) ] ) , baseClassLoader ) ; return loader ; } } ) ; PLUGIN_REPOSITORY . put ( baseClassLoader , pluginClassLoader ) ; return pluginClassLoader ; } } private static ClassLoader getBareClassLoader ( ) { ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( contextClassLoader != null ) { return contextClassLoader ; } return ClassLoader . getSystemClassLoader ( ) ; } public static < T extends Preparable & Closeable > T prepare ( T object ) throws IOException { if ( object == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , object ) ; boolean succeed = false ; try { object . prepare ( ) ; succeed = true ; return object ; } finally { if ( succeed == false ) { LOG . warn ( "" , object ) ; try { object . close ( ) ; } catch ( IOException e ) { LOG . warn ( "" , e ) ; } } } } private WindGateTestHelper ( ) { return ; } } package com . asakusafw . testdriver . windgate ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . BaseImporterPreparator ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . ImporterPreparator ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; public class WindGateImporterPreparator extends BaseImporterPreparator < WindGateImporterDescription > { @ Override public void truncate ( WindGateImporterDescription description , TestContext context ) throws IOException { ProcessScript < ? > process = WindGateTestHelper . createProcessScript ( description . getModelType ( ) , description ) ; ParameterList parameterList = new ParameterList ( context . getArguments ( ) ) ; ResourceManipulator manipulator = WindGateTestHelper . createResourceManipulator ( context , description , parameterList ) ; manipulator . cleanupSource ( process ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , WindGateImporterDescription description , TestContext context ) throws IOException { ProcessScript < V > process = WindGateTestHelper . createProcessScript ( definition . getModelClass ( ) , description ) ; ParameterList parameterList = new ParameterList ( context . getArguments ( ) ) ; ResourceManipulator manipulator = WindGateTestHelper . createResourceManipulator ( context , description , parameterList ) ; DrainDriver < V > driver = manipulator . createDrainForSource ( process ) ; return new WindGateOutput < V > ( WindGateTestHelper . prepare ( driver ) ) ; } } package com . asakusafw . testdriver . windgate ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . windgate . core . resource . DrainDriver ; public class WindGateOutput < T > implements ModelOutput < T > { private final DrainDriver < T > driver ; public WindGateOutput ( DrainDriver < T > driver ) { if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } this . driver = driver ; } @ Override public void write ( T model ) throws IOException { driver . put ( model ) ; } @ Override public void close ( ) throws IOException { driver . close ( ) ; } } package com . asakusafw . testdriver . windgate ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . BaseExporterRetriever ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . ExporterRetriever ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . SourceDriver ; public class WindGateExporterRetriever extends BaseExporterRetriever < WindGateExporterDescription > { @ Override public void truncate ( WindGateExporterDescription description , TestContext context ) throws IOException { ProcessScript < ? > process = WindGateTestHelper . createProcessScript ( description . getModelType ( ) , description ) ; ParameterList parameterList = new ParameterList ( context . getArguments ( ) ) ; ResourceManipulator manipulator = WindGateTestHelper . createResourceManipulator ( context , description , parameterList ) ; manipulator . cleanupDrain ( process ) ; } @ Override public < V > ModelOutput < V > createOutput ( DataModelDefinition < V > definition , WindGateExporterDescription description , TestContext context ) throws IOException { ProcessScript < V > process = WindGateTestHelper . createProcessScript ( definition . getModelClass ( ) , description ) ; ParameterList parameterList = new ParameterList ( context . getArguments ( ) ) ; ResourceManipulator manipulator = WindGateTestHelper . createResourceManipulator ( context , description , parameterList ) ; DrainDriver < V > driver = manipulator . createDrainForDrain ( process ) ; return new WindGateOutput < V > ( WindGateTestHelper . prepare ( driver ) ) ; } @ Override public < V > DataModelSource createSource ( DataModelDefinition < V > definition , WindGateExporterDescription description , TestContext context ) throws IOException { ProcessScript < V > process = WindGateTestHelper . createProcessScript ( definition . getModelClass ( ) , description ) ; ParameterList parameterList = new ParameterList ( context . getArguments ( ) ) ; ResourceManipulator manipulator = WindGateTestHelper . createResourceManipulator ( context , description , parameterList ) ; SourceDriver < V > driver = manipulator . createSourceForDrain ( process ) ; return new WindGateSource < V > ( WindGateTestHelper . prepare ( driver ) , definition ) ; } } package com . asakusafw . testdriver . windgate ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . DataModelSourceProvider ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . SourceDriver ; public class WindGateSourceProvider implements DataModelSourceProvider { private static final String SCHEME = "" ; static final Logger LOG = LoggerFactory . getLogger ( WindGateSourceProvider . class ) ; @ Override public < T > DataModelSource open ( DataModelDefinition < T > definition , URI source , TestContext context ) throws IOException { String scheme = source . getScheme ( ) ; if ( scheme == null || scheme . equals ( SCHEME ) == false ) { LOG . debug ( "" , source ) ; return null ; } ClassLoader classLoader = context . getClassLoader ( ) ; String rest = source . getSchemeSpecificPart ( ) ; LOG . debug ( "" , rest ) ; Object instance ; try { Class < ? > target = classLoader . loadClass ( rest ) ; instance = target . newInstance ( ) ; } catch ( Exception e ) { throw new IOException ( MessageFormat . format ( "" , rest ) , e ) ; } if ( instance instanceof WindGateImporterDescription ) { WindGateImporterDescription description = ( WindGateImporterDescription ) instance ; ProcessScript < T > process = WindGateTestHelper . createProcessScript ( definition . getModelClass ( ) , description ) ; ParameterList parameterList = new ParameterList ( context . getArguments ( ) ) ; ResourceManipulator manipulator = WindGateTestHelper . createResourceManipulator ( context , description , parameterList ) ; SourceDriver < T > driver = manipulator . createSourceForSource ( process ) ; return new WindGateSource < T > ( WindGateTestHelper . prepare ( driver ) , definition ) ; } else if ( instance instanceof WindGateExporterDescription ) { WindGateExporterDescription description = ( WindGateExporterDescription ) instance ; ProcessScript < T > process = WindGateTestHelper . createProcessScript ( definition . getModelClass ( ) , description ) ; ParameterList parameterList = new ParameterList ( context . getArguments ( ) ) ; ResourceManipulator manipulator = WindGateTestHelper . createResourceManipulator ( context , description , parameterList ) ; SourceDriver < T > driver = manipulator . createSourceForDrain ( process ) ; return new WindGateSource < T > ( WindGateTestHelper . prepare ( driver ) , definition ) ; } else { throw new IOException ( MessageFormat . format ( "" , source , WindGateImporterDescription . class . getSimpleName ( ) , WindGateExporterDescription . class . getSimpleName ( ) ) ) ; } } } package com . asakusafw . testdriver . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . Collections ; import java . util . Properties ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . file . resource . FileResourceProvider ; public class WindGateExporterRetrieverTest { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Rule public ProfileContext context = new ProfileContext ( ) ; @ Test public void truncate ( ) throws Exception { Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , FileResourceProvider . class . getName ( ) ) ; context . put ( "" , profile ) ; File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateExporterDescription description = new MockExporterDescription ( String . class , "" , driver ) ; WindGateExporterRetriever preparator = new WindGateExporterRetriever ( ) ; assertThat ( file . exists ( ) , is ( true ) ) ; preparator . truncate ( description , EMPTY ) ; assertThat ( file . exists ( ) , is ( false ) ) ; } @ Test public void createOutput ( ) throws Exception { Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , FileResourceProvider . class . getName ( ) ) ; context . put ( "" , profile ) ; File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateExporterDescription description = new MockExporterDescription ( String . class , "" , driver ) ; WindGateExporterRetriever retriever = new WindGateExporterRetriever ( ) ; ModelOutput < String > output = retriever . createOutput ( ValueDefinition . of ( String . class ) , description , EMPTY ) ; try { output . write ( "" ) ; output . write ( "" ) ; output . write ( "" ) ; } finally { output . close ( ) ; } FileInputStream input = new FileInputStream ( file ) ; try { ObjectInputStream in = new ObjectInputStream ( input ) ; assertThat ( in . readObject ( ) , is ( ( Object ) "" ) ) ; assertThat ( in . readObject ( ) , is ( ( Object ) "" ) ) ; assertThat ( in . readObject ( ) , is ( ( Object ) "" ) ) ; try { in . readObject ( ) ; fail ( ) ; } catch ( IOException e ) { } in . close ( ) ; } finally { input . close ( ) ; } } @ Test public void createSource ( ) throws Exception { Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , FileResourceProvider . class . getName ( ) ) ; context . put ( "" , profile ) ; File file = folder . newFile ( "" ) ; FileOutputStream output = new FileOutputStream ( file ) ; try { ObjectOutputStream out = new ObjectOutputStream ( output ) ; out . writeObject ( "" ) ; out . writeObject ( "" ) ; out . writeObject ( "" ) ; out . close ( ) ; } finally { output . close ( ) ; } DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateExporterDescription description = new MockExporterDescription ( String . class , "" , driver ) ; WindGateExporterRetriever retriever = new WindGateExporterRetriever ( ) ; ValueDefinition < String > stringDef = ValueDefinition . of ( String . class ) ; DataModelSource source = retriever . createSource ( stringDef , description , EMPTY ) ; try { DataModelReflection r1 = source . next ( ) ; assertThat ( r1 , is ( notNullValue ( ) ) ) ; assertThat ( stringDef . toObject ( r1 ) , is ( "" ) ) ; DataModelReflection r2 = source . next ( ) ; assertThat ( r2 , is ( notNullValue ( ) ) ) ; assertThat ( stringDef . toObject ( r2 ) , is ( "" ) ) ; DataModelReflection r3 = source . next ( ) ; assertThat ( r3 , is ( notNullValue ( ) ) ) ; assertThat ( stringDef . toObject ( r3 ) , is ( "" ) ) ; DataModelReflection r4 = source . next ( ) ; assertThat ( r4 , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } } package com . asakusafw . testdriver . windgate ; import java . lang . annotation . Annotation ; import java . util . Collection ; import java . util . Collections ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . PropertyName ; import com . asakusafw . testdriver . core . PropertyType ; import com . asakusafw . testdriver . model . SimpleDataModelDefinition ; public class ValueDefinition < T > implements DataModelDefinition < T > { public static final PropertyName VALUE = PropertyName . newInstance ( "" ) ; private final Class < T > type ; private final PropertyType kind ; public static < T > ValueDefinition < T > of ( Class < T > type ) { return new ValueDefinition < T > ( type ) ; } public ValueDefinition ( Class < T > type ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } this . type = type ; this . kind = SimpleDataModelDefinition . getType ( VALUE , type ) ; if ( kind == null ) { throw new IllegalArgumentException ( type . getName ( ) ) ; } } @ Override public Class < T > getModelClass ( ) { return type ; } @ Override public < A extends Annotation > A getAnnotation ( Class < A > annotationType ) { return type . getAnnotation ( annotationType ) ; } @ Override public Collection < PropertyName > getProperties ( ) { return Collections . singleton ( VALUE ) ; } @ Override public PropertyType getType ( PropertyName name ) { if ( VALUE . equals ( name ) ) { return kind ; } return null ; } @ Override public < A extends Annotation > A getAnnotation ( PropertyName name , Class < A > annotationType ) { return null ; } @ Override public Builder < T > newReflection ( ) { return new Builder < T > ( this ) ; } @ Override public DataModelReflection toReflection ( T object ) { return newReflection ( ) . add ( VALUE , object ) . build ( ) ; } @ Override public T toObject ( DataModelReflection reflection ) { return type . cast ( reflection . getValue ( VALUE ) ) ; } } package com . asakusafw . testdriver . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . util . Collections ; import java . util . Properties ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . testdriver . core . DataModelDefinition ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . file . resource . FileResourceProvider ; public class WindGateImporterPreparatorTest { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Rule public ProfileContext context = new ProfileContext ( ) ; @ Test public void truncate ( ) throws Exception { Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , FileResourceProvider . class . getName ( ) ) ; context . put ( "" , profile ) ; File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateImporterDescription description = new MockImporterDescription ( String . class , "" , driver ) ; WindGateImporterPreparator preparator = new WindGateImporterPreparator ( ) ; assertThat ( file . exists ( ) , is ( true ) ) ; preparator . truncate ( description , EMPTY ) ; assertThat ( file . exists ( ) , is ( false ) ) ; } @ Test public void createOutput ( ) throws Exception { Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , FileResourceProvider . class . getName ( ) ) ; context . put ( "" , profile ) ; File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateImporterDescription description = new MockImporterDescription ( String . class , "" , driver ) ; WindGateImporterPreparator preparator = new WindGateImporterPreparator ( ) ; ModelOutput < String > output = preparator . createOutput ( ValueDefinition . of ( String . class ) , description , EMPTY ) ; try { output . write ( "" ) ; output . write ( "" ) ; output . write ( "" ) ; } finally { output . close ( ) ; } FileInputStream input = new FileInputStream ( file ) ; try { ObjectInputStream in = new ObjectInputStream ( input ) ; assertThat ( in . readObject ( ) , is ( ( Object ) "" ) ) ; assertThat ( in . readObject ( ) , is ( ( Object ) "" ) ) ; assertThat ( in . readObject ( ) , is ( ( Object ) "" ) ) ; try { in . readObject ( ) ; fail ( ) ; } catch ( IOException e ) { } in . close ( ) ; } finally { input . close ( ) ; } } } package com . asakusafw . testdriver . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . net . URLClassLoader ; import java . text . MessageFormat ; import java . util . Properties ; import org . junit . rules . ExternalResource ; import org . junit . rules . TemporaryFolder ; public class ProfileContext extends ExternalResource { private final TemporaryFolder folder = new TemporaryFolder ( ) ; private ClassLoader context ; @ Override protected void before ( ) throws Throwable { folder . create ( ) ; ClassLoader classLoader = new URLClassLoader ( new URL [ ] { folder . getRoot ( ) . toURI ( ) . toURL ( ) , } , getClass ( ) . getClassLoader ( ) ) ; context = Thread . currentThread ( ) . getContextClassLoader ( ) ; boolean green = false ; try { Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; green = true ; } finally { if ( green == false ) { after ( ) ; } } } @ Override protected void after ( ) { try { Thread . currentThread ( ) . setContextClassLoader ( context ) ; System . gc ( ) ; } finally { folder . delete ( ) ; } } public Properties getTemplate ( ) { Properties p = new Properties ( ) ; InputStream in = ProfileContext . class . getResourceAsStream ( "" ) ; assertThat ( in , is ( notNullValue ( ) ) ) ; try { p . load ( in ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } finally { try { in . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } return p ; } public void put ( String profileName , Properties properties ) { try { File file = folder . newFile ( MessageFormat . format ( WindGateTestHelper . TESTING_PROFILE_PATH , profileName ) ) ; FileOutputStream out = new FileOutputStream ( file ) ; try { properties . store ( out , "" ) ; } finally { out . close ( ) ; } } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } package com . asakusafw . testdriver . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . Closeable ; import java . io . File ; import java . io . IOException ; import java . util . Collections ; import java . util . Properties ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateProcessDescription ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . file . resource . FileResourceProvider ; import com . asakusafw . windgate . file . resource . Preparable ; public class WindGateTestHelperTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Rule public ProfileContext context = new ProfileContext ( ) ; @ Test public void createImporterProcessScript ( ) throws Exception { File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateImporterDescription description = new MockImporterDescription ( String . class , "" , driver ) ; ProcessScript < String > script = WindGateTestHelper . createProcessScript ( String . class , description ) ; assertThat ( script . getDataClass ( ) , equalTo ( String . class ) ) ; assertThat ( script . getSourceScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( script . getSourceScript ( ) . getConfiguration ( ) , is ( driver . getConfiguration ( ) ) ) ; } @ Test public void createExporterProcessScript ( ) throws Exception { File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateExporterDescription description = new MockExporterDescription ( String . class , "" , driver ) ; ProcessScript < String > script = WindGateTestHelper . createProcessScript ( String . class , description ) ; assertThat ( script . getDataClass ( ) , equalTo ( String . class ) ) ; assertThat ( script . getDrainScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( script . getDrainScript ( ) . getConfiguration ( ) , is ( driver . getConfiguration ( ) ) ) ; } @ Test public void createResourceManipulator ( ) throws Exception { Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , FileResourceProvider . class . getName ( ) ) ; context . put ( "" , profile ) ; File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateImporterDescription description = new MockImporterDescription ( String . class , "" , driver ) ; ResourceManipulator manipulator = WindGateTestHelper . createResourceManipulator ( new TestContext . Empty ( ) , description , new ParameterList ( ) ) ; assertThat ( file . exists ( ) , is ( true ) ) ; ProcessScript < String > script = WindGateTestHelper . createProcessScript ( String . class , description ) ; manipulator . cleanupSource ( script ) ; assertThat ( file . exists ( ) , is ( false ) ) ; } @ Test public void createResourceManipulator_missing_profile ( ) throws Exception { File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateImporterDescription description = new MockImporterDescription ( String . class , "" , driver ) ; try { WindGateTestHelper . createResourceManipulator ( new TestContext . Empty ( ) , description , new ParameterList ( ) ) ; fail ( ) ; } catch ( IOException e ) { } } @ Test public void createResourceManipulator_invalid_profile ( ) throws Exception { Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , "" ) ; context . put ( "" , profile ) ; File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateImporterDescription description = new MockImporterDescription ( String . class , "" , driver ) ; try { WindGateTestHelper . createResourceManipulator ( new TestContext . Empty ( ) , description , new ParameterList ( ) ) ; fail ( ) ; } catch ( IOException e ) { } } @ Test public void createResourceManipulator_missing_resource ( ) throws Exception { Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , FileResourceProvider . class . getName ( ) ) ; context . put ( "" , profile ) ; File file = folder . newFile ( "" ) ; DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; WindGateImporterDescription description = new MockImporterDescription ( String . class , "" , driver ) ; try { WindGateTestHelper . createResourceManipulator ( new TestContext . Empty ( ) , description , new ParameterList ( ) ) ; fail ( ) ; } catch ( IOException e ) { } } @ Test public void prepare ( ) throws Exception { MockDriver driver = new MockDriver ( ) ; WindGateTestHelper . prepare ( driver ) ; assertThat ( driver . prepared , is ( true ) ) ; assertThat ( driver . closed , is ( false ) ) ; } @ Test public void prepare_fail ( ) throws Exception { MockDriver driver = new MockDriver ( ) ; driver . failOnPrepare = true ; try { WindGateTestHelper . prepare ( driver ) ; fail ( ) ; } catch ( IOException e ) { assertThat ( e . getMessage ( ) , is ( "" ) ) ; } assertThat ( driver . prepared , is ( true ) ) ; assertThat ( driver . closed , is ( true ) ) ; } @ Test public void prepare_close_fail ( ) throws Exception { MockDriver driver = new MockDriver ( ) ; driver . failOnPrepare = true ; driver . failOnClose = true ; try { WindGateTestHelper . prepare ( driver ) ; fail ( ) ; } catch ( IOException e ) { assertThat ( e . getMessage ( ) , is ( "" ) ) ; } assertThat ( driver . prepared , is ( true ) ) ; assertThat ( driver . closed , is ( true ) ) ; } private static class MockDriver implements Preparable , Closeable { boolean failOnPrepare ; boolean failOnClose ; boolean prepared ; boolean closed ; MockDriver ( ) { return ; } @ Override public void prepare ( ) throws IOException { prepared = true ; if ( failOnPrepare ) { throw new IOException ( "" ) ; } } @ Override public void close ( ) throws IOException { closed = true ; if ( failOnClose ) { throw new IOException ( "" ) ; } } } } package com . asakusafw . testdriver . windgate ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . DriverScript ; public class MockExporterDescription extends WindGateExporterDescription { private final Class < ? > modelType ; private final String profileName ; private final DriverScript driverScript ; MockExporterDescription ( Class < ? > modelType , String profileName , DriverScript driverScript ) { this . modelType = modelType ; this . profileName = profileName ; this . driverScript = driverScript ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getProfileName ( ) { return profileName ; } @ Override public DriverScript getDriverScript ( ) { return driverScript ; } } package com . asakusafw . testdriver . windgate ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . DriverScript ; public class MockImporterDescription extends WindGateImporterDescription { private final Class < ? > modelType ; private final String profileName ; private final DriverScript driverScript ; MockImporterDescription ( Class < ? > modelType , String profileName , DriverScript driverScript ) { this . modelType = modelType ; this . profileName = profileName ; this . driverScript = driverScript ; } @ Override public Class < ? > getModelType ( ) { return modelType ; } @ Override public String getProfileName ( ) { return profileName ; } @ Override public DriverScript getDriverScript ( ) { return driverScript ; } } package com . asakusafw . testdriver . windgate ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . ObjectOutputStream ; import java . net . URI ; import java . util . Collections ; import java . util . Properties ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . testdriver . core . DataModelReflection ; import com . asakusafw . testdriver . core . DataModelSource ; import com . asakusafw . testdriver . core . DataModelSourceProvider ; import com . asakusafw . testdriver . core . SpiDataModelSourceProvider ; import com . asakusafw . testdriver . core . TestContext ; import com . asakusafw . vocabulary . windgate . WindGateExporterDescription ; import com . asakusafw . vocabulary . windgate . WindGateImporterDescription ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . file . resource . FileResourceProvider ; public class WindGateSourceProviderTest { private static final TestContext EMPTY = new TestContext . Empty ( ) ; @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Rule public ProfileContext context = new ProfileContext ( ) ; volatile static File file ; @ Before public void setUp ( ) throws Exception { file = folder . newFile ( "" ) ; Properties profile = context . getTemplate ( ) ; profile . setProperty ( "" , FileResourceProvider . class . getName ( ) ) ; context . put ( "" , profile ) ; FileOutputStream output = new FileOutputStream ( file ) ; try { ObjectOutputStream out = new ObjectOutputStream ( output ) ; out . writeObject ( "" ) ; out . writeObject ( "" ) ; out . writeObject ( "" ) ; out . close ( ) ; } finally { output . close ( ) ; } } @ Test public void open_importer ( ) throws Exception { DataModelSourceProvider provider = new SpiDataModelSourceProvider ( getClass ( ) . getClassLoader ( ) ) ; URI uri = new URI ( "" + MockImporter . class . getName ( ) ) ; ValueDefinition < String > definition = ValueDefinition . of ( String . class ) ; DataModelSource source = provider . open ( definition , uri , EMPTY ) ; try { DataModelReflection r1 = source . next ( ) ; assertThat ( r1 , is ( notNullValue ( ) ) ) ; assertThat ( definition . toObject ( r1 ) , is ( "" ) ) ; DataModelReflection r2 = source . next ( ) ; assertThat ( r2 , is ( notNullValue ( ) ) ) ; assertThat ( definition . toObject ( r2 ) , is ( "" ) ) ; DataModelReflection r3 = source . next ( ) ; assertThat ( r3 , is ( notNullValue ( ) ) ) ; assertThat ( definition . toObject ( r3 ) , is ( "" ) ) ; DataModelReflection r4 = source . next ( ) ; assertThat ( r4 , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void open_exporter ( ) throws Exception { DataModelSourceProvider provider = new SpiDataModelSourceProvider ( getClass ( ) . getClassLoader ( ) ) ; URI uri = new URI ( "" + MockExporter . class . getName ( ) ) ; ValueDefinition < String > definition = ValueDefinition . of ( String . class ) ; DataModelSource source = provider . open ( definition , uri , EMPTY ) ; try { DataModelReflection r1 = source . next ( ) ; assertThat ( r1 , is ( notNullValue ( ) ) ) ; assertThat ( definition . toObject ( r1 ) , is ( "" ) ) ; DataModelReflection r2 = source . next ( ) ; assertThat ( r2 , is ( notNullValue ( ) ) ) ; assertThat ( definition . toObject ( r2 ) , is ( "" ) ) ; DataModelReflection r3 = source . next ( ) ; assertThat ( r3 , is ( notNullValue ( ) ) ) ; assertThat ( definition . toObject ( r3 ) , is ( "" ) ) ; DataModelReflection r4 = source . next ( ) ; assertThat ( r4 , is ( nullValue ( ) ) ) ; } finally { source . close ( ) ; } } @ Test public void invalid_scheme ( ) throws Exception { DataModelSourceProvider provider = new WindGateSourceProvider ( ) ; URI uri = new URI ( "" + MockExporter . class . getName ( ) ) ; ValueDefinition < String > definition = ValueDefinition . of ( String . class ) ; DataModelSource source = provider . open ( definition , uri , EMPTY ) ; assertThat ( source , is ( nullValue ( ) ) ) ; } @ Test ( expected = IOException . class ) public void unknown_class ( ) throws Exception { DataModelSourceProvider provider = new WindGateSourceProvider ( ) ; URI uri = new URI ( "" ) ; ValueDefinition < String > definition = ValueDefinition . of ( String . class ) ; provider . open ( definition , uri , EMPTY ) ; } @ Test ( expected = IOException . class ) public void unexpected_class ( ) throws Exception { DataModelSourceProvider provider = new WindGateSourceProvider ( ) ; URI uri = new URI ( "" + String . class . getName ( ) ) ; ValueDefinition < String > definition = ValueDefinition . of ( String . class ) ; provider . open ( definition , uri , EMPTY ) ; } public static class MockImporter extends WindGateImporterDescription { @ Override public Class < ? > getModelType ( ) { return String . class ; } @ Override public String getProfileName ( ) { return "" ; } @ Override public DriverScript getDriverScript ( ) { DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; return driver ; } } public static class MockExporter extends WindGateExporterDescription { @ Override public Class < ? > getModelType ( ) { return String . class ; } @ Override public String getProfileName ( ) { return "" ; } @ Override public DriverScript getDriverScript ( ) { DriverScript driver = new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getAbsolutePath ( ) ) ) ; return driver ; } } } package com . asakusafw . windgate . jdbc ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . windgate . core . WindGateLogger ; public class JdbcLogger extends WindGateLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public JdbcLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . windgate . jdbc ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . resource . ResourceProvider ; public class JdbcResourceProvider extends ResourceProvider { static final Logger LOG = LoggerFactory . getLogger ( JdbcResourceProvider . class ) ; private volatile JdbcProfile jdbcProfile ; @ Override protected void configure ( ResourceProfile profile ) throws IOException { LOG . debug ( "" , profile . getName ( ) ) ; try { this . jdbcProfile = JdbcProfile . convert ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getName ( ) ) , e ) ; } } @ Override public ResourceMirror create ( String sessionId , ParameterList arguments ) throws IOException { LOG . debug ( "" , jdbcProfile . getResourceName ( ) , sessionId ) ; return new JdbcResourceMirror ( jdbcProfile , arguments ) ; } @ Override public ResourceManipulator createManipulator ( ParameterList arguments ) throws IOException { if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , jdbcProfile . getResourceName ( ) ) ; return new JdbcResourceManipulator ( jdbcProfile , arguments ) ; } } package com . asakusafw . windgate . jdbc ; import java . io . IOException ; import java . sql . Connection ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . util . ProcessUtil ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess ; public class JdbcResourceManipulator extends ResourceManipulator { static final Logger LOG = LoggerFactory . getLogger ( JdbcResourceManipulator . class ) ; private final JdbcProfile profile ; private final ParameterList arguments ; public JdbcResourceManipulator ( JdbcProfile profile , ParameterList arguments ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . arguments = arguments ; } @ Override public String getName ( ) { return profile . getResourceName ( ) ; } @ Override public void cleanupSource ( ProcessScript < ? > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } JdbcScript < ? > jdbc = createOppositeJdbcScript ( script , DriverScript . Kind . SOURCE ) ; truncate ( jdbc ) ; } @ Override public void cleanupDrain ( ProcessScript < ? > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } JdbcScript < ? > jdbc = createOppositeJdbcScript ( script , DriverScript . Kind . DRAIN ) ; truncate ( jdbc ) ; } private void truncate ( JdbcScript < ? > jdbc ) throws IOException { assert jdbc != null ; Connection conn = profile . openConnection ( ) ; Statement statement = null ; try { LOG . info ( "" , jdbc . getTableName ( ) , jdbc . getName ( ) ) ; statement = conn . createStatement ( ) ; statement . execute ( profile . getTruncateStatement ( jdbc . getTableName ( ) ) ) ; conn . commit ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { LOG . warn ( MessageFormat . format ( "" , jdbc . getName ( ) , jdbc . getTableName ( ) ) , ex ) ; } } finally { close ( statement ) ; close ( conn ) ; } } @ Override public < T > SourceDriver < T > createSourceForSource ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } JdbcScript < T > jdbc = JdbcResourceUtil . convert ( profile , script , arguments , DriverScript . Kind . SOURCE ) ; T object = ProcessUtil . newDataModel ( profile . getResourceName ( ) , script ) ; boolean succeed = false ; Connection conn = profile . openConnection ( ) ; try { JdbcSourceDriver < T > result = new JdbcSourceDriver < T > ( profile , jdbc , conn , object ) ; succeed = true ; return result ; } finally { if ( succeed == false ) { close ( conn ) ; } } } @ Override public < T > DrainDriver < T > createDrainForSource ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } JdbcScript < T > jdbc = createOppositeJdbcScript ( script , DriverScript . Kind . SOURCE ) ; boolean succeed = false ; Connection conn = profile . openConnection ( ) ; try { JdbcDrainDriver < T > result = new JdbcDrainDriver < T > ( profile , jdbc , conn , false ) ; succeed = true ; return result ; } finally { if ( succeed == false ) { close ( conn ) ; } } } @ Override public < T > SourceDriver < T > createSourceForDrain ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } JdbcScript < T > jdbc = createOppositeJdbcScript ( script , DriverScript . Kind . DRAIN ) ; T object = ProcessUtil . newDataModel ( profile . getResourceName ( ) , script ) ; boolean succeed = false ; Connection conn = profile . openConnection ( ) ; try { JdbcSourceDriver < T > result = new JdbcSourceDriver < T > ( profile , jdbc , conn , object ) ; succeed = true ; return result ; } finally { if ( succeed == false ) { close ( conn ) ; } } } @ Override public < T > DrainDriver < T > createDrainForDrain ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } JdbcScript < T > jdbc = JdbcResourceUtil . convert ( profile , script , arguments , DriverScript . Kind . DRAIN ) ; boolean succeed = false ; Connection conn = profile . openConnection ( ) ; try { JdbcDrainDriver < T > result = new JdbcDrainDriver < T > ( profile , jdbc , conn , false ) ; succeed = true ; return result ; } finally { if ( succeed == false ) { close ( conn ) ; } } } private void close ( Statement statement ) { if ( statement != null ) { try { statement . close ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { LOG . warn ( MessageFormat . format ( "" , getName ( ) ) , ex ) ; } } } } private void close ( Connection conn ) { assert conn != null ; try { conn . close ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { LOG . warn ( MessageFormat . format ( "" , getName ( ) ) , ex ) ; } } } private < T > JdbcScript < T > createOppositeJdbcScript ( ProcessScript < T > process , DriverScript . Kind kind ) throws IOException { assert process != null ; assert kind != null ; DriverScript driver = process . getDriverScript ( kind ) ; if ( driver . getResourceName ( ) . equals ( getName ( ) ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , process . getName ( ) , kind . prefix ) ) ; } ProcessScript < T > opposite ; if ( kind == DriverScript . Kind . SOURCE ) { opposite = createDrainProcessFromSource ( process ) ; } else if ( kind == DriverScript . Kind . DRAIN ) { opposite = createSourceProcessFromDrain ( process ) ; } else { throw new AssertionError ( kind ) ; } return JdbcResourceUtil . convert ( profile , opposite , arguments , kind . opposite ( ) ) ; } private < T > ProcessScript < T > createSourceProcessFromDrain ( ProcessScript < T > script ) { assert script != null ; Map < String , String > rebuilt = new HashMap < String , String > ( script . getDrainScript ( ) . getConfiguration ( ) ) ; rebuilt . remove ( JdbcProcess . CONDITION . key ( ) ) ; rebuilt . remove ( JdbcProcess . OPERATION . key ( ) ) ; return new ProcessScript < T > ( script . getName ( ) , script . getProcessType ( ) , script . getDataClass ( ) , new DriverScript ( script . getDrainScript ( ) . getResourceName ( ) , rebuilt ) , script . getSourceScript ( ) ) ; } private < T > ProcessScript < T > createDrainProcessFromSource ( ProcessScript < T > script ) { assert script != null ; Map < String , String > rebuilt = new HashMap < String , String > ( script . getSourceScript ( ) . getConfiguration ( ) ) ; rebuilt . remove ( JdbcProcess . CONDITION . key ( ) ) ; rebuilt . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; return new ProcessScript < T > ( script . getName ( ) , script . getProcessType ( ) , script . getDataClass ( ) , script . getDrainScript ( ) , new DriverScript ( script . getSourceScript ( ) . getResourceName ( ) , rebuilt ) ) ; } } package com . asakusafw . windgate . jdbc ; package com . asakusafw . windgate . jdbc ; import java . io . IOException ; import java . sql . Connection ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport . DataModelResultSet ; public class JdbcSourceDriver < T > implements SourceDriver < T > { static final WindGateLogger WGLOG = new JdbcLogger ( JdbcSourceDriver . class ) ; static final Logger LOG = LoggerFactory . getLogger ( JdbcSourceDriver . class ) ; private final JdbcProfile profile ; private final JdbcScript < T > script ; private final Connection connection ; private final T object ; private Statement statement ; private ResultSet resultSet ; private DataModelResultSet < ? super T > support ; private boolean sawNext ; public JdbcSourceDriver ( JdbcProfile profile , JdbcScript < T > script , Connection connection , T object ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } if ( connection == null ) { throw new IllegalArgumentException ( "" ) ; } if ( object == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . script = script ; this . connection = connection ; this . object = object ; } @ Override public void prepare ( ) throws IOException { LOG . debug ( "" , profile . getResourceName ( ) , script . getTableName ( ) ) ; try { this . resultSet = prepareResultSet ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . error ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) , e ) ; } LOG . debug ( "" , script . getSupport ( ) . getClass ( ) . getName ( ) , script . getColumnNames ( ) ) ; support = script . getSupport ( ) . createResultSetSupport ( resultSet , script . getColumnNames ( ) ) ; } private ResultSet prepareResultSet ( ) throws SQLException { String sql = createSql ( ) ; statement = connection . createStatement ( ) ; boolean succeed = false ; try { WGLOG . info ( "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; if ( profile . getBatchGetUnit ( ) != ) { statement . setFetchSize ( profile . getBatchGetUnit ( ) ) ; } LOG . debug ( "" , sql ) ; ResultSet result = statement . executeQuery ( sql ) ; LOG . debug ( "" , sql ) ; WGLOG . info ( "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; succeed = true ; return result ; } finally { if ( succeed == false ) { try { statement . close ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . warn ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } } } } } private String createSql ( ) { assert script . getColumnNames ( ) . isEmpty ( ) == false ; if ( script . getCondition ( ) != null ) { assert script . getCondition ( ) . isEmpty ( ) == false ; return MessageFormat . format ( "" , script . getTableName ( ) , JdbcResourceUtil . join ( script . getColumnNames ( ) ) , script . getCondition ( ) ) ; } else { return MessageFormat . format ( "" , script . getTableName ( ) , JdbcResourceUtil . join ( script . getColumnNames ( ) ) ) ; } } @ Override public boolean next ( ) throws IOException { try { sawNext = support . next ( object ) ; return sawNext ; } catch ( SQLException e ) { sawNext = false ; for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . error ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getTableName ( ) ) , e ) ; } } @ Override public T get ( ) throws IOException { if ( sawNext == false ) { throw new IOException ( "" ) ; } return object ; } @ Override public void close ( ) throws IOException { LOG . debug ( "" , profile . getResourceName ( ) , script . getTableName ( ) ) ; sawNext = false ; if ( resultSet != null ) { try { resultSet . close ( ) ; resultSet = null ; support = null ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . warn ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } } try { if ( statement != null ) { statement . close ( ) ; } } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . warn ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } } } try { connection . close ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . warn ( ex , "" , profile . getResourceName ( ) , script . getName ( ) ) ; } } } } package com . asakusafw . windgate . jdbc ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess . OperationKind ; final class JdbcResourceUtil { static final WindGateLogger WGLOG = new JdbcLogger ( JdbcResourceUtil . class ) ; static final Logger LOG = LoggerFactory . getLogger ( JdbcResourceUtil . class ) ; private JdbcResourceUtil ( ) { return ; } static String join ( Iterable < String > list ) { assert list != null ; Iterator < String > iterator = list . iterator ( ) ; assert iterator . hasNext ( ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( iterator . next ( ) ) ; while ( iterator . hasNext ( ) ) { buf . append ( "" ) ; buf . append ( iterator . next ( ) ) ; } return buf . toString ( ) ; } static < T > JdbcScript < T > convert ( JdbcProfile profile , ProcessScript < T > process , ParameterList arguments , DriverScript . Kind kind ) throws IOException { assert profile != null ; assert process != null ; assert arguments != null ; assert kind != null ; String supportClassName = extract ( profile , process , kind , JdbcProcess . JDBC_SUPPORT , true ) ; DataModelJdbcSupport < ? super T > support = loadSupport ( profile , process , supportClassName ) ; String tableName = extract ( profile , process , kind , JdbcProcess . TABLE , true ) ; String columnNameList = extract ( profile , process , kind , JdbcProcess . COLUMNS , true ) ; List < String > columnNames = Arrays . asList ( columnNameList . split ( "" ) ) ; if ( support . isSupported ( columnNames ) == false ) { WGLOG . error ( "" , profile . getResourceName ( ) , process . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , process . getName ( ) , support . getClass ( ) . getName ( ) , columnNames ) ) ; } String condition = extract ( profile , process , kind , JdbcProcess . CONDITION , false ) ; if ( kind == DriverScript . Kind . SOURCE ) { if ( condition == null || condition . isEmpty ( ) ) { LOG . debug ( "" , profile . getResourceName ( ) , process . getName ( ) ) ; condition = null ; } else { try { condition = arguments . replace ( condition , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( "" , profile . getResourceName ( ) , process . getName ( ) , kind . prefix , JdbcProcess . CONDITION . key ( ) , condition ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , process . getName ( ) , kind , JdbcProcess . CONDITION . key ( ) , condition ) , e ) ; } } } if ( kind == DriverScript . Kind . DRAIN ) { condition = null ; String operationString = extract ( profile , process , kind , JdbcProcess . OPERATION , true ) ; JdbcProcess . OperationKind op = JdbcProcess . OperationKind . find ( operationString ) ; if ( op != OperationKind . INSERT_AFTER_TRUNCATE ) { WGLOG . error ( "" , profile . getResourceName ( ) , process . getName ( ) , kind . prefix , JdbcProcess . OPERATION . key ( ) , operationString ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , process . getName ( ) , kind , JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE , operationString ) ) ; } } return new JdbcScript < T > ( process . getName ( ) , support , tableName , columnNames , condition ) ; } private static String extract ( JdbcProfile profile , ProcessScript < ? > process , DriverScript . Kind kind , JdbcProcess item , boolean mandatory ) throws IOException { assert process != null ; assert kind != null ; assert item != null ; Map < String , String > conf = process . getDriverScript ( kind ) . getConfiguration ( ) ; String value = conf . get ( item . key ( ) ) ; if ( mandatory && ( value == null || value . isEmpty ( ) ) ) { WGLOG . error ( "" , profile . getResourceName ( ) , process . getName ( ) , kind . prefix , item . key ( ) , value ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , process . getName ( ) , kind , item . key ( ) ) ) ; } return value == null ? null : value . trim ( ) ; } @ SuppressWarnings ( "" ) private static < T > DataModelJdbcSupport < ? super T > loadSupport ( JdbcProfile profile , ProcessScript < T > script , String supportClassName ) throws IOException { assert script != null ; assert supportClassName != null ; LOG . debug ( "" , new Object [ ] { supportClassName , profile . getResourceName ( ) , script . getName ( ) , } ) ; Class < ? > supportClass ; try { supportClass = Class . forName ( supportClassName , true , profile . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { WGLOG . error ( e , "" , profile . getResourceName ( ) , script . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getName ( ) , supportClassName ) , e ) ; } if ( DataModelJdbcSupport . class . isAssignableFrom ( supportClass ) == false ) { WGLOG . error ( "" , profile . getResourceName ( ) , script . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getName ( ) , supportClass . getName ( ) , DataModelJdbcSupport . class . getName ( ) ) ) ; } DataModelJdbcSupport < ? > obj ; try { obj = supportClass . asSubclass ( DataModelJdbcSupport . class ) . newInstance ( ) ; } catch ( Exception e ) { WGLOG . error ( e , "" , profile . getResourceName ( ) , script . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getName ( ) , supportClass . getName ( ) ) , e ) ; } if ( obj . getSupportedType ( ) . isAssignableFrom ( script . getDataClass ( ) ) == false ) { WGLOG . error ( "" , profile . getResourceName ( ) , script . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getName ( ) , supportClass . getName ( ) , script . getDataClass ( ) . getName ( ) ) ) ; } return ( DataModelJdbcSupport < ? super T > ) obj ; } } package com . asakusafw . windgate . jdbc ; import java . io . IOException ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . Collections ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport . DataModelPreparedStatement ; public class JdbcDrainDriver < T > implements DrainDriver < T > { static final WindGateLogger WGLOG = new JdbcLogger ( JdbcDrainDriver . class ) ; static final Logger LOG = LoggerFactory . getLogger ( JdbcDrainDriver . class ) ; private final JdbcProfile profile ; private final JdbcScript < T > script ; private final Connection connection ; private final boolean truncateOnPrepare ; private final long batchPutUnit ; private long putLimitRest ; private long putCount ; private PreparedStatement statement ; private DataModelPreparedStatement < ? super T > support ; private boolean sawError ; public JdbcDrainDriver ( JdbcProfile profile , JdbcScript < T > script , Connection connection , boolean truncateOnPrepare ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } if ( connection == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . script = script ; this . connection = connection ; this . batchPutUnit = profile . getBatchPutUnit ( ) ; this . truncateOnPrepare = truncateOnPrepare ; } @ Override public void prepare ( ) throws IOException { LOG . debug ( "" , profile . getResourceName ( ) , script . getTableName ( ) ) ; try { if ( truncateOnPrepare ) { truncate ( ) ; } } catch ( SQLException e ) { sawError = true ; for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . error ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) ) ; } throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) , e ) ; } try { this . statement = prepareStatement ( ) ; } catch ( SQLException e ) { sawError = true ; for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . error ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) , e ) ; } LOG . debug ( "" , script . getSupport ( ) . getClass ( ) . getName ( ) , script . getColumnNames ( ) ) ; support = script . getSupport ( ) . createPreparedStatementSupport ( statement , script . getColumnNames ( ) ) ; putLimitRest = batchPutUnit ; } private void truncate ( ) throws SQLException { String sql = profile . getTruncateStatement ( script . getTableName ( ) ) ; Statement truncater = connection . createStatement ( ) ; try { WGLOG . info ( "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) ) ; LOG . debug ( "" , sql ) ; truncater . execute ( sql ) ; LOG . debug ( "" , sql ) ; } finally { truncater . close ( ) ; } } private PreparedStatement prepareStatement ( ) throws SQLException { String sql = createSql ( ) ; LOG . debug ( "" , sql ) ; return connection . prepareStatement ( sql ) ; } private String createSql ( ) { assert script . getColumnNames ( ) . isEmpty ( ) == false ; assert script . getCondition ( ) == null ; return MessageFormat . format ( "" , script . getTableName ( ) , JdbcResourceUtil . join ( script . getColumnNames ( ) ) , JdbcResourceUtil . join ( Collections . nCopies ( script . getColumnNames ( ) . size ( ) , "" ) ) ) ; } @ Override public void put ( T object ) throws IOException { try { support . setParameters ( object ) ; statement . addBatch ( ) ; } catch ( SQLException e ) { sawError = true ; for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . error ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getTableName ( ) , object ) , e ) ; } putLimitRest -- ; if ( putLimitRest == ) { flush ( ) ; } assert putLimitRest > ; } private void flush ( ) throws IOException { assert putLimitRest != batchPutUnit ; try { LOG . debug ( "" , batchPutUnit - putLimitRest , script . getTableName ( ) ) ; statement . executeBatch ( ) ; connection . commit ( ) ; putCount += batchPutUnit - putLimitRest ; putLimitRest = batchPutUnit ; } catch ( SQLException e ) { sawError = true ; for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . error ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , script . getTableName ( ) ) , e ) ; } } @ Override public void close ( ) throws IOException { LOG . debug ( "" , profile . getResourceName ( ) , script . getTableName ( ) ) ; IOException occurred = null ; if ( statement != null ) { if ( sawError == false && putLimitRest != batchPutUnit ) { try { flush ( ) ; } catch ( IOException e ) { occurred = e ; } } try { statement . close ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . warn ( ex , "" , profile . getResourceName ( ) , script . getName ( ) , script . getTableName ( ) , script . getColumnNames ( ) ) ; } } } try { connection . close ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . warn ( ex , "" , profile . getResourceName ( ) , script . getName ( ) ) ; } } if ( occurred != null ) { throw occurred ; } } } package com . asakusafw . windgate . jdbc ; import java . io . IOException ; import java . sql . Connection ; import java . sql . Driver ; import java . sql . DriverManager ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import java . util . concurrent . TimeUnit ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . util . PropertiesUtil ; public class JdbcProfile { static final WindGateLogger WGLOG = new JdbcLogger ( JdbcProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( JdbcProfile . class ) ; public static final String KEY_DRIVER = "" ; public static final String KEY_URL = "" ; public static final String KEY_USER = "" ; public static final String KEY_PASSWORD = "" ; public static final String KEY_BATCH_PUT_UNIT = "" ; public static final String KEY_BATCH_GET_UNIT = "" ; public static final String KEY_CONNECT_RETRY_COUNT = "" ; public static final String KEY_CONNECT_RETRY_INTERVAL = "" ; public static final String KEY_TRUNCATE_STATEMENT = "" ; public static final String KEY_PREFIX_PROPERTIES = "" ; public static final int DEFAULT_BATCH_GET_UNIT = ; public static final long DEFAULT_BATCH_PUT_UNIT = Long . MAX_VALUE ; public static final int DEFAULT_CONNECT_RETRY_COUNT = ; public static final int DEFAULT_CONNECT_RETRY_INTERVAL = ; public static final String DEFAULT_TRUNCATE_STATEMENT = "" ; private final String resourceName ; private final ClassLoader classLoader ; private final String driver ; private final String url ; private final String user ; private final String password ; private final Map < String , String > connectionProperties ; private volatile int batchGetUnit = DEFAULT_BATCH_GET_UNIT ; private volatile long batchPutUnit = DEFAULT_BATCH_PUT_UNIT ; private volatile int connectRetryCount = DEFAULT_CONNECT_RETRY_COUNT ; private volatile int connectRetryInterval = DEFAULT_CONNECT_RETRY_INTERVAL ; private volatile String truncateStatement = DEFAULT_TRUNCATE_STATEMENT ; public JdbcProfile ( String resourceName , ClassLoader classLoader , String driver , String url , String user , String password , long batchPutUnit ) { this ( resourceName , classLoader , driver , url , user , password , Collections . < String , String > emptyMap ( ) ) ; setBatchPutUnit0 ( batchPutUnit ) ; } public JdbcProfile ( String resourceName , ClassLoader classLoader , String driver , String url , String user , String password , Map < String , String > connectionProperties ) { if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( driver == null ) { throw new IllegalArgumentException ( "" ) ; } if ( url == null ) { throw new IllegalArgumentException ( "" ) ; } if ( connectionProperties == null ) { throw new IllegalArgumentException ( "" ) ; } this . resourceName = resourceName ; this . classLoader = classLoader == null ? ClassLoader . getSystemClassLoader ( ) : classLoader ; this . driver = driver ; this . url = url ; this . user = user ; this . password = password ; this . connectionProperties = Collections . unmodifiableMap ( connectionProperties ) ; } public static JdbcProfile convert ( ResourceProfile profile ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } String resourceName = profile . getName ( ) ; ClassLoader classLoader = profile . getContext ( ) . getClassLoader ( ) ; String driver = extract ( profile , KEY_DRIVER , true ) ; String url = extract ( profile , KEY_URL , true ) ; String user = extract ( profile , KEY_USER , false ) ; String password = extract ( profile , KEY_PASSWORD , false ) ; Map < String , String > connectionProperties = extractConnectionProperties ( profile ) ; JdbcProfile result = new JdbcProfile ( resourceName , classLoader , driver , url , user , password , connectionProperties ) ; int batchGetUnit = extractInt ( profile , KEY_BATCH_GET_UNIT , , DEFAULT_BATCH_GET_UNIT ) ; long batchPutUnit = extractLong ( profile , KEY_BATCH_PUT_UNIT , , DEFAULT_BATCH_PUT_UNIT ) ; int connectRetryCount = extractInt ( profile , KEY_CONNECT_RETRY_COUNT , , DEFAULT_CONNECT_RETRY_COUNT ) ; int connectRetryInterval = extractInt ( profile , KEY_CONNECT_RETRY_INTERVAL , , DEFAULT_CONNECT_RETRY_INTERVAL ) ; String truncateStatement = extract ( profile , KEY_TRUNCATE_STATEMENT , false ) ; if ( truncateStatement == null ) { truncateStatement = DEFAULT_TRUNCATE_STATEMENT ; } try { MessageFormat . format ( truncateStatement , "" ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( "" , profile . getName ( ) , KEY_TRUNCATE_STATEMENT , truncateStatement ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , KEY_TRUNCATE_STATEMENT , truncateStatement ) , e ) ; } result . setBatchGetUnit ( batchGetUnit ) ; result . setBatchPutUnit ( batchPutUnit ) ; result . setConnectRetryCount ( connectRetryCount ) ; result . setConnectRetryInterval ( connectRetryInterval ) ; result . setTruncateStatement ( truncateStatement ) ; return result ; } private static Map < String , String > extractConnectionProperties ( ResourceProfile profile ) { assert profile != null ; Map < String , String > raw = PropertiesUtil . createPrefixMap ( profile . getConfiguration ( ) , KEY_PREFIX_PROPERTIES ) ; Map < String , String > results = new HashMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : raw . entrySet ( ) ) { String value = resolve ( profile , KEY_PREFIX_PROPERTIES + entry . getKey ( ) , entry . getValue ( ) ) ; results . put ( entry . getKey ( ) , value ) ; } return results ; } private static int extractInt ( ResourceProfile profile , String key , int minimumValue , int defaultValue ) { assert profile != null ; assert key != null ; String valueString = extract ( profile , key , false ) ; int value ; try { if ( valueString == null || valueString . trim ( ) . isEmpty ( ) ) { value = defaultValue ; } else { value = Integer . parseInt ( valueString ) ; } } catch ( NumberFormatException e ) { WGLOG . error ( "" , profile . getName ( ) , key , valueString ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , key , valueString ) , e ) ; } if ( value < minimumValue ) { WGLOG . error ( "" , profile . getName ( ) , key , valueString ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , value , valueString ) ) ; } return value ; } private static long extractLong ( ResourceProfile profile , String key , long minimumValue , long defaultValue ) { assert profile != null ; assert key != null ; String valueString = extract ( profile , key , false ) ; long value ; try { if ( valueString == null || valueString . isEmpty ( ) ) { value = defaultValue ; } else { value = Integer . parseInt ( valueString ) ; } } catch ( NumberFormatException e ) { WGLOG . error ( "" , profile . getName ( ) , key , valueString ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , key , valueString ) , e ) ; } if ( value < minimumValue ) { WGLOG . error ( "" , profile . getName ( ) , key , valueString ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , value , valueString ) ) ; } return value ; } private static String extract ( ResourceProfile profile , String configKey , boolean mandatory ) { assert profile != null ; assert configKey != null ; String value = profile . getConfiguration ( ) . get ( configKey ) ; if ( value == null ) { if ( mandatory == false ) { return null ; } else { WGLOG . error ( "" , profile . getName ( ) , configKey , null ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey ) ) ; } } return resolve ( profile , configKey , value . trim ( ) ) ; } private static String resolve ( ResourceProfile profile , String configKey , String value ) { assert profile != null ; assert configKey != null ; assert value != null ; try { return profile . getContext ( ) . getContextParameters ( ) . replace ( value , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , profile . getName ( ) , configKey , value ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey , value ) , e ) ; } } public String getResourceName ( ) { return resourceName ; } public ClassLoader getClassLoader ( ) { return classLoader ; } public Connection openConnection ( ) throws IOException { LOG . debug ( "" , url ) ; try { Class < ? extends Driver > driverClass = Class . forName ( driver , true , classLoader ) . asSubclass ( Driver . class ) ; Properties properties = new Properties ( ) ; properties . putAll ( getConnectionProperties ( ) ) ; if ( user != null ) { properties . put ( "" , user ) ; } if ( password != null ) { properties . put ( "" , password ) ; } Connection conn = null ; try { conn = openConnection ( driverClass , properties ) ; } catch ( Exception first ) { Exception last = first ; for ( int i = , n = getConnectRetryCount ( ) ; i <= n ; i ++ ) { WGLOG . warn ( last , "" , getResourceName ( ) , url , i , getConnectRetryCount ( ) ) ; try { TimeUnit . SECONDS . sleep ( getConnectRetryInterval ( ) ) ; conn = openConnection ( driverClass , properties ) ; break ; } catch ( Exception retry ) { last = retry ; } } if ( conn == null ) { throw last ; } } boolean succeed = false ; try { conn . setAutoCommit ( false ) ; succeed = true ; } finally { if ( succeed == false ) { LOG . debug ( "" , url ) ; conn . close ( ) ; } } return conn ; } catch ( Exception e ) { WGLOG . error ( e , "" , getResourceName ( ) , url ) ; throw new IOException ( MessageFormat . format ( "" , url ) , e ) ; } } private Connection openConnection ( Class < ? extends Driver > driverClass , Properties properties ) throws Exception { assert properties != null ; try { return DriverManager . getConnection ( url , properties ) ; } catch ( Exception e ) { try { Driver driverObject = driverClass . getConstructor ( ) . newInstance ( ) ; Connection connection = driverObject . connect ( url , properties ) ; if ( connection == null ) { throw new IllegalStateException ( MessageFormat . format ( "" , driverClass . getName ( ) , url ) ) ; } return connection ; } catch ( RuntimeException inner ) { LOG . debug ( MessageFormat . format ( "" , driverClass . getName ( ) , driverClass . getClassLoader ( ) ) , e ) ; } catch ( Exception inner ) { LOG . debug ( MessageFormat . format ( "" , driverClass . getName ( ) , driverClass . getClassLoader ( ) ) , e ) ; } throw e ; } } public Map < String , String > getConnectionProperties ( ) { return connectionProperties ; } public int getBatchGetUnit ( ) { return batchGetUnit ; } public void setBatchGetUnit ( int value ) { if ( value < ) { throw new IllegalArgumentException ( "" ) ; } this . batchGetUnit = value ; } public long getBatchPutUnit ( ) { return batchPutUnit ; } public void setBatchPutUnit ( long value ) { setBatchPutUnit0 ( value ) ; } private void setBatchPutUnit0 ( long value ) { if ( value <= ) { throw new IllegalArgumentException ( "" ) ; } this . batchPutUnit = value ; } public int getConnectRetryCount ( ) { return connectRetryCount ; } public void setConnectRetryCount ( int value ) { if ( value < ) { throw new IllegalArgumentException ( "" ) ; } this . connectRetryCount = value ; } public int getConnectRetryInterval ( ) { return connectRetryInterval ; } public void setConnectRetryInterval ( int value ) { if ( value < ) { throw new IllegalArgumentException ( "" ) ; } this . connectRetryInterval = value ; } public String getTruncateStatement ( String tableName ) { return MessageFormat . format ( truncateStatement , tableName ) ; } public void setTruncateStatement ( String pattern ) { if ( pattern == null ) { throw new IllegalArgumentException ( "" ) ; } MessageFormat . format ( pattern , "" ) ; this . truncateStatement = pattern ; } } package com . asakusafw . windgate . jdbc ; import java . io . IOException ; import java . sql . Connection ; import java . sql . SQLException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . util . ProcessUtil ; @ SimulationSupport public class JdbcResourceMirror extends ResourceMirror { static final WindGateLogger WGLOG = new JdbcLogger ( JdbcResourceMirror . class ) ; static final Logger LOG = LoggerFactory . getLogger ( JdbcResourceMirror . class ) ; private final JdbcProfile profile ; private final ParameterList arguments ; public JdbcResourceMirror ( JdbcProfile profile , ParameterList arguments ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . arguments = arguments ; } @ Override public String getName ( ) { return profile . getResourceName ( ) ; } @ Override public void prepare ( GateScript script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) ) ; for ( ProcessScript < ? > process : script . getProcesses ( ) ) { if ( process . getSourceScript ( ) . getResourceName ( ) . equals ( getName ( ) ) ) { JdbcResourceUtil . convert ( profile , process , arguments , DriverScript . Kind . SOURCE ) ; ProcessUtil . newDataModel ( profile . getResourceName ( ) , process ) ; } if ( process . getDrainScript ( ) . getResourceName ( ) . equals ( getName ( ) ) ) { JdbcResourceUtil . convert ( profile , process , arguments , DriverScript . Kind . DRAIN ) ; } } } @ Override public < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; JdbcScript < T > jdbcScript = JdbcResourceUtil . convert ( profile , script , arguments , DriverScript . Kind . SOURCE ) ; T object = ProcessUtil . newDataModel ( profile . getResourceName ( ) , script ) ; WGLOG . info ( "" , getName ( ) , script . getName ( ) ) ; Connection connection = profile . openConnection ( ) ; boolean succeed = false ; try { JdbcSourceDriver < T > driver = new JdbcSourceDriver < T > ( profile , jdbcScript , connection , object ) ; succeed = true ; return driver ; } finally { if ( succeed == false ) { try { LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; connection . close ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . warn ( ex , "" , getName ( ) , script . getName ( ) ) ; } } } } } @ Override public < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; JdbcScript < T > jdbcScript = JdbcResourceUtil . convert ( profile , script , arguments , DriverScript . Kind . DRAIN ) ; WGLOG . info ( "" , getName ( ) , script . getName ( ) ) ; Connection connection = profile . openConnection ( ) ; boolean succeed = false ; try { JdbcDrainDriver < T > driver = new JdbcDrainDriver < T > ( profile , jdbcScript , connection , true ) ; succeed = true ; return driver ; } finally { if ( succeed == false ) { try { LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; connection . close ( ) ; } catch ( SQLException e ) { for ( SQLException ex = e ; ex != null ; ex = ex . getNextException ( ) ) { WGLOG . warn ( ex , "" , getName ( ) , script . getName ( ) ) ; } } } } } @ Override public void close ( ) throws IOException { LOG . debug ( "" , getName ( ) ) ; } } package com . asakusafw . windgate . jdbc ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; public class JdbcScript < T > { private final String name ; private final DataModelJdbcSupport < ? super T > support ; private final String tableName ; private final List < String > columnNames ; private final String condition ; public JdbcScript ( String name , DataModelJdbcSupport < ? super T > support , String tableName , List < String > columnNames , String condition ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( support == null ) { throw new IllegalArgumentException ( "" ) ; } if ( tableName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( columnNames == null ) { throw new IllegalArgumentException ( "" ) ; } if ( condition != null && isEmpty ( condition ) ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . support = support ; this . tableName = tableName ; for ( String columnName : columnNames ) { if ( isEmpty ( columnName ) ) { throw new IllegalArgumentException ( "" ) ; } } this . columnNames = Collections . unmodifiableList ( new ArrayList < String > ( columnNames ) ) ; this . condition = condition ; } private boolean isEmpty ( String string ) { return ( string == null || string . trim ( ) . isEmpty ( ) ) ; } public String getName ( ) { return name ; } public DataModelJdbcSupport < ? super T > getSupport ( ) { return support ; } public String getTableName ( ) { return tableName ; } public List < String > getColumnNames ( ) { return columnNames ; } public String getCondition ( ) { return condition ; } } package com . asakusafw . windgate . jdbc ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . Reader ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . ResultSetMetaData ; import java . sql . SQLException ; import java . sql . Statement ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . junit . rules . TestWatcher ; import org . junit . runner . Description ; public class H2Resource extends TestWatcher { private final String name ; private Class < ? > context ; private Connection connection ; public H2Resource ( String name ) { this . name = name ; } @ Override protected void starting ( Description description ) { org . h2 . Driver . load ( ) ; this . context = description . getTestClass ( ) ; this . connection = open ( ) ; boolean green = false ; try { leakcheck ( ) ; before ( ) ; green = true ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } finally { if ( green == false ) { finished ( description ) ; } } } private void leakcheck ( ) { try { execute0 ( "" ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } protected void before ( ) throws Exception { return ; } public Connection open ( ) { try { return DriverManager . getConnection ( getJdbcUrl ( ) ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } public String getJdbcUrl ( ) { return "" + name ; } public List < List < Object > > query ( String sql ) { try { return query0 ( sql ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public List < Object > single ( String sql ) { try { List < List < Object > > query = query0 ( sql ) ; assertThat ( sql , query . size ( ) , is ( ) ) ; return query . get ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } public int count ( String table ) { try { List < List < Object > > r = query0 ( MessageFormat . format ( "" , table ) ) ; if ( r . size ( ) != ) { return - ; } return ( ( Number ) r . get ( ) . get ( ) ) . intValue ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return - ; } } private List < List < Object > > query0 ( String sql ) throws SQLException { Statement s = connection . createStatement ( ) ; try { ResultSet rs = s . executeQuery ( sql ) ; ResultSetMetaData meta = rs . getMetaData ( ) ; int size = meta . getColumnCount ( ) ; List < List < Object > > results = new ArrayList < List < Object > > ( ) ; while ( rs . next ( ) ) { Object [ ] columns = new Object [ size ] ; for ( int i = ; i < size ; i ++ ) { columns [ i ] = rs . getObject ( i + ) ; } results . add ( Arrays . asList ( columns ) ) ; } return results ; } finally { s . close ( ) ; } } public void execute ( String sql ) { try { execute0 ( sql ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } private void execute0 ( String sql ) throws SQLException { PreparedStatement ps = connection . prepareStatement ( sql ) ; try { ps . execute ( ) ; connection . commit ( ) ; } finally { ps . close ( ) ; } } public void executeFile ( String sqlFile ) { String content = load ( sqlFile ) ; execute ( content ) ; } private String load ( String resource ) { InputStream source = context . getResourceAsStream ( resource ) ; assertThat ( resource , source , is ( not ( nullValue ( ) ) ) ) ; try { StringBuilder buf = new StringBuilder ( ) ; Reader reader = new InputStreamReader ( source , "" ) ; char [ ] cbuf = new char [ ] ; while ( true ) { int read = reader . read ( cbuf ) ; if ( read < ) { break ; } buf . append ( cbuf , , read ) ; } return buf . toString ( ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } finally { try { source . close ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } } @ Override public void finished ( Description description ) { if ( connection != null ) { try { connection . close ( ) ; } catch ( SQLException e ) { throw new AssertionError ( e ) ; } } } } package com . asakusafw . windgate . jdbc ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . sql . Connection ; import java . sql . Statement ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . util . VariableTable ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . resource . ResourceProfile ; public class JdbcProfileTest { @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; } } ; @ Test public void convert ( ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( JdbcProfile . KEY_DRIVER , org . h2 . Driver . class . getName ( ) ) ; map . put ( JdbcProfile . KEY_URL , h2 . getJdbcUrl ( ) ) ; ResourceProfile rp = toProfile ( map ) ; JdbcProfile profile = JdbcProfile . convert ( rp ) ; assertThat ( profile . getResourceName ( ) , is ( rp . getName ( ) ) ) ; assertThat ( profile . getBatchPutUnit ( ) , greaterThan ( ) ) ; Connection conn = profile . openConnection ( ) ; try { Statement stmt = conn . createStatement ( ) ; stmt . execute ( "" ) ; stmt . close ( ) ; conn . commit ( ) ; } finally { conn . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void convert_all ( ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( JdbcProfile . KEY_DRIVER , org . h2 . Driver . class . getName ( ) ) ; map . put ( JdbcProfile . KEY_URL , h2 . getJdbcUrl ( ) ) ; map . put ( JdbcProfile . KEY_USER , "" ) ; map . put ( JdbcProfile . KEY_PASSWORD , "" ) ; map . put ( JdbcProfile . KEY_BATCH_GET_UNIT , "" ) ; map . put ( JdbcProfile . KEY_BATCH_PUT_UNIT , "" ) ; map . put ( JdbcProfile . KEY_CONNECT_RETRY_COUNT , "" ) ; map . put ( JdbcProfile . KEY_CONNECT_RETRY_INTERVAL , "" ) ; map . put ( JdbcProfile . KEY_TRUNCATE_STATEMENT , "" ) ; map . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , "" ) ; map . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , "" ) ; map . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , "" ) ; JdbcProfile profile = JdbcProfile . convert ( toProfile ( map ) ) ; assertThat ( profile . getBatchGetUnit ( ) , is ( ) ) ; assertThat ( profile . getBatchPutUnit ( ) , is ( ) ) ; Map < String , String > extra = new HashMap < String , String > ( ) ; extra . put ( "" , "" ) ; extra . put ( "" , "" ) ; extra . put ( "" , "" ) ; assertThat ( profile . getConnectionProperties ( ) , is ( extra ) ) ; assertThat ( profile . getTruncateStatement ( "" ) . trim ( ) , startsWith ( "" ) ) ; Connection conn = profile . openConnection ( ) ; try { Statement stmt = conn . createStatement ( ) ; stmt . execute ( "" ) ; stmt . close ( ) ; conn . commit ( ) ; } finally { conn . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void convert_parameterized ( ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( JdbcProfile . KEY_DRIVER , VariableTable . toVariable ( JdbcProfile . KEY_DRIVER ) ) ; map . put ( JdbcProfile . KEY_URL , VariableTable . toVariable ( JdbcProfile . KEY_URL ) ) ; map . put ( JdbcProfile . KEY_USER , VariableTable . toVariable ( JdbcProfile . KEY_USER ) ) ; map . put ( JdbcProfile . KEY_PASSWORD , VariableTable . toVariable ( JdbcProfile . KEY_PASSWORD ) ) ; map . put ( JdbcProfile . KEY_BATCH_GET_UNIT , VariableTable . toVariable ( JdbcProfile . KEY_BATCH_GET_UNIT ) ) ; map . put ( JdbcProfile . KEY_BATCH_PUT_UNIT , VariableTable . toVariable ( JdbcProfile . KEY_BATCH_PUT_UNIT ) ) ; map . put ( JdbcProfile . KEY_CONNECT_RETRY_COUNT , VariableTable . toVariable ( JdbcProfile . KEY_CONNECT_RETRY_COUNT ) ) ; map . put ( JdbcProfile . KEY_CONNECT_RETRY_INTERVAL , VariableTable . toVariable ( JdbcProfile . KEY_CONNECT_RETRY_INTERVAL ) ) ; map . put ( JdbcProfile . KEY_TRUNCATE_STATEMENT , VariableTable . toVariable ( JdbcProfile . KEY_TRUNCATE_STATEMENT ) ) ; map . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , VariableTable . toVariable ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" ) ) ; map . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , VariableTable . toVariable ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" ) ) ; map . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , VariableTable . toVariable ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" ) ) ; Map < String , String > parameters = new HashMap < String , String > ( ) ; parameters . put ( JdbcProfile . KEY_DRIVER , org . h2 . Driver . class . getName ( ) ) ; parameters . put ( JdbcProfile . KEY_URL , h2 . getJdbcUrl ( ) ) ; parameters . put ( JdbcProfile . KEY_USER , "" ) ; parameters . put ( JdbcProfile . KEY_PASSWORD , "" ) ; parameters . put ( JdbcProfile . KEY_BATCH_GET_UNIT , "" ) ; parameters . put ( JdbcProfile . KEY_BATCH_PUT_UNIT , "" ) ; parameters . put ( JdbcProfile . KEY_CONNECT_RETRY_COUNT , "" ) ; parameters . put ( JdbcProfile . KEY_CONNECT_RETRY_INTERVAL , "" ) ; parameters . put ( JdbcProfile . KEY_TRUNCATE_STATEMENT , "" ) ; parameters . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , "" ) ; parameters . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , "" ) ; parameters . put ( JdbcProfile . KEY_PREFIX_PROPERTIES + "" , "" ) ; JdbcProfile profile = JdbcProfile . convert ( toProfile ( map , parameters ) ) ; assertThat ( profile . getBatchGetUnit ( ) , is ( ) ) ; assertThat ( profile . getBatchPutUnit ( ) , is ( ) ) ; Map < String , String > extra = new HashMap < String , String > ( ) ; extra . put ( "" , "" ) ; extra . put ( "" , "" ) ; extra . put ( "" , "" ) ; assertThat ( profile . getConnectionProperties ( ) , is ( extra ) ) ; assertThat ( profile . getTruncateStatement ( "" ) . trim ( ) , startsWith ( "" ) ) ; Connection conn = profile . openConnection ( ) ; try { Statement stmt = conn . createStatement ( ) ; stmt . execute ( "" ) ; stmt . close ( ) ; conn . commit ( ) ; } finally { conn . close ( ) ; } assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_empty ( ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; JdbcProfile . convert ( toProfile ( map ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_negative_batchPutUnit ( ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( JdbcProfile . KEY_DRIVER , org . h2 . Driver . class . getName ( ) ) ; map . put ( JdbcProfile . KEY_URL , h2 . getJdbcUrl ( ) ) ; map . put ( JdbcProfile . KEY_BATCH_PUT_UNIT , "" ) ; JdbcProfile . convert ( toProfile ( map ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_invalid_batchPutUnit ( ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( JdbcProfile . KEY_DRIVER , org . h2 . Driver . class . getName ( ) ) ; map . put ( JdbcProfile . KEY_URL , h2 . getJdbcUrl ( ) ) ; map . put ( JdbcProfile . KEY_BATCH_PUT_UNIT , "" ) ; JdbcProfile . convert ( toProfile ( map ) ) ; } @ Test ( expected = Exception . class ) public void openConnection_invalid_driver ( ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( JdbcProfile . KEY_DRIVER , "" ) ; map . put ( JdbcProfile . KEY_URL , h2 . getJdbcUrl ( ) ) ; JdbcProfile profile = JdbcProfile . convert ( toProfile ( map ) ) ; Connection conn = profile . openConnection ( ) ; conn . close ( ) ; } @ Test ( expected = Exception . class ) public void openConnection_invalid_url ( ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( JdbcProfile . KEY_DRIVER , org . h2 . Driver . class . getName ( ) ) ; map . put ( JdbcProfile . KEY_URL , "" ) ; JdbcProfile profile = JdbcProfile . convert ( toProfile ( map ) ) ; Connection conn = profile . openConnection ( ) ; conn . close ( ) ; } private ResourceProfile toProfile ( Map < String , String > map ) { return toProfile ( map , Collections . < String , String > emptyMap ( ) ) ; } private ResourceProfile toProfile ( Map < String , String > map , Map < String , String > params ) { return new ResourceProfile ( "" , JdbcResourceProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( params ) ) , map ) ; } } package com . asakusafw . windgate . jdbc ; public class Pair implements Comparable < Pair > { int key ; String value ; public Pair ( ) { return ; } Pair ( int key , String value ) { this . key = key ; this . value = value ; } @ Override public int compareTo ( Pair o ) { if ( key < o . key ) { return - ; } else if ( key > o . key ) { return + ; } else { return value . compareTo ( o . value ) ; } } } package com . asakusafw . windgate . jdbc ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess ; public class JdbcResourceMirrorTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; } } ; @ Test public void source_simple ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; h2 . execute ( "" ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { resource . prepare ( script ) ; SourceDriver < Pair > source = resource . createSource ( process ) ; try { source . prepare ( ) ; test ( source , "" ) ; } finally { source . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_many ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { resource . prepare ( script ) ; SourceDriver < Pair > source = resource . createSource ( process ) ; try { source . prepare ( ) ; test ( source , "" , "" , "" ) ; } finally { source . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_condition ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . CONDITION . key ( ) , "" ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { resource . prepare ( script ) ; SourceDriver < Pair > source = resource . createSource ( process ) ; try { source . prepare ( ) ; test ( source , "" , "" ) ; } finally { source . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_condition_parameterized ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . CONDITION . key ( ) , "" ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( Collections . singletonMap ( "" , "" ) ) ) ; try { resource . prepare ( script ) ; SourceDriver < Pair > source = resource . createSource ( process ) ; try { source . prepare ( ) ; test ( source , "" , "" ) ; } finally { source . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; h2 . execute ( "" ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( resource ) , is ( true ) ) ; resource . prepare ( script ) ; SourceDriver < Pair > source = resource . createSource ( process ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( source ) , is ( false ) ) ; } finally { source . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_condition_invalid_parameterized ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . CONDITION . key ( ) , "" ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void source_invalid_model ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , VoidSupport . class . getName ( ) ) ; ProcessScript < Void > process = new ProcessScript < Void > ( "" , "" , Void . class , new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void drain_simple ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { resource . prepare ( script ) ; DrainDriver < Pair > drain = resource . createDrain ( process ) ; try { drain . prepare ( ) ; drain . put ( new Pair ( , "" ) ) ; } finally { drain . close ( ) ; } test ( "" ) ; } finally { resource . close ( ) ; } } @ Test public void drain_many ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { resource . prepare ( script ) ; DrainDriver < Pair > drain = resource . createDrain ( process ) ; try { drain . prepare ( ) ; drain . put ( new Pair ( , "" ) ) ; drain . put ( new Pair ( , "" ) ) ; drain . put ( new Pair ( , "" ) ) ; } finally { drain . close ( ) ; } test ( "" , "" , "" ) ; } finally { resource . close ( ) ; } } @ Test public void drain_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; h2 . execute ( "" ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( resource ) , is ( true ) ) ; resource . prepare ( script ) ; DrainDriver < Pair > drain = resource . createDrain ( process ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( drain ) , is ( false ) ) ; } finally { drain . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void invalid_drain_operation_missing ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_drain_operation_unknown ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , "" ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_table_missing ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_table_empty ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_columns_missing ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_columns_empty ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_support_missing ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_support_unknown ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , "" ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_support_class ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , Pair . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_support_failnew ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , SupportWithPrivateConstructor . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_support_inconsistent ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , VoidSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } @ Test public void invalid_support_unsupported ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; GateScript script = script ( process ) ; JdbcResourceMirror resource = new JdbcResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { try { resource . prepare ( script ) ; fail ( ) ; } catch ( IOException e ) { } } finally { resource . close ( ) ; } } private void test ( SourceDriver < Pair > source , String ... expected ) throws IOException { List < Pair > results = new ArrayList < Pair > ( ) ; while ( source . next ( ) ) { Pair pair = source . get ( ) ; results . add ( new Pair ( pair . key , pair . value ) ) ; } Collections . sort ( results ) ; List < String > actual = new ArrayList < String > ( ) ; for ( Pair row : results ) { actual . add ( row . value ) ; } assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private void test ( String ... expected ) { List < List < Object > > results = h2 . query ( "" ) ; List < String > actual = new ArrayList < String > ( ) ; for ( List < Object > row : results ) { actual . add ( ( String ) row . get ( ) ) ; } assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private GateScript script ( ProcessScript < ? > ... processes ) { return new GateScript ( "" , Arrays . < ProcessScript < ? > > asList ( processes ) ) ; } private ProcessScript < Pair > process ( DriverScript source , DriverScript drain ) { return new ProcessScript < Pair > ( "" , "" , Pair . class , source , drain ) ; } private DriverScript dummy ( ) { return new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) ; } private JdbcProfile profile ( ) { return new JdbcProfile ( "" , null , org . h2 . Driver . class . getName ( ) , h2 . getJdbcUrl ( ) , null , null , ) ; } } package com . asakusafw . windgate . jdbc ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . JdbcProcess ; public class JdbcResourceManipulatorTest { @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; } } ; @ Test public void cleanupSource ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; manipulator . cleanupSource ( process ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void cleanupSource_with_condition ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . CONDITION . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; manipulator . cleanupSource ( process ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void cleanupSource_modified ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcProfile profile = profile ( ) ; profile . setTruncateStatement ( "" ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile , new ParameterList ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; manipulator . cleanupSource ( process ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void cleanupSource_missing_table ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; manipulator . cleanupSource ( process ) ; } @ Test public void cleanupDrain ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; manipulator . cleanupDrain ( process ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void cleanupDrain_modified ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcProfile profile = profile ( ) ; profile . setTruncateStatement ( "" ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile , new ParameterList ( ) ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; manipulator . cleanupDrain ( process ) ; assertThat ( h2 . count ( "" ) , is ( ) ) ; } @ Test public void cleanupDrain_missing_table ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; manipulator . cleanupDrain ( process ) ; } @ Test public void createSourceForSource ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . CONDITION . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; SourceDriver < Pair > driver = manipulator . createSourceForSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" , "" , "" ) ; } finally { driver . close ( ) ; } } @ Test public void createDrainForSource ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . CONDITION . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; h2 . execute ( "" ) ; ProcessScript < Pair > process = process ( new DriverScript ( "" , conf ) , dummy ( ) ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; DrainDriver < Pair > driver = manipulator . createDrainForSource ( process ) ; try { driver . prepare ( ) ; driver . put ( new Pair ( , "" ) ) ; driver . put ( new Pair ( , "" ) ) ; } finally { driver . close ( ) ; } test ( "" , "" , "" ) ; } @ Test public void createSourceForDrain ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; h2 . execute ( "" ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; SourceDriver < Pair > driver = manipulator . createSourceForDrain ( process ) ; try { driver . prepare ( ) ; test ( driver , "" , "" , "" ) ; } finally { driver . close ( ) ; } } @ Test public void createDrainForDrain ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( JdbcProcess . TABLE . key ( ) , "" ) ; conf . put ( JdbcProcess . COLUMNS . key ( ) , "" ) ; conf . put ( JdbcProcess . JDBC_SUPPORT . key ( ) , PairSupport . class . getName ( ) ) ; conf . put ( JdbcProcess . OPERATION . key ( ) , JdbcProcess . OperationKind . INSERT_AFTER_TRUNCATE . value ( ) ) ; h2 . execute ( "" ) ; ProcessScript < Pair > process = process ( dummy ( ) , new DriverScript ( "" , conf ) ) ; JdbcResourceManipulator manipulator = new JdbcResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; DrainDriver < Pair > driver = manipulator . createDrainForDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new Pair ( , "" ) ) ; driver . put ( new Pair ( , "" ) ) ; } finally { driver . close ( ) ; } test ( "" , "" , "" ) ; } private void test ( SourceDriver < Pair > source , String ... expected ) throws IOException { List < Pair > results = new ArrayList < Pair > ( ) ; while ( source . next ( ) ) { Pair pair = source . get ( ) ; results . add ( new Pair ( pair . key , pair . value ) ) ; } Collections . sort ( results ) ; List < String > actual = new ArrayList < String > ( ) ; for ( Pair row : results ) { actual . add ( row . value ) ; } assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private void test ( String ... expected ) { List < List < Object > > results = h2 . query ( "" ) ; List < String > actual = new ArrayList < String > ( ) ; for ( List < Object > row : results ) { actual . add ( ( String ) row . get ( ) ) ; } assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private ProcessScript < Pair > process ( DriverScript source , DriverScript drain ) { return new ProcessScript < Pair > ( "" , "" , Pair . class , source , drain ) ; } private DriverScript dummy ( ) { return new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) ; } private JdbcProfile profile ( ) { return new JdbcProfile ( "" , null , org . h2 . Driver . class . getName ( ) , h2 . getJdbcUrl ( ) , null , null , ) ; } } package com . asakusafw . windgate . jdbc ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . util . Arrays ; import java . util . List ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; public class VoidSupport implements DataModelJdbcSupport < Void > { @ Override public Class < Void > getSupportedType ( ) { return Void . class ; } @ Override public boolean isSupported ( List < String > columnNames ) { return columnNames . equals ( Arrays . asList ( "" , "" ) ) ; } @ Override public DataModelResultSet < Void > createResultSetSupport ( ResultSet resultSet , List < String > columnNames ) { throw new UnsupportedOperationException ( ) ; } @ Override public DataModelPreparedStatement < Void > createPreparedStatementSupport ( PreparedStatement statement , List < String > columnNames ) { throw new UnsupportedOperationException ( ) ; } } package com . asakusafw . windgate . jdbc ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . sql . Connection ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; public class JdbcSourceDriverTest { @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; } } ; @ Test public void simple ( ) throws Exception { h2 . execute ( "" ) ; Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcSourceDriver < Pair > driver = new JdbcSourceDriver < Pair > ( profile ( ) , script , conn , new Pair ( ) ) ; driver . prepare ( ) ; List < String > values = values ( driver ) ; driver . close ( ) ; assertThat ( values , is ( Arrays . asList ( "" ) ) ) ; } finally { conn . close ( ) ; } } @ Test public void empty ( ) throws Exception { Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcSourceDriver < Pair > driver = new JdbcSourceDriver < Pair > ( profile ( ) , script , conn , new Pair ( ) ) ; driver . prepare ( ) ; List < String > values = values ( driver ) ; driver . close ( ) ; assertThat ( values , is ( Arrays . < String > asList ( ) ) ) ; } finally { conn . close ( ) ; } } @ Test public void large ( ) throws Exception { List < String > answer = new ArrayList < String > ( ) ; for ( int i = ; i < ; i ++ ) { String value = MessageFormat . format ( "" , String . valueOf ( i + ) ) ; answer . add ( value ) ; h2 . execute ( MessageFormat . format ( "" , String . valueOf ( i + ) , value ) ) ; } Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcSourceDriver < Pair > driver = new JdbcSourceDriver < Pair > ( profile ( ) , script , conn , new Pair ( ) ) ; driver . prepare ( ) ; List < String > values = values ( driver ) ; driver . close ( ) ; assertThat ( values , is ( answer ) ) ; } finally { conn . close ( ) ; } } @ Test public void condition ( ) throws Exception { for ( int i = ; i < ; i ++ ) { String value = MessageFormat . format ( "" , String . valueOf ( i + ) ) ; h2 . execute ( MessageFormat . format ( "" , String . valueOf ( i + ) , value ) ) ; } Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , "" ) ; JdbcSourceDriver < Pair > driver = new JdbcSourceDriver < Pair > ( profile ( ) , script , conn , new Pair ( ) ) ; driver . prepare ( ) ; List < String > values = values ( driver ) ; driver . close ( ) ; assertThat ( values , is ( Arrays . asList ( "" , "" ) ) ) ; } finally { conn . close ( ) ; } } @ Test public void suppress_error_on_close ( ) throws Exception { h2 . execute ( "" ) ; Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcSourceDriver < Pair > driver = new JdbcSourceDriver < Pair > ( profile ( ) , script , conn , new Pair ( ) ) ; driver . prepare ( ) ; conn . close ( ) ; try { driver . next ( ) ; fail ( ) ; } catch ( IOException e ) { } driver . close ( ) ; } finally { conn . close ( ) ; } } private List < String > values ( JdbcSourceDriver < Pair > driver ) throws IOException { List < Pair > results = new ArrayList < Pair > ( ) ; while ( driver . next ( ) ) { Pair got = driver . get ( ) ; Pair copy = new Pair ( ) ; copy . key = got . key ; copy . value = got . value ; results . add ( copy ) ; } Collections . sort ( results ) ; List < String > values = new ArrayList < String > ( ) ; for ( Pair p : results ) { values . add ( p . value ) ; } return values ; } private JdbcProfile profile ( ) { return new JdbcProfile ( "" , null , org . h2 . Driver . class . getName ( ) , h2 . getJdbcUrl ( ) , null , null , ) ; } } package com . asakusafw . windgate . jdbc ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . sql . Connection ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; public class JdbcDrainDriverTest { @ Rule public H2Resource h2 = new H2Resource ( "" ) { @ Override protected void before ( ) throws Exception { executeFile ( "" ) ; } } ; @ Test public void simple ( ) throws Exception { Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcDrainDriver < Pair > driver = new JdbcDrainDriver < Pair > ( profile ( ) , script , conn , true ) ; driver . prepare ( ) ; driver . put ( new Pair ( , "" ) ) ; driver . close ( ) ; test ( "" ) ; } finally { conn . close ( ) ; } } @ Test public void empty ( ) throws Exception { Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcDrainDriver < Pair > driver = new JdbcDrainDriver < Pair > ( profile ( ) , script , conn , true ) ; driver . prepare ( ) ; driver . close ( ) ; test ( ) ; } finally { conn . close ( ) ; } } @ Test public void large ( ) throws Exception { Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcDrainDriver < Pair > driver = new JdbcDrainDriver < Pair > ( profile ( ) , script , conn , true ) ; driver . prepare ( ) ; String [ ] expected = new String [ ] ; for ( int i = ; i <= ; i ++ ) { String value = "" + i ; expected [ i - ] = value ; driver . put ( new Pair ( i , value ) ) ; } driver . close ( ) ; test ( expected ) ; } finally { conn . close ( ) ; } } @ Test public void large_align ( ) throws Exception { Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcDrainDriver < Pair > driver = new JdbcDrainDriver < Pair > ( profile ( ) , script , conn , true ) ; driver . prepare ( ) ; String [ ] expected = new String [ ] ; for ( int i = ; i <= ; i ++ ) { String value = "" + i ; expected [ i - ] = value ; driver . put ( new Pair ( i , value ) ) ; } driver . close ( ) ; test ( expected ) ; } finally { conn . close ( ) ; } } @ Test public void truncate ( ) throws Exception { h2 . execute ( "" ) ; Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcDrainDriver < Pair > driver = new JdbcDrainDriver < Pair > ( profile ( ) , script , conn , true ) ; driver . prepare ( ) ; driver . put ( new Pair ( , "" ) ) ; driver . close ( ) ; test ( "" ) ; } finally { conn . close ( ) ; } } @ Test public void suppress_truncate ( ) throws Exception { h2 . execute ( "" ) ; Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcDrainDriver < Pair > driver = new JdbcDrainDriver < Pair > ( profile ( ) , script , conn , false ) ; driver . prepare ( ) ; driver . put ( new Pair ( , "" ) ) ; driver . close ( ) ; test ( "" , "" ) ; } finally { conn . close ( ) ; } } @ Test public void suppress_error_on_close ( ) throws Exception { Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcDrainDriver < Pair > driver = new JdbcDrainDriver < Pair > ( profile ( ) , script , conn , true ) ; driver . prepare ( ) ; conn . close ( ) ; try { driver . put ( new Pair ( , "" ) ) ; fail ( ) ; } catch ( IOException e ) { } driver . close ( ) ; } finally { conn . close ( ) ; } } @ Test public void aware_commit_failure ( ) throws Exception { Connection conn = h2 . open ( ) ; try { JdbcScript < Pair > script = new JdbcScript < Pair > ( "" , new PairSupport ( ) , "" , Arrays . asList ( "" , "" ) , null ) ; JdbcDrainDriver < Pair > driver = new JdbcDrainDriver < Pair > ( profile ( ) , script , conn , true ) ; driver . prepare ( ) ; driver . put ( new Pair ( , "" ) ) ; conn . close ( ) ; try { driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } } finally { conn . close ( ) ; } } private void test ( String ... expected ) { List < List < Object > > results = h2 . query ( "" ) ; List < String > actual = new ArrayList < String > ( ) ; for ( List < Object > row : results ) { actual . add ( ( String ) row . get ( ) ) ; } assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private JdbcProfile profile ( ) { return new JdbcProfile ( "" , null , org . h2 . Driver . class . getName ( ) , h2 . getJdbcUrl ( ) , null , null , ) ; } } package com . asakusafw . windgate . jdbc ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . util . List ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; public class SupportWithPrivateConstructor implements DataModelJdbcSupport < Object > { private SupportWithPrivateConstructor ( ) { return ; } @ Override public Class < Object > getSupportedType ( ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean isSupported ( List < String > columnNames ) { throw new UnsupportedOperationException ( ) ; } @ Override public DataModelResultSet < Object > createResultSetSupport ( ResultSet resultSet , List < String > columnNames ) { throw new UnsupportedOperationException ( ) ; } @ Override public DataModelPreparedStatement < Object > createPreparedStatementSupport ( PreparedStatement statement , List < String > columnNames ) { throw new UnsupportedOperationException ( ) ; } } package com . asakusafw . windgate . jdbc ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . Arrays ; import java . util . List ; import com . asakusafw . windgate . core . vocabulary . DataModelJdbcSupport ; public class PairSupport implements DataModelJdbcSupport < Pair > { @ Override public Class < Pair > getSupportedType ( ) { return Pair . class ; } @ Override public boolean isSupported ( List < String > columnNames ) { return columnNames . equals ( Arrays . asList ( "" , "" ) ) ; } @ Override public DataModelResultSet < Pair > createResultSetSupport ( final ResultSet resultSet , List < String > columnNames ) { return new DataModelResultSet < Pair > ( ) { @ Override public boolean next ( Pair object ) throws SQLException { if ( resultSet . next ( ) ) { object . key = resultSet . getInt ( ) ; object . value = resultSet . getString ( ) ; return true ; } return false ; } } ; } @ Override public DataModelPreparedStatement < Pair > createPreparedStatementSupport ( final PreparedStatement statement , List < String > columnNames ) { return new DataModelPreparedStatement < Pair > ( ) { @ Override public void setParameters ( Pair object ) throws SQLException { statement . setInt ( , object . key ) ; statement . setString ( , object . value ) ; } } ; } } package com . asakusafw . windgate . stream . file ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Scanner ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . core . vocabulary . StreamProcess ; import com . asakusafw . windgate . stream . StringBuilderSupport ; public class FileResourceMirrorTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void prepare ( ) throws Exception { FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > a = process ( "" , driver ( "" ) , dummy ( ) ) ; ProcessScript < StringBuilder > b = process ( "" , dummy ( ) , driver ( "" ) ) ; GateScript gate = script ( a , b ) ; resource . prepare ( gate ) ; } finally { resource . close ( ) ; } } @ Test ( expected = IOException . class ) public void prepare_invalid_variable ( ) throws Exception { FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > a = process ( "" , driver ( "" ) , dummy ( ) ) ; ProcessScript < StringBuilder > b = process ( "" , dummy ( ) , driver ( "" ) ) ; GateScript gate = script ( a , b ) ; resource . prepare ( gate ) ; fail ( ) ; } finally { resource . close ( ) ; } } @ Test ( expected = IOException . class ) public void prepare_invalid_source ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; DriverScript driverScript = new DriverScript ( "" , conf ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > a = process ( "" , driverScript , dummy ( ) ) ; ProcessScript < StringBuilder > b = process ( "" , dummy ( ) , driver ( "" ) ) ; GateScript gate = script ( a , b ) ; resource . prepare ( gate ) ; fail ( ) ; } finally { resource . close ( ) ; } } @ Test ( expected = IOException . class ) public void prepare_invalid_drain ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; DriverScript driverScript = new DriverScript ( "" , conf ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > a = process ( "" , driver ( "" ) , dummy ( ) ) ; ProcessScript < StringBuilder > b = process ( "" , dummy ( ) , driverScript ) ; GateScript gate = script ( a , b ) ; resource . prepare ( gate ) ; fail ( ) ; } finally { resource . close ( ) ; } } @ Test public void source ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , driver ( file . getName ( ) ) , dummy ( ) ) ; resource . prepare ( script ( process ) ) ; SourceDriver < StringBuilder > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_parameterized ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( Collections . singletonMap ( "" , file . getName ( ) ) ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , driver ( "" ) , dummy ( ) ) ; resource . prepare ( script ( process ) ) ; SourceDriver < StringBuilder > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_multi ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" , "" , "" ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , driver ( file . getName ( ) ) , dummy ( ) ) ; resource . prepare ( script ( process ) ) ; SourceDriver < StringBuilder > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" , "" , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test ( expected = IOException . class ) public void source_invalid ( ) throws Exception { File file = folder . newFile ( "" ) ; Assume . assumeTrue ( file . delete ( ) ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , driver ( file . getName ( ) ) , dummy ( ) ) ; resource . prepare ( script ( process ) ) ; SourceDriver < StringBuilder > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; File file = folder . newFile ( "" ) ; file . delete ( ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( resource ) , is ( true ) ) ; ProcessScript < StringBuilder > process = process ( "" , driver ( file . getName ( ) ) , dummy ( ) ) ; resource . prepare ( script ( process ) ) ; SourceDriver < StringBuilder > driver = resource . createSource ( process ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( driver ) , is ( false ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void drain ( ) throws Exception { File file = folder . newFile ( "" ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( file . getName ( ) ) ) ; resource . prepare ( script ( process ) ) ; DrainDriver < StringBuilder > driver = resource . createDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } test ( file , "" ) ; } @ Test public void drain_parameterized ( ) throws Exception { File file = folder . newFile ( "" ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( Collections . singletonMap ( "" , file . getName ( ) ) ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( "" ) ) ; resource . prepare ( script ( process ) ) ; DrainDriver < StringBuilder > driver = resource . createDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } test ( file , "" ) ; } @ Test public void drain_create_parent ( ) throws Exception { File parent = folder . newFolder ( "" ) ; Assume . assumeTrue ( parent . delete ( ) ) ; File file = new File ( parent , "" ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( "" ) ) ; resource . prepare ( script ( process ) ) ; DrainDriver < StringBuilder > driver = resource . createDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } test ( file , "" ) ; } @ Test public void drain_multi ( ) throws Exception { File file = folder . newFile ( "" ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( file . getName ( ) ) ) ; resource . prepare ( script ( process ) ) ; DrainDriver < StringBuilder > driver = resource . createDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; driver . put ( new StringBuilder ( "" ) ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } test ( file , "" , "" , "" ) ; } @ Test ( expected = IOException . class ) public void drain_invalid ( ) throws Exception { File file = folder . newFolder ( "" ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( file . getName ( ) ) ) ; resource . prepare ( script ( process ) ) ; DrainDriver < StringBuilder > driver = resource . createDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void drain_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; File file = folder . newFile ( "" ) ; file . delete ( ) ; FileResourceMirror resource = new FileResourceMirror ( profile ( ) , new ParameterList ( ) ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( resource ) , is ( true ) ) ; ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( file . getName ( ) ) ) ; resource . prepare ( script ( process ) ) ; DrainDriver < StringBuilder > driver = resource . createDrain ( process ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( driver ) , is ( false ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } assertThat ( file . exists ( ) , is ( false ) ) ; } private void put ( File file , String ... lines ) throws IOException { PrintWriter writer = new PrintWriter ( file . getAbsolutePath ( ) , "" ) ; try { for ( String line : lines ) { writer . println ( line ) ; } } finally { writer . close ( ) ; } } private void test ( SourceDriver < StringBuilder > source , String ... expected ) throws IOException { List < String > actual = new ArrayList < String > ( ) ; while ( source . next ( ) ) { StringBuilder pair = source . get ( ) ; actual . add ( pair . toString ( ) ) ; } Collections . sort ( actual ) ; Arrays . sort ( expected ) ; assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private void test ( File file , String ... expected ) throws IOException { List < String > actual = new ArrayList < String > ( ) ; Scanner scanner = new Scanner ( file , "" ) ; while ( scanner . hasNextLine ( ) ) { actual . add ( scanner . nextLine ( ) ) ; } Collections . sort ( actual ) ; Arrays . sort ( expected ) ; assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private GateScript script ( ProcessScript < ? > ... processes ) { return new GateScript ( "" , Arrays . < ProcessScript < ? > > asList ( processes ) ) ; } private ProcessScript < StringBuilder > process ( String name , DriverScript source , DriverScript drain ) { return new ProcessScript < StringBuilder > ( name , "" , StringBuilder . class , source , drain ) ; } private DriverScript driver ( String file ) { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( FileProcess . FILE . key ( ) , file ) ; conf . put ( StreamProcess . STREAM_SUPPORT . key ( ) , StringBuilderSupport . class . getName ( ) ) ; return new DriverScript ( "" , conf ) ; } private DriverScript dummy ( ) { return new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) ; } private FileProfile profile ( ) { return new FileProfile ( "" , getClass ( ) . getClassLoader ( ) , folder . getRoot ( ) ) ; } } package com . asakusafw . windgate . stream . file ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Scanner ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . core . vocabulary . StreamProcess ; import com . asakusafw . windgate . stream . StringBuilderSupport ; public class FileResourceManipulatorTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void cleanupSource ( ) throws Exception { File file = folder . newFile ( "" ) ; ProcessScript < StringBuilder > process = process ( "" , driver ( file . getName ( ) ) , dummy ( ) ) ; FileResourceManipulator manipulator = new FileResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; assertThat ( file . exists ( ) , is ( true ) ) ; manipulator . cleanupSource ( process ) ; assertThat ( file . exists ( ) , is ( false ) ) ; manipulator . cleanupSource ( process ) ; } @ Test public void cleanupDrain ( ) throws Exception { File file = folder . newFile ( "" ) ; ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( file . getName ( ) ) ) ; FileResourceManipulator manipulator = new FileResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; assertThat ( file . exists ( ) , is ( true ) ) ; manipulator . cleanupDrain ( process ) ; assertThat ( file . exists ( ) , is ( false ) ) ; manipulator . cleanupDrain ( process ) ; } @ Test public void createSourceForSource ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" , "" , "" ) ; ProcessScript < StringBuilder > process = process ( "" , driver ( file . getName ( ) ) , dummy ( ) ) ; FileResourceManipulator manipulator = new FileResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; SourceDriver < StringBuilder > driver = manipulator . createSourceForSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" , "" , "" ) ; } finally { driver . close ( ) ; } } @ Test public void createDrainForSource ( ) throws Exception { File file = folder . newFile ( "" ) ; ProcessScript < StringBuilder > process = process ( "" , driver ( file . getName ( ) ) , dummy ( ) ) ; FileResourceManipulator manipulator = new FileResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; DrainDriver < StringBuilder > driver = manipulator . createDrainForSource ( process ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; driver . put ( new StringBuilder ( "" ) ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } test ( file , "" , "" , "" ) ; } @ Test public void createSourceForDrain ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" , "" , "" ) ; ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( file . getName ( ) ) ) ; FileResourceManipulator manipulator = new FileResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; SourceDriver < StringBuilder > driver = manipulator . createSourceForDrain ( process ) ; try { driver . prepare ( ) ; test ( driver , "" , "" , "" ) ; } finally { driver . close ( ) ; } } @ Test public void createDrainForDrain ( ) throws Exception { File file = folder . newFile ( "" ) ; ProcessScript < StringBuilder > process = process ( "" , dummy ( ) , driver ( file . getName ( ) ) ) ; FileResourceManipulator manipulator = new FileResourceManipulator ( profile ( ) , new ParameterList ( ) ) ; DrainDriver < StringBuilder > driver = manipulator . createDrainForDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; driver . put ( new StringBuilder ( "" ) ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } test ( file , "" , "" , "" ) ; } private void put ( File file , String ... lines ) throws IOException { PrintWriter writer = new PrintWriter ( file . getAbsolutePath ( ) , "" ) ; try { for ( String line : lines ) { writer . println ( line ) ; } } finally { writer . close ( ) ; } } private void test ( SourceDriver < StringBuilder > source , String ... expected ) throws IOException { List < String > actual = new ArrayList < String > ( ) ; while ( source . next ( ) ) { StringBuilder pair = source . get ( ) ; actual . add ( pair . toString ( ) ) ; } Collections . sort ( actual ) ; Arrays . sort ( expected ) ; assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private void test ( File file , String ... expected ) throws IOException { List < String > actual = new ArrayList < String > ( ) ; Scanner scanner = new Scanner ( file , "" ) ; while ( scanner . hasNextLine ( ) ) { actual . add ( scanner . nextLine ( ) ) ; } Collections . sort ( actual ) ; Arrays . sort ( expected ) ; assertThat ( actual , is ( Arrays . asList ( expected ) ) ) ; } private ProcessScript < StringBuilder > process ( String name , DriverScript source , DriverScript drain ) { return new ProcessScript < StringBuilder > ( name , "" , StringBuilder . class , source , drain ) ; } private DriverScript driver ( String file ) { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( FileProcess . FILE . key ( ) , file ) ; conf . put ( StreamProcess . STREAM_SUPPORT . key ( ) , StringBuilderSupport . class . getName ( ) ) ; return new DriverScript ( "" , conf ) ; } private DriverScript dummy ( ) { return new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) ; } private FileProfile profile ( ) { return new FileProfile ( "" , getClass ( ) . getClassLoader ( ) , folder . getRoot ( ) ) ; } } package com . asakusafw . windgate . stream ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . Scanner ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class StreamDrainDriverTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { File file = folder . newFile ( "" ) ; StreamDrainDriver < StringBuilder > driver = new StreamDrainDriver < StringBuilder > ( "" , "" , wrap ( new FileOutputStreamProvider ( file ) ) , new StringBuilderSupport ( ) ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } test ( file , "" ) ; } @ Test public void empty ( ) throws Exception { File file = folder . newFile ( "" ) ; StreamDrainDriver < StringBuilder > driver = new StreamDrainDriver < StringBuilder > ( "" , "" , wrap ( new FileOutputStreamProvider ( file ) ) , new StringBuilderSupport ( ) ) ; try { driver . prepare ( ) ; } finally { driver . close ( ) ; } test ( file ) ; } @ Test public void multiple ( ) throws Exception { File file = folder . newFile ( "" ) ; StreamDrainDriver < StringBuilder > driver = new StreamDrainDriver < StringBuilder > ( "" , "" , wrap ( new FileOutputStreamProvider ( file ) ) , new StringBuilderSupport ( ) ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; driver . put ( new StringBuilder ( "" ) ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } test ( file , "" , "" , "" ) ; } @ Test ( expected = IOException . class ) public void invalid_open_fail ( ) throws Exception { File file = folder . newFile ( "" ) ; Assume . assumeTrue ( file . delete ( ) ) ; Assume . assumeTrue ( file . mkdirs ( ) ) ; StreamDrainDriver < StringBuilder > driver = new StreamDrainDriver < StringBuilder > ( "" , "" , wrap ( new FileOutputStreamProvider ( file ) ) , new StringBuilderSupport ( ) ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; fail ( ) ; } finally { driver . close ( ) ; } } @ Test ( expected = IOException . class ) public void invalid_flush_failed ( ) throws Exception { StreamDrainDriver < StringBuilder > driver = new StreamDrainDriver < StringBuilder > ( "" , "" , wrap ( new StreamProvider < OutputStream > ( ) { @ Override public String getDescription ( ) { return "" ; } @ Override public OutputStream open ( ) throws IOException { return new OutputStream ( ) { @ Override public void write ( int b ) throws IOException { return ; } @ Override public void flush ( ) throws IOException { throw new IOException ( ) ; } } ; } } ) , new StringBuilderSupport ( ) ) ; try { driver . prepare ( ) ; driver . put ( new StringBuilder ( "" ) ) ; } finally { driver . close ( ) ; } } private void test ( File file , String ... lines ) throws IOException { List < String > actual = new ArrayList < String > ( ) ; Scanner scanner = new Scanner ( file , "" ) ; try { while ( scanner . hasNextLine ( ) ) { actual . add ( scanner . nextLine ( ) ) ; } } finally { scanner . close ( ) ; } assertThat ( actual , is ( Arrays . asList ( lines ) ) ) ; } private OutputStreamProvider wrap ( StreamProvider < OutputStream > provider ) { return new MockOutputStreamProvider ( provider ) ; } private static class FileOutputStreamProvider implements StreamProvider < OutputStream > { private final File file ; FileOutputStreamProvider ( File file ) { this . file = file ; } @ Override public String getDescription ( ) { return file . getName ( ) ; } @ Override public OutputStream open ( ) throws IOException { return new FileOutputStream ( file ) ; } } } package com . asakusafw . windgate . stream ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . PrintWriter ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class StreamSourceDriverTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" ) ; StringBuilder buf = new StringBuilder ( ) ; StreamSourceDriver < StringBuilder > driver = new StreamSourceDriver < StringBuilder > ( "" , "" , wrap ( new FileInputStreamProvider ( file ) ) , new StringBuilderSupport ( ) , buf ) ; try { driver . prepare ( ) ; assertThat ( driver . next ( ) , is ( true ) ) ; assertThat ( driver . get ( ) . toString ( ) , is ( "" ) ) ; assertThat ( driver . next ( ) , is ( false ) ) ; } finally { driver . close ( ) ; } } @ Test public void empty ( ) throws Exception { File file = folder . newFile ( "" ) ; StringBuilder buf = new StringBuilder ( ) ; StreamSourceDriver < StringBuilder > driver = new StreamSourceDriver < StringBuilder > ( "" , "" , wrap ( new FileInputStreamProvider ( file ) ) , new StringBuilderSupport ( ) , buf ) ; try { driver . prepare ( ) ; assertThat ( driver . next ( ) , is ( false ) ) ; } finally { driver . close ( ) ; } } @ Test public void multiple ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" , "" , "" ) ; StringBuilder buf = new StringBuilder ( ) ; StreamSourceDriver < StringBuilder > driver = new StreamSourceDriver < StringBuilder > ( "" , "" , wrap ( new FileInputStreamProvider ( file ) ) , new StringBuilderSupport ( ) , buf ) ; try { driver . prepare ( ) ; assertThat ( driver . next ( ) , is ( true ) ) ; assertThat ( driver . get ( ) . toString ( ) , is ( "" ) ) ; assertThat ( driver . next ( ) , is ( true ) ) ; assertThat ( driver . get ( ) . toString ( ) , is ( "" ) ) ; assertThat ( driver . next ( ) , is ( true ) ) ; assertThat ( driver . get ( ) . toString ( ) , is ( "" ) ) ; assertThat ( driver . next ( ) , is ( false ) ) ; } finally { driver . close ( ) ; } } @ Test ( expected = IOException . class ) public void invalid_open_fail ( ) throws Exception { File file = folder . newFile ( "" ) ; Assume . assumeTrue ( file . delete ( ) ) ; StringBuilder buf = new StringBuilder ( ) ; StreamSourceDriver < StringBuilder > driver = new StreamSourceDriver < StringBuilder > ( "" , "" , wrap ( new FileInputStreamProvider ( file ) ) , new StringBuilderSupport ( ) , buf ) ; try { driver . prepare ( ) ; driver . next ( ) ; fail ( ) ; } finally { driver . close ( ) ; } } @ Test public void suppress_close_failed ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" ) ; StringBuilder buf = new StringBuilder ( ) ; StreamSourceDriver < StringBuilder > driver = new StreamSourceDriver < StringBuilder > ( "" , "" , wrap ( new StreamProvider < InputStream > ( ) { @ Override public String getDescription ( ) { return "" ; } @ Override public InputStream open ( ) throws IOException { return new InputStream ( ) { @ Override public int read ( ) throws IOException { return - ; } @ Override public void close ( ) throws IOException { throw new IOException ( ) ; } } ; } } ) , new StringBuilderSupport ( ) , buf ) ; try { driver . prepare ( ) ; assertThat ( driver . next ( ) , is ( false ) ) ; } finally { driver . close ( ) ; } } private void put ( File file , String ... lines ) throws IOException { PrintWriter writer = new PrintWriter ( file . getAbsolutePath ( ) , "" ) ; try { for ( String line : lines ) { writer . println ( line ) ; } } finally { writer . close ( ) ; } } private InputStreamProvider wrap ( StreamProvider < InputStream > provider ) { return new MockInputStreamProvider ( provider ) ; } private static class FileInputStreamProvider implements StreamProvider < InputStream > { private final File file ; FileInputStreamProvider ( File file ) { this . file = file ; } @ Override public String getDescription ( ) { return file . getName ( ) ; } @ Override public InputStream open ( ) throws IOException { return new FileInputStream ( file ) ; } } } package com . asakusafw . windgate . stream ; import java . io . IOException ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; public class MockOutputStreamProvider extends OutputStreamProvider { private final Iterator < ? extends StreamProvider < ? extends OutputStream > > iterator ; private StreamProvider < ? extends OutputStream > current ; public MockOutputStreamProvider ( StreamProvider < ? extends OutputStream > provider ) { List < StreamProvider < ? extends OutputStream > > list = new ArrayList < StreamProvider < ? extends OutputStream > > ( ) ; list . add ( provider ) ; iterator = list . iterator ( ) ; } @ Override public void next ( ) throws IOException { current = null ; if ( iterator . hasNext ( ) ) { current = iterator . next ( ) ; } else { throw new IOException ( ) ; } } @ Override public String getCurrentPath ( ) { return current . getDescription ( ) ; } @ Override public CountingOutputStream openStream ( ) throws IOException { return new CountingOutputStream ( current . open ( ) ) ; } @ Override public void close ( ) throws IOException { return ; } } package com . asakusafw . windgate . stream ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; public class MockInputStreamProvider extends InputStreamProvider { private final Iterator < ? extends StreamProvider < ? extends InputStream > > iterator ; private StreamProvider < ? extends InputStream > current ; public MockInputStreamProvider ( StreamProvider < ? extends InputStream > provider ) { List < StreamProvider < ? extends InputStream > > list = new ArrayList < StreamProvider < ? extends InputStream > > ( ) ; list . add ( provider ) ; iterator = list . iterator ( ) ; } @ Override public boolean next ( ) throws IOException { current = null ; if ( iterator . hasNext ( ) ) { current = iterator . next ( ) ; return true ; } else { return false ; } } @ Override public String getCurrentPath ( ) { return current . getDescription ( ) ; } @ Override public CountingInputStream openStream ( ) throws IOException { return new CountingInputStream ( current . open ( ) ) ; } @ Override public void close ( ) throws IOException { return ; } } package com . asakusafw . windgate . stream ; import java . io . BufferedWriter ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . util . Scanner ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; public class StringBuilderSupport implements DataModelStreamSupport < StringBuilder > { @ Override public Class < StringBuilder > getSupportedType ( ) { return StringBuilder . class ; } @ Override public DataModelReader < StringBuilder > createReader ( String path , InputStream stream ) throws IOException { final Scanner scanner = new Scanner ( stream , "" ) ; return new DataModelReader < StringBuilder > ( ) { @ Override public boolean readTo ( StringBuilder object ) throws IOException { if ( scanner . hasNextLine ( ) ) { object . setLength ( ) ; object . append ( scanner . nextLine ( ) ) ; return true ; } return false ; } } ; } @ Override public DataModelWriter < StringBuilder > createWriter ( String path , OutputStream stream ) throws IOException { final BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( stream , "" ) ) ; return new DataModelWriter < StringBuilder > ( ) { @ Override public void flush ( ) throws IOException { writer . flush ( ) ; } @ Override public void write ( StringBuilder object ) throws IOException { writer . write ( object . toString ( ) ) ; writer . newLine ( ) ; } } ; } } package com . asakusafw . windgate . stream ; import java . io . IOException ; public interface StreamProvider < T > { String getDescription ( ) ; T open ( ) throws IOException ; } package com . asakusafw . windgate . stream ; import java . io . IOException ; import java . io . OutputStream ; public final class CountingOutputStream extends OutputStream { private final OutputStream stream ; private long count ; public CountingOutputStream ( OutputStream stream ) { if ( stream == null ) { throw new IllegalArgumentException ( "" ) ; } this . stream = stream ; } public long getCount ( ) { return count ; } @ Override public void write ( int b ) throws IOException { count += ; stream . write ( b ) ; } @ Override public void write ( byte [ ] b ) throws IOException { count += b . length ; stream . write ( b ) ; } @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { count += len ; stream . write ( b , off , len ) ; } @ Override public void flush ( ) throws IOException { stream . flush ( ) ; } @ Override public void close ( ) throws IOException { stream . close ( ) ; } } package com . asakusafw . windgate . stream ; package com . asakusafw . windgate . stream ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . windgate . core . WindGateLogger ; public class WindGateStreamLogger extends WindGateLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public WindGateStreamLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . windgate . stream ; import java . io . Closeable ; import java . io . IOException ; import java . io . OutputStream ; public abstract class OutputStreamProvider implements Closeable { public long getDesiredStreamSize ( ) { return ; } public abstract void next ( ) throws IOException ; public abstract String getCurrentPath ( ) ; public abstract CountingOutputStream openStream ( ) throws IOException ; } package com . asakusafw . windgate . stream ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport . DataModelReader ; public class StreamSourceDriver < T > implements SourceDriver < T > { static final WindGateLogger WGLOG = new WindGateStreamLogger ( StreamSourceDriver . class ) ; private final String resourceName ; private final String processName ; private final InputStreamProvider streamProvider ; private final DataModelStreamSupport < ? super T > streamSupport ; private final T buffer ; private String currentPath ; private CountingInputStream currentStream ; private DataModelReader < ? super T > currentReader ; private boolean sawNext ; private long bytesCount ; private boolean closed ; public StreamSourceDriver ( String resourceName , String processName , InputStreamProvider streamProvider , DataModelStreamSupport < ? super T > streamSupport , T buffer ) { if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( processName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( streamProvider == null ) { throw new IllegalArgumentException ( "" ) ; } if ( streamSupport == null ) { throw new IllegalArgumentException ( "" ) ; } if ( buffer == null ) { throw new IllegalArgumentException ( "" ) ; } this . resourceName = resourceName ; this . processName = processName ; this . streamProvider = streamProvider ; this . streamSupport = streamSupport ; this . buffer = buffer ; } @ Override public void prepare ( ) throws IOException { sawNext = false ; } @ Override public boolean next ( ) throws IOException { while ( true ) { if ( currentReader == null ) { if ( prepareNextStream ( ) == false ) { sawNext = false ; break ; } } if ( currentReader . readTo ( buffer ) ) { sawNext = true ; break ; } else { closeCurrentStream ( ) ; } } return sawNext ; } private boolean prepareNextStream ( ) throws IOException { if ( streamProvider . next ( ) == false ) { return false ; } currentPath = streamProvider . getCurrentPath ( ) ; WGLOG . info ( "" , resourceName , processName , currentPath ) ; try { currentStream = streamProvider . openStream ( ) ; currentReader = streamSupport . createReader ( currentPath , currentStream ) ; } catch ( IOException e ) { WGLOG . error ( e , "" , resourceName , processName , currentPath ) ; throw e ; } return true ; } private void closeCurrentStream ( ) { WGLOG . info ( "" , resourceName , processName , currentPath , currentStream . getCount ( ) ) ; bytesCount += currentStream . getCount ( ) ; try { currentStream . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , resourceName , processName , currentPath ) ; } currentPath = null ; currentStream = null ; currentReader = null ; } @ Override public T get ( ) throws IOException { if ( sawNext == false ) { throw new IllegalStateException ( MessageFormat . format ( "" , resourceName , processName ) ) ; } return buffer ; } @ Override public void close ( ) throws IOException { if ( closed ) { return ; } if ( currentStream != null ) { closeCurrentStream ( ) ; } sawNext = false ; closed = true ; } } package com . asakusafw . windgate . stream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport . DataModelWriter ; public class StreamDrainDriver < T > implements DrainDriver < T > { static final WindGateLogger WGLOG = new WindGateStreamLogger ( StreamDrainDriver . class ) ; private final String resourceName ; private final String processName ; private final OutputStreamProvider streamProvider ; private final DataModelStreamSupport < ? super T > streamSupport ; private final long eachStreamSize ; private String currentPath ; private CountingOutputStream currentStream ; private DataModelWriter < ? super T > currentWriter ; private long bytesCount ; private boolean closed ; public StreamDrainDriver ( String resourceName , String processName , OutputStreamProvider streamProvider , DataModelStreamSupport < ? super T > streamSupport ) { if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( processName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( streamProvider == null ) { throw new IllegalArgumentException ( "" ) ; } if ( streamSupport == null ) { throw new IllegalArgumentException ( "" ) ; } this . resourceName = resourceName ; this . processName = processName ; this . streamProvider = streamProvider ; this . streamSupport = streamSupport ; if ( streamProvider . getDesiredStreamSize ( ) > ) { eachStreamSize = streamProvider . getDesiredStreamSize ( ) ; } else { eachStreamSize = Long . MAX_VALUE ; } } @ Override public void prepare ( ) throws IOException { prepareNextStream ( ) ; } @ Override public void put ( T object ) throws IOException { if ( currentWriter == null || currentStream . getCount ( ) >= eachStreamSize ) { if ( currentWriter != null ) { closeCurrentStream ( ) ; } prepareNextStream ( ) ; } currentWriter . write ( object ) ; } private void prepareNextStream ( ) throws IOException { streamProvider . next ( ) ; currentPath = streamProvider . getCurrentPath ( ) ; WGLOG . info ( "" , resourceName , processName , currentPath ) ; try { currentStream = streamProvider . openStream ( ) ; currentWriter = streamSupport . createWriter ( currentPath , currentStream ) ; } catch ( IOException e ) { WGLOG . error ( e , "" , resourceName , processName , currentPath ) ; throw e ; } } private void closeCurrentStream ( ) throws IOException { currentWriter . flush ( ) ; WGLOG . info ( "" , resourceName , processName , currentPath , currentStream . getCount ( ) ) ; bytesCount += currentStream . getCount ( ) ; try { currentStream . close ( ) ; } catch ( IOException e ) { WGLOG . error ( e , "" , resourceName , processName , currentPath ) ; throw e ; } currentPath = null ; currentStream = null ; currentWriter = null ; } @ Override public void close ( ) throws IOException { if ( closed ) { return ; } if ( currentWriter != null ) { closeCurrentStream ( ) ; } closed = true ; } } package com . asakusafw . windgate . stream ; import java . io . IOException ; import java . io . InputStream ; public final class CountingInputStream extends InputStream { private final InputStream target ; private long count ; public CountingInputStream ( InputStream target ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } this . target = target ; } public long getCount ( ) { return count ; } @ Override public int read ( ) throws IOException { int read = target . read ( ) ; if ( read > ) { count += ; } return read ; } @ Override public int read ( byte [ ] b ) throws IOException { int read = target . read ( b ) ; if ( read > ) { count += read ; } return read ; } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { int read = target . read ( b , off , len ) ; if ( read > ) { count += read ; } return read ; } @ Override public long skip ( long n ) throws IOException { long read = target . skip ( n ) ; return read ; } @ Override public int available ( ) throws IOException { return target . available ( ) ; } @ Override public void close ( ) throws IOException { target . close ( ) ; } @ Override public synchronized void mark ( int readlimit ) { target . mark ( readlimit ) ; } @ Override public synchronized void reset ( ) throws IOException { target . reset ( ) ; } @ Override public boolean markSupported ( ) { return target . markSupported ( ) ; } } package com . asakusafw . windgate . stream ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . StreamProcess ; public final class StreamResourceUtil { static final WindGateLogger WGLOG = new WindGateStreamLogger ( StreamResourceUtil . class ) ; static final Logger LOG = LoggerFactory . getLogger ( StreamResourceUtil . class ) ; @ SuppressWarnings ( "" ) public static < T > DataModelStreamSupport < ? super T > loadSupport ( ClassLoader classLoader , String resourceName , ProcessScript < T > script , DriverScript . Kind direction ) throws IOException { if ( classLoader == null ) { throw new IllegalArgumentException ( "" ) ; } if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } Map < String , String > configuration = script . getDriverScript ( direction ) . getConfiguration ( ) ; String supportClassName = configuration . get ( StreamProcess . STREAM_SUPPORT . key ( ) ) ; if ( supportClassName == null ) { WGLOG . error ( "" , resourceName , script . getName ( ) , StreamProcess . STREAM_SUPPORT . key ( ) , null ) ; throw new IOException ( MessageFormat . format ( "" , resourceName , script . getName ( ) , StreamProcess . STREAM_SUPPORT . key ( ) , null ) ) ; } LOG . debug ( "" , new Object [ ] { supportClassName , resourceName , script . getName ( ) , } ) ; Class < ? > supportClass ; try { supportClass = Class . forName ( supportClassName , true , classLoader ) ; } catch ( ClassNotFoundException e ) { WGLOG . error ( e , "" , resourceName , script . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , resourceName , script . getName ( ) , supportClassName ) , e ) ; } if ( DataModelStreamSupport . class . isAssignableFrom ( supportClass ) == false ) { WGLOG . error ( "" , resourceName , script . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , resourceName , script . getName ( ) , supportClass . getName ( ) , DataModelStreamSupport . class . getName ( ) ) ) ; } DataModelStreamSupport < ? > obj ; try { obj = supportClass . asSubclass ( DataModelStreamSupport . class ) . newInstance ( ) ; } catch ( Exception e ) { WGLOG . error ( e , "" , resourceName , script . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , resourceName , script . getName ( ) , supportClass . getName ( ) ) , e ) ; } if ( obj . getSupportedType ( ) . isAssignableFrom ( script . getDataClass ( ) ) == false ) { WGLOG . error ( "" , resourceName , script . getName ( ) , supportClassName ) ; throw new IOException ( MessageFormat . format ( "" , resourceName , script . getName ( ) , supportClass . getName ( ) , script . getDataClass ( ) . getName ( ) ) ) ; } return ( DataModelStreamSupport < ? super T > ) obj ; } private StreamResourceUtil ( ) { return ; } } package com . asakusafw . windgate . stream . file ; import java . io . File ; import java . text . MessageFormat ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . stream . WindGateStreamLogger ; public class FileProfile { static final WindGateLogger WGLOG = new WindGateStreamLogger ( FileProfile . class ) ; public static final String KEY_BASE_PATH = "" ; private final String resourceName ; private final ClassLoader classLoader ; private final File basePath ; public FileProfile ( String resourceName , ClassLoader classLoader , File basePath ) { if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( classLoader == null ) { throw new IllegalArgumentException ( "" ) ; } if ( basePath == null ) { throw new IllegalArgumentException ( "" ) ; } this . resourceName = resourceName ; this . classLoader = classLoader ; this . basePath = basePath ; } public String getResourceName ( ) { return resourceName ; } public ClassLoader getClassLoader ( ) { return classLoader ; } public File getBasePath ( ) { return basePath ; } public static FileProfile convert ( ResourceProfile profile ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } String resourceName = profile . getName ( ) ; ClassLoader classLoader = profile . getContext ( ) . getClassLoader ( ) ; String basePath = extract ( profile , KEY_BASE_PATH , false ) ; return new FileProfile ( resourceName , classLoader , new File ( basePath ) ) ; } private static String extract ( ResourceProfile profile , String configKey , boolean mandatory ) { assert profile != null ; assert configKey != null ; String value = profile . getConfiguration ( ) . get ( configKey ) ; if ( value == null ) { if ( mandatory == false ) { return null ; } else { WGLOG . error ( "" , profile . getName ( ) , configKey , null ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey ) ) ; } } try { return profile . getContext ( ) . getContextParameters ( ) . replace ( value . trim ( ) , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , profile . getName ( ) , configKey , value ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey , value ) , e ) ; } } } package com . asakusafw . windgate . stream . file ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . resource . ResourceProvider ; public class FileResourceProvider extends ResourceProvider { static final Logger LOG = LoggerFactory . getLogger ( FileResourceProvider . class ) ; private volatile FileProfile fileProfile ; @ Override protected void configure ( ResourceProfile profile ) throws IOException { LOG . debug ( "" , profile . getName ( ) ) ; try { this . fileProfile = FileProfile . convert ( profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getName ( ) ) , e ) ; } } @ Override public ResourceMirror create ( String sessionId , ParameterList arguments ) throws IOException { if ( sessionId == null ) { throw new IllegalArgumentException ( "" ) ; } return new FileResourceMirror ( fileProfile , arguments ) ; } @ Override public ResourceManipulator createManipulator ( ParameterList arguments ) throws IOException { return new FileResourceManipulator ( fileProfile , arguments ) ; } } package com . asakusafw . windgate . stream . file ; import java . io . File ; import java . io . IOException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . util . ProcessUtil ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . stream . StreamDrainDriver ; import com . asakusafw . windgate . stream . StreamSourceDriver ; import com . asakusafw . windgate . stream . WindGateStreamLogger ; @ SimulationSupport public class FileResourceMirror extends ResourceMirror { static final WindGateLogger WGLOG = new WindGateStreamLogger ( FileResourceMirror . class ) ; static final Logger LOG = LoggerFactory . getLogger ( FileResourceMirror . class ) ; private final FileProfile profile ; private final ParameterList arguments ; public FileResourceMirror ( FileProfile profile , ParameterList arguments ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . arguments = arguments ; } @ Override public String getName ( ) { return profile . getResourceName ( ) ; } @ Override public void prepare ( GateScript script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) ) ; for ( ProcessScript < ? > process : script . getProcesses ( ) ) { if ( process . getSourceScript ( ) . getResourceName ( ) . equals ( getName ( ) ) ) { FileResourceUtil . getPath ( profile , process , arguments , DriverScript . Kind . SOURCE ) ; FileResourceUtil . loadSupport ( profile , process , DriverScript . Kind . SOURCE ) ; ProcessUtil . newDataModel ( profile . getResourceName ( ) , process ) ; } if ( process . getDrainScript ( ) . getResourceName ( ) . equals ( getName ( ) ) ) { FileResourceUtil . getPath ( profile , process , arguments , DriverScript . Kind . DRAIN ) ; FileResourceUtil . loadSupport ( profile , process , DriverScript . Kind . DRAIN ) ; } } } @ Override public < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; File path = FileResourceUtil . getPath ( profile , script , arguments , DriverScript . Kind . SOURCE ) ; DataModelStreamSupport < ? super T > support = FileResourceUtil . loadSupport ( profile , script , DriverScript . Kind . SOURCE ) ; T model = ProcessUtil . newDataModel ( profile . getResourceName ( ) , script ) ; LOG . debug ( "" , new Object [ ] { path . getAbsolutePath ( ) , getName ( ) , script . getName ( ) , } ) ; FileInputStreamProvider provider = new FileInputStreamProvider ( path ) ; return new StreamSourceDriver < T > ( getName ( ) , script . getName ( ) , provider , support , model ) ; } @ Override public < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; File path = FileResourceUtil . getPath ( profile , script , arguments , DriverScript . Kind . DRAIN ) ; DataModelStreamSupport < ? super T > support = FileResourceUtil . loadSupport ( profile , script , DriverScript . Kind . DRAIN ) ; LOG . debug ( "" , new Object [ ] { path . getAbsolutePath ( ) , getName ( ) , script . getName ( ) , } ) ; FileOutputStreamProvider provider = new FileOutputStreamProvider ( path ) ; return new StreamDrainDriver < T > ( getName ( ) , script . getName ( ) , provider , support ) ; } @ Override public void close ( ) throws IOException { return ; } } package com . asakusafw . windgate . stream . file ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Map ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . stream . StreamResourceUtil ; import com . asakusafw . windgate . stream . WindGateStreamLogger ; final class FileResourceUtil { static final WindGateLogger WGLOG = new WindGateStreamLogger ( FileResourceUtil . class ) ; static final Logger LOG = LoggerFactory . getLogger ( FileResourceUtil . class ) ; public static < T > DataModelStreamSupport < ? super T > loadSupport ( FileProfile profile , ProcessScript < T > script , DriverScript . Kind direction ) throws IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } return StreamResourceUtil . loadSupport ( profile . getClassLoader ( ) , profile . getResourceName ( ) , script , direction ) ; } public static File getPath ( FileProfile profile , ProcessScript < ? > process , ParameterList arguments , DriverScript . Kind direction ) throws IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( process == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } if ( direction == null ) { throw new IllegalArgumentException ( "" ) ; } Map < String , String > configuration = process . getDriverScript ( direction ) . getConfiguration ( ) ; String rawPath = configuration . get ( FileProcess . FILE . key ( ) ) ; if ( rawPath == null ) { WGLOG . error ( "" , profile . getResourceName ( ) , process . getName ( ) , direction . prefix , FileProcess . FILE . key ( ) , null ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , process . getName ( ) , direction , FileProcess . FILE . key ( ) ) ) ; } LOG . debug ( "" , rawPath ) ; String path ; try { path = arguments . replace ( rawPath , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , profile . getResourceName ( ) , process . getName ( ) , direction . prefix , FileProcess . FILE . key ( ) , rawPath ) ; throw new IOException ( MessageFormat . format ( "" , profile . getResourceName ( ) , process . getName ( ) , direction , FileProcess . FILE . key ( ) , rawPath ) , e ) ; } return new File ( profile . getBasePath ( ) , path ) ; } private FileResourceUtil ( ) { return ; } } package com . asakusafw . windgate . stream . file ; package com . asakusafw . windgate . stream . file ; import java . io . BufferedOutputStream ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . Iterator ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . stream . CountingOutputStream ; import com . asakusafw . windgate . stream . OutputStreamProvider ; public class FileOutputStreamProvider extends OutputStreamProvider { static final Logger LOG = LoggerFactory . getLogger ( FileOutputStreamProvider . class ) ; private static final int BUFFER_SIZE = * ; private final Iterator < File > iterator ; private File current ; public FileOutputStreamProvider ( File file ) { if ( file == null ) { throw new IllegalArgumentException ( "" ) ; } this . iterator = Arrays . asList ( file ) . iterator ( ) ; } @ Override public void next ( ) throws IOException { current = null ; if ( iterator . hasNext ( ) ) { current = iterator . next ( ) . getCanonicalFile ( ) ; } else { throw new IOException ( ) ; } } @ Override public String getCurrentPath ( ) { return current . getAbsolutePath ( ) ; } @ Override public CountingOutputStream openStream ( ) throws IOException { LOG . debug ( "" , current ) ; boolean succeed = false ; File parent = current . getParentFile ( ) ; for ( int i = ; i < ; i ++ ) { if ( parent == null || parent . exists ( ) ) { break ; } LOG . debug ( "" , current ) ; if ( parent . mkdirs ( ) ) { break ; } } if ( parent != null && parent . isDirectory ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , parent . getAbsolutePath ( ) ) ) ; } FileOutputStream stream = new FileOutputStream ( current ) ; try { CountingOutputStream result = new CountingOutputStream ( new BufferedOutputStream ( stream , BUFFER_SIZE ) ) ; succeed = true ; return result ; } finally { if ( succeed == false ) { try { stream . close ( ) ; } catch ( IOException ignored ) { } } } } @ Override public void close ( ) { return ; } } package com . asakusafw . windgate . stream . file ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . Iterator ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . stream . CountingInputStream ; import com . asakusafw . windgate . stream . InputStreamProvider ; public class FileInputStreamProvider extends InputStreamProvider { static final Logger LOG = LoggerFactory . getLogger ( FileInputStreamProvider . class ) ; private static final int BUFFER_SIZE = * ; private final Iterator < File > iterator ; private File current ; public FileInputStreamProvider ( File file ) { if ( file == null ) { throw new IllegalArgumentException ( "" ) ; } this . iterator = Arrays . asList ( file ) . iterator ( ) ; } @ Override public boolean next ( ) throws IOException { current = null ; if ( iterator . hasNext ( ) ) { current = iterator . next ( ) . getCanonicalFile ( ) ; return true ; } else { return false ; } } @ Override public String getCurrentPath ( ) { return current . getAbsolutePath ( ) ; } @ Override public CountingInputStream openStream ( ) throws IOException { LOG . debug ( "" , current ) ; boolean succeed = false ; FileInputStream stream = new FileInputStream ( current ) ; try { CountingInputStream result = new CountingInputStream ( new BufferedInputStream ( stream , BUFFER_SIZE ) ) ; succeed = true ; return result ; } finally { if ( succeed == false ) { try { stream . close ( ) ; } catch ( IOException ignored ) { } } } } @ Override public void close ( ) { return ; } } package com . asakusafw . windgate . stream . file ; import java . io . File ; import java . io . IOException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . util . ProcessUtil ; import com . asakusafw . windgate . core . vocabulary . DataModelStreamSupport ; import com . asakusafw . windgate . stream . StreamDrainDriver ; import com . asakusafw . windgate . stream . StreamSourceDriver ; public class FileResourceManipulator extends ResourceManipulator { static final Logger LOG = LoggerFactory . getLogger ( FileResourceManipulator . class ) ; private final FileProfile profile ; private final ParameterList arguments ; public FileResourceManipulator ( FileProfile profile , ParameterList arguments ) { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . arguments = arguments ; } @ Override public String getName ( ) { return profile . getResourceName ( ) ; } @ Override public void cleanupSource ( ProcessScript < ? > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } File path = FileResourceUtil . getPath ( profile , script , arguments , DriverScript . Kind . SOURCE ) ; delete ( path ) ; } @ Override public void cleanupDrain ( ProcessScript < ? > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } File path = FileResourceUtil . getPath ( profile , script , arguments , DriverScript . Kind . DRAIN ) ; delete ( path ) ; } private void delete ( File path ) { assert path != null ; LOG . info ( "" , path . getAbsolutePath ( ) ) ; if ( path . delete ( ) ) { LOG . info ( "" , path . getAbsolutePath ( ) ) ; } else { LOG . info ( "" , path . getAbsolutePath ( ) ) ; } } @ Override public < T > SourceDriver < T > createSourceForSource ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } File path = FileResourceUtil . getPath ( profile , script , arguments , DriverScript . Kind . SOURCE ) ; DataModelStreamSupport < ? super T > support = FileResourceUtil . loadSupport ( profile , script , DriverScript . Kind . SOURCE ) ; T model = ProcessUtil . newDataModel ( profile . getResourceName ( ) , script ) ; FileInputStreamProvider provider = new FileInputStreamProvider ( path ) ; return new StreamSourceDriver < T > ( profile . getResourceName ( ) , script . getName ( ) , provider , support , model ) ; } @ Override public < T > DrainDriver < T > createDrainForSource ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } File path = FileResourceUtil . getPath ( profile , script , arguments , DriverScript . Kind . SOURCE ) ; DataModelStreamSupport < ? super T > support = FileResourceUtil . loadSupport ( profile , script , DriverScript . Kind . SOURCE ) ; FileOutputStreamProvider provider = new FileOutputStreamProvider ( path ) ; return new StreamDrainDriver < T > ( profile . getResourceName ( ) , script . getName ( ) , provider , support ) ; } @ Override public < T > SourceDriver < T > createSourceForDrain ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } File path = FileResourceUtil . getPath ( profile , script , arguments , DriverScript . Kind . DRAIN ) ; DataModelStreamSupport < ? super T > support = FileResourceUtil . loadSupport ( profile , script , DriverScript . Kind . DRAIN ) ; T model = ProcessUtil . newDataModel ( profile . getResourceName ( ) , script ) ; FileInputStreamProvider provider = new FileInputStreamProvider ( path ) ; return new StreamSourceDriver < T > ( profile . getResourceName ( ) , script . getName ( ) , provider , support , model ) ; } @ Override public < T > DrainDriver < T > createDrainForDrain ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } File path = FileResourceUtil . getPath ( profile , script , arguments , DriverScript . Kind . DRAIN ) ; DataModelStreamSupport < ? super T > support = FileResourceUtil . loadSupport ( profile , script , DriverScript . Kind . DRAIN ) ; FileOutputStreamProvider provider = new FileOutputStreamProvider ( path ) ; return new StreamDrainDriver < T > ( profile . getResourceName ( ) , script . getName ( ) , provider , support ) ; } } package com . asakusafw . windgate . stream ; import java . io . Closeable ; import java . io . IOException ; import java . io . InputStream ; public abstract class InputStreamProvider implements Closeable { public abstract boolean next ( ) throws IOException ; public abstract String getCurrentPath ( ) ; public abstract CountingInputStream openStream ( ) throws IOException ; } package com . asakusafw . windgate . hadoopfs ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Text ; import org . junit . Assume ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; public class HadoopFsMirrorTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; @ Rule public final TemporaryFolder temp = new TemporaryFolder ( ) ; private Configuration conf ; private Path working ; private FileSystem fs ; @ Before public void setUp ( ) throws Exception { conf = new ConfigurationProvider ( ) . newInstance ( ) ; working = new Path ( temp . getRoot ( ) . toURI ( ) ) ; fs = FileSystem . get ( working . toUri ( ) , conf ) ; Assume . assumeThat ( working . toString ( ) , is ( not ( containsString ( "" ) ) ) ) ; } @ Test public void source ( ) throws Exception { set ( "" , "" ) ; HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = source ( "" , "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_parameterized ( ) throws Exception { set ( "" , "" ) ; HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( Collections . singletonMap ( "" , "" ) ) ) ; try { ProcessScript < Text > process = source ( "" , "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_multivalue ( ) throws Exception { set ( "" , "" , "" , "" ) ; HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = source ( "" , "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" , "" , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_multisource ( ) throws Exception { set ( "" , "" ) ; set ( "" , "" ) ; set ( "" , "" ) ; HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = source ( "" , "" , "" , "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" , "" , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_glob ( ) throws Exception { set ( "" , "" ) ; set ( "" , "" ) ; set ( "" , "" ) ; HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = source ( "" , "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; try { driver . prepare ( ) ; test ( driver , "" , "" , "" ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( resource ) , is ( true ) ) ; ProcessScript < Text > process = source ( "" , "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( driver ) , is ( false ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_missing ( ) throws Exception { HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = source ( "" , "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; driver . prepare ( ) ; driver . get ( ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void source_nosource ( ) throws Exception { HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = source ( "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void source_invalid_parameter ( ) throws Exception { HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = source ( "" , "" ) ; resource . prepare ( script ( process ) ) ; SourceDriver < Text > driver = resource . createSource ( process ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void drain ( ) throws Exception { HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = drain ( "" , "" ) ; resource . prepare ( script ( process ) ) ; DrainDriver < Text > driver = resource . createDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new Text ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } test ( "" , "" ) ; } @ Test public void drain_parameterized ( ) throws Exception { HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( Collections . singletonMap ( "" , "" ) ) ) ; try { ProcessScript < Text > process = drain ( "" , "" ) ; resource . prepare ( script ( process ) ) ; DrainDriver < Text > driver = resource . createDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new Text ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } test ( "" , "" ) ; } @ Test public void drain_multivalue ( ) throws Exception { HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = drain ( "" , "" ) ; resource . prepare ( script ( process ) ) ; DrainDriver < Text > driver = resource . createDrain ( process ) ; try { driver . prepare ( ) ; driver . put ( new Text ( "" ) ) ; driver . put ( new Text ( "" ) ) ; driver . put ( new Text ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } test ( "" , "" , "" , "" ) ; } @ Test public void drain_multisource ( ) throws Exception { HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = drain ( "" , "" , "" , "" ) ; resource . prepare ( script ( process ) ) ; DrainDriver < Text > driver = resource . createDrain ( process ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void drain_conflict ( ) throws Exception { fs . mkdirs ( new Path ( working , "" ) ) ; HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = drain ( "" , "" ) ; resource . prepare ( script ( process ) ) ; DrainDriver < Text > driver = resource . createDrain ( process ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void drain_invalid_parameter ( ) throws Exception { HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { ProcessScript < Text > process = drain ( "" , "" ) ; resource . prepare ( script ( process ) ) ; DrainDriver < Text > driver = resource . createDrain ( process ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void drain_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; HadoopFsMirror resource = new HadoopFsMirror ( conf , profile ( ) , new ParameterList ( ) ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( resource ) , is ( true ) ) ; ProcessScript < Text > process = drain ( "" , "" ) ; resource . prepare ( script ( process ) ) ; DrainDriver < Text > driver = resource . createDrain ( process ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( driver ) , is ( false ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } try { FileStatus status = fs . getFileStatus ( getPath ( "" ) ) ; assertThat ( status , is ( nullValue ( ) ) ) ; } catch ( IOException e ) { } } private HadoopFsProfile profile ( ) { return new HadoopFsProfile ( "" , working , null ) ; } private GateScript script ( ProcessScript < ? > ... processes ) { return new GateScript ( "" , Arrays . asList ( processes ) ) ; } private ProcessScript < Text > source ( String resource , String ... files ) { StringBuilder buf = new StringBuilder ( ) ; for ( String file : files ) { buf . append ( file ) ; buf . append ( "" ) ; } return new ProcessScript < Text > ( "" , "" , Text . class , d ( resource , buf . toString ( ) . trim ( ) ) , new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) ) ; } private ProcessScript < Text > drain ( String resource , String ... files ) { StringBuilder buf = new StringBuilder ( ) ; for ( String file : files ) { buf . append ( file ) ; buf . append ( "" ) ; } return new ProcessScript < Text > ( "" , "" , Text . class , new DriverScript ( "" , Collections . < String , String > emptyMap ( ) ) , d ( resource , buf . toString ( ) . trim ( ) ) ) ; } private DriverScript d ( String name , String file ) { return new DriverScript ( name , file == null ? Collections . < String , String > emptyMap ( ) : Collections . singletonMap ( FileProcess . FILE . key ( ) , file ) ) ; } private void test ( SourceDriver < Text > source , String ... expects ) throws IOException { List < String > results = new ArrayList < String > ( ) ; while ( source . next ( ) ) { results . add ( source . get ( ) . toString ( ) ) ; } Arrays . sort ( expects ) ; Collections . sort ( results ) ; assertThat ( results , is ( Arrays . asList ( expects ) ) ) ; } private void test ( String path , String ... expects ) throws IOException { List < String > results = new ArrayList < String > ( ) ; Path resolved = getPath ( path ) ; ModelInput < Text > input = TemporaryStorage . openInput ( conf , Text . class , resolved ) ; try { Text text = new Text ( ) ; while ( input . readTo ( text ) ) { results . add ( text . toString ( ) ) ; } } finally { input . close ( ) ; } assertThat ( results , is ( Arrays . asList ( expects ) ) ) ; } private void set ( String path , String ... values ) throws IOException { Path resolved = getPath ( path ) ; ModelOutput < Text > output = TemporaryStorage . openOutput ( conf , Text . class , resolved ) ; try { for ( String string : values ) { output . write ( new Text ( string ) ) ; } } finally { output . close ( ) ; } } private Path getPath ( String path ) { Path resolved = new Path ( working , path ) ; return resolved ; } } package com . asakusafw . windgate . hadoopfs . ssh ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import org . apache . hadoop . fs . Path ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class FileListTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void simple ( ) throws Exception { File file = folder . newFile ( "" ) ; FileOutputStream output = new FileOutputStream ( file ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; write ( writer , "" , "" ) ; writer . close ( ) ; } finally { output . close ( ) ; } FileInputStream input = new FileInputStream ( file ) ; try { FileList . Reader reader = FileList . createReader ( input ) ; read ( reader , "" , "" ) ; assertThat ( reader . next ( ) , is ( false ) ) ; reader . close ( ) ; } finally { input . close ( ) ; } } @ Test public void empty ( ) throws Exception { File file = folder . newFile ( "" ) ; FileOutputStream output = new FileOutputStream ( file ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; writer . close ( ) ; } finally { output . close ( ) ; } FileInputStream input = new FileInputStream ( file ) ; try { FileList . Reader reader = FileList . createReader ( input ) ; assertThat ( reader . next ( ) , is ( false ) ) ; reader . close ( ) ; } finally { input . close ( ) ; } } @ Test public void multiple ( ) throws Exception { File file = folder . newFile ( "" ) ; FileOutputStream output = new FileOutputStream ( file ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; write ( writer , "" , "" ) ; write ( writer , "" , "" ) ; write ( writer , "" , "" ) ; writer . close ( ) ; } finally { output . close ( ) ; } FileInputStream input = new FileInputStream ( file ) ; try { FileList . Reader reader = FileList . createReader ( input ) ; read ( reader , "" , "" ) ; read ( reader , "" , "" ) ; read ( reader , "" , "" ) ; assertThat ( reader . next ( ) , is ( false ) ) ; reader . close ( ) ; } finally { input . close ( ) ; } } @ Test public void unexpected_eof ( ) throws Exception { File file = folder . newFile ( "" ) ; FileOutputStream output = new FileOutputStream ( file ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; write ( writer , "" , "" ) ; write ( writer , "" , "" ) ; write ( writer , "" , "" ) ; } finally { output . close ( ) ; } FileInputStream input = new FileInputStream ( file ) ; try { FileList . Reader reader = FileList . createReader ( input ) ; read ( reader , "" , "" ) ; read ( reader , "" , "" ) ; read ( reader , "" , "" ) ; reader . next ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { input . close ( ) ; } } @ Test public void invalid_stream ( ) throws Exception { File file = folder . newFile ( "" ) ; FileInputStream input = new FileInputStream ( file ) ; try { FileList . Reader reader = FileList . createReader ( input ) ; reader . next ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { input . close ( ) ; } } private void write ( FileList . Writer writer , String path , String content ) throws IOException { OutputStream f = writer . openNext ( FileList . createFileStatus ( new Path ( path ) ) ) ; try { f . write ( content . getBytes ( "" ) ) ; } finally { f . close ( ) ; } } private void read ( FileList . Reader reader , String path , String content ) throws IOException { assertThat ( reader . next ( ) , is ( true ) ) ; assertThat ( reader . getCurrentFile ( ) . getPath ( ) . toString ( ) , is ( path ) ) ; InputStream f = reader . openContent ( ) ; try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = f . read ( buf ) ; if ( read < ) { break ; } baos . write ( buf , , read ) ; } String result = new String ( baos . toByteArray ( ) , "" ) ; assertThat ( path , result , is ( content ) ) ; } finally { f . close ( ) ; } } } package com . asakusafw . windgate . hadoopfs . ssh ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . junit . After ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; public class WindGateHadoopPutTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; private static final Path PREFIX = new Path ( "" ) ; private Configuration conf ; private FileSystem fs ; private InputStream stdin ; @ Before public void setUp ( ) throws Exception { conf = new Configuration ( ) ; fs = FileSystem . get ( conf ) ; clear ( ) ; stdin = System . in ; } @ After public void tearDown ( ) throws Exception { if ( stdin != null ) { System . setIn ( stdin ) ; } clear ( ) ; } private void clear ( ) throws IOException { if ( fs == null ) { return ; } fs . delete ( PREFIX , true ) ; } @ Test public void simple ( ) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( buffer ) ; Path testing = new Path ( PREFIX , "" ) ; put ( writer , testing , "" ) ; writer . close ( ) ; ByteArrayInputStream in = new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; int result = new WindGateHadoopPut ( conf ) . execute ( in ) ; assertThat ( result , is ( ) ) ; Map < String , String > contents = get ( ) ; assertThat ( contents . size ( ) , is ( ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; } @ Test public void multiple ( ) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( buffer ) ; Path testing1 = new Path ( PREFIX , "" ) ; Path testing2 = new Path ( PREFIX , "" ) ; Path testing3 = new Path ( PREFIX , "" ) ; put ( writer , testing1 , "" ) ; put ( writer , testing2 , "" ) ; put ( writer , testing3 , "" ) ; writer . close ( ) ; ByteArrayInputStream in = new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; int result = new WindGateHadoopPut ( conf ) . execute ( in ) ; assertThat ( result , is ( ) ) ; Map < String , String > contents = get ( ) ; assertThat ( contents . size ( ) , is ( ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; } @ Test public void empty ( ) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( buffer ) ; writer . close ( ) ; ByteArrayInputStream in = new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; int result = new WindGateHadoopPut ( conf ) . execute ( in ) ; assertThat ( result , is ( ) ) ; Map < String , String > contents = get ( ) ; assertThat ( contents . size ( ) , is ( ) ) ; } @ Test public void arguments ( ) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( buffer ) ; Path testing = new Path ( PREFIX , "" ) ; put ( writer , testing , "" ) ; writer . close ( ) ; ByteArrayInputStream in = new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; int result = new WindGateHadoopPut ( conf ) . execute ( in , testing . toString ( ) ) ; assertThat ( result , is ( not ( ) ) ) ; } @ Test public void broken ( ) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( buffer ) ; Path testing = new Path ( PREFIX , "" ) ; put ( writer , testing , "" ) ; ByteArrayInputStream in = new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; int result = new WindGateHadoopPut ( conf ) . execute ( in ) ; assertThat ( result , is ( not ( ) ) ) ; } @ Test public void simulated ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; FileList . Writer writer = FileList . createWriter ( buffer ) ; Path testing = new Path ( PREFIX , "" ) ; put ( writer , testing , "" ) ; writer . close ( ) ; ByteArrayInputStream in = new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; int result = new WindGateHadoopPut ( conf ) . execute ( in ) ; assertThat ( result , is ( ) ) ; Map < String , String > contents = get ( ) ; assertThat ( contents . size ( ) , is ( ) ) ; } private void put ( FileList . Writer writer , Path path , String string ) throws IOException { FileStatus status = FileList . createFileStatus ( path ) ; OutputStream out = writer . openNext ( status ) ; try { out . write ( string . getBytes ( "" ) ) ; } finally { out . close ( ) ; } } private Map < String , String > get ( ) throws IOException { FileStatus [ ] files = fs . listStatus ( PREFIX ) ; if ( files == null ) { return Collections . emptyMap ( ) ; } Map < String , String > results = new HashMap < String , String > ( ) ; for ( FileStatus status : files ) { if ( status . isDir ( ) ) { continue ; } InputStream f = fs . open ( status . getPath ( ) ) ; try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = f . read ( buf ) ; if ( read < ) { break ; } baos . write ( buf , , read ) ; } String result = new String ( baos . toByteArray ( ) , "" ) ; results . put ( status . getPath ( ) . getName ( ) , result ) ; } finally { f . close ( ) ; } } return results ; } } package com . asakusafw . windgate . hadoopfs . ssh ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Text ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; public class AbstractSshHadoopFsMirrorTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; @ Rule public final TemporaryFolder folder = new TemporaryFolder ( ) ; private final SshProfile profile ; { Map < String , String > emptyMap = Collections . emptyMap ( ) ; profile = new SshProfile ( "" , "" , "" , "" , , "" , "" , null , emptyMap ) { @ Override public String getGetCommand ( ) { return "" ; } @ Override public String getPutCommand ( ) { return "" ; } @ Override public String getDeleteCommand ( ) { return "" ; } } ; } volatile List < String > lastCommand ; volatile File stdIn ; volatile File stdOut ; volatile int exit = - ; @ Test public void drain ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; DrainDriver < Text > driver = resource . createDrain ( proc ) ; try { driver . prepare ( ) ; driver . put ( new Text ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } assertThat ( lastCommand , is ( Arrays . asList ( "" ) ) ) ; Map < String , List < String > > results = read ( stdIn ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( "" ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void drain_parameter ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( Collections . singletonMap ( "" , "" ) ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; DrainDriver < Text > driver = resource . createDrain ( proc ) ; try { driver . prepare ( ) ; driver . put ( new Text ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } assertThat ( lastCommand , is ( Arrays . asList ( "" ) ) ) ; Map < String , List < String > > results = read ( stdIn ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( "" ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void drain_multiple ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; DrainDriver < Text > driver = resource . createDrain ( proc ) ; try { driver . prepare ( ) ; driver . put ( new Text ( "" ) ) ; driver . put ( new Text ( "" ) ) ; driver . put ( new Text ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } Map < String , List < String > > results = read ( stdIn ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( "" ) , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test public void drain_nullpath ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , null ) ; resource . prepare ( script ( proc ) ) ; DrainDriver < Text > driver = resource . createDrain ( proc ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void drain_nopath ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; DrainDriver < Text > driver = resource . createDrain ( proc ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void drain_invalid_parameter ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( Collections . singletonMap ( "" , "" ) ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; DrainDriver < Text > driver = resource . createDrain ( proc ) ; driver . close ( ) ; fail ( ) ; } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test ( expected = IOException . class ) public void drain_processfailed ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; DrainDriver < Text > driver = resource . createDrain ( proc ) ; try { driver . prepare ( ) ; driver . put ( new Text ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void drain_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( resource ) , is ( true ) ) ; ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; DrainDriver < Text > driver = resource . createDrain ( proc ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( driver ) , is ( true ) ) ; driver . prepare ( ) ; driver . put ( new Text ( "" ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } assertThat ( lastCommand , is ( Arrays . asList ( "" ) ) ) ; Map < String , List < String > > results = read ( stdIn ) ; assertThat ( results . size ( ) , is ( ) ) ; assertThat ( results . get ( "" ) , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void source ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" ) ; writer . close ( ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } Collections . sort ( results ) ; assertThat ( lastCommand , is ( Arrays . asList ( "" , "" ) ) ) ; assertThat ( results , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void source_parameter ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" ) ; writer . close ( ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( Collections . singletonMap ( "" , "" ) ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } Collections . sort ( results ) ; assertThat ( lastCommand , is ( Arrays . asList ( "" , "" ) ) ) ; assertThat ( results , is ( Arrays . asList ( "" ) ) ) ; } @ Test public void source_multiple_values ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" , "" , "" ) ; writer . close ( ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } Collections . sort ( results ) ; assertThat ( lastCommand , is ( Arrays . asList ( "" , "" ) ) ) ; assertThat ( results , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test public void source_multiple_files ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" ) ; put ( writer , "" , "" ) ; put ( writer , "" , "" ) ; writer . close ( ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } Collections . sort ( results ) ; assertThat ( lastCommand , is ( Arrays . asList ( "" , "" , "" , "" ) ) ) ; assertThat ( results , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test public void source_invalid_contents ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } fail ( ) ; } finally { driver . close ( ) ; } } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void source_nullpath ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , null , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } fail ( ) ; } finally { driver . close ( ) ; } } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test public void source_emptypath ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } fail ( ) ; } finally { driver . close ( ) ; } } catch ( IOException e ) { } finally { resource . close ( ) ; } } @ Test ( expected = IOException . class ) public void source_processfailed ( ) throws Exception { stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" ) ; writer . close ( ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void source_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; stdIn = folder . newFile ( "" ) ; stdOut = folder . newFile ( "" ) ; exit = ; FileOutputStream output = new FileOutputStream ( stdOut ) ; try { FileList . Writer writer = FileList . createWriter ( output ) ; put ( writer , "" , "" ) ; writer . close ( ) ; } finally { output . close ( ) ; } List < String > results = new ArrayList < String > ( ) ; MockSshHadoopFsMirror resource = new MockSshHadoopFsMirror ( new Configuration ( ) , profile , new ParameterList ( ) ) ; try { assertThat ( RuntimeContext . get ( ) . canExecute ( resource ) , is ( true ) ) ; ProcessScript < Text > proc = p ( "" , "" , "" , "" , "" ) ; resource . prepare ( script ( proc ) ) ; SourceDriver < Text > driver = resource . createSource ( proc ) ; try { driver . prepare ( ) ; assertThat ( RuntimeContext . get ( ) . canExecute ( driver ) , is ( true ) ) ; while ( driver . next ( ) ) { results . add ( driver . get ( ) . toString ( ) ) ; } } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } Collections . sort ( results ) ; assertThat ( lastCommand , is ( Arrays . asList ( "" , "" ) ) ) ; assertThat ( results , is ( Arrays . asList ( "" ) ) ) ; } private void put ( FileList . Writer writer , String path , String ... contents ) throws IOException { Configuration conf = new Configuration ( ) ; File temp = folder . newFile ( path ) ; FileSystem fs = FileSystem . getLocal ( conf ) ; ModelOutput < Text > output = TemporaryStorage . openOutput ( conf , Text . class , new Path ( temp . toURI ( ) ) ) ; try { for ( String content : contents ) { output . write ( new Text ( content ) ) ; } } finally { output . close ( ) ; } FileStatus status = fs . getFileStatus ( new Path ( temp . toURI ( ) ) ) ; FSDataInputStream src = fs . open ( status . getPath ( ) ) ; try { OutputStream dst = writer . openNext ( status ) ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = src . read ( buf ) ; if ( read < ) { break ; } dst . write ( buf , , read ) ; } dst . close ( ) ; } finally { src . close ( ) ; } } private Map < String , List < String > > read ( File file ) throws IOException { List < File > files = new ArrayList < File > ( ) ; FileInputStream in = new FileInputStream ( file ) ; try { FileList . Reader reader = FileList . createReader ( in ) ; while ( reader . next ( ) ) { FileStatus status = reader . getCurrentFile ( ) ; File entry = folder . newFile ( status . getPath ( ) . getName ( ) ) ; FileOutputStream dst = new FileOutputStream ( entry ) ; try { InputStream src = reader . openContent ( ) ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = src . read ( buf ) ; if ( read < ) { break ; } dst . write ( buf , , read ) ; } } finally { dst . close ( ) ; } files . add ( entry ) ; } } finally { in . close ( ) ; } Configuration conf = new Configuration ( ) ; Map < String , List < String > > results = new HashMap < String , List < String > > ( ) ; Text text = new Text ( ) ; for ( File entry : files ) { List < String > lines = new ArrayList < String > ( ) ; results . put ( entry . getName ( ) , lines ) ; ModelInput < Text > input = TemporaryStorage . openInput ( conf , Text . class , new Path ( entry . toURI ( ) ) ) ; try { while ( input . readTo ( text ) ) { lines . add ( text . toString ( ) ) ; } } finally { input . close ( ) ; } } return results ; } private GateScript script ( ProcessScript < ? > ... processes ) { return new GateScript ( "" , Arrays . asList ( processes ) ) ; } private ProcessScript < Text > p ( String name , String sourceName , String sourceFile , String drainName , String drainFile ) { return new ProcessScript < Text > ( name , "" , Text . class , d ( sourceName , sourceFile ) , d ( drainName , drainFile ) ) ; } private DriverScript d ( String name , String file ) { return new DriverScript ( name , file == null ? Collections . < String , String > emptyMap ( ) : Collections . singletonMap ( FileProcess . FILE . key ( ) , file ) ) ; } @ SimulationSupport private class MockSshHadoopFsMirror extends AbstractSshHadoopFsMirror { MockSshHadoopFsMirror ( Configuration configuration , SshProfile profile , ParameterList arguments ) { super ( configuration , profile , arguments ) ; } @ Override protected SshConnection openConnection ( SshProfile sshProfile , List < String > command ) throws IOException { lastCommand = command ; return new SshConnection ( ) { @ Override public void connect ( ) throws IOException { return ; } @ Override public OutputStream openStandardInput ( ) throws IOException { return new FileOutputStream ( stdIn ) ; } @ Override public InputStream openStandardOutput ( ) throws IOException { return new FileInputStream ( stdOut ) ; } @ Override public void redirectStandardOutput ( OutputStream output , boolean dontClose ) { return ; } @ Override public int waitForExit ( long timeout ) throws IOException , InterruptedException { return exit ; } @ Override public void close ( ) throws IOException { return ; } } ; } } } package com . asakusafw . windgate . hadoopfs . ssh ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . PrintStream ; import java . util . HashMap ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . junit . After ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; public class WindGateHadoopGetTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; private static final Path PREFIX = new Path ( "" ) ; private Configuration conf ; private FileSystem fs ; private PrintStream stdout ; @ Before public void setUp ( ) throws Exception { conf = new Configuration ( ) ; fs = FileSystem . get ( conf ) ; clear ( ) ; stdout = System . out ; } @ After public void tearDown ( ) throws Exception { if ( stdout != null ) { System . setOut ( stdout ) ; } clear ( ) ; } private void clear ( ) throws IOException { if ( fs == null ) { return ; } fs . delete ( PREFIX , true ) ; } @ Test public void simple ( ) throws Exception { Path testing = new Path ( PREFIX , "" ) ; put ( testing , "" ) ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int result = new WindGateHadoopGet ( conf ) . execute ( buffer , testing . toString ( ) ) ; assertThat ( result , is ( ) ) ; Map < String , String > contents = get ( buffer . toByteArray ( ) ) ; assertThat ( contents . size ( ) , is ( ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; } @ Test public void multiple ( ) throws Exception { Path path1 = new Path ( PREFIX , "" ) ; Path path2 = new Path ( PREFIX , "" ) ; Path path3 = new Path ( PREFIX , "" ) ; put ( path1 , "" ) ; put ( path2 , "" ) ; put ( path3 , "" ) ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int result = new WindGateHadoopGet ( conf ) . execute ( buffer , path1 . toString ( ) , path2 . toString ( ) , path3 . toString ( ) ) ; assertThat ( result , is ( ) ) ; Map < String , String > contents = get ( buffer . toByteArray ( ) ) ; assertThat ( contents . size ( ) , is ( ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; } @ Test public void glob ( ) throws Exception { Path path1 = new Path ( PREFIX , "" ) ; Path path2 = new Path ( PREFIX , "" ) ; Path path3 = new Path ( PREFIX , "" ) ; put ( path1 , "" ) ; put ( path2 , "" ) ; put ( path3 , "" ) ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int result = new WindGateHadoopGet ( conf ) . execute ( buffer , new Path ( PREFIX , "" ) . toString ( ) ) ; assertThat ( result , is ( ) ) ; Map < String , String > contents = get ( buffer . toByteArray ( ) ) ; assertThat ( contents . size ( ) , is ( ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; assertThat ( contents . get ( "" ) , is ( "" ) ) ; } @ Test public void missing ( ) throws Exception { Path testing = new Path ( PREFIX , "" ) ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int result = new WindGateHadoopGet ( conf ) . execute ( buffer , testing . toString ( ) ) ; assertThat ( result , is ( not ( ) ) ) ; } @ Test public void empty ( ) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int result = new WindGateHadoopGet ( conf ) . execute ( buffer ) ; assertThat ( result , is ( not ( ) ) ) ; } @ Test public void simulated ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; Path testing = new Path ( PREFIX , "" ) ; put ( testing , "" ) ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int result = new WindGateHadoopGet ( conf ) . execute ( buffer , testing . toString ( ) ) ; assertThat ( result , is ( ) ) ; Map < String , String > contents = get ( buffer . toByteArray ( ) ) ; assertThat ( contents . toString ( ) , contents . size ( ) , is ( ) ) ; } @ Test public void missing_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; Path testing = new Path ( PREFIX , "" ) ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int result = new WindGateHadoopGet ( conf ) . execute ( buffer , testing . toString ( ) ) ; assertThat ( result , is ( ) ) ; } private void put ( Path path , String string ) throws IOException { FSDataOutputStream out = fs . create ( path , true ) ; try { out . write ( string . getBytes ( "" ) ) ; } finally { out . close ( ) ; } } private Map < String , String > get ( byte [ ] contents ) throws IOException { FileList . Reader reader = FileList . createReader ( new ByteArrayInputStream ( contents ) ) ; Map < String , String > results = new HashMap < String , String > ( ) ; while ( reader . next ( ) ) { InputStream f = reader . openContent ( ) ; try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = f . read ( buf ) ; if ( read < ) { break ; } baos . write ( buf , , read ) ; } String result = new String ( baos . toByteArray ( ) , "" ) ; results . put ( reader . getCurrentFile ( ) . getPath ( ) . getName ( ) , result ) ; } finally { f . close ( ) ; } } return results ; } } package com . asakusafw . windgate . hadoopfs ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . compress . DefaultCodec ; import org . junit . Before ; import org . junit . Test ; import com . asakusafw . runtime . util . hadoop . ConfigurationProvider ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . resource . ResourceProfile ; public class HadoopFsProfileTest { private Configuration hadoopConf ; @ Before public void setUp ( ) throws Exception { hadoopConf = new ConfigurationProvider ( ) . newInstance ( ) ; } @ Test public void convert ( ) throws Exception { hadoopConf . set ( "" , "" ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( ) ) , conf ) ; HadoopFsProfile profile = HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; assertThat ( profile . getResourceName ( ) , is ( "" ) ) ; assertThat ( profile . getBasePath ( ) . toUri ( ) . getScheme ( ) , is ( "" ) ) ; assertThat ( profile . getCompressionCodec ( ) , is ( nullValue ( ) ) ) ; } @ Test public void convert_basePath ( ) throws Exception { File current = new File ( "" ) . getAbsoluteFile ( ) . getCanonicalFile ( ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( HadoopFsProfile . KEY_BASE_PATH , current . toURI ( ) . toString ( ) ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( ) ) , conf ) ; HadoopFsProfile profile = HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; assertThat ( profile . getResourceName ( ) , is ( "" ) ) ; assertThat ( profile . getBasePath ( ) , is ( new Path ( current . toURI ( ) ) ) ) ; } @ Test public void convert_basePath_relative ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( HadoopFsProfile . KEY_BASE_PATH , "" ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( ) ) , conf ) ; HadoopFsProfile profile = HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; assertThat ( profile . getResourceName ( ) , is ( "" ) ) ; assertThat ( profile . getBasePath ( ) . getName ( ) , is ( "" ) ) ; } @ Test public void convert_basePath_parameterize ( ) throws Exception { File current = new File ( "" ) . getAbsoluteFile ( ) . getCanonicalFile ( ) ; Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( HadoopFsProfile . KEY_BASE_PATH , current . toURI ( ) . toString ( ) + "" ) ; Map < String , String > env = new HashMap < String , String > ( ) ; env . put ( "" , "" ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( env ) ) , conf ) ; HadoopFsProfile profile = HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; assertThat ( profile . getResourceName ( ) , is ( "" ) ) ; assertThat ( profile . getBasePath ( ) . getName ( ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_basePath_unresolved ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( HadoopFsProfile . KEY_BASE_PATH , "" ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( ) ) , conf ) ; HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; } @ Test ( expected = IOException . class ) public void convert_basePath_invalid ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( HadoopFsProfile . KEY_BASE_PATH , "" ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( ) ) , conf ) ; HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; } @ Test public void convert_compression ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( HadoopFsProfile . KEY_COMPRESSION , DefaultCodec . class . getName ( ) ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( ) ) , conf ) ; HadoopFsProfile profile = HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; assertThat ( profile . getResourceName ( ) , is ( "" ) ) ; assertThat ( profile . getCompressionCodec ( ) , instanceOf ( DefaultCodec . class ) ) ; } @ Test public void convert_compression_parameterize ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( HadoopFsProfile . KEY_COMPRESSION , "" ) ; Map < String , String > parameters = new HashMap < String , String > ( ) ; parameters . put ( "" , DefaultCodec . class . getName ( ) ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( parameters ) ) , conf ) ; HadoopFsProfile profile = HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; assertThat ( profile . getResourceName ( ) , is ( "" ) ) ; assertThat ( profile . getCompressionCodec ( ) , instanceOf ( DefaultCodec . class ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void convert_invalid_compression ( ) throws Exception { Map < String , String > conf = new HashMap < String , String > ( ) ; conf . put ( HadoopFsProfile . KEY_COMPRESSION , "" ) ; ResourceProfile resourceProfile = new ResourceProfile ( "" , HadoopFsProvider . class , new ProfileContext ( getClass ( ) . getClassLoader ( ) , new ParameterList ( ) ) , conf ) ; HadoopFsProfile . convert ( hadoopConf , resourceProfile ) ; } } package com . asakusafw . windgate . hadoopfs . jsch ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . UnsupportedEncodingException ; import java . util . Arrays ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import java . util . Scanner ; import org . apache . hadoop . conf . Configuration ; import org . junit . Assume ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . hadoopfs . ssh . SshProfile ; public class JschConnectionTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; private SshProfile profile ; private File target ; @ Before public void setUp ( ) throws Exception { Properties p = new Properties ( ) ; InputStream in = getClass ( ) . getResourceAsStream ( "" ) ; if ( in == null ) { System . err . println ( "" ) ; Assume . assumeNotNull ( in ) ; return ; } try { p . load ( in ) ; } finally { in . close ( ) ; } target = folder . newFolder ( "" ) ; putScript ( target , SshProfile . COMMAND_GET ) ; putScript ( target , SshProfile . COMMAND_PUT ) ; putScript ( target , SshProfile . COMMAND_DELETE ) ; p . setProperty ( "" , target . getAbsolutePath ( ) ) ; Collection < ? extends ResourceProfile > rps = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( rps . size ( ) , is ( ) ) ; ResourceProfile rp = rps . iterator ( ) . next ( ) ; this . profile = SshProfile . convert ( new Configuration ( ) , rp ) ; } private void putScript ( File directory , String sourcePath ) throws IOException { String targetPath = sourcePath ; putScript ( directory , sourcePath , targetPath ) ; } private void putScript ( File directory , String sourcePath , String targetPath ) throws IOException { InputStream in = getClass ( ) . getResourceAsStream ( sourcePath ) ; assertThat ( sourcePath , in , is ( notNullValue ( ) ) ) ; try { File targetFile = new File ( directory , targetPath ) ; targetFile . getParentFile ( ) . mkdirs ( ) ; FileOutputStream output = new FileOutputStream ( targetFile ) ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = in . read ( buf ) ; if ( read < ) { break ; } output . write ( buf , , read ) ; } output . close ( ) ; assertThat ( targetFile . getName ( ) , targetFile . setExecutable ( true ) , is ( true ) ) ; } finally { in . close ( ) ; } } @ Test public void get ( ) throws Exception { File file = folder . newFile ( "" ) ; put ( file , "" ) ; JschConnection conn = new JschConnection ( profile , Arrays . asList ( profile . getGetCommand ( ) , file . getAbsolutePath ( ) ) ) ; try { InputStream output = conn . openStandardOutput ( ) ; conn . connect ( ) ; String result = get ( output ) ; assertThat ( result , is ( "" ) ) ; int exit = conn . waitForExit ( ) ; assertThat ( exit , is ( ) ) ; } finally { conn . close ( ) ; } } @ Test public void put ( ) throws Exception { File file = folder . newFile ( "" ) ; file . delete ( ) ; JschConnection conn = new JschConnection ( profile , Arrays . asList ( profile . getPutCommand ( ) , file . getAbsolutePath ( ) ) ) ; try { conn . redirectStandardOutput ( System . out , true ) ; OutputStream out = conn . openStandardInput ( ) ; conn . connect ( ) ; out . write ( "" . getBytes ( "" ) ) ; out . close ( ) ; int exit = conn . waitForExit ( ) ; assertThat ( exit , is ( ) ) ; } finally { conn . close ( ) ; } String result = get ( file ) ; assertThat ( result , is ( "" ) ) ; } @ Test public void delete ( ) throws Exception { File file = folder . newFile ( "" ) ; JschConnection conn = new JschConnection ( profile , Arrays . asList ( profile . getDeleteCommand ( ) , file . getAbsolutePath ( ) ) ) ; try { conn . redirectStandardOutput ( System . out , true ) ; OutputStream out = conn . openStandardInput ( ) ; conn . connect ( ) ; out . write ( "" . getBytes ( "" ) ) ; out . close ( ) ; int exit = conn . waitForExit ( ) ; assertThat ( exit , is ( ) ) ; } finally { conn . close ( ) ; } assertThat ( file . toString ( ) , file . exists ( ) , is ( false ) ) ; } @ Test public void env ( ) throws Exception { putScript ( target , "" , SshProfile . COMMAND_GET ) ; JschConnection conn = new JschConnection ( profile , Arrays . asList ( profile . getGetCommand ( ) ) ) ; try { InputStream output = conn . openStandardOutput ( ) ; conn . connect ( ) ; String result = get ( output ) ; assertThat ( result , is ( "" ) ) ; int exit = conn . waitForExit ( ) ; assertThat ( exit , is ( ) ) ; } finally { conn . close ( ) ; } } @ Test public void inherit_context ( ) throws Exception { RuntimeContext context = RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) . batchId ( "" ) . buildId ( "" ) ; RuntimeContext . set ( context ) ; putScript ( target , "" , SshProfile . COMMAND_GET ) ; Map < String , String > results = new HashMap < String , String > ( ) ; JschConnection conn = new JschConnection ( profile , Arrays . asList ( profile . getGetCommand ( ) ) ) ; try { InputStream output = conn . openStandardOutput ( ) ; conn . connect ( ) ; Scanner s = new Scanner ( output , "" ) ; while ( s . hasNextLine ( ) ) { String [ ] pair = s . nextLine ( ) . split ( "" , ) ; if ( pair . length == ) { results . put ( pair [ ] , pair [ ] ) ; } } int exit = conn . waitForExit ( ) ; assertThat ( exit , is ( ) ) ; } finally { conn . close ( ) ; } RuntimeContext restored = RuntimeContext . DEFAULT . apply ( results ) ; assertThat ( results . toString ( ) , restored , is ( context ) ) ; } private void put ( File file , String content ) throws IOException { FileOutputStream out = new FileOutputStream ( file ) ; try { out . write ( content . getBytes ( "" ) ) ; } finally { out . close ( ) ; } } private String get ( File file ) throws IOException { InputStream in = new FileInputStream ( file ) ; try { return get ( in ) ; } finally { in . close ( ) ; } } private String get ( InputStream in ) throws IOException , UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ ] ; while ( true ) { int read = in . read ( buf ) ; if ( read < ) { break ; } baos . write ( buf , , read ) ; } return new String ( baos . toByteArray ( ) , "" ) ; } } package com . asakusafw . windgate . hadoopfs ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . conf . Configuration ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . resource . ResourceProvider ; public class HadoopFsProvider extends ResourceProvider { static final Logger LOG = LoggerFactory . getLogger ( HadoopFsProvider . class ) ; private volatile Configuration configuration ; private volatile HadoopFsProfile hfsProfile ; @ Override protected void configure ( ResourceProfile profile ) throws IOException { LOG . debug ( "" , profile . getName ( ) ) ; this . configuration = new Configuration ( ) ; try { this . hfsProfile = HadoopFsProfile . convert ( configuration , profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getName ( ) ) ) ; } } @ Override public ResourceMirror create ( String sessionId , ParameterList arguments ) throws IOException { if ( sessionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , hfsProfile . getResourceName ( ) , sessionId ) ; return new HadoopFsMirror ( configuration , hfsProfile , arguments ) ; } } package com . asakusafw . windgate . hadoopfs . ssh ; import static com . asakusafw . windgate . core . vocabulary . FileProcess . * ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . concurrent . TimeUnit ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . util . ReflectionUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . hadoopfs . HadoopFsLogger ; import com . asakusafw . windgate . hadoopfs . ssh . FileList . Writer ; import com . asakusafw . windgate . hadoopfs . temporary . ModelInputProvider ; import com . asakusafw . windgate . hadoopfs . temporary . ModelInputSourceDriver ; import com . asakusafw . windgate . hadoopfs . temporary . ModelOutputDrainDriver ; public abstract class AbstractSshHadoopFsMirror extends ResourceMirror { static final WindGateLogger WGLOG = new HadoopFsLogger ( AbstractSshHadoopFsMirror . class ) ; static final Logger LOG = LoggerFactory . getLogger ( AbstractSshHadoopFsMirror . class ) ; private final Configuration configuration ; final SshProfile profile ; private final ParameterList arguments ; public AbstractSshHadoopFsMirror ( Configuration configuration , SshProfile profile , ParameterList arguments ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . configuration = configuration ; this . profile = profile ; this . arguments = arguments ; } @ Override public String getName ( ) { return profile . getResourceName ( ) ; } @ Override public void prepare ( GateScript script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) ) ; for ( ProcessScript < ? > process : script . getProcesses ( ) ) { if ( process . getSourceScript ( ) . getResourceName ( ) . equals ( getName ( ) ) ) { getPath ( process , DriverScript . Kind . SOURCE ) ; } if ( process . getDrainScript ( ) . getResourceName ( ) . equals ( getName ( ) ) ) { getPath ( process , DriverScript . Kind . DRAIN ) ; } } } @ Override public < T > SourceDriver < T > createSource ( final ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; final List < String > path = getPath ( script , DriverScript . Kind . SOURCE ) ; T value = newDataModel ( script ) ; final SshConnection connection = openGet ( path ) ; boolean succeeded = false ; try { InputStream output = connection . openStandardOutput ( ) ; connection . connect ( ) ; FileList . Reader fileList = FileList . createReader ( output ) ; ModelInputProvider < T > provider = new FileListModelInputProvider < T > ( configuration , fileList , script . getDataClass ( ) ) ; ModelInputSourceDriver < T > result = new SshSourceDriver < T > ( provider , value , script , connection , path ) ; succeeded = true ; return result ; } finally { if ( succeeded == false ) { try { connection . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , profile . getResourceName ( ) , script . getName ( ) , path ) ; } } } } @ Override public < T > DrainDriver < T > createDrain ( final ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; final List < String > path = getPath ( script , DriverScript . Kind . DRAIN ) ; final SshConnection connection = openPut ( ) ; boolean succeeded = false ; try { OutputStream input = connection . openStandardInput ( ) ; connection . connect ( ) ; final FileList . Writer fileList = FileList . createWriter ( input ) ; ModelOutput < T > output = TemporaryStorage . openOutput ( configuration , script . getDataClass ( ) , fileList . openNext ( FileList . createFileStatus ( new Path ( path . get ( ) ) ) ) , profile . getCompressionCodec ( ) ) ; ModelOutputDrainDriver < T > result = new SshDrainDriver < T > ( output , connection , path , fileList , script ) ; succeeded = true ; return result ; } finally { if ( succeeded == false ) { try { connection . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , profile . getResourceName ( ) , script . getName ( ) , path ) ; } } } } private SshConnection openGet ( List < String > paths ) throws IOException { assert paths != null ; List < String > tokens = new ArrayList < String > ( ) ; tokens . add ( profile . getGetCommand ( ) ) ; tokens . addAll ( paths ) ; SshConnection connection = openConnection ( profile , tokens ) ; boolean succeed = false ; try { connection . openStandardInput ( ) . close ( ) ; succeed = true ; return connection ; } finally { if ( succeed == false ) { connection . close ( ) ; } } } private SshConnection openPut ( ) throws IOException { SshConnection connection = openConnection ( profile , Collections . singletonList ( profile . getPutCommand ( ) ) ) ; boolean succeed = false ; try { connection . redirectStandardOutput ( System . out , true ) ; succeed = true ; return connection ; } finally { if ( succeed == false ) { connection . close ( ) ; } } } protected abstract SshConnection openConnection ( SshProfile sshProfile , List < String > command ) throws IOException ; private List < String > getPath ( ProcessScript < ? > proc , DriverScript . Kind kind ) throws IOException { assert proc != null ; assert kind != null ; DriverScript script = proc . getDriverScript ( kind ) ; String pathString = script . getConfiguration ( ) . get ( FILE . key ( ) ) ; if ( pathString == null ) { WGLOG . error ( "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , null ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , proc . getName ( ) , kind . toString ( ) , FILE . key ( ) ) ) ; } String [ ] paths = pathString . split ( "" ) ; List < String > results = new ArrayList < String > ( ) ; for ( String path : paths ) { if ( path . isEmpty ( ) ) { continue ; } try { String resolved = arguments . replace ( path , true ) ; results . add ( resolved ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , pathString ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , proc . getName ( ) , kind . toString ( ) , path ) ) ; } } if ( kind == DriverScript . Kind . SOURCE && results . size ( ) <= ) { WGLOG . error ( "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , pathString ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , proc . getName ( ) , results ) ) ; } if ( kind == DriverScript . Kind . DRAIN && results . size ( ) != ) { WGLOG . error ( "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , pathString ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , proc . getName ( ) , results ) ) ; } return results ; } private < T > T newDataModel ( ProcessScript < T > script ) throws IOException { assert script != null ; Class < T > dataClass = script . getDataClass ( ) ; LOG . debug ( "" , new Object [ ] { dataClass . getName ( ) , getName ( ) , script . getName ( ) , } ) ; try { return ReflectionUtils . newInstance ( dataClass , configuration ) ; } catch ( Exception e ) { WGLOG . error ( "" , getName ( ) , script . getName ( ) , FILE . key ( ) , dataClass . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , script . getName ( ) , dataClass . getName ( ) ) , e ) ; } } @ Override public void close ( ) throws IOException { LOG . debug ( "" , getName ( ) ) ; } @ SimulationSupport private final class SshSourceDriver < T > extends ModelInputSourceDriver < T > { private final ProcessScript < T > script ; private final SshConnection connection ; private final List < String > path ; SshSourceDriver ( ModelInputProvider < T > provider , T value , ProcessScript < T > script , SshConnection connection , List < String > path ) { super ( provider , value ) ; this . script = script ; this . connection = connection ; this . path = path ; } @ Override public void close ( ) throws IOException { try { LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; super . close ( ) ; int exit = connection . waitForExit ( TimeUnit . SECONDS . toMillis ( ) ) ; if ( exit != ) { WGLOG . error ( "" , profile . getResourceName ( ) , script . getName ( ) , path ) ; throw new IOException ( MessageFormat . format ( "" , String . valueOf ( exit ) , script . getName ( ) ) ) ; } } catch ( InterruptedException e ) { WGLOG . error ( e , "" , profile . getResourceName ( ) , script . getName ( ) , path ) ; Thread . currentThread ( ) . interrupt ( ) ; throw new IOException ( "" , e ) ; } finally { try { connection . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , profile . getResourceName ( ) , script . getName ( ) , path ) ; } } } } @ SimulationSupport private final class SshDrainDriver < T > extends ModelOutputDrainDriver < T > { private final SshConnection connection ; private final List < String > path ; private final Writer fileList ; private final ProcessScript < T > script ; SshDrainDriver ( ModelOutput < T > output , SshConnection connection , List < String > path , FileList . Writer fileList , ProcessScript < T > script ) { super ( output ) ; this . connection = connection ; this . path = path ; this . fileList = fileList ; this . script = script ; } @ Override public void close ( ) throws IOException { try { LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; super . close ( ) ; fileList . close ( ) ; int exit = connection . waitForExit ( TimeUnit . SECONDS . toMillis ( ) ) ; if ( exit != ) { WGLOG . error ( "" , profile . getResourceName ( ) , script . getName ( ) , path ) ; throw new IOException ( MessageFormat . format ( "" , String . valueOf ( exit ) , script . getName ( ) ) ) ; } } catch ( InterruptedException e ) { WGLOG . error ( e , "" , profile . getResourceName ( ) , script . getName ( ) , path ) ; Thread . currentThread ( ) . interrupt ( ) ; throw new IOException ( "" , e ) ; } finally { try { connection . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , profile . getResourceName ( ) , script . getName ( ) , path ) ; } } } } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . text . MessageFormat ; public final class StdoutEscapeMain { static { StdioHelper . load ( ) ; } private StdoutEscapeMain ( ) { return ; } public static void main ( String [ ] args ) throws Throwable { if ( args . length == ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , StdoutEscapeMain . class . getName ( ) ) ) ; } String mainClassName = args [ ] ; String [ ] mainArgs = new String [ args . length - ] ; System . arraycopy ( args , , mainArgs , , mainArgs . length ) ; System . setOut ( System . err ) ; try { launch ( mainClassName , mainArgs ) ; } finally { StdioHelper . reset ( ) ; } } private static void launch ( String className , String [ ] args ) throws Throwable { Class < ? > mainClass = Class . forName ( className ) ; Method method = mainClass . getMethod ( "" , String [ ] . class ) ; try { method . invoke ( null , new Object [ ] { args } ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . IOException ; import java . io . InputStream ; import java . util . zip . ZipInputStream ; public class ZipEntryInputStream extends InputStream { private final ZipInputStream zipped ; private boolean closed = false ; public ZipEntryInputStream ( ZipInputStream zipped ) { if ( zipped == null ) { throw new IllegalArgumentException ( "" ) ; } this . zipped = zipped ; } @ Override public void close ( ) throws IOException { if ( closed == false ) { zipped . closeEntry ( ) ; } closed = true ; } @ Override public int read ( byte [ ] b ) throws IOException { return zipped . read ( b ) ; } @ Override public int read ( ) throws IOException { return zipped . read ( ) ; } @ Override public int available ( ) throws IOException { return zipped . available ( ) ; } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { return zipped . read ( b , off , len ) ; } @ Override public long skip ( long n ) throws IOException { return zipped . skip ( n ) ; } @ Override public boolean markSupported ( ) { return zipped . markSupported ( ) ; } @ Override public synchronized void mark ( int readlimit ) { zipped . mark ( readlimit ) ; } @ Override public synchronized void reset ( ) throws IOException { zipped . reset ( ) ; } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . compress . CompressionCodec ; import org . apache . hadoop . util . ReflectionUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . util . PropertiesUtil ; import com . asakusafw . windgate . hadoopfs . HadoopFsLogger ; public class SshProfile { static final WindGateLogger WGLOG = new HadoopFsLogger ( SshProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( SshProfile . class ) ; public static final String PATH_BASE_TARGET = "" ; public static final String COMMAND_GET = "" ; public static final String COMMAND_PUT = "" ; public static final String COMMAND_DELETE = "" ; public static final String KEY_TARGET = "" ; public static final String KEY_USER = "" ; public static final String KEY_HOST = "" ; public static final String KEY_PORT = "" ; public static final String KEY_PRIVATE_KEY = "" ; public static final String KEY_PASS_PHRASE = "" ; public static final String KEY_COMPRESSION = "" ; public static final String PREFIX_ENV = "" ; private final String resourceName ; private final String target ; private final String user ; private final String host ; private final int port ; private final String privateKey ; private final String passPhrase ; private final CompressionCodec compressionCodec ; private final Map < String , String > environmentVariables ; public SshProfile ( String name , String target , String user , String host , int port , String privateKey , String passPhrase , CompressionCodec compressionCodec , Map < String , String > env ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( user == null ) { throw new IllegalArgumentException ( "" ) ; } if ( host == null ) { throw new IllegalArgumentException ( "" ) ; } if ( privateKey == null ) { throw new IllegalArgumentException ( "" ) ; } if ( passPhrase == null ) { throw new IllegalArgumentException ( "" ) ; } if ( env == null ) { throw new IllegalArgumentException ( "" ) ; } this . resourceName = name ; this . target = target ; this . user = user ; this . host = host ; this . port = port ; this . privateKey = privateKey ; this . passPhrase = passPhrase ; this . compressionCodec = compressionCodec ; this . environmentVariables = Collections . unmodifiableMap ( env ) ; } public static SshProfile convert ( Configuration configuration , ResourceProfile profile ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } String name = profile . getName ( ) ; String target = extract ( profile , KEY_TARGET , false ) ; String user = extract ( profile , KEY_USER , true ) ; String host = extract ( profile , KEY_HOST , true ) ; int port = extractPort ( profile ) ; String privateKey = extract ( profile , KEY_PRIVATE_KEY , true ) ; String passPhrase = extractPassPhrase ( profile ) ; CompressionCodec compressionCodec = extractCompressionCodec ( configuration , profile ) ; Map < String , String > env = extractEnv ( profile ) ; if ( target == null ) { String home = env . get ( "" ) ; if ( home == null || home . isEmpty ( ) ) { WGLOG . error ( "" , profile . getName ( ) , PREFIX_ENV + "" , null ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , PREFIX_ENV + "" ) ) ; } if ( home . endsWith ( "" ) == false ) { home = home + "" ; } target = home + PATH_BASE_TARGET ; } return new SshProfile ( name , target , user , host , port , privateKey , passPhrase , compressionCodec , env ) ; } private static String extract ( ResourceProfile profile , String configKey , boolean mandatory ) { assert profile != null ; assert configKey != null ; String value = profile . getConfiguration ( ) . get ( configKey ) ; if ( value == null ) { if ( mandatory == false ) { return null ; } else { WGLOG . error ( "" , profile . getName ( ) , configKey , null ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey ) ) ; } } return resolve ( profile , configKey , value . trim ( ) ) ; } private static String resolve ( ResourceProfile profile , String configKey , String value ) { assert profile != null ; assert configKey != null ; assert value != null ; try { return profile . getContext ( ) . getContextParameters ( ) . replace ( value , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , profile . getName ( ) , configKey , value ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey , value ) , e ) ; } } private static int extractPort ( ResourceProfile profile ) { assert profile != null ; String portString = extract ( profile , KEY_PORT , true ) ; try { return Integer . parseInt ( portString ) ; } catch ( NumberFormatException e ) { WGLOG . error ( "" , profile . getName ( ) , KEY_PORT , portString ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , KEY_PORT , portString ) ) ; } } private static Map < String , String > extractEnv ( ResourceProfile profile ) { assert profile != null ; Map < String , String > map = PropertiesUtil . createPrefixMap ( profile . getConfiguration ( ) , PREFIX_ENV ) ; Map < String , String > results = new HashMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { String resolved = resolve ( profile , PREFIX_ENV + entry . getKey ( ) , entry . getValue ( ) ) ; results . put ( entry . getKey ( ) , resolved ) ; } LOG . debug ( "" , profile . getName ( ) , results ) ; return results ; } private static String extractPassPhrase ( ResourceProfile profile ) { assert profile != null ; String passPhrase = extract ( profile , KEY_PASS_PHRASE , false ) ; passPhrase = passPhrase == null ? "" : passPhrase ; return passPhrase ; } private static CompressionCodec extractCompressionCodec ( Configuration configuration , ResourceProfile profile ) { assert configuration != null ; assert profile != null ; String compressionCodecString = extract ( profile , KEY_COMPRESSION , false ) ; CompressionCodec compressionCodec ; try { if ( compressionCodecString == null ) { compressionCodec = null ; } else { Class < ? > codecClass = configuration . getClassByName ( compressionCodecString ) ; compressionCodec = ( CompressionCodec ) ReflectionUtils . newInstance ( codecClass , configuration ) ; } } catch ( Exception e ) { WGLOG . error ( e , "" , profile . getName ( ) , KEY_COMPRESSION , compressionCodecString ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , KEY_COMPRESSION , compressionCodecString ) , e ) ; } WGLOG . info ( "" , profile . getName ( ) , KEY_COMPRESSION , compressionCodec == null ? null : compressionCodecString ) ; return compressionCodec ; } public String getResourceName ( ) { return resourceName ; } public String getTarget ( ) { return target ; } public String getGetCommand ( ) { return getCommand ( COMMAND_GET ) ; } public String getPutCommand ( ) { return getCommand ( COMMAND_PUT ) ; } public String getDeleteCommand ( ) { return getCommand ( COMMAND_DELETE ) ; } private String getCommand ( String command ) { assert command != null ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( target ) ; if ( target . endsWith ( "" ) == false ) { buf . append ( '' ) ; } buf . append ( command ) ; return buf . toString ( ) ; } public String getUser ( ) { return user ; } public String getHost ( ) { return host ; } public int getPort ( ) { return port ; } public String getPrivateKey ( ) { return privateKey ; } public String getPassPhrase ( ) { return passPhrase ; } public CompressionCodec getCompressionCodec ( ) { return compressionCodec ; } public Map < String , String > getEnvironmentVariables ( ) { return environmentVariables ; } } package com . asakusafw . windgate . hadoopfs . ssh ; package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . Closeable ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . zip . ZipEntry ; import java . util . zip . ZipInputStream ; import java . util . zip . ZipOutputStream ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . DataInputBuffer ; import org . apache . hadoop . io . DataOutputBuffer ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . hadoopfs . HadoopFsLogger ; public final class FileList { static final WindGateLogger WGLOG = new HadoopFsLogger ( FileList . class ) ; static final Logger LOG = LoggerFactory . getLogger ( FileList . class ) ; static final String FIRST_ENTRY_NAME = "" ; static final String LAST_ENTRY_NAME = "" ; public static FileStatus createFileStatus ( Path path ) { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } return new FileStatus ( , false , , , , , null , null , null , path ) ; } public static FileList . Reader createReader ( InputStream input ) throws IOException { if ( input == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; return new Reader ( input ) ; } public static FileList . Writer createWriter ( OutputStream output ) throws IOException { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; return new Writer ( output ) ; } private FileList ( ) { return ; } public static class Reader implements Closeable { private final InputStream original ; private final ZipInputStream input ; private final FileStatus current = new FileStatus ( ) ; private final DataInputBuffer buffer = new DataInputBuffer ( ) ; private boolean sawNext ; private boolean sawEof ; Reader ( InputStream input ) throws IOException { assert input != null ; this . original = input ; this . input = new ZipInputStream ( input ) ; ZipEntry first = this . input . getNextEntry ( ) ; if ( first == null || first . getName ( ) . equals ( FIRST_ENTRY_NAME ) == false ) { throw new IOException ( "" ) ; } } public boolean next ( ) throws IOException { while ( sawEof == false ) { ZipEntry entry = input . getNextEntry ( ) ; if ( entry == null ) { throw new IOException ( "" ) ; } LOG . debug ( "" , entry . getName ( ) ) ; if ( entry . getName ( ) . equals ( LAST_ENTRY_NAME ) ) { sawEof = true ; sawNext = false ; consume ( ) ; return false ; } if ( entry . isDirectory ( ) ) { continue ; } LOG . debug ( "" , entry . getName ( ) ) ; if ( restoreExtra ( entry ) == false ) { throw new IOException ( MessageFormat . format ( "" , entry . getName ( ) ) ) ; } sawNext = true ; return true ; } return false ; } private void consume ( ) throws IOException { byte [ ] buf = new byte [ ] ; int rest = ; while ( true ) { int read = original . read ( buf ) ; if ( read < ) { break ; } rest += read ; } LOG . debug ( "" , rest ) ; } private boolean restoreExtra ( ZipEntry entry ) { assert entry != null ; byte [ ] extra = entry . getExtra ( ) ; if ( extra == null ) { return false ; } buffer . reset ( extra , extra . length ) ; try { current . readFields ( buffer ) ; } catch ( Exception e ) { WGLOG . warn ( e , "" , entry . getName ( ) ) ; return false ; } return true ; } public FileStatus getCurrentFile ( ) throws IOException { checkCurrent ( ) ; return current ; } public InputStream openContent ( ) throws IOException { checkCurrent ( ) ; return new ZipEntryInputStream ( input ) ; } private void checkCurrent ( ) throws IOException { if ( sawNext == false ) { throw new IOException ( "" ) ; } } @ Override public void close ( ) throws IOException { LOG . debug ( "" ) ; sawNext = false ; input . close ( ) ; } } public static class Writer implements Closeable { private final ZipOutputStream output ; private final DataOutputBuffer buffer = new DataOutputBuffer ( ) ; private boolean closed = false ; Writer ( OutputStream output ) throws IOException { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . output = new ZipOutputStream ( output ) ; this . output . setMethod ( ZipOutputStream . DEFLATED ) ; this . output . setLevel ( ) ; this . output . putNextEntry ( new ZipEntry ( FIRST_ENTRY_NAME ) ) ; this . output . closeEntry ( ) ; } public OutputStream openNext ( FileStatus status ) throws IOException { if ( status == null ) { throw new IllegalArgumentException ( "" ) ; } if ( status . getPath ( ) == null ) { throw new IllegalAccessError ( "" ) ; } ZipEntry entry = createEntryFromStatus ( status ) ; LOG . debug ( "" , entry . getName ( ) ) ; output . putNextEntry ( entry ) ; return new ZipEntryOutputStream ( output ) ; } private ZipEntry createEntryFromStatus ( FileStatus status ) throws IOException { assert status != null ; buffer . reset ( ) ; status . write ( buffer ) ; ZipEntry entry = new ZipEntry ( status . getPath ( ) . toString ( ) ) ; entry . setExtra ( Arrays . copyOfRange ( buffer . getData ( ) , , buffer . getLength ( ) ) ) ; return entry ; } @ Override public void close ( ) throws IOException { if ( closed == false ) { LOG . debug ( "" ) ; output . putNextEntry ( new ZipEntry ( LAST_ENTRY_NAME ) ) ; output . closeEntry ( ) ; output . close ( ) ; LOG . debug ( "" ) ; } closed = true ; } } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . IOException ; import java . io . OutputStream ; import java . util . zip . ZipOutputStream ; public class ZipEntryOutputStream extends OutputStream { private final ZipOutputStream zipped ; private boolean closed = false ; public ZipEntryOutputStream ( ZipOutputStream zipped ) { if ( zipped == null ) { throw new IllegalArgumentException ( "" ) ; } this . zipped = zipped ; } @ Override public void close ( ) throws IOException { if ( closed == false ) { zipped . closeEntry ( ) ; } closed = true ; } @ Override public void write ( byte [ ] b ) throws IOException { zipped . write ( b ) ; } @ Override public void write ( int b ) throws IOException { zipped . write ( b ) ; } @ Override public void flush ( ) throws IOException { zipped . flush ( ) ; } @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { zipped . write ( b , off , len ) ; } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . BufferedInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . Arrays ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . io . util . VoidOutputStream ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . hadoopfs . HadoopFsLogger ; public class WindGateHadoopPut { static { StdioHelper . load ( ) ; } static final WindGateLogger WGLOG = new HadoopFsLogger ( WindGateHadoopPut . class ) ; static final Logger LOG = LoggerFactory . getLogger ( WindGateHadoopPut . class ) ; private static final int BUFFER_SIZE = * ; private final Configuration conf ; public WindGateHadoopPut ( Configuration conf ) { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } this . conf = conf ; } public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( WindGateHadoopPut . class . getClassLoader ( ) ) ; WGLOG . info ( "" ) ; long start = System . currentTimeMillis ( ) ; Configuration conf = new Configuration ( ) ; int result = new WindGateHadoopPut ( conf ) . execute ( StdioHelper . getOriginalStdin ( ) , args ) ; long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , result , end - start ) ; System . exit ( result ) ; } int execute ( InputStream in , String ... args ) { assert args != null ; if ( args . length != ) { WGLOG . error ( "" , Arrays . asList ( args ) ) ; System . err . printf ( "" , WindGateHadoopPut . class . getName ( ) ) ; return ; } try { WGLOG . info ( "" ) ; FileList . Reader reader = FileList . createReader ( new BufferedInputStream ( in , BUFFER_SIZE ) ) ; doPut ( reader ) ; WGLOG . info ( "" ) ; reader . close ( ) ; return ; } catch ( IOException e ) { WGLOG . info ( e , "" ) ; return ; } } void doPut ( FileList . Reader source ) throws IOException { assert source != null ; FileSystem fs = FileSystem . get ( conf ) ; while ( source . next ( ) ) { FileStatus status = source . getCurrentFile ( ) ; InputStream input = source . openContent ( ) ; try { doPut ( fs , status , input ) ; } finally { input . close ( ) ; } } } private void doPut ( FileSystem fs , FileStatus status , InputStream input ) throws IOException { assert fs != null ; assert status != null ; assert input != null ; WGLOG . info ( "" , fs . getUri ( ) , status . getPath ( ) ) ; long transferred = ; OutputStream output ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { output = new VoidOutputStream ( ) ; } else { output = fs . create ( status . getPath ( ) , true , BUFFER_SIZE ) ; } try { byte [ ] buf = new byte [ ] ; while ( true ) { int read = input . read ( buf ) ; if ( read < ) { break ; } output . write ( buf , , read ) ; transferred += read ; } } finally { output . close ( ) ; } WGLOG . info ( "" , fs . getUri ( ) , status . getPath ( ) , transferred ) ; } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . Closeable ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; public interface SshConnection extends Closeable { void connect ( ) throws IOException ; OutputStream openStandardInput ( ) throws IOException ; InputStream openStandardOutput ( ) throws IOException ; void redirectStandardOutput ( OutputStream output , boolean dontClose ) ; int waitForExit ( long timeout ) throws IOException , InterruptedException ; } package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . IOException ; import java . io . InputStream ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . windgate . hadoopfs . temporary . ModelInputProvider ; public class FileListModelInputProvider < T > implements ModelInputProvider < T > { static final Logger LOG = LoggerFactory . getLogger ( FileListModelInputProvider . class ) ; private final Configuration conf ; private final FileList . Reader fileList ; private final Class < T > dataModelClass ; public FileListModelInputProvider ( Configuration conf , FileList . Reader fileList , Class < T > dataModelClass ) { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } if ( fileList == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataModelClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . conf = conf ; this . fileList = fileList ; this . dataModelClass = dataModelClass ; } @ Override public boolean next ( ) throws IOException { return fileList . next ( ) ; } @ Override public ModelInput < T > open ( ) throws IOException { FileStatus status = fileList . getCurrentFile ( ) ; InputStream content = fileList . openContent ( ) ; boolean succeeded = false ; try { LOG . debug ( "" , status . getPath ( ) ) ; ModelInput < T > input = TemporaryStorage . openInput ( conf , dataModelClass , status , content ) ; succeeded = true ; return input ; } finally { if ( succeeded == false ) { content . close ( ) ; } } } @ Override public void close ( ) throws IOException { LOG . debug ( "" ) ; fileList . close ( ) ; } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . BufferedOutputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . Callable ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . SynchronousQueue ; import java . util . concurrent . TimeUnit ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . io . util . VoidInputStream ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . hadoopfs . HadoopFsLogger ; import com . asakusafw . windgate . hadoopfs . ssh . FileList . Writer ; public class WindGateHadoopGet { static { StdioHelper . load ( ) ; } static final WindGateLogger WGLOG = new HadoopFsLogger ( WindGateHadoopGet . class ) ; static final Logger LOG = LoggerFactory . getLogger ( WindGateHadoopGet . class ) ; static final int BUFFER_SIZE = * ; final Configuration conf ; public WindGateHadoopGet ( Configuration conf ) { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } this . conf = conf ; } public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( WindGateHadoopGet . class . getClassLoader ( ) ) ; WGLOG . info ( "" ) ; long start = System . currentTimeMillis ( ) ; Configuration conf = new Configuration ( ) ; int result = new WindGateHadoopGet ( conf ) . execute ( StdioHelper . getOriginalStdout ( ) , args ) ; long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , result , end - start ) ; System . exit ( result ) ; } int execute ( OutputStream out , String ... args ) { assert args != null ; if ( args . length == ) { WGLOG . error ( "" , Arrays . toString ( args ) ) ; System . err . printf ( "" , WindGateHadoopGet . class . getName ( ) ) ; return ; } List < Path > paths = new ArrayList < Path > ( ) ; for ( String arg : args ) { paths . add ( new Path ( arg ) ) ; } try { WGLOG . info ( "" , paths ) ; FileList . Writer writer = FileList . createWriter ( new BufferedOutputStream ( out , BUFFER_SIZE ) ) ; doGet ( paths , writer ) ; WGLOG . info ( "" , paths ) ; writer . close ( ) ; return ; } catch ( IOException e ) { WGLOG . error ( e , "" , paths ) ; return ; } catch ( InterruptedException e ) { WGLOG . error ( e , "" , paths ) ; return ; } } void doGet ( final List < Path > paths , FileList . Writer drain ) throws IOException , InterruptedException { assert paths != null ; assert drain != null ; final BlockingQueue < Pair > queue = new SynchronousQueue < Pair > ( ) ; final FileSystem fs = FileSystem . get ( conf ) ; ExecutorService executor = Executors . newFixedThreadPool ( ) ; try { Future < Void > fetcher = executor . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { fetch ( fs , paths , queue ) ; queue . put ( Pair . eof ( ) ) ; return null ; } } ) ; while ( true ) { Pair next = queue . poll ( , TimeUnit . SECONDS ) ; if ( next != null ) { if ( next . isEof ( ) ) { break ; } else { transfer ( fs , next . status , next . input , drain ) ; } } else if ( fetcher . isDone ( ) ) { break ; } } try { fetcher . get ( ) ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof Error ) { throw ( Error ) cause ; } else if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else if ( cause instanceof InterruptedException ) { throw ( InterruptedException ) cause ; } throw new AssertionError ( e ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } } finally { executor . shutdownNow ( ) ; while ( true ) { Pair next = queue . poll ( ) ; if ( next == null ) { break ; } try { next . input . close ( ) ; } catch ( IOException e ) { } } } } void fetch ( FileSystem fs , List < Path > paths , BlockingQueue < Pair > queue ) throws IOException , InterruptedException { assert fs != null ; assert paths != null ; assert queue != null ; for ( Path path : paths ) { boolean found = false ; WGLOG . info ( "" , fs . getUri ( ) , path ) ; FileStatus [ ] results = fs . globStatus ( path ) ; if ( results != null ) { for ( FileStatus status : results ) { if ( status . isDir ( ) ) { continue ; } found = true ; InputStream in ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { in = new VoidInputStream ( ) ; } else { in = fs . open ( status . getPath ( ) , BUFFER_SIZE ) ; } boolean succeed = false ; try { queue . put ( new Pair ( in , status ) ) ; succeed = true ; } finally { if ( succeed == false ) { in . close ( ) ; } } } } if ( found == false && RuntimeContext . get ( ) . isSimulation ( ) == false ) { throw new FileNotFoundException ( paths . toString ( ) ) ; } } } private void transfer ( FileSystem fs , FileStatus status , InputStream input , Writer drain ) throws IOException { assert fs != null ; assert status != null ; assert input != null ; assert drain != null ; WGLOG . info ( "" , fs . getUri ( ) , status . getPath ( ) ) ; long transferred = ; try { if ( RuntimeContext . get ( ) . isSimulation ( ) == false ) { OutputStream output = drain . openNext ( status ) ; try { byte [ ] buf = new byte [ ] ; while ( true ) { int read = input . read ( buf ) ; if ( read < ) { break ; } output . write ( buf , , read ) ; transferred += read ; } } finally { output . close ( ) ; } } } finally { input . close ( ) ; } WGLOG . info ( "" , fs . getUri ( ) , status . getPath ( ) , transferred ) ; } private static class Pair { final InputStream input ; final FileStatus status ; Pair ( InputStream input , FileStatus status ) { this . input = input ; this . status = status ; } static Pair eof ( ) { return new Pair ( null , null ) ; } boolean isEof ( ) { return input == null && status == null ; } } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . BufferedOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . nio . charset . Charset ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . hadoopfs . HadoopFsLogger ; public class WindGateHadoopDelete { static { StdioHelper . load ( ) ; } static final WindGateLogger WGLOG = new HadoopFsLogger ( WindGateHadoopDelete . class ) ; static final Logger LOG = LoggerFactory . getLogger ( WindGateHadoopDelete . class ) ; private static final int BUFFER_SIZE = * ; private final Configuration conf ; private static final Charset UTF8 = Charset . forName ( "" ) ; public WindGateHadoopDelete ( Configuration conf ) { if ( conf == null ) { throw new IllegalArgumentException ( "" ) ; } this . conf = conf ; } public static void main ( String [ ] args ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( WindGateHadoopDelete . class . getClassLoader ( ) ) ; WGLOG . info ( "" ) ; long start = System . currentTimeMillis ( ) ; Configuration conf = new Configuration ( ) ; int result = new WindGateHadoopDelete ( conf ) . execute ( StdioHelper . getOriginalStdout ( ) , args ) ; long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , result , end - start ) ; System . exit ( result ) ; } int execute ( OutputStream out , String ... args ) { assert args != null ; if ( args . length == ) { WGLOG . error ( "" , Arrays . toString ( args ) ) ; System . err . printf ( "" , WindGateHadoopDelete . class . getName ( ) ) ; return ; } List < Path > paths = new ArrayList < Path > ( ) ; for ( String arg : args ) { paths . add ( new Path ( arg ) ) ; } try { WGLOG . info ( "" , paths ) ; FileList . Writer writer = FileList . createWriter ( new BufferedOutputStream ( out , BUFFER_SIZE ) ) ; doDelete ( paths , writer ) ; WGLOG . info ( "" , paths ) ; writer . close ( ) ; return ; } catch ( IOException e ) { WGLOG . error ( e , "" , paths ) ; return ; } } void doDelete ( List < Path > paths , FileList . Writer drain ) throws IOException { assert paths != null ; assert drain != null ; FileSystem fs = FileSystem . get ( conf ) ; for ( Path path : paths ) { WGLOG . info ( "" , fs . getUri ( ) , path ) ; FileStatus [ ] results = fs . globStatus ( path ) ; if ( results == null ) { continue ; } for ( FileStatus status : results ) { doDelete ( fs , status , drain ) ; } } } private void doDelete ( FileSystem fs , FileStatus status , FileList . Writer drain ) throws IOException { assert fs != null ; assert status != null ; assert drain != null ; WGLOG . info ( "" , fs . getUri ( ) , status . getPath ( ) ) ; OutputStream output = drain . openNext ( status ) ; try { String failReason = null ; try { boolean deleted ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { deleted = true ; } else { deleted = fs . delete ( status . getPath ( ) , true ) ; } if ( deleted == false ) { if ( fs . exists ( status . getPath ( ) ) ) { WGLOG . warn ( "" , fs . getUri ( ) , status . getPath ( ) ) ; failReason = "" ; } } } catch ( IOException e ) { WGLOG . warn ( e , "" , fs . getUri ( ) , status . getPath ( ) ) ; failReason = e . toString ( ) ; } if ( failReason != null ) { output . write ( failReason . getBytes ( UTF8 ) ) ; } } finally { output . close ( ) ; } } } package com . asakusafw . windgate . hadoopfs . ssh ; import java . io . InputStream ; import java . io . PrintStream ; public final class StdioHelper { private static final InputStream ORIGINAL_STDIN = System . in ; private static final PrintStream ORIGINAL_STDOUT = System . out ; private static final PrintStream ORIGINAL_STDERR = System . err ; private StdioHelper ( ) { return ; } public static void load ( ) { return ; } public static void reset ( ) { System . setIn ( ORIGINAL_STDIN ) ; System . setOut ( ORIGINAL_STDOUT ) ; System . setErr ( ORIGINAL_STDERR ) ; } public static InputStream getOriginalStdin ( ) { return ORIGINAL_STDIN ; } public static PrintStream getOriginalStdout ( ) { return ORIGINAL_STDOUT ; } public static PrintStream getOriginalStderr ( ) { return ORIGINAL_STDERR ; } } package com . asakusafw . windgate . hadoopfs ; import static com . asakusafw . windgate . core . vocabulary . FileProcess . * ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . compress . CompressionCodec ; import org . apache . hadoop . util . ReflectionUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . runtime . io . util . VoidModelOutput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . hadoopfs . temporary . FileSystemModelInputProvider ; import com . asakusafw . windgate . hadoopfs . temporary . ModelInputProvider ; import com . asakusafw . windgate . hadoopfs . temporary . ModelInputSourceDriver ; import com . asakusafw . windgate . hadoopfs . temporary . ModelOutputDrainDriver ; @ SimulationSupport public class HadoopFsMirror extends ResourceMirror { static final WindGateLogger WGLOG = new HadoopFsLogger ( HadoopFsMirror . class ) ; static final Logger LOG = LoggerFactory . getLogger ( HadoopFsMirror . class ) ; private final Configuration configuration ; private final HadoopFsProfile profile ; private final ParameterList arguments ; public HadoopFsMirror ( Configuration configuration , HadoopFsProfile profile , ParameterList arguments ) { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . configuration = configuration ; this . profile = profile ; this . arguments = arguments ; } @ Override public String getName ( ) { return profile . getResourceName ( ) ; } @ Override public void prepare ( GateScript script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) ) ; for ( ProcessScript < ? > process : script . getProcesses ( ) ) { if ( process . getSourceScript ( ) . getResourceName ( ) . equals ( getName ( ) ) ) { getPath ( process , DriverScript . Kind . SOURCE ) ; } if ( process . getDrainScript ( ) . getResourceName ( ) . equals ( getName ( ) ) ) { getPath ( process , DriverScript . Kind . DRAIN ) ; } } } @ Override public < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; List < Path > pathList = getPath ( script , DriverScript . Kind . SOURCE ) ; T value = newDataModel ( script ) ; ModelInputProvider < T > provider = null ; boolean succeeded = false ; try { FileSystem fs = FileSystem . get ( profile . getBasePath ( ) . toUri ( ) , configuration ) ; provider = new FileSystemModelInputProvider < T > ( configuration , fs , pathList , script . getDataClass ( ) ) ; SourceDriver < T > result = new ModelInputSourceDriver < T > ( provider , value ) ; succeeded = true ; return result ; } finally { if ( succeeded == false ) { if ( provider != null ) { try { provider . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , profile . getResourceName ( ) , script . getName ( ) , pathList ) ; } } } } } @ Override public < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) , script . getName ( ) ) ; List < Path > pathList = getPath ( script , DriverScript . Kind . DRAIN ) ; assert pathList . size ( ) == ; Path path = pathList . get ( ) ; ModelOutput < T > output = null ; boolean succeeded = false ; try { CompressionCodec codec = profile . getCompressionCodec ( ) ; if ( RuntimeContext . get ( ) . isSimulation ( ) ) { output = new VoidModelOutput < T > ( ) ; } else { output = TemporaryStorage . openOutput ( configuration , script . getDataClass ( ) , path , codec ) ; } DrainDriver < T > result = new ModelOutputDrainDriver < T > ( output ) ; succeeded = true ; return result ; } finally { if ( succeeded == false ) { if ( output != null ) { try { output . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , profile . getResourceName ( ) , script . getName ( ) , pathList ) ; } } } } } @ Override public void close ( ) throws IOException { return ; } private List < Path > getPath ( ProcessScript < ? > proc , DriverScript . Kind kind ) throws IOException { assert proc != null ; assert kind != null ; DriverScript script = proc . getDriverScript ( kind ) ; String pathString = script . getConfiguration ( ) . get ( FILE . key ( ) ) ; if ( pathString == null ) { WGLOG . error ( "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , null ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , proc . getName ( ) , kind . toString ( ) , FILE . key ( ) ) ) ; } List < Path > results = resolvePaths ( proc , kind , pathString ) ; if ( kind == DriverScript . Kind . SOURCE && results . size ( ) <= && RuntimeContext . get ( ) . isSimulation ( ) == false ) { WGLOG . error ( "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , pathString ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , proc . getName ( ) , results ) ) ; } if ( kind == DriverScript . Kind . DRAIN && results . size ( ) != ) { WGLOG . error ( "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , pathString ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , proc . getName ( ) , results ) ) ; } return results ; } private List < Path > resolvePaths ( ProcessScript < ? > proc , DriverScript . Kind kind , String pathString ) throws IOException { assert proc != null ; assert kind != null ; assert pathString != null ; Path basePath = profile . getBasePath ( ) ; String [ ] paths = pathString . split ( "" ) ; List < Path > results = new ArrayList < Path > ( ) ; for ( String path : paths ) { if ( path . isEmpty ( ) ) { continue ; } String resolved ; try { resolved = arguments . replace ( path , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , pathString ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , proc . getName ( ) , kind . toString ( ) , path ) ) ; } Path relative = new Path ( resolved ) ; if ( relative . isAbsolute ( ) ) { WGLOG . warn ( "" , getName ( ) , proc . getName ( ) , kind . prefix , FILE . key ( ) , pathString ) ; } results . add ( new Path ( basePath , relative ) ) ; } return results ; } private < T > T newDataModel ( ProcessScript < T > script ) throws IOException { assert script != null ; Class < T > dataClass = script . getDataClass ( ) ; LOG . debug ( "" , new Object [ ] { dataClass . getName ( ) , getName ( ) , script . getName ( ) , } ) ; try { return ReflectionUtils . newInstance ( dataClass , configuration ) ; } catch ( Exception e ) { WGLOG . error ( "" , getName ( ) , script . getName ( ) , FILE . key ( ) , dataClass . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , getName ( ) , script . getName ( ) , dataClass . getName ( ) ) , e ) ; } } } package com . asakusafw . windgate . hadoopfs . jsch ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . concurrent . TimeUnit ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . hadoopfs . HadoopFsLogger ; import com . asakusafw . windgate . hadoopfs . ssh . SshConnection ; import com . asakusafw . windgate . hadoopfs . ssh . SshProfile ; import com . jcraft . jsch . ChannelExec ; import com . jcraft . jsch . JSch ; import com . jcraft . jsch . JSchException ; import com . jcraft . jsch . Session ; class JschConnection implements SshConnection { static final WindGateLogger WGLOG = new HadoopFsLogger ( JschConnection . class ) ; static final Logger LOG = LoggerFactory . getLogger ( JschConnection . class ) ; private static final Pattern SH_NAME = Pattern . compile ( "" ) ; private static final Pattern SH_METACHARACTERS = Pattern . compile ( "" ) ; private final Session session ; private final ChannelExec channel ; private final SshProfile profile ; private final String command ; public JschConnection ( SshProfile profile , List < String > commandLineTokens ) throws IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( commandLineTokens == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . command = buildCommand ( commandLineTokens , profile . getEnvironmentVariables ( ) ) ; try { JSch jsch = new JSch ( ) ; jsch . addIdentity ( profile . getPrivateKey ( ) , profile . getPassPhrase ( ) ) ; session = jsch . getSession ( profile . getUser ( ) , profile . getHost ( ) , profile . getPort ( ) ) ; session . setConfig ( "" , "" ) ; session . setServerAliveInterval ( ( int ) TimeUnit . SECONDS . toMillis ( ) ) ; session . setTimeout ( ( int ) TimeUnit . SECONDS . toMillis ( ) ) ; WGLOG . info ( "" , profile . getResourceName ( ) , profile . getUser ( ) , profile . getHost ( ) , profile . getPort ( ) ) ; session . connect ( ) ; WGLOG . info ( "" , profile . getResourceName ( ) , profile . getUser ( ) , profile . getHost ( ) , profile . getPort ( ) ) ; boolean succeeded = false ; try { channel = ( ChannelExec ) session . openChannel ( "" ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "" , command ) ; } channel . setCommand ( command ) ; channel . setErrStream ( System . err , true ) ; succeeded = true ; } finally { if ( succeeded == false ) { LOG . debug ( "" ) ; session . disconnect ( ) ; } } } catch ( JSchException e ) { WGLOG . error ( "" , profile . getResourceName ( ) , profile . getUser ( ) , profile . getHost ( ) , profile . getPort ( ) ) ; throw new IOException ( MessageFormat . format ( "" , profile . getUser ( ) , profile . getHost ( ) , String . valueOf ( profile . getPort ( ) ) , command ) , e ) ; } } private String buildCommand ( List < String > commandLineTokens , Map < String , String > environmentVariables ) { assert commandLineTokens != null ; assert environmentVariables != null ; Map < String , String > env = new HashMap < String , String > ( ) ; env . putAll ( environmentVariables ) ; env . putAll ( RuntimeContext . get ( ) . unapply ( ) ) ; StringBuilder buf = new StringBuilder ( ) ; for ( Map . Entry < String , String > entry : env . entrySet ( ) ) { if ( SH_NAME . matcher ( entry . getKey ( ) ) . matches ( ) == false ) { WGLOG . warn ( "" , profile . getResourceName ( ) , profile . getUser ( ) , profile . getHost ( ) , String . valueOf ( profile . getPort ( ) ) , entry . getKey ( ) , entry . getValue ( ) ) ; continue ; } if ( buf . length ( ) > ) { buf . append ( '' ) ; } buf . append ( entry . getKey ( ) ) ; String replaced = SH_METACHARACTERS . matcher ( entry . getValue ( ) ) . replaceAll ( "" ) ; buf . append ( '' ) ; buf . append ( '' ) ; buf . append ( replaced ) ; buf . append ( '' ) ; } for ( String token : commandLineTokens ) { if ( buf . length ( ) > ) { buf . append ( '' ) ; } String replaced = SH_METACHARACTERS . matcher ( token ) . replaceAll ( "" ) ; buf . append ( '' ) ; buf . append ( replaced ) ; buf . append ( '' ) ; } return buf . toString ( ) ; } @ Override public void connect ( ) throws IOException { try { WGLOG . info ( "" , profile . getResourceName ( ) , profile . getUser ( ) , profile . getHost ( ) , profile . getPort ( ) , command ) ; channel . connect ( ( int ) TimeUnit . SECONDS . toMillis ( ) ) ; WGLOG . info ( "" , profile . getResourceName ( ) , profile . getUser ( ) , profile . getHost ( ) , profile . getPort ( ) , command ) ; } catch ( JSchException e ) { WGLOG . error ( "" , profile . getResourceName ( ) , profile . getUser ( ) , profile . getHost ( ) , profile . getPort ( ) , command ) ; throw new IOException ( MessageFormat . format ( "" , profile . getUser ( ) , profile . getHost ( ) , String . valueOf ( profile . getPort ( ) ) ) , e ) ; } } @ Override public OutputStream openStandardInput ( ) throws IOException { LOG . debug ( "" , command ) ; return channel . getOutputStream ( ) ; } @ Override public InputStream openStandardOutput ( ) throws IOException { LOG . debug ( "" , command ) ; return channel . getInputStream ( ) ; } @ Override public void redirectStandardOutput ( OutputStream output , boolean dontClose ) { LOG . debug ( "" , command ) ; channel . setOutputStream ( output , dontClose ) ; } @ Override public int waitForExit ( long timeout ) throws InterruptedException , IOException { LOG . debug ( "" , command ) ; long until = System . currentTimeMillis ( ) + timeout ; while ( until > System . currentTimeMillis ( ) ) { if ( channel . isClosed ( ) ) { break ; } Thread . sleep ( ) ; } if ( channel . isClosed ( ) == false ) { WGLOG . error ( "" , profile . getResourceName ( ) , profile . getUser ( ) , profile . getHost ( ) , profile . getPort ( ) , command ) ; throw new IOException ( MessageFormat . format ( "" , profile . getUser ( ) , profile . getHost ( ) , String . valueOf ( profile . getPort ( ) ) , command ) ) ; } return channel . getExitStatus ( ) ; } @ Override public void close ( ) throws IOException { LOG . debug ( "" , command ) ; try { channel . disconnect ( ) ; } finally { session . disconnect ( ) ; } } } package com . asakusafw . windgate . hadoopfs . jsch ; import java . io . IOException ; import java . util . List ; import org . apache . hadoop . conf . Configuration ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . hadoopfs . ssh . AbstractSshHadoopFsMirror ; import com . asakusafw . windgate . hadoopfs . ssh . SshConnection ; import com . asakusafw . windgate . hadoopfs . ssh . SshProfile ; @ SimulationSupport public class JschHadoopFsMirror extends AbstractSshHadoopFsMirror { static final Logger LOG = LoggerFactory . getLogger ( JschHadoopFsMirror . class ) ; public JschHadoopFsMirror ( Configuration configuration , SshProfile profile , ParameterList arguments ) { super ( configuration , profile , arguments ) ; } @ Override protected SshConnection openConnection ( SshProfile profile , List < String > command ) throws IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( command == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , new Object [ ] { profile . getUser ( ) , profile . getHost ( ) , String . valueOf ( profile . getPort ( ) ) , command , } ) ; return new JschConnection ( profile , command ) ; } } package com . asakusafw . windgate . hadoopfs . jsch ; package com . asakusafw . windgate . hadoopfs . jsch ; import java . io . IOException ; import java . text . MessageFormat ; import org . apache . hadoop . conf . Configuration ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . resource . ResourceProvider ; import com . asakusafw . windgate . hadoopfs . ssh . SshProfile ; public class JschHadoopFsProvider extends ResourceProvider { static final Logger LOG = LoggerFactory . getLogger ( JschHadoopFsProvider . class ) ; private volatile Configuration configuration ; private volatile SshProfile sshProfile ; @ Override protected void configure ( ResourceProfile profile ) throws IOException { LOG . debug ( "" , profile . getName ( ) ) ; this . configuration = new Configuration ( ) ; try { this . sshProfile = SshProfile . convert ( configuration , profile ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( MessageFormat . format ( "" , profile . getName ( ) ) ) ; } } @ Override public ResourceMirror create ( String sessionId , ParameterList arguments ) throws IOException { if ( sessionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , sshProfile . getResourceName ( ) , sessionId ) ; return new JschHadoopFsMirror ( configuration , sshProfile , arguments ) ; } } package com . asakusafw . windgate . hadoopfs . temporary ; import java . io . EOFException ; import java . io . IOException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . windgate . core . resource . SourceDriver ; public class ModelInputSourceDriver < T > implements SourceDriver < T > { static final Logger LOG = LoggerFactory . getLogger ( ModelInputSourceDriver . class ) ; private final ModelInputProvider < T > provider ; private final T value ; private ModelInput < T > currentInput ; private boolean sawNext ; public ModelInputSourceDriver ( ModelInputProvider < T > provider , T value ) { if ( provider == null ) { throw new IllegalArgumentException ( "" ) ; } if ( value == null ) { throw new IllegalArgumentException ( "" ) ; } this . provider = provider ; this . value = value ; } @ Override public void prepare ( ) { sawNext = false ; currentInput = null ; } @ Override public boolean next ( ) throws IOException { while ( true ) { if ( currentInput == null ) { if ( provider . next ( ) ) { currentInput = provider . open ( ) ; } else { sawNext = false ; return false ; } } if ( currentInput . readTo ( value ) ) { sawNext = true ; return true ; } else { currentInput . close ( ) ; currentInput = null ; } } } @ Override public T get ( ) throws IOException { if ( sawNext ) { return value ; } throw new EOFException ( ) ; } @ Override public void close ( ) throws IOException { LOG . debug ( "" ) ; sawNext = false ; try { if ( currentInput != null ) { currentInput . close ( ) ; currentInput = null ; } } finally { provider . close ( ) ; } } } package com . asakusafw . windgate . hadoopfs . temporary ; import java . io . IOException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelOutput ; import com . asakusafw . windgate . core . resource . DrainDriver ; public class ModelOutputDrainDriver < T > implements DrainDriver < T > { static final Logger LOG = LoggerFactory . getLogger ( ModelOutputDrainDriver . class ) ; private final ModelOutput < T > output ; public ModelOutputDrainDriver ( ModelOutput < T > output ) { if ( output == null ) { throw new IllegalArgumentException ( "" ) ; } this . output = output ; } @ Override public void prepare ( ) throws IOException { return ; } @ Override public void put ( T object ) throws IOException { output . write ( object ) ; } @ Override public void close ( ) throws IOException { LOG . debug ( "" ) ; output . close ( ) ; } } package com . asakusafw . windgate . hadoopfs . temporary ; package com . asakusafw . windgate . hadoopfs . temporary ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . Callable ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . SynchronousQueue ; import java . util . concurrent . TimeUnit ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . io . ModelInput ; import com . asakusafw . runtime . stage . temporary . TemporaryStorage ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . hadoopfs . HadoopFsLogger ; public class FileSystemModelInputProvider < T > implements ModelInputProvider < T > { static final WindGateLogger WGLOG = new HadoopFsLogger ( FileSystemModelInputProvider . class ) ; static final Logger LOG = LoggerFactory . getLogger ( FileSystemModelInputProvider . class ) ; final FileSystem fileSystem ; final ExecutorService executor ; final Future < ? > fetcher ; final BlockingQueue < Entry < T > > queue ; private Entry < T > current ; private boolean sawEof ; private boolean closed ; public FileSystemModelInputProvider ( final Configuration configuration , final FileSystem fileSystem , final Iterable < Path > paths , final Class < T > dataModelClass ) throws IOException { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( fileSystem == null ) { throw new IllegalArgumentException ( "" ) ; } if ( paths == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataModelClass == null ) { throw new IllegalArgumentException ( "" ) ; } this . fileSystem = fileSystem ; this . queue = new SynchronousQueue < Entry < T > > ( ) ; this . executor = Executors . newFixedThreadPool ( ) ; this . fetcher = this . executor . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { for ( Path path : paths ) { WGLOG . info ( "" , fileSystem . getUri ( ) , paths ) ; FileStatus [ ] statusList = fileSystem . globStatus ( path ) ; if ( statusList == null || statusList . length == ) { throw new FileNotFoundException ( MessageFormat . format ( "" , fileSystem . getUri ( ) , paths ) ) ; } for ( FileStatus status : statusList ) { WGLOG . info ( "" , fileSystem . getUri ( ) , status . getPath ( ) , status . getLen ( ) ) ; ModelInput < T > input = TemporaryStorage . openInput ( configuration , dataModelClass , status . getPath ( ) ) ; boolean succeed = false ; try { queue . put ( new Entry < T > ( status , input ) ) ; succeed = true ; } finally { if ( succeed == false ) { input . close ( ) ; } } } } queue . put ( Entry . < T > eof ( ) ) ; return null ; } } ) ; } @ Override public boolean next ( ) throws IOException { closeCurrent ( ) ; Entry < T > next = fetchNext ( ) ; if ( next == Entry . EOF ) { return false ; } current = next ; return true ; } private Entry < T > fetchNext ( ) throws IOException { if ( sawEof ) { return Entry . eof ( ) ; } try { while ( true ) { Entry < T > next = queue . poll ( , TimeUnit . SECONDS ) ; if ( next != null ) { return next ; } else if ( fetcher . isDone ( ) ) { break ; } } fetcher . get ( ) ; sawEof = true ; return Entry . eof ( ) ; } catch ( InterruptedException e ) { throw new IOException ( "" , e ) ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof Error ) { throw ( Error ) cause ; } else if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else if ( cause instanceof InterruptedException ) { throw new IOException ( "" , cause ) ; } throw new AssertionError ( e ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } } @ Override public ModelInput < T > open ( ) throws IOException { if ( current == null ) { throw new IOException ( "" ) ; } ModelInput < T > result = current . input ; current = null ; return result ; } @ Override public void close ( ) throws IOException { if ( closed ) { return ; } fetcher . cancel ( true ) ; executor . shutdown ( ) ; closed = true ; closeCurrent ( ) ; while ( true ) { Entry < T > next = queue . poll ( ) ; if ( next == null || next == Entry . EOF ) { break ; } try { next . input . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , fileSystem . getUri ( ) , next . status . getPath ( ) ) ; } } } private void closeCurrent ( ) { if ( current != null ) { try { current . input . close ( ) ; current = null ; } catch ( IOException e ) { WGLOG . warn ( e , "" , fileSystem . getUri ( ) , current . status . getPath ( ) ) ; } } } private static class Entry < T > { static final Entry < ? > EOF = new Entry < Object > ( null , null ) ; final FileStatus status ; final ModelInput < T > input ; Entry ( FileStatus status , ModelInput < T > input ) { this . status = status ; this . input = input ; } @ SuppressWarnings ( "" ) static < T > Entry < T > eof ( ) { return ( Entry < T > ) EOF ; } } } package com . asakusafw . windgate . hadoopfs . temporary ; import java . io . Closeable ; import java . io . IOException ; import com . asakusafw . runtime . io . ModelInput ; public interface ModelInputProvider < T > extends Closeable { boolean next ( ) throws IOException ; ModelInput < T > open ( ) throws IOException ; } package com . asakusafw . windgate . hadoopfs ; import java . io . IOException ; import java . net . URI ; import java . text . MessageFormat ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . compress . CompressionCodec ; import org . apache . hadoop . util . ReflectionUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . hadoopfs . ssh . SshProfile ; public class HadoopFsProfile { static final WindGateLogger WGLOG = new HadoopFsLogger ( HadoopFsProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( HadoopFsProfile . class ) ; public static final String KEY_BASE_PATH = "" ; public static final String KEY_COMPRESSION = "" ; private final String resourceName ; private final Path basePath ; private final CompressionCodec compressionCodec ; public HadoopFsProfile ( String resourceName , Path basePath , CompressionCodec compressionCodec ) { if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( basePath == null ) { throw new IllegalArgumentException ( "" ) ; } this . resourceName = resourceName ; this . basePath = basePath ; this . compressionCodec = compressionCodec ; } public static HadoopFsProfile convert ( Configuration configuration , ResourceProfile profile ) throws IOException { if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } String name = profile . getName ( ) ; Path basePath = extractBasePath ( configuration , profile ) ; CompressionCodec compressionCodec = extractCompressionCodec ( configuration , profile ) ; return new HadoopFsProfile ( name , basePath , compressionCodec ) ; } private static Path extractBasePath ( Configuration configuration , ResourceProfile profile ) throws IOException { assert configuration != null ; assert profile != null ; String result = extract ( profile , KEY_BASE_PATH , false ) ; try { if ( result == null || result . isEmpty ( ) ) { FileSystem fileSystem = FileSystem . get ( configuration ) ; return fileSystem . getWorkingDirectory ( ) ; } URI uri = URI . create ( result ) ; FileSystem fileSystem = FileSystem . get ( uri , configuration ) ; return fileSystem . makeQualified ( new Path ( uri ) ) ; } catch ( IOException e ) { WGLOG . error ( e , "" , profile . getName ( ) , KEY_BASE_PATH , result == null ? "" : result ) ; throw new IOException ( MessageFormat . format ( "" , profile . getName ( ) , KEY_BASE_PATH , result == null ? "" : result ) , e ) ; } } private static CompressionCodec extractCompressionCodec ( Configuration configuration , ResourceProfile profile ) { assert configuration != null ; assert profile != null ; String raw = extract ( profile , KEY_COMPRESSION , false ) ; CompressionCodec compressionCodec ; try { if ( raw == null ) { compressionCodec = null ; } else { Class < ? > codecClass = configuration . getClassByName ( raw ) ; compressionCodec = ( CompressionCodec ) ReflectionUtils . newInstance ( codecClass , configuration ) ; } } catch ( Exception e ) { WGLOG . error ( e , "" , profile . getName ( ) , KEY_COMPRESSION , raw ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , KEY_COMPRESSION , raw ) , e ) ; } WGLOG . info ( "" , profile . getName ( ) , KEY_COMPRESSION , compressionCodec == null ? null : raw ) ; return compressionCodec ; } private static String extract ( ResourceProfile profile , String configKey , boolean mandatory ) { assert profile != null ; assert configKey != null ; String value = profile . getConfiguration ( ) . get ( configKey ) ; if ( value == null ) { if ( mandatory == false ) { return null ; } else { WGLOG . error ( "" , profile . getName ( ) , configKey , null ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey ) ) ; } } try { return profile . getContext ( ) . getContextParameters ( ) . replace ( value . trim ( ) , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , profile . getName ( ) , configKey , value ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , profile . getName ( ) , configKey , value ) , e ) ; } } public String getResourceName ( ) { return resourceName ; } public Path getBasePath ( ) { return basePath ; } public CompressionCodec getCompressionCodec ( ) { return compressionCodec ; } } package com . asakusafw . windgate . hadoopfs ; package com . asakusafw . windgate . hadoopfs ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . windgate . core . WindGateLogger ; public class HadoopFsLogger extends WindGateLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public HadoopFsLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . windgate . file . session ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import static org . junit . matchers . JUnitMatchers . * ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . junit . Assume ; import org . junit . Before ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . session . SessionException ; import com . asakusafw . windgate . core . session . SessionException . Reason ; import com . asakusafw . windgate . core . session . SessionMirror ; import com . asakusafw . windgate . core . session . SessionProfile ; public class FileSessionProviderTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; private FileSessionProvider provider ; @ Before public void setUp ( ) throws Throwable { provider = new FileSessionProvider ( ) ; provider . configure ( new SessionProfile ( FileSessionProvider . class , ProfileContext . system ( FileSessionProvider . class . getClassLoader ( ) ) , Collections . singletonMap ( FileSessionProvider . KEY_DIRECTORY , folder . getRoot ( ) . getAbsolutePath ( ) ) ) ) ; } @ Test public void create ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; session . close ( ) ; } @ Test public void create_multiple ( ) throws Exception { SessionMirror session1 = provider . create ( "" ) ; try { SessionMirror session2 = provider . create ( "" ) ; session2 . close ( ) ; } finally { session1 . close ( ) ; } } @ Test public void create_exists ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; session . close ( ) ; try { SessionMirror reopen = provider . create ( "" ) ; reopen . close ( ) ; fail ( ) ; } catch ( SessionException e ) { assertThat ( e . getSessionId ( ) , is ( "" ) ) ; assertThat ( e . getReason ( ) , is ( Reason . ALREADY_EXIST ) ) ; } } @ Test public void create_acquired ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; try { try { SessionMirror reopen = provider . create ( "" ) ; reopen . close ( ) ; fail ( ) ; } catch ( SessionException e ) { assertThat ( e . getSessionId ( ) , is ( "" ) ) ; assertThat ( e . getReason ( ) , is ( Reason . ACQUIRED ) ) ; } } finally { session . close ( ) ; } } @ Test public void open ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; session . close ( ) ; SessionMirror reopen = provider . open ( "" ) ; reopen . close ( ) ; } @ Test public void open_missing ( ) throws Exception { try { SessionMirror session = provider . open ( "" ) ; session . close ( ) ; fail ( ) ; } catch ( SessionException e ) { assertThat ( e . getSessionId ( ) , is ( "" ) ) ; assertThat ( e . getReason ( ) , is ( Reason . NOT_EXIST ) ) ; List < String > all = new ArrayList < String > ( provider . getCreatedIds ( ) ) ; assertThat ( all . isEmpty ( ) , is ( true ) ) ; } } @ Test public void open_acquired ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; try { try { SessionMirror reopen = provider . open ( "" ) ; reopen . close ( ) ; fail ( ) ; } catch ( SessionException e ) { assertThat ( e . getSessionId ( ) , is ( "" ) ) ; assertThat ( e . getReason ( ) , is ( Reason . ACQUIRED ) ) ; } } finally { session . close ( ) ; } } @ Test public void open_conflict ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; session . close ( ) ; SessionMirror other = provider . open ( "" ) ; try { try { SessionMirror reopen = provider . open ( "" ) ; reopen . close ( ) ; } catch ( SessionException e ) { assertThat ( e . getSessionId ( ) , is ( "" ) ) ; assertThat ( e . getReason ( ) , is ( Reason . ACQUIRED ) ) ; } } finally { other . close ( ) ; } } @ Test public void getIds ( ) throws Exception { SessionMirror session1 = provider . create ( "" ) ; session1 . close ( ) ; SessionMirror session2 = provider . create ( "" ) ; session2 . complete ( ) ; SessionMirror session3 = provider . create ( "" ) ; session3 . close ( ) ; List < String > all = new ArrayList < String > ( provider . getCreatedIds ( ) ) ; assertThat ( all , hasItems ( "" , "" ) ) ; assertThat ( all . size ( ) , is ( ) ) ; } @ Test public void delete ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; session . close ( ) ; provider . delete ( "" ) ; List < String > all = new ArrayList < String > ( provider . getCreatedIds ( ) ) ; assertThat ( all . isEmpty ( ) , is ( true ) ) ; } @ Test public void delete_missing ( ) throws Exception { try { provider . delete ( "" ) ; fail ( ) ; } catch ( SessionException e ) { assertThat ( e . getReason ( ) , is ( SessionException . Reason . NOT_EXIST ) ) ; } List < String > all = new ArrayList < String > ( provider . getCreatedIds ( ) ) ; assertThat ( all . isEmpty ( ) , is ( true ) ) ; } @ Test public void getId ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; try { assertThat ( session . getId ( ) , is ( "" ) ) ; } finally { session . close ( ) ; } } @ Test public void complete ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; session . complete ( ) ; SessionMirror reopen = provider . create ( "" ) ; reopen . close ( ) ; } @ Test public void abort ( ) throws Exception { SessionMirror session = provider . create ( "" ) ; session . abort ( ) ; SessionMirror reopen = provider . create ( "" ) ; reopen . close ( ) ; } @ Test ( expected = IOException . class ) public void config_empty ( ) throws Exception { provider = new FileSessionProvider ( ) ; provider . configure ( new SessionProfile ( FileSessionProvider . class , ProfileContext . system ( FileSessionProvider . class . getClassLoader ( ) ) , Collections . < String , String > emptyMap ( ) ) ) ; } @ Test ( expected = IOException . class ) public void config_unknown_variable ( ) throws Exception { Assume . assumeThat ( System . getenv ( "" ) , is ( nullValue ( ) ) ) ; provider = new FileSessionProvider ( ) ; provider . configure ( new SessionProfile ( FileSessionProvider . class , ProfileContext . system ( FileSessionProvider . class . getClassLoader ( ) ) , Collections . singletonMap ( FileSessionProvider . KEY_DIRECTORY , "" ) ) ) ; } @ Test ( expected = IOException . class ) public void config_conflict_directory ( ) throws Exception { File file = folder . newFile ( "" ) ; provider = new FileSessionProvider ( ) ; provider . configure ( new SessionProfile ( FileSessionProvider . class , ProfileContext . system ( FileSessionProvider . class . getClassLoader ( ) ) , Collections . singletonMap ( FileSessionProvider . KEY_DIRECTORY , file . getAbsolutePath ( ) ) ) ) ; } } package com . asakusafw . windgate . file . resource ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . ObjectOutputStream ; import java . util . Arrays ; import java . util . Collections ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; public class FileResourceMirrorTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void getName ( ) throws Exception { FileResourceMirror resource = new FileResourceMirror ( "" ) ; try { assertThat ( resource . getName ( ) , is ( "" ) ) ; } finally { resource . close ( ) ; } } @ Test public void prepare ( ) throws Exception { File source = folder . newFile ( "" ) ; File drain = folder . newFile ( "" ) ; FileResourceMirror resource = new FileResourceMirror ( "" ) ; try { ProcessScript < String > script = script ( source , drain ) ; resource . prepare ( gate ( script ) ) ; } finally { resource . close ( ) ; } } @ Test public void createSource ( ) throws Exception { File source = folder . newFile ( "" ) ; File drain = folder . newFile ( "" ) ; put ( source , "" , "" ) ; FileResourceMirror resource = new FileResourceMirror ( "" ) ; try { ProcessScript < String > script = script ( source , drain ) ; resource . prepare ( gate ( script ) ) ; SourceDriver < String > driver = resource . createSource ( script ) ; try { driver . prepare ( ) ; assertThat ( driver . next ( ) , is ( true ) ) ; assertThat ( driver . get ( ) , is ( "" ) ) ; assertThat ( driver . next ( ) , is ( true ) ) ; assertThat ( driver . get ( ) , is ( "" ) ) ; assertThat ( driver . next ( ) , is ( false ) ) ; } finally { driver . close ( ) ; } } finally { resource . close ( ) ; } } @ Test public void createDrain ( ) throws Exception { File source = folder . newFile ( "" ) ; File drain = folder . newFile ( "" ) ; FileResourceMirror resource = new FileResourceMirror ( "" ) ; try { ProcessScript < String > script = script ( source , drain ) ; ProcessScript < String > opposite = script ( drain , source ) ; resource . prepare ( gate ( script , opposite ) ) ; DrainDriver < String > driver = resource . createDrain ( script ) ; try { driver . prepare ( ) ; driver . put ( "" ) ; driver . put ( "" ) ; } finally { driver . close ( ) ; } SourceDriver < String > verifier = resource . createSource ( opposite ) ; try { verifier . prepare ( ) ; assertThat ( verifier . next ( ) , is ( true ) ) ; assertThat ( verifier . get ( ) , is ( "" ) ) ; assertThat ( verifier . next ( ) , is ( true ) ) ; assertThat ( verifier . get ( ) , is ( "" ) ) ; assertThat ( verifier . next ( ) , is ( false ) ) ; } finally { verifier . close ( ) ; } } finally { resource . close ( ) ; } } private GateScript gate ( ProcessScript < ? > ... scripts ) { return new GateScript ( "" , Arrays . asList ( scripts ) ) ; } private ProcessScript < String > script ( File source , File drain ) { return new ProcessScript < String > ( "" , "" , String . class , new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , source . getPath ( ) ) ) , new DriverScript ( "" , Collections . singletonMap ( FileProcess . FILE . key ( ) , drain . getPath ( ) ) ) ) ; } private void put ( File file , String ... values ) throws IOException { FileOutputStream out = new FileOutputStream ( file ) ; try { ObjectOutputStream output = new ObjectOutputStream ( out ) ; for ( String string : values ) { output . writeObject ( string ) ; } output . close ( ) ; } finally { out . close ( ) ; } } } package com . asakusafw . windgate . core . session ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . util . Properties ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . file . session . FileSessionProvider ; public class SessionProfileTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void loadFrom ( ) { Properties p = new Properties ( ) ; p . setProperty ( SessionProfile . KEY_PROVIDER , FileSessionProvider . class . getName ( ) ) ; SessionProfile profile = SessionProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profile . getProviderClass ( ) , is ( ( Object ) FileSessionProvider . class ) ) ; assertThat ( profile . getConfiguration ( ) . size ( ) , is ( ) ) ; } @ Test public void loadFrom_configure ( ) { String path = new File ( "" + getClass ( ) . getSimpleName ( ) ) . getAbsolutePath ( ) ; Properties p = new Properties ( ) ; p . setProperty ( SessionProfile . KEY_PROVIDER , FileSessionProvider . class . getName ( ) ) ; p . setProperty ( SessionProfile . KEY_PREFIX + FileSessionProvider . KEY_DIRECTORY , path ) ; SessionProfile profile = SessionProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profile . getProviderClass ( ) , is ( ( Object ) FileSessionProvider . class ) ) ; assertThat ( profile . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( profile . getConfiguration ( ) . get ( FileSessionProvider . KEY_DIRECTORY ) , is ( path ) ) ; } @ Test public void storeTo ( ) { String path = new File ( "" + getClass ( ) . getSimpleName ( ) ) . getAbsolutePath ( ) ; Properties p = new Properties ( ) ; p . setProperty ( SessionProfile . KEY_PROVIDER , FileSessionProvider . class . getName ( ) ) ; p . setProperty ( SessionProfile . KEY_PREFIX + FileSessionProvider . KEY_DIRECTORY , path ) ; SessionProfile profile = SessionProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; profile . storeTo ( restored ) ; assertThat ( restored , is ( p ) ) ; } @ Test public void storeTo_configure ( ) { Properties p = new Properties ( ) ; p . setProperty ( SessionProfile . KEY_PROVIDER , FileSessionProvider . class . getName ( ) ) ; SessionProfile profile = SessionProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; profile . storeTo ( restored ) ; assertThat ( restored , is ( p ) ) ; } @ Test public void removeCorrespondingKeys ( ) { Properties p = new Properties ( ) ; p . setProperty ( SessionProfile . KEY_PROVIDER , "" ) ; p . setProperty ( SessionProfile . KEY_PROVIDER + "" , "" ) ; p . setProperty ( SessionProfile . KEY_PREFIX + "" , "" ) ; p . setProperty ( SessionProfile . KEY_PREFIX + "" , "" ) ; SessionProfile . removeCorrespondingKeys ( p ) ; Properties answer = new Properties ( ) ; answer . setProperty ( SessionProfile . KEY_PROVIDER + "" , "" ) ; assertThat ( p , is ( answer ) ) ; } @ Test public void createProvider ( ) throws Exception { File path = folder . newFolder ( "" ) ; Assume . assumeTrue ( path . delete ( ) ) ; Properties p = new Properties ( ) ; p . setProperty ( SessionProfile . KEY_PROVIDER , FileSessionProvider . class . getName ( ) ) ; p . setProperty ( SessionProfile . KEY_PREFIX + FileSessionProvider . KEY_DIRECTORY , path . getPath ( ) ) ; SessionProfile profile = SessionProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; SessionProvider provider = profile . createProvider ( ) ; SessionMirror session = provider . create ( "" ) ; session . close ( ) ; assertThat ( path . isDirectory ( ) , is ( true ) ) ; } } package com . asakusafw . windgate . core ; import static org . hamcrest . Matchers . * ; import static org . junit . Assert . * ; import java . util . Properties ; import org . junit . Test ; public class CoreProfileTest { @ Test public void loadFrom ( ) { Properties p = new Properties ( ) ; CoreProfile profile = CoreProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profile . getMaxProcesses ( ) , is ( CoreProfile . DEFAULT_MAX_PROCESSES ) ) ; } @ Test public void loadFrom_configured ( ) { Properties p = new Properties ( ) ; p . setProperty ( CoreProfile . KEY_PREFIX + CoreProfile . KEY_MAX_PROCESSES , "" ) ; CoreProfile profile = CoreProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profile . getMaxProcesses ( ) , is ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_maxThreads ( ) { Properties p = new Properties ( ) ; p . setProperty ( CoreProfile . KEY_PREFIX + CoreProfile . KEY_MAX_PROCESSES , "" ) ; CoreProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_token ( ) { Properties p = new Properties ( ) ; p . setProperty ( CoreProfile . KEY_PREFIX + CoreProfile . KEY_MAX_PROCESSES , "" ) ; CoreProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test public void storeTo ( ) { Properties p = new Properties ( ) ; p . setProperty ( CoreProfile . KEY_PREFIX + CoreProfile . KEY_MAX_PROCESSES , "" ) ; CoreProfile profile = CoreProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; profile . storeTo ( restored ) ; assertThat ( restored , is ( p ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void storeTo_conflict ( ) { Properties p = new Properties ( ) ; p . setProperty ( CoreProfile . KEY_PREFIX + CoreProfile . KEY_MAX_PROCESSES , "" ) ; CoreProfile profile = CoreProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; restored . setProperty ( CoreProfile . KEY_PREFIX + "" , "" ) ; profile . storeTo ( restored ) ; } @ Test public void removeCorrespondingKeys ( ) { Properties p = new Properties ( ) ; p . setProperty ( CoreProfile . KEY_PREFIX + "" , "" ) ; p . setProperty ( "" , "" ) ; CoreProfile . removeCorrespondingKeys ( p ) ; Properties answer = new Properties ( ) ; answer . setProperty ( "" , "" ) ; assertThat ( p , is ( answer ) ) ; } } package com . asakusafw . windgate . core ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . EOFException ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; import com . asakusafw . windgate . core . process . BasicProcessProvider ; import com . asakusafw . windgate . core . process . ProcessProfile ; import com . asakusafw . windgate . core . process . ProcessProvider ; import com . asakusafw . windgate . core . resource . DriverFactory ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . session . SessionProfile ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; import com . asakusafw . windgate . file . resource . FileResourceProvider ; import com . asakusafw . windgate . file . session . FileSessionProvider ; public class GateTaskTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void execute ( ) throws Exception { File in = folder . newFile ( "" ) ; File out = folder . newFile ( "" ) ; put ( in , "" , "" , "" ) ; new GateTask ( profile ( ) , script ( p ( "" , "" , in , "" , out ) ) , "" , true , true , new ParameterList ( ) ) . execute ( ) ; List < String > results = get ( out ) ; assertThat ( results , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test public void execute_multiple ( ) throws Exception { File in1 = folder . newFile ( "" ) ; File in2 = folder . newFile ( "" ) ; File out1 = folder . newFile ( "" ) ; File out2 = folder . newFile ( "" ) ; put ( in1 , "" , "" , "" ) ; put ( in2 , "" , "" , "" ) ; new GateTask ( profile ( ) , script ( p ( "" , "" , in1 , "" , out1 ) , p ( "" , "" , in2 , "" , out2 ) ) , "" , true , true , new ParameterList ( ) ) . execute ( ) ; assertThat ( get ( out1 ) , is ( Arrays . asList ( "" , "" , "" ) ) ) ; assertThat ( get ( out2 ) , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test public void execute_dual ( ) throws Exception { File in = folder . newFile ( "" ) ; File temp = folder . newFile ( "" ) ; File out = folder . newFile ( "" ) ; put ( in , "" , "" , "" ) ; GateProfile profile = profile ( ) ; GateScript importer = script ( p ( "" , "" , in , "" , temp ) ) ; new GateTask ( profile , importer , "" , true , false , new ParameterList ( ) ) . execute ( ) ; GateScript exporter = script ( p ( "" , "" , temp , "" , out ) ) ; new GateTask ( profile , exporter , "" , false , true , new ParameterList ( ) ) . execute ( ) ; List < String > results = get ( out ) ; assertThat ( results , is ( Arrays . asList ( "" , "" , "" ) ) ) ; } @ Test ( expected = IOException . class ) public void execute_missing_session ( ) throws Exception { File in = folder . newFile ( "" ) ; File out = folder . newFile ( "" ) ; new GateTask ( profile ( ) , script ( p ( "" , "" , in , "" , out ) ) , "" , false , false , new ParameterList ( ) ) . execute ( ) ; } @ Test ( expected = IOException . class ) public void execute_missing_input ( ) throws Exception { File in = folder . newFile ( "" ) ; File out = folder . newFile ( "" ) ; in . delete ( ) ; new GateTask ( profile ( ) , script ( p ( "" , "" , in , "" , out ) ) , "" , true , true , new ParameterList ( ) ) . execute ( ) ; } @ Test public void execute_sim ( ) throws Exception { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; File in = folder . newFile ( "" ) ; File out = folder . newFile ( "" ) ; out . delete ( ) ; put ( in , "" , "" , "" ) ; new GateTask ( profile ( ) , script ( p ( "" , "" , "" , in , "" , out ) ) , "" , true , true , new ParameterList ( ) ) . execute ( ) ; assertThat ( out . exists ( ) , is ( false ) ) ; } private GateProfile profile ( ) { CoreProfile core = new CoreProfile ( ) ; SessionProfile session = new SessionProfile ( FileSessionProvider . class , ProfileContext . system ( FileSessionProvider . class . getClassLoader ( ) ) , Collections . singletonMap ( FileSessionProvider . KEY_DIRECTORY , folder . newFolder ( "" ) . getAbsolutePath ( ) ) ) ; List < ProcessProfile > processes = Arrays . asList ( new ProcessProfile [ ] { new ProcessProfile ( "" , BasicProcessProvider . class , ProfileContext . system ( BasicProcessProvider . class . getClassLoader ( ) ) , Collections . < String , String > emptyMap ( ) ) , new ProcessProfile ( "" , VoidProcessProvider . class , ProfileContext . system ( BasicProcessProvider . class . getClassLoader ( ) ) , Collections . < String , String > emptyMap ( ) ) , } ) ; List < ResourceProfile > resources = Arrays . asList ( new ResourceProfile [ ] { new ResourceProfile ( "" , FileResourceProvider . class , ProfileContext . system ( FileResourceProvider . class . getClassLoader ( ) ) , Collections . < String , String > emptyMap ( ) ) , new ResourceProfile ( "" , FileResourceProvider . class , ProfileContext . system ( FileResourceProvider . class . getClassLoader ( ) ) , Collections . < String , String > emptyMap ( ) ) , } ) ; return new GateProfile ( "" , core , session , processes , resources ) ; } private File put ( File file , String ... values ) throws IOException { FileOutputStream out = new FileOutputStream ( file ) ; try { ObjectOutputStream output = new ObjectOutputStream ( out ) ; for ( String string : values ) { output . writeObject ( string ) ; } output . close ( ) ; } finally { out . close ( ) ; } return file ; } private List < String > get ( File file ) throws IOException { FileInputStream in = new FileInputStream ( file ) ; try { List < String > results = new ArrayList < String > ( ) ; ObjectInputStream input = new ObjectInputStream ( in ) ; while ( true ) { try { String value = ( String ) input . readObject ( ) ; results . add ( value ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } catch ( EOFException e ) { return results ; } } } finally { in . close ( ) ; } } private GateScript script ( ProcessScript < ? > ... processes ) { return new GateScript ( "" , Arrays . asList ( processes ) ) ; } private ProcessScript < ? > p ( String name , String sourceName , File sourceFile , String drainName , File drainFile ) { return p ( drainName , "" , sourceName , sourceFile , drainName , drainFile ) ; } private ProcessScript < ? > p ( String name , String processName , String sourceName , File sourceFile , String drainName , File drainFile ) { return new ProcessScript < String > ( name , processName , String . class , d ( sourceName , sourceFile ) , d ( drainName , drainFile ) ) ; } private DriverScript d ( String name , File file ) { return new DriverScript ( name , Collections . singletonMap ( FileProcess . FILE . key ( ) , file . getPath ( ) ) ) ; } public static class VoidProcessProvider extends ProcessProvider { @ Override protected void configure ( ProcessProfile profile ) throws IOException { return ; } @ Override public < T > void execute ( DriverFactory drivers , ProcessScript < T > script ) throws IOException { throw new AssertionError ( ) ; } } } package com . asakusafw . windgate . core . process ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . junit . Rule ; import org . junit . Test ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . RuntimeContext . ExecutionMode ; import com . asakusafw . runtime . core . context . RuntimeContextKeeper ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . resource . MockDrainDriver ; import com . asakusafw . windgate . core . resource . MockSourceDriver ; public class BasicProcessProviderTest { @ Rule public final RuntimeContextKeeper rc = new RuntimeContextKeeper ( ) ; BasicProcessProvider provider = new BasicProcessProvider ( ) ; { provider . configure ( new ProcessProfile ( "" , BasicProcessProvider . class , ProfileContext . system ( BasicProcessProvider . class . getClassLoader ( ) ) , Collections . < String , String > emptyMap ( ) ) ) ; } @ Test public void execute ( ) throws IOException { MockDriverFactory factory = new MockDriverFactory ( ) ; MockSourceDriver < String > source = factory . add ( "" , new MockSourceDriver < String > ( "" ) ) ; MockDrainDriver < String > drain = factory . add ( "" , new MockDrainDriver < String > ( "" ) ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; List < String > data = Arrays . asList ( "" , "" , "" ) ; source . setIterable ( data ) ; provider . execute ( factory , script ) ; assertThat ( drain . getResults ( ) , is ( data ) ) ; } @ Test ( expected = IOException . class ) public void execute_invalid_source ( ) throws IOException { MockDriverFactory factory = new MockDriverFactory ( ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; provider . execute ( factory , script ) ; } @ Test ( expected = IOException . class ) public void execute_invalid_drain ( ) throws IOException { MockDriverFactory factory = new MockDriverFactory ( ) ; MockSourceDriver < String > source = factory . add ( "" , new MockSourceDriver < String > ( "" ) ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; List < String > data = Arrays . asList ( "" , "" , "" ) ; source . setIterable ( data ) ; provider . execute ( factory , script ) ; } @ Test ( expected = IOException . class ) public void execute_transfer_failed ( ) throws IOException { MockDriverFactory factory = new MockDriverFactory ( ) ; factory . add ( "" , new MockSourceDriver < String > ( "" ) ) ; factory . add ( "" , new MockDrainDriver < String > ( "" ) ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; provider . execute ( factory , script ) ; } @ Test public void execute_simulated ( ) throws IOException { RuntimeContext . set ( RuntimeContext . DEFAULT . mode ( ExecutionMode . SIMULATION ) ) ; MockDriverFactory factory = new MockDriverFactory ( ) ; factory . add ( "" , new MockSourceDriver < String > ( "" ) { @ Override public void prepare ( ) throws IOException { throw new AssertionError ( ) ; } @ Override public boolean next ( ) throws IOException { throw new AssertionError ( ) ; } @ Override public String get ( ) throws IOException { throw new AssertionError ( ) ; } @ Override public void close ( ) throws IOException { return ; } } ) ; factory . add ( "" , new MockDrainDriver < String > ( "" ) { @ Override public void prepare ( ) throws IOException { throw new AssertionError ( ) ; } @ Override public void put ( String object ) throws IOException { throw new AssertionError ( ) ; } @ Override public void close ( ) throws IOException { return ; } } ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; provider . execute ( factory , script ) ; } private DriverScript driver ( String name ) { return new DriverScript ( name , Collections . < String , String > emptyMap ( ) ) ; } } package com . asakusafw . windgate . core . process ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . DriverFactory ; import com . asakusafw . windgate . core . resource . SourceDriver ; public class MockDriverFactory implements DriverFactory { private final Map < String , SourceDriver < ? > > sources = new HashMap < String , SourceDriver < ? > > ( ) ; private final Map < String , DrainDriver < ? > > drains = new HashMap < String , DrainDriver < ? > > ( ) ; public < T , D extends SourceDriver < T > > D add ( String name , D driver ) { sources . put ( name , driver ) ; return driver ; } public < T , D extends DrainDriver < T > > D add ( String name , D driver ) { drains . put ( name , driver ) ; return driver ; } @ SuppressWarnings ( "" ) @ Override public < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException { SourceDriver < ? > driver = sources . remove ( script . getName ( ) ) ; if ( driver == null ) { throw new IOException ( script . getName ( ) ) ; } return ( SourceDriver < T > ) driver ; } @ SuppressWarnings ( "" ) @ Override public < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException { DrainDriver < ? > driver = drains . remove ( script . getName ( ) ) ; if ( driver == null ) { throw new IOException ( script . getName ( ) ) ; } return ( DrainDriver < T > ) driver ; } } package com . asakusafw . windgate . core . process ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . util . Collection ; import java . util . Properties ; import org . junit . Test ; import com . asakusafw . windgate . core . BaseProfile ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . session . SessionProfile ; public class ProcessProfileTest { @ Test public void loadFrom ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ProcessProfile p1 = find ( profiles , "" ) ; assertThat ( p1 . getName ( ) , is ( "" ) ) ; assertThat ( p1 . getProviderClass ( ) , is ( ( Object ) BasicProcessProvider . class ) ) ; assertThat ( p1 . getConfiguration ( ) . size ( ) , is ( ) ) ; } @ Test public void loadFrom_configured ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ProcessProfile p1 = find ( profiles , "" ) ; assertThat ( p1 . getName ( ) , is ( "" ) ) ; assertThat ( p1 . getProviderClass ( ) , is ( ( Object ) BasicProcessProvider . class ) ) ; assertThat ( p1 . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( p1 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( p1 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void loadFrom_multiple ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ProcessProfile p1 = find ( profiles , "" ) ; assertThat ( p1 . getName ( ) , is ( "" ) ) ; assertThat ( p1 . getProviderClass ( ) , is ( ( Object ) BasicProcessProvider . class ) ) ; assertThat ( p1 . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( p1 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; ProcessProfile p2 = find ( profiles , "" ) ; assertThat ( p2 . getName ( ) , is ( "" ) ) ; assertThat ( p2 . getProviderClass ( ) , is ( ( Object ) BasicProcessProvider . class ) ) ; assertThat ( p2 . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( p2 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; ProcessProfile p3 = find ( profiles , "" ) ; assertThat ( p3 . getName ( ) , is ( "" ) ) ; assertThat ( p3 . getProviderClass ( ) , is ( ( Object ) BasicProcessProvider . class ) ) ; assertThat ( p3 . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( p3 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_name ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_provider ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , String . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_missing_provider ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test public void storeTo ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; for ( ProcessProfile profile : profiles ) { profile . storeTo ( restored ) ; } assertThat ( restored , is ( p ) ) ; } @ Test public void storeTo_configured ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; for ( ProcessProfile profile : profiles ) { profile . storeTo ( restored ) ; } assertThat ( restored , is ( p ) ) ; } @ Test public void storeTo_multiple ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; for ( ProcessProfile profile : profiles ) { profile . storeTo ( restored ) ; } assertThat ( restored , is ( p ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void storeTo_conflict_provider ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; restored . setProperty ( ProcessProfile . KEY_PREFIX + "" , "" ) ; for ( ProcessProfile profile : profiles ) { profile . storeTo ( restored ) ; } } @ Test ( expected = IllegalArgumentException . class ) public void storeTo_conflict_configuration ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; restored . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; for ( ProcessProfile profile : profiles ) { profile . storeTo ( restored ) ; } } @ Test public void storeTo_orthogonal ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; restored . setProperty ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; for ( ProcessProfile profile : profiles ) { profile . storeTo ( restored ) ; } restored . remove ( ProcessProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" ) ; assertThat ( restored , is ( p ) ) ; } @ Test public void removeCorrespondingKeys ( ) { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , "" ) ; p . setProperty ( SessionProfile . KEY_PREFIX + "" , "" ) ; ProcessProfile . removeCorrespondingKeys ( p ) ; Properties answer = new Properties ( ) ; answer . setProperty ( SessionProfile . KEY_PREFIX + "" , "" ) ; assertThat ( p , is ( answer ) ) ; } @ Test public void createProvider ( ) throws Exception { Properties p = new Properties ( ) ; p . setProperty ( ProcessProfile . KEY_PREFIX + "" , BasicProcessProvider . class . getName ( ) ) ; Collection < ? extends ProcessProfile > profiles = ProcessProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ProcessProfile r1 = find ( profiles , "" ) ; ProcessProvider provider = r1 . createProvider ( ) ; assertThat ( provider , is ( instanceOf ( BasicProcessProvider . class ) ) ) ; } private ProcessProfile find ( Collection < ? extends ProcessProfile > profiles , String name ) { for ( ProcessProfile profile : profiles ) { if ( profile . getName ( ) . equals ( name ) ) { return profile ; } } throw new AssertionError ( name ) ; } } package com . asakusafw . windgate . core . util ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import org . junit . Test ; public class PropertiesUtilTest { @ Test public void createPrefixMap ( ) { Properties properties = new Properties ( ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; char [ ] array = "" . toCharArray ( ) ; properties . put ( array , "" ) ; properties . put ( "" , array ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; assertThat ( PropertiesUtil . createPrefixMap ( properties , "" ) , is ( answer ) ) ; } @ Test public void removeKeyPrefix ( ) { Properties properties = new Properties ( ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; char [ ] array = "" . toCharArray ( ) ; properties . put ( array , "" ) ; properties . put ( "" , array ) ; Properties answer = new Properties ( ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; answer . put ( array , "" ) ; PropertiesUtil . removeKeyPrefix ( properties , "" ) ; assertThat ( properties , is ( answer ) ) ; } @ Test public void checkAbsentKey ( ) { Properties properties = new Properties ( ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; char [ ] array = "" . toCharArray ( ) ; properties . put ( array , "" ) ; PropertiesUtil . checkAbsentKey ( properties , "" ) ; try { properties . put ( "" , "" ) ; PropertiesUtil . checkAbsentKey ( properties , "" ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } @ Test public void testCheckAbsentKeyPrefix ( ) { Properties properties = new Properties ( ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; properties . put ( "" , "" ) ; char [ ] array = "" . toCharArray ( ) ; properties . put ( array , "" ) ; PropertiesUtil . checkAbsentKeyPrefix ( properties , "" ) ; try { properties . put ( "" , "" ) ; PropertiesUtil . checkAbsentKeyPrefix ( properties , "" ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { properties . remove ( "" ) ; } try { properties . put ( "" , "" ) ; PropertiesUtil . checkAbsentKeyPrefix ( properties , "" ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { properties . remove ( "" ) ; } } } package com . asakusafw . windgate . core . resource ; import java . io . IOException ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ProcessScript ; public class MockResourceMirror extends ResourceMirror { private final ResourceProfile profile ; public MockResourceMirror ( ResourceProfile profile ) { this . profile = profile ; } public MockResourceMirror ( String name ) { this ( MockResourceProvider . createProfile ( name ) ) ; } @ Override public String getName ( ) { return profile . getName ( ) ; } @ Override public void prepare ( GateScript script ) throws IOException { return ; } @ Override public < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException { return new MockSourceDriver < T > ( getName ( ) ) ; } @ Override public < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException { return new MockDrainDriver < T > ( getName ( ) ) ; } @ Override public void close ( ) throws IOException { return ; } } package com . asakusafw . windgate . core . resource ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collections ; import org . junit . Test ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ProcessScript ; public class DriverRepositoryTest { @ Test public void createSource ( ) throws Exception { DriverRepository repo = new DriverRepository ( Arrays . asList ( new MockResourceMirror ( "" ) ) ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; SourceDriver < String > source = repo . createSource ( script ) ; assertThat ( source , is ( instanceOf ( MockSourceDriver . class ) ) ) ; MockSourceDriver < String > mock = ( MockSourceDriver < String > ) source ; assertThat ( mock . name , is ( "" ) ) ; } @ Test ( expected = IOException . class ) public void createSource_missing ( ) throws Exception { DriverRepository repo = new DriverRepository ( Arrays . asList ( new MockResourceMirror ( "" ) ) ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; repo . createSource ( script ) ; } @ Test public void testCreateDrain ( ) throws Exception { DriverRepository repo = new DriverRepository ( Arrays . asList ( new MockResourceMirror ( "" ) ) ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; DrainDriver < String > source = repo . createDrain ( script ) ; assertThat ( source , is ( instanceOf ( MockDrainDriver . class ) ) ) ; MockDrainDriver < String > mock = ( MockDrainDriver < String > ) source ; assertThat ( mock . name , is ( "" ) ) ; } @ Test ( expected = IOException . class ) public void createDrain_missing ( ) throws Exception { DriverRepository repo = new DriverRepository ( Arrays . asList ( new MockResourceMirror ( "" ) ) ) ; ProcessScript < String > script = new ProcessScript < String > ( "" , "" , String . class , driver ( "" ) , driver ( "" ) ) ; repo . createDrain ( script ) ; } private DriverScript driver ( String name ) { assert name != null ; return new DriverScript ( name , Collections . < String , String > emptyMap ( ) ) ; } } package com . asakusafw . windgate . core . resource ; import java . io . IOException ; import java . util . Collections ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProfileContext ; public class MockResourceProvider extends ResourceProvider { ResourceProfile configuredProfile ; public MockResourceProvider ( ) { return ; } public MockResourceProvider ( String name ) { configure ( createProfile ( name ) ) ; } public static ResourceProfile createProfile ( String name ) { assert name != null ; return new ResourceProfile ( name , MockResourceProvider . class , ProfileContext . system ( MockResourceProvider . class . getClassLoader ( ) ) , Collections . < String , String > emptyMap ( ) ) ; } @ Override protected final void configure ( ResourceProfile profile ) { this . configuredProfile = profile ; } @ Override public ResourceMirror create ( String sessionId , ParameterList arguments ) throws IOException { return new MockResourceMirror ( configuredProfile ) ; } } package com . asakusafw . windgate . core . resource ; import java . io . IOException ; import java . util . Iterator ; public class MockSourceDriver < T > implements SourceDriver < T > { final String name ; private Iterable < ? extends T > source ; private Iterator < ? extends T > iterator ; private boolean canGet ; private T nextResult ; public MockSourceDriver ( String name ) { this . name = name ; this . canGet = false ; this . nextResult = null ; } public void setIterable ( Iterable < ? extends T > iterable ) { this . source = iterable ; } @ Override public void prepare ( ) throws IOException { if ( source == null ) { throw new IOException ( "" ) ; } this . iterator = source . iterator ( ) ; this . canGet = false ; this . nextResult = null ; } @ Override public boolean next ( ) throws IOException { if ( iterator == null ) { throw new IOException ( ) ; } if ( iterator . hasNext ( ) ) { nextResult = iterator . next ( ) ; canGet = true ; } else { nextResult = null ; canGet = false ; } return canGet ; } @ Override public T get ( ) throws IOException { if ( canGet ) { return nextResult ; } throw new IllegalStateException ( ) ; } @ Override public void close ( ) throws IOException { while ( next ( ) ) { } this . iterator = null ; } } package com . asakusafw . windgate . core . resource ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; public class MockDrainDriver < T > implements DrainDriver < T > { final String name ; final List < T > results = new ArrayList < T > ( ) ; public MockDrainDriver ( String name ) { this . name = name ; } public List < T > getResults ( ) { return results ; } @ Override public void prepare ( ) throws IOException { results . clear ( ) ; } @ Override public void put ( T object ) throws IOException { results . add ( object ) ; } @ Override public void close ( ) throws IOException { return ; } } package com . asakusafw . windgate . core . resource ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . util . Collection ; import java . util . Collections ; import java . util . Properties ; import org . junit . Test ; import com . asakusafw . windgate . core . BaseProfile ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . session . SessionProfile ; public class ResourceProfileTest { @ Test public void loadFrom ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ResourceProfile r1 = find ( profiles , "" ) ; assertThat ( r1 . getName ( ) , is ( "" ) ) ; assertThat ( r1 . getProviderClass ( ) , is ( ( Object ) MockResourceProvider . class ) ) ; assertThat ( r1 . getConfiguration ( ) . size ( ) , is ( ) ) ; } @ Test public void loadFrom_configured ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ResourceProfile r1 = find ( profiles , "" ) ; assertThat ( r1 . getName ( ) , is ( "" ) ) ; assertThat ( r1 . getProviderClass ( ) , is ( ( Object ) MockResourceProvider . class ) ) ; assertThat ( r1 . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( r1 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( r1 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void loadFrom_multiple ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ResourceProfile r1 = find ( profiles , "" ) ; assertThat ( r1 . getName ( ) , is ( "" ) ) ; assertThat ( r1 . getProviderClass ( ) , is ( ( Object ) MockResourceProvider . class ) ) ; assertThat ( r1 . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( r1 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; ResourceProfile r2 = find ( profiles , "" ) ; assertThat ( r2 . getName ( ) , is ( "" ) ) ; assertThat ( r2 . getProviderClass ( ) , is ( ( Object ) MockResourceProvider . class ) ) ; assertThat ( r2 . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( r2 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; ResourceProfile r3 = find ( profiles , "" ) ; assertThat ( r3 . getName ( ) , is ( "" ) ) ; assertThat ( r3 . getProviderClass ( ) , is ( ( Object ) MockResourceProvider . class ) ) ; assertThat ( r3 . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( r3 . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_name ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_provider ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , "" ) ; ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_missing_provider ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; } @ Test public void storeTo ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; for ( ResourceProfile profile : profiles ) { profile . storeTo ( restored ) ; } assertThat ( restored , is ( p ) ) ; } @ Test public void storeTo_configured ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; for ( ResourceProfile profile : profiles ) { profile . storeTo ( restored ) ; } assertThat ( restored , is ( p ) ) ; } @ Test public void storeTo_multiple ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; for ( ResourceProfile profile : profiles ) { profile . storeTo ( restored ) ; } assertThat ( restored , is ( p ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void storeTo_conflict_provider ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; restored . setProperty ( ResourceProfile . KEY_PREFIX + "" , "" ) ; for ( ResourceProfile profile : profiles ) { profile . storeTo ( restored ) ; } } @ Test ( expected = IllegalArgumentException . class ) public void storeTo_conflict_configuration ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; restored . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; for ( ResourceProfile profile : profiles ) { profile . storeTo ( restored ) ; } } @ Test public void storeTo_orthogonal ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; Properties restored = new Properties ( ) ; restored . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; for ( ResourceProfile profile : profiles ) { profile . storeTo ( restored ) ; } restored . remove ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" ) ; assertThat ( restored , is ( p ) ) ; } @ Test public void removeCorrespondingKeys ( ) { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , "" ) ; p . setProperty ( SessionProfile . KEY_PREFIX + "" , "" ) ; ResourceProfile . removeCorrespondingKeys ( p ) ; Properties answer = new Properties ( ) ; answer . setProperty ( SessionProfile . KEY_PREFIX + "" , "" ) ; assertThat ( p , is ( answer ) ) ; } @ Test public void createProvider ( ) throws Exception { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ResourceProfile r1 = find ( profiles , "" ) ; ResourceProvider provider = r1 . createProvider ( ) ; assertThat ( provider , is ( instanceOf ( MockResourceProvider . class ) ) ) ; MockResourceProvider mock = ( MockResourceProvider ) provider ; assertThat ( mock . configuredProfile . getName ( ) , is ( "" ) ) ; assertThat ( mock . configuredProfile . getConfiguration ( ) . size ( ) , is ( ) ) ; } @ Test public void createProvider_configured ( ) throws Exception { Properties p = new Properties ( ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" , MockResourceProvider . class . getName ( ) ) ; p . setProperty ( ResourceProfile . KEY_PREFIX + "" + BaseProfile . QUALIFIER + "" , "" ) ; Collection < ? extends ResourceProfile > profiles = ResourceProfile . loadFrom ( p , ProfileContext . system ( getClass ( ) . getClassLoader ( ) ) ) ; assertThat ( profiles . size ( ) , is ( ) ) ; ResourceProfile r1 = find ( profiles , "" ) ; ResourceProvider provider = r1 . createProvider ( ) ; assertThat ( provider , is ( instanceOf ( MockResourceProvider . class ) ) ) ; MockResourceProvider mock = ( MockResourceProvider ) provider ; assertThat ( mock . configuredProfile . getName ( ) , is ( "" ) ) ; assertThat ( mock . configuredProfile . getConfiguration ( ) , is ( Collections . singletonMap ( "" , "" ) ) ) ; } private ResourceProfile find ( Collection < ? extends ResourceProfile > profiles , String name ) { for ( ResourceProfile profile : profiles ) { if ( profile . getName ( ) . equals ( name ) ) { return profile ; } } throw new AssertionError ( name ) ; } } package com . asakusafw . windgate . core ; import static com . asakusafw . windgate . core . DriverScript . * ; import static com . asakusafw . windgate . core . ProcessScript . * ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . util . Properties ; import org . junit . Test ; public class GateScriptTest { @ Test public void loadFrom ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; GateScript script = GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; assertThat ( script . getProcesses ( ) . size ( ) , is ( ) ) ; ProcessScript < ? > test = find ( script , "" ) ; assertThat ( test . getName ( ) , is ( "" ) ) ; assertThat ( test . getProcessType ( ) , is ( "" ) ) ; assertThat ( test . getDataClass ( ) , is ( ( Object ) String . class ) ) ; assertThat ( test . getSourceScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test . getSourceScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( test . getDrainScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test . getDrainScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; } @ Test public void loadFrom_sourceConf ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE , "" ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE , "" ) , "" ) ; GateScript script = GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; assertThat ( script . getProcesses ( ) . size ( ) , is ( ) ) ; ProcessScript < ? > test = find ( script , "" ) ; assertThat ( test . getName ( ) , is ( "" ) ) ; assertThat ( test . getProcessType ( ) , is ( "" ) ) ; assertThat ( test . getDataClass ( ) , is ( ( Object ) String . class ) ) ; assertThat ( test . getSourceScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test . getSourceScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( test . getSourceScript ( ) . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( test . getSourceScript ( ) . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( test . getDrainScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test . getDrainScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; } @ Test public void loadFrom_drainConf ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN , "" ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN , "" ) , "" ) ; GateScript script = GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; assertThat ( script . getProcesses ( ) . size ( ) , is ( ) ) ; ProcessScript < ? > test = find ( script , "" ) ; assertThat ( test . getName ( ) , is ( "" ) ) ; assertThat ( test . getProcessType ( ) , is ( "" ) ) ; assertThat ( test . getDataClass ( ) , is ( ( Object ) String . class ) ) ; assertThat ( test . getSourceScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test . getSourceScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( test . getDrainScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test . getDrainScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( test . getDrainScript ( ) . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; assertThat ( test . getDrainScript ( ) . getConfiguration ( ) . get ( "" ) , is ( "" ) ) ; } @ Test public void loadFrom_multiple ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , Integer . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , Long . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; GateScript script = GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; assertThat ( script . getProcesses ( ) . size ( ) , is ( ) ) ; ProcessScript < ? > test1 = find ( script , "" ) ; assertThat ( test1 . getName ( ) , is ( "" ) ) ; assertThat ( test1 . getProcessType ( ) , is ( "" ) ) ; assertThat ( test1 . getDataClass ( ) , is ( ( Object ) String . class ) ) ; assertThat ( test1 . getSourceScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test1 . getSourceScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( test1 . getDrainScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test1 . getDrainScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; ProcessScript < ? > test2 = find ( script , "" ) ; assertThat ( test2 . getName ( ) , is ( "" ) ) ; assertThat ( test2 . getProcessType ( ) , is ( "" ) ) ; assertThat ( test2 . getDataClass ( ) , is ( ( Object ) Integer . class ) ) ; assertThat ( test2 . getSourceScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test2 . getSourceScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( test2 . getDrainScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test2 . getDrainScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; ProcessScript < ? > test3 = find ( script , "" ) ; assertThat ( test3 . getName ( ) , is ( "" ) ) ; assertThat ( test3 . getProcessType ( ) , is ( "" ) ) ; assertThat ( test3 . getDataClass ( ) , is ( ( Object ) Long . class ) ) ; assertThat ( test3 . getSourceScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test3 . getSourceScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; assertThat ( test3 . getDrainScript ( ) . getResourceName ( ) , is ( "" ) ) ; assertThat ( test3 . getDrainScript ( ) . getConfiguration ( ) . size ( ) , is ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_missing_processtype ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_missing_dataclass ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_missing_source ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_missing_drain ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_dataclass ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , "" ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_prefix ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , "" ) , "" ) ; GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void loadFrom_invalid_key ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" ) , "" ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; } @ Test public void storeTo ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE , "" ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN , "" ) , "" ) ; GateScript script = GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; Properties target = new Properties ( ) ; script . storeTo ( target ) ; assertThat ( target , is ( p ) ) ; } @ Test public void storeTo_multiple ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , Integer . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , Long . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; GateScript script = GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; Properties target = new Properties ( ) ; script . storeTo ( target ) ; assertThat ( target , is ( p ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void storeTo_conflict ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE , "" ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN , "" ) , "" ) ; GateScript script = GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; Properties target = new Properties ( ) ; target . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; script . storeTo ( target ) ; } @ Test public void storeTo_orthogonal ( ) { Properties p = new Properties ( ) ; p . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; p . setProperty ( k ( "" , KEY_PROCESS_TYPE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE ) , "" ) ; p . setProperty ( k ( "" , PREFIX_SOURCE , "" ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN ) , "" ) ; p . setProperty ( k ( "" , PREFIX_DRAIN , "" ) , "" ) ; GateScript script = GateScript . loadFrom ( "" , p , getClass ( ) . getClassLoader ( ) ) ; Properties target = new Properties ( ) ; target . setProperty ( k ( "" , KEY_DATA_CLASS ) , String . class . getName ( ) ) ; script . storeTo ( target ) ; } private String k ( String first , String ... rest ) { StringBuilder buf = new StringBuilder ( first ) ; for ( String s : rest ) { buf . append ( GateScript . QUALIFIER ) ; buf . append ( s ) ; } return buf . toString ( ) ; } private ProcessScript < ? > find ( GateScript script , String name ) { for ( ProcessScript < ? > proc : script . getProcesses ( ) ) { if ( proc . getName ( ) . equals ( name ) ) { return proc ; } } throw new AssertionError ( name ) ; } } package com . asakusafw . windgate . file . resource ; import java . io . IOException ; import java . io . InputStream ; import java . io . ObjectInputStream ; import java . io . ObjectStreamClass ; import java . lang . reflect . Array ; public class LoadingObjectInputStream extends ObjectInputStream { private final ClassLoader loader ; public LoadingObjectInputStream ( InputStream in , ClassLoader loader ) throws IOException { super ( in ) ; if ( loader == null ) { this . loader = ClassLoader . getSystemClassLoader ( ) ; } else { this . loader = loader ; } } @ Override protected Class < ? > resolveClass ( ObjectStreamClass desc ) throws IOException , ClassNotFoundException { String name = desc . getName ( ) ; if ( name . startsWith ( "" ) ) { return resolveClassDesc ( desc ) ; } try { Class < ? > loaded = loader . loadClass ( name ) ; return loaded ; } catch ( ClassNotFoundException e ) { return super . resolveClass ( desc ) ; } } private Class < ? > resolveClassDesc ( ObjectStreamClass desc ) throws IOException , ClassNotFoundException { assert desc != null ; String name = desc . getName ( ) ; int dimensions = ; for ( int i = , n = name . length ( ) ; i < n ; i ++ ) { if ( name . charAt ( i ) == '' ) { dimensions ++ ; } else { break ; } } if ( name . length ( ) == dimensions ) { return super . resolveClass ( desc ) ; } if ( name . charAt ( dimensions ) != '' || name . charAt ( name . length ( ) - ) != '' ) { return super . resolveClass ( desc ) ; } String internalName = name . substring ( dimensions + , name . length ( ) - ) ; Class < ? > loaded = loader . loadClass ( internalName . replace ( '' , '' ) ) ; for ( int i = ; i < dimensions ; i ++ ) { loaded = Array . newInstance ( loaded , ) . getClass ( ) ; } return loaded ; } } package com . asakusafw . windgate . file . resource ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . ObjectOutputStream ; import java . text . MessageFormat ; import com . asakusafw . windgate . core . resource . DrainDriver ; class FileDrainDriver < T > implements DrainDriver < T > { private final File file ; private ObjectOutputStream output ; public FileDrainDriver ( Class < T > type , File file ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( file == null ) { throw new IllegalArgumentException ( "" ) ; } this . file = file ; } @ Override public void prepare ( ) throws IOException { if ( file . exists ( ) && file . delete ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , file ) ) ; } boolean green = false ; FileOutputStream out = new FileOutputStream ( file ) ; try { this . output = new ObjectOutputStream ( out ) ; green = true ; } finally { if ( green == false ) { out . close ( ) ; } } } @ Override public void put ( T object ) throws IOException { output . writeObject ( object ) ; } @ Override public void close ( ) throws IOException { if ( output != null ) { output . close ( ) ; } this . output = null ; } } package com . asakusafw . windgate . file . resource ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . SourceDriver ; public class FileResourceManipulator extends ResourceManipulator { private final String name ; public FileResourceManipulator ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } @ Override public String getName ( ) { return name ; } @ Override public void cleanupSource ( ProcessScript < ? > script ) throws IOException { cleanup ( script , DriverScript . Kind . SOURCE ) ; } @ Override public void cleanupDrain ( ProcessScript < ? > script ) throws IOException { cleanup ( script , DriverScript . Kind . DRAIN ) ; } private void cleanup ( ProcessScript < ? > script , DriverScript . Kind kind ) throws IOException { assert script != null ; assert kind != null ; File file = FileResourceMirror . getPath ( script , kind ) ; if ( file . exists ( ) && file . delete ( ) == false ) { throw new IOException ( MessageFormat . format ( "" , getName ( ) , script . getName ( ) , file . getPath ( ) , kind . prefix ) ) ; } } @ Override public < T > SourceDriver < T > createSourceForSource ( ProcessScript < T > script ) throws IOException { File file = FileResourceMirror . getPath ( script , DriverScript . Kind . SOURCE ) ; return new FileSourceDriver < T > ( script . getDataClass ( ) , file ) ; } @ Override public < T > DrainDriver < T > createDrainForSource ( ProcessScript < T > script ) throws IOException { File file = FileResourceMirror . getPath ( script , DriverScript . Kind . SOURCE ) ; return new FileDrainDriver < T > ( script . getDataClass ( ) , file ) ; } @ Override public < T > SourceDriver < T > createSourceForDrain ( ProcessScript < T > script ) throws IOException { File file = FileResourceMirror . getPath ( script , DriverScript . Kind . DRAIN ) ; return new FileSourceDriver < T > ( script . getDataClass ( ) , file ) ; } @ Override public < T > DrainDriver < T > createDrainForDrain ( ProcessScript < T > script ) throws IOException { File file = FileResourceMirror . getPath ( script , DriverScript . Kind . DRAIN ) ; return new FileDrainDriver < T > ( script . getDataClass ( ) , file ) ; } } package com . asakusafw . windgate . file . resource ; import java . io . IOException ; public interface Preparable { void prepare ( ) throws IOException ; } package com . asakusafw . windgate . file . resource ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . windgate . core . DriverScript ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . SourceDriver ; import com . asakusafw . windgate . core . vocabulary . FileProcess ; public class FileResourceMirror extends ResourceMirror { private final String name ; public FileResourceMirror ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } @ Override public String getName ( ) { return name ; } @ Override public void prepare ( GateScript script ) throws IOException { return ; } @ Override public < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException { File file = getPath ( script , DriverScript . Kind . SOURCE ) ; return new FileSourceDriver < T > ( script . getDataClass ( ) , file ) ; } @ Override public < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException { File file = getPath ( script , DriverScript . Kind . DRAIN ) ; return new FileDrainDriver < T > ( script . getDataClass ( ) , file ) ; } @ Override public void close ( ) throws IOException { return ; } static File getPath ( ProcessScript < ? > script , DriverScript . Kind kind ) throws IOException { assert script != null ; assert kind != null ; String path = script . getDriverScript ( kind ) . getConfiguration ( ) . get ( FileProcess . FILE . key ( ) ) ; if ( path == null ) { throw new IOException ( MessageFormat . format ( "" , FileProcess . FILE . key ( ) , script . getName ( ) , kind . prefix ) ) ; } File file = new File ( path ) ; return file ; } } package com . asakusafw . windgate . file . resource ; import java . io . IOException ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . resource . ResourceManipulator ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . resource . ResourceProvider ; public class FileResourceProvider extends ResourceProvider { private volatile String name ; @ Override protected void configure ( ResourceProfile profile ) throws IOException { this . name = profile . getName ( ) ; } @ Override public ResourceMirror create ( String sessionId , ParameterList arguments ) throws IOException { return new FileResourceMirror ( name ) ; } @ Override public ResourceManipulator createManipulator ( ParameterList arguments ) throws IOException { return new FileResourceManipulator ( name ) ; } } package com . asakusafw . windgate . file . resource ; package com . asakusafw . windgate . file . resource ; import java . io . EOFException ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . OptionalDataException ; import com . asakusafw . windgate . core . resource . SourceDriver ; class FileSourceDriver < T > implements SourceDriver < T > { private final Class < T > type ; private final File file ; private ObjectInputStream input ; private boolean canGet ; private T next ; public FileSourceDriver ( Class < T > type , File file ) { if ( type == null ) { throw new IllegalArgumentException ( "" ) ; } if ( file == null ) { throw new IllegalArgumentException ( "" ) ; } this . type = type ; this . file = file ; } @ Override public void prepare ( ) throws IOException { boolean green = false ; FileInputStream in = new FileInputStream ( file ) ; try { this . input = new LoadingObjectInputStream ( in , type . getClassLoader ( ) ) ; green = true ; } finally { if ( green == false ) { in . close ( ) ; } } this . next = null ; this . canGet = false ; } @ Override public boolean next ( ) throws IOException { try { Object object = input . readObject ( ) ; next = type . cast ( object ) ; canGet = true ; return true ; } catch ( ClassNotFoundException e ) { throw new IOException ( e ) ; } catch ( EOFException e ) { next = null ; canGet = true ; return false ; } catch ( OptionalDataException e ) { if ( e . eof ) { next = null ; canGet = true ; return false ; } throw e ; } } @ Override public T get ( ) throws IOException { if ( canGet ) { return next ; } throw new IOException ( ) ; } @ Override public void close ( ) throws IOException { if ( input != null ) { input . close ( ) ; } input = null ; } } package com . asakusafw . windgate . file . session ; import java . io . File ; import java . io . FileFilter ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . nio . channels . FileLock ; import java . nio . channels . OverlappingFileLockException ; import java . nio . charset . Charset ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . session . SessionException ; import com . asakusafw . windgate . core . session . SessionException . Reason ; import com . asakusafw . windgate . core . session . SessionMirror ; import com . asakusafw . windgate . core . session . SessionProfile ; import com . asakusafw . windgate . core . session . SessionProvider ; public class FileSessionProvider extends SessionProvider { static final FileSessionLogger WGLOG = new FileSessionLogger ( FileSessionProvider . class ) ; static final Logger LOG = LoggerFactory . getLogger ( FileSessionProvider . class ) ; private static final String VALID_STRING = "" ; private static final String DISPOSED_STRING = "" ; private static final byte [ ] VALID = String . format ( "" , VALID_STRING ) . getBytes ( Charset . forName ( "" ) ) ; private static final byte [ ] DISPOSED = String . format ( "" , DISPOSED_STRING ) . getBytes ( Charset . forName ( "" ) ) ; public static final String KEY_DIRECTORY = "" ; private volatile File directory ; @ Override protected void configure ( SessionProfile profile ) throws IOException { LOG . debug ( "" , profile . getProviderClass ( ) . getName ( ) ) ; directory = prepareDirectory ( profile ) ; LOG . debug ( "" , directory ) ; } File getDirectory ( ) { return directory ; } private File prepareDirectory ( SessionProfile profile ) throws IOException { assert profile != null ; String rawPath = profile . getConfiguration ( ) . get ( KEY_DIRECTORY ) ; if ( rawPath == null || rawPath . isEmpty ( ) ) { WGLOG . error ( "" , KEY_DIRECTORY , rawPath ) ; throw new IOException ( MessageFormat . format ( "" , KEY_DIRECTORY ) ) ; } String path ; try { LOG . debug ( "" , rawPath ) ; path = profile . getContext ( ) . getContextParameters ( ) . replace ( rawPath , true ) ; } catch ( IllegalArgumentException e ) { WGLOG . error ( e , "" , KEY_DIRECTORY , rawPath ) ; throw new IOException ( MessageFormat . format ( "" , KEY_DIRECTORY , rawPath ) , e ) ; } File dir = new File ( path ) ; if ( dir . isDirectory ( ) == false && dir . mkdirs ( ) == false ) { WGLOG . error ( "" , dir . getAbsolutePath ( ) ) ; throw new IOException ( MessageFormat . format ( "" , dir . getAbsolutePath ( ) ) ) ; } return dir ; } @ Override public List < String > getCreatedIds ( ) throws IOException { LOG . debug ( "" , directory ) ; File [ ] files = directory . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { if ( pathname . isFile ( ) == false ) { return false ; } if ( pathname . getName ( ) . startsWith ( "" ) ) { return false ; } return true ; } } ) ; List < String > results = new ArrayList < String > ( ) ; for ( File file : files ) { results . add ( fileToId ( file ) ) ; } return results ; } @ Override public SessionMirror create ( String id ) throws SessionException , IOException { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , id ) ; return attach ( id , true , false ) ; } @ Override public SessionMirror open ( String id ) throws SessionException , IOException { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , id ) ; return attach ( id , false , false ) ; } @ Override public void delete ( String id ) throws IOException { assert id != null ; LOG . debug ( "" , id ) ; SessionMirror session = attach ( id , false , true ) ; session . abort ( ) ; } private SessionMirror attach ( String id , boolean create , boolean force ) throws IOException { assert id != null ; boolean completed = false ; boolean delete = false ; File path = idToFile ( id ) ; RandomAccessFile file = null ; FileLock lock = null ; try { LOG . debug ( "" , path ) ; file = new RandomAccessFile ( path , "" ) ; lock = acquireLock ( id , path , file ) ; State state = getSessionState ( id , path , file ) ; switch ( state ) { case INIT : if ( create == false ) { delete = true ; throw new SessionException ( id , Reason . NOT_EXIST ) ; } else { createSession ( path , file ) ; } break ; case CREATED : if ( create ) { throw new SessionException ( id , Reason . ALREADY_EXIST ) ; } break ; case INVALID : if ( force == false ) { WGLOG . error ( "" , id , path ) ; throw new SessionException ( id , Reason . BROKEN ) ; } break ; default : throw new AssertionError ( MessageFormat . format ( "" , id , path , state ) ) ; } completed = true ; return new FileSessionMirror ( id , path , file , lock ) ; } catch ( SessionException e ) { throw e ; } catch ( IOException e ) { WGLOG . error ( e , "" , id , path ) ; throw e ; } finally { if ( completed == false ) { if ( delete ) { try { invalidate ( path , file ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , id , path ) ; } } if ( lock != null ) { try { lock . release ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , id , path ) ; } } if ( file != null ) { try { file . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , id , path ) ; } } if ( delete ) { if ( path . delete ( ) == false ) { WGLOG . warn ( "" , id , path ) ; } } } } } private FileLock acquireLock ( String id , File path , RandomAccessFile file ) throws IOException { assert id != null ; assert path != null ; assert file != null ; LOG . debug ( "" , id ) ; try { FileLock lock = file . getChannel ( ) . tryLock ( ) ; if ( lock != null ) { return lock ; } LOG . debug ( "" , id ) ; } catch ( OverlappingFileLockException e ) { LOG . debug ( MessageFormat . format ( "" , id ) , e ) ; } throw new SessionException ( id , Reason . ACQUIRED ) ; } private void createSession ( File path , RandomAccessFile file ) throws IOException { assert path != null ; assert file != null ; assert file . getFilePointer ( ) == ; LOG . debug ( "" , path ) ; file . write ( VALID ) ; file . getFD ( ) . sync ( ) ; } private State getSessionState ( String id , File path , RandomAccessFile file ) throws IOException { assert id != null ; assert path != null ; assert file != null ; file . seek ( ) ; LOG . debug ( "" , path ) ; byte [ ] buf = new byte [ VALID . length ] ; int length = file . read ( buf ) ; file . seek ( file . length ( ) ) ; if ( length <= ) { return State . INIT ; } else if ( Arrays . equals ( buf , VALID ) ) { return State . CREATED ; } return State . INVALID ; } static void invalidate ( File path , RandomAccessFile file ) throws IOException { assert path != null ; assert file != null ; LOG . debug ( "" , path ) ; file . seek ( ) ; file . write ( DISPOSED ) ; } private File idToFile ( String id ) { assert id != null ; return new File ( directory , id ) ; } private String fileToId ( File file ) { assert file != null ; return file . getName ( ) ; } private enum State { INIT , CREATED , INVALID , } } package com . asakusafw . windgate . file . session ; package com . asakusafw . windgate . file . session ; import java . io . File ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . nio . channels . FileLock ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . session . SessionMirror ; class FileSessionMirror extends SessionMirror { static final FileSessionLogger WGLOG = new FileSessionLogger ( FileSessionMirror . class ) ; static final Logger LOG = LoggerFactory . getLogger ( FileSessionMirror . class ) ; private final String id ; private final File path ; private final RandomAccessFile file ; private final FileLock lock ; private volatile boolean closed ; FileSessionMirror ( String id , File path , RandomAccessFile file , FileLock lock ) { assert id != null ; assert path != null ; assert file != null ; assert lock != null ; this . id = id ; this . path = path ; this . file = file ; this . lock = lock ; } @ Override public String getId ( ) { return id ; } @ Override public void complete ( ) throws IOException { LOG . debug ( "" , id ) ; delete ( ) ; } @ Override public void abort ( ) throws IOException { LOG . debug ( "" , id ) ; delete ( ) ; } private void delete ( ) throws IOException { try { FileSessionProvider . invalidate ( path , file ) ; } catch ( IOException e ) { WGLOG . error ( e , "" , id , path ) ; throw e ; } close ( ) ; LOG . debug ( "" , path ) ; if ( path . delete ( ) == false ) { WGLOG . error ( "" , id , path ) ; throw new IOException ( MessageFormat . format ( "" , id , path ) ) ; } } @ Override public synchronized void close ( ) { if ( closed == false ) { LOG . debug ( "" , path ) ; try { lock . release ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , id , path ) ; } try { file . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , id , path ) ; } } closed = true ; } } package com . asakusafw . windgate . file . session ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . windgate . core . WindGateLogger ; public class FileSessionLogger extends WindGateLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public FileSessionLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . windgate . core . vocabulary ; public enum FileProcess implements ConfigurationItem { FILE ( "" , "" ) , ; private final String key ; private final String description ; private FileProcess ( String key , String description ) { assert key != null ; assert description != null ; this . key = key ; this . description = description ; } @ Override public final String key ( ) { return key ; } @ Override public String description ( ) { return description ; } } package com . asakusafw . windgate . core . vocabulary ; import java . io . Flushable ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; public interface DataModelStreamSupport < T > { Class < T > getSupportedType ( ) ; DataModelReader < T > createReader ( String path , InputStream stream ) throws IOException ; DataModelWriter < T > createWriter ( String path , OutputStream stream ) throws IOException ; public interface DataModelReader < T > { boolean readTo ( T object ) throws IOException ; } public interface DataModelWriter < T > extends Flushable { void write ( T object ) throws IOException ; } } package com . asakusafw . windgate . core . vocabulary ; package com . asakusafw . windgate . core . vocabulary ; public enum StreamProcess implements ConfigurationItem { STREAM_SUPPORT ( "" , "" ) , ; private final String key ; private final String description ; private StreamProcess ( String key , String description ) { assert key != null ; assert description != null ; this . key = key ; this . description = description ; } @ Override public final String key ( ) { return key ; } @ Override public String description ( ) { return description ; } } package com . asakusafw . windgate . core . vocabulary ; public interface ConfigurationItem { String key ( ) ; String description ( ) ; } package com . asakusafw . windgate . core . vocabulary ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . List ; public interface DataModelJdbcSupport < T > { Class < T > getSupportedType ( ) ; boolean isSupported ( List < String > columnNames ) ; DataModelResultSet < T > createResultSetSupport ( ResultSet resultSet , List < String > columnNames ) ; DataModelPreparedStatement < T > createPreparedStatementSupport ( PreparedStatement statement , List < String > columnNames ) ; public interface DataModelResultSet < T > { boolean next ( T object ) throws SQLException ; } public interface DataModelPreparedStatement < T > { void setParameters ( T object ) throws SQLException ; } } package com . asakusafw . windgate . core . vocabulary ; public enum JdbcProcess implements ConfigurationItem { JDBC_SUPPORT ( "" , "" ) , TABLE ( "" , "" ) , COLUMNS ( "" , "" ) , CONDITION ( "" , "" ) , OPERATION ( "" , "" ) , ; private final String key ; private final String description ; private JdbcProcess ( String key , String description ) { assert key != null ; assert description != null ; this . key = key ; this . description = description ; } @ Override public final String key ( ) { return key ; } @ Override public String description ( ) { return description ; } public enum OperationKind { INSERT , INSERT_AFTER_TRUNCATE , ; public String value ( ) { return name ( ) . toLowerCase ( ) ; } public static OperationKind find ( String value ) { if ( value == null ) { throw new IllegalArgumentException ( "" ) ; } try { return OperationKind . valueOf ( value . toUpperCase ( ) ) ; } catch ( IllegalArgumentException e ) { return null ; } } } } package com . asakusafw . windgate . core ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . resource . ResourceProvider ; import com . asakusafw . windgate . core . session . SessionException ; import com . asakusafw . windgate . core . session . SessionException . Reason ; import com . asakusafw . windgate . core . session . SessionMirror ; import com . asakusafw . windgate . core . session . SessionProfile ; import com . asakusafw . windgate . core . session . SessionProvider ; @ SimulationSupport public class AbortTask { static final WindGateLogger WGLOG = new WindGateCoreLogger ( AbortTask . class ) ; static final Logger LOG = LoggerFactory . getLogger ( AbortTask . class ) ; private final GateProfile profile ; private final String sessionId ; private final SessionProvider sessionProvider ; private final Map < String , ResourceProvider > resourceProviders ; public AbortTask ( GateProfile profile , String sessionId ) throws IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . sessionId = sessionId ; this . sessionProvider = loadSessionProvider ( profile . getSession ( ) ) ; this . resourceProviders = loadResourceProviders ( profile . getResources ( ) ) ; } private SessionProvider loadSessionProvider ( SessionProfile session ) throws IOException { assert session != null ; LOG . debug ( "" , session . getProviderClass ( ) . getName ( ) ) ; SessionProvider result = session . createProvider ( ) ; return result ; } private Map < String , ResourceProvider > loadResourceProviders ( List < ResourceProfile > resources ) throws IOException { assert resources != null ; Map < String , ResourceProvider > results = new TreeMap < String , ResourceProvider > ( ) ; for ( ResourceProfile resourceProfile : resources ) { LOG . debug ( "" , resourceProfile . getName ( ) , resourceProfile . getProviderClass ( ) . getName ( ) ) ; ResourceProvider provider = resourceProfile . createProvider ( ) ; results . put ( resourceProfile . getName ( ) , provider ) ; } return results ; } public void execute ( ) throws IOException , InterruptedException { WGLOG . info ( "" , sessionId , profile . getName ( ) ) ; long start = System . currentTimeMillis ( ) ; try { if ( sessionId != null ) { doAbortSingle ( sessionId ) ; } else { int failureCount = ; List < String > sessionIds ; if ( RuntimeContext . get ( ) . canExecute ( sessionProvider ) ) { sessionIds = sessionProvider . getCreatedIds ( ) ; } else { sessionIds = Collections . emptyList ( ) ; } for ( String sid : sessionIds ) { try { doAbortSingle ( sid ) ; } catch ( IOException e ) { failureCount ++ ; WGLOG . warn ( e , "" , sid , profile . getName ( ) ) ; } } if ( failureCount > ) { throw new IOException ( "" ) ; } } WGLOG . info ( "" , sessionId , profile . getName ( ) ) ; } finally { long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , sessionId , profile . getName ( ) , end - start ) ; } } private boolean doAbortSingle ( String targetSessionId ) throws IOException { assert targetSessionId != null ; SessionMirror session ; try { WGLOG . info ( "" , targetSessionId , profile . getName ( ) ) ; if ( RuntimeContext . get ( ) . canExecute ( sessionProvider ) ) { session = sessionProvider . open ( targetSessionId ) ; } else { session = new SessionMirror . Null ( targetSessionId ) ; } } catch ( SessionException e ) { if ( e . getReason ( ) == Reason . NOT_EXIST ) { WGLOG . info ( "" , targetSessionId , profile . getName ( ) ) ; return false ; } throw e ; } try { WGLOG . info ( "" , targetSessionId , profile . getName ( ) ) ; int failureCount = ; for ( Map . Entry < String , ResourceProvider > entry : resourceProviders . entrySet ( ) ) { String name = entry . getKey ( ) ; ResourceProvider provider = entry . getValue ( ) ; LOG . debug ( "" , name , targetSessionId ) ; try { if ( RuntimeContext . get ( ) . isSimulation ( ) == false ) { provider . abort ( session . getId ( ) ) ; } } catch ( IOException e ) { failureCount ++ ; WGLOG . warn ( e , "" , targetSessionId , profile . getName ( ) , name ) ; } } if ( failureCount > ) { throw new IOException ( MessageFormat . format ( "" , targetSessionId ) ) ; } WGLOG . info ( "" , targetSessionId , profile . getName ( ) ) ; session . abort ( ) ; return true ; } finally { try { session . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , targetSessionId , profile . getName ( ) ) ; } } } } package com . asakusafw . windgate . core ; package com . asakusafw . windgate . core . process ; package com . asakusafw . windgate . core . process ; import java . io . IOException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateCoreLogger ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . resource . DrainDriver ; import com . asakusafw . windgate . core . resource . DriverFactory ; import com . asakusafw . windgate . core . resource . SourceDriver ; @ SimulationSupport public class BasicProcessProvider extends ProcessProvider { static final WindGateLogger WGLOG = new WindGateCoreLogger ( BasicProcessProvider . class ) ; static final Logger LOG = LoggerFactory . getLogger ( BasicProcessProvider . class ) ; @ Override protected void configure ( ProcessProfile profile ) { return ; } @ Override public < T > void execute ( DriverFactory drivers , ProcessScript < T > script ) throws IOException { WGLOG . info ( "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) ) ; long start = System . currentTimeMillis ( ) ; long count = ; try { IOException exception = null ; SourceDriver < T > source = null ; DrainDriver < T > drain = null ; try { LOG . debug ( "" , script . getSourceScript ( ) . getResourceName ( ) , script . getName ( ) ) ; source = drivers . createSource ( script ) ; LOG . debug ( "" , script . getDrainScript ( ) . getResourceName ( ) , script . getName ( ) ) ; drain = drivers . createDrain ( script ) ; performPrepare ( script , source , drain ) ; count = performTransfer ( script , source , drain ) ; } catch ( IOException e ) { exception = e ; WGLOG . error ( e , "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) ) ; } finally { try { if ( source != null ) { LOG . debug ( "" , script . getName ( ) ) ; source . close ( ) ; } } catch ( IOException e ) { exception = exception == null ? e : exception ; WGLOG . error ( e , "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) ) ; } try { if ( drain != null ) { LOG . debug ( "" , script . getName ( ) ) ; drain . close ( ) ; } } catch ( IOException e ) { exception = exception == null ? e : exception ; WGLOG . error ( e , "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) ) ; } } if ( exception != null ) { throw exception ; } WGLOG . info ( "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) , count ) ; } finally { long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , script . getName ( ) , script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) , count , end - start ) ; } } private < T > void performPrepare ( ProcessScript < T > script , SourceDriver < T > source , DrainDriver < T > drain ) throws IOException { assert script != null ; assert source != null ; assert drain != null ; LOG . debug ( "" , script . getSourceScript ( ) . getResourceName ( ) , script . getName ( ) ) ; if ( RuntimeContext . get ( ) . canExecute ( source ) ) { source . prepare ( ) ; } else { LOG . info ( "" ) ; } LOG . debug ( "" , script . getSourceScript ( ) . getResourceName ( ) , script . getName ( ) ) ; if ( RuntimeContext . get ( ) . canExecute ( drain ) ) { drain . prepare ( ) ; } else { LOG . info ( "" ) ; } } private < T > long performTransfer ( ProcessScript < T > script , SourceDriver < T > source , DrainDriver < T > drain ) throws IOException { assert script != null ; assert source != null ; assert drain != null ; LOG . debug ( "" , new Object [ ] { script . getSourceScript ( ) . getResourceName ( ) , script . getDrainScript ( ) . getResourceName ( ) , script . getName ( ) , } ) ; long count = ; if ( RuntimeContext . get ( ) . canExecute ( source ) && RuntimeContext . get ( ) . canExecute ( drain ) ) { while ( source . next ( ) ) { T obj = source . get ( ) ; drain . put ( obj ) ; count ++ ; } } else if ( RuntimeContext . get ( ) . canExecute ( source ) ) { LOG . info ( "" ) ; while ( source . next ( ) ) { count ++ ; } } else if ( RuntimeContext . get ( ) . canExecute ( drain ) ) { LOG . info ( "" ) ; } else { LOG . info ( "" ) ; } return count ; } } package com . asakusafw . windgate . core . process ; import java . io . IOException ; import com . asakusafw . windgate . core . BaseProvider ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . resource . DriverFactory ; public abstract class ProcessProvider extends BaseProvider < ProcessProfile > { public abstract < T > void execute ( DriverFactory drivers , ProcessScript < T > script ) throws IOException ; } package com . asakusafw . windgate . core . process ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . NavigableMap ; import java . util . Properties ; import java . util . TreeMap ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . BaseProfile ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . WindGateCoreLogger ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . util . PropertiesUtil ; public class ProcessProfile extends BaseProfile < ProcessProfile , ProcessProvider > { static final WindGateLogger WGLOG = new WindGateCoreLogger ( ProcessProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ProcessProfile . class ) ; public static final Pattern NAME_PATTERN = Pattern . compile ( "" ) ; public static final String KEY_PREFIX = "" + QUALIFIER ; private final String name ; private final Class < ? extends ProcessProvider > providerClass ; private final ProfileContext context ; private final Map < String , String > configuration ; public ProcessProfile ( String name , Class < ? extends ProcessProvider > providerClass , ProfileContext context , Map < String , String > configuration ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( providerClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( isValidName ( name ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } this . name = name ; this . providerClass = providerClass ; this . context = context ; this . configuration = Collections . unmodifiableMap ( new TreeMap < String , String > ( configuration ) ) ; } public String getName ( ) { return name ; } @ Override public Class < ? extends ProcessProvider > getProviderClass ( ) { return providerClass ; } @ Override public ProfileContext getContext ( ) { return context ; } public Map < String , String > getConfiguration ( ) { return configuration ; } @ Override protected ProcessProfile getThis ( ) { return this ; } @ Deprecated public static Collection < ? extends ProcessProfile > loadFrom ( Properties properties , ClassLoader loader ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( loader == null ) { throw new IllegalArgumentException ( "" ) ; } return loadFrom ( properties , ProfileContext . system ( loader ) ) ; } public static Collection < ? extends ProcessProfile > loadFrom ( Properties properties , ProfileContext context ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; List < ProcessProfile > results = new ArrayList < ProcessProfile > ( ) ; Map < String , Map < String , String > > processs = partitioning ( properties ) ; for ( Map . Entry < String , Map < String , String > > partitionPair : processs . entrySet ( ) ) { String name = partitionPair . getKey ( ) ; LOG . debug ( "" , name ) ; Map < String , String > partition = partitionPair . getValue ( ) ; assert isValidName ( name ) ; String className = partition . remove ( name ) ; assert className != null ; Map < String , String > conf = PropertiesUtil . createPrefixMap ( partition , name + QUALIFIER ) ; Class < ? extends ProcessProvider > loaded = loadProviderClass ( className , context , ProcessProvider . class ) ; ProcessProfile profile = new ProcessProfile ( name , loaded , context , conf ) ; results . add ( profile ) ; } return results ; } private static Map < String , Map < String , String > > partitioning ( Properties properties ) { assert properties != null ; NavigableMap < String , String > map = PropertiesUtil . createPrefixMap ( properties , KEY_PREFIX ) ; Map < String , Map < String , String > > results = new TreeMap < String , Map < String , String > > ( ) ; while ( map . isEmpty ( ) == false ) { String name = map . firstKey ( ) ; if ( isValidName ( name ) == false ) { WGLOG . error ( "" , name ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } String first = name + QUALIFIER ; String last = name + ( char ) ( QUALIFIER + ) ; Map < String , String > partition = new TreeMap < String , String > ( map . subMap ( first , false , last , false ) ) ; partition . put ( map . firstKey ( ) , map . firstEntry ( ) . getValue ( ) ) ; results . put ( name , partition ) ; for ( String key : partition . keySet ( ) ) { map . remove ( key ) ; } } return results ; } private static boolean isValidName ( String name ) { assert name != null ; return NAME_PATTERN . matcher ( name ) . matches ( ) ; } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) ) ; String providerKey = KEY_PREFIX + name ; String keyPrefix = providerKey + QUALIFIER ; PropertiesUtil . checkAbsentKey ( properties , providerKey ) ; PropertiesUtil . checkAbsentKeyPrefix ( properties , keyPrefix ) ; properties . setProperty ( providerKey , providerClass . getName ( ) ) ; for ( Map . Entry < String , String > entry : configuration . entrySet ( ) ) { properties . setProperty ( keyPrefix + entry . getKey ( ) , entry . getValue ( ) ) ; } } public static void removeCorrespondingKeys ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } PropertiesUtil . removeKeyPrefix ( properties , KEY_PREFIX ) ; } } package com . asakusafw . windgate . core ; import java . io . Closeable ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; import java . util . concurrent . Callable ; import java . util . concurrent . CancellationException ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . runtime . core . context . SimulationSupport ; import com . asakusafw . windgate . core . process . ProcessProfile ; import com . asakusafw . windgate . core . process . ProcessProvider ; import com . asakusafw . windgate . core . resource . DriverRepository ; import com . asakusafw . windgate . core . resource . ResourceMirror ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . resource . ResourceProvider ; import com . asakusafw . windgate . core . session . SessionMirror ; import com . asakusafw . windgate . core . session . SessionProfile ; import com . asakusafw . windgate . core . session . SessionProvider ; @ SimulationSupport public class GateTask implements Closeable { static final WindGateLogger WGLOG = new WindGateCoreLogger ( GateTask . class ) ; static final Logger LOG = LoggerFactory . getLogger ( GateTask . class ) ; private final ExecutorService executor ; private final SessionProvider sessionProvider ; private final List < ResourceProvider > resourceProviders ; private final Map < String , ProcessProvider > processProviders ; final GateProfile profile ; final GateScript script ; final String sessionId ; private final boolean createSession ; private final boolean completeSession ; private final ParameterList arguments ; public GateTask ( GateProfile profile , GateScript script , String sessionId , boolean createSession , boolean completeSession , ParameterList arguments ) throws IOException { if ( profile == null ) { throw new IllegalArgumentException ( "" ) ; } if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sessionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } this . profile = profile ; this . script = script ; this . sessionId = sessionId ; this . createSession = createSession ; this . completeSession = completeSession ; this . arguments = arguments ; this . sessionProvider = loadSessionProvider ( profile . getSession ( ) ) ; this . resourceProviders = loadResourceProviders ( profile . getResources ( ) ) ; this . processProviders = loadProcessProviders ( profile . getProcesses ( ) ) ; this . executor = Executors . newFixedThreadPool ( profile . getCore ( ) . getMaxProcesses ( ) ) ; } private SessionProvider loadSessionProvider ( SessionProfile session ) throws IOException { assert session != null ; LOG . debug ( "" , session . getProviderClass ( ) . getName ( ) ) ; SessionProvider result = session . createProvider ( ) ; return result ; } private List < ResourceProvider > loadResourceProviders ( List < ResourceProfile > resources ) throws IOException { assert resources != null ; List < ResourceProvider > results = new ArrayList < ResourceProvider > ( ) ; for ( ResourceProfile resourceProfile : resources ) { LOG . debug ( "" , resourceProfile . getName ( ) , resourceProfile . getProviderClass ( ) . getName ( ) ) ; ResourceProvider provider = resourceProfile . createProvider ( ) ; results . add ( provider ) ; } return results ; } private Map < String , ProcessProvider > loadProcessProviders ( List < ProcessProfile > processes ) throws IOException { assert processes != null ; Map < String , ProcessProvider > results = new TreeMap < String , ProcessProvider > ( ) ; for ( ProcessProfile processProfile : processes ) { LOG . debug ( "" , processProfile . getName ( ) , processProfile . getProviderClass ( ) . getName ( ) ) ; assert results . containsKey ( processProfile . getName ( ) ) == false ; ProcessProvider provider = processProfile . createProvider ( ) ; results . put ( processProfile . getName ( ) , provider ) ; } return results ; } public void execute ( ) throws IOException , InterruptedException { WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; long start = System . currentTimeMillis ( ) ; try { WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; SessionMirror session = attachSession ( createSession ) ; try { WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; List < ResourceMirror > resources = createResources ( ) ; if ( createSession ) { WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; fireSessionCreated ( resources ) ; } WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; prepareResources ( resources ) ; WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; runGateProcesses ( resources ) ; if ( completeSession ) { WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; fireSessionCompleted ( resources ) ; WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; session . complete ( ) ; } } finally { try { session . close ( ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; } } WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; } finally { long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , sessionId , profile . getName ( ) , script . getName ( ) , end - start ) ; } } private SessionMirror attachSession ( boolean create ) throws IOException { if ( create ) { LOG . debug ( "" , sessionId ) ; if ( RuntimeContext . get ( ) . canExecute ( sessionProvider ) ) { return sessionProvider . create ( sessionId ) ; } else { return new SessionMirror . Null ( sessionId ) ; } } else { LOG . debug ( "" , sessionId ) ; if ( RuntimeContext . get ( ) . canExecute ( sessionProvider ) ) { return sessionProvider . open ( sessionId ) ; } else { return new SessionMirror . Null ( sessionId ) ; } } } private List < ResourceMirror > createResources ( ) throws IOException { List < ResourceMirror > results = new ArrayList < ResourceMirror > ( ) ; for ( ResourceProvider provider : resourceProviders ) { LOG . debug ( "" , provider . getClass ( ) . getName ( ) ) ; ResourceMirror resource = provider . create ( sessionId , arguments ) ; results . add ( resource ) ; } return results ; } private void fireSessionCreated ( List < ResourceMirror > resources ) throws IOException { assert resources != null ; for ( final ResourceMirror resource : resources ) { if ( resource . isTransactional ( ) ) { try { LOG . debug ( "" , resource . getName ( ) , sessionId ) ; if ( RuntimeContext . get ( ) . canExecute ( resource ) ) { resource . onSessionCreated ( ) ; } } catch ( IOException e ) { WGLOG . error ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) , resource . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , resource . getName ( ) , sessionId ) , e ) ; } } } LinkedList < Future < ? > > futures = new LinkedList < Future < ? > > ( ) ; for ( final ResourceMirror resource : resources ) { if ( resource . isTransactional ( ) == false ) { Future < ? > future = executor . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws IOException { LOG . debug ( "" , resource . getName ( ) , sessionId ) ; try { if ( RuntimeContext . get ( ) . canExecute ( resource ) ) { resource . onSessionCreated ( ) ; } } catch ( IOException e ) { WGLOG . error ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) , resource . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , resource . getName ( ) , sessionId ) , e ) ; } return null ; } } ) ; futures . add ( future ) ; } } int failureCount = waitForComplete ( futures ) ; if ( failureCount > ) { throw new IOException ( MessageFormat . format ( "" , sessionId ) ) ; } } private void prepareResources ( List < ResourceMirror > resources ) throws IOException { assert resources != null ; LinkedList < Future < ? > > futures = new LinkedList < Future < ? > > ( ) ; for ( final ResourceMirror resource : resources ) { Future < ? > future = executor . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws IOException { LOG . debug ( "" , resource . getName ( ) ) ; try { if ( RuntimeContext . get ( ) . canExecute ( resource ) ) { resource . prepare ( script ) ; } } catch ( IOException e ) { WGLOG . error ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) , resource . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , resource . getName ( ) , sessionId ) , e ) ; } return null ; } } ) ; futures . add ( future ) ; } int failureCount = waitForComplete ( futures ) ; if ( failureCount > ) { throw new IOException ( "" ) ; } } private void runGateProcesses ( List < ResourceMirror > resources ) throws IOException { assert resources != null ; final DriverRepository drivers = new DriverRepository ( resources ) ; LinkedList < Future < ? > > futures = new LinkedList < Future < ? > > ( ) ; for ( final ProcessScript < ? > process : script . getProcesses ( ) ) { final ProcessProvider processProvider = processProviders . get ( process . getProcessType ( ) ) ; assert processProvider != null ; Future < ? > future = executor . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws IOException { LOG . debug ( "" , process . getName ( ) , sessionId ) ; try { if ( RuntimeContext . get ( ) . canExecute ( processProvider ) ) { processProvider . execute ( drivers , process ) ; } else { LOG . info ( "" ) ; } } catch ( IOException e ) { WGLOG . error ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) , process . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , process . getName ( ) , process . getSourceScript ( ) . getResourceName ( ) , process . getDrainScript ( ) . getResourceName ( ) , sessionId ) , e ) ; } return null ; } } ) ; futures . add ( future ) ; } int failureCount = waitForComplete ( futures ) ; if ( failureCount > ) { throw new IOException ( MessageFormat . format ( "" , sessionId ) ) ; } } private void fireSessionCompleted ( List < ResourceMirror > resources ) throws IOException { assert resources != null ; LinkedList < Future < ? > > futures = new LinkedList < Future < ? > > ( ) ; for ( final ResourceMirror resource : resources ) { if ( resource . isTransactional ( ) == false ) { Future < ? > future = executor . submit ( new Callable < Void > ( ) { @ Override public Void call ( ) throws IOException { LOG . debug ( "" , resource . getName ( ) , sessionId ) ; try { if ( RuntimeContext . get ( ) . canExecute ( resource ) ) { resource . onSessionCompleting ( ) ; } } catch ( IOException e ) { WGLOG . error ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) , resource . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , resource . getName ( ) , sessionId ) , e ) ; } return null ; } } ) ; futures . add ( future ) ; } } int failureCount = waitForComplete ( futures ) ; if ( failureCount > ) { throw new IOException ( MessageFormat . format ( "" , sessionId ) ) ; } for ( final ResourceMirror resource : resources ) { if ( resource . isTransactional ( ) ) { LOG . debug ( "" , resource . getName ( ) , sessionId ) ; try { if ( RuntimeContext . get ( ) . canExecute ( resource ) ) { resource . onSessionCompleting ( ) ; } } catch ( IOException e ) { WGLOG . error ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) , resource . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , resource . getName ( ) , sessionId ) , e ) ; } } } } private int waitForComplete ( LinkedList < Future < ? > > futures ) { assert futures != null ; int failureCount = ; while ( futures . isEmpty ( ) == false ) { Future < ? > future = futures . removeFirst ( ) ; try { future . get ( , TimeUnit . MILLISECONDS ) ; } catch ( TimeoutException e ) { futures . addLast ( future ) ; } catch ( InterruptedException e ) { WGLOG . warn ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; futures . addLast ( future ) ; cancelAll ( futures ) ; } catch ( ExecutionException e ) { failureCount ++ ; WGLOG . warn ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; cancelAll ( futures ) ; if ( e . getCause ( ) instanceof Error ) { throw ( Error ) e . getCause ( ) ; } } catch ( CancellationException e ) { failureCount ++ ; WGLOG . warn ( e , "" , sessionId , profile . getName ( ) , script . getName ( ) ) ; } } return failureCount ; } private void cancelAll ( LinkedList < Future < ? > > futures ) { assert futures != null ; for ( Future < ? > future : futures ) { future . cancel ( true ) ; } } @ Override public void close ( ) { executor . shutdown ( ) ; } } package com . asakusafw . windgate . core . util ; package com . asakusafw . windgate . core . util ; import java . text . MessageFormat ; import java . util . Iterator ; import java . util . Map ; import java . util . NavigableMap ; import java . util . Properties ; import java . util . TreeMap ; public final class PropertiesUtil { public static void removeKeyPrefix ( Properties properties , String prefix ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } for ( Iterator < ? > iter = properties . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Object key = iter . next ( ) ; if ( ( key instanceof String ) == false ) { continue ; } String name = ( String ) key ; if ( name . startsWith ( prefix ) ) { iter . remove ( ) ; } } } public static NavigableMap < String , String > createPrefixMap ( Map < ? , ? > properties , String prefix ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( prefix == null ) { throw new IllegalArgumentException ( "" ) ; } NavigableMap < String , String > results = new TreeMap < String , String > ( ) ; for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { if ( ( entry . getKey ( ) instanceof String ) == false || ( entry . getValue ( ) instanceof String ) == false ) { continue ; } String name = ( String ) entry . getKey ( ) ; if ( name . startsWith ( prefix ) == false ) { continue ; } results . put ( name . substring ( prefix . length ( ) ) , ( String ) entry . getValue ( ) ) ; } return results ; } public static void checkAbsentKey ( Properties properties , String key ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( key == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties . containsKey ( key ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , key ) ) ; } } public static void checkAbsentKeyPrefix ( Properties properties , String keyPrefix ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( keyPrefix == null ) { throw new IllegalArgumentException ( "" ) ; } for ( String key : properties . stringPropertyNames ( ) ) { if ( key . startsWith ( keyPrefix ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , key ) ) ; } } } private PropertiesUtil ( ) { return ; } } package com . asakusafw . windgate . core . util ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateCoreLogger ; import com . asakusafw . windgate . core . WindGateLogger ; public final class ProcessUtil { static final WindGateLogger WGLOG = new WindGateCoreLogger ( ProcessUtil . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ProcessUtil . class ) ; public static < T > T newDataModel ( String resourceName , ProcessScript < T > script ) throws IOException { if ( resourceName == null ) { throw new IllegalArgumentException ( "" ) ; } if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } Class < T > dataClass = script . getDataClass ( ) ; LOG . debug ( "" , new Object [ ] { dataClass . getName ( ) , resourceName , script . getName ( ) , } ) ; try { T object = dataClass . newInstance ( ) ; return object ; } catch ( Exception e ) { WGLOG . error ( e , "" , resourceName , script . getName ( ) , dataClass . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , resourceName , script . getName ( ) , dataClass . getName ( ) ) , e ) ; } } private ProcessUtil ( ) { return ; } } package com . asakusafw . windgate . core ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . util . PropertiesUtil ; public class GateScript { static final WindGateLogger WGLOG = new WindGateCoreLogger ( GateScript . class ) ; static final Logger LOG = LoggerFactory . getLogger ( GateScript . class ) ; static final char QUALIFIER = '' ; private final String name ; private final List < ProcessScript < ? > > processes ; public GateScript ( String name , List < ? extends ProcessScript < ? > > processes ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( processes == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . processes = Collections . unmodifiableList ( new ArrayList < ProcessScript < ? > > ( processes ) ) ; } public String getName ( ) { return name ; } public List < ProcessScript < ? > > getProcesses ( ) { return processes ; } public static GateScript loadFrom ( String name , Properties properties , ClassLoader loader ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( loader == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; Map < String , Map < String , String > > partitions = partitioning ( properties ) ; List < ProcessScript < ? > > processes = new ArrayList < ProcessScript < ? > > ( ) ; for ( Map . Entry < String , Map < String , String > > entry : partitions . entrySet ( ) ) { LOG . debug ( "" , entry . getKey ( ) ) ; ProcessScript < ? > process = loadProcess ( entry . getKey ( ) , entry . getValue ( ) , loader ) ; processes . add ( process ) ; } return new GateScript ( name , processes ) ; } private static Map < String , Map < String , String > > partitioning ( Properties properties ) { assert properties != null ; Map < String , Map < String , String > > results = new HashMap < String , Map < String , String > > ( ) ; for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { if ( ( entry . getKey ( ) instanceof String ) == false || ( entry . getValue ( ) instanceof String ) == false ) { continue ; } String key = ( String ) entry . getKey ( ) ; int index = key . indexOf ( QUALIFIER ) ; if ( index < ) { WGLOG . error ( "" , key , entry . getValue ( ) ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , key ) ) ; } String name = key . substring ( , index ) ; Map < String , String > partition = results . get ( name ) ; if ( partition == null ) { partition = new TreeMap < String , String > ( ) ; results . put ( name , partition ) ; } partition . put ( key . substring ( index + ) , ( String ) entry . getValue ( ) ) ; } return results ; } private static ProcessScript < ? > loadProcess ( String name , Map < String , String > conf , ClassLoader loader ) { assert name != null ; assert conf != null ; assert loader != null ; String processType = consume ( conf , name , ProcessScript . KEY_PROCESS_TYPE ) ; String dataClassName = consume ( conf , name , ProcessScript . KEY_DATA_CLASS ) ; DriverScript sourceScript = loadDriver ( name , DriverScript . Kind . SOURCE , conf ) ; DriverScript drainScript = loadDriver ( name , DriverScript . Kind . DRAIN , conf ) ; LOG . debug ( "" , dataClassName ) ; Class < ? > dataClass ; try { dataClass = loader . loadClass ( dataClassName ) ; } catch ( ClassNotFoundException e ) { WGLOG . error ( e , "" , name , dataClassName ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , dataClassName , name , ProcessScript . KEY_DATA_CLASS ) ) ; } if ( conf . isEmpty ( ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name , conf . keySet ( ) ) ) ; } return createProcess ( name , processType , dataClass , sourceScript , drainScript ) ; } private static String consume ( Map < String , String > proccessConf , String name , String key ) { assert proccessConf != null ; assert name != null ; assert key != null ; String value = proccessConf . remove ( key ) ; if ( value == null ) { WGLOG . error ( "" , name + QUALIFIER + key , "" ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , name , key ) ) ; } return value ; } private static DriverScript loadDriver ( String name , DriverScript . Kind kind , Map < String , String > conf ) { assert name != null ; assert kind != null ; assert conf != null ; String resourceName = consume ( conf , name , kind . prefix ) ; Map < String , String > driverConf = new HashMap < String , String > ( ) ; String prefix = kind . prefix + QUALIFIER ; for ( Iterator < Map . Entry < String , String > > iter = conf . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Map . Entry < String , String > entry = iter . next ( ) ; String key = entry . getKey ( ) ; if ( key . startsWith ( prefix ) ) { driverConf . put ( key . substring ( prefix . length ( ) ) , entry . getValue ( ) ) ; iter . remove ( ) ; } } return new DriverScript ( resourceName , driverConf ) ; } private static < T > ProcessScript < T > createProcess ( String name , String processType , Class < T > dataClass , DriverScript sourceScript , DriverScript drainScript ) { return new ProcessScript < T > ( name , processType , dataClass , sourceScript , drainScript ) ; } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; for ( ProcessScript < ? > process : processes ) { PropertiesUtil . checkAbsentKeyPrefix ( properties , process . getName ( ) + QUALIFIER ) ; } for ( ProcessScript < ? > process : processes ) { storeProcessTo ( properties , process ) ; } } private void storeProcessTo ( Properties properties , ProcessScript < ? > process ) { assert properties != null ; assert process != null ; String prefix = process . getName ( ) + QUALIFIER ; properties . setProperty ( prefix + ProcessScript . KEY_DATA_CLASS , process . getDataClass ( ) . getName ( ) ) ; properties . setProperty ( prefix + ProcessScript . KEY_PROCESS_TYPE , process . getProcessType ( ) ) ; storeDriverTo ( properties , process , DriverScript . Kind . SOURCE , process . getSourceScript ( ) ) ; storeDriverTo ( properties , process , DriverScript . Kind . DRAIN , process . getDrainScript ( ) ) ; } private void storeDriverTo ( Properties properties , ProcessScript < ? > process , DriverScript . Kind kind , DriverScript driver ) { assert properties != null ; assert process != null ; assert kind != null ; assert driver != null ; properties . setProperty ( process . getName ( ) + QUALIFIER + kind . prefix , driver . getResourceName ( ) ) ; String prefix = process . getName ( ) + QUALIFIER + kind . prefix + QUALIFIER ; for ( Map . Entry < String , String > entry : driver . getConfiguration ( ) . entrySet ( ) ) { properties . put ( prefix + entry . getKey ( ) , entry . getValue ( ) ) ; } } } package com . asakusafw . windgate . core . resource ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import com . asakusafw . windgate . core . GateProfile ; import com . asakusafw . windgate . core . ProcessScript ; import com . asakusafw . windgate . core . WindGateCoreLogger ; import com . asakusafw . windgate . core . WindGateLogger ; public class DriverRepository implements DriverFactory { static final WindGateLogger WGLOG = new WindGateCoreLogger ( GateProfile . class ) ; private final Map < String , ResourceMirror > resources ; public DriverRepository ( Iterable < ? extends ResourceMirror > resources ) { if ( resources == null ) { throw new IllegalArgumentException ( "" ) ; } HashMap < String , ResourceMirror > map = new HashMap < String , ResourceMirror > ( ) ; for ( ResourceMirror resource : resources ) { map . put ( resource . getName ( ) , resource ) ; } this . resources = Collections . unmodifiableMap ( map ) ; } @ Override public < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } String name = script . getSourceScript ( ) . getResourceName ( ) ; ResourceMirror resource = resources . get ( name ) ; if ( resource == null ) { WGLOG . error ( "" , script . getName ( ) , name ) ; throw new IOException ( MessageFormat . format ( "" , name , script . getName ( ) ) ) ; } return resource . createSource ( script ) ; } @ Override public < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "" ) ; } String name = script . getDrainScript ( ) . getResourceName ( ) ; ResourceMirror resource = resources . get ( name ) ; if ( resource == null ) { WGLOG . error ( "" , script . getName ( ) , name ) ; throw new IOException ( MessageFormat . format ( "" , name , script . getName ( ) ) ) ; } return resource . createDrain ( script ) ; } } package com . asakusafw . windgate . core . resource ; import java . io . IOException ; import com . asakusafw . windgate . core . ProcessScript ; public interface DriverFactory { < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException ; < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException ; } package com . asakusafw . windgate . core . resource ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import java . util . NavigableMap ; import java . util . Properties ; import java . util . TreeMap ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . BaseProfile ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . WindGateCoreLogger ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . util . PropertiesUtil ; public final class ResourceProfile extends BaseProfile < ResourceProfile , ResourceProvider > { static final WindGateLogger WGLOG = new WindGateCoreLogger ( ResourceProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ResourceProfile . class ) ; public static final Pattern NAME_PATTERN = Pattern . compile ( "" ) ; public static final String KEY_PREFIX = "" ; private final String name ; private final Class < ? extends ResourceProvider > providerClass ; private final ProfileContext context ; private final Map < String , String > configuration ; public ResourceProfile ( String name , Class < ? extends ResourceProvider > providerClass , ProfileContext context , Map < String , String > configuration ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( providerClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } if ( isValidName ( name ) == false ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } this . name = name ; this . providerClass = providerClass ; this . context = context ; this . configuration = Collections . unmodifiableMap ( new TreeMap < String , String > ( configuration ) ) ; } public String getName ( ) { return name ; } @ Override public Class < ? extends ResourceProvider > getProviderClass ( ) { return providerClass ; } @ Override public ProfileContext getContext ( ) { return context ; } public Map < String , String > getConfiguration ( ) { return configuration ; } @ Override protected ResourceProfile getThis ( ) { return this ; } @ Deprecated public static Collection < ? extends ResourceProfile > loadFrom ( Properties properties , ClassLoader loader ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( loader == null ) { throw new IllegalArgumentException ( "" ) ; } return loadFrom ( properties , ProfileContext . system ( loader ) ) ; } public static Collection < ? extends ResourceProfile > loadFrom ( Properties properties , ProfileContext context ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; List < ResourceProfile > results = new ArrayList < ResourceProfile > ( ) ; Map < String , Map < String , String > > resources = partitioning ( properties ) ; for ( Map . Entry < String , Map < String , String > > partitionPair : resources . entrySet ( ) ) { String name = partitionPair . getKey ( ) ; LOG . debug ( "" , name ) ; Map < String , String > partition = partitionPair . getValue ( ) ; assert isValidName ( name ) ; String className = partition . remove ( name ) ; assert className != null ; Map < String , String > conf = PropertiesUtil . createPrefixMap ( partition , name + QUALIFIER ) ; Class < ? extends ResourceProvider > loaded = loadProviderClass ( className , context , ResourceProvider . class ) ; ResourceProfile profile = new ResourceProfile ( name , loaded , context , conf ) ; results . add ( profile ) ; } return results ; } private static Map < String , Map < String , String > > partitioning ( Properties properties ) { assert properties != null ; NavigableMap < String , String > map = PropertiesUtil . createPrefixMap ( properties , KEY_PREFIX ) ; Map < String , Map < String , String > > results = new TreeMap < String , Map < String , String > > ( ) ; while ( map . isEmpty ( ) == false ) { String name = map . firstKey ( ) ; if ( isValidName ( name ) == false ) { WGLOG . error ( "" , name ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , name ) ) ; } String first = name + QUALIFIER ; String last = name + ( char ) ( QUALIFIER + ) ; Map < String , String > partition = new TreeMap < String , String > ( map . subMap ( first , false , last , false ) ) ; partition . put ( map . firstKey ( ) , map . firstEntry ( ) . getValue ( ) ) ; results . put ( name , partition ) ; for ( String key : partition . keySet ( ) ) { map . remove ( key ) ; } } return results ; } private static boolean isValidName ( String name ) { assert name != null ; return NAME_PATTERN . matcher ( name ) . matches ( ) ; } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , getName ( ) ) ; String providerKey = KEY_PREFIX + name ; String keyPrefix = providerKey + QUALIFIER ; PropertiesUtil . checkAbsentKey ( properties , providerKey ) ; PropertiesUtil . checkAbsentKeyPrefix ( properties , keyPrefix ) ; properties . setProperty ( providerKey , providerClass . getName ( ) ) ; for ( Map . Entry < String , String > entry : configuration . entrySet ( ) ) { properties . setProperty ( keyPrefix + entry . getKey ( ) , entry . getValue ( ) ) ; } } public static void removeCorrespondingKeys ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } PropertiesUtil . removeKeyPrefix ( properties , KEY_PREFIX ) ; } } package com . asakusafw . windgate . core . resource ; package com . asakusafw . windgate . core . resource ; import java . io . IOException ; import java . text . MessageFormat ; import com . asakusafw . windgate . core . BaseProvider ; import com . asakusafw . windgate . core . ParameterList ; public abstract class ResourceProvider extends BaseProvider < ResourceProfile > { public abstract ResourceMirror create ( String sessionId , ParameterList arguments ) throws IOException ; public void abort ( String sessionId ) throws IOException { return ; } public void abortAll ( ) throws IOException { return ; } public ResourceManipulator createManipulator ( ParameterList arguments ) throws IOException { if ( arguments == null ) { throw new IllegalArgumentException ( "" ) ; } throw new IOException ( MessageFormat . format ( "" , getClass ( ) . getName ( ) ) ) ; } } package com . asakusafw . windgate . core . resource ; import java . io . Closeable ; import java . io . IOException ; import com . asakusafw . windgate . file . resource . Preparable ; public interface DrainDriver < T > extends Preparable , Closeable { @ Override void prepare ( ) throws IOException ; void put ( T object ) throws IOException ; @ Override void close ( ) throws IOException ; } package com . asakusafw . windgate . core . resource ; import java . io . IOException ; import com . asakusafw . windgate . core . ProcessScript ; public abstract class ResourceManipulator { public abstract String getName ( ) ; public abstract void cleanupSource ( ProcessScript < ? > script ) throws IOException ; public abstract void cleanupDrain ( ProcessScript < ? > script ) throws IOException ; public abstract < T > SourceDriver < T > createSourceForSource ( ProcessScript < T > script ) throws IOException ; public abstract < T > DrainDriver < T > createDrainForSource ( ProcessScript < T > script ) throws IOException ; public abstract < T > SourceDriver < T > createSourceForDrain ( ProcessScript < T > script ) throws IOException ; public abstract < T > DrainDriver < T > createDrainForDrain ( ProcessScript < T > script ) throws IOException ; } package com . asakusafw . windgate . core . resource ; import java . io . Closeable ; import java . io . IOException ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . ProcessScript ; public abstract class ResourceMirror implements Closeable { public abstract String getName ( ) ; public boolean isTransactional ( ) { return false ; } public void onSessionCreated ( ) throws IOException { return ; } public void onSessionCompleting ( ) throws IOException { return ; } public abstract void prepare ( GateScript script ) throws IOException ; public abstract < T > SourceDriver < T > createSource ( ProcessScript < T > script ) throws IOException ; public abstract < T > DrainDriver < T > createDrain ( ProcessScript < T > script ) throws IOException ; } package com . asakusafw . windgate . core . resource ; import java . io . Closeable ; import java . io . IOException ; import com . asakusafw . windgate . file . resource . Preparable ; public interface SourceDriver < T > extends Preparable , Closeable { @ Override void prepare ( ) throws IOException ; boolean next ( ) throws IOException ; T get ( ) throws IOException ; @ Override void close ( ) throws IOException ; } package com . asakusafw . windgate . core ; public class ProfileContext { private final ClassLoader classLoader ; private final ParameterList contextParameters ; public ProfileContext ( ClassLoader classLoader , ParameterList contextParameters ) { if ( classLoader == null ) { throw new IllegalArgumentException ( "" ) ; } if ( contextParameters == null ) { throw new IllegalArgumentException ( "" ) ; } this . classLoader = classLoader ; this . contextParameters = contextParameters ; } public static ProfileContext system ( ClassLoader classLoader ) { return new ProfileContext ( classLoader , new ParameterList ( System . getenv ( ) ) ) ; } public ClassLoader getClassLoader ( ) { return classLoader ; } public ParameterList getContextParameters ( ) { return contextParameters ; } } package com . asakusafw . windgate . core ; import java . text . MessageFormat ; import java . util . Map ; import java . util . Properties ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . util . PropertiesUtil ; public class CoreProfile { static final WindGateLogger WGLOG = new WindGateCoreLogger ( CoreProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( CoreProfile . class ) ; private static final char QUALIFIER = '' ; public static final String KEY_PREFIX = "" + QUALIFIER ; @ Deprecated public static final String KEY_MAX_THREADS = "" ; public static final String KEY_MAX_PROCESSES = "" ; public static final int DEFAULT_MAX_PROCESSES = ; private final int maxProcesses ; public CoreProfile ( int maxProcesses ) { if ( maxProcesses < ) { throw new IllegalArgumentException ( "" ) ; } this . maxProcesses = maxProcesses ; } public int getMaxProcesses ( ) { return maxProcesses ; } @ Deprecated public static CoreProfile loadFrom ( Properties properties , ClassLoader loader ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( loader == null ) { throw new IllegalArgumentException ( "" ) ; } return loadFrom ( properties , ProfileContext . system ( loader ) ) ; } public static CoreProfile loadFrom ( Properties properties , ProfileContext context ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; Map < String , String > config = PropertiesUtil . createPrefixMap ( properties , KEY_PREFIX ) ; int maxProcesses ; if ( config . containsKey ( KEY_MAX_PROCESSES ) ) { maxProcesses = getMaxProcesses ( config , KEY_MAX_PROCESSES ) ; } else { maxProcesses = getMaxProcesses ( config , KEY_MAX_THREADS ) ; } return new CoreProfile ( maxProcesses ) ; } private static int getMaxProcesses ( Map < String , String > config , String key ) { assert config != null ; assert key != null ; int maxProcesses = getInt ( config , key , DEFAULT_MAX_PROCESSES ) ; if ( maxProcesses <= ) { WGLOG . error ( "" , key , maxProcesses ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , key , String . valueOf ( maxProcesses ) ) ) ; } return maxProcesses ; } private static int getInt ( Map < String , String > config , String name , int defaultValue ) { assert config != null ; assert name != null ; String value = config . get ( name ) ; if ( value == null ) { LOG . debug ( "" , name , defaultValue ) ; return defaultValue ; } try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { WGLOG . error ( "" , name , value ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , name , value ) ) ; } } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; PropertiesUtil . checkAbsentKeyPrefix ( properties , KEY_PREFIX ) ; properties . setProperty ( KEY_PREFIX + KEY_MAX_PROCESSES , String . valueOf ( getMaxProcesses ( ) ) ) ; } public static void removeCorrespondingKeys ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } PropertiesUtil . removeKeyPrefix ( properties , KEY_PREFIX ) ; } } package com . asakusafw . windgate . core ; import java . util . Collections ; import java . util . Map ; import java . util . TreeMap ; public class DriverScript { public static final String PREFIX_SOURCE = "" ; public static final String PREFIX_DRAIN = "" ; private final String resourceName ; private final Map < String , String > configuration ; public DriverScript ( String resource , Map < String , String > configuration ) { if ( resource == null ) { throw new IllegalArgumentException ( "" ) ; } if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . resourceName = resource ; this . configuration = Collections . unmodifiableMap ( new TreeMap < String , String > ( configuration ) ) ; } public String getResourceName ( ) { return resourceName ; } public Map < String , String > getConfiguration ( ) { return configuration ; } public enum Kind { SOURCE ( PREFIX_SOURCE ) { @ Override public Kind opposite ( ) { return DRAIN ; } } , DRAIN ( PREFIX_DRAIN ) { @ Override public Kind opposite ( ) { return SOURCE ; } } , ; public final String prefix ; private Kind ( String prefix ) { assert prefix != null ; this . prefix = prefix ; } public abstract Kind opposite ( ) ; } } package com . asakusafw . windgate . core ; public class ProcessScript < T > { public static final String KEY_DATA_CLASS = "" ; public static final String KEY_PROCESS_TYPE = "" ; private final String name ; private final String processType ; private final Class < T > dataClass ; private final DriverScript sourceScript ; private final DriverScript drainScript ; public ProcessScript ( String name , String processType , Class < T > dataClass , DriverScript sourceScript , DriverScript drainScript ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( processType == null ) { throw new IllegalArgumentException ( "" ) ; } if ( dataClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( sourceScript == null ) { throw new IllegalArgumentException ( "" ) ; } if ( drainScript == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . processType = processType ; this . dataClass = dataClass ; this . sourceScript = sourceScript ; this . drainScript = drainScript ; } public String getName ( ) { return name ; } public String getProcessType ( ) { return processType ; } public Class < T > getDataClass ( ) { return dataClass ; } public DriverScript getSourceScript ( ) { return sourceScript ; } public DriverScript getDrainScript ( ) { return drainScript ; } public DriverScript getDriverScript ( DriverScript . Kind kind ) { if ( kind == null ) { throw new IllegalArgumentException ( "" ) ; } switch ( kind ) { case SOURCE : return getSourceScript ( ) ; case DRAIN : return getDrainScript ( ) ; default : throw new AssertionError ( kind ) ; } } } package com . asakusafw . windgate . core ; import java . text . MessageFormat ; import java . util . ResourceBundle ; public class WindGateCoreLogger extends WindGateLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public WindGateCoreLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . windgate . core ; import java . io . IOException ; public abstract class BaseProvider < T > { protected abstract void configure ( T profile ) throws IOException ; } package com . asakusafw . windgate . core ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public abstract class WindGateLogger { private final Logger internal ; private final MessageFormat format = new MessageFormat ( "" ) ; private final String componentName ; public WindGateLogger ( Class < ? > target , String componentName ) { if ( target == null ) { throw new IllegalArgumentException ( "" ) ; } if ( componentName == null ) { throw new IllegalArgumentException ( "" ) ; } this . componentName = componentName ; this . internal = LoggerFactory . getLogger ( target ) ; } public void info ( String code , Object ... arguments ) { if ( internal . isInfoEnabled ( ) ) { String message = message ( code , arguments ) ; internal . info ( message ) ; } } public void info ( Exception exception , String code , Object ... arguments ) { if ( internal . isInfoEnabled ( ) ) { String message = message ( code , arguments ) ; internal . info ( message , exception ) ; } } public void warn ( String code , Object ... arguments ) { if ( internal . isWarnEnabled ( ) ) { String message = message ( code , arguments ) ; internal . warn ( message ) ; } } public void warn ( Exception exception , String code , Object ... arguments ) { if ( internal . isWarnEnabled ( ) ) { String message = message ( code , arguments ) ; internal . warn ( message , exception ) ; } } public void error ( String code , Object ... arguments ) { if ( internal . isErrorEnabled ( ) ) { String message = message ( code , arguments ) ; internal . error ( message ) ; } } public void error ( Exception exception , String code , Object ... arguments ) { if ( internal . isErrorEnabled ( ) ) { String message = message ( code , arguments ) ; internal . error ( message , exception ) ; } } private String message ( String code , Object ... arguments ) { assert code != null ; assert arguments != null ; String message = getMessage ( code , arguments ) ; return format . format ( new Object [ ] { componentName , code , message } ) ; } protected abstract String getMessage ( String code , Object ... arguments ) ; } package com . asakusafw . windgate . core ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Map ; import java . util . TreeMap ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class ParameterList { static final WindGateLogger WGLOG = new WindGateCoreLogger ( ParameterList . class ) ; static final Logger LOG = LoggerFactory . getLogger ( ParameterList . class ) ; private static final Pattern VARIABLE = Pattern . compile ( "" ) ; private final Map < String , String > parameters ; public ParameterList ( ) { this ( Collections . < String , String > emptyMap ( ) ) ; } public ParameterList ( Map < String , String > parameters ) { if ( parameters == null ) { throw new IllegalArgumentException ( "" ) ; } this . parameters = Collections . unmodifiableMap ( new TreeMap < String , String > ( parameters ) ) ; } public Map < String , String > getPairs ( ) { return parameters ; } public String replace ( String string , boolean strict ) { if ( string == null ) { throw new IllegalArgumentException ( "" ) ; } StringBuilder buf = new StringBuilder ( ) ; int start = ; Matcher matcher = VARIABLE . matcher ( string ) ; while ( matcher . find ( start ) ) { String name = matcher . group ( ) ; String replacement = parameters . get ( name ) ; if ( replacement == null ) { if ( strict ) { WGLOG . error ( "" , name ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , name , this ) ) ; } else { buf . append ( string . substring ( start , matcher . start ( ) + ) ) ; } start = matcher . start ( ) + ; } else { buf . append ( string . substring ( start , matcher . start ( ) ) ) ; buf . append ( replacement ) ; start = matcher . end ( ) ; } } buf . append ( string . substring ( start ) ) ; return buf . toString ( ) ; } @ Override public String toString ( ) { return parameters . toString ( ) ; } } package com . asakusafw . windgate . core . session ; package com . asakusafw . windgate . core . session ; import java . io . IOException ; import java . util . List ; import com . asakusafw . windgate . core . BaseProvider ; public abstract class SessionProvider extends BaseProvider < SessionProfile > { public abstract List < String > getCreatedIds ( ) throws IOException ; public abstract SessionMirror create ( String id ) throws SessionException , IOException ; public abstract SessionMirror open ( String id ) throws SessionException , IOException ; public abstract void delete ( String id ) throws SessionException , IOException ; } package com . asakusafw . windgate . core . session ; import java . io . Closeable ; import java . io . IOException ; public abstract class SessionMirror implements Closeable { public abstract String getId ( ) ; public abstract void complete ( ) throws IOException ; public abstract void abort ( ) throws IOException ; @ Override public abstract void close ( ) throws IOException ; public static final class Null extends SessionMirror { private final String id ; public Null ( String id ) { if ( id == null ) { throw new IllegalArgumentException ( "" ) ; } this . id = id ; } @ Override public String getId ( ) { return id ; } @ Override public void complete ( ) { return ; } @ Override public void abort ( ) { return ; } @ Override public void close ( ) { return ; } } } package com . asakusafw . windgate . core . session ; import java . text . MessageFormat ; import java . util . Collections ; import java . util . Map ; import java . util . Properties ; import java . util . TreeMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . BaseProfile ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . WindGateCoreLogger ; import com . asakusafw . windgate . core . WindGateLogger ; import com . asakusafw . windgate . core . util . PropertiesUtil ; public class SessionProfile extends BaseProfile < SessionProfile , SessionProvider > { static final WindGateLogger WGLOG = new WindGateCoreLogger ( SessionProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( SessionProfile . class ) ; public static final String KEY_PROVIDER = "" ; public static final String KEY_PREFIX = KEY_PROVIDER + QUALIFIER ; private final Class < ? extends SessionProvider > providerClass ; private final ProfileContext context ; private final Map < String , String > configuration ; public SessionProfile ( Class < ? extends SessionProvider > providerClass , ProfileContext context , Map < String , String > configuration ) { if ( providerClass == null ) { throw new IllegalArgumentException ( "" ) ; } if ( configuration == null ) { throw new IllegalArgumentException ( "" ) ; } this . providerClass = providerClass ; this . context = context ; this . configuration = Collections . unmodifiableMap ( new TreeMap < String , String > ( configuration ) ) ; } @ Override public Class < ? extends SessionProvider > getProviderClass ( ) { return providerClass ; } @ Override public ProfileContext getContext ( ) { return context ; } public Map < String , String > getConfiguration ( ) { return configuration ; } @ Override protected SessionProfile getThis ( ) { return this ; } @ Deprecated public static SessionProfile loadFrom ( Properties properties , ClassLoader loader ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( loader == null ) { throw new IllegalArgumentException ( "" ) ; } return loadFrom ( properties , ProfileContext . system ( loader ) ) ; } public static SessionProfile loadFrom ( Properties properties , ProfileContext context ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; String className = properties . getProperty ( KEY_PROVIDER ) ; if ( className == null ) { WGLOG . error ( "" ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , KEY_PROVIDER ) ) ; } Class < ? extends SessionProvider > provider = loadProviderClass ( className , context , SessionProvider . class ) ; Map < String , String > config = PropertiesUtil . createPrefixMap ( properties , KEY_PREFIX ) ; return new SessionProfile ( provider , context , config ) ; } public void storeTo ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; PropertiesUtil . checkAbsentKey ( properties , KEY_PROVIDER ) ; PropertiesUtil . checkAbsentKeyPrefix ( properties , KEY_PREFIX ) ; properties . setProperty ( KEY_PROVIDER , providerClass . getName ( ) ) ; for ( Map . Entry < String , String > entry : configuration . entrySet ( ) ) { properties . setProperty ( KEY_PREFIX + entry . getKey ( ) , entry . getValue ( ) ) ; } } public static void removeCorrespondingKeys ( Properties properties ) { if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } properties . remove ( KEY_PROVIDER ) ; PropertiesUtil . removeKeyPrefix ( properties , KEY_PREFIX ) ; } } package com . asakusafw . windgate . core . session ; import java . io . IOException ; import java . text . MessageFormat ; public class SessionException extends IOException { private static final long serialVersionUID = - ; private final String sessionId ; private final Reason reason ; public SessionException ( String sessionId , Reason reason , Throwable cause ) { super ( buildMessage ( sessionId , reason ) , cause ) ; this . sessionId = sessionId ; this . reason = reason ; } public String getSessionId ( ) { return sessionId ; } public Reason getReason ( ) { return reason ; } private static String buildMessage ( String sessionId , Reason reason ) { if ( sessionId == null ) { throw new IllegalArgumentException ( "" ) ; } if ( reason == null ) { throw new IllegalArgumentException ( "" ) ; } return MessageFormat . format ( "" , sessionId , reason . getDescription ( ) ) ; } public SessionException ( String sessionId , Reason reason ) { this ( sessionId , reason , null ) ; } public enum Reason { ALREADY_EXIST ( "" ) , NOT_EXIST ( "" ) , ACQUIRED ( "" ) , BROKEN ( "" ) , ; private final String description ; private Reason ( String description ) { assert description != null ; this . description = description ; } public String getDescription ( ) { return description ; } @ Override public String toString ( ) { return MessageFormat . format ( "" , name ( ) , getDescription ( ) ) ; } } } package com . asakusafw . windgate . core ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Properties ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . windgate . core . process . ProcessProfile ; import com . asakusafw . windgate . core . process . ProcessProvider ; import com . asakusafw . windgate . core . resource . ResourceProfile ; import com . asakusafw . windgate . core . session . SessionProfile ; public class GateProfile { static final WindGateLogger WGLOG = new WindGateCoreLogger ( GateProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( GateProfile . class ) ; private final String name ; private final CoreProfile core ; private final SessionProfile session ; private final List < ProcessProfile > processes ; private final List < ResourceProfile > resources ; public GateProfile ( String name , CoreProfile core , SessionProfile session , Collection < ? extends ProcessProfile > processes , Collection < ? extends ResourceProfile > resources ) { if ( core == null ) { throw new IllegalArgumentException ( "" ) ; } if ( session == null ) { throw new IllegalArgumentException ( "" ) ; } if ( processes == null ) { throw new IllegalArgumentException ( "" ) ; } if ( resources == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; this . core = core ; this . session = session ; this . processes = Collections . unmodifiableList ( new ArrayList < ProcessProfile > ( processes ) ) ; this . resources = Collections . unmodifiableList ( new ArrayList < ResourceProfile > ( resources ) ) ; } public String getName ( ) { return name ; } public CoreProfile getCore ( ) { return core ; } public SessionProfile getSession ( ) { return session ; } public List < ProcessProfile > getProcesses ( ) { return processes ; } public List < ResourceProfile > getResources ( ) { return resources ; } @ Deprecated public static GateProfile loadFrom ( String name , Properties properties , ClassLoader loader ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( loader == null ) { throw new IllegalArgumentException ( "" ) ; } return loadFrom ( name , properties , ProfileContext . system ( loader ) ) ; } public static GateProfile loadFrom ( String name , Properties properties , ProfileContext context ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( properties == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" ) ; Properties copy = ( Properties ) properties . clone ( ) ; CoreProfile core = CoreProfile . loadFrom ( copy , context ) ; CoreProfile . removeCorrespondingKeys ( copy ) ; SessionProfile session = SessionProfile . loadFrom ( copy , context ) ; SessionProfile . removeCorrespondingKeys ( copy ) ; Collection < ? extends ProcessProfile > processes = ProcessProfile . loadFrom ( copy , context ) ; ProcessProfile . removeCorrespondingKeys ( copy ) ; Collection < ? extends ResourceProfile > resources = ResourceProfile . loadFrom ( copy , context ) ; ResourceProfile . removeCorrespondingKeys ( copy ) ; if ( copy . isEmpty ( ) == false ) { WGLOG . warn ( "" , copy . keySet ( ) ) ; } return new GateProfile ( name , core , session , processes , resources ) ; } } package com . asakusafw . windgate . core ; import java . io . IOException ; import java . text . MessageFormat ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public abstract class BaseProfile < S extends BaseProfile < S , T > , T extends BaseProvider < S > > { static final WindGateLogger WGLOG = new WindGateCoreLogger ( BaseProfile . class ) ; static final Logger LOG = LoggerFactory . getLogger ( BaseProfile . class ) ; public static final char QUALIFIER = '' ; public abstract Class < ? extends T > getProviderClass ( ) ; public abstract ProfileContext getContext ( ) ; @ Deprecated public ClassLoader getClassLoader ( ) { return getContext ( ) . getClassLoader ( ) ; } protected abstract S getThis ( ) ; protected static < T extends BaseProvider < ? > > Class < ? extends T > loadProviderClass ( String className , ProfileContext context , Class < T > providerInterface ) { if ( className == null ) { throw new IllegalArgumentException ( "" ) ; } if ( context == null ) { throw new IllegalArgumentException ( "" ) ; } if ( providerInterface == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , className ) ; Class < ? > loaded ; try { loaded = context . getClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { WGLOG . error ( "" , className ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , className ) , e ) ; } if ( providerInterface . isAssignableFrom ( loaded ) == false ) { WGLOG . error ( "" , className ) ; throw new IllegalArgumentException ( MessageFormat . format ( "" , className , providerInterface . getName ( ) ) ) ; } return loaded . asSubclass ( providerInterface ) ; } public T createProvider ( ) throws IOException { LOG . debug ( "" , getProviderClass ( ) . getName ( ) ) ; T instance ; try { instance = getProviderClass ( ) . newInstance ( ) ; } catch ( Exception e ) { WGLOG . error ( e , "" , getProviderClass ( ) . getName ( ) ) ; throw new IOException ( MessageFormat . format ( "" , getProviderClass ( ) . getName ( ) ) , e ) ; } instance . configure ( getThis ( ) ) ; return instance ; } } package com . asakusafw . windgate . bootstrap ; package com . asakusafw . windgate . bootstrap ; public enum ExecutionKind { BEGIN ( "" , true , false ) , CONTINUE ( "" , false , false ) , END ( "" , false , true ) , ONESHOT ( "" , true , true ) , ; public final String symbol ; public final boolean createsSession ; public final boolean completesSession ; private ExecutionKind ( String symbol , boolean createsSession , boolean completesSession ) { assert symbol != null ; this . symbol = symbol ; this . createsSession = createsSession ; this . completesSession = completesSession ; } public static ExecutionKind parse ( String symbol ) { if ( symbol == null ) { throw new IllegalArgumentException ( "" ) ; } for ( ExecutionKind kind : ExecutionKind . values ( ) ) { if ( symbol . equals ( kind . symbol ) ) { return kind ; } } return null ; } @ Override public String toString ( ) { return symbol ; } } package com . asakusafw . windgate . bootstrap ; import java . io . File ; import java . net . URI ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import java . util . Properties ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . apache . commons . cli . ParseException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . windgate . core . GateProfile ; import com . asakusafw . windgate . core . GateScript ; import com . asakusafw . windgate . core . GateTask ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . WindGateLogger ; public final class WindGate { static final WindGateLogger WGLOG = new WindGateBootstrapLogger ( WindGate . class ) ; static final Logger LOG = LoggerFactory . getLogger ( WindGate . class ) ; static final Option OPT_MODE ; static final Option OPT_PROFILE ; static final Option OPT_SCRIPT ; static final Option OPT_SESSION_ID ; static final Option OPT_PLUGIN ; static final Option OPT_ARGUMENTS ; private static final Options OPTIONS ; static { OPT_MODE = new Option ( "" , true , "" ) ; { StringBuilder buf = new StringBuilder ( ) ; for ( ExecutionKind kind : ExecutionKind . values ( ) ) { if ( buf . length ( ) > ) { buf . append ( '' ) ; } buf . append ( kind . symbol ) ; } OPT_MODE . setArgName ( buf . toString ( ) ) ; } OPT_MODE . setRequired ( true ) ; OPT_PROFILE = new Option ( "" , true , "" ) ; OPT_PROFILE . setArgName ( "" ) ; OPT_PROFILE . setRequired ( true ) ; OPT_SCRIPT = new Option ( "" , true , "" ) ; OPT_SCRIPT . setArgName ( "" ) ; OPT_SCRIPT . setRequired ( true ) ; OPT_SESSION_ID = new Option ( "" , true , "" ) ; OPT_SESSION_ID . setArgName ( "" ) ; OPT_SESSION_ID . setRequired ( true ) ; OPT_PLUGIN = new Option ( "" , true , "" ) ; OPT_PLUGIN . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN . setRequired ( false ) ; OPT_ARGUMENTS = new Option ( "" , true , "" ) ; OPT_ARGUMENTS . setArgName ( "" ) ; OPT_ARGUMENTS . setRequired ( false ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_MODE ) ; OPTIONS . addOption ( OPT_PROFILE ) ; OPTIONS . addOption ( OPT_SCRIPT ) ; OPTIONS . addOption ( OPT_SESSION_ID ) ; OPTIONS . addOption ( OPT_PLUGIN ) ; OPTIONS . addOption ( OPT_ARGUMENTS ) ; } private WindGate ( ) { return ; } public static void main ( String ... args ) { CommandLineUtil . prepareLogContext ( ) ; CommandLineUtil . prepareRuntimeContext ( ) ; WGLOG . info ( "" ) ; long start = System . currentTimeMillis ( ) ; int status = execute ( args ) ; long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , status , end - start ) ; System . exit ( status ) ; } static int execute ( String [ ] args ) { GateTask task ; try { Configuration conf = parseConfiguration ( args ) ; task = new GateTask ( conf . profile , conf . script , conf . sessionId , conf . mode . createsSession , conf . mode . completesSession , conf . arguments ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , WindGate . class . getName ( ) ) , OPTIONS , true ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; WGLOG . error ( e , "" ) ; return ; } try { if ( RuntimeContext . get ( ) . canExecute ( task ) ) { task . execute ( ) ; } return ; } catch ( Exception e ) { WGLOG . error ( e , "" ) ; return ; } finally { task . close ( ) ; } } static Configuration parseConfiguration ( String [ ] args ) throws ParseException { assert args != null ; LOG . debug ( "" , Arrays . toString ( args ) ) ; CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String mode = cmd . getOptionValue ( OPT_MODE . getOpt ( ) ) ; LOG . debug ( "" , mode ) ; String profile = cmd . getOptionValue ( OPT_PROFILE . getOpt ( ) ) ; LOG . debug ( "" , profile ) ; String script = cmd . getOptionValue ( OPT_SCRIPT . getOpt ( ) ) ; LOG . debug ( "" , script ) ; String sessionId = cmd . getOptionValue ( OPT_SESSION_ID . getOpt ( ) ) ; LOG . debug ( "" , sessionId ) ; String plugins = cmd . getOptionValue ( OPT_PLUGIN . getOpt ( ) ) ; LOG . debug ( "" , plugins ) ; String arguments = cmd . getOptionValue ( OPT_ARGUMENTS . getOpt ( ) ) ; LOG . debug ( "" , arguments ) ; LOG . debug ( "" , plugins ) ; List < File > pluginFiles = CommandLineUtil . parseFileList ( plugins ) ; ClassLoader loader = CommandLineUtil . buildPluginLoader ( WindGate . class . getClassLoader ( ) , pluginFiles ) ; Configuration result = new Configuration ( ) ; result . mode = ExecutionKind . parse ( mode ) ; if ( result . mode == null ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , mode , Arrays . toString ( ExecutionKind . values ( ) ) ) ) ; } LOG . debug ( "" , profile ) ; try { ProfileContext context = ProfileContext . system ( loader ) ; URI uri = CommandLineUtil . toUri ( profile ) ; Properties properties = CommandLineUtil . loadProperties ( uri , loader ) ; result . profile = GateProfile . loadFrom ( CommandLineUtil . toName ( uri ) , properties , context ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile ) , e ) ; } LOG . debug ( "" , script ) ; try { URI uri = CommandLineUtil . toUri ( script ) ; Properties properties = CommandLineUtil . loadProperties ( uri , loader ) ; result . script = GateScript . loadFrom ( CommandLineUtil . toName ( uri ) , properties , loader ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , script ) , e ) ; } if ( sessionId . isEmpty ( ) ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , sessionId ) ) ; } result . sessionId = sessionId ; LOG . debug ( "" , arguments ) ; result . arguments = CommandLineUtil . parseArguments ( arguments ) ; LOG . debug ( "" ) ; return result ; } static final class Configuration { ExecutionKind mode ; GateProfile profile ; GateScript script ; String sessionId ; ParameterList arguments ; } } package com . asakusafw . windgate . bootstrap ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import com . asakusafw . windgate . core . WindGateLogger ; public class WindGateBootstrapLogger extends WindGateLogger { private static final ResourceBundle BUNDLE = ResourceBundle . getBundle ( "" ) ; public WindGateBootstrapLogger ( Class < ? > target ) { super ( target , "" ) ; } @ Override protected String getMessage ( String code , Object ... arguments ) { String messagePattern = BUNDLE . getString ( code ) ; return MessageFormat . format ( messagePattern , arguments ) ; } } package com . asakusafw . windgate . bootstrap ; import java . io . File ; import java . net . URI ; import java . text . MessageFormat ; import java . util . Arrays ; import java . util . List ; import java . util . Properties ; import org . apache . commons . cli . BasicParser ; import org . apache . commons . cli . CommandLine ; import org . apache . commons . cli . CommandLineParser ; import org . apache . commons . cli . HelpFormatter ; import org . apache . commons . cli . Option ; import org . apache . commons . cli . Options ; import org . apache . commons . cli . ParseException ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . windgate . core . AbortTask ; import com . asakusafw . windgate . core . GateProfile ; import com . asakusafw . windgate . core . ProfileContext ; import com . asakusafw . windgate . core . WindGateLogger ; public final class WindGateAbort { static final WindGateLogger WGLOG = new WindGateBootstrapLogger ( WindGateAbort . class ) ; static final Logger LOG = LoggerFactory . getLogger ( WindGateAbort . class ) ; static final Option OPT_PROFILE ; static final Option OPT_SESSION_ID ; static final Option OPT_PLUGIN ; private static final Options OPTIONS ; static { OPT_PROFILE = new Option ( "" , true , "" ) ; OPT_PROFILE . setArgName ( "" ) ; OPT_PROFILE . setRequired ( true ) ; OPT_SESSION_ID = new Option ( "" , true , "" ) ; OPT_SESSION_ID . setArgName ( "" ) ; OPT_SESSION_ID . setRequired ( false ) ; OPT_PLUGIN = new Option ( "" , true , "" ) ; OPT_PLUGIN . setArgName ( "" + File . pathSeparatorChar + "" ) ; OPT_PLUGIN . setRequired ( false ) ; OPTIONS = new Options ( ) ; OPTIONS . addOption ( OPT_PROFILE ) ; OPTIONS . addOption ( OPT_SESSION_ID ) ; OPTIONS . addOption ( OPT_PLUGIN ) ; } private WindGateAbort ( ) { return ; } public static void main ( String ... args ) { CommandLineUtil . prepareLogContext ( ) ; CommandLineUtil . prepareRuntimeContext ( ) ; WGLOG . info ( "" ) ; long start = System . currentTimeMillis ( ) ; int status = execute ( args ) ; long end = System . currentTimeMillis ( ) ; WGLOG . info ( "" , status , end - start ) ; System . exit ( status ) ; } static int execute ( String [ ] args ) { AbortTask task ; try { Configuration conf = parseConfiguration ( args ) ; task = new AbortTask ( conf . profile , conf . sessionId ) ; } catch ( Exception e ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( Integer . MAX_VALUE ) ; formatter . printHelp ( MessageFormat . format ( "" , WindGateAbort . class . getName ( ) ) , OPTIONS , true ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; WGLOG . error ( e , "" ) ; return ; } try { if ( RuntimeContext . get ( ) . canExecute ( task ) ) { task . execute ( ) ; } return ; } catch ( Exception e ) { WGLOG . error ( e , "" ) ; return ; } } static Configuration parseConfiguration ( String [ ] args ) throws ParseException { assert args != null ; LOG . debug ( "" , Arrays . toString ( args ) ) ; CommandLineParser parser = new BasicParser ( ) ; CommandLine cmd = parser . parse ( OPTIONS , args ) ; String profile = cmd . getOptionValue ( OPT_PROFILE . getOpt ( ) ) ; LOG . debug ( "" , profile ) ; String sessionId = cmd . getOptionValue ( OPT_SESSION_ID . getOpt ( ) ) ; LOG . debug ( "" , sessionId ) ; String plugins = cmd . getOptionValue ( OPT_PLUGIN . getOpt ( ) ) ; LOG . debug ( "" , plugins ) ; LOG . debug ( "" , plugins ) ; List < File > pluginFiles = CommandLineUtil . parseFileList ( plugins ) ; ClassLoader loader = CommandLineUtil . buildPluginLoader ( WindGateAbort . class . getClassLoader ( ) , pluginFiles ) ; Configuration result = new Configuration ( ) ; LOG . debug ( "" , profile ) ; try { ProfileContext context = ProfileContext . system ( loader ) ; URI uri = CommandLineUtil . toUri ( profile ) ; Properties properties = CommandLineUtil . loadProperties ( uri , loader ) ; result . profile = GateProfile . loadFrom ( CommandLineUtil . toName ( uri ) , properties , context ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( MessageFormat . format ( "" , profile ) , e ) ; } if ( sessionId == null || sessionId . isEmpty ( ) ) { result . sessionId = null ; } else { result . sessionId = sessionId ; } LOG . debug ( "" ) ; return result ; } static final class Configuration { GateProfile profile ; String sessionId ; } } package com . asakusafw . windgate . bootstrap ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . net . URI ; import java . net . URISyntaxException ; import java . net . URL ; import java . net . URLClassLoader ; import java . security . AccessController ; import java . security . PrivilegedAction ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . TreeMap ; import java . util . regex . Pattern ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . slf4j . MDC ; import com . asakusafw . runtime . core . context . RuntimeContext ; import com . asakusafw . windgate . core . ParameterList ; import com . asakusafw . windgate . core . WindGateLogger ; public final class CommandLineUtil { static final WindGateLogger WGLOG = new WindGateBootstrapLogger ( CommandLineUtil . class ) ; static final Logger LOG = LoggerFactory . getLogger ( CommandLineUtil . class ) ; public static void prepareRuntimeContext ( ) { RuntimeContext . set ( RuntimeContext . DEFAULT . apply ( System . getenv ( ) ) ) ; RuntimeContext . get ( ) . verifyApplication ( WindGate . class . getClassLoader ( ) ) ; LOG . debug ( "" , RuntimeContext . get ( ) ) ; } public static final String LOG_CONTEXT_PREFIX = "" ; public static final String SCHEME_CLASSPATH = "" ; public static void prepareLogContext ( ) { Map < String , String > registered = new TreeMap < String , String > ( ) ; Properties properties = System . getProperties ( ) ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { if ( ( entry . getKey ( ) instanceof String ) == false || ( entry . getValue ( ) instanceof String ) == false ) { continue ; } String key = ( String ) entry . getKey ( ) ; if ( key . startsWith ( LOG_CONTEXT_PREFIX ) == false ) { continue ; } String value = ( String ) entry . getValue ( ) ; String name = key . substring ( LOG_CONTEXT_PREFIX . length ( ) ) ; MDC . put ( name , value ) ; registered . put ( name , value ) ; } LOG . debug ( "" , registered ) ; } public static String toName ( URI uri ) { if ( uri == null ) { throw new IllegalArgumentException ( "" ) ; } String path = uri . getSchemeSpecificPart ( ) ; if ( path == null ) { return uri . toString ( ) ; } String name = path . substring ( path . lastIndexOf ( '' ) + ) ; if ( name . endsWith ( "" ) ) { return name . substring ( , name . length ( ) - "" . length ( ) ) ; } else { return name ; } } public static URI toUri ( String path ) throws URISyntaxException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } URI uri = new URI ( path ) ; if ( uri . getScheme ( ) == null || uri . getScheme ( ) . length ( ) != ) { return uri ; } String os = System . getProperty ( "" , "" ) ; LOG . debug ( "" , os ) ; if ( os . toLowerCase ( ) . startsWith ( "" ) == false ) { return uri ; } File file = new File ( path ) ; uri = file . toURI ( ) ; LOG . debug ( "" , path , uri ) ; return uri ; } public static Properties loadProperties ( URI path , ClassLoader loader ) throws IOException { if ( path == null ) { throw new IllegalArgumentException ( "" ) ; } LOG . debug ( "" , path ) ; String scheme = path . getScheme ( ) ; if ( scheme == null ) { File file = new File ( path . getPath ( ) ) ; LOG . debug ( "" , file ) ; FileInputStream in = new FileInputStream ( file ) ; return loadProperties ( path , in ) ; } else if ( scheme . equals ( SCHEME_CLASSPATH ) ) { ClassLoader cl = loader == null ? ClassLoader . getSystemClassLoader ( ) : loader ; String rest = path . getSchemeSpecificPart ( ) ; LOG . debug ( "" , rest ) ; InputStream in = cl . getResourceAsStream ( rest ) ; if ( in == null ) { throw new FileNotFoundException ( MessageFormat . format ( "" , path . toString ( ) ) ) ; } return loadProperties ( path , in ) ; } else { URL url = path . toURL ( ) ; LOG . debug ( "" , url ) ; InputStream in = url . openStream ( ) ; return loadProperties ( path , in ) ; } } private static Properties loadProperties ( URI uri , InputStream in ) throws IOException { assert uri != null ; assert in != null ; try { Properties properties = new Properties ( ) ; properties . load ( new BufferedInputStream ( in ) ) ; return properties ; } finally { in . close ( ) ; } } public static List < File > parseFileList ( String fileListOrNull ) { if ( fileListOrNull == null || fileListOrNull . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < File > results = new ArrayList < File > ( ) ; int start = ; while ( true ) { int index = fileListOrNull . indexOf ( File . pathSeparatorChar , start ) ; if ( index < ) { break ; } if ( start != index ) { results . add ( new File ( fileListOrNull . substring ( start , index ) . trim ( ) ) ) ; } start = index + ; } results . add ( new File ( fileListOrNull . substring ( start ) . trim ( ) ) ) ; return results ; } public static ClassLoader buildPluginLoader ( final ClassLoader parent , List < File > files ) { if ( files == null ) { throw new IllegalArgumentException ( "" ) ; } final List < URL > pluginLocations = new ArrayList < URL > ( ) ; for ( File file : files ) { try { if ( file . exists ( ) == false ) { throw new FileNotFoundException ( MessageFormat . format ( "" , file . getAbsolutePath ( ) ) ) ; } URL url = file . toURI ( ) . toURL ( ) ; pluginLocations . add ( url ) ; } catch ( IOException e ) { WGLOG . warn ( e , "" , file . getAbsolutePath ( ) ) ; } } ClassLoader serviceLoader = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { @ Override public ClassLoader run ( ) { URLClassLoader loader = new URLClassLoader ( pluginLocations . toArray ( new URL [ pluginLocations . size ( ) ] ) , parent ) ; return loader ; } } ) ; return serviceLoader ; } private static final Pattern PAIRS = Pattern . compile ( "" ) ; private static final Pattern KEY_VALUE = Pattern . compile ( "" ) ; public static ParameterList parseArguments ( String arguments ) { if ( arguments == null || arguments . isEmpty ( ) ) { return new ParameterList ( ) ; } Map < String , String > results = new LinkedHashMap < String , String > ( ) ; String [ ] pairs = PAIRS . split ( arguments ) ; for ( String pair : pairs ) { if ( pair . isEmpty ( ) ) { continue ; } String [ ] kv = KEY_VALUE . split ( pair ) ; if ( kv . length == ) { addArgument ( results , "" , "" ) ; } else if ( kv . length == && kv [ ] . equals ( pair ) == false ) { addArgument ( results , unescape ( kv [ ] ) , "" ) ; } else if ( kv . length == ) { addArgument ( results , unescape ( kv [ ] ) , unescape ( kv [ ] ) ) ; } else { WGLOG . warn ( "" , pair ) ; } } return new ParameterList ( results ) ; } private static void addArgument ( Map < String , String > results , String key , String value ) { assert results != null ; assert key != null ; assert value != null ; if ( results . containsKey ( key ) ) { WGLOG . warn ( "" , key , value ) ; } else { results . put ( key , value ) ; } } private static String unescape ( String string ) { assert string != null ; StringBuilder buf = new StringBuilder ( ) ; int start = ; while ( true ) { int index = string . indexOf ( '' , start ) ; if ( index < ) { break ; } buf . append ( string . substring ( start , index ) ) ; if ( index != string . length ( ) - ) { buf . append ( string . charAt ( index + ) ) ; start = index + ; } else { buf . append ( string . charAt ( index ) ) ; start = index + ; } } if ( start < string . length ( ) ) { buf . append ( string . substring ( start ) ) ; } return buf . toString ( ) ; } private CommandLineUtil ( ) { return ; } } package com . asakusafw . windgate . bootstrap ; import static org . hamcrest . CoreMatchers . * ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . net . URI ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . junit . Assume ; import org . junit . Rule ; import org . junit . Test ; import org . junit . rules . TemporaryFolder ; public class CommandLineUtilTest { @ Rule public TemporaryFolder folder = new TemporaryFolder ( ) ; @ Test public void loadProperties_local ( ) throws Exception { Properties p = new Properties ( ) ; p . setProperty ( "" , "" ) ; File file = store ( p ) ; Properties loaded = CommandLineUtil . loadProperties ( new URI ( file . toURI ( ) . getPath ( ) ) , null ) ; assertThat ( loaded , is ( p ) ) ; } @ Test public void loadProperties_uri ( ) throws Exception { Properties p = new Properties ( ) ; p . setProperty ( "" , "" ) ; File file = store ( p ) ; Properties loaded = CommandLineUtil . loadProperties ( file . toURI ( ) , null ) ; assertThat ( loaded , is ( p ) ) ; } @ Test public void loadProperties_classpath ( ) throws Exception { String className = getClass ( ) . getName ( ) ; String packageName = className . substring ( , className . lastIndexOf ( '' ) ) ; URI uri = new URI ( "" + packageName . replace ( '' , '' ) + "" ) ; Properties loaded = CommandLineUtil . loadProperties ( uri , getClass ( ) . getClassLoader ( ) ) ; Properties p = new Properties ( ) ; p . setProperty ( "" , "" ) ; assertThat ( loaded , is ( p ) ) ; } @ Test ( expected = IOException . class ) public void loadProperties_classpath_missing ( ) throws Exception { URI uri = new URI ( "" ) ; CommandLineUtil . loadProperties ( uri , null ) ; } @ Test public void parseFileList ( ) throws Exception { File a = folder . newFile ( "" ) ; File b = folder . newFile ( "" ) ; File c = folder . newFile ( "" ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( a ) ; buf . append ( File . pathSeparatorChar ) ; buf . append ( b ) ; buf . append ( File . pathSeparatorChar ) ; buf . append ( c ) ; List < File > result = canonicalize ( CommandLineUtil . parseFileList ( buf . toString ( ) ) ) ; assertThat ( result , is ( Arrays . asList ( a , b , c ) ) ) ; } @ Test public void parseFileList_null ( ) { List < File > result = canonicalize ( CommandLineUtil . parseFileList ( null ) ) ; assertThat ( result , is ( Arrays . < File > asList ( ) ) ) ; } @ Test public void parseFileList_empty ( ) { List < File > result = canonicalize ( CommandLineUtil . parseFileList ( "" ) ) ; assertThat ( result , is ( Arrays . < File > asList ( ) ) ) ; } private List < File > canonicalize ( List < File > list ) { List < File > results = new ArrayList < File > ( ) ; for ( File f : list ) { try { results . add ( f . getCanonicalFile ( ) ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } } return results ; } @ Test public void buildPluginLoader ( ) throws Exception { File cp1 = folder . newFolder ( "" ) ; File cp2 = folder . newFolder ( "" ) ; new File ( cp1 , "" ) . createNewFile ( ) ; new File ( cp2 , "" ) . createNewFile ( ) ; ClassLoader cl = CommandLineUtil . buildPluginLoader ( getClass ( ) . getClassLoader ( ) , Arrays . asList ( cp1 , cp2 ) ) ; assertThat ( cl . getResource ( "" ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( cl . getResource ( "" ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( cl . getResource ( "" ) , is ( nullValue ( ) ) ) ; } @ Test public void buildPluginLoader_missing_path ( ) throws Exception { File cp1 = folder . newFolder ( "" ) ; File cp2 = folder . newFolder ( "" ) ; new File ( cp1 , "" ) . createNewFile ( ) ; Assume . assumeTrue ( cp2 . delete ( ) ) ; ClassLoader cl = CommandLineUtil . buildPluginLoader ( getClass ( ) . getClassLoader ( ) , Arrays . asList ( cp1 , cp2 ) ) ; assertThat ( cl . getResource ( "" ) , is ( not ( nullValue ( ) ) ) ) ; assertThat ( cl . getResource ( "" ) , is ( nullValue ( ) ) ) ; assertThat ( cl . getResource ( "" ) , is ( nullValue ( ) ) ) ; } @ Test public void parseArguments ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_multiple ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_escaped ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_empty_keyvaule ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_empty_key ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_empty_value ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_duplicate_pair ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_empty ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_null ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( null ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_empty_pair ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_invalid_pair ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; assertThat ( parsed , is ( answer ) ) ; } @ Test public void parseArguments_keyonly ( ) { Map < String , String > parsed = CommandLineUtil . parseArguments ( "" ) . getPairs ( ) ; Map < String , String > answer = new HashMap < String , String > ( ) ; answer . put ( "" , "" ) ; assertThat ( parsed , is ( answer ) ) ; } private File store ( Properties p ) throws IOException , FileNotFoundException { File file = folder . newFile ( "" ) ; FileOutputStream out = new FileOutputStream ( file ) ; try { p . store ( out , "" ) ; } finally { out . close ( ) ; } return file ; } } package com . mcbans . firestar . mcbans ; import com . mcbans . firestar . mcbans . bukkitListeners . PlayerListener ; import com . mcbans . firestar . mcbans . callBacks . BanSync ; import com . mcbans . firestar . mcbans . callBacks . MainCallBack ; import com . mcbans . firestar . mcbans . callBacks . serverChoose ; import com . mcbans . firestar . mcbans . commands . CommandHandler ; import com . mcbans . firestar . mcbans . log . ActionLog ; import com . mcbans . firestar . mcbans . log . LogLevels ; import com . mcbans . firestar . mcbans . log . Logger ; import de . diddiz . LogBlock . LogBlock ; import fr . neatmonster . nocheatplus . NoCheatPlus ; import org . bukkit . command . Command ; import org . bukkit . command . CommandSender ; import org . bukkit . entity . Player ; import org . bukkit . plugin . Plugin ; import org . bukkit . plugin . PluginManager ; import org . bukkit . plugin . java . JavaPlugin ; import java . util . HashMap ; public class BukkitInterface extends JavaPlugin { private CommandHandler commandHandle ; private PlayerListener bukkitPlayer = new PlayerListener ( this ) ; public int taskID = ; public HashMap < String , Integer > connectionData = new HashMap < String , Integer > ( ) ; public HashMap < String , Long > resetTime = new HashMap < String , Long > ( ) ; public Settings Settings ; public Language Language = null ; public Thread callbackThread = null ; public Thread syncBan = null ; public boolean syncRunning = false ; public long lastID = ; public ActionLog actionLog = null ; public LogBlock logblock = null ; public long lastCallBack = ; public long lastSync = ; public NoCheatPlus noCheatPlus = null ; public boolean notSelectedServer = true ; public String apiServers = "" ; public String apiServer = "" ; private String apiKey = "" ; public BukkitPermissions Permissions = null ; public Logger logger = new Logger ( this ) ; public void onDisable ( ) { if ( callbackThread != null ) { if ( callbackThread . isAlive ( ) ) { callbackThread . interrupt ( ) ; } } if ( syncBan != null ) { if ( syncBan . isAlive ( ) ) { syncBan . interrupt ( ) ; } } log ( LogLevels . INFO , "" ) ; } public void onEnable ( ) { PluginManager pm = getServer ( ) . getPluginManager ( ) ; pm . registerEvents ( bukkitPlayer , this ) ; if ( ! this . getServer ( ) . getOnlineMode ( ) ) { logger . log ( LogLevels . FATAL , "" ) ; pm . disablePlugin ( pluginInterface ( "" ) ) ; return ; } Settings = new Settings ( ) ; if ( Settings . exists ) { pm . disablePlugin ( pluginInterface ( "" ) ) ; return ; } this . apiKey = Settings . getString ( "" ) ; String language ; language = Settings . getString ( "" ) ; log ( LogLevels . INFO , "" + language ) ; Language = new Language ( this ) ; if ( Settings . getBoolean ( "" ) ) { log ( LogLevels . INFO , "" ) ; actionLog = new ActionLog ( this , Settings . getString ( "" ) ) ; actionLog . write ( "" ) ; } else { log ( LogLevels . INFO , "" ) ; } Permissions = new BukkitPermissions ( Settings , this ) ; commandHandle = new CommandHandler ( Settings , this ) ; MainCallBack thisThread = new MainCallBack ( this ) ; callbackThread = new Thread ( thisThread ) ; callbackThread . start ( ) ; BanSync syncBanRunner = new BanSync ( this ) ; syncBan = new Thread ( syncBanRunner ) ; syncBan . start ( ) ; serverChoose serverChooser = new serverChoose ( this ) ; ( new Thread ( serverChooser ) ) . start ( ) ; Plugin logBlock = pm . getPlugin ( "" ) ; if ( logBlock != null ) { logblock = ( LogBlock ) logBlock ; log ( LogLevels . INFO , "" ) ; } Plugin NoCheat = pm . getPlugin ( "" ) ; if ( NoCheat != null ) { noCheatPlus = ( ( NoCheatPlus ) NoCheat ) ; log ( LogLevels . INFO , "" ) ; } log ( LogLevels . INFO , "" ) ; } @ Override public boolean onCommand ( CommandSender sender , Command command , String commandLabel , String [ ] args ) { return commandHandle . execCommand ( command . getName ( ) , args , sender ) ; } public void log ( String message ) { log ( LogLevels . NONE , message ) ; } public void log ( LogLevels type , String message ) { if ( actionLog != null ) { actionLog . write ( message ) ; } logger . log ( type , message ) ; } public void broadcastBanView ( String msg ) { for ( String player : Permissions . getPlayersBan ( ) ) { this . getServer ( ) . getPlayer ( player ) . sendMessage ( Settings . getPrefix ( ) + "" + msg ) ; } } public void broadcastJoinView ( String msg ) { for ( String player : Permissions . getPlayersJoin ( ) ) { this . getServer ( ) . getPlayer ( player ) . sendMessage ( Settings . getPrefix ( ) + "" + msg ) ; } } public void broadcastJoinView ( String msg , String playername ) { for ( String player : Permissions . getPlayersJoin ( ) ) { if ( playername != player ) { this . getServer ( ) . getPlayer ( player ) . sendMessage ( Settings . getPrefix ( ) + "" + msg ) ; } } } public void broadcastAltView ( String msg ) { for ( String player : Permissions . getPlayersAlts ( ) ) { this . getServer ( ) . getPlayer ( player ) . sendMessage ( Settings . getPrefix ( ) + "" + msg ) ; } } public void broadcastKickView ( String msg ) { for ( String player : Permissions . getPlayersKick ( ) ) { this . getServer ( ) . getPlayer ( player ) . sendMessage ( Settings . getPrefix ( ) + "" + msg ) ; } } public void broadcastAll ( String msg ) { for ( Player player : this . getServer ( ) . getOnlinePlayers ( ) ) { player . sendMessage ( Settings . getPrefix ( ) + "" + msg ) ; } } public void broadcastPlayer ( String Player , String msg ) { Player target = this . getServer ( ) . getPlayer ( Player ) ; if ( target != null ) { target . sendMessage ( Settings . getPrefix ( ) + "" + msg ) ; } else { System . out . print ( Settings . getPrefix ( ) + "" + msg ) ; } } public String getApiKey ( ) { return this . apiKey ; } public void broadcastPlayer ( Player target , String msg ) { target . sendMessage ( Settings . getPrefix ( ) + "" + msg ) ; } public Plugin pluginInterface ( String pluginName ) { return this . getServer ( ) . getPluginManager ( ) . getPlugin ( pluginName ) ; } } package com . mcbans . firestar . mcbans . request ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . log . LogLevels ; import com . mcbans . firestar . mcbans . org . json . JSONException ; import com . mcbans . firestar . mcbans . org . json . JSONObject ; import java . io . BufferedReader ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . io . UnsupportedEncodingException ; import java . net . URL ; import java . net . URLConnection ; import java . net . URLEncoder ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; @ SuppressWarnings ( "" ) public class JsonHandler { private String apiKey = "" ; private BukkitInterface MCBans ; private boolean debug = false ; public JsonHandler ( BukkitInterface p ) { MCBans = p ; apiKey = MCBans . getApiKey ( ) ; debug = MCBans . Settings . getBoolean ( "" ) ; } public JSONObject get_data ( String json_text ) { try { return new JSONObject ( json_text ) ; } catch ( JSONException e ) { if ( debug ) { e . printStackTrace ( ) ; } } return null ; } public HashMap < String , String > mainRequest ( HashMap < String , String > items ) { HashMap < String , String > out = new HashMap < String , String > ( ) ; String url_req = this . urlparse ( items ) ; String json_text = this . request_from_api ( url_req ) ; JSONObject output = this . get_data ( json_text ) ; if ( output != null ) { Iterator < String > i = output . keys ( ) ; if ( i != null ) { while ( i . hasNext ( ) ) { String next = i . next ( ) ; try { out . put ( next , output . getString ( next ) ) ; } catch ( JSONException e ) { if ( debug ) { MCBans . log ( LogLevels . SEVERE , "" ) ; e . printStackTrace ( ) ; } } } } } return out ; } public JSONObject hdl_jobj ( HashMap < String , String > items ) { String urlReq = urlparse ( items ) ; String jsonText = request_from_api ( urlReq ) ; return get_data ( jsonText ) ; } public String request_from_api ( String data ) { try { if ( debug ) { MCBans . log ( LogLevels . INFO , "" ) ; } URL url = new URL ( "" + MCBans . apiServer + "" + this . apiKey ) ; URLConnection conn = url . openConnection ( ) ; conn . setConnectTimeout ( ) ; conn . setReadTimeout ( ) ; conn . setDoOutput ( true ) ; OutputStreamWriter wr = new OutputStreamWriter ( conn . getOutputStream ( ) ) ; wr . write ( data ) ; wr . flush ( ) ; StringBuilder buf = new StringBuilder ( ) ; BufferedReader rd = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; String line ; while ( ( line = rd . readLine ( ) ) != null ) { buf . append ( line ) ; } String result = buf . toString ( ) ; if ( debug ) { MCBans . log ( LogLevels . INFO , result ) ; } wr . close ( ) ; rd . close ( ) ; return result ; } catch ( Exception e ) { if ( debug ) { if ( MCBans != null ) { MCBans . log ( LogLevels . SEVERE , "" ) ; } e . printStackTrace ( ) ; } return "" ; } } public String request_from_api ( String data , String Server ) { try { if ( debug ) { MCBans . log ( LogLevels . INFO , "" ) ; } URL url = new URL ( "" + Server + "" + this . apiKey ) ; URLConnection conn = url . openConnection ( ) ; conn . setConnectTimeout ( ) ; conn . setReadTimeout ( ) ; conn . setDoOutput ( true ) ; OutputStreamWriter wr = new OutputStreamWriter ( conn . getOutputStream ( ) ) ; wr . write ( data ) ; wr . flush ( ) ; StringBuilder buf = new StringBuilder ( ) ; BufferedReader rd = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; String line ; while ( ( line = rd . readLine ( ) ) != null ) { buf . append ( line ) ; } String result = buf . toString ( ) ; if ( debug ) { MCBans . log ( LogLevels . INFO , result ) ; } wr . close ( ) ; rd . close ( ) ; return result ; } catch ( Exception e ) { if ( debug ) { if ( MCBans != null ) { MCBans . log ( LogLevels . SEVERE , "" ) ; } e . printStackTrace ( ) ; } return "" ; } } public String urlparse ( HashMap < String , String > items ) { String data = "" ; try { for ( Map . Entry < String , String > entry : items . entrySet ( ) ) { String key = entry . getKey ( ) ; String val = entry . getValue ( ) ; if ( data . equals ( "" ) ) { data = URLEncoder . encode ( key , "" ) + "" + URLEncoder . encode ( val , "" ) ; } else { data += "" + URLEncoder . encode ( key , "" ) + "" + URLEncoder . encode ( val , "" ) ; } } } catch ( UnsupportedEncodingException e ) { if ( debug ) { e . printStackTrace ( ) ; } } return data ; } } package com . mcbans . firestar . mcbans . log ; import com . mcbans . firestar . mcbans . BukkitInterface ; public class Logger { private BukkitInterface MCBans = null ; public Logger ( BukkitInterface p ) { MCBans = p ; } public void log ( String message ) { log ( LogLevels . NONE , message ) ; } public void log ( LogLevels type , String message ) { switch ( type ) { case INFO : System . out . print ( "" + message ) ; break ; case WARNING : System . out . print ( "" + message ) ; break ; case SEVERE : System . out . print ( "" + message ) ; break ; case FATAL : System . out . print ( "" + message ) ; MCBans . getServer ( ) . getPluginManager ( ) . disablePlugin ( MCBans . pluginInterface ( "" ) ) ; break ; default : System . out . print ( "" + message ) ; break ; } } } package com . mcbans . firestar . mcbans . log ; public enum LogLevels { NONE , INFO , WARNING , SEVERE , FATAL } package com . mcbans . firestar . mcbans . log ; import com . mcbans . firestar . mcbans . BukkitInterface ; import java . io . FileWriter ; import java . io . StringWriter ; import java . text . DateFormat ; import java . text . SimpleDateFormat ; import java . util . Date ; public class ActionLog { private static String logFile = "" ; private static BukkitInterface MCBans = null ; private final static DateFormat df = new SimpleDateFormat ( "" ) ; public ActionLog ( BukkitInterface p , String logfile ) { logFile = logfile ; MCBans = p ; } public void write ( String msg ) { if ( MCBans . Settings . getBoolean ( "" ) ) { write ( logFile , msg ) ; } } public void write ( Exception e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { write ( logFile , stack2string ( e ) ) ; } MCBans . log ( stack2string ( e ) ) ; } public static void write ( String file , String msg ) { try { Date now = new Date ( ) ; String currentTime = ActionLog . df . format ( now ) ; FileWriter aWriter = new FileWriter ( file , true ) ; aWriter . write ( currentTime + "" + msg + System . getProperty ( "" ) ) ; aWriter . flush ( ) ; aWriter . close ( ) ; } catch ( Exception e ) { MCBans . log ( LogLevels . WARNING , stack2string ( e ) ) ; } } private static String stack2string ( Exception e ) { try { StringWriter sw = new StringWriter ( ) ; return "" + sw . toString ( ) + "" ; } catch ( Exception e2 ) { return "" ; } } } package com . mcbans . firestar . mcbans . pluginInterface ; public enum ConnectStatus { N , G , S , T , L , B , I } package com . mcbans . firestar . mcbans . pluginInterface ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . Settings ; import org . bukkit . ChatColor ; import org . bukkit . entity . Player ; @ SuppressWarnings ( "" ) public class Kick implements Runnable { private Settings Config ; private BukkitInterface MCBans ; private String PlayerName = null ; private String PlayerAdmin = null ; private String Reason = null ; public Kick ( Settings cf , BukkitInterface p , String playerName , String playerAdmin , String reason ) { Config = cf ; MCBans = p ; PlayerName = playerName ; PlayerAdmin = playerAdmin ; Reason = reason ; } @ Override public void run ( ) { while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } final Player player = MCBans . getServer ( ) . getPlayer ( PlayerName ) ; if ( player != null ) { MCBans . log ( PlayerAdmin + "" + player . getName ( ) + "" + Reason + "" ) ; MCBans . getServer ( ) . getScheduler ( ) . scheduleSyncDelayedTask ( MCBans , new Runnable ( ) { public void run ( ) { player . kickPlayer ( MCBans . Language . getFormat ( "" , player . getName ( ) , PlayerAdmin , Reason ) ) ; } } , ) ; MCBans . broadcastKickView ( ChatColor . GREEN + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , "" , true ) ) ; } else { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , "" , true ) ) ; } } } package com . mcbans . firestar . mcbans . pluginInterface ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . request . JsonHandler ; import java . util . HashMap ; public class Disconnect implements Runnable { private BukkitInterface MCBans ; private String PlayerName ; public Disconnect ( BukkitInterface p , String Player ) { MCBans = p ; PlayerName = Player ; } @ Override public void run ( ) { while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } MCBans . log ( PlayerName + "" ) ; JsonHandler webhandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , PlayerName ) ; url_items . put ( "" , "" ) ; webhandle . mainRequest ( url_items ) ; } } package com . mcbans . firestar . mcbans . pluginInterface ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . org . json . JSONException ; import com . mcbans . firestar . mcbans . org . json . JSONObject ; import com . mcbans . firestar . mcbans . request . JsonHandler ; import de . diddiz . LogBlock . BlockChange ; import de . diddiz . LogBlock . QueryParams ; import de . diddiz . LogBlock . QueryParams . BlockChangeType ; import fr . neatmonster . nocheatplus . players . NCPPlayer ; import org . bukkit . ChatColor ; import org . bukkit . OfflinePlayer ; import org . bukkit . command . CommandSender ; import org . bukkit . entity . Player ; import java . sql . SQLException ; import java . util . HashMap ; import java . util . Map . Entry ; import java . util . regex . * ; public class Ban implements Runnable { private BukkitInterface MCBans ; private String PlayerName = null ; private String PlayerIP = null ; private String PlayerAdmin = null ; private String Reason = null ; private String Action = null ; private int rollbackTime = ; private String Duration = null ; private String Measure = null ; private boolean Rollback = false ; private String Badword = null ; private JSONObject ActionData = new JSONObject ( ) ; private HashMap < String , Integer > responses = new HashMap < String , Integer > ( ) ; public Ban ( BukkitInterface p , String action , String playerName , String playerIP , String playerAdmin , String reason , String duration , String measure ) { MCBans = p ; PlayerName = playerName ; PlayerIP = playerIP ; PlayerAdmin = playerAdmin ; Reason = reason ; Duration = duration ; Rollback = MCBans . Settings . getBoolean ( "" ) ; rollbackTime = MCBans . Settings . getInteger ( "" ) ; Measure = measure ; Action = action ; responses . put ( "" , ) ; responses . put ( "" , ) ; responses . put ( "" , ) ; responses . put ( "" , ) ; } public Ban ( BukkitInterface p , String action , String playerName , String playerIP , String playerAdmin , String reason , String duration , String measure , JSONObject actionData , boolean rollback ) { MCBans = p ; PlayerName = playerName ; PlayerIP = playerIP ; PlayerAdmin = playerAdmin ; Reason = reason ; Rollback = rollback ; rollbackTime = MCBans . Settings . getInteger ( "" ) ; Duration = duration ; Measure = measure ; Action = action ; ActionData = actionData ; responses . put ( "" , ) ; responses . put ( "" , ) ; responses . put ( "" , ) ; responses . put ( "" , ) ; } public Ban ( BukkitInterface p , String action , String playerName , String playerIP , String playerAdmin , String reason , String duration , String measure , JSONObject actionData , int rollback ) { MCBans = p ; PlayerName = playerName ; PlayerIP = playerIP ; PlayerAdmin = playerAdmin ; Reason = reason ; Rollback = true ; rollbackTime = rollback ; Duration = duration ; Measure = measure ; Action = action ; ActionData = actionData ; responses . put ( "" , ) ; responses . put ( "" , ) ; responses . put ( "" , ) ; responses . put ( "" , ) ; } public void kickPlayer ( String playerToKick , final String kickString ) { final Player target = MCBans . getServer ( ) . getPlayer ( playerToKick ) ; if ( target != null ) { MCBans . getServer ( ) . getScheduler ( ) . scheduleSyncDelayedTask ( MCBans , new Runnable ( ) { public void run ( ) { target . kickPlayer ( kickString ) ; } } , ) ; } } public void run ( ) { while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } try { if ( responses . containsKey ( Action ) ) { switch ( responses . get ( Action ) ) { case : globalBan ( ) ; break ; case : localBan ( ) ; break ; case : tempBan ( ) ; break ; case : unBan ( ) ; break ; } } else { MCBans . log ( "" ) ; } } catch ( NullPointerException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } public void unBan ( ) { JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , PlayerName ) ; url_items . put ( "" , PlayerAdmin ) ; url_items . put ( "" , "" ) ; HashMap < String , String > response = webHandle . mainRequest ( url_items ) ; try { if ( ! response . containsKey ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin ) ) ; return ; } if ( response . get ( "" ) . equals ( "" ) ) { OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( PlayerName ) ; if ( d . isBanned ( ) ) { d . setBanned ( false ) ; } MCBans . log ( PlayerAdmin + "" + PlayerName + "" ) ; MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . GREEN + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin ) ) ; return ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin ) ) ; } MCBans . log ( PlayerAdmin + "" + PlayerName + "" ) ; } catch ( NullPointerException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } public void localBan ( ) { JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , PlayerName ) ; url_items . put ( "" , PlayerIP ) ; url_items . put ( "" , Reason ) ; url_items . put ( "" , PlayerAdmin ) ; if ( MCBans . logblock != null ) { if ( Rollback ) { rollback ( ) ; } } if ( ActionData != null ) { url_items . put ( "" , ActionData . toString ( ) ) ; } url_items . put ( "" , "" ) ; HashMap < String , String > response = webHandle . mainRequest ( url_items ) ; try { if ( ! response . containsKey ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( PlayerName ) ; if ( ! d . isBanned ( ) ) { d . setBanned ( true ) ; } this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; return ; } if ( response . get ( "" ) . equals ( "" ) ) { MCBans . log ( PlayerName + "" + Reason + "" + PlayerAdmin + "" ) ; this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; MCBans . broadcastAll ( ChatColor . GREEN + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; return ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } MCBans . log ( PlayerAdmin + "" + PlayerName + "" + Reason + "" ) ; } catch ( NullPointerException e ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( PlayerName ) ; if ( ! d . isBanned ( ) ) { d . setBanned ( true ) ; } this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } public void globalBan ( ) { JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , PlayerName ) ; url_items . put ( "" , PlayerIP ) ; url_items . put ( "" , Reason ) ; url_items . put ( "" , PlayerAdmin ) ; if ( MCBans . noCheatPlus != null ) { boolean foundMatch = false ; try { Pattern regex = Pattern . compile ( "" ) ; Matcher regexMatcher = regex . matcher ( Reason ) ; foundMatch = regexMatcher . find ( ) ; } catch ( PatternSyntaxException ex ) { } if ( MCBans . getServer ( ) . getPlayer ( PlayerName ) != null && foundMatch == true ) { JSONObject tmp = new JSONObject ( ) ; final NCPPlayer player = NCPPlayer . getPlayer ( MCBans . getServer ( ) . getPlayer ( PlayerName ) ) ; try { for ( Entry < String , Object > s : player . collectData ( ) . entrySet ( ) ) { tmp . put ( s . getKey ( ) , s . getValue ( ) ) ; } ActionData . put ( "" , tmp ) ; } catch ( JSONException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } } if ( MCBans . logblock != null ) { boolean foundMatch = false ; try { Pattern regex = Pattern . compile ( "" ) ; Matcher regexMatcher = regex . matcher ( Reason ) ; foundMatch = regexMatcher . find ( ) ; } catch ( PatternSyntaxException ex ) { } if ( foundMatch ) { String [ ] worlds = MCBans . Settings . getString ( "" ) . split ( "" ) ; JSONObject Out = new JSONObject ( ) ; for ( String world : worlds ) { QueryParams params = new QueryParams ( MCBans . logblock ) ; params . setPlayer ( PlayerName ) ; params . bct = BlockChangeType . ALL ; params . limit = - ; params . world = MCBans . getServer ( ) . getWorld ( world ) ; params . needDate = true ; params . needType = true ; params . needData = true ; params . needPlayer = true ; params . needCoords = true ; params . needSignText = true ; JSONObject tmpOut = new JSONObject ( ) ; int increment = ; try { for ( BlockChange bc : MCBans . logblock . getBlockChanges ( params ) ) { try { JSONObject tmp = new JSONObject ( ) ; tmp . put ( "" , String . valueOf ( bc . date ) ) ; if ( bc . loc != null ) { tmp . put ( "" , String . valueOf ( bc . loc . getX ( ) ) ) ; tmp . put ( "" , String . valueOf ( bc . loc . getY ( ) ) ) ; tmp . put ( "" , String . valueOf ( bc . loc . getZ ( ) ) ) ; } tmp . put ( "" , String . valueOf ( bc . data ) ) ; tmp . put ( "" , String . valueOf ( bc . ca ) ) ; if ( bc . signtext != null ) { tmp . put ( "" , "" + bc . signtext + "" ) ; } tmp . put ( "" , String . valueOf ( bc . type ) ) ; tmp . put ( "" , String . valueOf ( bc . replaced ) ) ; tmp . put ( "" , String . valueOf ( bc . playerName ) ) ; tmpOut . put ( String . valueOf ( increment ) , tmp ) ; increment ++ ; } catch ( JSONException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } catch ( NullPointerException en ) { if ( MCBans . Settings . getBoolean ( "" ) ) { en . printStackTrace ( ) ; } } } } catch ( SQLException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } catch ( NullPointerException en ) { if ( MCBans . Settings . getBoolean ( "" ) ) { en . printStackTrace ( ) ; } } try { Out . put ( world , tmpOut ) ; } catch ( JSONException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } try { ActionData . put ( "" , Out ) ; } catch ( JSONException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } if ( Rollback ) { rollback ( ) ; } } if ( ActionData . length ( ) > ) { url_items . put ( "" , ActionData . toString ( ) ) ; } url_items . put ( "" , "" ) ; HashMap < String , String > response = webHandle . mainRequest ( url_items ) ; try { if ( ! response . containsKey ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( PlayerName ) ; if ( ! d . isBanned ( ) ) { d . setBanned ( true ) ; } this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; return ; } if ( response . get ( "" ) . equals ( "" ) ) { MCBans . log ( PlayerName + "" + Reason + "" + PlayerAdmin + "" ) ; this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; MCBans . broadcastAll ( ChatColor . GREEN + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; return ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { Badword = response . get ( "" ) ; MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP , Badword ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } MCBans . log ( PlayerAdmin + "" + PlayerName + "" + Reason + "" ) ; } catch ( NullPointerException e ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( PlayerName ) ; if ( ! d . isBanned ( ) ) { d . setBanned ( true ) ; } this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } public void tempBan ( ) { JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , PlayerName ) ; url_items . put ( "" , PlayerIP ) ; url_items . put ( "" , Reason ) ; url_items . put ( "" , PlayerAdmin ) ; url_items . put ( "" , Duration ) ; url_items . put ( "" , Measure ) ; if ( MCBans . logblock != null && MCBans . Settings . getBoolean ( "" ) ) { if ( Rollback ) { rollback ( ) ; } } if ( ActionData != null ) { url_items . put ( "" , ActionData . toString ( ) ) ; } url_items . put ( "" , "" ) ; HashMap < String , String > response = webHandle . mainRequest ( url_items ) ; try { if ( ! response . containsKey ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( PlayerName ) ; if ( ! d . isBanned ( ) ) { d . setBanned ( true ) ; } this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; return ; } if ( response . get ( "" ) . equals ( "" ) ) { MCBans . log ( PlayerName + "" + Reason + "" + PlayerAdmin + "" ) ; this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; MCBans . broadcastAll ( ChatColor . GREEN + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; return ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } else if ( response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; } MCBans . log ( PlayerAdmin + "" + PlayerName + "" + Reason + "" ) ; } catch ( NullPointerException e ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( PlayerName ) ; if ( ! d . isBanned ( ) ) { d . setBanned ( true ) ; } this . kickPlayer ( PlayerName , MCBans . Language . getFormat ( "" , PlayerName , PlayerAdmin , Reason , PlayerIP ) ) ; if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } public void rollback ( ) { String [ ] worlds = MCBans . Settings . getString ( "" ) . split ( "" ) ; Player h = MCBans . getServer ( ) . getPlayer ( PlayerAdmin ) ; if ( h == null ) { h = MCBans . getServer ( ) . getPlayer ( PlayerName ) ; } if ( h != null ) { for ( String world : worlds ) { QueryParams params = new QueryParams ( MCBans . logblock ) ; params . setPlayer ( PlayerName ) ; params . since = ( rollbackTime * MCBans . Settings . getInteger ( "" ) ) ; params . world = MCBans . getServer ( ) . getWorld ( world ) ; params . silent = false ; try { MCBans . logblock . getCommandsHandler ( ) . new CommandRollback ( ( CommandSender ) h , params , true ) ; MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . GREEN + "" ) ; } catch ( Exception e ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . RED + "" ) ; if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } } else { MCBans . log ( PlayerAdmin + "" + PlayerName + "" ) ; } } } package com . mcbans . firestar . mcbans . pluginInterface ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . log . LogLevels ; import com . mcbans . firestar . mcbans . org . json . JSONException ; import com . mcbans . firestar . mcbans . org . json . JSONObject ; import com . mcbans . firestar . mcbans . request . JsonHandler ; import org . bukkit . ChatColor ; import java . util . HashMap ; public class Lookup implements Runnable { private BukkitInterface MCBans ; private String PlayerName ; private String PlayerAdmin ; public Lookup ( BukkitInterface p , String playerName , String playerAdmin ) { MCBans = p ; PlayerName = playerName ; PlayerAdmin = playerAdmin ; } @ Override public void run ( ) { while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } MCBans . log ( PlayerAdmin + "" + PlayerName + "" ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; JsonHandler webHandle = new JsonHandler ( MCBans ) ; url_items . put ( "" , PlayerName ) ; url_items . put ( "" , PlayerAdmin ) ; url_items . put ( "" , "" ) ; JSONObject result = webHandle . hdl_jobj ( url_items ) ; try { MCBans . broadcastPlayer ( PlayerAdmin , "" + ChatColor . DARK_AQUA + PlayerName + ChatColor . WHITE + "" + ChatColor . DARK_RED + result . getString ( "" ) + "" + ChatColor . WHITE + "" + ChatColor . BLUE + result . getString ( "" ) + "" + ChatColor . WHITE + "" ) ; if ( result . getJSONArray ( "" ) . length ( ) > ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . DARK_RED + "" ) ; for ( int v = ; v < result . getJSONArray ( "" ) . length ( ) ; v ++ ) { MCBans . broadcastPlayer ( PlayerAdmin , result . getJSONArray ( "" ) . getString ( v ) ) ; } } if ( result . getJSONArray ( "" ) . length ( ) > ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . GOLD + "" ) ; for ( int v = ; v < result . getJSONArray ( "" ) . length ( ) ; v ++ ) { MCBans . broadcastPlayer ( PlayerAdmin , result . getJSONArray ( "" ) . getString ( v ) ) ; } } if ( result . getJSONArray ( "" ) . length ( ) > ) { for ( int v = ; v < result . getJSONArray ( "" ) . length ( ) ; v ++ ) { MCBans . broadcastPlayer ( PlayerAdmin , result . getJSONArray ( "" ) . getString ( v ) ) ; } } } catch ( JSONException e ) { if ( result . toString ( ) . contains ( "" ) ) { if ( result . toString ( ) . contains ( "" ) ) { MCBans . broadcastBanView ( ChatColor . RED + "" ) ; MCBans . broadcastBanView ( "" ) ; MCBans . log ( LogLevels . SEVERE , "" ) ; MCBans . log ( LogLevels . SEVERE , "" ) ; } } else { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . RED + "" ) ; MCBans . log ( LogLevels . SEVERE , "" ) ; } } catch ( NullPointerException e ) { MCBans . broadcastPlayer ( PlayerAdmin , ChatColor . RED + "" ) ; MCBans . log ( LogLevels . SEVERE , "" ) ; } } } package com . mcbans . firestar . mcbans . pluginInterface ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . log . LogLevels ; import com . mcbans . firestar . mcbans . org . json . JSONException ; import com . mcbans . firestar . mcbans . org . json . JSONObject ; import com . mcbans . firestar . mcbans . request . JsonHandler ; import org . bukkit . ChatColor ; import java . util . HashMap ; public class Connect implements Runnable { private BukkitInterface MCBans ; private String PlayerIP ; private String PlayerName ; public void ConnectSet ( BukkitInterface p , String pn , String pi ) { MCBans = p ; PlayerIP = pi ; PlayerName = pn ; } public void run ( ) { while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , PlayerName ) ; url_items . put ( "" , PlayerIP ) ; url_items . put ( "" , "" ) ; JSONObject response = webHandle . hdl_jobj ( url_items ) ; try { if ( ! response . has ( "" ) ) { } else { if ( MCBans . Settings . getBoolean ( "" ) ) { MCBans . broadcastPlayer ( PlayerName , ChatColor . DARK_GREEN + "" ) ; } switch ( ConnectStatus . valueOf ( response . get ( "" ) . toString ( ) . toUpperCase ( ) ) ) { case N : if ( response . has ( "" ) ) { if ( response . get ( "" ) . equals ( "" ) ) { MCBans . log ( LogLevels . INFO , PlayerName + "" ) ; MCBans . broadcastJoinView ( ChatColor . AQUA + MCBans . Language . getFormat ( "" , PlayerName ) , PlayerName ) ; MCBans . broadcastPlayer ( PlayerName , ChatColor . AQUA + MCBans . Language . getFormat ( "" ) ) ; } } if ( response . has ( "" ) ) { if ( ! response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerName , ChatColor . DARK_RED + response . get ( "" ) . toString ( ) + "" ) ; } } if ( response . has ( "" ) ) { if ( ! response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerName , ChatColor . AQUA + response . get ( "" ) . toString ( ) ) ; } } if ( response . has ( "" ) && ! MCBans . Permissions . isAllow ( PlayerName , "" ) ) { if ( ! response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastAltView ( ChatColor . DARK_PURPLE + MCBans . Language . getFormatAlts ( "" , PlayerName , response . get ( "" ) . toString ( ) ) ) ; } } MCBans . log ( PlayerName + "" ) ; break ; case B : MCBans . log ( PlayerName + "" ) ; String [ ] out = null ; if ( response . getJSONArray ( "" ) . length ( ) > && MCBans . Settings . getBoolean ( "" ) ) { MCBans . broadcastJoinView ( "" + ChatColor . DARK_AQUA + PlayerName + ChatColor . WHITE + "" + ChatColor . DARK_RED + response . getString ( "" ) + "" + ChatColor . WHITE + "" + ChatColor . BLUE + response . getString ( "" ) + "" + ChatColor . WHITE + "" ) ; MCBans . broadcastJoinView ( "" ) ; if ( response . getJSONArray ( "" ) . length ( ) > ) { for ( int v = ; v < response . getJSONArray ( "" ) . length ( ) ; v ++ ) { out = response . getJSONArray ( "" ) . getString ( v ) . split ( "" ) ; if ( out . length == ) { MCBans . broadcastJoinView ( ChatColor . LIGHT_PURPLE + out [ ] ) ; MCBans . broadcastJoinView ( "" + ChatColor . DARK_PURPLE + out [ ] + "" ) ; } } } MCBans . broadcastJoinView ( "" ) ; } if ( response . has ( "" ) && ! MCBans . Permissions . isAllow ( PlayerName , "" ) ) { if ( ! response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastAltView ( ChatColor . DARK_PURPLE + MCBans . Language . getFormatAlts ( "" , PlayerName , response . get ( "" ) . toString ( ) ) ) ; } } if ( response . has ( "" ) ) { if ( ! response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerName , ChatColor . DARK_RED + response . get ( "" ) . toString ( ) + "" ) ; } } if ( response . has ( "" ) ) { if ( ! response . get ( "" ) . equals ( "" ) ) { MCBans . broadcastPlayer ( PlayerName , ChatColor . AQUA + response . get ( "" ) . toString ( ) ) ; } } MCBans . broadcastPlayer ( PlayerName , ChatColor . DARK_RED + "" ) ; if ( MCBans . Settings . getBoolean ( "" ) ) { System . out . print ( "" + Float . parseFloat ( response . get ( "" ) . toString ( ) ) ) ; } if ( response . has ( "" ) ) { if ( response . get ( "" ) . equals ( "" ) ) { MCBans . log ( LogLevels . INFO , PlayerName + "" ) ; MCBans . broadcastBanView ( ChatColor . AQUA + MCBans . Language . getFormat ( "" , PlayerName ) ) ; MCBans . broadcastPlayer ( PlayerName , ChatColor . AQUA + MCBans . Language . getFormat ( "" ) ) ; } } break ; } } } catch ( JSONException e ) { if ( response . toString ( ) . contains ( "" ) ) { if ( response . toString ( ) . contains ( "" ) ) { MCBans . broadcastBanView ( ChatColor . RED + "" ) ; MCBans . broadcastBanView ( "" ) ; MCBans . log ( LogLevels . SEVERE , "" ) ; MCBans . log ( LogLevels . SEVERE , "" ) ; } } else { MCBans . log ( LogLevels . SEVERE , "" ) ; } } catch ( NullPointerException e ) { } } } package com . mcbans . firestar . mcbans . bukkitListeners ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . net . URL ; import java . net . URLEncoder ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . pluginInterface . Connect ; import com . mcbans . firestar . mcbans . pluginInterface . Disconnect ; import org . bukkit . entity . Player ; import org . bukkit . event . EventHandler ; import org . bukkit . event . EventPriority ; import org . bukkit . event . Listener ; import org . bukkit . event . player . AsyncPlayerPreLoginEvent ; import org . bukkit . event . player . PlayerJoinEvent ; import org . bukkit . event . player . PlayerPreLoginEvent . Result ; import org . bukkit . event . player . PlayerQuitEvent ; public class PlayerListener implements Listener { private BukkitInterface MCBans ; public PlayerListener ( BukkitInterface plugin ) { MCBans = plugin ; } @ EventHandler ( priority = EventPriority . HIGHEST ) public void onAsyncPlayerPreLoginEvent ( AsyncPlayerPreLoginEvent event ) { try { int check = ; while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } check ++ ; if ( check > ) { break ; } } if ( check <= ) { URL urlMCBans = new URL ( "" + MCBans . apiServer + "" + MCBans . getApiKey ( ) + "" + URLEncoder . encode ( event . getName ( ) , "" ) + "" + URLEncoder . encode ( String . valueOf ( event . getAddress ( ) . getHostAddress ( ) ) , "" ) ) ; BufferedReader bufferedreaderMCBans = new BufferedReader ( new InputStreamReader ( urlMCBans . openStream ( ) ) ) ; String s2 = bufferedreaderMCBans . readLine ( ) ; System . out . println ( s2 ) ; bufferedreaderMCBans . close ( ) ; if ( s2 != null ) { String [ ] s3 = s2 . split ( "" ) ; double repMin = MCBans . Settings . getDouble ( "" ) ; int maxAlts = MCBans . Settings . getInteger ( "" ) ; if ( s3 . length == ) { if ( s3 [ ] . equals ( "" ) || s3 [ ] . equals ( "" ) || s3 [ ] . equals ( "" ) || s3 [ ] . equals ( "" ) || s3 [ ] . equals ( "" ) ) { event . disallow ( Result . KICK_BANNED , s3 [ ] ) ; return ; } else if ( repMin > Double . valueOf ( s3 [ ] ) ) { event . disallow ( Result . KICK_BANNED , "" ) ; return ; } else if ( maxAlts < Integer . valueOf ( s3 [ ] ) ) { event . disallow ( Result . KICK_BANNED , "" ) ; return ; } if ( MCBans . Settings . getBoolean ( "" ) ) { System . out . println ( "" + event . getName ( ) + "" + s3 [ ] + "" ) ; } } } } } catch ( IOException e ) { } catch ( IllegalArgumentException e ) { } catch ( NullPointerException e ) { } } @ EventHandler ( priority = EventPriority . HIGHEST ) public void onPlayerJoin ( PlayerJoinEvent event ) { String playerIP = event . getPlayer ( ) . getAddress ( ) . getAddress ( ) . getHostAddress ( ) ; Player player = event . getPlayer ( ) ; MCBans . Permissions . playerConnect ( player ) ; Connect playerConnect = new Connect ( ) ; playerConnect . ConnectSet ( MCBans , player . getName ( ) , playerIP ) ; ( new Thread ( playerConnect ) ) . start ( ) ; } @ EventHandler ( priority = EventPriority . HIGHEST ) public void onPlayerQuit ( PlayerQuitEvent event ) { Player player = event . getPlayer ( ) ; MCBans . Permissions . playerDisconnect ( player . getName ( ) ) ; String playerName = player . getName ( ) ; Disconnect disconnectHandler = new Disconnect ( MCBans , playerName ) ; ( new Thread ( disconnectHandler ) ) . start ( ) ; } } package com . mcbans . firestar . mcbans . commands ; public enum Commands { BAN , TEMPBAN , UNBAN , KICK , LOOKUP , LUP , MCBANS , RBAN , TBAN , GBAN } package com . mcbans . firestar . mcbans . commands ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . Settings ; import com . mcbans . firestar . mcbans . callBacks . ManualSync ; import com . mcbans . firestar . mcbans . callBacks . Ping ; import com . mcbans . firestar . mcbans . callBacks . serverChoose ; import com . mcbans . firestar . mcbans . org . json . JSONObject ; import com . mcbans . firestar . mcbans . pluginInterface . Ban ; import com . mcbans . firestar . mcbans . pluginInterface . Kick ; import com . mcbans . firestar . mcbans . pluginInterface . Lookup ; import org . bukkit . ChatColor ; import org . bukkit . command . CommandSender ; import org . bukkit . entity . Player ; public class CommandHandler { private BukkitInterface MCBans ; private Settings Config ; public CommandHandler ( Settings cf , BukkitInterface p ) { MCBans = p ; Config = cf ; } public boolean execCommand ( String command , String [ ] args , CommandSender from ) { Lookup lookupControl = null ; String CommandSend = "" ; String PlayerIP = "" ; boolean commandSet = false ; boolean isPlayer = false ; String reasonString = "" ; Ban banControl = null ; if ( from instanceof Player ) { Player player = ( Player ) from ; CommandSend = player . getName ( ) ; isPlayer = true ; } else { CommandSend = "" ; isPlayer = false ; } if ( args . length >= ) { Player target = MCBans . getServer ( ) . getPlayer ( args [ ] ) ; if ( target != null ) { PlayerIP = target . getAddress ( ) . getAddress ( ) . getHostAddress ( ) ; } } switch ( Commands . valueOf ( command . toUpperCase ( ) ) ) { case GBAN : if ( args . length >= ) { return handleGlobal ( command , args , CommandSend , isPlayer , PlayerIP , , , false , ) ; } break ; case BAN : if ( args . length < ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; return true ; } if ( args . length >= ) { if ( args [ ] . equalsIgnoreCase ( "" ) ) { return handleGlobal ( command , args , CommandSend , isPlayer , PlayerIP , , , false , ) ; } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { return handleTemp ( command , args , CommandSend , isPlayer , PlayerIP , , , false , , , ) ; } } if ( args . length >= ) { return handleLocal ( command , args , CommandSend , isPlayer , PlayerIP , , , false , ) ; } break ; case RBAN : if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { if ( args . length < ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; return true ; } if ( args . length > ) { if ( isNum ( args [ ] ) ) { if ( args . length >= ) { if ( args [ ] . equalsIgnoreCase ( "" ) ) { return handleGlobal ( command , args , CommandSend , isPlayer , PlayerIP , , , false , Integer . valueOf ( args [ ] ) ) ; } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { return handleTemp ( command , args , CommandSend , isPlayer , PlayerIP , , , false , Integer . valueOf ( args [ ] ) , , ) ; } } return handleLocal ( command , args , CommandSend , isPlayer , PlayerIP , , , false , Integer . valueOf ( args [ ] ) ) ; } else { if ( args . length >= ) { if ( args [ ] . equalsIgnoreCase ( "" ) ) { return handleGlobal ( command , args , CommandSend , isPlayer , PlayerIP , , , true , ) ; } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { return handleTemp ( command , args , CommandSend , isPlayer , PlayerIP , , , true , , , ) ; } } } } if ( args . length >= ) { return handleLocal ( command , args , CommandSend , isPlayer , PlayerIP , , , true , ) ; } } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } break ; case TBAN : case TEMPBAN : if ( args . length >= ) { return handleTemp ( command , args , CommandSend , isPlayer , PlayerIP , , , false , , , ) ; } break ; case UNBAN : if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { if ( args . length < ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; return true ; } banControl = new Ban ( MCBans , "" , args [ ] , "" , CommandSend , "" , "" , "" ) ; Thread triggerThread = new Thread ( banControl ) ; triggerThread . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } commandSet = true ; break ; case KICK : if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { if ( args . length < ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; return true ; } if ( args . length == ) { reasonString = Config . getString ( "" ) ; } else { reasonString = getReason ( args , "" , ) ; } Kick kickPlayer = new Kick ( MCBans . Settings , MCBans , args [ ] , CommandSend , reasonString ) ; Thread triggerThread = new Thread ( kickPlayer ) ; triggerThread . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } commandSet = true ; break ; case LOOKUP : case LUP : if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { if ( args . length < ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; return true ; } lookupControl = new Lookup ( MCBans , args [ ] , CommandSend ) ; Thread triggerThread = new Thread ( lookupControl ) ; triggerThread . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } commandSet = true ; break ; case MCBANS : if ( args . length == ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; } else if ( args . length > ) { if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { if ( args [ ] . equalsIgnoreCase ( "" ) ) { if ( args [ ] . equalsIgnoreCase ( "" ) ) { long callBackInterval = ; callBackInterval = * MCBans . Settings . getInteger ( "" ) ; if ( callBackInterval < ( ( * ) * ) ) { callBackInterval = ( ( * ) * ) ; } String r = this . timeRemain ( ( MCBans . lastCallBack + callBackInterval ) - ( System . currentTimeMillis ( ) / ) ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . GOLD + r + "" ) ; } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { String r = this . timeRemain ( ( MCBans . lastSync + ( * MCBans . Settings . getInteger ( "" ) ) ) - ( System . currentTimeMillis ( ) / ) ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . GOLD + r + "" ) ; } } } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } } else if ( args . length == ) { if ( args [ ] . equalsIgnoreCase ( "" ) ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { Ping manualPingCheck = new Ping ( MCBans , CommandSend ) ; ( new Thread ( manualPingCheck ) ) . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { long ht = ( MCBans . lastSync + ( * MCBans . Settings . getInteger ( "" ) ) ) - ( System . currentTimeMillis ( ) / ) ; if ( ht > ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . GREEN + "" ) ; ManualSync manualSyncBanRunner = new ManualSync ( MCBans , CommandSend ) ; ( new Thread ( manualSyncBanRunner ) ) . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . RED + "" ) ; } } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; MCBans . broadcastPlayer ( CommandSend , ChatColor . WHITE + "" + ChatColor . BLUE + "" ) ; } else if ( args [ ] . equalsIgnoreCase ( "" ) ) { if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . AQUA + "" ) ; Integer reloadSettings = MCBans . Settings . reload ( ) ; if ( reloadSettings == - ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . RED + "" ) ; } else if ( reloadSettings == - ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . RED + "" ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . GREEN + "" ) ; } MCBans . broadcastPlayer ( CommandSend , ChatColor . AQUA + "" ) ; boolean reloadLanguage = MCBans . Language . reload ( ) ; if ( ! reloadLanguage ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . RED + "" ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . GREEN + "" ) ; } serverChoose serverChooser = new serverChoose ( MCBans ) ; ( new Thread ( serverChooser ) ) . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; } } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; } commandSet = true ; break ; } return commandSet ; } private String getReason ( String [ ] args , String reason , int start ) { for ( int x = start ; x < args . length ; x ++ ) { reason += reason . equalsIgnoreCase ( "" ) ? args [ x ] : "" + args [ x ] ; } return reason ; } private boolean isNum ( String s ) { try { Integer . parseInt ( s ) ; } catch ( NumberFormatException nfe ) { return false ; } return true ; } private String timeRemain ( long remain ) { try { String format = "" ; long timeRemaining = remain ; long sec = timeRemaining % ; long min = ( timeRemaining / ) % ; long hours = ( timeRemaining / ( * ) ) % ; long days = ( timeRemaining / ( * * ) ) % ; long weeks = ( timeRemaining / ( * * * ) ) ; if ( sec != ) { format = sec + "" ; } if ( min != ) { format = min + "" + format ; } if ( hours != ) { format = hours + "" + format ; } if ( days != ) { format = days + "" + format ; } if ( weeks != ) { format = weeks + "" + format ; } return format ; } catch ( ArithmeticException e ) { return "" ; } } private boolean handleGlobal ( String command , String [ ] args , String CommandSend , boolean isPlayer , String PlayerIP , int reasonOffset , int minVars , boolean setRollback , int setRollbackTime ) { if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { if ( args . length < minVars ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; return true ; } String reasonString = getReason ( args , "" , reasonOffset ) ; Ban banControl = null ; if ( setRollback ) { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , "" , "" , ( new JSONObject ( ) ) , setRollback ) ; } else if ( setRollbackTime != ) { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , "" , "" , ( new JSONObject ( ) ) , setRollbackTime ) ; } else { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , "" , "" ) ; } Thread triggerThread = new Thread ( banControl ) ; triggerThread . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } return true ; } public boolean handleTemp ( String command , String [ ] args , String CommandSend , boolean isPlayer , String PlayerIP , int reasonOffset , int minVars , boolean setRollback , int setRollbackTime , int tempBanDuration , int tempBanMeasure ) { if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { if ( args . length < minVars ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; return true ; } String reasonString = "" ; if ( args . length == minVars ) { reasonString = Config . getString ( "" ) ; } else { reasonString = getReason ( args , "" , reasonOffset ) ; } Ban banControl = null ; if ( setRollback ) { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , args [ tempBanDuration ] , args [ tempBanMeasure ] , ( new JSONObject ( ) ) , setRollback ) ; } else if ( setRollbackTime != ) { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , args [ tempBanDuration ] , args [ tempBanMeasure ] , ( new JSONObject ( ) ) , setRollbackTime ) ; } else { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , args [ tempBanDuration ] , args [ tempBanMeasure ] ) ; } Thread triggerThread = new Thread ( banControl ) ; triggerThread . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } return true ; } public boolean handleLocal ( String command , String [ ] args , String CommandSend , boolean isPlayer , String PlayerIP , int reasonOffset , int minVars , boolean setRollback , int setRollbackTime ) { if ( MCBans . Permissions . isAllow ( CommandSend , "" ) || ! isPlayer ) { if ( args . length < minVars ) { MCBans . broadcastPlayer ( CommandSend , ChatColor . DARK_RED + MCBans . Language . getFormat ( "" ) ) ; return true ; } String reasonString = "" ; if ( args . length == minVars ) { reasonString = Config . getString ( "" ) ; } else { reasonString = getReason ( args , "" , reasonOffset ) ; } Ban banControl = null ; if ( setRollback ) { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , "" , "" , ( new JSONObject ( ) ) , true ) ; } else if ( setRollbackTime != ) { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , "" , "" , ( new JSONObject ( ) ) , setRollbackTime ) ; } else { banControl = new Ban ( MCBans , "" , args [ ] , PlayerIP , CommandSend , reasonString , "" , "" ) ; } Thread triggerThread = new Thread ( banControl ) ; triggerThread . start ( ) ; } else { MCBans . broadcastPlayer ( CommandSend , MCBans . Language . getFormat ( "" ) ) ; MCBans . log ( CommandSend + "" + command + "" ) ; } return true ; } } package com . mcbans . firestar . mcbans ; import java . util . ArrayList ; import org . bukkit . entity . Player ; public class BukkitPermissions { private BukkitInterface MCBans ; private ArrayList < String > banView = new ArrayList < String > ( ) ; private ArrayList < String > joinView = new ArrayList < String > ( ) ; private ArrayList < String > altsView = new ArrayList < String > ( ) ; private ArrayList < String > kickView = new ArrayList < String > ( ) ; public BukkitPermissions ( Settings cf , BukkitInterface p ) { MCBans = p ; } public boolean isAllow ( String PlayerName , String PermissionNode ) { Player target = MCBans . getServer ( ) . getPlayer ( PlayerName ) ; return target != null && isAllow ( target , PermissionNode ) ; } public boolean isAllow ( Player Player , String PermissionNode ) { if ( Player . hasPermission ( "" + PermissionNode ) ) { return true ; } return false ; } public void playerConnect ( Player player ) { if ( player . hasPermission ( "" ) ) { kickView . add ( player . getName ( ) ) ; banView . add ( player . getName ( ) ) ; joinView . add ( player . getName ( ) ) ; altsView . add ( player . getName ( ) ) ; return ; } if ( player . hasPermission ( "" ) ) { kickView . add ( player . getName ( ) ) ; } if ( player . hasPermission ( "" ) ) { banView . add ( player . getName ( ) ) ; } if ( player . hasPermission ( "" ) ) { joinView . add ( player . getName ( ) ) ; } if ( player . hasPermission ( "" ) ) { altsView . add ( player . getName ( ) ) ; } } public ArrayList < String > getPlayersKick ( ) { return kickView ; } public ArrayList < String > getPlayersBan ( ) { return banView ; } public ArrayList < String > getPlayersJoin ( ) { return joinView ; } public ArrayList < String > getPlayersAlts ( ) { return altsView ; } public void playerDisconnect ( String playerName ) { if ( altsView . contains ( playerName ) ) { altsView . remove ( playerName ) ; } if ( joinView . contains ( playerName ) ) { joinView . remove ( playerName ) ; } if ( kickView . contains ( playerName ) ) { kickView . remove ( playerName ) ; } if ( banView . contains ( playerName ) ) { banView . remove ( playerName ) ; } } } package com . mcbans . firestar . mcbans ; import org . bukkit . configuration . file . YamlConfiguration ; import java . io . IOException ; import java . io . InputStream ; public class Language { private BukkitInterface MCBans ; private YamlConfiguration config ; public Language ( BukkitInterface mcbans ) { MCBans = mcbans ; InputStream in = null ; try { in = Language . class . getClassLoader ( ) . getResourceAsStream ( "" + MCBans . Settings . getString ( "" ) + "" ) ; } catch ( NullPointerException ex ) { } config = YamlConfiguration . loadConfiguration ( in ) ; try { in . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } private String errorMessage ( String Message ) { if ( Message == null ) { return "" ; } else { return "" + Message ; } } public boolean reload ( ) { InputStream in ; try { in = Language . class . getClassLoader ( ) . getResourceAsStream ( "" + MCBans . Settings . getString ( "" ) + "" ) ; } catch ( NullPointerException ex ) { return false ; } config = YamlConfiguration . loadConfiguration ( in ) ; try { in . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return true ; } public String getFormat ( String Message ) { return config . getString ( Message , this . errorMessage ( Message ) ) ; } public String getFormatMessageView ( String Message , String Sender , String Date , String message ) { return config . getString ( Message , this . errorMessage ( Message ) ) . replaceAll ( "" , Sender ) . replaceAll ( "" , Date ) . replaceAll ( "" , message ) ; } public String getFormat ( String Message , String PlayerName ) { return config . getString ( Message , this . errorMessage ( Message ) ) . replaceAll ( "" , PlayerName ) ; } public String getFormatCount ( String Message , String Count ) { return config . getString ( Message , this . errorMessage ( Message ) ) . replaceAll ( "" , Count ) ; } public String getFormat ( String Message , String PlayerName , String PlayerAdmin ) { return config . getString ( Message , this . errorMessage ( Message ) ) . replaceAll ( "" , PlayerName ) . replaceAll ( "" , PlayerAdmin ) ; } public String getFormat ( String Message , String PlayerName , String PlayerAdmin , String Reason ) { return config . getString ( Message , this . errorMessage ( Message ) ) . replaceAll ( "" , PlayerName ) . replaceAll ( "" , PlayerAdmin ) . replaceAll ( "" , Reason ) ; } public String getFormat ( String Message , String PlayerName , String PlayerAdmin , String Reason , String defaultMessage , boolean meow ) { return config . getString ( Message , defaultMessage ) . replaceAll ( "" , PlayerName ) . replaceAll ( "" , PlayerAdmin ) . replaceAll ( "" , Reason ) ; } public String getFormat ( String Message , String PlayerName , String PlayerAdmin , String Reason , String PlayerIP ) { return config . getString ( Message , this . errorMessage ( Message ) ) . replaceAll ( "" , PlayerName ) . replaceAll ( "" , PlayerIP ) . replaceAll ( "" , PlayerAdmin ) . replaceAll ( "" , Reason ) ; } public String getFormat ( String Message , String PlayerName , String PlayerAdmin , String Reason , String PlayerIP , String Word ) { return config . getString ( Message , this . errorMessage ( Message ) ) . replaceAll ( "" , PlayerName ) . replaceAll ( "" , PlayerIP ) . replaceAll ( "" , PlayerAdmin ) . replaceAll ( "" , Reason ) . replaceAll ( "" , Word ) ; } public String getFormatAlts ( String Message , String PlayerName , String AltList ) { return config . getString ( Message , this . errorMessage ( Message ) ) . replaceAll ( "" , PlayerName ) . replaceAll ( "" , AltList ) ; } } package com . mcbans . firestar . mcbans . org . json ; import java . util . Iterator ; @ SuppressWarnings ( { "" } ) public class XML { public static final Character AMP = new Character ( '' ) ; public static final Character APOS = new Character ( '' ) ; public static final Character BANG = new Character ( '' ) ; public static final Character EQ = new Character ( '' ) ; public static final Character GT = new Character ( '>' ) ; public static final Character LT = new Character ( '' ) ; public static final Character QUEST = new Character ( '' ) ; public static final Character QUOT = new Character ( '' ) ; public static final Character SLASH = new Character ( '' ) ; public static String escape ( String string ) { StringBuffer sb = new StringBuffer ( ) ; for ( int i = , length = string . length ( ) ; i < length ; i ++ ) { char c = string . charAt ( i ) ; switch ( c ) { case '' : sb . append ( "" ) ; break ; case '' : sb . append ( "" ) ; break ; case '>' : sb . append ( "" ) ; break ; case '' : sb . append ( "" ) ; break ; case '' : sb . append ( "" ) ; break ; default : sb . append ( c ) ; } } return sb . toString ( ) ; } public static void noSpace ( String string ) throws JSONException { int i , length = string . length ( ) ; if ( length == ) { throw new JSONException ( "" ) ; } for ( i = ; i < length ; i += ) { if ( Character . isWhitespace ( string . charAt ( i ) ) ) { throw new JSONException ( "" + string + "" ) ; } } } private static boolean parse ( XMLTokener x , JSONObject context , String name ) throws JSONException { char c ; int i ; JSONObject jsonobject = null ; String string ; String tagName ; Object token ; token = x . nextToken ( ) ; if ( token == BANG ) { c = x . next ( ) ; if ( c == '' ) { if ( x . next ( ) == '' ) { x . skipPast ( "" ) ; return false ; } x . back ( ) ; } else if ( c == '' ) { token = x . nextToken ( ) ; if ( token . equals ( "" ) ) { if ( x . next ( ) == '' ) { string = x . nextCDATA ( ) ; if ( string . length ( ) > ) { context . accumulate ( "" , string ) ; } return false ; } } throw x . syntaxError ( "" ) ; } i = ; do { token = x . nextMeta ( ) ; if ( token == null ) { throw x . syntaxError ( "" ) ; } else if ( token == LT ) { i += ; } else if ( token == GT ) { i -= ; } } while ( i > ) ; return false ; } else if ( token == QUEST ) { x . skipPast ( "" ) ; return false ; } else if ( token == SLASH ) { token = x . nextToken ( ) ; if ( name == null ) { throw x . syntaxError ( "" + token ) ; } if ( ! token . equals ( name ) ) { throw x . syntaxError ( "" + name + "" + token ) ; } if ( x . nextToken ( ) != GT ) { throw x . syntaxError ( "" ) ; } return true ; } else if ( token instanceof Character ) { throw x . syntaxError ( "" ) ; } else { tagName = ( String ) token ; token = null ; jsonobject = new JSONObject ( ) ; for ( ; ; ) { if ( token == null ) { token = x . nextToken ( ) ; } if ( token instanceof String ) { string = ( String ) token ; token = x . nextToken ( ) ; if ( token == EQ ) { token = x . nextToken ( ) ; if ( ! ( token instanceof String ) ) { throw x . syntaxError ( "" ) ; } jsonobject . accumulate ( string , XML . stringToValue ( ( String ) token ) ) ; token = null ; } else { jsonobject . accumulate ( string , "" ) ; } } else if ( token == SLASH ) { if ( x . nextToken ( ) != GT ) { throw x . syntaxError ( "" ) ; } if ( jsonobject . length ( ) > ) { context . accumulate ( tagName , jsonobject ) ; } else { context . accumulate ( tagName , "" ) ; } return false ; } else if ( token == GT ) { for ( ; ; ) { token = x . nextContent ( ) ; if ( token == null ) { if ( tagName != null ) { throw x . syntaxError ( "" + tagName ) ; } return false ; } else if ( token instanceof String ) { string = ( String ) token ; if ( string . length ( ) > ) { jsonobject . accumulate ( "" , XML . stringToValue ( string ) ) ; } } else if ( token == LT ) { if ( parse ( x , jsonobject , tagName ) ) { if ( jsonobject . length ( ) == ) { context . accumulate ( tagName , "" ) ; } else if ( jsonobject . length ( ) == && jsonobject . opt ( "" ) != null ) { context . accumulate ( tagName , jsonobject . opt ( "" ) ) ; } else { context . accumulate ( tagName , jsonobject ) ; } return false ; } } } } else { throw x . syntaxError ( "" ) ; } } } } public static Object stringToValue ( String string ) { if ( string . equals ( "" ) ) { return string ; } if ( string . equalsIgnoreCase ( "" ) ) { return Boolean . TRUE ; } if ( string . equalsIgnoreCase ( "" ) ) { return Boolean . FALSE ; } if ( string . equalsIgnoreCase ( "" ) ) { return JSONObject . NULL ; } try { char initial = string . charAt ( ) ; boolean negative = false ; if ( initial == '' ) { initial = string . charAt ( ) ; negative = true ; } if ( initial == '' && string . charAt ( negative ? : ) == '' ) { return string ; } if ( ( initial >= '' && initial <= '' ) ) { if ( string . indexOf ( '' ) >= ) { return Double . valueOf ( string ) ; } else if ( string . indexOf ( '' ) < && string . indexOf ( '' ) < ) { Long myLong = new Long ( string ) ; if ( myLong . longValue ( ) == myLong . intValue ( ) ) { return new Integer ( myLong . intValue ( ) ) ; } else { return myLong ; } } } } catch ( Exception ignore ) { } return string ; } public static JSONObject toJSONObject ( String string ) throws JSONException { JSONObject jo = new JSONObject ( ) ; XMLTokener x = new XMLTokener ( string ) ; while ( x . more ( ) && x . skipPast ( "" ) ) { parse ( x , jo , null ) ; } return jo ; } public static String toString ( Object object ) throws JSONException { return toString ( object , null ) ; } public static String toString ( Object object , String tagName ) throws JSONException { StringBuffer sb = new StringBuffer ( ) ; int i ; JSONArray ja ; JSONObject jo ; String key ; Iterator keys ; int length ; String string ; Object value ; if ( object instanceof JSONObject ) { if ( tagName != null ) { sb . append ( '' ) ; sb . append ( tagName ) ; sb . append ( '>' ) ; } jo = ( JSONObject ) object ; keys = jo . keys ( ) ; while ( keys . hasNext ( ) ) { key = keys . next ( ) . toString ( ) ; value = jo . opt ( key ) ; if ( value == null ) { value = "" ; } if ( value instanceof String ) { string = ( String ) value ; } else { string = null ; } if ( key . equals ( "" ) ) { if ( value instanceof JSONArray ) { ja = ( JSONArray ) value ; length = ja . length ( ) ; for ( i = ; i < length ; i += ) { if ( i > ) { sb . append ( '' ) ; } sb . append ( escape ( ja . get ( i ) . toString ( ) ) ) ; } } else { sb . append ( escape ( value . toString ( ) ) ) ; } } else if ( value instanceof JSONArray ) { ja = ( JSONArray ) value ; length = ja . length ( ) ; for ( i = ; i < length ; i += ) { value = ja . get ( i ) ; if ( value instanceof JSONArray ) { sb . append ( '' ) ; sb . append ( key ) ; sb . append ( '>' ) ; sb . append ( toString ( value ) ) ; sb . append ( "" ) ; sb . append ( key ) ; sb . append ( '>' ) ; } else { sb . append ( toString ( value , key ) ) ; } } } else if ( value . equals ( "" ) ) { sb . append ( '' ) ; sb . append ( key ) ; sb . append ( "" ) ; } else { sb . append ( toString ( value , key ) ) ; } } if ( tagName != null ) { sb . append ( "" ) ; sb . append ( tagName ) ; sb . append ( '>' ) ; } return sb . toString ( ) ; } else { if ( object . getClass ( ) . isArray ( ) ) { object = new JSONArray ( object ) ; } if ( object instanceof JSONArray ) { ja = ( JSONArray ) object ; length = ja . length ( ) ; for ( i = ; i < length ; i += ) { sb . append ( toString ( ja . opt ( i ) , tagName == null ? "" : tagName ) ) ; } return sb . toString ( ) ; } else { string = ( object == null ) ? "" : escape ( object . toString ( ) ) ; return ( tagName == null ) ? "" + string + "" : ( string . length ( ) == ) ? "" + tagName + "" : "" + tagName + ">" + string + "" + tagName + ">" ; } } } } package com . mcbans . firestar . mcbans . org . json ; import java . io . * ; public class JSONTokener { private int character ; private boolean eof ; private int index ; private int line ; private char previous ; private Reader reader ; private boolean usePrevious ; public JSONTokener ( Reader reader ) { this . reader = reader . markSupported ( ) ? reader : new BufferedReader ( reader ) ; this . eof = false ; this . usePrevious = false ; this . previous = ; this . index = ; this . character = ; this . line = ; } public JSONTokener ( InputStream inputStream ) throws JSONException { this ( new InputStreamReader ( inputStream ) ) ; } public JSONTokener ( String s ) { this ( new StringReader ( s ) ) ; } public void back ( ) throws JSONException { if ( usePrevious || index <= ) { throw new JSONException ( "" ) ; } this . index -= ; this . character -= ; this . usePrevious = true ; this . eof = false ; } public static int dehexchar ( char c ) { if ( c >= '' && c <= '' ) { return c - '' ; } if ( c >= '' && c <= '' ) { return c - ( '' - ) ; } if ( c >= '' && c <= '' ) { return c - ( '' - ) ; } return - ; } public boolean end ( ) { return eof && ! usePrevious ; } public boolean more ( ) throws JSONException { next ( ) ; if ( end ( ) ) { return false ; } back ( ) ; return true ; } public char next ( ) throws JSONException { int c ; if ( this . usePrevious ) { this . usePrevious = false ; c = this . previous ; } else { try { c = this . reader . read ( ) ; } catch ( IOException exception ) { throw new JSONException ( exception ) ; } if ( c <= ) { this . eof = true ; c = ; } } this . index += ; if ( this . previous == '' ) { this . line += ; this . character = c == '' ? : ; } else if ( c == '' ) { this . line += ; this . character = ; } else { this . character += ; } this . previous = ( char ) c ; return this . previous ; } public char next ( char c ) throws JSONException { char n = next ( ) ; if ( n != c ) { throw syntaxError ( "" + c + "" + n + "" ) ; } return n ; } public String next ( int n ) throws JSONException { if ( n == ) { return "" ; } char [ ] chars = new char [ n ] ; int pos = ; while ( pos < n ) { chars [ pos ] = next ( ) ; if ( end ( ) ) { throw syntaxError ( "" ) ; } pos += ; } return new String ( chars ) ; } public char nextClean ( ) throws JSONException { for ( ; ; ) { char c = next ( ) ; if ( c == || c > '' ) { return c ; } } } public String nextString ( char quote ) throws JSONException { char c ; StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { c = next ( ) ; switch ( c ) { case : case '' : case '' : throw syntaxError ( "" ) ; case '' : c = next ( ) ; switch ( c ) { case '' : sb . append ( '' ) ; break ; case '' : sb . append ( '' ) ; break ; case '' : sb . append ( '' ) ; break ; case '' : sb . append ( '' ) ; break ; case '' : sb . append ( '' ) ; break ; case '' : sb . append ( ( char ) Integer . parseInt ( next ( ) , ) ) ; break ; case '' : case '' : case '' : case '' : sb . append ( c ) ; break ; default : throw syntaxError ( "" ) ; } break ; default : if ( c == quote ) { return sb . toString ( ) ; } sb . append ( c ) ; } } } public String nextTo ( char delimiter ) throws JSONException { StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { char c = next ( ) ; if ( c == delimiter || c == || c == '' || c == '' ) { if ( c != ) { back ( ) ; } return sb . toString ( ) . trim ( ) ; } sb . append ( c ) ; } } public String nextTo ( String delimiters ) throws JSONException { char c ; StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { c = next ( ) ; if ( delimiters . indexOf ( c ) >= || c == || c == '' || c == '' ) { if ( c != ) { back ( ) ; } return sb . toString ( ) . trim ( ) ; } sb . append ( c ) ; } } public Object nextValue ( ) throws JSONException { char c = nextClean ( ) ; String string ; switch ( c ) { case '' : case '' : return nextString ( c ) ; case '' : back ( ) ; return new JSONObject ( this ) ; case '' : back ( ) ; return new JSONArray ( this ) ; } StringBuffer sb = new StringBuffer ( ) ; while ( c >= '' && "" . indexOf ( c ) < ) { sb . append ( c ) ; c = next ( ) ; } back ( ) ; string = sb . toString ( ) . trim ( ) ; if ( string . equals ( "" ) ) { throw syntaxError ( "" ) ; } return JSONObject . stringToValue ( string ) ; } public char skipTo ( char to ) throws JSONException { char c ; try { int startIndex = this . index ; int startCharacter = this . character ; int startLine = this . line ; reader . mark ( Integer . MAX_VALUE ) ; do { c = next ( ) ; if ( c == ) { reader . reset ( ) ; this . index = startIndex ; this . character = startCharacter ; this . line = startLine ; return c ; } } while ( c != to ) ; } catch ( IOException exc ) { throw new JSONException ( exc ) ; } back ( ) ; return c ; } public JSONException syntaxError ( String message ) { return new JSONException ( message + toString ( ) ) ; } public String toString ( ) { return "" + index + "" + this . character + "" + this . line + "" ; } } package com . mcbans . firestar . mcbans . org . json ; import java . util . Iterator ; public class HTTP { public static final String CRLF = "" ; public static JSONObject toJSONObject ( String string ) throws JSONException { JSONObject jo = new JSONObject ( ) ; HTTPTokener x = new HTTPTokener ( string ) ; String token ; token = x . nextToken ( ) ; if ( token . toUpperCase ( ) . startsWith ( "" ) ) { jo . put ( "" , token ) ; jo . put ( "" , x . nextToken ( ) ) ; jo . put ( "" , x . nextTo ( '' ) ) ; x . next ( ) ; } else { jo . put ( "" , token ) ; jo . put ( "" , x . nextToken ( ) ) ; jo . put ( "" , x . nextToken ( ) ) ; } while ( x . more ( ) ) { String name = x . nextTo ( '' ) ; x . next ( '' ) ; jo . put ( name , x . nextTo ( '' ) ) ; x . next ( ) ; } return jo ; } public static String toString ( JSONObject jo ) throws JSONException { @ SuppressWarnings ( "" ) Iterator keys = jo . keys ( ) ; String string ; StringBuffer sb = new StringBuffer ( ) ; if ( jo . has ( "" ) && jo . has ( "" ) ) { sb . append ( jo . getString ( "" ) ) ; sb . append ( '' ) ; sb . append ( jo . getString ( "" ) ) ; sb . append ( '' ) ; sb . append ( jo . getString ( "" ) ) ; } else if ( jo . has ( "" ) && jo . has ( "" ) ) { sb . append ( jo . getString ( "" ) ) ; sb . append ( '' ) ; sb . append ( '' ) ; sb . append ( jo . getString ( "" ) ) ; sb . append ( '' ) ; sb . append ( '' ) ; sb . append ( jo . getString ( "" ) ) ; } else { throw new JSONException ( "" ) ; } sb . append ( CRLF ) ; while ( keys . hasNext ( ) ) { string = keys . next ( ) . toString ( ) ; if ( ! string . equals ( "" ) && ! string . equals ( "" ) && ! string . equals ( "" ) && ! string . equals ( "" ) && ! string . equals ( "" ) && ! jo . isNull ( string ) ) { sb . append ( string ) ; sb . append ( "" ) ; sb . append ( jo . getString ( string ) ) ; sb . append ( CRLF ) ; } } sb . append ( CRLF ) ; return sb . toString ( ) ; } } package com . mcbans . firestar . mcbans . org . json ; public class JSONException extends Exception { private static final long serialVersionUID = ; private Throwable cause ; public JSONException ( String message ) { super ( message ) ; } public JSONException ( Throwable cause ) { super ( cause . getMessage ( ) ) ; this . cause = cause ; } public Throwable getCause ( ) { return this . cause ; } } package com . mcbans . firestar . mcbans . org . json ; public class CDL { private static String getValue ( JSONTokener x ) throws JSONException { char c ; char q ; StringBuffer sb ; do { c = x . next ( ) ; } while ( c == '' || c == '' ) ; switch ( c ) { case : return null ; case '' : case '' : q = c ; sb = new StringBuffer ( ) ; for ( ; ; ) { c = x . next ( ) ; if ( c == q ) { break ; } if ( c == || c == '' || c == '' ) { throw x . syntaxError ( "" + q + "" ) ; } sb . append ( c ) ; } return sb . toString ( ) ; case '' : x . back ( ) ; return "" ; default : x . back ( ) ; return x . nextTo ( '' ) ; } } public static JSONArray rowToJSONArray ( JSONTokener x ) throws JSONException { JSONArray ja = new JSONArray ( ) ; for ( ; ; ) { String value = getValue ( x ) ; char c = x . next ( ) ; if ( value == null || ( ja . length ( ) == && value . length ( ) == && c != '' ) ) { return null ; } ja . put ( value ) ; for ( ; ; ) { if ( c == '' ) { break ; } if ( c != '' ) { if ( c == '' || c == '' || c == ) { return ja ; } throw x . syntaxError ( "" + c + "" + ( int ) c + "" ) ; } c = x . next ( ) ; } } } public static JSONObject rowToJSONObject ( JSONArray names , JSONTokener x ) throws JSONException { JSONArray ja = rowToJSONArray ( x ) ; return ja != null ? ja . toJSONObject ( names ) : null ; } public static String rowToString ( JSONArray ja ) { StringBuffer sb = new StringBuffer ( ) ; for ( int i = ; i < ja . length ( ) ; i += ) { if ( i > ) { sb . append ( '' ) ; } Object object = ja . opt ( i ) ; if ( object != null ) { String string = object . toString ( ) ; if ( string . length ( ) > && ( string . indexOf ( '' ) >= || string . indexOf ( '' ) >= || string . indexOf ( '' ) >= || string . indexOf ( ) >= || string . charAt ( ) == '' ) ) { sb . append ( '' ) ; int length = string . length ( ) ; for ( int j = ; j < length ; j += ) { char c = string . charAt ( j ) ; if ( c >= '' && c != '' ) { sb . append ( c ) ; } } sb . append ( '' ) ; } else { sb . append ( string ) ; } } } sb . append ( '' ) ; return sb . toString ( ) ; } public static JSONArray toJSONArray ( String string ) throws JSONException { return toJSONArray ( new JSONTokener ( string ) ) ; } public static JSONArray toJSONArray ( JSONTokener x ) throws JSONException { return toJSONArray ( rowToJSONArray ( x ) , x ) ; } public static JSONArray toJSONArray ( JSONArray names , String string ) throws JSONException { return toJSONArray ( names , new JSONTokener ( string ) ) ; } public static JSONArray toJSONArray ( JSONArray names , JSONTokener x ) throws JSONException { if ( names == null || names . length ( ) == ) { return null ; } JSONArray ja = new JSONArray ( ) ; for ( ; ; ) { JSONObject jo = rowToJSONObject ( names , x ) ; if ( jo == null ) { break ; } ja . put ( jo ) ; } if ( ja . length ( ) == ) { return null ; } return ja ; } public static String toString ( JSONArray ja ) throws JSONException { JSONObject jo = ja . optJSONObject ( ) ; if ( jo != null ) { JSONArray names = jo . names ( ) ; if ( names != null ) { return rowToString ( names ) + toString ( names , ja ) ; } } return null ; } public static String toString ( JSONArray names , JSONArray ja ) throws JSONException { if ( names == null || names . length ( ) == ) { return null ; } StringBuffer sb = new StringBuffer ( ) ; for ( int i = ; i < ja . length ( ) ; i += ) { JSONObject jo = ja . optJSONObject ( i ) ; if ( jo != null ) { sb . append ( rowToString ( jo . toJSONArray ( names ) ) ) ; } } return sb . toString ( ) ; } } package com . mcbans . firestar . mcbans . org . json ; @ SuppressWarnings ( { "" , "" } ) public class XMLTokener extends JSONTokener { public static final java . util . HashMap entity ; static { entity = new java . util . HashMap ( ) ; entity . put ( "" , XML . AMP ) ; entity . put ( "" , XML . APOS ) ; entity . put ( "" , XML . GT ) ; entity . put ( "" , XML . LT ) ; entity . put ( "" , XML . QUOT ) ; } public XMLTokener ( String s ) { super ( s ) ; } public String nextCDATA ( ) throws JSONException { char c ; int i ; StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { c = next ( ) ; if ( end ( ) ) { throw syntaxError ( "" ) ; } sb . append ( c ) ; i = sb . length ( ) - ; if ( i >= && sb . charAt ( i ) == '' && sb . charAt ( i + ) == '' && sb . charAt ( i + ) == '>' ) { sb . setLength ( i ) ; return sb . toString ( ) ; } } } public Object nextContent ( ) throws JSONException { char c ; StringBuffer sb ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; if ( c == ) { return null ; } if ( c == '' ) { return XML . LT ; } sb = new StringBuffer ( ) ; for ( ; ; ) { if ( c == '' || c == ) { back ( ) ; return sb . toString ( ) . trim ( ) ; } if ( c == '' ) { sb . append ( nextEntity ( c ) ) ; } else { sb . append ( c ) ; } c = next ( ) ; } } public Object nextEntity ( char ampersand ) throws JSONException { StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { char c = next ( ) ; if ( Character . isLetterOrDigit ( c ) || c == '' ) { sb . append ( Character . toLowerCase ( c ) ) ; } else if ( c == '' ) { break ; } else { throw syntaxError ( "" + sb ) ; } } String string = sb . toString ( ) ; Object object = entity . get ( string ) ; return object != null ? object : ampersand + string + "" ; } public Object nextMeta ( ) throws JSONException { char c ; char q ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; switch ( c ) { case : throw syntaxError ( "" ) ; case '' : return XML . LT ; case '>' : return XML . GT ; case '' : return XML . SLASH ; case '' : return XML . EQ ; case '' : return XML . BANG ; case '' : return XML . QUEST ; case '' : case '' : q = c ; for ( ; ; ) { c = next ( ) ; if ( c == ) { throw syntaxError ( "" ) ; } if ( c == q ) { return Boolean . TRUE ; } } default : for ( ; ; ) { c = next ( ) ; if ( Character . isWhitespace ( c ) ) { return Boolean . TRUE ; } switch ( c ) { case : case '' : case '>' : case '' : case '' : case '' : case '' : case '' : case '' : back ( ) ; return Boolean . TRUE ; } } } } public Object nextToken ( ) throws JSONException { char c ; char q ; StringBuffer sb ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; switch ( c ) { case : throw syntaxError ( "" ) ; case '' : throw syntaxError ( "" ) ; case '>' : return XML . GT ; case '' : return XML . SLASH ; case '' : return XML . EQ ; case '' : return XML . BANG ; case '' : return XML . QUEST ; case '' : case '' : q = c ; sb = new StringBuffer ( ) ; for ( ; ; ) { c = next ( ) ; if ( c == ) { throw syntaxError ( "" ) ; } if ( c == q ) { return sb . toString ( ) ; } if ( c == '' ) { sb . append ( nextEntity ( c ) ) ; } else { sb . append ( c ) ; } } default : sb = new StringBuffer ( ) ; for ( ; ; ) { sb . append ( c ) ; c = next ( ) ; if ( Character . isWhitespace ( c ) ) { return sb . toString ( ) ; } switch ( c ) { case : return sb . toString ( ) ; case '>' : case '' : case '' : case '' : case '' : case '' : case '' : back ( ) ; return sb . toString ( ) ; case '' : case '' : case '' : throw syntaxError ( "" ) ; } } } } public boolean skipPast ( String to ) throws JSONException { boolean b ; char c ; int i ; int j ; int offset = ; int length = to . length ( ) ; char [ ] circle = new char [ length ] ; for ( i = ; i < length ; i += ) { c = next ( ) ; if ( c == ) { return false ; } circle [ i ] = c ; } for ( ; ; ) { j = offset ; b = true ; for ( i = ; i < length ; i += ) { if ( circle [ j ] != to . charAt ( i ) ) { b = false ; break ; } j += ; if ( j >= length ) { j -= length ; } } if ( b ) { return true ; } c = next ( ) ; if ( c == ) { return false ; } circle [ offset ] = c ; offset += ; if ( offset >= length ) { offset -= length ; } } } } package com . mcbans . firestar . mcbans . org . json ; public class Cookie { public static String escape ( String string ) { char c ; String s = string . trim ( ) ; StringBuffer sb = new StringBuffer ( ) ; int length = s . length ( ) ; for ( int i = ; i < length ; i += ) { c = s . charAt ( i ) ; if ( c < '' || c == '' || c == '' || c == '' || c == '' ) { sb . append ( '' ) ; sb . append ( Character . forDigit ( ( char ) ( ( c > > > ) & ) , ) ) ; sb . append ( Character . forDigit ( ( char ) ( c & ) , ) ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; } public static JSONObject toJSONObject ( String string ) throws JSONException { String name ; JSONObject jo = new JSONObject ( ) ; Object value ; JSONTokener x = new JSONTokener ( string ) ; jo . put ( "" , x . nextTo ( '' ) ) ; x . next ( '' ) ; jo . put ( "" , x . nextTo ( '' ) ) ; x . next ( ) ; while ( x . more ( ) ) { name = unescape ( x . nextTo ( "" ) ) ; if ( x . next ( ) != '' ) { if ( name . equals ( "" ) ) { value = Boolean . TRUE ; } else { throw x . syntaxError ( "" ) ; } } else { value = unescape ( x . nextTo ( '' ) ) ; x . next ( ) ; } jo . put ( name , value ) ; } return jo ; } public static String toString ( JSONObject jo ) throws JSONException { StringBuffer sb = new StringBuffer ( ) ; sb . append ( escape ( jo . getString ( "" ) ) ) ; sb . append ( "" ) ; sb . append ( escape ( jo . getString ( "" ) ) ) ; if ( jo . has ( "" ) ) { sb . append ( "" ) ; sb . append ( jo . getString ( "" ) ) ; } if ( jo . has ( "" ) ) { sb . append ( "" ) ; sb . append ( escape ( jo . getString ( "" ) ) ) ; } if ( jo . has ( "" ) ) { sb . append ( "" ) ; sb . append ( escape ( jo . getString ( "" ) ) ) ; } if ( jo . optBoolean ( "" ) ) { sb . append ( "" ) ; } return sb . toString ( ) ; } public static String unescape ( String string ) { int length = string . length ( ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = ; i < length ; ++ i ) { char c = string . charAt ( i ) ; if ( c == '' ) { c = '' ; } else if ( c == '' && i + < length ) { int d = JSONTokener . dehexchar ( string . charAt ( i + ) ) ; int e = JSONTokener . dehexchar ( string . charAt ( i + ) ) ; if ( d >= && e >= ) { c = ( char ) ( d * + e ) ; i += ; } } sb . append ( c ) ; } return sb . toString ( ) ; } } package com . mcbans . firestar . mcbans . org . json ; import java . io . IOException ; import java . io . Writer ; public class JSONWriter { private static final int maxdepth = ; private boolean comma ; protected char mode ; private JSONObject stack [ ] ; private int top ; protected Writer writer ; public JSONWriter ( Writer w ) { this . comma = false ; this . mode = '' ; this . stack = new JSONObject [ maxdepth ] ; this . top = ; this . writer = w ; } private JSONWriter append ( String string ) throws JSONException { if ( string == null ) { throw new JSONException ( "" ) ; } if ( this . mode == '' || this . mode == '' ) { try { if ( this . comma && this . mode == '' ) { this . writer . write ( '' ) ; } this . writer . write ( string ) ; } catch ( IOException e ) { throw new JSONException ( e ) ; } if ( this . mode == '' ) { this . mode = '' ; } this . comma = true ; return this ; } throw new JSONException ( "" ) ; } public JSONWriter array ( ) throws JSONException { if ( this . mode == '' || this . mode == '' || this . mode == '' ) { this . push ( null ) ; this . append ( "" ) ; this . comma = false ; return this ; } throw new JSONException ( "" ) ; } private JSONWriter end ( char mode , char c ) throws JSONException { if ( this . mode != mode ) { throw new JSONException ( mode == '' ? "" : "" ) ; } this . pop ( mode ) ; try { this . writer . write ( c ) ; } catch ( IOException e ) { throw new JSONException ( e ) ; } this . comma = true ; return this ; } public JSONWriter endArray ( ) throws JSONException { return this . end ( '' , '' ) ; } public JSONWriter endObject ( ) throws JSONException { return this . end ( '' , '' ) ; } public JSONWriter key ( String string ) throws JSONException { if ( string == null ) { throw new JSONException ( "" ) ; } if ( this . mode == '' ) { try { stack [ top - ] . putOnce ( string , Boolean . TRUE ) ; if ( this . comma ) { this . writer . write ( '' ) ; } this . writer . write ( JSONObject . quote ( string ) ) ; this . writer . write ( '' ) ; this . comma = false ; this . mode = '' ; return this ; } catch ( IOException e ) { throw new JSONException ( e ) ; } } throw new JSONException ( "" ) ; } public JSONWriter object ( ) throws JSONException { if ( this . mode == '' ) { this . mode = '' ; } if ( this . mode == '' || this . mode == '' ) { this . append ( "" ) ; this . push ( new JSONObject ( ) ) ; this . comma = false ; return this ; } throw new JSONException ( "" ) ; } private void pop ( char c ) throws JSONException { if ( this . top <= ) { throw new JSONException ( "" ) ; } char m = this . stack [ this . top - ] == null ? '' : '' ; if ( m != c ) { throw new JSONException ( "" ) ; } this . top -= ; this . mode = this . top == ? '' : this . stack [ this . top - ] == null ? '' : '' ; } private void push ( JSONObject jo ) throws JSONException { if ( this . top >= maxdepth ) { throw new JSONException ( "" ) ; } this . stack [ this . top ] = jo ; this . mode = jo == null ? '' : '' ; this . top += ; } public JSONWriter value ( boolean b ) throws JSONException { return this . append ( b ? "" : "" ) ; } public JSONWriter value ( double d ) throws JSONException { return this . value ( new Double ( d ) ) ; } public JSONWriter value ( long l ) throws JSONException { return this . append ( Long . toString ( l ) ) ; } public JSONWriter value ( Object object ) throws JSONException { return this . append ( JSONObject . valueToString ( object ) ) ; } } package com . mcbans . firestar . mcbans . org . json ; public class HTTPTokener extends JSONTokener { public HTTPTokener ( String string ) { super ( string ) ; } public String nextToken ( ) throws JSONException { char c ; char q ; StringBuffer sb = new StringBuffer ( ) ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; if ( c == '' || c == '' ) { q = c ; for ( ; ; ) { c = next ( ) ; if ( c < '' ) { throw syntaxError ( "" ) ; } if ( c == q ) { return sb . toString ( ) ; } sb . append ( c ) ; } } for ( ; ; ) { if ( c == || Character . isWhitespace ( c ) ) { return sb . toString ( ) ; } sb . append ( c ) ; c = next ( ) ; } } } package com . mcbans . firestar . mcbans . org . json ; import java . io . IOException ; import java . io . Writer ; import java . lang . reflect . Array ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Iterator ; import java . util . Map ; public class JSONArray { @ SuppressWarnings ( "" ) private ArrayList myArrayList ; @ SuppressWarnings ( "" ) public JSONArray ( ) { this . myArrayList = new ArrayList ( ) ; } @ SuppressWarnings ( "" ) public JSONArray ( JSONTokener x ) throws JSONException { this ( ) ; if ( x . nextClean ( ) != '' ) { throw x . syntaxError ( "" ) ; } if ( x . nextClean ( ) != '' ) { x . back ( ) ; for ( ; ; ) { if ( x . nextClean ( ) == '' ) { x . back ( ) ; this . myArrayList . add ( JSONObject . NULL ) ; } else { x . back ( ) ; this . myArrayList . add ( x . nextValue ( ) ) ; } switch ( x . nextClean ( ) ) { case '' : case '' : if ( x . nextClean ( ) == '' ) { return ; } x . back ( ) ; break ; case '' : return ; default : throw x . syntaxError ( "" ) ; } } } } public JSONArray ( String source ) throws JSONException { this ( new JSONTokener ( source ) ) ; } @ SuppressWarnings ( { "" , "" } ) public JSONArray ( Collection collection ) { this . myArrayList = new ArrayList ( ) ; if ( collection != null ) { Iterator iter = collection . iterator ( ) ; while ( iter . hasNext ( ) ) { this . myArrayList . add ( JSONObject . wrap ( iter . next ( ) ) ) ; } } } public JSONArray ( Object array ) throws JSONException { this ( ) ; if ( array . getClass ( ) . isArray ( ) ) { int length = Array . getLength ( array ) ; for ( int i = ; i < length ; i += ) { this . put ( JSONObject . wrap ( Array . get ( array , i ) ) ) ; } } else { throw new JSONException ( "" ) ; } } public Object get ( int index ) throws JSONException { Object object = opt ( index ) ; if ( object == null ) { throw new JSONException ( "" + index + "" ) ; } return object ; } public boolean getBoolean ( int index ) throws JSONException { Object object = get ( index ) ; if ( object . equals ( Boolean . FALSE ) || ( object instanceof String && ( ( String ) object ) . equalsIgnoreCase ( "" ) ) ) { return false ; } else if ( object . equals ( Boolean . TRUE ) || ( object instanceof String && ( ( String ) object ) . equalsIgnoreCase ( "" ) ) ) { return true ; } throw new JSONException ( "" + index + "" ) ; } public double getDouble ( int index ) throws JSONException { Object object = get ( index ) ; try { return object instanceof Number ? ( ( Number ) object ) . doubleValue ( ) : Double . parseDouble ( ( String ) object ) ; } catch ( Exception e ) { throw new JSONException ( "" + index + "" ) ; } } public int getInt ( int index ) throws JSONException { Object object = get ( index ) ; try { return object instanceof Number ? ( ( Number ) object ) . intValue ( ) : Integer . parseInt ( ( String ) object ) ; } catch ( Exception e ) { throw new JSONException ( "" + index + "" ) ; } } public JSONArray getJSONArray ( int index ) throws JSONException { Object object = get ( index ) ; if ( object instanceof JSONArray ) { return ( JSONArray ) object ; } throw new JSONException ( "" + index + "" ) ; } public JSONObject getJSONObject ( int index ) throws JSONException { Object object = get ( index ) ; if ( object instanceof JSONObject ) { return ( JSONObject ) object ; } throw new JSONException ( "" + index + "" ) ; } public long getLong ( int index ) throws JSONException { Object object = get ( index ) ; try { return object instanceof Number ? ( ( Number ) object ) . longValue ( ) : Long . parseLong ( ( String ) object ) ; } catch ( Exception e ) { throw new JSONException ( "" + index + "" ) ; } } public String getString ( int index ) throws JSONException { Object object = get ( index ) ; return object == JSONObject . NULL ? null : object . toString ( ) ; } public boolean isNull ( int index ) { return JSONObject . NULL . equals ( opt ( index ) ) ; } public String join ( String separator ) throws JSONException { int len = length ( ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = ; i < len ; i += ) { if ( i > ) { sb . append ( separator ) ; } sb . append ( JSONObject . valueToString ( this . myArrayList . get ( i ) ) ) ; } return sb . toString ( ) ; } public int length ( ) { return this . myArrayList . size ( ) ; } public Object opt ( int index ) { return ( index < || index >= length ( ) ) ? null : this . myArrayList . get ( index ) ; } public boolean optBoolean ( int index ) { return optBoolean ( index , false ) ; } public boolean optBoolean ( int index , boolean defaultValue ) { try { return getBoolean ( index ) ; } catch ( Exception e ) { return defaultValue ; } } public double optDouble ( int index ) { return optDouble ( index , Double . NaN ) ; } public double optDouble ( int index , double defaultValue ) { try { return getDouble ( index ) ; } catch ( Exception e ) { return defaultValue ; } } public int optInt ( int index ) { return optInt ( index , ) ; } public int optInt ( int index , int defaultValue ) { try { return getInt ( index ) ; } catch ( Exception e ) { return defaultValue ; } } public JSONArray optJSONArray ( int index ) { Object o = opt ( index ) ; return o instanceof JSONArray ? ( JSONArray ) o : null ; } public JSONObject optJSONObject ( int index ) { Object o = opt ( index ) ; return o instanceof JSONObject ? ( JSONObject ) o : null ; } public long optLong ( int index ) { return optLong ( index , ) ; } public long optLong ( int index , long defaultValue ) { try { return getLong ( index ) ; } catch ( Exception e ) { return defaultValue ; } } public String optString ( int index ) { return optString ( index , "" ) ; } public String optString ( int index , String defaultValue ) { Object object = opt ( index ) ; return object != null ? object . toString ( ) : defaultValue ; } public JSONArray put ( boolean value ) { put ( value ? Boolean . TRUE : Boolean . FALSE ) ; return this ; } public JSONArray put ( @ SuppressWarnings ( "" ) Collection value ) { put ( new JSONArray ( value ) ) ; return this ; } public JSONArray put ( double value ) throws JSONException { Double d = new Double ( value ) ; JSONObject . testValidity ( d ) ; put ( d ) ; return this ; } public JSONArray put ( int value ) { put ( new Integer ( value ) ) ; return this ; } public JSONArray put ( long value ) { put ( new Long ( value ) ) ; return this ; } public JSONArray put ( @ SuppressWarnings ( "" ) Map value ) { put ( new JSONObject ( value ) ) ; return this ; } @ SuppressWarnings ( "" ) public JSONArray put ( Object value ) { this . myArrayList . add ( value ) ; return this ; } public JSONArray put ( int index , boolean value ) throws JSONException { put ( index , value ? Boolean . TRUE : Boolean . FALSE ) ; return this ; } public JSONArray put ( int index , @ SuppressWarnings ( "" ) Collection value ) throws JSONException { put ( index , new JSONArray ( value ) ) ; return this ; } public JSONArray put ( int index , double value ) throws JSONException { put ( index , new Double ( value ) ) ; return this ; } public JSONArray put ( int index , int value ) throws JSONException { put ( index , new Integer ( value ) ) ; return this ; } public JSONArray put ( int index , long value ) throws JSONException { put ( index , new Long ( value ) ) ; return this ; } public JSONArray put ( int index , @ SuppressWarnings ( "" ) Map value ) throws JSONException { put ( index , new JSONObject ( value ) ) ; return this ; } @ SuppressWarnings ( "" ) public JSONArray put ( int index , Object value ) throws JSONException { JSONObject . testValidity ( value ) ; if ( index < ) { throw new JSONException ( "" + index + "" ) ; } if ( index < length ( ) ) { this . myArrayList . set ( index , value ) ; } else { while ( index != length ( ) ) { put ( JSONObject . NULL ) ; } put ( value ) ; } return this ; } public Object remove ( int index ) { Object o = opt ( index ) ; this . myArrayList . remove ( index ) ; return o ; } public JSONObject toJSONObject ( JSONArray names ) throws JSONException { if ( names == null || names . length ( ) == || length ( ) == ) { return null ; } JSONObject jo = new JSONObject ( ) ; for ( int i = ; i < names . length ( ) ; i += ) { jo . put ( names . getString ( i ) , this . opt ( i ) ) ; } return jo ; } public String toString ( ) { try { return '' + join ( "" ) + '' ; } catch ( Exception e ) { return null ; } } public String toString ( int indentFactor ) throws JSONException { return toString ( indentFactor , ) ; } String toString ( int indentFactor , int indent ) throws JSONException { int len = length ( ) ; if ( len == ) { return "" ; } int i ; StringBuffer sb = new StringBuffer ( "" ) ; if ( len == ) { sb . append ( JSONObject . valueToString ( this . myArrayList . get ( ) , indentFactor , indent ) ) ; } else { int newindent = indent + indentFactor ; sb . append ( '' ) ; for ( i = ; i < len ; i += ) { if ( i > ) { sb . append ( "" ) ; } for ( int j = ; j < newindent ; j += ) { sb . append ( '' ) ; } sb . append ( JSONObject . valueToString ( this . myArrayList . get ( i ) , indentFactor , newindent ) ) ; } sb . append ( '' ) ; for ( i = ; i < indent ; i += ) { sb . append ( '' ) ; } } sb . append ( '' ) ; return sb . toString ( ) ; } public Writer write ( Writer writer ) throws JSONException { try { boolean b = false ; int len = length ( ) ; writer . write ( '' ) ; for ( int i = ; i < len ; i += ) { if ( b ) { writer . write ( '' ) ; } Object v = this . myArrayList . get ( i ) ; if ( v instanceof JSONObject ) { ( ( JSONObject ) v ) . write ( writer ) ; } else if ( v instanceof JSONArray ) { ( ( JSONArray ) v ) . write ( writer ) ; } else { writer . write ( JSONObject . valueToString ( v ) ) ; } b = true ; } writer . write ( '' ) ; return writer ; } catch ( IOException e ) { throw new JSONException ( e ) ; } } } package com . mcbans . firestar . mcbans . org . json ; import java . io . IOException ; import java . io . Writer ; import java . lang . reflect . Field ; import java . lang . reflect . Method ; import java . lang . reflect . Modifier ; import java . util . * ; @ SuppressWarnings ( { "" , "" } ) public class JSONObject { private static final class Null { protected final Object clone ( ) { return this ; } public boolean equals ( Object object ) { return object == null || object == this ; } public String toString ( ) { return "" ; } } private Map map ; public static final Object NULL = new Null ( ) ; public JSONObject ( ) { this . map = new HashMap ( ) ; } public JSONObject ( JSONObject jo , String [ ] names ) { this ( ) ; for ( int i = ; i < names . length ; i += ) { try { putOnce ( names [ i ] , jo . opt ( names [ i ] ) ) ; } catch ( Exception ignore ) { } } } public JSONObject ( JSONTokener x ) throws JSONException { this ( ) ; char c ; String key ; if ( x . nextClean ( ) != '' ) { throw x . syntaxError ( "" ) ; } for ( ; ; ) { c = x . nextClean ( ) ; switch ( c ) { case : throw x . syntaxError ( "" ) ; case '' : return ; default : x . back ( ) ; key = x . nextValue ( ) . toString ( ) ; } c = x . nextClean ( ) ; if ( c == '' ) { if ( x . next ( ) != '>' ) { x . back ( ) ; } } else if ( c != '' ) { throw x . syntaxError ( "" ) ; } putOnce ( key , x . nextValue ( ) ) ; switch ( x . nextClean ( ) ) { case '' : case '' : if ( x . nextClean ( ) == '' ) { return ; } x . back ( ) ; break ; case '' : return ; default : throw x . syntaxError ( "" ) ; } } } public JSONObject ( Map map ) { this . map = new HashMap ( ) ; if ( map != null ) { Iterator i = map . entrySet ( ) . iterator ( ) ; while ( i . hasNext ( ) ) { Map . Entry e = ( Map . Entry ) i . next ( ) ; Object value = e . getValue ( ) ; if ( value != null ) { this . map . put ( e . getKey ( ) , wrap ( value ) ) ; } } } } public JSONObject ( Object bean ) { this ( ) ; populateMap ( bean ) ; } public JSONObject ( Object object , String names [ ] ) { this ( ) ; Class c = object . getClass ( ) ; for ( int i = ; i < names . length ; i += ) { String name = names [ i ] ; try { putOpt ( name , c . getField ( name ) . get ( object ) ) ; } catch ( Exception ignore ) { } } } public JSONObject ( String source ) throws JSONException { this ( new JSONTokener ( source ) ) ; } public JSONObject ( String baseName , Locale locale ) throws JSONException { this ( ) ; ResourceBundle r = ResourceBundle . getBundle ( baseName , locale , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; Enumeration keys = r . getKeys ( ) ; while ( keys . hasMoreElements ( ) ) { Object key = keys . nextElement ( ) ; if ( key instanceof String ) { String [ ] path = ( ( String ) key ) . split ( "" ) ; int last = path . length - ; JSONObject target = this ; for ( int i = ; i < last ; i += ) { String segment = path [ i ] ; JSONObject nextTarget = target . optJSONObject ( segment ) ; if ( nextTarget == null ) { nextTarget = new JSONObject ( ) ; target . put ( segment , nextTarget ) ; } target = nextTarget ; } target . put ( path [ last ] , r . getString ( ( String ) key ) ) ; } } } public JSONObject accumulate ( String key , Object value ) throws JSONException { testValidity ( value ) ; Object object = opt ( key ) ; if ( object == null ) { put ( key , value instanceof JSONArray ? new JSONArray ( ) . put ( value ) : value ) ; } else if ( object instanceof JSONArray ) { ( ( JSONArray ) object ) . put ( value ) ; } else { put ( key , new JSONArray ( ) . put ( object ) . put ( value ) ) ; } return this ; } public JSONObject append ( String key , Object value ) throws JSONException { testValidity ( value ) ; Object object = opt ( key ) ; if ( object == null ) { put ( key , new JSONArray ( ) . put ( value ) ) ; } else if ( object instanceof JSONArray ) { put ( key , ( ( JSONArray ) object ) . put ( value ) ) ; } else { throw new JSONException ( "" + key + "" ) ; } return this ; } public static String doubleToString ( double d ) { if ( Double . isInfinite ( d ) || Double . isNaN ( d ) ) { return "" ; } String string = Double . toString ( d ) ; if ( string . indexOf ( '' ) > && string . indexOf ( '' ) < && string . indexOf ( '' ) < ) { while ( string . endsWith ( "" ) ) { string = string . substring ( , string . length ( ) - ) ; } if ( string . endsWith ( "" ) ) { string = string . substring ( , string . length ( ) - ) ; } } return string ; } public Object get ( String key ) throws JSONException { if ( key == null ) { throw new JSONException ( "" ) ; } Object object = opt ( key ) ; if ( object == null ) { throw new JSONException ( "" + quote ( key ) + "" ) ; } return object ; } public boolean getBoolean ( String key ) throws JSONException { Object object = get ( key ) ; if ( object . equals ( Boolean . FALSE ) || ( object instanceof String && ( ( String ) object ) . equalsIgnoreCase ( "" ) ) ) { return false ; } else if ( object . equals ( Boolean . TRUE ) || ( object instanceof String && ( ( String ) object ) . equalsIgnoreCase ( "" ) ) ) { return true ; } throw new JSONException ( "" + quote ( key ) + "" ) ; } public double getDouble ( String key ) throws JSONException { Object object = get ( key ) ; try { return object instanceof Number ? ( ( Number ) object ) . doubleValue ( ) : Double . parseDouble ( ( String ) object ) ; } catch ( Exception e ) { throw new JSONException ( "" + quote ( key ) + "" ) ; } } public int getInt ( String key ) throws JSONException { Object object = get ( key ) ; try { return object instanceof Number ? ( ( Number ) object ) . intValue ( ) : Integer . parseInt ( ( String ) object ) ; } catch ( Exception e ) { throw new JSONException ( "" + quote ( key ) + "" ) ; } } public JSONArray getJSONArray ( String key ) throws JSONException { Object object = get ( key ) ; if ( object instanceof JSONArray ) { return ( JSONArray ) object ; } throw new JSONException ( "" + quote ( key ) + "" ) ; } public JSONObject getJSONObject ( String key ) throws JSONException { Object object = get ( key ) ; if ( object instanceof JSONObject ) { return ( JSONObject ) object ; } throw new JSONException ( "" + quote ( key ) + "" ) ; } public long getLong ( String key ) throws JSONException { Object object = get ( key ) ; try { return object instanceof Number ? ( ( Number ) object ) . longValue ( ) : Long . parseLong ( ( String ) object ) ; } catch ( Exception e ) { throw new JSONException ( "" + quote ( key ) + "" ) ; } } public static String [ ] getNames ( JSONObject jo ) { int length = jo . length ( ) ; if ( length == ) { return null ; } Iterator iterator = jo . keys ( ) ; String [ ] names = new String [ length ] ; int i = ; while ( iterator . hasNext ( ) ) { names [ i ] = ( String ) iterator . next ( ) ; i += ; } return names ; } public static String [ ] getNames ( Object object ) { if ( object == null ) { return null ; } Class klass = object . getClass ( ) ; Field [ ] fields = klass . getFields ( ) ; int length = fields . length ; if ( length == ) { return null ; } String [ ] names = new String [ length ] ; for ( int i = ; i < length ; i += ) { names [ i ] = fields [ i ] . getName ( ) ; } return names ; } public String getString ( String key ) throws JSONException { Object object = get ( key ) ; return object == NULL ? null : object . toString ( ) ; } public boolean has ( String key ) { return this . map . containsKey ( key ) ; } public JSONObject increment ( String key ) throws JSONException { Object value = opt ( key ) ; if ( value == null ) { put ( key , ) ; } else if ( value instanceof Integer ) { put ( key , ( ( Integer ) value ) . intValue ( ) + ) ; } else if ( value instanceof Long ) { put ( key , ( ( Long ) value ) . longValue ( ) + ) ; } else if ( value instanceof Double ) { put ( key , ( ( Double ) value ) . doubleValue ( ) + ) ; } else if ( value instanceof Float ) { put ( key , ( ( Float ) value ) . floatValue ( ) + ) ; } else { throw new JSONException ( "" + quote ( key ) + "" ) ; } return this ; } public boolean isNull ( String key ) { return JSONObject . NULL . equals ( opt ( key ) ) ; } public Iterator keys ( ) { return this . map . keySet ( ) . iterator ( ) ; } public int length ( ) { return this . map . size ( ) ; } public JSONArray names ( ) { JSONArray ja = new JSONArray ( ) ; Iterator keys = keys ( ) ; while ( keys . hasNext ( ) ) { ja . put ( keys . next ( ) ) ; } return ja . length ( ) == ? null : ja ; } public static String numberToString ( Number number ) throws JSONException { if ( number == null ) { throw new JSONException ( "" ) ; } testValidity ( number ) ; String string = number . toString ( ) ; if ( string . indexOf ( '' ) > && string . indexOf ( '' ) < && string . indexOf ( '' ) < ) { while ( string . endsWith ( "" ) ) { string = string . substring ( , string . length ( ) - ) ; } if ( string . endsWith ( "" ) ) { string = string . substring ( , string . length ( ) - ) ; } } return string ; } public Object opt ( String key ) { return key == null ? null : this . map . get ( key ) ; } public boolean optBoolean ( String key ) { return optBoolean ( key , false ) ; } public boolean optBoolean ( String key , boolean defaultValue ) { try { return getBoolean ( key ) ; } catch ( Exception e ) { return defaultValue ; } } public double optDouble ( String key ) { return optDouble ( key , Double . NaN ) ; } public double optDouble ( String key , double defaultValue ) { try { return getDouble ( key ) ; } catch ( Exception e ) { return defaultValue ; } } public int optInt ( String key ) { return optInt ( key , ) ; } public int optInt ( String key , int defaultValue ) { try { return getInt ( key ) ; } catch ( Exception e ) { return defaultValue ; } } public JSONArray optJSONArray ( String key ) { Object o = opt ( key ) ; return o instanceof JSONArray ? ( JSONArray ) o : null ; } public JSONObject optJSONObject ( String key ) { Object object = opt ( key ) ; return object instanceof JSONObject ? ( JSONObject ) object : null ; } public long optLong ( String key ) { return optLong ( key , ) ; } public long optLong ( String key , long defaultValue ) { try { return getLong ( key ) ; } catch ( Exception e ) { return defaultValue ; } } public String optString ( String key ) { return optString ( key , "" ) ; } public String optString ( String key , String defaultValue ) { Object object = opt ( key ) ; return NULL . equals ( object ) ? defaultValue : object . toString ( ) ; } private void populateMap ( Object bean ) { Class klass = bean . getClass ( ) ; boolean includeSuperClass = klass . getClassLoader ( ) != null ; Method [ ] methods = ( includeSuperClass ) ? klass . getMethods ( ) : klass . getDeclaredMethods ( ) ; for ( int i = ; i < methods . length ; i += ) { try { Method method = methods [ i ] ; if ( Modifier . isPublic ( method . getModifiers ( ) ) ) { String name = method . getName ( ) ; String key = "" ; if ( name . startsWith ( "" ) ) { if ( name . equals ( "" ) || name . equals ( "" ) ) { key = "" ; } else { key = name . substring ( ) ; } } else if ( name . startsWith ( "" ) ) { key = name . substring ( ) ; } if ( key . length ( ) > && Character . isUpperCase ( key . charAt ( ) ) && method . getParameterTypes ( ) . length == ) { if ( key . length ( ) == ) { key = key . toLowerCase ( ) ; } else if ( ! Character . isUpperCase ( key . charAt ( ) ) ) { key = key . substring ( , ) . toLowerCase ( ) + key . substring ( ) ; } Object result = method . invoke ( bean , ( Object [ ] ) null ) ; if ( result != null ) { map . put ( key , wrap ( result ) ) ; } } } } catch ( Exception ignore ) { } } } public JSONObject put ( String key , boolean value ) throws JSONException { put ( key , value ? Boolean . TRUE : Boolean . FALSE ) ; return this ; } public JSONObject put ( String key , Collection value ) throws JSONException { put ( key , new JSONArray ( value ) ) ; return this ; } public JSONObject put ( String key , double value ) throws JSONException { put ( key , new Double ( value ) ) ; return this ; } public JSONObject put ( String key , int value ) throws JSONException { put ( key , new Integer ( value ) ) ; return this ; } public JSONObject put ( String key , long value ) throws JSONException { put ( key , new Long ( value ) ) ; return this ; } public JSONObject put ( String key , Map value ) throws JSONException { put ( key , new JSONObject ( value ) ) ; return this ; } public JSONObject put ( String key , Object value ) throws JSONException { if ( key == null ) { throw new JSONException ( "" ) ; } if ( value != null ) { testValidity ( value ) ; this . map . put ( key , value ) ; } else { remove ( key ) ; } return this ; } public JSONObject putOnce ( String key , Object value ) throws JSONException { if ( key != null && value != null ) { if ( opt ( key ) != null ) { throw new JSONException ( "" + key + "" ) ; } put ( key , value ) ; } return this ; } public JSONObject putOpt ( String key , Object value ) throws JSONException { if ( key != null && value != null ) { put ( key , value ) ; } return this ; } public static String quote ( String string ) { if ( string == null || string . length ( ) == ) { return "" ; } char b ; char c = ; String hhhh ; int i ; int len = string . length ( ) ; StringBuffer sb = new StringBuffer ( len + ) ; sb . append ( '' ) ; for ( i = ; i < len ; i += ) { b = c ; c = string . charAt ( i ) ; switch ( c ) { case '' : case '' : sb . append ( '' ) ; sb . append ( c ) ; break ; case '' : if ( b == '' ) { sb . append ( '' ) ; } sb . append ( c ) ; break ; case '' : sb . append ( "" ) ; break ; case '' : sb . append ( "" ) ; break ; case '' : sb . append ( "" ) ; break ; case '' : sb . append ( "" ) ; break ; case '' : sb . append ( "" ) ; break ; default : if ( c < '' || ( c >= '' && c < '' ) || ( c >= '' && c < '' ) ) { hhhh = "" + Integer . toHexString ( c ) ; sb . append ( "" + hhhh . substring ( hhhh . length ( ) - ) ) ; } else { sb . append ( c ) ; } } } sb . append ( '' ) ; return sb . toString ( ) ; } public Object remove ( String key ) { return this . map . remove ( key ) ; } public Iterator sortedKeys ( ) { return new TreeSet ( this . map . keySet ( ) ) . iterator ( ) ; } public static Object stringToValue ( String string ) { if ( string . equals ( "" ) ) { return string ; } if ( string . equalsIgnoreCase ( "" ) ) { return Boolean . TRUE ; } if ( string . equalsIgnoreCase ( "" ) ) { return Boolean . FALSE ; } if ( string . equalsIgnoreCase ( "" ) ) { return JSONObject . NULL ; } char b = string . charAt ( ) ; if ( ( b >= '' && b <= '' ) || b == '' || b == '' || b == '' ) { if ( b == '' && string . length ( ) > && ( string . charAt ( ) == '' || string . charAt ( ) == '' ) ) { try { return new Integer ( Integer . parseInt ( string . substring ( ) , ) ) ; } catch ( Exception ignore ) { } } try { if ( string . indexOf ( '' ) > - || string . indexOf ( '' ) > - || string . indexOf ( '' ) > - ) { return Double . valueOf ( string ) ; } else { Long myLong = new Long ( string ) ; if ( myLong . longValue ( ) == myLong . intValue ( ) ) { return new Integer ( myLong . intValue ( ) ) ; } else { return myLong ; } } } catch ( Exception ignore ) { } } return string ; } public static void testValidity ( Object o ) throws JSONException { if ( o != null ) { if ( o instanceof Double ) { if ( ( ( Double ) o ) . isInfinite ( ) || ( ( Double ) o ) . isNaN ( ) ) { throw new JSONException ( "" ) ; } } else if ( o instanceof Float ) { if ( ( ( Float ) o ) . isInfinite ( ) || ( ( Float ) o ) . isNaN ( ) ) { throw new JSONException ( "" ) ; } } } } public JSONArray toJSONArray ( JSONArray names ) throws JSONException { if ( names == null || names . length ( ) == ) { return null ; } JSONArray ja = new JSONArray ( ) ; for ( int i = ; i < names . length ( ) ; i += ) { ja . put ( this . opt ( names . getString ( i ) ) ) ; } return ja ; } public String toString ( ) { try { Iterator keys = keys ( ) ; StringBuffer sb = new StringBuffer ( "" ) ; while ( keys . hasNext ( ) ) { if ( sb . length ( ) > ) { sb . append ( '' ) ; } Object o = keys . next ( ) ; sb . append ( quote ( o . toString ( ) ) ) ; sb . append ( '' ) ; sb . append ( valueToString ( this . map . get ( o ) ) ) ; } sb . append ( '' ) ; return sb . toString ( ) ; } catch ( Exception e ) { return null ; } } public String toString ( int indentFactor ) throws JSONException { return toString ( indentFactor , ) ; } String toString ( int indentFactor , int indent ) throws JSONException { int i ; int length = this . length ( ) ; if ( length == ) { return "" ; } Iterator keys = sortedKeys ( ) ; int newindent = indent + indentFactor ; Object object ; StringBuffer sb = new StringBuffer ( "" ) ; if ( length == ) { object = keys . next ( ) ; sb . append ( quote ( object . toString ( ) ) ) ; sb . append ( "" ) ; sb . append ( valueToString ( this . map . get ( object ) , indentFactor , indent ) ) ; } else { while ( keys . hasNext ( ) ) { object = keys . next ( ) ; if ( sb . length ( ) > ) { sb . append ( "" ) ; } else { sb . append ( '' ) ; } for ( i = ; i < newindent ; i += ) { sb . append ( '' ) ; } sb . append ( quote ( object . toString ( ) ) ) ; sb . append ( "" ) ; sb . append ( valueToString ( this . map . get ( object ) , indentFactor , newindent ) ) ; } if ( sb . length ( ) > ) { sb . append ( '' ) ; for ( i = ; i < indent ; i += ) { sb . append ( '' ) ; } } } sb . append ( '' ) ; return sb . toString ( ) ; } public static String valueToString ( Object value ) throws JSONException { if ( value == null || value . equals ( null ) ) { return "" ; } if ( value instanceof JSONString ) { Object object ; try { object = ( ( JSONString ) value ) . toJSONString ( ) ; } catch ( Exception e ) { throw new JSONException ( e ) ; } if ( object instanceof String ) { return ( String ) object ; } throw new JSONException ( "" + object ) ; } if ( value instanceof Number ) { return numberToString ( ( Number ) value ) ; } if ( value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray ) { return value . toString ( ) ; } if ( value instanceof Map ) { return new JSONObject ( ( Map ) value ) . toString ( ) ; } if ( value instanceof Collection ) { return new JSONArray ( ( Collection ) value ) . toString ( ) ; } if ( value . getClass ( ) . isArray ( ) ) { return new JSONArray ( value ) . toString ( ) ; } return quote ( value . toString ( ) ) ; } static String valueToString ( Object value , int indentFactor , int indent ) throws JSONException { if ( value == null || value . equals ( null ) ) { return "" ; } try { if ( value instanceof JSONString ) { Object o = ( ( JSONString ) value ) . toJSONString ( ) ; if ( o instanceof String ) { return ( String ) o ; } } } catch ( Exception ignore ) { } if ( value instanceof Number ) { return numberToString ( ( Number ) value ) ; } if ( value instanceof Boolean ) { return value . toString ( ) ; } if ( value instanceof JSONObject ) { return ( ( JSONObject ) value ) . toString ( indentFactor , indent ) ; } if ( value instanceof JSONArray ) { return ( ( JSONArray ) value ) . toString ( indentFactor , indent ) ; } if ( value instanceof Map ) { return new JSONObject ( ( Map ) value ) . toString ( indentFactor , indent ) ; } if ( value instanceof Collection ) { return new JSONArray ( ( Collection ) value ) . toString ( indentFactor , indent ) ; } if ( value . getClass ( ) . isArray ( ) ) { return new JSONArray ( value ) . toString ( indentFactor , indent ) ; } return quote ( value . toString ( ) ) ; } public static Object wrap ( Object object ) { try { if ( object == null ) { return NULL ; } if ( object instanceof JSONObject || object instanceof JSONArray || NULL . equals ( object ) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String ) { return object ; } if ( object instanceof Collection ) { return new JSONArray ( ( Collection ) object ) ; } if ( object . getClass ( ) . isArray ( ) ) { return new JSONArray ( object ) ; } if ( object instanceof Map ) { return new JSONObject ( ( Map ) object ) ; } Package objectPackage = object . getClass ( ) . getPackage ( ) ; String objectPackageName = ( objectPackage != null ? objectPackage . getName ( ) : "" ) ; if ( objectPackageName . startsWith ( "" ) || objectPackageName . startsWith ( "" ) || object . getClass ( ) . getClassLoader ( ) == null ) { return object . toString ( ) ; } return new JSONObject ( object ) ; } catch ( Exception exception ) { return null ; } } public Writer write ( Writer writer ) throws JSONException { try { boolean commanate = false ; Iterator keys = keys ( ) ; writer . write ( '' ) ; while ( keys . hasNext ( ) ) { if ( commanate ) { writer . write ( '' ) ; } Object key = keys . next ( ) ; writer . write ( quote ( key . toString ( ) ) ) ; writer . write ( '' ) ; Object value = this . map . get ( key ) ; if ( value instanceof JSONObject ) { ( ( JSONObject ) value ) . write ( writer ) ; } else if ( value instanceof JSONArray ) { ( ( JSONArray ) value ) . write ( writer ) ; } else { writer . write ( valueToString ( value ) ) ; } commanate = true ; } writer . write ( '' ) ; return writer ; } catch ( IOException exception ) { throw new JSONException ( exception ) ; } } } package com . mcbans . firestar . mcbans . org . json ; import java . util . Iterator ; public class JSONML { private static Object parse ( XMLTokener x , boolean arrayForm , JSONArray ja ) throws JSONException { String attribute ; char c ; String closeTag = null ; int i ; JSONArray newja = null ; JSONObject newjo = null ; Object token ; String tagName = null ; while ( true ) { token = x . nextContent ( ) ; if ( token == XML . LT ) { token = x . nextToken ( ) ; if ( token instanceof Character ) { if ( token == XML . SLASH ) { token = x . nextToken ( ) ; if ( ! ( token instanceof String ) ) { throw new JSONException ( "" + token + "" ) ; } if ( x . nextToken ( ) != XML . GT ) { throw x . syntaxError ( "" ) ; } return token ; } else if ( token == XML . BANG ) { c = x . next ( ) ; if ( c == '' ) { if ( x . next ( ) == '' ) { x . skipPast ( "" ) ; } x . back ( ) ; } else if ( c == '' ) { token = x . nextToken ( ) ; if ( token . equals ( "" ) && x . next ( ) == '' ) { if ( ja != null ) { ja . put ( x . nextCDATA ( ) ) ; } } else { throw x . syntaxError ( "" ) ; } } else { i = ; do { token = x . nextMeta ( ) ; if ( token == null ) { throw x . syntaxError ( "" ) ; } else if ( token == XML . LT ) { i += ; } else if ( token == XML . GT ) { i -= ; } } while ( i > ) ; } } else if ( token == XML . QUEST ) { x . skipPast ( "" ) ; } else { throw x . syntaxError ( "" ) ; } } else { if ( ! ( token instanceof String ) ) { throw x . syntaxError ( "" + token + "" ) ; } tagName = ( String ) token ; newja = new JSONArray ( ) ; newjo = new JSONObject ( ) ; if ( arrayForm ) { newja . put ( tagName ) ; if ( ja != null ) { ja . put ( newja ) ; } } else { newjo . put ( "" , tagName ) ; if ( ja != null ) { ja . put ( newjo ) ; } } token = null ; for ( ; ; ) { if ( token == null ) { token = x . nextToken ( ) ; } if ( token == null ) { throw x . syntaxError ( "" ) ; } if ( ! ( token instanceof String ) ) { break ; } attribute = ( String ) token ; if ( ! arrayForm && ( attribute == "" || attribute == "" ) ) { throw x . syntaxError ( "" ) ; } token = x . nextToken ( ) ; if ( token == XML . EQ ) { token = x . nextToken ( ) ; if ( ! ( token instanceof String ) ) { throw x . syntaxError ( "" ) ; } newjo . accumulate ( attribute , XML . stringToValue ( ( String ) token ) ) ; token = null ; } else { newjo . accumulate ( attribute , "" ) ; } } if ( arrayForm && newjo . length ( ) > ) { newja . put ( newjo ) ; } if ( token == XML . SLASH ) { if ( x . nextToken ( ) != XML . GT ) { throw x . syntaxError ( "" ) ; } if ( ja == null ) { if ( arrayForm ) { return newja ; } else { return newjo ; } } } else { if ( token != XML . GT ) { throw x . syntaxError ( "" ) ; } closeTag = ( String ) parse ( x , arrayForm , newja ) ; if ( closeTag != null ) { if ( ! closeTag . equals ( tagName ) ) { throw x . syntaxError ( "" + tagName + "" + closeTag + "" ) ; } tagName = null ; if ( ! arrayForm && newja . length ( ) > ) { newjo . put ( "" , newja ) ; } if ( ja == null ) { if ( arrayForm ) { return newja ; } else { return newjo ; } } } } } } else { if ( ja != null ) { ja . put ( token instanceof String ? XML . stringToValue ( ( String ) token ) : token ) ; } } } } public static JSONArray toJSONArray ( String string ) throws JSONException { return toJSONArray ( new XMLTokener ( string ) ) ; } public static JSONArray toJSONArray ( XMLTokener x ) throws JSONException { return ( JSONArray ) parse ( x , true , null ) ; } public static JSONObject toJSONObject ( XMLTokener x ) throws JSONException { return ( JSONObject ) parse ( x , false , null ) ; } public static JSONObject toJSONObject ( String string ) throws JSONException { return toJSONObject ( new XMLTokener ( string ) ) ; } public static String toString ( JSONArray ja ) throws JSONException { int i ; JSONObject jo ; String key ; @ SuppressWarnings ( "" ) Iterator keys ; int length ; Object object ; StringBuffer sb = new StringBuffer ( ) ; String tagName ; String value ; tagName = ja . getString ( ) ; XML . noSpace ( tagName ) ; tagName = XML . escape ( tagName ) ; sb . append ( '' ) ; sb . append ( tagName ) ; object = ja . opt ( ) ; if ( object instanceof JSONObject ) { i = ; jo = ( JSONObject ) object ; keys = jo . keys ( ) ; while ( keys . hasNext ( ) ) { key = keys . next ( ) . toString ( ) ; XML . noSpace ( key ) ; value = jo . optString ( key ) ; if ( value != null ) { sb . append ( '' ) ; sb . append ( XML . escape ( key ) ) ; sb . append ( '' ) ; sb . append ( '' ) ; sb . append ( XML . escape ( value ) ) ; sb . append ( '' ) ; } } } else { i = ; } length = ja . length ( ) ; if ( i >= length ) { sb . append ( '' ) ; sb . append ( '>' ) ; } else { sb . append ( '>' ) ; do { object = ja . get ( i ) ; i += ; if ( object != null ) { if ( object instanceof String ) { sb . append ( XML . escape ( object . toString ( ) ) ) ; } else if ( object instanceof JSONObject ) { sb . append ( toString ( ( JSONObject ) object ) ) ; } else if ( object instanceof JSONArray ) { sb . append ( toString ( ( JSONArray ) object ) ) ; } } } while ( i < length ) ; sb . append ( '' ) ; sb . append ( '' ) ; sb . append ( tagName ) ; sb . append ( '>' ) ; } return sb . toString ( ) ; } public static String toString ( JSONObject jo ) throws JSONException { StringBuffer sb = new StringBuffer ( ) ; int i ; JSONArray ja ; String key ; @ SuppressWarnings ( "" ) Iterator keys ; int length ; Object object ; String tagName ; String value ; tagName = jo . optString ( "" ) ; if ( tagName == null ) { return XML . escape ( jo . toString ( ) ) ; } XML . noSpace ( tagName ) ; tagName = XML . escape ( tagName ) ; sb . append ( '' ) ; sb . append ( tagName ) ; keys = jo . keys ( ) ; while ( keys . hasNext ( ) ) { key = keys . next ( ) . toString ( ) ; if ( ! key . equals ( "" ) && ! key . equals ( "" ) ) { XML . noSpace ( key ) ; value = jo . optString ( key ) ; if ( value != null ) { sb . append ( '' ) ; sb . append ( XML . escape ( key ) ) ; sb . append ( '' ) ; sb . append ( '' ) ; sb . append ( XML . escape ( value ) ) ; sb . append ( '' ) ; } } } ja = jo . optJSONArray ( "" ) ; if ( ja == null ) { sb . append ( '' ) ; sb . append ( '>' ) ; } else { sb . append ( '>' ) ; length = ja . length ( ) ; for ( i = ; i < length ; i += ) { object = ja . get ( i ) ; if ( object != null ) { if ( object instanceof String ) { sb . append ( XML . escape ( object . toString ( ) ) ) ; } else if ( object instanceof JSONObject ) { sb . append ( toString ( ( JSONObject ) object ) ) ; } else if ( object instanceof JSONArray ) { sb . append ( toString ( ( JSONArray ) object ) ) ; } } } sb . append ( '' ) ; sb . append ( '' ) ; sb . append ( tagName ) ; sb . append ( '>' ) ; } return sb . toString ( ) ; } } package com . mcbans . firestar . mcbans . org . json ; import java . io . StringWriter ; public class JSONStringer extends JSONWriter { public JSONStringer ( ) { super ( new StringWriter ( ) ) ; } public String toString ( ) { return this . mode == '' ? this . writer . toString ( ) : null ; } } package com . mcbans . firestar . mcbans . org . json ; import java . util . Iterator ; public class CookieList { public static JSONObject toJSONObject ( String string ) throws JSONException { JSONObject jo = new JSONObject ( ) ; JSONTokener x = new JSONTokener ( string ) ; while ( x . more ( ) ) { String name = Cookie . unescape ( x . nextTo ( '' ) ) ; x . next ( '' ) ; jo . put ( name , Cookie . unescape ( x . nextTo ( '' ) ) ) ; x . next ( ) ; } return jo ; } public static String toString ( JSONObject jo ) throws JSONException { boolean b = false ; @ SuppressWarnings ( "" ) Iterator keys = jo . keys ( ) ; String string ; StringBuffer sb = new StringBuffer ( ) ; while ( keys . hasNext ( ) ) { string = keys . next ( ) . toString ( ) ; if ( ! jo . isNull ( string ) ) { if ( b ) { sb . append ( '' ) ; } sb . append ( Cookie . escape ( string ) ) ; sb . append ( "" ) ; sb . append ( Cookie . escape ( jo . getString ( string ) ) ) ; b = true ; } } return sb . toString ( ) ; } } package com . mcbans . firestar . mcbans . org . json ; public interface JSONString { public String toJSONString ( ) ; } package com . mcbans . firestar . mcbans . callBacks ; import java . util . HashMap ; import org . bukkit . ChatColor ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . request . JsonHandler ; public class Ping implements Runnable { private final BukkitInterface MCBans ; private String commandSend = "" ; public Ping ( BukkitInterface p , String player ) { MCBans = p ; commandSend = player ; } @ Override public void run ( ) { while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } long pingTime = ( System . currentTimeMillis ( ) ) ; JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > items = new HashMap < String , String > ( ) ; items . put ( "" , "" ) ; String urlReq = webHandle . urlparse ( items ) ; String jsonText = webHandle . request_from_api ( urlReq ) ; if ( jsonText . equals ( "" ) ) { MCBans . broadcastPlayer ( commandSend , ChatColor . GREEN + "" + ( ( System . currentTimeMillis ( ) ) - pingTime ) + "" ) ; } else { MCBans . broadcastPlayer ( commandSend , ChatColor . RED + "" ) ; } } } package com . mcbans . firestar . mcbans . callBacks ; import java . io . BufferedReader ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . io . Writer ; import java . util . HashMap ; import org . bukkit . OfflinePlayer ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . org . json . JSONException ; import com . mcbans . firestar . mcbans . org . json . JSONObject ; import com . mcbans . firestar . mcbans . request . JsonHandler ; public class BanSync implements Runnable { private final BukkitInterface MCBans ; public long last_req = ; private long timeRecieved = ; public BanSync ( BukkitInterface p ) { MCBans = p ; this . load ( ) ; } @ Override public void run ( ) { while ( true ) { int syncInterval = ( ( * ) * MCBans . Settings . getInteger ( "" ) ) ; if ( syncInterval < ( ( * ) ) ) { syncInterval = ( ( * ) ) ; } while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } this . mainRequest ( ) ; MCBans . lastSync = System . currentTimeMillis ( ) / ; try { Thread . sleep ( syncInterval ) ; } catch ( InterruptedException e ) { } } } public void goRequest ( ) { this . mainRequest ( ) ; } private void mainRequest ( ) { if ( MCBans . lastID == ) { this . initialSync ( ) ; this . save ( ) ; } else { this . startSync ( ) ; this . save ( ) ; } } public void initialSync ( ) { if ( MCBans . syncRunning == true ) { return ; } MCBans . syncRunning = true ; boolean goNext = true ; int f = ; while ( goNext ) { long startID = MCBans . lastID ; JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , String . valueOf ( MCBans . lastID ) ) ; url_items . put ( "" , String . valueOf ( timeRecieved ) ) ; url_items . put ( "" , "" ) ; JSONObject response = webHandle . hdl_jobj ( url_items ) ; try { if ( response . has ( "" ) ) { if ( response . getJSONArray ( "" ) . length ( ) > ) { for ( int v = ; v < response . getJSONArray ( "" ) . length ( ) ; v ++ ) { String [ ] plyer = response . getJSONArray ( "" ) . getString ( v ) . split ( "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( plyer [ ] ) ; if ( d . isBanned ( ) ) { if ( plyer [ ] . equals ( "" ) ) { d . setBanned ( false ) ; } } else { if ( plyer [ ] . equals ( "" ) ) { d . setBanned ( true ) ; } } } } } if ( MCBans . lastID == ) { if ( response . has ( "" ) ) { timeRecieved = response . getLong ( "" ) ; } } if ( response . has ( "" ) ) { MCBans . lastID = response . getLong ( "" ) ; } if ( response . has ( "" ) ) { goNext = true ; } else { goNext = false ; } } catch ( JSONException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } catch ( NullPointerException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } if ( MCBans . lastID == startID ) { f ++ ; } else { f = ; } if ( f > ) { goNext = false ; } } MCBans . syncRunning = false ; } public void startSync ( ) { if ( MCBans . syncRunning == true ) { return ; } MCBans . syncRunning = true ; boolean goNext = true ; int f = ; while ( goNext ) { long startID = MCBans . lastID ; JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , String . valueOf ( MCBans . lastID ) ) ; url_items . put ( "" , "" ) ; JSONObject response = webHandle . hdl_jobj ( url_items ) ; try { if ( response . has ( "" ) ) { if ( response . getJSONArray ( "" ) . length ( ) > ) { for ( int v = ; v < response . getJSONArray ( "" ) . length ( ) ; v ++ ) { String [ ] plyer = response . getJSONArray ( "" ) . getString ( v ) . split ( "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( plyer [ ] ) ; if ( d . isBanned ( ) ) { if ( plyer [ ] . equals ( "" ) ) { d . setBanned ( false ) ; } } else { if ( plyer [ ] . equals ( "" ) ) { d . setBanned ( true ) ; } } } } } if ( response . has ( "" ) ) { long h = response . getLong ( "" ) ; if ( h != ) { MCBans . lastID = h ; } } if ( response . has ( "" ) ) { goNext = true ; } else { goNext = false ; } } catch ( NullPointerException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } catch ( JSONException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } if ( MCBans . lastID == startID ) { f ++ ; } else { f = ; } if ( f > ) { goNext = false ; } } MCBans . syncRunning = false ; } public void save ( ) { try { Writer writer = new OutputStreamWriter ( new FileOutputStream ( "" ) , "" ) ; BufferedWriter fout = new BufferedWriter ( writer ) ; fout . write ( String . valueOf ( MCBans . lastID ) ) ; fout . close ( ) ; writer . close ( ) ; } catch ( Exception e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } public void load ( ) { File f = new File ( "" ) ; if ( f . exists ( ) != true ) { MCBans . lastID = ; return ; } String strLine = "" ; try { BufferedReader i = new BufferedReader ( new InputStreamReader ( new FileInputStream ( "" ) , "" ) ) ; String line = null ; while ( ( line = i . readLine ( ) ) != null ) { strLine += line ; } i . close ( ) ; MCBans . lastID = Integer . valueOf ( strLine ) ; } catch ( Exception e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } } package com . mcbans . firestar . mcbans . callBacks ; import java . util . HashMap ; import org . bukkit . ChatColor ; import org . bukkit . OfflinePlayer ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . org . json . JSONException ; import com . mcbans . firestar . mcbans . org . json . JSONObject ; import com . mcbans . firestar . mcbans . request . JsonHandler ; public class ManualSync implements Runnable { private final BukkitInterface MCBans ; private String commandSend = "" ; public ManualSync ( BukkitInterface p , String player ) { MCBans = p ; commandSend = player ; } @ Override public void run ( ) { if ( MCBans . syncRunning == true ) { return ; } while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } int fre = ; MCBans . syncRunning = true ; boolean goNext = true ; while ( goNext ) { JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , String . valueOf ( MCBans . lastID ) ) ; url_items . put ( "" , "" ) ; JSONObject response = webHandle . hdl_jobj ( url_items ) ; try { if ( response . has ( "" ) ) { fre += response . getJSONArray ( "" ) . length ( ) ; if ( response . getJSONArray ( "" ) . length ( ) > ) { for ( int v = ; v < response . getJSONArray ( "" ) . length ( ) ; v ++ ) { String [ ] plyer = response . getJSONArray ( "" ) . getString ( v ) . split ( "" ) ; OfflinePlayer d = MCBans . getServer ( ) . getOfflinePlayer ( plyer [ ] ) ; if ( d . isBanned ( ) ) { if ( plyer [ ] . equals ( "" ) ) { d . setBanned ( false ) ; } } else { if ( plyer [ ] . equals ( "" ) ) { d . setBanned ( true ) ; } } } } } if ( response . has ( "" ) ) { long h = response . getLong ( "" ) ; if ( h != ) { MCBans . lastID = h ; } } if ( response . has ( "" ) ) { goNext = true ; } else { goNext = false ; } } catch ( JSONException e ) { e . printStackTrace ( ) ; } } MCBans . syncRunning = false ; MCBans . broadcastPlayer ( commandSend , ChatColor . GREEN + "" + fre + "" ) ; } } package com . mcbans . firestar . mcbans . callBacks ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . log . LogLevels ; import com . mcbans . firestar . mcbans . request . JsonHandler ; import org . bukkit . ChatColor ; import org . bukkit . entity . Player ; import java . util . HashMap ; public class MainCallBack implements Runnable { private final BukkitInterface MCBans ; public long last_req = ; public MainCallBack ( BukkitInterface p ) { MCBans = p ; } @ Override public void run ( ) { int callBackInterval = ( ( * ) * MCBans . Settings . getInteger ( "" ) ) ; if ( callBackInterval < ( ( * ) * ) ) { callBackInterval = ( ( * ) * ) ; } while ( true ) { while ( MCBans . notSelectedServer ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } this . mainRequest ( ) ; MCBans . lastCallBack = System . currentTimeMillis ( ) / ; try { Thread . sleep ( callBackInterval ) ; } catch ( InterruptedException e ) { } } } public void goRequest ( ) { mainRequest ( ) ; } private void mainRequest ( ) { JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > url_items = new HashMap < String , String > ( ) ; url_items . put ( "" , String . valueOf ( MCBans . getServer ( ) . getMaxPlayers ( ) ) ) ; url_items . put ( "" , this . playerList ( ) ) ; url_items . put ( "" , MCBans . getDescription ( ) . getVersion ( ) ) ; url_items . put ( "" , "" ) ; HashMap < String , String > response = webHandle . mainRequest ( url_items ) ; try { if ( response . containsKey ( "" ) ) { for ( String cb : response . keySet ( ) ) { if ( cb . contains ( "" ) ) { MCBans . broadcastBanView ( ChatColor . GOLD + "" + ChatColor . WHITE + response . get ( cb ) ) ; MCBans . log ( LogLevels . INFO , "" + response . get ( cb ) ) ; } } } } catch ( NullPointerException e ) { if ( MCBans . Settings . getBoolean ( "" ) ) { e . printStackTrace ( ) ; } } } private String playerList ( ) { StringBuilder playerList = new StringBuilder ( ) ; for ( Player player : MCBans . getServer ( ) . getOnlinePlayers ( ) ) { if ( playerList . length ( ) > ) { playerList . append ( "" ) ; } playerList . append ( player . getName ( ) ) ; } return playerList . toString ( ) ; } } package com . mcbans . firestar . mcbans . callBacks ; import java . util . HashMap ; import com . mcbans . firestar . mcbans . BukkitInterface ; import com . mcbans . firestar . mcbans . request . JsonHandler ; public class serverChoose implements Runnable { private final BukkitInterface MCBans ; public serverChoose ( BukkitInterface p ) { MCBans = p ; } @ Override public void run ( ) { MCBans . notSelectedServer = true ; MCBans . log ( "" ) ; long d = ; for ( String server : MCBans . apiServers . split ( "" ) ) { try { long pingTime = ( System . currentTimeMillis ( ) ) ; JsonHandler webHandle = new JsonHandler ( MCBans ) ; HashMap < String , String > items = new HashMap < String , String > ( ) ; items . put ( "" , "" ) ; String urlReq = webHandle . urlparse ( items ) ; String jsonText = webHandle . request_from_api ( urlReq , server ) ; if ( jsonText . equals ( "" ) ) { long ft = ( ( System . currentTimeMillis ( ) ) - pingTime ) ; if ( d > ft ) { d = ft ; MCBans . apiServer = server ; MCBans . log ( "" + server + "" + ft ) ; } } } catch ( IllegalArgumentException e ) { } catch ( NullPointerException e ) { } } MCBans . log ( "" + MCBans . apiServer + "" + d ) ; MCBans . notSelectedServer = false ; } } package com . mcbans . firestar . mcbans ; import org . bukkit . configuration . file . YamlConfiguration ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; public class Settings { private YamlConfiguration config ; public boolean exists = false ; public Settings ( ) { File plugin_settings = new File ( "" ) ; YamlConfiguration configTest = null ; if ( ! plugin_settings . exists ( ) ) { System . out . print ( "" ) ; this . generate ( ) ; plugin_settings = new File ( "" ) ; configTest = YamlConfiguration . loadConfiguration ( plugin_settings ) ; } else { configTest = YamlConfiguration . loadConfiguration ( plugin_settings ) ; } String verify = verifyIntegrity ( configTest ) ; if ( verify != "" ) { System . out . print ( "" + verify + "" ) ; this . exists = true ; } else { config = configTest ; } } public void generate ( ) { InputStream in = null ; try { in = Settings . class . getClassLoader ( ) . getResourceAsStream ( "" ) ; File file = new File ( "" ) ; if ( ! file . exists ( ) ) { file . mkdir ( ) ; } file = new File ( "" ) ; OutputStream out = new FileOutputStream ( file ) ; int read = ; byte [ ] bytes = new byte [ ] ; while ( ( read = in . read ( bytes ) ) != - ) { out . write ( bytes , , read ) ; } in . close ( ) ; out . flush ( ) ; out . close ( ) ; } catch ( IOException e ) { System . err . println ( "" ) ; } } public Integer reload ( ) { File plugin_settings = new File ( "" ) ; if ( ! plugin_settings . exists ( ) ) { return - ; } else { YamlConfiguration configTest = YamlConfiguration . loadConfiguration ( plugin_settings ) ; String verify = verifyIntegrity ( configTest ) ; if ( verify == "" ) { config = configTest ; return ; } else { return - ; } } } private String verifyIntegrity ( YamlConfiguration test ) { if ( test . getString ( "" , "" ) . equals ( "" ) ) { return "" ; } else if ( ! test . isString ( "" ) ) { return "" ; } else if ( ! test . isString ( "" ) ) { return "" ; } else if ( ! test . isString ( "" ) ) { return "" ; } else if ( ! test . isString ( "" ) ) { return "" ; } else if ( ! test . isString ( "" ) ) { return "" ; } else if ( ! test . isString ( "" ) ) { return "" ; } else if ( ! test . isBoolean ( "" ) ) { return "" ; } else if ( ! test . isBoolean ( "" ) ) { return "" ; } else if ( ! test . isBoolean ( "" ) ) { return "" ; } else if ( ! test . isBoolean ( "" ) ) { return "" ; } return "" ; } public String getString ( String variable ) { return config . getString ( variable , "" ) ; } public String getPrefix ( ) { return config . get ( "" , "" ) . toString ( ) ; } public Integer getInteger ( String variable ) { return config . getInt ( variable , ) ; } public boolean getBoolean ( String variable ) { return config . getBoolean ( variable , true ) ; } public double getDouble ( String variable ) { return config . getDouble ( variable , ) ; } public float getFloat ( String variable ) { return Float . valueOf ( config . getString ( variable , "" ) ) ; } } package uk . me . sample . android . confcaller ; public final class R { public static final class attr { } public static final class color { public static final int emptyTextColour = ; } public static final class drawable { public static final int ic_menu_add = ; public static final int ic_menu_call = ; public static final int ic_menu_close_clear_cancel = ; public static final int ic_menu_delete = ; public static final int ic_menu_edit = ; public static final int ic_menu_preferences = ; public static final int ic_menu_save = ; public static final int icon = ; } public static final class id { public static final int input_name = ; public static final int input_number = ; public static final int input_pin = ; public static final int item_name = ; public static final int list = ; public static final int newConf = ; public static final int save = ; public static final int settingsOption = ; } public static final class layout { public static final int contactslistitem = ; public static final int main = ; public static final int newconf = ; } public static final class menu { public static final int main = ; } public static final class string { public static final int app_name = ; public static final int button_cancel = ; public static final int button_save = ; public static final int emptyText = ; public static final int menu_delete = ; public static final int menu_edit = ; } public static final class xml { public static final int preferences = ; } } package uk . me . sample . android . confcaller ; import java . net . URLEncoder ; import android . app . ListActivity ; import android . content . Intent ; import android . content . SharedPreferences ; import android . database . Cursor ; import android . net . Uri ; import android . os . Bundle ; import android . preference . PreferenceManager ; import android . telephony . PhoneNumberUtils ; import android . view . ContextMenu ; import android . view . Menu ; import android . view . MenuItem ; import android . view . View ; import android . view . ContextMenu . ContextMenuInfo ; import android . widget . AdapterView ; import android . widget . ListView ; import android . widget . SimpleCursorAdapter ; import android . widget . TextView ; import android . widget . Toast ; import android . widget . AdapterView . AdapterContextMenuInfo ; import android . widget . AdapterView . OnItemClickListener ; public class ConfCaller extends ListActivity { private ConfDbAdapter mDbHelper ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; mDbHelper = new ConfDbAdapter ( this ) ; mDbHelper . open ( ) ; setListAdapter ( getList ( ) ) ; ListView lv = getListView ( ) ; lv . setTextFilterEnabled ( true ) ; registerForContextMenu ( lv ) ; lv . setOnItemClickListener ( new OnItemClickListener ( ) { public void onItemClick ( AdapterView < ? > parent , View view , int position , long id ) { Cursor confItem = mDbHelper . fetchConf ( id ) ; String confNumber = confItem . getString ( confItem . getColumnIndexOrThrow ( ConfDbAdapter . KEY_NUMBER ) ) ; String confPin = confItem . getString ( confItem . getColumnIndexOrThrow ( ConfDbAdapter . KEY_PIN ) ) ; SharedPreferences prefs = PreferenceManager . getDefaultSharedPreferences ( getApplicationContext ( ) ) ; String accessNumber = prefs . getString ( "" , "" ) ; String separator = prefs . getString ( "" , "" ) ; confItem . close ( ) ; mDbHelper . close ( ) ; if ( accessNumber . equals ( "" ) ) { Toast . makeText ( getApplicationContext ( ) , "" , Toast . LENGTH_LONG ) . show ( ) ; return ; } else { String telUri = "" + accessNumber + PhoneNumberUtils . PAUSE + confNumber + URLEncoder . encode ( separator ) + PhoneNumberUtils . PAUSE + confPin + URLEncoder . encode ( separator ) ; Toast . makeText ( getApplicationContext ( ) , "" + ( ( TextView ) view ) . getText ( ) , Toast . LENGTH_SHORT ) . show ( ) ; Intent call = new Intent ( android . content . Intent . ACTION_CALL , Uri . parse ( telUri ) ) ; startActivity ( call ) ; } } } ) ; } @ Override protected void onPause ( ) { mDbHelper . close ( ) ; super . onPause ( ) ; } @ Override protected void onResume ( ) { mDbHelper . open ( ) ; setListAdapter ( getList ( ) ) ; super . onResume ( ) ; } @ Override protected void onStop ( ) { mDbHelper . close ( ) ; super . onStop ( ) ; } private SimpleCursorAdapter getList ( ) { Cursor c = mDbHelper . fetchAllConfs ( ) ; startManagingCursor ( c ) ; String [ ] from = new String [ ] { ConfDbAdapter . KEY_NAME } ; int [ ] to = new int [ ] { R . id . item_name } ; SimpleCursorAdapter confs = new SimpleCursorAdapter ( this , R . layout . contactslistitem , c , from , to ) ; return confs ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { getMenuInflater ( ) . inflate ( R . menu . main , menu ) ; return super . onCreateOptionsMenu ( menu ) ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { Intent i ; switch ( item . getItemId ( ) ) { case R . id . newConf : i = new Intent ( this , NewConf . class ) ; startActivityForResult ( i , NewConf . ACTIVITY_CREATE ) ; return true ; case R . id . settingsOption : i = new Intent ( this , Preferences . class ) ; startActivity ( i ) ; return true ; default : return false ; } } static final int DELETE_ID = Menu . FIRST ; static final int EDIT_ID = Menu . FIRST + ; @ Override public void onCreateContextMenu ( ContextMenu menu , View v , ContextMenuInfo menuInfo ) { super . onCreateContextMenu ( menu , v , menuInfo ) ; menu . add ( , DELETE_ID , , R . string . menu_delete ) ; menu . add ( , EDIT_ID , , R . string . menu_edit ) ; } @ Override public boolean onContextItemSelected ( MenuItem item ) { AdapterContextMenuInfo info = ( AdapterContextMenuInfo ) item . getMenuInfo ( ) ; Intent i ; switch ( item . getItemId ( ) ) { case DELETE_ID : mDbHelper . deleteConf ( info . id ) ; setListAdapter ( getList ( ) ) ; return true ; case EDIT_ID : i = new Intent ( this , NewConf . class ) ; i . putExtra ( ConfDbAdapter . KEY_ROWID , info . id ) ; startActivityForResult ( i , NewConf . ACTIVITY_EDIT ) ; return true ; default : return false ; } } } package uk . me . sample . android . confcaller ; import android . app . Activity ; import android . database . Cursor ; import android . os . Bundle ; import android . view . View ; import android . view . View . OnClickListener ; import android . widget . Button ; import android . widget . EditText ; public class NewConf extends Activity { public static final int ACTIVITY_EDIT = ; public static final int ACTIVITY_CREATE = ; private EditText mNameText ; private EditText mNumberText ; private EditText mPinText ; private Long mRowId ; private ConfDbAdapter mDbHelper ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; mDbHelper = new ConfDbAdapter ( this ) ; mDbHelper . open ( ) ; setContentView ( R . layout . newconf ) ; mNameText = ( EditText ) findViewById ( R . id . input_name ) ; mNumberText = ( EditText ) findViewById ( R . id . input_number ) ; mPinText = ( EditText ) findViewById ( R . id . input_pin ) ; Button saveButton = ( Button ) findViewById ( R . id . save ) ; mRowId = ( savedInstanceState == null ) ? null : ( Long ) savedInstanceState . getSerializable ( ConfDbAdapter . KEY_ROWID ) ; if ( mRowId == null ) { Bundle extras = getIntent ( ) . getExtras ( ) ; if ( extras != null ) { mRowId = extras . getLong ( ConfDbAdapter . KEY_ROWID ) ; loadData ( ) ; } } saveButton . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { saveState ( ) ; mDbHelper . close ( ) ; finish ( ) ; } } ) ; } protected void loadData ( ) { if ( mRowId != null ) { Cursor conf = mDbHelper . fetchConf ( mRowId ) ; startManagingCursor ( conf ) ; mNameText . setText ( conf . getString ( conf . getColumnIndexOrThrow ( ConfDbAdapter . KEY_NAME ) ) ) ; mNumberText . setText ( conf . getString ( conf . getColumnIndexOrThrow ( ConfDbAdapter . KEY_NUMBER ) ) ) ; mPinText . setText ( conf . getString ( conf . getColumnIndexOrThrow ( ConfDbAdapter . KEY_PIN ) ) ) ; conf . close ( ) ; } } @ Override protected void onSaveInstanceState ( Bundle outState ) { super . onSaveInstanceState ( outState ) ; } @ Override protected void onPause ( ) { super . onPause ( ) ; mDbHelper . close ( ) ; } @ Override protected void onResume ( ) { super . onResume ( ) ; mDbHelper . open ( ) ; } private void saveState ( ) { String name = mNameText . getText ( ) . toString ( ) ; String number = mNumberText . getText ( ) . toString ( ) ; String pin = mPinText . getText ( ) . toString ( ) ; if ( mRowId == null ) { long id = mDbHelper . createConf ( name , number , pin ) ; if ( id > ) { mRowId = id ; } } else { mDbHelper . updateConf ( mRowId , name , number , pin ) ; } } } package uk . me . sample . android . confcaller ; import android . content . ContentValues ; import android . content . Context ; import android . database . Cursor ; import android . database . SQLException ; import android . database . sqlite . SQLiteDatabase ; import android . database . sqlite . SQLiteOpenHelper ; import android . util . Log ; public class ConfDbAdapter { public static final String KEY_ROWID = "" ; public static final String KEY_NAME = "" ; public static final String KEY_NUMBER = "" ; public static final String KEY_PIN = "" ; private static final String DATABASE_NAME = "" ; private static final String DATABASE_TABLE = "" ; private static final int DATABASE_VERSION = ; private static final String TAG = "" ; private DatabaseHelper mDbHelper ; private SQLiteDatabase mDb ; private static final String DATABASE_CREATE = "" + DATABASE_TABLE + "" + KEY_ROWID + "" + KEY_NAME + "" + KEY_NUMBER + "" + KEY_PIN + "" ; private final Context mCtx ; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper ( Context context ) { super ( context , DATABASE_NAME , null , DATABASE_VERSION ) ; } @ Override public void onCreate ( SQLiteDatabase db ) { db . execSQL ( DATABASE_CREATE ) ; } @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { Log . w ( TAG , "" + oldVersion + "" + newVersion + "" ) ; db . execSQL ( "" + DATABASE_TABLE ) ; onCreate ( db ) ; } } public ConfDbAdapter ( Context ctx ) { this . mCtx = ctx ; } public ConfDbAdapter open ( ) throws SQLException { mDbHelper = new DatabaseHelper ( mCtx ) ; mDb = mDbHelper . getWritableDatabase ( ) ; return this ; } public void close ( ) { mDbHelper . close ( ) ; } public long createConf ( String name , String number , String pin ) { ContentValues initialValues = new ContentValues ( ) ; initialValues . put ( KEY_NAME , name ) ; initialValues . put ( KEY_NUMBER , number ) ; initialValues . put ( KEY_PIN , pin ) ; return mDb . insert ( DATABASE_TABLE , null , initialValues ) ; } public boolean deleteConf ( long rowId ) { return mDb . delete ( DATABASE_TABLE , KEY_ROWID + "" + rowId , null ) > ; } public Cursor fetchAllConfs ( ) { return mDb . query ( DATABASE_TABLE , new String [ ] { KEY_ROWID , KEY_NAME , KEY_NUMBER , KEY_PIN } , null , null , null , null , KEY_NAME ) ; } public Cursor fetchConf ( long rowId ) throws SQLException { Cursor mCursor = mDb . query ( true , DATABASE_TABLE , new String [ ] { KEY_ROWID , KEY_NAME , KEY_NUMBER , KEY_PIN } , KEY_ROWID + "" + rowId , null , null , null , null , null ) ; if ( mCursor != null ) { mCursor . moveToFirst ( ) ; } return mCursor ; } public boolean updateConf ( long rowId , String name , String number , String pin ) { ContentValues args = new ContentValues ( ) ; args . put ( KEY_NAME , name ) ; args . put ( KEY_NUMBER , number ) ; args . put ( KEY_PIN , pin ) ; return mDb . update ( DATABASE_TABLE , args , KEY_ROWID + "" + rowId , null ) > ; } } package uk . me . sample . android . confcaller ; import android . os . Bundle ; import android . preference . PreferenceActivity ; public class Preferences extends PreferenceActivity { @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; addPreferencesFromResource ( R . xml . preferences ) ; } } package com . pogofish . jadt . maven ; import java . io . File ; import org . apache . maven . plugin . AbstractMojo ; import org . apache . maven . plugin . MojoExecutionException ; import org . apache . maven . project . MavenProject ; import com . pogofish . jadt . JADT ; public class JADTMojo extends AbstractMojo { JADT jadt = JADT . standardConfigDriver ( ) ; File srcPath = new File ( "" ) ; File destDir = new File ( "" ) ; MavenProject project = null ; @ Override public void execute ( ) throws MojoExecutionException { try { project . addCompileSourceRoot ( destDir . getCanonicalPath ( ) ) ; jadt . parseAndEmit ( srcPath . getCanonicalPath ( ) , destDir . getCanonicalPath ( ) ) ; } catch ( Exception e ) { throw new MojoExecutionException ( "" , e ) ; } } public void setSrcPath ( File srcPath ) { this . srcPath = srcPath ; } public void setDestDir ( File destDir ) { this . destDir = destDir ; } public void setProject ( MavenProject project ) { this . project = project ; } } package com . pogofish . jadt . maven ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . fail ; import java . io . File ; import java . util . Collections ; import org . apache . maven . plugin . MojoExecutionException ; import org . apache . maven . project . MavenProject ; import org . junit . Test ; import com . pogofish . jadt . JADT ; import com . pogofish . jadt . errors . SemanticError ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . sink . StringSinkFactoryFactory ; public class JADTMojoTest { @ Test public void testHappy ( ) throws Exception { final File srcFile = new File ( JADT . TEST_SRC_INFO ) ; final File destDir = new File ( JADT . TEST_DIR ) ; final JADTMojo mojo = new JADTMojo ( ) ; final StringSinkFactoryFactory factory = new StringSinkFactoryFactory ( ) ; mojo . jadt = JADT . createDummyJADT ( Collections . < SyntaxError > emptyList ( ) , Collections . < SemanticError > emptyList ( ) , srcFile . getCanonicalPath ( ) , factory ) ; mojo . setSrcPath ( srcFile ) ; mojo . setDestDir ( destDir ) ; mojo . setProject ( new MavenProject ( ) ) ; mojo . execute ( ) ; final String result = factory . results ( ) . get ( destDir . getCanonicalPath ( ) ) . get ( ) . getResults ( ) . get ( JADT . TEST_CLASS_NAME ) ; assertEquals ( JADT . TEST_SRC_INFO , result ) ; assertEquals ( , mojo . project . getCompileSourceRoots ( ) . size ( ) ) ; assertEquals ( destDir . getCanonicalPath ( ) , mojo . project . getCompileSourceRoots ( ) . get ( ) ) ; } @ Test public void testException ( ) throws Exception { final File srcFile = new File ( JADT . TEST_SRC_INFO ) ; final File destDir = new File ( JADT . TEST_DIR ) ; final JADTMojo mojo = new JADTMojo ( ) ; final StringSinkFactoryFactory factory = new StringSinkFactoryFactory ( ) ; mojo . jadt = JADT . createDummyJADT ( Collections . < SyntaxError > emptyList ( ) , Collections . < SemanticError > singletonList ( SemanticError . _DuplicateConstructor ( "" , "" ) ) , srcFile . getCanonicalPath ( ) , factory ) ; mojo . setSrcPath ( srcFile ) ; mojo . setDestDir ( destDir ) ; mojo . setProject ( new MavenProject ( ) ) ; try { mojo . execute ( ) ; final String result = factory . results ( ) . get ( destDir . getCanonicalPath ( ) ) . get ( ) . getResults ( ) . get ( JADT . TEST_CLASS_NAME ) ; fail ( "" + result ) ; } catch ( MojoExecutionException e ) { } } } package com . pogofish . jadt . sink ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . fail ; import org . junit . Test ; public class StringSinkTest { @ Test public void testHappy ( ) { final StringSink sink = new StringSink ( "" ) ; try { sink . write ( "" ) ; } finally { sink . close ( ) ; } assertEquals ( "" , sink . result ( ) ) ; } @ Test public void testExceptionIfNotClosed ( ) { final StringSink sink = new StringSink ( "" ) ; try { sink . write ( "" ) ; final String result = sink . result ( ) ; fail ( "" + result ) ; } catch ( RuntimeException e ) { assertEquals ( "" , e . getMessage ( ) ) ; } finally { sink . close ( ) ; } } } package com . pogofish . jadt . sink ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertNotSame ; import static org . junit . Assert . assertSame ; import java . util . List ; import java . util . Map ; import org . junit . Test ; public class StringSinkFactoryFactoryTest { @ Test public void test ( ) { final StringSinkFactoryFactory ugh = new StringSinkFactoryFactory ( ) ; final StringSinkFactory sf1 = ugh . createSinkFactory ( "" ) ; final StringSinkFactory sf2 = ugh . createSinkFactory ( "" ) ; final StringSinkFactory sf3 = ugh . createSinkFactory ( "" ) ; assertNotSame ( sf1 , sf2 ) ; assertNotSame ( sf2 , sf3 ) ; assertNotSame ( sf1 , sf3 ) ; final Map < String , List < StringSinkFactory > > results = ugh . results ( ) ; assertEquals ( , results . size ( ) ) ; final List < StringSinkFactory > result1 = results . get ( "" ) ; assertEquals ( , result1 . size ( ) ) ; assertSame ( sf1 , result1 . get ( ) ) ; assertSame ( sf2 , result1 . get ( ) ) ; final List < StringSinkFactory > result2 = results . get ( "" ) ; assertEquals ( , result2 . size ( ) ) ; assertSame ( sf3 , result2 . get ( ) ) ; } } package com . pogofish . jadt . sink ; import static org . junit . Assert . assertEquals ; import java . io . BufferedReader ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import org . junit . Test ; public class FileSinkTest { @ Test public void testMissingFile ( ) throws IOException { final File temp = File . createTempFile ( "" , "" ) ; try { temp . delete ( ) ; final FileSink sink = new FileSink ( temp . getAbsolutePath ( ) ) ; try { sink . write ( "" ) ; } finally { sink . close ( ) ; } final BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( temp ) , "" ) ) ; final String contents = reader . readLine ( ) ; assertEquals ( "" , contents ) ; } finally { if ( temp . exists ( ) ) { temp . delete ( ) ; } } } @ Test public void testExistingFile ( ) throws IOException { final File temp = File . createTempFile ( "" , "" ) ; try { temp . createNewFile ( ) ; final BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( temp ) , "" ) ) ; try { writer . write ( "" ) ; } finally { writer . close ( ) ; } final FileSink sink = new FileSink ( temp . getAbsolutePath ( ) ) ; try { sink . write ( "" ) ; } finally { sink . close ( ) ; } final BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( temp ) , "" ) ) ; final String contents = reader . readLine ( ) ; assertEquals ( "" , contents ) ; } finally { if ( temp . exists ( ) ) { temp . delete ( ) ; } } } } package com . pogofish . jadt . sink ; import static com . pogofish . jadt . util . TestUtil . assertEqualsBarringFileSeparators ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; import java . io . File ; import java . io . IOException ; import org . junit . Test ; public class FileSinkFactoryTest { @ Test public void testCreate ( ) throws IOException { final String tempDir = new File ( System . getProperty ( "" ) ) . getCanonicalPath ( ) ; final FileSinkFactory factory = new FileSinkFactory ( tempDir ) ; final FileSink sink = ( FileSink ) factory . createSink ( "" ) ; try { assertTrue ( "" , sink . outputFile . exists ( ) ) ; assertEquals ( new File ( tempDir + "" ) . getCanonicalPath ( ) , sink . outputFile . getCanonicalPath ( ) ) ; } finally { sink . outputFile . delete ( ) ; } } @ Test public void testFactorySlash ( ) { final FileSinkFactory factory = new FileSinkFactory ( "" ) ; final String path = factory . convertToPath ( "" ) ; assertEqualsBarringFileSeparators ( "" , path ) ; } @ Test public void testFactoryNoSlash ( ) { final FileSinkFactory factory = new FileSinkFactory ( "" ) ; final String path = factory . convertToPath ( "" ) ; assertEqualsBarringFileSeparators ( "" , path ) ; } } package com . pogofish . jadt . sink ; import static org . junit . Assert . assertEquals ; import org . junit . Test ; public class FileSinkFactoryFactoryTest { @ Test public void test ( ) { final FileSinkFactoryFactory factoryFactory = new FileSinkFactoryFactory ( ) ; final FileSinkFactory sinkFactory = ( FileSinkFactory ) factoryFactory . createSinkFactory ( "" ) ; assertEquals ( "" , sinkFactory . destDirName ) ; } } package com . pogofish . jadt . printer ; import static com . pogofish . jadt . ast . ASTConstants . EMPTY_PKG ; import static com . pogofish . jadt . ast . ASTConstants . NO_COMMENTS ; import static com . pogofish . jadt . ast . ASTConstants . NO_IMPORTS ; import static com . pogofish . jadt . ast . Annotation . _Annotation ; import static com . pogofish . jadt . ast . AnnotationElement . _ElementValue ; import static com . pogofish . jadt . ast . AnnotationElement . _ElementValuePairs ; import static com . pogofish . jadt . ast . AnnotationKeyValue . _AnnotationKeyValue ; import static com . pogofish . jadt . ast . AnnotationValue . _AnnotationValueAnnotation ; import static com . pogofish . jadt . ast . AnnotationValue . _AnnotationValueExpression ; import static com . pogofish . jadt . ast . ArgModifier . _Final ; import static com . pogofish . jadt . ast . ArgModifier . _Transient ; import static com . pogofish . jadt . ast . ArgModifier . _Volatile ; import static com . pogofish . jadt . ast . BlockToken . _BlockEOL ; import static com . pogofish . jadt . ast . BlockToken . _BlockWhiteSpace ; import static com . pogofish . jadt . ast . BlockToken . _BlockWord ; import static com . pogofish . jadt . ast . Expression . * ; import static com . pogofish . jadt . ast . JDTagSection . _JDTagSection ; import static com . pogofish . jadt . ast . JDToken . _JDAsterisk ; import static com . pogofish . jadt . ast . JDToken . _JDEOL ; import static com . pogofish . jadt . ast . JDToken . _JDTag ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import static com . pogofish . jadt . ast . JDToken . _JDWord ; import static com . pogofish . jadt . ast . JavaComment . _JavaBlockComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaEOLComment ; import static com . pogofish . jadt . ast . Literal . _BooleanLiteral ; import static com . pogofish . jadt . ast . Literal . _CharLiteral ; import static com . pogofish . jadt . ast . Literal . _FloatingPointLiteral ; import static com . pogofish . jadt . ast . Literal . _IntegerLiteral ; import static com . pogofish . jadt . ast . Literal . _NullLiteral ; import static com . pogofish . jadt . ast . Literal . _StringLiteral ; import static com . pogofish . jadt . ast . Optional . _Some ; import static com . pogofish . jadt . ast . PrimitiveType . _BooleanType ; import static com . pogofish . jadt . ast . PrimitiveType . _ByteType ; import static com . pogofish . jadt . ast . PrimitiveType . _CharType ; import static com . pogofish . jadt . ast . PrimitiveType . _DoubleType ; import static com . pogofish . jadt . ast . PrimitiveType . _FloatType ; import static com . pogofish . jadt . ast . PrimitiveType . _IntType ; import static com . pogofish . jadt . ast . PrimitiveType . _LongType ; import static com . pogofish . jadt . ast . PrimitiveType . _ShortType ; import static com . pogofish . jadt . ast . RefType . _ArrayType ; import static com . pogofish . jadt . ast . RefType . _ClassType ; import static com . pogofish . jadt . ast . Type . _Primitive ; import static com . pogofish . jadt . ast . Type . _Ref ; import static com . pogofish . jadt . printer . ASTPrinter . print ; import static com . pogofish . jadt . printer . ASTPrinter . printComments ; import static com . pogofish . jadt . util . Util . list ; import static junit . framework . Assert . assertEquals ; import static org . junit . Assert . assertFalse ; import java . util . List ; import org . junit . Test ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . AnnotationElement ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . BlockToken ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Expression ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . JDToken ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . ast . Literal ; import com . pogofish . jadt . ast . Optional ; import com . pogofish . jadt . ast . Pkg ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . util . Util ; public class ASTPrinterTest { private static final BlockToken BLOCKEOL = _BlockEOL ( "" ) ; private static final BlockToken BLOCKSTART = _BlockWord ( "" ) ; private static final BlockToken BLOCKEND = _BlockWord ( "" ) ; private static final BlockToken BLOCKONEWS = _BlockWhiteSpace ( "" ) ; private static final JDToken ONEEOL = _JDEOL ( "" ) ; private static final JDToken ONEWS = _JDWhiteSpace ( "" ) ; private static final List < JDToken > NO_TOKENS = Util . < JDToken > list ( ) ; private static final List < RefType > NO_TYPE_ARGS = Util . < RefType > list ( ) ; private static final List < JDTagSection > NO_TAG_SECTIONS = Util . < JDTagSection > list ( ) ; private static final Optional < RefType > NO_EXTENDS = Optional . < RefType > _None ( ) ; private static final List < RefType > NO_IMPLEMENTS = Util . < RefType > list ( ) ; private static final List < Annotation > NO_ANNOTATIONS = Util . < Annotation > list ( ) ; @ Test public void constructorTest ( ) { final ASTPrinter printer = new ASTPrinter ( ) ; assertFalse ( printer . toString ( ) . isEmpty ( ) ) ; } @ Test public void testPrimitiveTypes ( ) { assertEquals ( "" , print ( _Primitive ( _BooleanType ( ) ) ) ) ; assertEquals ( "" , print ( _Primitive ( _ByteType ( ) ) ) ) ; assertEquals ( "" , print ( _Primitive ( _CharType ( ) ) ) ) ; assertEquals ( "" , print ( _Primitive ( _ShortType ( ) ) ) ) ; assertEquals ( "" , print ( _Primitive ( _IntType ( ) ) ) ) ; assertEquals ( "" , print ( _Primitive ( _LongType ( ) ) ) ) ; assertEquals ( "" , print ( _Primitive ( _FloatType ( ) ) ) ) ; assertEquals ( "" , print ( _Primitive ( _DoubleType ( ) ) ) ) ; } @ Test public void testClassTypes ( ) { assertEquals ( "" , print ( _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) ) ) ; assertEquals ( "" , print ( _Ref ( _ClassType ( "" , list ( _ClassType ( "" , Util . < RefType > list ( ) ) ) ) ) ) ) ; assertEquals ( "" , print ( _Ref ( _ClassType ( "" , list ( _ClassType ( "" , Util . < RefType > list ( ) ) , _ClassType ( "" , list ( ( _ClassType ( "" , list ( _ClassType ( "" , Util . < RefType > list ( ) ) ) ) ) ) ) ) ) ) ) ) ; } @ Test public void testArrayTypes ( ) { assertEquals ( "" , print ( _Ref ( _ArrayType ( _Primitive ( _BooleanType ( ) ) ) ) ) ) ; assertEquals ( "" , print ( _Ref ( _ArrayType ( _Ref ( _ArrayType ( _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) ) ) ) ) ) ) ; } @ Test public void testArg ( ) { assertEquals ( "" , print ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ArrayType ( _Primitive ( _BooleanType ( ) ) ) ) , "" ) ) ) ; assertEquals ( "" , print ( new Arg ( list ( _Final ( ) ) , _Ref ( _ArrayType ( _Primitive ( _BooleanType ( ) ) ) ) , "" ) ) ) ; assertEquals ( "" , print ( new Arg ( list ( _Final ( ) , _Final ( ) ) , _Ref ( _ArrayType ( _Primitive ( _BooleanType ( ) ) ) ) , "" ) ) ) ; } @ Test public void testArgModifier ( ) { assertEquals ( "" , print ( _Final ( ) ) ) ; assertEquals ( "" , print ( _Volatile ( ) ) ) ; assertEquals ( "" , print ( _Transient ( ) ) ) ; } @ Test public void testConstructors ( ) { assertEquals ( "" , print ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ; assertEquals ( "" , print ( new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _BooleanType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) ) ) ) ) ; } @ Test public void testDataTypes ( ) { assertEquals ( "" + "" + "" , print ( new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) ; assertEquals ( "" + "" + "" , print ( new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , _Some ( _ClassType ( "" , NO_TYPE_ARGS ) ) , list ( _ClassType ( "" , NO_TYPE_ARGS ) , _ClassType ( "" , NO_TYPE_ARGS ) ) , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) ; assertEquals ( "" + "" + "" , print ( new DataType ( NO_COMMENTS , list ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) , _Annotation ( "" , _Some ( _ElementValue ( _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) ; } @ Test public void testDoc ( ) { assertEquals ( "" , print ( new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Util . < DataType > list ( ) ) ) ) ; assertEquals ( "" , print ( new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , NO_IMPORTS , Util . < DataType > list ( ) ) ) ) ; assertEquals ( "" , print ( new Doc ( "" , EMPTY_PKG , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) , Imprt . _Imprt ( NO_COMMENTS , "" ) ) , Util . < DataType > list ( ) ) ) ) ; assertEquals ( "" , print ( new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) , Imprt . _Imprt ( NO_COMMENTS , "" ) ) , Util . < DataType > list ( ) ) ) ) ; assertEquals ( "" , print ( new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) , Imprt . _Imprt ( NO_COMMENTS , "" ) ) , list ( new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) ) ) ; } @ Test public void testJDGeneralSection ( ) { testComment ( "" , _JavaDocComment ( "" , list ( ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; testComment ( "" , _JavaDocComment ( "" , list ( ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; testComment ( "" , _JavaDocComment ( "" , list ( ONEWS , _JDAsterisk ( ) , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; testComment ( "" , _JavaDocComment ( "" , list ( ONEWS , _JDAsterisk ( ) , ONEEOL , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; testComment ( "" , _JavaDocComment ( "" , list ( ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; testComment ( "" , _JavaDocComment ( "" , list ( ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEWS , _JDTag ( "" ) , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; testComment ( "" , _JavaDocComment ( "" , list ( ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDAsterisk ( ) , ONEWS , _JDTag ( "" ) , ONEEOL , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; } @ Test public void testJDTagSections ( ) { testComment ( "" , _JavaDocComment ( "" , NO_TOKENS , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) ) ) ) , "" ) ) ; testComment ( "" , _JavaDocComment ( "" , NO_TOKENS , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) ) ) ) , "" ) ) ; testComment ( "" , _JavaDocComment ( "" , NO_TOKENS , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL ) ) , _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) ) ) ) , "" ) ) ; } @ Test public void testJDFull ( ) { testComment ( "" , _JavaDocComment ( "" , list ( ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDAsterisk ( ) , ONEWS , _JDTag ( "" ) , ONEEOL , ONEWS ) , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL ) ) , _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) ) ) ) , "" ) ) ; } private void testComment ( String expected , JavaComment comment ) { assertEquals ( expected , ASTPrinter . print ( "" , comment ) ) ; } @ Test public void testComments ( ) { @ SuppressWarnings ( "" ) final List < JavaComment > comments = Util . < JavaComment > list ( _JavaDocComment ( "" , list ( _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) , _JavaBlockComment ( list ( list ( BLOCKSTART , BLOCKONEWS , _BlockWord ( "" ) , BLOCKONEWS , BLOCKEND ) ) ) , _JavaEOLComment ( "" ) ) ; assertEquals ( "" , printComments ( "" , comments ) ) ; } @ SuppressWarnings ( "" ) @ Test public void testBlockComment ( ) { testComment ( "" , _JavaBlockComment ( list ( list ( BLOCKSTART , BLOCKONEWS , BLOCKEND ) ) ) ) ; testComment ( "" , _JavaBlockComment ( list ( list ( BLOCKSTART , BLOCKONEWS , _BlockWord ( "" ) , BLOCKONEWS , BLOCKEND ) ) ) ) ; testComment ( "" , _JavaBlockComment ( list ( list ( BLOCKSTART , BLOCKONEWS , _BlockWord ( "" ) , BLOCKEOL ) , list ( BLOCKONEWS , _BlockWord ( "" ) , BLOCKONEWS , _BlockWord ( "" ) , BLOCKONEWS , BLOCKEND ) ) ) ) ; } @ Test public void testLiteral ( ) { testLiteral ( "" , _NullLiteral ( ) ) ; testLiteral ( "" , _StringLiteral ( "" ) ) ; testLiteral ( "" , _FloatingPointLiteral ( "" ) ) ; testLiteral ( "" , _IntegerLiteral ( "" ) ) ; testLiteral ( "" , _CharLiteral ( "" ) ) ; testLiteral ( "" , _BooleanLiteral ( "" ) ) ; } @ Test public void testExpression ( ) { testExpression ( "" , _TernaryExpression ( _VariableExpression ( Optional . < Expression > _None ( ) , "" ) , _VariableExpression ( Optional . < Expression > _None ( ) , "" ) , _VariableExpression ( Optional . < Expression > _None ( ) , "" ) ) ) ; testExpression ( "" , _LiteralExpression ( _NullLiteral ( ) ) ) ; testExpression ( "" , _VariableExpression ( Optional . < Expression > _None ( ) , "" ) ) ; testExpression ( "" , _VariableExpression ( _Some ( _LiteralExpression ( _NullLiteral ( ) ) ) , "" ) ) ; testExpression ( "" , _NestedExpression ( _LiteralExpression ( _NullLiteral ( ) ) ) ) ; testExpression ( "" , _ClassReference ( _Primitive ( _BooleanType ( ) ) ) ) ; } private void testExpression ( String expected , Expression expression ) { assertEquals ( expected , ASTPrinter . print ( expression ) ) ; } private void testLiteral ( String expected , Literal literal ) { assertEquals ( expected , ASTPrinter . print ( literal ) ) ; } @ Test public void testAnnotation ( ) { testAnnotation ( "" , _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ; testAnnotation ( "" , _Annotation ( "" , _Some ( _ElementValue ( _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) ; testAnnotation ( "" , _Annotation ( "" , _Some ( _ElementValue ( _AnnotationValueExpression ( _LiteralExpression ( _NullLiteral ( ) ) ) ) ) ) ) ; testAnnotation ( "" , _Annotation ( "" , _Some ( _ElementValuePairs ( list ( _AnnotationKeyValue ( "" , _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) ) ) ; testAnnotation ( "" , _Annotation ( "" , _Some ( _ElementValuePairs ( list ( _AnnotationKeyValue ( "" , _AnnotationValueExpression ( _LiteralExpression ( _NullLiteral ( ) ) ) ) ) ) ) ) ) ; testAnnotation ( "" , _Annotation ( "" , _Some ( _ElementValuePairs ( list ( _AnnotationKeyValue ( "" , _AnnotationValueExpression ( _LiteralExpression ( _NullLiteral ( ) ) ) ) , _AnnotationKeyValue ( "" , _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) ) ) ; } private void testAnnotation ( String expected , Annotation annotation ) { assertEquals ( expected , ASTPrinter . print ( annotation ) ) ; } } package com . pogofish . jadt . printer ; import static com . pogofish . jadt . errors . SemanticError . _ConstructorDataTypeConflict ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateArgName ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateConstructor ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateDataType ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateModifier ; import static com . pogofish . jadt . errors . SyntaxError . _UnexpectedToken ; import static com . pogofish . jadt . errors . UserError . _Semantic ; import static com . pogofish . jadt . errors . UserError . _Syntactic ; import static com . pogofish . jadt . printer . UserErrorPrinter . print ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertFalse ; import org . junit . Test ; public class UserErrorPrinterTest { @ Test public void constructorTest ( ) { final UserErrorPrinter printer = new UserErrorPrinter ( ) ; assertFalse ( printer . toString ( ) . isEmpty ( ) ) ; } @ Test public void test ( ) { assertEquals ( "" , print ( _Syntactic ( _UnexpectedToken ( "" , "" , ) ) ) ) ; assertEquals ( "" , print ( _Semantic ( _DuplicateDataType ( "" ) ) ) ) ; assertEquals ( "" , print ( _Semantic ( _ConstructorDataTypeConflict ( "" ) ) ) ) ; assertEquals ( "" , print ( _Semantic ( _DuplicateConstructor ( "" , "" ) ) ) ) ; assertEquals ( "" , print ( _Semantic ( _DuplicateArgName ( "" , "" , "" ) ) ) ) ; assertEquals ( "" , print ( _Semantic ( _DuplicateModifier ( "" , "" , "" , "" ) ) ) ) ; } } package com . pogofish . jadt . util ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertFalse ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . junit . Test ; public class UtilTest { @ Test public void constructorTest ( ) { final Util util = new Util ( ) ; assertFalse ( util . toString ( ) . isEmpty ( ) ) ; } @ Test public void testList ( ) { final List < String > list = new ArrayList < String > ( ) ; list . add ( "" ) ; list . add ( "" ) ; assertEquals ( list , Util . list ( "" , "" ) ) ; } @ Test public void testSet ( ) { final Set < String > set = new HashSet < String > ( ) ; set . add ( "" ) ; set . add ( "" ) ; assertEquals ( set , Util . set ( "" , "" ) ) ; } } package com . pogofish . jadt . util ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertSame ; import static org . junit . Assert . fail ; import java . io . IOException ; import org . junit . Test ; public class ExceptionActionTest { @ Test public void testNoException ( ) { final String result = Util . execute ( new ExceptionAction < String > ( ) { @ Override public String doAction ( ) throws IOException { return "" ; } } ) ; assertEquals ( "" , result ) ; } @ Test public void testException ( ) { final IOException thrown = new IOException ( "" ) ; try { final String result = Util . execute ( new ExceptionAction < String > ( ) { @ Override public String doAction ( ) throws IOException { throw thrown ; } } ) ; fail ( "" + result ) ; } catch ( RuntimeException e ) { assertSame ( "" , e . getCause ( ) , thrown ) ; } } @ Test public void testRuntimeException ( ) { final RuntimeException thrown = new RuntimeException ( "" ) ; try { final String result = Util . execute ( new ExceptionAction < String > ( ) { @ Override public String doAction ( ) { throw thrown ; } } ) ; fail ( "" + result ) ; } catch ( RuntimeException e ) { assertSame ( "" , e , thrown ) ; } } @ Test public void testError ( ) { final Error thrown = new Error ( "" ) ; try { final String result = Util . execute ( new ExceptionAction < String > ( ) { @ Override public String doAction ( ) { throw thrown ; } } ) ; fail ( "" + result ) ; } catch ( Error e ) { assertSame ( "" , e , thrown ) ; } } } package com . pogofish . jadt . util ; import java . io . File ; import java . io . IOException ; import static org . junit . Assert . assertEquals ; public class TestUtil { public static File createTmpDir ( ) throws IOException { final File tmp = File . createTempFile ( "" , "" + System . nanoTime ( ) ) ; if ( ! tmp . delete ( ) ) { throw new IOException ( "" + tmp . getAbsolutePath ( ) ) ; } if ( ! tmp . mkdir ( ) ) { throw new IOException ( "" + tmp . getAbsolutePath ( ) ) ; } return tmp ; } public static void assertEqualsBarringFileSeparators ( String expected , String actual ) { assertEquals ( sanitize ( expected ) , sanitize ( actual ) ) ; } private static String sanitize ( String s ) { return s . replaceAll ( "" , "" ) . replaceAll ( "" , "" ) ; } } package com . pogofish . jadt ; import static com . pogofish . jadt . errors . SemanticError . _ConstructorDataTypeConflict ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateConstructor ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; import static org . junit . Assert . fail ; import java . io . BufferedReader ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . util . Collections ; import java . util . List ; import org . junit . Test ; import com . pogofish . jadt . checker . StandardChecker ; import com . pogofish . jadt . emitter . StandardDocEmitter ; import com . pogofish . jadt . errors . SemanticError ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . errors . UserError ; import com . pogofish . jadt . parser . StandardParser ; import com . pogofish . jadt . sink . FileSinkFactoryFactory ; import com . pogofish . jadt . sink . StringSinkFactoryFactory ; import com . pogofish . jadt . source . FileSourceFactory ; import com . pogofish . jadt . util . TestUtil ; import com . pogofish . jadt . util . Util ; public class JADTTest { private static final List < SyntaxError > NO_SYNTAX_ERRORS = Collections . < SyntaxError > emptyList ( ) ; private static final List < SemanticError > NO_SEMANTIC_ERRORS = Collections . < SemanticError > emptyList ( ) ; private static final String [ ] GOOD_ARGS = new String [ ] { JADT . TEST_SRC_INFO , JADT . TEST_DIR } ; @ Test public void testStandardConfig ( ) { final JADT driver = JADT . standardConfigDriver ( ) ; assertTrue ( "" , driver . sourceFactory instanceof FileSourceFactory ) ; assertTrue ( "" , driver . parser instanceof StandardParser ) ; assertTrue ( "" , driver . checker instanceof StandardChecker ) ; assertTrue ( "" , driver . emitter instanceof StandardDocEmitter ) ; assertTrue ( "" , driver . factoryFactory instanceof FileSinkFactoryFactory ) ; } private String testWithDummyJADT ( String [ ] args , List < SyntaxError > syntaxErrors , List < SemanticError > semanticErrors ) { final StringSinkFactoryFactory factory = new StringSinkFactoryFactory ( ) ; JADT . createDummyJADT ( syntaxErrors , semanticErrors , JADT . TEST_SRC_INFO , factory ) . parseAndEmit ( args ) ; return factory . results ( ) . get ( JADT . TEST_DIR ) . get ( ) . getResults ( ) . get ( JADT . TEST_CLASS_NAME ) ; } @ Test public void testDriverBadArgs ( ) { try { final String result = testWithDummyJADT ( new String [ ] { JADT . TEST_SRC_INFO } , NO_SYNTAX_ERRORS , NO_SEMANTIC_ERRORS ) ; fail ( "" + result ) ; } catch ( IllegalArgumentException e ) { } } @ Test public void testDriverGood ( ) { final String result = testWithDummyJADT ( GOOD_ARGS , NO_SYNTAX_ERRORS , NO_SEMANTIC_ERRORS ) ; assertEquals ( JADT . TEST_SRC_INFO , result ) ; } @ Test public void testDriverSyntacticIssue ( ) { final List < SyntaxError > errors = Util . list ( SyntaxError . _UnexpectedToken ( "" , "" , ) ) ; try { final String result = testWithDummyJADT ( GOOD_ARGS , errors , NO_SEMANTIC_ERRORS ) ; fail ( "" + result ) ; } catch ( JADTUserErrorsException e ) { final List < UserError > userErrors = e . getErrors ( ) ; assertEquals ( errors . size ( ) , userErrors . size ( ) ) ; for ( SyntaxError error : errors ) { final UserError userError = UserError . _Syntactic ( error ) ; assertTrue ( "" + userError , userErrors . contains ( userError ) ) ; } } } @ Test public void testDriverSemanticIssue ( ) { final List < SemanticError > errors = Util . < SemanticError > list ( _DuplicateConstructor ( "" , "" ) , _ConstructorDataTypeConflict ( "" ) ) ; try { final String result = testWithDummyJADT ( GOOD_ARGS , NO_SYNTAX_ERRORS , errors ) ; fail ( "" + result ) ; } catch ( JADTUserErrorsException e ) { final List < UserError > userErrors = e . getErrors ( ) ; assertEquals ( errors . size ( ) , userErrors . size ( ) ) ; for ( SemanticError error : errors ) { final UserError userError = UserError . _Semantic ( error ) ; assertTrue ( "" + userError , userErrors . contains ( userError ) ) ; } } } @ Test public void testMain ( ) throws IOException { final File srcFile = File . createTempFile ( "" , "" ) ; try { final BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( srcFile ) , "" ) ) ; try { writer . write ( "" ) ; writer . close ( ) ; final File tmpDir = TestUtil . createTmpDir ( ) ; try { JADT . main ( new String [ ] { srcFile . getAbsolutePath ( ) , tmpDir . getAbsolutePath ( ) } ) ; final File outputFile = new File ( tmpDir , "" ) ; try { assertTrue ( "" + outputFile . getAbsolutePath ( ) , outputFile . exists ( ) ) ; final BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( outputFile ) , "" ) ) ; try { assertStartsWith ( "" , reader . readLine ( ) ) ; assertStartsWith ( "" , reader . readLine ( ) ) ; } finally { reader . close ( ) ; } } finally { outputFile . delete ( ) ; } } finally { tmpDir . delete ( ) ; } } finally { writer . close ( ) ; } } finally { srcFile . delete ( ) ; } } private void assertStartsWith ( String expected , String actual ) { assertTrue ( "" + expected + "" + actual + "" , actual . startsWith ( expected ) ) ; } } package com . pogofish . jadt . parser ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertSame ; import static org . junit . Assert . fail ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . Reader ; import java . util . List ; import org . junit . Test ; import com . pogofish . jadt . ast . ASTConstants ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . ast . ParseResult ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . source . Source ; import com . pogofish . jadt . source . StringSource ; import com . pogofish . jadt . util . Util ; public class ParserTest { @ Test public void testErrorClosing ( ) { final IOException thrown = new IOException ( "" ) ; final Source source = new Source ( ) { @ Override public String getSrcInfo ( ) { return "" ; } @ Override public BufferedReader createReader ( ) { return new BufferedReader ( new Reader ( ) { @ Override public int read ( char [ ] cbuf , int off , int len ) throws IOException { throw new RuntimeException ( "" ) ; } @ Override public void close ( ) throws IOException { throw thrown ; } } ) ; } } ; final Parser parser = new StandardParser ( new ParserImplFactory ( ) { @ Override public ParserImpl create ( String srcInfo , Reader reader ) { return new BaseTestParserImpl ( ) { @ Override public Doc doc ( ) throws Exception { return Doc . _Doc ( "" , ASTConstants . EMPTY_PKG , Util . < Imprt > list ( ) , Util . < DataType > list ( ) ) ; } @ Override public List < SyntaxError > errors ( ) { return Util . < SyntaxError > list ( ) ; } } ; } } ) ; try { final ParseResult parseResult = parser . parse ( source ) ; fail ( "" + parseResult ) ; } catch ( RuntimeException caught ) { assertEquals ( "" , thrown , caught . getCause ( ) ) ; } } @ Test public void testExceptionHandling ( ) { final Throwable thrown1 = new RuntimeException ( "" ) ; try { final Parser parser = new StandardParser ( new ThrowingParserImplFactory ( thrown1 ) ) ; final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; fail ( "" + result ) ; } catch ( RuntimeException caught ) { assertSame ( "" , thrown1 , caught ) ; } final Throwable thrown2 = new Error ( "" ) ; try { final Parser parser = new StandardParser ( new ThrowingParserImplFactory ( thrown2 ) ) ; final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; fail ( "" + result ) ; } catch ( Error caught ) { assertSame ( "" , thrown2 , caught ) ; } final Throwable thrown3 = new Exception ( "" ) ; try { final Parser parser = new StandardParser ( new ThrowingParserImplFactory ( thrown3 ) ) ; final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; fail ( "" + result ) ; } catch ( RuntimeException caught ) { assertSame ( "" , thrown3 , caught . getCause ( ) ) ; } } private final static class ThrowingParserImplFactory implements ParserImplFactory { final Throwable exception ; public ThrowingParserImplFactory ( Throwable exception ) { super ( ) ; this . exception = exception ; } @ Override public ParserImpl create ( String srcInfo , Reader reader ) { return new BaseTestParserImpl ( ) { @ Override public Doc doc ( ) throws Exception { try { throw exception ; } catch ( RuntimeException e ) { throw e ; } catch ( Error e ) { throw e ; } catch ( Exception e ) { throw e ; } catch ( Throwable e ) { throw new RuntimeException ( e ) ; } } } ; } } } package com . pogofish . jadt . parser ; import java . util . List ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Expression ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . ast . Literal ; import com . pogofish . jadt . ast . Pkg ; import com . pogofish . jadt . ast . PrimitiveType ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . ast . Tuple ; import com . pogofish . jadt . ast . Type ; import com . pogofish . jadt . errors . SyntaxError ; public abstract class BaseTestParserImpl implements ParserImpl { public BaseTestParserImpl ( ) { super ( ) ; } @ Override public List < String > typeArguments ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public String typeArgument ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Type type ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Imprt singleImport ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType shortType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void rparen ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public RefType refType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void rbracket ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void rangle ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType primitiveType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Pkg pkg ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public String packageName ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public String packageSpec ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < JavaComment > packageKeyword ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void lparen ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType longType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void lbracket ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void langle ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType intType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < Imprt > imports ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < JavaComment > importKeyword ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public String identifier ( String expected ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public String getSrcInfo ( ) { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType floatType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public ArgModifier finalKeyword ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public ArgModifier transientKeyword ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public ArgModifier volatileKeyword ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < SyntaxError > errors ( ) { throw new RuntimeException ( "" ) ; } @ Override public List < JavaComment > equals ( boolean allowComments ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void eof ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType doubleType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public String dottedIdentifier ( String expected ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void dot ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < DataType > dataTypes ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Tuple < List < JavaComment > , String > dataTypeName ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public DataType dataType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < Constructor > constructors ( List < JavaComment > comments ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Tuple < List < JavaComment > , String > constructorName ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Constructor constructor ( List < JavaComment > comments ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Tuple < List < JavaComment > , String > commentedIdentifier ( String expected ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void comma ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public RefType classType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public String className ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType charType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType byteType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public PrimitiveType booleanType ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < JavaComment > bar ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void arrayTypeBrackets ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < Arg > args ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public String argName ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < ArgModifier > argModifiers ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public ArgModifier argModifier ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Arg arg ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < RefType > actualTypeArguments ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void extendsKeyword ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void implementsKeyword ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Literal literal ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Expression expression ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public List < JavaComment > at ( boolean allowComments ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public Tuple < List < JavaComment > , Annotation > annotation ( boolean allowComments ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void lcurly ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void rcurly ( ) throws Exception { throw new RuntimeException ( "" ) ; } @ Override public void question ( ) { throw new RuntimeException ( "" ) ; } @ Override public void colon ( ) { throw new RuntimeException ( "" ) ; } } package com . pogofish . jadt . parser . javacc ; import static com . pogofish . jadt . parser . javacc . generated . BaseJavaCCParserImplConstants . * ; import static org . junit . Assert . assertEquals ; import org . junit . Test ; import com . pogofish . jadt . parser . javacc . generated . BaseJavaCCParserImplTokenManager ; import com . pogofish . jadt . parser . javacc . generated . JavaCharStream ; import com . pogofish . jadt . parser . javacc . generated . Token ; import com . pogofish . jadt . source . Source ; import com . pogofish . jadt . source . StringSource ; public class JavaCCTokenizerTest { private BaseJavaCCParserImplTokenManager tokenizer ( String testString ) { final Source source = new StringSource ( "" , testString ) ; return new BaseJavaCCParserImplTokenManager ( new JavaCharStream ( source . createReader ( ) ) ) ; } @ Test public void testComments ( ) { final BaseJavaCCParserImplTokenManager tokenizer1 = tokenizer ( "" ) ; check ( tokenizer1 , "" , IDENTIFIER , ) ; check ( tokenizer1 , "" , IDENTIFIER , ) ; check ( tokenizer1 , "" , IDENTIFIER , ) ; check ( tokenizer1 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer3 = tokenizer ( "" ) ; check ( tokenizer3 , "" , IDENTIFIER , ) ; check ( tokenizer3 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer4 = tokenizer ( "" ) ; check ( tokenizer4 , "" , IDENTIFIER , ) ; check ( tokenizer4 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer5 = tokenizer ( "" ) ; check ( tokenizer5 , "" , IDENTIFIER , ) ; check ( tokenizer5 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer6 = tokenizer ( "" ) ; check ( tokenizer6 , "" , IDENTIFIER , ) ; check ( tokenizer6 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer7 = tokenizer ( "" ) ; check ( tokenizer7 , "" , IDENTIFIER , ) ; check ( tokenizer7 , "" , EOF , ) ; } @ Test public void testUnterminatedComments ( ) { final BaseJavaCCParserImplTokenManager tokenizer1 = tokenizer ( "" ) ; check ( tokenizer1 , "" , UNTERMINATED_COMMENT , ) ; check ( tokenizer1 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer2 = tokenizer ( "" ) ; check ( tokenizer2 , "" , UNTERMINATED_COMMENT , ) ; check ( tokenizer2 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer3 = tokenizer ( "" ) ; check ( tokenizer3 , "" , EOF , ) ; } @ Test public void testWhitespace ( ) { final BaseJavaCCParserImplTokenManager tokenizer = tokenizer ( "" ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , EOF , ) ; } @ Test public void testEol ( ) { final BaseJavaCCParserImplTokenManager tokenizer = tokenizer ( "" ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , EOF , ) ; } @ Test public void testIdentifiers ( ) { final BaseJavaCCParserImplTokenManager tokenizer = tokenizer ( "" ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , IDENTIFIER , ) ; check ( tokenizer , "" , EOF , ) ; } @ Test public void testBadIdentifiers ( ) { final BaseJavaCCParserImplTokenManager tokenizer = tokenizer ( "" ) ; check ( tokenizer , "" , UNKNOWN , ) ; check ( tokenizer , "" , UNKNOWN , ) ; } @ Test public void testPunctuation ( ) { final BaseJavaCCParserImplTokenManager tokenizer = tokenizer ( "" ) ; check ( tokenizer , "" , LANGLE , ) ; check ( tokenizer , ">" , RANGLE , ) ; check ( tokenizer , "" , EQUALS , ) ; check ( tokenizer , "" , LPAREN , ) ; check ( tokenizer , "" , RPAREN , ) ; check ( tokenizer , "" , COMMA , ) ; check ( tokenizer , "" , LBRACKET , ) ; check ( tokenizer , "" , RBRACKET , ) ; check ( tokenizer , "" , BAR , ) ; check ( tokenizer , "" , DOT , ) ; check ( tokenizer , "" , AT , ) ; check ( tokenizer , "" , SPLAT , ) ; check ( tokenizer , "" , QUESTION , ) ; check ( tokenizer , "" , COLON , ) ; check ( tokenizer , "" , EOF , ) ; } @ Test public void testUnknown ( ) { final BaseJavaCCParserImplTokenManager tokenizer1 = tokenizer ( "" ) ; check ( tokenizer1 , "" , UNKNOWN , ) ; check ( tokenizer1 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer2 = tokenizer ( "" ) ; check ( tokenizer2 , "" , UNKNOWN , ) ; check ( tokenizer2 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer3 = tokenizer ( "" ) ; check ( tokenizer3 , "" , UNKNOWN , ) ; check ( tokenizer3 , "" , EOF , ) ; final BaseJavaCCParserImplTokenManager tokenizer4 = tokenizer ( "" ) ; check ( tokenizer4 , "" , UNKNOWN , ) ; check ( tokenizer4 , "" , UNKNOWN , ) ; check ( tokenizer4 , "" , EOF , ) ; } @ Test public void testEOF ( ) { final BaseJavaCCParserImplTokenManager tokenizer = tokenizer ( "" ) ; check ( tokenizer , "" , EOF , ) ; } @ Test public void testKeywords ( ) { final BaseJavaCCParserImplTokenManager tokenizer = tokenizer ( "" + "" + "" ) ; check ( tokenizer , "" , IMPORT , ) ; check ( tokenizer , "" , PACKAGE , ) ; check ( tokenizer , "" , FINAL , ) ; check ( tokenizer , "" , EXTENDS , ) ; check ( tokenizer , "" , IMPLEMENTS , ) ; check ( tokenizer , "" , CLASS , ) ; check ( tokenizer , "" , BOOLEAN , ) ; check ( tokenizer , "" , BYTE , ) ; check ( tokenizer , "" , DOUBLE , ) ; check ( tokenizer , "" , CHAR , ) ; check ( tokenizer , "" , FLOAT , ) ; check ( tokenizer , "" , INT , ) ; check ( tokenizer , "" , LONG , ) ; check ( tokenizer , "" , SHORT , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , JAVA_KEYWORD , ) ; check ( tokenizer , "" , EOF , ) ; } private void check ( BaseJavaCCParserImplTokenManager tokenizer , String expectedSymbol , int expectedTokenType , int expectedLineNo ) { final Token token = tokenizer . getNextToken ( ) ; final String actualSymbol = token . kind == EOF ? "" : token . image ; assertEquals ( "" + expectedTokenType + "" + expectedSymbol + "" + token . kind + "" + actualSymbol , expectedTokenType , token . kind ) ; assertEquals ( "" + expectedTokenType + "" , expectedSymbol , actualSymbol ) ; assertEquals ( "" , expectedLineNo , token . beginLine ) ; } } package com . pogofish . jadt . parser . javacc ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertSame ; import static org . junit . Assert . fail ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . Reader ; import java . io . StringReader ; import org . junit . Test ; public class JavaCCReaderTest { @ Test public void testRead ( ) throws Exception { final StringReader stringReader = new StringReader ( "" ) ; final JavaCCReader javaccReader = new JavaCCReader ( stringReader ) ; final BufferedReader reader = new BufferedReader ( javaccReader ) ; assertEquals ( "" , reader . readLine ( ) ) ; } @ Test public void testIOExceptionBeforeClose ( ) throws Exception { final IOException thrown = new IOException ( "" ) ; final Reader throwingReader = createThrowingReader ( thrown ) ; final JavaCCReader reader = new JavaCCReader ( throwingReader ) ; try { reader . read ( ) ; fail ( "" ) ; } catch ( RuntimeException caught ) { assertSame ( thrown , caught . getCause ( ) ) ; } } @ Test public void testIOExceptionAfterClose ( ) throws Exception { final IOException thrown = new IOException ( "" ) ; final Reader throwingReader = createThrowingReader ( thrown ) ; final JavaCCReader reader = new JavaCCReader ( throwingReader ) ; reader . close ( ) ; try { reader . read ( ) ; fail ( "" ) ; } catch ( IOException caught ) { assertSame ( thrown , caught ) ; } } private Reader createThrowingReader ( final IOException thrown ) { return new Reader ( ) { @ Override public int read ( char [ ] cbuf , int off , int len ) throws IOException { throw thrown ; } @ Override public void close ( ) throws IOException { } } ; } } package com . pogofish . jadt . parser . javacc ; import static com . pogofish . jadt . ast . ASTConstants . EMPTY_PKG ; import static com . pogofish . jadt . ast . ASTConstants . NO_COMMENTS ; import static com . pogofish . jadt . ast . ASTConstants . NO_IMPORTS ; import static com . pogofish . jadt . ast . Annotation . _Annotation ; import static com . pogofish . jadt . ast . AnnotationElement . _ElementValue ; import static com . pogofish . jadt . ast . AnnotationElement . _ElementValuePairs ; import static com . pogofish . jadt . ast . AnnotationKeyValue . _AnnotationKeyValue ; import static com . pogofish . jadt . ast . AnnotationValue . _AnnotationValueAnnotation ; import static com . pogofish . jadt . ast . AnnotationValue . _AnnotationValueExpression ; import static com . pogofish . jadt . ast . Arg . _Arg ; import static com . pogofish . jadt . ast . ArgModifier . _Final ; import static com . pogofish . jadt . ast . ArgModifier . _Transient ; import static com . pogofish . jadt . ast . ArgModifier . _Volatile ; import static com . pogofish . jadt . ast . BlockToken . _BlockWhiteSpace ; import static com . pogofish . jadt . ast . BlockToken . _BlockWord ; import static com . pogofish . jadt . ast . Tuple . * ; import static com . pogofish . jadt . ast . Constructor . _Constructor ; import static com . pogofish . jadt . ast . DataType . _DataType ; import static com . pogofish . jadt . ast . Expression . * ; import static com . pogofish . jadt . ast . JDToken . _JDWord ; import static com . pogofish . jadt . ast . JavaComment . _JavaBlockComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaEOLComment ; import static com . pogofish . jadt . ast . Literal . _BooleanLiteral ; import static com . pogofish . jadt . ast . Literal . _CharLiteral ; import static com . pogofish . jadt . ast . Literal . _FloatingPointLiteral ; import static com . pogofish . jadt . ast . Literal . _IntegerLiteral ; import static com . pogofish . jadt . ast . Literal . _NullLiteral ; import static com . pogofish . jadt . ast . Literal . _StringLiteral ; import static com . pogofish . jadt . ast . Optional . _Some ; import static com . pogofish . jadt . ast . PrimitiveType . _BooleanType ; import static com . pogofish . jadt . ast . PrimitiveType . _ByteType ; import static com . pogofish . jadt . ast . PrimitiveType . _CharType ; import static com . pogofish . jadt . ast . PrimitiveType . _DoubleType ; import static com . pogofish . jadt . ast . PrimitiveType . _FloatType ; import static com . pogofish . jadt . ast . PrimitiveType . _IntType ; import static com . pogofish . jadt . ast . PrimitiveType . _LongType ; import static com . pogofish . jadt . ast . PrimitiveType . _ShortType ; import static com . pogofish . jadt . ast . RefType . _ArrayType ; import static com . pogofish . jadt . ast . RefType . _ClassType ; import static com . pogofish . jadt . ast . Type . _Primitive ; import static com . pogofish . jadt . ast . Type . _Ref ; import static com . pogofish . jadt . errors . SyntaxError . _UnexpectedToken ; import static com . pogofish . jadt . util . Util . list ; import static org . junit . Assert . assertEquals ; import java . util . List ; import org . junit . Test ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . AnnotationElement ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . BlockToken ; import com . pogofish . jadt . ast . Tuple ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Expression ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . ast . Literal ; import com . pogofish . jadt . ast . Optional ; import com . pogofish . jadt . ast . ParseResult ; import com . pogofish . jadt . ast . Pkg ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . parser . Parser ; import com . pogofish . jadt . parser . ParserImpl ; import com . pogofish . jadt . parser . StandardParser ; import com . pogofish . jadt . parser . javacc . generated . BaseJavaCCParserImplConstants ; import com . pogofish . jadt . parser . javacc . generated . Token ; import com . pogofish . jadt . source . StringSource ; import com . pogofish . jadt . util . Util ; public class JavaCCParserImplTest { private static final List < RefType > NO_ACTUAL_TYPE_ARGUMENTS = Util . < RefType > list ( ) ; private static final List < String > NO_FORMAL_TYPE_ARGUMENTS = Util . < String > list ( ) ; private static final Optional < RefType > NO_EXTENDS = Optional . < RefType > _None ( ) ; private static final List < RefType > NO_IMPLEMENTS = NO_ACTUAL_TYPE_ARGUMENTS ; private static final BlockToken BLOCKSTART = _BlockWord ( "" ) ; private static final BlockToken BLOCKEND = _BlockWord ( "" ) ; private static final BlockToken BLOCKONEWS = _BlockWhiteSpace ( "" ) ; private static final List < Annotation > NO_ANNOTATIONS = Util . < Annotation > list ( ) ; @ SuppressWarnings ( "" ) private static final JavaComment IMPORTS_COMMENT = _JavaBlockComment ( list ( list ( BLOCKSTART , BLOCKONEWS , _BlockWord ( "" ) , BLOCKONEWS , _BlockWord ( "" ) , BLOCKONEWS , _BlockWord ( "" ) , BLOCKONEWS , _BlockWord ( "" ) , BLOCKONEWS , BLOCKEND ) ) ) ; private static final JavaCCParserImplFactory PARSER_IMPL_FACTORY = new JavaCCParserImplFactory ( ) ; private static final String COMMENT_ERROR_MESSAGE = "" ; private JavaCCParserImpl parserImpl ( final String text ) { final StringSource source = new StringSource ( "" , text ) ; return PARSER_IMPL_FACTORY . create ( source . getSrcInfo ( ) , source . createReader ( ) ) ; } @ Test public void testUnterminatedComment ( ) throws Exception { final ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , "" , p1 . identifier ( "" ) , p1 ) ; } @ Test public void testPrimitive ( ) throws Exception { assertEquals ( _BooleanType ( ) , parserImpl ( "" ) . primitiveType ( ) ) ; assertEquals ( _ByteType ( ) , parserImpl ( "" ) . primitiveType ( ) ) ; assertEquals ( _ShortType ( ) , parserImpl ( "" ) . primitiveType ( ) ) ; assertEquals ( _CharType ( ) , parserImpl ( "" ) . primitiveType ( ) ) ; assertEquals ( _IntType ( ) , parserImpl ( "" ) . primitiveType ( ) ) ; assertEquals ( _LongType ( ) , parserImpl ( "" ) . primitiveType ( ) ) ; assertEquals ( _DoubleType ( ) , parserImpl ( "" ) . primitiveType ( ) ) ; assertEquals ( _FloatType ( ) , parserImpl ( "" ) . primitiveType ( ) ) ; } @ Test public void testClassType ( ) throws Exception { assertEquals ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) , parserImpl ( "" ) . classType ( ) ) ; assertEquals ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) , parserImpl ( "" ) . classType ( ) ) ; assertEquals ( _ClassType ( "" , list ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) , parserImpl ( "" ) . classType ( ) ) ; assertEquals ( _ClassType ( "" , list ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) ) , parserImpl ( "" ) . classType ( ) ) ; assertEquals ( _ClassType ( "" , list ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) , _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) , parserImpl ( "" ) . classType ( ) ) ; } @ Test public void testArray ( ) throws Exception { assertEquals ( _ArrayType ( _Primitive ( _IntType ( ) ) ) , parserImpl ( "" ) . refType ( ) ) ; assertEquals ( _ArrayType ( _Ref ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) ) , parserImpl ( "" ) . refType ( ) ) ; assertEquals ( _Ref ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) , parserImpl ( "" ) . type ( ) ) ; assertEquals ( _Ref ( _ArrayType ( _Ref ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) ) ) , parserImpl ( "" ) . type ( ) ) ; } @ Test public void testType ( ) throws Exception { assertEquals ( _Primitive ( _IntType ( ) ) , parserImpl ( "" ) . type ( ) ) ; assertEquals ( _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) , parserImpl ( "" ) . type ( ) ) ; assertEquals ( _Ref ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) , parserImpl ( "" ) . type ( ) ) ; assertEquals ( _Ref ( _ArrayType ( _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) ) , parserImpl ( "" ) . type ( ) ) ; } @ Test public void testRefType ( ) throws Exception { assertEquals ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) , parserImpl ( "" ) . refType ( ) ) ; assertEquals ( _ArrayType ( _Primitive ( _IntType ( ) ) ) , parserImpl ( "" ) . refType ( ) ) ; assertEquals ( _ArrayType ( _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) , parserImpl ( "" ) . refType ( ) ) ; } @ Test public void testRefTypeErrors ( ) throws Exception { final ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _ArrayType ( _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) , p1 . refType ( ) , p1 ) ; final ParserImpl p2 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _Ref ( _ClassType ( "" , list ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) ) ) , p2 . type ( ) , p2 ) ; final ParserImpl p3 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _Ref ( _ClassType ( "" , list ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) ) , p3 . type ( ) , p3 ) ; final ParserImpl p4 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _Ref ( _ClassType ( "" , list ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) ) , p4 . type ( ) , p4 ) ; final ParserImpl p5 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) , p5 . type ( ) , p5 ) ; final ParserImpl p6 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) , p6 . type ( ) , p6 ) ; } @ Test public void testArgModifier ( ) throws Exception { assertEquals ( _Final ( ) , parserImpl ( "" ) . argModifier ( ) ) ; assertEquals ( _Transient ( ) , parserImpl ( "" ) . argModifier ( ) ) ; assertEquals ( _Volatile ( ) , parserImpl ( "" ) . argModifier ( ) ) ; } @ Test public void testArgModifiers ( ) throws Exception { assertEquals ( list ( _Final ( ) ) , parserImpl ( "" ) . argModifiers ( ) ) ; assertEquals ( list ( _Final ( ) , _Transient ( ) , _Volatile ( ) ) , parserImpl ( "" ) . argModifiers ( ) ) ; assertEquals ( Util . < ArgModifier > list ( ) , parserImpl ( "" ) . argModifiers ( ) ) ; assertEquals ( Util . < ArgModifier > list ( ) , parserImpl ( "" ) . argModifiers ( ) ) ; } @ Test public void testArg ( ) throws Exception { assertEquals ( _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , parserImpl ( "" ) . arg ( ) ) ; assertEquals ( _Arg ( list ( _Final ( ) ) , _Primitive ( _IntType ( ) ) , "" ) , parserImpl ( "" ) . arg ( ) ) ; } @ Test public void testArgErrors ( ) throws Exception { ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , p1 . arg ( ) , p1 ) ; ParserImpl p2 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , p2 . arg ( ) , p2 ) ; } @ Test public void testArgs ( ) throws Exception { assertEquals ( list ( _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) ) , parserImpl ( "" ) . args ( ) ) ; assertEquals ( list ( _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _BooleanType ( ) ) , "" ) ) , parserImpl ( "" ) . args ( ) ) ; } @ Test public void testArgsErrors ( ) throws Exception { ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) ) , p1 . args ( ) , p1 ) ; ParserImpl p2 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( _Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) , "" ) ) , p2 . args ( ) , p2 ) ; ParserImpl p3 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , _Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) , "" ) ) , p3 . args ( ) , p3 ) ; ParserImpl p4 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) ) , p4 . args ( ) , p4 ) ; } @ Test public void testConstructor ( ) throws Exception { assertEquals ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , parserImpl ( "" ) . constructor ( NO_COMMENTS ) ) ; assertEquals ( _Constructor ( NO_COMMENTS , "" , list ( _Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) ) ) , parserImpl ( "" ) . constructor ( NO_COMMENTS ) ) ; } @ Test public void testConstructorErrors ( ) throws Exception { ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , p1 . constructor ( NO_COMMENTS ) , p1 ) ; } @ Test public void testConstructors ( ) throws Exception { assertEquals ( list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) , parserImpl ( "" ) . constructors ( NO_COMMENTS ) ) ; assertEquals ( list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) , parserImpl ( "" ) . constructors ( NO_COMMENTS ) ) ; } @ Test public void testConstructorsErrors ( ) throws Exception { final ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) , p1 . constructors ( NO_COMMENTS ) , p1 ) ; final ParserImpl p2 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) , p2 . constructors ( NO_COMMENTS ) , p2 ) ; } @ Test public void testDataType ( ) throws Exception { assertEquals ( _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , parserImpl ( "" ) . dataType ( ) ) ; assertEquals ( _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , list ( "" ) , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , parserImpl ( "" ) . dataType ( ) ) ; assertEquals ( _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , list ( "" , "" ) , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , parserImpl ( "" ) . dataType ( ) ) ; testAnnotation ( _Tuple ( NO_COMMENTS , _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) , "" ) ; assertEquals ( _DataType ( NO_COMMENTS , list ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) , _Annotation ( "" , _Some ( _ElementValue ( _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , parserImpl ( "" ) . dataType ( ) ) ; } @ Test public void testDataTypeErrors ( ) throws Exception { final ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , p1 . dataType ( ) , p1 ) ; final ParserImpl p2 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , p2 . dataType ( ) , p2 ) ; final ParserImpl p3 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , p3 . dataType ( ) , p3 ) ; final ParserImpl p4 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , p4 . dataType ( ) , p4 ) ; final ParserImpl p5 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , list ( "" , "" ) , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , p5 . dataType ( ) , p5 ) ; } @ Test public void testDataTypes ( ) throws Exception { assertEquals ( list ( _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) , parserImpl ( "" ) . dataTypes ( ) ) ; assertEquals ( list ( _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , _Some ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) , list ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) , _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) . toString ( ) , parserImpl ( "" ) . dataTypes ( ) . toString ( ) ) ; } @ Test public void testTypeArguments ( ) throws Exception { assertEquals ( "" , list ( "" ) , parserImpl ( "" ) . typeArguments ( ) ) ; assertEquals ( "" , list ( "" , "" , "" ) , parserImpl ( "" ) . typeArguments ( ) ) ; } @ Test public void testTypeArgumentsErrors ( ) throws Exception { ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( "" ) , p1 . typeArguments ( ) , p1 ) ; ParserImpl p2 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( "" ) , p2 . typeArguments ( ) , p2 ) ; ParserImpl p3 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( "" ) , p3 . typeArguments ( ) , p3 ) ; ParserImpl p4 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( "" , "" ) , p4 . typeArguments ( ) , p4 ) ; ParserImpl p5 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( "" , "" , "" ) , p5 . typeArguments ( ) , p5 ) ; ParserImpl p6 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( "" ) , p6 . typeArguments ( ) , p6 ) ; } @ Test public void testPackage ( ) throws Exception { assertEquals ( Pkg . _Pkg ( NO_COMMENTS , "" ) , parserImpl ( "" ) . pkg ( ) ) ; assertEquals ( Pkg . _Pkg ( NO_COMMENTS , "" ) , parserImpl ( "" ) . pkg ( ) ) ; } @ Test public void testPackageErrors ( ) throws Exception { final ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , Pkg . _Pkg ( NO_COMMENTS , "" ) , p1 . pkg ( ) , p1 ) ; final ParserImpl p3 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , Pkg . _Pkg ( NO_COMMENTS , "" ) , p3 . pkg ( ) , p3 ) ; final ParserImpl p4 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , Pkg . _Pkg ( NO_COMMENTS , "" ) , p4 . pkg ( ) , p4 ) ; } @ Test public void testImports ( ) throws Exception { assertEquals ( NO_IMPORTS , parserImpl ( "" ) . imports ( ) ) ; assertEquals ( list ( Imprt . _Imprt ( NO_COMMENTS , "" ) ) , parserImpl ( "" ) . imports ( ) ) ; assertEquals ( list ( Imprt . _Imprt ( NO_COMMENTS , "" ) ) , parserImpl ( "" ) . imports ( ) ) ; assertEquals ( list ( Imprt . _Imprt ( NO_COMMENTS , "" ) ) , parserImpl ( "" ) . imports ( ) ) ; assertEquals ( list ( Imprt . _Imprt ( NO_COMMENTS , "" ) , Imprt . _Imprt ( NO_COMMENTS , "" ) ) , parserImpl ( "" ) . imports ( ) ) ; } @ Test public void testImportsErrors ( ) throws Exception { final ParserImpl p1 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) ) , p1 . imports ( ) , p1 ) ; final ParserImpl p2 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) ) , p2 . imports ( ) , p2 ) ; final ParserImpl p3 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) ) , p3 . imports ( ) , p3 ) ; final ParserImpl p4 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) ) , p4 . imports ( ) , p4 ) ; final ParserImpl p5 = parserImpl ( "" ) ; checkError ( list ( _UnexpectedToken ( "" , "" , ) ) , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) ) , p5 . imports ( ) , p5 ) ; } private static < A > void checkError ( List < SyntaxError > expectedErrors , A expectedResult , A actualResult , ParserImpl p ) { assertEquals ( expectedErrors , p . errors ( ) ) ; assertEquals ( expectedResult , actualResult ) ; } @ Test public void testMinimal ( ) { final Parser parser = new StandardParser ( PARSER_IMPL_FACTORY ) ; final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; assertEquals ( new ParseResult ( new Doc ( "" , EMPTY_PKG , NO_IMPORTS , list ( _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) , Util . < SyntaxError > list ( ) ) , result ) ; } @ Test public void testFull ( ) { final Parser parser = new StandardParser ( PARSER_IMPL_FACTORY ) ; final String source = "" + "" ; final ParseResult result = parser . parse ( new StringSource ( "" , source ) ) ; assertEquals ( new ParseResult ( new Doc ( "" , Pkg . _Pkg ( list ( _JavaEOLComment ( "" ) , _JavaEOLComment ( "" ) ) , "" ) , list ( Imprt . _Imprt ( list ( IMPORTS_COMMENT ) , "" ) , Imprt . _Imprt ( NO_COMMENTS , "" ) ) , list ( new DataType ( list ( _JavaEOLComment ( "" ) , _JavaEOLComment ( "" ) ) , list ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) , _Annotation ( "" , _Some ( _ElementValue ( _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( list ( _JavaEOLComment ( "" ) , _JavaEOLComment ( "" ) ) , "" , Util . < Arg > list ( ) ) , new Constructor ( list ( _JavaEOLComment ( "" ) , _JavaEOLComment ( "" ) ) , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , new Arg ( list ( _Final ( ) ) , _Ref ( _ArrayType ( _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) ) , "" ) ) ) ) ) , new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) , Util . < SyntaxError > list ( ) ) . toString ( ) , result . toString ( ) ) ; } @ Test public void testError ( ) { final Parser parser = new StandardParser ( PARSER_IMPL_FACTORY ) ; final String source = "" + "" ; final ParseResult result = parser . parse ( new StringSource ( "" , source ) ) ; assertEquals ( new ParseResult ( new Doc ( "" , Pkg . _Pkg ( list ( _JavaEOLComment ( "" ) ) , "" ) , list ( Imprt . _Imprt ( list ( IMPORTS_COMMENT ) , "" ) , Imprt . _Imprt ( NO_COMMENTS , "" ) ) , list ( new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) , new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , new Arg ( list ( _Final ( ) ) , _Ref ( _ArrayType ( _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) ) , "" ) ) ) ) ) , new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) , list ( SyntaxError . _UnexpectedToken ( "" , "" , ) ) ) . toString ( ) , result . toString ( ) ) ; } @ Test public void testInvalidCommentLocations ( ) throws Exception { final ParserImpl p1 = parserImpl ( "" ) ; p1 . eof ( ) ; checkVoidCommentError ( "" , p1 ) ; final ParserImpl p2 = parserImpl ( "" ) ; p2 . rangle ( ) ; checkVoidCommentError ( "" , p2 ) ; final ParserImpl p3 = parserImpl ( "" ) ; p3 . langle ( ) ; checkVoidCommentError ( "" , p3 ) ; final ParserImpl p4 = parserImpl ( "" ) ; p4 . lbracket ( ) ; checkVoidCommentError ( "" , p4 ) ; final ParserImpl p5 = parserImpl ( "" ) ; p5 . rbracket ( ) ; checkVoidCommentError ( "" , p5 ) ; final ParserImpl p6 = parserImpl ( "" ) ; p6 . lparen ( ) ; checkVoidCommentError ( "" , p6 ) ; final ParserImpl p7 = parserImpl ( "" ) ; p7 . rparen ( ) ; checkVoidCommentError ( "" , p7 ) ; final ParserImpl p8 = parserImpl ( "" ) ; p8 . comma ( ) ; checkVoidCommentError ( "" , p8 ) ; final ParserImpl p9 = parserImpl ( "" ) ; p9 . dot ( ) ; checkVoidCommentError ( "" , p9 ) ; final ParserImpl p10 = parserImpl ( "" ) ; checkCommentError ( _DoubleType ( ) , p10 . doubleType ( ) , "" , p10 ) ; final ParserImpl p11 = parserImpl ( "" ) ; checkCommentError ( _FloatType ( ) , p11 . floatType ( ) , "" , p11 ) ; final ParserImpl p12 = parserImpl ( "" ) ; checkCommentError ( _LongType ( ) , p12 . longType ( ) , "" , p12 ) ; final ParserImpl p13 = parserImpl ( "" ) ; checkCommentError ( _IntType ( ) , p13 . intType ( ) , "" , p13 ) ; final ParserImpl p14 = parserImpl ( "" ) ; checkCommentError ( _ShortType ( ) , p14 . shortType ( ) , "" , p14 ) ; final ParserImpl p15 = parserImpl ( "" ) ; checkCommentError ( _CharType ( ) , p15 . charType ( ) , "" , p15 ) ; final ParserImpl p16 = parserImpl ( "" ) ; checkCommentError ( _ByteType ( ) , p16 . byteType ( ) , "" , p16 ) ; final ParserImpl p17 = parserImpl ( "" ) ; checkCommentError ( _BooleanType ( ) , p17 . booleanType ( ) , "" , p17 ) ; final ParserImpl p18 = parserImpl ( "" ) ; checkCommentError ( _Final ( ) , p18 . finalKeyword ( ) , "" , p18 ) ; final ParserImpl p20 = parserImpl ( "" ) ; checkCommentError ( "" , p20 . identifier ( "" ) , "" , p20 ) ; final ParserImpl p21 = parserImpl ( "" ) ; p21 . extendsKeyword ( ) ; checkVoidCommentError ( "" , p21 ) ; final ParserImpl p22 = parserImpl ( "" ) ; p22 . implementsKeyword ( ) ; checkVoidCommentError ( "" , p22 ) ; final ParserImpl p23 = parserImpl ( "" ) ; checkCommentError ( _Transient ( ) , p23 . transientKeyword ( ) , "" , p23 ) ; final ParserImpl p24 = parserImpl ( "" ) ; checkCommentError ( _Volatile ( ) , p24 . volatileKeyword ( ) , "" , p24 ) ; final ParserImpl p25 = parserImpl ( "" ) ; p25 . at ( false ) ; checkVoidCommentError ( "" , p25 ) ; final ParserImpl p26 = parserImpl ( "" ) ; p26 . lcurly ( ) ; checkVoidCommentError ( "" , p26 ) ; final ParserImpl p27 = parserImpl ( "" ) ; p27 . rcurly ( ) ; checkVoidCommentError ( "" , p27 ) ; final ParserImpl p28 = parserImpl ( "" ) ; p28 . equals ( false ) ; checkVoidCommentError ( "" , p28 ) ; final ParserImpl p29 = parserImpl ( "" ) ; p29 . question ( ) ; checkVoidCommentError ( "" , p29 ) ; final ParserImpl p30 = parserImpl ( "" ) ; p30 . colon ( ) ; checkVoidCommentError ( "" , p30 ) ; } private static void checkVoidCommentError ( String expected , ParserImpl p ) { assertEquals ( list ( _UnexpectedToken ( expected , COMMENT_ERROR_MESSAGE , ) ) , p . errors ( ) ) ; } private static < A > void checkCommentError ( A expected , A actual , String message , ParserImpl p ) { checkError ( list ( _UnexpectedToken ( message , COMMENT_ERROR_MESSAGE , ) ) , expected , actual , p ) ; } @ Test public void testCommentAllowedTokens ( ) throws Exception { final String commentString = "" ; @ SuppressWarnings ( "" ) final List < JavaComment > comments = list ( _JavaBlockComment ( list ( list ( _BlockWord ( "" ) ) ) ) , _JavaDocComment ( "" , list ( _JDWord ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) , _JavaEOLComment ( "" ) ) ; final ParserImpl p1 = parserImpl ( commentString + "" ) ; checkParseResult ( comments , p1 . bar ( ) , p1 ) ; final ParserImpl p2 = parserImpl ( commentString + "" ) ; checkParseResult ( comments , p2 . equals ( true ) , p2 ) ; final ParserImpl p3 = parserImpl ( commentString + "" ) ; checkParseResult ( comments , p3 . packageKeyword ( ) , p3 ) ; final ParserImpl p4 = parserImpl ( commentString + "" ) ; checkParseResult ( comments , p4 . importKeyword ( ) , p4 ) ; final ParserImpl p5 = parserImpl ( commentString + "" ) ; checkParseResult ( _Tuple ( comments , "" ) , p5 . commentedIdentifier ( "" ) , p5 ) ; final ParserImpl p6 = parserImpl ( commentString + "" ) ; checkParseResult ( comments , p6 . at ( true ) , p6 ) ; } private < A > void checkParseResult ( A expected , A actual , ParserImpl p ) { assertEquals ( expected , actual ) ; assertEquals ( Util . < SyntaxError > list ( ) , p . errors ( ) ) ; } @ Test public void testNonJavaCommentSpecialToken ( ) { final JavaCCParserImpl p1 = parserImpl ( "" ) ; final Token token = new Token ( BaseJavaCCParserImplConstants . IDENTIFIER , "" ) ; final Token specialtoken1 = new Token ( BaseJavaCCParserImplConstants . WS , "" ) ; token . specialToken = specialtoken1 ; final Token specialtoken2 = new Token ( BaseJavaCCParserImplConstants . JAVA_EOL_COMMENT , "" ) ; token . specialToken . specialToken = specialtoken2 ; final List < JavaComment > comments = p1 . tokenComments ( token ) ; assertEquals ( list ( _JavaEOLComment ( "" ) ) , comments ) ; } @ Test public void testNonsense ( ) throws Exception { final Parser parser = new StandardParser ( PARSER_IMPL_FACTORY ) ; final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; assertEquals ( ParseResult . _ParseResult ( Doc . _Doc ( "" , EMPTY_PKG , NO_IMPORTS , list ( _DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , NO_FORMAL_TYPE_ARGUMENTS , NO_EXTENDS , NO_IMPLEMENTS , list ( _Constructor ( NO_COMMENTS , "" , list ( _Arg ( list ( _Final ( ) ) , _Ref ( _ClassType ( "" , list ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) ) , "" ) ) ) ) ) ) ) , list ( SyntaxError . _UnexpectedToken ( "" , "" , ) ) ) . toString ( ) , result . toString ( ) ) ; } @ Test public void testLiteral ( ) throws Exception { testLiteral ( _NullLiteral ( ) , "" ) ; testLiteral ( _BooleanLiteral ( "" ) , "" ) ; testLiteral ( _BooleanLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _IntegerLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _FloatingPointLiteral ( "" ) , "" ) ; testLiteral ( _StringLiteral ( "" ) , "" ) ; testLiteral ( _StringLiteral ( "" ) , "" ) ; testLiteral ( _CharLiteral ( "" ) , "" ) ; } private void testLiteral ( Literal expected , String input ) throws Exception { final ParserImpl p = parserImpl ( input ) ; final Literal lit = p . literal ( ) ; assertEquals ( Util . < SyntaxError > list ( ) . toString ( ) , p . errors ( ) . toString ( ) ) ; assertEquals ( expected , lit ) ; } @ Test public void testExpression ( ) throws Exception { testExpression ( _TernaryExpression ( _VariableExpression ( Optional . < Expression > _None ( ) , "" ) , _VariableExpression ( Optional . < Expression > _None ( ) , "" ) , _VariableExpression ( Optional . < Expression > _None ( ) , "" ) ) , "" ) ; testExpression ( _LiteralExpression ( _NullLiteral ( ) ) , "" ) ; testExpression ( _NestedExpression ( _LiteralExpression ( _NullLiteral ( ) ) ) , "" ) ; testExpression ( _VariableExpression ( Optional . < Expression > _None ( ) , "" ) , "" ) ; testExpression ( _VariableExpression ( _Some ( _VariableExpression ( Optional . < Expression > _None ( ) , "" ) ) , "" ) , "" ) ; testExpression ( _ClassReference ( _Ref ( _ClassType ( "" , NO_ACTUAL_TYPE_ARGUMENTS ) ) ) , "" ) ; } private void testExpression ( Expression expected , String input ) throws Exception { final ParserImpl p = parserImpl ( input ) ; final Expression expression = p . expression ( ) ; assertEquals ( "" , p . errors ( ) . toString ( ) ) ; assertEquals ( expected . toString ( ) , expression . toString ( ) ) ; } @ Test public void testAnnotaion ( ) throws Exception { testAnnotation ( _Tuple ( NO_COMMENTS , _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) , "" ) ; testAnnotation ( _Tuple ( NO_COMMENTS , _Annotation ( "" , _Some ( _ElementValue ( _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) , "" ) ; testAnnotation ( _Tuple ( NO_COMMENTS , _Annotation ( "" , _Some ( _ElementValue ( _AnnotationValueExpression ( _LiteralExpression ( _NullLiteral ( ) ) ) ) ) ) ) , "" ) ; testAnnotation ( _Tuple ( NO_COMMENTS , _Annotation ( "" , _Some ( _ElementValuePairs ( list ( _AnnotationKeyValue ( "" , _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) ) ) , "" ) ; testAnnotation ( _Tuple ( NO_COMMENTS , _Annotation ( "" , _Some ( _ElementValuePairs ( list ( _AnnotationKeyValue ( "" , _AnnotationValueExpression ( _LiteralExpression ( _NullLiteral ( ) ) ) ) ) ) ) ) ) , "" ) ; testAnnotation ( _Tuple ( NO_COMMENTS , _Annotation ( "" , _Some ( _ElementValuePairs ( list ( _AnnotationKeyValue ( "" , _AnnotationValueExpression ( _LiteralExpression ( _NullLiteral ( ) ) ) ) , _AnnotationKeyValue ( "" , _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) ) ) , "" ) ; } private void testAnnotation ( Tuple < List < JavaComment > , Annotation > expected , String input ) throws Exception { final ParserImpl p = parserImpl ( input ) ; final Tuple < List < JavaComment > , Annotation > ca = p . annotation ( true ) ; assertEquals ( "" , p . errors ( ) . toString ( ) ) ; assertEquals ( expected . toString ( ) , ca . toString ( ) ) ; } } package com . pogofish . jadt . parser ; import static com . pogofish . jadt . ast . ASTConstants . EMPTY_PKG ; import static com . pogofish . jadt . ast . ASTConstants . NO_IMPORTS ; import static org . junit . Assert . assertSame ; import static org . junit . Assert . fail ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . Reader ; import java . util . Collections ; import org . junit . Test ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . ParseResult ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . source . Source ; import com . pogofish . jadt . source . StringSource ; import com . pogofish . jadt . util . Util ; public class DummyParserTest { @ Test public void testHappy ( ) { final ParseResult testResult = new ParseResult ( new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Collections . < DataType > emptyList ( ) ) , Util . < SyntaxError > list ( ) ) ; final Parser parser = new DummyParser ( testResult , "" , "" ) ; final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; assertSame ( testResult , result ) ; } @ Test public void testWrongSourceString ( ) { final ParseResult testResult = new ParseResult ( new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Collections . < DataType > emptyList ( ) ) , Util . < SyntaxError > list ( ) ) ; final Parser parser = new DummyParser ( testResult , "" , "" ) ; try { final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; fail ( "" + result ) ; } catch ( RuntimeException e ) { } } @ Test public void testWrongSourceInfo ( ) { final ParseResult testResult = new ParseResult ( new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Collections . < DataType > emptyList ( ) ) , Util . < SyntaxError > list ( ) ) ; final Parser parser = new DummyParser ( testResult , "" , "" ) ; try { final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; fail ( "" + result ) ; } catch ( RuntimeException e ) { } } @ Test public void testWrongExtraSource ( ) { final ParseResult testResult = new ParseResult ( new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Collections . < DataType > emptyList ( ) ) , Util . < SyntaxError > list ( ) ) ; final Parser parser = new DummyParser ( testResult , "" , "" ) ; try { final ParseResult result = parser . parse ( new StringSource ( "" , "" ) ) ; fail ( "" + result ) ; } catch ( RuntimeException e ) { } } @ Test public void testIOException ( ) { final ParseResult testResult = new ParseResult ( new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Collections . < DataType > emptyList ( ) ) , Util . < SyntaxError > list ( ) ) ; final Parser parser = new DummyParser ( testResult , "" , "" ) ; try { final ParseResult resultDoc = parser . parse ( new Source ( ) { @ Override public BufferedReader createReader ( ) { return new BufferedReader ( new Reader ( ) { @ Override public int read ( char [ ] cbuf , int off , int len ) throws IOException { throw new IOException ( "" ) ; } @ Override public void close ( ) throws IOException { } } ) ; } @ Override public String getSrcInfo ( ) { return "" ; } } ) ; fail ( "" + resultDoc ) ; } catch ( RuntimeException e ) { } } } package com . pogofish . jadt . checker ; import static com . pogofish . jadt . ast . ASTConstants . NO_COMMENTS ; import static com . pogofish . jadt . ast . ASTConstants . NO_IMPORTS ; import static com . pogofish . jadt . errors . SemanticError . _ConstructorDataTypeConflict ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateArgName ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateConstructor ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateDataType ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateModifier ; import static com . pogofish . jadt . util . Util . list ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; import java . util . List ; import org . junit . Test ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Optional ; import com . pogofish . jadt . ast . Pkg ; import com . pogofish . jadt . ast . PrimitiveType ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . ast . Type ; import com . pogofish . jadt . errors . SemanticError ; import com . pogofish . jadt . util . Util ; public class CheckerTest { private static final Optional < RefType > NO_EXTENDS = Optional . < RefType > _None ( ) ; private static final List < RefType > NO_IMPLEMENTS = Util . < RefType > list ( ) ; private static final List < Annotation > NO_ANNOTATIONS = Util . < Annotation > list ( ) ; @ Test public void testDuplicateDataType ( ) { final Checker checker = new StandardChecker ( ) ; final DataType dataType = new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ; final Doc doc = new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , NO_IMPORTS , list ( dataType , dataType ) ) ; final List < SemanticError > errors = checker . check ( doc ) ; assertEquals ( , errors . size ( ) ) ; assertTrue ( errors . contains ( _DuplicateDataType ( dataType . name ) ) ) ; } @ Test public void testDuplicateConstructor ( ) { final Checker checker = new StandardChecker ( ) ; final Constructor constructor = new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ; final DataType dataType = new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( constructor , constructor ) ) ; final Doc doc = new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , NO_IMPORTS , list ( dataType ) ) ; final List < SemanticError > errors = checker . check ( doc ) ; assertEquals ( , errors . size ( ) ) ; assertTrue ( errors . contains ( _DuplicateConstructor ( dataType . name , constructor . name ) ) ) ; } @ Test public void testConstructorDataTypeConflict ( ) { final Checker checker = new StandardChecker ( ) ; final Constructor constructor1 = new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ; final Constructor constructor2 = new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ; final DataType dataType = new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( constructor1 , constructor2 ) ) ; final Doc doc = new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , NO_IMPORTS , list ( dataType ) ) ; final List < SemanticError > errors = checker . check ( doc ) ; assertEquals ( , errors . size ( ) ) ; assertTrue ( errors . contains ( _ConstructorDataTypeConflict ( dataType . name ) ) ) ; } @ Test public void testDuplicateArgName ( ) { final Checker checker = new StandardChecker ( ) ; final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( Arg . _Arg ( Util . < ArgModifier > list ( ) , Type . _Primitive ( PrimitiveType . _IntType ( ) ) , "" ) , Arg . _Arg ( Util . < ArgModifier > list ( ) , Type . _Primitive ( PrimitiveType . _BooleanType ( ) ) , "" ) ) ) ; final DataType dataType = new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( constructor ) ) ; final Doc doc = new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , NO_IMPORTS , list ( dataType ) ) ; final List < SemanticError > errors = checker . check ( doc ) ; assertEquals ( , errors . size ( ) ) ; assertTrue ( errors . contains ( _DuplicateArgName ( dataType . name , constructor . name , "" ) ) ) ; } @ Test public void testDuplicateArgModifier ( ) { final Checker checker = new StandardChecker ( ) ; final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( Arg . _Arg ( list ( ArgModifier . _Final ( ) , ArgModifier . _Final ( ) ) , Type . _Primitive ( PrimitiveType . _IntType ( ) ) , "" ) ) ) ; final DataType dataType = new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( constructor ) ) ; final Doc doc = new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , NO_IMPORTS , list ( dataType ) ) ; final List < SemanticError > errors = checker . check ( doc ) ; assertEquals ( , errors . size ( ) ) ; assertTrue ( errors . contains ( _DuplicateModifier ( dataType . name , constructor . name , "" , "" ) ) ) ; } } package com . pogofish . jadt . source ; import static com . pogofish . jadt . util . TestUtil . assertEqualsBarringFileSeparators ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . fail ; import java . io . BufferedReader ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStreamWriter ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import org . junit . Test ; import com . pogofish . jadt . util . TestUtil ; public class FileSourceFactoryTest { private static final class SourceComparator implements Comparator < Source > { @ Override public int compare ( Source source1 , Source source2 ) { return source1 . getSrcInfo ( ) . compareTo ( source2 . getSrcInfo ( ) ) ; } } @ Test public void testValidFile ( ) throws IOException { final File temp = File . createTempFile ( "" , "" ) ; try { final BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( temp ) , "" ) ) ; try { writer . write ( "" ) ; } finally { writer . close ( ) ; } final SourceFactory factory = new FileSourceFactory ( ) ; final List < ? extends Source > sources = factory . createSources ( temp . getAbsolutePath ( ) ) ; assertEquals ( , sources . size ( ) ) ; final Source source = sources . get ( ) ; final BufferedReader reader = source . createReader ( ) ; try { assertEquals ( "" , reader . readLine ( ) ) ; assertEquals ( temp . getAbsolutePath ( ) , source . getSrcInfo ( ) ) ; } finally { reader . close ( ) ; } } finally { temp . delete ( ) ; } } @ Test public void testInValidFile ( ) throws IOException { final File temp = File . createTempFile ( "" , "" ) ; temp . delete ( ) ; final SourceFactory factory = new FileSourceFactory ( ) ; final List < ? extends Source > sources = factory . createSources ( temp . getAbsolutePath ( ) ) ; final Source source = sources . get ( ) ; try { final BufferedReader reader = source . createReader ( ) ; try { assertEquals ( "" , reader . readLine ( ) ) ; assertEquals ( temp . getAbsolutePath ( ) , source . getSrcInfo ( ) ) ; } finally { reader . close ( ) ; } fail ( "" ) ; } catch ( RuntimeException e ) { } } @ Test public void testDir ( ) throws IOException { final File tempDir = TestUtil . createTmpDir ( ) ; try { final List < File > tempFiles = new ArrayList < File > ( ) ; try { for ( int i = ; i < ; i ++ ) { tempFiles . add ( createTempFile ( tempDir , i ) ) ; } final SourceFactory factory = new FileSourceFactory ( ) ; final List < ? extends Source > sources = factory . createSources ( tempDir . getAbsolutePath ( ) ) ; assertEquals ( , sources . size ( ) ) ; Collections . sort ( sources , new SourceComparator ( ) ) ; for ( int i = ; i < ; i ++ ) { checkSource ( i , tempDir , sources . get ( i ) ) ; } } finally { for ( File tempFile : tempFiles ) { tempFile . delete ( ) ; } } } finally { tempDir . delete ( ) ; } } private void checkSource ( int i , File parent , Source source ) throws IOException { final BufferedReader reader = source . createReader ( ) ; try { assertEqualsBarringFileSeparators ( parent . getAbsolutePath ( ) + "" + i + "" , source . getSrcInfo ( ) ) ; final String line = reader . readLine ( ) ; assertEquals ( "" + i , line ) ; } finally { reader . close ( ) ; } } private File createTempFile ( File parentDir , int i ) { final File tempFile = new File ( parentDir , i + "" ) ; try { final BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( tempFile ) , "" ) ) ; try { writer . write ( "" + i ) ; } finally { writer . close ( ) ; } return tempFile ; } catch ( Throwable t ) { tempFile . delete ( ) ; throw new RuntimeException ( t ) ; } } } package com . pogofish . jadt . emitter ; import static com . pogofish . jadt . ast . ASTConstants . NO_COMMENTS ; import static com . pogofish . jadt . ast . Annotation . _Annotation ; import static com . pogofish . jadt . ast . AnnotationElement . _ElementValue ; import static com . pogofish . jadt . ast . AnnotationValue . _AnnotationValueAnnotation ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import static com . pogofish . jadt . ast . JDToken . _JDWord ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import static com . pogofish . jadt . ast . Optional . _Some ; import static com . pogofish . jadt . ast . RefType . _ClassType ; import static com . pogofish . jadt . ast . Type . _Ref ; import static com . pogofish . jadt . util . Util . list ; import static org . junit . Assert . assertEquals ; import java . util . List ; import org . junit . Test ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . AnnotationElement ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . Optional ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . sink . StringSink ; import com . pogofish . jadt . util . Util ; public class DataTypeEmitterTest { private static final Optional < RefType > NO_EXTENDS = Optional . < RefType > _None ( ) ; private static final List < RefType > NO_IMPLEMENTS = Util . < RefType > list ( ) ; private static final List < RefType > NO_TYPE_ARGS = Util . < RefType > list ( ) ; private static final List < Annotation > ANNOTATIONS = list ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) , _Annotation ( "" , _Some ( _ElementValue ( _AnnotationValueAnnotation ( _Annotation ( "" , Optional . < AnnotationElement > _None ( ) ) ) ) ) ) ) ; private static final String HEADER = "" ; private static final String MULTI_HEADER_NO_BASE = "" + "" + "" + "" + "" + "" ; private static final String MULTI_HEADER_WITH_BASE = "" + "" + "" + "" + "" + "" ; private static final String MULTI_CONSTRUCTOR_NO_BASE = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String MULTI_CONSTRUCTOR_WITH_BASE = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String SINGLE_CONSTRUCTOR_NO_BASE = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String SINGLE_CONSTRUCTOR_WITH_BASE = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String SINGLE_HEADER_NO_BASE = "" + "" + "" + "" + "" ; private static final String SINGLE_HEADER_WITH_BASE = "" + "" + "" + "" + "" ; @ Test public void testMultipleConstructorsNoBase ( ) { final DataType fooBar = new DataType ( Util . list ( _JavaDocComment ( "" , list ( _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) ) , ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) , new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { final DataTypeEmitter emitter = new StandardDataTypeEmitter ( new DummyClassBodyEmitter ( ) , new DummyConstructorEmitter ( ) ) ; emitter . emit ( sink , fooBar , HEADER ) ; } finally { sink . close ( ) ; } assertEquals ( HEADER + MULTI_HEADER_NO_BASE + MULTI_CONSTRUCTOR_NO_BASE , sink . result ( ) ) ; } @ Test public void testMultipleConstructorsWithBase ( ) { final DataType fooBar = new DataType ( Util . list ( _JavaDocComment ( "" , list ( _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) ) , ANNOTATIONS , "" , Util . < String > list ( ) , _Some ( _ClassType ( "" , NO_TYPE_ARGS ) ) , list ( _ClassType ( "" , NO_TYPE_ARGS ) , _ClassType ( "" , NO_TYPE_ARGS ) ) , list ( new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) , new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { final DataTypeEmitter emitter = new StandardDataTypeEmitter ( new DummyClassBodyEmitter ( ) , new DummyConstructorEmitter ( ) ) ; emitter . emit ( sink , fooBar , HEADER ) ; } finally { sink . close ( ) ; } assertEquals ( HEADER + MULTI_HEADER_WITH_BASE + MULTI_CONSTRUCTOR_WITH_BASE , sink . result ( ) ) ; } @ Test public void testSingleConstructorNoBase ( ) { final DataType fooBar = new DataType ( Util . list ( _JavaDocComment ( "" , list ( _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) ) , ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { final DataTypeEmitter emitter = new StandardDataTypeEmitter ( new DummyClassBodyEmitter ( ) , new DummyConstructorEmitter ( ) ) ; emitter . emit ( sink , fooBar , HEADER ) ; } finally { sink . close ( ) ; } assertEquals ( HEADER + SINGLE_HEADER_NO_BASE + SINGLE_CONSTRUCTOR_NO_BASE , sink . result ( ) ) ; } @ Test public void testSingleConstructorWithBase ( ) { final DataType fooBar = new DataType ( Util . list ( _JavaDocComment ( "" , list ( _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) ) , ANNOTATIONS , "" , Util . < String > list ( ) , _Some ( _ClassType ( "" , NO_TYPE_ARGS ) ) , list ( _ClassType ( "" , NO_TYPE_ARGS ) , _ClassType ( "" , NO_TYPE_ARGS ) ) , list ( new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { final DataTypeEmitter emitter = new StandardDataTypeEmitter ( new DummyClassBodyEmitter ( ) , new DummyConstructorEmitter ( ) ) ; emitter . emit ( sink , fooBar , HEADER ) ; } finally { sink . close ( ) ; } assertEquals ( HEADER + SINGLE_HEADER_WITH_BASE + SINGLE_CONSTRUCTOR_WITH_BASE , sink . result ( ) ) ; } } package com . pogofish . jadt . emitter ; import static com . pogofish . jadt . ast . ASTConstants . NO_COMMENTS ; import static com . pogofish . jadt . ast . ArgModifier . _Final ; import static com . pogofish . jadt . ast . ArgModifier . _Transient ; import static com . pogofish . jadt . ast . ArgModifier . _Volatile ; import static com . pogofish . jadt . ast . JDTagSection . _JDTagSection ; import static com . pogofish . jadt . ast . JDToken . _JDAsterisk ; import static com . pogofish . jadt . ast . JDToken . _JDEOL ; import static com . pogofish . jadt . ast . JDToken . _JDTag ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import static com . pogofish . jadt . ast . JDToken . _JDWord ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import static com . pogofish . jadt . ast . PrimitiveType . _BooleanType ; import static com . pogofish . jadt . ast . PrimitiveType . _ByteType ; import static com . pogofish . jadt . ast . PrimitiveType . _CharType ; import static com . pogofish . jadt . ast . PrimitiveType . _DoubleType ; import static com . pogofish . jadt . ast . PrimitiveType . _FloatType ; import static com . pogofish . jadt . ast . PrimitiveType . _IntType ; import static com . pogofish . jadt . ast . PrimitiveType . _LongType ; import static com . pogofish . jadt . ast . PrimitiveType . _ShortType ; import static com . pogofish . jadt . ast . RefType . _ArrayType ; import static com . pogofish . jadt . ast . RefType . _ClassType ; import static com . pogofish . jadt . ast . Type . _Primitive ; import static com . pogofish . jadt . ast . Type . _Ref ; import static com . pogofish . jadt . util . Util . list ; import static org . junit . Assert . assertEquals ; import org . junit . Test ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . sink . StringSink ; import com . pogofish . jadt . util . Util ; public class ClassBodyEmitterTest { private static final String NO_ARG_NO_TYPES_FACTORY = "" + "" ; private static final String NO_ARG_TYPES_FACTORY = "" + "" + "" + "" ; private static final String ARGS_NO_TYPES_FACTORY = "" ; private static final String ARGS_TYPES_FACTORY = "" ; private static final String CONSTRUCTOR_METHOD = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String NO_ARG_TO_STRING = "" + "" + "" + "" ; private static final String ONE_ARG_TO_STRING = "" + "" + "" + "" ; private static final String ARGS_TO_STRING = "" + "" + "" + "" ; private static final String NO_ARG_EQUALS = "" + "" + "" + "" + "" + "" + "" ; private static final String ARGS_NO_TYPES_EQUALS = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String ARGS_TYPES_EQUALS = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String NO_ARG_HASHCODE = "" + "" + "" + "" ; private static final String ARGS_HASHCODE = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private final ClassBodyEmitter emitter = new StandardClassBodyEmitter ( ) ; public void testNonParameterizedTypeName ( ) { final StringSink sink = new StringSink ( "" ) ; try { emitter . emitParameterizedTypeName ( sink , Util . < String > list ( ) ) ; } finally { sink . close ( ) ; } assertEquals ( "" , sink . result ( ) ) ; } public void testOneParameterizedTypeName ( ) { final StringSink sink = new StringSink ( "" ) ; try { emitter . emitParameterizedTypeName ( sink , list ( "" ) ) ; } finally { sink . close ( ) ; } assertEquals ( "" , sink . result ( ) ) ; } public void testMultiParameterizedTypeName ( ) { final StringSink sink = new StringSink ( "" ) ; try { emitter . emitParameterizedTypeName ( sink , list ( "" , "" , "" ) ) ; } finally { sink . close ( ) ; } assertEquals ( "" , sink . result ( ) ) ; } @ Test public void testNoArgNoTypesFactory ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . constructorFactory ( sink , "" , "" , Util . < String > list ( ) , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( NO_ARG_NO_TYPES_FACTORY , sink . result ( ) ) ; } @ Test public void testNoArgTypesFactory ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . constructorFactory ( sink , "" , "" , list ( "" , "" ) , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( NO_ARG_TYPES_FACTORY , sink . result ( ) ) ; } @ Test public void testArgsNoTypesFactory ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . constructorFactory ( sink , "" , "" , Util . < String > list ( ) , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( ARGS_NO_TYPES_FACTORY , sink . result ( ) ) ; } @ Test public void testArgsTypesFactory ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . constructorFactory ( sink , "" , "" , list ( "" , "" ) , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( ARGS_TYPES_FACTORY , sink . result ( ) ) ; } @ Test public void testConstructorMethod ( ) { final Constructor constructor = new Constructor ( list ( _JavaDocComment ( "" , list ( _JDEOL ( "" ) ) , list ( _JDTagSection ( "" , list ( _JDWhiteSpace ( "" ) , _JDAsterisk ( ) , _JDWhiteSpace ( "" ) , _JDTag ( "" ) , _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDEOL ( "" ) , _JDWhiteSpace ( "" ) ) ) ) , "" ) ) , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . list ( _Final ( ) , _Transient ( ) , _Volatile ( ) ) , _Primitive ( _IntType ( ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitConstructorMethod ( sink , "" , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( CONSTRUCTOR_METHOD , sink . result ( ) ) ; } @ Test public void testNoArgToString ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitToString ( sink , "" , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( NO_ARG_TO_STRING , sink . result ( ) ) ; } @ Test public void testOneArgToString ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitToString ( sink , "" , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( ONE_ARG_TO_STRING , sink . result ( ) ) ; } @ Test public void testArgsToString ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitToString ( sink , "" , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( ARGS_TO_STRING , sink . result ( ) ) ; } @ Test public void testNoArgsNoTypesEquals ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitEquals ( sink , "" , constructor , Util . < String > list ( ) ) ; } finally { sink . close ( ) ; } assertEquals ( NO_ARG_EQUALS , sink . result ( ) ) ; } @ Test public void testArgsNoTypesEquals ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitEquals ( sink , "" , constructor , Util . < String > list ( ) ) ; } finally { sink . close ( ) ; } assertEquals ( ARGS_NO_TYPES_EQUALS , sink . result ( ) ) ; } @ Test public void testArgsTypesEquals ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitEquals ( sink , "" , constructor , list ( "" , "" ) ) ; } finally { sink . close ( ) ; } assertEquals ( ARGS_TYPES_EQUALS , sink . result ( ) ) ; } @ Test public void testNoArgHashCode ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitHashCode ( sink , "" , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( NO_ARG_HASHCODE , sink . result ( ) ) ; } @ Test public void testArgHashCode ( ) { final Constructor constructor = new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _BooleanType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _ByteType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _CharType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _ShortType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _LongType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _FloatType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _DoubleType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ArrayType ( _Primitive ( _IntType ( ) ) ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { emitter . emitHashCode ( sink , "" , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( ARGS_HASHCODE , sink . result ( ) ) ; } } package com . pogofish . jadt . emitter ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import static com . pogofish . jadt . ast . JDToken . _JDWord ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import static com . pogofish . jadt . ast . PrimitiveType . _IntType ; import static com . pogofish . jadt . ast . RefType . _ClassType ; import static com . pogofish . jadt . ast . Type . _Primitive ; import static com . pogofish . jadt . ast . Type . _Ref ; import static com . pogofish . jadt . util . Util . list ; import static org . junit . Assert . assertEquals ; import org . junit . Test ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . sink . StringSink ; import com . pogofish . jadt . util . Util ; public class ConstructorEmitterTest { private static final String CONSTRUCTOR_CLASS = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String FACTORY = "" ; @ Test public void testFactory ( ) { final Constructor constructor = new Constructor ( Util . list ( _JavaDocComment ( "" , list ( _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) ) , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { final ConstructorEmitter emitter = new StandardConstructorEmitter ( new DummyClassBodyEmitter ( ) ) ; emitter . constructorFactory ( sink , "" , Util . < String > list ( ) , constructor ) ; } finally { sink . close ( ) ; } assertEquals ( FACTORY , sink . result ( ) ) ; } @ Test public void testConstrucorDeclaration ( ) { final Constructor constructor = new Constructor ( Util . list ( _JavaDocComment ( "" , list ( _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) ) , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) ) ) ; final StringSink sink = new StringSink ( "" ) ; try { final ConstructorEmitter emitter = new StandardConstructorEmitter ( new DummyClassBodyEmitter ( ) ) ; emitter . constructorDeclaration ( sink , constructor , "" , Util . < String > list ( ) ) ; } finally { sink . close ( ) ; } assertEquals ( CONSTRUCTOR_CLASS , sink . result ( ) ) ; } } package com . pogofish . jadt . emitter ; import static com . pogofish . jadt . ast . ASTConstants . EMPTY_PKG ; import static com . pogofish . jadt . ast . ASTConstants . NO_COMMENTS ; import static com . pogofish . jadt . ast . ASTConstants . NO_IMPORTS ; import static com . pogofish . jadt . ast . BlockToken . _BlockWord ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import static com . pogofish . jadt . ast . JDToken . _JDWord ; import static com . pogofish . jadt . ast . JavaComment . _JavaBlockComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaEOLComment ; import static com . pogofish . jadt . ast . PrimitiveType . _IntType ; import static com . pogofish . jadt . ast . RefType . _ClassType ; import static com . pogofish . jadt . ast . Type . _Primitive ; import static com . pogofish . jadt . ast . Type . _Ref ; import static com . pogofish . jadt . util . Util . list ; import static org . junit . Assert . assertEquals ; import java . util . List ; import java . util . Map ; import org . junit . Test ; import com . pogofish . jadt . Version ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . Optional ; import com . pogofish . jadt . ast . Pkg ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . sink . StringSinkFactory ; import com . pogofish . jadt . util . Util ; public class DocEmitterTest { private static final Optional < RefType > NO_EXTENDS = Optional . < RefType > _None ( ) ; private static final List < RefType > NO_IMPLEMENTS = Util . < RefType > list ( ) ; private static final List < Annotation > NO_ANNOTATIONS = Util . < Annotation > list ( ) ; private static final String VERSION = new Version ( ) . getVersion ( ) ; private static final String BOILERPLATE = "" + VERSION + "" + "" + "" + "" ; private static final String FULL_HEADER = "" + "" + "" + "" + "" + "" + "" + "" + "" + BOILERPLATE ; private static final String NO_PACKAGE_HEADER = "" + "" + "" + "" + BOILERPLATE ; private static final String NO_IMPORTS_HEADER = "" + "" + "" + BOILERPLATE ; private static final String FOOBAR = "" ; private static final String WHATEVER = "" ; @ Test public void testFull ( ) { @ SuppressWarnings ( "" ) final Doc doc = new Doc ( "" , Pkg . _Pkg ( Util . list ( _JavaDocComment ( "" , list ( _JDWhiteSpace ( "" ) , _JDWord ( "" ) , _JDWhiteSpace ( "" ) ) , Util . < JDTagSection > list ( ) , "" ) ) , "" ) , list ( Imprt . _Imprt ( Util . list ( _JavaBlockComment ( list ( list ( _BlockWord ( "" ) ) ) ) ) , "" ) , Imprt . _Imprt ( Util . list ( _JavaEOLComment ( "" ) ) , "" ) ) , list ( new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) , new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) ; final StringSinkFactory factory = new StringSinkFactory ( "" ) ; final DocEmitter emitter = new StandardDocEmitter ( new DummyDataTypeEmitter ( ) ) ; emitter . emit ( factory , doc ) ; final Map < String , String > results = factory . getResults ( ) ; assertEquals ( "" , , results . size ( ) ) ; final String foobar = results . get ( "" ) ; assertEquals ( FULL_HEADER + FOOBAR , foobar ) ; assertEquals ( FULL_HEADER + WHATEVER , results . get ( "" ) ) ; } @ Test public void testNoImports ( ) { final Doc doc = new Doc ( "" , Pkg . _Pkg ( NO_COMMENTS , "" ) , NO_IMPORTS , list ( new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) , new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) ; final StringSinkFactory factory = new StringSinkFactory ( "" ) ; final DocEmitter emitter = new StandardDocEmitter ( new DummyDataTypeEmitter ( ) ) ; emitter . emit ( factory , doc ) ; final Map < String , String > results = factory . getResults ( ) ; assertEquals ( "" , , results . size ( ) ) ; final String foobar = results . get ( "" ) ; assertEquals ( NO_IMPORTS_HEADER + FOOBAR , foobar ) ; assertEquals ( NO_IMPORTS_HEADER + WHATEVER , results . get ( "" ) ) ; } @ Test public void testNoPackage ( ) { final Doc doc = new Doc ( "" , EMPTY_PKG , list ( Imprt . _Imprt ( NO_COMMENTS , "" ) , Imprt . _Imprt ( NO_COMMENTS , "" ) ) , list ( new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , list ( new Arg ( Util . < ArgModifier > list ( ) , _Primitive ( _IntType ( ) ) , "" ) , new Arg ( Util . < ArgModifier > list ( ) , _Ref ( _ClassType ( "" , Util . < RefType > list ( ) ) ) , "" ) ) ) , new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) , new DataType ( NO_COMMENTS , NO_ANNOTATIONS , "" , Util . < String > list ( ) , NO_EXTENDS , NO_IMPLEMENTS , list ( new Constructor ( NO_COMMENTS , "" , Util . < Arg > list ( ) ) ) ) ) ) ; final StringSinkFactory factory = new StringSinkFactory ( "" ) ; final DocEmitter emitter = new StandardDocEmitter ( new DummyDataTypeEmitter ( ) ) ; emitter . emit ( factory , doc ) ; final Map < String , String > results = factory . getResults ( ) ; assertEquals ( "" , , results . size ( ) ) ; final String foobar = results . get ( "" ) ; assertEquals ( NO_PACKAGE_HEADER + FOOBAR , foobar ) ; assertEquals ( NO_PACKAGE_HEADER + WHATEVER , results . get ( "" ) ) ; } } package com . pogofish . jadt . emitter ; import static com . pogofish . jadt . ast . ASTConstants . EMPTY_PKG ; import static com . pogofish . jadt . ast . ASTConstants . NO_IMPORTS ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . fail ; import java . util . Collections ; import org . junit . Test ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . sink . StringSinkFactory ; public class DummyDocEmitterTest { @ Test public void testHappy ( ) { final Doc testDoc = new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Collections . < DataType > emptyList ( ) ) ; final DocEmitter dummyDocEmitter = new DummyDocEmitter ( testDoc , "" ) ; final StringSinkFactory factory = new StringSinkFactory ( "" ) ; dummyDocEmitter . emit ( factory , testDoc ) ; assertEquals ( "" , factory . getResults ( ) . get ( "" ) ) ; } @ Test public void testWrongDoc ( ) { final Doc testDoc = new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Collections . < DataType > emptyList ( ) ) ; final Doc doc = new Doc ( "" , EMPTY_PKG , NO_IMPORTS , Collections . < DataType > emptyList ( ) ) ; final DocEmitter dummyDocEmitter = new DummyDocEmitter ( testDoc , "" ) ; final StringSinkFactory factory = new StringSinkFactory ( "" ) ; try { dummyDocEmitter . emit ( factory , doc ) ; fail ( "" + factory . getResults ( ) . get ( "" ) ) ; } catch ( RuntimeException e ) { } } } package com . pogofish . jadt . comments ; import static com . pogofish . jadt . ast . BlockToken . _BlockEOL ; import static com . pogofish . jadt . ast . BlockToken . _BlockWhiteSpace ; import static com . pogofish . jadt . ast . BlockToken . _BlockWord ; import static com . pogofish . jadt . ast . JavaComment . _JavaBlockComment ; import static com . pogofish . jadt . util . Util . list ; import static junit . framework . Assert . assertEquals ; import java . io . StringReader ; import org . junit . Test ; import com . pogofish . jadt . ast . BlockToken ; import com . pogofish . jadt . ast . JavaComment ; public class BlockCommentParserTest { private static final BlockToken EOL = _BlockEOL ( "" ) ; private static final BlockToken START = _BlockWord ( "" ) ; private static final BlockToken END = _BlockWord ( "" ) ; private static final BlockToken ONEWS = _BlockWhiteSpace ( "" ) ; @ SuppressWarnings ( "" ) @ Test public void test ( ) { test ( "" , _JavaBlockComment ( list ( list ( START , ONEWS , END ) ) ) ) ; test ( "" , _JavaBlockComment ( list ( list ( START , ONEWS , _BlockWord ( "" ) , ONEWS , END ) ) ) ) ; test ( "" , _JavaBlockComment ( list ( list ( START , ONEWS , _BlockWord ( "" ) , EOL ) , list ( ONEWS , _BlockWord ( "" ) , ONEWS , _BlockWord ( "" ) , ONEWS , END ) ) ) ) ; } private void test ( String string , JavaComment expected ) { final BlockCommentParser parser = new BlockCommentParser ( ) ; assertEquals ( expected . toString ( ) , parser . parse ( new StringReader ( string ) ) . toString ( ) ) ; } } package com . pogofish . jadt . comments ; import static com . pogofish . jadt . ast . BlockToken . _BlockWhiteSpace ; import static com . pogofish . jadt . ast . BlockToken . _BlockWord ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import static com . pogofish . jadt . ast . JavaComment . _JavaBlockComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaEOLComment ; import static com . pogofish . jadt . util . Util . list ; import static com . pogofish . jadt . util . Util . set ; import static org . junit . Assert . assertEquals ; import java . io . StringReader ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . JDToken ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . printer . ASTPrinter ; import com . pogofish . jadt . util . Util ; public class CommentProcessorTest { private static final JDToken ONEWS = _JDWhiteSpace ( "" ) ; private static final List < JDTagSection > NO_TAG_SECTIONS = Util . < JDTagSection > list ( ) ; @ Test public void testStripTags ( ) { testStripTags ( "" , list ( "" ) , set ( "" ) ) ; testStripTags ( "" , list ( "" ) , set ( "" ) ) ; testStripTags ( "" , list ( "" ) , set ( "" ) ) ; testStripTags ( "" , list ( "" ) , set ( "" ) ) ; final CommentProcessor commentProcessor = new CommentProcessor ( ) ; @ SuppressWarnings ( "" ) List < JavaComment > comments = list ( _JavaEOLComment ( "" ) , _JavaBlockComment ( list ( list ( _BlockWord ( "" ) , _BlockWhiteSpace ( "" ) , _BlockWord ( "" ) ) ) ) ) ; assertEquals ( comments , commentProcessor . stripTags ( set ( "" ) , comments ) ) ; } private void testStripTags ( String expected , List < String > inputs , Set < String > tags ) { final JavaDocParser parser = new JavaDocParser ( ) ; final List < JavaComment > outputs = new ArrayList < JavaComment > ( inputs . size ( ) ) ; final CommentProcessor commentProcessor = new CommentProcessor ( ) ; for ( String input : inputs ) { final JavaComment comment = parser . parse ( new StringReader ( input ) ) ; outputs . add ( comment ) ; } final List < JavaComment > stripped = commentProcessor . stripTags ( tags , outputs ) ; final String actual = ASTPrinter . printComments ( "" , stripped ) ; assertEquals ( expected , actual ) ; } @ Test public void testJavaDocOnly ( ) { final CommentProcessor commentProcessor = new CommentProcessor ( ) ; JavaComment javaDocComment = _JavaDocComment ( "" , list ( ONEWS ) , NO_TAG_SECTIONS , "" ) ; @ SuppressWarnings ( "" ) List < JavaComment > comments = list ( javaDocComment , _JavaEOLComment ( "" ) , _JavaBlockComment ( list ( list ( _BlockWord ( "" ) , _BlockWhiteSpace ( "" ) , _BlockWord ( "" ) ) ) ) ) ; assertEquals ( list ( javaDocComment ) , commentProcessor . javaDocOnly ( comments ) ) ; } @ Test public void testLeftAlignBlock ( ) { testBlockAlign ( "" , list ( "" ) ) ; testBlockAlign ( "" , list ( "" ) ) ; testBlockAlign ( "" , list ( "" , "" ) ) ; testBlockAlign ( "" , list ( "" ) ) ; testBlockAlign ( "" , list ( "" ) ) ; testBlockAlign ( "" , list ( "" ) ) ; } private void testBlockAlign ( String expected , List < String > inputs ) { final BlockCommentParser parser = new BlockCommentParser ( ) ; final List < JavaComment > outputs = new ArrayList < JavaComment > ( inputs . size ( ) ) ; final CommentProcessor commentProcessor = new CommentProcessor ( ) ; for ( String input : inputs ) { final JavaComment comment = parser . parse ( new StringReader ( input ) ) ; outputs . add ( comment ) ; } final List < JavaComment > aligned = commentProcessor . leftAlign ( outputs ) ; final String actual = ASTPrinter . printComments ( "" , aligned ) ; assertEquals ( expected , actual ) ; } @ Test public void testLeftAlignJavaDoc ( ) { testJavaDocAlign ( "" , list ( "" ) ) ; testJavaDocAlign ( "" , list ( "" ) ) ; testJavaDocAlign ( "" , list ( "" , "" ) ) ; testJavaDocAlign ( "" , list ( "" ) ) ; testJavaDocAlign ( "" , list ( "" ) ) ; testJavaDocAlign ( "" , list ( "" ) ) ; testJavaDocAlign ( "" , list ( "" ) ) ; testJavaDocAlign ( "" , list ( "" ) ) ; testJavaDocAlign ( "" , list ( "" ) ) ; } private void testJavaDocAlign ( String expected , List < String > inputs ) { final JavaDocParser parser = new JavaDocParser ( ) ; final List < JavaComment > outputs = new ArrayList < JavaComment > ( inputs . size ( ) ) ; final CommentProcessor commentProcessor = new CommentProcessor ( ) ; for ( String input : inputs ) { final JavaComment comment = parser . parse ( new StringReader ( input ) ) ; outputs . add ( comment ) ; } final List < JavaComment > aligned = commentProcessor . leftAlign ( outputs ) ; final String actual = ASTPrinter . printComments ( "" , aligned ) ; assertEquals ( expected , actual ) ; } @ Test public void testParamDoc ( ) { testParamDoc ( "" , "" , list ( "" ) ) ; testParamDoc ( "" , "" , list ( "" ) ) ; testParamDoc ( "" , "" , list ( "" ) ) ; testParamDoc ( "" , "" , list ( "" ) ) ; testParamDoc ( "" , "" , list ( "" ) ) ; testParamDoc ( "" , "" , list ( "" ) ) ; } private void testParamDoc ( String expected , String paramName , List < String > inputs ) { final JavaDocParser parser = new JavaDocParser ( ) ; final List < JavaComment > outputs = new ArrayList < JavaComment > ( inputs . size ( ) ) ; final CommentProcessor commentProcessor = new CommentProcessor ( ) ; for ( String input : inputs ) { final JavaComment comment = parser . parse ( new StringReader ( input ) ) ; outputs . add ( comment ) ; } final List < JavaComment > paramDoc = commentProcessor . paramDoc ( paramName , outputs ) ; final String actual = ASTPrinter . printComments ( "" , paramDoc ) ; assertEquals ( expected , actual ) ; } @ Test public void testParamDocNonJavaDoc ( ) { final CommentProcessor commentProcessor = new CommentProcessor ( ) ; @ SuppressWarnings ( "" ) List < JavaComment > comments = list ( _JavaEOLComment ( "" ) , _JavaBlockComment ( list ( list ( _BlockWord ( "" ) , _BlockWhiteSpace ( "" ) , _BlockWord ( "" ) ) ) ) ) ; assertEquals ( Util . < JavaComment > list ( ) , commentProcessor . paramDoc ( "" , comments ) ) ; } } package com . pogofish . jadt . comments ; import static com . pogofish . jadt . ast . JDTagSection . _JDTagSection ; import static com . pogofish . jadt . ast . JDToken . _JDAsterisk ; import static com . pogofish . jadt . ast . JDToken . _JDEOL ; import static com . pogofish . jadt . ast . JDToken . _JDTag ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import static com . pogofish . jadt . ast . JDToken . _JDWord ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import static com . pogofish . jadt . util . Util . list ; import static junit . framework . Assert . assertEquals ; import java . io . StringReader ; import java . util . List ; import org . junit . Test ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . JDToken ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . comments . javacc . generated . Token ; import com . pogofish . jadt . javadoc . javacc . JavaDocParserImpl ; import com . pogofish . jadt . printer . ASTPrinter ; import com . pogofish . jadt . util . Util ; public class JavaDocParserTest { private static final JDToken ONEEOL = _JDEOL ( "" ) ; private static final JDToken ONEWS = _JDWhiteSpace ( "" ) ; private static final List < JDToken > NO_TOKENS = Util . < JDToken > list ( ) ; private static final List < JDTagSection > NO_TAG_SECTIONS = Util . < JDTagSection > list ( ) ; @ Test public void testLookahead ( ) { final JavaDocParserImpl impl = new JavaDocParserImpl ( new StringReader ( "" ) ) ; impl . token = new Token ( , "" ) ; final Token token1 = impl . lookahead ( ) ; assertEquals ( "" , token1 . image ) ; impl . token = new Token ( , "" ) ; impl . token . next = new Token ( , "" ) ; final Token token2 = impl . lookahead ( ) ; assertEquals ( "" , token2 . image ) ; } @ Test public void testGeneralSection ( ) { test ( "" , _JavaDocComment ( "" , list ( ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; test ( "" , _JavaDocComment ( "" , list ( ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; test ( "" , _JavaDocComment ( "" , list ( ONEWS , _JDAsterisk ( ) , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; test ( "" , _JavaDocComment ( "" , list ( ONEWS , _JDAsterisk ( ) , ONEEOL , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; test ( "" , _JavaDocComment ( "" , list ( ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; test ( "" , _JavaDocComment ( "" , list ( ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEWS , _JDTag ( "" ) , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; test ( "" , _JavaDocComment ( "" , list ( ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDAsterisk ( ) , ONEWS , _JDTag ( "" ) , ONEEOL , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; test ( "" , _JavaDocComment ( "" , list ( ONEWS , _JDWord ( "" ) , ONEWS ) , NO_TAG_SECTIONS , "" ) ) ; } @ Test public void testTagSections ( ) { test ( "" , _JavaDocComment ( "" , NO_TOKENS , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) ) ) ) , "" ) ) ; test ( "" , _JavaDocComment ( "" , NO_TOKENS , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) ) ) ) , "" ) ) ; test ( "" , _JavaDocComment ( "" , NO_TOKENS , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL ) ) , _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) ) ) ) , "" ) ) ; test ( "" , _JavaDocComment ( "" , list ( ONEWS ) , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS ) ) ) , "" ) ) ; } @ Test public void testFull ( ) { test ( "" , _JavaDocComment ( "" , list ( ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDAsterisk ( ) , ONEWS , _JDTag ( "" ) , ONEEOL , ONEWS ) , list ( _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) , ONEEOL , ONEWS , _JDAsterisk ( ) , ONEWS , _JDWord ( "" ) , ONEEOL ) ) , _JDTagSection ( "" , list ( _JDTag ( "" ) , ONEWS , _JDWord ( "" ) ) ) ) , "" ) ) ; } @ Test public void testRoundTrip ( ) { testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; testRoundTrip ( "" ) ; } private void testRoundTrip ( String string ) { final JavaDocParser parser = new JavaDocParser ( ) ; assertEquals ( string , ASTPrinter . print ( "" , parser . parse ( new StringReader ( string ) ) ) ) ; } private void test ( String string , JavaComment expected ) { final JavaDocParser parser = new JavaDocParser ( ) ; assertEquals ( expected . toString ( ) , parser . parse ( new StringReader ( string ) ) . toString ( ) ) ; } } package com . pogofish . jadt ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; import static org . junit . Assert . fail ; import java . io . FileNotFoundException ; import org . junit . Test ; public class VersionTest { @ Test public void testHappy ( ) { final String version = new Version ( ) . getVersion ( ) ; assertTrue ( "" + version + "" , version . equals ( "" ) || version . matches ( "" ) ) ; } @ Test public void testMissingFile ( ) throws Throwable { try { final Version version = new Version ( ) ; version . MODULE_PROPERTIES = "" ; final String result = version . getVersion ( ) ; fail ( "" + result ) ; } catch ( RuntimeException e ) { try { throw ( e . getCause ( ) ) ; } catch ( FileNotFoundException e2 ) { } } } @ Test public void testMissingProperty ( ) throws Throwable { final Version version = new Version ( ) ; version . MODULE_VERSION = "" ; final String result = version . getVersion ( ) ; assertEquals ( "" , result ) ; } } package com . pogofish . jadt . sampleast ; import java . util . List ; public final class Function { public static final Function _Function ( Type returnType , String name , List < Arg > args , List < Statement > statements ) { return new Function ( returnType , name , args , statements ) ; } public final Type returnType ; public final String name ; public final List < Arg > args ; public final List < Statement > statements ; public Function ( Type returnType , String name , List < Arg > args , List < Statement > statements ) { this . returnType = returnType ; this . name = name ; this . args = args ; this . statements = statements ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( returnType == null ) ? : returnType . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; result = prime * result + ( ( args == null ) ? : args . hashCode ( ) ) ; result = prime * result + ( ( statements == null ) ? : statements . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Function other = ( Function ) obj ; if ( returnType == null ) { if ( other . returnType != null ) return false ; } else if ( ! returnType . equals ( other . returnType ) ) return false ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( args == null ) { if ( other . args != null ) return false ; } else if ( ! args . equals ( other . args ) ) return false ; if ( statements == null ) { if ( other . statements != null ) return false ; } else if ( ! statements . equals ( other . statements ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + returnType + "" + name + "" + args + "" + statements + "" ; } } package com . pogofish . jadt . sampleast ; import static com . pogofish . jadt . sampleast . Arg . _Arg ; import static com . pogofish . jadt . sampleast . Expression . _Add ; import static com . pogofish . jadt . sampleast . Expression . _Variable ; import static com . pogofish . jadt . sampleast . Function . _Function ; import static com . pogofish . jadt . sampleast . Statement . _Return ; import static com . pogofish . jadt . sampleast . Type . _Int ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . pogofish . jadt . sampleast . Expression . Add ; import com . pogofish . jadt . sampleast . Expression . Literal ; import com . pogofish . jadt . sampleast . Expression . Variable ; import com . pogofish . jadt . sampleast . Statement . Return ; public class SampleConsumer { public Function sampleFunction ( ) { return _Function ( _Int ( ) , "" , list ( _Arg ( _Int ( ) , "" ) , _Arg ( _Int ( ) , "" ) ) , list ( _Return ( _Add ( _Variable ( "" ) , _Variable ( "" ) ) ) ) ) ; } public Set < Integer > expressionLiterals ( Expression expression ) { return expression . accept ( new Expression . Visitor < Set < Integer > > ( ) { @ Override public Set < Integer > visit ( Add x ) { final Set < Integer > results = expressionLiterals ( x . left ) ; results . addAll ( expressionLiterals ( x . right ) ) ; return results ; } @ Override public Set < Integer > visit ( Variable x ) { return Collections . < Integer > emptySet ( ) ; } @ Override public Set < Integer > visit ( Literal x ) { return Collections . singleton ( x . value ) ; } } ) ; } public boolean hasReturn ( List < Statement > statements ) { boolean hasReturn = false ; for ( Statement statement : statements ) { hasReturn = hasReturn || statement . accept ( new Statement . VisitorWithDefault < Boolean > ( ) { @ Override public Boolean visit ( Return x ) { return true ; } @ Override public Boolean getDefault ( Statement x ) { return false ; } } ) ; } return hasReturn ; } public static < A > List < A > list ( A ... elements ) { final List < A > list = new ArrayList < A > ( elements . length ) ; for ( A element : elements ) { list . add ( element ) ; } return list ; } } package com . pogofish . jadt . sampleast ; import java . util . List ; public abstract class Option < A > { private Option ( ) { } public static final < A > Option < A > _Some ( A value ) { return new Some < A > ( value ) ; } @ SuppressWarnings ( "" ) private static final Option _None = new None ( ) ; @ SuppressWarnings ( "" ) public static final < A > Option < A > _None ( ) { return _None ; } public static interface Visitor < A , ResultType > { ResultType visit ( Some < A > x ) ; ResultType visit ( None < A > x ) ; } public static abstract class VisitorWithDefault < A , ResultType > implements Visitor < A , ResultType > { @ Override public ResultType visit ( Some < A > x ) { return getDefault ( x ) ; } @ Override public ResultType visit ( None < A > x ) { return getDefault ( x ) ; } protected abstract ResultType getDefault ( Option < A > x ) ; } public static interface VoidVisitor < A > { void visit ( Some < A > x ) ; void visit ( None < A > x ) ; } public static abstract class VoidVisitorWithDefault < A > implements VoidVisitor < A > { @ Override public void visit ( Some < A > x ) { doDefault ( x ) ; } @ Override public void visit ( None < A > x ) { doDefault ( x ) ; } protected abstract void doDefault ( Option < A > x ) ; } public static final class Some < A > extends Option < A > { public final A value ; public Some ( A value ) { this . value = value ; } @ Override public < ResultType > ResultType accept ( Visitor < A , ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor < A > visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( value == null ) ? : value . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; @ SuppressWarnings ( "" ) Some other = ( Some ) obj ; if ( value == null ) { if ( other . value != null ) return false ; } else if ( ! value . equals ( other . value ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + value + "" ; } } public static final class None < A > extends Option < A > { public None ( ) { } @ Override public < ResultType > ResultType accept ( Visitor < A , ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor < A > visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public abstract < ResultType > ResultType accept ( Visitor < A , ResultType > visitor ) ; public abstract void accept ( VoidVisitor < A > visitor ) ; } package com . pogofish . jadt . sampleast ; import java . util . List ; public final class Arg { public static final Arg _Arg ( Type type , String name ) { return new Arg ( type , name ) ; } public final Type type ; public final String name ; public Arg ( Type type , String name ) { this . type = type ; this . name = name ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( type == null ) ? : type . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Arg other = ( Arg ) obj ; if ( type == null ) { if ( other . type != null ) return false ; } else if ( ! type . equals ( other . type ) ) return false ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + type + "" + name + "" ; } } package com . pogofish . jadt . sampleast ; import java . util . List ; public abstract class Statement { private Statement ( ) { } public static final Statement _Declaration ( Type type , String name , Expression expression ) { return new Declaration ( type , name , expression ) ; } public static final Statement _Assignment ( String name , Expression expression ) { return new Assignment ( name , expression ) ; } public static final Statement _Return ( Expression expression ) { return new Return ( expression ) ; } public static interface Visitor < ResultType > { ResultType visit ( Declaration x ) ; ResultType visit ( Assignment x ) ; ResultType visit ( Return x ) ; } public static abstract class VisitorWithDefault < ResultType > implements Visitor < ResultType > { @ Override public ResultType visit ( Declaration x ) { return getDefault ( x ) ; } @ Override public ResultType visit ( Assignment x ) { return getDefault ( x ) ; } @ Override public ResultType visit ( Return x ) { return getDefault ( x ) ; } protected abstract ResultType getDefault ( Statement x ) ; } public static interface VoidVisitor { void visit ( Declaration x ) ; void visit ( Assignment x ) ; void visit ( Return x ) ; } public static abstract class VoidVisitorWithDefault implements VoidVisitor { @ Override public void visit ( Declaration x ) { doDefault ( x ) ; } @ Override public void visit ( Assignment x ) { doDefault ( x ) ; } @ Override public void visit ( Return x ) { doDefault ( x ) ; } protected abstract void doDefault ( Statement x ) ; } public static final class Declaration extends Statement { public final Type type ; public final String name ; public final Expression expression ; public Declaration ( Type type , String name , Expression expression ) { this . type = type ; this . name = name ; this . expression = expression ; } @ Override public < ResultType > ResultType accept ( Visitor < ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( type == null ) ? : type . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; result = prime * result + ( ( expression == null ) ? : expression . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Declaration other = ( Declaration ) obj ; if ( type == null ) { if ( other . type != null ) return false ; } else if ( ! type . equals ( other . type ) ) return false ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( expression == null ) { if ( other . expression != null ) return false ; } else if ( ! expression . equals ( other . expression ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + type + "" + name + "" + expression + "" ; } } public static final class Assignment extends Statement { public final String name ; public final Expression expression ; public Assignment ( String name , Expression expression ) { this . name = name ; this . expression = expression ; } @ Override public < ResultType > ResultType accept ( Visitor < ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; result = prime * result + ( ( expression == null ) ? : expression . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Assignment other = ( Assignment ) obj ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( expression == null ) { if ( other . expression != null ) return false ; } else if ( ! expression . equals ( other . expression ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + name + "" + expression + "" ; } } public static final class Return extends Statement { public final Expression expression ; public Return ( Expression expression ) { this . expression = expression ; } @ Override public < ResultType > ResultType accept ( Visitor < ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( expression == null ) ? : expression . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Return other = ( Return ) obj ; if ( expression == null ) { if ( other . expression != null ) return false ; } else if ( ! expression . equals ( other . expression ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + expression + "" ; } } public abstract < ResultType > ResultType accept ( Visitor < ResultType > visitor ) ; public abstract void accept ( VoidVisitor visitor ) ; } package com . pogofish . jadt . sampleast ; import java . util . List ; public abstract class Type { private Type ( ) { } private static final Type _Int = new Int ( ) ; public static final Type _Int ( ) { return _Int ; } private static final Type _Long = new Long ( ) ; public static final Type _Long ( ) { return _Long ; } public static interface Visitor < ResultType > { ResultType visit ( Int x ) ; ResultType visit ( Long x ) ; } public static abstract class VisitorWithDefault < ResultType > implements Visitor < ResultType > { @ Override public ResultType visit ( Int x ) { return getDefault ( x ) ; } @ Override public ResultType visit ( Long x ) { return getDefault ( x ) ; } protected abstract ResultType getDefault ( Type x ) ; } public static interface VoidVisitor { void visit ( Int x ) ; void visit ( Long x ) ; } public static abstract class VoidVisitorWithDefault implements VoidVisitor { @ Override public void visit ( Int x ) { doDefault ( x ) ; } @ Override public void visit ( Long x ) { doDefault ( x ) ; } protected abstract void doDefault ( Type x ) ; } public static final class Int extends Type { public Int ( ) { } @ Override public < ResultType > ResultType accept ( Visitor < ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public static final class Long extends Type { public Long ( ) { } @ Override public < ResultType > ResultType accept ( Visitor < ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public abstract < ResultType > ResultType accept ( Visitor < ResultType > visitor ) ; public abstract void accept ( VoidVisitor visitor ) ; } package com . pogofish . jadt . sampleast ; import java . util . List ; public abstract class Expression { private Expression ( ) { } public static final Expression _Add ( Expression left , Expression right ) { return new Add ( left , right ) ; } public static final Expression _Variable ( String name ) { return new Variable ( name ) ; } public static final Expression _Literal ( int value ) { return new Literal ( value ) ; } public static interface Visitor < ResultType > { ResultType visit ( Add x ) ; ResultType visit ( Variable x ) ; ResultType visit ( Literal x ) ; } public static abstract class VisitorWithDefault < ResultType > implements Visitor < ResultType > { @ Override public ResultType visit ( Add x ) { return getDefault ( x ) ; } @ Override public ResultType visit ( Variable x ) { return getDefault ( x ) ; } @ Override public ResultType visit ( Literal x ) { return getDefault ( x ) ; } protected abstract ResultType getDefault ( Expression x ) ; } public static interface VoidVisitor { void visit ( Add x ) ; void visit ( Variable x ) ; void visit ( Literal x ) ; } public static abstract class VoidVisitorWithDefault implements VoidVisitor { @ Override public void visit ( Add x ) { doDefault ( x ) ; } @ Override public void visit ( Variable x ) { doDefault ( x ) ; } @ Override public void visit ( Literal x ) { doDefault ( x ) ; } protected abstract void doDefault ( Expression x ) ; } public static final class Add extends Expression { public final Expression left ; public final Expression right ; public Add ( Expression left , Expression right ) { this . left = left ; this . right = right ; } @ Override public < ResultType > ResultType accept ( Visitor < ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( left == null ) ? : left . hashCode ( ) ) ; result = prime * result + ( ( right == null ) ? : right . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Add other = ( Add ) obj ; if ( left == null ) { if ( other . left != null ) return false ; } else if ( ! left . equals ( other . left ) ) return false ; if ( right == null ) { if ( other . right != null ) return false ; } else if ( ! right . equals ( other . right ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + left + "" + right + "" ; } } public static final class Variable extends Expression { public final String name ; public Variable ( String name ) { this . name = name ; } @ Override public < ResultType > ResultType accept ( Visitor < ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Variable other = ( Variable ) obj ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + name + "" ; } } public static final class Literal extends Expression { public final int value ; public Literal ( int value ) { this . value = value ; } @ Override public < ResultType > ResultType accept ( Visitor < ResultType > visitor ) { return visitor . visit ( this ) ; } @ Override public void accept ( VoidVisitor visitor ) { visitor . visit ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + value ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Literal other = ( Literal ) obj ; if ( value != other . value ) return false ; return true ; } @ Override public String toString ( ) { return "" + value + "" ; } } public abstract < ResultType > ResultType accept ( Visitor < ResultType > visitor ) ; public abstract void accept ( VoidVisitor visitor ) ; } package com . pogofish . jadt . comments ; import java . io . Reader ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . comments . javacc . generated . BlockCommentParserImpl ; import com . pogofish . jadt . parser . javacc . JavaCCReader ; import com . pogofish . jadt . util . ExceptionAction ; import com . pogofish . jadt . util . Util ; public class BlockCommentParser { public JavaComment parse ( final Reader BlockComment ) { return Util . execute ( new ExceptionAction < JavaComment > ( ) { @ Override public JavaComment doAction ( ) throws Throwable { BlockCommentParserImpl impl = new BlockCommentParserImpl ( new JavaCCReader ( BlockComment ) ) ; return impl . blockComment ( ) ; } } ) ; } } package com . pogofish . jadt . comments ; import java . io . Reader ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . javadoc . javacc . JavaDocParserImpl ; import com . pogofish . jadt . parser . javacc . JavaCCReader ; import com . pogofish . jadt . util . ExceptionAction ; import com . pogofish . jadt . util . Util ; public class JavaDocParser { public JavaComment parse ( final Reader javaDoc ) { return Util . execute ( new ExceptionAction < JavaComment > ( ) { @ Override public JavaComment doAction ( ) throws Throwable { JavaDocParserImpl impl = new JavaDocParserImpl ( new JavaCCReader ( javaDoc ) ) ; return impl . javaDoc ( ) ; } } ) ; } } package com . pogofish . jadt . comments ; import static com . pogofish . jadt . ast . BlockToken . _BlockWhiteSpace ; import static com . pogofish . jadt . ast . JDTagSection . _JDTagSection ; import static com . pogofish . jadt . ast . JDToken . _JDAsterisk ; import static com . pogofish . jadt . ast . JDToken . _JDEOL ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import static com . pogofish . jadt . ast . JavaComment . _JavaBlockComment ; import static com . pogofish . jadt . ast . JavaComment . _JavaDocComment ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import com . pogofish . jadt . ast . BlockToken ; import com . pogofish . jadt . ast . BlockToken . BlockEOL ; import com . pogofish . jadt . ast . BlockToken . BlockWhiteSpace ; import com . pogofish . jadt . ast . BlockToken . BlockWord ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . JDToken ; import com . pogofish . jadt . ast . JDToken . JDAsterisk ; import com . pogofish . jadt . ast . JDToken . JDEOL ; import com . pogofish . jadt . ast . JDToken . JDTag ; import com . pogofish . jadt . ast . JDToken . JDWhiteSpace ; import com . pogofish . jadt . ast . JDToken . JDWord ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . ast . JavaComment . JavaBlockComment ; import com . pogofish . jadt . ast . JavaComment . JavaDocComment ; import com . pogofish . jadt . ast . JavaComment . JavaEOLComment ; import com . pogofish . jadt . util . Util ; public class CommentProcessor { public List < JavaComment > javaDocOnly ( final List < JavaComment > originals ) { final List < JavaComment > results = new ArrayList < JavaComment > ( originals . size ( ) ) ; for ( JavaComment comment : originals ) { comment . _switch ( new JavaComment . SwitchBlockWithDefault ( ) { @ Override public void _case ( JavaDocComment x ) { results . add ( x ) ; } @ Override protected void _default ( JavaComment x ) { } } ) ; } return results ; } public List < JavaComment > stripTags ( final Set < String > tagNames , List < JavaComment > originals ) { final List < JavaComment > results = new ArrayList < JavaComment > ( originals . size ( ) ) ; for ( JavaComment original : originals ) { results . add ( original . match ( new JavaComment . MatchBlock < JavaComment > ( ) { @ Override public JavaComment _case ( JavaDocComment x ) { final List < JDTagSection > newTagSections = new ArrayList < JDTagSection > ( x . tagSections . size ( ) ) ; for ( JDTagSection tagSection : x . tagSections ) { if ( ! tagNames . contains ( tagSection . name ) ) { newTagSections . add ( tagSection ) ; } } return _JavaDocComment ( x . start , x . generalSection , newTagSections , x . end ) ; } @ Override public JavaComment _case ( JavaBlockComment x ) { return x ; } @ Override public JavaComment _case ( JavaEOLComment x ) { return x ; } } ) ) ; } return results ; } public List < JavaComment > paramDoc ( final String paramName , List < JavaComment > originals ) { final List < JavaComment > results = new ArrayList < JavaComment > ( originals . size ( ) ) ; for ( JavaComment original : originals ) { original . _switch ( new JavaComment . SwitchBlock ( ) { @ Override public void _case ( JavaDocComment x ) { paramDocSections ( paramName , x . tagSections , results ) ; } @ Override public void _case ( JavaBlockComment x ) { } @ Override public void _case ( JavaEOLComment x ) { } } ) ; } return results ; } private void paramDocSections ( String paramName , List < JDTagSection > tagSections , List < JavaComment > results ) { for ( JDTagSection section : tagSections ) { if ( section . name . equals ( "" ) ) { paramDocSection ( paramName , section . tokens , results ) ; } } } private static enum ParamState { BEGIN , ASTERISK , TAGGED , ACCUMULATING , DEAD ; } private void paramDocSection ( final String paramName , final List < JDToken > tokens , List < JavaComment > results ) { final ParamState state [ ] = new ParamState [ ] { ParamState . BEGIN } ; @ SuppressWarnings ( "" ) final List < JDToken > [ ] accum = new List [ ] ; for ( JDToken token : tokens ) { token . _switch ( new JDToken . SwitchBlock ( ) { @ Override public void _case ( JDWhiteSpace x ) { if ( state [ ] == ParamState . ACCUMULATING ) { accum [ ] . add ( x ) ; } } @ Override public void _case ( JDWord x ) { switch ( state [ ] ) { case ACCUMULATING : accum [ ] . add ( x ) ; break ; case TAGGED : if ( x . word . equals ( paramName ) ) { state [ ] = ParamState . ACCUMULATING ; accum [ ] = new ArrayList < JDToken > ( tokens . size ( ) - ) ; accum [ ] . add ( _JDEOL ( "" ) ) ; accum [ ] . add ( _JDWhiteSpace ( "" ) ) ; accum [ ] . add ( _JDAsterisk ( ) ) ; } else { state [ ] = ParamState . DEAD ; } break ; default : state [ ] = ParamState . DEAD ; break ; } } @ Override public void _case ( JDTag x ) { switch ( state [ ] ) { case ACCUMULATING : accum [ ] . add ( x ) ; break ; case BEGIN : state [ ] = ParamState . TAGGED ; break ; case ASTERISK : state [ ] = ParamState . TAGGED ; break ; default : state [ ] = ParamState . DEAD ; break ; } } @ Override public void _case ( JDEOL x ) { if ( state [ ] == ParamState . ACCUMULATING ) { accum [ ] . add ( x ) ; } } @ Override public void _case ( JDAsterisk x ) { switch ( state [ ] ) { case ACCUMULATING : accum [ ] . add ( x ) ; break ; case BEGIN : state [ ] = ParamState . ASTERISK ; break ; default : state [ ] = ParamState . DEAD ; break ; } } } ) ; } if ( state [ ] == ParamState . ACCUMULATING ) { results . add ( _JavaDocComment ( "" , accum [ ] , Util . < JDTagSection > list ( ) , "" ) ) ; } } public List < JavaComment > leftAlign ( List < JavaComment > originals ) { final List < JavaComment > results = new ArrayList < JavaComment > ( originals . size ( ) ) ; for ( JavaComment original : originals ) { results . add ( original . match ( new JavaComment . MatchBlock < JavaComment > ( ) { @ Override public JavaComment _case ( JavaDocComment x ) { final List < JDToken > leadingWhiteSpace = new ArrayList < JDToken > ( ) ; final LeftAlignState state [ ] = new LeftAlignState [ ] { LeftAlignState . IN_LINE } ; return _JavaDocComment ( x . start , leftAlignSection ( x . generalSection , x . tagSections . isEmpty ( ) , leadingWhiteSpace , state ) , leftAlignSections ( x . tagSections , leadingWhiteSpace , state ) , x . end ) ; } @ Override public JavaComment _case ( JavaBlockComment x ) { return _JavaBlockComment ( leftAlignBlock ( x . lines ) ) ; } @ Override public JavaComment _case ( JavaEOLComment x ) { return x ; } } ) ) ; } return results ; } private List < JDTagSection > leftAlignSections ( List < JDTagSection > tagSections , List < JDToken > leadingWhiteSpace , LeftAlignState [ ] state ) { final int size = tagSections . size ( ) ; final List < JDTagSection > newSections = new ArrayList < JDTagSection > ( size ) ; int count = ; for ( JDTagSection section : tagSections ) { count ++ ; newSections . add ( _JDTagSection ( section . name , leftAlignSection ( section . tokens , count == size , leadingWhiteSpace , state ) ) ) ; } return newSections ; } private List < JDToken > leftAlignSection ( List < JDToken > originalSection , boolean lastSection , final List < JDToken > leadingWhiteSpace , final LeftAlignState [ ] state ) { final List < JDToken > result = new ArrayList < JDToken > ( originalSection . size ( ) + ) ; for ( JDToken token : originalSection ) { token . _switch ( new JDToken . SwitchBlockWithDefault ( ) { @ Override public void _case ( JDWhiteSpace x ) { switch ( state [ ] ) { case START_LINE : leadingWhiteSpace . add ( x ) ; break ; case IN_LINE : result . add ( x ) ; break ; } } @ Override public void _case ( JDEOL x ) { switch ( state [ ] ) { case START_LINE : result . addAll ( leadingWhiteSpace ) ; leadingWhiteSpace . clear ( ) ; result . add ( x ) ; break ; case IN_LINE : result . add ( x ) ; break ; } state [ ] = LeftAlignState . START_LINE ; } @ Override public void _case ( JDAsterisk x ) { switch ( state [ ] ) { case START_LINE : result . add ( _JDWhiteSpace ( "" ) ) ; leadingWhiteSpace . clear ( ) ; result . add ( x ) ; state [ ] = LeftAlignState . IN_LINE ; break ; case IN_LINE : result . add ( x ) ; break ; } } @ Override protected void _default ( JDToken x ) { switch ( state [ ] ) { case START_LINE : result . addAll ( leadingWhiteSpace ) ; leadingWhiteSpace . clear ( ) ; result . add ( x ) ; state [ ] = LeftAlignState . IN_LINE ; break ; case IN_LINE : result . add ( x ) ; break ; } } } ) ; } if ( lastSection && state [ ] == LeftAlignState . START_LINE ) { result . add ( _JDWhiteSpace ( "" ) ) ; } return result ; } private static enum LeftAlignState { START_LINE , IN_LINE ; } private List < List < BlockToken > > leftAlignBlock ( List < List < BlockToken > > lines ) { final List < List < BlockToken > > results = new ArrayList < List < BlockToken > > ( lines . size ( ) ) ; for ( List < BlockToken > line : lines ) { results . add ( leftAlignLign ( line ) ) ; } return results ; } private List < BlockToken > leftAlignLign ( List < BlockToken > line ) { final List < BlockToken > result = new ArrayList < BlockToken > ( line . size ( ) + ) ; final List < BlockToken > leadingWhiteSpace = new ArrayList < BlockToken > ( ) ; final LeftAlignState state [ ] = new LeftAlignState [ ] { LeftAlignState . START_LINE } ; for ( BlockToken token : line ) { token . _switch ( new BlockToken . SwitchBlock ( ) { @ Override public void _case ( BlockEOL x ) { switch ( state [ ] ) { case START_LINE : result . addAll ( leadingWhiteSpace ) ; leadingWhiteSpace . clear ( ) ; result . add ( x ) ; break ; case IN_LINE : result . add ( x ) ; break ; } state [ ] = LeftAlignState . START_LINE ; } @ Override public void _case ( BlockWhiteSpace x ) { switch ( state [ ] ) { case START_LINE : leadingWhiteSpace . add ( x ) ; break ; case IN_LINE : result . add ( x ) ; break ; } } @ Override public void _case ( BlockWord x ) { if ( x . word . startsWith ( "" ) ) { switch ( state [ ] ) { case START_LINE : result . add ( _BlockWhiteSpace ( "" ) ) ; leadingWhiteSpace . clear ( ) ; result . add ( x ) ; state [ ] = LeftAlignState . IN_LINE ; break ; case IN_LINE : result . add ( x ) ; break ; } } else { switch ( state [ ] ) { case START_LINE : result . addAll ( leadingWhiteSpace ) ; leadingWhiteSpace . clear ( ) ; result . add ( x ) ; state [ ] = LeftAlignState . IN_LINE ; break ; case IN_LINE : result . add ( x ) ; break ; } } } } ) ; } return result ; } } package com . pogofish . jadt . sink ; public interface Sink { public String getInfo ( ) ; public abstract void close ( ) ; public abstract void write ( String data ) ; } package com . pogofish . jadt . sink ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStreamWriter ; import java . io . Writer ; import com . pogofish . jadt . util . ExceptionAction ; import com . pogofish . jadt . util . Util ; public class FileSink implements Sink { private final Writer writer ; final File outputFile ; @ Override public String getInfo ( ) { return outputFile . getAbsolutePath ( ) ; } public FileSink ( final String outputFileName ) { super ( ) ; outputFile = new File ( outputFileName ) ; writer = Util . execute ( new ExceptionAction < Writer > ( ) { @ Override public Writer doAction ( ) throws IOException { final File parentDir = outputFile . getParentFile ( ) ; parentDir . mkdirs ( ) ; outputFile . createNewFile ( ) ; return new OutputStreamWriter ( new FileOutputStream ( outputFile ) , "" ) ; } } ) ; } @ Override public void write ( final String data ) { Util . execute ( new ExceptionAction < Writer > ( ) { @ Override public Writer doAction ( ) throws IOException { writer . write ( data ) ; return null ; } } ) ; } @ Override public void close ( ) { Util . execute ( new ExceptionAction < Writer > ( ) { @ Override public Writer doAction ( ) throws IOException { writer . close ( ) ; return null ; } } ) ; } } package com . pogofish . jadt . sink ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; public class StringSinkFactory implements SinkFactory { final String baseDir ; private final Map < String , StringSink > sinks = new HashMap < String , StringSink > ( ) ; public StringSinkFactory ( String baseDir ) { super ( ) ; this . baseDir = baseDir ; } @ Override public Sink createSink ( String className ) { StringSink sink = new StringSink ( className ) ; sinks . put ( className , sink ) ; return sink ; } public Map < String , String > getResults ( ) { final Map < String , String > results = new HashMap < String , String > ( sinks . size ( ) ) ; for ( Map . Entry < String , StringSink > entry : sinks . entrySet ( ) ) { results . put ( entry . getKey ( ) , entry . getValue ( ) . result ( ) ) ; } return Collections . unmodifiableMap ( results ) ; } } package com . pogofish . jadt . sink ; import java . io . IOException ; import java . io . StringWriter ; import com . pogofish . jadt . util . ExceptionAction ; import com . pogofish . jadt . util . Util ; public class StringSink implements Sink { private final StringWriter writer ; private boolean closed = false ; private final String name ; @ Override public String getInfo ( ) { return name ; } public StringSink ( final String name ) { super ( ) ; this . writer = new StringWriter ( ) ; this . name = name ; } @ Override public void write ( String data ) { writer . write ( data ) ; } @ Override public void close ( ) { Util . execute ( new ExceptionAction < Void > ( ) { @ Override public Void doAction ( ) throws IOException { writer . close ( ) ; return null ; } } ) ; closed = true ; } public String result ( ) { if ( ! closed ) { throw new RuntimeException ( "" ) ; } return writer . toString ( ) ; } } package com . pogofish . jadt . sink ; import java . io . File ; public class FileSinkFactory implements SinkFactory { final String destDirName ; public FileSinkFactory ( String destDirName ) { this . destDirName = destDirName ; } @ Override public Sink createSink ( String className ) { return new FileSink ( convertToPath ( className ) ) ; } public String convertToPath ( String className ) { final String fixedDir = destDirName . endsWith ( File . separator ) ? destDirName : destDirName + File . separator ; final String fixedClassName = className . replace ( '' , '' ) ; return fixedDir + fixedClassName + "" ; } } package com . pogofish . jadt . sink ; public interface SinkFactoryFactory { public SinkFactory createSinkFactory ( String baseDir ) ; } package com . pogofish . jadt . sink ; import static com . pogofish . jadt . util . Util . list ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; public class StringSinkFactoryFactory implements SinkFactoryFactory { private Map < String , List < StringSinkFactory > > results = new HashMap < String , List < StringSinkFactory > > ( ) ; @ Override public StringSinkFactory createSinkFactory ( String baseDir ) { final StringSinkFactory result = new StringSinkFactory ( baseDir ) ; if ( results . containsKey ( baseDir ) ) { results . get ( baseDir ) . add ( result ) ; } else { results . put ( baseDir , list ( result ) ) ; } return result ; } public Map < String , List < StringSinkFactory > > results ( ) { return results ; } } package com . pogofish . jadt . sink ; public class FileSinkFactoryFactory implements SinkFactoryFactory { @ Override public SinkFactory createSinkFactory ( String baseDir ) { return new FileSinkFactory ( baseDir ) ; } } package com . pogofish . jadt . sink ; public interface SinkFactory { public Sink createSink ( String className ) ; } package com . pogofish . jadt . printer ; import java . util . List ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . AnnotationElement ; import com . pogofish . jadt . ast . AnnotationElement . ElementValue ; import com . pogofish . jadt . ast . AnnotationElement . ElementValuePairs ; import com . pogofish . jadt . ast . AnnotationKeyValue ; import com . pogofish . jadt . ast . AnnotationValue ; import com . pogofish . jadt . ast . AnnotationValue . AnnotationValueAnnotation ; import com . pogofish . jadt . ast . AnnotationValue . AnnotationValueArray ; import com . pogofish . jadt . ast . AnnotationValue . AnnotationValueExpression ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . ArgModifier . Final ; import com . pogofish . jadt . ast . ArgModifier . Transient ; import com . pogofish . jadt . ast . ArgModifier . Volatile ; import com . pogofish . jadt . ast . BlockToken ; import com . pogofish . jadt . ast . BlockToken . BlockEOL ; import com . pogofish . jadt . ast . BlockToken . BlockWhiteSpace ; import com . pogofish . jadt . ast . BlockToken . BlockWord ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Expression ; import com . pogofish . jadt . ast . Expression . ClassReference ; import com . pogofish . jadt . ast . Expression . LiteralExpression ; import com . pogofish . jadt . ast . Expression . NestedExpression ; import com . pogofish . jadt . ast . Expression . TernaryExpression ; import com . pogofish . jadt . ast . Expression . VariableExpression ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . ast . JDTagSection ; import com . pogofish . jadt . ast . JDToken ; import com . pogofish . jadt . ast . Literal ; import com . pogofish . jadt . ast . JDToken . JDAsterisk ; import com . pogofish . jadt . ast . JDToken . JDEOL ; import com . pogofish . jadt . ast . JDToken . JDTag ; import com . pogofish . jadt . ast . JDToken . JDWhiteSpace ; import com . pogofish . jadt . ast . JDToken . JDWord ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . ast . JavaComment . JavaBlockComment ; import com . pogofish . jadt . ast . JavaComment . JavaDocComment ; import com . pogofish . jadt . ast . JavaComment . JavaEOLComment ; import com . pogofish . jadt . ast . Literal . BooleanLiteral ; import com . pogofish . jadt . ast . Literal . CharLiteral ; import com . pogofish . jadt . ast . Literal . FloatingPointLiteral ; import com . pogofish . jadt . ast . Literal . IntegerLiteral ; import com . pogofish . jadt . ast . Literal . NullLiteral ; import com . pogofish . jadt . ast . Literal . StringLiteral ; import com . pogofish . jadt . ast . Optional ; import com . pogofish . jadt . ast . Optional . None ; import com . pogofish . jadt . ast . Optional . Some ; import com . pogofish . jadt . ast . PrimitiveType ; import com . pogofish . jadt . ast . PrimitiveType . BooleanType ; import com . pogofish . jadt . ast . PrimitiveType . ByteType ; import com . pogofish . jadt . ast . PrimitiveType . CharType ; import com . pogofish . jadt . ast . PrimitiveType . DoubleType ; import com . pogofish . jadt . ast . PrimitiveType . FloatType ; import com . pogofish . jadt . ast . PrimitiveType . IntType ; import com . pogofish . jadt . ast . PrimitiveType . LongType ; import com . pogofish . jadt . ast . PrimitiveType . ShortType ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . ast . RefType . ArrayType ; import com . pogofish . jadt . ast . RefType . ClassType ; import com . pogofish . jadt . ast . Type ; import com . pogofish . jadt . ast . Type . Primitive ; import com . pogofish . jadt . ast . Type . Ref ; public class ASTPrinter { public static String print ( Doc doc ) { final StringBuilder builder = new StringBuilder ( doc . pkg . name . isEmpty ( ) ? "" : ( "" + doc . pkg . name + "" ) ) ; if ( ! doc . imports . isEmpty ( ) ) { for ( Imprt imp : doc . imports ) { builder . append ( "" + imp . name + "" ) ; } builder . append ( "" ) ; } for ( DataType dataType : doc . dataTypes ) { builder . append ( print ( dataType ) ) ; builder . append ( "" ) ; } return builder . toString ( ) ; } public static String printComments ( String indent , List < JavaComment > comments ) { final StringBuilder builder = new StringBuilder ( ) ; for ( JavaComment comment : comments ) { builder . append ( print ( indent , comment ) ) ; builder . append ( "" ) ; } return builder . toString ( ) ; } public static String print ( final String indent , JavaComment comment ) { return comment . match ( new JavaComment . MatchBlock < String > ( ) { @ Override public String _case ( JavaDocComment x ) { final StringBuilder builder = new StringBuilder ( indent ) ; builder . append ( x . start ) ; for ( JDToken token : x . generalSection ) { builder . append ( print ( indent , token ) ) ; } for ( JDTagSection tagSection : x . tagSections ) { for ( JDToken token : tagSection . tokens ) { builder . append ( print ( indent , token ) ) ; } } builder . append ( x . end ) ; return builder . toString ( ) ; } @ Override public String _case ( JavaBlockComment comment ) { final StringBuilder builder = new StringBuilder ( indent ) ; for ( List < BlockToken > line : comment . lines ) { for ( BlockToken token : line ) { builder . append ( token . match ( new BlockToken . MatchBlock < String > ( ) { @ Override public String _case ( BlockWord x ) { return x . word ; } @ Override public String _case ( BlockWhiteSpace x ) { return x . ws ; } @ Override public String _case ( BlockEOL x ) { return x . content + indent ; } } ) ) ; } } return builder . toString ( ) ; } @ Override public String _case ( JavaEOLComment x ) { return x . comment ; } } ) ; } public static String print ( DataType dataType ) { final StringBuilder builder = new StringBuilder ( ) ; for ( Annotation annotation : dataType . annotations ) { builder . append ( print ( annotation ) ) ; builder . append ( "" ) ; } builder . append ( dataType . name ) ; dataType . extendedType . _switch ( new Optional . SwitchBlock < RefType > ( ) { @ Override public void _case ( Some < RefType > x ) { builder . append ( "" ) ; builder . append ( print ( x . value ) ) ; } @ Override public void _case ( None < RefType > x ) { } } ) ; if ( ! dataType . implementedTypes . isEmpty ( ) ) { builder . append ( "" ) ; boolean first = true ; for ( RefType type : dataType . implementedTypes ) { if ( first ) { first = false ; } else { builder . append ( "" ) ; } builder . append ( print ( type ) ) ; } } builder . append ( "" ) ; boolean first = true ; for ( Constructor constructor : dataType . constructors ) { if ( first ) { first = false ; } else { builder . append ( "" ) ; } builder . append ( print ( constructor ) ) ; } return builder . toString ( ) ; } public static String print ( Constructor constructor ) { final StringBuilder builder = new StringBuilder ( constructor . name ) ; if ( ! constructor . args . isEmpty ( ) ) { builder . append ( "" ) ; boolean first = true ; for ( Arg arg : constructor . args ) { if ( first ) { first = false ; } else { builder . append ( "" ) ; } builder . append ( print ( arg ) ) ; } builder . append ( "" ) ; } return builder . toString ( ) ; } public static String print ( Arg arg ) { return printArgModifiers ( arg . modifiers ) + print ( arg . type ) + "" + arg . name ; } public static String printArgModifiers ( List < ArgModifier > modifiers ) { final StringBuilder builder = new StringBuilder ( ) ; if ( modifiers . contains ( ArgModifier . _Final ( ) ) ) { builder . append ( print ( ArgModifier . _Final ( ) ) ) ; builder . append ( "" ) ; } if ( modifiers . contains ( ArgModifier . _Transient ( ) ) ) { builder . append ( print ( ArgModifier . _Transient ( ) ) ) ; builder . append ( "" ) ; } if ( modifiers . contains ( ArgModifier . _Volatile ( ) ) ) { builder . append ( print ( ArgModifier . _Volatile ( ) ) ) ; builder . append ( "" ) ; } return builder . toString ( ) ; } public static String print ( Type type ) { return type . match ( new Type . MatchBlock < String > ( ) { @ Override public String _case ( Ref x ) { return print ( x . type ) ; } @ Override public String _case ( Primitive x ) { return print ( x . type ) ; } } ) ; } public static String print ( RefType type ) { return type . match ( new RefType . MatchBlock < String > ( ) { @ Override public String _case ( ClassType x ) { final StringBuilder builder = new StringBuilder ( x . baseName ) ; if ( ! x . typeArguments . isEmpty ( ) ) { builder . append ( "" ) ; boolean first = true ; for ( RefType typeArgument : x . typeArguments ) { if ( first ) { first = false ; } else { builder . append ( "" ) ; } builder . append ( print ( typeArgument ) ) ; } builder . append ( ">" ) ; } return builder . toString ( ) ; } @ Override public String _case ( ArrayType x ) { return print ( x . heldType ) + "" ; } } ) ; } public static String print ( PrimitiveType type ) { return type . match ( new PrimitiveType . MatchBlock < String > ( ) { @ Override public String _case ( BooleanType x ) { return "" ; } @ Override public String _case ( ByteType x ) { return "" ; } @ Override public String _case ( CharType x ) { return "" ; } @ Override public String _case ( DoubleType x ) { return "" ; } @ Override public String _case ( FloatType x ) { return "" ; } @ Override public String _case ( IntType x ) { return "" ; } @ Override public String _case ( LongType x ) { return "" ; } @ Override public String _case ( ShortType x ) { return "" ; } } ) ; } public static String print ( ArgModifier modifier ) { return modifier . match ( new ArgModifier . MatchBlock < String > ( ) { @ Override public String _case ( Final x ) { return "" ; } @ Override public String _case ( Volatile x ) { return "" ; } @ Override public String _case ( Transient x ) { return "" ; } } ) ; } private static String print ( final String indent , JDToken token ) { return token . match ( new JDToken . MatchBlock < String > ( ) { @ Override public String _case ( JDAsterisk x ) { return "" ; } @ Override public String _case ( JDEOL x ) { return x . content + indent ; } @ Override public String _case ( JDTag x ) { return x . name ; } @ Override public String _case ( JDWord x ) { return x . word ; } @ Override public String _case ( JDWhiteSpace x ) { return x . ws ; } } ) ; } public static String print ( final Literal literal ) { return literal . match ( new Literal . MatchBlock < String > ( ) { @ Override public String _case ( StringLiteral x ) { return x . content ; } @ Override public String _case ( FloatingPointLiteral x ) { return x . content ; } @ Override public String _case ( IntegerLiteral x ) { return x . content ; } @ Override public String _case ( CharLiteral x ) { return x . content ; } @ Override public String _case ( BooleanLiteral x ) { return x . content ; } @ Override public String _case ( NullLiteral x ) { return "" ; } } ) ; } public static String print ( Expression expression ) { return expression . match ( new Expression . MatchBlock < String > ( ) { @ Override public String _case ( LiteralExpression x ) { return print ( x . literal ) ; } @ Override public String _case ( VariableExpression x ) { return x . selector . match ( new Optional . MatchBlock < Expression , String > ( ) { @ Override public String _case ( Some < Expression > x ) { return print ( x . value ) + "" ; } @ Override public String _case ( None < Expression > x ) { return "" ; } } ) + x . identifier ; } @ Override public String _case ( NestedExpression x ) { return "" + print ( x . expression ) + "" ; } @ Override public String _case ( ClassReference x ) { return print ( x . type ) + "" ; } @ Override public String _case ( TernaryExpression x ) { return print ( x . cond ) + "" + print ( x . trueExpression ) + "" + print ( x . falseExpression ) ; } } ) ; } public static String print ( Annotation annotation ) { return "" + annotation . name + annotation . element . match ( new Optional . MatchBlock < AnnotationElement , String > ( ) { @ Override public String _case ( Some < AnnotationElement > x ) { return "" + print ( x . value ) + "" ; } @ Override public String _case ( None < AnnotationElement > x ) { return "" ; } } ) ; } public static String print ( AnnotationElement value ) { return value . match ( new AnnotationElement . MatchBlock < String > ( ) { @ Override public String _case ( ElementValue x ) { return print ( x . value ) ; } @ Override public String _case ( ElementValuePairs x ) { final StringBuilder builder = new StringBuilder ( ) ; boolean first = true ; for ( AnnotationKeyValue kv : x . keyValues ) { if ( first ) { first = false ; } else { builder . append ( "" ) ; } builder . append ( kv . key ) ; builder . append ( "" ) ; builder . append ( print ( kv . value ) ) ; } return builder . toString ( ) ; } } ) ; } public static String print ( AnnotationValue value ) { return value . match ( new AnnotationValue . MatchBlock < String > ( ) { @ Override public String _case ( AnnotationValueAnnotation x ) { return print ( x . annotation ) ; } @ Override public String _case ( AnnotationValueExpression x ) { return print ( x . expression ) ; } @ Override public String _case ( AnnotationValueArray x ) { final StringBuilder builder = new StringBuilder ( "" ) ; boolean first = true ; for ( AnnotationValue value : x . values ) { if ( first ) { first = false ; } else { builder . append ( "" ) ; } builder . append ( print ( value ) ) ; } return builder . toString ( ) ; } } ) ; } } package com . pogofish . jadt . printer ; import com . pogofish . jadt . errors . SemanticError ; import com . pogofish . jadt . errors . SemanticError . ConstructorDataTypeConflict ; import com . pogofish . jadt . errors . SemanticError . DuplicateArgName ; import com . pogofish . jadt . errors . SemanticError . DuplicateConstructor ; import com . pogofish . jadt . errors . SemanticError . DuplicateDataType ; import com . pogofish . jadt . errors . SemanticError . DuplicateModifier ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . errors . UserError ; import com . pogofish . jadt . errors . UserError . Semantic ; import com . pogofish . jadt . errors . UserError . Syntactic ; public class UserErrorPrinter { public static String print ( UserError error ) { return error . match ( new UserError . MatchBlock < String > ( ) { @ Override public String _case ( Semantic x ) { return print ( x . error ) ; } @ Override public String _case ( Syntactic x ) { return print ( x . error ) ; } } ) ; } public static String print ( SyntaxError error ) { return "" + error . found + "" + error . expected + "" + error . line + "" ; } public static String print ( SemanticError error ) { return error . match ( new SemanticError . MatchBlock < String > ( ) { @ Override public String _case ( DuplicateDataType x ) { return "" + x . dataTypeName + "" ; } @ Override public String _case ( ConstructorDataTypeConflict x ) { return "" + x . dataTypeName + "" + x . dataTypeName + "" ; } @ Override public String _case ( DuplicateConstructor x ) { return "" + x . dataTypeName + "" + x . constructorName + "" ; } @ Override public String _case ( DuplicateArgName x ) { return "" + x . argName + "" + x . constructorName + "" + x . dataTypeName + "" ; } @ Override public String _case ( DuplicateModifier x ) { return "" + x . modifier + "" + x . argName + "" + x . constructorName + "" + x . dataTypeName + "" ; } } ) ; } } package com . pogofish . jadt . util ; public interface ExceptionAction < A > { public abstract A doAction ( ) throws Throwable ; } package com . pogofish . jadt . util ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; public class Util { public static < A > List < A > list ( A ... elements ) { final List < A > list = new ArrayList < A > ( elements . length ) ; for ( A element : elements ) { list . add ( element ) ; } return list ; } public static < A > Set < A > set ( A ... elements ) { final Set < A > set = new HashSet < A > ( elements . length ) ; for ( A element : elements ) { set . add ( element ) ; } return set ; } public static < A > A execute ( ExceptionAction < A > action ) { try { return action . doAction ( ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Error e ) { throw e ; } catch ( Throwable e ) { throw new RuntimeException ( e ) ; } } } package com . pogofish . jadt ; import static com . pogofish . jadt . ast . ASTConstants . NO_COMMENTS ; import java . util . ArrayList ; import java . util . List ; import java . util . logging . Logger ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . ast . ParseResult ; import com . pogofish . jadt . ast . Pkg ; import com . pogofish . jadt . checker . Checker ; import com . pogofish . jadt . checker . DummyChecker ; import com . pogofish . jadt . checker . StandardChecker ; import com . pogofish . jadt . emitter . ClassBodyEmitter ; import com . pogofish . jadt . emitter . ConstructorEmitter ; import com . pogofish . jadt . emitter . DataTypeEmitter ; import com . pogofish . jadt . emitter . DocEmitter ; import com . pogofish . jadt . emitter . DummyDocEmitter ; import com . pogofish . jadt . emitter . StandardClassBodyEmitter ; import com . pogofish . jadt . emitter . StandardConstructorEmitter ; import com . pogofish . jadt . emitter . StandardDataTypeEmitter ; import com . pogofish . jadt . emitter . StandardDocEmitter ; import com . pogofish . jadt . errors . SemanticError ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . errors . UserError ; import com . pogofish . jadt . parser . DummyParser ; import com . pogofish . jadt . parser . Parser ; import com . pogofish . jadt . parser . StandardParser ; import com . pogofish . jadt . parser . javacc . JavaCCParserImplFactory ; import com . pogofish . jadt . sink . FileSinkFactoryFactory ; import com . pogofish . jadt . sink . SinkFactoryFactory ; import com . pogofish . jadt . source . FileSourceFactory ; import com . pogofish . jadt . source . Source ; import com . pogofish . jadt . source . SourceFactory ; import com . pogofish . jadt . source . StringSourceFactory ; import com . pogofish . jadt . util . Util ; public class JADT { private static final Logger logger = Logger . getLogger ( JADT . class . toString ( ) ) ; public static final String TEST_CLASS_NAME = "" ; private static final String TEST_STRING = "" ; public static final String TEST_SRC_INFO = "" ; public static final String TEST_DIR = "" ; final Parser parser ; final DocEmitter emitter ; final Checker checker ; final SourceFactory sourceFactory ; final SinkFactoryFactory factoryFactory ; public static void main ( String [ ] args ) { standardConfigDriver ( ) . parseAndEmit ( args ) ; } public static JADT standardConfigDriver ( ) { logger . fine ( "" ) ; final SourceFactory sourceFactory = new FileSourceFactory ( ) ; final ClassBodyEmitter classBodyEmitter = new StandardClassBodyEmitter ( ) ; final ConstructorEmitter constructorEmitter = new StandardConstructorEmitter ( classBodyEmitter ) ; final DataTypeEmitter dataTypeEmitter = new StandardDataTypeEmitter ( classBodyEmitter , constructorEmitter ) ; final DocEmitter docEmitter = new StandardDocEmitter ( dataTypeEmitter ) ; final Parser parser = new StandardParser ( new JavaCCParserImplFactory ( ) ) ; final Checker checker = new StandardChecker ( ) ; final SinkFactoryFactory factoryFactory = new FileSinkFactoryFactory ( ) ; return new JADT ( sourceFactory , parser , checker , docEmitter , factoryFactory ) ; } public JADT ( SourceFactory sourceFactory , Parser parser , Checker checker , DocEmitter emitter , SinkFactoryFactory factoryFactory ) { super ( ) ; this . sourceFactory = sourceFactory ; this . parser = parser ; this . emitter = emitter ; this . checker = checker ; this . factoryFactory = factoryFactory ; } public void parseAndEmit ( String [ ] args ) { logger . finest ( "" ) ; if ( args . length != ) { final String version = new Version ( ) . getVersion ( ) ; logger . info ( "" + version + "" ) ; logger . info ( "" ) ; logger . info ( "" ) ; throw new IllegalArgumentException ( "" + version + "" ) ; } final String srcPath = args [ ] ; final String destDirName = args [ ] ; parseAndEmit ( srcPath , destDirName ) ; } public void parseAndEmit ( String srcPath , final String destDir ) { final String version = new Version ( ) . getVersion ( ) ; logger . info ( "" + version + "" ) ; logger . info ( "" + srcPath ) ; logger . info ( "" + destDir ) ; final List < ? extends Source > sources = sourceFactory . createSources ( srcPath ) ; for ( Source source : sources ) { final List < UserError > errors = new ArrayList < UserError > ( ) ; final ParseResult result = parser . parse ( source ) ; for ( SyntaxError error : result . errors ) { errors . add ( UserError . _Syntactic ( error ) ) ; } final List < SemanticError > semanticErrors = checker . check ( result . doc ) ; for ( SemanticError error : semanticErrors ) { errors . add ( UserError . _Semantic ( error ) ) ; } if ( ! errors . isEmpty ( ) ) { throw new JADTUserErrorsException ( errors ) ; } emitter . emit ( factoryFactory . createSinkFactory ( destDir ) , result . doc ) ; } } public static JADT createDummyJADT ( List < SyntaxError > syntaxErrors , List < SemanticError > semanticErrors , String testSrcInfo , SinkFactoryFactory factory ) { final SourceFactory sourceFactory = new StringSourceFactory ( TEST_STRING ) ; final Doc doc = new Doc ( TEST_SRC_INFO , Pkg . _Pkg ( NO_COMMENTS , "" ) , Util . < Imprt > list ( ) , Util . < DataType > list ( ) ) ; final ParseResult parseResult = new ParseResult ( doc , syntaxErrors ) ; final DocEmitter docEmitter = new DummyDocEmitter ( doc , TEST_CLASS_NAME ) ; final Parser parser = new DummyParser ( parseResult , testSrcInfo , TEST_STRING ) ; final Checker checker = new DummyChecker ( semanticErrors ) ; final JADT jadt = new JADT ( sourceFactory , parser , checker , docEmitter , factory ) ; return jadt ; } } package com . pogofish . jadt ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . Reader ; import java . net . URL ; import java . util . Properties ; import com . pogofish . jadt . util . ExceptionAction ; import com . pogofish . jadt . util . Util ; public class Version { String MODULE_PROPERTIES = "" ; String MODULE_VERSION = "" ; public String getVersion ( ) { return Util . execute ( new ExceptionAction < String > ( ) { @ Override public String doAction ( ) throws IOException { final URL resource = Version . class . getClassLoader ( ) . getResource ( MODULE_PROPERTIES ) ; if ( resource == null ) { throw new FileNotFoundException ( "" + MODULE_PROPERTIES ) ; } final Reader reader = new InputStreamReader ( resource . openStream ( ) , "" ) ; try { final Properties properties = new Properties ( ) ; properties . load ( reader ) ; final String property = properties . getProperty ( MODULE_VERSION ) ; return property == null ? "" + MODULE_VERSION + "" + MODULE_PROPERTIES : property ; } finally { reader . close ( ) ; } } } ) ; } } package com . pogofish . jadt . ast ; import java . util . Collections ; import java . util . List ; public class ASTConstants { public static final List < JavaComment > NO_COMMENTS = Collections . emptyList ( ) ; public static final Pkg EMPTY_PKG = Pkg . _Pkg ( NO_COMMENTS , "" ) ; public static final List < Imprt > NO_IMPORTS = Collections . emptyList ( ) ; } package com . pogofish . jadt . javadoc . javacc ; import static com . pogofish . jadt . ast . JDToken . _JDWhiteSpace ; import java . io . Reader ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . pogofish . jadt . ast . JDToken ; import com . pogofish . jadt . comments . javacc . generated . BaseJavaDocParserImpl ; import com . pogofish . jadt . comments . javacc . generated . Token ; public class JavaDocParserImpl extends BaseJavaDocParserImpl { public JavaDocParserImpl ( Reader stream ) { super ( stream ) ; } public Token lookahead ( ) { Token current = token ; if ( current . next == null ) { current . next = token_source . getNextToken ( ) ; } return current . next ; } @ Override protected List < JDToken > nextTokenWhitespace ( ) { final Token next = lookahead ( ) ; return whiteSpace ( next ) ; } protected List < JDToken > whiteSpace ( Token token ) { final List < JDToken > wss = new ArrayList < JDToken > ( ) ; Token ws = token . specialToken ; while ( ws != null ) { switch ( ws . kind ) { case WS : wss . add ( _JDWhiteSpace ( ws . image ) ) ; break ; default : } ws = ws . specialToken ; } Collections . reverse ( wss ) ; return wss ; } } package com . pogofish . jadt . parser ; import java . util . List ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Expression ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . ast . Literal ; import com . pogofish . jadt . ast . Pkg ; import com . pogofish . jadt . ast . PrimitiveType ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . ast . Tuple ; import com . pogofish . jadt . ast . Type ; import com . pogofish . jadt . errors . SyntaxError ; public interface ParserImpl { public abstract String getSrcInfo ( ) ; public abstract Doc doc ( ) throws Exception ; public abstract Pkg pkg ( ) throws Exception ; public abstract List < Imprt > imports ( ) throws Exception ; public abstract Imprt singleImport ( ) throws Exception ; public abstract String packageName ( ) throws Exception ; public abstract String packageSpec ( ) throws Exception ; public abstract List < DataType > dataTypes ( ) throws Exception ; public abstract DataType dataType ( ) throws Exception ; public abstract Tuple < List < JavaComment > , String > dataTypeName ( ) throws Exception ; public abstract List < String > typeArguments ( ) throws Exception ; public abstract String typeArgument ( ) throws Exception ; public abstract List < Constructor > constructors ( List < JavaComment > comments ) throws Exception ; public abstract Constructor constructor ( List < JavaComment > comments ) throws Exception ; public abstract Tuple < List < JavaComment > , String > constructorName ( ) throws Exception ; public abstract List < Arg > args ( ) throws Exception ; public abstract Arg arg ( ) throws Exception ; public abstract List < ArgModifier > argModifiers ( ) throws Exception ; public abstract ArgModifier argModifier ( ) throws Exception ; public abstract String argName ( ) throws Exception ; public abstract Type type ( ) throws Exception ; public abstract RefType refType ( ) throws Exception ; public abstract void arrayTypeBrackets ( ) throws Exception ; public abstract RefType classType ( ) throws Exception ; public abstract String className ( ) throws Exception ; public abstract List < RefType > actualTypeArguments ( ) throws Exception ; public abstract PrimitiveType primitiveType ( ) throws Exception ; public abstract String dottedIdentifier ( String expected ) throws Exception ; public abstract Tuple < List < JavaComment > , String > commentedIdentifier ( String expected ) throws Exception ; public abstract String identifier ( String expected ) throws Exception ; public abstract List < JavaComment > importKeyword ( ) throws Exception ; public abstract List < JavaComment > packageKeyword ( ) throws Exception ; public abstract ArgModifier finalKeyword ( ) throws Exception ; public abstract ArgModifier transientKeyword ( ) throws Exception ; public abstract ArgModifier volatileKeyword ( ) throws Exception ; public abstract void extendsKeyword ( ) throws Exception ; public abstract void implementsKeyword ( ) throws Exception ; public abstract PrimitiveType booleanType ( ) throws Exception ; public abstract PrimitiveType byteType ( ) throws Exception ; public abstract PrimitiveType charType ( ) throws Exception ; public abstract PrimitiveType shortType ( ) throws Exception ; public abstract PrimitiveType intType ( ) throws Exception ; public abstract PrimitiveType longType ( ) throws Exception ; public abstract PrimitiveType floatType ( ) throws Exception ; public abstract PrimitiveType doubleType ( ) throws Exception ; public abstract void dot ( ) throws Exception ; public abstract List < JavaComment > at ( boolean allowComments ) throws Exception ; public abstract void comma ( ) throws Exception ; public abstract void lparen ( ) throws Exception ; public abstract void rparen ( ) throws Exception ; public abstract void lbracket ( ) throws Exception ; public abstract void rbracket ( ) throws Exception ; public abstract void langle ( ) throws Exception ; public abstract void rangle ( ) throws Exception ; public abstract List < JavaComment > equals ( boolean allowComments ) throws Exception ; public abstract List < JavaComment > bar ( ) throws Exception ; public abstract void eof ( ) throws Exception ; public abstract List < SyntaxError > errors ( ) ; public abstract Literal literal ( ) throws Exception ; public abstract Tuple < List < JavaComment > , Annotation > annotation ( boolean allowComments ) throws Exception ; public abstract Expression expression ( ) throws Exception ; public abstract void lcurly ( ) throws Exception ; public abstract void rcurly ( ) throws Exception ; public abstract void question ( ) throws Exception ; public abstract void colon ( ) throws Exception ; } package com . pogofish . jadt . parser ; import java . io . Reader ; public interface ParserImplFactory { public ParserImpl create ( String srcInfo , Reader reader ) ; } package com . pogofish . jadt . parser ; import java . io . BufferedReader ; import java . io . IOException ; import com . pogofish . jadt . ast . ParseResult ; import com . pogofish . jadt . source . Source ; public class DummyParser implements Parser { private final ParseResult testResult ; private final String testSrcInfo ; private final String testString ; public DummyParser ( ParseResult testResult , String testSrcInfo , String testString ) { this . testResult = testResult ; this . testSrcInfo = testSrcInfo ; this . testString = testString ; } @ Override public ParseResult parse ( Source source ) { if ( ! testSrcInfo . equals ( source . getSrcInfo ( ) ) ) { throw new RuntimeException ( "" + testSrcInfo + "" + source . getSrcInfo ( ) ) ; } try { BufferedReader reader = source . createReader ( ) ; try { if ( ! testString . equals ( reader . readLine ( ) ) ) { throw new RuntimeException ( "" ) ; } final String secondLine = reader . readLine ( ) ; if ( secondLine != null ) { throw new RuntimeException ( "" + secondLine + "" ) ; } } finally { reader . close ( ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return testResult ; } } package com . pogofish . jadt . parser . javacc ; import static com . pogofish . jadt . ast . JavaComment . _JavaEOLComment ; import java . io . Reader ; import java . io . StringReader ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Set ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . comments . BlockCommentParser ; import com . pogofish . jadt . comments . JavaDocParser ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . parser . ParserImpl ; import com . pogofish . jadt . parser . javacc . generated . BaseJavaCCParserImpl ; import com . pogofish . jadt . parser . javacc . generated . Token ; import com . pogofish . jadt . util . Util ; public class JavaCCParserImpl extends BaseJavaCCParserImpl implements ParserImpl { private static final String COMMENT_NOT_ALLOWED = "" ; private static final String UNTERMINATED_COMMENT_STRING = "" ; private static final String EOF_STRING = "" ; private static final JavaDocParser javaDocParser = new JavaDocParser ( ) ; private static final BlockCommentParser blockCommentParser = new BlockCommentParser ( ) ; private boolean recovering = false ; private final String srcInfo ; ; private final List < SyntaxError > errors = new ArrayList < SyntaxError > ( ) ; private int nextId = ; private static final Set < Integer > punctuation = Collections . unmodifiableSet ( Util . set ( LANGLE , RANGLE , EQUALS , LPAREN , RPAREN , COMMA , BAR , LBRACKET , RBRACKET , DOT , EOF ) ) ; public JavaCCParserImpl ( String srcInfo , Reader stream ) { super ( new JavaCCReader ( stream ) ) ; this . srcInfo = srcInfo ; } @ Override protected void checkNoComments ( String expected ) { final List < JavaComment > comments = tokenComments ( ) ; if ( ! comments . isEmpty ( ) ) { error ( expected , COMMENT_NOT_ALLOWED ) ; } } private boolean peekPunctuation ( ) { return ( punctuation . contains ( lookahead ( ) . kind ) ) ; } @ Override protected String badIdentifier ( String expected ) { error ( expected ) ; final String id = "" + ( nextId ++ ) ; if ( ! peekPunctuation ( ) ) { final Token token = getNextToken ( ) ; return "" + "" + friendlyName ( token ) + id ; } else { return "" + id ; } } @ Override protected void recovered ( ) { recovering = false ; } @ Override public List < SyntaxError > errors ( ) { return errors ; } @ Override public String getSrcInfo ( ) { return srcInfo ; } @ Override protected void error ( String expected ) { error ( expected , friendlyName ( lookahead ( ) ) ) ; } private void error ( String expected , String actual ) { if ( ! recovering ) { recovering = true ; final String outputString = ( EOF_STRING . equals ( actual ) || UNTERMINATED_COMMENT_STRING . equals ( actual ) || COMMENT_NOT_ALLOWED . equals ( actual ) ) ? actual : "" + actual + "" ; errors . add ( SyntaxError . _UnexpectedToken ( expected , outputString , lookahead ( ) . beginLine ) ) ; } } private String friendlyName ( Token token ) { return token . kind == EOF ? EOF_STRING : token . kind == UNTERMINATED_COMMENT ? UNTERMINATED_COMMENT_STRING : token . image ; } private Token lookahead ( int n ) { Token current = token ; for ( int i = ; i < n ; i ++ ) { if ( current . next == null ) { current . next = token_source . getNextToken ( ) ; } current = current . next ; } return current ; } @ Override protected List < JavaComment > tokenComments ( ) { return tokenComments ( token ) ; } protected List < JavaComment > tokenComments ( Token token ) { final List < JavaComment > comments = new ArrayList < JavaComment > ( ) ; Token comment = token . specialToken ; while ( comment != null ) { switch ( comment . kind ) { case JAVA_EOL_COMMENT : comments . add ( _JavaEOLComment ( comment . image ) ) ; break ; case JAVA_ML_COMMENT : comments . add ( blockCommentParser . parse ( new StringReader ( comment . image ) ) ) ; break ; case JAVADOC_COMMENT : comments . add ( javaDocParser . parse ( new StringReader ( comment . image ) ) ) ; break ; default : break ; } comment = comment . specialToken ; } Collections . reverse ( comments ) ; return comments ; } } package com . pogofish . jadt . parser . javacc ; import java . io . Reader ; import com . pogofish . jadt . parser . ParserImplFactory ; public class JavaCCParserImplFactory implements ParserImplFactory { @ Override public JavaCCParserImpl create ( String srcInfo , Reader reader ) { final JavaCCParserImpl impl = new JavaCCParserImpl ( srcInfo , reader ) ; return impl ; } } package com . pogofish . jadt . parser . javacc ; import java . io . IOException ; import java . io . Reader ; public class JavaCCReader extends Reader { private final Reader reader ; private boolean closed = false ; public JavaCCReader ( Reader reader ) { super ( ) ; this . reader = reader ; } @ Override public void close ( ) throws IOException { reader . close ( ) ; closed = true ; } @ Override public int read ( char [ ] cbuf , int off , int len ) throws IOException { try { return reader . read ( cbuf , off , len ) ; } catch ( IOException e ) { return handleIOException ( e ) ; } } private int handleIOException ( IOException e ) throws IOException { if ( closed ) { throw e ; } else { throw new RuntimeException ( e ) ; } } } package com . pogofish . jadt . parser ; import com . pogofish . jadt . ast . ParseResult ; import com . pogofish . jadt . source . Source ; public interface Parser { public abstract ParseResult parse ( Source source ) ; } package com . pogofish . jadt . parser ; import java . io . BufferedReader ; import java . util . logging . Logger ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . ParseResult ; import com . pogofish . jadt . source . Source ; import com . pogofish . jadt . util . ExceptionAction ; import com . pogofish . jadt . util . Util ; public class StandardParser implements Parser { private final ParserImplFactory factory ; static final Logger logger = Logger . getLogger ( StandardParser . class . toString ( ) ) ; public StandardParser ( ParserImplFactory factory ) { super ( ) ; this . factory = factory ; } @ Override public ParseResult parse ( final Source source ) { return Util . execute ( new ExceptionAction < ParseResult > ( ) { @ Override public ParseResult doAction ( ) throws Throwable { logger . fine ( "" + source . getSrcInfo ( ) ) ; final BufferedReader reader = source . createReader ( ) ; try { final ParserImpl impl = factory . create ( source . getSrcInfo ( ) , reader ) ; final Doc doc = impl . doc ( ) ; return new ParseResult ( doc , impl . errors ( ) ) ; } finally { reader . close ( ) ; } } } ) ; } } package com . pogofish . jadt . checker ; import java . util . List ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . errors . SemanticError ; public class DummyChecker implements Checker { private final List < SemanticError > errors ; public DummyChecker ( List < SemanticError > errors ) { super ( ) ; this . errors = errors ; } @ Override public List < SemanticError > check ( Doc doc ) { return errors ; } } package com . pogofish . jadt . checker ; import static com . pogofish . jadt . errors . SemanticError . _ConstructorDataTypeConflict ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateArgName ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateConstructor ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateDataType ; import static com . pogofish . jadt . errors . SemanticError . _DuplicateModifier ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . logging . Logger ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . ArgModifier ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . errors . SemanticError ; import com . pogofish . jadt . printer . ASTPrinter ; public class StandardChecker implements Checker { private static final Logger logger = Logger . getLogger ( StandardChecker . class . toString ( ) ) ; @ Override public List < SemanticError > check ( Doc doc ) { logger . fine ( "" + doc . srcInfo ) ; final List < SemanticError > errors = new ArrayList < SemanticError > ( ) ; final Set < String > dataTypeNames = new HashSet < String > ( ) ; for ( DataType dataType : doc . dataTypes ) { if ( dataTypeNames . contains ( dataType . name ) ) { logger . info ( "" + dataType . name + "" ) ; errors . add ( _DuplicateDataType ( dataType . name ) ) ; } else { dataTypeNames . add ( dataType . name ) ; } errors . addAll ( check ( dataType ) ) ; } return errors ; } private List < SemanticError > check ( DataType dataType ) { logger . finer ( "" + dataType . name ) ; final List < SemanticError > errors = new ArrayList < SemanticError > ( ) ; final Set < String > constructorNames = new HashSet < String > ( ) ; for ( Constructor constructor : dataType . constructors ) { logger . finest ( "" + constructor . name + "" + dataType . name ) ; if ( dataType . constructors . size ( ) > && dataType . name . equals ( constructor . name ) ) { logger . info ( "" + dataType . name + "" ) ; errors . add ( _ConstructorDataTypeConflict ( dataType . name ) ) ; } if ( constructorNames . contains ( constructor . name ) ) { logger . info ( "" + constructor . name + "" + dataType . name + "" ) ; errors . add ( _DuplicateConstructor ( dataType . name , constructor . name ) ) ; } else { constructorNames . add ( constructor . name ) ; } errors . addAll ( check ( dataType , constructor ) ) ; } return errors ; } private List < SemanticError > check ( DataType dataType , Constructor constructor ) { logger . finer ( "" + dataType . name + "" + constructor . name ) ; final List < SemanticError > errors = new ArrayList < SemanticError > ( ) ; final Set < String > argNames = new HashSet < String > ( ) ; for ( Arg arg : constructor . args ) { if ( argNames . contains ( arg . name ) ) { errors . add ( _DuplicateArgName ( dataType . name , constructor . name , arg . name ) ) ; } else { argNames . add ( arg . name ) ; } errors . addAll ( check ( dataType , constructor , arg ) ) ; } return errors ; } private List < SemanticError > check ( DataType dataType , Constructor constructor , Arg arg ) { logger . finest ( "" + dataType . name + "" + constructor . name ) ; final List < SemanticError > errors = new ArrayList < SemanticError > ( ) ; final Set < ArgModifier > modifiers = new HashSet < ArgModifier > ( ) ; for ( ArgModifier modifier : arg . modifiers ) { if ( modifiers . contains ( modifier ) ) { final String modName = ASTPrinter . print ( modifier ) ; errors . add ( _DuplicateModifier ( dataType . name , constructor . name , arg . name , modName ) ) ; } else { modifiers . add ( modifier ) ; } } return errors ; } } package com . pogofish . jadt . checker ; import java . util . List ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . errors . SemanticError ; public interface Checker { public List < SemanticError > check ( Doc doc ) ; } package com . pogofish . jadt . emitter ; import java . util . List ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . sink . Sink ; public interface ClassBodyEmitter { public abstract void constructorFactory ( Sink sink , String dataTypeName , String factoryName , List < String > typeParameters , Constructor constructor ) ; public abstract void emitConstructorMethod ( Sink sink , String indent , Constructor constructor ) ; public abstract void emitToString ( Sink sink , String indent , Constructor constructor ) ; public abstract void emitEquals ( Sink sink , String indent , Constructor constructor , List < String > typeArguments ) ; public abstract void emitHashCode ( Sink sink , String indent , Constructor constructor ) ; public void emitParameterizedTypeName ( Sink sink , List < String > typeArguments ) ; } package com . pogofish . jadt . emitter ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . sink . Sink ; public class DummyDataTypeEmitter implements DataTypeEmitter { @ Override public void emit ( Sink sink , DataType dataType , String header ) { sink . write ( header + dataType . name ) ; } } package com . pogofish . jadt . emitter ; import static com . pogofish . jadt . util . Util . set ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import java . util . logging . Logger ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . comments . CommentProcessor ; import com . pogofish . jadt . printer . ASTPrinter ; import com . pogofish . jadt . sink . Sink ; public class StandardConstructorEmitter implements ConstructorEmitter { private static final String INDENT = "" ; private static final Logger logger = Logger . getLogger ( StandardConstructorEmitter . class . toString ( ) ) ; private final ClassBodyEmitter classBodyEmitter ; private final CommentProcessor commentProcessor = new CommentProcessor ( ) ; private static final Set < String > CONSTRUCTOR_CLASS_STRIP = set ( "" , "" ) ; public StandardConstructorEmitter ( ClassBodyEmitter classBodyEmitter ) { super ( ) ; this . classBodyEmitter = classBodyEmitter ; } @ Override public void constructorFactory ( Sink sink , String dataTypeName , List < String > typeParameters , Constructor constructor ) { classBodyEmitter . constructorFactory ( sink , dataTypeName , constructor . name , typeParameters , constructor ) ; } @ Override public void constructorDeclaration ( Sink sink , Constructor constructor , String dataTypeName , List < String > typeParameters ) { logger . finer ( "" + constructor . name + "" + dataTypeName ) ; sink . write ( ASTPrinter . printComments ( "" , commentProcessor . leftAlign ( commentProcessor . stripTags ( CONSTRUCTOR_CLASS_STRIP , constructor . comments ) ) ) ) ; sink . write ( "" + constructor . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , typeParameters ) ; sink . write ( "" + dataTypeName ) ; classBodyEmitter . emitParameterizedTypeName ( sink , typeParameters ) ; sink . write ( "" ) ; classBodyEmitter . emitConstructorMethod ( sink , INDENT , constructor ) ; sink . write ( "" ) ; emitAccept ( sink , typeParameters ) ; sink . write ( "" ) ; classBodyEmitter . emitHashCode ( sink , INDENT , constructor ) ; sink . write ( "" ) ; classBodyEmitter . emitEquals ( sink , INDENT , constructor , typeParameters ) ; sink . write ( "" ) ; classBodyEmitter . emitToString ( sink , INDENT , constructor ) ; sink . write ( "" ) ; sink . write ( "" ) ; } private void emitAccept ( Sink sink , List < String > typeArguments ) { final List < String > visitorTypeArguments = new ArrayList < String > ( typeArguments ) ; visitorTypeArguments . add ( "" ) ; sink . write ( "" ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , visitorTypeArguments ) ; sink . write ( "" ) ; sink . write ( "" ) ; sink . write ( "" ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , typeArguments ) ; sink . write ( "" ) ; } } package com . pogofish . jadt . emitter ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . sink . Sink ; public interface DataTypeEmitter { public abstract void emit ( Sink sink , DataType dataType , String header ) ; } package com . pogofish . jadt . emitter ; import java . util . List ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . sink . Sink ; public class DummyClassBodyEmitter implements ClassBodyEmitter { @ Override public void constructorFactory ( Sink sink , String dataTypeName , String factoryName , List < String > typeParameters , Constructor constructor ) { sink . write ( "" + dataTypeName + "" + factoryName + "" + constructor . name + "" ) ; } @ Override public void emitConstructorMethod ( Sink sink , String indent , Constructor constructor ) { sink . write ( indent + "" + constructor . name + "" ) ; } @ Override public void emitToString ( Sink sink , String indent , Constructor constructor ) { sink . write ( indent + "" + constructor . name + "" ) ; } @ Override public void emitEquals ( Sink sink , String indent , Constructor constructor , List < String > typeArguments ) { sink . write ( indent + "" + constructor . name + "" ) ; } @ Override public void emitHashCode ( Sink sink , String indent , Constructor constructor ) { sink . write ( indent + "" + constructor . name + "" ) ; } @ Override public void emitParameterizedTypeName ( Sink sink , List < String > typeArguments ) { sink . write ( "" ) ; } } package com . pogofish . jadt . emitter ; import java . util . ArrayList ; import java . util . List ; import java . util . logging . Logger ; import com . pogofish . jadt . ast . Annotation ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Optional ; import com . pogofish . jadt . ast . Optional . None ; import com . pogofish . jadt . ast . Optional . Some ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . comments . CommentProcessor ; import com . pogofish . jadt . printer . ASTPrinter ; import com . pogofish . jadt . sink . Sink ; public class StandardDataTypeEmitter implements DataTypeEmitter { private static final String SINGLE_CONSTRUCTOR_INDENT = "" ; private static final Logger logger = Logger . getLogger ( StandardConstructorEmitter . class . toString ( ) ) ; private final ConstructorEmitter constructorEmitter ; private final ClassBodyEmitter classBodyEmitter ; private final CommentProcessor commentProcessor = new CommentProcessor ( ) ; public StandardDataTypeEmitter ( ClassBodyEmitter classBodyEmitter , ConstructorEmitter constructorEmitter ) { super ( ) ; this . constructorEmitter = constructorEmitter ; this . classBodyEmitter = classBodyEmitter ; } @ Override public void emit ( Sink sink , DataType dataType , String header ) { logger . fine ( "" + dataType . name + "" ) ; sink . write ( header ) ; sink . write ( ASTPrinter . print ( dataType ) ) ; sink . write ( "" ) ; sink . write ( ASTPrinter . printComments ( "" , commentProcessor . leftAlign ( dataType . comments ) ) ) ; for ( Annotation annotation : dataType . annotations ) { sink . write ( ASTPrinter . print ( annotation ) ) ; sink . write ( "" ) ; } if ( dataType . constructors . size ( ) == ) { emitSingleConstructor ( sink , dataType , header ) ; } else { emitMultipleConstructor ( sink , dataType , header ) ; } } private void emitBaseClassAndInterfaces ( final Sink sink , DataType dataType ) { dataType . extendedType . _switch ( new Optional . SwitchBlock < RefType > ( ) { @ Override public void _case ( Some < RefType > x ) { sink . write ( "" ) ; sink . write ( ASTPrinter . print ( x . value ) ) ; } @ Override public void _case ( None < RefType > x ) { } } ) ; if ( ! dataType . implementedTypes . isEmpty ( ) ) { sink . write ( "" ) ; boolean first = true ; for ( RefType type : dataType . implementedTypes ) { if ( first ) { first = false ; } else { sink . write ( "" ) ; } sink . write ( ASTPrinter . print ( type ) ) ; } } } private void emitSingleConstructor ( Sink sink , DataType dataType , String header ) { logger . finer ( "" + dataType . name + "" ) ; final Constructor originalConstructor = dataType . constructors . get ( ) ; final Constructor pseudoConstructor = new Constructor ( originalConstructor . comments , dataType . name , originalConstructor . args ) ; sink . write ( "" + dataType . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; emitBaseClassAndInterfaces ( sink , dataType ) ; sink . write ( "" ) ; classBodyEmitter . constructorFactory ( sink , dataType . name , originalConstructor . name , dataType . typeArguments , pseudoConstructor ) ; sink . write ( "" ) ; classBodyEmitter . emitConstructorMethod ( sink , SINGLE_CONSTRUCTOR_INDENT , pseudoConstructor ) ; sink . write ( "" ) ; classBodyEmitter . emitHashCode ( sink , SINGLE_CONSTRUCTOR_INDENT , pseudoConstructor ) ; sink . write ( "" ) ; classBodyEmitter . emitEquals ( sink , SINGLE_CONSTRUCTOR_INDENT , pseudoConstructor , dataType . typeArguments ) ; sink . write ( "" ) ; classBodyEmitter . emitToString ( sink , SINGLE_CONSTRUCTOR_INDENT , pseudoConstructor ) ; sink . write ( "" ) ; sink . write ( "" ) ; } private void emitMultipleConstructor ( Sink sink , DataType dataType , String header ) { logger . finer ( "" + dataType . name + "" ) ; sink . write ( "" + dataType . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; emitBaseClassAndInterfaces ( sink , dataType ) ; sink . write ( "" ) ; sink . write ( "" + dataType . name + "" ) ; sink . write ( "" ) ; for ( Constructor constructor : dataType . constructors ) { sink . write ( "" ) ; constructorEmitter . constructorFactory ( sink , dataType . name , dataType . typeArguments , constructor ) ; } sink . write ( "" ) ; final List < String > visitorTypeArguments = new ArrayList < String > ( dataType . typeArguments ) ; visitorTypeArguments . add ( "" ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , visitorTypeArguments ) ; sink . write ( "" ) ; for ( Constructor constructor : dataType . constructors ) { sink . write ( "" + constructor . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; } sink . write ( "" ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , visitorTypeArguments ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , visitorTypeArguments ) ; sink . write ( "" ) ; for ( Constructor constructor : dataType . constructors ) { sink . write ( "" ) ; sink . write ( "" + constructor . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; } sink . write ( "" + dataType . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; sink . write ( "" ) ; sink . write ( "" ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; for ( Constructor constructor : dataType . constructors ) { sink . write ( "" + constructor . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; } sink . write ( "" ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; for ( Constructor constructor : dataType . constructors ) { sink . write ( "" ) ; sink . write ( "" + constructor . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; } sink . write ( "" + dataType . name ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; sink . write ( "" ) ; for ( Constructor constructor : dataType . constructors ) { sink . write ( "" ) ; constructorEmitter . constructorDeclaration ( sink , constructor , dataType . name , dataType . typeArguments ) ; } sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , visitorTypeArguments ) ; sink . write ( "" ) ; sink . write ( "" ) ; classBodyEmitter . emitParameterizedTypeName ( sink , dataType . typeArguments ) ; sink . write ( "" ) ; sink . write ( "" ) ; } } package com . pogofish . jadt . emitter ; import java . util . logging . Logger ; import com . pogofish . jadt . Version ; import com . pogofish . jadt . ast . DataType ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . ast . Imprt ; import com . pogofish . jadt . comments . CommentProcessor ; import com . pogofish . jadt . printer . ASTPrinter ; import com . pogofish . jadt . sink . Sink ; import com . pogofish . jadt . sink . SinkFactory ; public class StandardDocEmitter implements DocEmitter { private static final Logger logger = Logger . getLogger ( StandardConstructorEmitter . class . toString ( ) ) ; private final DataTypeEmitter dataTypeEmitter ; private final CommentProcessor commentProcessor = new CommentProcessor ( ) ; public StandardDocEmitter ( DataTypeEmitter dataTypeEmitter ) { super ( ) ; this . dataTypeEmitter = dataTypeEmitter ; } @ Override public void emit ( SinkFactory factory , Doc doc ) { logger . fine ( "" + doc . srcInfo ) ; final StringBuilder header = new StringBuilder ( ) ; header . append ( ASTPrinter . printComments ( "" , commentProcessor . leftAlign ( doc . pkg . comments ) ) ) ; header . append ( doc . pkg . name . isEmpty ( ) ? "" : ( "" + doc . pkg . name + "" ) ) ; if ( ! doc . imports . isEmpty ( ) ) { for ( Imprt imp : doc . imports ) { header . append ( ASTPrinter . printComments ( "" , commentProcessor . leftAlign ( imp . comments ) ) ) ; header . append ( "" + imp . name + "" ) ; } header . append ( "" ) ; } final String version = new Version ( ) . getVersion ( ) ; header . append ( "" + doc . srcInfo + "" + version + "" ) ; header . append ( "" ) ; for ( DataType dataType : doc . dataTypes ) { final Sink sink = factory . createSink ( doc . pkg . name . isEmpty ( ) ? dataType . name : doc . pkg . name + "" + dataType . name ) ; logger . info ( "" + sink . getInfo ( ) ) ; try { dataTypeEmitter . emit ( sink , dataType , header . toString ( ) ) ; } finally { sink . close ( ) ; } } } } package com . pogofish . jadt . emitter ; import java . util . List ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . sink . Sink ; public class DummyConstructorEmitter implements ConstructorEmitter { @ Override public void constructorFactory ( Sink sink , String dataTypeName , List < String > typeParameters , Constructor constructor ) { sink . write ( "" + dataTypeName + "" + constructor . name + "" ) ; } @ Override public void constructorDeclaration ( Sink sink , Constructor constructor , String dataTypeName , List < String > typeParamters ) { sink . write ( "" + dataTypeName + "" + constructor . name + "" ) ; } } package com . pogofish . jadt . emitter ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . sink . SinkFactory ; public interface DocEmitter { public abstract void emit ( SinkFactory factory , Doc doc ) ; } package com . pogofish . jadt . emitter ; import static com . pogofish . jadt . util . Util . set ; import java . util . List ; import java . util . Set ; import java . util . logging . Logger ; import com . pogofish . jadt . ast . Arg ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . ast . JavaComment ; import com . pogofish . jadt . ast . PrimitiveType ; import com . pogofish . jadt . ast . PrimitiveType . BooleanType ; import com . pogofish . jadt . ast . PrimitiveType . ByteType ; import com . pogofish . jadt . ast . PrimitiveType . CharType ; import com . pogofish . jadt . ast . PrimitiveType . IntType ; import com . pogofish . jadt . ast . PrimitiveType . ShortType ; import com . pogofish . jadt . ast . RefType ; import com . pogofish . jadt . ast . RefType . ArrayType ; import com . pogofish . jadt . ast . RefType . ClassType ; import com . pogofish . jadt . ast . Type ; import com . pogofish . jadt . ast . Type . Primitive ; import com . pogofish . jadt . ast . Type . Ref ; import com . pogofish . jadt . comments . CommentProcessor ; import com . pogofish . jadt . printer . ASTPrinter ; import com . pogofish . jadt . sink . Sink ; public class StandardClassBodyEmitter implements ClassBodyEmitter { private static final Set < String > CONSTRUCTOR_METHOD_STRIP = set ( "" ) ; private static final CommentProcessor commentProcessor = new CommentProcessor ( ) ; private static final Logger logger = Logger . getLogger ( StandardClassBodyEmitter . class . toString ( ) ) ; @ Override public void constructorFactory ( Sink sink , String dataTypeName , String factoryName , List < String > typeParametrs , Constructor constructor ) { if ( constructor . args . isEmpty ( ) ) { if ( typeParametrs . isEmpty ( ) ) { logger . finest ( "" + constructor . name ) ; } else { logger . finest ( "" + constructor . name ) ; sink . write ( "" ) ; } sink . write ( "" + dataTypeName + "" + factoryName + "" + constructor . name + "" ) ; sink . write ( ASTPrinter . printComments ( "" , commentProcessor . leftAlign ( commentProcessor . javaDocOnly ( constructor . comments ) ) ) ) ; if ( ! typeParametrs . isEmpty ( ) ) { sink . write ( "" ) ; } sink . write ( "" ) ; emitParameterizedTypeName ( sink , typeParametrs ) ; sink . write ( "" ) ; sink . write ( dataTypeName ) ; emitParameterizedTypeName ( sink , typeParametrs ) ; sink . write ( "" + factoryName + "" + factoryName + "" ) ; } else { logger . finest ( "" + constructor . name ) ; sink . write ( ASTPrinter . printComments ( "" , commentProcessor . leftAlign ( constructor . comments ) ) ) ; sink . write ( "" ) ; emitParameterizedTypeName ( sink , typeParametrs ) ; sink . write ( "" ) ; sink . write ( dataTypeName ) ; emitParameterizedTypeName ( sink , typeParametrs ) ; sink . write ( "" + factoryName + "" ) ; constructorArgs ( sink , constructor , true ) ; sink . write ( "" + constructor . name ) ; emitParameterizedTypeName ( sink , typeParametrs ) ; sink . write ( "" ) ; constructorArgs ( sink , constructor , false ) ; sink . write ( "" ) ; } } private void constructorArgs ( Sink sink , Constructor constructor , boolean withTypes ) { boolean first = true ; for ( Arg arg : constructor . args ) { if ( first ) { first = false ; } else { sink . write ( "" ) ; } sink . write ( constructorArg ( arg , withTypes ) ) ; } } @ Override public void emitConstructorMethod ( Sink sink , String indent , Constructor constructor ) { logger . finest ( "" + constructor . name ) ; final List < JavaComment > javaDoc = commentProcessor . leftAlign ( commentProcessor . javaDocOnly ( constructor . comments ) ) ; for ( Arg arg : constructor . args ) { final List < JavaComment > paramDoc = commentProcessor . paramDoc ( arg . name , javaDoc ) ; sink . write ( ASTPrinter . printComments ( indent , paramDoc ) ) ; sink . write ( indent + "" ) ; sink . write ( ASTPrinter . printArgModifiers ( arg . modifiers ) ) ; sink . write ( ASTPrinter . print ( arg . type ) + "" + arg . name + "" ) ; } sink . write ( "" ) ; sink . write ( ASTPrinter . printComments ( indent , commentProcessor . leftAlign ( commentProcessor . stripTags ( CONSTRUCTOR_METHOD_STRIP , commentProcessor . javaDocOnly ( constructor . comments ) ) ) ) ) ; sink . write ( indent + "" + constructor . name + "" ) ; constructorArgs ( sink , constructor , true ) ; sink . write ( "" ) ; for ( Arg arg : constructor . args ) { sink . write ( "" + indent + "" + arg . name + "" + arg . name + "" ) ; } sink . write ( "" + indent + "" ) ; } @ Override public void emitToString ( Sink sink , String indent , Constructor constructor ) { logger . finest ( "" + constructor . name ) ; sink . write ( indent + "" ) ; sink . write ( indent + "" ) ; sink . write ( indent + "" + constructor . name ) ; if ( ! constructor . args . isEmpty ( ) ) { sink . write ( "" ) ; boolean first = true ; for ( Arg arg : constructor . args ) { if ( first ) { first = false ; } else { sink . write ( "" ) ; } sink . write ( arg . name + "" + arg . name + "" ) ; } sink . write ( "" ) ; } sink . write ( "" ) ; sink . write ( indent + "" ) ; } @ Override public void emitEquals ( final Sink sink , final String indent , Constructor constructor , List < String > typeArguments ) { logger . finest ( "" + constructor . name ) ; sink . write ( indent + "" ) ; sink . write ( indent + "" ) ; sink . write ( indent + "" ) ; sink . write ( indent + "" ) ; sink . write ( indent + "" ) ; if ( ! constructor . args . isEmpty ( ) ) { if ( ! typeArguments . isEmpty ( ) ) { sink . write ( indent + "" ) ; } sink . write ( indent + "" + constructor . name + "" + constructor . name + "" ) ; for ( final Arg arg : constructor . args ) { arg . type . _switch ( new Type . SwitchBlock ( ) { @ Override public void _case ( Ref x ) { x . type . _switch ( new RefType . SwitchBlock ( ) { @ Override public void _case ( ClassType x ) { sink . write ( indent + "" + arg . name + "" ) ; sink . write ( indent + "" + arg . name + "" ) ; sink . write ( indent + "" + arg . name + "" + arg . name + "" ) ; } @ Override public void _case ( ArrayType x ) { sink . write ( indent + "" + arg . name + "" + arg . name + "" ) ; } } ) ; } @ Override public void _case ( Primitive x ) { sink . write ( indent + "" + arg . name + "" + arg . name + "" ) ; } } ) ; } } sink . write ( indent + "" ) ; sink . write ( indent + "" ) ; } @ Override public void emitHashCode ( final Sink sink , final String indent , Constructor constructor ) { logger . finest ( "" + constructor . name ) ; sink . write ( indent + "" ) ; sink . write ( indent + "" ) ; if ( constructor . args . isEmpty ( ) ) { sink . write ( indent + "" ) ; } else { sink . write ( indent + "" ) ; sink . write ( indent + "" ) ; for ( final Arg arg : constructor . args ) { arg . type . _switch ( new Type . SwitchBlock ( ) { @ Override public void _case ( Ref x ) { x . type . _switch ( new RefType . SwitchBlock ( ) { @ Override public void _case ( ClassType x ) { sink . write ( indent + "" + arg . name + "" + arg . name + "" ) ; } @ Override public void _case ( ArrayType x ) { sink . write ( indent + "" + arg . name + "" ) ; } } ) ; } @ Override public void _case ( Primitive x ) { x . type . _switch ( new PrimitiveType . SwitchBlockWithDefault ( ) { @ Override public void _case ( BooleanType x ) { sink . write ( indent + "" + arg . name + "" ) ; } @ Override public void _case ( IntType x ) { uncastedHashChunk ( sink , arg ) ; } private void uncastedHashChunk ( final Sink sink , final Arg arg ) { sink . write ( indent + "" + arg . name + "" ) ; } @ Override public void _case ( ByteType x ) { uncastedHashChunk ( sink , arg ) ; } @ Override public void _case ( CharType x ) { uncastedHashChunk ( sink , arg ) ; } @ Override public void _case ( ShortType x ) { uncastedHashChunk ( sink , arg ) ; } @ Override public void _default ( PrimitiveType x ) { sink . write ( indent + "" + arg . name + "" ) ; } } ) ; } } ) ; } sink . write ( indent + "" ) ; } sink . write ( indent + "" ) ; } @ Override public void emitParameterizedTypeName ( Sink sink , List < String > typeArguments ) { if ( ! typeArguments . isEmpty ( ) ) { sink . write ( "" ) ; boolean first = true ; for ( String typeArgument : typeArguments ) { if ( first ) { first = false ; } else { sink . write ( "" ) ; } sink . write ( typeArgument ) ; } sink . write ( ">" ) ; } } private String constructorArg ( Arg arg , boolean withType ) { return withType ? ( ASTPrinter . print ( arg . type ) + "" + arg . name ) : arg . name ; } } package com . pogofish . jadt . emitter ; import com . pogofish . jadt . ast . Doc ; import com . pogofish . jadt . sink . Sink ; import com . pogofish . jadt . sink . SinkFactory ; public class DummyDocEmitter implements DocEmitter { private final Doc testDoc ; private final String className ; public DummyDocEmitter ( Doc testDoc , String className ) { super ( ) ; this . testDoc = testDoc ; this . className = className ; } @ Override public void emit ( SinkFactory factory , Doc doc ) { if ( testDoc != doc ) { throw new RuntimeException ( "" ) ; } final Sink sink = factory . createSink ( className ) ; try { sink . write ( doc . srcInfo ) ; } finally { sink . close ( ) ; } } } package com . pogofish . jadt . emitter ; import java . util . List ; import com . pogofish . jadt . ast . Constructor ; import com . pogofish . jadt . sink . Sink ; public interface ConstructorEmitter { public void constructorFactory ( Sink sink , String dataTypeName , List < String > typeParameters , Constructor constructor ) ; public void constructorDeclaration ( Sink sink , Constructor constructor , String dataTypeName , List < String > typeParameters ) ; } package com . pogofish . jadt ; import java . util . List ; import com . pogofish . jadt . errors . UserError ; import com . pogofish . jadt . printer . UserErrorPrinter ; public class JADTUserErrorsException extends RuntimeException { private static final long serialVersionUID = ; private final List < UserError > errors ; public JADTUserErrorsException ( List < UserError > errors ) { super ( makeString ( errors ) ) ; this . errors = errors ; } private static final String makeString ( List < UserError > errors ) { final StringBuilder builder = new StringBuilder ( ) ; for ( UserError error : errors ) { builder . append ( UserErrorPrinter . print ( error ) ) ; builder . append ( "" ) ; } return builder . toString ( ) ; } public List < UserError > getErrors ( ) { return errors ; } } package com . pogofish . jadt . source ; import java . io . File ; import java . io . FilenameFilter ; import java . util . ArrayList ; import java . util . List ; import com . pogofish . jadt . util . Util ; public class FileSourceFactory implements SourceFactory { private static final FilenameFilter FILTER = new FilenameFilter ( ) { @ Override public boolean accept ( File dir , String name ) { return name . endsWith ( "" ) ; } } ; @ Override public List < FileSource > createSources ( String srcName ) { final File dirOrFile = new File ( srcName ) ; final File [ ] files = dirOrFile . listFiles ( FILTER ) ; if ( files != null ) { final List < FileSource > sources = new ArrayList < FileSource > ( files . length ) ; for ( File file : files ) { sources . add ( new FileSource ( file ) ) ; } return sources ; } else { return Util . list ( new FileSource ( dirOrFile ) ) ; } } } package com . pogofish . jadt . source ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStreamReader ; public class FileSource implements Source { private final File srcFile ; public FileSource ( File srcFile ) { this . srcFile = srcFile ; } @ Override public BufferedReader createReader ( ) { try { return new BufferedReader ( new InputStreamReader ( new FileInputStream ( srcFile ) , "" ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } @ Override public String getSrcInfo ( ) { return srcFile . getAbsolutePath ( ) ; } } package com . pogofish . jadt . source ; import java . io . BufferedReader ; public interface Source { public BufferedReader createReader ( ) ; public String getSrcInfo ( ) ; } package com . pogofish . jadt . source ; import java . io . BufferedReader ; import java . io . StringReader ; public class StringSource implements Source { private final String source ; private final String srcInfo ; public StringSource ( String srcInfo , String source ) { this . srcInfo = srcInfo ; this . source = source ; } @ Override public BufferedReader createReader ( ) { return new BufferedReader ( new StringReader ( source ) ) ; } @ Override public String getSrcInfo ( ) { return srcInfo ; } } package com . pogofish . jadt . source ; import java . util . List ; public interface SourceFactory { public List < ? extends Source > createSources ( String sourceFileName ) ; } package com . pogofish . jadt . source ; import java . util . List ; import com . pogofish . jadt . util . Util ; public class StringSourceFactory implements SourceFactory { private final String source ; public StringSourceFactory ( String source ) { super ( ) ; this . source = source ; } @ Override public List < StringSource > createSources ( String sourceFileName ) { return Util . list ( new StringSource ( sourceFileName , source ) ) ; } } package com . pogofish . jadt . samples . whathow ; import org . junit . Test ; import com . pogofish . jadt . samples . whathow . GenericBinaryTreeUsage ; import com . pogofish . jadt . samples . whathow . data . BinaryTree ; import static com . pogofish . jadt . samples . whathow . data . BinaryTree . * ; import static org . junit . Assert . * ; public class GenericBinaryTreeUsageTest { @ Test public void testMax ( ) { GenericBinaryTreeUsage usage = new GenericBinaryTreeUsage ( ) ; BinaryTree < String > empty = _EmptyTree ( ) ; assertEquals ( null , usage . max ( empty ) ) ; assertEquals ( "" , usage . max ( _Node ( "" , _Node ( "" , empty , empty ) , _Node ( "" , empty , _Node ( "" , empty , empty ) ) ) ) ) ; } @ Test public void testExampleCration ( ) { GenericBinaryTreeUsage usage = new GenericBinaryTreeUsage ( ) ; BinaryTree < String > empty = _EmptyTree ( ) ; assertEquals ( _Node ( "" , _Node ( "" , empty , empty ) , _Node ( "" , empty , _Node ( "" , empty , empty ) ) ) , usage . createExample ( ) ) ; } } package com . pogofish . jadt . samples . whathow ; import static com . pogofish . jadt . samples . whathow . data . Manager . * ; import static com . pogofish . jadt . samples . whathow . data . TPSReportStatus . * ; import static org . junit . Assert . * ; import org . junit . Test ; import com . pogofish . jadt . samples . whathow . TPSReportStatusUsage ; import com . pogofish . jadt . samples . whathow . TPSReportStatusUsage . StatusNotifier ; public class TPSReportStatusUsageTest { private final TPSReportStatusUsage usage = new TPSReportStatusUsage ( ) ; @ Test public void testWithVisitor ( ) { assertFalse ( usage . isApproved ( _Denied ( _Manager ( "" ) ) ) ) ; assertFalse ( usage . isApproved ( _Pending ( ) ) ) ; assertTrue ( usage . isApproved ( _Approved ( _Manager ( "" ) ) ) ) ; } @ Test public void testWithInstanceOf ( ) { assertFalse ( usage . isApprovedV2 ( _Denied ( _Manager ( "" ) ) ) ) ; assertFalse ( usage . isApprovedV2 ( _Pending ( ) ) ) ; assertTrue ( usage . isApprovedV2 ( _Approved ( _Manager ( "" ) ) ) ) ; } @ Test public void testMessage ( ) { assertEquals ( "" , usage . message ( _Approved ( _Manager ( "" ) ) ) ) ; assertEquals ( "" , usage . message ( _Denied ( _Manager ( "" ) ) ) ) ; assertEquals ( "" , usage . message ( _Pending ( ) ) ) ; } private static final class Ref < T > { public T value ; } @ Test public void testNotify ( ) { final Ref < String > result = new Ref < String > ( ) ; final StatusNotifier notifier = new StatusNotifier ( ) { @ Override public void notifyPending ( ) { result . value = "" ; } @ Override public void notifyDenied ( ) { result . value = "" ; } @ Override public void notifyApproved ( ) { result . value = "" ; } } ; usage . notify ( _Approved ( _Manager ( "" ) ) , notifier ) ; assertEquals ( "" , result . value ) ; usage . notify ( _Denied ( _Manager ( "" ) ) , notifier ) ; assertEquals ( "" , result . value ) ; usage . notify ( _Pending ( ) , notifier ) ; assertEquals ( "" , result . value ) ; } @ Test public void testNotifyDenid ( ) { final Ref < String > result = new Ref < String > ( ) ; final StatusNotifier notifier = new StatusNotifier ( ) { @ Override public void notifyPending ( ) { result . value = "" ; } @ Override public void notifyDenied ( ) { result . value = "" ; } @ Override public void notifyApproved ( ) { result . value = "" ; } } ; usage . notifyDenied ( _Approved ( _Manager ( "" ) ) , notifier ) ; assertNull ( result . value ) ; usage . notifyDenied ( _Denied ( _Manager ( "" ) ) , notifier ) ; assertEquals ( "" , result . value ) ; result . value = null ; usage . notifyDenied ( _Pending ( ) , notifier ) ; assertNull ( result . value ) ; } } package com . pogofish . jadt . samples . whathow ; import static com . pogofish . jadt . samples . whathow . data . IntBinaryTree . _EmptyTree ; import static com . pogofish . jadt . samples . whathow . data . IntBinaryTree . _Node ; import static org . junit . Assert . * ; import org . junit . Test ; import com . pogofish . jadt . samples . whathow . IntBinaryTreeUsage ; public class IntBinaryTreeUsageTest { @ Test public void testExampleCreate ( ) { final IntBinaryTreeUsage usage = new IntBinaryTreeUsage ( ) ; assertEquals ( _Node ( , _Node ( , _EmptyTree ( ) , _EmptyTree ( ) ) , _Node ( , _EmptyTree ( ) , _Node ( , _EmptyTree ( ) , _EmptyTree ( ) ) ) ) , usage . createExample ( ) ) ; } @ Test public void testMax ( ) { final IntBinaryTreeUsage usage = new IntBinaryTreeUsage ( ) ; assertEquals ( null , usage . max ( _EmptyTree ( ) ) ) ; assertEquals ( Integer . valueOf ( ) , usage . max ( _Node ( , _Node ( , _EmptyTree ( ) , _EmptyTree ( ) ) , _Node ( , _EmptyTree ( ) , _Node ( , _EmptyTree ( ) , _EmptyTree ( ) ) ) ) ) ) ; } } package com . pogofish . jadt . samples . ast ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . Set ; import org . junit . Test ; import com . pogofish . jadt . samples . ast . Usage ; import com . pogofish . jadt . samples . ast . data . * ; import static com . pogofish . jadt . samples . ast . data . Arg . _Arg ; import static com . pogofish . jadt . samples . ast . data . Expression . * ; import static com . pogofish . jadt . samples . ast . data . Function . * ; import static com . pogofish . jadt . samples . ast . data . Statement . * ; import static com . pogofish . jadt . samples . ast . data . Type . * ; import static java . util . Arrays . asList ; import static org . junit . Assert . * ; public class UsageTest { static final Usage usage = new Usage ( ) ; @ Test public void testSampleFunction ( ) { final Function expectedFunction = _Function ( _Int ( ) , "" , asList ( _Arg ( _Int ( ) , "" ) , _Arg ( _Int ( ) , "" ) ) , asList ( _Return ( _Add ( _Variable ( "" ) , _Variable ( "" ) ) ) ) ) ; assertEquals ( expectedFunction , usage . sampleFunction ( ) ) ; } @ Test public void testExpressionLiterals ( ) { final Set < Integer > emptyIntegers = usage . expressionLiterals ( _LongLiteral ( ) ) ; assertTrue ( "" + emptyIntegers , emptyIntegers . isEmpty ( ) ) ; final Set < Integer > twoIntegers = usage . expressionLiterals ( _Add ( _Variable ( "" ) , _Add ( _IntLiteral ( ) , _IntLiteral ( ) ) ) ) ; assertTrue ( "" , twoIntegers . size ( ) == ) ; assertTrue ( "" , twoIntegers . contains ( ) ) ; assertTrue ( "" , twoIntegers . contains ( ) ) ; } @ Test public void testHasReturn ( ) { final List < Statement > noReturn = Arrays . asList ( _Declaration ( _Int ( ) , "" , _IntLiteral ( ) ) , _Assignment ( "" , _IntLiteral ( ) ) ) ; assertFalse ( "" , usage . hasReturn ( noReturn ) ) ; final List < Statement > hasReturn = new ArrayList < Statement > ( noReturn ) ; hasReturn . add ( _Return ( _LongLiteral ( ) ) ) ; assertTrue ( "" , usage . hasReturn ( hasReturn ) ) ; } } package com . pogofish . jadt . samples . visitor ; import static org . junit . Assert . assertEquals ; import java . io . PrintWriter ; import java . io . StringWriter ; import org . junit . Test ; public class ColorExamplesTest { @ Test public void test ( ) { check ( new Red ( ) , "" ) ; check ( new Green ( ) , "" ) ; check ( new Blue ( ) , "" ) ; } private void check ( Color color , String string ) { final ColorExamples usage = new ColorExamples ( ) ; final StringWriter writer = new StringWriter ( ) ; final PrintWriter printWriter = new PrintWriter ( writer ) ; usage . printString ( color , printWriter ) ; assertEquals ( string , writer . toString ( ) ) ; } } package com . pogofish . jadt . samples . visitor ; import static org . junit . Assert . assertEquals ; import java . io . PrintWriter ; import java . io . StringWriter ; import org . junit . Test ; public class ColorEnumExamplesTest { @ Test public void test ( ) { check ( ColorEnum . Red , "" ) ; check ( ColorEnum . Green , "" ) ; check ( ColorEnum . Blue , "" ) ; } private void check ( ColorEnum color , String string ) { final ColorEnumExamples usage = new ColorEnumExamples ( ) ; final StringWriter writer = new StringWriter ( ) ; final PrintWriter printWriter = new PrintWriter ( writer ) ; usage . printString ( color , printWriter ) ; assertEquals ( string , writer . toString ( ) ) ; } } package com . pogofish . jadt . samples . whathow ; import com . pogofish . jadt . samples . whathow . data . BinaryTree ; import com . pogofish . jadt . samples . whathow . data . BinaryTree . * ; import static com . pogofish . jadt . samples . whathow . data . BinaryTree . * ; public class GenericBinaryTreeUsage { public BinaryTree < String > createExample ( ) { BinaryTree < String > empty = BinaryTree . < String > _EmptyTree ( ) ; return _Node ( "" , _Node ( "" , empty , empty ) , _Node ( "" , empty , _Node ( "" , empty , empty ) ) ) ; } public String max ( BinaryTree < String > tree ) { return tree . match ( new BinaryTree . MatchBlock < String , String > ( ) { @ Override public String _case ( Node < String > x ) { final String maxLeft = max ( x . left ) ; final String maxRight = max ( x . right ) ; return maxString ( maxString ( maxLeft , maxRight ) , x . value ) ; } @ Override public String _case ( EmptyTree < String > x ) { return null ; } } ) ; } private String maxString ( String l , String r ) { return l == null ? r : ( r == null ? l : ( l . compareTo ( r ) >= ? l : r ) ) ; } } package com . pogofish . jadt . samples . whathow ; import com . pogofish . jadt . samples . whathow . data . IntBinaryTree ; import com . pogofish . jadt . samples . whathow . data . IntBinaryTree . * ; import static com . pogofish . jadt . samples . whathow . data . IntBinaryTree . * ; public class IntBinaryTreeUsage { public IntBinaryTree createExample ( ) { IntBinaryTree tree = _Node ( , _Node ( , _EmptyTree ( ) , _EmptyTree ( ) ) , _Node ( , _EmptyTree ( ) , _Node ( , _EmptyTree ( ) , _EmptyTree ( ) ) ) ) ; return tree ; } public Integer max ( IntBinaryTree tree ) { return tree . match ( new IntBinaryTree . MatchBlock < Integer > ( ) { @ Override public Integer _case ( Node x ) { final Integer maxLeft = max ( x . left ) ; final int l = maxLeft == null ? Integer . MIN_VALUE : maxLeft ; final Integer maxRight = max ( x . right ) ; final int r = maxRight == null ? Integer . MIN_VALUE : maxRight ; return Math . max ( Math . max ( l , r ) , x . value ) ; } @ Override public Integer _case ( EmptyTree x ) { return null ; } } ) ; } } package com . pogofish . jadt . samples . whathow ; import com . pogofish . jadt . samples . whathow . data . TPSReportStatus ; import com . pogofish . jadt . samples . whathow . data . TPSReportStatus . * ; public class TPSReportStatusUsage { public boolean isApproved ( TPSReportStatus status ) { return status . match ( new TPSReportStatus . MatchBlockWithDefault < Boolean > ( ) { @ Override public Boolean _case ( Approved x ) { return true ; } @ Override protected Boolean _default ( TPSReportStatus x ) { return false ; } } ) ; } public String message ( TPSReportStatus status ) { return status . match ( new TPSReportStatus . MatchBlock < String > ( ) { @ Override public String _case ( Pending x ) { return "" ; } @ Override public String _case ( Approved x ) { return "" + x . approver ; } @ Override public String _case ( Denied x ) { return "" + x . rejector ; } } ) ; } public void notify ( TPSReportStatus status , final StatusNotifier notifier ) { status . _switch ( new TPSReportStatus . SwitchBlock ( ) { @ Override public void _case ( Denied x ) { notifier . notifyDenied ( ) ; } @ Override public void _case ( Approved x ) { notifier . notifyApproved ( ) ; } @ Override public void _case ( Pending x ) { notifier . notifyPending ( ) ; } } ) ; } public void notifyDenied ( TPSReportStatus status , final StatusNotifier notifier ) { status . _switch ( new SwitchBlockWithDefault ( ) { @ Override public void _case ( Denied x ) { notifier . notifyDenied ( ) ; } @ Override protected void _default ( TPSReportStatus x ) { } } ) ; } public boolean isApprovedV2 ( TPSReportStatus status ) { return status instanceof TPSReportStatus . Approved ; } public static interface StatusNotifier { void notifyApproved ( ) ; void notifyPending ( ) ; void notifyDenied ( ) ; } } package com . pogofish . jadt . samples . ast ; import static com . pogofish . jadt . samples . ast . data . Arg . * ; import static com . pogofish . jadt . samples . ast . data . Expression . * ; import static com . pogofish . jadt . samples . ast . data . Function . * ; import static com . pogofish . jadt . samples . ast . data . Statement . * ; import static com . pogofish . jadt . samples . ast . data . Type . * ; import static java . util . Arrays . asList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import com . pogofish . jadt . samples . ast . data . * ; public class Usage { public Function sampleFunction ( ) { Function sampleFunction = _Function ( _Int ( ) , "" , asList ( _Arg ( _Int ( ) , "" ) , _Arg ( _Int ( ) , "" ) ) , asList ( _Return ( _Add ( _Variable ( "" ) , _Variable ( "" ) ) ) ) ) ; return sampleFunction ; } public Set < Integer > expressionLiterals ( Expression expression ) { return expression . match ( new Expression . MatchBlock < Set < Integer > > ( ) { @ Override public Set < Integer > _case ( Add x ) { final Set < Integer > results = expressionLiterals ( x . left ) ; results . addAll ( expressionLiterals ( x . right ) ) ; return results ; } @ Override public Set < Integer > _case ( Variable x ) { return new HashSet < Integer > ( ) ; } @ Override public Set < Integer > _case ( IntLiteral x ) { return new HashSet < Integer > ( asList ( x . value ) ) ; } @ Override public Set < Integer > _case ( LongLiteral x ) { return new HashSet < Integer > ( ) ; } } ) ; } public boolean hasReturn ( List < Statement > statements ) { boolean hasReturn = false ; for ( Statement statement : statements ) { hasReturn = hasReturn || statement . match ( new Statement . MatchBlockWithDefault < Boolean > ( ) { @ Override public Boolean _case ( Return x ) { return true ; } @ Override public Boolean _default ( Statement x ) { return false ; } } ) ; } return hasReturn ; } } package com . pogofish . jadt . samples . visitor ; public class Red implements Color { @ Override public void _switch ( ColorSwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } } package com . pogofish . jadt . samples . visitor ; public interface Color { public void _switch ( ColorSwitchBlock switchBlock ) ; } package com . pogofish . jadt . samples . visitor ; public class Blue implements Color { @ Override public void _switch ( ColorSwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } } package com . pogofish . jadt . samples . visitor ; import java . io . PrintWriter ; public class ColorExamples { public void printString ( Color color , final PrintWriter writer ) { color . _switch ( new ColorSwitchBlock ( ) { @ Override public void _case ( Red x ) { writer . print ( "" ) ; } @ Override public void _case ( Green x ) { writer . print ( "" ) ; } @ Override public void _case ( Blue x ) { writer . print ( "" ) ; } } ) ; } } package com . pogofish . jadt . samples . visitor ; public interface ColorSwitchBlock { public void _case ( Red x ) ; public void _case ( Blue x ) ; public void _case ( Green x ) ; } package com . pogofish . jadt . samples . visitor ; import java . io . PrintWriter ; public class ColorEnumExamples { public void printString ( ColorEnum color , PrintWriter writer ) { switch ( color ) { case Red : writer . print ( "" ) ; break ; case Green : writer . print ( "" ) ; break ; case Blue : writer . print ( "" ) ; break ; } } } package com . pogofish . jadt . samples . visitor ; public enum ColorEnum { Red , Green , Blue ; } package com . pogofish . jadt . samples . visitor ; public class Green implements Color { @ Override public void _switch ( ColorSwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } } package com . pogofish . jadt . samples . comments . data ; import java . util . * ; public abstract class CommentStyle1 { private CommentStyle1 ( ) { } public static final CommentStyle1 _Foo ( int arg1 , int arg2 ) { return new Foo ( arg1 , arg2 ) ; } private static final CommentStyle1 _Bar = new Bar ( ) ; public static final CommentStyle1 _Bar ( ) { return _Bar ; } public static interface MatchBlock < ResultType > { ResultType _case ( Foo x ) ; ResultType _case ( Bar x ) ; } public static abstract class MatchBlockWithDefault < ResultType > implements MatchBlock < ResultType > { @ Override public ResultType _case ( Foo x ) { return _default ( x ) ; } @ Override public ResultType _case ( Bar x ) { return _default ( x ) ; } protected abstract ResultType _default ( CommentStyle1 x ) ; } public static interface SwitchBlock { void _case ( Foo x ) ; void _case ( Bar x ) ; } public static abstract class SwitchBlockWithDefault implements SwitchBlock { @ Override public void _case ( Foo x ) { _default ( x ) ; } @ Override public void _case ( Bar x ) { _default ( x ) ; } protected abstract void _default ( CommentStyle1 x ) ; } public static final class Foo extends CommentStyle1 { public int arg1 ; public int arg2 ; public Foo ( int arg1 , int arg2 ) { this . arg1 = arg1 ; this . arg2 = arg2 ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + arg1 ; result = prime * result + arg2 ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Foo other = ( Foo ) obj ; if ( arg1 != other . arg1 ) return false ; if ( arg2 != other . arg2 ) return false ; return true ; } @ Override public String toString ( ) { return "" + arg1 + "" + arg2 + "" ; } } public static final class Bar extends CommentStyle1 { public Bar ( ) { } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock switchBlock ) ; } package com . pogofish . jadt . samples . comments . data ; import java . util . * ; public abstract class CommentStyle2 { private CommentStyle2 ( ) { } public static final CommentStyle2 _Foo ( int arg1 , int arg2 ) { return new Foo ( arg1 , arg2 ) ; } private static final CommentStyle2 _Bar = new Bar ( ) ; public static final CommentStyle2 _Bar ( ) { return _Bar ; } public static interface MatchBlock < ResultType > { ResultType _case ( Foo x ) ; ResultType _case ( Bar x ) ; } public static abstract class MatchBlockWithDefault < ResultType > implements MatchBlock < ResultType > { @ Override public ResultType _case ( Foo x ) { return _default ( x ) ; } @ Override public ResultType _case ( Bar x ) { return _default ( x ) ; } protected abstract ResultType _default ( CommentStyle2 x ) ; } public static interface SwitchBlock { void _case ( Foo x ) ; void _case ( Bar x ) ; } public static abstract class SwitchBlockWithDefault implements SwitchBlock { @ Override public void _case ( Foo x ) { _default ( x ) ; } @ Override public void _case ( Bar x ) { _default ( x ) ; } protected abstract void _default ( CommentStyle2 x ) ; } public static final class Foo extends CommentStyle2 { public int arg1 ; public int arg2 ; public Foo ( int arg1 , int arg2 ) { this . arg1 = arg1 ; this . arg2 = arg2 ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + arg1 ; result = prime * result + arg2 ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Foo other = ( Foo ) obj ; if ( arg1 != other . arg1 ) return false ; if ( arg2 != other . arg2 ) return false ; return true ; } @ Override public String toString ( ) { return "" + arg1 + "" + arg2 + "" ; } } public static final class Bar extends CommentStyle2 { public Bar ( ) { } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock switchBlock ) ; } package com . pogofish . jadt . samples . whathow . data ; public abstract class IntBinaryTree { private IntBinaryTree ( ) { } public static final IntBinaryTree _Node ( int value , IntBinaryTree left , IntBinaryTree right ) { return new Node ( value , left , right ) ; } private static final IntBinaryTree _EmptyTree = new EmptyTree ( ) ; public static final IntBinaryTree _EmptyTree ( ) { return _EmptyTree ; } public static interface MatchBlock < ResultType > { ResultType _case ( Node x ) ; ResultType _case ( EmptyTree x ) ; } public static abstract class MatchBlockWithDefault < ResultType > implements MatchBlock < ResultType > { @ Override public ResultType _case ( Node x ) { return _default ( x ) ; } @ Override public ResultType _case ( EmptyTree x ) { return _default ( x ) ; } protected abstract ResultType _default ( IntBinaryTree x ) ; } public static interface SwitchBlock { void _case ( Node x ) ; void _case ( EmptyTree x ) ; } public static abstract class SwitchBlockWithDefault implements SwitchBlock { @ Override public void _case ( Node x ) { _default ( x ) ; } @ Override public void _case ( EmptyTree x ) { _default ( x ) ; } protected abstract void _default ( IntBinaryTree x ) ; } public static final class Node extends IntBinaryTree { public int value ; public IntBinaryTree left ; public IntBinaryTree right ; public Node ( int value , IntBinaryTree left , IntBinaryTree right ) { this . value = value ; this . left = left ; this . right = right ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + value ; result = prime * result + ( ( left == null ) ? : left . hashCode ( ) ) ; result = prime * result + ( ( right == null ) ? : right . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Node other = ( Node ) obj ; if ( value != other . value ) return false ; if ( left == null ) { if ( other . left != null ) return false ; } else if ( ! left . equals ( other . left ) ) return false ; if ( right == null ) { if ( other . right != null ) return false ; } else if ( ! right . equals ( other . right ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + value + "" + left + "" + right + "" ; } } public static final class EmptyTree extends IntBinaryTree { public EmptyTree ( ) { } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock switchBlock ) ; } package com . pogofish . jadt . samples . whathow . data ; public abstract class TPSReportStatus { private TPSReportStatus ( ) { } private static final TPSReportStatus _Pending = new Pending ( ) ; public static final TPSReportStatus _Pending ( ) { return _Pending ; } public static final TPSReportStatus _Approved ( Manager approver ) { return new Approved ( approver ) ; } public static final TPSReportStatus _Denied ( Manager rejector ) { return new Denied ( rejector ) ; } public static interface MatchBlock < ResultType > { ResultType _case ( Pending x ) ; ResultType _case ( Approved x ) ; ResultType _case ( Denied x ) ; } public static abstract class MatchBlockWithDefault < ResultType > implements MatchBlock < ResultType > { @ Override public ResultType _case ( Pending x ) { return _default ( x ) ; } @ Override public ResultType _case ( Approved x ) { return _default ( x ) ; } @ Override public ResultType _case ( Denied x ) { return _default ( x ) ; } protected abstract ResultType _default ( TPSReportStatus x ) ; } public static interface SwitchBlock { void _case ( Pending x ) ; void _case ( Approved x ) ; void _case ( Denied x ) ; } public static abstract class SwitchBlockWithDefault implements SwitchBlock { @ Override public void _case ( Pending x ) { _default ( x ) ; } @ Override public void _case ( Approved x ) { _default ( x ) ; } @ Override public void _case ( Denied x ) { _default ( x ) ; } protected abstract void _default ( TPSReportStatus x ) ; } public static final class Pending extends TPSReportStatus { public Pending ( ) { } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public static final class Approved extends TPSReportStatus { public final Manager approver ; public Approved ( Manager approver ) { this . approver = approver ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( approver == null ) ? : approver . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Approved other = ( Approved ) obj ; if ( approver == null ) { if ( other . approver != null ) return false ; } else if ( ! approver . equals ( other . approver ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + approver + "" ; } } public static final class Denied extends TPSReportStatus { public final Manager rejector ; public Denied ( Manager rejector ) { this . rejector = rejector ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( rejector == null ) ? : rejector . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Denied other = ( Denied ) obj ; if ( rejector == null ) { if ( other . rejector != null ) return false ; } else if ( ! rejector . equals ( other . rejector ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + rejector + "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock switchBlock ) ; } package com . pogofish . jadt . samples . whathow . data ; public abstract class BinaryTree < T > { private BinaryTree ( ) { } public static final < T > BinaryTree < T > _Node ( T value , BinaryTree < T > left , BinaryTree < T > right ) { return new Node < T > ( value , left , right ) ; } @ SuppressWarnings ( "" ) private static final BinaryTree _EmptyTree = new EmptyTree ( ) ; @ SuppressWarnings ( "" ) public static final < T > BinaryTree < T > _EmptyTree ( ) { return _EmptyTree ; } public static interface MatchBlock < T , ResultType > { ResultType _case ( Node < T > x ) ; ResultType _case ( EmptyTree < T > x ) ; } public static abstract class MatchBlockWithDefault < T , ResultType > implements MatchBlock < T , ResultType > { @ Override public ResultType _case ( Node < T > x ) { return _default ( x ) ; } @ Override public ResultType _case ( EmptyTree < T > x ) { return _default ( x ) ; } protected abstract ResultType _default ( BinaryTree < T > x ) ; } public static interface SwitchBlock < T > { void _case ( Node < T > x ) ; void _case ( EmptyTree < T > x ) ; } public static abstract class SwitchBlockWithDefault < T > implements SwitchBlock < T > { @ Override public void _case ( Node < T > x ) { _default ( x ) ; } @ Override public void _case ( EmptyTree < T > x ) { _default ( x ) ; } protected abstract void _default ( BinaryTree < T > x ) ; } public static final class Node < T > extends BinaryTree < T > { public T value ; public BinaryTree < T > left ; public BinaryTree < T > right ; public Node ( T value , BinaryTree < T > left , BinaryTree < T > right ) { this . value = value ; this . left = left ; this . right = right ; } @ Override public < ResultType > ResultType match ( MatchBlock < T , ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock < T > switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( value == null ) ? : value . hashCode ( ) ) ; result = prime * result + ( ( left == null ) ? : left . hashCode ( ) ) ; result = prime * result + ( ( right == null ) ? : right . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; @ SuppressWarnings ( "" ) Node other = ( Node ) obj ; if ( value == null ) { if ( other . value != null ) return false ; } else if ( ! value . equals ( other . value ) ) return false ; if ( left == null ) { if ( other . left != null ) return false ; } else if ( ! left . equals ( other . left ) ) return false ; if ( right == null ) { if ( other . right != null ) return false ; } else if ( ! right . equals ( other . right ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + value + "" + left + "" + right + "" ; } } public static final class EmptyTree < T > extends BinaryTree < T > { public EmptyTree ( ) { } @ Override public < ResultType > ResultType match ( MatchBlock < T , ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock < T > switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < T , ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock < T > switchBlock ) ; } package com . pogofish . jadt . samples . whathow . data ; public final class Manager { public static final Manager _Manager ( String name ) { return new Manager ( name ) ; } public String name ; public Manager ( String name ) { this . name = name ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Manager other = ( Manager ) obj ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + name + "" ; } } package com . pogofish . jadt . samples . whathow . data ; public abstract class OptionalInt { private OptionalInt ( ) { } public static final OptionalInt _Some ( int value ) { return new Some ( value ) ; } private static final OptionalInt _None = new None ( ) ; public static final OptionalInt _None ( ) { return _None ; } public static interface MatchBlock < ResultType > { ResultType _case ( Some x ) ; ResultType _case ( None x ) ; } public static abstract class MatchBlockWithDefault < ResultType > implements MatchBlock < ResultType > { @ Override public ResultType _case ( Some x ) { return _default ( x ) ; } @ Override public ResultType _case ( None x ) { return _default ( x ) ; } protected abstract ResultType _default ( OptionalInt x ) ; } public static interface SwitchBlock { void _case ( Some x ) ; void _case ( None x ) ; } public static abstract class SwitchBlockWithDefault implements SwitchBlock { @ Override public void _case ( Some x ) { _default ( x ) ; } @ Override public void _case ( None x ) { _default ( x ) ; } protected abstract void _default ( OptionalInt x ) ; } public static final class Some extends OptionalInt { public int value ; public Some ( int value ) { this . value = value ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + value ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Some other = ( Some ) obj ; if ( value != other . value ) return false ; return true ; } @ Override public String toString ( ) { return "" + value + "" ; } } public static final class None extends OptionalInt { public None ( ) { } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock switchBlock ) ; } package com . pogofish . jadt . samples . ast . data ; import java . util . List ; public abstract class Expression { private Expression ( ) { } public static final Expression _Add ( Expression left , Expression right ) { return new Add ( left , right ) ; } public static final Expression _Variable ( String name ) { return new Variable ( name ) ; } public static final Expression _IntLiteral ( int value ) { return new IntLiteral ( value ) ; } public static final Expression _LongLiteral ( long value ) { return new LongLiteral ( value ) ; } public static interface MatchBlock < ResultType > { ResultType _case ( Add x ) ; ResultType _case ( Variable x ) ; ResultType _case ( IntLiteral x ) ; ResultType _case ( LongLiteral x ) ; } public static abstract class MatchBlockWithDefault < ResultType > implements MatchBlock < ResultType > { @ Override public ResultType _case ( Add x ) { return _default ( x ) ; } @ Override public ResultType _case ( Variable x ) { return _default ( x ) ; } @ Override public ResultType _case ( IntLiteral x ) { return _default ( x ) ; } @ Override public ResultType _case ( LongLiteral x ) { return _default ( x ) ; } protected abstract ResultType _default ( Expression x ) ; } public static interface SwitchBlock { void _case ( Add x ) ; void _case ( Variable x ) ; void _case ( IntLiteral x ) ; void _case ( LongLiteral x ) ; } public static abstract class SwitchBlockWithDefault implements SwitchBlock { @ Override public void _case ( Add x ) { _default ( x ) ; } @ Override public void _case ( Variable x ) { _default ( x ) ; } @ Override public void _case ( IntLiteral x ) { _default ( x ) ; } @ Override public void _case ( LongLiteral x ) { _default ( x ) ; } protected abstract void _default ( Expression x ) ; } public static final class Add extends Expression { public final Expression left ; public final Expression right ; public Add ( Expression left , Expression right ) { this . left = left ; this . right = right ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( left == null ) ? : left . hashCode ( ) ) ; result = prime * result + ( ( right == null ) ? : right . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Add other = ( Add ) obj ; if ( left == null ) { if ( other . left != null ) return false ; } else if ( ! left . equals ( other . left ) ) return false ; if ( right == null ) { if ( other . right != null ) return false ; } else if ( ! right . equals ( other . right ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + left + "" + right + "" ; } } public static final class Variable extends Expression { public final String name ; public Variable ( String name ) { this . name = name ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Variable other = ( Variable ) obj ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + name + "" ; } } public static final class IntLiteral extends Expression { public final int value ; public IntLiteral ( int value ) { this . value = value ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + value ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; IntLiteral other = ( IntLiteral ) obj ; if ( value != other . value ) return false ; return true ; } @ Override public String toString ( ) { return "" + value + "" ; } } public static final class LongLiteral extends Expression { public final long value ; public LongLiteral ( long value ) { this . value = value ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( int ) value ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; LongLiteral other = ( LongLiteral ) obj ; if ( value != other . value ) return false ; return true ; } @ Override public String toString ( ) { return "" + value + "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock switchBlock ) ; } package com . pogofish . jadt . samples . ast . data ; import java . util . List ; public abstract class Type { private Type ( ) { } private static final Type _Int = new Int ( ) ; public static final Type _Int ( ) { return _Int ; } private static final Type _Long = new Long ( ) ; public static final Type _Long ( ) { return _Long ; } public static interface MatchBlock < ResultType > { ResultType _case ( Int x ) ; ResultType _case ( Long x ) ; } public static abstract class MatchBlockWithDefault < ResultType > implements MatchBlock < ResultType > { @ Override public ResultType _case ( Int x ) { return _default ( x ) ; } @ Override public ResultType _case ( Long x ) { return _default ( x ) ; } protected abstract ResultType _default ( Type x ) ; } public static interface SwitchBlock { void _case ( Int x ) ; void _case ( Long x ) ; } public static abstract class SwitchBlockWithDefault implements SwitchBlock { @ Override public void _case ( Int x ) { _default ( x ) ; } @ Override public void _case ( Long x ) { _default ( x ) ; } protected abstract void _default ( Type x ) ; } public static final class Int extends Type { public Int ( ) { } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public static final class Long extends Type { public Long ( ) { } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { return ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; return true ; } @ Override public String toString ( ) { return "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock switchBlock ) ; } package com . pogofish . jadt . samples . ast . data ; import java . util . List ; public final class Function { public static final Function _Function ( Type returnType , String name , List < Arg > args , List < Statement > statements ) { return new Function ( returnType , name , args , statements ) ; } public final Type returnType ; public final String name ; public List < Arg > args ; public final List < Statement > statements ; public Function ( Type returnType , String name , List < Arg > args , List < Statement > statements ) { this . returnType = returnType ; this . name = name ; this . args = args ; this . statements = statements ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( returnType == null ) ? : returnType . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; result = prime * result + ( ( args == null ) ? : args . hashCode ( ) ) ; result = prime * result + ( ( statements == null ) ? : statements . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Function other = ( Function ) obj ; if ( returnType == null ) { if ( other . returnType != null ) return false ; } else if ( ! returnType . equals ( other . returnType ) ) return false ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( args == null ) { if ( other . args != null ) return false ; } else if ( ! args . equals ( other . args ) ) return false ; if ( statements == null ) { if ( other . statements != null ) return false ; } else if ( ! statements . equals ( other . statements ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + returnType + "" + name + "" + args + "" + statements + "" ; } } package com . pogofish . jadt . samples . ast . data ; import java . util . List ; public final class Arg { public static final Arg _Arg ( Type type , String name ) { return new Arg ( type , name ) ; } public final Type type ; public final String name ; public Arg ( Type type , String name ) { this . type = type ; this . name = name ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( type == null ) ? : type . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Arg other = ( Arg ) obj ; if ( type == null ) { if ( other . type != null ) return false ; } else if ( ! type . equals ( other . type ) ) return false ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + type + "" + name + "" ; } } package com . pogofish . jadt . samples . ast . data ; import java . util . List ; public abstract class Statement { private Statement ( ) { } public static final Statement _Declaration ( Type type , String name , Expression expression ) { return new Declaration ( type , name , expression ) ; } public static final Statement _Assignment ( String name , Expression expression ) { return new Assignment ( name , expression ) ; } public static final Statement _Return ( Expression expression ) { return new Return ( expression ) ; } public static interface MatchBlock < ResultType > { ResultType _case ( Declaration x ) ; ResultType _case ( Assignment x ) ; ResultType _case ( Return x ) ; } public static abstract class MatchBlockWithDefault < ResultType > implements MatchBlock < ResultType > { @ Override public ResultType _case ( Declaration x ) { return _default ( x ) ; } @ Override public ResultType _case ( Assignment x ) { return _default ( x ) ; } @ Override public ResultType _case ( Return x ) { return _default ( x ) ; } protected abstract ResultType _default ( Statement x ) ; } public static interface SwitchBlock { void _case ( Declaration x ) ; void _case ( Assignment x ) ; void _case ( Return x ) ; } public static abstract class SwitchBlockWithDefault implements SwitchBlock { @ Override public void _case ( Declaration x ) { _default ( x ) ; } @ Override public void _case ( Assignment x ) { _default ( x ) ; } @ Override public void _case ( Return x ) { _default ( x ) ; } protected abstract void _default ( Statement x ) ; } public static final class Declaration extends Statement { public final Type type ; public final String name ; public final Expression expression ; public Declaration ( Type type , String name , Expression expression ) { this . type = type ; this . name = name ; this . expression = expression ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( type == null ) ? : type . hashCode ( ) ) ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; result = prime * result + ( ( expression == null ) ? : expression . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Declaration other = ( Declaration ) obj ; if ( type == null ) { if ( other . type != null ) return false ; } else if ( ! type . equals ( other . type ) ) return false ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( expression == null ) { if ( other . expression != null ) return false ; } else if ( ! expression . equals ( other . expression ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + type + "" + name + "" + expression + "" ; } } public static final class Assignment extends Statement { public final String name ; public final Expression expression ; public Assignment ( String name , Expression expression ) { this . name = name ; this . expression = expression ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( name == null ) ? : name . hashCode ( ) ) ; result = prime * result + ( ( expression == null ) ? : expression . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Assignment other = ( Assignment ) obj ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( expression == null ) { if ( other . expression != null ) return false ; } else if ( ! expression . equals ( other . expression ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + name + "" + expression + "" ; } } public static final class Return extends Statement { public final Expression expression ; public Return ( Expression expression ) { this . expression = expression ; } @ Override public < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) { return matchBlock . _case ( this ) ; } @ Override public void _switch ( SwitchBlock switchBlock ) { switchBlock . _case ( this ) ; } @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + ( ( expression == null ) ? : expression . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Return other = ( Return ) obj ; if ( expression == null ) { if ( other . expression != null ) return false ; } else if ( ! expression . equals ( other . expression ) ) return false ; return true ; } @ Override public String toString ( ) { return "" + expression + "" ; } } public abstract < ResultType > ResultType match ( MatchBlock < ResultType > matchBlock ) ; public abstract void _switch ( SwitchBlock switchBlock ) ; } package com . pogofish . jadt . ant ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . fail ; import java . util . Collections ; import org . apache . tools . ant . BuildException ; import org . junit . Test ; import com . pogofish . jadt . JADT ; import com . pogofish . jadt . errors . SemanticError ; import com . pogofish . jadt . errors . SyntaxError ; import com . pogofish . jadt . sink . StringSinkFactoryFactory ; public class JADTAntTaskTest { @ Test public void testHappy ( ) { final JADTAntTask antTask = new JADTAntTask ( ) ; final StringSinkFactoryFactory factory = new StringSinkFactoryFactory ( ) ; antTask . jadt = JADT . createDummyJADT ( Collections . < SyntaxError > emptyList ( ) , Collections . < SemanticError > emptyList ( ) , JADT . TEST_SRC_INFO , factory ) ; antTask . setSrcPath ( JADT . TEST_SRC_INFO ) ; antTask . setDestDir ( JADT . TEST_DIR ) ; antTask . execute ( ) ; final String result = factory . results ( ) . get ( JADT . TEST_DIR ) . get ( ) . getResults ( ) . get ( JADT . TEST_CLASS_NAME ) ; assertEquals ( JADT . TEST_SRC_INFO , result ) ; } @ Test public void testException ( ) { final JADTAntTask antTask = new JADTAntTask ( ) ; final StringSinkFactoryFactory factory = new StringSinkFactoryFactory ( ) ; antTask . jadt = JADT . createDummyJADT ( Collections . < SyntaxError > emptyList ( ) , Collections . < SemanticError > singletonList ( SemanticError . _DuplicateConstructor ( "" , "" ) ) , JADT . TEST_SRC_INFO , factory ) ; antTask . setSrcPath ( JADT . TEST_SRC_INFO ) ; antTask . setDestDir ( JADT . TEST_DIR ) ; try { antTask . execute ( ) ; final String result = factory . results ( ) . get ( JADT . TEST_DIR ) . get ( ) . getResults ( ) . get ( JADT . TEST_CLASS_NAME ) ; fail ( "" + result ) ; } catch ( BuildException e ) { } } } package com . pogofish . jadt . ant ; import org . apache . tools . ant . BuildException ; import org . apache . tools . ant . Task ; import com . pogofish . jadt . JADT ; public class JADTAntTask extends Task { JADT jadt = JADT . standardConfigDriver ( ) ; private String srcPath ; private String destDir ; public void setSrcPath ( String srcPath ) { this . srcPath = srcPath ; } public void setDestDir ( String destDir ) { this . destDir = destDir ; } @ Override public void execute ( ) throws BuildException { try { jadt . parseAndEmit ( srcPath , destDir ) ; } catch ( RuntimeException e ) { throw new BuildException ( e ) ; } } } package osgiutils . services ; public abstract class DefaultServiceRunnable < T , R > implements ServiceRunnableFallback < T , R > { private final R defaultReturn ; public DefaultServiceRunnable ( final R defaultReturn ) { this . defaultReturn = defaultReturn ; } public R serviceNotFound ( ) { return defaultReturn ; } } package osgiutils . services ; public interface MultiServiceRunnable < T , R > extends ServiceRunnable < T , R > { } package osgiutils . services ; public interface ServiceRunnable < T , R > { R run ( T service ) ; } package osgiutils . services ; public abstract class SimpleServiceRunnable < T > implements ServiceRunnableFallback < T , Object > { public final Object run ( final T service ) { runWithService ( service ) ; return null ; } public final Object serviceNotFound ( ) { runWithoutService ( ) ; return null ; } protected void runWithoutService ( ) { } protected abstract void runWithService ( T service ) ; } package osgiutils . services ; import java . util . Collection ; import java . util . Collections ; public abstract class DefaultCollectionServiceRunnable < T , R > extends DefaultServiceRunnable < T , Collection < R > > { @ SuppressWarnings ( "" ) public DefaultCollectionServiceRunnable ( ) { super ( Collections . EMPTY_LIST ) ; } } package osgiutils . services ; public interface ServiceRunnableFallback < T , R > extends ServiceRunnable < T , R > { R serviceNotFound ( ) ; } package osgiutils . services ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import org . osgi . framework . BundleContext ; import org . osgi . framework . FrameworkUtil ; import org . osgi . framework . InvalidSyntaxException ; import org . osgi . framework . ServiceReference ; public final class Services { private static BundleContext context = FrameworkUtil . getBundle ( Services . class ) . getBundleContext ( ) ; private Services ( ) { } public static < T , R > R run ( final Class < T > serviceClass , final ServiceRunnable < T , R > runnable ) { return runService ( context . getServiceReference ( serviceClass . getName ( ) ) , runnable ) ; } public static < T , R > Collection < R > runAll ( final Class < T > serviceClass , final ServiceRunnable < T , R > runnable ) { return runAll ( serviceClass , null , runnable ) ; } public static < T , R > Collection < R > runAll ( final Class < T > serviceClass , final String filter , final ServiceRunnable < T , R > runnable ) { try { final ServiceReference [ ] references = context . getServiceReferences ( serviceClass . getName ( ) , filter ) ; if ( references != null ) { final Collection < R > results = new ArrayList < R > ( references . length ) ; for ( final ServiceReference reference : references ) { results . add ( runService ( reference , runnable ) ) ; } return results ; } } catch ( final InvalidSyntaxException e ) { } return Collections . emptyList ( ) ; } private static < T , R > R run ( final T service , final ServiceRunnable < T , R > runnable ) { if ( service != null ) { return runnable . run ( service ) ; } else if ( runnable instanceof ServiceRunnableFallback < ? , ? > ) { return ( ( ServiceRunnableFallback < T , R > ) runnable ) . serviceNotFound ( ) ; } return null ; } @ SuppressWarnings ( "" ) private static < T , R > R runService ( final ServiceReference reference , final ServiceRunnable < T , R > runnable ) { if ( reference != null ) { try { final T service = ( T ) context . getService ( reference ) ; return run ( service , runnable ) ; } finally { context . ungetService ( reference ) ; } } else if ( runnable instanceof ServiceRunnableFallback < ? , ? > ) { return ( ( ServiceRunnableFallback < T , R > ) runnable ) . serviceNotFound ( ) ; } return null ; } } package osgiutils . log ; import org . osgi . service . log . LogService ; import osgiutils . services . Services ; import osgiutils . services . SimpleServiceRunnable ; public final class LogHelper { public static void debug ( final String message , final Object ... args ) { log ( LogService . LOG_DEBUG , null , message , args ) ; } public static void info ( final String message , final Object ... args ) { log ( LogService . LOG_INFO , null , message , args ) ; } public static void warn ( final String message , final Object ... args ) { log ( LogService . LOG_WARNING , null , message , args ) ; } public static void error ( final Throwable t , final String message , final Object ... args ) { log ( LogService . LOG_ERROR , t , message , args ) ; } public static void log ( final int level , final Throwable t , final String message , final Object ... args ) { final String text = String . format ( message , args ) ; Services . run ( LogService . class , new SimpleServiceRunnable < LogService > ( ) { @ Override protected void runWithService ( final LogService service ) { service . log ( level , text , t ) ; } @ Override protected void runWithoutService ( ) { if ( level == LogService . LOG_ERROR ) { if ( t != null ) { t . printStackTrace ( System . err ) ; } else { System . err . println ( text ) ; } } else { System . out . println ( text ) ; } } } ) ; } private LogHelper ( ) { } } package com . sun . phobos . script . util ; import javax . script . * ; import java . lang . reflect . * ; public class InterfaceImplementor { private Invocable engine ; public InterfaceImplementor ( Invocable engine ) { this . engine = engine ; } public class InterfaceImplementorInvocationHandler implements InvocationHandler { private Invocable engine ; private Object thiz ; public InterfaceImplementorInvocationHandler ( Invocable engine , Object thiz ) { this . engine = engine ; this . thiz = thiz ; } public Object invoke ( Object proxy , Method method , Object [ ] args ) throws java . lang . Throwable { args = convertArguments ( method , args ) ; Object result = engine . invokeMethod ( thiz , method . getName ( ) , args ) ; return convertResult ( method , result ) ; } } public < T > T getInterface ( Object thiz , Class < T > iface ) throws ScriptException { if ( iface == null || ! iface . isInterface ( ) ) { throw new IllegalArgumentException ( "" ) ; } return iface . cast ( Proxy . newProxyInstance ( iface . getClassLoader ( ) , new Class [ ] { iface } , new InterfaceImplementorInvocationHandler ( engine , thiz ) ) ) ; } protected Object convertResult ( Method method , Object res ) throws ScriptException { return res ; } protected Object [ ] convertArguments ( Method method , Object [ ] args ) throws ScriptException { return args ; } } package com . sun . phobos . script . util ; import javax . script . * ; public abstract class ScriptEngineFactoryBase implements ScriptEngineFactory { public String getName ( ) { return ( String ) getParameter ( ScriptEngine . NAME ) ; } public String getEngineName ( ) { return ( String ) getParameter ( ScriptEngine . ENGINE ) ; } public String getEngineVersion ( ) { return ( String ) getParameter ( ScriptEngine . ENGINE_VERSION ) ; } public String getLanguageName ( ) { return ( String ) getParameter ( ScriptEngine . LANGUAGE ) ; } public String getLanguageVersion ( ) { return ( String ) getParameter ( ScriptEngine . LANGUAGE_VERSION ) ; } } package com . sun . phobos . script . util ; import javax . script . ScriptException ; public class ExtendedScriptException extends ScriptException { public ExtendedScriptException ( Throwable cause , String message , String fileName , int lineNumber , int columnNumber ) { super ( message , fileName , lineNumber , columnNumber ) ; initCause ( cause ) ; } public ExtendedScriptException ( String s ) { super ( s ) ; } public ExtendedScriptException ( Exception e ) { super ( e ) ; } public ExtendedScriptException ( String message , String fileName , int lineNumber ) { super ( message , fileName , lineNumber ) ; } public ExtendedScriptException ( Throwable cause , String message , String fileName , int lineNumber ) { super ( message , fileName , lineNumber ) ; initCause ( cause ) ; } public ExtendedScriptException ( String message , String fileName , int lineNumber , int columnNumber ) { super ( message , fileName , lineNumber , columnNumber ) ; } } package com . sun . phobos . script . javascript ; import javax . script . * ; import org . mozilla . javascript . * ; import com . sun . phobos . script . util . * ; final class RhinoCompiledScript extends CompiledScript { private RhinoScriptEngine engine ; private Script script ; private final static boolean DEBUG = RhinoScriptEngine . DEBUG ; RhinoCompiledScript ( RhinoScriptEngine engine , Script script ) { this . engine = engine ; this . script = script ; } public Object eval ( ScriptContext context ) throws ScriptException { Object result = null ; Context cx = RhinoScriptEngine . enterContext ( ) ; try { Scriptable scope = engine . getRuntimeScope ( context ) ; Object ret = script . exec ( cx , scope ) ; result = engine . unwrapReturnValue ( ret ) ; } catch ( JavaScriptException jse ) { if ( DEBUG ) jse . printStackTrace ( ) ; int line = ( line = jse . lineNumber ( ) ) == ? - : line ; Object value = jse . getValue ( ) ; String str = ( value != null && value . getClass ( ) . getName ( ) . equals ( "" ) ? value . toString ( ) : jse . toString ( ) ) ; throw new ExtendedScriptException ( jse , str , jse . sourceName ( ) , line ) ; } catch ( RhinoException re ) { if ( DEBUG ) re . printStackTrace ( ) ; int line = ( line = re . lineNumber ( ) ) == ? - : line ; throw new ExtendedScriptException ( re , re . toString ( ) , re . sourceName ( ) , line ) ; } finally { Context . exit ( ) ; } return result ; } public ScriptEngine getEngine ( ) { return engine ; } } package com . sun . phobos . script . javascript ; import org . mozilla . javascript . * ; import javax . script . * ; import java . util . * ; final class ExternalScriptable implements Scriptable { private ScriptContext context ; private Map < Object , Object > indexedProps ; private Scriptable prototype ; private Scriptable parent ; ExternalScriptable ( ScriptContext context ) { this ( context , new HashMap < Object , Object > ( ) ) ; } ExternalScriptable ( ScriptContext context , Map < Object , Object > indexedProps ) { if ( context == null ) { throw new NullPointerException ( "" ) ; } this . context = context ; this . indexedProps = indexedProps ; } ScriptContext getContext ( ) { return context ; } private boolean isEmpty ( String name ) { return name . equals ( "" ) ; } public String getClassName ( ) { return "" ; } public synchronized Object get ( String name , Scriptable start ) { if ( isEmpty ( name ) ) { if ( indexedProps . containsKey ( name ) ) { return indexedProps . get ( name ) ; } else { return NOT_FOUND ; } } else { synchronized ( context ) { int scope = context . getAttributesScope ( name ) ; if ( scope != - ) { Object value = context . getAttribute ( name , scope ) ; return Context . javaToJS ( value , this ) ; } else { return NOT_FOUND ; } } } } public synchronized Object get ( int index , Scriptable start ) { Integer key = index ; if ( indexedProps . containsKey ( index ) ) { return indexedProps . get ( key ) ; } else { return NOT_FOUND ; } } public synchronized boolean has ( String name , Scriptable start ) { if ( isEmpty ( name ) ) { return indexedProps . containsKey ( name ) ; } else { synchronized ( context ) { return context . getAttributesScope ( name ) != - ; } } } public synchronized boolean has ( int index , Scriptable start ) { Integer key = index ; return indexedProps . containsKey ( key ) ; } public void put ( String name , Scriptable start , Object value ) { if ( start == this ) { synchronized ( this ) { if ( isEmpty ( name ) ) { indexedProps . put ( name , value ) ; } else { synchronized ( context ) { int scope = context . getAttributesScope ( name ) ; if ( scope == - ) { scope = ScriptContext . ENGINE_SCOPE ; } context . setAttribute ( name , jsToJava ( value ) , scope ) ; } } } } else { start . put ( name , start , value ) ; } } public void put ( int index , Scriptable start , Object value ) { if ( start == this ) { synchronized ( this ) { indexedProps . put ( index , value ) ; } } else { start . put ( index , start , value ) ; } } public synchronized void delete ( String name ) { if ( isEmpty ( name ) ) { indexedProps . remove ( name ) ; } else { synchronized ( context ) { int scope = context . getAttributesScope ( name ) ; if ( scope != - ) { context . removeAttribute ( name , scope ) ; } } } } public void delete ( int index ) { indexedProps . remove ( index ) ; } public Scriptable getPrototype ( ) { return prototype ; } public void setPrototype ( Scriptable prototype ) { this . prototype = prototype ; } public Scriptable getParentScope ( ) { return parent ; } public void setParentScope ( Scriptable parent ) { this . parent = parent ; } public synchronized Object [ ] getIds ( ) { String [ ] keys = getAllKeys ( ) ; int size = keys . length + indexedProps . size ( ) ; Object [ ] res = new Object [ size ] ; System . arraycopy ( keys , , res , , keys . length ) ; int i = keys . length ; for ( Object index : indexedProps . keySet ( ) ) { res [ i ++ ] = index ; } return res ; } public Object getDefaultValue ( Class < ? > typeHint ) { for ( int i = ; i < ; i ++ ) { boolean tryToString ; if ( typeHint == String . class ) { tryToString = ( i == ) ; } else { tryToString = ( i == ) ; } String methodName ; Object [ ] args ; if ( tryToString ) { methodName = "" ; args = ScriptRuntime . emptyArgs ; } else { methodName = "" ; String hint ; if ( typeHint == null ) { hint = "" ; } else if ( typeHint == String . class ) { hint = "" ; } else if ( typeHint == Scriptable . class ) { hint = "" ; } else if ( typeHint == Function . class ) { hint = "" ; } else if ( typeHint == Boolean . class || typeHint == boolean . class ) { hint = "" ; } else if ( typeHint == Number . class || typeHint == Byte . class || typeHint == byte . class || typeHint == Short . class || typeHint == short . class || typeHint == Integer . class || typeHint == int . class || typeHint == Float . class || typeHint == float . class || typeHint == Double . class || typeHint == double . class ) { hint = "" ; } else { throw Context . reportRuntimeError ( "" + typeHint . toString ( ) ) ; } args = new Object [ ] { hint } ; } Object v = ScriptableObject . getProperty ( this , methodName ) ; if ( ! ( v instanceof Function ) ) continue ; Function fun = ( Function ) v ; Context cx = RhinoScriptEngine . enterContext ( ) ; try { v = fun . call ( cx , fun . getParentScope ( ) , this , args ) ; } finally { Context . exit ( ) ; } if ( v != null ) { if ( ! ( v instanceof Scriptable ) ) { return v ; } if ( typeHint == Scriptable . class || typeHint == Function . class ) { return v ; } if ( tryToString && v instanceof Wrapper ) { Object u = ( ( Wrapper ) v ) . unwrap ( ) ; if ( u instanceof String ) return u ; } } } String arg = ( typeHint == null ) ? "" : typeHint . getName ( ) ; throw Context . reportRuntimeError ( "" + arg ) ; } public boolean hasInstance ( Scriptable instance ) { Scriptable proto = instance . getPrototype ( ) ; while ( proto != null ) { if ( proto . equals ( this ) ) return true ; proto = proto . getPrototype ( ) ; } return false ; } private String [ ] getAllKeys ( ) { ArrayList < String > list = new ArrayList < String > ( ) ; synchronized ( context ) { for ( int scope : context . getScopes ( ) ) { Bindings bindings = context . getBindings ( scope ) ; if ( bindings != null ) { list . ensureCapacity ( bindings . size ( ) ) ; for ( String key : bindings . keySet ( ) ) { list . add ( key ) ; } } } } String [ ] res = new String [ list . size ( ) ] ; list . toArray ( res ) ; return res ; } private Object jsToJava ( Object jsObj ) { if ( jsObj instanceof Wrapper ) { Wrapper njb = ( Wrapper ) jsObj ; if ( njb instanceof NativeJavaClass ) { return njb ; } Object obj = njb . unwrap ( ) ; if ( obj instanceof Number || obj instanceof String || obj instanceof Boolean || obj instanceof Character ) { return njb ; } else { return obj ; } } else { return jsObj ; } } } package com . sun . phobos . script . javascript ; import javax . script . * ; import java . util . * ; import org . mozilla . javascript . * ; import com . sun . phobos . script . util . * ; public class RhinoScriptEngineFactory extends ScriptEngineFactoryBase { public static final String USE_INTERPRETER_SYSTEM_PROPERTY = "" ; private Properties properties ; private boolean initialized ; private ContextFactory . Listener listener ; public RhinoScriptEngineFactory ( ) { } public RhinoScriptEngineFactory ( ContextFactory . Listener listener ) { this . listener = listener ; } public List < String > getExtensions ( ) { return extensions ; } public List < String > getMimeTypes ( ) { return mimeTypes ; } public List < String > getNames ( ) { return names ; } public Object getParameter ( String key ) { if ( key . equals ( ScriptEngine . NAME ) ) { return "" ; } else if ( key . equals ( ScriptEngine . ENGINE ) ) { return "" ; } else if ( key . equals ( ScriptEngine . ENGINE_VERSION ) ) { return "" ; } else if ( key . equals ( ScriptEngine . LANGUAGE ) ) { return "" ; } else if ( key . equals ( ScriptEngine . LANGUAGE_VERSION ) ) { return "" ; } else if ( key . equals ( "" ) ) { return "" ; } else { throw new IllegalArgumentException ( "" ) ; } } public ScriptEngine getScriptEngine ( ) { RhinoScriptEngine ret = new RhinoScriptEngine ( ) ; ret . setEngineFactory ( this ) ; return ret ; } public void initialize ( ) { if ( ! initialized ) { if ( "" . equals ( getProperty ( USE_INTERPRETER_SYSTEM_PROPERTY ) ) ) { if ( ! ContextFactory . hasExplicitGlobal ( ) ) { ContextFactory . initGlobal ( new ContextFactory ( ) { protected Context makeContext ( ) { Context cx = super . makeContext ( ) ; cx . setOptimizationLevel ( - ) ; return cx ; } } ) ; } } if ( listener != null ) { ContextFactory . getGlobal ( ) . addListener ( listener ) ; } initialized = true ; } } public void destroy ( ) { if ( initialized ) { if ( listener != null ) { ContextFactory . getGlobal ( ) . removeListener ( listener ) ; } initialized = false ; } } public void setProperties ( Properties properties ) { this . properties = properties ; } private String getProperty ( String key ) { String value = null ; if ( properties != null ) { value = properties . getProperty ( key ) ; } if ( value == null ) { value = System . getProperty ( key ) ; } return value ; } private String getProperty ( String name , String defaultValue ) { String s = getProperty ( name ) ; return ( s == null ? defaultValue : s ) ; } public String getMethodCallSyntax ( String obj , String method , String ... args ) { String ret = obj + "" + method + "" ; int len = args . length ; if ( len == ) { ret += "" ; return ret ; } for ( int i = ; i < len ; i ++ ) { ret += args [ i ] ; if ( i != len - ) { ret += "" ; } else { ret += "" ; } } return ret ; } public String getOutputStatement ( String toDisplay ) { StringBuilder buf = new StringBuilder ( ) ; int len = toDisplay . length ( ) ; buf . append ( "" ) ; for ( int i = ; i < len ; i ++ ) { char ch = toDisplay . charAt ( i ) ; switch ( ch ) { case '' : case '' : buf . append ( '' ) ; default : buf . append ( ch ) ; break ; } } buf . append ( "" ) ; return buf . toString ( ) ; } public String getProgram ( String ... statements ) { int len = statements . length ; String ret = "" ; for ( int i = ; i < len ; i ++ ) { ret += statements [ i ] + "" ; } return ret ; } public static void main ( String [ ] args ) { RhinoScriptEngineFactory fact = new RhinoScriptEngineFactory ( ) ; System . out . println ( fact . getParameter ( ScriptEngine . ENGINE_VERSION ) ) ; } private static final List < String > names ; private static final List < String > mimeTypes ; private static final List < String > extensions ; static { names = Collections . unmodifiableList ( Arrays . asList ( "" , "" , "" , "" , "" , "" , "" ) ) ; mimeTypes = Collections . unmodifiableList ( Arrays . asList ( "" , "" , "" , "" ) ) ; extensions = Collections . unmodifiableList ( Arrays . asList ( "" ) ) ; } } package com . sun . phobos . script . javascript ; import org . mozilla . javascript . * ; public final class JSAdapter implements Function { private JSAdapter ( Scriptable obj ) { setAdaptee ( obj ) ; } public static void init ( Context cx , Scriptable scope , boolean sealed ) throws RhinoException { JSAdapter obj = new JSAdapter ( cx . newObject ( scope ) ) ; obj . setParentScope ( scope ) ; obj . setPrototype ( getFunctionPrototype ( scope ) ) ; obj . isPrototype = true ; ScriptableObject . defineProperty ( scope , "" , obj , ScriptableObject . DONTENUM ) ; } public String getClassName ( ) { return "" ; } public Object get ( String name , Scriptable start ) { Function func = getAdapteeFunction ( GET_PROP ) ; if ( func != null ) { return call ( func , new Object [ ] { name } ) ; } else { start = getAdaptee ( ) ; return start . get ( name , start ) ; } } public Object get ( int index , Scriptable start ) { Function func = getAdapteeFunction ( GET_PROP ) ; if ( func != null ) { return call ( func , new Object [ ] { new Integer ( index ) } ) ; } else { start = getAdaptee ( ) ; return start . get ( index , start ) ; } } public boolean has ( String name , Scriptable start ) { Function func = getAdapteeFunction ( HAS_PROP ) ; if ( func != null ) { Object res = call ( func , new Object [ ] { name } ) ; return Context . toBoolean ( res ) ; } else { start = getAdaptee ( ) ; return start . has ( name , start ) ; } } public boolean has ( int index , Scriptable start ) { Function func = getAdapteeFunction ( HAS_PROP ) ; if ( func != null ) { Object res = call ( func , new Object [ ] { new Integer ( index ) } ) ; return Context . toBoolean ( res ) ; } else { start = getAdaptee ( ) ; return start . has ( index , start ) ; } } public void put ( String name , Scriptable start , Object value ) { if ( start == this ) { Function func = getAdapteeFunction ( PUT_PROP ) ; if ( func != null ) { call ( func , new Object [ ] { name , value } ) ; } else { start = getAdaptee ( ) ; start . put ( name , start , value ) ; } } else { start . put ( name , start , value ) ; } } public void put ( int index , Scriptable start , Object value ) { if ( start == this ) { Function func = getAdapteeFunction ( PUT_PROP ) ; if ( func != null ) { call ( func , new Object [ ] { new Integer ( index ) , value } ) ; } else { start = getAdaptee ( ) ; start . put ( index , start , value ) ; } } else { start . put ( index , start , value ) ; } } public void delete ( String name ) { Function func = getAdapteeFunction ( DEL_PROP ) ; if ( func != null ) { call ( func , new Object [ ] { name } ) ; } else { getAdaptee ( ) . delete ( name ) ; } } public void delete ( int index ) { Function func = getAdapteeFunction ( DEL_PROP ) ; if ( func != null ) { call ( func , new Object [ ] { new Integer ( index ) } ) ; } else { getAdaptee ( ) . delete ( index ) ; } } public Scriptable getPrototype ( ) { return prototype ; } public void setPrototype ( Scriptable prototype ) { this . prototype = prototype ; } public Scriptable getParentScope ( ) { return parent ; } public void setParentScope ( Scriptable parent ) { this . parent = parent ; } public Object [ ] getIds ( ) { Function func = getAdapteeFunction ( GET_PROPIDS ) ; if ( func != null ) { Object val = call ( func , new Object [ ] ) ; if ( val instanceof NativeArray ) { NativeArray array = ( NativeArray ) val ; Object [ ] res = new Object [ ( int ) array . getLength ( ) ] ; for ( int index = ; index < res . length ; index ++ ) { res [ index ] = mapToId ( array . get ( index , array ) ) ; } return res ; } else if ( val instanceof NativeJavaArray ) { Object tmp = ( ( NativeJavaArray ) val ) . unwrap ( ) ; Object [ ] res ; if ( tmp . getClass ( ) == Object [ ] . class ) { Object [ ] array = ( Object [ ] ) tmp ; res = new Object [ array . length ] ; for ( int index = ; index < array . length ; index ++ ) { res [ index ] = mapToId ( array [ index ] ) ; } } else { res = Context . emptyArgs ; } return res ; } else { return Context . emptyArgs ; } } else { return getAdaptee ( ) . getIds ( ) ; } } public boolean hasInstance ( Scriptable scriptable ) { if ( scriptable instanceof JSAdapter ) { return true ; } else { Scriptable proto = scriptable . getPrototype ( ) ; while ( proto != null ) { if ( proto . equals ( this ) ) return true ; proto = proto . getPrototype ( ) ; } return false ; } } public Object getDefaultValue ( Class < ? > hint ) { return getAdaptee ( ) . getDefaultValue ( hint ) ; } public Object call ( Context cx , Scriptable scope , Scriptable thisObj , Object [ ] args ) throws RhinoException { if ( isPrototype ) { return construct ( cx , scope , args ) ; } else { Scriptable tmp = getAdaptee ( ) ; if ( tmp instanceof Function ) { return ( ( Function ) tmp ) . call ( cx , scope , tmp , args ) ; } else { throw Context . reportRuntimeError ( "" ) ; } } } public Scriptable construct ( Context cx , Scriptable scope , Object [ ] args ) throws RhinoException { if ( isPrototype ) { Scriptable topLevel = ScriptableObject . getTopLevelScope ( scope ) ; JSAdapter newObj ; if ( args . length > ) { newObj = new JSAdapter ( Context . toObject ( args [ ] , topLevel ) ) ; } else { throw Context . reportRuntimeError ( "" ) ; } return newObj ; } else { Scriptable tmp = getAdaptee ( ) ; if ( tmp instanceof Function ) { return ( ( Function ) tmp ) . construct ( cx , scope , args ) ; } else { throw Context . reportRuntimeError ( "" ) ; } } } public Scriptable getAdaptee ( ) { return adaptee ; } public void setAdaptee ( Scriptable adaptee ) { if ( adaptee == null ) { throw new NullPointerException ( "" ) ; } this . adaptee = adaptee ; } private Object mapToId ( Object tmp ) { if ( tmp instanceof Double ) { return new Integer ( ( ( Double ) tmp ) . intValue ( ) ) ; } else { return Context . toString ( tmp ) ; } } private static Scriptable getFunctionPrototype ( Scriptable scope ) { return ScriptableObject . getFunctionPrototype ( scope ) ; } private Function getAdapteeFunction ( String name ) { Object o = ScriptableObject . getProperty ( getAdaptee ( ) , name ) ; return ( o instanceof Function ) ? ( Function ) o : null ; } private Object call ( Function func , Object [ ] args ) { Context cx = Context . getCurrentContext ( ) ; Scriptable thisObj = getAdaptee ( ) ; Scriptable scope = func . getParentScope ( ) ; try { return func . call ( cx , scope , thisObj , args ) ; } catch ( RhinoException re ) { throw Context . reportRuntimeError ( re . getMessage ( ) ) ; } } private Scriptable prototype ; private Scriptable parent ; private Scriptable adaptee ; private boolean isPrototype ; private static final String GET_PROP = "" ; private static final String HAS_PROP = "" ; private static final String PUT_PROP = "" ; private static final String DEL_PROP = "" ; private static final String GET_PROPIDS = "" ; } package com . sun . phobos . script . javascript ; import com . sun . phobos . script . util . * ; import javax . script . * ; import org . mozilla . javascript . * ; import java . lang . reflect . Method ; import java . io . * ; import java . util . * ; public class RhinoScriptEngine extends AbstractScriptEngine implements Invocable , Compilable { public static final boolean DEBUG = false ; private static final String TOPLEVEL_SCRIPT_NAME = "" ; private ScriptableObject topLevel ; private Map < Object , Object > indexedProps ; private ScriptEngineFactory factory ; private InterfaceImplementor implementor ; public RhinoScriptEngine ( ) { Context cx = enterContext ( ) ; try { topLevel = new ImporterTopLevel ( cx , false ) ; new LazilyLoadedCtor ( topLevel , "" , "" , false ) ; String names [ ] = { "" , "" , "" } ; topLevel . defineFunctionProperties ( names , RhinoScriptEngine . class , ScriptableObject . DONTENUM ) ; processAllTopLevelScripts ( cx ) ; } finally { Context . exit ( ) ; } indexedProps = new HashMap < Object , Object > ( ) ; implementor = new InterfaceImplementor ( this ) { protected Object convertResult ( Method method , Object res ) throws ScriptException { Class < ? > desiredType = method . getReturnType ( ) ; if ( desiredType == void . class ) { return null ; } else { return Context . jsToJava ( res , desiredType ) ; } } } ; } public Object eval ( Reader reader , ScriptContext ctxt ) throws ScriptException { Object ret ; Context cx = enterContext ( ) ; try { Scriptable scope = getRuntimeScope ( ctxt ) ; scope . put ( "" , scope , ctxt ) ; String filename = null ; if ( ctxt != null && ctxt . getBindings ( ScriptContext . ENGINE_SCOPE ) != null ) { filename = ( String ) ctxt . getBindings ( ScriptContext . ENGINE_SCOPE ) . get ( ScriptEngine . FILENAME ) ; } if ( filename == null ) { filename = ( String ) get ( ScriptEngine . FILENAME ) ; } filename = filename == null ? "" : filename ; ret = cx . evaluateReader ( scope , preProcessScriptSource ( reader ) , filename , , null ) ; } catch ( JavaScriptException jse ) { if ( DEBUG ) jse . printStackTrace ( ) ; int line = ( line = jse . lineNumber ( ) ) == ? - : line ; Object value = jse . getValue ( ) ; String str = ( value != null && value . getClass ( ) . getName ( ) . equals ( "" ) ? value . toString ( ) : jse . toString ( ) ) ; throw new ExtendedScriptException ( jse , str , jse . sourceName ( ) , line ) ; } catch ( RhinoException re ) { if ( DEBUG ) re . printStackTrace ( ) ; int line = ( line = re . lineNumber ( ) ) == ? - : line ; throw new ExtendedScriptException ( re , re . toString ( ) , re . sourceName ( ) , line ) ; } catch ( IOException ee ) { throw new ScriptException ( ee ) ; } finally { Context . exit ( ) ; } return unwrapReturnValue ( ret ) ; } public Object eval ( String script , ScriptContext ctxt ) throws ScriptException { if ( script == null ) { throw new NullPointerException ( "" ) ; } return eval ( preProcessScriptSource ( new StringReader ( script ) ) , ctxt ) ; } public ScriptEngineFactory getFactory ( ) { if ( factory != null ) { return factory ; } else { return new RhinoScriptEngineFactory ( ) ; } } public Bindings createBindings ( ) { return new SimpleBindings ( ) ; } public Object invokeFunction ( String name , Object ... args ) throws ScriptException , NoSuchMethodException { return invoke ( null , name , args ) ; } public Object invokeMethod ( Object thiz , String name , Object ... args ) throws ScriptException , NoSuchMethodException { if ( thiz == null ) { throw new IllegalArgumentException ( "" ) ; } return invoke ( thiz , name , args ) ; } private Object invoke ( Object thiz , String name , Object ... args ) throws ScriptException , NoSuchMethodException { Context cx = enterContext ( ) ; try { if ( name == null ) { throw new NullPointerException ( "" ) ; } if ( thiz != null && ! ( thiz instanceof Scriptable ) ) { thiz = Context . toObject ( thiz , topLevel ) ; } Scriptable engineScope = getRuntimeScope ( context ) ; Scriptable localScope = ( thiz != null ) ? ( Scriptable ) thiz : engineScope ; Object obj = ScriptableObject . getProperty ( localScope , name ) ; if ( ! ( obj instanceof Function ) ) { throw new NoSuchMethodException ( "" + name ) ; } Function func = ( Function ) obj ; Scriptable scope = func . getParentScope ( ) ; if ( scope == null ) { scope = engineScope ; } Object result = func . call ( cx , scope , localScope , wrapArguments ( args ) ) ; return unwrapReturnValue ( result ) ; } catch ( JavaScriptException jse ) { if ( DEBUG ) jse . printStackTrace ( ) ; int line = ( line = jse . lineNumber ( ) ) == ? - : line ; Object value = jse . getValue ( ) ; String str = ( value != null && value . getClass ( ) . getName ( ) . equals ( "" ) ? value . toString ( ) : jse . toString ( ) ) ; throw new ExtendedScriptException ( jse , str , jse . sourceName ( ) , line ) ; } catch ( RhinoException re ) { if ( DEBUG ) re . printStackTrace ( ) ; int line = ( line = re . lineNumber ( ) ) == ? - : line ; throw new ExtendedScriptException ( re , re . toString ( ) , re . sourceName ( ) , line ) ; } finally { Context . exit ( ) ; } } public < T > T getInterface ( Class < T > clasz ) { try { return implementor . getInterface ( null , clasz ) ; } catch ( ScriptException e ) { return null ; } } public < T > T getInterface ( Object thiz , Class < T > clasz ) { if ( thiz == null ) { throw new IllegalArgumentException ( "" ) ; } try { return implementor . getInterface ( thiz , clasz ) ; } catch ( ScriptException e ) { return null ; } } private static final String printSource = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final Script printScript ; static { Context cx = enterContext ( ) ; try { printScript = cx . compileString ( printSource , "" , , null ) ; } finally { Context . exit ( ) ; } } Scriptable getRuntimeScope ( ScriptContext ctxt ) { if ( ctxt == null ) { throw new NullPointerException ( "" ) ; } Scriptable newScope = new ExternalScriptable ( ctxt , indexedProps ) ; newScope . setPrototype ( topLevel ) ; newScope . put ( "" , newScope , ctxt ) ; Context cx = enterContext ( ) ; try { printScript . exec ( cx , newScope ) ; } finally { Context . exit ( ) ; } return newScope ; } public CompiledScript compile ( String script ) throws ScriptException { return compile ( preProcessScriptSource ( new StringReader ( script ) ) ) ; } public CompiledScript compile ( java . io . Reader script ) throws ScriptException { CompiledScript ret = null ; Context cx = enterContext ( ) ; try { String filename = ( String ) get ( ScriptEngine . FILENAME ) ; if ( filename == null ) { filename = "" ; } Script scr = cx . compileReader ( preProcessScriptSource ( script ) , filename , , null ) ; ret = new RhinoCompiledScript ( this , scr ) ; } catch ( Exception e ) { if ( DEBUG ) e . printStackTrace ( ) ; throw new ScriptException ( e ) ; } finally { Context . exit ( ) ; } return ret ; } static Context enterContext ( ) { return Context . enter ( ) ; } void setEngineFactory ( ScriptEngineFactory fac ) { factory = fac ; } Object [ ] wrapArguments ( Object [ ] args ) { if ( args == null ) { return Context . emptyArgs ; } Object [ ] res = new Object [ args . length ] ; for ( int i = ; i < res . length ; i ++ ) { res [ i ] = Context . javaToJS ( args [ i ] , topLevel ) ; } return res ; } Object unwrapReturnValue ( Object result ) { if ( result instanceof Wrapper ) { result = ( ( Wrapper ) result ) . unwrap ( ) ; } return result instanceof Undefined ? null : result ; } protected Reader preProcessScriptSource ( Reader reader ) throws ScriptException { return reader ; } protected void processAllTopLevelScripts ( Context cx ) { processTopLevelScript ( TOPLEVEL_SCRIPT_NAME , cx ) ; } protected void processTopLevelScript ( String scriptName , Context cx ) { InputStream toplevelScript = this . getClass ( ) . getResourceAsStream ( scriptName ) ; if ( toplevelScript != null ) { Reader reader = new InputStreamReader ( toplevelScript ) ; try { cx . evaluateReader ( topLevel , reader , scriptName , , null ) ; } catch ( Exception e ) { if ( DEBUG ) e . printStackTrace ( ) ; } finally { try { toplevelScript . close ( ) ; } catch ( IOException e ) { } } } } public static Object bindings ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { if ( args . length == ) { Object arg = args [ ] ; if ( arg instanceof Wrapper ) { arg = ( ( Wrapper ) arg ) . unwrap ( ) ; } if ( arg instanceof ExternalScriptable ) { ScriptContext ctx = ( ( ExternalScriptable ) arg ) . getContext ( ) ; Bindings bind = ctx . getBindings ( ScriptContext . ENGINE_SCOPE ) ; return Context . javaToJS ( bind , ScriptableObject . getTopLevelScope ( thisObj ) ) ; } } return Context . getUndefinedValue ( ) ; } public static Object scope ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { if ( args . length == ) { Object arg = args [ ] ; if ( arg instanceof Wrapper ) { arg = ( ( Wrapper ) arg ) . unwrap ( ) ; } if ( arg instanceof Bindings ) { ScriptContext ctx = new SimpleScriptContext ( ) ; ctx . setBindings ( ( Bindings ) arg , ScriptContext . ENGINE_SCOPE ) ; Scriptable res = new ExternalScriptable ( ctx ) ; res . setPrototype ( ScriptableObject . getObjectPrototype ( thisObj ) ) ; res . setParentScope ( ScriptableObject . getTopLevelScope ( thisObj ) ) ; return res ; } } return Context . getUndefinedValue ( ) ; } public static Object sync ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { if ( args . length == && args [ ] instanceof Function ) { return new Synchronizer ( ( Function ) args [ ] ) ; } else { throw Context . reportRuntimeError ( "" ) ; } } public static void main ( String [ ] args ) throws Exception { if ( args . length == ) { System . out . println ( "" ) ; return ; } InputStreamReader r = new InputStreamReader ( new FileInputStream ( args [ ] ) ) ; ScriptEngine engine = new RhinoScriptEngine ( ) ; SimpleScriptContext context = new SimpleScriptContext ( ) ; engine . put ( ScriptEngine . FILENAME , args [ ] ) ; engine . eval ( r , context ) ; context . getWriter ( ) . flush ( ) ; } } package com . sun . tools . hat . internal . model ; public class JavaFloat extends JavaValue { public final float value ; public JavaFloat ( float value ) { this . value = value ; } public String toString ( ) { return Float . toString ( value ) ; } } package com . sun . tools . hat . internal . model ; import com . sun . tools . hat . internal . util . Misc ; public class Root { private final long id ; private final long refererId ; private int index = - ; private final int type ; private final String description ; private JavaHeapObject referer = null ; private StackTrace stackTrace = null ; public final static int INVALID_TYPE = ; public final static int UNKNOWN = ; public final static int SYSTEM_CLASS = ; public final static int NATIVE_LOCAL = ; public final static int NATIVE_STATIC = ; public final static int THREAD_BLOCK = ; public final static int BUSY_MONITOR = ; public final static int JAVA_LOCAL = ; public final static int NATIVE_STACK = ; public final static int JAVA_STATIC = ; public Root ( long id , long refererId , int type , String description ) { this ( id , refererId , type , description , null ) ; } public Root ( long id , long refererId , int type , String description , StackTrace stackTrace ) { this . id = id ; this . refererId = refererId ; this . type = type ; this . description = description ; this . stackTrace = stackTrace ; } public long getId ( ) { return id ; } public String getIdString ( ) { return Misc . toHex ( id ) ; } public String getDescription ( ) { if ( "" . equals ( description ) ) { return getTypeName ( ) + "" ; } else { return description ; } } public int getType ( ) { return type ; } public String getTypeName ( ) { switch ( type ) { case INVALID_TYPE : return "" ; case UNKNOWN : return "" ; case SYSTEM_CLASS : return "" ; case NATIVE_LOCAL : return "" ; case NATIVE_STATIC : return "" ; case THREAD_BLOCK : return "" ; case BUSY_MONITOR : return "" ; case JAVA_LOCAL : return "" ; case NATIVE_STACK : return "" ; case JAVA_STATIC : return "" ; default : return "" ; } } public Root mostInteresting ( Root other ) { if ( other . type > this . type ) { return other ; } else { return this ; } } public JavaHeapObject getReferer ( ) { return referer ; } public StackTrace getStackTrace ( ) { return stackTrace ; } public int getIndex ( ) { return index ; } void resolve ( Snapshot ss ) { if ( refererId != ) { referer = ss . findThing ( refererId ) ; } if ( stackTrace != null ) { stackTrace . resolve ( ss ) ; } } void setIndex ( int i ) { index = i ; } } package com . sun . tools . hat . internal . model ; import com . sun . tools . hat . internal . util . Misc ; public class JavaObjectRef extends JavaThing { private final long id ; public JavaObjectRef ( long id ) { this . id = id ; } public long getId ( ) { return id ; } public boolean isHeapAllocated ( ) { return true ; } public JavaThing dereference ( Snapshot snapshot , JavaField field ) { return dereference ( snapshot , field , true ) ; } public JavaThing dereference ( Snapshot snapshot , JavaField field , boolean verbose ) { if ( field != null && ! field . hasId ( ) ) { return new JavaLong ( id ) ; } if ( id == ) { return snapshot . getNullThing ( ) ; } JavaThing result = snapshot . findThing ( id ) ; if ( result == null ) { if ( ! snapshot . getUnresolvedObjectsOK ( ) && verbose ) { String msg = "" + Misc . toHex ( id ) ; if ( field != null ) { msg += "" + field . getName ( ) + "" + field . getSignature ( ) + "" ; } System . out . println ( msg ) ; } result = new HackJavaValue ( "" + Misc . toHex ( id ) , ) ; } return result ; } public int getSize ( ) { return ; } public String toString ( ) { return "" + Misc . toHex ( id ) ; } } package com . sun . tools . hat . internal . model ; import java . io . IOException ; import com . sun . tools . hat . internal . parser . ReadBuffer ; public class JavaObjectArray extends JavaLazyReadObject { private Object clazz ; public JavaObjectArray ( long classID , long offset ) { super ( offset ) ; this . clazz = makeId ( classID ) ; } public JavaClass getClazz ( ) { return ( JavaClass ) clazz ; } public void resolve ( Snapshot snapshot ) { if ( clazz instanceof JavaClass ) { return ; } long classID = getIdValue ( ( Number ) clazz ) ; if ( snapshot . isNewStyleArrayClass ( ) ) { JavaThing t = snapshot . findThing ( classID ) ; if ( t instanceof JavaClass ) { clazz = t ; } } if ( ! ( clazz instanceof JavaClass ) ) { JavaThing t = snapshot . findThing ( classID ) ; if ( t != null && t instanceof JavaClass ) { JavaClass el = ( JavaClass ) t ; String nm = el . getName ( ) ; if ( ! nm . startsWith ( "" ) ) { nm = "" + el . getName ( ) + "" ; } clazz = snapshot . getArrayClass ( nm ) ; } } if ( ! ( clazz instanceof JavaClass ) ) { clazz = snapshot . getOtherArrayType ( ) ; } ( ( JavaClass ) clazz ) . addInstance ( this ) ; super . resolve ( snapshot ) ; } public JavaThing [ ] getValues ( ) { return getElements ( ) ; } public JavaThing [ ] getElements ( ) { Snapshot snapshot = getClazz ( ) . getSnapshot ( ) ; byte [ ] data = getValue ( ) ; final int idSize = snapshot . getIdentifierSize ( ) ; final int numElements = data . length / idSize ; JavaThing [ ] elements = new JavaThing [ numElements ] ; int index = ; for ( int i = ; i < elements . length ; i ++ ) { long id = objectIdAt ( index , data ) ; index += idSize ; elements [ i ] = snapshot . findThing ( id ) ; } return elements ; } public int compareTo ( JavaThing other ) { if ( other instanceof JavaObjectArray ) { return ; } return super . compareTo ( other ) ; } public int getLength ( ) { return getValueLength ( ) / getClazz ( ) . getIdentifierSize ( ) ; } public void visitReferencedObjects ( JavaHeapObjectVisitor v ) { super . visitReferencedObjects ( v ) ; for ( JavaThing element : getElements ( ) ) { if ( element != null && element instanceof JavaHeapObject ) { v . visit ( ( JavaHeapObject ) element ) ; } } } public String describeReferenceTo ( JavaThing target , Snapshot ss ) { JavaThing [ ] elements = getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { if ( elements [ i ] == target ) { return "" + i + "" + this ; } } return super . describeReferenceTo ( target , ss ) ; } protected final int readValueLength ( ) throws IOException { JavaClass cl = getClazz ( ) ; ReadBuffer buf = cl . getReadBuffer ( ) ; int idSize = cl . getIdentifierSize ( ) ; long offset = getOffset ( ) + idSize + ; int len = buf . getInt ( offset ) ; return len * cl . getIdentifierSize ( ) ; } protected final byte [ ] readValue ( ) throws IOException { JavaClass cl = getClazz ( ) ; ReadBuffer buf = cl . getReadBuffer ( ) ; int idSize = cl . getIdentifierSize ( ) ; long offset = getOffset ( ) + idSize + ; int len = buf . getInt ( offset ) ; if ( len == ) { return Snapshot . EMPTY_BYTE_ARRAY ; } else { byte [ ] res = new byte [ len * idSize ] ; buf . get ( offset + + idSize , res ) ; return res ; } } } package com . sun . tools . hat . internal . model ; abstract public class AbstractJavaHeapObjectVisitor implements JavaHeapObjectVisitor { abstract public void visit ( JavaHeapObject other ) ; public boolean exclude ( JavaClass clazz , JavaField f ) { return false ; } public boolean mightExclude ( ) { return false ; } } package com . sun . tools . hat . internal . model ; public class StackTrace { private final StackFrame [ ] frames ; public StackTrace ( StackFrame [ ] frames ) { this . frames = frames ; } public StackTrace traceForDepth ( int depth ) { if ( depth >= frames . length ) { return this ; } else { StackFrame [ ] f = new StackFrame [ depth ] ; System . arraycopy ( frames , , f , , depth ) ; return new StackTrace ( f ) ; } } public void resolve ( Snapshot snapshot ) { for ( StackFrame frame : frames ) { frame . resolve ( snapshot ) ; } } public StackFrame [ ] getFrames ( ) { return frames ; } } package com . sun . tools . hat . internal . model ; public class HackJavaValue extends JavaValue { private final String value ; private final int size ; public HackJavaValue ( String value , int size ) { this . value = value ; this . size = size ; } public String toString ( ) { return value ; } public int getSize ( ) { return size ; } } package com . sun . tools . hat . internal . model ; public class StackFrame { public final static int LINE_NUMBER_UNKNOWN = - ; public final static int LINE_NUMBER_COMPILED = - ; public final static int LINE_NUMBER_NATIVE = - ; private final String methodName ; private final String methodSignature ; private final String className ; private final String sourceFileName ; private final int lineNumber ; public StackFrame ( String methodName , String methodSignature , String className , String sourceFileName , int lineNumber ) { this . methodName = methodName ; this . methodSignature = methodSignature ; this . className = className ; this . sourceFileName = sourceFileName ; this . lineNumber = lineNumber ; } public void resolve ( Snapshot snapshot ) { } public String getMethodName ( ) { return methodName ; } public String getMethodSignature ( ) { return methodSignature ; } public String getClassName ( ) { return className ; } public String getSourceFileName ( ) { return sourceFileName ; } public String getLineNumber ( ) { switch ( lineNumber ) { case LINE_NUMBER_UNKNOWN : return "" ; case LINE_NUMBER_COMPILED : return "" ; case LINE_NUMBER_NATIVE : return "" ; default : return Integer . toString ( lineNumber , ) ; } } } package com . sun . tools . hat . internal . model ; public interface ReachableExcludes { public boolean isExcluded ( String fieldName ) ; } package com . sun . tools . hat . internal . model ; import java . io . IOException ; import com . sun . tools . hat . internal . parser . ReadBuffer ; public class JavaObject extends JavaLazyReadObject { private Object clazz ; public JavaObject ( long classID , long offset ) { super ( offset ) ; this . clazz = makeId ( classID ) ; } public void resolve ( Snapshot snapshot ) { if ( clazz instanceof JavaClass ) { return ; } if ( clazz instanceof Number ) { long classID = getIdValue ( ( Number ) clazz ) ; clazz = snapshot . findThing ( classID ) ; if ( ! ( clazz instanceof JavaClass ) ) { warn ( "" + Long . toHexString ( classID ) + "" + "" ) ; int length ; ReadBuffer buf = snapshot . getReadBuffer ( ) ; int idSize = snapshot . getIdentifierSize ( ) ; long lenOffset = getOffset ( ) + * idSize + ; try { length = buf . getInt ( lenOffset ) ; } catch ( IOException exp ) { throw new RuntimeException ( exp ) ; } clazz = snapshot . addFakeInstanceClass ( classID , length ) ; } } else { throw new InternalError ( "" ) ; } JavaClass cl = ( JavaClass ) clazz ; cl . resolve ( snapshot ) ; parseFields ( getValue ( ) , true ) ; cl . addInstance ( this ) ; super . resolve ( snapshot ) ; } public boolean isSameTypeAs ( JavaThing other ) { if ( ! ( other instanceof JavaObject ) ) { return false ; } JavaObject oo = ( JavaObject ) other ; return getClazz ( ) . equals ( oo . getClazz ( ) ) ; } public JavaClass getClazz ( ) { return ( JavaClass ) clazz ; } public JavaThing [ ] getFields ( ) { return parseFields ( getValue ( ) , false ) ; } public JavaThing getField ( String name ) { JavaThing [ ] flds = getFields ( ) ; JavaField [ ] instFields = getClazz ( ) . getFieldsForInstance ( ) ; for ( int i = ; i < instFields . length ; i ++ ) { if ( instFields [ i ] . getName ( ) . equals ( name ) ) { return flds [ i ] ; } } return null ; } public int compareTo ( JavaThing other ) { if ( other instanceof JavaObject ) { JavaObject oo = ( JavaObject ) other ; return getClazz ( ) . getName ( ) . compareTo ( oo . getClazz ( ) . getName ( ) ) ; } return super . compareTo ( other ) ; } public void visitReferencedObjects ( JavaHeapObjectVisitor v ) { super . visitReferencedObjects ( v ) ; JavaThing [ ] flds = getFields ( ) ; for ( int i = ; i < flds . length ; i ++ ) { if ( flds [ i ] != null ) { if ( v . mightExclude ( ) && v . exclude ( getClazz ( ) . getClassForField ( i ) , getClazz ( ) . getFieldForInstance ( i ) ) ) { } else if ( flds [ i ] instanceof JavaHeapObject ) { v . visit ( ( JavaHeapObject ) flds [ i ] ) ; } } } } public boolean refersOnlyWeaklyTo ( Snapshot ss , JavaThing other ) { if ( ss . getWeakReferenceClass ( ) != null ) { final int referentFieldIndex = ss . getReferentFieldIndex ( ) ; if ( ss . getWeakReferenceClass ( ) . isAssignableFrom ( getClazz ( ) ) ) { JavaThing [ ] flds = getFields ( ) ; for ( int i = ; i < flds . length ; i ++ ) { if ( i != referentFieldIndex && flds [ i ] == other ) { return false ; } } return true ; } } return false ; } public String describeReferenceTo ( JavaThing target , Snapshot ss ) { JavaThing [ ] flds = getFields ( ) ; for ( int i = ; i < flds . length ; i ++ ) { if ( flds [ i ] == target ) { JavaField f = getClazz ( ) . getFieldForInstance ( i ) ; return "" + f . getName ( ) ; } } return super . describeReferenceTo ( target , ss ) ; } public String toString ( ) { if ( getClazz ( ) . isString ( ) ) { JavaThing value = getField ( "" ) ; if ( value instanceof JavaValueArray ) { return ( ( JavaValueArray ) value ) . valueString ( ) ; } else { return "" ; } } else { return super . toString ( ) ; } } protected final int readValueLength ( ) throws IOException { JavaClass cl = getClazz ( ) ; int idSize = cl . getIdentifierSize ( ) ; long lengthOffset = getOffset ( ) + * idSize + ; return cl . getReadBuffer ( ) . getInt ( lengthOffset ) ; } protected final byte [ ] readValue ( ) throws IOException { JavaClass cl = getClazz ( ) ; int idSize = cl . getIdentifierSize ( ) ; ReadBuffer buf = cl . getReadBuffer ( ) ; long offset = getOffset ( ) + * idSize + ; int length = buf . getInt ( offset ) ; if ( length == ) { return Snapshot . EMPTY_BYTE_ARRAY ; } else { byte [ ] res = new byte [ length ] ; buf . get ( offset + , res ) ; return res ; } } private JavaThing [ ] parseFields ( byte [ ] data , boolean verbose ) { JavaClass cl = getClazz ( ) ; int target = cl . getNumFieldsForInstance ( ) ; JavaField [ ] fields = cl . getFields ( ) ; JavaThing [ ] fieldValues = new JavaThing [ target ] ; Snapshot snapshot = cl . getSnapshot ( ) ; int idSize = snapshot . getIdentifierSize ( ) ; int fieldNo = ; target -= fields . length ; JavaClass currClass = cl ; int index = ; for ( int i = ; i < fieldValues . length ; i ++ , fieldNo ++ ) { while ( fieldNo >= fields . length ) { currClass = currClass . getSuperclass ( ) ; fields = currClass . getFields ( ) ; fieldNo = ; target -= fields . length ; } JavaField f = fields [ fieldNo ] ; char sig = f . getSignature ( ) . charAt ( ) ; switch ( sig ) { case '' : case '' : { long id = objectIdAt ( index , data ) ; index += idSize ; JavaObjectRef ref = new JavaObjectRef ( id ) ; fieldValues [ target + fieldNo ] = ref . dereference ( snapshot , f , verbose ) ; break ; } case '' : { byte value = byteAt ( index , data ) ; index ++ ; fieldValues [ target + fieldNo ] = new JavaBoolean ( value != ) ; break ; } case '' : { byte value = byteAt ( index , data ) ; index ++ ; fieldValues [ target + fieldNo ] = new JavaByte ( value ) ; break ; } case '' : { short value = shortAt ( index , data ) ; index += ; fieldValues [ target + fieldNo ] = new JavaShort ( value ) ; break ; } case '' : { char value = charAt ( index , data ) ; index += ; fieldValues [ target + fieldNo ] = new JavaChar ( value ) ; break ; } case '' : { int value = intAt ( index , data ) ; index += ; fieldValues [ target + fieldNo ] = new JavaInt ( value ) ; break ; } case '' : { long value = longAt ( index , data ) ; index += ; fieldValues [ target + fieldNo ] = new JavaLong ( value ) ; break ; } case '' : { float value = floatAt ( index , data ) ; index += ; fieldValues [ target + fieldNo ] = new JavaFloat ( value ) ; break ; } case '' : { double value = doubleAt ( index , data ) ; index += ; fieldValues [ target + fieldNo ] = new JavaDouble ( value ) ; break ; } default : throw new IllegalArgumentException ( "" + sig ) ; } } return fieldValues ; } private void warn ( String msg ) { System . out . println ( "" + msg ) ; } } package com . sun . tools . hat . internal . model ; public class ArrayTypeCodes { public static final int T_BOOLEAN = ; public static final int T_CHAR = ; public static final int T_FLOAT = ; public static final int T_DOUBLE = ; public static final int T_BYTE = ; public static final int T_SHORT = ; public static final int T_INT = ; public static final int T_LONG = ; } package com . sun . tools . hat . internal . model ; import com . google . common . collect . ImmutableSet ; import com . sun . tools . hat . internal . util . Misc ; public abstract class JavaHeapObject extends JavaThing { private ImmutableSet . Builder < JavaHeapObject > builder = ImmutableSet . builder ( ) ; private ImmutableSet < JavaHeapObject > referers ; public abstract JavaClass getClazz ( ) ; public abstract int getSize ( ) ; public abstract long getId ( ) ; public void resolve ( Snapshot snapshot ) { StackTrace trace = snapshot . getSiteTrace ( this ) ; if ( trace != null ) { trace . resolve ( snapshot ) ; } } void setupReferers ( ) { if ( referers == null ) { referers = builder . build ( ) ; builder = null ; } } public String getIdString ( ) { return Misc . toHex ( getId ( ) ) ; } public String toString ( ) { return getClazz ( ) . getName ( ) + "" + getIdString ( ) ; } public StackTrace getAllocatedFrom ( ) { return getClazz ( ) . getSiteTrace ( this ) ; } public boolean isNew ( ) { return getClazz ( ) . isNew ( this ) ; } void setNew ( boolean flag ) { getClazz ( ) . setNew ( this , flag ) ; } public void visitReferencedObjects ( JavaHeapObjectVisitor v ) { v . visit ( getClazz ( ) ) ; } void addReferenceFrom ( JavaHeapObject other ) { builder . add ( other ) ; } void addReferenceFromRoot ( Root r ) { getClazz ( ) . addReferenceFromRoot ( r , this ) ; } public Root getRoot ( ) { return getClazz ( ) . getRoot ( this ) ; } public ImmutableSet < JavaHeapObject > getReferers ( ) { if ( referers == null ) { throw new IllegalStateException ( "" + getIdString ( ) ) ; } return referers ; } public boolean refersOnlyWeaklyTo ( Snapshot ss , JavaThing other ) { return false ; } public String describeReferenceTo ( JavaThing target , Snapshot ss ) { return "" ; } public boolean isHeapAllocated ( ) { return true ; } } package com . sun . tools . hat . internal . model ; public interface JavaHeapObjectVisitor { public void visit ( JavaHeapObject other ) ; public boolean exclude ( JavaClass clazz , JavaField f ) ; public boolean mightExclude ( ) ; } package com . sun . tools . hat . internal . model ; public class JavaShort extends JavaValue { public final short value ; public JavaShort ( short value ) { this . value = value ; } public String toString ( ) { return String . valueOf ( value ) ; } } package com . sun . tools . hat . internal . model ; public class JavaByte extends JavaValue { public final byte value ; public JavaByte ( byte value ) { this . value = value ; } public String toString ( ) { return "" + Integer . toString ( value & , ) ; } } package com . sun . tools . hat . internal . model ; import java . util . Arrays ; import java . util . Comparator ; import java . util . HashSet ; import java . util . Set ; import com . google . common . base . Function ; import com . google . common . collect . ComparisonChain ; import com . google . common . collect . Ordering ; public class ReachableObjects { private enum Sorters implements Function < JavaThing , Comparable < ? > > , Comparator < JavaThing > { BY_SIZE { @ Override public Integer apply ( JavaThing thing ) { return thing . getSize ( ) ; } } ; private final Ordering < JavaThing > ordering ; private Sorters ( ) { this . ordering = Ordering . natural ( ) . onResultOf ( this ) ; } @ Override public int compare ( JavaThing lhs , JavaThing rhs ) { return ordering . compare ( lhs , rhs ) ; } } public ReachableObjects ( JavaHeapObject root , final ReachableExcludes excludes ) { this . root = root ; final Set < JavaHeapObject > bag = new HashSet < JavaHeapObject > ( ) ; final Set < String > fieldsExcluded = new HashSet < String > ( ) ; final Set < String > fieldsUsed = new HashSet < String > ( ) ; JavaHeapObjectVisitor visitor = new AbstractJavaHeapObjectVisitor ( ) { public void visit ( JavaHeapObject t ) { if ( t != null && t . getSize ( ) > && ! bag . contains ( t ) ) { bag . add ( t ) ; t . visitReferencedObjects ( this ) ; } } public boolean mightExclude ( ) { return excludes != null ; } public boolean exclude ( JavaClass clazz , JavaField f ) { if ( excludes == null ) { return false ; } String nm = clazz . getName ( ) + "" + f . getName ( ) ; if ( excludes . isExcluded ( nm ) ) { fieldsExcluded . add ( nm ) ; return true ; } else { fieldsUsed . add ( nm ) ; return false ; } } } ; visitor . visit ( root ) ; bag . remove ( root ) ; JavaThing [ ] things = new JavaThing [ bag . size ( ) ] ; int i = ; for ( JavaHeapObject thing : bag ) { things [ i ++ ] = thing ; } Arrays . sort ( things , new Comparator < JavaThing > ( ) { public int compare ( JavaThing left , JavaThing right ) { return ComparisonChain . start ( ) . compare ( right , left , Sorters . BY_SIZE ) . compare ( left , right ) . result ( ) ; } } ) ; this . reachables = things ; long totalSize = root . getSize ( ) ; for ( JavaThing thing : things ) { totalSize += thing . getSize ( ) ; } this . totalSize = totalSize ; excludedFields = getElements ( fieldsExcluded ) ; usedFields = getElements ( fieldsUsed ) ; } public JavaHeapObject getRoot ( ) { return root ; } public JavaThing [ ] getReachables ( ) { return reachables ; } public long getTotalSize ( ) { return totalSize ; } public String [ ] getExcludedFields ( ) { return excludedFields ; } public String [ ] getUsedFields ( ) { return usedFields ; } private static String [ ] getElements ( Set < String > set ) { String [ ] res = set . toArray ( new String [ set . size ( ) ] ) ; Arrays . sort ( res ) ; return res ; } private final JavaHeapObject root ; private final JavaThing [ ] reachables ; private final String [ ] excludedFields ; private final String [ ] usedFields ; private final long totalSize ; } package com . sun . tools . hat . internal . model ; public abstract class JavaThing implements Comparable < JavaThing > { protected JavaThing ( ) { } public JavaThing dereference ( Snapshot shapshot , JavaField field ) { return this ; } public boolean isSameTypeAs ( JavaThing other ) { return getClass ( ) == other . getClass ( ) ; } abstract public boolean isHeapAllocated ( ) ; abstract public int getSize ( ) ; abstract public String toString ( ) ; public int compareTo ( JavaThing other ) { return toString ( ) . compareTo ( other . toString ( ) ) ; } } package com . sun . tools . hat . internal . model ; public class ReferenceChain { private final JavaHeapObject obj ; private final ReferenceChain next ; public ReferenceChain ( JavaHeapObject obj , ReferenceChain next ) { this . obj = obj ; this . next = next ; } public JavaHeapObject getObj ( ) { return obj ; } public ReferenceChain getNext ( ) { return next ; } public int getDepth ( ) { int count = ; ReferenceChain tmp = next ; while ( tmp != null ) { count ++ ; tmp = tmp . next ; } return count ; } } package com . sun . tools . hat . internal . model ; public class JavaLong extends JavaValue { public final long value ; public JavaLong ( long value ) { this . value = value ; } public String toString ( ) { return Long . toString ( value ) ; } } package com . sun . tools . hat . internal . model ; import static com . sun . tools . hat . internal . model . ArrayTypeCodes . * ; import com . sun . tools . hat . internal . parser . ReadBuffer ; import java . io . IOException ; public class JavaValueArray extends JavaLazyReadObject { private static String arrayTypeName ( byte sig ) { switch ( sig ) { case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; default : throw new IllegalArgumentException ( "" + sig ) ; } } private static int elementSize ( byte type ) { switch ( type ) { case T_BYTE : case T_BOOLEAN : return ; case T_CHAR : case T_SHORT : return ; case T_INT : case T_FLOAT : return ; case T_LONG : case T_DOUBLE : return ; default : throw new IllegalArgumentException ( "" + type ) ; } } protected final int readValueLength ( ) throws IOException { JavaClass cl = getClazz ( ) ; ReadBuffer buf = cl . getReadBuffer ( ) ; int idSize = cl . getIdentifierSize ( ) ; long offset = getOffset ( ) + idSize + ; int len = buf . getInt ( offset ) ; byte type = buf . getByte ( offset + ) ; return len * elementSize ( type ) ; } protected final byte [ ] readValue ( ) throws IOException { JavaClass cl = getClazz ( ) ; ReadBuffer buf = cl . getReadBuffer ( ) ; int idSize = cl . getIdentifierSize ( ) ; long offset = getOffset ( ) + idSize + ; int length = buf . getInt ( offset ) ; byte type = buf . getByte ( offset + ) ; if ( length == ) { return Snapshot . EMPTY_BYTE_ARRAY ; } else { length *= elementSize ( type ) ; byte [ ] res = new byte [ length ] ; buf . get ( offset + , res ) ; return res ; } } private JavaClass clazz ; private int data ; private static final int SIGNATURE_MASK = ; private static final int LENGTH_DIVIDER_MASK = ; private static final int LENGTH_DIVIDER_SHIFT = ; public JavaValueArray ( byte elementSignature , long offset ) { super ( offset ) ; this . data = ( elementSignature & SIGNATURE_MASK ) ; } public JavaClass getClazz ( ) { return clazz ; } public void visitReferencedObjects ( JavaHeapObjectVisitor v ) { super . visitReferencedObjects ( v ) ; } public void resolve ( Snapshot snapshot ) { if ( clazz != null ) { return ; } byte elementSig = getElementType ( ) ; clazz = snapshot . findClass ( arrayTypeName ( elementSig ) ) ; if ( clazz == null ) { clazz = snapshot . getArrayClass ( "" + ( ( char ) elementSig ) ) ; } getClazz ( ) . addInstance ( this ) ; super . resolve ( snapshot ) ; } public int getLength ( ) { int divider = ( data & LENGTH_DIVIDER_MASK ) > > > LENGTH_DIVIDER_SHIFT ; if ( divider == ) { byte elementSignature = getElementType ( ) ; switch ( elementSignature ) { case '' : case '' : divider = ; break ; case '' : case '' : divider = ; break ; case '' : case '' : divider = ; break ; case '' : case '' : divider = ; break ; default : throw new IllegalArgumentException ( "" + elementSignature ) ; } data |= ( divider << LENGTH_DIVIDER_SHIFT ) ; } return ( getValueLength ( ) / divider ) ; } public Object getElements ( ) { final int len = getLength ( ) ; final byte et = getElementType ( ) ; byte [ ] data = getValue ( ) ; int index = ; switch ( et ) { case '' : { boolean [ ] res = new boolean [ len ] ; for ( int i = ; i < len ; i ++ ) { res [ i ] = booleanAt ( index , data ) ; index ++ ; } return res ; } case '' : { byte [ ] res = new byte [ len ] ; for ( int i = ; i < len ; i ++ ) { res [ i ] = byteAt ( index , data ) ; index ++ ; } return res ; } case '' : { char [ ] res = new char [ len ] ; for ( int i = ; i < len ; i ++ ) { res [ i ] = charAt ( index , data ) ; index += ; } return res ; } case '' : { short [ ] res = new short [ len ] ; for ( int i = ; i < len ; i ++ ) { res [ i ] = shortAt ( index , data ) ; index += ; } return res ; } case '' : { int [ ] res = new int [ len ] ; for ( int i = ; i < len ; i ++ ) { res [ i ] = intAt ( index , data ) ; index += ; } return res ; } case '' : { long [ ] res = new long [ len ] ; for ( int i = ; i < len ; i ++ ) { res [ i ] = longAt ( index , data ) ; index += ; } return res ; } case '' : { float [ ] res = new float [ len ] ; for ( int i = ; i < len ; i ++ ) { res [ i ] = floatAt ( index , data ) ; index += ; } return res ; } case '' : { double [ ] res = new double [ len ] ; for ( int i = ; i < len ; i ++ ) { res [ i ] = doubleAt ( index , data ) ; index += ; } return res ; } default : { throw new IllegalArgumentException ( "" ) ; } } } public byte getElementType ( ) { return ( byte ) ( data & SIGNATURE_MASK ) ; } private void checkIndex ( int index ) { if ( index < || index >= getLength ( ) ) { throw new ArrayIndexOutOfBoundsException ( index ) ; } } private void requireType ( char type ) { if ( getElementType ( ) != type ) { throw new IllegalArgumentException ( "" + type ) ; } } public boolean getBooleanAt ( int index ) { checkIndex ( index ) ; requireType ( '' ) ; return booleanAt ( index , getValue ( ) ) ; } public byte getByteAt ( int index ) { checkIndex ( index ) ; requireType ( '' ) ; return byteAt ( index , getValue ( ) ) ; } public char getCharAt ( int index ) { checkIndex ( index ) ; requireType ( '' ) ; return charAt ( index << , getValue ( ) ) ; } public short getShortAt ( int index ) { checkIndex ( index ) ; requireType ( '' ) ; return shortAt ( index << , getValue ( ) ) ; } public int getIntAt ( int index ) { checkIndex ( index ) ; requireType ( '' ) ; return intAt ( index << , getValue ( ) ) ; } public long getLongAt ( int index ) { checkIndex ( index ) ; requireType ( '' ) ; return longAt ( index << , getValue ( ) ) ; } public float getFloatAt ( int index ) { checkIndex ( index ) ; requireType ( '' ) ; return floatAt ( index << , getValue ( ) ) ; } public double getDoubleAt ( int index ) { checkIndex ( index ) ; requireType ( '' ) ; return doubleAt ( index << , getValue ( ) ) ; } public String valueString ( ) { return valueString ( true ) ; } public String valueString ( boolean bigLimit ) { StringBuilder result ; byte [ ] value = getValue ( ) ; int max = value . length ; byte elementSignature = getElementType ( ) ; if ( elementSignature == '' ) { result = new StringBuilder ( ) ; for ( int i = ; i < max ; ) { char val = charAt ( i , value ) ; result . append ( val ) ; i += ; } } else { int limit = ; if ( bigLimit ) { limit = ; } result = new StringBuilder ( "" ) ; int num = ; for ( int i = ; i < max ; ) { if ( num > ) { result . append ( "" ) ; } if ( num >= limit ) { result . append ( "" ) ; break ; } num ++ ; switch ( elementSignature ) { case '' : { boolean val = booleanAt ( i , value ) ; if ( val ) { result . append ( "" ) ; } else { result . append ( "" ) ; } i ++ ; break ; } case '' : { int val = & byteAt ( i , value ) ; result . append ( "" + Integer . toString ( val , ) ) ; i ++ ; break ; } case '' : { short val = shortAt ( i , value ) ; i += ; result . append ( "" + val ) ; break ; } case '' : { int val = intAt ( i , value ) ; i += ; result . append ( "" + val ) ; break ; } case '' : { long val = longAt ( i , value ) ; result . append ( "" + val ) ; i += ; break ; } case '' : { float val = floatAt ( i , value ) ; result . append ( "" + val ) ; i += ; break ; } case '' : { double val = doubleAt ( i , value ) ; result . append ( "" + val ) ; i += ; break ; } default : { throw new IllegalArgumentException ( "" ) ; } } } result . append ( "" ) ; } return result . toString ( ) ; } } package com . sun . tools . hat . internal . model ; import java . io . File ; import java . io . FileInputStream ; import java . io . InputStreamReader ; import java . io . BufferedReader ; import java . io . IOException ; import java . util . HashSet ; import java . util . Set ; public class ReachableExcludesImpl implements ReachableExcludes { private final File excludesFile ; private volatile long lastModified ; private volatile Set < String > methods ; public ReachableExcludesImpl ( File excludesFile ) { this . excludesFile = excludesFile ; readFile ( ) ; } private void readFileIfNeeded ( ) { if ( excludesFile . lastModified ( ) != lastModified ) { synchronized ( this ) { if ( excludesFile . lastModified ( ) != lastModified ) { readFile ( ) ; } } } } private void readFile ( ) { long lm = excludesFile . lastModified ( ) ; Set < String > m = new HashSet < String > ( ) ; try { BufferedReader r = new BufferedReader ( new InputStreamReader ( new FileInputStream ( excludesFile ) ) ) ; String method ; while ( ( method = r . readLine ( ) ) != null ) { m . add ( method ) ; } lastModified = lm ; methods = m ; } catch ( IOException ex ) { System . out . println ( "" + excludesFile + "" + ex ) ; } } public boolean isExcluded ( String fieldName ) { readFileIfNeeded ( ) ; return methods . contains ( fieldName ) ; } } package com . sun . tools . hat . internal . model ; public class JavaField { private final String name ; private final String signature ; public JavaField ( String name , String signature ) { this . name = name ; this . signature = signature ; } public boolean hasId ( ) { char ch = signature . charAt ( ) ; return ( ch == '' || ch == '' ) ; } public String getName ( ) { return name ; } public String getSignature ( ) { return signature ; } } package com . sun . tools . hat . internal . model ; public class JavaInt extends JavaValue { public final int value ; public JavaInt ( int value ) { this . value = value ; } public String toString ( ) { return String . valueOf ( value ) ; } } package com . sun . tools . hat . internal . model ; public class JavaBoolean extends JavaValue { public final boolean value ; public JavaBoolean ( boolean value ) { this . value = value ; } public String toString ( ) { return String . valueOf ( value ) ; } } package com . sun . tools . hat . internal . model ; public class JavaDouble extends JavaValue { public final double value ; public JavaDouble ( double value ) { this . value = value ; } public String toString ( ) { return Double . toString ( value ) ; } } package com . sun . tools . hat . internal . model ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import com . google . common . collect . Iterables ; import com . sun . tools . hat . internal . parser . ReadBuffer ; public class JavaClass extends JavaHeapObject { private final long id ; private final String name ; private JavaThing superclass ; private JavaThing loader ; private JavaThing signers ; private JavaThing protectionDomain ; private final JavaField [ ] fields ; private final JavaStatic [ ] statics ; private final List < JavaClass > subclasses = new ArrayList < JavaClass > ( ) ; private final List < JavaHeapObject > instances = new ArrayList < JavaHeapObject > ( ) ; private Snapshot mySnapshot ; private int instanceSize ; private int totalNumFields ; public JavaClass ( long id , String name , long superclassId , long loaderId , long signersId , long protDomainId , JavaField [ ] fields , JavaStatic [ ] statics , int instanceSize ) { this . id = id ; this . name = name ; this . superclass = new JavaObjectRef ( superclassId ) ; this . loader = new JavaObjectRef ( loaderId ) ; this . signers = new JavaObjectRef ( signersId ) ; this . protectionDomain = new JavaObjectRef ( protDomainId ) ; this . fields = fields ; this . statics = statics ; this . instanceSize = instanceSize ; } public JavaClass ( String name , long superclassId , long loaderId , long signersId , long protDomainId , JavaField [ ] fields , JavaStatic [ ] statics , int instanceSize ) { this ( - , name , superclassId , loaderId , signersId , protDomainId , fields , statics , instanceSize ) ; } public final JavaClass getClazz ( ) { return mySnapshot . getJavaLangClass ( ) ; } public final int getIdentifierSize ( ) { return mySnapshot . getIdentifierSize ( ) ; } public final int getMinimumObjectSize ( ) { return mySnapshot . getMinimumObjectSize ( ) ; } public void resolve ( Snapshot snapshot ) { if ( mySnapshot != null ) { return ; } mySnapshot = snapshot ; resolveSuperclass ( snapshot ) ; if ( superclass != null ) { ( ( JavaClass ) superclass ) . addSubclass ( this ) ; } loader = loader . dereference ( snapshot , null ) ; signers = signers . dereference ( snapshot , null ) ; protectionDomain = protectionDomain . dereference ( snapshot , null ) ; for ( JavaStatic s : statics ) { s . resolve ( this , snapshot ) ; } snapshot . getJavaLangClass ( ) . addInstance ( this ) ; super . resolve ( snapshot ) ; return ; } public void resolveSuperclass ( Snapshot snapshot ) { if ( superclass == null ) { } else { totalNumFields = fields . length ; superclass = superclass . dereference ( snapshot , null ) ; if ( superclass == snapshot . getNullThing ( ) ) { superclass = null ; } else { try { JavaClass sc = ( JavaClass ) superclass ; sc . resolveSuperclass ( snapshot ) ; totalNumFields += sc . totalNumFields ; } catch ( ClassCastException ex ) { System . out . println ( "" + name + "" + superclass ) ; superclass = null ; } } } } public boolean isString ( ) { return mySnapshot . getJavaLangString ( ) == this ; } public boolean isClassLoader ( ) { return mySnapshot . getJavaLangClassLoader ( ) . isAssignableFrom ( this ) ; } public JavaField getField ( int i ) { if ( i < || i >= fields . length ) { throw new IndexOutOfBoundsException ( "" + i + "" + name ) ; } return fields [ i ] ; } public int getNumFieldsForInstance ( ) { return totalNumFields ; } public JavaField getFieldForInstance ( int i ) { if ( superclass != null ) { JavaClass sc = ( JavaClass ) superclass ; if ( i < sc . totalNumFields ) { return sc . getFieldForInstance ( i ) ; } i -= sc . totalNumFields ; } return getField ( i ) ; } public JavaClass getClassForField ( int i ) { if ( superclass != null ) { JavaClass sc = ( JavaClass ) superclass ; if ( i < sc . totalNumFields ) { return sc . getClassForField ( i ) ; } } return this ; } public long getId ( ) { return id ; } public String getName ( ) { return name ; } public boolean isArray ( ) { return name . indexOf ( '' ) != - ; } public Iterable < JavaHeapObject > getInstances ( boolean includeSubclasses ) { if ( includeSubclasses ) { Iterable < JavaHeapObject > res = instances ; for ( JavaClass subclass : subclasses ) { res = Iterables . concat ( res , subclass . getInstances ( true ) ) ; } return res ; } else { return instances ; } } public int getInstancesCount ( boolean includeSubclasses ) { int result = instances . size ( ) ; if ( includeSubclasses ) { for ( JavaClass subclass : subclasses ) { result += subclass . getInstancesCount ( includeSubclasses ) ; } } return result ; } public JavaClass [ ] getSubclasses ( ) { return subclasses . toArray ( new JavaClass [ subclasses . size ( ) ] ) ; } public JavaClass getSuperclass ( ) { return ( JavaClass ) superclass ; } public JavaThing getLoader ( ) { return loader ; } public boolean isBootstrap ( ) { return loader == mySnapshot . getNullThing ( ) ; } public JavaThing getSigners ( ) { return signers ; } public JavaThing getProtectionDomain ( ) { return protectionDomain ; } public JavaField [ ] getFields ( ) { return fields ; } public JavaField [ ] getFieldsForInstance ( ) { List < JavaField > v = new ArrayList < JavaField > ( ) ; addFields ( v ) ; return v . toArray ( new JavaField [ v . size ( ) ] ) ; } public JavaStatic [ ] getStatics ( ) { return statics ; } public JavaThing getStaticField ( String name ) { for ( JavaStatic s : statics ) { if ( s . getField ( ) . getName ( ) . equals ( name ) ) { return s . getValue ( ) ; } } return null ; } public String toString ( ) { return "" + name ; } public int compareTo ( JavaThing other ) { if ( other instanceof JavaClass ) { return name . compareTo ( ( ( JavaClass ) other ) . name ) ; } return super . compareTo ( other ) ; } public boolean isAssignableFrom ( JavaClass other ) { if ( this == other ) { return true ; } else if ( other == null ) { return false ; } else { return isAssignableFrom ( ( JavaClass ) other . superclass ) ; } } public String describeReferenceTo ( JavaThing target , Snapshot ss ) { for ( JavaStatic s : statics ) { JavaField f = s . getField ( ) ; if ( f . hasId ( ) ) { JavaThing other = s . getValue ( ) ; if ( other == target ) { return "" + f . getName ( ) ; } } } return super . describeReferenceTo ( target , ss ) ; } public int getInstanceSize ( ) { return instanceSize + mySnapshot . getMinimumObjectSize ( ) ; } public long getTotalInstanceSize ( ) { int count = instances . size ( ) ; if ( count == || ! isArray ( ) ) { return count * instanceSize ; } long result = ; for ( JavaThing t : instances ) { result += t . getSize ( ) ; } return result ; } public int getSize ( ) { JavaClass cl = mySnapshot . getJavaLangClass ( ) ; if ( cl == null ) { return ; } else { return cl . getInstanceSize ( ) ; } } public void visitReferencedObjects ( JavaHeapObjectVisitor v ) { super . visitReferencedObjects ( v ) ; JavaHeapObject sc = getSuperclass ( ) ; if ( sc != null ) v . visit ( getSuperclass ( ) ) ; JavaThing other ; other = getLoader ( ) ; if ( other instanceof JavaHeapObject ) { v . visit ( ( JavaHeapObject ) other ) ; } other = getSigners ( ) ; if ( other instanceof JavaHeapObject ) { v . visit ( ( JavaHeapObject ) other ) ; } other = getProtectionDomain ( ) ; if ( other instanceof JavaHeapObject ) { v . visit ( ( JavaHeapObject ) other ) ; } for ( JavaStatic s : statics ) { JavaField f = s . getField ( ) ; if ( ! v . exclude ( this , f ) && f . hasId ( ) ) { other = s . getValue ( ) ; if ( other instanceof JavaHeapObject ) { v . visit ( ( JavaHeapObject ) other ) ; } } } } final ReadBuffer getReadBuffer ( ) { return mySnapshot . getReadBuffer ( ) ; } final void setNew ( JavaHeapObject obj , boolean flag ) { mySnapshot . setNew ( obj , flag ) ; } final boolean isNew ( JavaHeapObject obj ) { return mySnapshot . isNew ( obj ) ; } final StackTrace getSiteTrace ( JavaHeapObject obj ) { return mySnapshot . getSiteTrace ( obj ) ; } final void addReferenceFromRoot ( Root root , JavaHeapObject obj ) { mySnapshot . addReferenceFromRoot ( root , obj ) ; } final Root getRoot ( JavaHeapObject obj ) { return mySnapshot . getRoot ( obj ) ; } final Snapshot getSnapshot ( ) { return mySnapshot ; } void addInstance ( JavaHeapObject inst ) { instances . add ( inst ) ; } private void addFields ( List < ? super JavaField > v ) { if ( superclass != null ) { ( ( JavaClass ) superclass ) . addFields ( v ) ; } Collections . addAll ( v , fields ) ; } private void addSubclass ( JavaClass sub ) { subclasses . add ( sub ) ; } } package com . sun . tools . hat . internal . model ; import java . lang . ref . SoftReference ; import java . util . * ; import com . google . common . collect . ImmutableList ; import com . sun . tools . hat . internal . lang . ModelFactory ; import com . sun . tools . hat . internal . lang . ModelFactoryFactory ; import com . sun . tools . hat . internal . parser . ReadBuffer ; import com . sun . tools . hat . internal . util . Misc ; public class Snapshot { public static long SMALL_ID_MASK = ; public static final byte [ ] EMPTY_BYTE_ARRAY = new byte [ ] ; private static final JavaField [ ] EMPTY_FIELD_ARRAY = new JavaField [ ] ; private static final JavaStatic [ ] EMPTY_STATIC_ARRAY = new JavaStatic [ ] ; private final Map < Number , JavaHeapObject > heapObjects = new HashMap < Number , JavaHeapObject > ( ) ; private final Map < Number , JavaClass > fakeClasses = new HashMap < Number , JavaClass > ( ) ; private final List < Root > roots = new ArrayList < Root > ( ) ; private final Map < String , JavaClass > classes = new TreeMap < String , JavaClass > ( ) ; private final Set < JavaHeapObject > newObjects = new HashSet < JavaHeapObject > ( ) ; private final Map < JavaHeapObject , StackTrace > siteTraces = new HashMap < JavaHeapObject , StackTrace > ( ) ; private final Map < JavaHeapObject , Root > rootsMap = new HashMap < JavaHeapObject , Root > ( ) ; private SoftReference < List < JavaHeapObject > > finalizablesCache ; private JavaThing nullThing ; private JavaClass weakReferenceClass ; private int referentFieldIndex ; private JavaClass javaLangClass ; private JavaClass javaLangString ; private JavaClass javaLangClassLoader ; private volatile JavaClass otherArrayType ; private ReachableExcludes reachableExcludes ; private ReadBuffer readBuf ; private boolean hasNewSet ; private boolean unresolvedObjectsOK ; private boolean newStyleArrayClass ; private int identifierSize = ; private int minimumObjectSize ; private volatile ImmutableList < ModelFactory > modelFactories ; public Snapshot ( ReadBuffer buf ) { nullThing = new HackJavaValue ( "" , ) ; readBuf = buf ; } public void setSiteTrace ( JavaHeapObject obj , StackTrace trace ) { if ( trace != null && trace . getFrames ( ) . length != ) { siteTraces . put ( obj , trace ) ; } } public StackTrace getSiteTrace ( JavaHeapObject obj ) { return siteTraces . get ( obj ) ; } public void setNewStyleArrayClass ( boolean value ) { newStyleArrayClass = value ; } public boolean isNewStyleArrayClass ( ) { return newStyleArrayClass ; } public void setIdentifierSize ( int size ) { identifierSize = size ; minimumObjectSize = * size ; } public int getIdentifierSize ( ) { return identifierSize ; } public int getMinimumObjectSize ( ) { return minimumObjectSize ; } public void addHeapObject ( long id , JavaHeapObject ho ) { heapObjects . put ( makeId ( id ) , ho ) ; } public void addRoot ( Root r ) { r . setIndex ( roots . size ( ) ) ; roots . add ( r ) ; } public void addClass ( long id , JavaClass c ) { addHeapObject ( id , c ) ; putInClassesMap ( c ) ; } JavaClass addFakeInstanceClass ( long classID , int instSize ) { String name = "" + Misc . toHex ( classID ) + ">" ; int numInts = instSize / ; int numBytes = instSize % ; JavaField [ ] fields = new JavaField [ numInts + numBytes ] ; int i ; for ( i = ; i < numInts ; i ++ ) { fields [ i ] = new JavaField ( "" + i , "" ) ; } for ( i = ; i < numBytes ; i ++ ) { fields [ i + numInts ] = new JavaField ( "" + i + numInts , "" ) ; } JavaClass c = new JavaClass ( name , , , , , fields , EMPTY_STATIC_ARRAY , instSize ) ; addFakeClass ( makeId ( classID ) , c ) ; return c ; } public boolean getHasNewSet ( ) { return hasNewSet ; } private static final int DOT_LIMIT = ; public void resolve ( boolean calculateRefs ) { System . out . println ( "" + heapObjects . size ( ) + "" ) ; javaLangClass = findClass ( "" ) ; if ( javaLangClass == null ) { System . out . println ( "" ) ; javaLangClass = new JavaClass ( "" , , , , , EMPTY_FIELD_ARRAY , EMPTY_STATIC_ARRAY , ) ; addFakeClass ( javaLangClass ) ; } javaLangString = findClass ( "" ) ; if ( javaLangString == null ) { System . out . println ( "" ) ; javaLangString = new JavaClass ( "" , , , , , EMPTY_FIELD_ARRAY , EMPTY_STATIC_ARRAY , ) ; addFakeClass ( javaLangString ) ; } javaLangClassLoader = findClass ( "" ) ; if ( javaLangClassLoader == null ) { System . out . println ( "" ) ; javaLangClassLoader = new JavaClass ( "" , , , , , EMPTY_FIELD_ARRAY , EMPTY_STATIC_ARRAY , ) ; addFakeClass ( javaLangClassLoader ) ; } for ( JavaHeapObject t : heapObjects . values ( ) ) { if ( t instanceof JavaClass ) { t . resolve ( this ) ; } } for ( JavaHeapObject t : heapObjects . values ( ) ) { if ( ! ( t instanceof JavaClass ) ) { t . resolve ( this ) ; } } heapObjects . putAll ( fakeClasses ) ; fakeClasses . clear ( ) ; weakReferenceClass = findClass ( "" ) ; if ( weakReferenceClass == null ) { weakReferenceClass = findClass ( "" ) ; referentFieldIndex = ; } else { JavaField [ ] fields = weakReferenceClass . getFieldsForInstance ( ) ; for ( int i = ; i < fields . length ; i ++ ) { if ( "" . equals ( fields [ i ] . getName ( ) ) ) { referentFieldIndex = i ; break ; } } } if ( calculateRefs ) { calculateReferencesToObjects ( ) ; System . out . print ( "" ) ; System . out . flush ( ) ; } int count = ; for ( JavaHeapObject t : heapObjects . values ( ) ) { t . setupReferers ( ) ; ++ count ; if ( calculateRefs && count % DOT_LIMIT == ) { System . out . print ( "" ) ; System . out . flush ( ) ; } } if ( calculateRefs ) { System . out . println ( "" ) ; } } private void calculateReferencesToObjects ( ) { System . out . print ( "" + ( heapObjects . size ( ) / DOT_LIMIT ) + "" ) ; System . out . flush ( ) ; int count = ; for ( final JavaHeapObject t : heapObjects . values ( ) ) { t . visitReferencedObjects ( new AbstractJavaHeapObjectVisitor ( ) { @ Override public void visit ( JavaHeapObject other ) { other . addReferenceFrom ( t ) ; } } ) ; ++ count ; if ( count % DOT_LIMIT == ) { System . out . print ( "" ) ; System . out . flush ( ) ; } } System . out . println ( ) ; for ( Root r : roots ) { r . resolve ( this ) ; JavaHeapObject t = findThing ( r . getId ( ) ) ; if ( t != null ) { t . addReferenceFromRoot ( r ) ; } } } public void markNewRelativeTo ( Snapshot baseline ) { hasNewSet = true ; for ( JavaHeapObject t : heapObjects . values ( ) ) { boolean isNew ; long thingID = t . getId ( ) ; if ( thingID == || thingID == - ) { isNew = false ; } else { JavaThing other = baseline . findThing ( t . getId ( ) ) ; if ( other == null ) { isNew = true ; } else { isNew = ! t . isSameTypeAs ( other ) ; } } t . setNew ( isNew ) ; } } public Collection < JavaHeapObject > getThings ( ) { return heapObjects . values ( ) ; } public JavaHeapObject findThing ( long id ) { Number idObj = makeId ( id ) ; JavaHeapObject jho = heapObjects . get ( idObj ) ; return jho != null ? jho : fakeClasses . get ( idObj ) ; } public JavaHeapObject findThing ( String id ) { return findThing ( Misc . parseHex ( id ) ) ; } public JavaClass findClass ( String name ) { if ( name . startsWith ( "" ) ) { return ( JavaClass ) findThing ( name ) ; } else { return classes . get ( name ) ; } } public Collection < JavaClass > getClasses ( ) { return Collections . unmodifiableCollection ( classes . values ( ) ) ; } public JavaClass [ ] getClassesArray ( ) { return classes . values ( ) . toArray ( new JavaClass [ classes . size ( ) ] ) ; } public synchronized Collection < JavaHeapObject > getFinalizerObjects ( ) { if ( finalizablesCache != null ) { List < JavaHeapObject > obj = finalizablesCache . get ( ) ; if ( obj != null ) { return obj ; } } JavaClass clazz = findClass ( "" ) ; JavaObject queue = ( JavaObject ) clazz . getStaticField ( "" ) ; JavaThing tmp = queue . getField ( "" ) ; List < JavaHeapObject > finalizables = new ArrayList < JavaHeapObject > ( ) ; if ( tmp != getNullThing ( ) ) { JavaObject head = ( JavaObject ) tmp ; while ( true ) { JavaHeapObject referent = ( JavaHeapObject ) head . getField ( "" ) ; JavaThing next = head . getField ( "" ) ; if ( next == getNullThing ( ) || next . equals ( head ) ) { break ; } head = ( JavaObject ) next ; finalizables . add ( referent ) ; } } finalizablesCache = new SoftReference < List < JavaHeapObject > > ( finalizables ) ; return finalizables ; } public Collection < Root > getRoots ( ) { return roots ; } public Root [ ] getRootsArray ( ) { return roots . toArray ( new Root [ roots . size ( ) ] ) ; } public Root getRootAt ( int i ) { return roots . get ( i ) ; } public ReferenceChain [ ] rootsetReferencesTo ( JavaHeapObject target , boolean includeWeak ) { Queue < ReferenceChain > fifo = new ArrayDeque < ReferenceChain > ( ) ; Set < JavaHeapObject > visited = new HashSet < JavaHeapObject > ( ) ; List < ReferenceChain > result = new ArrayList < ReferenceChain > ( ) ; visited . add ( target ) ; fifo . add ( new ReferenceChain ( target , null ) ) ; while ( ! fifo . isEmpty ( ) ) { ReferenceChain chain = fifo . remove ( ) ; JavaHeapObject curr = chain . getObj ( ) ; if ( curr . getRoot ( ) != null ) { result . add ( chain ) ; } for ( JavaHeapObject t : curr . getReferers ( ) ) { if ( t != null && ! visited . contains ( t ) ) { if ( includeWeak || ! t . refersOnlyWeaklyTo ( this , curr ) ) { visited . add ( t ) ; fifo . add ( new ReferenceChain ( t , chain ) ) ; } } } } return result . toArray ( new ReferenceChain [ result . size ( ) ] ) ; } public boolean getUnresolvedObjectsOK ( ) { return unresolvedObjectsOK ; } public void setUnresolvedObjectsOK ( boolean v ) { unresolvedObjectsOK = v ; } public JavaClass getWeakReferenceClass ( ) { return weakReferenceClass ; } public int getReferentFieldIndex ( ) { return referentFieldIndex ; } public JavaThing getNullThing ( ) { return nullThing ; } public void setReachableExcludes ( ReachableExcludes e ) { reachableExcludes = e ; } public ReachableExcludes getReachableExcludes ( ) { return reachableExcludes ; } void addReferenceFromRoot ( Root r , JavaHeapObject obj ) { Root root = rootsMap . get ( obj ) ; if ( root == null ) { rootsMap . put ( obj , r ) ; } else { rootsMap . put ( obj , root . mostInteresting ( r ) ) ; } } Root getRoot ( JavaHeapObject obj ) { return rootsMap . get ( obj ) ; } JavaClass getJavaLangClass ( ) { return javaLangClass ; } JavaClass getJavaLangString ( ) { return javaLangString ; } JavaClass getJavaLangClassLoader ( ) { return javaLangClassLoader ; } JavaClass getOtherArrayType ( ) { if ( otherArrayType == null ) { synchronized ( this ) { if ( otherArrayType == null ) { addFakeClass ( new JavaClass ( "" , , , , , EMPTY_FIELD_ARRAY , EMPTY_STATIC_ARRAY , ) ) ; otherArrayType = findClass ( "" ) ; } } } return otherArrayType ; } JavaClass getArrayClass ( String elementSignature ) { JavaClass clazz ; synchronized ( classes ) { clazz = findClass ( "" + elementSignature ) ; if ( clazz == null ) { clazz = new JavaClass ( "" + elementSignature , , , , , EMPTY_FIELD_ARRAY , EMPTY_STATIC_ARRAY , ) ; addFakeClass ( clazz ) ; } } return clazz ; } ReadBuffer getReadBuffer ( ) { return readBuf ; } void setNew ( JavaHeapObject obj , boolean isNew ) { if ( isNew ) { newObjects . add ( obj ) ; } } boolean isNew ( JavaHeapObject obj ) { return newObjects . contains ( obj ) ; } private Number makeId ( long id ) { if ( identifierSize == ) { return ( int ) id ; } else { return id ; } } private void putInClassesMap ( JavaClass c ) { String name = c . getName ( ) ; if ( classes . containsKey ( name ) ) { name += "" + c . getIdString ( ) ; } classes . put ( name , c ) ; } private void addFakeClass ( JavaClass c ) { putInClassesMap ( c ) ; c . resolve ( this ) ; } private void addFakeClass ( Number id , JavaClass c ) { fakeClasses . put ( id , c ) ; addFakeClass ( c ) ; } public ImmutableList < ModelFactory > getModelFactories ( ) { return modelFactories ; } public void setUpModelFactories ( ModelFactoryFactory ... factoryFactories ) { ImmutableList . Builder < ModelFactory > builder = ImmutableList . builder ( ) ; for ( ModelFactoryFactory factoryFactory : factoryFactories ) { if ( factoryFactory . isSupported ( this ) ) { builder . add ( factoryFactory . newFactory ( this ) ) ; } } modelFactories = builder . build ( ) ; } } package com . sun . tools . hat . internal . model ; public abstract class JavaValue extends JavaThing { protected JavaValue ( ) { } public boolean isHeapAllocated ( ) { return false ; } abstract public String toString ( ) ; public int getSize ( ) { return ; } } package com . sun . tools . hat . internal . model ; import java . io . IOException ; import com . sun . tools . hat . internal . parser . ReadBuffer ; public abstract class JavaLazyReadObject extends JavaHeapObject { private final long offset ; protected JavaLazyReadObject ( long offset ) { this . offset = offset ; } public final int getSize ( ) { return getValueLength ( ) + getClazz ( ) . getMinimumObjectSize ( ) ; } protected final long getOffset ( ) { return offset ; } protected final int getValueLength ( ) { try { return readValueLength ( ) ; } catch ( IOException exp ) { System . err . println ( "" + offset ) ; exp . printStackTrace ( ) ; return ; } } protected final byte [ ] getValue ( ) { try { return readValue ( ) ; } catch ( IOException exp ) { System . err . println ( "" + offset ) ; exp . printStackTrace ( ) ; return Snapshot . EMPTY_BYTE_ARRAY ; } } public final long getId ( ) { try { ReadBuffer buf = getClazz ( ) . getReadBuffer ( ) ; int idSize = getClazz ( ) . getIdentifierSize ( ) ; if ( idSize == ) { return buf . getInt ( offset ) & Snapshot . SMALL_ID_MASK ; } else { return buf . getLong ( offset ) ; } } catch ( IOException exp ) { System . err . println ( "" + offset ) ; exp . printStackTrace ( ) ; return - ; } } protected abstract int readValueLength ( ) throws IOException ; protected abstract byte [ ] readValue ( ) throws IOException ; protected static Number makeId ( long id ) { if ( ( id & ~ Snapshot . SMALL_ID_MASK ) == ) { return ( int ) id ; } else { return id ; } } protected static long getIdValue ( Number num ) { long id = num . longValue ( ) ; if ( num instanceof Integer ) { id &= Snapshot . SMALL_ID_MASK ; } return id ; } protected final long objectIdAt ( int index , byte [ ] data ) { int idSize = getClazz ( ) . getIdentifierSize ( ) ; if ( idSize == ) { return intAt ( index , data ) & Snapshot . SMALL_ID_MASK ; } else { return longAt ( index , data ) ; } } protected static byte byteAt ( int index , byte [ ] value ) { return value [ index ] ; } protected static boolean booleanAt ( int index , byte [ ] value ) { return ( value [ index ] & ) == ? false : true ; } protected static char charAt ( int index , byte [ ] value ) { int b1 = value [ index ++ ] & ; int b2 = value [ index ++ ] & ; return ( char ) ( ( b1 << ) + b2 ) ; } protected static short shortAt ( int index , byte [ ] value ) { int b1 = value [ index ++ ] & ; int b2 = value [ index ++ ] & ; return ( short ) ( ( b1 << ) + b2 ) ; } protected static int intAt ( int index , byte [ ] value ) { int b1 = value [ index ++ ] & ; int b2 = value [ index ++ ] & ; int b3 = value [ index ++ ] & ; int b4 = value [ index ++ ] & ; return ( ( b1 << ) + ( b2 << ) + ( b3 << ) + b4 ) ; } protected static long longAt ( int index , byte [ ] value ) { long val = ; for ( int j = ; j < ; j ++ ) { val = val << ; int b = value [ index ++ ] & ; val |= b ; } return val ; } protected static float floatAt ( int index , byte [ ] value ) { int val = intAt ( index , value ) ; return Float . intBitsToFloat ( val ) ; } protected static double doubleAt ( int index , byte [ ] value ) { long val = longAt ( index , value ) ; return Double . longBitsToDouble ( val ) ; } } package com . sun . tools . hat . internal . model ; public class JavaStatic { private final JavaField field ; private JavaThing value ; public JavaStatic ( JavaField field , JavaThing value ) { this . field = field ; this . value = value ; } public void resolve ( JavaClass clazz , Snapshot snapshot ) { long id = - ; if ( value instanceof JavaObjectRef ) { id = ( ( JavaObjectRef ) value ) . getId ( ) ; } value = value . dereference ( snapshot , field ) ; if ( value . isHeapAllocated ( ) && clazz . getLoader ( ) == snapshot . getNullThing ( ) ) { JavaHeapObject ho = ( JavaHeapObject ) value ; String s = "" + clazz . getName ( ) + "" + field . getName ( ) ; snapshot . addRoot ( new Root ( id , clazz . getId ( ) , Root . JAVA_STATIC , s ) ) ; } } public JavaField getField ( ) { return field ; } public JavaThing getValue ( ) { return value ; } } package com . sun . tools . hat . internal . model ; public class JavaChar extends JavaValue { public final char value ; public JavaChar ( char value ) { this . value = value ; } public String toString ( ) { return String . valueOf ( value ) ; } } package com . sun . tools . hat . internal . lang ; package com . sun . tools . hat . internal . lang ; public interface Model { void visit ( ModelVisitor visitor ) ; } package com . sun . tools . hat . internal . lang . jruby12 ; package com . sun . tools . hat . internal . lang . jruby12 ; import com . sun . tools . hat . internal . lang . Model ; import com . sun . tools . hat . internal . lang . ModelFactory ; import com . sun . tools . hat . internal . lang . ModelFactoryFactory ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . lang . jruby . JRubyArray ; import com . sun . tools . hat . internal . lang . jruby . JRubyString ; import com . sun . tools . hat . internal . lang . openjdk6 . JavaHash ; import com . sun . tools . hat . internal . model . JavaClass ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; import com . sun . tools . hat . internal . model . Snapshot ; public class JRuby12 implements ModelFactory { public enum Factory implements ModelFactoryFactory { INSTANCE ; @ Override public boolean isSupported ( Snapshot snapshot ) { JavaClass constants = snapshot . findClass ( "" ) ; return Models . checkStaticString ( constants , "" , "" ) ; } @ Override public ModelFactory newFactory ( Snapshot snapshot ) { return isSupported ( snapshot ) ? new JRuby12 ( snapshot ) : null ; } } private final JavaClass constantsClass ; private final JavaClass stringClass ; private final JavaClass objectClass ; private final JavaClass arrayClass ; private final JavaClass hashClass ; private JRuby12 ( Snapshot snapshot ) { constantsClass = Models . grabClass ( snapshot , "" ) ; stringClass = Models . grabClass ( snapshot , "" ) ; objectClass = Models . grabClass ( snapshot , "" ) ; arrayClass = Models . grabClass ( snapshot , "" ) ; hashClass = Models . grabClass ( snapshot , "" ) ; } @ Override public Model newModel ( JavaThing thing ) { JavaObject obj = Models . safeCast ( thing , JavaObject . class ) ; if ( obj != null ) { JavaClass clazz = obj . getClazz ( ) ; if ( clazz == stringClass ) return JRubyString . make ( obj ) ; else if ( clazz == objectClass ) return new JRubyObject ( obj ) ; else if ( clazz == arrayClass ) return JRubyArray . make ( obj ) ; else if ( clazz == hashClass ) return JavaHash . make ( obj ) ; } return null ; } @ Override public String toString ( ) { return String . format ( "" , Models . getStaticString ( constantsClass , "" ) , Models . getStaticString ( constantsClass , "" ) ) ; } } package com . sun . tools . hat . internal . lang . jruby12 ; import java . util . List ; import java . util . Map ; import com . google . common . collect . ImmutableMap ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . lang . ObjectModel ; import com . sun . tools . hat . internal . lang . common . HashCommon ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; class JRubyObject extends ObjectModel { private final JavaObject obj ; private final ImmutableMap < String , JavaThing > properties ; public JRubyObject ( JavaObject obj ) { this . obj = obj ; this . properties = makeProperties ( obj ) ; } private static ImmutableMap < String , JavaThing > makeProperties ( JavaObject obj ) { final ImmutableMap . Builder < String , JavaThing > builder = ImmutableMap . builder ( ) ; JavaObject variables = Models . getFieldObject ( obj , "" ) ; if ( variables != null ) { JavaObject packedVFields = Models . getFieldObject ( variables , "" ) ; if ( packedVFields != null ) { getPropertiesFromPackedFields ( packedVFields , builder ) ; } List < JavaObject > packedVTable = Models . getFieldObjectArray ( variables , "" , JavaObject . class ) ; if ( packedVTable != null ) { getPropertiesFromPackedTable ( packedVTable , builder ) ; } List < JavaObject > vTable = Models . getFieldObjectArray ( variables , "" , JavaObject . class ) ; if ( vTable != null ) { HashCommon . walkHashTable ( vTable , "" , "" , "" , new HashCommon . KeyValueVisitor ( ) { @ Override public void visit ( JavaThing key , JavaThing value ) { builder . put ( Models . getStringValue ( ( JavaObject ) key ) , value ) ; } } ) ; } } return builder . build ( ) ; } private static void getPropertiesFromPackedFields ( JavaObject packedVFields , ImmutableMap . Builder < String , JavaThing > builder ) { for ( int i = ; ; ++ i ) { String name = Models . getFieldString ( packedVFields , "" + i ) ; if ( name == null ) { return ; } builder . put ( name , packedVFields . getField ( "" + i ) ) ; } } private static void getPropertiesFromPackedTable ( List < JavaObject > packedVTable , ImmutableMap . Builder < String , JavaThing > builder ) { int midway = packedVTable . size ( ) / ; for ( int i = ; i < midway ; ++ i ) { String name = Models . getStringValue ( packedVTable . get ( i ) ) ; if ( name == null ) { return ; } builder . put ( name , packedVTable . get ( i + midway ) ) ; } } @ Override public String getClassName ( ) { JavaObject cls = getClassObject ( ) ; String name = Models . getFieldString ( cls , "" ) ; return name != null ? name : "" + cls . getIdString ( ) + ">" ; } @ Override public JavaObject getClassObject ( ) { return Models . getFieldObject ( obj , "" ) ; } @ Override public Map < String , JavaThing > getProperties ( ) { return properties ; } } package com . sun . tools . hat . internal . lang ; import java . util . Map ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; public abstract class ObjectModel implements Model { @ Override public void visit ( ModelVisitor visitor ) { visitor . visit ( this ) ; } public abstract String getClassName ( ) ; public abstract JavaObject getClassObject ( ) ; public abstract Map < String , JavaThing > getProperties ( ) ; } package com . sun . tools . hat . internal . lang ; import java . util . Collection ; import com . sun . tools . hat . internal . model . JavaThing ; public abstract class CollectionModel implements Model { @ Override public void visit ( ModelVisitor visitor ) { visitor . visit ( this ) ; } public abstract Collection < JavaThing > getCollection ( ) ; } package com . sun . tools . hat . internal . lang . jruby16 ; package com . sun . tools . hat . internal . lang . jruby16 ; import com . sun . tools . hat . internal . lang . Model ; import com . sun . tools . hat . internal . lang . ModelFactory ; import com . sun . tools . hat . internal . lang . ModelFactoryFactory ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . lang . jruby . JRubyArray ; import com . sun . tools . hat . internal . lang . jruby . JRubyString ; import com . sun . tools . hat . internal . lang . openjdk6 . JavaHash ; import com . sun . tools . hat . internal . model . JavaClass ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; import com . sun . tools . hat . internal . model . Snapshot ; public class JRuby16 implements ModelFactory { public enum Factory implements ModelFactoryFactory { INSTANCE ; @ Override public boolean isSupported ( Snapshot snapshot ) { JavaClass constants = snapshot . findClass ( "" ) ; return Models . checkStaticString ( constants , "" , "" ) ; } @ Override public ModelFactory newFactory ( Snapshot snapshot ) { return isSupported ( snapshot ) ? new JRuby16 ( snapshot ) : null ; } } private final JavaClass constantsClass ; private final JavaClass stringClass ; private final JavaClass objectClass ; private final JavaClass arrayClass ; private final JavaClass hashClass ; private JRuby16 ( Snapshot snapshot ) { constantsClass = Models . grabClass ( snapshot , "" ) ; stringClass = Models . grabClass ( snapshot , "" ) ; objectClass = Models . grabClass ( snapshot , "" ) ; arrayClass = Models . grabClass ( snapshot , "" ) ; hashClass = Models . grabClass ( snapshot , "" ) ; } @ Override public Model newModel ( JavaThing thing ) { JavaObject obj = Models . safeCast ( thing , JavaObject . class ) ; if ( obj != null ) { JavaClass clazz = obj . getClazz ( ) ; if ( clazz == stringClass ) return JRubyString . make ( obj ) ; else if ( clazz == objectClass ) return new JRubyObject ( obj ) ; else if ( clazz == arrayClass ) return JRubyArray . make ( obj ) ; else if ( clazz == hashClass ) return JavaHash . make ( obj ) ; } return null ; } @ Override public String toString ( ) { return String . format ( "" , Models . getStaticString ( constantsClass , "" ) , Models . getStaticString ( constantsClass , "" ) ) ; } } package com . sun . tools . hat . internal . lang . jruby16 ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import com . google . common . base . Function ; import com . google . common . cache . CacheBuilder ; import com . google . common . cache . CacheLoader ; import com . google . common . cache . LoadingCache ; import com . google . common . collect . ImmutableList ; import com . google . common . collect . ImmutableMap ; import com . google . common . collect . Lists ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . lang . ObjectModel ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; class JRubyObject extends ObjectModel { private enum GetVariableNames implements Function < JavaObject , ImmutableList < String > > { INSTANCE ; @ Override public ImmutableList < String > apply ( JavaObject rubyClass ) { ImmutableList < JavaObject > names = Models . getFieldObjectArray ( rubyClass , "" , JavaObject . class ) ; return ImmutableList . copyOf ( Lists . transform ( names , Models . GetStringValue . INSTANCE ) ) ; } } private static final LoadingCache < JavaObject , ImmutableList < String > > VARIABLE_NAME_CACHE = CacheBuilder . newBuilder ( ) . softValues ( ) . build ( CacheLoader . from ( GetVariableNames . INSTANCE ) ) ; private final JavaObject obj ; private final ImmutableMap < String , JavaThing > properties ; public JRubyObject ( JavaObject obj ) { this . obj = obj ; this . properties = makeProperties ( obj , getClassObject ( ) ) ; } private static ImmutableMap < String , JavaThing > makeProperties ( JavaObject obj , JavaObject rubyClass ) { List < String > names = VARIABLE_NAME_CACHE . getUnchecked ( rubyClass ) ; if ( names . isEmpty ( ) ) return ImmutableMap . of ( ) ; List < JavaThing > values = Models . getFieldObjectArray ( obj , "" , JavaThing . class ) ; ImmutableMap . Builder < String , JavaThing > builder = ImmutableMap . builder ( ) ; Iterator < JavaThing > iter = values . iterator ( ) ; for ( String name : names ) { if ( ! iter . hasNext ( ) ) break ; builder . put ( name , iter . next ( ) ) ; } return builder . build ( ) ; } @ Override public String getClassName ( ) { JavaObject cls = getClassObject ( ) ; String name = Models . getFieldString ( cls , "" ) ; return name != null ? name : "" + cls . getIdString ( ) + ">" ; } @ Override public JavaObject getClassObject ( ) { return Models . getFieldObject ( obj , "" ) ; } @ Override public Map < String , JavaThing > getProperties ( ) { return properties ; } } package com . sun . tools . hat . internal . lang . common ; package com . sun . tools . hat . internal . lang . common ; import java . util . List ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; public final class HashCommon { public interface KeyValueVisitor { void visit ( JavaThing key , JavaThing value ) ; } private HashCommon ( ) { } public static void walkHashTable ( List < JavaObject > table , String keyField , String valueField , String nextField , KeyValueVisitor visitor ) { for ( JavaObject element : table ) { for ( JavaObject bucket = element ; bucket != null ; bucket = Models . getFieldObject ( bucket , nextField ) ) { visitor . visit ( bucket . getField ( keyField ) , bucket . getField ( valueField ) ) ; } } } } package com . sun . tools . hat . internal . lang ; import java . util . Map ; import com . sun . tools . hat . internal . model . JavaThing ; public abstract class MapModel implements Model { @ Override public void visit ( ModelVisitor visitor ) { visitor . visit ( this ) ; } public abstract Map < JavaThing , JavaThing > getMap ( ) ; } package com . sun . tools . hat . internal . lang . jruby ; package com . sun . tools . hat . internal . lang . jruby ; import java . util . Collection ; import java . util . List ; import com . google . common . base . Function ; import com . google . common . cache . CacheBuilder ; import com . google . common . cache . CacheLoader ; import com . google . common . cache . LoadingCache ; import com . google . common . collect . ImmutableList ; import com . sun . tools . hat . internal . lang . CollectionModel ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . model . JavaInt ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaObjectArray ; import com . sun . tools . hat . internal . model . JavaThing ; public class JRubyArray extends CollectionModel { private enum GetObjectArrayElements implements Function < JavaObjectArray , ImmutableList < JavaThing > > { INSTANCE ; @ Override public ImmutableList < JavaThing > apply ( JavaObjectArray arr ) { return ImmutableList . copyOf ( arr . getElements ( ) ) ; } } private static final LoadingCache < JavaObjectArray , ImmutableList < JavaThing > > ELEMENT_CACHE = CacheBuilder . newBuilder ( ) . softValues ( ) . build ( CacheLoader . from ( GetObjectArrayElements . INSTANCE ) ) ; private final Collection < JavaThing > value ; private JRubyArray ( Collection < JavaThing > value ) { this . value = value ; } public static JRubyArray make ( JavaObject obj ) { JavaObjectArray arr = Models . getFieldThing ( obj , "" , JavaObjectArray . class ) ; JavaInt begin = Models . getFieldThing ( obj , "" , JavaInt . class ) ; JavaInt length = Models . getFieldThing ( obj , "" , JavaInt . class ) ; if ( arr == null || begin == null || length == null ) return null ; List < JavaThing > elements = ELEMENT_CACHE . getUnchecked ( arr ) ; return new JRubyArray ( elements . subList ( begin . value , begin . value + length . value ) ) ; } @ Override public Collection < JavaThing > getCollection ( ) { return value ; } } package com . sun . tools . hat . internal . lang . jruby ; import com . google . common . base . Charsets ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . lang . ScalarModel ; import com . sun . tools . hat . internal . model . JavaInt ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaValueArray ; public class JRubyString extends ScalarModel { private final String value ; private JRubyString ( String value ) { this . value = value ; } public static JRubyString make ( JavaObject obj ) { String value = getRubyStringValue ( obj ) ; return value != null ? new JRubyString ( value ) : null ; } private static String getRubyStringValue ( JavaObject obj ) { JavaObject value = Models . getFieldObject ( obj , "" ) ; if ( value != null ) { JavaValueArray bytes = Models . safeCast ( value . getField ( "" ) , JavaValueArray . class ) ; JavaInt begin = Models . safeCast ( value . getField ( "" ) , JavaInt . class ) ; JavaInt realSize = Models . safeCast ( value . getField ( "" ) , JavaInt . class ) ; if ( bytes != null && begin != null && realSize != null ) { return new String ( ( byte [ ] ) bytes . getElements ( ) , begin . value , realSize . value , Charsets . UTF_8 ) ; } } return null ; } @ Override public String toString ( ) { return value ; } } package com . sun . tools . hat . internal . lang ; import java . util . Arrays ; import com . google . common . base . Function ; import com . google . common . base . Preconditions ; import com . google . common . collect . ImmutableList ; import com . sun . tools . hat . internal . model . JavaClass ; import com . sun . tools . hat . internal . model . JavaInt ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaObjectArray ; import com . sun . tools . hat . internal . model . JavaThing ; import com . sun . tools . hat . internal . model . JavaValueArray ; import com . sun . tools . hat . internal . model . Snapshot ; public final class Models { private Models ( ) { } public static < T , U extends T > U safeCast ( T obj , Class < U > cls ) { return cls . isInstance ( obj ) ? cls . cast ( obj ) : null ; } private static JavaClass getClass ( Snapshot snapshot , String ... classNames ) { for ( String className : classNames ) { JavaClass result = snapshot . findClass ( className ) ; if ( result != null ) return result ; } return null ; } public static JavaClass grabClass ( Snapshot snapshot , String ... classNames ) { return Preconditions . checkNotNull ( getClass ( snapshot , classNames ) , "" + Arrays . toString ( classNames ) ) ; } public static boolean hasClass ( Snapshot snapshot , String ... classNames ) { return getClass ( snapshot , classNames ) != null ; } public enum GetStringValue implements Function < JavaObject , String > { INSTANCE ; @ Override public String apply ( JavaObject obj ) { if ( obj != null && obj . getClazz ( ) . isString ( ) ) { JavaValueArray value = safeCast ( obj . getField ( "" ) , JavaValueArray . class ) ; JavaInt offset = safeCast ( obj . getField ( "" ) , JavaInt . class ) ; JavaInt count = safeCast ( obj . getField ( "" ) , JavaInt . class ) ; if ( value != null && offset != null && count != null ) { return new String ( ( char [ ] ) value . getElements ( ) , offset . value , count . value ) ; } } return null ; } } public static String getStringValue ( JavaObject obj ) { return GetStringValue . INSTANCE . apply ( obj ) ; } public static < T extends JavaThing > ImmutableList < T > getObjectArrayValue ( JavaObjectArray arr , Class < T > typeKey ) { if ( arr != null ) { ImmutableList . Builder < T > builder = ImmutableList . builder ( ) ; for ( JavaThing t : arr . getElements ( ) ) { if ( t != null ) { if ( ! typeKey . isInstance ( t ) ) return null ; builder . add ( typeKey . cast ( t ) ) ; } } ImmutableList < T > result = builder . build ( ) ; return result ; } return null ; } public static String getStaticString ( JavaClass clazz , String fieldName ) { return getStringValue ( safeCast ( clazz . getStaticField ( fieldName ) , JavaObject . class ) ) ; } public static boolean checkStaticString ( JavaClass clazz , String fieldName , String prefix ) { if ( clazz != null ) { String value = getStaticString ( clazz , fieldName ) ; if ( value != null ) { return value . startsWith ( prefix ) ; } } return false ; } public static JavaObject getFieldObject ( JavaObject obj , String field ) { return getFieldThing ( obj , field , JavaObject . class ) ; } public static < T extends JavaThing > T getFieldThing ( JavaObject obj , String field , Class < T > typeKey ) { return obj == null ? null : safeCast ( obj . getField ( field ) , typeKey ) ; } public static String getFieldString ( JavaObject obj , String field ) { return getStringValue ( getFieldObject ( obj , field ) ) ; } public static < T extends JavaThing > ImmutableList < T > getFieldObjectArray ( JavaObject obj , String field , Class < T > typeKey ) { return getObjectArrayValue ( getFieldThing ( obj , field , JavaObjectArray . class ) , typeKey ) ; } } package com . sun . tools . hat . internal . lang . openjdk6 ; import java . util . Collection ; import com . google . common . collect . ImmutableList ; import com . sun . tools . hat . internal . lang . CollectionModel ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; class JavaLinkedList extends CollectionModel { private final ImmutableList < JavaThing > items ; private JavaLinkedList ( ImmutableList < JavaThing > items ) { this . items = items ; } public static JavaLinkedList make ( JavaObject list ) { JavaObject header = Models . getFieldObject ( list , "" ) ; if ( header == null ) return null ; ImmutableList . Builder < JavaThing > builder = ImmutableList . builder ( ) ; for ( JavaObject entry = Models . getFieldObject ( header , "" ) ; entry != header ; entry = Models . getFieldObject ( entry , "" ) ) { if ( entry == null ) return null ; builder . add ( entry . getField ( "" ) ) ; } return new JavaLinkedList ( builder . build ( ) ) ; } @ Override public Collection < JavaThing > getCollection ( ) { return items ; } } package com . sun . tools . hat . internal . lang . openjdk6 ; import java . util . List ; import java . util . Map ; import com . google . common . collect . ImmutableMap ; import com . sun . tools . hat . internal . lang . MapModel ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . lang . common . HashCommon ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; public class JavaHash extends MapModel { private final ImmutableMap < JavaThing , JavaThing > map ; private JavaHash ( ImmutableMap < JavaThing , JavaThing > map ) { this . map = map ; } public static JavaHash make ( JavaObject hash ) { List < JavaObject > table = Models . getFieldObjectArray ( hash , "" , JavaObject . class ) ; if ( table == null ) return null ; final ImmutableMap . Builder < JavaThing , JavaThing > builder = ImmutableMap . builder ( ) ; HashCommon . walkHashTable ( table , "" , "" , "" , new HashCommon . KeyValueVisitor ( ) { @ Override public void visit ( JavaThing key , JavaThing value ) { builder . put ( key , value ) ; } } ) ; return new JavaHash ( builder . build ( ) ) ; } @ Override public Map < JavaThing , JavaThing > getMap ( ) { return map ; } } package com . sun . tools . hat . internal . lang . openjdk6 ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import com . sun . tools . hat . internal . lang . CollectionModel ; import com . sun . tools . hat . internal . model . JavaObjectArray ; import com . sun . tools . hat . internal . model . JavaThing ; class JavaArray extends CollectionModel { private final List < JavaThing > items ; public JavaArray ( JavaObjectArray array ) { items = Collections . unmodifiableList ( Arrays . asList ( array . getElements ( ) ) ) ; } @ Override public Collection < JavaThing > getCollection ( ) { return items ; } } package com . sun . tools . hat . internal . lang . openjdk6 ; package com . sun . tools . hat . internal . lang . openjdk6 ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . lang . ScalarModel ; import com . sun . tools . hat . internal . model . JavaObject ; class JavaString extends ScalarModel { private final String value ; private JavaString ( String value ) { this . value = value ; } public static JavaString make ( JavaObject obj ) { String value = Models . getStringValue ( obj ) ; return value != null ? new JavaString ( value ) : null ; } @ Override public String toString ( ) { return value ; } } package com . sun . tools . hat . internal . lang . openjdk6 ; import java . util . Arrays ; import java . util . Collection ; import java . util . List ; import com . google . common . collect . ImmutableList ; import com . sun . tools . hat . internal . lang . CollectionModel ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . model . JavaInt ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaObjectArray ; import com . sun . tools . hat . internal . model . JavaThing ; class JavaVector extends CollectionModel { private final ImmutableList < JavaThing > items ; private JavaVector ( List < JavaThing > items ) { this . items = ImmutableList . copyOf ( items ) ; } public static JavaVector make ( JavaObject vec , String sizeField ) { JavaThing [ ] data = Models . getFieldThing ( vec , "" , JavaObjectArray . class ) . getElements ( ) ; JavaInt size = Models . getFieldThing ( vec , sizeField , JavaInt . class ) ; return data == null || size == null ? null : new JavaVector ( Arrays . asList ( data ) . subList ( , size . value ) ) ; } @ Override public Collection < JavaThing > getCollection ( ) { return items ; } } package com . sun . tools . hat . internal . lang . openjdk6 ; import com . sun . tools . hat . internal . lang . Model ; import com . sun . tools . hat . internal . lang . ModelFactory ; import com . sun . tools . hat . internal . lang . ModelFactoryFactory ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . model . JavaClass ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaObjectArray ; import com . sun . tools . hat . internal . model . JavaThing ; import com . sun . tools . hat . internal . model . Snapshot ; public class OpenJDK6 implements ModelFactory { public enum Factory implements ModelFactoryFactory { INSTANCE ; @ Override public boolean isSupported ( Snapshot snapshot ) { JavaClass version = snapshot . findClass ( "" ) ; return ( Models . checkStaticString ( version , "" , "" ) || Models . checkStaticString ( version , "" , "" ) ) && Models . checkStaticString ( version , "" , "" ) ; } @ Override public ModelFactory newFactory ( Snapshot snapshot ) { return new OpenJDK6 ( snapshot ) ; } } private final JavaClass versionClass ; private final JavaClass concHashMapClass ; private final JavaClass hashMapClass ; private final JavaClass hashtableClass ; private final JavaClass arrayListClass ; private final JavaClass vectorClass ; private final JavaClass linkedListClass ; private OpenJDK6 ( Snapshot snapshot ) { versionClass = Models . grabClass ( snapshot , "" ) ; concHashMapClass = Models . grabClass ( snapshot , "" ) ; hashMapClass = Models . grabClass ( snapshot , "" ) ; hashtableClass = Models . grabClass ( snapshot , "" ) ; arrayListClass = Models . grabClass ( snapshot , "" ) ; vectorClass = Models . grabClass ( snapshot , "" ) ; linkedListClass = Models . grabClass ( snapshot , "" ) ; } @ Override public Model newModel ( JavaThing thing ) { if ( thing instanceof JavaObject ) { JavaObject obj = ( JavaObject ) thing ; JavaClass clazz = obj . getClazz ( ) ; if ( clazz . isString ( ) ) return JavaString . make ( obj ) ; else if ( clazz == concHashMapClass ) return JavaConcHash . make ( obj ) ; else if ( clazz == hashMapClass || clazz == hashtableClass ) return JavaHash . make ( obj ) ; else if ( clazz == arrayListClass ) return JavaVector . make ( obj , "" ) ; else if ( clazz == vectorClass ) return JavaVector . make ( obj , "" ) ; else if ( clazz == linkedListClass ) return JavaLinkedList . make ( obj ) ; } if ( thing instanceof JavaObjectArray ) return new JavaArray ( ( JavaObjectArray ) thing ) ; return null ; } @ Override public String toString ( ) { return String . format ( "" , Models . getStaticString ( versionClass , "" ) , Models . getStaticString ( versionClass , "" ) ) ; } } package com . sun . tools . hat . internal . lang . openjdk6 ; import java . util . List ; import java . util . Map ; import com . google . common . collect . ImmutableMap ; import com . sun . tools . hat . internal . lang . MapModel ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . lang . common . HashCommon ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; class JavaConcHash extends MapModel { private final ImmutableMap < JavaThing , JavaThing > map ; private JavaConcHash ( ImmutableMap < JavaThing , JavaThing > map ) { this . map = map ; } public static JavaConcHash make ( JavaObject chm ) { List < JavaObject > segments = Models . getFieldObjectArray ( chm , "" , JavaObject . class ) ; if ( segments == null ) return null ; final ImmutableMap . Builder < JavaThing , JavaThing > builder = ImmutableMap . builder ( ) ; HashCommon . KeyValueVisitor visitor = new HashCommon . KeyValueVisitor ( ) { @ Override public void visit ( JavaThing key , JavaThing value ) { builder . put ( key , value ) ; } } ; for ( JavaObject segment : segments ) { List < JavaObject > table = Models . getFieldObjectArray ( segment , "" , JavaObject . class ) ; if ( table != null ) HashCommon . walkHashTable ( table , "" , "" , "" , visitor ) ; } return new JavaConcHash ( builder . build ( ) ) ; } @ Override public Map < JavaThing , JavaThing > getMap ( ) { return map ; } } package com . sun . tools . hat . internal . lang . guava ; package com . sun . tools . hat . internal . lang . guava ; import com . sun . tools . hat . internal . lang . Model ; import com . sun . tools . hat . internal . lang . ModelFactory ; import com . sun . tools . hat . internal . lang . ModelFactoryFactory ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . model . JavaClass ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; import com . sun . tools . hat . internal . model . Snapshot ; public class Guava implements ModelFactory { public enum Factory implements ModelFactoryFactory { INSTANCE ; @ Override public boolean isSupported ( Snapshot snapshot ) { return Models . hasClass ( snapshot , CLASSES ) ; } @ Override public ModelFactory newFactory ( Snapshot snapshot ) { return new Guava ( snapshot ) ; } } private static final String [ ] CLASSES = { "" , "" } ; private final JavaClass custConcHashClass ; public Guava ( Snapshot snapshot ) { custConcHashClass = Models . grabClass ( snapshot , CLASSES ) ; } @ Override public Model newModel ( JavaThing thing ) { JavaObject obj = Models . safeCast ( thing , JavaObject . class ) ; if ( obj != null ) { JavaClass clazz = obj . getClazz ( ) ; if ( clazz == custConcHashClass ) return GuavaCustConcHash . make ( obj ) ; } return null ; } } package com . sun . tools . hat . internal . lang . guava ; import java . util . List ; import java . util . Map ; import com . google . common . collect . ImmutableMap ; import com . sun . tools . hat . internal . lang . MapModel ; import com . sun . tools . hat . internal . lang . Models ; import com . sun . tools . hat . internal . model . JavaObject ; import com . sun . tools . hat . internal . model . JavaThing ; class GuavaCustConcHash extends MapModel { private final ImmutableMap < JavaThing , JavaThing > map ; private GuavaCustConcHash ( ImmutableMap < JavaThing , JavaThing > map ) { this . map = map ; } public static GuavaCustConcHash make ( JavaObject chm ) { List < JavaObject > segments = Models . getFieldObjectArray ( chm , "" , JavaObject . class ) ; if ( segments == null ) return null ; final ImmutableMap . Builder < JavaThing , JavaThing > builder = ImmutableMap . builder ( ) ; for ( JavaObject segment : segments ) { JavaObject table = Models . getFieldObject ( segment , "" ) ; List < JavaObject > array = Models . getFieldObjectArray ( table , "" , JavaObject . class ) ; if ( array != null ) { for ( JavaObject entry : array ) { JavaThing key = entry . getField ( "" ) ; if ( key == null ) key = entry . getField ( "" ) ; JavaObject valueReference = Models . getFieldObject ( entry , "" ) ; JavaThing value = valueReference . getField ( "" ) ; if ( key != null && value != null ) builder . put ( key , value ) ; } } } return new GuavaCustConcHash ( builder . build ( ) ) ; } @ Override public Map < JavaThing , JavaThing > getMap ( ) { return map ; } } package com . sun . tools . hat . internal . lang ; import com . sun . tools . hat . internal . model . Snapshot ; public interface ModelFactoryFactory { boolean isSupported ( Snapshot snapshot ) ; ModelFactory newFactory ( Snapshot snapshot ) ; } package com . sun . tools . hat . internal . lang ; public interface ModelVisitor { public void visit ( ScalarModel model ) ; public void visit ( CollectionModel model ) ; public void visit ( MapModel model ) ; public void visit ( ObjectModel model ) ; } package com . sun . tools . hat . internal . lang ; public abstract class ScalarModel implements Model { @ Override public void visit ( ModelVisitor visitor ) { visitor . visit ( this ) ; } @ Override public abstract String toString ( ) ; } package com . sun . tools . hat . internal . lang ; import com . sun . tools . hat . internal . model . JavaThing ; public interface ModelFactory { Model newModel ( JavaThing thing ) ; } package com . sun . tools . hat . internal . server ; import com . sun . tools . hat . internal . model . * ; public class FinalizerObjectsQuery extends QueryHandler { public void run ( ) { startHtml ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; for ( JavaHeapObject obj : snapshot . getFinalizerObjects ( ) ) { printThing ( obj ) ; out . println ( "" ) ; } endHtml ( ) ; } } package com . sun . tools . hat . internal . server ; import com . google . common . base . Function ; import com . google . common . collect . Collections2 ; import com . google . common . collect . ImmutableMultiset ; import com . google . common . collect . ImmutableSetMultimap ; import com . google . common . collect . Lists ; import com . google . common . collect . Multiset ; import com . google . common . collect . Ordering ; import com . sun . tools . hat . internal . model . * ; import com . sun . tools . hat . internal . util . Misc ; import java . util . * ; public class RefsByTypeQuery extends QueryHandler { private enum Sorters implements Function < Multiset . Entry < JavaClass > , Integer > , Comparator < Multiset . Entry < JavaClass > > { BY_COUNT { @ Override public Integer apply ( Multiset . Entry < JavaClass > entry ) { return ~ entry . getCount ( ) ; } } ; private final Ordering < Multiset . Entry < JavaClass > > ordering ; private Sorters ( ) { ordering = Ordering . natural ( ) . onResultOf ( this ) ; } @ Override public int compare ( Multiset . Entry < JavaClass > lhs , Multiset . Entry < JavaClass > rhs ) { return ordering . compare ( lhs , rhs ) ; } } public void run ( ) { ClassResolver resolver = new ClassResolver ( snapshot , true ) ; JavaClass clazz = resolver . apply ( query ) ; Collection < JavaClass > referrers = Collections2 . transform ( params . get ( "" ) , resolver ) ; ImmutableSetMultimap . Builder < JavaClass , JavaHeapObject > rfrBuilder = ImmutableSetMultimap . builder ( ) ; final ImmutableSetMultimap . Builder < JavaClass , JavaHeapObject > rfeBuilder = ImmutableSetMultimap . builder ( ) ; for ( final JavaHeapObject instance : Misc . getInstances ( clazz , false , referrers ) ) { if ( instance . getId ( ) == - ) { continue ; } for ( JavaHeapObject ref : instance . getReferers ( ) ) { JavaClass cl = ref . getClazz ( ) ; if ( cl == null ) { System . out . println ( "" + ref ) ; continue ; } rfrBuilder . put ( cl , instance ) ; } instance . visitReferencedObjects ( new AbstractJavaHeapObjectVisitor ( ) { public void visit ( JavaHeapObject obj ) { rfeBuilder . put ( obj . getClazz ( ) , instance ) ; } } ) ; } startHtml ( "" ) ; out . println ( "" ) ; printClass ( clazz ) ; if ( clazz . getId ( ) != - ) { out . println ( "" + clazz . getIdString ( ) + "" ) ; } out . println ( "" ) ; printBreadcrumbs ( path , null , null , clazz , referrers , null ) ; ImmutableMultiset < JavaClass > referrersStat = rfrBuilder . build ( ) . keys ( ) ; if ( ! referrersStat . isEmpty ( ) ) { out . println ( "" ) ; print ( referrersStat , clazz , referrers , true ) ; } ImmutableMultiset < JavaClass > refereesStat = rfeBuilder . build ( ) . keys ( ) ; if ( ! refereesStat . isEmpty ( ) ) { out . println ( "" ) ; print ( refereesStat , clazz , referrers , false ) ; } endHtml ( ) ; } private void print ( Multiset < JavaClass > multiset , JavaClass primary , Collection < JavaClass > referrers , boolean supportsChaining ) { out . println ( "" ) ; List < Multiset . Entry < JavaClass > > entries = Lists . newArrayList ( multiset . entrySet ( ) ) ; Collections . sort ( entries , Sorters . BY_COUNT ) ; out . println ( "" ) ; for ( Multiset . Entry < JavaClass > entry : entries ) { out . println ( "" ) ; JavaClass clazz = entry . getElement ( ) ; printClass ( clazz ) ; if ( supportsChaining ) { out . printf ( "" , formatLink ( "" , clazz , null , null ) , formatLink ( "" , primary , referrers , clazz ) ) ; } else { out . printf ( "" , formatLink ( "" , clazz , null , null ) ) ; } out . println ( "" ) ; out . println ( entry . getCount ( ) ) ; out . println ( "" ) ; } out . println ( "" ) ; } private String formatLink ( String label , JavaClass clazz , Collection < JavaClass > referrers , JavaClass tail ) { return formatLink ( path , null , label , null , clazz , referrers , tail , null ) ; } } package com . sun . tools . hat . internal . server ; import java . util . Arrays ; import java . util . Comparator ; import com . google . common . base . Function ; import com . google . common . collect . Ordering ; import com . google . common . primitives . Ints ; import com . sun . tools . hat . internal . model . * ; class ObjectQuery extends ClassQuery { private enum Sorters implements Function < FieldThing , Comparable < ? > > , Comparator < FieldThing > { BY_FIELD_NAME { @ Override public String apply ( FieldThing ft ) { return ft . field . getName ( ) ; } } ; private final Ordering < FieldThing > ordering ; private Sorters ( ) { this . ordering = Ordering . natural ( ) . onResultOf ( this ) ; } @ Override public int compare ( FieldThing lhs , FieldThing rhs ) { return ordering . compare ( lhs , rhs ) ; } } private static class FieldThing { public final JavaField field ; public final JavaThing thing ; public FieldThing ( JavaField field , JavaThing thing ) { this . field = field ; this . thing = thing ; } public static FieldThing [ ] make ( JavaField [ ] fields , JavaThing [ ] things ) { int len = Ints . min ( fields . length , things . length ) ; FieldThing [ ] result = new FieldThing [ len ] ; for ( int i = ; i < len ; ++ i ) { result [ i ] = new FieldThing ( fields [ i ] , things [ i ] ) ; } return result ; } } public ObjectQuery ( ) { } public void run ( ) { startHtml ( "" + query ) ; JavaHeapObject thing = snapshot . findThing ( query ) ; if ( thing == null ) { error ( "" ) ; } else if ( thing instanceof JavaClass ) { printFullClass ( ( JavaClass ) thing ) ; } else if ( thing instanceof JavaValueArray ) { print ( ( ( JavaValueArray ) thing ) . valueString ( true ) ) ; printAllocationSite ( thing ) ; printReferencesTo ( thing ) ; } else if ( thing instanceof JavaObjectArray ) { printFullObjectArray ( ( JavaObjectArray ) thing ) ; printAllocationSite ( thing ) ; printReferencesTo ( thing ) ; } else if ( thing instanceof JavaObject ) { printFullObject ( ( JavaObject ) thing ) ; printAllocationSite ( thing ) ; printReferencesTo ( thing ) ; } else { print ( thing . toString ( ) ) ; printReferencesTo ( thing ) ; } endHtml ( ) ; } private void printFullObject ( JavaObject obj ) { out . print ( "" ) ; print ( obj . toString ( ) ) ; out . print ( "" + obj . getSize ( ) + "" ) ; out . println ( "" ) ; out . println ( "" ) ; printClass ( obj . getClazz ( ) ) ; out . println ( "" ) ; FieldThing [ ] fieldThings = FieldThing . make ( obj . getClazz ( ) . getFieldsForInstance ( ) , obj . getFields ( ) ) ; Arrays . sort ( fieldThings , Sorters . BY_FIELD_NAME ) ; for ( FieldThing fieldThing : fieldThings ) { printField ( fieldThing . field ) ; out . print ( "" ) ; printThing ( fieldThing . thing ) ; out . println ( "" ) ; } } private void printFullObjectArray ( JavaObjectArray arr ) { JavaThing [ ] elements = arr . getElements ( ) ; out . println ( "" + elements . length + "" ) ; out . println ( "" ) ; printClass ( arr . getClazz ( ) ) ; out . println ( "" ) ; for ( int i = ; i < elements . length ; i ++ ) { out . print ( "" + i + "" ) ; printThing ( elements [ i ] ) ; out . println ( "" ) ; } } private void printAllocationSite ( JavaHeapObject obj ) { StackTrace trace = obj . getAllocatedFrom ( ) ; if ( trace == null || trace . getFrames ( ) . length == ) { return ; } out . println ( "" ) ; printStackTrace ( trace ) ; } } package com . sun . tools . hat . internal . server ; import java . util . Collection ; import java . util . List ; import com . google . common . collect . Iterables ; import com . google . common . collect . Lists ; import com . sun . tools . hat . internal . model . * ; import com . sun . tools . hat . internal . util . Misc ; class InstancesQuery extends QueryHandler { private final boolean includeSubclasses ; private final boolean newObjects ; public InstancesQuery ( boolean includeSubclasses ) { this ( includeSubclasses , false ) ; } public InstancesQuery ( boolean includeSubclasses , boolean newObjects ) { this . includeSubclasses = includeSubclasses ; this . newObjects = newObjects ; } public void run ( ) { ClassResolver resolver = new ClassResolver ( snapshot , true ) ; JavaClass clazz = resolver . apply ( query ) ; List < JavaClass > referrers = Lists . transform ( params . get ( "" ) , resolver ) ; boolean referee = Boolean . parseBoolean ( Iterables . getOnlyElement ( params . get ( "" ) , "" ) ) ; String instancesOf ; if ( newObjects ) instancesOf = referee ? "" : "" ; else instancesOf = referee ? "" : "" ; startHtml ( String . format ( "" , instancesOf , clazz . getName ( ) , includeSubclasses ? "" : "" ) ) ; if ( referrers . isEmpty ( ) ) { out . print ( "" ) ; printClass ( clazz ) ; out . print ( "" ) ; } else { printBreadcrumbs ( path , null , null , clazz , referrers , null ) ; } Collection < JavaHeapObject > objects = Misc . getInstances ( clazz , includeSubclasses , referrers ) ; if ( referee ) { int size = referrers . size ( ) ; JavaClass prev = size > ? referrers . get ( size - ) : clazz ; objects = Misc . getRefereesByClass ( objects , prev ) ; } long totalSize = ; long instances = ; for ( JavaHeapObject obj : objects ) { if ( newObjects && ! obj . isNew ( ) ) continue ; printThing ( obj ) ; out . println ( "" ) ; totalSize += obj . getSize ( ) ; instances ++ ; } out . println ( "" + instances + "" + totalSize + "" ) ; endHtml ( ) ; } } package com . sun . tools . hat . internal . server ; import com . google . common . base . Function ; import com . google . common . collect . Ordering ; import com . sun . tools . hat . internal . model . * ; import java . util . Arrays ; import java . util . Comparator ; class ClassQuery extends QueryHandler { private enum Sorters implements Function < JavaField , Comparable < ? > > , Comparator < JavaField > { BY_NAME { @ Override public String apply ( JavaField cls ) { return cls . getName ( ) ; } } ; private final Ordering < JavaField > ordering ; private Sorters ( ) { this . ordering = Ordering . natural ( ) . onResultOf ( this ) ; } @ Override public int compare ( JavaField lhs , JavaField rhs ) { return ordering . compare ( lhs , rhs ) ; } } public ClassQuery ( ) { } public void run ( ) { startHtml ( "" + query ) ; JavaClass clazz = snapshot . findClass ( query ) ; if ( clazz == null ) { error ( "" + query ) ; } else { printFullClass ( clazz ) ; } endHtml ( ) ; } protected void printFullClass ( JavaClass clazz ) { out . print ( "" ) ; print ( clazz . toString ( ) ) ; out . println ( "" ) ; out . println ( "" ) ; printClass ( clazz . getSuperclass ( ) ) ; out . println ( "" ) ; out . println ( "" ) ; printThing ( clazz . getLoader ( ) ) ; out . println ( "" ) ; printThing ( clazz . getSigners ( ) ) ; out . println ( "" ) ; printThing ( clazz . getProtectionDomain ( ) ) ; out . println ( "" ) ; for ( JavaClass sc : clazz . getSubclasses ( ) ) { out . print ( "" ) ; printClass ( sc ) ; out . println ( "" ) ; } out . println ( "" ) ; JavaField [ ] ff = clazz . getFields ( ) . clone ( ) ; Arrays . sort ( ff , Sorters . BY_NAME ) ; for ( JavaField f : ff ) { out . print ( "" ) ; printField ( f ) ; out . println ( "" ) ; } out . println ( "" ) ; JavaStatic [ ] ss = clazz . getStatics ( ) ; for ( JavaStatic s : ss ) { printStatic ( s ) ; out . println ( "" ) ; } out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" + encodeForURL ( clazz ) ) ; out . print ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" + encodeForURL ( clazz ) ) ; out . print ( "" ) ; out . println ( "" ) ; if ( snapshot . getHasNewSet ( ) ) { out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" + encodeForURL ( clazz ) ) ; out . print ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" + encodeForURL ( clazz ) ) ; out . print ( "" ) ; out . println ( "" ) ; } out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" + encodeForURL ( clazz ) ) ; out . print ( "" ) ; out . println ( "" ) ; printReferencesTo ( clazz ) ; } protected void printReferencesTo ( JavaHeapObject obj ) { if ( obj . getId ( ) == - ) { return ; } out . println ( "" ) ; out . flush ( ) ; for ( JavaHeapObject ref : obj . getReferers ( ) ) { printThing ( ref ) ; print ( "" + ref . describeReferenceTo ( obj , snapshot ) ) ; out . println ( "" ) ; } out . println ( "" ) ; out . println ( "" ) ; long id = obj . getId ( ) ; out . print ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; printHex ( id ) ; out . print ( "" ) ; out . println ( "" ) ; out . print ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; printHex ( id ) ; out . print ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; printHex ( id ) ; out . print ( "" ) ; out . println ( "" ) ; } } package com . sun . tools . hat . internal . server ; import java . util . Arrays ; import java . util . Comparator ; import com . google . common . base . Function ; import com . google . common . collect . ComparisonChain ; import com . google . common . collect . Ordering ; import com . sun . tools . hat . internal . model . * ; class AllRootsQuery extends QueryHandler { private enum Sorters implements Function < Root , Comparable < ? > > , Comparator < Root > { BY_TYPE { @ Override public Integer apply ( Root root ) { return root . getType ( ) ; } } , BY_DESCRIPTION { @ Override public String apply ( Root root ) { return root . getDescription ( ) ; } } ; private final Ordering < Root > ordering ; private Sorters ( ) { this . ordering = Ordering . natural ( ) . onResultOf ( this ) ; } @ Override public int compare ( Root lhs , Root rhs ) { return ordering . compare ( lhs , rhs ) ; } } public AllRootsQuery ( ) { } public void run ( ) { startHtml ( "" ) ; Root [ ] roots = snapshot . getRootsArray ( ) ; Arrays . sort ( roots , new Comparator < Root > ( ) { public int compare ( Root left , Root right ) { return ComparisonChain . start ( ) . compare ( right , left , Sorters . BY_TYPE ) . compare ( left , right , Sorters . BY_DESCRIPTION ) . result ( ) ; } } ) ; int lastType = Root . INVALID_TYPE ; for ( Root root : roots ) { if ( root . getType ( ) != lastType ) { lastType = root . getType ( ) ; out . print ( "" ) ; print ( root . getTypeName ( ) + "" ) ; out . println ( "" ) ; } printRoot ( root ) ; if ( root . getReferer ( ) != null ) { out . print ( "" ) ; printThingAnchorTag ( root . getReferer ( ) . getId ( ) ) ; print ( root . getReferer ( ) . toString ( ) ) ; out . print ( "" ) ; } out . print ( "" ) ; JavaThing t = snapshot . findThing ( root . getId ( ) ) ; if ( t != null ) { print ( "" ) ; printThing ( t ) ; out . println ( "" ) ; } } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; endHtml ( ) ; } } package com . sun . tools . hat . internal . server ; import com . google . common . collect . Iterables ; import com . sun . tools . hat . internal . oql . * ; class OQLQuery extends QueryHandler { public OQLQuery ( ThreadLocal < OQLEngine > engine ) { this . engine = engine ; } public void run ( ) { startHtml ( "" ) ; String oql = Iterables . getOnlyElement ( params . get ( "" ) , null ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; if ( oql != null ) { out . print ( oql ) ; } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; if ( oql != null ) { executeQuery ( oql ) ; } endHtml ( ) ; } private void executeQuery ( String q ) { try { out . println ( "" ) ; engine . get ( ) . executeQuery ( q , new ObjectVisitor ( ) { public boolean visit ( Object o ) { out . println ( "" ) ; try { out . println ( engine . get ( ) . toHtml ( o ) ) ; } catch ( Exception e ) { out . println ( e . getMessage ( ) ) ; out . println ( "" ) ; e . printStackTrace ( out ) ; out . println ( "" ) ; } out . println ( "" ) ; return out . checkError ( ) ; } } ) ; out . println ( "" ) ; } catch ( OQLException exp ) { out . println ( exp . getMessage ( ) ) ; out . println ( "" ) ; exp . printStackTrace ( out ) ; out . println ( "" ) ; } } private final ThreadLocal < OQLEngine > engine ; } package com . sun . tools . hat . internal . server ; import com . sun . tools . hat . internal . model . * ; class ReachableQuery extends QueryHandler { public ReachableQuery ( ) { } public void run ( ) { startHtml ( "" + query ) ; long id = parseHex ( query ) ; JavaHeapObject root = snapshot . findThing ( id ) ; ReachableObjects ro = new ReachableObjects ( root , snapshot . getReachableExcludes ( ) ) ; long totalSize = ro . getTotalSize ( ) ; JavaThing [ ] things = ro . getReachables ( ) ; long instances = things . length ; out . print ( "" ) ; printThing ( root ) ; out . println ( "" ) ; out . println ( "" ) ; for ( JavaThing thing : things ) { printThing ( thing ) ; out . println ( "" ) ; } printFields ( ro . getUsedFields ( ) , "" ) ; printFields ( ro . getExcludedFields ( ) , "" ) ; out . println ( "" + instances + "" + totalSize + "" ) ; endHtml ( ) ; } private void printFields ( String [ ] fields , String title ) { if ( fields . length == ) { return ; } out . print ( "" ) ; print ( title ) ; out . println ( "" ) ; for ( String field : fields ) { print ( field ) ; out . println ( "" ) ; } } } package com . sun . tools . hat . internal . server ; import com . sun . tools . hat . internal . model . * ; class AllClassesQuery extends QueryHandler { private final boolean excludePlatform ; private final boolean oqlSupported ; public AllClassesQuery ( boolean excludePlatform , boolean oqlSupported ) { this . excludePlatform = excludePlatform ; this . oqlSupported = oqlSupported ; } public void run ( ) { if ( excludePlatform ) { startHtml ( "" ) ; } else { startHtml ( "" ) ; } String lastPackage = null ; for ( JavaClass clazz : snapshot . getClasses ( ) ) { if ( excludePlatform && PlatformClasses . isPlatformClass ( clazz ) ) { continue ; } String name = clazz . getName ( ) ; int pos = name . lastIndexOf ( "" ) ; String pkg ; if ( name . startsWith ( "" ) ) { pkg = "" ; } else if ( pos == - ) { pkg = "" ; } else { pkg = name . substring ( , pos ) ; } if ( ! pkg . equals ( lastPackage ) ) { out . print ( "" ) ; print ( pkg ) ; out . println ( "" ) ; } lastPackage = pkg ; printClass ( clazz ) ; if ( clazz . getId ( ) != - ) { out . print ( "" + clazz . getIdString ( ) + "" ) ; } out . println ( "" ) ; } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; if ( excludePlatform ) { out . print ( "" ) ; print ( "" ) ; } else { out . print ( "" ) ; print ( "" ) ; } out . println ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; if ( oqlSupported ) { out . println ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; } out . println ( "" ) ; endHtml ( ) ; } } package com . sun . tools . hat . internal . server ; import java . io . PrintWriter ; import com . google . common . base . Function ; import com . google . common . base . Preconditions ; import com . google . common . base . Strings ; import com . google . common . collect . Collections2 ; import com . google . common . collect . ImmutableListMultimap ; import com . google . common . collect . ImmutableMultimap ; import com . google . common . collect . Iterables ; import com . google . common . collect . Multimap ; import com . sun . tools . hat . internal . lang . CollectionModel ; import com . sun . tools . hat . internal . lang . MapModel ; import com . sun . tools . hat . internal . lang . Model ; import com . sun . tools . hat . internal . lang . ModelFactory ; import com . sun . tools . hat . internal . lang . ModelVisitor ; import com . sun . tools . hat . internal . lang . ObjectModel ; import com . sun . tools . hat . internal . lang . ScalarModel ; import com . sun . tools . hat . internal . model . * ; import com . sun . tools . hat . internal . util . Misc ; import java . net . URLEncoder ; import java . util . Collection ; import java . util . Formatter ; import java . util . Map ; import java . io . UnsupportedEncodingException ; abstract class QueryHandler implements Runnable { protected enum GetIdString implements Function < JavaClass , String > { INSTANCE ; @ Override public String apply ( JavaClass clazz ) { return clazz . getIdString ( ) ; } } protected static class ClassResolver implements Function < String , JavaClass > { private final Snapshot snapshot ; private final boolean valueRequired ; public ClassResolver ( Snapshot snapshot , boolean valueRequired ) { this . snapshot = snapshot ; this . valueRequired = valueRequired ; } @ Override public JavaClass apply ( String name ) { if ( name == null && ! valueRequired ) { return null ; } JavaClass result = snapshot . findClass ( name ) ; Preconditions . checkNotNull ( result , "" , name ) ; return result ; } } protected String path ; protected String urlStart ; protected String query ; protected PrintWriter out ; protected Snapshot snapshot ; protected ImmutableListMultimap < String , String > params ; void setPath ( String s ) { path = s ; } void setUrlStart ( String s ) { urlStart = s ; } void setQuery ( String s ) { query = s ; } void setOutput ( PrintWriter o ) { this . out = o ; } void setSnapshot ( Snapshot ss ) { this . snapshot = ss ; } void setParams ( ImmutableListMultimap < String , String > params ) { this . params = params ; } protected static String encodeForURL ( String s ) { try { s = URLEncoder . encode ( s , "" ) ; } catch ( UnsupportedEncodingException ex ) { throw new AssertionError ( ex ) ; } return s ; } protected void startHtml ( String title ) { out . print ( "" ) ; print ( title ) ; out . println ( "" ) ; out . println ( "" ) ; print ( title ) ; out . println ( "" ) ; } protected void endHtml ( ) { out . println ( "" ) ; } protected void error ( String msg ) { out . println ( Misc . encodeHtml ( msg ) ) ; } protected void printAnchorStart ( ) { out . print ( "" ) ; out . print ( urlStart ) ; } protected void printThingAnchorTag ( long id ) { printAnchorStart ( ) ; out . print ( "" ) ; printHex ( id ) ; out . print ( "" ) ; } protected void printObject ( JavaObject obj ) { printThing ( obj ) ; } protected void printThing ( JavaThing thing ) { printThing ( thing , false ) ; } protected void printThing ( JavaThing thing , boolean simple ) { if ( thing == null ) { out . print ( "" ) ; return ; } if ( thing instanceof JavaHeapObject ) { JavaHeapObject ho = ( JavaHeapObject ) thing ; long id = ho . getId ( ) ; if ( id != - ) { printThingAnchorTag ( id ) ; if ( ho . isNew ( ) ) out . println ( "" ) ; } Model model = simple ? null : getModelFor ( thing ) ; printSummary ( model , thing ) ; if ( id != - ) { if ( ho . isNew ( ) ) out . println ( "" ) ; out . println ( "" ) ; printDetail ( model , ho . getSize ( ) ) ; } } else { print ( thing . toString ( ) ) ; } } protected void printRoot ( Root root ) { StackTrace st = root . getStackTrace ( ) ; boolean traceAvailable = ( st != null ) && ( st . getFrames ( ) . length != ) ; if ( traceAvailable ) { printAnchorStart ( ) ; out . print ( "" ) ; printHex ( root . getIndex ( ) ) ; out . print ( "" ) ; } print ( root . getDescription ( ) ) ; if ( traceAvailable ) { out . print ( "" ) ; } } protected void printClass ( JavaClass clazz ) { if ( clazz == null ) { out . println ( "" ) ; return ; } printAnchorStart ( ) ; out . print ( "" ) ; print ( encodeForURL ( clazz ) ) ; out . print ( "" ) ; print ( clazz . toString ( ) ) ; out . println ( "" ) ; } protected static String encodeForURL ( JavaClass clazz ) { if ( clazz . getId ( ) == - ) { return encodeForURL ( clazz . getName ( ) ) ; } else { return clazz . getIdString ( ) ; } } protected void printField ( JavaField field ) { print ( field . getName ( ) + "" + field . getSignature ( ) + "" ) ; } protected void printStatic ( JavaStatic member ) { JavaField f = member . getField ( ) ; printField ( f ) ; out . print ( "" ) ; if ( f . hasId ( ) ) { JavaThing t = member . getValue ( ) ; printThing ( t ) ; } else { print ( member . getValue ( ) . toString ( ) ) ; } } protected void printStackTrace ( StackTrace trace ) { StackFrame [ ] frames = trace . getFrames ( ) ; for ( StackFrame f : frames ) { String clazz = f . getClassName ( ) ; out . print ( "" ) ; print ( clazz ) ; out . print ( "" ) ; print ( "" + f . getMethodName ( ) + "" + f . getMethodSignature ( ) + "" ) ; out . print ( "" ) ; print ( f . getSourceFileName ( ) + "" + f . getLineNumber ( ) ) ; out . println ( "" ) ; } } protected void printHex ( long addr ) { if ( snapshot . getIdentifierSize ( ) == ) { out . print ( Misc . toHex ( ( int ) addr ) ) ; } else { out . print ( Misc . toHex ( addr ) ) ; } } protected long parseHex ( String value ) { return Misc . parseHex ( value ) ; } protected void print ( String str ) { out . print ( Misc . encodeHtml ( str ) ) ; } protected Model getModelFor ( JavaThing thing ) { for ( ModelFactory factory : snapshot . getModelFactories ( ) ) { Model model = factory . newModel ( thing ) ; if ( model != null ) { return model ; } } return null ; } protected void printSummary ( Model model , final JavaThing thing ) { if ( model != null ) { model . visit ( new ModelVisitor ( ) { @ Override public void visit ( ScalarModel model ) { print ( model . toString ( ) ) ; } @ Override public void visit ( CollectionModel model ) { print ( thing . toString ( ) ) ; } @ Override public void visit ( MapModel model ) { print ( thing . toString ( ) ) ; } @ Override public void visit ( ObjectModel model ) { print ( model . getClassName ( ) ) ; } } ) ; } else { print ( thing . toString ( ) ) ; } } private void printDetail ( Model model , int size ) { if ( model != null ) { model . visit ( new ModelVisitor ( ) { @ Override public void visit ( ScalarModel model ) { } @ Override public void visit ( CollectionModel model ) { out . print ( "" ) ; Collection < JavaThing > collection = model . getCollection ( ) ; boolean first = true ; for ( JavaThing thing : Iterables . limit ( collection , ) ) { if ( first ) { first = false ; } else { out . print ( "" ) ; } printThing ( thing , true ) ; } if ( collection . size ( ) > ) { out . printf ( "" , collection . size ( ) - ) ; } out . print ( "" ) ; } @ Override public void visit ( MapModel model ) { out . print ( "" ) ; Map < JavaThing , JavaThing > map = model . getMap ( ) ; boolean first = true ; for ( Map . Entry < JavaThing , JavaThing > entry : Iterables . limit ( map . entrySet ( ) , ) ) { if ( first ) { first = false ; } else { out . print ( "" ) ; } printThing ( entry . getKey ( ) , true ) ; out . print ( "" ) ; printThing ( entry . getValue ( ) , true ) ; } if ( map . size ( ) > ) { out . printf ( "" , map . size ( ) - ) ; } out . print ( "" ) ; } @ Override public void visit ( ObjectModel model ) { out . print ( "" ) ; Map < String , JavaThing > map = model . getProperties ( ) ; boolean first = true ; for ( Map . Entry < String , JavaThing > entry : map . entrySet ( ) ) { if ( first ) { first = false ; } else { out . print ( "" ) ; } out . print ( entry . getKey ( ) ) ; out . print ( "" ) ; printThing ( entry . getValue ( ) , true ) ; } out . print ( "" ) ; } } ) ; } else { out . print ( "" + size + "" ) ; } } protected static String formatLink ( String path , String pathInfo , String label , Multimap < String , String > params ) { StringBuilder sb = new StringBuilder ( ) ; Formatter fmt = new Formatter ( sb ) ; fmt . format ( "" , path , encodeForURL ( Strings . nullToEmpty ( pathInfo ) ) ) ; if ( params != null ) { for ( Map . Entry < String , String > entry : params . entries ( ) ) { fmt . format ( "" , encodeForURL ( entry . getKey ( ) ) , encodeForURL ( entry . getValue ( ) ) ) ; } } sb . setLength ( sb . length ( ) - ) ; fmt . format ( "" , Misc . encodeHtml ( label ) ) ; return sb . toString ( ) ; } protected static String formatLink ( String path , String pathInfo , String label , String name , JavaClass clazz , Collection < JavaClass > referrers , JavaClass tail , Multimap < String , String > params ) { ImmutableListMultimap . Builder < String , String > builder = ImmutableListMultimap . builder ( ) ; if ( params != null ) { builder . putAll ( params ) ; } if ( clazz != null ) { if ( name != null ) { builder . put ( name , clazz . getIdString ( ) ) ; } else { pathInfo = clazz . getIdString ( ) ; } if ( referrers != null ) { builder . putAll ( "" , Collections2 . transform ( referrers , GetIdString . INSTANCE ) ) ; } if ( tail != null ) { builder . put ( "" , tail . getIdString ( ) ) ; } } return formatLink ( path , pathInfo , label , builder . build ( ) ) ; } protected void printBreadcrumbs ( String path , String pathInfo , String name , JavaClass clazz , Iterable < JavaClass > referrers , Multimap < String , String > params ) { ImmutableMultimap . Builder < String , String > builder = ImmutableMultimap . builder ( ) ; if ( params != null ) { builder . putAll ( params ) ; } if ( clazz != null ) { out . print ( "" ) ; if ( name != null ) { builder . put ( name , clazz . getIdString ( ) ) ; } else { pathInfo = clazz . getIdString ( ) ; } out . print ( formatLink ( path , pathInfo , clazz . getName ( ) , builder . build ( ) ) ) ; for ( JavaClass referrer : referrers ) { out . print ( "" ) ; builder . put ( "" , referrer . getIdString ( ) ) ; out . print ( formatLink ( path , pathInfo , referrer . getName ( ) , builder . build ( ) ) ) ; } out . println ( "" ) ; } } } package com . sun . tools . hat . internal . server ; import java . net . Socket ; import java . net . URLDecoder ; import java . util . regex . Pattern ; import java . io . InputStream ; import java . io . BufferedInputStream ; import java . io . IOException ; import java . io . BufferedWriter ; import java . io . PrintWriter ; import java . io . OutputStreamWriter ; import java . io . UnsupportedEncodingException ; import com . google . common . base . Strings ; import com . google . common . base . Supplier ; import com . google . common . collect . ImmutableList ; import com . google . common . collect . ImmutableListMultimap ; import com . google . common . io . Closeables ; import com . sun . tools . hat . internal . model . Snapshot ; import com . sun . tools . hat . internal . oql . OQLEngine ; import com . sun . tools . hat . internal . util . Misc ; public class HttpReader implements Runnable { private class EngineThreadLocal extends ThreadLocal < OQLEngine > { @ Override protected OQLEngine initialValue ( ) { return new OQLEngine ( snapshot ) ; } } private static class HandlerRoute { private static final Pattern SLASH = Pattern . compile ( "" ) ; private static final Pattern AMPER = Pattern . compile ( "" ) ; private final String name ; private final String [ ] parts ; private final Supplier < QueryHandler > handlerFactory ; public HandlerRoute ( String name , Supplier < QueryHandler > handlerFactory ) { this . name = name ; this . parts = SLASH . split ( name , - ) ; this . handlerFactory = handlerFactory ; } private static String decode ( String str ) { try { return URLDecoder . decode ( str , "" ) ; } catch ( UnsupportedEncodingException exc ) { throw new AssertionError ( exc ) ; } } public QueryHandler parse ( String queryString ) { int qpos = queryString . indexOf ( '' ) ; String query = qpos == - ? queryString : queryString . substring ( , qpos ) ; String [ ] qparts = SLASH . split ( query , - ) ; if ( qparts . length != parts . length ) { return null ; } StringBuilder path = new StringBuilder ( ) ; String pathInfo = null ; StringBuilder urlStart = new StringBuilder ( ) ; for ( int i = ; i < parts . length ; ++ i ) { if ( parts [ i ] . equals ( "" ) ) { pathInfo = decode ( qparts [ i ] ) ; } else if ( parts [ i ] . equals ( qparts [ i ] ) ) { path . append ( '' ) . append ( parts [ i ] ) ; } else { return null ; } if ( i > ) { urlStart . append ( "" ) ; } } ImmutableListMultimap . Builder < String , String > params = ImmutableListMultimap . builder ( ) ; if ( qpos != - ) { for ( String item : AMPER . split ( queryString . substring ( qpos + ) ) ) { int epos = item . indexOf ( '' ) ; if ( epos != - ) { params . put ( decode ( item . substring ( , epos ) ) , decode ( item . substring ( epos + ) ) ) ; } } } QueryHandler handler = handlerFactory . get ( ) ; handler . setPath ( path . substring ( ) ) ; handler . setUrlStart ( urlStart . toString ( ) ) ; handler . setQuery ( pathInfo ) ; handler . setParams ( params . build ( ) ) ; return handler ; } @ Override public String toString ( ) { return name ; } } private final Socket socket ; private PrintWriter out ; private final Snapshot snapshot ; private final EngineThreadLocal engine = new EngineThreadLocal ( ) ; private final ImmutableList < HandlerRoute > routes = makeHandlerRoutes ( ) ; private ImmutableList < HandlerRoute > makeHandlerRoutes ( ) { final boolean isOQLSupported = OQLEngine . isOQLSupported ( ) ; ImmutableList . Builder < HandlerRoute > builder = ImmutableList . builder ( ) ; if ( isOQLSupported ) { builder . add ( new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new OQLQuery ( engine ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new OQLHelp ( ) ; } } ) ) ; } builder . add ( new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new AllClassesQuery ( true , isOQLSupported ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new AllClassesQuery ( false , isOQLSupported ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new AllRootsQuery ( ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new InstancesCountQuery ( true ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new InstancesCountQuery ( false ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new InstancesQuery ( false , false ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new InstancesQuery ( false , true ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new InstancesQuery ( true , false ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new InstancesQuery ( true , true ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new ObjectQuery ( ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new ClassQuery ( ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new RootsQuery ( false ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new RootsQuery ( true ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new ReachableQuery ( ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new RootStackQuery ( ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new HistogramQuery ( ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new RefsByTypeQuery ( ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new FinalizerSummaryQuery ( ) ; } } ) , new HandlerRoute ( "" , new Supplier < QueryHandler > ( ) { public QueryHandler get ( ) { return new FinalizerObjectsQuery ( ) ; } } ) ) ; return builder . build ( ) ; } public HttpReader ( Socket s , Snapshot snapshot ) { this . socket = s ; this . snapshot = snapshot ; } public void run ( ) { InputStream in = null ; try { in = new BufferedInputStream ( socket . getInputStream ( ) ) ; out = new PrintWriter ( new BufferedWriter ( new OutputStreamWriter ( socket . getOutputStream ( ) , "" ) ) ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( ) ; if ( in . read ( ) != '' || in . read ( ) != '' || in . read ( ) != '' || in . read ( ) != '' ) { outputError ( "" ) ; } int data ; StringBuilder queryBuf = new StringBuilder ( ) ; while ( ( data = in . read ( ) ) != - && data != '' ) { char ch = ( char ) data ; queryBuf . append ( ch ) ; } String query = queryBuf . toString ( ) ; if ( snapshot == null ) { outputError ( "" ) ; return ; } QueryHandler handler = null ; for ( HandlerRoute route : routes ) { handler = route . parse ( query ) ; if ( handler != null ) { break ; } } if ( handler != null ) { handler . setOutput ( out ) ; handler . setSnapshot ( snapshot ) ; try { handler . run ( ) ; } catch ( RuntimeException ex ) { ex . printStackTrace ( ) ; outputError ( ex . getMessage ( ) ) ; } } else { outputError ( "" + query + "" ) ; } } catch ( IOException ex ) { ex . printStackTrace ( ) ; } finally { Closeables . closeQuietly ( out ) ; Closeables . closeQuietly ( in ) ; try { socket . close ( ) ; } catch ( IOException ignored ) { } } } private void outputError ( String msg ) { out . println ( ) ; out . println ( "" ) ; out . println ( Misc . encodeHtml ( Strings . nullToEmpty ( msg ) ) ) ; out . println ( "" ) ; } } package com . sun . tools . hat . internal . server ; import com . sun . tools . hat . internal . model . * ; class RootStackQuery extends QueryHandler { public RootStackQuery ( ) { } public void run ( ) { int index = ( int ) parseHex ( query ) ; Root root = snapshot . getRootAt ( index ) ; if ( root == null ) { error ( "" + index + "" ) ; return ; } StackTrace st = root . getStackTrace ( ) ; if ( st == null || st . getFrames ( ) . length == ) { error ( "" + root . getDescription ( ) ) ; return ; } startHtml ( "" + root . getDescription ( ) ) ; out . println ( "" ) ; printStackTrace ( st ) ; out . println ( "" ) ; endHtml ( ) ; } } package com . sun . tools . hat . internal . server ; import com . google . common . base . Predicate ; import com . google . common . collect . Iterables ; import com . google . common . io . Closeables ; import com . sun . tools . hat . internal . model . JavaClass ; import java . util . ArrayList ; import java . util . List ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . BufferedReader ; import java . io . IOException ; public class PlatformClasses { static volatile List < String > names = null ; public static List < String > getNames ( ) { if ( names == null ) { List < String > list = new ArrayList < String > ( ) ; InputStream str = PlatformClasses . class . getResourceAsStream ( "" ) ; if ( str != null ) { BufferedReader rdr = null ; try { rdr = new BufferedReader ( new InputStreamReader ( str ) ) ; String s ; while ( ( s = rdr . readLine ( ) ) != null ) { if ( ! s . isEmpty ( ) ) { list . add ( s ) ; } } } catch ( IOException ex ) { ex . printStackTrace ( ) ; } finally { Closeables . closeQuietly ( rdr ) ; Closeables . closeQuietly ( str ) ; } } names = list ; } return names ; } public static boolean isPlatformClass ( JavaClass clazz ) { if ( clazz . isBootstrap ( ) ) { return true ; } String name = clazz . getName ( ) ; if ( name . startsWith ( "" ) ) { int index = name . lastIndexOf ( '' ) ; if ( index != - ) { if ( name . charAt ( index + ) != '' ) { return true ; } name = name . substring ( index + ) ; } } final String haystack = name ; return Iterables . any ( getNames ( ) , new Predicate < String > ( ) { @ Override public boolean apply ( String needle ) { return haystack . startsWith ( needle ) ; } } ) ; } } package com . sun . tools . hat . internal . server ; import com . google . common . base . Function ; import com . google . common . collect . Collections2 ; import com . google . common . collect . ImmutableMultimap ; import com . google . common . collect . ImmutableMultiset ; import com . google . common . collect . ImmutableSet ; import com . google . common . collect . ImmutableSetMultimap ; import com . google . common . collect . Iterables ; import com . google . common . collect . Multimaps ; import com . google . common . collect . Ordering ; import com . sun . tools . hat . internal . model . JavaClass ; import com . sun . tools . hat . internal . model . JavaHeapObject ; import com . sun . tools . hat . internal . model . Snapshot ; import com . sun . tools . hat . internal . util . Misc ; import java . util . Arrays ; import java . util . Collection ; import java . util . Comparator ; public class HistogramQuery extends QueryHandler { private enum Sorters implements Function < JavaClass , Comparable < ? > > , Comparator < JavaClass > { BY_NAME { @ Override public String apply ( JavaClass clazz ) { return clazz . getName ( ) ; } } ; private final Ordering < JavaClass > ordering ; private Sorters ( ) { ordering = Ordering . natural ( ) . onResultOf ( this ) ; } @ Override public int compare ( JavaClass lhs , JavaClass rhs ) { return ordering . compare ( lhs , rhs ) ; } } private static abstract class MetricsProvider { private final JavaClass [ ] classes ; protected MetricsProvider ( JavaClass [ ] classes ) { this . classes = classes ; } public abstract int getCount ( JavaClass clazz ) ; public abstract long getSize ( JavaClass clazz ) ; public int getRefCount ( JavaClass clazz ) { throw new UnsupportedOperationException ( ) ; } public Function < JavaClass , Integer > getCountMethod ( ) { return new Function < JavaClass , Integer > ( ) { public Integer apply ( JavaClass clazz ) { return getCount ( clazz ) ; } } ; } public Function < JavaClass , Long > getSizeMethod ( ) { return new Function < JavaClass , Long > ( ) { public Long apply ( JavaClass clazz ) { return getSize ( clazz ) ; } } ; } public Function < JavaClass , Integer > getRefCountMethod ( ) { return new Function < JavaClass , Integer > ( ) { public Integer apply ( JavaClass clazz ) { return getRefCount ( clazz ) ; } } ; } public JavaClass [ ] getClasses ( ) { return classes . clone ( ) ; } public boolean hasRefCount ( ) { return false ; } } private static class GlobalMetricsProvider extends MetricsProvider { public GlobalMetricsProvider ( Snapshot snapshot ) { super ( snapshot . getClassesArray ( ) ) ; } @ Override public int getCount ( JavaClass clazz ) { return clazz . getInstancesCount ( false ) ; } @ Override public long getSize ( JavaClass clazz ) { return clazz . getTotalInstanceSize ( ) ; } } private static class RefereeMetricsProvider extends MetricsProvider { private enum GetClass implements Function < JavaHeapObject , JavaClass > { INSTANCE ; @ Override public JavaClass apply ( JavaHeapObject obj ) { return obj . getClazz ( ) ; } } final ImmutableMultimap < JavaClass , JavaHeapObject > referrers ; final ImmutableMultiset < JavaClass > references ; private RefereeMetricsProvider ( ImmutableMultimap < JavaClass , JavaHeapObject > referrers , ImmutableMultiset < JavaClass > references ) { super ( referrers . keySet ( ) . toArray ( new JavaClass [ ] ) ) ; this . referrers = referrers ; this . references = references ; } public static RefereeMetricsProvider make ( JavaClass referee , Collection < JavaClass > referrers ) { ImmutableSet < JavaHeapObject > instances = Misc . getInstances ( referee , false , referrers ) ; return new RefereeMetricsProvider ( Multimaps . index ( Misc . getReferrers ( instances ) , GetClass . INSTANCE ) , getReferences ( instances ) . keys ( ) ) ; } @ Override public int getCount ( JavaClass clazz ) { return referrers . get ( clazz ) . size ( ) ; } @ Override public long getSize ( JavaClass clazz ) { Collection < JavaHeapObject > subset = referrers . get ( clazz ) ; if ( ! clazz . isArray ( ) ) { return ( long ) clazz . getInstanceSize ( ) * subset . size ( ) ; } long size = ; for ( JavaHeapObject instance : subset ) { size += instance . getSize ( ) ; } return size ; } @ Override public int getRefCount ( JavaClass clazz ) { return references . count ( clazz ) ; } @ Override public boolean hasRefCount ( ) { return true ; } private static ImmutableMultimap < JavaClass , JavaHeapObject > getReferences ( Iterable < JavaHeapObject > instances ) { ImmutableSetMultimap . Builder < JavaClass , JavaHeapObject > builder = ImmutableSetMultimap . builder ( ) ; for ( JavaHeapObject instance : instances ) { for ( JavaHeapObject referrer : instance . getReferers ( ) ) { builder . put ( referrer . getClazz ( ) , instance ) ; } } return builder . build ( ) ; } } public void run ( ) { ClassResolver resolver = new ClassResolver ( snapshot , false ) ; JavaClass referee = resolver . apply ( Iterables . getOnlyElement ( params . get ( "" ) , null ) ) ; Collection < JavaClass > referrers = Collections2 . transform ( params . get ( "" ) , resolver ) ; MetricsProvider metrics ; if ( referee == null ) { metrics = new GlobalMetricsProvider ( snapshot ) ; } else { metrics = RefereeMetricsProvider . make ( referee , referrers ) ; } Comparator < JavaClass > comparator ; if ( query . equals ( "" ) ) { comparator = Ordering . natural ( ) . reverse ( ) . onResultOf ( metrics . getCountMethod ( ) ) ; } else if ( query . equals ( "" ) ) { comparator = Sorters . BY_NAME ; } else if ( query . equals ( "" ) || ! metrics . hasRefCount ( ) ) { comparator = Ordering . natural ( ) . reverse ( ) . onResultOf ( metrics . getSizeMethod ( ) ) ; } else { comparator = Ordering . natural ( ) . reverse ( ) . onResultOf ( metrics . getRefCountMethod ( ) ) ; } JavaClass [ ] classes = metrics . getClasses ( ) ; Arrays . sort ( classes , comparator ) ; startHtml ( "" ) ; printBreadcrumbs ( query , referee , referrers ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; printHeader ( "" , "" , referee , referrers ) ; if ( metrics . hasRefCount ( ) ) { printHeader ( "" , "" , referee , referrers ) ; } printHeader ( "" , "" , referee , referrers ) ; printHeader ( "" , "" , referee , referrers ) ; out . println ( "" ) ; for ( JavaClass clazz : classes ) { out . print ( "" ) ; printClass ( clazz ) ; if ( referee == null ) { out . printf ( "" , formatLink ( query , "" , clazz , null , null ) ) ; } else { out . printf ( "" , formatLink ( query , "" , clazz , null , null ) , formatLink ( query , "" , referee , referrers , clazz ) ) ; } out . println ( "" ) ; if ( metrics . hasRefCount ( ) ) { String refCount = String . valueOf ( metrics . getRefCount ( clazz ) ) ; ImmutableMultimap < String , String > params = ImmutableMultimap . of ( "" , "" ) ; if ( referee == null ) { out . printf ( "" , formatLink ( "" , null , refCount , null , clazz , null , null , params ) ) ; } else { out . printf ( "" , formatLink ( "" , null , refCount , null , referee , referrers , clazz , params ) ) ; } } String count = String . valueOf ( metrics . getCount ( clazz ) ) ; if ( referee == null ) { out . printf ( "" , formatLink ( "" , null , count , null , clazz , null , null , null ) ) ; } else { out . printf ( "" , formatLink ( "" , null , count , null , referee , referrers , clazz , null ) ) ; } out . printf ( "" , metrics . getSize ( clazz ) ) ; } out . println ( "" ) ; endHtml ( ) ; } private void printBreadcrumbs ( String pathInfo , JavaClass referee , Collection < JavaClass > referrers ) { super . printBreadcrumbs ( path , pathInfo , "" , referee , referrers , null ) ; } private void printHeader ( String pathInfo , String label , JavaClass referee , Collection < JavaClass > referrers ) { out . printf ( "" , formatLink ( pathInfo , label , referee , referrers , null ) ) ; } private String formatLink ( String pathInfo , String label , JavaClass referee , Collection < JavaClass > referrers , JavaClass tail ) { return formatLink ( path , pathInfo , label , "" , referee , referrers , tail , null ) ; } } package com . sun . tools . hat . internal . server ; import com . google . common . primitives . Longs ; import com . sun . tools . hat . internal . model . * ; import java . util . * ; public class FinalizerSummaryQuery extends QueryHandler { public void run ( ) { startHtml ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; printFinalizerSummary ( snapshot . getFinalizerObjects ( ) ) ; endHtml ( ) ; } private static class HistogramElement implements Comparable < HistogramElement > { public HistogramElement ( JavaClass clazz ) { this . clazz = clazz ; } public void updateCount ( ) { this . count ++ ; } @ Override public int compareTo ( HistogramElement other ) { return Longs . compare ( other . count , count ) ; } public JavaClass getClazz ( ) { return clazz ; } public long getCount ( ) { return count ; } private final JavaClass clazz ; private long count ; } private void printFinalizerSummary ( Collection < ? extends JavaHeapObject > objs ) { int count = ; Map < JavaClass , HistogramElement > map = new HashMap < JavaClass , HistogramElement > ( ) ; for ( JavaHeapObject obj : objs ) { count ++ ; JavaClass clazz = obj . getClazz ( ) ; if ( ! map . containsKey ( clazz ) ) { map . put ( clazz , new HistogramElement ( clazz ) ) ; } HistogramElement element = map . get ( clazz ) ; element . updateCount ( ) ; } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; if ( count != ) { out . print ( "" ) ; } else { out . print ( "" ) ; } out . println ( "" ) ; out . print ( count ) ; out . println ( "" ) ; if ( count == ) { return ; } HistogramElement [ ] elements = map . values ( ) . toArray ( new HistogramElement [ map . size ( ) ] ) ; Arrays . sort ( elements ) ; out . println ( "" ) ; out . println ( "" ) ; for ( HistogramElement element : elements ) { out . println ( "" ) ; out . println ( element . getCount ( ) ) ; out . println ( "" ) ; printClass ( element . getClazz ( ) ) ; out . println ( "" ) ; } out . println ( "" ) ; } } package com . sun . tools . hat . internal . server ; import com . google . common . base . Function ; import com . google . common . base . Predicate ; import com . google . common . collect . Collections2 ; import com . google . common . collect . ComparisonChain ; import com . google . common . collect . Ordering ; import com . sun . tools . hat . internal . model . * ; import java . util . Arrays ; import java . util . Comparator ; class InstancesCountQuery extends QueryHandler { private enum NonPlatformPredicate implements Predicate < JavaClass > { INSTANCE ; @ Override public boolean apply ( JavaClass clazz ) { return ! PlatformClasses . isPlatformClass ( clazz ) ; } } private enum Sorters implements Function < JavaClass , Comparable < ? > > , Comparator < JavaClass > { BY_INSTANCE_COUNT { @ Override public Integer apply ( JavaClass cls ) { return cls . getInstancesCount ( false ) ; } } , BY_ARRAY_TYPE { @ Override public Boolean apply ( JavaClass cls ) { return cls . getName ( ) . startsWith ( "" ) ; } } , BY_NAME { @ Override public String apply ( JavaClass cls ) { return cls . getName ( ) ; } } ; private final Ordering < JavaClass > ordering ; private Sorters ( ) { this . ordering = Ordering . natural ( ) . onResultOf ( this ) ; } @ Override public int compare ( JavaClass lhs , JavaClass rhs ) { return ordering . compare ( lhs , rhs ) ; } } private final boolean excludePlatform ; public InstancesCountQuery ( boolean excludePlatform ) { this . excludePlatform = excludePlatform ; } public void run ( ) { if ( excludePlatform ) { startHtml ( "" ) ; } else { startHtml ( "" ) ; } JavaClass [ ] classes = snapshot . getClassesArray ( ) ; if ( excludePlatform ) { classes = Collections2 . filter ( Arrays . asList ( classes ) , NonPlatformPredicate . INSTANCE ) . toArray ( new JavaClass [ ] ) ; } Arrays . sort ( classes , new Comparator < JavaClass > ( ) { public int compare ( JavaClass lhs , JavaClass rhs ) { return ComparisonChain . start ( ) . compare ( rhs , lhs , Sorters . BY_INSTANCE_COUNT ) . compare ( lhs , rhs , Sorters . BY_ARRAY_TYPE ) . compare ( lhs , rhs , Sorters . BY_NAME ) . result ( ) ; } } ) ; long totalSize = ; long instances = ; for ( JavaClass clazz : classes ) { int count = clazz . getInstancesCount ( false ) ; print ( "" + count ) ; printAnchorStart ( ) ; out . print ( "" + encodeForURL ( clazz ) ) ; out . print ( "" ) ; if ( count == ) { print ( "" ) ; } else { print ( "" ) ; } out . print ( "" ) ; if ( snapshot . getHasNewSet ( ) ) { int newInst = ; for ( JavaHeapObject obj : clazz . getInstances ( false ) ) { if ( obj . isNew ( ) ) { newInst ++ ; } } print ( "" ) ; printAnchorStart ( ) ; out . print ( "" + encodeForURL ( clazz ) ) ; out . print ( "" ) ; print ( "" + newInst + "" ) ; out . print ( "" ) ; } print ( "" ) ; printClass ( clazz ) ; out . println ( "" ) ; instances += count ; totalSize += clazz . getTotalInstanceSize ( ) ; } out . println ( "" + instances + "" + totalSize + "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . print ( "" ) ; printAnchorStart ( ) ; if ( ! excludePlatform ) { out . print ( "" ) ; print ( "" ) ; } else { out . print ( "" ) ; print ( "" ) ; } out . println ( "" ) ; out . print ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; out . print ( "" ) ; printAnchorStart ( ) ; out . print ( "" ) ; print ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; endHtml ( ) ; } } package com . sun . tools . hat . internal . server ; import java . io . * ; class OQLHelp extends QueryHandler { public OQLHelp ( ) { } public void run ( ) { InputStream is = getClass ( ) . getResourceAsStream ( "" ) ; int ch = - ; try { is = new BufferedInputStream ( is ) ; while ( ( ch = is . read ( ) ) != - ) { out . print ( ( char ) ch ) ; } } catch ( Exception exp ) { out . println ( exp . getMessage ( ) ) ; out . println ( "" ) ; exp . printStackTrace ( out ) ; out . println ( "" ) ; } } } package com . sun . tools . hat . internal . server ; import java . net . Socket ; import java . net . ServerSocket ; import java . util . concurrent . Executor ; import java . util . concurrent . Executors ; import java . io . IOException ; import com . sun . tools . hat . internal . model . Snapshot ; public class QueryListener implements Runnable { private final Executor executor = Executors . newCachedThreadPool ( ) ; private Snapshot snapshot ; private final int port ; public QueryListener ( int port ) { this . port = port ; this . snapshot = null ; } public void setModel ( Snapshot ss ) { this . snapshot = ss ; } public void run ( ) { try { waitForRequests ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; System . exit ( ) ; } } private void waitForRequests ( ) throws IOException { ServerSocket ss = new ServerSocket ( port ) ; while ( true ) { Socket s = ss . accept ( ) ; executor . execute ( new HttpReader ( s , snapshot ) ) ; } } } package com . sun . tools . hat . internal . server ; import java . util . Arrays ; import java . util . Comparator ; import com . google . common . base . Function ; import com . google . common . collect . ComparisonChain ; import com . google . common . collect . Ordering ; import com . sun . tools . hat . internal . model . * ; class RootsQuery extends QueryHandler { private enum Sorters implements Function < ReferenceChain , Comparable < ? > > , Comparator < ReferenceChain > { BY_ROOT_TYPE { @ Override public Integer apply ( ReferenceChain chain ) { return chain . getObj ( ) . getRoot ( ) . getType ( ) ; } } , BY_DEPTH { @ Override public Integer apply ( ReferenceChain chain ) { return chain . getDepth ( ) ; } } ; private final Ordering < ReferenceChain > ordering ; private Sorters ( ) { this . ordering = Ordering . natural ( ) . onResultOf ( this ) ; } @ Override public int compare ( ReferenceChain lhs , ReferenceChain rhs ) { return ordering . compare ( lhs , rhs ) ; } } private final boolean includeWeak ; public RootsQuery ( boolean includeWeak ) { this . includeWeak = includeWeak ; } public void run ( ) { long id = parseHex ( query ) ; JavaHeapObject target = snapshot . findThing ( id ) ; if ( target == null ) { startHtml ( "" ) ; error ( "" ) ; endHtml ( ) ; return ; } if ( includeWeak ) { startHtml ( "" + target + "" ) ; } else { startHtml ( "" + target + "" ) ; } out . flush ( ) ; ReferenceChain [ ] refs = snapshot . rootsetReferencesTo ( target , includeWeak ) ; Arrays . sort ( refs , new Comparator < ReferenceChain > ( ) { public int compare ( ReferenceChain left , ReferenceChain right ) { return ComparisonChain . start ( ) . compare ( right , left , Sorters . BY_ROOT_TYPE ) . compare ( left , right , Sorters . BY_DEPTH ) . result ( ) ; } } ) ; out . print ( "" ) ; printThing ( target ) ; out . println ( "" ) ; int lastType = Root . INVALID_TYPE ; for ( ReferenceChain ref : refs ) { Root root = ref . getObj ( ) . getRoot ( ) ; if ( root . getType ( ) != lastType ) { lastType = root . getType ( ) ; out . print ( "" ) ; print ( root . getTypeName ( ) + "" ) ; out . println ( "" ) ; } out . print ( "" ) ; printRoot ( root ) ; if ( root . getReferer ( ) != null ) { out . print ( "" ) ; printThingAnchorTag ( root . getReferer ( ) . getId ( ) ) ; print ( root . getReferer ( ) . toString ( ) ) ; out . print ( "" ) ; } out . print ( "" ) ; while ( ref != null ) { ReferenceChain next = ref . getNext ( ) ; JavaHeapObject obj = ref . getObj ( ) ; print ( "" ) ; printThing ( obj ) ; if ( next != null ) { print ( "" + obj . describeReferenceTo ( next . getObj ( ) , snapshot ) + "" ) ; } out . println ( "" ) ; ref = next ; } } out . println ( "" ) ; if ( includeWeak ) { printAnchorStart ( ) ; out . print ( "" ) ; printHex ( id ) ; out . print ( "" ) ; out . println ( "" ) ; endHtml ( ) ; } if ( ! includeWeak ) { printAnchorStart ( ) ; out . print ( "" ) ; printHex ( id ) ; out . print ( "" ) ; out . println ( "" ) ; } } } package com . sun . tools . hat . internal . oql ; public class OQLException extends Exception { public OQLException ( String msg ) { super ( msg ) ; } public OQLException ( String msg , Throwable cause ) { super ( msg , cause ) ; } public OQLException ( Throwable cause ) { super ( cause ) ; } } package com . sun . tools . hat . internal . oql ; import com . sun . tools . hat . internal . model . * ; import java . io . * ; import java . util . * ; import javax . script . * ; public class OQLEngine { static { ScriptEngineManager manager = new ScriptEngineManager ( ) ; ScriptEngine jse = manager . getEngineByName ( "" ) ; oqlSupported = jse != null ; } public static boolean isOQLSupported ( ) { return oqlSupported ; } public OQLEngine ( Snapshot snapshot ) { if ( ! isOQLSupported ( ) ) { throw new UnsupportedOperationException ( "" ) ; } init ( snapshot ) ; } public synchronized void executeQuery ( String query , ObjectVisitor visitor ) throws OQLException { debugPrint ( "" + query ) ; StringTokenizer st = new StringTokenizer ( query ) ; if ( st . hasMoreTokens ( ) ) { String first = st . nextToken ( ) ; if ( ! first . equals ( "" ) ) { try { Object res = evalScript ( query ) ; visitor . visit ( res ) ; } catch ( Exception e ) { throw new OQLException ( e ) ; } return ; } } else { throw new OQLException ( "" ) ; } String selectExpr = "" ; boolean seenFrom = false ; while ( st . hasMoreTokens ( ) ) { String tok = st . nextToken ( ) ; if ( tok . equals ( "" ) ) { seenFrom = true ; break ; } selectExpr += "" + tok ; } if ( selectExpr . equals ( "" ) ) { throw new OQLException ( "" ) ; } String className = null ; boolean isInstanceOf = false ; String whereExpr = null ; String identifier = null ; if ( seenFrom ) { if ( st . hasMoreTokens ( ) ) { String tmp = st . nextToken ( ) ; if ( tmp . equals ( "" ) ) { isInstanceOf = true ; if ( ! st . hasMoreTokens ( ) ) { throw new OQLException ( "" ) ; } className = st . nextToken ( ) ; } else { className = tmp ; } } else { throw new OQLException ( "" ) ; } if ( st . hasMoreTokens ( ) ) { identifier = st . nextToken ( ) ; if ( identifier . equals ( "" ) ) { throw new OQLException ( "" ) ; } if ( st . hasMoreTokens ( ) ) { String tmp = st . nextToken ( ) ; if ( ! tmp . equals ( "" ) ) { throw new OQLException ( "" ) ; } whereExpr = "" ; while ( st . hasMoreTokens ( ) ) { whereExpr += "" + st . nextToken ( ) ; } if ( whereExpr . equals ( "" ) ) { throw new OQLException ( "" ) ; } } } else { throw new OQLException ( "" ) ; } } executeQuery ( new OQLQuery ( selectExpr , isInstanceOf , className , identifier , whereExpr ) , visitor ) ; } private void executeQuery ( OQLQuery q , ObjectVisitor visitor ) throws OQLException { JavaClass clazz = null ; if ( q . className != null ) { clazz = snapshot . findClass ( q . className ) ; if ( clazz == null ) { throw new OQLException ( q . className + "" ) ; } } StringBuilder buf = new StringBuilder ( ) ; buf . append ( "" ) ; if ( q . identifier != null ) { buf . append ( q . identifier ) ; } buf . append ( "" ) ; buf . append ( q . selectExpr . replace ( '' , '' ) ) ; buf . append ( "" ) ; String selectCode = buf . toString ( ) ; debugPrint ( selectCode ) ; String whereCode = null ; if ( q . whereExpr != null ) { buf = new StringBuilder ( ) ; buf . append ( "" ) ; buf . append ( q . identifier ) ; buf . append ( "" ) ; buf . append ( q . whereExpr . replace ( '' , '' ) ) ; buf . append ( "" ) ; whereCode = buf . toString ( ) ; } debugPrint ( whereCode ) ; try { evalScript ( selectCode ) ; if ( whereCode != null ) { evalScript ( whereCode ) ; } if ( clazz != null ) { for ( JavaHeapObject obj : clazz . getInstances ( q . isInstanceOf ) ) { Object [ ] args = new Object [ ] { wrapJavaObject ( obj ) } ; boolean b = ( whereCode == null ) ; if ( ! b ) { Object res = call ( "" , args ) ; if ( res instanceof Boolean ) { b = ( ( Boolean ) res ) . booleanValue ( ) ; } else if ( res instanceof Number ) { b = ( ( Number ) res ) . intValue ( ) != ; } else { b = ( res != null ) ; } } if ( b ) { Object select = call ( "" , args ) ; if ( visitor . visit ( select ) ) return ; } } } else { Object select = call ( "" ) ; visitor . visit ( select ) ; } } catch ( Exception e ) { throw new OQLException ( e ) ; } } public Object evalScript ( String script ) throws ScriptException { return engine . eval ( script ) ; } public Object wrapJavaObject ( JavaHeapObject obj ) throws ScriptException , NoSuchMethodException { return call ( "" , obj ) ; } public Object toHtml ( Object obj ) throws ScriptException , NoSuchMethodException { return call ( "" , obj ) ; } public Object call ( String func , Object ... args ) throws ScriptException , NoSuchMethodException { return ( ( Invocable ) engine ) . invokeFunction ( func , args ) ; } private static void debugPrint ( String msg ) { if ( debug ) System . out . println ( msg ) ; } private void init ( Snapshot snapshot ) throws RuntimeException { this . snapshot = snapshot ; ScriptEngineManager manager = new ScriptEngineManager ( ) ; try { engine = manager . getEngineByName ( "" ) ; engine . eval ( new InputStreamReader ( getInitStream ( ) ) ) ; engine . put ( "" , call ( "" , snapshot ) ) ; } catch ( Exception e ) { if ( debug ) e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } } private InputStream getInitStream ( ) { return getClass ( ) . getResourceAsStream ( "" ) ; } private ScriptEngine engine ; private Snapshot snapshot ; private static boolean debug = false ; private static final boolean oqlSupported ; } package com . sun . tools . hat . internal . oql ; class OQLQuery { OQLQuery ( String selectExpr , boolean isInstanceOf , String className , String identifier , String whereExpr ) { this . selectExpr = selectExpr ; this . isInstanceOf = isInstanceOf ; this . className = className ; this . identifier = identifier ; this . whereExpr = whereExpr ; } final String selectExpr ; final boolean isInstanceOf ; final String className ; final String identifier ; final String whereExpr ; } package com . sun . tools . hat . internal . oql ; public interface ObjectVisitor { public boolean visit ( Object o ) ; } package com . sun . tools . hat . internal . util ; import com . google . common . base . Function ; import com . google . common . base . Predicate ; import com . google . common . base . Predicates ; import com . google . common . collect . ImmutableSet ; import com . google . common . collect . Sets ; import com . sun . tools . hat . internal . model . AbstractJavaHeapObjectVisitor ; import com . sun . tools . hat . internal . model . JavaClass ; import com . sun . tools . hat . internal . model . JavaHeapObject ; public class Misc { private enum GetClass implements Function < JavaHeapObject , JavaClass > { INSTANCE ; @ Override public JavaClass apply ( JavaHeapObject obj ) { return obj . getClazz ( ) ; } } private static final String digits = "" ; public final static String toHex ( int addr ) { StringBuilder sb = new StringBuilder ( "" ) ; for ( int s = ; s >= ; s -= ) { sb . append ( digits . charAt ( ( addr > > > s ) & ) ) ; } return sb . toString ( ) ; } public final static String toHex ( long addr ) { return "" + Long . toHexString ( addr ) ; } public final static long parseHex ( String value ) { long result = ; if ( value . length ( ) < || value . charAt ( ) != '' || value . charAt ( ) != '' ) { return - ; } for ( int i = ; i < value . length ( ) ; i ++ ) { result *= ; char ch = value . charAt ( i ) ; if ( ch >= '' && ch <= '' ) { result += ( ch - '' ) ; } else if ( ch >= '' && ch <= '' ) { result += ( ch - '' ) + ; } else if ( ch >= '' && ch <= '' ) { result += ( ch - '' ) + ; } else { throw new NumberFormatException ( "" + ch + "" ) ; } } return result ; } public static String encodeHtml ( String str ) { final int len = str . length ( ) ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = ; i < len ; i ++ ) { char ch = str . charAt ( i ) ; if ( ch == '' ) { buf . append ( "" ) ; } else if ( ch == '>' ) { buf . append ( "" ) ; } else if ( ch == '' ) { buf . append ( "" ) ; } else if ( ch == '' ) { buf . append ( "" ) ; } else if ( ch == '' ) { buf . append ( "" ) ; } else if ( ch < '' ) { buf . append ( "" + Integer . toString ( ch ) + "" ) ; } else if ( ! Character . isHighSurrogate ( ch ) ) { if ( Character . isLowSurrogate ( ch ) ) { throw new IllegalArgumentException ( "" ) ; } int c = ( ch & ) ; if ( c > ) { buf . append ( "" + c + "" ) ; } else { buf . append ( ch ) ; } } else if ( ++ i < len ) { char ch2 = str . charAt ( i ) ; if ( ! Character . isLowSurrogate ( ch2 ) ) { throw new IllegalArgumentException ( "" ) ; } int c = Character . toCodePoint ( ch , ch2 ) ; buf . append ( "" + c + "" ) ; } else { throw new IllegalArgumentException ( "" ) ; } } return buf . toString ( ) ; } public static ImmutableSet < JavaHeapObject > getReferrers ( Iterable < JavaHeapObject > instances ) { ImmutableSet . Builder < JavaHeapObject > builder = ImmutableSet . builder ( ) ; for ( JavaHeapObject instance : instances ) { builder . addAll ( instance . getReferers ( ) ) ; } return builder . build ( ) ; } public static ImmutableSet < JavaHeapObject > getReferrers ( Iterable < JavaHeapObject > instances , Predicate < JavaHeapObject > filter ) { ImmutableSet . Builder < JavaHeapObject > builder = ImmutableSet . builder ( ) ; for ( JavaHeapObject instance : instances ) { builder . addAll ( Sets . filter ( instance . getReferers ( ) , filter ) ) ; } return builder . build ( ) ; } public static ImmutableSet < JavaHeapObject > getReferrersByClass ( Iterable < JavaHeapObject > instances , JavaClass clazz ) { return getReferrers ( instances , Predicates . compose ( Predicates . equalTo ( clazz ) , GetClass . INSTANCE ) ) ; } public static ImmutableSet < JavaHeapObject > getReferees ( Iterable < JavaHeapObject > instances , final Predicate < JavaHeapObject > filter ) { final ImmutableSet . Builder < JavaHeapObject > builder = ImmutableSet . builder ( ) ; for ( JavaHeapObject instance : instances ) { instance . visitReferencedObjects ( new AbstractJavaHeapObjectVisitor ( ) { @ Override public void visit ( JavaHeapObject obj ) { if ( filter . apply ( obj ) ) { builder . add ( obj ) ; } } } ) ; } return builder . build ( ) ; } public static ImmutableSet < JavaHeapObject > getRefereesByClass ( Iterable < JavaHeapObject > instances , JavaClass clazz ) { return getReferees ( instances , Predicates . compose ( Predicates . equalTo ( clazz ) , GetClass . INSTANCE ) ) ; } public static ImmutableSet < JavaHeapObject > getInstances ( JavaClass clazz , boolean includeSubclasses , Iterable < JavaClass > referrers ) { Iterable < JavaHeapObject > instances = clazz . getInstances ( includeSubclasses ) ; if ( referrers != null ) { for ( JavaClass referrer : referrers ) { instances = getReferrersByClass ( instances , referrer ) ; } } return ImmutableSet . copyOf ( instances ) ; } } package com . sun . tools . hat . internal . parser ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . nio . MappedByteBuffer ; import java . nio . channels . FileChannel ; class MappedReadBuffer implements ReadBuffer { private final MappedByteBuffer buf ; MappedReadBuffer ( MappedByteBuffer buf ) { this . buf = buf ; } static ReadBuffer create ( RandomAccessFile file ) throws IOException { FileChannel ch = file . getChannel ( ) ; long size = ch . size ( ) ; if ( canUseFileMap ( ) && ( size <= Integer . MAX_VALUE ) ) { MappedByteBuffer buf ; try { buf = ch . map ( FileChannel . MapMode . READ_ONLY , , size ) ; ch . close ( ) ; return new MappedReadBuffer ( buf ) ; } catch ( IOException exp ) { exp . printStackTrace ( ) ; System . err . println ( "" ) ; } } return new FileReadBuffer ( file ) ; } private static boolean canUseFileMap ( ) { String prop = System . getProperty ( "" ) ; return prop == null || prop . equals ( "" ) ; } private void seek ( long pos ) { assert pos <= Integer . MAX_VALUE : "" ; buf . position ( ( int ) pos ) ; } public synchronized void get ( long pos , byte [ ] res ) throws IOException { seek ( pos ) ; buf . get ( res ) ; } public synchronized char getChar ( long pos ) throws IOException { seek ( pos ) ; return buf . getChar ( ) ; } public synchronized byte getByte ( long pos ) throws IOException { seek ( pos ) ; return buf . get ( ) ; } public synchronized short getShort ( long pos ) throws IOException { seek ( pos ) ; return buf . getShort ( ) ; } public synchronized int getInt ( long pos ) throws IOException { seek ( pos ) ; return buf . getInt ( ) ; } public synchronized long getLong ( long pos ) throws IOException { seek ( pos ) ; return buf . getLong ( ) ; } } package com . sun . tools . hat . internal . parser ; import java . io . FilterInputStream ; import java . io . IOException ; import java . io . InputStream ; public class PositionInputStream extends FilterInputStream { private long position = ; public PositionInputStream ( InputStream in ) { super ( in ) ; } public int read ( ) throws IOException { int res = super . read ( ) ; if ( res != - ) position ++ ; return res ; } public int read ( byte [ ] b , int off , int len ) throws IOException { int res = super . read ( b , off , len ) ; if ( res != - ) position += res ; return res ; } public long skip ( long n ) throws IOException { long res = super . skip ( n ) ; position += res ; return res ; } public boolean markSupported ( ) { return false ; } public void mark ( int readLimit ) { throw new UnsupportedOperationException ( "" ) ; } public void reset ( ) { throw new UnsupportedOperationException ( "" ) ; } public long position ( ) { return position ; } } package com . sun . tools . hat . internal . parser ; import java . io . IOException ; import java . io . RandomAccessFile ; class FileReadBuffer implements ReadBuffer { private final RandomAccessFile file ; FileReadBuffer ( RandomAccessFile file ) { this . file = file ; } private void seek ( long pos ) throws IOException { file . getChannel ( ) . position ( pos ) ; } public synchronized void get ( long pos , byte [ ] buf ) throws IOException { seek ( pos ) ; file . read ( buf ) ; } public synchronized char getChar ( long pos ) throws IOException { seek ( pos ) ; return file . readChar ( ) ; } public synchronized byte getByte ( long pos ) throws IOException { seek ( pos ) ; return ( byte ) file . read ( ) ; } public synchronized short getShort ( long pos ) throws IOException { seek ( pos ) ; return file . readShort ( ) ; } public synchronized int getInt ( long pos ) throws IOException { seek ( pos ) ; return file . readInt ( ) ; } public synchronized long getLong ( long pos ) throws IOException { seek ( pos ) ; return file . readLong ( ) ; } } package com . sun . tools . hat . internal . parser ; import java . io . IOException ; public interface ReadBuffer { public void get ( long pos , byte [ ] buf ) throws IOException ; public char getChar ( long pos ) throws IOException ; public byte getByte ( long pos ) throws IOException ; public short getShort ( long pos ) throws IOException ; public int getInt ( long pos ) throws IOException ; public long getLong ( long pos ) throws IOException ; } package com . sun . tools . hat . internal . parser ; import java . io . * ; import com . google . common . io . Closeables ; import com . sun . tools . hat . internal . model . * ; public abstract class Reader { protected final PositionDataInputStream in ; protected Reader ( PositionDataInputStream in ) { this . in = in ; } abstract public Snapshot read ( ) throws IOException ; public static Snapshot readFile ( String heapFile , boolean callStack , int debugLevel ) throws IOException { int dumpNumber = ; int pos = heapFile . lastIndexOf ( '' ) ; if ( pos > - ) { String num = heapFile . substring ( pos + , heapFile . length ( ) ) ; try { dumpNumber = Integer . parseInt ( num , ) ; } catch ( java . lang . NumberFormatException ex ) { String msg = "" + heapFile + "" + "" + num + "" ; System . err . println ( msg ) ; throw new IOException ( msg ) ; } heapFile = heapFile . substring ( , pos ) ; } PositionDataInputStream in = new PositionDataInputStream ( new BufferedInputStream ( new FileInputStream ( heapFile ) ) ) ; try { int i = in . readInt ( ) ; if ( i == HprofReader . MAGIC_NUMBER ) { Reader r = new HprofReader ( heapFile , in , dumpNumber , callStack , debugLevel ) ; return r . read ( ) ; } else { throw new IOException ( "" + i ) ; } } finally { Closeables . closeQuietly ( in ) ; } } } package com . sun . tools . hat . internal . parser ; import java . io . DataInputStream ; import java . io . InputStream ; public class PositionDataInputStream extends DataInputStream { public PositionDataInputStream ( InputStream in ) { super ( in instanceof PositionInputStream ? in : new PositionInputStream ( in ) ) ; } public boolean markSupported ( ) { return false ; } public void mark ( int readLimit ) { throw new UnsupportedOperationException ( "" ) ; } public void reset ( ) { throw new UnsupportedOperationException ( "" ) ; } public long position ( ) { return ( ( PositionInputStream ) in ) . position ( ) ; } } package com . sun . tools . hat . internal . parser ; import java . io . * ; import java . util . Date ; import java . util . HashMap ; import java . util . Map ; import static com . sun . tools . hat . internal . model . ArrayTypeCodes . * ; import com . sun . tools . hat . internal . model . * ; public class HprofReader extends Reader { final static int MAGIC_NUMBER = ; private final static String [ ] VERSIONS = { "" , "" , "" , } ; private final static int VERSION_JDK12BETA3 = ; private final static int VERSION_JDK12BETA4 = ; private final static int VERSION_JDK6 = ; static final int HPROF_UTF8 = ; static final int HPROF_LOAD_CLASS = ; static final int HPROF_UNLOAD_CLASS = ; static final int HPROF_FRAME = ; static final int HPROF_TRACE = ; static final int HPROF_ALLOC_SITES = ; static final int HPROF_HEAP_SUMMARY = ; static final int HPROF_START_THREAD = ; static final int HPROF_END_THREAD = ; static final int HPROF_HEAP_DUMP = ; static final int HPROF_CPU_SAMPLES = ; static final int HPROF_CONTROL_SETTINGS = ; static final int HPROF_LOCKSTATS_WAIT_TIME = ; static final int HPROF_LOCKSTATS_HOLD_TIME = ; static final int HPROF_GC_ROOT_UNKNOWN = ; static final int HPROF_GC_ROOT_JNI_GLOBAL = ; static final int HPROF_GC_ROOT_JNI_LOCAL = ; static final int HPROF_GC_ROOT_JAVA_FRAME = ; static final int HPROF_GC_ROOT_NATIVE_STACK = ; static final int HPROF_GC_ROOT_STICKY_CLASS = ; static final int HPROF_GC_ROOT_THREAD_BLOCK = ; static final int HPROF_GC_ROOT_MONITOR_USED = ; static final int HPROF_GC_ROOT_THREAD_OBJ = ; static final int HPROF_GC_CLASS_DUMP = ; static final int HPROF_GC_INSTANCE_DUMP = ; static final int HPROF_GC_OBJ_ARRAY_DUMP = ; static final int HPROF_GC_PRIM_ARRAY_DUMP = ; static final int HPROF_HEAP_DUMP_SEGMENT = ; static final int HPROF_HEAP_DUMP_END = ; private final static int T_CLASS = ; private int version ; private final int debugLevel ; private long currPos ; private int dumpsToSkip ; private final boolean callStack ; private int identifierSize ; private final Map < Long , String > names ; private final Map < Integer , ThreadObject > threadObjects ; private final Map < Long , String > classNameFromObjectID ; private final Map < Integer , String > classNameFromSerialNo ; private final Map < Long , StackFrame > stackFrames ; private final Map < Integer , StackTrace > stackTraces ; private final Snapshot snapshot ; public HprofReader ( String fileName , PositionDataInputStream in , int dumpNumber , boolean callStack , int debugLevel ) throws IOException { super ( in ) ; RandomAccessFile file = new RandomAccessFile ( fileName , "" ) ; this . snapshot = new Snapshot ( MappedReadBuffer . create ( file ) ) ; this . dumpsToSkip = dumpNumber - ; this . callStack = callStack ; this . debugLevel = debugLevel ; names = new HashMap < Long , String > ( ) ; threadObjects = new HashMap < Integer , ThreadObject > ( ) ; classNameFromObjectID = new HashMap < Long , String > ( ) ; if ( callStack ) { stackFrames = new HashMap < Long , StackFrame > ( ) ; stackTraces = new HashMap < Integer , StackTrace > ( ) ; classNameFromSerialNo = new HashMap < Integer , String > ( ) ; } else { stackFrames = null ; stackTraces = null ; classNameFromSerialNo = null ; } } public Snapshot read ( ) throws IOException { currPos = ; version = readVersionHeader ( ) ; identifierSize = in . readInt ( ) ; snapshot . setIdentifierSize ( identifierSize ) ; if ( version >= VERSION_JDK12BETA4 ) { snapshot . setNewStyleArrayClass ( true ) ; } else { snapshot . setNewStyleArrayClass ( false ) ; } currPos += ; if ( identifierSize != && identifierSize != ) { throw new IOException ( "" + identifierSize + "" ) ; } System . out . println ( "" + ( new Date ( in . readLong ( ) ) ) ) ; currPos += ; for ( ; ; ) { int type ; try { type = in . readUnsignedByte ( ) ; } catch ( EOFException ignored ) { break ; } in . readInt ( ) ; long length = in . readInt ( ) & ; if ( debugLevel > ) { System . out . println ( "" + type + "" + length + "" + toHex ( currPos ) ) ; } if ( length < ) { throw new IOException ( "" + length + "" + toHex ( currPos + ) + "" ) ; } currPos += + length ; switch ( type ) { case HPROF_UTF8 : { long id = readID ( ) ; byte [ ] chars = new byte [ ( int ) length - identifierSize ] ; in . readFully ( chars ) ; names . put ( id , new String ( chars , "" ) ) ; break ; } case HPROF_LOAD_CLASS : { int serialNo = in . readInt ( ) ; long classID = readID ( ) ; int stackTraceSerialNo = in . readInt ( ) ; long classNameID = readID ( ) ; String nm = getNameFromID ( classNameID ) . replace ( '' , '' ) ; classNameFromObjectID . put ( classID , nm ) ; if ( classNameFromSerialNo != null ) { classNameFromSerialNo . put ( serialNo , nm ) ; } break ; } case HPROF_HEAP_DUMP : { if ( dumpsToSkip <= ) { try { readHeapDump ( length , currPos ) ; } catch ( EOFException exp ) { handleEOF ( exp , snapshot ) ; } if ( debugLevel > ) { System . out . println ( "" ) ; } return snapshot ; } else { dumpsToSkip -- ; skipBytes ( length ) ; } break ; } case HPROF_HEAP_DUMP_END : { if ( version >= VERSION_JDK6 ) { if ( dumpsToSkip <= ) { skipBytes ( length ) ; return snapshot ; } else { dumpsToSkip -- ; } } else { warn ( "" + type ) ; } skipBytes ( length ) ; break ; } case HPROF_HEAP_DUMP_SEGMENT : { if ( version >= VERSION_JDK6 ) { if ( dumpsToSkip <= ) { try { readHeapDump ( length , currPos ) ; } catch ( EOFException exp ) { handleEOF ( exp , snapshot ) ; } } else { skipBytes ( length ) ; } } else { warn ( "" + type ) ; skipBytes ( length ) ; } break ; } case HPROF_FRAME : { if ( stackFrames == null ) { skipBytes ( length ) ; } else { long id = readID ( ) ; String methodName = getNameFromID ( readID ( ) ) ; String methodSig = getNameFromID ( readID ( ) ) ; String sourceFile = getNameFromID ( readID ( ) ) ; int classSer = in . readInt ( ) ; String className = classNameFromSerialNo . get ( classSer ) ; int lineNumber = in . readInt ( ) ; if ( lineNumber < StackFrame . LINE_NUMBER_NATIVE ) { warn ( "" + lineNumber ) ; lineNumber = StackFrame . LINE_NUMBER_UNKNOWN ; } stackFrames . put ( id , new StackFrame ( methodName , methodSig , className , sourceFile , lineNumber ) ) ; } break ; } case HPROF_TRACE : { if ( stackTraces == null ) { skipBytes ( length ) ; } else { int serialNo = in . readInt ( ) ; int threadSeq = in . readInt ( ) ; StackFrame [ ] frames = new StackFrame [ in . readInt ( ) ] ; for ( int i = ; i < frames . length ; i ++ ) { long fid = readID ( ) ; frames [ i ] = stackFrames . get ( fid ) ; if ( frames [ i ] == null ) { throw new IOException ( "" + toHex ( fid ) + "" ) ; } } stackTraces . put ( serialNo , new StackTrace ( frames ) ) ; } break ; } case HPROF_UNLOAD_CLASS : case HPROF_ALLOC_SITES : case HPROF_START_THREAD : case HPROF_END_THREAD : case HPROF_HEAP_SUMMARY : case HPROF_CPU_SAMPLES : case HPROF_CONTROL_SETTINGS : case HPROF_LOCKSTATS_WAIT_TIME : case HPROF_LOCKSTATS_HOLD_TIME : { skipBytes ( length ) ; break ; } default : { skipBytes ( length ) ; warn ( "" + type ) ; } } } return snapshot ; } private void skipBytes ( long length ) throws IOException { in . skipBytes ( ( int ) length ) ; } private int readVersionHeader ( ) throws IOException { int candidatesLeft = VERSIONS . length ; boolean [ ] matched = new boolean [ VERSIONS . length ] ; for ( int i = ; i < candidatesLeft ; i ++ ) { matched [ i ] = true ; } int pos = ; while ( candidatesLeft > ) { char c = ( char ) in . readByte ( ) ; currPos ++ ; for ( int i = ; i < VERSIONS . length ; i ++ ) { if ( matched [ i ] ) { if ( c != VERSIONS [ i ] . charAt ( pos ) ) { matched [ i ] = false ; -- candidatesLeft ; } else if ( pos == VERSIONS [ i ] . length ( ) - ) { return i ; } } } ++ pos ; } throw new IOException ( "" + ( pos + ) ) ; } private void readHeapDump ( long bytesLeft , long posAtEnd ) throws IOException { while ( bytesLeft > ) { int type = in . readUnsignedByte ( ) ; if ( debugLevel > ) { System . out . println ( "" + type + "" + toHex ( posAtEnd - bytesLeft ) ) ; } bytesLeft -- ; switch ( type ) { case HPROF_GC_ROOT_UNKNOWN : { long id = readID ( ) ; bytesLeft -= identifierSize ; snapshot . addRoot ( new Root ( id , , Root . UNKNOWN , "" ) ) ; break ; } case HPROF_GC_ROOT_THREAD_OBJ : { long id = readID ( ) ; int threadSeq = in . readInt ( ) ; int stackSeq = in . readInt ( ) ; bytesLeft -= identifierSize + ; threadObjects . put ( threadSeq , new ThreadObject ( id , stackSeq ) ) ; break ; } case HPROF_GC_ROOT_JNI_GLOBAL : { long id = readID ( ) ; long globalRefId = readID ( ) ; bytesLeft -= * identifierSize ; snapshot . addRoot ( new Root ( id , , Root . NATIVE_STATIC , "" ) ) ; break ; } case HPROF_GC_ROOT_JNI_LOCAL : { long id = readID ( ) ; int threadSeq = in . readInt ( ) ; int depth = in . readInt ( ) ; bytesLeft -= identifierSize + ; ThreadObject to = getThreadObjectFromSequence ( threadSeq ) ; StackTrace st = getStackTraceFromSerial ( to . stackSeq ) ; if ( st != null ) { st = st . traceForDepth ( depth + ) ; } snapshot . addRoot ( new Root ( id , to . threadId , Root . NATIVE_LOCAL , "" , st ) ) ; break ; } case HPROF_GC_ROOT_JAVA_FRAME : { long id = readID ( ) ; int threadSeq = in . readInt ( ) ; int depth = in . readInt ( ) ; bytesLeft -= identifierSize + ; ThreadObject to = getThreadObjectFromSequence ( threadSeq ) ; StackTrace st = getStackTraceFromSerial ( to . stackSeq ) ; if ( st != null ) { st = st . traceForDepth ( depth + ) ; } snapshot . addRoot ( new Root ( id , to . threadId , Root . JAVA_LOCAL , "" , st ) ) ; break ; } case HPROF_GC_ROOT_NATIVE_STACK : { long id = readID ( ) ; int threadSeq = in . readInt ( ) ; bytesLeft -= identifierSize + ; ThreadObject to = getThreadObjectFromSequence ( threadSeq ) ; StackTrace st = getStackTraceFromSerial ( to . stackSeq ) ; snapshot . addRoot ( new Root ( id , to . threadId , Root . NATIVE_STACK , "" , st ) ) ; break ; } case HPROF_GC_ROOT_STICKY_CLASS : { long id = readID ( ) ; bytesLeft -= identifierSize ; snapshot . addRoot ( new Root ( id , , Root . SYSTEM_CLASS , "" ) ) ; break ; } case HPROF_GC_ROOT_THREAD_BLOCK : { long id = readID ( ) ; int threadSeq = in . readInt ( ) ; bytesLeft -= identifierSize + ; ThreadObject to = getThreadObjectFromSequence ( threadSeq ) ; StackTrace st = getStackTraceFromSerial ( to . stackSeq ) ; snapshot . addRoot ( new Root ( id , to . threadId , Root . THREAD_BLOCK , "" , st ) ) ; break ; } case HPROF_GC_ROOT_MONITOR_USED : { long id = readID ( ) ; bytesLeft -= identifierSize ; snapshot . addRoot ( new Root ( id , , Root . BUSY_MONITOR , "" ) ) ; break ; } case HPROF_GC_CLASS_DUMP : { int bytesRead = readClass ( ) ; bytesLeft -= bytesRead ; break ; } case HPROF_GC_INSTANCE_DUMP : { int bytesRead = readInstance ( ) ; bytesLeft -= bytesRead ; break ; } case HPROF_GC_OBJ_ARRAY_DUMP : { int bytesRead = readArray ( false ) ; bytesLeft -= bytesRead ; break ; } case HPROF_GC_PRIM_ARRAY_DUMP : { int bytesRead = readArray ( true ) ; bytesLeft -= bytesRead ; break ; } default : { throw new IOException ( "" + type ) ; } } } if ( bytesLeft != ) { warn ( "" + bytesLeft + "" ) ; skipBytes ( bytesLeft ) ; } if ( debugLevel > ) { System . out . println ( "" ) ; } } private long readID ( ) throws IOException { return ( identifierSize == ) ? ( Snapshot . SMALL_ID_MASK & in . readInt ( ) ) : in . readLong ( ) ; } private int readValue ( JavaThing [ ] resultArr ) throws IOException { byte type = in . readByte ( ) ; return + readValueForType ( type , resultArr ) ; } private int readValueForType ( byte type , JavaThing [ ] resultArr ) throws IOException { if ( version >= VERSION_JDK12BETA4 ) { type = signatureFromTypeId ( type ) ; } return readValueForTypeSignature ( type , resultArr ) ; } private int readValueForTypeSignature ( byte type , JavaThing [ ] resultArr ) throws IOException { switch ( type ) { case '' : case '' : { long id = readID ( ) ; if ( resultArr != null ) { resultArr [ ] = new JavaObjectRef ( id ) ; } return identifierSize ; } case '' : { int b = in . readByte ( ) ; if ( b != && b != ) { warn ( "" ) ; } if ( resultArr != null ) { resultArr [ ] = new JavaBoolean ( b != ) ; } return ; } case '' : { byte b = in . readByte ( ) ; if ( resultArr != null ) { resultArr [ ] = new JavaByte ( b ) ; } return ; } case '' : { short s = in . readShort ( ) ; if ( resultArr != null ) { resultArr [ ] = new JavaShort ( s ) ; } return ; } case '' : { char ch = in . readChar ( ) ; if ( resultArr != null ) { resultArr [ ] = new JavaChar ( ch ) ; } return ; } case '' : { int val = in . readInt ( ) ; if ( resultArr != null ) { resultArr [ ] = new JavaInt ( val ) ; } return ; } case '' : { long val = in . readLong ( ) ; if ( resultArr != null ) { resultArr [ ] = new JavaLong ( val ) ; } return ; } case '' : { float val = in . readFloat ( ) ; if ( resultArr != null ) { resultArr [ ] = new JavaFloat ( val ) ; } return ; } case '' : { double val = in . readDouble ( ) ; if ( resultArr != null ) { resultArr [ ] = new JavaDouble ( val ) ; } return ; } default : { throw new IOException ( "" + type ) ; } } } private ThreadObject getThreadObjectFromSequence ( int threadSeq ) throws IOException { ThreadObject to = threadObjects . get ( threadSeq ) ; if ( to == null ) { throw new IOException ( "" + threadSeq + "" ) ; } return to ; } private String getNameFromID ( Long id ) { if ( id == ) { return "" ; } String result = names . get ( id ) ; if ( result == null ) { warn ( "" + toHex ( id ) ) ; return "" + toHex ( id ) ; } return result ; } private StackTrace getStackTraceFromSerial ( int ser ) { if ( stackTraces == null ) { return null ; } StackTrace result = stackTraces . get ( ser ) ; if ( result == null ) { warn ( "" + ser ) ; } return result ; } private int readClass ( ) throws IOException { long id = readID ( ) ; StackTrace stackTrace = getStackTraceFromSerial ( in . readInt ( ) ) ; long superId = readID ( ) ; long classLoaderId = readID ( ) ; long signersId = readID ( ) ; long protDomainId = readID ( ) ; long reserved1 = readID ( ) ; long reserved2 = readID ( ) ; int instanceSize = in . readInt ( ) ; int bytesRead = * identifierSize + ; int numConstPoolEntries = in . readUnsignedShort ( ) ; bytesRead += ; for ( int i = ; i < numConstPoolEntries ; i ++ ) { int index = in . readUnsignedShort ( ) ; bytesRead += ; bytesRead += readValue ( null ) ; } int numStatics = in . readUnsignedShort ( ) ; bytesRead += ; JavaThing [ ] valueBin = new JavaThing [ ] ; JavaStatic [ ] statics = new JavaStatic [ numStatics ] ; for ( int i = ; i < numStatics ; i ++ ) { long nameId = readID ( ) ; bytesRead += identifierSize ; byte type = in . readByte ( ) ; bytesRead ++ ; bytesRead += readValueForType ( type , valueBin ) ; String fieldName = getNameFromID ( nameId ) ; if ( version >= VERSION_JDK12BETA4 ) { type = signatureFromTypeId ( type ) ; } String signature = "" + ( ( char ) type ) ; JavaField f = new JavaField ( fieldName , signature ) ; statics [ i ] = new JavaStatic ( f , valueBin [ ] ) ; } int numFields = in . readUnsignedShort ( ) ; bytesRead += ; JavaField [ ] fields = new JavaField [ numFields ] ; for ( int i = ; i < numFields ; i ++ ) { long nameId = readID ( ) ; bytesRead += identifierSize ; byte type = in . readByte ( ) ; bytesRead ++ ; String fieldName = getNameFromID ( nameId ) ; if ( version >= VERSION_JDK12BETA4 ) { type = signatureFromTypeId ( type ) ; } String signature = "" + ( ( char ) type ) ; fields [ i ] = new JavaField ( fieldName , signature ) ; } String name = classNameFromObjectID . get ( id ) ; if ( name == null ) { warn ( "" + toHex ( id ) ) ; name = "" + toHex ( id ) ; } JavaClass c = new JavaClass ( id , name , superId , classLoaderId , signersId , protDomainId , fields , statics , instanceSize ) ; snapshot . addClass ( id , c ) ; snapshot . setSiteTrace ( c , stackTrace ) ; return bytesRead ; } private String toHex ( long addr ) { return com . sun . tools . hat . internal . util . Misc . toHex ( addr ) ; } private int readInstance ( ) throws IOException { long start = in . position ( ) ; long id = readID ( ) ; StackTrace stackTrace = getStackTraceFromSerial ( in . readInt ( ) ) ; long classID = readID ( ) ; int bytesFollowing = in . readInt ( ) ; int bytesRead = ( * identifierSize ) + + bytesFollowing ; JavaObject jobj = new JavaObject ( classID , start ) ; skipBytes ( bytesFollowing ) ; snapshot . addHeapObject ( id , jobj ) ; snapshot . setSiteTrace ( jobj , stackTrace ) ; return bytesRead ; } private int readArray ( boolean isPrimitive ) throws IOException { long start = in . position ( ) ; long id = readID ( ) ; StackTrace stackTrace = getStackTraceFromSerial ( in . readInt ( ) ) ; int num = in . readInt ( ) ; int bytesRead = identifierSize + ; long elementClassID ; if ( isPrimitive ) { elementClassID = in . readByte ( ) ; bytesRead ++ ; } else { elementClassID = readID ( ) ; bytesRead += identifierSize ; } byte primitiveSignature = ; int elSize = ; if ( isPrimitive || version < VERSION_JDK12BETA4 ) { switch ( ( int ) elementClassID ) { case T_BOOLEAN : { primitiveSignature = ( byte ) '' ; elSize = ; break ; } case T_CHAR : { primitiveSignature = ( byte ) '' ; elSize = ; break ; } case T_FLOAT : { primitiveSignature = ( byte ) '' ; elSize = ; break ; } case T_DOUBLE : { primitiveSignature = ( byte ) '' ; elSize = ; break ; } case T_BYTE : { primitiveSignature = ( byte ) '' ; elSize = ; break ; } case T_SHORT : { primitiveSignature = ( byte ) '' ; elSize = ; break ; } case T_INT : { primitiveSignature = ( byte ) '' ; elSize = ; break ; } case T_LONG : { primitiveSignature = ( byte ) '' ; elSize = ; break ; } } if ( version >= VERSION_JDK12BETA4 && primitiveSignature == ) { throw new IOException ( "" + elementClassID ) ; } } if ( primitiveSignature != ) { int size = elSize * num ; bytesRead += size ; JavaValueArray va = new JavaValueArray ( primitiveSignature , start ) ; skipBytes ( size ) ; snapshot . addHeapObject ( id , va ) ; snapshot . setSiteTrace ( va , stackTrace ) ; } else { int sz = num * identifierSize ; bytesRead += sz ; JavaObjectArray arr = new JavaObjectArray ( elementClassID , start ) ; skipBytes ( sz ) ; snapshot . addHeapObject ( id , arr ) ; snapshot . setSiteTrace ( arr , stackTrace ) ; } return bytesRead ; } private static byte signatureFromTypeId ( byte typeId ) throws IOException { switch ( typeId ) { case T_CLASS : { return ( byte ) '' ; } case T_BOOLEAN : { return ( byte ) '' ; } case T_CHAR : { return ( byte ) '' ; } case T_FLOAT : { return ( byte ) '' ; } case T_DOUBLE : { return ( byte ) '' ; } case T_BYTE : { return ( byte ) '' ; } case T_SHORT : { return ( byte ) '' ; } case T_INT : { return ( byte ) '' ; } case T_LONG : { return ( byte ) '' ; } default : { throw new IOException ( "" + typeId ) ; } } } private void handleEOF ( EOFException exp , Snapshot snapshot ) { if ( debugLevel > ) { exp . printStackTrace ( ) ; } warn ( "" ) ; snapshot . setUnresolvedObjectsOK ( true ) ; } private void warn ( String msg ) { System . out . println ( "" + msg ) ; } private static class ThreadObject { public final long threadId ; public final int stackSeq ; ThreadObject ( long threadId , int stackSeq ) { this . threadId = threadId ; this . stackSeq = stackSeq ; } } } package com . sun . tools . hat ; import java . io . IOException ; import java . io . File ; import com . sun . tools . hat . internal . lang . guava . Guava ; import com . sun . tools . hat . internal . lang . jruby12 . JRuby12 ; import com . sun . tools . hat . internal . lang . jruby16 . JRuby16 ; import com . sun . tools . hat . internal . lang . openjdk6 . OpenJDK6 ; import com . sun . tools . hat . internal . model . Snapshot ; import com . sun . tools . hat . internal . model . ReachableExcludesImpl ; import com . sun . tools . hat . internal . server . QueryListener ; public class Main { private static String VERSION_STRING = "" ; private static void usage ( String message ) { if ( message != null ) { System . err . println ( "" + message ) ; } System . err . println ( "" ) ; System . err . println ( ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( "" ) ; System . err . println ( ) ; System . err . println ( "" ) ; System . exit ( ) ; } private static boolean booleanValue ( String s ) { if ( "" . equalsIgnoreCase ( s ) ) { return true ; } else if ( "" . equalsIgnoreCase ( s ) ) { return false ; } else { usage ( "" ) ; return false ; } } public static void main ( String [ ] args ) throws IOException { if ( args . length < ) { usage ( "" ) ; } boolean parseonly = false ; int portNumber = ; boolean callStack = true ; boolean calculateRefs = true ; String baselineDump = null ; String excludeFileName = null ; int debugLevel = ; for ( int i = ; ; i += ) { if ( i > ( args . length - ) ) { usage ( "" ) ; } if ( "" . equals ( args [ i ] ) ) { System . out . print ( VERSION_STRING ) ; System . out . println ( "" + System . getProperty ( "" ) + "" ) ; System . exit ( ) ; } if ( "" . equals ( args [ i ] ) || "" . equals ( args [ i ] ) ) { usage ( null ) ; } if ( i == ( args . length - ) ) { break ; } String key = args [ i ] ; String value = args [ i + ] ; if ( "" . equals ( key ) ) { callStack = booleanValue ( value ) ; } else if ( "" . equals ( key ) ) { calculateRefs = booleanValue ( value ) ; } else if ( "" . equals ( key ) ) { portNumber = Integer . parseInt ( value , ) ; } else if ( "" . equals ( key ) ) { excludeFileName = value ; } else if ( "" . equals ( key ) ) { baselineDump = value ; } else if ( "" . equals ( key ) ) { debugLevel = Integer . parseInt ( value , ) ; } else if ( "" . equals ( key ) ) { parseonly = booleanValue ( value ) ; } } String fileName = args [ args . length - ] ; File excludeFile = null ; if ( excludeFileName != null ) { excludeFile = new File ( excludeFileName ) ; if ( ! excludeFile . exists ( ) ) { System . out . println ( "" + excludeFile + "" ) ; System . exit ( ) ; } } System . out . println ( "" + fileName + "" ) ; Snapshot model = com . sun . tools . hat . internal . parser . Reader . readFile ( fileName , callStack , debugLevel ) ; System . out . println ( "" ) ; model . resolve ( calculateRefs ) ; System . out . println ( "" ) ; if ( excludeFile != null ) { model . setReachableExcludes ( new ReachableExcludesImpl ( excludeFile ) ) ; } if ( baselineDump != null ) { System . out . println ( "" ) ; Snapshot baseline = com . sun . tools . hat . internal . parser . Reader . readFile ( baselineDump , false , debugLevel ) ; baseline . resolve ( false ) ; System . out . println ( "" ) ; model . markNewRelativeTo ( baseline ) ; baseline = null ; } model . setUpModelFactories ( OpenJDK6 . Factory . INSTANCE , Guava . Factory . INSTANCE , JRuby12 . Factory . INSTANCE , JRuby16 . Factory . INSTANCE ) ; if ( debugLevel == ) { System . out . println ( "" ) ; System . exit ( ) ; } if ( parseonly ) { System . out . println ( "" ) ; System . exit ( ) ; } QueryListener listener = new QueryListener ( portNumber ) ; listener . setModel ( model ) ; System . out . println ( "" + portNumber ) ; System . out . println ( "" ) ; listener . run ( ) ; } } package com . fredbrunel . android . twitter ; import android . app . Activity ; import android . app . AlertDialog ; import android . app . ProgressDialog ; import android . net . Uri ; import android . os . Bundle ; import android . os . Handler ; import android . os . Message ; import android . view . Menu ; import android . view . MenuItem ; import android . view . View ; import android . view . View . OnClickListener ; import android . widget . EditText ; import android . widget . ListView ; import android . widget . ImageView ; import jtwitter . TwitterResponse ; public class StatusActivity extends Activity { private static final int MENU_CONFIGURE_ID = Menu . FIRST ; private ProgressDialog activeProgress ; private TwitterService twitter = null ; @ Override public void onCreate ( Bundle icicle ) { super . onCreate ( icicle ) ; setContentView ( R . layout . splash ) ; ( ( ImageView ) findViewById ( R . id . splash_logo ) ) . setImageResource ( R . drawable . twitterdroid ) ; } @ Override public void onResume ( ) { super . onResume ( ) ; Config config = Config . getConfig ( this ) ; Uri uri = this . getIntent ( ) . getData ( ) ; if ( uri != null && uri . toString ( ) . startsWith ( AuthConstants . CALLBACK_URL ) ) { TwitterAuth auth = new TwitterAuth ( uri ) ; config . setAccessKey ( auth . getAccessKey ( ) ) ; config . setAccessSecret ( auth . getAccessSecret ( ) ) ; config . commit ( ) ; } else if ( ! config . authorized ( ) ) { ConfigActivity . requestUpdate ( this ) ; return ; } if ( twitter == null ) { twitter = new TwitterService ( config . getAccessKey ( ) , config . getAccessSecret ( ) ) ; } showFetchingProgress ( ) ; twitter . requestFriendsTimeline ( handler ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { super . onCreateOptionsMenu ( menu ) ; menu . add ( Menu . NONE , MENU_CONFIGURE_ID , Menu . NONE , R . string . status_configure_menu ) . setShortcut ( '' , '' ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { switch ( item . getItemId ( ) ) { case MENU_CONFIGURE_ID : ConfigActivity . requestUpdate ( this ) ; return true ; } return super . onOptionsItemSelected ( item ) ; } private Handler handler = new Handler ( ) { @ Override public void handleMessage ( Message msg ) { if ( msg . arg1 == TwitterService . RESPONSE_OK ) { switch ( msg . arg2 ) { case TwitterService . REQUEST_FRIENDS_TIMELINE : updateStatusListView ( ( TwitterResponse ) msg . obj ) ; case TwitterService . REQUEST_STATUS_UPDATE : clearEditMessageView ( ) ; } } else { String message = ( ( Exception ) msg . obj ) . getMessage ( ) ; new AlertDialog . Builder ( StatusActivity . this ) . setTitle ( "" ) . setMessage ( message ) . setNegativeButton ( "" , null ) . setCancelable ( false ) . show ( ) ; } hideProgress ( ) ; } } ; private void updateStatusListView ( TwitterResponse statuses ) { setContentView ( R . layout . main ) ; findViewById ( R . id . status_message ) . requestFocus ( ) ; findViewById ( R . id . status_message ) . setOnClickListener ( messageListener ) ; findViewById ( R . id . status_refresh ) . setOnClickListener ( refreshListener ) ; ListView list = ( ListView ) findViewById ( R . id . status_list ) ; list . setAdapter ( new StatusAdapter ( this , statuses ) ) ; } private void clearEditMessageView ( ) { ( ( EditText ) findViewById ( R . id . status_message ) ) . setText ( "" ) ; } private OnClickListener messageListener = new OnClickListener ( ) { public void onClick ( View v ) { EditText edit = ( EditText ) v ; String text = edit . getText ( ) . toString ( ) ; showSendingProgress ( ) ; twitter . requestUpdateStatus ( text , handler ) ; } } ; private OnClickListener refreshListener = new OnClickListener ( ) { public void onClick ( View v ) { showFetchingProgress ( ) ; twitter . requestFriendsTimeline ( handler ) ; } } ; private void showFetchingProgress ( ) { activeProgress = ProgressDialog . show ( this , null , "" , true , false ) ; } private void showSendingProgress ( ) { activeProgress = ProgressDialog . show ( this , null , "" , true , false ) ; } private void hideProgress ( ) { if ( activeProgress != null ) { activeProgress . dismiss ( ) ; activeProgress = null ; } } } package com . fredbrunel . android . twitter ; import android . content . Context ; import android . content . SharedPreferences ; import android . content . SharedPreferences . Editor ; public class Config { public static final String PREFS_NAME = "" ; private SharedPreferences settings ; private Editor editor ; public static Config getConfig ( Context context ) { return new Config ( context ) ; } private Config ( Context context ) { settings = context . getSharedPreferences ( PREFS_NAME , ) ; editor = settings . edit ( ) ; } public void commit ( ) { editor . commit ( ) ; } public String getAccessKey ( ) { return settings . getString ( "" , "" ) ; } public void setAccessKey ( String accessKey ) { editor . putString ( "" , accessKey ) ; } public String getAccessSecret ( ) { return settings . getString ( "" , "" ) ; } public void setAccessSecret ( String accessSecret ) { editor . putString ( "" , accessSecret ) ; } public boolean authorized ( ) { if ( ( getAccessKey ( ) != "" ) && ( getAccessSecret ( ) != "" ) ) return true ; else return false ; } } package com . fredbrunel . android . twitter ; import oauth . signpost . basic . DefaultOAuthConsumer ; import oauth . signpost . basic . DefaultOAuthProvider ; public interface AuthConstants { public static final String CONSUMER_KEY = "" ; public static final String CONSUMER_SECRET = "" ; public static final String REQUEST_URL = "" ; public static final String ACCESS_TOKEN_URL = "" ; public static final String AUTH_URL = "" ; public static final String CALLBACK_URL = "" ; public static final String PREFERENCE_FILE = "" ; public static DefaultOAuthConsumer consumer = new DefaultOAuthConsumer ( CONSUMER_KEY , CONSUMER_SECRET ) ; public static DefaultOAuthProvider provider = new DefaultOAuthProvider ( REQUEST_URL , ACCESS_TOKEN_URL , AUTH_URL ) ; } package com . fredbrunel . android . twitter ; import java . util . HashMap ; import java . util . Map ; import android . content . Context ; import android . database . DataSetObserver ; import android . graphics . Bitmap ; import android . view . View ; import android . view . ViewGroup ; import android . widget . ImageView ; import android . widget . LinearLayout ; import android . widget . ListAdapter ; import android . widget . TextView ; import android . widget . ImageView . ScaleType ; import android . widget . LinearLayout . LayoutParams ; import jtwitter . TwitterEntry ; import jtwitter . TwitterResponse ; public class StatusAdapter implements ListAdapter { private final TwitterResponse statuses ; private final Map < Integer , View > views = new HashMap < Integer , View > ( ) ; public StatusAdapter ( Context context , TwitterResponse statuses ) { this . statuses = statuses ; for ( int i = ; i < statuses . getNumberOfItems ( ) ; i ++ ) views . put ( i , makeUserStatusView ( context , statuses . getItemAt ( i ) ) ) ; } public boolean areAllItemsEnabled ( ) { return true ; } public boolean isEnabled ( int position ) { return true ; } public boolean hasStableIds ( ) { return true ; } public int getItemViewType ( int position ) { return ; } public int getViewTypeCount ( ) { return ; } public boolean isEmpty ( ) { return getCount ( ) == ; } public int getCount ( ) { return statuses . getNumberOfItems ( ) ; } public Object getItem ( int position ) { return statuses . getItemAt ( position ) ; } public long getItemId ( int position ) { return statuses . getItemAt ( position ) . getId ( ) ; } public View getView ( int position , View convertView , ViewGroup parent ) { return views . get ( position ) ; } public void registerDataSetObserver ( DataSetObserver observer ) { } public void unregisterDataSetObserver ( DataSetObserver observer ) { } private View makeUserStatusView ( Context context , TwitterEntry entry ) { ImageView iv = new ImageView ( context ) ; Bitmap photo = BitmapCache . getInstance ( ) . get ( entry . getUser ( ) . getProfileImageURL ( ) ) ; iv . setImageBitmap ( photo ) ; iv . setScaleType ( ScaleType . CENTER ) ; iv . setPadding ( , , , ) ; iv . setLayoutParams ( new LayoutParams ( LayoutParams . WRAP_CONTENT , LayoutParams . WRAP_CONTENT ) ) ; TextView tv = new TextView ( context ) ; tv . setText ( entry . getUser ( ) . getName ( ) + "" + entry . getText ( ) ) ; tv . setLayoutParams ( new LayoutParams ( LayoutParams . WRAP_CONTENT , LayoutParams . WRAP_CONTENT ) ) ; LinearLayout layout = new LinearLayout ( context ) ; layout . setOrientation ( LinearLayout . HORIZONTAL ) ; layout . setPadding ( , , , ) ; layout . addView ( iv ) ; layout . addView ( tv ) ; return layout ; } } package com . fredbrunel . android . twitter ; import android . os . Handler ; import android . os . Message ; import jtwitter . TwitterConnection ; import jtwitter . TwitterConnectionException ; import jtwitter . TwitterResponse ; public class TwitterService { public static final int RESPONSE_OK = ; public static final int RESPONSE_KO = ; public static final int RESPONSE_CONN_KO = ; public static final int REQUEST_FRIENDS_TIMELINE = ; public static final int REQUEST_STATUS_UPDATE = ; private TwitterConnection twitter ; public TwitterService ( String accessKey , String accessSecret ) { this . twitter = new TwitterConnection ( accessKey , accessSecret ) ; } public void requestFriendsTimeline ( Handler response ) { new Thread ( new DoGetFriendsTimeline ( response ) ) . start ( ) ; } public void requestUpdateStatus ( String text , Handler response ) { new Thread ( new DoStatusUpdate ( text , response ) ) . start ( ) ; } private class DoGetFriendsTimeline implements Runnable { private Handler handler ; public DoGetFriendsTimeline ( Handler handler ) { this . handler = handler ; } public void run ( ) { Message msg = new Message ( ) ; msg . arg2 = REQUEST_FRIENDS_TIMELINE ; try { TwitterResponse statuses = twitter . getFriendsTimeline ( ) ; BitmapCache cache = BitmapCache . getInstance ( ) ; for ( int i = ; i < statuses . getNumberOfItems ( ) ; i ++ ) cache . load ( statuses . getItemAt ( i ) . getUser ( ) . getProfileImageURL ( ) ) ; msg . arg1 = RESPONSE_OK ; msg . obj = statuses ; } catch ( TwitterConnectionException e ) { msg . arg1 = RESPONSE_CONN_KO ; msg . obj = e ; } catch ( Exception e ) { msg . arg1 = RESPONSE_KO ; msg . obj = e ; } handler . sendMessage ( msg ) ; } } private class DoStatusUpdate implements Runnable { private Handler handler ; private String text ; public DoStatusUpdate ( String text , Handler response ) { this . text = text ; this . handler = response ; } public void run ( ) { Message msg = new Message ( ) ; msg . arg2 = REQUEST_STATUS_UPDATE ; try { TwitterResponse status = twitter . updateStatus ( text ) ; msg . arg1 = RESPONSE_OK ; msg . obj = status ; } catch ( TwitterConnectionException e ) { msg . arg1 = RESPONSE_CONN_KO ; msg . obj = e ; } catch ( Exception e ) { msg . arg1 = RESPONSE_KO ; msg . obj = e ; } handler . sendMessage ( msg ) ; } } } package com . fredbrunel . android . twitter ; import java . io . IOException ; import java . net . URL ; import java . util . concurrent . ConcurrentHashMap ; import android . graphics . Bitmap ; import android . graphics . BitmapFactory ; public class BitmapCache { private static BitmapCache instance = null ; private ConcurrentHashMap < URL , Bitmap > cache = new ConcurrentHashMap < URL , Bitmap > ( ) ; private BitmapCache ( ) { } public static BitmapCache getInstance ( ) { if ( instance == null ) { instance = new BitmapCache ( ) ; } return instance ; } public boolean containsURL ( URL url ) { return cache . containsKey ( url ) ; } public Bitmap get ( URL url ) { return cache . get ( url ) ; } public Bitmap load ( URL url ) throws IOException { if ( containsURL ( url ) ) { return get ( url ) ; } Bitmap bitmap = BitmapFactory . decodeStream ( url . openStream ( ) ) ; cache . put ( url , bitmap ) ; return bitmap ; } } package com . fredbrunel . android . twitter ; import oauth . signpost . exception . OAuthCommunicationException ; import oauth . signpost . exception . OAuthExpectationFailedException ; import oauth . signpost . exception . OAuthMessageSignerException ; import oauth . signpost . exception . OAuthNotAuthorizedException ; import android . app . Activity ; import android . content . Intent ; import android . net . Uri ; import android . os . Bundle ; public class ConfigActivity extends Activity implements AuthConstants { public static final int CONFIG_UPDATE_REQUEST = ; public static void requestUpdate ( Activity parent ) { Intent configure = new Intent ( parent , ConfigActivity . class ) ; parent . startActivity ( configure ) ; } @ Override public void onCreate ( Bundle icicle ) { super . onCreate ( icicle ) ; try { String authURL = provider . retrieveRequestToken ( consumer , CALLBACK_URL ) ; startActivity ( new Intent ( Intent . ACTION_VIEW , Uri . parse ( authURL ) ) ) ; } catch ( OAuthMessageSignerException e ) { e . printStackTrace ( ) ; } catch ( OAuthNotAuthorizedException e ) { e . printStackTrace ( ) ; } catch ( OAuthExpectationFailedException e ) { e . printStackTrace ( ) ; } catch ( OAuthCommunicationException e ) { e . printStackTrace ( ) ; } finish ( ) ; } } package com . fredbrunel . android . twitter ; import oauth . signpost . OAuth ; import oauth . signpost . exception . OAuthCommunicationException ; import oauth . signpost . exception . OAuthExpectationFailedException ; import oauth . signpost . exception . OAuthMessageSignerException ; import oauth . signpost . exception . OAuthNotAuthorizedException ; import android . net . Uri ; public class TwitterAuth implements AuthConstants { private String accessKey = "" ; private String accessSecret = "" ; public TwitterAuth ( Uri uri ) { String verifier = uri . getQueryParameter ( OAuth . OAUTH_VERIFIER ) ; try { provider . retrieveAccessToken ( consumer , verifier ) ; accessKey = consumer . getToken ( ) ; accessSecret = consumer . getTokenSecret ( ) ; } catch ( OAuthMessageSignerException e ) { e . printStackTrace ( ) ; } catch ( OAuthNotAuthorizedException e ) { e . printStackTrace ( ) ; } catch ( OAuthExpectationFailedException e ) { e . printStackTrace ( ) ; } catch ( OAuthCommunicationException e ) { e . printStackTrace ( ) ; } } public String getAccessKey ( ) { return accessKey ; } public String getAccessSecret ( ) { return accessSecret ; } } package jtwitter ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . net . HttpURLConnection ; import java . net . URL ; import java . net . URLEncoder ; import java . text . ParseException ; import javax . xml . parsers . ParserConfigurationException ; import oauth . signpost . exception . OAuthCommunicationException ; import oauth . signpost . exception . OAuthExpectationFailedException ; import oauth . signpost . exception . OAuthMessageSignerException ; import org . xml . sax . SAXException ; import com . fredbrunel . android . twitter . AuthConstants ; public class TwitterConnection implements AuthConstants { public static final String PUBLIC_TIMELINE_URL = "" ; public static final String FRIENDS_TIMELINE_URL = "" ; public static final String UPDATE_URL = "" ; private String accessKey = "" ; private String accessSecret = "" ; public TwitterConnection ( String accessKey , String accessSecret ) { this . accessKey = accessKey ; this . accessSecret = accessSecret ; } public TwitterResponse getPublicTimeline ( ) throws Exception { return new TwitterResponse ( ) . parse ( getResponseBody ( makeConnection ( PUBLIC_TIMELINE_URL ) ) ) ; } public TwitterResponse getFriendsTimeline ( ) throws ParseException , SAXException , ParserConfigurationException , IOException , TwitterConnectionException { return new TwitterResponse ( ) . parse ( getResponseBody ( makeAuthConnection ( FRIENDS_TIMELINE_URL ) ) ) ; } public InputStream getFriendsTimelineStream ( ) throws IOException { return makeAuthConnection ( FRIENDS_TIMELINE_URL ) . getInputStream ( ) ; } public TwitterResponse updateStatus ( String text ) throws ParseException , SAXException , ParserConfigurationException , IOException , TwitterConnectionException { if ( text . length ( ) > ) { throw new IllegalArgumentException ( "" ) ; } String status = "" + URLEncoder . encode ( text , "" ) ; HttpURLConnection conn = makeAuthConnection ( UPDATE_URL ) ; sendPostRequest ( conn , status ) ; return new TwitterResponse ( ) . parse ( getResponseBody ( conn ) ) ; } private HttpURLConnection makeConnection ( String resource ) throws IOException { HttpURLConnection conn = ( HttpURLConnection ) ( new URL ( resource ) . openConnection ( ) ) ; conn . setDoOutput ( true ) ; return conn ; } private HttpURLConnection makeAuthConnection ( String resource ) throws IOException { HttpURLConnection conn = makeConnection ( resource ) ; conn . setUseCaches ( false ) ; try { consumer . sign ( conn ) ; } catch ( OAuthMessageSignerException e ) { e . printStackTrace ( ) ; } catch ( OAuthExpectationFailedException e ) { e . printStackTrace ( ) ; } catch ( OAuthCommunicationException e ) { e . printStackTrace ( ) ; } return conn ; } private String getResponseBody ( HttpURLConnection conn ) throws TwitterConnectionException { try { BufferedReader rd = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; String line ; StringBuffer output = new StringBuffer ( ) ; while ( ( line = rd . readLine ( ) ) != null ) { output . append ( line ) ; } rd . close ( ) ; return output . toString ( ) ; } catch ( Exception e ) { throw new TwitterConnectionException ( conn , e ) ; } } private void sendPostRequest ( HttpURLConnection conn , String data ) throws TwitterConnectionException { try { OutputStreamWriter wr = new OutputStreamWriter ( conn . getOutputStream ( ) ) ; wr . write ( data ) ; wr . flush ( ) ; wr . close ( ) ; } catch ( Exception e ) { throw new TwitterConnectionException ( conn , e ) ; } } } package jtwitter ; import java . net . MalformedURLException ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . Locale ; public class TwitterEntry { public static final String CREATED_AT = "" ; public static final String ID = "" ; public static final String TEXT = "" ; private Date createdAt ; private long id ; private String text ; private TwitterUser user ; public static final String TWITTER_DATE_FORMAT = "" ; public TwitterEntry ( Date createdAt , long id , String text , TwitterUser user ) { super ( ) ; this . createdAt = createdAt ; this . id = id ; this . text = text ; this . user = user ; } public TwitterEntry ( ) { this . user = new TwitterUser ( ) ; } public Date getCreatedAt ( ) { return createdAt ; } public void setCreatedAt ( Date createdAt ) { this . createdAt = createdAt ; } public long getId ( ) { return id ; } public void setId ( long id ) { this . id = id ; } public String getText ( ) { return text ; } public void setText ( String text ) { this . text = text ; } public TwitterUser getUser ( ) { return user ; } public void setUser ( TwitterUser user ) { this . user = user ; } @ Override public int hashCode ( ) { final int PRIME = ; int result = ; result = PRIME * result + ( int ) id ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; final TwitterEntry other = ( TwitterEntry ) obj ; if ( id != other . id ) return false ; return true ; } public void addAttribute ( String key , String value ) throws ParseException , MalformedURLException { if ( key . equals ( CREATED_AT ) ) this . setCreatedAt ( makeDate ( value ) ) ; else if ( key . equals ( ID ) ) this . setId ( Long . parseLong ( value ) ) ; else if ( key . equals ( TEXT ) ) this . setText ( value ) ; else if ( key . equals ( TwitterUser . NAME ) ) this . getUser ( ) . setName ( value ) ; else if ( key . equals ( TwitterUser . SCREEN_NAME ) ) this . getUser ( ) . setScreenName ( value ) ; else if ( key . equals ( TwitterUser . LOCATION ) ) this . getUser ( ) . setLocation ( value ) ; else if ( key . equals ( TwitterUser . DESCRIPTION ) ) this . getUser ( ) . setDescription ( value ) ; else if ( key . equals ( TwitterUser . PROFILE_IMAGE_URL ) ) this . getUser ( ) . setProfileImageURL ( value ) ; else if ( key . equals ( TwitterUser . URL ) ) this . getUser ( ) . setUrl ( value ) ; else if ( key . equals ( TwitterUser . IS_PROTECTED ) ) this . getUser ( ) . setProtected ( Boolean . parseBoolean ( value ) ) ; } public String toString ( ) { return "" + this . getCreatedAt ( ) + "" + "" + this . getText ( ) + "" + "" + this . getUser ( ) ; } private Date makeDate ( String date ) throws ParseException { return new SimpleDateFormat ( TWITTER_DATE_FORMAT , Locale . US ) . parse ( date ) ; } } package jtwitter ; import java . net . URL ; import java . net . MalformedURLException ; public class TwitterUser { public static final String ID = "" ; public static final String NAME = "" ; public static final String SCREEN_NAME = "" ; public static final String LOCATION = "" ; public static final String DESCRIPTION = "" ; public static final String PROFILE_IMAGE_URL = "" ; public static final String URL = "" ; public static final String IS_PROTECTED = "" ; private long id ; private String name ; private String screenName ; private String location ; private String description ; private URL profileImageURL ; private URL url ; private boolean isProtected ; public TwitterUser ( long id , String name , String screenName , String location , String description , String profileImageURL , String url , boolean isProtected ) throws MalformedURLException { this . id = id ; this . name = name ; this . screenName = screenName ; this . location = location ; this . description = description ; this . isProtected = isProtected ; setProfileImageURL ( profileImageURL ) ; setUrl ( url ) ; } public TwitterUser ( ) { } public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this . description = description ; } public long getId ( ) { return id ; } public void setId ( long id ) { this . id = id ; } public boolean isProtected ( ) { return isProtected ; } public void setProtected ( boolean isProtected ) { this . isProtected = isProtected ; } public String getLocation ( ) { return location ; } public void setLocation ( String location ) { this . location = location ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public URL getProfileImageURL ( ) { return profileImageURL ; } public void setProfileImageURL ( String profileImageURL ) { try { this . profileImageURL = new URL ( profileImageURL ) ; } catch ( MalformedURLException e ) { this . profileImageURL = null ; } } public String getScreenName ( ) { return screenName ; } public void setScreenName ( String screenName ) { this . screenName = screenName ; } public URL getUrl ( ) { return url ; } public void setUrl ( String url ) { try { this . url = new URL ( url ) ; } catch ( MalformedURLException e ) { this . url = null ; } } @ Override public int hashCode ( ) { final int PRIME = ; int result = ; result = PRIME * result + ( int ) id ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; final TwitterUser other = ( TwitterUser ) obj ; if ( id != other . id ) return false ; return true ; } public String toString ( ) { return "" + getName ( ) + "" + getScreenName ( ) + "" ; } } package jtwitter ; import java . io . IOException ; import java . net . HttpURLConnection ; public class TwitterConnectionException extends Exception { private HttpURLConnection conn ; public TwitterConnectionException ( HttpURLConnection conn , Throwable cause ) { super ( cause ) ; this . conn = conn ; } public int getResponseCode ( ) { try { return conn . getResponseCode ( ) ; } catch ( IOException e ) { return - ; } } public String getResponseMessage ( ) { try { return conn . getResponseMessage ( ) ; } catch ( IOException e ) { return null ; } } } package jtwitter ; import java . io . IOException ; import java . io . InputStream ; import java . io . StringReader ; import java . net . MalformedURLException ; import java . text . ParseException ; import java . util . HashMap ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import org . w3c . dom . Document ; import org . w3c . dom . NodeList ; import org . xml . sax . SAXException ; import org . xml . sax . InputSource ; public class TwitterResponse { private static final String TOP_LEVEL_NODE_NAME = "" ; private static final String USER_NODE_NAME = "" ; private static final String TEXT_NODE_NAME = "" ; DocumentBuilder builder ; NodeList nodes ; HashMap < Integer , TwitterEntry > entries = new HashMap < Integer , TwitterEntry > ( ) ; public TwitterResponse ( ) throws SAXException , IOException , ParserConfigurationException { builder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; } public TwitterResponse parse ( InputStream xmlStream ) throws SAXException , IOException , ParseException , MalformedURLException { Document d = builder . parse ( xmlStream ) ; nodes = d . getElementsByTagName ( TOP_LEVEL_NODE_NAME ) ; readEntries ( ) ; return this ; } public TwitterResponse parse ( String xmlString ) throws SAXException , IOException , ParseException , MalformedURLException { Document d = builder . parse ( new InputSource ( new StringReader ( xmlString ) ) ) ; nodes = d . getElementsByTagName ( TOP_LEVEL_NODE_NAME ) ; readEntries ( ) ; return this ; } public int getNumberOfItems ( ) { return entries . size ( ) ; } public TwitterEntry getItemAt ( int index ) { return entries . get ( index ) ; } private void readEntries ( ) throws ParseException , MalformedURLException { for ( int i = ; i < nodes . getLength ( ) ; i ++ ) { entries . put ( i , readEntry ( i ) ) ; } } private TwitterEntry readEntry ( int index ) throws ParseException , MalformedURLException { TwitterEntry entry = new TwitterEntry ( ) ; NodeList nd = nodes . item ( index ) . getChildNodes ( ) ; for ( int i = ; i < nd . getLength ( ) ; i ++ ) { if ( ! nd . item ( i ) . getNodeName ( ) . equals ( TEXT_NODE_NAME ) ) { if ( nd . item ( i ) . getNodeName ( ) . equals ( USER_NODE_NAME ) ) { NodeList nd_usr = nd . item ( i ) . getChildNodes ( ) ; for ( int j = ; j < nd_usr . getLength ( ) ; j ++ ) { if ( ! nd_usr . item ( j ) . getNodeName ( ) . equals ( TEXT_NODE_NAME ) ) { String value = "" , name = nd_usr . item ( j ) . getNodeName ( ) ; if ( nd_usr . item ( j ) . hasChildNodes ( ) ) value = nd_usr . item ( j ) . getFirstChild ( ) . getNodeValue ( ) ; entry . addAttribute ( name , value ) ; } } } else { String value = "" , name = nd . item ( i ) . getNodeName ( ) ; if ( nd . item ( i ) . hasChildNodes ( ) ) value = nd . item ( i ) . getFirstChild ( ) . getNodeValue ( ) ; entry . addAttribute ( name , value ) ; } } } return entry ; } } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsRational extends Structure { public NativeLong numerator ; public NativeLong denominator ; public EdsRational ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" } ) ; } public EdsRational ( NativeLong numerator , NativeLong denominator ) { super ( ) ; this . numerator = numerator ; this . denominator = denominator ; initFieldOrder ( ) ; } public static class ByReference extends EdsRational implements Structure . ByReference { } ; public static class ByValue extends EdsRational implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsDirectoryItemInfo extends Structure { public NativeLong size ; public int isFolder ; public NativeLong groupID ; public NativeLong option ; public byte [ ] szFileName = new byte [ ( ) ] ; public NativeLong format ; public EdsDirectoryItemInfo ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" , "" , "" } ) ; } public EdsDirectoryItemInfo ( NativeLong size , int isFolder , NativeLong groupID , NativeLong option , byte szFileName [ ] , NativeLong format ) { super ( ) ; this . size = size ; this . isFolder = isFolder ; this . groupID = groupID ; this . option = option ; if ( szFileName . length != this . szFileName . length ) throw new IllegalArgumentException ( "" ) ; this . szFileName = szFileName ; this . format = format ; initFieldOrder ( ) ; } public static class ByReference extends EdsDirectoryItemInfo implements Structure . ByReference { } ; public static class ByValue extends EdsDirectoryItemInfo implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsPropertyDesc extends Structure { public NativeLong form ; public NativeLong access ; public NativeLong numElements ; public NativeLong [ ] propDesc = new NativeLong [ ( ) ] ; public EdsPropertyDesc ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" } ) ; } public EdsPropertyDesc ( NativeLong form , NativeLong access , NativeLong numElements , NativeLong propDesc [ ] ) { super ( ) ; this . form = form ; this . access = access ; this . numElements = numElements ; if ( propDesc . length != this . propDesc . length ) throw new IllegalArgumentException ( "" ) ; this . propDesc = propDesc ; initFieldOrder ( ) ; } public static class ByReference extends EdsPropertyDesc implements Structure . ByReference { } ; public static class ByValue extends EdsPropertyDesc implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsFocusPoint extends Structure { public NativeLong valid ; public NativeLong selected ; public NativeLong justFocus ; public EdsRect rect ; public NativeLong reserved ; public EdsFocusPoint ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" , "" } ) ; } public EdsFocusPoint ( NativeLong valid , NativeLong selected , NativeLong justFocus , EdsRect rect , NativeLong reserved ) { super ( ) ; this . valid = valid ; this . selected = selected ; this . justFocus = justFocus ; this . rect = rect ; this . reserved = reserved ; initFieldOrder ( ) ; } public static class ByReference extends EdsFocusPoint implements Structure . ByReference { } ; public static class ByValue extends EdsFocusPoint implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsSize extends Structure { public NativeLong width ; public NativeLong height ; public EdsSize ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" } ) ; } public EdsSize ( NativeLong width , NativeLong height ) { super ( ) ; this . width = width ; this . height = height ; initFieldOrder ( ) ; } public static class ByReference extends EdsSize implements Structure . ByReference { } ; public static class ByValue extends EdsSize implements Structure . ByValue { } ; } package edsdk ; import java . nio . ByteBuffer ; import java . nio . IntBuffer ; import com . sun . jna . Library ; import com . sun . jna . NativeLong ; import com . sun . jna . Pointer ; import com . sun . jna . PointerType ; import com . sun . jna . ptr . IntByReference ; import com . sun . jna . ptr . NativeLongByReference ; import com . sun . jna . ptr . PointerByReference ; import com . sun . jna . ptr . ShortByReference ; import com . sun . jna . win32 . StdCallLibrary . StdCallCallback ; public interface EdSdkLibrary extends Library { public static interface EdsDataType { public static final int kEdsDataType_Unknown = ; public static final int kEdsDataType_Bool = ; public static final int kEdsDataType_String = ; public static final int kEdsDataType_Int8 = ; public static final int kEdsDataType_UInt8 = ; public static final int kEdsDataType_Int16 = ; public static final int kEdsDataType_UInt16 = ; public static final int kEdsDataType_Int32 = ; public static final int kEdsDataType_UInt32 = ; public static final int kEdsDataType_Int64 = ; public static final int kEdsDataType_UInt64 = ; public static final int kEdsDataType_Float = ; public static final int kEdsDataType_Double = ; public static final int kEdsDataType_ByteBlock = ; public static final int kEdsDataType_Rational = ; public static final int kEdsDataType_Point = ; public static final int kEdsDataType_Rect = ; public static final int kEdsDataType_Time = ; public static final int kEdsDataType_Bool_Array = ; public static final int kEdsDataType_Int8_Array = ; public static final int kEdsDataType_Int16_Array = ; public static final int kEdsDataType_Int32_Array = ; public static final int kEdsDataType_UInt8_Array = ; public static final int kEdsDataType_UInt16_Array = ; public static final int kEdsDataType_UInt32_Array = ; public static final int kEdsDataType_Rational_Array = ; public static final int kEdsDataType_FocusInfo = ; public static final int kEdsDataType_PictureStyleDesc = ; } ; public static interface EdsEvfAf { public static final int kEdsCameraCommand_EvfAf_OFF = ; public static final int kEdsCameraCommand_EvfAf_ON = ; } ; public static interface EdsShutterButton { public static final int kEdsCameraCommand_ShutterButton_OFF = ; public static final int kEdsCameraCommand_ShutterButton_Halfway = ; public static final int kEdsCameraCommand_ShutterButton_Completely = ; public static final int kEdsCameraCommand_ShutterButton_Halfway_NonAF = ; public static final int kEdsCameraCommand_ShutterButton_Completely_NonAF = ; } ; public static interface EdsEvfDriveLens { public static final int kEdsEvfDriveLens_Near1 = ; public static final int kEdsEvfDriveLens_Near2 = ; public static final int kEdsEvfDriveLens_Near3 = ; public static final int kEdsEvfDriveLens_Far1 = ; public static final int kEdsEvfDriveLens_Far2 = ; public static final int kEdsEvfDriveLens_Far3 = ; } ; public static interface EdsEvfDepthOfFieldPreview { public static final int kEdsEvfDepthOfFieldPreview_OFF = ; public static final int kEdsEvfDepthOfFieldPreview_ON = ; } ; public static interface EdsSeekOrigin { public static final int kEdsSeek_Cur = ; public static final int kEdsSeek_Begin = ; public static final int kEdsSeek_End = ; } ; public static interface EdsAccess { public static final int kEdsAccess_Read = ; public static final int kEdsAccess_Write = ; public static final int kEdsAccess_ReadWrite = ; public static final int kEdsAccess_Error = - ; } ; public static interface EdsFileCreateDisposition { public static final int kEdsFileCreateDisposition_CreateNew = ; public static final int kEdsFileCreateDisposition_CreateAlways = ; public static final int kEdsFileCreateDisposition_OpenExisting = ; public static final int kEdsFileCreateDisposition_OpenAlways = ; public static final int kEdsFileCreateDisposition_TruncateExsisting = ; } ; public static interface EdsImageType { public static final int kEdsImageType_Unknown = ; public static final int kEdsImageType_Jpeg = ; public static final int kEdsImageType_CRW = ; public static final int kEdsImageType_RAW = ; public static final int kEdsImageType_CR2 = ; public static final int kEdsImageType_MOVwithTHM = ; public static final int kEdsImageType_MOVwithoutTHM = ; } ; public static interface EdsImageSize { public static final int kEdsImageSize_Large = ; public static final int kEdsImageSize_Middle = ; public static final int kEdsImageSize_Small = ; public static final int kEdsImageSize_Middle1 = ; public static final int kEdsImageSize_Middle2 = ; public static final int kEdsImageSize_Unknown = - ; } ; public static interface EdsCompressQuality { public static final int kEdsCompressQuality_Normal = ; public static final int kEdsCompressQuality_Fine = ; public static final int kEdsCompressQuality_Lossless = ; public static final int kEdsCompressQuality_SuperFine = ; public static final int kEdsCompressQuality_Unknown = - ; } ; public static interface EdsImageQuality { public static final int EdsImageQuality_LJ = ; public static final int EdsImageQuality_M1J = ; public static final int EdsImageQuality_M2J = ; public static final int EdsImageQuality_SJ = ; public static final int EdsImageQuality_LJF = ; public static final int EdsImageQuality_LJN = ; public static final int EdsImageQuality_MJF = ; public static final int EdsImageQuality_MJN = ; public static final int EdsImageQuality_SJF = ; public static final int EdsImageQuality_SJN = ; public static final int EdsImageQuality_S1JF = ; public static final int EdsImageQuality_S1JN = ; public static final int EdsImageQuality_S2JF = ; public static final int EdsImageQuality_S3JF = ; public static final int EdsImageQuality_LR = ; public static final int EdsImageQuality_LRLJF = ; public static final int EdsImageQuality_LRLJN = ; public static final int EdsImageQuality_LRMJF = ; public static final int EdsImageQuality_LRMJN = ; public static final int EdsImageQuality_LRSJF = ; public static final int EdsImageQuality_LRSJN = ; public static final int EdsImageQuality_LRS1JF = ; public static final int EdsImageQuality_LRS1JN = ; public static final int EdsImageQuality_LRS2JF = ; public static final int EdsImageQuality_LRS3JF = ; public static final int EdsImageQuality_LRLJ = ; public static final int EdsImageQuality_LRM1J = ; public static final int EdsImageQuality_LRM2J = ; public static final int EdsImageQuality_LRSJ = ; public static final int EdsImageQuality_MR = ; public static final int EdsImageQuality_MRLJF = ; public static final int EdsImageQuality_MRLJN = ; public static final int EdsImageQuality_MRMJF = ; public static final int EdsImageQuality_MRMJN = ; public static final int EdsImageQuality_MRSJF = ; public static final int EdsImageQuality_MRSJN = ; public static final int EdsImageQuality_MRS1JF = ; public static final int EdsImageQuality_MRS1JN = ; public static final int EdsImageQuality_MRS2JF = ; public static final int EdsImageQuality_MRS3JF = ; public static final int EdsImageQuality_MRLJ = ; public static final int EdsImageQuality_MRM1J = ; public static final int EdsImageQuality_MRM2J = ; public static final int EdsImageQuality_MRSJ = ; public static final int EdsImageQuality_SR = ; public static final int EdsImageQuality_SRLJF = ; public static final int EdsImageQuality_SRLJN = ; public static final int EdsImageQuality_SRMJF = ; public static final int EdsImageQuality_SRMJN = ; public static final int EdsImageQuality_SRSJF = ; public static final int EdsImageQuality_SRSJN = ; public static final int EdsImageQuality_SRS1JF = ; public static final int EdsImageQuality_SRS1JN = ; public static final int EdsImageQuality_SRS2JF = ; public static final int EdsImageQuality_SRS3JF = ; public static final int EdsImageQuality_SRLJ = ; public static final int EdsImageQuality_SRM1J = ; public static final int EdsImageQuality_SRM2J = ; public static final int EdsImageQuality_SRSJ = ; public static final int EdsImageQuality_Unknown = - ; } ; public static interface EdsImageQualityForLegacy { public static final int kEdsImageQualityForLegacy_LJ = ; public static final int kEdsImageQualityForLegacy_M1J = ; public static final int kEdsImageQualityForLegacy_M2J = ; public static final int kEdsImageQualityForLegacy_SJ = ; public static final int kEdsImageQualityForLegacy_LJF = ; public static final int kEdsImageQualityForLegacy_LJN = ; public static final int kEdsImageQualityForLegacy_MJF = ; public static final int kEdsImageQualityForLegacy_MJN = ; public static final int kEdsImageQualityForLegacy_SJF = ; public static final int kEdsImageQualityForLegacy_SJN = ; public static final int kEdsImageQualityForLegacy_LR = ; public static final int kEdsImageQualityForLegacy_LRLJF = ; public static final int kEdsImageQualityForLegacy_LRLJN = ; public static final int kEdsImageQualityForLegacy_LRMJF = ; public static final int kEdsImageQualityForLegacy_LRMJN = ; public static final int kEdsImageQualityForLegacy_LRSJF = ; public static final int kEdsImageQualityForLegacy_LRSJN = ; public static final int kEdsImageQualityForLegacy_LR2 = ; public static final int kEdsImageQualityForLegacy_LR2LJ = ; public static final int kEdsImageQualityForLegacy_LR2M1J = ; public static final int kEdsImageQualityForLegacy_LR2M2J = ; public static final int kEdsImageQualityForLegacy_LR2SJ = ; public static final int kEdsImageQualityForLegacy_Unknown = - ; } ; public static interface EdsImageSource { public static final int kEdsImageSrc_FullView = ; public static final int kEdsImageSrc_Thumbnail = ; public static final int kEdsImageSrc_Preview = ; public static final int kEdsImageSrc_RAWThumbnail = ; public static final int kEdsImageSrc_RAWFullView = ; } ; public static interface EdsTargetImageType { public static final int kEdsTargetImageType_Unknown = ; public static final int kEdsTargetImageType_Jpeg = ; public static final int kEdsTargetImageType_TIFF = ; public static final int kEdsTargetImageType_TIFF16 = ; public static final int kEdsTargetImageType_RGB = ; public static final int kEdsTargetImageType_RGB16 = ; public static final int kEdsTargetImageType_DIB = ; } ; public static interface EdsProgressOption { public static final int kEdsProgressOption_NoReport = ; public static final int kEdsProgressOption_Done = ; public static final int kEdsProgressOption_Periodically = ; } ; public static interface EdsFileAttributes { public static final int kEdsFileAttribute_Normal = ; public static final int kEdsFileAttribute_ReadOnly = ; public static final int kEdsFileAttribute_Hidden = ; public static final int kEdsFileAttribute_System = ; public static final int kEdsFileAttribute_Archive = ; } ; public static interface EdsBatteryLevel2 { public static final int kEdsBatteryLevel2_Empty = ; public static final int kEdsBatteryLevel2_Low = ; public static final int kEdsBatteryLevel2_Half = ; public static final int kEdsBatteryLevel2_Normal = ; public static final int kEdsBatteryLevel2_Hi = ; public static final int kEdsBatteryLevel2_Quarter = ; public static final int kEdsBatteryLevel2_Error = ; public static final int kEdsBatteryLevel2_BCLevel = ; public static final int kEdsBatteryLevel2_AC = - ; } ; public static interface EdsSaveTo { public static final int kEdsSaveTo_Camera = ; public static final int kEdsSaveTo_Host = ; public static final int kEdsSaveTo_Both = EdSdkLibrary . EdsSaveTo . kEdsSaveTo_Camera | EdSdkLibrary . EdsSaveTo . kEdsSaveTo_Host ; } ; public static interface EdsStorageType { public static final int kEdsStorageType_Non = ; public static final int kEdsStorageType_CF = ; public static final int kEdsStorageType_SD = ; public static final int kEdsStorageType_HD = ; } ; public static interface EdsWhiteBalance { public static final int kEdsWhiteBalance_Auto = ; public static final int kEdsWhiteBalance_Daylight = ; public static final int kEdsWhiteBalance_Cloudy = ; public static final int kEdsWhiteBalance_Tangsten = ; public static final int kEdsWhiteBalance_Fluorescent = ; public static final int kEdsWhiteBalance_Strobe = ; public static final int kEdsWhiteBalance_WhitePaper = ; public static final int kEdsWhiteBalance_Shade = ; public static final int kEdsWhiteBalance_ColorTemp = ; public static final int kEdsWhiteBalance_PCSet1 = ; public static final int kEdsWhiteBalance_PCSet2 = ; public static final int kEdsWhiteBalance_PCSet3 = ; public static final int kEdsWhiteBalance_WhitePaper2 = ; public static final int kEdsWhiteBalance_WhitePaper3 = ; public static final int kEdsWhiteBalance_WhitePaper4 = ; public static final int kEdsWhiteBalance_WhitePaper5 = ; public static final int kEdsWhiteBalance_PCSet4 = ; public static final int kEdsWhiteBalance_PCSet5 = ; public static final int kEdsWhiteBalance_Click = - ; public static final int kEdsWhiteBalance_Pasted = - ; } ; public static interface EdsPhotoEffect { public static final int kEdsPhotoEffect_Off = ; public static final int kEdsPhotoEffect_Monochrome = ; } ; public static interface EdsColorMatrix { public static final int kEdsColorMatrix_Custom = ; public static final int kEdsColorMatrix_1 = ; public static final int kEdsColorMatrix_2 = ; public static final int kEdsColorMatrix_3 = ; public static final int kEdsColorMatrix_4 = ; public static final int kEdsColorMatrix_5 = ; public static final int kEdsColorMatrix_6 = ; public static final int kEdsColorMatrix_7 = ; } ; public static interface EdsFilterEffect { public static final int kEdsFilterEffect_None = ; public static final int kEdsFilterEffect_Yellow = ; public static final int kEdsFilterEffect_Orange = ; public static final int kEdsFilterEffect_Red = ; public static final int kEdsFilterEffect_Green = ; } ; public static interface EdsTonigEffect { public static final int kEdsTonigEffect_None = ; public static final int kEdsTonigEffect_Sepia = ; public static final int kEdsTonigEffect_Blue = ; public static final int kEdsTonigEffect_Purple = ; public static final int kEdsTonigEffect_Green = ; } ; public static interface EdsColorSpace { public static final int kEdsColorSpace_sRGB = ; public static final int kEdsColorSpace_AdobeRGB = ; public static final int kEdsColorSpace_Unknown = - ; } ; public static interface EdsPictureStyle { public static final int kEdsPictureStyle_Standard = ; public static final int kEdsPictureStyle_Portrait = ; public static final int kEdsPictureStyle_Landscape = ; public static final int kEdsPictureStyle_Neutral = ; public static final int kEdsPictureStyle_Faithful = ; public static final int kEdsPictureStyle_Monochrome = ; public static final int kEdsPictureStyle_User1 = ; public static final int kEdsPictureStyle_User2 = ; public static final int kEdsPictureStyle_User3 = ; public static final int kEdsPictureStyle_PC1 = ; public static final int kEdsPictureStyle_PC2 = ; public static final int kEdsPictureStyle_PC3 = ; } ; public static interface EdsTransferOption { public static final int kEdsTransferOption_ByDirectTransfer = ; public static final int kEdsTransferOption_ByRelease = ; public static final int kEdsTransferOption_ToDesktop = ; } ; public static interface EdsAEMode { public static final int kEdsAEMode_Program = ; public static final int kEdsAEMode_Tv = ; public static final int kEdsAEMode_Av = ; public static final int kEdsAEMode_Manual = ; public static final int kEdsAEMode_Bulb = ; public static final int kEdsAEMode_A_DEP = ; public static final int kEdsAEMode_DEP = ; public static final int kEdsAEMode_Custom = ; public static final int kEdsAEMode_Lock = ; public static final int kEdsAEMode_Green = ; public static final int kEdsAEMode_NightPortrait = ; public static final int kEdsAEMode_Sports = ; public static final int kEdsAEMode_Portrait = ; public static final int kEdsAEMode_Landscape = ; public static final int kEdsAEMode_Closeup = ; public static final int kEdsAEMode_FlashOff = ; public static final int kEdsAEMode_CreativeAuto = ; public static final int kEdsAEMode_Movie = ; public static final int kEdsAEMode_PhotoInMovie = ; public static final int kEdsAEMode_Unknown = - ; } ; public static interface EdsBracket { public static final int kEdsBracket_AEB = ; public static final int kEdsBracket_ISOB = ; public static final int kEdsBracket_WBB = ; public static final int kEdsBracket_FEB = ; public static final int kEdsBracket_Unknown = - ; } ; public static interface EdsEvfOutputDevice { public static final int kEdsEvfOutputDevice_TFT = ; public static final int kEdsEvfOutputDevice_PC = ; } ; public static interface EdsEvfZoom { public static final int kEdsEvfZoom_Fit = ; public static final int kEdsEvfZoom_x5 = ; public static final int kEdsEvfZoom_x10 = ; } ; public static interface EdsEvfAFMode { public static final int Evf_AFMode_Quick = ; public static final int Evf_AFMode_Live = ; public static final int Evf_AFMode_LiveFace = ; } ; public static interface EdsStroboMode { public static final int kEdsStroboModeInternal = ; public static final int kEdsStroboModeExternalETTL = ; public static final int kEdsStroboModeExternalATTL = ; public static final int kEdsStroboModeExternalTTL = ; public static final int kEdsStroboModeExternalAuto = ; public static final int kEdsStroboModeExternalManual = ; public static final int kEdsStroboModeManual = ; } ; public static interface EdsETTL2Mode { public static final int kEdsETTL2ModeEvaluative = ; public static final int kEdsETTL2ModeAverage = ; } ; public static final int EDS_ERR_STREAM_SEEK_ERROR = ; public static final int EDS_ERR_INVALID_PARAMETER = ; public static final int kEdsObjectEvent_VolumeInfoChanged = ; public static final int kEdsStateEvent_ShutDownTimerUpdate = ; public static final int EDS_ERR_FILE_NOT_FOUND = ; public static final int EDS_CMP_ID_CLIENT_COMPONENTID = ; public static final int kEdsPropID_Bracket = ; public static final int kEdsPropID_GPSLatitudeRef = ; public static final int EDS_ERR_INVALID_FN_CALL = ; public static final int kEdsPropID_WhiteBalanceBracket = ; public static final int EDS_ERR_INCOMPATIBLE_VERSION = ; public static final int kEdsPropID_DriveMode = ; public static final int EDS_ERR_PROTECTION_VIOLATION = ; public static final int kEdsPropID_Copyright = ; public static final int kEdsPropID_FocalLength = ; public static final int EDS_ERR_INVALID_DEVICEPROP_FORMAT = ; public static final int kEdsPropID_LensName = ; public static final int EDS_ERR_FILE_DISK_FULL_ERROR = ; public static final int kEdsPropID_PictureStyle = ; public static final int kEdsPropID_DigitalExposure = ; public static final int EDS_ERR_WAIT_TIMEOUT_ERROR = ; public static final int EDS_ERR_INVALID_OBJECTFORMATCODE = ; public static final int EDS_ERR_TAKE_PICTURE_MOVIE_CROP_NG = ; public static final int EDS_ERR_INVALID_LENGTH = ; public static final int kEdsPropID_WhiteBalanceShift = ; public static final int kEdsObjectEvent_FolderUpdateItems = ; public static final int EDS_ERR_INVALID_TRANSACTIONID = ; public static final int kEdsObjectEvent_VolumeAdded = ; public static final int kEdsPropID_Contrast = ; public static final int EDS_ERR_STREAM_READ_ERROR = ; public static final int EDS_ERR_DEVICE_DISK_ERROR = ; public static final int kEdsPropID_FlashMode = ; public static final int EDS_ERR_SELECTION_UNAVAILABLE = ; public static final int EDS_MAX_NAME = ; public static final int EDS_RESERVED_MASK = ; public static final int EDS_CMP_ID_HLSDK_COMPONENTID = ; public static final int kEdsStateEvent_JobStatusChanged = ; public static final int kEdsPropID_Evf_Histogram = ; public static final int EDS_ERR_STREAM_ALREADY_OPEN = ; public static final int EDS_ISSPECIFIC_MASK = - ; public static final int kEdsPropID_MyMenu = ; public static final int kEdsObjectEvent_DirItemRemoved = ; public static final int kEdsPropID_ICCProfile = ; public static final int EDS_ERR_FILE_TOO_MANY_OPEN = ; public static final int kEdsPropID_PictureStyleCaption = ; public static final int EDS_ERR_UNEXPECTED_EXCEPTION = ; public static final int EDS_ERR_STI_DEVICE_RELEASE_ERROR = ; public static final int EDS_ERR_TAKE_PICTURE_SILENCE_NG = ; public static final int kEdsPropID_BatteryQuality = ; public static final int EDS_ERR_FILE_DATA_CORRUPT = ; public static final int kEdsPropID_Evf_OutputDevice = ; public static final int kEdsPropID_OwnerName = ; public static final int kEdsPropID_Sharpness = ; public static final int EDS_ERR_INVALID_SORT_FN = ; public static final int kEdsPropID_DepthOfField = ; public static final int EDS_ERR_ENUM_NA = ; public static final int EDS_ERR_STI_UNKNOWN_ERROR = ; public static final int EDS_ERR_INVALID_POINTER = ; public static final int kEdsPropID_WBCoeffs = ; public static final int kEdsPropID_GPSLongitude = ; public static final int EDS_ERR_DEVICE_INVALID = ; public static final int EDS_ERR_USB_DEVICE_UNLOCK_ERROR = ; public static final int kEdsPropID_Tv = ; public static final int EDS_ERR_SPECIFICATION_OF_DESTINATION_UNSUPPORTED = ; public static final int kEdsCameraStatusCommand_EnterDirectTransfer = ; public static final int kEdsPropID_FirmwareVersion = ; public static final int EDS_ERR_DIR_IO_ERROR = ; public static final int EDS_ERR_CAPTURE_ALREADY_TERMINATED = ; public static final int EDS_ERR_INVALID_ID = ; public static final int kEdsPropID_HDDirectoryStructure = ; public static final int EDS_ERR_FILE_ALREADY_EXISTS = ; public static final int EDS_ERR_DEVICE_MEMORY_FULL = ; public static final int kEdsPropID_GPSLongitudeRef = ; public static final int EDS_ERR_INVALID_HANDLE = ; public static final int kEdsPropID_Artist = ; public static final int EDS_ERR_NOT_SUPPORTED = ; public static final int kEdsCameraCommand_DoClickWBEvf = ; public static final int EDS_ERR_INVALID_INDEX = ; public static final int kEdsObjectEvent_DirItemContentChanged = ; public static final int EDS_ERR_INVALID_PARENTOBJECT = ; public static final int EDS_ERR_DEVICE_NO_DISK = ; public static final int kEdsPropID_Evf_ImagePosition = ; public static final int kEdsPropID_DateTime = ; public static final int kEdsCameraStatusCommand_UILock = ; public static final int EDS_ERR_STREAM_PERMISSION_ERROR = ; public static final int kEdsPropertyEvent_PropertyChanged = ; public static final int EDS_ERR_DEVICE_NOT_RELEASED = ; public static final int kEdsPropID_MakerName = ; public static final int kEdsObjectEvent_DirItemCreated = ; public static final int EDS_ERR_NO_VALID_OBJECTINFO = ; public static final int kEdsCameraCommand_ExtendShutDownTimer = ; public static final int kEdsPropID_Av = ; public static final int EDS_ERR_TAKE_PICTURE_CARD_NG = ; public static final int EDS_ERR_DEVICE_DIAL_CHANGED = ; public static final int EDS_ERR_DEVICE_BUSY = ; public static final int EDS_ERR_LENS_COVER_CLOSE = ; public static final int kEdsPropID_ProductName = ; public static final int kEdsCameraCommand_BulbEnd = ; public static final int kEdsPropID_BatteryLevel = ; public static final int kEdsPropID_Orientation = ; public static final int kEdsPropID_FlashCompensation = ; public static final int EDS_ERR_DEVICE_CF_GATE_CHANGED = ; public static final int EDS_TRANSFER_BLOCK_SIZE = ; public static final int oldif = ; public static final int kEdsPropID_GPSTimeStamp = ; public static final int EDS_ERR_DEVICEPROP_NOT_SUPPORTED = ; public static final int kEdsPropID_CFn = ; public static final int kEdsPropID_ColorMatrix = ; public static final int kEdsPropID_NoiseReduction = ; public static final int EDS_ERR_COMM_PORT_IS_IN_USE = ; public static final int EDS_ERR_LAST_GENERIC_ERROR_PLUS_ONE = ; public static final int kEdsPropID_GPSVersionID = ; public static final int kEdsPropID_Evf_ColorTemperature = ; public static final int kEdsPropID_GPSStatus = ; public static final int EDS_ERR_STREAM_END_OF_STREAM = ; public static final int EDS_ERR_FILE_WRITE_ERROR = ; public static final int EDS_ERR_DIR_NOT_FOUND = ; public static final int kEdsPropID_ToneCurve = ; public static final int kEdsCameraCommand_PressShutterButton = ; public static final int kEdsPropID_Evf_ZoomRect = ; public static final int EDS_ERR_OK = ; public static final int kEdsPropID_AtCapture_Flag = - ; public static final int kEdsPropID_GPSDateStamp = ; public static final int EDS_ERR_DIR_ENTRY_EXISTS = ; public static final int EDS_ERR_FILE_SEEK_ERROR = ; public static final int EDS_ERR_PROPERTIES_NOT_LOADED = ; public static final int EDS_ERR_SESSION_NOT_OPEN = ; public static final int kEdsPropID_SaveTo = ; public static final int EDS_ERR_TAKE_PICTURE_CARD_PROTECT_NG = ; public static final int kEdsPropID_ExposureCompensation = ; public static final int kEdsPropID_CurrentFolder = ; public static final int kEdsCameraStatusCommand_UIUnLock = ; public static final int EDS_ERR_DEVICE_INTERNAL_ERROR = ; public static final int EDS_ERR_FILE_FORMAT_UNRECOGNIZED = ; public static final int kEdsStateEvent_InternalError = ; public static final int EDS_COMPONENTID_MASK = ; public static final int EDS_ERR_DIR_ENTRY_NOT_FOUND = ; public static final int kEdsCameraCommand_BulbStart = ; public static final int kEdsPropID_ColorTemperature = ; public static final int EDS_ERR_STREAM_BAD_OPTIONS = ; public static final int kEdsObjectEvent_VolumeUpdateItems = ; public static final int EDS_ERR_COMM_BUFFER_FULL = ; public static final int EDS_ERR_COMM_USB_BUS_ERR = ; public static final int kEdsPropID_ColorSpace = ; public static final int kEdsPropID_AFMode = ; public static final int EDS_ERR_TAKE_PICTURE_AF_NG = ; public static final int kEdsStateEvent_BulbExposureTime = ; public static final int EDS_ERR_DEVICE_NOT_INSTALLED = ; public static final int kEdsPropID_Evf_WhiteBalance = ; public static final int EDS_ERR_DEVICE_INVALID_PARAMETER = ; public static final int kEdsPropID_PhotoEffect = ; public static final int kEdsPropID_Evf_DepthOfFieldPreview = ; public static final int kEdsPropID_Evf_Mode = ; public static final int kEdsPropID_Evf_FocusAid = ; public static final int kEdsPropID_FlashOn = ; public static final int kEdsPropID_ISOBracket = ; public static final int EDS_ERR_SPECIFICATION_BY_FORMAT_UNSUPPORTED = ; public static final int kEdsPropID_EFCompensation = ; public static final int kEdsPropID_PictureStyleDesc = ; public static final int kEdsCameraCommand_DoEvfAf = ; public static final int kEdsPropertyEvent_PropertyDescChanged = ; public static final int kEdsPropID_ISOSpeed = ; public static final int EDS_ERR_PROPERTIES_MISMATCH = ; public static final int EDS_ERR_STREAM_WRITE_ERROR = ; public static final int EDS_ERR_INTERNAL_ERROR = ; public static final int EDS_ERR_MEM_FREE_FAILED = ; public static final int EDS_ERR_FILE_OPEN_ERROR = ; public static final int kEdsPropID_JpegQuality = ; public static final int kEdsPropID_BodyID = ; public static final int kEdsPropID_Evf_CoordinateSystem = ; public static final int EDS_ERR_STI_INTERNAL_ERROR = ; public static final int kEdsPropID_AvailableShots = ; public static final int EDS_ERR_STI_DEVICE_CREATE_ERROR = ; public static final int EDS_ERR_INVALID_CODE_FORMAT = ; public static final int kEdsStateEvent_AfResult = ; public static final int kEdsStateEvent_All = ; public static final int EDS_ERRORID_MASK = ; public static final int kEdsPropID_RedEye = ; public static final int EDS_ERR_UNIMPLEMENTED = ; public static final int EDS_ERR_OPERATION_CANCELLED = ; public static final int kEdsPropID_Evf_ZoomPosition = ; public static final int kEdsObjectEvent_DirItemRequestTransfer = ; public static final int NULL = ; public static final int EDS_ERR_TRANSACTION_CANCELLED = ; public static final int kEdsPropID_Evf_Zoom = ; public static final int kEdsObjectEvent_All = ; public static final int EDS_ERR_STREAM_CLOSE_ERROR = ; public static final int kEdsPropID_FilterEffect = ; public static final int EDS_ERR_INVALID_STRAGEID = ; public static final int EDS_ERR_MEM_ALLOC_FAILED = ; public static final int kEdsPropID_FocusInfo = ; public static final int EDS_ERR_DEVICE_STAY_AWAKE = ; public static final int EDS_ERR_STREAM_NOT_OPEN = ; public static final int kEdsPropertyEvent_All = ; public static final int kEdsObjectEvent_DirItemCancelTransferDT = ; public static final int EDS_ERR_TAKE_PICTURE_MIRROR_UP_NG = ; public static final int EDS_ERR_HANDLE_NOT_FOUND = ; public static final int kEdsStateEvent_Shutdown = ; public static final int EDS_ERR_INVALID_DEVICEPROP_VALUE = ; public static final int kEdsPropID_Evf_HistogramStatus = ; public static final int kEdsPropID_GPSAltitudeRef = ; public static final int EDS_ERR_COMM_DEVICE_INCOMPATIBLE = ; public static final int EDS_ERR_DEVICE_NOT_LAUNCHED = ; public static final int kEdsPropID_ImageQuality = ; public static final int EDS_ERR_FILE_TELL_ERROR = ; public static final int EDS_ERR_SESSION_ALREADY_OPEN = ; public static final int EDS_ERR_DEVICE_NOT_FOUND = ; public static final int EDS_ERR_STREAM_IO_ERROR = ; public static final int EDS_ERR_INVALID_FN_POINTER = ; public static final int FALSE = ; public static final int EDS_ERR_OPERATION_REFUSED = ; public static final int kEdsPropID_GPSMapDatum = ; public static final int kEdsObjectEvent_VolumeRemoved = ; public static final int EDS_ERR_SELF_TEST_FAILED = ; public static final int kEdsPropID_WhiteBalance = ; public static final int kEdsPropID_GPSAltitude = ; public static final int EDS_ERR_COMM_DISCONNECTED = ; public static final int kEdsObjectEvent_DirItemRequestTransferDT = ; public static final int EDS_ERR_USB_DEVICE_LOCK_ERROR = ; public static final int EDS_CMP_ID_LLSDK_COMPONENTID = ; public static final int kEdsPropID_GPSSatellites = ; public static final int kEdsPropID_AEMode = ; public static final int kEdsCameraCommand_DriveLensEvf = ; public static final int kEdsCameraStatusCommand_ExitDirectTransfer = ; public static final int kEdsPropID_ETTL2Mode = ; public static final int kEdsPropID_ToningEffect = ; public static final int EDS_ERR_DEVICE_EMERGENCY = ; public static final int kEdsCameraCommand_TakePicture = ; public static final int EDS_ERR_STREAM_TELL_ERROR = ; public static final int kEdsPropID_LensStatus = ; public static final int EDS_ERR_TAKE_PICTURE_STROBO_CHARGE_NG = ; public static final int kEdsPropID_ParameterSet = ; public static final int kEdsStateEvent_CaptureError = ; public static final int kEdsPropID_Unknown = ; public static final int EDS_ERR_PROPERTIES_UNAVAILABLE = ; public static final int kEdsPropID_AEBracket = ; public static final int EDS_ERR_PARTIAL_DELETION = ; public static final int EDS_ERR_TAKE_PICTURE_RESERVED = ; public static final int EDS_ERR_STREAM_COULDNT_BEGIN_THREAD = ; public static final int EDS_ERR_FILE_READ_ERROR = ; public static final int kEdsPropID_ColorTone = ; public static final int kEdsPropID_GPSLatitude = ; public static final int EDS_ERR_MISSING_SUBCOMPONENT = ; public static final int kEdsPropID_ColorSaturation = ; public static final int kEdsPropID_MeteringMode = ; public static final int EDS_ERR_FILE_NAMING_NA = ; public static final int kEdsPropID_Linear = ; public static final int EDS_ERR_FILE_IO_ERROR = ; public static final int kEdsPropID_CurrentStorage = ; public static final int kEdsPropID_FEBracket = ; public static final int EDS_ERR_FILE_PERMISSION_ERROR = ; public static final int kEdsPropID_ClickWBPoint = ; public static final int kEdsStateEvent_WillSoonShutDown = ; public static final int EDS_ERR_TAKE_PICTURE_SENSOR_CLEANING_NG = ; public static final int TRUE = ; public static final int EDS_ERR_FILE_CLOSE_ERROR = ; public static final int EDS_ERR_INCOMPLETE_TRANSFER = ; public static final int EDS_ERR_TAKE_PICTURE_NO_CARD_NG = ; public static final int EDS_ERR_LOW_BATTERY = ; public static final int EDS_ERR_UNKNOWN_COMMAND = ; public static final int EDS_ERR_UNKNOWN_VENDOR_CODE = ; public static final int EDS_ERR_STREAM_OPEN_ERROR = ; public static final int kEdsObjectEvent_DirItemInfoChanged = ; public static final int EDS_ERR_DIR_NOT_EMPTY = ; public static final int EDS_ERR_OBJECT_NOTREADY = ; public static final int kEdsPropID_Evf_AFMode = ; public interface EdsProgressCallback extends StdCallCallback { NativeLong apply ( NativeLong inPercent , EdSdkLibrary . EdsVoid inContext , IntByReference outCancel ) ; } ; public interface EdsCameraAddedHandler extends StdCallCallback { NativeLong apply ( EdSdkLibrary . EdsVoid inContext ) ; } ; public interface EdsPropertyEventHandler extends StdCallCallback { NativeLong apply ( NativeLong inEvent , NativeLong inPropertyID , NativeLong inParam , EdSdkLibrary . EdsVoid inContext ) ; } ; public interface EdsObjectEventHandler extends StdCallCallback { NativeLong apply ( NativeLong inEvent , EdSdkLibrary . __EdsObject inRef , EdSdkLibrary . EdsVoid inContext ) ; } ; public interface EdsStateEventHandler extends StdCallCallback { NativeLong apply ( NativeLong inEvent , NativeLong inEventData , EdSdkLibrary . EdsVoid inContext ) ; } ; NativeLong EdsInitializeSDK ( ) ; NativeLong EdsTerminateSDK ( ) ; NativeLong EdsRetain ( EdSdkLibrary . __EdsObject inRef ) ; NativeLong EdsRelease ( EdSdkLibrary . __EdsObject inRef ) ; NativeLong EdsGetChildCount ( EdSdkLibrary . __EdsObject inRef , NativeLongByReference outCount ) ; @ Deprecated NativeLong EdsGetChildAtIndex ( EdSdkLibrary . __EdsObject inRef , NativeLong inIndex , PointerByReference outRef ) ; NativeLong EdsGetChildAtIndex ( EdSdkLibrary . __EdsObject inRef , NativeLong inIndex , EdSdkLibrary . __EdsObject outRef [ ] ) ; @ Deprecated NativeLong EdsGetParent ( EdSdkLibrary . __EdsObject inRef , PointerByReference outParentRef ) ; NativeLong EdsGetParent ( EdSdkLibrary . __EdsObject inRef , EdSdkLibrary . __EdsObject outParentRef [ ] ) ; @ Deprecated NativeLong EdsGetPropertySize ( EdSdkLibrary . __EdsObject inRef , NativeLong inPropertyID , NativeLong inParam , IntByReference outDataType , NativeLongByReference outSize ) ; NativeLong EdsGetPropertySize ( EdSdkLibrary . __EdsObject inRef , NativeLong inPropertyID , NativeLong inParam , IntBuffer outDataType , NativeLongByReference outSize ) ; NativeLong EdsGetPropertyData ( EdSdkLibrary . __EdsObject inRef , NativeLong inPropertyID , NativeLong inParam , NativeLong inPropertySize , EdSdkLibrary . EdsVoid outPropertyData ) ; NativeLong EdsSetPropertyData ( EdSdkLibrary . __EdsObject inRef , NativeLong inPropertyID , NativeLong inParam , NativeLong inPropertySize , EdSdkLibrary . EdsVoid inPropertyData ) ; NativeLong EdsGetPropertyDesc ( EdSdkLibrary . __EdsObject inRef , NativeLong inPropertyID , EdsPropertyDesc outPropertyDesc ) ; @ Deprecated NativeLong EdsGetCameraList ( PointerByReference outCameraListRef ) ; NativeLong EdsGetCameraList ( EdSdkLibrary . __EdsObject outCameraListRef [ ] ) ; NativeLong EdsGetDeviceInfo ( EdSdkLibrary . __EdsObject inCameraRef , EdsDeviceInfo outDeviceInfo ) ; NativeLong EdsOpenSession ( EdSdkLibrary . __EdsObject inCameraRef ) ; NativeLong EdsCloseSession ( EdSdkLibrary . __EdsObject inCameraRef ) ; NativeLong EdsSendCommand ( EdSdkLibrary . __EdsObject inCameraRef , NativeLong inCommand , NativeLong inParam ) ; NativeLong EdsSendStatusCommand ( EdSdkLibrary . __EdsObject inCameraRef , NativeLong inStatusCommand , NativeLong inParam ) ; NativeLong EdsSetCapacity ( EdSdkLibrary . __EdsObject inCameraRef , edsdk . EdsCapacity . ByValue inCapacity ) ; NativeLong EdsGetVolumeInfo ( EdSdkLibrary . __EdsObject inVolumeRef , EdsVolumeInfo outVolumeInfo ) ; NativeLong EdsFormatVolume ( EdSdkLibrary . __EdsObject inVolumeRef ) ; NativeLong EdsGetDirectoryItemInfo ( EdSdkLibrary . __EdsObject inDirItemRef , EdsDirectoryItemInfo outDirItemInfo ) ; NativeLong EdsDeleteDirectoryItem ( EdSdkLibrary . __EdsObject inDirItemRef ) ; NativeLong EdsDownload ( EdSdkLibrary . __EdsObject inDirItemRef , NativeLong inReadSize , EdSdkLibrary . __EdsObject outStream ) ; NativeLong EdsDownloadCancel ( EdSdkLibrary . __EdsObject inDirItemRef ) ; NativeLong EdsDownloadComplete ( EdSdkLibrary . __EdsObject inDirItemRef ) ; NativeLong EdsDownloadThumbnail ( EdSdkLibrary . __EdsObject inDirItemRef , EdSdkLibrary . __EdsObject outStream ) ; @ Deprecated NativeLong EdsGetAttribute ( EdSdkLibrary . __EdsObject inDirItemRef , IntByReference outFileAttribute ) ; NativeLong EdsGetAttribute ( EdSdkLibrary . __EdsObject inDirItemRef , IntBuffer outFileAttribute ) ; NativeLong EdsSetAttribute ( EdSdkLibrary . __EdsObject inDirItemRef , int inFileAttribute ) ; @ Deprecated NativeLong EdsCreateFileStream ( Pointer inFileName , int inCreateDisposition , int inDesiredAccess , PointerByReference outStream ) ; NativeLong EdsCreateFileStream ( ByteBuffer inFileName , int inCreateDisposition , int inDesiredAccess , EdSdkLibrary . __EdsObject outStream [ ] ) ; NativeLong EdsCreateFileStream ( Pointer inFileName , int inCreateDisposition , int inDesiredAccess , EdSdkLibrary . __EdsObject outStream [ ] ) ; @ Deprecated NativeLong EdsCreateMemoryStream ( NativeLong inBufferSize , PointerByReference outStream ) ; NativeLong EdsCreateMemoryStream ( NativeLong inBufferSize , EdSdkLibrary . __EdsObject outStream [ ] ) ; @ Deprecated NativeLong EdsCreateFileStreamEx ( ShortByReference inFileName , int inCreateDisposition , int inDesiredAccess , PointerByReference outStream ) ; NativeLong EdsCreateFileStreamEx ( short inFileName [ ] , int inCreateDisposition , int inDesiredAccess , EdSdkLibrary . __EdsObject outStream [ ] ) ; NativeLong EdsCreateFileStreamEx ( ShortByReference inFileName , int inCreateDisposition , int inDesiredAccess , EdSdkLibrary . __EdsObject outStream [ ] ) ; @ Deprecated NativeLong EdsCreateMemoryStreamFromPointer ( EdSdkLibrary . EdsVoid inUserBuffer , NativeLong inBufferSize , PointerByReference outStream ) ; NativeLong EdsCreateMemoryStreamFromPointer ( EdSdkLibrary . EdsVoid inUserBuffer , NativeLong inBufferSize , EdSdkLibrary . __EdsObject outStream [ ] ) ; NativeLong EdsGetPointer ( EdSdkLibrary . __EdsObject inStream , PointerByReference outPointer ) ; NativeLong EdsRead ( EdSdkLibrary . __EdsObject inStreamRef , NativeLong inReadSize , EdSdkLibrary . EdsVoid outBuffer , NativeLongByReference outReadSize ) ; NativeLong EdsWrite ( EdSdkLibrary . __EdsObject inStreamRef , NativeLong inWriteSize , EdSdkLibrary . EdsVoid inBuffer , NativeLongByReference outWrittenSize ) ; NativeLong EdsSeek ( EdSdkLibrary . __EdsObject inStreamRef , NativeLong inSeekOffset , int inSeekOrigin ) ; NativeLong EdsGetPosition ( EdSdkLibrary . __EdsObject inStreamRef , NativeLongByReference outPosition ) ; NativeLong EdsGetLength ( EdSdkLibrary . __EdsObject inStreamRef , NativeLongByReference outLength ) ; NativeLong EdsCopyData ( EdSdkLibrary . __EdsObject inStreamRef , NativeLong inWriteSize , EdSdkLibrary . __EdsObject outStreamRef ) ; NativeLong EdsSetProgressCallback ( EdSdkLibrary . __EdsObject inRef , EdSdkLibrary . EdsProgressCallback inProgressCallback , int inProgressOption , EdSdkLibrary . EdsVoid inContext ) ; @ Deprecated NativeLong EdsCreateImageRef ( EdSdkLibrary . __EdsObject inStreamRef , PointerByReference outImageRef ) ; NativeLong EdsCreateImageRef ( EdSdkLibrary . __EdsObject inStreamRef , EdSdkLibrary . __EdsObject outImageRef [ ] ) ; NativeLong EdsGetImageInfo ( EdSdkLibrary . __EdsObject inImageRef , int inImageSource , EdsImageInfo outImageInfo ) ; NativeLong EdsGetImage ( EdSdkLibrary . __EdsObject inImageRef , int inImageSource , int inImageType , edsdk . EdsRect . ByValue inSrcRect , edsdk . EdsSize . ByValue inDstSize , EdSdkLibrary . __EdsObject outStreamRef ) ; NativeLong EdsSaveImage ( EdSdkLibrary . __EdsObject inImageRef , int inImageType , edsdk . EdsSaveImageSetting . ByValue inSaveSetting , EdSdkLibrary . __EdsObject outStreamRef ) ; NativeLong EdsCacheImage ( EdSdkLibrary . __EdsObject inImageRef , int inUseCache ) ; NativeLong EdsReflectImageProperty ( EdSdkLibrary . __EdsObject inImageRef ) ; @ Deprecated NativeLong EdsCreateEvfImageRef ( EdSdkLibrary . __EdsObject inStreamRef , PointerByReference outEvfImageRef ) ; NativeLong EdsCreateEvfImageRef ( EdSdkLibrary . __EdsObject inStreamRef , EdSdkLibrary . __EdsObject outEvfImageRef [ ] ) ; NativeLong EdsDownloadEvfImage ( EdSdkLibrary . __EdsObject inCameraRef , EdSdkLibrary . __EdsObject inEvfImageRef ) ; NativeLong EdsSetCameraAddedHandler ( EdSdkLibrary . EdsCameraAddedHandler inCameraAddedHandler , EdSdkLibrary . EdsVoid inContext ) ; NativeLong EdsSetPropertyEventHandler ( EdSdkLibrary . __EdsObject inCameraRef , NativeLong inEvnet , EdSdkLibrary . EdsPropertyEventHandler inPropertyEventHandler , EdSdkLibrary . EdsVoid inContext ) ; NativeLong EdsSetObjectEventHandler ( EdSdkLibrary . __EdsObject inCameraRef , NativeLong inEvnet , EdSdkLibrary . EdsObjectEventHandler inObjectEventHandler , EdSdkLibrary . EdsVoid inContext ) ; NativeLong EdsSetCameraStateEventHandler ( EdSdkLibrary . __EdsObject inCameraRef , NativeLong inEvnet , EdSdkLibrary . EdsStateEventHandler inStateEventHandler , EdSdkLibrary . EdsVoid inContext ) ; @ Deprecated NativeLong EdsCreateStream ( EdsIStream inStream , PointerByReference outStreamRef ) ; NativeLong EdsCreateStream ( EdsIStream inStream , EdSdkLibrary . __EdsObject outStreamRef [ ] ) ; NativeLong EdsGetEvent ( ) ; public static class EdsVoid extends PointerType { public EdsVoid ( Pointer address ) { super ( address ) ; } public EdsVoid ( ) { super ( ) ; } } ; public static class __EdsObject extends PointerType { public __EdsObject ( Pointer address ) { super ( address ) ; } public __EdsObject ( ) { super ( ) ; } } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsUsersetData extends Structure { public NativeLong valid ; public NativeLong dataSize ; public byte [ ] szCaption = new byte [ ( ) ] ; public byte [ ] data = new byte [ ( ) ] ; public EdsUsersetData ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" } ) ; } public EdsUsersetData ( NativeLong valid , NativeLong dataSize , byte szCaption [ ] , byte data [ ] ) { super ( ) ; this . valid = valid ; this . dataSize = dataSize ; if ( szCaption . length != this . szCaption . length ) throw new IllegalArgumentException ( "" ) ; this . szCaption = szCaption ; if ( data . length != this . data . length ) throw new IllegalArgumentException ( "" ) ; this . data = data ; initFieldOrder ( ) ; } public static class ByReference extends EdsUsersetData implements Structure . ByReference { } ; public static class ByValue extends EdsUsersetData implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsTime extends Structure { public NativeLong year ; public NativeLong month ; public NativeLong day ; public NativeLong hour ; public NativeLong minute ; public NativeLong second ; public NativeLong milliseconds ; public EdsTime ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" , "" , "" , "" } ) ; } public EdsTime ( NativeLong year , NativeLong month , NativeLong day , NativeLong hour , NativeLong minute , NativeLong second , NativeLong milliseconds ) { super ( ) ; this . year = year ; this . month = month ; this . day = day ; this . hour = hour ; this . minute = minute ; this . second = second ; this . milliseconds = milliseconds ; initFieldOrder ( ) ; } public static class ByReference extends EdsTime implements Structure . ByReference { } ; public static class ByValue extends EdsTime implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsPoint extends Structure { public NativeLong x ; public NativeLong y ; public EdsPoint ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" } ) ; } public EdsPoint ( NativeLong x , NativeLong y ) { super ( ) ; this . x = x ; this . y = y ; initFieldOrder ( ) ; } public static class ByReference extends EdsPoint implements Structure . ByReference { } ; public static class ByValue extends EdsPoint implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . Pointer ; import com . sun . jna . Structure ; import com . sun . jna . ptr . NativeLongByReference ; public class EdsIStream extends Structure { public Pointer context ; public NativeLongByReference read ; public NativeLongByReference write ; public NativeLongByReference seek ; public NativeLongByReference tell ; public NativeLongByReference getLength ; public EdsIStream ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" , "" , "" } ) ; } public EdsIStream ( Pointer context , NativeLongByReference read , NativeLongByReference write , NativeLongByReference seek , NativeLongByReference tell , NativeLongByReference getLength ) { super ( ) ; this . context = context ; this . read = read ; this . write = write ; this . seek = seek ; this . tell = tell ; this . getLength = getLength ; initFieldOrder ( ) ; } public static class ByReference extends EdsIStream implements Structure . ByReference { } ; public static class ByValue extends EdsIStream implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsVolumeInfo extends Structure { public NativeLong storageType ; public int access ; public long maxCapacity ; public long freeSpaceInBytes ; public byte [ ] szVolumeLabel = new byte [ ( ) ] ; public EdsVolumeInfo ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" , "" } ) ; } public EdsVolumeInfo ( NativeLong storageType , int access , long maxCapacity , long freeSpaceInBytes , byte szVolumeLabel [ ] ) { super ( ) ; this . storageType = storageType ; this . access = access ; this . maxCapacity = maxCapacity ; this . freeSpaceInBytes = freeSpaceInBytes ; if ( szVolumeLabel . length != this . szVolumeLabel . length ) throw new IllegalArgumentException ( "" ) ; this . szVolumeLabel = szVolumeLabel ; initFieldOrder ( ) ; } public static class ByReference extends EdsVolumeInfo implements Structure . ByReference { } ; public static class ByValue extends EdsVolumeInfo implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsPictureStyleDesc extends Structure { public NativeLong contrast ; public NativeLong sharpness ; public NativeLong saturation ; public NativeLong colorTone ; public NativeLong filterEffect ; public NativeLong toningEffect ; public EdsPictureStyleDesc ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" , "" , "" } ) ; } public EdsPictureStyleDesc ( NativeLong contrast , NativeLong sharpness , NativeLong saturation , NativeLong colorTone , NativeLong filterEffect , NativeLong toningEffect ) { super ( ) ; this . contrast = contrast ; this . sharpness = sharpness ; this . saturation = saturation ; this . colorTone = colorTone ; this . filterEffect = filterEffect ; this . toningEffect = toningEffect ; initFieldOrder ( ) ; } public static class ByReference extends EdsPictureStyleDesc implements Structure . ByReference { } ; public static class ByValue extends EdsPictureStyleDesc implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsDeviceInfo extends Structure { public byte [ ] szPortName = new byte [ ( ) ] ; public byte [ ] szDeviceDescription = new byte [ ( ) ] ; public NativeLong deviceSubType ; public NativeLong reserved ; public EdsDeviceInfo ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" } ) ; } public EdsDeviceInfo ( byte szPortName [ ] , byte szDeviceDescription [ ] , NativeLong deviceSubType , NativeLong reserved ) { super ( ) ; if ( szPortName . length != this . szPortName . length ) throw new IllegalArgumentException ( "" ) ; this . szPortName = szPortName ; if ( szDeviceDescription . length != this . szDeviceDescription . length ) throw new IllegalArgumentException ( "" ) ; this . szDeviceDescription = szDeviceDescription ; this . deviceSubType = deviceSubType ; this . reserved = reserved ; initFieldOrder ( ) ; } public static class ByReference extends EdsDeviceInfo implements Structure . ByReference { } ; public static class ByValue extends EdsDeviceInfo implements Structure . ByValue { } ; } package edsdk . utils ; import java . awt . image . BufferedImage ; import java . io . ByteArrayInputStream ; import java . io . File ; import java . io . IOException ; import java . lang . reflect . Field ; import java . nio . ByteBuffer ; import javax . imageio . ImageIO ; import com . sun . jna . Native ; import com . sun . jna . NativeLong ; import com . sun . jna . Pointer ; import com . sun . jna . ptr . NativeLongByReference ; import com . sun . jna . ptr . PointerByReference ; import edsdk . EdSdkLibrary ; import edsdk . EdSdkLibrary . EdsVoid ; import edsdk . EdSdkLibrary . __EdsObject ; import edsdk . EdsDirectoryItemInfo ; public class CanonUtils { public static String toString ( byte bytes [ ] ) { for ( int i = ; i < bytes . length ; i ++ ) { if ( bytes [ i ] == ) { return new String ( bytes , , i ) ; } } return new String ( bytes ) ; } public static String toString ( int errorCode ) { Field [ ] fields = EdSdkLibrary . class . getFields ( ) ; for ( Field field : fields ) { try { if ( field . getType ( ) . toString ( ) . equals ( "" ) && field . getInt ( EdSdkLibrary . class ) == errorCode ) { if ( field . getName ( ) . startsWith ( "" ) ) { return field . getName ( ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } } return "" ; } public static String propertyIdToString ( long property ) { Field [ ] fields = EdSdkLibrary . class . getFields ( ) ; for ( Field field : fields ) { try { if ( field . getType ( ) . toString ( ) . equals ( "" ) && field . getInt ( EdSdkLibrary . class ) == property ) { if ( field . getName ( ) . startsWith ( "" ) ) { return field . getName ( ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } } return "" ; } public static int sizeof ( Object o ) { int size = ; for ( Field field : o . getClass ( ) . getDeclaredFields ( ) ) { Class < ? > fieldtype = field . getType ( ) ; if ( fieldtype . equals ( NativeLong . class ) ) { size += NativeLong . SIZE ; } else { System . out . println ( "" + field ) ; } } return size ; } public static File download ( __EdsObject directoryItem , File destination , boolean deleteAfterDownload ) { int err = EdSdkLibrary . EDS_ERR_OK ; __EdsObject [ ] stream = new __EdsObject [ ] ; EdsDirectoryItemInfo dirItemInfo = new EdsDirectoryItemInfo ( ) ; boolean success = false ; long timeStart = System . currentTimeMillis ( ) ; err = CanonCamera . EDSDK . EdsGetDirectoryItemInfo ( directoryItem , dirItemInfo ) . intValue ( ) ; if ( err == EdSdkLibrary . EDS_ERR_OK ) { if ( destination == null ) { destination = new File ( System . getProperty ( "" ) ) ; } if ( destination . isDirectory ( ) ) { destination = new File ( destination , toString ( dirItemInfo . szFileName ) ) ; } destination . getParentFile ( ) . mkdirs ( ) ; System . out . println ( "" + toString ( dirItemInfo . szFileName ) + "" + destination . getAbsolutePath ( ) ) ; err = CanonCamera . EDSDK . EdsCreateFileStream ( ByteBuffer . wrap ( Native . toByteArray ( destination . getAbsolutePath ( ) ) ) , EdSdkLibrary . EdsFileCreateDisposition . kEdsFileCreateDisposition_CreateAlways , EdSdkLibrary . EdsAccess . kEdsAccess_ReadWrite , stream ) . intValue ( ) ; } if ( err == EdSdkLibrary . EDS_ERR_OK ) { err = CanonCamera . EDSDK . EdsDownload ( directoryItem , dirItemInfo . size , stream [ ] ) . intValue ( ) ; } if ( err == EdSdkLibrary . EDS_ERR_OK ) { System . out . println ( "" + ( System . currentTimeMillis ( ) - timeStart ) ) ; err = CanonCamera . EDSDK . EdsDownloadComplete ( directoryItem ) . intValue ( ) ; if ( deleteAfterDownload ) { System . out . println ( "" ) ; CanonCamera . EDSDK . EdsDeleteDirectoryItem ( directoryItem ) ; } success = true ; } if ( stream [ ] != null ) { CanonCamera . EDSDK . EdsRelease ( stream [ ] ) ; } return success ? destination : null ; } public static int setPropertyData ( __EdsObject ref , long property , long param , int size , EdsVoid data ) { return CanonCamera . EDSDK . EdsSetPropertyData ( ref , new NativeLong ( property ) , new NativeLong ( param ) , new NativeLong ( size ) , data ) . intValue ( ) ; } public static int setPropertyData ( __EdsObject ref , long property , long value ) { NativeLongByReference number = new NativeLongByReference ( new NativeLong ( value ) ) ; EdsVoid data = new EdsVoid ( number . getPointer ( ) ) ; return setPropertyData ( ref , property , , NativeLong . SIZE , data ) ; } public static int getPropertyData ( __EdsObject ref , long property , long param , int size , EdsVoid data ) { return CanonCamera . EDSDK . EdsGetPropertyData ( ref , new NativeLong ( property ) , new NativeLong ( param ) , new NativeLong ( size ) , data ) . intValue ( ) ; } public static int getPropertyData ( __EdsObject ref , long property ) { NativeLongByReference number = new NativeLongByReference ( new NativeLong ( ) ) ; EdsVoid data = new EdsVoid ( number . getPointer ( ) ) ; int res = getPropertyData ( ref , property , , NativeLong . SIZE , data ) ; System . out . println ( "" + res ) ; return number . getValue ( ) . intValue ( ) ; } public static boolean beginLiveView ( __EdsObject camera ) { int err = EdSdkLibrary . EDS_ERR_OK ; NativeLongByReference number = new NativeLongByReference ( new NativeLong ( ) ) ; EdsVoid data = new EdsVoid ( number . getPointer ( ) ) ; err = setPropertyData ( camera , EdSdkLibrary . kEdsPropID_Evf_Mode , , NativeLong . SIZE , data ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" + err + "" + toString ( err ) ) ; return false ; } getPropertyData ( camera , EdSdkLibrary . kEdsPropID_Evf_Mode , , NativeLong . SIZE , data ) ; System . out . println ( "" + number . getValue ( ) ) ; number = new NativeLongByReference ( new NativeLong ( EdSdkLibrary . EdsEvfOutputDevice . kEdsEvfOutputDevice_PC ) ) ; data = new EdsVoid ( number . getPointer ( ) ) ; err = setPropertyData ( camera , EdSdkLibrary . kEdsPropID_Evf_OutputDevice , , NativeLong . SIZE , data ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" + err + "" + toString ( err ) ) ; return false ; } return true ; } public static boolean endLiveView ( __EdsObject camera ) { int err = EdSdkLibrary . EDS_ERR_OK ; NativeLongByReference number = new NativeLongByReference ( new NativeLong ( ) ) ; EdsVoid data = new EdsVoid ( number . getPointer ( ) ) ; err = setPropertyData ( camera , EdSdkLibrary . kEdsPropID_Evf_Mode , , NativeLong . SIZE , data ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" + err + "" + toString ( err ) ) ; return false ; } number = new NativeLongByReference ( new NativeLong ( EdSdkLibrary . EdsEvfOutputDevice . kEdsEvfOutputDevice_TFT ) ) ; data = new EdsVoid ( number . getPointer ( ) ) ; err = setPropertyData ( camera , EdSdkLibrary . kEdsPropID_Evf_OutputDevice , , NativeLong . SIZE , data ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" + err + "" + toString ( err ) ) ; return false ; } return true ; } public static BufferedImage downloadLiveViewImage ( __EdsObject camera ) { int err = EdSdkLibrary . EDS_ERR_OK ; __EdsObject stream [ ] = new __EdsObject [ ] ; __EdsObject image [ ] = new __EdsObject [ ] ; err = CanonCamera . EDSDK . EdsCreateMemoryStream ( new NativeLong ( ) , stream ) . intValue ( ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" + err + "" + toString ( err ) ) ; release ( image [ ] , stream [ ] ) ; return null ; } err = CanonCamera . EDSDK . EdsCreateEvfImageRef ( stream [ ] , image ) . intValue ( ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" + err + "" + toString ( err ) ) ; release ( image [ ] , stream [ ] ) ; return null ; } err = CanonCamera . EDSDK . EdsDownloadEvfImage ( camera , image [ ] ) . intValue ( ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" + err + "" + toString ( err ) ) ; release ( image [ ] , stream [ ] ) ; return null ; } NativeLongByReference length = new NativeLongByReference ( ) ; err = CanonCamera . EDSDK . EdsGetLength ( stream [ ] , length ) . intValue ( ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" + err + "" + toString ( err ) ) ; release ( image [ ] , stream [ ] ) ; return null ; } PointerByReference ref = new PointerByReference ( ) ; err = CanonCamera . EDSDK . EdsGetPointer ( stream [ ] , ref ) . intValue ( ) ; long address = ref . getPointer ( ) . getNativeLong ( ) . longValue ( ) ; Pointer pp = new Pointer ( address ) ; byte data [ ] = pp . getByteArray ( , length . getValue ( ) . intValue ( ) ) ; try { BufferedImage img = ImageIO . read ( new ByteArrayInputStream ( data ) ) ; System . out . println ( img . getWidth ( ) + "" + img . getHeight ( ) ) ; return img ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { release ( image [ ] , stream [ ] ) ; } return null ; } public static void release ( __EdsObject ... objects ) { for ( __EdsObject obj : objects ) { if ( obj != null ) { CanonCamera . EDSDK . EdsRelease ( obj ) ; } } } } package edsdk . utils ; public interface CanonConstants { public final static int Av_1 = ; public final static int Av_1_1 = ; public final static int Av_1_2 = ; public final static int Av_1_2b = ; public final static int Av_1_4 = ; public final static int Av_1_6 = ; public final static int Av_1_8 = ; public final static int Av_1_8b = ; public final static int Av_2 = ; public final static int Av_2_2 = ; public final static int Av_2_5 = ; public final static int Av_2_5b = ; public final static int Av_2_8 = ; public final static int Av_3_2 = ; public final static int Av_3_5 = ; public final static int Av_3_5b = ; public final static int Av_4 = ; public final static int Av_4_5 = ; public final static int Av_4_5b = ; public final static int Av_5_0 = ; public final static int Av_5_6 = ; public final static int Av_6_3 = ; public final static int Av_6_7 = ; public final static int Av_7_1 = ; public final static int Av_8 = ; public final static int Av_9 = ; public final static int Av_9_5 = ; public final static int Av_10 = ; public final static int Av_11 = ; public final static int Av_13 = ; public final static int Av_13_b = ; public final static int Av_14 = ; public final static int Av_16 = ; public final static int Av_18 = ; public final static int Av_19 = ; public final static int Av_20 = ; public final static int Av_22 = ; public final static int Av_25 = ; public final static int Av_27 = ; public final static int Av_29 = ; public final static int Av_32 = ; public final static int Av_36 = ; public final static int Av_38 = ; public final static int Av_40 = ; public final static int Av_45 = ; public final static int Av_51 = ; public final static int Av_54 = ; public final static int Av_57 = ; public final static int Av_64 = ; public final static int Av_72 = ; public final static int Av_76 = ; public final static int Av_80 = ; public final static int Av_91 = ; public final static int Av_invalid = ; public final static int Tv_BULB = ; public final static int Tv_30 = ; public final static int Tv_25 = ; public final static int Tv_20 = ; public final static int Tv_20b = ; public final static int Tv_15 = ; public final static int Tv_13 = ; public final static int Tv_10 = ; public final static int Tv_10b = ; public final static int Tv_8 = ; public final static int Tv_6 = ; public final static int Tv_6b = ; public final static int Tv_5 = ; public final static int Tv_4 = ; public final static int Tv_3_2 = ; public final static int Tv_3 = ; public final static int Tv_2_5 = ; public final static int Tv_2 = ; public final static int Tv_1_6 = ; public final static int Tv_1_5 = ; public final static int Tv_1_3 = ; public final static int Tv_1 = ; public final static int Tv_0_8 = ; public final static int Tv_0_7 = ; public final static int Tv_0_6 = ; public final static int Tv_0_5 = ; public final static int Tv_0_4 = ; public final static int Tv_0_3 = ; public final static int Tv_0_3b = ; public final static int Tv_1by4 = ; public final static int Tv_1by5 = ; public final static int Tv_1by6 = ; public final static int Tv_1by6b = ; public final static int Tv_1by8 = ; public final static int Tv_1by10 = ; public final static int Tv_1by10b = ; public final static int Tv_1by25 = ; public final static int Tv_1by30 = ; public final static int Tv_1by40 = ; public final static int Tv_1by45 = ; public final static int Tv_1by50 = ; public final static int Tv_1by60 = ; public final static int Tv_1by80 = ; public final static int Tv_1by90 = ; public final static int Tv_1by100 = ; public final static int Tv_1by125 = ; public final static int Tv_1by160 = ; public final static int Tv_1by180 = ; public final static int Tv_1by200 = ; public final static int Tv_1by250 = ; public final static int Tv_1by320 = ; public final static int Tv_1by350 = ; public final static int Tv_1by400 = ; public final static int Tv_1by500 = ; public final static int Tv_1by640 = ; public final static int Tv_1by750 = ; public final static int Tv_1by800 = ; public final static int Tv_1by1000 = ; public final static int Tv_1by1250 = ; public final static int Tv_1by1500 = ; public final static int Tv_1by1600 = ; public final static int Tv_1by2000 = ; public final static int Tv_1by2500 = ; public final static int Tv_1by3000 = ; public final static int Tv_1by3200 = ; public final static int Tv_1by4000 = ; public final static int Tv_1by5000 = ; public final static int Tv_1by6000 = ; public final static int Tv_1by6400 = ; public final static int Tv_1by8000 = ; public final static int Tv_1by8000_invalid = ; public final static int ISO_6 = ; public final static int ISO_12 = ; public final static int ISO_25 = ; public final static int ISO_50 = ; public final static int ISO_100 = ; public final static int ISO_125 = ; public final static int ISO_160 = ; public final static int ISO_200 = ; public final static int ISO_250 = ; public final static int ISO_320 = ; public final static int ISO_400 = ; public final static int ISO_500 = ; public final static int ISO_640 = ; public final static int ISO_800 = ; public final static int ISO_1000 = ; public final static int ISO_1250 = ; public final static int ISO_1600 = ; public final static int ISO_3200 = ; public final static int ISO_6400 = ; public final static int ISO_12800 = ; public final static int ISO_25600 = ; public final static int ISO_51200 = ; public final static int ISO_102400 = ; public final static int ISO_invalid = ; public final static int kEdsSaveTo_Camera = ; public final static int kEdsSaveTo_Host = ; public final static int kEdsSaveTo_Both = ; } package edsdk . utils . commands ; import edsdk . utils . CanonTask ; import edsdk . utils . CanonUtils ; public class GetPropertyTask extends CanonTask < Long > { private long property ; public GetPropertyTask ( long property ) { this . property = property ; } @ Override public void run ( ) { long result = CanonUtils . getPropertyData ( camera . getEdsCamera ( ) , property ) ; setResult ( result ) ; } } package edsdk . utils . commands ; import java . io . File ; import com . sun . jna . NativeLong ; import edsdk . EdSdkLibrary ; import edsdk . EdSdkLibrary . EdsVoid ; import edsdk . EdSdkLibrary . __EdsObject ; import edsdk . utils . CanonTask ; import edsdk . utils . CanonUtils ; public class ShootTask extends CanonTask < File > { private File dest = null ; public ShootTask ( ) { } public ShootTask ( File dest ) { this . dest = dest ; } @ Override public void run ( ) { int result = - ; while ( result != EdSdkLibrary . EDS_ERR_OK ) { System . out . println ( "" ) ; result = sendCommand ( EdSdkLibrary . kEdsCameraCommand_TakePicture , ) ; System . out . println ( "" + result + "" + CanonUtils . toString ( result ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } System . out . println ( "" ) ; notYetFinished ( ) ; } @ Override public NativeLong apply ( NativeLong inEvent , __EdsObject inRef , EdsVoid inContext ) { if ( inEvent . intValue ( ) == EdSdkLibrary . kEdsObjectEvent_DirItemCreated ) { System . out . println ( "" ) ; setResult ( CanonUtils . download ( inRef , dest , false ) ) ; finish ( ) ; } return null ; } } package edsdk . utils . commands ; import edsdk . EdSdkLibrary ; import edsdk . utils . CanonTask ; import edsdk . utils . CanonUtils ; public class SetPropertyTask extends CanonTask < Boolean > { private long property ; private long value ; public SetPropertyTask ( long property , long value ) { this . property = property ; this . value = value ; } @ Override public void run ( ) { int result = CanonUtils . setPropertyData ( camera . getEdsCamera ( ) , property , value ) ; System . out . println ( "" + CanonUtils . propertyIdToString ( property ) + "" + value + "" + CanonUtils . toString ( result ) ) ; setResult ( result == EdSdkLibrary . EDS_ERR_OK ) ; } } package edsdk . utils . commands ; import java . awt . image . BufferedImage ; import edsdk . utils . CanonTask ; import edsdk . utils . CanonUtils ; public class LiveViewTask { public static class Begin extends CanonTask < Boolean > { @ Override public void run ( ) { setResult ( CanonUtils . beginLiveView ( camera . getEdsCamera ( ) ) ) ; } } public static class End extends CanonTask < Boolean > { @ Override public void run ( ) { setResult ( CanonUtils . endLiveView ( camera . getEdsCamera ( ) ) ) ; } } public static class Download extends CanonTask < BufferedImage > { @ Override public void run ( ) { setResult ( CanonUtils . downloadLiveViewImage ( camera . getEdsCamera ( ) ) ) ; } } } package edsdk . utils ; import java . awt . image . BufferedImage ; import java . io . File ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Map ; import java . util . concurrent . ConcurrentLinkedQueue ; import com . sun . jna . Library ; import com . sun . jna . Native ; import com . sun . jna . NativeLong ; import com . sun . jna . Pointer ; import com . sun . jna . platform . win32 . User32 ; import com . sun . jna . platform . win32 . User32 . MSG ; import com . sun . jna . ptr . NativeLongByReference ; import com . sun . jna . win32 . StdCallLibrary ; import edsdk . EdSdkLibrary ; import edsdk . EdSdkLibrary . EdsObjectEventHandler ; import edsdk . EdSdkLibrary . EdsVoid ; import edsdk . EdSdkLibrary . __EdsObject ; import edsdk . utils . commands . GetPropertyTask ; import edsdk . utils . commands . LiveViewTask ; import edsdk . utils . commands . SetPropertyTask ; import edsdk . utils . commands . ShootTask ; public class CanonCamera implements EdsObjectEventHandler { private static final Map < String , Integer > options = new HashMap < String , Integer > ( ) ; static { options . put ( Library . OPTION_CALLING_CONVENTION , StdCallLibrary . STDCALL_CONVENTION ) ; } public static EdSdkLibrary EDSDK = ( EdSdkLibrary ) Native . loadLibrary ( "" , EdSdkLibrary . class , options ) ; private static final User32 lib = User32 . INSTANCE ; private static ConcurrentLinkedQueue < CanonTask < ? > > queue = new ConcurrentLinkedQueue < CanonTask < ? > > ( ) ; private static ArrayList < EdsObjectEventHandler > objectEventHandlers = new ArrayList < EdsObjectEventHandler > ( ) ; private static Thread dispatcherThread ; static { dispatcherThread = new Thread ( ) { public void run ( ) { dispatchMessages ( ) ; } } ; dispatcherThread . start ( ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { CanonCamera . close ( ) ; } } ) ; } private __EdsObject edsCamera ; private String errorMessage ; private int errorCode ; public CanonCamera ( ) { } public boolean openSession ( ) { return executeNow ( new OpenSessionCommand ( ) ) ; } public boolean closeSession ( ) { return executeNow ( new CloseSessionCommand ( ) ) ; } public __EdsObject getEdsCamera ( ) { return edsCamera ; } public File shoot ( ) { return executeNow ( new ShootTask ( ) ) ; } public Boolean setProperty ( long property , long value ) { return executeNow ( new SetPropertyTask ( property , value ) ) ; } public Long getProperty ( long property ) { return executeNow ( new GetPropertyTask ( property ) ) ; } public void execute ( CanonTask < ? > cmd ) { cmd . setSLR ( this ) ; queue . add ( cmd ) ; } public < T > T executeNow ( CanonTask < T > cmd ) { execute ( cmd ) ; return cmd . result ( ) ; } public boolean setError ( int result , String message ) { errorMessage = message + "" + result + "" + CanonUtils . toString ( result ) + "" ; errorCode = result ; System . err . println ( errorMessage ) ; return false ; } public void addObjectEventHandler ( EdsObjectEventHandler handler ) { objectEventHandlers . add ( handler ) ; } public void removeObjectEventHandler ( EdsObjectEventHandler handler ) { objectEventHandlers . remove ( handler ) ; } @ Override public NativeLong apply ( NativeLong inEvent , __EdsObject inRef , EdsVoid inContext ) { System . out . println ( "" + inEvent . doubleValue ( ) + "" + inContext ) ; for ( EdsObjectEventHandler handler : objectEventHandlers ) { handler . apply ( inEvent , inRef , inContext ) ; } return new NativeLong ( ) ; } private static void dispatchMessages ( ) { int err = EDSDK . EdsInitializeSDK ( ) . intValue ( ) ; if ( err != EdSdkLibrary . EDS_ERR_OK ) { System . err . println ( "" ) ; } MSG msg = new MSG ( ) ; CanonTask < ? > task = null ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { boolean hasMessage = lib . PeekMessage ( msg , null , , , ) ; if ( hasMessage ) { lib . TranslateMessage ( msg ) ; lib . DispatchMessage ( msg ) ; } if ( task != null ) { if ( task . finished ( ) ) { System . out . println ( "" ) ; task . camera . removeObjectEventHandler ( task ) ; task = null ; } } if ( ! queue . isEmpty ( ) && task == null ) { System . out . println ( "" + queue . peek ( ) . getClass ( ) . toString ( ) ) ; task = queue . poll ( ) ; if ( ! ( task instanceof OpenSessionCommand ) ) task . camera . addObjectEventHandler ( task ) ; task . run ( ) ; task . ran ( ) ; } try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { break ; } } EDSDK . EdsTerminateSDK ( ) ; System . out . println ( "" ) ; } public static void close ( ) { if ( dispatcherThread != null && dispatcherThread . isAlive ( ) ) { dispatcherThread . interrupt ( ) ; try { dispatcherThread . join ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } private class OpenSessionCommand extends CanonTask < Boolean > { public void run ( ) { setResult ( connect ( ) ) ; } private boolean connect ( ) { int result ; __EdsObject list [ ] = new __EdsObject [ ] ; result = EDSDK . EdsGetCameraList ( list ) . intValue ( ) ; if ( result != EdSdkLibrary . EDS_ERR_OK ) { return setError ( result , "" ) ; } NativeLongByReference outRef = new NativeLongByReference ( ) ; result = EDSDK . EdsGetChildCount ( list [ ] , outRef ) . intValue ( ) ; if ( result != EdSdkLibrary . EDS_ERR_OK ) { return setError ( result , "" ) ; } long numCams = outRef . getValue ( ) . longValue ( ) ; if ( numCams <= ) { return setError ( , "" ) ; } __EdsObject cameras [ ] = new __EdsObject [ ] ; result = EDSDK . EdsGetChildAtIndex ( list [ ] , new NativeLong ( ) , cameras ) . intValue ( ) ; if ( result != EdSdkLibrary . EDS_ERR_OK ) { return setError ( result , "" ) ; } EdsVoid context = new EdsVoid ( new Pointer ( ) ) ; edsCamera = cameras [ ] ; result = EDSDK . EdsSetObjectEventHandler ( edsCamera , new NativeLong ( EdSdkLibrary . kEdsObjectEvent_All ) , CanonCamera . this , context ) . intValue ( ) ; if ( result != EdSdkLibrary . EDS_ERR_OK ) { return setError ( result , "" ) ; } result = EDSDK . EdsOpenSession ( edsCamera ) . intValue ( ) ; if ( result != EdSdkLibrary . EDS_ERR_OK ) { return setError ( result , "" ) ; } return true ; } } private class CloseSessionCommand extends CanonTask < Boolean > { public void run ( ) { setResult ( close ( ) ) ; } private boolean close ( ) { System . out . println ( "" ) ; int result = EDSDK . EdsCloseSession ( edsCamera ) . intValue ( ) ; if ( result != EdSdkLibrary . EDS_ERR_OK ) { return setError ( result , "" ) ; } return true ; } } public boolean beginLiveView ( ) { return executeNow ( new LiveViewTask . Begin ( ) ) ; } public boolean endLiveView ( ) { return executeNow ( new LiveViewTask . End ( ) ) ; } public BufferedImage downloadLiveView ( ) { return executeNow ( new LiveViewTask . Download ( ) ) ; } } package edsdk . utils ; import com . sun . jna . NativeLong ; import edsdk . EdSdkLibrary ; import edsdk . EdSdkLibrary . EdsObjectEventHandler ; import edsdk . EdSdkLibrary . EdsVoid ; import edsdk . EdSdkLibrary . __EdsObject ; public abstract class CanonTask < T > implements EdsObjectEventHandler { public CanonCamera camera ; public static EdSdkLibrary EDSDK = CanonCamera . EDSDK ; private boolean finished = false ; private boolean waitForFinish = false ; private boolean ran = false ; private T result ; public CanonTask ( ) { } public void setSLR ( CanonCamera slr ) { this . camera = slr ; } public abstract void run ( ) ; public void setResult ( T result ) { this . result = result ; } public void notYetFinished ( ) { waitForFinish = true ; } public void finish ( ) { finished = true ; } protected void ran ( ) { ran = true ; } protected boolean finished ( ) { return waitForFinish ? finished : ran ; } public int sendCommand ( long command , long params ) { return EDSDK . EdsSendCommand ( camera . getEdsCamera ( ) , new NativeLong ( command ) , new NativeLong ( params ) ) . intValue ( ) ; } @ Override public NativeLong apply ( NativeLong inEvent , __EdsObject inRef , EdsVoid inContext ) { return new NativeLong ( ) ; } public T result ( ) { while ( ! finished ( ) ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { return null ; } } return result ; } } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsCapacity extends Structure { public NativeLong numberOfFreeClusters ; public NativeLong bytesPerSector ; public int reset ; public EdsCapacity ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" } ) ; } public EdsCapacity ( NativeLong numberOfFreeClusters , NativeLong bytesPerSector , int reset ) { super ( ) ; this . numberOfFreeClusters = numberOfFreeClusters ; this . bytesPerSector = bytesPerSector ; this . reset = reset ; initFieldOrder ( ) ; } public static class ByReference extends EdsCapacity implements Structure . ByReference { } ; public static class ByValue extends EdsCapacity implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . Structure ; public class EdsRect extends Structure { public EdsPoint point ; public EdsSize size ; public EdsRect ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" } ) ; } public EdsRect ( EdsPoint point , EdsSize size ) { super ( ) ; this . point = point ; this . size = size ; initFieldOrder ( ) ; } public static class ByReference extends EdsRect implements Structure . ByReference { } ; public static class ByValue extends EdsRect implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsFocusInfo extends Structure { public EdsRect imageRect ; public NativeLong pointNumber ; public EdsFocusPoint [ ] focusPoint = new EdsFocusPoint [ ( ) ] ; public NativeLong executeMode ; public EdsFocusInfo ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" } ) ; } public EdsFocusInfo ( EdsRect imageRect , NativeLong pointNumber , EdsFocusPoint focusPoint [ ] , NativeLong executeMode ) { super ( ) ; this . imageRect = imageRect ; this . pointNumber = pointNumber ; if ( focusPoint . length != this . focusPoint . length ) throw new IllegalArgumentException ( "" ) ; this . focusPoint = focusPoint ; this . executeMode = executeMode ; initFieldOrder ( ) ; } public static class ByReference extends EdsFocusInfo implements Structure . ByReference { } ; public static class ByValue extends EdsFocusInfo implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; public class EdsImageInfo extends Structure { public NativeLong width ; public NativeLong height ; public NativeLong numOfComponents ; public NativeLong componentDepth ; public EdsRect effectiveRect ; public NativeLong reserved1 ; public NativeLong reserved2 ; public EdsImageInfo ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" , "" , "" , "" , "" } ) ; } public EdsImageInfo ( NativeLong width , NativeLong height , NativeLong numOfComponents , NativeLong componentDepth , EdsRect effectiveRect , NativeLong reserved1 , NativeLong reserved2 ) { super ( ) ; this . width = width ; this . height = height ; this . numOfComponents = numOfComponents ; this . componentDepth = componentDepth ; this . effectiveRect = effectiveRect ; this . reserved1 = reserved1 ; this . reserved2 = reserved2 ; initFieldOrder ( ) ; } public static class ByReference extends EdsImageInfo implements Structure . ByReference { } ; public static class ByValue extends EdsImageInfo implements Structure . ByValue { } ; } package edsdk ; import com . sun . jna . NativeLong ; import com . sun . jna . Structure ; import edsdk . EdSdkLibrary . __EdsObject ; public class EdsSaveImageSetting extends Structure { public NativeLong JPEGQuality ; public __EdsObject iccProfileStream ; public NativeLong reserved ; public EdsSaveImageSetting ( ) { super ( ) ; initFieldOrder ( ) ; } protected void initFieldOrder ( ) { setFieldOrder ( new java . lang . String [ ] { "" , "" , "" } ) ; } public EdsSaveImageSetting ( NativeLong JPEGQuality , __EdsObject iccProfileStream , NativeLong reserved ) { super ( ) ; this . JPEGQuality = JPEGQuality ; this . iccProfileStream = iccProfileStream ; this . reserved = reserved ; initFieldOrder ( ) ; } public static class ByReference extends EdsSaveImageSetting implements Structure . ByReference { } ; public static class ByValue extends EdsSaveImageSetting implements Structure . ByValue { } ; } package gettingstarted ; import com . sun . jna . NativeLong ; import com . sun . jna . Pointer ; import com . sun . jna . platform . win32 . Kernel32 ; import com . sun . jna . platform . win32 . User32 ; import com . sun . jna . platform . win32 . User32 . MSG ; import com . sun . jna . platform . win32 . W32API . HMODULE ; import com . sun . jna . ptr . NativeLongByReference ; import edsdk . EdSdkLibrary ; import edsdk . EdSdkLibrary . EdsObjectEventHandler ; import edsdk . EdSdkLibrary . EdsVoid ; import edsdk . EdSdkLibrary . __EdsObject ; import edsdk . utils . CanonCamera ; import edsdk . utils . CanonUtils ; public class E01_Simple { public static EdSdkLibrary EDSDK = CanonCamera . EDSDK ; static final User32 lib = User32 . INSTANCE ; static final HMODULE hMod = Kernel32 . INSTANCE . GetModuleHandle ( "" ) ; public static void main ( String [ ] args ) throws InterruptedException { int result = ; result = EDSDK . EdsInitializeSDK ( ) . intValue ( ) ; check ( result ) ; __EdsObject list [ ] = new __EdsObject [ ] ; debug ( list ) ; result = EDSDK . EdsGetCameraList ( list ) . intValue ( ) ; debug ( list ) ; check ( result ) ; NativeLongByReference outRef = new NativeLongByReference ( ) ; result = EDSDK . EdsGetChildCount ( list [ ] , outRef ) . intValue ( ) ; check ( result ) ; System . out . println ( "" + outRef . getValue ( ) . longValue ( ) ) ; long numCams = outRef . getValue ( ) . longValue ( ) ; if ( numCams == ) { System . out . println ( "" ) ; } __EdsObject camera [ ] = new __EdsObject [ ] ; debug ( camera ) ; result = EDSDK . EdsGetChildAtIndex ( list [ ] , new NativeLong ( ) , camera ) . intValue ( ) ; debug ( camera ) ; check ( result ) ; EdsVoid context = new EdsVoid ( new Pointer ( ) ) ; EdsObjectEventHandler handler = new EdsObjectEventHandler ( ) { @ Override public NativeLong apply ( NativeLong inEvent , __EdsObject inRef , EdsVoid inContext ) { System . out . println ( "" + inEvent . doubleValue ( ) + "" + inContext ) ; if ( inEvent . intValue ( ) == ) { CanonUtils . download ( inRef , null , true ) ; } return new NativeLong ( - ) ; } } ; EDSDK . EdsSetObjectEventHandler ( camera [ ] , new NativeLong ( EdSdkLibrary . kEdsObjectEvent_All ) , handler , context ) ; result = EDSDK . EdsOpenSession ( camera [ ] ) . intValue ( ) ; check ( result ) ; dispatchMessages ( ) ; } public static void check ( int result ) { if ( result != EdSdkLibrary . EDS_ERR_OK ) { System . out . println ( "" + CanonUtils . toString ( result ) ) ; } } public static void debug ( __EdsObject [ ] obj ) { System . out . println ( "" ) ; for ( __EdsObject o : obj ) { if ( o != null ) { System . out . println ( o + "" + o . getPointer ( ) . getLong ( ) ) ; ; } } } public static void dispatchMessages ( ) { int count = ; int result ; MSG msg = new MSG ( ) ; while ( ( result = lib . GetMessage ( msg , null , , ) ) != ) { if ( result == - ) { System . err . println ( "" ) ; break ; } else { count ++ ; lib . TranslateMessage ( msg ) ; try { lib . DispatchMessage ( msg ) ; } catch ( Error e ) { e . printStackTrace ( ) ; } } } } } package gettingstarted ; import edsdk . utils . CanonCamera ; public class E02_Simpler { public static void main ( String [ ] args ) throws InterruptedException { CanonCamera slr = new CanonCamera ( ) ; slr . openSession ( ) ; slr . shoot ( ) ; slr . closeSession ( ) ; CanonCamera . close ( ) ; } } package gettingstarted ; import java . awt . BorderLayout ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import java . awt . image . BufferedImage ; import javax . swing . ImageIcon ; import javax . swing . JFrame ; import javax . swing . JLabel ; import edsdk . utils . CanonCamera ; public class E04_LiveView { public static void main ( String [ ] args ) throws InterruptedException { final CanonCamera cam = new CanonCamera ( ) ; cam . openSession ( ) ; cam . beginLiveView ( ) ; JFrame frame = new JFrame ( "" ) ; JLabel label = new JLabel ( ) ; frame . getContentPane ( ) . add ( label , BorderLayout . CENTER ) ; frame . setDefaultCloseOperation ( JFrame . DO_NOTHING_ON_CLOSE ) ; frame . addWindowListener ( new WindowAdapter ( ) { @ Override public void windowClosing ( WindowEvent e ) { cam . endLiveView ( ) ; cam . closeSession ( ) ; CanonCamera . close ( ) ; System . exit ( ) ; } } ) ; frame . setVisible ( true ) ; while ( true ) { Thread . sleep ( ) ; BufferedImage image = cam . downloadLiveView ( ) ; if ( image != null ) { label . setIcon ( new ImageIcon ( image ) ) ; frame . pack ( ) ; image . flush ( ) ; } } } } package gettingstarted ; import static edsdk . EdSdkLibrary . kEdsPropID_Av ; import static edsdk . EdSdkLibrary . kEdsPropID_BatteryLevel ; import static edsdk . EdSdkLibrary . kEdsPropID_ISOSpeed ; import static edsdk . EdSdkLibrary . kEdsPropID_Tv ; import static edsdk . utils . CanonConstants . Av_7_1 ; import static edsdk . utils . CanonConstants . ISO_800 ; import static edsdk . utils . CanonConstants . Tv_1by100 ; import java . awt . GridBagConstraints ; import java . awt . GridBagLayout ; import java . awt . Insets ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . io . File ; import java . lang . reflect . Field ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . LinkedList ; import java . util . concurrent . Callable ; import javax . swing . BorderFactory ; import javax . swing . JComboBox ; import javax . swing . JFrame ; import javax . swing . JLabel ; import javax . swing . JPanel ; import edsdk . utils . CanonCamera ; import edsdk . utils . CanonConstants ; import edsdk . utils . commands . ShootTask ; public class E05_Timelapse { public static void main ( String [ ] args ) throws InterruptedException { CanonCamera camera = new CanonCamera ( ) ; camera . openSession ( ) ; camera . setProperty ( kEdsPropID_Av , Av_7_1 ) ; camera . setProperty ( kEdsPropID_Tv , Tv_1by100 ) ; camera . setProperty ( kEdsPropID_ISOSpeed , ISO_800 ) ; createUI ( camera ) ; while ( true ) { System . out . println ( "" ) ; System . out . println ( "" + camera . getProperty ( kEdsPropID_BatteryLevel ) ) ; camera . execute ( new ShootTask ( filename ( ) ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } public static File filename ( ) { return new File ( "" + new SimpleDateFormat ( "" ) . format ( new Date ( ) ) + "" ) ; } private static void createUI ( final CanonCamera camera ) { JFrame frame = new JFrame ( ) ; JPanel content = new JPanel ( new GridBagLayout ( ) ) ; content . setBorder ( BorderFactory . createEmptyBorder ( , , , ) ) ; GridBagConstraints gbc = new GridBagConstraints ( ) ; gbc . anchor = GridBagConstraints . EAST ; gbc . fill = gbc . HORIZONTAL ; gbc . insets = new Insets ( , , , ) ; gbc . gridy = ; addCombobox ( content , gbc , "" , "" , new Callback ( ) { public void call ( int value ) { camera . setProperty ( kEdsPropID_Tv , value ) ; } } ) ; addCombobox ( content , gbc , "" , "" , new Callback ( ) { public void call ( int value ) { camera . setProperty ( kEdsPropID_Av , value ) ; } } ) ; addCombobox ( content , gbc , "" , "" , new Callback ( ) { public void call ( int value ) { camera . setProperty ( kEdsPropID_ISOSpeed , value ) ; } } ) ; frame . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; frame . setContentPane ( content ) ; frame . setSize ( , ) ; frame . setVisible ( true ) ; } private static void addCombobox ( JPanel content , GridBagConstraints gbc , String label , String prefix , final Callback callback ) { gbc . gridx = ; gbc . weightx = ; content . add ( new JLabel ( label ) , gbc ) ; gbc . gridx = ; gbc . weightx = ; LinkedList < String > items = new LinkedList < String > ( ) ; for ( Field field : CanonConstants . class . getDeclaredFields ( ) ) { if ( field . getName ( ) . startsWith ( prefix ) ) { items . add ( field . getName ( ) ) ; } } final JComboBox combo = new JComboBox ( items . toArray ( new String [ ] { } ) ) ; combo . addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent event ) { try { int value = CanonConstants . class . getDeclaredField ( combo . getSelectedItem ( ) . toString ( ) ) . getInt ( null ) ; callback . call ( value ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( NoSuchFieldException e ) { e . printStackTrace ( ) ; } } } ) ; gbc . gridx = ; gbc . weightx = ; content . add ( combo , gbc ) ; gbc . gridy ++ ; } interface Callback { public void call ( int value ) ; } } package gettingstarted ; import edsdk . utils . CanonCamera ; import edsdk . utils . CanonTask ; public class E03_Mixed { public static void main ( String [ ] args ) throws InterruptedException { CanonCamera camera = new CanonCamera ( ) ; camera . openSession ( ) ; boolean result = camera . executeNow ( new CanonTask < Boolean > ( ) { @ Override public void run ( ) { setResult ( true ) ; } } ) ; if ( ! result ) { System . out . println ( "" ) ; } camera . closeSession ( ) ; CanonCamera . close ( ) ; } } package bonsai . app ; public final class BuildConfig { public final static boolean DEBUG = true ; } package bonsai . app ; public final class R { public static final class array { public static final int family_array = ; public static final int situation_array = ; } public static final class attr { } public static final class drawable { public static final int bonsai = ; public static final int chance_of_rain = ; public static final int chance_of_snow = ; public static final int chance_of_storm = ; public static final int cloudy = ; public static final int disease = ; public static final int donate = ; public static final int dust = ; public static final int escaledlogo = ; public static final int fog = ; public static final int haze = ; public static final int ic_launche = ; public static final int ic_launcher = ; public static final int ic_menu_help = ; public static final int ic_pode = ; public static final int ic_tab_bonsai = ; public static final int ic_tab_calendar = ; public static final int ic_tab_more = ; public static final int ic_tab_selectbonsai = ; public static final int ic_task = ; public static final int ic_transplant = ; public static final int ic_water = ; public static final int icy = ; public static final int mist = ; public static final int mostly_sunny = ; public static final int sleet = ; public static final int smoke = ; public static final int snow = ; public static final int storm = ; public static final int sunny = ; public static final int task = ; public static final int thunderstorm = ; } public static final class id { public static final int ImageView01 = ; public static final int LinearLayout01 = ; public static final int LinearLayout02 = ; public static final int LinearLayout03 = ; public static final int LinearLayout04 = ; public static final int MnuOpc1 = ; public static final int MnuOpc2 = ; public static final int bonsaiImage = ; public static final int bonsairowtext = ; public static final int btnCountry = ; public static final int btnPostCode = ; public static final int btnSend = ; public static final int button1 = ; public static final int button2 = ; public static final int cancelButton = ; public static final int chkAttachment = ; public static final int contactbutton = ; public static final int donatebutton = ; public static final int editAge = ; public static final int editCountry = ; public static final int editHeight = ; public static final int editName = ; public static final int editPostCode = ; public static final int etBody = ; public static final int etEmail = ; public static final int etSubject = ; public static final int familySpinner = ; public static final int footer = ; public static final int imageButton1 = ; public static final int imageButton2 = ; public static final int imageButton3 = ; public static final int imageView1 = ; public static final int imageView2 = ; public static final int imageView4 = ; public static final int imageView5 = ; public static final int imageWeather = ; public static final int linearLayout1 = ; public static final int manageNotifications = ; public static final int photoURLtext = ; public static final int podeButton = ; public static final int relativeLayout1 = ; public static final int saveButton = ; public static final int scrollMore = ; public static final int scrollView1 = ; public static final int spinner1 = ; public static final int tableRow1 = ; public static final int tableRow2 = ; public static final int tableRow3 = ; public static final int tableRow4 = ; public static final int textFamily = ; public static final int textName = ; public static final int textPrune = ; public static final int textTemperature = ; public static final int textTransplant = ; public static final int textView1 = ; public static final int textView2 = ; public static final int textView3 = ; public static final int textWater = ; public static final int textYears = ; public static final int textweather = ; public static final int txtForBody = ; public static final int txtForEmail = ; public static final int txtForSubject = ; public static final int waterButton = ; } public static final class layout { public static final int bonsai = ; public static final int bonsai_row = ; public static final int editbonsai = ; public static final int enviomail = ; public static final int main = ; public static final int more = ; public static final int selectbonsai = ; public static final int start = ; public static final int task = ; public static final int task_row = ; } public static final class menu { public static final int menu = ; public static final int menubonsai = ; } public static final class string { public static final int app_name = ; public static final int arrow_text = ; public static final int bonsai_text_family = ; public static final int bonsai_text_name = ; public static final int cancel_button = ; public static final int delete_button = ; public static final int edit_button = ; public static final int image_desc_bonsai = ; public static final int loading_text = ; public static final int menu_help = ; public static final int pode_button = ; public static final int pode_no_info = ; public static final int save_button = ; public static final int tage = ; public static final int tdelete = ; public static final int tfamily = ; public static final int theight = ; public static final int tlocalize = ; public static final int tname = ; public static final int tphoto = ; public static final int tpostalcode = ; public static final int transplant_button = ; public static final int transplant_no_info = ; public static final int tselect = ; public static final int tsituation = ; public static final int water_button = ; public static final int water_no_info = ; public static final int weather_img = ; public static final int weather_no_info = ; public static final int years_n_text = ; public static final int years_text = ; } } package bonsai . app ; import bonsai . app . alarm . NotificationService ; import android . app . TabActivity ; import android . content . Intent ; import android . content . res . Resources ; import android . database . Cursor ; import android . os . Bundle ; import android . widget . TabHost ; import android . widget . Toast ; public class AndroidProjectActivity extends TabActivity { public static long bonsaiactual ; public static boolean fullversion ; public static boolean iamediting ; private BonsaiDbUtil bonsaidb ; public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; iamediting = false ; fullversion = true ; try { bonsaidb = new BonsaiDbUtil ( this ) ; bonsaidb . open ( ) ; Cursor bonsai = bonsaidb . fetchAllBonsais ( ) ; bonsai . moveToLast ( ) ; bonsaiactual = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_ROWID ) ) ; bonsai . close ( ) ; bonsaidb . close ( ) ; setContentView ( R . layout . main ) ; Resources res = getResources ( ) ; TabHost tabHost = getTabHost ( ) ; TabHost . TabSpec spec ; Intent intent ; intent = new Intent ( ) . setClass ( this , SelectBonsaiActivity . class ) ; spec = tabHost . newTabSpec ( "" ) . setIndicator ( "" , res . getDrawable ( R . drawable . ic_tab_selectbonsai ) ) . setContent ( intent ) ; tabHost . addTab ( spec ) ; intent = new Intent ( ) . setClass ( this , BonsaiActivity . class ) ; spec = tabHost . newTabSpec ( "" ) . setIndicator ( "" , res . getDrawable ( R . drawable . ic_tab_bonsai ) ) . setContent ( intent ) ; tabHost . addTab ( spec ) ; intent = new Intent ( ) . setClass ( this , TaskActivity . class ) ; spec = tabHost . newTabSpec ( "" ) . setIndicator ( "" , res . getDrawable ( R . drawable . ic_tab_calendar ) ) . setContent ( intent ) ; tabHost . addTab ( spec ) ; intent = new Intent ( ) . setClass ( this , MoreActivity . class ) ; spec = tabHost . newTabSpec ( "" ) . setIndicator ( "" , res . getDrawable ( R . drawable . ic_tab_more ) ) . setContent ( intent ) ; tabHost . addTab ( spec ) ; tabHost . setCurrentTab ( ) ; intent = new Intent ( this , NotificationService . class ) ; startService ( intent ) ; Intent startmessage = new Intent ( ) . setClass ( this , StartActivity . class ) ; startActivity ( startmessage ) ; } catch ( Exception e ) { bonsaiactual = ; System . out . println ( e . toString ( ) ) ; } } public void changeTab ( int i ) { getTabHost ( ) . setCurrentTab ( i ) ; } } package bonsai . app . weather ; import java . io . IOException ; import java . io . InputStream ; import java . util . List ; import java . net . URL ; import javax . xml . parsers . SAXParser ; import java . net . MalformedURLException ; import javax . xml . parsers . SAXParserFactory ; public class XmlParserSax { private URL rssUrl ; public XmlParserSax ( String url ) { try { this . rssUrl = new URL ( url ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } public List < Weather > parse ( ) { SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; try { SAXParser parser = factory . newSAXParser ( ) ; XmlHandler handler = new XmlHandler ( ) ; parser . parse ( this . getInputStream ( ) , handler ) ; return handler . getweather ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } private InputStream getInputStream ( ) { try { System . out . println ( rssUrl . openConnection ( ) . getInputStream ( ) ) ; return rssUrl . openConnection ( ) . getInputStream ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } package bonsai . app . weather ; public class Weather { private int tempMax ; private int tempMin ; private double tempMediaC ; private String icon ; public double getTempMax ( ) { double t = ( tempMax - ) / ; return t ; } public void setTempMax ( int tempMax ) { this . tempMax = tempMax ; } public double getTempMin ( ) { double t = ( tempMin - ) / ; return t ; } public void setTempMin ( int tempMin ) { this . tempMin = tempMin ; } public int getTempMedia ( ) { double t1 = ( tempMax - ) / ; System . out . println ( "" + tempMax + "" + t1 ) ; double t2 = ( tempMin - ) / ; System . out . println ( "" + tempMin + "" + t2 ) ; tempMediaC = ( t1 + t2 ) / ; return ( int ) tempMediaC ; } public String getIcon ( ) { return icon ; } public void setIcon ( String icon ) { this . icon = icon ; } } package bonsai . app . weather ; import java . util . ArrayList ; import java . util . List ; import org . xml . sax . Attributes ; import org . xml . sax . helpers . DefaultHandler ; public class XmlHandler extends DefaultHandler { int n = ; private List < Weather > weathers = new ArrayList < Weather > ( ) ; private Weather weatherActual ; public List < Weather > getweather ( ) { return weathers ; } public void startElement ( String uri , String name , String qName , Attributes atts ) { if ( qName . compareTo ( "" ) == ) { String day = atts . getValue ( ) ; System . out . println ( "" + day ) ; weatherActual = new Weather ( ) ; } if ( qName . compareToIgnoreCase ( "" ) == ) { int low = Integer . parseInt ( atts . getValue ( ) ) ; System . out . println ( "" + low ) ; weatherActual . setTempMin ( low ) ; } if ( qName . compareToIgnoreCase ( "" ) == ) { int high = Integer . parseInt ( atts . getValue ( ) ) ; System . out . println ( "" + high ) ; weatherActual . setTempMax ( high ) ; } if ( qName . compareToIgnoreCase ( "" ) == ) { if ( n > ) { String icon = atts . getValue ( ) ; System . out . println ( "" + icon ) ; weatherActual . setIcon ( icon ) ; weathers . add ( weatherActual ) ; } n ++ ; } } } package bonsai . app ; import android . content . ContentValues ; import android . content . Context ; import android . database . Cursor ; import android . database . SQLException ; import android . database . sqlite . SQLiteDatabase ; import android . database . sqlite . SQLiteOpenHelper ; import android . util . Log ; public class BonsaiDbUtil { public static final String KEY_ROWID = "" ; public static final String KEY_NAME = "" ; public static final String KEY_FAMILY = "" ; public static final String KEY_AGE = "" ; public static final String KEY_HEIGHT = "" ; public static final String KEY_PHOTO = "" ; public static final String KEY_LAST_PODE = "" ; public static final String KEY_LAST_WATER = "" ; public static final String KEY_LAST_TRASPLANT = "" ; public static final String KEY_LOCALIZATION = "" ; public static final String KEY_SITUATION = "" ; private static final String TAG = "" ; private DatabaseHelper mDbHelper ; private SQLiteDatabase mDb ; private static final String DATABASE_CREATE = "" + "" + "" + "" ; private static final String FAMILY_DATABASE_CREATE = "" + "" + "" ; private static final String DATABASE_NAME = "" ; private static final String DATABASE_TABLE = "" ; private static final int DATABASE_VERSION = ; private final Context mCtx ; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper ( Context context ) { super ( context , DATABASE_NAME , null , DATABASE_VERSION ) ; } @ Override public void onCreate ( SQLiteDatabase db ) { db . execSQL ( DATABASE_CREATE ) ; db . execSQL ( FAMILY_DATABASE_CREATE ) ; familydbseed ( db ) ; } @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { Log . w ( TAG , "" + oldVersion + "" + newVersion + "" ) ; db . execSQL ( "" ) ; onCreate ( db ) ; } public void familydbseed ( SQLiteDatabase db ) { db . execSQL ( "" + "" + * + "" + * + "" + * + "" ) ; db . execSQL ( "" + "" + * + "" + * + "" + * + "" ) ; db . execSQL ( "" + "" + * + "" + * + "" + * + "" ) ; db . execSQL ( "" + "" + * + "" + * + "" + * + "" ) ; db . execSQL ( "" + "" + * + "" + * + "" + * + "" ) ; } } public BonsaiDbUtil ( Context ctx ) { this . mCtx = ctx ; } public BonsaiDbUtil open ( ) throws SQLException { mDbHelper = new DatabaseHelper ( mCtx ) ; mDb = mDbHelper . getWritableDatabase ( ) ; return this ; } public void close ( ) { mDbHelper . close ( ) ; } public long createBonsai ( String name , String family , long age , int height , String photo , long last_pode , long last_water , long last_trasplant , String localization , String situation ) { ContentValues initialValues = new ContentValues ( ) ; initialValues . put ( KEY_NAME , name ) ; initialValues . put ( KEY_FAMILY , family ) ; initialValues . put ( KEY_AGE , age ) ; initialValues . put ( KEY_HEIGHT , height ) ; initialValues . put ( KEY_PHOTO , photo ) ; initialValues . put ( KEY_LAST_PODE , last_pode ) ; initialValues . put ( KEY_LAST_WATER , last_water ) ; initialValues . put ( KEY_LAST_TRASPLANT , last_trasplant ) ; initialValues . put ( KEY_LOCALIZATION , localization ) ; initialValues . put ( KEY_SITUATION , situation ) ; return mDb . insert ( DATABASE_TABLE , null , initialValues ) ; } public boolean deleteBonsai ( long rowId ) { return mDb . delete ( DATABASE_TABLE , KEY_ROWID + "" + rowId , null ) > ; } public Cursor fetchAllBonsais ( ) { return mDb . query ( DATABASE_TABLE , new String [ ] { KEY_ROWID , KEY_NAME , KEY_FAMILY , KEY_AGE , KEY_HEIGHT , KEY_PHOTO , KEY_LAST_PODE , KEY_LAST_WATER , KEY_LAST_TRASPLANT , KEY_LOCALIZATION , KEY_SITUATION } , null , null , null , null , null ) ; } public Cursor fetchBonsai ( long rowId ) throws SQLException { Cursor mCursor = mDb . query ( true , DATABASE_TABLE , new String [ ] { KEY_ROWID , KEY_NAME , KEY_FAMILY , KEY_AGE , KEY_HEIGHT , KEY_PHOTO , KEY_LAST_PODE , KEY_LAST_WATER , KEY_LAST_TRASPLANT , KEY_LOCALIZATION , KEY_SITUATION } , KEY_ROWID + "" + rowId , null , null , null , null , null ) ; if ( mCursor != null ) { mCursor . moveToFirst ( ) ; } return mCursor ; } public boolean updateBonsai ( long rowId , String name , String family , long age , int height , String photo , String localization , String situation ) { ContentValues args = new ContentValues ( ) ; args . put ( KEY_NAME , name ) ; args . put ( KEY_FAMILY , family ) ; args . put ( KEY_AGE , age ) ; args . put ( KEY_HEIGHT , height ) ; args . put ( KEY_PHOTO , photo ) ; args . put ( KEY_LOCALIZATION , localization ) ; args . put ( KEY_SITUATION , situation ) ; return mDb . update ( DATABASE_TABLE , args , KEY_ROWID + "" + rowId , null ) > ; } public boolean waterBonsai ( long rowId , long last_water ) { ContentValues args = new ContentValues ( ) ; args . put ( KEY_LAST_WATER , last_water ) ; return mDb . update ( DATABASE_TABLE , args , KEY_ROWID + "" + rowId , null ) > ; } public boolean podeBonsai ( long rowId , long last_pode ) { ContentValues args = new ContentValues ( ) ; args . put ( KEY_LAST_PODE , last_pode ) ; return mDb . update ( DATABASE_TABLE , args , KEY_ROWID + "" + rowId , null ) > ; } public boolean transplantBonsai ( long rowId , long last_trasplant ) { ContentValues args = new ContentValues ( ) ; args . put ( KEY_LAST_TRASPLANT , last_trasplant ) ; return mDb . update ( DATABASE_TABLE , args , KEY_ROWID + "" + rowId , null ) > ; } } package bonsai . app . alarm ; import java . util . Date ; import bonsai . app . AndroidProjectActivity ; import bonsai . app . BonsaiDbUtil ; import bonsai . app . FamilyDbUtil ; import bonsai . app . R ; import android . app . IntentService ; import android . app . Notification ; import android . app . NotificationManager ; import android . app . PendingIntent ; import android . content . Intent ; import android . database . Cursor ; public class NotificationService extends IntentService { public static boolean notificado ; public static boolean enabled ; private BonsaiDbUtil bonsaidb ; private FamilyDbUtil familydb ; public NotificationService ( ) { super ( "" ) ; } @ Override protected void onHandleIntent ( Intent intent ) { while ( true ) { try { enabled = true ; Thread . sleep ( ) ; if ( ! enabled ) break ; boolean tarea = checkForTasks ( ) ; if ( notificado ) { if ( tarea ) { } else { notificado = false ; } } else { if ( tarea ) { notifica ( ) ; notificado = true ; } else { } } } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; } } } private boolean checkForTasks ( ) { Cursor bonsaisCursor = null ; try { bonsaidb = new BonsaiDbUtil ( this ) ; bonsaidb . open ( ) ; familydb = new FamilyDbUtil ( this ) ; familydb . open ( ) ; bonsaisCursor = bonsaidb . fetchAllBonsais ( ) ; bonsaisCursor . moveToFirst ( ) ; for ( int i = ; i < bonsaisCursor . getCount ( ) ; i ++ ) { long id = bonsaisCursor . getLong ( bonsaisCursor . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_ROWID ) ) ; String possibletask = checkWater ( id ) ; if ( possibletask != null ) { return true ; } possibletask = checkPode ( id ) ; if ( possibletask != null ) { return true ; } possibletask = checkTransplant ( id ) ; if ( possibletask != null ) { return true ; } if ( i < bonsaisCursor . getCount ( ) - ) bonsaisCursor . moveToNext ( ) ; } bonsaisCursor . close ( ) ; bonsaidb . close ( ) ; familydb . close ( ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; bonsaisCursor . close ( ) ; bonsaidb . close ( ) ; familydb . close ( ) ; } return false ; } private void notifica ( ) { try { int icon = R . drawable . bonsai ; CharSequence tickerText = "" ; long when = System . currentTimeMillis ( ) ; Notification notification = new Notification ( icon , tickerText , when ) ; NotificationManager notificationManager = ( NotificationManager ) getSystemService ( NOTIFICATION_SERVICE ) ; Intent notificationIntent = new Intent ( this , AndroidProjectActivity . class ) ; PendingIntent contentIntent = PendingIntent . getActivity ( this , , notificationIntent , ) ; notification . setLatestEventInfo ( this , "" , "" , contentIntent ) ; notification . defaults |= Notification . DEFAULT_SOUND ; notification . defaults |= Notification . DEFAULT_VIBRATE ; notification . defaults |= Notification . DEFAULT_LIGHTS ; notification . flags = Notification . FLAG_AUTO_CANCEL ; notification . ledARGB = ; notification . ledOnMS = ; notification . ledOffMS = ; notification . flags |= Notification . FLAG_SHOW_LIGHTS ; notificationManager . notify ( , notification ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; } } private String checkWater ( long id ) { String name ; String family ; long lastwatered ; long waterfrec ; int height = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; Cursor bonsai = null ; Cursor cfamily = null ; try { bonsai = bonsaidb . fetchBonsai ( id ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lastwatered = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_WATER ) ) ; height = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_HEIGHT ) ) ; cfamily = familydb . fetchFamilybyName ( family ) ; waterfrec = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_WATER_FRECUENCY ) ) ; if ( lastwatered == ) return ( "" + name ) ; else if ( ( hoursTime - lastwatered ) > waterfrec ) return ( "" + name + "" + height / + "" ) ; else return null ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; return null ; } finally { bonsai . close ( ) ; cfamily . close ( ) ; } } private String checkTransplant ( long id ) { String name ; String family ; long lasttransplant ; long transplantfrec ; long age = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; Cursor bonsai = null ; Cursor cfamily = null ; try { bonsai = bonsaidb . fetchBonsai ( id ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lasttransplant = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_TRASPLANT ) ) ; long date = new Date ( ) . getTime ( ) / ( * * ) ; age = ( ( date - bonsai . getLong ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_AGE ) ) ) / ( * ) ) ; cfamily = familydb . fetchFamilybyName ( family ) ; transplantfrec = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_TRANSPLANT_FRECUENCY ) ) ; if ( age < ) return null ; else if ( lasttransplant == ) return ( "" + name ) ; else { if ( ( hoursTime - lasttransplant ) > transplantfrec ) return ( "" + name + "" + ( hoursTime - lasttransplant ) / + "" ) ; else return null ; } } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; return null ; } finally { bonsai . close ( ) ; cfamily . close ( ) ; } } private String checkPode ( long id ) { String name ; String family ; long lastpode ; long podefrecuency ; long age = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; Cursor bonsai = null ; Cursor cfamily = null ; try { bonsai = bonsaidb . fetchBonsai ( id ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lastpode = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_PODE ) ) ; long date = new Date ( ) . getTime ( ) / ( * * ) ; age = ( ( date - bonsai . getLong ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_AGE ) ) ) / ( * ) ) ; cfamily = familydb . fetchFamilybyName ( family ) ; podefrecuency = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_PODE_FRECUENCY ) ) ; if ( lastpode == ) return ( "" + name + "" ) ; else if ( age < ) { if ( hoursTime - lastpode > * ) return ( "" + name + "" ) ; else return null ; } else if ( age >= && ( hoursTime - lastpode > podefrecuency ) ) return ( "" + name + "" ) ; else return null ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; return null ; } finally { bonsai . close ( ) ; cfamily . close ( ) ; } } } package bonsai . app ; import android . content . ContentValues ; import android . content . Context ; import android . database . Cursor ; import android . database . SQLException ; import android . database . sqlite . SQLiteDatabase ; import android . database . sqlite . SQLiteOpenHelper ; import android . util . Log ; public class FamilyDbUtil { public static final String KEY_ROWID = "" ; public static final String KEY_FAMILY = "" ; public static final String KEY_PODE_FRECUENCY = "" ; public static final String KEY_WATER_FRECUENCY = "" ; public static final String KEY_TRANSPLANT_FRECUENCY = "" ; public static final String KEY_SITUATION = "" ; private static final String TAG = "" ; private FamDatabaseHelper mDbHelper ; private SQLiteDatabase mDb ; private static final String DATABASE_NAME = "" ; private static final String DATABASE_TABLE = "" ; private static final int DATABASE_VERSION = ; private final Context mCtx ; private static class FamDatabaseHelper extends SQLiteOpenHelper { FamDatabaseHelper ( Context context ) { super ( context , DATABASE_NAME , null , DATABASE_VERSION ) ; } @ Override public void onCreate ( SQLiteDatabase db ) { } @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { Log . w ( TAG , "" + oldVersion + "" + newVersion + "" ) ; db . execSQL ( "" ) ; onCreate ( db ) ; } } public FamilyDbUtil ( Context ctx ) { this . mCtx = ctx ; } public FamilyDbUtil open ( ) throws SQLException { mDbHelper = new FamDatabaseHelper ( mCtx ) ; mDb = mDbHelper . getWritableDatabase ( ) ; return this ; } public void close ( ) { mDbHelper . close ( ) ; } public long createFamily ( String family , long pode_frecuency , long water_frecuency , long transplant_frecuency , String situation ) { ContentValues initialValues = new ContentValues ( ) ; initialValues . put ( KEY_FAMILY , family ) ; initialValues . put ( KEY_PODE_FRECUENCY , pode_frecuency ) ; initialValues . put ( KEY_WATER_FRECUENCY , water_frecuency ) ; initialValues . put ( KEY_TRANSPLANT_FRECUENCY , transplant_frecuency ) ; initialValues . put ( KEY_SITUATION , situation ) ; return mDb . insert ( DATABASE_TABLE , null , initialValues ) ; } public boolean deleteFamily ( long rowId ) { return mDb . delete ( DATABASE_TABLE , KEY_ROWID + "" + rowId , null ) > ; } public Cursor fetchAllFamilys ( ) { return mDb . query ( DATABASE_TABLE , new String [ ] { KEY_ROWID , KEY_FAMILY , KEY_PODE_FRECUENCY , KEY_WATER_FRECUENCY , KEY_TRANSPLANT_FRECUENCY , KEY_SITUATION } , null , null , null , null , null ) ; } public Cursor fetchFamily ( long rowId ) throws SQLException { Cursor mCursor = mDb . query ( true , DATABASE_TABLE , new String [ ] { KEY_ROWID , KEY_FAMILY , KEY_PODE_FRECUENCY , KEY_WATER_FRECUENCY , KEY_TRANSPLANT_FRECUENCY , KEY_SITUATION } , KEY_ROWID + "" + rowId , null , null , null , null , null ) ; if ( mCursor != null ) { mCursor . moveToFirst ( ) ; } return mCursor ; } public Cursor fetchFamilybyName ( String name ) throws SQLException { Cursor mCursor = mDb . query ( true , DATABASE_TABLE , new String [ ] { KEY_ROWID , KEY_FAMILY , KEY_PODE_FRECUENCY , KEY_WATER_FRECUENCY , KEY_TRANSPLANT_FRECUENCY , KEY_SITUATION } , KEY_FAMILY + "" + name + "" , null , null , null , null , null ) ; if ( mCursor != null ) { mCursor . moveToFirst ( ) ; } return mCursor ; } public boolean updateFamily ( long rowId , String family , long pode_frecuency , long water_frecuency , long transplant_frecuency , String situation ) { ContentValues args = new ContentValues ( ) ; args . put ( KEY_FAMILY , family ) ; args . put ( KEY_PODE_FRECUENCY , pode_frecuency ) ; args . put ( KEY_WATER_FRECUENCY , water_frecuency ) ; args . put ( KEY_TRANSPLANT_FRECUENCY , transplant_frecuency ) ; args . put ( KEY_SITUATION , situation ) ; return mDb . update ( DATABASE_TABLE , args , KEY_ROWID + "" + rowId , null ) > ; } } package bonsai . app ; import java . util . Date ; import android . app . Activity ; import android . content . Intent ; import android . database . Cursor ; import android . net . Uri ; import android . os . Bundle ; import android . os . Handler ; import android . view . Menu ; import android . view . MenuInflater ; import android . view . MenuItem ; import android . view . View ; import android . widget . ImageView ; import android . widget . ImageView . ScaleType ; import android . widget . LinearLayout ; import android . widget . TextView ; import android . widget . Toast ; import java . util . List ; import bonsai . app . weather . Weather ; import bonsai . app . weather . XmlParserSax ; public class BonsaiActivity extends Activity { private BonsaiDbUtil bonsaidb ; private FamilyDbUtil familydb ; private TextView name ; private TextView family ; private ImageView photo ; private TextView age ; private TextView textWater ; private TextView textTransplant ; private TextView textPrune ; private TextView textTemperature ; private TextView textWeather ; private ImageView weatherIcon ; private Weather w ; private boolean weatherAvail ; private String location ; private double temperature ; private String imageWeather ; private final Handler handler = new Handler ( ) ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . bonsai ) ; name = ( TextView ) findViewById ( R . id . textName ) ; family = ( TextView ) findViewById ( R . id . textFamily ) ; photo = ( ImageView ) findViewById ( R . id . bonsaiImage ) ; age = ( TextView ) findViewById ( R . id . textYears ) ; textWater = ( TextView ) findViewById ( R . id . textWater ) ; textTransplant = ( TextView ) findViewById ( R . id . textTransplant ) ; textPrune = ( TextView ) findViewById ( R . id . textPrune ) ; textTemperature = ( TextView ) findViewById ( R . id . textTemperature ) ; textWeather = ( TextView ) findViewById ( R . id . textweather ) ; weatherIcon = ( ImageView ) findViewById ( R . id . imageWeather ) ; textWeather = ( TextView ) findViewById ( R . id . textweather ) ; weatherIcon = ( ImageView ) findViewById ( R . id . imageWeather ) ; } @ Override public void onResume ( ) { super . onResume ( ) ; try { bonsaidb = new BonsaiDbUtil ( this ) ; bonsaidb . open ( ) ; familydb = new FamilyDbUtil ( this ) ; familydb . open ( ) ; Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; name . setText ( bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ) ; family . setText ( bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ) ; String photouri = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_PHOTO ) ) ; if ( photouri . length ( ) > ) { photo . setImageURI ( Uri . parse ( photouri ) ) ; photo . setScaleType ( ScaleType . FIT_CENTER ) ; } else photo . setImageResource ( R . drawable . ic_launcher ) ; long date = new Date ( ) . getTime ( ) / ( * * ) ; age . setText ( "" + ( ( date - bonsai . getLong ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_AGE ) ) ) / ( * ) ) ) ; checkWeather ( ) ; weatherAction ( ) ; checkWater ( ) ; checkTransplant ( ) ; checkPode ( ) ; } catch ( Exception e ) { Toast . makeText ( this , "" , Toast . LENGTH_SHORT ) . show ( ) ; } } @ Override public void onPause ( ) { super . onPause ( ) ; bonsaidb . close ( ) ; familydb . close ( ) ; } private void weatherAction ( ) { handler . postDelayed ( new Runnable ( ) { @ Override public void run ( ) { if ( weatherAvail ) { setTempInfo ( ) ; setWeatherInfo ( ) ; setWeatherComment ( ) ; } else { weatherAction ( ) ; } } } , ) ; } public void goEdit ( View v ) { try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; AndroidProjectActivity . iamediting = true ; Intent editAct = new Intent ( ) . setClass ( this , EditBonsaiActivity . class ) ; startActivity ( editAct ) ; } catch ( Exception e ) { Toast . makeText ( this , "" , Toast . LENGTH_SHORT ) . show ( ) ; } } public void toastImage ( View v ) { Toast ImageToast = new Toast ( getBaseContext ( ) ) ; LinearLayout toastLayout = new LinearLayout ( getBaseContext ( ) ) ; toastLayout . setOrientation ( LinearLayout . HORIZONTAL ) ; ImageView image = new ImageView ( getBaseContext ( ) ) ; Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; String photouri = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_PHOTO ) ) ; if ( photouri . length ( ) > ) image . setImageURI ( Uri . parse ( photouri ) ) ; else image . setImageResource ( R . drawable . ic_launcher ) ; toastLayout . addView ( image ) ; ImageToast . setView ( toastLayout ) ; ImageToast . setDuration ( Toast . LENGTH_SHORT ) ; ImageToast . show ( ) ; } private void checkWater ( ) { String family ; long lastwatered ; long waterfrec ; int height = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lastwatered = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_WATER ) ) ; height = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_HEIGHT ) ) ; Cursor cfamily = familydb . fetchFamilybyName ( family ) ; startManagingCursor ( cfamily ) ; waterfrec = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_WATER_FRECUENCY ) ) ; if ( lastwatered == ) textWater . setText ( "" ) ; else if ( temperature > ) textWater . setText ( "" + height / + "" ) ; else if ( ( hoursTime - lastwatered ) > waterfrec ) textWater . setText ( "" + height / + "" ) ; else textWater . setText ( "" + new Date ( ( long ) ( lastwatered * ( * * ) ) ) . toLocaleString ( ) . toString ( ) . substring ( , ) ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; } } private void checkTransplant ( ) { String family ; long lasttransplant ; long transplantfrec ; long age = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lasttransplant = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_TRASPLANT ) ) ; long date = new Date ( ) . getTime ( ) / ( * * ) ; age = ( ( date - bonsai . getLong ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_AGE ) ) ) / ( * ) ) ; Cursor cfamily = familydb . fetchFamilybyName ( family ) ; startManagingCursor ( cfamily ) ; transplantfrec = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_TRANSPLANT_FRECUENCY ) ) ; if ( age < ) textTransplant . setText ( "" ) ; else if ( lasttransplant == ) textTransplant . setText ( "" ) ; else { if ( ( hoursTime - lasttransplant ) > transplantfrec ) textTransplant . setText ( "" + "" + ( hoursTime - lasttransplant ) / + "" ) ; else textTransplant . setText ( "" + ( hoursTime - lasttransplant ) / + "" ) ; } } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; } } private void checkPode ( ) { String name ; String family ; long lastpode ; long podefrecuency ; long age = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lastpode = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_PODE ) ) ; long date = new Date ( ) . getTime ( ) / ( * * ) ; age = ( ( date - bonsai . getLong ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_AGE ) ) ) / ( * ) ) ; Cursor cfamily = familydb . fetchFamilybyName ( family ) ; startManagingCursor ( cfamily ) ; podefrecuency = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_PODE_FRECUENCY ) ) ; if ( lastpode == ) textPrune . setText ( "" + name + "" ) ; else if ( age < ) { if ( hoursTime - lastpode > * ) textPrune . setText ( "" ) ; else textPrune . setText ( "" ) ; } else if ( age >= && ( hoursTime - lastpode > podefrecuency ) ) textPrune . setText ( "" + name + "" ) ; else textPrune . setText ( name + "" ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; } } private void checkWeather ( ) { weatherAvail = false ; Thread thread = new Thread ( ) { public void run ( ) { try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; location = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LOCALIZATION ) ) ; XmlParserSax saxparser = new XmlParserSax ( "" + location ) ; List < Weather > weather = saxparser . parse ( ) ; w = weather . get ( ) ; temperature = w . getTempMedia ( ) ; String s = w . getIcon ( ) ; imageWeather = s ; weatherAvail = true ; } catch ( Exception e ) { System . out . println ( "" + e . toString ( ) ) ; } } } ; thread . start ( ) ; } public void setTempInfo ( ) { try { textWeather . setText ( Integer . toString ( w . getTempMedia ( ) ) + "" ) ; } catch ( Exception e ) { } } public void setWeatherInfo ( ) { try { String s = imageWeather ; s = s . replaceAll ( "" , "" ) ; s = s . replaceAll ( "" , "" ) ; System . out . println ( "" + s ) ; if ( s . equals ( "" ) ) { weatherIcon . setImageResource ( R . drawable . chance_of_rain ) ; } if ( s . equals ( "" ) ) weatherIcon . setImageResource ( R . drawable . chance_of_snow ) ; if ( s . equals ( "" ) ) weatherIcon . setImageResource ( R . drawable . chance_of_storm ) ; if ( s . equals ( "" ) ) weatherIcon . setImageResource ( R . drawable . cloudy ) ; if ( s . equals ( "" ) ) weatherIcon . setImageResource ( R . drawable . dust ) ; if ( s . equals ( "" ) ) weatherIcon . setImageResource ( R . drawable . fog ) ; if ( s . equals ( "" ) ) weatherIcon . setImageResource ( R . drawable . haze ) ; if ( s . equals ( "" ) ) { weatherIcon . setImageResource ( R . drawable . icy ) ; } if ( s . equals ( "" ) ) weatherIcon . setImageResource ( R . drawable . mist ) ; if ( s . equals ( "" ) ) { weatherIcon . setImageResource ( R . drawable . mostly_sunny ) ; } if ( s . equals ( "" ) ) weatherIcon . setImageResource ( R . drawable . smoke ) ; if ( s . equals ( "" ) ) { weatherIcon . setImageResource ( R . drawable . snow ) ; } if ( s . equals ( "" ) ) { weatherIcon . setImageResource ( R . drawable . storm ) ; } if ( s . equals ( "" ) ) { weatherIcon . setImageResource ( R . drawable . sunny ) ; } if ( s . equals ( "" ) ) { weatherIcon . setImageResource ( R . drawable . thunderstorm ) ; } } catch ( Exception e ) { } } public void setWeatherComment ( ) { try { String situation ; Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; situation = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_SITUATION ) ) ; System . out . println ( "" + situation ) ; String s = imageWeather ; s = s . replaceAll ( "" , "" ) ; s = s . replaceAll ( "" , "" ) ; System . out . println ( "" + s ) ; if ( s . equals ( "" ) ) { if ( situation . equals ( "" ) ) textTemperature . setText ( "" ) ; } if ( s . equals ( "" ) || s . equals ( "" ) ) { if ( situation . equals ( "" ) ) textTemperature . setText ( "" ) ; } if ( s . equals ( "" ) ) { if ( situation . equals ( "" ) ) textTemperature . setText ( "" ) ; } if ( s . equals ( "" ) || s . equals ( "" ) ) { if ( situation . equals ( "" ) ) textTemperature . setText ( "" + "" ) ; } else { textTemperature . setText ( "" ) ; } } catch ( Exception e ) { } } public void makeWater ( View v ) { String name = "" ; try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; } catch ( Exception e ) { } long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; bonsaidb . waterBonsai ( AndroidProjectActivity . bonsaiactual , hoursTime ) ; Toast . makeText ( this , name + "" , Toast . LENGTH_LONG ) . show ( ) ; onResume ( ) ; } public void makePode ( View v ) { String name = "" ; try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; } catch ( Exception e ) { } long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; bonsaidb . podeBonsai ( AndroidProjectActivity . bonsaiactual , hoursTime ) ; Toast . makeText ( this , name + "" , Toast . LENGTH_LONG ) . show ( ) ; onResume ( ) ; } public void makeTransplant ( View v ) { String name = "" ; try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; } catch ( Exception e ) { } long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; bonsaidb . transplantBonsai ( AndroidProjectActivity . bonsaiactual , hoursTime ) ; Toast . makeText ( this , name + "" , Toast . LENGTH_LONG ) . show ( ) ; onResume ( ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { MenuInflater inflater = getMenuInflater ( ) ; inflater . inflate ( R . menu . menubonsai , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { switch ( item . getItemId ( ) ) { case R . id . MnuOpc1 : Toast . makeText ( this , "" , Toast . LENGTH_LONG ) . show ( ) ; return true ; case R . id . MnuOpc2 : Intent intent = new Intent ( BonsaiActivity . this , EnvioMailActivity . class ) ; Bundle bundle = new Bundle ( ) ; bundle . putString ( "" , "" ) ; intent . putExtras ( bundle ) ; startActivity ( intent ) ; return true ; default : return super . onOptionsItemSelected ( item ) ; } } } package bonsai . app ; import android . app . Activity ; import android . content . Intent ; import android . net . Uri ; import android . os . Bundle ; import android . view . View ; import android . view . View . OnClickListener ; import android . widget . Button ; import android . widget . CheckBox ; import android . widget . EditText ; import android . widget . TextView ; public class EnvioMailActivity extends Activity { @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . enviomail ) ; final TextView etEmail = ( TextView ) findViewById ( R . id . etEmail ) ; final EditText etSubject = ( EditText ) findViewById ( R . id . etSubject ) ; final EditText etBody = ( EditText ) findViewById ( R . id . etBody ) ; final CheckBox chkAttachment = ( CheckBox ) findViewById ( R . id . chkAttachment ) ; Bundle bundle = getIntent ( ) . getExtras ( ) ; etEmail . setText ( bundle . getString ( "" ) ) ; Button btnSend = ( Button ) findViewById ( R . id . btnSend ) ; btnSend . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { Intent itSend = new Intent ( android . content . Intent . ACTION_SEND ) ; itSend . setType ( "" ) ; itSend . putExtra ( android . content . Intent . EXTRA_EMAIL , new String [ ] { etEmail . getText ( ) . toString ( ) } ) ; itSend . putExtra ( android . content . Intent . EXTRA_SUBJECT , etSubject . getText ( ) . toString ( ) ) ; itSend . putExtra ( android . content . Intent . EXTRA_TEXT , etBody . getText ( ) ) ; if ( chkAttachment . isChecked ( ) ) { itSend . putExtra ( Intent . EXTRA_STREAM , Uri . parse ( "" + getPackageName ( ) + "" + R . drawable . ic_launcher ) ) ; itSend . setType ( "" ) ; } startActivity ( itSend ) ; } } ) ; } } package bonsai . app ; import android . app . Notification ; import android . app . NotificationManager ; import android . app . PendingIntent ; import android . content . Context ; import android . content . Intent ; import android . widget . Toast ; public class MyReceiver extends android . content . BroadcastReceiver { public static final int APP_ID_NOTIFICATION = ; private static final int NOTIF_ALERTA_ID = ; @ Override public void onReceive ( android . content . Context context , android . content . Intent intent ) { Toast . makeText ( context , "" , Toast . LENGTH_LONG ) . show ( ) ; Notificar ( context ) ; } public void Notificar ( android . content . Context context ) { NotificationManager notManager = ( NotificationManager ) context . getSystemService ( Context . NOTIFICATION_SERVICE ) ; int icono = ; CharSequence textoEstado = "" ; long hora = System . currentTimeMillis ( ) ; Notification notif = new Notification ( icono , textoEstado , hora ) ; Context contexto = context ; CharSequence titulo = "" ; CharSequence descripcion = "" ; Intent notIntent = new Intent ( contexto , TaskActivity . class ) ; PendingIntent contIntent = PendingIntent . getActivity ( contexto , , notIntent , ) ; notif . setLatestEventInfo ( contexto , titulo , descripcion , contIntent ) ; notif . flags |= Notification . FLAG_AUTO_CANCEL ; notManager . notify ( NOTIF_ALERTA_ID , notif ) ; } } package bonsai . app ; import android . app . ListActivity ; import android . content . Intent ; import android . database . Cursor ; import android . view . Menu ; import android . view . MenuInflater ; import android . view . MenuItem ; import android . view . View ; import android . widget . ListView ; import android . widget . SimpleCursorAdapter ; import android . widget . Toast ; public class SelectBonsaiActivity extends ListActivity { private BonsaiDbUtil bonsaidb ; private Cursor bonsaisCursor = null ; @ Override public void onResume ( ) { super . onResume ( ) ; setContentView ( R . layout . selectbonsai ) ; try { bonsaidb = new BonsaiDbUtil ( this ) ; bonsaidb . open ( ) ; bonsaisCursor = bonsaidb . fetchAllBonsais ( ) ; startManagingCursor ( bonsaisCursor ) ; String [ ] from = new String [ ] { BonsaiDbUtil . KEY_NAME } ; int [ ] to = new int [ ] { R . id . bonsairowtext } ; SimpleCursorAdapter bonsais = new SimpleCursorAdapter ( this , R . layout . bonsai_row , bonsaisCursor , from , to ) ; setListAdapter ( bonsais ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; } } @ Override public void onPause ( ) { super . onPause ( ) ; } @ Override protected void onListItemClick ( ListView l , View v , int position , long id ) { super . onListItemClick ( l , v , position , id ) ; AndroidProjectActivity . bonsaiactual = id ; try { bonsaidb . close ( ) ; AndroidProjectActivity tabs = ( AndroidProjectActivity ) this . getParent ( ) ; tabs . changeTab ( ) ; } catch ( Exception e ) { Toast . makeText ( this , "" , Toast . LENGTH_LONG ) . show ( ) ; } } public void goCreate ( View v ) { if ( AndroidProjectActivity . fullversion == true ) { AndroidProjectActivity . iamediting = false ; Intent editAct = new Intent ( ) . setClass ( this , EditBonsaiActivity . class ) ; startActivity ( editAct ) ; } else { Cursor bonsaisCursor = bonsaidb . fetchAllBonsais ( ) ; startManagingCursor ( bonsaisCursor ) ; if ( bonsaisCursor . getCount ( ) >= ) { Toast . makeText ( this , "" , Toast . LENGTH_LONG ) . show ( ) ; AndroidProjectActivity tabs = ( AndroidProjectActivity ) this . getParent ( ) ; tabs . changeTab ( ) ; } else { AndroidProjectActivity . iamediting = false ; Intent editAct = new Intent ( ) . setClass ( this , EditBonsaiActivity . class ) ; startActivity ( editAct ) ; } } } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { MenuInflater inflater = getMenuInflater ( ) ; inflater . inflate ( R . menu . menu , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { switch ( item . getItemId ( ) ) { case R . id . MnuOpc1 : Toast . makeText ( this , "" , Toast . LENGTH_LONG ) . show ( ) ; return true ; default : return super . onOptionsItemSelected ( item ) ; } } } package bonsai . app ; import java . io . IOException ; import java . util . Date ; import java . util . List ; import java . util . Locale ; import android . app . Activity ; import android . app . AlertDialog ; import android . content . Context ; import android . content . DialogInterface ; import android . content . Intent ; import android . database . Cursor ; import android . location . Address ; import android . location . Geocoder ; import android . location . Location ; import android . location . LocationListener ; import android . location . LocationManager ; import android . net . Uri ; import android . os . Bundle ; import android . util . Log ; import android . view . KeyEvent ; import android . view . Menu ; import android . view . MenuInflater ; import android . view . MenuItem ; import android . view . View ; import android . widget . ArrayAdapter ; import android . widget . EditText ; import android . widget . Spinner ; import android . widget . TextView ; import android . widget . Toast ; public class EditBonsaiActivity extends Activity { private BonsaiDbUtil bonsaidb ; private EditText editName ; private Spinner editFamily ; private EditText editAge ; private EditText editHeight ; private TextView photoURLtext ; private Spinner editSituation ; private EditText editpostCode ; private EditText editCountry ; private String name ; private String family ; private long age ; private int height ; private String photo ; private String localization ; private String situation ; private AlertDialog alert ; private AlertDialog deletealert ; private LocationManager locManager ; private LocationListener locListener ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . editbonsai ) ; editName = ( EditText ) findViewById ( R . id . editName ) ; editFamily = ( Spinner ) findViewById ( R . id . familySpinner ) ; ArrayAdapter < CharSequence > adapter = ArrayAdapter . createFromResource ( this , R . array . family_array , android . R . layout . simple_spinner_item ) ; adapter . setDropDownViewResource ( android . R . layout . simple_spinner_dropdown_item ) ; editFamily . setAdapter ( adapter ) ; editAge = ( EditText ) findViewById ( R . id . editAge ) ; editHeight = ( EditText ) findViewById ( R . id . editHeight ) ; photoURLtext = ( TextView ) findViewById ( R . id . photoURLtext ) ; editSituation = ( Spinner ) findViewById ( R . id . spinner1 ) ; ArrayAdapter < CharSequence > adapter2 = ArrayAdapter . createFromResource ( this , R . array . situation_array , android . R . layout . simple_spinner_item ) ; adapter2 . setDropDownViewResource ( android . R . layout . simple_spinner_dropdown_item ) ; editSituation . setAdapter ( adapter2 ) ; editpostCode = ( EditText ) findViewById ( R . id . editPostCode ) ; editCountry = ( EditText ) findViewById ( R . id . editCountry ) ; createCancelAlert ( ) ; createDeleteAlert ( ) ; bonsaidb = new BonsaiDbUtil ( this ) ; bonsaidb . open ( ) ; if ( AndroidProjectActivity . iamediting ) try { Cursor bonsai = bonsaidb . fetchBonsai ( AndroidProjectActivity . bonsaiactual ) ; startManagingCursor ( bonsai ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; editName . setText ( name ) ; long date = new Date ( ) . getTime ( ) / ( * * ) ; age = ( date - bonsai . getLong ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_AGE ) ) ) / ( * ) ; editAge . setText ( String . valueOf ( age ) ) ; height = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_HEIGHT ) ) ; editHeight . setText ( String . valueOf ( height ) ) ; photo = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_PHOTO ) ) ; localization = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LOCALIZATION ) ) ; editCountry . setText ( localization . substring ( , ) ) ; editpostCode . setText ( localization . substring ( , ) ) ; if ( photo . length ( ) < ) { photoURLtext . setText ( photo ) ; } else { photoURLtext . setText ( "" + photo . substring ( ( photo . length ( ) - ) , photo . length ( ) ) ) ; } bonsai . close ( ) ; } catch ( Exception e ) { Toast . makeText ( this , "" + e . toString ( ) , Toast . LENGTH_LONG ) . show ( ) ; } } @ Override public void onStop ( ) { super . onStop ( ) ; bonsaidb . close ( ) ; } public void selectImage ( View v ) { Intent intent = new Intent ( Intent . ACTION_PICK , android . provider . MediaStore . Images . Media . EXTERNAL_CONTENT_URI ) ; startActivityForResult ( intent , ) ; } public void deleteImage ( View v ) { photo = "" ; photoURLtext . setText ( photo ) ; } @ Override protected void onActivityResult ( int requestCode , int resultCode , Intent data ) { super . onActivityResult ( requestCode , resultCode , data ) ; if ( resultCode == RESULT_OK ) { Uri targetUri = data . getData ( ) ; photo = targetUri . toString ( ) ; if ( photo . length ( ) < ) { photoURLtext . setText ( photo ) ; } else { photoURLtext . setText ( "" + photo . substring ( ( photo . length ( ) - ) , photo . length ( ) ) ) ; } } } public void goSave ( View v ) { try { name = editName . getText ( ) . toString ( ) ; family = editFamily . getSelectedItem ( ) . toString ( ) ; age = Long . parseLong ( editAge . getText ( ) . toString ( ) ) ; height = Integer . parseInt ( editHeight . getText ( ) . toString ( ) ) ; situation = editSituation . getSelectedItem ( ) . toString ( ) ; localization = editpostCode . getText ( ) . toString ( ) + "" + editCountry . getText ( ) . toString ( ) ; if ( photoURLtext . getText ( ) . length ( ) < ) photo = "" ; } catch ( Exception e ) { Toast . makeText ( this , e . toString ( ) , Toast . LENGTH_LONG ) . show ( ) ; } if ( ( name . length ( ) > ) && ( family . length ( ) > ) && ( situation . length ( ) > ) && localization . length ( ) > ) { if ( AndroidProjectActivity . iamediting ) { long date = ( new Date ( ) . getTime ( ) ) / ( * * ) ; bonsaidb . updateBonsai ( AndroidProjectActivity . bonsaiactual , name , family , ( date - ( age * * ) ) , height , photo , localization , situation ) ; Toast . makeText ( this , name + "" , Toast . LENGTH_LONG ) . show ( ) ; finish ( ) ; } else { long date = new Date ( ) . getTime ( ) / ( * * ) ; AndroidProjectActivity . bonsaiactual = bonsaidb . createBonsai ( name , family , ( date - ( age * * ) ) , height , photo , , , , localization , situation ) ; Toast . makeText ( this , name + "" , Toast . LENGTH_LONG ) . show ( ) ; finish ( ) ; } } else { Toast . makeText ( this , "" , Toast . LENGTH_LONG ) . show ( ) ; } } public void goDelete ( View v ) { deletealert . show ( ) ; } public void goCancel ( View v ) { alert . show ( ) ; } private void createCancelAlert ( ) { AlertDialog . Builder builder = new AlertDialog . Builder ( this ) ; builder . setMessage ( "" ) . setCancelable ( false ) . setPositiveButton ( "" , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int id ) { EditBonsaiActivity . this . finish ( ) ; } } ) . setNegativeButton ( "" , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int id ) { dialog . cancel ( ) ; } } ) ; alert = builder . create ( ) ; } private void createDeleteAlert ( ) { AlertDialog . Builder builder = new AlertDialog . Builder ( this ) ; builder . setMessage ( "" ) . setCancelable ( false ) . setPositiveButton ( "" , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int id ) { if ( AndroidProjectActivity . iamediting = true ) bonsaidb . deleteBonsai ( AndroidProjectActivity . bonsaiactual ) ; Cursor bonsai = bonsaidb . fetchAllBonsais ( ) ; bonsai . moveToLast ( ) ; try { AndroidProjectActivity . bonsaiactual = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_ROWID ) ) ; } catch ( Exception e ) { AndroidProjectActivity . bonsaiactual = ; } EditBonsaiActivity . this . finish ( ) ; } } ) . setNegativeButton ( "" , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int id ) { dialog . cancel ( ) ; } } ) ; deletealert = builder . create ( ) ; } @ Override public boolean onKeyDown ( int keyCode , KeyEvent event ) { alert . show ( ) ; return false ; } private Location comenzarLocalizacion ( ) { locListener = new LocationListener ( ) { public void onLocationChanged ( Location location ) { } public void onProviderDisabled ( String provider ) { } public void onProviderEnabled ( String provider ) { } public void onStatusChanged ( String provider , int status , Bundle extras ) { Log . i ( "" , "" + status ) ; } } ; locManager = ( LocationManager ) getSystemService ( Context . LOCATION_SERVICE ) ; locManager . requestLocationUpdates ( LocationManager . GPS_PROVIDER , , , locListener ) ; Location loc = locManager . getLastKnownLocation ( LocationManager . GPS_PROVIDER ) ; if ( loc == null ) { locManager . requestLocationUpdates ( LocationManager . NETWORK_PROVIDER , , , locListener ) ; loc = locManager . getLastKnownLocation ( LocationManager . NETWORK_PROVIDER ) ; } return loc ; } public void goMakeCountry ( View v ) { Location loc = comenzarLocalizacion ( ) ; if ( loc == null ) { Toast . makeText ( this , "" , Toast . LENGTH_SHORT ) . show ( ) ; return ; } Geocoder myloc = new Geocoder ( this , Locale . getDefault ( ) ) ; Address ad ; try { List < Address > addresses = myloc . getFromLocation ( loc . getLatitude ( ) , loc . getLongitude ( ) , ) ; ad = addresses . get ( ) ; editCountry . setText ( ad . getCountryCode ( ) ) ; } catch ( IOException e ) { Toast . makeText ( this , "" + e . toString ( ) , Toast . LENGTH_SHORT ) . show ( ) ; } } public void goMakePostCode ( View v ) { Location loc = comenzarLocalizacion ( ) ; if ( loc == null ) { Toast . makeText ( this , "" , Toast . LENGTH_SHORT ) . show ( ) ; return ; } Geocoder myloc = new Geocoder ( this , Locale . getDefault ( ) ) ; Address ad ; try { List < Address > addresses = myloc . getFromLocation ( loc . getLatitude ( ) , loc . getLongitude ( ) , ) ; ad = addresses . get ( ) ; editpostCode . setText ( ad . getPostalCode ( ) ) ; } catch ( Exception e ) { Toast . makeText ( this , "" + e . toString ( ) , Toast . LENGTH_SHORT ) . show ( ) ; } } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { MenuInflater inflater = getMenuInflater ( ) ; inflater . inflate ( R . menu . menu , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { switch ( item . getItemId ( ) ) { case R . id . MnuOpc1 : Toast . makeText ( this , "" , Toast . LENGTH_LONG ) . show ( ) ; return true ; default : return super . onOptionsItemSelected ( item ) ; } } } package bonsai . app ; import android . app . Activity ; import android . content . Intent ; import android . net . Uri ; import android . os . Bundle ; import android . view . View ; import android . widget . Toast ; import android . view . View . OnClickListener ; import android . widget . Button ; public class MoreActivity extends Activity { @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . more ) ; final Button btn = ( Button ) findViewById ( R . id . contactbutton ) ; btn . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View arg0 ) { Intent intent = new Intent ( MoreActivity . this , EnvioMailActivity . class ) ; Bundle bundle = new Bundle ( ) ; bundle . putString ( "" , "" ) ; intent . putExtras ( bundle ) ; startActivity ( intent ) ; } } ) ; } public void goDonate ( View v ) { Uri uri = Uri . parse ( "" ) ; Intent intent = new Intent ( Intent . ACTION_VIEW , uri ) ; startActivity ( intent ) ; } public void doExit ( View v ) { finish ( ) ; } public void buyFullVersion ( View v ) { Toast . makeText ( this , "" , Toast . LENGTH_SHORT ) . show ( ) ; } } package bonsai . app ; import android . app . Activity ; import android . os . Bundle ; public class CalendarActivity extends Activity { @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . calendar ) ; } } package bonsai . app ; import java . util . Date ; import bonsai . app . alarm . NotificationService ; import android . app . ListActivity ; import android . content . Intent ; import android . database . Cursor ; import android . os . Bundle ; import android . view . Menu ; import android . view . MenuInflater ; import android . view . MenuItem ; import android . view . View ; import android . widget . ArrayAdapter ; import android . widget . Button ; import android . widget . TextView ; import android . widget . Toast ; public class TaskActivity extends ListActivity { private BonsaiDbUtil bonsaidb ; private FamilyDbUtil familydb ; private String [ ] tasks ; private int cont ; private Button manageNotifications ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . task ) ; } @ Override public void onResume ( ) { super . onResume ( ) ; manageNotifications = ( Button ) findViewById ( R . id . manageNotifications ) ; bonsaidb = new BonsaiDbUtil ( this ) ; bonsaidb . open ( ) ; familydb = new FamilyDbUtil ( this ) ; familydb . open ( ) ; Cursor bonsaisCursor = bonsaidb . fetchAllBonsais ( ) ; startManagingCursor ( bonsaisCursor ) ; tasks = new String [ bonsaisCursor . getCount ( ) * ] ; cont = ; bonsaisCursor . moveToFirst ( ) ; for ( int i = ; i < bonsaisCursor . getCount ( ) ; i ++ ) { long id = bonsaisCursor . getLong ( bonsaisCursor . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_ROWID ) ) ; Cursor bonsai = bonsaidb . fetchBonsai ( id ) ; startManagingCursor ( bonsai ) ; String possibletask = checkWater ( id ) ; if ( possibletask != null ) { tasks [ cont ] = possibletask ; cont ++ ; } possibletask = checkPode ( id ) ; if ( possibletask != null ) { tasks [ cont ] = possibletask ; cont ++ ; } possibletask = checkTransplant ( id ) ; if ( possibletask != null ) { tasks [ cont ] = possibletask ; cont ++ ; } if ( i < bonsaisCursor . getCount ( ) - ) bonsaisCursor . moveToNext ( ) ; } int cuenta = ; for ( int i = ; i < tasks . length ; i ++ ) { if ( tasks [ i ] != null ) cuenta ++ ; } int situac = ; String [ ] finaltasks = new String [ cuenta ] ; for ( int i = ; i < tasks . length ; i ++ ) { if ( tasks [ i ] != null ) { finaltasks [ situac ] = tasks [ i ] ; situac ++ ; } } setListAdapter ( new ArrayAdapter < String > ( this , R . layout . task_row , finaltasks ) ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { MenuInflater inflater = getMenuInflater ( ) ; inflater . inflate ( R . menu . menu , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { switch ( item . getItemId ( ) ) { case R . id . MnuOpc1 : Toast . makeText ( this , "" , Toast . LENGTH_LONG ) . show ( ) ; return true ; default : return super . onOptionsItemSelected ( item ) ; } } private String checkWater ( long id ) { String name ; String family ; long lastwatered ; long waterfrec ; int height = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; try { Cursor bonsai = bonsaidb . fetchBonsai ( id ) ; startManagingCursor ( bonsai ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lastwatered = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_WATER ) ) ; height = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_HEIGHT ) ) ; Cursor cfamily = familydb . fetchFamilybyName ( family ) ; startManagingCursor ( cfamily ) ; waterfrec = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_WATER_FRECUENCY ) ) ; if ( lastwatered == ) return ( "" + name ) ; else if ( ( hoursTime - lastwatered ) > waterfrec ) return ( "" + name + "" + height / + "" ) ; else return null ; } catch ( Exception e ) { System . out . println ( "" + e . toString ( ) ) ; return null ; } } private String checkTransplant ( long id ) { String name ; String family ; long lasttransplant ; long transplantfrec ; long age = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; try { Cursor bonsai = bonsaidb . fetchBonsai ( id ) ; startManagingCursor ( bonsai ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lasttransplant = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_TRASPLANT ) ) ; long date = new Date ( ) . getTime ( ) / ( * * ) ; age = ( ( date - bonsai . getLong ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_AGE ) ) ) / ( * ) ) ; Cursor cfamily = familydb . fetchFamilybyName ( family ) ; startManagingCursor ( cfamily ) ; transplantfrec = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_TRANSPLANT_FRECUENCY ) ) ; if ( age < ) return null ; else if ( lasttransplant == ) return ( "" + name ) ; else { if ( ( hoursTime - lasttransplant ) > transplantfrec ) return ( "" + name + "" + ( hoursTime - lasttransplant ) / + "" ) ; else return null ; } } catch ( Exception e ) { System . out . println ( "" + e . toString ( ) ) ; return null ; } } private String checkPode ( long id ) { String name ; String family ; long lastpode ; long podefrecuency ; long age = ; long hoursTime = ( new Date ( ) . getTime ( ) ) / ( * * ) ; try { Cursor bonsai = bonsaidb . fetchBonsai ( id ) ; startManagingCursor ( bonsai ) ; name = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_NAME ) ) ; family = bonsai . getString ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_FAMILY ) ) ; lastpode = bonsai . getInt ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_LAST_PODE ) ) ; long date = new Date ( ) . getTime ( ) / ( * * ) ; age = ( ( date - bonsai . getLong ( bonsai . getColumnIndexOrThrow ( BonsaiDbUtil . KEY_AGE ) ) ) / ( * ) ) ; Cursor cfamily = familydb . fetchFamilybyName ( family ) ; startManagingCursor ( cfamily ) ; podefrecuency = cfamily . getInt ( cfamily . getColumnIndexOrThrow ( FamilyDbUtil . KEY_PODE_FRECUENCY ) ) ; if ( lastpode == ) return ( "" + name + "" ) ; else if ( age < ) { if ( hoursTime - lastpode > * ) return ( "" + name + "" ) ; else return null ; } else if ( age >= && ( hoursTime - lastpode > podefrecuency ) ) return ( "" + name + "" ) ; else return null ; } catch ( Exception e ) { System . out . println ( "" + e . toString ( ) ) ; return null ; } } public void stopNotifications ( View v ) { NotificationService . notificado = true ; NotificationService . enabled = false ; Intent miintent = new Intent ( this , NotificationService . class ) ; stopService ( miintent ) ; Toast . makeText ( this , "" , Toast . LENGTH_LONG ) . show ( ) ; manageNotifications . setText ( "" ) ; } } package bonsai . app ; import android . app . Activity ; import android . os . Bundle ; import android . view . View ; public class StartActivity extends Activity { @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . start ) ; } public void goStart ( View v ) { finish ( ) ; } } package logmx . parser ; import java . text . SimpleDateFormat ; import java . util . Date ; import com . lightysoft . logmx . business . ParsedEntry ; import com . lightysoft . logmx . mgr . LogFileParser ; public class GlassfishLogFileParser extends LogFileParser { private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat ( "" ) ; private final static boolean DEBUG = false ; private boolean recordStarted = false ; private StringBuilder buffer = new StringBuilder ( ) ; @ Override protected void parseLine ( String s ) throws Exception { if ( s == null ) { return ; } if ( DEBUG ) { ParsedEntry entry = createNewEntry ( ) ; entry . setMessage ( s ) ; addEntry ( entry ) ; } if ( s . startsWith ( "" ) || s . startsWith ( "" ) ) { recordStarted = true ; buffer . setLength ( ) ; } if ( recordStarted ) { buffer . append ( s ) ; buffer . append ( "" ) ; if ( s . endsWith ( "" ) ) { recordEntry ( buffer . toString ( ) ) ; recordStarted = false ; } } } private void recordEntry ( String s ) throws Exception { String [ ] ss = s . split ( "" ) ; if ( ss . length < ) { return ; } ParsedEntry entry = createNewEntry ( ) ; entry . setDate ( ss [ ] ) ; entry . setEmitter ( ss [ ] ) ; entry . setLevel ( ss [ ] ) ; entry . setMessage ( ss [ ] ) ; entry . setThread ( ss [ ] ) ; addEntry ( entry ) ; } @ Override public Date getRelativeEntryDate ( ParsedEntry entry ) throws Exception { return null ; } @ Override public Date getAbsoluteEntryDate ( ParsedEntry entry ) throws Exception { return DATE_FORMAT . parse ( entry . getDate ( ) ) ; } @ Override public String getParserName ( ) { return "" ; } @ Override public String getSupportedFileType ( ) { return "" ; } } package net . heraan . ui ; public class GUI { public GUI ( ) { throw new UnsupportedOperationException ( "" ) ; } public GUI ( int rounds_per_match ) { throw new UnsupportedOperationException ( "" ) ; } } package net . heraan . ui ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Scanner ; import net . heraan . Game ; import net . heraan . Game . Play ; import net . heraan . Game . Result ; import net . heraan . Player . AI . AI ; import net . heraan . Player . AI . AI_Strategy ; import net . heraan . Player . AI . Personality . Personality_Random ; import net . heraan . Player . Human . Human ; import net . heraan . Player . Player ; import net . heraan . Round ; public class CLI { public CLI ( int rounds_per_game ) throws Exception { this . mind = new Personality_Random ( ) ; this . rounds_per_game = rounds_per_game ; this . current_round = ; this . competitors = new ArrayList < Player > ( ) ; this . load_Humans ( ) ; { Player human = new Human ( "" ) ; this . competitors . add ( human ) ; Player ai = new AI ( "" , mind ) ; this . competitors . add ( ai ) ; this . current_game = new Game ( this . competitors ) ; } System . out . println ( "" + Calendar . getInstance ( ) . getTime ( ) ) ; String quitString = "" ; while ( ( quitString . equalsIgnoreCase ( "" ) == false ) ) { this . gameOverHandler ( ) ; Scanner input = new Scanner ( System . in ) ; System . out . print ( "" ) ; String answer = input . next ( ) ; if ( answer . equalsIgnoreCase ( "" ) ) { quitString = "" ; System . out . println ( "" ) ; } else if ( answer . equalsIgnoreCase ( "" ) ) { System . out . println ( "" ) ; this . print_Help ( ) ; continue ; } else if ( answer . equalsIgnoreCase ( "" ) ) { System . out . println ( "" ) ; this . print_Score ( ) ; continue ; } else if ( answer . equalsIgnoreCase ( "" ) ) { this . play_Rock ( ) ; continue ; } else if ( answer . equalsIgnoreCase ( "" ) ) { this . play_Paper ( ) ; continue ; } else if ( answer . equalsIgnoreCase ( "" ) ) { this . play_Scissors ( ) ; continue ; } else { System . out . println ( "" ) ; continue ; } input . close ( ) ; } } private void play_Rock ( ) { System . out . println ( "" + this . current_round + "" ) ; this . current_game . set_Play ( null , Play . ROCK ) ; Play ai_play = ( ( AI ) this . competitors . get ( ) ) . play ( ) ; this . current_game . set_Play ( null , ai_play ) ; System . out . println ( "" + ai_play + "" + this . current_round + "" ) ; this . current_round ++ ; } private void play_Paper ( ) { System . out . println ( "" + this . current_round + "" ) ; this . current_game . set_Play ( null , Play . PAPER ) ; Play ai_play = ( ( AI ) this . competitors . get ( ) ) . play ( ) ; this . current_game . set_Play ( null , ai_play ) ; System . out . println ( "" + ai_play + "" + this . current_round + "" ) ; this . current_round ++ ; } private void play_Scissors ( ) { System . out . println ( "" + this . current_round + "" ) ; this . current_game . set_Play ( null , Play . SCISSORS ) ; Play ai_play = ( ( AI ) this . competitors . get ( ) ) . play ( ) ; this . current_game . set_Play ( null , ai_play ) ; System . out . println ( "" + ai_play + "" + this . current_round + "" ) ; this . current_round ++ ; } private void gameOverHandler ( ) { if ( ( this . current_round > this . rounds_per_game ) && ( this . current_game . get_CurrentRound ( ) . is_RoundComplete ( ) == true ) ) { this . competitors . get ( ) . record_Game ( current_game ) ; if ( this . current_game . get_PlayerResult ( this . competitors . get ( ) ) == Result . TIE ) { System . out . println ( "" ) ; } else if ( this . current_game . get_PlayerResult ( this . competitors . get ( ) ) == Result . WIN ) { System . out . println ( "" ) ; } else { System . out . println ( "" ) ; } this . current_game = new Game ( this . competitors ) ; this . current_round = ; } } private void print_Score ( ) { int game_wins = ; int game_ties = ; int game_loses = ; int round_wins = ; int round_ties = ; int round_loses = ; for ( Game game : this . competitors . get ( ) . get_GameHistory ( ) ) { if ( ( game . is_Tie ( ) == true ) ) { game_ties ++ ; } else if ( ( game . is_Winner ( this . competitors . get ( ) ) == true ) ) { game_wins ++ ; } else { game_loses ++ ; } for ( Round round : game . get_Rounds ( ) ) { if ( ( round . is_Tie ( ) ) ) { round_ties ++ ; } else if ( ( round . is_Winner ( this . competitors . get ( ) ) == true ) ) { round_wins ++ ; } else { round_loses ++ ; } } } System . out . print ( "" + game_wins ) ; System . out . print ( "" + game_ties ) ; System . out . print ( "" + game_loses ) ; System . out . print ( "" + round_wins ) ; System . out . print ( "" + round_ties ) ; System . out . print ( "" + round_loses + "" ) ; } private void load_Humans ( ) { this . humans_list = new ArrayList < Player > ( ) ; this . humans_list . trimToSize ( ) ; } private void print_Help ( ) { System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; System . out . print ( "" ) ; } private AI_Strategy mind ; private ArrayList < Player > competitors ; private ArrayList < Player > humans_list ; private Game current_game ; private int rounds_per_game ; private int current_round ; } package net . heraan ; import net . heraan . ui . CLI ; public class Main { public static void main ( String [ ] args ) throws Exception { if ( args . length > ) { int rounds_per_match = Integer . parseInt ( args [ ] ) ; CLI ui = new CLI ( rounds_per_match - ) ; } else { CLI ui = new CLI ( ) ; } int version = ; if ( version == ) { if ( args . length > ) { for ( int arg_number = ; arg_number >= ; arg_number ++ ) { if ( args [ ( arg_number - ) ] . equalsIgnoreCase ( "" ) ) { } else if ( args [ ( arg_number - ) ] . equalsIgnoreCase ( "" ) ) { } else { } } } else { } } } } package net . heraan ; import java . util . ArrayList ; import net . heraan . Game . Play ; import net . heraan . Game . Result ; import net . heraan . Player . Player ; public class Round { public Round ( ) { players = new ArrayList < Player > ( ) ; plays = new ArrayList < Play > ( ) ; } public Round ( ArrayList < Player > players ) { this . set_Players ( players ) ; plays = new ArrayList < Play > ( ) ; } public Round ( ArrayList < Player > players , ArrayList < Play > plays ) { this . set_Plays ( players , plays ) ; } public void set_Play ( Player player , Play play ) { this . plays . add ( play ) ; } public void set_Plays ( ArrayList < Player > players , ArrayList < Play > plays ) { this . players = players ; this . plays = plays ; } public void set_Players ( ArrayList < Player > players ) { this . players = players ; } public void add_Player ( Player player ) { this . players . add ( player ) ; } public void add_Players ( ArrayList < Player > players ) { throw new UnsupportedOperationException ( "" ) ; } public Play get_Play ( Player player ) { if ( ( this . players . get ( ) == player ) ) { return ( this . plays . get ( ) ) ; } else { return ( this . plays . get ( ) ) ; } } public ArrayList < Player > get_Players ( ) { return ( this . players ) ; } public ArrayList < Player > get_HasPlayedList ( ) { throw new UnsupportedOperationException ( "" ) ; } public ArrayList < Player > get_HasNotPlayedList ( ) { throw new UnsupportedOperationException ( "" ) ; } public Result get_PlayerResult ( Player player ) { if ( ( this . is_RoundComplete ( ) == false ) ) { return ( null ) ; } if ( ( this . is_Tie ( ) == true ) ) { return ( Result . TIE ) ; } else if ( ( this . get_Winner ( ) == player ) ) { return ( Result . WIN ) ; } else { return ( Result . LOSE ) ; } } public Player get_Winner ( ) { if ( ( this . is_RoundComplete ( ) == false ) ) { return ( null ) ; } if ( ( this . plays . get ( ) == Play . ROCK ) && ( this . plays . get ( ) == Play . SCISSORS ) ) { return ( this . players . get ( ) ) ; } else if ( ( this . plays . get ( ) == Play . PAPER ) && ( this . plays . get ( ) == Play . ROCK ) ) { return ( this . players . get ( ) ) ; } else if ( ( this . plays . get ( ) == Play . SCISSORS ) && ( this . plays . get ( ) == Play . PAPER ) ) { return ( this . players . get ( ) ) ; } else if ( ( this . plays . get ( ) == Play . ROCK ) && ( this . plays . get ( ) == Play . SCISSORS ) ) { return ( this . players . get ( ) ) ; } else if ( ( this . plays . get ( ) == Play . PAPER ) && ( this . plays . get ( ) == Play . ROCK ) ) { return ( this . players . get ( ) ) ; } else if ( ( this . plays . get ( ) == Play . SCISSORS ) && ( this . plays . get ( ) == Play . PAPER ) ) { return ( this . players . get ( ) ) ; } else { return ( null ) ; } } public Player get_Loser ( ) { throw new UnsupportedOperationException ( "" ) ; } public boolean is_RoundComplete ( ) { if ( ( this . plays != null ) && ( this . plays . size ( ) == ) ) { return ( true ) ; } else { return ( false ) ; } } public boolean has_Played ( Player player ) { throw new UnsupportedOperationException ( "" ) ; } public boolean is_Winner ( Player player ) { if ( ( this . get_Winner ( ) == player ) ) { return ( true ) ; } else { return ( false ) ; } } public boolean is_Loser ( Player player ) { throw new UnsupportedOperationException ( "" ) ; } public boolean is_Tie ( ) { if ( ( this . is_RoundComplete ( ) == false ) ) { return ( false ) ; } else if ( ( this . plays . get ( ) == this . plays . get ( ) ) ) { return ( true ) ; } else { return ( false ) ; } } private ArrayList < Player > players ; private ArrayList < Play > plays ; } package net . heraan . Player . Human ; import net . heraan . Player . Player ; public class Human extends Player { public Human ( ) { } public Human ( String nickname ) { super . set_Nickname ( nickname ) ; } public Human ( String nickname , String first_name , String last_name ) { super . set_Nickname ( nickname ) ; this . set_FirstName ( first_name ) ; this . set_LastName ( last_name ) ; } public void set_FirstName ( String first_name ) { this . human_first_name = first_name ; } public void set_LastName ( String last_name ) { this . human_last_name = last_name ; } public String get_FirstName ( ) { return ( this . human_first_name ) ; } public String get_LastName ( ) { return ( this . human_last_name ) ; } private String human_first_name ; private String human_last_name ; public void save ( ) { } @ Override public void import_Player ( ) { throw new UnsupportedOperationException ( "" ) ; } @ Override public void export_Player ( ) { throw new UnsupportedOperationException ( "" ) ; } } package net . heraan . Player . AI . Personality ; import java . util . Random ; import net . heraan . Game . Play ; import net . heraan . Player . AI . AI_Strategy ; public class Personality_Random implements AI_Strategy { @ Override public Play calculate_play ( ) { int unique_plays = Play . values ( ) . length ; Random play_chooser = new Random ( ) ; int play_integer = play_chooser . nextInt ( unique_plays ) ; if ( ( play_integer == ) ) { return ( Play . PAPER ) ; } else if ( ( play_integer == ) ) { return ( Play . ROCK ) ; } else { return ( Play . SCISSORS ) ; } } } package net . heraan . Player . AI ; import net . heraan . Game . Play ; import net . heraan . Player . Player ; public final class AI extends Player { public AI ( ) { } public AI ( String nickname ) { super . set_Nickname ( nickname ) ; } public AI ( AI_Strategy mind ) { this . set_Strategy ( mind ) ; } public AI ( String nickname , AI_Strategy mind ) { super . set_Nickname ( nickname ) ; this . set_Strategy ( mind ) ; } public Play play ( ) { return ( mind . calculate_play ( ) ) ; } public void set_Strategy ( AI_Strategy mind ) { this . mind = mind ; } public AI_Strategy get_Strategy ( ) { return ( this . mind ) ; } private AI_Strategy mind = null ; @ Override public void import_Player ( ) { throw new UnsupportedOperationException ( "" ) ; } @ Override public void export_Player ( ) { throw new UnsupportedOperationException ( "" ) ; } } package net . heraan . Player . AI ; import net . heraan . Game . Play ; public interface AI_Strategy { public abstract Play calculate_play ( ) ; } package net . heraan . Player ; import java . util . ArrayList ; import net . heraan . Game ; public abstract class Player { public Player ( ) { this . game_history = new ArrayList < Game > ( ) ; } public void record_Game ( Game game ) { this . game_history . add ( game ) ; } public ArrayList < Game > get_GameHistory ( ) { return ( game_history ) ; } public String get_Nickname ( ) { return ( this . player_nickname ) ; } public void set_Nickname ( String nickname ) { this . player_nickname = nickname ; } private String player_nickname ; private ArrayList < Game > game_history ; public abstract void import_Player ( ) ; public abstract void export_Player ( ) ; private String player_ID ; } package net . heraan ; import java . util . ArrayList ; import net . heraan . Player . Player ; public class Game { public Game ( ) { this . players = new ArrayList < Player > ( ) ; this . rounds = new ArrayList < Round > ( ) ; this . rounds . add ( new Round ( this . players ) ) ; } public Game ( ArrayList < Player > players ) { this . players = players ; this . rounds = new ArrayList < Round > ( ) ; this . rounds . add ( new Round ( this . players ) ) ; } public void set_Play ( Player player , Play play ) { if ( ( this . get_CurrentRound ( ) . is_RoundComplete ( ) == true ) ) { this . rounds . add ( new Round ( this . players ) ) ; this . set_Play ( player , play ) ; } else { this . get_CurrentRound ( ) . set_Play ( player , play ) ; } } public ArrayList < Player > get_Players ( ) { return ( this . players ) ; } public ArrayList < Round > get_Rounds ( ) { return ( this . rounds ) ; } public int get_CurrentRoundNumber ( ) { return ( this . rounds . size ( ) ) ; } public Round get_CurrentRound ( ) { return ( this . rounds . get ( this . get_CurrentRoundNumber ( ) - ) ) ; } public Result get_PlayerResult ( Player player ) { if ( ( this . is_Tie ( ) ) ) { return ( Result . TIE ) ; } else if ( ( this . is_Winner ( player ) == true ) ) { return ( Result . WIN ) ; } else { return ( Result . LOSE ) ; } } public Player get_Winner ( ) { int wins = ; int ties = ; int loses = ; for ( Round round : this . rounds ) { if ( ( round . is_Tie ( ) == true ) ) { ties ++ ; } else if ( ( round . is_Winner ( this . players . get ( ) ) == true ) ) { wins ++ ; } else { loses ++ ; } } if ( ( wins == loses ) ) { return ( null ) ; } else if ( ( wins > loses ) ) { return ( this . players . get ( ) ) ; } else { return ( this . players . get ( ) ) ; } } public Player get_Loser ( ) { throw new UnsupportedOperationException ( "" ) ; } public boolean is_Winner ( Player player ) { if ( ( this . get_Winner ( ) == player ) ) { return ( true ) ; } else { return ( false ) ; } } public boolean is_Loser ( Player player ) { throw new UnsupportedOperationException ( "" ) ; } public boolean is_Tie ( ) { int wins = ; int ties = ; int loses = ; for ( Round round : this . rounds ) { if ( ( round . is_Tie ( ) == true ) ) { ties ++ ; } else if ( ( round . is_Winner ( this . players . get ( ) ) == true ) ) { wins ++ ; } else { loses ++ ; } } if ( ( wins == loses ) ) { return ( true ) ; } else { return ( false ) ; } } public enum Result { WIN , LOSE , TIE } public enum Play { ROCK , PAPER , SCISSORS } private ArrayList < Player > players ; private ArrayList < Round > rounds ; } package handson . springbatch ; import static org . junit . Assert . assertEquals ; import org . junit . Assert ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . springframework . batch . core . BatchStatus ; import org . springframework . batch . core . Job ; import org . springframework . batch . core . JobExecution ; import org . springframework . batch . core . JobParameters ; import org . springframework . batch . core . StepExecution ; import org . springframework . batch . core . launch . JobLauncher ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . test . context . ContextConfiguration ; import org . springframework . test . context . junit4 . SpringJUnit4ClassRunner ; @ RunWith ( SpringJUnit4ClassRunner . class ) @ ContextConfiguration public class HelloWorldJobTest { @ Autowired private Job job ; @ Autowired private JobLauncher jobLauncher ; @ Test public void helloworldTasklet ( ) throws Exception { JobExecution jobExecution = jobLauncher . run ( job , new JobParameters ( ) ) ; Assert . assertEquals ( BatchStatus . COMPLETED , jobExecution . getStatus ( ) ) ; StepExecution stepExecution = jobExecution . getStepExecutions ( ) . iterator ( ) . next ( ) ; assertEquals ( , stepExecution . getReadCount ( ) ) ; assertEquals ( , stepExecution . getSkipCount ( ) ) ; assertEquals ( , stepExecution . getFilterCount ( ) ) ; assertEquals ( , stepExecution . getWriteCount ( ) ) ; } } package handson . springbatch ; import java . util . List ; import org . springframework . batch . item . ItemReader ; import org . springframework . batch . item . NonTransientResourceException ; import org . springframework . batch . item . ParseException ; import org . springframework . batch . item . UnexpectedInputException ; import org . springframework . stereotype . Component ; import com . google . common . collect . Lists ; @ Component public class HelloWorldReader implements ItemReader < String > { private List < String > names = Lists . newArrayList ( "" , "" , "" , "" , "" , "" , "" ) ; @ Override public String read ( ) throws Exception , UnexpectedInputException , ParseException , NonTransientResourceException { throw new RuntimeException ( "" ) ; } } package handson . springbatch ; import org . springframework . batch . item . ItemProcessor ; import org . springframework . stereotype . Component ; @ Component public class HelloWorldProcessor implements ItemProcessor < String , String > { @ Override public String process ( String item ) throws Exception { throw new RuntimeException ( "" ) ; } } package handson . springbatch ; import java . util . List ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . springframework . batch . item . ItemWriter ; import org . springframework . stereotype . Component ; @ Component public class HelloWorldWriter implements ItemWriter < String > { Logger logger = LoggerFactory . getLogger ( HelloWorldWriter . class ) ; @ Override public void write ( List < ? extends String > items ) throws Exception { throw new RuntimeException ( "" ) ; } } package handson . springbatch ; import org . junit . Assert ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . springframework . batch . core . BatchStatus ; import org . springframework . batch . core . Job ; import org . springframework . batch . core . JobExecution ; import org . springframework . batch . core . JobParameters ; import org . springframework . batch . core . launch . JobLauncher ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . test . context . ContextConfiguration ; import org . springframework . test . context . junit4 . SpringJUnit4ClassRunner ; @ RunWith ( SpringJUnit4ClassRunner . class ) @ ContextConfiguration public class HelloWorldJobTest { @ Autowired private Job job ; @ Autowired private JobLauncher jobLauncher ; @ Test public void helloworldTasklet ( ) throws Exception { JobExecution exec = jobLauncher . run ( job , new JobParameters ( ) ) ; Assert . assertEquals ( BatchStatus . COMPLETED , exec . getStatus ( ) ) ; } } package handson . springbatch ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . springframework . batch . core . StepContribution ; import org . springframework . batch . core . scope . context . ChunkContext ; import org . springframework . batch . core . step . tasklet . Tasklet ; import org . springframework . batch . repeat . RepeatStatus ; import org . springframework . stereotype . Component ; @ Component public class HelloWorldTasklet implements Tasklet { Logger logger = LoggerFactory . getLogger ( HelloWorldTasklet . class ) ; @ Override public RepeatStatus execute ( StepContribution contribution , ChunkContext chunkContext ) throws Exception { throw new RuntimeException ( "" ) ; } } package handson . springbatch . tasklet ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . springframework . batch . core . StepContribution ; import org . springframework . batch . core . scope . context . ChunkContext ; import org . springframework . batch . core . step . tasklet . Tasklet ; import org . springframework . batch . repeat . RepeatStatus ; public class GenderTasklet implements Tasklet { Logger logger = LoggerFactory . getLogger ( GenderTasklet . class ) ; @ Override public RepeatStatus execute ( StepContribution contribution , ChunkContext chunkContext ) throws Exception { return RepeatStatus . FINISHED ; } } package handson . springbatch . writer ; import java . util . List ; import org . springframework . batch . item . ItemWriter ; public class NoopItemWriter implements ItemWriter < Object > { @ Override public void write ( List < ? extends Object > items ) throws Exception { } } package handson . springbatch . reader ; import org . springframework . batch . item . ItemReader ; import org . springframework . batch . item . NonTransientResourceException ; import org . springframework . batch . item . ParseException ; import org . springframework . batch . item . UnexpectedInputException ; public class NoopItemReader implements ItemReader < Object > { @ Override public Object read ( ) throws Exception , UnexpectedInputException , ParseException , NonTransientResourceException { return null ; } } package handson . springbatch . reader ; import handson . springbatch . model . Employee ; import java . text . SimpleDateFormat ; import java . util . Date ; import org . springframework . batch . item . file . mapping . BeanWrapperFieldSetMapper ; import org . springframework . beans . propertyeditors . CustomDateEditor ; import org . springframework . validation . DataBinder ; public class EmployeeFieldSetMapper extends BeanWrapperFieldSetMapper < Employee > { @ Override protected void initBinder ( DataBinder binder ) { CustomDateEditor editor = new CustomDateEditor ( new SimpleDateFormat ( "" ) , true ) ; binder . registerCustomEditor ( Date . class , editor ) ; } } package handson . springbatch . model ; import java . util . Date ; public class Employee { private int id ; private Date birthDate ; private String firstName ; private String lastName ; private String gender ; private Date hireDate ; public int getId ( ) { return id ; } public void setId ( int id ) { this . id = id ; } public Date getBirthDate ( ) { return birthDate ; } public void setBirthDate ( Date birthDate ) { this . birthDate = birthDate ; } public String getFirstName ( ) { return firstName ; } public void setFirstName ( String firstName ) { this . firstName = firstName ; } public String getLastName ( ) { return lastName ; } public void setLastName ( String lastName ) { this . lastName = lastName ; } public String getGender ( ) { return gender ; } public void setGender ( String gender ) { this . gender = gender ; } public Date getHireDate ( ) { return hireDate ; } public void setHireDate ( Date hireDate ) { this . hireDate = hireDate ; } } package handson . springbatch . model ; import java . util . Date ; public class Salary { private String id ; private int employeeId ; private int amount ; private Date fromDate ; private Date toDate ; public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public int getEmployeeId ( ) { return employeeId ; } public void setEmployeeId ( int employeeId ) { this . employeeId = employeeId ; } public int getAmount ( ) { return amount ; } public void setAmount ( int amount ) { this . amount = amount ; } public Date getFromDate ( ) { return fromDate ; } public void setFromDate ( Date fromDate ) { this . fromDate = fromDate ; } public Date getToDate ( ) { return toDate ; } public void setToDate ( Date toDate ) { this . toDate = toDate ; } } package handson . springbatch ; import static org . junit . Assert . assertEquals ; import org . junit . Assert ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . springframework . batch . core . BatchStatus ; import org . springframework . batch . core . JobExecution ; import org . springframework . batch . core . JobParameter ; import org . springframework . batch . core . JobParameters ; import org . springframework . batch . core . JobParametersBuilder ; import org . springframework . batch . core . StepExecution ; import org . springframework . batch . test . JobLauncherTestUtils ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . jdbc . core . JdbcTemplate ; import org . springframework . test . annotation . DirtiesContext ; import org . springframework . test . annotation . DirtiesContext . ClassMode ; import org . springframework . test . context . ContextConfiguration ; import org . springframework . test . context . junit4 . SpringJUnit4ClassRunner ; @ RunWith ( SpringJUnit4ClassRunner . class ) @ ContextConfiguration @ DirtiesContext ( classMode = ClassMode . AFTER_EACH_TEST_METHOD ) public class EmployeeStep2Test { @ Autowired private JobLauncherTestUtils jobLauncherTestUtils ; @ Autowired private JdbcTemplate jdbcTemplate ; @ Test public void read_sample_salaries ( ) throws Exception { JobParameters jobParameters = new JobParametersBuilder ( ) . addParameter ( "" , new JobParameter ( "" ) ) . toJobParameters ( ) ; JobExecution jobExecution = jobLauncherTestUtils . launchStep ( "" , jobParameters ) ; Assert . assertEquals ( BatchStatus . COMPLETED , jobExecution . getStatus ( ) ) ; StepExecution stepExecution = jobExecution . getStepExecutions ( ) . iterator ( ) . next ( ) ; assertEquals ( , stepExecution . getReadCount ( ) ) ; assertEquals ( , stepExecution . getSkipCount ( ) ) ; assertEquals ( , stepExecution . getFilterCount ( ) ) ; assertEquals ( , stepExecution . getWriteCount ( ) ) ; assertEquals ( , jdbcTemplate . queryForInt ( "" ) ) ; } } package handson . springbatch ; import static org . junit . Assert . assertEquals ; import java . util . Iterator ; import org . junit . Assert ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . springframework . batch . core . BatchStatus ; import org . springframework . batch . core . JobExecution ; import org . springframework . batch . core . JobParameter ; import org . springframework . batch . core . JobParameters ; import org . springframework . batch . core . JobParametersBuilder ; import org . springframework . batch . core . StepExecution ; import org . springframework . batch . test . JobLauncherTestUtils ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . jdbc . core . JdbcTemplate ; import org . springframework . test . annotation . DirtiesContext ; import org . springframework . test . annotation . DirtiesContext . ClassMode ; import org . springframework . test . context . ContextConfiguration ; import org . springframework . test . context . junit4 . SpringJUnit4ClassRunner ; @ RunWith ( SpringJUnit4ClassRunner . class ) @ ContextConfiguration @ DirtiesContext ( classMode = ClassMode . AFTER_EACH_TEST_METHOD ) public class EmployeeJobTest { @ Autowired private JobLauncherTestUtils jobLauncherTestUtils ; @ Autowired private JdbcTemplate jdbcTemplate ; @ Test public void test_all_job_but_only_step1_and_step3 ( ) throws Exception { JobParameters jobParameters = new JobParametersBuilder ( ) . addParameter ( "" , new JobParameter ( "" ) ) . addParameter ( "" , new JobParameter ( "" ) ) . toJobParameters ( ) ; JobExecution jobExecution = jobLauncherTestUtils . launchJob ( jobParameters ) ; Assert . assertEquals ( BatchStatus . COMPLETED , jobExecution . getStatus ( ) ) ; Iterator < StepExecution > iterator = jobExecution . getStepExecutions ( ) . iterator ( ) ; StepExecution stepExecution = iterator . next ( ) ; assertEquals ( , stepExecution . getReadCount ( ) ) ; assertEquals ( , stepExecution . getSkipCount ( ) ) ; assertEquals ( , stepExecution . getFilterCount ( ) ) ; assertEquals ( , stepExecution . getWriteCount ( ) ) ; assertEquals ( , jdbcTemplate . queryForInt ( "" ) ) ; stepExecution = iterator . next ( ) ; assertEquals ( , stepExecution . getReadCount ( ) ) ; assertEquals ( , stepExecution . getSkipCount ( ) ) ; assertEquals ( , stepExecution . getFilterCount ( ) ) ; assertEquals ( , stepExecution . getWriteCount ( ) ) ; assertEquals ( , jdbcTemplate . queryForInt ( "" ) ) ; } @ Test public void test_all_job ( ) throws Exception { JobParameters jobParameters = new JobParametersBuilder ( ) . addParameter ( "" , new JobParameter ( "" ) ) . addParameter ( "" , new JobParameter ( "" ) ) . toJobParameters ( ) ; JobExecution jobExecution = jobLauncherTestUtils . launchJob ( jobParameters ) ; Assert . assertEquals ( BatchStatus . COMPLETED , jobExecution . getStatus ( ) ) ; assertEquals ( , jobExecution . getExecutionContext ( ) . get ( "" ) ) ; assertEquals ( , jobExecution . getExecutionContext ( ) . get ( "" ) ) ; } } package handson . springbatch ; import static org . junit . Assert . assertEquals ; import org . junit . Assert ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . springframework . batch . core . BatchStatus ; import org . springframework . batch . core . JobExecution ; import org . springframework . batch . core . JobParameter ; import org . springframework . batch . core . JobParameters ; import org . springframework . batch . core . JobParametersBuilder ; import org . springframework . batch . core . StepExecution ; import org . springframework . batch . test . JobLauncherTestUtils ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . jdbc . core . JdbcTemplate ; import org . springframework . test . annotation . DirtiesContext ; import org . springframework . test . annotation . DirtiesContext . ClassMode ; import org . springframework . test . context . ContextConfiguration ; import org . springframework . test . context . junit4 . SpringJUnit4ClassRunner ; @ RunWith ( SpringJUnit4ClassRunner . class ) @ ContextConfiguration @ DirtiesContext ( classMode = ClassMode . AFTER_EACH_TEST_METHOD ) public class EmployeeStep1Test { @ Autowired private JobLauncherTestUtils jobLauncherTestUtils ; @ Autowired private JdbcTemplate jdbcTemplate ; @ Test public void read_sample_employees ( ) throws Exception { JobParameters jobParameters = new JobParametersBuilder ( ) . addParameter ( "" , new JobParameter ( "" ) ) . toJobParameters ( ) ; JobExecution jobExecution = jobLauncherTestUtils . launchStep ( "" , jobParameters ) ; Assert . assertEquals ( BatchStatus . COMPLETED , jobExecution . getStatus ( ) ) ; StepExecution stepExecution = jobExecution . getStepExecutions ( ) . iterator ( ) . next ( ) ; assertEquals ( , stepExecution . getReadCount ( ) ) ; assertEquals ( , stepExecution . getSkipCount ( ) ) ; assertEquals ( , stepExecution . getFilterCount ( ) ) ; assertEquals ( , stepExecution . getWriteCount ( ) ) ; assertEquals ( , jdbcTemplate . queryForInt ( "" ) ) ; } @ Test public void read_skip_employees ( ) throws Exception { JobParameters jobParameters = new JobParametersBuilder ( ) . addParameter ( "" , new JobParameter ( "" ) ) . toJobParameters ( ) ; JobExecution jobExecution = jobLauncherTestUtils . launchStep ( "" , jobParameters ) ; Assert . assertEquals ( BatchStatus . COMPLETED , jobExecution . getStatus ( ) ) ; StepExecution stepExecution = jobExecution . getStepExecutions ( ) . iterator ( ) . next ( ) ; assertEquals ( , stepExecution . getReadCount ( ) ) ; assertEquals ( , stepExecution . getSkipCount ( ) ) ; assertEquals ( , stepExecution . getFilterCount ( ) ) ; assertEquals ( , stepExecution . getWriteCount ( ) ) ; assertEquals ( , jdbcTemplate . queryForInt ( "" ) ) ; } } package org . springframework . samples . petclinic . web ; import java . util . ArrayList ; import java . util . Date ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . sun . syndication . feed . atom . Entry ; import com . sun . syndication . feed . atom . Feed ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertNotNull ; import org . joda . time . LocalDate ; import org . junit . Before ; import org . junit . Test ; import org . springframework . samples . petclinic . Pet ; import org . springframework . samples . petclinic . PetType ; import org . springframework . samples . petclinic . Visit ; public class VisitsAtomViewTest { private VisitsAtomView visitView ; private Map < String , Object > model ; private Feed feed ; @ Before public void setUp ( ) { visitView = new VisitsAtomView ( ) ; PetType dog = new PetType ( ) ; dog . setName ( "" ) ; Pet bello = new Pet ( ) ; bello . setName ( "" ) ; bello . setType ( dog ) ; Visit belloVisit = new Visit ( ) ; belloVisit . setPet ( bello ) ; belloVisit . setDate ( new LocalDate ( , , ) ) ; belloVisit . setDescription ( "" ) ; Pet wodan = new Pet ( ) ; wodan . setName ( "" ) ; wodan . setType ( dog ) ; Visit wodanVisit = new Visit ( ) ; wodanVisit . setPet ( wodan ) ; wodanVisit . setDate ( new LocalDate ( , , ) ) ; wodanVisit . setDescription ( "" ) ; List < Visit > visits = new ArrayList < Visit > ( ) ; visits . add ( belloVisit ) ; visits . add ( wodanVisit ) ; model = new HashMap < String , Object > ( ) ; model . put ( "" , visits ) ; feed = new Feed ( ) ; } @ Test public void buildFeedMetadata ( ) { visitView . buildFeedMetadata ( model , feed , null ) ; assertNotNull ( "" , feed . getId ( ) ) ; assertNotNull ( "" , feed . getTitle ( ) ) ; assertEquals ( "" , new LocalDate ( , , ) . toDateTimeAtStartOfDay ( ) . toDate ( ) , feed . getUpdated ( ) ) ; } @ Test public void buildFeedEntries ( ) throws Exception { List < Entry > entries = visitView . buildFeedEntries ( model , null , null ) ; assertEquals ( "" , , entries . size ( ) ) ; } } package org . springframework . samples . petclinic . jpa ; import java . util . List ; import org . springframework . samples . petclinic . aspects . UsageLogAspect ; public class HibernateEntityManagerClinicTests extends AbstractJpaClinicTests { private UsageLogAspect usageLogAspect ; @ Override protected String [ ] getConfigPaths ( ) { return new String [ ] { "" , "" } ; } public void setUsageLogAspect ( UsageLogAspect usageLogAspect ) { this . usageLogAspect = usageLogAspect ; } public void testUsageLogAspectIsInvoked ( ) { String name1 = "" ; String name2 = "" ; String name3 = "" ; assertTrue ( this . clinic . findOwners ( name1 ) . isEmpty ( ) ) ; assertTrue ( this . clinic . findOwners ( name2 ) . isEmpty ( ) ) ; List < String > namesRequested = this . usageLogAspect . getNamesRequested ( ) ; assertTrue ( namesRequested . contains ( name1 ) ) ; assertTrue ( namesRequested . contains ( name2 ) ) ; assertFalse ( namesRequested . contains ( name3 ) ) ; } } package org . springframework . samples . petclinic . jpa ; import java . util . Collection ; import javax . persistence . EntityManager ; import org . joda . time . LocalDate ; import org . springframework . jdbc . core . simple . SimpleJdbcTemplate ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Owner ; import org . springframework . samples . petclinic . Pet ; import org . springframework . samples . petclinic . PetType ; import org . springframework . samples . petclinic . Vet ; import org . springframework . samples . petclinic . Visit ; import org . springframework . samples . petclinic . util . EntityUtils ; import org . springframework . test . annotation . ExpectedException ; import org . springframework . test . jpa . AbstractJpaTests ; public abstract class AbstractJpaClinicTests extends AbstractJpaTests { protected Clinic clinic ; public void setClinic ( Clinic clinic ) { this . clinic = clinic ; } @ ExpectedException ( IllegalArgumentException . class ) public void testBogusJpql ( ) { this . sharedEntityManager . createQuery ( "" ) . executeUpdate ( ) ; } public void testApplicationManaged ( ) { EntityManager appManaged = this . entityManagerFactory . createEntityManager ( ) ; appManaged . joinTransaction ( ) ; } public void testGetVets ( ) { Collection < Vet > vets = this . clinic . getVets ( ) ; assertEquals ( "" , super . countRowsInTable ( "" ) , vets . size ( ) ) ; Vet v1 = EntityUtils . getById ( vets , Vet . class , ) ; assertEquals ( "" , v1 . getLastName ( ) ) ; assertEquals ( , v1 . getNrOfSpecialties ( ) ) ; assertEquals ( "" , ( v1 . getSpecialties ( ) . get ( ) ) . getName ( ) ) ; Vet v2 = EntityUtils . getById ( vets , Vet . class , ) ; assertEquals ( "" , v2 . getLastName ( ) ) ; assertEquals ( , v2 . getNrOfSpecialties ( ) ) ; assertEquals ( "" , ( v2 . getSpecialties ( ) . get ( ) ) . getName ( ) ) ; assertEquals ( "" , ( v2 . getSpecialties ( ) . get ( ) ) . getName ( ) ) ; } public void testGetPetTypes ( ) { Collection < PetType > petTypes = this . clinic . getPetTypes ( ) ; assertEquals ( "" , super . countRowsInTable ( "" ) , petTypes . size ( ) ) ; PetType t1 = EntityUtils . getById ( petTypes , PetType . class , ) ; assertEquals ( "" , t1 . getName ( ) ) ; PetType t4 = EntityUtils . getById ( petTypes , PetType . class , ) ; assertEquals ( "" , t4 . getName ( ) ) ; } public void testFindOwners ( ) { Collection < Owner > owners = this . clinic . findOwners ( "" ) ; assertEquals ( , owners . size ( ) ) ; owners = this . clinic . findOwners ( "" ) ; assertEquals ( , owners . size ( ) ) ; } public void testLoadOwner ( ) { Owner o1 = this . clinic . loadOwner ( ) ; assertTrue ( o1 . getLastName ( ) . startsWith ( "" ) ) ; Owner o10 = this . clinic . loadOwner ( ) ; assertEquals ( "" , o10 . getFirstName ( ) ) ; endTransaction ( ) ; o1 . getPets ( ) ; } public void testInsertOwner ( ) { Collection < Owner > owners = this . clinic . findOwners ( "" ) ; int found = owners . size ( ) ; Owner owner = new Owner ( ) ; owner . setLastName ( "" ) ; this . clinic . storeOwner ( owner ) ; owners = this . clinic . findOwners ( "" ) ; assertEquals ( found + , owners . size ( ) ) ; } public void testUpdateOwner ( ) throws Exception { Owner o1 = this . clinic . loadOwner ( ) ; String old = o1 . getLastName ( ) ; o1 . setLastName ( old + "" ) ; this . clinic . storeOwner ( o1 ) ; o1 = this . clinic . loadOwner ( ) ; assertEquals ( old + "" , o1 . getLastName ( ) ) ; } public void testLoadPet ( ) { Collection < PetType > types = this . clinic . getPetTypes ( ) ; Pet p7 = this . clinic . loadPet ( ) ; assertTrue ( p7 . getName ( ) . startsWith ( "" ) ) ; assertEquals ( EntityUtils . getById ( types , PetType . class , ) . getId ( ) , p7 . getType ( ) . getId ( ) ) ; assertEquals ( "" , p7 . getOwner ( ) . getFirstName ( ) ) ; Pet p6 = this . clinic . loadPet ( ) ; assertEquals ( "" , p6 . getName ( ) ) ; assertEquals ( EntityUtils . getById ( types , PetType . class , ) . getId ( ) , p6 . getType ( ) . getId ( ) ) ; assertEquals ( "" , p6 . getOwner ( ) . getFirstName ( ) ) ; } public void testInsertPet ( ) { Owner o6 = this . clinic . loadOwner ( ) ; int found = o6 . getPets ( ) . size ( ) ; Pet pet = new Pet ( ) ; pet . setName ( "" ) ; Collection < PetType > types = this . clinic . getPetTypes ( ) ; pet . setType ( EntityUtils . getById ( types , PetType . class , ) ) ; pet . setBirthDate ( new LocalDate ( ) ) ; o6 . addPet ( pet ) ; assertEquals ( found + , o6 . getPets ( ) . size ( ) ) ; this . clinic . storeOwner ( o6 ) ; o6 = this . clinic . loadOwner ( ) ; assertEquals ( found + , o6 . getPets ( ) . size ( ) ) ; } public void testUpdatePet ( ) throws Exception { Pet p7 = this . clinic . loadPet ( ) ; String old = p7 . getName ( ) ; p7 . setName ( old + "" ) ; this . clinic . storePet ( p7 ) ; p7 = this . clinic . loadPet ( ) ; assertEquals ( old + "" , p7 . getName ( ) ) ; } public void testInsertVisit ( ) { Pet p7 = this . clinic . loadPet ( ) ; int found = p7 . getVisits ( ) . size ( ) ; Visit visit = new Visit ( ) ; p7 . addVisit ( visit ) ; visit . setDescription ( "" ) ; this . clinic . storePet ( p7 ) ; p7 = this . clinic . loadPet ( ) ; assertEquals ( found + , p7 . getVisits ( ) . size ( ) ) ; } } package org . springframework . samples . petclinic ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertNull ; import org . junit . Test ; public class OwnerTests { @ Test public void testHasPet ( ) { Owner owner = new Owner ( ) ; Pet fido = new Pet ( ) ; fido . setName ( "" ) ; assertNull ( owner . getPet ( "" ) ) ; assertNull ( owner . getPet ( "" ) ) ; owner . addPet ( fido ) ; assertEquals ( fido , owner . getPet ( "" ) ) ; assertEquals ( fido , owner . getPet ( "" ) ) ; } } package org . springframework . samples . petclinic ; import java . util . Collection ; import java . util . Date ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; import org . joda . time . LocalDate ; import org . junit . Test ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . samples . petclinic . util . EntityUtils ; import org . springframework . test . context . ContextConfiguration ; import org . springframework . test . context . junit4 . AbstractTransactionalJUnit4SpringContextTests ; @ ContextConfiguration public abstract class AbstractClinicTests extends AbstractTransactionalJUnit4SpringContextTests { @ Autowired protected Clinic clinic ; @ Test public void getVets ( ) { Collection < Vet > vets = this . clinic . getVets ( ) ; assertEquals ( "" , super . countRowsInTable ( "" ) , vets . size ( ) ) ; Vet v1 = EntityUtils . getById ( vets , Vet . class , ) ; assertEquals ( "" , v1 . getLastName ( ) ) ; assertEquals ( , v1 . getNrOfSpecialties ( ) ) ; assertEquals ( "" , ( v1 . getSpecialties ( ) . get ( ) ) . getName ( ) ) ; Vet v2 = EntityUtils . getById ( vets , Vet . class , ) ; assertEquals ( "" , v2 . getLastName ( ) ) ; assertEquals ( , v2 . getNrOfSpecialties ( ) ) ; assertEquals ( "" , ( v2 . getSpecialties ( ) . get ( ) ) . getName ( ) ) ; assertEquals ( "" , ( v2 . getSpecialties ( ) . get ( ) ) . getName ( ) ) ; } @ Test public void getPetTypes ( ) { Collection < PetType > petTypes = this . clinic . getPetTypes ( ) ; assertEquals ( "" , super . countRowsInTable ( "" ) , petTypes . size ( ) ) ; PetType t1 = EntityUtils . getById ( petTypes , PetType . class , ) ; assertEquals ( "" , t1 . getName ( ) ) ; PetType t4 = EntityUtils . getById ( petTypes , PetType . class , ) ; assertEquals ( "" , t4 . getName ( ) ) ; } @ Test public void findOwners ( ) { Collection < Owner > owners = this . clinic . findOwners ( "" ) ; assertEquals ( , owners . size ( ) ) ; owners = this . clinic . findOwners ( "" ) ; assertEquals ( , owners . size ( ) ) ; } @ Test public void loadOwner ( ) { Owner o1 = this . clinic . loadOwner ( ) ; assertTrue ( o1 . getLastName ( ) . startsWith ( "" ) ) ; Owner o10 = this . clinic . loadOwner ( ) ; assertEquals ( "" , o10 . getFirstName ( ) ) ; o1 . getPets ( ) ; } @ Test public void insertOwner ( ) { Collection < Owner > owners = this . clinic . findOwners ( "" ) ; int found = owners . size ( ) ; Owner owner = new Owner ( ) ; owner . setLastName ( "" ) ; this . clinic . storeOwner ( owner ) ; owners = this . clinic . findOwners ( "" ) ; assertEquals ( "" , found + , owners . size ( ) ) ; } @ Test public void updateOwner ( ) throws Exception { Owner o1 = this . clinic . loadOwner ( ) ; String old = o1 . getLastName ( ) ; o1 . setLastName ( old + "" ) ; this . clinic . storeOwner ( o1 ) ; o1 = this . clinic . loadOwner ( ) ; assertEquals ( old + "" , o1 . getLastName ( ) ) ; } @ Test public void loadPet ( ) { Collection < PetType > types = this . clinic . getPetTypes ( ) ; Pet p7 = this . clinic . loadPet ( ) ; assertTrue ( p7 . getName ( ) . startsWith ( "" ) ) ; assertEquals ( EntityUtils . getById ( types , PetType . class , ) . getId ( ) , p7 . getType ( ) . getId ( ) ) ; assertEquals ( "" , p7 . getOwner ( ) . getFirstName ( ) ) ; Pet p6 = this . clinic . loadPet ( ) ; assertEquals ( "" , p6 . getName ( ) ) ; assertEquals ( EntityUtils . getById ( types , PetType . class , ) . getId ( ) , p6 . getType ( ) . getId ( ) ) ; assertEquals ( "" , p6 . getOwner ( ) . getFirstName ( ) ) ; } @ Test public void insertPet ( ) { Owner o6 = this . clinic . loadOwner ( ) ; int found = o6 . getPets ( ) . size ( ) ; Pet pet = new Pet ( ) ; pet . setName ( "" ) ; Collection < PetType > types = this . clinic . getPetTypes ( ) ; pet . setType ( EntityUtils . getById ( types , PetType . class , ) ) ; pet . setBirthDate ( new LocalDate ( ) ) ; o6 . addPet ( pet ) ; assertEquals ( found + , o6 . getPets ( ) . size ( ) ) ; this . clinic . storePet ( pet ) ; this . clinic . storeOwner ( o6 ) ; o6 = this . clinic . loadOwner ( ) ; assertEquals ( found + , o6 . getPets ( ) . size ( ) ) ; } @ Test public void updatePet ( ) throws Exception { Pet p7 = this . clinic . loadPet ( ) ; String old = p7 . getName ( ) ; p7 . setName ( old + "" ) ; this . clinic . storePet ( p7 ) ; p7 = this . clinic . loadPet ( ) ; assertEquals ( old + "" , p7 . getName ( ) ) ; } @ Test public void insertVisit ( ) { Pet p7 = this . clinic . loadPet ( ) ; int found = p7 . getVisits ( ) . size ( ) ; Visit visit = new Visit ( ) ; p7 . addVisit ( visit ) ; visit . setDescription ( "" ) ; this . clinic . storeVisit ( visit ) ; this . clinic . storePet ( p7 ) ; p7 = this . clinic . loadPet ( ) ; assertEquals ( found + , p7 . getVisits ( ) . size ( ) ) ; } } package org . springframework . samples . petclinic . aspects ; import org . aspectj . lang . ProceedingJoinPoint ; import org . aspectj . lang . annotation . Around ; import org . aspectj . lang . annotation . Aspect ; import org . springframework . jmx . export . annotation . ManagedAttribute ; import org . springframework . jmx . export . annotation . ManagedOperation ; import org . springframework . jmx . export . annotation . ManagedResource ; import org . springframework . util . StopWatch ; @ ManagedResource ( "" ) @ Aspect public class CallMonitoringAspect { private boolean isEnabled = true ; private int callCount = ; private long accumulatedCallTime = ; @ ManagedAttribute public void setEnabled ( boolean enabled ) { isEnabled = enabled ; } @ ManagedAttribute public boolean isEnabled ( ) { return isEnabled ; } @ ManagedOperation public void reset ( ) { this . callCount = ; this . accumulatedCallTime = ; } @ ManagedAttribute public int getCallCount ( ) { return callCount ; } @ ManagedAttribute public long getCallTime ( ) { return ( this . callCount > ? this . accumulatedCallTime / this . callCount : ) ; } @ Around ( "" ) public Object invoke ( ProceedingJoinPoint joinPoint ) throws Throwable { if ( this . isEnabled ) { StopWatch sw = new StopWatch ( joinPoint . toShortString ( ) ) ; sw . start ( "" ) ; try { return joinPoint . proceed ( ) ; } finally { sw . stop ( ) ; synchronized ( this ) { this . callCount ++ ; this . accumulatedCallTime += sw . getTotalTimeMillis ( ) ; } } } else { return joinPoint . proceed ( ) ; } } } package org . springframework . samples . petclinic . aspects ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . aspectj . lang . annotation . Aspect ; import org . aspectj . lang . annotation . Before ; @ Aspect public class UsageLogAspect { private int historySize = ; private List < String > namesRequested = new ArrayList < String > ( this . historySize ) ; public synchronized void setHistorySize ( int historySize ) { this . historySize = historySize ; this . namesRequested = new ArrayList < String > ( historySize ) ; } @ Before ( "" ) public synchronized void logNameRequest ( String name ) { if ( this . namesRequested . size ( ) > this . historySize ) { this . namesRequested . remove ( ) ; } this . namesRequested . add ( name ) ; } public synchronized List < String > getNamesRequested ( ) { return Collections . unmodifiableList ( this . namesRequested ) ; } } package org . springframework . samples . petclinic . aspects ; import org . aspectj . lang . JoinPoint ; import org . aspectj . lang . annotation . Aspect ; import org . aspectj . lang . annotation . Before ; import org . aspectj . lang . annotation . Pointcut ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; @ Aspect public abstract class AbstractTraceAspect { private static final Logger logger = LoggerFactory . getLogger ( AbstractTraceAspect . class ) ; @ Pointcut public abstract void traced ( ) ; @ Before ( "" ) public void trace ( JoinPoint . StaticPart jpsp ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "" + jpsp . getSignature ( ) . toLongString ( ) ) ; } } } package org . springframework . samples . petclinic ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import javax . persistence . Basic ; import javax . persistence . Column ; import javax . persistence . Entity ; import javax . persistence . FetchType ; import javax . persistence . GeneratedValue ; import javax . persistence . GenerationType ; import javax . persistence . Id ; import javax . persistence . JoinColumn ; import javax . persistence . JoinTable ; import javax . persistence . ManyToMany ; import javax . persistence . Table ; import javax . xml . bind . annotation . XmlElement ; import org . hibernate . annotations . Index ; import org . springframework . beans . support . MutableSortDefinition ; import org . springframework . beans . support . PropertyComparator ; @ Entity @ Table ( name = "" ) public class Vet implements Person { @ Basic @ Column ( name = "" ) private String firstName ; @ Id @ GeneratedValue ( strategy = GenerationType . IDENTITY ) private Integer id ; @ Basic @ Column ( name = "" ) @ Index ( name = "" ) private String lastName ; @ ManyToMany ( targetEntity = Specialty . class , fetch = FetchType . EAGER ) @ JoinTable ( name = "" , joinColumns = { @ JoinColumn ( name = "" ) } , inverseJoinColumns = { @ JoinColumn ( name = "" ) } ) private Set < Specialty > specialties ; public void addSpecialty ( Specialty specialty ) { getSpecialtiesInternal ( ) . add ( specialty ) ; } @ Override public String getFirstName ( ) { return this . firstName ; } @ Override public Integer getId ( ) { return id ; } @ Override public String getLastName ( ) { return this . lastName ; } public int getNrOfSpecialties ( ) { return getSpecialtiesInternal ( ) . size ( ) ; } @ XmlElement public List < Specialty > getSpecialties ( ) { List < Specialty > sortedSpecs = new ArrayList < Specialty > ( getSpecialtiesInternal ( ) ) ; PropertyComparator . sort ( sortedSpecs , new MutableSortDefinition ( "" , true , true ) ) ; return Collections . unmodifiableList ( sortedSpecs ) ; } protected Set < Specialty > getSpecialtiesInternal ( ) { if ( this . specialties == null ) { this . specialties = new HashSet < Specialty > ( ) ; } return this . specialties ; } @ Override public boolean isNew ( ) { return ( this . id == null ) ; } @ Override public boolean getIsNew ( ) { return isNew ( ) ; } @ Override public void setFirstName ( String firstName ) { this . firstName = firstName ; } @ Override public void setId ( Integer id ) { this . id = id ; } @ Override public void setLastName ( String lastName ) { this . lastName = lastName ; } protected void setSpecialtiesInternal ( Set < Specialty > specialties ) { this . specialties = specialties ; } } package org . springframework . samples . petclinic ; import javax . persistence . Basic ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . GenerationType ; import javax . persistence . Id ; import javax . persistence . Table ; import org . hibernate . annotations . Index ; @ Entity @ Table ( name = "" ) public class Specialty implements NamedEntity { @ Id @ GeneratedValue ( strategy = GenerationType . IDENTITY ) private Integer id ; @ Basic @ Index ( name = "" ) private String name ; @ Override public Integer getId ( ) { return id ; } @ Override public String getName ( ) { return this . name ; } @ Override public boolean isNew ( ) { return ( this . id == null ) ; } @ Override public boolean getIsNew ( ) { return isNew ( ) ; } @ Override public void setId ( Integer id ) { this . id = id ; } @ Override public void setName ( String name ) { this . name = name ; } @ Override public String toString ( ) { return this . getName ( ) ; } } package org . springframework . samples . petclinic ; public interface NamedEntity extends BaseEntity { public void setName ( String name ) ; public String getName ( ) ; } package org . springframework . samples . petclinic . web ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Owner ; import org . springframework . samples . petclinic . validation . OwnerValidator ; import org . springframework . stereotype . Controller ; import org . springframework . ui . Model ; import org . springframework . validation . BindingResult ; import org . springframework . web . bind . WebDataBinder ; import org . springframework . web . bind . annotation . InitBinder ; import org . springframework . web . bind . annotation . ModelAttribute ; import org . springframework . web . bind . annotation . PathVariable ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . bind . annotation . SessionAttributes ; import org . springframework . web . bind . support . SessionStatus ; @ Controller @ RequestMapping ( "" ) @ SessionAttributes ( types = Owner . class ) public class EditOwnerForm { private final Clinic clinic ; @ Autowired public EditOwnerForm ( Clinic clinic ) { this . clinic = clinic ; } @ InitBinder public void setAllowedFields ( WebDataBinder dataBinder ) { dataBinder . setDisallowedFields ( "" ) ; } @ RequestMapping ( method = RequestMethod . GET ) public String setupForm ( @ PathVariable ( "" ) int ownerId , Model model ) { Owner owner = this . clinic . loadOwner ( ownerId ) ; model . addAttribute ( owner ) ; return "" ; } @ RequestMapping ( method = RequestMethod . PUT ) public String processSubmit ( @ ModelAttribute Owner owner , BindingResult result , SessionStatus status ) { new OwnerValidator ( ) . validate ( owner , result ) ; if ( result . hasErrors ( ) ) { return "" ; } else { this . clinic . storeOwner ( owner ) ; status . setComplete ( ) ; return "" + owner . getId ( ) ; } } } package org . springframework . samples . petclinic . web ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Vets ; import org . springframework . stereotype . Controller ; import org . springframework . ui . ModelMap ; import org . springframework . web . bind . annotation . PathVariable ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . servlet . ModelAndView ; @ Controller public class ClinicController { private final Clinic clinic ; @ Autowired public ClinicController ( Clinic clinic ) { this . clinic = clinic ; } @ RequestMapping ( "" ) public String welcomeHandler ( ) { return "" ; } @ RequestMapping ( "" ) public ModelMap vetsHandler ( ) { Vets vets = new Vets ( ) ; vets . getVetList ( ) . addAll ( this . clinic . getVets ( ) ) ; return new ModelMap ( vets ) ; } @ RequestMapping ( "" ) public ModelAndView ownerHandler ( @ PathVariable ( "" ) int ownerId ) { ModelAndView mav = new ModelAndView ( "" ) ; mav . addObject ( this . clinic . loadOwner ( ownerId ) ) ; return mav ; } @ RequestMapping ( value = "" , method = RequestMethod . GET ) public ModelAndView visitsHandler ( @ PathVariable int petId ) { ModelAndView mav = new ModelAndView ( "" ) ; mav . addObject ( "" , this . clinic . loadPet ( petId ) . getVisits ( ) ) ; return mav ; } } package org . springframework . samples . petclinic . web ; import java . util . Collection ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Pet ; import org . springframework . samples . petclinic . PetType ; import org . springframework . samples . petclinic . validation . PetValidator ; import org . springframework . stereotype . Controller ; import org . springframework . ui . Model ; import org . springframework . validation . BindingResult ; import org . springframework . web . bind . WebDataBinder ; import org . springframework . web . bind . annotation . InitBinder ; import org . springframework . web . bind . annotation . ModelAttribute ; import org . springframework . web . bind . annotation . PathVariable ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . bind . annotation . SessionAttributes ; import org . springframework . web . bind . support . SessionStatus ; @ Controller @ RequestMapping ( "" ) @ SessionAttributes ( "" ) public class EditPetForm { private final Clinic clinic ; @ Autowired public EditPetForm ( Clinic clinic ) { this . clinic = clinic ; } @ ModelAttribute ( "" ) public Collection < PetType > populatePetTypes ( ) { return this . clinic . getPetTypes ( ) ; } @ InitBinder public void setAllowedFields ( WebDataBinder dataBinder ) { dataBinder . setDisallowedFields ( "" ) ; } @ RequestMapping ( method = RequestMethod . GET ) public String setupForm ( @ PathVariable ( "" ) int petId , Model model ) { Pet pet = this . clinic . loadPet ( petId ) ; model . addAttribute ( "" , pet ) ; return "" ; } @ RequestMapping ( method = { RequestMethod . PUT , RequestMethod . POST } ) public String processSubmit ( @ ModelAttribute ( "" ) Pet pet , BindingResult result , SessionStatus status ) { new PetValidator ( ) . validate ( pet , result ) ; if ( result . hasErrors ( ) ) { return "" ; } else { this . clinic . storePet ( pet ) ; status . setComplete ( ) ; return "" + pet . getOwner ( ) . getId ( ) ; } } @ RequestMapping ( method = RequestMethod . DELETE ) public String deletePet ( @ PathVariable int petId ) { Pet pet = this . clinic . loadPet ( petId ) ; this . clinic . deletePet ( petId ) ; return "" + pet . getOwner ( ) . getId ( ) ; } } package org . springframework . samples . petclinic . web ; import java . util . Collection ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Owner ; import org . springframework . samples . petclinic . Pet ; import org . springframework . samples . petclinic . PetType ; import org . springframework . samples . petclinic . validation . PetValidator ; import org . springframework . stereotype . Controller ; import org . springframework . ui . Model ; import org . springframework . validation . BindingResult ; import org . springframework . web . bind . WebDataBinder ; import org . springframework . web . bind . annotation . InitBinder ; import org . springframework . web . bind . annotation . ModelAttribute ; import org . springframework . web . bind . annotation . PathVariable ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . bind . annotation . SessionAttributes ; import org . springframework . web . bind . support . SessionStatus ; @ Controller @ RequestMapping ( "" ) @ SessionAttributes ( "" ) public class AddPetForm { private final Clinic clinic ; @ Autowired public AddPetForm ( Clinic clinic ) { this . clinic = clinic ; } @ ModelAttribute ( "" ) public Collection < PetType > populatePetTypes ( ) { return this . clinic . getPetTypes ( ) ; } @ InitBinder public void setAllowedFields ( WebDataBinder dataBinder ) { dataBinder . setDisallowedFields ( "" ) ; } @ RequestMapping ( method = RequestMethod . GET ) public String setupForm ( @ PathVariable ( "" ) int ownerId , Model model ) { Owner owner = this . clinic . loadOwner ( ownerId ) ; Pet pet = new Pet ( ) ; owner . addPet ( pet ) ; model . addAttribute ( "" , pet ) ; return "" ; } @ RequestMapping ( method = RequestMethod . POST ) public String processSubmit ( @ ModelAttribute ( "" ) Pet pet , BindingResult result , SessionStatus status ) { new PetValidator ( ) . validate ( pet , result ) ; if ( result . hasErrors ( ) ) { return "" ; } else { this . clinic . storePet ( pet ) ; status . setComplete ( ) ; return "" + pet . getOwner ( ) . getId ( ) ; } } } package org . springframework . samples . petclinic . web ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . Map ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; import org . springframework . samples . petclinic . Visit ; import org . springframework . web . servlet . view . feed . AbstractAtomFeedView ; import com . sun . syndication . feed . atom . Content ; import com . sun . syndication . feed . atom . Entry ; import com . sun . syndication . feed . atom . Feed ; public class VisitsAtomView extends AbstractAtomFeedView { @ Override protected void buildFeedMetadata ( Map < String , Object > model , Feed feed , HttpServletRequest request ) { feed . setId ( "" ) ; feed . setTitle ( "" ) ; @ SuppressWarnings ( "" ) List < Visit > visits = ( List < Visit > ) model . get ( "" ) ; for ( Visit visit : visits ) { Date date = visit . getDate ( ) . toDateTimeAtStartOfDay ( ) . toDate ( ) ; if ( feed . getUpdated ( ) == null || date . compareTo ( feed . getUpdated ( ) ) > ) { feed . setUpdated ( date ) ; } } } @ Override protected List < Entry > buildFeedEntries ( Map < String , Object > model , HttpServletRequest request , HttpServletResponse response ) throws Exception { @ SuppressWarnings ( "" ) List < Visit > visits = ( List < Visit > ) model . get ( "" ) ; List < Entry > entries = new ArrayList < Entry > ( visits . size ( ) ) ; for ( Visit visit : visits ) { Entry entry = new Entry ( ) ; String date = visit . getDate ( ) . toString ( ) ; entry . setId ( String . format ( "" , date , visit . getId ( ) ) ) ; entry . setTitle ( String . format ( "" , visit . getPet ( ) . getName ( ) , date ) ) ; entry . setUpdated ( visit . getDate ( ) . toDateTimeAtStartOfDay ( ) . toDate ( ) ) ; Content summary = new Content ( ) ; summary . setValue ( visit . getDescription ( ) ) ; entry . setSummary ( summary ) ; entries . add ( entry ) ; } return entries ; } } package org . springframework . samples . petclinic . web ; package org . springframework . samples . petclinic . web ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Pet ; import org . springframework . samples . petclinic . Visit ; import org . springframework . samples . petclinic . validation . VisitValidator ; import org . springframework . stereotype . Controller ; import org . springframework . ui . Model ; import org . springframework . validation . BindingResult ; import org . springframework . web . bind . WebDataBinder ; import org . springframework . web . bind . annotation . InitBinder ; import org . springframework . web . bind . annotation . ModelAttribute ; import org . springframework . web . bind . annotation . PathVariable ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . bind . annotation . SessionAttributes ; import org . springframework . web . bind . support . SessionStatus ; @ Controller @ RequestMapping ( "" ) @ SessionAttributes ( "" ) public class AddVisitForm { private final Clinic clinic ; @ Autowired public AddVisitForm ( Clinic clinic ) { this . clinic = clinic ; } @ InitBinder public void setAllowedFields ( WebDataBinder dataBinder ) { dataBinder . setDisallowedFields ( "" ) ; } @ RequestMapping ( method = RequestMethod . GET ) public String setupForm ( @ PathVariable ( "" ) int petId , Model model ) { Pet pet = this . clinic . loadPet ( petId ) ; Visit visit = new Visit ( ) ; pet . addVisit ( visit ) ; model . addAttribute ( "" , visit ) ; return "" ; } @ RequestMapping ( method = RequestMethod . POST ) public String processSubmit ( @ ModelAttribute ( "" ) Visit visit , BindingResult result , SessionStatus status ) { new VisitValidator ( ) . validate ( visit , result ) ; if ( result . hasErrors ( ) ) { return "" ; } else { this . clinic . storeVisit ( visit ) ; status . setComplete ( ) ; return "" + visit . getPet ( ) . getOwner ( ) . getId ( ) ; } } } package org . springframework . samples . petclinic . web ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Owner ; import org . springframework . samples . petclinic . validation . OwnerValidator ; import org . springframework . stereotype . Controller ; import org . springframework . ui . Model ; import org . springframework . validation . BindingResult ; import org . springframework . web . bind . WebDataBinder ; import org . springframework . web . bind . annotation . InitBinder ; import org . springframework . web . bind . annotation . ModelAttribute ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . bind . annotation . SessionAttributes ; import org . springframework . web . bind . support . SessionStatus ; @ Controller @ RequestMapping ( "" ) @ SessionAttributes ( types = Owner . class ) public class AddOwnerForm { private final Clinic clinic ; @ Autowired public AddOwnerForm ( Clinic clinic ) { this . clinic = clinic ; } @ InitBinder public void setAllowedFields ( WebDataBinder dataBinder ) { dataBinder . setDisallowedFields ( "" ) ; } @ RequestMapping ( method = RequestMethod . GET ) public String setupForm ( Model model ) { Owner owner = new Owner ( ) ; model . addAttribute ( owner ) ; return "" ; } @ RequestMapping ( method = RequestMethod . POST ) public String processSubmit ( @ ModelAttribute Owner owner , BindingResult result , SessionStatus status ) { new OwnerValidator ( ) . validate ( owner , result ) ; if ( result . hasErrors ( ) ) { return "" ; } else { this . clinic . storeOwner ( owner ) ; status . setComplete ( ) ; return "" + owner . getId ( ) ; } } } package org . springframework . samples . petclinic . web ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . core . convert . converter . Converter ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . PetType ; public class PetTypeConverter implements Converter < String , PetType > { @ Autowired private Clinic clinic ; @ Override public PetType convert ( String source ) { for ( PetType type : this . clinic . getPetTypes ( ) ) { if ( type . getName ( ) . equals ( source ) ) { return type ; } } throw new IllegalStateException ( "" + source + "" ) ; } } package org . springframework . samples . petclinic . web ; import java . util . Collection ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Owner ; import org . springframework . stereotype . Controller ; import org . springframework . ui . Model ; import org . springframework . validation . BindingResult ; import org . springframework . web . bind . WebDataBinder ; import org . springframework . web . bind . annotation . InitBinder ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; @ Controller public class FindOwnersForm { private final Clinic clinic ; @ Autowired public FindOwnersForm ( Clinic clinic ) { this . clinic = clinic ; } @ InitBinder public void setAllowedFields ( WebDataBinder dataBinder ) { dataBinder . setDisallowedFields ( "" ) ; } @ RequestMapping ( value = "" , method = RequestMethod . GET ) public String setupForm ( Model model ) { model . addAttribute ( "" , new Owner ( ) ) ; return "" ; } @ RequestMapping ( value = "" , method = RequestMethod . GET ) public String processSubmit ( Owner owner , BindingResult result , Model model ) { if ( owner . getLastName ( ) == null ) { owner . setLastName ( "" ) ; } Collection < Owner > results = this . clinic . findOwners ( owner . getLastName ( ) ) ; if ( results . size ( ) < ) { result . rejectValue ( "" , "" , "" ) ; return "" ; } if ( results . size ( ) > ) { model . addAttribute ( "" , results ) ; return "" ; } else { owner = results . iterator ( ) . next ( ) ; return "" + owner . getId ( ) ; } } } package org . springframework . samples . petclinic ; public interface Person extends BaseEntity { public String getFirstName ( ) ; public void setFirstName ( String firstName ) ; public String getLastName ( ) ; public void setLastName ( String lastName ) ; } package org . springframework . samples . petclinic ; package org . springframework . samples . petclinic ; public interface BaseEntity { public void setId ( Integer id ) ; public Integer getId ( ) ; public boolean isNew ( ) ; public boolean getIsNew ( ) ; } package org . springframework . samples . petclinic . util ; import java . util . Collection ; import org . springframework . orm . ObjectRetrievalFailureException ; import org . springframework . samples . petclinic . BaseEntity ; public abstract class EntityUtils { public static < T extends BaseEntity > T getById ( Collection < T > entities , Class < T > entityClass , int entityId ) throws ObjectRetrievalFailureException { for ( T entity : entities ) { if ( entity . getId ( ) . intValue ( ) == entityId && entityClass . isInstance ( entity ) ) { return entity ; } } throw new ObjectRetrievalFailureException ( entityClass , new Integer ( entityId ) ) ; } } package org . springframework . samples . petclinic ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import javax . persistence . Basic ; import javax . persistence . CascadeType ; import javax . persistence . Column ; import javax . persistence . Entity ; import javax . persistence . FetchType ; import javax . persistence . GeneratedValue ; import javax . persistence . GenerationType ; import javax . persistence . Id ; import javax . persistence . ManyToOne ; import javax . persistence . OneToMany ; import javax . persistence . Table ; import org . hibernate . annotations . Index ; import org . joda . time . LocalDate ; import org . springframework . beans . support . MutableSortDefinition ; import org . springframework . beans . support . PropertyComparator ; import org . springframework . format . annotation . DateTimeFormat ; import org . springframework . format . annotation . DateTimeFormat . ISO ; @ Entity ( ) @ Table ( name = "" ) public class Pet implements NamedEntity { @ DateTimeFormat ( iso = ISO . DATE ) @ Basic @ Column ( name = "" ) private LocalDate birthDate ; @ Id @ GeneratedValue ( strategy = GenerationType . IDENTITY ) private Integer id ; @ Basic @ Index ( name = "" ) private String name ; @ ManyToOne ( fetch = FetchType . EAGER ) private Owner owner ; @ ManyToOne ( fetch = FetchType . EAGER ) private PetType type ; @ OneToMany ( mappedBy = "" , fetch = FetchType . EAGER , cascade = CascadeType . ALL ) private Set < Visit > visits ; public void addVisit ( Visit visit ) { getVisitsInternal ( ) . add ( visit ) ; visit . setPet ( this ) ; } public LocalDate getBirthDate ( ) { return this . birthDate ; } @ Override public Integer getId ( ) { return id ; } @ Override public String getName ( ) { return this . name ; } public Owner getOwner ( ) { return this . owner ; } public PetType getType ( ) { return this . type ; } public List < Visit > getVisits ( ) { List < Visit > sortedVisits = new ArrayList < Visit > ( getVisitsInternal ( ) ) ; PropertyComparator . sort ( sortedVisits , new MutableSortDefinition ( "" , false , false ) ) ; return Collections . unmodifiableList ( sortedVisits ) ; } protected Set < Visit > getVisitsInternal ( ) { if ( this . visits == null ) { this . visits = new HashSet < Visit > ( ) ; } return this . visits ; } @ Override public boolean isNew ( ) { return ( this . id == null ) ; } @ Override public boolean getIsNew ( ) { return isNew ( ) ; } public void setBirthDate ( LocalDate birthDate ) { this . birthDate = birthDate ; } @ Override public void setId ( Integer id ) { this . id = id ; } @ Override public void setName ( String name ) { this . name = name ; } protected void setOwner ( Owner owner ) { this . owner = owner ; } public void setType ( PetType type ) { this . type = type ; } protected void setVisitsInternal ( Set < Visit > visits ) { this . visits = visits ; } @ Override public String toString ( ) { return this . getName ( ) ; } } package org . springframework . samples . petclinic . validation ; import org . springframework . samples . petclinic . Pet ; import org . springframework . util . StringUtils ; import org . springframework . validation . Errors ; public class PetValidator { public void validate ( Pet pet , Errors errors ) { String name = pet . getName ( ) ; if ( ! StringUtils . hasLength ( name ) ) { errors . rejectValue ( "" , "" , "" ) ; } else if ( pet . isNew ( ) && pet . getOwner ( ) . getPet ( name , true ) != null ) { errors . rejectValue ( "" , "" , "" ) ; } } } package org . springframework . samples . petclinic . validation ; package org . springframework . samples . petclinic . validation ; import org . springframework . samples . petclinic . Owner ; import org . springframework . util . StringUtils ; import org . springframework . validation . Errors ; public class OwnerValidator { public void validate ( Owner owner , Errors errors ) { if ( ! StringUtils . hasLength ( owner . getFirstName ( ) ) ) { errors . rejectValue ( "" , "" , "" ) ; } if ( ! StringUtils . hasLength ( owner . getLastName ( ) ) ) { errors . rejectValue ( "" , "" , "" ) ; } if ( ! StringUtils . hasLength ( owner . getAddress ( ) ) ) { errors . rejectValue ( "" , "" , "" ) ; } if ( ! StringUtils . hasLength ( owner . getCity ( ) ) ) { errors . rejectValue ( "" , "" , "" ) ; } String telephone = owner . getTelephone ( ) ; if ( ! StringUtils . hasLength ( telephone ) ) { errors . rejectValue ( "" , "" , "" ) ; } else { for ( int i = ; i < telephone . length ( ) ; ++ i ) { if ( ( Character . isDigit ( telephone . charAt ( i ) ) ) == false ) { errors . rejectValue ( "" , "" , "" ) ; break ; } } } } } package org . springframework . samples . petclinic . validation ; import org . springframework . samples . petclinic . Visit ; import org . springframework . util . StringUtils ; import org . springframework . validation . Errors ; public class VisitValidator { public void validate ( Visit visit , Errors errors ) { if ( ! StringUtils . hasLength ( visit . getDescription ( ) ) ) { errors . rejectValue ( "" , "" , "" ) ; } } } package org . springframework . samples . petclinic ; import javax . persistence . Basic ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . GenerationType ; import javax . persistence . Id ; import javax . persistence . Table ; import org . hibernate . annotations . Index ; @ Entity @ Table ( name = "" ) public class PetType implements NamedEntity { @ Id @ GeneratedValue ( strategy = GenerationType . IDENTITY ) private Integer id ; @ Override public void setId ( Integer id ) { this . id = id ; } @ Override public Integer getId ( ) { return id ; } @ Override public boolean isNew ( ) { return ( this . id == null ) ; } @ Override public boolean getIsNew ( ) { return isNew ( ) ; } @ Basic @ Index ( name = "" ) private String name ; @ Override public void setName ( String name ) { this . name = name ; } @ Override public String getName ( ) { return this . name ; } @ Override public String toString ( ) { return this . getName ( ) ; } } package org . springframework . samples . petclinic ; import java . util . ArrayList ; import java . util . List ; import javax . xml . bind . annotation . XmlElement ; import javax . xml . bind . annotation . XmlRootElement ; @ XmlRootElement public class Vets { private List < Vet > vets ; @ XmlElement public List < Vet > getVetList ( ) { if ( vets == null ) { vets = new ArrayList < Vet > ( ) ; } return vets ; } } package org . springframework . samples . petclinic ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import javax . persistence . Basic ; import javax . persistence . CascadeType ; import javax . persistence . Column ; import javax . persistence . Entity ; import javax . persistence . FetchType ; import javax . persistence . GeneratedValue ; import javax . persistence . GenerationType ; import javax . persistence . Id ; import javax . persistence . OneToMany ; import javax . persistence . Table ; import org . hibernate . annotations . Index ; import org . springframework . beans . support . MutableSortDefinition ; import org . springframework . beans . support . PropertyComparator ; import org . springframework . core . style . ToStringCreator ; @ Entity @ Table ( name = "" ) public class Owner implements Person { @ Basic private String address ; @ Basic private String city ; @ Basic @ Column ( name = "" ) private String firstName ; @ Id @ GeneratedValue ( strategy = GenerationType . IDENTITY ) private Integer id ; @ Basic @ Column ( name = "" ) @ Index ( name = "" ) private String lastName ; @ OneToMany ( targetEntity = Pet . class , mappedBy = "" , fetch = FetchType . EAGER , cascade = CascadeType . ALL ) private Set < Pet > pets ; @ Basic private String telephone ; public void addPet ( Pet pet ) { getPetsInternal ( ) . add ( pet ) ; pet . setOwner ( this ) ; } public String getAddress ( ) { return this . address ; } public String getCity ( ) { return this . city ; } @ Override public String getFirstName ( ) { return this . firstName ; } @ Override public Integer getId ( ) { return id ; } @ Override public String getLastName ( ) { return this . lastName ; } public Pet getPet ( String name ) { return getPet ( name , false ) ; } public Pet getPet ( String name , boolean ignoreNew ) { name = name . toLowerCase ( ) ; for ( Pet pet : getPetsInternal ( ) ) { if ( ! ignoreNew || ! pet . isNew ( ) ) { String compName = pet . getName ( ) ; compName = compName . toLowerCase ( ) ; if ( compName . equals ( name ) ) { return pet ; } } } return null ; } public List < Pet > getPets ( ) { List < Pet > sortedPets = new ArrayList < Pet > ( getPetsInternal ( ) ) ; PropertyComparator . sort ( sortedPets , new MutableSortDefinition ( "" , true , true ) ) ; return Collections . unmodifiableList ( sortedPets ) ; } protected Set < Pet > getPetsInternal ( ) { if ( this . pets == null ) { this . pets = new HashSet < Pet > ( ) ; } return this . pets ; } public String getTelephone ( ) { return this . telephone ; } @ Override public boolean isNew ( ) { return ( this . id == null ) ; } @ Override public boolean getIsNew ( ) { return isNew ( ) ; } public void setAddress ( String address ) { this . address = address ; } public void setCity ( String city ) { this . city = city ; } @ Override public void setFirstName ( String firstName ) { this . firstName = firstName ; } @ Override public void setId ( Integer id ) { this . id = id ; } @ Override public void setLastName ( String lastName ) { this . lastName = lastName ; } protected void setPetsInternal ( Set < Pet > pets ) { this . pets = pets ; } public void setTelephone ( String telephone ) { this . telephone = telephone ; } @ Override public String toString ( ) { return new ToStringCreator ( this ) . append ( "" , this . getId ( ) ) . append ( "" , this . isNew ( ) ) . append ( "" , this . getLastName ( ) ) . append ( "" , this . getFirstName ( ) ) . append ( "" , this . address ) . append ( "" , this . city ) . append ( "" , this . telephone ) . toString ( ) ; } } package org . springframework . samples . petclinic . jpa ; import java . util . Collection ; import javax . persistence . EntityManager ; import javax . persistence . PersistenceContext ; import javax . persistence . Query ; import org . springframework . dao . DataAccessException ; import org . springframework . samples . petclinic . Clinic ; import org . springframework . samples . petclinic . Owner ; import org . springframework . samples . petclinic . Pet ; import org . springframework . samples . petclinic . PetType ; import org . springframework . samples . petclinic . Vet ; import org . springframework . samples . petclinic . Visit ; import org . springframework . stereotype . Repository ; import org . springframework . transaction . annotation . Transactional ; @ Repository @ Transactional public class EntityManagerClinic implements Clinic { @ PersistenceContext private EntityManager em ; @ Override @ Transactional ( readOnly = true ) @ SuppressWarnings ( "" ) public Collection < Vet > getVets ( ) { return this . em . createQuery ( "" ) . getResultList ( ) ; } @ Override @ Transactional ( readOnly = true ) @ SuppressWarnings ( "" ) public Collection < PetType > getPetTypes ( ) { return this . em . createQuery ( "" ) . getResultList ( ) ; } @ Override @ Transactional ( readOnly = true ) @ SuppressWarnings ( "" ) public Collection < Owner > findOwners ( String lastName ) { Query query = this . em . createQuery ( "" ) ; query . setParameter ( "" , lastName + "" ) ; return query . getResultList ( ) ; } @ Override @ Transactional ( readOnly = true ) public Owner loadOwner ( int id ) { return this . em . find ( Owner . class , id ) ; } @ Override @ Transactional ( readOnly = true ) public Pet loadPet ( int id ) { return this . em . find ( Pet . class , id ) ; } @ Override public void storeOwner ( Owner owner ) { Owner merged = this . em . merge ( owner ) ; this . em . flush ( ) ; owner . setId ( merged . getId ( ) ) ; } @ Override public void storePet ( Pet pet ) { Pet merged = this . em . merge ( pet ) ; this . em . flush ( ) ; pet . setId ( merged . getId ( ) ) ; } @ Override public void storeVisit ( Visit visit ) { Visit merged = this . em . merge ( visit ) ; this . em . flush ( ) ; visit . setId ( merged . getId ( ) ) ; } @ Override public void deletePet ( int id ) throws DataAccessException { Pet pet = loadPet ( id ) ; this . em . remove ( pet ) ; } } package org . springframework . samples . petclinic . jpa ; package org . springframework . samples . petclinic ; import javax . persistence . Basic ; import javax . persistence . Column ; import javax . persistence . Entity ; import javax . persistence . FetchType ; import javax . persistence . GeneratedValue ; import javax . persistence . GenerationType ; import javax . persistence . Id ; import javax . persistence . ManyToOne ; import javax . persistence . Table ; import org . hibernate . annotations . Index ; import org . joda . time . LocalDate ; import org . springframework . format . annotation . DateTimeFormat ; import org . springframework . format . annotation . DateTimeFormat . ISO ; @ Entity @ Table ( name = "" ) public class Visit implements BaseEntity { @ DateTimeFormat ( iso = ISO . DATE ) @ Basic @ Column ( name = "" ) private LocalDate date ; @ Basic private String description ; @ Id @ GeneratedValue ( strategy = GenerationType . IDENTITY ) private Integer id ; @ ManyToOne ( fetch = FetchType . EAGER ) @ Index ( name = "" ) private Pet pet ; public Visit ( ) { this . date = new LocalDate ( ) ; } public LocalDate getDate ( ) { return this . date ; } public String getDescription ( ) { return this . description ; } @ Override public Integer getId ( ) { return id ; } public Pet getPet ( ) { return this . pet ; } @ Override public boolean isNew ( ) { return ( this . id == null ) ; } @ Override public boolean getIsNew ( ) { return isNew ( ) ; } public void setDate ( LocalDate date ) { this . date = date ; } public void setDescription ( String description ) { this . description = description ; } @ Override public void setId ( Integer id ) { this . id = id ; } public void setPet ( Pet pet ) { this . pet = pet ; } } package org . springframework . samples . petclinic ; import java . util . Collection ; import org . springframework . dao . DataAccessException ; public interface Clinic { Collection < Vet > getVets ( ) throws DataAccessException ; Collection < PetType > getPetTypes ( ) throws DataAccessException ; Collection < Owner > findOwners ( String lastName ) throws DataAccessException ; Owner loadOwner ( int id ) throws DataAccessException ; Pet loadPet ( int id ) throws DataAccessException ; void storeOwner ( Owner owner ) throws DataAccessException ; void storePet ( Pet pet ) throws DataAccessException ; void storeVisit ( Visit visit ) throws DataAccessException ; void deletePet ( int id ) throws DataAccessException ; } package net . bioclipse . opentox . ui . wizards ; import java . net . URL ; import java . util . List ; import net . bioclipse . opentox . OpenToxService ; import org . eclipse . core . resources . IFile ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . IWorkbench ; public class CreateDatasetPage extends WizardPage { private Combo cboLicense ; private IFile file ; private Text txtTitle ; private Text customLicense ; protected CreateDatasetPage ( ) { super ( "" ) ; setTitle ( "" ) ; setDescription ( "" ) ; } public CreateDatasetPage ( IFile file ) { this ( ) ; this . file = file ; } public void init ( IWorkbench workbench , IStructuredSelection selection ) { } public void createControl ( Composite parent ) { Composite container = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; container . setLayout ( layout ) ; layout . numColumns = ; layout . verticalSpacing = ; Label fromLabel = new Label ( container , SWT . NULL ) ; fromLabel . setText ( "" ) ; fromLabel . setLayoutData ( new GridData ( GridData . BEGINNING ) ) ; Label lblDSinfo = new Label ( container , SWT . NULL ) ; lblDSinfo . setText ( file . getName ( ) ) ; lblDSinfo . setLayoutData ( new GridData ( GridData . BEGINNING ) ) ; Label lblServer = new Label ( container , SWT . NULL ) ; lblServer . setText ( "" ) ; lblServer . setLayoutData ( new GridData ( GridData . BEGINNING ) ) ; Combo cboServer = new Combo ( container , SWT . NONE ) ; GridData gds = new GridData ( ) ; cboServer . setLayoutData ( gds ) ; List < OpenToxService > OTservices = net . bioclipse . opentox . Activator . getOpenToxServices ( ) ; for ( OpenToxService service : OTservices ) { cboServer . add ( service . getName ( ) ) ; } cboServer . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { Combo cbo = ( Combo ) e . getSource ( ) ; int ix = cbo . getSelectionIndex ( ) ; String service = net . bioclipse . opentox . Activator . getOpenToxServices ( ) . get ( ix ) . getService ( ) ; ( ( CreateDatasetWizard ) getWizard ( ) ) . setService ( service ) ; } } ) ; cboServer . select ( ) ; String service = net . bioclipse . opentox . Activator . getOpenToxServices ( ) . get ( ) . getService ( ) ; ( ( CreateDatasetWizard ) getWizard ( ) ) . setService ( service ) ; Label lblTitle = new Label ( container , SWT . NULL ) ; lblTitle . setText ( "" ) ; lblTitle . setLayoutData ( new GridData ( GridData . BEGINNING ) ) ; txtTitle = new Text ( container , SWT . BORDER | SWT . SINGLE ) ; txtTitle . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { ( ( CreateDatasetWizard ) getWizard ( ) ) . setTitle ( txtTitle . getText ( ) ) ; dialogChanged ( ) ; } } ) ; txtTitle . setText ( "" ) ; txtTitle . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; Label lblLicense = new Label ( container , SWT . NULL ) ; lblLicense . setText ( "" ) ; lblLicense . setLayoutData ( new GridData ( GridData . BEGINNING ) ) ; cboLicense = new Combo ( container , SWT . NONE ) ; GridData gdAutoBuild = new GridData ( ) ; cboLicense . setLayoutData ( gdAutoBuild ) ; cboLicense . add ( "" ) ; cboLicense . add ( "" ) ; cboLicense . add ( "" ) ; cboLicense . add ( "" ) ; cboLicense . add ( "" ) ; cboLicense . add ( "" ) ; cboLicense . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { Combo cbo = ( Combo ) e . getSource ( ) ; if ( cbo . getSelectionIndex ( ) == ) { ( ( CreateDatasetWizard ) getWizard ( ) ) . setLicense ( "" ) ; customLicense . setEnabled ( false ) ; } else if ( cbo . getSelectionIndex ( ) == ) { ( ( CreateDatasetWizard ) getWizard ( ) ) . setLicense ( "" ) ; customLicense . setEnabled ( false ) ; } else if ( cbo . getSelectionIndex ( ) == ) { ( ( CreateDatasetWizard ) getWizard ( ) ) . setLicense ( "" ) ; customLicense . setEnabled ( false ) ; } else if ( cbo . getSelectionIndex ( ) == ) { ( ( CreateDatasetWizard ) getWizard ( ) ) . setLicense ( "" ) ; customLicense . setEnabled ( false ) ; } else if ( cbo . getSelectionIndex ( ) == ) { ( ( CreateDatasetWizard ) getWizard ( ) ) . setLicense ( null ) ; customLicense . setEnabled ( false ) ; } else if ( cbo . getSelectionIndex ( ) == ) { customLicense . setEnabled ( true ) ; checkCustomLicense ( customLicense . getText ( ) ) ; } else { System . out . println ( "" ) ; } } } ) ; cboLicense . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; cboLicense . select ( ) ; ( ( CreateDatasetWizard ) getWizard ( ) ) . setLicense ( "" ) ; lblTitle = new Label ( container , SWT . NULL ) ; lblTitle . setText ( "" ) ; lblTitle . setLayoutData ( new GridData ( GridData . BEGINNING ) ) ; customLicense = new Text ( container , SWT . BORDER | SWT . SINGLE ) ; customLicense . setEnabled ( false ) ; customLicense . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { checkCustomLicense ( customLicense . getText ( ) ) ; } } ) ; customLicense . setText ( "" ) ; customLicense . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; setControl ( container ) ; dialogChanged ( ) ; } private void checkCustomLicense ( String customURL ) { if ( customURL . length ( ) > ) { try { URL url = new URL ( customURL ) ; if ( url . getHost ( ) . length ( ) > ) { setErrorMessage ( null ) ; setPageComplete ( true ) ; ( ( CreateDatasetWizard ) getWizard ( ) ) . setLicense ( customLicense . getText ( ) ) ; return ; } } catch ( Exception e1 ) { } } setErrorMessage ( "" ) ; setPageComplete ( false ) ; ( ( CreateDatasetWizard ) getWizard ( ) ) . setLicense ( null ) ; } private void dialogChanged ( ) { if ( txtTitle . getText ( ) . isEmpty ( ) ) { updateStatus ( "" ) ; return ; } updateStatus ( null ) ; } private void updateStatus ( String message ) { setErrorMessage ( message ) ; setPageComplete ( message == null ) ; } } package net . bioclipse . opentox . ui . wizards ; import java . lang . reflect . InvocationTargetException ; import java . util . List ; import net . bioclipse . browser . editors . RichBrowserEditor ; import net . bioclipse . cdk . business . ICDKManager ; import net . bioclipse . cdk . domain . ICDKMolecule ; import net . bioclipse . opentox . Activator ; import net . bioclipse . opentox . business . IOpentoxManager ; import org . apache . log4j . Logger ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . wizard . Wizard ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . internal . part . NullEditorInput ; public class CreateDatasetWizard extends Wizard implements INewWizard { private CreateDatasetPage createDatasetPage ; private static final Logger logger = Logger . getLogger ( CreateDatasetWizard . class ) ; private String license ; private String title ; private String service ; private IFile file ; public String getLicense ( ) { return license ; } public void setLicense ( String license ) { this . license = license ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } public String getService ( ) { return service ; } public void setService ( String service ) { this . service = service ; } public CreateDatasetWizard ( ) { super ( ) ; setWindowTitle ( "" ) ; setNeedsProgressMonitor ( true ) ; } public CreateDatasetWizard ( IFile file ) { this ( ) ; this . file = file ; } public void init ( IWorkbench workbench , IStructuredSelection selection ) { } public void addPages ( ) { createDatasetPage = new CreateDatasetPage ( file ) ; this . addPage ( createDatasetPage ) ; } @ Override public boolean performFinish ( ) { try { getContainer ( ) . run ( true , true , new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) { try { IOpentoxManager opentox = Activator . getDefault ( ) . getJavaOpentoxManager ( ) ; ICDKManager cdk = net . bioclipse . cdk . business . Activator . getDefault ( ) . getJavaCDKManager ( ) ; monitor . beginTask ( "" , ) ; monitor . subTask ( "" ) ; monitor . worked ( ) ; List < ICDKMolecule > mols = null ; mols = cdk . loadMolecules ( file , new SubProgressMonitor ( monitor , ) ) ; monitor . subTask ( "" ) ; monitor . worked ( ) ; final String datasetURI = opentox . createDataset ( service , mols ) ; System . out . println ( "" + datasetURI ) ; monitor . subTask ( "" ) ; if ( title != null && title . length ( ) > ) { System . out . println ( "" + title ) ; monitor . worked ( ) ; opentox . setDatasetTitle ( datasetURI , title ) ; } monitor . subTask ( "" ) ; monitor . worked ( ) ; if ( license != null ) { opentox . setDatasetLicense ( datasetURI , license ) ; } monitor . subTask ( "" ) ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { @ Override public void run ( ) { IEditorPart editor ; try { editor = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . openEditor ( new NullEditorInput ( ) , RichBrowserEditor . EDITOR_ID ) ; if ( editor != null ) { ( ( RichBrowserEditor ) editor ) . setURL ( datasetURI ) ; } } catch ( PartInitException e ) { e . printStackTrace ( ) ; } } } ) ; monitor . done ( ) ; } catch ( Exception exception ) { monitor . done ( ) ; return ; } } } ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } System . out . println ( "" ) ; return true ; } } package net . bioclipse . opentox . ui ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static Activator plugin ; public Activator ( ) { } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static Activator getDefault ( ) { return plugin ; } } package net . bioclipse . opentox . ui . handlers ; import net . bioclipse . opentox . ui . wizards . CreateDatasetWizard ; import org . eclipse . core . commands . AbstractHandler ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . core . commands . IHandler ; import org . eclipse . core . commands . IHandlerListener ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . handlers . HandlerUtil ; public class CreateDatasetHandler extends AbstractHandler { @ Override public Object execute ( ExecutionEvent event ) throws ExecutionException { ISelection sel = HandlerUtil . getCurrentSelection ( event ) ; if ( sel . isEmpty ( ) ) return null ; if ( ! ( sel instanceof IStructuredSelection ) ) return null ; Object obj = ( ( IStructuredSelection ) sel ) . getFirstElement ( ) ; if ( ! ( obj instanceof IFile ) ) return null ; IFile file = ( IFile ) obj ; try { CreateDatasetWizard wiz = new CreateDatasetWizard ( file ) ; WizardDialog dialog = new WizardDialog ( PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getShell ( ) , wiz ) ; dialog . open ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e . getMessage ( ) ) ; } return null ; } } package net . bioclipse . opentox ; import java . util . ArrayList ; import java . util . List ; import net . bioclipse . opentox . business . IJavaOpentoxManager ; import net . bioclipse . opentox . business . IJavaScriptOpentoxManager ; import net . bioclipse . opentox . business . IOpentoxManager ; import net . bioclipse . opentox . prefs . ServicesPreferencePage ; import net . bioclipse . usermanager . business . IUserManager ; import org . apache . log4j . Logger ; import org . eclipse . core . runtime . preferences . ConfigurationScope ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . opentox . aa . opensso . OpenSSOToken ; import org . osgi . framework . BundleContext ; import org . osgi . service . prefs . BackingStoreException ; import org . osgi . service . prefs . Preferences ; import org . osgi . util . tracker . ServiceTracker ; public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static final Logger logger = Logger . getLogger ( Activator . class ) ; public static final Integer TIME_OUT = ; private static Activator plugin ; private static List < OpenToxService > openToxServices ; private static OpenSSOToken token = null ; private ServiceTracker javaFinderTracker ; private ServiceTracker jsFinderTracker ; public Activator ( ) { IUserManager userManager = net . bioclipse . usermanager . Activator . getDefault ( ) . getUserManager ( ) ; OpenToxLogInOutListener listener = new OpenToxLogInOutListener ( userManager ) ; userManager . addListener ( listener ) ; } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; javaFinderTracker = new ServiceTracker ( context , IJavaOpentoxManager . class . getName ( ) , null ) ; javaFinderTracker . open ( ) ; jsFinderTracker = new ServiceTracker ( context , IJavaScriptOpentoxManager . class . getName ( ) , null ) ; jsFinderTracker . open ( ) ; openToxServices = new ArrayList < OpenToxService > ( ) ; logger . debug ( "" ) ; List < OpenToxService > prefss = ServiceReader . readServicesFromPreferences ( ) ; openToxServices . addAll ( prefss ) ; logger . debug ( "" + prefss . size ( ) + "" ) ; List < OpenToxService > epservices = ServiceReader . readServicesFromExtensionPoints ( ) ; for ( OpenToxService eps : epservices ) { if ( ! openToxServices . contains ( eps ) ) { openToxServices . add ( eps ) ; logger . debug ( "" + eps ) ; } } Preferences preferences = ConfigurationScope . INSTANCE . getNode ( OpenToxConstants . PLUGIN_ID ) ; List < String [ ] > toPrefs = ServicesPreferencePage . convertPreferenceStringToArraylist ( preferences . get ( OpenToxConstants . SERVICES , "" ) ) ; for ( OpenToxService eps : epservices ) { String [ ] entry = new String [ ] ; entry [ ] = eps . getName ( ) ; entry [ ] = eps . getService ( ) ; entry [ ] = eps . getServiceSPARQL ( ) ; if ( ! listContains ( toPrefs , entry ) ) toPrefs . add ( entry ) ; } String toPrefsString = ServicesPreferencePage . convertToPreferenceString ( toPrefs ) ; preferences . put ( OpenToxConstants . SERVICES , toPrefsString ) ; try { preferences . flush ( ) ; } catch ( BackingStoreException e ) { logger . error ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } logger . debug ( "" + toPrefsString ) ; logger . debug ( "" ) ; } private boolean listContains ( List < String [ ] > list , String [ ] item ) { boolean found = false , itemEquals ; for ( String [ ] listItem : list ) { itemEquals = false ; for ( int i = ; i < listItem . length ; i ++ ) { if ( item [ i ] == null || item [ i ] . isEmpty ( ) ) { if ( listItem [ i ] . equals ( "" ) || listItem [ i ] . isEmpty ( ) ) itemEquals = true ; } else if ( listItem [ i ] . equals ( item [ i ] ) ) itemEquals = true ; else itemEquals = false ; } if ( itemEquals ) found = true ; } return found ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static Activator getDefault ( ) { return plugin ; } public IOpentoxManager getJavaOpentoxManager ( ) { IOpentoxManager manager = null ; try { manager = ( IOpentoxManager ) javaFinderTracker . waitForService ( * ) ; } catch ( InterruptedException e ) { throw new IllegalStateException ( "" , e ) ; } if ( manager == null ) { throw new IllegalStateException ( "" ) ; } return manager ; } public IJavaScriptOpentoxManager getJavaScriptOpentoxManager ( ) { IJavaScriptOpentoxManager manager = null ; try { manager = ( IJavaScriptOpentoxManager ) jsFinderTracker . waitForService ( * ) ; } catch ( InterruptedException e ) { throw new IllegalStateException ( "" , e ) ; } if ( manager == null ) { throw new IllegalStateException ( "" ) ; } return manager ; } public static boolean login ( String user , String pass ) throws Exception { if ( Activator . token == null ) { Activator . token = new OpenSSOToken ( "" ) ; } return token . login ( user , pass ) ; } public static void logout ( ) throws Exception { if ( Activator . token == null ) return ; Activator . token . logout ( ) ; Activator . token = null ; } public static String getToken ( ) { if ( Activator . token == null ) return null ; return Activator . token . getToken ( ) ; } public static List < OpenToxService > getOpenToxServices ( ) { return openToxServices ; } public static void setOpenToxServices ( List < OpenToxService > openToxServices2 ) { openToxServices = openToxServices2 ; } public static OpenToxService getCurrentDSService ( ) { if ( openToxServices == null || openToxServices . size ( ) <= ) return null ; else return openToxServices . get ( ) ; } } package net . bioclipse . opentox ; import java . util . List ; import net . bioclipse . usermanager . IUserManagerListener ; import net . bioclipse . usermanager . UserManagerEvent ; import net . bioclipse . usermanager . business . IUserManager ; public class OpenToxLogInOutListener implements IUserManagerListener { private IUserManager userManager ; public static String myAccountType = "" ; public OpenToxLogInOutListener ( IUserManager userManager ) { this . userManager = userManager ; } @ Override public boolean receiveUserManagerEvent ( UserManagerEvent event ) { System . out . println ( "" + event ) ; boolean eventSucceeded = true ; switch ( event ) { case LOGIN : eventSucceeded = updateOnLogin ( ) ; break ; case LOGOUT : updateOnLogout ( ) ; break ; case UPDATE : eventSucceeded = update ( ) ; break ; default : break ; } return eventSucceeded ; } private boolean updateOnLogin ( ) { System . out . println ( "" ) ; System . out . println ( "" + userManager . isLoggedIn ( ) ) ; boolean loginSucceeded = false ; if ( userManager . isLoggedIn ( ) && Activator . getToken ( ) == null ) { try { System . out . println ( "" ) ; List < String > otssoAccounts = userManager . getAccountIdsByAccountTypeName ( getAccountType ( ) ) ; if ( otssoAccounts . size ( ) > ) { String account = otssoAccounts . get ( ) ; loginSucceeded = Activator . login ( userManager . getProperty ( account , "" ) , userManager . getProperty ( account , "" ) ) ; } } catch ( Exception e ) { System . out . println ( "" + e . getMessage ( ) ) ; e . printStackTrace ( ) ; loginSucceeded = false ; } } return loginSucceeded ; } private boolean update ( ) { return updateOnLogin ( ) ; } private void updateOnLogout ( ) { System . out . println ( "" ) ; System . out . println ( "" + userManager . isLoggedIn ( ) ) ; if ( ! userManager . isLoggedIn ( ) && Activator . getToken ( ) != null ) { try { System . out . println ( "" ) ; Activator . logout ( ) ; } catch ( Exception e ) { System . out . println ( "" + e . getMessage ( ) ) ; e . printStackTrace ( ) ; } } } @ Override public String getAccountType ( ) { if ( myAccountType . isEmpty ( ) ) myAccountType = "" ; return myAccountType ; } } package net . bioclipse . opentox ; public class OpenToxConstants { public static final String PREFS_SEPERATOR = "" ; public static final String SERVICES = "" ; public static final String PREFERENCES_OBJECT_DELIMITER = null ; public static final String PLUGIN_ID = "" ; } package net . bioclipse . opentox . business ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExecutableExtension ; import org . eclipse . core . runtime . IExecutableExtensionFactory ; import net . bioclipse . opentox . Activator ; public class OpentoxManagerFactory implements IExecutableExtension , IExecutableExtensionFactory { private Object manager ; public void setInitializationData ( IConfigurationElement config , String propertyName , Object data ) throws CoreException { manager = Activator . getDefault ( ) . getJavaScriptOpentoxManager ( ) ; if ( manager == null ) { throw new IllegalStateException ( "" + "" ) ; } } public Object create ( ) throws CoreException { return manager ; } } package net . bioclipse . opentox . business ; import net . bioclipse . managers . business . IBioclipseJSManager ; public interface IJavaScriptOpentoxManager extends IOpentoxManager , IBioclipseJSManager { } package net . bioclipse . opentox . business ; import java . io . BufferedReader ; import java . io . StringReader ; import java . net . URI ; import java . net . URL ; import java . net . URLEncoder ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import net . bioclipse . business . BioclipsePlatformManager ; import net . bioclipse . cdk . business . CDKManager ; import net . bioclipse . core . business . BioclipseException ; import net . bioclipse . core . domain . IMolecule ; import net . bioclipse . core . domain . IMolecule . Property ; import net . bioclipse . core . domain . IStringMatrix ; import net . bioclipse . core . domain . StringMatrix ; import net . bioclipse . jobs . IReturner ; import net . bioclipse . managers . business . IBioclipseManager ; import net . bioclipse . opentox . Activator ; import net . bioclipse . opentox . api . Algorithm ; import net . bioclipse . opentox . api . Dataset ; import net . bioclipse . opentox . api . Feature ; import net . bioclipse . opentox . api . HttpMethodHelper ; import net . bioclipse . opentox . api . Model ; import net . bioclipse . opentox . api . ModelAlgorithm ; import net . bioclipse . opentox . api . MolecularDescriptorAlgorithm ; import net . bioclipse . rdf . business . IRDFStore ; import net . bioclipse . rdf . business . RDFManager ; import org . apache . commons . httpclient . HttpClient ; import org . apache . commons . httpclient . methods . GetMethod ; import org . apache . log4j . Logger ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public class OpentoxManager implements IBioclipseManager { private static final Logger logger = Logger . getLogger ( OpentoxManager . class ) ; private RDFManager rdf = new RDFManager ( ) ; private BioclipsePlatformManager bioclipse = new BioclipsePlatformManager ( ) ; private CDKManager cdk = new CDKManager ( ) ; private final static String QUERY_ALGORITHMS = "" + "" + "" ; private final static String QUERY_MODELS = "" + "" + "" ; private final static String SPARQL_DESCRIPTORS = "" + "" + "" + "" + "" + "" ; private final static String QUERY_DATASETS = "" + "" + "" ; private final static String QUERY_FEATURES = "" + "" + "" ; private final static String QUERY_COMPOUNDS = "" + "" + "" ; public String getManagerName ( ) { return "" ; } public String getToken ( ) { return Activator . getToken ( ) ; } public void logout ( ) throws BioclipseException { try { Activator . logout ( ) ; } catch ( Exception e ) { throw new BioclipseException ( "" + e . getMessage ( ) , e ) ; } } public boolean login ( String user , String pass ) throws BioclipseException { try { return Activator . login ( user , pass ) ; } catch ( Exception e ) { throw new BioclipseException ( "" + e . getMessage ( ) , e ) ; } } public Map < String , String > getFeatureInfo ( String ontologyServer , String feature , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; Map < String , String > properties = Feature . getProperties ( ontologyServer , feature ) ; monitor . done ( ) ; return properties ; } public Map < String , String > getModelInfo ( String ontologyServer , String model , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; Map < String , String > properties = Model . getProperties ( ontologyServer , model ) ; monitor . done ( ) ; return properties ; } public Map < String , String > getAlgorithmInfo ( String ontologyServer , String algorithm , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; Map < String , String > properties = Algorithm . getProperties ( ontologyServer , algorithm ) ; monitor . done ( ) ; return properties ; } public Map < String , Map < String , String > > getFeatureInfo ( String ontologyServer , List < String > features , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , features . size ( ) ) ; Map < String , Map < String , String > > results = new HashMap < String , Map < String , String > > ( ) ; for ( String feature : features ) { results . put ( feature , Feature . getProperties ( ontologyServer , feature ) ) ; monitor . worked ( ) ; } monitor . done ( ) ; return results ; } public Map < String , Map < String , String > > getAlgorithmInfo ( String ontologyServer , List < String > algorithms , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , algorithms . size ( ) ) ; Map < String , Map < String , String > > results = new HashMap < String , Map < String , String > > ( ) ; for ( String algorithm : algorithms ) { results . put ( algorithm , Algorithm . getProperties ( ontologyServer , algorithm ) ) ; monitor . worked ( ) ; } monitor . done ( ) ; return results ; } public Map < String , Map < String , String > > getModelInfo ( String ontologyServer , List < String > features , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , features . size ( ) ) ; Map < String , Map < String , String > > results = new HashMap < String , Map < String , String > > ( ) ; for ( String feature : features ) { results . put ( feature , Model . getProperties ( ontologyServer , feature ) ) ; monitor . worked ( ) ; } monitor . done ( ) ; return results ; } public List < String > listDataSets ( String service , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; IRDFStore store = rdf . createInMemoryStore ( ) ; List < String > dataSets = Collections . emptyList ( ) ; Map < String , String > extraHeaders = new HashMap < String , String > ( ) ; String token = Activator . getToken ( ) ; if ( token != null ) { extraHeaders . put ( "" , Activator . getToken ( ) ) ; } try { rdf . importURL ( store , service + "" , extraHeaders , monitor ) ; String dump = rdf . asRDFN3 ( store ) ; System . out . println ( "" + dump ) ; monitor . worked ( ) ; IStringMatrix results = rdf . sparql ( store , QUERY_DATASETS ) ; monitor . worked ( ) ; if ( results . getRowCount ( ) > ) { dataSets = results . getColumn ( "" ) ; } monitor . worked ( ) ; } catch ( BioclipseException exception ) { throw exception ; } catch ( Exception exception ) { throw new BioclipseException ( "" + exception . getMessage ( ) , exception ) ; } monitor . done ( ) ; return dataSets ; } public List < String > listFeatures ( String service , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; IRDFStore store = rdf . createInMemoryStore ( ) ; List < String > dataSets = Collections . emptyList ( ) ; Map < String , String > extraHeaders = new HashMap < String , String > ( ) ; String token = Activator . getToken ( ) ; if ( token != null ) { extraHeaders . put ( "" , Activator . getToken ( ) ) ; } try { rdf . importURL ( store , service + "" , extraHeaders , monitor ) ; String dump = rdf . asRDFN3 ( store ) ; System . out . println ( "" + dump ) ; monitor . worked ( ) ; IStringMatrix results = rdf . sparql ( store , QUERY_FEATURES ) ; monitor . worked ( ) ; if ( results . getRowCount ( ) > ) { dataSets = results . getColumn ( "" ) ; } monitor . worked ( ) ; } catch ( BioclipseException exception ) { throw exception ; } catch ( Exception exception ) { throw new BioclipseException ( "" + exception . getMessage ( ) , exception ) ; } monitor . done ( ) ; return dataSets ; } public IStringMatrix searchDataSets ( String ontologyServer , String query , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { String sparql = "" + "" + "" + "" + query + "" + "" ; IStringMatrix results = rdf . sparqlRemote ( ontologyServer , sparql , monitor ) ; monitor . worked ( ) ; return results ; } catch ( Exception exception ) { throw new BioclipseException ( "" + ontologyServer , exception ) ; } } public IStringMatrix searchDescriptors ( String ontologyServer , String query , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { String sparql = "" + "" + "" + "" + "" + "" + "" + query + "" + "" ; IStringMatrix results = rdf . sparqlRemote ( ontologyServer , sparql , monitor ) ; System . out . println ( "" + sparql ) ; monitor . worked ( ) ; return results ; } catch ( Exception exception ) { throw new BioclipseException ( "" + ontologyServer , exception ) ; } } public IStringMatrix searchModels ( String ontologyServer , String query , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { String sparql = "" + "" + "" + "" + query + "" + "" ; IStringMatrix results = rdf . sparqlRemote ( ontologyServer , sparql , monitor ) ; System . out . println ( "" + sparql ) ; monitor . worked ( ) ; return results ; } catch ( Exception exception ) { throw new BioclipseException ( "" + ontologyServer , exception ) ; } } public List < String > listAlgorithms ( String ontologyServer , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; IStringMatrix results = new StringMatrix ( ) ; monitor . beginTask ( "" , ) ; try { results = rdf . sparqlRemote ( ontologyServer , QUERY_ALGORITHMS , monitor ) ; monitor . worked ( ) ; } catch ( Exception exception ) { throw new BioclipseException ( "" + ontologyServer , exception ) ; } monitor . done ( ) ; return results . getColumn ( "" ) ; } private IStringMatrix regex ( IStringMatrix matrix , String column , String substring ) { StringMatrix table = new StringMatrix ( ) ; int rowCount = matrix . getRowCount ( ) ; int colCount = matrix . getColumnCount ( ) ; int hitCount = ; for ( int col = ; col <= colCount ; col ++ ) { table . setColumnName ( col , matrix . getColumnName ( col ) ) ; } for ( int row = ; row <= rowCount ; row ++ ) { String algo = matrix . get ( row , column ) ; if ( algo . contains ( substring ) ) { hitCount ++ ; for ( int col = ; col <= colCount ; col ++ ) { table . set ( hitCount , col , matrix . get ( row , col ) ) ; } } } return table ; } public IStringMatrix listDescriptors ( String ontologyServer , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; IStringMatrix results = new StringMatrix ( ) ; monitor . beginTask ( "" , ) ; try { results = regex ( rdf . sparqlRemote ( ontologyServer , SPARQL_DESCRIPTORS , monitor ) , "" , "" ) ; monitor . worked ( ) ; } catch ( Exception exception ) { throw new BioclipseException ( "" + ontologyServer , exception ) ; } monitor . done ( ) ; return results ; } public List < String > listModels ( String ontologyServer , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; IStringMatrix results = new StringMatrix ( ) ; monitor . beginTask ( "" , ) ; try { results = rdf . sparqlRemote ( ontologyServer , QUERY_MODELS , monitor ) ; monitor . worked ( ) ; } catch ( Exception exception ) { throw new BioclipseException ( "" + ontologyServer , exception ) ; } monitor . done ( ) ; return results . getColumn ( "" ) ; } public List < Integer > listCompounds ( String service , Integer dataSet , IProgressMonitor monitor ) throws BioclipseException { return listCompounds ( service + "" + dataSet , monitor ) ; } public List < Integer > listCompounds ( String dataSet , IProgressMonitor monitor ) throws BioclipseException { List < Integer > compounds = new ArrayList < Integer > ( ) ; if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; IRDFStore store = rdf . createInMemoryStore ( ) ; try { Map < String , String > extraHeaders = new HashMap < String , String > ( ) ; String token = Activator . getToken ( ) ; if ( token != null ) { extraHeaders . put ( "" , Activator . getToken ( ) ) ; } rdf . importURL ( store , dataSet + "" , extraHeaders , monitor ) ; monitor . worked ( ) ; System . out . println ( rdf . dump ( store ) ) ; IStringMatrix results = rdf . sparql ( store , QUERY_COMPOUNDS ) ; monitor . worked ( ) ; if ( results . getRowCount ( ) > ) { for ( String compound : results . getColumn ( "" ) ) { compounds . add ( Integer . valueOf ( compound . substring ( compound . lastIndexOf ( '' ) + ) ) ) ; } } monitor . worked ( ) ; } catch ( BioclipseException exception ) { throw exception ; } catch ( Exception exception ) { throw new BioclipseException ( "" , exception ) ; } monitor . done ( ) ; return compounds ; } public String downloadCompoundAsMDLMolfile ( String service , String dataSet , Integer compound , IProgressMonitor monitor ) throws BioclipseException { return downloadCompoundAsMDLMolfile ( dataSet + "" + compound , monitor ) ; } public String downloadCompoundAsMDLMolfile ( String compoundURI , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; String result = bioclipse . download ( compoundURI , "" , monitor ) ; monitor . done ( ) ; return result ; } public IFile downloadDataSetAsMDLSDfile ( String service , String dataSet , IFile file , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; Map < String , String > extraHeaders = null ; if ( getToken ( ) != null ) { extraHeaders = new HashMap < String , String > ( ) ; extraHeaders . put ( "" , getToken ( ) ) ; } IFile result = bioclipse . downloadAsFile ( dataSet , "" , file , extraHeaders , monitor ) ; monitor . done ( ) ; return result ; } public void createDataset ( String service , IReturner < String > returner , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { String dataset = Dataset . createNewDataset ( service , monitor ) ; monitor . done ( ) ; returner . completeReturn ( dataset ) ; } catch ( Exception exc ) { throw new BioclipseException ( "" + exc . getMessage ( ) ) ; } } public void createDataset ( String service , List < IMolecule > molecules , IReturner < String > returner , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { String dataset = Dataset . createNewDataset ( service , molecules , monitor ) ; monitor . done ( ) ; returner . completeReturn ( dataset ) ; } catch ( Exception exc ) { throw new BioclipseException ( "" + exc . getMessage ( ) ) ; } } public void createDataset ( String service , IMolecule molecule , IReturner < String > returner , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { String dataset = Dataset . createNewDataset ( service , molecule , monitor ) ; monitor . done ( ) ; returner . completeReturn ( dataset ) ; } catch ( Exception exc ) { throw new BioclipseException ( "" + exc . getMessage ( ) ) ; } } public void addMolecule ( String datasetURI , IMolecule mol , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { Dataset . addMolecule ( datasetURI , mol ) ; monitor . done ( ) ; } catch ( Exception exc ) { throw new BioclipseException ( "" + exc . getMessage ( ) ) ; } } public void addMolecules ( String datasetURI , List < IMolecule > molecules , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { Dataset . addMolecules ( datasetURI , molecules ) ; monitor . done ( ) ; } catch ( Exception exc ) { throw new BioclipseException ( "" + exc . getMessage ( ) ) ; } } public void deleteDataset ( String datasetURI ) throws BioclipseException { try { Dataset . deleteDataset ( datasetURI ) ; } catch ( Exception exc ) { throw new BioclipseException ( "" + exc . getMessage ( ) ) ; } } public void setDatasetLicense ( String datasetURI , String license , IProgressMonitor monitor ) throws Exception { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; new URI ( license ) ; monitor . worked ( ) ; Dataset . setLicense ( datasetURI , license ) ; monitor . worked ( ) ; monitor . done ( ) ; } public void setDatasetRightsHolder ( String datasetURI , String holder , IProgressMonitor monitor ) throws Exception { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; new URI ( holder ) ; monitor . worked ( ) ; Dataset . setRightsHolder ( datasetURI , holder ) ; monitor . worked ( ) ; monitor . done ( ) ; } public void setDatasetTitle ( String datasetURI , String title , IProgressMonitor monitor ) throws Exception { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; monitor . worked ( ) ; Dataset . setTitle ( datasetURI , title ) ; monitor . worked ( ) ; monitor . done ( ) ; } public List < String > calculateDescriptor ( String service , String descriptor , List < IMolecule > molecules , IProgressMonitor monitor ) throws Exception { if ( service == null ) throw new BioclipseException ( "" ) ; if ( descriptor == null ) throw new BioclipseException ( "" ) ; if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , molecules . size ( ) ) ; List < String > calcResults = new ArrayList < String > ( ) ; for ( IMolecule molecule : molecules ) { String dataset = Dataset . createNewDataset ( service , molecule , monitor ) ; if ( monitor . isCanceled ( ) ) continue ; String results = MolecularDescriptorAlgorithm . calculate ( service , descriptor , dataset , monitor ) ; if ( monitor . isCanceled ( ) ) continue ; StringMatrix features = Dataset . listPredictedFeatures ( results ) ; calcResults . addAll ( removeDataType ( features . getColumn ( "" ) ) ) ; Dataset . deleteDataset ( dataset ) ; monitor . worked ( ) ; } return calcResults ; } public List < String > calculateDescriptor ( String service , String descriptor , IMolecule molecule , IProgressMonitor monitor ) throws Exception { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; List < String > calcResults = new ArrayList < String > ( ) ; logger . debug ( "" ) ; String dataset = Dataset . createNewDataset ( service , molecule , monitor ) ; logger . debug ( "" ) ; if ( monitor . isCanceled ( ) ) return Collections . emptyList ( ) ; String results = MolecularDescriptorAlgorithm . calculate ( service , descriptor , dataset , monitor ) ; if ( monitor . isCanceled ( ) ) return Collections . emptyList ( ) ; logger . debug ( "" ) ; StringMatrix features = Dataset . listPredictedFeatures ( results ) ; logger . debug ( "" + features ) ; calcResults . addAll ( removeDataType ( features . getColumn ( "" ) ) ) ; logger . debug ( "" ) ; Dataset . deleteDataset ( dataset ) ; monitor . worked ( ) ; return calcResults ; } public List < String > predictWithModel ( String service , String model , List < IMolecule > molecules , IProgressMonitor monitor ) throws Exception { if ( service == null ) throw new BioclipseException ( "" ) ; if ( model == null ) throw new BioclipseException ( "" ) ; if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , molecules . size ( ) ) ; List < String > calcResults = new ArrayList < String > ( ) ; for ( IMolecule molecule : molecules ) { String dataset = Dataset . createNewDataset ( service , molecule , monitor ) ; if ( monitor . isCanceled ( ) ) return calcResults ; String results = ModelAlgorithm . calculate ( service , model , dataset , monitor ) ; if ( monitor . isCanceled ( ) ) return calcResults ; StringMatrix features = Dataset . listPredictedFeatures ( results ) ; calcResults . addAll ( removeDataType ( features . getColumn ( "" ) ) ) ; Dataset . deleteDataset ( dataset ) ; monitor . worked ( ) ; } return calcResults ; } public Map < String , String > predictWithModelWithLabel ( String service , String model , List < IMolecule > molecules , IProgressMonitor monitor ) throws Exception { if ( service == null ) throw new BioclipseException ( "" ) ; if ( model == null ) throw new BioclipseException ( "" ) ; if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , molecules . size ( ) ) ; Map < String , String > calcResults = new HashMap < String , String > ( ) ; for ( IMolecule molecule : molecules ) { String dataset = Dataset . createNewDataset ( service , molecule , monitor ) ; if ( monitor . isCanceled ( ) ) return calcResults ; String results = ModelAlgorithm . calculate ( service , model , dataset , monitor ) ; if ( monitor . isCanceled ( ) ) return calcResults ; StringMatrix features = Dataset . listPredictedFeatures ( results ) ; List < String > fcol = removeDataType ( features . getColumn ( "" ) ) ; List < String > lcol = features . getColumn ( "" ) ; for ( int i = ; i < fcol . size ( ) ; i ++ ) { calcResults . put ( lcol . get ( i ) , fcol . get ( i ) ) ; } Dataset . deleteDataset ( dataset ) ; monitor . worked ( ) ; } return calcResults ; } public List < String > predictWithModel ( String service , String model , IMolecule molecule , IProgressMonitor monitor ) throws Exception { if ( service == null ) throw new BioclipseException ( "" ) ; if ( model == null ) throw new BioclipseException ( "" ) ; if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; List < String > calcResults = new ArrayList < String > ( ) ; String dataset = Dataset . createNewDataset ( service , molecule , monitor ) ; if ( monitor . isCanceled ( ) ) return calcResults ; String results = ModelAlgorithm . calculate ( service , model , dataset , monitor ) ; if ( monitor . isCanceled ( ) ) return calcResults ; StringMatrix features = Dataset . listPredictedFeatures ( results ) ; calcResults . addAll ( removeDataType ( features . getColumn ( "" ) ) ) ; Dataset . deleteDataset ( dataset ) ; monitor . worked ( ) ; return calcResults ; } public Map < String , String > predictWithModelWithLabel ( String service , String model , IMolecule molecule , IProgressMonitor monitor ) throws Exception { if ( service == null ) throw new BioclipseException ( "" ) ; if ( model == null ) throw new BioclipseException ( "" ) ; if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; Map < String , String > calcResults = new HashMap < String , String > ( ) ; String dataset = Dataset . createNewDataset ( service , molecule , monitor ) ; if ( monitor . isCanceled ( ) ) return calcResults ; String results = ModelAlgorithm . calculate ( service , model , dataset , monitor ) ; if ( monitor . isCanceled ( ) ) return calcResults ; StringMatrix features = Dataset . listPredictedFeatures ( results ) ; if ( features . getRowCount ( ) > ) { List < String > fcol = removeDataType ( features . getColumn ( "" ) ) ; List < String > lcol = features . getColumn ( "" ) ; for ( int i = ; i < lcol . size ( ) ; i ++ ) { calcResults . put ( lcol . get ( i ) , fcol . get ( i ) ) ; } } Dataset . deleteDataset ( dataset ) ; monitor . worked ( ) ; return calcResults ; } private List < String > removeDataType ( List < String > column ) { List < String > cleanedData = new ArrayList < String > ( column . size ( ) ) ; for ( String value : column ) { if ( value . contains ( "" ) ) { value = value . substring ( , value . indexOf ( "" ) ) ; } cleanedData . add ( value ) ; } return cleanedData ; } public List < String > search ( String service , IMolecule molecule ) throws BioclipseException { String inchi = cdk . asCDKMolecule ( molecule ) . getInChI ( Property . USE_CACHED_OR_CALCULATED ) ; return search ( service , inchi ) ; } @ SuppressWarnings ( "" ) public List < String > search ( String service , String inchi ) throws BioclipseException { try { URL searchURL = new URL ( normalizeURI ( service ) + "" + URLEncoder . encode ( inchi , "" ) ) ; HttpClient client = new HttpClient ( ) ; GetMethod method = new GetMethod ( searchURL . toString ( ) ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; client . executeMethod ( method ) ; List < String > compounds = new ArrayList < String > ( ) ; BufferedReader reader = new BufferedReader ( new StringReader ( method . getResponseBodyAsString ( ) ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . length ( ) > ) compounds . add ( line ) ; } reader . close ( ) ; method . releaseConnection ( ) ; return compounds ; } catch ( Exception exception ) { throw new BioclipseException ( "" , exception ) ; } } public String createModel ( String algoURI , String datasetURI , List < String > featureURIs , String predictionFeatureURI , IProgressMonitor monitor ) throws BioclipseException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; String modelURI ; try { modelURI = ModelAlgorithm . createModel ( algoURI , datasetURI , featureURIs , predictionFeatureURI , monitor ) ; return modelURI ; } catch ( Exception exception ) { throw new BioclipseException ( "" + exception . getMessage ( ) , exception ) ; } } private static String normalizeURI ( String datasetURI ) { datasetURI = datasetURI . replaceAll ( "" , "" ) ; datasetURI = datasetURI . replaceAll ( "" , "" ) ; if ( ! datasetURI . endsWith ( "" ) ) datasetURI += "" ; return datasetURI ; } } package net . bioclipse . opentox . business ; import java . util . List ; import java . util . Map ; import net . bioclipse . core . PublishedClass ; import net . bioclipse . core . PublishedMethod ; import net . bioclipse . core . Recorded ; import net . bioclipse . core . business . BioclipseException ; import net . bioclipse . core . domain . IMolecule ; import net . bioclipse . core . domain . IStringMatrix ; import net . bioclipse . jobs . BioclipseUIJob ; import net . bioclipse . managers . business . IBioclipseManager ; @ PublishedClass ( value = "" , doi = { "" , "" } ) public interface IOpentoxManager extends IBioclipseManager { @ Recorded @ PublishedMethod ( methodSummary = "" ) public String getToken ( ) ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public boolean login ( String user , String password ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" ) public void logout ( ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > listModels ( String ontologyServer ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > calculateDescriptor ( String service , String descriptor , List < ? extends IMolecule > molecules ) throws Exception ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > calculateDescriptor ( String service , String descriptor , IMolecule molecule ) throws Exception ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > predictWithModel ( String service , String model , List < ? extends IMolecule > molecules ) ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > predictWithModel ( String service , String model , IMolecule molecule ) throws Exception ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public Map < String , String > predictWithModelWithLabel ( String service , String model , List < ? extends IMolecule > molecules ) throws Exception ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public Map < String , String > predictWithModelWithLabel ( String service , String model , IMolecule molecule ) ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public Map < String , String > getFeatureInfo ( String ontologyServer , String feature ) ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public Map < String , Map < String , String > > getFeatureInfo ( String ontologyServer , List < String > features ) ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public Map < String , String > getModelInfo ( String ontologyServer , String model ) ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public Map < String , Map < String , String > > getModelInfo ( String ontologyServer , List < String > models ) ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public Map < String , String > getAlgorithmInfo ( String ontologyServer , String algorithm ) ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public Map < String , Map < String , String > > getAlgorithmInfo ( String ontologyServer , List < String > algorithms ) ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public List < String > listAlgorithms ( String ontologyServer ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public IStringMatrix listDescriptors ( String ontologyServer ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > listDataSets ( String service ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > listFeatures ( String service ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public IStringMatrix searchDataSets ( String ontologyServer , String query ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public IStringMatrix searchDescriptors ( String ontologyServer , String query ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public IStringMatrix searchModels ( String ontologyServer , String query ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public String createDataset ( String service ) throws BioclipseException ; public void createDataset ( String service , BioclipseUIJob < String > uiJob ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public String createDataset ( String service , List < ? extends IMolecule > molecules ) throws BioclipseException ; public void createDataset ( String service , List < ? extends IMolecule > molecules , BioclipseUIJob < String > uiJob ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public String createDataset ( String service , IMolecule molecule ) throws BioclipseException ; public void createDataset ( String service , IMolecule molecule , BioclipseUIJob < String > uiJob ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public String setDatasetLicense ( String datasetURI , String license ) throws Exception ; public void setDatasetLicense ( String datasetURI , String license , BioclipseUIJob < String > uiJob ) throws Exception ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public String setDatasetRightsHolder ( String datasetURI , String holder ) throws Exception ; public void setDatasetRightsHolder ( String datasetURI , String holder , BioclipseUIJob < String > uiJob ) throws Exception ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public String setDatasetTitle ( String datasetURI , String title ) throws Exception ; public void setDatasetTitle ( String datasetURI , String title , BioclipseUIJob < String > uiJob ) throws Exception ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public void addMolecule ( String datasetURI , IMolecule mol ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public void addMolecules ( String datasetURI , List < ? extends IMolecule > molecules ) ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public void deleteDataset ( String datasetURI ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < Integer > listCompounds ( String service , Integer dataSet ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > listCompounds ( String dataSet ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public String downloadCompoundAsMDLMolfile ( String service , String dataSet , Integer compound ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public String downloadCompoundAsMDLMolfile ( String compoundURI ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" , params = "" ) public String downloadDataSetAsMDLSDfile ( String service , String dataSet , String filename ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > search ( String service , IMolecule molecule ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" , params = "" ) public List < String > search ( String service , String inchi ) throws BioclipseException ; @ Recorded @ PublishedMethod ( methodSummary = "" + "" + "" , params = "" ) public String createModel ( String algoURI , String datasetURI , List < String > featureURIs , String predictionFeatureURI ) throws BioclipseException ; } package net . bioclipse . opentox . business ; public interface IJavaOpentoxManager extends IOpentoxManager { } package net . bioclipse . opentox . api ; import java . util . HashMap ; import java . util . Map ; import net . bioclipse . core . domain . IStringMatrix ; import net . bioclipse . rdf . business . RDFManager ; public abstract class Model { private static RDFManager rdf = new RDFManager ( ) ; public static Map < String , String > getProperties ( String ontologyServer , String feature ) { String propertiesQuery = "" + "" + feature + "" + "" ; Map < String , String > properties = new HashMap < String , String > ( ) ; IStringMatrix matrix = rdf . sparqlRemote ( ontologyServer , propertiesQuery , null ) ; for ( int i = ; i < matrix . getRowCount ( ) ; i ++ ) { String predicate = matrix . get ( i , "" ) ; String value = matrix . get ( i , "" ) ; if ( predicate != null && predicate . length ( ) > && value != null && value . length ( ) > ) properties . put ( predicate , value ) ; } return properties ; } } package net . bioclipse . opentox . api ; import java . io . IOException ; import java . security . GeneralSecurityException ; import java . util . HashMap ; import java . util . List ; import org . apache . commons . httpclient . HttpClient ; import org . apache . commons . httpclient . HttpException ; import org . apache . commons . httpclient . methods . PostMethod ; import org . apache . log4j . Logger ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public abstract class ModelAlgorithm extends Algorithm { private static final Logger logger = Logger . getLogger ( ModelAlgorithm . class ) ; @ SuppressWarnings ( "" ) public static String calculate ( String service , String model , String dataSetURI , IProgressMonitor monitor ) throws HttpException , IOException , InterruptedException , GeneralSecurityException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; int worked = ; HttpClient client = new HttpClient ( ) ; dataSetURI = Dataset . normalizeURI ( dataSetURI ) ; PostMethod method = new PostMethod ( model ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; method . setParameter ( "" , dataSetURI ) ; method . setParameter ( "" , service + "" ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; String dataset = "" ; String responseString = method . getResponseBodyAsString ( ) ; logger . debug ( "" + status ) ; int tailing = ; if ( status == || status == ) { if ( responseString . contains ( "" ) ) { String task = responseString ; logger . debug ( "" + task ) ; Thread . sleep ( andABit ( ) ) ; TaskState state = Task . getState ( task ) ; while ( ! state . isFinished ( ) && ! monitor . isCanceled ( ) ) { int onlineWorked = ( int ) state . getPercentageCompleted ( ) ; if ( onlineWorked > worked ) { monitor . worked ( onlineWorked - worked ) ; worked = onlineWorked ; } int waitingTime = andABit ( * tailing ) ; logger . debug ( "" + waitingTime + "" ) ; waitUnlessInterrupted ( waitingTime , monitor ) ; state = Task . getState ( task ) ; if ( state . isRedirected ( ) ) { task = state . getResults ( ) ; logger . debug ( "" + task ) ; } if ( tailing < ) tailing ++ ; } if ( monitor . isCanceled ( ) ) Task . delete ( task ) ; dataset = state . getResults ( ) ; } else { dataset = responseString ; logger . debug ( "" + dataset ) ; monitor . worked ( ) ; } } else if ( status == ) { throw new GeneralSecurityException ( "" ) ; } else if ( status == ) { throw new GeneralSecurityException ( "" ) ; } else if ( status == ) { logger . debug ( "" + responseString ) ; throw new UnsupportedOperationException ( "" ) ; } else { logger . debug ( "" + status + "" + responseString ) ; throw new IllegalStateException ( "" + status ) ; } method . releaseConnection ( ) ; dataset = dataset . replaceAll ( "" , "" ) ; return dataset ; } @ SuppressWarnings ( "" ) public static String createModel ( String algoURI , String datasetURI , List < String > featureURIs , String predictionFeatureURI , IProgressMonitor monitor ) throws HttpException , IOException , InterruptedException , GeneralSecurityException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; int worked = ; HttpClient client = new HttpClient ( ) ; PostMethod method = new PostMethod ( algoURI ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; datasetURI = datasetURI + "" + asFeatureURIString ( featureURIs ) + "" ; logger . debug ( "" + datasetURI ) ; method . setParameter ( "" , datasetURI ) ; method . setParameter ( "" , predictionFeatureURI ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; String modelURI = "" ; String responseString = method . getResponseBodyAsString ( ) ; logger . debug ( "" + status ) ; int tailing = ; if ( status == || status == ) { if ( responseString . contains ( "" ) ) { String task = responseString ; logger . debug ( "" + task ) ; Thread . sleep ( andABit ( ) ) ; TaskState state = Task . getState ( task ) ; while ( ! state . isFinished ( ) && ! monitor . isCanceled ( ) ) { int onlineWorked = ( int ) state . getPercentageCompleted ( ) ; if ( onlineWorked > worked ) { monitor . worked ( onlineWorked - worked ) ; worked = onlineWorked ; } int waitingTime = andABit ( * tailing ) ; logger . debug ( "" + waitingTime + "" ) ; waitUnlessInterrupted ( waitingTime , monitor ) ; state = Task . getState ( task ) ; if ( state . isRedirected ( ) ) { task = state . getResults ( ) ; logger . debug ( "" + task ) ; } if ( tailing < ) tailing ++ ; } if ( monitor . isCanceled ( ) ) Task . delete ( task ) ; modelURI = state . getResults ( ) ; } else { modelURI = responseString ; logger . debug ( "" + modelURI ) ; monitor . worked ( ) ; } } else if ( status == ) { throw new GeneralSecurityException ( "" ) ; } else if ( status == ) { throw new GeneralSecurityException ( "" ) ; } else if ( status == ) { logger . debug ( "" + responseString ) ; throw new UnsupportedOperationException ( "" ) ; } else { logger . debug ( "" + status + "" + responseString ) ; throw new IllegalStateException ( "" + status ) ; } method . releaseConnection ( ) ; modelURI = modelURI . replaceAll ( "" , "" ) ; return modelURI ; } private static String asFeatureURIString ( List < String > featureURIs ) { if ( featureURIs == null || featureURIs . size ( ) == ) return "" ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < featureURIs . size ( ) ; i ++ ) { String feature = featureURIs . get ( i ) ; buffer . append ( "" ) . append ( feature ) ; if ( ( i + ) < featureURIs . size ( ) ) buffer . append ( "" ) ; } return buffer . toString ( ) ; } private static void waitUnlessInterrupted ( int waitingTime , IProgressMonitor monitor ) throws InterruptedException { int passed = ; final int step = ; while ( passed < waitingTime && ! monitor . isCanceled ( ) ) { Thread . sleep ( step ) ; passed += step ; } } private static int andABit ( int minimum ) { return ( minimum + ( int ) Math . round ( minimum * Math . random ( ) ) ) ; } } package net . bioclipse . opentox . api ; import java . io . IOException ; import java . io . InputStream ; import java . security . GeneralSecurityException ; import java . util . HashMap ; import net . bioclipse . core . business . BioclipseException ; import net . bioclipse . core . domain . StringMatrix ; import net . bioclipse . opentox . Activator ; import net . bioclipse . opentox . api . TaskState . STATUS ; import net . bioclipse . rdf . business . IRDFStore ; import net . bioclipse . rdf . business . RDFManager ; import org . apache . commons . httpclient . HttpClient ; import org . apache . commons . httpclient . methods . DeleteMethod ; import org . apache . commons . httpclient . methods . GetMethod ; import org . apache . log4j . Logger ; public class Task { private static final Logger logger = Logger . getLogger ( Task . class ) ; private static RDFManager rdf = new RDFManager ( ) ; private final static String QUERY_TASK_DETAILS = "" + "" + "" + "" + "" + "" + "" ; private final static String QUERY_ERROR_REPORT = "" + "" + "" + "" + "" + "" ; public static void delete ( String task ) throws IOException , GeneralSecurityException { HttpClient client = new HttpClient ( ) ; DeleteMethod method = new DeleteMethod ( task ) ; method . getParams ( ) . setParameter ( "" , new Integer ( Activator . TIME_OUT ) ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; switch ( status ) { case : break ; case : throw new GeneralSecurityException ( "" ) ; case : break ; case : throw new IOException ( "" ) ; default : throw new IOException ( "" + status ) ; } } @ SuppressWarnings ( "" ) public static TaskState getState ( String task ) throws IOException { HttpClient client = new HttpClient ( ) ; GetMethod method = new GetMethod ( task ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; method . getParams ( ) . setParameter ( "" , new Integer ( Activator . TIME_OUT ) ) ; method . setRequestHeader ( "" , "" ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; logger . debug ( "" + status ) ; TaskState state = new TaskState ( ) ; logger . debug ( "" + task ) ; logger . debug ( "" + status ) ; InputStream result = method . getResponseBodyAsStream ( ) ; switch ( status ) { case : logger . error ( "" + task ) ; state . setExists ( false ) ; break ; case : if ( result == null ) throw new IOException ( "" + task ) ; state . setFinished ( true ) ; state . setResults ( getResultSetURI ( createStore ( result ) ) ) ; break ; case : state . setFinished ( true ) ; state . setRedirected ( true ) ; state . setResults ( getResultSetURI ( createStore ( result ) ) ) ; break ; case : state . setFinished ( false ) ; state . setPercentageCompleted ( getPercentageCompleted ( createStore ( result ) ) ) ; break ; case : state . setFinished ( true ) ; state . setStatus ( STATUS . ERROR ) ; IRDFStore store = createStore ( result ) ; try { logger . debug ( "" + rdf . asRDFN3 ( store ) ) ; } catch ( BioclipseException e ) { } String error = getErrorMessage ( store ) ; throw new IllegalStateException ( "" + task + "" + error ) ; default : logger . error ( "" + status + "" + task ) ; logger . debug ( "" + result ) ; throw new IllegalStateException ( "" + status + "" + method . getStatusText ( ) ) ; } method . releaseConnection ( ) ; return state ; } private static String getErrorMessage ( IRDFStore store ) { try { StringMatrix matrix = rdf . sparql ( store , QUERY_ERROR_REPORT ) ; logger . debug ( "" + matrix ) ; if ( matrix != null && matrix . getRowCount ( ) != && matrix . hasColumn ( "" ) ) { String message = matrix . get ( , "" ) ; if ( message . contains ( "" ) ) message = message . substring ( , message . lastIndexOf ( "" ) ) ; return message ; } } catch ( Exception e ) { logger . debug ( "" + e . getMessage ( ) ) ; } return "" ; } private static float getPercentageCompleted ( IRDFStore store ) { try { StringMatrix matrix = rdf . sparql ( store , QUERY_TASK_DETAILS ) ; if ( matrix != null && matrix . getRowCount ( ) != && matrix . hasColumn ( "" ) ) { String floatStr = matrix . get ( , "" ) ; if ( floatStr . contains ( "" ) ) floatStr = floatStr . substring ( , floatStr . indexOf ( "" ) ) ; logger . debug ( "" + floatStr ) ; return Float . parseFloat ( floatStr ) ; } else { return ; } } catch ( Exception e ) { logger . debug ( "" + e . getMessage ( ) ) ; } return ; } private static IRDFStore createStore ( InputStream rdfResults ) { IRDFStore store = rdf . createInMemoryStore ( ) ; try { return rdf . importFromStream ( store , rdfResults , "" , null ) ; } catch ( Exception e ) { logger . debug ( "" + e . getMessage ( ) ) ; logger . debug ( e ) ; } throw new IllegalStateException ( "" + rdfResults ) ; } private static String getResultSetURI ( IRDFStore store ) { try { StringMatrix matrix = rdf . sparql ( store , QUERY_TASK_DETAILS ) ; if ( matrix != null && matrix . getRowCount ( ) != && matrix . hasColumn ( "" ) ) { String uri = matrix . get ( , "" ) ; if ( uri . contains ( "" ) ) uri = uri . substring ( , uri . indexOf ( "" ) ) ; logger . debug ( "" + uri ) ; return uri ; } } catch ( Exception e ) { logger . debug ( "" + e . getMessage ( ) ) ; logger . debug ( e ) ; } throw new IllegalStateException ( "" ) ; } } package net . bioclipse . opentox . api ; import java . util . HashMap ; import java . util . Map ; import net . bioclipse . core . domain . IStringMatrix ; import net . bioclipse . rdf . business . RDFManager ; public class Feature { private static RDFManager rdf = new RDFManager ( ) ; public static Map < String , String > getProperties ( String ontologyServer , String feature ) { String propertiesQuery = "" + "" + feature + "" + "" ; Map < String , String > properties = new HashMap < String , String > ( ) ; IStringMatrix matrix = rdf . sparqlRemote ( ontologyServer , propertiesQuery , null ) ; for ( int i = ; i < matrix . getRowCount ( ) ; i ++ ) { String predicate = matrix . get ( i , "" ) ; String value = matrix . get ( i , "" ) ; if ( predicate != null && predicate . length ( ) > && value != null && value . length ( ) > ) properties . put ( predicate , value ) ; } return properties ; } public static void main ( String [ ] args ) { Feature . getProperties ( "" , "" ) ; } } package net . bioclipse . opentox . api ; import java . util . HashMap ; import java . util . Map ; import net . bioclipse . core . domain . IStringMatrix ; import net . bioclipse . rdf . business . RDFManager ; public abstract class Algorithm { private static RDFManager rdf = new RDFManager ( ) ; public static Map < String , String > getProperties ( String ontologyServer , String feature ) { String propertiesQuery = "" + "" + feature + "" + "" ; Map < String , String > properties = new HashMap < String , String > ( ) ; IStringMatrix matrix = rdf . sparqlRemote ( ontologyServer , propertiesQuery , null ) ; for ( int i = ; i < matrix . getRowCount ( ) ; i ++ ) { String predicate = matrix . get ( i , "" ) ; String value = matrix . get ( i , "" ) ; if ( predicate != null && predicate . length ( ) > && value != null && value . length ( ) > ) properties . put ( predicate , value ) ; } return properties ; } } package net . bioclipse . opentox . api ; import java . util . Map ; import net . bioclipse . opentox . Activator ; import org . apache . commons . httpclient . HttpMethodBase ; public class HttpMethodHelper { public static HttpMethodBase addMethodHeaders ( HttpMethodBase method , Map < String , String > extraHeaders ) { method . getParams ( ) . setParameter ( "" , new Integer ( Activator . TIME_OUT ) ) ; if ( Activator . getToken ( ) != null ) { method . setRequestHeader ( "" , Activator . getToken ( ) ) ; } if ( extraHeaders != null ) { for ( String header : extraHeaders . keySet ( ) ) { method . setRequestHeader ( header , extraHeaders . get ( header ) ) ; } } return method ; } } package net . bioclipse . opentox . api ; public class TaskState { enum STATUS { CANCELLED , COMPLETED , RUNNING , ERROR , UNKNOWN } private STATUS status = STATUS . UNKNOWN ; private boolean exists = false ; private boolean isRedirected = false ; private String results = null ; private float percentageCompleted = ; public boolean isFinished ( ) { return status == STATUS . ERROR || status == STATUS . COMPLETED ; } public void setStatus ( STATUS status ) { this . status = status ; } public STATUS getStatus ( ) { return this . status ; } public void setFinished ( boolean isFinished ) { if ( isFinished ) { this . status = STATUS . COMPLETED ; } else { this . status = STATUS . RUNNING ; } } public boolean isRedirected ( ) { return isRedirected ; } public void setRedirected ( boolean isRedirected ) { this . isRedirected = isRedirected ; } public String getResults ( ) { return results ; } public void setResults ( String results ) { this . results = results ; } public void setExists ( boolean exists ) { this . exists = exists ; } public boolean exists ( ) { return exists ; } public void setPercentageCompleted ( float percentageCompleted ) { this . percentageCompleted = percentageCompleted ; } public float getPercentageCompleted ( ) { return percentageCompleted ; } } package net . bioclipse . opentox . api ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . StringReader ; import java . io . StringWriter ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import net . bioclipse . cdk . business . CDKManager ; import net . bioclipse . core . business . BioclipseException ; import net . bioclipse . core . domain . IMolecule ; import net . bioclipse . core . domain . StringMatrix ; import net . bioclipse . rdf . business . IRDFStore ; import net . bioclipse . rdf . business . RDFManager ; import org . apache . commons . httpclient . HttpClient ; import org . apache . commons . httpclient . methods . DeleteMethod ; import org . apache . commons . httpclient . methods . GetMethod ; import org . apache . commons . httpclient . methods . PostMethod ; import org . apache . commons . httpclient . methods . PutMethod ; import org . apache . commons . httpclient . util . URIUtil ; import org . apache . log4j . Logger ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . openscience . cdk . AtomContainer ; import org . openscience . cdk . io . SDFWriter ; public class Dataset { private static final Logger logger = Logger . getLogger ( Dataset . class ) ; private final static String QUERY_PREDICTED_FEATURES = "" + "" + "" + "" + "" + "" + "" + "" ; static CDKManager cdk = new CDKManager ( ) ; static RDFManager rdf = new RDFManager ( ) ; @ SuppressWarnings ( "" ) public static List < String > getListOfAvailableDatasets ( String service ) throws IOException { HttpClient client = new HttpClient ( ) ; GetMethod method = new GetMethod ( service + "" ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; client . executeMethod ( method ) ; List < String > datasets = new ArrayList < String > ( ) ; BufferedReader reader = new BufferedReader ( new StringReader ( method . getResponseBodyAsString ( ) ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . length ( ) > ) datasets . add ( line ) ; } reader . close ( ) ; method . releaseConnection ( ) ; return datasets ; } public static String normalizeURI ( String datasetURI ) { datasetURI = datasetURI . replaceAll ( "" , "" ) ; datasetURI = datasetURI . replaceAll ( "" , "" ) ; if ( ! datasetURI . endsWith ( "" ) ) datasetURI += "" ; return datasetURI ; } @ SuppressWarnings ( "" ) public static List < String > getCompoundList ( String datasetURI ) throws IOException { HttpClient client = new HttpClient ( ) ; datasetURI = normalizeURI ( datasetURI ) ; GetMethod method = new GetMethod ( datasetURI + "" ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; client . executeMethod ( method ) ; List < String > compounds = new ArrayList < String > ( ) ; BufferedReader reader = new BufferedReader ( new StringReader ( method . getResponseBodyAsString ( ) ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . length ( ) > ) compounds . add ( line ) ; } reader . close ( ) ; method . releaseConnection ( ) ; return compounds ; } @ SuppressWarnings ( "" ) public static StringMatrix listPredictedFeatures ( String datasetURI ) throws Exception { logger . debug ( "" + datasetURI ) ; datasetURI = datasetURI . replaceAll ( "" , "" ) ; if ( datasetURI . contains ( "" ) ) { String baseURI = datasetURI . substring ( , datasetURI . indexOf ( "" ) ) ; String featureURIs = datasetURI . substring ( datasetURI . indexOf ( "" ) + ) ; featureURIs = URIUtil . decode ( featureURIs ) ; String fullURI = baseURI + "" + featureURIs ; datasetURI = URIUtil . encodeQuery ( fullURI ) ; } HttpClient client = new HttpClient ( ) ; GetMethod method = new GetMethod ( datasetURI ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; client . executeMethod ( method ) ; String result = method . getResponseBodyAsString ( ) ; IRDFStore store = rdf . createInMemoryStore ( ) ; rdf . importFromStream ( store , method . getResponseBodyAsStream ( ) , "" , null ) ; method . releaseConnection ( ) ; String dump = rdf . asRDFN3 ( store ) ; StringMatrix matrix = rdf . sparql ( store , QUERY_PREDICTED_FEATURES ) ; return matrix ; } public static void deleteDataset ( String datasetURI ) throws Exception { HttpClient client = new HttpClient ( ) ; DeleteMethod method = new DeleteMethod ( datasetURI ) ; HttpMethodHelper . addMethodHeaders ( method , null ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; method . releaseConnection ( ) ; if ( status == ) throw new IllegalArgumentException ( "" ) ; if ( status == ) throw new IllegalStateException ( "" + status ) ; } public static void addMolecule ( String datasetURI , IMolecule mol ) throws Exception { StringWriter strWriter = new StringWriter ( ) ; SDFWriter writer = new SDFWriter ( strWriter ) ; writer . write ( cdk . asCDKMolecule ( mol ) . getAtomContainer ( ) ) ; writer . close ( ) ; addMolecules ( datasetURI , strWriter . toString ( ) , null ) ; } public static void addMolecules ( String datasetURI , List < IMolecule > mols ) throws Exception { StringWriter strWriter = new StringWriter ( ) ; SDFWriter writer = new SDFWriter ( strWriter ) ; for ( IMolecule mol : mols ) { writer . write ( cdk . asCDKMolecule ( mol ) . getAtomContainer ( ) ) ; } writer . close ( ) ; addMolecules ( datasetURI , strWriter . toString ( ) , null ) ; } public static void setMetadata ( String datasetURI , String predicate , String value ) throws Exception { HttpClient client = new HttpClient ( ) ; PutMethod method = new PutMethod ( normalizeURI ( datasetURI ) + "" ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; String triples = "" + datasetURI + "" + "" + "" + datasetURI + "" + predicate + "" + value + "" ; System . out . println ( "" + triples ) ; method . setRequestBody ( triples ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; if ( status == ) { String response = method . getResponseBodyAsString ( ) ; System . out . println ( "" + response ) ; } else if ( status == ) { String task = method . getResponseBodyAsString ( ) ; Thread . sleep ( ) ; TaskState state = Task . getState ( task ) ; while ( ! state . isFinished ( ) ) { Thread . sleep ( ) ; state = Task . getState ( task ) ; if ( state . isRedirected ( ) ) { task = state . getResults ( ) ; } } String dataset = state . getResults ( ) ; } else { throw new BioclipseException ( "" + status ) ; } method . releaseConnection ( ) ; } public static void setLicense ( String datasetURI , String license ) throws Exception { setMetadata ( datasetURI , "" , "" + license + ">" ) ; } public static void setRightsHolder ( String datasetURI , String holder ) throws Exception { setMetadata ( datasetURI , "" , "" + holder + ">" ) ; } public static void setTitle ( String datasetURI , String title ) throws Exception { setMetadata ( datasetURI , "" , "" + title + "" ) ; } @ SuppressWarnings ( "" ) public static void addMolecules ( String datasetURI , String sdFile , IProgressMonitor monitor ) throws Exception { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; HttpClient client = new HttpClient ( ) ; datasetURI = normalizeURI ( datasetURI ) ; PutMethod method = new PutMethod ( datasetURI ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; put ( "" , "" ) ; } } ) ; method . setRequestBody ( sdFile ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; String dataset = "" ; String responseString = method . getResponseBodyAsString ( ) ; logger . debug ( "" + responseString ) ; int tailing = ; if ( status == ) { dataset = method . getResponseBodyAsString ( ) ; logger . debug ( "" + dataset ) ; } else if ( status == || status == ) { String task = method . getResponseBodyAsString ( ) ; Thread . sleep ( ) ; TaskState state = Task . getState ( task ) ; while ( ! state . isFinished ( ) && ! monitor . isCanceled ( ) ) { int waitingTime = andABit ( * tailing ) ; logger . debug ( "" + waitingTime + "" ) ; waitUnlessInterrupted ( waitingTime , monitor ) ; state = Task . getState ( task ) ; if ( state . isRedirected ( ) ) { task = state . getResults ( ) ; logger . debug ( "" + task ) ; } if ( tailing < ) tailing ++ ; } if ( monitor . isCanceled ( ) ) Task . delete ( task ) ; dataset = state . getResults ( ) ; } else { logger . warn ( "" + status ) ; } method . releaseConnection ( ) ; } public static String createNewDataset ( String service , List < IMolecule > molecules , IProgressMonitor monitor ) throws Exception { StringWriter strWriter = new StringWriter ( ) ; SDFWriter writer = new SDFWriter ( strWriter ) ; for ( IMolecule mol : molecules ) { writer . write ( cdk . asCDKMolecule ( mol ) . getAtomContainer ( ) ) ; } writer . close ( ) ; return createNewDataset ( normalizeURI ( service ) , strWriter . toString ( ) , monitor ) ; } public static String createNewDataset ( String service , IMolecule mol , IProgressMonitor monitor ) throws Exception { StringWriter strWriter = new StringWriter ( ) ; SDFWriter writer = new SDFWriter ( strWriter ) ; writer . write ( cdk . asCDKMolecule ( mol ) . getAtomContainer ( ) ) ; writer . close ( ) ; return createNewDataset ( service , strWriter . toString ( ) , monitor ) ; } public static String createNewDataset ( String service , IProgressMonitor monitor ) throws Exception { StringWriter strWriter = new StringWriter ( ) ; SDFWriter writer = new SDFWriter ( strWriter ) ; writer . write ( new AtomContainer ( ) ) ; writer . close ( ) ; return createNewDataset ( service , strWriter . toString ( ) , monitor ) ; } public static String createNewDataset ( String service , String sdFile , IProgressMonitor monitor ) throws Exception { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; HttpClient client = new HttpClient ( ) ; PostMethod method = new PostMethod ( service + "" ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; put ( "" , "" ) ; } } ) ; System . out . println ( "" + method . toString ( ) ) ; method . setRequestBody ( sdFile ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; String dataset = "" ; String responseString = method . getResponseBodyAsString ( ) ; logger . debug ( "" + responseString ) ; int tailing = ; if ( status == || status == || status == ) { if ( responseString . contains ( "" ) ) { logger . debug ( "" + responseString ) ; String task = method . getResponseBodyAsString ( ) ; Thread . sleep ( ) ; TaskState state = Task . getState ( task ) ; while ( ! state . isFinished ( ) && ! monitor . isCanceled ( ) ) { int waitingTime = andABit ( * tailing ) ; logger . debug ( "" + waitingTime + "" ) ; waitUnlessInterrupted ( waitingTime , monitor ) ; state = Task . getState ( task ) ; if ( state . isRedirected ( ) ) { task = state . getResults ( ) ; logger . debug ( "" + task ) ; } if ( tailing < ) tailing ++ ; } if ( monitor . isCanceled ( ) ) Task . delete ( task ) ; dataset = state . getResults ( ) ; } else { dataset = method . getResponseBodyAsString ( ) ; logger . debug ( "" + dataset ) ; } } method . releaseConnection ( ) ; if ( monitor . isCanceled ( ) ) return "" ; logger . debug ( "" + dataset ) ; dataset = dataset . replaceAll ( "" , "" ) ; return dataset ; } private static void waitUnlessInterrupted ( int waitingTime , IProgressMonitor monitor ) throws InterruptedException { int passed = ; final int step = ; while ( passed < waitingTime && ! monitor . isCanceled ( ) ) { Thread . sleep ( step ) ; passed += step ; } } private static int andABit ( int minimum ) { return ( minimum + ( int ) Math . round ( minimum * Math . random ( ) ) ) ; } public static void main ( String [ ] args ) throws Exception { String service = "" ; String dataset = createNewDataset ( service , null ) ; List < IMolecule > mols = new ArrayList < IMolecule > ( ) ; mols . add ( cdk . fromSMILES ( "" ) ) ; mols . add ( cdk . fromSMILES ( "" ) ) ; mols . add ( cdk . fromSMILES ( "" ) ) ; addMolecules ( dataset , mols ) ; } } package net . bioclipse . opentox . api ; import java . io . IOException ; import java . security . GeneralSecurityException ; import java . util . HashMap ; import org . apache . commons . httpclient . HttpClient ; import org . apache . commons . httpclient . HttpException ; import org . apache . commons . httpclient . methods . PostMethod ; import org . apache . log4j . Logger ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; public abstract class MolecularDescriptorAlgorithm extends Algorithm { private static final Logger logger = Logger . getLogger ( MolecularDescriptorAlgorithm . class ) ; public static String calculate ( String service , String descriptor , String dataSetURI , IProgressMonitor monitor ) throws HttpException , IOException , InterruptedException , GeneralSecurityException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; HttpClient client = new HttpClient ( ) ; dataSetURI = Dataset . normalizeURI ( dataSetURI ) ; PostMethod method = new PostMethod ( descriptor ) ; HttpMethodHelper . addMethodHeaders ( method , new HashMap < String , String > ( ) { { put ( "" , "" ) ; } } ) ; method . setParameter ( "" , dataSetURI ) ; method . setParameter ( "" , service + "" ) ; logger . debug ( "" + descriptor ) ; logger . debug ( "" + dataSetURI ) ; client . executeMethod ( method ) ; int status = method . getStatusCode ( ) ; logger . debug ( "" + status ) ; String dataset = "" ; String responseString = method . getResponseBodyAsString ( ) ; int tailing = ; if ( status == || status == ) { if ( responseString . contains ( "" ) ) { String task = responseString ; logger . debug ( "" + task ) ; Thread . sleep ( andABit ( ) ) ; TaskState state = Task . getState ( task ) ; while ( ! state . isFinished ( ) && ! monitor . isCanceled ( ) ) { int waitingTime = andABit ( * tailing ) ; logger . debug ( "" + waitingTime + "" ) ; waitUnlessInterrupted ( waitingTime , monitor ) ; state = Task . getState ( task ) ; if ( state . isRedirected ( ) ) { task = state . getResults ( ) ; logger . debug ( "" + task ) ; } if ( tailing < ) tailing ++ ; } if ( monitor . isCanceled ( ) ) Task . delete ( task ) ; dataset = state . getResults ( ) ; } else { dataset = responseString ; } } else if ( status == ) { throw new GeneralSecurityException ( "" ) ; } else if ( status == ) { throw new GeneralSecurityException ( "" ) ; } else { throw new IllegalStateException ( "" + status ) ; } method . releaseConnection ( ) ; dataset = dataset . replaceAll ( "" , "" ) ; return dataset ; } private static void waitUnlessInterrupted ( int waitingTime , IProgressMonitor monitor ) throws InterruptedException { int passed = ; final int step = ; while ( passed < waitingTime && ! monitor . isCanceled ( ) ) { Thread . sleep ( step ) ; passed += step ; } } private static int andABit ( int minimum ) { return ( minimum + ( int ) Math . round ( minimum * Math . random ( ) ) ) ; } } package net . bioclipse . opentox . prefs ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . dialogs . TitleAreaDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . PlatformUI ; import org . eclipse . swt . layout . GridLayout ; public class ServicesEditDialog extends TitleAreaDialog { private String [ ] serviceInfo = new String [ ] ; private Text txtName ; private Text txtService ; private Text txtServiceSparql ; private String name ; private String service ; private String serviceSparql ; public ServicesEditDialog ( Shell parentShell ) { this ( parentShell , "" , "" , "" ) ; } public ServicesEditDialog ( Shell shell , String name , String service , String serviceSparql ) { super ( shell ) ; this . name = name ; this . service = service ; this . serviceSparql = serviceSparql ; } protected Control createDialogArea ( Composite parent ) { setTitle ( "" ) ; setMessage ( "" ) ; Composite area = ( Composite ) super . createDialogArea ( parent ) ; Composite container = new Composite ( area , SWT . NONE ) ; container . setLayout ( new GridLayout ( , false ) ) ; container . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; final Label lblName = new Label ( container , SWT . NONE ) ; lblName . setLayoutData ( new GridData ( SWT . RIGHT , SWT . CENTER , false , false , , ) ) ; lblName . setText ( "" ) ; txtName = new Text ( container , SWT . BORDER ) ; GridData gridData_1 = new GridData ( SWT . FILL , SWT . CENTER , true , false , , ) ; gridData_1 . widthHint = ; txtName . setLayoutData ( gridData_1 ) ; txtName . setText ( name ) ; final Label lblURL = new Label ( container , SWT . NONE ) ; lblURL . setLayoutData ( new GridData ( SWT . RIGHT , SWT . CENTER , false , false , , ) ) ; lblURL . setText ( "" ) ; txtService = new Text ( container , SWT . BORDER ) ; GridData gridData = new GridData ( SWT . FILL , SWT . CENTER , true , false , , ) ; gridData . widthHint = ; txtService . setLayoutData ( gridData ) ; txtService . setText ( service ) ; final Label lblServiceSPARQL = new Label ( container , SWT . NONE ) ; lblServiceSPARQL . setLayoutData ( new GridData ( SWT . RIGHT , SWT . CENTER , false , false , , ) ) ; lblServiceSPARQL . setText ( "" ) ; txtServiceSparql = new Text ( container , SWT . BORDER ) ; GridData gridData2 = new GridData ( SWT . FILL , SWT . CENTER , true , false , , ) ; gridData2 . widthHint = ; txtServiceSparql . setLayoutData ( gridData2 ) ; txtServiceSparql . setText ( serviceSparql ) ; return area ; } protected void createButtonsForButtonBar ( Composite parent ) { createButton ( parent , IDialogConstants . OK_ID , IDialogConstants . OK_LABEL , true ) ; createButton ( parent , IDialogConstants . CANCEL_ID , IDialogConstants . CANCEL_LABEL , false ) ; } protected void buttonPressed ( int buttonId ) { if ( buttonId == IDialogConstants . OK_ID ) { if ( txtName . getText ( ) . length ( ) <= ) { showMessage ( "" ) ; return ; } if ( txtService . getText ( ) . length ( ) <= ) { showMessage ( "" ) ; return ; } if ( txtServiceSparql . getText ( ) . length ( ) <= ) { showMessage ( "" ) ; return ; } serviceInfo [ ] = txtName . getText ( ) ; serviceInfo [ ] = txtService . getText ( ) ; serviceInfo [ ] = txtServiceSparql . getText ( ) ; okPressed ( ) ; return ; } super . buttonPressed ( buttonId ) ; } private void showMessage ( String message ) { MessageDialog . openInformation ( PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getShell ( ) , "" , message ) ; } public void setTxtService ( String service ) { this . txtService . setText ( service ) ; } public void setTxtServiceSparql ( String serviceSparql ) { this . txtServiceSparql . setText ( serviceSparql ) ; } public void setTxtName ( String name ) { this . txtName . setText ( name ) ; } public String [ ] getServiceInfo ( ) { return serviceInfo ; } @ Override protected boolean isResizable ( ) { return true ; } } package net . bioclipse . opentox . prefs ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . bioclipse . opentox . Activator ; import net . bioclipse . opentox . OpenToxConstants ; import net . bioclipse . ui . prefs . IPreferenceConstants ; import org . apache . log4j . Logger ; import org . eclipse . core . runtime . preferences . ConfigurationScope ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . MouseAdapter ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . PlatformUI ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . layout . FormAttachment ; import org . osgi . service . prefs . BackingStoreException ; import org . osgi . service . prefs . Preferences ; public class ServicesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final Logger logger = Logger . getLogger ( ServicesPreferencePage . class . toString ( ) ) ; private static Preferences preferences = ConfigurationScope . INSTANCE . getNode ( OpenToxConstants . PLUGIN_ID ) ; private List < String [ ] > appList ; private TableViewer checkboxTableViewer ; public ServicesPreferencePage ( ) { super ( ) ; } class ApplicationsLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage ( Object element , int columnIndex ) { return null ; } public String getColumnText ( Object element , int index ) { if ( ! ( element instanceof String [ ] ) ) return "" ; String [ ] retList = ( String [ ] ) element ; if ( index == ) { if ( retList . length > ) return retList [ ] ; else return "" ; } else if ( index == ) { if ( retList . length > ) return retList [ ] ; else return "" ; } else if ( index == ) { if ( retList . length > ) return retList [ ] ; else return "" ; } else return "" ; } } class ApplicationsContentProvider implements IStructuredContentProvider { @ SuppressWarnings ( "" ) public Object [ ] getElements ( Object inputElement ) { if ( inputElement instanceof ArrayList ) { ArrayList retList = ( ArrayList ) inputElement ; return retList . toArray ( ) ; } return new Object [ ] ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } } public Control createContents ( Composite parent ) { Composite container = new Composite ( parent , SWT . NULL ) ; setSize ( new Point ( , ) ) ; container . setSize ( , ) ; container . setLayout ( new FormLayout ( ) ) ; checkboxTableViewer = new TableViewer ( container , SWT . BORDER | SWT . SINGLE ) ; checkboxTableViewer . setContentProvider ( new ApplicationsContentProvider ( ) ) ; checkboxTableViewer . setLabelProvider ( new ApplicationsLabelProvider ( ) ) ; final Table table = checkboxTableViewer . getTable ( ) ; FormData formData = new FormData ( , ) ; formData . left = new FormAttachment ( , ) ; formData . top = new FormAttachment ( , ) ; table . setLayoutData ( formData ) ; table . setHeaderVisible ( true ) ; table . setLinesVisible ( true ) ; TableColumn tableColumn = new TableColumn ( table , SWT . LEFT ) ; tableColumn . setText ( "" ) ; tableColumn . setWidth ( ) ; TableColumn tableColumn2 = new TableColumn ( table , SWT . LEFT ) ; tableColumn2 . setText ( "" ) ; tableColumn2 . setWidth ( ) ; TableColumn tableColumn3 = new TableColumn ( table , SWT . LEFT ) ; tableColumn3 . setText ( "" ) ; tableColumn3 . setWidth ( ) ; appList = getPreferencesFromStore ( ) ; checkboxTableViewer . setInput ( appList ) ; final Button addButton = new Button ( container , SWT . NONE ) ; formData . right = new FormAttachment ( , - ) ; FormData formData_1 = new FormData ( ) ; formData_1 . right = new FormAttachment ( , - ) ; formData_1 . left = new FormAttachment ( table , ) ; addButton . setLayoutData ( formData_1 ) ; addButton . setText ( "" ) ; addButton . addMouseListener ( new MouseAdapter ( ) { public void mouseUp ( MouseEvent e ) { ServicesEditDialog dlg = new ServicesEditDialog ( getShell ( ) ) ; dlg . open ( ) ; String [ ] ret = dlg . getServiceInfo ( ) ; if ( ret . length == ) { appList . add ( ret ) ; checkboxTableViewer . refresh ( ) ; } } } ) ; final Button editButton = new Button ( container , SWT . NONE ) ; FormData formData_2 = new FormData ( ) ; formData_2 . top = new FormAttachment ( table , , SWT . TOP ) ; formData_2 . left = new FormAttachment ( table , ) ; formData_2 . right = new FormAttachment ( , - ) ; editButton . setLayoutData ( formData_2 ) ; editButton . setText ( "" ) ; editButton . addMouseListener ( new MouseAdapter ( ) { public void mouseUp ( MouseEvent e ) { ISelection sel = checkboxTableViewer . getSelection ( ) ; if ( ! ( sel instanceof IStructuredSelection ) ) { logger . debug ( "" ) ; showMessage ( "" ) ; return ; } IStructuredSelection ssel = ( IStructuredSelection ) sel ; Object obj = ssel . getFirstElement ( ) ; if ( ! ( obj instanceof String [ ] ) ) { logger . debug ( "" ) ; showMessage ( "" ) ; return ; } String [ ] chosen = ( String [ ] ) obj ; if ( chosen . length < ) { String [ ] temp = { "" , "" , "" } ; for ( int i = ; i < chosen . length ; i ++ ) temp [ i ] = chosen [ i ] ; chosen = temp ; } ServicesEditDialog dlg = new ServicesEditDialog ( getShell ( ) , chosen [ ] , chosen [ ] , chosen [ ] ) ; dlg . open ( ) ; String [ ] ret = dlg . getServiceInfo ( ) ; if ( dlg . getReturnCode ( ) == ) { if ( ret . length == ) { chosen [ ] = ret [ ] ; chosen [ ] = ret [ ] ; chosen [ ] = ret [ ] ; checkboxTableViewer . refresh ( ) ; } else { logger . debug ( "" ) ; showMessage ( "" ) ; } } } } ) ; final Button removeButton = new Button ( container , SWT . NONE ) ; formData_1 . top = new FormAttachment ( removeButton , ) ; FormData formData_3 = new FormData ( ) ; formData_3 . right = new FormAttachment ( , - ) ; formData_3 . left = new FormAttachment ( table , ) ; formData_3 . top = new FormAttachment ( , ) ; removeButton . setLayoutData ( formData_3 ) ; removeButton . setText ( "" ) ; removeButton . addMouseListener ( new MouseAdapter ( ) { public void mouseUp ( MouseEvent e ) { if ( checkboxTableViewer . getSelection ( ) instanceof IStructuredSelection ) { IStructuredSelection selection = ( IStructuredSelection ) checkboxTableViewer . getSelection ( ) ; Object [ ] objSelection = selection . toArray ( ) ; for ( int i = ; i < objSelection . length ; i ++ ) { if ( objSelection [ i ] instanceof String [ ] ) { String [ ] row = ( String [ ] ) objSelection [ i ] ; if ( appList . contains ( row ) ) { appList . remove ( row ) ; } } } checkboxTableViewer . refresh ( ) ; } } } ) ; if ( table . getItemCount ( ) > ) table . setSelection ( ) ; container . pack ( ) ; parent . pack ( ) ; return container ; } public void init ( IWorkbench workbench ) { setPreferenceStore ( Activator . getDefault ( ) . getPreferenceStore ( ) ) ; } public boolean performOk ( ) { String value = convertToPreferenceString ( appList ) ; logger . debug ( "" + value ) ; preferences . put ( OpenToxConstants . SERVICES , value ) ; try { preferences . flush ( ) ; } catch ( BackingStoreException e ) { logger . error ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } return true ; } public static List < String [ ] > getPreferencesFromStore ( ) { String entireString = preferences . get ( OpenToxConstants . SERVICES , "" ) ; return convertPreferenceStringToArraylist ( entireString ) ; } public static List < String [ ] > getDefaultPreferencesFromStore ( ) { String entireString = preferences . get ( OpenToxConstants . SERVICES , "" ) ; return convertPreferenceStringToArraylist ( entireString ) ; } public static List < String [ ] > convertPreferenceStringToArraylist ( String entireString ) { List < String [ ] > myList = new ArrayList < String [ ] > ( ) ; String [ ] ret = entireString . split ( IPreferenceConstants . PREFERENCES_OBJECT_DELIMITER ) ; String [ ] partString = new String [ ] ; for ( int i = ; i < ret . length ; i ++ ) { partString = ret [ i ] . split ( IPreferenceConstants . PREFERENCES_DELIMITER ) ; myList . add ( partString ) ; } if ( ret . length == ) { if ( partString . length < ) { logger . debug ( "" ) ; myList . clear ( ) ; } } return myList ; } public static String convertToPreferenceString ( List < String [ ] > appList2 ) { Iterator < String [ ] > it = appList2 . iterator ( ) ; String ret = "" ; while ( it . hasNext ( ) ) { String [ ] str = ( String [ ] ) it . next ( ) ; String singleRet = "" ; for ( int i = ; i < str . length ; i ++ ) { singleRet = singleRet + str [ i ] ; if ( ( i + ) < str . length ) { singleRet += IPreferenceConstants . PREFERENCES_DELIMITER ; } } ret = ret + singleRet ; if ( it . hasNext ( ) ) { ret += IPreferenceConstants . PREFERENCES_OBJECT_DELIMITER ; } } return ret ; } protected void performDefaults ( ) { super . performDefaults ( ) ; appList = getDefaultPreferencesFromStore ( ) ; checkboxTableViewer . setInput ( appList ) ; } private void showMessage ( String message ) { MessageDialog . openInformation ( PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getShell ( ) , "" , message ) ; } } package net . bioclipse . opentox ; public class OpenToxService { private String name ; private String service ; private String serviceSPARQL ; public OpenToxService ( String name , String service , String serviceSPARQL ) { super ( ) ; this . name = name ; this . service = service ; this . serviceSPARQL = serviceSPARQL ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getService ( ) { return service ; } public void setService ( String service ) { this . service = service ; } public String getServiceSPARQL ( ) { return serviceSPARQL ; } public void setServiceSPARQL ( String serviceSPARQL ) { this . serviceSPARQL = serviceSPARQL ; } @ Override public String toString ( ) { return "" + name + "" + service + "" + serviceSPARQL + "" ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof OpenToxService ) { OpenToxService in = ( OpenToxService ) obj ; if ( this . name . equals ( in . name ) ) return true ; } return false ; } } package net . bioclipse . opentox ; import java . util . ArrayList ; import java . util . List ; import net . bioclipse . opentox . prefs . ServicesPreferencePage ; import org . apache . log4j . Logger ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . preference . IPreferenceStore ; public class ServiceReader { private static final Logger logger = Logger . getLogger ( ServiceReader . class ) ; public static List < OpenToxService > readServicesFromExtensionPoints ( ) { List < OpenToxService > services = new ArrayList < OpenToxService > ( ) ; IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; if ( registry == null ) throw new UnsupportedOperationException ( "" + "" ) ; IExtensionPoint serviceObjectExtensionPoint = registry . getExtensionPoint ( "" ) ; IExtension [ ] serviceObjectExtensions = serviceObjectExtensionPoint . getExtensions ( ) ; for ( IExtension extension : serviceObjectExtensions ) { for ( IConfigurationElement element : extension . getConfigurationElements ( ) ) { if ( element . getName ( ) . equals ( "" ) ) { String pid = element . getAttribute ( "" ) ; String pname = element . getAttribute ( "" ) ; String purl = element . getAttribute ( "" ) ; if ( purl == null ) purl = "" ; String pspql = element . getAttribute ( "" ) ; if ( pspql == null ) pspql = "" ; OpenToxService service = new OpenToxService ( pname , purl , pspql ) ; services . add ( service ) ; logger . debug ( "" + service ) ; } } } return services ; } public static List < OpenToxService > readServicesFromPreferences ( ) { logger . debug ( "" ) ; List < OpenToxService > services = new ArrayList < OpenToxService > ( ) ; IPreferenceStore prefsStore = Activator . getDefault ( ) . getPreferenceStore ( ) ; String entireString = prefsStore . getString ( OpenToxConstants . SERVICES ) ; List < String [ ] > parts = ServicesPreferencePage . convertPreferenceStringToArraylist ( entireString ) ; for ( String [ ] entry : parts ) { if ( entry . length == ) { OpenToxService service = new OpenToxService ( entry [ ] , entry [ ] , entry [ ] ) ; services . add ( service ) ; } else { logger . debug ( "" + entry ) ; } } return services ; } } package net . bioclipse . opentox . qsar ; public class OpenToxProvider { public String id ; public String name ; public String service ; public String serviceSPARQL ; public OpenToxProvider ( String id , String name , String service , String serviceSPARQL ) { super ( ) ; this . id = id ; this . name = name ; this . service = service ; this . serviceSPARQL = serviceSPARQL ; } public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public String getService ( ) { return service ; } public void setService ( String service ) { this . service = service ; } public String getServiceSPARQL ( ) { return serviceSPARQL ; } public void setServiceSPARQL ( String serviceSPARQL ) { this . serviceSPARQL = serviceSPARQL ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } } package net . bioclipse . opentox . qsar ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . log4j . Logger ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import net . bioclipse . core . business . BioclipseException ; import net . bioclipse . core . domain . IMolecule ; import net . bioclipse . opentox . Activator ; import net . bioclipse . opentox . business . IOpentoxManager ; import net . bioclipse . qsar . DescriptorType ; import net . bioclipse . qsar . business . IQsarManager ; import net . bioclipse . qsar . descriptor . DescriptorResult ; import net . bioclipse . qsar . descriptor . IDescriptorCalculator ; import net . bioclipse . qsar . descriptor . IDescriptorResult ; import net . bioclipse . qsar . descriptor . model . DescriptorImpl ; public class OpenToxDescriptorCalculator implements IDescriptorCalculator { private static final Logger logger = Logger . getLogger ( OpenToxDescriptorCalculator . class ) ; private Map < String , String > ontologyMap ; private String service ; private String providerID ; public OpenToxDescriptorCalculator ( String providerID , String service ) { super ( ) ; this . providerID = providerID ; this . service = service ; } public OpenToxDescriptorCalculator ( ) { } @ Override public Map < ? extends IMolecule , List < IDescriptorResult > > calculateDescriptor ( Map < IMolecule , List < DescriptorType > > moldesc , IProgressMonitor monitor ) throws BioclipseException { Map < IMolecule , List < IDescriptorResult > > allResults = new HashMap < IMolecule , List < IDescriptorResult > > ( ) ; int workload = ; for ( IMolecule mol : moldesc . keySet ( ) ) { workload = workload + moldesc . get ( mol ) . size ( ) ; } monitor . beginTask ( "" , workload ) ; monitor . subTask ( "" ) ; try { verifyServer ( ) ; } catch ( Exception e ) { throw new BioclipseException ( "" + ontologyMap ) ; } IQsarManager qsar = net . bioclipse . qsar . init . Activator . getDefault ( ) . getJavaQsarManager ( ) ; IOpentoxManager opentox = Activator . getDefault ( ) . getJavaOpentoxManager ( ) ; for ( IMolecule mol : moldesc . keySet ( ) ) { List < IDescriptorResult > molResults = new ArrayList < IDescriptorResult > ( ) ; for ( DescriptorType desc : moldesc . get ( mol ) ) { if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; DescriptorImpl dimpl = qsar . getDescriptorImpl ( desc . getOntologyid ( ) , providerID ) ; String descOTid = dimpl . getId ( ) ; monitor . subTask ( "" + dimpl . getName ( ) ) ; monitor . worked ( ) ; logger . debug ( "" + service + "" + descOTid ) ; List < String > OTres = null ; for ( int i = ; i < ; i ++ ) { if ( i > ) logger . debug ( "" + i ) ; try { OTres = opentox . calculateDescriptor ( service , descOTid , mol ) ; } catch ( Exception e ) { logger . error ( "" ) ; } if ( OTres != null ) break ; } IDescriptorResult res = parseOTResults ( OTres , desc ) ; molResults . add ( res ) ; } allResults . put ( mol , molResults ) ; } monitor . done ( ) ; return allResults ; } private IDescriptorResult parseOTResults ( List < String > OTres , DescriptorType desc ) { IDescriptorResult res = new DescriptorResult ( ) ; if ( OTres == null ) { res . setDescriptor ( desc ) ; res . setErrorMessage ( "" + desc . getId ( ) + "" ) ; } else { Float [ ] floats = new Float [ OTres . size ( ) ] ; String [ ] labels = new String [ OTres . size ( ) ] ; String baseLabel = desc . getOntologyid ( ) . substring ( desc . getOntologyid ( ) . lastIndexOf ( "" ) + ) ; for ( int i = ; i < OTres . size ( ) ; i ++ ) { floats [ i ] = Float . parseFloat ( OTres . get ( i ) ) ; if ( OTres . size ( ) > ) labels [ i ] = baseLabel + "" + ( i + ) ; else labels [ i ] = baseLabel ; } res . setValues ( floats ) ; res . setLabels ( labels ) ; res . setDescriptor ( desc ) ; } return res ; } private void verifyServer ( ) { } } package net . bioclipse . opentox . qsar ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static Activator plugin ; public Activator ( ) { } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static Activator getDefault ( ) { return plugin ; } } package net . bioclipse . opentox . qsar ; import org . apache . log4j . Logger ; import java . util . ArrayList ; import java . util . List ; import net . bioclipse . core . business . BioclipseException ; import net . bioclipse . core . domain . IStringMatrix ; import net . bioclipse . opentox . Activator ; import net . bioclipse . opentox . business . IOpentoxManager ; import net . bioclipse . qsar . descriptor . IDescriptorCalculator ; import net . bioclipse . qsar . descriptor . model . DescriptorImpl ; import net . bioclipse . qsar . descriptor . model . DescriptorProvider ; import net . bioclipse . qsar . discovery . IDiscoveryService ; public class OpenToxProviderDiscovery implements IDiscoveryService { private static final Logger logger = Logger . getLogger ( OpenToxProviderDiscovery . class ) ; private static List < OpenToxProvider > providers ; @ Override public String getName ( ) { return "" ; } @ Override public List < DescriptorProvider > discoverProvidersAndImpls ( ) { List < DescriptorProvider > returnList = new ArrayList < DescriptorProvider > ( ) ; IOpentoxManager opentox = Activator . getDefault ( ) . getJavaOpentoxManager ( ) ; logger . debug ( "" ) ; providers = discoverProviders ( ) ; for ( OpenToxProvider provider : providers ) { logger . debug ( "" + provider . name ) ; } for ( OpenToxProvider provider : providers ) { DescriptorProvider dp = new DescriptorProvider ( provider . getId ( ) , provider . getName ( ) ) ; dp . setShortName ( provider . getName ( ) ) ; IDescriptorCalculator calculator = new OpenToxDescriptorCalculator ( provider . getId ( ) , provider . getService ( ) ) ; dp . setCalculator ( calculator ) ; List < DescriptorImpl > impls = new ArrayList < DescriptorImpl > ( ) ; logger . debug ( "" + provider . getService ( ) ) ; IStringMatrix stringMat ; try { stringMat = opentox . listDescriptors ( provider . getServiceSPARQL ( ) ) ; } catch ( BioclipseException e ) { e . printStackTrace ( ) ; return returnList ; } for ( int i = ; i < stringMat . getRowCount ( ) ; i ++ ) { String implID = stringMat . get ( i , ) ; String bodo = stringMat . get ( i , ) ; String implName = "" ; if ( bodo . length ( ) > ) implName = bodo . substring ( bodo . indexOf ( "" ) + ) ; if ( implID == null || implID . length ( ) < ) { logger . error ( "" + implID + "" + bodo + "" + "" + implName ) ; } else if ( bodo == null || bodo . length ( ) < ) { logger . error ( "" + implID + "" + bodo + "" + "" + implName ) ; } else { DescriptorImpl impl = new DescriptorImpl ( implID , implName ) ; impl . setDefinition ( bodo ) ; impl . setProvider ( dp ) ; impls . add ( impl ) ; logger . debug ( "" + impl . getId ( ) + "" + impl . getDefinition ( ) ) ; } } dp . setDescriptorImpls ( impls ) ; returnList . add ( dp ) ; } return returnList ; } private ArrayList < OpenToxProvider > discoverProviders ( ) { ArrayList < OpenToxProvider > endpoints = new ArrayList < OpenToxProvider > ( ) ; OpenToxProvider s1 = new OpenToxProvider ( "" , "" , "" , "" ) ; endpoints . add ( s1 ) ; return endpoints ; } } package net . bioclipse . opentox . ds . prefs ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . preference . FieldEditor ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . core . runtime . Assert ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . List ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Widget ; public abstract class ModelsListEditor extends FieldEditor { private List list ; private Composite buttonBox ; private Button addButton ; private Button removeButton ; private Button upButton ; private Button downButton ; private SelectionListener selectionListener ; protected ModelsListEditor ( ) { } protected ModelsListEditor ( String name , String labelText , Composite parent ) { init ( name , labelText ) ; createControl ( parent ) ; } private void addPressed ( ) { setPresentsDefaultValue ( false ) ; String [ ] inputs = selectNewModels ( ) ; if ( inputs != null && inputs . length > ) { int index = list . getSelectionIndex ( ) ; for ( String input : inputs ) { if ( index >= ) list . add ( input , index + ) ; else list . add ( input , ) ; index ++ ; } } selectionChanged ( ) ; } private String [ ] selectNewModels ( ) { System . out . println ( "" ) ; return null ; } protected void adjustForNumColumns ( int numColumns ) { Control control = getLabelControl ( ) ; ( ( GridData ) control . getLayoutData ( ) ) . horizontalSpan = numColumns ; ( ( GridData ) list . getLayoutData ( ) ) . horizontalSpan = numColumns - ; } private void createButtons ( Composite box ) { addButton = createPushButton ( box , "" ) ; removeButton = createPushButton ( box , "" ) ; upButton = createPushButton ( box , "" ) ; downButton = createPushButton ( box , "" ) ; } protected abstract String createList ( String [ ] items ) ; private Button createPushButton ( Composite parent , String key ) { Button button = new Button ( parent , SWT . PUSH ) ; button . setText ( JFaceResources . getString ( key ) ) ; button . setFont ( parent . getFont ( ) ) ; GridData data = new GridData ( GridData . FILL_HORIZONTAL ) ; int widthHint = convertHorizontalDLUsToPixels ( button , IDialogConstants . BUTTON_WIDTH ) ; data . widthHint = Math . max ( widthHint , button . computeSize ( SWT . DEFAULT , SWT . DEFAULT , true ) . x ) ; button . setLayoutData ( data ) ; button . addSelectionListener ( getSelectionListener ( ) ) ; return button ; } public void createSelectionListener ( ) { selectionListener = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent event ) { Widget widget = event . widget ; if ( widget == addButton ) { addPressed ( ) ; } else if ( widget == removeButton ) { removePressed ( ) ; } else if ( widget == upButton ) { upPressed ( ) ; } else if ( widget == downButton ) { downPressed ( ) ; } else if ( widget == list ) { selectionChanged ( ) ; } } } ; } protected void doFillIntoGrid ( Composite parent , int numColumns ) { Control control = getLabelControl ( parent ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = numColumns ; control . setLayoutData ( gd ) ; list = getListControl ( parent ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . verticalAlignment = GridData . FILL ; gd . horizontalSpan = numColumns - ; gd . grabExcessHorizontalSpace = true ; list . setLayoutData ( gd ) ; buttonBox = getButtonBoxControl ( parent ) ; gd = new GridData ( ) ; gd . verticalAlignment = GridData . BEGINNING ; buttonBox . setLayoutData ( gd ) ; } protected void doLoad ( ) { if ( list != null ) { String s = getPreferenceStore ( ) . getString ( getPreferenceName ( ) ) ; String [ ] array = parseString ( s ) ; for ( int i = ; i < array . length ; i ++ ) { list . add ( array [ i ] ) ; } } } protected void doLoadDefault ( ) { if ( list != null ) { list . removeAll ( ) ; String s = getPreferenceStore ( ) . getDefaultString ( getPreferenceName ( ) ) ; String [ ] array = parseString ( s ) ; for ( int i = ; i < array . length ; i ++ ) { list . add ( array [ i ] ) ; } } } protected void doStore ( ) { String s = createList ( list . getItems ( ) ) ; if ( s != null ) { getPreferenceStore ( ) . setValue ( getPreferenceName ( ) , s ) ; } } private void downPressed ( ) { swap ( false ) ; } public Composite getButtonBoxControl ( Composite parent ) { if ( buttonBox == null ) { buttonBox = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . marginWidth = ; buttonBox . setLayout ( layout ) ; createButtons ( buttonBox ) ; buttonBox . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent event ) { addButton = null ; removeButton = null ; upButton = null ; downButton = null ; buttonBox = null ; } } ) ; } else { checkParent ( buttonBox , parent ) ; } selectionChanged ( ) ; return buttonBox ; } public List getListControl ( Composite parent ) { if ( list == null ) { list = new List ( parent , SWT . BORDER | SWT . SINGLE | SWT . V_SCROLL | SWT . H_SCROLL ) ; list . setFont ( parent . getFont ( ) ) ; list . addSelectionListener ( getSelectionListener ( ) ) ; list . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent event ) { list = null ; } } ) ; } else { checkParent ( list , parent ) ; } return list ; } public int getNumberOfControls ( ) { return ; } private SelectionListener getSelectionListener ( ) { if ( selectionListener == null ) { createSelectionListener ( ) ; } return selectionListener ; } protected Shell getShell ( ) { if ( addButton == null ) { return null ; } return addButton . getShell ( ) ; } protected abstract String [ ] parseString ( String stringList ) ; private void removePressed ( ) { setPresentsDefaultValue ( false ) ; int index = list . getSelectionIndex ( ) ; if ( index >= ) { list . remove ( index ) ; selectionChanged ( ) ; } } protected void selectionChanged ( ) { int index = list . getSelectionIndex ( ) ; int size = list . getItemCount ( ) ; removeButton . setEnabled ( index >= ) ; upButton . setEnabled ( size > && index > ) ; downButton . setEnabled ( size > && index >= && index < size - ) ; } public void setFocus ( ) { if ( list != null ) { list . setFocus ( ) ; } } private void swap ( boolean up ) { setPresentsDefaultValue ( false ) ; int index = list . getSelectionIndex ( ) ; int target = up ? index - : index + ; if ( index >= ) { String [ ] selection = list . getSelection ( ) ; Assert . isTrue ( selection . length == ) ; list . remove ( index ) ; list . add ( selection [ ] , target ) ; list . setSelection ( target ) ; } selectionChanged ( ) ; } private void upPressed ( ) { swap ( true ) ; } public void setEnabled ( boolean enabled , Composite parent ) { super . setEnabled ( enabled , parent ) ; getListControl ( parent ) . setEnabled ( enabled ) ; addButton . setEnabled ( enabled ) ; removeButton . setEnabled ( enabled ) ; upButton . setEnabled ( enabled ) ; downButton . setEnabled ( enabled ) ; } protected Button getAddButton ( ) { return addButton ; } protected Button getRemoveButton ( ) { return removeButton ; } protected Button getUpButton ( ) { return upButton ; } protected Button getDownButton ( ) { return downButton ; } protected List getList ( ) { return list ; } } package net . bioclipse . opentox . ds . prefs ; import java . util . ArrayList ; import java . util . List ; import java . util . StringTokenizer ; import net . bioclipse . opentox . OpenToxConstants ; import net . bioclipse . opentox . ds . Activator ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . swt . layout . GridData ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; public class OpenToxModelsPrefsPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public static final String OT_MODELS_PREFS = "" ; protected static final String PREFS_SEPERATOR = "" ; public OpenToxModelsPrefsPage ( ) { super ( FieldEditorPreferencePage . GRID ) ; IPreferenceStore store = Activator . getDefault ( ) . getPreferenceStore ( ) ; setPreferenceStore ( store ) ; } @ Override protected void createFieldEditors ( ) { ModelsListEditor listeditor = new ModelsListEditor ( "" , OT_MODELS_PREFS , getFieldEditorParent ( ) ) { @ Override protected String [ ] parseString ( String stringList ) { StringTokenizer st = new StringTokenizer ( stringList , PREFS_SEPERATOR ) ; List < String > v = new ArrayList < String > ( ) ; while ( st . hasMoreElements ( ) ) { v . add ( ( String ) st . nextElement ( ) ) ; } return ( String [ ] ) v . toArray ( new String [ v . size ( ) ] ) ; } @ Override protected String createList ( String [ ] items ) { StringBuffer path = new StringBuffer ( "" ) ; for ( int i = ; i < items . length ; i ++ ) { path . append ( items [ i ] ) ; path . append ( PREFS_SEPERATOR ) ; } return path . toString ( ) ; } } ; addField ( listeditor ) ; GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . heightHint = ; listeditor . getListControl ( getFieldEditorParent ( ) ) . setLayoutData ( gd ) ; } public void init ( IWorkbench workbench ) { } public static String createPreferenceStringFromItems ( String [ ] items ) { StringBuffer path = new StringBuffer ( "" ) ; for ( int i = ; i < items . length ; i ++ ) { path . append ( items [ i ] ) ; path . append ( OpenToxConstants . PREFS_SEPERATOR ) ; } return path . toString ( ) ; } public static String [ ] parsePreferenceString ( String stringList ) { StringTokenizer st = new StringTokenizer ( stringList , OpenToxConstants . PREFS_SEPERATOR ) ; List < String > v = new ArrayList < String > ( ) ; while ( st . hasMoreElements ( ) ) { v . add ( ( String ) st . nextElement ( ) ) ; } return ( String [ ] ) v . toArray ( new String [ v . size ( ) ] ) ; } } package net . bioclipse . opentox . ds . wizards ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . swt . graphics . Image ; public class ServicesLabelProvider implements ILabelProvider { @ Override public void addListener ( ILabelProviderListener listener ) { } @ Override public void dispose ( ) { } @ Override public boolean isLabelProperty ( Object element , String property ) { return false ; } @ Override public void removeListener ( ILabelProviderListener listener ) { } @ Override public Image getImage ( Object element ) { return null ; } @ Override public String getText ( Object element ) { return null ; } } package net . bioclipse . opentox . ds . wizards ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class ServicesContentProvider implements ITreeContentProvider { @ Override public Object [ ] getElements ( Object inputElement ) { return null ; } @ Override public void dispose ( ) { } @ Override public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } @ Override public Object [ ] getChildren ( Object parentElement ) { return null ; } @ Override public Object getParent ( Object element ) { return null ; } @ Override public boolean hasChildren ( Object element ) { return false ; } } package net . bioclipse . opentox . ds . wizards ; import net . bioclipse . opentox . ds . Activator ; import net . bioclipse . opentox . ds . prefs . OpenToxModelsPrefsPage ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTreeViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; public class SelectModelsPage extends WizardPage { private CheckboxTreeViewer viewer ; private AddModelsWizard wizard ; protected SelectModelsPage ( String pageName ) { super ( pageName ) ; } public void createControl ( Composite parent ) { wizard = ( AddModelsWizard ) getWizard ( ) ; setTitle ( "" ) ; setDescription ( "" + "" ) ; Composite comp = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; comp . setLayout ( layout ) ; viewer = new CheckboxTreeViewer ( parent , SWT . CHECK | SWT . MULTI | SWT . H_SCROLL | SWT . V_SCROLL | SWT . BORDER ) ; viewer . setUseHashlookup ( true ) ; viewer . setContentProvider ( new ServicesContentProvider ( ) ) ; viewer . setLabelProvider ( new ServicesLabelProvider ( ) ) ; IPreferenceStore store = Activator . getDefault ( ) . getPreferenceStore ( ) ; String servicePrefs = store . getString ( OpenToxModelsPrefsPage . OT_MODELS_PREFS ) ; String [ ] serviceStrings = OpenToxModelsPrefsPage . parsePreferenceString ( servicePrefs ) ; viewer . setInput ( serviceStrings ) ; viewer . expandToLevel ( ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . grabExcessHorizontalSpace = true ; data . grabExcessVerticalSpace = true ; data . heightHint = ; data . widthHint = ; viewer . getControl ( ) . setLayoutData ( data ) ; viewer . addCheckStateListener ( new ICheckStateListener ( ) { @ Override public void checkStateChanged ( CheckStateChangedEvent event ) { System . out . println ( "" + event . getElement ( ) + "" + event . getChecked ( ) ) ; } } ) ; setControl ( comp ) ; } } package net . bioclipse . opentox . ds . wizards ; import java . util . List ; import java . util . Map ; import net . bioclipse . opentox . ds . OpenToxModel ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . jface . wizard . Wizard ; public class AddModelsWizard extends Wizard { private SelectModelsPage selectModelsPage ; private List < OpenToxModel > models ; public List < OpenToxModel > getModels ( ) { return models ; } public void setModels ( List < OpenToxModel > models ) { this . models = models ; } @ Override public void addPages ( ) { selectModelsPage = new SelectModelsPage ( "" + "" ) ; addPage ( selectModelsPage ) ; } @ Override public boolean performFinish ( ) { return true ; } } package net . bioclipse . opentox . ds ; import java . util . List ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static Activator plugin ; private List < OpenToxModel > openToxModels ; public Activator ( ) { } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static Activator getDefault ( ) { return plugin ; } } package net . bioclipse . opentox . ds ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import net . bioclipse . core . business . BioclipseException ; import net . bioclipse . ds . Activator ; import net . bioclipse . ds . business . DSBusinessModel ; import net . bioclipse . ds . business . IDSManager ; import net . bioclipse . ds . model . Endpoint ; import net . bioclipse . ds . model . IConsensusCalculator ; import net . bioclipse . ds . model . IDSTest ; import net . bioclipse . ds . model . ITestDiscovery ; import net . bioclipse . opentox . OpenToxService ; import net . bioclipse . opentox . business . IOpentoxManager ; import org . apache . log4j . Logger ; public class OpenToxTestDiscovery implements ITestDiscovery { private static final Logger logger = Logger . getLogger ( OpenToxTestDiscovery . class ) ; public OpenToxTestDiscovery ( ) { } @ Override public List < IDSTest > discoverTests ( ) throws BioclipseException { List < IDSTest > discoveredTests = new ArrayList < IDSTest > ( ) ; IOpentoxManager opentox = net . bioclipse . opentox . Activator . getDefault ( ) . getJavaOpentoxManager ( ) ; List < OpenToxService > OTservices = net . bioclipse . opentox . Activator . getOpenToxServices ( ) ; if ( OTservices == null ) throw new BioclipseException ( "" + "" ) ; for ( OpenToxService service : OTservices ) { if ( service . getServiceSPARQL ( ) != null && service . getServiceSPARQL ( ) . length ( ) > ) { List < String > models = opentox . listModels ( service . getServiceSPARQL ( ) ) ; if ( models != null ) { logger . debug ( "" + models . size ( ) + "" + service ) ; for ( String model : models ) { Map < String , String > props = opentox . getModelInfo ( service . getServiceSPARQL ( ) , model ) ; String title = props . get ( "" ) ; if ( title . endsWith ( "" ) ) { title = title . substring ( , title . indexOf ( "" ) ) ; } IDSTest test = createOpenToxTest ( model , title ) ; discoveredTests . add ( test ) ; logger . debug ( "" + test ) ; } } else { logger . debug ( "" + service ) ; } } } return discoveredTests ; } private IDSTest createOpenToxTest ( String model , String title ) throws BioclipseException { IDSTest test = new OpenToxModel ( model ) ; if ( title != null && title . length ( ) > ) { test . setName ( title ) ; } else { test . setName ( model . substring ( model . lastIndexOf ( "" ) + ) ) ; } test . setId ( "" + model ) ; test . setIcon ( "" ) ; test . setDescription ( "" ) ; test . setOverride ( false ) ; test . setInformative ( false ) ; test . setVisible ( true ) ; test . setPluginID ( net . bioclipse . opentox . ds . Activator . PLUGIN_ID ) ; String endpoint = "" ; IDSManager ds = Activator . getDefault ( ) . getJavaManager ( ) ; for ( Endpoint ep : ds . getFullEndpoints ( ) ) { if ( ep . getId ( ) . equals ( endpoint ) ) { test . setEndpoint ( ep ) ; ep . addTest ( test ) ; } } IConsensusCalculator conscalc = DSBusinessModel . createNewConsCalc ( null ) ; test . setConsensusCalculator ( conscalc ) ; return test ; } } package net . bioclipse . opentox . ds ; import java . security . GeneralSecurityException ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import net . bioclipse . cdk . domain . ICDKMolecule ; import net . bioclipse . ds . model . AbstractDSTest ; import net . bioclipse . ds . model . DSException ; import net . bioclipse . ds . model . ITestResult ; import net . bioclipse . opentox . Activator ; import net . bioclipse . opentox . OpenToxService ; import net . bioclipse . opentox . business . OpentoxManager ; import org . apache . log4j . Logger ; import org . eclipse . core . runtime . IProgressMonitor ; public class OpenToxModel extends AbstractDSTest { private static final Logger logger = Logger . getLogger ( OpenToxModel . class ) ; OpentoxManager opentox ; private String model ; public OpenToxModel ( String model ) { this . model = model ; } @ Override public void initialize ( IProgressMonitor monitor ) throws DSException { opentox = new OpentoxManager ( ) ; } @ Override protected List < ? extends ITestResult > doRunTest ( ICDKMolecule cdkmol , IProgressMonitor monitor ) { OpenToxService otservice = Activator . getCurrentDSService ( ) ; if ( otservice == null ) { logger . error ( "" ) ; returnError ( "" , "" ) ; } String service = otservice . getService ( ) ; if ( service == null ) { logger . error ( "" ) ; returnError ( "" , "" ) ; } ArrayList < net . bioclipse . ds . model . result . SimpleResult > results = new ArrayList < net . bioclipse . ds . model . result . SimpleResult > ( ) ; logger . debug ( "" + model + "" + service ) ; Map < String , String > OTres = null ; for ( int i = ; i < && ! monitor . isCanceled ( ) ; i ++ ) { if ( i > ) logger . debug ( "" + model + "" + i ) ; try { OTres = opentox . predictWithModelWithLabel ( service , model , cdkmol , monitor ) ; } catch ( GeneralSecurityException e ) { logger . error ( "" + model ) ; String errorMessage = "" + e . getMessage ( ) . toLowerCase ( ) ; return returnError ( errorMessage , errorMessage ) ; } catch ( UnsupportedOperationException e ) { logger . error ( "" + model ) ; String errorMessage = "" + e . getMessage ( ) . toLowerCase ( ) ; return returnError ( errorMessage , errorMessage ) ; } catch ( Exception e ) { logger . error ( "" + model ) ; logger . debug ( e ) ; String errorMessage = "" + e . getMessage ( ) ; return returnError ( errorMessage , errorMessage ) ; } if ( OTres != null ) break ; } if ( OTres == null || OTres . size ( ) <= ) { return returnError ( "" , "" ) ; } for ( String label : OTres . keySet ( ) ) { String name = label . substring ( label . lastIndexOf ( "" ) + ) ; results . add ( new net . bioclipse . ds . model . result . SimpleResult ( name + "" + OTres . get ( label ) , ITestResult . INFORMATIVE ) ) ; } return results ; } @ Override public List < String > getRequiredParameters ( ) { return new ArrayList < String > ( ) ; } } package net . bioclipse . opentox . test ; import net . bioclipse . opentox . test . api . TaskTest ; import org . junit . runner . RunWith ; import org . junit . runners . Suite ; import org . junit . runners . Suite . SuiteClasses ; @ RunWith ( Suite . class ) @ SuiteClasses ( { APITest . class , CoverageTest . class , TaskTest . class } ) public class AllOpentoxManagerTests { } package net . bioclipse . opentox . test . api ; import net . bioclipse . opentox . api . Task ; import net . bioclipse . opentox . api . TaskState ; import org . junit . Assert ; import org . junit . Test ; public class TaskTest { @ Test public void testGetState ( ) throws Exception { String task = "" ; TaskState state = Task . getState ( task ) ; Assert . assertNotNull ( state ) ; } } package net . bioclipse . opentox . test ; import net . bioclipse . managers . business . IBioclipseManager ; import org . junit . BeforeClass ; public class JavaScriptOpentoxManagerPluginTest extends AbstractOpentoxManagerPluginTest { @ BeforeClass public static void setup ( ) { opentox = net . bioclipse . opentox . Activator . getDefault ( ) . getJavaScriptOpentoxManager ( ) ; } @ Override public IBioclipseManager getManager ( ) { return opentox ; } } package net . bioclipse . opentox . test ; import org . junit . runner . RunWith ; import org . junit . runners . Suite ; import org . junit . runners . Suite . SuiteClasses ; @ RunWith ( Suite . class ) @ SuiteClasses ( { JavaOpentoxManagerPluginTest . class , JavaScriptOpentoxManagerPluginTest . class } ) public class AllOpentoxManagerPluginTests { } package net . bioclipse . opentox . test ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static Activator sharedInstance ; public Activator ( ) { } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; sharedInstance = this ; } public void stop ( BundleContext context ) throws Exception { sharedInstance = null ; super . stop ( context ) ; } public static Activator getDefault ( ) { return sharedInstance ; } } package net . bioclipse . opentox . test ; import net . bioclipse . core . tests . coverage . AbstractCoverageTest ; import net . bioclipse . managers . business . IBioclipseManager ; import net . bioclipse . opentox . business . IOpentoxManager ; import net . bioclipse . opentox . business . OpentoxManager ; public class CoverageTest extends AbstractCoverageTest { private static OpentoxManager manager = new OpentoxManager ( ) ; @ Override public IBioclipseManager getManager ( ) { return manager ; } @ Override public Class < ? extends IBioclipseManager > getManagerInterface ( ) { return IOpentoxManager . class ; } } package net . bioclipse . opentox . test ; import net . bioclipse . managers . business . IBioclipseManager ; import org . junit . BeforeClass ; public class JavaOpentoxManagerPluginTest extends AbstractOpentoxManagerPluginTest { @ BeforeClass public static void setup ( ) { opentox = net . bioclipse . opentox . Activator . getDefault ( ) . getJavaOpentoxManager ( ) ; } @ Override public IBioclipseManager getManager ( ) { return opentox ; } } package net . bioclipse . opentox . test ; import net . bioclipse . core . tests . AbstractManagerTest ; import net . bioclipse . managers . business . IBioclipseManager ; import net . bioclipse . opentox . business . IOpentoxManager ; import net . bioclipse . opentox . business . OpentoxManager ; public class APITest extends AbstractManagerTest { private static OpentoxManager manager = new OpentoxManager ( ) ; @ Override public IBioclipseManager getManager ( ) { return manager ; } @ Override public Class < ? extends IBioclipseManager > getManagerInterface ( ) { return IOpentoxManager . class ; } } package net . bioclipse . opentox . test ; import java . net . URI ; import java . util . List ; import net . bioclipse . cdk . business . CDKManager ; import net . bioclipse . cdk . domain . CDKMolecule ; import net . bioclipse . cdk . domain . ICDKMolecule ; import net . bioclipse . core . business . BioclipseException ; import net . bioclipse . core . domain . IStringMatrix ; import net . bioclipse . core . tests . AbstractManagerTest ; import net . bioclipse . inchi . InChI ; import net . bioclipse . managers . business . IBioclipseManager ; import net . bioclipse . opentox . business . IOpentoxManager ; import org . junit . Assert ; import org . junit . Test ; public abstract class AbstractOpentoxManagerPluginTest extends AbstractManagerTest { private CDKManager cdk = new CDKManager ( ) ; private final static String TEST_ACCOUNT = "" ; private final static String TEST_ACCOUNT_PWD = "" ; private final static String TEST_SERVER_OT = "" ; private final static String TEST_SERVER_ONT = "" ; protected static IOpentoxManager opentox ; @ Test public void testAuthentication ( ) throws Exception { opentox . logout ( ) ; Assert . assertNull ( opentox . getToken ( ) ) ; opentox . login ( TEST_ACCOUNT , TEST_ACCOUNT_PWD ) ; String token = opentox . getToken ( ) ; Assert . assertNotNull ( token ) ; Assert . assertNotSame ( , token . length ( ) ) ; opentox . logout ( ) ; Assert . assertNull ( opentox . getToken ( ) ) ; } @ Test public void testSearchDescriptors ( ) throws Exception { IStringMatrix descriptors = opentox . searchDescriptors ( TEST_SERVER_ONT , "" ) ; Assert . assertNotNull ( descriptors ) ; Assert . assertNotSame ( , descriptors . getRowCount ( ) ) ; } @ Test public void testSearchModels ( ) throws Exception { IStringMatrix models = opentox . searchModels ( TEST_SERVER_ONT , "" ) ; Assert . assertNotNull ( models ) ; Assert . assertNotSame ( , models . getRowCount ( ) ) ; } @ Test public void testSearchDataSets ( ) throws Exception { IStringMatrix models = opentox . searchDataSets ( TEST_SERVER_ONT , "" ) ; Assert . assertNotNull ( models ) ; Assert . assertNotSame ( , models . getRowCount ( ) ) ; } @ Test public void testListDatasets ( ) throws Exception { List < String > sets = opentox . listDataSets ( TEST_SERVER_OT ) ; Assert . assertNotNull ( sets ) ; Assert . assertNotSame ( , sets . size ( ) ) ; } @ Test public void testListAlgorithms ( ) throws Exception { List < String > algos = opentox . listAlgorithms ( TEST_SERVER_ONT ) ; Assert . assertNotNull ( algos ) ; Assert . assertNotSame ( , algos . size ( ) ) ; } @ Test public void testGetAlgorithmsInfo ( ) throws Exception { List < String > algos = opentox . listAlgorithms ( TEST_SERVER_ONT ) ; Assert . assertNotNull ( algos ) ; Assert . assertNotSame ( , algos . size ( ) ) ; String algo = algos . get ( ) ; opentox . getAlgorithmInfo ( TEST_SERVER_ONT , algo ) ; } @ Test public void testGetAlgorithmsInfos ( ) throws Exception { List < String > algos = opentox . listAlgorithms ( TEST_SERVER_ONT ) ; Assert . assertNotNull ( algos ) ; Assert . assertNotSame ( , algos . size ( ) ) ; opentox . getAlgorithmInfo ( TEST_SERVER_ONT , algos ) ; } @ Test public void testSearchInChI ( ) throws Exception { List < String > hits = opentox . search ( TEST_SERVER_OT , "" ) ; Assert . assertNotNull ( hits ) ; Assert . assertNotSame ( , hits . size ( ) ) ; } @ Test public void testSearchMolecule ( ) throws BioclipseException { ICDKMolecule mol = cdk . fromSMILES ( "" ) ; mol . setProperty ( CDKMolecule . INCHI_OBJECT , new InChI ( "" , "" ) ) ; List < String > hits = opentox . search ( TEST_SERVER_OT , mol ) ; Assert . assertNotNull ( hits ) ; Assert . assertNotSame ( , hits . size ( ) ) ; } @ Test public void testListDescriptors ( ) throws Exception { IStringMatrix descriptors = opentox . listDescriptors ( TEST_SERVER_ONT ) ; Assert . assertNotNull ( descriptors ) ; Assert . assertNotSame ( , descriptors . getRowCount ( ) ) ; } @ Test public void testListModels ( ) throws Exception { List < String > models = opentox . listModels ( TEST_SERVER_ONT ) ; Assert . assertNotNull ( models ) ; Assert . assertNotSame ( , models . size ( ) ) ; } @ Test public void testListFeatures ( ) throws Exception { List < String > features = opentox . listFeatures ( TEST_SERVER_OT ) ; Assert . assertNotNull ( features ) ; Assert . assertNotSame ( , features . size ( ) ) ; } @ Test public void testCreateEmptyDataSet ( ) throws Exception { String uriString = opentox . createDataset ( TEST_SERVER_OT ) ; Assert . assertNotNull ( uriString ) ; Assert . assertTrue ( uriString . startsWith ( "" ) ) ; URI uri = new URI ( uriString ) ; Assert . assertNotNull ( uri ) ; } @ Test public void testAddMolecule ( ) throws Exception { String uriString = opentox . createDataset ( TEST_SERVER_OT ) ; Assert . assertNotNull ( uriString ) ; opentox . addMolecule ( uriString , cdk . fromSMILES ( "" ) ) ; } @ Test public void testAddMolecules ( ) throws Exception { List < ICDKMolecule > molecules = cdk . createMoleculeList ( ) ; molecules . add ( cdk . fromSMILES ( "" ) ) ; molecules . add ( cdk . fromSMILES ( "" ) ) ; String uriString = opentox . createDataset ( TEST_SERVER_OT ) ; Assert . assertNotNull ( uriString ) ; opentox . addMolecules ( uriString , molecules ) ; } @ Test public void testListCompounds ( ) throws Exception { List < ICDKMolecule > molecules = cdk . createMoleculeList ( ) ; molecules . add ( cdk . fromSMILES ( "" ) ) ; molecules . add ( cdk . fromSMILES ( "" ) ) ; String uriString = opentox . createDataset ( TEST_SERVER_OT , molecules ) ; List < String > compounds = opentox . listCompounds ( uriString ) ; Assert . assertNotNull ( compounds ) ; Assert . assertEquals ( "" + uriString , , compounds . size ( ) ) ; } @ Test public void testListCompoundsDataSet2 ( ) throws Exception { List < Integer > compounds = opentox . listCompounds ( TEST_SERVER_OT , ) ; Assert . assertNotNull ( compounds ) ; Assert . assertNotSame ( , compounds . size ( ) ) ; } @ Test public void testDownloadAsMDLMolfile ( ) throws Exception { String mdlMolfile = opentox . downloadCompoundAsMDLMolfile ( TEST_SERVER_OT , "" , ) ; Assert . assertNotNull ( mdlMolfile ) ; Assert . assertTrue ( mdlMolfile . contains ( "" ) ) ; } @ Test public void testDownloadAsMDLMolfileFromURI ( ) throws Exception { String mdlMolfile = opentox . downloadCompoundAsMDLMolfile ( "" ) ; Assert . assertNotNull ( mdlMolfile ) ; Assert . assertTrue ( mdlMolfile . contains ( "" ) ) ; } @ Test public void testCreateDataSetFromSet ( ) throws Exception { List < ICDKMolecule > molecules = cdk . createMoleculeList ( ) ; molecules . add ( cdk . fromSMILES ( "" ) ) ; molecules . add ( cdk . fromSMILES ( "" ) ) ; String uriString = opentox . createDataset ( TEST_SERVER_OT , molecules ) ; Assert . assertNotNull ( uriString ) ; URI uri = new URI ( uriString ) ; Assert . assertNotNull ( uri ) ; } @ Test public void testCreateDataSet ( ) throws Exception { String uriString = opentox . createDataset ( TEST_SERVER_OT , cdk . fromSMILES ( "" ) ) ; Assert . assertNotNull ( uriString ) ; URI uri = new URI ( uriString ) ; Assert . assertNotNull ( uri ) ; } @ Test public void testCalculateDescriptor_List_Molecule ( ) throws Exception { IStringMatrix stringMat = opentox . listDescriptors ( TEST_SERVER_ONT ) ; String descriptor = stringMat . get ( , "" ) ; Assert . assertNotNull ( descriptor ) ; List < ICDKMolecule > molecules = cdk . createMoleculeList ( ) ; molecules . add ( cdk . fromSMILES ( "" ) ) ; molecules . add ( cdk . fromSMILES ( "" ) ) ; List < String > descriptorVals = opentox . calculateDescriptor ( TEST_SERVER_OT , descriptor , molecules ) ; Assert . assertNotNull ( descriptorVals ) ; Assert . assertSame ( , descriptorVals . size ( ) ) ; } @ Test public void testCalculateDescriptor ( ) throws Exception { IStringMatrix stringMat = opentox . listDescriptors ( TEST_SERVER_ONT ) ; String descriptor = stringMat . get ( , "" ) ; Assert . assertNotNull ( descriptor ) ; List < String > descriptorVals = opentox . calculateDescriptor ( TEST_SERVER_OT , descriptor , cdk . fromSMILES ( "" ) ) ; Assert . assertNotNull ( descriptorVals ) ; Assert . assertSame ( , descriptorVals . size ( ) ) ; } public Class < ? extends IBioclipseManager > getManagerInterface ( ) { return IOpentoxManager . class ; } } package net . ggtools . grand . ui . launcher ; import java . io . File ; import java . io . FilenameFilter ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . ArrayList ; import java . util . Locale ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class Launcher { private static final class JarFilenameFilter implements FilenameFilter { public boolean accept ( final File dir , final String name ) { return name . endsWith ( "" ) ; } } private static final Log log = LogFactory . getLog ( Launcher . class ) ; public Launcher ( ) { super ( ) ; } public static void main ( final String [ ] args ) { try { final ArrayList < URL > urlList = new ArrayList < URL > ( ) ; addDirectoryJars ( "" , urlList ) ; final String osName = System . getProperty ( "" ) . toLowerCase ( Locale . US ) ; if ( osName . equals ( "" ) ) { addDirectoryJars ( "" , urlList ) ; } final URLClassLoader cl = new URLClassLoader ( urlList . toArray ( new URL [ ] ) , Launcher . class . getClassLoader ( ) ) ; Thread . currentThread ( ) . setName ( "" ) ; Thread . currentThread ( ) . setContextClassLoader ( cl ) ; final Class clazz = cl . loadClass ( "" ) ; log . info ( "" + clazz . getClassLoader ( ) ) ; final Runnable application = ( Runnable ) clazz . newInstance ( ) ; application . run ( ) ; } catch ( final Throwable e ) { log . fatal ( "" , e ) ; } log . info ( "" ) ; System . exit ( ) ; } private static void addDirectoryJars ( final String directory , final ArrayList < URL > jarList ) throws MalformedURLException { final File libDir = new File ( directory ) ; final File [ ] jars = libDir . listFiles ( new JarFilenameFilter ( ) ) ; if ( jars != null ) { for ( File element : jars ) { jarList . add ( element . toURL ( ) ) ; } } } } package net . ggtools . grand . ui . event ; import sf . blacksun . util . StopWatch ; public class DispatcherPerformanceMeter { private static final int LOOP = ; public static class ManualDispatcher extends DispatcherAdapter implements Dispatcher { ManualDispatcher ( final EventManager manager ) { super ( manager ) ; } public void sendEventToSubscriber ( final Object subscriber , final Object eventData ) { ( ( Listener ) subscriber ) . listen ( eventData ) ; } } public static class Listener { public void listen ( final Object o ) { } } public static void main ( final String [ ] args ) throws SecurityException , NoSuchMethodException { final StopWatch timer = new StopWatch ( ) ; final Listener subscriber = new Listener ( ) ; System . out . println ( "" ) ; final ManualDispatcher manualDispatcher = new ManualDispatcher ( null ) ; timer . start ( ) ; for ( int i = ; i < LOOP ; i ++ ) { manualDispatcher . sendEventToSubscriber ( subscriber , "" ) ; } timer . stop ( ) ; System . out . println ( "" + timer ) ; System . out . println ( "" ) ; final SimpleDispatcher simpleDispatcher = new SimpleDispatcher ( null , Listener . class . getDeclaredMethod ( "" , new Class [ ] { Object . class } ) ) ; timer . reset ( ) ; timer . start ( ) ; for ( int i = ; i < LOOP ; i ++ ) { simpleDispatcher . sendEventToSubscriber ( subscriber , "" ) ; } timer . stop ( ) ; System . out . println ( "" + timer ) ; } } package net . ggtools . grand . ui . widgets . property ; import java . util . Properties ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; public class PropertyEditorTestApp { public static void main ( final String [ ] args ) { final Shell shell = new Shell ( ) ; shell . setText ( "" ) ; shell . setLayout ( new FillLayout ( ) ) ; final Composite composite = new Composite ( shell , SWT . NONE ) ; composite . setLayout ( new FillLayout ( ) ) ; final PropertyEditor propertyViewer = new PropertyEditor ( composite , SWT . NONE ) ; final Properties props = new Properties ( ) ; props . setProperty ( "" , "" ) ; props . setProperty ( "" , "" ) ; props . setProperty ( "" , "" ) ; propertyViewer . setInput ( props ) ; shell . open ( ) ; final Display display = shell . getDisplay ( ) ; while ( ! shell . isDisposed ( ) ) { if ( ! display . readAndDispatch ( ) ) { display . sleep ( ) ; } } System . err . println ( propertyViewer . getPropertyList ( ) ) ; System . exit ( ) ; } } package net . ggtools . grand . ui . menu ; import net . ggtools . grand . ui . actions . OpenFileAction ; import net . ggtools . grand . ui . actions . PageSetupAction ; import net . ggtools . grand . ui . actions . PreferenceAction ; import net . ggtools . grand . ui . actions . PrintAction ; import net . ggtools . grand . ui . actions . QuickOpenFileAction ; import net . ggtools . grand . ui . actions . QuitAction ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; public class FileMenuManager extends MenuManager { public FileMenuManager ( final GraphWindow window ) { super ( "" ) ; add ( new QuickOpenFileAction ( window ) ) ; add ( new OpenFileAction ( window ) ) ; add ( new Separator ( "" ) ) ; add ( new PageSetupAction ( window ) ) ; add ( new PrintAction ( window ) ) ; add ( new PreferenceAction ( window ) ) ; add ( new Separator ( "" ) ) ; add ( new RecentFilesMenu ( window ) ) ; add ( new Separator ( "" ) ) ; add ( new QuitAction ( ) ) ; } } package net . ggtools . grand . ui . menu ; import java . io . File ; import java . util . Collection ; import java . util . Iterator ; import net . ggtools . grand . ui . RecentFilesListener ; import net . ggtools . grand . ui . RecentFilesManager ; import net . ggtools . grand . ui . actions . ClearRecentFilesAction ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IContributionItem ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . swt . widgets . Display ; public class RecentFilesMenu extends MenuManager implements RecentFilesListener { private class OpenRecentFileAction extends Action { private final File file ; private final GraphWindow window ; public OpenRecentFileAction ( final GraphWindow window , final String fileName ) { super ( fileName ) ; this . window = window ; file = new File ( fileName ) ; } @ Override public void run ( ) { window . openGraphInNewDisplayer ( file , RecentFilesManager . getInstance ( ) . getProperties ( file ) ) ; } } private static final Log log = LogFactory . getLog ( RecentFilesMenu . class ) ; private static final String RECENT_FILES_GROUP = "" ; private final GraphWindow window ; public RecentFilesMenu ( final GraphWindow window ) { super ( "" ) ; this . window = window ; add ( new ClearRecentFilesAction ( ) ) ; add ( new Separator ( RECENT_FILES_GROUP ) ) ; RecentFilesManager . getInstance ( ) . addListener ( this ) ; } public void refreshRecentFiles ( final Collection < String > recentFiles ) { final Runnable runnable = new Runnable ( ) { public void run ( ) { final IContributionItem [ ] items = getItems ( ) ; for ( int i = indexOf ( RECENT_FILES_GROUP ) + ; i < items . length ; i ++ ) { IContributionItem item = items [ i ] ; if ( item . isGroupMarker ( ) ) { break ; } remove ( item ) ; } for ( final Iterator < String > iter = recentFiles . iterator ( ) ; iter . hasNext ( ) ; ) { final String fileName = iter . next ( ) ; appendToGroup ( RECENT_FILES_GROUP , new OpenRecentFileAction ( window , fileName ) ) ; } } } ; if ( Display . getCurrent ( ) == null ) { Display . getDefault ( ) . syncExec ( runnable ) ; } else { runnable . run ( ) ; } } } package net . ggtools . grand . ui . menu ; import net . ggtools . grand . ui . actions . ShowLogAction ; import net . ggtools . grand . ui . actions . ShowOutlinePanelAction ; import net . ggtools . grand . ui . actions . ShowSourcePanelAction ; import net . ggtools . grand . ui . actions . UseBusRoutingAction ; import net . ggtools . grand . ui . actions . ZoomInAction ; import net . ggtools . grand . ui . actions . ZoomOutAction ; import net . ggtools . grand . ui . actions . ZoomResetAction ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; public class ViewMenu extends MenuManager { public ViewMenu ( final GraphWindow window ) { super ( "" ) ; add ( new Separator ( "" ) ) ; add ( new ShowSourcePanelAction ( window ) ) ; add ( new ShowOutlinePanelAction ( window ) ) ; add ( new Separator ( "" ) ) ; add ( new UseBusRoutingAction ( window ) ) ; add ( new Separator ( "" ) ) ; add ( new ZoomInAction ( window ) ) ; add ( new ZoomOutAction ( window ) ) ; add ( new ZoomResetAction ( window ) ) ; add ( new Separator ( "" ) ) ; add ( new ShowLogAction ( window ) ) ; } } package net . ggtools . grand . ui . menu ; import net . ggtools . grand . ui . actions . ClearFiltersAction ; import net . ggtools . grand . ui . actions . EditGraphPropertiesAction ; import net . ggtools . grand . ui . actions . ExportGraphAction ; import net . ggtools . grand . ui . actions . FilterConnectedToNodeAction ; import net . ggtools . grand . ui . actions . FilterFromNodeAction ; import net . ggtools . grand . ui . actions . FilterIsolatedNodesAction ; import net . ggtools . grand . ui . actions . FilterMissingNodesAction ; import net . ggtools . grand . ui . actions . FilterSelectedNodesAction ; import net . ggtools . grand . ui . actions . FilterToNodeAction ; import net . ggtools . grand . ui . actions . ReloadGraphAction ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; public class GraphMenu extends MenuManager { public GraphMenu ( final GraphControlerProvider controlerProvider ) { super ( "" ) ; add ( new ReloadGraphAction ( controlerProvider ) ) ; add ( new EditGraphPropertiesAction ( controlerProvider ) ) ; add ( new ExportGraphAction ( controlerProvider ) ) ; add ( new Separator ( "" ) ) ; add ( new FilterIsolatedNodesAction ( controlerProvider ) ) ; add ( new FilterMissingNodesAction ( controlerProvider ) ) ; add ( new Separator ( "" ) ) ; add ( new FilterSelectedNodesAction ( controlerProvider ) ) ; add ( new FilterConnectedToNodeAction ( controlerProvider ) ) ; add ( new FilterFromNodeAction ( controlerProvider ) ) ; add ( new FilterToNodeAction ( controlerProvider ) ) ; add ( new Separator ( "" ) ) ; add ( new ClearFiltersAction ( controlerProvider ) ) ; } } package net . ggtools . grand . ui . menu ; import net . ggtools . grand . ui . actions . AboutAction ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . eclipse . jface . action . MenuManager ; public class HelpMenu extends MenuManager { public HelpMenu ( final GraphWindow window ) { super ( "" ) ; add ( new AboutAction ( window ) ) ; } } package net . ggtools . grand . ui . image ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . ImageLoader ; import org . eclipse . swt . graphics . PaletteData ; import org . eclipse . swt . graphics . RGB ; public class ImageSaver { private static class ColorCounter implements Comparable { private static final Log log = LogFactory . getLog ( ColorCounter . class ) ; int count ; RGB rgb ; public int compareTo ( final Object o ) { return ( ( ColorCounter ) o ) . count - count ; } } private static class ImageFormat { public final String name ; public final boolean needDownsampling ; public final int swtId ; public ImageFormat ( final String name , final int swtId , final boolean needDownsampling ) { this . name = name ; this . swtId = swtId ; this . needDownsampling = needDownsampling ; } } private static boolean formatInitDone = false ; private final static Map < String , ImageFormat > formatRegistry = new HashMap < String , ImageFormat > ( ) ; private static final Log log = LogFactory . getLog ( ImageSaver . class ) ; private static String [ ] supportedExtensions ; private static int closest ( final RGB [ ] rgbs , final int n , final RGB rgb ) { int minDist = * * ; int minIndex = ; for ( int i = ; i < n ; ++ i ) { final RGB rgb2 = rgbs [ i ] ; final int da = rgb2 . red - rgb . red ; final int dg = rgb2 . green - rgb . green ; final int db = rgb2 . blue - rgb . blue ; final int dist = da * da + dg * dg + db * db ; if ( dist < minDist ) { minDist = dist ; minIndex = i ; } } return minIndex ; } private static ImageData downSample ( final Image image ) { final ImageData data = image . getImageData ( ) ; if ( ! data . palette . isDirect && ( data . depth <= ) ) { return data ; } final HashMap < RGB , ColorCounter > freq = new HashMap < RGB , ColorCounter > ( ) ; final int width = data . width ; final int [ ] pixels = new int [ width ] ; final int [ ] maskPixels = new int [ width ] ; for ( int y = , height = data . height ; y < height ; ++ y ) { data . getPixels ( , y , width , pixels , ) ; for ( int x = ; x < width ; ++ x ) { final RGB rgb = data . palette . getRGB ( pixels [ x ] ) ; ColorCounter counter = freq . get ( rgb ) ; if ( counter == null ) { counter = new ColorCounter ( ) ; counter . rgb = rgb ; freq . put ( rgb , counter ) ; } counter . count ++ ; } } final ColorCounter [ ] counters = new ColorCounter [ freq . size ( ) ] ; freq . values ( ) . toArray ( counters ) ; Arrays . sort ( counters ) ; ImageData mask = null ; if ( ( data . transparentPixel != - ) || ( data . maskData != null ) ) { mask = data . getTransparencyMask ( ) ; } final int n = Math . min ( , freq . size ( ) ) ; final RGB [ ] rgbs = new RGB [ n + ( mask != null ? : ) ] ; for ( int i = ; i < n ; ++ i ) { rgbs [ i ] = counters [ i ] . rgb ; } if ( mask != null ) { rgbs [ rgbs . length - ] = data . transparentPixel != - ? data . palette . getRGB ( data . transparentPixel ) : new RGB ( , , ) ; } final PaletteData palette = new PaletteData ( rgbs ) ; final ImageData newData = new ImageData ( width , data . height , , palette ) ; if ( mask != null ) { newData . transparentPixel = rgbs . length - ; } for ( int y = , height = data . height ; y < height ; ++ y ) { data . getPixels ( , y , width , pixels , ) ; if ( mask != null ) { mask . getPixels ( , y , width , maskPixels , ) ; } for ( int x = ; x < width ; ++ x ) { if ( ( mask != null ) && ( maskPixels [ x ] == ) ) { pixels [ x ] = rgbs . length - ; } else { final RGB rgb = data . palette . getRGB ( pixels [ x ] ) ; pixels [ x ] = closest ( rgbs , n , rgb ) ; } } newData . setPixels ( , y , width , pixels , ) ; } return newData ; } private final static void initFormats ( ) { if ( ! formatInitDone ) { final ImageFormat jpegImageFormat = new ImageFormat ( "" , SWT . IMAGE_JPEG , false ) ; formatRegistry . put ( "" , jpegImageFormat ) ; formatRegistry . put ( "" , jpegImageFormat ) ; formatRegistry . put ( "" , new ImageFormat ( "" , SWT . IMAGE_GIF , true ) ) ; formatRegistry . put ( "" , new ImageFormat ( "" , SWT . IMAGE_PNG , false ) ) ; formatRegistry . put ( "" , new ImageFormat ( "" , SWT . IMAGE_BMP , false ) ) ; supportedExtensions = formatRegistry . keySet ( ) . toArray ( new String [ formatRegistry . keySet ( ) . size ( ) ] ) ; formatInitDone = true ; } } public ImageSaver ( ) { initFormats ( ) ; } public final String [ ] getSupportedExtensions ( ) { return supportedExtensions ; } public void saveImage ( final Image image , final String fileName ) throws IOException , IllegalArgumentException { final int lastDotPosition = fileName . lastIndexOf ( '' ) ; final String extension = fileName . substring ( lastDotPosition + ) . toLowerCase ( ) ; if ( ! formatRegistry . containsKey ( extension ) ) { final String message = "" + extension ; log . error ( message ) ; throw new IllegalArgumentException ( message ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "" + fileName + "" + extension ) ; } final ImageFormat format = formatRegistry . get ( extension ) ; FileOutputStream result = null ; try { result = new FileOutputStream ( fileName ) ; ImageData imageData = image . getImageData ( ) ; if ( format . needDownsampling && ( imageData . depth > ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } imageData = downSample ( image ) ; } final ImageLoader imageLoader = new ImageLoader ( ) ; imageLoader . data = new ImageData [ ] { imageData } ; imageLoader . save ( result , format . swtId ) ; } catch ( final FileNotFoundException e ) { throw e ; } finally { if ( result != null ) { try { result . close ( ) ; } catch ( final IOException e ) { log . warn ( "" , e ) ; } } } } } package net . ggtools . grand . ui ; import java . io . File ; import java . io . IOException ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Properties ; import net . ggtools . grand . ui . prefs . PreferenceKeys ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; public class RecentFilesManager implements IPropertyChangeListener , PreferenceKeys { private static final Log log = LogFactory . getLog ( RecentFilesManager . class ) ; private static RecentFilesManager instance ; private int maxFiles = - ; private final LinkedList < String > recentFiles = new LinkedList < String > ( ) ; private final GrandUiPrefStore preferenceStore ; private final Collection < RecentFilesListener > subscribers ; private final List < String > readOnlyRecentFiles ; private RecentFilesManager ( ) { subscribers = new HashSet < RecentFilesListener > ( ) ; readOnlyRecentFiles = Collections . unmodifiableList ( recentFiles ) ; preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; loadRecentFiles ( ) ; } public void addListener ( final RecentFilesListener listener ) { if ( ! subscribers . contains ( listener ) ) { subscribers . add ( listener ) ; listener . refreshRecentFiles ( getRecentFiles ( ) ) ; } } public void removeListener ( final RecentFilesListener listener ) { subscribers . remove ( listener ) ; } private void notifyListeners ( ) { for ( final Iterator < RecentFilesListener > iter = subscribers . iterator ( ) ; iter . hasNext ( ) ; ) { final RecentFilesListener listener = iter . next ( ) ; listener . refreshRecentFiles ( getRecentFiles ( ) ) ; } } static public RecentFilesManager getInstance ( ) { if ( instance == null ) { instance = new RecentFilesManager ( ) ; } return instance ; } public void addNewFile ( final File file ) { addNewFile ( file , null ) ; } public void addNewFile ( final File file , final Properties properties ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + file + "" ) ; } final String fileName = file . getAbsolutePath ( ) ; recentFiles . remove ( fileName ) ; recentFiles . addFirst ( fileName ) ; removeExcessFiles ( ) ; preferenceStore . setValue ( RECENT_FILES_PREFS_KEY , recentFiles ) ; if ( properties == null ) { preferenceStore . setPropertiesToDefault ( getKeyForProperties ( fileName ) ) ; } else { preferenceStore . setValue ( getKeyForProperties ( fileName ) , properties ) ; } try { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } preferenceStore . save ( ) ; } catch ( final IOException e ) { log . error ( "" , e ) ; } notifyListeners ( ) ; } public void updatePropertiesFor ( final File file , final Properties properties ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + file ) ; } final String fileName = file . getAbsolutePath ( ) ; if ( recentFiles . contains ( fileName ) ) { if ( properties == null ) { preferenceStore . setPropertiesToDefault ( getKeyForProperties ( fileName ) ) ; } else { preferenceStore . setValue ( getKeyForProperties ( fileName ) , properties ) ; } try { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } preferenceStore . save ( ) ; } catch ( final IOException e ) { log . error ( "" , e ) ; } } } private String getKeyForProperties ( final String fileName ) { return RECENT_FILES_PREFS_KEY + "" + fileName ; } public void clear ( ) { recentFiles . clear ( ) ; preferenceStore . setToDefault ( RECENT_FILES_PREFS_KEY ) ; try { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } preferenceStore . save ( ) ; } catch ( final IOException e ) { log . warn ( "" , e ) ; } notifyListeners ( ) ; } private final void loadRecentFiles ( ) { maxFiles = preferenceStore . getInt ( MAX_RECENT_FILES_PREFS_KEY ) ; recentFiles . clear ( ) ; recentFiles . addAll ( preferenceStore . getCollection ( RECENT_FILES_PREFS_KEY , maxFiles ) ) ; notifyListeners ( ) ; } public void propertyChange ( final PropertyChangeEvent event ) { final String changedProperty = event . getProperty ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" + changedProperty + "" + event . getNewValue ( ) + "" ) ; } if ( MAX_RECENT_FILES_PREFS_KEY . equals ( changedProperty ) ) { maxFiles = preferenceStore . getInt ( MAX_RECENT_FILES_PREFS_KEY ) ; removeExcessFiles ( ) ; preferenceStore . setValue ( RECENT_FILES_PREFS_KEY , recentFiles ) ; } } private void removeExcessFiles ( ) { while ( recentFiles . size ( ) > maxFiles ) { recentFiles . removeLast ( ) ; } } public final Collection < String > getRecentFiles ( ) { return readOnlyRecentFiles ; } public Properties getProperties ( final File file ) { if ( file == null ) { return null ; } else { return getProperties ( file . getAbsolutePath ( ) ) ; } } public Properties getProperties ( final String fileName ) { return preferenceStore . getProperties ( getKeyForProperties ( fileName ) ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . RecentFilesManager ; import org . eclipse . jface . action . Action ; public class ClearRecentFilesAction extends Action { public ClearRecentFilesAction ( ) { super ( "" ) ; } @ Override public void run ( ) { RecentFilesManager . getInstance ( ) . clear ( ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . widgets . GraphWindow ; import net . ggtools . grand . ui . widgets . PageSetupDialog ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; public class PageSetupAction extends Action { private static final Log log = LogFactory . getLog ( PageSetupAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; public PageSetupAction ( final GraphWindow parent ) { super ( DEFAULT_ACTION_NAME ) ; window = parent ; } @ Override public void run ( ) { final PageSetupDialog dialog = new PageSetupDialog ( window . getShell ( ) ) ; dialog . open ( ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . filters . FromNodeFilter ; import net . ggtools . grand . filters . GraphFilter ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . graph . GraphListener ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class FilterFromNodeAction extends GraphSelectionAction implements GraphListener { private static final Log log = LogFactory . getLog ( FilterFromNodeAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; public FilterFromNodeAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME ) ; } @ Override public void run ( ) { final GraphFilter filter = new FromNodeFilter ( getCurrentNode ( ) ) ; getGraphControler ( ) . addFilter ( filter ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . graph . GraphControler ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class UseBusRoutingAction extends GraphListenerAction { private static final String DEFAULT_ACTION_NAME = "" ; private static final Log log = LogFactory . getLog ( UseBusRoutingAction . class ) ; public UseBusRoutingAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME , AS_CHECK_BOX ) ; } @ Override public void parameterChanged ( final GraphControler controler ) { final boolean newState = getGraphControler ( ) . isBusRoutingEnabled ( ) ; if ( newState != isChecked ( ) ) { setChecked ( newState ) ; } } @ Override public void run ( ) { getGraphControler ( ) . enableBusRouting ( isChecked ( ) ) ; } @ Override protected void postAddHook ( ) { super . postAddHook ( ) ; setEnabled ( true ) ; setChecked ( getGraphControler ( ) . isBusRoutingEnabled ( ) ) ; } @ Override protected void postInitHook ( ) { super . postInitHook ( ) ; if ( getGraphControler ( ) != null ) { setChecked ( getGraphControler ( ) . isBusRoutingEnabled ( ) ) ; setEnabled ( true ) ; } else { setEnabled ( false ) ; } } } package net . ggtools . grand . ui . actions ; import java . util . Collection ; import net . ggtools . grand . ui . graph . GraphControler ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . graph . GraphListener ; import org . eclipse . jface . resource . ImageDescriptor ; public abstract class GraphListenerAction extends GraphControlerAction implements GraphListener { public GraphListenerAction ( final GraphControlerProvider parent ) { super ( parent ) ; } public GraphListenerAction ( final GraphControlerProvider parent , final String text ) { super ( parent , text ) ; } public GraphListenerAction ( final GraphControlerProvider parent , final String text , final ImageDescriptor image ) { super ( parent , text , image ) ; } public GraphListenerAction ( final GraphControlerProvider parent , final String text , final int style ) { super ( parent , text , style ) ; } public void parameterChanged ( final GraphControler controler ) { } public void selectionChanged ( final Collection selectedNodes ) { } @ Override protected void postAddHook ( ) { getGraphControler ( ) . addListener ( this ) ; } @ Override protected void postInitHook ( ) { if ( getGraphControler ( ) != null ) { getGraphControler ( ) . addListener ( this ) ; } } @ Override protected void preRemoveHook ( ) { getGraphControler ( ) . removeSelectionListener ( this ) ; setEnabled ( false ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . widgets . PropertyEditionDialog ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . window . Window ; public class EditGraphPropertiesAction extends GraphControlerAction { private static final Log log = LogFactory . getLog ( EditGraphPropertiesAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; @ Override public void run ( ) { final PropertyEditionDialog dialog = new PropertyEditionDialog ( getGraphControler ( ) . getWindow ( ) . getShell ( ) ) ; dialog . setProperties ( getGraphControler ( ) . getGraphProperties ( ) ) ; if ( dialog . open ( ) == Window . OK ) { getGraphControler ( ) . reloadGraph ( dialog . getProperties ( ) ) ; } } public EditGraphPropertiesAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . filters . GraphFilter ; import net . ggtools . grand . filters . MissingNodeFilter ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class FilterMissingNodesAction extends GraphControlerAction { private static final Log log = LogFactory . getLog ( FilterMissingNodesAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; @ Override public void run ( ) { final GraphFilter filter = new MissingNodeFilter ( ) ; getGraphControler ( ) . addFilter ( filter ) ; } public FilterMissingNodesAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . filters . GraphFilter ; import net . ggtools . grand . filters . IsolatedNodeFilter ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class FilterIsolatedNodesAction extends GraphControlerAction { private static final Log log = LogFactory . getLog ( FilterIsolatedNodesAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; @ Override public void run ( ) { final GraphFilter filter = new IsolatedNodeFilter ( ) ; getGraphControler ( ) . addFilter ( filter ) ; } public FilterIsolatedNodesAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class ClearFiltersAction extends GraphControlerAction { private static final Log log = LogFactory . getLog ( ClearFiltersAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; @ Override public void run ( ) { getGraphControler ( ) . clearFilters ( ) ; } public ClearFiltersAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . filters . ConnectedToNodeFilter ; import net . ggtools . grand . filters . GraphFilter ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . graph . GraphListener ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class FilterConnectedToNodeAction extends GraphSelectionAction implements GraphListener { private static final Log log = LogFactory . getLog ( FilterConnectedToNodeAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; @ Override public void run ( ) { final GraphFilter filter = new ConnectedToNodeFilter ( getCurrentNode ( ) ) ; getGraphControler ( ) . addFilter ( filter ) ; } public FilterConnectedToNodeAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . swt . SWT ; import org . eclipse . swt . printing . PrintDialog ; import org . eclipse . swt . printing . Printer ; import org . eclipse . swt . printing . PrinterData ; public class PrintAction extends GraphControlerAction { private static final Log log = LogFactory . getLog ( PrintAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; @ Override public void run ( ) { final PrintDialog dialog = new PrintDialog ( window . getShell ( ) ) ; final PrinterData printerData = dialog . open ( ) ; log . debug ( "" + printerData ) ; if ( printerData != null ) { final Printer printer = new Printer ( printerData ) ; getGraphControler ( ) . print ( printer ) ; printer . dispose ( ) ; } if ( SWT . getPlatform ( ) . equals ( "" ) ) { getGraphControler ( ) . dotPrint ( ) ; } } public PrintAction ( final GraphWindow parent ) { this ( parent , DEFAULT_ACTION_NAME ) ; } public PrintAction ( final GraphWindow parent , final String name ) { super ( parent , name ) ; window = parent ; setAccelerator ( SWT . CONTROL | '' ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; public class ShowSourcePanelAction extends Action { private static final Log log = LogFactory . getLog ( ShowSourcePanelAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; public ShowSourcePanelAction ( final GraphWindow parent ) { super ( DEFAULT_ACTION_NAME ) ; window = parent ; setChecked ( parent . isSourcePanelVisible ( ) ) ; setAccelerator ( '' ) ; } @ Override public void run ( ) { window . setSourcePanelVisible ( isChecked ( ) ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . swt . SWT ; public class ZoomInAction extends GraphControlerAction { private static final String DEFAULT_ACTION_NAME = "" ; private static final Log log = LogFactory . getLog ( ZoomInAction . class ) ; public ZoomInAction ( final GraphControlerProvider provider ) { super ( provider , DEFAULT_ACTION_NAME ) ; setAccelerator ( SWT . PAGE_UP ) ; } @ Override public void run ( ) { getGraphControler ( ) . getDisplayer ( ) . zoomIn ( ) ; } } package net . ggtools . grand . ui . actions ; import java . io . IOException ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . image . ImageSaver ; import net . ggtools . grand . ui . widgets . ExceptionDialog ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Shell ; public class ExportGraphAction extends GraphControlerAction { private static final String DEFAULT_ACTION_NAME = "" ; private static final Log log = LogFactory . getLog ( ExportGraphAction . class ) ; public ExportGraphAction ( final GraphControlerProvider parent ) { this ( parent , DEFAULT_ACTION_NAME ) ; } public ExportGraphAction ( final GraphControlerProvider parent , final String name ) { super ( parent , name ) ; } @ Override public void run ( ) { final Shell parentShell = getGraphControler ( ) . getWindow ( ) . getShell ( ) ; final FileDialog dialog = new FileDialog ( parentShell , SWT . SAVE ) ; final ImageSaver imageSaver = new ImageSaver ( ) ; dialog . setFilterExtensions ( imageSaver . getSupportedExtensions ( ) ) ; dialog . setText ( "" ) ; final String fileName = dialog . open ( ) ; log . debug ( "" + fileName ) ; if ( fileName != null ) { Image image = null ; try { image = getGraphControler ( ) . createImageForGraph ( ) ; imageSaver . saveImage ( image , fileName ) ; } catch ( final IllegalArgumentException e ) { ExceptionDialog . openException ( parentShell , "" , e ) ; } catch ( final IOException e ) { ExceptionDialog . openException ( parentShell , "" , e ) ; } finally { if ( image != null ) { image . dispose ( ) ; } } } } } package net . ggtools . grand . ui . actions ; import java . util . Collection ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import net . ggtools . grand . filters . GraphFilter ; import net . ggtools . grand . filters . NodeRemoverFilter ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . graph . draw2d . Draw2dNode ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class FilterSelectedNodesAction extends GraphListenerAction { private static final String DEFAULT_ACTION_NAME = "" ; private static final Log log = LogFactory . getLog ( FilterSelectedNodesAction . class ) ; public FilterSelectedNodesAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME ) ; boolean isEnabled = false ; if ( getGraphControler ( ) != null ) { final Collection < Draw2dNode > selectedNodes = getGraphControler ( ) . getSelection ( ) ; isEnabled = ! selectedNodes . isEmpty ( ) ; } setEnabled ( isEnabled ) ; } @ Override public void run ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } final Collection < Draw2dNode > selection = getGraphControler ( ) . getSelection ( ) ; final List < String > nodeList = new LinkedList < String > ( ) ; for ( final Iterator < Draw2dNode > iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { final Draw2dNode node = iter . next ( ) ; nodeList . add ( node . getName ( ) ) ; } final GraphFilter filter = new NodeRemoverFilter ( nodeList ) ; getGraphControler ( ) . addFilter ( filter ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } } @ Override public void selectionChanged ( final Collection selectedNodes ) { setEnabled ( ! selectedNodes . isEmpty ( ) ) ; } } package net . ggtools . grand . ui . actions ; import java . io . File ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . FileDialog ; public class QuickOpenFileAction extends Action { private static final Log log = LogFactory . getLog ( QuickOpenFileAction . class ) ; private static final String [ ] FILTER_EXTENSIONS = new String [ ] { "" , "" } ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; private String previousPath ; @ Override public void run ( ) { final FileDialog dialog = new FileDialog ( window . getShell ( ) ) ; dialog . setFilterExtensions ( FILTER_EXTENSIONS ) ; dialog . setFilterPath ( previousPath ) ; final String buildFileName = dialog . open ( ) ; log . debug ( "" + buildFileName ) ; if ( buildFileName != null ) { previousPath = dialog . getFilterPath ( ) ; window . openGraphInNewDisplayer ( new File ( buildFileName ) , null ) ; } } public QuickOpenFileAction ( final GraphWindow parent ) { super ( DEFAULT_ACTION_NAME ) ; window = parent ; setAccelerator ( SWT . CONTROL | '' ) ; } public QuickOpenFileAction ( final String name , final GraphWindow parent ) { super ( name ) ; window = parent ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; public class ShowOutlinePanelAction extends Action { private static final Log log = LogFactory . getLog ( ShowOutlinePanelAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; public ShowOutlinePanelAction ( final GraphWindow parent ) { super ( DEFAULT_ACTION_NAME ) ; window = parent ; setChecked ( parent . isOutlinePanelVisible ( ) ) ; setAccelerator ( '' ) ; } @ Override public void run ( ) { window . setOutlinePanelVisible ( isChecked ( ) ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . swt . SWT ; public class ZoomOutAction extends GraphControlerAction { private static final String DEFAULT_ACTION_NAME = "" ; private static final Log log = LogFactory . getLog ( ZoomOutAction . class ) ; public ZoomOutAction ( final GraphControlerProvider provider ) { super ( provider , DEFAULT_ACTION_NAME ) ; setAccelerator ( SWT . PAGE_DOWN ) ; } @ Override public void run ( ) { getGraphControler ( ) . getDisplayer ( ) . zoomOut ( ) ; } } package net . ggtools . grand . ui . actions ; import java . util . Collection ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . graph . GraphListener ; import net . ggtools . grand . ui . graph . draw2d . Draw2dNode ; import org . eclipse . jface . resource . ImageDescriptor ; public abstract class GraphSelectionAction extends GraphListenerAction implements GraphListener { private String currentNode ; public GraphSelectionAction ( final GraphControlerProvider parent ) { super ( parent ) ; init ( ) ; } public GraphSelectionAction ( final GraphControlerProvider parent , final String text ) { super ( parent , text ) ; init ( ) ; } public GraphSelectionAction ( final GraphControlerProvider parent , final String text , final ImageDescriptor image ) { super ( parent , text , image ) ; init ( ) ; } public GraphSelectionAction ( final GraphControlerProvider parent , final String text , final int style ) { super ( parent , text , style ) ; init ( ) ; } public final String getCurrentNode ( ) { return currentNode ; } @ Override public void selectionChanged ( final Collection selectedNodes ) { final boolean isEnabled = selectedNodes . size ( ) == ; if ( isEnabled ) { currentNode = ( ( Draw2dNode ) selectedNodes . iterator ( ) . next ( ) ) . getName ( ) ; } setEnabled ( isEnabled ) ; } final private void init ( ) { boolean isEnabled = false ; if ( getGraphControler ( ) != null ) { final Collection < Draw2dNode > selectedNodes = getGraphControler ( ) . getSelection ( ) ; isEnabled = selectedNodes . size ( ) == ; if ( isEnabled ) { currentNode = selectedNodes . iterator ( ) . next ( ) . getName ( ) ; } } setEnabled ( isEnabled ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . prefs . GrandUiPreferenceManager ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . preference . PreferenceDialog ; public class PreferenceAction extends Action { private static final Log log = LogFactory . getLog ( PreferenceAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; @ Override public void run ( ) { final GrandUiPreferenceManager pm = new GrandUiPreferenceManager ( ) ; final PreferenceDialog dialog = new PreferenceDialog ( window . getShell ( ) , pm ) ; dialog . open ( ) ; } public PreferenceAction ( final GraphWindow parent ) { super ( DEFAULT_ACTION_NAME ) ; window = parent ; } } package net . ggtools . grand . ui . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . SWT ; public class QuitAction extends Action { private static final String DEFAULT_ACTION_NAME = "" ; public QuitAction ( ) { super ( DEFAULT_ACTION_NAME ) ; setAccelerator ( SWT . CONTROL | '' ) ; } @ Override public void run ( ) { System . exit ( ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . swt . SWT ; public class ReloadGraphAction extends GraphControlerAction { private static final Log log = LogFactory . getLog ( ReloadGraphAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; @ Override public void run ( ) { getGraphControler ( ) . reloadGraph ( ) ; } public ReloadGraphAction ( final GraphControlerProvider parent ) { this ( parent , DEFAULT_ACTION_NAME ) ; } public ReloadGraphAction ( final GraphControlerProvider parent , final String name ) { super ( parent , name ) ; setAccelerator ( SWT . F5 ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . widgets . GraphWindow ; import net . ggtools . grand . ui . widgets . LogWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . widgets . Shell ; public class ShowLogAction extends Action { private final class DialogDisposeListener implements DisposeListener { private final Shell shell ; private DialogDisposeListener ( final Shell shell ) { super ( ) ; this . shell = shell ; } public void widgetDisposed ( final DisposeEvent e ) { setChecked ( false ) ; shell . removeDisposeListener ( this ) ; dialog = null ; } } private static final Log log = LogFactory . getLog ( ShowLogAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; private LogWindow dialog ; public ShowLogAction ( final GraphWindow parent ) { super ( DEFAULT_ACTION_NAME ) ; setChecked ( false ) ; window = parent ; setAccelerator ( '' ) ; } @ Override public void run ( ) { if ( isChecked ( ) ) { if ( ( dialog != null ) && dialog . getShell ( ) . isDisposed ( ) ) { dialog = null ; } if ( dialog == null ) { dialog = new LogWindow ( window . getShell ( ) ) ; } dialog . open ( ) ; final Shell shell = dialog . getShell ( ) ; shell . addDisposeListener ( new DialogDisposeListener ( shell ) ) ; } else { if ( dialog != null ) { dialog . close ( ) ; dialog = null ; } } } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . widgets . GraphWindow ; import net . ggtools . grand . ui . widgets . OpenFileWizard ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . wizard . IWizard ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . swt . SWT ; public class OpenFileAction extends Action { private static final Log log = LogFactory . getLog ( OpenFileAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; @ Override public void run ( ) { final IWizard wizard = new OpenFileWizard ( window ) ; final WizardDialog dialog = new WizardDialog ( window . getShell ( ) , wizard ) ; dialog . create ( ) ; dialog . open ( ) ; } public OpenFileAction ( final GraphWindow parent ) { super ( DEFAULT_ACTION_NAME ) ; window = parent ; setAccelerator ( SWT . SHIFT | SWT . CONTROL | '' ) ; } public OpenFileAction ( final String name , final GraphWindow parent ) { super ( name ) ; window = parent ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . widgets . AboutDialog ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . action . Action ; public class AboutAction extends Action { private static final Log log = LogFactory . getLog ( AboutAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; private final GraphWindow window ; public AboutAction ( final GraphWindow parent ) { super ( DEFAULT_ACTION_NAME ) ; window = parent ; } @ Override public void run ( ) { final AboutDialog dialog = new AboutDialog ( window . getShell ( ) ) ; dialog . open ( ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . swt . SWT ; public class ZoomResetAction extends GraphControlerAction { private static final String DEFAULT_ACTION_NAME = "" ; private static final Log log = LogFactory . getLog ( ZoomResetAction . class ) ; public ZoomResetAction ( final GraphControlerProvider provider ) { super ( provider , DEFAULT_ACTION_NAME ) ; setAccelerator ( SWT . HOME ) ; } @ Override public void run ( ) { getGraphControler ( ) . getDisplayer ( ) . zoomReset ( ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . ui . graph . GraphControler ; import net . ggtools . grand . ui . graph . GraphControlerListener ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . resource . ImageDescriptor ; public abstract class GraphControlerAction extends Action implements GraphControlerListener { private GraphControler graphControler ; private GraphControlerProvider graphControlerProvider ; public GraphControlerAction ( final GraphControlerProvider parent ) { super ( ) ; init ( parent ) ; } public GraphControlerAction ( final GraphControlerProvider parent , final String text ) { super ( text ) ; init ( parent ) ; } public GraphControlerAction ( final GraphControlerProvider parent , final String text , final ImageDescriptor image ) { super ( text , image ) ; init ( parent ) ; } public GraphControlerAction ( final GraphControlerProvider parent , final String text , final int style ) { super ( text , style ) ; init ( parent ) ; } final public void controlerAvailable ( final GraphControler controler ) { if ( graphControler != null ) { removeGraphControler ( ) ; } graphControler = controler ; postAddHook ( ) ; } final public void controlerRemoved ( final GraphControler controler ) { if ( controler == graphControler ) { removeGraphControler ( ) ; } } final public GraphControler getGraphControler ( ) { return graphControler ; } final public GraphControlerProvider getGraphControlerProvider ( ) { return graphControlerProvider ; } final private void init ( final GraphControlerProvider provider ) { graphControlerProvider = provider ; provider . addControlerListener ( this ) ; graphControler = provider . getControler ( ) ; postInitHook ( ) ; } protected void postInitHook ( ) { setEnabled ( graphControler != null ) ; } private void removeGraphControler ( ) { preRemoveHook ( ) ; graphControler = null ; } protected void postAddHook ( ) { setEnabled ( true ) ; } protected void preRemoveHook ( ) { setEnabled ( false ) ; } } package net . ggtools . grand . ui . actions ; import net . ggtools . grand . filters . GraphFilter ; import net . ggtools . grand . filters . ToNodeFilter ; import net . ggtools . grand . ui . graph . GraphControlerListener ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . graph . GraphListener ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class FilterToNodeAction extends GraphSelectionAction implements GraphControlerListener , GraphListener { private static final Log log = LogFactory . getLog ( FilterToNodeAction . class ) ; private static final String DEFAULT_ACTION_NAME = "" ; public FilterToNodeAction ( final GraphControlerProvider parent ) { super ( parent , DEFAULT_ACTION_NAME ) ; } @ Override public void run ( ) { final GraphFilter filter = new ToNodeFilter ( getCurrentNode ( ) ) ; getGraphControler ( ) . addFilter ( filter ) ; } } package net . ggtools . grand . ui . prefs ; import org . eclipse . jface . preference . BooleanFieldEditor ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . IntegerFieldEditor ; import org . eclipse . swt . widgets . Composite ; public class GraphPreferencePage extends FieldEditorPreferencePage implements PreferenceKeys { public static void setDefaults ( final IPreferenceStore prefs ) { prefs . setDefault ( GRAPH_BUS_ENABLED_DEFAULT , false ) ; prefs . setDefault ( GRAPH_BUS_IN_THRESHOLD , ) ; prefs . setDefault ( GRAPH_BUS_OUT_THRESHOLD , ) ; } public GraphPreferencePage ( ) { super ( "" , GRID ) ; } @ Override protected void createFieldEditors ( ) { final Composite parent = getFieldEditorParent ( ) ; final BooleanFieldEditor enableBusRouting = new BooleanFieldEditor ( GRAPH_BUS_ENABLED_DEFAULT , "" , parent ) ; addField ( enableBusRouting ) ; final IntegerFieldEditor inThreshold = new IntegerFieldEditor ( GRAPH_BUS_IN_THRESHOLD , "" , parent ) ; addField ( inThreshold ) ; final IntegerFieldEditor outThreadshold = new IntegerFieldEditor ( GRAPH_BUS_OUT_THRESHOLD , "" , parent ) ; addField ( outThreadshold ) ; } } package net . ggtools . grand . ui . prefs ; import net . ggtools . grand . ui . Application ; import org . eclipse . jface . preference . IPersistentPreferenceStore ; import org . eclipse . jface . preference . IPreferenceNode ; import org . eclipse . jface . preference . PreferenceManager ; import org . eclipse . jface . preference . PreferenceNode ; import org . eclipse . jface . preference . PreferencePage ; public class GrandUiPreferenceManager extends PreferenceManager { public GrandUiPreferenceManager ( ) { final PreferencePage generalPage = new GeneralPreferencePage ( ) ; final IPersistentPreferenceStore preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; generalPage . setPreferenceStore ( preferenceStore ) ; final IPreferenceNode generalPageNode = new PreferenceNode ( "" , generalPage ) ; addToRoot ( generalPageNode ) ; final PreferencePage graphPage = new GraphPreferencePage ( ) ; graphPage . setPreferenceStore ( preferenceStore ) ; final IPreferenceNode graphNode = new PreferenceNode ( "" , graphPage ) ; addToRoot ( graphNode ) ; final PreferencePage nodePage = new NodesPreferencePage ( ) ; nodePage . setPreferenceStore ( preferenceStore ) ; final IPreferenceNode nodesNode = new PreferenceNode ( "" , nodePage ) ; graphNode . add ( nodesNode ) ; final PreferencePage linksPage = new LinksPreferencePage ( ) ; linksPage . setPreferenceStore ( preferenceStore ) ; final IPreferenceNode linksNode = new PreferenceNode ( "" , linksPage ) ; graphNode . add ( linksNode ) ; } } package net . ggtools . grand . ui . prefs ; public interface PreferenceKeys { public static final String MAX_RECENT_FILES_PREFS_KEY = "" ; public static final String RECENT_FILES_PREFS_KEY = "" ; public static final String GRAPH_PREFIX = "" ; public static final String NODE_PREFIX = GRAPH_PREFIX + "" ; public static final String GRAPH_BUS_ENABLED_DEFAULT = GRAPH_PREFIX + "" ; public static final String GRAPH_BUS_OUT_THRESHOLD = GRAPH_PREFIX + "" ; public static final String GRAPH_BUS_IN_THRESHOLD = GRAPH_PREFIX + "" ; public static final String LINK_SUBANT_COLOR = GRAPH_PREFIX + "" ; public static final String LINK_SUBANT_LINEWIDTH = GRAPH_PREFIX + "" ; public static final String LINK_WEAK_COLOR = GRAPH_PREFIX + "" ; public static final String LINK_WEAK_LINEWIDTH = GRAPH_PREFIX + "" ; public static final String LINK_DEFAULT_COLOR = GRAPH_PREFIX + "" ; public static final String LINK_DEFAULT_LINEWIDTH = GRAPH_PREFIX + "" ; } package net . ggtools . grand . ui . prefs ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . Collection ; import java . util . Date ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . Map ; import java . util . Properties ; import java . util . StringTokenizer ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . Transformer ; import javax . xml . transform . TransformerConfigurationException ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . preference . PreferenceStore ; import org . eclipse . jface . resource . ColorRegistry ; import org . eclipse . jface . resource . FontRegistry ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . graphics . RGB ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; public class ComplexPreferenceStore extends PreferenceStore { private interface PropertyLoader { void addEntry ( final String key , final String value ) ; void addProperties ( final String key , final Element propertiesElement ) ; } private interface PropertySaver { String get ( final String key ) ; Collection < ? > getKeys ( ) ; boolean needSaving ( final String key ) ; } private static final int COLLECTION_NO_LIMIT = - ; private static final String DATE_ATTRIBUTE = "" ; private static final String ENTRY_ELEMENT = "" ; private static final String KEY_ATTRIBUTE = "" ; private static final Log log = LogFactory . getLog ( ComplexPreferenceStore . class ) ; private static final int PREF_FILE_VERSION_MAJOR = ; private static final int PREF_FILE_VERSION_MINOR = ; private static final String PROPERTIES_ELEMENT = "" ; private static final String ROOT_ELEMENT = "" ; private static final String VERSION_ATTRIBUTE = "" ; private static String escapeString ( final String item ) { return item . replaceAll ( "" , "" ) . replaceAll ( "" , "" ) ; } private static String unEscapeString ( final String item ) { return item . replaceAll ( "" , "" ) . replaceAll ( "" , "" ) ; } private final ColorRegistry colorRegistry = new ColorRegistry ( ) ; private final FontRegistry fontRegistry = new FontRegistry ( ) ; private File prefFile ; private final Map < String , Properties > propertiesTable = new HashMap < String , Properties > ( ) ; public Collection < String > getCollection ( final String key ) { return getCollection ( key , COLLECTION_NO_LIMIT ) ; } public Collection < String > getCollection ( final String key , int limit ) { final LinkedList < String > list = new LinkedList < String > ( ) ; final StringTokenizer tokenizer = new StringTokenizer ( getString ( key ) , "" ) ; if ( limit == COLLECTION_NO_LIMIT ) { limit = tokenizer . countTokens ( ) ; } for ( int i = ; ( i < limit ) && tokenizer . hasMoreTokens ( ) ; i ++ ) { list . addLast ( unEscapeString ( tokenizer . nextToken ( ) ) ) ; } return list ; } public Color getColor ( final String key ) { final RGB newRGBColor = PreferenceConverter . getColor ( this , key ) ; final RGB currentRGBColor = colorRegistry . getRGB ( key ) ; if ( ! newRGBColor . equals ( currentRGBColor ) ) { colorRegistry . put ( key , newRGBColor ) ; } return colorRegistry . get ( key ) ; } public Font getFont ( final String key ) { final FontData [ ] newFontDataArray = PreferenceConverter . getFontDataArray ( this , key ) ; final FontData [ ] currentFontDataArray = fontRegistry . getFontData ( key ) ; if ( ! newFontDataArray . equals ( currentFontDataArray ) ) { fontRegistry . put ( key , newFontDataArray ) ; } return fontRegistry . get ( key ) ; } public Properties getProperties ( final String key ) { Properties properties = null ; if ( propertiesTable . containsKey ( key ) ) { properties = new Properties ( ) ; properties . putAll ( propertiesTable . get ( key ) ) ; } return properties ; } @ Override public void load ( ) throws IOException { FileInputStream is = null ; try { is = new FileInputStream ( prefFile ) ; final DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setIgnoringElementContentWhitespace ( true ) ; dbf . setValidating ( false ) ; dbf . setCoalescing ( true ) ; dbf . setIgnoringComments ( true ) ; Document doc = null ; try { final DocumentBuilder db = dbf . newDocumentBuilder ( ) ; final InputSource inputSource = new InputSource ( is ) ; doc = db . parse ( is ) ; } catch ( final ParserConfigurationException e ) { log . error ( "" , e ) ; throw new Error ( e ) ; } catch ( final SAXException e ) { log . error ( "" , e ) ; throw new Error ( e ) ; } final Element rootElement = doc . getDocumentElement ( ) ; if ( rootElement . hasAttribute ( VERSION_ATTRIBUTE ) ) { final String version = rootElement . getAttribute ( VERSION_ATTRIBUTE ) ; final String [ ] versionParts = version . split ( "" , ) ; if ( PREF_FILE_VERSION_MAJOR != Integer . parseInt ( versionParts [ ] ) ) { final String message = "" + version + "" + PREF_FILE_VERSION_MAJOR + "" + PREF_FILE_VERSION_MINOR ; log . error ( message ) ; throw new Error ( message ) ; } if ( log . isInfoEnabled ( ) ) { log . info ( "" + version ) ; } } else { log . warn ( "" ) ; } final PropertyLoader loader = new PropertyLoader ( ) { public void addEntry ( String key , String value ) { putValue ( key , value ) ; } public void addProperties ( final String key , final Element propertiesElement ) { final Properties properties = new Properties ( ) ; final PropertyLoader propertiesLoader = new PropertyLoader ( ) { public void addEntry ( final String k , final String v ) { properties . setProperty ( k , v ) ; } public void addProperties ( final String k , final Element element ) { log . warn ( "" + k ) ; } } ; loadProperties ( propertiesElement , propertiesLoader ) ; propertiesTable . put ( key , properties ) ; } } ; loadProperties ( rootElement , loader ) ; } finally { if ( is != null ) { is . close ( ) ; } } } @ Override public void save ( ) throws IOException { FileOutputStream os = null ; try { os = new FileOutputStream ( prefFile ) ; final DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder db = null ; try { db = dbf . newDocumentBuilder ( ) ; } catch ( final ParserConfigurationException e ) { log . error ( "" , e ) ; throw new Error ( "" , e ) ; } final Document doc = db . newDocument ( ) ; final Element rootElement = ( Element ) doc . appendChild ( doc . createElement ( ROOT_ELEMENT ) ) ; rootElement . setAttribute ( VERSION_ATTRIBUTE , Integer . toString ( PREF_FILE_VERSION_MAJOR ) + "" + PREF_FILE_VERSION_MINOR ) ; rootElement . setAttribute ( DATE_ATTRIBUTE , new Date ( ) . toString ( ) ) ; final PropertySaver prefStoreSaver = new PropertySaver ( ) { public String get ( String key ) { return getString ( key ) ; } public Collection < String > getKeys ( ) { return Arrays . asList ( preferenceNames ( ) ) ; } public boolean needSaving ( String key ) { return ! isDefault ( key ) ; } } ; saveProperties ( doc , rootElement , prefStoreSaver ) ; for ( final Iterator < Map . Entry < String , Properties > > iter = propertiesTable . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final Map . Entry < String , Properties > entry = iter . next ( ) ; final String propKey = entry . getKey ( ) ; final Properties props = entry . getValue ( ) ; final Element currentElement = ( Element ) rootElement . appendChild ( doc . createElement ( PROPERTIES_ELEMENT ) ) ; currentElement . setAttribute ( KEY_ATTRIBUTE , propKey ) ; final PropertySaver propertySaver = new PropertySaver ( ) { public String get ( String key ) { return props . getProperty ( key ) ; } public Collection < ? > getKeys ( ) { return props . keySet ( ) ; } public boolean needSaving ( String key ) { return true ; } } ; saveProperties ( doc , currentElement , propertySaver ) ; } final TransformerFactory tf = TransformerFactory . newInstance ( ) ; Transformer t = null ; try { t = tf . newTransformer ( ) ; t . setOutputProperty ( OutputKeys . INDENT , "" ) ; t . setOutputProperty ( OutputKeys . METHOD , "" ) ; t . setOutputProperty ( OutputKeys . ENCODING , "" ) ; } catch ( final TransformerConfigurationException e ) { log . error ( "" , e ) ; throw new RuntimeException ( "" , e ) ; } final DOMSource doms = new DOMSource ( doc ) ; final StreamResult sr = new StreamResult ( os ) ; try { t . transform ( doms , sr ) ; } catch ( final TransformerException e ) { log . error ( "" , e ) ; final IOException ioe = new IOException ( "" ) ; ioe . initCause ( e ) ; throw ioe ; } } finally { if ( os != null ) { os . close ( ) ; } } } public final void setPrefFile ( final File prefFile ) { this . prefFile = prefFile ; } public void setPropertiesToDefault ( final String key ) { if ( propertiesTable . containsKey ( key ) ) { propertiesTable . remove ( key ) ; } } public void setValue ( final String key , final Collection < String > value ) { final StringBuffer buffer = new StringBuffer ( ) ; for ( final Iterator < String > iter = value . iterator ( ) ; iter . hasNext ( ) ; ) { final String item = iter . next ( ) ; buffer . append ( escapeString ( item ) ) ; if ( iter . hasNext ( ) ) { buffer . append ( "" ) ; } } setValue ( key , buffer . toString ( ) ) ; } public void setValue ( final String key , final Properties props ) { final Properties myProperties = new Properties ( ) ; myProperties . putAll ( props ) ; propertiesTable . remove ( key ) ; propertiesTable . put ( key , myProperties ) ; } private void loadProperties ( final Element propElement , final PropertyLoader loader ) { final NodeList entries = propElement . getChildNodes ( ) ; for ( int i = ; i < entries . getLength ( ) ; i ++ ) { final Node item = entries . item ( i ) ; if ( ENTRY_ELEMENT . equals ( item . getNodeName ( ) ) ) { final Element entryElement = ( Element ) item ; if ( entryElement . hasAttribute ( KEY_ATTRIBUTE ) ) { final Node n = entryElement . getFirstChild ( ) ; final String val = ( n == null ) ? "" : n . getNodeValue ( ) ; loader . addEntry ( entryElement . getAttribute ( KEY_ATTRIBUTE ) , val ) ; } } else if ( PROPERTIES_ELEMENT . equals ( item . getNodeName ( ) ) ) { final Element entryElement = ( Element ) item ; if ( entryElement . hasAttribute ( KEY_ATTRIBUTE ) ) { loader . addProperties ( entryElement . getAttribute ( KEY_ATTRIBUTE ) , entryElement ) ; } } } } private void saveProperties ( final Document doc , final Element properties , final PropertySaver saver ) { final Collection < ? > keys = saver . getKeys ( ) ; for ( Object i : keys ) { final String key = i instanceof String ? ( String ) i : i . toString ( ) ; if ( saver . needSaving ( key ) ) { final Element entry = ( Element ) properties . appendChild ( doc . createElement ( ENTRY_ELEMENT ) ) ; entry . setAttribute ( KEY_ATTRIBUTE , key ) ; entry . appendChild ( doc . createTextNode ( saver . get ( key ) ) ) ; } } } } package net . ggtools . grand . ui . prefs ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . jface . preference . IntegerFieldEditor ; import org . eclipse . swt . widgets . Composite ; public class GeneralPreferencePage extends FieldEditorPreferencePage implements PreferenceKeys { GeneralPreferencePage ( ) { super ( "" , GRID ) ; } @ Override protected void createFieldEditors ( ) { final Composite parent = getFieldEditorParent ( ) ; final IntegerFieldEditor maxFiles = new IntegerFieldEditor ( MAX_RECENT_FILES_PREFS_KEY , "" , parent ) ; addField ( maxFiles ) ; } } package net . ggtools . grand . ui . prefs ; import org . eclipse . draw2d . ColorConstants ; import org . eclipse . jface . preference . ColorFieldEditor ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . IntegerFieldEditor ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . swt . widgets . Composite ; public class LinksPreferencePage extends FieldEditorPreferencePage implements PreferenceKeys { public static void setDefaults ( final IPreferenceStore prefs ) { PreferenceConverter . setDefault ( prefs , LINK_DEFAULT_COLOR , ColorConstants . black . getRGB ( ) ) ; prefs . setDefault ( LINK_DEFAULT_LINEWIDTH , ) ; PreferenceConverter . setDefault ( prefs , LINK_WEAK_COLOR , ColorConstants . lightGray . getRGB ( ) ) ; prefs . setDefault ( LINK_WEAK_LINEWIDTH , ) ; PreferenceConverter . setDefault ( prefs , LINK_SUBANT_COLOR , ColorConstants . lightGray . getRGB ( ) ) ; prefs . setDefault ( LINK_SUBANT_LINEWIDTH , ) ; } public LinksPreferencePage ( ) { super ( "" , GRID ) ; } @ Override protected void createFieldEditors ( ) { final Composite parent = getFieldEditorParent ( ) ; final ColorFieldEditor defaultLinkColor = new ColorFieldEditor ( LINK_DEFAULT_COLOR , "" , parent ) ; addField ( defaultLinkColor ) ; final IntegerFieldEditor defaultLinkLineWidth = new IntegerFieldEditor ( LINK_DEFAULT_LINEWIDTH , "" , parent ) ; defaultLinkLineWidth . setValidRange ( , ) ; addField ( defaultLinkLineWidth ) ; final ColorFieldEditor weakLinkColor = new ColorFieldEditor ( LINK_WEAK_COLOR , "" , parent ) ; addField ( weakLinkColor ) ; final IntegerFieldEditor weakLinkLineWidth = new IntegerFieldEditor ( LINK_WEAK_LINEWIDTH , "" , parent ) ; weakLinkLineWidth . setValidRange ( , ) ; addField ( weakLinkLineWidth ) ; final ColorFieldEditor subantLinkColor = new ColorFieldEditor ( LINK_SUBANT_COLOR , "" , parent ) ; addField ( subantLinkColor ) ; final IntegerFieldEditor subantLinkLineWidth = new IntegerFieldEditor ( LINK_SUBANT_LINEWIDTH , "" , parent ) ; subantLinkLineWidth . setValidRange ( , ) ; addField ( subantLinkLineWidth ) ; } } package net . ggtools . grand . ui . prefs ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import org . eclipse . draw2d . ColorConstants ; import org . eclipse . jface . preference . ColorFieldEditor ; import org . eclipse . jface . preference . FieldEditor ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . IntegerFieldEditor ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . preference . RadioGroupFieldEditor ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . TabFolder ; import org . eclipse . swt . widgets . TabItem ; public class NodesPreferencePage extends PreferencePage implements PreferenceKeys { private static final String [ ] [ ] SUPPORTED_SHAPES = new String [ ] [ ] { { "" , "" } , { "" , "" } , { "" , "" } , { "" , "" } , { "" , "" } , { "" , "" } , { "" , "" } } ; public static void setDefaults ( final IPreferenceStore prefs ) { PreferenceConverter . setDefault ( prefs , NODE_PREFIX + "" , ColorConstants . black . getRGB ( ) ) ; PreferenceConverter . setDefault ( prefs , NODE_PREFIX + "" , ColorConstants . white . getRGB ( ) ) ; prefs . setDefault ( NODE_PREFIX + "" , "" ) ; prefs . setDefault ( NODE_PREFIX + "" , ) ; PreferenceConverter . setDefault ( prefs , NODE_PREFIX + "" , ColorConstants . black . getRGB ( ) ) ; PreferenceConverter . setDefault ( prefs , NODE_PREFIX + "" , ColorConstants . cyan . getRGB ( ) ) ; prefs . setDefault ( NODE_PREFIX + "" , "" ) ; prefs . setDefault ( NODE_PREFIX + "" , ) ; PreferenceConverter . setDefault ( prefs , NODE_PREFIX + "" , ColorConstants . black . getRGB ( ) ) ; PreferenceConverter . setDefault ( prefs , NODE_PREFIX + "" , ColorConstants . yellow . getRGB ( ) ) ; prefs . setDefault ( NODE_PREFIX + "" , "" ) ; prefs . setDefault ( NODE_PREFIX + "" , ) ; PreferenceConverter . setDefault ( prefs , NODE_PREFIX + "" , ColorConstants . gray . getRGB ( ) ) ; PreferenceConverter . setDefault ( prefs , NODE_PREFIX + "" , ColorConstants . lightGray . getRGB ( ) ) ; prefs . setDefault ( NODE_PREFIX + "" , "" ) ; prefs . setDefault ( NODE_PREFIX + "" , ) ; } private final List < FieldEditor > fields = new ArrayList < FieldEditor > ( ) ; NodesPreferencePage ( ) { super ( "" ) ; } @ Override public boolean performOk ( ) { if ( fields != null ) { for ( final Iterator < FieldEditor > iter = fields . iterator ( ) ; iter . hasNext ( ) ; ) { final FieldEditor fieldEditor = iter . next ( ) ; fieldEditor . store ( ) ; } } return true ; } private int calcNumberOfColumns ( final List < FieldEditor > tabFields ) { int result = ; if ( tabFields != null ) { final Iterator < FieldEditor > e = tabFields . iterator ( ) ; while ( e . hasNext ( ) ) { final FieldEditor pe = e . next ( ) ; result = Math . max ( result , pe . getNumberOfControls ( ) ) ; } } return result ; } private void createNodeTab ( final TabFolder tabFolder , final String title , final String nodeType ) { final String prefix = NODE_PREFIX + nodeType ; final TabItem tabItem = new TabItem ( tabFolder , SWT . NONE ) ; tabItem . setText ( title ) ; final Composite parent = new Composite ( tabFolder , SWT . NONE ) ; tabItem . setControl ( parent ) ; final List < FieldEditor > tabFields = new LinkedList < FieldEditor > ( ) ; final ColorFieldEditor fgcolorField = new ColorFieldEditor ( prefix + "" , "" , parent ) ; tabFields . add ( fgcolorField ) ; final ColorFieldEditor fillcolorField = new ColorFieldEditor ( prefix + "" , "" , parent ) ; tabFields . add ( fillcolorField ) ; final RadioGroupFieldEditor shapeField = new RadioGroupFieldEditor ( prefix + "" , "" , , SUPPORTED_SHAPES , parent ) ; tabFields . add ( shapeField ) ; final IntegerFieldEditor lineWidthField = new IntegerFieldEditor ( prefix + "" , "" , parent ) ; lineWidthField . setValidRange ( , ) ; tabFields . add ( lineWidthField ) ; final GridLayout layout = ( GridLayout ) parent . getLayout ( ) ; layout . numColumns = calcNumberOfColumns ( tabFields ) ; if ( tabFields != null ) { for ( final Iterator < FieldEditor > iter = tabFields . iterator ( ) ; iter . hasNext ( ) ; ) { final FieldEditor fieldEditor = iter . next ( ) ; if ( fieldEditor . getNumberOfControls ( ) < layout . numColumns ) { fieldEditor . fillIntoGrid ( parent , layout . numColumns ) ; } fieldEditor . setPage ( this ) ; fieldEditor . setPreferenceStore ( getPreferenceStore ( ) ) ; fieldEditor . load ( ) ; } } fields . addAll ( tabFields ) ; } @ Override protected Control createContents ( final Composite parent ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( new FillLayout ( ) ) ; final TabFolder tabFolder = new TabFolder ( composite , SWT . TOP ) ; createNodeTab ( tabFolder , "" , "" ) ; createNodeTab ( tabFolder , "" , "" ) ; createNodeTab ( tabFolder , "" , "" ) ; createNodeTab ( tabFolder , "" , "" ) ; return composite ; } @ Override protected void performDefaults ( ) { if ( fields != null ) { final Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { final FieldEditor pe = e . next ( ) ; pe . loadDefault ( ) ; } } super . performDefaults ( ) ; } } package net . ggtools . grand . ui . event ; import java . lang . ref . WeakReference ; import java . lang . reflect . Method ; import java . util . Iterator ; import java . util . LinkedList ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class EventManager implements Runnable { private final class DispatchEventAction implements Runnable { private final Dispatcher dispatcher ; private final Object event ; public DispatchEventAction ( final Object event , final Dispatcher dispatcher ) { this . event = event ; this . dispatcher = dispatcher ; } public void run ( ) { dispatchOneEvent ( event , dispatcher ) ; } } private final class SubscriptionAction implements Runnable { private Object subscriber ; public SubscriptionAction ( final Object subscriber ) { this . subscriber = subscriber ; } public void run ( ) { doSubscribtion ( subscriber ) ; } } private final class UnsubscriptionAction implements Runnable { private Object subscriber ; public UnsubscriptionAction ( final Object subscriber ) { this . subscriber = subscriber ; } public void run ( ) { doUnsubscription ( subscriber ) ; } } private static final Log log = LogFactory . getLog ( EventManager . class ) ; private boolean defaultDispatchAsynchronous = true ; private final DispatcherFactory dispatcherFactory ; private Thread dispatcherThread ; private final LinkedList < Runnable > eventQueue = new LinkedList < Runnable > ( ) ; private final LinkedList < WeakReference < Object > > listenerList = new LinkedList < WeakReference < Object > > ( ) ; private final String name ; public EventManager ( ) { this ( "" ) ; } public EventManager ( final String name ) { this . name = name ; dispatcherThread = new Thread ( this , "" + name ) ; dispatcherThread . start ( ) ; dispatcherFactory = DispatcherFactory . getInstance ( ) ; } public void clear ( ) { if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; } synchronized ( eventQueue ) { eventQueue . clear ( ) ; } synchronized ( listenerList ) { listenerList . clear ( ) ; } } public Dispatcher createDispatcher ( final Method method ) { return dispatcherFactory . createDispatcher ( this , method ) ; } final public String getName ( ) { return name ; } public boolean isDefaultDispatchAnsynchronous ( ) { return defaultDispatchAsynchronous ; } public void run ( ) { while ( true ) { Runnable nextEvent ; do { nextEvent = null ; synchronized ( eventQueue ) { if ( ! eventQueue . isEmpty ( ) ) { nextEvent = eventQueue . removeFirst ( ) ; } } if ( nextEvent != null ) { nextEvent . run ( ) ; } } while ( nextEvent != null ) ; try { synchronized ( eventQueue ) { eventQueue . wait ( ) ; } } catch ( final InterruptedException e ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" ) ; } } } } public void setDefaultDispatchAnsynchronous ( final boolean defaultDispatchAnsynchronous ) { defaultDispatchAsynchronous = defaultDispatchAnsynchronous ; } public void subscribe ( final Object listener ) { synchronized ( eventQueue ) { eventQueue . add ( new SubscriptionAction ( listener ) ) ; } } public void unSubscribe ( final Object listener ) { synchronized ( eventQueue ) { eventQueue . add ( new UnsubscriptionAction ( listener ) ) ; } } private final void asynchronousDispatchEvent ( final Object event , final Dispatcher dispatcher ) { synchronized ( eventQueue ) { eventQueue . add ( new DispatchEventAction ( event , dispatcher ) ) ; eventQueue . notify ( ) ; } } private void dispatchOneEvent ( final Object eventData , final Dispatcher dispatcher ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + dispatcher ) ; } synchronized ( listenerList ) { for ( final Iterator < WeakReference < Object > > iterator = listenerList . iterator ( ) ; iterator . hasNext ( ) ; ) { final WeakReference weakReference = iterator . next ( ) ; final Object subscriber = weakReference . get ( ) ; if ( subscriber != null ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + eventData + "" + subscriber ) ; } dispatcher . sendEventToSubscriber ( subscriber , eventData ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + weakReference ) ; } iterator . remove ( ) ; } } } } private void doSubscribtion ( final Object listener ) { if ( log . isDebugEnabled ( ) ) { log . debug ( name + "" + listener ) ; } synchronized ( listenerList ) { listenerList . add ( new WeakReference < Object > ( listener ) ) ; } } private void doUnsubscription ( final Object listener ) { if ( log . isDebugEnabled ( ) ) { log . debug ( name + "" + listener ) ; } synchronized ( listenerList ) { for ( final Iterator < WeakReference < Object > > iterator = listenerList . iterator ( ) ; iterator . hasNext ( ) ; ) { final WeakReference weakRef = iterator . next ( ) ; if ( weakRef . get ( ) == listener ) { iterator . remove ( ) ; break ; } } } } private final void synchronousDispatchEvent ( final Object event , final Dispatcher dispatcher ) { dispatchOneEvent ( event , dispatcher ) ; } final void dispatchEvent ( final Object eventData , final Dispatcher dispatcher ) { if ( defaultDispatchAsynchronous ) { asynchronousDispatchEvent ( eventData , dispatcher ) ; } else { synchronousDispatchEvent ( eventData , dispatcher ) ; } } } package net . ggtools . grand . ui . event ; import java . lang . reflect . Method ; abstract class DispatcherFactory { private static DispatcherFactory instance = null ; protected DispatcherFactory ( ) { } final static DispatcherFactory getInstance ( ) { if ( instance == null ) { instance = new SimpleDispatcherFactory ( ) ; } return instance ; } abstract Dispatcher createDispatcher ( final EventManager eventManager , final Method method ) ; } package net . ggtools . grand . ui . event ; import java . lang . reflect . Method ; class SimpleDispatcherFactory extends DispatcherFactory { @ Override Dispatcher createDispatcher ( final EventManager eventManager , final Method method ) { return new SimpleDispatcher ( eventManager , method ) ; } } package net . ggtools . grand . ui . event ; public interface Dispatcher { void dispatch ( final Object eventData ) ; void sendEventToSubscriber ( final Object subscriber , final Object eventData ) ; } package net . ggtools . grand . ui . event ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; class SimpleDispatcher extends DispatcherAdapter implements Dispatcher { private final static Log log = LogFactory . getLog ( SimpleDispatcher . class ) ; private final Method method ; SimpleDispatcher ( final EventManager manager , final Method method ) { super ( manager ) ; this . method = method ; } public void sendEventToSubscriber ( final Object subscriber , final Object eventData ) { try { method . invoke ( subscriber , new Object [ ] { eventData } ) ; } catch ( final IllegalAccessException e ) { log . fatal ( getEventManager ( ) . getName ( ) + "" , e ) ; throw new RuntimeException ( e ) ; } catch ( final InvocationTargetException e ) { log . error ( getEventManager ( ) . getName ( ) + "" , e ) ; throw new RuntimeException ( e . getCause ( ) ) ; } } } package net . ggtools . grand . ui . event ; abstract class DispatcherAdapter implements Dispatcher { private final EventManager eventManager ; protected DispatcherAdapter ( final EventManager manager ) { eventManager = manager ; } public final void dispatch ( final Object eventData ) { eventManager . dispatchEvent ( eventData , this ) ; } protected final EventManager getEventManager ( ) { return eventManager ; } } package net . ggtools . grand . ui . log ; import org . apache . commons . logging . Log ; final class UILogger implements Log { private final Log underlying ; private final String name ; private LogEventBufferImpl logBuffer ; UILogger ( final String name , final Log logger ) { this . name = name ; underlying = logger ; logBuffer = LogEventBufferImpl . getInstance ( ) ; } public void debug ( final Object message ) { underlying . debug ( message ) ; logBuffer . addLogEvent ( LogEvent . DEBUG , name , message ) ; } public void debug ( final Object message , final Throwable t ) { underlying . debug ( message , t ) ; logBuffer . addLogEvent ( LogEvent . DEBUG , name , message , t ) ; } public void error ( final Object message ) { underlying . error ( message ) ; logBuffer . addLogEvent ( LogEvent . ERROR , name , message ) ; } public void error ( final Object message , final Throwable t ) { underlying . error ( message , t ) ; logBuffer . addLogEvent ( LogEvent . ERROR , name , message , t ) ; } public void fatal ( final Object message ) { underlying . fatal ( message ) ; logBuffer . addLogEvent ( LogEvent . FATAL , name , message ) ; } public void fatal ( final Object message , final Throwable t ) { underlying . fatal ( message , t ) ; logBuffer . addLogEvent ( LogEvent . FATAL , name , message , t ) ; } public void info ( final Object message ) { underlying . info ( message ) ; logBuffer . addLogEvent ( LogEvent . INFO , name , message ) ; } public void info ( final Object message , final Throwable t ) { underlying . info ( message , t ) ; logBuffer . addLogEvent ( LogEvent . INFO , name , message , t ) ; } public boolean isDebugEnabled ( ) { return underlying . isDebugEnabled ( ) ; } public boolean isErrorEnabled ( ) { return underlying . isErrorEnabled ( ) ; } public boolean isFatalEnabled ( ) { return underlying . isFatalEnabled ( ) ; } public boolean isInfoEnabled ( ) { return underlying . isInfoEnabled ( ) ; } public boolean isTraceEnabled ( ) { return underlying . isTraceEnabled ( ) ; } public boolean isWarnEnabled ( ) { return underlying . isWarnEnabled ( ) ; } public void trace ( final Object message ) { underlying . trace ( message ) ; logBuffer . addLogEvent ( LogEvent . TRACE , name , message ) ; } public void trace ( final Object message , final Throwable t ) { underlying . trace ( message , t ) ; logBuffer . addLogEvent ( LogEvent . TRACE , name , message , t ) ; } public void warn ( final Object message ) { underlying . warn ( message ) ; logBuffer . addLogEvent ( LogEvent . WARNING , name , message ) ; } public void warn ( final Object message , final Throwable t ) { underlying . warn ( message , t ) ; logBuffer . addLogEvent ( LogEvent . WARNING , name , message , t ) ; } } package net . ggtools . grand . ui . log ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; abstract class TableTooltipListener implements Listener { private final class ToolTipRemoverListener implements Listener { private ToolTipRemoverListener ( ) { } public void handleEvent ( final Event event ) { final Control control = ( Control ) event . widget ; final Shell shell = control . getShell ( ) ; switch ( event . type ) { case SWT . MouseDown : final Event e = new Event ( ) ; e . item = ( TableItem ) control . getData ( "" ) ; table . setSelection ( new TableItem [ ] { ( TableItem ) e . item } ) ; table . notifyListeners ( SWT . Selection , e ) ; case SWT . MouseExit : shell . dispose ( ) ; break ; } } } private Shell tip = null ; private final Table table ; private Listener labelListener = null ; TableTooltipListener ( final Table table ) { this . table = table ; labelListener = new ToolTipRemoverListener ( ) ; } public void activateTooltips ( ) { table . setToolTipText ( "" ) ; table . addListener ( SWT . Dispose , this ) ; table . addListener ( SWT . KeyDown , this ) ; table . addListener ( SWT . MouseMove , this ) ; table . addListener ( SWT . MouseHover , this ) ; } public void handleEvent ( final Event event ) { switch ( event . type ) { case SWT . Dispose : case SWT . KeyDown : case SWT . MouseMove : { if ( tip == null ) { break ; } tip . dispose ( ) ; tip = null ; break ; } case SWT . MouseHover : { final TableItem item = table . getItem ( new Point ( event . x , event . y ) ) ; if ( item != null ) { if ( ( tip != null ) && ! tip . isDisposed ( ) ) { tip . dispose ( ) ; } tip = new Shell ( table . getShell ( ) , SWT . ON_TOP ) ; tip . setLayout ( new FillLayout ( ) ) ; createTooltipContents ( tip , item ) ; final Point size = tip . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; final Point pt = table . toDisplay ( event . x - size . x / , event . y - size . y ) ; tip . setBounds ( pt . x , pt . y , size . x , size . y ) ; tip . setVisible ( true ) ; } } } } protected Control createTooltipContents ( final Composite parent , final TableItem item ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; final Display display = table . getShell ( ) . getDisplay ( ) ; composite . setForeground ( display . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; composite . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; composite . setData ( "" , item ) ; final GridLayout gridLayout = new GridLayout ( ) ; composite . setLayout ( gridLayout ) ; composite . addListener ( SWT . MouseExit , labelListener ) ; composite . addListener ( SWT . MouseDown , labelListener ) ; return composite ; } } package net . ggtools . grand . ui . log ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . impl . LogFactoryImpl ; public class UILogFactory extends LogFactoryImpl { public UILogFactory ( ) { super ( ) ; } @ Override protected Log newInstance ( final String name ) { final Log log = super . newInstance ( name ) ; return new UILogger ( name , log ) ; } } package net . ggtools . grand . ui . log ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . util . Date ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . ScrolledComposite ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class LogEventDetailDialog extends Dialog { private static final int [ ] ICONS_FOR_LEVELS = { SWT . ICON_INFORMATION , SWT . ICON_INFORMATION , SWT . ICON_INFORMATION , SWT . ICON_INFORMATION , SWT . ICON_WARNING , SWT . ICON_ERROR , SWT . ICON_ERROR } ; private static final Log log = LogFactory . getLog ( LogEventDetailDialog . class ) ; private Control details ; private Button detailsButton ; private Display display ; private final LogEvent event ; public LogEventDetailDialog ( final Shell parentShell , final LogEvent event ) { super ( parentShell ) ; setShellStyle ( SWT . SHELL_TRIM ) ; this . event = event ; } private void addKeyValue ( final Composite composite , final String key , final String value ) { addKeyValue ( composite , key , value , ) ; } private void addKeyValue ( final Composite composite , final String key , final String value , final int valueColumnSpan ) { if ( value == null ) { log . warn ( "" ) ; return ; } final Label header = new Label ( composite , SWT . BOLD ) ; header . setText ( key ) ; header . setFont ( JFaceResources . getDefaultFont ( ) ) ; GridData layoutData = new GridData ( GridData . VERTICAL_ALIGN_BEGINNING ) ; header . setLayoutData ( layoutData ) ; final Label content = new Label ( composite , SWT . WRAP ) ; content . setText ( value ) ; content . setBackground ( display . getSystemColor ( SWT . COLOR_WIDGET_BACKGROUND ) ) ; content . setFont ( JFaceResources . getTextFont ( ) ) ; final GC gc = new GC ( content ) ; layoutData = new GridData ( GridData . GRAB_HORIZONTAL ) ; layoutData . widthHint = Math . min ( gc . stringExtent ( "" ) . x * , gc . stringExtent ( value ) . x ) ; layoutData . horizontalSpan = valueColumnSpan ; content . setLayoutData ( layoutData ) ; gc . dispose ( ) ; } private Control createDetailWidget ( final Throwable exception ) { final ScrolledComposite textComposite = new ScrolledComposite ( ( Composite ) getContents ( ) , SWT . H_SCROLL | SWT . V_SCROLL | SWT . BORDER ) ; textComposite . setExpandHorizontal ( true ) ; textComposite . setExpandVertical ( true ) ; final GridData layoutData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . GRAB_HORIZONTAL | GridData . VERTICAL_ALIGN_FILL | GridData . GRAB_VERTICAL ) ; layoutData . horizontalSpan = ; textComposite . setLayoutData ( layoutData ) ; final Text exceptionStack = new Text ( textComposite , SWT . READ_ONLY | SWT . MULTI ) ; exceptionStack . setFont ( JFaceResources . getTextFont ( ) ) ; textComposite . setContent ( exceptionStack ) ; final StringWriter stringWriter = new StringWriter ( ) ; final PrintWriter printWriter = new PrintWriter ( stringWriter ) ; exception . printStackTrace ( printWriter ) ; exceptionStack . setText ( stringWriter . getBuffer ( ) . toString ( ) ) ; printWriter . close ( ) ; layoutData . heightHint = Math . min ( , exceptionStack . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) . y ) ; textComposite . setMinSize ( exceptionStack . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ) ; return textComposite ; } private void toggleExceptionDetail ( ) { final Shell shell = getShell ( ) ; final Point windowSize = shell . getSize ( ) ; final Point minimumWindowSize = shell . getMinimumSize ( ) ; final Point oldSize = shell . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; if ( details != null ) { details . dispose ( ) ; details = null ; detailsButton . setText ( IDialogConstants . SHOW_DETAILS_LABEL ) ; } else { details = createDetailWidget ( event . getException ( ) ) ; detailsButton . setText ( IDialogConstants . HIDE_DETAILS_LABEL ) ; } final Point newSize = shell . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; shell . setMinimumSize ( new Point ( minimumWindowSize . x , minimumWindowSize . y + ( newSize . y - oldSize . y ) ) ) ; shell . setSize ( new Point ( windowSize . x , windowSize . y + ( newSize . y - oldSize . y ) ) ) ; } @ Override protected void buttonPressed ( final int buttonId ) { if ( IDialogConstants . DETAILS_ID == buttonId ) { toggleExceptionDetail ( ) ; } else { super . buttonPressed ( buttonId ) ; } } @ Override protected void configureShell ( final Shell newShell ) { super . configureShell ( newShell ) ; newShell . setText ( "" ) ; display = newShell . getDisplay ( ) ; } @ Override protected void createButtonsForButtonBar ( final Composite parent ) { createButton ( parent , IDialogConstants . OK_ID , IDialogConstants . OK_LABEL , true ) ; if ( event . getException ( ) != null ) { detailsButton = createButton ( parent , IDialogConstants . DETAILS_ID , IDialogConstants . SHOW_DETAILS_LABEL , false ) ; } } @ Override protected Control createContents ( final Composite parent ) { final Control contents = super . createContents ( parent ) ; getShell ( ) . setMinimumSize ( getShell ( ) . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ) ; return contents ; } @ Override protected Control createDialogArea ( final Composite parent ) { final Composite composite = ( Composite ) super . createDialogArea ( parent ) ; final GridData compositeLayoutData = new GridData ( GridData . FILL_HORIZONTAL ) ; composite . setLayoutData ( compositeLayoutData ) ; final GridLayout gridLayout = new GridLayout ( , false ) ; composite . setLayout ( gridLayout ) ; final Label icon = new Label ( composite , SWT . NONE ) ; final GridData layoutData = new GridData ( GridData . HORIZONTAL_ALIGN_CENTER ) ; layoutData . verticalSpan = ; icon . setLayoutData ( layoutData ) ; icon . setImage ( display . getSystemImage ( ICONS_FOR_LEVELS [ event . getLevel ( ) . value ] ) ) ; addKeyValue ( composite , "" , event . getLevel ( ) . name ) ; addKeyValue ( composite , "" , event . getClass ( ) . getName ( ) ) ; addKeyValue ( composite , "" , new Date ( event . getTime ( ) ) . toString ( ) ) ; addKeyValue ( composite , "" , event . getMessage ( ) . toString ( ) , ) ; final Throwable exception = event . getException ( ) ; if ( exception != null ) { addKeyValue ( composite , "" , exception . getClass ( ) . getName ( ) , ) ; addKeyValue ( composite , "" , exception . getMessage ( ) , ) ; } compositeLayoutData . minimumHeight = composite . computeSize ( SWT . DEFAULT , SWT . DEFAULT , false ) . y ; return composite ; } } package net . ggtools . grand . ui . log ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . ObjectOutputStream ; import java . util . Date ; import java . util . Iterator ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . viewers . ArrayContentProvider ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . swt . widgets . TableItem ; public class LogViewer extends Composite { private final class LogEventFilter extends ViewerFilter { private final Log log = LogFactory . getLog ( LogEventFilter . class ) ; @ Override public boolean select ( final Viewer v , final Object parentElement , final Object element ) { if ( element instanceof LogEvent ) { final LogEvent event = ( LogEvent ) element ; if ( event . getLevel ( ) . value >= minLogLevel ) { return true ; } } return false ; } } private final class LogEventRefreshListener implements LogEventListener { private final Log log = LogFactory . getLog ( LogEventRefreshListener . class ) ; public void logEventReceived ( final LogEvent event ) { if ( refreshEnabled && ( event . getLevel ( ) . value >= minLogLevel ) ) { synchronized ( refreshThread ) { nextEvent = event ; refreshThread . notify ( ) ; } } } } private static final class LogEventTooltipListener extends TableTooltipListener { private final int CI_CLASS ; private final int CI_MESSAGE ; private final Table table ; private LogEventTooltipListener ( final Table table , final int CI_CLASS , final int CI_MESSAGE ) { super ( table ) ; this . table = table ; this . CI_CLASS = CI_CLASS ; this . CI_MESSAGE = CI_MESSAGE ; } @ Override protected Control createTooltipContents ( final Composite tooltipParent , final TableItem item ) { final Composite composite = ( Composite ) super . createTooltipContents ( tooltipParent , item ) ; final GridLayout parentGridLayout = ( ( GridLayout ) composite . getLayout ( ) ) ; parentGridLayout . numColumns = ; final Display display = table . getShell ( ) . getDisplay ( ) ; final Label icon = new Label ( composite , SWT . NONE ) ; icon . setForeground ( display . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; icon . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; icon . setImage ( item . getImage ( ) ) ; final Label date = new Label ( composite , SWT . NO_BACKGROUND ) ; date . setForeground ( display . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; date . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; date . setText ( item . getText ( CI_CLASS ) ) ; final Label message = new Label ( composite , SWT . READ_ONLY | SWT . WRAP ) ; message . setForeground ( display . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; message . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; message . setText ( item . getText ( CI_MESSAGE ) ) ; final GridData msgGridData = new GridData ( GridData . GRAB_HORIZONTAL ) ; msgGridData . horizontalSpan = ; msgGridData . widthHint = Math . min ( , message . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) . x + parentGridLayout . marginWidth ) ; message . setLayoutData ( msgGridData ) ; return composite ; } } private final class LogSaver extends SelectionAdapter { private final Log log = LogFactory . getLog ( LogSaver . class ) ; @ Override public void widgetSelected ( final SelectionEvent e ) { if ( e . widget instanceof Button ) { final FileDialog dialog = new FileDialog ( viewer . getTable ( ) . getShell ( ) , SWT . SAVE ) ; dialog . setFilterExtensions ( new String [ ] { "" , "" , "" } ) ; final String logFileName = dialog . open ( ) ; if ( logFileName != null ) { ObjectOutputStream oos = null ; try { oos = new ObjectOutputStream ( new FileOutputStream ( logFileName ) ) ; oos . writeObject ( LogEventBufferImpl . getInstance ( ) ) ; } catch ( final IOException exception ) { throw new RuntimeException ( "" + logFileName , exception ) ; } finally { if ( oos != null ) { try { oos . close ( ) ; } catch ( final IOException exception ) { throw new RuntimeException ( "" + logFileName , exception ) ; } } } } } } } private final class ViewerRefreshThread extends Thread { private final Display display = getDisplay ( ) ; private boolean keepRunning = true ; @ Override public void run ( ) { while ( keepRunning ) { final LogEvent myEvent ; synchronized ( this ) { myEvent = nextEvent ; nextEvent = null ; } if ( myEvent != null ) { display . syncExec ( new Runnable ( ) { public void run ( ) { refreshViewer ( ) ; } } ) ; } try { sleep ( ) ; synchronized ( this ) { wait ( ) ; } } catch ( final InterruptedException e ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" , e ) ; } } } } private void stopThread ( ) { keepRunning = false ; interrupt ( ) ; } } private static final int DEFAULT_NUM_LINES = ; private static final int HEADER_EXTRA_WIDTH = ; private static final Log log = LogFactory . getLog ( LogViewer . class ) ; static final int CI_CLASS = ; static final int CI_DATE = ; static final int CI_LEVEL = ; static final int CI_MESSAGE = ; static final String [ ] COLUMN_NAMES = new String [ ] { "" , "" , "" , "" } ; private LogEventFilter eventLevelFilter ; private LogEventBuffer logBuffer ; private int minLogLevel = LogEvent . INFO . value ; private LogEvent nextEvent = null ; private boolean refreshEnabled = true ; private LogEventRefreshListener refreshListener ; private final ViewerRefreshThread refreshThread ; private Table table ; private TableViewer viewer ; public LogViewer ( final Composite parent , final int style ) { super ( parent , style ) ; refreshThread = new ViewerRefreshThread ( ) ; createContents ( this ) ; } @ Override public void dispose ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } stopRefreshThread ( ) ; super . dispose ( ) ; } public final LogEventBuffer getLogBuffer ( ) { return logBuffer ; } public final void setLogBuffer ( final LogEventBuffer newLogBuffer ) { if ( logBuffer != null ) { logBuffer . removeListener ( refreshListener ) ; } logBuffer = newLogBuffer ; logBuffer . addListener ( refreshListener ) ; viewer . setInput ( logBuffer . getEventList ( ) ) ; } private void createCommands ( final Composite parent ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; final GridLayout layout = new GridLayout ( ) ; composite . setLayout ( layout ) ; composite . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; final Label label = new Label ( composite , SWT . NONE ) ; layout . numColumns ++ ; label . setText ( "" ) ; label . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . CENTER , false , false ) ) ; final Combo combo = new Combo ( composite , SWT . DROP_DOWN | SWT . READ_ONLY ) ; layout . numColumns ++ ; combo . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . CENTER , false , false ) ) ; fillUpLevelCombo ( combo ) ; combo . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { if ( e . widget instanceof Combo ) { final Combo selectedCombo = ( Combo ) e . widget ; minLogLevel = comboIndexToLogLevel ( selectedCombo . getSelectionIndex ( ) ) ; viewer . refresh ( false ) ; } } } ) ; final Button refreshToggle = new Button ( composite , SWT . CHECK ) ; layout . numColumns ++ ; refreshToggle . setLayoutData ( new GridData ( SWT . END , SWT . CENTER , true , false ) ) ; refreshToggle . setText ( "" ) ; refreshToggle . setSelection ( refreshEnabled ) ; final Button refreshButton = new Button ( composite , SWT . NONE ) ; layout . numColumns ++ ; refreshButton . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . CENTER , true , false ) ) ; refreshButton . setText ( "" ) ; refreshButton . setEnabled ( ! refreshEnabled ) ; refreshButton . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { refreshViewer ( ) ; } } ) ; refreshToggle . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { if ( e . widget instanceof Button ) { final Button button = ( Button ) e . widget ; refreshEnabled = button . getSelection ( ) ; refreshButton . setEnabled ( ! refreshEnabled ) ; if ( refreshEnabled ) { refreshViewer ( ) ; } } } } ) ; final Button saveButton = new Button ( composite , SWT . NONE ) ; layout . numColumns ++ ; saveButton . setLayoutData ( new GridData ( SWT . END , SWT . CENTER , true , false ) ) ; saveButton . setText ( "" ) ; saveButton . addSelectionListener ( new LogSaver ( ) ) ; final Button clearButton = new Button ( composite , SWT . NONE ) ; layout . numColumns ++ ; clearButton . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . CENTER , false , false ) ) ; clearButton . setText ( "" ) ; clearButton . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { if ( e . widget instanceof Button ) { logBuffer . clearLogEvents ( ) ; viewer . refresh ( ) ; } } } ) ; } private void createContents ( final Composite composite ) { final GridLayout layout = new GridLayout ( ) ; composite . setLayout ( layout ) ; composite . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; createCommands ( composite ) ; createViewer ( composite ) ; refreshListener = new LogEventRefreshListener ( ) ; refreshThread . start ( ) ; } private void createViewer ( final Composite parent ) { viewer = new TableViewer ( parent , SWT . READ_ONLY | SWT . H_SCROLL | SWT . V_SCROLL | SWT . HIDE_SELECTION ) ; final LogLabelProvider logLabelProvider = new LogLabelProvider ( ) ; viewer . setContentProvider ( new ArrayContentProvider ( ) ) ; viewer . setLabelProvider ( logLabelProvider ) ; eventLevelFilter = new LogEventFilter ( ) ; viewer . addFilter ( eventLevelFilter ) ; table = viewer . getTable ( ) ; table . setHeaderVisible ( true ) ; table . setLinesVisible ( true ) ; table . pack ( ) ; final GridData gridData = new GridData ( GridData . FILL_BOTH ) ; gridData . heightHint = table . getHeaderHeight ( ) * DEFAULT_NUM_LINES ; table . setLayoutData ( gridData ) ; final TableTooltipListener tableListener = new LogEventTooltipListener ( table , CI_CLASS , CI_MESSAGE ) ; tableListener . activateTooltips ( ) ; final GC gc = new GC ( table ) ; gc . setFont ( table . getFont ( ) ) ; for ( int columnIndex = ; columnIndex < COLUMN_NAMES . length ; columnIndex ++ ) { final String header = COLUMN_NAMES [ columnIndex ] ; final TableColumn column = new TableColumn ( table , SWT . LEFT ) ; int columnWidth ; switch ( columnIndex ) { case CI_DATE : columnWidth = gc . stringExtent ( new Date ( ) . toString ( ) ) . x ; break ; case CI_CLASS : columnWidth = gc . stringExtent ( "" ) . x * ; break ; case CI_MESSAGE : columnWidth = gc . stringExtent ( "" ) . x * ; break ; default : columnWidth = gc . stringExtent ( header ) . x ; break ; } columnWidth += HEADER_EXTRA_WIDTH ; column . setText ( header ) ; column . setWidth ( columnWidth ) ; column . setMoveable ( true ) ; } gc . dispose ( ) ; table . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( final DisposeEvent e ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" ) ; } stopRefreshThread ( ) ; } } ) ; viewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( final DoubleClickEvent event ) { final ISelection s = event . getSelection ( ) ; if ( s instanceof IStructuredSelection ) { final IStructuredSelection selection = ( IStructuredSelection ) s ; for ( final Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { final LogEvent logEvent = ( LogEvent ) iter . next ( ) ; final LogEventDetailDialog window = new LogEventDetailDialog ( getShell ( ) , logEvent ) ; window . setBlockOnOpen ( false ) ; window . open ( ) ; } } } } ) ; } private void refreshViewer ( ) { if ( ! table . isDisposed ( ) ) { viewer . refresh ( false ) ; table . showItem ( table . getItem ( table . getItemCount ( ) - ) ) ; } else { log . warn ( "" ) ; } } private void stopRefreshThread ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } refreshThread . stopThread ( ) ; try { refreshThread . join ( ) ; } catch ( final InterruptedException e ) { log . warn ( "" , e ) ; } } protected int comboIndexToLogLevel ( final int comboIndex ) { return comboIndex + LogEvent . TRACE . value ; } protected void fillUpLevelCombo ( final Combo combo ) { combo . add ( LogEvent . TRACE . name ) ; combo . add ( LogEvent . DEBUG . name ) ; combo . add ( LogEvent . INFO . name ) ; combo . add ( LogEvent . WARNING . name ) ; combo . add ( LogEvent . ERROR . name ) ; combo . add ( LogEvent . FATAL . name ) ; combo . select ( LogEvent . INFO . value - LogEvent . TRACE . value ) ; } } package net . ggtools . grand . ui . log ; import java . util . Date ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ITableColorProvider ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Display ; class LogLabelProvider implements ITableLabelProvider , ITableColorProvider { private static final Log log = LogFactory . getLog ( LogLabelProvider . class ) ; private final Map logLevelIcons = new HashMap ( ) ; public LogLabelProvider ( ) { super ( ) ; } public void addListener ( final ILabelProviderListener listener ) { } public void dispose ( ) { for ( final Iterator iter = logLevelIcons . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final Map . Entry entry = ( Map . Entry ) iter . next ( ) ; final Object entryValue = entry . getValue ( ) ; if ( ( entryValue != null ) && ( entryValue instanceof Image ) ) { final Image image = ( Image ) entryValue ; image . dispose ( ) ; } } } public Color getBackground ( final Object element , final int columnIndex ) { return null ; } public Image getColumnImage ( final Object element , final int columnIndex ) { Image rc = null ; if ( element instanceof LogEvent ) { final LogEvent event = ( LogEvent ) element ; if ( columnIndex == ) { final LogEvent . Level eventLevel = event . getLevel ( ) ; if ( logLevelIcons . containsKey ( eventLevel ) ) { rc = ( Image ) logLevelIcons . get ( eventLevel ) ; } else { final String resourceName = "" + eventLevel . name . toLowerCase ( ) + "" ; rc = new Image ( Display . getCurrent ( ) , this . getClass ( ) . getResourceAsStream ( resourceName ) ) ; } } } return rc ; } public String getColumnText ( final Object element , final int columnIndex ) { String rc = null ; if ( element instanceof LogEvent ) { final LogEvent event = ( LogEvent ) element ; switch ( columnIndex ) { case LogViewer . CI_LEVEL : break ; case LogViewer . CI_DATE : rc = new Date ( event . getTime ( ) ) . toString ( ) ; break ; case LogViewer . CI_CLASS : rc = event . getOriginator ( ) ; rc = rc . substring ( rc . lastIndexOf ( '' ) + ) ; break ; case LogViewer . CI_MESSAGE : rc = event . getMessage ( ) . toString ( ) ; break ; default : if ( log . isWarnEnabled ( ) ) { log . warn ( "" + columnIndex + "" ) ; } break ; } } return rc ; } public Color getForeground ( final Object element , final int columnIndex ) { return null ; } public boolean isLabelProperty ( final Object element , final String property ) { return false ; } public void removeListener ( final ILabelProviderListener listener ) { } } package net . ggtools . grand . ui . log ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . ObjectInputStream ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . window . ApplicationWindow ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Shell ; public class Analyzer extends ApplicationWindow { private LogViewer logViewer ; public Analyzer ( ) { super ( null ) ; addMenuBar ( ) ; } @ Override protected void configureShell ( final Shell shell ) { super . configureShell ( shell ) ; shell . setText ( "" ) ; } @ Override protected MenuManager createMenuManager ( ) { final MenuManager manager = new MenuManager ( ) ; final MenuManager fileMenu = new MenuManager ( "" ) ; manager . add ( fileMenu ) ; fileMenu . add ( new Action ( "" ) { @ Override public int getAccelerator ( ) { return SWT . CONTROL | '' ; } @ Override public void run ( ) { if ( logViewer != null ) { final FileDialog dialog = new FileDialog ( getShell ( ) , SWT . NONE ) ; dialog . setFilterExtensions ( new String [ ] { "" , "" , "" } ) ; final String logFileName = dialog . open ( ) ; if ( logFileName != null ) { ObjectInputStream ois = null ; try { ois = new ObjectInputStream ( new FileInputStream ( logFileName ) ) ; logViewer . setLogBuffer ( ( LogEventBuffer ) ois . readObject ( ) ) ; } catch ( final FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } catch ( final ClassNotFoundException e ) { e . printStackTrace ( ) ; } finally { if ( ois != null ) { try { ois . close ( ) ; } catch ( final IOException exception ) { throw new RuntimeException ( "" + logFileName , exception ) ; } } } } } } } ) ; fileMenu . add ( new Action ( "" ) { @ Override public int getAccelerator ( ) { return SWT . CONTROL | '' ; } @ Override public void run ( ) { System . exit ( ) ; } } ) ; manager . setVisible ( true ) ; return manager ; } @ Override protected Control createContents ( final Composite parent ) { logViewer = new LogViewer ( parent , SWT . NONE ) ; return logViewer ; } public static void main ( final String [ ] args ) { final Analyzer analyzer = new Analyzer ( ) ; analyzer . setBlockOnOpen ( true ) ; analyzer . open ( ) ; System . exit ( ) ; } } package net . ggtools . grand . ui . log ; import java . util . Collections ; import java . util . LinkedList ; import java . util . List ; import net . ggtools . grand . ui . log . LogEvent . Level ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class LogEventBufferImpl implements LogEventBuffer { private static LogEventBufferImpl instance ; private static final Log log = LogFactory . getLog ( LogEventBufferImpl . class ) ; private static final long serialVersionUID = ; public static LogEventBufferImpl getInstance ( ) { if ( instance == null ) { instance = new LogEventBufferImpl ( ) ; } return instance ; } private final LinkedList < LogEvent > eventList = new LinkedList < LogEvent > ( ) ; private transient LogEventListener listener ; private LogEventBufferImpl ( ) { super ( ) ; } public void addListener ( final LogEventListener newListener ) { listener = newListener ; } synchronized public void clearLogEvents ( ) { eventList . clear ( ) ; } public List < LogEvent > getEventList ( ) { return Collections . unmodifiableList ( eventList ) ; } public void removeListener ( final LogEventListener toRemove ) { if ( listener == toRemove ) { listener = null ; } } void addLogEvent ( final Level level , final String originator , final Object message ) { addLogEvent ( level , originator , message , null ) ; } void addLogEvent ( final Level level , final String originator , final Object message , final Throwable exception ) { final LogEvent logEvent = new LogEvent ( level , originator , message , exception ) ; eventList . addLast ( logEvent ) ; if ( listener != null ) { listener . logEventReceived ( logEvent ) ; } } } package net . ggtools . grand . ui . log ; public interface LogEventListener { void logEventReceived ( LogEvent event ) ; } package net . ggtools . grand . ui . log ; import net . ggtools . grand . log . LoggerFactory ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class CommonsLoggingLoggerFactory implements LoggerFactory { public CommonsLoggingLoggerFactory ( ) { } public Log getLog ( final Class clazz ) { return LogFactory . getLog ( clazz ) ; } public Log getLog ( final String name ) { return LogFactory . getLog ( name ) ; } } package net . ggtools . grand . ui . log ; import java . io . Serializable ; public class LogEvent implements Serializable { public static final class Level implements Serializable { private static final long serialVersionUID = ; public final String name ; public final int value ; private Level ( final int value , final String name ) { this . value = value ; this . name = name ; } } public static final Level DEBUG = new Level ( , "" ) ; public static final Level ERROR = new Level ( , "" ) ; public static final Level FATAL = new Level ( , "" ) ; public static final Level INFO = new Level ( , "" ) ; public static final Level TRACE = new Level ( , "" ) ; public static final Level WARNING = new Level ( , "" ) ; private static final long serialVersionUID = ; private Throwable exception ; private Level level ; private Object message ; private String originator ; private long time ; public LogEvent ( final Level level , final String originator , final Object message , final Throwable exception ) { this . level = level ; this . originator = originator ; this . message = message ; this . exception = exception ; time = System . currentTimeMillis ( ) ; } public final Throwable getException ( ) { return exception ; } public final Level getLevel ( ) { return level ; } public final Object getMessage ( ) { return message ; } public final String getOriginator ( ) { return originator ; } public final long getTime ( ) { return time ; } final void setException ( final Throwable exception ) { this . exception = exception ; } final void setLevel ( final Level level ) { this . level = level ; } final void setMessage ( final String message ) { this . message = message ; } final void setOriginator ( final String originator ) { this . originator = originator ; } final void setTime ( final long time ) { this . time = time ; } } package net . ggtools . grand . ui . log ; import java . io . Serializable ; import java . util . List ; public interface LogEventBuffer extends Serializable { void addListener ( final LogEventListener newListener ) ; void clearLogEvents ( ) ; List < LogEvent > getEventList ( ) ; void removeListener ( final LogEventListener toRemove ) ; } package net . ggtools . grand . ui . widgets ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . draw2d . Cursors ; import org . eclipse . draw2d . FigureCanvas ; import org . eclipse . draw2d . Viewport ; import org . eclipse . draw2d . geometry . Point ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . events . MouseMoveListener ; public final class CanvasScroller implements MouseMoveListener { private static final Log log = LogFactory . getLog ( CanvasScroller . class ) ; final private FigureCanvas canvas ; private boolean gotStartPoint ; private boolean inDragMode ; private int startDragX , startDragY ; private final Viewport viewport ; public CanvasScroller ( final FigureCanvas c ) { canvas = c ; viewport = canvas . getViewport ( ) ; inDragMode = false ; gotStartPoint = false ; } public void enterDragMode ( ) { if ( ! inDragMode ) { canvas . addMouseMoveListener ( this ) ; canvas . setCursor ( Cursors . SIZEALL ) ; inDragMode = true ; gotStartPoint = false ; } } public void leaveDragMode ( ) { if ( inDragMode ) { canvas . removeMouseMoveListener ( this ) ; canvas . setCursor ( Cursors . ARROW ) ; inDragMode = false ; } } public void mouseMove ( final MouseEvent e ) { if ( gotStartPoint ) { canvas . scrollTo ( startDragX - e . x , startDragY - e . y ) ; } else { final Point vpLocation = viewport . getViewLocation ( ) ; startDragX = vpLocation . x + e . x ; startDragY = vpLocation . y + e . y ; gotStartPoint = true ; } } } package net . ggtools . grand . ui . widgets ; import java . io . IOException ; import net . ggtools . grand . Configuration ; import net . ggtools . grand . ui . Application ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . RowLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; public class AboutDialog extends Dialog { private static final Log log = LogFactory . getLog ( AboutDialog . class ) ; private Configuration coreConfiguration ; public AboutDialog ( final Shell parentShell ) { super ( parentShell ) ; try { coreConfiguration = Configuration . getConfiguration ( ) ; } catch ( final IOException e ) { log . error ( "" , e ) ; coreConfiguration = null ; } } @ Override protected void configureShell ( final Shell newShell ) { super . configureShell ( newShell ) ; newShell . setText ( "" ) ; } @ Override protected void createButtonsForButtonBar ( final Composite parent ) { createButton ( parent , IDialogConstants . OK_ID , IDialogConstants . OK_LABEL , true ) ; } @ Override protected Control createDialogArea ( final Composite parent ) { final Composite composite = ( Composite ) super . createDialogArea ( parent ) ; final RowLayout rowLayout = new RowLayout ( SWT . VERTICAL ) ; rowLayout . justify = true ; rowLayout . spacing = ; composite . setLayout ( rowLayout ) ; final Label image = new Label ( composite , SWT . NONE ) ; image . setImage ( Application . getInstance ( ) . getImage ( Application . ABOUT_DIALOG_IMAGE ) ) ; final Label message = new Label ( composite , SWT . NONE ) ; final StringBuffer messageBuffer = new StringBuffer ( "" ) ; messageBuffer . append ( Application . getInstance ( ) . getVersionString ( ) ) ; if ( coreConfiguration != null ) { messageBuffer . append ( "" ) . append ( coreConfiguration . getVersionString ( ) ) ; } message . setText ( messageBuffer . toString ( ) ) ; return composite ; } } package net . ggtools . grand . ui . widgets ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . swt . widgets . * ; import org . eclipse . swt . widgets . Shell ; public class ExceptionDialog extends ErrorDialog { private ExceptionDialog ( final Shell parentShell , final String dialogTitle , final String message , final IStatus status , final int displayMask ) { super ( parentShell , dialogTitle , message , status , displayMask ) ; } public static void openException ( final Shell parent , final String message , final Throwable e ) { final MultiStatus topStatus = new MultiStatus ( "" , , message , e ) ; for ( Throwable nested = e ; nested != null ; nested = nested . getCause ( ) ) { final IStatus status = new Status ( IStatus . ERROR , "" , , nested . getMessage ( ) , nested ) ; topStatus . add ( status ) ; } Display display ; if ( parent == null ) { display = Display . getCurrent ( ) ; } else { display = parent . getDisplay ( ) ; } display . syncExec ( new Runnable ( ) { public void run ( ) { ErrorDialog . openError ( parent , message , e . getMessage ( ) , topStatus ) ; } } ) ; } } package net . ggtools . grand . ui . widgets ; import java . io . File ; import org . eclipse . jface . wizard . Wizard ; public class OpenFileWizard extends Wizard { interface SelectedFileProvider { void addListener ( SelectedFileListener listener ) ; void removeListener ( SelectedFileListener listener ) ; } interface SelectedFileListener { void fileSelected ( File selectedFile ) ; } private final GraphWindow window ; private PropertySettingPage propertySettingPage ; private FileSelectionPage fileSelectionPage ; public OpenFileWizard ( final GraphWindow window ) { super ( ) ; this . window = window ; } @ Override public void addPages ( ) { fileSelectionPage = new FileSelectionPage ( ) ; addPage ( fileSelectionPage ) ; propertySettingPage = new PropertySettingPage ( fileSelectionPage ) ; addPage ( propertySettingPage ) ; } @ Override public boolean performFinish ( ) { boolean rc = false ; final File selectedFile = fileSelectionPage . getSelectedFile ( ) ; if ( selectedFile != null ) { window . openGraphInNewDisplayer ( selectedFile , propertySettingPage . getProperties ( ) ) ; rc = true ; } return rc ; } @ Override public boolean canFinish ( ) { return fileSelectionPage . getSelectedFile ( ) != null ; } } package net . ggtools . grand . ui . widgets ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; public class Splash { private final Display display ; private final Image image ; private final Shell shell ; public Splash ( final Display display , final String versionString ) { this . display = display ; shell = new Shell ( display , SWT . NO_TRIM | SWT . NO_BACKGROUND | SWT . ON_TOP ) ; shell . setLayout ( new FillLayout ( ) ) ; image = new Image ( display , getClass ( ) . getResourceAsStream ( "" ) ) ; final Label label = new Label ( shell , SWT . NONE ) ; label . setImage ( image ) ; final Rectangle displayBounds = display . getPrimaryMonitor ( ) . getBounds ( ) ; final Rectangle imageBounds = image . getBounds ( ) ; final GC gc = new GC ( image ) ; gc . setForeground ( display . getSystemColor ( SWT . COLOR_BLACK ) ) ; final Point size = gc . stringExtent ( versionString ) ; gc . drawText ( versionString , , imageBounds . height - size . y - , true ) ; gc . dispose ( ) ; shell . setBounds ( displayBounds . x + ( ( displayBounds . width - imageBounds . width ) / ) , displayBounds . y + ( ( displayBounds . height - imageBounds . height ) / ) , imageBounds . width , imageBounds . height ) ; } public void close ( ) { shell . close ( ) ; } public void dispose ( ) { shell . dispose ( ) ; image . dispose ( ) ; } public void open ( ) { shell . open ( ) ; } } package net . ggtools . grand . ui . widgets ; import java . io . File ; import java . lang . reflect . InvocationTargetException ; import java . util . Properties ; import net . ggtools . grand . ui . event . Dispatcher ; import net . ggtools . grand . ui . event . EventManager ; import net . ggtools . grand . ui . graph . GraphControler ; import net . ggtools . grand . ui . graph . GraphControlerListener ; import net . ggtools . grand . ui . graph . GraphControlerProvider ; import net . ggtools . grand . ui . graph . GraphDisplayer ; import net . ggtools . grand . ui . menu . FileMenuManager ; import net . ggtools . grand . ui . menu . GraphMenu ; import net . ggtools . grand . ui . menu . HelpMenu ; import net . ggtools . grand . ui . menu . ViewMenu ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . window . ApplicationWindow ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CTabFolder ; import org . eclipse . swt . custom . CTabFolder2Adapter ; import org . eclipse . swt . custom . CTabFolderEvent ; import org . eclipse . swt . custom . CTabItem ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Widget ; public class GraphWindow extends ApplicationWindow implements GraphControlerProvider { private static final Log log = LogFactory . getLog ( GraphWindow . class ) ; private final Dispatcher controlerAvailableDispatcher ; private final EventManager controlerEventManager ; private final Dispatcher controlerRemovedDispatcher ; private Display display ; private MenuManager manager ; private boolean outlinePanelVisible = false ; private boolean sourcePanelVisible = true ; private CTabFolder tabFolder ; public GraphWindow ( ) { this ( null ) ; } public GraphWindow ( final Shell parent ) { super ( parent ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } controlerEventManager = new EventManager ( "" ) ; try { controlerAvailableDispatcher = controlerEventManager . createDispatcher ( GraphControlerListener . class . getDeclaredMethod ( "" , new Class [ ] { GraphControler . class } ) ) ; controlerRemovedDispatcher = controlerEventManager . createDispatcher ( GraphControlerListener . class . getDeclaredMethod ( "" , new Class [ ] { GraphControler . class } ) ) ; } catch ( final SecurityException e ) { log . fatal ( "" , e ) ; throw new RuntimeException ( "" , e ) ; } catch ( final NoSuchMethodException e ) { log . fatal ( "" , e ) ; throw new RuntimeException ( "" , e ) ; } addStatusLine ( ) ; addMenuBar ( ) ; } public void addControlerListener ( final GraphControlerListener listener ) { controlerEventManager . subscribe ( listener ) ; } public GraphControler getControler ( ) { if ( tabFolder != null ) { final GraphTabItem selectedTab = ( GraphTabItem ) tabFolder . getSelection ( ) ; if ( selectedTab == null ) { return null ; } else { return selectedTab . getControler ( ) ; } } return null ; } public GraphDisplayer newDisplayer ( final GraphControler controler ) { final GraphTabItem graphTabItem = new GraphTabItem ( tabFolder , SWT . CLOSE , controler ) ; graphTabItem . setSourcePanelVisible ( sourcePanelVisible ) ; graphTabItem . setOutlinePanelVisible ( outlinePanelVisible ) ; tabFolder . setSelection ( graphTabItem ) ; controlerAvailableDispatcher . dispatch ( controler ) ; controler . setProgressMonitor ( new SafeProgressMonitor ( getStatusLineManager ( ) . getProgressMonitor ( ) , display ) ) ; return graphTabItem ; } public void openGraphInNewDisplayer ( final File buildFile , final Properties properties ) { openGraphInNewDisplayer ( buildFile , null , properties ) ; } public void openGraphInNewDisplayer ( final File buildFile , final String targetName , final Properties properties ) { final GraphControler controler = new GraphControler ( this ) ; try { new ProgressMonitorDialog ( getShell ( ) ) . run ( true , false , new IRunnableWithProgress ( ) { public void run ( final IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { controler . setProgressMonitor ( monitor ) ; controler . openFile ( buildFile , properties ) ; if ( targetName != null ) { controler . focusOn ( targetName ) ; } } } ) ; } catch ( final InvocationTargetException e ) { log . error ( "" , e ) ; } catch ( final InterruptedException e ) { log . info ( "" , e ) ; } } public void removeControlerListener ( final GraphControlerListener listener ) { controlerEventManager . unSubscribe ( listener ) ; } public final void setOutlinePanelVisible ( final boolean outlinePanelVisible ) { if ( outlinePanelVisible != this . outlinePanelVisible ) { this . outlinePanelVisible = outlinePanelVisible ; final CTabItem [ ] children = tabFolder . getItems ( ) ; for ( final CTabItem current : children ) { if ( current instanceof GraphTabItem ) { final GraphTabItem tab = ( GraphTabItem ) current ; tab . setOutlinePanelVisible ( outlinePanelVisible ) ; } } } } public final void setSourcePanelVisible ( final boolean sourcePanelVisible ) { if ( sourcePanelVisible != this . sourcePanelVisible ) { this . sourcePanelVisible = sourcePanelVisible ; final CTabItem [ ] children = tabFolder . getItems ( ) ; for ( final CTabItem current : children ) { if ( current instanceof GraphTabItem ) { final GraphTabItem tab = ( GraphTabItem ) current ; tab . setSourcePanelVisible ( sourcePanelVisible ) ; } } } } @ Override protected void configureShell ( final Shell shell ) { super . configureShell ( shell ) ; shell . setText ( "" ) ; } @ Override protected Control createContents ( final Composite parent ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } tabFolder = new CTabFolder ( parent , SWT . BORDER | SWT . TOP ) ; tabFolder . addCTabFolder2Listener ( new CTabFolder2Adapter ( ) { @ Override public void close ( final CTabFolderEvent event ) { log . debug ( "" + event ) ; final Widget item = event . item ; if ( item instanceof GraphTabItem ) { controlerRemovedDispatcher . dispatch ( ( ( GraphTabItem ) item ) . getControler ( ) ) ; } } } ) ; tabFolder . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { log . debug ( "" + e ) ; final Widget widget = e . widget ; if ( widget instanceof CTabFolder ) { final CTabFolder folder = ( CTabFolder ) widget ; final CTabItem selection = folder . getSelection ( ) ; if ( selection instanceof GraphTabItem ) { controlerAvailableDispatcher . dispatch ( ( ( GraphTabItem ) selection ) . getControler ( ) ) ; } } } } ) ; display = parent . getDisplay ( ) ; return tabFolder ; } @ Override protected MenuManager createMenuManager ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } manager = new MenuManager ( ) ; manager . add ( new FileMenuManager ( this ) ) ; manager . add ( new ViewMenu ( this ) ) ; manager . add ( new GraphMenu ( this ) ) ; manager . add ( new HelpMenu ( this ) ) ; manager . setVisible ( true ) ; return manager ; } public final boolean isOutlinePanelVisible ( ) { return outlinePanelVisible ; } public final boolean isSourcePanelVisible ( ) { return sourcePanelVisible ; } } package net . ggtools . grand . ui . widgets . property ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; final class PropertyListLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage ( final Object element , final int columnIndex ) { return null ; } public String getColumnText ( final Object element , final int columnIndex ) { String rc = null ; if ( element instanceof PropertyPair ) { final PropertyPair pair = ( PropertyPair ) element ; switch ( columnIndex ) { case PropertyEditor . STATUS_COLUMN_NUM : rc = null ; break ; case PropertyEditor . NAME_COLUMN_NUM : rc = pair . getName ( ) ; break ; case PropertyEditor . VALUE_COLUMN_NUM : rc = pair . getValue ( ) ; break ; default : break ; } } return rc ; } @ Override public String getText ( final Object element ) { if ( element instanceof PropertyPair ) { final PropertyPair pair = ( PropertyPair ) element ; return pair . getName ( ) ; } else { return element . toString ( ) ; } } } package net . ggtools . grand . ui . widgets . property ; public interface PropertyChangedListener { void allPropertiesChanged ( Object fillerParameter ) ; void clearedProperties ( Object fillerParameter ) ; void propertyAdded ( PropertyPair propertyPair ) ; void propertyChanged ( PropertyPair propertyPair ) ; void propertyRemoved ( PropertyPair propertyPair ) ; } package net . ggtools . grand . ui . widgets . property ; import java . util . Map . Entry ; class PropertyPair { String name ; String value ; public PropertyPair ( final String name , final String value ) { this . name = name ; this . value = value ; } public PropertyPair ( final Entry entry ) { this ( ( String ) entry . getKey ( ) , ( String ) entry . getValue ( ) ) ; } public final String getName ( ) { return name ; } public final void setName ( final String name ) { this . name = name ; } public final String getValue ( ) { return value ; } public final void setValue ( final String value ) { this . value = value ; } } package net . ggtools . grand . ui . widgets . property ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import net . ggtools . grand . ui . widgets . ExceptionDialog ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . viewers . CellEditor ; import org . eclipse . jface . viewers . ICellModifier ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . TextCellEditor ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . swt . widgets . TableItem ; public class PropertyEditor { private final class CellModifier implements ICellModifier { public boolean canModify ( final Object element , final String property ) { if ( columnExists ( property ) ) { final int columnNumber = getColumnNumber ( property ) ; switch ( columnNumber ) { case STATUS_COLUMN_NUM : return false ; default : return true ; } } return false ; } public Object getValue ( final Object element , final String property ) { if ( columnExists ( property ) && ( element instanceof PropertyPair ) ) { final int columnNumber = getColumnNumber ( property ) ; final PropertyPair pair = ( PropertyPair ) element ; switch ( columnNumber ) { case NAME_COLUMN_NUM : return pair . getName ( ) ; case VALUE_COLUMN_NUM : return pair . getValue ( ) ; } } return null ; } public void modify ( final Object element , final String property , final Object value ) { if ( columnExists ( property ) ) { final PropertyPair pair = ( PropertyPair ) ( ( TableItem ) element ) . getData ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" + pair ) ; } final int columnNumber = getColumnNumber ( property ) ; switch ( columnNumber ) { case NAME_COLUMN_NUM : pair . setName ( value . toString ( ) ) ; propertyList . update ( pair ) ; break ; case VALUE_COLUMN_NUM : pair . setValue ( value . toString ( ) ) ; propertyList . update ( pair ) ; break ; } } } } private static final class PropertyListContentProvider implements IStructuredContentProvider , PropertyChangedListener { private static final Log log = LogFactory . getLog ( PropertyListContentProvider . class ) ; private PropertyList currentPropertyList ; private TableViewer tableViewer ; public void allPropertiesChanged ( final Object fillerParameter ) { tableViewer . getTable ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { tableViewer . refresh ( ) ; } } ) ; } public void clearedProperties ( final Object fillerParameter ) { tableViewer . getTable ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { tableViewer . refresh ( ) ; } } ) ; } public void dispose ( ) { if ( currentPropertyList != null ) { currentPropertyList . removePropertyChangedListener ( this ) ; } } public Object [ ] getElements ( final Object inputElement ) { if ( inputElement instanceof PropertyList ) { final PropertyList pList = ( PropertyList ) inputElement ; return pList . toArray ( ) ; } else { return null ; } } public void inputChanged ( final Viewer viewer , final Object oldInput , final Object newInput ) { tableViewer = ( TableViewer ) viewer ; if ( oldInput != null ) { ( ( PropertyList ) oldInput ) . removePropertyChangedListener ( this ) ; } if ( newInput != null ) { currentPropertyList = ( ( PropertyList ) newInput ) ; currentPropertyList . addPropertyChangedListener ( this ) ; } } public void propertyAdded ( final PropertyPair propertyPair ) { tableViewer . getTable ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { tableViewer . refresh ( ) ; } } ) ; } public void propertyChanged ( final PropertyPair propertyPair ) { tableViewer . getTable ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { tableViewer . update ( propertyPair , null ) ; } } ) ; } public void propertyRemoved ( final PropertyPair propertyPair ) { tableViewer . getTable ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { tableViewer . refresh ( ) ; } } ) ; } } private static final class Sorter extends ViewerSorter { private final static int NAME_COLUMN = ; private final static int VALUE_COLUMN = ; private int column = NAME_COLUMN ; @ Override public int compare ( final Viewer viewer , final Object e1 , final Object e2 ) { if ( ( e1 instanceof PropertyPair ) && ( e2 instanceof PropertyPair ) ) { final PropertyPair p1 = ( PropertyPair ) e1 ; final PropertyPair p2 = ( PropertyPair ) e2 ; String name1 = null ; String name2 = null ; switch ( column ) { case NAME_COLUMN : name1 = p1 . getName ( ) ; name2 = p2 . getName ( ) ; break ; case VALUE_COLUMN : name1 = p1 . getValue ( ) ; name2 = p2 . getValue ( ) ; break ; } return collator . compare ( name1 , name2 ) ; } else { return super . compare ( viewer , e1 , e2 ) ; } } public void sortByName ( ) { column = NAME_COLUMN ; } public void sortByValue ( ) { column = VALUE_COLUMN ; } } private static final int BUTTON_WIDTH = ; private static final int DEFAULT_NUM_LINES = ; private static final String [ ] FILTER_EXTENSIONS = new String [ ] { "" , "" } ; private static final int GRID_LAYOUT_COLUMNS = ; private static final Log log = LogFactory . getLog ( PropertyEditor . class ) ; private static final String STATUS_COLUMN = "" ; private static final String NAME_COLUMN = "" ; private static final String VALUE_COLUMN = "" ; static final int STATUS_COLUMN_NUM = ; static final int NAME_COLUMN_NUM = ; static final int VALUE_COLUMN_NUM = ; private static Map < String , Integer > columnNamesToNumMap = null ; private final String [ ] columnNames = new String [ ] { STATUS_COLUMN , NAME_COLUMN , VALUE_COLUMN } ; private final PropertyList propertyList ; private Table table ; private TableViewer tableViewer ; private Sorter viewerSorter ; public PropertyEditor ( final Composite parent , final int style ) { if ( columnNamesToNumMap == null ) { columnNamesToNumMap = new HashMap < String , Integer > ( ) ; columnNamesToNumMap . put ( STATUS_COLUMN , new Integer ( STATUS_COLUMN_NUM ) ) ; columnNamesToNumMap . put ( NAME_COLUMN , new Integer ( NAME_COLUMN_NUM ) ) ; columnNamesToNumMap . put ( VALUE_COLUMN , new Integer ( VALUE_COLUMN_NUM ) ) ; } propertyList = new PropertyList ( ) ; viewerSorter = new Sorter ( ) ; createContents ( parent , style ) ; tableViewer . setInput ( propertyList ) ; } public Properties getValues ( ) { return propertyList . getAsProperties ( ) ; } PropertyList getPropertyList ( ) { return propertyList ; } public void setInput ( final Map properties ) { propertyList . clear ( ) ; if ( properties != null ) { propertyList . addAll ( properties ) ; } } private void createButtons ( final Composite parent ) { final Button load = new Button ( parent , SWT . PUSH | SWT . CENTER ) ; load . setText ( "" ) ; GridData gridData = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gridData . widthHint = BUTTON_WIDTH ; load . setLayoutData ( gridData ) ; load . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent event ) { final FileDialog dialog = new FileDialog ( table . getShell ( ) ) ; dialog . setFilterExtensions ( FILTER_EXTENSIONS ) ; final String fileName = dialog . open ( ) ; if ( fileName != null ) { FileInputStream fileInputStream = null ; try { final Properties props = new Properties ( ) ; fileInputStream = new FileInputStream ( fileName ) ; props . load ( fileInputStream ) ; setInput ( props ) ; } catch ( final IOException e ) { final String message = "" + fileName ; log . error ( message , e ) ; ExceptionDialog . openException ( table . getShell ( ) , message , e ) ; } finally { if ( fileInputStream != null ) { try { fileInputStream . close ( ) ; } catch ( final IOException e ) { log . warn ( "" , e ) ; } } } } } } ) ; final Button save = new Button ( parent , SWT . PUSH | SWT . CENTER ) ; save . setText ( "" ) ; gridData = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gridData . widthHint = BUTTON_WIDTH ; save . setLayoutData ( gridData ) ; save . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent event ) { final FileDialog dialog = new FileDialog ( table . getShell ( ) , SWT . SAVE ) ; dialog . setFilterExtensions ( FILTER_EXTENSIONS ) ; final String fileName = dialog . open ( ) ; if ( fileName != null ) { FileOutputStream fileOutputStream = null ; try { fileOutputStream = new FileOutputStream ( fileName ) ; getValues ( ) . store ( fileOutputStream , null ) ; } catch ( final IOException e ) { final String message = "" + fileName ; log . error ( message , e ) ; ExceptionDialog . openException ( table . getShell ( ) , message , e ) ; } finally { if ( fileOutputStream != null ) { try { fileOutputStream . close ( ) ; } catch ( final IOException e ) { log . warn ( "" , e ) ; } } } } } } ) ; final Label filler = new Label ( parent , SWT . NO_BACKGROUND ) ; gridData = new GridData ( SWT . CENTER , SWT . CENTER , true , false ) ; filler . setLayoutData ( gridData ) ; final Button add = new Button ( parent , SWT . PUSH | SWT . CENTER ) ; add . setText ( "" ) ; gridData = new GridData ( GridData . HORIZONTAL_ALIGN_END ) ; gridData . widthHint = BUTTON_WIDTH ; add . setLayoutData ( gridData ) ; add . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } propertyList . addProperty ( ) ; } } ) ; final Button delete = new Button ( parent , SWT . PUSH | SWT . CENTER ) ; delete . setText ( "" ) ; gridData = new GridData ( GridData . HORIZONTAL_ALIGN_END ) ; gridData . widthHint = BUTTON_WIDTH ; delete . setLayoutData ( gridData ) ; delete . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { final PropertyPair pair = ( PropertyPair ) ( ( IStructuredSelection ) tableViewer . getSelection ( ) ) . getFirstElement ( ) ; if ( pair != null ) { propertyList . remove ( pair ) ; } } } ) ; final Button clear = new Button ( parent , SWT . PUSH | SWT . CENTER ) ; clear . setText ( "" ) ; gridData = new GridData ( GridData . HORIZONTAL_ALIGN_END ) ; gridData . widthHint = BUTTON_WIDTH ; clear . setLayoutData ( gridData ) ; clear . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { propertyList . clear ( ) ; } } ) ; } private void createContents ( final Composite parent , final int style ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; final GridData gridData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . FILL_BOTH ) ; composite . setLayoutData ( gridData ) ; final GridLayout layout = new GridLayout ( GRID_LAYOUT_COLUMNS , false ) ; layout . marginWidth = ; composite . setLayout ( layout ) ; createTable ( composite ) ; createTableViewer ( ) ; tableViewer . setContentProvider ( new PropertyListContentProvider ( ) ) ; tableViewer . setLabelProvider ( new PropertyListLabelProvider ( ) ) ; createButtons ( composite ) ; } private void createTable ( final Composite parent ) { final int style = SWT . SINGLE | SWT . BORDER | SWT . H_SCROLL | SWT . V_SCROLL | SWT . FULL_SELECTION | SWT . HIDE_SELECTION ; table = new Table ( parent , style ) ; table . setLinesVisible ( true ) ; table . setHeaderVisible ( true ) ; table . pack ( ) ; final GridData gridData = new GridData ( GridData . FILL_BOTH ) ; gridData . grabExcessVerticalSpace = true ; gridData . horizontalSpan = GRID_LAYOUT_COLUMNS ; gridData . heightHint = table . getHeaderHeight ( ) * DEFAULT_NUM_LINES ; table . setLayoutData ( gridData ) ; TableColumn column ; column = new TableColumn ( table , SWT . LEFT ) ; column . setWidth ( ) ; column . setMoveable ( true ) ; column . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { if ( tableViewer != null ) { tableViewer . refresh ( false ) ; } } } ) ; column = new TableColumn ( table , SWT . LEFT ) ; column . setText ( NAME_COLUMN ) ; column . setWidth ( ) ; column . setMoveable ( true ) ; column . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { viewerSorter . sortByName ( ) ; if ( tableViewer != null ) { tableViewer . refresh ( false ) ; } } } ) ; column = new TableColumn ( table , SWT . LEFT ) ; column . setText ( VALUE_COLUMN ) ; column . setWidth ( ) ; column . setMoveable ( true ) ; column . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { viewerSorter . sortByValue ( ) ; if ( tableViewer != null ) { tableViewer . refresh ( false ) ; } } } ) ; } private void createTableViewer ( ) { tableViewer = new TableViewer ( table ) ; tableViewer . setUseHashlookup ( true ) ; tableViewer . setColumnProperties ( columnNames ) ; final CellEditor [ ] editors = new CellEditor [ columnNames . length ] ; editors [ STATUS_COLUMN_NUM ] = null ; TextCellEditor textEditor = new TextCellEditor ( table ) ; editors [ NAME_COLUMN_NUM ] = textEditor ; textEditor = new TextCellEditor ( table ) ; editors [ VALUE_COLUMN_NUM ] = textEditor ; tableViewer . setCellEditors ( editors ) ; tableViewer . setCellModifier ( new CellModifier ( ) ) ; tableViewer . setSorter ( viewerSorter ) ; } int getColumnNumber ( final String columnName ) { return columnNamesToNumMap . get ( columnName ) . intValue ( ) ; } boolean columnExists ( final String columnName ) { return columnNamesToNumMap . containsKey ( columnName ) ; } } package net . ggtools . grand . ui . widgets . property ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import net . ggtools . grand . ui . event . Dispatcher ; import net . ggtools . grand . ui . event . EventManager ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; class PropertyList { private static final Log log = LogFactory . getLog ( PropertyList . class ) ; private Dispatcher allPropertiesChangedDispatcher ; private Dispatcher clearedPropertiesDispatcher ; private Dispatcher propertyAddedDispatcher ; private Dispatcher propertyChangedDispatcher ; private Dispatcher propertyRemovedDispatcher ; EventManager eventManager ; final Set < PropertyPair > pairList = new HashSet < PropertyPair > ( ) ; public PropertyList ( ) { eventManager = new EventManager ( "" ) ; try { propertyChangedDispatcher = eventManager . createDispatcher ( PropertyChangedListener . class . getDeclaredMethod ( "" , new Class [ ] { PropertyPair . class } ) ) ; propertyAddedDispatcher = eventManager . createDispatcher ( PropertyChangedListener . class . getDeclaredMethod ( "" , new Class [ ] { PropertyPair . class } ) ) ; propertyRemovedDispatcher = eventManager . createDispatcher ( PropertyChangedListener . class . getDeclaredMethod ( "" , new Class [ ] { PropertyPair . class } ) ) ; clearedPropertiesDispatcher = eventManager . createDispatcher ( PropertyChangedListener . class . getDeclaredMethod ( "" , new Class [ ] { Object . class } ) ) ; allPropertiesChangedDispatcher = eventManager . createDispatcher ( PropertyChangedListener . class . getDeclaredMethod ( "" , new Class [ ] { Object . class } ) ) ; } catch ( final SecurityException e ) { log . fatal ( "" , e ) ; throw new RuntimeException ( "" , e ) ; } catch ( final NoSuchMethodException e ) { log . fatal ( "" , e ) ; throw new RuntimeException ( "" , e ) ; } } public void addAll ( final Map properties ) { for ( final Iterator iter = properties . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final Map . Entry entry = ( Map . Entry ) iter . next ( ) ; pairList . add ( new PropertyPair ( entry ) ) ; } } public void addProperty ( ) { add ( new PropertyPair ( "" , "" ) ) ; } public void addPropertyChangedListener ( final PropertyChangedListener listener ) { eventManager . subscribe ( listener ) ; } public void clear ( ) { pairList . clear ( ) ; clearedPropertiesDispatcher . dispatch ( null ) ; } public Properties getAsProperties ( ) { final Properties props = new Properties ( ) ; for ( final Iterator < PropertyPair > iter = pairList . iterator ( ) ; iter . hasNext ( ) ; ) { final PropertyPair pair = iter . next ( ) ; props . setProperty ( pair . getName ( ) , pair . getValue ( ) ) ; } return props ; } public void remove ( final PropertyPair pair ) { pairList . remove ( pair ) ; propertyRemovedDispatcher . dispatch ( pair ) ; } public void removePropertyChangedListener ( final PropertyChangedListener listener ) { eventManager . unSubscribe ( listener ) ; } public PropertyPair [ ] toArray ( ) { return pairList . toArray ( new PropertyPair [ pairList . size ( ) ] ) ; } @ Override public String toString ( ) { final StringBuffer strBuff = new StringBuffer ( ) ; for ( final Iterator < PropertyPair > iter = pairList . iterator ( ) ; iter . hasNext ( ) ; ) { final PropertyPair pair = iter . next ( ) ; strBuff . append ( pair . getName ( ) ) . append ( "" ) . append ( pair . getValue ( ) ) . append ( "" ) ; } return strBuff . toString ( ) ; } public void update ( final PropertyPair pair ) { propertyChangedDispatcher . dispatch ( pair ) ; } private void add ( final PropertyPair pair ) { pairList . add ( pair ) ; propertyAddedDispatcher . dispatch ( pair ) ; } } package net . ggtools . grand . ui . widgets ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . swt . widgets . Display ; public class SafeProgressMonitor implements IProgressMonitor { private final IProgressMonitor monitor ; private final Display display ; public SafeProgressMonitor ( final IProgressMonitor monitor , final Display display ) { this . monitor = monitor ; this . display = display ; } public void beginTask ( final String name , final int totalWork ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { monitor . beginTask ( name , totalWork ) ; } } ) ; } public void done ( ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { monitor . done ( ) ; } } ) ; } public void internalWorked ( final double work ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { monitor . internalWorked ( work ) ; } } ) ; } public boolean isCanceled ( ) { return monitor . isCanceled ( ) ; } public void setCanceled ( final boolean value ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { monitor . setCanceled ( value ) ; } } ) ; } public void setTaskName ( final String name ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { monitor . setTaskName ( name ) ; } } ) ; } public void subTask ( final String name ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { monitor . subTask ( name ) ; } } ) ; } public void worked ( final int work ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { monitor . worked ( work ) ; } } ) ; } } package net . ggtools . grand . ui . widgets ; import net . ggtools . grand . ui . graph . GraphControler ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; public class PageSetupDialog extends Dialog { private Combo combo ; public PageSetupDialog ( final Shell parentShell ) { super ( parentShell ) ; } @ Override protected void cancelPressed ( ) { super . cancelPressed ( ) ; } @ Override protected Control createDialogArea ( final Composite parent ) { final Composite composite = ( Composite ) super . createDialogArea ( parent ) ; final GridLayout layout = new GridLayout ( ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . numColumns = ; composite . setLayout ( layout ) ; final Label label = new Label ( composite , SWT . NONE ) ; label . setText ( "" ) ; label . setAlignment ( SWT . RIGHT ) ; label . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_END ) ) ; combo = new Combo ( composite , SWT . DROP_DOWN | SWT . READ_ONLY ) ; combo . setItems ( new String [ ] { "" , "" , "" , "" } ) ; combo . select ( GraphControler . getPrintMode ( ) - ) ; combo . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . GRAB_HORIZONTAL ) ) ; return composite ; } @ Override protected void okPressed ( ) { GraphControler . setPrintMode ( combo . getSelectionIndex ( ) + ) ; super . okPressed ( ) ; } @ Override protected void configureShell ( final Shell newShell ) { super . configureShell ( newShell ) ; newShell . setText ( "" ) ; } } package net . ggtools . grand . ui . widgets ; import java . util . Map ; import java . util . Properties ; import net . ggtools . grand . ui . widgets . property . PropertyEditor ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; public class PropertyEditionDialog extends Dialog { private PropertyEditor propertyEditor ; private Map propertiesToLoad ; public PropertyEditionDialog ( final Shell parentShell ) { super ( parentShell ) ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; } @ Override protected Control createDialogArea ( final Composite parent ) { final Composite composite = ( Composite ) super . createDialogArea ( parent ) ; composite . setLayout ( new FillLayout ( ) ) ; propertyEditor = new PropertyEditor ( composite , SWT . NONE ) ; if ( propertiesToLoad != null ) { propertyEditor . setInput ( propertiesToLoad ) ; propertiesToLoad = null ; } return composite ; } @ Override protected void configureShell ( final Shell newShell ) { super . configureShell ( newShell ) ; newShell . setText ( "" ) ; } public void setProperties ( final Map properties ) { if ( propertyEditor == null ) { propertiesToLoad = properties ; } else { propertyEditor . setInput ( properties ) ; } } public Properties getProperties ( ) { if ( propertyEditor == null ) { return null ; } return propertyEditor . getValues ( ) ; } } package net . ggtools . grand . ui . widgets ; import java . io . File ; import java . util . Properties ; import net . ggtools . grand . ui . RecentFilesManager ; import net . ggtools . grand . ui . widgets . OpenFileWizard . SelectedFileListener ; import net . ggtools . grand . ui . widgets . OpenFileWizard . SelectedFileProvider ; import net . ggtools . grand . ui . widgets . property . PropertyEditor ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; public class PropertySettingPage extends WizardPage implements SelectedFileListener { private PropertyEditor editor ; private final SelectedFileProvider fileProvider ; public PropertySettingPage ( final OpenFileWizard . SelectedFileProvider fileProvider ) { super ( "" , "" , null ) ; setDescription ( "" ) ; this . fileProvider = fileProvider ; fileProvider . addListener ( this ) ; } public void createControl ( final Composite parent ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; setControl ( composite ) ; composite . setLayout ( new FillLayout ( ) ) ; editor = new PropertyEditor ( composite , SWT . NONE ) ; } public Properties getProperties ( ) { return editor . getValues ( ) ; } @ Override public void dispose ( ) { fileProvider . removeListener ( this ) ; super . dispose ( ) ; } public void fileSelected ( final File selectedFile ) { if ( editor != null ) { editor . setInput ( RecentFilesManager . getInstance ( ) . getProperties ( selectedFile ) ) ; } } } package net . ggtools . grand . ui . widgets ; import java . io . File ; import java . util . Collection ; import java . util . HashSet ; import java . util . Iterator ; import net . ggtools . grand . ui . RecentFilesManager ; import net . ggtools . grand . ui . widgets . OpenFileWizard . SelectedFileListener ; import net . ggtools . grand . ui . widgets . OpenFileWizard . SelectedFileProvider ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CCombo ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . FileDialog ; public class FileSelectionPage extends WizardPage implements SelectedFileProvider { private static final Log log = LogFactory . getLog ( FileSelectionPage . class ) ; private static final String [ ] FILTER_EXTENSIONS = new String [ ] { "" , "" } ; private String selectedFileName ; private File selectedFile ; private final Collection < SelectedFileListener > subscribers ; public FileSelectionPage ( ) { super ( "" , "" , null ) ; setDescription ( "" ) ; subscribers = new HashSet < SelectedFileListener > ( ) ; } public void createControl ( final Composite parent ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; final GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; setControl ( composite ) ; final CCombo combo = new CCombo ( composite , SWT . NONE ) ; combo . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; combo . add ( "" ) ; for ( final Iterator < String > iter = RecentFilesManager . getInstance ( ) . getRecentFiles ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final String fileName = iter . next ( ) ; combo . add ( fileName ) ; } combo . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( final SelectionEvent e ) { updateSelectedFile ( combo . getText ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" + selectedFileName ) ; } } public void widgetDefaultSelected ( final SelectionEvent e ) { widgetSelected ( e ) ; if ( combo . indexOf ( selectedFileName ) == - ) { combo . add ( selectedFileName ) ; } } } ) ; updateSelectedFile ( combo . getItem ( ) ) ; setPageComplete ( false ) ; final Button openFileButton = new Button ( composite , SWT . PUSH ) ; openFileButton . setText ( "" ) ; openFileButton . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( final SelectionEvent e ) { final FileDialog dialog = new FileDialog ( getShell ( ) ) ; dialog . setFilterExtensions ( FILTER_EXTENSIONS ) ; dialog . setFilterPath ( selectedFileName ) ; final String buildFileName = dialog . open ( ) ; log . debug ( "" + buildFileName ) ; if ( buildFileName != null ) { combo . add ( buildFileName ) ; combo . select ( combo . getItemCount ( ) - ) ; updateSelectedFile ( combo . getText ( ) ) ; } } } ) ; } private void updateSelectedFile ( final String text ) { selectedFileName = text ; if ( "" . equals ( selectedFileName ) ) { selectedFile = null ; } else { selectedFile = new File ( selectedFileName ) ; final boolean isSelectedFileValid = selectedFile . isFile ( ) ; setPageComplete ( isSelectedFileValid ) ; if ( isSelectedFileValid ) { setErrorMessage ( null ) ; } else { selectedFile = null ; setErrorMessage ( selectedFileName + "" ) ; } } notifyListeners ( ) ; } public final File getSelectedFile ( ) { return selectedFile ; } public void addListener ( final OpenFileWizard . SelectedFileListener listener ) { if ( ! subscribers . contains ( listener ) ) { subscribers . add ( listener ) ; listener . fileSelected ( selectedFile ) ; } } public void removeListener ( final OpenFileWizard . SelectedFileListener listener ) { subscribers . remove ( listener ) ; } private void notifyListeners ( ) { for ( final Iterator < SelectedFileListener > iter = subscribers . iterator ( ) ; iter . hasNext ( ) ; ) { final OpenFileWizard . SelectedFileListener listener = iter . next ( ) ; listener . fileSelected ( selectedFile ) ; } } } package net . ggtools . grand . ui . widgets ; import net . ggtools . grand . ui . log . LogEventBufferImpl ; import net . ggtools . grand . ui . log . LogViewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; public class LogWindow extends Window { private LogViewer viewer ; public LogWindow ( final Shell parentShell ) { super ( parentShell ) ; setShellStyle ( SWT . SHELL_TRIM ) ; setBlockOnOpen ( false ) ; } @ Override protected void configureShell ( final Shell newShell ) { super . configureShell ( newShell ) ; newShell . setText ( "" ) ; } @ Override protected Control createContents ( final Composite parent ) { final GridLayout layout = new GridLayout ( ) ; parent . setLayout ( layout ) ; viewer = new LogViewer ( parent , SWT . BORDER ) ; viewer . setLogBuffer ( LogEventBufferImpl . getInstance ( ) ) ; return parent ; } } package net . ggtools . grand . ui . widgets ; import java . text . CollationKey ; import java . text . Collator ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Iterator ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import net . ggtools . grand . ant . AntTargetNode ; import net . ggtools . grand . ant . AntTargetNode . SourceElement ; import net . ggtools . grand . graph . Node ; import net . ggtools . grand . ui . Application ; import net . ggtools . grand . ui . graph . GraphControler ; import net . ggtools . grand . ui . graph . GraphControlerListener ; import net . ggtools . grand . ui . graph . GraphDisplayer ; import net . ggtools . grand . ui . graph . GraphListener ; import net . ggtools . grand . ui . graph . draw2d . Draw2dGraph ; import net . ggtools . grand . ui . graph . draw2d . Draw2dNode ; import net . ggtools . grand . ui . menu . GraphMenu ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . draw2d . ColorConstants ; import org . eclipse . draw2d . FigureCanvas ; import org . eclipse . draw2d . geometry . Point ; import org . eclipse . draw2d . geometry . Rectangle ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CTabFolder ; import org . eclipse . swt . custom . CTabItem ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . custom . ScrolledComposite ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Menu ; public class GraphTabItem extends CTabItem implements GraphDisplayer , GraphListener { private final class MouseWheelZoomListener implements Listener { private final Log log = LogFactory . getLog ( MouseWheelZoomListener . class ) ; private MouseWheelZoomListener ( ) { } public void handleEvent ( final Event event ) { final float zoomBefore = getZoom ( ) ; event . doit = false ; if ( event . count > ) { zoomIn ( ) ; } else { zoomOut ( ) ; } final float zoomAfter = getZoom ( ) ; if ( zoomAfter != zoomBefore ) { final Point location = canvas . getViewport ( ) . getViewLocation ( ) ; final int newX = ( int ) ( ( ( location . x + event . x ) / zoomBefore ) * zoomAfter ) - event . x ; final int newY = ( int ) ( ( ( location . y + event . y ) / zoomBefore ) * zoomAfter ) - event . y ; canvas . scrollTo ( newX , newY ) ; } } } private final static class OutlineViewerCollator extends Collator { private static final Log log = LogFactory . getLog ( OutlineViewerCollator . class ) ; private static final int NODE_INDEX_GROUP_NUM = ; private final static int NODE_NAME_GROUP_NUM = ; private final static Pattern pattern = Pattern . compile ( "" , Pattern . CASE_INSENSITIVE ) ; private final Collator underlying ; public OutlineViewerCollator ( ) { underlying = getInstance ( ) ; } @ Override public int compare ( final String source , final String target ) { final Matcher sourceMatcher = pattern . matcher ( source ) ; if ( ! sourceMatcher . matches ( ) ) { final String message = "" + source + "" ; log . error ( message ) ; throw new Error ( message ) ; } assert ( sourceMatcher . groupCount ( ) == ) ; final Matcher targetMatcher = pattern . matcher ( target ) ; if ( ! targetMatcher . matches ( ) ) { final String message = "" + source + "" ; log . error ( message ) ; throw new Error ( message ) ; } assert ( targetMatcher . groupCount ( ) == ) ; int result = underlying . compare ( sourceMatcher . group ( NODE_NAME_GROUP_NUM ) , targetMatcher . group ( NODE_NAME_GROUP_NUM ) ) ; if ( result == ) { int sourceIndex ; final String sourceIndexGroup = sourceMatcher . group ( NODE_INDEX_GROUP_NUM ) ; try { sourceIndex = Integer . parseInt ( sourceIndexGroup ) ; } catch ( final NumberFormatException e ) { log . debug ( "" + sourceIndexGroup + "" ) ; sourceIndex = ; } int targetIndex ; final String targetIndexGroup = targetMatcher . group ( NODE_INDEX_GROUP_NUM ) ; try { targetIndex = Integer . parseInt ( targetIndexGroup ) ; } catch ( final NumberFormatException e ) { log . debug ( "" + targetIndexGroup + "" ) ; targetIndex = ; } result = sourceIndex < targetIndex ? - : ( sourceIndex == targetIndex ? : ) ; } return result ; } @ Override public CollationKey getCollationKey ( final String source ) { throw new Error ( "" ) ; } @ Override public int hashCode ( ) { return underlying . hashCode ( ) ; } } private static final Log log = LogFactory . getLog ( GraphTabItem . class ) ; private final static float ZOOM_MAX = ; private final static float ZOOM_MIN = ; private final static float ZOOM_STEP = ; private final FigureCanvas canvas ; private final CanvasScroller canvasScroller ; private final Menu contextMenu ; private final MenuManager contextMenuManager ; private final GraphControler controler ; private Draw2dGraph graph ; private final SashForm outlineSashForm ; private final TableViewer outlineViewer ; private boolean skipJumpToNode = false ; private final SashForm sourceSashForm ; private final ScrolledComposite textComposite ; private final StyledText textDisplayer ; public GraphTabItem ( final CTabFolder parent , final int style , final GraphControler controler ) { super ( parent , style ) ; this . controler = controler ; sourceSashForm = new SashForm ( parent , SWT . VERTICAL | SWT . BORDER ) ; outlineSashForm = new SashForm ( sourceSashForm , SWT . HORIZONTAL | SWT . BORDER ) ; setControl ( sourceSashForm ) ; outlineViewer = new TableViewer ( outlineSashForm , SWT . READ_ONLY | SWT . H_SCROLL | SWT . V_SCROLL ) ; outlineViewer . setContentProvider ( controler . getNodeContentProvider ( ) ) ; outlineViewer . setLabelProvider ( controler . getNodeLabelProvider ( ) ) ; outlineViewer . setSorter ( new ViewerSorter ( new OutlineViewerCollator ( ) ) ) ; outlineViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( final SelectionChangedEvent event ) { final ISelection selection = event . getSelection ( ) ; if ( ! selection . isEmpty ( ) ) { if ( selection instanceof IStructuredSelection ) { final IStructuredSelection structuredSelection = ( IStructuredSelection ) selection ; if ( structuredSelection . size ( ) == ) { final String nodeName = structuredSelection . getFirstElement ( ) . toString ( ) ; if ( ! skipJumpToNode ) { jumpToNode ( nodeName ) ; } skipJumpToNode = false ; getControler ( ) . selectNodeByName ( nodeName , false ) ; } } } } } ) ; canvas = new FigureCanvas ( outlineSashForm ) ; canvas . getViewport ( ) . setContentsTracksHeight ( true ) ; canvas . getViewport ( ) . setContentsTracksWidth ( true ) ; canvas . setBackground ( ColorConstants . white ) ; canvas . setScrollBarVisibility ( FigureCanvas . AUTOMATIC ) ; canvas . addListener ( SWT . MouseWheel , new MouseWheelZoomListener ( ) ) ; canvasScroller = new CanvasScroller ( canvas ) ; contextMenuManager = new GraphMenu ( this ) ; contextMenu = contextMenuManager . createContextMenu ( canvas ) ; outlineSashForm . setWeights ( new int [ ] { , } ) ; textComposite = new ScrolledComposite ( sourceSashForm , SWT . H_SCROLL | SWT . V_SCROLL ) ; textDisplayer = new StyledText ( textComposite , SWT . MULTI | SWT . READ_ONLY ) ; textDisplayer . setFont ( Application . getInstance ( ) . getFont ( Application . MONOSPACE_FONT ) ) ; textComposite . setContent ( textDisplayer ) ; textComposite . setExpandHorizontal ( true ) ; textComposite . setExpandVertical ( true ) ; sourceSashForm . setWeights ( new int [ ] { , } ) ; controler . addListener ( this ) ; } public void addControlerListener ( final GraphControlerListener listener ) { } public Menu getContextMenu ( ) { return contextMenu ; } public GraphControler getControler ( ) { return controler ; } public void jumpToNode ( final String nodeName ) { if ( graph != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + nodeName + "" ) ; } final Rectangle bounds = graph . getBoundsForNode ( nodeName ) ; if ( bounds != null ) { final Point center = bounds . getCenter ( ) ; final float graphZoom = graph . getZoom ( ) ; Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { final org . eclipse . swt . graphics . Point size = canvas . getSize ( ) ; canvas . scrollSmoothTo ( ( int ) ( center . x * graphZoom - size . x / ) , ( int ) ( center . y * graphZoom - size . y / ) ) ; } } ) ; } } } public void parameterChanged ( final GraphControler graphControler ) { } public void removeControlerListener ( final GraphControlerListener listener ) { } public void selectionChanged ( final Collection selectedNodes ) { final List < Node > selection = new ArrayList < Node > ( selectedNodes . size ( ) ) ; for ( final Iterator iter = selectedNodes . iterator ( ) ; iter . hasNext ( ) ; ) { final Draw2dNode node = ( Draw2dNode ) iter . next ( ) ; selection . add ( node . getNode ( ) ) ; } Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { skipJumpToNode = true ; outlineViewer . setSelection ( new StructuredSelection ( selection ) , true ) ; } } ) ; } public void setGraph ( final Draw2dGraph graph , final String name , final String toolTip ) { this . graph = graph ; Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { canvas . setContents ( graph ) ; setText ( name ) ; setToolTipText ( toolTip ) ; graph . setScroller ( canvasScroller ) ; outlineViewer . setInput ( graph ) ; } } ) ; } public final void setOutlinePanelVisible ( final boolean outlinePanelVisible ) { outlineViewer . getControl ( ) . setVisible ( outlinePanelVisible ) ; outlineSashForm . layout ( ) ; } public void setRichSource ( final SourceElement [ ] richSource ) { if ( richSource == null ) { setSourceText ( "" ) ; return ; } final StringBuffer buffer = new StringBuffer ( ) ; for ( final AntTargetNode . SourceElement element : richSource ) { buffer . append ( element . getText ( ) ) ; } setSourceText ( buffer . toString ( ) ) ; int start = ; for ( final AntTargetNode . SourceElement element : richSource ) { Color textColor ; switch ( element . getStyle ( ) ) { case AntTargetNode . SOURCE_ATTRIBUTE : textColor = ColorConstants . darkGreen ; break ; case AntTargetNode . SOURCE_MARKUP : textColor = ColorConstants . darkBlue ; break ; case AntTargetNode . SOURCE_TEXT : textColor = ColorConstants . black ; break ; default : textColor = ColorConstants . lightGray ; break ; } textDisplayer . setStyleRange ( new StyleRange ( start , element . getText ( ) . length ( ) , textColor , textDisplayer . getBackground ( ) ) ) ; start += element . getText ( ) . length ( ) ; } } public final void setSourcePanelVisible ( final boolean sourcePanelVisible ) { textComposite . setVisible ( sourcePanelVisible ) ; sourceSashForm . layout ( ) ; } public void setSourceText ( final String text ) { textDisplayer . setText ( text ) ; textComposite . setMinSize ( textDisplayer . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ) ; } public void zoomIn ( ) { final float zoom = getZoom ( ) ; if ( zoom < ZOOM_MAX ) { setZoom ( zoom * ZOOM_STEP ) ; } } public void zoomOut ( ) { final float zoom = getZoom ( ) ; if ( zoom > ZOOM_MIN ) { setZoom ( zoom / ZOOM_STEP ) ; } } public void zoomReset ( ) { setZoom ( ) ; } private final float getZoom ( ) { return graph == null ? : graph . getZoom ( ) ; } private final void setZoom ( final float zoom ) { if ( graph != null ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + zoom + "" ) ; } graph . setZoom ( zoom ) ; } } } package net . ggtools . grand . ui ; import java . io . IOException ; import java . util . Iterator ; import java . util . Properties ; import net . ggtools . grand . Configuration ; import net . ggtools . grand . log . LoggerManager ; import net . ggtools . grand . ui . log . CommonsLoggingLoggerFactory ; import net . ggtools . grand . ui . widgets . ExceptionDialog ; import net . ggtools . grand . ui . widgets . GraphWindow ; import net . ggtools . grand . ui . widgets . Splash ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . resource . FontRegistry ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . resource . ImageRegistry ; import org . eclipse . jface . window . ApplicationWindow ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Display ; public class Application implements Runnable { final public static String ABOUT_DIALOG_IMAGE = "" ; final public static String APPLICATION_ICON = "" ; final public static String GRAPH_FONT = "" ; final public static String LINK_FONT = "" ; final public static String LINK_ICON = "" ; final public static String MONOSPACE_FONT = "" ; final public static String NODE_FONT = "" ; final public static String NODE_ICON = "" ; final public static String TOOLTIP_FONT = "" ; final public static String TOOLTIP_MONOSPACE_FONT = "" ; private static final Log log = LogFactory . getLog ( Application . class ) ; private static Application singleton ; static public Application getInstance ( ) { return singleton ; } public static void main ( final String [ ] args ) { try { Thread . currentThread ( ) . setName ( "" ) ; final Application application = new Application ( ) ; application . run ( ) ; } catch ( final Throwable e ) { log . fatal ( "" , e ) ; } log . info ( "" ) ; System . exit ( ) ; } final private Properties buildProperties ; private FontRegistry fontRegistry ; private ImageRegistry imageRegistry ; private GrandUiPrefStore preferenceStore ; final private String versionString ; public Application ( ) throws IOException { if ( log . isTraceEnabled ( ) ) { log . trace ( "" ) ; } singleton = this ; buildProperties = new Properties ( ) ; buildProperties . load ( getClass ( ) . getResourceAsStream ( "" ) ) ; versionString = "" + buildProperties . getProperty ( "" ) + "" + buildProperties . getProperty ( "" ) + "" + buildProperties . getProperty ( "" ) + "" ; } final public Font getBoldFont ( final String symbolicName ) { return fontRegistry . getBold ( symbolicName ) ; } final public Properties getBuildProperties ( ) { return buildProperties ; } final public Font getFont ( final String symbolicName ) { return fontRegistry . get ( symbolicName ) ; } public final FontRegistry getFontRegistry ( ) { return fontRegistry ; } final public Image getImage ( final String key ) { return imageRegistry . get ( key ) ; } public final ImageRegistry getImageRegistry ( ) { return imageRegistry ; } final public Font getItalicFont ( final String symbolicName ) { return fontRegistry . getItalic ( symbolicName ) ; } public final GrandUiPrefStore getPreferenceStore ( ) { return preferenceStore ; } final public String getVersionString ( ) { return versionString ; } final private void initResources ( ) throws IOException { if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } preferenceStore = new GrandUiPrefStore ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } fontRegistry = new FontRegistry ( "" ) ; for ( final Iterator iter = fontRegistry . getKeySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final String key = ( String ) iter . next ( ) ; fontRegistry . get ( key ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } imageRegistry = new ImageRegistry ( ) ; imageRegistry . put ( ABOUT_DIALOG_IMAGE , ImageDescriptor . createFromFile ( Application . class , "" ) ) ; imageRegistry . put ( APPLICATION_ICON , ImageDescriptor . createFromFile ( Application . class , "" ) ) ; imageRegistry . put ( LINK_ICON , ImageDescriptor . createFromFile ( Application . class , "" ) ) ; imageRegistry . put ( NODE_ICON , ImageDescriptor . createFromFile ( Application . class , "" ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } Window . setDefaultImage ( getImage ( APPLICATION_ICON ) ) ; LoggerManager . setFactory ( new CommonsLoggingLoggerFactory ( ) ) ; } final public void run ( ) { if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; log . info ( "" + versionString ) ; log . info ( "" + SWT . getPlatform ( ) + "" + SWT . getVersion ( ) ) ; Configuration coreConfiguration = null ; try { coreConfiguration = Configuration . getConfiguration ( ) ; log . info ( "" + coreConfiguration . getVersionString ( ) ) ; log . info ( "" + coreConfiguration . getAntVersionString ( ) ) ; } catch ( final IOException e ) { log . error ( "" , e ) ; } log . info ( "" + System . getProperty ( "" ) + "" + System . getProperty ( "" ) ) ; } final Display display = Display . getDefault ( ) ; final Splash splash = new Splash ( display , versionString ) ; splash . open ( ) ; try { initResources ( ) ; } catch ( final IOException e ) { splash . close ( ) ; splash . dispose ( ) ; log . error ( "" , e ) ; ExceptionDialog . openException ( null , "" , e ) ; throw new RuntimeException ( "" , e ) ; } final ApplicationWindow mainWindow = new GraphWindow ( ) ; mainWindow . setBlockOnOpen ( true ) ; splash . close ( ) ; splash . dispose ( ) ; mainWindow . open ( ) ; } } package net . ggtools . grand . ui ; import java . util . Collection ; public interface RecentFilesListener { void refreshRecentFiles ( Collection < String > fileList ) ; } package net . ggtools . grand . ui ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . prefs . BackingStoreException ; import java . util . prefs . Preferences ; import net . ggtools . grand . ui . prefs . ComplexPreferenceStore ; import net . ggtools . grand . ui . prefs . GraphPreferencePage ; import net . ggtools . grand . ui . prefs . LinksPreferencePage ; import net . ggtools . grand . ui . prefs . NodesPreferencePage ; import net . ggtools . grand . ui . prefs . PreferenceKeys ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class GrandUiPrefStore extends ComplexPreferenceStore { private static final Log log = LogFactory . getLog ( GrandUiPrefStore . class ) ; private final File baseDir ; GrandUiPrefStore ( ) throws IOException { super ( ) ; baseDir = new File ( System . getProperty ( "" ) , "" ) ; final File destFile = new File ( baseDir , "" ) ; setPrefFile ( destFile ) ; setDefaults ( ) ; if ( destFile . isFile ( ) ) { load ( ) ; } else { migratePreferences ( ) ; } } @ Override public void save ( ) throws IOException { if ( ! baseDir . isDirectory ( ) ) { baseDir . mkdirs ( ) ; if ( ! baseDir . isDirectory ( ) ) { throw new FileNotFoundException ( "" + baseDir ) ; } } super . save ( ) ; } private void migratePreferences ( ) { final Preferences node = Preferences . userNodeForPackage ( GrandUiPrefStore . class ) ; final String [ ] keys ; try { keys = node . keys ( ) ; for ( final String key : keys ) { putValue ( key , node . get ( key , "" ) ) ; } save ( ) ; node . removeNode ( ) ; } catch ( final BackingStoreException e ) { log . warn ( "" , e ) ; } catch ( final IOException e ) { log . error ( "" , e ) ; } } private void setDefaults ( ) { setDefault ( PreferenceKeys . MAX_RECENT_FILES_PREFS_KEY , ) ; GraphPreferencePage . setDefaults ( this ) ; NodesPreferencePage . setDefaults ( this ) ; LinksPreferencePage . setDefaults ( this ) ; } } package net . ggtools . grand . ui . graph ; import java . io . File ; import java . lang . reflect . InvocationTargetException ; import java . util . Collection ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import net . ggtools . grand . ant . AntTargetNode ; import net . ggtools . grand . exceptions . GrandException ; import net . ggtools . grand . filters . GraphFilter ; import net . ggtools . grand . graph . Graph ; import net . ggtools . grand . output . DotWriter ; import net . ggtools . grand . ui . Application ; import net . ggtools . grand . ui . GrandUiPrefStore ; import net . ggtools . grand . ui . RecentFilesManager ; import net . ggtools . grand . ui . event . Dispatcher ; import net . ggtools . grand . ui . event . EventManager ; import net . ggtools . grand . ui . graph . draw2d . Draw2dGraph ; import net . ggtools . grand . ui . graph . draw2d . Draw2dGraphRenderer ; import net . ggtools . grand . ui . graph . draw2d . Draw2dNode ; import net . ggtools . grand . ui . prefs . PreferenceKeys ; import net . ggtools . grand . ui . widgets . ExceptionDialog ; import net . ggtools . grand . ui . widgets . GraphWindow ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . apache . tools . ant . BuildException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . draw2d . PrintFigureOperation ; import org . eclipse . draw2d . SWTGraphics ; import org . eclipse . draw2d . geometry . Rectangle ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . operation . ModalContext ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . printing . Printer ; import org . eclipse . swt . widgets . Display ; import sf . jzgraph . IDotGraph ; import sf . jzgraph . dot . impl . Dot ; public class GraphControler implements DotGraphAttributes , SelectionManager , IPropertyChangeListener { private static final Log log = LogFactory . getLog ( GraphControler . class ) ; private static int printMode = PrintFigureOperation . FIT_PAGE ; public static final int getPrintMode ( ) { return printMode ; } public static final void setPrintMode ( final int printMode ) { GraphControler . printMode = printMode ; } private boolean busRoutingEnabled ; private boolean clearFiltersOnNextLoad ; private IProgressMonitor defaultProgressMonitor ; private GraphDisplayer displayer ; private Draw2dGraph figure ; private FilterChainModel filterChain ; private Graph graph ; private EventManager graphEventManager ; private GraphModel model ; private final GraphNodeContentProvider nodeContentProvider ; private Dispatcher parameterChangedEvent ; private Draw2dGraphRenderer renderer ; private final Set < Draw2dNode > selectedNodes = new HashSet < Draw2dNode > ( ) ; private Dispatcher selectionChangedDispatcher ; private GraphWindow window ; public GraphControler ( final GraphWindow window ) { if ( log . isInfoEnabled ( ) ) { log . info ( "" + window ) ; } this . window = window ; model = new GraphModel ( ) ; filterChain = new FilterChainModel ( model ) ; renderer = new Draw2dGraphRenderer ( ) ; nodeContentProvider = new GraphNodeContentProvider ( ) ; graphEventManager = new EventManager ( "" ) ; try { selectionChangedDispatcher = graphEventManager . createDispatcher ( GraphListener . class . getDeclaredMethod ( "" , new Class [ ] { Collection . class } ) ) ; parameterChangedEvent = graphEventManager . createDispatcher ( GraphListener . class . getDeclaredMethod ( "" , new Class [ ] { GraphControler . class } ) ) ; } catch ( final SecurityException e ) { log . fatal ( "" , e ) ; throw new RuntimeException ( "" , e ) ; } catch ( final NoSuchMethodException e ) { log . fatal ( "" , e ) ; throw new RuntimeException ( "" , e ) ; } clearFiltersOnNextLoad = true ; final GrandUiPrefStore preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; busRoutingEnabled = preferenceStore . getBoolean ( PreferenceKeys . GRAPH_BUS_ENABLED_DEFAULT ) ; preferenceStore . addPropertyChangeListener ( this ) ; } public void addFilter ( final GraphFilter filter ) { final IProgressMonitor progressMonitor = defaultProgressMonitor ; try { ModalContext . run ( new IRunnableWithProgress ( ) { public void run ( final IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { log . info ( "" + filter ) ; progressMonitor . beginTask ( "" , ) ; filterChain . addFilterLast ( filter ) ; progressMonitor . worked ( ) ; renderFilteredGraph ( progressMonitor ) ; } } , true , progressMonitor , Display . getCurrent ( ) ) ; } catch ( final InvocationTargetException e ) { reportError ( "" , e ) ; } catch ( final InterruptedException e ) { reportError ( "" , e ) ; } finally { progressMonitor . done ( ) ; } } public void addListener ( final GraphListener listener ) { if ( graphEventManager != null ) { graphEventManager . subscribe ( listener ) ; } } public void clearFilters ( ) { final IProgressMonitor progressMonitor = defaultProgressMonitor ; try { ModalContext . run ( new IRunnableWithProgress ( ) { public void run ( final IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { log . info ( "" ) ; progressMonitor . beginTask ( "" , ) ; filterChain . clearFilters ( ) ; progressMonitor . worked ( ) ; renderFilteredGraph ( progressMonitor ) ; } } , true , progressMonitor , Display . getCurrent ( ) ) ; } catch ( final InvocationTargetException e ) { reportError ( "" , e ) ; } catch ( final InterruptedException e ) { reportError ( "" , e ) ; } finally { progressMonitor . done ( ) ; } } public void deselectAllNodes ( ) { if ( ! selectedNodes . isEmpty ( ) ) { for ( final Iterator < Draw2dNode > iter = selectedNodes . iterator ( ) ; iter . hasNext ( ) ; ) { final Draw2dNode currentNode = iter . next ( ) ; currentNode . setSelected ( false ) ; } selectedNodes . clear ( ) ; displayer . setSourceText ( "" ) ; selectionChangedDispatcher . dispatch ( selectedNodes ) ; } } public void deselectNode ( final Draw2dNode node ) { log . debug ( "" + node ) ; if ( node . isSelected ( ) ) { selectedNodes . remove ( node ) ; node . setSelected ( false ) ; selectionChangedDispatcher . dispatch ( selectedNodes ) ; } } public void dotPrint ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } final Properties props = new Properties ( ) ; props . setProperty ( "" , "" ) ; String dotParameters ; switch ( printMode ) { case PrintFigureOperation . FIT_WIDTH : dotParameters = "" ; break ; case PrintFigureOperation . FIT_HEIGHT : dotParameters = "" ; break ; case PrintFigureOperation . FIT_PAGE : dotParameters = "" ; break ; default : dotParameters = "" ; break ; } try { final DotWriter dotWriter = new DotWriter ( props ) ; dotWriter . setProducer ( filterChain ) ; dotWriter . setShowGraphName ( true ) ; dotWriter . write ( new File ( "" ) ) ; final Process proc = Runtime . getRuntime ( ) . exec ( "" + dotParameters + "" ) ; proc . waitFor ( ) ; proc . destroy ( ) ; log . info ( "" ) ; final MessageDialog dialog = new MessageDialog ( window . getShell ( ) , "" , Application . getInstance ( ) . getImage ( Application . APPLICATION_ICON ) , "" , MessageDialog . INFORMATION , new String [ ] { "" } , ) ; dialog . open ( ) ; } catch ( final Exception e ) { log . error ( "" , e ) ; } } public void enableBusRouting ( final boolean enabled ) { final IProgressMonitor progressMonitor = defaultProgressMonitor ; if ( busRoutingEnabled != enabled ) { if ( log . isInfoEnabled ( ) ) { log . info ( "" + enabled ) ; } busRoutingEnabled = enabled ; parameterChangedEvent . dispatch ( this ) ; progressMonitor . beginTask ( "" , ) ; renderFilteredGraph ( progressMonitor ) ; progressMonitor . done ( ) ; } } public void focusOn ( final String targetName ) { if ( displayer != null ) { displayer . jumpToNode ( targetName ) ; } } public final GraphDisplayer getDisplayer ( ) { if ( displayer == null ) { if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; } Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { displayer = window . newDisplayer ( GraphControler . this ) ; } } ) ; } return displayer ; } public Map getGraphProperties ( ) { if ( model != null ) { return model . getUserProperties ( ) ; } else { return null ; } } public IStructuredContentProvider getNodeContentProvider ( ) { return nodeContentProvider ; } public ILabelProvider getNodeLabelProvider ( ) { return nodeContentProvider ; } public final IProgressMonitor getProgressMonitor ( ) { return defaultProgressMonitor ; } public Collection < Draw2dNode > getSelection ( ) { return selectedNodes ; } public final GraphWindow getWindow ( ) { return window ; } public final boolean isBusRoutingEnabled ( ) { return busRoutingEnabled ; } public void openFile ( final File file , final Properties properties ) { final IProgressMonitor progressMonitor = defaultProgressMonitor ; if ( log . isInfoEnabled ( ) ) { log . info ( "" + file ) ; } progressMonitor . beginTask ( "" , ) ; clearFiltersOnNextLoad = true ; try { progressMonitor . subTask ( "" ) ; model . openFile ( file , properties ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } progressMonitor . worked ( ) ; filterAndRenderGraph ( progressMonitor ) ; if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; } RecentFilesManager . getInstance ( ) . addNewFile ( file , properties ) ; } catch ( final GrandException e ) { reportError ( "" , e ) ; stopControler ( ) ; } catch ( final BuildException e ) { reportError ( "" , e ) ; stopControler ( ) ; } finally { progressMonitor . done ( ) ; } } public void openNodeFile ( final Draw2dNode node ) { final AntTargetNode targetNode = ( AntTargetNode ) node . getVertex ( ) . getData ( ) ; final String buildFile = targetNode . getBuildFile ( ) ; if ( ( buildFile != null ) && ( buildFile . length ( ) > ) ) { String targetName = targetNode . getName ( ) ; if ( targetName != null ) { targetName = targetName . substring ( , targetName . length ( ) - ) ; } window . openGraphInNewDisplayer ( new File ( buildFile ) , targetName , null ) ; } } public void print ( final Printer printer ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } final PrintFigureOperation printOp = new PrintFigureOperation ( printer , figure ) ; printOp . setPrintMode ( printMode ) ; printOp . run ( "" + graph . getName ( ) ) ; } public void propertyChange ( final PropertyChangeEvent event ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + event . getProperty ( ) ) ; } if ( event . getProperty ( ) . startsWith ( PreferenceKeys . GRAPH_PREFIX ) ) { refreshGraph ( ) ; } } public void refreshGraph ( ) { final IProgressMonitor progressMonitor = defaultProgressMonitor ; if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; } progressMonitor . beginTask ( "" , ) ; clearFiltersOnNextLoad = false ; try { renderFilteredGraph ( progressMonitor ) ; if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; } } catch ( final BuildException e ) { reportError ( "" , e ) ; } finally { progressMonitor . done ( ) ; } } public void reloadGraph ( ) { reloadGraph ( null ) ; } public void reloadGraph ( final Properties properties ) { final IProgressMonitor progressMonitor = defaultProgressMonitor ; if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; } progressMonitor . beginTask ( "" , ) ; clearFiltersOnNextLoad = false ; try { model . reload ( properties ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } progressMonitor . worked ( ) ; filterAndRenderGraph ( progressMonitor ) ; if ( log . isInfoEnabled ( ) ) { log . info ( "" ) ; } RecentFilesManager . getInstance ( ) . updatePropertiesFor ( model . getLastLoadedFile ( ) , properties ) ; } catch ( final GrandException e ) { reportError ( "" , e ) ; } catch ( final BuildException e ) { reportError ( "" , e ) ; } finally { progressMonitor . done ( ) ; } } public void removeSelectionListener ( final GraphListener listener ) { graphEventManager . unSubscribe ( listener ) ; } public void selectNode ( final Draw2dNode node , final boolean addToSelection ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + node ) ; } if ( ! node . isSelected ( ) ) { if ( ! addToSelection ) { deselectAllNodes ( ) ; } selectedNodes . add ( node ) ; node . setSelected ( true ) ; final AntTargetNode antNode = ( AntTargetNode ) node . getVertex ( ) . getData ( ) ; displayer . setRichSource ( ( ( AntTargetNode ) node . getVertex ( ) . getData ( ) ) . getRichSource ( ) ) ; selectionChangedDispatcher . dispatch ( selectedNodes ) ; } } public void selectNodeByName ( final String nodeName , final boolean addToSelection ) { figure . selectNodeByName ( nodeName , addToSelection ) ; } public final void setProgressMonitor ( final IProgressMonitor progressMonitor ) { defaultProgressMonitor = progressMonitor ; } private void filterAndRenderGraph ( final IProgressMonitor progressMonitor ) { progressMonitor . subTask ( "" ) ; if ( clearFiltersOnNextLoad ) { filterChain . clearFilters ( ) ; } filterChain . filterGraph ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } progressMonitor . worked ( ) ; renderFilteredGraph ( progressMonitor ) ; } private void renderFilteredGraph ( final IProgressMonitor progressMonitor ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } progressMonitor . subTask ( "" ) ; graph = filterChain . getGraph ( ) ; nodeContentProvider . setGraph ( graph ) ; final DotGraphCreator creator = new DotGraphCreator ( graph , busRoutingEnabled ) ; final IDotGraph dotGraph = creator . getGraph ( ) ; progressMonitor . worked ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } final Dot app = new Dot ( ) ; app . layout ( dotGraph , , - ) ; progressMonitor . worked ( ) ; progressMonitor . subTask ( "" ) ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { if ( figure == null ) { figure = renderer . render ( dotGraph ) ; } else { renderer . render ( figure , dotGraph ) ; } } } ) ; figure . setSelectionManager ( this ) ; progressMonitor . worked ( ) ; String graphName = graph . getName ( ) ; if ( graphName == null ) { graphName = "" ; } getDisplayer ( ) . setGraph ( figure , graphName , model . getLastLoadedFile ( ) . getAbsolutePath ( ) ) ; } private void reportError ( final String message , final Throwable e ) { log . error ( message , e ) ; ExceptionDialog . openException ( window . getShell ( ) , message , e ) ; } private void stopControler ( ) { graphEventManager . clear ( ) ; Application . getInstance ( ) . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; window = null ; model = null ; filterChain = null ; renderer = null ; graphEventManager = null ; selectionChangedDispatcher = null ; parameterChangedEvent = null ; } public Image createImageForGraph ( ) { if ( figure == null ) { return null ; } final Display display = window . getShell ( ) . getDisplay ( ) ; final Rectangle r = figure . getBounds ( ) ; final Image image = new Image ( display , r . width , r . height ) ; display . syncExec ( new Runnable ( ) { public void run ( ) { GC gc = null ; SWTGraphics g = null ; try { gc = new GC ( image ) ; g = new SWTGraphics ( gc ) ; g . translate ( r . x * - , r . y * - ) ; g . setForegroundColor ( figure . getForegroundColor ( ) ) ; g . setBackgroundColor ( figure . getBackgroundColor ( ) ) ; g . setFont ( figure . getFont ( ) ) ; figure . paint ( g ) ; } finally { if ( g != null ) { g . dispose ( ) ; } if ( gc != null ) { gc . dispose ( ) ; } } } } ) ; return image ; } } package net . ggtools . grand . ui . graph ; import java . io . File ; import java . util . Map ; import java . util . Properties ; import net . ggtools . grand . ant . AntProject ; import net . ggtools . grand . exceptions . GrandException ; import net . ggtools . grand . graph . Graph ; import net . ggtools . grand . graph . GraphProducer ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class GraphModel implements GraphProducer { private static final Log log = LogFactory . getLog ( GraphModel . class ) ; private File lastLoadedFile ; private AntProject producer = null ; private Properties lastLoadedFileProperties ; public final Graph getGraph ( ) throws GrandException { Graph graph = null ; if ( producer != null ) { graph = producer . getGraph ( ) ; } return graph ; } public void openFile ( final File file , final Properties properties ) throws GrandException { lastLoadedFileProperties = properties ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" + file ) ; } lastLoadedFile = file ; producer = new AntProject ( file , properties ) ; } public void reload ( final Properties properties ) throws GrandException { if ( lastLoadedFile != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } if ( properties != null ) { lastLoadedFileProperties = properties ; } openFile ( lastLoadedFile , lastLoadedFileProperties ) ; } else { log . warn ( "" ) ; } } final File getLastLoadedFile ( ) { return lastLoadedFile ; } final Map getAllProperties ( ) { Map rc = null ; if ( producer != null ) { rc = producer . getAntProject ( ) . getProperties ( ) ; } return rc ; } final Map getUserProperties ( ) { return lastLoadedFileProperties ; } } package net . ggtools . grand . ui . graph ; public class GraphEvent { public final GraphModel model ; public GraphEvent ( final GraphModel model ) { this . model = model ; } } package net . ggtools . grand . ui . graph ; import java . util . Iterator ; import java . util . LinkedList ; import net . ggtools . grand . graph . Graph ; import net . ggtools . grand . graph . Node ; import net . ggtools . grand . ui . Application ; import net . ggtools . grand . ui . GrandUiPrefStore ; import net . ggtools . grand . ui . prefs . PreferenceKeys ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . jface . viewers . IColorProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; public class GraphNodeContentProvider implements IStructuredContentProvider , ILabelProvider , IColorProvider { private static final Log log = LogFactory . getLog ( GraphNodeContentProvider . class ) ; private Graph graph ; public GraphNodeContentProvider ( ) { } public void addListener ( final ILabelProviderListener listener ) { } public void dispose ( ) { graph = null ; } public Color getBackground ( final Object element ) { if ( element instanceof Node ) { final Node node = ( Node ) element ; final GrandUiPrefStore preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; if ( node . equals ( graph . getStartNode ( ) ) ) { return preferenceStore . getColor ( PreferenceKeys . NODE_PREFIX + "" ) ; } if ( node . hasAttributes ( Node . ATTR_MISSING_NODE ) ) { return preferenceStore . getColor ( PreferenceKeys . NODE_PREFIX + "" ) ; } if ( node . hasAttributes ( Node . ATTR_MAIN_NODE ) ) { return preferenceStore . getColor ( PreferenceKeys . NODE_PREFIX + "" ) ; } return preferenceStore . getColor ( PreferenceKeys . NODE_PREFIX + "" ) ; } return null ; } public Object [ ] getElements ( final Object inputElement ) { if ( graph == null ) { return null ; } final LinkedList < Node > list = new LinkedList < Node > ( ) ; for ( final Iterator < Node > iter = graph . getNodes ( ) ; iter . hasNext ( ) ; ) { list . add ( iter . next ( ) ) ; } return list . toArray ( ) ; } public Color getForeground ( final Object element ) { if ( element instanceof Node ) { final Node node = ( Node ) element ; final GrandUiPrefStore preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; if ( node . equals ( graph . getStartNode ( ) ) ) { return preferenceStore . getColor ( PreferenceKeys . NODE_PREFIX + "" ) ; } if ( node . hasAttributes ( Node . ATTR_MISSING_NODE ) ) { return preferenceStore . getColor ( PreferenceKeys . NODE_PREFIX + "" ) ; } if ( node . hasAttributes ( Node . ATTR_MAIN_NODE ) ) { return preferenceStore . getColor ( PreferenceKeys . NODE_PREFIX + "" ) ; } return preferenceStore . getColor ( PreferenceKeys . NODE_PREFIX + "" ) ; } return null ; } public Image getImage ( final Object element ) { return null ; } public String getText ( final Object element ) { if ( element == null ) { return null ; } if ( element instanceof Node ) { final Node node = ( Node ) element ; return node . getName ( ) ; } return element . toString ( ) ; } public void inputChanged ( final Viewer viewer , final Object oldInput , final Object newInput ) { } public boolean isLabelProperty ( final Object element , final String property ) { return false ; } public void removeListener ( final ILabelProviderListener listener ) { } void setGraph ( final Graph graph ) { this . graph = graph ; } } package net . ggtools . grand . ui . graph ; public interface GraphControlerProvider { GraphControler getControler ( ) ; void addControlerListener ( GraphControlerListener listener ) ; void removeControlerListener ( GraphControlerListener listener ) ; } package net . ggtools . grand . ui . graph ; public interface GraphControlerListener { void controlerRemoved ( GraphControler controler ) ; void controlerAvailable ( GraphControler controler ) ; } package net . ggtools . grand . ui . graph ; import net . ggtools . grand . ant . AntTargetNode . SourceElement ; import net . ggtools . grand . ui . graph . draw2d . Draw2dGraph ; import org . eclipse . swt . widgets . Menu ; public interface GraphDisplayer extends GraphControlerProvider { Menu getContextMenu ( ) ; void jumpToNode ( final String nodeName ) ; void setGraph ( Draw2dGraph graph , String name , String toolTip ) ; void setRichSource ( SourceElement [ ] richSource ) ; void setSourceText ( String text ) ; void zoomIn ( ) ; void zoomOut ( ) ; void zoomReset ( ) ; } package net . ggtools . grand . ui . graph ; public interface DotGraphAttributes { static final String _BOUNDS_ATTR = "" ; static final String _SHAPE_ATTR = "" ; static final String BUILD_FILE_ATTR = "" ; static final String DESCRIPTION_ATTR = "" ; static final String DRAW2DFGCOLOR_ATTR = "" ; static final String DRAW2DFILLCOLOR_ATTR = "" ; static final String DRAW2DLINEWIDTH_ATTR = "" ; static final String IF_CONDITION_ATTR = "" ; static final String LABEL_ATTR = "" ; static final String MINHEIGHT_ATTR = "" ; static final String MINWIDTH_ATTR = "" ; static final double PATH_ITERATOR_FLATNESS = ; static final String LINK_PARAMETERS_ATTR = "" ; static final String LINK_SUBANT_DIRECTORIES = "" ; static final String LINK_TASK_ATTR = "" ; static final String POSITION_ATTR = "" ; static final String SHAPE_ATTR = "" ; static final String UNLESS_CONDITION_ATTR = "" ; } package net . ggtools . grand . ui . graph ; import java . util . Collection ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import net . ggtools . grand . ant . AntLink ; import net . ggtools . grand . ant . AntTargetNode ; import net . ggtools . grand . ant . AntTaskLink ; import net . ggtools . grand . ant . SubantTaskLink ; import net . ggtools . grand . graph . Graph ; import net . ggtools . grand . graph . Link ; import net . ggtools . grand . graph . Node ; import net . ggtools . grand . graph . visit . LinkVisitor ; import net . ggtools . grand . graph . visit . NodeVisitor ; import net . ggtools . grand . ui . Application ; import net . ggtools . grand . ui . GrandUiPrefStore ; import net . ggtools . grand . ui . prefs . PreferenceKeys ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . draw2d . FigureUtilities ; import org . eclipse . draw2d . geometry . Dimension ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . widgets . Display ; import sf . jzgraph . IDotGraph ; import sf . jzgraph . IEdge ; import sf . jzgraph . IGraph ; import sf . jzgraph . IVertex ; import sf . jzgraph . dot . impl . DotGraph ; public class DotGraphCreator implements NodeVisitor , LinkVisitor , DotGraphAttributes { private static final Log log = LogFactory . getLog ( GraphControler . class ) ; private String currentLinkName ; private final IDotGraph dotGraph ; private Graph graph ; private final Map < String , IVertex > nameDimensions ; private final Node startNode ; private final boolean useBusRouting ; private final Map < String , IVertex > vertexLUT ; public DotGraphCreator ( final Graph graph , final boolean useBusRouting ) { this . graph = graph ; this . useBusRouting = useBusRouting ; nameDimensions = new HashMap < String , IVertex > ( ) ; dotGraph = new DotGraph ( IGraph . GRAPH , graph . getName ( ) ) ; vertexLUT = new HashMap < String , IVertex > ( ) ; startNode = graph . getStartNode ( ) ; } public IDotGraph getGraph ( ) { if ( startNode != null ) { startNode . accept ( this ) ; } for ( final Iterator iter = graph . getNodes ( ) ; iter . hasNext ( ) ; ) { final Node node = ( Node ) iter . next ( ) ; if ( "" . equals ( node . getName ( ) ) || ( node == startNode ) ) { continue ; } node . accept ( this ) ; } Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { final Font systemFont = Application . getInstance ( ) . getFont ( Application . NODE_FONT ) ; for ( final Iterator iter = nameDimensions . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final Map . Entry entry = ( Map . Entry ) iter . next ( ) ; final String name = ( String ) entry . getKey ( ) ; final IVertex vertex = ( IVertex ) entry . getValue ( ) ; final Dimension dim = FigureUtilities . getTextExtents ( name , systemFont ) ; vertex . setAttr ( MINWIDTH_ATTR , Math . max ( dim . width , ) ) ; vertex . setAttr ( MINHEIGHT_ATTR , Math . max ( dim . height , ) ) ; } } } ) ; for ( final Iterator iter = graph . getNodes ( ) ; iter . hasNext ( ) ; ) { final Node node = ( Node ) iter . next ( ) ; final Collection deps = node . getLinks ( ) ; int index = ; final int numDeps = deps . size ( ) ; for ( final Iterator iterator = deps . iterator ( ) ; iterator . hasNext ( ) ; ) { final Link link = ( Link ) iterator . next ( ) ; currentLinkName = "" ; if ( numDeps > ) { currentLinkName += index ++ ; } link . accept ( this ) ; } } return dotGraph ; } public void visitLink ( final AntLink link ) { addLink ( link ) ; } public void visitLink ( final AntTaskLink link ) { final IEdge edge = addLink ( link ) ; edge . setAttr ( LINK_TASK_ATTR , link . getTaskName ( ) ) ; edge . setAttr ( LINK_PARAMETERS_ATTR , link . getParameterMap ( ) ) ; } public void visitLink ( final Link link ) { addLink ( link ) ; } public void visitLink ( final SubantTaskLink link ) { final IEdge edge = addLink ( link ) ; edge . setAttr ( LINK_TASK_ATTR , link . getTaskName ( ) ) ; edge . setAttr ( LINK_PARAMETERS_ATTR , link . getParameterMap ( ) ) ; edge . setAttr ( LINK_SUBANT_DIRECTORIES , link . getDirectories ( ) ) ; final GrandUiPrefStore preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; edge . setAttr ( DRAW2DFGCOLOR_ATTR , preferenceStore . getColor ( PreferenceKeys . LINK_SUBANT_COLOR ) ) ; edge . setAttr ( DRAW2DLINEWIDTH_ATTR , preferenceStore . getInt ( PreferenceKeys . LINK_SUBANT_LINEWIDTH ) ) ; } public void visitNode ( final AntTargetNode node ) { final IVertex vertex = addNode ( node ) ; final String ifCondition = node . getIfCondition ( ) ; if ( ifCondition != null ) { vertex . setAttr ( IF_CONDITION_ATTR , ifCondition ) ; } final String unlessCondition = node . getUnlessCondition ( ) ; if ( unlessCondition != null ) { vertex . setAttr ( UNLESS_CONDITION_ATTR , unlessCondition ) ; } final String buildFile = node . getBuildFile ( ) ; if ( buildFile != null ) { vertex . setAttr ( BUILD_FILE_ATTR , buildFile ) ; } } public void visitNode ( final Node node ) { addNode ( node ) ; } private IEdge addLink ( final Link link ) { final IEdge edge = dotGraph . newEdge ( vertexLUT . get ( link . getStartNode ( ) . getName ( ) ) , vertexLUT . get ( link . getEndNode ( ) . getName ( ) ) , currentLinkName , link ) ; final GrandUiPrefStore preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; if ( link . hasAttributes ( Link . ATTR_WEAK_LINK ) ) { edge . setAttr ( DRAW2DFGCOLOR_ATTR , preferenceStore . getColor ( PreferenceKeys . LINK_WEAK_COLOR ) ) ; edge . setAttr ( DRAW2DLINEWIDTH_ATTR , preferenceStore . getInt ( PreferenceKeys . LINK_WEAK_LINEWIDTH ) ) ; } else { edge . setAttr ( DRAW2DFGCOLOR_ATTR , preferenceStore . getColor ( PreferenceKeys . LINK_DEFAULT_COLOR ) ) ; edge . setAttr ( DRAW2DLINEWIDTH_ATTR , preferenceStore . getInt ( PreferenceKeys . LINK_DEFAULT_LINEWIDTH ) ) ; } return edge ; } private final IVertex addNode ( final Node node ) { final String name = node . getName ( ) ; final IVertex vertex = dotGraph . newVertex ( name , node ) ; if ( node . equals ( startNode ) ) { setVertexPreferences ( vertex , "" ) ; } else if ( node . hasAttributes ( Node . ATTR_MAIN_NODE ) ) { setVertexPreferences ( vertex , "" ) ; } else if ( node . hasAttributes ( Node . ATTR_MISSING_NODE ) ) { setVertexPreferences ( vertex , "" ) ; } else { setVertexPreferences ( vertex , "" ) ; } if ( node . getDescription ( ) != null ) { vertex . setAttr ( DESCRIPTION_ATTR , node . getDescription ( ) ) ; } if ( useBusRouting ) { final GrandUiPrefStore preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; vertex . setAttr ( "" , preferenceStore . getInt ( PreferenceKeys . GRAPH_BUS_IN_THRESHOLD ) ) ; vertex . setAttr ( "" , preferenceStore . getInt ( PreferenceKeys . GRAPH_BUS_OUT_THRESHOLD ) ) ; } vertexLUT . put ( name , vertex ) ; nameDimensions . put ( name , vertex ) ; return vertex ; } private void setVertexPreferences ( final IVertex vertex , final String nodeType ) { final GrandUiPrefStore preferenceStore = Application . getInstance ( ) . getPreferenceStore ( ) ; final String keyPrefix = PreferenceKeys . NODE_PREFIX + nodeType ; vertex . setAttr ( SHAPE_ATTR , preferenceStore . getString ( keyPrefix + "" ) ) ; vertex . setAttr ( DRAW2DFGCOLOR_ATTR , preferenceStore . getColor ( keyPrefix + "" ) ) ; vertex . setAttr ( DRAW2DFILLCOLOR_ATTR , preferenceStore . getColor ( keyPrefix + "" ) ) ; vertex . setAttr ( DRAW2DLINEWIDTH_ATTR , preferenceStore . getInt ( keyPrefix + "" ) ) ; } } package net . ggtools . grand . ui . graph ; public interface GraphModelListener { void newGraphLoaded ( GraphEvent event ) ; } package net . ggtools . grand . ui . graph ; import java . util . List ; import net . ggtools . grand . exceptions . GrandException ; import net . ggtools . grand . filters . FilterChain ; import net . ggtools . grand . filters . GraphFilter ; import net . ggtools . grand . graph . Graph ; import net . ggtools . grand . graph . GraphProducer ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public class FilterChainModel implements GraphProducer { private static final Log log = LogFactory . getLog ( FilterChainModel . class ) ; private final FilterChain filterChain ; private Graph graph = null ; private GraphModel graphModel ; public FilterChainModel ( final GraphModel graphModel ) { filterChain = new FilterChain ( ) ; this . graphModel = graphModel ; filterChain . setProducer ( graphModel ) ; } public void addFilterFirst ( final GraphFilter newFilter ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + newFilter ) ; } filterChain . addFilterFirst ( newFilter ) ; filterGraph ( ) ; } public void addFilterLast ( final GraphFilter newFilter ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + newFilter ) ; } filterChain . addFilterLast ( newFilter ) ; filterGraph ( ) ; } public void clearFilters ( ) { if ( filterChain . getFilterList ( ) . size ( ) > ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } filterChain . clearFilters ( ) ; filterGraph ( ) ; } else if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } } public List getFilterList ( ) { return filterChain . getFilterList ( ) ; } public final Graph getGraph ( ) { return graph ; } public void filterGraph ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + filterChain . getFilterList ( ) . size ( ) ) ; } try { graph = filterChain . getGraph ( ) ; } catch ( final GrandException e ) { log . error ( "" , e ) ; graph = null ; } } public void setProducer ( final GraphProducer producer ) { filterChain . setProducer ( producer ) ; } } package net . ggtools . grand . ui . graph . draw2d ; import net . ggtools . grand . ui . Application ; import net . ggtools . grand . ui . graph . DotGraphAttributes ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . draw2d . Label ; import org . eclipse . draw2d . text . BlockFlow ; import org . eclipse . draw2d . text . FlowPage ; import org . eclipse . draw2d . text . InlineFlow ; import org . eclipse . draw2d . text . TextFlow ; import sf . jzgraph . IVertex ; public class NodeTooltip extends AbstractGraphTooltip implements DotGraphAttributes { private static final Log log = LogFactory . getLog ( NodeTooltip . class ) ; private final IVertex vertex ; public NodeTooltip ( final IVertex vertex ) { super ( ) ; this . vertex = vertex ; createContents ( ) ; } @ Override protected void createContents ( ) { final Label name = new Label ( vertex . getName ( ) , Application . getInstance ( ) . getImage ( Application . NODE_ICON ) ) ; name . setFont ( Application . getInstance ( ) . getBoldFont ( Application . TOOLTIP_FONT ) ) ; add ( name ) ; FlowPage page = null ; if ( vertex . hasAttr ( BUILD_FILE_ATTR ) ) { final Label buildFile = new Label ( vertex . getAttrAsString ( BUILD_FILE_ATTR ) ) ; buildFile . setFont ( Application . getInstance ( ) . getFont ( Application . TOOLTIP_MONOSPACE_FONT ) ) ; buildFile . setBorder ( new SectionBorder ( ) ) ; add ( buildFile ) ; } if ( vertex . hasAttr ( IF_CONDITION_ATTR ) ) { if ( page == null ) { page = createFlowPage ( ) ; } final BlockFlow blockFlow = new BlockFlow ( ) ; blockFlow . add ( new TextFlow ( "" ) ) ; final InlineFlow inline = new InlineFlow ( ) ; final TextFlow textFlow = new TextFlow ( vertex . getAttrAsString ( IF_CONDITION_ATTR ) ) ; inline . add ( textFlow ) ; textFlow . setFont ( Application . getInstance ( ) . getFont ( Application . TOOLTIP_MONOSPACE_FONT ) ) ; blockFlow . add ( inline ) ; blockFlow . setBorder ( new SectionBorder ( ) ) ; page . add ( blockFlow ) ; } if ( vertex . hasAttr ( UNLESS_CONDITION_ATTR ) ) { if ( page == null ) { page = createFlowPage ( ) ; } final BlockFlow blockFlow = new BlockFlow ( ) ; blockFlow . add ( new TextFlow ( "" ) ) ; final InlineFlow inline = new InlineFlow ( ) ; final TextFlow textFlow = new TextFlow ( vertex . getAttrAsString ( UNLESS_CONDITION_ATTR ) ) ; inline . add ( textFlow ) ; textFlow . setFont ( Application . getInstance ( ) . getFont ( Application . TOOLTIP_MONOSPACE_FONT ) ) ; blockFlow . add ( inline ) ; blockFlow . setBorder ( new SectionBorder ( ) ) ; page . add ( blockFlow ) ; } if ( vertex . hasAttr ( DESCRIPTION_ATTR ) ) { if ( page == null ) { page = createFlowPage ( ) ; } final BlockFlow blockFlow = new BlockFlow ( ) ; final TextFlow textFlow = new TextFlow ( vertex . getAttrAsString ( DESCRIPTION_ATTR ) ) ; textFlow . setFont ( Application . getInstance ( ) . getItalicFont ( Application . TOOLTIP_FONT ) ) ; blockFlow . add ( textFlow ) ; blockFlow . setBorder ( new SectionBorder ( ) ) ; page . add ( blockFlow ) ; } } } package net . ggtools . grand . ui . graph . draw2d ; import org . eclipse . draw2d . text . FlowPage ; import org . eclipse . draw2d . text . LineBox ; import org . eclipse . draw2d . text . PageFlowLayout ; public class ConstrainedPageFlowLayout extends PageFlowLayout { private int maxFlowWidth = - ; public ConstrainedPageFlowLayout ( final FlowPage page ) { super ( page ) ; } public int getMaxFlowWidth ( ) { return maxFlowWidth ; } public void setMaxFlowWidth ( final int maxFlowWidth ) { this . maxFlowWidth = maxFlowWidth ; invalidate ( ) ; } @ Override protected void setupLine ( final LineBox line ) { super . setupLine ( line ) ; final int lineWidth = line . getRecommendedWidth ( ) ; if ( ( maxFlowWidth > ) && ( ( lineWidth > maxFlowWidth ) || ( lineWidth == - ) ) ) { line . setRecommendedWidth ( maxFlowWidth ) ; } } } package net . ggtools . grand . ui . graph . draw2d ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import net . ggtools . grand . ui . Application ; import net . ggtools . grand . ui . graph . GraphControler ; import net . ggtools . grand . ui . graph . GraphListener ; import net . ggtools . grand . ui . graph . SelectionManager ; import net . ggtools . grand . ui . widgets . CanvasScroller ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . draw2d . Cursors ; import org . eclipse . draw2d . Graphics ; import org . eclipse . draw2d . InputEvent ; import org . eclipse . draw2d . MouseEvent ; import org . eclipse . draw2d . MouseListener ; import org . eclipse . draw2d . Panel ; import org . eclipse . draw2d . ScaledGraphics ; import org . eclipse . draw2d . XYLayout ; import org . eclipse . draw2d . geometry . Dimension ; import org . eclipse . draw2d . geometry . Rectangle ; import org . eclipse . draw2d . geometry . Translatable ; import sf . jzgraph . IVertex ; public class Draw2dGraph extends Panel implements SelectionManager { private final class GraphMouseListener extends MouseListener . Stub { @ Override public void mousePressed ( final MouseEvent me ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + me . button ) ; } switch ( me . button ) { case ( ) : deselectAllNodes ( ) ; me . consume ( ) ; case ( ) : if ( scroller != null ) { scroller . enterDragMode ( ) ; } break ; case ( ) : if ( graphControler != null ) { graphControler . getDisplayer ( ) . getContextMenu ( ) . setVisible ( true ) ; } break ; } } @ Override public void mouseReleased ( final MouseEvent me ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + me . button ) ; } switch ( me . button ) { case ( ) : case ( ) : if ( scroller != null ) { scroller . leaveDragMode ( ) ; } break ; } } } private final class NodeMouseListener extends MouseListener . Stub { private final Log log = LogFactory . getLog ( NodeMouseListener . class ) ; private final Draw2dNode node ; private NodeMouseListener ( final Draw2dNode node ) { super ( ) ; this . node = node ; } @ Override public void mouseDoubleClicked ( final MouseEvent me ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + me . button ) ; } switch ( me . button ) { case ( ) : { final boolean addToSelection ; if ( ( me . getState ( ) & InputEvent . CONTROL ) == ) { addToSelection = false ; } else { addToSelection = true ; } selectNode ( node , addToSelection ) ; graphControler . openNodeFile ( node ) ; } } me . consume ( ) ; } @ Override public void mousePressed ( final MouseEvent me ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + me . button ) ; } switch ( me . button ) { case ( ) : { final boolean addToSelection ; if ( ( me . getState ( ) & InputEvent . CONTROL ) == ) { addToSelection = false ; } else { addToSelection = true ; } toggleSelection ( node , addToSelection ) ; me . consume ( ) ; break ; } case ( ) : { if ( ! node . isSelected ( ) ) { selectNode ( node , false ) ; } if ( graphControler != null ) { ( graphControler ) . getDisplayer ( ) . getContextMenu ( ) . setVisible ( true ) ; } break ; } } } @ Override public void mouseReleased ( final MouseEvent me ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + me . button ) ; } switch ( me . button ) { case ( ) : case ( ) : if ( scroller != null ) { scroller . leaveDragMode ( ) ; } break ; } } } private static final Log log = LogFactory . getLog ( Draw2dGraph . class ) ; private GraphControler graphControler ; private GraphMouseListener graphMouseListener ; private final Map < String , Draw2dNode > nodeIndex = new HashMap < String , Draw2dNode > ( ) ; private CanvasScroller scroller ; private float zoom ; public Draw2dGraph ( ) { super ( ) ; scroller = null ; setLayoutManager ( new XYLayout ( ) ) ; setZoom ( ) ; } public void addListener ( final GraphListener listener ) { if ( graphControler != null ) { graphControler . addListener ( listener ) ; } } @ Override public void addNotify ( ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" ) ; } super . addNotify ( ) ; graphMouseListener = new GraphMouseListener ( ) ; addMouseListener ( graphMouseListener ) ; setFocusTraversable ( true ) ; } public Draw2dNode createNode ( final IVertex vertex ) { final Draw2dNode node = new Draw2dNode ( this , vertex ) ; add ( node , node . getBounds ( ) ) ; node . setFont ( Application . getInstance ( ) . getFont ( Application . NODE_FONT ) ) ; node . addMouseListener ( new NodeMouseListener ( node ) ) ; node . setCursor ( Cursors . HAND ) ; nodeIndex . put ( node . getName ( ) , node ) ; return node ; } public void deselectAllNodes ( ) { if ( graphControler != null ) { graphControler . deselectAllNodes ( ) ; } } public void deselectNode ( final Draw2dNode node ) { if ( graphControler != null ) { graphControler . deselectNode ( node ) ; } } public Rectangle getBoundsForNode ( final String name ) { final Draw2dNode node = nodeIndex . get ( name ) ; return node == null ? null : node . getBounds ( ) ; } @ Override public Rectangle getClientArea ( final Rectangle rect ) { super . getClientArea ( rect ) ; rect . width /= zoom ; rect . height /= zoom ; return rect ; } public final SelectionManager getControler ( ) { return graphControler ; } @ Override public Dimension getMinimumSize ( final int wHint , final int hHint ) { final Dimension d = super . getMinimumSize ( wHint , hHint ) ; int w = getInsets ( ) . getWidth ( ) ; int h = getInsets ( ) . getHeight ( ) ; return d . getExpanded ( - w , - h ) . scale ( zoom ) . expand ( w , h ) ; } @ Override public Dimension getPreferredSize ( final int wHint , final int hHint ) { final Dimension d = super . getPreferredSize ( wHint , hHint ) ; int w = getInsets ( ) . getWidth ( ) ; int h = getInsets ( ) . getHeight ( ) ; return d . getExpanded ( - w , - h ) . scale ( zoom ) . expand ( w , h ) ; } public final CanvasScroller getScroller ( ) { return scroller ; } public Collection < Draw2dNode > getSelection ( ) { if ( graphControler != null ) { return graphControler . getSelection ( ) ; } return null ; } public final float getZoom ( ) { return zoom ; } @ Override public void removeNotify ( ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" ) ; } super . removeNotify ( ) ; if ( graphMouseListener != null ) { removeMouseListener ( graphMouseListener ) ; } setFocusTraversable ( false ) ; } public void removeSelectionListener ( final GraphListener listener ) { if ( graphControler != null ) { graphControler . removeSelectionListener ( listener ) ; } } public void selectNode ( final Draw2dNode node , final boolean addToSelection ) { if ( graphControler != null ) { graphControler . selectNode ( node , addToSelection ) ; } } public void selectNodeByName ( final String nodeName , final boolean addToSelection ) { final Draw2dNode node = nodeIndex . get ( nodeName ) ; if ( node != null ) { selectNode ( node , addToSelection ) ; } } public final void setScroller ( final CanvasScroller scroller ) { this . scroller = scroller ; } public final void setSelectionManager ( final GraphControler graphControler ) { this . graphControler = graphControler ; } public void setZoom ( final float zoom ) { this . zoom = zoom ; revalidate ( ) ; repaint ( ) ; } @ Override public void translateFromParent ( final Translatable t ) { super . translateFromParent ( t ) ; t . performScale ( / zoom ) ; } @ Override public void translateToParent ( final Translatable t ) { t . performScale ( zoom ) ; super . translateToParent ( t ) ; } private void toggleSelection ( final Draw2dNode node , final boolean addToSelection ) { if ( node . isSelected ( ) ) { deselectNode ( node ) ; } else { selectNode ( node , addToSelection ) ; } } @ Override protected void paintClientArea ( final Graphics graphics ) { if ( getChildren ( ) . isEmpty ( ) ) { return ; } boolean optimizeClip = ( getBorder ( ) == null ) || getBorder ( ) . isOpaque ( ) ; final ScaledGraphics g = new ScaledGraphics ( graphics ) ; if ( ! optimizeClip ) { g . clipRect ( getBounds ( ) . getCropped ( getInsets ( ) ) ) ; } g . translate ( getBounds ( ) . x + getInsets ( ) . left , getBounds ( ) . y + getInsets ( ) . top ) ; g . scale ( zoom ) ; g . pushState ( ) ; paintChildren ( g ) ; g . popState ( ) ; g . dispose ( ) ; graphics . restoreState ( ) ; } @ Override protected boolean useLocalCoordinates ( ) { return true ; } } package net . ggtools . grand . ui . graph . draw2d ; import org . eclipse . draw2d . ConnectionAnchorBase ; import org . eclipse . draw2d . IFigure ; import org . eclipse . draw2d . geometry . Point ; public class XYRelativeAnchor extends ConnectionAnchorBase { private IFigure owner ; private Point location ; public XYRelativeAnchor ( final IFigure owner , final Point location ) { this . owner = owner ; this . location = location ; } public Point getLocation ( final Point reference ) { final Point result = location . getCopy ( ) ; getOwner ( ) . translateToAbsolute ( result ) ; return result ; } public IFigure getOwner ( ) { return owner ; } public Point getReferencePoint ( ) { return location ; } public void setLocation ( final Point p ) { location . setLocation ( p ) ; fireAnchorMoved ( ) ; } } package net . ggtools . grand . ui . graph . draw2d ; import java . awt . geom . AffineTransform ; import java . awt . geom . FlatteningPathIterator ; import java . awt . geom . PathIterator ; import java . awt . geom . Rectangle2D ; import net . ggtools . grand . graph . Node ; import net . ggtools . grand . ui . graph . DotGraphAttributes ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . draw2d . BorderLayout ; import org . eclipse . draw2d . FigureUtilities ; import org . eclipse . draw2d . Label ; import org . eclipse . draw2d . Polygon ; import org . eclipse . draw2d . geometry . Point ; import org . eclipse . swt . graphics . Color ; import sf . jzgraph . IVertex ; import sf . jzgraph . impl . GraphShape ; public class Draw2dNode extends Polygon implements DotGraphAttributes { private static final Log log = LogFactory . getLog ( Draw2dNode . class ) ; private Draw2dGraph graph ; private Label label ; private String name ; private Color nodeBgColor ; private Color nodeFgColor ; private boolean selected ; private Color selectedBgColor ; private IVertex vertex ; public Draw2dNode ( final Draw2dGraph graph , final IVertex vertex ) { super ( ) ; this . vertex = vertex ; selected = false ; this . graph = graph ; nodeFgColor = ( Color ) vertex . getAttr ( DRAW2DFGCOLOR_ATTR ) ; nodeBgColor = ( Color ) vertex . getAttr ( DRAW2DFILLCOLOR_ATTR ) ; selectedBgColor = FigureUtilities . darker ( nodeBgColor ) ; int x , y , width , height ; final Rectangle2D rect = ( Rectangle2D ) vertex . getAttr ( _BOUNDS_ATTR ) ; x = ( int ) rect . getX ( ) ; y = ( int ) rect . getY ( ) ; width = ( int ) rect . getWidth ( ) ; height = ( int ) rect . getHeight ( ) ; setForegroundColor ( nodeFgColor ) ; setBackgroundColor ( nodeBgColor ) ; setLineWidth ( vertex . getAttrInt ( DRAW2DLINEWIDTH_ATTR ) ) ; setOpaque ( true ) ; final GraphShape shape = ( GraphShape ) vertex . getAttr ( _SHAPE_ATTR ) ; final float [ ] coords = new float [ ] ; for ( final PathIterator ite = new FlatteningPathIterator ( shape . getPathIterator ( new AffineTransform ( ) ) , PATH_ITERATOR_FLATNESS ) ; ! ite . isDone ( ) ; ite . next ( ) ) { final int segType = ite . currentSegment ( coords ) ; switch ( segType ) { case PathIterator . SEG_MOVETO : addPoint ( new Point ( coords [ ] , coords [ ] ) ) ; break ; case PathIterator . SEG_LINETO : addPoint ( new Point ( coords [ ] , coords [ ] ) ) ; break ; case PathIterator . SEG_CLOSE : break ; default : log . error ( "" + segType ) ; break ; } } label = new Label ( ) ; name = vertex . getAttrString ( LABEL_ATTR ) ; label . setText ( name ) ; label . setForegroundColor ( nodeFgColor ) ; setLayoutManager ( new BorderLayout ( ) ) ; add ( label , BorderLayout . CENTER ) ; } public final String getName ( ) { return name ; } public Node getNode ( ) { return ( Node ) vertex . getData ( ) ; } public final IVertex getVertex ( ) { return vertex ; } public final boolean isSelected ( ) { return selected ; } public final void setSelected ( final boolean selected ) { if ( selected != this . selected ) { this . selected = selected ; if ( selected ) { setBackgroundColor ( selectedBgColor ) ; } else { setBackgroundColor ( nodeBgColor ) ; } repaint ( ) ; } } @ Override public String toString ( ) { return this . getClass ( ) . getName ( ) + "" + vertex . getName ( ) ; } } package net . ggtools . grand . ui . graph . draw2d ; import java . awt . geom . AffineTransform ; import java . awt . geom . FlatteningPathIterator ; import java . awt . geom . PathIterator ; import java . util . ArrayList ; import java . util . Iterator ; import net . ggtools . grand . ui . Application ; import net . ggtools . grand . ui . graph . DotGraphAttributes ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . draw2d . AbsoluteBendpoint ; import org . eclipse . draw2d . BendpointConnectionRouter ; import org . eclipse . draw2d . ColorConstants ; import org . eclipse . draw2d . ConnectionLocator ; import org . eclipse . draw2d . Cursors ; import org . eclipse . draw2d . IFigure ; import org . eclipse . draw2d . Label ; import org . eclipse . draw2d . LineBorder ; import org . eclipse . draw2d . MarginBorder ; import org . eclipse . draw2d . MidpointLocator ; import org . eclipse . draw2d . PolygonDecoration ; import org . eclipse . draw2d . PolylineConnection ; import org . eclipse . draw2d . PositionConstants ; import org . eclipse . draw2d . geometry . Dimension ; import org . eclipse . draw2d . geometry . Point ; import org . eclipse . draw2d . geometry . Rectangle ; import org . eclipse . swt . graphics . Color ; import sf . jzgraph . IDotGraph ; import sf . jzgraph . IEdge ; import sf . jzgraph . IVertex ; import sf . jzgraph . dot . impl . DotRoute ; public class Draw2dGraphRenderer implements DotGraphAttributes { private static final Log log = LogFactory . getLog ( Draw2dGraphRenderer . class ) ; public Draw2dGraph render ( final IDotGraph dotGraph ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } final Draw2dGraph contents = new Draw2dGraph ( ) ; contents . setBorder ( new MarginBorder ( , , , ) ) ; return createGraph ( dotGraph , contents ) ; } public Draw2dGraph render ( final Draw2dGraph contents , final IDotGraph dotGraph ) { contents . removeAll ( ) ; return createGraph ( dotGraph , contents ) ; } private Draw2dGraph createGraph ( final IDotGraph dotGraph , final Draw2dGraph contents ) { for ( final Iterator iter = dotGraph . allVertices ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final IVertex node = ( IVertex ) iter . next ( ) ; buildNodeFigure ( contents , node ) ; } for ( final Iterator iter = dotGraph . edgeIterator ( ) ; iter . hasNext ( ) ; ) { final IEdge edge = ( IEdge ) iter . next ( ) ; buildEdgeFigure ( contents , edge ) ; } return contents ; } private final void addBendPoint ( final float [ ] coords , final ArrayList < AbsoluteBendpoint > bends , final Point min , final Point max ) { final int x = ( int ) coords [ ] ; final int y = ( int ) coords [ ] ; bends . add ( new AbsoluteBendpoint ( x , y ) ) ; if ( x < min . x ) { min . x = x ; } if ( x > max . x ) { max . x = x ; } if ( y < min . y ) { min . y = y ; } if ( y > max . y ) { max . y = y ; } } private PolylineConnection addConnectionFromRoute ( final IFigure contents , final String name , final DotRoute route ) { final float [ ] coords = new float [ ] ; final ArrayList < AbsoluteBendpoint > bends = new ArrayList < AbsoluteBendpoint > ( ) ; boolean isFirstPoint = true ; final Point min = new Point ( Integer . MAX_VALUE , Integer . MAX_VALUE ) ; final Point max = new Point ( Integer . MIN_VALUE , Integer . MIN_VALUE ) ; for ( final PathIterator ite = new FlatteningPathIterator ( route . getPath ( ) . getPathIterator ( new AffineTransform ( ) ) , PATH_ITERATOR_FLATNESS ) ; ! ite . isDone ( ) ; ite . next ( ) ) { final int segType = ite . currentSegment ( coords ) ; switch ( segType ) { case PathIterator . SEG_MOVETO : if ( isFirstPoint ) { addBendPoint ( coords , bends , min , max ) ; } else { log . error ( "" ) ; } break ; case PathIterator . SEG_LINETO : addBendPoint ( coords , bends , min , max ) ; break ; default : log . error ( "" + segType ) ; break ; } isFirstPoint = false ; } final Rectangle bounds = new Rectangle ( min , max ) ; final PolylineConnection conn = new PolylineConnection ( ) ; final Point sourcePoint = bends . remove ( ) ; final Point targetPoint ; if ( route . getEndPt ( ) != null ) { targetPoint = new Point ( route . getEndPt ( ) . getX ( ) , route . getEndPt ( ) . getY ( ) ) ; } else { targetPoint = bends . remove ( bends . size ( ) - ) ; } conn . setSourceAnchor ( new XYRelativeAnchor ( conn , sourcePoint ) ) ; conn . setTargetAnchor ( new XYRelativeAnchor ( conn , targetPoint ) ) ; if ( bends . isEmpty ( ) ) { conn . setConnectionRouter ( null ) ; } else { conn . setConnectionRouter ( new BendpointConnectionRouter ( ) ) ; conn . setRoutingConstraint ( bends ) ; } if ( name != null ) { final Label label = new Label ( name ) ; label . setOpaque ( true ) ; label . setBackgroundColor ( ColorConstants . buttonLightest ) ; label . setBorder ( new LineBorder ( ) ) ; label . setFont ( Application . getInstance ( ) . getFont ( Application . LINK_FONT ) ) ; final ConnectionLocator locator = new MidpointLocator ( conn , bends . size ( ) / ) ; locator . setRelativePosition ( PositionConstants . CENTER ) ; final Dimension labelSize = label . getPreferredSize ( ) ; bounds . expand ( labelSize . width , labelSize . height ) ; conn . add ( label , locator ) ; } contents . add ( conn , bounds ) ; return conn ; } private void buildEdgeFigure ( final IFigure contents , final IEdge edge ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "" + edge . getTail ( ) . getName ( ) + "" + edge . getHead ( ) . getName ( ) ) ; } final DotRoute route = ( DotRoute ) edge . getAttr ( POSITION_ATTR ) ; String name = edge . getName ( ) ; if ( "" . equals ( name ) ) { name = null ; } final PolylineConnection conn = addConnectionFromRoute ( contents , name , route ) ; if ( edge . getAttr ( DRAW2DFGCOLOR_ATTR ) != null ) { conn . setForegroundColor ( ( Color ) edge . getAttr ( DRAW2DFGCOLOR_ATTR ) ) ; } if ( edge . getAttr ( DRAW2DLINEWIDTH_ATTR ) != null ) { conn . setLineWidth ( edge . getAttrInt ( DRAW2DLINEWIDTH_ATTR ) ) ; } final PolygonDecoration dec = new PolygonDecoration ( ) ; conn . setTargetDecoration ( dec ) ; conn . setToolTip ( new LinkTooltip ( edge ) ) ; conn . setCursor ( Cursors . HAND ) ; } private void buildNodeFigure ( final Draw2dGraph contents , final IVertex node ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + node . getName ( ) ) ; } final Draw2dNode polygon = contents . createNode ( node ) ; polygon . setToolTip ( new NodeTooltip ( node ) ) ; if ( node . hasAttr ( "" ) ) { final PolylineConnection conn = createBusConnexion ( contents , node , ColorConstants . red , "" , "" ) ; conn . setLineWidth ( ) ; } if ( node . hasAttr ( "" ) ) { final PolylineConnection conn = createBusConnexion ( contents , node , ColorConstants . blue , "" , "" ) ; conn . setLineWidth ( ) ; } if ( node . hasAttr ( "" ) ) { final PolylineConnection conn = createBusConnexion ( contents , node , ColorConstants . blue , "" , "" ) ; } if ( node . hasAttr ( "" ) ) { final PolylineConnection conn = createBusConnexion ( contents , node , ColorConstants . red , "" , "" ) ; final PolygonDecoration dec = new PolygonDecoration ( ) ; conn . setTargetDecoration ( dec ) ; } } private PolylineConnection createBusConnexion ( final Draw2dGraph contents , final IVertex node , final Color color , final String busId , final String busLabel ) { final PolylineConnection conn = addConnectionFromRoute ( contents , null , ( DotRoute ) node . getAttr ( busId ) ) ; conn . setForegroundColor ( color ) ; contents . add ( conn , conn . getBounds ( ) ) ; final Label label = new Label ( busLabel + "" + node . getName ( ) , Application . getInstance ( ) . getImage ( Application . LINK_ICON ) ) ; label . setFont ( Application . getInstance ( ) . getBoldFont ( Application . TOOLTIP_FONT ) ) ; conn . setToolTip ( label ) ; return conn ; } } package net . ggtools . grand . ui . graph . draw2d ; import java . io . File ; import java . util . Collection ; import java . util . Iterator ; import java . util . Map ; import net . ggtools . grand . ui . Application ; import net . ggtools . grand . ui . graph . DotGraphAttributes ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; import org . eclipse . draw2d . FigureUtilities ; import org . eclipse . draw2d . Label ; import org . eclipse . draw2d . geometry . Dimension ; import org . eclipse . draw2d . text . BlockFlow ; import org . eclipse . draw2d . text . FlowPage ; import org . eclipse . draw2d . text . InlineFlow ; import org . eclipse . draw2d . text . TextFlow ; import org . eclipse . swt . graphics . Font ; import sf . jzgraph . IEdge ; public class LinkTooltip extends AbstractGraphTooltip implements DotGraphAttributes { private static final String ELLIPSIS = "" ; private static final Log log = LogFactory . getLog ( LinkTooltip . class ) ; private final IEdge edge ; public LinkTooltip ( final IEdge edge ) { super ( ) ; this . edge = edge ; createContents ( ) ; } @ Override protected void createContents ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } final Label type ; if ( edge . hasAttr ( LINK_TASK_ATTR ) ) { type = new Label ( edge . getAttrAsString ( LINK_TASK_ATTR ) , Application . getInstance ( ) . getImage ( Application . LINK_ICON ) ) ; } else { type = new Label ( "" , Application . getInstance ( ) . getImage ( Application . LINK_ICON ) ) ; } type . setFont ( Application . getInstance ( ) . getBoldFont ( Application . TOOLTIP_FONT ) ) ; add ( type ) ; final Font italicMonospaceFont = Application . getInstance ( ) . getItalicFont ( Application . TOOLTIP_MONOSPACE_FONT ) ; final Font monospaceFont = Application . getInstance ( ) . getFont ( Application . TOOLTIP_MONOSPACE_FONT ) ; final FlowPage page = createFlowPage ( ) ; BlockFlow blockFlow = new BlockFlow ( ) ; TextFlow textFlow = new TextFlow ( "" ) ; blockFlow . add ( textFlow ) ; InlineFlow inline = new InlineFlow ( ) ; textFlow = new TextFlow ( edge . getTail ( ) . getName ( ) ) ; textFlow . setFont ( italicMonospaceFont ) ; inline . add ( textFlow ) ; blockFlow . add ( inline ) ; blockFlow . setBorder ( new SectionBorder ( ) ) ; page . add ( blockFlow ) ; blockFlow = new BlockFlow ( ) ; textFlow = new TextFlow ( "" ) ; blockFlow . add ( textFlow ) ; inline = new InlineFlow ( ) ; textFlow = new TextFlow ( edge . getHead ( ) . getName ( ) ) ; textFlow . setFont ( italicMonospaceFont ) ; inline . add ( textFlow ) ; blockFlow . add ( inline ) ; page . add ( blockFlow ) ; if ( ! "" . equals ( edge . getName ( ) ) ) { blockFlow = new BlockFlow ( ) ; textFlow = new TextFlow ( "" + edge . getName ( ) ) ; blockFlow . add ( textFlow ) ; page . add ( blockFlow ) ; } if ( edge . hasAttr ( LINK_PARAMETERS_ATTR ) ) { final Map parameters = ( Map ) edge . getAttr ( LINK_PARAMETERS_ATTR ) ; if ( ! parameters . isEmpty ( ) ) { final BlockFlow outterBlock = new BlockFlow ( ) ; for ( final Iterator iter = parameters . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final Map . Entry entry = ( Map . Entry ) iter . next ( ) ; final BlockFlow innerBlock = new BlockFlow ( ) ; textFlow = new TextFlow ( ( ( String ) entry . getKey ( ) ) + "" ) ; textFlow . setFont ( monospaceFont ) ; innerBlock . add ( textFlow ) ; inline = new InlineFlow ( ) ; textFlow = new TextFlow ( ( String ) entry . getValue ( ) ) ; textFlow . setFont ( italicMonospaceFont ) ; inline . add ( textFlow ) ; innerBlock . add ( inline ) ; outterBlock . add ( innerBlock ) ; } outterBlock . setBorder ( new SectionBorder ( ) ) ; page . add ( outterBlock ) ; } } if ( edge . hasAttr ( LINK_SUBANT_DIRECTORIES ) ) { final Collection directories = ( Collection ) edge . getAttr ( LINK_SUBANT_DIRECTORIES ) ; if ( ! directories . isEmpty ( ) ) { final BlockFlow outterBlock = new BlockFlow ( ) ; textFlow = new TextFlow ( "" ) ; outterBlock . add ( textFlow ) ; for ( final Iterator iter = directories . iterator ( ) ; iter . hasNext ( ) ; ) { String currentDirectory = ( String ) iter . next ( ) ; final Dimension dim = FigureUtilities . getTextExtents ( currentDirectory , monospaceFont ) ; if ( dim . width > TOOLTIP_WIDTH ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "" + dim + "" + currentDirectory ) ; } final int length = currentDirectory . length ( ) ; int index = length ; String part = "" ; while ( true ) { index = currentDirectory . lastIndexOf ( File . separatorChar , index - ) ; final String tmp = currentDirectory . substring ( index ) ; if ( FigureUtilities . getTextExtents ( ELLIPSIS + tmp , monospaceFont ) . width > TOOLTIP_WIDTH ) { break ; } part = tmp ; } currentDirectory = ELLIPSIS + part ; if ( log . isDebugEnabled ( ) ) { log . debug ( "" + currentDirectory ) ; } } final BlockFlow innerBlock = new BlockFlow ( ) ; textFlow = new TextFlow ( currentDirectory ) ; textFlow . setFont ( monospaceFont ) ; innerBlock . add ( textFlow ) ; outterBlock . add ( innerBlock ) ; } outterBlock . setBorder ( new SectionBorder ( ) ) ; page . add ( outterBlock ) ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( "" ) ; } } } package net . ggtools . grand . ui . graph . draw2d ; import net . ggtools . grand . ui . Application ; import org . eclipse . draw2d . AbstractBorder ; import org . eclipse . draw2d . ColorConstants ; import org . eclipse . draw2d . Figure ; import org . eclipse . draw2d . Graphics ; import org . eclipse . draw2d . IFigure ; import org . eclipse . draw2d . MarginBorder ; import org . eclipse . draw2d . ToolbarLayout ; import org . eclipse . draw2d . geometry . Insets ; import org . eclipse . draw2d . geometry . Rectangle ; import org . eclipse . draw2d . text . FlowPage ; abstract class AbstractGraphTooltip extends Figure { public class SectionBorder extends AbstractBorder { public Insets getInsets ( final IFigure figure ) { return new Insets ( , , , ) ; } public void paint ( final IFigure figure , final Graphics graphics , final Insets insets ) { final Rectangle paintRectangle = getPaintRectangle ( figure , insets ) ; graphics . drawLine ( paintRectangle . getTopLeft ( ) , paintRectangle . getTopRight ( ) ) ; } } static final int TOOLTIP_WIDTH = ; public AbstractGraphTooltip ( ) { setForegroundColor ( ColorConstants . tooltipForeground ) ; setBackgroundColor ( ColorConstants . tooltipBackground ) ; setOpaque ( true ) ; final ToolbarLayout layout = new ToolbarLayout ( ) ; setLayoutManager ( layout ) ; setBorder ( new MarginBorder ( ) ) ; } abstract protected void createContents ( ) ; protected FlowPage createFlowPage ( ) { FlowPage page ; page = new FlowPage ( ) ; final ConstrainedPageFlowLayout pageLayout = new ConstrainedPageFlowLayout ( page ) ; page . setLayoutManager ( pageLayout ) ; pageLayout . setMaxFlowWidth ( TOOLTIP_WIDTH ) ; page . setBorder ( new SectionBorder ( ) ) ; page . setFont ( Application . getInstance ( ) . getFont ( Application . TOOLTIP_FONT ) ) ; add ( page ) ; return page ; } } package net . ggtools . grand . ui . graph ; import java . util . Collection ; import net . ggtools . grand . ui . graph . draw2d . Draw2dNode ; public interface SelectionManager { void addListener ( GraphListener listener ) ; void deselectAllNodes ( ) ; void deselectNode ( Draw2dNode node ) ; Collection < Draw2dNode > getSelection ( ) ; void removeSelectionListener ( GraphListener listener ) ; void selectNode ( final Draw2dNode node , final boolean addToSelection ) ; void selectNodeByName ( final String nodeName , final boolean addToSelection ) ; } package net . ggtools . grand . ui . graph ; import net . ggtools . grand . graph . Graph ; public interface FilterChainModelListener { void filteredGraphAvailable ( final Graph filteredGraph ) ; } package net . ggtools . grand . ui . graph ; import java . util . Collection ; public interface GraphListener { void selectionChanged ( Collection selectedNodes ) ; void parameterChanged ( GraphControler controler ) ; } package net . michaelkerley ; import javax . microedition . lcdui . Graphics ; import javax . microedition . lcdui . Image ; public class Pipe { private int x , y ; private int gridX , gridY ; private byte connections = ; private boolean inConnectedSet = false ; public static final int CONN_UP = ; public static final int CONN_RIGHT = ; public static final int CONN_DOWN = ; public static final int CONN_LEFT = ; private static final int CONN_OVERFLOW = ; private static int size = ; private static final int [ ] bitmapSizes = { , , , } ; private static Image [ ] disconnectedBmps = null ; private static Image [ ] connectedBmps = null ; private static boolean bmpsLoaded = false ; private static final int NUM_BMPS = ; private static int sizePlusOne = size + ; private static int size_2 = size / ; private static int size_3 = size / ; public static final int CONNECTED_COLOR = ; public static final int DISCONNECTED_COLOR = ; public static final int DIM_CONNECTED_COLOR = ; public static final int DIM_DISCONNECTED_COLOR = ; public Pipe ( ) { } public void paint ( Graphics g , boolean bright ) { if ( bright ) { paint ( g , inConnectedSet ? CONNECTED_COLOR : DISCONNECTED_COLOR , true ) ; } else { paint ( g , inConnectedSet ? DIM_CONNECTED_COLOR : DIM_DISCONNECTED_COLOR , false ) ; } } public void paint ( Graphics g , int color , boolean preferBitmap ) { if ( preferBitmap && bmpsLoaded ) { if ( color == CONNECTED_COLOR ) { g . drawImage ( connectedBmps [ connections ] , x , y , Graphics . TOP | Graphics . LEFT ) ; } else { g . drawImage ( disconnectedBmps [ connections ] , x , y , Graphics . TOP | Graphics . LEFT ) ; } return ; } g . setColor ( ) ; g . fillRect ( x , y , size , size ) ; g . setColor ( color ) ; g . fillArc ( x + size_3 , y + size_3 , size_3 , size_3 , , ) ; if ( isConnected ( CONN_UP ) ) { g . fillRect ( x + size_3 , y , size_3 , size_2 ) ; } if ( isConnected ( CONN_DOWN ) ) { g . fillRect ( x + size_3 , y + size_2 , size_3 , size_2 + ) ; } if ( isConnected ( CONN_RIGHT ) ) { g . fillRect ( x + size_2 , y + size_3 , size_2 + , size_3 ) ; } if ( isConnected ( CONN_LEFT ) ) { g . fillRect ( x , y + size_3 , size_2 , size_3 ) ; } } public void setConnected ( int dir , boolean connected ) { if ( connected ) { connections |= dir ; } else { connections &= ( ~ dir ) ; } } public void rotate ( boolean clockwise ) { if ( clockwise ) { connections <<= ; if ( isConnected ( CONN_OVERFLOW ) ) { setConnected ( CONN_OVERFLOW , false ) ; setConnected ( CONN_UP , true ) ; } } else { if ( isConnected ( CONN_UP ) ) { setConnected ( CONN_OVERFLOW , true ) ; } connections >>= ; } } private static int getBestBitmapSize ( int preferredSize ) { for ( int i = ; i < bitmapSizes . length ; ++ i ) { if ( bitmapSizes [ i ] <= preferredSize ) { return bitmapSizes [ i ] ; } } return ; } public static int loadBitmaps ( ) { if ( size > ) { try { Image allPipes = Image . createImage ( "" + size + "" ) ; connectedBmps = new Image [ NUM_BMPS ] ; disconnectedBmps = new Image [ NUM_BMPS ] ; for ( int n = ; n < NUM_BMPS ; ++ n ) { disconnectedBmps [ n ] = extractImage ( allPipes , n * size , , size , size ) ; connectedBmps [ n ] = extractImage ( allPipes , n * size , size , size , size ) ; } bmpsLoaded = true ; return size ; } catch ( Exception e ) { e . printStackTrace ( ) ; bmpsLoaded = false ; return ; } } bmpsLoaded = false ; return ; } private static Image extractImage ( Image source , int xOffset , int yOffset , int width , int height ) { Image img = Image . createImage ( width , height ) ; img . getGraphics ( ) . drawImage ( source , - xOffset , - yOffset , Graphics . TOP | Graphics . LEFT ) ; return img ; } public boolean isConnected ( int dir ) { return ( connections & dir ) == dir ; } public int getX ( ) { return x ; } public void setX ( ) { setX ( gridX * sizePlusOne + ) ; } public void setX ( int x ) { this . x = x ; } public int getY ( ) { return y ; } public void setY ( ) { setY ( gridY * sizePlusOne + ) ; } public void setY ( int y ) { this . y = y ; } public int getGridX ( ) { return gridX ; } public void setGridX ( int gridX ) { this . gridX = gridX ; setX ( ) ; } public int getGridY ( ) { return gridY ; } public void setGridY ( int gridY ) { this . gridY = gridY ; setY ( ) ; } public byte getConnections ( ) { return connections ; } public void setConnections ( byte connections ) { this . connections = connections ; } public static int getSize ( ) { return size ; } public static int setSize ( int preferredSize ) { Pipe . size = preferredSize ; int bestSize = getBestBitmapSize ( preferredSize ) ; if ( bestSize > ) { Pipe . size = bestSize ; } Pipe . sizePlusOne = Pipe . size + ; Pipe . size_2 = Pipe . size / ; Pipe . size_3 = Pipe . size / ; return Pipe . size ; } public static int incrementSize ( ) { int bestSize = Pipe . size ; for ( int i = ; i < bitmapSizes . length ; ++ i ) { if ( bitmapSizes [ i ] > Pipe . size ) { bestSize = bitmapSizes [ i ] ; } } setSize ( bestSize ) ; return Pipe . size ; } public static int decrementSize ( ) { return setSize ( Pipe . size - ) ; } public boolean isInConnectedSet ( ) { return inConnectedSet ; } public void setInConnectedSet ( boolean inConnectedSet ) { this . inConnectedSet = inConnectedSet ; } } package net . michaelkerley ; import javax . microedition . lcdui . * ; import javax . microedition . rms . InvalidRecordIDException ; import javax . microedition . rms . RecordStore ; import javax . microedition . rms . RecordStoreException ; import javax . microedition . rms . RecordStoreNotFoundException ; import java . io . IOException ; import java . util . * ; class PipesCanvas extends Canvas implements CommandListener { private Pipe [ ] [ ] pipes ; private PipesMIDlet midlet ; private int cursorX , cursorY ; private Image offscreenGraphics ; private Image imgYouWin ; private Random random = new Random ( ) ; private Stack connectedPipes ; private int mode = MODE_GAME ; private Stack toBeChecked ; private Command rotate , quit , reset , resize , ok , about , help ; private int rows = ; private int cols = ; private static int scrollX = ; private static int scrollY = ; private static final int MODE_GAME = ; private static final int MODE_YOU_WIN = ; private static final int MODE_RESIZE = ; private static final int MODE_ABOUT = ; private static final int MODE_GAME_OVER = ; private static final String STORE_NAME = "" ; private static final int STORE_SIZE_RECORD = ; private static final int STORE_PIPES_RECORD = ; private static final String MESSAGE_GAME_OVER = "" ; private static final Font FONT_GAME_OVER = Font . getFont ( Font . FACE_PROPORTIONAL , Font . STYLE_BOLD | Font . STYLE_ITALIC , Font . SIZE_LARGE ) ; private static final int COLOR_GAME_OVER = ; private static final int COLOR_GAME_OVER_SHADOW = ; private static final long DISPLAY_YOU_WIN_MILLISECONDS = ; private static final String HELP_ALERT_TITLE = "" ; private static final String HELP_ALERT_TEXT = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; public static final int RESIZE_TEXT_COLOR = ; public static final int RESIZE_GRIDLINE_COLOR = RESIZE_TEXT_COLOR ; public static final int CURSOR_COLOR = ; public static final int GRIDLINE_COLOR = ; public static final int DIM_GRIDLINE_COLOR = ; public PipesCanvas ( PipesMIDlet midlet ) { this . midlet = midlet ; offscreenGraphics = Image . createImage ( getWidth ( ) , getHeight ( ) ) ; rotate = new Command ( "" , Command . SCREEN , ) ; reset = new Command ( "" , Command . SCREEN , ) ; resize = new Command ( "" , Command . SCREEN , ) ; help = new Command ( "" , Command . SCREEN , ) ; about = new Command ( "" , Command . SCREEN , ) ; quit = new Command ( "" , Command . SCREEN , ) ; ok = new Command ( "" , Command . OK , ) ; setCommandListener ( this ) ; imgYouWin = loadImage ( new String [ ] { "" , "" , "" } , getWidth ( ) , getHeight ( ) ) ; } private static Image loadImage ( String [ ] filenames , int maxWidth , int maxHeight ) { if ( filenames == null || filenames . length == ) { return null ; } Image img ; for ( int i = ; i < filenames . length ; ++ i ) { img = null ; try { img = Image . createImage ( filenames [ i ] ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } if ( img != null && img . getWidth ( ) <= maxWidth && img . getHeight ( ) <= maxHeight ) { return img ; } } return null ; } public void init ( ) { initPipeSize ( ) ; buildPipes ( ) ; scramblePipes ( ) ; checkConnections ( ) ; if ( mode != MODE_GAME ) { setMode ( MODE_GAME ) ; } } private void assertValidCursor ( ) { if ( cursorX < ) { cursorX = ; } if ( cursorX >= cols ) { cursorX = cols - ; } if ( cursorY < ) { cursorY = ; } if ( cursorY >= rows ) { cursorY = rows - ; } } private void initPipeSize ( ) { int sizeX = ( getWidth ( ) - ) / cols ; int sizeY = ( getHeight ( ) - ) / rows ; while ( sizeX % != ) { -- sizeX ; } while ( sizeY % != ) { -- sizeY ; } int size = Math . min ( sizeX , sizeY ) ; Pipe . setSize ( size - ) ; } private void initPipes ( ) { Pipe b ; pipes = new Pipe [ cols ] [ rows ] ; for ( int x = ; x < cols ; ++ x ) { for ( int y = ; y < rows ; ++ y ) { b = pipes [ x ] [ y ] = new Pipe ( ) ; b . setGridX ( x ) ; b . setGridY ( y ) ; } } connectedPipes = new Stack ( ) ; toBeChecked = new Stack ( ) ; } protected void paint ( Graphics g ) { Graphics offscreen = offscreenGraphics . getGraphics ( ) ; paintPipes ( offscreen ) ; if ( mode == MODE_ABOUT ) { paintAbout ( offscreen ) ; } else if ( mode == MODE_YOU_WIN ) { if ( imgYouWin != null ) { offscreen . drawImage ( imgYouWin , getWidth ( ) / , getHeight ( ) / , Graphics . HCENTER | Graphics . VCENTER ) ; } else { int x = ( getWidth ( ) - FONT_GAME_OVER . stringWidth ( MESSAGE_GAME_OVER ) ) / ; int y = ( getHeight ( ) - FONT_GAME_OVER . getHeight ( ) ) / ; offscreen . setFont ( FONT_GAME_OVER ) ; offscreen . setColor ( COLOR_GAME_OVER_SHADOW ) ; offscreen . drawString ( MESSAGE_GAME_OVER , x + , y + , Graphics . TOP | Graphics . LEFT ) ; offscreen . setColor ( COLOR_GAME_OVER ) ; offscreen . drawString ( MESSAGE_GAME_OVER , x - , y - , Graphics . TOP | Graphics . LEFT ) ; } } g . drawImage ( offscreenGraphics , , , Graphics . LEFT | Graphics . TOP ) ; } private void paintPipes ( Graphics g ) { g . setColor ( ) ; g . fillRect ( , , getWidth ( ) , getHeight ( ) ) ; int gridWidth = cols * ( Pipe . getSize ( ) + ) + ; int gridHeight = rows * ( Pipe . getSize ( ) + ) + ; int xOffset , yOffset ; if ( gridWidth <= getWidth ( ) ) { xOffset = ( getWidth ( ) - gridWidth ) / ; } else { int cursorLeft = cursorX * ( Pipe . getSize ( ) + ) ; xOffset = - ( cursorLeft + Pipe . getSize ( ) / - getWidth ( ) / ) ; xOffset = Math . min ( xOffset , ) ; xOffset = Math . max ( xOffset , getWidth ( ) - gridWidth ) ; } if ( gridHeight <= getHeight ( ) ) { yOffset = ( getHeight ( ) - gridHeight ) / ; } else { int cursorTop = cursorY * ( Pipe . getSize ( ) + ) ; yOffset = - ( cursorTop + Pipe . getSize ( ) / - getHeight ( ) / ) ; yOffset = Math . min ( yOffset , ) ; yOffset = Math . max ( yOffset , getHeight ( ) - gridHeight ) ; } g . translate ( xOffset , yOffset ) ; if ( mode != MODE_RESIZE ) { for ( int x = ; x < cols ; ++ x ) { for ( int y = ; y < rows ; ++ y ) { pipes [ x ] [ y ] . paint ( g , mode != MODE_ABOUT ) ; } } if ( mode != MODE_ABOUT ) { g . setColor ( GRIDLINE_COLOR ) ; } else { g . setColor ( DIM_GRIDLINE_COLOR ) ; } } else { g . setColor ( RESIZE_GRIDLINE_COLOR ) ; } for ( int i = ; i <= rows * ( Pipe . getSize ( ) + ) ; i += Pipe . getSize ( ) + ) { g . drawLine ( , i , cols * ( Pipe . getSize ( ) + ) , i ) ; } for ( int i = ; i <= cols * ( Pipe . getSize ( ) + ) ; i += Pipe . getSize ( ) + ) { g . drawLine ( i , , i , rows * ( Pipe . getSize ( ) + ) ) ; } if ( mode == MODE_GAME ) { g . setColor ( CURSOR_COLOR ) ; g . drawRect ( cursorX * ( Pipe . getSize ( ) + ) , cursorY * ( Pipe . getSize ( ) + ) , Pipe . getSize ( ) + , Pipe . getSize ( ) + ) ; } g . translate ( - xOffset , - yOffset ) ; if ( mode == MODE_RESIZE ) { String msg = cols + "" + rows ; Font font = Font . getDefaultFont ( ) ; g . setFont ( font ) ; int msgWidth = font . stringWidth ( msg ) ; int msgHeight = font . getHeight ( ) ; int msgXOffset = ( getWidth ( ) - msgWidth ) / ; int msgYOffset = ( getHeight ( ) - msgHeight ) / ; g . setColor ( ) ; g . fillRect ( msgXOffset - , msgYOffset - , msgWidth + , msgHeight + ) ; g . setColor ( RESIZE_TEXT_COLOR ) ; g . drawString ( msg , msgXOffset , msgYOffset , Graphics . LEFT | Graphics . TOP ) ; } } private void paintAbout ( Graphics g ) { int y = ; String line ; g . setColor ( ) ; for ( int i = ; i < PipesMIDlet . aboutText . length ; ++ i ) { if ( i == ) { line = "" + PipesMIDlet . getInstance ( ) . getAppProperty ( "" ) ; } else { line = PipesMIDlet . aboutText [ i ] ; } if ( PipesMIDlet . largeFont . stringWidth ( line ) < getWidth ( ) ) { g . setFont ( PipesMIDlet . largeFont ) ; } else if ( PipesMIDlet . mediumFont . stringWidth ( line ) < getWidth ( ) ) { g . setFont ( PipesMIDlet . mediumFont ) ; } else { g . setFont ( PipesMIDlet . smallFont ) ; } g . drawString ( line , getWidth ( ) / , y , Graphics . TOP | Graphics . HCENTER ) ; y += g . getFont ( ) . getHeight ( ) ; } } protected void keyRepeated ( int i ) { keyPressed ( i ) ; } protected void keyPressed ( int i ) { switch ( mode ) { case MODE_GAME : keyPressedGame ( i ) ; break ; case MODE_YOU_WIN : keyPressedYouWin ( i ) ; break ; case MODE_GAME_OVER : keyPressedGameOver ( i ) ; break ; case MODE_RESIZE : keyPressedResize ( i ) ; break ; case MODE_ABOUT : setMode ( MODE_GAME ) ; repaint ( ) ; break ; } } private void keyPressedGame ( int i ) { switch ( getGameAction ( i ) ) { case UP : -- cursorY ; if ( cursorY < ) { cursorY = rows - ; } repaint ( ) ; break ; case LEFT : -- cursorX ; if ( cursorX < ) { cursorX = cols - ; } repaint ( ) ; break ; case DOWN : ++ cursorY ; if ( cursorY >= rows ) { cursorY = ; } repaint ( ) ; break ; case RIGHT : ++ cursorX ; if ( cursorX >= cols ) { cursorX = ; } repaint ( ) ; break ; case FIRE : pipes [ cursorX ] [ cursorY ] . rotate ( true ) ; checkConnections ( ) ; repaint ( ) ; break ; default : switch ( i ) { case KEY_NUM1 : pipes [ cursorX ] [ cursorY ] . rotate ( false ) ; checkConnections ( ) ; repaint ( ) ; break ; case KEY_NUM3 : pipes [ cursorX ] [ cursorY ] . rotate ( true ) ; checkConnections ( ) ; repaint ( ) ; break ; case KEY_STAR : zoomOut ( ) ; repaint ( ) ; break ; case KEY_POUND : zoomIn ( ) ; repaint ( ) ; break ; } } } private void keyPressedYouWin ( int i ) { keyPressedGameOver ( i ) ; } private void keyPressedGameOver ( int i ) { commandAction ( reset , this ) ; } private void keyPressedResize ( int i ) { switch ( getGameAction ( i ) ) { case UP : if ( rows > ) { -- rows ; initPipeSize ( ) ; repaint ( ) ; } break ; case LEFT : if ( cols > ) { -- cols ; initPipeSize ( ) ; repaint ( ) ; } break ; case DOWN : ++ rows ; initPipeSize ( ) ; if ( Pipe . getSize ( ) < ) { -- rows ; initPipeSize ( ) ; } repaint ( ) ; break ; case RIGHT : ++ cols ; initPipeSize ( ) ; if ( Pipe . getSize ( ) < ) { -- cols ; initPipeSize ( ) ; } repaint ( ) ; break ; case FIRE : commandAction ( ok , this ) ; break ; } } private Pipe getPipe ( int x , int y ) { if ( x < || x >= cols || y < || y >= rows ) { return null ; } else { return pipes [ x ] [ y ] ; } } private void buildPipes ( ) { initPipes ( ) ; Vector connected = new Vector ( rows * cols ) ; connected . addElement ( pipes [ Math . abs ( random . nextInt ( ) ) % cols ] [ Math . abs ( random . nextInt ( ) ) % rows ] ) ; Pipe p , p2 = null ; int direction , reverseDirection = ; while ( connected . size ( ) < connected . capacity ( ) ) { p = ( Pipe ) connected . elementAt ( Math . abs ( random . nextInt ( ) ) % connected . size ( ) ) ; direction = << Math . abs ( random . nextInt ( ) ) % ; switch ( direction ) { case Pipe . CONN_UP : p2 = getPipe ( p . getGridX ( ) , p . getGridY ( ) - ) ; reverseDirection = Pipe . CONN_DOWN ; break ; case Pipe . CONN_DOWN : p2 = getPipe ( p . getGridX ( ) , p . getGridY ( ) + ) ; reverseDirection = Pipe . CONN_UP ; break ; case Pipe . CONN_LEFT : p2 = getPipe ( p . getGridX ( ) - , p . getGridY ( ) ) ; reverseDirection = Pipe . CONN_RIGHT ; break ; case Pipe . CONN_RIGHT : p2 = getPipe ( p . getGridX ( ) + , p . getGridY ( ) ) ; reverseDirection = Pipe . CONN_LEFT ; break ; } if ( p2 != null && p2 . getConnections ( ) == ) { p . setConnected ( direction , true ) ; p2 . setConnected ( reverseDirection , true ) ; connected . addElement ( p2 ) ; repaint ( ) ; } } } private void scramblePipes ( ) { Pipe p ; int rotations ; for ( int x = ; x < cols ; ++ x ) { for ( int y = ; y < rows ; ++ y ) { p = pipes [ x ] [ y ] ; rotations = Math . abs ( random . nextInt ( ) ) % ; for ( int i = ; i < rotations ; ++ i ) { p . rotate ( true ) ; } } } } public void commandAction ( Command command , Displayable displayable ) { if ( command == rotate ) { pipes [ cursorX ] [ cursorY ] . rotate ( true ) ; checkConnections ( ) ; repaint ( ) ; } else if ( command == reset ) { init ( ) ; } else if ( command == quit ) { midlet . quit ( ) ; } else if ( command == resize ) { setMode ( MODE_RESIZE ) ; repaint ( ) ; } else if ( command == ok ) { setMode ( MODE_GAME ) ; repaint ( ) ; } else if ( command == about ) { setMode ( MODE_ABOUT ) ; repaint ( ) ; } else if ( command == help ) { Alert alert = new Alert ( HELP_ALERT_TITLE , HELP_ALERT_TEXT , null , null ) ; alert . setTimeout ( Alert . FOREVER ) ; Display . getDisplay ( PipesMIDlet . getInstance ( ) ) . setCurrent ( alert ) ; } } public void checkConnections ( ) { Pipe p , p2 ; int x , y ; while ( connectedPipes . size ( ) > ) { ( ( Pipe ) connectedPipes . pop ( ) ) . setInConnectedSet ( false ) ; } p = pipes [ cols / ] [ rows / ] ; connectedPipes . addElement ( p ) ; toBeChecked . addElement ( p ) ; p . setInConnectedSet ( true ) ; while ( ! toBeChecked . empty ( ) ) { p = ( Pipe ) toBeChecked . pop ( ) ; x = p . getGridX ( ) ; y = p . getGridY ( ) ; if ( p . isConnected ( Pipe . CONN_UP ) ) { p2 = getPipe ( x , y - ) ; if ( p2 != null && p2 . isConnected ( Pipe . CONN_DOWN ) && ! p2 . isInConnectedSet ( ) ) { connectedPipes . addElement ( p2 ) ; toBeChecked . addElement ( p2 ) ; p2 . setInConnectedSet ( true ) ; } } if ( p . isConnected ( Pipe . CONN_DOWN ) ) { p2 = getPipe ( x , y + ) ; if ( p2 != null && p2 . isConnected ( Pipe . CONN_UP ) && ! p2 . isInConnectedSet ( ) ) { connectedPipes . addElement ( p2 ) ; toBeChecked . addElement ( p2 ) ; p2 . setInConnectedSet ( true ) ; } } if ( p . isConnected ( Pipe . CONN_LEFT ) ) { p2 = getPipe ( x - , y ) ; if ( p2 != null && p2 . isConnected ( Pipe . CONN_RIGHT ) && ! p2 . isInConnectedSet ( ) ) { connectedPipes . addElement ( p2 ) ; toBeChecked . addElement ( p2 ) ; p2 . setInConnectedSet ( true ) ; } } if ( p . isConnected ( Pipe . CONN_RIGHT ) ) { p2 = getPipe ( x + , y ) ; if ( p2 != null && p2 . isConnected ( Pipe . CONN_LEFT ) && ! p2 . isInConnectedSet ( ) ) { connectedPipes . addElement ( p2 ) ; toBeChecked . addElement ( p2 ) ; p2 . setInConnectedSet ( true ) ; } } } if ( connectedPipes . size ( ) == ( rows * cols ) ) { setMode ( MODE_YOU_WIN ) ; } } public int getMode ( ) { return mode ; } public void setMode ( int mode ) { int oldMode = this . mode ; this . mode = mode ; removeCommand ( ok ) ; removeCommand ( rotate ) ; removeCommand ( reset ) ; removeCommand ( resize ) ; removeCommand ( quit ) ; removeCommand ( about ) ; removeCommand ( help ) ; switch ( mode ) { case MODE_GAME : addCommand ( rotate ) ; addCommand ( reset ) ; addCommand ( resize ) ; addCommand ( help ) ; addCommand ( about ) ; addCommand ( quit ) ; assertValidCursor ( ) ; Pipe . loadBitmaps ( ) ; if ( oldMode != MODE_ABOUT && oldMode != MODE_GAME ) { init ( ) ; } checkConnections ( ) ; break ; case MODE_YOU_WIN : initPipeSize ( ) ; Pipe . loadBitmaps ( ) ; repositionPipes ( ) ; new Timer ( ) . schedule ( new HideYouWinTask ( ) , DISPLAY_YOU_WIN_MILLISECONDS ) ; break ; case MODE_GAME_OVER : break ; case MODE_RESIZE : initPipeSize ( ) ; addCommand ( ok ) ; break ; case MODE_ABOUT : addCommand ( ok ) ; break ; } } public void save ( ) throws RecordStoreException { RecordStore rs = null ; try { rs = RecordStore . openRecordStore ( STORE_NAME , true ) ; byte [ ] size = new byte [ ] ; size [ ] = ( byte ) cols ; size [ ] = ( byte ) rows ; try { rs . setRecord ( STORE_SIZE_RECORD , size , , size . length ) ; } catch ( InvalidRecordIDException e ) { rs . addRecord ( size , , size . length ) ; } byte [ ] pipesBytes = new byte [ rows * cols ] ; int i = ; for ( int y = ; y < rows ; ++ y ) { for ( int x = ; x < cols ; ++ x ) { pipesBytes [ i ] = pipes [ x ] [ y ] . getConnections ( ) ; ++ i ; } } try { rs . setRecord ( STORE_PIPES_RECORD , pipesBytes , , pipesBytes . length ) ; } catch ( InvalidRecordIDException e ) { rs . addRecord ( pipesBytes , , pipesBytes . length ) ; } rs . closeRecordStore ( ) ; } catch ( Throwable t ) { try { rs . closeRecordStore ( ) ; } catch ( Throwable t2 ) { t2 . printStackTrace ( ) ; } try { RecordStore . deleteRecordStore ( STORE_NAME ) ; } catch ( Throwable t2 ) { t2 . printStackTrace ( ) ; } } } public void load ( ) throws RecordStoreException { RecordStore rs ; boolean success = true ; try { rs = RecordStore . openRecordStore ( STORE_NAME , false ) ; try { byte [ ] size = rs . getRecord ( STORE_SIZE_RECORD ) ; cols = ( int ) size [ ] ; rows = ( int ) size [ ] ; if ( cols > && rows > ) { initPipeSize ( ) ; try { byte [ ] pipesBytes = rs . getRecord ( STORE_PIPES_RECORD ) ; initPipes ( ) ; int i = ; for ( int y = ; y < rows ; ++ y ) { for ( int x = ; x < cols ; ++ x ) { pipes [ x ] [ y ] . setConnections ( pipesBytes [ i ] ) ; ++ i ; if ( pipes [ x ] [ y ] . getConnections ( ) == ) { success = false ; } } } if ( success ) { checkConnections ( ) ; } } catch ( InvalidRecordIDException e ) { success = false ; } } else { success = false ; } } catch ( Exception e ) { try { rs . closeRecordStore ( ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; } try { RecordStore . deleteRecordStore ( STORE_NAME ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; } } finally { try { rs . closeRecordStore ( ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; } } } catch ( RecordStoreNotFoundException e ) { success = false ; } if ( ! success ) { cols = rows = ; init ( ) ; } } public void showAbout ( long time ) { setMode ( MODE_ABOUT ) ; repaint ( ) ; new Timer ( ) . schedule ( new CloseAboutTask ( ) , time ) ; } private void zoomOut ( ) { Pipe . decrementSize ( ) ; Pipe . loadBitmaps ( ) ; repositionPipes ( ) ; } private void zoomIn ( ) { Pipe . incrementSize ( ) ; Pipe . loadBitmaps ( ) ; repositionPipes ( ) ; } private void repositionPipes ( ) { for ( int y = ; y < rows ; ++ y ) { for ( int x = ; x < cols ; ++ x ) { pipes [ x ] [ y ] . setX ( ) ; pipes [ x ] [ y ] . setY ( ) ; } } } private class CloseAboutTask extends TimerTask { public void run ( ) { if ( mode == MODE_ABOUT ) { setMode ( MODE_GAME ) ; repaint ( ) ; } } } private class HideYouWinTask extends TimerTask { public void run ( ) { if ( mode == MODE_YOU_WIN ) { setMode ( MODE_GAME_OVER ) ; repaint ( ) ; } } } } package net . michaelkerley ; import javax . microedition . lcdui . Font ; import javax . microedition . lcdui . Display ; import javax . microedition . midlet . MIDlet ; import javax . microedition . midlet . MIDletStateChangeException ; import javax . microedition . rms . RecordStoreException ; public class PipesMIDlet extends MIDlet { public static final String [ ] aboutText = { "" , "" , "" , "" , "" , "" , "" } ; public static final Font largeFont = Font . getFont ( Font . FACE_PROPORTIONAL , Font . STYLE_BOLD , Font . SIZE_LARGE ) ; public static final Font mediumFont = Font . getFont ( Font . FACE_PROPORTIONAL , Font . STYLE_BOLD , Font . SIZE_MEDIUM ) ; public static final Font smallFont = Font . getFont ( Font . FACE_PROPORTIONAL , Font . STYLE_PLAIN , Font . SIZE_SMALL ) ; private PipesCanvas pipesCanvas ; private boolean firstStart = true ; private static PipesMIDlet instance ; public PipesMIDlet ( ) { instance = this ; pipesCanvas = new PipesCanvas ( this ) ; } protected void startApp ( ) throws MIDletStateChangeException { try { pipesCanvas . load ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; pipesCanvas . init ( ) ; } if ( firstStart ) { pipesCanvas . showAbout ( ) ; Display . getDisplay ( this ) . setCurrent ( pipesCanvas ) ; firstStart = false ; } } protected void pauseApp ( ) { try { pipesCanvas . save ( ) ; } catch ( RecordStoreException e ) { e . printStackTrace ( ) ; } } protected void destroyApp ( boolean b ) throws MIDletStateChangeException { try { pipesCanvas . save ( ) ; } catch ( RecordStoreException e ) { e . printStackTrace ( ) ; } } public void quit ( ) { try { destroyApp ( true ) ; notifyDestroyed ( ) ; } catch ( MIDletStateChangeException e ) { e . printStackTrace ( ) ; } } public static PipesMIDlet getInstance ( ) { return instance ; } public static void log ( String str ) { } public static void clearLog ( ) { } public static String getLogContents ( ) { String ret = null ; return ret ; } } package mc . now . ui ; import java . awt . Desktop ; import java . awt . Dimension ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . awt . image . BufferedImage ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileReader ; import java . io . IOException ; import java . net . URI ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import javax . imageio . ImageIO ; import javax . swing . BoxLayout ; import javax . swing . ImageIcon ; import javax . swing . JButton ; import javax . swing . JComboBox ; import javax . swing . JEditorPane ; import javax . swing . JFileChooser ; import javax . swing . JFrame ; import javax . swing . JLabel ; import javax . swing . JOptionPane ; import javax . swing . JPanel ; import javax . swing . JProgressBar ; import javax . swing . JScrollPane ; import javax . swing . JTextArea ; import javax . swing . JTextPane ; import javax . swing . SwingWorker ; import javax . swing . UIManager ; import javax . swing . event . HyperlinkEvent ; import javax . swing . event . HyperlinkListener ; import javax . swing . event . TreeSelectionEvent ; import javax . swing . event . TreeSelectionListener ; import javax . swing . tree . DefaultMutableTreeNode ; import javax . swing . tree . TreePath ; import mc . now . util . InstallScript ; import mc . now . util . InstallerConfig ; import net . miginfocom . layout . AC ; import net . miginfocom . layout . CC ; import net . miginfocom . layout . LC ; import net . miginfocom . swing . MigLayout ; import org . apache . commons . io . FilenameUtils ; import org . apache . log4j . Logger ; import com . jidesoft . swing . CheckBoxTree ; import com . jidesoft . swing . CheckBoxTreeSelectionModel ; @ SuppressWarnings ( "" ) public class Installer extends JFrame implements ActionListener , HyperlinkListener { private static final Logger LOGGER = Logger . getLogger ( Installer . class ) ; private static final String PRESET_NONE = "" ; private static final String PRESET_ALL = "" ; private static final String PRESET_CUSTOM = "" ; private JButton nextButton ; private JButton cancelButton ; private JProgressBar progressBar ; private int step = ; private JPanel contentPane ; private CheckBoxTree modTree ; private JComboBox presetDropdown ; private JPanel modDescrPane ; private DefaultMutableTreeNode modTreeRoot ; private JButton targetButton ; private Map < String , List < String > > presetMap ; private Map < String , DefaultMutableTreeNode > treeNodeMap ; public Installer ( ) { super ( InstallerConfig . getFrameTitle ( ) ) ; setDefaultCloseOperation ( JFrame . DISPOSE_ON_CLOSE ) ; setMinimumSize ( new Dimension ( , ) ) ; init ( ) ; pack ( ) ; } private void init ( ) { JPanel p = new JPanel ( ) ; p . setLayout ( new MigLayout ( "" , "" , "" ) ) ; p . add ( getMainPane ( ) , new CC ( ) . spanX ( ) . grow ( ) ) ; p . add ( getProgressBar ( ) , new CC ( ) . growX ( ) ) ; p . add ( getCancelButton ( ) , new CC ( ) . alignX ( "" ) ) ; p . add ( getNextButton ( ) , new CC ( ) . alignX ( "" ) ) ; setContentPane ( p ) ; } private JButton getNextButton ( ) { if ( nextButton == null ) { nextButton = new JButton ( "" ) ; nextButton . addActionListener ( this ) ; } return nextButton ; } private JButton getCancelButton ( ) { if ( cancelButton == null ) { cancelButton = new JButton ( "" ) ; cancelButton . addActionListener ( this ) ; } return cancelButton ; } private JProgressBar getProgressBar ( ) { if ( progressBar == null ) { progressBar = new JProgressBar ( ) ; } return progressBar ; } private JPanel getMainPane ( ) { if ( contentPane == null ) { contentPane = new JPanel ( ) ; initialPanel ( contentPane ) ; } return contentPane ; } protected void initialPanel ( JPanel contentPane ) { JLabel text = new JLabel ( ) ; try { ImageIcon icon = new ImageIcon ( ImageIO . read ( new FileInputStream ( InstallerConfig . getLogoFile ( ) ) ) ) ; text . setIcon ( icon ) ; } catch ( IOException e ) { LOGGER . error ( "" , e ) ; } StringBuffer textBuffer = new StringBuffer ( ) ; try { BufferedReader r = new BufferedReader ( new FileReader ( InstallerConfig . getInitTextFile ( ) ) ) ; String line = null ; while ( ( line = r . readLine ( ) ) != null ) { textBuffer . append ( line + "" ) ; } } catch ( IOException ioe ) { LOGGER . error ( "" , ioe ) ; } text . setText ( textBuffer . toString ( ) ) ; text . setVerticalTextPosition ( JLabel . BOTTOM ) ; text . setHorizontalTextPosition ( JLabel . CENTER ) ; contentPane . setLayout ( new MigLayout ( new LC ( ) . fill ( ) ) ) ; contentPane . add ( text , new CC ( ) . alignX ( "" ) . wrap ( ) ) ; contentPane . add ( getTargetButton ( ) , new CC ( ) . alignX ( "" ) . wrap ( ) ) ; } private JButton getTargetButton ( ) { if ( targetButton == null ) { targetButton = new JButton ( "" ) ; targetButton . addActionListener ( this ) ; } return targetButton ; } private void chooseTargetMinecraftFolder ( ) { JFileChooser chooser = new JFileChooser ( ) ; chooser . setFileSelectionMode ( JFileChooser . DIRECTORIES_ONLY ) ; chooser . setMultiSelectionEnabled ( false ) ; int opt = chooser . showOpenDialog ( getMainPane ( ) ) ; if ( opt == JFileChooser . APPROVE_OPTION ) { File dir = chooser . getSelectedFile ( ) ; String oldDir = InstallerConfig . getMinecraftFolder ( ) ; InstallerConfig . setMinecraftFolder ( dir . getAbsolutePath ( ) ) ; File mcjar = new File ( InstallerConfig . getMinecraftJar ( ) ) ; if ( ! mcjar . exists ( ) ) { JOptionPane . showMessageDialog ( getMainPane ( ) , "" + "" + oldDir , "" , JOptionPane . ERROR_MESSAGE ) ; InstallerConfig . setMinecraftFolder ( oldDir ) ; } } } private void advanceStep ( ) { step ++ ; switch ( step ) { case : { String msg = InstallScript . preInstallCheck ( ) ; if ( msg != null ) { msg = msg + "" + "" ; int opt = JOptionPane . showConfirmDialog ( this , msg , "" , JOptionPane . YES_NO_OPTION , JOptionPane . WARNING_MESSAGE ) ; if ( opt == JOptionPane . NO_OPTION ) { setVisible ( false ) ; dispose ( ) ; return ; } } File modsFolder = new File ( InstallerConfig . getInstallerModsFolder ( ) ) ; if ( ! modsFolder . exists ( ) ) { JOptionPane . showMessageDialog ( this , "" , "" , EXIT_ON_CLOSE , null ) ; } advanceStep ( ) ; return ; } case : buildInstallingPane ( ) ; return ; default : LOGGER . error ( "" ) ; return ; } } private void buildInstallingPane ( ) { getNextButton ( ) . setEnabled ( false ) ; getCancelButton ( ) . setEnabled ( false ) ; getMainPane ( ) . removeAll ( ) ; getMainPane ( ) . setLayout ( new MigLayout ( new LC ( ) . fill ( ) ) ) ; final JTextArea textArea = new JTextArea ( ) ; textArea . setEditable ( false ) ; getMainPane ( ) . add ( new JScrollPane ( textArea ) , new CC ( ) . grow ( ) . spanY ( ) . wrap ( ) ) ; getMainPane ( ) . validate ( ) ; getMainPane ( ) . repaint ( ) ; SwingWorker < Object , String > worker = new SwingWorker < Object , String > ( ) { @ Override protected Object doInBackground ( ) throws Exception { try { InstallScript . guiInstall ( textArea , getProgressBar ( ) ) ; } catch ( Exception e ) { LOGGER . error ( "" , e ) ; JOptionPane . showMessageDialog ( Installer . this , "" + e . getMessage ( ) , "" , JOptionPane . ERROR_MESSAGE ) ; setVisible ( false ) ; dispose ( ) ; } return null ; } @ Override public void done ( ) { getNextButton ( ) . removeActionListener ( Installer . this ) ; getNextButton ( ) . setText ( "" ) ; getNextButton ( ) . addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { setVisible ( false ) ; dispose ( ) ; } } ) ; getNextButton ( ) . setEnabled ( true ) ; } } ; worker . execute ( ) ; } private JComboBox getPresetDropdown ( ) { if ( presetDropdown == null ) { presetDropdown = new JComboBox ( ) ; presetDropdown . addItem ( PRESET_NONE ) ; presetDropdown . addItem ( PRESET_ALL ) ; presetDropdown . addItem ( PRESET_CUSTOM ) ; presetDropdown . addActionListener ( this ) ; File presetDir = new File ( FilenameUtils . concat ( InstallerConfig . getInstallerDir ( ) , "" ) ) ; if ( ! presetDir . exists ( ) || ! presetDir . isDirectory ( ) ) { LOGGER . warn ( "" ) ; } else { presetMap = new HashMap < String , List < String > > ( ) ; File [ ] children = presetDir . listFiles ( ) ; for ( File child : children ) { if ( ! child . isFile ( ) ) { continue ; } String name = FilenameUtils . getBaseName ( child . getName ( ) ) ; try { BufferedReader r = new BufferedReader ( new FileReader ( child ) ) ; String l = null ; List < String > mods = new ArrayList < String > ( ) ; while ( ( l = r . readLine ( ) ) != null ) { mods . add ( l ) ; } presetMap . put ( name , mods ) ; presetDropdown . addItem ( name ) ; } catch ( IOException e ) { LOGGER . warn ( "" + child . getName ( ) , e ) ; } } } } return presetDropdown ; } @ Override public void actionPerformed ( ActionEvent e ) { if ( e . getSource ( ) == getNextButton ( ) ) { advanceStep ( ) ; } else if ( e . getSource ( ) == getCancelButton ( ) ) { setVisible ( false ) ; dispose ( ) ; } else if ( e . getSource ( ) == getTargetButton ( ) ) { chooseTargetMinecraftFolder ( ) ; } } @ Override public void hyperlinkUpdate ( final HyperlinkEvent e ) { if ( e . getEventType ( ) != HyperlinkEvent . EventType . ACTIVATED ) { return ; } SwingWorker < Object , Object > worker = new SwingWorker < Object , Object > ( ) { @ Override protected Object doInBackground ( ) throws Exception { try { String url = e . getURL ( ) . toExternalForm ( ) ; Desktop . getDesktop ( ) . browse ( URI . create ( url ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; } } ; worker . execute ( ) ; } public static boolean sanityCheck ( ) { File mcFolder = new File ( InstallerConfig . getMinecraftFolder ( ) ) ; String errmsg = "" ; if ( InstallerConfig . getInstallerDir ( ) . toLowerCase ( ) . endsWith ( "" ) ) { errmsg += "" ; return false ; } File modsFolder = new File ( InstallerConfig . getInstallerModsFolder ( ) ) ; if ( ! modsFolder . exists ( ) ) { errmsg += InstallerConfig . getInstallerModsFolder ( ) + "" ; } File logofile = new File ( InstallerConfig . getInitTextFile ( ) ) ; if ( ! logofile . exists ( ) ) { errmsg += InstallerConfig . getInitTextFile ( ) + "" ; } File textfile = new File ( InstallerConfig . getLogoFile ( ) ) ; if ( ! textfile . exists ( ) ) { errmsg += InstallerConfig . getLogoFile ( ) + "" ; } errmsg = errmsg . trim ( ) ; if ( ! errmsg . isEmpty ( ) ) { LOGGER . error ( errmsg ) ; JOptionPane . showMessageDialog ( null , errmsg , "" , JOptionPane . ERROR_MESSAGE ) ; } return errmsg . isEmpty ( ) ; } public static void main ( String [ ] args ) throws IOException { LOGGER . debug ( "" ) ; LOGGER . debug ( "" + InstallerConfig . currentOS ) ; if ( ! sanityCheck ( ) ) { return ; } try { UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; } catch ( Exception e ) { LOGGER . warn ( "" , e ) ; } Installer installer = new Installer ( ) ; installer . setVisible ( true ) ; } } package mc . now . util ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Enumeration ; import java . util . LinkedList ; import java . util . List ; import java . util . Queue ; import java . util . Random ; import java . util . jar . JarEntry ; import java . util . jar . JarFile ; import java . util . jar . JarOutputStream ; import javax . swing . JProgressBar ; import javax . swing . JTextArea ; import javax . swing . JTextPane ; import org . apache . commons . codec . digest . DigestUtils ; import org . apache . commons . io . FileUtils ; import org . apache . commons . io . FilenameUtils ; import org . apache . log4j . Logger ; public class InstallScript { private static final Logger LOGGER = Logger . getLogger ( InstallScript . class ) ; public static void repackMCJar ( File tmp , File mcjar ) throws IOException { byte [ ] dat = new byte [ * ] ; JarOutputStream jarout = new JarOutputStream ( FileUtils . openOutputStream ( mcjar ) ) ; Queue < File > queue = new LinkedList < File > ( ) ; for ( File f : tmp . listFiles ( ) ) { queue . add ( f ) ; } while ( ! queue . isEmpty ( ) ) { File f = queue . poll ( ) ; if ( f . isDirectory ( ) ) { for ( File child : f . listFiles ( ) ) { queue . add ( child ) ; } } else { String name = f . getPath ( ) . substring ( tmp . getPath ( ) . length ( ) + ) ; name = name . replace ( "" , "" ) ; if ( f . isDirectory ( ) && ! name . endsWith ( "" ) ) { name = name + "" ; } JarEntry entry = new JarEntry ( name ) ; jarout . putNextEntry ( entry ) ; FileInputStream in = new FileInputStream ( f ) ; int len = - ; while ( ( len = in . read ( dat ) ) > ) { jarout . write ( dat , , len ) ; } in . close ( ) ; } jarout . closeEntry ( ) ; } jarout . close ( ) ; } public static void unpackMCJar ( File tmpdir , File mcjar ) throws IOException { byte [ ] dat = new byte [ * ] ; JarFile jar = new JarFile ( mcjar ) ; Enumeration < JarEntry > entries = jar . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; String name = entry . getName ( ) ; if ( name . startsWith ( "" ) ) { continue ; } InputStream in = jar . getInputStream ( entry ) ; File dest = new File ( FilenameUtils . concat ( tmpdir . getPath ( ) , name ) ) ; if ( entry . isDirectory ( ) ) { LOGGER . warn ( "" ) ; dest . mkdirs ( ) ; } else if ( ! dest . getParentFile ( ) . exists ( ) ) { if ( ! dest . getParentFile ( ) . mkdirs ( ) ) { throw new IOException ( "" + name ) ; } } FileOutputStream out = new FileOutputStream ( dest ) ; int len = - ; while ( ( len = in . read ( dat ) ) > ) { out . write ( dat , , len ) ; } out . flush ( ) ; out . close ( ) ; in . close ( ) ; } } private static File getTempDir ( ) throws IOException { Random rand = new Random ( ) ; String hex = Integer . toHexString ( rand . nextInt ( Integer . MAX_VALUE ) ) ; File tmp = new File ( FilenameUtils . concat ( InstallerConfig . getInstallerDir ( ) , hex + "" ) ) ; int t = ; while ( tmp . exists ( ) && t < ) { hex = Integer . toHexString ( rand . nextInt ( Integer . MAX_VALUE ) ) ; tmp = new File ( FilenameUtils . normalize ( "" + hex + "" ) ) ; t ++ ; } if ( tmp . exists ( ) ) { throw new IOException ( "" ) ; } return tmp ; } public static String preInstallCheck ( ) { try { InputStream mcJarIn = new FileInputStream ( InstallerConfig . getMinecraftJar ( ) ) ; String digest = DigestUtils . md5Hex ( mcJarIn ) ; mcJarIn . close ( ) ; boolean jarValid = InstallerConfig . getMinecraftJarMD5 ( ) . equalsIgnoreCase ( digest ) ; File modsDir = new File ( InstallerConfig . getMinecraftModsFolder ( ) ) ; boolean noMods = ! modsDir . exists ( ) || modsDir . listFiles ( ) . length == ; String msg = null ; if ( ! jarValid ) { LOGGER . warn ( "" ) ; msg = String . format ( "" , InstallerConfig . getMinecraftVersion ( ) ) ; } if ( ! noMods ) { msg = ( msg == null ? "" : msg + "" ) + "" ; } return msg ; } catch ( Exception e ) { LOGGER . error ( "" , e ) ; return "" + e . getMessage ( ) ; } } public static void guiInstall ( JTextArea text , JProgressBar progressBar ) { try { createBackup ( ) ; } catch ( IOException e ) { text . append ( "" ) ; LOGGER . error ( "" , e ) ; return ; } File tmp ; try { tmp = getTempDir ( ) ; } catch ( IOException e ) { text . append ( "" ) ; LOGGER . error ( "" , e ) ; return ; } if ( ! tmp . mkdirs ( ) ) { text . append ( "" ) ; return ; } File mcDir = new File ( InstallerConfig . getMinecraftFolder ( ) ) ; File mcJar = new File ( InstallerConfig . getMinecraftJar ( ) ) ; File reqDir = new File ( InstallerConfig . getInstallerModsFolder ( ) ) ; int reqMods = ; for ( File f : reqDir . listFiles ( ) ) { if ( f . isDirectory ( ) ) { reqMods ++ ; } } boolean installationInErrorState = false ; int baseTasks = ; int taskSize = reqMods + baseTasks ; progressBar . setMinimum ( ) ; progressBar . setMaximum ( taskSize ) ; int task = ; text . append ( "" ) ; LOGGER . info ( "" ) ; try { unpackMCJar ( tmp , mcJar ) ; } catch ( IOException e1 ) { text . append ( "" ) ; LOGGER . error ( "" , e1 ) ; installationInErrorState = true ; } progressBar . setValue ( task ++ ) ; if ( ! installationInErrorState ) { text . append ( "" ) ; LOGGER . info ( "" ) ; try { installForge ( tmp ) ; } catch ( IOException e ) { text . append ( "" ) ; LOGGER . error ( "" , e ) ; installationInErrorState = true ; } progressBar . setValue ( task ++ ) ; } if ( ! installationInErrorState ) { text . append ( "" ) ; LOGGER . info ( "" ) ; try { repackMCJar ( tmp , mcJar ) ; } catch ( IOException e1 ) { text . append ( "" ) ; LOGGER . error ( "" , e1 ) ; installationInErrorState = true ; } progressBar . setValue ( task ++ ) ; } if ( ! installationInErrorState ) { text . append ( "" ) ; LOGGER . info ( "" ) ; try { installMods ( ) ; } catch ( IOException e ) { text . append ( "" ) ; LOGGER . error ( "" , e ) ; installationInErrorState = true ; } progressBar . setValue ( task ++ ) ; } if ( installationInErrorState ) { text . append ( "" ) ; LOGGER . info ( "" ) ; try { restoreBackup ( ) ; } catch ( IOException ioe ) { text . append ( "" ) ; LOGGER . error ( "" , ioe ) ; } } text . append ( "" ) ; LOGGER . info ( "" ) ; try { FileUtils . deleteDirectory ( tmp ) ; progressBar . setValue ( task ++ ) ; } catch ( IOException e ) { text . append ( "" ) ; LOGGER . error ( "" , e ) ; return ; } if ( ! installationInErrorState ) { text . append ( "" ) ; LOGGER . info ( "" ) ; } else { text . append ( "" ) ; LOGGER . error ( "" ) ; } } private static final String [ ] otherThingsToBackup = { "" } ; private static void createBackup ( ) throws IOException { FileUtils . copyFile ( new File ( InstallerConfig . getMinecraftJar ( ) ) , new File ( InstallerConfig . getMinecraftJar ( ) + "" ) ) ; File mods = new File ( InstallerConfig . getMinecraftModsFolder ( ) ) ; File modsBackup = new File ( InstallerConfig . getMinecraftModsFolder ( ) + "" ) ; if ( modsBackup . exists ( ) ) { FileUtils . deleteDirectory ( modsBackup ) ; } if ( mods . exists ( ) ) { FileUtils . copyDirectory ( mods , modsBackup ) ; } for ( String name : otherThingsToBackup ) { String fname = FilenameUtils . normalize ( FilenameUtils . concat ( InstallerConfig . getMinecraftFolder ( ) , name ) ) ; String fnameBackup = fname + "" ; File f = new File ( fname ) ; File backup = new File ( fnameBackup ) ; if ( backup . exists ( ) ) { FileUtils . deleteDirectory ( backup ) ; } if ( f . exists ( ) ) { FileUtils . copyDirectory ( f , backup ) ; } } } private static void restoreBackup ( ) throws IOException { FileUtils . copyFile ( new File ( InstallerConfig . getMinecraftJar ( ) + "" ) , new File ( InstallerConfig . getMinecraftJar ( ) ) ) ; File mods = new File ( InstallerConfig . getMinecraftModsFolder ( ) ) ; File modsBackup = new File ( InstallerConfig . getMinecraftModsFolder ( ) + "" ) ; if ( modsBackup . exists ( ) ) { FileUtils . deleteDirectory ( mods ) ; FileUtils . copyDirectory ( modsBackup , mods ) ; } for ( String name : otherThingsToBackup ) { String fname = FilenameUtils . normalize ( FilenameUtils . concat ( InstallerConfig . getMinecraftFolder ( ) , name ) ) ; String fnameBackup = fname + "" ; File f = new File ( fname ) ; File backup = new File ( fnameBackup ) ; if ( backup . exists ( ) ) { FileUtils . copyDirectory ( backup , f ) ; } } } private static void installForge ( File jarDir ) throws IOException { File forgeDirectoryFile = new File ( InstallerConfig . getForgeFolder ( ) ) ; for ( File file : forgeDirectoryFile . listFiles ( ) ) { if ( file . isDirectory ( ) ) { FileUtils . copyDirectoryToDirectory ( file , jarDir ) ; } else { FileUtils . copyFileToDirectory ( file , jarDir ) ; } } } private static void installMods ( ) throws IOException { File minecraftModsDirectoryFile = new File ( InstallerConfig . getMinecraftModsFolder ( ) ) ; File mcss13ModsDirectoryFile = new File ( InstallerConfig . getMCSS13Folder ( ) ) ; for ( File file : mcss13ModsDirectoryFile . listFiles ( ) ) { if ( file . isDirectory ( ) ) continue ; FileUtils . copyFileToDirectory ( file , minecraftModsDirectoryFile ) ; } } } package mc . now . util ; import java . io . File ; import java . util . HashMap ; import java . util . LinkedList ; import java . util . Map ; import java . util . Queue ; public class CollisionCheck { public static void main ( String [ ] args ) { String dirstr = "" ; File dir = new File ( dirstr ) ; Map < String , String > parentMap = new HashMap < String , String > ( ) ; for ( File moddir : dir . listFiles ( ) ) { if ( ! moddir . isDirectory ( ) ) { continue ; } String parent = moddir . getName ( ) ; System . out . println ( parent ) ; Queue < File > queue = new LinkedList < File > ( ) ; for ( File f : moddir . listFiles ( ) ) { queue . add ( f ) ; } while ( ! queue . isEmpty ( ) ) { File f = queue . poll ( ) ; if ( f . getName ( ) . startsWith ( "" ) ) { continue ; } if ( f . isDirectory ( ) ) { for ( File g : f . listFiles ( ) ) { queue . add ( g ) ; } } else { String child = f . getPath ( ) . substring ( moddir . getPath ( ) . length ( ) ) ; if ( ! parentMap . containsKey ( child ) ) { parentMap . put ( child , parent ) ; } else { String other = parentMap . get ( child ) ; System . err . printf ( "" , child , parent , other ) ; } } } } } } package mc . now . util ; import java . io . File ; import java . io . FileInputStream ; import java . net . URI ; import java . net . URL ; import java . util . Properties ; import org . apache . commons . io . FilenameUtils ; import org . apache . log4j . Logger ; public class InstallerConfig { private static final Logger LOGGER = Logger . getLogger ( InstallerConfig . class ) ; private static enum OS { Mac , Linux , Windows ; } private static final String installerDir ; private static final Properties properties ; public static final OS currentOS ; private static String mcFolder = null ; static { String osname = System . getProperty ( "" ) . toLowerCase ( ) ; if ( osname . startsWith ( "" ) ) { currentOS = OS . Mac ; } else if ( osname . startsWith ( "" ) ) { currentOS = OS . Linux ; } else if ( osname . startsWith ( "" ) ) { currentOS = OS . Windows ; } else { throw new RuntimeException ( "" + osname ) ; } switch ( currentOS ) { case Mac : mcFolder = System . getProperty ( "" ) + "" ; break ; case Linux : mcFolder = System . getProperty ( "" ) + "" ; break ; case Windows : mcFolder = System . getenv ( "" ) + "" ; break ; } properties = new Properties ( ) ; try { URL url = InstallerConfig . class . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) ; File f = new File ( new URI ( url . toString ( ) ) ) ; File dir = f . getParentFile ( ) ; installerDir = dir . getPath ( ) ; properties . load ( new FileInputStream ( FilenameUtils . concat ( installerDir , "" ) ) ) ; } catch ( Exception e ) { LOGGER . error ( "" , e ) ; throw new RuntimeException ( "" ) ; } } public static String getInstallerDir ( ) { return installerDir ; } public static String getMinecraftVersion ( ) { return properties . getProperty ( "" ) ; } public static String getMinecraftJarMD5 ( ) { return properties . getProperty ( "" ) ; } public static String getFrameTitle ( ) { return properties . getProperty ( "" , "" ) ; } public static String getLogoFile ( ) { return FilenameUtils . concat ( installerDir , "" ) ; } public static String getInitTextFile ( ) { return FilenameUtils . concat ( installerDir , "" ) ; } public static String getMinecraftFolder ( ) { return mcFolder ; } public static void setMinecraftFolder ( String target ) { mcFolder = target ; } public static String getMinecraftJar ( ) { return FilenameUtils . normalize ( FilenameUtils . concat ( getMinecraftFolder ( ) , "" ) ) ; } public static String getMinecraftModsFolder ( ) { return FilenameUtils . normalize ( FilenameUtils . concat ( getMinecraftFolder ( ) , "" ) ) ; } public static String getInstallerModsFolder ( ) { return FilenameUtils . concat ( getInstallerDir ( ) , "" ) ; } public static String getForgeFolder ( ) { return FilenameUtils . concat ( getInstallerModsFolder ( ) , "" ) ; } public static String getMCSS13Folder ( ) { return FilenameUtils . concat ( getInstallerModsFolder ( ) , "" ) ; } } package com . example . servletjspdemo . web ; import java . io . IOException ; import java . io . PrintWriter ; import javax . servlet . ServletException ; import javax . servlet . annotation . WebServlet ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; @ WebServlet ( urlPatterns = "" ) public class GreetingServlet extends HttpServlet { private static final long serialVersionUID = ; @ Override protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { response . setContentType ( "" ) ; PrintWriter out = response . getWriter ( ) ; out . println ( "" + new java . util . Date ( ) + "" ) ; out . close ( ) ; } } package com . example . servletjspdemo . web ; import java . io . IOException ; import java . io . PrintWriter ; import javax . servlet . ServletException ; import javax . servlet . annotation . WebServlet ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; @ WebServlet ( urlPatterns = "" ) public class DataServlet extends HttpServlet { private static final long serialVersionUID = ; @ Override protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { response . setContentType ( "" ) ; PrintWriter out = response . getWriter ( ) ; String selectedHobby = "" ; for ( String hobby : request . getParameterValues ( "" ) ) { selectedHobby += hobby + "" ; } out . println ( "" + "" + request . getParameter ( "" ) + "" + "" + selectedHobby + "" + "" ) ; out . close ( ) ; } } package com . example . servletjspdemo . web ; import java . io . IOException ; import java . io . PrintWriter ; import javax . servlet . ServletException ; import javax . servlet . annotation . WebServlet ; import javax . servlet . http . HttpServlet ; import javax . servlet . http . HttpServletRequest ; import javax . servlet . http . HttpServletResponse ; @ WebServlet ( urlPatterns = "" ) public class FormServlet extends HttpServlet { private static final long serialVersionUID = ; @ Override protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { response . setContentType ( "" ) ; PrintWriter out = response . getWriter ( ) ; out . println ( "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; out . close ( ) ; } } package com . example . servletjspdemo . service ; import java . util . ArrayList ; import java . util . List ; import com . example . servletjspdemo . domain . Person ; public class StorageService { private List < Person > db = new ArrayList < Person > ( ) ; public void add ( Person person ) { Person newPerson = new Person ( person . getFirstName ( ) , person . getYob ( ) ) ; db . add ( newPerson ) ; } public List < Person > getAllPersons ( ) { return db ; } } package com . example . servletjspdemo . domain ; public class Person { private String firstName = "" ; private int yob = ; public Person ( ) { super ( ) ; } public Person ( String firstName , int yob ) { super ( ) ; this . firstName = firstName ; this . yob = yob ; } public String getFirstName ( ) { return firstName ; } public void setFirstName ( String firstName ) { this . firstName = firstName ; } public int getYob ( ) { return yob ; } public void setYob ( int yob ) { this . yob = yob ; } } package com . lmax . disruptor ; import com . lmax . disruptor . support . TestEntry ; import org . jmock . Expectations ; import org . jmock . Mockery ; import org . jmock . integration . junit4 . JMock ; import org . jmock . lib . legacy . ClassImposteriser ; import org . junit . Assert ; import org . junit . Test ; import org . junit . runner . RunWith ; import java . util . logging . Level ; import java . util . logging . Logger ; @ RunWith ( JMock . class ) public final class FatalExceptionHandlerTest { private final Mockery context = new Mockery ( ) ; public FatalExceptionHandlerTest ( ) { context . setImposteriser ( ClassImposteriser . INSTANCE ) ; } @ Test public void shouldHandleFatalException ( ) { final Exception causeException = new Exception ( ) ; final AbstractEntry entry = new TestEntry ( ) ; final Logger logger = context . mock ( Logger . class ) ; context . checking ( new Expectations ( ) { { oneOf ( logger ) . log ( Level . SEVERE , "" + entry , causeException ) ; } } ) ; ExceptionHandler exceptionHandler = new FatalExceptionHandler ( logger ) ; try { exceptionHandler . handle ( causeException , entry ) ; } catch ( RuntimeException ex ) { Assert . assertEquals ( causeException , ex . getCause ( ) ) ; } } } package com . lmax . disruptor ; import com . lmax . disruptor . support . StubEntry ; import org . junit . Test ; import static org . hamcrest . core . Is . is ; import static org . junit . Assert . assertThat ; public final class BatchProducerTest { private final RingBuffer < StubEntry > ringBuffer = new RingBuffer < StubEntry > ( StubEntry . ENTRY_FACTORY , ) ; private final ConsumerBarrier < StubEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final ProducerBarrier < StubEntry > producerBarrier = ringBuffer . createProducerBarrier ( new NoOpConsumer ( ringBuffer ) ) ; @ Test public void shouldClaimBatchAndCommitBack ( ) throws Exception { final int batchSize = ; final SequenceBatch sequenceBatch = new SequenceBatch ( batchSize ) ; producerBarrier . nextEntries ( sequenceBatch ) ; assertThat ( Long . valueOf ( sequenceBatch . getStart ( ) ) , is ( Long . valueOf ( ) ) ) ; assertThat ( Long . valueOf ( sequenceBatch . getEnd ( ) ) , is ( Long . valueOf ( ) ) ) ; assertThat ( Long . valueOf ( ringBuffer . getCursor ( ) ) , is ( Long . valueOf ( RingBuffer . INITIAL_CURSOR_VALUE ) ) ) ; producerBarrier . commit ( sequenceBatch ) ; assertThat ( Long . valueOf ( ringBuffer . getCursor ( ) ) , is ( Long . valueOf ( batchSize - ) ) ) ; assertThat ( Long . valueOf ( consumerBarrier . waitFor ( ) ) , is ( Long . valueOf ( batchSize - ) ) ) ; } } package com . lmax . disruptor ; import java . util . List ; import java . util . concurrent . * ; import java . util . concurrent . atomic . AtomicBoolean ; import com . lmax . disruptor . support . DaemonThreadFactory ; import com . lmax . disruptor . support . TestWaiter ; import com . lmax . disruptor . support . StubEntry ; import org . junit . Test ; import static junit . framework . Assert . assertEquals ; import static junit . framework . Assert . assertTrue ; import static org . hamcrest . CoreMatchers . is ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertThat ; public class RingBufferTest { private final ExecutorService EXECUTOR = Executors . newSingleThreadExecutor ( new DaemonThreadFactory ( ) ) ; private final RingBuffer < StubEntry > ringBuffer = new RingBuffer < StubEntry > ( StubEntry . ENTRY_FACTORY , ) ; private final ConsumerBarrier < StubEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final ProducerBarrier < StubEntry > producerBarrier = ringBuffer . createProducerBarrier ( new NoOpConsumer ( ringBuffer ) ) ; @ Test public void shouldClaimAndGet ( ) throws Exception { assertEquals ( RingBuffer . INITIAL_CURSOR_VALUE , ringBuffer . getCursor ( ) ) ; StubEntry expectedEntry = new StubEntry ( ) ; StubEntry oldEntry = producerBarrier . nextEntry ( ) ; oldEntry . copy ( expectedEntry ) ; producerBarrier . commit ( oldEntry ) ; long sequence = consumerBarrier . waitFor ( ) ; assertEquals ( , sequence ) ; StubEntry entry = ringBuffer . getEntry ( sequence ) ; assertEquals ( expectedEntry , entry ) ; assertEquals ( , ringBuffer . getCursor ( ) ) ; } @ Test public void shouldClaimAndGetWithTimeout ( ) throws Exception { assertEquals ( RingBuffer . INITIAL_CURSOR_VALUE , ringBuffer . getCursor ( ) ) ; StubEntry expectedEntry = new StubEntry ( ) ; StubEntry oldEntry = producerBarrier . nextEntry ( ) ; oldEntry . copy ( expectedEntry ) ; producerBarrier . commit ( oldEntry ) ; long sequence = consumerBarrier . waitFor ( , , TimeUnit . MILLISECONDS ) ; assertEquals ( , sequence ) ; StubEntry entry = ringBuffer . getEntry ( sequence ) ; assertEquals ( expectedEntry , entry ) ; assertEquals ( , ringBuffer . getCursor ( ) ) ; } @ Test public void shouldGetWithTimeout ( ) throws Exception { long sequence = consumerBarrier . waitFor ( , , TimeUnit . MILLISECONDS ) ; assertEquals ( RingBuffer . INITIAL_CURSOR_VALUE , sequence ) ; } @ Test public void shouldClaimAndGetInSeparateThread ( ) throws Exception { Future < List < StubEntry > > messages = getMessages ( , ) ; StubEntry expectedEntry = new StubEntry ( ) ; StubEntry oldEntry = producerBarrier . nextEntry ( ) ; oldEntry . copy ( expectedEntry ) ; producerBarrier . commit ( oldEntry ) ; assertEquals ( expectedEntry , messages . get ( ) . get ( ) ) ; } @ Test public void shouldClaimAndGetMultipleMessages ( ) throws Exception { int numMessages = ringBuffer . getCapacity ( ) ; for ( int i = ; i < numMessages ; i ++ ) { StubEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( i ) ; producerBarrier . commit ( entry ) ; } int expectedSequence = numMessages - ; long available = consumerBarrier . waitFor ( expectedSequence ) ; assertEquals ( expectedSequence , available ) ; for ( int i = ; i < numMessages ; i ++ ) { assertEquals ( i , ringBuffer . getEntry ( i ) . getValue ( ) ) ; } } @ Test public void shouldWrap ( ) throws Exception { int numMessages = ringBuffer . getCapacity ( ) ; int offset = ; for ( int i = ; i < numMessages + offset ; i ++ ) { StubEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( i ) ; producerBarrier . commit ( entry ) ; } int expectedSequence = numMessages + offset - ; long available = consumerBarrier . waitFor ( expectedSequence ) ; assertEquals ( expectedSequence , available ) ; for ( int i = offset ; i < numMessages + offset ; i ++ ) { assertEquals ( i , ringBuffer . getEntry ( i ) . getValue ( ) ) ; } } @ Test public void shouldSetAtSpecificSequence ( ) throws Exception { long expectedSequence = ; ForceFillProducerBarrier < StubEntry > forceFillProducerBarrier = ringBuffer . createForceFillProducerBarrier ( new NoOpConsumer ( ringBuffer ) ) ; StubEntry expectedEntry = forceFillProducerBarrier . claimEntry ( expectedSequence ) ; expectedEntry . setValue ( ( int ) expectedSequence ) ; forceFillProducerBarrier . commit ( expectedEntry ) ; long sequence = consumerBarrier . waitFor ( expectedSequence ) ; assertEquals ( expectedSequence , sequence ) ; StubEntry entry = ringBuffer . getEntry ( sequence ) ; assertEquals ( expectedEntry , entry ) ; assertEquals ( expectedSequence , ringBuffer . getCursor ( ) ) ; } @ Test public void shouldPreventProducersOvertakingConsumerWrapPoint ( ) throws InterruptedException { final int ringBufferSize = ; final CountDownLatch latch = new CountDownLatch ( ringBufferSize ) ; final AtomicBoolean producerComplete = new AtomicBoolean ( false ) ; final RingBuffer < StubEntry > ringBuffer = new RingBuffer < StubEntry > ( StubEntry . ENTRY_FACTORY , ringBufferSize ) ; final TestConsumer consumer = new TestConsumer ( ringBuffer . createConsumerBarrier ( ) ) ; final ProducerBarrier < StubEntry > producerBarrier = ringBuffer . createProducerBarrier ( consumer ) ; Thread thread = new Thread ( new Runnable ( ) { @ Override public void run ( ) { for ( int i = ; i <= ringBufferSize ; i ++ ) { StubEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( i ) ; producerBarrier . commit ( entry ) ; latch . countDown ( ) ; } producerComplete . set ( true ) ; } } ) ; thread . start ( ) ; latch . await ( ) ; assertThat ( Long . valueOf ( ringBuffer . getCursor ( ) ) , is ( Long . valueOf ( ringBufferSize - ) ) ) ; assertFalse ( producerComplete . get ( ) ) ; consumer . run ( ) ; thread . join ( ) ; assertTrue ( producerComplete . get ( ) ) ; } private Future < List < StubEntry > > getMessages ( final long initial , final long toWaitFor ) throws InterruptedException , BrokenBarrierException { final CyclicBarrier cyclicBarrier = new CyclicBarrier ( ) ; final ConsumerBarrier < StubEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; final Future < List < StubEntry > > f = EXECUTOR . submit ( new TestWaiter ( cyclicBarrier , consumerBarrier , initial , toWaitFor ) ) ; cyclicBarrier . await ( ) ; return f ; } private static final class TestConsumer implements Consumer { private final ConsumerBarrier < StubEntry > consumerBarrier ; private volatile long sequence = RingBuffer . INITIAL_CURSOR_VALUE ; public TestConsumer ( final ConsumerBarrier < StubEntry > consumerBarrier ) { this . consumerBarrier = consumerBarrier ; } @ Override public long getSequence ( ) { return sequence ; } @ Override public void halt ( ) { } @ Override public void run ( ) { try { consumerBarrier . waitFor ( ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } ++ sequence ; } } } package com . lmax . disruptor ; import com . lmax . disruptor . support . StubEntry ; import org . junit . Assert ; import org . junit . Test ; public final class EntryTranslatorTest { private static final String TEST_VALUE = "" ; @ Test public void shouldTranslateOtherDataIntoAnEntry ( ) { StubEntry entry = StubEntry . ENTRY_FACTORY . create ( ) ; EntryTranslator < StubEntry > entryTranslator = new ExampleEntryTranslator ( TEST_VALUE ) ; entry = entryTranslator . translateTo ( entry ) ; Assert . assertEquals ( TEST_VALUE , entry . getTestString ( ) ) ; } public static final class ExampleEntryTranslator implements EntryTranslator < StubEntry > { private final String testValue ; public ExampleEntryTranslator ( final String testValue ) { this . testValue = testValue ; } @ Override public StubEntry translateTo ( final StubEntry entry ) { entry . setTestString ( testValue ) ; return entry ; } } } package com . lmax . disruptor ; import com . lmax . disruptor . support . StubEntry ; import org . junit . Test ; import java . util . concurrent . CountDownLatch ; import static org . junit . Assert . assertEquals ; public class BatchConsumerSequenceTrackingCallbackTest { private final CountDownLatch callbackLatch = new CountDownLatch ( ) ; private final CountDownLatch onEndOfBatchLatch = new CountDownLatch ( ) ; @ Test public void shouldReportProgressByUpdatingSequenceViaCallback ( ) throws Exception { final RingBuffer < StubEntry > ringBuffer = new RingBuffer < StubEntry > ( StubEntry . ENTRY_FACTORY , ) ; final ConsumerBarrier < StubEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; final SequenceTrackingHandler < StubEntry > handler = new TestSequenceTrackingHandler ( ) ; final BatchConsumer < StubEntry > batchConsumer = new BatchConsumer < StubEntry > ( consumerBarrier , handler ) ; final ProducerBarrier < StubEntry > producerBarrier = ringBuffer . createProducerBarrier ( batchConsumer ) ; Thread thread = new Thread ( batchConsumer ) ; thread . setDaemon ( true ) ; thread . start ( ) ; assertEquals ( - , batchConsumer . getSequence ( ) ) ; producerBarrier . commit ( producerBarrier . nextEntry ( ) ) ; callbackLatch . await ( ) ; assertEquals ( , batchConsumer . getSequence ( ) ) ; onEndOfBatchLatch . countDown ( ) ; assertEquals ( , batchConsumer . getSequence ( ) ) ; batchConsumer . halt ( ) ; thread . join ( ) ; } private class TestSequenceTrackingHandler implements SequenceTrackingHandler < StubEntry > { private BatchConsumer . SequenceTrackerCallback sequenceTrackerCallback ; @ Override public void setSequenceTrackerCallback ( final BatchConsumer . SequenceTrackerCallback sequenceTrackerCallback ) { this . sequenceTrackerCallback = sequenceTrackerCallback ; } @ Override public void onAvailable ( final StubEntry entry ) throws Exception { sequenceTrackerCallback . onCompleted ( entry . getSequence ( ) ) ; callbackLatch . countDown ( ) ; } @ Override public void onEndOfBatch ( ) throws Exception { onEndOfBatchLatch . await ( ) ; } } } package com . lmax . disruptor . support ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . Callable ; import java . util . concurrent . CyclicBarrier ; import org . junit . Ignore ; import com . lmax . disruptor . ConsumerBarrier ; @ Ignore public final class TestWaiter implements Callable < List < StubEntry > > { private final long toWaitForSequence ; private final long initialSequence ; private final CyclicBarrier cyclicBarrier ; private final ConsumerBarrier < StubEntry > consumerBarrier ; public TestWaiter ( final CyclicBarrier cyclicBarrier , final ConsumerBarrier < StubEntry > consumerBarrier , final long initialSequence , final long toWaitForSequence ) { this . cyclicBarrier = cyclicBarrier ; this . initialSequence = initialSequence ; this . toWaitForSequence = toWaitForSequence ; this . consumerBarrier = consumerBarrier ; } @ Override public List < StubEntry > call ( ) throws Exception { this . cyclicBarrier . await ( ) ; this . consumerBarrier . waitFor ( this . toWaitForSequence ) ; final List < StubEntry > messages = new ArrayList < StubEntry > ( ) ; for ( long l = this . initialSequence ; l <= this . toWaitForSequence ; l ++ ) { messages . add ( this . consumerBarrier . getEntry ( l ) ) ; } return messages ; } } package com . lmax . disruptor . support ; import java . util . concurrent . ThreadFactory ; public final class DaemonThreadFactory implements ThreadFactory { @ Override public Thread newThread ( final Runnable r ) { Thread t = new Thread ( r ) ; t . setDaemon ( true ) ; return t ; } } package com . lmax . disruptor . support ; import org . junit . Ignore ; import com . lmax . disruptor . AbstractEntry ; import com . lmax . disruptor . EntryFactory ; @ Ignore public final class TestEntry extends AbstractEntry { @ Override public String toString ( ) { return "" ; } public final static EntryFactory < TestEntry > ENTRY_FACTORY = new EntryFactory < TestEntry > ( ) { @ Override public TestEntry create ( ) { return new TestEntry ( ) ; } } ; } package com . lmax . disruptor . support ; import com . lmax . disruptor . AbstractEntry ; import com . lmax . disruptor . EntryFactory ; public final class StubEntry extends AbstractEntry { private int value ; private String testString ; public StubEntry ( int i ) { this . value = i ; } public void copy ( StubEntry entry ) { value = entry . value ; } public int getValue ( ) { return value ; } public void setValue ( int value ) { this . value = value ; } public String getTestString ( ) { return testString ; } public void setTestString ( final String testString ) { this . testString = testString ; } public final static EntryFactory < StubEntry > ENTRY_FACTORY = new EntryFactory < StubEntry > ( ) { public StubEntry create ( ) { return new StubEntry ( - ) ; } } ; @ Override public int hashCode ( ) { final int prime = ; int result = ; result = prime * result + value ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; StubEntry other = ( StubEntry ) obj ; return value == other . value ; } } package com . lmax . disruptor . support ; import org . jmock . api . Action ; import org . jmock . api . Invocation ; import org . jmock . lib . action . CustomAction ; import java . util . concurrent . CountDownLatch ; public final class Actions { public static Action countDown ( final CountDownLatch latch ) { return new CustomAction ( "" ) { public Object invoke ( Invocation invocation ) throws Throwable { latch . countDown ( ) ; return null ; } } ; } } package com . lmax . disruptor ; import com . lmax . disruptor . support . StubEntry ; import org . hamcrest . Description ; import org . jmock . Expectations ; import org . jmock . Mockery ; import org . jmock . Sequence ; import org . jmock . api . Action ; import org . jmock . api . Invocation ; import org . jmock . integration . junit4 . JMock ; import org . junit . Test ; import org . junit . runner . RunWith ; import java . util . concurrent . CountDownLatch ; import static com . lmax . disruptor . support . Actions . countDown ; import static org . junit . Assert . assertEquals ; @ RunWith ( JMock . class ) public final class BatchConsumerTest { private final Mockery context = new Mockery ( ) ; private final Sequence lifecycleSequence = context . sequence ( "" ) ; private final CountDownLatch latch = new CountDownLatch ( ) ; private final RingBuffer < StubEntry > ringBuffer = new RingBuffer < StubEntry > ( StubEntry . ENTRY_FACTORY , ) ; private final ConsumerBarrier < StubEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; @ SuppressWarnings ( "" ) private final BatchHandler < StubEntry > batchHandler = context . mock ( BatchHandler . class ) ; private final BatchConsumer batchConsumer = new BatchConsumer < StubEntry > ( consumerBarrier , batchHandler ) ; private final ProducerBarrier < StubEntry > producerBarrier = ringBuffer . createProducerBarrier ( batchConsumer ) ; @ Test ( expected = NullPointerException . class ) public void shouldThrowExceptionOnSettingNullExceptionHandler ( ) { batchConsumer . setExceptionHandler ( null ) ; } @ Test public void shouldReturnUnderlyingBarrier ( ) { assertEquals ( consumerBarrier , batchConsumer . getConsumerBarrier ( ) ) ; } @ Test public void shouldCallMethodsInLifecycleOrder ( ) throws Exception { context . checking ( new Expectations ( ) { { oneOf ( batchHandler ) . onAvailable ( ringBuffer . getEntry ( ) ) ; inSequence ( lifecycleSequence ) ; oneOf ( batchHandler ) . onEndOfBatch ( ) ; inSequence ( lifecycleSequence ) ; will ( countDown ( latch ) ) ; } } ) ; Thread thread = new Thread ( batchConsumer ) ; thread . start ( ) ; assertEquals ( - , batchConsumer . getSequence ( ) ) ; producerBarrier . commit ( producerBarrier . nextEntry ( ) ) ; latch . await ( ) ; batchConsumer . halt ( ) ; thread . join ( ) ; } @ Test public void shouldCallMethodsInLifecycleOrderForBatch ( ) throws Exception { context . checking ( new Expectations ( ) { { oneOf ( batchHandler ) . onAvailable ( ringBuffer . getEntry ( ) ) ; inSequence ( lifecycleSequence ) ; oneOf ( batchHandler ) . onAvailable ( ringBuffer . getEntry ( ) ) ; inSequence ( lifecycleSequence ) ; oneOf ( batchHandler ) . onAvailable ( ringBuffer . getEntry ( ) ) ; inSequence ( lifecycleSequence ) ; oneOf ( batchHandler ) . onEndOfBatch ( ) ; inSequence ( lifecycleSequence ) ; will ( countDown ( latch ) ) ; } } ) ; producerBarrier . commit ( producerBarrier . nextEntry ( ) ) ; producerBarrier . commit ( producerBarrier . nextEntry ( ) ) ; producerBarrier . commit ( producerBarrier . nextEntry ( ) ) ; Thread thread = new Thread ( batchConsumer ) ; thread . start ( ) ; latch . await ( ) ; batchConsumer . halt ( ) ; thread . join ( ) ; } @ Test public void shouldCallExceptionHandlerOnUncaughtException ( ) throws Exception { final Exception ex = new Exception ( ) ; final ExceptionHandler exceptionHandler = context . mock ( ExceptionHandler . class ) ; batchConsumer . setExceptionHandler ( exceptionHandler ) ; context . checking ( new Expectations ( ) { { oneOf ( batchHandler ) . onAvailable ( ringBuffer . getEntry ( ) ) ; inSequence ( lifecycleSequence ) ; will ( new Action ( ) { @ Override public Object invoke ( final Invocation invocation ) throws Throwable { throw ex ; } @ Override public void describeTo ( final Description description ) { description . appendText ( "" ) ; } } ) ; oneOf ( exceptionHandler ) . handle ( ex , ringBuffer . getEntry ( ) ) ; inSequence ( lifecycleSequence ) ; will ( countDown ( latch ) ) ; } } ) ; Thread thread = new Thread ( batchConsumer ) ; thread . start ( ) ; producerBarrier . commit ( producerBarrier . nextEntry ( ) ) ; latch . await ( ) ; batchConsumer . halt ( ) ; thread . join ( ) ; } } package com . lmax . disruptor ; import com . lmax . disruptor . support . TestEntry ; import org . jmock . Expectations ; import org . jmock . Mockery ; import org . jmock . integration . junit4 . JMock ; import org . jmock . lib . legacy . ClassImposteriser ; import org . junit . Test ; import org . junit . runner . RunWith ; import java . util . logging . Level ; import java . util . logging . Logger ; @ RunWith ( JMock . class ) public final class IgnoreExceptionHandlerTest { private final Mockery context = new Mockery ( ) ; public IgnoreExceptionHandlerTest ( ) { context . setImposteriser ( ClassImposteriser . INSTANCE ) ; } @ Test public void shouldHandleAndIgnoreException ( ) { final Exception ex = new Exception ( ) ; final AbstractEntry entry = new TestEntry ( ) ; final Logger logger = context . mock ( Logger . class ) ; context . checking ( new Expectations ( ) { { oneOf ( logger ) . log ( Level . INFO , "" + entry , ex ) ; } } ) ; ExceptionHandler exceptionHandler = new IgnoreExceptionHandler ( logger ) ; exceptionHandler . handle ( ex , entry ) ; } } package com . lmax . disruptor ; import static com . lmax . disruptor . support . Actions . countDown ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import java . util . concurrent . CountDownLatch ; import java . util . concurrent . TimeUnit ; import com . lmax . disruptor . support . StubEntry ; import org . jmock . Expectations ; import org . jmock . Mockery ; import org . jmock . integration . junit4 . JMock ; import org . jmock . lib . action . DoAllAction ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; @ RunWith ( JMock . class ) public final class ConsumerBarrierTest { private Mockery context ; private RingBuffer < StubEntry > ringBuffer ; private Consumer consumer1 ; private Consumer consumer2 ; private Consumer consumer3 ; private ConsumerBarrier < StubEntry > consumerBarrier ; private ProducerBarrier < StubEntry > producerBarrier ; @ Before public void setUp ( ) { context = new Mockery ( ) ; ringBuffer = new RingBuffer < StubEntry > ( StubEntry . ENTRY_FACTORY , ) ; consumer1 = context . mock ( Consumer . class , "" ) ; consumer2 = context . mock ( Consumer . class , "" ) ; consumer3 = context . mock ( Consumer . class , "" ) ; consumerBarrier = ringBuffer . createConsumerBarrier ( consumer1 , consumer2 , consumer3 ) ; producerBarrier = ringBuffer . createProducerBarrier ( new NoOpConsumer ( ringBuffer ) ) ; } @ Test public void shouldWaitForWorkCompleteWhereCompleteWorkThresholdIsAhead ( ) throws Exception { final long expectedNumberMessages = ; final long expectedWorkSequence = ; fillRingBuffer ( expectedNumberMessages ) ; context . checking ( new Expectations ( ) { { one ( consumer1 ) . getSequence ( ) ; will ( returnValue ( Long . valueOf ( expectedNumberMessages ) ) ) ; one ( consumer2 ) . getSequence ( ) ; will ( returnValue ( Long . valueOf ( expectedWorkSequence ) ) ) ; one ( consumer3 ) . getSequence ( ) ; will ( returnValue ( Long . valueOf ( expectedWorkSequence ) ) ) ; } } ) ; long completedWorkSequence = consumerBarrier . waitFor ( expectedWorkSequence ) ; assertTrue ( completedWorkSequence >= expectedWorkSequence ) ; } @ Test public void shouldWaitForWorkCompleteWhereAllWorkersAreBlockedOnRingBuffer ( ) throws Exception { long expectedNumberMessages = ; fillRingBuffer ( expectedNumberMessages ) ; final StubConsumer [ ] workers = new StubConsumer [ ] ; for ( int i = , size = workers . length ; i < size ; i ++ ) { workers [ i ] = new StubConsumer ( ) ; workers [ i ] . setSequence ( expectedNumberMessages - ) ; } final ConsumerBarrier consumerBarrier = ringBuffer . createConsumerBarrier ( workers ) ; Runnable runnable = new Runnable ( ) { public void run ( ) { StubEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( ( int ) entry . getSequence ( ) ) ; producerBarrier . commit ( entry ) ; for ( StubConsumer stubWorker : workers ) { stubWorker . setSequence ( entry . getSequence ( ) ) ; } } } ; new Thread ( runnable ) . start ( ) ; long expectedWorkSequence = expectedNumberMessages ; long completedWorkSequence = consumerBarrier . waitFor ( expectedNumberMessages ) ; assertTrue ( completedWorkSequence >= expectedWorkSequence ) ; } @ Test public void shouldInterruptDuringBusySpin ( ) throws Exception { final long expectedNumberMessages = ; fillRingBuffer ( expectedNumberMessages ) ; final CountDownLatch latch = new CountDownLatch ( ) ; context . checking ( new Expectations ( ) { { allowing ( consumer1 ) . getSequence ( ) ; will ( new DoAllAction ( countDown ( latch ) , returnValue ( Long . valueOf ( ) ) ) ) ; allowing ( consumer2 ) . getSequence ( ) ; will ( new DoAllAction ( countDown ( latch ) , returnValue ( Long . valueOf ( ) ) ) ) ; allowing ( consumer3 ) . getSequence ( ) ; will ( new DoAllAction ( countDown ( latch ) , returnValue ( Long . valueOf ( ) ) ) ) ; } } ) ; final boolean [ ] alerted = { false } ; Thread t = new Thread ( new Runnable ( ) { public void run ( ) { try { consumerBarrier . waitFor ( expectedNumberMessages - ) ; } catch ( AlertException e ) { alerted [ ] = true ; } catch ( InterruptedException e ) { } } } ) ; t . start ( ) ; assertTrue ( latch . await ( , TimeUnit . SECONDS ) ) ; consumerBarrier . alert ( ) ; t . join ( ) ; assertTrue ( "" , alerted [ ] ) ; } @ Test public void shouldWaitForWorkCompleteWhereCompleteWorkThresholdIsBehind ( ) throws Exception { long expectedNumberMessages = ; fillRingBuffer ( expectedNumberMessages ) ; final StubConsumer [ ] entryConsumers = new StubConsumer [ ] ; for ( int i = , size = entryConsumers . length ; i < size ; i ++ ) { entryConsumers [ i ] = new StubConsumer ( ) ; entryConsumers [ i ] . setSequence ( expectedNumberMessages - ) ; } final ConsumerBarrier consumerBarrier = ringBuffer . createConsumerBarrier ( entryConsumers ) ; Runnable runnable = new Runnable ( ) { public void run ( ) { for ( StubConsumer stubWorker : entryConsumers ) { stubWorker . setSequence ( stubWorker . getSequence ( ) + ) ; } } } ; new Thread ( runnable ) . start ( ) ; long expectedWorkSequence = expectedNumberMessages - ; long completedWorkSequence = consumerBarrier . waitFor ( expectedWorkSequence ) ; assertTrue ( completedWorkSequence >= expectedWorkSequence ) ; } @ Test public void shouldSetAndClearAlertStatus ( ) { assertFalse ( consumerBarrier . isAlerted ( ) ) ; consumerBarrier . alert ( ) ; assertTrue ( consumerBarrier . isAlerted ( ) ) ; consumerBarrier . clearAlert ( ) ; assertFalse ( consumerBarrier . isAlerted ( ) ) ; } private void fillRingBuffer ( long expectedNumberMessages ) throws InterruptedException { for ( long i = ; i < expectedNumberMessages ; i ++ ) { StubEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( ( int ) i ) ; producerBarrier . commit ( entry ) ; } } private static final class StubConsumer implements Consumer { private volatile long sequence ; public void setSequence ( long sequence ) { this . sequence = sequence ; } @ Override public long getSequence ( ) { return sequence ; } @ Override public void halt ( ) { } @ Override public void run ( ) { } } } package com . lmax . disruptor ; import org . jmock . Expectations ; import org . jmock . Mockery ; import org . jmock . integration . junit4 . JMock ; import org . junit . Assert ; import org . junit . Test ; import org . junit . runner . RunWith ; @ RunWith ( JMock . class ) public final class UtilTest { private final Mockery context = new Mockery ( ) ; @ Test public void shouldReturnNextPowerOfTwo ( ) { int powerOfTwo = Util . ceilingNextPowerOfTwo ( ) ; Assert . assertEquals ( , powerOfTwo ) ; } @ Test public void shouldReturnExactPowerOfTwo ( ) { int powerOfTwo = Util . ceilingNextPowerOfTwo ( ) ; Assert . assertEquals ( , powerOfTwo ) ; } @ Test public void shouldReturnMinimumSequence ( ) { final Consumer [ ] consumers = new Consumer [ ] ; consumers [ ] = context . mock ( Consumer . class , "" ) ; consumers [ ] = context . mock ( Consumer . class , "" ) ; consumers [ ] = context . mock ( Consumer . class , "" ) ; context . checking ( new Expectations ( ) { { oneOf ( consumers [ ] ) . getSequence ( ) ; will ( returnValue ( Long . valueOf ( ) ) ) ; oneOf ( consumers [ ] ) . getSequence ( ) ; will ( returnValue ( Long . valueOf ( ) ) ) ; oneOf ( consumers [ ] ) . getSequence ( ) ; will ( returnValue ( Long . valueOf ( ) ) ) ; } } ) ; Assert . assertEquals ( , Util . getMinimumSequence ( consumers ) ) ; } @ Test public void shouldReturnLongMaxWhenNoConsumers ( ) { final Consumer [ ] consumers = new Consumer [ ] ; Assert . assertEquals ( Long . MAX_VALUE , Util . getMinimumSequence ( consumers ) ) ; } } package com . lmax . disruptor . collections ; import org . junit . Test ; import java . math . BigDecimal ; import static org . hamcrest . core . Is . is ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertThat ; import static org . junit . Assert . assertTrue ; public final class HistogramTest { public static final long [ ] INTERVALS = new long [ ] { , , , , Long . MAX_VALUE } ; private Histogram histogram = new Histogram ( INTERVALS ) ; @ Test public void shouldSizeBasedOnBucketConfiguration ( ) { assertThat ( Long . valueOf ( histogram . getSize ( ) ) , is ( Long . valueOf ( INTERVALS . length ) ) ) ; } @ Test public void shouldWalkIntervals ( ) { for ( int i = , size = histogram . getSize ( ) ; i < size ; i ++ ) { assertThat ( Long . valueOf ( histogram . getUpperBoundAt ( i ) ) , is ( Long . valueOf ( INTERVALS [ i ] ) ) ) ; } } @ Test public void shouldConfirmIntervalsAreInitialised ( ) { for ( int i = , size = histogram . getSize ( ) ; i < size ; i ++ ) { assertThat ( Long . valueOf ( histogram . getCountAt ( i ) ) , is ( Long . valueOf ( ) ) ) ; } } @ Test ( expected = IllegalArgumentException . class ) public void shouldThrowExceptionWhenIntervalLessThanOrEqualToZero ( ) { new Histogram ( new long [ ] { - , , } ) ; } @ Test ( expected = IllegalArgumentException . class ) public void shouldThrowExceptionWhenIntervalDoNotIncrease ( ) { new Histogram ( new long [ ] { , , , } ) ; } @ Test public void shouldAddObservation ( ) { assertTrue ( histogram . addObservation ( ) ) ; assertThat ( Long . valueOf ( histogram . getCountAt ( ) ) , is ( Long . valueOf ( ) ) ) ; } @ Test public void shouldNotAddObservation ( ) { Histogram histogram = new Histogram ( new long [ ] { , , } ) ; assertFalse ( histogram . addObservation ( ) ) ; } @ Test public void shouldAddObservations ( ) { addObservations ( histogram , , , ) ; Histogram histogram2 = new Histogram ( INTERVALS ) ; addObservations ( histogram2 , , , ) ; histogram . addObservations ( histogram2 ) ; assertThat ( Long . valueOf ( ) , is ( Long . valueOf ( histogram . getCount ( ) ) ) ) ; } @ Test ( expected = IllegalArgumentException . class ) public void shouldThrowExceptionWhenIntervalsDoNotMatch ( ) { Histogram histogram2 = new Histogram ( new long [ ] { , , } ) ; histogram . addObservations ( histogram2 ) ; } @ Test public void shouldClearCounts ( ) { addObservations ( histogram , , , , ) ; histogram . clear ( ) ; for ( int i = , size = histogram . getSize ( ) ; i < size ; i ++ ) { assertThat ( Long . valueOf ( histogram . getCountAt ( i ) ) , is ( Long . valueOf ( ) ) ) ; } } @ Test public void shouldCountTotalObservations ( ) { addObservations ( histogram , , , , ) ; assertThat ( Long . valueOf ( histogram . getCount ( ) ) , is ( Long . valueOf ( ) ) ) ; } @ Test public void shouldGetMeanObservation ( ) { final long [ ] INTERVALS = new long [ ] { , , , , } ; final Histogram histogram = new Histogram ( INTERVALS ) ; addObservations ( histogram , , , , , , ) ; assertThat ( histogram . getMean ( ) , is ( new BigDecimal ( "" ) ) ) ; } @ Test public void shouldCorrectMeanForSkewInTopAndBottomPopulatedIntervals ( ) { final long [ ] INTERVALS = new long [ ] { , , , , , , , } ; final Histogram histogram = new Histogram ( INTERVALS ) ; for ( long i = ; i < ; i ++ ) { histogram . addObservation ( i ) ; } assertThat ( histogram . getMean ( ) , is ( new BigDecimal ( "" ) ) ) ; } @ Test public void shouldGetMaxObservation ( ) { addObservations ( histogram , , , , , , ) ; assertThat ( Long . valueOf ( histogram . getMax ( ) ) , is ( Long . valueOf ( ) ) ) ; } @ Test public void shouldGetMinObservation ( ) { addObservations ( histogram , , , , , , ) ; assertThat ( Long . valueOf ( histogram . getMin ( ) ) , is ( Long . valueOf ( ) ) ) ; } @ Test public void shouldGetTwoNinesUpperBound ( ) { final long [ ] INTERVALS = new long [ ] { , , , , } ; final Histogram histogram = new Histogram ( INTERVALS ) ; for ( long i = ; i < ; i ++ ) { histogram . addObservation ( i ) ; } assertThat ( Long . valueOf ( histogram . getTwoNinesUpperBound ( ) ) , is ( Long . valueOf ( ) ) ) ; } @ Test public void shouldGetFourNinesUpperBound ( ) { final long [ ] INTERVALS = new long [ ] { , , , , } ; final Histogram histogram = new Histogram ( INTERVALS ) ; for ( long i = ; i < ; i ++ ) { histogram . addObservation ( i ) ; } assertThat ( Long . valueOf ( histogram . getFourNinesUpperBound ( ) ) , is ( Long . valueOf ( ) ) ) ; } @ Test public void shouldToString ( ) { addObservations ( histogram , , , , ) ; String expectedResults = "" ; assertThat ( histogram . toString ( ) , is ( expectedResults ) ) ; } private void addObservations ( final Histogram histogram , final long ... observations ) { for ( int i = , size = observations . length ; i < size ; i ++ ) { histogram . addObservation ( observations [ i ] ) ; } } } package com . lmax . disruptor ; import com . lmax . disruptor . support . StubEntry ; import org . junit . Test ; import java . util . concurrent . CountDownLatch ; import static org . hamcrest . core . Is . is ; import static org . junit . Assert . assertThat ; public final class LifecycleAwareTest { private final CountDownLatch startLatch = new CountDownLatch ( ) ; private final CountDownLatch shutdownLatch = new CountDownLatch ( ) ; private final RingBuffer < StubEntry > ringBuffer = new RingBuffer < StubEntry > ( StubEntry . ENTRY_FACTORY , ) ; private final ConsumerBarrier < StubEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final LifecycleAwareBatchHandler handler = new LifecycleAwareBatchHandler ( ) ; private final BatchConsumer batchConsumer = new BatchConsumer < StubEntry > ( consumerBarrier , handler ) ; @ Test public void shouldNotifyOfBatchConsumerLifecycle ( ) throws Exception { new Thread ( batchConsumer ) . start ( ) ; startLatch . await ( ) ; batchConsumer . halt ( ) ; shutdownLatch . await ( ) ; assertThat ( Integer . valueOf ( handler . startCounter ) , is ( Integer . valueOf ( ) ) ) ; assertThat ( Integer . valueOf ( handler . shutdownCounter ) , is ( Integer . valueOf ( ) ) ) ; } private final class LifecycleAwareBatchHandler implements BatchHandler < StubEntry > , LifecycleAware { private int startCounter = ; private int shutdownCounter = ; @ Override public void onAvailable ( final StubEntry entry ) throws Exception { } @ Override public void onEndOfBatch ( ) throws Exception { } @ Override public void onStart ( ) { ++ startCounter ; startLatch . countDown ( ) ; } @ Override public void onShutdown ( ) { ++ shutdownCounter ; shutdownLatch . countDown ( ) ; } } } package com . lmax . disruptor ; public interface LifecycleAware { void onStart ( ) ; void onShutdown ( ) ; } package com . lmax . disruptor ; public interface ExceptionHandler { void handle ( Exception ex , AbstractEntry currentEntry ) ; } package com . lmax . disruptor ; public abstract class AbstractEntry { private long sequence ; public final long getSequence ( ) { return sequence ; } final void setSequence ( final long sequence ) { this . sequence = sequence ; } } package com . lmax . disruptor ; public interface EntryFactory < T extends AbstractEntry > { T create ( ) ; } package com . lmax . disruptor ; import java . util . logging . Level ; import java . util . logging . Logger ; public final class FatalExceptionHandler implements ExceptionHandler { private final static Logger LOGGER = Logger . getLogger ( FatalExceptionHandler . class . getName ( ) ) ; private final Logger logger ; public FatalExceptionHandler ( ) { this . logger = LOGGER ; } public FatalExceptionHandler ( final Logger logger ) { this . logger = logger ; } @ Override public void handle ( final Exception ex , final AbstractEntry currentEntry ) { logger . log ( Level . SEVERE , "" + currentEntry , ex ) ; throw new RuntimeException ( ex ) ; } } package com . lmax . disruptor ; import java . util . logging . Level ; import java . util . logging . Logger ; public final class IgnoreExceptionHandler implements ExceptionHandler { private final static Logger LOGGER = Logger . getLogger ( IgnoreExceptionHandler . class . getName ( ) ) ; private final Logger logger ; public IgnoreExceptionHandler ( ) { this . logger = LOGGER ; } public IgnoreExceptionHandler ( final Logger logger ) { this . logger = logger ; } @ Override public void handle ( final Exception ex , final AbstractEntry currentEntry ) { logger . log ( Level . INFO , "" + currentEntry , ex ) ; } } package com . lmax . disruptor ; import java . util . concurrent . TimeUnit ; import static com . lmax . disruptor . Util . ceilingNextPowerOfTwo ; import static com . lmax . disruptor . Util . getMinimumSequence ; public final class RingBuffer < T extends AbstractEntry > { public static final long INITIAL_CURSOR_VALUE = - ; public long p1 , p2 , p3 , p4 , p5 , p6 , p7 ; private volatile long cursor = INITIAL_CURSOR_VALUE ; public long p8 , p9 , p10 , p11 , p12 , p13 , p14 ; private final AbstractEntry [ ] entries ; private final int ringModMask ; private final ClaimStrategy claimStrategy ; private final ClaimStrategy . Option claimStrategyOption ; private final WaitStrategy waitStrategy ; public RingBuffer ( final EntryFactory < T > entryFactory , final int size , final ClaimStrategy . Option claimStrategyOption , final WaitStrategy . Option waitStrategyOption ) { int sizeAsPowerOfTwo = ceilingNextPowerOfTwo ( size ) ; ringModMask = sizeAsPowerOfTwo - ; entries = new AbstractEntry [ sizeAsPowerOfTwo ] ; this . claimStrategyOption = claimStrategyOption ; claimStrategy = claimStrategyOption . newInstance ( ) ; waitStrategy = waitStrategyOption . newInstance ( ) ; fill ( entryFactory ) ; } public RingBuffer ( final EntryFactory < T > entryFactory , final int size ) { this ( entryFactory , size , ClaimStrategy . Option . MULTI_THREADED , WaitStrategy . Option . BLOCKING ) ; } public ConsumerBarrier < T > createConsumerBarrier ( final Consumer ... consumersToTrack ) { return new ConsumerTrackingConsumerBarrier ( consumersToTrack ) ; } public ProducerBarrier < T > createProducerBarrier ( final Consumer ... consumersToTrack ) { return new ConsumerTrackingProducerBarrier ( consumersToTrack ) ; } public ForceFillProducerBarrier < T > createForceFillProducerBarrier ( final Consumer ... consumersToTrack ) { return new ForceFillConsumerTrackingProducerBarrier ( consumersToTrack ) ; } public int getCapacity ( ) { return entries . length ; } public long getCursor ( ) { return cursor ; } @ SuppressWarnings ( "" ) public T getEntry ( final long sequence ) { return ( T ) entries [ ( int ) sequence & ringModMask ] ; } private void fill ( final EntryFactory < T > entryFactory ) { for ( int i = ; i < entries . length ; i ++ ) { entries [ i ] = entryFactory . create ( ) ; } } private final class ConsumerTrackingConsumerBarrier implements ConsumerBarrier < T > { private volatile boolean alerted = false ; private final Consumer [ ] consumers ; public ConsumerTrackingConsumerBarrier ( final Consumer ... consumers ) { this . consumers = consumers ; } @ Override @ SuppressWarnings ( "" ) public T getEntry ( final long sequence ) { return ( T ) entries [ ( int ) sequence & ringModMask ] ; } @ Override public long waitFor ( final long sequence ) throws AlertException , InterruptedException { return waitStrategy . waitFor ( consumers , RingBuffer . this , this , sequence ) ; } @ Override public long waitFor ( final long sequence , final long timeout , final TimeUnit units ) throws AlertException , InterruptedException { return waitStrategy . waitFor ( consumers , RingBuffer . this , this , sequence , timeout , units ) ; } @ Override public long getCursor ( ) { return cursor ; } @ Override public boolean isAlerted ( ) { return alerted ; } @ Override public void alert ( ) { alerted = true ; waitStrategy . signalAll ( ) ; } @ Override public void clearAlert ( ) { alerted = false ; } } private final class ConsumerTrackingProducerBarrier implements ProducerBarrier < T > { private final Consumer [ ] consumers ; private long lastConsumerMinimum = RingBuffer . INITIAL_CURSOR_VALUE ; public ConsumerTrackingProducerBarrier ( final Consumer ... consumers ) { if ( == consumers . length ) { throw new IllegalArgumentException ( "" ) ; } this . consumers = consumers ; } @ Override @ SuppressWarnings ( "" ) public T nextEntry ( ) { final long sequence = claimStrategy . incrementAndGet ( ) ; ensureConsumersAreInRange ( sequence ) ; AbstractEntry entry = entries [ ( int ) sequence & ringModMask ] ; entry . setSequence ( sequence ) ; return ( T ) entry ; } @ Override public void commit ( final T entry ) { commit ( entry . getSequence ( ) , ) ; } @ Override public SequenceBatch nextEntries ( final SequenceBatch sequenceBatch ) { final long sequence = claimStrategy . incrementAndGet ( sequenceBatch . getSize ( ) ) ; sequenceBatch . setEnd ( sequence ) ; ensureConsumersAreInRange ( sequence ) ; for ( long i = sequenceBatch . getStart ( ) , end = sequenceBatch . getEnd ( ) ; i <= end ; i ++ ) { AbstractEntry entry = entries [ ( int ) i & ringModMask ] ; entry . setSequence ( i ) ; } return sequenceBatch ; } @ Override public void commit ( final SequenceBatch sequenceBatch ) { commit ( sequenceBatch . getEnd ( ) , sequenceBatch . getSize ( ) ) ; } @ Override @ SuppressWarnings ( "" ) public T getEntry ( final long sequence ) { return ( T ) entries [ ( int ) sequence & ringModMask ] ; } @ Override public long getCursor ( ) { return cursor ; } private void ensureConsumersAreInRange ( final long sequence ) { final long wrapPoint = sequence - entries . length ; while ( wrapPoint > lastConsumerMinimum && wrapPoint > ( lastConsumerMinimum = getMinimumSequence ( consumers ) ) ) { Thread . yield ( ) ; } } private void commit ( final long sequence , final long batchSize ) { if ( ClaimStrategy . Option . MULTI_THREADED == claimStrategyOption ) { final long expectedSequence = sequence - batchSize ; while ( expectedSequence != cursor ) { } } cursor = sequence ; waitStrategy . signalAll ( ) ; } } private final class ForceFillConsumerTrackingProducerBarrier implements ForceFillProducerBarrier < T > { private final Consumer [ ] consumers ; private long lastConsumerMinimum = RingBuffer . INITIAL_CURSOR_VALUE ; public ForceFillConsumerTrackingProducerBarrier ( final Consumer ... consumers ) { if ( == consumers . length ) { throw new IllegalArgumentException ( "" ) ; } this . consumers = consumers ; } @ Override @ SuppressWarnings ( "" ) public T claimEntry ( final long sequence ) { ensureConsumersAreInRange ( sequence ) ; AbstractEntry entry = entries [ ( int ) sequence & ringModMask ] ; entry . setSequence ( sequence ) ; return ( T ) entry ; } @ Override public void commit ( final T entry ) { long sequence = entry . getSequence ( ) ; claimStrategy . setSequence ( sequence ) ; cursor = sequence ; waitStrategy . signalAll ( ) ; } @ Override public long getCursor ( ) { return cursor ; } private void ensureConsumersAreInRange ( final long sequence ) { final long wrapPoint = sequence - entries . length ; while ( wrapPoint > lastConsumerMinimum && wrapPoint > ( lastConsumerMinimum = getMinimumSequence ( consumers ) ) ) { Thread . yield ( ) ; } } } } package com . lmax . disruptor ; public final class SequenceBatch { private final int size ; private long end = RingBuffer . INITIAL_CURSOR_VALUE ; public SequenceBatch ( final int size ) { this . size = size ; } public long getEnd ( ) { return end ; } void setEnd ( final long end ) { this . end = end ; } public int getSize ( ) { return size ; } public long getStart ( ) { return end - ( size - ) ; } } package com . lmax . disruptor ; public interface ForceFillProducerBarrier < T extends AbstractEntry > { T claimEntry ( long sequence ) ; void commit ( T entry ) ; long getCursor ( ) ; } package com . lmax . disruptor ; public interface BatchHandler < T extends AbstractEntry > { void onAvailable ( T entry ) throws Exception ; void onEndOfBatch ( ) throws Exception ; } package com . lmax . disruptor . collections ; import java . math . BigDecimal ; import java . math . RoundingMode ; import java . util . Arrays ; public final class Histogram { private final long [ ] upperBounds ; private final long [ ] counts ; private long minValue = Long . MAX_VALUE ; private long maxValue = ; public Histogram ( final long [ ] upperBounds ) { validateBounds ( upperBounds ) ; this . upperBounds = Arrays . copyOf ( upperBounds , upperBounds . length ) ; this . counts = new long [ upperBounds . length ] ; } private void validateBounds ( final long [ ] upperBounds ) { long lastBound = - ; for ( final long bound : upperBounds ) { if ( bound <= ) { throw new IllegalArgumentException ( "" ) ; } if ( bound <= lastBound ) { throw new IllegalArgumentException ( "" + bound + "" + lastBound ) ; } lastBound = bound ; } } public int getSize ( ) { return upperBounds . length ; } public long getUpperBoundAt ( final int index ) { return upperBounds [ index ] ; } public long getCountAt ( final int index ) { return counts [ index ] ; } public boolean addObservation ( final long value ) { int low = ; int high = upperBounds . length - ; while ( low < high ) { int mid = low + ( ( high - low ) > > ) ; if ( upperBounds [ mid ] < value ) { low = mid + ; } else { high = mid ; } } if ( value <= upperBounds [ high ] ) { counts [ high ] ++ ; trackRange ( value ) ; return true ; } return false ; } private void trackRange ( final long value ) { if ( value < minValue ) { minValue = value ; } else if ( value > maxValue ) { maxValue = value ; } } public void addObservations ( final Histogram histogram ) { if ( upperBounds . length != histogram . upperBounds . length ) { throw new IllegalArgumentException ( "" ) ; } for ( int i = , size = upperBounds . length ; i < size ; i ++ ) { if ( upperBounds [ i ] != histogram . upperBounds [ i ] ) { throw new IllegalArgumentException ( "" ) ; } } for ( int i = , size = counts . length ; i < size ; i ++ ) { counts [ i ] += histogram . counts [ i ] ; } trackRange ( histogram . minValue ) ; trackRange ( histogram . maxValue ) ; } public void clear ( ) { maxValue = ; minValue = Long . MAX_VALUE ; for ( int i = , size = counts . length ; i < size ; i ++ ) { counts [ i ] = ; } } public long getCount ( ) { long count = ; for ( int i = , size = counts . length ; i < size ; i ++ ) { count += counts [ i ] ; } return count ; } public long getMin ( ) { return minValue ; } public long getMax ( ) { return maxValue ; } public BigDecimal getMean ( ) { if ( == getCount ( ) ) { return BigDecimal . ZERO ; } long lowerBound = counts [ ] > ? minValue : ; BigDecimal total = BigDecimal . ZERO ; for ( int i = , size = upperBounds . length ; i < size ; i ++ ) { if ( != counts [ i ] ) { long upperBound = Math . min ( upperBounds [ i ] , maxValue ) ; long midPoint = lowerBound + ( ( upperBound - lowerBound ) / ) ; BigDecimal intervalTotal = new BigDecimal ( midPoint ) . multiply ( new BigDecimal ( counts [ i ] ) ) ; total = total . add ( intervalTotal ) ; } lowerBound = Math . max ( upperBounds [ i ] + , minValue ) ; } return total . divide ( new BigDecimal ( getCount ( ) ) , , RoundingMode . HALF_UP ) ; } public long getTwoNinesUpperBound ( ) { return getUpperBoundForFactor ( ) ; } public long getFourNinesUpperBound ( ) { return getUpperBoundForFactor ( ) ; } public long getUpperBoundForFactor ( final double factor ) { if ( >= factor || factor >= ) { throw new IllegalArgumentException ( "" ) ; } final long totalCount = getCount ( ) ; final long tailTotal = totalCount - Math . round ( totalCount * factor ) ; long tailCount = ; for ( int i = counts . length - ; i >= ; i -- ) { if ( != counts [ i ] ) { tailCount += counts [ i ] ; if ( tailCount >= tailTotal ) { return upperBounds [ i ] ; } } } return ; } @ Override public String toString ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "" ) ; sb . append ( "" ) . append ( getMin ( ) ) . append ( "" ) ; sb . append ( "" ) . append ( getMax ( ) ) . append ( "" ) ; sb . append ( "" ) . append ( getMean ( ) ) . append ( "" ) ; sb . append ( "" ) . append ( getTwoNinesUpperBound ( ) ) . append ( "" ) ; sb . append ( "" ) . append ( getFourNinesUpperBound ( ) ) . append ( "" ) ; sb . append ( '' ) ; for ( int i = , size = counts . length ; i < size ; i ++ ) { sb . append ( upperBounds [ i ] ) . append ( '' ) . append ( counts [ i ] ) . append ( "" ) ; } if ( counts . length > ) { sb . setLength ( sb . length ( ) - ) ; } sb . append ( '' ) ; sb . append ( '' ) ; return sb . toString ( ) ; } } package com . lmax . disruptor ; public final class Util { public static int ceilingNextPowerOfTwo ( final int x ) { return << ( - Integer . numberOfLeadingZeros ( x - ) ) ; } public static long getMinimumSequence ( final Consumer [ ] consumers ) { long minimum = Long . MAX_VALUE ; for ( Consumer consumer : consumers ) { long sequence = consumer . getSequence ( ) ; minimum = minimum < sequence ? minimum : sequence ; } return minimum ; } } package com . lmax . disruptor ; public interface SequenceTrackingHandler < T extends AbstractEntry > extends BatchHandler < T > { void setSequenceTrackerCallback ( final BatchConsumer . SequenceTrackerCallback sequenceTrackerCallback ) ; } package com . lmax . disruptor ; public final class BatchConsumer < T extends AbstractEntry > implements Consumer { private final ConsumerBarrier < T > consumerBarrier ; private final BatchHandler < T > handler ; private ExceptionHandler exceptionHandler = new FatalExceptionHandler ( ) ; public long p1 , p2 , p3 , p4 , p5 , p6 , p7 ; private volatile boolean running = true ; public long p8 , p9 , p10 , p11 , p12 , p13 , p14 ; private volatile long sequence = RingBuffer . INITIAL_CURSOR_VALUE ; public long p15 , p16 , p17 , p18 , p19 , p20 ; public BatchConsumer ( final ConsumerBarrier < T > consumerBarrier , final BatchHandler < T > handler ) { this . consumerBarrier = consumerBarrier ; this . handler = handler ; } public BatchConsumer ( final ConsumerBarrier < T > consumerBarrier , final SequenceTrackingHandler < T > entryHandler ) { this . consumerBarrier = consumerBarrier ; this . handler = entryHandler ; entryHandler . setSequenceTrackerCallback ( new SequenceTrackerCallback ( ) ) ; } @ Override public long getSequence ( ) { return sequence ; } @ Override public void halt ( ) { running = false ; consumerBarrier . alert ( ) ; } public void setExceptionHandler ( final ExceptionHandler exceptionHandler ) { if ( null == exceptionHandler ) { throw new NullPointerException ( ) ; } this . exceptionHandler = exceptionHandler ; } public ConsumerBarrier < ? extends T > getConsumerBarrier ( ) { return consumerBarrier ; } @ Override public void run ( ) { running = true ; if ( LifecycleAware . class . isAssignableFrom ( handler . getClass ( ) ) ) { ( ( LifecycleAware ) handler ) . onStart ( ) ; } T entry = null ; long nextSequence = sequence + ; while ( running ) { try { final long availableSequence = consumerBarrier . waitFor ( nextSequence ) ; for ( ; nextSequence <= availableSequence ; nextSequence ++ ) { entry = consumerBarrier . getEntry ( nextSequence ) ; handler . onAvailable ( entry ) ; } handler . onEndOfBatch ( ) ; sequence = entry . getSequence ( ) ; } catch ( final AlertException ex ) { } catch ( final Exception ex ) { exceptionHandler . handle ( ex , entry ) ; sequence = entry . getSequence ( ) ; nextSequence = entry . getSequence ( ) + ; } } if ( LifecycleAware . class . isAssignableFrom ( handler . getClass ( ) ) ) { ( ( LifecycleAware ) handler ) . onShutdown ( ) ; } } public final class SequenceTrackerCallback { public void onCompleted ( final long sequence ) { BatchConsumer . this . sequence = sequence ; } } } package com . lmax . disruptor ; @ SuppressWarnings ( "" ) public class AlertException extends Exception { public static final AlertException ALERT_EXCEPTION = new AlertException ( ) ; private AlertException ( ) { } @ Override public Throwable fillInStackTrace ( ) { return this ; } } package com . lmax . disruptor ; import java . util . concurrent . atomic . AtomicLong ; public interface ClaimStrategy { long incrementAndGet ( ) ; long incrementAndGet ( int delta ) ; void setSequence ( long sequence ) ; enum Option { MULTI_THREADED { @ Override public ClaimStrategy newInstance ( ) { return new MultiThreadedStrategy ( ) ; } } , SINGLE_THREADED { @ Override public ClaimStrategy newInstance ( ) { return new SingleThreadedStrategy ( ) ; } } ; abstract ClaimStrategy newInstance ( ) ; } static final class MultiThreadedStrategy implements ClaimStrategy { private final AtomicLong sequence = new AtomicLong ( RingBuffer . INITIAL_CURSOR_VALUE ) ; @ Override public long incrementAndGet ( ) { return sequence . incrementAndGet ( ) ; } @ Override public long incrementAndGet ( final int delta ) { return sequence . addAndGet ( delta ) ; } @ Override public void setSequence ( final long sequence ) { this . sequence . set ( sequence ) ; } } static final class SingleThreadedStrategy implements ClaimStrategy { private long sequence = RingBuffer . INITIAL_CURSOR_VALUE ; @ Override public long incrementAndGet ( ) { return ++ sequence ; } @ Override public long incrementAndGet ( final int delta ) { sequence += delta ; return sequence ; } @ Override public void setSequence ( final long sequence ) { this . sequence = sequence ; } } } package com . lmax . disruptor ; public final class NoOpConsumer implements Consumer { private final RingBuffer ringBuffer ; public NoOpConsumer ( final RingBuffer ringBuffer ) { this . ringBuffer = ringBuffer ; } @ Override public long getSequence ( ) { return ringBuffer . getCursor ( ) ; } @ Override public void halt ( ) { } @ Override public void run ( ) { } } package com . lmax . disruptor ; public interface Consumer extends Runnable { long getSequence ( ) ; void halt ( ) ; } package com . lmax . disruptor ; import java . util . concurrent . TimeUnit ; public interface ConsumerBarrier < T extends AbstractEntry > { T getEntry ( long sequence ) ; long waitFor ( long sequence ) throws AlertException , InterruptedException ; long waitFor ( long sequence , long timeout , TimeUnit units ) throws AlertException , InterruptedException ; long getCursor ( ) ; boolean isAlerted ( ) ; void alert ( ) ; void clearAlert ( ) ; } package com . lmax . disruptor ; public interface EntryTranslator < T extends AbstractEntry > { T translateTo ( final T entry ) ; } package com . lmax . disruptor ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . locks . Condition ; import java . util . concurrent . locks . Lock ; import java . util . concurrent . locks . ReentrantLock ; import static com . lmax . disruptor . AlertException . ALERT_EXCEPTION ; import static com . lmax . disruptor . Util . getMinimumSequence ; public interface WaitStrategy { long waitFor ( Consumer [ ] consumers , RingBuffer ringBuffer , ConsumerBarrier barrier , long sequence ) throws AlertException , InterruptedException ; long waitFor ( Consumer [ ] consumers , RingBuffer ringBuffer , ConsumerBarrier barrier , long sequence , long timeout , TimeUnit units ) throws AlertException , InterruptedException ; void signalAll ( ) ; enum Option { BLOCKING { @ Override public WaitStrategy newInstance ( ) { return new BlockingStrategy ( ) ; } } , YIELDING { @ Override public WaitStrategy newInstance ( ) { return new YieldingStrategy ( ) ; } } , BUSY_SPIN { @ Override public WaitStrategy newInstance ( ) { return new BusySpinStrategy ( ) ; } } ; abstract WaitStrategy newInstance ( ) ; } static final class BlockingStrategy implements WaitStrategy { private final Lock lock = new ReentrantLock ( ) ; private final Condition consumerNotifyCondition = lock . newCondition ( ) ; @ Override public long waitFor ( final Consumer [ ] consumers , final RingBuffer ringBuffer , final ConsumerBarrier barrier , final long sequence ) throws AlertException , InterruptedException { long availableSequence ; if ( ( availableSequence = ringBuffer . getCursor ( ) ) < sequence ) { lock . lock ( ) ; try { while ( ( availableSequence = ringBuffer . getCursor ( ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } consumerNotifyCondition . await ( ) ; } } finally { lock . unlock ( ) ; } } if ( != consumers . length ) { while ( ( availableSequence = getMinimumSequence ( consumers ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } } } return availableSequence ; } @ Override public long waitFor ( final Consumer [ ] consumers , final RingBuffer ringBuffer , final ConsumerBarrier barrier , final long sequence , final long timeout , final TimeUnit units ) throws AlertException , InterruptedException { long availableSequence ; if ( ( availableSequence = ringBuffer . getCursor ( ) ) < sequence ) { lock . lock ( ) ; try { while ( ( availableSequence = ringBuffer . getCursor ( ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } if ( ! consumerNotifyCondition . await ( timeout , units ) ) { break ; } } } finally { lock . unlock ( ) ; } } if ( != consumers . length ) { while ( ( availableSequence = getMinimumSequence ( consumers ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } } } return availableSequence ; } @ Override public void signalAll ( ) { lock . lock ( ) ; try { consumerNotifyCondition . signalAll ( ) ; } finally { lock . unlock ( ) ; } } } static final class YieldingStrategy implements WaitStrategy { @ Override public long waitFor ( final Consumer [ ] consumers , final RingBuffer ringBuffer , final ConsumerBarrier barrier , final long sequence ) throws AlertException , InterruptedException { long availableSequence ; if ( == consumers . length ) { while ( ( availableSequence = ringBuffer . getCursor ( ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } Thread . yield ( ) ; } } else { while ( ( availableSequence = getMinimumSequence ( consumers ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } Thread . yield ( ) ; } } return availableSequence ; } @ Override public long waitFor ( final Consumer [ ] consumers , final RingBuffer ringBuffer , final ConsumerBarrier barrier , final long sequence , final long timeout , final TimeUnit units ) throws AlertException , InterruptedException { final long timeoutMs = units . convert ( timeout , TimeUnit . MILLISECONDS ) ; final long currentTime = System . currentTimeMillis ( ) ; long availableSequence ; if ( == consumers . length ) { while ( ( availableSequence = ringBuffer . getCursor ( ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } Thread . yield ( ) ; if ( timeoutMs < ( System . currentTimeMillis ( ) - currentTime ) ) { break ; } } } else { while ( ( availableSequence = getMinimumSequence ( consumers ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } Thread . yield ( ) ; if ( timeoutMs < ( System . currentTimeMillis ( ) - currentTime ) ) { break ; } } } return availableSequence ; } @ Override public void signalAll ( ) { } } static final class BusySpinStrategy implements WaitStrategy { @ Override public long waitFor ( final Consumer [ ] consumers , final RingBuffer ringBuffer , final ConsumerBarrier barrier , final long sequence ) throws AlertException , InterruptedException { long availableSequence ; if ( == consumers . length ) { while ( ( availableSequence = ringBuffer . getCursor ( ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } } } else { while ( ( availableSequence = getMinimumSequence ( consumers ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } } } return availableSequence ; } @ Override public long waitFor ( final Consumer [ ] consumers , final RingBuffer ringBuffer , final ConsumerBarrier barrier , final long sequence , final long timeout , final TimeUnit units ) throws AlertException , InterruptedException { final long timeoutMs = units . convert ( timeout , TimeUnit . MILLISECONDS ) ; final long currentTime = System . currentTimeMillis ( ) ; long availableSequence ; if ( == consumers . length ) { while ( ( availableSequence = ringBuffer . getCursor ( ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } if ( timeoutMs < ( System . currentTimeMillis ( ) - currentTime ) ) { break ; } } } else { while ( ( availableSequence = getMinimumSequence ( consumers ) ) < sequence ) { if ( barrier . isAlerted ( ) ) { throw ALERT_EXCEPTION ; } if ( timeoutMs < ( System . currentTimeMillis ( ) - currentTime ) ) { break ; } } } return availableSequence ; } @ Override public void signalAll ( ) { } } } package com . lmax . disruptor ; public interface ProducerBarrier < T extends AbstractEntry > { T nextEntry ( ) ; SequenceBatch nextEntries ( SequenceBatch sequenceBatch ) ; void commit ( T entry ) ; void commit ( SequenceBatch sequenceBatch ) ; T getEntry ( long sequence ) ; long getCursor ( ) ; } package com . lmax . disruptor ; import org . junit . Assert ; public abstract class AbstractPerfTestQueueVsDisruptor { protected void testImplementations ( ) throws Exception { final int RUNS = ; long disruptorOps = ; long queueOps = ; for ( int i = ; i < RUNS ; i ++ ) { System . gc ( ) ; disruptorOps = runDisruptorPass ( i ) ; queueOps = runQueuePass ( i ) ; printResults ( getClass ( ) . getSimpleName ( ) , disruptorOps , queueOps , i ) ; } Assert . assertTrue ( "" , disruptorOps > queueOps ) ; } public static void printResults ( final String className , final long disruptorOps , final long queueOps , final int i ) { System . out . format ( "" , className , Integer . valueOf ( i ) , Long . valueOf ( queueOps ) , Long . valueOf ( disruptorOps ) ) ; } protected abstract long runQueuePass ( int passNumber ) throws Exception ; protected abstract long runDisruptorPass ( int passNumber ) throws Exception ; protected abstract void shouldCompareDisruptorVsQueues ( ) throws Exception ; } package com . lmax . disruptor . support ; import com . lmax . disruptor . BatchHandler ; public final class ValueAdditionHandler implements BatchHandler < ValueEntry > { private long value ; public long getValue ( ) { return value ; } public void reset ( ) { value = ; } @ Override public void onAvailable ( final ValueEntry entry ) throws Exception { value += entry . getValue ( ) ; } @ Override public void onEndOfBatch ( ) throws Exception { } } package com . lmax . disruptor . support ; import com . lmax . disruptor . collections . Histogram ; import java . util . concurrent . BlockingQueue ; public final class LatencyStepQueueConsumer implements Runnable { private final FunctionStep functionStep ; private final BlockingQueue < Long > inputQueue ; private final BlockingQueue < Long > outputQueue ; private final Histogram histogram ; private final long nanoTimeCost ; private volatile boolean running ; private volatile long sequence ; public LatencyStepQueueConsumer ( final FunctionStep functionStep , final BlockingQueue < Long > inputQueue , final BlockingQueue < Long > outputQueue , final Histogram histogram , final long nanoTimeCost ) { this . functionStep = functionStep ; this . inputQueue = inputQueue ; this . outputQueue = outputQueue ; this . histogram = histogram ; this . nanoTimeCost = nanoTimeCost ; } public void reset ( ) { sequence = - ; } public long getSequence ( ) { return sequence ; } public void halt ( ) { running = false ; } @ Override public void run ( ) { running = true ; while ( running ) { try { switch ( functionStep ) { case ONE : case TWO : { outputQueue . put ( inputQueue . take ( ) ) ; break ; } case THREE : { Long value = inputQueue . take ( ) ; long duration = System . nanoTime ( ) - value . longValue ( ) ; duration /= ; duration -= nanoTimeCost ; histogram . addObservation ( duration ) ; break ; } } sequence ++ ; } catch ( InterruptedException ex ) { break ; } } } } package com . lmax . disruptor . support ; import java . util . concurrent . BlockingQueue ; public final class ValueMutationQueueConsumer implements Runnable { private volatile boolean running ; private volatile long sequence ; private long value ; private final BlockingQueue < Long > blockingQueue ; private final Operation operation ; public ValueMutationQueueConsumer ( final BlockingQueue < Long > blockingQueue , final Operation operation ) { this . blockingQueue = blockingQueue ; this . operation = operation ; } public long getValue ( ) { return value ; } public void reset ( ) { value = ; } public long getSequence ( ) { return sequence ; } public void halt ( ) { running = false ; } @ Override public void run ( ) { running = true ; while ( running ) { try { long value = blockingQueue . take ( ) . longValue ( ) ; this . value = operation . op ( this . value , value ) ; sequence = value ; } catch ( InterruptedException ex ) { break ; } } } } package com . lmax . disruptor . support ; import java . util . concurrent . BlockingQueue ; public final class FunctionQueueConsumer implements Runnable { private final FunctionStep functionStep ; private final BlockingQueue < long [ ] > stepOneQueue ; private final BlockingQueue < Long > stepTwoQueue ; private final BlockingQueue < Long > stepThreeQueue ; private volatile boolean running ; private volatile long sequence ; private long stepThreeCounter ; public FunctionQueueConsumer ( final FunctionStep functionStep , final BlockingQueue < long [ ] > stepOneQueue , final BlockingQueue < Long > stepTwoQueue , final BlockingQueue < Long > stepThreeQueue ) { this . functionStep = functionStep ; this . stepOneQueue = stepOneQueue ; this . stepTwoQueue = stepTwoQueue ; this . stepThreeQueue = stepThreeQueue ; } public long getStepThreeCounter ( ) { return stepThreeCounter ; } public void reset ( ) { stepThreeCounter = ; sequence = - ; } public long getSequence ( ) { return sequence ; } public void halt ( ) { running = false ; } @ Override public void run ( ) { running = true ; while ( running ) { try { switch ( functionStep ) { case ONE : { long [ ] values = stepOneQueue . take ( ) ; stepTwoQueue . put ( Long . valueOf ( values [ ] + values [ ] ) ) ; break ; } case TWO : { Long value = stepTwoQueue . take ( ) ; stepThreeQueue . put ( Long . valueOf ( value . longValue ( ) + ) ) ; break ; } case THREE : { Long value = stepThreeQueue . take ( ) ; long testValue = value . longValue ( ) ; if ( ( testValue & ) == ) { ++ stepThreeCounter ; } break ; } } sequence ++ ; } catch ( InterruptedException ex ) { break ; } } } } package com . lmax . disruptor . support ; import com . lmax . disruptor . BatchHandler ; public final class FizzBuzzHandler implements BatchHandler < FizzBuzzEntry > { private final FizzBuzzStep fizzBuzzStep ; private long fizzBuzzCounter = ; public FizzBuzzHandler ( final FizzBuzzStep fizzBuzzStep ) { this . fizzBuzzStep = fizzBuzzStep ; } public void reset ( ) { fizzBuzzCounter = ; } public long getFizzBuzzCounter ( ) { return fizzBuzzCounter ; } @ Override public void onAvailable ( final FizzBuzzEntry entry ) throws Exception { switch ( fizzBuzzStep ) { case FIZZ : entry . setFizz ( == ( entry . getValue ( ) % ) ) ; break ; case BUZZ : entry . setBuzz ( == ( entry . getValue ( ) % ) ) ; break ; case FIZZ_BUZZ : if ( entry . isFizz ( ) && entry . isBuzz ( ) ) { ++ fizzBuzzCounter ; } break ; } } @ Override public void onEndOfBatch ( ) throws Exception { } } package com . lmax . disruptor . support ; import java . util . concurrent . BlockingQueue ; public final class FizzBuzzQueueConsumer implements Runnable { private final FizzBuzzStep fizzBuzzStep ; private final BlockingQueue < Long > fizzInputQueue ; private final BlockingQueue < Long > buzzInputQueue ; private final BlockingQueue < Boolean > fizzOutputQueue ; private final BlockingQueue < Boolean > buzzOutputQueue ; private volatile boolean running ; private volatile long sequence ; private long fizzBuzzCounter = ; public FizzBuzzQueueConsumer ( final FizzBuzzStep fizzBuzzStep , final BlockingQueue < Long > fizzInputQueue , final BlockingQueue < Long > buzzInputQueue , final BlockingQueue < Boolean > fizzOutputQueue , final BlockingQueue < Boolean > buzzOutputQueue ) { this . fizzBuzzStep = fizzBuzzStep ; this . fizzInputQueue = fizzInputQueue ; this . buzzInputQueue = buzzInputQueue ; this . fizzOutputQueue = fizzOutputQueue ; this . buzzOutputQueue = buzzOutputQueue ; } public long getFizzBuzzCounter ( ) { return fizzBuzzCounter ; } public void reset ( ) { fizzBuzzCounter = ; sequence = - ; } public long getSequence ( ) { return sequence ; } public void halt ( ) { running = false ; } @ Override public void run ( ) { running = true ; while ( running ) { try { switch ( fizzBuzzStep ) { case FIZZ : { Long value = fizzInputQueue . take ( ) ; fizzOutputQueue . put ( Boolean . valueOf ( == ( value . longValue ( ) % ) ) ) ; break ; } case BUZZ : { Long value = buzzInputQueue . take ( ) ; buzzOutputQueue . put ( Boolean . valueOf ( == ( value . longValue ( ) % ) ) ) ; break ; } case FIZZ_BUZZ : { final boolean fizz = fizzOutputQueue . take ( ) . booleanValue ( ) ; final boolean buzz = buzzOutputQueue . take ( ) . booleanValue ( ) ; if ( fizz && buzz ) { ++ fizzBuzzCounter ; } break ; } } sequence ++ ; } catch ( InterruptedException ex ) { break ; } } } } package com . lmax . disruptor . support ; public enum Operation { ADDITION { @ Override public long op ( final long lhs , final long rhs ) { return lhs + rhs ; } } , SUBTRACTION { @ Override public long op ( final long lhs , final long rhs ) { return lhs - rhs ; } } , AND { @ Override public long op ( final long lhs , final long rhs ) { return lhs & rhs ; } } ; public abstract long op ( final long lhs , final long rhs ) ; } package com . lmax . disruptor . support ; import com . lmax . disruptor . AbstractEntry ; import com . lmax . disruptor . EntryFactory ; public final class ValueEntry extends AbstractEntry { private long value ; public long getValue ( ) { return value ; } public void setValue ( final long value ) { this . value = value ; } public final static EntryFactory < ValueEntry > ENTRY_FACTORY = new EntryFactory < ValueEntry > ( ) { public ValueEntry create ( ) { return new ValueEntry ( ) ; } } ; } package com . lmax . disruptor . support ; public enum FunctionStep { ONE , TWO , THREE } package com . lmax . disruptor . support ; import com . lmax . disruptor . AbstractEntry ; import com . lmax . disruptor . EntryFactory ; public final class FizzBuzzEntry extends AbstractEntry { private long value = ; private boolean fizz = false ; private boolean buzz = false ; public void reset ( ) { value = ; fizz = false ; buzz = false ; } public long getValue ( ) { return value ; } public void setValue ( final long value ) { this . value = value ; } public boolean isFizz ( ) { return fizz ; } public void setFizz ( final boolean fizz ) { this . fizz = fizz ; } public boolean isBuzz ( ) { return buzz ; } public void setBuzz ( final boolean buzz ) { this . buzz = buzz ; } public final static EntryFactory < FizzBuzzEntry > ENTRY_FACTORY = new EntryFactory < FizzBuzzEntry > ( ) { public FizzBuzzEntry create ( ) { return new FizzBuzzEntry ( ) ; } } ; } package com . lmax . disruptor . support ; import com . lmax . disruptor . BatchHandler ; import com . lmax . disruptor . collections . Histogram ; public final class LatencyStepHandler implements BatchHandler < ValueEntry > { private final FunctionStep functionStep ; private final Histogram histogram ; private final long nanoTimeCost ; public LatencyStepHandler ( final FunctionStep functionStep , final Histogram histogram , final long nanoTimeCost ) { this . functionStep = functionStep ; this . histogram = histogram ; this . nanoTimeCost = nanoTimeCost ; } @ Override public void onAvailable ( final ValueEntry entry ) throws Exception { switch ( functionStep ) { case ONE : case TWO : break ; case THREE : long duration = System . nanoTime ( ) - entry . getValue ( ) ; duration /= ; duration -= nanoTimeCost ; histogram . addObservation ( duration ) ; break ; } } @ Override public void onEndOfBatch ( ) throws Exception { } } package com . lmax . disruptor . support ; import com . lmax . disruptor . BatchHandler ; public final class ValueMutationHandler implements BatchHandler < ValueEntry > { private final Operation operation ; private long value ; public ValueMutationHandler ( final Operation operation ) { this . operation = operation ; } public long getValue ( ) { return value ; } public void reset ( ) { value = ; } @ Override public void onAvailable ( final ValueEntry entry ) throws Exception { value = operation . op ( value , entry . getValue ( ) ) ; } @ Override public void onEndOfBatch ( ) throws Exception { } } package com . lmax . disruptor . support ; import java . util . concurrent . BlockingQueue ; public final class ValueAdditionQueueConsumer implements Runnable { private volatile boolean running ; private volatile long sequence ; private long value ; private final BlockingQueue < Long > blockingQueue ; public ValueAdditionQueueConsumer ( final BlockingQueue < Long > blockingQueue ) { this . blockingQueue = blockingQueue ; } public long getValue ( ) { return value ; } public void reset ( ) { value = ; sequence = - ; } public long getSequence ( ) { return sequence ; } public void halt ( ) { running = false ; } @ Override public void run ( ) { running = true ; while ( running ) { try { long value = blockingQueue . take ( ) . longValue ( ) ; this . value += value ; sequence ++ ; } catch ( InterruptedException ex ) { break ; } } } } package com . lmax . disruptor . support ; import com . lmax . disruptor . AbstractEntry ; import com . lmax . disruptor . EntryFactory ; public final class FunctionEntry extends AbstractEntry { private long operandOne ; private long operandTwo ; private long stepOneResult ; private long stepTwoResult ; public long getOperandOne ( ) { return operandOne ; } public void setOperandOne ( final long operandOne ) { this . operandOne = operandOne ; } public long getOperandTwo ( ) { return operandTwo ; } public void setOperandTwo ( final long operandTwo ) { this . operandTwo = operandTwo ; } public long getStepOneResult ( ) { return stepOneResult ; } public void setStepOneResult ( final long stepOneResult ) { this . stepOneResult = stepOneResult ; } public long getStepTwoResult ( ) { return stepTwoResult ; } public void setStepTwoResult ( final long stepTwoResult ) { this . stepTwoResult = stepTwoResult ; } public final static EntryFactory < FunctionEntry > ENTRY_FACTORY = new EntryFactory < FunctionEntry > ( ) { public FunctionEntry create ( ) { return new FunctionEntry ( ) ; } } ; } package com . lmax . disruptor . support ; import com . lmax . disruptor . BatchHandler ; public final class FunctionHandler implements BatchHandler < FunctionEntry > { private final FunctionStep functionStep ; private long stepThreeCounter ; public FunctionHandler ( final FunctionStep functionStep ) { this . functionStep = functionStep ; } public long getStepThreeCounter ( ) { return stepThreeCounter ; } public void reset ( ) { stepThreeCounter = ; } @ Override public void onAvailable ( final FunctionEntry entry ) throws Exception { switch ( functionStep ) { case ONE : entry . setStepOneResult ( entry . getOperandOne ( ) + entry . getOperandTwo ( ) ) ; break ; case TWO : entry . setStepTwoResult ( entry . getStepOneResult ( ) + ) ; break ; case THREE : if ( ( entry . getStepTwoResult ( ) & ) == ) { stepThreeCounter ++ ; } break ; } } @ Override public void onEndOfBatch ( ) throws Exception { } } package com . lmax . disruptor . support ; public enum FizzBuzzStep { FIZZ , BUZZ , FIZZ_BUZZ , } package com . lmax . disruptor . support ; import com . lmax . disruptor . ProducerBarrier ; import java . util . concurrent . CyclicBarrier ; public final class ValueProducer implements Runnable { private final CyclicBarrier cyclicBarrier ; private final ProducerBarrier < ValueEntry > producerBarrier ; private final long iterations ; public ValueProducer ( final CyclicBarrier cyclicBarrier , final ProducerBarrier < ValueEntry > producerBarrier , final long iterations ) { this . cyclicBarrier = cyclicBarrier ; this . producerBarrier = producerBarrier ; this . iterations = iterations ; } @ Override public void run ( ) { try { cyclicBarrier . await ( ) ; for ( long i = ; i < iterations ; i ++ ) { ValueEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( i ) ; producerBarrier . commit ( entry ) ; } } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } } package com . lmax . disruptor . support ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . CyclicBarrier ; public final class ValueQueueProducer implements Runnable { private final CyclicBarrier cyclicBarrier ; private final BlockingQueue < Long > blockingQueue ; private final long iterations ; public ValueQueueProducer ( final CyclicBarrier cyclicBarrier , final BlockingQueue < Long > blockingQueue , final long iterations ) { this . cyclicBarrier = cyclicBarrier ; this . blockingQueue = blockingQueue ; this . iterations = iterations ; } @ Override public void run ( ) { try { cyclicBarrier . await ( ) ; for ( long i = ; i < iterations ; i ++ ) { blockingQueue . put ( Long . valueOf ( i ) ) ; } } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } } package com . lmax . disruptor ; import com . lmax . disruptor . support . Operation ; import com . lmax . disruptor . support . ValueEntry ; import com . lmax . disruptor . support . ValueMutationHandler ; import com . lmax . disruptor . support . ValueMutationQueueConsumer ; import org . junit . Assert ; import org . junit . Test ; import java . util . concurrent . * ; @ SuppressWarnings ( "" ) public final class MultiCast1P3CPerfTest extends AbstractPerfTestQueueVsDisruptor { private static final int NUM_CONSUMERS = ; private static final int SIZE = * ; private static final long ITERATIONS = * * ; private final ExecutorService EXECUTOR = Executors . newFixedThreadPool ( NUM_CONSUMERS ) ; private final long [ ] results = new long [ NUM_CONSUMERS ] ; { for ( long i = ; i < ITERATIONS ; i ++ ) { results [ ] = Operation . ADDITION . op ( results [ ] , i ) ; results [ ] = Operation . SUBTRACTION . op ( results [ ] , i ) ; results [ ] = Operation . AND . op ( results [ ] , i ) ; } } private final ArrayBlockingQueue < Long > [ ] blockingQueues = new ArrayBlockingQueue [ NUM_CONSUMERS ] ; { blockingQueues [ ] = new ArrayBlockingQueue < Long > ( SIZE ) ; blockingQueues [ ] = new ArrayBlockingQueue < Long > ( SIZE ) ; blockingQueues [ ] = new ArrayBlockingQueue < Long > ( SIZE ) ; } private final ValueMutationQueueConsumer [ ] queueConsumers = new ValueMutationQueueConsumer [ NUM_CONSUMERS ] ; { queueConsumers [ ] = new ValueMutationQueueConsumer ( blockingQueues [ ] , Operation . ADDITION ) ; queueConsumers [ ] = new ValueMutationQueueConsumer ( blockingQueues [ ] , Operation . SUBTRACTION ) ; queueConsumers [ ] = new ValueMutationQueueConsumer ( blockingQueues [ ] , Operation . AND ) ; } private final RingBuffer < ValueEntry > ringBuffer = new RingBuffer < ValueEntry > ( ValueEntry . ENTRY_FACTORY , SIZE , ClaimStrategy . Option . SINGLE_THREADED , WaitStrategy . Option . YIELDING ) ; private final ConsumerBarrier < ValueEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final ValueMutationHandler [ ] handlers = new ValueMutationHandler [ NUM_CONSUMERS ] ; { handlers [ ] = new ValueMutationHandler ( Operation . ADDITION ) ; handlers [ ] = new ValueMutationHandler ( Operation . SUBTRACTION ) ; handlers [ ] = new ValueMutationHandler ( Operation . AND ) ; } private final BatchConsumer [ ] batchConsumers = new BatchConsumer [ NUM_CONSUMERS ] ; { batchConsumers [ ] = new BatchConsumer < ValueEntry > ( consumerBarrier , handlers [ ] ) ; batchConsumers [ ] = new BatchConsumer < ValueEntry > ( consumerBarrier , handlers [ ] ) ; batchConsumers [ ] = new BatchConsumer < ValueEntry > ( consumerBarrier , handlers [ ] ) ; } private final ProducerBarrier < ValueEntry > producerBarrier = ringBuffer . createProducerBarrier ( batchConsumers ) ; @ Test @ Override public void shouldCompareDisruptorVsQueues ( ) throws Exception { testImplementations ( ) ; } @ Override protected long runQueuePass ( final int passNumber ) throws InterruptedException { Future [ ] futures = new Future [ NUM_CONSUMERS ] ; for ( int i = ; i < NUM_CONSUMERS ; i ++ ) { queueConsumers [ i ] . reset ( ) ; futures [ i ] = EXECUTOR . submit ( queueConsumers [ i ] ) ; } long start = System . currentTimeMillis ( ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { final Long value = Long . valueOf ( i ) ; blockingQueues [ ] . put ( value ) ; blockingQueues [ ] . put ( value ) ; blockingQueues [ ] . put ( value ) ; } final long expectedSequence = ITERATIONS - ; while ( getMinimumSequence ( queueConsumers ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; for ( int i = ; i < NUM_CONSUMERS ; i ++ ) { queueConsumers [ i ] . halt ( ) ; futures [ i ] . cancel ( true ) ; Assert . assertEquals ( results [ i ] , queueConsumers [ i ] . getValue ( ) ) ; } return opsPerSecond ; } private long getMinimumSequence ( final ValueMutationQueueConsumer [ ] queueConsumers ) { long minimum = Long . MAX_VALUE ; for ( ValueMutationQueueConsumer consumer : queueConsumers ) { long sequence = consumer . getSequence ( ) ; minimum = minimum < sequence ? minimum : sequence ; } return minimum ; } @ Override protected long runDisruptorPass ( final int passNumber ) { for ( int i = ; i < NUM_CONSUMERS ; i ++ ) { handlers [ i ] . reset ( ) ; EXECUTOR . submit ( batchConsumers [ i ] ) ; } long start = System . currentTimeMillis ( ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { ValueEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( i ) ; producerBarrier . commit ( entry ) ; } final long expectedSequence = ringBuffer . getCursor ( ) ; while ( Util . getMinimumSequence ( batchConsumers ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; for ( int i = ; i < NUM_CONSUMERS ; i ++ ) { batchConsumers [ i ] . halt ( ) ; Assert . assertEquals ( results [ i ] , handlers [ i ] . getValue ( ) ) ; } return opsPerSecond ; } } package com . lmax . disruptor ; import com . lmax . disruptor . support . FunctionStep ; import com . lmax . disruptor . support . FunctionEntry ; import com . lmax . disruptor . support . FunctionHandler ; import com . lmax . disruptor . support . FunctionQueueConsumer ; import org . junit . Assert ; import org . junit . Test ; import java . util . concurrent . * ; public final class Pipeline3StepPerfTest extends AbstractPerfTestQueueVsDisruptor { private static final int NUM_CONSUMERS = ; private static final int SIZE = * ; private static final long ITERATIONS = * * ; private final ExecutorService EXECUTOR = Executors . newFixedThreadPool ( NUM_CONSUMERS ) ; private static final long OPERAND_TWO_INITIAL_VALUE = ; private final long expectedResult ; { long temp = ; long operandTwo = OPERAND_TWO_INITIAL_VALUE ; for ( long i = ; i < ITERATIONS ; i ++ ) { long stepOneResult = i + operandTwo -- ; long stepTwoResult = stepOneResult + ; if ( ( stepTwoResult & ) == ) { ++ temp ; } } expectedResult = temp ; } private final BlockingQueue < long [ ] > stepOneQueue = new ArrayBlockingQueue < long [ ] > ( SIZE ) ; private final BlockingQueue < Long > stepTwoQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final BlockingQueue < Long > stepThreeQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final FunctionQueueConsumer stepOneQueueConsumer = new FunctionQueueConsumer ( FunctionStep . ONE , stepOneQueue , stepTwoQueue , stepThreeQueue ) ; private final FunctionQueueConsumer stepTwoQueueConsumer = new FunctionQueueConsumer ( FunctionStep . TWO , stepOneQueue , stepTwoQueue , stepThreeQueue ) ; private final FunctionQueueConsumer stepThreeQueueConsumer = new FunctionQueueConsumer ( FunctionStep . THREE , stepOneQueue , stepTwoQueue , stepThreeQueue ) ; private final RingBuffer < FunctionEntry > ringBuffer = new RingBuffer < FunctionEntry > ( FunctionEntry . ENTRY_FACTORY , SIZE , ClaimStrategy . Option . SINGLE_THREADED , WaitStrategy . Option . YIELDING ) ; private final ConsumerBarrier < FunctionEntry > stepOneConsumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final FunctionHandler stepOneFunctionHandler = new FunctionHandler ( FunctionStep . ONE ) ; private final BatchConsumer < FunctionEntry > stepOneBatchConsumer = new BatchConsumer < FunctionEntry > ( stepOneConsumerBarrier , stepOneFunctionHandler ) ; private final ConsumerBarrier < FunctionEntry > stepTwoConsumerBarrier = ringBuffer . createConsumerBarrier ( stepOneBatchConsumer ) ; private final FunctionHandler stepTwoFunctionHandler = new FunctionHandler ( FunctionStep . TWO ) ; private final BatchConsumer < FunctionEntry > stepTwoBatchConsumer = new BatchConsumer < FunctionEntry > ( stepTwoConsumerBarrier , stepTwoFunctionHandler ) ; private final ConsumerBarrier < FunctionEntry > stepThreeConsumerBarrier = ringBuffer . createConsumerBarrier ( stepTwoBatchConsumer ) ; private final FunctionHandler stepThreeFunctionHandler = new FunctionHandler ( FunctionStep . THREE ) ; private final BatchConsumer < FunctionEntry > stepThreeBatchConsumer = new BatchConsumer < FunctionEntry > ( stepThreeConsumerBarrier , stepThreeFunctionHandler ) ; private final ProducerBarrier < FunctionEntry > producerBarrier = ringBuffer . createProducerBarrier ( stepThreeBatchConsumer ) ; @ Test @ Override public void shouldCompareDisruptorVsQueues ( ) throws Exception { testImplementations ( ) ; } @ Override protected long runDisruptorPass ( final int passNumber ) { stepThreeFunctionHandler . reset ( ) ; EXECUTOR . submit ( stepOneBatchConsumer ) ; EXECUTOR . submit ( stepTwoBatchConsumer ) ; EXECUTOR . submit ( stepThreeBatchConsumer ) ; long start = System . currentTimeMillis ( ) ; long operandTwo = OPERAND_TWO_INITIAL_VALUE ; for ( long i = ; i < ITERATIONS ; i ++ ) { FunctionEntry entry = producerBarrier . nextEntry ( ) ; entry . setOperandOne ( i ) ; entry . setOperandTwo ( operandTwo -- ) ; producerBarrier . commit ( entry ) ; } final long expectedSequence = ringBuffer . getCursor ( ) ; while ( stepThreeBatchConsumer . getSequence ( ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; stepOneBatchConsumer . halt ( ) ; stepTwoBatchConsumer . halt ( ) ; stepThreeBatchConsumer . halt ( ) ; Assert . assertEquals ( expectedResult , stepThreeFunctionHandler . getStepThreeCounter ( ) ) ; return opsPerSecond ; } @ Override protected long runQueuePass ( final int passNumber ) throws Exception { stepThreeQueueConsumer . reset ( ) ; Future [ ] futures = new Future [ NUM_CONSUMERS ] ; futures [ ] = EXECUTOR . submit ( stepOneQueueConsumer ) ; futures [ ] = EXECUTOR . submit ( stepTwoQueueConsumer ) ; futures [ ] = EXECUTOR . submit ( stepThreeQueueConsumer ) ; long start = System . currentTimeMillis ( ) ; long operandTwo = OPERAND_TWO_INITIAL_VALUE ; for ( long i = ; i < ITERATIONS ; i ++ ) { long [ ] values = new long [ ] ; values [ ] = i ; values [ ] = operandTwo -- ; stepOneQueue . put ( values ) ; } final long expectedSequence = ITERATIONS - ; while ( stepThreeQueueConsumer . getSequence ( ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; stepOneQueueConsumer . halt ( ) ; stepTwoQueueConsumer . halt ( ) ; stepThreeQueueConsumer . halt ( ) ; for ( Future future : futures ) { future . cancel ( true ) ; } Assert . assertEquals ( expectedResult , stepThreeQueueConsumer . getStepThreeCounter ( ) ) ; return opsPerSecond ; } } package com . lmax . disruptor ; import com . lmax . disruptor . support . * ; import org . junit . Test ; import java . util . concurrent . * ; public final class Sequencer3P1CPerfTest extends AbstractPerfTestQueueVsDisruptor { private static final int NUM_PRODUCERS = ; private static final int SIZE = * ; private static final long ITERATIONS = * * ; private final ExecutorService EXECUTOR = Executors . newFixedThreadPool ( NUM_PRODUCERS + ) ; private final CyclicBarrier cyclicBarrier = new CyclicBarrier ( NUM_PRODUCERS + ) ; private final BlockingQueue < Long > blockingQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final ValueAdditionQueueConsumer queueConsumer = new ValueAdditionQueueConsumer ( blockingQueue ) ; private final ValueQueueProducer [ ] valueQueueProducers = new ValueQueueProducer [ NUM_PRODUCERS ] ; { valueQueueProducers [ ] = new ValueQueueProducer ( cyclicBarrier , blockingQueue , ITERATIONS ) ; valueQueueProducers [ ] = new ValueQueueProducer ( cyclicBarrier , blockingQueue , ITERATIONS ) ; valueQueueProducers [ ] = new ValueQueueProducer ( cyclicBarrier , blockingQueue , ITERATIONS ) ; } private final RingBuffer < ValueEntry > ringBuffer = new RingBuffer < ValueEntry > ( ValueEntry . ENTRY_FACTORY , SIZE , ClaimStrategy . Option . MULTI_THREADED , WaitStrategy . Option . YIELDING ) ; private final ConsumerBarrier < ValueEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final ValueAdditionHandler handler = new ValueAdditionHandler ( ) ; private final BatchConsumer < ValueEntry > batchConsumer = new BatchConsumer < ValueEntry > ( consumerBarrier , handler ) ; private final ProducerBarrier < ValueEntry > producerBarrier = ringBuffer . createProducerBarrier ( batchConsumer ) ; private final ValueProducer [ ] valueProducers = new ValueProducer [ NUM_PRODUCERS ] ; { valueProducers [ ] = new ValueProducer ( cyclicBarrier , producerBarrier , ITERATIONS ) ; valueProducers [ ] = new ValueProducer ( cyclicBarrier , producerBarrier , ITERATIONS ) ; valueProducers [ ] = new ValueProducer ( cyclicBarrier , producerBarrier , ITERATIONS ) ; } @ Test @ Override public void shouldCompareDisruptorVsQueues ( ) throws Exception { testImplementations ( ) ; } @ Override protected long runQueuePass ( final int passNumber ) throws Exception { Future [ ] futures = new Future [ NUM_PRODUCERS ] ; for ( int i = ; i < NUM_PRODUCERS ; i ++ ) { futures [ i ] = EXECUTOR . submit ( valueQueueProducers [ i ] ) ; } Future consumerFuture = EXECUTOR . submit ( queueConsumer ) ; long start = System . currentTimeMillis ( ) ; cyclicBarrier . await ( ) ; for ( int i = ; i < NUM_PRODUCERS ; i ++ ) { futures [ i ] . get ( ) ; } final long expectedSequence = ( ITERATIONS * NUM_PRODUCERS ) - ; while ( expectedSequence > queueConsumer . getSequence ( ) ) { } long opsPerSecond = ( NUM_PRODUCERS * ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; batchConsumer . halt ( ) ; consumerFuture . cancel ( true ) ; return opsPerSecond ; } @ Override protected long runDisruptorPass ( final int passNumber ) throws Exception { Future [ ] futures = new Future [ NUM_PRODUCERS ] ; for ( int i = ; i < NUM_PRODUCERS ; i ++ ) { futures [ i ] = EXECUTOR . submit ( valueProducers [ i ] ) ; } EXECUTOR . submit ( batchConsumer ) ; long start = System . currentTimeMillis ( ) ; cyclicBarrier . await ( ) ; for ( int i = ; i < NUM_PRODUCERS ; i ++ ) { futures [ i ] . get ( ) ; } final long expectedSequence = ( ITERATIONS * NUM_PRODUCERS * ( passNumber + ) ) - ; while ( expectedSequence > batchConsumer . getSequence ( ) ) { } long opsPerSecond = ( NUM_PRODUCERS * ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; batchConsumer . halt ( ) ; return opsPerSecond ; } } package com . lmax . disruptor ; import com . lmax . disruptor . support . ValueAdditionHandler ; import com . lmax . disruptor . support . ValueAdditionQueueConsumer ; import com . lmax . disruptor . support . ValueEntry ; import org . junit . Assert ; import org . junit . Test ; import java . util . concurrent . * ; public final class UniCast1P1CBatchPerfTest extends AbstractPerfTestQueueVsDisruptor { private static final int SIZE = * ; private static final long ITERATIONS = * * ; private final ExecutorService EXECUTOR = Executors . newSingleThreadExecutor ( ) ; private final long expectedResult ; { long temp = ; for ( long i = ; i < ITERATIONS ; i ++ ) { temp += i ; } expectedResult = temp ; } private final BlockingQueue < Long > blockingQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final ValueAdditionQueueConsumer queueConsumer = new ValueAdditionQueueConsumer ( blockingQueue ) ; private final RingBuffer < ValueEntry > ringBuffer = new RingBuffer < ValueEntry > ( ValueEntry . ENTRY_FACTORY , SIZE , ClaimStrategy . Option . SINGLE_THREADED , WaitStrategy . Option . YIELDING ) ; private final ConsumerBarrier < ValueEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final ValueAdditionHandler handler = new ValueAdditionHandler ( ) ; private final BatchConsumer < ValueEntry > batchConsumer = new BatchConsumer < ValueEntry > ( consumerBarrier , handler ) ; private final ProducerBarrier < ValueEntry > producerBarrier = ringBuffer . createProducerBarrier ( batchConsumer ) ; @ Test @ Override public void shouldCompareDisruptorVsQueues ( ) throws Exception { testImplementations ( ) ; } @ Override protected long runQueuePass ( final int passNumber ) throws InterruptedException { queueConsumer . reset ( ) ; Future future = EXECUTOR . submit ( queueConsumer ) ; long start = System . currentTimeMillis ( ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { blockingQueue . put ( Long . valueOf ( i ) ) ; } final long expectedSequence = ITERATIONS - ; while ( queueConsumer . getSequence ( ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; queueConsumer . halt ( ) ; future . cancel ( true ) ; Assert . assertEquals ( expectedResult , queueConsumer . getValue ( ) ) ; return opsPerSecond ; } @ Override protected long runDisruptorPass ( final int passNumber ) throws InterruptedException { handler . reset ( ) ; EXECUTOR . submit ( batchConsumer ) ; final int batchSize = ; final SequenceBatch sequenceBatch = new SequenceBatch ( batchSize ) ; long start = System . currentTimeMillis ( ) ; long offset = ; for ( long i = ; i < ITERATIONS ; i += batchSize ) { producerBarrier . nextEntries ( sequenceBatch ) ; for ( long c = sequenceBatch . getStart ( ) , end = sequenceBatch . getEnd ( ) ; c <= end ; c ++ ) { ValueEntry entry = producerBarrier . getEntry ( c ) ; entry . setValue ( offset ++ ) ; } producerBarrier . commit ( sequenceBatch ) ; } final long expectedSequence = ringBuffer . getCursor ( ) ; while ( batchConsumer . getSequence ( ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; batchConsumer . halt ( ) ; Assert . assertEquals ( expectedResult , handler . getValue ( ) ) ; return opsPerSecond ; } } package com . lmax . disruptor ; import com . lmax . disruptor . support . ValueAdditionHandler ; import com . lmax . disruptor . support . ValueAdditionQueueConsumer ; import com . lmax . disruptor . support . ValueEntry ; import org . junit . Assert ; import org . junit . Test ; import java . util . concurrent . * ; public final class UniCast1P1CPerfTest extends AbstractPerfTestQueueVsDisruptor { private static final int SIZE = * ; private static final long ITERATIONS = * * ; private final ExecutorService EXECUTOR = Executors . newSingleThreadExecutor ( ) ; private final long expectedResult ; { long temp = ; for ( long i = ; i < ITERATIONS ; i ++ ) { temp += i ; } expectedResult = temp ; } private final BlockingQueue < Long > blockingQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final ValueAdditionQueueConsumer queueConsumer = new ValueAdditionQueueConsumer ( blockingQueue ) ; private final RingBuffer < ValueEntry > ringBuffer = new RingBuffer < ValueEntry > ( ValueEntry . ENTRY_FACTORY , SIZE , ClaimStrategy . Option . SINGLE_THREADED , WaitStrategy . Option . YIELDING ) ; private final ConsumerBarrier < ValueEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final ValueAdditionHandler handler = new ValueAdditionHandler ( ) ; private final BatchConsumer < ValueEntry > batchConsumer = new BatchConsumer < ValueEntry > ( consumerBarrier , handler ) ; private final ProducerBarrier < ValueEntry > producerBarrier = ringBuffer . createProducerBarrier ( batchConsumer ) ; @ Test @ Override public void shouldCompareDisruptorVsQueues ( ) throws Exception { testImplementations ( ) ; } @ Override protected long runQueuePass ( final int passNumber ) throws InterruptedException { queueConsumer . reset ( ) ; Future future = EXECUTOR . submit ( queueConsumer ) ; long start = System . currentTimeMillis ( ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { blockingQueue . put ( Long . valueOf ( i ) ) ; } final long expectedSequence = ITERATIONS - ; while ( queueConsumer . getSequence ( ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; queueConsumer . halt ( ) ; future . cancel ( true ) ; Assert . assertEquals ( expectedResult , queueConsumer . getValue ( ) ) ; return opsPerSecond ; } @ Override protected long runDisruptorPass ( final int passNumber ) throws InterruptedException { handler . reset ( ) ; EXECUTOR . submit ( batchConsumer ) ; long start = System . currentTimeMillis ( ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { ValueEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( i ) ; producerBarrier . commit ( entry ) ; } final long expectedSequence = ringBuffer . getCursor ( ) ; while ( batchConsumer . getSequence ( ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; batchConsumer . halt ( ) ; Assert . assertEquals ( expectedResult , handler . getValue ( ) ) ; return opsPerSecond ; } } package com . lmax . disruptor ; import com . lmax . disruptor . collections . Histogram ; import com . lmax . disruptor . support . * ; import org . junit . Test ; import java . io . PrintStream ; import java . math . BigDecimal ; import java . util . concurrent . * ; import static org . hamcrest . core . Is . is ; import static org . junit . Assert . assertThat ; import static org . junit . Assert . assertTrue ; public final class Pipeline3StepLatencyPerfTest { private static final int NUM_CONSUMERS = ; private static final int SIZE = * ; private static final long ITERATIONS = * * ; private static final long PAUSE_NANOS = ; private final ExecutorService EXECUTOR = Executors . newFixedThreadPool ( NUM_CONSUMERS ) ; private final Histogram histogram ; { long [ ] intervals = new long [ ] ; long intervalUpperBound = ; for ( int i = , size = intervals . length - ; i < size ; i ++ ) { intervalUpperBound *= ; intervals [ i ] = intervalUpperBound ; } intervals [ intervals . length - ] = Long . MAX_VALUE ; histogram = new Histogram ( intervals ) ; } private final long nanoTimeCost ; { final long iterations = ; long start = System . nanoTime ( ) ; long finish = start ; for ( int i = ; i < iterations ; i ++ ) { finish = System . nanoTime ( ) ; } if ( finish <= start ) { throw new IllegalStateException ( ) ; } finish = System . nanoTime ( ) ; nanoTimeCost = ( finish - start ) / iterations ; } private final BlockingQueue < Long > stepOneQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final BlockingQueue < Long > stepTwoQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final BlockingQueue < Long > stepThreeQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final LatencyStepQueueConsumer stepOneQueueConsumer = new LatencyStepQueueConsumer ( FunctionStep . ONE , stepOneQueue , stepTwoQueue , histogram , nanoTimeCost ) ; private final LatencyStepQueueConsumer stepTwoQueueConsumer = new LatencyStepQueueConsumer ( FunctionStep . TWO , stepTwoQueue , stepThreeQueue , histogram , nanoTimeCost ) ; private final LatencyStepQueueConsumer stepThreeQueueConsumer = new LatencyStepQueueConsumer ( FunctionStep . THREE , stepThreeQueue , null , histogram , nanoTimeCost ) ; private final RingBuffer < ValueEntry > ringBuffer = new RingBuffer < ValueEntry > ( ValueEntry . ENTRY_FACTORY , SIZE , ClaimStrategy . Option . SINGLE_THREADED , WaitStrategy . Option . BUSY_SPIN ) ; private final ConsumerBarrier < ValueEntry > stepOneConsumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final LatencyStepHandler stepOneFunctionHandler = new LatencyStepHandler ( FunctionStep . ONE , histogram , nanoTimeCost ) ; private final BatchConsumer < ValueEntry > stepOneBatchConsumer = new BatchConsumer < ValueEntry > ( stepOneConsumerBarrier , stepOneFunctionHandler ) ; private final ConsumerBarrier < ValueEntry > stepTwoConsumerBarrier = ringBuffer . createConsumerBarrier ( stepOneBatchConsumer ) ; private final LatencyStepHandler stepTwoFunctionHandler = new LatencyStepHandler ( FunctionStep . TWO , histogram , nanoTimeCost ) ; private final BatchConsumer < ValueEntry > stepTwoBatchConsumer = new BatchConsumer < ValueEntry > ( stepTwoConsumerBarrier , stepTwoFunctionHandler ) ; private final ConsumerBarrier < ValueEntry > stepThreeConsumerBarrier = ringBuffer . createConsumerBarrier ( stepTwoBatchConsumer ) ; private final LatencyStepHandler stepThreeFunctionHandler = new LatencyStepHandler ( FunctionStep . THREE , histogram , nanoTimeCost ) ; private final BatchConsumer < ValueEntry > stepThreeBatchConsumer = new BatchConsumer < ValueEntry > ( stepThreeConsumerBarrier , stepThreeFunctionHandler ) ; private final ProducerBarrier < ValueEntry > producerBarrier = ringBuffer . createProducerBarrier ( stepThreeBatchConsumer ) ; @ Test public void shouldCompareDisruptorVsQueues ( ) throws Exception { final int RUNS = ; for ( int i = ; i < RUNS ; i ++ ) { System . gc ( ) ; histogram . clear ( ) ; runDisruptorPass ( ) ; assertThat ( Long . valueOf ( histogram . getCount ( ) ) , is ( Long . valueOf ( ITERATIONS ) ) ) ; final BigDecimal disruptorMeanLatency = histogram . getMean ( ) ; System . out . format ( "" , getClass ( ) . getSimpleName ( ) , Long . valueOf ( i ) , histogram ) ; dumpHistogram ( System . out ) ; histogram . clear ( ) ; runQueuePass ( ) ; assertThat ( Long . valueOf ( histogram . getCount ( ) ) , is ( Long . valueOf ( ITERATIONS ) ) ) ; final BigDecimal queueMeanLatency = histogram . getMean ( ) ; System . out . format ( "" , getClass ( ) . getSimpleName ( ) , Long . valueOf ( i ) , histogram ) ; dumpHistogram ( System . out ) ; assertTrue ( queueMeanLatency . compareTo ( disruptorMeanLatency ) > ) ; } } private void dumpHistogram ( final PrintStream out ) { for ( int i = , size = histogram . getSize ( ) ; i < size ; i ++ ) { out . print ( histogram . getUpperBoundAt ( i ) ) ; out . print ( '' ) ; out . print ( histogram . getCountAt ( i ) ) ; out . println ( ) ; } } private void runDisruptorPass ( ) { EXECUTOR . submit ( stepOneBatchConsumer ) ; EXECUTOR . submit ( stepTwoBatchConsumer ) ; EXECUTOR . submit ( stepThreeBatchConsumer ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { ValueEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( System . nanoTime ( ) ) ; producerBarrier . commit ( entry ) ; long pauseStart = System . nanoTime ( ) ; while ( PAUSE_NANOS > ( System . nanoTime ( ) - pauseStart ) ) { } } final long expectedSequence = ringBuffer . getCursor ( ) ; while ( stepThreeBatchConsumer . getSequence ( ) < expectedSequence ) { } stepOneBatchConsumer . halt ( ) ; stepTwoBatchConsumer . halt ( ) ; stepThreeBatchConsumer . halt ( ) ; } private void runQueuePass ( ) throws Exception { stepThreeQueueConsumer . reset ( ) ; Future [ ] futures = new Future [ NUM_CONSUMERS ] ; futures [ ] = EXECUTOR . submit ( stepOneQueueConsumer ) ; futures [ ] = EXECUTOR . submit ( stepTwoQueueConsumer ) ; futures [ ] = EXECUTOR . submit ( stepThreeQueueConsumer ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { stepOneQueue . put ( Long . valueOf ( System . nanoTime ( ) ) ) ; long pauseStart = System . nanoTime ( ) ; while ( PAUSE_NANOS > ( System . nanoTime ( ) - pauseStart ) ) { } } final long expectedSequence = ITERATIONS - ; while ( stepThreeQueueConsumer . getSequence ( ) < expectedSequence ) { } stepOneQueueConsumer . halt ( ) ; stepTwoQueueConsumer . halt ( ) ; stepThreeQueueConsumer . halt ( ) ; for ( Future future : futures ) { future . cancel ( true ) ; } } } package com . lmax . disruptor ; import com . lmax . disruptor . support . FizzBuzzEntry ; import com . lmax . disruptor . support . FizzBuzzHandler ; import com . lmax . disruptor . support . FizzBuzzQueueConsumer ; import com . lmax . disruptor . support . FizzBuzzStep ; import org . junit . Assert ; import org . junit . Test ; import java . util . concurrent . * ; public final class DiamondPath1P3CPerfTest extends AbstractPerfTestQueueVsDisruptor { private static final int NUM_CONSUMERS = ; private static final int SIZE = * ; private static final long ITERATIONS = * * ; private final ExecutorService EXECUTOR = Executors . newFixedThreadPool ( NUM_CONSUMERS ) ; private final long expectedResult ; { long temp = ; for ( long i = ; i < ITERATIONS ; i ++ ) { boolean fizz = == ( i % ) ; boolean buzz = == ( i % ) ; if ( fizz && buzz ) { ++ temp ; } } expectedResult = temp ; } private final BlockingQueue < Long > fizzInputQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final BlockingQueue < Long > buzzInputQueue = new ArrayBlockingQueue < Long > ( SIZE ) ; private final BlockingQueue < Boolean > fizzOutputQueue = new ArrayBlockingQueue < Boolean > ( SIZE ) ; private final BlockingQueue < Boolean > buzzOutputQueue = new ArrayBlockingQueue < Boolean > ( SIZE ) ; private final FizzBuzzQueueConsumer fizzQueueConsumer = new FizzBuzzQueueConsumer ( FizzBuzzStep . FIZZ , fizzInputQueue , buzzInputQueue , fizzOutputQueue , buzzOutputQueue ) ; private final FizzBuzzQueueConsumer buzzQueueConsumer = new FizzBuzzQueueConsumer ( FizzBuzzStep . BUZZ , fizzInputQueue , buzzInputQueue , fizzOutputQueue , buzzOutputQueue ) ; private final FizzBuzzQueueConsumer fizzBuzzQueueConsumer = new FizzBuzzQueueConsumer ( FizzBuzzStep . FIZZ_BUZZ , fizzInputQueue , buzzInputQueue , fizzOutputQueue , buzzOutputQueue ) ; private final RingBuffer < FizzBuzzEntry > ringBuffer = new RingBuffer < FizzBuzzEntry > ( FizzBuzzEntry . ENTRY_FACTORY , SIZE , ClaimStrategy . Option . SINGLE_THREADED , WaitStrategy . Option . YIELDING ) ; private final ConsumerBarrier < FizzBuzzEntry > consumerBarrier = ringBuffer . createConsumerBarrier ( ) ; private final FizzBuzzHandler fizzHandler = new FizzBuzzHandler ( FizzBuzzStep . FIZZ ) ; private final BatchConsumer < FizzBuzzEntry > batchConsumerFizz = new BatchConsumer < FizzBuzzEntry > ( consumerBarrier , fizzHandler ) ; private final FizzBuzzHandler buzzHandler = new FizzBuzzHandler ( FizzBuzzStep . BUZZ ) ; private final BatchConsumer < FizzBuzzEntry > batchConsumerBuzz = new BatchConsumer < FizzBuzzEntry > ( consumerBarrier , buzzHandler ) ; private final ConsumerBarrier < FizzBuzzEntry > consumerBarrierFizzBuzz = ringBuffer . createConsumerBarrier ( batchConsumerFizz , batchConsumerBuzz ) ; private final FizzBuzzHandler fizzBuzzHandler = new FizzBuzzHandler ( FizzBuzzStep . FIZZ_BUZZ ) ; private final BatchConsumer < FizzBuzzEntry > batchConsumerFizzBuzz = new BatchConsumer < FizzBuzzEntry > ( consumerBarrierFizzBuzz , fizzBuzzHandler ) ; private final ProducerBarrier < FizzBuzzEntry > producerBarrier = ringBuffer . createProducerBarrier ( batchConsumerFizzBuzz ) ; @ Test @ Override public void shouldCompareDisruptorVsQueues ( ) throws Exception { testImplementations ( ) ; } @ Override protected long runDisruptorPass ( int PassNumber ) throws Exception { fizzBuzzHandler . reset ( ) ; EXECUTOR . submit ( batchConsumerFizz ) ; EXECUTOR . submit ( batchConsumerBuzz ) ; EXECUTOR . submit ( batchConsumerFizzBuzz ) ; long start = System . currentTimeMillis ( ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { FizzBuzzEntry entry = producerBarrier . nextEntry ( ) ; entry . setValue ( i ) ; producerBarrier . commit ( entry ) ; } final long expectedSequence = ringBuffer . getCursor ( ) ; while ( batchConsumerFizzBuzz . getSequence ( ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; batchConsumerFizz . halt ( ) ; batchConsumerBuzz . halt ( ) ; batchConsumerFizzBuzz . halt ( ) ; Assert . assertEquals ( expectedResult , fizzBuzzHandler . getFizzBuzzCounter ( ) ) ; return opsPerSecond ; } @ Override protected long runQueuePass ( int passNumber ) throws Exception { fizzBuzzQueueConsumer . reset ( ) ; Future [ ] futures = new Future [ NUM_CONSUMERS ] ; futures [ ] = EXECUTOR . submit ( fizzQueueConsumer ) ; futures [ ] = EXECUTOR . submit ( buzzQueueConsumer ) ; futures [ ] = EXECUTOR . submit ( fizzBuzzQueueConsumer ) ; long start = System . currentTimeMillis ( ) ; for ( long i = ; i < ITERATIONS ; i ++ ) { Long value = Long . valueOf ( i ) ; fizzInputQueue . put ( value ) ; buzzInputQueue . put ( value ) ; } final long expectedSequence = ITERATIONS - ; while ( fizzBuzzQueueConsumer . getSequence ( ) < expectedSequence ) { } long opsPerSecond = ( ITERATIONS * ) / ( System . currentTimeMillis ( ) - start ) ; fizzQueueConsumer . halt ( ) ; buzzQueueConsumer . halt ( ) ; fizzBuzzQueueConsumer . halt ( ) ; for ( Future future : futures ) { future . cancel ( true ) ; } Assert . assertEquals ( expectedResult , fizzBuzzQueueConsumer . getFizzBuzzCounter ( ) ) ; return opsPerSecond ; } } package org . rubypeople . rdt . refactoring . documentprovider ; import java . util . ArrayList ; import java . util . Collection ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Util ; public class WorkspaceDocumentProvider extends DocumentProvider { private IFile activeFile ; private String activeFileContent ; private IProject activeProject ; private IWorkspaceRoot workspaceRoot ; public WorkspaceDocumentProvider ( IFile activeFile ) { this . activeFile = activeFile ; this . activeProject = activeFile . getProject ( ) ; workspaceRoot = this . activeFile . getWorkspace ( ) . getRoot ( ) ; this . activeFileContent = getFileContent ( getActiveFileName ( ) ) ; } public String getActiveFileContent ( ) { return activeFileContent ; } public String getActiveFileName ( ) { return activeFile . getFullPath ( ) . toOSString ( ) ; } public IFile getIFile ( String fileName ) { fileName = makePathAbsoulte ( fileName ) ; return workspaceRoot . getFile ( new Path ( fileName ) ) ; } public Collection < String > getFileNames ( ) { ArrayList < String > fileNames = new ArrayList < String > ( ) ; fillFileNames ( fileNames , activeProject ) ; return fileNames ; } private void fillFileNames ( ArrayList < String > fileNames , IContainer container ) { try { for ( IResource resource : container . members ( ) ) { if ( resource . getType ( ) == IResource . FILE ) { IFile currentFile = ( IFile ) resource ; String fileExtension = currentFile . getFileExtension ( ) ; if ( fileExtension != null && fileExtension . equals ( "" ) ) { fileNames . add ( currentFile . getFullPath ( ) . toOSString ( ) ) ; } } if ( resource instanceof IContainer ) { IContainer subContainer = ( IContainer ) resource ; fillFileNames ( fileNames , subContainer ) ; } } } catch ( CoreException e ) { e . printStackTrace ( ) ; } } public String getFileContent ( String fileName ) { IFile currentFile = getIFile ( fileName ) ; try { return new String ( Util . getResourceContentsAsCharArray ( currentFile ) ) ; } catch ( RubyModelException e ) { } return null ; } private String makePathAbsoulte ( String path ) { Path absolutePath = new Path ( path ) ; if ( absolutePath . isAbsolute ( ) ) { return absolutePath . toOSString ( ) ; } return activeFile . getFullPath ( ) . removeLastSegments ( ) . append ( path ) . toOSString ( ) ; } } package org . rubypeople . rdt . refactoring . documentprovider ; import java . util . Collection ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; public interface IDocumentProvider { public String getActiveFileName ( ) ; public String getActiveFileContent ( ) ; public Collection < String > getFileNames ( ) ; public String getFileContent ( String currentFileName ) ; public ClassNodeProvider getClassNodeProvider ( ) ; public ClassNodeProvider getProjectClassNodeProvider ( ) ; public ClassNodeProvider getIncludedClassNodeProvider ( ) ; public RootNode getActiveFileRootNode ( ) ; public RootNode getRootNode ( String fileName ) ; public Collection < Node > getAllNodes ( ) ; } package org . rubypeople . rdt . refactoring . documentprovider ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Map ; public class StringDocumentProvider extends DocumentProvider { protected String document ; protected String docName ; protected Map < String , String > files ; public StringDocumentProvider ( String name , String document ) { this . document = document ; this . docName = name ; files = new LinkedHashMap < String , String > ( ) ; files . put ( name , document ) ; } public StringDocumentProvider ( IDocumentProvider other ) { this ( other . getActiveFileName ( ) , other . getActiveFileContent ( ) ) ; } public String getActiveFileContent ( ) { return document ; } public String getActiveFileName ( ) { return docName ; } public String getFileContent ( String currentFileName ) { return files . get ( currentFileName ) ; } public Collection < String > getFileNames ( ) { return files . keySet ( ) ; } public void addFile ( String fileName , String fileContent ) { files . put ( fileName , fileContent ) ; } } package org . rubypeople . rdt . refactoring . documentprovider ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import org . jruby . ast . FCallNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . StrNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class DocumentWithIncluding extends StringDocumentProvider { protected final IDocumentProvider docProvider ; public DocumentWithIncluding ( IDocumentProvider docProvider ) { super ( docProvider . getActiveFileName ( ) , docProvider . getActiveFileContent ( ) ) ; this . docProvider = docProvider ; searchForRelatedFiles ( ) ; } private void searchForRelatedFiles ( ) { Collection < String > candidates = new ArrayList < String > ( docProvider . getFileNames ( ) ) ; ArrayList < String > markedForRemoval = new ArrayList < String > ( ) ; HashSet < String > includedFiles = findAllIncludedFiles ( ) ; do { markedForRemoval . clear ( ) ; for ( String actFileName : candidates ) { String fileName = getFileNameWithoutPath ( actFileName ) ; if ( includedFiles . contains ( fileName ) ) { addAndRemove ( markedForRemoval , actFileName , fileName ) ; continue ; } for ( FCallNode node : getRequires ( actFileName ) ) { if ( nodeRequiresMe ( node ) && ! getFileNames ( ) . contains ( actFileName ) ) { addAndRemove ( markedForRemoval , actFileName , fileName ) ; } } } removeMarkedFromCandidates ( markedForRemoval , candidates ) ; } while ( markedForRemoval . size ( ) > ) ; } private void addAndRemove ( ArrayList < String > markedForRemoval , String actFileName , String fileName ) { addFile ( fileName , docProvider . getFileContent ( actFileName ) ) ; markedForRemoval . add ( actFileName ) ; } private String cutProjectPath ( String fileName ) { return fileName . substring ( fileName . lastIndexOf ( '' ) + ) ; } private HashSet < String > findAllIncludedFiles ( ) { HashSet < String > includedFiles = new HashSet < String > ( ) ; ClassNodeProvider includedProvider = docProvider . getIncludedClassNodeProvider ( ) ; for ( ClassNodeWrapper classNode : includedProvider . getAllClassNodes ( ) ) { for ( PartialClassNodeWrapper partialClassNode : classNode . getPartialClassNodes ( ) ) { String file = partialClassNode . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; if ( ! file . equals ( docName ) ) { includedFiles . add ( file ) ; } } } return includedFiles ; } private String getFileNameWithoutPath ( String actFileName ) { if ( actFileName . contains ( "" ) ) { return actFileName . substring ( actFileName . lastIndexOf ( "" ) + ) ; } return actFileName ; } private boolean nodeRequiresMe ( FCallNode node ) { return isStrNode ( node ) && fileIsInResultSet ( getRequiredFilename ( node ) ) ; } private void removeMarkedFromCandidates ( ArrayList < String > markedForRemoval , Collection < String > candidates ) { for ( String actName : markedForRemoval ) { candidates . remove ( actName ) ; } } private String getRequiredFilename ( FCallNode node ) { return ( ( StrNode ) node . getArgsNode ( ) . childNodes ( ) . iterator ( ) . next ( ) ) . getValue ( ) . toString ( ) ; } private Collection < FCallNode > getRequires ( String fileName ) { try { RootNode rootNode = docProvider . getRootNode ( fileName ) ; return NodeProvider . getLoadAndRequireNodes ( rootNode ) ; } catch ( SyntaxException e ) { return new ArrayList < FCallNode > ( ) ; } } private boolean fileIsInResultSet ( String fileName ) { String pathlessName = cutProjectPath ( fileName ) ; if ( ! pathlessName . matches ( "" ) ) { pathlessName += "" ; } if ( fileName . equals ( cutProjectPath ( docName ) ) ) { return true ; } for ( String name : files . keySet ( ) ) { if ( cutProjectPath ( name ) . equals ( pathlessName ) ) { return true ; } } return false ; } private boolean isStrNode ( FCallNode node ) { return node . getArgsNode ( ) . childNodes ( ) . iterator ( ) . next ( ) instanceof StrNode ; } } package org . rubypeople . rdt . refactoring . documentprovider ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Map ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . AllFilesClassNodeProvider ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; public abstract class DocumentProvider implements IDocumentProvider { private Map < String , RootNode > cachedRootNodes ; public DocumentProvider ( ) { cachedRootNodes = new LinkedHashMap < String , RootNode > ( ) ; } public ClassNodeProvider getClassNodeProvider ( ) { return new ClassNodeProvider ( this ) ; } public ClassNodeProvider getProjectClassNodeProvider ( ) { return new AllFilesClassNodeProvider ( this ) ; } public ClassNodeProvider getIncludedClassNodeProvider ( ) { return new IncludedClassesProvider ( this ) ; } public RootNode getActiveFileRootNode ( ) { return getRootNode ( getActiveFileName ( ) ) ; } public Collection < Node > getAllNodes ( ) { ArrayList < Node > allNodes = new ArrayList < Node > ( ) ; for ( String currentFileName : getFileNames ( ) ) { allNodes . addAll ( getAllNodes ( currentFileName ) ) ; } return allNodes ; } public Collection < Node > getAllNodes ( String fileName ) { return NodeProvider . getAllNodes ( getRootNode ( fileName ) ) ; } public RootNode getRootNode ( String fileName ) { if ( ! cachedRootNodes . containsKey ( fileName ) ) { cachedRootNodes . put ( fileName , NodeProvider . getRootNode ( fileName , getFileContent ( fileName ) ) ) ; } return cachedRootNodes . get ( fileName ) ; } } package org . rubypeople . rdt . refactoring . offsetprovider ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class AfterMethodOffsetProvider extends OffsetProvider { private MethodDefNode insertAfterNode ; public AfterMethodOffsetProvider ( MethodNodeWrapper methodNode , String document ) { super ( document ) ; insertAfterNode = methodNode . getWrappedNode ( ) ; } @ Override public Node getInsertAfterNode ( ) { return insertAfterNode ; } } package org . rubypeople . rdt . refactoring . offsetprovider ; import java . util . Collection ; import org . jruby . ast . DefnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class ConstructorOffsetProvider extends OffsetProvider { private PartialClassNodeWrapper classPart ; public ConstructorOffsetProvider ( ClassNodeWrapper classNode , String document ) { this ( classNode . getFirstPartialClassNode ( ) , document ) ; } public ConstructorOffsetProvider ( PartialClassNodeWrapper classPart , String document ) { super ( document ) ; this . classPart = classPart ; } @ Override public Node getInsertAfterNode ( ) { Node contentNode = classPart . getClassBodyNode ( ) ; if ( contentNode != null ) { if ( NodeProvider . hasChildNode ( contentNode , DefnNode . class ) ) { Collection < MethodNodeWrapper > constructors = classPart . getExistingConstructors ( ) ; if ( constructors . isEmpty ( ) ) { Node firstMethodNode = NodeProvider . getFirstChildNode ( contentNode , DefnNode . class ) ; if ( NodeProvider . hasNodeBefore ( contentNode , firstMethodNode ) ) { Node nodeBefore = NodeProvider . getNodeBefore ( contentNode , firstMethodNode ) ; return nodeBefore ; } return classPart . getDeclarationEndNode ( ) ; } MethodNodeWrapper lastConstructor = constructors . toArray ( new MethodNodeWrapper [ constructors . size ( ) ] ) [ constructors . size ( ) - ] ; return lastConstructor . getWrappedNode ( ) ; } return getLastContentNode ( classPart ) ; } return classPart . getDeclarationEndNode ( ) ; } } package org . rubypeople . rdt . refactoring . offsetprovider ; public interface IOffsetProvider { public int getOffset ( ) ; } package org . rubypeople . rdt . refactoring . offsetprovider ; import org . jruby . ast . DefnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class AfterLastMethodInClassOffsetProvider extends OffsetProvider { private Node insertAfterNode ; public AfterLastMethodInClassOffsetProvider ( ClassNodeWrapper classNode , String document ) { this ( classNode . getFirstPartialClassNode ( ) , document ) ; } public AfterLastMethodInClassOffsetProvider ( PartialClassNodeWrapper classPart , String document ) { super ( document ) ; Node contentNode = classPart . getClassBodyNode ( ) ; if ( contentNode == null ) { insertAfterNode = classPart . getDeclarationEndNode ( ) ; } else { insertAfterNode = NodeProvider . getLastChildNode ( contentNode , DefnNode . class ) ; if ( insertAfterNode == null ) { insertAfterNode = NodeProvider . getLastChildNode ( contentNode ) ; } } } @ Override public Node getInsertAfterNode ( ) { return insertAfterNode ; } } package org . rubypeople . rdt . refactoring . offsetprovider ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class AfterLastNodeInMethodOffsetProvider extends OffsetProvider { private MethodNodeWrapper methodNode ; public AfterLastNodeInMethodOffsetProvider ( MethodNodeWrapper methodNode , String document ) { super ( document ) ; this . methodNode = methodNode ; } @ Override public Node getInsertAfterNode ( ) { Node methodContentNode = methodNode . getWrappedNode ( ) . getBodyNode ( ) ; if ( methodContentNode == null ) { ArgsNode argsNode = methodNode . getWrappedNode ( ) . getArgsNode ( ) ; if ( argsNode . getRequiredArgsCount ( ) > ) { return argsNode ; } return methodNode . getWrappedNode ( ) . getNameNode ( ) ; } return NodeProvider . getLastChildNode ( methodContentNode ) ; } } package org . rubypeople . rdt . refactoring . offsetprovider ; import org . jruby . ast . DefnNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class BeforeFirstMethodInClassOffsetProvider extends OffsetProvider { private Node bodyNode ; private Node declEndNode ; public BeforeFirstMethodInClassOffsetProvider ( ClassNodeWrapper classNode , String document ) { this ( classNode . getFirstPartialClassNode ( ) , document ) ; } public BeforeFirstMethodInClassOffsetProvider ( PartialClassNodeWrapper classPart , String document ) { super ( document ) ; this . bodyNode = classPart . getClassBodyNode ( ) ; this . declEndNode = classPart . getDeclarationEndNode ( ) ; } public BeforeFirstMethodInClassOffsetProvider ( ModuleNode classNode , String document ) { super ( document ) ; this . bodyNode = classNode . getBodyNode ( ) ; this . declEndNode = classNode . getCPath ( ) ; } @ Override public Node getInsertAfterNode ( ) { if ( NodeProvider . hasChildNode ( bodyNode , DefnNode . class ) ) { Node contentNode = bodyNode ; Node firstMethodNode = NodeProvider . getFirstChildNode ( contentNode , DefnNode . class ) ; if ( NodeProvider . hasNodeBefore ( contentNode , firstMethodNode ) ) { return NodeProvider . getNodeBefore ( contentNode , firstMethodNode ) ; } return declEndNode ; } return bodyNode ; } } package org . rubypeople . rdt . refactoring . offsetprovider ; import org . jruby . ast . DefnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; public class MethodOffsetProvider extends OffsetProvider { private ClassNodeWrapper classNode ; public MethodOffsetProvider ( ClassNodeWrapper classNode , String document ) { super ( document ) ; this . classNode = classNode ; } @ Override public Node getInsertAfterNode ( ) { Node contentNode = classNode . getFirstPartialClassNode ( ) . getClassBodyNode ( ) ; if ( contentNode != null ) { if ( NodeProvider . hasChildNode ( contentNode , DefnNode . class ) ) { Node lastMethodNode = NodeProvider . getLastChildNode ( contentNode , DefnNode . class ) ; return lastMethodNode ; } return getLastContentNode ( classNode . getFirstPartialClassNode ( ) ) ; } return classNode . getFirstPartialClassNode ( ) . getDeclarationEndNode ( ) ; } } package org . rubypeople . rdt . refactoring . offsetprovider ; import java . util . List ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . util . FileHelper ; public abstract class OffsetProvider implements IOffsetProvider { private String document ; public OffsetProvider ( String document ) { this . document = document ; } public abstract Node getInsertAfterNode ( ) ; public int getOffset ( ) { Node insertAfterNode = getInsertAfterNode ( ) ; if ( insertAfterNode == null ) return Integer . MAX_VALUE ; int lineNr = insertAfterNode . getPositionIncludingComments ( ) . getEndLine ( ) ; return getLineEndOffset ( lineNr - ) ; } private int getLineEndOffset ( int lineNr ) { String lineDelimiter = FileHelper . getLineDelimiter ( document ) ; int pos = - ; for ( int i = ; i <= lineNr ; i ++ ) { pos = document . indexOf ( lineDelimiter , pos + ) ; } if ( pos == - ) return document . length ( ) ; return pos ; } protected Node getLastContentNode ( PartialClassNodeWrapper classNode ) { List < Node > childNodes = classNode . getClassBodyNode ( ) . childNodes ( ) ; return ( Node ) childNodes . get ( childNodes . size ( ) - ) ; } } package org . rubypeople . rdt . refactoring . offsetprovider ; import org . jruby . ast . Node ; public class AfterNodeOffsetProvider extends OffsetProvider { private Node node ; public AfterNodeOffsetProvider ( Node node , String document ) { super ( document ) ; this . node = node ; } @ Override public Node getInsertAfterNode ( ) { return node ; } } package org . rubypeople . rdt . refactoring . editprovider ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . refactoring . util . StringHelper ; public abstract class ReplaceEditProvider extends EditProvider { public ReplaceEditProvider ( boolean doFormat , boolean doTrim ) { super ( doFormat , doTrim ) ; } public ReplaceEditProvider ( boolean doFormat ) { super ( doFormat , false ) ; } public ReplaceEditProvider ( ) { super ( false , false ) ; } @ Override public TextEdit getEdit ( String document ) { return new ReplaceEdit ( getOffset ( document ) , getOffsetLength ( document ) , getFormatedNode ( document ) ) ; } protected boolean missesClosingParenthesis ( String source ) { return StringHelper . numberOfOccurences ( '' , source ) > StringHelper . numberOfOccurences ( '' , source ) ; } protected int getOffsetLength ( String document ) { return getOffsetLength ( ) ; } protected abstract int getOffsetLength ( ) ; } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . ArrayList ; import java . util . Collection ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . TreeContentProvider ; public abstract class EditAndTreeContentProvider extends TreeContentProvider implements IEditProvider { private IEditProvider multiEditProvider ; private Collection < ITreeClass > treeClasses = new ArrayList < ITreeClass > ( ) ; public EditAndTreeContentProvider ( ) { multiEditProvider = new MultiEditProvider ( ) { @ Override protected Collection < EditProvider > getEditProviders ( ) { return EditAndTreeContentProvider . this . getEditProviders ( ) ; } } ; } @ Override public Object [ ] getElements ( Object inputElement ) { return treeClasses . toArray ( ) ; } protected void initTreeClasses ( ClassNodeProvider classNodeProvider ) { if ( classNodeProvider != null ) { for ( ClassNodeWrapper classNode : classNodeProvider . getAllClassNodes ( ) ) { ITreeClass treeClass = createTreeClass ( classNode ) ; if ( treeClass . hasChildren ( ) ) treeClasses . add ( treeClass ) ; } } } protected ITreeClass createTreeClass ( @ SuppressWarnings ( "" ) ClassNodeWrapper classNode ) { return null ; } public TextEdit getEdit ( String document ) { return multiEditProvider . getEdit ( document ) ; } public abstract Collection < EditProvider > getEditProviders ( ) ; } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . Collection ; public interface IMultiFileEditProvider { public Collection < FileMultiEditProvider > getFileEditProviders ( ) ; } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . ArrayList ; import java . util . Collection ; public class EditProviderGroup { private EditProvider first ; private EditProvider last ; private Collection < EditProvider > group ; public EditProviderGroup ( ) { group = new ArrayList < EditProvider > ( ) ; first = null ; last = null ; } public void add ( EditProvider editProvider ) { if ( first == null ) setFirst ( editProvider ) ; setLast ( editProvider ) ; group . add ( editProvider ) ; } private void setFirst ( EditProvider editProvider ) { first = editProvider ; editProvider . setFirstInGroup ( true ) ; } private void setLast ( EditProvider editProvider ) { if ( last != null ) last . setLastInGroup ( false ) ; last = editProvider ; last . setLastInGroup ( true ) ; } public Collection < EditProvider > getEditProviders ( ) { return group ; } } package org . rubypeople . rdt . refactoring . editprovider ; public interface ITreeClass { boolean hasChildren ( ) ; } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . Collection ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . TextEdit ; public abstract class MultiEditProvider implements IEditProvider { protected MultiTextEdit getMultiTextEdit ( String document ) { MultiTextEdit edit = new MultiTextEdit ( ) ; EditProviderGroups groups = new EditProviderGroups ( ) ; Collection < EditProvider > unsortedProviders = getEditProviders ( ) ; for ( EditProvider editProvider : unsortedProviders ) { String groupName = Messages . MultiEditProvider_Offset + editProvider . getOffset ( document ) ; groups . add ( groupName , editProvider ) ; } for ( IEditProvider editProvider : groups . getAllEditProviders ( ) ) { TextEdit createdEdit = editProvider . getEdit ( document ) ; edit . addChild ( createdEdit ) ; } return edit ; } public TextEdit getEdit ( String document ) { return getMultiTextEdit ( document ) ; } protected abstract Collection < EditProvider > getEditProviders ( ) ; } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . resources . IFile ; public class FileNameChangeProvider { public Map < String , String > getFilesToRename ( Collection < IFile > objects ) { return new HashMap < String , String > ( ) ; } } package org . rubypeople . rdt . refactoring . editprovider ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . util . Constants ; public abstract class InsertEditProvider extends EditProvider { public static final int INSERT_AFTER_EXISTING_NODE = ; public static final int INSERT_AT_BEGIN_OF_LINE = ; private static final int DEFAULT_INSERT_TYPE = INSERT_AFTER_EXISTING_NODE ; private int insertType ; public InsertEditProvider ( boolean doFormat ) { super ( doFormat , false ) ; insertType = DEFAULT_INSERT_TYPE ; } public TextEdit getEdit ( String document ) { String formatedNode = getFormatedNode ( document ) ; StringBuilder formatedText = new StringBuilder ( ) ; if ( insertType == INSERT_AFTER_EXISTING_NODE ) formatedText . append ( Constants . NL ) ; formatedText . append ( formatedNode ) ; if ( insertType == INSERT_AT_BEGIN_OF_LINE ) { formatedText . append ( Constants . NL ) ; } return new InsertEdit ( getOffset ( document ) , formatedText . toString ( ) ) ; } public void setInsertType ( int insertType ) { this . insertType = insertType ; } protected abstract Node getInsertNode ( int offset , String document ) ; protected Node getEditNode ( int offset , String document ) { return getInsertNode ( offset , document ) ; } } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Map ; public class MultiFileEditProvider implements IMultiFileEditProvider { private Map < String , FileMultiEditProvider > providers ; public MultiFileEditProvider ( ) { providers = new LinkedHashMap < String , FileMultiEditProvider > ( ) ; } public void addEditProvider ( FileEditProvider editProvider ) { String fileName = editProvider . getFileName ( ) ; if ( ! providers . containsKey ( fileName ) ) { providers . put ( fileName , new FileMultiEditProvider ( fileName ) ) ; } FileMultiEditProvider fileMultiEditProvider = providers . get ( fileName ) ; fileMultiEditProvider . addEditProvider ( editProvider . getDecoratedProvider ( ) ) ; } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { return providers . values ( ) ; } public void addEditProviders ( Collection < FileEditProvider > editProviders ) { for ( FileEditProvider aktEdit : editProviders ) { addEditProvider ( aktEdit ) ; } } } package org . rubypeople . rdt . refactoring . editprovider ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String MultiEditProvider_Offset ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . editprovider ; import org . jruby . ast . Node ; public class SimpleNodeEditProvider extends ReplaceEditProvider { private final Node node ; public SimpleNodeEditProvider ( Node node ) { this . node = node ; } @ Override protected int getOffsetLength ( ) { return node . getPosition ( ) . getEndOffset ( ) - node . getPosition ( ) . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return node ; } @ Override protected int getOffset ( String document ) { return node . getPosition ( ) . getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . editprovider ; import org . eclipse . text . edits . TextEdit ; public interface IEditProvider { public TextEdit getEdit ( String document ) ; } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . eclipse . text . edits . DeleteEdit ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . util . Constants ; import org . rubypeople . rdt . refactoring . util . FileHelper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class DeleteEditProvider extends EditProvider { public final static int DELETE_LINEBREAK_AFTER = ; public final static int DELETE_LINEBREAK_BEFORE = ; public final static int DEFAULT_DELETE_TYPE = DELETE_LINEBREAK_BEFORE ; private Node fromNode ; private Node toNode ; private int type ; public DeleteEditProvider ( Node fromNode , Node toNode ) { super ( true , false ) ; this . fromNode = fromNode ; this . toNode = toNode ; this . type = DEFAULT_DELETE_TYPE ; } public DeleteEditProvider ( Node node ) { this ( node , node ) ; } public TextEdit getEdit ( String document ) { int startOffset = getStartOffset ( document ) ; int endOffset = getEndOffset ( document ) ; int length = endOffset - startOffset ; return new DeleteEdit ( startOffset , length ) ; } private int getStartOffset ( String document ) { int startLine = NodeUtil . subPositionUnion ( fromNode ) . getStartLine ( ) - ; int pos = - ; String lineDelimiter = FileHelper . getLineDelimiter ( document ) ; for ( int i = ; i < startLine ; i ++ ) { pos = document . indexOf ( lineDelimiter , pos + ) ; } if ( pos < ) { pos = ; } String leadingStr = document . substring ( pos , NodeUtil . subPositionUnion ( fromNode ) . getStartOffset ( ) ) ; if ( leadingStr . trim ( ) . equals ( "" ) ) { return pos ; } return NodeUtil . subPositionUnion ( fromNode ) . getStartOffset ( ) ; } private int getEndOffset ( String document ) { int offset = NodeUtil . subPositionUnion ( toNode ) . getEndOffset ( ) ; int aktPos = offset ; Matcher matcher = Pattern . compile ( "" ) . matcher ( document ) ; String lineDelimiter = FileHelper . getLineDelimiter ( document ) ; while ( matcher . find ( aktPos ) ) { if ( matcher . start ( ) == aktPos ) { aktPos += matcher . group ( ) . length ( ) ; } else { offset = aktPos ; break ; } if ( foundTerminator ( matcher . group ( ) ) ) break ; } if ( type != DELETE_LINEBREAK_AFTER ) { if ( matcher . find ( offset ) && matcher . group ( ) . equals ( lineDelimiter ) ) { aktPos -= lineDelimiter . length ( ) ; } } return aktPos ; } private boolean foundTerminator ( String terminator ) { return ( terminator . equals ( Character . toString ( Constants . NL ) ) || terminator . equals ( "" ) ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return null ; } @ Override protected int getOffset ( String document ) { return Integer . MAX_VALUE ; } public void setDeleteType ( int deleteType ) { type = deleteType ; } } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . IScopingNode ; import org . jruby . ast . Node ; public class ScopingNodeRenameEditProvider { private final Collection < ? extends IScopingNode > nodes ; private final String newName ; public ScopingNodeRenameEditProvider ( Collection < ? extends IScopingNode > nodes , String newName ) { this . nodes = nodes ; this . newName = newName ; } public Collection < FileEditProvider > getEditProviders ( ) { Collection < FileEditProvider > edits = new ArrayList < FileEditProvider > ( ) ; for ( IScopingNode klass : nodes ) { klass . getCPath ( ) . setName ( newName ) ; edits . add ( new FileEditProvider ( ( ( Node ) klass ) . getPosition ( ) . getFile ( ) , new SimpleNodeEditProvider ( klass . getCPath ( ) ) ) ) ; } return edits ; } } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . ArrayList ; import java . util . Collection ; public class FileMultiEditProvider extends MultiEditProvider { private Collection < EditProvider > providers ; private String fileName ; public FileMultiEditProvider ( String fileName ) { this . fileName = fileName ; providers = new ArrayList < EditProvider > ( ) ; } public FileMultiEditProvider ( String fileName , EditProvider editProvider ) { this ( fileName ) ; addEditProvider ( editProvider ) ; } public void addEditProvider ( EditProvider editProvider ) { providers . add ( editProvider ) ; } public String getFileName ( ) { return fileName ; } @ Override public Collection < EditProvider > getEditProviders ( ) { return providers ; } } package org . rubypeople . rdt . refactoring . editprovider ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . FormatHelper ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . util . FileHelper ; import org . rubypeople . rdt . refactoring . util . HsrFormatter ; public abstract class EditProvider implements IEditProvider { protected boolean lastEditInGroup ; protected boolean firstEditInGroup ; private boolean doFormat ; private boolean doTrim ; public abstract TextEdit getEdit ( String document ) ; protected abstract int getOffset ( String document ) ; protected abstract Node getEditNode ( int offset , String document ) ; public EditProvider ( boolean doFormat , boolean doTrim ) { this . doFormat = doFormat ; this . doTrim = doTrim ; } protected FormatHelper getFormatHelper ( ) { return new EditableFormatHelper ( ) ; } protected String getFormatedNode ( String document ) { int offset = getOffset ( document ) ; Node insertNode = getEditNode ( offset , document ) ; String text = ReWriteVisitor . createCodeFromNode ( insertNode , document , getFormatHelper ( ) ) ; if ( doFormat ) { text = HsrFormatter . format ( document , text , offset ) ; } if ( doTrim ) { text = text . trim ( ) ; } return text . replaceAll ( "" , FileHelper . getLineDelimiter ( document ) ) ; } protected void setFirstInGroup ( boolean first ) { firstEditInGroup = first ; } protected void setLastInGroup ( boolean last ) { lastEditInGroup = last ; } protected boolean isNextLineEmpty ( int offset , String document ) { if ( document . length ( ) <= offset + ) return false ; int firstNL = getNextNLPosition ( offset , document ) ; if ( firstNL == - ) return false ; int secondNL = getNextNLPosition ( firstNL + , document ) ; if ( secondNL == - ) secondNL = document . length ( ) ; String nextLine = document . substring ( firstNL + , secondNL ) ; return nextLine . trim ( ) . length ( ) == ; } private int getNextNLPosition ( int offset , String document ) { return document . indexOf ( FileHelper . getLineDelimiter ( document ) , offset ) ; } protected ISourcePosition getExtendedPosition ( Node node ) { if ( node instanceof NewlineNode ) { node = ( ( NewlineNode ) node ) . getNextNode ( ) ; } ISourcePosition extendedPosition = node . getPositionIncludingComments ( ) ; for ( Node currentChild : node . childNodes ( ) ) { if ( currentChild . isInvisible ( ) ) continue ; extendedPosition = NodeFactory . unionPositions ( extendedPosition , getExtendedPosition ( currentChild ) ) ; } return extendedPosition ; } } package org . rubypeople . rdt . refactoring . editprovider ; public class FileEditProvider { private String fileName ; private EditProvider decoratedProvider ; public FileEditProvider ( String fileName , EditProvider decoratedProvider ) { this . fileName = fileName ; this . decoratedProvider = decoratedProvider ; } public String getFileName ( ) { return fileName ; } public EditProvider getDecoratedProvider ( ) { return decoratedProvider ; } } package org . rubypeople . rdt . refactoring . editprovider ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Map ; public class EditProviderGroups { private Map < String , EditProviderGroup > groups ; public EditProviderGroups ( ) { groups = new LinkedHashMap < String , EditProviderGroup > ( ) ; } public void add ( String groupName , EditProvider editProvider ) { EditProviderGroup group ; if ( groups . containsKey ( groupName ) ) group = groups . get ( groupName ) ; else { group = new EditProviderGroup ( ) ; groups . put ( groupName , group ) ; } group . add ( editProvider ) ; } public void add ( String groupName , Collection < EditProvider > editProviders ) { for ( EditProvider provider : editProviders ) { add ( groupName , provider ) ; } } public boolean hasGroup ( String name ) { return groups . containsKey ( name ) ; } public Collection < EditProvider > getGroup ( String groupName ) { return groups . get ( groupName ) . getEditProviders ( ) ; } public Collection < EditProvider > getAllEditProviders ( ) { Collection < EditProvider > providers = new ArrayList < EditProvider > ( ) ; for ( EditProviderGroup group : groups . values ( ) ) { providers . addAll ( group . getEditProviders ( ) ) ; } return providers ; } } package org . rubypeople . rdt . refactoring . preview ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String RubyTextEditChangePreviewViewer_OriginalSource ; public static String RubyTextEditChangePreviewViewer_RefactoredSource ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . jruby . Ruby ; import org . osgi . framework . BundleContext ; public class RefactoringPlugin extends AbstractUIPlugin { private static RefactoringPlugin plugin ; private static Ruby ruby ; public RefactoringPlugin ( ) { super ( ) ; } public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; } public void stop ( BundleContext context ) throws Exception { super . stop ( context ) ; plugin = null ; } public static RefactoringPlugin getDefault ( ) { return plugin ; } public static ImageDescriptor getImageDescriptor ( String path ) { return AbstractUIPlugin . imageDescriptorFromPlugin ( "" , path ) ; } public static Ruby getRuby ( ) { if ( ruby == null ) ruby = Ruby . getDefaultInstance ( ) ; return ruby ; } } package org . rubypeople . rdt . refactoring . util ; import java . io . FileNotFoundException ; import java . io . FileReader ; import java . io . IOException ; import java . io . Reader ; public class FileHelper { public static final String DEFAULT_LINE_DELIMITER = System . getProperty ( "" ) ; public static String getFileContent ( String fileName ) { FileReader reader = null ; try { reader = new FileReader ( fileName ) ; return getReaderContent ( reader ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } finally { if ( reader != null ) try { reader . close ( ) ; } catch ( IOException e ) { } } return null ; } private static String getReaderContent ( Reader reader ) { try { StringBuilder contentBuilder = new StringBuilder ( ) ; int character ; while ( ( character = reader . read ( ) ) != - ) { contentBuilder . append ( ( char ) character ) ; } return contentBuilder . toString ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return null ; } public static String getLineDelimiter ( String document ) { for ( int i = ; i < document . length ( ) ; i ++ ) { char currentChar = document . charAt ( i ) ; if ( currentChar == '' ) { if ( document . length ( ) > i + && document . charAt ( i + ) == '' ) { return "" ; } return "" ; } else if ( currentChar == '' ) { return "" ; } } return DEFAULT_LINE_DELIMITER ; } } package org . rubypeople . rdt . refactoring . util ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . List ; import org . jruby . ast . Colon3Node ; import org . jruby . ast . IterNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . parser . StaticScope ; public class NodeUtil { public static boolean hasScope ( Node node ) { Method [ ] methods = node . getClass ( ) . getMethods ( ) ; for ( int i = ; i < methods . length ; i ++ ) { if ( methods [ i ] . getName ( ) . equals ( "" ) || methods [ i ] . equals ( "" ) ) { return true ; } } return false ; } public static Node getBody ( Node node ) { try { Method method = node . getClass ( ) . getMethod ( "" , new Class [ ] { } ) ; return ( Node ) method . invoke ( node , new Object [ ] { } ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } return null ; } public static StaticScope getScope ( Node node ) { String methodName = "" ; if ( node instanceof MethodDefNode || node instanceof IterNode ) { methodName = "" ; } try { Method method = node . getClass ( ) . getMethod ( methodName , new Class [ ] { } ) ; return ( StaticScope ) method . invoke ( node , new Object [ ] { } ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } return null ; } public static boolean nodeAssignableFrom ( Node n , Class ... klasses ) { if ( n == null ) { return false ; } for ( Class < ? > klass : klasses ) { if ( klass . isAssignableFrom ( n . getClass ( ) ) ) { return true ; } } return false ; } public static ISourcePosition subPositionUnion ( Node node ) { ISourcePosition enclosingPosition = node . getPosition ( ) ; try { enclosingPosition = node . getPositionIncludingComments ( ) ; } catch ( Throwable t ) { } List < Node > childList = node . childNodes ( ) ; for ( Node currentChild : childList ) { if ( currentChild . equals ( NilImplicitNode . NIL ) ) { continue ; } enclosingPosition = posUnion ( enclosingPosition , subPositionUnion ( currentChild ) ) ; } return enclosingPosition ; } private static ISourcePosition posUnion ( ISourcePosition firstPos , ISourcePosition secondPos ) { String fileName = firstPos . getFile ( ) ; int startOffset = firstPos . getStartOffset ( ) ; int endOffset = firstPos . getEndOffset ( ) ; int startLine = firstPos . getStartLine ( ) ; int endLine = firstPos . getEndLine ( ) ; if ( startOffset > secondPos . getStartOffset ( ) ) { startOffset = secondPos . getStartOffset ( ) ; startLine = secondPos . getStartLine ( ) ; } if ( endOffset < secondPos . getEndOffset ( ) ) { endOffset = secondPos . getEndOffset ( ) ; endLine = secondPos . getEndLine ( ) ; } return new IDESourcePosition ( fileName , startLine , endLine , startOffset , endOffset ) ; } public static boolean positionIsInNode ( int offset , Colon3Node path ) { return offset >= path . getPosition ( ) . getStartOffset ( ) && offset <= path . getPosition ( ) . getEndOffset ( ) ; } } package org . rubypeople . rdt . refactoring . util ; public class Constants { public static final String OBJECT_NAME = "" ; public static final char NL = '' ; public static final String ARGUMENT_ERROR = "" ; public static final String CONSTRUCTOR_NAME = "" ; } package org . rubypeople . rdt . refactoring . util ; import java . util . regex . Pattern ; import org . jruby . lexer . yacc . RubyYaccLexer ; public class NameValidator { private static final String localVariableRegexp = "" ; private static final String methodNameRegexp = "" ; private static final String classNameRegexp = "" ; public static boolean isValidLocalVariableName ( String name ) { return validate ( localVariableRegexp , name ) ; } public static boolean isValidMethodName ( String name ) { return validate ( methodNameRegexp , name ) ; } public static boolean isValidConstName ( String name ) { return validate ( classNameRegexp , name ) ; } private static boolean validate ( String regexp , String stringToValidate ) { boolean valid = Pattern . compile ( regexp ) . matcher ( stringToValidate ) . matches ( ) ; return valid && RubyYaccLexer . getKeyword ( stringToValidate ) == null ; } public static boolean isValidConstantName ( String newName ) { return isValidConstName ( newName ) ; } } package org . rubypeople . rdt . refactoring . util ; public class StringHelper { public static int numberOfOccurences ( char c , String source ) { int count = ; int pos = ; while ( ( pos = source . indexOf ( c , pos ) ) != - ) { count ++ ; pos ++ ; } return count ; } } package org . rubypeople . rdt . refactoring . util ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Iterator ; import java . util . Vector ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . Colon3Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class NameHelper { public static String createName ( String string ) { Matcher matcher = Pattern . compile ( "" ) . matcher ( string ) ; if ( matcher . matches ( ) ) { return matcher . group ( ) + String . valueOf ( Integer . valueOf ( matcher . group ( ) ) . intValue ( ) + ) ; } return string + ; } public static ArrayList < String > findDuplicates ( String [ ] myNames , String [ ] oldNames ) { ArrayList < String > found = new ArrayList < String > ( ) ; for ( int i = ; i < oldNames . length ; i ++ ) { if ( namesContainName ( myNames , oldNames [ i ] ) ) { found . add ( oldNames [ i ] ) ; } } return found ; } public static boolean namesContainName ( String [ ] names , String name ) { for ( int i = ; i < names . length ; i ++ ) { if ( names [ i ] . equals ( name ) ) { return true ; } } return false ; } public static boolean fieldnameExistsInClass ( String name , ClassNodeWrapper klass ) { for ( FieldNodeWrapper currentTargetField : klass . getFields ( ) ) { if ( name . equals ( currentTargetField . getName ( ) ) ) { return true ; } } return false ; } public static boolean methodnameExistsInClassPart ( String methodName , ClassNodeWrapper klass ) { return methodsContainMethod ( klass . getMethods ( ) , methodName ) ; } private static boolean methodsContainMethod ( Collection < MethodNodeWrapper > methods , String methodName ) { for ( MethodNodeWrapper currentTargetMethod : methods ) { if ( methodName . equals ( currentTargetMethod . getName ( ) ) ) { return true ; } } return false ; } private static boolean fieldsContainField ( Collection < FieldNodeWrapper > fields , String fieldName ) { for ( FieldNodeWrapper currentField : fields ) { if ( fieldName . equals ( currentField . getName ( ) ) ) { return true ; } } return false ; } public static boolean methodnameExistsInClass ( String methodName , ClassNodeWrapper classNode ) { return methodsContainMethod ( classNode . getMethods ( ) , methodName ) ; } public static String createMethodName ( MethodNodeWrapper methodWrapper , ClassNodeWrapper klass ) { String newName = methodWrapper . getName ( ) ; while ( methodsContainMethod ( klass . getMethods ( ) , newName ) ) { newName = createName ( newName ) ; } return newName ; } public static String createFieldName ( FieldNodeWrapper fieldWrapper , ClassNodeWrapper klass ) { String newName = fieldWrapper . getName ( ) ; while ( fieldsContainField ( klass . getFields ( ) , newName ) ) { newName = createName ( newName ) ; } return newName ; } public static String getEncosingModulePrefix ( Node rootNode , Node node ) { Vector < String > nameParts = new Vector < String > ( ) ; while ( true ) { Node parent = NodeProvider . findParentNode ( rootNode , node , ModuleNode . class ) ; if ( parent == null ) { break ; } Colon3Node path = ( ( ModuleNode ) parent ) . getCPath ( ) ; if ( path != node ) { nameParts . insertElementAt ( getFullyQualifiedName ( path ) , ) ; } node = parent ; } StringBuilder prefix = new StringBuilder ( ) ; Iterator < String > it = nameParts . iterator ( ) ; while ( it . hasNext ( ) ) { String name = it . next ( ) ; prefix . append ( name ) ; if ( it . hasNext ( ) ) { prefix . append ( "" ) ; } } return prefix . toString ( ) ; } public static String getFullyQualifiedName ( Node n ) { assert n instanceof ConstNode || n instanceof Colon2Node ; if ( n instanceof ConstNode ) { ConstNode constNode = ( ConstNode ) n ; return constNode . getName ( ) ; } StringBuilder name = new StringBuilder ( ) ; ArrayList < Node > subNodes = new ArrayList < Node > ( NodeProvider . getSubNodes ( ( ( Colon2Node ) n ) . getLeftNode ( ) , Colon2Node . class , ConstNode . class ) ) ; Collections . reverse ( subNodes ) ; for ( Node node : subNodes ) { name . append ( ( ( INameNode ) node ) . getName ( ) ) ; name . append ( "" ) ; } name . append ( ( ( INameNode ) n ) . getName ( ) ) ; return name . toString ( ) ; } } package org . rubypeople . rdt . refactoring . util ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; public abstract class JRubyRefactoringUtils { public static boolean isParameter ( LocalNodeWrapper selectedItem , MethodDefNode enclosingMethod ) { return isParameter ( enclosingMethod . getScope ( ) . getVariables ( ) [ selectedItem . getId ( ) ] , enclosingMethod ) ; } public static boolean isParameter ( String name , MethodDefNode enclosingMethod ) { ArgsNode argsNode = enclosingMethod . getArgsNode ( ) ; ListNode argumentList = argsNode . getArgs ( ) ; if ( argumentList == null ) { return false ; } for ( Object currentArg : argumentList . childNodes ( ) ) { if ( currentArg instanceof ArgumentNode ) { ArgumentNode arg = ( ArgumentNode ) currentArg ; if ( arg . getName ( ) . equals ( name ) ) { return true ; } } } return false ; } public static boolean isMathematicalExpression ( Node node ) { if ( ! ( node instanceof CallNode ) ) { return false ; } String name = ( ( CallNode ) node ) . getName ( ) ; String [ ] operators = new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , ">" , "" , "" , "" , "" , "" , "" , "" } ; for ( String currentOp : operators ) { if ( name . equals ( currentOp ) ) { return true ; } } return false ; } public static boolean hasSamePosition ( Node node1 , Node node2 ) { String file1 = node1 . getPosition ( ) . getFile ( ) ; String file2 = node2 . getPosition ( ) . getFile ( ) ; if ( ! file1 . equals ( file2 ) ) { return false ; } int start1 = node1 . getPosition ( ) . getStartOffset ( ) ; int start2 = node2 . getPosition ( ) . getStartOffset ( ) ; if ( start1 != start2 ) { return false ; } int end1 = node1 . getPosition ( ) . getEndOffset ( ) ; int end2 = node2 . getPosition ( ) . getEndOffset ( ) ; if ( end1 != end2 ) { return false ; } return true ; } } package org . rubypeople . rdt . refactoring . util ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . text . edits . MalformedTreeException ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . formatter . OldCodeFormatter ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class HsrFormatter { public static String format ( String document , String replaceText , int replaceStartOffset , int replaceEndOffset ) { StringBuilder docStringBuilder = new StringBuilder ( document ) ; docStringBuilder . delete ( replaceStartOffset , replaceEndOffset ) ; return format ( docStringBuilder . toString ( ) , replaceText , replaceStartOffset ) ; } public static String format ( String document , String insertText , int insertOffset ) { if ( insertText . length ( ) == ) return insertText ; String lineDelimiter = "" ; if ( document . length ( ) == ) return formatString ( insertText , lineDelimiter ) ; StringBuilder docStringBuilder = new StringBuilder ( document ) ; insertText = lineDelimiter + insertText + lineDelimiter ; if ( insertOffset == document . length ( ) ) { docStringBuilder . append ( insertText ) ; } else { docStringBuilder . insert ( insertOffset , insertText ) ; } int end = insertOffset + insertText . length ( ) - ; insertOffset += lineDelimiter . length ( ) ; int linesToSort = getLineCount ( docStringBuilder . toString ( ) , insertOffset , end , lineDelimiter ) ; int lnNr = getLnNr ( docStringBuilder . toString ( ) , insertOffset - , lineDelimiter ) ; document = docStringBuilder . toString ( ) ; String formattedDocument = formatString ( document , lineDelimiter ) ; String text = getSubstring ( formattedDocument , lnNr , linesToSort , lineDelimiter ) ; return text ; } private static String formatString ( String code , String lineDelimiter ) { Document doc = new Document ( code ) ; try { getFormatter ( ) . format ( , code , , code . length ( ) , , lineDelimiter ) . apply ( doc ) ; return doc . get ( ) ; } catch ( MalformedTreeException e ) { e . printStackTrace ( ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } return "" ; } private static OldCodeFormatter getFormatter ( ) { if ( RubyPlugin . getDefault ( ) != null ) { return RubyPlugin . getDefault ( ) . getCodeFormatter ( ) ; } Map < String , String > options = new HashMap < String , String > ( ) ; options . put ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , "" ) ; options . put ( DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE , "" ) ; options . put ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE , "" ) ; return new OldCodeFormatter ( options ) ; } private static String getSubstring ( String str , int lnNr , int lnCount , String lineDelimiter ) { int start = - ; int stop = ; for ( int i = ; i < lnNr ; i ++ ) { start = str . indexOf ( lineDelimiter , start + ) ; } start ++ ; stop = start - ; for ( int i = ; i < lnCount ; i ++ ) { int tmpStop = str . indexOf ( lineDelimiter , stop + ) ; if ( tmpStop != - ) { stop = tmpStop ; } else { break ; } } str = str . substring ( start , stop ) ; return str ; } private static int getLineCount ( String text , int offset , int end , String lineDelimiter ) { int count = ; int pos = offset - ; while ( ( pos = text . indexOf ( lineDelimiter , pos + ) ) <= end && pos != - ) { count ++ ; } return ++ count ; } private static int getLnNr ( String text , int offset , String lineDelimiter ) { return getLineCount ( text , , offset , lineDelimiter ) - ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; public class AttrAccessorNodeWrapper implements INodeWrapper { private Collection < FCallNode > callNodes ; private AccessorType accessorType ; private String name ; private String fileName ; private SymbolNode symbolNode ; public static final String ATTR_WRITER = "" ; public static final String ATTR_READER = "" ; public static final String ATTR_ACCESSOR = "" ; private static final String [ ] typeNames = { ATTR_WRITER , ATTR_READER , ATTR_ACCESSOR } ; public AttrAccessorNodeWrapper ( FCallNode callNode , SymbolNode symbolNode ) { this . symbolNode = symbolNode ; callNodes = new ArrayList < FCallNode > ( ) ; callNodes . add ( callNode ) ; accessorType = new AccessorType ( callNode . getName ( ) ) ; name = getName ( ) ; fileName = callNode . getPosition ( ) . getFile ( ) ; } private String getName ( ) { return ( symbolNode . getName ( ) . charAt ( ) == '' ) ? symbolNode . getName ( ) . substring ( ) : symbolNode . getName ( ) ; } public String getAccessorTypeName ( ) { return accessorType . getTypeName ( ) ; } public String getAttrName ( ) { return name ; } public boolean isWriter ( ) { return accessorType . isWriter ( ) ; } public boolean isReader ( ) { return accessorType . isReader ( ) ; } public void addAccessorType ( AttrAccessorNodeWrapper otherAccessorNode ) { accessorType . addOtherType ( otherAccessorNode . getAccessorTypeName ( ) ) ; callNodes . addAll ( otherAccessorNode . callNodes ) ; } private static class AccessorType { private static final int TYPE_WRITER = ; private static final int TYPE_READER = ; private static final int TYPE_ACCESSOR = ; private int type ; public AccessorType ( String typeName ) { type = evaluateType ( typeName ) ; } private int evaluateType ( String typeName ) { if ( typeName . equals ( ATTR_WRITER ) ) { return TYPE_WRITER ; } return ( typeName . equals ( ATTR_READER ) ) ? TYPE_READER : TYPE_ACCESSOR ; } public void addOtherType ( String otherTypeName ) { int otherType = evaluateType ( otherTypeName ) ; type = type | otherType ; } public String getTypeName ( ) { return typeNames [ type - ] ; } public boolean isWriter ( ) { return ( type & TYPE_WRITER ) != ; } public boolean isReader ( ) { return ( type & TYPE_READER ) != ; } public boolean contains ( AccessorType otherType ) { int andResult = otherType . type & type ; return andResult == otherType . type ; } } public Collection < FCallNode > getAccessorNodes ( ) { return callNodes ; } public String getFileName ( ) { return fileName ; } public SymbolNode getSymbolNode ( ) { return symbolNode ; } public boolean containsAccessor ( AttrAccessorNodeWrapper otherAccessor ) { if ( otherAccessor . getAttrName ( ) . equals ( getAttrName ( ) ) ) { if ( accessorType . contains ( otherAccessor . accessorType ) ) { return true ; } } return false ; } public Node getWrappedNode ( ) { return callNodes . toArray ( new Node [ callNodes . size ( ) ] ) [ ] ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . DefsNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . signatureprovider . MethodSignature ; import org . rubypeople . rdt . refactoring . util . Constants ; public class MethodNodeWrapper implements INodeWrapper { protected MethodDefNode methodNode ; private final ClassNodeWrapper containingClass ; public MethodNodeWrapper ( MethodDefNode methodDef , ClassNodeWrapper containingClass ) { this . methodNode = methodDef ; this . containingClass = containingClass ; } public String getName ( ) { return methodNode . getName ( ) ; } public MethodSignature getSignature ( ) { return new MethodSignature ( methodNode . getName ( ) , getArgsNode ( ) ) ; } public ArgsNodeWrapper getArgsNode ( ) { return new ArgsNodeWrapper ( methodNode . getArgsNode ( ) ) ; } public MethodDefNode getWrappedNode ( ) { return methodNode ; } public boolean isClassMethod ( ) { return methodNode instanceof DefsNode ; } public Collection < MethodCallNodeWrapper > getMethodCallNodes ( ) { return NodeProvider . getMethodCallNodes ( methodNode ) ; } @ Override public int hashCode ( ) { final int PRIME = ; int result = ; result = PRIME * result + ( isClassMethod ( ) ? : ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof MethodNodeWrapper ) { MethodNodeWrapper otherMethodNode = ( MethodNodeWrapper ) obj ; return getSignature ( ) . equals ( otherMethodNode . getSignature ( ) ) ; } return false ; } public boolean isConstructor ( ) { return getName ( ) . equals ( Constants . CONSTRUCTOR_NAME ) ; } public ISourcePosition getPosition ( ) { return methodNode . getPosition ( ) ; } public String [ ] getLocalNames ( ) { return methodNode . getScope ( ) . getVariables ( ) ; } public Node getBodyNode ( ) { return methodNode . getBodyNode ( ) ; } public Collection < MethodCallNodeWrapper > getCallCandidatesInClass ( ClassNodeWrapper classNode ) { if ( classNode == null ) { return new ArrayList < MethodCallNodeWrapper > ( ) ; } return classNode . getMethodCalls ( methodNode ) ; } public Collection < SymbolNode > getSymbolCandidatesInClass ( ClassNodeWrapper classNode ) { if ( classNode == null ) { return new ArrayList < SymbolNode > ( ) ; } return classNode . getMethodSymbols ( methodNode ) ; } public boolean isAccessor ( ) { return isWriter ( ) || isReader ( ) ; } public boolean isWriter ( ) { if ( containingClass == null ) { return false ; } for ( FieldNodeWrapper field : containingClass . getFields ( ) ) { if ( ( field . getNameWithoutAts ( ) + "" ) . equals ( getName ( ) ) && getSignature ( ) . getArguments ( ) . size ( ) == ) { return true ; } } return false ; } public boolean isReader ( ) { if ( containingClass == null ) { return false ; } for ( FieldNodeWrapper field : containingClass . getFields ( ) ) { if ( field . getNameWithoutAts ( ) . equals ( getName ( ) ) && getSignature ( ) . getArguments ( ) . isEmpty ( ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class LocalNodeWrapper implements INodeWrapper { public static final int INVALID_ID = - ; public static final int LOCAL_ASGN_VAR_NODE = ; public static final int LOCAL_VAR_NODE = ; public static final int D_VAR_NODE = ; public static final int D_ASGN_NODE = ; public static final Class [ ] LOCAL_NODES_CLASSES = { LocalAsgnNode . class , LocalVarNode . class , DVarNode . class , DAsgnNode . class } ; private Node wrappedNode ; private int nodeType ; private Node valueNode ; private String name ; private int id ; public LocalNodeWrapper ( Node node ) { id = INVALID_ID ; if ( NodeUtil . nodeAssignableFrom ( node , LocalVarNode . class ) ) { id = ( ( LocalVarNode ) node ) . getIndex ( ) ; name = ( ( LocalVarNode ) node ) . getName ( ) ; nodeType = LOCAL_VAR_NODE ; } else if ( NodeUtil . nodeAssignableFrom ( node , LocalAsgnNode . class ) ) { LocalAsgnNode localAsgnNode = ( LocalAsgnNode ) node ; id = localAsgnNode . getIndex ( ) ; name = localAsgnNode . getName ( ) ; nodeType = LOCAL_ASGN_VAR_NODE ; valueNode = localAsgnNode . getValueNode ( ) ; } else if ( NodeUtil . nodeAssignableFrom ( node , DAsgnNode . class ) ) { DAsgnNode dAsgnNode = ( DAsgnNode ) node ; name = dAsgnNode . getName ( ) ; nodeType = D_ASGN_NODE ; valueNode = dAsgnNode . getValueNode ( ) ; } else if ( NodeUtil . nodeAssignableFrom ( node , DVarNode . class ) ) { DVarNode dVarNode = ( DVarNode ) node ; name = dVarNode . getName ( ) ; nodeType = D_VAR_NODE ; } wrappedNode = node ; } public Node getWrappedNode ( ) { return wrappedNode ; } public boolean hasValidId ( ) { return id != INVALID_ID ; } public int getId ( ) { return id ; } public int getNodeType ( ) { return nodeType ; } public Node getValueNode ( ) { return valueNode ; } public boolean hasValueNode ( ) { return valueNode != null ; } public boolean hasName ( ) { return name != null ; } public String getName ( ) { return name ; } public boolean isAsgnNode ( ) { return nodeType == LOCAL_ASGN_VAR_NODE || nodeType == D_ASGN_NODE ; } public boolean isDVarNode ( ) { return nodeType == D_VAR_NODE || nodeType == D_ASGN_NODE ; } public void setName ( String name ) { if ( nodeType != LOCAL_VAR_NODE ) { this . name = name ; } if ( NodeUtil . nodeAssignableFrom ( wrappedNode , LocalVarNode . class ) ) { LocalVarNode localVarNode = ( LocalVarNode ) wrappedNode ; localVarNode . setName ( name ) ; } else if ( NodeUtil . nodeAssignableFrom ( wrappedNode , LocalAsgnNode . class ) ) { LocalAsgnNode localAsgnNode = ( LocalAsgnNode ) wrappedNode ; localAsgnNode . setName ( name ) ; } else if ( NodeUtil . nodeAssignableFrom ( wrappedNode , DAsgnNode . class ) ) { DAsgnNode dAsgnNode = ( DAsgnNode ) wrappedNode ; dAsgnNode . setName ( name ) ; } else if ( NodeUtil . nodeAssignableFrom ( wrappedNode , DVarNode . class ) ) { DVarNode dVarNode = ( DVarNode ) wrappedNode ; dVarNode . setName ( name ) ; } } public static String getLocalNodeName ( LocalNodeWrapper node ) { return node . getName ( ) ; } public static Collection < LocalNodeWrapper > gatherLocalNodes ( Node baseNode ) { return gatherLocalNodes ( baseNode , LOCAL_NODES_CLASSES ) ; } public static Collection < LocalNodeWrapper > gatherLocalVarNodes ( Node baseNode ) { return gatherLocalNodes ( baseNode , DVarNode . class , LocalVarNode . class ) ; } public static Collection < LocalNodeWrapper > gatherLocalAsgnNodes ( Node baseNode ) { return gatherLocalNodes ( baseNode , DAsgnNode . class , LocalAsgnNode . class ) ; } private static Collection < LocalNodeWrapper > gatherLocalNodes ( Node baseNode , Class ... klasses ) { Collection < LocalNodeWrapper > localNodes = new ArrayList < LocalNodeWrapper > ( ) ; for ( Node aktNode : NodeProvider . getSubNodes ( baseNode , klasses ) ) { localNodes . add ( new LocalNodeWrapper ( aktNode ) ) ; } return localNodes ; } public static Collection < LocalNodeWrapper > createLocalNodes ( Collection < Node > nodes ) { Collection < LocalNodeWrapper > localNodes = new ArrayList < LocalNodeWrapper > ( ) ; for ( Node aktNode : nodes ) { if ( NodeUtil . nodeAssignableFrom ( aktNode , LOCAL_NODES_CLASSES ) ) { localNodes . add ( new LocalNodeWrapper ( aktNode ) ) ; } } return localNodes ; } @ Override public int hashCode ( ) { final int PRIME = ; int result = ; result = PRIME * result + ( ( wrappedNode == null ) ? : wrappedNode . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof LocalNodeWrapper ) { LocalNodeWrapper localNode = ( LocalNodeWrapper ) obj ; return localNode . getWrappedNode ( ) . equals ( getWrappedNode ( ) ) ; } return false ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . BlockArgNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . RestArgNode ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; public class ArgsNodeWrapper implements INodeWrapper { private ArgsNode argsNode ; private Collection < String > argumentNames ; public ArgsNodeWrapper ( ArgsNode argsNode ) { this . argsNode = argsNode ; argumentNames = new ArrayList < String > ( ) ; if ( hasArgs ( ) ) { ListNode list = argsNode . getArgs ( ) ; for ( Object obj : list . childNodes ( ) ) { if ( obj instanceof ArgumentNode ) { argumentNames . add ( ( ( ArgumentNode ) obj ) . getName ( ) ) ; } } } } public String getArgsListAsString ( ) { if ( ! hasArgs ( ) ) return "" ; StringBuilder argList = new StringBuilder ( ) ; for ( String argName : argumentNames ) { argList . append ( argName + "" ) ; } return '' + argList . substring ( , argList . length ( ) - ) ; } public Collection < String > getArgsList ( ) { return argumentNames ; } public boolean hasArgs ( ) { return argsNode . getRequiredArgsCount ( ) != || argsNode . getOptArgs ( ) != null || argsNode . getBlockArgNode ( ) != null || argsNode . getRestArg ( ) > ; } public ListNode getOptArgs ( ) { return argsNode . getOptArgs ( ) ; } public BlockArgNode getBlockArgNode ( ) { return argsNode . getBlockArgNode ( ) ; } public int getRestArg ( ) { return argsNode . getRestArg ( ) ; } public ArgsNode getWrappedNode ( ) { return argsNode ; } public ArgsNodeWrapper cloneWithNewArgName ( String newArgName ) { Collection < String > newArgNames = new ArrayList < String > ( argumentNames ) ; newArgNames . add ( newArgName ) ; ArgsNode tempArgsNode = NodeFactory . createArgsNode ( newArgNames . toArray ( new String [ newArgNames . size ( ) ] ) , argsNode . getOptArgs ( ) , argsNode . getRestArg ( ) , ( RestArgNode ) argsNode . getRestArgNode ( ) , argsNode . getBlockArgNode ( ) ) ; return new ArgsNodeWrapper ( tempArgsNode ) ; } public boolean argsCountMatches ( MethodCallNodeWrapper callNode ) { int callArgs = callNode . getArgsCount ( ) ; int minArgs = argsNode . getRequiredArgsCount ( ) ; int maxArgs = minArgs + getOptArgsCount ( ) ; if ( argsNode . getRestArg ( ) >= ) { maxArgs = Integer . MAX_VALUE ; } return ( callArgs >= minArgs ) && ( callArgs <= maxArgs ) ; } private int getOptArgsCount ( ) { if ( getOptArgs ( ) == null ) { return ; } return getOptArgs ( ) . size ( ) ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class FieldNodeWrapper implements INodeWrapper { public static final int INVALID_TYPE = - ; public static final int INST_ASGN_NODE = ; public static final int INST_VAR_NODE = ; public static final int CLASS_VAR_ASGN_NODE = ; public static final int CLASS_VAR_NODE = ; public static final int SYMBOL_NODE = ; public static final int CLASS_VAR_DECL_NODE = ; final static Class [ ] FIELD_NODE_CLASSES = { InstAsgnNode . class , InstVarNode . class , ClassVarAsgnNode . class , ClassVarNode . class , ClassVarDeclNode . class , SymbolNode . class } ; static final Class [ ] FIELD_NODE_CLASSES_WITHOUT_SYMBOL_NODE = { InstAsgnNode . class , InstVarNode . class , ClassVarAsgnNode . class , ClassVarNode . class , ClassVarDeclNode . class } ; public static final String ATTR_NAME = "" ; private Node wrappedNode ; private int nodeType ; private String name ; public FieldNodeWrapper ( Node node ) { nodeType = INVALID_TYPE ; if ( NodeUtil . nodeAssignableFrom ( node , InstAsgnNode . class ) ) { nodeType = INST_ASGN_NODE ; InstAsgnNode instAsgnNode = ( InstAsgnNode ) node ; name = instAsgnNode . getName ( ) ; } else if ( NodeUtil . nodeAssignableFrom ( node , InstVarNode . class ) ) { InstVarNode instVarNode = ( InstVarNode ) node ; name = instVarNode . getName ( ) ; nodeType = INST_VAR_NODE ; } else if ( NodeUtil . nodeAssignableFrom ( node , ClassVarAsgnNode . class ) ) { ClassVarAsgnNode classVarAsgnNode = ( ClassVarAsgnNode ) node ; name = classVarAsgnNode . getName ( ) ; nodeType = CLASS_VAR_ASGN_NODE ; } else if ( NodeUtil . nodeAssignableFrom ( node , ClassVarNode . class ) ) { ClassVarNode classVarNode = ( ClassVarNode ) node ; name = classVarNode . getName ( ) ; nodeType = CLASS_VAR_NODE ; } else if ( NodeUtil . nodeAssignableFrom ( node , SymbolNode . class ) ) { SymbolNode symbolNode = ( SymbolNode ) node ; name = symbolNode . getName ( ) ; nodeType = SYMBOL_NODE ; } else if ( NodeUtil . nodeAssignableFrom ( node , ClassVarDeclNode . class ) ) { ClassVarDeclNode classVarDeclNode = ( ClassVarDeclNode ) node ; name = classVarDeclNode . getName ( ) ; nodeType = CLASS_VAR_DECL_NODE ; } wrappedNode = node ; } public Node getWrappedNode ( ) { return wrappedNode ; } public String getName ( ) { return name ; } public String getNameWithoutAts ( ) { return name . replaceFirst ( "" , "" ) ; } public int getNodeType ( ) { return nodeType ; } public boolean isInstVar ( ) { return ( nodeType == INST_ASGN_NODE || nodeType == INST_VAR_NODE || nodeType == SYMBOL_NODE ) ; } public boolean isClassVar ( ) { return ( nodeType == CLASS_VAR_ASGN_NODE || nodeType == CLASS_VAR_NODE || nodeType == CLASS_VAR_DECL_NODE ) ; } public boolean isAsgnNode ( ) { return nodeType == INST_ASGN_NODE || nodeType == CLASS_VAR_ASGN_NODE || nodeType == CLASS_VAR_DECL_NODE ; } public ISourcePosition getPosition ( ) { return wrappedNode . getPosition ( ) ; } public static Class [ ] fieldNodeClasses ( ) { return FIELD_NODE_CLASSES . clone ( ) ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import org . jruby . ast . AttrAssignNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . VCallNode ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class MethodCallNodeWrapper implements INodeWrapper { static final Class [ ] METHOD_CALL_NODE_CLASSES = { CallNode . class , VCallNode . class , FCallNode . class , AttrAssignNode . class } ; public static final int INVALID_TYPE = - ; public static final int CALL_NODE = ; public static final int V_CALL_NODE = ; public static final int F_CALL_NODE = ; private int nodeType ; private Node wrappedNode ; private Node receiverNode ; private Node argsNode ; private String name ; public MethodCallNodeWrapper ( Node node ) { this . wrappedNode = node ; if ( NodeUtil . nodeAssignableFrom ( node , CallNode . class ) ) { CallNode callNode = ( CallNode ) node ; nodeType = CALL_NODE ; receiverNode = callNode . getReceiverNode ( ) ; argsNode = callNode . getArgsNode ( ) ; name = callNode . getName ( ) ; } else if ( NodeUtil . nodeAssignableFrom ( node , AttrAssignNode . class ) ) { AttrAssignNode callNode = ( AttrAssignNode ) node ; nodeType = CALL_NODE ; receiverNode = callNode . getReceiverNode ( ) ; argsNode = callNode . getArgsNode ( ) ; name = callNode . getName ( ) ; } else if ( NodeUtil . nodeAssignableFrom ( node , VCallNode . class ) ) { nodeType = V_CALL_NODE ; name = ( ( VCallNode ) node ) . getName ( ) ; } else if ( NodeUtil . nodeAssignableFrom ( node , FCallNode . class ) ) { FCallNode fCallNode = ( FCallNode ) node ; nodeType = F_CALL_NODE ; name = fCallNode . getName ( ) ; argsNode = fCallNode . getArgsNode ( ) ; } else { nodeType = INVALID_TYPE ; } } public boolean isCallNode ( ) { return nodeType == CALL_NODE ; } public boolean isVCallNode ( ) { return nodeType == V_CALL_NODE ; } public boolean isFCallNode ( ) { return nodeType == F_CALL_NODE ; } public Node getReceiverNode ( ) { return receiverNode ; } public String getName ( ) { return name ; } public String getFileName ( ) { return getPosition ( ) . getFile ( ) ; } public ISourcePosition getPosition ( ) { return wrappedNode . getPosition ( ) ; } public Node getArgsNode ( ) { return argsNode ; } public int getType ( ) { return nodeType ; } public boolean isCallToClassMethod ( ) { return NodeUtil . nodeAssignableFrom ( receiverNode , ConstNode . class ) ; } public Node getWrappedNode ( ) { return wrappedNode ; } public int getArgsCount ( ) { if ( argsNode == null ) { return ; } return argsNode . childNodes ( ) . size ( ) ; } public String getReceiverName ( ) { if ( receiverNode instanceof INameNode ) { return ( ( INameNode ) receiverNode ) . getName ( ) ; } return null ; } public static Class [ ] METHOD_CALL_NODE_CLASSES ( ) { return METHOD_CALL_NODE_CLASSES . clone ( ) ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Iterator ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . FCallNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . SClassNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . VCallNode ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . renamemodule . ModuleSpecifierWrapper ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public abstract class PartialClassNodeWrapper implements INodeWrapper { private Node wrappedNode ; private Collection < ModuleNode > enclosingModules ; private Collection < MethodNodeWrapper > methods ; private Collection < FieldNodeWrapper > fields ; private Collection < Node > attributes ; public PartialClassNodeWrapper ( Node node ) { wrappedNode = node ; } public Collection < FieldNodeWrapper > getFields ( ) { if ( fields == null ) { fields = getFieldsFromNode ( wrappedNode ) ; } return fields ; } public static Collection < FieldNodeWrapper > getFieldsFromNode ( Node wrappedNode ) { Collection < FieldNodeWrapper > fields = new ArrayList < FieldNodeWrapper > ( ) ; Collection < Node > fieldNodes = NodeProvider . getSubNodes ( wrappedNode , FieldNodeWrapper . FIELD_NODE_CLASSES_WITHOUT_SYMBOL_NODE ) ; for ( Node currentField : fieldNodes ) { fields . add ( new FieldNodeWrapper ( currentField ) ) ; } addSymbolNodeFields ( fields , wrappedNode ) ; return fields ; } private static void addSymbolNodeFields ( Collection < FieldNodeWrapper > fields , Node wrappedNode ) { Collection < AttrAccessorNodeWrapper > accessors = NodeProvider . getAccessorNodes ( wrappedNode ) ; for ( AttrAccessorNodeWrapper aktAcessor : accessors ) { fields . add ( new FieldNodeWrapper ( aktAcessor . getSymbolNode ( ) ) ) ; } for ( Node aktNode : NodeProvider . getSubNodes ( wrappedNode , FCallNode . class ) ) { FCallNode aktFCallNode = ( FCallNode ) aktNode ; if ( aktFCallNode . getName ( ) . equals ( FieldNodeWrapper . ATTR_NAME ) ) { addAttrNodeFields ( aktFCallNode , fields ) ; } } } private static void addAttrNodeFields ( FCallNode callNode , Collection < FieldNodeWrapper > fields ) { if ( NodeUtil . nodeAssignableFrom ( callNode . getArgsNode ( ) , ArrayNode . class ) ) { for ( Object o : callNode . getArgsNode ( ) . childNodes ( ) ) { Node aktNode = ( Node ) o ; if ( NodeUtil . nodeAssignableFrom ( aktNode , SymbolNode . class ) ) { SymbolNode symbolNode = ( ( SymbolNode ) aktNode ) ; fields . add ( new FieldNodeWrapper ( symbolNode ) ) ; } } } } public Collection < MethodNodeWrapper > getMethods ( ) { if ( methods == null ) { methods = new ArrayList < MethodNodeWrapper > ( ) ; Collection < Node > methodNodes = NodeProvider . getSubNodes ( wrappedNode , MethodDefNode . class ) ; for ( Node methodNode : methodNodes ) { methods . add ( new MethodNodeWrapper ( ( MethodDefNode ) methodNode , new ClassNodeWrapper ( this ) ) ) ; } } return methods ; } public abstract Node getClassBodyNode ( ) ; public abstract String getClassName ( ) ; public Node getWrappedNode ( ) { return wrappedNode ; } public abstract Node getDeclarationEndNode ( ) ; public abstract String getSuperClassName ( ) ; public Collection < Node > getAttrNodes ( ) { if ( attributes == null ) { Collection < Node > allAttrs = NodeProvider . getAttributeNodes ( wrappedNode ) ; attributes = new ArrayList < Node > ( ) ; for ( Node node : allAttrs ) { if ( ! isDirectChild ( node ) ) attributes . add ( node ) ; } } return attributes ; } private boolean isDirectChild ( Node child ) { return isDirectChild ( child , wrappedNode ) ; } private boolean isDirectChild ( Node child , Node parent ) { for ( Object aktChild : parent . childNodes ( ) ) { if ( aktChild . equals ( child ) ) return true ; if ( ignoreInDirectChildLine ( ( Node ) aktChild ) ) if ( isDirectChild ( child , ( Node ) aktChild ) ) return true ; } return false ; } private boolean ignoreInDirectChildLine ( Node node ) { return node instanceof NewlineNode || node instanceof BlockNode ; } public static PartialClassNodeWrapper getPartialClassNodeWrapper ( Node node , Node rootNode ) throws NoClassNodeException { if ( node instanceof ClassNode ) return new RealClassNodeWrapper ( node ) ; if ( node instanceof SClassNode ) return new SClassNodeWrapper ( node , rootNode ) ; throw new NoClassNodeException ( ) ; } public Collection < AttrAccessorNodeWrapper > getAccessorNodes ( ) { return NodeProvider . getAccessorNodes ( wrappedNode ) ; } public String getFile ( ) { return wrappedNode . getPosition ( ) . getFile ( ) ; } public void setEnclosingModules ( Collection < ModuleNode > enclosingModules ) { if ( enclosingModules . size ( ) > ) { this . enclosingModules = enclosingModules ; } } public String getModulePrefix ( ) { if ( enclosingModules == null ) { return "" ; } StringBuilder modulePrefix = new StringBuilder ( ) ; Iterator < ModuleNode > it = enclosingModules . iterator ( ) ; while ( it . hasNext ( ) ) { ModuleNode currentModule = it . next ( ) ; Node cPath = currentModule . getCPath ( ) ; if ( cPath instanceof Colon2Node ) { modulePrefix . append ( ( ( Colon2Node ) cPath ) . getName ( ) ) ; if ( it . hasNext ( ) ) { modulePrefix . append ( "" ) ; } } } return modulePrefix . toString ( ) ; } public Collection < Node > getInstFieldOccurences ( ) { return NodeProvider . getInstFieldOccurences ( wrappedNode ) ; } public Collection < Node > getClassFieldOccurences ( ) { return NodeProvider . getClassFieldOccurences ( wrappedNode ) ; } public Collection < ModuleSpecifierWrapper > getIncludeCalls ( ) { Collection < ModuleSpecifierWrapper > includes = new ArrayList < ModuleSpecifierWrapper > ( ) ; for ( Node node : NodeProvider . getSubNodes ( wrappedNode , FCallNode . class ) ) { FCallNode call = ( FCallNode ) node ; if ( "" . equals ( call . getName ( ) ) ) { includes . add ( ModuleSpecifierWrapper . create ( ( ( ArrayNode ) call . getArgsNode ( ) ) . get ( ) , getModulePrefix ( ) ) ) ; } } return includes ; } public Collection < MethodCallNodeWrapper > getMethodCalls ( MethodDefNode decoratedMethod ) { ArrayList < MethodCallNodeWrapper > localCalls = new ArrayList < MethodCallNodeWrapper > ( ) ; Collection < Node > callNodes = NodeProvider . getSubNodes ( this . wrappedNode , VCallNode . class , CallNode . class , FCallNode . class ) ; for ( Node currentCall : callNodes ) { MethodCallNodeWrapper callNode = new MethodCallNodeWrapper ( currentCall ) ; if ( callNode . getName ( ) . equals ( decoratedMethod . getName ( ) ) ) { localCalls . add ( callNode ) ; } } return localCalls ; } public Collection < SymbolNode > getMethodSymbols ( MethodDefNode decoratedNode ) { ArrayList < SymbolNode > localSymbols = new ArrayList < SymbolNode > ( ) ; Collection < Node > fCallNodes = NodeProvider . getSubNodes ( this . wrappedNode , FCallNode . class ) ; for ( Node currentCall : fCallNodes ) { FCallNode currentFCall = ( FCallNode ) currentCall ; String callName = currentFCall . getName ( ) ; if ( VisibilityNodeWrapper . isVisibilityString ( callName ) || "" . equals ( callName ) ) { Collection < Node > symbolNodes = NodeProvider . getSubNodes ( currentFCall , SymbolNode . class ) ; for ( Node currentItem : symbolNodes ) { SymbolNode currentSymbol = ( SymbolNode ) currentItem ; if ( currentSymbol . getName ( ) . equals ( decoratedNode . getName ( ) ) ) { localSymbols . add ( currentSymbol ) ; } } } } return localSymbols ; } public METHOD_VISIBILITY getPosVisibility ( int pos ) { Collection < Node > vCallNodes = NodeProvider . getSubNodes ( wrappedNode , VCallNode . class ) ; VCallNode lastMatch = null ; for ( Node aktNode : vCallNodes ) { VCallNode aktVCallNode = ( VCallNode ) aktNode ; if ( VisibilityNodeWrapper . isVisibilityString ( aktVCallNode . getName ( ) ) ) { if ( aktVCallNode . getPosition ( ) . getEndOffset ( ) <= pos ) { lastMatch = aktVCallNode ; } else { break ; } } } if ( lastMatch == null ) { return METHOD_VISIBILITY . PUBLIC ; } return VisibilityNodeWrapper . getVisibility ( lastMatch . getName ( ) ) ; } public Collection < MethodCallNodeWrapper > getMethodCallNodes ( ) { return NodeProvider . getMethodCallNodes ( wrappedNode ) ; } public Collection < MethodNodeWrapper > getExistingConstructors ( ) { Collection < MethodNodeWrapper > methodNodes = getMethods ( ) ; Collection < MethodNodeWrapper > constructors = new ArrayList < MethodNodeWrapper > ( ) ; for ( MethodNodeWrapper aktMethod : methodNodes ) { if ( aktMethod . isConstructor ( ) ) { constructors . add ( aktMethod ) ; } } return constructors ; } public Collection < VisibilityNodeWrapper > getMethodVisibilityNodes ( ) { Collection < Node > fCallNodes = NodeProvider . getSubNodes ( wrappedNode , FCallNode . class ) ; Collection < VisibilityNodeWrapper > visibilities = new ArrayList < VisibilityNodeWrapper > ( ) ; for ( Node aktNode : fCallNodes ) { FCallNode aktFCallNode = ( FCallNode ) aktNode ; if ( VisibilityNodeWrapper . isVisibilityString ( aktFCallNode . getName ( ) ) ) { visibilities . add ( new VisibilityNodeWrapper ( aktFCallNode ) ) ; } } return visibilities ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; public class ModuleNodeWrapper implements INodeWrapper { private final ModuleNode moduleNode ; private ModuleNodeWrapper parentModule ; private ArrayList < ConstNode > moduleMethodNodes = new ArrayList < ConstNode > ( ) ; ; public ModuleNodeWrapper ( ModuleNode moduleNode , ModuleNodeWrapper parentModule ) { this . moduleNode = moduleNode ; this . parentModule = parentModule ; initModuleMethodConstNodes ( ) ; } public ModuleNode getWrappedNode ( ) { return moduleNode ; } public ModuleNodeWrapper getParentModule ( ) { return parentModule ; } public void setParentModule ( ModuleNodeWrapper parentModule ) { this . parentModule = parentModule ; } public String getName ( ) { return moduleNode . getCPath ( ) . getName ( ) ; } public String getFullName ( ) { return ( parentModule != null ? parentModule . getFullName ( ) + "" : "" ) + getName ( ) ; } public Collection < ConstNode > getModuleMethodConstNodes ( ) { return moduleMethodNodes ; } private void initModuleMethodConstNodes ( ) { for ( Node node : NodeProvider . getSubNodes ( getWrappedNode ( ) , DefsNode . class ) ) { DefsNode defsNode = ( DefsNode ) node ; if ( defsNode . getReceiverNode ( ) instanceof ConstNode ) { ConstNode constNode = ( ConstNode ) defsNode . getReceiverNode ( ) ; if ( constNode . getName ( ) . equals ( getName ( ) ) ) { moduleMethodNodes . add ( constNode ) ; } } } } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ArgsCatNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . Node ; import org . jruby . ast . SplatNode ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class CallArgsNodeWrapper implements INodeWrapper { private SplatNode splatNode ; private ArrayNode arrayNode ; private Node wrappedNode ; public CallArgsNodeWrapper ( Node node ) { wrappedNode = node ; if ( NodeUtil . nodeAssignableFrom ( node , ArrayNode . class ) ) { arrayNode = ( ArrayNode ) node ; } else if ( NodeUtil . nodeAssignableFrom ( node , SplatNode . class ) ) { splatNode = ( SplatNode ) node ; } else if ( NodeUtil . nodeAssignableFrom ( node , ArgsCatNode . class ) ) { ArgsCatNode argsCatNode = ( ArgsCatNode ) node ; arrayNode = ( ArrayNode ) argsCatNode . getFirstNode ( ) ; splatNode = ( SplatNode ) argsCatNode . getSecondNode ( ) ; } } public boolean hasSplatNode ( ) { return splatNode != null ; } public boolean hasArrayNode ( ) { return arrayNode != null ; } public Node cloneWithAddedArg ( Node addedArg ) { ArrayNode newArrayNode = getNewArrayNode ( addedArg ) ; if ( hasSplatNode ( ) ) { return NodeFactory . createArgsCatNode ( newArrayNode , splatNode ) ; } return newArrayNode ; } private ArrayNode getNewArrayNode ( Node addedArg ) { Collection < Node > newArrayChilds = new ArrayList < Node > ( ) ; if ( hasArrayNode ( ) ) { for ( Node obj : arrayNode . childNodes ( ) ) { newArrayChilds . add ( obj ) ; } } newArrayChilds . add ( addedArg ) ; return NodeFactory . createArrayNode ( newArrayChilds ) ; } public Node getWrappedNode ( ) { return wrappedNode ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import org . jruby . ast . ClassNode ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . util . Constants ; public class RealClassNodeWrapper extends PartialClassNodeWrapper { private ClassNode classNode ; public RealClassNodeWrapper ( Node node ) { super ( node ) ; classNode = ( ClassNode ) node ; } @ Override public String getSuperClassName ( ) { if ( getClassName ( ) . equals ( Constants . OBJECT_NAME ) ) { return null ; } Node superClassNode = classNode . getSuperNode ( ) ; if ( superClassNode instanceof INameNode ) { return ( ( INameNode ) superClassNode ) . getName ( ) ; } return Constants . OBJECT_NAME ; } @ Override public String getClassName ( ) { if ( "" . equals ( getModulePrefix ( ) ) ) { return classNode . getCPath ( ) . getName ( ) ; } return getModulePrefix ( ) + "" + classNode . getCPath ( ) . getName ( ) ; } @ Override public Node getClassBodyNode ( ) { Node node = classNode . getBodyNode ( ) ; if ( node . equals ( NilImplicitNode . NIL ) ) return null ; return node ; } @ Override public Node getDeclarationEndNode ( ) { Node endDeclarationNode = classNode . getSuperNode ( ) ; if ( endDeclarationNode == null ) endDeclarationNode = classNode . getCPath ( ) ; return endDeclarationNode ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . SClassNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . exception . UnknownReferenceException ; public class SClassNodeWrapper extends PartialClassNodeWrapper { private SClassNode wrappedNode ; Map < Integer , Node > references ; public SClassNodeWrapper ( Node node , Node rootNode ) { super ( node ) ; wrappedNode = ( SClassNode ) node ; this . references = buildReferences ( rootNode ) ; } @ Override public String getSuperClassName ( ) { return "" ; } @ Override public String getClassName ( ) { Node receiverNode = wrappedNode . getReceiverNode ( ) ; if ( receiverNode instanceof LocalVarNode ) { LocalVarNode localVarNode = ( LocalVarNode ) receiverNode ; Node referencedNode ; try { referencedNode = getReferencedNode ( localVarNode . getIndex ( ) , references ) ; if ( referencedNode instanceof INameNode ) { return getModulePrefix ( ) + ( ( INameNode ) referencedNode ) . getName ( ) ; } } catch ( UnknownReferenceException e ) { e . printStackTrace ( ) ; } } else if ( receiverNode instanceof VCallNode ) { VCallNode vCallNode = ( VCallNode ) receiverNode ; return getModulePrefix ( ) + vCallNode . getName ( ) ; } return Messages . SClassNodeWrapper_UnknownNode + receiverNode . toString ( ) ; } private Node getReferencedNode ( int id , Map < Integer , Node > references ) throws UnknownReferenceException { if ( references . containsKey ( Integer . valueOf ( id ) ) ) { return references . get ( Integer . valueOf ( id ) ) ; } throw new UnknownReferenceException ( ) ; } @ Override public Node getClassBodyNode ( ) { return wrappedNode . getBodyNode ( ) ; } @ Override public Node getDeclarationEndNode ( ) { return wrappedNode . getReceiverNode ( ) ; } private Map < Integer , Node > buildReferences ( Node root ) { Map < Integer , Node > references = new HashMap < Integer , Node > ( ) ; Collection < Node > referencedNodes = NodeProvider . getSubNodes ( root , LocalAsgnNode . class ) ; for ( Node node : referencedNodes ) { if ( node instanceof LocalAsgnNode ) { LocalAsgnNode localAsgnNode = ( LocalAsgnNode ) node ; references . put ( Integer . valueOf ( localAsgnNode . getIndex ( ) ) , node ) ; } } return references ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import org . jruby . ast . Node ; public interface INodeWrapper { public Node getWrappedNode ( ) ; } package org . rubypeople . rdt . refactoring . nodewrapper ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String SClassNodeWrapper_UnknownNode ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . SymbolNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class VisibilityNodeWrapper implements INodeWrapper { public static enum METHOD_VISIBILITY { PRIVATE , PROTECTED , PUBLIC , NONE } public static final String PUBLIC = "" ; public static final String PROTECTED = "" ; public static final String PRIVATE = "" ; private FCallNode wrappedNode ; public VisibilityNodeWrapper ( FCallNode node ) { wrappedNode = node ; } public boolean containsMethod ( MethodNodeWrapper methodNode ) { Collection < String > methodNames = getMethodNames ( ) ; String searchedMethodName = methodNode . getName ( ) ; for ( String aktMethodName : methodNames ) { if ( aktMethodName . equals ( searchedMethodName ) ) { return true ; } } return false ; } public Collection < String > getMethodNames ( ) { Collection < String > methods = new ArrayList < String > ( ) ; if ( NodeUtil . nodeAssignableFrom ( wrappedNode . getArgsNode ( ) , ArrayNode . class ) ) { ArrayNode arrayNode = ( ArrayNode ) wrappedNode . getArgsNode ( ) ; for ( Object aktObj : arrayNode . childNodes ( ) ) { if ( aktObj instanceof SymbolNode ) { methods . add ( ( ( SymbolNode ) aktObj ) . getName ( ) ) ; } } } return methods ; } public METHOD_VISIBILITY getVisibility ( ) { return getVisibility ( wrappedNode . getName ( ) ) ; } public static METHOD_VISIBILITY getVisibility ( String name ) { if ( name . equals ( PUBLIC ) ) { return METHOD_VISIBILITY . PUBLIC ; } else if ( name . equals ( PROTECTED ) ) { return METHOD_VISIBILITY . PROTECTED ; } else if ( name . equals ( PRIVATE ) ) { return METHOD_VISIBILITY . PRIVATE ; } return METHOD_VISIBILITY . NONE ; } public ISourcePosition getPosition ( ) { return wrappedNode . getPosition ( ) ; } public static boolean isVisibilityString ( String name ) { return name . equals ( PUBLIC ) || name . equals ( PROTECTED ) || name . equals ( PRIVATE ) ; } public FCallNode getWrappedNode ( ) { return wrappedNode ; } public static String getVisibilityName ( METHOD_VISIBILITY visibility ) { if ( METHOD_VISIBILITY . PUBLIC . equals ( visibility ) ) { return PUBLIC ; } else if ( METHOD_VISIBILITY . PROTECTED . equals ( visibility ) ) { return PROTECTED ; } else if ( METHOD_VISIBILITY . PRIVATE . equals ( ( visibility ) ) ) { return PRIVATE ; } return "" ; } } package org . rubypeople . rdt . refactoring . nodewrapper ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . renamemodule . ModuleSpecifierWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; public class ClassNodeWrapper implements INodeWrapper { private Collection < PartialClassNodeWrapper > partialClassNodes ; public ClassNodeWrapper ( PartialClassNodeWrapper partialClassNode ) { partialClassNodes = new ArrayList < PartialClassNodeWrapper > ( ) ; addPartialClassNode ( partialClassNode ) ; } public void addPartialClassNode ( PartialClassNodeWrapper partialClassNode ) { partialClassNodes . add ( partialClassNode ) ; } public Collection < FieldNodeWrapper > getFields ( ) { ArrayList < FieldNodeWrapper > fields = new ArrayList < FieldNodeWrapper > ( ) ; for ( PartialClassNodeWrapper partialClassNode : partialClassNodes ) { fields . addAll ( partialClassNode . getFields ( ) ) ; } return fields ; } public Collection < ModuleSpecifierWrapper > getIncludes ( ) { ArrayList < ModuleSpecifierWrapper > fields = new ArrayList < ModuleSpecifierWrapper > ( ) ; for ( PartialClassNodeWrapper partialClassNode : partialClassNodes ) { fields . addAll ( partialClassNode . getIncludeCalls ( ) ) ; } return fields ; } public Collection < MethodNodeWrapper > getMethods ( ) { Collection < MethodNodeWrapper > methodNodes = new ArrayList < MethodNodeWrapper > ( ) ; for ( PartialClassNodeWrapper partialClassNode : partialClassNodes ) { methodNodes . addAll ( partialClassNode . getMethods ( ) ) ; } return methodNodes ; } public boolean hasMethod ( String name ) { for ( MethodNodeWrapper method : getMethods ( ) ) { if ( name . equals ( method . getName ( ) ) ) { return true ; } } return false ; } public PartialClassNodeWrapper getFirstPartialClassNode ( ) { return partialClassNodes . iterator ( ) . next ( ) ; } public String getName ( ) { return getFirstPartialClassNode ( ) . getClassName ( ) ; } public String getSuperClassName ( ) { return getFirstPartialClassNode ( ) . getSuperClassName ( ) ; } public MethodNodeWrapper getConstructorNode ( ) { Collection < MethodNodeWrapper > constructors = getExistingConstructors ( ) ; if ( constructors . isEmpty ( ) ) { return new MethodNodeWrapper ( NodeFactory . createDefaultConstructor ( ) , this ) ; } return constructors . toArray ( new MethodNodeWrapper [ constructors . size ( ) ] ) [ constructors . size ( ) - ] ; } public Collection < MethodNodeWrapper > getExistingConstructors ( ) { Collection < MethodNodeWrapper > constructors = new ArrayList < MethodNodeWrapper > ( ) ; for ( PartialClassNodeWrapper partialClassNode : partialClassNodes ) { constructors . addAll ( partialClassNode . getExistingConstructors ( ) ) ; } return constructors ; } public boolean hasConstructor ( ) { return ! getExistingConstructors ( ) . isEmpty ( ) ; } public Collection < Node > getAttrNodes ( ) { Collection < Node > attrNodes = new ArrayList < Node > ( ) ; for ( PartialClassNodeWrapper partialClassNode : partialClassNodes ) { attrNodes . addAll ( partialClassNode . getAttrNodes ( ) ) ; } return attrNodes ; } public Collection < AttrAccessorNodeWrapper > getAccessorNodes ( ) { Collection < AttrAccessorNodeWrapper > accessorNodes = new ArrayList < AttrAccessorNodeWrapper > ( ) ; for ( PartialClassNodeWrapper partialClassNode : partialClassNodes ) { accessorNodes . addAll ( partialClassNode . getAccessorNodes ( ) ) ; } return accessorNodes ; } public Collection < PartialClassNodeWrapper > getPartialClassNodes ( ) { return partialClassNodes ; } public Collection < PartialClassNodeWrapper > getPartialClassNodesOfFile ( String file ) { ArrayList < PartialClassNodeWrapper > matchingPartialClasses = new ArrayList < PartialClassNodeWrapper > ( ) ; for ( PartialClassNodeWrapper currentClassPart : partialClassNodes ) { String fileOfClassPart = currentClassPart . getFile ( ) ; if ( fileOfClassPart . equals ( file ) ) { matchingPartialClasses . add ( currentClassPart ) ; } } return matchingPartialClasses ; } public Collection < Node > getInstFieldOccurences ( ) { Collection < Node > allFieldOccuences = new ArrayList < Node > ( ) ; for ( PartialClassNodeWrapper partialClassNode : partialClassNodes ) { allFieldOccuences . addAll ( partialClassNode . getInstFieldOccurences ( ) ) ; } return allFieldOccuences ; } public Collection < Node > getClassFieldOccurences ( ) { Collection < Node > classFieldOccuences = new ArrayList < Node > ( ) ; for ( PartialClassNodeWrapper partialClassNode : partialClassNodes ) { classFieldOccuences . addAll ( partialClassNode . getClassFieldOccurences ( ) ) ; } return classFieldOccuences ; } public Collection < MethodCallNodeWrapper > getMethodCalls ( MethodDefNode decoratedNode ) { ArrayList < MethodCallNodeWrapper > calls = new ArrayList < MethodCallNodeWrapper > ( ) ; for ( PartialClassNodeWrapper classPart : partialClassNodes ) { calls . addAll ( classPart . getMethodCalls ( decoratedNode ) ) ; } return calls ; } public Collection < MethodCallNodeWrapper > getMethodCallNodes ( ) { ArrayList < MethodCallNodeWrapper > methodCalls = new ArrayList < MethodCallNodeWrapper > ( ) ; for ( PartialClassNodeWrapper classPart : partialClassNodes ) { methodCalls . addAll ( classPart . getMethodCallNodes ( ) ) ; } return methodCalls ; } public Collection < SymbolNode > getMethodSymbols ( MethodDefNode decoratedNode ) { ArrayList < SymbolNode > symbols = new ArrayList < SymbolNode > ( ) ; for ( PartialClassNodeWrapper classPart : partialClassNodes ) { symbols . addAll ( classPart . getMethodSymbols ( decoratedNode ) ) ; } return symbols ; } public METHOD_VISIBILITY getMethodVisibility ( MethodNodeWrapper methodNode ) { if ( methodNode . isClassMethod ( ) ) { return METHOD_VISIBILITY . PUBLIC ; } VisibilityNodeWrapper methodVisibility = getMethodVisibilityNode ( methodNode ) ; if ( methodVisibility != null ) { return methodVisibility . getVisibility ( ) ; } PartialClassNodeWrapper affectedClassPart = getPartContainingMethod ( methodNode ) ; return affectedClassPart . getPosVisibility ( methodNode . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ) ; } public VisibilityNodeWrapper getMethodVisibilityNode ( MethodNodeWrapper methodNode ) { PartialClassNodeWrapper affectedClassPart = getPartContainingMethod ( methodNode ) ; Collection < VisibilityNodeWrapper > visibilities = affectedClassPart . getMethodVisibilityNodes ( ) ; for ( VisibilityNodeWrapper aktNode : visibilities ) { if ( aktNode . containsMethod ( methodNode ) ) { return aktNode ; } } return null ; } public Collection < VisibilityNodeWrapper > getMethodVisibilityNodes ( ) { Collection < VisibilityNodeWrapper > visibilites = new ArrayList < VisibilityNodeWrapper > ( ) ; for ( PartialClassNodeWrapper classPart : partialClassNodes ) { visibilites . addAll ( classPart . getMethodVisibilityNodes ( ) ) ; } return visibilites ; } private PartialClassNodeWrapper getPartContainingMethod ( MethodNodeWrapper methodNode ) { for ( PartialClassNodeWrapper classPart : partialClassNodes ) { for ( MethodNodeWrapper aktMethodNode : classPart . getMethods ( ) ) { if ( aktMethodNode . equals ( methodNode ) ) { return classPart ; } } } return null ; } public MethodNodeWrapper getMethod ( String searchedMethodName ) { Collection < MethodNodeWrapper > methodNodes = getMethods ( ) ; MethodNodeWrapper lastMethod = null ; for ( MethodNodeWrapper aktMethod : methodNodes ) { if ( aktMethod . getName ( ) . equals ( searchedMethodName ) ) { lastMethod = aktMethod ; } } return lastMethod ; } @ Override public int hashCode ( ) { final int PRIME = ; int result = ; result = PRIME * result + ( ( partialClassNodes == null ) ? : partialClassNodes . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof ClassNodeWrapper ) { ClassNodeWrapper otherClassNode = ( ClassNodeWrapper ) obj ; return getName ( ) . equals ( otherClassNode . getName ( ) ) ; } return false ; } @ Override public String toString ( ) { return getName ( ) ; } public boolean containsMethod ( String searchedMethodName , boolean isClassMethod ) { Collection < MethodNodeWrapper > methodNodes = getMethods ( ) ; for ( MethodNodeWrapper aktMethod : methodNodes ) { if ( ( ! isClassMethod || aktMethod . isClassMethod ( ) ) && aktMethod . getName ( ) . equals ( searchedMethodName ) ) { return true ; } } return false ; } public boolean containsMethod ( String searchedMethodName ) { return containsMethod ( searchedMethodName , false ) ; } public PartialClassNodeWrapper getPartialClassNodeForFileName ( String fileName ) { for ( PartialClassNodeWrapper aktPart : partialClassNodes ) { if ( aktPart . getWrappedNode ( ) . getPosition ( ) . getFile ( ) . equals ( fileName ) ) { return aktPart ; } } return null ; } public Node getWrappedNode ( ) { return partialClassNodes . toArray ( new PartialClassNodeWrapper [ partialClassNodes . size ( ) ] ) [ ] . getWrappedNode ( ) ; } public boolean containsField ( String searchedFieldName ) { for ( FieldNodeWrapper aktFieldNode : getFields ( ) ) { if ( aktFieldNode . getName ( ) . equals ( searchedFieldName ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . refactoring . signatureprovider ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . exception . UnknownClassNameException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class ClassNodeSignatureProvider extends ClassSignatureProvider { private ClassNodeWrapper classNode ; public ClassNodeSignatureProvider ( ClassNodeWrapper classNode , ClassNodeProvider classNodeProvider ) { super ( getSuperProvider ( classNode , classNodeProvider ) ) ; this . classNode = classNode ; createMethodSignatures ( ) ; } private void createMethodSignatures ( ) { Collection < MethodNodeWrapper > methods = classNode . getMethods ( ) ; for ( MethodNodeWrapper method : methods ) { addMethodSignature ( method . getName ( ) , method ) ; } } @ Override public String getClassName ( ) { return classNode . getName ( ) ; } private static IClassSignatureProvider getSuperProvider ( ClassNodeWrapper classNode , ClassNodeProvider classNodeProvider ) { try { return ClassSignatureProvider . getClassSignatureProvider ( classNode . getSuperClassName ( ) , classNodeProvider ) ; } catch ( UnknownClassNameException e ) { return null ; } } @ Override protected MethodSignature getSignature ( String methodName , Object data ) { return ( ( MethodNodeWrapper ) data ) . getSignature ( ) ; } } package org . rubypeople . rdt . refactoring . signatureprovider ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . LinkedHashSet ; import java . util . Map ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . exception . UnknownClassNameException ; import org . rubypeople . rdt . refactoring . exception . UnknownMethodNameException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . util . Constants ; public abstract class ClassSignatureProvider implements IClassSignatureProvider { private Map < String , Object > methodSignatures ; private IClassSignatureProvider superProvider ; public abstract String getClassName ( ) ; protected abstract MethodSignature getSignature ( String methodName , Object data ) ; public ClassSignatureProvider ( IClassSignatureProvider superProvider ) { this . methodSignatures = new LinkedHashMap < String , Object > ( ) ; this . superProvider = superProvider ; } protected void addMethodSignature ( String methodName , Object data ) { methodSignatures . put ( methodName , data ) ; } public boolean hasMethodSignature ( String methodName ) { if ( methodSignatures . containsKey ( methodName ) ) { return true ; } if ( superProvider != null ) { return superProvider . hasMethodSignature ( methodName ) ; } return false ; } public MethodSignature getMethodSignature ( String methodName ) throws UnknownMethodNameException { if ( methodSignatures . containsKey ( methodName ) ) return getSignature ( methodName , methodSignatures . get ( methodName ) ) ; if ( superProvider != null ) return superProvider . getMethodSignature ( methodName ) ; throw new UnknownMethodNameException ( ) ; } public Collection < MethodSignature > getMethodSignatures ( ) { Collection < MethodSignature > signs = new LinkedHashSet < MethodSignature > ( ) ; for ( String methodName : methodSignatures . keySet ( ) ) { signs . add ( getSignature ( methodName , methodSignatures . get ( methodName ) ) ) ; } if ( superProvider != null ) { signs . addAll ( superProvider . getMethodSignatures ( ) ) ; } return signs ; } public boolean hasConstructorSignature ( ) { return hasMethodSignature ( Constants . CONSTRUCTOR_NAME ) ; } public MethodSignature getConstructorSignature ( ) throws UnknownMethodNameException { return getMethodSignature ( Constants . CONSTRUCTOR_NAME ) ; } public static IClassSignatureProvider getClassSignatureProvider ( String className , ClassNodeProvider classNodeProvider ) throws UnknownClassNameException { ClassNodeWrapper classNode = null ; if ( classNodeProvider != null ) classNode = classNodeProvider . getClassNode ( className ) ; if ( classNode != null ) return new ClassNodeSignatureProvider ( classNode , classNodeProvider ) ; throw new UnknownClassNameException ( ) ; } protected Object getData ( String methodName ) { return methodSignatures . get ( methodName ) ; } } package org . rubypeople . rdt . refactoring . signatureprovider ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . nodewrapper . ArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . util . Constants ; public class MethodSignature { private String methodName ; private Collection < String > args ; public MethodSignature ( String methodName , Collection < String > args ) { this . methodName = methodName ; this . args = args ; } public MethodSignature ( String methodName , int argCount ) { this ( methodName , getAnnonymousArgs ( argCount ) ) ; } public MethodSignature ( String methodName , ArgsNodeWrapper args ) { this ( methodName , args . getArgsList ( ) ) ; } private static Collection < String > getAnnonymousArgs ( int argCount ) { Collection < String > args = new ArrayList < String > ( ) ; for ( int i = ; i < argCount ; i ++ ) { args . add ( "" + i ) ; } return args ; } public String getMethodName ( ) { return methodName ; } public Collection < String > getArguments ( ) { return args ; } public String getArgListAsString ( ) { if ( args . isEmpty ( ) ) return "" ; StringBuilder argList = new StringBuilder ( ) ; for ( String arg : args ) { argList . append ( arg + "" ) ; } return '' + argList . substring ( , argList . length ( ) - ) ; } public boolean isConstructor ( ) { return methodName . equals ( Constants . CONSTRUCTOR_NAME ) ; } public String getNameWithArgs ( ) { String argsList = getArgListAsString ( ) ; return getMethodName ( ) + ( ( argsList . length ( ) != ) ? argsList : "" ) ; } @ Override public int hashCode ( ) { final int PRIME = ; int result = ; result = PRIME * result + ( ( args == null ) ? : args . hashCode ( ) ) ; result = PRIME * result + ( ( methodName == null ) ? : methodName . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof MethodSignature ) { MethodSignature otherSignature = ( MethodSignature ) obj ; if ( getNameWithArgs ( ) . equals ( otherSignature . getNameWithArgs ( ) ) ) return true ; } return false ; } } package org . rubypeople . rdt . refactoring . signatureprovider ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . exception . UnknownMethodNameException ; public interface IClassSignatureProvider { public String getClassName ( ) ; public MethodSignature getMethodSignature ( String name ) throws UnknownMethodNameException ; public boolean hasMethodSignature ( String methodName ) ; public Collection < MethodSignature > getMethodSignatures ( ) ; public boolean hasConstructorSignature ( ) ; public MethodSignature getConstructorSignature ( ) throws UnknownMethodNameException ; } package org . rubypeople . rdt . refactoring . ui ; public interface IParentProvider { public Object getParent ( ) ; } package org . rubypeople . rdt . refactoring . ui ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . ui . preferences . formatter . RubyScriptPreview ; public class RdtCodeViewer extends RubyScriptPreview { public static RdtCodeViewer create ( Composite parent ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , "" ) ; return new RdtCodeViewer ( map , parent ) ; } protected RdtCodeViewer ( Map workingValues , Composite parent ) { super ( workingValues , parent ) ; getTextWidget ( ) . setEditable ( false ) ; } protected void doFormatPreview ( ) { if ( fPreviewText == null ) { fPreviewDocument . set ( "" ) ; return ; } fPreviewDocument . set ( fPreviewText ) ; } public void setBackgroundColor ( int start , int length , RGB color ) { setBackgroundColor ( start , length , new Color ( Display . getCurrent ( ) , color ) ) ; } public void setBackgroundColor ( int start , int length , int color ) { setBackgroundColor ( start , length , Display . getCurrent ( ) . getSystemColor ( color ) ) ; } public void setBackgroundColor ( int start , int length , Color color ) { StyleRange styleRangeNode = new StyleRange ( ) ; styleRangeNode . start = start ; styleRangeNode . length = length ; styleRangeNode . background = color ; getTextWidget ( ) . setStyleRange ( styleRangeNode ) ; } } package org . rubypeople . rdt . refactoring . ui ; public interface IChildrenProvider { public boolean hasChildren ( ) ; public Object [ ] getChildren ( ) ; } package org . rubypeople . rdt . refactoring . ui ; import org . eclipse . swt . widgets . Listener ; public interface IErrorMessageGenerator extends Listener { void setErrorReceiver ( IErrorMessageReceiver errorReceiver ) ; } package org . rubypeople . rdt . refactoring . ui . util ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; public class AbstractSelectionListener implements SelectionListener { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { } } package org . rubypeople . rdt . refactoring . ui . util ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; public class SwtUtils { public static void initExplanation ( Composite control , String explTitle , String explText ) { Group group = new Group ( control , SWT . NONE ) ; Label label = new Label ( group , SWT . WRAP ) ; group . setLayout ( new FillLayout ( SWT . VERTICAL ) ) ; group . setText ( explTitle ) ; label . setText ( explText ) ; } public static Label initLabel ( Group group , String text ) { Label label = new Label ( group , SWT . None ) ; label . setText ( text ) ; return label ; } public static Group initGroup ( Composite c , String text ) { Group group = new Group ( c , SWT . NONE ) ; group . setLayout ( new FillLayout ( SWT . HORIZONTAL ) ) ; group . setText ( text ) ; return group ; } } package org . rubypeople . rdt . refactoring . ui ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . ltk . ui . refactoring . RefactoringWizard ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; public class RubyRefactoringWizard extends RefactoringWizard { private RubyRefactoring refactoring ; public RubyRefactoringWizard ( RubyRefactoring refactoring ) { super ( refactoring , WIZARD_BASED_USER_INTERFACE ) ; this . refactoring = refactoring ; } protected void addUserInputPages ( ) { for ( IWizardPage page : refactoring . getPages ( ) ) { addPage ( page ) ; } } } package org . rubypeople . rdt . refactoring . ui ; import java . util . Collection ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . refactoring . core . IValidator ; public class NewNameListener implements IErrorMessageGenerator { private final INewNameReceiver receiver ; private IErrorMessageReceiver errorReceiver ; private final Collection < String > fields ; private final IValidator validator ; public NewNameListener ( INewNameReceiver receiver , IValidator validator , Collection < String > fields ) { this . receiver = receiver ; this . validator = validator ; this . fields = fields ; } public void handleEvent ( Event event ) { if ( event . widget instanceof Text ) { String name = ( ( Text ) event . widget ) . getText ( ) ; if ( isValid ( name ) ) { receiver . setNewName ( name ) ; } } } private boolean isValid ( String name ) { boolean valid = validator . isValid ( name ) ; boolean nameAlreadyInUse = false ; for ( String field : fields ) { if ( name . equals ( field ) ) { nameAlreadyInUse = true ; } } if ( valid && ! nameAlreadyInUse ) { errorReceiver . setError ( null ) ; } else if ( nameAlreadyInUse ) { errorReceiver . setError ( name + Messages . NewNameListener_AlreadyInUse ) ; } else { errorReceiver . setError ( name + Messages . NewNameListener_IsNotValid ) ; } return valid ; } public void setErrorReceiver ( IErrorMessageReceiver errorReceiver ) { this . errorReceiver = errorReceiver ; } } package org . rubypeople . rdt . refactoring . ui ; public interface IItemSelectionReceiver { public void setSelectedItems ( Object [ ] checkedElements ) ; } package org . rubypeople . rdt . refactoring . ui ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; public abstract class TreeContentProvider implements ITreeContentProvider { public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof IChildrenProvider ) { return ( ( IChildrenProvider ) parentElement ) . getChildren ( ) ; } return new Object [ ] ; } public Object getParent ( Object element ) { return null ; } public boolean hasChildren ( Object element ) { if ( element instanceof IChildrenProvider ) { return ( ( IChildrenProvider ) element ) . hasChildren ( ) ; } return false ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public abstract Object [ ] getElements ( Object inputElement ) ; } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . FieldEncapsulator ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . pages . encapsulatefield . EncapsulateFieldAccessorComposite ; import org . rubypeople . rdt . refactoring . ui . pages . encapsulatefield . IVisibilitySelectionListener ; import org . rubypeople . rdt . refactoring . ui . util . AbstractSelectionListener ; public class EncapsulateFieldPage extends RefactoringWizardPage { private static final String TITLE = Messages . EncapsulateFieldPage_Title ; private FieldEncapsulator fieldEncapsulator ; public EncapsulateFieldPage ( FieldEncapsulator fieldEncapsulator ) { super ( TITLE ) ; this . fieldEncapsulator = fieldEncapsulator ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . NONE ) ; control . setLayout ( new GridLayout ( , true ) ) ; initFieldInfoGroup ( control ) ; initReaderAccessorControl ( control ) ; initWriterAccessorControl ( control ) ; setControl ( control ) ; } private void initWriterAccessorControl ( Composite parent ) { boolean isOptional = fieldEncapsulator . isWriterGenerationOptional ( ) ; VisibilityNodeWrapper . METHOD_VISIBILITY visibility = fieldEncapsulator . getWriterVisibility ( ) ; final EncapsulateFieldAccessorComposite accessorControl = new EncapsulateFieldAccessorComposite ( parent , Messages . EncapsulateFieldPage_Writer , visibility , isOptional ) ; accessorControl . enableVisibilityGroup ( false ) ; if ( isOptional ) { accessorControl . addEnableDisableListener ( new AbstractSelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { fieldEncapsulator . setWriterDisabled ( accessorControl . isDisabled ( ) ) ; accessorControl . enableVisibilityGroup ( ! accessorControl . isDisabled ( ) ) ; } } ) ; } accessorControl . addVisibilitySelectionListener ( new IVisibilitySelectionListener ( ) { public void visibilitySelected ( VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) { fieldEncapsulator . setWriterVisibility ( visibility ) ; } } ) ; } private void initReaderAccessorControl ( Composite parent ) { boolean isOptional = fieldEncapsulator . isReaderGenerationOptional ( ) ; VisibilityNodeWrapper . METHOD_VISIBILITY visibility = fieldEncapsulator . getReaderVisibility ( ) ; final EncapsulateFieldAccessorComposite accessorControl = new EncapsulateFieldAccessorComposite ( parent , Messages . EncapsulateFieldPage_Reader , visibility , isOptional ) ; accessorControl . enableVisibilityGroup ( false ) ; if ( isOptional ) { accessorControl . addEnableDisableListener ( new AbstractSelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { fieldEncapsulator . setReaderDisabled ( accessorControl . isDisabled ( ) ) ; accessorControl . enableVisibilityGroup ( ! accessorControl . isDisabled ( ) ) ; } } ) ; } accessorControl . addVisibilitySelectionListener ( new IVisibilitySelectionListener ( ) { public void visibilitySelected ( VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) { fieldEncapsulator . setReaderVisibility ( visibility ) ; } } ) ; } private void initFieldInfoGroup ( Composite control ) { Group fieldInfoGroup = new Group ( control , SWT . NONE ) ; GridData gridData = new GridData ( ) ; gridData . grabExcessHorizontalSpace = true ; gridData . horizontalAlignment = GridData . FILL ; fieldInfoGroup . setLayoutData ( gridData ) ; fieldInfoGroup . setLayout ( new GridLayout ( , true ) ) ; fieldInfoGroup . setText ( Messages . EncapsulateFieldPage_SelectedField ) ; Label fieldNameLabel = new Label ( fieldInfoGroup , SWT . NONE ) ; fieldNameLabel . setText ( Messages . EncapsulateFieldPage_Name + fieldEncapsulator . getSelectedFieldName ( ) ) ; Label existingAccessorLabel = new Label ( fieldInfoGroup , SWT . NONE ) ; existingAccessorLabel . setText ( Messages . EncapsulateFieldPage_FieldAccessor + fieldEncapsulator . getExistingAccessorName ( ) ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . layout . RowLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . List ; import org . rubypeople . rdt . refactoring . core . inlineclass . InlineClassConfig ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; public class InlineClassPage extends RefactoringWizardPage { public static final String TITLE = Messages . InlineClassPage_InlineTemp ; private InlineClassConfig config ; public InlineClassPage ( InlineClassConfig config ) { super ( TITLE ) ; this . config = config ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . NONE ) ; initBaseLayout ( control ) ; initList ( control ) ; setControl ( control ) ; } private void initBaseLayout ( Composite control ) { GridLayout baseLayout = new GridLayout ( ) ; baseLayout . numColumns = ; control . setLayout ( baseLayout ) ; } private void initList ( Composite control ) { RowLayout panelLayout = new RowLayout ( SWT . VERTICAL ) ; panelLayout . wrap = false ; Label selectText = new Label ( control , SWT . NONE ) ; selectText . setText ( Messages . InlineClassPage_SelectTargetClass ) ; List classList = new List ( control , SWT . BORDER | SWT . SINGLE | SWT . V_SCROLL ) ; setListLayout ( classList ) ; fillList ( classList ) ; initSelectionListener ( classList ) ; } private void fillList ( List classList ) { for ( ClassNodeWrapper currentClass : config . getPossibleTargetClasses ( ) ) { classList . add ( currentClass . getName ( ) ) ; } } private void setListLayout ( List classList ) { GridData listData = new GridData ( ) ; listData . grabExcessHorizontalSpace = true ; listData . grabExcessVerticalSpace = true ; listData . horizontalAlignment = GridData . FILL ; listData . verticalAlignment = GridData . FILL ; classList . setLayoutData ( listData ) ; } private void initSelectionListener ( final List classList ) { classList . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { String selection = classList . getSelection ( ) [ ] ; ClassNodeWrapper selectedClass = config . getDocumentProvider ( ) . getClassNodeProvider ( ) . getClassNode ( selection ) ; config . setTargetClassPart ( selectedClass . getFirstPartialClassNode ( ) ) ; } } ) ; } } package org . rubypeople . rdt . refactoring . ui . pages . encapsulatefield ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . layout . RowLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; public class EncapsulateFieldAccessorComposite extends Group { private Button enableDisableCheckBox ; private IVisibilitySelectionListener visibilitySelectionListener ; private VisibilityNodeWrapper . METHOD_VISIBILITY selectedVisibility ; private Button publicButton ; private Button protectedButton ; private Button privateButton ; public EncapsulateFieldAccessorComposite ( Composite parent , String name , VisibilityNodeWrapper . METHOD_VISIBILITY selectedVisibility , boolean isOptional ) { super ( parent , SWT . NONE ) ; this . selectedVisibility = selectedVisibility ; setLayoutData ( getDefaultGridData ( ) ) ; setLayout ( new GridLayout ( , true ) ) ; setText ( name ) ; if ( isOptional ) { initEnableDisableCheckBox ( name ) ; } initAccessModifierGroup ( ) ; } private void initAccessModifierGroup ( ) { Group accessModifierGroup = new Group ( this , SWT . SHADOW_NONE | SWT . NONE ) ; RowLayout groupLayout = new RowLayout ( SWT . HORIZONTAL ) ; groupLayout . fill = true ; accessModifierGroup . setLayout ( groupLayout ) ; accessModifierGroup . setLayoutData ( getDefaultGridData ( ) ) ; accessModifierGroup . setText ( Messages . EncapsulateFieldAccessorComposite_AccessModifier ) ; publicButton = initAccessModifierButton ( accessModifierGroup , "" , VisibilityNodeWrapper . METHOD_VISIBILITY . PUBLIC ) ; protectedButton = initAccessModifierButton ( accessModifierGroup , "" , VisibilityNodeWrapper . METHOD_VISIBILITY . PROTECTED ) ; privateButton = initAccessModifierButton ( accessModifierGroup , "" , VisibilityNodeWrapper . METHOD_VISIBILITY . PRIVATE ) ; } private GridData getDefaultGridData ( ) { GridData gridData = new GridData ( ) ; gridData . grabExcessHorizontalSpace = true ; gridData . horizontalAlignment = GridData . FILL ; return gridData ; } private Button initAccessModifierButton ( Group accessModifierGroup , String accessModifierName , final VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) { Button accessModifierButton = new Button ( accessModifierGroup , SWT . RADIO | SWT . LEFT ) ; accessModifierButton . setText ( accessModifierName ) ; if ( visibility . equals ( selectedVisibility ) ) { accessModifierButton . setSelection ( true ) ; } accessModifierButton . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { visibilitySelectionListener . visibilitySelected ( visibility ) ; } } ) ; return accessModifierButton ; } private void initEnableDisableCheckBox ( String name ) { enableDisableCheckBox = new Button ( this , SWT . CHECK ) ; enableDisableCheckBox . setLayoutData ( getDefaultGridData ( ) ) ; enableDisableCheckBox . setText ( Messages . EncapsulateFieldAccessorComposite_Generate + name ) ; } public void addEnableDisableListener ( SelectionListener listener ) { enableDisableCheckBox . addSelectionListener ( listener ) ; } public boolean isDisabled ( ) { return ( enableDisableCheckBox != null ) ? ! enableDisableCheckBox . getSelection ( ) : false ; } public void addVisibilitySelectionListener ( IVisibilitySelectionListener visibilitySelectionListener ) { this . visibilitySelectionListener = visibilitySelectionListener ; } @ Override protected void checkSubclass ( ) { } public void enableVisibilityGroup ( boolean enabled ) { publicButton . setEnabled ( enabled ) ; protectedButton . setEnabled ( enabled ) ; privateButton . setEnabled ( enabled ) ; } } package org . rubypeople . rdt . refactoring . ui . pages . encapsulatefield ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; public interface IVisibilitySelectionListener { public void visibilitySelected ( VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) ; } package org . rubypeople . rdt . refactoring . ui . pages . encapsulatefield ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String EncapsulateFieldAccessorComposite_AccessModifier ; public static String EncapsulateFieldAccessorComposite_Generate ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . ui . pages ; import java . util . ArrayList ; import java . util . Collection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . List ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . MergeClassPartInFileConfig ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . RdtCodeViewer ; import org . rubypeople . rdt . refactoring . ui . util . SwtUtils ; public class MergeClassPartsInFilePage extends RefactoringWizardPage { private static final String TITLE = Messages . MergeClassPartsInFilePage_SelectClassParts ; private RdtCodeViewer classView ; private String activeFileName ; private MergeClassPartInFileConfig config ; public MergeClassPartsInFilePage ( MergeClassPartInFileConfig config ) { super ( TITLE ) ; setTitle ( TITLE ) ; activeFileName = config . getDocumentProvider ( ) . getActiveFileName ( ) ; this . config = config ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . NONE ) ; FillLayout baseLayout = new FillLayout ( ) ; baseLayout . spacing = ; control . setLayout ( baseLayout ) ; initList ( control ) ; initSidePanel ( control ) ; setControl ( control ) ; } private void initSidePanel ( Composite control ) { Composite sidePanel = new Composite ( control , SWT . NONE ) ; FillLayout sidePanelLayout = new FillLayout ( SWT . VERTICAL ) ; sidePanelLayout . spacing = ; sidePanel . setLayout ( sidePanelLayout ) ; String explTitle = Messages . MergeClassPartsInFilePage_Description ; String explText = Messages . MergeClassPartsInFilePage_Explanation ; SwtUtils . initExplanation ( sidePanel , explTitle , explText ) ; classView = RdtCodeViewer . create ( sidePanel ) ; } private void initList ( Composite control ) { Composite listSide = new Composite ( control , SWT . NONE ) ; FillLayout listSideLayout = new FillLayout ( SWT . VERTICAL ) ; listSideLayout . spacing = ; listSide . setLayout ( listSideLayout ) ; final List classSelection = new List ( listSide , SWT . H_SCROLL | SWT . V_SCROLL | SWT . BORDER | SWT . SINGLE ) ; final Collection < ClassNodeWrapper > selectableClasses = config . getSelectableClasses ( ) ; for ( ClassNodeWrapper currentClass : selectableClasses ) { classSelection . add ( currentClass . getName ( ) ) ; } final Table partTable = new Table ( listSide , SWT . V_SCROLL | SWT . H_SCROLL | SWT . BORDER | SWT . CHECK | SWT . SINGLE ) ; classSelection . addSelectionListener ( createClassSelectionListener ( classSelection , selectableClasses , partTable ) ) ; partTable . addListener ( SWT . Selection , createPartSelectionListener ( partTable ) ) ; } private Listener createPartSelectionListener ( final Table partTable ) { return new Listener ( ) { private void setClassView ( final Table partTable ) { TableItem selectedItem = partTable . getSelection ( ) [ ] ; PartialClassNodeWrapper classPart = ( PartialClassNodeWrapper ) selectedItem . getData ( ) ; Node classNode = classPart . getWrappedNode ( ) ; classView . setPreviewText ( ReWriteVisitor . createCodeFromNode ( NodeFactory . createNewLineNode ( classNode ) , "" ) ) ; } public void handleEvent ( Event event ) { ArrayList < PartialClassNodeWrapper > checkedParts = new ArrayList < PartialClassNodeWrapper > ( ) ; for ( TableItem currentItem : partTable . getItems ( ) ) { if ( currentItem . getChecked ( ) ) { checkedParts . add ( ( PartialClassNodeWrapper ) currentItem . getData ( ) ) ; } } partTable . setSelection ( ( TableItem ) event . item ) ; setClassView ( partTable ) ; config . setCheckedClassParts ( checkedParts ) ; config . setSelectedClassPart ( ( PartialClassNodeWrapper ) partTable . getSelection ( ) [ ] . getData ( ) ) ; } } ; } private SelectionListener createClassSelectionListener ( final List classSelection , final Collection < ClassNodeWrapper > selectableClasses , final Table partTable ) { return new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { if ( config . getSelectedClassPart ( ) != null && classSelection . getSelection ( ) [ ] . equals ( config . getSelectedClassPart ( ) . getClassName ( ) ) ) { return ; } partTable . removeAll ( ) ; String currentSelection = classSelection . getSelection ( ) [ ] ; for ( ClassNodeWrapper currentClass : selectableClasses ) { if ( currentClass . getName ( ) . equals ( currentSelection ) ) { fillClassPartTable ( partTable , currentClass ) ; } resetClassView ( ) ; } } private void fillClassPartTable ( final Table partTable , ClassNodeWrapper currentClass ) { for ( PartialClassNodeWrapper currentPart : currentClass . getPartialClassNodes ( ) ) { if ( currentPart . getFile ( ) . equals ( activeFileName ) ) { final TableItem currentItem = new TableItem ( partTable , SWT . NONE ) ; currentItem . setData ( currentPart ) ; String itemText = createItemCaption ( currentPart ) ; currentItem . setText ( itemText . trim ( ) ) ; } } } private String createItemCaption ( PartialClassNodeWrapper currentPart ) { StringBuilder itemText = new StringBuilder ( ) ; int lineCount = ; for ( MethodNodeWrapper method : currentPart . getMethods ( ) ) { itemText . append ( method . getSignature ( ) . getNameWithArgs ( ) ) . append ( "" ) ; if ( lineCount >= ) { itemText . append ( "" ) ; break ; } lineCount ++ ; } return itemText . toString ( ) ; } } ; } private void resetClassView ( ) { classView . setPreviewText ( "" ) ; config . setCheckedClassParts ( new ArrayList < PartialClassNodeWrapper > ( ) ) ; config . setSelectedClassPart ( null ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . ClassPartTreeItem ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . ExternalClassPartsMerger ; import org . rubypeople . rdt . refactoring . ui . NotifiedContainerCheckedTree ; import org . rubypeople . rdt . refactoring . ui . RdtCodeViewer ; import org . rubypeople . rdt . refactoring . ui . util . SwtUtils ; public class MergeWithExternalClassPartsPage extends RefactoringWizardPage { private static final String TITLE = Messages . MergeWithExternalClassPartsPage_SelectParts ; private NotifiedContainerCheckedTree tree ; private ExternalClassPartsMerger merger ; private RdtCodeViewer classView ; public MergeWithExternalClassPartsPage ( ExternalClassPartsMerger merger ) { super ( TITLE ) ; setTitle ( TITLE ) ; this . merger = merger ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . NONE ) ; initLayout ( control ) ; } private void initLayout ( Composite control ) { setControl ( control ) ; FillLayout layout = new FillLayout ( SWT . HORIZONTAL ) ; control . setLayout ( layout ) ; this . tree = initTree ( control ) ; Composite sidePanel = new Composite ( control , SWT . NONE ) ; FillLayout sidePanelLayout = new FillLayout ( SWT . VERTICAL ) ; sidePanel . setLayout ( sidePanelLayout ) ; String explTitle = Messages . MergeWithExternalClassPartsPage_Description ; String explText = Messages . MergeWithExternalClassPartsPage_DescriptionText ; SwtUtils . initExplanation ( sidePanel , explTitle , explText ) ; initClassPartView ( sidePanel ) ; } private void initClassPartView ( Composite sidePanel ) { classView = RdtCodeViewer . create ( sidePanel ) ; tree . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { TreeSelection selection = ( TreeSelection ) event . getSelectionProvider ( ) . getSelection ( ) ; ClassPartTreeItem treeItem = ( ClassPartTreeItem ) selection . getFirstElement ( ) ; Node classNode = treeItem . getClassPartWrapper ( ) . getWrappedNode ( ) ; classView . setPreviewText ( ReWriteVisitor . createCodeFromNode ( NodeFactory . createNewLineNode ( classNode ) , "" ) ) ; } } ) ; } private NotifiedContainerCheckedTree initTree ( Composite c ) { return new NotifiedContainerCheckedTree ( c , merger , merger ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import java . util . Collection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . layout . FormAttachment ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . refactoring . core . splitlocal . ISplittedNamesReceiver ; import org . rubypeople . rdt . refactoring . core . splitlocal . LocalVarUsage ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitTempRefactoring ; import org . rubypeople . rdt . refactoring . ui . RdtCodeViewer ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class SplitLocalPage extends RefactoringWizardPage { private static final int SEPARATOR_AT = ; private static final int BORDER_WIDTH = ; private static RGB [ ] colors ; private final Collection < LocalVarUsage > localUsages ; private final String source ; private final ISplittedNamesReceiver receiver ; private Text [ ] names ; static { colors = new RGB [ ] { new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) , new RGB ( , , ) } ; } public SplitLocalPage ( Collection < LocalVarUsage > localUsages , String source , ISplittedNamesReceiver receiver ) { super ( SplitTempRefactoring . NAME + "" ) ; this . localUsages = localUsages ; this . source = source ; this . receiver = receiver ; setTitle ( SplitTempRefactoring . NAME ) ; } public void createControl ( Composite parent ) { Composite main = new Composite ( parent , SWT . NONE ) ; FormLayout thisLayout = new FormLayout ( ) ; main . setLayout ( thisLayout ) ; Composite variableNames = new Composite ( main , SWT . NONE ) ; GridLayout variableNamesLayout = new GridLayout ( ) ; variableNamesLayout . makeColumnsEqualWidth = true ; FormData variableNamesLayoutData = new FormData ( ) ; variableNamesLayoutData . top = new FormAttachment ( , , BORDER_WIDTH ) ; variableNamesLayoutData . bottom = new FormAttachment ( , , - BORDER_WIDTH ) ; variableNamesLayoutData . left = new FormAttachment ( , , BORDER_WIDTH ) ; variableNamesLayoutData . width = SEPARATOR_AT - * BORDER_WIDTH ; variableNames . setLayoutData ( variableNamesLayoutData ) ; variableNames . setLayout ( variableNamesLayout ) ; Label newNameLabel = new Label ( variableNames , SWT . NONE ) ; newNameLabel . setText ( Messages . SplitTempPage_ChooseNewNames ) ; if ( localUsages != null ) { names = new Text [ localUsages . size ( ) ] ; for ( int i = ; i < localUsages . size ( ) ; i ++ ) { Text text = new Text ( variableNames , SWT . BORDER ) ; GridData textLData = new GridData ( ) ; textLData . horizontalAlignment = GridData . FILL ; textLData . grabExcessHorizontalSpace = true ; text . setLayoutData ( textLData ) ; text . setText ( localUsages . toArray ( new LocalVarUsage [ localUsages . size ( ) ] ) [ i ] . getName ( ) ) ; text . setBackground ( new Color ( getShell ( ) . getDisplay ( ) , colors [ i ] ) ) ; text . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { setNewNames ( ) ; } } ) ; names [ i ] = text ; } RdtCodeViewer sourceWidget = RdtCodeViewer . create ( main ) ; FormData layoutData = new FormData ( ) ; layoutData . top = new FormAttachment ( , , BORDER_WIDTH ) ; layoutData . bottom = new FormAttachment ( , , - BORDER_WIDTH ) ; layoutData . right = new FormAttachment ( , , - BORDER_WIDTH ) ; layoutData . left = new FormAttachment ( , , SEPARATOR_AT ) ; sourceWidget . getTextWidget ( ) . setLayoutData ( layoutData ) ; sourceWidget . getTextWidget ( ) . setText ( source ) ; int colorIndex = ; for ( LocalVarUsage var : localUsages ) { sourceWidget . setBackgroundColor ( var . getFromPosition ( ) , var . getName ( ) . length ( ) , colors [ colorIndex ++ ] ) ; } setNewNames ( ) ; sourceWidget . getTextWidget ( ) . setSelection ( localUsages . toArray ( new LocalVarUsage [ localUsages . size ( ) ] ) [ localUsages . size ( ) - ] . getFromPosition ( ) ) ; } main . layout ( ) ; setControl ( main ) ; } private void setNewNames ( ) { assert names . length == localUsages . size ( ) ; String [ ] newNames = new String [ localUsages . size ( ) ] ; boolean allOk = true ; for ( int i = ; i < names . length ; i ++ ) { if ( names [ i ] . getText ( ) . equals ( "" ) ) { setErrorMessage ( Messages . SplitTempPage_PleaseEnterName ) ; allOk = false ; } else if ( ! NameValidator . isValidLocalVariableName ( names [ i ] . getText ( ) ) ) { setErrorMessage ( names [ i ] . getText ( ) + Messages . SplitTempPage_InvalidVariableName ) ; allOk = false ; } newNames [ i ] = names [ i ] . getText ( ) ; } setPageComplete ( allOk ) ; if ( allOk ) { setErrorMessage ( null ) ; } receiver . setNewNames ( newNames ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldConfig ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldRefactoring ; public class MoveFieldPage extends RefactoringWizardPage { private final class ReferenceSelectionListener implements SelectionListener { private final Combo combo ; public ReferenceSelectionListener ( final Combo combo ) { this . combo = combo ; } public void widgetDefaultSelected ( final SelectionEvent event ) { } public void widgetSelected ( final SelectionEvent event ) { config . setTargetReference ( combo . getText ( ) ) ; } } private final class ClassNameSelectionListener implements SelectionListener { private final Combo combo ; public ClassNameSelectionListener ( final Combo combo ) { this . combo = combo ; } public void widgetDefaultSelected ( final SelectionEvent event ) { } public void widgetSelected ( final SelectionEvent event ) { config . setTargetClass ( combo . getText ( ) ) ; } } private final MoveFieldConfig config ; public MoveFieldPage ( final MoveFieldConfig config ) { super ( MoveFieldRefactoring . NAME ) ; this . config = config ; setTitle ( MoveFieldRefactoring . NAME ) ; } public void createControl ( final Composite parent ) { final Composite composite = new Composite ( parent , SWT . None ) ; composite . setLayout ( new GridLayout ( , false ) ) ; createTitleLabel ( composite ) ; createClassLabel ( composite ) ; createClassComboBox ( composite ) ; createReferenceLabel ( composite ) ; createReferenceComboBox ( composite ) ; setControl ( composite ) ; } private void createReferenceComboBox ( final Composite composite ) { final Combo combobox = new Combo ( composite , SWT . DROP_DOWN | SWT . READ_ONLY ) ; combobox . setVisibleItemCount ( ) ; for ( String fieldName : config . getReferenceCandidates ( ) ) { if ( config . getTargetReference ( ) == null ) { config . setTargetReference ( fieldName ) ; combobox . setText ( fieldName ) ; } combobox . add ( fieldName ) ; } combobox . select ( ) ; combobox . addSelectionListener ( new ReferenceSelectionListener ( combobox ) ) ; } private void createReferenceLabel ( final Composite composite ) { final Label referenceLabel = new Label ( composite , SWT . NONE ) ; referenceLabel . setText ( Messages . MoveFieldPage_AccessibleBy ) ; } private void createClassComboBox ( final Composite composite ) { final Combo combobox = new Combo ( composite , SWT . DROP_DOWN | SWT . READ_ONLY ) ; combobox . setVisibleItemCount ( ) ; for ( String name : config . getTargetClassCandidates ( ) ) { if ( config . getTargetClass ( ) == null ) { config . setTargetClass ( name ) ; } combobox . add ( name ) ; } combobox . select ( ) ; combobox . addSelectionListener ( new ClassNameSelectionListener ( combobox ) ) ; } private void createClassLabel ( final Composite composite ) { final Label moveToClassLabel = new Label ( composite , SWT . NONE ) ; moveToClassLabel . setText ( Messages . MoveFieldPage_MoveToClass ) ; } private void createTitleLabel ( final Composite composite ) { final Label title = new Label ( composite , SWT . NONE ) ; title . setText ( Messages . MoveFieldPage_Target + config . getSelectedFieldName ( ) + "" ) ; final GridData gridData = new GridData ( ) ; gridData . horizontalSpan = ; title . setLayoutData ( gridData ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . jface . dialogs . IMessageProvider ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Table ; import org . rubypeople . rdt . internal . refactoring . RefactoringMessages ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractedMethodHelper ; import org . rubypeople . rdt . refactoring . core . extractmethod . MethodExtractor ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . ButtonStateListener ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . ExtractMethodComposite ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . IValidationController ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . MethodArgumentTableItem ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . MethodNameListener ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . ParameterTextChanged ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . ParametersButtonDownListener ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . ParametersButtonUpListener ; import org . rubypeople . rdt . refactoring . ui . pages . extractmethod . SignatureObserver ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class ExtractMethodPage extends RefactoringWizardPage implements IValidationController { private static final String title = Messages . ExtractMethodPage_Title ; private MethodExtractor methodExtractor ; private ExtractMethodComposite extractComposite ; private final IRefactoringContext selectionInformation ; private ExtractedMethodHelper extractedMethod ; public ExtractMethodPage ( MethodExtractor methodExtractor , IRefactoringContext selectionInformation ) { super ( title ) ; this . methodExtractor = methodExtractor ; extractedMethod = methodExtractor . getExtractedMethod ( ) ; this . selectionInformation = selectionInformation ; } private class ItemNameObserver implements Observer { public void update ( Observable o , Object arg ) { ParameterTextChanged change = ( ParameterTextChanged ) arg ; extractedMethod . changeParameter ( change . getOriginalPosition ( ) , change . getTo ( ) ) ; } } private class ItemOrderObserver implements Observer { public void update ( Observable o , Object arg ) { ParameterTextChanged change = ( ParameterTextChanged ) arg ; extractedMethod . changeParameter ( change . getOriginalPosition ( ) , change . getNewPosition ( ) ) ; } } public void createControl ( Composite parent ) { extractComposite = new ExtractMethodComposite ( parent , this , extractedMethod . hasArguments ( ) , extractedMethod . getVisibility ( ) != VisibilityNodeWrapper . METHOD_VISIBILITY . NONE ) ; extractedMethod . addObserver ( new SignatureObserver ( extractComposite . getMethodSignaturePreviewLabel ( ) , extractedMethod ) ) ; if ( extractedMethod . hasArguments ( ) ) { setupArgumentsTable ( extractComposite . getParametersTable ( ) , extractComposite . getUpParametersButton ( ) , extractComposite . getDownParametersButton ( ) , extractComposite . getEditParametersButton ( ) ) ; } setControl ( extractComposite ) ; addNewMethodNameListener ( ) ; if ( extractedMethod . getVisibility ( ) != VisibilityNodeWrapper . METHOD_VISIBILITY . NONE ) { setupVisibilityHandlers ( ) ; } if ( extractComposite . getCellEditorListener ( ) != null ) { extractComposite . getCellEditorListener ( ) . addObserver ( new ItemNameObserver ( ) ) ; } setupSelectionPreview ( ) ; final Button replaceAllInstance = new Button ( extractComposite , SWT . CHECK ) ; GridData checkData = new GridData ( ) ; replaceAllInstance . setLayoutData ( checkData ) ; replaceAllInstance . setText ( RefactoringMessages . ExtractConstantInputPage_replace_all_occurrences ) ; replaceAllInstance . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { methodExtractor . setReplaceAllInstances ( replaceAllInstance . getSelection ( ) ) ; } } ) ; } private void setupSelectionPreview ( ) { extractComposite . getCodeViewer ( ) . setPreviewText ( selectionInformation . getSource ( ) ) ; int nodeStart = NodeUtil . subPositionUnion ( extractedMethod . getSelectedNodes ( ) ) . getStartOffset ( ) ; int nodeLength = NodeUtil . subPositionUnion ( extractedMethod . getSelectedNodes ( ) ) . getEndOffset ( ) - nodeStart ; extractComposite . getCodeViewer ( ) . setBackgroundColor ( nodeStart , nodeLength , SWT . COLOR_GRAY ) ; int selectionStart = selectionInformation . getStartOffset ( ) ; int selectionLength = selectionInformation . getEndOffset ( ) - selectionStart + ; extractComposite . getCodeViewer ( ) . setBackgroundColor ( selectionStart , selectionLength , SWT . COLOR_DARK_GRAY ) ; scrollToSelection ( ) ; } private void setupVisibilityHandlers ( ) { if ( ExtractedMethodHelper . DEFAULT_VISIBILITY . equals ( VisibilityNodeWrapper . METHOD_VISIBILITY . PRIVATE ) ) { extractComposite . getPrivateAccessRadioButton ( ) . setSelection ( true ) ; } else if ( ExtractedMethodHelper . DEFAULT_VISIBILITY . equals ( VisibilityNodeWrapper . METHOD_VISIBILITY . PROTECTED ) ) { extractComposite . getProtectedAccessRadioButton ( ) . setSelection ( true ) ; } else if ( ExtractedMethodHelper . DEFAULT_VISIBILITY . equals ( VisibilityNodeWrapper . METHOD_VISIBILITY . PUBLIC ) ) { extractComposite . getPublicAccessRadioButton ( ) . setSelection ( true ) ; } extractComposite . getPrivateAccessRadioButton ( ) . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { extractedMethod . setVisibility ( VisibilityNodeWrapper . METHOD_VISIBILITY . PRIVATE ) ; } } ) ; extractComposite . getPublicAccessRadioButton ( ) . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { extractedMethod . setVisibility ( VisibilityNodeWrapper . METHOD_VISIBILITY . PUBLIC ) ; } } ) ; extractComposite . getProtectedAccessRadioButton ( ) . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { extractedMethod . setVisibility ( VisibilityNodeWrapper . METHOD_VISIBILITY . PROTECTED ) ; } } ) ; extractComposite . getNoneAccessRadioButton ( ) . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { extractedMethod . setVisibility ( VisibilityNodeWrapper . METHOD_VISIBILITY . NONE ) ; } } ) ; } private void setupArgumentsTable ( final Table table , Button upButton , Button downButton , Button editButton ) { insertParameterItems ( table ) ; ParametersButtonUpListener upListener = new ParametersButtonUpListener ( extractComposite . getParametersTable ( ) ) ; ParametersButtonDownListener downListener = new ParametersButtonDownListener ( extractComposite . getParametersTable ( ) ) ; extractComposite . getUpParametersButton ( ) . addListener ( SWT . Selection , upListener ) ; extractComposite . getDownParametersButton ( ) . addListener ( SWT . Selection , downListener ) ; ButtonStateListener listener = new ButtonStateListener ( table , upButton , downButton , editButton ) ; upListener . addObserver ( listener ) ; downListener . addObserver ( listener ) ; upListener . addObserver ( new ItemOrderObserver ( ) ) ; downListener . addObserver ( new ItemOrderObserver ( ) ) ; table . addListener ( SWT . Selection , listener ) ; } private void insertParameterItems ( final Table table ) { String [ ] names = extractedMethod . getArguments ( ) . toArray ( new String [ extractedMethod . getArguments ( ) . size ( ) ] ) ; for ( int i = ; i < names . length ; i ++ ) { new MethodArgumentTableItem ( table , names [ i ] , true , i , i ) ; } } private void addNewMethodNameListener ( ) { MethodNameListener methodNameListener = new MethodNameListener ( methodExtractor , this ) ; extractComposite . getNewMethodNameText ( ) . getText ( ) . addModifyListener ( methodNameListener ) ; setComplete ( methodNameListener , false ) ; } private HashMap < Object , Boolean > completedValidators = new HashMap < Object , Boolean > ( ) ; public void setError ( String message ) { setMessage ( message , IMessageProvider . ERROR ) ; } public void setComplete ( Object source , boolean complete ) { completedValidators . put ( source , Boolean . valueOf ( complete ) ) ; boolean allOk = true ; for ( boolean ok : completedValidators . values ( ) ) { if ( ! ok ) { allOk = false ; } } setPageComplete ( allOk ) ; } public void scrollToSelection ( ) { extractComposite . getCodeViewer ( ) . getTextWidget ( ) . setSelection ( selectionInformation . getStartOffset ( ) ) ; extractComposite . getCodeViewer ( ) . getTextWidget ( ) . setSelection ( selectionInformation . getEndOffset ( ) ) ; extractComposite . getCodeViewer ( ) . getTextWidget ( ) . showSelection ( ) ; } public ArrayList < String > getInvalidNames ( ) { return extractedMethod . getLocalOnlyVariables ( ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . ltk . ui . refactoring . UserInputWizardPage ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; public abstract class RefactoringWizardPage extends UserInputWizardPage { public RefactoringWizardPage ( String name ) { super ( name ) ; } @ Override public void setVisible ( boolean visible ) { if ( visible ) { pageIsEnabled ( ) ; } else { pageIsDisabled ( ) ; } super . setVisible ( visible ) ; } public void pageIsEnabled ( ) { RubyRefactoring refactoring = ( RubyRefactoring ) getRefactoring ( ) ; RefactoringConditionChecker refactoringConditionChecker = ( RefactoringConditionChecker ) refactoring . getConditionChecker ( ) ; if ( refactoringConditionChecker == null ) { return ; } IRefactoringConfig config = refactoringConditionChecker . getConfig ( ) ; config . setDocumentProvider ( refactoring . getDocumentProvider ( ) ) ; refactoringConditionChecker . init ( config ) ; } public void pageIsDisabled ( ) { } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . layout . RowLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . LocalToFieldConverter ; import org . rubypeople . rdt . refactoring . ui . LabeledTextField ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class ConvertLocalToFieldPage extends RefactoringWizardPage { private static final String TITLE = Messages . ConvertTempToFieldPage_ConvertLocalVariableToField ; private LocalToFieldConverter converter ; private ConverterPageParameters pageParameters ; public ConvertLocalToFieldPage ( LocalToFieldConverter converter , ConverterPageParameters parameters ) { super ( TITLE ) ; this . converter = converter ; this . pageParameters = parameters ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . None ) ; setControl ( control ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . verticalSpacing = ; control . setLayout ( layout ) ; final LabeledTextField labeledText = new LabeledTextField ( control , Messages . ConvertTempToFieldPage_FieldName , converter . getLocalVarName ( ) ) ; GridData layoutData = new GridData ( GridData . FILL_HORIZONTAL ) ; labeledText . setLayoutData ( layoutData ) ; labeledText . getText ( ) . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { String newName = labeledText . getText ( ) . getText ( ) ; converter . setNewName ( newName ) ; checkInput ( newName ) ; } private void checkInput ( String newName ) { if ( NameValidator . isValidLocalVariableName ( newName ) ) { ConvertLocalToFieldPage . this . setMessage ( null ) ; ConvertLocalToFieldPage . this . setPageComplete ( true ) ; } else { ConvertLocalToFieldPage . this . setMessage ( "" + newName + Messages . ConvertTempToFieldPage_IsNotValid , ConvertLocalToFieldPage . ERROR ) ; ConvertLocalToFieldPage . this . setPageComplete ( false ) ; } } } ) ; initInitializeRadioGroup ( control ) ; final Button declareClassField = new Button ( control , SWT . CHECK ) ; GridData checkData = new GridData ( ) ; declareClassField . setLayoutData ( checkData ) ; declareClassField . setText ( Messages . ConvertTempToFieldPage_DeclareAsClassField ) ; declareClassField . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { converter . setIsClassField ( declareClassField . getSelection ( ) ) ; } } ) ; } private void initInitializeRadioGroup ( Composite control ) { Group initializeInGroup = new Group ( control , SWT . NONE ) ; RowLayout radioGroupLayout = new RowLayout ( SWT . VERTICAL ) ; initializeInGroup . setLayout ( radioGroupLayout ) ; initializeInGroup . setText ( Messages . ConvertTempToFieldPage_InitializeIn ) ; Button inCurrentMethod = new Button ( initializeInGroup , SWT . RADIO ) ; inCurrentMethod . setText ( Messages . ConvertTempToFieldPage_CurrentMethod ) ; inCurrentMethod . setEnabled ( pageParameters . isInCurrentMethodRadioEnabled ( ) ) ; addRadioListener ( inCurrentMethod , LocalToFieldConverter . INIT_IN_METHOD ) ; inCurrentMethod . setSelection ( true ) ; Button inClassConstructor = new Button ( initializeInGroup , SWT . RADIO ) ; inClassConstructor . setText ( Messages . ConvertTempToFieldPage_ClassConstructor ) ; inClassConstructor . setEnabled ( pageParameters . isInClassConstructorRadioEnabled ( ) ) ; addRadioListener ( inClassConstructor , LocalToFieldConverter . INIT_IN_CONSTRUCTOR ) ; GridData groupData = new GridData ( GridData . FILL_HORIZONTAL ) ; initializeInGroup . setLayoutData ( groupData ) ; } private void addRadioListener ( Button button , final int initPlace ) { button . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { converter . setInitPlace ( initPlace ) ; } } ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import java . util . ArrayList ; import java . util . Comparator ; import java . util . TreeSet ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . renamemethod . NodeSelector ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . ui . RdtCodeViewer ; import org . rubypeople . rdt . refactoring . util . JRubyRefactoringUtils ; public class OccurenceReplaceSelectionPage extends RefactoringWizardPage { public static final String NAME = Messages . OccurenceReplaceSelectionPage_SelectCalls ; private final static RGB highlightColor = new RGB ( , , ) ; private NodeSelector selector ; private Table possibilityTable ; private IDocumentProvider docProvider ; public OccurenceReplaceSelectionPage ( NodeSelector selector , IDocumentProvider docProvider ) { super ( NAME ) ; this . selector = selector ; this . docProvider = docProvider ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . NONE ) ; FillLayout controlLayout = new FillLayout ( ) ; controlLayout . spacing = ; controlLayout . marginHeight = ; controlLayout . marginWidth = ; control . setLayout ( controlLayout ) ; initPossibilityTable ( control ) ; initCodeView ( control ) ; setControl ( control ) ; } private void initCodeView ( Composite control ) { final RdtCodeViewer viewer = RdtCodeViewer . create ( control ) ; possibilityTable . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { INodeWrapper currentCall = ( INodeWrapper ) e . item . getData ( ) ; ISourcePosition pos = currentCall . getWrappedNode ( ) . getPosition ( ) ; String file = docProvider . getFileContent ( currentCall . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ) ; updateCodeViewer ( viewer , pos , file ) ; updateChecks ( ) ; } private void updateCodeViewer ( final RdtCodeViewer viewer , ISourcePosition pos , String content ) { int length = pos . getEndOffset ( ) - pos . getStartOffset ( ) ; viewer . setPreviewText ( content ) ; viewer . setBackgroundColor ( pos . getStartOffset ( ) , length , highlightColor ) ; viewer . getTextWidget ( ) . setSelection ( pos . getStartOffset ( ) ) ; viewer . getTextWidget ( ) . showSelection ( ) ; } private void updateChecks ( ) { ArrayList < INodeWrapper > checkedCalls = new ArrayList < INodeWrapper > ( ) ; for ( TableItem currentItem : possibilityTable . getItems ( ) ) { if ( currentItem . getChecked ( ) ) { checkedCalls . add ( ( INodeWrapper ) currentItem . getData ( ) ) ; } } selector . setSelectedCalls ( checkedCalls ) ; } } ) ; } private void initPossibilityTable ( Composite control ) { possibilityTable = new Table ( control , SWT . BORDER | SWT . CHECK ) ; TreeSet < INodeWrapper > possibleCalls = new TreeSet < INodeWrapper > ( new Comparator < INodeWrapper > ( ) { public int compare ( INodeWrapper left , INodeWrapper right ) { return left . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) - right . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ; } } ) ; possibleCalls . addAll ( selector . getPossibleCalls ( ) ) ; for ( INodeWrapper currentCall : possibleCalls ) { TableItem currentItem = new TableItem ( possibilityTable , SWT . NONE ) ; currentItem . setText ( getTableCaption ( currentCall ) ) ; if ( probableCall ( currentCall ) ) { currentItem . setChecked ( true ) ; } currentItem . setData ( currentCall ) ; } } private String getTableCaption ( INodeWrapper currentCall ) { ISourcePosition pos = currentCall . getWrappedNode ( ) . getPosition ( ) ; return pos . getFile ( ) + Messages . OccurenceReplaceSelectionPage_Line + ( pos . getStartLine ( ) ) ; } private boolean probableCall ( INodeWrapper currentCall ) { for ( INodeWrapper targetCall : selector . getSelectedCalls ( ) ) { if ( hasSamePosition ( currentCall , targetCall ) ) { return true ; } } return false ; } private boolean hasSamePosition ( INodeWrapper currentCall , INodeWrapper targetCall ) { return JRubyRefactoringUtils . hasSamePosition ( currentCall . getWrappedNode ( ) , targetCall . getWrappedNode ( ) ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . layout . RowLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Spinner ; import org . eclipse . swt . widgets . TabFolder ; import org . eclipse . swt . widgets . TabItem ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . refactoring . core . formatsource . PreviewGenerator ; public class FormatSourcePage extends RefactoringWizardPage { private static final String title = "" ; private StyledText previewText ; private EditableFormatHelper formatter ; private PreviewGenerator previewGenererator ; public FormatSourcePage ( EditableFormatHelper formatter , PreviewGenerator previewGenerator ) { super ( title ) ; setTitle ( title ) ; this . formatter = formatter ; this . previewGenererator = previewGenerator ; } private void createMethodsTab ( TabFolder categoryTab ) { TabItem methodsTabItem = createTabItem ( categoryTab , Messages . FormatSourcePage_Methods ) ; Composite optionComposite = createCompositeWithGridLayout ( categoryTab ) ; methodsTabItem . setControl ( optionComposite ) ; Group callArgumentsGroup = createGroupWithGridLayout ( optionComposite , Messages . FormatSourcePage_MethodCallArguments ) ; final Button callArgumentsParanthesizeWhereNecessary = createButton ( callArgumentsGroup , SWT . RADIO , Messages . FormatSourcePage_ParenthesizeWhereNecesary ) ; callArgumentsParanthesizeWhereNecessary . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setAlwaysParanthesizeMethodCalls ( ! callArgumentsParanthesizeWhereNecessary . getEnabled ( ) ) ; generatePreview ( ) ; } } ) ; final Button callArgumentsParanthesizeAlways = createButton ( callArgumentsGroup , SWT . RADIO , Messages . FormatSourcePage_AlwaysParenthesize ) ; callArgumentsParanthesizeAlways . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setAlwaysParanthesizeMethodCalls ( callArgumentsParanthesizeAlways . getEnabled ( ) ) ; generatePreview ( ) ; } } ) ; Group defArgumentsGroup = createGroupWithGridLayout ( optionComposite , Messages . FormatSourcePage_MethodDefArguments ) ; final Button defArgumentsParanthesizeWhereNecessary = createButton ( defArgumentsGroup , SWT . RADIO , Messages . FormatSourcePage_ParenthesizeWhereNecesary ) ; defArgumentsParanthesizeWhereNecessary . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setAlwaysParanthesizeMethodDefs ( ! defArgumentsParanthesizeWhereNecessary . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; final Button defArgumentsParanthesizeAlways = createButton ( defArgumentsGroup , SWT . RADIO , Messages . FormatSourcePage_AlwaysParenthesize ) ; defArgumentsParanthesizeAlways . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setAlwaysParanthesizeMethodDefs ( defArgumentsParanthesizeAlways . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; final Button newlineBetweenClassBodyElements = createButton ( optionComposite , SWT . CHECK , Messages . FormatSourcePage_NewlineBetweenClassElements ) ; newlineBetweenClassBodyElements . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setNewlineBetweenClassBodyElements ( newlineBetweenClassBodyElements . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; } private void createBlocksTab ( TabFolder categoryTab ) { TabItem misc = createTabItem ( categoryTab , Messages . FormatSourcePage_Blocks ) ; Composite composite = createCompositeWithGridLayout ( categoryTab ) ; misc . setControl ( composite ) ; final Button spaceBeforeIterBrackets = createButton ( composite , SWT . CHECK , Messages . FormatSourcePage_SpaceBeforeIterBrackets ) ; spaceBeforeIterBrackets . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setSpaceBeforeIterBrackets ( spaceBeforeIterBrackets . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; final Button spaceBeforeClosingIterBrackets = createButton ( composite , SWT . CHECK , Messages . FormatSourcePage_SpaceBeforeClosingIterBracket ) ; spaceBeforeClosingIterBrackets . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setSpaceBeforeClosingIterBrackets ( spaceBeforeClosingIterBrackets . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; final Button spaceBeforeIterVars = createButton ( composite , SWT . CHECK , Messages . FormatSourcePage_SpaceBeforeIterVars ) ; spaceBeforeIterVars . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setSpaceBeforeIterVars ( spaceBeforeIterVars . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; final Button spaceAfterIterVars = createButton ( composite , SWT . CHECK , Messages . FormatSourcePage_SpaceAfterIterVars ) ; spaceAfterIterVars . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setSpaceAfterIterVars ( spaceAfterIterVars . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; } private void createSpacesTab ( TabFolder categoryTab ) { TabItem spaces = createTabItem ( categoryTab , Messages . FormatSourcePage_Spaces ) ; Composite composite = createCompositeWithGridLayout ( categoryTab ) ; spaces . setControl ( composite ) ; final Button spaceAfterComma = createButton ( composite , SWT . CHECK , Messages . FormatSourcePage_SpaceAfterComma ) ; spaceAfterComma . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setSpaceAfterCommaInListings ( spaceAfterComma . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; final Button spacesAroundHashAss = createButton ( composite , SWT . CHECK , Messages . FormatSourcePage_SpacesAroundHashOperator ) ; spacesAroundHashAss . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setSpacesAroundHashAssignment ( spacesAroundHashAss . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; final Button spacesAroundHashContent = createButton ( composite , SWT . CHECK , Messages . FormatSourcePage_SpacesAroundHash ) ; spacesAroundHashContent . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setSpacesBeforeAndAfterHashContent ( spacesAroundHashContent . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; final Button spacesAroundAssignments = createButton ( composite , SWT . CHECK , Messages . FormatSourcePage_SpacesAroundAssignment ) ; spacesAroundAssignments . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setSpacesBeforeAndAfterAssignments ( spacesAroundAssignments . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; } private void createGeneralTab ( TabFolder categoryTab ) { TabItem spaces = createTabItem ( categoryTab , Messages . FormatSourcePage_General ) ; Composite composite = createCompositeWithGridLayout ( categoryTab ) ; spaces . setControl ( composite ) ; Group callArgumentsGroup = createGroupWithGridLayout ( composite , Messages . FormatSourcePage_Indentation ) ; final Button tabInsteadOfSpaces = createButton ( callArgumentsGroup , SWT . CHECK , Messages . FormatSourcePage_UseTab ) ; tabInsteadOfSpaces . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setTabInsteadOfSpaces ( tabInsteadOfSpaces . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; Composite indentationComposite = new Composite ( callArgumentsGroup , SWT . NONE ) ; indentationComposite . setLayout ( new RowLayout ( ) ) ; final Spinner indentationSteps = new Spinner ( indentationComposite , SWT . BORDER ) ; indentationSteps . setMinimum ( ) ; indentationSteps . setMaximum ( ) ; indentationSteps . setSelection ( ) ; indentationSteps . setIncrement ( ) ; indentationSteps . pack ( ) ; indentationSteps . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { formatter . setIndentationSteps ( indentationSteps . getSelection ( ) ) ; generatePreview ( ) ; } } ) ; Label label = new Label ( indentationComposite , SWT . NONE ) ; label . setText ( Messages . FormatSourcePage_IndentationSteps ) ; } public void createControl ( Composite parent ) { SashForm mainSashForm = new SashForm ( parent , SWT . NONE ) ; TabFolder categoryTab = new TabFolder ( mainSashForm , SWT . NONE ) ; createGeneralTab ( categoryTab ) ; createMethodsTab ( categoryTab ) ; createSpacesTab ( categoryTab ) ; createBlocksTab ( categoryTab ) ; previewText = new StyledText ( mainSashForm , SWT . H_SCROLL | SWT . V_SCROLL | SWT . READ_ONLY | SWT . BORDER ) ; generatePreview ( ) ; parent . layout ( ) ; setControl ( parent ) ; } private void generatePreview ( ) { previewText . setText ( previewGenererator . getPreview ( formatter ) ) ; } private TabItem createTabItem ( TabFolder parent , String name ) { TabItem item = new TabItem ( parent , SWT . NONE ) ; item . setText ( name ) ; return item ; } private Composite createCompositeWithGridLayout ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . makeColumnsEqualWidth = true ; composite . setLayout ( layout ) ; return composite ; } private GridData createFillingGrid ( ) { GridData groupData = new GridData ( ) ; groupData . verticalAlignment = GridData . BEGINNING ; groupData . grabExcessHorizontalSpace = true ; groupData . horizontalAlignment = GridData . FILL ; return groupData ; } private Group createGroupWithGridLayout ( Composite parent , String groupText ) { Group group = new Group ( parent , SWT . NONE ) ; GridLayout groupLayout = new GridLayout ( ) ; groupLayout . makeColumnsEqualWidth = true ; group . setLayout ( groupLayout ) ; group . setLayoutData ( createFillingGrid ( ) ) ; group . setText ( groupText ) ; return group ; } private Button createButton ( Composite parent , int style , String text ) { Button button = new Button ( parent , style | SWT . LEFT ) ; button . setText ( text ) ; return button ; } } package org . rubypeople . rdt . refactoring . ui . pages . movemethod ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String FirstMoveMethodPage_Title ; public static String FirstMoveMethodPageComposite_DelegatesCalls ; public static String FirstMoveMethodPageComposite_LeaveDelegate ; public static String FirstMoveMethodPageComposite_MoveToClass ; public static String FirstMoveMethodPageComposite_SelectedClass ; public static String FirstMoveMethodPageComposite_SelectedMethod ; public static String FirstMoveMethodPageComposite_Selection ; public static String FirstMoveMethodPageComposite_Visibility ; public static String SecondMoveMethodPage_Title ; public static String SecondMoveMethodPageComposite_FieldReference ; public static String SecondMoveMethodPageComposite_MaintainCalls ; public static String SecondMoveMethodPageComposite_RequiredInClass ; public static String SecondMoveMethodPageComposite_SelectField ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . ui . pages . movemethod ; import org . eclipse . ltk . ui . refactoring . UserInputWizardPage ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodConfig ; public class SecondMoveMethodPage extends UserInputWizardPage { private static final String TITLE = Messages . SecondMoveMethodPage_Title ; private MoveMethodConfig config ; public SecondMoveMethodPage ( MoveMethodConfig config ) { super ( TITLE ) ; this . config = config ; } public void createControl ( Composite parent ) { SecondMoveMethodPageComposite pageContent = new SecondMoveMethodPageComposite ( parent , config ) ; setControl ( pageContent ) ; } } package org . rubypeople . rdt . refactoring . ui . pages . movemethod ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodConfig ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; public class FirstMoveMethodPageComposite extends Composite { private MoveMethodConfig config ; public FirstMoveMethodPageComposite ( Composite parent , MoveMethodConfig config ) { super ( parent , SWT . NONE ) ; this . config = config ; initialize ( ) ; } private void initialize ( ) { GridLayout gridLayout = new GridLayout ( , false ) ; setLayout ( gridLayout ) ; createSelectionGroup ( ) ; createClassSelection ( ) ; createLeaveDelegateMethodCheck ( ) ; } private void createSelectionGroup ( ) { String selectedMethodName = config . getMethodNode ( ) . getName ( ) ; String selectedMethodVisibility = VisibilityNodeWrapper . getVisibilityName ( config . getMethodVisibility ( ) ) ; String selectedClassName = config . getSourceClassNode ( ) . getName ( ) ; Group group = new Group ( this , SWT . NONE ) ; group . setLayout ( new GridLayout ( ) ) ; group . setText ( Messages . FirstMoveMethodPageComposite_Selection ) ; group . setLayoutData ( getGridData ( , true ) ) ; Label selectedMethodLabel = new Label ( group , SWT . NONE ) ; selectedMethodLabel . setText ( Messages . FirstMoveMethodPageComposite_SelectedMethod + selectedMethodName ) ; Label visibilityLabel = new Label ( group , SWT . NONE ) ; visibilityLabel . setText ( Messages . FirstMoveMethodPageComposite_Visibility + selectedMethodVisibility ) ; visibilityLabel . setLayoutData ( getGridData ( , true ) ) ; Label selcetecClassLabel = new Label ( group , SWT . NONE ) ; selcetecClassLabel . setText ( Messages . FirstMoveMethodPageComposite_SelectedClass + selectedClassName ) ; selcetecClassLabel . setLayoutData ( getGridData ( , true ) ) ; } private GridData getGridData ( int span , boolean fill ) { GridData gridData = new GridData ( ) ; if ( span > ) { gridData . horizontalSpan = span ; } if ( fill ) { gridData . horizontalAlignment = GridData . FILL ; gridData . grabExcessHorizontalSpace = true ; } return gridData ; } private void createClassSelection ( ) { Label moveToClassLabel = new Label ( this , SWT . NONE ) ; moveToClassLabel . setText ( Messages . FirstMoveMethodPageComposite_MoveToClass ) ; final Combo classSelectionCombo = new Combo ( this , SWT . DROP_DOWN | SWT . READ_ONLY ) ; classSelectionCombo . setVisibleItemCount ( ) ; for ( String aktClassName : config . getTargetClassNames ( ) ) { if ( config . getDestinationClassNode ( ) == null ) { config . setDestinationClassNode ( aktClassName ) ; } classSelectionCombo . add ( aktClassName ) ; } classSelectionCombo . select ( ) ; classSelectionCombo . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { config . setDestinationClassNode ( classSelectionCombo . getText ( ) ) ; } } ) ; } private void createLeaveDelegateMethodCheck ( ) { final Button delegateCheck = new Button ( this , SWT . CHECK ) ; delegateCheck . setLayoutData ( getGridData ( , true ) ) ; delegateCheck . setText ( Messages . FirstMoveMethodPageComposite_LeaveDelegate + config . getSourceClassNode ( ) . getName ( ) + Messages . FirstMoveMethodPageComposite_DelegatesCalls + config . getMethodNode ( ) . getName ( ) + "" ) ; delegateCheck . setSelection ( config . leaveDelegateMethodInSource ( ) ) ; if ( config . canCreateDelegateMethod ( ) ) { delegateCheck . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { config . setLeaveDelegateMethodInSource ( delegateCheck . getSelection ( ) ) ; } } ) ; } else { delegateCheck . setEnabled ( false ) ; } } } package org . rubypeople . rdt . refactoring . ui . pages . movemethod ; import org . eclipse . ltk . ui . refactoring . UserInputWizardPage ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodConfig ; public class FirstMoveMethodPage extends UserInputWizardPage { private static final String TITLE = Messages . FirstMoveMethodPage_Title ; private MoveMethodConfig config ; public FirstMoveMethodPage ( MoveMethodConfig config ) { super ( TITLE ) ; this . config = config ; } public void createControl ( Composite parent ) { FirstMoveMethodPageComposite pageContent = new FirstMoveMethodPageComposite ( parent , config ) ; setControl ( pageContent ) ; } } package org . rubypeople . rdt . refactoring . ui . pages . movemethod ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodConfig ; public class SecondMoveMethodPageComposite extends Composite implements Observer { private MoveMethodConfig config ; private Label infoTextLabel ; public SecondMoveMethodPageComposite ( Composite parent , MoveMethodConfig config ) { super ( parent , SWT . NONE ) ; this . config = config ; config . addObserver ( this ) ; setLayout ( new GridLayout ( , true ) ) ; init ( ) ; } private void init ( ) { initInformationText ( ) ; initFieldSelection ( ) ; } private void initInformationText ( ) { infoTextLabel = new Label ( this , SWT . WRAP ) ; infoTextLabel . setLayoutData ( getGridData ( true ) ) ; } private GridData getGridData ( boolean grab ) { GridData gridData = new GridData ( ) ; if ( grab ) { gridData . grabExcessHorizontalSpace = true ; gridData . horizontalAlignment = GridData . FILL ; } return gridData ; } private void initFieldSelection ( ) { final Combo fieldSelectionCombo = new Combo ( this , SWT . DROP_DOWN | SWT . READ_ONLY ) ; fieldSelectionCombo . setVisibleItemCount ( ) ; fieldSelectionCombo . setLayoutData ( getGridData ( false ) ) ; for ( String fieldName : config . getFieldInSourceClassOfTypeDestinationClassNames ( ) ) { if ( config . getFieldInSourceClassOfTypeDestinationClass ( ) == null ) { config . setFieldInSourceClassOfTypeDestinationClass ( fieldName ) ; fieldSelectionCombo . setText ( fieldName ) ; } fieldSelectionCombo . add ( fieldName ) ; } fieldSelectionCombo . select ( ) ; fieldSelectionCombo . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { config . setFieldInSourceClassOfTypeDestinationClass ( fieldSelectionCombo . getText ( ) ) ; } } ) ; } public void update ( Observable arg0 , Object arg1 ) { String selectedMethodName = config . getMethodNode ( ) . getName ( ) ; String sourceClassName = config . getSourceClassNode ( ) . getName ( ) ; String destClassName = config . getDestinationClassNode ( ) . getName ( ) ; String infoText = Messages . SecondMoveMethodPageComposite_MaintainCalls + selectedMethodName + Messages . SecondMoveMethodPageComposite_FieldReference + destClassName + Messages . SecondMoveMethodPageComposite_RequiredInClass + sourceClassName + Messages . SecondMoveMethodPageComposite_SelectField ; infoTextLabel . setText ( infoText ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String AccessorSelectionPage_AccessorMethod ; public static String AccessorSelectionPage_ExampleAccessorMethod ; public static String AccessorSelectionPage_ExampleSimpleAccessor ; public static String AccessorSelectionPage_GenerateMethods ; public static String AccessorSelectionPage_GenerateSimple ; public static String AccessorSelectionPage_SelectType ; public static String AccessorSelectionPage_SimpeAccessor ; public static String AccessorSelectionPage_Title ; public static String ConstructorSelectionPage_EmptyConstructor ; public static String ConstructorSelectionPage_EmptyConstructorCode ; public static String ConstructorSelectionPage_ParametrisedConstructor ; public static String ConstructorSelectionPage_ParametrisedConstructorCode ; public static String ConstructorSelectionPage_SelectConstructor ; public static String ConvertTempToFieldPage_ClassConstructor ; public static String ConvertTempToFieldPage_ConvertLocalVariableToField ; public static String ConvertTempToFieldPage_CurrentMethod ; public static String ConvertTempToFieldPage_DeclareAsClassField ; public static String ConvertTempToFieldPage_FieldName ; public static String ConvertTempToFieldPage_InitializeIn ; public static String ConvertTempToFieldPage_IsNotValid ; public static String EncapsulateFieldPage_FieldAccessor ; public static String EncapsulateFieldPage_Name ; public static String EncapsulateFieldPage_Reader ; public static String EncapsulateFieldPage_SelectedField ; public static String EncapsulateFieldPage_Title ; public static String EncapsulateFieldPage_Writer ; public static String ExtractMethodPage_Title ; public static String FormatSourcePage_AlwaysParenthesize ; public static String FormatSourcePage_Blocks ; public static String FormatSourcePage_General ; public static String FormatSourcePage_Indentation ; public static String FormatSourcePage_IndentationSteps ; public static String FormatSourcePage_MethodCallArguments ; public static String FormatSourcePage_MethodDefArguments ; public static String FormatSourcePage_Methods ; public static String FormatSourcePage_NewlineBetweenClassElements ; public static String FormatSourcePage_ParenthesizeWhereNecesary ; public static String FormatSourcePage_SpaceAfterComma ; public static String FormatSourcePage_SpaceAfterIterVars ; public static String FormatSourcePage_SpaceBeforeClosingIterBracket ; public static String FormatSourcePage_SpaceBeforeIterBrackets ; public static String FormatSourcePage_SpaceBeforeIterVars ; public static String FormatSourcePage_Spaces ; public static String FormatSourcePage_SpacesAroundAssignment ; public static String FormatSourcePage_SpacesAroundHash ; public static String FormatSourcePage_SpacesAroundHashOperator ; public static String FormatSourcePage_UseTab ; public static String InlineClassPage_InlineTemp ; public static String InlineClassPage_SelectTargetClass ; public static String InlineMethodPage_DeleteDeclaration ; public static String InlineMethodPage_MakeSureIsntUsed ; public static String InlineMethodPage_Name ; public static String InlineTempPage_ExtractToMethod ; public static String InlineTempPage_IsNotValidName ; public static String InlineTempPage_NewMethodName ; public static String InlineTempPage_Occurences ; public static String InlineTempPage_Replace ; public static String InlineTempPage_ReplaceTempWithQuery ; public static String MergeClassPartsInFilePage_Description ; public static String MergeClassPartsInFilePage_Explanation ; public static String MergeClassPartsInFilePage_SelectClassParts ; public static String MergeWithExternalClassPartsPage_Description ; public static String MergeWithExternalClassPartsPage_DescriptionText ; public static String MergeWithExternalClassPartsPage_SelectParts ; public static String MethodDownPusherSelectionPage_Title ; public static String MoveFieldPage_AccessibleBy ; public static String MoveFieldPage_MoveToClass ; public static String MoveFieldPage_Target ; public static String OccurenceReplaceSelectionPage_Line ; public static String OccurenceReplaceSelectionPage_SelectCalls ; public static String OverrideMethodSelectionPage_SelectMethods ; public static String RenameFieldPage_Name ; public static String RenameFieldPage_RenameAccessors ; public static String RenamePage_NewName ; public static String RenamePage_Title ; public static String SplitTempPage_ChooseNewNames ; public static String SplitTempPage_InvalidVariableName ; public static String SplitTempPage_PleaseEnterName ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . rubypeople . rdt . refactoring . ui . ICheckboxListener ; import org . rubypeople . rdt . refactoring . ui . LabeledTextField ; import org . rubypeople . rdt . refactoring . ui . NewNameListener ; public class RenameFieldPage extends RenamePage { private static final String NAME = Messages . RenameFieldPage_Name ; private final ICheckboxListener checkListener ; public RenameFieldPage ( String selectedVariable , NewNameListener listener , ICheckboxListener checkListener ) { super ( NAME , selectedVariable , listener ) ; this . checkListener = checkListener ; } public void createControl ( Composite parent ) { Composite main = new Composite ( parent , SWT . None ) ; main . setLayout ( new GridLayout ( ) ) ; LabeledTextField textField = createTextField ( main ) ; textField . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; Button button = new Button ( main , SWT . CHECK ) ; button . setText ( Messages . RenameFieldPage_RenameAccessors ) ; button . setLayoutData ( new GridData ( ) ) ; button . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { checkListener . setChecked ( ( ( Button ) event . widget ) . getSelection ( ) ) ; } } ) ; setControl ( main ) ; } } package org . rubypeople . rdt . refactoring . ui . pages . inlinemethod ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . PlatformUI ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . ui . dialogs . TypeSelectionDialog2 ; import org . rubypeople . rdt . refactoring . core . inlinemethod . ITargetClassFinder ; import org . rubypeople . rdt . refactoring . core . inlinemethod . TargetClassFinder ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; public class TargetClassFinderUI implements ITargetClassFinder { private TargetClassFinder targetClassFinder ; public TargetClassFinderUI ( ) { targetClassFinder = new TargetClassFinder ( ) ; } public String findTargetClass ( MethodCallNodeWrapper call , IDocumentProvider doc ) { String result = targetClassFinder . findTargetClass ( call , doc ) ; if ( "" . equals ( result ) && call . getReceiverNode ( ) == null ) { return "" ; } if ( result == null || "" . equals ( result ) ) { final String title = Messages . TargetClassFinderUI_ChooseType + ( ( INameNode ) call . getReceiverNode ( ) ) . getName ( ) + '' ; TypeSelectionDialog2 dialog = new TypeSelectionDialog2 ( Display . getDefault ( ) . getActiveShell ( ) , false , PlatformUI . getWorkbench ( ) . getProgressService ( ) , SearchEngine . createWorkspaceScope ( ) , IRubySearchConstants . TYPE ) ; dialog . setTitle ( title ) ; if ( dialog . open ( ) == Window . OK ) { result = ( ( IType ) dialog . getFirstResult ( ) ) . getFullyQualifiedName ( ) ; } } return result ; } } package org . rubypeople . rdt . refactoring . ui . pages . inlinemethod ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String TargetClassFinderUI_ChooseType ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . refactoring . core . inlinelocal . InlineLocalConfig ; import org . rubypeople . rdt . refactoring . core . inlinelocal . InlineLocalRefactoring ; import org . rubypeople . rdt . refactoring . ui . LabeledTextField ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class InlineLocalPage extends RefactoringWizardPage { private InlineLocalConfig config ; private int occurencesCount ; private String selectedItemName ; private LabeledTextField newMethodName ; private Button checkQuery ; public InlineLocalPage ( InlineLocalConfig config , int occurencesCount , String selectedItemName ) { super ( InlineLocalRefactoring . NAME + "" ) ; this . config = config ; this . occurencesCount = occurencesCount ; this . selectedItemName = selectedItemName ; } @ Override public void pageIsEnabled ( ) { super . pageIsEnabled ( ) ; newMethodName . setEnabled ( checkQuery . getSelection ( ) ) ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . NONE ) ; setControl ( control ) ; initPage ( control ) ; } private void initPage ( Composite control ) { GridLayout baseLayout = new GridLayout ( ) ; baseLayout . numColumns = ; baseLayout . verticalSpacing = ; control . setLayout ( baseLayout ) ; initLabel ( control ) ; initExtractArea ( control ) ; } private void initExtractArea ( Composite control ) { Group queryGroup = initGroup ( control ) ; checkQuery = new Button ( queryGroup , SWT . CHECK ) ; checkQuery . setText ( Messages . InlineTempPage_ReplaceTempWithQuery ) ; checkQuery . setEnabled ( true ) ; newMethodName = new LabeledTextField ( queryGroup , Messages . InlineTempPage_NewMethodName ) ; GridData textData = new GridData ( GridData . FILL_HORIZONTAL ) ; newMethodName . setLayoutData ( textData ) ; createSelectionListener ( checkQuery , newMethodName ) ; createModifyListener ( newMethodName . getText ( ) ) ; } private void createModifyListener ( final Text newMethodName ) { newMethodName . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { String newName = newMethodName . getText ( ) ; config . setNewMethodName ( newName ) ; checkInput ( newName ) ; } private void checkInput ( String newName ) { if ( NameValidator . isValidMethodName ( newName ) ) { InlineLocalPage . this . setMessage ( null ) ; InlineLocalPage . this . setPageComplete ( true ) ; } else { InlineLocalPage . this . setMessage ( "" + newName + Messages . InlineTempPage_IsNotValidName , ConvertLocalToFieldPage . ERROR ) ; InlineLocalPage . this . setPageComplete ( false ) ; } } } ) ; } private void createSelectionListener ( final Button checkQuery , final LabeledTextField newMethodName ) { checkQuery . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { boolean doReplaceTempWithQuery = checkQuery . getSelection ( ) ; newMethodName . setEnabled ( doReplaceTempWithQuery ) ; config . setReplaceTempWithQuery ( doReplaceTempWithQuery ) ; if ( ! doReplaceTempWithQuery ) { setMessage ( null ) ; } setPageComplete ( ! doReplaceTempWithQuery ) ; } } ) ; } private Group initGroup ( Composite control ) { Group queryGroup = new Group ( control , SWT . NONE ) ; queryGroup . setText ( Messages . InlineTempPage_ExtractToMethod ) ; GridLayout groupLayout = new GridLayout ( ) ; groupLayout . numColumns = ; groupLayout . verticalSpacing = ; queryGroup . setLayout ( groupLayout ) ; GridData groupData = new GridData ( GridData . FILL_HORIZONTAL ) ; queryGroup . setLayoutData ( groupData ) ; return queryGroup ; } private void initLabel ( Composite control ) { Label infoLabel = new Label ( control , SWT . NONE ) ; infoLabel . setText ( Messages . InlineTempPage_Replace + occurencesCount + Messages . InlineTempPage_Occurences + selectedItemName + "" ) ; GridData layoutData = new GridData ( GridData . FILL_HORIZONTAL ) ; infoLabel . setLayoutData ( layoutData ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FormAttachment ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . rubypeople . rdt . refactoring . core . inlinemethod . IRemoveDeclaration ; public class InlineMethodPage extends RefactoringWizardPage { private static final int BORDER = ; private static final String NAME = Messages . InlineMethodPage_Name ; private final IRemoveDeclaration remover ; public InlineMethodPage ( IRemoveDeclaration remover ) { super ( NAME ) ; this . remover = remover ; setTitle ( NAME ) ; } public void createControl ( Composite parent ) { Composite body = new Composite ( parent , SWT . None ) ; body . setLayout ( new FormLayout ( ) ) ; Button button = new Button ( body , SWT . CHECK ) ; button . setText ( Messages . InlineMethodPage_DeleteDeclaration ) ; FormData variableNamesLayoutData = new FormData ( ) ; variableNamesLayoutData . top = new FormAttachment ( , , BORDER ) ; variableNamesLayoutData . left = new FormAttachment ( , , BORDER ) ; button . setLayoutData ( variableNamesLayoutData ) ; button . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event event ) { if ( ( ( Button ) event . widget ) . getSelection ( ) ) { setMessage ( Messages . InlineMethodPage_MakeSureIsntUsed , WARNING ) ; } else { setMessage ( null ) ; } remover . setRemove ( ( ( Button ) event . widget ) . getSelection ( ) ) ; } } ) ; setControl ( body ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; public class ConverterPageParameters { private boolean inCurrentMethodRadioEnabled = true ; private boolean inClassConstructorRadioEnabled = true ; private boolean deaclareAsClassFieldEnabled = true ; public ConverterPageParameters ( boolean inCurrentMethodRadioEnabled , boolean inClassConstructorRadioEnabled , boolean deaclareAsClassField ) { this . inCurrentMethodRadioEnabled = inCurrentMethodRadioEnabled ; this . inClassConstructorRadioEnabled = inClassConstructorRadioEnabled ; this . deaclareAsClassFieldEnabled = deaclareAsClassField ; } public ConverterPageParameters ( ) { } public boolean isDeaclareAsClassField ( ) { return deaclareAsClassFieldEnabled ; } public void setDeaclareAsClassField ( boolean deaclareAsClassField ) { this . deaclareAsClassFieldEnabled = deaclareAsClassField ; } public boolean isInClassConstructorRadioEnabled ( ) { return inClassConstructorRadioEnabled ; } public void setInClassConstructorRadioEnabled ( boolean inClassConstructorRadioEnabled ) { this . inClassConstructorRadioEnabled = inClassConstructorRadioEnabled ; } public boolean isInCurrentMethodRadioEnabled ( ) { return inCurrentMethodRadioEnabled ; } public void setInCurrentMethodRadioEnabled ( boolean inCurrentMethodRadioEnabled ) { this . inCurrentMethodRadioEnabled = inCurrentMethodRadioEnabled ; } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import java . util . Observable ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; public abstract class ParametersButtonListener extends Observable implements Listener { protected final Table table ; public ParametersButtonListener ( Table table ) { this . table = table ; } public void handleEvent ( Event event ) { TableItem [ ] tableItems = table . getSelection ( ) ; if ( tableItems == null || tableItems . length < ) { return ; } assert ( tableItems . length == ) ; if ( tableItems [ ] instanceof MethodArgumentTableItem ) { buttonPressed ( ( MethodArgumentTableItem ) tableItems [ ] , table . getSelectionIndex ( ) ) ; setChanged ( ) ; notifyObservers ( ) ; } } abstract protected void buttonPressed ( MethodArgumentTableItem item , int position ) ; } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import java . util . Iterator ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractedMethodHelper ; public class SignatureObserver implements Observer { private final Label signatureLabel ; private final ExtractedMethodHelper methodHelper ; public SignatureObserver ( Label signatureLabel , ExtractedMethodHelper methodHelper ) { this . signatureLabel = signatureLabel ; this . methodHelper = methodHelper ; setPreviewText ( ) ; } public void update ( Observable observable , Object object ) { setPreviewText ( ) ; } private void setPreviewText ( ) { if ( "" . equals ( methodHelper . getMethodName ( ) ) ) { return ; } StringBuilder string = new StringBuilder ( "" + methodHelper . getMethodName ( ) + '' ) ; Iterator < String > it = methodHelper . getArguments ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { string . append ( it . next ( ) ) ; if ( it . hasNext ( ) ) { string . append ( "" ) ; } } signatureLabel . setText ( string . toString ( ) ) ; } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String ExtractMethodComposite_AccessModifier ; public static String ExtractMethodComposite_ButtonDown ; public static String ExtractMethodComposite_ButtonEdit ; public static String ExtractMethodComposite_ButtonUp ; public static String ExtractMethodComposite_ExpansionHint ; public static String ExtractMethodComposite_MethodName ; public static String ExtractMethodComposite_Name ; public static String ExtractMethodComposite_Parameters ; public static String ExtractMethodComposite_ReplaceAll ; public static String ExtractMethodComposite_SameAsSource ; public static String ExtractMethodComposite_SelectedCode ; public static String ExtractMethodComposite_SignaturePreview ; public static String MethodNameListener_IsNotValidName ; public static String ParametersTableCellEditorListener_CannotHaveParametersWithEqualNames ; public static String ParametersTableCellEditorListener_IsAlreadyUsed ; public static String ParametersTableCellEditorListener_IsNotValidParameterName ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . layout . FormAttachment ; import org . eclipse . swt . layout . FormData ; import org . eclipse . swt . layout . FormLayout ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . layout . RowLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . rubypeople . rdt . refactoring . ui . LabeledTextField ; import org . rubypeople . rdt . refactoring . ui . RdtCodeViewer ; public class ExtractMethodComposite extends Composite { private Group accessModifierGroup ; private Composite modifySelectionEditorComposite ; private Label modifySelectionLabel ; private Button privateAccessRadioButton ; private Button protectedAccessRadioButton ; private Button publicAccessRadioButton ; private Label methodSignaturePreviewLabel ; private Label methodSignatureLabel ; private Button replaceAllCheckbox ; private Label parametersLabel ; private Button editParametersButton ; private TableColumn parametersTableNameColumns ; private Table parametersTable ; private Button downParametersButton ; private Button upParametersButton ; private LabeledTextField newMethodName ; private RdtCodeViewer selectionPreview ; private final IValidationController validationController ; private ParametersTableCellEditorListener cellEditorListener ; private Button noneAccessRadioButton ; public ExtractMethodComposite ( Composite parent , IValidationController validationController , boolean hasParameters , boolean needsAccessModifiers ) { super ( parent , SWT . NONE ) ; this . validationController = validationController ; setLayout ( new GridLayout ( ) ) ; createNewMethodNameComposite ( this ) ; if ( needsAccessModifiers ) { createAccessModifierComposite ( this ) ; } if ( hasParameters ) { createParametersComposite ( this ) ; } createMethodSignatureComposite ( this ) ; createModifySelectionComposite ( this ) ; layout ( ) ; } public LabeledTextField getNewMethodNameText ( ) { return newMethodName ; } private void createModifySelectionComposite ( Composite control ) { Composite modifySelectionComposite = new Composite ( control , SWT . FLAT ) ; GridLayout compositeLayout = new GridLayout ( ) ; compositeLayout . makeColumnsEqualWidth = true ; GridData compositeLData = new GridData ( ) ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessHorizontalSpace = true ; compositeLData . grabExcessVerticalSpace = true ; compositeLData . verticalAlignment = GridData . FILL ; modifySelectionComposite . setLayoutData ( compositeLData ) ; modifySelectionComposite . setLayout ( compositeLayout ) ; modifySelectionLabel = new Label ( modifySelectionComposite , SWT . NONE ) ; GridData labelLData = new GridData ( ) ; labelLData . verticalAlignment = GridData . BEGINNING ; modifySelectionLabel . setLayoutData ( labelLData ) ; modifySelectionLabel . setText ( Messages . ExtractMethodComposite_SelectedCode ) ; modifySelectionEditorComposite = new Composite ( modifySelectionComposite , SWT . NONE ) ; FormLayout composite8Layout = new FormLayout ( ) ; GridData composite8LData = new GridData ( ) ; composite8LData . horizontalAlignment = GridData . FILL ; composite8LData . grabExcessHorizontalSpace = true ; composite8LData . grabExcessVerticalSpace = true ; composite8LData . verticalAlignment = GridData . FILL ; modifySelectionEditorComposite . setLayoutData ( composite8LData ) ; modifySelectionEditorComposite . setLayout ( composite8Layout ) ; selectionPreview = RdtCodeViewer . create ( modifySelectionEditorComposite ) ; FormData textLData = new FormData ( , ) ; textLData . right = new FormAttachment ( , , ) ; textLData . left = new FormAttachment ( , , ) ; textLData . top = new FormAttachment ( , , ) ; textLData . bottom = new FormAttachment ( , , ) ; selectionPreview . getTextWidget ( ) . setLayoutData ( textLData ) ; Composite modifySelectionButtonComposite = new Composite ( modifySelectionEditorComposite , SWT . NONE ) ; GridLayout composite9Layout = new GridLayout ( ) ; composite9Layout . makeColumnsEqualWidth = true ; composite9Layout . marginHeight = ; FormData composite9LData = new FormData ( ) ; composite9LData . width = ; composite9LData . right = new FormAttachment ( , , ) ; composite9LData . top = new FormAttachment ( , , ) ; composite9LData . bottom = new FormAttachment ( , , ) ; modifySelectionButtonComposite . setLayoutData ( composite9LData ) ; modifySelectionButtonComposite . setLayout ( composite9Layout ) ; Label selectionHelpLabel = new Label ( modifySelectionComposite , SWT . NONE ) ; GridData labelData = new GridData ( ) ; labelData . verticalAlignment = GridData . BEGINNING ; selectionHelpLabel . setLayoutData ( labelData ) ; FontData fontData = selectionHelpLabel . getFont ( ) . getFontData ( ) [ ] ; Font font = new Font ( getFont ( ) . getDevice ( ) , fontData . getName ( ) , fontData . getHeight ( ) , fontData . getStyle ( ) | SWT . ITALIC ) ; selectionHelpLabel . setFont ( font ) ; selectionHelpLabel . setText ( Messages . ExtractMethodComposite_ExpansionHint ) ; } private Button createButton ( Composite parent , String name ) { Button button = new Button ( parent , SWT . PUSH | SWT . CENTER ) ; GridData buttonLData = new GridData ( ) ; buttonLData . horizontalAlignment = GridData . FILL ; buttonLData . grabExcessHorizontalSpace = true ; button . setLayoutData ( buttonLData ) ; button . setText ( name ) ; return button ; } private void createMethodSignatureComposite ( Composite control ) { Composite methodSignatureComposite = new Composite ( control , SWT . NONE ) ; GridLayout compositeLayout = new GridLayout ( ) ; compositeLayout . makeColumnsEqualWidth = true ; GridData compositeLData = new GridData ( ) ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessHorizontalSpace = true ; methodSignatureComposite . setLayoutData ( compositeLData ) ; methodSignatureComposite . setLayout ( compositeLayout ) ; methodSignatureLabel = new Label ( methodSignatureComposite , SWT . NONE ) ; GridData labelLData = new GridData ( ) ; labelLData . horizontalAlignment = GridData . FILL ; labelLData . grabExcessHorizontalSpace = true ; methodSignatureLabel . setLayoutData ( labelLData ) ; methodSignatureLabel . setText ( Messages . ExtractMethodComposite_SignaturePreview ) ; methodSignaturePreviewLabel = new Label ( methodSignatureComposite , SWT . NONE ) ; GridData methodSignaturePreviewData = new GridData ( ) ; methodSignaturePreviewData . horizontalAlignment = GridData . FILL ; methodSignaturePreviewData . grabExcessHorizontalSpace = true ; methodSignaturePreviewData . verticalAlignment = GridData . FILL ; methodSignaturePreviewData . grabExcessVerticalSpace = true ; methodSignaturePreviewLabel . setLayoutData ( methodSignaturePreviewData ) ; methodSignaturePreviewLabel . setText ( "" ) ; } private void createParametersComposite ( Composite control ) { Composite parametersComposite = new Composite ( control , SWT . NONE ) ; GridLayout compositeLayout = new GridLayout ( ) ; compositeLayout . makeColumnsEqualWidth = true ; GridData compositeLData = new GridData ( ) ; compositeLData . grabExcessHorizontalSpace = true ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessVerticalSpace = true ; compositeLData . verticalAlignment = GridData . FILL ; parametersComposite . setLayoutData ( compositeLData ) ; parametersComposite . setLayout ( compositeLayout ) ; createParametersLabel ( parametersComposite ) ; createParametersTable ( parametersComposite ) ; replaceAllCheckbox = new Button ( parametersComposite , SWT . CHECK | SWT . LEFT ) ; GridData buttonLData = new GridData ( ) ; buttonLData . grabExcessHorizontalSpace = true ; buttonLData . horizontalAlignment = GridData . FILL ; replaceAllCheckbox . setLayoutData ( buttonLData ) ; replaceAllCheckbox . setText ( Messages . ExtractMethodComposite_ReplaceAll ) ; replaceAllCheckbox . setEnabled ( false ) ; } private void createParametersButton ( Composite parametersTableComposite ) { Composite parametersButtonComposite = new Composite ( parametersTableComposite , SWT . NONE ) ; GridLayout compositeLayout = new GridLayout ( ) ; compositeLayout . makeColumnsEqualWidth = true ; FormData compositeLData = new FormData ( , ) ; compositeLData . width = ; compositeLData . bottom = new FormAttachment ( , , ) ; compositeLData . right = new FormAttachment ( , , ) ; compositeLData . top = new FormAttachment ( , , ) ; parametersButtonComposite . setLayoutData ( compositeLData ) ; parametersButtonComposite . setLayout ( compositeLayout ) ; editParametersButton = createButton ( parametersButtonComposite , Messages . ExtractMethodComposite_ButtonEdit ) ; editParametersButton . setEnabled ( false ) ; upParametersButton = createButton ( parametersButtonComposite , Messages . ExtractMethodComposite_ButtonUp ) ; upParametersButton . setEnabled ( false ) ; downParametersButton = createButton ( parametersButtonComposite , Messages . ExtractMethodComposite_ButtonDown ) ; downParametersButton . setEnabled ( false ) ; } private Composite createParametersTable ( Composite parametersComposite ) { Composite parametersTableComposite = new Composite ( parametersComposite , SWT . NONE ) ; FormLayout compositeLayout = new FormLayout ( ) ; GridData compositeLData = new GridData ( ) ; compositeLData . grabExcessHorizontalSpace = true ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessVerticalSpace = true ; compositeLData . verticalAlignment = GridData . FILL ; parametersTableComposite . setLayoutData ( compositeLData ) ; parametersTableComposite . setLayout ( compositeLayout ) ; parametersTable = new Table ( parametersTableComposite , SWT . BORDER ) ; FormData tableLData = new FormData ( ) ; tableLData . bottom = new FormAttachment ( , , ) ; tableLData . left = new FormAttachment ( , , ) ; tableLData . right = new FormAttachment ( , , - ) ; tableLData . top = new FormAttachment ( , , ) ; parametersTable . setLayoutData ( tableLData ) ; parametersTable . setHeaderVisible ( true ) ; parametersTableNameColumns = new TableColumn ( parametersTable , SWT . NONE ) ; parametersTableNameColumns . setText ( Messages . ExtractMethodComposite_Name ) ; parametersTableNameColumns . setWidth ( ) ; createParametersButton ( parametersTableComposite ) ; cellEditorListener = new ParametersTableCellEditorListener ( parametersTable , validationController ) ; parametersTable . addListener ( SWT . MouseDoubleClick , cellEditorListener ) ; editParametersButton . addListener ( SWT . Selection , cellEditorListener ) ; return parametersTableComposite ; } private void createParametersLabel ( Composite parametersComposite ) { parametersLabel = new Label ( parametersComposite , SWT . NONE ) ; GridData labelLData = new GridData ( ) ; labelLData . grabExcessHorizontalSpace = true ; labelLData . horizontalAlignment = GridData . FILL ; parametersLabel . setLayoutData ( labelLData ) ; parametersLabel . setText ( Messages . ExtractMethodComposite_Parameters ) ; } private void createAccessModifierComposite ( Composite control ) { Composite accessModifierComposite = new Composite ( control , SWT . NONE ) ; FillLayout compositeLayout = new FillLayout ( SWT . HORIZONTAL ) ; GridData compositeLData = new GridData ( ) ; compositeLData . grabExcessHorizontalSpace = true ; compositeLData . horizontalAlignment = GridData . FILL ; accessModifierComposite . setLayoutData ( compositeLData ) ; accessModifierComposite . setLayout ( compositeLayout ) ; accessModifierGroup = new Group ( accessModifierComposite , SWT . SHADOW_NONE | SWT . NONE ) ; RowLayout groupLayout = new RowLayout ( SWT . HORIZONTAL ) ; groupLayout . fill = true ; accessModifierGroup . setLayout ( groupLayout ) ; accessModifierGroup . setText ( Messages . ExtractMethodComposite_AccessModifier ) ; publicAccessRadioButton = new Button ( accessModifierGroup , SWT . RADIO | SWT . LEFT ) ; publicAccessRadioButton . setText ( "" ) ; protectedAccessRadioButton = new Button ( accessModifierGroup , SWT . RADIO | SWT . LEFT ) ; protectedAccessRadioButton . setText ( "" ) ; privateAccessRadioButton = new Button ( accessModifierGroup , SWT . RADIO | SWT . LEFT ) ; privateAccessRadioButton . setText ( "" ) ; noneAccessRadioButton = new Button ( accessModifierGroup , SWT . RADIO | SWT . LEFT ) ; noneAccessRadioButton . setText ( Messages . ExtractMethodComposite_SameAsSource ) ; } private void createNewMethodNameComposite ( Composite control ) { Composite methodNameComposite = new Composite ( control , SWT . NONE ) ; FillLayout compositeLayout = new FillLayout ( SWT . HORIZONTAL ) ; GridData gridData = new GridData ( ) ; gridData . horizontalAlignment = GridData . FILL ; methodNameComposite . setLayoutData ( gridData ) ; methodNameComposite . setLayout ( compositeLayout ) ; newMethodName = new LabeledTextField ( methodNameComposite , Messages . ExtractMethodComposite_MethodName ) ; } public RdtCodeViewer getCodeViewer ( ) { return selectionPreview ; } public Table getParametersTable ( ) { return parametersTable ; } public Button getDownParametersButton ( ) { return downParametersButton ; } public Button getEditParametersButton ( ) { return editParametersButton ; } public Button getUpParametersButton ( ) { return upParametersButton ; } public ParametersTableCellEditorListener getCellEditorListener ( ) { return cellEditorListener ; } public Button getPrivateAccessRadioButton ( ) { return privateAccessRadioButton ; } public Button getProtectedAccessRadioButton ( ) { return protectedAccessRadioButton ; } public Button getPublicAccessRadioButton ( ) { return publicAccessRadioButton ; } public Label getMethodSignaturePreviewLabel ( ) { return methodSignaturePreviewLabel ; } public Button getNoneAccessRadioButton ( ) { return noneAccessRadioButton ; } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; public class ParameterTextChanged { private final String from ; private final String to ; private final int newPosition ; private final int originalPosition ; public String getFrom ( ) { return from ; } public String getTo ( ) { return to ; } public ParameterTextChanged ( int originalPosition , int newPosition , String from , String to ) { this . originalPosition = originalPosition ; this . newPosition = newPosition ; this . from = from ; this . to = to ; } public int getNewPosition ( ) { return newPosition ; } public int getOriginalPosition ( ) { return originalPosition ; } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; public class ButtonStateListener implements Observer , Listener { private final Table table ; private final Button upButton ; private final Button downButton ; private final Button editButton ; public ButtonStateListener ( Table table , Button upButton , Button downButton , Button editButton ) { this . table = table ; this . upButton = upButton ; this . downButton = downButton ; this . editButton = editButton ; } public void handleEvent ( Event event ) { setButtonStates ( ) ; } private void setButtonStates ( ) { TableItem [ ] tableItems = table . getSelection ( ) ; if ( tableItems == null || tableItems . length < ) { editButton . setEnabled ( false ) ; return ; } MethodArgumentTableItem item = ( MethodArgumentTableItem ) tableItems [ ] ; upButton . setEnabled ( true ) ; downButton . setEnabled ( true ) ; editButton . setEnabled ( true ) ; if ( item . isMoveable ( ) ) { if ( table . getSelectionIndex ( ) == ) { upButton . setEnabled ( false ) ; } if ( table . getSelectionIndex ( ) + == table . getItemCount ( ) ) { downButton . setEnabled ( false ) ; } MethodArgumentTableItem next = getNextItem ( table . getSelectionIndex ( ) ) ; if ( next != null && ! next . isMoveable ( ) ) { downButton . setEnabled ( false ) ; } } else { upButton . setEnabled ( false ) ; downButton . setEnabled ( false ) ; } } private MethodArgumentTableItem getNextItem ( int selected ) { if ( selected + >= table . getItemCount ( ) ) { return null ; } return ( MethodArgumentTableItem ) table . getItem ( selected + ) ; } public void update ( Observable arg0 , Object arg1 ) { setButtonStates ( ) ; } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import java . util . ArrayList ; public interface IValidationController { public void setComplete ( Object source , boolean complete ) ; public void setError ( String message ) ; public ArrayList < String > getInvalidNames ( ) ; } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import java . util . Observable ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . TableEditor ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class ParametersTableCellEditorListener extends Observable implements Listener { private final class TextListener implements Listener { private final MethodArgumentTableItem item ; private final Text text ; private TextListener ( MethodArgumentTableItem item , Text text ) { this . item = item ; this . text = text ; } public void handleEvent ( final Event e ) { if ( e . type == SWT . FocusOut ) { setNewName ( item , text ) ; text . dispose ( ) ; table . setFocus ( ) ; } else if ( e . type == SWT . Traverse ) { if ( e . detail == SWT . TRAVERSE_RETURN ) { setNewName ( item , text ) ; } if ( e . detail == SWT . TRAVERSE_RETURN || e . detail == SWT . TRAVERSE_ESCAPE ) { text . dispose ( ) ; e . doit = false ; } } } } private final Table table ; private final IValidationController validationController ; public ParametersTableCellEditorListener ( Table parametersTable , IValidationController validationController ) { this . table = parametersTable ; this . validationController = validationController ; } private boolean areAllNamesUnique ( ) { TableItem [ ] items = table . getItems ( ) ; boolean unique = true ; for ( int outer = ; outer < items . length ; outer ++ ) { for ( int inner = ; inner < items . length ; inner ++ ) { if ( outer == inner ) { continue ; } else if ( items [ outer ] . getText ( ) . equals ( items [ inner ] . getText ( ) ) ) { unique = false ; } } } return unique ; } private boolean areAllNamesValid ( StringBuilder message ) { TableItem [ ] items = table . getItems ( ) ; boolean valid = true ; for ( TableItem item : items ) { if ( ! NameValidator . isValidLocalVariableName ( item . getText ( ) ) ) { valid = false ; item . setBackground ( new Color ( table . getBackground ( ) . getDevice ( ) , , , ) ) ; message . append ( '' ) ; message . append ( item . getText ( ) ) ; message . append ( Messages . ParametersTableCellEditorListener_IsNotValidParameterName ) ; } else if ( nameAlreadyUsed ( item . getText ( ) ) ) { valid = false ; message . append ( '' ) ; message . append ( item . getText ( ) ) ; message . append ( Messages . ParametersTableCellEditorListener_IsAlreadyUsed ) ; } else { item . setBackground ( table . getBackground ( ) ) ; } } return valid ; } private boolean nameAlreadyUsed ( String name ) { return validationController . getInvalidNames ( ) . contains ( name ) ; } private void setNewName ( final MethodArgumentTableItem item , final Text text ) { String oldName = item . getItemName ( ) ; item . setItemName ( text . getText ( ) ) ; item . setText ( text . getText ( ) ) ; StringBuilder message = new StringBuilder ( ) ; if ( areAllNamesValid ( message ) ) { setChanged ( ) ; notifyObservers ( new ParameterTextChanged ( table . getSelectionIndex ( ) , table . getSelectionIndex ( ) , oldName , text . getText ( ) ) ) ; } if ( ! areAllNamesUnique ( ) ) { message . append ( Messages . ParametersTableCellEditorListener_CannotHaveParametersWithEqualNames ) ; } if ( message . toString ( ) . equals ( "" ) ) { validationController . setError ( null ) ; validationController . setComplete ( this , true ) ; } else { validationController . setError ( message . toString ( ) ) ; validationController . setComplete ( this , false ) ; } } public void handleEvent ( Event event ) { final TableEditor editor = new TableEditor ( table ) ; editor . horizontalAlignment = SWT . LEFT ; editor . grabHorizontal = true ; Rectangle clientArea = table . getClientArea ( ) ; Rectangle bounds = table . getSelection ( ) [ ] . getBounds ( ) ; Point pt = new Point ( bounds . x , bounds . y ) ; int index = table . getTopIndex ( ) ; while ( index < table . getItemCount ( ) ) { boolean visible = false ; final MethodArgumentTableItem item = ( MethodArgumentTableItem ) table . getItem ( index ) ; for ( int i = ; i < table . getColumnCount ( ) ; i ++ ) { Rectangle rect = item . getBounds ( i ) ; if ( rect . contains ( pt ) ) { final Text text = new Text ( table , SWT . NONE ) ; Listener textListener = new TextListener ( item , text ) ; text . addListener ( SWT . FocusOut , textListener ) ; text . addListener ( SWT . Traverse , textListener ) ; editor . setEditor ( text , item , i ) ; text . setText ( item . getText ( i ) ) ; text . selectAll ( ) ; text . setFocus ( ) ; return ; } if ( ! visible && rect . intersects ( clientArea ) ) { visible = true ; } } if ( ! visible ) { return ; } index ++ ; } } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import java . util . Observable ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . refactoring . core . extractmethod . MethodExtractor ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class MethodNameListener extends Observable implements ModifyListener { private final MethodExtractor extractor ; private final IValidationController validationController ; public MethodNameListener ( MethodExtractor extractor , IValidationController validationController ) { this . extractor = extractor ; this . validationController = validationController ; } public void modifyText ( ModifyEvent e ) { String name = ( ( Text ) e . widget ) . getText ( ) ; extractor . getExtractedMethod ( ) . setMethodName ( name ) ; checkInput ( name ) ; setChanged ( ) ; notifyObservers ( name ) ; } private void checkInput ( String name ) { if ( NameValidator . isValidMethodName ( name ) ) { validationController . setError ( null ) ; validationController . setComplete ( this , true ) ; } else { validationController . setError ( '' + name + Messages . MethodNameListener_IsNotValidName ) ; validationController . setComplete ( this , false ) ; } } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import org . eclipse . swt . widgets . Table ; public class ParametersButtonUpListener extends ParametersButtonListener { public ParametersButtonUpListener ( Table table ) { super ( table ) ; } @ Override protected void buttonPressed ( MethodArgumentTableItem item , int position ) { if ( position < ) { return ; } if ( item . isMoveable ( ) ) { table . remove ( position ) ; new MethodArgumentTableItem ( table , item . getItemName ( ) , true , item . getOriginalPosition ( ) , position - ) ; table . setSelection ( position - ) ; setChanged ( ) ; notifyObservers ( new ParameterTextChanged ( position , position - , item . getItemName ( ) , item . getItemName ( ) ) ) ; } } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import org . eclipse . swt . widgets . Table ; public class ParametersButtonDownListener extends ParametersButtonListener { public ParametersButtonDownListener ( Table table ) { super ( table ) ; } @ Override protected void buttonPressed ( MethodArgumentTableItem item , int position ) { if ( position + >= table . getItemCount ( ) ) { return ; } if ( item . isMoveable ( ) ) { table . remove ( position ) ; int newPosition = position + ; new MethodArgumentTableItem ( table , item . getItemName ( ) , true , item . getOriginalPosition ( ) , newPosition ) ; table . setSelection ( newPosition ) ; setChanged ( ) ; notifyObservers ( new ParameterTextChanged ( position , newPosition , item . getItemName ( ) , item . getItemName ( ) ) ) ; } } } package org . rubypeople . rdt . refactoring . ui . pages . extractmethod ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; public class MethodArgumentTableItem extends TableItem { private final boolean isMoveable ; private final int originalPosition ; private String name ; public MethodArgumentTableItem ( Table parent , String name , boolean isMoveable , int originalPosition , int position ) { super ( parent , SWT . NONE , position ) ; this . name = name ; this . isMoveable = isMoveable ; setText ( name ) ; this . originalPosition = originalPosition ; } @ Override protected void checkSubclass ( ) { } public boolean isMoveable ( ) { return isMoveable ; } public String getItemName ( ) { return name ; } public void setItemName ( String name ) { this . name = name ; } public int getOriginalPosition ( ) { return originalPosition ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Widget ; import org . rubypeople . rdt . refactoring . ui . ConstructorGenerationTree ; import org . rubypeople . rdt . refactoring . ui . util . SwtUtils ; public class ConstructorSelectionPage extends RefactoringWizardPage { private static final String title = Messages . ConstructorSelectionPage_SelectConstructor ; private ConstructorGenerationTree tree ; private ITreeContentProvider contentProvider ; public ConstructorSelectionPage ( ITreeContentProvider contentProvider ) { super ( title ) ; setTitle ( title ) ; this . contentProvider = contentProvider ; } public void createControl ( Composite parent ) { Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new FillLayout ( SWT . HORIZONTAL ) ) ; initTree ( c ) ; Composite c2 = new Composite ( c , SWT . NONE ) ; c2 . setLayout ( new FillLayout ( SWT . VERTICAL ) ) ; initExamples ( c2 ) ; setControl ( c ) ; } private ConstructorGenerationTree initTree ( Composite c ) { tree = new ConstructorGenerationTree ( c , contentProvider ) ; return tree ; } private Widget [ ] initExamples ( Composite c ) { Group emptyGroup = SwtUtils . initGroup ( c , Messages . ConstructorSelectionPage_EmptyConstructor ) ; Label emptyLable = SwtUtils . initLabel ( emptyGroup , Messages . ConstructorSelectionPage_EmptyConstructorCode ) ; Group paramGroup = SwtUtils . initGroup ( c , Messages . ConstructorSelectionPage_ParametrisedConstructor ) ; Label paramLabel = SwtUtils . initLabel ( paramGroup , Messages . ConstructorSelectionPage_ParametrisedConstructorCode ) ; return new Widget [ ] { emptyGroup , emptyLable , paramGroup , paramLabel } ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Listener ; import org . rubypeople . rdt . refactoring . ui . IErrorMessageGenerator ; import org . rubypeople . rdt . refactoring . ui . IErrorMessageReceiver ; import org . rubypeople . rdt . refactoring . ui . LabeledTextField ; public class RenamePage extends RefactoringWizardPage implements IErrorMessageReceiver { private static final String TITLE = Messages . RenamePage_Title ; private final String variableName ; private final Listener listener ; public RenamePage ( String name , IErrorMessageGenerator listener ) { this ( TITLE , name , listener ) ; } public RenamePage ( String title , String name , IErrorMessageGenerator listener ) { super ( title ) ; setTitle ( title ) ; variableName = name ; listener . setErrorReceiver ( this ) ; this . listener = listener ; } public void createControl ( Composite parent ) { LabeledTextField textField = createTextField ( parent ) ; setControl ( textField ) ; } protected LabeledTextField createTextField ( Composite parent ) { LabeledTextField textField = new LabeledTextField ( parent , Messages . RenamePage_NewName , variableName ) ; textField . getText ( ) . addListener ( SWT . Modify , listener ) ; return textField ; } public void setError ( String error ) { setErrorMessage ( error ) ; setPageComplete ( error == null ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . refactoring . core . overridemethod . MethodsOverrider ; import org . rubypeople . rdt . refactoring . ui . NotifiedContainerCheckedTree ; public class OverrideMethodSelectionPage extends RefactoringWizardPage { private static final String TITLE = Messages . OverrideMethodSelectionPage_SelectMethods ; private NotifiedContainerCheckedTree tree ; private MethodsOverrider methodsOverrider ; public OverrideMethodSelectionPage ( MethodsOverrider methodsOverrider ) { super ( TITLE ) ; setTitle ( TITLE ) ; this . methodsOverrider = methodsOverrider ; } public void createControl ( Composite parent ) { Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new FillLayout ( SWT . HORIZONTAL ) ) ; initTree ( c ) ; setControl ( c ) ; } private NotifiedContainerCheckedTree initTree ( Composite c ) { tree = new NotifiedContainerCheckedTree ( c , methodsOverrider , methodsOverrider ) ; return tree ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . refactoring . core . pushdown . MethodDownPusher ; import org . rubypeople . rdt . refactoring . ui . NotifiedContainerCheckedTree ; public class MethodDownPusherSelectionPage extends RefactoringWizardPage { private static final String TITLE = Messages . MethodDownPusherSelectionPage_Title ; private NotifiedContainerCheckedTree tree ; private MethodDownPusher methodDownPusher ; public MethodDownPusherSelectionPage ( MethodDownPusher methodDownPusher ) { super ( TITLE ) ; setTitle ( TITLE ) ; this . methodDownPusher = methodDownPusher ; } public void createControl ( Composite parent ) { Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new FillLayout ( SWT . HORIZONTAL ) ) ; initTree ( c ) ; setControl ( c ) ; } private NotifiedContainerCheckedTree initTree ( Composite c ) { tree = new NotifiedContainerCheckedTree ( c , methodDownPusher , methodDownPusher ) ; return tree ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Widget ; import org . rubypeople . rdt . refactoring . core . generateaccessors . AccessorsGenerator ; import org . rubypeople . rdt . refactoring . core . generateaccessors . GeneratedAccessor ; import org . rubypeople . rdt . refactoring . ui . NotifiedContainerCheckedTree ; import org . rubypeople . rdt . refactoring . ui . util . SwtUtils ; public class AccessorSelectionPage extends RefactoringWizardPage { private static final String title = Messages . AccessorSelectionPage_Title ; private NotifiedContainerCheckedTree tree ; private AccessorsGenerator accessorsGenerator ; private static final int DEFAULT_TYPE = GeneratedAccessor . DEFAULT_TYPE ; public AccessorSelectionPage ( AccessorsGenerator accessorsGenerator ) { super ( title ) ; setTitle ( title ) ; this . accessorsGenerator = accessorsGenerator ; } public void createControl ( Composite parent ) { Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new FillLayout ( SWT . HORIZONTAL ) ) ; initTree ( c ) ; Composite c2 = new Composite ( c , SWT . NONE ) ; c2 . setLayout ( new FillLayout ( SWT . VERTICAL ) ) ; initAccessorTypeSelection ( c2 ) ; initTypeExamples ( c2 ) ; setControl ( c ) ; } private Widget [ ] initTypeExamples ( Composite c ) { Group simpleGroup = SwtUtils . initGroup ( c , Messages . AccessorSelectionPage_SimpeAccessor ) ; Label simpleLable = SwtUtils . initLabel ( simpleGroup , Messages . AccessorSelectionPage_ExampleSimpleAccessor ) ; Group methodGroup = SwtUtils . initGroup ( c , Messages . AccessorSelectionPage_AccessorMethod ) ; Label methodLabel = SwtUtils . initLabel ( methodGroup , Messages . AccessorSelectionPage_ExampleAccessorMethod ) ; return new Widget [ ] { simpleGroup , simpleLable , methodGroup , methodLabel } ; } private NotifiedContainerCheckedTree initTree ( Composite c ) { tree = new NotifiedContainerCheckedTree ( c , accessorsGenerator , accessorsGenerator ) ; return tree ; } private Widget [ ] initAccessorTypeSelection ( Composite parent ) { Group g = new Group ( parent , SWT . NONE | SWT . VERTICAL ) ; g . setText ( Messages . AccessorSelectionPage_SelectType ) ; g . setBounds ( , , , ) ; Button simpleButton = initTypeButton ( Messages . AccessorSelectionPage_GenerateSimple , GeneratedAccessor . TYPE_SIMPLE_ACCESSOR , g , ) ; Button methodButton = initTypeButton ( Messages . AccessorSelectionPage_GenerateMethods , GeneratedAccessor . TYPE_METHOD_ACCESSOR , g , ) ; return new Widget [ ] { g , simpleButton , methodButton } ; } private Button initTypeButton ( String name , final int type , Group g , int y ) { Button button = new Button ( g , SWT . RADIO ) ; button . setText ( name ) ; button . setBounds ( , y , , ) ; button . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { setType ( type ) ; } } ) ; if ( type == DEFAULT_TYPE ) { setType ( type ) ; button . setSelection ( true ) ; } return button ; } protected void setType ( int type ) { accessorsGenerator . setType ( type ) ; tree . setInput ( "" ) ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . ltk . ui . refactoring . UserInputWizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . internal . refactoring . RefactoringMessages ; import org . rubypeople . rdt . refactoring . core . pullup . MethodUpPuller ; import org . rubypeople . rdt . refactoring . ui . NotifiedContainerCheckedTree ; public class MethodUpPullerSelectionPage extends UserInputWizardPage { private NotifiedContainerCheckedTree tree ; private MethodUpPuller methodUpPuller ; public MethodUpPullerSelectionPage ( MethodUpPuller methodUpPuller ) { super ( RefactoringMessages . PullUpMethod_Wizard_title ) ; setTitle ( RefactoringMessages . PullUpMethod_Wizard_title ) ; this . methodUpPuller = methodUpPuller ; } public void createControl ( Composite parent ) { Composite c = new Composite ( parent , SWT . NONE ) ; c . setLayout ( new FillLayout ( SWT . HORIZONTAL ) ) ; initTree ( c ) ; setControl ( c ) ; } private NotifiedContainerCheckedTree initTree ( Composite c ) { tree = new NotifiedContainerCheckedTree ( c , methodUpPuller , methodUpPuller ) ; return tree ; } } package org . rubypeople . rdt . refactoring . ui . pages ; import org . eclipse . jface . dialogs . IMessageProvider ; import org . eclipse . ltk . ui . refactoring . UserInputWizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . internal . refactoring . RefactoringMessages ; import org . rubypeople . rdt . refactoring . core . extractconstant . ConstantExtractor ; import org . rubypeople . rdt . refactoring . ui . LabeledTextField ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class ExtractConstantPage extends UserInputWizardPage { private ConstantExtractor extractor ; public ExtractConstantPage ( ConstantExtractor extractor ) { super ( RefactoringMessages . ExtractConstantWizard_defaultPageTitle ) ; setDescription ( RefactoringMessages . ExtractConstantInputPage_enter_name ) ; this . extractor = extractor ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . None ) ; setControl ( control ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . verticalSpacing = ; control . setLayout ( layout ) ; final LabeledTextField labeledText = new LabeledTextField ( control , RefactoringMessages . ExtractConstantInputPage_constant_name , extractor . getConstantName ( ) ) ; GridData layoutData = new GridData ( GridData . FILL_HORIZONTAL ) ; labeledText . setLayoutData ( layoutData ) ; labeledText . getText ( ) . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { String newName = labeledText . getText ( ) . getText ( ) ; extractor . setConstantName ( newName ) ; checkInput ( newName ) ; } private void checkInput ( String newName ) { if ( NameValidator . isValidConstantName ( newName ) ) { ExtractConstantPage . this . setMessage ( null ) ; ExtractConstantPage . this . setPageComplete ( true ) ; } else { ExtractConstantPage . this . setMessage ( RefactoringMessages . bind ( RefactoringMessages . ExtractConstantInputPage_invalid_name , newName ) , IMessageProvider . ERROR ) ; ExtractConstantPage . this . setPageComplete ( false ) ; } } } ) ; final Button replaceAllInstance = new Button ( control , SWT . CHECK ) ; GridData checkData = new GridData ( ) ; replaceAllInstance . setLayoutData ( checkData ) ; replaceAllInstance . setText ( RefactoringMessages . ExtractConstantInputPage_replace_all_occurrences ) ; replaceAllInstance . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { extractor . setReplaceAllInstances ( replaceAllInstance . getSelection ( ) ) ; } } ) ; } } package org . rubypeople . rdt . refactoring . ui ; public interface INewNameReceiver { void setNewName ( String name ) ; } package org . rubypeople . rdt . refactoring . ui ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTreeViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . swt . widgets . Composite ; public class ConstructorGenerationTree extends CheckboxTreeViewer { public ConstructorGenerationTree ( Composite parent , ITreeContentProvider contentProvider ) { super ( parent ) ; this . setAutoExpandLevel ( ) ; setContentProvider ( contentProvider ) ; setInput ( "" ) ; addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { handleItemChecked ( event . getChecked ( ) , event . getElement ( ) ) ; } } ) ; } protected void handleItemChecked ( boolean checked , Object element ) { if ( element instanceof CheckableItem ) { CheckableItem checkableItem = ( CheckableItem ) element ; setItemChecked ( checkableItem , checked ) ; if ( checkableItem . autoCheckParentOnCheck ( ) && checkableItem instanceof IParentProvider ) setParentChecked ( ( IParentProvider ) checkableItem ) ; if ( checkableItem . autoUncheckChildsOnUncheck ( ) && checkableItem instanceof IChildrenProvider ) setChildrenUnchecked ( ( IChildrenProvider ) checkableItem ) ; } } protected void setItemChecked ( CheckableItem item , boolean checked ) { item . setChecked ( checked ) ; } protected void setChildrenUnchecked ( IChildrenProvider item ) { for ( Object attr : item . getChildren ( ) ) { setChecked ( attr , false ) ; setItemChecked ( ( CheckableItem ) attr , false ) ; } } protected void setParentChecked ( IParentProvider item ) { setChecked ( item . getParent ( ) , true ) ; setItemChecked ( ( CheckableItem ) item . getParent ( ) , true ) ; } } package org . rubypeople . rdt . refactoring . ui ; public abstract class CheckableItem { private boolean checked ; private boolean autoUncheckChildsOnUncheck ; private boolean autoCheckParentOnCheck ; public CheckableItem ( boolean checked , boolean autoCheckParentOnCheck , boolean autoUncheckChildsOnUncheck ) { this . checked = checked ; this . autoCheckParentOnCheck = autoCheckParentOnCheck ; this . autoUncheckChildsOnUncheck = autoUncheckChildsOnUncheck ; } public void setChecked ( boolean checked ) { this . checked = checked ; } public boolean isChecked ( ) { return checked ; } public boolean autoUncheckChildsOnUncheck ( ) { return autoUncheckChildsOnUncheck ; } public boolean autoCheckParentOnCheck ( ) { return autoCheckParentOnCheck ; } } package org . rubypeople . rdt . refactoring . ui ; public interface IErrorMessageReceiver { void setError ( String error ) ; } package org . rubypeople . rdt . refactoring . ui ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String NewNameListener_AlreadyInUse ; public static String NewNameListener_IsNotValid ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . ui ; public interface ICheckboxListener { void setChecked ( boolean checked ) ; } package org . rubypeople . rdt . refactoring . ui ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; public class LabeledTextField extends Composite { private Text textField ; private Label label ; public LabeledTextField ( Composite parent , String labelName , String textContent ) { super ( parent , SWT . None ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; setLayout ( layout ) ; label = new Label ( this , SWT . NONE ) ; label . setText ( labelName ) ; label . setLayoutData ( new GridData ( ) ) ; textField = new Text ( this , SWT . BORDER | SWT . SINGLE ) ; textField . setText ( textContent ) ; textField . selectAll ( ) ; GridData textData = new GridData ( GridData . FILL_HORIZONTAL ) ; textData . grabExcessHorizontalSpace = true ; textField . setLayoutData ( textData ) ; } public LabeledTextField ( Composite parent , String labelName ) { this ( parent , labelName , "" ) ; } public Text getText ( ) { return textField ; } @ Override public void setEnabled ( boolean enabled ) { label . setEnabled ( enabled ) ; textField . setEnabled ( enabled ) ; } } package org . rubypeople . rdt . refactoring . ui ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . dialogs . ContainerCheckedTreeViewer ; public class NotifiedContainerCheckedTree extends ContainerCheckedTreeViewer { public NotifiedContainerCheckedTree ( Composite parent , ITreeContentProvider contentProvider , final IItemSelectionReceiver receiver ) { super ( parent ) ; this . setAutoExpandLevel ( ) ; setContentProvider ( contentProvider ) ; setInput ( "" ) ; addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { receiver . setSelectedItems ( getCheckedElements ( ) ) ; } } ) ; } } package org . rubypeople . rdt . refactoring . core . renamefield ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . CallNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . FieldCallItem ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . FieldItem ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; public class InstVarAccessesFinder { public static Collection < FieldItem > find ( IDocumentProvider document , String selectedName ) { ArrayList < FieldItem > fieldCallNodes = new ArrayList < FieldItem > ( ) ; Collection < Node > allNodes = document . getAllNodes ( ) ; for ( Node currentNode : allNodes ) { if ( isPossibleCall ( currentNode , document , selectedName ) ) { fieldCallNodes . add ( new FieldCallItem ( ( CallNode ) currentNode ) ) ; } } return fieldCallNodes ; } private static boolean isPossibleCall ( Node candidateNode , IDocumentProvider document , String selectedName ) { if ( ( candidateNode instanceof CallNode ) ) { CallNode callNode = ( CallNode ) candidateNode ; if ( callNode . getName ( ) . replaceAll ( "" , "" ) . equals ( selectedName ) ) { String fileName = callNode . getPosition ( ) . getFile ( ) ; Node rootNode = document . getRootNode ( fileName ) ; try { SelectionNodeProvider . getSelectedClassNode ( rootNode , callNode . getPosition ( ) . getStartOffset ( ) ) ; } catch ( NoClassNodeException e ) { return true ; } } } return false ; } } package org . rubypeople . rdt . refactoring . core . renamefield ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . FieldItem ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; public class FieldRenameEditProvider extends ReplaceEditProvider { private FieldItem fieldItem ; private String newName ; private ISourcePosition position ; public FieldRenameEditProvider ( FieldItem fieldItem , String newName ) { super ( false ) ; this . fieldItem = fieldItem ; this . newName = newName ; this . position = fieldItem . getFieldNode ( ) . getPositionIncludingComments ( ) ; } @ Override protected int getOffsetLength ( ) { return position . getEndOffset ( ) - position . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return fieldItem . getRenamedNode ( newName ) ; } @ Override protected int getOffset ( String document ) { return position . getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . renamefield ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . FieldItem ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class RenameFieldConditionChecker extends RefactoringConditionChecker { public static final String DEFAULT_ERROR = Messages . RenameFieldConditionChecker_NoFieldAtCaretPosition ; private RenameFieldConfig config ; private RootNode rootNode ; public RenameFieldConditionChecker ( RenameFieldConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( RenameFieldConfig ) configObj ; config . setDocProvider ( new DocumentWithIncluding ( config . getDocumentProvider ( ) ) ) ; rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; try { ClassNodeWrapper enclosingClassNode = SelectionNodeProvider . getSelectedClassNode ( rootNode , config . getCaretPosition ( ) ) ; ClassNodeProvider classNodeProvider = new IncludedClassesProvider ( config . getDocumentProvider ( ) ) ; config . setWholeClassNode ( classNodeProvider . getClassNode ( enclosingClassNode . getName ( ) ) ) ; config . setFieldProvider ( new FieldProvider ( config . getWholeClassNode ( ) , config . getDocumentProvider ( ) ) ) ; config . setSelectedItem ( config . getFieldProvider ( ) . getNameAtPosition ( config . getCaretPosition ( ) , config . getDocumentProvider ( ) . getActiveFileName ( ) ) ) ; if ( config . hasSelectedItem ( ) ) { config . setSelectedName ( config . getSelectedItem ( ) . getFieldName ( ) ) ; } } catch ( NoClassNodeException e ) { } if ( config . hasSelectedName ( ) ) { setSelection ( ) ; } } private void setSelection ( ) { String fieldName = config . getSelectedName ( ) ; boolean concernsClassField = config . concernsClassField ( ) ; Collection < FieldItem > selectedItems = config . getFieldProvider ( ) . getFieldItems ( fieldName , concernsClassField ) ; config . setSelectedCalls ( selectedItems ) ; Collection < FieldItem > possibleItems = new ArrayList < FieldItem > ( ) ; possibleItems . addAll ( selectedItems ) ; if ( ! concernsClassField ) { possibleItems . addAll ( InstVarAccessesFinder . find ( config . getDocumentProvider ( ) , config . getSelectedName ( ) ) ) ; } config . setPossibleCalls ( possibleItems ) ; } @ Override protected void checkFinalConditions ( ) { String newName = config . getNewName ( ) ; String selectedName = config . getSelectedName ( ) ; if ( newName == null || selectedName . equals ( newName ) ) { addError ( Messages . RenameFieldConditionChecker_NoNewName ) ; return ; } for ( String currentName : config . getFieldNames ( ) ) { if ( currentName . equals ( newName ) ) { addError ( Messages . RenameFieldConditionChecker_AlreadyExists ) ; return ; } } } @ Override protected void checkInitialConditions ( ) { Collection < FieldNodeWrapper > fields = PartialClassNodeWrapper . getFieldsFromNode ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ) ; FieldNodeWrapper selectedFieldNode = SelectionNodeProvider . getSelectedWrappedNode ( fields , config . getCaretPosition ( ) ) ; if ( config . getWholeClassNode ( ) == null ) { if ( selectedFieldNode != null ) { addError ( Messages . RenameFieldConditionChecker_CannotNoSurroundingClass ) ; return ; } } if ( ! config . hasSelectedName ( ) || ! isSelectionInFieldName ( selectedFieldNode ) ) { addError ( DEFAULT_ERROR ) ; } } private boolean isSelectionInFieldName ( FieldNodeWrapper node ) { return config . getCaretPosition ( ) <= node . getPosition ( ) . getStartOffset ( ) + node . getName ( ) . length ( ) ; } } package org . rubypeople . rdt . refactoring . core . renamefield ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String FieldProvider_RetrievedAsAttribute ; public static String FieldProvider_RetrievedAsField ; public static String FieldProvider_UnexpectedNodeOfType ; public static String RenameFieldConditionChecker_AlreadyExists ; public static String RenameFieldConditionChecker_CannotNoSurroundingClass ; public static String RenameFieldConditionChecker_NoFieldAtCaretPosition ; public static String RenameFieldConditionChecker_NoNewName ; public static String RenameFieldRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . renamefield ; import java . util . Collection ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . FieldItem ; import org . rubypeople . rdt . refactoring . core . renamemethod . MethodRenamer ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConfig ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiFileEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class FieldRenamer implements IMultiFileEditProvider { private RenameFieldConfig config ; public FieldRenamer ( RenameFieldConfig config ) { this . config = config ; } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { MultiFileEditProvider fileEdits = new MultiFileEditProvider ( ) ; for ( INodeWrapper currentItem : config . getSelectedCalls ( ) ) { String file = currentItem . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; FieldRenameEditProvider currentRenameProvider = new FieldRenameEditProvider ( ( FieldItem ) currentItem , config . getNewName ( ) ) ; fileEdits . addEditProvider ( new FileEditProvider ( file , currentRenameProvider ) ) ; } if ( config . doRenameAccessorMethods ( ) ) { addAccessorMethodRenamers ( fileEdits ) ; } return fileEdits . getFileEditProviders ( ) ; } private void addAccessorMethodRenamers ( MultiFileEditProvider fileEdits ) { ClassNodeWrapper wholeClass = config . getWholeClassNode ( ) ; Collection < MethodNodeWrapper > methods = wholeClass . getMethods ( ) ; for ( MethodNodeWrapper currentMethod : methods ) { ISourcePosition methodPosition = currentMethod . getWrappedNode ( ) . getPosition ( ) ; RenameMethodConfig methodConfig = new RenameMethodConfig ( config . getDocumentProvider ( ) , methodPosition . getStartOffset ( ) ) ; new RenameMethodConditionChecker ( methodConfig ) ; methodConfig . setRenameFields ( false ) ; if ( currentMethod . getName ( ) . equals ( config . getSelectedName ( ) ) ) { methodConfig . setNewName ( config . getNewName ( ) ) ; MethodRenamer methodRenamer = new MethodRenamer ( methodConfig ) ; addMethodEditProviders ( fileEdits , methodRenamer ) ; } else if ( currentMethod . getName ( ) . equals ( config . getSelectedName ( ) + '' ) ) { methodConfig . setNewName ( config . getNewName ( ) + "" ) ; MethodRenamer methodRenamer = new MethodRenamer ( methodConfig ) ; addMethodEditProviders ( fileEdits , methodRenamer ) ; } } } private void addMethodEditProviders ( MultiFileEditProvider fileEdits , MethodRenamer methodRenamer ) { Collection < FileMultiEditProvider > methodEdits = methodRenamer . getFileEditProviders ( ) ; for ( FileMultiEditProvider currentEditProvider : methodEdits ) { putEditProvider ( fileEdits , currentEditProvider ) ; } } private void putEditProvider ( MultiFileEditProvider fileEdits , FileMultiEditProvider multiEditProvider ) { String file = multiEditProvider . getFileName ( ) ; Collection < EditProvider > editProviders = multiEditProvider . getEditProviders ( ) ; for ( EditProvider currentEditProvider : editProviders ) { fileEdits . addEditProvider ( new FileEditProvider ( file , currentEditProvider ) ) ; } } } package org . rubypeople . rdt . refactoring . core . renamefield ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . LinkedHashMap ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . AttrFieldItem ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . ClassVarAsgnFieldItem ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . ClassVarFieldItem ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . FieldItem ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . InstAsgnFieldItem ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . InstVarFieldItem ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; public class FieldProvider { private ClassNodeWrapper classNode ; private Collection < ClassNodeWrapper > relatedClasses ; private LinkedHashMap < String , ArrayList < FieldItem > > fields ; private IDocumentProvider docProvider ; public FieldProvider ( ClassNodeWrapper classNode , IDocumentProvider docProvider ) { this . classNode = classNode ; this . fields = new LinkedHashMap < String , ArrayList < FieldItem > > ( ) ; this . docProvider = docProvider ; initRelatedClasses ( ) ; for ( ClassNodeWrapper currentClass : relatedClasses ) { initAttrs ( currentClass ) ; initAccessors ( currentClass ) ; initClassFields ( currentClass ) ; } } private void initRelatedClasses ( ) { relatedClasses = new ArrayList < ClassNodeWrapper > ( ) ; Collection < ClassNodeWrapper > itselfAndSuperclasses = docProvider . getProjectClassNodeProvider ( ) . getClassAndAllSuperClasses ( classNode ) ; relatedClasses . addAll ( itselfAndSuperclasses ) ; Collection < ClassNodeWrapper > subclasses = docProvider . getProjectClassNodeProvider ( ) . getSubClassesOf ( classNode . getName ( ) ) ; relatedClasses . addAll ( subclasses ) ; } private void initClassFields ( ClassNodeWrapper classWrapper ) { Collection < Node > allOccurences = classWrapper . getClassFieldOccurences ( ) ; for ( Node currentAttr : allOccurences ) { if ( currentAttr instanceof ClassVarNode ) { ClassVarNode classVar = ( ClassVarNode ) currentAttr ; if ( ! isVarSubNodeOfAsgn ( classVar , allOccurences , ClassVarAsgnNode . class ) ) { addClassVar ( classVar ) ; } } else if ( currentAttr instanceof ClassVarAsgnNode ) { addClassVarAsgn ( ( ClassVarAsgnNode ) currentAttr ) ; } else { System . out . println ( Messages . FieldProvider_UnexpectedNodeOfType + currentAttr . getClass ( ) + Messages . FieldProvider_RetrievedAsField + currentAttr . toString ( ) ) ; } } } private void addClassVarAsgn ( ClassVarAsgnNode classVarAsgnNode ) { String name = FieldItem . fieldName ( classVarAsgnNode . getName ( ) ) ; initNameList ( name ) ; ArrayList < FieldItem > fieldList = fields . get ( name ) ; fieldList . add ( new ClassVarAsgnFieldItem ( classVarAsgnNode ) ) ; } private void addClassVar ( ClassVarNode classVarNode ) { String name = FieldItem . fieldName ( classVarNode . getName ( ) ) ; initNameList ( name ) ; ArrayList < FieldItem > fieldList = fields . get ( name ) ; fieldList . add ( new ClassVarFieldItem ( classVarNode ) ) ; } private void initAccessors ( ClassNodeWrapper classWrapper ) { for ( AttrAccessorNodeWrapper currentAccessor : classWrapper . getAccessorNodes ( ) ) { String name = FieldItem . fieldName ( currentAccessor . getAttrName ( ) ) ; initNameList ( name ) ; ArrayList < FieldItem > itemList = fields . get ( name ) ; for ( FCallNode accessorPart : currentAccessor . getAccessorNodes ( ) ) { ArrayNode arrayNode = ( ArrayNode ) accessorPart . getArgsNode ( ) ; for ( Object actObj : arrayNode . childNodes ( ) ) { SymbolNode aktSymbol = ( SymbolNode ) actObj ; if ( name . equals ( aktSymbol . getName ( ) ) ) { itemList . add ( new AttrFieldItem ( aktSymbol ) ) ; } } } } } private void initAttrs ( ClassNodeWrapper classWrapper ) { Collection < Node > allOccurences = classWrapper . getInstFieldOccurences ( ) ; for ( Node currentAttr : allOccurences ) { if ( currentAttr instanceof SymbolNode ) { addAttr ( ( SymbolNode ) currentAttr ) ; } else if ( currentAttr instanceof InstVarNode ) { InstVarNode instVar = ( InstVarNode ) currentAttr ; if ( ! isVarSubNodeOfAsgn ( instVar , allOccurences , InstAsgnNode . class ) ) { addInstVar ( instVar ) ; } } else if ( currentAttr instanceof InstAsgnNode ) { addInstAsgn ( ( InstAsgnNode ) currentAttr ) ; } else { System . out . println ( Messages . FieldProvider_UnexpectedNodeOfType + currentAttr . getClass ( ) + Messages . FieldProvider_RetrievedAsAttribute + currentAttr . toString ( ) ) ; } } } private boolean isVarSubNodeOfAsgn ( Node instVar , Collection < Node > allNodes , Class kind ) { for ( Node currentNode : allNodes ) { if ( currentNode . getClass ( ) . isAssignableFrom ( kind ) ) { if ( currentNode . getPosition ( ) . getFile ( ) . equals ( instVar . getPosition ( ) . getFile ( ) ) ) { if ( SelectionNodeProvider . nodeContainsPosition ( currentNode , instVar . getPosition ( ) . getStartOffset ( ) ) ) { return true ; } } } } return false ; } private void addInstAsgn ( InstAsgnNode currentAttr ) { String name = FieldItem . fieldName ( currentAttr . getName ( ) ) ; initNameList ( name ) ; ArrayList < FieldItem > fieldList = fields . get ( name ) ; fieldList . add ( new InstAsgnFieldItem ( currentAttr ) ) ; } private void addInstVar ( InstVarNode instVar ) { String name = FieldItem . fieldName ( instVar . getName ( ) ) ; initNameList ( name ) ; ArrayList < FieldItem > varList = fields . get ( name ) ; varList . add ( new InstVarFieldItem ( instVar ) ) ; } private void initNameList ( String name ) { if ( ! fields . containsKey ( name ) ) { fields . put ( name , new ArrayList < FieldItem > ( ) ) ; } } private void addAttr ( SymbolNode symbol ) { String name = FieldItem . fieldName ( symbol . getName ( ) ) ; initNameList ( name ) ; ArrayList < FieldItem > attrList = fields . get ( name ) ; attrList . add ( new AttrFieldItem ( symbol ) ) ; } public ArrayList < FieldItem > getFieldItems ( String fieldName , boolean concernsClassField ) { ArrayList < FieldItem > matchingItems = new ArrayList < FieldItem > ( ) ; for ( FieldItem currentItem : fields . get ( fieldName ) ) { if ( currentItem . concernsClassField ( ) == concernsClassField ) { matchingItems . add ( currentItem ) ; } } return matchingItems ; } public Collection < String > getFieldNames ( ) { HashSet < String > names = new HashSet < String > ( fields . keySet ( ) ) ; return names ; } public FieldItem getNameAtPosition ( int caretPosition , String fileName ) { for ( String currentName : fields . keySet ( ) ) { for ( FieldItem currentItem : fields . get ( currentName ) ) { if ( currentItem . getFieldNode ( ) . getPosition ( ) . getFile ( ) . equals ( fileName ) && SelectionNodeProvider . nodeContainsPosition ( currentItem . getFieldNode ( ) , caretPosition ) ) { return currentItem ; } } } return null ; } } package org . rubypeople . rdt . refactoring . core . renamefield ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . AttrFieldItem ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . FieldItem ; import org . rubypeople . rdt . refactoring . core . renamemethod . NodeSelector ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . ui . ICheckboxListener ; import org . rubypeople . rdt . refactoring . ui . INewNameReceiver ; public class RenameFieldConfig implements INewNameReceiver , ICheckboxListener , NodeSelector , IRefactoringConfig { private IDocumentProvider docProvider ; private int caretPosition ; private String newName ; private String selectedName ; private ClassNodeWrapper wholeClassNode ; private FieldProvider fieldProvider ; private boolean doRenameAccessorMethods ; private boolean doRenameAccessors = true ; private Collection < ? extends INodeWrapper > possibleCalls ; private Collection < ? extends INodeWrapper > selectedCalls ; private FieldItem selectedItem ; public RenameFieldConfig ( IDocumentProvider docProvider , int caretPosition ) { this . docProvider = docProvider ; this . caretPosition = caretPosition ; possibleCalls = new ArrayList < INodeWrapper > ( ) ; selectedCalls = new ArrayList < INodeWrapper > ( ) ; } public int getCaretPosition ( ) { return caretPosition ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public String getNewName ( ) { return newName ; } public void setNewName ( String newName ) { this . newName = newName ; } public String getSelectedName ( ) { return selectedName ; } public ClassNodeWrapper getWholeClassNode ( ) { return wholeClassNode ; } public Collection < String > getFieldNames ( ) { return fieldProvider . getFieldNames ( ) ; } public boolean hasSelectedName ( ) { return selectedName != null ; } public boolean hasWholeClassNode ( ) { return wholeClassNode != null ; } public FieldProvider getFieldProvider ( ) { return fieldProvider ; } public boolean doRenameAccessorMethods ( ) { return doRenameAccessorMethods ; } public void setDoRenameAccessorMethods ( boolean doRenameAccessorMethods ) { this . doRenameAccessorMethods = doRenameAccessorMethods ; } public void setChecked ( boolean checked ) { setDoRenameAccessorMethods ( checked ) ; } public boolean concernsClassField ( ) { return selectedItem . concernsClassField ( ) ; } public boolean hasSelectedItem ( ) { return selectedItem != null ; } public void setSelectedItem ( FieldItem selectedItem ) { this . selectedItem = selectedItem ; } public FieldItem getSelectedItem ( ) { return selectedItem ; } public Collection < ? extends INodeWrapper > getPossibleCalls ( ) { return possibleCalls ; } public Collection < ? extends INodeWrapper > getSelectedCalls ( ) { if ( doRenameAccessors ) { return selectedCalls ; } Collection < INodeWrapper > nodes = new ArrayList < INodeWrapper > ( ) ; for ( INodeWrapper wrapper : selectedCalls ) { if ( wrapper instanceof AttrFieldItem ) { continue ; } nodes . add ( wrapper ) ; } return nodes ; } public void setPossibleCalls ( Collection < ? extends INodeWrapper > possibleCalls ) { this . possibleCalls = possibleCalls ; } public void setSelectedCalls ( Collection < ? extends INodeWrapper > selectedCalls ) { this . selectedCalls = selectedCalls ; } public boolean isDoRenameAccessors ( ) { return doRenameAccessors ; } public void setDoRenameAccessors ( boolean doRenameAccessors ) { this . doRenameAccessors = doRenameAccessors ; } public void setDocProvider ( DocumentWithIncluding docProvider ) { this . docProvider = docProvider ; } public void setWholeClassNode ( ClassNodeWrapper wholeClassNode ) { this . wholeClassNode = wholeClassNode ; } public void setFieldProvider ( FieldProvider fieldProvider ) { this . fieldProvider = fieldProvider ; } public void setSelectedName ( String selectedName ) { this . selectedName = selectedName ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . renamefield ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . IValidator ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . ui . NewNameListener ; import org . rubypeople . rdt . refactoring . ui . pages . OccurenceReplaceSelectionPage ; import org . rubypeople . rdt . refactoring . ui . pages . RenameFieldPage ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class RenameFieldRefactoring extends RubyRefactoring { private static final class LocalVarNameValidator implements IValidator { public boolean isValid ( String test ) { return NameValidator . isValidLocalVariableName ( test ) ; } } public static final String NAME = Messages . RenameFieldRefactoring_Name ; private RenameFieldConfig config ; private RenameFieldConditionChecker checker ; private FieldRenamer renamer ; private NewNameListener nameListener ; private RenameFieldPage pageOne ; private OccurenceReplaceSelectionPage page ; public RenameFieldRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; config = new RenameFieldConfig ( new DocumentWithIncluding ( getDocumentProvider ( ) ) , selectionProvider . getCaretPosition ( ) ) ; checker = new RenameFieldConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { renamer = new FieldRenamer ( config ) ; setEditProvider ( renamer ) ; nameListener = new NewNameListener ( config , new LocalVarNameValidator ( ) , config . getFieldNames ( ) ) ; pageOne = new RenameFieldPage ( config . getSelectedName ( ) . replaceAll ( "" , "" ) , nameListener , config ) ; pages . add ( pageOne ) ; page = new OccurenceReplaceSelectionPage ( config , config . getDocumentProvider ( ) ) ; pages . add ( page ) ; } } } package org . rubypeople . rdt . refactoring . core . renamefield . fielditems ; import org . jruby . ast . CallNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; public class FieldCallItem extends FieldItem { private CallNode fieldCall ; public FieldCallItem ( CallNode fieldCall ) { this . fieldCall = fieldCall ; } @ Override public boolean concernsClassField ( ) { return false ; } @ Override public String getFieldName ( ) { return fieldCall . getName ( ) ; } @ Override public Node getFieldNode ( ) { return fieldCall ; } @ Override public Node getRenamedNode ( String newName ) { String adaptedName = getFieldName ( ) . endsWith ( "" ) ? newName + '' : newName ; return NodeFactory . createCallNode ( fieldCall . getReceiverNode ( ) , adaptedName , fieldCall . getArgsNode ( ) ) ; } } package org . rubypeople . rdt . refactoring . core . renamefield . fielditems ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; public abstract class FieldItem implements INodeWrapper { public abstract Node getFieldNode ( ) ; public abstract Node getRenamedNode ( String newName ) ; public abstract String getFieldName ( ) ; protected String setPrefixName ( String newName , String prefix ) { if ( newName . startsWith ( prefix ) ) { return newName ; } return prefix + newName ; } public static String fieldName ( String name ) { return name . replaceAll ( "" , "" ) ; } public abstract boolean concernsClassField ( ) ; public Node getWrappedNode ( ) { return getFieldNode ( ) ; } public String getName ( ) { return getFieldName ( ) ; } } package org . rubypeople . rdt . refactoring . core . renamefield . fielditems ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Node ; public class ClassVarAsgnFieldItem extends FieldItem { private ClassVarAsgnNode classVarAsgnNode ; public ClassVarAsgnFieldItem ( ClassVarAsgnNode classVarAsgnNode ) { this . classVarAsgnNode = classVarAsgnNode ; } @ Override public String getFieldName ( ) { return fieldName ( classVarAsgnNode . getName ( ) ) ; } @ Override public Node getFieldNode ( ) { return classVarAsgnNode ; } @ Override public Node getRenamedNode ( String newName ) { Node valueNode = classVarAsgnNode . getValueNode ( ) ; replaceNameInSubnodes ( valueNode , setPrefixName ( newName , "" ) ) ; return new ClassVarAsgnNode ( classVarAsgnNode . getPosition ( ) , setPrefixName ( newName , "" ) , classVarAsgnNode . getValueNode ( ) ) ; } private void replaceNameInSubnodes ( Node baseNode , String newName ) { if ( baseNode instanceof ClassVarNode ) { ( ( ClassVarNode ) baseNode ) . setName ( newName ) ; } for ( Object currentChild : baseNode . childNodes ( ) ) { replaceNameInSubnodes ( ( Node ) currentChild , newName ) ; } } @ Override public boolean concernsClassField ( ) { return true ; } } package org . rubypeople . rdt . refactoring . core . renamefield . fielditems ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; public class AccessorFieldItem extends FieldItem { private AttrAccessorNodeWrapper currentAccessor ; public AccessorFieldItem ( AttrAccessorNodeWrapper currentAccessor ) { this . currentAccessor = currentAccessor ; } @ Override public String getFieldName ( ) { return currentAccessor . getAttrName ( ) ; } @ Override public Node getFieldNode ( ) { return null ; } @ Override public Node getRenamedNode ( String newName ) { return null ; } @ Override public boolean concernsClassField ( ) { return false ; } } package org . rubypeople . rdt . refactoring . core . renamefield . fielditems ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Node ; public class ClassVarFieldItem extends FieldItem { private ClassVarNode classVarNode ; public ClassVarFieldItem ( ClassVarNode classVarNode ) { this . classVarNode = classVarNode ; } @ Override public String getFieldName ( ) { return fieldName ( classVarNode . getName ( ) ) ; } @ Override public Node getFieldNode ( ) { return classVarNode ; } @ Override public Node getRenamedNode ( String newName ) { return new ClassVarNode ( classVarNode . getPosition ( ) , setPrefixName ( newName , "" ) ) ; } @ Override public boolean concernsClassField ( ) { return true ; } } package org . rubypeople . rdt . refactoring . core . renamefield . fielditems ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; public class AttrFieldItem extends FieldItem { private SymbolNode symbol ; public AttrFieldItem ( SymbolNode symbol ) { this . symbol = symbol ; } @ Override public String getFieldName ( ) { return fieldName ( symbol . getName ( ) ) ; } @ Override public Node getFieldNode ( ) { return symbol ; } @ Override public Node getRenamedNode ( String newName ) { return new SymbolNode ( symbol . getPosition ( ) , newName ) ; } @ Override public boolean concernsClassField ( ) { return false ; } } package org . rubypeople . rdt . refactoring . core . renamefield . fielditems ; import java . util . ArrayList ; import java . util . List ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . Node ; public class InstAsgnFieldItem extends FieldItem { private InstAsgnNode instAsgnNode ; public InstAsgnFieldItem ( InstAsgnNode instAsgnNode ) { this . instAsgnNode = instAsgnNode ; } @ Override public String getFieldName ( ) { return fieldName ( instAsgnNode . getName ( ) ) ; } @ Override public Node getFieldNode ( ) { return instAsgnNode ; } @ Override public Node getRenamedNode ( String newName ) { Node valueNode = instAsgnNode . getValueNode ( ) ; replaceInstVars ( valueNode , setPrefixName ( newName , "" ) ) ; return new InstAsgnNode ( instAsgnNode . getPosition ( ) , setPrefixName ( newName , "" ) , valueNode ) ; } private void replaceInstVars ( Node valueNode , String newName ) { if ( valueNode instanceof InstVarNode ) { InstVarNode instVarNode = ( InstVarNode ) valueNode ; if ( instVarNode . getName ( ) . equals ( instAsgnNode . getName ( ) ) ) { ( ( InstVarNode ) valueNode ) . setName ( newName ) ; } } List childNodes ; if ( valueNode != null ) { childNodes = valueNode . childNodes ( ) ; } else { childNodes = new ArrayList < Object > ( ) ; } for ( Object currentChild : childNodes ) { replaceInstVars ( ( Node ) currentChild , newName ) ; } } @ Override public boolean concernsClassField ( ) { return false ; } } package org . rubypeople . rdt . refactoring . core . renamefield . fielditems ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . Node ; public class InstVarFieldItem extends FieldItem { private InstVarNode instVarNode ; public InstVarFieldItem ( InstVarNode instVarNode ) { this . instVarNode = instVarNode ; } @ Override public String getFieldName ( ) { return fieldName ( instVarNode . getName ( ) ) ; } @ Override public Node getFieldNode ( ) { return instVarNode ; } @ Override public Node getRenamedNode ( String newName ) { return new InstVarNode ( instVarNode . getPosition ( ) , setPrefixName ( newName , "" ) ) ; } @ Override public boolean concernsClassField ( ) { return false ; } } package org . rubypeople . rdt . refactoring . core ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . AttrAssignNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class SelectionNodeProvider { public static Node getEnclosingScope ( Node rootNode , Node from ) { return getEnclosingScope ( rootNode , from . getPosition ( ) . getStartOffset ( ) ) ; } public static Node getEnclosingScope ( Node rootNode , int where ) { return SelectionNodeProvider . getSelectedNodeOfType ( rootNode , where , MethodDefNode . class , ClassNode . class , RootNode . class , IterNode . class ) ; } public static Node getSelectedNodes ( Node rootNode , IRefactoringContext selection ) { Node enclosingNode = getEnclosingNode ( rootNode , selection , Node . class ) ; if ( enclosingNode == null ) return null ; BlockNode enclosingBlockNode = ( BlockNode ) getEnclosingNode ( rootNode , selection , BlockNode . class ) ; if ( enclosingBlockNode == null ) { return enclosingNode ; } Collection < Node > blockChildren = NodeProvider . getChildren ( enclosingBlockNode ) ; Node beginNode = getSelectedNodeOfType ( enclosingBlockNode , selection . getStartOffset ( ) , Node . class ) ; Node beginBlockChildNode = getEnclosingNode ( beginNode , blockChildren ) ; Node endNode = getSelectedNodeOfType ( enclosingBlockNode , selection . getEndOffset ( ) , Node . class ) ; Node endBlockChildNode = getEnclosingNode ( endNode , blockChildren ) ; Collection < Node > selectedNodes = getNodesFromTo ( beginBlockChildNode , endBlockChildNode , blockChildren ) ; if ( isNodeContainedInNode ( selectedNodes . toArray ( new Node [ selectedNodes . size ( ) ] ) [ ] , enclosingNode ) ) { BlockNode blockAroundSelected = NodeFactory . createBlockNode ( selectedNodes . toArray ( new Node [ ] ) ) ; blockAroundSelected . setPosition ( NodeFactory . unionPositions ( NodeProvider . unwrap ( beginBlockChildNode ) . getPosition ( ) , NodeProvider . unwrap ( endBlockChildNode ) . getPosition ( ) ) ) ; return blockAroundSelected ; } else if ( beginNode . equals ( endNode ) ) { return beginNode ; } return enclosingNode ; } public static boolean isNodeContainedInNode ( Node containedNode , Node containingNode ) { return ( nodeContainsPosition ( containingNode , containedNode . getPosition ( ) . getStartOffset ( ) ) && nodeContainsPosition ( containingNode , containedNode . getPosition ( ) . getEndOffset ( ) ) ) ; } private static Collection < Node > getNodesFromTo ( Node beginNode , Node endNode , Collection < Node > allNodes ) { Collection < Node > affectedNodes = new ArrayList < Node > ( ) ; boolean between = false ; for ( Node aktNode : allNodes ) { if ( aktNode . equals ( beginNode ) ) between = true ; if ( between ) { affectedNodes . add ( aktNode ) ; } if ( aktNode . equals ( endNode ) ) between = false ; } return affectedNodes ; } private static Node getEnclosingNode ( Node enclosedNode , Collection < Node > possibleEnclosingNodes ) { for ( Node aktNode : possibleEnclosingNodes ) { if ( nodeEnclosesNode ( aktNode , enclosedNode ) ) return aktNode ; } return null ; } public static boolean nodeEnclosesNode ( Node enclosingNode , Node enclosedNode ) { ISourcePosition enclosingPos = enclosingNode . getPosition ( ) ; ISourcePosition enclosedPos = enclosedNode . getPosition ( ) ; return ( enclosingPos . getStartOffset ( ) <= enclosedPos . getStartOffset ( ) && enclosingPos . getEndOffset ( ) >= enclosedPos . getEndOffset ( ) ) ; } public static Node getEnclosingNode ( Node rootNode , IRefactoringContext selection , Class ... classes ) { Collection < Node > enclosingNodes = getEnclosingNodes ( rootNode , selection , classes ) ; Node lastNode = null ; Node secondLastNode = null ; Node thirdLastNode = null ; for ( Node aktNode : enclosingNodes ) { thirdLastNode = secondLastNode ; secondLastNode = lastNode ; lastNode = aktNode ; } if ( thirdLastNode != null && sameStartPosAndIsVariableNode ( thirdLastNode , lastNode ) && hasSamePosAndIsSelfAsignment ( secondLastNode , thirdLastNode ) ) { return thirdLastNode ; } if ( secondLastNode != null && hasSamePosAndIsSelfAsignment ( lastNode , secondLastNode ) ) { return secondLastNode ; } return lastNode ; } private static boolean sameStartPosAndIsVariableNode ( Node firstNode , Node secondNode ) { Class [ ] classes = { LocalAsgnNode . class , LocalVarNode . class , DAsgnNode . class , DVarNode . class , InstAsgnNode . class , InstVarNode . class , ClassVarAsgnNode . class , ClassVarNode . class , GlobalAsgnNode . class , GlobalVarNode . class } ; boolean sameStart = firstNode . getPosition ( ) . getStartOffset ( ) == secondNode . getPosition ( ) . getStartOffset ( ) ; boolean isFirstNodeVarNode = NodeUtil . nodeAssignableFrom ( firstNode , classes ) ; boolean isSecondNodeVarNode = NodeUtil . nodeAssignableFrom ( secondNode , classes ) ; return sameStart && isFirstNodeVarNode && isSecondNodeVarNode ; } private static boolean hasSamePosAndIsSelfAsignment ( Node probablyCallNode , Node probablyAsgnNode ) { boolean sameStart = probablyCallNode . getPosition ( ) . getStartOffset ( ) == probablyAsgnNode . getPosition ( ) . getStartOffset ( ) ; boolean sameEnd = probablyCallNode . getPosition ( ) . getEndOffset ( ) == probablyAsgnNode . getPosition ( ) . getEndOffset ( ) ; boolean isAsgnNode = NodeUtil . nodeAssignableFrom ( probablyAsgnNode , LocalAsgnNode . class , DAsgnNode . class , InstAsgnNode . class , ClassVarAsgnNode . class ) ; boolean isCallNode = NodeUtil . nodeAssignableFrom ( probablyCallNode , CallNode . class , AttrAssignNode . class ) ; return sameStart && sameEnd && isCallNode && isAsgnNode ; } public static Collection < Node > getEnclosingNodes ( Node rootNode , IRefactoringContext selection , Class ... classes ) { Collection < Node > allNodes = NodeProvider . getAllNodes ( rootNode ) ; Collection < Node > enclosingStartNodes = getSelectedNodesOfType ( allNodes , selection . getStartOffset ( ) , classes ) ; Collection < Node > enclosingNodes = new ArrayList < Node > ( ) ; for ( Node aktNode : enclosingStartNodes ) { if ( nodeContainsPosition ( aktNode , selection . getEndOffset ( ) ) ) { enclosingNodes . add ( aktNode ) ; } else { break ; } } return enclosingNodes ; } public static Node getSelectedNodeOfType ( Node baseNode , int position , Class ... klasses ) { return getSelectedNodeOfType ( NodeProvider . getAllNodes ( baseNode ) , position , klasses ) ; } public static Node getSelectedNodeOfType ( Collection < ? extends Node > nodes , int position , Class ... klasses ) { return returnLast ( getSelectedNodesOfType ( nodes , position , klasses ) ) ; } private static Node returnLast ( Collection < Node > candidates ) { if ( candidates . size ( ) <= ) return null ; Node candidate = candidates . toArray ( new Node [ candidates . size ( ) ] ) [ ] ; for ( Node node : candidates ) { if ( node . getPosition ( ) . getEndOffset ( ) <= candidate . getPosition ( ) . getEndOffset ( ) ) { candidate = node ; } } return candidate ; } public static Collection < Node > getSelectedNodesOfType ( Collection < ? extends Node > nodes , int position , Class ... klasses ) { ArrayList < Node > candidates = new ArrayList < Node > ( ) ; for ( Node n : nodes ) { if ( n . equals ( NilImplicitNode . NIL ) ) continue ; if ( nodeContainsPosition ( n , position ) && ! ( n instanceof NewlineNode ) && NodeUtil . nodeAssignableFrom ( n , klasses ) ) { candidates . add ( n ) ; } } return candidates ; } public static Collection < Node > getSelectedNodesOfType ( Node baseNode , int position , Class ... klasses ) { return getSelectedNodesOfType ( NodeProvider . getAllNodes ( baseNode ) , position , klasses ) ; } public static boolean nodeContainsPosition ( Node n , int position ) { return ( position + CURSOR_TOLERANCE >= NodeUtil . subPositionUnion ( n ) . getStartOffset ( ) && position - CURSOR_TOLERANCE < NodeUtil . subPositionUnion ( n ) . getEndOffset ( ) ) ; } public static final int CURSOR_TOLERANCE = ; public static ClassNodeWrapper getSelectedClassNode ( Node rootNode , int position ) throws NoClassNodeException { Node enclosingClassNode = getSelectedNodeOfType ( rootNode , position , ClassNode . class ) ; PartialClassNodeWrapper partialClassNode = PartialClassNodeWrapper . getPartialClassNodeWrapper ( enclosingClassNode , rootNode ) ; ArrayList < ModuleNode > moduleNodes = new ArrayList < ModuleNode > ( ) ; Collection < Node > subNodes = NodeProvider . getSubNodes ( rootNode , ModuleNode . class ) ; for ( Node node : subNodes ) { if ( nodeContainsPosition ( node , position ) ) { moduleNodes . add ( ( ModuleNode ) node ) ; } } partialClassNode . setEnclosingModules ( moduleNodes ) ; return new ClassNodeWrapper ( partialClassNode ) ; } public static AttrAccessorNodeWrapper getSelectedAccessorNode ( Node baseNode , INameNode selectedAccessorNameNode ) { Collection < AttrAccessorNodeWrapper > accessorNodes = NodeProvider . getAccessorNodes ( baseNode ) ; String selectedName = selectedAccessorNameNode . getName ( ) ; if ( selectedName . charAt ( ) == '' ) { selectedName = selectedName . substring ( ) ; } AttrAccessorNodeWrapper selectedAccessor = null ; for ( AttrAccessorNodeWrapper aktAccessorNode : accessorNodes ) { if ( aktAccessorNode . getAttrName ( ) . equals ( selectedName ) ) { if ( selectedAccessor == null ) { selectedAccessor = aktAccessorNode ; } else { selectedAccessor . addAccessorType ( aktAccessorNode ) ; } } } return selectedAccessor ; } public static < T extends INodeWrapper > T getSelectedWrappedNode ( Collection < T > candidates , int caretPosition ) { T selected = null ; for ( T aktNode : candidates ) { if ( nodeContainsPosition ( aktNode . getWrappedNode ( ) , caretPosition ) ) { selected = getBestCandidate ( selected , aktNode ) ; } } return selected ; } private static < T extends INodeWrapper > T getBestCandidate ( T oldNode , T newNode ) { if ( oldNode == null ) { return newNode ; } if ( nodeEnclosesNode ( newNode . getWrappedNode ( ) , oldNode . getWrappedNode ( ) ) ) { return oldNode ; } return newNode ; } } package org . rubypeople . rdt . refactoring . core . generateaccessors ; import org . jruby . ast . DefnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterLastMethodInClassOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . BeforeFirstMethodInClassOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . OffsetProvider ; public class AccessorOffsetProvider extends OffsetProvider { private ClassNodeWrapper classNode ; private int type ; private String document ; public AccessorOffsetProvider ( ClassNodeWrapper classNode , int type , String document ) { super ( document ) ; this . document = document ; this . classNode = classNode ; this . type = type ; } @ Override public Node getInsertAfterNode ( ) { if ( NodeProvider . hasChildNode ( classNode . getFirstPartialClassNode ( ) . getClassBodyNode ( ) , DefnNode . class ) ) { if ( type == GeneratedAccessor . TYPE_SIMPLE_ACCESSOR ) { return getSimpleOffsetNode ( ) ; } return getMethodOffsetNode ( ) ; } return classNode . getFirstPartialClassNode ( ) . getClassBodyNode ( ) ; } private Node getMethodOffsetNode ( ) { AfterLastMethodInClassOffsetProvider afterLastMethodInClassOffsetProvider = new AfterLastMethodInClassOffsetProvider ( classNode , document ) ; return afterLastMethodInClassOffsetProvider . getInsertAfterNode ( ) ; } private Node getSimpleOffsetNode ( ) { OffsetProvider beforeFirstMethodInClassOffsetProvider = new BeforeFirstMethodInClassOffsetProvider ( classNode , document ) ; return beforeFirstMethodInClassOffsetProvider . getInsertAfterNode ( ) ; } } package org . rubypeople . rdt . refactoring . core . generateaccessors ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . BlockNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; public class GeneratedAccessor extends InsertEditProvider { public static final int TYPE_SIMPLE_ACCESSOR = ; public static final int TYPE_METHOD_ACCESSOR = ; public static final int DEFAULT_TYPE = TYPE_SIMPLE_ACCESSOR ; public String definitionName ; private int type ; private String attrName ; private ClassNodeWrapper classNode ; public GeneratedAccessor ( String definitionName , String instVarName , int type , ClassNodeWrapper classNode ) { super ( true ) ; this . definitionName = definitionName ; this . attrName = instVarName ; this . type = type ; this . classNode = classNode ; } public boolean isWriter ( ) { return definitionName . equals ( AttrAccessorNodeWrapper . ATTR_WRITER ) ; } public boolean isReader ( ) { return definitionName . equals ( AttrAccessorNodeWrapper . ATTR_READER ) ; } public boolean isAccessor ( ) { return definitionName . equals ( AttrAccessorNodeWrapper . ATTR_ACCESSOR ) ; } protected BlockNode getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = lastEditInGroup && ! isNextLineEmpty ( offset , document ) ; if ( type == TYPE_SIMPLE_ACCESSOR ) { return NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , getSimpleInsertNode ( ) ) ; } return NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , getMethodInsertNode ( ) ) ; } private Node getSimpleInsertNode ( ) { FCallNode accessorNode = NodeFactory . createSimpleAccessorNode ( definitionName , attrName ) ; return NodeFactory . createNewLineNode ( accessorNode ) ; } private Node [ ] getMethodInsertNode ( ) { Collection < Node > methodNodes = new ArrayList < Node > ( ) ; if ( isReader ( ) || isAccessor ( ) ) methodNodes . add ( NodeFactory . createGetterSetter ( attrName , false , VisibilityNodeWrapper . METHOD_VISIBILITY . PUBLIC ) ) ; if ( isAccessor ( ) ) { methodNodes . add ( NodeFactory . createNewLineNode ( null ) ) ; } if ( isWriter ( ) || isAccessor ( ) ) methodNodes . add ( NodeFactory . createGetterSetter ( attrName , true , VisibilityNodeWrapper . METHOD_VISIBILITY . PUBLIC ) ) ; return methodNodes . toArray ( new Node [ methodNodes . size ( ) ] ) ; } protected int getOffset ( String document ) { IOffsetProvider offsetProvider = new AccessorOffsetProvider ( classNode , type , document ) ; return offsetProvider . getOffset ( ) ; } public String getInstVarName ( ) { return attrName ; } } package org . rubypeople . rdt . refactoring . core . generateaccessors ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashSet ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . generateaccessors . AccessorsGenerator . TreeClass . TreeAttribute ; import org . rubypeople . rdt . refactoring . core . generateaccessors . AccessorsGenerator . TreeClass . TreeAttribute . TreeAccessor ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditAndTreeContentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . IItemSelectionReceiver ; public class AccessorsGenerator extends EditAndTreeContentProvider implements IItemSelectionReceiver { private Collection < TreeClass > classes ; private int type ; private Object [ ] selectedTreeItems ; public static final String WRITER = Messages . AccessorsGenerator_Writer ; public static final String READER = Messages . AccessorsGenerator_Reader ; public AccessorsGenerator ( DocumentProvider documentProvider , int type ) { this . type = type ; selectedTreeItems = new Object [ ] { } ; initTreeClasses ( documentProvider . getClassNodeProvider ( ) ) ; } protected void initTreeClasses ( ClassNodeProvider classNodeProvider ) { classes = new ArrayList < TreeClass > ( ) ; if ( classNodeProvider != null ) { for ( ClassNodeWrapper node : classNodeProvider . getAllClassNodes ( ) ) { classes . add ( new TreeClass ( node ) ) ; } } } public Object [ ] getElements ( Object inputElement ) { Collection < TreeClass > elements = new ArrayList < TreeClass > ( ) ; for ( TreeClass klass : classes ) { if ( klass . hasChildren ( ) ) elements . add ( klass ) ; } return elements . toArray ( ) ; } public void setType ( int type ) { this . type = type ; } public void setSelectedItems ( Object [ ] selected ) { this . selectedTreeItems = selected . clone ( ) ; } public Collection < EditProvider > getEditProviders ( ) { Collection < TreeAccessor > treeAccessors = getTreeAccessors ( ) ; LinkedHashSet < TreeAttribute > attribtes = getTreeAttributes ( treeAccessors ) ; Collection < EditProvider > generatedAccessors = getGeneratedAccessors ( attribtes ) ; return generatedAccessors ; } private Collection < EditProvider > getGeneratedAccessors ( LinkedHashSet < TreeAttribute > attribtes ) { Collection < EditProvider > providers = new ArrayList < EditProvider > ( ) ; for ( TreeAttribute attr : attribtes ) { providers . addAll ( attr . getGeneratedAccessors ( ) ) ; } return providers ; } private LinkedHashSet < TreeAttribute > getTreeAttributes ( Collection < TreeAccessor > treeAccessors ) { LinkedHashSet < TreeAttribute > attribtes = new LinkedHashSet < TreeAttribute > ( ) ; for ( TreeAccessor accessor : treeAccessors ) { setSelection ( accessor ) ; attribtes . add ( accessor . getAttribute ( ) ) ; } return attribtes ; } private void setSelection ( TreeAccessor accessor ) { if ( accessor . isReader ( ) ) accessor . getAttribute ( ) . setReaderSelected ( ) ; else if ( accessor . isWriter ( ) ) accessor . getAttribute ( ) . setWriterSelected ( ) ; } private Collection < TreeAccessor > getTreeAccessors ( ) { Collection < TreeAccessor > treeAccessors = new ArrayList < TreeAccessor > ( ) ; for ( Object o : selectedTreeItems ) { if ( o instanceof TreeAccessor ) { TreeAccessor accessor = ( ( TreeAccessor ) o ) ; accessor . getAttribute ( ) . clearSelection ( ) ; treeAccessors . add ( accessor ) ; } } return treeAccessors ; } public class TreeClass implements org . rubypeople . rdt . refactoring . ui . IChildrenProvider { private ClassNodeWrapper classNode ; private Collection < TreeAttribute > attrs ; private final Collection < AttrAccessorNodeWrapper > existingSimpleAccessorNodes ; private final Collection < MethodNodeWrapper > existingMethodAccessorNodes ; public TreeClass ( ClassNodeWrapper classNode ) { this . classNode = classNode ; existingSimpleAccessorNodes = classNode . getAccessorNodes ( ) ; existingMethodAccessorNodes = classNode . getMethods ( ) ; attrs = new ArrayList < TreeAttribute > ( ) ; for ( Node attrNode : classNode . getAttrNodes ( ) ) { attrs . add ( new TreeAttribute ( ( INameNode ) attrNode , classNode ) ) ; } } public String toString ( ) { return classNode . getName ( ) ; } public Object [ ] getChildren ( ) { Collection < TreeAttribute > children = new ArrayList < TreeAttribute > ( ) ; for ( TreeAttribute attr : attrs ) { if ( attr . hasChildren ( ) ) children . add ( attr ) ; } return children . toArray ( ) ; } public boolean hasChildren ( ) { for ( TreeAttribute attr : attrs ) { if ( attr . hasChildren ( ) ) return true ; } return false ; } public ClassNodeWrapper getClassNode ( ) { return classNode ; } public class TreeAttribute implements Comparable , org . rubypeople . rdt . refactoring . ui . IChildrenProvider { private ClassNodeWrapper classNode ; private TreeAccessor reader ; private TreeAccessor writer ; private boolean readerSelected ; private boolean writerSelected ; private String name ; public TreeAttribute ( INameNode node , ClassNodeWrapper classNode ) { this . classNode = classNode ; name = node . getName ( ) ; if ( name . indexOf ( '' ) == ) name = name . substring ( ) ; reader = new TreeAccessor ( name , true ) ; writer = new TreeAccessor ( name , false ) ; readerSelected = false ; writerSelected = false ; } public String toString ( ) { return name ; } public String getName ( ) { return name ; } public Object [ ] getChildren ( ) { return getChlidren ( ) . toArray ( ) ; } private Collection < TreeAccessor > getChlidren ( ) { Collection < TreeAccessor > accessors = new ArrayList < TreeAccessor > ( ) ; if ( ! existsSameAccessor ( reader , type ) ) accessors . add ( reader ) ; if ( ! existsSameAccessor ( writer , type ) ) accessors . add ( writer ) ; return accessors ; } private boolean existsSameAccessor ( TreeAccessor accessor , int type ) { if ( type == GeneratedAccessor . TYPE_SIMPLE_ACCESSOR ) { return existsSimpleAccessor ( accessor ) ; } return existsMethodAccessor ( accessor ) ; } private boolean existsSimpleAccessor ( TreeAccessor treeAccessor ) { for ( AttrAccessorNodeWrapper aktAccessorNode : existingSimpleAccessorNodes ) { if ( isSameSimpleAccessorType ( treeAccessor , aktAccessorNode ) ) { if ( aktAccessorNode . getAttrName ( ) . equals ( treeAccessor . getAttributeName ( ) ) ) { return true ; } } } return false ; } private boolean isSameSimpleAccessorType ( TreeAccessor accessor , AttrAccessorNodeWrapper node ) { return ( node . getAccessorTypeName ( ) . equals ( AttrAccessorNodeWrapper . ATTR_ACCESSOR ) ) || ( node . getAccessorTypeName ( ) . equals ( AttrAccessorNodeWrapper . ATTR_READER ) && accessor . isReader ( ) ) || ( node . getAccessorTypeName ( ) . equals ( AttrAccessorNodeWrapper . ATTR_WRITER ) && accessor . isWriter ( ) ) ; } private boolean existsMethodAccessor ( TreeAccessor accessor ) { for ( MethodNodeWrapper node : existingMethodAccessorNodes ) { if ( isSameReader ( accessor , node ) ) return true ; else if ( isSameWriter ( accessor , node ) ) return true ; } return false ; } private boolean isSameWriter ( TreeAccessor accessor , MethodNodeWrapper methodNode ) { if ( methodNode . getName ( ) . equals ( accessor . getAttributeName ( ) + '' ) && accessor . isWriter ( ) ) { ArgsNodeWrapper argsNode = methodNode . getArgsNode ( ) ; if ( argsNode . getArgsList ( ) . size ( ) == && argsNode . getOptArgs ( ) == null && argsNode . getBlockArgNode ( ) == null ) { String argName = argsNode . getArgsList ( ) . iterator ( ) . next ( ) ; if ( argName . equals ( accessor . getAttributeName ( ) ) ) return true ; } } return false ; } private boolean isSameReader ( TreeAccessor accessor , MethodNodeWrapper node ) { return node . getName ( ) . equals ( accessor . getAttributeName ( ) ) && accessor . isReader ( ) && ! node . getArgsNode ( ) . hasArgs ( ) ; } public boolean hasChildren ( ) { return ! getChlidren ( ) . isEmpty ( ) ; } public int compareTo ( Object arg0 ) { String thisStr = classNode . getName ( ) + name ; String otherStr ; if ( arg0 instanceof String ) { otherStr = ( String ) arg0 ; } else { TreeAttribute otherAttr = ( TreeAttribute ) arg0 ; ClassNodeWrapper otherClassNode = otherAttr . getTreeClass ( ) . getClassNode ( ) ; otherStr = otherClassNode . getName ( ) + otherAttr . toString ( ) ; } return thisStr . compareTo ( otherStr ) ; } public boolean equals ( Object o ) { return o != null && o instanceof TreeAttribute && compareTo ( o ) == ; } @ Override public int hashCode ( ) { return ; } public void clearSelection ( ) { readerSelected = false ; writerSelected = false ; } public void setReaderSelected ( ) { readerSelected = true ; } public void setWriterSelected ( ) { writerSelected = true ; } public TreeClass getTreeClass ( ) { return TreeClass . this ; } public Collection < EditProvider > getGeneratedAccessors ( ) { Collection < EditProvider > accessors = new ArrayList < EditProvider > ( ) ; if ( readerSelected && writerSelected ) accessors . add ( new GeneratedAccessor ( AttrAccessorNodeWrapper . ATTR_ACCESSOR , toString ( ) , type , classNode ) ) ; else if ( readerSelected ) accessors . add ( new GeneratedAccessor ( AttrAccessorNodeWrapper . ATTR_READER , toString ( ) , type , classNode ) ) ; else if ( writerSelected ) accessors . add ( new GeneratedAccessor ( AttrAccessorNodeWrapper . ATTR_WRITER , toString ( ) , type , classNode ) ) ; return accessors ; } public class TreeAccessor { private boolean isReader ; private String name ; public TreeAccessor ( String name , boolean isReader ) { this . name = name ; this . isReader = isReader ; } public String toString ( ) { return ( ( isReader ( ) ) ? READER : WRITER ) ; } public boolean isWriter ( ) { return ! isReader ; } public boolean isReader ( ) { return isReader ; } public String getAttributeName ( ) { return name ; } public TreeAttribute getAttribute ( ) { return TreeAttribute . this ; } } } } } package org . rubypeople . rdt . refactoring . core . generateaccessors ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String AccessorsGenerator_Reader ; public static String AccessorsGenerator_Writer ; public static String GenerateAccessorsRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . generateaccessors ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . AccessorSelectionPage ; public class GenerateAccessorsRefactoring extends RubyRefactoring { public static final String NAME = Messages . GenerateAccessorsRefactoring_Name ; public GenerateAccessorsRefactoring ( ) { super ( NAME ) ; AccessorsGenerator accessorsGenerator = new AccessorsGenerator ( getDocumentProvider ( ) , GeneratedAccessor . DEFAULT_TYPE ) ; setEditProvider ( accessorsGenerator ) ; pages . add ( new AccessorSelectionPage ( accessorsGenerator ) ) ; } } package org . rubypeople . rdt . refactoring . core ; import java . text . MessageFormat ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String RefactoringConditionChecker_EmptyDocument ; public static String RefactoringConditionChecker_SyntaxErrorInCurrent ; public static String RefactoringConditionChecker_SyntaxErrorInProject ; public static String RenameResourceChange_name ; public static String RenameResourceChange_does_not_exist ; public static String RenameResourceChange_rename_resource ; public static String DynamicValidationStateChange_workspace_changed ; public static String Change_is_unsaved ; public static String Change_is_read_only ; public static String Change_same_read_only ; public static String Change_has_modifications ; public static String Change_does_not_exist ; public static String deleteFile_deleting_resource ; public static String createFile_Create_file ; public static String CreateFileChange_error_unknownLocation ; public static String CreateFileChange_error_exists ; public static String createFile_creating_resource ; public static String deleteFile_Delete_File ; public static String RubyScriptChange_label ; public static String MultiStateRubyScriptChange_name_pattern ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } public static String format ( String message , Object object ) { return MessageFormat . format ( message , new Object [ ] { object } ) ; } public static String format ( String message , Object [ ] objects ) { return MessageFormat . format ( message , objects ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . extractmethod ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . extractconstant . MatchingNodesVisitor ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; public class MethodExtractor extends MultiEditProvider { private ExtractMethodConfig config ; private boolean replaceAll ; public MethodExtractor ( ExtractMethodConfig config ) { this . config = config ; } @ Override protected Collection < EditProvider > getEditProviders ( ) { Collection < EditProvider > providers = new ArrayList < EditProvider > ( ) ; if ( replaceAll ) { Node selection = config . getSelectedNodes ( ) ; Node rootNode = config . getRootNode ( ) ; MatchingNodesVisitor visitor = new MatchingNodesVisitor ( selection , config . getDocumentProvider ( ) . getActiveFileContent ( ) ) ; rootNode . accept ( visitor ) ; List < Node > matches = visitor . getMatches ( ) ; for ( Node node : matches ) { providers . add ( new ExtractedMethodCall ( node , config . getExtractMethodHelper ( ) . getMethodCallNode ( ) , rootNode ) ) ; } } else { providers . add ( new ExtractedMethodCall ( config ) ) ; } providers . add ( new ExtractedMethodDef ( config ) ) ; return providers ; } public EditProvider getDefEdit ( ) { return new ExtractedMethodDef ( config ) ; } public void setMethodName ( String name ) { config . getHelper ( ) . setMethodName ( name ) ; } public ExtractedMethodHelper getExtractedMethod ( ) { return config . getHelper ( ) ; } public void setReplaceAllInstances ( boolean selection ) { this . replaceAll = selection ; } } package org . rubypeople . rdt . refactoring . core . extractmethod ; import org . jruby . ast . BlockNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterNodeOffsetProvider ; public class ExtractedMethodDef extends InsertEditProvider { private ExtractedMethodHelper extractedMethodHelper ; private Node insertAfterNode ; public ExtractedMethodDef ( ExtractMethodConfig config ) { super ( true ) ; extractedMethodHelper = config . getHelper ( ) ; insertAfterNode = initInsertAfterNode ( config ) ; if ( insertAfterNode == null ) { setInsertType ( INSERT_AT_BEGIN_OF_LINE ) ; } } private Node initInsertAfterNode ( ExtractMethodConfig config ) { Node enclosingMethodNode = SelectionNodeProvider . getEnclosingNode ( config . getRootNode ( ) , config . getSelection ( ) , MethodDefNode . class ) ; if ( enclosingMethodNode != null ) { return enclosingMethodNode ; } Node enclosingBlockNode = SelectionNodeProvider . getEnclosingNode ( config . getRootNode ( ) , config . getSelection ( ) , BlockNode . class ) ; if ( enclosingBlockNode != null ) { Node firstSelectedNode = ( Node ) config . getSelectedNodes ( ) ; if ( ! firstSelectedNode . childNodes ( ) . isEmpty ( ) ) { firstSelectedNode = ( Node ) firstSelectedNode . childNodes ( ) . toArray ( ) [ ] ; } return NodeProvider . getNodeBefore ( enclosingBlockNode , firstSelectedNode ) ; } return null ; } @ Override protected Node getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = ! isNextLineEmpty ( offset , document ) ; boolean needsNewLineAtBeginOfBlock = ( insertAfterNode != null ) ; return extractedMethodHelper . getMethodNode ( needsNewLineAtBeginOfBlock , needsNewLineAtEndOfBlock ) ; } @ Override protected int getOffset ( String document ) { if ( insertAfterNode == null ) { return ; } return new AfterNodeOffsetProvider ( insertAfterNode , document ) . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . extractmethod ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String ExtractMethodConditionChecker_MethodAlreadyExists ; public static String ExtractMethodConditionChecker_MustNotContainAClass ; public static String ExtractMethodConditionChecker_MustNotContainAMethod ; public static String ExtractMethodConditionChecker_MustNotContainSubmethods ; public static String ExtractMethodConditionChecker_NothingToDo ; public static String ExtractMethodConditionChecker_NotInsideAMethod ; public static String ExtractMethodConditionChecker_NotPossibleContainsSuper ; public static String ExtractMethodConditionChecker_NotPossibleContainsYield ; public static String ExtractMethodConditionChecker_NotPossibleModule ; public static String ExtractMethodRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . extractmethod ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class ExtractMethodConfig implements IRefactoringConfig { private IDocumentProvider docProvider ; private IRefactoringContext selectionInfo ; private ExtractedMethodHelper extractMethodHelper ; private Node selectedNodes ; private Node enclosingNode ; private MethodDefNode enclosingMethodNode ; private PartialClassNodeWrapper enclosingClassNode ; private Node rootNode ; public ExtractMethodConfig ( IDocumentProvider docProvider , IRefactoringContext selectionInfo ) { this . docProvider = docProvider ; this . selectionInfo = optimizeSelection ( selectionInfo ) ; } private IRefactoringContext optimizeSelection ( IRefactoringContext selectionInfo ) { int start = selectionInfo . getStartOffset ( ) ; int end = selectionInfo . getEndOffset ( ) + ; String content = docProvider . getActiveFileContent ( ) ; if ( end > content . length ( ) ) end = content . length ( ) ; if ( end == start ) return selectionInfo ; String selectedText = content . substring ( start , end ) ; String trimedSelectionInformation = selectedText . trim ( ) ; start += selectedText . indexOf ( trimedSelectionInformation ) ; end = start + trimedSelectionInformation . length ( ) - ; return new RefactoringContext ( start , end , start , selectionInfo . getSource ( ) ) ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public ExtractedMethodHelper getHelper ( ) { return extractMethodHelper ; } public IRefactoringContext getSelection ( ) { return selectionInfo ; } public void setEnclosingScopeNode ( Node enclosingScopeNode ) { this . enclosingNode = enclosingScopeNode ; } public void setEnclosingMethodNode ( MethodDefNode enclosingMethodNode ) { this . enclosingMethodNode = enclosingMethodNode ; } public void setSelectedNodes ( Node selectedNodes ) { this . selectedNodes = selectedNodes ; } public void setEnclosingClassNode ( PartialClassNodeWrapper classNode ) { this . enclosingClassNode = classNode ; } public Node getSelectedNodes ( ) { return selectedNodes ; } public void setExtractedMethodHelper ( ExtractedMethodHelper extractedMethodHelper ) { this . extractMethodHelper = extractedMethodHelper ; } public boolean hasEnclosingClassNode ( ) { return enclosingClassNode != null ; } public PartialClassNodeWrapper getEnclosingClassNode ( ) { return enclosingClassNode ; } public Node getEnclosingScopeNode ( ) { return enclosingNode ; } public MethodDefNode getEnclosingMethodNode ( ) { return enclosingMethodNode ; } public boolean hasEnclosingMethodNode ( ) { return enclosingMethodNode != null ; } public void setRootNode ( Node rootNode ) { this . rootNode = rootNode ; } public Node getRootNode ( ) { return rootNode ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } public ExtractedMethodHelper getExtractMethodHelper ( ) { return extractMethodHelper ; } } package org . rubypeople . rdt . refactoring . core . extractmethod ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Map ; import java . util . Observable ; import org . jruby . ast . BlockNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class ExtractedMethodHelper extends Observable { public static final VisibilityNodeWrapper . METHOD_VISIBILITY DEFAULT_VISIBILITY = VisibilityNodeWrapper . METHOD_VISIBILITY . PRIVATE ; private VisibilityNodeWrapper . METHOD_VISIBILITY visibility ; private Node selectedNodes ; private Collection < LocalNodeWrapper > localNodesNeededAsReturnValues ; private Map < Integer , LocalNodeWrapper > afterSelectionNodes ; private ArrayList < ExtractedArgument > argsOrdered ; private String methodName = "" ; private final boolean isStaticMethod ; public ExtractedMethodHelper ( ExtractMethodConfig config ) { selectedNodes = config . getSelectedNodes ( ) ; visibility = initVisibility ( config . hasEnclosingClassNode ( ) ) ; isStaticMethod = config . getEnclosingMethodNode ( ) instanceof DefsNode ; initAfterSelectionNodes ( config . getEnclosingScopeNode ( ) ) ; initNeededLocalNodes ( ) ; } public Node getSelectedNodes ( ) { return selectedNodes ; } private VisibilityNodeWrapper . METHOD_VISIBILITY initVisibility ( boolean isDefnNodeInClassNode ) { if ( isDefnNodeInClassNode ) { return DEFAULT_VISIBILITY ; } return VisibilityNodeWrapper . METHOD_VISIBILITY . NONE ; } private void initAfterSelectionNodes ( Node enclosingScopeNode ) { Collection < Node > allNodes = NodeProvider . getAllNodes ( enclosingScopeNode ) ; afterSelectionNodes = new LinkedHashMap < Integer , LocalNodeWrapper > ( ) ; int endPostOfLastSelectedNode = selectedNodes . getPosition ( ) . getEndOffset ( ) ; boolean isWrongScopeNode = false ; int endOfOtherScope = ; for ( Node aktNode : allNodes ) { if ( NodeUtil . hasScope ( aktNode ) ) { if ( aktNode . getPosition ( ) . getEndOffset ( ) > endOfOtherScope ) { isWrongScopeNode = false ; endOfOtherScope = ; } if ( ! containsSameNodes ( selectedNodes , aktNode ) ) { isWrongScopeNode = true ; int endOfAktNode = aktNode . getPosition ( ) . getEndOffset ( ) ; if ( endOfAktNode > endOfOtherScope ) { endOfOtherScope = endOfAktNode ; } } } if ( isLocalNodeOfEnclosingScope ( isWrongScopeNode , aktNode ) ) { int aktStartOffset = aktNode . getPosition ( ) . getStartOffset ( ) ; if ( aktStartOffset > endPostOfLastSelectedNode ) { LocalNodeWrapper localNode = new LocalNodeWrapper ( aktNode ) ; afterSelectionNodes . put ( Integer . valueOf ( localNode . getId ( ) ) , localNode ) ; } } } } private boolean containsSameNodes ( Node selectionScopeNode , Node aktScopeNode ) { if ( selectionScopeNode . childNodes ( ) . isEmpty ( ) ) { return false ; } Object nodeToFind = selectionScopeNode . childNodes ( ) . toArray ( ) [ ] ; for ( Object aktNode : NodeProvider . getAllNodes ( aktScopeNode ) ) { if ( aktNode . equals ( nodeToFind ) ) { return true ; } } return false ; } private boolean isLocalNodeOfEnclosingScope ( boolean isWrongScopeNode , Node aktNode ) { return ! isWrongScopeNode && ( NodeUtil . nodeAssignableFrom ( aktNode , LocalNodeWrapper . LOCAL_NODES_CLASSES ) ) ; } private void initNeededLocalNodes ( ) { Collection < LocalNodeWrapper > allLocalNodes = LocalNodeWrapper . gatherLocalNodes ( selectedNodes ) ; Map < String , LocalNodeWrapper > firstOccurrenceIsNotDefinitionLocalNodes = new LinkedHashMap < String , LocalNodeWrapper > ( ) ; Map < String , LocalNodeWrapper > localNodesNeededAsReturnValues = new LinkedHashMap < String , LocalNodeWrapper > ( ) ; Map < String , LocalNodeWrapper > firstOccurrenceIsDefinitionLocalNodes = new LinkedHashMap < String , LocalNodeWrapper > ( ) ; for ( LocalNodeWrapper aktLocalNode : allLocalNodes ) { String nodeName = getLocalNodeName ( aktLocalNode ) ; if ( aktLocalNode . isAsgnNode ( ) ) { if ( ! firstOccurrenceIsNotDefinitionLocalNodes . containsKey ( nodeName ) && ! containsOccurrencesOfItself ( aktLocalNode ) ) { firstOccurrenceIsDefinitionLocalNodes . put ( nodeName , aktLocalNode ) ; } if ( localNodeNeededAfterSelectedNodes ( aktLocalNode ) ) { localNodesNeededAsReturnValues . put ( nodeName , aktLocalNode ) ; } } else { if ( ! firstOccurrenceIsDefinitionLocalNodes . containsKey ( nodeName ) ) { firstOccurrenceIsNotDefinitionLocalNodes . put ( nodeName , aktLocalNode ) ; } } } this . localNodesNeededAsReturnValues = localNodesNeededAsReturnValues . values ( ) ; argsOrdered = new ArrayList < ExtractedArgument > ( ) ; for ( LocalNodeWrapper aktArgNode : firstOccurrenceIsNotDefinitionLocalNodes . values ( ) ) { argsOrdered . add ( new ExtractedArgument ( aktArgNode . getId ( ) , getLocalNodeName ( aktArgNode ) ) ) ; } } private boolean containsOccurrencesOfItself ( LocalNodeWrapper localNode ) { String name = getLocalNodeName ( localNode ) ; Collection < LocalNodeWrapper > subNodes = LocalNodeWrapper . gatherLocalNodes ( localNode . getWrappedNode ( ) ) ; for ( LocalNodeWrapper aktSubNode : subNodes ) { if ( ! aktSubNode . equals ( localNode ) && getLocalNodeName ( aktSubNode ) . equals ( name ) ) { return true ; } } return false ; } private boolean localNodeNeededAfterSelectedNodes ( LocalNodeWrapper localNode ) { return afterSelectionNodes . containsKey ( Integer . valueOf ( localNode . getId ( ) ) ) ; } public Node getMethodNode ( boolean needsNewLineAtBeginOfBlock , boolean needsNewLineAtEndOfBlock ) { updateLocalNamesInNamedNodes ( selectedNodes ) ; BlockNode blockNode = ( BlockNode ) ( selectedNodes instanceof BlockNode ? selectedNodes : NodeFactory . createBlockNode ( NodeFactory . createNewLineNode ( selectedNodes ) ) ) ; if ( localNodesNeededAsReturnValues . size ( ) > ) { blockNode . add ( getReturnNode ( ) ) ; } Node methodDefinitionNode = null ; if ( isStaticMethod ) { methodDefinitionNode = NodeFactory . createStaticMethodNode ( methodName , getInMethodStringMethodArgs ( ) , null , blockNode ) ; } else { methodDefinitionNode = NodeFactory . createMethodNodeWithoutNewline ( methodName , NodeFactory . createArgsNode ( getInMethodStringMethodArgs ( ) ) , blockNode ) ; } methodDefinitionNode = NodeFactory . createNewLineNode ( methodDefinitionNode ) ; if ( visibility . equals ( VisibilityNodeWrapper . METHOD_VISIBILITY . NONE ) ) { return NodeFactory . createBlockNode ( needsNewLineAtBeginOfBlock , needsNewLineAtEndOfBlock , methodDefinitionNode ) ; } Node visibilityNode = NodeFactory . createVisibilityNode ( visibility , methodName ) ; return NodeFactory . createBlockNode ( needsNewLineAtBeginOfBlock , needsNewLineAtEndOfBlock , methodDefinitionNode , visibilityNode ) ; } private void updateLocalNamesInNamedNodes ( Node scopeNode ) { Collection < LocalNodeWrapper > allLocalNodes = LocalNodeWrapper . gatherLocalNodes ( scopeNode ) ; for ( LocalNodeWrapper aktLocalNode : allLocalNodes ) { updateLocalNameInNamedNode ( aktLocalNode ) ; } updateArgsOrderedNames ( ) ; } private void updateArgsOrderedNames ( ) { for ( ExtractedArgument aktArg : argsOrdered ) { aktArg . setOldInExtractedMethodArgName ( aktArg . getNewInExtractedMethodArgName ( ) ) ; } } private void updateLocalNameInNamedNode ( LocalNodeWrapper aktNode ) { String oldName = aktNode . getName ( ) ; for ( ExtractedArgument aktArg : argsOrdered ) { if ( aktArg . getOldInExtractedMethodArgName ( ) . equals ( oldName ) ) { String newName = aktArg . getNewInExtractedMethodArgName ( ) ; aktNode . setName ( newName ) ; } } } public ArrayList < String > getLocalOnlyVariables ( ) { ArrayList < String > arguments = new ArrayList < String > ( ) ; for ( ExtractedArgument arg : argsOrdered ) { arguments . add ( arg . getOriginalName ( ) ) ; } ArrayList < String > local = new ArrayList < String > ( ) ; for ( LocalNodeWrapper varNode : LocalNodeWrapper . gatherLocalNodes ( getMethodCallNode ( ) ) ) { if ( ! arguments . contains ( varNode . getName ( ) ) ) { local . add ( varNode . getName ( ) ) ; } } for ( DAsgnNode n : NodeProvider . gatherLocalDAsgnNodes ( selectedNodes ) ) { local . add ( n . getName ( ) ) ; } return local ; } private Node getReturnNode ( ) { if ( localNodesNeededAsReturnValues . size ( ) == ) { LocalNodeWrapper node = localNodesNeededAsReturnValues . toArray ( new LocalNodeWrapper [ localNodesNeededAsReturnValues . size ( ) ] ) [ ] ; DVarNode localNode = NodeFactory . createDVarNode ( getLocalNodeName ( node ) ) ; return NodeFactory . createNewLineNode ( localNode ) ; } Collection < Node > localVarNodes = getLocalVarNodes ( localNodesNeededAsReturnValues ) ; return NodeFactory . createNewLineNode ( NodeFactory . createArrayNode ( localVarNodes ) ) ; } private Collection < String > getInMethodStringMethodArgs ( ) { Collection < String > args = new ArrayList < String > ( ) ; for ( ExtractedArgument arg : argsOrdered ) { args . add ( arg . getNewInExtractedMethodArgName ( ) ) ; } return args ; } private Collection < Node > getCallArgs ( ) { Collection < Node > args = new ArrayList < Node > ( ) ; for ( ExtractedArgument aktArg : argsOrdered ) { args . add ( NodeFactory . createDVarNode ( aktArg . getOriginalName ( ) ) ) ; } return args ; } private Collection < Node > getLocalVarNodes ( Collection < LocalNodeWrapper > localNodes ) { Collection < Node > arguments = new ArrayList < Node > ( ) ; for ( LocalNodeWrapper aktLocalNode : localNodes ) { if ( aktLocalNode . isDVarNode ( ) ) { arguments . add ( NodeFactory . createDVarNode ( aktLocalNode . getName ( ) ) ) ; } else { arguments . add ( NodeFactory . createLocalVarNode ( aktLocalNode . getName ( ) ) ) ; } } return arguments ; } public Node getMethodCallNode ( ) { Node methodCallNode = NodeFactory . createMethodCallNode ( methodName , getCallArgs ( ) ) ; if ( localNodesNeededAsReturnValues . size ( ) > ) { return getAsgnNode ( methodCallNode ) ; } return methodCallNode ; } private Node getAsgnNode ( Node methodCallNode ) { if ( localNodesNeededAsReturnValues . size ( ) == ) { LocalNodeWrapper firstReturnNode = localNodesNeededAsReturnValues . toArray ( new LocalNodeWrapper [ localNodesNeededAsReturnValues . size ( ) ] ) [ ] ; return getLocalAsgnNode ( firstReturnNode , methodCallNode ) ; } Collection < Node > localAsgnNodes = getLocalAsgnNodesForMultipleAsgnNode ( ) ; return NodeFactory . createMultipleAsgnNode ( localAsgnNodes , methodCallNode ) ; } private LocalAsgnNode getLocalAsgnNode ( LocalNodeWrapper localNode , Node valueNode ) { String name = getLocalNodeName ( localNode ) ; return NodeFactory . createLocalAsgnNode ( name , localNode . getId ( ) , valueNode ) ; } private Collection < Node > getLocalAsgnNodesForMultipleAsgnNode ( ) { Collection < Node > result = new ArrayList < Node > ( ) ; for ( LocalNodeWrapper aktNode : localNodesNeededAsReturnValues ) { result . add ( NodeFactory . createLocalAsgnNode ( getLocalNodeName ( aktNode ) , aktNode . getId ( ) , null ) ) ; } return result ; } private String getLocalNodeName ( LocalNodeWrapper node ) { return LocalNodeWrapper . getLocalNodeName ( node ) ; } public Collection < String > getArguments ( ) { return getInMethodStringMethodArgs ( ) ; } public boolean hasArguments ( ) { return ! argsOrdered . isEmpty ( ) ; } public void changeParameter ( int fromId , int toId ) { ExtractedArgument aktArg = argsOrdered . remove ( fromId ) ; argsOrdered . add ( toId , aktArg ) ; setChanged ( ) ; notifyObservers ( ) ; } public void changeParameter ( int id , String name ) { ExtractedArgument aktArg = argsOrdered . get ( id ) ; aktArg . setNewInExtractedMethodArgName ( name ) ; setChanged ( ) ; notifyObservers ( ) ; } public void setVisibility ( VisibilityNodeWrapper . METHOD_VISIBILITY v ) { visibility = v ; } public VisibilityNodeWrapper . METHOD_VISIBILITY getVisibility ( ) { return visibility ; } public String getMethodName ( ) { return methodName ; } public void setMethodName ( String methodName ) { this . methodName = methodName ; setChanged ( ) ; notifyObservers ( ) ; } } package org . rubypeople . rdt . refactoring . core . extractmethod ; import org . eclipse . ltk . ui . refactoring . UserInputWizardPage ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . ui . pages . ExtractMethodPage ; public class ExtractMethodRefactoring extends RubyRefactoring { public static final String NAME = Messages . ExtractMethodRefactoring_Name ; public ExtractMethodRefactoring ( RefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; ExtractMethodConfig config = new ExtractMethodConfig ( getDocumentProvider ( ) , selectionProvider ) ; ExtractMethodConditionChecker checker = new ExtractMethodConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { MethodExtractor methodExtractor = new MethodExtractor ( config ) ; setEditProvider ( methodExtractor ) ; UserInputWizardPage page = new ExtractMethodPage ( methodExtractor , selectionProvider ) ; pages . add ( page ) ; } } } package org . rubypeople . rdt . refactoring . core . extractmethod ; import java . util . HashMap ; import java . util . Map ; import org . jruby . ast . CallNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . FormatHelper ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; public class ExtractedMethodCall extends ReplaceEditProvider { private final Node rootNode ; private Node selectedNode ; private Node methodCallNode ; public ExtractedMethodCall ( Node selectedNode , Node methodCallNode , Node rootNode ) { super ( false ) ; this . selectedNode = selectedNode ; this . methodCallNode = methodCallNode ; this . rootNode = rootNode ; } public ExtractedMethodCall ( ExtractMethodConfig config ) { this ( config . getExtractMethodHelper ( ) . getSelectedNodes ( ) , config . getExtractMethodHelper ( ) . getMethodCallNode ( ) , config . getRootNode ( ) ) ; } @ Override protected int getOffsetLength ( ) { return getEndOffset ( ) - getStartOffset ( ) ; } private int getStartOffset ( ) { return getExtendedPosition ( selectedNode ) . getStartOffset ( ) ; } private int getEndOffset ( ) { return getExtendedPosition ( selectedNode ) . getEndOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return methodCallNode ; } @ Override protected FormatHelper getFormatHelper ( ) { Node bodyNode = selectedNode ; while ( bodyNode instanceof NewlineNode ) { bodyNode = ( ( NewlineNode ) bodyNode ) . getNextNode ( ) ; } Map < String , Object > options = new HashMap < String , Object > ( ) ; if ( NodeProvider . findParentNode ( rootNode , bodyNode ) instanceof CallNode ) { options . put ( FormatHelper . ALWAYS_SURROUND_METHOD_CALLS_IN_PARENS , true ) ; } return new EditableFormatHelper ( options ) ; } @ Override protected int getOffset ( String document ) { return getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . extractmethod ; import java . util . Collection ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . BreakNode ; import org . jruby . ast . CaseNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . ForNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . NextNode ; import org . jruby . ast . Node ; import org . jruby . ast . RedoNode ; import org . jruby . ast . RetryNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . jruby . ast . SuperNode ; import org . jruby . ast . WhenNode ; import org . jruby . ast . WhileNode ; import org . jruby . ast . YieldNode ; import org . jruby . ast . ZSuperNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class ExtractMethodConditionChecker extends RefactoringConditionChecker { private ExtractMethodConfig config ; public ExtractMethodConditionChecker ( ExtractMethodConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( ExtractMethodConfig ) configObj ; initEnclosingNodes ( ) ; if ( ! NodeProvider . isEmptyNode ( config . getSelectedNodes ( ) ) && config . getExtractMethodHelper ( ) == null ) { config . setExtractedMethodHelper ( new ExtractedMethodHelper ( config ) ) ; } } private void initEnclosingNodes ( ) { RootNode rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; config . setRootNode ( rootNode ) ; config . setEnclosingScopeNode ( SelectionNodeProvider . getEnclosingScope ( rootNode , config . getSelection ( ) . getStartOffset ( ) ) ) ; config . setEnclosingMethodNode ( ( MethodDefNode ) SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , MethodDefNode . class ) ) ; config . setSelectedNodes ( getSelectedNodes ( rootNode ) ) ; Node classNode = SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , ClassNode . class , SClassNode . class ) ; try { config . setEnclosingClassNode ( PartialClassNodeWrapper . getPartialClassNodeWrapper ( classNode , rootNode ) ) ; } catch ( NoClassNodeException e ) { } } private Node getSelectedNodes ( RootNode rootNode ) { Node selectedNode = SelectionNodeProvider . getSelectedNodes ( rootNode , config . getSelection ( ) ) ; if ( NodeUtil . nodeAssignableFrom ( selectedNode , WhenNode . class ) ) { selectedNode = SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , CaseNode . class ) ; } if ( NodeUtil . nodeAssignableFrom ( selectedNode , ArrayNode . class ) ) { WhenNode enclosingWhen = ( WhenNode ) SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , WhenNode . class ) ; if ( enclosingWhen != null && SelectionNodeProvider . nodeEnclosesNode ( enclosingWhen . getExpressionNodes ( ) , selectedNode ) ) { selectedNode = SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , CaseNode . class ) ; } } if ( containsLoopControlNode ( selectedNode ) ) { selectedNode = getLoopOrItsParent ( rootNode , selectedNode ) ; } if ( SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , ArgsNode . class ) != null ) { return SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , MethodDefNode . class ) ; } if ( NodeUtil . nodeAssignableFrom ( selectedNode , ArgumentNode . class ) ) { selectedNode = config . getEnclosingMethodNode ( ) ; } ArrayNode enclosingArrayNode = ( ArrayNode ) SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , ArrayNode . class ) ; if ( ! sectedNodesInArrayNode ( enclosingArrayNode , selectedNode ) || ! NodeUtil . nodeAssignableFrom ( selectedNode , ArrayNode . class ) ) { return selectedNode ; } Node enclosingMethodCallNode = SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , MethodCallNodeWrapper . METHOD_CALL_NODE_CLASSES ( ) ) ; MethodCallNodeWrapper enclosingMethodCall = new MethodCallNodeWrapper ( enclosingMethodCallNode ) ; if ( NodeUtil . nodeAssignableFrom ( enclosingMethodCall . getArgsNode ( ) , ArrayNode . class ) ) { ArrayNode enclosingMethodCallArgs = ( ArrayNode ) enclosingMethodCall . getArgsNode ( ) ; if ( enclosingArrayNode == enclosingMethodCallArgs ) return enclosingMethodCallNode ; } MultipleAsgnNode asgnNode = ( MultipleAsgnNode ) SelectionNodeProvider . getEnclosingNode ( rootNode , config . getSelection ( ) , MultipleAsgnNode . class ) ; if ( asgnNode != null && NodeUtil . nodeAssignableFrom ( asgnNode . getHeadNode ( ) , ArrayNode . class ) ) { } return selectedNode ; } private Node getLoopOrItsParent ( RootNode rootNode , Node selectedNode ) { Node loopNode = NodeProvider . getEnclosingNodeOfType ( rootNode , selectedNode , WhileNode . class , ForNode . class , IterNode . class ) ; if ( loopNode != null ) { selectedNode = loopNode ; } if ( NodeUtil . nodeAssignableFrom ( loopNode , IterNode . class ) ) { selectedNode = NodeProvider . findParentNode ( rootNode , loopNode ) ; } return selectedNode ; } private boolean containsLoopControlNode ( Node selectedNode ) { return ! NodeProvider . getSubNodes ( selectedNode , BreakNode . class , RedoNode . class , NextNode . class , RetryNode . class ) . isEmpty ( ) ; } private boolean sectedNodesInArrayNode ( ArrayNode arrayNode , Node selectedNode ) { if ( arrayNode == null ) { return false ; } Collection < Node > arrayChilds = NodeProvider . getAllNodes ( arrayNode ) ; for ( Object actSelectedNode : selectedNode . childNodes ( ) ) { if ( ! arrayChilds . contains ( actSelectedNode ) ) { return false ; } } return true ; } @ Override protected void checkFinalConditions ( ) { checkNewMethodName ( ) ; } private void checkNewMethodName ( ) { String newMethodName = config . getHelper ( ) . getMethodName ( ) ; PartialClassNodeWrapper enclosingClassNode = config . getEnclosingClassNode ( ) ; if ( enclosingClassNode != null ) { Collection < Node > methodNodes = NodeProvider . getSubNodes ( enclosingClassNode . getWrappedNode ( ) , DefnNode . class ) ; for ( Node aktNode : methodNodes ) { if ( ( ( DefnNode ) aktNode ) . getName ( ) . equals ( newMethodName ) ) { addError ( Messages . ExtractMethodConditionChecker_MethodAlreadyExists ) ; } } } } @ Override protected void checkInitialConditions ( ) { if ( ! existSelectedNodes ( ) ) { addError ( Messages . ExtractMethodConditionChecker_NothingToDo ) ; } else if ( containsYieldStatements ( ) ) { addError ( Messages . ExtractMethodConditionChecker_NotPossibleContainsYield ) ; } else if ( containsSuperStatement ( ) ) { addError ( Messages . ExtractMethodConditionChecker_NotPossibleContainsSuper ) ; } else if ( isModuleInSelection ( ) ) { addError ( Messages . ExtractMethodConditionChecker_NotPossibleModule ) ; } else if ( isClassInSelection ( ) ) { addError ( Messages . ExtractMethodConditionChecker_MustNotContainAClass ) ; } else if ( isMethodInSelction ( ) ) { addError ( Messages . ExtractMethodConditionChecker_MustNotContainAMethod ) ; } else { checkInternalMethods ( ) ; } } private boolean existSelectedNodes ( ) { return ! NodeProvider . isEmptyNode ( config . getSelectedNodes ( ) ) ; } private boolean containsYieldStatements ( ) { return NodeProvider . hasSubNodes ( config . getSelectedNodes ( ) , YieldNode . class ) ; } private boolean containsSuperStatement ( ) { return NodeProvider . hasSubNodes ( config . getSelectedNodes ( ) , SuperNode . class , ZSuperNode . class ) ; } private boolean isModuleInSelection ( ) { Node selctedNodes = config . getSelectedNodes ( ) ; Collection < Node > moduleNodes = NodeProvider . getSubNodes ( selctedNodes , ModuleNode . class ) ; return ! moduleNodes . isEmpty ( ) ; } private boolean isClassInSelection ( ) { Node selctedNodes = config . getSelectedNodes ( ) ; Collection < Node > classNodes = NodeProvider . getSubNodes ( selctedNodes , ClassNode . class ) ; return ! classNodes . isEmpty ( ) ; } private boolean isMethodInSelction ( ) { Node selctedNodes = config . getSelectedNodes ( ) ; Collection < Node > methodNodes = NodeProvider . getSubNodes ( selctedNodes , MethodDefNode . class ) ; return ! methodNodes . isEmpty ( ) ; } private void checkInternalMethods ( ) { if ( config . hasEnclosingClassNode ( ) && ! config . hasEnclosingMethodNode ( ) ) { addError ( Messages . ExtractMethodConditionChecker_NotInsideAMethod ) ; } if ( config . hasEnclosingClassNode ( ) && NodeProvider . hasSubNodes ( NodeUtil . getBody ( config . getEnclosingScopeNode ( ) ) , DefnNode . class ) ) { addError ( Messages . ExtractMethodConditionChecker_MustNotContainSubmethods ) ; } } } package org . rubypeople . rdt . refactoring . core . extractmethod ; public class ExtractedArgument { private String originalArgName ; private String newInExtractedMethodArgName ; private String oldInExtractedMethodArgName ; private int index ; public ExtractedArgument ( int id , String argName ) { this . index = id ; this . originalArgName = argName ; newInExtractedMethodArgName = argName ; oldInExtractedMethodArgName = argName ; } public String getOriginalName ( ) { return originalArgName ; } public int getIndex ( ) { return index ; } public String getNewInExtractedMethodArgName ( ) { return newInExtractedMethodArgName ; } public void setNewInExtractedMethodArgName ( String name ) { newInExtractedMethodArgName = name ; } public String getOldInExtractedMethodArgName ( ) { return oldInExtractedMethodArgName ; } public void setOldInExtractedMethodArgName ( String name ) { oldInExtractedMethodArgName = name ; } } package org . rubypeople . rdt . refactoring . core ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class ConstNameValidator implements IValidator { public boolean isValid ( String test ) { return NameValidator . isValidConstName ( test ) ; } } package org . rubypeople . rdt . refactoring . core ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ConstNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ModuleNodeWrapper ; public abstract class ModuleNodeProvider { private interface IModuleAcceptor { boolean accept ( ModuleNodeWrapper wrapper ) ; } public static ModuleNodeWrapper getSelectedModuleNode ( Node root , int pos ) { ModuleNode module = ( ModuleNode ) SelectionNodeProvider . getSelectedNodeOfType ( root , pos , ModuleNode . class ) ; if ( module == null ) { return null ; } return createModuleNodeWrapper ( root , module ) ; } private static Collection < ModuleNodeWrapper > findModules ( IDocumentProvider doc , IModuleAcceptor acceptor ) { ArrayList < ModuleNodeWrapper > modules = new ArrayList < ModuleNodeWrapper > ( ) ; for ( String file : doc . getFileNames ( ) ) { for ( Node node : NodeProvider . getSubNodes ( doc . getRootNode ( file ) , ModuleNode . class ) ) { ModuleNode moduleNode = ( ModuleNode ) node ; ModuleNodeWrapper wrapper = createModuleNodeWrapper ( doc . getRootNode ( file ) , moduleNode ) ; if ( acceptor . accept ( wrapper ) ) { modules . add ( wrapper ) ; } } } return modules ; } public static Collection < ModuleNodeWrapper > findOtherParts ( IDocumentProvider doc , final ModuleNodeWrapper module ) { return findModules ( doc , new IModuleAcceptor ( ) { public boolean accept ( ModuleNodeWrapper wrapper ) { return wrapper . getFullName ( ) . equals ( module . getFullName ( ) ) ; } } ) ; } public static Collection < ModuleNodeWrapper > findAllModules ( IDocumentProvider doc ) { return findModules ( doc , new IModuleAcceptor ( ) { public boolean accept ( ModuleNodeWrapper wrapper ) { return true ; } } ) ; } public static Collection < ConstNode > getAllModuleMethodDefinitions ( Collection < ModuleNodeWrapper > modules ) { ArrayList < ConstNode > methods = new ArrayList < ConstNode > ( ) ; for ( ModuleNodeWrapper wrapper : modules ) { methods . addAll ( wrapper . getModuleMethodConstNodes ( ) ) ; } return methods ; } private static ModuleNodeWrapper createModuleNodeWrapper ( Node root , ModuleNode module ) { ArrayList < ModuleNode > modules = new ArrayList < ModuleNode > ( ) ; modules . add ( module ) ; ModuleNode parent = null ; while ( true ) { parent = ( ModuleNode ) NodeProvider . findParentNode ( root , module , ModuleNode . class ) ; if ( parent == null ) break ; modules . add ( , parent ) ; module = parent ; } ModuleNodeWrapper previousWrapper = null ; for ( ModuleNode node : modules ) { ModuleNodeWrapper nodeWrapper = new ModuleNodeWrapper ( node , previousWrapper ) ; previousWrapper = nodeWrapper ; } return previousWrapper ; } } package org . rubypeople . rdt . refactoring . core . inlinelocal ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ClassNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; import org . rubypeople . rdt . refactoring . util . JRubyRefactoringUtils ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class InlineLocalConditionChecker extends RefactoringConditionChecker { private InlineLocalConfig config ; private RootNode rootNode ; public InlineLocalConditionChecker ( InlineLocalConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( InlineLocalConfig ) configObj ; rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; int caretPosition = config . getCaretPosition ( ) ; config . setEnclosingMethod ( ( MethodDefNode ) SelectionNodeProvider . getSelectedNodeOfType ( rootNode , caretPosition , MethodDefNode . class ) ) ; config . setEnclosingScopeNode ( SelectionNodeProvider . getEnclosingScope ( rootNode , caretPosition ) ) ; Node locVarNode = SelectionNodeProvider . getSelectedNodeOfType ( rootNode , caretPosition , LocalNodeWrapper . LOCAL_NODES_CLASSES ) ; if ( locVarNode == null ) { return ; } config . setSelectedItem ( new LocalNodeWrapper ( locVarNode ) ) ; config . setSelectedItemName ( LocalNodeWrapper . getLocalNodeName ( config . getSelectedItem ( ) ) ) ; initDefinitionNode ( ) ; initLocalOccurrences ( ) ; } private void initDefinitionNode ( ) { Collection < LocalNodeWrapper > asgnNodes = LocalNodeWrapper . gatherLocalAsgnNodes ( config . getEnclosingScopeNode ( ) ) ; for ( LocalNodeWrapper currentAsgnNode : asgnNodes ) { if ( currentAsgnNode . getName ( ) . equals ( config . getSelectedItemName ( ) ) ) { config . setDefinitionNode ( currentAsgnNode ) ; } } } private void initLocalOccurrences ( ) { Collection < LocalNodeWrapper > localOccurrences = new ArrayList < LocalNodeWrapper > ( ) ; Collection < LocalNodeWrapper > nodesInMethod = LocalNodeWrapper . gatherLocalVarNodes ( config . getEnclosingScopeNode ( ) ) ; for ( LocalNodeWrapper currentLocalNode : nodesInMethod ) { String currentNodeName = LocalNodeWrapper . getLocalNodeName ( currentLocalNode ) ; if ( currentNodeName . equals ( config . getSelectedItemName ( ) ) ) { localOccurrences . add ( currentLocalNode ) ; } } config . setLocalOccurences ( localOccurrences ) ; } @ Override protected void checkFinalConditions ( ) { if ( ! isNewMethodNameUnique ( ) ) { addError ( Messages . InlineLocalConditionChecker_NameNotUnique ) ; } } @ Override protected void checkInitialConditions ( ) { if ( config . getSelectedItem ( ) == null ) { addError ( Messages . InlineLocalConditionChecker_NoLocalVariable ) ; } else if ( isTempParameter ( ) ) { addError ( Messages . InlineLocalConditionChecker_CannotMethodParameters ) ; } else if ( isBlockArgument ( ) ) { addError ( Messages . InlineLocalConditionChecker_CannotBlockArgument ) ; } else if ( isTempMultiassigned ( ) ) { addError ( Messages . InlineLocalConditionChecker_CannotMultiAssigned ) ; } else if ( defintiontionContainsItself ( ) ) { addError ( Messages . InlineLocalConditionChecker_CannotSelfReferencing ) ; } else if ( isMultipleAsgnNode ( ) ) { addError ( Messages . InlineLocalConditionChecker_CannotMultipleAssignments ) ; } else if ( ! hasTarget ( ) ) { addError ( Messages . InlineLocalConditionChecker_NoTarget ) ; } } private boolean hasTarget ( ) { return ! config . getLocalOccurrences ( ) . isEmpty ( ) ; } private boolean isBlockArgument ( ) { IterNode enclosingIterNode = ( IterNode ) SelectionNodeProvider . getSelectedNodeOfType ( rootNode , config . getCaretPosition ( ) , IterNode . class ) ; if ( enclosingIterNode == null ) { return false ; } Node varNode = enclosingIterNode . getVarNode ( ) ; return config . getSelectedItem ( ) . getWrappedNode ( ) . equals ( varNode ) ; } private boolean isMultipleAsgnNode ( ) { Node enclosingMultipleAssignmentNode = SelectionNodeProvider . getSelectedNodeOfType ( config . getEnclosingScopeNode ( ) , config . getCaretPosition ( ) , MultipleAsgnNode . class ) ; return enclosingMultipleAssignmentNode != null ; } private boolean isTempParameter ( ) { if ( config . getEnclosingMethod ( ) == null || ! config . getSelectedItem ( ) . hasValidId ( ) ) { return false ; } return JRubyRefactoringUtils . isParameter ( config . getSelectedItem ( ) , config . getEnclosingMethod ( ) ) ; } private boolean isNewMethodNameUnique ( ) { Node environment = SelectionNodeProvider . getSelectedNodeOfType ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , config . getCaretPosition ( ) , ClassNode . class , RootNode . class ) ; Collection < MethodDefNode > methodNodes = NodeProvider . gatherMethodDefinitionNodes ( NodeUtil . getBody ( environment ) ) ; for ( MethodDefNode currentDefnNode : methodNodes ) { if ( currentDefnNode . getName ( ) . equals ( config . getNewMethodName ( ) ) ) { return false ; } } return true ; } private boolean isTempMultiassigned ( ) { Collection < LocalNodeWrapper > nodesInMethod = LocalNodeWrapper . gatherLocalAsgnNodes ( config . getEnclosingScopeNode ( ) ) ; int countOccurrence = ; for ( LocalNodeWrapper currentLocalNode : nodesInMethod ) { String currentNodeName = LocalNodeWrapper . getLocalNodeName ( currentLocalNode ) ; if ( currentNodeName . equals ( config . getSelectedItemName ( ) ) ) { countOccurrence ++ ; } } return countOccurrence > ; } private boolean defintiontionContainsItself ( ) { if ( config . getDefinitionNode ( ) == null ) { return false ; } ISourcePosition defPosition = config . getDefinitionNode ( ) . getWrappedNode ( ) . getPosition ( ) ; for ( LocalNodeWrapper currentOccurrence : config . getLocalOccurrences ( ) ) { ISourcePosition occurrencePosition = currentOccurrence . getWrappedNode ( ) . getPosition ( ) ; if ( defPosition . getStartOffset ( ) <= occurrencePosition . getStartOffset ( ) && defPosition . getEndOffset ( ) >= occurrencePosition . getEndOffset ( ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . refactoring . core . inlinelocal ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . InlineLocalPage ; public class InlineLocalRefactoring extends RubyRefactoring { public static final String NAME = Messages . InlineLocalRefactoring_Name ; private LocalVariableInliner tempInliner ; public InlineLocalRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; InlineLocalConfig config = new InlineLocalConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; InlineLocalConditionChecker checker = new InlineLocalConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { tempInliner = new LocalVariableInliner ( config ) ; setEditProvider ( tempInliner ) ; pages . add ( new InlineLocalPage ( config , tempInliner . getOccurrencesCount ( ) , tempInliner . getSelectedItemName ( ) ) ) ; } } } package org . rubypeople . rdt . refactoring . core . inlinelocal ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String InlineLocalConditionChecker_CannotBlockArgument ; public static String InlineLocalConditionChecker_CannotMethodParameters ; public static String InlineLocalConditionChecker_CannotMultiAssigned ; public static String InlineLocalConditionChecker_CannotMultipleAssignments ; public static String InlineLocalConditionChecker_CannotSelfReferencing ; public static String InlineLocalConditionChecker_NameNotUnique ; public static String InlineLocalConditionChecker_NoLocalVariable ; public static String InlineLocalConditionChecker_NoTarget ; public static String InlineLocalRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . inlinelocal ; import java . util . HashMap ; import java . util . Map ; import org . jruby . ast . CallNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . FormatHelper ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . util . JRubyRefactoringUtils ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class LocalValueReplaceProvider extends ReplaceEditProvider { private LocalNodeWrapper targetNode ; private LocalNodeWrapper inlinedNode ; private boolean addBrackets ; private InlineLocalConfig config ; public LocalValueReplaceProvider ( LocalNodeWrapper targetNode , InlineLocalConfig config , boolean addBrackets ) { super ( false ) ; this . config = config ; this . inlinedNode = config . getDefinitionNode ( ) ; this . targetNode = targetNode ; this . addBrackets = addBrackets ; } @ Override protected int getOffsetLength ( ) { ISourcePosition replacePos = targetNode . getWrappedNode ( ) . getPosition ( ) ; return replacePos . getEndOffset ( ) - replacePos . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return inlinedNode . getValueNode ( ) ; } @ Override protected int getOffset ( String document ) { return targetNode . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ; } protected String getFormatedNode ( String document ) { if ( addBrackets ) { return '' + super . getFormatedNode ( document ) + '' ; } return super . getFormatedNode ( document ) ; } @ Override protected FormatHelper getFormatHelper ( ) { if ( callNeedsBrackets ( ) ) { Map < String , Object > options = new HashMap < String , Object > ( ) ; options . put ( FormatHelper . ALWAYS_SURROUND_METHOD_CALLS_IN_PARENS , true ) ; return new EditableFormatHelper ( options ) ; } else { return super . getFormatHelper ( ) ; } } private boolean callNeedsBrackets ( ) { Node targetEnclosingNode = NodeProvider . findParentNode ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , targetNode . getWrappedNode ( ) ) ; boolean isTargetEnclosingNodeCallNode = NodeUtil . nodeAssignableFrom ( targetEnclosingNode , MethodCallNodeWrapper . METHOD_CALL_NODE_CLASSES ( ) ) ; if ( NodeUtil . nodeAssignableFrom ( targetEnclosingNode , CallNode . class ) ) { isTargetEnclosingNodeCallNode &= ! JRubyRefactoringUtils . isMathematicalExpression ( targetEnclosingNode ) ; } boolean isInlinedNodeCallNode = NodeUtil . nodeAssignableFrom ( inlinedNode . getValueNode ( ) , MethodCallNodeWrapper . METHOD_CALL_NODE_CLASSES ( ) ) ; if ( NodeUtil . nodeAssignableFrom ( inlinedNode . getValueNode ( ) , CallNode . class ) ) { isInlinedNodeCallNode &= ! JRubyRefactoringUtils . isMathematicalExpression ( inlinedNode . getValueNode ( ) ) ; } return isTargetEnclosingNodeCallNode && isInlinedNodeCallNode ; } } package org . rubypeople . rdt . refactoring . core . inlinelocal ; import java . util . Collection ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; public class InlineLocalConfig implements IRefactoringConfig { private boolean replaceTempWithQuery ; private String newMethodName = "" ; private IDocumentProvider docProvider ; private int caretPosition ; private MethodDefNode enclosingMethod ; private Node enclosingScopeNode ; private LocalNodeWrapper selectedItem ; private String selectedItemName ; private LocalNodeWrapper definitionNode ; private Collection < LocalNodeWrapper > localOccurrences ; public InlineLocalConfig ( DocumentProvider docProvider , int caretPosition ) { this . docProvider = docProvider ; this . caretPosition = caretPosition ; } public boolean isReplaceTempWithQuery ( ) { return replaceTempWithQuery ; } public void setReplaceTempWithQuery ( boolean replaceTempWithQuery ) { this . replaceTempWithQuery = replaceTempWithQuery ; } public String getNewMethodName ( ) { return newMethodName ; } public void setNewMethodName ( String newMethodName ) { this . newMethodName = newMethodName ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public int getCaretPosition ( ) { return caretPosition ; } public String getActiveFileName ( ) { return docProvider . getActiveFileName ( ) ; } public LocalNodeWrapper getDefinitionNode ( ) { return definitionNode ; } public MethodDefNode getEnclosingMethod ( ) { return enclosingMethod ; } public Node getEnclosingScopeNode ( ) { return enclosingScopeNode ; } public Collection < LocalNodeWrapper > getLocalOccurrences ( ) { return localOccurrences ; } public LocalNodeWrapper getSelectedItem ( ) { return selectedItem ; } public String getSelectedItemName ( ) { return selectedItemName ; } public void setLocalOccurences ( Collection < LocalNodeWrapper > localOccurrences ) { this . localOccurrences = localOccurrences ; } public void setDefinitionNode ( LocalNodeWrapper definitionNode ) { this . definitionNode = definitionNode ; } public void setSelectedItemName ( String selectedItemName ) { this . selectedItemName = selectedItemName ; } public void setSelectedItem ( LocalNodeWrapper selectedItem ) { this . selectedItem = selectedItem ; } public void setEnclosingScopeNode ( Node enclosingScopeNode ) { this . enclosingScopeNode = enclosingScopeNode ; } public void setEnclosingMethod ( MethodDefNode enclosingMethod ) { this . enclosingMethod = enclosingMethod ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . inlinelocal ; import java . util . HashMap ; import java . util . Map ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . FormatHelper ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; public class MethodCallReplaceProvider extends ReplaceEditProvider { LocalNodeWrapper targetNode ; Node methodCallNode ; public MethodCallReplaceProvider ( LocalNodeWrapper targetNode , Node methodCallNode ) { super ( false ) ; this . targetNode = targetNode ; this . methodCallNode = methodCallNode ; } @ Override protected int getOffsetLength ( ) { ISourcePosition replacePos = targetNode . getWrappedNode ( ) . getPosition ( ) ; return replacePos . getEndOffset ( ) - replacePos . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return methodCallNode ; } @ Override protected int getOffset ( String document ) { return targetNode . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ; } @ Override protected FormatHelper getFormatHelper ( ) { Map < String , Object > options = new HashMap < String , Object > ( ) ; options . put ( FormatHelper . ALWAYS_SURROUND_METHOD_CALLS_IN_PARENS , true ) ; return new EditableFormatHelper ( options ) ; } } package org . rubypeople . rdt . refactoring . core . inlinelocal ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractMethodConfig ; import org . rubypeople . rdt . refactoring . core . extractmethod . MethodExtractor ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; import org . rubypeople . rdt . refactoring . util . JRubyRefactoringUtils ; public class LocalVariableInliner extends MultiEditProvider { private InlineLocalConfig config ; private ExtractMethodConfig extractConfig ; public LocalVariableInliner ( InlineLocalConfig config ) { this . config = config ; } @ Override protected Collection < EditProvider > getEditProviders ( ) { ArrayList < EditProvider > editProviders = new ArrayList < EditProvider > ( ) ; editProviders . add ( createDeleteEdit ( ) ) ; if ( config . isReplaceTempWithQuery ( ) ) { editProviders . add ( extractMethodProvider ( ) ) ; for ( LocalNodeWrapper currentLocalNode : config . getLocalOccurrences ( ) ) { editProviders . add ( replaceWithMethodCallProvider ( currentLocalNode ) ) ; } } else { for ( LocalNodeWrapper currentLocalNode : config . getLocalOccurrences ( ) ) { editProviders . add ( replaceWithValueProvider ( currentLocalNode ) ) ; } } return editProviders ; } private EditProvider replaceWithMethodCallProvider ( LocalNodeWrapper targetNode ) { return new MethodCallReplaceProvider ( targetNode , extractConfig . getHelper ( ) . getMethodCallNode ( ) ) ; } private EditProvider replaceWithValueProvider ( LocalNodeWrapper targetNode ) { boolean addBrackets = JRubyRefactoringUtils . isMathematicalExpression ( config . getDefinitionNode ( ) . getValueNode ( ) ) ; return new LocalValueReplaceProvider ( targetNode , config , addBrackets ) ; } private EditProvider extractMethodProvider ( ) { int startPos = config . getDefinitionNode ( ) . getValueNode ( ) . getPosition ( ) . getStartOffset ( ) ; int endPos = config . getDefinitionNode ( ) . getValueNode ( ) . getPosition ( ) . getEndOffset ( ) ; extractConfig = new ExtractMethodConfig ( config . getDocumentProvider ( ) , new RefactoringContext ( startPos , endPos , startPos , "" ) ) ; new ExtractMethodConditionChecker ( extractConfig ) ; MethodExtractor methodExtractor = new MethodExtractor ( extractConfig ) ; extractConfig . getHelper ( ) . setMethodName ( config . getNewMethodName ( ) ) ; return methodExtractor . getDefEdit ( ) ; } private EditProvider createDeleteEdit ( ) { return new DeleteEditProvider ( config . getDefinitionNode ( ) . getWrappedNode ( ) ) ; } public int getOccurrencesCount ( ) { return config . getLocalOccurrences ( ) == null ? : config . getLocalOccurrences ( ) . size ( ) ; } public String getSelectedItemName ( ) { return config . getSelectedItemName ( ) ; } public InlineLocalConfig getConfig ( ) { return config ; } } package org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class MergeClassPartInFileConfig implements IRefactoringConfig { private IDocumentProvider documentProvider ; private Collection < ClassNodeWrapper > selectableClasses ; private PartialClassNodeWrapper selectedClassPart ; private Collection < PartialClassNodeWrapper > checkedClassParts ; private IncludedClassesProvider classNodeProvider ; public MergeClassPartInFileConfig ( IDocumentProvider documentProvider ) { this . documentProvider = documentProvider ; checkedClassParts = new ArrayList < PartialClassNodeWrapper > ( ) ; } public IDocumentProvider getDocumentProvider ( ) { return documentProvider ; } public boolean hasSelectableClasses ( ) { return selectableClasses != null && ! selectableClasses . isEmpty ( ) ; } public PartialClassNodeWrapper getSelectedClassPart ( ) { return selectedClassPart ; } public Collection < PartialClassNodeWrapper > getCheckedClassParts ( ) { return checkedClassParts ; } public void setSelectableClasses ( Collection < ClassNodeWrapper > selectableClasses ) { this . selectableClasses = selectableClasses ; } public Collection < ClassNodeWrapper > getSelectableClasses ( ) { return selectableClasses ; } public void setCheckedClassParts ( Collection < PartialClassNodeWrapper > checkedClassParts ) { this . checkedClassParts = checkedClassParts ; } public void setSelectedClassPart ( PartialClassNodeWrapper selectedClassPart ) { this . selectedClassPart = selectedClassPart ; } public ClassNodeWrapper getClassNode ( String className ) { return classNodeProvider . getClassNode ( className ) ; } public Collection < ClassNodeWrapper > getAllClassNodes ( ) { return classNodeProvider . getAllClassNodes ( ) ; } public void setClassNodeProvider ( IncludedClassesProvider classNodeProvider ) { this . classNodeProvider = classNodeProvider ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . documentProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . ClassInsertProvider ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProviderGroups ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class InFileClassPartsMerger extends MultiEditProvider { private MergeClassPartInFileConfig config ; public InFileClassPartsMerger ( MergeClassPartInFileConfig config ) { this . config = config ; } @ Override protected Collection < EditProvider > getEditProviders ( ) { EditProviderGroups providerGroups = new EditProviderGroups ( ) ; for ( PartialClassNodeWrapper currentClassPart : config . getCheckedClassParts ( ) ) { if ( currentClassPart == config . getSelectedClassPart ( ) ) { continue ; } DeleteEditProvider delEditProvider = new DeleteEditProvider ( currentClassPart . getWrappedNode ( ) ) ; delEditProvider . setDeleteType ( DeleteEditProvider . DELETE_LINEBREAK_AFTER ) ; providerGroups . add ( currentClassPart . getWrappedNode ( ) . toString ( ) , delEditProvider ) ; if ( currentClassPart . getClassBodyNode ( ) != null ) { providerGroups . add ( Messages . InFileClassPartsMerger_GroupInsertion , new ClassInsertProvider ( currentClassPart . getClassBodyNode ( ) , config . getSelectedClassPart ( ) ) ) ; } } return providerGroups . getAllEditProviders ( ) ; } } package org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class MergeClassPartsInFileConditionChecker extends RefactoringConditionChecker { private MergeClassPartInFileConfig config ; public MergeClassPartsInFileConditionChecker ( MergeClassPartInFileConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( MergeClassPartInFileConfig ) configObj ; config . setClassNodeProvider ( new IncludedClassesProvider ( config . getDocumentProvider ( ) ) ) ; initSelectableClasses ( ) ; } private void initSelectableClasses ( ) { Collection < ClassNodeWrapper > selectableClasses = new ArrayList < ClassNodeWrapper > ( ) ; for ( ClassNodeWrapper currentClassNode : config . getAllClassNodes ( ) ) { if ( currentClassNode . getPartialClassNodesOfFile ( config . getDocumentProvider ( ) . getActiveFileName ( ) ) . size ( ) >= ) selectableClasses . add ( currentClassNode ) ; } config . setSelectableClasses ( selectableClasses ) ; } @ Override protected void checkFinalConditions ( ) { if ( ! isSelectionMergable ( ) ) { addError ( Messages . MergeClassPartsInFileConditionChecker_TooFewParts ) ; } } private boolean isSelectionMergable ( ) { Collection < PartialClassNodeWrapper > checkedClassParts = config . getCheckedClassParts ( ) ; if ( checkedClassParts . isEmpty ( ) ) { return false ; } else if ( checkedClassParts . size ( ) == ) { if ( checkedClassParts . toArray ( ) [ ] . equals ( config . getSelectedClassPart ( ) ) ) { return false ; } } return true ; } @ Override protected void checkInitialConditions ( ) { if ( ! config . hasSelectableClasses ( ) ) { addError ( Messages . MergeClassPartsInFileConditionChecker_NotEnoughPartsFound ) ; } } } package org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String InFileClassPartsMerger_GroupInsertion ; public static String MergeClassPartsInFileConditionChecker_NotEnoughPartsFound ; public static String MergeClassPartsInFileConditionChecker_TooFewParts ; public static String MergeClassPartsInFileRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . MergeClassPartsInFilePage ; public class MergeClassPartsInFileRefactoring extends RubyRefactoring { public static final String NAME = Messages . MergeClassPartsInFileRefactoring_Name ; public MergeClassPartsInFileRefactoring ( ) throws CoreException { super ( NAME ) ; MergeClassPartInFileConfig config = new MergeClassPartInFileConfig ( getDocumentProvider ( ) ) ; MergeClassPartsInFileConditionChecker checker = new MergeClassPartsInFileConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { InFileClassPartsMerger selector = new InFileClassPartsMerger ( config ) ; setEditProvider ( selector ) ; MergeClassPartsInFilePage selectionPage = new MergeClassPartsInFilePage ( config ) ; pages . add ( selectionPage ) ; } } } package org . rubypeople . rdt . refactoring . core ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . ResourcesPlugin ; public class WorkspaceTracker { public final static WorkspaceTracker INSTANCE = new WorkspaceTracker ( ) ; public interface Listener { public void workspaceChanged ( ) ; } private ListenerList fListeners ; private ResourceListener fResourceListener ; private WorkspaceTracker ( ) { fListeners = new ListenerList ( ) ; } private class ResourceListener implements IResourceChangeListener { public void resourceChanged ( IResourceChangeEvent event ) { workspaceChanged ( ) ; } } private void workspaceChanged ( ) { Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { ( ( Listener ) listeners [ i ] ) . workspaceChanged ( ) ; } } public void addListener ( Listener l ) { fListeners . add ( l ) ; if ( fResourceListener == null ) { fResourceListener = new ResourceListener ( ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( fResourceListener ) ; } } public void removeListener ( Listener l ) { if ( fListeners . size ( ) == ) return ; fListeners . remove ( l ) ; if ( fListeners . size ( ) == ) { ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( fResourceListener ) ; fResourceListener = null ; } } } package org . rubypeople . rdt . refactoring . core ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . SafeRunner ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . CompositeChange ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class DynamicValidationStateChange extends CompositeChange implements WorkspaceTracker . Listener { private boolean fListenerRegistered = false ; private RefactoringStatus fValidationState = null ; private long fTimeStamp ; private static final long LIFE_TIME = * * ; public DynamicValidationStateChange ( Change change ) { super ( change . getName ( ) ) ; add ( change ) ; markAsSynthetic ( ) ; } public DynamicValidationStateChange ( String name ) { super ( name ) ; markAsSynthetic ( ) ; } public DynamicValidationStateChange ( String name , Change [ ] changes ) { super ( name , changes ) ; markAsSynthetic ( ) ; } public void initializeValidationData ( IProgressMonitor pm ) { super . initializeValidationData ( pm ) ; WorkspaceTracker . INSTANCE . addListener ( this ) ; fListenerRegistered = true ; fTimeStamp = System . currentTimeMillis ( ) ; } public void dispose ( ) { if ( fListenerRegistered ) { WorkspaceTracker . INSTANCE . removeListener ( this ) ; fListenerRegistered = false ; } super . dispose ( ) ; } public RefactoringStatus isValid ( IProgressMonitor pm ) throws CoreException { if ( fValidationState == null ) { return super . isValid ( pm ) ; } return fValidationState ; } public Change perform ( IProgressMonitor pm ) throws CoreException { final Change [ ] result = new Change [ ] ; IWorkspaceRunnable runnable = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { result [ ] = DynamicValidationStateChange . super . perform ( monitor ) ; } } ; RubyCore . run ( runnable , null , pm ) ; return result [ ] ; } protected Change createUndoChange ( Change [ ] childUndos ) { DynamicValidationStateChange result = new DynamicValidationStateChange ( getName ( ) ) ; for ( int i = ; i < childUndos . length ; i ++ ) { result . add ( childUndos [ i ] ) ; } return result ; } public void workspaceChanged ( ) { long currentTime = System . currentTimeMillis ( ) ; if ( currentTime - fTimeStamp < LIFE_TIME ) return ; fValidationState = RefactoringStatus . createFatalErrorStatus ( Messages . DynamicValidationStateChange_workspace_changed ) ; WorkspaceTracker . INSTANCE . removeListener ( this ) ; fListenerRegistered = false ; Change [ ] children = clear ( ) ; for ( int i = ; i < children . length ; i ++ ) { final Change change = children [ i ] ; SafeRunner . run ( new ISafeRunnable ( ) { public void run ( ) throws Exception { change . dispose ( ) ; } public void handleException ( Throwable exception ) { RubyPlugin . log ( exception ) ; } } ) ; } } } package org . rubypeople . rdt . refactoring . core . inlineclass ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Locale ; import java . util . Map ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterLastMethodInClassOffsetProvider ; import org . rubypeople . rdt . refactoring . util . Constants ; public class ClassInliner implements IMultiFileEditProvider { private final class ClassInsertEditProvider extends InsertEditProvider { private final StringDocumentProvider provider ; private ClassInsertEditProvider ( boolean format , StringDocumentProvider provider ) { super ( format ) ; this . provider = provider ; } @ Override protected Node getInsertNode ( int offset , String document ) { try { Node rootNode = provider . getActiveFileRootNode ( ) ; return SelectionNodeProvider . getSelectedClassNode ( rootNode , ) . getFirstPartialClassNode ( ) . getClassBodyNode ( ) ; } catch ( NoClassNodeException e ) { return provider . getActiveFileRootNode ( ) ; } } @ Override protected int getOffset ( String document ) { AfterLastMethodInClassOffsetProvider offsetProvider = new AfterLastMethodInClassOffsetProvider ( config . getTargetClassPart ( ) , document ) ; return offsetProvider . getOffset ( ) ; } } private static final class ConstructorlessSelfAssginmentReplacer extends ReplaceEditProvider { private final AssignableNode assignment ; private ConstructorlessSelfAssginmentReplacer ( AssignableNode assignment ) { this . assignment = assignment ; } @ Override protected int getOffsetLength ( ) { return assignment . getPosition ( ) . getEndOffset ( ) - assignment . getPosition ( ) . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { Node selfAsgnNode = NodeFactory . createInstAsgnNode ( ( ( INameNode ) assignment ) . getName ( ) , NodeFactory . createSelfNode ( ) ) ; return selfAsgnNode ; } @ Override protected int getOffset ( String document ) { return assignment . getPosition ( ) . getStartOffset ( ) ; } } private final class ConstructorAndSelfAsgnReplacer extends ReplaceEditProvider { private final AssignableNode assignment ; private ConstructorAndSelfAsgnReplacer ( boolean format , boolean trim , AssignableNode assignment ) { super ( format , trim ) ; this . assignment = assignment ; } @ Override protected int getOffsetLength ( ) { ISourcePosition pos = assignment . getPosition ( ) ; return pos . getEndOffset ( ) - pos . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { MethodCallNodeWrapper valueWrapper = new MethodCallNodeWrapper ( assignment . getValueNode ( ) ) ; Node constrReplaceNode = NodeFactory . createMethodCallNode ( createNewConstructorName ( ) , valueWrapper . getArgsNode ( ) ) ; Node selfAsgnNode = NodeFactory . createInstAsgnNode ( ( ( INameNode ) assignment ) . getName ( ) , NodeFactory . createSelfNode ( ) ) ; return NodeFactory . createBlockNode ( false , false , true , constrReplaceNode , selfAsgnNode ) ; } @ Override protected int getOffset ( String document ) { return assignment . getPosition ( ) . getStartOffset ( ) ; } } private static final class CallReplaceEditProvider extends ReplaceEditProvider { private final MethodCallNodeWrapper wrapper ; private final String name ; private CallReplaceEditProvider ( MethodCallNodeWrapper wrapper , String name ) { this . wrapper = wrapper ; this . name = name ; } @ Override protected int getOffsetLength ( ) { ISourcePosition pos = wrapper . getPosition ( ) ; return pos . getEndOffset ( ) - pos . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return NodeFactory . createCallNode ( wrapper . getReceiverNode ( ) , name , wrapper . getArgsNode ( ) ) ; } @ Override protected int getOffset ( String document ) { return wrapper . getPosition ( ) . getStartOffset ( ) ; } } private InlineClassConfig config ; private PartialClassNodeWrapper inlinedClassPart ; public ClassInliner ( InlineClassConfig config ) { this . config = config ; inlinedClassPart = getInlinedClassPart ( ) ; } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { MultiFileEditProvider editProvider = new MultiFileEditProvider ( ) ; addClassDeleteProvider ( editProvider ) ; addConstructorInsertProvider ( editProvider ) ; Collection < AssignableNode > concerningAssignments = addContructorCallReplacer ( editProvider ) ; InsertClassBuilder inlinedClassProvider = new InsertClassBuilder ( config ) ; addCallReplaceProvider ( editProvider , inlinedClassProvider , concerningAssignments ) ; addClassInsertProvider ( editProvider , inlinedClassProvider . getInlinedClass ( inlinedClassPart ) ) ; return editProvider . getFileEditProviders ( ) ; } private void addCallReplaceProvider ( MultiFileEditProvider editProvider , InsertClassBuilder inlinedClassProvider , Collection < AssignableNode > concerningAssignments ) { Map < String , MethodNodeWrapper > concerningMethods = inlinedClassProvider . getMethodsWithNameConflict ( inlinedClassPart ) ; for ( String currentKey : concerningMethods . keySet ( ) ) { MethodNodeWrapper currentMethod = concerningMethods . get ( currentKey ) ; for ( AssignableNode currentAssignment : concerningAssignments ) { String concerningVarName = ( ( INameNode ) currentAssignment ) . getName ( ) ; if ( currentAssignment instanceof InstAsgnNode ) { Collection < MethodNodeWrapper > targetClassMethods = config . getTargetClass ( ) . getMethods ( ) ; for ( MethodNodeWrapper currentTargetMethod : targetClassMethods ) { addCallReplacerForMethod ( editProvider , currentKey , currentMethod , currentTargetMethod , concerningVarName ) ; } } else if ( currentAssignment instanceof LocalAsgnNode ) { MethodNodeWrapper targetConstructor = config . getTargetClass ( ) . getConstructorNode ( ) ; addCallReplacerForMethod ( editProvider , currentKey , currentMethod , targetConstructor , concerningVarName ) ; } } } } private void addCallReplacerForMethod ( MultiFileEditProvider editProvider , String newMethodName , MethodNodeWrapper renamedMethod , MethodNodeWrapper targetMethod , String concerningVarName ) { Collection < Node > calls = NodeProvider . getSubNodes ( targetMethod . getWrappedNode ( ) , CallNode . class ) ; for ( Node currentCall : calls ) { MethodCallNodeWrapper callWrapper = new MethodCallNodeWrapper ( currentCall ) ; if ( concerningVarName . equals ( callWrapper . getReceiverName ( ) ) && callWrapper . getName ( ) . equals ( renamedMethod . getName ( ) ) ) { editProvider . addEditProvider ( new FileEditProvider ( callWrapper . getFileName ( ) , createCallReplaceEditProvider ( callWrapper , newMethodName ) ) ) ; } } } private ReplaceEditProvider createCallReplaceEditProvider ( final MethodCallNodeWrapper callWrapper , final String newName ) { return new CallReplaceEditProvider ( callWrapper , newName ) ; } private Collection < AssignableNode > addContructorCallReplacer ( MultiFileEditProvider editProvider ) { MethodNodeWrapper constructorNode = config . getTargetClass ( ) . getConstructorNode ( ) ; ArrayList < AssignableNode > concerningAssignables = new ArrayList < AssignableNode > ( ) ; for ( AssignableNode currentAssignment : config . findFieldAsgnsOfSource ( constructorNode ) ) { String file = currentAssignment . getPosition ( ) . getFile ( ) ; concerningAssignables . add ( currentAssignment ) ; if ( inlinedClassPart . getExistingConstructors ( ) . isEmpty ( ) ) { editProvider . addEditProvider ( new FileEditProvider ( file , createConstructorlessSelfAsignment ( currentAssignment ) ) ) ; } else { editProvider . addEditProvider ( new FileEditProvider ( file , createConstructorMethodAndSelfAsgnReplacer ( currentAssignment ) ) ) ; } } return concerningAssignables ; } private ReplaceEditProvider createConstructorMethodAndSelfAsgnReplacer ( final AssignableNode assignment ) { return new ConstructorAndSelfAsgnReplacer ( true , true , assignment ) ; } private ReplaceEditProvider createConstructorlessSelfAsignment ( final AssignableNode currentAssignment ) { return new ConstructorlessSelfAssginmentReplacer ( currentAssignment ) ; } private void addConstructorInsertProvider ( MultiFileEditProvider editProvider ) { Collection < MethodNodeWrapper > constructors = inlinedClassPart . getExistingConstructors ( ) ; PartialClassNodeWrapper targetClassPart = config . getTargetClassPart ( ) ; for ( MethodNodeWrapper currentConstructor : constructors ) { ConstructorInliner constructorInliner = new ConstructorInliner ( currentConstructor , targetClassPart , createNewConstructorName ( ) ) ; editProvider . addEditProvider ( new FileEditProvider ( targetClassPart . getFile ( ) , constructorInliner ) ) ; } } private String createNewConstructorName ( ) { String className = inlinedClassPart . getClassName ( ) . toLowerCase ( Locale . ENGLISH ) ; return className + "" + Constants . CONSTRUCTOR_NAME ; } private void addClassInsertProvider ( MultiFileEditProvider editProvider , final StringDocumentProvider inlinedClassDocumentProvider ) { InsertEditProvider classEditProvider = new ClassInsertEditProvider ( true , inlinedClassDocumentProvider ) ; String file = config . getTargetClassPart ( ) . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; editProvider . addEditProvider ( new FileEditProvider ( file , classEditProvider ) ) ; } private void addClassDeleteProvider ( MultiFileEditProvider editProvider ) { DeleteEditProvider classPartDeleter = new DeleteEditProvider ( inlinedClassPart . getWrappedNode ( ) ) ; editProvider . addEditProvider ( new FileEditProvider ( config . getDocumentProvider ( ) . getActiveFileName ( ) , classPartDeleter ) ) ; } public PartialClassNodeWrapper getInlinedClassPart ( ) { IDocumentProvider docProvider = config . getDocumentProvider ( ) ; Node rootNode = docProvider . getActiveFileRootNode ( ) ; try { return SelectionNodeProvider . getSelectedClassNode ( rootNode , config . getCaretPosition ( ) ) . getFirstPartialClassNode ( ) ; } catch ( NoClassNodeException e ) { e . printStackTrace ( ) ; return null ; } } } package org . rubypeople . rdt . refactoring . core . inlineclass ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . InlineClassPage ; public class InlineClassRefactoring extends RubyRefactoring { public final static String NAME = Messages . InlineClassRefactoring_Name ; public InlineClassRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; InlineClassConfig config = new InlineClassConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; InlineClassConditionChecker checker = new InlineClassConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { ClassInliner inliner = new ClassInliner ( config ) ; setEditProvider ( inliner ) ; InlineClassPage page = new InlineClassPage ( config ) ; pages . add ( page ) ; } } } package org . rubypeople . rdt . refactoring . core . inlineclass ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String InlineClassConditionChecker_CannorDerivedClasses ; public static String InlineClassConditionChecker_CannotInlineToItself ; public static String InlineClassConditionChecker_CannotMultipleClassParts ; public static String InlineClassConditionChecker_CannotWithSubclasses ; public static String InlineClassConditionChecker_NoClassSelected ; public static String InlineClassConditionChecker_NoFieldToReference ; public static String InlineClassRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . inlineclass ; import java . io . Serializable ; import java . util . Comparator ; import org . eclipse . text . edits . TextEdit ; public class TextEditComparator implements Comparator < TextEdit > , Serializable { private static final long serialVersionUID = - ; public int compare ( TextEdit o1 , TextEdit o2 ) { if ( o1 . getOffset ( ) < o2 . getOffset ( ) ) { return - ; } else if ( o1 . getOffset ( ) == o2 . getOffset ( ) ) { if ( o1 . getLength ( ) < o2 . getLength ( ) ) { return - ; } else if ( o1 . getOffset ( ) == o2 . getOffset ( ) ) { return ; } else { return ; } } else { return ; } } } package org . rubypeople . rdt . refactoring . core . inlineclass ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . BeforeFirstMethodInClassOffsetProvider ; public class ConstructorInliner extends InsertEditProvider { private MethodNodeWrapper inlinedConstructor ; private PartialClassNodeWrapper targetClass ; private String newName ; public ConstructorInliner ( MethodNodeWrapper inlinedConstructor , PartialClassNodeWrapper targetClass , String newName ) { super ( true ) ; this . newName = newName ; this . inlinedConstructor = inlinedConstructor ; this . targetClass = targetClass ; } @ Override protected Node getInsertNode ( int offset , String document ) { MethodDefNode constructor = inlinedConstructor . getWrappedNode ( ) ; MethodDefNode inlinedConstructor = NodeFactory . createMethodNode ( newName , constructor . getArgsNode ( ) , constructor . getBodyNode ( ) ) ; ISourcePosition constructorPosition = constructor . getPosition ( ) ; inlinedConstructor . setPosition ( constructorPosition ) ; return NodeFactory . createBlockNode ( false , true , inlinedConstructor ) ; } @ Override protected int getOffset ( String document ) { BeforeFirstMethodInClassOffsetProvider offsetProvider = new BeforeFirstMethodInClassOffsetProvider ( targetClass , document ) ; return offsetProvider . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . inlineclass ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class InlineClassConfig implements IRefactoringConfig { private int caretPosition ; private IDocumentProvider docProvider ; private PartialClassNodeWrapper targetClassPart ; private Collection < ClassNodeWrapper > possibleTargetClasses ; private ClassNodeWrapper sourceClass ; public InlineClassConfig ( DocumentProvider docProvider , int caretPosition ) { super ( ) ; this . caretPosition = caretPosition ; this . docProvider = docProvider ; } public int getCaretPosition ( ) { return caretPosition ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public PartialClassNodeWrapper getTargetClassPart ( ) { return targetClassPart ; } public void setTargetClassPart ( PartialClassNodeWrapper targetClassPart ) { this . targetClassPart = targetClassPart ; } public ClassNodeWrapper getTargetClass ( ) { IncludedClassesProvider classesProvider = new IncludedClassesProvider ( docProvider ) ; ClassNodeWrapper classNode = classesProvider . getClassNode ( targetClassPart . getClassName ( ) ) ; return classNode ; } public void setPossibleTargetClasses ( Collection < ClassNodeWrapper > possibleClassNodes ) { this . possibleTargetClasses = possibleClassNodes ; } public Collection < ClassNodeWrapper > getPossibleTargetClasses ( ) { return this . possibleTargetClasses ; } public ClassNodeWrapper getSourceClass ( ) { return sourceClass ; } public void setSourceClass ( ClassNodeWrapper sourceClass ) { this . sourceClass = sourceClass ; } public Collection < AssignableNode > findFieldAsgnsOfSource ( MethodNodeWrapper constructorNode ) { ArrayList < AssignableNode > assignmentsFound = new ArrayList < AssignableNode > ( ) ; Collection < Node > assignmentNodes = NodeProvider . getSubNodes ( constructorNode . getWrappedNode ( ) , LocalAsgnNode . class , InstAsgnNode . class ) ; for ( Node currentNode : assignmentNodes ) { AssignableNode currentAssignment = ( AssignableNode ) currentNode ; Node valueNode = currentAssignment . getValueNode ( ) ; MethodCallNodeWrapper valueWrapper = new MethodCallNodeWrapper ( valueNode ) ; if ( valueWrapper . getType ( ) == MethodCallNodeWrapper . INVALID_TYPE ) { continue ; } if ( valueWrapper . getName ( ) . equals ( "" ) && valueWrapper . getReceiverNode ( ) instanceof ConstNode && ( ( ConstNode ) valueWrapper . getReceiverNode ( ) ) . getName ( ) . equals ( sourceClass . getName ( ) ) ) { assignmentsFound . add ( currentAssignment ) ; } } return assignmentsFound ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . inlineclass ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import java . util . TreeSet ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . renamefield . FieldRenamer ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConfig ; import org . rubypeople . rdt . refactoring . core . renamemethod . MethodRenamer ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConfig ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NameHelper ; public class InsertClassBuilder { private InlineClassConfig config ; public InsertClassBuilder ( InlineClassConfig config ) { this . config = config ; } public StringDocumentProvider getInlinedClass ( PartialClassNodeWrapper inlinedClassPart ) { MultiTextEdit prechanges = new MultiTextEdit ( ) ; StringDocumentProvider inlinedClassDocumentProvider = getDocumentProviderForClassPart ( inlinedClassPart ) ; ClassNodeWrapper inlinedClass = inlinedClassDocumentProvider . getClassNodeProvider ( ) . getAllClassNodes ( ) . iterator ( ) . next ( ) ; PartialClassNodeWrapper contextfreeClassPart = inlinedClass . getFirstPartialClassNode ( ) ; Map < String , MethodNodeWrapper > conflictingMethods = getMethodsWithNameConflict ( contextfreeClassPart ) ; Map < String , FieldNodeWrapper > conflictingFields = getFieldsWithNameConflict ( contextfreeClassPart ) ; prechanges . addChildren ( getMethodRenameEdits ( conflictingMethods , inlinedClassDocumentProvider ) ) ; prechanges . addChildren ( getFieldRenameEdits ( conflictingFields , inlinedClassDocumentProvider ) ) ; prechanges . addChildren ( getConstructorDeleteEdits ( inlinedClassDocumentProvider ) ) ; return new StringDocumentProvider ( inlinedClassDocumentProvider . getActiveFileName ( ) + "" , applyPrechanges ( prechanges , inlinedClassDocumentProvider ) ) ; } private TextEdit [ ] getMethodRenameEdits ( Map < String , MethodNodeWrapper > conflictingMethods , StringDocumentProvider inlinedClassDocumentProvider ) { ArrayList < TextEdit > edits = new ArrayList < TextEdit > ( ) ; for ( String currentMethodName : conflictingMethods . keySet ( ) ) { MethodNodeWrapper currentMethod = conflictingMethods . get ( currentMethodName ) ; int methodPos = currentMethod . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ; RenameMethodConfig config = new RenameMethodConfig ( inlinedClassDocumentProvider , methodPos ) ; new RenameMethodConditionChecker ( config ) ; config . setNewName ( currentMethodName ) ; MethodRenamer renamer = new MethodRenamer ( config ) ; fillTextEdits ( inlinedClassDocumentProvider , edits , renamer ) ; } filterEditsInConstructor ( edits ) ; return edits . toArray ( new TextEdit [ edits . size ( ) ] ) ; } private void filterEditsInConstructor ( Collection < TextEdit > edits ) { ArrayList < TextEdit > removeList = new ArrayList < TextEdit > ( ) ; Collection < MethodNodeWrapper > constructorNodes = config . getSourceClass ( ) . getExistingConstructors ( ) ; for ( TextEdit currentEdit : edits ) { int editOffset = currentEdit . getOffset ( ) ; for ( MethodNodeWrapper currentConstructor : constructorNodes ) { if ( SelectionNodeProvider . nodeContainsPosition ( currentConstructor . getWrappedNode ( ) , editOffset ) ) { removeList . add ( currentEdit ) ; } } } for ( TextEdit currentRevomable : removeList ) { edits . remove ( currentRevomable ) ; } } private void fillTextEdits ( StringDocumentProvider inlinedClassDocumentProvider , Collection < TextEdit > edits , IMultiFileEditProvider renamer ) { for ( FileMultiEditProvider currentMultiProvider : renamer . getFileEditProviders ( ) ) { for ( EditProvider currentEditProvider : currentMultiProvider . getEditProviders ( ) ) { edits . add ( currentEditProvider . getEdit ( inlinedClassDocumentProvider . getActiveFileContent ( ) ) ) ; } } } private TextEdit [ ] getFieldRenameEdits ( Map < String , FieldNodeWrapper > conflictingFields , StringDocumentProvider inlinedClassDocumentProvider ) { TreeSet < TextEdit > edits = new TreeSet < TextEdit > ( new TextEditComparator ( ) ) ; for ( String newFieldName : conflictingFields . keySet ( ) ) { FieldNodeWrapper currentField = conflictingFields . get ( newFieldName ) ; int fieldPos = currentField . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ; RenameFieldConfig config = new RenameFieldConfig ( inlinedClassDocumentProvider , fieldPos ) ; new RenameFieldConditionChecker ( config ) ; config . setNewName ( newFieldName . replaceAll ( "" , "" ) ) ; setSelectedCalls ( config ) ; FieldRenamer renamer = new FieldRenamer ( config ) ; fillTextEdits ( inlinedClassDocumentProvider , edits , renamer ) ; } filterEditsInConstructor ( edits ) ; return edits . toArray ( new TextEdit [ edits . size ( ) ] ) ; } private void setSelectedCalls ( RenameFieldConfig config ) { String fieldName = config . getSelectedName ( ) ; boolean concernsClassField = config . concernsClassField ( ) ; config . setSelectedCalls ( config . getFieldProvider ( ) . getFieldItems ( fieldName , concernsClassField ) ) ; } public Map < String , MethodNodeWrapper > getMethodsWithNameConflict ( PartialClassNodeWrapper inlinedClassPart ) { Collection < MethodNodeWrapper > inlinedMethods = inlinedClassPart . getMethods ( ) ; HashMap < String , MethodNodeWrapper > conflictingMethods = new HashMap < String , MethodNodeWrapper > ( ) ; for ( MethodNodeWrapper currentInlinedMethod : inlinedMethods ) { addConflictingMethods ( conflictingMethods , currentInlinedMethod ) ; } return conflictingMethods ; } private void addConflictingMethods ( Map < String , MethodNodeWrapper > conflictingMethods , MethodNodeWrapper currentInlinedMethod ) { if ( ! currentInlinedMethod . isConstructor ( ) && NameHelper . methodnameExistsInClassPart ( currentInlinedMethod . getName ( ) , config . getTargetClass ( ) ) ) { String newName = NameHelper . createMethodName ( currentInlinedMethod , config . getTargetClass ( ) ) ; conflictingMethods . put ( newName , currentInlinedMethod ) ; } } private Map < String , FieldNodeWrapper > getFieldsWithNameConflict ( PartialClassNodeWrapper inlinedClassPart ) { Collection < FieldNodeWrapper > inlinedFields = inlinedClassPart . getFields ( ) ; HashMap < String , FieldNodeWrapper > conflictingFields = new HashMap < String , FieldNodeWrapper > ( ) ; for ( FieldNodeWrapper currentInlinedField : inlinedFields ) { addConflictingFields ( conflictingFields , currentInlinedField ) ; } return conflictingFields ; } private void addConflictingFields ( Map < String , FieldNodeWrapper > conflictingFields , FieldNodeWrapper currentInlinedField ) { if ( NameHelper . fieldnameExistsInClass ( currentInlinedField . getName ( ) , config . getTargetClass ( ) ) ) { String newName = NameHelper . createFieldName ( currentInlinedField , config . getTargetClass ( ) ) ; conflictingFields . put ( newName , currentInlinedField ) ; } } private StringDocumentProvider getDocumentProviderForClassPart ( PartialClassNodeWrapper inlinedClassPart ) { ISourcePosition classPartPosition = inlinedClassPart . getWrappedNode ( ) . getPosition ( ) ; String activeFileContent = config . getDocumentProvider ( ) . getActiveFileContent ( ) ; String inlinedClassDocument = activeFileContent . substring ( classPartPosition . getStartOffset ( ) , classPartPosition . getEndOffset ( ) ) ; String fileName = "" + config . getDocumentProvider ( ) . getActiveFileName ( ) ; StringDocumentProvider inlinedClassDocumentProvider = new StringDocumentProvider ( fileName , inlinedClassDocument ) ; return inlinedClassDocumentProvider ; } private TextEdit [ ] getConstructorDeleteEdits ( StringDocumentProvider inlinedClassDocument ) { ArrayList < TextEdit > constructorDeleters = new ArrayList < TextEdit > ( ) ; Node rootNode = inlinedClassDocument . getActiveFileRootNode ( ) ; ClassNodeWrapper classNode ; try { classNode = SelectionNodeProvider . getSelectedClassNode ( rootNode , ) ; } catch ( NoClassNodeException e ) { e . printStackTrace ( ) ; return constructorDeleters . toArray ( new TextEdit [ constructorDeleters . size ( ) ] ) ; } Collection < MethodNodeWrapper > constructors = classNode . getExistingConstructors ( ) ; for ( MethodNodeWrapper currentConstructor : constructors ) { DeleteEditProvider deleteEditProvider = new DeleteEditProvider ( currentConstructor . getWrappedNode ( ) ) ; constructorDeleters . add ( deleteEditProvider . getEdit ( inlinedClassDocument . getActiveFileContent ( ) ) ) ; } return constructorDeleters . toArray ( new TextEdit [ constructorDeleters . size ( ) ] ) ; } private String applyPrechanges ( MultiTextEdit prechanges , StringDocumentProvider inlinedClassDocumentProvider ) { Document inlinedPart = new Document ( inlinedClassDocumentProvider . getActiveFileContent ( ) ) ; try { prechanges . apply ( inlinedPart ) ; } catch ( MalformedTreeException e ) { e . printStackTrace ( ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } return inlinedPart . get ( ) ; } } package org . rubypeople . rdt . refactoring . core . inlineclass ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . util . Constants ; public class InlineClassConditionChecker extends RefactoringConditionChecker { private InlineClassConfig config ; private IDocumentProvider docProvider ; private ClassNodeWrapper selectedClass ; public InlineClassConditionChecker ( InlineClassConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( InlineClassConfig ) configObj ; docProvider = config . getDocumentProvider ( ) ; intiSourceClass ( ) ; initPossibleTargetClasses ( ) ; } private void intiSourceClass ( ) { int caretPosition = config . getCaretPosition ( ) ; Node rootNode = docProvider . getActiveFileRootNode ( ) ; try { selectedClass = SelectionNodeProvider . getSelectedClassNode ( rootNode , caretPosition ) ; config . setSourceClass ( selectedClass ) ; } catch ( NoClassNodeException e ) { } } @ Override protected void checkFinalConditions ( ) { if ( equalClassPartPosition ( selectedClass . getFirstPartialClassNode ( ) , config . getTargetClassPart ( ) ) ) { addError ( Messages . InlineClassConditionChecker_CannotInlineToItself ) ; } } @ Override protected void checkInitialConditions ( ) { if ( selectedClass == null ) { addError ( Messages . InlineClassConditionChecker_NoClassSelected ) ; return ; } ClassNodeProvider classesProvider = docProvider . getProjectClassNodeProvider ( ) ; Collection < PartialClassNodeWrapper > inlinedClass = classesProvider . getClassNode ( selectedClass . getName ( ) ) . getPartialClassNodes ( ) ; if ( inlinedClass . size ( ) > ) { addError ( Messages . InlineClassConditionChecker_CannotMultipleClassParts ) ; } if ( classesProvider . getSubClassesOf ( selectedClass . getName ( ) ) . size ( ) > ) { addError ( Messages . InlineClassConditionChecker_CannotWithSubclasses ) ; } if ( ! selectedClass . getSuperClassName ( ) . equals ( Constants . OBJECT_NAME ) ) { addError ( Messages . InlineClassConditionChecker_CannorDerivedClasses ) ; } if ( config . getPossibleTargetClasses ( ) . isEmpty ( ) ) { addError ( Messages . InlineClassConditionChecker_NoFieldToReference ) ; } } public void initPossibleTargetClasses ( ) { ClassNodeProvider classesProvider = config . getDocumentProvider ( ) . getIncludedClassNodeProvider ( ) ; Collection < ClassNodeWrapper > classNodes = classesProvider . getAllClassNodes ( ) ; ArrayList < ClassNodeWrapper > possibleClassNodes = new ArrayList < ClassNodeWrapper > ( ) ; Node rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; try { ClassNodeWrapper selectedClass = SelectionNodeProvider . getSelectedClassNode ( rootNode , config . getCaretPosition ( ) ) ; for ( ClassNodeWrapper currentClass : classNodes ) { if ( isPossibleTarget ( selectedClass , currentClass ) ) { possibleClassNodes . add ( currentClass ) ; } } } catch ( NoClassNodeException e ) { } config . setPossibleTargetClasses ( possibleClassNodes ) ; } private boolean isPossibleTarget ( ClassNodeWrapper selectedClass , ClassNodeWrapper targetClass ) { String inlinedClassName = selectedClass . getName ( ) ; String targetClassName = targetClass . getName ( ) ; if ( targetClassName . equals ( inlinedClassName ) ) { return false ; } MethodNodeWrapper constructor = targetClass . getConstructorNode ( ) ; Collection < AssignableNode > matchingAssignmentsFound = config . findFieldAsgnsOfSource ( constructor ) ; if ( matchingAssignmentsFound . isEmpty ( ) ) { return false ; } return true ; } private boolean equalClassPartPosition ( PartialClassNodeWrapper part1 , PartialClassNodeWrapper part2 ) { ISourcePosition first = part1 . getWrappedNode ( ) . getPosition ( ) ; ISourcePosition second = part2 . getWrappedNode ( ) . getPosition ( ) ; return ( first . getFile ( ) . equals ( second . getFile ( ) ) && first . getStartOffset ( ) == second . getStartOffset ( ) && first . getEndOffset ( ) == second . getEndOffset ( ) ) ; } } package org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . MergeWithExternalClassPartsPage ; public class MergeWithExternalClassPartsRefactoring extends RubyRefactoring { public static final String NAME = Messages . getString ( "" ) ; private ExternalClassPartsMerger merger ; public MergeWithExternalClassPartsRefactoring ( ) { super ( NAME ) ; MergeWithExternalClassPartConfig config = new MergeWithExternalClassPartConfig ( getDocumentProvider ( ) ) ; MergeWithExternalClassPartsConditionChecker checker = new MergeWithExternalClassPartsConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { merger = new ExternalClassPartsMerger ( config ) ; setEditProvider ( merger ) ; MergeWithExternalClassPartsPage page = new MergeWithExternalClassPartsPage ( merger ) ; pages . add ( page ) ; } } } package org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiFileEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . IChildrenProvider ; import org . rubypeople . rdt . refactoring . ui . IItemSelectionReceiver ; import org . rubypeople . rdt . refactoring . ui . TreeContentProvider ; public class ExternalClassPartsMerger extends TreeContentProvider implements IItemSelectionReceiver , IMultiFileEditProvider { private ArrayList < MergeTreeClassItem > treeItems ; private String activeFile ; private MergeWithExternalClassPartConfig config ; private Object [ ] checkedElements ; public ExternalClassPartsMerger ( MergeWithExternalClassPartConfig config ) { this . config = config ; activeFile = config . getDocumentProvider ( ) . getActiveFileName ( ) ; initClassesTree ( config . getClassNodeProvider ( ) ) ; } private void initClassesTree ( ClassNodeProvider classesProvider ) { treeItems = new ArrayList < MergeTreeClassItem > ( ) ; Collection < ClassNodeWrapper > classes = classesProvider . getAllClassNodes ( ) ; for ( ClassNodeWrapper currentClassNode : classes ) { addTreeItem ( currentClassNode ) ; } } private void addTreeItem ( ClassNodeWrapper classWrapper ) { Collection < PartialClassNodeWrapper > classParts = classWrapper . getPartialClassNodes ( ) ; Collection < PartialClassNodeWrapper > localParts = classWrapper . getPartialClassNodesOfFile ( activeFile ) ; classParts . removeAll ( localParts ) ; if ( ! classParts . isEmpty ( ) ) { for ( PartialClassNodeWrapper currentClassPart : localParts ) treeItems . add ( new MergeTreeClassItem ( currentClassPart , classWrapper ) ) ; } } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { MultiFileEditProvider multiProvider = new MultiFileEditProvider ( ) ; for ( Object item : checkedElements ) { FileEditProvider editProvider = null ; if ( item instanceof MergeTreeFileItem ) { MergeTreeFileItem fileItem = ( MergeTreeFileItem ) item ; editProvider = new FileEditProvider ( fileItem . toString ( ) , fileItem ) ; if ( fileItem . getInsertedNodeWrapper ( ) . getClassBodyNode ( ) == null ) { continue ; } } else if ( item instanceof MergeTreeClassItem ) { MergeTreeClassItem classItem = ( MergeTreeClassItem ) item ; editProvider = new FileEditProvider ( classItem . getPath ( ) , classItem ) ; } multiProvider . addEditProvider ( editProvider ) ; } return multiProvider . getFileEditProviders ( ) ; } @ Override public Object [ ] getElements ( Object inputElement ) { return treeItems . toArray ( ) ; } public void setSelectedItems ( Object [ ] checkedElements ) { this . checkedElements = checkedElements . clone ( ) ; config . setSelectionEmpty ( checkedElements . length == ) ; } public class MergeTreeClassItem extends DeleteEditProvider implements IChildrenProvider , ClassPartTreeItem { PartialClassNodeWrapper classPart ; ClassNodeWrapper wholeClass ; ArrayList < MergeTreeFileItem > classParts ; public MergeTreeClassItem ( PartialClassNodeWrapper classPart , ClassNodeWrapper wholeClass ) { super ( classPart . getWrappedNode ( ) ) ; this . classPart = classPart ; this . wholeClass = wholeClass ; initClassParts ( ) ; } private void initClassParts ( ) { classParts = new ArrayList < MergeTreeFileItem > ( ) ; Collection < PartialClassNodeWrapper > partialClasses = wholeClass . getPartialClassNodes ( ) ; for ( PartialClassNodeWrapper currentClassPart : partialClasses ) { String file = currentClassPart . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; if ( activeFile . equals ( file ) ) { continue ; } classParts . add ( new MergeTreeFileItem ( currentClassPart , classPart ) ) ; } } public Object [ ] getChildren ( ) { return classParts . toArray ( ) ; } public Collection < MergeTreeFileItem > getClassParts ( ) { return classParts ; } public boolean hasChildren ( ) { return true ; } private String getPath ( ) { return config . getDocumentProvider ( ) . getActiveFileName ( ) ; } public String toString ( ) { return classPart . getClassName ( ) ; } public PartialClassNodeWrapper getClassPartWrapper ( ) { return classPart ; } } public static class MergeTreeFileItem extends ClassInsertProvider implements ClassPartTreeItem { private PartialClassNodeWrapper classNode ; private PartialClassNodeWrapper insertedNode ; public MergeTreeFileItem ( PartialClassNodeWrapper classNode , PartialClassNodeWrapper classPart ) { super ( classPart . getClassBodyNode ( ) , classNode ) ; this . classNode = classNode ; this . insertedNode = classPart ; } public String toString ( ) { return classNode . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; } public PartialClassNodeWrapper getClassPartWrapper ( ) { return classNode ; } public PartialClassNodeWrapper getInsertedNodeWrapper ( ) { return insertedNode ; } } public ArrayList < MergeTreeClassItem > getTreeItems ( ) { return treeItems ; } } package org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public interface ClassPartTreeItem { public PartialClassNodeWrapper getClassPartWrapper ( ) ; } package org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterLastMethodInClassOffsetProvider ; public class ClassInsertProvider extends InsertEditProvider { Node classBody ; PartialClassNodeWrapper destinationClass ; public ClassInsertProvider ( Node classBody , PartialClassNodeWrapper classNodeWrapper ) { super ( true ) ; this . classBody = classBody ; this . destinationClass = classNodeWrapper ; } @ Override protected Node getInsertNode ( int offset , String document ) { boolean endNewLine = lastEditInGroup && ! isNextLineEmpty ( offset , document ) ; return NodeFactory . createBlockNode ( true , endNewLine , classBody ) ; } @ Override protected int getOffset ( String document ) { ClassNodeWrapper destClassWrapper = new ClassNodeWrapper ( destinationClass ) ; AfterLastMethodInClassOffsetProvider offsetProvider = new AfterLastMethodInClassOffsetProvider ( destClassWrapper , document ) ; return offsetProvider . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; public class Messages { private static final String BUNDLE_NAME = "" ; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle . getBundle ( BUNDLE_NAME ) ; private Messages ( ) { } public static String getString ( String key ) { try { return RESOURCE_BUNDLE . getString ( key ) ; } catch ( MissingResourceException e ) { return '' + key + '' ; } } } package org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class MergeWithExternalClassPartConfig implements IRefactoringConfig { private ClassNodeProvider classNodeProvider ; private IDocumentProvider documentProvider ; private boolean selectionEmpty ; public MergeWithExternalClassPartConfig ( IDocumentProvider documentProvider ) { this . documentProvider = documentProvider ; selectionEmpty = true ; } public IDocumentProvider getDocumentProvider ( ) { return documentProvider ; } public ClassNodeProvider getClassNodeProvider ( ) { return classNodeProvider ; } public boolean hasClassParts ( ) { return ! classNodeProvider . getAllClassNodes ( ) . isEmpty ( ) ; } public boolean isSelectionEmpty ( ) { return selectionEmpty ; } public void setSelectionEmpty ( boolean selectioEmpty ) { this . selectionEmpty = selectioEmpty ; } public boolean hasClassWithExternalPart ( ) { ClassNodeProvider activeFileClassNodeProvider = documentProvider . getClassNodeProvider ( ) ; for ( ClassNodeWrapper aktClassNode : activeFileClassNodeProvider . getAllClassNodes ( ) ) { String className = aktClassNode . getName ( ) ; ClassNodeWrapper wholeClass = classNodeProvider . getClassNode ( className ) ; for ( PartialClassNodeWrapper aktPart : wholeClass . getPartialClassNodes ( ) ) { if ( ! aktPart . getFile ( ) . equals ( documentProvider . getActiveFileName ( ) ) ) { return true ; } } } return false ; } public void setClassNodeProvider ( ClassNodeProvider classNodeProvider ) { this . classNodeProvider = classNodeProvider ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . documentProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; public class MergeWithExternalClassPartsConditionChecker extends RefactoringConditionChecker { private MergeWithExternalClassPartConfig config ; public MergeWithExternalClassPartsConditionChecker ( MergeWithExternalClassPartConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( MergeWithExternalClassPartConfig ) configObj ; config . setClassNodeProvider ( config . getDocumentProvider ( ) . getIncludedClassNodeProvider ( ) ) ; } @ Override protected void checkFinalConditions ( ) { if ( config . isSelectionEmpty ( ) ) { addError ( Messages . getString ( "" ) ) ; } } @ Override protected void checkInitialConditions ( ) { if ( ! config . hasClassParts ( ) ) { addError ( Messages . getString ( "" ) ) ; } else if ( ! config . hasClassWithExternalPart ( ) ) { addError ( Messages . getString ( "" ) ) ; } } } package org . rubypeople . rdt . refactoring . core ; import java . util . Collection ; import java . util . Map ; public interface IRefactoringConditionChecker { public static final String ERRORS = "" ; public static final String WARNING = "" ; public Map < String , Collection < String > > getInitialMessages ( ) ; public Map < String , Collection < String > > getFinalMessages ( ) ; public boolean shouldPerform ( ) ; } package org . rubypeople . rdt . refactoring . core . renamemodule ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . SimpleNodeEditProvider ; public class IncludeRenameEditProvider { private RenameModuleConfig config ; public IncludeRenameEditProvider ( RenameModuleConfig config ) { this . config = config ; } public Collection < FileEditProvider > getEditProviders ( ) { Collection < FileEditProvider > edits = new ArrayList < FileEditProvider > ( ) ; Collection < ModuleSpecifierWrapper > wrappers = config . getIncludes ( ) ; wrappers . addAll ( config . getSelectedCalls ( ) ) ; for ( ModuleSpecifierWrapper node : wrappers ) { node . setNewName ( config . getOriginalName ( ) , config . getNewName ( ) ) ; edits . add ( new FileEditProvider ( node . getWrappedNode ( ) . getPosition ( ) . getFile ( ) , new SimpleNodeEditProvider ( node . getWrappedNode ( ) ) ) ) ; } return edits ; } } package org . rubypeople . rdt . refactoring . core . renamemodule ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ConstNode ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . SimpleNodeEditProvider ; public class ModuleMethodDefRenameEditProvider { private final Collection < ConstNode > nodes ; private final String newName ; public ModuleMethodDefRenameEditProvider ( Collection < ConstNode > nodes , String newName ) { this . nodes = nodes ; this . newName = newName ; } public Collection < FileEditProvider > getEditProviders ( ) { Collection < FileEditProvider > edits = new ArrayList < FileEditProvider > ( ) ; for ( ConstNode node : nodes ) { node . setName ( newName ) ; edits . add ( new FileEditProvider ( node . getPosition ( ) . getFile ( ) , new SimpleNodeEditProvider ( node ) ) ) ; } return edits ; } } package org . rubypeople . rdt . refactoring . core . renamemodule ; import java . util . ArrayList ; import org . rubypeople . rdt . refactoring . core . ConstNameValidator ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . NewNameListener ; import org . rubypeople . rdt . refactoring . ui . pages . OccurenceReplaceSelectionPage ; import org . rubypeople . rdt . refactoring . ui . pages . RenamePage ; public class RenameModuleRefactoring extends RubyRefactoring { public static final String NAME = "" ; public RenameModuleRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; RenameModuleConfig renameModuleConfig = new RenameModuleConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; RenameModuleConditionChecker conditionChecker = new RenameModuleConditionChecker ( renameModuleConfig ) ; setRefactoringConditionChecker ( conditionChecker ) ; if ( conditionChecker . shouldPerform ( ) ) { RenameModuleEditProvider editProvider = new RenameModuleEditProvider ( renameModuleConfig ) ; setEditProvider ( editProvider ) ; pages . add ( new RenamePage ( NAME , renameModuleConfig . getOriginalName ( ) , new NewNameListener ( renameModuleConfig , new ConstNameValidator ( ) , new ArrayList < String > ( ) ) ) ) ; if ( ! renameModuleConfig . getPossibleCalls ( ) . isEmpty ( ) ) { pages . add ( new OccurenceReplaceSelectionPage ( renameModuleConfig , renameModuleConfig . getDocumentProvider ( ) ) ) ; } } } } package org . rubypeople . rdt . refactoring . core . renamemodule ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; public class ModuleIncludeFinder { private final IDocumentProvider document ; public ModuleIncludeFinder ( IDocumentProvider document ) { this . document = document ; } public Collection < ModuleSpecifierWrapper > find ( String name ) { ArrayList < ModuleSpecifierWrapper > includes = new ArrayList < ModuleSpecifierWrapper > ( ) ; for ( ModuleSpecifierWrapper includeWrapper : findAllIncludes ( ) ) { if ( includeWrapper . getFullName ( ) . equals ( name ) ) { includes . add ( includeWrapper ) ; } } return includes ; } private ArrayList < ModuleSpecifierWrapper > findAllIncludes ( ) { ArrayList < ModuleSpecifierWrapper > includes = new ArrayList < ModuleSpecifierWrapper > ( ) ; for ( ClassNodeWrapper classNodeWrapper : document . getIncludedClassNodeProvider ( ) . getAllClassNodes ( ) ) { includes . addAll ( classNodeWrapper . getIncludes ( ) ) ; } return includes ; } } package org . rubypeople . rdt . refactoring . core . renamemodule ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . renamemethod . NodeSelector ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ModuleNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . INewNameReceiver ; public class RenameModuleConfig implements IRefactoringConfig , INewNameReceiver , NodeSelector { private IDocumentProvider doc ; private final int carretPosition ; private ModuleNodeWrapper selectedModule ; private String newName ; private Collection < ModuleNodeWrapper > moduleParts ; private String originalFullName ; private String originalName ; private Collection < ? extends INodeWrapper > possibleCalls ; private Collection < ? extends INodeWrapper > selectedCalls ; private Collection < ModuleSpecifierWrapper > includes ; private Collection < String > allModuleNames ; public RenameModuleConfig ( IDocumentProvider doc , int carretPosition ) { this . doc = doc ; this . carretPosition = carretPosition ; } public IDocumentProvider getDocumentProvider ( ) { return doc ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . doc = new DocumentWithIncluding ( doc ) ; } public void setNewName ( String newName ) { this . newName = newName ; } public int getCarretPosition ( ) { return carretPosition ; } public ModuleNodeWrapper getSelectedModule ( ) { return selectedModule ; } public void setSelectedModule ( ModuleNodeWrapper selectedModule ) { this . selectedModule = selectedModule ; originalFullName = selectedModule . getFullName ( ) ; originalName = selectedModule . getName ( ) ; } public String getNewName ( ) { return newName ; } public void setModuleParts ( Collection < ModuleNodeWrapper > moduleParts ) { this . moduleParts = moduleParts ; } public Collection < ModuleNodeWrapper > getModuleParts ( ) { return moduleParts ; } public String getOriginalFullName ( ) { return originalFullName ; } public String getOriginalName ( ) { return originalName ; } public Collection < ? extends INodeWrapper > getPossibleCalls ( ) { return possibleCalls ; } public Collection < ModuleSpecifierWrapper > getSelectedCalls ( ) { return ( Collection < ModuleSpecifierWrapper > ) selectedCalls ; } public void setPossibleCalls ( Collection < ? extends INodeWrapper > possibleCalls ) { this . possibleCalls = possibleCalls ; } public void setSelectedCalls ( Collection < ? extends INodeWrapper > selectedCalls ) { this . selectedCalls = selectedCalls ; } public void setIncludes ( Collection < ModuleSpecifierWrapper > includes ) { this . includes = includes ; } public Collection < ModuleSpecifierWrapper > getIncludes ( ) { return includes ; } public Collection < String > getAllModuleNames ( ) { return allModuleNames ; } public void setAllModuleNames ( Collection < String > allModuleNames ) { this . allModuleNames = allModuleNames ; } } package org . rubypeople . rdt . refactoring . core . renamemodule ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . IScopingNode ; import org . rubypeople . rdt . refactoring . core . ModuleNodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . ScopingNodeRenameEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ModuleNodeWrapper ; public class RenameModuleEditProvider implements IMultiFileEditProvider { private final RenameModuleConfig config ; public RenameModuleEditProvider ( RenameModuleConfig config ) { this . config = config ; } private ScopingNodeRenameEditProvider getModuleEditProvider ( ) { ArrayList < IScopingNode > modules = new ArrayList < IScopingNode > ( ) ; for ( ModuleNodeWrapper node : config . getModuleParts ( ) ) { modules . add ( node . getWrappedNode ( ) ) ; } return new ScopingNodeRenameEditProvider ( modules , config . getNewName ( ) ) ; } private ModuleMethodDefRenameEditProvider getModuleModuleMethodDefEditProvider ( ) { return new ModuleMethodDefRenameEditProvider ( ModuleNodeProvider . getAllModuleMethodDefinitions ( config . getModuleParts ( ) ) , config . getNewName ( ) ) ; } private IncludeRenameEditProvider getIncludeRenameEditProvider ( ) { return new IncludeRenameEditProvider ( config ) ; } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { MultiFileEditProvider fileEdits = new MultiFileEditProvider ( ) ; fileEdits . addEditProviders ( getModuleEditProvider ( ) . getEditProviders ( ) ) ; fileEdits . addEditProviders ( getModuleModuleMethodDefEditProvider ( ) . getEditProviders ( ) ) ; fileEdits . addEditProviders ( getIncludeRenameEditProvider ( ) . getEditProviders ( ) ) ; return fileEdits . getFileEditProviders ( ) ; } } package org . rubypeople . rdt . refactoring . core . renamemodule ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import org . jruby . ast . ClassNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . ModuleNodeProvider ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . nodewrapper . ModuleNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NameHelper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class RenameModuleConditionChecker extends RefactoringConditionChecker { public static final String DEFAULT_ERROR = "" ; private RenameModuleConfig config ; public RenameModuleConditionChecker ( IRefactoringConfig config ) { super ( config ) ; } @ Override protected void checkInitialConditions ( ) { if ( config . getSelectedModule ( ) == null ) { addError ( DEFAULT_ERROR ) ; } } @ Override protected void checkFinalConditions ( ) { if ( config . getOriginalName ( ) . equals ( config . getNewName ( ) ) ) { addWarning ( "" ) ; } if ( config . getAllModuleNames ( ) . contains ( config . getNewName ( ) ) ) { addWarning ( "" ) ; } } @ Override public void init ( IRefactoringConfig configObj ) { config = ( RenameModuleConfig ) configObj ; ModuleNodeWrapper selectedModule = ModuleNodeProvider . getSelectedModuleNode ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , config . getCarretPosition ( ) ) ; if ( selectedModule == null || caretIsNotOnModuleName ( selectedModule ) ) { return ; } config . setSelectedModule ( selectedModule ) ; config . setNewName ( config . getOriginalName ( ) ) ; config . setModuleParts ( ModuleNodeProvider . findOtherParts ( config . getDocumentProvider ( ) , config . getSelectedModule ( ) ) ) ; config . setIncludes ( new ModuleIncludeFinder ( config . getDocumentProvider ( ) ) . find ( config . getOriginalFullName ( ) ) ) ; config . setPossibleCalls ( findPossibleCalls ( ) ) ; config . setSelectedCalls ( config . getPossibleCalls ( ) ) ; config . setAllModuleNames ( getAllModuleNames ( ) ) ; } private Collection < String > getAllModuleNames ( ) { Collection < String > names = new ArrayList < String > ( ) ; for ( ModuleNodeWrapper module : ModuleNodeProvider . findAllModules ( config . getDocumentProvider ( ) ) ) { names . add ( module . getFullName ( ) ) ; } return names ; } private ArrayList < ModuleSpecifierWrapper > findPossibleCalls ( ) { ArrayList < ModuleSpecifierWrapper > calls = new ArrayList < ModuleSpecifierWrapper > ( ) ; Collection < Node > toSkip = collectAllModulePartsAndIncludeNameNodes ( ) ; for ( String file : config . getDocumentProvider ( ) . getFileNames ( ) ) { RootNode rootNode = config . getDocumentProvider ( ) . getRootNode ( file ) ; for ( final Node node : NodeProvider . getSubNodes ( rootNode , ConstNode . class , Colon2Node . class ) ) { if ( toSkip . contains ( node ) || NodeProvider . findParentNode ( rootNode , node ) instanceof ClassNode || NodeProvider . findParentNode ( rootNode , node ) instanceof SClassNode ) { continue ; } ModuleSpecifierWrapper module = ModuleSpecifierWrapper . create ( node , NameHelper . getEncosingModulePrefix ( rootNode , node ) ) ; if ( module . getFullName ( ) . equals ( config . getOriginalFullName ( ) ) ) { calls . add ( module ) ; } } } return calls ; } private Collection < Node > collectAllModulePartsAndIncludeNameNodes ( ) { Collection < Node > toSkip = new HashSet < Node > ( ) ; for ( ModuleNodeWrapper part : config . getModuleParts ( ) ) { toSkip . add ( part . getWrappedNode ( ) . getCPath ( ) ) ; } for ( ModuleSpecifierWrapper include : config . getIncludes ( ) ) { toSkip . add ( include . getWrappedNode ( ) ) ; } return toSkip ; } private boolean caretIsNotOnModuleName ( ModuleNodeWrapper selectedModule ) { return ! NodeUtil . positionIsInNode ( config . getCarretPosition ( ) , selectedModule . getWrappedNode ( ) . getCPath ( ) ) ; } } package org . rubypeople . rdt . refactoring . core . renamemodule ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . util . NameHelper ; public abstract class ModuleSpecifierWrapper implements INodeWrapper { protected String modulePrefix ; private static class Colon2IncludeWrapper extends ModuleSpecifierWrapper { protected Colon2Node node ; public Colon2IncludeWrapper ( Colon2Node node , String modulePrefix ) { this . node = node ; this . modulePrefix = modulePrefix ; } @ Override public String getIncludeName ( ) { return NameHelper . getFullyQualifiedName ( node ) ; } @ Override public Node getWrappedNode ( ) { return node ; } @ Override public void setNewName ( String oldName , String newName ) { for ( Node node : NodeProvider . getSubNodes ( this . node , Colon2Node . class , ConstNode . class ) ) { INameNode nameNode = ( INameNode ) node ; if ( ! nameNode . getName ( ) . equals ( oldName ) ) { continue ; } if ( node instanceof Colon2Node ) { ( ( Colon2Node ) node ) . setName ( newName ) ; return ; } else { ( ( ConstNode ) node ) . setName ( newName ) ; return ; } } } } private static class ConstIncludeWrapper extends ModuleSpecifierWrapper { protected ConstNode node ; public ConstIncludeWrapper ( ConstNode node , String modulePrefix ) { this . node = node ; this . modulePrefix = modulePrefix ; } @ Override public String getIncludeName ( ) { return node . getName ( ) ; } @ Override public Node getWrappedNode ( ) { return node ; } @ Override public void setNewName ( String oldName , String newName ) { node . setName ( newName ) ; } } public static ModuleSpecifierWrapper create ( Node node , String modulePrefix ) { if ( node instanceof Colon2Node ) { return new Colon2IncludeWrapper ( ( Colon2Node ) node , modulePrefix ) ; } else { return new ConstIncludeWrapper ( ( ConstNode ) node , modulePrefix ) ; } } public abstract Node getWrappedNode ( ) ; public abstract String getIncludeName ( ) ; public String getFullName ( ) { if ( "" . equals ( modulePrefix ) ) { return getIncludeName ( ) ; } return modulePrefix + "" + getIncludeName ( ) ; } public abstract void setNewName ( String oldName , String newName ) ; } package org . rubypeople . rdt . refactoring . core . extractconstant ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; public class ConstantExtractor extends MultiEditProvider { private ExtractConstantConfig config ; private boolean replaceAll ; public ConstantExtractor ( ExtractConstantConfig config ) { this . config = config ; } protected Collection < EditProvider > getEditProviders ( ) { Collection < EditProvider > providers = new ArrayList < EditProvider > ( ) ; if ( replaceAll ) { Node selection = config . getSelectedNodes ( ) ; Node rootNode = config . getRootNode ( ) ; MatchingNodesVisitor visitor = new MatchingNodesVisitor ( selection , config . getDocumentProvider ( ) . getActiveFileContent ( ) ) ; rootNode . accept ( visitor ) ; List < Node > matches = visitor . getMatches ( ) ; for ( Node node : matches ) { providers . add ( new ExtractedConstantCall ( node , config . getConstantCallNode ( ) ) ) ; } } else { providers . add ( new ExtractedConstantCall ( config ) ) ; } providers . add ( new ExtractedConstantDef ( config ) ) ; return providers ; } public EditProvider getDefEdit ( ) { return new ExtractedConstantDef ( config ) ; } public void setConstantName ( String name ) { config . setConstantName ( name ) ; } public String getConstantName ( ) { return config . getConstantName ( ) ; } public void setReplaceAllInstances ( boolean selection ) { this . replaceAll = selection ; } } package org . rubypeople . rdt . refactoring . core . extractconstant ; import java . io . StringWriter ; import java . util . ArrayList ; import java . util . List ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . FormatHelper ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; public class MatchingNodesVisitor extends InOrderVisitor { private Node toMatch ; private String src ; private String selectedNodeSrc ; private List < Node > matches ; public MatchingNodesVisitor ( Node selection , String src ) { this . toMatch = selection ; this . src = src ; this . selectedNodeSrc = getSource ( selection ) ; this . matches = new ArrayList < Node > ( ) ; } @ Override protected Object visitNode ( Node iVisited ) { if ( iVisited != null && iVisited . getClass ( ) . equals ( toMatch . getClass ( ) ) ) { String currentNodeSrc = getSource ( iVisited ) ; if ( currentNodeSrc . equals ( selectedNodeSrc ) ) { matches . add ( iVisited ) ; } } return super . visitNode ( iVisited ) ; } private String getSource ( Node iVisited ) { StringWriter writer = new StringWriter ( ) ; FormatHelper helper = new EditableFormatHelper ( ) ; ReWriterContext context = new ReWriterContext ( writer , src , helper ) ; ReWriteVisitor visitor = new ReWriteVisitor ( context ) ; iVisited . accept ( visitor ) ; return writer . getBuffer ( ) . toString ( ) ; } public List < Node > getMatches ( ) { return matches ; } } package org . rubypeople . rdt . refactoring . core . extractconstant ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; public class ExtractedConstantCall extends ReplaceEditProvider { private Node selected ; private Node editNode ; public ExtractedConstantCall ( ExtractConstantConfig config ) { this ( config . getSelectedNodes ( ) , config . getConstantCallNode ( ) ) ; } public ExtractedConstantCall ( Node toReplace , Node replacement ) { super ( false ) ; this . selected = toReplace ; editNode = replacement ; } protected int getOffsetLength ( ) { return getEndOffset ( ) - getStartOffset ( ) ; } private int getStartOffset ( ) { return selected . getPosition ( ) . getStartOffset ( ) ; } private int getEndOffset ( ) { return selected . getPosition ( ) . getEndOffset ( ) ; } protected Node getEditNode ( int offset , String document ) { return editNode ; } protected int getOffset ( String document ) { return getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . extractconstant ; import org . jruby . ast . BlockNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . SClassNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . RealClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . SClassNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterNodeOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . BeforeFirstMethodInClassOffsetProvider ; public class ExtractedConstantDef extends InsertEditProvider { private Node insertAfterNode ; private ExtractConstantConfig config ; public ExtractedConstantDef ( ExtractConstantConfig config ) { super ( true ) ; this . config = config ; insertAfterNode = getNodeToInsertAfter ( config . getRootNode ( ) , config . getSelection ( ) ) ; if ( insertAfterNode == null ) { setInsertType ( INSERT_AT_BEGIN_OF_LINE ) ; } } private Node getNodeToInsertAfter ( Node rootNode , IRefactoringContext selection ) { Node enclosingClassNode = SelectionNodeProvider . getEnclosingNode ( rootNode , selection , ClassNode . class ) ; if ( enclosingClassNode != null ) { return enclosingClassNode ; } Node enclosingModuleNode = SelectionNodeProvider . getEnclosingNode ( rootNode , selection , ModuleNode . class ) ; if ( enclosingModuleNode != null ) { return enclosingModuleNode ; } Node enclosingBlockNode = SelectionNodeProvider . getEnclosingNode ( config . getRootNode ( ) , config . getSelection ( ) , BlockNode . class ) ; if ( enclosingBlockNode != null ) { Node firstSelectedNode = ( Node ) config . getSelectedNodes ( ) ; if ( ! firstSelectedNode . childNodes ( ) . isEmpty ( ) ) { firstSelectedNode = ( Node ) firstSelectedNode . childNodes ( ) . toArray ( ) [ ] ; } return NodeProvider . getNodeBefore ( enclosingBlockNode , firstSelectedNode ) ; } return null ; } @ Override protected Node getInsertNode ( int offset , String document ) { return config . getConstantDeclNode ( ) ; } @ Override protected int getOffset ( String document ) { if ( insertAfterNode == null ) { return ; } if ( insertAfterNode instanceof ClassNode ) { return new BeforeFirstMethodInClassOffsetProvider ( new RealClassNodeWrapper ( ( ClassNode ) insertAfterNode ) , config . getDocumentProvider ( ) . getActiveFileContent ( ) ) . getOffset ( ) ; } if ( insertAfterNode instanceof SClassNode ) { return new BeforeFirstMethodInClassOffsetProvider ( new SClassNodeWrapper ( ( SClassNode ) insertAfterNode , config . getRootNode ( ) ) , config . getDocumentProvider ( ) . getActiveFileContent ( ) ) . getOffset ( ) ; } if ( insertAfterNode instanceof ModuleNode ) { return new BeforeFirstMethodInClassOffsetProvider ( ( ModuleNode ) insertAfterNode , config . getDocumentProvider ( ) . getActiveFileContent ( ) ) . getOffset ( ) ; } return new AfterNodeOffsetProvider ( insertAfterNode , document ) . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . extractconstant ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . BignumNode ; import org . jruby . ast . FalseNode ; import org . jruby . ast . FixnumNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . NilNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . TrueNode ; import org . jruby . ast . ZArrayNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; public class ExtractConstantConditionChecker extends RefactoringConditionChecker { private ExtractConstantConfig config ; public ExtractConstantConditionChecker ( IRefactoringConfig config2 ) { super ( config2 ) ; } protected void checkInitialConditions ( ) { if ( ! existSelectedNodes ( ) ) { addError ( "" ) ; } else if ( ! isPrimitive ( ) ) { addError ( "" ) ; } } private boolean isPrimitive ( ) { return ( config . getSelectedNodes ( ) instanceof ZArrayNode ) || ( config . getSelectedNodes ( ) instanceof ArrayNode ) || ( config . getSelectedNodes ( ) instanceof HashNode ) || ( config . getSelectedNodes ( ) instanceof FixnumNode ) || ( config . getSelectedNodes ( ) instanceof BignumNode ) || ( config . getSelectedNodes ( ) instanceof NilNode ) || ( config . getSelectedNodes ( ) instanceof TrueNode ) || ( config . getSelectedNodes ( ) instanceof FalseNode ) || ( config . getSelectedNodes ( ) instanceof StrNode ) ; } private boolean existSelectedNodes ( ) { return ! NodeProvider . isEmptyNode ( config . getSelectedNodes ( ) ) ; } @ Override public void init ( IRefactoringConfig configObj ) { this . config = ( ExtractConstantConfig ) configObj ; config . init ( ) ; if ( ! NodeProvider . isEmptyNode ( config . getSelectedNodes ( ) ) ) { } } } package org . rubypeople . rdt . refactoring . core . extractconstant ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public class ExtractConstantConfig implements IRefactoringConfig { private static final String DEFAULT_CONSTANT_NAME = "" ; private IDocumentProvider docProvider ; private IRefactoringContext selectionInfo ; private Node selectedNodes ; private Node rootNode ; private String constName = DEFAULT_CONSTANT_NAME ; public ExtractConstantConfig ( DocumentProvider docProvider , IRefactoringContext selectionInfo ) { this . docProvider = docProvider ; this . selectionInfo = optimizeSelection ( selectionInfo ) ; } private IRefactoringContext optimizeSelection ( IRefactoringContext selectionInfo ) { int start = selectionInfo . getStartOffset ( ) ; int end = selectionInfo . getEndOffset ( ) + ; String content = docProvider . getActiveFileContent ( ) ; if ( end > content . length ( ) ) end = content . length ( ) ; if ( end == start ) return selectionInfo ; String selectedText = content . substring ( start , end ) ; String trimedSelectionInformation = selectedText . trim ( ) ; start += selectedText . indexOf ( trimedSelectionInformation ) ; end = start + trimedSelectionInformation . length ( ) - ; return new RefactoringContext ( start , end , start , selectionInfo . getSource ( ) ) ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public IRefactoringContext getSelection ( ) { return selectionInfo ; } public Node getSelectedNodes ( ) { return selectedNodes ; } public Node getRootNode ( ) { return rootNode ; } public Node getConstantCallNode ( ) { return NodeFactory . createConstNode ( constName ) ; } public void setConstantName ( String name ) { constName = name ; } public Node getConstantDeclNode ( ) { return NodeFactory . createConstDeclNode ( constName , selectedNodes ) ; } public String getConstantName ( ) { return constName ; } public void init ( ) { rootNode = getDocumentProvider ( ) . getActiveFileRootNode ( ) ; selectedNodes = SelectionNodeProvider . getSelectedNodes ( rootNode , getSelection ( ) ) ; constName = extractConstantName ( selectedNodes ) ; } private String extractConstantName ( Node node ) { String name = ASTUtil . stringRepresentation ( node ) ; name = trim ( name ) ; if ( RubyConventions . validateConstant ( name ) . isOK ( ) ) return name ; return DEFAULT_CONSTANT_NAME ; } private String trim ( String name ) { name = name . trim ( ) ; name = name . toUpperCase ( ) ; name = name . replace ( '' , '' ) ; while ( true ) { if ( name . length ( ) == ) break ; char c = name . charAt ( ) ; if ( ! ( Character . isUpperCase ( c ) && Character . isLetter ( c ) ) ) { name = name . substring ( ) ; } else { break ; } } while ( true ) { if ( name . length ( ) == ) break ; char c = name . charAt ( name . length ( ) - ) ; if ( ! Character . isLetter ( c ) && c != '' ) { name = name . substring ( , name . length ( ) - ) ; } else { break ; } } return name ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . extractconstant ; import org . eclipse . ltk . ui . refactoring . UserInputWizardPage ; import org . rubypeople . rdt . internal . refactoring . RefactoringMessages ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . ui . pages . ExtractConstantPage ; public class ExtractConstantRefactoring extends RubyRefactoring { public static final String NAME = RefactoringMessages . ExtractConstantAction_extract_constant ; public ExtractConstantRefactoring ( RefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; ExtractConstantConfig config = new ExtractConstantConfig ( getDocumentProvider ( ) , selectionProvider ) ; ExtractConstantConditionChecker checker = new ExtractConstantConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { ConstantExtractor methodExtractor = new ConstantExtractor ( config ) ; setEditProvider ( methodExtractor ) ; UserInputWizardPage page = new ExtractConstantPage ( methodExtractor ) ; pages . add ( page ) ; } } } package org . rubypeople . rdt . refactoring . core . renamemethod . methoditems ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; public class CallCandidateItem extends MethodItem { private MethodCallNodeWrapper itemDecorator ; public CallCandidateItem ( MethodCallNodeWrapper currentCandidate ) { this . itemDecorator = currentCandidate ; } @ Override public String getMethodPartName ( ) { return itemDecorator . getName ( ) ; } @ Override public Node getMethodPartNode ( ) { return itemDecorator . getWrappedNode ( ) ; } @ Override public Node getRenamedPartNode ( String newName ) { return getReamedNode ( newName ) ; } public Node getReamedNode ( String newName ) { int type = itemDecorator . getType ( ) ; if ( type == MethodCallNodeWrapper . CALL_NODE ) { return getRenamedCallNode ( newName ) ; } else if ( type == MethodCallNodeWrapper . V_CALL_NODE ) { return getRenamedVCallNode ( newName ) ; } else if ( type == MethodCallNodeWrapper . F_CALL_NODE ) { return getRenamedFCallNode ( newName ) ; } return null ; } private Node getRenamedFCallNode ( String newName ) { Node arguments = ( ( FCallNode ) itemDecorator . getWrappedNode ( ) ) . getArgsNode ( ) ; return NodeFactory . createFCallNode ( newName , arguments ) ; } private Node getRenamedVCallNode ( String newName ) { return NodeFactory . createVCallNode ( newName ) ; } private Node getRenamedCallNode ( String newName ) { return NodeFactory . createCallNode ( itemDecorator . getReceiverNode ( ) , newName , itemDecorator . getArgsNode ( ) ) ; } } package org . rubypeople . rdt . refactoring . core . renamemethod . methoditems ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; public class MethodNameArgumentItem extends MethodItem { private ArgumentNode nameNode ; public MethodNameArgumentItem ( ArgumentNode nameNode ) { this . nameNode = nameNode ; } @ Override public String getMethodPartName ( ) { return nameNode . getName ( ) ; } @ Override public Node getMethodPartNode ( ) { return nameNode ; } @ Override public Node getRenamedPartNode ( String newName ) { return NodeFactory . createArgumentNode ( newName ) ; } } package org . rubypeople . rdt . refactoring . core . renamemethod . methoditems ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; public class SymbolItem extends MethodItem { private SymbolNode decoratedSymbol ; public SymbolItem ( SymbolNode currentNode ) { this . decoratedSymbol = currentNode ; } @ Override public String getMethodPartName ( ) { return decoratedSymbol . getName ( ) ; } @ Override public Node getMethodPartNode ( ) { return decoratedSymbol ; } @ Override public Node getRenamedPartNode ( String newName ) { return new SymbolNode ( decoratedSymbol . getPosition ( ) , newName ) ; } } package org . rubypeople . rdt . refactoring . core . renamemethod . methoditems ; import org . jruby . ast . Node ; public abstract class MethodItem { public abstract Node getMethodPartNode ( ) ; public abstract Node getRenamedPartNode ( String newName ) ; public abstract String getMethodPartName ( ) ; } package org . rubypeople . rdt . refactoring . core . renamemethod ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String RenameMethodConditionChecker_AlreadyExists ; public static String RenameMethodConditionChecker_NoMethodSelected ; public static String RenameMethodConditionChecker_NotChanged ; public static String RenameMethodRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . renamemethod ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . IValidator ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . NewNameListener ; import org . rubypeople . rdt . refactoring . ui . pages . OccurenceReplaceSelectionPage ; import org . rubypeople . rdt . refactoring . ui . pages . RenamePage ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class RenameMethodRefactoring extends RubyRefactoring { private static final class MethodNameValidator implements IValidator { public boolean isValid ( String test ) { return NameValidator . isValidMethodName ( test ) ; } } public static final String NAME = Messages . RenameMethodRefactoring_Name ; public RenameMethodRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; RenameMethodConfig config = new RenameMethodConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; RenameMethodConditionChecker checker = new RenameMethodConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { MethodRenamer methodRenamer = new MethodRenamer ( config ) ; setEditProvider ( methodRenamer ) ; NewNameListener nameListener = new NewNameListener ( config , new MethodNameValidator ( ) , checker . getAlreadyUsedNames ( ) ) ; RenamePage page = new RenamePage ( NAME + "" , config . getTargetMethod ( ) . getName ( ) , nameListener ) ; pages . add ( page ) ; if ( ! config . getPossibleCalls ( ) . isEmpty ( ) ) { pages . add ( new OccurenceReplaceSelectionPage ( config , config . getDocumentProvider ( ) ) ) ; } } } } package org . rubypeople . rdt . refactoring . core . renamemethod ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . SClassNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . VCallNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . renamefield . FieldRenameEditProvider ; import org . rubypeople . rdt . refactoring . core . renamefield . fielditems . FieldItem ; import org . rubypeople . rdt . refactoring . core . renamemethod . methoditems . CallCandidateItem ; import org . rubypeople . rdt . refactoring . core . renamemethod . methoditems . MethodNameArgumentItem ; import org . rubypeople . rdt . refactoring . core . renamemethod . methoditems . SymbolItem ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiFileEditProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class MethodRenamer implements IMultiFileEditProvider { private RenameMethodConfig config ; public Collection < String > getAllMethodsFromClass ( ) { Collection < String > names = new ArrayList < String > ( ) ; if ( config . getSelectedClass ( ) != null ) { for ( MethodNodeWrapper method : config . getSelectedClass ( ) . getMethods ( ) ) { names . add ( method . getName ( ) ) ; } } return names ; } public MethodRenamer ( RenameMethodConfig config ) { this . config = config ; Collection < INodeWrapper > probableClass = getCallCandidatesInClass ( ) ; probableClass . addAll ( getSubsequentCalls ( ) ) ; probableClass . addAll ( config . getSelectedCalls ( ) ) ; config . setSelectedCalls ( probableClass ) ; } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { MultiFileEditProvider fileEdits = new MultiFileEditProvider ( ) ; addDefinitionRenamer ( fileEdits ) ; addCallRenamers ( fileEdits ) ; if ( ! config . getTargetMethod ( ) . isClassMethod ( ) ) { addSymbolRenamers ( fileEdits ) ; } return fileEdits . getFileEditProviders ( ) ; } private void addSymbolRenamers ( MultiFileEditProvider fileEdits ) { if ( config . getTargetMethod ( ) . isClassMethod ( ) ) { return ; } String file = config . getDocumentProvider ( ) . getActiveFileName ( ) ; for ( SymbolNode currentNode : getSymbolCandidatesInClass ( ) ) { addSymbolRenamer ( fileEdits , file , currentNode , config . getNewName ( ) ) ; } } private void addSymbolRenamer ( MultiFileEditProvider fileEdits , String file , SymbolNode currentNode , String name ) { SymbolItem currentItem = new SymbolItem ( currentNode ) ; fileEdits . addEditProvider ( new FileEditProvider ( file , new MethodRenameEditProvider ( currentItem , name ) ) ) ; } private void addCallRenamers ( MultiFileEditProvider fileEdits ) { for ( INodeWrapper currentCandidate : config . getSelectedCalls ( ) ) { String file = currentCandidate . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; String newName = config . getNewName ( ) ; if ( currentCandidate instanceof MethodCallNodeWrapper ) { CallCandidateItem candidateItem = new CallCandidateItem ( ( MethodCallNodeWrapper ) currentCandidate ) ; fileEdits . addEditProvider ( new FileEditProvider ( file , new MethodRenameEditProvider ( candidateItem , newName ) ) ) ; } else if ( config . renameFields ( ) ) { if ( config . getTargetMethod ( ) . isWriter ( ) ) { newName = newName . replace ( "" , "" ) ; } FieldRenameEditProvider currentRenameProvider = new FieldRenameEditProvider ( ( FieldItem ) currentCandidate , newName ) ; fileEdits . addEditProvider ( new FileEditProvider ( file , currentRenameProvider ) ) ; } } } private void addDefinitionRenamer ( MultiFileEditProvider fileEdits ) { if ( config . getSelectedClass ( ) == null || config . getTargetMethod ( ) . isClassMethod ( ) ) { String file = config . getDocumentProvider ( ) . getActiveFileName ( ) ; MethodNameArgumentItem argumentItem = new MethodNameArgumentItem ( config . getTargetMethod ( ) . getWrappedNode ( ) . getNameNode ( ) ) ; fileEdits . addEditProvider ( new FileEditProvider ( file , new MethodRenameEditProvider ( argumentItem , config . getNewName ( ) ) ) ) ; } else { for ( ClassNodeWrapper currentClassNode : findRelatedClasses ( ) ) { MethodNodeWrapper currentMethodDef = currentClassNode . getMethod ( config . getTargetMethod ( ) . getName ( ) ) ; if ( currentMethodDef == null ) { continue ; } String currentFile = currentMethodDef . getPosition ( ) . getFile ( ) ; addMethodNameRenamer ( fileEdits , currentMethodDef , currentFile , config . getNewName ( ) ) ; } } if ( config . getTargetMethod ( ) . isAccessor ( ) && config . renameFields ( ) ) { String theOtherAccessor ; String newName ; if ( config . getTargetMethod ( ) . isReader ( ) ) { theOtherAccessor = config . getTargetMethod ( ) . getName ( ) + "" ; newName = config . getNewName ( ) + "" ; } else { theOtherAccessor = config . getTargetMethod ( ) . getName ( ) . replace ( "" , "" ) ; newName = config . getNewName ( ) . replace ( "" , "" ) ; } MethodNodeWrapper method = config . getSelectedClass ( ) . getMethod ( theOtherAccessor ) ; if ( method != null ) { addMethodNameRenamer ( fileEdits , method , method . getPosition ( ) . getFile ( ) , newName ) ; for ( SymbolNode node : method . getSymbolCandidatesInClass ( config . getSelectedClass ( ) ) ) { addSymbolRenamer ( fileEdits , method . getPosition ( ) . getFile ( ) , node , newName ) ; } } } } private void addMethodNameRenamer ( MultiFileEditProvider fileEdits , MethodNodeWrapper currentMethodDef , String currentFile , String newName ) { MethodNameArgumentItem argumentItem = new MethodNameArgumentItem ( currentMethodDef . getWrappedNode ( ) . getNameNode ( ) ) ; fileEdits . addEditProvider ( new FileEditProvider ( currentFile , new MethodRenameEditProvider ( argumentItem , newName ) ) ) ; } private ArrayList < ClassNodeWrapper > findRelatedClasses ( ) { ClassNodeProvider projectClassProvider = config . getDocumentProvider ( ) . getProjectClassNodeProvider ( ) ; ArrayList < ClassNodeWrapper > relatedClasses = new ArrayList < ClassNodeWrapper > ( ) ; relatedClasses . addAll ( projectClassProvider . getClassAndAllSuperClassesFor ( config . getSelectedClass ( ) . getName ( ) ) ) ; relatedClasses . addAll ( projectClassProvider . getSubClassesOf ( config . getSelectedClass ( ) . getName ( ) ) ) ; return relatedClasses ; } public NodeSelector getConfig ( ) { return config ; } public Collection < INodeWrapper > getCallCandidatesInClass ( ) { ArrayList < INodeWrapper > callCandidates = new ArrayList < INodeWrapper > ( ) ; if ( config . getSelectedClass ( ) != null ) { for ( ClassNodeWrapper currentClass : findRelatedClasses ( ) ) { callCandidates . addAll ( config . getTargetMethod ( ) . getCallCandidatesInClass ( currentClass ) ) ; } } return callCandidates ; } public Collection < SymbolNode > getSymbolCandidatesInClass ( ) { return config . getTargetMethod ( ) . getSymbolCandidatesInClass ( config . getSelectedClass ( ) ) ; } public Collection < MethodCallNodeWrapper > getSubsequentCalls ( ) { Node fileRoot = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; int methodEndPos = config . getTargetMethod ( ) . getWrappedNode ( ) . getPosition ( ) . getEndOffset ( ) ; ArrayList < MethodCallNodeWrapper > subsequentCalls = new ArrayList < MethodCallNodeWrapper > ( ) ; if ( SelectionNodeProvider . getSelectedNodeOfType ( fileRoot , methodEndPos , ClassNode . class , SClassNode . class ) != null ) { return subsequentCalls ; } Collection < Node > callNodes = NodeProvider . getSubNodes ( fileRoot , CallNode . class , VCallNode . class , FCallNode . class ) ; for ( Node currentNode : callNodes ) { if ( currentNode . getPosition ( ) . getStartOffset ( ) >= methodEndPos ) { MethodCallNodeWrapper currentCall = new MethodCallNodeWrapper ( currentNode ) ; if ( currentCall . getName ( ) . equals ( config . getTargetMethod ( ) . getName ( ) ) && ! hasDefsInEnclosingClass ( currentCall , fileRoot ) ) { subsequentCalls . add ( currentCall ) ; } } } return subsequentCalls ; } private boolean hasDefsInEnclosingClass ( MethodCallNodeWrapper currentCall , Node rootNode ) { int position = currentCall . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ; try { ClassNodeWrapper classNode = SelectionNodeProvider . getSelectedClassNode ( rootNode , position ) ; for ( MethodNodeWrapper currentMethod : classNode . getMethods ( ) ) { if ( currentCall . getName ( ) . equals ( currentMethod . getName ( ) ) ) { return true ; } } return false ; } catch ( NoClassNodeException e ) { return false ; } } } package org . rubypeople . rdt . refactoring . core . renamemethod ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . renamemethod . methoditems . MethodItem ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; public class MethodRenameEditProvider extends ReplaceEditProvider { private MethodItem methodItem ; private String newName ; private ISourcePosition position ; public MethodRenameEditProvider ( MethodItem methodItem , String newName ) { super ( false ) ; this . methodItem = methodItem ; this . newName = newName ; this . position = methodItem . getMethodPartNode ( ) . getPosition ( ) ; } @ Override protected int getOffsetLength ( ) { return position . getEndOffset ( ) - position . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return methodItem . getRenamedPartNode ( newName ) ; } @ Override protected int getOffset ( String document ) { return methodItem . getMethodPartNode ( ) . getPosition ( ) . getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . renamemethod ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . SymbolNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . INewNameReceiver ; public class RenameMethodConfig implements INewNameReceiver , NodeSelector , IRefactoringConfig { private IDocumentProvider docProvider ; private int caretPosition ; private String newName ; private Collection < ? extends INodeWrapper > renamedCalls ; private Collection < ? extends INodeWrapper > possibleCalls ; private Collection < SymbolNode > symbolCandidate ; private ClassNodeWrapper classNode ; private MethodNodeWrapper targetMethod ; private boolean renameFields = true ; public RenameMethodConfig ( IDocumentProvider docProvider , int caretPosition ) { this . docProvider = docProvider ; this . caretPosition = caretPosition ; this . renamedCalls = new ArrayList < INodeWrapper > ( ) ; this . possibleCalls = new ArrayList < INodeWrapper > ( ) ; } public int getCaretPosition ( ) { return caretPosition ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public String getNewName ( ) { return newName ; } public void setNewName ( String newName ) { this . newName = newName ; } public void setSelectedCalls ( Collection < ? extends INodeWrapper > callCandidates ) { this . renamedCalls = callCandidates ; } public Collection < ? extends INodeWrapper > getSelectedCalls ( ) { return renamedCalls ; } public void setRenamedSymbols ( Collection < SymbolNode > symbolCandidate ) { this . symbolCandidate = symbolCandidate ; } public Collection < SymbolNode > getRenamedSymbols ( ) { return symbolCandidate ; } public void setClassNode ( ClassNodeWrapper selectedClassNode ) { classNode = selectedClassNode ; } public void setTargetMethod ( MethodNodeWrapper selectedMethod ) { this . targetMethod = selectedMethod ; } public MethodNodeWrapper getTargetMethod ( ) { return targetMethod ; } public ClassNodeWrapper getSelectedClass ( ) { return classNode ; } public Collection < ? extends INodeWrapper > getPossibleCalls ( ) { return possibleCalls ; } public void setPossibleCalls ( Collection < ? extends INodeWrapper > possibleCalls ) { this . possibleCalls = possibleCalls ; } public void setDocProvider ( DocumentWithIncluding docProvider ) { this . docProvider = docProvider ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } public boolean renameFields ( ) { return renameFields ; } public void setRenameFields ( boolean renameFields ) { this . renameFields = renameFields ; } } package org . rubypeople . rdt . refactoring . core . renamemethod ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; public interface NodeSelector { public abstract void setSelectedCalls ( Collection < ? extends INodeWrapper > selectedCalls ) ; public abstract Collection < ? extends INodeWrapper > getSelectedCalls ( ) ; public abstract Collection < ? extends INodeWrapper > getPossibleCalls ( ) ; public abstract void setPossibleCalls ( Collection < ? extends INodeWrapper > possibleCalls ) ; } package org . rubypeople . rdt . refactoring . core . renamemethod ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . renamefield . FieldProvider ; import org . rubypeople . rdt . refactoring . core . renamefield . InstVarAccessesFinder ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class RenameMethodConditionChecker extends RefactoringConditionChecker { public static final String DEFAULT_ERROR = Messages . RenameMethodConditionChecker_NoMethodSelected ; private RenameMethodConfig config ; public RenameMethodConditionChecker ( RenameMethodConfig config ) { super ( config ) ; } @ Override public void init ( IRefactoringConfig configObj ) { this . config = ( RenameMethodConfig ) configObj ; config . setDocProvider ( new DocumentWithIncluding ( config . getDocumentProvider ( ) ) ) ; Node rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; try { this . config . setClassNode ( SelectionNodeProvider . getSelectedClassNode ( rootNode , this . config . getCaretPosition ( ) ) ) ; } catch ( NoClassNodeException e ) { } setSelectedMethodNode ( rootNode ) ; if ( config . getTargetMethod ( ) . getWrappedNode ( ) != null ) { this . config . setPossibleCalls ( getAllCallCandidates ( ) ) ; } } private void setSelectedMethodNode ( Node rootNode ) { MethodDefNode methodNode = ( MethodDefNode ) SelectionNodeProvider . getSelectedNodeOfType ( rootNode , this . config . getCaretPosition ( ) , MethodDefNode . class ) ; if ( methodNode == null ) { SymbolNode selectedSymbolNode = ( SymbolNode ) SelectionNodeProvider . getSelectedNodeOfType ( rootNode , config . getCaretPosition ( ) , SymbolNode . class ) ; if ( selectedSymbolNode != null && config . getSelectedClass ( ) != null ) { MethodNodeWrapper method = config . getSelectedClass ( ) . getMethod ( selectedSymbolNode . getName ( ) ) ; if ( method != null ) { methodNode = method . getWrappedNode ( ) ; } } } MethodNodeWrapper targetMethod = new MethodNodeWrapper ( methodNode , config . getSelectedClass ( ) ) ; this . config . setTargetMethod ( targetMethod ) ; if ( methodNode != null && config . getNewName ( ) == null ) { this . config . setNewName ( targetMethod . getName ( ) ) ; } } private Collection < INodeWrapper > getAllCallCandidates ( ) { Collection < Node > allNodes = config . getDocumentProvider ( ) . getAllNodes ( ) ; ArrayList < INodeWrapper > possibleCalls = new ArrayList < INodeWrapper > ( ) ; for ( Node currentNode : allNodes ) { MethodCallNodeWrapper callNode = new MethodCallNodeWrapper ( currentNode ) ; if ( isPossibleCall ( callNode ) ) { possibleCalls . add ( callNode ) ; } } if ( config . getTargetMethod ( ) . isAccessor ( ) && config . renameFields ( ) ) { String name ; if ( config . getTargetMethod ( ) . isWriter ( ) ) { name = config . getTargetMethod ( ) . getName ( ) . replace ( "" , "" ) ; } else { name = config . getTargetMethod ( ) . getName ( ) ; } possibleCalls . addAll ( InstVarAccessesFinder . find ( config . getDocumentProvider ( ) , name ) ) ; possibleCalls . addAll ( new FieldProvider ( config . getSelectedClass ( ) , config . getDocumentProvider ( ) ) . getFieldItems ( name , false ) ) ; config . setSelectedCalls ( new FieldProvider ( config . getSelectedClass ( ) , config . getDocumentProvider ( ) ) . getFieldItems ( name , false ) ) ; } return possibleCalls ; } private boolean isPossibleCall ( MethodCallNodeWrapper callNode ) { if ( config . getTargetMethod ( ) . isClassMethod ( ) != callNode . isCallToClassMethod ( ) ) { return false ; } if ( callNode . getType ( ) == MethodCallNodeWrapper . INVALID_TYPE ) { return false ; } if ( callNode . getName ( ) . equals ( config . getTargetMethod ( ) . getName ( ) ) ) { ArgsNodeWrapper targetNodeArgs = config . getTargetMethod ( ) . getArgsNode ( ) ; if ( targetNodeArgs . argsCountMatches ( callNode ) ) { return true ; } } return false ; } @ Override protected void checkFinalConditions ( ) { if ( config . getNewName ( ) . equals ( config . getTargetMethod ( ) . getName ( ) ) ) { addWarning ( Messages . RenameMethodConditionChecker_NotChanged ) ; } else if ( getAlreadyUsedNames ( ) . contains ( config . getNewName ( ) ) ) { addError ( Messages . RenameMethodConditionChecker_AlreadyExists ) ; } } private boolean checkMethodIsBeyondClasses ( MethodDefNode currentMethod , ClassNodeProvider classes ) { String methodFile = currentMethod . getPosition ( ) . getFile ( ) ; int methodStart = currentMethod . getPosition ( ) . getStartOffset ( ) ; int methodEnd = currentMethod . getPosition ( ) . getEndOffset ( ) ; for ( ClassNodeWrapper currentClass : classes . getAllClassNodes ( ) ) { for ( PartialClassNodeWrapper currentPart : currentClass . getPartialClassNodes ( ) ) { if ( checkIsInClassPart ( methodFile , methodStart , methodEnd , currentPart ) ) { return false ; } } } return true ; } private boolean checkIsInClassPart ( String methodFile , int methodStart , int methodEnd , PartialClassNodeWrapper currentPart ) { String partFile = currentPart . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; int partStart = currentPart . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ; int partEnd = currentPart . getWrappedNode ( ) . getPosition ( ) . getEndOffset ( ) ; if ( methodFile . equals ( partFile ) && ( methodStart > partStart ) && ( methodEnd < partEnd ) ) { return true ; } return false ; } @ Override protected void checkInitialConditions ( ) { Node methodNode = config . getTargetMethod ( ) . getWrappedNode ( ) ; if ( methodNode == null || ! isSelectionInMethodName ( ) ) { addError ( DEFAULT_ERROR ) ; } } private boolean isSelectionInMethodName ( ) { return SelectionNodeProvider . nodeContainsPosition ( config . getTargetMethod ( ) . getWrappedNode ( ) . getNameNode ( ) , config . getCaretPosition ( ) ) ; } public Collection < String > getAlreadyUsedNames ( ) { HashSet < String > usedNames = new HashSet < String > ( ) ; if ( config . getSelectedClass ( ) != null ) { for ( MethodNodeWrapper currentMethod : config . getSelectedClass ( ) . getMethods ( ) ) { if ( isSameTypeAsSelectedMethod ( currentMethod ) ) { usedNames . add ( currentMethod . getName ( ) ) ; } } } else { Node rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; Collection < MethodDefNode > methods = NodeProvider . getMethodNodes ( rootNode ) ; ClassNodeProvider classes = new ClassNodeProvider ( config . getDocumentProvider ( ) ) ; for ( MethodDefNode currentMethod : methods ) { if ( checkMethodIsBeyondClasses ( currentMethod , classes ) ) usedNames . add ( currentMethod . getName ( ) ) ; } } return usedNames ; } private boolean isSameTypeAsSelectedMethod ( MethodNodeWrapper currentMethod ) { return currentMethod . isClassMethod ( ) == config . getTargetMethod ( ) . isClassMethod ( ) ; } } package org . rubypeople . rdt . refactoring . core . movefield ; import org . rubypeople . rdt . refactoring . core . generateaccessors . GeneratedAccessor ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; public class GenerateAccessorsAtTarget { private ClassNodeWrapper targetClass ; private GeneratedAccessor generatedAccessor ; public GenerateAccessorsAtTarget ( IDocumentProvider doc , String className , String accessorName ) { for ( String fileName : doc . getFileNames ( ) ) { StringDocumentProvider stringDocumentProvider = new StringDocumentProvider ( fileName , doc . getFileContent ( fileName ) ) ; ClassNodeWrapper classNodeWrapper = stringDocumentProvider . getIncludedClassNodeProvider ( ) . getClassNode ( className ) ; if ( classNodeWrapper != null ) { targetClass = classNodeWrapper ; } } generatedAccessor = new GeneratedAccessor ( "" , accessorName , GeneratedAccessor . TYPE_SIMPLE_ACCESSOR , targetClass ) ; } public String getFileName ( ) { return targetClass . getFirstPartialClassNode ( ) . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; } public EditProvider getEditProvider ( ) { return generatedAccessor ; } } package org . rubypeople . rdt . refactoring . core . movefield ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . ui . pages . MoveFieldPage ; public class MoveFieldRefactoring extends RubyRefactoring { public static final String NAME = Messages . MoveFieldRefactoring_Name ; public MoveFieldRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; MoveFieldConfig config = new MoveFieldConfig ( new DocumentWithIncluding ( getDocumentProvider ( ) ) , selectionProvider . getCaretPosition ( ) ) ; MoveFieldConditionChecker checker = new MoveFieldConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { MoveFieldEditProvider editProvider = new MoveFieldEditProvider ( config ) ; setEditProvider ( editProvider ) ; pages . add ( new MoveFieldPage ( config ) ) ; } } } package org . rubypeople . rdt . refactoring . core . movefield ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String MoveFieldConditionChecker_NoDestination ; public static String MoveFieldConditionChecker_NoFieldSelected ; public static String MoveFieldConditionChecker_NoInstanceInsideClass ; public static String MoveFieldConditionChecker_NoReference ; public static String MoveFieldRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . movefield ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . renamefield . FieldRenamer ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConfig ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiFileEditProvider ; public class MoveFieldEditProvider implements IMultiFileEditProvider { private final MoveFieldConfig config ; public MoveFieldEditProvider ( MoveFieldConfig config ) { this . config = config ; } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { MultiFileEditProvider providers = new MultiFileEditProvider ( ) ; addTargetAccessorGenerator ( providers ) ; addSourceAccessorGenerator ( providers ) ; addFieldRenamers ( providers ) ; return providers . getFileEditProviders ( ) ; } private void addFieldRenamers ( MultiFileEditProvider providers ) { RenameFieldConfig renameFieldConfig = new RenameFieldConfig ( new DocumentWithIncluding ( config . getDocumentProvider ( ) ) , config . getPos ( ) ) ; new RenameFieldConditionChecker ( renameFieldConfig ) ; renameFieldConfig . setDoRenameAccessorMethods ( false ) ; renameFieldConfig . setDoRenameAccessors ( false ) ; renameFieldConfig . setNewName ( config . getTargetReference ( ) + '' + config . getSelectedFieldName ( ) ) ; FieldRenamer renamer = new FieldRenamer ( renameFieldConfig ) ; for ( FileMultiEditProvider fileMultiEditProvider : renamer . getFileEditProviders ( ) ) { for ( EditProvider editProvider : fileMultiEditProvider . getEditProviders ( ) ) { providers . addEditProvider ( new FileEditProvider ( fileMultiEditProvider . getFileName ( ) , editProvider ) ) ; } } } private void addTargetAccessorGenerator ( MultiFileEditProvider providers ) { GenerateAccessorsAtTarget generateAccessors = new GenerateAccessorsAtTarget ( config . getDocumentProvider ( ) , config . getTargetClass ( ) , config . getSelectedFieldName ( ) ) ; providers . addEditProvider ( new FileEditProvider ( generateAccessors . getFileName ( ) , generateAccessors . getEditProvider ( ) ) ) ; } private void addSourceAccessorGenerator ( MultiFileEditProvider providers ) { GenerateAccessorAtSource accessorAtSource = new GenerateAccessorAtSource ( config ) ; for ( EditProvider edit : accessorAtSource . getEditProviders ( ) ) { providers . addEditProvider ( new FileEditProvider ( config . getDocumentProvider ( ) . getActiveFileName ( ) , edit ) ) ; } } } package org . rubypeople . rdt . refactoring . core . movefield ; import java . util . Collection ; import java . util . TreeSet ; import org . rubypeople . rdt . refactoring . classnodeprovider . AllFilesClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; public class MoveFieldConditionChecker extends RefactoringConditionChecker { private ClassNodeWrapper selectedClassNode ; private FieldNodeWrapper selectedField ; private MoveFieldConfig config ; public MoveFieldConditionChecker ( MoveFieldConfig config ) { super ( config ) ; } @ Override public void init ( IRefactoringConfig configObj ) { config = ( MoveFieldConfig ) configObj ; try { selectedClassNode = SelectionNodeProvider . getSelectedClassNode ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , config . getPos ( ) ) ; } catch ( NoClassNodeException e ) { selectedClassNode = null ; return ; } selectedField = findSelectedField ( selectedClassNode . getFields ( ) , config . getPos ( ) ) ; config . setSelectedField ( selectedField ) ; if ( selectedField == null ) { return ; } config . setTargetClassCandidates ( getPossibleTargetClassNames ( selectedClassNode . getName ( ) ) ) ; config . setReferenceCandidates ( getPossibleFieldNames ( selectedClassNode . getFields ( ) , selectedField . getNameWithoutAts ( ) ) ) ; } private static Collection < String > getPossibleFieldNames ( Collection < FieldNodeWrapper > fields , String selectedFieldName ) { Collection < String > names = new TreeSet < String > ( ) ; for ( FieldNodeWrapper field : fields ) { if ( field . isInstVar ( ) && ! field . getNameWithoutAts ( ) . equals ( selectedFieldName ) ) { names . add ( "" + field . getNameWithoutAts ( ) ) ; } } return names ; } private static FieldNodeWrapper findSelectedField ( Collection < FieldNodeWrapper > fields , int pos ) { FieldNodeWrapper selected = null ; for ( FieldNodeWrapper fieldNode : fields ) { if ( isFieldAtCursorPos ( fieldNode , pos ) && fieldNode . isInstVar ( ) ) { selected = fieldNode ; } } return selected ; } private static boolean isFieldAtCursorPos ( FieldNodeWrapper fieldNode , int pos ) { return fieldNode . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) <= pos && fieldNode . getWrappedNode ( ) . getPosition ( ) . getEndOffset ( ) >= pos ; } private Collection < String > getPossibleTargetClassNames ( String selectedClassName ) { Collection < String > allClasses = new TreeSet < String > ( ) ; for ( ClassNodeWrapper classNode : new AllFilesClassNodeProvider ( config . getDocumentProvider ( ) ) . getAllClassNodes ( ) ) { if ( ! classNode . getName ( ) . equals ( selectedClassName ) ) allClasses . add ( classNode . getName ( ) ) ; } return allClasses ; } @ Override protected void checkInitialConditions ( ) { if ( selectedClassNode == null ) { addError ( Messages . MoveFieldConditionChecker_NoInstanceInsideClass ) ; } else if ( selectedField == null ) { addError ( Messages . MoveFieldConditionChecker_NoFieldSelected ) ; } else if ( config . getReferenceCandidates ( ) . isEmpty ( ) ) { addError ( Messages . MoveFieldConditionChecker_NoReference ) ; } else if ( config . getTargetClassCandidates ( ) . isEmpty ( ) ) { addError ( Messages . MoveFieldConditionChecker_NoDestination ) ; } } } package org . rubypeople . rdt . refactoring . core . movefield ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; public class MoveFieldConfig implements IRefactoringConfig { private IDocumentProvider doc ; private final int pos ; private Collection < String > targetClassCandidates ; private Collection < String > referenceCandidates ; private String targetClass ; private String targetReference ; private FieldNodeWrapper selectedField ; public MoveFieldConfig ( IDocumentProvider doc , int pos ) { this . doc = doc ; this . pos = pos ; } public Collection < String > getTargetClassCandidates ( ) { return targetClassCandidates ; } public void setTargetClassCandidates ( Collection < String > targetCandidates ) { this . targetClassCandidates = targetCandidates ; } public String getTargetClass ( ) { return targetClass ; } public void setTargetClass ( String targetClass ) { this . targetClass = targetClass ; } public String getTargetReference ( ) { return targetReference ; } public void setTargetReference ( String targetReference ) { this . targetReference = targetReference ; } public String getSelectedFieldName ( ) { return selectedField . getNameWithoutAts ( ) ; } public IDocumentProvider getDocumentProvider ( ) { return doc ; } public int getPos ( ) { return pos ; } public Collection < String > getReferenceCandidates ( ) { return referenceCandidates ; } public void setReferenceCandidates ( Collection < String > targetReferenceCandidates ) { this . referenceCandidates = targetReferenceCandidates ; } public void setSelectedField ( FieldNodeWrapper selectedField ) { this . selectedField = selectedField ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . doc = doc ; } } package org . rubypeople . rdt . refactoring . core . movefield ; import java . util . Collection ; import org . jruby . ast . BlockNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . EncapsulateFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . EncapsulateFieldConfig ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . FieldEncapsulator ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; public class GenerateAccessorAtSource { private class CustomTargetFieldEncapsulator extends FieldEncapsulator { public CustomTargetFieldEncapsulator ( EncapsulateFieldConfig fieldConfig ) { super ( fieldConfig ) ; } @ Override protected BlockNode createGetterOrSetter ( boolean writer , METHOD_VISIBILITY visibility ) { BlockNode accessor = super . createGetterOrSetter ( writer , visibility ) ; INameNode targetNode = ( INameNode ) NodeProvider . getSubNodes ( accessor , InstVarNode . class , InstAsgnNode . class ) . iterator ( ) . next ( ) ; if ( targetNode instanceof InstVarNode ) { ( ( InstVarNode ) targetNode ) . setName ( config . getTargetReference ( ) + '' + targetNode . getName ( ) . substring ( ) ) ; } else { ( ( InstAsgnNode ) targetNode ) . setName ( config . getTargetReference ( ) + '' + targetNode . getName ( ) . substring ( ) ) ; } return accessor ; } } private final MoveFieldConfig config ; public GenerateAccessorAtSource ( MoveFieldConfig config ) { this . config = config ; } public Collection < EditProvider > getEditProviders ( ) { EncapsulateFieldConfig fieldConfig = new EncapsulateFieldConfig ( config . getDocumentProvider ( ) , config . getPos ( ) ) ; new EncapsulateFieldConditionChecker ( fieldConfig ) ; FieldEncapsulator fieldEncapsulator = new CustomTargetFieldEncapsulator ( fieldConfig ) ; return fieldEncapsulator . getEditProviders ( ) ; } } package org . rubypeople . rdt . refactoring . core . encapsulatefield ; import org . jruby . ast . DefnNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class EncapsulateFieldConditionChecker extends RefactoringConditionChecker { private EncapsulateFieldConfig config ; private Node rootNode ; public EncapsulateFieldConditionChecker ( EncapsulateFieldConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { config = ( EncapsulateFieldConfig ) configObj ; rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; config . setSelectedInstNode ( findSelectedInstNode ( config . getCaretPosition ( ) ) ) ; if ( ! config . hasSelectedInstNode ( ) ) { return ; } config . setSelectedAccessor ( findSelectedAccessor ( config . getSelectedInstNode ( ) ) ) ; try { config . setEnclosingClassNode ( SelectionNodeProvider . getSelectedClassNode ( rootNode , config . getCaretPosition ( ) ) ) ; } catch ( NoClassNodeException e ) { } } private AttrAccessorNodeWrapper findSelectedAccessor ( INameNode selectedInstNode ) { return SelectionNodeProvider . getSelectedAccessorNode ( rootNode , selectedInstNode ) ; } private INameNode findSelectedInstNode ( int caretPosition ) { return ( INameNode ) SelectionNodeProvider . getSelectedNodeOfType ( rootNode , caretPosition , InstVarNode . class , InstAsgnNode . class , SymbolNode . class ) ; } public void checkFinalConditions ( ) { if ( config . isWriterGenerationDisabled ( ) && config . isReaderGenerationDisabled ( ) ) { addError ( Messages . EncapsulateFieldConditionChecker_NothingToRefactor ) ; } String readerMethodName = config . getReaderMethodName ( ) ; String writerMethodName = config . getWriterMethodName ( ) ; for ( MethodNodeWrapper aktMethodNode : config . getEnclosingClassNode ( ) . getMethods ( ) ) { if ( aktMethodNode . getName ( ) . equals ( readerMethodName ) && ! config . isReaderGenerationDisabled ( ) ) { addWarning ( Messages . EncapsulateFieldConditionChecker_MethodWithName + aktMethodNode . getName ( ) + Messages . EncapsulateFieldConditionChecker_AlreadyExists ) ; } if ( aktMethodNode . getName ( ) . equals ( writerMethodName ) && ! config . isWriterGenerationDisabled ( ) ) { addWarning ( Messages . EncapsulateFieldConditionChecker_MethodWithName + aktMethodNode . getName ( ) + Messages . EncapsulateFieldConditionChecker_AlreadyExists ) ; } } } public void checkInitialConditions ( ) { if ( ! config . hasSelectedAccessor ( ) && ! config . hasSelectedInstNode ( ) ) { addError ( Messages . EncapsulateFieldConditionChecker_NoInstanceVariableSelected ) ; } else if ( config . getEnclosingClassNode ( ) == null ) { addError ( Messages . EncapsulateFieldConditionChecker_NotInsideAClass ) ; } else if ( selectedNodeIsInstVarNodeAndNotInMethod ( ) ) { addError ( Messages . EncapsulateFieldConditionChecker_NotInsideAMethod ) ; } } private boolean selectedNodeIsInstVarNodeAndNotInMethod ( ) { Node selectedVarNode = SelectionNodeProvider . getSelectedNodeOfType ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , config . getCaretPosition ( ) , InstVarNode . class , InstAsgnNode . class ) ; if ( selectedVarNode == null ) { return false ; } Node enclosingMethod = SelectionNodeProvider . getSelectedNodeOfType ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , config . getCaretPosition ( ) , DefnNode . class ) ; return enclosingMethod == null ; } } package org . rubypeople . rdt . refactoring . core . encapsulatefield ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . EncapsulateFieldPage ; public class EncapsulateFieldRefactoring extends RubyRefactoring { public static final String NAME = Messages . EncapsulateFieldRefactoring_Name ; public EncapsulateFieldRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; EncapsulateFieldConfig config = new EncapsulateFieldConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; EncapsulateFieldConditionChecker checker = new EncapsulateFieldConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { FieldEncapsulator fieldEncapsulator = new FieldEncapsulator ( config ) ; setEditProvider ( fieldEncapsulator ) ; EncapsulateFieldPage page = new EncapsulateFieldPage ( fieldEncapsulator ) ; pages . add ( page ) ; } } } package org . rubypeople . rdt . refactoring . core . encapsulatefield ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . BlockNode ; import org . jruby . ast . CommentNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterLastMethodInClassOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; public class FieldEncapsulator extends MultiEditProvider { public static enum ACCESSOR { ATTR_ACCESSOR , PROTECTED , PUBLIC } private VisibilityNodeWrapper . METHOD_VISIBILITY readerVisibility ; private VisibilityNodeWrapper . METHOD_VISIBILITY writerVisibility ; private EncapsulateFieldConfig config ; public FieldEncapsulator ( EncapsulateFieldConfig config ) { this . config = config ; initVisibilities ( ) ; initGenerationFields ( ) ; } private void initVisibilities ( ) { writerVisibility = ( ! config . hasSelectedAccessor ( ) || ! config . getSelectedAccessor ( ) . isWriter ( ) ? VisibilityNodeWrapper . METHOD_VISIBILITY . PRIVATE : VisibilityNodeWrapper . METHOD_VISIBILITY . PUBLIC ) ; readerVisibility = ( ! config . hasSelectedAccessor ( ) || ! config . getSelectedAccessor ( ) . isReader ( ) ? VisibilityNodeWrapper . METHOD_VISIBILITY . PRIVATE : VisibilityNodeWrapper . METHOD_VISIBILITY . PUBLIC ) ; } private void initGenerationFields ( ) { config . setReaderGenerationDisabled ( isReaderGenerationOptional ( ) ) ; config . setWriterGenerationDisabled ( isWriterGenerationOptional ( ) ) ; } @ Override public Collection < EditProvider > getEditProviders ( ) { Collection < EditProvider > providers = new ArrayList < EditProvider > ( ) ; if ( ! config . isReaderGenerationDisabled ( ) ) { providers . add ( getInsertEditProvider ( false , readerVisibility ) ) ; } if ( ! config . isWriterGenerationDisabled ( ) ) { providers . add ( getInsertEditProvider ( true , writerVisibility ) ) ; } if ( config . hasSelectedAccessor ( ) ) { for ( FCallNode aktAccessorNode : config . getSelectedAccessor ( ) . getAccessorNodes ( ) ) { providers . add ( new DeleteEditProvider ( aktAccessorNode ) ) ; } } return providers ; } private InsertEditProvider getInsertEditProvider ( final boolean writer , final VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) { return new InsertEditProvider ( true ) { @ Override protected Node getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = lastEditInGroup && ! isNextLineEmpty ( offset , document ) ; Node contentNode = createGetterOrSetter ( writer , visibility ) ; return NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , contentNode ) ; } @ Override protected int getOffset ( String document ) { IOffsetProvider offsetProvider = new AfterLastMethodInClassOffsetProvider ( config . getEnclosingClassNode ( ) , document ) ; return offsetProvider . getOffset ( ) ; } } ; } public String getSelectedFieldName ( ) { return ( config . hasSelectedAccessor ( ) ) ? '' + config . getSelectedAccessor ( ) . getAttrName ( ) : config . getSelectedInstNode ( ) . getName ( ) ; } public String getExistingAccessorName ( ) { return ( config . hasSelectedAccessor ( ) ) ? config . getSelectedAccessor ( ) . getAccessorTypeName ( ) : "" ; } public boolean isWriterGenerationOptional ( ) { return writerVisibility . equals ( VisibilityNodeWrapper . METHOD_VISIBILITY . PRIVATE ) ; } public VisibilityNodeWrapper . METHOD_VISIBILITY getWriterVisibility ( ) { return writerVisibility ; } public boolean isReaderGenerationOptional ( ) { return readerVisibility . equals ( VisibilityNodeWrapper . METHOD_VISIBILITY . PRIVATE ) ; } public VisibilityNodeWrapper . METHOD_VISIBILITY getReaderVisibility ( ) { return readerVisibility ; } public void setWriterDisabled ( boolean writerDisabled ) { config . setWriterGenerationDisabled ( writerDisabled ) ; } public void setWriterVisibility ( VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) { writerVisibility = visibility ; } public void setReaderVisibility ( VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) { readerVisibility = visibility ; } public void setReaderDisabled ( boolean readerDisabled ) { config . setReaderGenerationDisabled ( readerDisabled ) ; } protected BlockNode createGetterOrSetter ( final boolean writer , final VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) { return NodeFactory . createGetterSetter ( config . getFieldName ( ) , writer , visibility , getAccessorComments ( writer ) ) ; } private Collection < CommentNode > getAccessorComments ( boolean isSetter ) { ArrayList < CommentNode > matchingComments = new ArrayList < CommentNode > ( ) ; AttrAccessorNodeWrapper accessor = config . getSelectedAccessor ( ) ; if ( accessor != null ) { Collection < FCallNode > accessors = accessor . getAccessorNodes ( ) ; for ( FCallNode currentAccessor : accessors ) { if ( isSetter && currentAccessor . getName ( ) . equals ( "" ) ) { matchingComments . addAll ( currentAccessor . getComments ( ) ) ; } else if ( ! isSetter && currentAccessor . getName ( ) . equals ( "" ) ) { matchingComments . addAll ( currentAccessor . getComments ( ) ) ; } else if ( currentAccessor . getName ( ) . equals ( "" ) ) { matchingComments . addAll ( currentAccessor . getComments ( ) ) ; } } } return resetCommentPositions ( matchingComments ) ; } private Collection < CommentNode > resetCommentPositions ( ArrayList < CommentNode > comments ) { ArrayList < CommentNode > resettedComments = new ArrayList < CommentNode > ( ) ; for ( CommentNode currentComment : comments ) { resettedComments . add ( new CommentNode ( new IDESourcePosition ( "" , - , - , - , - ) , currentComment . getContent ( ) ) ) ; } return resettedComments ; } } package org . rubypeople . rdt . refactoring . core . encapsulatefield ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String EncapsulateFieldConditionChecker_AlreadyExists ; public static String EncapsulateFieldConditionChecker_MethodWithName ; public static String EncapsulateFieldConditionChecker_NoInstanceVariableSelected ; public static String EncapsulateFieldConditionChecker_NothingToRefactor ; public static String EncapsulateFieldConditionChecker_NotInsideAClass ; public static String EncapsulateFieldConditionChecker_NotInsideAMethod ; public static String EncapsulateFieldRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . encapsulatefield ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; public class EncapsulateFieldConfig implements IRefactoringConfig { private IDocumentProvider docProvider ; private int caretPosition ; private boolean readerGenerationDisabled ; private boolean writerGenerationDisabled ; private ClassNodeWrapper enclosingClassNode ; private INameNode selectedInstNode ; private AttrAccessorNodeWrapper selectedAccessor ; public EncapsulateFieldConfig ( IDocumentProvider docProvider , int caretPosition ) { this . docProvider = docProvider ; this . caretPosition = caretPosition ; } public int getCaretPosition ( ) { return caretPosition ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public boolean isReaderGenerationDisabled ( ) { return readerGenerationDisabled ; } public boolean isWriterGenerationDisabled ( ) { return writerGenerationDisabled ; } public ClassNodeWrapper getEnclosingClassNode ( ) { return enclosingClassNode ; } public INameNode getSelectedInstNode ( ) { return selectedInstNode ; } public AttrAccessorNodeWrapper getSelectedAccessor ( ) { return selectedAccessor ; } public void setEnclosingClassNode ( ClassNodeWrapper enclosingClassNode ) { this . enclosingClassNode = enclosingClassNode ; } public void setReaderGenerationDisabled ( boolean readerGenerationDisabled ) { this . readerGenerationDisabled = readerGenerationDisabled ; } public void setSelectedAccessor ( AttrAccessorNodeWrapper selectedAccessor ) { this . selectedAccessor = selectedAccessor ; } public void setSelectedInstNode ( INameNode selectedInstNode ) { this . selectedInstNode = selectedInstNode ; } public void setWriterGenerationDisabled ( boolean writerGenerationDisabled ) { this . writerGenerationDisabled = writerGenerationDisabled ; } public boolean hasSelectedInstNode ( ) { return selectedInstNode != null ; } public boolean hasSelectedAccessor ( ) { return selectedAccessor != null ; } public String getReaderMethodName ( ) { String fieldName = getFieldName ( ) ; return fieldName != null ? fieldName : null ; } public String getWriterMethodName ( ) { String fieldName = getFieldName ( ) ; return fieldName != null ? fieldName + '' : null ; } String getFieldName ( ) { if ( hasSelectedAccessor ( ) ) { return getSelectedAccessor ( ) . getAttrName ( ) ; } if ( hasSelectedInstNode ( ) ) { return getSelectedInstNode ( ) . getName ( ) . substring ( ) ; } return null ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . generateconstructor ; import java . util . Collection ; import java . util . Iterator ; import org . jruby . ast . BlockNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . ConstructorOffsetProvider ; import org . rubypeople . rdt . refactoring . util . Constants ; public class GeneratedConstructor extends InsertEditProvider { private Collection < String > arguments ; private ClassNodeWrapper classNode ; public GeneratedConstructor ( ClassNodeWrapper classNode , Collection < String > arguments ) { super ( true ) ; this . classNode = classNode ; this . arguments = arguments ; } protected BlockNode getInsertNode ( int offset , String document ) { return NodeFactory . createBlockNode ( ! isNextLineEmpty ( offset , document ) , NodeFactory . createNewLineNode ( getConstructorNode ( ) ) ) ; } private DefnNode getConstructorNode ( ) { return NodeFactory . createMethodNode ( Constants . CONSTRUCTOR_NAME , arguments . toArray ( new String [ arguments . size ( ) ] ) , arguments . size ( ) > ? getBody ( arguments ) : null ) ; } private Node getBody ( Collection < String > args ) { Iterator < String > argsIter = args . iterator ( ) ; BlockNode blockNode = new BlockNode ( new IDESourcePosition ( ) ) ; for ( int i = ; i < args . size ( ) ; i ++ ) { String name = argsIter . next ( ) ; InstAsgnNode assignment = NodeFactory . createInstAsgnNode ( '' + name , NodeFactory . createLocalVarNode ( name ) ) ; if ( i > ) { blockNode . add ( NodeFactory . createNewLineNode ( assignment ) ) ; } else { blockNode . add ( assignment ) ; } } return blockNode ; } protected int getOffset ( String document ) { return new ConstructorOffsetProvider ( classNode , document ) . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . generateconstructor ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . pages . ConstructorSelectionPage ; import org . rubypeople . rdt . refactoring . util . Constants ; public class GenerateConstructorRefactoring extends RubyRefactoring { public static final String NAME = Messages . GenerateConstructorRefactoring_Name ; public GenerateConstructorRefactoring ( ) { super ( NAME ) ; ConstructorsGenerator constructorsGenerator = new ConstructorsGenerator ( getDocumentProvider ( ) ) ; setEditProvider ( constructorsGenerator ) ; ConstructorSelectionPage page = new ConstructorSelectionPage ( constructorsGenerator ) ; pages . add ( page ) ; setInfoMessage ( page ) ; } private void setInfoMessage ( ConstructorSelectionPage page ) { if ( getDocumentProvider ( ) . getClassNodeProvider ( ) == null ) return ; StringBuilder classNames = new StringBuilder ( ) ; for ( ClassNodeWrapper classNode : getDocumentProvider ( ) . getClassNodeProvider ( ) . getAllClassNodes ( ) ) { if ( classNode . hasConstructor ( ) ) classNames . append ( classNode . getName ( ) + "" ) ; } if ( classNames . length ( ) != ) page . setMessage ( Messages . GenerateConstructorRefactoring_TheClass + ( ( classNames . length ( ) != ) ? Messages . GenerateConstructorRefactoring_ClassesPluralForm : "" ) + '' + classNames . substring ( , classNames . length ( ) - ) + Messages . GenerateConstructorRefactoring_AlreadyContainsConstructors + "" , RefactoringStatus . WARNING ) ; } } package org . rubypeople . rdt . refactoring . core . generateconstructor ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditAndTreeContentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . CheckableItem ; import org . rubypeople . rdt . refactoring . ui . IParentProvider ; public class ConstructorsGenerator extends EditAndTreeContentProvider { private Collection < TreeClass > classes ; public ConstructorsGenerator ( DocumentProvider docProvider ) { classes = new ArrayList < TreeClass > ( ) ; ClassNodeProvider provider = docProvider . getClassNodeProvider ( ) ; if ( provider != null ) { for ( ClassNodeWrapper node : provider . getAllClassNodes ( ) ) { classes . add ( new TreeClass ( node ) ) ; } } } public Object [ ] getElements ( Object inputElement ) { return classes . toArray ( ) ; } public Collection < EditProvider > getEditProviders ( ) { Collection < EditProvider > constructors = new ArrayList < EditProvider > ( ) ; for ( TreeClass treeClass : classes ) { if ( treeClass . isChecked ( ) ) constructors . add ( treeClass . getGeneratedConstructor ( ) ) ; } return constructors ; } public static class TreeClass extends CheckableItem implements org . rubypeople . rdt . refactoring . ui . IChildrenProvider { private ClassNodeWrapper classNode ; private Collection < TreeAttribute > attrs ; private Collection < Node > attrNodes ; public TreeClass ( ClassNodeWrapper classNode ) { super ( false , false , true ) ; this . classNode = classNode ; attrNodes = classNode . getAttrNodes ( ) ; attrs = new ArrayList < TreeAttribute > ( ) ; for ( Node node : attrNodes ) { attrs . add ( new TreeAttribute ( ( INameNode ) node ) ) ; } } public String toString ( ) { return classNode . getName ( ) ; } public Object [ ] getChildren ( ) { return attrs . toArray ( ) ; } public boolean hasChildren ( ) { return ! attrs . isEmpty ( ) ; } public GeneratedConstructor getGeneratedConstructor ( ) { Collection < String > checkedAttrNodes = new ArrayList < String > ( ) ; for ( TreeAttribute treeAttr : attrs ) { if ( treeAttr . isChecked ( ) ) checkedAttrNodes . add ( treeAttr . getAttrNode ( ) . getName ( ) . substring ( ) ) ; } return new GeneratedConstructor ( classNode , checkedAttrNodes ) ; } public class TreeAttribute extends CheckableItem implements IParentProvider { private INameNode node ; private String name ; public TreeAttribute ( INameNode node ) { super ( false , true , false ) ; name = node . getName ( ) ; if ( name . indexOf ( '' ) == ) name = name . substring ( ) ; this . node = node ; } public String toString ( ) { return name ; } public INameNode getAttrNode ( ) { return node ; } public Object getParent ( ) { return TreeClass . this ; } } } } package org . rubypeople . rdt . refactoring . core . generateconstructor ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String GenerateConstructorRefactoring_AlreadyContainsConstructors ; public static String GenerateConstructorRefactoring_ClassesPluralForm ; public static String GenerateConstructorRefactoring_Name ; public static String GenerateConstructorRefactoring_TheClass ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public interface IRefactoringConfig { IDocumentProvider getDocumentProvider ( ) ; void setDocumentProvider ( IDocumentProvider doc ) ; } package org . rubypeople . rdt . refactoring . core ; import java . io . File ; import java . net . URI ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceStatus ; import org . eclipse . core . resources . ResourceAttributes ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . internal . ui . IRubyStatusConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIStatus ; public class Resources { private Resources ( ) { } public static IStatus checkInSync ( IResource resource ) { return checkInSync ( new IResource [ ] { resource } ) ; } public static IStatus checkInSync ( IResource [ ] resources ) { IStatus result = null ; for ( int i = ; i < resources . length ; i ++ ) { IResource resource = resources [ i ] ; if ( ! resource . isSynchronized ( IResource . DEPTH_INFINITE ) ) { result = addOutOfSync ( result , resource ) ; } } if ( result != null ) return result ; return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } public static IStatus makeCommittable ( IResource resource , Object context ) { return makeCommittable ( new IResource [ ] { resource } , context ) ; } public static IStatus makeCommittable ( IResource [ ] resources , Object context ) { List readOnlyFiles = new ArrayList ( ) ; for ( int i = ; i < resources . length ; i ++ ) { IResource resource = resources [ i ] ; if ( resource . getType ( ) == IResource . FILE && isReadOnly ( resource ) ) readOnlyFiles . add ( resource ) ; } if ( readOnlyFiles . size ( ) == ) return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; Map oldTimeStamps = createModificationStampMap ( readOnlyFiles ) ; IStatus status = ResourcesPlugin . getWorkspace ( ) . validateEdit ( ( IFile [ ] ) readOnlyFiles . toArray ( new IFile [ readOnlyFiles . size ( ) ] ) , context ) ; if ( ! status . isOK ( ) ) return status ; IStatus modified = null ; Map newTimeStamps = createModificationStampMap ( readOnlyFiles ) ; for ( Iterator iter = oldTimeStamps . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { IFile file = ( IFile ) iter . next ( ) ; if ( ! oldTimeStamps . get ( file ) . equals ( newTimeStamps . get ( file ) ) ) modified = addModified ( modified , file ) ; } if ( modified != null ) return modified ; return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } private static Map createModificationStampMap ( List files ) { Map map = new HashMap ( ) ; for ( Iterator iter = files . iterator ( ) ; iter . hasNext ( ) ; ) { IFile file = ( IFile ) iter . next ( ) ; map . put ( file , new Long ( file . getModificationStamp ( ) ) ) ; } return map ; } private static IStatus addModified ( IStatus status , IFile file ) { IStatus entry = RubyUIStatus . createError ( IRubyStatusConstants . VALIDATE_EDIT_CHANGED_CONTENT , Messages . format ( "" , file . getFullPath ( ) . toString ( ) ) , null ) ; if ( status == null ) { return entry ; } else if ( status . isMultiStatus ( ) ) { ( ( MultiStatus ) status ) . add ( entry ) ; return status ; } else { MultiStatus result = new MultiStatus ( RubyPlugin . getPluginId ( ) , IRubyStatusConstants . VALIDATE_EDIT_CHANGED_CONTENT , "" , null ) ; result . add ( status ) ; result . add ( entry ) ; return result ; } } private static IStatus addOutOfSync ( IStatus status , IResource resource ) { IStatus entry = new Status ( IStatus . ERROR , ResourcesPlugin . PI_RESOURCES , IResourceStatus . OUT_OF_SYNC_LOCAL , Messages . format ( "" , resource . getFullPath ( ) . toString ( ) ) , null ) ; if ( status == null ) { return entry ; } else if ( status . isMultiStatus ( ) ) { ( ( MultiStatus ) status ) . add ( entry ) ; return status ; } else { MultiStatus result = new MultiStatus ( ResourcesPlugin . PI_RESOURCES , IResourceStatus . OUT_OF_SYNC_LOCAL , "" , null ) ; result . add ( status ) ; result . add ( entry ) ; return result ; } } public static String [ ] getLocationOSStrings ( IResource [ ] resources ) { List result = new ArrayList ( resources . length ) ; for ( int i = ; i < resources . length ; i ++ ) { IPath location = resources [ i ] . getLocation ( ) ; if ( location != null ) result . add ( location . toOSString ( ) ) ; } return ( String [ ] ) result . toArray ( new String [ result . size ( ) ] ) ; } public static String getLocationString ( IResource resource ) { URI uri = resource . getLocationURI ( ) ; if ( uri == null ) return null ; return EFS . SCHEME_FILE . equalsIgnoreCase ( uri . getScheme ( ) ) ? new File ( uri ) . getAbsolutePath ( ) : uri . toString ( ) ; } public static boolean isReadOnly ( IResource resource ) { ResourceAttributes resourceAttributes = resource . getResourceAttributes ( ) ; if ( resourceAttributes == null ) return false ; return resourceAttributes . isReadOnly ( ) ; } static void setReadOnly ( IResource resource , boolean readOnly ) { ResourceAttributes resourceAttributes = resource . getResourceAttributes ( ) ; if ( resourceAttributes == null ) return ; resourceAttributes . setReadOnly ( readOnly ) ; try { resource . setResourceAttributes ( resourceAttributes ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } } package org . rubypeople . rdt . refactoring . core . pullup ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . BlockNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . ConstructorOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . MethodOffsetProvider ; public class UpPulledMethods extends InsertEditProvider { private Collection < MethodNodeWrapper > methodNodes ; private boolean constructors ; private ClassNodeWrapper classNode ; public UpPulledMethods ( Collection < MethodNodeWrapper > methodNodes , ClassNodeWrapper classNode , boolean constructors ) { super ( true ) ; this . methodNodes = methodNodes ; this . constructors = constructors ; this . classNode = classNode ; } @ Override protected BlockNode getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = lastEditInGroup && ! isNextLineEmpty ( offset , document ) ; return NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , getMethodNodes ( methodNodes ) ) ; } private Node [ ] getMethodNodes ( Collection < MethodNodeWrapper > nodeCollection ) { Collection < Node > nodes = new ArrayList < Node > ( ) ; boolean first = true ; for ( MethodNodeWrapper methodNode : nodeCollection ) { if ( first ) { first = false ; } else { nodes . add ( NodeFactory . createNewLineNode ( null ) ) ; } nodes . add ( NodeFactory . createNewLineNode ( methodNode . getWrappedNode ( ) ) ) ; } return nodes . toArray ( new Node [ nodes . size ( ) ] ) ; } @ Override protected int getOffset ( String document ) { IOffsetProvider offsetProvider ; if ( constructors ) { offsetProvider = new ConstructorOffsetProvider ( classNode , document ) ; } else { offsetProvider = new MethodOffsetProvider ( classNode , document ) ; } return offsetProvider . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . pullup ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . MethodUpPullerSelectionPage ; public class PullUpRefactoring extends RubyRefactoring { public static final String NAME = "" ; public PullUpRefactoring ( ) { super ( NAME ) ; MethodUpPuller upPuller = new MethodUpPuller ( getDocumentProvider ( ) ) ; setEditProvider ( upPuller ) ; pages . add ( new MethodUpPullerSelectionPage ( upPuller ) ) ; } } package org . rubypeople . rdt . refactoring . core . pullup ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditAndTreeContentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProviderGroups ; import org . rubypeople . rdt . refactoring . editprovider . ITreeClass ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . IItemSelectionReceiver ; import org . rubypeople . rdt . refactoring . ui . IParentProvider ; public class MethodUpPuller extends EditAndTreeContentProvider implements IItemSelectionReceiver { private Object [ ] selectedTreeItems ; private ClassNodeProvider projectClassNodeProvider ; private ClassNodeProvider classNodeProvider ; public MethodUpPuller ( DocumentProvider documentProvider ) { this . projectClassNodeProvider = documentProvider . getProjectClassNodeProvider ( ) ; this . classNodeProvider = documentProvider . getClassNodeProvider ( ) ; initTreeClasses ( classNodeProvider ) ; } @ Override protected ITreeClass createTreeClass ( ClassNodeWrapper classNode ) { return new TreeClass ( classNode ) ; } @ Override public Collection < EditProvider > getEditProviders ( ) { EditProviderGroups editProviderGroups = new EditProviderGroups ( ) ; if ( selectedTreeItems != null ) { for ( Object o : selectedTreeItems ) { if ( o instanceof TreeClass ) { TreeClass treeClass = ( TreeClass ) o ; treeClass . addUpPulledMethods ( editProviderGroups ) ; } } } return editProviderGroups . getAllEditProviders ( ) ; } public void setSelectedItems ( Object [ ] checkedElements ) { selectedTreeItems = checkedElements . clone ( ) ; } public class TreeClass implements org . rubypeople . rdt . refactoring . ui . IChildrenProvider , ITreeClass { private ClassNodeWrapper classNode ; private Collection < DownPushableMethod > downPushableMethods ; private ClassNodeWrapper superClass ; public TreeClass ( ClassNodeWrapper classNode ) { this . classNode = classNode ; downPushableMethods = new ArrayList < DownPushableMethod > ( ) ; superClass = projectClassNodeProvider . getSuperClassOf ( classNode . getSuperClassName ( ) ) ; if ( superClass != null ) { for ( MethodNodeWrapper methodNode : classNode . getMethods ( ) ) { downPushableMethods . add ( new DownPushableMethod ( methodNode ) ) ; } } } public void addUpPulledMethods ( EditProviderGroups editProviderGroups ) { Collection < MethodNodeWrapper > checkedMethods = getCheckedMethods ( ) ; String childClassName = superClass . getName ( ) ; if ( classNodeProvider . hasClassNode ( childClassName ) ) { ClassNodeWrapper classNode = classNodeProvider . getClassNode ( childClassName ) ; addUpPulledMethods ( classNode , checkedMethods , editProviderGroups ) ; } else { addUpPulledMethodsClass ( childClassName , checkedMethods , editProviderGroups ) ; } addRemoveEdits ( checkedMethods , editProviderGroups ) ; } private void addRemoveEdits ( Collection < MethodNodeWrapper > checkedMethods , EditProviderGroups editProviderGroups ) { for ( MethodNodeWrapper methodNode : checkedMethods ) { editProviderGroups . add ( "" , new DeleteEditProvider ( methodNode . getWrappedNode ( ) ) ) ; } } private void addUpPulledMethods ( ClassNodeWrapper childClassNode , Collection < MethodNodeWrapper > checkedMethods , EditProviderGroups editProviderGroups ) { Collection < MethodNodeWrapper > constructorNodes = new ArrayList < MethodNodeWrapper > ( ) ; Collection < MethodNodeWrapper > methodNodes = new ArrayList < MethodNodeWrapper > ( ) ; separateConstructors ( checkedMethods , methodNodes , constructorNodes ) ; if ( ! constructorNodes . isEmpty ( ) ) { UpPulledMethods constructors = new UpPulledMethods ( constructorNodes , childClassNode , true ) ; editProviderGroups . add ( "" + childClassNode . getName ( ) , constructors ) ; } if ( ! methodNodes . isEmpty ( ) ) { UpPulledMethods methods = new UpPulledMethods ( methodNodes , childClassNode , false ) ; editProviderGroups . add ( "" + childClassNode . getName ( ) , methods ) ; } } private void separateConstructors ( Collection < MethodNodeWrapper > nodes , Collection < MethodNodeWrapper > methodNodes , Collection < MethodNodeWrapper > constructorNodes ) { for ( MethodNodeWrapper method : nodes ) { if ( method . getSignature ( ) . isConstructor ( ) ) constructorNodes . add ( method ) ; else methodNodes . add ( method ) ; } } private Collection < MethodNodeWrapper > getCheckedMethods ( ) { Collection < Object > allCheckedItems = Arrays . asList ( selectedTreeItems ) ; Collection < MethodNodeWrapper > checkedMethods = new ArrayList < MethodNodeWrapper > ( ) ; for ( DownPushableMethod method : downPushableMethods ) { if ( allCheckedItems . contains ( method ) ) checkedMethods . add ( method . getMethodNode ( ) ) ; } return checkedMethods ; } private void addUpPulledMethodsClass ( String className , Collection < MethodNodeWrapper > checkedMethods , EditProviderGroups editProviderGroups ) { UpPulledMethodsClass methodsClass = new UpPulledMethodsClass ( className , checkedMethods ) ; editProviderGroups . add ( "" , methodsClass ) ; } public String toString ( ) { return classNode . getName ( ) ; } public Object [ ] getChildren ( ) { return downPushableMethods . toArray ( ) ; } public boolean hasChildren ( ) { return ! downPushableMethods . isEmpty ( ) ; } public class DownPushableMethod implements IParentProvider { private MethodNodeWrapper methodNode ; public DownPushableMethod ( MethodNodeWrapper methodNode ) { this . methodNode = methodNode ; } public String toString ( ) { return methodNode . getName ( ) ; } public Object getParent ( ) { return TreeClass . this ; } public TreeClass getTreeClass ( ) { return TreeClass . this ; } public MethodNodeWrapper getMethodNode ( ) { return methodNode ; } } } } package org . rubypeople . rdt . refactoring . core . pullup ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . BlockNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . pushdown . NewClassOffsetProvier ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; public class UpPulledMethodsClass extends InsertEditProvider { private Collection < MethodNodeWrapper > methodNodes ; private Collection < MethodNodeWrapper > constructorNodes ; private String className ; public UpPulledMethodsClass ( String className , Collection < MethodNodeWrapper > allMethodNodes ) { super ( true ) ; this . className = className ; initConstrucorAndMethodNodes ( allMethodNodes ) ; } private void initConstrucorAndMethodNodes ( Collection < MethodNodeWrapper > allMethodNodes ) { methodNodes = new ArrayList < MethodNodeWrapper > ( ) ; constructorNodes = new ArrayList < MethodNodeWrapper > ( ) ; for ( MethodNodeWrapper node : allMethodNodes ) { if ( node . getSignature ( ) . isConstructor ( ) ) constructorNodes . add ( node ) ; else methodNodes . add ( node ) ; } } @ Override protected BlockNode getInsertNode ( int offset , String document ) { if ( firstEditInGroup ) { setInsertType ( INSERT_AT_BEGIN_OF_LINE ) ; } boolean needsNewLineAtEndOfBlock = lastEditInGroup && ! isNextLineEmpty ( offset , document ) ; Node classNode = getClassNode ( ) ; BlockNode blockNode = NodeFactory . createBlockNode ( ) ; blockNode . add ( classNode ) ; if ( ! firstEditInGroup ) blockNode . add ( NodeFactory . createNewLineNode ( null ) ) ; if ( needsNewLineAtEndOfBlock ) blockNode . add ( NodeFactory . createNewLineNode ( null ) ) ; return blockNode ; } private Node getClassNode ( ) { return NodeFactory . createNewLineNode ( NodeFactory . createClassNode ( className , getBody ( ) ) ) ; } private Node getBody ( ) { BlockNode body = new BlockNode ( new IDESourcePosition ( ) ) ; body . add ( NodeFactory . createNewLineNode ( null ) ) ; for ( MethodNodeWrapper constructor : constructorNodes ) { body . add ( NodeFactory . createNewLineNode ( constructor . getWrappedNode ( ) ) ) ; } for ( MethodNodeWrapper method : methodNodes ) { body . add ( NodeFactory . createNewLineNode ( method . getWrappedNode ( ) ) ) ; } body . add ( NodeFactory . createNewLineNode ( null ) ) ; return body ; } @ Override protected int getOffset ( String document ) { IOffsetProvider offsetProvider = new NewClassOffsetProvier ( ) ; return offsetProvider . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core ; import org . eclipse . core . resources . IFile ; public interface IRefactoringContext { public abstract int getCaretPosition ( ) ; public abstract int getStartOffset ( ) ; public abstract int getEndOffset ( ) ; public abstract String getSource ( ) ; public IFile getActiveFile ( ) ; } package org . rubypeople . rdt . refactoring . core . formatsource ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String FormatSourceConditionChecker_NothingToDo ; public static String FormatSourceRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . formatsource ; import java . io . PrintWriter ; import java . io . StringWriter ; import org . rubypeople . rdt . core . formatter . FormatHelper ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; import org . rubypeople . rdt . core . formatter . ReWriterFactory ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . parser . RubyParserWithComments ; public class PreviewGeneratorImpl implements PreviewGenerator { private String source ; public PreviewGeneratorImpl ( String source ) { this . source = source ; } public String getPreview ( FormatHelper formatHelper ) { StringWriter writer = new StringWriter ( ) ; ReWriterFactory factory = new ReWriterFactory ( new ReWriterContext ( new PrintWriter ( writer ) , source , formatHelper ) ) ; RubyParser parser = new RubyParserWithComments ( ) ; ReWriteVisitor visitor = factory . createReWriteVisitor ( ) ; parser . parse ( source ) . getAST ( ) . accept ( visitor ) ; visitor . flushStream ( ) ; return writer . getBuffer ( ) . toString ( ) ; } } package org . rubypeople . rdt . refactoring . core . formatsource ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public class FormatSourceConfig implements IRefactoringConfig { private IDocumentProvider documentProvider ; public FormatSourceConfig ( DocumentProvider documentProvider ) { this . documentProvider = documentProvider ; } public IDocumentProvider getDocumentProvider ( ) { return documentProvider ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . documentProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . formatsource ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; public class FormattedSourceEditProvider extends ReplaceEditProvider { private Node fileRootNode ; public FormattedSourceEditProvider ( FormatSourceConfig config ) { super ( true ) ; this . fileRootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; } @ Override protected int getOffsetLength ( ) { return fileRootNode . getPosition ( ) . getEndOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return fileRootNode ; } @ Override protected int getOffset ( String document ) { return ; } } package org . rubypeople . rdt . refactoring . core . formatsource ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . FormatSourcePage ; import org . rubypeople . rdt . refactoring . util . FileHelper ; public class FormatSourceRefactoring extends RubyRefactoring { public static final String NAME = Messages . FormatSourceRefactoring_Name ; private static final String source = "" + "" + "" + "" + "" + "" + "" + "" + "" ; private FormattedSourceEditProvider provider ; public FormatSourceRefactoring ( ) { super ( NAME ) ; FormatSourceConfig config = new FormatSourceConfig ( getDocumentProvider ( ) ) ; FormatSourceConditionChecker checker = new FormatSourceConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { provider = new FormattedSourceEditProvider ( config ) ; setEditProvider ( provider ) ; String lineDelmiter = FileHelper . getLineDelimiter ( config . getDocumentProvider ( ) . getActiveFileContent ( ) ) ; EditableFormatHelper formatHelper = new EditableFormatHelper ( lineDelmiter ) ; FormatSourcePage page = new FormatSourcePage ( formatHelper , new PreviewGeneratorImpl ( source ) ) ; pages . add ( page ) ; } } } package org . rubypeople . rdt . refactoring . core . formatsource ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; public class FormatSourceConditionChecker extends RefactoringConditionChecker { private FormatSourceConfig config ; public FormatSourceConditionChecker ( FormatSourceConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( FormatSourceConfig ) configObj ; } @ Override protected void checkFinalConditions ( ) { } @ Override protected void checkInitialConditions ( ) { if ( config == null ) { addError ( Messages . FormatSourceConditionChecker_NothingToDo ) ; } } } package org . rubypeople . rdt . refactoring . core . formatsource ; import org . rubypeople . rdt . core . formatter . FormatHelper ; public interface PreviewGenerator { public abstract String getPreview ( FormatHelper formatHelper ) ; } package org . rubypeople . rdt . refactoring . core ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Map ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public abstract class RefactoringConditionChecker implements IRefactoringConditionChecker { private Map < String , Collection < String > > messages ; private IDocumentProvider docProvider ; private final IRefactoringConfig config ; public RefactoringConditionChecker ( IRefactoringConfig config ) { this . docProvider = config . getDocumentProvider ( ) ; this . config = config ; initMessages ( ) ; addLocalInitialErrors ( ) ; if ( shouldPerform ( true ) ) { init ( config ) ; } } public boolean shouldPerform ( boolean onlyInternalErrors ) { if ( ! onlyInternalErrors && shouldPerform ( true ) ) { checkInitialConditions ( ) ; } return messages . get ( IRefactoringConditionChecker . ERRORS ) . isEmpty ( ) ; } public boolean shouldPerform ( ) { return shouldPerform ( false ) ; } public Map < String , Collection < String > > getFinalMessages ( ) { initMessages ( ) ; checkFinalConditions ( ) ; checkForSyntaxErrors ( ) ; return messages ; } private void checkForSyntaxErrors ( ) { boolean syntaxError = false ; for ( String file : docProvider . getFileNames ( ) ) { if ( NodeProvider . hasSyntaxErrors ( file , docProvider . getFileContent ( file ) ) ) { syntaxError = true ; } } if ( syntaxError ) { addWarning ( Messages . RefactoringConditionChecker_SyntaxErrorInProject ) ; } } private void initMessages ( ) { messages = new LinkedHashMap < String , Collection < String > > ( ) ; messages . put ( IRefactoringConditionChecker . ERRORS , new ArrayList < String > ( ) ) ; messages . put ( IRefactoringConditionChecker . WARNING , new ArrayList < String > ( ) ) ; } public Map < String , Collection < String > > getInitialMessages ( ) { initMessages ( ) ; addInitialMessages ( ) ; return messages ; } private void addInitialMessages ( ) { addLocalInitialErrors ( ) ; if ( shouldPerform ( true ) ) { checkInitialConditions ( ) ; } } private void addLocalInitialErrors ( ) { String fileName = null ; try { fileName = docProvider . getActiveFileName ( ) ; if ( docProvider . getActiveFileContent ( ) . equals ( "" ) ) { addError ( Messages . RefactoringConditionChecker_EmptyDocument ) ; } for ( String aktFileName : docProvider . getFileNames ( ) ) { fileName = aktFileName ; docProvider . getRootNode ( aktFileName ) ; } } catch ( SyntaxException se ) { String activeFileName = docProvider . getActiveFileName ( ) ; if ( fileName == null || fileName . equals ( activeFileName ) ) { addError ( Messages . RefactoringConditionChecker_SyntaxErrorInCurrent ) ; } } if ( NodeProvider . hasSyntaxErrors ( docProvider . getActiveFileName ( ) , docProvider . getActiveFileContent ( ) ) ) { addError ( Messages . RefactoringConditionChecker_SyntaxErrorInCurrent ) ; } } protected void addError ( String message ) { messages . get ( IRefactoringConditionChecker . ERRORS ) . add ( message ) ; } protected void addWarning ( String message ) { messages . get ( IRefactoringConditionChecker . WARNING ) . add ( message ) ; } protected boolean hasErrors ( ) { return ! messages . get ( IRefactoringConditionChecker . ERRORS ) . isEmpty ( ) ; } protected abstract void checkInitialConditions ( ) ; protected void checkFinalConditions ( ) { } public abstract void init ( IRefactoringConfig configObj ) ; public IRefactoringConfig getConfig ( ) { return config ; } } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ClassNode ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class ClassFinder implements IClassFinder { private final String name ; private Collection < ClassNodeWrapper > classNodes ; private String modulePrefix ; private interface INodeAcceptor { boolean accept ( PartialClassNodeWrapper node ) ; } public ClassFinder ( IDocumentProvider doc , String name , String modulePrefix ) { this . name = name ; this . modulePrefix = modulePrefix ; classNodes = new ArrayList < ClassNodeWrapper > ( ) ; classNodes . addAll ( doc . getProjectClassNodeProvider ( ) . getAllClassNodes ( ) ) ; } private Collection < ClassNode > find ( INodeAcceptor acceptor ) { Collection < ClassNode > found = new ArrayList < ClassNode > ( ) ; for ( ClassNodeWrapper classNode : classNodes ) { for ( PartialClassNodeWrapper node : classNode . getPartialClassNodes ( ) ) { if ( acceptor . accept ( node ) ) { found . add ( ( ClassNode ) node . getWrappedNode ( ) ) ; } } } return found ; } public Collection < ClassNode > findParts ( ) { return find ( new INodeAcceptor ( ) { public boolean accept ( PartialClassNodeWrapper node ) { return node . getClassName ( ) . equals ( modulePrefix + name ) ; } } ) ; } public Collection < ClassNode > findChildren ( ) { return find ( new INodeAcceptor ( ) { public boolean accept ( PartialClassNodeWrapper node ) { String fullName = node . getModulePrefix ( ) ; if ( ! "" . equals ( fullName ) ) { fullName += "" ; } fullName += node . getSuperClassName ( ) ; return ( fullName ) . equals ( modulePrefix + name ) ; } } ) ; } } package org . rubypeople . rdt . refactoring . core . renameclass ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String RenameClassConditionChecker_PleaseSelectNameOfAClassDeclaration ; public static String RenameClassRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . CallNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . util . NameHelper ; public class ClassInstanciationFinder implements IClassInstanciationFinder { private String modulePrefix ; public Collection < ConstructorCall > findAll ( IDocumentProvider doc , String name , String modulePrefix ) { this . modulePrefix = modulePrefix ; Collection < ConstructorCall > found = new ArrayList < ConstructorCall > ( ) ; for ( String fileName : doc . getFileNames ( ) ) { if ( ! fileName . equals ( doc . getActiveFileName ( ) ) ) { addIfCreatesInstance ( name , found , new StringDocumentProvider ( fileName , doc . getFileContent ( fileName ) ) ) ; } } addIfCreatesInstance ( name , found , new StringDocumentProvider ( doc . getActiveFileName ( ) , doc . getActiveFileContent ( ) ) ) ; return found ; } private void addIfCreatesInstance ( String name , Collection < ConstructorCall > found , DocumentProvider file ) { for ( Node node : NodeProvider . getSubNodes ( file . getActiveFileRootNode ( ) , CallNode . class ) ) { CallNode call = ( CallNode ) node ; if ( isConstructorFor ( name , call ) ) { found . add ( new ConstructorCall ( call ) ) ; } } } private boolean isConstructorFor ( String name , CallNode call ) { return isCallToNew ( call ) && ( ( isNotInModule ( ) && createsAnInstance ( name , call ) ) || createsAnInstanceWithFullModulePath ( name , call ) ) ; } private boolean isCallToNew ( CallNode call ) { return call . getName ( ) . equals ( "" ) ; } private boolean createsAnInstanceWithFullModulePath ( String name , CallNode call ) { return ( call . getReceiverNode ( ) instanceof Colon2Node && NameHelper . getFullyQualifiedName ( call . getReceiverNode ( ) ) . equals ( modulePrefix + name ) ) ; } private boolean isNotInModule ( ) { return modulePrefix == null || "" . equals ( modulePrefix ) ; } private boolean createsAnInstance ( String name , CallNode call ) { return call . getReceiverNode ( ) instanceof ConstNode && ( ( ConstNode ) call . getReceiverNode ( ) ) . getName ( ) . equals ( name ) ; } } package org . rubypeople . rdt . refactoring . core . renameclass ; import org . jruby . ast . ClassNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class RenameClassConditionChecker extends RefactoringConditionChecker { public static final String DEFAULT_ERROR = Messages . RenameClassConditionChecker_PleaseSelectNameOfAClassDeclaration ; private RenameClassConfig config ; public RenameClassConditionChecker ( RenameClassConfig config ) { super ( config ) ; } @ Override public void init ( IRefactoringConfig configObj ) { config = ( RenameClassConfig ) configObj ; config . setDocumentWithIncludingProvider ( new DocumentWithIncluding ( config . getDocumentProvider ( ) ) ) ; ClassNodeWrapper classNode = null ; try { classNode = SelectionNodeProvider . getSelectedClassNode ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , config . getOffset ( ) ) ; if ( ! NodeUtil . positionIsInNode ( config . getOffset ( ) , ( ( ClassNode ) classNode . getWrappedNode ( ) ) . getCPath ( ) ) ) { return ; } } catch ( NoClassNodeException e ) { return ; } String modulePrefix = classNode . getFirstPartialClassNode ( ) . getModulePrefix ( ) ; if ( "" . equals ( modulePrefix ) ) { config . setModulePrefix ( "" ) ; } else { config . setModulePrefix ( modulePrefix + "" ) ; } config . setSelectedNode ( ( ClassNode ) classNode . getFirstPartialClassNode ( ) . getWrappedNode ( ) ) ; config . setNewName ( classNode . getName ( ) ) ; } @ Override protected void checkInitialConditions ( ) { if ( config . getSelectedNode ( ) == null ) { addError ( DEFAULT_ERROR ) ; } } } package org . rubypeople . rdt . refactoring . core . renameclass ; import org . jruby . ast . ClassNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . ui . INewNameReceiver ; public class RenameClassConfig implements INewNameReceiver , IRefactoringConfig { private IDocumentProvider documentWithIncludingProvider ; private final int offset ; private ClassNode selectedNode ; private String newName ; private String modulePrefix ; private IDocumentProvider docProvider ; private String fOldName ; public RenameClassConfig ( IDocumentProvider docProvider , int offset ) { this . docProvider = docProvider ; this . offset = offset ; } public void setDocumentWithIncludingProvider ( IDocumentProvider documentWithIncludingProvider ) { this . documentWithIncludingProvider = documentWithIncludingProvider ; } public int getOffset ( ) { return offset ; } public void setSelectedNode ( ClassNode selectedNode ) { this . selectedNode = selectedNode ; this . fOldName = selectedNode . getCPath ( ) . getName ( ) ; } public void setNewName ( String name ) { newName = name ; } public IDocumentProvider getDocumentWithIncludingProvider ( ) { return documentWithIncludingProvider ; } public String getNewName ( ) { return newName ; } public ClassNode getSelectedNode ( ) { return selectedNode ; } public void setModulePrefix ( String modulePrefix ) { this . modulePrefix = modulePrefix ; } public String getModulePrefix ( ) { return modulePrefix ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } public String getOldName ( ) { return fOldName ; } } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . Collection ; import org . jruby . ast . ClassNode ; public interface IClassFinder { Collection < ClassNode > findParts ( ) ; Collection < ClassNode > findChildren ( ) ; } package org . rubypeople . rdt . refactoring . core . renameclass ; import org . jruby . ast . CallNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . util . NameHelper ; public class ConstructorCall { private final CallNode node ; public ConstructorCall ( CallNode node ) { assert node . getName ( ) . equals ( "" ) ; assert node . getReceiverNode ( ) instanceof ConstNode || node . getReceiverNode ( ) instanceof Colon2Node ; this . node = node ; } public String getClassName ( ) { return NameHelper . getFullyQualifiedName ( node . getReceiverNode ( ) ) ; } public CallNode getNode ( ) { return node ; } public Node getArgs ( ) { return node . getArgsNode ( ) ; } public void setName ( String newName ) { if ( node . getReceiverNode ( ) instanceof ConstNode ) { ( ( ConstNode ) node . getReceiverNode ( ) ) . setName ( newName ) ; } else { ( ( Colon2Node ) node . getReceiverNode ( ) ) . setName ( newName ) ; } } public int getReceiverOffset ( ) { return node . getReceiverNode ( ) . getPosition ( ) . getStartOffset ( ) ; } public int getReceiverLength ( ) { return node . getReceiverNode ( ) . getPosition ( ) . getEndOffset ( ) - getReceiverOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . Collection ; import org . jruby . ast . ClassNode ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . ScopingNodeRenameEditProvider ; public class RenameClassEditProvider implements IMultiFileEditProvider { private final RenameClassConfig config ; private IDocumentProvider document ; public RenameClassEditProvider ( RenameClassConfig config ) { this . config = config ; document = config . getDocumentWithIncludingProvider ( ) ; } private ChildClassesRenameEditProvider createChildrenEditProvider ( ) { Collection < ClassNode > childClasses = new ClassFinder ( document , config . getOldName ( ) , config . getModulePrefix ( ) ) . findChildren ( ) ; return new ChildClassesRenameEditProvider ( childClasses , config . getNewName ( ) ) ; } private ScopingNodeRenameEditProvider createPartialsEditProvider ( ) { Collection < ClassNode > classNodes = new ClassFinder ( document , config . getOldName ( ) , config . getModulePrefix ( ) ) . findParts ( ) ; return new ScopingNodeRenameEditProvider ( classNodes , config . getNewName ( ) ) ; } private ConstructorRenameEditProvider createConstructorEditProvider ( ) { Collection < ConstructorCall > allCalls = new ClassInstanciationFinder ( ) . findAll ( document , config . getOldName ( ) , config . getModulePrefix ( ) ) ; return new ConstructorRenameEditProvider ( allCalls , config . getNewName ( ) ) ; } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { MultiFileEditProvider fileEdits = new MultiFileEditProvider ( ) ; fileEdits . addEditProviders ( createConstructorEditProvider ( ) . getEditProviders ( ) ) ; fileEdits . addEditProviders ( createChildrenEditProvider ( ) . getEditProviders ( ) ) ; fileEdits . addEditProviders ( createPartialsEditProvider ( ) . getEditProviders ( ) ) ; return fileEdits . getFileEditProviders ( ) ; } } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public interface IClassInstanciationFinder { Collection < ConstructorCall > findAll ( IDocumentProvider doc , String name , String modulePrefix ) ; } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ConstNode ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . SimpleNodeEditProvider ; public class ChildClassesRenameEditProvider { private final Collection < ClassNode > classes ; private final String newName ; public ChildClassesRenameEditProvider ( Collection < ClassNode > childClasses , String newName ) { this . classes = childClasses ; this . newName = newName ; } protected Collection < FileEditProvider > getEditProviders ( ) { Collection < FileEditProvider > edits = new ArrayList < FileEditProvider > ( ) ; for ( ClassNode klass : classes ) { ( ( ConstNode ) klass . getSuperNode ( ) ) . setName ( newName ) ; edits . add ( new FileEditProvider ( klass . getPosition ( ) . getFile ( ) , new SimpleNodeEditProvider ( klass . getSuperNode ( ) ) ) ) ; } return edits ; } } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . ArrayList ; import org . rubypeople . rdt . refactoring . core . ConstNameValidator ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . NewNameListener ; import org . rubypeople . rdt . refactoring . ui . pages . RenamePage ; public class RenameClassRefactoring extends RubyRefactoring { public static final String NAME = Messages . RenameClassRefactoring_Name ; public RenameClassRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; RenameClassConfig renameClassConfig = new RenameClassConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; RenameClassConditionChecker conditionChecker = new RenameClassConditionChecker ( renameClassConfig ) ; setRefactoringConditionChecker ( conditionChecker ) ; if ( conditionChecker . shouldPerform ( ) ) { RenameClassEditProvider editProvider = new RenameClassEditProvider ( renameClassConfig ) ; setEditProvider ( editProvider ) ; setFileNameChangeProvider ( new RenameClassFileNameChangeProvider ( renameClassConfig ) ) ; pages . add ( new RenamePage ( NAME , renameClassConfig . getOldName ( ) , new NewNameListener ( renameClassConfig , new ConstNameValidator ( ) , new ArrayList < String > ( ) ) ) ) ; } } } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . Collection ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . resources . IFile ; import org . rubypeople . rdt . refactoring . editprovider . FileNameChangeProvider ; public class RenameClassFileNameChangeProvider extends FileNameChangeProvider { private final RenameClassConfig config ; public RenameClassFileNameChangeProvider ( RenameClassConfig renameClassConfig ) { this . config = renameClassConfig ; } @ Override public Map < String , String > getFilesToRename ( Collection < IFile > objects ) { HashMap < String , String > filesToRename = new HashMap < String , String > ( ) ; for ( IFile file : objects ) { String name = file . getName ( ) ; name = name . replaceAll ( "" + file . getFileExtension ( ) + "" , "" ) ; if ( name . equals ( config . getOldName ( ) ) ) { filesToRename . put ( file . getFullPath ( ) . toString ( ) , config . getNewName ( ) + "" ) ; } } return filesToRename ; } } package org . rubypeople . rdt . refactoring . core . renameclass ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; public class ConstructorRenameEditProvider { private static class ConstructorEditProvider extends ReplaceEditProvider { private final ConstructorCall call ; public ConstructorEditProvider ( ConstructorCall call ) { this . call = call ; } @ Override protected int getOffsetLength ( ) { return call . getReceiverLength ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return call . getNode ( ) . getReceiverNode ( ) ; } @ Override protected int getOffset ( String document ) { return call . getReceiverOffset ( ) ; } } private final Collection < ConstructorCall > calls ; private final String newName ; public ConstructorRenameEditProvider ( Collection < ConstructorCall > calls , String newName ) { this . calls = calls ; this . newName = newName ; } protected Collection < FileEditProvider > getEditProviders ( ) { Collection < FileEditProvider > edits = new ArrayList < FileEditProvider > ( ) ; for ( ConstructorCall call : calls ) { call . setName ( newName ) ; edits . add ( new FileEditProvider ( call . getNode ( ) . getPosition ( ) . getFile ( ) , new ConstructorEditProvider ( call ) ) ) ; } return edits ; } } package org . rubypeople . rdt . refactoring . core . convertlocaltofield ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String ConvertLocalToFieldRefactoring_Name ; public static String TempToFieldConditionChecker_AlreadyExists ; public static String TempToFieldConditionChecker_CannotConvertBlockParameters ; public static String TempToFieldConditionChecker_CannotConvertMethodParameters ; public static String TempToFieldConditionChecker_CannotConvertNonlocalVars ; public static String TempToFieldConditionChecker_FieldWithName ; public static String TempToFieldConditionChecker_NoEnclosingClassToInsert ; public static String TempToFieldConditionChecker_NoLocalVarAtpos ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . convertlocaltofield ; import org . jruby . ast . MethodDefNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; public class LocalToFieldConfig implements IRefactoringConfig { private IDocumentProvider docProvider ; private int caretPosition ; private LocalNodeWrapper selectedNode ; private ClassNodeWrapper enclosingClassNode ; private MethodDefNode enclosingMethod ; private boolean classField ; private String newName ; public LocalToFieldConfig ( IDocumentProvider docProvider , int caretPosition ) { this . docProvider = docProvider ; this . caretPosition = caretPosition ; } public boolean isClassField ( ) { return classField ; } public void setClassField ( boolean classField ) { this . classField = classField ; } public String getNewName ( ) { return newName ; } public void setNewName ( String newName ) { this . newName = newName ; } public int getCaretPosition ( ) { return caretPosition ; } public ClassNodeWrapper getEnclosingClassNode ( ) { return enclosingClassNode ; } public void setEnclosingClassNode ( ClassNodeWrapper enclosingClassNode ) { this . enclosingClassNode = enclosingClassNode ; } public MethodDefNode getEnclosingMethod ( ) { return enclosingMethod ; } public void setEnclosingMethod ( MethodDefNode enclosingMethod ) { this . enclosingMethod = enclosingMethod ; } public LocalNodeWrapper getSelectedNode ( ) { return selectedNode ; } public void setSelectedNode ( LocalNodeWrapper selectedItem ) { this . selectedNode = selectedItem ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . convertlocaltofield ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Map ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . FixnumNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . Node ; import org . jruby . ast . StrNode ; import org . jruby . ast . VCallNode ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; import org . rubypeople . rdt . refactoring . util . Constants ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class LocalToFieldConverter extends MultiEditProvider { public static final int INIT_IN_METHOD = ; public static final int INIT_IN_CONSTRUCTOR = ; private int initPlace ; private Collection < LocalNodeWrapper > localNodes ; private LocalToFieldConfig config ; public LocalToFieldConverter ( LocalToFieldConfig config ) { this . config = config ; config . setNewName ( getLocalVarName ( ) ) ; localNodes = gatherLocalNodes ( ) ; } private Collection < LocalNodeWrapper > gatherLocalNodes ( ) { Collection < Node > allNodes = gatherLocalNodes ( NodeUtil . getBody ( config . getEnclosingMethod ( ) ) ) ; Collection < LocalNodeWrapper > allLocalNodes = LocalNodeWrapper . createLocalNodes ( allNodes ) ; Collection < LocalNodeWrapper > affectedLocalNodes = new ArrayList < LocalNodeWrapper > ( ) ; String selectedNodeName = LocalNodeWrapper . getLocalNodeName ( config . getSelectedNode ( ) ) ; for ( LocalNodeWrapper aktLokalNode : allLocalNodes ) { String aktLokalNodeName = LocalNodeWrapper . getLocalNodeName ( aktLokalNode ) ; if ( selectedNodeName . equals ( aktLokalNodeName ) ) { affectedLocalNodes . add ( aktLokalNode ) ; } } return affectedLocalNodes ; } private Collection < Node > gatherLocalNodes ( Node baseNode ) { ArrayList < Node > candidates = new ArrayList < Node > ( ) ; if ( baseNode == null || baseNode instanceof MethodDefNode ) { return candidates ; } for ( Object o : baseNode . childNodes ( ) ) { Node n = ( Node ) o ; if ( NodeUtil . nodeAssignableFrom ( n , LocalNodeWrapper . LOCAL_NODES_CLASSES ) ) { candidates . add ( n ) ; } if ( ! NodeUtil . nodeAssignableFrom ( n , DAsgnNode . class , LocalAsgnNode . class ) ) { candidates . addAll ( gatherLocalNodes ( n ) ) ; } } return candidates ; } @ Override protected Collection < EditProvider > getEditProviders ( ) { return getConversions ( localNodes ) ; } private Collection < EditProvider > getConversions ( Collection < LocalNodeWrapper > localNodes ) { Map < LocalNodeWrapper , EditProvider > editProviderMap = new LinkedHashMap < LocalNodeWrapper , EditProvider > ( ) ; LocalNodeWrapper firstLocalNode = localNodes . toArray ( new LocalNodeWrapper [ localNodes . size ( ) ] ) [ ] ; for ( LocalNodeWrapper aktLocalNode : localNodes ) { boolean initInConstructor = ( initPlace == INIT_IN_CONSTRUCTOR ) ; LocalToFieldEditProvider conversion = new LocalToFieldEditProvider ( aktLocalNode , config . getNewName ( ) , config . isClassField ( ) , initInConstructor ) ; editProviderMap . put ( aktLocalNode , conversion ) ; } if ( initPlace == INIT_IN_CONSTRUCTOR ) { editProviderMap . remove ( firstLocalNode ) ; } Collection < EditProvider > editProviders = new ArrayList < EditProvider > ( editProviderMap . values ( ) ) ; if ( initPlace == INIT_IN_CONSTRUCTOR ) { editProviders . add ( new InitInConstructorEditProvider ( firstLocalNode , config ) ) ; editProviders . add ( new DeleteEditProvider ( firstLocalNode . getWrappedNode ( ) ) ) ; } return editProviders ; } public void setNewName ( String newName ) { config . setNewName ( newName ) ; } public void setInitPlace ( int initPlace ) { this . initPlace = initPlace ; } public void setIsClassField ( boolean isClassField ) { config . setClassField ( isClassField ) ; } public String getLocalVarName ( ) { return LocalNodeWrapper . getLocalNodeName ( config . getSelectedNode ( ) ) ; } private Node findSelectedNode ( Class < ? > ... filterNodes ) { return SelectionNodeProvider . getSelectedNodeOfType ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , config . getCaretPosition ( ) , filterNodes ) ; } boolean isInitializationExternalizable ( ) { if ( config . getEnclosingMethod ( ) == null ) { return false ; } LocalNodeWrapper firstNodeInAST = getFirstLocalNodeWrapper ( ) ; if ( firstNodeInAST == null ) { return false ; } if ( findSelectedNode ( MultipleAsgnNode . class ) != null ) { return false ; } if ( firstNodeInAST . getWrappedNode ( ) instanceof LocalAsgnNode ) { LocalAsgnNode firstAssignment = ( LocalAsgnNode ) firstNodeInAST . getWrappedNode ( ) ; Node assignmentValue = firstAssignment . getValueNode ( ) ; return hasSameClass ( assignmentValue , FixnumNode . class , StrNode . class , VCallNode . class , InstVarNode . class , ClassVarNode . class ) ; } return false ; } private boolean hasSameClass ( Node assignmentValue , Class < ? > ... klasses ) { for ( Class klass : klasses ) { if ( assignmentValue . getClass ( ) . equals ( klass ) ) { return true ; } } return false ; } private LocalNodeWrapper getFirstLocalNodeWrapper ( ) { if ( localNodes == null || localNodes . isEmpty ( ) ) { return null ; } return localNodes . toArray ( new LocalNodeWrapper [ localNodes . size ( ) ] ) [ ] ; } boolean isVariableInConstructor ( ) { if ( config . getEnclosingMethod ( ) == null ) { return false ; } return config . getEnclosingMethod ( ) . getName ( ) . equals ( Constants . CONSTRUCTOR_NAME ) ; } } package org . rubypeople . rdt . refactoring . core . convertlocaltofield ; import java . util . Collection ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; import org . rubypeople . rdt . refactoring . util . JRubyRefactoringUtils ; public class LocalToFieldConditionChecker extends RefactoringConditionChecker { private LocalToFieldConfig config ; private RootNode rootNode ; public LocalToFieldConditionChecker ( LocalToFieldConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { config = ( LocalToFieldConfig ) configObj ; rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; Node selectedNode = findSelectedNode ( LocalAsgnNode . class , LocalVarNode . class , DVarNode . class , DAsgnNode . class ) ; if ( selectedNode != null ) { config . setSelectedNode ( new LocalNodeWrapper ( selectedNode ) ) ; config . setEnclosingMethod ( ( MethodDefNode ) findSelectedNode ( MethodDefNode . class ) ) ; config . setEnclosingClassNode ( getClassNode ( ) ) ; } } private Node findSelectedNode ( Class < ? > ... filterNodes ) { return SelectionNodeProvider . getSelectedNodeOfType ( rootNode . getBodyNode ( ) , config . getCaretPosition ( ) , filterNodes ) ; } private ClassNodeWrapper getClassNode ( ) { try { return SelectionNodeProvider . getSelectedClassNode ( rootNode , config . getCaretPosition ( ) ) ; } catch ( NoClassNodeException e ) { return null ; } } @ Override public void checkFinalConditions ( ) { String fieldTypeName = ( config . isClassField ( ) ) ? "" : "" ; for ( FieldNodeWrapper aktField : config . getEnclosingClassNode ( ) . getFields ( ) ) { if ( checkFieldName ( config . getNewName ( ) , aktField . getNameWithoutAts ( ) , fieldTypeName ) ) { return ; } } } private boolean checkFieldName ( String newName , String aktNodeName , String fieldTypeName ) { if ( newName . equals ( aktNodeName ) ) { addError ( fieldTypeName + Messages . TempToFieldConditionChecker_FieldWithName + newName + Messages . TempToFieldConditionChecker_AlreadyExists ) ; return true ; } return false ; } @ Override public void checkInitialConditions ( ) { if ( config . getSelectedNode ( ) == null ) { addError ( Messages . TempToFieldConditionChecker_NoLocalVarAtpos ) ; } else if ( config . getEnclosingClassNode ( ) == null ) { addError ( Messages . TempToFieldConditionChecker_NoEnclosingClassToInsert ) ; } else if ( config . getEnclosingMethod ( ) == null ) { addError ( Messages . TempToFieldConditionChecker_CannotConvertNonlocalVars ) ; } else if ( JRubyRefactoringUtils . isParameter ( LocalNodeWrapper . getLocalNodeName ( config . getSelectedNode ( ) ) , config . getEnclosingMethod ( ) ) ) { addError ( Messages . TempToFieldConditionChecker_CannotConvertMethodParameters ) ; } else if ( isIterParameter ( ) ) { addError ( Messages . TempToFieldConditionChecker_CannotConvertBlockParameters ) ; } } private boolean isIterParameter ( ) { Collection < Node > allIterNodes = NodeProvider . getSubNodes ( config . getEnclosingMethod ( ) , IterNode . class ) ; for ( Node aktNode : allIterNodes ) { IterNode aktIterNode = ( IterNode ) aktNode ; if ( iterNodeContainsAsArg ( aktIterNode , config . getSelectedNode ( ) ) ) { return true ; } } return false ; } private boolean iterNodeContainsAsArg ( IterNode iterNode , LocalNodeWrapper localNode ) { if ( iterNode . getVarNode ( ) == null ) { return false ; } String localNodeName = LocalNodeWrapper . getLocalNodeName ( localNode ) ; for ( LocalNodeWrapper aktIterArg : LocalNodeWrapper . gatherLocalNodes ( iterNode . getVarNode ( ) ) ) { String aktIterArgName = LocalNodeWrapper . getLocalNodeName ( aktIterArg ) ; if ( aktIterArgName . equals ( localNodeName ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . refactoring . core . convertlocaltofield ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . ConvertLocalToFieldPage ; import org . rubypeople . rdt . refactoring . ui . pages . ConverterPageParameters ; public class ConvertLocalToFieldRefactoring extends RubyRefactoring { public static final String NAME = Messages . ConvertLocalToFieldRefactoring_Name ; public ConvertLocalToFieldRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; LocalToFieldConfig config = new LocalToFieldConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; LocalToFieldConditionChecker checker = new LocalToFieldConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { LocalToFieldConverter tempToFieldConverter = new LocalToFieldConverter ( config ) ; setEditProvider ( tempToFieldConverter ) ; ConverterPageParameters pageParameters = createPageParameters ( tempToFieldConverter ) ; ConvertLocalToFieldPage page = new ConvertLocalToFieldPage ( tempToFieldConverter , pageParameters ) ; pages . add ( page ) ; } } private ConverterPageParameters createPageParameters ( LocalToFieldConverter tempToFieldConverter ) { ConverterPageParameters pageParameters = new ConverterPageParameters ( ) ; if ( tempToFieldConverter . isVariableInConstructor ( ) ) { pageParameters . setInClassConstructorRadioEnabled ( false ) ; } if ( ! tempToFieldConverter . isInitializationExternalizable ( ) ) { pageParameters . setInClassConstructorRadioEnabled ( false ) ; } return pageParameters ; } } package org . rubypeople . rdt . refactoring . core . convertlocaltofield ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; public class LocalToFieldEditProvider extends ReplaceEditProvider { private LocalNodeWrapper localNode ; private boolean initInConstructor ; public LocalToFieldEditProvider ( LocalNodeWrapper localNode , String newName , boolean isClassField , boolean initInConstructor ) { super ( false ) ; this . localNode = localNode ; this . initInConstructor = initInConstructor ; newName = ( ( isClassField ) ? "" : "" ) + newName ; Collection < LocalNodeWrapper > allLocalNodes = new ArrayList < LocalNodeWrapper > ( ) ; allLocalNodes . add ( localNode ) ; allLocalNodes . addAll ( LocalNodeWrapper . gatherLocalNodes ( localNode . getWrappedNode ( ) ) ) ; replaceAllNames ( allLocalNodes , LocalNodeWrapper . getLocalNodeName ( localNode ) , newName ) ; } private void replaceAllNames ( Collection < LocalNodeWrapper > allLocalNodes , String orgName , String newName ) { for ( LocalNodeWrapper aktNode : allLocalNodes ) { String aktNodeName = LocalNodeWrapper . getLocalNodeName ( aktNode ) ; if ( aktNodeName . equals ( orgName ) ) { setNodeName ( aktNode , newName ) ; } } } private void setNodeName ( LocalNodeWrapper localNode , String newName ) { localNode . setName ( newName ) ; } @ Override protected int getOffsetLength ( ) { if ( initInConstructor ) return localNode . getWrappedNode ( ) . getPositionIncludingComments ( ) . getEndOffset ( ) - getOffset ( null ) ; else return localNode . getWrappedNode ( ) . getPosition ( ) . getEndOffset ( ) - getOffset ( null ) ; } @ Override protected Node getEditNode ( int offset , String document ) { if ( initInConstructor ) return localNode . getWrappedNode ( ) ; else return stripComments ( localNode . getWrappedNode ( ) ) ; } private Node stripComments ( Node wrappedNode ) { wrappedNode . getComments ( ) . clear ( ) ; for ( Node child : wrappedNode . childNodes ( ) ) { if ( child . isInvisible ( ) ) continue ; stripComments ( child ) ; } return wrappedNode ; } @ Override protected int getOffset ( String document ) { if ( initInConstructor ) return localNode . getWrappedNode ( ) . getPositionIncludingComments ( ) . getStartOffset ( ) ; else return localNode . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . convertlocaltofield ; import org . jruby . ast . BlockNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterLastNodeInMethodOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . ConstructorOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . OffsetProvider ; public class InitInConstructorEditProvider extends InsertEditProvider { private ClassNodeWrapper enclosingClassNode ; private Node insertNode ; public InitInConstructorEditProvider ( LocalNodeWrapper originalNode , LocalToFieldConfig config ) { super ( true ) ; LocalToFieldEditProvider conversion = new LocalToFieldEditProvider ( originalNode , config . getNewName ( ) , config . isClassField ( ) , true ) ; insertNode = conversion . getEditNode ( , null ) ; enclosingClassNode = config . getEnclosingClassNode ( ) ; } @ Override protected int getOffset ( String document ) { OffsetProvider offsetProvider ; if ( enclosingClassNode . hasConstructor ( ) ) { offsetProvider = new AfterLastNodeInMethodOffsetProvider ( enclosingClassNode . getConstructorNode ( ) , document ) ; } else { offsetProvider = new ConstructorOffsetProvider ( enclosingClassNode , document ) ; } return offsetProvider . getOffset ( ) ; } @ Override protected Node getInsertNode ( int offset , String document ) { BlockNode blockNode = NodeFactory . createBlockNode ( true , ! isNextLineEmpty ( offset , document ) , insertNode ) ; if ( ! enclosingClassNode . hasConstructor ( ) ) { DefnNode constructorNode = NodeFactory . createConstructor ( blockNode ) ; NewlineNode newlineNode = NodeFactory . createNewLineNode ( constructorNode ) ; blockNode = NodeFactory . createBlockNode ( true , ! isNextLineEmpty ( offset , document ) , newlineNode ) ; } return blockNode ; } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String LocalVariableRenamer_Modified ; public static String RenameLocalConditionChecker_NameAlreadyExists ; public static String RenameLocalConditionChecker_NameInvalid ; public static String RenameLocalConditionChecker_NoLocalVariable ; public static String RenameLocalConditionChecker_NoSelection ; public static String RenameLocalConditionChecker_SameName ; public static String RenameLocalRefactoring_Name ; public static String VariableNameProvider_NoValidName ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . Node ; import org . jruby . ast . RestArgNode ; import org . jruby . ast . RootNode ; import org . jruby . parser . LocalStaticScope ; import org . jruby . runtime . DynamicScope ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; public class SingleLocalVariableEdit extends ReplaceEditProvider { private final Node node ; private final String [ ] localNames ; public SingleLocalVariableEdit ( Node node , String [ ] localNames ) { super ( false ) ; this . node = node ; this . localNames = localNames . clone ( ) ; } @ Override public int getOffsetLength ( ) { return node . getPositionIncludingComments ( ) . getEndOffset ( ) - getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { if ( node instanceof ArgsNode ) { LocalStaticScope localStaticScope = new LocalStaticScope ( null ) ; localStaticScope . setVariables ( localNames ) ; return new RootNode ( node . getPosition ( ) , DynamicScope . newDynamicScope ( localStaticScope ) , node ) ; } return node ; } @ Override public int getOffset ( String document ) { return getStartOffset ( ) ; } private int getStartOffset ( ) { if ( node instanceof RestArgNode ) { return node . getPositionIncludingComments ( ) . getStartOffset ( ) + ; } return node . getPositionIncludingComments ( ) . getStartOffset ( ) ; } public Node getNode ( ) { return node ; } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import java . util . ArrayList ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; public class DynamicVariableRenamer extends VariableRenamer { public DynamicVariableRenamer ( String oldName , String newName , IAbortCondition abort ) { super ( oldName , newName , abort ) ; } public ArrayList < Node > replaceVariableNamesInNode ( Node n , String [ ] localNames ) { ArrayList < Node > renamed = new ArrayList < Node > ( ) ; if ( n instanceof MethodDefNode ) { n = ( ( MethodDefNode ) n ) . getBodyNode ( ) ; } else if ( n instanceof IterNode ) { renamed . addAll ( replaceVariableNames ( ( ( IterNode ) n ) . getVarNode ( ) ) ) ; renamed . addAll ( replaceVariableNames ( ( ( IterNode ) n ) . getBodyNode ( ) ) ) ; } renamed . addAll ( replaceVariableNames ( n ) ) ; return renamed ; } public ArrayList < Node > replaceVariableNames ( Node n ) { ArrayList < Node > renamedNodes = new ArrayList < Node > ( ) ; if ( abort . abort ( n ) ) { return renamedNodes ; } if ( n instanceof INameNode && ( ( INameNode ) n ) . getName ( ) . equals ( oldName ) ) { if ( n instanceof DVarNode ) { ( ( DVarNode ) n ) . setName ( newName ) ; } else if ( n instanceof DAsgnNode ) { ( ( DAsgnNode ) n ) . setName ( newName ) ; replaceVariableNames ( n ) ; } renamedNodes . add ( n ) ; return renamedNodes ; } for ( Object node : n . childNodes ( ) ) { renamedNodes . addAll ( replaceVariableNames ( ( Node ) node ) ) ; } return renamedNodes ; } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; public class LocalVariableRenamer { private final DocumentProvider doc ; private final String from ; private final String to ; public LocalVariableRenamer ( DocumentProvider doc , String from , String to ) { this . doc = doc ; this . from = from ; this . to = to ; } public TextEdit getEdit ( ) { RenameLocalConfig config = new RenameLocalConfig ( doc , ) ; new RenameLocalConditionChecker ( config ) ; RenameLocalEditProvider editProvider = new RenameLocalEditProvider ( config ) ; editProvider . setSelectedVariableName ( from ) ; editProvider . setNewVariableName ( to ) ; return editProvider . getEdit ( doc . getActiveFileContent ( ) ) ; } public DocumentProvider rename ( ) { return applyEdit ( doc , getEdit ( ) ) ; } public static StringDocumentProvider applyEdit ( DocumentProvider doc , TextEdit edit ) { Document result = new Document ( doc . getActiveFileContent ( ) ) ; try { edit . apply ( result ) ; } catch ( MalformedTreeException e ) { assert false ; } catch ( BadLocationException e ) { assert false ; } return new StringDocumentProvider ( Messages . LocalVariableRenamer_Modified + doc . getActiveFileName ( ) , result . get ( ) ) ; } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import java . util . ArrayList ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . BlockArgNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; public class VariableRenamer { protected final String oldName ; protected final String newName ; protected final IAbortCondition abort ; public VariableRenamer ( String oldName , String newName , IAbortCondition abort ) { super ( ) ; this . oldName = oldName ; this . newName = newName ; this . abort = abort ; } private boolean isRenamedVariableRestArg ( ArgsNode args , String [ ] localNames ) { return args . getRestArg ( ) > && args . getRestArg ( ) < localNames . length && localNames [ args . getRestArg ( ) ] . equals ( oldName ) ; } public ArrayList < Node > replaceVariableNamesInNode ( Node n , String [ ] localNames ) { ArrayList < Node > nodes = new ArrayList < Node > ( ) ; if ( n instanceof MethodDefNode ) { nodes . addAll ( replaceVariableNames ( ( ( MethodDefNode ) n ) . getArgsNode ( ) ) ) ; nodes . addAll ( replaceVariableNames ( ( ( MethodDefNode ) n ) . getBodyNode ( ) ) ) ; } else { nodes . addAll ( replaceVariableNames ( n ) ) ; } if ( n instanceof MethodDefNode && isRenamedVariableRestArg ( ( ( MethodDefNode ) n ) . getArgsNode ( ) , localNames ) ) { MethodDefNode defn = ( ( MethodDefNode ) n ) ; localNames [ defn . getArgsNode ( ) . getRestArg ( ) ] = newName ; } return nodes ; } private ArrayList < Node > replaceVariableNames ( Node n ) { ArrayList < Node > renamedNodes = new ArrayList < Node > ( ) ; if ( n == null || abort . abort ( n ) ) { return renamedNodes ; } if ( n instanceof INameNode && ( ( INameNode ) n ) . getName ( ) . equals ( oldName ) ) { renamedNodes . add ( n ) ; if ( n instanceof LocalAsgnNode ) { ( ( LocalAsgnNode ) n ) . setName ( newName ) ; replaceVariableNames ( ( ( LocalAsgnNode ) n ) . getValueNode ( ) ) ; return renamedNodes ; } else if ( n instanceof ArgumentNode ) { ( ( ArgumentNode ) n ) . setName ( newName ) ; } else if ( n instanceof LocalVarNode ) { ( ( LocalVarNode ) n ) . setName ( newName ) ; } else if ( n instanceof BlockArgNode ) { ( ( BlockArgNode ) n ) . setName ( newName ) ; } } for ( Object node : n . childNodes ( ) ) { renamedNodes . addAll ( replaceVariableNames ( ( Node ) node ) ) ; } return renamedNodes ; } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . ui . pages . RenamePage ; public class RenameLocalRefactoring extends RubyRefactoring { public static final String NAME = Messages . RenameLocalRefactoring_Name ; public RenameLocalRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; DocumentProvider docProvider = getDocumentProvider ( ) ; RenameLocalConfig config = new RenameLocalConfig ( docProvider , selectionProvider . getCaretPosition ( ) ) ; RenameLocalConditionChecker checker = new RenameLocalConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { RenameLocalEditProvider editProvider = new RenameLocalEditProvider ( config ) ; setEditProvider ( editProvider ) ; String name = config . getSelectedNodeName ( ) ; editProvider . setSelectedVariableName ( name ) ; editProvider . setNewVariableName ( name ) ; VariableNameProvider nameProvider = new VariableNameProvider ( name ) ; pages . add ( new RenamePage ( name , nameProvider ) ) ; nameProvider . addObserver ( editProvider ) ; } } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import java . util . Collection ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . BlockArgNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . LocalNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NameValidator ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class RenameLocalConditionChecker extends RefactoringConditionChecker { private static final String ALREADY_EXISTS = Messages . RenameLocalConditionChecker_NameAlreadyExists ; private static final String INVALID_NAME = Messages . RenameLocalConditionChecker_NameInvalid ; private static final String NO_VARIABLE_SELECTED = Messages . RenameLocalConditionChecker_NoSelection ; private static final String NO_LOCAL_VARIABLES = Messages . RenameLocalConditionChecker_NoLocalVariable ; private static final Class [ ] SELECTED_NODE_TYPES = { LocalVarNode . class , LocalAsgnNode . class , ArgumentNode . class , BlockArgNode . class , DVarNode . class , DAsgnNode . class } ; public static final String DEFAULT_ERROR = NO_LOCAL_VARIABLES ; private RenameLocalConfig config ; public RenameLocalConditionChecker ( RenameLocalConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { config = ( RenameLocalConfig ) configObj ; RootNode rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; Node selectedNode = SelectionNodeProvider . getSelectedNodeOfType ( rootNode , config . getCaretPosition ( ) , SELECTED_NODE_TYPES ) ; if ( selectedNode instanceof AssignableNode ) { int start = selectedNode . getPosition ( ) . getStartOffset ( ) ; int end = start + ( ( INameNode ) selectedNode ) . getName ( ) . length ( ) ; if ( config . getCaretPosition ( ) < start || config . getCaretPosition ( ) > end ) { return ; } } config . setSelectedNode ( selectedNode ) ; if ( selectedNode == null ) { Collection < MethodDefNode > methodNodes = NodeProvider . getMethodNodes ( rootNode ) ; config . setSelectedMethod ( SelectionNodeProvider . getSelectedNodeOfType ( methodNodes , config . getCaretPosition ( ) , MethodDefNode . class ) ) ; } else { config . setSelectedMethod ( SelectionNodeProvider . getEnclosingScope ( rootNode , selectedNode ) ) ; } if ( config . getSelectedMethod ( ) != null ) { config . setLocalNames ( NodeUtil . getScope ( config . getSelectedMethod ( ) ) . getVariables ( ) ) ; } } @ Override protected void checkInitialConditions ( ) { if ( ( ! config . hasSelectedNode ( ) || ! isSelectedNodeLocalVar ( ) ) && ! isSelectionInMethodDefinition ( ) ) { addError ( NO_LOCAL_VARIABLES ) ; } } private boolean isSelectionInMethodDefinition ( ) { if ( config . getSelectedMethod ( ) == null ) { return false ; } ISourcePosition position = ( ( MethodDefNode ) config . getSelectedMethod ( ) ) . getArgsNode ( ) . getPosition ( ) ; return position . getStartOffset ( ) <= config . getCaretPosition ( ) && position . getEndOffset ( ) >= config . getCaretPosition ( ) ; } private boolean isSelectedNodeLocalVar ( ) { Node selected = config . getSelectedNode ( ) ; if ( NodeUtil . nodeAssignableFrom ( selected , LocalNodeWrapper . LOCAL_NODES_CLASSES ) ) { return true ; } if ( NodeUtil . nodeAssignableFrom ( selected , ArgumentNode . class , BlockArgNode . class ) && NodeUtil . nodeAssignableFrom ( config . getSelectedMethod ( ) , MethodDefNode . class ) ) { MethodDefNode methodNode = ( MethodDefNode ) config . getSelectedMethod ( ) ; return methodNode . getNameNode ( ) != selected ; } return false ; } @ Override protected void checkFinalConditions ( ) { RenameLocalEditProvider editProvider = config . getRenameEditProvider ( ) ; if ( editProvider . getSelectedVariableName ( ) . equals ( "" ) && editProvider . getNewVariableName ( ) . equals ( "" ) ) { addError ( NO_VARIABLE_SELECTED ) ; } if ( ! NameValidator . isValidLocalVariableName ( editProvider . getNewVariableName ( ) ) ) { addError ( INVALID_NAME ) ; } if ( editProvider . getSelectedVariableName ( ) . equals ( editProvider . getNewVariableName ( ) ) ) { addError ( Messages . RenameLocalConditionChecker_SameName ) ; } for ( String s : config . getLocalNames ( ) ) { if ( editProvider . getNewVariableName ( ) . equals ( s ) ) { addError ( ALREADY_EXISTS ) ; } } } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import java . util . Observable ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . List ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . refactoring . ui . IErrorMessageGenerator ; import org . rubypeople . rdt . refactoring . ui . IErrorMessageReceiver ; import org . rubypeople . rdt . refactoring . util . NameValidator ; public class VariableNameProvider extends Observable implements IErrorMessageGenerator { private String selected = "" ; private String name = "" ; private IErrorMessageReceiver errorReceiver ; public VariableNameProvider ( String selected ) { this . selected = selected ; this . name = selected ; } public String getSelected ( ) { return selected ; } public String getName ( ) { return name ; } public void handleEvent ( Event event ) { if ( event . widget instanceof List ) { selected = ( ( List ) event . widget ) . getSelection ( ) [ ] ; } else if ( event . widget instanceof Text ) { String newName = ( ( Text ) event . widget ) . getText ( ) ; if ( NameValidator . isValidLocalVariableName ( newName ) ) { name = newName ; errorReceiver . setError ( null ) ; } else { errorReceiver . setError ( newName + Messages . VariableNameProvider_NoValidName ) ; } } else { return ; } setChanged ( ) ; notifyObservers ( ) ; } public void setErrorReceiver ( IErrorMessageReceiver errorReceiver ) { this . errorReceiver = errorReceiver ; } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import org . jruby . ast . Node ; public interface IAbortCondition { boolean abort ( Node currentNode ) ; } package org . rubypeople . rdt . refactoring . core . renamelocal ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public class RenameLocalConfig implements IRefactoringConfig { private IDocumentProvider docProvider ; private int caretPosition ; private Node selectedNode ; private Node selectedMethod ; private String [ ] localNames ; private RenameLocalEditProvider editProvider ; public RenameLocalConfig ( IDocumentProvider docProvider , int caretPosition ) { this . docProvider = docProvider ; this . caretPosition = caretPosition ; } public String getSelectedNodeName ( ) { if ( selectedNode instanceof INameNode ) { return ( ( INameNode ) selectedNode ) . getName ( ) ; } else if ( selectedNode == null && selectedMethod instanceof MethodDefNode ) { return localNames [ ( ( MethodDefNode ) selectedMethod ) . getArgsNode ( ) . getRestArg ( ) ] ; } return "" ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public int getCaretPosition ( ) { return caretPosition ; } public boolean hasSelectedMethod ( ) { return selectedMethod != null ; } public boolean hasLocalNames ( ) { return localNames . length > ; } public Node getSelectedNode ( ) { return selectedNode ; } public Node getSelectedMethod ( ) { return selectedMethod ; } public String [ ] getLocalNames ( ) { return localNames ; } public void setLocalVariablesEditProvider ( RenameLocalEditProvider editProvider ) { this . editProvider = editProvider ; } public RenameLocalEditProvider getRenameEditProvider ( ) { return editProvider ; } public void setSelectedNode ( Node selectedNode ) { this . selectedNode = selectedNode ; } public void setSelectedMethod ( Node selectedMethod ) { this . selectedMethod = selectedMethod ; } public void setLocalNames ( String [ ] localNames ) { this . localNames = localNames . clone ( ) ; } public boolean hasSelectedNode ( ) { return selectedNode != null ; } public void setDocumentProvider ( IDocumentProvider docProvider ) { this . docProvider = docProvider ; } } package org . rubypeople . rdt . refactoring . core . renamelocal ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Observable ; import java . util . Observer ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class RenameLocalEditProvider extends MultiEditProvider implements Observer { private static final class AbortOnScope implements IAbortCondition { public boolean abort ( Node currentNode ) { return NodeUtil . hasScope ( currentNode ) ; } } private static final class AbortOnMethodDef implements IAbortCondition { public boolean abort ( Node currentNode ) { return currentNode instanceof MethodDefNode ; } } private String selectedVariableName = "" ; private String newVariableName = "" ; private final RenameLocalConfig config ; public RenameLocalEditProvider ( RenameLocalConfig config ) { this . config = config ; config . setLocalVariablesEditProvider ( this ) ; } public void setSelectedVariableName ( String name ) { selectedVariableName = name ; } public String getSelectedVariableName ( ) { return selectedVariableName ; } public void setNewVariableName ( String name ) { newVariableName = name ; } public String getNewVariableName ( ) { return newVariableName ; } private ArrayList < Node > renameVariables ( ) { VariableRenamer renamer = null ; if ( config . getSelectedNode ( ) instanceof DVarNode || config . getSelectedNode ( ) instanceof DAsgnNode ) { renamer = new DynamicVariableRenamer ( selectedVariableName , newVariableName , new AbortOnScope ( ) ) ; } else { renamer = new VariableRenamer ( selectedVariableName , newVariableName , new AbortOnMethodDef ( ) ) ; } return renamer . replaceVariableNamesInNode ( config . getSelectedMethod ( ) , config . getLocalNames ( ) ) ; } public void update ( Observable subject , Object arg1 ) { if ( subject instanceof VariableNameProvider ) { setSelectedVariableName ( ( ( VariableNameProvider ) subject ) . getSelected ( ) ) ; setNewVariableName ( ( ( VariableNameProvider ) subject ) . getName ( ) ) ; } } @ Override protected Collection < EditProvider > getEditProviders ( ) { Collection < EditProvider > edits = new ArrayList < EditProvider > ( ) ; for ( Node n : renameVariables ( ) ) { edits . add ( new SingleLocalVariableEdit ( n , config . getLocalNames ( ) ) ) ; } return edits ; } } package org . rubypeople . rdt . refactoring . core . pushdown ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String MethodDownPusher_Constructors ; public static String MethodDownPusher_Methods ; public static String MethodDownPusher_NewClasses ; public static String MethodDownPusher_RemoveOldMethods ; public static String PushDownRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . pushdown ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . classnodeprovider . AllFilesClassNodeProvider ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditAndTreeContentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProviderGroups ; import org . rubypeople . rdt . refactoring . editprovider . ITreeClass ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . ui . IItemSelectionReceiver ; import org . rubypeople . rdt . refactoring . ui . IParentProvider ; public class MethodDownPusher extends EditAndTreeContentProvider implements IItemSelectionReceiver { private Object [ ] selectedTreeItems ; private ClassNodeProvider projectClassNodeProvider ; private ClassNodeProvider classNodeProvider ; public MethodDownPusher ( DocumentProvider documentProvider ) { this . projectClassNodeProvider = new AllFilesClassNodeProvider ( new DocumentWithIncluding ( documentProvider ) ) ; this . classNodeProvider = documentProvider . getClassNodeProvider ( ) ; initTreeClasses ( classNodeProvider ) ; } @ Override protected ITreeClass createTreeClass ( ClassNodeWrapper classNode ) { return new TreeClass ( classNode ) ; } @ Override public Collection < EditProvider > getEditProviders ( ) { EditProviderGroups editProviderGroups = new EditProviderGroups ( ) ; if ( selectedTreeItems != null ) { for ( Object o : selectedTreeItems ) { if ( o instanceof TreeClass ) { TreeClass treeClass = ( TreeClass ) o ; treeClass . addDownPushedMethods ( editProviderGroups ) ; } } } return editProviderGroups . getAllEditProviders ( ) ; } public void setSelectedItems ( Object [ ] checkedElements ) { selectedTreeItems = checkedElements . clone ( ) ; } public class TreeClass implements org . rubypeople . rdt . refactoring . ui . IChildrenProvider , ITreeClass { private ClassNodeWrapper classNode ; private Collection < DownPushableMethod > downPushableMethods ; private Collection < ClassNodeWrapper > childClassNodes ; public TreeClass ( ClassNodeWrapper classNode ) { this . classNode = classNode ; downPushableMethods = new ArrayList < DownPushableMethod > ( ) ; childClassNodes = projectClassNodeProvider . getSubClassesOf ( classNode . getName ( ) ) ; if ( ! childClassNodes . isEmpty ( ) ) { for ( MethodNodeWrapper methodNode : classNode . getMethods ( ) ) { downPushableMethods . add ( new DownPushableMethod ( methodNode ) ) ; } } } public void addDownPushedMethods ( EditProviderGroups editProviderGroups ) { Collection < MethodNodeWrapper > checkedMethods = getCheckedMethods ( ) ; for ( ClassNodeWrapper childClassNode : childClassNodes ) { String childClassName = childClassNode . getName ( ) ; if ( classNodeProvider . hasClassNode ( childClassName ) ) { ClassNodeWrapper classNode = classNodeProvider . getClassNode ( childClassName ) ; addDownPushedMethods ( classNode , checkedMethods , editProviderGroups ) ; } else { addDownPushedMethodsClass ( childClassName , checkedMethods , editProviderGroups ) ; } } addRemoveEdits ( checkedMethods , editProviderGroups ) ; } private void addRemoveEdits ( Collection < MethodNodeWrapper > checkedMethods , EditProviderGroups editProviderGroups ) { for ( MethodNodeWrapper methodNode : checkedMethods ) { editProviderGroups . add ( Messages . MethodDownPusher_RemoveOldMethods , new DeleteEditProvider ( methodNode . getWrappedNode ( ) ) ) ; } } private void addDownPushedMethods ( ClassNodeWrapper childClassNode , Collection < MethodNodeWrapper > checkedMethods , EditProviderGroups editProviderGroups ) { Collection < MethodNodeWrapper > constructorNodes = new ArrayList < MethodNodeWrapper > ( ) ; Collection < MethodNodeWrapper > methodNodes = new ArrayList < MethodNodeWrapper > ( ) ; separateConstructors ( checkedMethods , methodNodes , constructorNodes ) ; if ( ! constructorNodes . isEmpty ( ) ) { DownPushedMethods constructors = new DownPushedMethods ( constructorNodes , childClassNode , true ) ; editProviderGroups . add ( Messages . MethodDownPusher_Constructors + childClassNode . getName ( ) , constructors ) ; } if ( ! methodNodes . isEmpty ( ) ) { DownPushedMethods methods = new DownPushedMethods ( methodNodes , childClassNode , false ) ; editProviderGroups . add ( Messages . MethodDownPusher_Methods + childClassNode . getName ( ) , methods ) ; } } private void separateConstructors ( Collection < MethodNodeWrapper > nodes , Collection < MethodNodeWrapper > methodNodes , Collection < MethodNodeWrapper > constructorNodes ) { for ( MethodNodeWrapper method : nodes ) { if ( method . getSignature ( ) . isConstructor ( ) ) constructorNodes . add ( method ) ; else methodNodes . add ( method ) ; } } private Collection < MethodNodeWrapper > getCheckedMethods ( ) { Collection < Object > allCheckedItems = Arrays . asList ( selectedTreeItems ) ; Collection < MethodNodeWrapper > checkedMethods = new ArrayList < MethodNodeWrapper > ( ) ; for ( DownPushableMethod method : downPushableMethods ) { if ( allCheckedItems . contains ( method ) ) checkedMethods . add ( method . getMethodNode ( ) ) ; } return checkedMethods ; } private void addDownPushedMethodsClass ( String className , Collection < MethodNodeWrapper > checkedMethods , EditProviderGroups editProviderGroups ) { DownPushedMethodsClass methodsClass = new DownPushedMethodsClass ( className , checkedMethods ) ; editProviderGroups . add ( Messages . MethodDownPusher_NewClasses , methodsClass ) ; } public String toString ( ) { return classNode . getName ( ) ; } public Object [ ] getChildren ( ) { return downPushableMethods . toArray ( ) ; } public boolean hasChildren ( ) { return ! downPushableMethods . isEmpty ( ) ; } public class DownPushableMethod implements IParentProvider { private MethodNodeWrapper methodNode ; public DownPushableMethod ( MethodNodeWrapper methodNode ) { this . methodNode = methodNode ; } public String toString ( ) { return methodNode . getName ( ) ; } public Object getParent ( ) { return TreeClass . this ; } public TreeClass getTreeClass ( ) { return TreeClass . this ; } public MethodNodeWrapper getMethodNode ( ) { return methodNode ; } } } } package org . rubypeople . rdt . refactoring . core . pushdown ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . MethodDownPusherSelectionPage ; public class PushDownRefactoring extends RubyRefactoring { public static final String NAME = Messages . PushDownRefactoring_Name ; public PushDownRefactoring ( ) { super ( NAME ) ; MethodDownPusher downPusher = new MethodDownPusher ( getDocumentProvider ( ) ) ; setEditProvider ( downPusher ) ; pages . add ( new MethodDownPusherSelectionPage ( downPusher ) ) ; } } package org . rubypeople . rdt . refactoring . core . pushdown ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . BlockNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . ConstructorOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . MethodOffsetProvider ; public class DownPushedMethods extends InsertEditProvider { private Collection < MethodNodeWrapper > methodNodes ; private boolean constructors ; private ClassNodeWrapper classNode ; public DownPushedMethods ( Collection < MethodNodeWrapper > methodNodes , ClassNodeWrapper classNode , boolean constructors ) { super ( true ) ; this . methodNodes = methodNodes ; this . constructors = constructors ; this . classNode = classNode ; } @ Override protected BlockNode getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = lastEditInGroup && ! isNextLineEmpty ( offset , document ) ; return NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , getMethodNodes ( methodNodes ) ) ; } private Node [ ] getMethodNodes ( Collection < MethodNodeWrapper > nodeCollection ) { Collection < Node > nodes = new ArrayList < Node > ( ) ; boolean first = true ; for ( MethodNodeWrapper methodNode : nodeCollection ) { if ( first ) { first = false ; } else { nodes . add ( NodeFactory . createNewLineNode ( null ) ) ; } nodes . add ( NodeFactory . createNewLineNode ( methodNode . getWrappedNode ( ) ) ) ; } return nodes . toArray ( new Node [ nodes . size ( ) ] ) ; } @ Override protected int getOffset ( String document ) { IOffsetProvider offsetProvider ; if ( constructors ) { offsetProvider = new ConstructorOffsetProvider ( classNode , document ) ; } else { offsetProvider = new MethodOffsetProvider ( classNode , document ) ; } return offsetProvider . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . pushdown ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; public class NewClassOffsetProvier implements IOffsetProvider { public int getOffset ( ) { return ; } } package org . rubypeople . rdt . refactoring . core . pushdown ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . BlockNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; public class DownPushedMethodsClass extends InsertEditProvider { private Collection < MethodNodeWrapper > methodNodes ; private Collection < MethodNodeWrapper > constructorNodes ; private String className ; public DownPushedMethodsClass ( String className , Collection < MethodNodeWrapper > allMethodNodes ) { super ( true ) ; this . className = className ; initConstrucorAndMethodNodes ( allMethodNodes ) ; } private void initConstrucorAndMethodNodes ( Collection < MethodNodeWrapper > allMethodNodes ) { methodNodes = new ArrayList < MethodNodeWrapper > ( ) ; constructorNodes = new ArrayList < MethodNodeWrapper > ( ) ; for ( MethodNodeWrapper node : allMethodNodes ) { if ( node . getSignature ( ) . isConstructor ( ) ) constructorNodes . add ( node ) ; else methodNodes . add ( node ) ; } } @ Override protected BlockNode getInsertNode ( int offset , String document ) { if ( firstEditInGroup ) { setInsertType ( INSERT_AT_BEGIN_OF_LINE ) ; } boolean needsNewLineAtEndOfBlock = lastEditInGroup && ! isNextLineEmpty ( offset , document ) ; Node classNode = getClassNode ( ) ; BlockNode blockNode = NodeFactory . createBlockNode ( ) ; blockNode . add ( classNode ) ; if ( ! firstEditInGroup ) blockNode . add ( NodeFactory . createNewLineNode ( null ) ) ; if ( needsNewLineAtEndOfBlock ) blockNode . add ( NodeFactory . createNewLineNode ( null ) ) ; return blockNode ; } private Node getClassNode ( ) { return NodeFactory . createNewLineNode ( NodeFactory . createClassNode ( className , getBody ( ) ) ) ; } private Node getBody ( ) { BlockNode body = new BlockNode ( new IDESourcePosition ( ) ) ; body . add ( NodeFactory . createNewLineNode ( null ) ) ; for ( MethodNodeWrapper constructor : constructorNodes ) { body . add ( NodeFactory . createNewLineNode ( constructor . getWrappedNode ( ) ) ) ; } for ( MethodNodeWrapper method : methodNodes ) { body . add ( NodeFactory . createNewLineNode ( method . getWrappedNode ( ) ) ) ; } body . add ( NodeFactory . createNewLineNode ( null ) ) ; return body ; } @ Override protected int getOffset ( String document ) { IOffsetProvider offsetProvider = new NewClassOffsetProvier ( ) ; return offsetProvider . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . splitlocal ; import java . util . Collection ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public interface ILocalVarFinder { public Node getScopeNode ( ) ; public Collection < LocalVarUsage > findLocalUsages ( IDocumentProvider doc , int caretPosition ) ; } package org . rubypeople . rdt . refactoring . core . splitlocal ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; public interface ISplittedVariableRenamer { public Collection < EditProvider > rename ( Collection < LocalVarUsage > variables ) ; } package org . rubypeople . rdt . refactoring . core . splitlocal ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public class SplitLocalConfig implements IRefactoringConfig { private IDocumentProvider documentProvider ; private int caretPosition ; Collection < LocalVarUsage > localUsages ; private LocalVarFinder localVarFinder ; public SplitLocalConfig ( IDocumentProvider documentProvider , int caretPosition ) { this . documentProvider = documentProvider ; this . caretPosition = caretPosition ; } public int getCaretPsition ( ) { return caretPosition ; } public IDocumentProvider getDocumentProvider ( ) { return documentProvider ; } public boolean hasLocalUsages ( ) { return localUsages != null ; } public void setLocalUsages ( Collection < LocalVarUsage > localUsages ) { this . localUsages = localUsages ; } public ILocalVarFinder getLocalVariablesFinder ( ) { return localVarFinder ; } public void setLocalVariablesFinder ( LocalVarFinder localVarFinder ) { this . localVarFinder = localVarFinder ; } public Collection < LocalVarUsage > getLocalUsages ( ) { return localUsages ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . documentProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . splitlocal ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; public class SplitLocalConditionChecker extends RefactoringConditionChecker { private SplitLocalConfig config ; public SplitLocalConditionChecker ( SplitLocalConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( SplitLocalConfig ) configObj ; config . setLocalVariablesFinder ( new LocalVarFinder ( ) ) ; config . setLocalUsages ( config . getLocalVariablesFinder ( ) . findLocalUsages ( config . getDocumentProvider ( ) , config . getCaretPsition ( ) ) ) ; } @ Override protected void checkFinalConditions ( ) { } @ Override protected void checkInitialConditions ( ) { if ( ! config . hasLocalUsages ( ) ) { addError ( Messages . SplitTempConditionChecker_NoLocal ) ; } } } package org . rubypeople . rdt . refactoring . core . splitlocal ; import org . jruby . ast . AssignableNode ; public class LocalVarUsage { private int fromPosition ; private int toPosition ; private AssignableNode node ; private String name ; private String newName = "" ; public int getFromPosition ( ) { return fromPosition ; } public void setFromPosition ( int from ) { this . fromPosition = from ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public AssignableNode getNode ( ) { return node ; } public void setNode ( AssignableNode node ) { this . node = node ; } public int getToPosition ( ) { return toPosition ; } public void setToPosition ( int to ) { this . toPosition = to ; } public String getNewName ( ) { return newName ; } public void setNewName ( String newName ) { this . newName = newName ; } } package org . rubypeople . rdt . refactoring . core . splitlocal ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . inlinemethod . TargetClassFinder ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class LocalVarFinder implements ILocalVarFinder { private Node enclosingMethod ; public Collection < LocalVarUsage > findLocalUsages ( IDocumentProvider doc , int caretPosition ) { Node rootNode = doc . getActiveFileRootNode ( ) ; INameNode selectedAssignment = findAssignment ( doc , caretPosition , rootNode ) ; if ( selectedAssignment == null ) { return null ; } enclosingMethod = SelectionNodeProvider . getEnclosingScope ( rootNode , ( Node ) selectedAssignment ) ; assert enclosingMethod != null ; return createLocalVariableUsages ( gatherLocalAssignments ( selectedAssignment ) ) ; } private INameNode findAssignment ( IDocumentProvider doc , int caretPosition , Node rootNode ) { INameNode selectedAssignment = ( INameNode ) SelectionNodeProvider . getSelectedNodeOfType ( rootNode , caretPosition , LocalAsgnNode . class , DAsgnNode . class ) ; if ( selectedAssignment == null ) { final LocalVarNode selectedLocalVar = ( LocalVarNode ) SelectionNodeProvider . getSelectedNodeOfType ( rootNode , caretPosition , LocalVarNode . class ) ; if ( selectedLocalVar == null ) return null ; selectedAssignment = new TargetClassFinder ( ) . localAsgnFromLocalVar ( selectedLocalVar , doc ) ; } return selectedAssignment ; } private ArrayList < LocalVarUsage > createLocalVariableUsages ( ArrayList < AssignableNode > myAsgns ) { ArrayList < LocalVarUsage > foundNodes = new ArrayList < LocalVarUsage > ( ) ; AssignableNode [ ] assignments = myAsgns . toArray ( new AssignableNode [ myAsgns . size ( ) ] ) ; for ( int i = ; i < assignments . length ; i ++ ) { LocalVarUsage var = createLocalVarUsageFromNode ( assignments , i ) ; if ( isLastAssignment ( assignments , i ) ) { setPositionToScopeEnd ( var ) ; } else { setEndPositionBeforeNextNode ( assignments , i , var ) ; } foundNodes . add ( var ) ; } return foundNodes ; } private void setEndPositionBeforeNextNode ( AssignableNode [ ] assignments , int i , LocalVarUsage var ) { var . setToPosition ( assignments [ i + ] . getPosition ( ) . getStartOffset ( ) - ) ; } private void setPositionToScopeEnd ( LocalVarUsage var ) { var . setToPosition ( enclosingMethod . getPosition ( ) . getEndOffset ( ) ) ; } private boolean isLastAssignment ( AssignableNode [ ] assignments , int i ) { return i >= assignments . length - ; } private LocalVarUsage createLocalVarUsageFromNode ( AssignableNode [ ] assignments , int i ) { LocalVarUsage var = new LocalVarUsage ( ) ; var . setFromPosition ( assignments [ i ] . getPosition ( ) . getStartOffset ( ) ) ; var . setNode ( assignments [ i ] ) ; var . setName ( ( ( INameNode ) assignments [ i ] ) . getName ( ) ) ; return var ; } private ArrayList < AssignableNode > gatherLocalAssignments ( INameNode selectedNodeOfType ) { ArrayList < AssignableNode > myAsgns = new ArrayList < AssignableNode > ( ) ; Collection < LocalAsgnNode > allLocalAsgnNodes = NodeProvider . gatherLocalAsgnNodes ( NodeUtil . getBody ( enclosingMethod ) ) ; for ( LocalAsgnNode node : allLocalAsgnNodes ) { if ( node . getName ( ) . equals ( selectedNodeOfType . getName ( ) ) && ! nodeAssignsToItself ( node ) ) { myAsgns . add ( node ) ; } } Collection < Node > nodes = new ArrayList < Node > ( ) ; if ( enclosingMethod instanceof IterNode ) { nodes . addAll ( NodeProvider . gatherNodesOfTypeInAktScopeNode ( ( ( IterNode ) enclosingMethod ) . getVarNode ( ) , DAsgnNode . class ) ) ; } nodes . addAll ( NodeProvider . gatherNodesOfTypeInAktScopeNode ( NodeUtil . getBody ( enclosingMethod ) , DAsgnNode . class ) ) ; for ( Node node : nodes ) { if ( ( ( DAsgnNode ) node ) . getName ( ) . equals ( selectedNodeOfType . getName ( ) ) && ! nodeAssignsToItself ( ( DAsgnNode ) node ) ) { myAsgns . add ( ( DAsgnNode ) node ) ; } } return myAsgns ; } private boolean nodeAssignsToItself ( AssignableNode node ) { Collection < Node > allNodes = NodeProvider . getAllNodes ( node ) ; for ( Node child : allNodes ) { if ( child instanceof LocalVarNode && node instanceof LocalAsgnNode ) { LocalVarNode localVarNode = ( LocalVarNode ) child ; LocalAsgnNode localAsgnNode = ( LocalAsgnNode ) node ; if ( localAsgnNode . getIndex ( ) == localVarNode . getIndex ( ) ) { return true ; } } else if ( child instanceof DVarNode && node instanceof DAsgnNode ) { DVarNode localVarNode = ( DVarNode ) child ; DAsgnNode localAsgnNode = ( DAsgnNode ) node ; if ( localAsgnNode . getName ( ) . equals ( localVarNode . getName ( ) ) ) { return true ; } } } return false ; } public Node getScopeNode ( ) { return enclosingMethod ; } } package org . rubypeople . rdt . refactoring . core . splitlocal ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . SplitLocalPage ; public class SplitTempRefactoring extends RubyRefactoring { public static final String NAME = Messages . SplitTempRefactoring_Name ; public SplitTempRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; SplitLocalConfig config = new SplitLocalConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; SplitLocalConditionChecker checker = new SplitLocalConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { SplitTempEditProvider splitTempEditProvider = new SplitTempEditProvider ( config ) ; setEditProvider ( splitTempEditProvider ) ; pages . add ( new SplitLocalPage ( splitTempEditProvider . getLocalUsages ( ) , config . getDocumentProvider ( ) . getActiveFileContent ( ) , splitTempEditProvider ) ) ; } } } package org . rubypeople . rdt . refactoring . core . splitlocal ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; public class SplitTempEditProvider extends MultiEditProvider implements ISplittedNamesReceiver { private final SplitLocalConfig config ; public SplitTempEditProvider ( SplitLocalConfig config ) { this . config = config ; } @ Override protected Collection < EditProvider > getEditProviders ( ) { return new SplittedVariableRenamer ( config . getLocalVariablesFinder ( ) . getScopeNode ( ) ) . rename ( config . getLocalUsages ( ) ) ; } public void setNewNames ( String [ ] names ) { assert names . length == config . getLocalUsages ( ) . size ( ) ; for ( int i = ; i < names . length ; i ++ ) { config . getLocalUsages ( ) . toArray ( new LocalVarUsage [ config . getLocalUsages ( ) . size ( ) ] ) [ i ] . setNewName ( names [ i ] ) ; } } public Collection < LocalVarUsage > getLocalUsages ( ) { return config . getLocalUsages ( ) ; } } package org . rubypeople . rdt . refactoring . core . splitlocal ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String SplitTempConditionChecker_NoLocal ; public static String SplitTempRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . splitlocal ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . renamelocal . DynamicVariableRenamer ; import org . rubypeople . rdt . refactoring . core . renamelocal . IAbortCondition ; import org . rubypeople . rdt . refactoring . core . renamelocal . SingleLocalVariableEdit ; import org . rubypeople . rdt . refactoring . core . renamelocal . VariableRenamer ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class SplittedVariableRenamer implements ISplittedVariableRenamer { private static final class AbortOnOtherMethod implements IAbortCondition { private final LocalVarUsage usage ; private AbortOnOtherMethod ( LocalVarUsage usage ) { this . usage = usage ; } public boolean abort ( Node currentNode ) { if ( currentNode instanceof NewlineNode ) { currentNode = ( ( NewlineNode ) currentNode ) . getNextNode ( ) ; } if ( currentNode . isInvisible ( ) ) return false ; return currentNode instanceof MethodDefNode || currentNode . getPosition ( ) . getEndOffset ( ) < usage . getFromPosition ( ) || currentNode . getPosition ( ) . getStartOffset ( ) > usage . getToPosition ( ) ; } } private static final class AbortOnOtherScope implements IAbortCondition { private final LocalVarUsage usage ; private AbortOnOtherScope ( LocalVarUsage usage ) { this . usage = usage ; } public boolean abort ( Node currentNode ) { if ( currentNode instanceof NewlineNode ) { currentNode = ( ( NewlineNode ) currentNode ) . getNextNode ( ) ; } if ( currentNode . isInvisible ( ) ) return false ; return NodeUtil . hasScope ( currentNode ) || currentNode . getPosition ( ) . getEndOffset ( ) < usage . getFromPosition ( ) || currentNode . getPosition ( ) . getStartOffset ( ) > usage . getToPosition ( ) ; } } private final Node scopeNode ; public SplittedVariableRenamer ( Node scopeNode ) { this . scopeNode = scopeNode ; } public Collection < EditProvider > rename ( final Collection < LocalVarUsage > variables ) { final ArrayList < EditProvider > edits = new ArrayList < EditProvider > ( ) ; for ( final LocalVarUsage localVarUsage : variables ) { if ( localVarUsage . getName ( ) . equals ( localVarUsage . getNewName ( ) ) ) { continue ; } VariableRenamer renamer = null ; assert localVarUsage . getNode ( ) instanceof LocalAsgnNode || localVarUsage . getNode ( ) instanceof DAsgnNode ; if ( localVarUsage . getNode ( ) instanceof LocalAsgnNode ) { renamer = createLocalVariableRenamer ( localVarUsage ) ; } else if ( localVarUsage . getNode ( ) instanceof DAsgnNode ) { renamer = createDynamicVariableRenamer ( localVarUsage ) ; } else { return null ; } final ArrayList < Node > nodes = renamer . replaceVariableNamesInNode ( scopeNode , NodeUtil . getScope ( scopeNode ) . getVariables ( ) ) ; for ( Node node : nodes ) { edits . add ( new SingleLocalVariableEdit ( node , NodeUtil . getScope ( scopeNode ) . getVariables ( ) ) ) ; } } return edits ; } private VariableRenamer createLocalVariableRenamer ( final LocalVarUsage localVarUsage ) { VariableRenamer renamer ; renamer = new VariableRenamer ( localVarUsage . getName ( ) , localVarUsage . getNewName ( ) , new AbortOnOtherMethod ( localVarUsage ) ) ; return renamer ; } private VariableRenamer createDynamicVariableRenamer ( final LocalVarUsage localVarUsage ) { VariableRenamer renamer ; renamer = new DynamicVariableRenamer ( localVarUsage . getName ( ) , localVarUsage . getNewName ( ) , new AbortOnOtherScope ( localVarUsage ) ) ; return renamer ; } } package org . rubypeople . rdt . refactoring . core . splitlocal ; public interface ISplittedNamesReceiver { public void setNewNames ( String [ ] names ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . movefield . GenerateAccessorsAtTarget ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiEditProvider ; public class InlineAndRemoveEditProvider extends MultiEditProvider implements IRemoveDeclaration { private final InlineMethodConfig config ; private boolean remove ; public InlineAndRemoveEditProvider ( InlineMethodConfig config ) { this . config = config ; } @ Override protected Collection < EditProvider > getEditProviders ( ) { ArrayList < EditProvider > editProviders = new ArrayList < EditProvider > ( ) ; editProviders . add ( new InlineMethodEditProvider ( config ) ) ; if ( remove ) { editProviders . add ( new DeleteEditProvider ( config . getMethodDefinitionNode ( ) ) ) ; } if ( config . getUsedMembers ( ) != null && ! config . getUsedMembers ( ) . isEmpty ( ) ) { for ( String member : config . getUsedMembers ( ) ) { editProviders . add ( new GenerateAccessorsAtTarget ( config . getDocumentProvider ( ) , config . getClassName ( ) , member . substring ( ) ) . getEditProvider ( ) ) ; } } return editProviders ; } public void setRemove ( boolean remove ) { this . remove = remove ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; public interface ITargetClassFinder { String findTargetClass ( MethodCallNodeWrapper call , IDocumentProvider doc ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import java . util . Collection ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; public class InlineMethodConfig implements IRefactoringConfig { private Boolean singleReturnStatement ; private MethodCallNodeWrapper selectedCall ; private String className ; private MethodDefNode methodDefinitionNode ; private DocumentProvider methodDefDoc ; private IDocumentProvider originalDocument ; private int pos ; private ITargetClassFinder targetClassFinder ; private Collection < String > usedMembers ; private Node callParent ; public InlineMethodConfig ( DocumentProvider doc , int pos , ITargetClassFinder targetClassFinder ) { originalDocument = doc ; this . pos = pos ; this . targetClassFinder = targetClassFinder ; } public Node getCallParent ( ) { return callParent ; } public void setCallParent ( Node cellParent ) { this . callParent = cellParent ; } public String getClassName ( ) { return className ; } public DocumentProvider getMethodDefDoc ( ) { return methodDefDoc ; } public MethodDefNode getMethodDefinitionNode ( ) { return methodDefinitionNode ; } public MethodCallNodeWrapper getSelectedCall ( ) { return selectedCall ; } public Boolean isSingleReturnStatement ( ) { return singleReturnStatement ; } public int getPos ( ) { return pos ; } public ITargetClassFinder getTargetClassFinder ( ) { return targetClassFinder ; } public IDocumentProvider getDocumentProvider ( ) { return originalDocument ; } public void setMethodDefDoc ( DocumentProvider methodDefDoc ) { this . methodDefDoc = methodDefDoc ; } public void setSelectedCall ( MethodCallNodeWrapper selectedCall ) { this . selectedCall = selectedCall ; } public void setSingleReturnStatement ( Boolean singleReturnStatement ) { this . singleReturnStatement = singleReturnStatement ; } public void setClassName ( String className ) { this . className = className ; } public void setMethodDefinitionNode ( MethodDefNode methodDefinitionNode ) { this . methodDefinitionNode = methodDefinitionNode ; } public void setUsedMembers ( Collection < String > usedMembers ) { this . usedMembers = usedMembers ; } public Collection < String > getUsedMembers ( ) { return usedMembers ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . originalDocument = doc ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . CollectingSearchRequestor ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class MethodFinder implements IMethodFinder { public MethodDefNode find ( String className , String methodName , IDocumentProvider doc ) { SearchEngine engine = new SearchEngine ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . METHOD , className + '' + methodName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; SearchParticipant [ ] participants = { SearchEngine . getDefaultSearchParticipant ( ) } ; IRubySearchScope scope = SearchEngine . createWorkspaceScope ( ) ; CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; try { engine . search ( pattern , participants , scope , requestor , new NullProgressMonitor ( ) ) ; List < SearchMatch > matches = requestor . getResults ( ) ; for ( SearchMatch match : matches ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; if ( element . isType ( IRubyElement . METHOD ) ) { IMethod method = ( IMethod ) element ; Node rootNode = ASTProvider . getASTProvider ( ) . getAST ( method . getRubyScript ( ) , ASTProvider . WAIT_YES , new NullProgressMonitor ( ) ) ; Node node = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( rootNode , method . getSourceRange ( ) . getOffset ( ) ) ; if ( node instanceof MethodDefNode ) { return ( MethodDefNode ) node ; } } } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } for ( MethodNodeWrapper method : new IncludedClassesProvider ( doc ) . getAllMethodsFor ( className ) ) { if ( method . getName ( ) . equals ( methodName ) ) { return method . getWrappedNode ( ) ; } } return null ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . types . INameNode ; import org . jruby . parser . StaticScope ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class InlineMethodConditionChecker extends RefactoringConditionChecker { private InlineMethodConfig config ; public InlineMethodConditionChecker ( InlineMethodConfig config ) { super ( config ) ; } public void init ( IRefactoringConfig configObj ) { this . config = ( InlineMethodConfig ) configObj ; if ( ! ( findSelectedCall ( config . getPos ( ) ) && findTargetClass ( config . getTargetClassFinder ( ) ) && findMethodDefinition ( ) ) ) { return ; } config . setCallParent ( NodeProvider . findParentNode ( config . getDocumentProvider ( ) . getActiveFileRootNode ( ) , config . getSelectedCall ( ) . getWrappedNode ( ) ) ) ; replaceParameters ( ) ; if ( resultIsAssigned ( ) ) { replaceReturnStatements ( ) ; } createInlinedMethodBody ( config . getDocumentProvider ( ) ) ; renameDuplicates ( config . getDocumentProvider ( ) ) ; } private void renameDuplicates ( IDocumentProvider doc ) { StaticScope parent = NodeUtil . getScope ( SelectionNodeProvider . getEnclosingScope ( doc . getActiveFileRootNode ( ) , config . getSelectedCall ( ) . getWrappedNode ( ) ) ) ; ArrayList < String > localNames = new ArrayList < String > ( ) ; if ( parent . getVariables ( ) != null ) { for ( String name : parent . getVariables ( ) ) { localNames . add ( name ) ; } } if ( resultIsAssigned ( ) ) { AssignableNode callParent = ( AssignableNode ) config . getCallParent ( ) ; String name ; if ( callParent instanceof INameNode ) { name = ( ( INameNode ) callParent ) . getName ( ) ; localNames . remove ( name ) ; } else { ListNode head = ( ( MultipleAsgnNode ) callParent ) . getHeadNode ( ) ; localNames . removeAll ( head . childNodes ( ) ) ; } } config . setMethodDefDoc ( new RenameDuplicatedVariables ( ) . rename ( new StringDocumentProvider ( config . getMethodDefDoc ( ) ) , localNames . toArray ( new String [ localNames . size ( ) ] ) ) ) ; } private boolean findSelectedCall ( int pos ) { config . setSelectedCall ( new SelectedCallFinder ( ) . findSelectedCall ( pos , config . getDocumentProvider ( ) ) ) ; return config . getSelectedCall ( ) != null ; } private boolean findTargetClass ( ITargetClassFinder targetClassFinder ) { config . setClassName ( targetClassFinder . findTargetClass ( config . getSelectedCall ( ) , config . getDocumentProvider ( ) ) ) ; return config . getClassName ( ) != null && ! "" . equals ( config . getClassName ( ) ) ; } private boolean findMethodDefinition ( ) { config . setMethodDefinitionNode ( new MethodFinder ( ) . find ( config . getClassName ( ) , config . getSelectedCall ( ) . getName ( ) , config . getDocumentProvider ( ) ) ) ; return config . getMethodDefinitionNode ( ) != null ; } private void replaceParameters ( ) { config . setMethodDefDoc ( new ParameterReplacer ( ) . replace ( config . getDocumentProvider ( ) , config . getSelectedCall ( ) , config . getMethodDefinitionNode ( ) ) ) ; } private void createInlinedMethodBody ( IDocumentProvider doc ) { MethodBodyStatementReplacer bodyReplacer = new MethodBodyStatementReplacer ( ) ; if ( config . getSelectedCall ( ) . getReceiverNode ( ) != null ) { final String name = ( ( INameNode ) config . getSelectedCall ( ) . getReceiverNode ( ) ) . getName ( ) ; config . setMethodDefDoc ( bodyReplacer . replaceSelfWithObject ( config . getMethodDefDoc ( ) , name ) ) ; config . setMethodDefDoc ( bodyReplacer . prefixCallsWithObject ( config . getMethodDefDoc ( ) , new IncludedClassesProvider ( doc ) , config . getClassName ( ) , name ) ) ; Collection < String > usedMembers = new HashSet < String > ( ) ; config . setMethodDefDoc ( bodyReplacer . replaceVarsWithAccessor ( config . getMethodDefDoc ( ) , name , usedMembers ) ) ; config . setUsedMembers ( usedMembers ) ; } config . setMethodDefDoc ( bodyReplacer . removeReturnStatements ( config . getMethodDefDoc ( ) ) ) ; } private void replaceReturnStatements ( ) { IReturnStatementReplacer returnReplacer = new ReturnStatementReplacer ( ) ; config . setSingleReturnStatement ( Boolean . valueOf ( ( returnReplacer . singleReturnOnLastLine ( config . getMethodDefDoc ( ) ) ) ) ) ; if ( returnReplacer . singleReturnOnLastLine ( config . getMethodDefDoc ( ) ) ) { config . setMethodDefDoc ( returnReplacer . replaceReturn ( config . getMethodDefDoc ( ) , ( AssignableNode ) config . getCallParent ( ) ) ) ; } } private boolean resultIsAssigned ( ) { return config . getCallParent ( ) instanceof AssignableNode ; } @ Override protected void checkInitialConditions ( ) { if ( config . getSelectedCall ( ) == null ) { addError ( Messages . InlineMethodConditionChecker_NoMethodCall ) ; } else if ( config . getClassName ( ) == null || "" . equals ( config . getClassName ( ) ) ) { addError ( Messages . InlineMethodConditionChecker_CannotGuessType ) ; } else if ( config . getMethodDefinitionNode ( ) == null ) { addError ( Messages . InlineMethodConditionChecker_CannotFindDefinition ) ; } else if ( config . isSingleReturnStatement ( ) != null && config . isSingleReturnStatement ( ) . booleanValue ( ) == false ) { addError ( Messages . InlineMethodConditionChecker_ToManyReturns ) ; } } @ Override protected void checkFinalConditions ( ) { } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . refactoring . core . renamelocal . LocalVariableRenamer ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . util . FileHelper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class ParameterReplacer implements IParameterReplacer { public DocumentProvider replace ( IDocumentProvider doc , MethodCallNodeWrapper call , MethodDefNode definition ) { DocumentProvider strDoc = new StringDocumentProvider ( "" + doc . getActiveFileName ( ) , doc . getActiveFileContent ( ) . substring ( definition . getPosition ( ) . getStartOffset ( ) , definition . getPosition ( ) . getEndOffset ( ) + ) ) ; ArrayNode headList = new ArrayNode ( new IDESourcePosition ( ) ) ; ArrayNode tailList = new ArrayNode ( new IDESourcePosition ( ) ) ; if ( definition . getArgsNode ( ) . getArgs ( ) != null && call . getArgsNode ( ) != null ) { Object [ ] defnArguments = definition . getArgsNode ( ) . getArgs ( ) . childNodes ( ) . toArray ( ) ; Object [ ] arguments = call . getArgsNode ( ) . childNodes ( ) . toArray ( ) ; for ( int i = ; i < defnArguments . length ; i ++ ) { strDoc = processArguments ( strDoc , headList , tailList , ( Node ) arguments [ i ] , ( ArgumentNode ) defnArguments [ i ] ) ; } if ( definition . getArgsNode ( ) . getRestArg ( ) >= ) { processRestArg ( definition , headList , tailList , defnArguments , arguments ) ; } } if ( definition . getArgsNode ( ) . getOptArgs ( ) != null ) { processOptArgs ( definition , headList , tailList ) ; } StringBuffer insert = new StringBuffer ( ) ; if ( headList . size ( ) > ) { String lineDelimiter = FileHelper . getLineDelimiter ( strDoc . getActiveFileContent ( ) ) ; createAssignments ( headList , tailList , insert , lineDelimiter ) ; } MethodDefNode newDefinition = ( MethodDefNode ) ( ( NewlineNode ) strDoc . getActiveFileRootNode ( ) . getBodyNode ( ) ) . getNextNode ( ) ; ISourcePosition bodyPosition = NodeUtil . subPositionUnion ( newDefinition . getBodyNode ( ) ) ; insert . append ( strDoc . getActiveFileContent ( ) . substring ( bodyPosition . getStartOffset ( ) , bodyPosition . getEndOffset ( ) + ) . trim ( ) ) ; return new StringDocumentProvider ( "" + doc . getActiveFileName ( ) , insert . toString ( ) ) ; } private void createAssignments ( ArrayNode headList , ArrayNode tailList , StringBuffer insert , String lineDelimiter ) { MultipleAsgnNode multipleAsgnNode = new MultipleAsgnNode ( new IDESourcePosition ( ) , headList , null ) ; multipleAsgnNode . setValueNode ( tailList ) ; insert . append ( ReWriteVisitor . createCodeFromNode ( multipleAsgnNode , "" ) ) ; insert . append ( lineDelimiter ) ; } private DocumentProvider processArguments ( DocumentProvider StringDocumentProvider , ArrayNode headList , ArrayNode tailList , Node node , ArgumentNode arg ) { if ( node instanceof LocalVarNode || node instanceof InstAsgnNode ) { StringDocumentProvider = renameVariable ( StringDocumentProvider , ( INameNode ) node , ( INameNode ) arg ) ; } else { headList . add ( createAssignment ( arg . getName ( ) ) ) ; tailList . add ( node ) ; } return StringDocumentProvider ; } private void processOptArgs ( MethodDefNode definition , ArrayNode headList , ArrayNode tailList ) { for ( Object obj : definition . getArgsNode ( ) . getOptArgs ( ) . childNodes ( ) ) { assert obj instanceof AssignableNode ; headList . add ( ( AssignableNode ) obj ) ; tailList . add ( ( ( AssignableNode ) obj ) . getValueNode ( ) ) ; ( ( AssignableNode ) obj ) . setValueNode ( null ) ; } } private void processRestArg ( MethodDefNode definition , ArrayNode headList , ArrayNode tailList , Object [ ] defnArguments , Object [ ] arguments ) { String restArgName = definition . getScope ( ) . getVariables ( ) [ definition . getArgsNode ( ) . getRestArg ( ) ] ; ArrayNode restParams = new ArrayNode ( new IDESourcePosition ( ) ) ; for ( int i = defnArguments . length ; i < arguments . length ; i ++ ) { restParams . add ( ( Node ) arguments [ i ] ) ; } headList . add ( createAssignment ( restArgName ) ) ; tailList . add ( restParams ) ; } private LocalAsgnNode createAssignment ( String name ) { return new LocalAsgnNode ( new IDESourcePosition ( ) , name , - , null ) ; } private DocumentProvider renameVariable ( DocumentProvider StringDocumentProvider , INameNode varNode , INameNode argumentNode ) { return new LocalVariableRenamer ( StringDocumentProvider , argumentNode . getName ( ) , varNode . getName ( ) ) . rename ( ) ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String InlineMethodConditionChecker_CannotFindDefinition ; public static String InlineMethodConditionChecker_CannotGuessType ; public static String InlineMethodConditionChecker_NoMethodCall ; public static String InlineMethodConditionChecker_ToManyReturns ; public static String InlineMethodRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . InlineMethodPage ; import org . rubypeople . rdt . refactoring . ui . pages . inlinemethod . TargetClassFinderUI ; public class InlineMethodRefactoring extends RubyRefactoring { public static final String NAME = Messages . InlineMethodRefactoring_Name ; public InlineMethodRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; InlineMethodConfig config = new InlineMethodConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) , new TargetClassFinderUI ( ) ) ; InlineMethodConditionChecker checker = new InlineMethodConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { InlineAndRemoveEditProvider removeEditProvider = new InlineAndRemoveEditProvider ( config ) ; setEditProvider ( removeEditProvider ) ; pages . add ( new InlineMethodPage ( removeEditProvider ) ) ; } } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . refactoring . core . renamelocal . LocalVariableRenamer ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . util . NameHelper ; public class RenameDuplicatedVariables implements IRenameDuplicatedVariables { public DocumentProvider rename ( DocumentProvider doc , String [ ] localNames ) { RootNode rootNode = doc . getActiveFileRootNode ( ) ; DocumentProvider result = doc ; for ( String name : NameHelper . findDuplicates ( rootNode . getStaticScope ( ) . getVariables ( ) , localNames ) ) { if ( "" . equals ( name ) || "" . equals ( name ) ) continue ; result = new LocalVariableRenamer ( result , name , NameHelper . createName ( name ) ) . rename ( ) ; } return result ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . jruby . ast . MethodDefNode ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public interface IMethodFinder { MethodDefNode find ( String className , String methodName , IDocumentProvider doc ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; public interface IMethodBodyStatementReplacer { DocumentProvider replaceSelfWithObject ( DocumentProvider doc , String object ) ; DocumentProvider prefixCallsWithObject ( DocumentProvider doc , IncludedClassesProvider provider , String className , String object ) ; DocumentProvider removeReturnStatements ( DocumentProvider doc ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . jruby . ast . AssignableNode ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; public interface IReturnStatementReplacer { boolean singleReturnOnLastLine ( DocumentProvider doc ) ; DocumentProvider replaceReturn ( DocumentProvider doc , AssignableNode target ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . util . HsrFormatter ; public class InlineMethodEditProvider extends EditProvider { private final Node node ; private final InlineMethodConfig config ; public InlineMethodEditProvider ( InlineMethodConfig config ) { super ( true , false ) ; this . config = config ; if ( config . getSelectedCall ( ) == null ) { this . node = null ; return ; } Node parent = config . getCallParent ( ) ; if ( parent instanceof AssignableNode ) { this . node = parent ; } else { this . node = config . getSelectedCall ( ) . getWrappedNode ( ) ; } } @ Override public TextEdit getEdit ( final String document ) { return new ReplaceEdit ( getOffset ( ) , getOffsetLength ( ) , format ( document ) . replaceFirst ( "" , "" ) ) ; } private String format ( final String document ) { return HsrFormatter . format ( document , config . getMethodDefDoc ( ) . getActiveFileContent ( ) , getOffset ( ) ) ; } protected int getOffsetLength ( ) { return getOffsetLength ( node ) ; } private int getOffsetLength ( final Node parent ) { return parent . getPosition ( ) . getEndOffset ( ) - parent . getPosition ( ) . getStartOffset ( ) ; } @ Override protected Node getEditNode ( final int offset , final String document ) { assert false : "" ; return null ; } @ Override protected int getOffset ( final String document ) { return getOffset ( ) ; } private int getOffset ( ) { return node . getPosition ( ) . getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; public interface IRemoveDeclaration { void setRemove ( boolean remove ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . jruby . ast . MethodDefNode ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; public interface IParameterReplacer { DocumentProvider replace ( IDocumentProvider doc , MethodCallNodeWrapper call , MethodDefNode definition ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . jruby . ast . CallNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . VCallNode ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; public class SelectedCallFinder implements ISelectedCallFinder { public MethodCallNodeWrapper findSelectedCall ( final int pos , final IDocumentProvider doc ) { final Node selectedNode = SelectionNodeProvider . getSelectedNodeOfType ( doc . getActiveFileRootNode ( ) , pos , CallNode . class , FCallNode . class , VCallNode . class ) ; return selectedNode != null ? new MethodCallNodeWrapper ( selectedNode ) : null ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . FCallNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . ReturnNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class MethodBodyStatementReplacer implements IMethodBodyStatementReplacer { public DocumentProvider replaceSelfWithObject ( final DocumentProvider doc , final String object ) { Collection < Node > selfNodes = null ; DocumentProvider result = new StringDocumentProvider ( doc ) ; do { selfNodes = NodeProvider . gatherNodesOfTypeInAktScopeNode ( result . getActiveFileRootNode ( ) . getBodyNode ( ) , SelfNode . class ) ; if ( selfNodes . isEmpty ( ) ) { continue ; } final SelfNode node = ( SelfNode ) selfNodes . iterator ( ) . next ( ) ; StringBuilder tempResult = new StringBuilder ( ) ; tempResult . append ( result . getActiveFileContent ( ) . substring ( , node . getPosition ( ) . getStartOffset ( ) ) ) ; tempResult . append ( object ) ; tempResult . append ( result . getActiveFileContent ( ) . substring ( node . getPosition ( ) . getEndOffset ( ) ) ) ; result = new StringDocumentProvider ( "" + doc . getActiveFileName ( ) , tempResult . toString ( ) ) ; } while ( ! selfNodes . isEmpty ( ) ) ; return result ; } public DocumentProvider replaceVarsWithAccessor ( DocumentProvider doc , String object , Collection < String > usedMembers ) { DocumentProvider result = new StringDocumentProvider ( doc ) ; Collection < Node > varNodes = null ; do { varNodes = NodeProvider . gatherNodesOfTypeInAktScopeNode ( result . getActiveFileRootNode ( ) . getBodyNode ( ) , InstVarNode . class , InstAsgnNode . class ) ; for ( Node actVarNode : new ArrayList < Node > ( varNodes ) ) { if ( ( ( INameNode ) actVarNode ) . getName ( ) . equals ( object ) ) { varNodes . remove ( actVarNode ) ; } } if ( varNodes . isEmpty ( ) ) { continue ; } final Node varNode = varNodes . iterator ( ) . next ( ) ; String name = ( ( INameNode ) varNode ) . getName ( ) ; usedMembers . add ( name ) ; StringBuilder src = new StringBuilder ( result . getActiveFileContent ( ) ) ; src . replace ( varNode . getPosition ( ) . getStartOffset ( ) , varNode . getPosition ( ) . getStartOffset ( ) + name . length ( ) , object + '' + name . substring ( ) ) ; result = new StringDocumentProvider ( "" + doc . getActiveFileName ( ) , src . toString ( ) ) ; } while ( ! varNodes . isEmpty ( ) ) ; return result ; } public DocumentProvider prefixCallsWithObject ( DocumentProvider doc , IncludedClassesProvider provider , String className , String object ) { DocumentProvider result = new StringDocumentProvider ( doc ) ; MethodCallNodeWrapper call = null ; while ( ( call = findCallToMethodInClass ( result , provider , className ) ) != null ) { StringBuilder src = new StringBuilder ( result . getActiveFileContent ( ) ) ; src . insert ( call . getWrappedNode ( ) . getPosition ( ) . getStartOffset ( ) , object + '' ) ; result = new StringDocumentProvider ( "" + doc . getActiveFileName ( ) , src . toString ( ) ) ; } return result ; } private MethodCallNodeWrapper findCallToMethodInClass ( DocumentProvider doc , IncludedClassesProvider provider , String className ) { Collection < MethodNodeWrapper > definedMethods = provider . getAllMethodsFor ( className ) ; for ( MethodCallNodeWrapper node : findFAndVCalls ( doc ) ) { for ( MethodNodeWrapper methods : definedMethods ) { if ( methods . getName ( ) . equals ( node . getName ( ) ) ) { return node ; } } } return null ; } private Collection < MethodCallNodeWrapper > findFAndVCalls ( DocumentProvider doc ) { Collection < MethodCallNodeWrapper > methodCalls = new ArrayList < MethodCallNodeWrapper > ( ) ; for ( Node node : NodeProvider . gatherNodesOfTypeInAktScopeNode ( doc . getActiveFileRootNode ( ) . getBodyNode ( ) , VCallNode . class , FCallNode . class ) ) { methodCalls . add ( new MethodCallNodeWrapper ( node ) ) ; } return methodCalls ; } public DocumentProvider removeReturnStatements ( DocumentProvider doc ) { Collection < Node > nodes = null ; StringDocumentProvider result = new StringDocumentProvider ( doc ) ; do { nodes = NodeProvider . getSubNodes ( result . getActiveFileRootNode ( ) , ReturnNode . class ) ; if ( nodes . isEmpty ( ) ) break ; StringBuilder newBody = new StringBuilder ( result . getActiveFileContent ( ) ) ; int startOffset = nodes . iterator ( ) . next ( ) . getPosition ( ) . getStartOffset ( ) ; newBody . replace ( startOffset , startOffset + "" . length ( ) , "" ) ; result = new StringDocumentProvider ( "" + doc . getActiveFileName ( ) , newBody . toString ( ) ) ; } while ( ! nodes . isEmpty ( ) ) ; return result ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public interface IRenameDuplicatedVariables { IDocumentProvider rename ( DocumentProvider doc , String [ ] localNames ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . Node ; import org . jruby . ast . ReturnNode ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . util . FileHelper ; public class ReturnStatementReplacer implements IReturnStatementReplacer { public boolean singleReturnOnLastLine ( DocumentProvider doc ) { if ( countReturnNodes ( doc ) > ) { return false ; } else if ( countReturnNodes ( doc ) == ) { return returnIsOnLastLine ( getReturnNode ( doc ) , doc ) ; } else { return true ; } } private boolean returnIsOnLastLine ( ReturnNode node , DocumentProvider doc ) { String [ ] lines = doc . getActiveFileContent ( ) . split ( "" ) ; return node . getPosition ( ) . getStartLine ( ) == lines . length ; } private int countReturnNodes ( DocumentProvider doc ) { int returnNodes = ; for ( Node node : NodeProvider . getAllNodes ( doc . getActiveFileRootNode ( ) ) ) { if ( node instanceof ReturnNode ) { returnNodes ++ ; } } return returnNodes ; } private ReturnNode getReturnNode ( DocumentProvider doc ) { for ( Node node : NodeProvider . getAllNodes ( doc . getActiveFileRootNode ( ) ) ) { if ( node instanceof ReturnNode ) { return ( ReturnNode ) node ; } } return null ; } public DocumentProvider replaceReturn ( DocumentProvider doc , AssignableNode target ) { if ( ! singleReturnOnLastLine ( doc ) || target == null ) { return null ; } StringBuilder result = new StringBuilder ( ) ; ReturnNode returnNode = getReturnNode ( doc ) ; if ( returnNode == null ) { insertLastLineToAssignment ( doc , target , result ) ; } else { replaceReturnStatementWithAssignment ( doc , target , result , returnNode ) ; } return new StringDocumentProvider ( "" + doc . getActiveFileName ( ) , result . append ( ReWriteVisitor . createCodeFromNode ( target , doc . getActiveFileContent ( ) ) ) . toString ( ) ) ; } private void insertLastLineToAssignment ( DocumentProvider doc , AssignableNode target , StringBuilder result ) { String [ ] lines = doc . getActiveFileContent ( ) . split ( "" ) ; target . setValueNode ( NodeProvider . getRootNode ( "" + doc . getActiveFileName ( ) + "" , lines [ lines . length - ] ) . getBodyNode ( ) ) ; String lineDelimiter = FileHelper . getLineDelimiter ( doc . getActiveFileContent ( ) ) ; for ( int i = ; i < lines . length - ; i ++ ) { result . append ( lines [ i ] ) ; result . append ( lineDelimiter ) ; } } private void replaceReturnStatementWithAssignment ( DocumentProvider doc , AssignableNode target , StringBuilder result , ReturnNode returnNode ) { target . setValueNode ( returnNode . getValueNode ( ) ) ; result . append ( doc . getActiveFileContent ( ) . substring ( , returnNode . getPosition ( ) . getStartOffset ( ) ) ) ; } } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; public interface ISelectedCallFinder { MethodCallNodeWrapper findSelectedCall ( int pos , IDocumentProvider doc ) ; } package org . rubypeople . rdt . refactoring . core . inlinemethod ; import java . util . Collection ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NameHelper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class TargetClassFinder implements ITargetClassFinder { public String findTargetClass ( final MethodCallNodeWrapper call , final IDocumentProvider doc ) { String name = "" ; if ( call . getReceiverNode ( ) == null ) { name = getSurroundingClass ( call , doc ) ; } final AssignableNode type = getAssignableNode ( call , doc ) ; if ( createsNewInstance ( type ) ) { Node receiver = ( ( CallNode ) type . getValueNode ( ) ) . getReceiverNode ( ) ; name = NameHelper . getFullyQualifiedName ( receiver ) ; } return name ; } private String getSurroundingClass ( final MethodCallNodeWrapper call , final IDocumentProvider doc ) { ClassNode classNode = ( ( ClassNode ) NodeProvider . getEnclosingNodeOfType ( doc . getActiveFileRootNode ( ) , call . getWrappedNode ( ) , ClassNode . class ) ) ; if ( classNode != null ) { return classNode . getCPath ( ) . getName ( ) ; } return "" ; } private AssignableNode getAssignableNode ( final MethodCallNodeWrapper call , final IDocumentProvider doc ) { AssignableNode receiverType = null ; if ( call . getReceiverNode ( ) instanceof LocalVarNode ) { receiverType = localAsgnFromLocalVar ( ( LocalVarNode ) call . getReceiverNode ( ) , doc ) ; } else if ( call . getReceiverNode ( ) instanceof InstVarNode ) { receiverType = instVarFromCall ( ( InstVarNode ) call . getReceiverNode ( ) , doc ) ; } return receiverType ; } private boolean createsNewInstance ( final AssignableNode receiverType ) { return receiverType != null && receiverType . getValueNode ( ) instanceof CallNode && "" . equals ( ( ( CallNode ) receiverType . getValueNode ( ) ) . getName ( ) ) ; } public InstAsgnNode instVarFromCall ( final InstVarNode node , final IDocumentProvider doc ) { InstAsgnNode decoratedNode = null ; try { final ClassNodeWrapper selectedClassNode = SelectionNodeProvider . getSelectedClassNode ( doc . getActiveFileRootNode ( ) , node . getPosition ( ) . getStartOffset ( ) ) ; final ClassNodeWrapper allClassNodes = new ClassNodeProvider ( doc ) . getClassNode ( ( selectedClassNode . getName ( ) ) ) ; if ( allClassNodes == null ) { throw new NoClassNodeException ( ) ; } for ( FieldNodeWrapper field : allClassNodes . getFields ( ) ) { if ( field . getName ( ) . equals ( node . getName ( ) ) && field . getNodeType ( ) == FieldNodeWrapper . INST_ASGN_NODE ) { decoratedNode = ( InstAsgnNode ) field . getWrappedNode ( ) ; } } } catch ( NoClassNodeException e ) { decoratedNode = findInstVarInScope ( node , doc , null ) ; } return decoratedNode ; } private InstAsgnNode findInstVarInScope ( final InstVarNode node , final IDocumentProvider doc , InstAsgnNode decoratedNode ) { Collection < Node > assignments = NodeProvider . getSubNodes ( doc . getActiveFileRootNode ( ) , InstAsgnNode . class ) ; for ( Node assignment : assignments ) { if ( ( ( InstAsgnNode ) assignment ) . getName ( ) . equals ( node . getName ( ) ) && assignment . getPosition ( ) . getStartOffset ( ) < node . getPosition ( ) . getStartOffset ( ) ) { decoratedNode = ( InstAsgnNode ) assignment ; } } return decoratedNode ; } public LocalAsgnNode localAsgnFromLocalVar ( final LocalVarNode node , final IDocumentProvider doc ) { Node enclosingScope = SelectionNodeProvider . getEnclosingScope ( doc . getActiveFileRootNode ( ) , node ) ; LocalAsgnNode asgnNode = findLastAssignmentToVar ( node , NodeUtil . getBody ( enclosingScope ) ) ; if ( asgnNode != null ) { return asgnNode ; } do { enclosingScope = SelectionNodeProvider . getEnclosingScope ( doc . getActiveFileRootNode ( ) , NodeProvider . findParentNode ( doc . getActiveFileRootNode ( ) , enclosingScope ) ) ; asgnNode = findLastAssignmentToVar ( node , NodeUtil . getBody ( enclosingScope ) ) ; } while ( ! ( enclosingScope instanceof RootNode || enclosingScope instanceof MethodDefNode ) && asgnNode == null ) ; return asgnNode ; } private LocalAsgnNode findLastAssignmentToVar ( final LocalVarNode node , final Node enclosingScope ) { LocalAsgnNode localAsgnNode = null ; for ( LocalAsgnNode asgnNode : NodeProvider . gatherLocalAsgnNodes ( enclosingScope ) ) { if ( asgnNode . getIndex ( ) == node . getIndex ( ) && asgnNode . getName ( ) . equals ( node . getName ( ) ) && asgnNode . getPosition ( ) . getStartOffset ( ) < node . getPosition ( ) . getStartOffset ( ) ) { localAsgnNode = asgnNode ; } } return localAsgnNode ; } } package org . rubypeople . rdt . refactoring . core ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Locale ; import org . jruby . ast . ArgsCatNode ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . BlockArgNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2ImplicitNode ; import org . jruby . ast . Colon3Node ; import org . jruby . ast . CommentNode ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . FCallOneArgNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . RestArgNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . SuperNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . ZSuperNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . parser . LocalStaticScope ; import org . jruby . parser . StaticScope ; import org . rubypeople . rdt . refactoring . nodewrapper . ArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . util . Constants ; public class NodeFactory { public static final Node NULL_POSITION_NODE = new NewlineNode ( new IDESourcePosition ( ) , null ) ; public static FCallNode createSimpleAccessorNode ( String definitionName , String attrName ) { ArrayNode argsNode = new ArrayNode ( new IDESourcePosition ( ) ) ; argsNode . add ( new SymbolNode ( new IDESourcePosition ( ) , attrName ) ) ; return new FCallOneArgNode ( new IDESourcePosition ( ) , definitionName , argsNode ) ; } public static DefsNode createStaticMethodNode ( String methodName , Collection < String > args , StaticScope scopeNode , Node body ) { return createStaticMethodNode ( "" , methodName , createArgsNode ( args . toArray ( new String [ args . size ( ) ] ) ) , scopeNode == null ? new LocalStaticScope ( null ) : scopeNode , body ) ; } public static DefnNode createMethodNode ( String methodName , String [ ] args , Node scopeContentNode ) { ArgsNode argsNode = createArgsNode ( args ) ; return createMethodNode ( methodName , argsNode , scopeContentNode ) ; } public static DefnNode createMethodNode ( String methodName , ArgsNode argsNode , Node body ) { ArgumentNode methodNameNode = new ArgumentNode ( new IDESourcePosition ( ) , methodName ) ; return new DefnNode ( new IDESourcePosition ( ) , methodNameNode , argsNode , new LocalStaticScope ( null ) , body != null ? new NewlineNode ( body . getPosition ( ) , body ) : null ) ; } public static DefnNode createMethodNodeWithoutNewline ( String methodName , ArgsNode argsNode , Node body ) { ArgumentNode methodNameNode = new ArgumentNode ( new IDESourcePosition ( ) , methodName ) ; return new DefnNode ( new IDESourcePosition ( ) , methodNameNode , argsNode , new LocalStaticScope ( null ) , body ) ; } public static DefsNode createStaticMethodNode ( String className , String methodName , ArgsNodeWrapper argsNode , StaticScope scopeNode ) { return createStaticMethodNode ( className , methodName , argsNode . getWrappedNode ( ) , scopeNode , null ) ; } public static DefsNode createStaticMethodNode ( String className , String methodName , ArgsNode argsNode , StaticScope scopeNode , Node body ) { return new DefsNode ( new IDESourcePosition ( ) , createConstNode ( className ) , createArgumentNode ( methodName ) , argsNode , scopeNode , body ) ; } public static ArgsNode createArgsNode ( String ... args ) { return createArgsNode ( args , null , - , null , null ) ; } public static ArgsNode createArgsNode ( Collection < String > args ) { return createArgsNode ( args . toArray ( new String [ args . size ( ) ] ) ) ; } public static ArgsNode createArgsNode ( String [ ] args , ListNode optArgs , int restArgs , RestArgNode restArgNode , BlockArgNode blockArg ) { ListNode argumentsList = null ; if ( args . length > ) { argumentsList = new ListNode ( new IDESourcePosition ( ) ) ; for ( String arg : args ) argumentsList . add ( new ArgumentNode ( new IDESourcePosition ( ) , arg ) ) ; } ArgsNode argsNode = new ArgsNode ( new IDESourcePosition ( ) , argumentsList , optArgs , restArgNode , null , blockArg ) ; return argsNode ; } public static DefnNode createConstructor ( BlockNode content ) { return createMethodNode ( Constants . CONSTRUCTOR_NAME , new String [ ] { } , content ) ; } public static DefnNode createDefaultConstructor ( ) { return createConstructor ( new BlockNode ( new IDESourcePosition ( ) ) ) ; } public static InstAsgnNode createInstAsgnNode ( String name , Node valueNode ) { return new InstAsgnNode ( new IDESourcePosition ( ) , name , valueNode ) ; } public static InstVarNode createInstVarNode ( String name ) { return new InstVarNode ( new IDESourcePosition ( ) , name ) ; } public static Node createSuperNode ( Collection < String > args ) { if ( args . isEmpty ( ) ) { return new ZSuperNode ( new IDESourcePosition ( ) ) ; } ArrayNode argsNode = createArrayNodeWithLocalVarNodes ( args ) ; return new SuperNode ( new IDESourcePosition ( ) , argsNode ) ; } private static ArrayNode createArrayNodeWithLocalVarNodes ( Collection < String > args ) { ArrayNode arrayNode = new ArrayNode ( new IDESourcePosition ( ) ) ; for ( String name : args ) { arrayNode . add ( new LocalVarNode ( new IDESourcePosition ( ) , , name ) ) ; } return arrayNode ; } public static BlockNode createBlockNode ( ) { return new BlockNode ( new IDESourcePosition ( ) ) ; } public static BlockNode createBlockNode ( Node ... content ) { BlockNode blockNode = new BlockNode ( new IDESourcePosition ( ) ) ; for ( Node node : content ) { blockNode . add ( node ) ; } return blockNode ; } public static BlockNode createBlockNode ( boolean needsNewLineAtEndOfBlock , Node ... contentNodes ) { return createBlockNode ( true , needsNewLineAtEndOfBlock , contentNodes ) ; } public static BlockNode createBlockNode ( boolean leadingNewLine , boolean subsequentNewline , Node ... contentNodes ) { return createBlockNode ( leadingNewLine , subsequentNewline , false , contentNodes ) ; } public static BlockNode createBlockNode ( boolean leadingNewLine , boolean subsequentNewline , boolean newLineBetweenNodes , Node ... contentNodes ) { BlockNode blockNode = createBlockNode ( ) ; if ( leadingNewLine ) { blockNode . add ( NodeFactory . createNewLineNode ( null ) ) ; } for ( Node aktContentNode : contentNodes ) { if ( newLineBetweenNodes ) { blockNode . add ( createNewLineNode ( aktContentNode ) ) ; } else { blockNode . add ( aktContentNode ) ; } } if ( subsequentNewline ) { blockNode . add ( NodeFactory . createNewLineNode ( null ) ) ; } return blockNode ; } public static NewlineNode createNewLineNode ( Node nextNode ) { return new NewlineNode ( new IDESourcePosition ( ) , nextNode ) ; } public static ListNode createListNode ( Collection < ? extends Node > nodes ) { ListNode listNode = new ListNode ( new IDESourcePosition ( ) ) ; for ( Node aktNode : nodes ) { listNode . add ( aktNode ) ; } return listNode ; } public static ListNode createListNode ( ) { return new ListNode ( new IDESourcePosition ( ) ) ; } public static ClassNode createClassNode ( String className , Node bodyNode ) { Colon2ImplicitNode classNameNode = new Colon2ImplicitNode ( new IDESourcePosition ( ) , className ) ; return new ClassNode ( new IDESourcePosition ( ) , classNameNode , new LocalStaticScope ( null ) , bodyNode , null ) ; } public static Node createCommentNode ( String commentValue ) { return new CommentNode ( new IDESourcePosition ( ) , commentValue ) ; } public static ClassVarNode createClassVarNode ( String name ) { return new ClassVarNode ( new IDESourcePosition ( ) , name ) ; } public static ClassVarAsgnNode createClassVarAsgnNode ( String name , Node valueNode ) { return new ClassVarAsgnNode ( new IDESourcePosition ( ) , name , valueNode ) ; } public static Node createMethodCallNode ( String name , Collection < ? extends Node > arguments ) { if ( arguments == null || arguments . isEmpty ( ) ) { return createVCallNode ( name ) ; } return createFCallNode ( name , arguments ) ; } public static Node createMethodCallNode ( String name , Node argsNode ) { if ( argsNode == null ) { return createVCallNode ( name ) ; } return createFCallNode ( name , argsNode ) ; } public static FCallNode createFCallNode ( String name , Collection < ? extends Node > arguments ) { return new FCallNode ( new IDESourcePosition ( ) , name , createArrayNode ( arguments ) ) ; } public static FCallNode createFCallNode ( String name , Node argumentNode ) { return new FCallNode ( new IDESourcePosition ( ) , name , argumentNode ) ; } public static ArrayNode createArrayNode ( Collection < ? extends Node > nodes ) { ArrayNode arrNode = new ArrayNode ( new IDESourcePosition ( ) ) ; for ( Node aktNode : nodes ) { arrNode . add ( aktNode ) ; } return arrNode ; } public static Node createVCallNode ( String name ) { return new VCallNode ( new IDESourcePosition ( ) , name ) ; } public static LocalAsgnNode createLocalAsgnNode ( String name , int id , Node valueNode ) { return new LocalAsgnNode ( new IDESourcePosition ( ) , name , id , valueNode ) ; } public static MultipleAsgnNode createMultipleAsgnNode ( Collection < ? extends Node > headNodes , Node valueNode ) { ListNode listNode = createListNode ( headNodes ) ; MultipleAsgnNode multipleAsgnNode = new MultipleAsgnNode ( new IDESourcePosition ( ) , listNode , null ) ; multipleAsgnNode . setValueNode ( valueNode ) ; return multipleAsgnNode ; } public static SymbolNode createSymboleNode ( String symbolName ) { return new SymbolNode ( new IDESourcePosition ( ) , symbolName ) ; } public static DVarNode createDVarNode ( String name ) { return new DVarNode ( new IDESourcePosition ( ) , , name ) ; } public static ISourcePosition unionPositions ( ISourcePosition first , ISourcePosition second ) { String fileName = first . getFile ( ) ; int startOffset = first . getStartOffset ( ) ; int endOffset = first . getEndOffset ( ) ; int startLine = first . getStartLine ( ) ; int endLine = first . getEndLine ( ) ; if ( startOffset > second . getStartOffset ( ) ) { startOffset = second . getStartOffset ( ) ; startLine = second . getStartLine ( ) ; } if ( endOffset < second . getEndOffset ( ) ) { endOffset = second . getEndOffset ( ) ; endLine = second . getEndLine ( ) ; } return new IDESourcePosition ( fileName , startLine , endLine , startOffset , endOffset ) ; } public static BlockNode createGetterSetter ( String attrName , boolean isWriterMethod , VisibilityNodeWrapper . METHOD_VISIBILITY visibility ) { return createGetterSetter ( attrName , isWriterMethod , visibility , new ArrayList < CommentNode > ( ) ) ; } public static BlockNode createGetterSetter ( String attrName , boolean isWriterMethod , VisibilityNodeWrapper . METHOD_VISIBILITY visibility , Collection < CommentNode > comments ) { String methodName = attrName + ( ( isWriterMethod ) ? "" : "" ) ; String [ ] args = ( isWriterMethod ) ? new String [ ] { attrName } : new String [ ] { } ; DefnNode methodNode = createGetterSetterNode ( isWriterMethod , methodName , attrName , args ) ; methodNode . addComments ( comments ) ; BlockNode block = createBlockNode ( ) ; block . add ( createNewLineNode ( methodNode ) ) ; if ( ! visibility . equals ( VisibilityNodeWrapper . METHOD_VISIBILITY . NONE ) ) block . add ( createVisibilityNode ( visibility , methodName ) ) ; return block ; } public static Node createVisibilityNode ( VisibilityNodeWrapper . METHOD_VISIBILITY visibility , String ... methodNames ) { Collection < Node > arguments = new ArrayList < Node > ( ) ; for ( String methodName : methodNames ) { SymbolNode symbolNode = NodeFactory . createSymboleNode ( methodName ) ; arguments . add ( symbolNode ) ; } FCallNode fCallNode = NodeFactory . createFCallNode ( visibility . name ( ) . toLowerCase ( Locale . ENGLISH ) , arguments ) ; return NodeFactory . createNewLineNode ( fCallNode ) ; } private static DefnNode createGetterSetterNode ( boolean isWriterMethod , String methodName , String attrName , String [ ] args ) { Node bodyContent ; if ( isWriterMethod ) bodyContent = NodeFactory . createInstAsgnNode ( '' + attrName , NodeFactory . createLocalVarNode ( attrName ) ) ; else bodyContent = NodeFactory . createInstVarNode ( '' + attrName ) ; DefnNode methodNode = NodeFactory . createMethodNode ( methodName , args , bodyContent ) ; return methodNode ; } public static CallNode createCallNode ( Node receiverNode , String name , Node argsNode ) { return new CallNode ( new IDESourcePosition ( ) , receiverNode , name , argsNode , null ) ; } public static ArgumentNode createArgumentNode ( String name ) { return new ArgumentNode ( new IDESourcePosition ( ) , name ) ; } public static FCallNode createAccessorNode ( AttrAccessorNodeWrapper accessor ) { ArrayNode argsNode = new ArrayNode ( new IDESourcePosition ( ) ) ; argsNode . add ( new SymbolNode ( new IDESourcePosition ( ) , accessor . getAttrName ( ) ) ) ; return new FCallOneArgNode ( new IDESourcePosition ( ) , accessor . getAccessorTypeName ( ) , argsNode ) ; } public static ConstNode createConstNode ( String name ) { return new ConstNode ( new IDESourcePosition ( ) , name ) ; } public static ArgsCatNode createArgsCatNode ( Node firstNode , Node secondNode ) { return new ArgsCatNode ( new IDESourcePosition ( ) , firstNode , secondNode ) ; } public static SelfNode createSelfNode ( ) { return new SelfNode ( new IDESourcePosition ( ) ) ; } public static ArrayNode createArrayNode ( ) { return new ArrayNode ( new IDESourcePosition ( ) ) ; } public static Node createLocalVarNode ( String argName ) { return new LocalVarNode ( new IDESourcePosition ( ) , , argName ) ; } public static Node createConstDeclNode ( String name , Node valueNode ) { return new ConstDeclNode ( new IDESourcePosition ( ) , name , null , valueNode ) ; } } package org . rubypeople . rdt . refactoring . core . overridemethod ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . pages . OverrideMethodSelectionPage ; public class OverrideMethodRefactoring extends RubyRefactoring { public static final String NAME = Messages . OverrideMethodRefactoring_Name ; public OverrideMethodRefactoring ( ) { super ( NAME ) ; MethodsOverrider methodsOverrider = new MethodsOverrider ( getDocumentProvider ( ) ) ; setEditProvider ( methodsOverrider ) ; OverrideMethodSelectionPage page = new OverrideMethodSelectionPage ( methodsOverrider ) ; pages . add ( page ) ; } } package org . rubypeople . rdt . refactoring . core . overridemethod ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . classnodeprovider . IncludedClassesProvider ; import org . rubypeople . rdt . refactoring . core . overridemethod . MethodsOverrider . TreeClass . TreeMethod ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditAndTreeContentProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProviderGroups ; import org . rubypeople . rdt . refactoring . editprovider . ITreeClass ; import org . rubypeople . rdt . refactoring . exception . UnknownClassNameException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . signatureprovider . ClassSignatureProvider ; import org . rubypeople . rdt . refactoring . signatureprovider . IClassSignatureProvider ; import org . rubypeople . rdt . refactoring . signatureprovider . MethodSignature ; import org . rubypeople . rdt . refactoring . ui . IItemSelectionReceiver ; import org . rubypeople . rdt . refactoring . ui . IParentProvider ; public class MethodsOverrider extends EditAndTreeContentProvider implements IItemSelectionReceiver { private ClassNodeProvider superClassNodeProvider ; private Object [ ] selectedTreeItems ; public MethodsOverrider ( DocumentProvider docProvider ) { superClassNodeProvider = docProvider . getClassNodeProvider ( ) ; IncludedClassesProvider includedClassesProvider = new IncludedClassesProvider ( docProvider ) ; if ( includedClassesProvider != null ) superClassNodeProvider . addClassNodeProvider ( includedClassesProvider ) ; initTreeClasses ( docProvider . getClassNodeProvider ( ) ) ; } @ Override public Collection < EditProvider > getEditProviders ( ) { EditProviderGroups editProviderGroups = new EditProviderGroups ( ) ; if ( selectedTreeItems != null ) { for ( Object o : selectedTreeItems ) { if ( o instanceof TreeMethod ) { TreeMethod treeMethod = ( TreeMethod ) o ; editProviderGroups . add ( treeMethod . getSignatureGroup ( ) , treeMethod . getOverriddenMethod ( ) ) ; } } } return editProviderGroups . getAllEditProviders ( ) ; } private IClassSignatureProvider getSuperSignatureProvider ( ClassNodeWrapper classNode ) throws UnknownClassNameException { String superClassName = "" ; superClassName = classNode . getSuperClassName ( ) ; return ClassSignatureProvider . getClassSignatureProvider ( superClassName , superClassNodeProvider ) ; } public void setSelectedItems ( Object [ ] checkedElements ) { selectedTreeItems = checkedElements . clone ( ) ; } public class TreeClass implements org . rubypeople . rdt . refactoring . ui . IChildrenProvider , org . rubypeople . rdt . refactoring . editprovider . ITreeClass { private ClassNodeWrapper classNode ; private Collection < TreeMethod > treeMethods ; public TreeClass ( ClassNodeWrapper classNode ) { this . classNode = classNode ; treeMethods = new ArrayList < TreeMethod > ( ) ; try { IClassSignatureProvider superClassSignatureProvider = getSuperSignatureProvider ( classNode ) ; for ( MethodSignature sign : superClassSignatureProvider . getMethodSignatures ( ) ) { treeMethods . add ( new TreeMethod ( sign ) ) ; } } catch ( UnknownClassNameException e ) { } } public String toString ( ) { return classNode . getName ( ) ; } public Object [ ] getChildren ( ) { return treeMethods . toArray ( ) ; } public boolean hasChildren ( ) { return ! treeMethods . isEmpty ( ) ; } public class TreeMethod implements IParentProvider { private MethodSignature methodSignature ; private String name ; public TreeMethod ( MethodSignature methodSignature ) { this . methodSignature = methodSignature ; name = getName ( ) ; } public String getSignatureGroup ( ) { if ( methodSignature . isConstructor ( ) ) { return "" + TreeClass . this . toString ( ) ; } return TreeClass . this . toString ( ) ; } public OverriddenMethod getOverriddenMethod ( ) { return new OverriddenMethod ( classNode , methodSignature ) ; } private String getName ( ) { return methodSignature . getNameWithArgs ( ) ; } public String toString ( ) { return name ; } public Object getParent ( ) { return TreeClass . this ; } } } @ Override protected ITreeClass createTreeClass ( ClassNodeWrapper classNode ) { return new TreeClass ( classNode ) ; } } package org . rubypeople . rdt . refactoring . core . overridemethod ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String OverrideMethodRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . overridemethod ; import java . util . Collection ; import org . jruby . ast . BlockNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . ConstructorOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . MethodOffsetProvider ; import org . rubypeople . rdt . refactoring . signatureprovider . MethodSignature ; public class OverriddenMethod extends InsertEditProvider { private MethodSignature signature ; private ClassNodeWrapper classNode ; public OverriddenMethod ( ClassNodeWrapper classNode , MethodSignature signature ) { super ( true ) ; this . signature = signature ; this . classNode = classNode ; lastEditInGroup = false ; } @ Override protected int getOffset ( String document ) { IOffsetProvider offsetProvider ; if ( signature . isConstructor ( ) ) offsetProvider = new ConstructorOffsetProvider ( classNode , document ) ; else offsetProvider = new MethodOffsetProvider ( classNode , document ) ; return offsetProvider . getOffset ( ) ; } @ Override protected BlockNode getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = lastEditInGroup && ! isNextLineEmpty ( offset , document ) ; BlockNode blockNode = NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , getMethodNode ( ) ) ; return blockNode ; } private Node getMethodNode ( ) { String methodName = signature . getMethodName ( ) ; Collection < String > args = signature . getArguments ( ) ; Node methodNode = getMethodNode ( methodName , args ) ; return methodNode ; } private Node getMethodNode ( String methodName , Collection < String > args ) { DefnNode methodNode = NodeFactory . createMethodNode ( methodName , args . toArray ( new String [ args . size ( ) ] ) , NodeFactory . createSuperNode ( args ) ) ; return NodeFactory . createNewLineNode ( methodNode ) ; } } package org . rubypeople . rdt . refactoring . core ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Map ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . CompositeChange ; import org . eclipse . ltk . core . refactoring . Refactoring ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . refactoring . changes . RenameResourceChange ; import org . rubypeople . rdt . internal . corext . refactoring . changes . RubyScriptChange ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . WorkspaceDocumentProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileNameChangeProvider ; import org . rubypeople . rdt . refactoring . editprovider . IEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; public abstract class RubyRefactoring extends Refactoring { protected RefactoringStatus initialStatus ; protected RefactoringStatus finalStatus ; private String name ; protected Collection < IWizardPage > pages ; private IEditProvider editProvider ; private IMultiFileEditProvider multiFileEditProvider ; private IRefactoringConditionChecker conditionChecker ; private IFile file ; private FileNameChangeProvider fileNameChangeProvider ; public RubyRefactoring ( String name ) { this ( name , null ) ; } public RubyRefactoring ( String name , IRefactoringContext selectionProvider ) { this . name = name ; initialStatus = new RefactoringStatus ( ) ; finalStatus = new RefactoringStatus ( ) ; pages = new ArrayList < IWizardPage > ( ) ; if ( selectionProvider != null ) { this . file = selectionProvider . getActiveFile ( ) ; } else { RubyEditor editor = ( RubyEditor ) PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . getActiveEditor ( ) ; this . file = ( ( IFileEditorInput ) editor . getEditorInput ( ) ) . getFile ( ) ; } } protected IFile getActiveFile ( ) { return file ; } protected void setEditProvider ( IEditProvider editProvider ) { this . editProvider = editProvider ; } protected void setEditProvider ( IMultiFileEditProvider multiFileEditProvider ) { this . multiFileEditProvider = multiFileEditProvider ; } protected void setFileNameChangeProvider ( FileNameChangeProvider fileNameChangeProvider ) { this . fileNameChangeProvider = fileNameChangeProvider ; } @ Override public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } @ Override public RefactoringStatus checkInitialConditions ( IProgressMonitor pm ) { if ( conditionChecker != null ) { Map < String , Collection < String > > messages = conditionChecker . getInitialMessages ( ) ; Collection < String > errors = messages . get ( IRefactoringConditionChecker . ERRORS ) ; for ( String errMessage : errors ) { initialStatus . addFatalError ( errMessage ) ; } Collection < String > warnings = messages . get ( IRefactoringConditionChecker . ERRORS ) ; for ( String warningMessage : warnings ) { initialStatus . addWarning ( warningMessage ) ; } } return initialStatus ; } @ Override public RefactoringStatus checkFinalConditions ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { finalStatus = new RefactoringStatus ( ) ; if ( conditionChecker != null ) { Map < String , Collection < String > > messages = conditionChecker . getFinalMessages ( ) ; Collection < String > errors = messages . get ( IRefactoringConditionChecker . ERRORS ) ; for ( String errMessage : errors ) { finalStatus . addFatalError ( errMessage ) ; } Collection < String > warnings = messages . get ( IRefactoringConditionChecker . WARNING ) ; for ( String warningMessage : warnings ) { finalStatus . addWarning ( warningMessage ) ; } } return finalStatus ; } @ Override public Change createChange ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { Change change = createEditChanges ( ) ; Map < String , String > filesToRename = getFileNameChangeProvider ( ) . getFilesToRename ( getAllAffectedFiles ( change ) ) ; if ( filesToRename . isEmpty ( ) ) { return change ; } CompositeChange compositeChange = new CompositeChange ( getName ( ) , new Change [ ] { change } ) ; compositeChange . markAsSynthetic ( ) ; for ( Map . Entry < String , String > entry : filesToRename . entrySet ( ) ) { RenameResourceChange renameResourceChange = new RenameResourceChange ( null , RubyPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( entry . getKey ( ) ) , entry . getValue ( ) , "" ) ; compositeChange . add ( new DynamicValidationStateChange ( renameResourceChange ) ) ; } return compositeChange ; } private Collection < IFile > getAllAffectedFiles ( Change change ) { Collection < IFile > affectedFiles = new ArrayList < IFile > ( ) ; for ( Object object : change . getAffectedObjects ( ) ) { if ( object instanceof IFile ) { affectedFiles . add ( ( IFile ) object ) ; } } return affectedFiles ; } private Change createEditChanges ( ) { DocumentProvider docProvider = new WorkspaceDocumentProvider ( getActiveFile ( ) ) ; if ( multiFileEditProvider != null ) { return createMultiFileChange ( docProvider ) ; } return createActiveFileChange ( docProvider ) ; } private Change createActiveFileChange ( DocumentProvider docProvider ) { return getChange ( getActiveFile ( ) , editProvider , docProvider ) ; } private Change createMultiFileChange ( DocumentProvider docProvider ) { CompositeChange change = new CompositeChange ( name ) ; for ( FileMultiEditProvider currentProvider : multiFileEditProvider . getFileEditProviders ( ) ) { IFile currentIFile = getDocumentProvider ( ) . getIFile ( currentProvider . getFileName ( ) ) ; change . add ( getChange ( currentIFile , currentProvider , docProvider ) ) ; } return change ; } private Change getChange ( IFile file , IEditProvider editProvider , DocumentProvider docProvider ) { String fileName = file . getFullPath ( ) . toOSString ( ) ; IRubyScript script = RubyCore . create ( file ) ; RubyScriptChange change = new RubyScriptChange ( fileName , script ) ; String document = docProvider . getFileContent ( fileName ) ; change . setEdit ( editProvider . getEdit ( document ) ) ; return change ; } public Collection < IWizardPage > getPages ( ) { return pages ; } public WorkspaceDocumentProvider getDocumentProvider ( ) { return new WorkspaceDocumentProvider ( getActiveFile ( ) ) ; } protected void setRefactoringConditionChecker ( IRefactoringConditionChecker conditionChecker ) { this . conditionChecker = conditionChecker ; } public IRefactoringConditionChecker getConditionChecker ( ) { return conditionChecker ; } public IEditProvider getEditProvider ( ) { return editProvider ; } public IMultiFileEditProvider getMultiFileEditProvider ( ) { return multiFileEditProvider ; } public FileNameChangeProvider getFileNameChangeProvider ( ) { return fileNameChangeProvider != null ? fileNameChangeProvider : new FileNameChangeProvider ( ) ; } } package org . rubypeople . rdt . refactoring . core ; public interface IValidator { boolean isValid ( String test ) ; } package org . rubypeople . rdt . refactoring . core ; import org . eclipse . core . resources . IFile ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . TreeSelection ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; public class RefactoringContext implements IRefactoringContext { private String source ; private int start ; private int end ; private int caret ; private IFile file ; public RefactoringContext ( int start , int end , String src ) { this ( start , end , start , src ) ; } public RefactoringContext ( int start , int end , int caret , String src ) { this . start = start ; this . end = end ; this . caret = caret ; this . source = src ; } public RefactoringContext ( ) { initEditor ( ) ; } public RefactoringContext ( IAction action ) { if ( action == null || action instanceof org . eclipse . ui . internal . EditorPluginAction ) { initEditor ( ) ; } else { initOutline ( action ) ; } } private void initEditor ( ) { RubyEditor editor = ( RubyEditor ) PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . getActiveEditor ( ) ; ITextSelection selection = ( ITextSelection ) editor . getSelectionProvider ( ) . getSelection ( ) ; start = selection . getOffset ( ) ; end = start + selection . getLength ( ) ; if ( end > start ) { end -- ; } caret = editor . getCaretPosition ( ) . getOffset ( ) ; if ( editor . getEditorInput ( ) instanceof IFileEditorInput ) file = ( ( IFileEditorInput ) editor . getEditorInput ( ) ) . getFile ( ) ; } private void initOutline ( IAction action ) { TreeSelection selection = ( TreeSelection ) ( ( org . eclipse . ui . internal . PluginAction ) action ) . getSelection ( ) ; IMember member = ( IMember ) selection . toArray ( ) [ ] ; try { start = member . getNameRange ( ) . getOffset ( ) ; end = start + member . getNameRange ( ) . getLength ( ) ; caret = start ; file = ( IFile ) member . getRubyScript ( ) . getResource ( ) ; } catch ( RubyModelException e ) { e . printStackTrace ( ) ; } } public IFile getActiveFile ( ) { return file ; } public int getCaretPosition ( ) { return caret ; } public int getStartOffset ( ) { return start ; } public int getEndOffset ( ) { return end ; } public String getSource ( ) { if ( source == null ) { RubyEditor editor = ( RubyEditor ) PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . getActiveEditor ( ) ; source = editor . getViewer ( ) . getDocument ( ) . get ( ) ; } return source ; } } package org . rubypeople . rdt . refactoring . core . rename ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String RenameConditionChecker_NothingSelected ; public static String RenameRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . rename ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public class RenameConfig implements IRefactoringConfig { private IDocumentProvider documentProvider ; private int offset ; public RenameConfig ( DocumentProvider documentProvider , int offset ) { this . documentProvider = documentProvider ; this . offset = offset ; } public IDocumentProvider getDocumentProvider ( ) { return documentProvider ; } public int getOffset ( ) { return offset ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . documentProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . rename ; import org . rubypeople . rdt . refactoring . core . IRefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassConditionChecker ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassConfig ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConfig ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalConfig ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConfig ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public class RenameConditionChecker extends RefactoringConditionChecker { private enum RenameType { INVALID , LOCAL , FIELD , METHOD , CLASS , MODULE } ; private RenameType selectedType ; private RenameLocalConditionChecker localConditionChecker ; private RefactoringConditionChecker fieldConditionChecker ; private RefactoringConditionChecker methodConditionChecker ; private RefactoringConditionChecker classConditionChecker ; private RefactoringConditionChecker moduleConditionChecker ; public RenameConditionChecker ( RenameConfig config ) { super ( config ) ; } @ Override protected void checkInitialConditions ( ) { if ( selectedType == RenameType . INVALID ) { addErrorMessage ( ) ; } } private void addErrorMessage ( ) { addErrorIfNotDefaultError ( localConditionChecker , RenameLocalConditionChecker . DEFAULT_ERROR ) ; addErrorIfNotDefaultError ( fieldConditionChecker , RenameFieldConditionChecker . DEFAULT_ERROR ) ; addErrorIfNotDefaultError ( methodConditionChecker , RenameMethodConditionChecker . DEFAULT_ERROR ) ; addErrorIfNotDefaultError ( classConditionChecker , RenameClassConditionChecker . DEFAULT_ERROR ) ; addErrorIfNotDefaultError ( moduleConditionChecker , RenameClassConditionChecker . DEFAULT_ERROR ) ; if ( ! hasErrors ( ) ) { addError ( Messages . RenameConditionChecker_NothingSelected ) ; } } private void addErrorIfNotDefaultError ( RefactoringConditionChecker checker , String defaultError ) { String firstError = checker . getInitialMessages ( ) . get ( IRefactoringConditionChecker . ERRORS ) . toArray ( new String [ ] ) [ ] ; if ( ! firstError . equals ( defaultError ) ) { addError ( firstError ) ; } } @ Override public void init ( IRefactoringConfig configObj ) { RenameConfig config = ( RenameConfig ) configObj ; int offset = config . getOffset ( ) ; IDocumentProvider doc = config . getDocumentProvider ( ) ; localConditionChecker = new RenameLocalConditionChecker ( new RenameLocalConfig ( doc , offset ) ) ; fieldConditionChecker = new RenameFieldConditionChecker ( new RenameFieldConfig ( doc , offset ) ) ; methodConditionChecker = new RenameMethodConditionChecker ( new RenameMethodConfig ( doc , offset ) ) ; classConditionChecker = new RenameClassConditionChecker ( new RenameClassConfig ( doc , offset ) ) ; moduleConditionChecker = new RenameModuleConditionChecker ( new RenameModuleConfig ( doc , offset ) ) ; if ( localConditionChecker . shouldPerform ( ) ) { selectedType = RenameType . LOCAL ; } else if ( fieldConditionChecker . shouldPerform ( ) ) { selectedType = RenameType . FIELD ; } else if ( methodConditionChecker . shouldPerform ( ) ) { selectedType = RenameType . METHOD ; } else if ( classConditionChecker . shouldPerform ( ) ) { selectedType = RenameType . CLASS ; } else if ( moduleConditionChecker . shouldPerform ( ) ) { selectedType = RenameType . MODULE ; } else { selectedType = RenameType . INVALID ; } } public boolean shouldRenameLocal ( ) { return selectedType == RenameType . LOCAL ; } public boolean shouldRenameField ( ) { return selectedType == RenameType . FIELD ; } public boolean shouldRenameMethod ( ) { return selectedType == RenameType . METHOD ; } public boolean shouldRenameClass ( ) { return selectedType == RenameType . CLASS ; } public boolean shouldRenameModule ( ) { return selectedType == RenameType . MODULE ; } } package org . rubypeople . rdt . refactoring . core . rename ; import org . eclipse . jface . wizard . IWizardPage ; import org . rubypeople . rdt . refactoring . core . IRefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassRefactoring ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldRefactoring ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalRefactoring ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodRefactoring ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleRefactoring ; public class RenameRefactoring extends RubyRefactoring { public static final String NAME = Messages . RenameRefactoring_Name ; private RubyRefactoring delegateRenameRefactoring ; private IRefactoringContext selectionProvider ; public RenameRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; RenameConfig config = new RenameConfig ( getDocumentProvider ( ) , selectionProvider . getCaretPosition ( ) ) ; RenameConditionChecker checker = new RenameConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { if ( checker . shouldRenameLocal ( ) ) { delegateRenameRefactoring = new RenameLocalRefactoring ( selectionProvider ) ; } else if ( checker . shouldRenameField ( ) ) { delegateRenameRefactoring = new RenameFieldRefactoring ( selectionProvider ) ; } else if ( checker . shouldRenameMethod ( ) ) { delegateRenameRefactoring = new RenameMethodRefactoring ( selectionProvider ) ; } else if ( checker . shouldRenameClass ( ) ) { delegateRenameRefactoring = new RenameClassRefactoring ( selectionProvider ) ; } else if ( checker . shouldRenameModule ( ) ) { delegateRenameRefactoring = new RenameModuleRefactoring ( selectionProvider ) ; } IRefactoringConditionChecker delegateConditionChecker = delegateRenameRefactoring . getConditionChecker ( ) ; setRefactoringConditionChecker ( delegateConditionChecker ) ; if ( delegateConditionChecker . shouldPerform ( ) ) { setName ( delegateRenameRefactoring . getName ( ) ) ; setEditProvider ( delegateRenameRefactoring . getMultiFileEditProvider ( ) ) ; setEditProvider ( delegateRenameRefactoring . getEditProvider ( ) ) ; setFileNameChangeProvider ( delegateRenameRefactoring . getFileNameChangeProvider ( ) ) ; for ( IWizardPage aktPage : delegateRenameRefactoring . getPages ( ) ) { pages . add ( aktPage ) ; } } } } } package org . rubypeople . rdt . refactoring . core . movemethod ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; public class DelegateMethodEditProvider extends ReplaceEditProvider { private MoveMethodConfig config ; private Node scopePos ; private MethodNodeWrapper oldMethod ; public DelegateMethodEditProvider ( MoveMethodConfig config ) { super ( false ) ; this . config = config ; oldMethod = config . getMethodNode ( ) ; scopePos = NodeProvider . unwrap ( oldMethod . getBodyNode ( ) ) ; } @ Override protected int getOffsetLength ( String document ) { int length = getOffsetLength ( ) ; int offset = getOffset ( document ) ; String sub = document . substring ( offset , offset + length ) ; if ( sub . endsWith ( "" ) ) return length - ; return length ; } @ Override protected int getOffsetLength ( ) { return getExtendedPosition ( scopePos ) . getEndOffset ( ) - getExtendedPosition ( scopePos ) . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { return NodeFactory . createNewLineNode ( getMethodCallNode ( ) ) ; } private Node getMethodCallNode ( ) { Node receiverNode ; if ( oldMethod . isClassMethod ( ) ) { receiverNode = NodeFactory . createConstNode ( config . getDestinationClassNode ( ) . getName ( ) ) ; } else { receiverNode = NodeFactory . createInstVarNode ( config . getFieldInSourceClassOfTypeDestinationClass ( ) ) ; } ArgsNodeWrapper argsNode = oldMethod . getArgsNode ( ) ; ArrayNode arrayNode = NodeFactory . createArrayNode ( ) ; for ( String argName : argsNode . getArgsList ( ) ) { arrayNode . add ( NodeFactory . createLocalVarNode ( argName ) ) ; } if ( config . doesNewMethodNeedsReferenceToSourceClass ( ) ) { arrayNode . add ( NodeFactory . createSelfNode ( ) ) ; } return NodeFactory . createCallNode ( receiverNode , config . getMovedMethodName ( ) , ( arrayNode . size ( ) == ) ? null : arrayNode ) ; } @ Override protected int getOffset ( String document ) { return getExtendedPosition ( scopePos ) . getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . movemethod ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; public class ReplaceVisibilityEditProvider extends ReplaceEditProvider { private VisibilityNodeWrapper visbilityNode ; private METHOD_VISIBILITY newVisibility ; public ReplaceVisibilityEditProvider ( VisibilityNodeWrapper visibilityNode , METHOD_VISIBILITY newVisibility ) { super ( true ) ; this . visbilityNode = visibilityNode ; this . newVisibility = newVisibility ; } @ Override protected int getOffsetLength ( ) { return visbilityNode . getPosition ( ) . getEndOffset ( ) - visbilityNode . getPosition ( ) . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { String methodName = visbilityNode . getMethodNames ( ) . toArray ( new String [ visbilityNode . getMethodNames ( ) . size ( ) ] ) [ ] ; return NodeFactory . createVisibilityNode ( newVisibility , methodName ) ; } @ Override protected int getOffset ( String document ) { return visbilityNode . getPosition ( ) . getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . movemethod ; import org . jruby . ast . Node ; import org . jruby . ast . SelfNode ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . CallArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; public class ReplaceMethodCallEditProvider extends ReplaceEditProvider { private MethodCallNodeWrapper methodCallNode ; private MoveMethodConfig config ; public ReplaceMethodCallEditProvider ( MethodCallNodeWrapper methodCallNode , MoveMethodConfig config ) { super ( false ) ; this . config = config ; this . methodCallNode = methodCallNode ; } @ Override protected int getOffsetLength ( ) { return methodCallNode . getPosition ( ) . getEndOffset ( ) - methodCallNode . getPosition ( ) . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { Node receiverNode ; if ( ! methodCallNode . isCallToClassMethod ( ) ) { receiverNode = NodeFactory . createInstVarNode ( config . getFieldInSourceClassOfTypeDestinationClass ( ) ) ; } else { receiverNode = NodeFactory . createConstNode ( config . getDestinationClassNode ( ) . getName ( ) ) ; } CallArgsNodeWrapper argsNode = new CallArgsNodeWrapper ( methodCallNode . getArgsNode ( ) ) ; if ( config . doesNewMethodNeedsReferenceToSourceClass ( ) ) { SelfNode selfNode = NodeFactory . createSelfNode ( ) ; return NodeFactory . createCallNode ( receiverNode , config . getMovedMethodName ( ) , argsNode . cloneWithAddedArg ( selfNode ) ) ; } return NodeFactory . createCallNode ( receiverNode , config . getMovedMethodName ( ) , argsNode . getWrappedNode ( ) ) ; } @ Override protected int getOffset ( String document ) { return methodCallNode . getPosition ( ) . getStartOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . movemethod ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Observable ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; import org . rubypeople . rdt . refactoring . util . NameHelper ; public class MoveMethodConfig extends Observable implements IRefactoringConfig { private IDocumentProvider docProvider ; private int caretPosition ; private MethodNodeWrapper methodNode ; private ClassNodeWrapper sourceClassNode ; private ClassNodeProvider allClassesNodeProvider ; private ClassNodeWrapper destinationClassNode ; private String fieldInSourceClassOfTypeDestinationClass ; private String fieldInDestinationClassOfTypeSourceClass ; private METHOD_VISIBILITY movedMethodVisibility ; private METHOD_VISIBILITY methodVisibility ; private Collection < String > targetClassNames ; private Collection < String > fieldInSourceClassOfTypeDestinationClassNames ; private boolean leaveDelegateMethodInSoruce ; private boolean newMethodHasReferenceToSourceClass ; private boolean sourceClassHasCallsToMovingMethod ; private ArgsNodeWrapper movedMethodArgs ; private String movedMethodName ; private Collection < String > warnings ; public MoveMethodConfig ( IDocumentProvider docProvider , int caretPosition ) { this . docProvider = docProvider ; this . caretPosition = caretPosition ; warnings = new ArrayList < String > ( ) ; } public boolean doesNewMethodNeedsReferenceToSourceClass ( ) { return newMethodHasReferenceToSourceClass ; } public void setNewMethodNeedsReferenceToSourceClass ( boolean newMethodNeedsReferenceToSourceClass ) { this . newMethodHasReferenceToSourceClass = newMethodNeedsReferenceToSourceClass ; } public String getFieldInSourceClassOfTypeDestinationClass ( ) { return fieldInSourceClassOfTypeDestinationClass ; } public void setFieldInSourceClassOfTypeDestinationClass ( String fieldOfDestinationClassType ) { this . fieldInSourceClassOfTypeDestinationClass = fieldOfDestinationClassType ; this . setChanged ( ) ; this . notifyObservers ( ) ; } public IDocumentProvider getDocumentProvider ( ) { return docProvider ; } public boolean isClassMethod ( ) { return methodNode . isClassMethod ( ) ; } public ClassNodeProvider getAllClassesNodeProvider ( ) { return allClassesNodeProvider ; } public void setAllClassesNodeProvider ( ClassNodeProvider allClassesNodeProvider ) { this . allClassesNodeProvider = allClassesNodeProvider ; } public ClassNodeWrapper getDestinationClassNode ( ) { return destinationClassNode ; } public void setDestinationClassNode ( String aktClassName ) { destinationClassNode = allClassesNodeProvider . getClassNode ( aktClassName ) ; movedMethodName = initMovedMethodName ( ) ; this . setChanged ( ) ; this . notifyObservers ( ) ; } private String initMovedMethodName ( ) { String name = getMethodNode ( ) . getName ( ) ; while ( NameHelper . methodnameExistsInClass ( name , destinationClassNode ) ) { name = NameHelper . createName ( name ) ; } return name ; } public MethodNodeWrapper getMethodNode ( ) { return methodNode ; } public void setMethodNode ( MethodNodeWrapper methodNode ) { this . methodNode = methodNode ; if ( methodNode != null ) { movedMethodArgs = methodNode . getArgsNode ( ) ; movedMethodName = methodNode . getName ( ) ; } } public ClassNodeWrapper getSourceClassNode ( ) { return sourceClassNode ; } public void setSourceClassNode ( String sourceClassName ) { sourceClassNode = allClassesNodeProvider . getClassNode ( sourceClassName ) ; } public int getCaretPosition ( ) { return caretPosition ; } public String getFieldInDestinationClassOfTypeSourceClass ( ) { return fieldInDestinationClassOfTypeSourceClass ; } public void setFieldInDestinationClassOfTypeSourceClass ( String fieldInDestinationClassOfTypeSourceClass ) { this . fieldInDestinationClassOfTypeSourceClass = fieldInDestinationClassOfTypeSourceClass ; } public boolean leaveDelegateMethodInSource ( ) { return leaveDelegateMethodInSoruce ; } public void setLeaveDelegateMethodInSource ( boolean leaveDelegateMethodInSoruce ) { this . leaveDelegateMethodInSoruce = leaveDelegateMethodInSoruce ; setChanged ( ) ; notifyObservers ( ) ; } public METHOD_VISIBILITY getMovedMethodVisibility ( ) { return movedMethodVisibility ; } public void setMovedMethodVisibility ( METHOD_VISIBILITY neededMethodVisibility ) { this . movedMethodVisibility = neededMethodVisibility ; } public METHOD_VISIBILITY getMethodVisibility ( ) { return methodVisibility ; } public void setMethodVisibility ( METHOD_VISIBILITY methodVisibility ) { this . methodVisibility = methodVisibility ; } public Collection < String > getTargetClassNames ( ) { return targetClassNames ; } public void setTargetClassNames ( Collection < String > targetClassNames ) { this . targetClassNames = targetClassNames ; } public Collection < String > getFieldInSourceClassOfTypeDestinationClassNames ( ) { return fieldInSourceClassOfTypeDestinationClassNames ; } public void setFieldInSourceClassOfTypeDestinationClassNames ( Collection < String > fieldInSourceClassOfTypeDestinationClassNames ) { this . fieldInSourceClassOfTypeDestinationClassNames = fieldInSourceClassOfTypeDestinationClassNames ; } public boolean doesSourceClassHasCallsToMovingMethod ( ) { return sourceClassHasCallsToMovingMethod ; } public void setSourceClassHasCallsToMovingMethod ( boolean value ) { sourceClassHasCallsToMovingMethod = value ; } public ArgsNodeWrapper getMovedMethodArgs ( ) { return movedMethodArgs ; } public String getMovedMethodName ( ) { return movedMethodName ; } public void setMovedMethodName ( String name ) { movedMethodName = name ; } public void setMovedMethodArgs ( ArgsNodeWrapper movedMethodArgs ) { this . movedMethodArgs = movedMethodArgs ; } public boolean needsSecondPage ( ) { boolean isPrivate = sourceClassNode . getMethodVisibility ( methodNode ) . equals ( METHOD_VISIBILITY . PRIVATE ) ; boolean isClassMethod = methodNode . isClassMethod ( ) ; return ! isClassMethod && ( ! isPrivate || sourceClassHasCallsToMovingMethod ) ; } public boolean canCreateDelegateMethod ( ) { return needsSecondPage ( ) || methodNode . isClassMethod ( ) ; } public Collection < String > getWarnings ( ) { return warnings ; } public void addWarning ( String warning ) { warnings . add ( warning ) ; } public void resetWarnings ( ) { warnings . clear ( ) ; } public void setDocumentProvider ( IDocumentProvider doc ) { this . docProvider = doc ; } } package org . rubypeople . rdt . refactoring . core . movemethod ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String MethodMover_An ; public static String MethodMover_DuToNameConflicts ; public static String MethodMover_ForField ; public static String MethodMover_IsChangedFrom ; public static String MethodMover_NameWillBeChangedTo ; public static String MethodMover_TheVisibilityOfMethod ; public static String MethodMover_TheVisibilityOfTheMovingMethod ; public static String MethodMover_To ; public static String MethodMover_WillBeChangedToPublic ; public static String MethodMover_WillBeGenerated ; public static String MoveMethodConditionChecker_CanBeCalledFromOutside ; public static String MoveMethodConditionChecker_CannotMoveConstructor ; public static String MoveMethodConditionChecker_ContainsClassField ; public static String MoveMethodConditionChecker_MightNotGetReplaced ; public static String MoveMethodConditionChecker_MovingMightAffectTheFunctionality ; public static String MoveMethodConditionChecker_NeedsToBeInsideClass ; public static String MoveMethodConditionChecker_NeedsToBeInsideMethod ; public static String MoveMethodConditionChecker_NoFieldOfTargetType ; public static String MoveMethodConditionChecker_NoTarget ; public static String MoveMethodConditionChecker_TheMethod ; public static String MoveMethodRefactoring_Name ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . core . movemethod ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Locale ; import java . util . Map ; import java . util . Observable ; import java . util . Observer ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . SelfNode ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . DeleteEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . EditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . MultiFileEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; import org . rubypeople . rdt . refactoring . util . NameHelper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class MethodMover implements IMultiFileEditProvider , Observer { private MoveMethodConfig config ; private Collection < String > visibilitiesToDelete ; public MethodMover ( MoveMethodConfig config ) { this . config = config ; visibilitiesToDelete = new ArrayList < String > ( ) ; config . addObserver ( this ) ; initConfig ( ) ; } private void initConfig ( ) { boolean methodHasCallsToSourceClass = methodContainsReferencesToSourceClass ( ) ; config . setNewMethodNeedsReferenceToSourceClass ( methodHasCallsToSourceClass ) ; if ( methodHasCallsToSourceClass ) { initMovedMethodArgs ( ) ; } config . setSourceClassHasCallsToMovingMethod ( sourceClassContainsCallsToMovingMethod ( ) ) ; METHOD_VISIBILITY aktVisibility = config . getSourceClassNode ( ) . getMethodVisibility ( config . getMethodNode ( ) ) ; config . setMethodVisibility ( aktVisibility ) ; setMovedMethodVisibility ( ) ; config . setLeaveDelegateMethodInSource ( config . needsSecondPage ( ) ) ; } private void setMovedMethodVisibility ( ) { if ( config . doesSourceClassHasCallsToMovingMethod ( ) || config . leaveDelegateMethodInSource ( ) ) { config . setMovedMethodVisibility ( METHOD_VISIBILITY . PUBLIC ) ; } else { config . setMovedMethodVisibility ( config . getMethodVisibility ( ) ) ; } } private void initMovedMethodArgs ( ) { String className = config . getSourceClassNode ( ) . getName ( ) ; String newArgName = className . substring ( , ) . toLowerCase ( Locale . ENGLISH ) + className . substring ( ) ; while ( NameHelper . namesContainName ( config . getMethodNode ( ) . getLocalNames ( ) , newArgName ) ) { newArgName = NameHelper . createName ( newArgName ) ; } config . setFieldInDestinationClassOfTypeSourceClass ( newArgName ) ; ArgsNodeWrapper argsNode = config . getMethodNode ( ) . getArgsNode ( ) ; config . setMovedMethodArgs ( argsNode . cloneWithNewArgName ( newArgName ) ) ; } private boolean methodContainsReferencesToSourceClass ( ) { for ( MethodCallNodeWrapper aktCall : config . getMethodNode ( ) . getMethodCallNodes ( ) ) { if ( isCallToSourceClass ( aktCall ) ) { return true ; } } for ( FieldNodeWrapper aktFieldNode : NodeProvider . getFieldNodes ( config . getMethodNode ( ) . getWrappedNode ( ) ) ) { if ( aktFieldNode . isInstVar ( ) ) { return true ; } } return false ; } private boolean isCallToSourceClass ( MethodCallNodeWrapper callNode ) { if ( callNode . isCallToClassMethod ( ) ) { return false ; } boolean isReceiverSelf = callNode . isCallNode ( ) && NodeUtil . nodeAssignableFrom ( callNode . getReceiverNode ( ) , SelfNode . class ) ; boolean isNotCallNode = ! callNode . isCallNode ( ) ; boolean hasExistingMethodName = config . getSourceClassNode ( ) . containsMethod ( callNode . getName ( ) ) ; return ( isReceiverSelf || isNotCallNode ) && hasExistingMethodName ; } public Collection < FileMultiEditProvider > getFileEditProviders ( ) { MultiFileEditProvider multiFileEditProvider = new MultiFileEditProvider ( ) ; multiFileEditProvider . addEditProvider ( getInsertMethodInTargetClassProvider ( ) ) ; if ( config . leaveDelegateMethodInSource ( ) ) { multiFileEditProvider . addEditProvider ( getDelegateMethodEditProvider ( ) ) ; } else { multiFileEditProvider . addEditProvider ( getDeleteSelectedMethodEditProvider ( ) ) ; addDeleteVisibilityNodesOfMovingMethod ( multiFileEditProvider ) ; addUpdateReferencesInSourceClassEditProviders ( multiFileEditProvider ) ; } if ( config . doesNewMethodNeedsReferenceToSourceClass ( ) ) { addMethodVisibilityModifierEditProviders ( multiFileEditProvider ) ; addGenerateAccessorsEditProviders ( multiFileEditProvider ) ; } addDeleteMethodVisibilitiesEditProvider ( multiFileEditProvider ) ; return multiFileEditProvider . getFileEditProviders ( ) ; } private void addDeleteMethodVisibilitiesEditProvider ( MultiFileEditProvider multiFileEditProvider ) { for ( VisibilityNodeWrapper aktVisibilityNode : config . getSourceClassNode ( ) . getMethodVisibilityNodes ( ) ) { String fileName = aktVisibilityNode . getPosition ( ) . getFile ( ) ; RemovePartOfVisibilityNodeProvider editProvider = new RemovePartOfVisibilityNodeProvider ( aktVisibilityNode , visibilitiesToDelete ) ; if ( editProvider . shouldRemoveAll ( ) ) { multiFileEditProvider . addEditProvider ( new FileEditProvider ( fileName , new DeleteEditProvider ( aktVisibilityNode . getWrappedNode ( ) ) ) ) ; } else if ( editProvider . hasChange ( ) ) { multiFileEditProvider . addEditProvider ( new FileEditProvider ( fileName , editProvider ) ) ; } } } private void addDeleteVisibilityNodesOfMovingMethod ( MultiFileEditProvider multiFileEditProvider ) { VisibilityNodeWrapper visibilityNode = config . getSourceClassNode ( ) . getMethodVisibilityNode ( config . getMethodNode ( ) ) ; String fileName = config . getMethodNode ( ) . getPosition ( ) . getFile ( ) ; if ( visibilityNode == null ) { return ; } if ( visibilityNode . getMethodNames ( ) . size ( ) == ) { multiFileEditProvider . addEditProvider ( new FileEditProvider ( fileName , new DeleteEditProvider ( visibilityNode . getWrappedNode ( ) ) ) ) ; } else { visibilitiesToDelete . add ( config . getMethodNode ( ) . getName ( ) ) ; } } private void addGenerateAccessorsEditProviders ( MultiFileEditProvider multiFileEditProvider ) { Collection < AttrAccessorNodeWrapper > accessorsToCreate = getMissingAccessors ( ) ; String fileName = config . getDocumentProvider ( ) . getActiveFileName ( ) ; for ( AttrAccessorNodeWrapper aktAccessorNode : accessorsToCreate ) { EditProvider editProvider = new InsertAccessorEditProvider ( aktAccessorNode , config . getSourceClassNode ( ) ) ; multiFileEditProvider . addEditProvider ( new FileEditProvider ( fileName , editProvider ) ) ; } } private Collection < AttrAccessorNodeWrapper > getMissingAccessors ( ) { Collection < FieldNodeWrapper > fieldNodes = NodeProvider . getFieldNodes ( config . getMethodNode ( ) . getWrappedNode ( ) ) ; Collection < AttrAccessorNodeWrapper > existingAccessors = config . getSourceClassNode ( ) . getAccessorNodes ( ) ; Map < String , AttrAccessorNodeWrapper > accessorsToCreate = new LinkedHashMap < String , AttrAccessorNodeWrapper > ( ) ; String destClassField = config . getFieldInSourceClassOfTypeDestinationClass ( ) ; for ( FieldNodeWrapper aktFieldNode : fieldNodes ) { if ( ! aktFieldNode . getName ( ) . equals ( destClassField ) ) { addAccessorForField ( existingAccessors , accessorsToCreate , aktFieldNode ) ; } } return accessorsToCreate . values ( ) ; } private void addAccessorForField ( Collection < AttrAccessorNodeWrapper > existingAccessors , Map < String , AttrAccessorNodeWrapper > accessorsToCreate , FieldNodeWrapper fieldNode ) { AttrAccessorNodeWrapper accessorToInsert = getAccessor ( fieldNode ) ; if ( fieldNode . isInstVar ( ) && ! existsAccessor ( accessorToInsert , existingAccessors ) ) { if ( accessorsToCreate . containsKey ( fieldNode . getName ( ) ) ) { AttrAccessorNodeWrapper accessor = accessorsToCreate . get ( fieldNode . getName ( ) ) ; accessor . addAccessorType ( getAccessor ( fieldNode ) ) ; } else { accessorsToCreate . put ( fieldNode . getName ( ) , getAccessor ( fieldNode ) ) ; } } } private boolean existsAccessor ( AttrAccessorNodeWrapper accessorToInsert , Collection < AttrAccessorNodeWrapper > existingAccessors ) { for ( AttrAccessorNodeWrapper accessorNode : existingAccessors ) { if ( accessorNode . containsAccessor ( accessorToInsert ) ) { return true ; } } return false ; } private AttrAccessorNodeWrapper getAccessor ( final FieldNodeWrapper aktFieldNode ) { String accessorName ; if ( aktFieldNode . isAsgnNode ( ) ) { accessorName = AttrAccessorNodeWrapper . ATTR_WRITER ; } else { accessorName = AttrAccessorNodeWrapper . ATTR_READER ; } FCallNode fCallNode = NodeFactory . createFCallNode ( accessorName , new ArrayList < Node > ( ) ) ; return new AttrAccessorNodeWrapper ( fCallNode , NodeFactory . createSymboleNode ( aktFieldNode . getName ( ) ) ) ; } private void addUpdateReferencesInSourceClassEditProviders ( MultiFileEditProvider multiFileEditProvider ) { Collection < MethodCallNodeWrapper > methodCallsToMovingMethod = getMethodCallsToMovingMethodFromSourceClass ( ) ; for ( MethodCallNodeWrapper aktCall : methodCallsToMovingMethod ) { addReplaceMethodCallEditProvider ( aktCall , multiFileEditProvider ) ; } } private void addReplaceMethodCallEditProvider ( MethodCallNodeWrapper methodCall , MultiFileEditProvider multiFileEditProvider ) { String fileName = methodCall . getPosition ( ) . getFile ( ) ; EditProvider replaceEdit = new ReplaceMethodCallEditProvider ( methodCall , config ) ; multiFileEditProvider . addEditProvider ( new FileEditProvider ( fileName , replaceEdit ) ) ; } private void addMethodVisibilityModifierEditProviders ( MultiFileEditProvider multiFileEditProvider ) { Collection < MethodNodeWrapper > referencedMethod = getSourceClassMethodsReferencedInMovingMethod ( ) ; for ( MethodNodeWrapper aktMethod : referencedMethod ) { if ( ! config . getSourceClassNode ( ) . getMethodVisibility ( aktMethod ) . equals ( METHOD_VISIBILITY . PUBLIC ) ) { addMethodVisibilityModifierEditProvider ( aktMethod , multiFileEditProvider ) ; } } } private void addMethodVisibilityModifierEditProvider ( MethodNodeWrapper methodNode , MultiFileEditProvider multiFileEditProvider ) { VisibilityNodeWrapper visibilityNode = config . getSourceClassNode ( ) . getMethodVisibilityNode ( methodNode ) ; String fileName = methodNode . getWrappedNode ( ) . getPosition ( ) . getFile ( ) ; if ( visibilityNode == null ) { EditProvider insertEdit = new InsertVisibilityEditProvider ( methodNode , METHOD_VISIBILITY . PUBLIC ) ; multiFileEditProvider . addEditProvider ( new FileEditProvider ( fileName , insertEdit ) ) ; } else { if ( visibilityNode . getVisibility ( ) . equals ( METHOD_VISIBILITY . PUBLIC ) ) { return ; } if ( visibilityNode . getMethodNames ( ) . size ( ) == ) { EditProvider editProvider = new ReplaceVisibilityEditProvider ( visibilityNode , METHOD_VISIBILITY . PUBLIC ) ; multiFileEditProvider . addEditProvider ( new FileEditProvider ( fileName , editProvider ) ) ; } else { EditProvider insertEdit = new InsertVisibilityEditProvider ( methodNode , METHOD_VISIBILITY . PUBLIC ) ; multiFileEditProvider . addEditProvider ( new FileEditProvider ( fileName , insertEdit ) ) ; visibilitiesToDelete . add ( methodNode . getName ( ) ) ; } } } private Collection < MethodNodeWrapper > getSourceClassMethodsReferencedInMovingMethod ( ) { Collection < MethodCallNodeWrapper > calledMethods = config . getMethodNode ( ) . getMethodCallNodes ( ) ; Collection < MethodNodeWrapper > methods = new ArrayList < MethodNodeWrapper > ( ) ; for ( MethodCallNodeWrapper aktCall : calledMethods ) { if ( ! aktCall . isCallToClassMethod ( ) && ! aktCall . isCallNode ( ) && config . getSourceClassNode ( ) . containsMethod ( aktCall . getName ( ) ) ) { methods . add ( config . getSourceClassNode ( ) . getMethod ( aktCall . getName ( ) ) ) ; } } return methods ; } private FileEditProvider getDeleteSelectedMethodEditProvider ( ) { EditProvider deleteEditProvider = new DeleteEditProvider ( config . getMethodNode ( ) . getWrappedNode ( ) ) ; return new FileEditProvider ( config . getDocumentProvider ( ) . getActiveFileName ( ) , deleteEditProvider ) ; } private FileEditProvider getDelegateMethodEditProvider ( ) { EditProvider editProvider = new DelegateMethodEditProvider ( config ) ; return new FileEditProvider ( config . getDocumentProvider ( ) . getActiveFileName ( ) , editProvider ) ; } private FileEditProvider getInsertMethodInTargetClassProvider ( ) { PartialClassNodeWrapper insertClassPart = config . getDestinationClassNode ( ) . getPartialClassNodeForFileName ( config . getMethodNode ( ) . getPosition ( ) . getFile ( ) ) ; if ( insertClassPart == null ) { insertClassPart = config . getDestinationClassNode ( ) . getFirstPartialClassNode ( ) ; } InsertEditProvider insertEdit = new InsertMethodEditProvider ( config , insertClassPart ) ; return new FileEditProvider ( insertClassPart . getFile ( ) , insertEdit ) ; } private Collection < MethodCallNodeWrapper > getMethodCallsToMovingMethodFromSourceClass ( ) { Collection < MethodCallNodeWrapper > allMethodCalls = config . getSourceClassNode ( ) . getMethodCallNodes ( ) ; Collection < MethodCallNodeWrapper > methodCallsToMovingMethod = new ArrayList < MethodCallNodeWrapper > ( ) ; for ( MethodCallNodeWrapper aktCall : allMethodCalls ) { if ( isCallToMovingMethod ( aktCall ) ) { methodCallsToMovingMethod . add ( aktCall ) ; } } return methodCallsToMovingMethod ; } private boolean sourceClassContainsCallsToMovingMethod ( ) { Collection < MethodCallNodeWrapper > allMethodCalls = config . getSourceClassNode ( ) . getMethodCallNodes ( ) ; for ( MethodCallNodeWrapper aktCall : allMethodCalls ) { if ( isCallToMovingMethod ( aktCall ) && ! aktCall . isCallToClassMethod ( ) ) { return true ; } } return false ; } private boolean isCallToMovingMethod ( MethodCallNodeWrapper methodCall ) { String selectedMethodName = config . getMethodNode ( ) . getName ( ) ; boolean sameName = methodCall . getName ( ) . equals ( selectedMethodName ) ; boolean notInMovingMethod = ! SelectionNodeProvider . isNodeContainedInNode ( methodCall . getWrappedNode ( ) , config . getMethodNode ( ) . getWrappedNode ( ) ) ; boolean isNotCallNode = ! methodCall . isCallNode ( ) ; boolean isSelfNode = methodCall . isCallNode ( ) && NodeUtil . nodeAssignableFrom ( methodCall . getReceiverNode ( ) , SelfNode . class ) ; boolean sameType = config . getMethodNode ( ) . isClassMethod ( ) == methodCall . isCallToClassMethod ( ) ; return sameName && sameType && notInMovingMethod && ( isNotCallNode || isSelfNode || methodCall . isCallToClassMethod ( ) ) ; } public void update ( Observable arg0 , Object arg1 ) { setMovedMethodVisibility ( ) ; initWarnings ( ) ; } private void initWarnings ( ) { config . resetWarnings ( ) ; if ( config . doesNewMethodNeedsReferenceToSourceClass ( ) ) { for ( AttrAccessorNodeWrapper aktAccessorNode : getMissingAccessors ( ) ) { config . addWarning ( Messages . MethodMover_An + aktAccessorNode . getAccessorTypeName ( ) + Messages . MethodMover_ForField + aktAccessorNode . getAttrName ( ) + Messages . MethodMover_WillBeGenerated ) ; } } if ( config . doesNewMethodNeedsReferenceToSourceClass ( ) ) { for ( MethodNodeWrapper aktMethod : getSourceClassMethodsReferencedInMovingMethod ( ) ) { if ( ! config . getSourceClassNode ( ) . getMethodVisibility ( aktMethod ) . equals ( METHOD_VISIBILITY . PUBLIC ) ) { config . addWarning ( Messages . MethodMover_TheVisibilityOfMethod + aktMethod . getName ( ) + Messages . MethodMover_WillBeChangedToPublic ) ; } } } METHOD_VISIBILITY newVisibility = config . getMethodVisibility ( ) ; METHOD_VISIBILITY oldVisibility = config . getMethodVisibility ( ) ; if ( ! newVisibility . equals ( oldVisibility ) ) { String oldVisibilityName = VisibilityNodeWrapper . getVisibilityName ( oldVisibility ) ; String newVisibilityName = VisibilityNodeWrapper . getVisibilityName ( newVisibility ) ; config . addWarning ( Messages . MethodMover_TheVisibilityOfTheMovingMethod + config . getMethodNode ( ) . getName ( ) + Messages . MethodMover_IsChangedFrom + oldVisibilityName + Messages . MethodMover_To + newVisibilityName + '' ) ; } if ( ! config . getMethodNode ( ) . getName ( ) . equals ( config . getMovedMethodName ( ) ) ) { config . addWarning ( Messages . MethodMover_NameWillBeChangedTo + config . getMovedMethodName ( ) + Messages . MethodMover_DuToNameConflicts ) ; } } } package org . rubypeople . rdt . refactoring . core . movemethod ; import java . util . ArrayList ; import java . util . Collection ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . ReplaceEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; public class RemovePartOfVisibilityNodeProvider extends ReplaceEditProvider { private VisibilityNodeWrapper visibilityNode ; private Collection < String > methodNamesToDelete ; private Collection < String > remainingMethodNames ; public RemovePartOfVisibilityNodeProvider ( VisibilityNodeWrapper visibilityNode , Collection < String > methodNamesToDelete ) { this . visibilityNode = visibilityNode ; this . methodNamesToDelete = methodNamesToDelete ; initRemainingNames ( ) ; } private void initRemainingNames ( ) { remainingMethodNames = new ArrayList < String > ( visibilityNode . getMethodNames ( ) ) ; for ( String aktName : methodNamesToDelete ) { if ( remainingMethodNames . contains ( aktName ) ) { remainingMethodNames . remove ( aktName ) ; } } } @ Override protected int getOffsetLength ( ) { return visibilityNode . getPosition ( ) . getEndOffset ( ) - visibilityNode . getPosition ( ) . getStartOffset ( ) ; } @ Override protected Node getEditNode ( int offset , String document ) { METHOD_VISIBILITY visibility = visibilityNode . getVisibility ( ) ; return NodeFactory . createVisibilityNode ( visibility , remainingMethodNames . toArray ( new String [ remainingMethodNames . size ( ) ] ) ) ; } @ Override protected int getOffset ( String document ) { return visibilityNode . getPosition ( ) . getStartOffset ( ) ; } public boolean shouldRemoveAll ( ) { return remainingMethodNames . isEmpty ( ) ; } public boolean hasChange ( ) { return remainingMethodNames . size ( ) < visibilityNode . getMethodNames ( ) . size ( ) ; } } package org . rubypeople . rdt . refactoring . core . movemethod ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . offsetprovider . BeforeFirstMethodInClassOffsetProvider ; public class InsertAccessorEditProvider extends InsertEditProvider { private AttrAccessorNodeWrapper acccessorNode ; private ClassNodeWrapper classNode ; public InsertAccessorEditProvider ( AttrAccessorNodeWrapper acccessorNode , ClassNodeWrapper classNode ) { super ( true ) ; this . acccessorNode = acccessorNode ; this . classNode = classNode ; } @ Override protected Node getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = isNextLineEmpty ( offset , document ) ; Node accessorNode = NodeFactory . createAccessorNode ( acccessorNode ) ; return NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , accessorNode ) ; } @ Override protected int getOffset ( String document ) { return new BeforeFirstMethodInClassOffsetProvider ( classNode , document ) . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . movemethod ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashSet ; import java . util . TreeSet ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; public class MoveMethodConditionChecker extends RefactoringConditionChecker { private MoveMethodConfig config ; public MoveMethodConditionChecker ( MoveMethodConfig config ) { super ( config ) ; } @ Override public void init ( IRefactoringConfig configObj ) { this . config = ( MoveMethodConfig ) configObj ; Node rootNode = config . getDocumentProvider ( ) . getActiveFileRootNode ( ) ; int caretPos = config . getCaretPosition ( ) ; config . setAllClassesNodeProvider ( config . getDocumentProvider ( ) . getProjectClassNodeProvider ( ) ) ; try { ClassNodeWrapper selectedClassPart = SelectionNodeProvider . getSelectedClassNode ( rootNode , caretPos ) ; config . setSourceClassNode ( selectedClassPart . getName ( ) ) ; } catch ( NoClassNodeException e ) { } MethodDefNode methodDefNode = ( MethodDefNode ) SelectionNodeProvider . getSelectedNodeOfType ( rootNode , caretPos , MethodDefNode . class ) ; MethodNodeWrapper methodNode = ( methodDefNode == null ) ? null : new MethodNodeWrapper ( methodDefNode , config . getSourceClassNode ( ) ) ; config . setMethodNode ( methodNode ) ; initTargetClassNames ( ) ; if ( config . getSourceClassNode ( ) != null ) { initFieldInSourceClassOfTypeDestinationClassNames ( ) ; } } private void initTargetClassNames ( ) { Collection < ClassNodeWrapper > forbiddenClassNodes = new ArrayList < ClassNodeWrapper > ( ) ; forbiddenClassNodes . addAll ( config . getAllClassesNodeProvider ( ) . getClassAndAllSubClasses ( config . getSourceClassNode ( ) ) ) ; forbiddenClassNodes . addAll ( config . getAllClassesNodeProvider ( ) . getClassAndAllSuperClasses ( config . getSourceClassNode ( ) ) ) ; Collection < String > classNames = new TreeSet < String > ( ) ; for ( ClassNodeWrapper aktClassNode : config . getAllClassesNodeProvider ( ) . getAllClassNodes ( ) ) { if ( ! forbiddenClassNodes . contains ( aktClassNode ) ) { classNames . add ( aktClassNode . getName ( ) ) ; } } config . setTargetClassNames ( classNames ) ; } private void initFieldInSourceClassOfTypeDestinationClassNames ( ) { Collection < String > names = new LinkedHashSet < String > ( ) ; for ( FieldNodeWrapper aktField : config . getSourceClassNode ( ) . getFields ( ) ) { if ( aktField . getNodeType ( ) == FieldNodeWrapper . SYMBOL_NODE ) { names . add ( '' + aktField . getName ( ) ) ; } else if ( aktField . isInstVar ( ) ) { names . add ( aktField . getName ( ) ) ; } } config . setFieldInSourceClassOfTypeDestinationClassNames ( names ) ; } @ Override protected void checkInitialConditions ( ) { if ( config . getSourceClassNode ( ) == null ) { addError ( Messages . MoveMethodConditionChecker_NeedsToBeInsideClass ) ; } else if ( config . getMethodNode ( ) == null ) { addError ( Messages . MoveMethodConditionChecker_NeedsToBeInsideMethod ) ; } else if ( isConstructor ( ) ) { addError ( Messages . MoveMethodConditionChecker_CannotMoveConstructor ) ; } else if ( ! hasTargetClass ( ) ) { addError ( Messages . MoveMethodConditionChecker_NoTarget ) ; } else if ( ! hasFieldToSelect ( ) ) { addError ( Messages . MoveMethodConditionChecker_NoFieldOfTargetType ) ; } } private boolean hasFieldToSelect ( ) { return ! ( config . needsSecondPage ( ) && config . getFieldInSourceClassOfTypeDestinationClassNames ( ) . isEmpty ( ) ) ; } private boolean hasTargetClass ( ) { return ! config . getTargetClassNames ( ) . isEmpty ( ) ; } private boolean isConstructor ( ) { MethodNodeWrapper selectedMethod = config . getMethodNode ( ) ; return selectedMethod != null && selectedMethod . isConstructor ( ) ; } @ Override protected void checkFinalConditions ( ) { checkMethodContainsClassFields ( ) ; checkIsMethodPublicAndNoDelegateMethod ( ) ; addConfigWarnings ( ) ; } private void checkIsMethodPublicAndNoDelegateMethod ( ) { boolean isPrivate = config . getSourceClassNode ( ) . getMethodVisibility ( config . getMethodNode ( ) ) . equals ( METHOD_VISIBILITY . PRIVATE ) ; if ( ! isPrivate && ! config . leaveDelegateMethodInSource ( ) ) { addWarning ( Messages . MoveMethodConditionChecker_TheMethod + config . getMethodNode ( ) . getName ( ) + Messages . MoveMethodConditionChecker_CanBeCalledFromOutside + config . getSourceClassNode ( ) + Messages . MoveMethodConditionChecker_MightNotGetReplaced + config . getDestinationClassNode ( ) . getName ( ) + "" ) ; } } private void addConfigWarnings ( ) { for ( String aktWarning : config . getWarnings ( ) ) { addWarning ( aktWarning ) ; } } private void checkMethodContainsClassFields ( ) { for ( FieldNodeWrapper aktField : NodeProvider . getFieldNodes ( config . getMethodNode ( ) . getWrappedNode ( ) ) ) { if ( aktField . isClassVar ( ) ) { addWarning ( Messages . MoveMethodConditionChecker_TheMethod + config . getMethodNode ( ) . getName ( ) + Messages . MoveMethodConditionChecker_ContainsClassField + aktField . getName ( ) + Messages . MoveMethodConditionChecker_MovingMightAffectTheFunctionality + config . getSourceClassNode ( ) . getName ( ) + "" ) ; } } } } package org . rubypeople . rdt . refactoring . core . movemethod ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterNodeOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; public class InsertVisibilityEditProvider extends InsertEditProvider { private METHOD_VISIBILITY visibility ; private MethodNodeWrapper methodNode ; public InsertVisibilityEditProvider ( MethodNodeWrapper methodNode , METHOD_VISIBILITY visibility ) { super ( true ) ; this . methodNode = methodNode ; this . visibility = visibility ; } @ Override protected Node getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = ! isNextLineEmpty ( offset , document ) ; Node visibilityNode = NodeFactory . createVisibilityNode ( visibility , methodNode . getName ( ) ) ; return NodeFactory . createBlockNode ( false , needsNewLineAtEndOfBlock , visibilityNode ) ; } @ Override protected int getOffset ( String document ) { IOffsetProvider offsetProvider = new AfterNodeOffsetProvider ( methodNode . getWrappedNode ( ) , document ) ; return offsetProvider . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . movemethod ; import java . util . Collection ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . SelfNode ; import org . jruby . parser . LocalStaticScope ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . editprovider . InsertEditProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ArgsNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; import org . rubypeople . rdt . refactoring . offsetprovider . AfterLastMethodInClassOffsetProvider ; import org . rubypeople . rdt . refactoring . offsetprovider . IOffsetProvider ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class InsertMethodEditProvider extends InsertEditProvider { private MoveMethodConfig config ; private IOffsetProvider offsetProvider ; private PartialClassNodeWrapper classPart ; public InsertMethodEditProvider ( MoveMethodConfig config , PartialClassNodeWrapper classPart ) { super ( true ) ; this . config = config ; this . classPart = classPart ; } @ Override protected Node getInsertNode ( int offset , String document ) { boolean needsNewLineAtEndOfBlock = ! isNextLineEmpty ( offset , document ) ; Node insertMethodNode = NodeFactory . createNewLineNode ( getReferenceReplacedMethodNode ( document ) ) ; if ( ! config . getMethodNode ( ) . isClassMethod ( ) ) { METHOD_VISIBILITY aktVisibility = classPart . getPosVisibility ( offsetProvider . getOffset ( ) ) ; METHOD_VISIBILITY requiredVisibility = config . getMovedMethodVisibility ( ) ; if ( ! aktVisibility . equals ( requiredVisibility ) ) { Node visibilityNode = NodeFactory . createVisibilityNode ( requiredVisibility , config . getMovedMethodName ( ) ) ; return NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , new Node [ ] { insertMethodNode , visibilityNode } ) ; } } return NodeFactory . createBlockNode ( needsNewLineAtEndOfBlock , new Node [ ] { insertMethodNode } ) ; } private MethodDefNode getReferenceReplacedMethodNode ( String document ) { Node documentNode = NodeFactory . createNewLineNode ( config . getMethodNode ( ) . getWrappedNode ( ) ) ; String docStr = ReWriteVisitor . createCodeFromNode ( documentNode , document , getFormatHelper ( ) ) ; Document doc = new Document ( docStr ) ; try { getFieldInsertionEdit ( docStr ) . apply ( doc ) ; } catch ( MalformedTreeException e ) { e . printStackTrace ( ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } MethodDefNode methodNode = ( MethodDefNode ) NodeProvider . unwrap ( NodeProvider . getRootNode ( "" , doc . get ( ) ) . getBodyNode ( ) ) ; return createMethodNodeWithAdditionalArg ( methodNode ) ; } private MethodDefNode createMethodNodeWithAdditionalArg ( MethodDefNode methodNode ) { MethodDefNode resultMethod ; ArgsNodeWrapper args = config . getMovedMethodArgs ( ) ; if ( config . getMethodNode ( ) . isClassMethod ( ) ) { String destClassName = config . getDestinationClassNode ( ) . getName ( ) ; resultMethod = NodeFactory . createStaticMethodNode ( destClassName , config . getMovedMethodName ( ) , args . getWrappedNode ( ) , new LocalStaticScope ( null ) , methodNode . getBodyNode ( ) ) ; } else { resultMethod = NodeFactory . createMethodNodeWithoutNewline ( config . getMovedMethodName ( ) , args . getWrappedNode ( ) , methodNode . getBodyNode ( ) ) ; } resultMethod . addComments ( methodNode . getComments ( ) ) ; resultMethod . setPosition ( methodNode . getPosition ( ) ) ; return resultMethod ; } private TextEdit getFieldInsertionEdit ( String docStr ) { MultiTextEdit multiEdit = new MultiTextEdit ( ) ; Node rootNode = NodeProvider . getRootNode ( "" , docStr ) ; Collection < MethodCallNodeWrapper > callNodes = NodeProvider . getMethodCallNodes ( rootNode ) ; for ( MethodCallNodeWrapper aktCallNode : callNodes ) { addTextEditIfNeeded ( multiEdit , aktCallNode ) ; } Collection < FieldNodeWrapper > fieldNodes = NodeProvider . getFieldNodes ( rootNode ) ; for ( FieldNodeWrapper aktFieldNode : fieldNodes ) { addTextEditIfNeeded ( multiEdit , aktFieldNode ) ; } return multiEdit ; } private void addTextEditIfNeeded ( MultiTextEdit multiEdit , FieldNodeWrapper aktFieldNode ) { if ( aktFieldNode . getNodeType ( ) == FieldNodeWrapper . SYMBOL_NODE ) { return ; } if ( aktFieldNode . isInstVar ( ) ) { int insertPos = aktFieldNode . getPosition ( ) . getStartOffset ( ) ; int length ; String insertText ; if ( aktFieldNode . getName ( ) . equals ( config . getFieldInSourceClassOfTypeDestinationClass ( ) ) ) { insertText = "" ; length = aktFieldNode . getPosition ( ) . getEndOffset ( ) - insertPos ; } else { insertText = config . getFieldInDestinationClassOfTypeSourceClass ( ) + '' ; length = ; } try { multiEdit . addChild ( new ReplaceEdit ( insertPos , length , insertText ) ) ; } catch ( MalformedTreeException mte ) { } } } private void addTextEditIfNeeded ( MultiTextEdit multiEdit , MethodCallNodeWrapper aktCallNode ) { int insertPos = aktCallNode . getPosition ( ) . getStartOffset ( ) ; String insertText = config . getFieldInDestinationClassOfTypeSourceClass ( ) + "" ; if ( aktCallNode . isCallNode ( ) ) { Node receiverNode = aktCallNode . getReceiverNode ( ) ; if ( NodeUtil . nodeAssignableFrom ( receiverNode , SelfNode . class ) && ! isCallToMovingMethod ( aktCallNode . getName ( ) ) ) { int length = receiverNode . getPosition ( ) . getEndOffset ( ) - insertPos ; multiEdit . addChild ( new ReplaceEdit ( insertPos , length , config . getFieldInDestinationClassOfTypeSourceClass ( ) ) ) ; } } else if ( isCallToSourceClass ( aktCallNode . getName ( ) ) ) { multiEdit . addChild ( new InsertEdit ( insertPos , insertText ) ) ; } } private boolean isCallToMovingMethod ( String callName ) { return config . getMethodNode ( ) . getName ( ) . equals ( callName ) ; } private boolean isCallToSourceClass ( String callName ) { if ( isCallToMovingMethod ( callName ) ) { return false ; } Collection < MethodNodeWrapper > methodNodes = config . getSourceClassNode ( ) . getMethods ( ) ; for ( MethodNodeWrapper aktMethod : methodNodes ) { if ( aktMethod . getName ( ) . equals ( callName ) ) { return true ; } } return false ; } @ Override protected int getOffset ( String document ) { if ( offsetProvider == null ) { offsetProvider = new AfterLastMethodInClassOffsetProvider ( config . getDestinationClassNode ( ) , document ) ; } return offsetProvider . getOffset ( ) ; } } package org . rubypeople . rdt . refactoring . core . movemethod ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . ui . pages . movemethod . FirstMoveMethodPage ; import org . rubypeople . rdt . refactoring . ui . pages . movemethod . SecondMoveMethodPage ; public class MoveMethodRefactoring extends RubyRefactoring { public static final String NAME = Messages . MoveMethodRefactoring_Name ; public MoveMethodRefactoring ( IRefactoringContext selectionProvider ) { super ( NAME , selectionProvider ) ; MoveMethodConfig config = new MoveMethodConfig ( new DocumentWithIncluding ( getDocumentProvider ( ) ) , selectionProvider . getCaretPosition ( ) ) ; MoveMethodConditionChecker checker = new MoveMethodConditionChecker ( config ) ; setRefactoringConditionChecker ( checker ) ; if ( checker . shouldPerform ( ) ) { MethodMover mover = new MethodMover ( config ) ; setEditProvider ( mover ) ; pages . add ( new FirstMoveMethodPage ( config ) ) ; if ( config . needsSecondPage ( ) ) { SecondMoveMethodPage secondPage = new SecondMoveMethodPage ( config ) ; pages . add ( secondPage ) ; } } } } package org . rubypeople . rdt . refactoring . core ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . Comparator ; import java . util . Iterator ; import java . util . List ; import java . util . TreeSet ; import org . jruby . CompatVersion ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . CommentNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . WhileNode ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . parser . ParserConfiguration ; import org . jruby . util . KCode ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . parser . RubyParserWithComments ; import org . rubypeople . rdt . refactoring . nodewrapper . AttrAccessorNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class NodeProvider { private static final Class [ ] EMPTY_NODES = { NewlineNode . class , BlockNode . class , ArrayNode . class , ArgsNode . class , IterNode . class , WhileNode . class } ; public static Collection < Node > getChildren ( Node enclosingNode ) { Iterator < Node > it = enclosingNode . childNodes ( ) . iterator ( ) ; Collection < Node > children = new ArrayList < Node > ( ) ; while ( it . hasNext ( ) ) children . add ( it . next ( ) ) ; return children ; } public static boolean hasSyntaxErrors ( String fileName , String fileContent ) { try { parseFile ( fileName , fileContent ) ; return false ; } catch ( SyntaxException e ) { return true ; } } private static RootNode parseFile ( String fileName , String fileContent ) { RubyParser parser = new RubyParserWithComments ( ) { @ Override protected ParserConfiguration getParserConfig ( ) { return new ParserConfiguration ( KCode . NIL , , true , false , CompatVersion . RUBY1_8 ) ; } } ; return ( RootNode ) parser . parse ( fileName , fileContent , true ) . getAST ( ) ; } public static RootNode getRootNode ( String fileName , String fileContent ) { try { return ( fileContent != null ) ? parseFile ( fileName , fileContent ) : null ; } catch ( SyntaxException e ) { return null ; } } public static Collection < Node > getAttributeNodes ( Node parent ) { Collection < Node > attrNodes = getSubNodes ( parent , InstAsgnNode . class , InstVarNode . class ) ; attrNodes . addAll ( getAttrListNodes ( parent ) ) ; TreeSet < Node > attrNodesNoDuplicates = new TreeSet < Node > ( new Comparator < Node > ( ) { public int compare ( Node node0 , Node node1 ) { return getName ( node0 ) . compareTo ( getName ( node1 ) ) ; } private String getName ( Node node ) { return ( ( INameNode ) node ) . getName ( ) ; } } ) ; attrNodesNoDuplicates . addAll ( attrNodes ) ; return attrNodesNoDuplicates ; } private static Collection < Node > getAttrListNodes ( Node parent ) { Collection < Node > result = new ArrayList < Node > ( ) ; Collection < Node > fCallNodes = getSubNodes ( parent , FCallNode . class ) ; for ( Node node : fCallNodes ) { FCallNode fCallNode = ( FCallNode ) node ; if ( fCallNode . getName ( ) . equals ( "" ) ) { result . addAll ( getSubNodes ( fCallNode . getArgsNode ( ) , SymbolNode . class ) ) ; } } return result ; } public static Collection < AttrAccessorNodeWrapper > getAccessorNodes ( Node parent ) { Collection < Node > callNodes = getSubNodes ( parent , FCallNode . class ) ; Collection < AttrAccessorNodeWrapper > accessorNodes = new ArrayList < AttrAccessorNodeWrapper > ( ) ; for ( Node node : callNodes ) { FCallNode fCallNode = ( FCallNode ) node ; if ( isAccessorNode ( fCallNode ) ) { addAccessorNodes ( accessorNodes , fCallNode ) ; } } return accessorNodes ; } private static void addAccessorNodes ( Collection < AttrAccessorNodeWrapper > accessorNodes , FCallNode callNode ) { if ( NodeUtil . nodeAssignableFrom ( callNode . getArgsNode ( ) , ArrayNode . class ) ) { for ( Object o : callNode . getArgsNode ( ) . childNodes ( ) ) { Node aktNode = ( Node ) o ; if ( NodeUtil . nodeAssignableFrom ( aktNode , SymbolNode . class ) ) { SymbolNode symbolNode = ( ( SymbolNode ) aktNode ) ; accessorNodes . add ( new AttrAccessorNodeWrapper ( callNode , symbolNode ) ) ; } } } } public static boolean isAccessorNode ( FCallNode fCallNode ) { if ( ! hasAccessorName ( fCallNode ) ) { return false ; } if ( NodeUtil . nodeAssignableFrom ( fCallNode . getArgsNode ( ) , ArrayNode . class ) ) { ArrayNode arrayNode = ( ArrayNode ) fCallNode . getArgsNode ( ) ; for ( Object o : arrayNode . childNodes ( ) ) { Node aktNode = ( Node ) o ; if ( ! NodeUtil . nodeAssignableFrom ( aktNode , SymbolNode . class ) ) { return false ; } } } else { return false ; } return true ; } private static boolean hasAccessorName ( FCallNode callNode ) { String name = callNode . getName ( ) ; return ( name . equals ( AttrAccessorNodeWrapper . ATTR_ACCESSOR ) || name . equals ( AttrAccessorNodeWrapper . ATTR_READER ) || name . equals ( AttrAccessorNodeWrapper . ATTR_WRITER ) ) ; } public static Node getLastChildNode ( Node parent ) { return getLastChildNode ( parent , Node . class ) ; } public static Node getLastChildNode ( Node parent , Class < ? extends Node > childClass ) { Node lastMatch = null ; Collection < Node > childList = getChildren ( parent ) ; for ( Node o : childList ) { Node node = unwrap ( o ) ; if ( childClass . isAssignableFrom ( node . getClass ( ) ) ) lastMatch = node ; } return lastMatch ; } public static boolean hasChildNode ( Node parent , Class < ? extends Node > childClass ) { return getFirstChildNode ( parent , childClass ) != null ; } public static Node getFirstChildNode ( Node parent , Class < ? extends Node > childClass ) { Collection < Node > childList = getChildren ( parent ) ; for ( Node o : childList ) { Node node = unwrap ( o ) ; if ( childClass . isAssignableFrom ( node . getClass ( ) ) ) return node ; } return null ; } public static Node findParentNode ( Node rootNode , Node child ) { if ( child == null ) return null ; Collection < Node > allNodes = getAllNodes ( rootNode ) ; for ( Node node : allNodes ) { if ( containsNode ( node . childNodes ( ) , child ) ) { return node ; } } return null ; } public static Node findParentNode ( Node rootNode , Node child , Class type ) { while ( ( child = findParentNode ( rootNode , child ) ) != null && ! ( child instanceof RootNode ) ) { if ( child . getClass ( ) . isAssignableFrom ( type ) ) { return child ; } } return null ; } private static boolean containsNode ( List < Node > list , Node node ) { for ( Node child : list ) { if ( child . equals ( NilImplicitNode . NIL ) ) continue ; if ( child . getPosition ( ) . getStartOffset ( ) == node . getPosition ( ) . getStartOffset ( ) && child . getPosition ( ) . getEndOffset ( ) == node . getPosition ( ) . getEndOffset ( ) ) { return true ; } } return false ; } public static Node getNextNode ( Node parentNode , Node node ) { boolean match = false ; Collection < Node > childList = getChildren ( parentNode ) ; for ( Node o : childList ) { Node aktNode = unwrap ( o ) ; if ( match ) return aktNode ; if ( node . equals ( aktNode ) ) match = true ; } return null ; } public static Node getNodeBefore ( Node parentNode , Node node ) { Node nodeBefore = null ; Collection < Node > childList = getChildren ( parentNode ) ; for ( Node o : childList ) { Node aktNode = unwrap ( o ) ; if ( aktNode . equals ( node ) && ! ( aktNode instanceof CommentNode ) ) return nodeBefore ; else if ( ! ( aktNode instanceof CommentNode ) ) nodeBefore = aktNode ; } return null ; } public static Node unwrap ( Node node ) { if ( node instanceof NewlineNode ) node = ( ( NewlineNode ) node ) . getNextNode ( ) ; return node ; } public static boolean hasNodeBefore ( Node parentNode , Node node ) { return getNodeBefore ( parentNode , node ) != null ; } public static Collection < Node > getAllNodes ( Node parentNode ) { Collection < Node > allNodes = new ArrayList < Node > ( ) ; if ( parentNode != null ) { allNodes . add ( parentNode ) ; for ( Object o : parentNode . childNodes ( ) ) { Node node = ( Node ) o ; allNodes . addAll ( getAllNodes ( node ) ) ; } } return allNodes ; } public static Collection < MethodDefNode > getMethodNodes ( Node parentNode ) { Collection < Node > subNodes = getSubNodes ( parentNode , DefnNode . class , DefsNode . class ) ; return Arrays . asList ( subNodes . toArray ( new MethodDefNode [ subNodes . size ( ) ] ) ) ; } public static Collection < FCallNode > getLoadAndRequireNodes ( Node rootNode ) { Collection < FCallNode > loadAndRequireNodes = new ArrayList < FCallNode > ( ) ; Collection < Node > fCallNodes = NodeProvider . getSubNodes ( rootNode , FCallNode . class ) ; for ( Node node : fCallNodes ) { FCallNode fCallNode = ( FCallNode ) node ; if ( isLoadOrRequireNode ( fCallNode ) ) loadAndRequireNodes . add ( fCallNode ) ; } return loadAndRequireNodes ; } private static boolean isLoadOrRequireNode ( FCallNode fCallNode ) { return fCallNode . getName ( ) . equalsIgnoreCase ( "" ) || fCallNode . getName ( ) . equalsIgnoreCase ( "" ) ; } public static Collection < LocalAsgnNode > gatherLocalAsgnNodes ( Node baseNode ) { Collection < Node > nodes = gatherNodesOfTypeInAktScopeNode ( baseNode , LocalAsgnNode . class ) ; LocalAsgnNode [ ] asgnNodes = nodes . toArray ( new LocalAsgnNode [ nodes . size ( ) ] ) ; Collection < LocalAsgnNode > localAsgnNodes = Arrays . asList ( asgnNodes ) ; return localAsgnNodes ; } public static Collection < DAsgnNode > gatherLocalDAsgnNodes ( Node baseNode ) { Collection < Node > nodes = gatherNodesOfTypeInAktScopeNode ( baseNode , DAsgnNode . class ) ; Collection < DAsgnNode > dAsgnNodes = Arrays . asList ( nodes . toArray ( new DAsgnNode [ nodes . size ( ) ] ) ) ; return dAsgnNodes ; } public static Collection < Node > gatherNodesOfTypeInAktScopeNode ( Node baseNode , Class ... klasses ) { ArrayList < Node > candidates = new ArrayList < Node > ( ) ; if ( NodeUtil . nodeAssignableFrom ( baseNode , klasses ) ) { candidates . add ( baseNode ) ; } if ( baseNode != null && ! NodeUtil . hasScope ( baseNode ) ) { for ( Object o : baseNode . childNodes ( ) ) { Node n = ( Node ) o ; candidates . addAll ( gatherNodesOfTypeInAktScopeNode ( n , klasses ) ) ; } } return candidates ; } public static Collection < Node > getSubNodes ( Node baseNode , Class ... klasses ) { Collection < Node > allNodes = getAllNodes ( baseNode ) ; Collection < Node > resultNodes = new ArrayList < Node > ( ) ; for ( Node aktNode : allNodes ) { if ( NodeUtil . nodeAssignableFrom ( aktNode , klasses ) ) { resultNodes . add ( aktNode ) ; } } return resultNodes ; } public static boolean hasSubNodes ( Node baseNode , Class ... klasses ) { return ! getSubNodes ( baseNode , klasses ) . isEmpty ( ) ; } public static Node getEnclosingNodeOfType ( Node baseNode , Node enclosedNode , Class ... klasses ) { return SelectionNodeProvider . getSelectedNodeOfType ( baseNode , enclosedNode . getPosition ( ) . getStartOffset ( ) , klasses ) ; } public static Collection < MethodDefNode > gatherMethodDefinitionNodes ( Node enclosingScopeNode ) { Collection < Node > nodes = gatherNodesOfTypeInAktScopeNode ( enclosingScopeNode , DefnNode . class , DefsNode . class ) ; return Arrays . asList ( nodes . toArray ( new MethodDefNode [ nodes . size ( ) ] ) ) ; } public static Collection < Node > getInstFieldOccurences ( Node node ) { Collection < Node > allOccurences = getSubNodes ( node , InstAsgnNode . class , InstVarNode . class ) ; allOccurences . addAll ( getAttrListNodes ( node ) ) ; return allOccurences ; } public static Collection < Node > getClassFieldOccurences ( Node decoratedNode ) { return getSubNodes ( decoratedNode , ClassVarAsgnNode . class , ClassVarNode . class ) ; } public static boolean isEmptyNode ( Node node ) { if ( node == null ) { return true ; } if ( ! NodeUtil . nodeAssignableFrom ( node , EMPTY_NODES ) ) { return false ; } for ( Object o : node . childNodes ( ) ) { Node aktChild = ( Node ) o ; if ( ! isEmptyNode ( aktChild ) ) { return false ; } } return true ; } public static Collection < MethodCallNodeWrapper > getMethodCallNodes ( Node baseNode ) { Collection < Node > callNodes = getSubNodes ( baseNode , MethodCallNodeWrapper . METHOD_CALL_NODE_CLASSES ( ) ) ; Collection < MethodCallNodeWrapper > callNode = new ArrayList < MethodCallNodeWrapper > ( ) ; for ( Node aktCallNode : callNodes ) { callNode . add ( new MethodCallNodeWrapper ( aktCallNode ) ) ; } return callNode ; } public static Collection < FieldNodeWrapper > getFieldNodes ( Node baseNode ) { Collection < Node > fieldNodes = getSubNodes ( baseNode , FieldNodeWrapper . fieldNodeClasses ( ) ) ; Collection < FieldNodeWrapper > fields = new ArrayList < FieldNodeWrapper > ( ) ; for ( Node aktFieldNode : fieldNodes ) { fields . add ( new FieldNodeWrapper ( aktFieldNode ) ) ; } return fields ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . MergeWithExternalClassPartsRefactoring ; public class MergeClassPartsAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( MergeWithExternalClassPartsRefactoring . class , MergeWithExternalClassPartsRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodRefactoring ; public class MoveMethodAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( MoveMethodRefactoring . class , MoveMethodRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . overridemethod . OverrideMethodRefactoring ; public class OverrideMethodAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( OverrideMethodRefactoring . class , OverrideMethodRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . generateconstructor . GenerateConstructorRefactoring ; public class GenerateConstructorAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( GenerateConstructorRefactoring . class , GenerateConstructorRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . inlineclass . InlineClassRefactoring ; public class InlineClassAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( InlineClassRefactoring . class , InlineClassRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractMethodRefactoring ; public class ExtractMethodAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( ExtractMethodRefactoring . class , ExtractMethodRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . inlinelocal . InlineLocalRefactoring ; public class InlineTempAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( InlineLocalRefactoring . class , InlineLocalRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . EncapsulateFieldRefactoring ; public class EncapsulateFieldAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( EncapsulateFieldRefactoring . class , EncapsulateFieldRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . ConvertLocalToFieldRefactoring ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . EncapsulateFieldRefactoring ; import org . rubypeople . rdt . refactoring . core . extractconstant . ExtractConstantRefactoring ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractMethodRefactoring ; import org . rubypeople . rdt . refactoring . core . generateaccessors . GenerateAccessorsRefactoring ; import org . rubypeople . rdt . refactoring . core . generateconstructor . GenerateConstructorRefactoring ; import org . rubypeople . rdt . refactoring . core . inlineclass . InlineClassRefactoring ; import org . rubypeople . rdt . refactoring . core . inlinelocal . InlineLocalRefactoring ; import org . rubypeople . rdt . refactoring . core . inlinemethod . InlineMethodRefactoring ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . MergeClassPartsInFileRefactoring ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . MergeWithExternalClassPartsRefactoring ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldRefactoring ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodRefactoring ; import org . rubypeople . rdt . refactoring . core . overridemethod . OverrideMethodRefactoring ; import org . rubypeople . rdt . refactoring . core . pullup . PullUpRefactoring ; import org . rubypeople . rdt . refactoring . core . pushdown . PushDownRefactoring ; import org . rubypeople . rdt . refactoring . core . rename . RenameRefactoring ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitTempRefactoring ; import org . rubypeople . rdt . ui . actions . RubyActionGroup ; public class RefactoringActionGroup extends ActionGroup { public void fillContextMenu ( IMenuManager menu ) { IRefactoringContext selectionProvider = new RefactoringContext ( null ) ; IMenuManager source = menu . findMenuUsingPath ( RubyActionGroup . MENU_ID ) ; addSourceMenuItems ( source , selectionProvider ) ; menu . insertAfter ( RubyActionGroup . MENU_ID , getRefactorMenu ( selectionProvider ) ) ; } private IMenuManager getRefactorMenu ( IRefactoringContext selectionProvider ) { IMenuManager submenu = new MenuManager ( Messages . RefactoringActionGroup ) ; submenu . add ( new RefactoringAction ( ConvertLocalToFieldRefactoring . class , ConvertLocalToFieldRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( EncapsulateFieldRefactoring . class , EncapsulateFieldRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( ExtractMethodRefactoring . class , ExtractMethodRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( ExtractConstantRefactoring . class , ExtractConstantRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( InlineClassRefactoring . class , InlineClassRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( InlineLocalRefactoring . class , InlineLocalRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( InlineMethodRefactoring . class , InlineMethodRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( MergeClassPartsInFileRefactoring . class , MergeClassPartsInFileRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( MergeWithExternalClassPartsRefactoring . class , MergeWithExternalClassPartsRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( MoveFieldRefactoring . class , MoveFieldRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( MoveMethodRefactoring . class , MoveMethodRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( PushDownRefactoring . class , PushDownRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( PullUpRefactoring . class , PullUpRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( RenameRefactoring . class , RenameRefactoring . NAME , selectionProvider ) ) ; submenu . add ( new RefactoringAction ( SplitTempRefactoring . class , SplitTempRefactoring . NAME , selectionProvider ) ) ; return submenu ; } private void addSourceMenuItems ( IMenuManager source , IRefactoringContext selectionProvider ) { source . add ( new RefactoringAction ( GenerateAccessorsRefactoring . class , GenerateAccessorsRefactoring . NAME , selectionProvider ) ) ; source . add ( new RefactoringAction ( GenerateConstructorRefactoring . class , GenerateConstructorRefactoring . NAME , selectionProvider ) ) ; source . add ( new RefactoringAction ( OverrideMethodRefactoring . class , OverrideMethodRefactoring . NAME , selectionProvider ) ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . MergeWithExternalClassPartsRefactoring ; public class MergeWithExternalClassPartsAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( MergeWithExternalClassPartsRefactoring . class , MergeWithExternalClassPartsRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . IEditorActionDelegate ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; public abstract class WorkbenchWindowActionDelegate implements IWorkbenchWindowActionDelegate , IEditorActionDelegate { private IRefactoringContext selectionProvider ; abstract void run ( ) ; public void run ( IAction action ) { selectionProvider = new RefactoringContext ( action ) ; run ( ) ; } public void dispose ( ) { } public void init ( IWorkbenchWindow window ) { } public void selectionChanged ( IAction action , ISelection selection ) { } protected void run ( Class < ? extends RubyRefactoring > refactoringClass , String refactoringName ) { RefactoringAction delegateAction = new RefactoringAction ( refactoringClass , refactoringName , selectionProvider ) ; delegateAction . run ( ) ; } public void setActiveEditor ( IAction action , IEditorPart targetEditor ) { } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . formatsource . FormatSourceRefactoring ; public class FormatSourceAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( FormatSourceRefactoring . class , FormatSourceRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import java . lang . reflect . Constructor ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . jface . action . Action ; import org . eclipse . ltk . ui . refactoring . RefactoringWizardOpenOperation ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . ui . RubyRefactoringWizard ; public class RefactoringAction extends Action { private Class < ? extends RubyRefactoring > refactoringClass ; private IRefactoringContext selectionProvider ; private RubyRefactoring fRefactoring ; public RefactoringAction ( Class < ? extends RubyRefactoring > refactoringClass , String refactoringName , IRefactoringContext selectionProvider ) { setText ( refactoringName + "" ) ; this . refactoringClass = refactoringClass ; this . selectionProvider = selectionProvider ; } public void run ( ) { try { if ( PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . saveAllEditors ( true ) ) { RubyRefactoring refactoring = getRefactoring ( ) ; RubyRefactoringWizard wizard = new RubyRefactoringWizard ( refactoring ) ; wizard . setWindowTitle ( refactoring . getName ( ) ) ; RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation ( wizard ) ; Shell shell = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getShell ( ) ; op . run ( shell , refactoring . getName ( ) ) ; } } catch ( Exception e ) { RubyCore . log ( e ) ; } } private RubyRefactoring getRefactoring ( ) throws InstantiationException , IllegalAccessException , InvocationTargetException { if ( fRefactoring != null ) return fRefactoring ; Constructor constructor = refactoringClass . getConstructors ( ) [ ] ; Object [ ] args ; if ( constructor . getParameterTypes ( ) . length == ) { args = new Object [ ] { selectionProvider } ; } else { args = new Object [ ] ; } fRefactoring = ( RubyRefactoring ) constructor . newInstance ( args ) ; return fRefactoring ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . pullup . PullUpRefactoring ; public class PullUpAction extends WorkbenchWindowActionDelegate { public void run ( ) { run ( PullUpRefactoring . class , PullUpRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitTempRefactoring ; public class SplitTempAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( SplitTempRefactoring . class , SplitTempRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . MergeClassPartsInFileRefactoring ; public class MergeClassPartsInFileAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( MergeClassPartsInFileRefactoring . class , MergeClassPartsInFileRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . eclipse . osgi . util . NLS ; public class Messages extends NLS { private static final String BUNDLE_NAME = "" ; public static String RefactoringActionGroup ; public static String SourceActionGroup ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } private Messages ( ) { } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . internal . refactoring . RefactoringMessages ; import org . rubypeople . rdt . refactoring . core . extractconstant . ExtractConstantRefactoring ; public class ExtractConstantAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( ExtractConstantRefactoring . class , RefactoringMessages . ExtractConstantAction_label ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . pushdown . PushDownRefactoring ; public class PushDownAction extends WorkbenchWindowActionDelegate { public void run ( ) { run ( PushDownRefactoring . class , PushDownRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldRefactoring ; public class MoveFieldAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( MoveFieldRefactoring . class , MoveFieldRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . inlinemethod . InlineMethodRefactoring ; public class InlineMethodAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( InlineMethodRefactoring . class , InlineMethodRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . rename . RenameRefactoring ; public class RenameAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( RenameRefactoring . class , RenameRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . generateaccessors . GenerateAccessorsRefactoring ; public class GenerateAccessorsAction extends WorkbenchWindowActionDelegate { public void run ( ) { run ( GenerateAccessorsRefactoring . class , GenerateAccessorsRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . action ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . ConvertLocalToFieldRefactoring ; public class ConvertTempToFieldAction extends WorkbenchWindowActionDelegate { @ Override public void run ( ) { run ( ConvertLocalToFieldRefactoring . class , ConvertLocalToFieldRefactoring . NAME ) ; } } package org . rubypeople . rdt . refactoring . classnodeprovider ; import java . util . ArrayList ; import java . util . Collection ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . StrNode ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public class IncludedClassesProvider extends ClassNodeProvider { private String includingFileName ; private ArrayList < IPath > includeFilePaths ; public IncludedClassesProvider ( IDocumentProvider documentProvider ) { super ( documentProvider ) ; this . includingFileName = documentProvider . getActiveFileName ( ) ; prepareIncludedFileNames ( ) ; addIncludedFiles ( ) ; } public String getIncludingFileName ( ) { return includingFileName ; } public String getIncludingFileDocument ( ) { return documentProvider . getActiveFileContent ( ) ; } private void prepareIncludedFileNames ( ) { includeFilePaths = new ArrayList < IPath > ( ) ; Node rootNode = documentProvider . getActiveFileRootNode ( ) ; Collection < FCallNode > loadAndRequireNodes = NodeProvider . getLoadAndRequireNodes ( rootNode ) ; for ( FCallNode fCallNode : loadAndRequireNodes ) { addToIncludeFiles ( fCallNode . getArgsNode ( ) ) ; } } private void addToIncludeFiles ( Node node ) { if ( node instanceof ArrayNode ) { ArrayNode arrayNode = ( ArrayNode ) node ; for ( Object o : arrayNode . childNodes ( ) ) { if ( o instanceof StrNode ) { StrNode strNode = ( StrNode ) o ; appendPath ( strNode . getValue ( ) . toString ( ) ) ; } } } } private void appendPath ( String pathName ) { IPath path = new Path ( pathName ) ; if ( path . getFileExtension ( ) == null ) path = path . addFileExtension ( "" ) ; if ( ! path . getFileExtension ( ) . equalsIgnoreCase ( "" ) ) path = path . addFileExtension ( "" ) ; includeFilePaths . add ( path ) ; } private void addIncludedFiles ( ) { for ( IPath currentPath : includeFilePaths ) { String currentFileName = currentPath . toOSString ( ) ; super . addSource ( currentFileName ) ; } } public IDocumentProvider getDocumentProvider ( ) { return documentProvider ; } } package org . rubypeople . rdt . refactoring . classnodeprovider ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashMap ; import java . util . Map ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . SClassNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; public class ClassNodeProvider { private Map < String , ClassNodeWrapper > classNodeWrappers ; protected IDocumentProvider documentProvider ; public ClassNodeProvider ( IDocumentProvider docProvider ) { this ( docProvider , true ) ; } public ClassNodeProvider ( IDocumentProvider docProvider , boolean addActiveFile ) { classNodeWrappers = new LinkedHashMap < String , ClassNodeWrapper > ( ) ; this . documentProvider = docProvider ; if ( addActiveFile ) { addSource ( docProvider . getActiveFileName ( ) ) ; } } public void addSource ( String sourceName ) { Node rootNode = documentProvider . getRootNode ( sourceName ) ; createClassNodes ( rootNode ) ; } private void createClassNodes ( Node rootNode ) { if ( rootNode == null ) { return ; } Collection < Node > classNodes = NodeProvider . getSubNodes ( rootNode , ClassNode . class ) ; Collection < Node > moduleNodes = NodeProvider . getSubNodes ( rootNode , ModuleNode . class ) ; classNodes . addAll ( NodeProvider . getSubNodes ( rootNode , SClassNode . class ) ) ; for ( Node node : classNodes ) { try { PartialClassNodeWrapper partialClassNode = PartialClassNodeWrapper . getPartialClassNodeWrapper ( node , rootNode ) ; addEnclosingModules ( partialClassNode , moduleNodes ) ; addPartialClassNode ( partialClassNode , classNodeWrappers ) ; } catch ( NoClassNodeException e ) { e . printStackTrace ( ) ; } } } private void addEnclosingModules ( PartialClassNodeWrapper partialClassNode , Collection < Node > moduleNodes ) { ISourcePosition nodePosition = partialClassNode . getWrappedNode ( ) . getPosition ( ) ; ArrayList < ModuleNode > enclosingModules = new ArrayList < ModuleNode > ( ) ; for ( Node currentModule : moduleNodes ) { ISourcePosition modulePosition = currentModule . getPosition ( ) ; if ( modulePosition . getStartOffset ( ) < nodePosition . getStartOffset ( ) && modulePosition . getEndOffset ( ) > nodePosition . getEndOffset ( ) ) { enclosingModules . add ( ( ModuleNode ) currentModule ) ; } } partialClassNode . setEnclosingModules ( enclosingModules ) ; } private void addPartialClassNode ( PartialClassNodeWrapper partialClassNode , Map < String , ClassNodeWrapper > classes ) { String className = partialClassNode . getClassName ( ) ; if ( classes . containsKey ( className ) ) { ClassNodeWrapper classNode = classes . get ( className ) ; classNode . addPartialClassNode ( partialClassNode ) ; } else { ClassNodeWrapper classNode = new ClassNodeWrapper ( partialClassNode ) ; classes . put ( className , classNode ) ; } } public void addClassNodeProvider ( ClassNodeProvider provider ) { if ( provider != null ) { for ( ClassNodeWrapper classNode : provider . getAllClassNodes ( ) ) { if ( ! hasClassNode ( classNode . getName ( ) ) ) { classNodeWrappers . put ( classNode . getName ( ) , classNode ) ; } } } } public Collection < ClassNodeWrapper > getAllClassNodes ( ) { return classNodeWrappers . values ( ) ; } public ClassNodeWrapper getClassNode ( String className ) { return classNodeWrappers . containsKey ( className ) ? classNodeWrappers . get ( className ) : null ; } public boolean hasClassNode ( String className ) { return classNodeWrappers . containsKey ( className ) ; } public Collection < ClassNodeWrapper > getSubClassesOf ( String className ) { Collection < ClassNodeWrapper > childs = new ArrayList < ClassNodeWrapper > ( ) ; for ( ClassNodeWrapper classNode : getAllClassNodes ( ) ) { if ( classNode . getSuperClassName ( ) != null && classNode . getSuperClassName ( ) . equals ( className ) ) childs . add ( classNode ) ; } return childs ; } public Collection < MethodNodeWrapper > getAllMethodsFor ( String className ) { Collection < MethodNodeWrapper > methodNodes = new ArrayList < MethodNodeWrapper > ( ) ; for ( ClassNodeWrapper classNode : getClassAndAllSuperClassesFor ( className ) ) { methodNodes . addAll ( classNode . getMethods ( ) ) ; } return methodNodes ; } public Collection < ClassNodeWrapper > getClassAndAllSuperClassesFor ( String className ) { return getClassAndAllSuperClasses ( getClassNode ( className ) ) ; } public Collection < ClassNodeWrapper > getClassAndAllSuperClasses ( ClassNodeWrapper classNode ) { ArrayList < ClassNodeWrapper > classNodes = new ArrayList < ClassNodeWrapper > ( ) ; do { if ( classNode != null ) { classNodes . add ( classNode ) ; } } while ( classNode != null && ( classNode = getClassNode ( classNode . getSuperClassName ( ) ) ) != null ) ; return classNodes ; } public Collection < ClassNodeWrapper > getClassAndAllSubClasses ( ClassNodeWrapper classNode ) { Collection < ClassNodeWrapper > classes = new ArrayList < ClassNodeWrapper > ( ) ; if ( classNode == null ) { return classes ; } classes . add ( classNode ) ; for ( ClassNodeWrapper aktClassNode : getAllClassNodes ( ) ) { if ( classNode . getName ( ) . equals ( aktClassNode . getSuperClassName ( ) ) ) { classes . addAll ( getClassAndAllSubClasses ( aktClassNode ) ) ; } } return classes ; } public ClassNodeWrapper getSuperClassOf ( String className ) { for ( ClassNodeWrapper classNode : getAllClassNodes ( ) ) { if ( classNode . getName ( ) != null && classNode . getName ( ) . equals ( className ) ) return classNode ; } return null ; } } package org . rubypeople . rdt . refactoring . classnodeprovider ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; public class AllFilesClassNodeProvider extends ClassNodeProvider { public AllFilesClassNodeProvider ( IDocumentProvider docProvider ) { super ( docProvider , false ) ; for ( String fileName : docProvider . getFileNames ( ) ) { addSource ( fileName ) ; } } } package org . rubypeople . rdt . refactoring . exception ; public class NoClassNodeException extends Exception { private static final long serialVersionUID = ; } package org . rubypeople . rdt . refactoring . exception ; public class UnknownMethodNameException extends Exception { private static final long serialVersionUID = ; } package org . rubypeople . rdt . refactoring . exception ; public class UnknownReferenceException extends Exception { private static final long serialVersionUID = ; } package org . rubypeople . rdt . refactoring . exception ; public class UnknownClassNameException extends Exception { private static final long serialVersionUID = ; } package org . rubypeople . rdt . internal . ui . refactoring ; import org . eclipse . core . runtime . IAdapterFactory ; import org . eclipse . ltk . core . refactoring . TextEditBasedChange ; import org . eclipse . ltk . ui . refactoring . TextEditChangeNode ; import org . rubypeople . rdt . internal . corext . refactoring . changes . MultiStateRubyScriptChange ; import org . rubypeople . rdt . internal . corext . refactoring . changes . RubyScriptChange ; public class RefactoringAdapterFactory implements IAdapterFactory { private static final Class [ ] ADAPTER_LIST = new Class [ ] { TextEditChangeNode . class } ; public Class [ ] getAdapterList ( ) { return ADAPTER_LIST ; } public Object getAdapter ( Object object , Class key ) { if ( ! TextEditChangeNode . class . equals ( key ) ) return null ; if ( ! ( object instanceof RubyScriptChange ) && ! ( object instanceof MultiStateRubyScriptChange ) ) return null ; return new RubyScriptChangeNode ( ( TextEditBasedChange ) object ) ; } } package org . rubypeople . rdt . internal . ui . refactoring ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . ui . refactoring . ChangePreviewViewerInput ; import org . eclipse . ltk . ui . refactoring . IChangePreviewViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . rubypeople . rdt . internal . corext . refactoring . nls . changes . CreateTextFileChange ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . ViewerPane ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . RubySourceViewerConfiguration ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class CreateTextFileChangePreviewViewer implements IChangePreviewViewer { private ViewerPane fPane ; private SourceViewer fSourceViewer ; public void createControl ( Composite parent ) { fPane = new ViewerPane ( parent , SWT . BORDER | SWT . FLAT ) ; fSourceViewer = new SourceViewer ( fPane , null , SWT . V_SCROLL | SWT . H_SCROLL | SWT . MULTI | SWT . FULL_SELECTION ) ; fSourceViewer . setEditable ( false ) ; fSourceViewer . getControl ( ) . setFont ( JFaceResources . getFont ( PreferenceConstants . EDITOR_TEXT_FONT ) ) ; fPane . setContent ( fSourceViewer . getControl ( ) ) ; } public Control getControl ( ) { return fPane ; } public void setInput ( ChangePreviewViewerInput input ) { Change change = input . getChange ( ) ; if ( ! ( change instanceof CreateTextFileChange ) ) { fSourceViewer . setInput ( null ) ; fPane . setText ( "" ) ; return ; } CreateTextFileChange textFileChange = ( CreateTextFileChange ) change ; fPane . setText ( textFileChange . getName ( ) ) ; IDocument document = new Document ( textFileChange . getPreview ( ) ) ; fSourceViewer . unconfigure ( ) ; if ( "" . equals ( textFileChange . getTextType ( ) ) ) { RubyTextTools textTools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; textTools . setupRubyDocumentPartitioner ( document ) ; IPreferenceStore store = RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; fSourceViewer . configure ( new RubySourceViewerConfiguration ( textTools . getColorManager ( ) , store , null , null ) ) ; } else { fSourceViewer . configure ( new SourceViewerConfiguration ( ) ) ; } fSourceViewer . setInput ( document ) ; } public void refresh ( ) { fSourceViewer . refresh ( ) ; } } package org . rubypeople . rdt . internal . ui . refactoring ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . util . Assert ; import org . eclipse . ltk . core . refactoring . TextEditBasedChange ; import org . eclipse . ltk . core . refactoring . TextEditBasedChangeGroup ; import org . eclipse . ltk . ui . refactoring . LanguageElementNode ; import org . eclipse . ltk . ui . refactoring . TextEditChangeNode ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class RubyScriptChangeNode extends TextEditChangeNode { static final ChildNode [ ] EMPTY_CHILDREN = new ChildNode [ ] ; private static class RubyLanguageNode extends LanguageElementNode { private IRubyElement fRubyElement ; private static RubyElementImageProvider fgImageProvider = new RubyElementImageProvider ( ) ; public RubyLanguageNode ( TextEditChangeNode parent , IRubyElement element ) { super ( parent ) ; fRubyElement = element ; Assert . isNotNull ( fRubyElement ) ; } public RubyLanguageNode ( ChildNode parent , IRubyElement element ) { super ( parent ) ; fRubyElement = element ; Assert . isNotNull ( fRubyElement ) ; } public String getText ( ) { return RubyElementLabels . getElementLabel ( fRubyElement , RubyElementLabels . ALL_DEFAULT ) ; } public ImageDescriptor getImageDescriptor ( ) { return fgImageProvider . getRubyImageDescriptor ( fRubyElement , RubyElementImageProvider . OVERLAY_ICONS | RubyElementImageProvider . SMALL_ICONS ) ; } public IRegion getTextRange ( ) throws CoreException { ISourceRange range = ( ( ISourceReference ) fRubyElement ) . getSourceRange ( ) ; return new Region ( range . getOffset ( ) , range . getLength ( ) ) ; } } public RubyScriptChangeNode ( TextEditBasedChange change ) { super ( change ) ; } protected ChildNode [ ] createChildNodes ( ) { final TextEditBasedChange change = getTextEditBasedChange ( ) ; IRubyScript cunit = ( IRubyScript ) change . getAdapter ( IRubyScript . class ) ; if ( cunit != null ) { List children = new ArrayList ( ) ; Map map = new HashMap ( ) ; TextEditBasedChangeGroup [ ] changes = getSortedChangeGroups ( change ) ; for ( int i = ; i < changes . length ; i ++ ) { TextEditBasedChangeGroup tec = changes [ i ] ; try { IRubyElement element = getModifiedRubyElement ( tec , cunit ) ; if ( element . equals ( cunit ) ) { children . add ( createTextEditGroupNode ( this , tec ) ) ; } else { RubyLanguageNode pjce = getChangeElement ( map , element , children , this ) ; pjce . addChild ( createTextEditGroupNode ( pjce , tec ) ) ; } } catch ( RubyModelException e ) { children . add ( createTextEditGroupNode ( this , tec ) ) ; } } return ( ChildNode [ ] ) children . toArray ( new ChildNode [ children . size ( ) ] ) ; } else { return EMPTY_CHILDREN ; } } private static class OffsetComparator implements Comparator { public int compare ( Object o1 , Object o2 ) { TextEditBasedChangeGroup c1 = ( TextEditBasedChangeGroup ) o1 ; TextEditBasedChangeGroup c2 = ( TextEditBasedChangeGroup ) o2 ; int p1 = getOffset ( c1 ) ; int p2 = getOffset ( c2 ) ; if ( p1 < p2 ) return - ; if ( p1 > p2 ) return ; return ; } private int getOffset ( TextEditBasedChangeGroup edit ) { return edit . getRegion ( ) . getOffset ( ) ; } } private TextEditBasedChangeGroup [ ] getSortedChangeGroups ( TextEditBasedChange change ) { TextEditBasedChangeGroup [ ] edits = change . getChangeGroups ( ) ; List result = new ArrayList ( edits . length ) ; for ( int i = ; i < edits . length ; i ++ ) { if ( ! edits [ i ] . getTextEditGroup ( ) . isEmpty ( ) ) result . add ( edits [ i ] ) ; } Comparator comparator = new OffsetComparator ( ) ; Collections . sort ( result , comparator ) ; return ( TextEditBasedChangeGroup [ ] ) result . toArray ( new TextEditBasedChangeGroup [ result . size ( ) ] ) ; } private IRubyElement getModifiedRubyElement ( TextEditBasedChangeGroup edit , IRubyScript cunit ) throws RubyModelException { IRegion range = edit . getRegion ( ) ; if ( range . getOffset ( ) == && range . getLength ( ) == ) return cunit ; IRubyElement result = cunit . getElementAt ( range . getOffset ( ) ) ; if ( result == null ) return cunit ; try { while ( true ) { ISourceReference ref = ( ISourceReference ) result ; IRegion sRange = new Region ( ref . getSourceRange ( ) . getOffset ( ) , ref . getSourceRange ( ) . getLength ( ) ) ; if ( result . getElementType ( ) == IRubyElement . SCRIPT || result . getParent ( ) == null || coveredBy ( edit , sRange ) ) break ; result = result . getParent ( ) ; } } catch ( RubyModelException e ) { } catch ( ClassCastException e ) { } return result ; } private RubyLanguageNode getChangeElement ( Map map , IRubyElement element , List children , TextEditChangeNode cunitChange ) { RubyLanguageNode result = ( RubyLanguageNode ) map . get ( element ) ; if ( result != null ) return result ; IRubyElement parent = element . getParent ( ) ; if ( parent instanceof IRubyScript ) { result = new RubyLanguageNode ( cunitChange , element ) ; children . add ( result ) ; map . put ( element , result ) ; } else { RubyLanguageNode parentChange = getChangeElement ( map , parent , children , cunitChange ) ; result = new RubyLanguageNode ( parentChange , element ) ; parentChange . addChild ( result ) ; map . put ( element , result ) ; } return result ; } private boolean coveredBy ( TextEditBasedChangeGroup group , IRegion sourceRegion ) { int sLength = sourceRegion . getLength ( ) ; if ( sLength == ) return false ; int sOffset = sourceRegion . getOffset ( ) ; int sEnd = sOffset + sLength - ; TextEdit [ ] edits = group . getTextEdits ( ) ; for ( int i = ; i < edits . length ; i ++ ) { TextEdit edit = edits [ i ] ; if ( edit . isDeleted ( ) ) return false ; int rOffset = edit . getOffset ( ) ; int rLength = edit . getLength ( ) ; int rEnd = rOffset + rLength - ; if ( rLength == ) { if ( ! ( sOffset < rOffset && rOffset <= sEnd ) ) return false ; } else { if ( ! ( sOffset <= rOffset && rEnd <= sEnd ) ) return false ; } } return true ; } } package org . rubypeople . rdt . internal . refactoring ; import org . eclipse . osgi . util . NLS ; public class RefactoringMessages extends NLS { private static final String BUNDLE_NAME = RefactoringMessages . class . getName ( ) ; public static String Refactor ; public static String ExtractConstantAction_extract_constant ; public static String ExtractConstantAction_label ; public static String ExtractConstantInputPage_constant_name ; public static String ExtractConstantInputPage_enter_name ; public static String ExtractConstantInputPage_invalid_name ; public static String ExtractConstantInputPage_replace_all_occurrences ; public static String ExtractConstantWizard_defaultPageTitle ; public static String PullUpMethod_Wizard_title ; private RefactoringMessages ( ) { } static { NLS . initializeMessages ( BUNDLE_NAME , RefactoringMessages . class ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . nls ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; public class NLSUtil { private NLSUtil ( ) { } public static String readString ( InputStream is ) { if ( is == null ) return null ; BufferedReader reader = null ; try { StringBuffer buffer = new StringBuffer ( ) ; char [ ] part = new char [ ] ; int read = ; reader = new BufferedReader ( new InputStreamReader ( is , "" ) ) ; while ( ( read = reader . read ( part ) ) != - ) buffer . append ( part , , read ) ; return buffer . toString ( ) ; } catch ( IOException ex ) { } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException ex ) { } } } return null ; } } package org . rubypeople . rdt . internal . corext . refactoring . nls . changes ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . UnsupportedEncodingException ; import java . net . URI ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileInfo ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . refactoring . base . RDTChange ; import org . rubypeople . rdt . refactoring . core . Messages ; public class CreateFileChange extends RDTChange { private String fChangeName ; private IPath fPath ; private String fSource ; private String fEncoding ; private boolean fExplicitEncoding ; private long fStampToRestore ; public CreateFileChange ( IPath path , String source , String encoding ) { this ( path , source , encoding , IResource . NULL_STAMP ) ; } public CreateFileChange ( IPath path , String source , String encoding , long stampToRestore ) { Assert . isNotNull ( path , "" ) ; Assert . isNotNull ( source , "" ) ; fPath = path ; fSource = source ; fEncoding = encoding ; fExplicitEncoding = fEncoding != null ; fStampToRestore = stampToRestore ; } protected void setEncoding ( String encoding , boolean explicit ) { Assert . isNotNull ( encoding , "" ) ; fEncoding = encoding ; fExplicitEncoding = explicit ; } public String getName ( ) { if ( fChangeName == null ) return Messages . format ( Messages . createFile_Create_file , fPath . toOSString ( ) ) ; else return fChangeName ; } public void setName ( String name ) { fChangeName = name ; } protected void setSource ( String source ) { fSource = source ; } protected String getSource ( ) { return fSource ; } protected void setPath ( IPath path ) { fPath = path ; } protected IPath getPath ( ) { return fPath ; } public Object getModifiedElement ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( fPath ) ; } public RefactoringStatus isValid ( IProgressMonitor pm ) throws CoreException { RefactoringStatus result = new RefactoringStatus ( ) ; IFile file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( fPath ) ; URI location = file . getLocationURI ( ) ; if ( location == null ) { result . addFatalError ( Messages . format ( Messages . CreateFileChange_error_unknownLocation , file . getFullPath ( ) . toString ( ) ) ) ; return result ; } IFileInfo jFile = EFS . getStore ( location ) . fetchInfo ( ) ; if ( jFile . exists ( ) ) { result . addFatalError ( Messages . format ( Messages . CreateFileChange_error_exists , file . getFullPath ( ) . toString ( ) ) ) ; return result ; } return result ; } public Change perform ( IProgressMonitor pm ) throws CoreException { InputStream is = null ; try { pm . beginTask ( Messages . createFile_creating_resource , ) ; initializeEncoding ( ) ; IFile file = getOldFile ( new SubProgressMonitor ( pm , ) ) ; try { is = new ByteArrayInputStream ( fSource . getBytes ( fEncoding ) ) ; file . create ( is , false , new SubProgressMonitor ( pm , ) ) ; if ( fStampToRestore != IResource . NULL_STAMP ) { file . revertModificationStamp ( fStampToRestore ) ; } if ( fExplicitEncoding ) { file . setCharset ( fEncoding , new SubProgressMonitor ( pm , ) ) ; } else { pm . worked ( ) ; } return new DeleteFileChange ( file ) ; } catch ( UnsupportedEncodingException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } } finally { try { if ( is != null ) is . close ( ) ; } catch ( IOException ioe ) { throw new RubyModelException ( ioe , IRubyModelStatusConstants . IO_EXCEPTION ) ; } finally { pm . done ( ) ; } } } protected IFile getOldFile ( IProgressMonitor pm ) { pm . beginTask ( "" , ) ; try { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( fPath ) ; } finally { pm . done ( ) ; } } private void initializeEncoding ( ) { if ( fEncoding == null ) { fExplicitEncoding = false ; IFile file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( fPath ) ; if ( file != null ) { try { if ( file . exists ( ) ) { fEncoding = file . getCharset ( false ) ; if ( fEncoding == null ) { fEncoding = file . getCharset ( true ) ; } else { fExplicitEncoding = true ; } } else { fEncoding = file . getCharset ( true ) ; } } catch ( CoreException e ) { fEncoding = ResourcesPlugin . getEncoding ( ) ; fExplicitEncoding = true ; } } else { fEncoding = ResourcesPlugin . getEncoding ( ) ; fExplicitEncoding = true ; } } Assert . isNotNull ( fEncoding ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . nls . changes ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . refactoring . base . RDTChange ; import org . rubypeople . rdt . internal . corext . util . IOCloser ; import org . rubypeople . rdt . refactoring . core . Messages ; public class DeleteFileChange extends RDTChange { private IPath fPath ; private String fSource ; public DeleteFileChange ( IFile file ) { Assert . isNotNull ( file , "" ) ; fPath = file . getFullPath ( ) . removeFirstSegments ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFullPath ( ) . segmentCount ( ) ) ; } public RefactoringStatus isValid ( IProgressMonitor pm ) throws CoreException { return isValid ( pm , READ_ONLY | DIRTY ) ; } public Change perform ( IProgressMonitor pm ) throws CoreException { try { pm . beginTask ( Messages . deleteFile_deleting_resource , ) ; IFile file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( fPath ) ; Assert . isNotNull ( file ) ; Assert . isTrue ( file . exists ( ) ) ; Assert . isTrue ( ! file . isReadOnly ( ) ) ; fSource = getSource ( file ) ; CreateFileChange undo = createUndoChange ( file , fPath , file . getModificationStamp ( ) , fSource ) ; file . delete ( true , true , pm ) ; return undo ; } finally { pm . done ( ) ; } } private String getSource ( IFile file ) throws CoreException { String encoding = null ; try { encoding = file . getCharset ( ) ; } catch ( CoreException ex ) { } StringBuffer sb = new StringBuffer ( ) ; BufferedReader br = null ; InputStream in = null ; try { in = file . getContents ( ) ; if ( encoding != null ) br = new BufferedReader ( new InputStreamReader ( in , encoding ) ) ; else br = new BufferedReader ( new InputStreamReader ( in ) ) ; int read = ; while ( ( read = br . read ( ) ) != - ) sb . append ( ( char ) read ) ; } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } finally { try { IOCloser . rethrows ( br , in ) ; } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } } return sb . toString ( ) ; } private static CreateFileChange createUndoChange ( IFile file , IPath path , long stampToRestore , String source ) { String encoding ; try { encoding = file . getCharset ( false ) ; } catch ( CoreException e ) { encoding = null ; } return new CreateFileChange ( path , source , encoding , stampToRestore ) ; } public String getName ( ) { return Messages . deleteFile_Delete_File ; } public Object getModifiedElement ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( fPath ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . nls . changes ; import java . io . IOException ; import java . io . InputStream ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . refactoring . nls . NLSUtil ; public class CreateTextFileChange extends CreateFileChange { private final String fTextType ; public CreateTextFileChange ( IPath path , String source , String encoding , String textType ) { super ( path , source , encoding ) ; fTextType = textType ; } public String getTextType ( ) { return fTextType ; } public String getCurrentContent ( ) throws RubyModelException { IFile file = getOldFile ( new NullProgressMonitor ( ) ) ; if ( ! file . exists ( ) ) return "" ; InputStream stream = null ; try { stream = file . getContents ( ) ; String c = NLSUtil . readString ( stream ) ; return ( c == null ) ? "" : c ; } catch ( CoreException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . CORE_EXCEPTION ) ; } finally { try { if ( stream != null ) stream . close ( ) ; } catch ( IOException x ) { } } } public String getPreview ( ) { return getSource ( ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . base ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . filebuffers . FileBuffers ; import org . eclipse . core . filebuffers . ITextFileBuffer ; import org . eclipse . core . filebuffers . ITextFileBufferManager ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension4 ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . refactoring . core . Messages ; import org . rubypeople . rdt . refactoring . core . Resources ; public abstract class RDTChange extends Change { private long fModificationStamp ; private boolean fReadOnly ; private static class ValidationState { private IResource fResource ; private int fKind ; private boolean fDirty ; private boolean fReadOnly ; private long fModificationStamp ; private ITextFileBuffer fTextFileBuffer ; public static final int RESOURCE = ; public static final int DOCUMENT = ; public ValidationState ( IResource resource ) { fResource = resource ; if ( resource instanceof IFile ) { initializeFile ( ( IFile ) resource ) ; } else { initializeResource ( resource ) ; } } public void checkDirty ( RefactoringStatus status , long stampToMatch , IProgressMonitor pm ) throws CoreException { if ( fDirty ) { if ( fKind == DOCUMENT && fTextFileBuffer != null && stampToMatch == fModificationStamp ) { fTextFileBuffer . commit ( pm , false ) ; } else { status . addFatalError ( Messages . format ( Messages . Change_is_unsaved , fResource . getFullPath ( ) . toString ( ) ) ) ; } } } public void checkDirty ( RefactoringStatus status ) { if ( fDirty ) { status . addFatalError ( Messages . format ( Messages . Change_is_unsaved , fResource . getFullPath ( ) . toString ( ) ) ) ; } } public void checkReadOnly ( RefactoringStatus status ) { if ( fReadOnly ) { status . addFatalError ( Messages . format ( Messages . Change_is_read_only , fResource . getFullPath ( ) . toString ( ) ) ) ; } } public void checkSameReadOnly ( RefactoringStatus status , boolean valueToMatch ) { if ( fReadOnly != valueToMatch ) { status . addFatalError ( Messages . format ( Messages . Change_same_read_only , fResource . getFullPath ( ) . toString ( ) ) ) ; } } public void checkModificationStamp ( RefactoringStatus status , long stampToMatch ) { if ( fKind == DOCUMENT ) { if ( stampToMatch != IDocumentExtension4 . UNKNOWN_MODIFICATION_STAMP && fModificationStamp != stampToMatch ) { status . addFatalError ( Messages . format ( Messages . Change_has_modifications , fResource . getFullPath ( ) . toString ( ) ) ) ; } } else { if ( stampToMatch != IResource . NULL_STAMP && fModificationStamp != stampToMatch ) { status . addFatalError ( Messages . format ( Messages . Change_has_modifications , fResource . getFullPath ( ) . toString ( ) ) ) ; } } } private void initializeFile ( IFile file ) { fTextFileBuffer = getBuffer ( file ) ; if ( fTextFileBuffer == null ) { initializeResource ( file ) ; } else { IDocument document = fTextFileBuffer . getDocument ( ) ; fDirty = fTextFileBuffer . isDirty ( ) ; fReadOnly = Resources . isReadOnly ( file ) ; if ( document instanceof IDocumentExtension4 ) { fKind = DOCUMENT ; fModificationStamp = ( ( IDocumentExtension4 ) document ) . getModificationStamp ( ) ; } else { fKind = RESOURCE ; fModificationStamp = file . getModificationStamp ( ) ; } } } private void initializeResource ( IResource resource ) { fKind = RESOURCE ; fDirty = false ; fReadOnly = Resources . isReadOnly ( resource ) ; fModificationStamp = resource . getModificationStamp ( ) ; } } protected static final int NONE = ; protected static final int READ_ONLY = << ; protected static final int DIRTY = << ; private static final int SAVE = << ; protected static final int SAVE_IF_DIRTY = SAVE | DIRTY ; protected RDTChange ( ) { fModificationStamp = IResource . NULL_STAMP ; fReadOnly = false ; } public void initializeValidationData ( IProgressMonitor pm ) { IResource resource = getResource ( getModifiedElement ( ) ) ; if ( resource != null ) { fModificationStamp = getModificationStamp ( resource ) ; fReadOnly = Resources . isReadOnly ( resource ) ; } } protected final RefactoringStatus isValid ( IProgressMonitor pm , int flags ) throws CoreException { pm . beginTask ( "" , ) ; try { RefactoringStatus result = new RefactoringStatus ( ) ; Object modifiedElement = getModifiedElement ( ) ; checkExistence ( result , modifiedElement ) ; if ( result . hasFatalError ( ) ) return result ; if ( flags == NONE ) return result ; IResource resource = getResource ( modifiedElement ) ; if ( resource != null ) { ValidationState state = new ValidationState ( resource ) ; state . checkModificationStamp ( result , fModificationStamp ) ; if ( result . hasFatalError ( ) ) return result ; state . checkSameReadOnly ( result , fReadOnly ) ; if ( result . hasFatalError ( ) ) return result ; if ( ( flags & READ_ONLY ) != ) { state . checkReadOnly ( result ) ; if ( result . hasFatalError ( ) ) return result ; } if ( ( flags & DIRTY ) != ) { if ( ( flags & SAVE ) != ) { state . checkDirty ( result , fModificationStamp , new SubProgressMonitor ( pm , ) ) ; } else { state . checkDirty ( result ) ; } } } return result ; } finally { pm . done ( ) ; } } protected final RefactoringStatus isValid ( int flags ) throws CoreException { return isValid ( new NullProgressMonitor ( ) , flags ) ; } protected static void checkIfModifiable ( RefactoringStatus status , Object element , int flags ) { checkIfModifiable ( status , getResource ( element ) , flags ) ; } protected static void checkIfModifiable ( RefactoringStatus result , IResource resource , int flags ) { checkExistence ( result , resource ) ; if ( result . hasFatalError ( ) ) return ; if ( flags == NONE ) return ; ValidationState state = new ValidationState ( resource ) ; if ( ( flags & READ_ONLY ) != ) { state . checkReadOnly ( result ) ; if ( result . hasFatalError ( ) ) return ; } if ( ( flags & DIRTY ) != ) { state . checkDirty ( result ) ; } } protected static void checkExistence ( RefactoringStatus status , Object element ) { if ( element == null ) { status . addFatalError ( Messages . DynamicValidationStateChange_workspace_changed ) ; } else if ( element instanceof IResource && ! ( ( IResource ) element ) . exists ( ) ) { status . addFatalError ( Messages . format ( Messages . Change_does_not_exist , ( ( IResource ) element ) . getFullPath ( ) . toString ( ) ) ) ; } else if ( element instanceof IRubyElement && ! ( ( IRubyElement ) element ) . exists ( ) ) { status . addFatalError ( Messages . format ( Messages . Change_does_not_exist , ( ( IRubyElement ) element ) . getElementName ( ) ) ) ; } } private static IResource getResource ( Object element ) { if ( element instanceof IResource ) { return ( IResource ) element ; } if ( element instanceof IRubyElement ) { return ( ( IRubyElement ) element ) . getResource ( ) ; } if ( element instanceof IAdaptable ) { return ( IResource ) ( ( IAdaptable ) element ) . getAdapter ( IResource . class ) ; } return null ; } public String toString ( ) { return getName ( ) ; } public long getModificationStamp ( IResource resource ) { if ( ! ( resource instanceof IFile ) ) return resource . getModificationStamp ( ) ; IFile file = ( IFile ) resource ; ITextFileBuffer buffer = getBuffer ( file ) ; if ( buffer == null ) { return file . getModificationStamp ( ) ; } else { IDocument document = buffer . getDocument ( ) ; if ( document instanceof IDocumentExtension4 ) { return ( ( IDocumentExtension4 ) document ) . getModificationStamp ( ) ; } else { return file . getModificationStamp ( ) ; } } } private static ITextFileBuffer getBuffer ( IFile file ) { ITextFileBufferManager manager = FileBuffers . getTextFileBufferManager ( ) ; return manager . getTextFileBuffer ( file . getFullPath ( ) ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . changes ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . ChangeDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringChangeDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . rubypeople . rdt . internal . corext . refactoring . base . RDTChange ; import org . rubypeople . rdt . refactoring . core . Messages ; public final class RenameResourceChange extends RDTChange { public static IPath renamedResourcePath ( IPath path , String newName ) { return path . removeLastSegments ( ) . append ( newName ) ; } private final String fComment ; private final RefactoringDescriptor fDescriptor ; private final String fNewName ; private final IPath fResourcePath ; private final long fStampToRestore ; private RenameResourceChange ( RefactoringDescriptor descriptor , IPath resourcePath , String newName , String comment , long stampToRestore ) { fDescriptor = descriptor ; fResourcePath = resourcePath ; fNewName = newName ; fComment = comment ; fStampToRestore = stampToRestore ; } public RenameResourceChange ( RefactoringDescriptor descriptor , IResource resource , String newName , String comment ) { this ( descriptor , resource . getFullPath ( ) , newName , comment , IResource . NULL_STAMP ) ; } public ChangeDescriptor getDescriptor ( ) { if ( fDescriptor != null ) return new RefactoringChangeDescriptor ( fDescriptor ) ; return null ; } public Object getModifiedElement ( ) { return getResource ( ) ; } public String getName ( ) { return Messages . format ( Messages . RenameResourceChange_name , new String [ ] { fResourcePath . toString ( ) , fNewName } ) ; } public String getNewName ( ) { return fNewName ; } private IResource getResource ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( fResourcePath ) ; } public RefactoringStatus isValid ( IProgressMonitor pm ) throws CoreException { IResource resource = getResource ( ) ; if ( resource == null || ! resource . exists ( ) ) { return RefactoringStatus . createFatalErrorStatus ( Messages . format ( Messages . RenameResourceChange_does_not_exist , fResourcePath . toString ( ) ) ) ; } else { return super . isValid ( pm , DIRTY ) ; } } public Change perform ( IProgressMonitor pm ) throws CoreException { try { pm . beginTask ( Messages . RenameResourceChange_rename_resource , ) ; IResource resource = getResource ( ) ; long currentStamp = resource . getModificationStamp ( ) ; IPath newPath = renamedResourcePath ( fResourcePath , fNewName ) ; resource . move ( newPath , IResource . SHALLOW , pm ) ; if ( fStampToRestore != IResource . NULL_STAMP ) { IResource newResource = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( newPath ) ; newResource . revertModificationStamp ( fStampToRestore ) ; } String oldName = fResourcePath . lastSegment ( ) ; return new RenameResourceChange ( null , newPath , oldName , fComment , currentStamp ) ; } finally { pm . done ( ) ; } } } package org . rubypeople . rdt . internal . corext . refactoring . changes ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . ltk . core . refactoring . MultiStateTextFileChange ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . refactoring . core . Messages ; public final class MultiStateRubyScriptChange extends MultiStateTextFileChange { private final IRubyScript fUnit ; public MultiStateRubyScriptChange ( final String name , final IRubyScript unit ) { super ( name , ( IFile ) unit . getResource ( ) ) ; fUnit = unit ; setTextType ( "" ) ; } public final Object getAdapter ( final Class adapter ) { if ( IRubyScript . class . equals ( adapter ) ) return fUnit ; return super . getAdapter ( adapter ) ; } public final IRubyScript getRubyScript ( ) { return fUnit ; } public String getName ( ) { return Messages . format ( Messages . MultiStateRubyScriptChange_name_pattern , new String [ ] { fUnit . getElementName ( ) , getPath ( fUnit . getResource ( ) ) } ) ; } private String getPath ( IResource resource ) { final StringBuffer buffer = new StringBuffer ( resource . getProject ( ) . getName ( ) ) ; final String path = resource . getParent ( ) . getProjectRelativePath ( ) . toString ( ) ; if ( path . length ( ) > ) { buffer . append ( '' ) ; buffer . append ( path ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . changes ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . corext . refactoring . nls . changes . CreateTextFileChange ; import org . rubypeople . rdt . refactoring . core . Messages ; public class CreateRubyScriptChange extends CreateTextFileChange { private final IRubyScript fUnit ; public CreateRubyScriptChange ( IRubyScript unit , String source , String encoding ) { super ( unit . getResource ( ) . getFullPath ( ) , source , encoding , "" ) ; fUnit = unit ; } public String getName ( ) { return Messages . format ( Messages . RubyScriptChange_label , new String [ ] { fUnit . getElementName ( ) , getPath ( fUnit . getResource ( ) ) } ) ; } private String getPath ( IResource resource ) { final StringBuffer buffer = new StringBuffer ( resource . getProject ( ) . getName ( ) ) ; final String path = resource . getParent ( ) . getProjectRelativePath ( ) . toString ( ) ; if ( path . length ( ) > ) { buffer . append ( '' ) ; buffer . append ( path ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . corext . util ; import java . io . IOException ; import java . io . InputStream ; import java . io . Reader ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class IOCloser { public static void perform ( Reader reader , InputStream stream ) { try { rethrows ( reader , stream ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } } public static void rethrows ( Reader reader , InputStream stream ) throws IOException { if ( reader != null ) { reader . close ( ) ; return ; } if ( stream != null ) { stream . close ( ) ; return ; } } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; public class RubyUIStatus extends Status { private RubyUIStatus ( int severity , int code , String message , Throwable throwable ) { super ( severity , RubyPlugin . getPluginId ( ) , code , message , throwable ) ; } public static IStatus createError ( int code , Throwable throwable ) { String message = throwable . getMessage ( ) ; if ( message == null ) { message = throwable . getClass ( ) . getName ( ) ; } return new RubyUIStatus ( IStatus . ERROR , code , message , throwable ) ; } public static IStatus createError ( int code , String message , Throwable throwable ) { return new RubyUIStatus ( IStatus . ERROR , code , message , throwable ) ; } public static IStatus createWarning ( int code , String message , Throwable throwable ) { return new RubyUIStatus ( IStatus . WARNING , code , message , throwable ) ; } public static IStatus createInfo ( int code , String message , Throwable throwable ) { return new RubyUIStatus ( IStatus . INFO , code , message , throwable ) ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import org . rubypeople . rdt . internal . ui . wizards . InstallStandardRubyWizard ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RubyInstalledDetector extends UIJob { private static boolean fgFinished ; public RubyInstalledDetector ( ) { super ( "" ) ; } private boolean usingIncludedJRuby ( ) { Preferences store = LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) ; if ( store == null ) return false ; return store . getBoolean ( LaunchingPlugin . USING_INCLUDED_JRUBY ) ; } private boolean rubyInstalled ( ) { return ! rubyNotInstalled ( ) ; } private boolean rubyNotInstalled ( ) { IVMInstall [ ] cRubyInstalls = RubyRuntime . getVMInstallType ( IRubyLaunchConfigurationConstants . ID_STANDARD_VM_TYPE ) . getVMInstalls ( ) ; return cRubyInstalls == null || cRubyInstalls . length == ; } @ Override public IStatus runInUIThread ( IProgressMonitor monitor ) { if ( rubyInstalled ( ) || usingIncludedJRuby ( ) ) { markFinished ( ) ; return Status . CANCEL_STATUS ; } IWorkbench workbench = PlatformUI . getWorkbench ( ) ; InstallStandardRubyWizard wizard = new InstallStandardRubyWizard ( ) ; wizard . init ( workbench , null ) ; WizardDialog dialog = new WizardDialog ( workbench . getDisplay ( ) . getActiveShell ( ) , wizard ) ; dialog . open ( ) ; monitor . done ( ) ; return Status . OK_STATUS ; } public static void markFinished ( ) { fgFinished = true ; } public static boolean isFinished ( ) { return fgFinished ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . ui . IContainmentAdapter ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . RubyCore ; public class RubyElementContainmentAdapter implements IContainmentAdapter { private IRubyModel fRubyModel = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; public boolean contains ( Object workingSetElement , Object element , int flags ) { if ( ! ( workingSetElement instanceof IRubyElement ) || element == null ) return false ; IRubyElement workingSetRubyElement = ( IRubyElement ) workingSetElement ; IResource resource = null ; IRubyElement jElement = null ; if ( element instanceof IRubyElement ) { jElement = ( IRubyElement ) element ; resource = jElement . getResource ( ) ; } else { if ( element instanceof IAdaptable ) { resource = ( IResource ) ( ( IAdaptable ) element ) . getAdapter ( IResource . class ) ; if ( resource != null ) { if ( fRubyModel . contains ( resource ) ) { jElement = RubyCore . create ( resource ) ; if ( jElement != null && ! jElement . exists ( ) ) jElement = null ; } } } } if ( jElement != null ) { if ( contains ( workingSetRubyElement , jElement , flags ) ) return true ; if ( workingSetRubyElement . getElementType ( ) == IRubyElement . SOURCE_FOLDER && resource . getType ( ) == IResource . FOLDER && checkIfDescendant ( flags ) ) return isChild ( workingSetRubyElement , resource ) ; } else if ( resource != null ) { return contains ( workingSetRubyElement , resource , flags ) ; } return false ; } private boolean contains ( IRubyElement workingSetElement , IRubyElement element , int flags ) { if ( checkContext ( flags ) && workingSetElement . equals ( element ) ) { return true ; } if ( checkIfChild ( flags ) && workingSetElement . equals ( element . getParent ( ) ) ) { return true ; } if ( checkIfDescendant ( flags ) && check ( workingSetElement , element ) ) { return true ; } if ( checkIfAncestor ( flags ) && check ( element , workingSetElement ) ) { return true ; } return false ; } private boolean check ( IRubyElement ancestor , IRubyElement descendent ) { descendent = descendent . getParent ( ) ; while ( descendent != null ) { if ( ancestor . equals ( descendent ) ) return true ; descendent = descendent . getParent ( ) ; } return false ; } private boolean isChild ( IRubyElement workingSetElement , IResource element ) { IResource resource = workingSetElement . getResource ( ) ; if ( resource == null ) return false ; return check ( element , resource ) ; } private boolean contains ( IRubyElement workingSetElement , IResource element , int flags ) { IResource workingSetResource = workingSetElement . getResource ( ) ; if ( workingSetResource == null ) return false ; if ( checkContext ( flags ) && workingSetResource . equals ( element ) ) { return true ; } if ( checkIfChild ( flags ) && workingSetResource . equals ( element . getParent ( ) ) ) { return true ; } if ( checkIfDescendant ( flags ) && check ( workingSetResource , element ) ) { return true ; } if ( checkIfAncestor ( flags ) && check ( element , workingSetResource ) ) { return true ; } return false ; } private boolean check ( IResource ancestor , IResource descendent ) { descendent = descendent . getParent ( ) ; while ( descendent != null ) { if ( ancestor . equals ( descendent ) ) return true ; descendent = descendent . getParent ( ) ; } return false ; } private boolean checkIfDescendant ( int flags ) { return ( flags & CHECK_IF_DESCENDANT ) != ; } private boolean checkIfAncestor ( int flags ) { return ( flags & CHECK_IF_ANCESTOR ) != ; } private boolean checkIfChild ( int flags ) { return ( flags & CHECK_IF_CHILD ) != ; } private boolean checkContext ( int flags ) { return ( flags & CHECK_CONTEXT ) != ; } } package org . rubypeople . rdt . internal . ui ; import java . net . URL ; import java . util . HashMap ; import java . util . Iterator ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . resource . ImageRegistry ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . ImageData ; import org . osgi . framework . Bundle ; public class RubyPluginImages { protected static final String NAME_PREFIX = "" ; protected static final int NAME_PREFIX_LENGTH = NAME_PREFIX . length ( ) ; public static final IPath ICONS_PATH = new Path ( "" ) ; private static ImageRegistry fgImageRegistry = null ; private static HashMap fgAvoidSWTErrorMap = null ; private static final String T_OBJ = "" ; private static final String T_OVR = "" ; private static final String T_ELCL = "" ; private static final String T_DLCL = "" ; private static final String T_CTOOL = "" ; private static final String T_WIZBAN = "" ; private static final String T_ETOOL = "" ; public static final String IMG_MISC_PUBLIC = NAME_PREFIX + "" ; public static final String IMG_MISC_PROTECTED = NAME_PREFIX + "" ; public static final String IMG_MISC_PRIVATE = NAME_PREFIX + "" ; public static final String IMG_OBJS_ERROR = NAME_PREFIX + "" ; public static final String IMG_OBJS_WARNING = NAME_PREFIX + "" ; public static final String IMG_OBJS_INFO = NAME_PREFIX + "" ; public static final String IMG_OBJS_HELP = NAME_PREFIX + "" ; public static final String IMG_OBJS_LIGHTBULB = NAME_PREFIX + "" ; private static final String IMG_OBJS_GHOST = NAME_PREFIX + "" ; public static final String IMG_OBJS_SEARCH_DECL = NAME_PREFIX + "" ; public static final String IMG_OBJS_SEARCH_REF = NAME_PREFIX + "" ; public static final String IMG_OBJS_CLASS = NAME_PREFIX + "" ; private static final String IMG_OBJS_INNER_CLASS = NAME_PREFIX + "" ; private static final String IMG_OBJS_CLASSALT = NAME_PREFIX + "" ; public static final String IMG_OBJS_MODULE = NAME_PREFIX + "" ; private static final String IMG_OBJS_MODULEALT = NAME_PREFIX + "" ; private static final String IMG_OBJS_RUBY_MODEL = NAME_PREFIX + "" ; public static final String IMG_OBJS_SOURCE_FOLDER = NAME_PREFIX + "" ; public static final String IMG_OBJS_SOURCE_FOLDER_ROOT = NAME_PREFIX + "" ; private static final String IMG_OBJS_SCRIPT = NAME_PREFIX + "" ; private static final String IMG_OBJS_ERB_SCRIPT = NAME_PREFIX + "" ; private static final String IMG_OBJS_RUBY_RESOURCE = NAME_PREFIX + "" ; private static final String IMG_OBJS_UNKNOWN = NAME_PREFIX + "" ; public static final String IMG_OBJS_ENV_VAR = NAME_PREFIX + "" ; public static final String IMG_OBJS_LIBRARY = NAME_PREFIX + "" ; public static final String IMG_OBJS_EXTJAR = NAME_PREFIX + "" ; public static final String IMG_OBJS_EXTJAR_WSRC = NAME_PREFIX + "" ; public static final String IMG_OBJS_CORRECTION_CHANGE = NAME_PREFIX + "" ; public static final String IMG_OBJS_SEARCH_READACCESS = NAME_PREFIX + "" ; public static final String IMG_OBJS_SEARCH_WRITEACCESS = NAME_PREFIX + "" ; public static final String IMG_OBJS_SEARCH_OCCURRENCE = NAME_PREFIX + "" ; public static final String IMG_ELCL_VIEW_MENU = NAME_PREFIX + T_ELCL + "" ; public static final String IMG_DLCL_VIEW_MENU = NAME_PREFIX + T_DLCL + "" ; private static final String IMG_CTOOLS_RUBY_IMPORT_CONTAINER = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_IMPORT = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_BLOCK = NAME_PREFIX + "" ; public static final String IMG_OBJS_TEMPLATE = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_LOCAL_VAR = NAME_PREFIX + "" ; public static final String IMG_CTOOLS_RUBY_PAGE = NAME_PREFIX + "" ; public static final String IMG_CTOOLS_RUBY = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_GLOBAL = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_CLASS = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_SINGLETONMETHOD = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_SINGLETONMETHOD_PUB = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_SINGLETONMETHOD_PRO = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_CLASS_VAR = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_INSTANCE_VAR = NAME_PREFIX + "" ; private static final String IMG_CTOOLS_RUBY_CONSTANT = NAME_PREFIX + "" ; public static final String IMG_OBJS_QUICK_ASSIST = NAME_PREFIX + "" ; public static final String IMG_OBJS_FIXABLE_PROBLEM = NAME_PREFIX + "" ; public static final String IMG_OBJS_FIXABLE_ERROR = NAME_PREFIX + "" ; public static final ImageDescriptor DESC_WIZBAN_NEWJPRJ = createUnManaged ( T_WIZBAN , "" ) ; public static final ImageDescriptor DESC_WIZBAN_NEWCLASS = createUnManaged ( T_WIZBAN , "" ) ; public static final ImageDescriptor DESC_WIZBAN_NEWFILE = createUnManaged ( T_WIZBAN , "" ) ; public static final ImageDescriptor DESC_WIZBAN_NEWSRCFOLDR = createUnManaged ( T_WIZBAN , "" ) ; public static final ImageDescriptor DESC_WIZBAN_ADD_LIBRARY = createUnManaged ( T_WIZBAN , "" ) ; public static final ImageDescriptor DESC_WIZBAN_RUBY_WORKINGSET = createUnManaged ( T_WIZBAN , "" ) ; public static final ImageDescriptor TOOLBAR_REFRESH = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_OBJS_TYPE_SEPARATOR = createUnManaged ( T_OBJ , "" ) ; public static final ImageDescriptor DESC_OBJS_HELP = createManagedFromKey ( T_ELCL , IMG_OBJS_HELP ) ; public static final ImageDescriptor DESC_OBJS_LIGHTBULB = createManagedFromKey ( T_OBJ , IMG_OBJS_LIGHTBULB ) ; public static final ImageDescriptor DESC_OBJ_OVERRIDES = createUnManaged ( T_OBJ , "" ) ; public static final ImageDescriptor DESC_OBJ_IMPLEMENTS = createUnManaged ( T_OBJ , "" ) ; public static final ImageDescriptor DESC_OBJS_LIBRARY = createManagedFromKey ( T_OBJ , IMG_OBJS_LIBRARY ) ; public static final ImageDescriptor DESC_OBJS_EXTJAR = createManagedFromKey ( T_OBJ , IMG_OBJS_EXTJAR ) ; public static final ImageDescriptor DESC_OBJS_EXTJAR_WSRC = createManagedFromKey ( T_OBJ , IMG_OBJS_EXTJAR_WSRC ) ; public static final ImageDescriptor DESC_OBJS_CORRECTION_CHANGE = createManagedFromKey ( T_OBJ , IMG_OBJS_CORRECTION_CHANGE ) ; public static final ImageDescriptor DESC_OBJS_ENV_VAR = createManagedFromKey ( T_OBJ , IMG_OBJS_ENV_VAR ) ; public static final ImageDescriptor DESC_OBJS_SEARCH_DECL = createManagedFromKey ( T_OBJ , IMG_OBJS_SEARCH_DECL ) ; public static final ImageDescriptor DESC_OBJS_SEARCH_REF = createManagedFromKey ( T_OBJ , IMG_OBJS_SEARCH_REF ) ; public static final ImageDescriptor DESC_OBJS_QUICK_ASSIST = createManagedFromKey ( T_OBJ , IMG_OBJS_QUICK_ASSIST ) ; public static final ImageDescriptor DESC_OBJS_EXCLUSION_FILTER_ATTRIB = createUnManaged ( T_OBJ , "" ) ; public static final ImageDescriptor DESC_OBJS_INCLUSION_FILTER_ATTRIB = createUnManaged ( T_OBJ , "" ) ; public static final ImageDescriptor DESC_OVR_STATIC = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_FINAL = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_ABSTRACT = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_SYNCH = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_RUN = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_WARNING = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_ERROR = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_OVERRIDES = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_IMPLEMENTS = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_SYNCH_AND_OVERRIDES = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_SYNCH_AND_IMPLEMENTS = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_CONSTRUCTOR = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_DEPRECATED = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_FOCUS = createUnManagedCached ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OBJS_GHOST = createManagedFromKey ( T_OBJ , IMG_OBJS_GHOST ) ; public static final ImageDescriptor DESC_OBJS_IMPDECL = createManagedFromKey ( T_OBJ , IMG_CTOOLS_RUBY_IMPORT ) ; public static final ImageDescriptor DESC_OBJS_IMPCONT = createManagedFromKey ( T_OBJ , IMG_CTOOLS_RUBY_IMPORT_CONTAINER ) ; public static final ImageDescriptor DESC_OBJS_BLOCK = createManagedFromKey ( T_OBJ , IMG_CTOOLS_RUBY_BLOCK ) ; public static final ImageDescriptor DESC_OBJS_RUBY_MODEL = createManagedFromKey ( T_OBJ , IMG_OBJS_RUBY_MODEL ) ; public static final ImageDescriptor DESC_OBJS_SOURCE_FOLDER = createManagedFromKey ( T_OBJ , IMG_OBJS_SOURCE_FOLDER ) ; public static final ImageDescriptor DESC_OBJS_SOURCE_FOLDER_ROOT = createManagedFromKey ( T_OBJ , IMG_OBJS_SOURCE_FOLDER_ROOT ) ; public static final ImageDescriptor DESC_OBJS_LOCAL_VAR = createManagedFromKey ( T_OBJ , IMG_CTOOLS_RUBY_LOCAL_VAR ) ; public static final ImageDescriptor DESC_OBJS_GLOBAL = createManagedFromKey ( T_OBJ , IMG_CTOOLS_RUBY_GLOBAL ) ; public static final ImageDescriptor DESC_OBJS_MODULE = createManagedFromKey ( T_OBJ , IMG_OBJS_MODULE ) ; public static final ImageDescriptor DESC_OBJS_CLASS_VAR = createManagedFromKey ( T_OBJ , IMG_CTOOLS_RUBY_CLASS_VAR ) ; public static final ImageDescriptor DESC_OBJS_INSTANCE_VAR = createManagedFromKey ( T_OBJ , IMG_CTOOLS_RUBY_INSTANCE_VAR ) ; public static final ImageDescriptor DESC_OBJS_CONSTANT = createManagedFromKey ( T_OBJ , IMG_CTOOLS_RUBY_CONSTANT ) ; public static final ImageDescriptor DESC_OBJS_CLASS = createManagedFromKey ( T_OBJ , IMG_OBJS_CLASS ) ; public static final ImageDescriptor DESC_OBJS_CLASSALT = createManagedFromKey ( T_OBJ , IMG_OBJS_CLASSALT ) ; public static final ImageDescriptor DESC_OBJS_INNER_CLASS = createManagedFromKey ( T_OBJ , IMG_OBJS_INNER_CLASS ) ; public static final ImageDescriptor DESC_OBJS_MODULEALT = createManagedFromKey ( T_OBJ , IMG_OBJS_MODULEALT ) ; public static final ImageDescriptor DESC_OBJS_SCRIPT = createManagedFromKey ( T_OBJ , IMG_OBJS_SCRIPT ) ; public static final ImageDescriptor DESC_OBJS_ERB_SCRIPT = createManagedFromKey ( T_OBJ , IMG_OBJS_ERB_SCRIPT ) ; public static final ImageDescriptor DESC_OBJS_RUBY_RESOURCE = createManagedFromKey ( T_OBJ , IMG_OBJS_RUBY_RESOURCE ) ; public static final ImageDescriptor DESC_OBJS_UNKNOWN = createManagedFromKey ( T_OBJ , IMG_OBJS_UNKNOWN ) ; public static final ImageDescriptor DESC_OBJS_SEARCH_READACCESS = createManagedFromKey ( T_OBJ , IMG_OBJS_SEARCH_READACCESS ) ; public static final ImageDescriptor DESC_OBJS_SEARCH_WRITEACCESS = createManagedFromKey ( T_OBJ , IMG_OBJS_SEARCH_WRITEACCESS ) ; public static final ImageDescriptor DESC_OBJS_SEARCH_OCCURRENCE = createManagedFromKey ( T_OBJ , IMG_OBJS_SEARCH_OCCURRENCE ) ; public static final ImageDescriptor DESC_TOOL_NEWPACKROOT = createUnManaged ( T_ETOOL , "" ) ; public static final ImageDescriptor DESC_ELCL_FILTER = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_DLCL_FILTER = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_ELCL_REMOVE_FROM_BP = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_DLCL_ADD_AS_SOURCE_FOLDER = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_ELCL_ADD_AS_SOURCE_FOLDER = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_DLCL_REMOVE_AS_SOURCE_FOLDER = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_ELCL_REMOVE_AS_SOURCE_FOLDER = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_DLCL_EXCLUDE_FROM_BUILDPATH = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_ELCL_EXCLUDE_FROM_BUILDPATH = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_DLCL_INCLUDE_ON_BUILDPATH = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_ELCL_INCLUDE_ON_BUILDPATH = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_DLCL_CONFIGURE_BUILDPATH_FILTERS = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_ELCL_CONFIGURE_BUILDPATH_FILTERS = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_DLCL_ADD_LINKED_SOURCE_TO_BUILDPATH = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_ELCL_ADD_LINKED_SOURCE_TO_BUILDPATH = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_ELCL_CLEAR = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_DLCL_CLEAR = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_DLCL_CONFIGURE_BUILDPATH = createUnManaged ( T_DLCL , "" ) ; public static final ImageDescriptor DESC_ELCL_CONFIGURE_BUILDPATH = createUnManaged ( T_ELCL , "" ) ; public static final ImageDescriptor DESC_ELCL_VIEW_MENU = createManaged ( T_ELCL , "" , IMG_ELCL_VIEW_MENU ) ; public static final ImageDescriptor DESC_DLCL_VIEW_MENU = createManaged ( T_DLCL , "" , IMG_DLCL_VIEW_MENU ) ; public static final ImageDescriptor DESC_OVR_RECURSIVE = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_OVR_MAX_LEVEL = createUnManaged ( T_OVR , "" ) ; public static final ImageDescriptor DESC_MISC_PUBLIC = createManagedFromKey ( T_OBJ , IMG_MISC_PUBLIC ) ; public static final ImageDescriptor DESC_MISC_PROTECTED = createManagedFromKey ( T_OBJ , IMG_MISC_PROTECTED ) ; public static final ImageDescriptor DESC_MISC_PRIVATE = createManagedFromKey ( T_OBJ , IMG_MISC_PRIVATE ) ; public static final ImageDescriptor DESC_TOOL_LOADPATH_ORDER = createUnManaged ( T_OBJ , "" ) ; public static final ImageDescriptor DESC_TOOL_OPENTYPE = createUnManaged ( T_ETOOL , "" ) ; public static final String IMG_CORRECTION_RENAME = NAME_PREFIX + "" ; public static final String IMG_CORRECTION_ADD = NAME_PREFIX + "" ; public static final String IMG_CORRECTION_CHANGE = NAME_PREFIX + "" ; public static final String IMG_OBJS_NLS_NEVER_TRANSLATE = NAME_PREFIX + "" ; public static final ImageDescriptor DESC_OBJS_NLS_NEVER_TRANSLATE = createManagedFromKey ( T_OBJ , IMG_OBJS_NLS_NEVER_TRANSLATE ) ; static { createManagedFromKey ( T_OBJ , IMG_CORRECTION_RENAME ) ; createManagedFromKey ( T_OBJ , IMG_CORRECTION_ADD ) ; createManagedFromKey ( T_OBJ , IMG_CORRECTION_CHANGE ) ; createManagedFromKey ( T_OBJ , IMG_OBJS_FIXABLE_ERROR ) ; createManagedFromKey ( T_OBJ , IMG_OBJS_FIXABLE_PROBLEM ) ; createManagedFromKey ( T_OBJ , IMG_OBJS_ERROR ) ; createManagedFromKey ( T_OBJ , IMG_OBJS_WARNING ) ; createManagedFromKey ( T_OBJ , IMG_OBJS_INFO ) ; createManagedFromKey ( T_OBJ , IMG_OBJS_TEMPLATE ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_IMPORT_CONTAINER ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_IMPORT ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_PAGE ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_GLOBAL ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_CLASS ) ; createManagedFromKey ( T_CTOOL , IMG_OBJS_MODULE ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_SINGLETONMETHOD ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_SINGLETONMETHOD_PUB ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_SINGLETONMETHOD_PRO ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_CLASS_VAR ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_CONSTANT ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_LOCAL_VAR ) ; createManagedFromKey ( T_CTOOL , IMG_CTOOLS_RUBY_INSTANCE_VAR ) ; } public static Image get ( String key ) { return getImageRegistry ( ) . get ( key ) ; } public static void setToolImageDescriptors ( IAction action , String iconName ) { setImageDescriptors ( action , "" , iconName ) ; } public static void setLocalImageDescriptors ( IAction action , String iconName ) { setImageDescriptors ( action , "" , iconName ) ; } static ImageRegistry getImageRegistry ( ) { if ( fgImageRegistry == null ) { fgImageRegistry = new ImageRegistry ( ) ; for ( Iterator iter = fgAvoidSWTErrorMap . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { String key = ( String ) iter . next ( ) ; fgImageRegistry . put ( key , ( ImageDescriptor ) fgAvoidSWTErrorMap . get ( key ) ) ; } fgAvoidSWTErrorMap = null ; } return fgImageRegistry ; } private static ImageDescriptor createManagedFromKey ( String prefix , String key ) { return createManaged ( prefix , key . substring ( NAME_PREFIX_LENGTH ) , key ) ; } private static void setImageDescriptors ( IAction action , String type , String relPath ) { ImageDescriptor id = create ( "" + type , relPath , false ) ; if ( id != null ) action . setDisabledImageDescriptor ( id ) ; ImageDescriptor descriptor = create ( "" + type , relPath , true ) ; action . setHoverImageDescriptor ( descriptor ) ; action . setImageDescriptor ( descriptor ) ; } private static ImageDescriptor createManaged ( String prefix , String name , String key ) { ImageDescriptor result = create ( prefix , name , true ) ; if ( fgAvoidSWTErrorMap == null ) { fgAvoidSWTErrorMap = new HashMap ( ) ; } fgAvoidSWTErrorMap . put ( key , result ) ; if ( fgImageRegistry != null ) { RubyPlugin . logErrorMessage ( "" ) ; } return result ; } private static ImageDescriptor createUnManagedCached ( String prefix , String name ) { return new CachedImageDescriptor ( create ( prefix , name , true ) ) ; } private static ImageDescriptor create ( String prefix , String name , boolean useMissingImageDescriptor ) { IPath path = ICONS_PATH . append ( prefix ) . append ( name ) ; return createImageDescriptor ( RubyPlugin . getDefault ( ) . getBundle ( ) , path , useMissingImageDescriptor ) ; } private static ImageDescriptor createUnManaged ( String prefix , String name ) { return create ( prefix , name , true ) ; } public static ImageDescriptor createImageDescriptor ( Bundle bundle , IPath path , boolean useMissingImageDescriptor ) { URL url = FileLocator . find ( bundle , path , null ) ; if ( url != null ) { return ImageDescriptor . createFromURL ( url ) ; } if ( useMissingImageDescriptor ) { return ImageDescriptor . getMissingImageDescriptor ( ) ; } return null ; } public static ImageDescriptor getDescriptor ( String key ) { if ( fgImageRegistry == null ) { return ( ImageDescriptor ) fgAvoidSWTErrorMap . get ( key ) ; } return getImageRegistry ( ) . getDescriptor ( key ) ; } private static final class CachedImageDescriptor extends ImageDescriptor { private ImageDescriptor fDescriptor ; private ImageData fData ; public CachedImageDescriptor ( ImageDescriptor descriptor ) { fDescriptor = descriptor ; } public ImageData getImageData ( ) { if ( fData == null ) { fData = fDescriptor . getImageData ( ) ; } return fData ; } } } package org . rubypeople . rdt . internal . ui ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import org . eclipse . osgi . util . NLS ; public class RubyUIMessages extends NLS { private static final String BUNDLE_NAME = RubyUIMessages . class . getName ( ) ; private static ResourceBundle resourceBundle = ResourceBundle . getBundle ( BUNDLE_NAME ) ; public static String StatusBarUpdater_num_elements_selected ; public static String RubyElementLabels_anonym_type ; public static String RubyElementLabels_anonym ; public static String RubyElementLabels_import_container ; public static String RubyElementLabels_initializer ; public static String RubyElementLabels_concat_string ; public static String RubyElementLabels_comma_string ; public static String RubyElementLabels_declseparator_string ; public static String RubyImageLabelprovider_assert_wrongImage ; public static String CoreUtility_buildproject_taskname ; public static String CoreUtility_buildall_taskname ; public static String CoreUtility_job_title ; public static String MultiTypeSelectionDialog_errorTitle ; public static String MultiTypeSelectionDialog_errorMessage ; public static String TypeSelectionDialog_errorTitle ; public static String TypeSelectionDialog_dialogMessage ; public static String RubyElementLabels_default_package ; public static String RdtUiPlugin_internalErrorOccurred ; public static String RubyProjectLibraryPage_project ; public static String RubyProjectLibraryPage_elementNotIProject ; public static String RubyProjectPropertyPage_rubyProjectClosed ; public static String RubyProjectLibraryPage_tabName ; public static String RubyProjectPropertyPage_performOkException ; public static String RubyProjectPropertyPage_performOkExceptionDialogMessage ; public static String OptionalMessageDialog_dontShowAgain ; public static String FoldingConfigurationBlock_error_not_exist ; public static String FoldingConfigurationBlock_info_no_preferences ; public static String RubyBasePreferencePage_label ; public static String RDocPathErrorTitle ; public static String RDocPathError ; public static String ErrorRunningRdocTitle ; public static String ToggleMenuRubyFilesOnly_Tooltip ; public static String ToggleMenuRubyFilesOnly ; public static String RubySearchPage_SearchForGroupLabel ; public static String RubySearch_SearchForClassSymbol ; public static String RubySearch_SearchForMethodSymbol ; public static String RubySearch_ResultLabel ; public static String HTML2TextReader_listItemPrefix ; public static String HTMLTextPresenter_ellipsis ; public static String RubyAnnotationHover_multipleMarkersAtThisLine ; public static String ExceptionDialog_seeErrorLogMessage ; public static String NewProjectCreationWizard_windowTitle ; public static String NewProjectCreationWizard_projectCreationMessage ; public static String WizardNewProjectCreationPage_pageName ; public static String WizardNewProjectCreationPage_pageTitle ; public static String WizardNewProjectCreationPage_pageDescription ; public static String TypeSelectionComponent_show_status_line_label ; public static String TypeSelectionComponent_fully_qualify_duplicates_label ; public static String TypeSelectionComponent_label ; public static String TypeSelectionComponent_menu ; public static String TypeSelectionDialog2_title_format ; public static String TypeSelectionDialog_error_type_doesnot_exist ; public static String TypeSelectionDialog_error3Title ; public static String TypeSelectionDialog_error3Message ; public static String TypeSelectionDialog_progress_consistency ; public static String TypeInfoViewer_default_package ; public static String TypeInfoViewer_library_name_format ; public static String TypeInfoViewer_progressJob_label ; public static String TypeInfoViewer_progress_label ; public static String TypeInfoViewer_job_label ; public static String TypeInfoViewer_job_error ; public static String TypeInfoViewer_job_cancel ; public static String TypeInfoViewer_searchJob_taskName ; public static String TypeInfoViewer_syncJob_label ; public static String TypeInfoViewer_syncJob_taskName ; public static String TypeInfoViewer_remove_from_history ; public static String TypeInfoViewer_separator_message ; public static String TypeInfoLabelProvider_default_package ; public static String OpenTypeAction_dialogTitle ; public static String OpenTypeAction_dialogMessage ; public static String OpenTypeAction_label ; public static String OpenTypeAction_description ; public static String OpenTypeAction_tooltip ; public static String OpenTypeAction_errorTitle ; public static String OpenTypeAction_errorMessage ; public static String RubyOutlineControl_statusFieldText_hideInheritedMembers ; public static String RubyOutlineControl_statusFieldText_showInheritedMembers ; public static String OpenTypeHierarchyUtil_selectionDialog_title ; public static String OpenTypeHierarchyUtil_selectionDialog_message ; public static String OpenTypeHierarchyUtil_error_open_perspective ; public static String OpenTypeHierarchyUtil_error_open_editor ; public static String OpenTypeHierarchyUtil_error_open_view ; public static String RubyUI_defaultDialogMessage ; public static String Spelling_error_case_label ; public static String Spelling_error_label ; public static String AbstractSpellingDictionary_encodingError ; public static String Spelling_dictionary_file_extension ; public static String Spelling_correct_label ; public static String Spelling_case_label ; public static String Spelling_add_info ; public static String Spelling_add_label ; public static String Spelling_ignore_info ; public static String Spelling_ignore_label ; public static String RubyPlugin_initializing_ui ; public static String InitializeAfterLoadJob_starter_job_name ; public static String RubyElementProperties_name ; public static String RubyInstalledDetector_title ; public static String RubyInstalledDetector_message ; public static String RubyInstalledDetector_download_button ; public static String RubyInstalledDetector_preferences_button ; public static String RubyInstalledDetector_cancel_button ; public static String RubyEditor_codeassist_noCompletions ; public static String SelectionListenerWithASTManager_job_title ; public static String RDocExecutionError ; public static String RDocExecutionErrorAdditionalMessage ; public static String RDocExecutionErrorAdditionalMessageWithStderr ; public static String RubyInstalledDetector_msg ; private RubyUIMessages ( ) { } public static String getFormattedString ( String key , String arg ) { return getFormattedString ( key , new String [ ] { arg } ) ; } public static String getFormattedString ( String key , String [ ] args ) { return MessageFormat . format ( key , ( Object [ ] ) args ) ; } public static ResourceBundle getResourceBundle ( ) { return resourceBundle ; } static { NLS . initializeMessages ( BUNDLE_NAME , RubyUIMessages . class ) ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; public class RubyUIException extends CoreException { private static final long serialVersionUID = ; public RubyUIException ( IStatus status ) { super ( status ) ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdapterFactory ; import org . eclipse . search . ui . ISearchPageScoreComputer ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IStorageEditorInput ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . search . RubySearchPageScoreComputer ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; import org . rubypeople . rdt . ui . RubyUI ; public class EditorInputAdapterFactory implements IAdapterFactory { private static Class [ ] PROPERTIES = new Class [ ] { IRubyElement . class } ; private Object fSearchPageScoreComputer ; public Class [ ] getAdapterList ( ) { updateLazyLoadedAdapters ( ) ; return PROPERTIES ; } public Object getAdapter ( Object element , Class key ) { updateLazyLoadedAdapters ( ) ; if ( fSearchPageScoreComputer != null && ISearchPageScoreComputer . class . equals ( key ) ) return fSearchPageScoreComputer ; if ( IRubyElement . class . equals ( key ) && element instanceof IEditorInput ) { IRubyElement je = RubyUI . getWorkingCopyManager ( ) . getWorkingCopy ( ( IEditorInput ) element ) ; if ( je != null ) return je ; if ( element instanceof IStorageEditorInput ) { try { return ( ( IStorageEditorInput ) element ) . getStorage ( ) . getAdapter ( key ) ; } catch ( CoreException ex ) { } } } return null ; } private void updateLazyLoadedAdapters ( ) { if ( fSearchPageScoreComputer == null && SearchUtil . isSearchPlugInActivated ( ) ) createSearchPageScoreComputer ( ) ; } private void createSearchPageScoreComputer ( ) { fSearchPageScoreComputer = new RubySearchPageScoreComputer ( ) ; PROPERTIES = new Class [ ] { ISearchPageScoreComputer . class , IRubyElement . class } ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . resource . ImageRegistry ; import org . eclipse . jface . viewers . IColorProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public class CPVariableElementLabelProvider extends LabelProvider implements IColorProvider { private Image fJARImage ; private Image fFolderImage ; private boolean fShowResolvedVariables ; private Color fResolvedBackground ; public CPVariableElementLabelProvider ( boolean showResolvedVariables ) { ImageRegistry reg = RubyPlugin . getDefault ( ) . getImageRegistry ( ) ; fJARImage = reg . get ( RubyPluginImages . IMG_OBJS_EXTJAR ) ; fFolderImage = PlatformUI . getWorkbench ( ) . getSharedImages ( ) . getImage ( ISharedImages . IMG_OBJ_FOLDER ) ; fShowResolvedVariables = showResolvedVariables ; fResolvedBackground = null ; } public Image getImage ( Object element ) { if ( element instanceof CPVariableElement ) { CPVariableElement curr = ( CPVariableElement ) element ; IPath path = curr . getPath ( ) [ ] ; if ( path . toFile ( ) . isFile ( ) ) { return fJARImage ; } return fFolderImage ; } return super . getImage ( element ) ; } public String getText ( Object element ) { if ( element instanceof CPVariableElement ) { CPVariableElement curr = ( CPVariableElement ) element ; String name = curr . getName ( ) ; IPath path = curr . getPath ( ) [ ] ; StringBuffer buf = new StringBuffer ( name ) ; if ( curr . isReserved ( ) ) { buf . append ( '' ) ; buf . append ( NewWizardMessages . CPVariableElementLabelProvider_reserved ) ; } if ( path != null ) { buf . append ( "" ) ; if ( ! path . isEmpty ( ) ) { buf . append ( path . toOSString ( ) ) ; } else { buf . append ( NewWizardMessages . CPVariableElementLabelProvider_empty ) ; } } return buf . toString ( ) ; } return super . getText ( element ) ; } public Color getForeground ( Object element ) { return null ; } public Color getBackground ( Object element ) { if ( element instanceof CPVariableElement ) { CPVariableElement curr = ( CPVariableElement ) element ; if ( ! fShowResolvedVariables && curr . isReserved ( ) ) { if ( fResolvedBackground == null ) { Display display = Display . getCurrent ( ) ; fResolvedBackground = display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ; } return fResolvedBackground ; } } return null ; } public void dispose ( ) { super . dispose ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . ElementTreeSelectionDialog ; import org . eclipse . ui . dialogs . ISelectionStatusValidator ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; import org . eclipse . ui . views . navigator . ResourceSorter ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . TypedElementSelectionValidator ; import org . rubypeople . rdt . internal . ui . wizards . TypedViewerFilter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; public class ExclusionInclusionEntryDialog extends StatusDialog { private StringButtonDialogField fExclusionPatternDialog ; private StatusInfo fExclusionPatternStatus ; private IContainer fCurrSourceFolder ; private String fExclusionPattern ; private List fExistingPatterns ; private boolean fIsExclusion ; public ExclusionInclusionEntryDialog ( Shell parent , boolean isExclusion , String patternToEdit , List existingPatterns , CPListElement entryToEdit ) { super ( parent ) ; fIsExclusion = isExclusion ; fExistingPatterns = existingPatterns ; String title , message ; if ( isExclusion ) { if ( patternToEdit == null ) { title = NewWizardMessages . ExclusionInclusionEntryDialog_exclude_add_title ; } else { title = NewWizardMessages . ExclusionInclusionEntryDialog_exclude_edit_title ; } message = Messages . format ( NewWizardMessages . ExclusionInclusionEntryDialog_exclude_pattern_label , entryToEdit . getPath ( ) . makeRelative ( ) . toString ( ) ) ; } else { if ( patternToEdit == null ) { title = NewWizardMessages . ExclusionInclusionEntryDialog_include_add_title ; } else { title = NewWizardMessages . ExclusionInclusionEntryDialog_include_edit_title ; } message = Messages . format ( NewWizardMessages . ExclusionInclusionEntryDialog_include_pattern_label , entryToEdit . getPath ( ) . makeRelative ( ) . toString ( ) ) ; } setTitle ( title ) ; if ( patternToEdit != null ) { fExistingPatterns . remove ( patternToEdit ) ; } IWorkspaceRoot root = entryToEdit . getRubyProject ( ) . getProject ( ) . getWorkspace ( ) . getRoot ( ) ; IResource res = root . findMember ( entryToEdit . getPath ( ) ) ; if ( res instanceof IContainer ) { fCurrSourceFolder = ( IContainer ) res ; } fExclusionPatternStatus = new StatusInfo ( ) ; ExclusionPatternAdapter adapter = new ExclusionPatternAdapter ( ) ; fExclusionPatternDialog = new StringButtonDialogField ( adapter ) ; fExclusionPatternDialog . setLabelText ( message ) ; fExclusionPatternDialog . setButtonLabel ( NewWizardMessages . ExclusionInclusionEntryDialog_pattern_button ) ; fExclusionPatternDialog . setDialogFieldListener ( adapter ) ; fExclusionPatternDialog . enableButton ( fCurrSourceFolder != null ) ; if ( patternToEdit == null ) { fExclusionPatternDialog . setText ( "" ) ; } else { fExclusionPatternDialog . setText ( patternToEdit . toString ( ) ) ; } } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; int widthHint = convertWidthInCharsToPixels ( ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; inner . setLayout ( layout ) ; Label description = new Label ( inner , SWT . WRAP ) ; if ( fIsExclusion ) { description . setText ( NewWizardMessages . ExclusionInclusionEntryDialog_exclude_description ) ; } else { description . setText ( NewWizardMessages . ExclusionInclusionEntryDialog_include_description ) ; } GridData gd = new GridData ( ) ; gd . horizontalSpan = ; gd . widthHint = convertWidthInCharsToPixels ( ) ; description . setLayoutData ( gd ) ; fExclusionPatternDialog . doFillIntoGrid ( inner , ) ; LayoutUtil . setWidthHint ( fExclusionPatternDialog . getLabelControl ( null ) , widthHint ) ; LayoutUtil . setHorizontalSpan ( fExclusionPatternDialog . getLabelControl ( null ) , ) ; LayoutUtil . setWidthHint ( fExclusionPatternDialog . getTextControl ( null ) , widthHint ) ; LayoutUtil . setHorizontalGrabbing ( fExclusionPatternDialog . getTextControl ( null ) ) ; fExclusionPatternDialog . postSetFocusOnDialogField ( parent . getDisplay ( ) ) ; applyDialogFont ( composite ) ; return composite ; } private class ExclusionPatternAdapter implements IDialogFieldListener , IStringButtonAdapter { public void dialogFieldChanged ( DialogField field ) { doStatusLineUpdate ( ) ; } public void changeControlPressed ( DialogField field ) { doChangeControlPressed ( ) ; } } protected void doChangeControlPressed ( ) { IPath pattern = chooseExclusionPattern ( ) ; if ( pattern != null ) { fExclusionPatternDialog . setText ( pattern . toString ( ) ) ; } } protected void doStatusLineUpdate ( ) { checkIfPatternValid ( ) ; updateStatus ( fExclusionPatternStatus ) ; } protected void checkIfPatternValid ( ) { String pattern = fExclusionPatternDialog . getText ( ) . trim ( ) ; if ( pattern . length ( ) == ) { fExclusionPatternStatus . setError ( NewWizardMessages . ExclusionInclusionEntryDialog_error_empty ) ; return ; } IPath path = new Path ( pattern ) ; if ( path . isAbsolute ( ) || path . getDevice ( ) != null ) { fExclusionPatternStatus . setError ( NewWizardMessages . ExclusionInclusionEntryDialog_error_notrelative ) ; return ; } if ( fExistingPatterns . contains ( pattern ) ) { fExclusionPatternStatus . setError ( NewWizardMessages . ExclusionInclusionEntryDialog_error_exists ) ; return ; } fExclusionPattern = pattern ; fExclusionPatternStatus . setOK ( ) ; } public String getExclusionPattern ( ) { return fExclusionPattern ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; } private IPath chooseExclusionPattern ( ) { String title , message ; if ( fIsExclusion ) { title = NewWizardMessages . ExclusionInclusionEntryDialog_ChooseExclusionPattern_title ; message = NewWizardMessages . ExclusionInclusionEntryDialog_ChooseExclusionPattern_description ; } else { title = NewWizardMessages . ExclusionInclusionEntryDialog_ChooseInclusionPattern_title ; message = NewWizardMessages . ExclusionInclusionEntryDialog_ChooseInclusionPattern_description ; } IPath initialPath = new Path ( fExclusionPatternDialog . getText ( ) ) ; IPath [ ] res = chooseExclusionPattern ( getShell ( ) , fCurrSourceFolder , title , message , initialPath , false ) ; if ( res == null ) { return null ; } return res [ ] ; } public static IPath [ ] chooseExclusionPattern ( Shell shell , IContainer currentSourceFolder , String title , String message , IPath initialPath , boolean multiSelection ) { Class [ ] acceptedClasses = new Class [ ] { IFolder . class , IFile . class } ; ISelectionStatusValidator validator = new TypedElementSelectionValidator ( acceptedClasses , multiSelection ) ; ViewerFilter filter = new TypedViewerFilter ( acceptedClasses ) ; ILabelProvider lp = new WorkbenchLabelProvider ( ) ; ITreeContentProvider cp = new WorkbenchContentProvider ( ) ; IResource initialElement = null ; if ( initialPath != null ) { IContainer curr = currentSourceFolder ; int nSegments = initialPath . segmentCount ( ) ; for ( int i = ; i < nSegments ; i ++ ) { IResource elem = curr . findMember ( initialPath . segment ( i ) ) ; if ( elem != null ) { initialElement = elem ; } if ( elem instanceof IContainer ) { curr = ( IContainer ) elem ; } else { break ; } } } ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog ( shell , lp , cp ) ; dialog . setTitle ( title ) ; dialog . setValidator ( validator ) ; dialog . setMessage ( message ) ; dialog . addFilter ( filter ) ; dialog . setInput ( currentSourceFolder ) ; dialog . setInitialSelection ( initialElement ) ; dialog . setSorter ( new ResourceSorter ( ResourceSorter . NAME ) ) ; dialog . setHelpAvailable ( false ) ; if ( dialog . open ( ) == Window . OK ) { Object [ ] objects = dialog . getResult ( ) ; int existingSegments = currentSourceFolder . getFullPath ( ) . segmentCount ( ) ; IPath [ ] resArr = new IPath [ objects . length ] ; for ( int i = ; i < objects . length ; i ++ ) { IResource currRes = ( IResource ) objects [ i ] ; IPath path = currRes . getFullPath ( ) . removeFirstSegments ( existingSegments ) . makeRelative ( ) ; if ( currRes instanceof IContainer ) { path = path . addTrailingSeparator ( ) ; } resArr [ i ] = path ; } return resArr ; } return null ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . jface . viewers . ArrayContentProvider ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . ListSelectionDialog ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyUILabelProvider ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ITreeListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . TreeListDialogField ; import org . rubypeople . rdt . ui . RubyElementSorter ; public class ProjectsWorkbookPage extends BuildPathBasePage { private final int IDX_ADDPROJECT = ; private final int IDX_EDIT = ; private final int IDX_REMOVE = ; private ListDialogField fClassPathList ; private IRubyProject fCurrJProject ; private TreeListDialogField fProjectsList ; private Control fSWTControl ; private final IWorkbenchPreferenceContainer fPageContainer ; public ProjectsWorkbookPage ( ListDialogField classPathList , IWorkbenchPreferenceContainer pageContainer ) { fClassPathList = classPathList ; fPageContainer = pageContainer ; fSWTControl = null ; String [ ] buttonLabels = new String [ ] { NewWizardMessages . ProjectsWorkbookPage_projects_add_button , null , NewWizardMessages . ProjectsWorkbookPage_projects_edit_button , NewWizardMessages . ProjectsWorkbookPage_projects_remove_button } ; ProjectsAdapter adapter = new ProjectsAdapter ( ) ; fProjectsList = new TreeListDialogField ( adapter , buttonLabels , new CPListLabelProvider ( ) ) ; fProjectsList . setDialogFieldListener ( adapter ) ; fProjectsList . setLabelText ( NewWizardMessages . ProjectsWorkbookPage_projects_label ) ; fProjectsList . enableButton ( IDX_REMOVE , false ) ; fProjectsList . enableButton ( IDX_EDIT , false ) ; fProjectsList . setViewerSorter ( new CPListElementSorter ( ) ) ; } public void init ( IRubyProject jproject ) { updateProjectsList ( jproject ) ; } private void updateProjectsList ( IRubyProject currJProject ) { List cpelements = fClassPathList . getElements ( ) ; final List checkedProjects = new ArrayList ( cpelements . size ( ) ) ; for ( int i = cpelements . size ( ) - ; i >= ; i -- ) { CPListElement cpelem = ( CPListElement ) cpelements . get ( i ) ; if ( isEntryKind ( cpelem . getEntryKind ( ) ) ) { checkedProjects . add ( cpelem ) ; } } fProjectsList . setElements ( checkedProjects ) ; fCurrJProject = currJProject ; } public Control getControl ( Composite parent ) { PixelConverter converter = new PixelConverter ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; LayoutUtil . doDefaultLayout ( composite , new DialogField [ ] { fProjectsList } , true , SWT . DEFAULT , SWT . DEFAULT ) ; LayoutUtil . setHorizontalGrabbing ( fProjectsList . getTreeControl ( null ) ) ; int buttonBarWidth = converter . convertWidthInCharsToPixels ( ) ; fProjectsList . setButtonsMinWidth ( buttonBarWidth ) ; fSWTControl = composite ; return composite ; } private void updateLoadpathList ( ) { List projelements = fProjectsList . getElements ( ) ; boolean remove = false ; List cpelements = fClassPathList . getElements ( ) ; for ( int i = cpelements . size ( ) - ; i >= ; i -- ) { CPListElement cpe = ( CPListElement ) cpelements . get ( i ) ; if ( isEntryKind ( cpe . getEntryKind ( ) ) ) { if ( ! projelements . remove ( cpe ) ) { cpelements . remove ( i ) ; remove = true ; } } } for ( int i = ; i < projelements . size ( ) ; i ++ ) { cpelements . add ( projelements . get ( i ) ) ; } if ( remove || ( projelements . size ( ) > ) ) { fClassPathList . setElements ( cpelements ) ; } } public List getSelection ( ) { return fProjectsList . getSelectedElements ( ) ; } public void setSelection ( List selElements , boolean expand ) { fProjectsList . selectElements ( new StructuredSelection ( selElements ) ) ; if ( expand ) { for ( int i = ; i < selElements . size ( ) ; i ++ ) { fProjectsList . expandElement ( selElements . get ( i ) , ) ; } } } public boolean isEntryKind ( int kind ) { return kind == ILoadpathEntry . CPE_PROJECT ; } private class ProjectsAdapter implements IDialogFieldListener , ITreeListAdapter { private final Object [ ] EMPTY_ARR = new Object [ ] ; public void customButtonPressed ( TreeListDialogField field , int index ) { projectPageCustomButtonPressed ( field , index ) ; } public void selectionChanged ( TreeListDialogField field ) { projectPageSelectionChanged ( field ) ; } public void doubleClicked ( TreeListDialogField field ) { projectPageDoubleClicked ( field ) ; } public void keyPressed ( TreeListDialogField field , KeyEvent event ) { projectPageKeyPressed ( field , event ) ; } public Object [ ] getChildren ( TreeListDialogField field , Object element ) { if ( element instanceof CPListElement ) { return ( ( CPListElement ) element ) . getChildren ( false ) ; } return EMPTY_ARR ; } public Object getParent ( TreeListDialogField field , Object element ) { if ( element instanceof CPListElementAttribute ) { return ( ( CPListElementAttribute ) element ) . getParent ( ) ; } return null ; } public boolean hasChildren ( TreeListDialogField field , Object element ) { return getChildren ( field , element ) . length > ; } public void dialogFieldChanged ( DialogField field ) { projectPageDialogFieldChanged ( field ) ; } } private void projectPageCustomButtonPressed ( DialogField field , int index ) { CPListElement [ ] entries = null ; switch ( index ) { case IDX_ADDPROJECT : entries = openProjectDialog ( null ) ; break ; case IDX_EDIT : editEntry ( ) ; return ; case IDX_REMOVE : removeEntry ( ) ; return ; } if ( entries != null ) { int nElementsChosen = entries . length ; List cplist = fProjectsList . getElements ( ) ; List elementsToAdd = new ArrayList ( nElementsChosen ) ; for ( int i = ; i < nElementsChosen ; i ++ ) { CPListElement curr = entries [ i ] ; if ( ! cplist . contains ( curr ) && ! elementsToAdd . contains ( curr ) ) { elementsToAdd . add ( curr ) ; } } fProjectsList . addElements ( elementsToAdd ) ; if ( index == IDX_ADDPROJECT ) { fProjectsList . refresh ( ) ; } fProjectsList . postSetSelection ( new StructuredSelection ( entries ) ) ; } } private void removeEntry ( ) { List selElements = fProjectsList . getSelectedElements ( ) ; for ( int i = selElements . size ( ) - ; i >= ; i -- ) { Object elem = selElements . get ( i ) ; if ( elem instanceof CPListElementAttribute ) { CPListElementAttribute attrib = ( CPListElementAttribute ) elem ; String key = attrib . getKey ( ) ; Object value = null ; attrib . getParent ( ) . setAttribute ( key , value ) ; selElements . remove ( i ) ; } } if ( selElements . isEmpty ( ) ) { fProjectsList . refresh ( ) ; fClassPathList . dialogFieldChanged ( ) ; } else { fProjectsList . removeElements ( selElements ) ; } } private boolean canRemove ( List selElements ) { if ( selElements . size ( ) == ) { return false ; } int elements = ; int attributes = ; for ( int i = ; i < selElements . size ( ) ; i ++ ) { Object elem = selElements . get ( i ) ; if ( elem instanceof CPListElementAttribute ) { CPListElementAttribute attrib = ( CPListElementAttribute ) elem ; if ( attrib . getValue ( ) == null ) { return false ; } attributes ++ ; } else if ( elem instanceof CPListElement ) { elements ++ ; } } return attributes == selElements . size ( ) || elements == selElements . size ( ) ; } private boolean canEdit ( List selElements ) { if ( selElements . size ( ) != ) { return false ; } Object elem = selElements . get ( ) ; if ( elem instanceof CPListElement ) { return false ; } if ( elem instanceof CPListElementAttribute ) { return true ; } return false ; } private void editEntry ( ) { List selElements = fProjectsList . getSelectedElements ( ) ; if ( selElements . size ( ) != ) { return ; } Object elem = selElements . get ( ) ; if ( fProjectsList . getIndexOfElement ( elem ) != - ) { editElementEntry ( ( CPListElement ) elem ) ; } else if ( elem instanceof CPListElementAttribute ) { } } private void editElementEntry ( CPListElement elem ) { CPListElement [ ] res = openProjectDialog ( elem ) ; if ( res != null && res . length > ) { CPListElement curr = res [ ] ; curr . setExported ( elem . isExported ( ) ) ; fProjectsList . replaceElement ( elem , curr ) ; } } private Shell getShell ( ) { if ( fSWTControl != null ) { return fSWTControl . getShell ( ) ; } return RubyPlugin . getActiveWorkbenchShell ( ) ; } private CPListElement [ ] openProjectDialog ( CPListElement elem ) { try { ArrayList selectable = new ArrayList ( ) ; selectable . addAll ( Arrays . asList ( fCurrJProject . getRubyModel ( ) . getRubyProjects ( ) ) ) ; selectable . remove ( fCurrJProject ) ; List elements = fProjectsList . getElements ( ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { CPListElement curr = ( CPListElement ) elements . get ( ) ; IRubyProject proj = ( IRubyProject ) RubyCore . create ( curr . getResource ( ) ) ; selectable . remove ( proj ) ; } Object [ ] selectArr = selectable . toArray ( ) ; new RubyElementSorter ( ) . sort ( null , selectArr ) ; ListSelectionDialog dialog = new ListSelectionDialog ( getShell ( ) , Arrays . asList ( selectArr ) , new ArrayContentProvider ( ) , new RubyUILabelProvider ( ) , NewWizardMessages . ProjectsWorkbookPage_chooseProjects_message ) ; dialog . setTitle ( NewWizardMessages . ProjectsWorkbookPage_chooseProjects_title ) ; dialog . setHelpAvailable ( false ) ; if ( dialog . open ( ) == Window . OK ) { Object [ ] result = dialog . getResult ( ) ; CPListElement [ ] cpElements = new CPListElement [ result . length ] ; for ( int i = ; i < result . length ; i ++ ) { IRubyProject curr = ( IRubyProject ) result [ i ] ; cpElements [ i ] = new CPListElement ( fCurrJProject , ILoadpathEntry . CPE_PROJECT , curr . getPath ( ) , curr . getResource ( ) ) ; } return cpElements ; } } catch ( RubyModelException e ) { return null ; } return null ; } protected void projectPageDoubleClicked ( TreeListDialogField field ) { List selection = fProjectsList . getSelectedElements ( ) ; if ( canEdit ( selection ) ) { editEntry ( ) ; } } protected void projectPageKeyPressed ( TreeListDialogField field , KeyEvent event ) { if ( field == fProjectsList ) { if ( event . character == SWT . DEL && event . stateMask == ) { List selection = field . getSelectedElements ( ) ; if ( canRemove ( selection ) ) { removeEntry ( ) ; } } } } private void projectPageDialogFieldChanged ( DialogField field ) { if ( fCurrJProject != null ) { updateLoadpathList ( ) ; } } private void projectPageSelectionChanged ( DialogField field ) { List selElements = fProjectsList . getSelectedElements ( ) ; fProjectsList . enableButton ( IDX_EDIT , canEdit ( selElements ) ) ; fProjectsList . enableButton ( IDX_REMOVE , canRemove ( selElements ) ) ; boolean noAttributes = containsOnlyTopLevelEntries ( selElements ) ; fProjectsList . enableButton ( IDX_ADDPROJECT , noAttributes ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . net . URI ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . TabFolder ; import org . eclipse . swt . widgets . TabItem ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . util . CoreUtility ; import org . rubypeople . rdt . internal . ui . viewsupport . ImageDisposer ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . NewSourceContainerWorkbookPage ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . CheckedListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class BuildPathsBlock { public static interface IRemoveOldBinariesQuery { boolean doQuery ( IPath oldOutputLocation ) throws OperationCanceledException ; } private CheckedListDialogField fLoadPathList ; private StatusInfo fLoadPathStatus ; private StatusInfo fBuildPathStatus ; private IRubyProject fCurrJProject ; private IPath fOutputLocationPath ; private IStatusChangeListener fContext ; private Control fSWTWidget ; private TabFolder fTabFolder ; private int fPageIndex ; private BuildPathBasePage fSourceContainerPage ; private ProjectsWorkbookPage fProjectsPage ; private LibrariesWorkbookPage fLibrariesPage ; private BuildPathBasePage fCurrPage ; private String fUserSettingsTimeStamp ; private long fFileTimeStamp ; private IRunnableContext fRunnableContext ; private boolean fUseNewPage ; private final IWorkbenchPreferenceContainer fPageContainer ; public BuildPathsBlock ( IRunnableContext runnableContext , IStatusChangeListener context , int pageToShow , boolean useNewPage , IWorkbenchPreferenceContainer pageContainer ) { fPageContainer = pageContainer ; fContext = context ; fUseNewPage = useNewPage ; fPageIndex = pageToShow ; fSourceContainerPage = null ; fLibrariesPage = null ; fProjectsPage = null ; fCurrPage = null ; fRunnableContext = runnableContext ; BuildPathAdapter adapter = new BuildPathAdapter ( ) ; String [ ] buttonLabels = new String [ ] { NewWizardMessages . BuildPathsBlock_classpath_up_button , NewWizardMessages . BuildPathsBlock_classpath_down_button , null , NewWizardMessages . BuildPathsBlock_classpath_checkall_button , NewWizardMessages . BuildPathsBlock_classpath_uncheckall_button } ; fLoadPathList = new CheckedListDialogField ( null , buttonLabels , new CPListLabelProvider ( ) ) ; fLoadPathList . setDialogFieldListener ( adapter ) ; fLoadPathList . setLabelText ( NewWizardMessages . BuildPathsBlock_classpath_label ) ; fLoadPathList . setUpButtonIndex ( ) ; fLoadPathList . setDownButtonIndex ( ) ; fLoadPathList . setCheckAllButtonIndex ( ) ; fLoadPathList . setUncheckAllButtonIndex ( ) ; fBuildPathStatus = new StatusInfo ( ) ; fLoadPathStatus = new StatusInfo ( ) ; fCurrJProject = null ; } public Control createControl ( Composite parent ) { fSWTWidget = parent ; Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginWidth = ; layout . marginHeight = ; layout . numColumns = ; composite . setLayout ( layout ) ; TabFolder folder = new TabFolder ( composite , SWT . NONE ) ; folder . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; folder . setFont ( composite . getFont ( ) ) ; TabItem item ; item = new TabItem ( folder , SWT . NONE ) ; item . setText ( NewWizardMessages . BuildPathsBlock_tab_source ) ; item . setImage ( RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_SOURCE_FOLDER_ROOT ) ) ; if ( fUseNewPage ) { fSourceContainerPage = new NewSourceContainerWorkbookPage ( fLoadPathList , fRunnableContext , this ) ; } else { fSourceContainerPage = new SourceContainerWorkbookPage ( fLoadPathList ) ; } item . setData ( fSourceContainerPage ) ; item . setControl ( fSourceContainerPage . getControl ( folder ) ) ; IWorkbench workbench = RubyPlugin . getDefault ( ) . getWorkbench ( ) ; Image projectImage = workbench . getSharedImages ( ) . getImage ( IDE . SharedImages . IMG_OBJ_PROJECT ) ; fProjectsPage = new ProjectsWorkbookPage ( fLoadPathList , fPageContainer ) ; item = new TabItem ( folder , SWT . NONE ) ; item . setText ( NewWizardMessages . BuildPathsBlock_tab_projects ) ; item . setImage ( projectImage ) ; item . setData ( fProjectsPage ) ; item . setControl ( fProjectsPage . getControl ( folder ) ) ; fLibrariesPage = new LibrariesWorkbookPage ( fLoadPathList , fPageContainer ) ; item = new TabItem ( folder , SWT . NONE ) ; item . setText ( NewWizardMessages . BuildPathsBlock_tab_libraries ) ; item . setImage ( RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_LIBRARY ) ) ; item . setData ( fLibrariesPage ) ; item . setControl ( fLibrariesPage . getControl ( folder ) ) ; Image cpoImage = RubyPluginImages . DESC_TOOL_LOADPATH_ORDER . createImage ( ) ; composite . addDisposeListener ( new ImageDisposer ( cpoImage ) ) ; LoadpathOrderingWorkbookPage ordpage = new LoadpathOrderingWorkbookPage ( fLoadPathList ) ; item = new TabItem ( folder , SWT . NONE ) ; item . setText ( NewWizardMessages . BuildPathsBlock_tab_order ) ; item . setImage ( cpoImage ) ; item . setData ( ordpage ) ; item . setControl ( ordpage . getControl ( folder ) ) ; if ( fCurrJProject != null ) { fSourceContainerPage . init ( fCurrJProject ) ; fLibrariesPage . init ( fCurrJProject ) ; fProjectsPage . init ( fCurrJProject ) ; } folder . setSelection ( fPageIndex ) ; fCurrPage = ( BuildPathBasePage ) folder . getItem ( fPageIndex ) . getData ( ) ; folder . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { tabChanged ( e . item ) ; } } ) ; fTabFolder = folder ; Dialog . applyDialogFont ( composite ) ; return composite ; } public void init ( IRubyProject jproject , IPath outputLocation , ILoadpathEntry [ ] classpathEntries ) { fCurrJProject = jproject ; boolean projectExists = false ; List newClassPath = null ; IProject project = fCurrJProject . getProject ( ) ; projectExists = ( project . exists ( ) && project . getFile ( "" ) . exists ( ) ) ; if ( projectExists ) { if ( classpathEntries == null ) { classpathEntries = fCurrJProject . readRawLoadpath ( ) ; } } if ( classpathEntries != null ) { newClassPath = getExistingEntries ( classpathEntries ) ; } if ( newClassPath == null ) { newClassPath = getDefaultClassPath ( jproject ) ; } List exportedEntries = new ArrayList ( ) ; for ( int i = ; i < newClassPath . size ( ) ; i ++ ) { CPListElement curr = ( CPListElement ) newClassPath . get ( i ) ; if ( curr . isExported ( ) || curr . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { exportedEntries . add ( curr ) ; } } fLoadPathList . setElements ( newClassPath ) ; fLoadPathList . setCheckedElements ( exportedEntries ) ; initializeTimeStamps ( ) ; updateUI ( ) ; } protected void updateUI ( ) { if ( fSWTWidget == null || fSWTWidget . isDisposed ( ) ) { return ; } if ( Display . getCurrent ( ) != null ) { doUpdateUI ( ) ; } else { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { if ( fSWTWidget == null || fSWTWidget . isDisposed ( ) ) { return ; } doUpdateUI ( ) ; } } ) ; } } protected void doUpdateUI ( ) { fLoadPathList . refresh ( ) ; if ( fSourceContainerPage != null ) { fSourceContainerPage . init ( fCurrJProject ) ; fProjectsPage . init ( fCurrJProject ) ; fLibrariesPage . init ( fCurrJProject ) ; } doStatusLineUpdate ( ) ; } private String getEncodedSettings ( ) { StringBuffer buf = new StringBuffer ( ) ; CPListElement . appendEncodePath ( fOutputLocationPath , buf ) . append ( '' ) ; int nElements = fLoadPathList . getSize ( ) ; buf . append ( '' ) . append ( nElements ) . append ( '' ) ; for ( int i = ; i < nElements ; i ++ ) { CPListElement elem = ( CPListElement ) fLoadPathList . getElement ( i ) ; elem . appendEncodedSettings ( buf ) ; } return buf . toString ( ) ; } public boolean hasChangesInDialog ( ) { String currSettings = getEncodedSettings ( ) ; return ! currSettings . equals ( fUserSettingsTimeStamp ) ; } public boolean hasChangesInLoadpathFile ( ) { IFile file = fCurrJProject . getProject ( ) . getFile ( "" ) ; return fFileTimeStamp != file . getModificationStamp ( ) ; } public void initializeTimeStamps ( ) { IFile file = fCurrJProject . getProject ( ) . getFile ( "" ) ; fFileTimeStamp = file . getModificationStamp ( ) ; fUserSettingsTimeStamp = getEncodedSettings ( ) ; } private ArrayList getExistingEntries ( ILoadpathEntry [ ] classpathEntries ) { ArrayList newClassPath = new ArrayList ( ) ; for ( int i = ; i < classpathEntries . length ; i ++ ) { ILoadpathEntry curr = classpathEntries [ i ] ; newClassPath . add ( CPListElement . createFromExisting ( curr , fCurrJProject ) ) ; } return newClassPath ; } public IRubyProject getRubyProject ( ) { return fCurrJProject ; } public ILoadpathEntry [ ] getRawClassPath ( ) { List elements = fLoadPathList . getElements ( ) ; int nElements = elements . size ( ) ; ILoadpathEntry [ ] entries = new ILoadpathEntry [ elements . size ( ) ] ; for ( int i = ; i < nElements ; i ++ ) { CPListElement currElement = ( CPListElement ) elements . get ( i ) ; entries [ i ] = currElement . getLoadpathEntry ( ) ; } return entries ; } public int getPageIndex ( ) { return fPageIndex ; } private List getDefaultClassPath ( IRubyProject jproj ) { List list = new ArrayList ( ) ; IResource srcFolder = jproj . getProject ( ) ; list . add ( new CPListElement ( jproj , ILoadpathEntry . CPE_SOURCE , srcFolder . getFullPath ( ) , srcFolder ) ) ; ILoadpathEntry [ ] jreEntries = PreferenceConstants . getDefaultRubyVMLibrary ( ) ; list . addAll ( getExistingEntries ( jreEntries ) ) ; return list ; } private class BuildPathAdapter implements IStringButtonAdapter , IDialogFieldListener { public void changeControlPressed ( DialogField field ) { buildPathChangeControlPressed ( field ) ; } public void dialogFieldChanged ( DialogField field ) { buildPathDialogFieldChanged ( field ) ; } } private void buildPathChangeControlPressed ( DialogField field ) { } private void buildPathDialogFieldChanged ( DialogField field ) { if ( field == fLoadPathList ) { updateLoadPathStatus ( ) ; } doStatusLineUpdate ( ) ; } private void doStatusLineUpdate ( ) { if ( Display . getCurrent ( ) != null ) { IStatus res = findMostSevereStatus ( ) ; fContext . statusChanged ( res ) ; } } private IStatus findMostSevereStatus ( ) { return StatusUtil . getMostSevere ( new IStatus [ ] { fLoadPathStatus , fBuildPathStatus } ) ; } public void updateLoadPathStatus ( ) { fLoadPathStatus . setOK ( ) ; List elements = fLoadPathList . getElements ( ) ; CPListElement entryMissing = null ; int nEntriesMissing = ; ILoadpathEntry [ ] entries = new ILoadpathEntry [ elements . size ( ) ] ; for ( int i = elements . size ( ) - ; i >= ; i -- ) { CPListElement currElement = ( CPListElement ) elements . get ( i ) ; boolean isChecked = fLoadPathList . isChecked ( currElement ) ; if ( currElement . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { if ( ! isChecked ) { fLoadPathList . setCheckedWithoutUpdate ( currElement , true ) ; } if ( ! fLoadPathList . isGrayed ( currElement ) ) { fLoadPathList . setGrayedWithoutUpdate ( currElement , true ) ; } } else { currElement . setExported ( isChecked ) ; } entries [ i ] = currElement . getLoadpathEntry ( ) ; if ( currElement . isMissing ( ) ) { nEntriesMissing ++ ; if ( entryMissing == null ) { entryMissing = currElement ; } } } if ( nEntriesMissing > ) { if ( nEntriesMissing == ) { fLoadPathStatus . setWarning ( Messages . format ( NewWizardMessages . BuildPathsBlock_warning_EntryMissing , entryMissing . getPath ( ) . toString ( ) ) ) ; } else { fLoadPathStatus . setWarning ( Messages . format ( NewWizardMessages . BuildPathsBlock_warning_EntriesMissing , String . valueOf ( nEntriesMissing ) ) ) ; } } updateBuildPathStatus ( ) ; } private void updateBuildPathStatus ( ) { List elements = fLoadPathList . getElements ( ) ; ILoadpathEntry [ ] entries = new ILoadpathEntry [ elements . size ( ) ] ; for ( int i = elements . size ( ) - ; i >= ; i -- ) { CPListElement currElement = ( CPListElement ) elements . get ( i ) ; entries [ i ] = currElement . getLoadpathEntry ( ) ; } IRubyModelStatus status = RubyConventions . validateLoadpath ( fCurrJProject , entries , fOutputLocationPath ) ; if ( ! status . isOK ( ) ) { fBuildPathStatus . setError ( status . getMessage ( ) ) ; return ; } fBuildPathStatus . setOK ( ) ; } public static void createProject ( IProject project , URI locationURI , IProgressMonitor monitor ) throws CoreException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( NewWizardMessages . BuildPathsBlock_operationdesc_project , ) ; try { if ( ! project . exists ( ) ) { IProjectDescription desc = project . getWorkspace ( ) . newProjectDescription ( project . getName ( ) ) ; if ( locationURI != null && ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getLocationURI ( ) . equals ( locationURI ) ) { locationURI = null ; } desc . setLocationURI ( locationURI ) ; project . create ( desc , monitor ) ; monitor = null ; } if ( ! project . isOpen ( ) ) { project . open ( monitor ) ; monitor = null ; } } finally { if ( monitor != null ) { monitor . done ( ) ; } } } public static void addRubyNature ( IProject project , IProgressMonitor monitor ) throws CoreException { if ( monitor != null && monitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } if ( ! project . hasNature ( RubyCore . NATURE_ID ) ) { IProjectDescription description = project . getDescription ( ) ; String [ ] prevNatures = description . getNatureIds ( ) ; String [ ] newNatures = new String [ prevNatures . length + ] ; System . arraycopy ( prevNatures , , newNatures , , prevNatures . length ) ; newNatures [ prevNatures . length ] = RubyCore . NATURE_ID ; description . setNatureIds ( newNatures ) ; project . setDescription ( description , monitor ) ; } else { if ( monitor != null ) { monitor . worked ( ) ; } } } public void configureRubyProject ( IProgressMonitor monitor ) throws CoreException , OperationCanceledException { flush ( fLoadPathList . getElements ( ) , getRubyProject ( ) , monitor ) ; initializeTimeStamps ( ) ; updateUI ( ) ; } public static void flush ( List classPathEntries , IRubyProject javaProject , IProgressMonitor monitor ) throws CoreException , OperationCanceledException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . setTaskName ( NewWizardMessages . BuildPathsBlock_operationdesc_java ) ; monitor . beginTask ( "" , classPathEntries . size ( ) * + ) ; try { IProject project = javaProject . getProject ( ) ; IPath projPath = project . getFullPath ( ) ; monitor . worked ( ) ; IWorkspaceRoot fWorkspaceRoot = RubyPlugin . getWorkspace ( ) . getRoot ( ) ; monitor . worked ( ) ; if ( monitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } int nEntries = classPathEntries . size ( ) ; ILoadpathEntry [ ] classpath = new ILoadpathEntry [ nEntries ] ; int i = ; for ( Iterator iter = classPathEntries . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement entry = ( CPListElement ) iter . next ( ) ; classpath [ i ] = entry . getLoadpathEntry ( ) ; i ++ ; IResource res = entry . getResource ( ) ; if ( res instanceof IFolder && entry . getLinkTarget ( ) == null && ! res . exists ( ) ) { CoreUtility . createFolder ( ( IFolder ) res , true , true , new SubProgressMonitor ( monitor , ) ) ; } else { monitor . worked ( ) ; } if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { monitor . worked ( ) ; IPath path = entry . getPath ( ) ; if ( projPath . equals ( path ) ) { monitor . worked ( ) ; continue ; } if ( projPath . isPrefixOf ( path ) ) { path = path . removeFirstSegments ( projPath . segmentCount ( ) ) ; } IFolder folder = project . getFolder ( path ) ; IPath orginalPath = entry . getOrginalPath ( ) ; if ( orginalPath == null ) { if ( ! folder . exists ( ) ) { if ( entry . getLinkTarget ( ) == null ) { CoreUtility . createFolder ( folder , true , true , new SubProgressMonitor ( monitor , ) ) ; } else { folder . createLink ( entry . getLinkTarget ( ) , IResource . ALLOW_MISSING_LOCAL , new SubProgressMonitor ( monitor , ) ) ; } } } else { if ( projPath . isPrefixOf ( orginalPath ) ) { orginalPath = orginalPath . removeFirstSegments ( projPath . segmentCount ( ) ) ; } IFolder orginalFolder = project . getFolder ( orginalPath ) ; if ( entry . getLinkTarget ( ) == null ) { if ( ! folder . exists ( ) ) { IPath parentPath = entry . getPath ( ) . removeLastSegments ( ) ; if ( projPath . isPrefixOf ( parentPath ) ) { parentPath = parentPath . removeFirstSegments ( projPath . segmentCount ( ) ) ; } if ( parentPath . segmentCount ( ) > ) { IFolder parentFolder = project . getFolder ( parentPath ) ; if ( ! parentFolder . exists ( ) ) { CoreUtility . createFolder ( parentFolder , true , true , new SubProgressMonitor ( monitor , ) ) ; } else { monitor . worked ( ) ; } } else { monitor . worked ( ) ; } orginalFolder . move ( entry . getPath ( ) , true , true , new SubProgressMonitor ( monitor , ) ) ; } } else { if ( ! folder . exists ( ) || ! entry . getLinkTarget ( ) . equals ( entry . getOrginalLinkTarget ( ) ) ) { orginalFolder . delete ( true , new SubProgressMonitor ( monitor , ) ) ; folder . createLink ( entry . getLinkTarget ( ) , IResource . ALLOW_MISSING_LOCAL , new SubProgressMonitor ( monitor , ) ) ; } } } } else { monitor . worked ( ) ; } if ( monitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } } javaProject . setRawLoadpath ( classpath , new SubProgressMonitor ( monitor , ) ) ; } finally { monitor . done ( ) ; } } public static boolean hasClassfiles ( IResource resource ) throws CoreException { if ( resource . isDerived ( ) ) { return true ; } if ( resource instanceof IContainer ) { IResource [ ] members = ( ( IContainer ) resource ) . members ( ) ; for ( int i = ; i < members . length ; i ++ ) { if ( hasClassfiles ( members [ i ] ) ) { return true ; } } } return false ; } public static void removeOldClassfiles ( IResource resource ) throws CoreException { if ( resource . isDerived ( ) ) { resource . delete ( false , null ) ; } else if ( resource instanceof IContainer ) { IResource [ ] members = ( ( IContainer ) resource ) . members ( ) ; for ( int i = ; i < members . length ; i ++ ) { removeOldClassfiles ( members [ i ] ) ; } } } public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery ( final Shell shell ) { return new IRemoveOldBinariesQuery ( ) { public boolean doQuery ( final IPath oldOutputLocation ) throws OperationCanceledException { final int [ ] res = new int [ ] { } ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { Shell sh = shell != null ? shell : RubyPlugin . getActiveWorkbenchShell ( ) ; String title = NewWizardMessages . BuildPathsBlock_RemoveBinariesDialog_title ; String message = Messages . format ( NewWizardMessages . BuildPathsBlock_RemoveBinariesDialog_description , oldOutputLocation . toString ( ) ) ; MessageDialog dialog = new MessageDialog ( sh , title , null , message , MessageDialog . QUESTION , new String [ ] { IDialogConstants . YES_LABEL , IDialogConstants . NO_LABEL , IDialogConstants . CANCEL_LABEL } , ) ; res [ ] = dialog . open ( ) ; } } ) ; if ( res [ ] == ) { return true ; } else if ( res [ ] == ) { return false ; } throw new OperationCanceledException ( ) ; } } ; } private void tabChanged ( Widget widget ) { if ( widget instanceof TabItem ) { TabItem tabItem = ( TabItem ) widget ; BuildPathBasePage newPage = ( BuildPathBasePage ) tabItem . getData ( ) ; if ( fCurrPage != null ) { List selection = fCurrPage . getSelection ( ) ; if ( ! selection . isEmpty ( ) ) { newPage . setSelection ( selection , false ) ; } } fCurrPage = newPage ; fPageIndex = tabItem . getParent ( ) . getSelectionIndex ( ) ; } } private int getPageIndex ( int entryKind ) { switch ( entryKind ) { case ILoadpathEntry . CPE_CONTAINER : case ILoadpathEntry . CPE_LIBRARY : case ILoadpathEntry . CPE_VARIABLE : return ; case ILoadpathEntry . CPE_PROJECT : return ; case ILoadpathEntry . CPE_SOURCE : return ; } return ; } private CPListElement findElement ( ILoadpathEntry entry ) { for ( int i = , len = fLoadPathList . getSize ( ) ; i < len ; i ++ ) { CPListElement curr = ( CPListElement ) fLoadPathList . getElement ( i ) ; if ( curr . getEntryKind ( ) == entry . getEntryKind ( ) && curr . getPath ( ) . equals ( entry . getPath ( ) ) ) { return curr ; } } return null ; } public void setElementToReveal ( ILoadpathEntry entry , String attributeKey ) { int pageIndex = getPageIndex ( entry . getEntryKind ( ) ) ; if ( fTabFolder == null ) { fPageIndex = pageIndex ; } else { fTabFolder . setSelection ( pageIndex ) ; CPListElement element = findElement ( entry ) ; if ( element != null ) { Object elementToSelect = element ; if ( attributeKey != null ) { Object attrib = element . findAttributeElement ( attributeKey ) ; if ( attrib != null ) { elementToSelect = attrib ; } } BuildPathBasePage page = ( BuildPathBasePage ) fTabFolder . getItem ( pageIndex ) . getData ( ) ; List selection = new ArrayList ( ) ; selection . add ( elementToSelect ) ; page . setSelection ( selection , true ) ; } } } public void addElement ( ILoadpathEntry entry ) { int pageIndex = getPageIndex ( entry . getEntryKind ( ) ) ; if ( fTabFolder == null ) { fPageIndex = pageIndex ; } else { fTabFolder . setSelection ( pageIndex ) ; Object page = fTabFolder . getItem ( pageIndex ) . getData ( ) ; if ( page instanceof LibrariesWorkbookPage ) { CPListElement element = CPListElement . createFromExisting ( entry , fCurrJProject ) ; ( ( LibrariesWorkbookPage ) page ) . addElement ( element ) ; } } } public boolean isOKStatus ( ) { return findMostSevereStatus ( ) . isOK ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; import org . rubypeople . rdt . ui . wizards . ILoadpathContainerPage ; import org . rubypeople . rdt . ui . wizards . ILoadpathContainerPageExtension ; import org . rubypeople . rdt . ui . wizards . NewElementWizardPage ; public class LoadpathContainerDefaultPage extends NewElementWizardPage implements ILoadpathContainerPage , ILoadpathContainerPageExtension { private StringDialogField fEntryField ; private ArrayList fUsedPaths ; public LoadpathContainerDefaultPage ( ) { super ( "" ) ; setTitle ( NewWizardMessages . LoadpathContainerDefaultPage_title ) ; setDescription ( NewWizardMessages . LoadpathContainerDefaultPage_description ) ; setImageDescriptor ( RubyPluginImages . DESC_WIZBAN_ADD_LIBRARY ) ; fUsedPaths = new ArrayList ( ) ; fEntryField = new StringDialogField ( ) ; fEntryField . setLabelText ( NewWizardMessages . LoadpathContainerDefaultPage_path_label ) ; fEntryField . setDialogFieldListener ( new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { validatePath ( ) ; } } ) ; validatePath ( ) ; } private void validatePath ( ) { StatusInfo status = new StatusInfo ( ) ; String str = fEntryField . getText ( ) ; if ( str . length ( ) == ) { status . setError ( NewWizardMessages . LoadpathContainerDefaultPage_path_error_enterpath ) ; } else if ( ! Path . ROOT . isValidPath ( str ) ) { status . setError ( NewWizardMessages . LoadpathContainerDefaultPage_path_error_invalidpath ) ; } else { IPath path = new Path ( str ) ; if ( path . segmentCount ( ) == ) { status . setError ( NewWizardMessages . LoadpathContainerDefaultPage_path_error_needssegment ) ; } else if ( fUsedPaths . contains ( path ) ) { status . setError ( NewWizardMessages . LoadpathContainerDefaultPage_path_error_alreadyexists ) ; } } updateStatus ( status ) ; } public void createControl ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; fEntryField . doFillIntoGrid ( composite , ) ; LayoutUtil . setHorizontalGrabbing ( fEntryField . getTextControl ( null ) ) ; fEntryField . setFocus ( ) ; setControl ( composite ) ; Dialog . applyDialogFont ( composite ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( composite , IRubyHelpContextIds . CLASSPATH_CONTAINER_DEFAULT_PAGE ) ; } public boolean finish ( ) { return true ; } public ILoadpathEntry getSelection ( ) { return RubyCore . newContainerEntry ( new Path ( fEntryField . getText ( ) ) ) ; } public void initialize ( IRubyProject project , ILoadpathEntry [ ] currentEntries ) { for ( int i = ; i < currentEntries . length ; i ++ ) { ILoadpathEntry curr = currentEntries [ i ] ; if ( curr . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) { fUsedPaths . add ( curr . getPath ( ) ) ; } } } public void setSelection ( ILoadpathEntry containerEntry ) { if ( containerEntry != null ) { fUsedPaths . remove ( containerEntry . getPath ( ) ) ; fEntryField . setText ( containerEntry . getPath ( ) . toString ( ) ) ; } else { fEntryField . setText ( "" ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public class EditFilterWizard extends BuildPathWizard { private SetFilterWizardPage fFilterPage ; private final IPath [ ] fOrginalInclusion , fOriginalExclusion ; public EditFilterWizard ( CPListElement [ ] existingEntries , CPListElement newEntry ) { super ( existingEntries , newEntry , NewWizardMessages . ExclusionInclusionDialog_title , null ) ; IPath [ ] inc = ( IPath [ ] ) newEntry . getAttribute ( CPListElement . INCLUSION ) ; fOrginalInclusion = new IPath [ inc . length ] ; System . arraycopy ( inc , , fOrginalInclusion , , inc . length ) ; IPath [ ] excl = ( IPath [ ] ) newEntry . getAttribute ( CPListElement . EXCLUSION ) ; fOriginalExclusion = new IPath [ excl . length ] ; System . arraycopy ( excl , , fOriginalExclusion , , excl . length ) ; } public void addPages ( ) { super . addPages ( ) ; fFilterPage = new SetFilterWizardPage ( getEntryToEdit ( ) , getExistingEntries ( ) ) ; addPage ( fFilterPage ) ; } public boolean performFinish ( ) { CPListElement entryToEdit = getEntryToEdit ( ) ; entryToEdit . setAttribute ( CPListElement . INCLUSION , fFilterPage . getInclusionPattern ( ) ) ; entryToEdit . setAttribute ( CPListElement . EXCLUSION , fFilterPage . getExclusionPattern ( ) ) ; return super . performFinish ( ) ; } public void cancel ( ) { CPListElement entryToEdit = getEntryToEdit ( ) ; entryToEdit . setAttribute ( CPListElement . INCLUSION , fOrginalInclusion ) ; entryToEdit . setAttribute ( CPListElement . EXCLUSION , fOriginalExclusion ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . WorkbenchRunnableAdapter ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . CheckedListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ITreeListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . TreeListDialogField ; import org . rubypeople . rdt . ui . wizards . BuildPathDialogAccess ; public class LibrariesWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList ; private IRubyProject fCurrJProject ; private TreeListDialogField fLibrariesList ; private Control fSWTControl ; private final int IDX_ADDEXT = ; private final int IDX_ADDVAR = ; private final int IDX_EDIT = ; private final int IDX_REMOVE = ; public LibrariesWorkbookPage ( CheckedListDialogField classPathList , IWorkbenchPreferenceContainer pageContainer ) { fClassPathList = classPathList ; fSWTControl = null ; String [ ] buttonLabels = new String [ ] { NewWizardMessages . LibrariesWorkbookPage_libraries_addextjar_button , NewWizardMessages . LibrariesWorkbookPage_libraries_addvariable_button , null , NewWizardMessages . LibrariesWorkbookPage_libraries_edit_button , NewWizardMessages . LibrariesWorkbookPage_libraries_remove_button , } ; LibrariesAdapter adapter = new LibrariesAdapter ( ) ; fLibrariesList = new TreeListDialogField ( adapter , buttonLabels , new CPListLabelProvider ( ) ) ; fLibrariesList . setDialogFieldListener ( adapter ) ; fLibrariesList . setLabelText ( NewWizardMessages . LibrariesWorkbookPage_libraries_label ) ; fLibrariesList . enableButton ( IDX_REMOVE , false ) ; fLibrariesList . enableButton ( IDX_EDIT , false ) ; fLibrariesList . setViewerSorter ( new CPListElementSorter ( ) ) ; } public void init ( IRubyProject jproject ) { fCurrJProject = jproject ; updateLibrariesList ( ) ; } private void updateLibrariesList ( ) { List cpelements = fClassPathList . getElements ( ) ; List libelements = new ArrayList ( cpelements . size ( ) ) ; int nElements = cpelements . size ( ) ; for ( int i = ; i < nElements ; i ++ ) { CPListElement cpe = ( CPListElement ) cpelements . get ( i ) ; if ( isEntryKind ( cpe . getEntryKind ( ) ) ) { libelements . add ( cpe ) ; } } fLibrariesList . setElements ( libelements ) ; } public Control getControl ( Composite parent ) { PixelConverter converter = new PixelConverter ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; LayoutUtil . doDefaultLayout ( composite , new DialogField [ ] { fLibrariesList } , true , SWT . DEFAULT , SWT . DEFAULT ) ; LayoutUtil . setHorizontalGrabbing ( fLibrariesList . getTreeControl ( null ) ) ; int buttonBarWidth = converter . convertWidthInCharsToPixels ( ) ; fLibrariesList . setButtonsMinWidth ( buttonBarWidth ) ; fLibrariesList . getTreeViewer ( ) . setSorter ( new CPListElementSorter ( ) ) ; fSWTControl = composite ; return composite ; } private Shell getShell ( ) { if ( fSWTControl != null ) { return fSWTControl . getShell ( ) ; } return RubyPlugin . getActiveWorkbenchShell ( ) ; } private class LibrariesAdapter implements IDialogFieldListener , ITreeListAdapter { private final Object [ ] EMPTY_ARR = new Object [ ] ; public void customButtonPressed ( TreeListDialogField field , int index ) { libaryPageCustomButtonPressed ( field , index ) ; } public void selectionChanged ( TreeListDialogField field ) { libaryPageSelectionChanged ( field ) ; } public void doubleClicked ( TreeListDialogField field ) { libaryPageDoubleClicked ( field ) ; } public void keyPressed ( TreeListDialogField field , KeyEvent event ) { libaryPageKeyPressed ( field , event ) ; } public Object [ ] getChildren ( TreeListDialogField field , Object element ) { if ( element instanceof CPListElement ) { return ( ( CPListElement ) element ) . getChildren ( false ) ; } return EMPTY_ARR ; } public Object getParent ( TreeListDialogField field , Object element ) { if ( element instanceof CPListElementAttribute ) { return ( ( CPListElementAttribute ) element ) . getParent ( ) ; } return null ; } public boolean hasChildren ( TreeListDialogField field , Object element ) { return getChildren ( field , element ) . length > ; } public void dialogFieldChanged ( DialogField field ) { libaryPageDialogFieldChanged ( field ) ; } } private void libaryPageCustomButtonPressed ( DialogField field , int index ) { CPListElement [ ] libentries = null ; switch ( index ) { case IDX_ADDEXT : libentries = openExtFolderDialog ( null ) ; break ; case IDX_ADDVAR : libentries = openVariableSelectionDialog ( null ) ; break ; case IDX_EDIT : editEntry ( ) ; return ; case IDX_REMOVE : removeEntry ( ) ; return ; } if ( libentries != null ) { int nElementsChosen = libentries . length ; List cplist = fLibrariesList . getElements ( ) ; List elementsToAdd = new ArrayList ( nElementsChosen ) ; for ( int i = ; i < nElementsChosen ; i ++ ) { CPListElement curr = libentries [ i ] ; if ( ! cplist . contains ( curr ) && ! elementsToAdd . contains ( curr ) ) { elementsToAdd . add ( curr ) ; } } fLibrariesList . addElements ( elementsToAdd ) ; fLibrariesList . postSetSelection ( new StructuredSelection ( libentries ) ) ; } } private CPListElement [ ] openExtFolderDialog ( CPListElement existing ) { if ( existing == null ) { IPath [ ] selected = BuildPathDialogAccess . chooseExternalFolderEntries ( getShell ( ) ) ; if ( selected != null ) { ArrayList res = new ArrayList ( ) ; for ( int i = ; i < selected . length ; i ++ ) { res . add ( new CPListElement ( fCurrJProject , ILoadpathEntry . CPE_LIBRARY , selected [ i ] , null ) ) ; } return ( CPListElement [ ] ) res . toArray ( new CPListElement [ res . size ( ) ] ) ; } } else { IPath configured = BuildPathDialogAccess . configureExternalFolderEntry ( getShell ( ) , existing . getPath ( ) ) ; if ( configured != null ) { return new CPListElement [ ] { new CPListElement ( fCurrJProject , ILoadpathEntry . CPE_LIBRARY , configured , null ) } ; } } return null ; } public void addElement ( CPListElement element ) { fLibrariesList . addElement ( element ) ; fLibrariesList . postSetSelection ( new StructuredSelection ( element ) ) ; } protected void libaryPageDoubleClicked ( TreeListDialogField field ) { List selection = fLibrariesList . getSelectedElements ( ) ; if ( canEdit ( selection ) ) { editEntry ( ) ; } } protected void libaryPageKeyPressed ( TreeListDialogField field , KeyEvent event ) { if ( field == fLibrariesList ) { if ( event . character == SWT . DEL && event . stateMask == ) { List selection = field . getSelectedElements ( ) ; if ( canRemove ( selection ) ) { removeEntry ( ) ; } } } } private void removeEntry ( ) { List selElements = fLibrariesList . getSelectedElements ( ) ; HashMap containerEntriesToUpdate = new HashMap ( ) ; for ( int i = selElements . size ( ) - ; i >= ; i -- ) { Object elem = selElements . get ( i ) ; if ( elem instanceof CPListElementAttribute ) { CPListElementAttribute attrib = ( CPListElementAttribute ) elem ; String key = attrib . getKey ( ) ; Object value = null ; attrib . getParent ( ) . setAttribute ( key , value ) ; selElements . remove ( i ) ; if ( attrib . getParent ( ) . getParentContainer ( ) instanceof CPListElement ) { CPListElement containerEntry = attrib . getParent ( ) ; HashSet changedAttributes = ( HashSet ) containerEntriesToUpdate . get ( containerEntry ) ; if ( changedAttributes == null ) { changedAttributes = new HashSet ( ) ; containerEntriesToUpdate . put ( containerEntry , changedAttributes ) ; } changedAttributes . add ( key ) ; } } } if ( selElements . isEmpty ( ) ) { fLibrariesList . refresh ( ) ; fClassPathList . dialogFieldChanged ( ) ; } else { fLibrariesList . removeElements ( selElements ) ; } for ( Iterator iter = containerEntriesToUpdate . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Map . Entry entry = ( Entry ) iter . next ( ) ; CPListElement curr = ( CPListElement ) entry . getKey ( ) ; HashSet attribs = ( HashSet ) entry . getValue ( ) ; String [ ] changedAttributes = ( String [ ] ) attribs . toArray ( new String [ attribs . size ( ) ] ) ; ILoadpathEntry changedEntry = curr . getLoadpathEntry ( ) ; updateContainerEntry ( changedEntry , changedAttributes , fCurrJProject , ( ( CPListElement ) curr . getParentContainer ( ) ) . getPath ( ) ) ; } } private boolean canRemove ( List selElements ) { if ( selElements . size ( ) == ) { return false ; } for ( int i = ; i < selElements . size ( ) ; i ++ ) { Object elem = selElements . get ( i ) ; if ( elem instanceof CPListElementAttribute ) { CPListElementAttribute attrib = ( CPListElementAttribute ) elem ; if ( attrib . isInNonModifiableContainer ( ) ) { return false ; } if ( attrib . getValue ( ) == null ) { return false ; } } else if ( elem instanceof CPListElement ) { CPListElement curr = ( CPListElement ) elem ; if ( curr . getParentContainer ( ) != null ) { return false ; } } else { return false ; } } return true ; } private void editEntry ( ) { List selElements = fLibrariesList . getSelectedElements ( ) ; if ( selElements . size ( ) != ) { return ; } Object elem = selElements . get ( ) ; if ( fLibrariesList . getIndexOfElement ( elem ) != - ) { editElementEntry ( ( CPListElement ) elem ) ; } } private void updateContainerEntry ( final ILoadpathEntry newEntry , final String [ ] changedAttributes , final IRubyProject jproject , final IPath containerPath ) { try { IWorkspaceRunnable runnable = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { BuildPathSupport . modifyLoadpathEntry ( null , newEntry , changedAttributes , jproject , containerPath , monitor ) ; } } ; PlatformUI . getWorkbench ( ) . getProgressService ( ) . run ( true , true , new WorkbenchRunnableAdapter ( runnable ) ) ; } catch ( InvocationTargetException e ) { String title = NewWizardMessages . LibrariesWorkbookPage_configurecontainer_error_title ; String message = NewWizardMessages . LibrariesWorkbookPage_configurecontainer_error_message ; ExceptionHandler . handle ( e , getShell ( ) , title , message ) ; } catch ( InterruptedException e ) { } } private void editElementEntry ( CPListElement elem ) { CPListElement [ ] res = null ; switch ( elem . getEntryKind ( ) ) { case ILoadpathEntry . CPE_LIBRARY : IResource resource = elem . getResource ( ) ; if ( resource == null ) { res = openExtFolderDialog ( elem ) ; } else if ( resource . getType ( ) == IResource . FOLDER ) { if ( resource . exists ( ) ) { res = openScriptFolderDialog ( elem ) ; } else { res = openNewScriptFolderDialog ( elem ) ; } } break ; case ILoadpathEntry . CPE_VARIABLE : res = openVariableSelectionDialog ( elem ) ; break ; } if ( res != null && res . length > ) { CPListElement curr = res [ ] ; curr . setExported ( elem . isExported ( ) ) ; fLibrariesList . replaceElement ( elem , curr ) ; if ( elem . getEntryKind ( ) == ILoadpathEntry . CPE_VARIABLE ) { fLibrariesList . refresh ( ) ; } } } private void libaryPageSelectionChanged ( DialogField field ) { updateEnabledState ( ) ; } private void updateEnabledState ( ) { List selElements = fLibrariesList . getSelectedElements ( ) ; fLibrariesList . enableButton ( IDX_EDIT , canEdit ( selElements ) ) ; fLibrariesList . enableButton ( IDX_REMOVE , canRemove ( selElements ) ) ; } private boolean canEdit ( List selElements ) { if ( selElements . size ( ) != ) { return false ; } Object elem = selElements . get ( ) ; if ( elem instanceof CPListElement ) { CPListElement curr = ( CPListElement ) elem ; return ! ( curr . getResource ( ) instanceof IFolder ) && curr . getParentContainer ( ) == null ; } if ( elem instanceof CPListElementAttribute ) { CPListElementAttribute attrib = ( CPListElementAttribute ) elem ; if ( attrib . isInNonModifiableContainer ( ) ) { return false ; } return true ; } return false ; } private void libaryPageDialogFieldChanged ( DialogField field ) { if ( fCurrJProject != null ) { updateLoadpathList ( ) ; } } private void updateLoadpathList ( ) { List projelements = fLibrariesList . getElements ( ) ; List cpelements = fClassPathList . getElements ( ) ; int nEntries = cpelements . size ( ) ; int lastRemovePos = nEntries ; for ( int i = nEntries - ; i >= ; i -- ) { CPListElement cpe = ( CPListElement ) cpelements . get ( i ) ; int kind = cpe . getEntryKind ( ) ; if ( isEntryKind ( kind ) ) { if ( ! projelements . remove ( cpe ) ) { cpelements . remove ( i ) ; lastRemovePos = i ; } } } cpelements . addAll ( lastRemovePos , projelements ) ; if ( lastRemovePos != nEntries || ! projelements . isEmpty ( ) ) { fClassPathList . setElements ( cpelements ) ; } } private CPListElement [ ] openNewScriptFolderDialog ( CPListElement existing ) { String title = ( existing == null ) ? NewWizardMessages . LibrariesWorkbookPage_NewClassFolderDialog_new_title : NewWizardMessages . LibrariesWorkbookPage_NewClassFolderDialog_edit_title ; IProject currProject = fCurrJProject . getProject ( ) ; NewContainerDialog dialog = new NewContainerDialog ( getShell ( ) , title , currProject , getUsedContainers ( existing ) , existing ) ; IPath projpath = currProject . getFullPath ( ) ; dialog . setMessage ( Messages . format ( NewWizardMessages . LibrariesWorkbookPage_NewClassFolderDialog_description , projpath . toString ( ) ) ) ; if ( dialog . open ( ) == Window . OK ) { IFolder folder = dialog . getFolder ( ) ; return new CPListElement [ ] { newCPLibraryElement ( folder ) } ; } return null ; } private CPListElement [ ] openScriptFolderDialog ( CPListElement existing ) { if ( existing == null ) { IPath [ ] selected = BuildPathDialogAccess . chooseSourceFolderEntries ( getShell ( ) , fCurrJProject . getPath ( ) , getUsedContainers ( existing ) ) ; if ( selected != null ) { IWorkspaceRoot root = fCurrJProject . getProject ( ) . getWorkspace ( ) . getRoot ( ) ; ArrayList res = new ArrayList ( ) ; for ( int i = ; i < selected . length ; i ++ ) { IPath curr = selected [ i ] ; IResource resource = root . findMember ( curr ) ; if ( resource instanceof IContainer ) { res . add ( newCPLibraryElement ( resource ) ) ; } } return ( CPListElement [ ] ) res . toArray ( new CPListElement [ res . size ( ) ] ) ; } } else { } return null ; } private IPath [ ] getUsedContainers ( CPListElement existing ) { ArrayList res = new ArrayList ( ) ; List cplist = fLibrariesList . getElements ( ) ; for ( int i = ; i < cplist . size ( ) ; i ++ ) { CPListElement elem = ( CPListElement ) cplist . get ( i ) ; if ( elem . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY && ( elem != existing ) ) { IResource resource = elem . getResource ( ) ; if ( resource instanceof IContainer && ! resource . equals ( existing ) ) { res . add ( resource . getFullPath ( ) ) ; } } } return ( IPath [ ] ) res . toArray ( new IPath [ res . size ( ) ] ) ; } private CPListElement newCPLibraryElement ( IResource res ) { return new CPListElement ( fCurrJProject , ILoadpathEntry . CPE_LIBRARY , res . getFullPath ( ) , res ) ; } public boolean isEntryKind ( int kind ) { return kind == ILoadpathEntry . CPE_LIBRARY || kind == ILoadpathEntry . CPE_VARIABLE || kind == ILoadpathEntry . CPE_CONTAINER ; } public List getSelection ( ) { return fLibrariesList . getSelectedElements ( ) ; } public void setSelection ( List selElements , boolean expand ) { fLibrariesList . selectElements ( new StructuredSelection ( selElements ) ) ; if ( expand ) { for ( int i = ; i < selElements . size ( ) ; i ++ ) { fLibrariesList . expandElement ( selElements . get ( i ) , ) ; } } } private CPListElement [ ] openVariableSelectionDialog ( CPListElement existing ) { List existingElements = fLibrariesList . getElements ( ) ; ArrayList existingPaths = new ArrayList ( existingElements . size ( ) ) ; for ( int i = ; i < existingElements . size ( ) ; i ++ ) { CPListElement elem = ( CPListElement ) existingElements . get ( i ) ; if ( elem . getEntryKind ( ) == ILoadpathEntry . CPE_VARIABLE ) { existingPaths . add ( elem . getPath ( ) ) ; } } IPath [ ] existingPathsArray = ( IPath [ ] ) existingPaths . toArray ( new IPath [ existingPaths . size ( ) ] ) ; if ( existing == null ) { IPath [ ] paths = BuildPathDialogAccess . chooseVariableEntries ( getShell ( ) , existingPathsArray ) ; if ( paths != null ) { ArrayList result = new ArrayList ( ) ; for ( int i = ; i < paths . length ; i ++ ) { CPListElement elem = new CPListElement ( fCurrJProject , ILoadpathEntry . CPE_VARIABLE , paths [ i ] , null ) ; IPath resolvedPath = RubyCore . getResolvedVariablePath ( paths [ i ] ) ; elem . setIsMissing ( ( resolvedPath == null ) || ! resolvedPath . toFile ( ) . exists ( ) ) ; if ( ! existingElements . contains ( elem ) ) { result . add ( elem ) ; } } return ( CPListElement [ ] ) result . toArray ( new CPListElement [ result . size ( ) ] ) ; } } else { IPath path = BuildPathDialogAccess . configureVariableEntry ( getShell ( ) , existing . getPath ( ) , existingPathsArray ) ; if ( path != null ) { CPListElement elem = new CPListElement ( fCurrJProject , ILoadpathEntry . CPE_VARIABLE , path , null ) ; return new CPListElement [ ] { elem } ; } } return null ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; public class CPUserLibraryElement { private class UpdatedLoadpathContainer implements ILoadpathContainer { public ILoadpathEntry [ ] getLoadpathEntries ( ) { CPListElement [ ] children = getChildren ( ) ; ILoadpathEntry [ ] entries = new ILoadpathEntry [ children . length ] ; for ( int i = ; i < entries . length ; i ++ ) { entries [ i ] = children [ i ] . getLoadpathEntry ( ) ; } return entries ; } public String getDescription ( ) { return getName ( ) ; } public int getKind ( ) { return isSystemLibrary ( ) ? ILoadpathContainer . K_SYSTEM : K_APPLICATION ; } public IPath getPath ( ) { return CPUserLibraryElement . this . getPath ( ) ; } } private String fName ; private List fChildren ; private boolean fIsSystemLibrary ; public CPUserLibraryElement ( String name , ILoadpathContainer container , IRubyProject project ) { fName = name ; fChildren = new ArrayList ( ) ; if ( container != null ) { ILoadpathEntry [ ] entries = container . getLoadpathEntries ( ) ; CPListElement [ ] res = new CPListElement [ entries . length ] ; for ( int i = ; i < res . length ; i ++ ) { ILoadpathEntry curr = entries [ i ] ; CPListElement elem = CPListElement . createFromExisting ( this , curr , project ) ; fChildren . add ( elem ) ; } fIsSystemLibrary = container . getKind ( ) == ILoadpathContainer . K_SYSTEM ; } else { fIsSystemLibrary = false ; } } public CPUserLibraryElement ( String name , boolean isSystemLibrary , CPListElement [ ] children ) { fName = name ; fChildren = new ArrayList ( ) ; if ( children != null ) { for ( int i = ; i < children . length ; i ++ ) { fChildren . add ( children [ i ] ) ; } } fIsSystemLibrary = isSystemLibrary ; } public CPListElement [ ] getChildren ( ) { return ( CPListElement [ ] ) fChildren . toArray ( new CPListElement [ fChildren . size ( ) ] ) ; } public String getName ( ) { return fName ; } public IPath getPath ( ) { return new Path ( RubyCore . USER_LIBRARY_CONTAINER_ID ) . append ( fName ) ; } public boolean isSystemLibrary ( ) { return fIsSystemLibrary ; } public void add ( CPListElement element ) { if ( ! fChildren . contains ( element ) ) { fChildren . add ( element ) ; } } private List moveUp ( List elements , List move ) { int nElements = elements . size ( ) ; List res = new ArrayList ( nElements ) ; Object floating = null ; for ( int i = ; i < nElements ; i ++ ) { Object curr = elements . get ( i ) ; if ( move . contains ( curr ) ) { res . add ( curr ) ; } else { if ( floating != null ) { res . add ( floating ) ; } floating = curr ; } } if ( floating != null ) { res . add ( floating ) ; } return res ; } public void moveUp ( List toMoveUp ) { if ( toMoveUp . size ( ) > ) { fChildren = moveUp ( fChildren , toMoveUp ) ; } } public void moveDown ( List toMoveDown ) { if ( toMoveDown . size ( ) > ) { Collections . reverse ( fChildren ) ; fChildren = moveUp ( fChildren , toMoveDown ) ; Collections . reverse ( fChildren ) ; } } public void remove ( CPListElement element ) { fChildren . remove ( element ) ; } public void replace ( CPListElement existingElement , CPListElement element ) { if ( fChildren . contains ( element ) ) { fChildren . remove ( existingElement ) ; } else { int index = fChildren . indexOf ( existingElement ) ; if ( index != - ) { fChildren . set ( index , element ) ; } else { fChildren . add ( element ) ; } } } private void copyAttribute ( CPListElement source , CPListElement target , String attributeName ) { Object value = source . getAttribute ( attributeName ) ; if ( value != null ) { target . setAttribute ( attributeName , value ) ; } } public ILoadpathContainer getUpdatedContainer ( ) { return new UpdatedLoadpathContainer ( ) ; } public boolean hasChanges ( ILoadpathContainer oldContainer ) { if ( oldContainer == null || ( oldContainer . getKind ( ) == ILoadpathContainer . K_SYSTEM ) != fIsSystemLibrary ) { return true ; } ILoadpathEntry [ ] oldEntries = oldContainer . getLoadpathEntries ( ) ; if ( fChildren . size ( ) != oldEntries . length ) { return true ; } for ( int i = ; i < oldEntries . length ; i ++ ) { CPListElement child = ( CPListElement ) fChildren . get ( i ) ; if ( ! child . getLoadpathEntry ( ) . equals ( oldEntries [ i ] ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . io . File ; import java . util . List ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . IUIConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; public class VariableCreationDialog extends StatusDialog { private IDialogSettings fDialogSettings ; private StringDialogField fNameField ; private StatusInfo fNameStatus ; private StringButtonDialogField fPathField ; private StatusInfo fPathStatus ; private SelectionButtonDialogField fDirButton ; private CPVariableElement fElement ; private List fExistingNames ; public VariableCreationDialog ( Shell parent , CPVariableElement element , List existingNames ) { super ( parent ) ; if ( element == null ) { setTitle ( NewWizardMessages . VariableCreationDialog_titlenew ) ; } else { setTitle ( NewWizardMessages . VariableCreationDialog_titleedit ) ; } fDialogSettings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; fElement = element ; fNameStatus = new StatusInfo ( ) ; fPathStatus = new StatusInfo ( ) ; NewVariableAdapter adapter = new NewVariableAdapter ( ) ; fNameField = new StringDialogField ( ) ; fNameField . setDialogFieldListener ( adapter ) ; fNameField . setLabelText ( NewWizardMessages . VariableCreationDialog_name_label ) ; fPathField = new StringButtonDialogField ( adapter ) ; fPathField . setDialogFieldListener ( adapter ) ; fPathField . setLabelText ( NewWizardMessages . VariableCreationDialog_path_label ) ; fPathField . setButtonLabel ( NewWizardMessages . VariableCreationDialog_path_file_button ) ; fDirButton = new SelectionButtonDialogField ( SWT . PUSH ) ; fDirButton . setDialogFieldListener ( adapter ) ; fDirButton . setLabelText ( NewWizardMessages . VariableCreationDialog_path_dir_button ) ; fExistingNames = existingNames ; if ( element != null ) { fNameField . setText ( element . getName ( ) ) ; fPathField . setText ( element . getPath ( ) . toString ( ) ) ; fExistingNames . remove ( element . getName ( ) ) ; } else { fNameField . setText ( "" ) ; fPathField . setText ( "" ) ; } } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . VARIABLE_CREATION_DIALOG ) ; } public CPVariableElement getClasspathElement ( ) { return new CPVariableElement ( fNameField . getText ( ) , new IPath [ ] { new Path ( fPathField . getText ( ) ) } , false ) ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; inner . setFont ( composite . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginWidth = ; layout . marginHeight = ; layout . numColumns = ; inner . setLayout ( layout ) ; int fieldWidthHint = convertWidthInCharsToPixels ( ) ; fNameField . doFillIntoGrid ( inner , ) ; LayoutUtil . setWidthHint ( fNameField . getTextControl ( null ) , fieldWidthHint ) ; LayoutUtil . setHorizontalGrabbing ( fNameField . getTextControl ( null ) ) ; DialogField . createEmptySpace ( inner , ) ; fPathField . doFillIntoGrid ( inner , ) ; LayoutUtil . setWidthHint ( fPathField . getTextControl ( null ) , fieldWidthHint ) ; DialogField . createEmptySpace ( inner , ) ; fDirButton . doFillIntoGrid ( inner , ) ; DialogField focusField = ( fElement == null ) ? fNameField : fPathField ; focusField . postSetFocusOnDialogField ( parent . getDisplay ( ) ) ; applyDialogFont ( composite ) ; return composite ; } private class NewVariableAdapter implements IDialogFieldListener , IStringButtonAdapter { public void dialogFieldChanged ( DialogField field ) { doFieldUpdated ( field ) ; } public void changeControlPressed ( DialogField field ) { doChangeControlPressed ( field ) ; } } private void doChangeControlPressed ( DialogField field ) { if ( field == fPathField ) { IPath path = chooseExtJarFile ( ) ; if ( path != null ) { fPathField . setText ( path . toString ( ) ) ; } } } private void doFieldUpdated ( DialogField field ) { if ( field == fNameField ) { fNameStatus = nameUpdated ( ) ; } else if ( field == fPathField ) { fPathStatus = pathUpdated ( ) ; } else if ( field == fDirButton ) { IPath path = chooseExtDirectory ( ) ; if ( path != null ) { fPathField . setText ( path . toString ( ) ) ; } } updateStatus ( StatusUtil . getMoreSevere ( fPathStatus , fNameStatus ) ) ; } private StatusInfo nameUpdated ( ) { StatusInfo status = new StatusInfo ( ) ; String name = fNameField . getText ( ) ; if ( name . length ( ) == ) { status . setError ( NewWizardMessages . VariableCreationDialog_error_entername ) ; return status ; } if ( name . trim ( ) . length ( ) != name . length ( ) ) { status . setError ( NewWizardMessages . VariableCreationDialog_error_whitespace ) ; } else if ( ! Path . ROOT . isValidSegment ( name ) ) { status . setError ( NewWizardMessages . VariableCreationDialog_error_invalidname ) ; } else if ( nameConflict ( name ) ) { status . setError ( NewWizardMessages . VariableCreationDialog_error_nameexists ) ; } return status ; } private boolean nameConflict ( String name ) { if ( fElement != null && fElement . getName ( ) . equals ( name ) ) { return false ; } for ( int i = ; i < fExistingNames . size ( ) ; i ++ ) { CPVariableElement elem = ( CPVariableElement ) fExistingNames . get ( i ) ; if ( name . equals ( elem . getName ( ) ) ) { return true ; } } return false ; } private StatusInfo pathUpdated ( ) { StatusInfo status = new StatusInfo ( ) ; String path = fPathField . getText ( ) ; if ( path . length ( ) > ) { if ( ! Path . ROOT . isValidPath ( path ) ) { status . setError ( NewWizardMessages . VariableCreationDialog_error_invalidpath ) ; } else if ( ! new File ( path ) . exists ( ) ) { status . setWarning ( NewWizardMessages . VariableCreationDialog_warning_pathnotexists ) ; } } return status ; } private String getInitPath ( ) { String initPath = fPathField . getText ( ) ; if ( initPath . length ( ) == ) { initPath = fDialogSettings . get ( IUIConstants . DIALOGSTORE_LASTEXTJAR ) ; if ( initPath == null ) { initPath = "" ; } } return initPath ; } private IPath chooseExtJarFile ( ) { String initPath = getInitPath ( ) ; FileDialog dialog = new FileDialog ( getShell ( ) ) ; dialog . setText ( NewWizardMessages . VariableCreationDialog_extjardialog_text ) ; dialog . setFilterExtensions ( new String [ ] { "" } ) ; dialog . setFilterPath ( initPath ) ; String res = dialog . open ( ) ; if ( res != null ) { fDialogSettings . put ( IUIConstants . DIALOGSTORE_LASTEXTJAR , dialog . getFilterPath ( ) ) ; return Path . fromOSString ( res ) . makeAbsolute ( ) ; } return null ; } private IPath chooseExtDirectory ( ) { String initPath = getInitPath ( ) ; DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) ) ; dialog . setText ( NewWizardMessages . VariableCreationDialog_extdirdialog_text ) ; dialog . setMessage ( NewWizardMessages . VariableCreationDialog_extdirdialog_message ) ; dialog . setFilterPath ( initPath ) ; String res = dialog . open ( ) ; if ( res != null ) { fDialogSettings . put ( IUIConstants . DIALOGSTORE_LASTEXTJAR , dialog . getFilterPath ( ) ) ; return Path . fromOSString ( res ) ; } return null ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . jface . viewers . ContentViewer ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . rubypeople . rdt . core . ILoadpathEntry ; public class CPListElementSorter extends ViewerSorter { private static final int SOURCE = ; private static final int PROJECT = ; private static final int LIBRARY = ; private static final int VARIABLE = ; private static final int CONTAINER = ; private static final int ATTRIBUTE = ; private static final int CONTAINER_ENTRY = ; private static final int OTHER = ; public int category ( Object obj ) { if ( obj instanceof CPListElement ) { CPListElement element = ( CPListElement ) obj ; if ( element . getParentContainer ( ) != null ) { return CONTAINER_ENTRY ; } switch ( element . getEntryKind ( ) ) { case ILoadpathEntry . CPE_LIBRARY : return LIBRARY ; case ILoadpathEntry . CPE_PROJECT : return PROJECT ; case ILoadpathEntry . CPE_SOURCE : return SOURCE ; case ILoadpathEntry . CPE_VARIABLE : return VARIABLE ; case ILoadpathEntry . CPE_CONTAINER : return CONTAINER ; } } else if ( obj instanceof CPListElementAttribute ) { return ATTRIBUTE ; } return OTHER ; } public int compare ( Viewer viewer , Object e1 , Object e2 ) { int cat1 = category ( e1 ) ; int cat2 = category ( e2 ) ; if ( cat1 != cat2 ) return cat1 - cat2 ; if ( cat1 == ATTRIBUTE || cat1 == CONTAINER_ENTRY ) { return ; } if ( viewer instanceof ContentViewer ) { IBaseLabelProvider prov = ( ( ContentViewer ) viewer ) . getLabelProvider ( ) ; if ( prov instanceof ILabelProvider ) { ILabelProvider lprov = ( ILabelProvider ) prov ; String name1 = lprov . getText ( e1 ) ; String name2 = lprov . getText ( e2 ) ; return collator . compare ( name1 , name2 ) ; } } return ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTreeViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . ui . dialogs . NewFolderDialog ; import org . eclipse . ui . dialogs . SelectionStatusDialog ; import org . eclipse . ui . views . navigator . ResourceSorter ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public class MultipleFolderSelectionDialog extends SelectionStatusDialog implements ISelectionChangedListener { private CheckboxTreeViewer fViewer ; private ILabelProvider fLabelProvider ; private ITreeContentProvider fContentProvider ; private List fFilters ; private Object fInput ; private Button fNewFolderButton ; private IContainer fSelectedContainer ; private Set fExisting ; private Object fFocusElement ; public MultipleFolderSelectionDialog ( Shell parent , ILabelProvider labelProvider , ITreeContentProvider contentProvider ) { super ( parent ) ; fLabelProvider = labelProvider ; fContentProvider = contentProvider ; setSelectionResult ( null ) ; setStatusLineAboveButtons ( true ) ; int shellStyle = getShellStyle ( ) ; setShellStyle ( shellStyle | SWT . MAX | SWT . RESIZE ) ; fExisting = null ; fFocusElement = null ; fFilters = null ; } public void setExisting ( Object [ ] existing ) { fExisting = new HashSet ( ) ; for ( int i = ; i < existing . length ; i ++ ) { fExisting . add ( existing [ i ] ) ; } } public void setInput ( Object input ) { fInput = input ; } public void addFilter ( ViewerFilter filter ) { if ( fFilters == null ) fFilters = new ArrayList ( ) ; fFilters . add ( filter ) ; } protected void cancelPressed ( ) { setSelectionResult ( null ) ; super . cancelPressed ( ) ; } protected void computeResult ( ) { Object [ ] checked = fViewer . getCheckedElements ( ) ; if ( fExisting == null ) { if ( checked . length == ) { checked = null ; } } else { ArrayList res = new ArrayList ( ) ; for ( int i = ; i < checked . length ; i ++ ) { Object elem = checked [ i ] ; if ( ! fExisting . contains ( elem ) ) { res . add ( elem ) ; } } if ( ! res . isEmpty ( ) ) { checked = res . toArray ( ) ; } else { checked = null ; } } setSelectionResult ( checked ) ; } private void access$superCreate ( ) { super . create ( ) ; } public void create ( ) { BusyIndicator . showWhile ( null , new Runnable ( ) { public void run ( ) { access$superCreate ( ) ; fViewer . setCheckedElements ( getInitialElementSelections ( ) . toArray ( ) ) ; fViewer . expandToLevel ( ) ; if ( fExisting != null ) { for ( Iterator iter = fExisting . iterator ( ) ; iter . hasNext ( ) ; ) { fViewer . reveal ( iter . next ( ) ) ; } } updateOKStatus ( ) ; } } ) ; } protected CheckboxTreeViewer createTreeViewer ( Composite parent ) { fViewer = new CheckboxTreeViewer ( parent , SWT . BORDER ) ; fViewer . setContentProvider ( fContentProvider ) ; fViewer . setLabelProvider ( fLabelProvider ) ; fViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { updateOKStatus ( ) ; } } ) ; fViewer . setSorter ( new ResourceSorter ( ResourceSorter . NAME ) ) ; if ( fFilters != null ) { for ( int i = ; i != fFilters . size ( ) ; i ++ ) fViewer . addFilter ( ( ViewerFilter ) fFilters . get ( i ) ) ; } fViewer . setInput ( fInput ) ; return fViewer ; } protected void updateOKStatus ( ) { computeResult ( ) ; if ( getResult ( ) != null ) { updateStatus ( new StatusInfo ( ) ) ; } else { updateStatus ( new StatusInfo ( IStatus . ERROR , "" ) ) ; } } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; createMessageArea ( composite ) ; CheckboxTreeViewer treeViewer = createTreeViewer ( composite ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . widthHint = convertWidthInCharsToPixels ( ) ; data . heightHint = convertHeightInCharsToPixels ( ) ; Tree treeWidget = treeViewer . getTree ( ) ; treeWidget . setLayoutData ( data ) ; treeWidget . setFont ( composite . getFont ( ) ) ; Button button = new Button ( composite , SWT . PUSH ) ; button . setText ( NewWizardMessages . MultipleFolderSelectionDialog_button ) ; button . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent event ) { newFolderButtonPressed ( ) ; } } ) ; button . setFont ( composite . getFont ( ) ) ; fNewFolderButton = button ; treeViewer . addSelectionChangedListener ( this ) ; if ( fExisting != null ) { Object [ ] existing = fExisting . toArray ( ) ; treeViewer . setGrayedElements ( existing ) ; setInitialSelections ( existing ) ; } if ( fFocusElement != null ) { treeViewer . setSelection ( new StructuredSelection ( fFocusElement ) , true ) ; } treeViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { forceExistingChecked ( event ) ; } } ) ; applyDialogFont ( composite ) ; return composite ; } protected void forceExistingChecked ( CheckStateChangedEvent event ) { if ( fExisting != null ) { Object elem = event . getElement ( ) ; if ( fExisting . contains ( elem ) ) { fViewer . setChecked ( elem , true ) ; } } } private void updateNewFolderButtonState ( ) { IStructuredSelection selection = ( IStructuredSelection ) fViewer . getSelection ( ) ; fSelectedContainer = null ; if ( selection . size ( ) == ) { Object first = selection . getFirstElement ( ) ; if ( first instanceof IContainer ) { fSelectedContainer = ( IContainer ) first ; } } fNewFolderButton . setEnabled ( fSelectedContainer != null ) ; } protected void newFolderButtonPressed ( ) { Object createdFolder = createFolder ( fSelectedContainer ) ; if ( createdFolder != null ) { CheckboxTreeViewer treeViewer = fViewer ; treeViewer . refresh ( fSelectedContainer ) ; treeViewer . reveal ( createdFolder ) ; treeViewer . setChecked ( createdFolder , true ) ; treeViewer . setSelection ( new StructuredSelection ( createdFolder ) ) ; updateOKStatus ( ) ; } } protected Object createFolder ( IContainer container ) { NewFolderDialog dialog = new NewFolderDialog ( getShell ( ) , container ) ; if ( dialog . open ( ) == Window . OK ) { return dialog . getResult ( ) [ ] ; } return null ; } public void selectionChanged ( SelectionChangedEvent event ) { updateNewFolderButtonState ( ) ; } public void setInitialFocus ( Object focusElement ) { fFocusElement = focusElement ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . core . runtime . Assert ; import org . rubypeople . rdt . core . ILoadpathAttribute ; import org . rubypeople . rdt . core . RubyCore ; public class CPListElementAttribute { private CPListElement fParent ; private String fKey ; private Object fValue ; private final boolean fBuiltIn ; public CPListElementAttribute ( CPListElement parent , String key , Object value , boolean builtIn ) { fKey = key ; fValue = value ; fParent = parent ; fBuiltIn = builtIn ; if ( ! builtIn ) { Assert . isTrue ( value instanceof String || value == null ) ; } } public ILoadpathAttribute newLoadpathAttribute ( ) { Assert . isTrue ( ! fBuiltIn ) ; if ( fValue != null ) { return RubyCore . newLoadpathAttribute ( fKey , ( String ) fValue ) ; } return null ; } public CPListElement getParent ( ) { return fParent ; } public boolean isBuiltIn ( ) { return fBuiltIn ; } public boolean isInNonModifiableContainer ( ) { return fParent . isInNonModifiableContainer ( ) ; } public String getKey ( ) { return fKey ; } public Object getValue ( ) { return fValue ; } public void setValue ( Object value ) { fValue = value ; } public boolean equals ( Object obj ) { if ( ! ( obj instanceof CPListElementAttribute ) ) return false ; CPListElementAttribute attrib = ( CPListElementAttribute ) obj ; return attrib . fKey == this . fKey && attrib . getParent ( ) . getPath ( ) . equals ( fParent . getPath ( ) ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . List ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; public class VariablePathDialogField extends StringButtonDialogField { public static class ChooseVariableDialog extends StatusDialog implements ISelectionChangedListener , IDoubleClickListener { private VariableBlock fVariableBlock ; public ChooseVariableDialog ( Shell parent , String variableSelection ) { super ( parent ) ; int shellStyle = getShellStyle ( ) ; setShellStyle ( shellStyle | SWT . MAX | SWT . RESIZE ) ; setTitle ( NewWizardMessages . VariablePathDialogField_variabledialog_title ) ; fVariableBlock = new VariableBlock ( false , variableSelection ) ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Control control = fVariableBlock . createContents ( composite ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . widthHint = convertWidthInCharsToPixels ( ) ; data . heightHint = convertHeightInCharsToPixels ( ) ; control . setLayoutData ( data ) ; fVariableBlock . addDoubleClickListener ( this ) ; fVariableBlock . addSelectionChangedListener ( this ) ; applyDialogFont ( composite ) ; return composite ; } protected void okPressed ( ) { fVariableBlock . performOk ( ) ; super . okPressed ( ) ; } public String getSelectedVariable ( ) { List elements = fVariableBlock . getSelectedElements ( ) ; return ( ( CPVariableElement ) elements . get ( ) ) . getName ( ) ; } public void doubleClick ( DoubleClickEvent event ) { if ( getStatus ( ) . isOK ( ) ) { okPressed ( ) ; } } public void selectionChanged ( SelectionChangedEvent event ) { List elements = fVariableBlock . getSelectedElements ( ) ; StatusInfo status = new StatusInfo ( ) ; if ( elements . size ( ) != ) { status . setError ( "" ) ; } updateStatus ( status ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . CHOOSE_VARIABLE_DIALOG ) ; } } private Button fBrowseVariableButton ; private String fVariableButtonLabel ; public VariablePathDialogField ( IStringButtonAdapter adapter ) { super ( adapter ) ; } public void setVariableButtonLabel ( String label ) { fVariableButtonLabel = label ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; Label label = getLabelControl ( parent ) ; label . setLayoutData ( gridDataForLabel ( ) ) ; Text text = getTextControl ( parent ) ; text . setLayoutData ( gridDataForText ( nColumns - ) ) ; Button variableButton = getBrowseVariableControl ( parent ) ; variableButton . setLayoutData ( gridDataForButton ( variableButton , ) ) ; Button browseButton = getChangeControl ( parent ) ; browseButton . setLayoutData ( gridDataForButton ( browseButton , ) ) ; return new Control [ ] { label , text , variableButton , browseButton } ; } public int getNumberOfControls ( ) { return ; } public Button getBrowseVariableControl ( Composite parent ) { if ( fBrowseVariableButton == null ) { assertCompositeNotNull ( parent ) ; fBrowseVariableButton = new Button ( parent , SWT . PUSH ) ; fBrowseVariableButton . setText ( fVariableButtonLabel ) ; fBrowseVariableButton . setEnabled ( isEnabled ( ) ) ; fBrowseVariableButton . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { chooseVariablePressed ( ) ; } public void widgetSelected ( SelectionEvent e ) { chooseVariablePressed ( ) ; } } ) ; } return fBrowseVariableButton ; } public IPath getPath ( ) { return new Path ( getText ( ) ) ; } public String getVariable ( ) { IPath path = getPath ( ) ; if ( ! path . isEmpty ( ) ) { return path . segment ( ) ; } return null ; } public IPath getPathExtension ( ) { return new Path ( getText ( ) ) . removeFirstSegments ( ) . setDevice ( null ) ; } public IPath getResolvedPath ( ) { String variable = getVariable ( ) ; if ( variable != null ) { IPath path = RubyCore . getLoadpathVariable ( variable ) [ ] ; if ( path != null ) { return path . append ( getPathExtension ( ) ) ; } } return null ; } private Shell getShell ( ) { if ( fBrowseVariableButton != null ) { return fBrowseVariableButton . getShell ( ) ; } return RubyPlugin . getActiveWorkbenchShell ( ) ; } private void chooseVariablePressed ( ) { String variable = getVariable ( ) ; ChooseVariableDialog dialog = new ChooseVariableDialog ( getShell ( ) , variable ) ; if ( dialog . open ( ) == Window . OK ) { IPath newPath = new Path ( dialog . getSelectedVariable ( ) ) . append ( getPathExtension ( ) ) ; setText ( newPath . toString ( ) ) ; } } protected void updateEnableState ( ) { super . updateEnableState ( ) ; if ( isOkToUse ( fBrowseVariableButton ) ) { fBrowseVariableButton . setEnabled ( isEnabled ( ) ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; public class NewContainerDialog extends StatusDialog { private StringDialogField fContainerDialogField ; private StatusInfo fContainerFieldStatus ; private IFolder fFolder ; private IPath [ ] fExistingFolders ; private IProject fCurrProject ; public NewContainerDialog ( Shell parent , String title , IProject project , IPath [ ] existingFolders , CPListElement entryToEdit ) { super ( parent ) ; setTitle ( title ) ; fContainerFieldStatus = new StatusInfo ( ) ; SourceContainerAdapter adapter = new SourceContainerAdapter ( ) ; fContainerDialogField = new StringDialogField ( ) ; fContainerDialogField . setDialogFieldListener ( adapter ) ; fFolder = null ; fExistingFolders = existingFolders ; fCurrProject = project ; if ( entryToEdit == null ) { fContainerDialogField . setText ( "" ) ; } else { fContainerDialogField . setText ( entryToEdit . getPath ( ) . removeFirstSegments ( ) . toString ( ) ) ; } } public void setMessage ( String message ) { fContainerDialogField . setLabelText ( message ) ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; int widthHint = convertWidthInCharsToPixels ( ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; inner . setLayout ( layout ) ; fContainerDialogField . doFillIntoGrid ( inner , ) ; LayoutUtil . setWidthHint ( fContainerDialogField . getLabelControl ( null ) , widthHint ) ; LayoutUtil . setWidthHint ( fContainerDialogField . getTextControl ( null ) , widthHint ) ; LayoutUtil . setHorizontalGrabbing ( fContainerDialogField . getTextControl ( null ) ) ; fContainerDialogField . postSetFocusOnDialogField ( parent . getDisplay ( ) ) ; applyDialogFont ( composite ) ; return composite ; } private class SourceContainerAdapter implements IDialogFieldListener { public void dialogFieldChanged ( DialogField field ) { doStatusLineUpdate ( ) ; } } protected void doStatusLineUpdate ( ) { checkIfPathValid ( ) ; updateStatus ( fContainerFieldStatus ) ; } protected void checkIfPathValid ( ) { fFolder = null ; String pathStr = fContainerDialogField . getText ( ) ; if ( pathStr . length ( ) == ) { fContainerFieldStatus . setError ( NewWizardMessages . NewContainerDialog_error_enterpath ) ; return ; } IPath path = fCurrProject . getFullPath ( ) . append ( pathStr ) ; IWorkspace workspace = fCurrProject . getWorkspace ( ) ; IStatus pathValidation = workspace . validatePath ( path . toString ( ) , IResource . FOLDER ) ; if ( ! pathValidation . isOK ( ) ) { fContainerFieldStatus . setError ( Messages . format ( NewWizardMessages . NewContainerDialog_error_invalidpath , pathValidation . getMessage ( ) ) ) ; return ; } IFolder folder = fCurrProject . getFolder ( pathStr ) ; if ( isFolderExisting ( folder ) ) { fContainerFieldStatus . setError ( NewWizardMessages . NewContainerDialog_error_pathexists ) ; return ; } fContainerFieldStatus . setOK ( ) ; fFolder = folder ; } private boolean isFolderExisting ( IFolder folder ) { for ( int i = ; i < fExistingFolders . length ; i ++ ) { if ( folder . getFullPath ( ) . equals ( fExistingFolders [ i ] ) ) { return true ; } } return false ; } public IFolder getFolder ( ) { return fFolder ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . NEW_CONTAINER_DIALOG ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; public class ExclusionInclusionDialog extends StatusDialog { private static class ExclusionInclusionLabelProvider extends LabelProvider { private Image fElementImage ; public ExclusionInclusionLabelProvider ( ImageDescriptor descriptor ) { ImageDescriptorRegistry registry = RubyPlugin . getImageDescriptorRegistry ( ) ; fElementImage = registry . get ( descriptor ) ; } public Image getImage ( Object element ) { return fElementImage ; } public String getText ( Object element ) { return ( String ) element ; } } private ListDialogField fInclusionPatternList ; private ListDialogField fExclusionPatternList ; private CPListElement fCurrElement ; private IProject fCurrProject ; private IContainer fCurrSourceFolder ; private static final int IDX_ADD = ; private static final int IDX_ADD_MULTIPLE = ; private static final int IDX_EDIT = ; private static final int IDX_REMOVE = ; public ExclusionInclusionDialog ( Shell parent , CPListElement entryToEdit , boolean focusOnExcluded ) { super ( parent ) ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; fCurrElement = entryToEdit ; setTitle ( NewWizardMessages . ExclusionInclusionDialog_title ) ; fCurrProject = entryToEdit . getRubyProject ( ) . getProject ( ) ; IWorkspaceRoot root = fCurrProject . getWorkspace ( ) . getRoot ( ) ; IResource res = root . findMember ( entryToEdit . getPath ( ) ) ; if ( res instanceof IContainer ) { fCurrSourceFolder = ( IContainer ) res ; } String excLabel = NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_label ; ImageDescriptor excDescriptor = RubyPluginImages . DESC_OBJS_EXCLUSION_FILTER_ATTRIB ; String [ ] excButtonLabels = new String [ ] { NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_add , NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_add_multiple , NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_edit , null , NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_remove } ; String incLabel = NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_label ; ImageDescriptor incDescriptor = RubyPluginImages . DESC_OBJS_INCLUSION_FILTER_ATTRIB ; String [ ] incButtonLabels = new String [ ] { NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_add , NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_add_multiple , NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_edit , null , NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_remove } ; fExclusionPatternList = createListContents ( entryToEdit , CPListElement . EXCLUSION , excLabel , excDescriptor , excButtonLabels ) ; fInclusionPatternList = createListContents ( entryToEdit , CPListElement . INCLUSION , incLabel , incDescriptor , incButtonLabels ) ; if ( focusOnExcluded ) { fExclusionPatternList . postSetFocusOnDialogField ( parent . getDisplay ( ) ) ; } else { fInclusionPatternList . postSetFocusOnDialogField ( parent . getDisplay ( ) ) ; } } private ListDialogField createListContents ( CPListElement entryToEdit , String key , String label , ImageDescriptor descriptor , String [ ] buttonLabels ) { ExclusionPatternAdapter adapter = new ExclusionPatternAdapter ( ) ; ListDialogField patternList = new ListDialogField ( adapter , buttonLabels , new ExclusionInclusionLabelProvider ( descriptor ) ) ; patternList . setDialogFieldListener ( adapter ) ; patternList . setLabelText ( label ) ; patternList . setRemoveButtonIndex ( IDX_REMOVE ) ; patternList . enableButton ( IDX_EDIT , false ) ; IPath [ ] pattern = ( IPath [ ] ) entryToEdit . getAttribute ( key ) ; ArrayList elements = new ArrayList ( pattern . length ) ; for ( int i = ; i < pattern . length ; i ++ ) { elements . add ( pattern [ i ] . toString ( ) ) ; } patternList . setElements ( elements ) ; patternList . selectFirstElement ( ) ; patternList . enableButton ( IDX_ADD_MULTIPLE , fCurrSourceFolder != null ) ; patternList . setViewerSorter ( new ViewerSorter ( ) ) ; return patternList ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; inner . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; inner . setLayout ( layout ) ; inner . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; DialogField labelField = new DialogField ( ) ; String name = fCurrElement . getPath ( ) . makeRelative ( ) . toString ( ) ; labelField . setLabelText ( Messages . format ( NewWizardMessages . ExclusionInclusionDialog_description , name ) ) ; labelField . doFillIntoGrid ( inner , ) ; fInclusionPatternList . doFillIntoGrid ( inner , ) ; LayoutUtil . setHorizontalSpan ( fInclusionPatternList . getLabelControl ( null ) , ) ; LayoutUtil . setHorizontalGrabbing ( fInclusionPatternList . getListControl ( null ) ) ; fExclusionPatternList . doFillIntoGrid ( inner , ) ; LayoutUtil . setHorizontalSpan ( fExclusionPatternList . getLabelControl ( null ) , ) ; LayoutUtil . setHorizontalGrabbing ( fExclusionPatternList . getListControl ( null ) ) ; applyDialogFont ( composite ) ; return composite ; } protected void doCustomButtonPressed ( ListDialogField field , int index ) { if ( index == IDX_ADD ) { addEntry ( field ) ; } else if ( index == IDX_EDIT ) { editEntry ( field ) ; } else if ( index == IDX_ADD_MULTIPLE ) { addMultipleEntries ( field ) ; } } protected void doDoubleClicked ( ListDialogField field ) { editEntry ( field ) ; } protected void doSelectionChanged ( ListDialogField field ) { List selected = field . getSelectedElements ( ) ; field . enableButton ( IDX_EDIT , canEdit ( selected ) ) ; } private boolean canEdit ( List selected ) { return selected . size ( ) == ; } private void editEntry ( ListDialogField field ) { List selElements = field . getSelectedElements ( ) ; if ( selElements . size ( ) != ) { return ; } List existing = field . getElements ( ) ; String entry = ( String ) selElements . get ( ) ; ExclusionInclusionEntryDialog dialog = new ExclusionInclusionEntryDialog ( getShell ( ) , isExclusion ( field ) , entry , existing , fCurrElement ) ; if ( dialog . open ( ) == Window . OK ) { field . replaceElement ( entry , dialog . getExclusionPattern ( ) ) ; } } private boolean isExclusion ( ListDialogField field ) { return field == fExclusionPatternList ; } private void addEntry ( ListDialogField field ) { List existing = field . getElements ( ) ; ExclusionInclusionEntryDialog dialog = new ExclusionInclusionEntryDialog ( getShell ( ) , isExclusion ( field ) , null , existing , fCurrElement ) ; if ( dialog . open ( ) == Window . OK ) { field . addElement ( dialog . getExclusionPattern ( ) ) ; } } private class ExclusionPatternAdapter implements IListAdapter , IDialogFieldListener { public void customButtonPressed ( ListDialogField field , int index ) { doCustomButtonPressed ( field , index ) ; } public void selectionChanged ( ListDialogField field ) { doSelectionChanged ( field ) ; } public void doubleClicked ( ListDialogField field ) { doDoubleClicked ( field ) ; } public void dialogFieldChanged ( DialogField field ) { } } protected void doStatusLineUpdate ( ) { } protected void checkIfPatternValid ( ) { } private IPath [ ] getPattern ( ListDialogField field ) { Object [ ] arr = field . getElements ( ) . toArray ( ) ; Arrays . sort ( arr ) ; IPath [ ] res = new IPath [ arr . length ] ; for ( int i = ; i < res . length ; i ++ ) { res [ i ] = new Path ( ( String ) arr [ i ] ) ; } return res ; } public IPath [ ] getExclusionPattern ( ) { return getPattern ( fExclusionPatternList ) ; } public IPath [ ] getInclusionPattern ( ) { return getPattern ( fInclusionPatternList ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; } private void addMultipleEntries ( ListDialogField field ) { String title , message ; if ( isExclusion ( field ) ) { title = NewWizardMessages . ExclusionInclusionDialog_ChooseExclusionPattern_title ; message = NewWizardMessages . ExclusionInclusionDialog_ChooseExclusionPattern_description ; } else { title = NewWizardMessages . ExclusionInclusionDialog_ChooseInclusionPattern_title ; message = NewWizardMessages . ExclusionInclusionDialog_ChooseInclusionPattern_description ; } IPath [ ] res = ExclusionInclusionEntryDialog . chooseExclusionPattern ( getShell ( ) , fCurrSourceFolder , title , message , null , true ) ; if ( res != null ) { for ( int i = ; i < res . length ; i ++ ) { field . addElement ( res [ i ] . toString ( ) ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public class AddSourceFolderWizard extends BuildPathWizard { private AddSourceFolderWizardPage fAddFolderPage ; private SetFilterWizardPage fFilterPage ; private final boolean fLinkedMode ; private boolean fAllowConflict ; private final boolean fAllowRemoveProjectFolder ; private final boolean fAllowAddExclusionPatterns ; private final boolean fCanCommitConflict ; private final IContainer fParent ; public AddSourceFolderWizard ( CPListElement [ ] existingEntries , CPListElement newEntry , boolean linkedMode , boolean canCommitConflict , boolean allowConflict , boolean allowRemoveProjectFolder , boolean allowAddExclusionPatterns ) { this ( existingEntries , newEntry , linkedMode , canCommitConflict , allowConflict , allowRemoveProjectFolder , allowAddExclusionPatterns , newEntry . getRubyProject ( ) . getProject ( ) ) ; } public AddSourceFolderWizard ( CPListElement [ ] existingEntries , CPListElement newEntry , boolean linkedMode , boolean canCommitConflict , boolean allowConflict , boolean allowRemoveProjectFolder , boolean allowAddExclusionPatterns , IContainer parent ) { super ( existingEntries , newEntry , getTitel ( newEntry , linkedMode ) , RubyPluginImages . DESC_WIZBAN_NEWSRCFOLDR ) ; fLinkedMode = linkedMode ; fCanCommitConflict = canCommitConflict ; fAllowConflict = allowConflict ; fAllowRemoveProjectFolder = allowRemoveProjectFolder ; fAllowAddExclusionPatterns = allowAddExclusionPatterns ; fParent = parent ; } private static String getTitel ( CPListElement newEntry , boolean linkedMode ) { if ( newEntry . getPath ( ) == null ) { if ( linkedMode ) { return NewWizardMessages . NewSourceFolderCreationWizard_link_title ; } else { return NewWizardMessages . NewSourceFolderCreationWizard_title ; } } else { return NewWizardMessages . NewSourceFolderCreationWizard_edit_title ; } } public void addPages ( ) { super . addPages ( ) ; fAddFolderPage = new AddSourceFolderWizardPage ( getEntryToEdit ( ) , getExistingEntries ( ) , fLinkedMode , fCanCommitConflict , fAllowConflict , fAllowRemoveProjectFolder , fAllowAddExclusionPatterns , fParent ) ; addPage ( fAddFolderPage ) ; fFilterPage = new SetFilterWizardPage ( getEntryToEdit ( ) , getExistingEntries ( ) ) ; addPage ( fFilterPage ) ; } public List getInsertedElements ( ) { List result = super . getInsertedElements ( ) ; if ( getEntryToEdit ( ) . getOrginalPath ( ) == null ) result . add ( getEntryToEdit ( ) ) ; return result ; } public List getRemovedElements ( ) { return fAddFolderPage . getRemovedElements ( ) ; } public List getModifiedElements ( ) { return fAddFolderPage . getModifiedElements ( ) ; } public boolean performFinish ( ) { getEntryToEdit ( ) . setAttribute ( CPListElement . INCLUSION , fFilterPage . getInclusionPattern ( ) ) ; getEntryToEdit ( ) . setAttribute ( CPListElement . EXCLUSION , fFilterPage . getExclusionPattern ( ) ) ; boolean res = super . performFinish ( ) ; if ( res ) { selectAndReveal ( fAddFolderPage . getCorrespondingResource ( ) ) ; } return res ; } public void cancel ( ) { fAddFolderPage . restore ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . Arrays ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . viewers . ArrayContentProvider ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . ListViewer ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . util . SelectionUtil ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public class LoadpathContainerSelectionPage extends WizardPage { private static final String DIALOGSTORE_SECTION = "" ; private static final String DIALOGSTORE_CONTAINER_IDX = "" ; private static class LoadpathContainerLabelProvider extends LabelProvider { public String getText ( Object element ) { return ( ( LoadpathContainerDescriptor ) element ) . getName ( ) ; } } private static class LoadpathContainerSorter extends ViewerSorter { } private ListViewer fListViewer ; private LoadpathContainerDescriptor [ ] fContainers ; private IDialogSettings fDialogSettings ; protected LoadpathContainerSelectionPage ( LoadpathContainerDescriptor [ ] containerPages ) { super ( "" ) ; setTitle ( NewWizardMessages . LoadpathContainerSelectionPage_title ) ; setDescription ( NewWizardMessages . LoadpathContainerSelectionPage_description ) ; setImageDescriptor ( RubyPluginImages . DESC_WIZBAN_ADD_LIBRARY ) ; fContainers = containerPages ; IDialogSettings settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; fDialogSettings = settings . getSection ( DIALOGSTORE_SECTION ) ; if ( fDialogSettings == null ) { fDialogSettings = settings . addNewSection ( DIALOGSTORE_SECTION ) ; fDialogSettings . put ( DIALOGSTORE_CONTAINER_IDX , ) ; } validatePage ( ) ; } public void createControl ( Composite parent ) { fListViewer = new ListViewer ( parent , SWT . SINGLE | SWT . BORDER ) ; fListViewer . setLabelProvider ( new LoadpathContainerLabelProvider ( ) ) ; fListViewer . setContentProvider ( new ArrayContentProvider ( ) ) ; fListViewer . setSorter ( new LoadpathContainerSorter ( ) ) ; fListViewer . setInput ( Arrays . asList ( fContainers ) ) ; fListViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { validatePage ( ) ; } } ) ; fListViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { doDoubleClick ( ) ; } } ) ; int selectionIndex = fDialogSettings . getInt ( DIALOGSTORE_CONTAINER_IDX ) ; if ( selectionIndex >= fContainers . length ) { selectionIndex = ; } fListViewer . getList ( ) . select ( selectionIndex ) ; validatePage ( ) ; setControl ( fListViewer . getList ( ) ) ; Dialog . applyDialogFont ( fListViewer . getList ( ) ) ; } private void validatePage ( ) { setPageComplete ( getSelected ( ) != null ) ; } public LoadpathContainerDescriptor getSelected ( ) { if ( fListViewer != null ) { ISelection selection = fListViewer . getSelection ( ) ; return ( LoadpathContainerDescriptor ) SelectionUtil . getSingleElement ( selection ) ; } return null ; } public LoadpathContainerDescriptor [ ] getContainers ( ) { return fContainers ; } protected void doDoubleClick ( ) { if ( canFlipToNextPage ( ) ) { getContainer ( ) . showPage ( getNextPage ( ) ) ; } } public boolean canFlipToNextPage ( ) { return isPageComplete ( ) ; } public void setVisible ( boolean visible ) { if ( ! visible && fListViewer != null ) { fDialogSettings . put ( DIALOGSTORE_CONTAINER_IDX , fListViewer . getList ( ) . getSelectionIndex ( ) ) ; } super . setVisible ( visible ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . ide . IDE ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . ui . ISharedImages ; import org . rubypeople . rdt . ui . RubyElementImageDescriptor ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; public class CPListLabelProvider extends LabelProvider { private String fNewLabel , fClassLabel , fCreateLabel ; private ImageDescriptorRegistry fRegistry ; private ISharedImages fSharedImages ; private ImageDescriptor fProjectImage ; public CPListLabelProvider ( ) { fNewLabel = NewWizardMessages . CPListLabelProvider_new ; fClassLabel = NewWizardMessages . CPListLabelProvider_classcontainer ; fCreateLabel = NewWizardMessages . CPListLabelProvider_willbecreated ; fRegistry = RubyPlugin . getImageDescriptorRegistry ( ) ; fSharedImages = RubyUI . getSharedImages ( ) ; IWorkbench workbench = RubyPlugin . getDefault ( ) . getWorkbench ( ) ; fProjectImage = workbench . getSharedImages ( ) . getImageDescriptor ( IDE . SharedImages . IMG_OBJ_PROJECT ) ; } public String getText ( Object element ) { if ( element instanceof CPListElement ) { return getCPListElementText ( ( CPListElement ) element ) ; } else if ( element instanceof CPListElementAttribute ) { CPListElementAttribute attribute = ( CPListElementAttribute ) element ; String text = getCPListElementAttributeText ( attribute ) ; if ( attribute . isInNonModifiableContainer ( ) ) { return Messages . format ( NewWizardMessages . CPListLabelProvider_non_modifiable_attribute , text ) ; } return text ; } else if ( element instanceof CPUserLibraryElement ) { return getCPUserLibraryText ( ( CPUserLibraryElement ) element ) ; } return super . getText ( element ) ; } public String getCPUserLibraryText ( CPUserLibraryElement element ) { String name = element . getName ( ) ; if ( element . isSystemLibrary ( ) ) { name = Messages . format ( NewWizardMessages . CPListLabelProvider_systemlibrary , name ) ; } return name ; } public String getCPListElementAttributeText ( CPListElementAttribute attrib ) { String notAvailable = NewWizardMessages . CPListLabelProvider_none ; String key = attrib . getKey ( ) ; if ( key . equals ( CPListElement . EXCLUSION ) ) { String arg = null ; IPath [ ] patterns = ( IPath [ ] ) attrib . getValue ( ) ; if ( patterns != null && patterns . length > ) { int patternsCount = ; StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < patterns . length ; i ++ ) { String pattern = patterns [ i ] . toString ( ) ; if ( pattern . length ( ) > ) { if ( patternsCount > ) { buf . append ( NewWizardMessages . CPListLabelProvider_exclusion_filter_separator ) ; } buf . append ( pattern ) ; patternsCount ++ ; } } if ( patternsCount > ) { arg = buf . toString ( ) ; } else { arg = notAvailable ; } } else { arg = notAvailable ; } return Messages . format ( NewWizardMessages . CPListLabelProvider_exclusion_filter_label , new String [ ] { arg } ) ; } else if ( key . equals ( CPListElement . INCLUSION ) ) { String arg = null ; IPath [ ] patterns = ( IPath [ ] ) attrib . getValue ( ) ; if ( patterns != null && patterns . length > ) { int patternsCount = ; StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < patterns . length ; i ++ ) { String pattern = patterns [ i ] . toString ( ) ; if ( pattern . length ( ) > ) { if ( patternsCount > ) { buf . append ( NewWizardMessages . CPListLabelProvider_inclusion_filter_separator ) ; } buf . append ( pattern ) ; patternsCount ++ ; } } if ( patternsCount > ) { arg = buf . toString ( ) ; } else { arg = notAvailable ; } } else { arg = NewWizardMessages . CPListLabelProvider_all ; } return Messages . format ( NewWizardMessages . CPListLabelProvider_inclusion_filter_label , new String [ ] { arg } ) ; } return notAvailable ; } public String getCPListElementText ( CPListElement cpentry ) { IPath path = cpentry . getPath ( ) ; switch ( cpentry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_LIBRARY : { IResource resource = cpentry . getResource ( ) ; if ( resource instanceof IContainer ) { StringBuffer buf = new StringBuffer ( path . makeRelative ( ) . toString ( ) ) ; IPath linkTarget = cpentry . getLinkTarget ( ) ; if ( linkTarget != null ) { buf . append ( RubyElementLabels . CONCAT_STRING ) ; buf . append ( linkTarget . toOSString ( ) ) ; } buf . append ( '' ) ; buf . append ( fClassLabel ) ; if ( ! resource . exists ( ) ) { buf . append ( '' ) ; if ( cpentry . isMissing ( ) ) { buf . append ( fCreateLabel ) ; } else { buf . append ( fNewLabel ) ; } } return buf . toString ( ) ; } return path . makeRelative ( ) . toString ( ) ; } case ILoadpathEntry . CPE_VARIABLE : { return getVariableString ( path ) ; } case ILoadpathEntry . CPE_PROJECT : return path . lastSegment ( ) ; case ILoadpathEntry . CPE_CONTAINER : try { ILoadpathContainer container = RubyCore . getLoadpathContainer ( path , cpentry . getRubyProject ( ) ) ; if ( container != null ) { return container . getDescription ( ) ; } LoadpathContainerInitializer initializer = RubyCore . getLoadpathContainerInitializer ( path . segment ( ) ) ; if ( initializer != null ) { String description = initializer . getDescription ( path , cpentry . getRubyProject ( ) ) ; return Messages . format ( NewWizardMessages . CPListLabelProvider_unbound_library , description ) ; } } catch ( RubyModelException e ) { } return path . toString ( ) ; case ILoadpathEntry . CPE_SOURCE : { StringBuffer buf = new StringBuffer ( path . makeRelative ( ) . toString ( ) ) ; IPath linkTarget = cpentry . getLinkTarget ( ) ; if ( linkTarget != null ) { buf . append ( RubyElementLabels . CONCAT_STRING ) ; buf . append ( linkTarget . toOSString ( ) ) ; } IResource resource = cpentry . getResource ( ) ; if ( resource != null && ! resource . exists ( ) ) { buf . append ( '' ) ; if ( cpentry . isMissing ( ) ) { buf . append ( fCreateLabel ) ; } else { buf . append ( fNewLabel ) ; } } else if ( cpentry . getOrginalPath ( ) == null ) { buf . append ( '' ) ; buf . append ( fNewLabel ) ; } return buf . toString ( ) ; } default : } return NewWizardMessages . CPListLabelProvider_unknown_element_label ; } private String getPathString ( IPath path , boolean isExternal ) { return isExternal ? path . toOSString ( ) : path . makeRelative ( ) . toString ( ) ; } private String getVariableString ( IPath path ) { String name = path . makeRelative ( ) . toString ( ) ; IPath [ ] entryPath = RubyCore . getLoadpathVariable ( path . segment ( ) ) ; if ( entryPath != null ) { String appended = entryPath [ ] . append ( path . removeFirstSegments ( ) ) . toOSString ( ) ; return Messages . format ( NewWizardMessages . CPListLabelProvider_twopart , new String [ ] { name , appended } ) ; } else { return name ; } } private ImageDescriptor getCPListElementBaseImage ( CPListElement cpentry ) { switch ( cpentry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_SOURCE : if ( cpentry . getPath ( ) . segmentCount ( ) == ) { return fProjectImage ; } else { return fSharedImages . getImageDescriptor ( ISharedImages . IMG_OBJS_SOURCE_FOLDER_ROOT ) ; } case ILoadpathEntry . CPE_LIBRARY : IResource res = cpentry . getResource ( ) ; if ( res == null ) { return fSharedImages . getImageDescriptor ( ISharedImages . IMG_OBJS_EXTERNAL_ARCHIVE_WITH_SOURCE ) ; } else { return fSharedImages . getImageDescriptor ( ISharedImages . IMG_OBJS_SOURCE_FOLDER_ROOT ) ; } case ILoadpathEntry . CPE_PROJECT : return fProjectImage ; case ILoadpathEntry . CPE_VARIABLE : return fSharedImages . getImageDescriptor ( ISharedImages . IMG_OBJS_LOADPATH_VAR_ENTRY ) ; case ILoadpathEntry . CPE_CONTAINER : return fSharedImages . getImageDescriptor ( ISharedImages . IMG_OBJS_LIBRARY ) ; default : return null ; } } public Image getImage ( Object element ) { if ( element instanceof CPListElement ) { CPListElement cpentry = ( CPListElement ) element ; ImageDescriptor imageDescriptor = getCPListElementBaseImage ( cpentry ) ; if ( imageDescriptor != null ) { if ( cpentry . isMissing ( ) ) { imageDescriptor = new RubyElementImageDescriptor ( imageDescriptor , RubyElementImageDescriptor . WARNING , RubyElementImageProvider . SMALL_SIZE ) ; } return fRegistry . get ( imageDescriptor ) ; } } else if ( element instanceof CPListElementAttribute ) { String key = ( ( CPListElementAttribute ) element ) . getKey ( ) ; if ( key . equals ( CPListElement . EXCLUSION ) ) { return fRegistry . get ( RubyPluginImages . DESC_OBJS_EXCLUSION_FILTER_ATTRIB ) ; } else if ( key . equals ( CPListElement . INCLUSION ) ) { return fRegistry . get ( RubyPluginImages . DESC_OBJS_INCLUSION_FILTER_ATTRIB ) ; } return fSharedImages . getImage ( ISharedImages . IMG_OBJS_LOADPATH_VAR_ENTRY ) ; } else if ( element instanceof CPUserLibraryElement ) { return fSharedImages . getImage ( ISharedImages . IMG_OBJS_LIBRARY ) ; } return null ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . List ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . CoreUtility ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . launching . IGemRuntime ; public class VariableBlock { private ListDialogField fVariablesList ; private Control fControl ; private boolean fHasChanges ; private List fSelectedElements ; private boolean fAskToBuild ; private boolean fInPreferencePage ; public VariableBlock ( boolean inPreferencePage , String initSelection ) { fSelectedElements = new ArrayList ( ) ; fInPreferencePage = inPreferencePage ; fAskToBuild = true ; String [ ] buttonLabels = new String [ ] { NewWizardMessages . VariableBlock_vars_add_button , NewWizardMessages . VariableBlock_vars_edit_button , NewWizardMessages . VariableBlock_vars_remove_button } ; VariablesAdapter adapter = new VariablesAdapter ( ) ; CPVariableElementLabelProvider labelProvider = new CPVariableElementLabelProvider ( ! inPreferencePage ) ; fVariablesList = new ListDialogField ( adapter , buttonLabels , labelProvider ) ; fVariablesList . setDialogFieldListener ( adapter ) ; fVariablesList . setLabelText ( NewWizardMessages . VariableBlock_vars_label ) ; fVariablesList . setRemoveButtonIndex ( ) ; fVariablesList . enableButton ( , false ) ; fVariablesList . setViewerSorter ( new ViewerSorter ( ) { public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( e1 instanceof CPVariableElement && e2 instanceof CPVariableElement ) { return ( ( CPVariableElement ) e1 ) . getName ( ) . compareTo ( ( ( CPVariableElement ) e2 ) . getName ( ) ) ; } return super . compare ( viewer , e1 , e2 ) ; } } ) ; refresh ( initSelection ) ; } public boolean hasChanges ( ) { return fHasChanges ; } public void setChanges ( boolean hasChanges ) { fHasChanges = hasChanges ; } private String [ ] getReservedVariableNames ( ) { return new String [ ] { RubyRuntime . RUBYLIB_VARIABLE , IGemRuntime . GEMLIB_VARIABLE } ; } public Control createContents ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; LayoutUtil . doDefaultLayout ( composite , new DialogField [ ] { fVariablesList } , true , , ) ; LayoutUtil . setHorizontalGrabbing ( fVariablesList . getListControl ( null ) ) ; fControl = composite ; return composite ; } public void addDoubleClickListener ( IDoubleClickListener listener ) { fVariablesList . getTableViewer ( ) . addDoubleClickListener ( listener ) ; } public void addSelectionChangedListener ( ISelectionChangedListener listener ) { fVariablesList . getTableViewer ( ) . addSelectionChangedListener ( listener ) ; } private Shell getShell ( ) { if ( fControl != null ) { return fControl . getShell ( ) ; } return RubyPlugin . getActiveWorkbenchShell ( ) ; } private class VariablesAdapter implements IDialogFieldListener , IListAdapter { public void customButtonPressed ( ListDialogField field , int index ) { switch ( index ) { case : editEntries ( null ) ; break ; case : List selected = field . getSelectedElements ( ) ; editEntries ( ( CPVariableElement ) selected . get ( ) ) ; break ; } } public void selectionChanged ( ListDialogField field ) { doSelectionChanged ( field ) ; } public void doubleClicked ( ListDialogField field ) { if ( fInPreferencePage ) { List selected = field . getSelectedElements ( ) ; if ( canEdit ( selected , containsReserved ( selected ) ) ) { editEntries ( ( CPVariableElement ) selected . get ( ) ) ; } } } public void dialogFieldChanged ( DialogField field ) { } } private boolean containsReserved ( List selected ) { for ( int i = selected . size ( ) - ; i >= ; i -- ) { if ( ( ( CPVariableElement ) selected . get ( i ) ) . isReserved ( ) ) { return true ; } } return false ; } private static void addAll ( Object [ ] objs , Collection dest ) { for ( int i = ; i < objs . length ; i ++ ) { dest . add ( objs [ i ] ) ; } } private boolean canEdit ( List selected , boolean containsReserved ) { return selected . size ( ) == && ! containsReserved ; } private void doSelectionChanged ( DialogField field ) { List selected = fVariablesList . getSelectedElements ( ) ; boolean containsReserved = containsReserved ( selected ) ; fVariablesList . enableButton ( , canEdit ( selected , containsReserved ) ) ; fVariablesList . enableButton ( , ! containsReserved ) ; fSelectedElements = selected ; } private void editEntries ( CPVariableElement entry ) { List existingEntries = fVariablesList . getElements ( ) ; VariableCreationDialog dialog = new VariableCreationDialog ( getShell ( ) , entry , existingEntries ) ; if ( dialog . open ( ) != Window . OK ) { return ; } CPVariableElement newEntry = dialog . getClasspathElement ( ) ; if ( entry == null ) { fVariablesList . addElement ( newEntry ) ; entry = newEntry ; fHasChanges = true ; } else { boolean hasChanges = ! ( entry . getName ( ) . equals ( newEntry . getName ( ) ) && entry . getPath ( ) . equals ( newEntry . getPath ( ) ) ) ; if ( hasChanges ) { fHasChanges = true ; entry . setName ( newEntry . getName ( ) ) ; entry . setPath ( newEntry . getPath ( ) ) ; fVariablesList . refresh ( ) ; } } fVariablesList . selectElements ( new StructuredSelection ( entry ) ) ; } public List getSelectedElements ( ) { return fSelectedElements ; } public void performDefaults ( ) { fVariablesList . removeAllElements ( ) ; String [ ] reservedName = getReservedVariableNames ( ) ; for ( int i = ; i < reservedName . length ; i ++ ) { CPVariableElement elem = new CPVariableElement ( reservedName [ i ] , new IPath [ ] { Path . EMPTY } , true ) ; elem . setReserved ( true ) ; fVariablesList . addElement ( elem ) ; } fHasChanges = true ; } public boolean performOk ( ) { ArrayList removedVariables = new ArrayList ( ) ; ArrayList changedVariables = new ArrayList ( ) ; removedVariables . addAll ( Arrays . asList ( RubyCore . getLoadpathVariableNames ( ) ) ) ; List changedElements = fVariablesList . getElements ( ) ; for ( int i = changedElements . size ( ) - ; i >= ; i -- ) { CPVariableElement curr = ( CPVariableElement ) changedElements . get ( i ) ; if ( curr . isReserved ( ) ) { changedElements . remove ( curr ) ; } else { IPath [ ] path = curr . getPath ( ) ; IPath [ ] prevPath = RubyCore . getLoadpathVariable ( curr . getName ( ) ) ; if ( prevPath != null && prevPath . equals ( path ) ) { changedElements . remove ( curr ) ; } else { changedVariables . add ( curr . getName ( ) ) ; } } removedVariables . remove ( curr . getName ( ) ) ; } int steps = changedElements . size ( ) + removedVariables . size ( ) ; if ( steps > ) { boolean needsBuild = false ; if ( fAskToBuild && doesChangeRequireFullBuild ( removedVariables , changedVariables ) ) { String title = NewWizardMessages . VariableBlock_needsbuild_title ; String message = NewWizardMessages . VariableBlock_needsbuild_message ; MessageDialog buildDialog = new MessageDialog ( getShell ( ) , title , null , message , MessageDialog . QUESTION , new String [ ] { IDialogConstants . YES_LABEL , IDialogConstants . NO_LABEL , IDialogConstants . CANCEL_LABEL } , ) ; int res = buildDialog . open ( ) ; if ( res != && res != ) { return false ; } needsBuild = ( res == ) ; } final VariableBlockRunnable runnable = new VariableBlockRunnable ( removedVariables , changedElements ) ; final ProgressMonitorDialog dialog = new ProgressMonitorDialog ( getShell ( ) ) ; try { dialog . run ( true , true , runnable ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( new InvocationTargetException ( new NullPointerException ( ) ) , getShell ( ) , NewWizardMessages . VariableBlock_variableSettingError_titel , NewWizardMessages . VariableBlock_variableSettingError_message ) ; return false ; } catch ( InterruptedException e ) { return false ; } if ( needsBuild ) { CoreUtility . getBuildJob ( null ) . schedule ( ) ; } } return true ; } private boolean doesChangeRequireFullBuild ( List removed , List changed ) { try { IRubyModel model = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; IRubyProject [ ] projects = model . getRubyProjects ( ) ; for ( int i = ; i < projects . length ; i ++ ) { ILoadpathEntry [ ] entries = projects [ i ] . getRawLoadpath ( ) ; for ( int k = ; k < entries . length ; k ++ ) { ILoadpathEntry curr = entries [ k ] ; if ( curr . getEntryKind ( ) == ILoadpathEntry . CPE_VARIABLE ) { String var = curr . getPath ( ) . segment ( ) ; if ( removed . contains ( var ) || changed . contains ( var ) ) { return true ; } } } } } catch ( RubyModelException e ) { return true ; } return false ; } private class VariableBlockRunnable implements IRunnableWithProgress { private List fToRemove ; private List fToChange ; public VariableBlockRunnable ( List toRemove , List toChange ) { fToRemove = toRemove ; fToChange = toChange ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { monitor . beginTask ( NewWizardMessages . VariableBlock_operation_desc , ) ; try { setVariables ( monitor ) ; } catch ( CoreException e ) { throw new InvocationTargetException ( e ) ; } catch ( OperationCanceledException e ) { throw new InterruptedException ( ) ; } finally { monitor . done ( ) ; } } public void setVariables ( IProgressMonitor monitor ) throws RubyModelException , CoreException { int nVariables = fToChange . size ( ) + fToRemove . size ( ) ; String [ ] names = new String [ nVariables ] ; IPath [ ] [ ] paths = new IPath [ nVariables ] [ ] ; int k = ; for ( int i = ; i < fToChange . size ( ) ; i ++ ) { CPVariableElement curr = ( CPVariableElement ) fToChange . get ( i ) ; names [ k ] = curr . getName ( ) ; paths [ k ] = curr . getPath ( ) ; k ++ ; } for ( int i = ; i < fToRemove . size ( ) ; i ++ ) { names [ k ] = ( String ) fToRemove . get ( i ) ; paths [ k ] = null ; k ++ ; } RubyCore . setLoadpathVariables ( names , paths , new SubProgressMonitor ( monitor , ) ) ; } } public void setAskToBuild ( boolean askToBuild ) { fAskToBuild = askToBuild ; } public void refresh ( String initSelection ) { CPVariableElement initSelectedElement = null ; String [ ] reservedName = getReservedVariableNames ( ) ; ArrayList reserved = new ArrayList ( reservedName . length ) ; addAll ( reservedName , reserved ) ; String [ ] entries = RubyCore . getLoadpathVariableNames ( ) ; ArrayList elements = new ArrayList ( entries . length ) ; for ( int i = ; i < entries . length ; i ++ ) { String name = entries [ i ] ; CPVariableElement elem ; IPath [ ] entryPath = RubyCore . getLoadpathVariable ( name ) ; if ( entryPath != null ) { elem = new CPVariableElement ( name , entryPath , reserved . contains ( name ) ) ; elements . add ( elem ) ; if ( name . equals ( initSelection ) ) { initSelectedElement = elem ; } } else { RubyPlugin . logErrorMessage ( "" + name ) ; } } fVariablesList . setElements ( elements ) ; if ( initSelectedElement != null ) { ISelection sel = new StructuredSelection ( initSelectedElement ) ; fVariablesList . selectElements ( sel ) ; } else { fVariablesList . selectFirstElement ( ) ; } fHasChanges = false ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . io . File ; import java . lang . reflect . InvocationTargetException ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IPathVariableManager ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . actions . WorkspaceModifyOperation ; import org . eclipse . ui . ide . dialogs . PathVariableSelectionDialog ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; import org . rubypeople . rdt . ui . RubyUI ; public class LinkFolderDialog extends StatusDialog { private final class FolderNameField extends Observable implements IDialogFieldListener { private StringDialogField fNameDialogField ; public FolderNameField ( Composite parent , int numOfColumns ) { createControls ( parent , numOfColumns ) ; } private void createControls ( Composite parent , int numColumns ) { fNameDialogField = new StringDialogField ( ) ; fNameDialogField . setLabelText ( NewWizardMessages . LinkFolderDialog_folderNameGroup_label ) ; fNameDialogField . doFillIntoGrid ( parent , ) ; LayoutUtil . setHorizontalGrabbing ( fNameDialogField . getTextControl ( null ) ) ; LayoutUtil . setHorizontalSpan ( fNameDialogField . getLabelControl ( null ) , numColumns ) ; DialogField . createEmptySpace ( parent , numColumns - ) ; fNameDialogField . setDialogFieldListener ( this ) ; } public StringDialogField getNameDialogField ( ) { return fNameDialogField ; } public void setText ( String text ) { fNameDialogField . setText ( text ) ; fNameDialogField . setFocus ( ) ; } public String getText ( ) { return fNameDialogField . getText ( ) ; } protected void fireEvent ( ) { setChanged ( ) ; notifyObservers ( ) ; } public void dialogFieldChanged ( DialogField field ) { fireEvent ( ) ; } } private final class LinkFields extends Observable implements IStringButtonAdapter , IDialogFieldListener { private StringButtonDialogField fLinkLocation ; private static final String DIALOGSTORE_LAST_EXTERNAL_LOC = RubyUI . ID_PLUGIN + "" ; public LinkFields ( Composite parent , int numColumns ) { createControls ( parent , numColumns ) ; } private void createControls ( Composite parent , int numColumns ) { fLinkLocation = new StringButtonDialogField ( this ) ; fLinkLocation . setLabelText ( NewWizardMessages . LinkFolderDialog_dependenciesGroup_locationLabel_desc ) ; fLinkLocation . setButtonLabel ( NewWizardMessages . LinkFolderDialog_dependenciesGroup_browseButton_desc ) ; fLinkLocation . setDialogFieldListener ( this ) ; SelectionButtonDialogField variables = new SelectionButtonDialogField ( SWT . PUSH ) ; variables . setLabelText ( NewWizardMessages . LinkFolderDialog_dependenciesGroup_variables_desc ) ; variables . setDialogFieldListener ( new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { handleVariablesButtonPressed ( ) ; } } ) ; fLinkLocation . doFillIntoGrid ( parent , numColumns ) ; LayoutUtil . setHorizontalSpan ( fLinkLocation . getLabelControl ( null ) , numColumns ) ; LayoutUtil . setHorizontalGrabbing ( fLinkLocation . getTextControl ( null ) ) ; variables . doFillIntoGrid ( parent , ) ; } public String getLinkTarget ( ) { return fLinkLocation . getText ( ) ; } public void setLinkTarget ( String text ) { fLinkLocation . setText ( text ) ; } public void changeControlPressed ( DialogField field ) { final DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) ) ; dialog . setMessage ( NewWizardMessages . RubyProjectWizardFirstPage_directory_message ) ; String directoryName = getLinkTarget ( ) . trim ( ) ; if ( directoryName . length ( ) == ) { String prevLocation = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( DIALOGSTORE_LAST_EXTERNAL_LOC ) ; if ( prevLocation != null ) { directoryName = prevLocation ; } } if ( directoryName . length ( ) > ) { final File path = new File ( directoryName ) ; if ( path . exists ( ) ) dialog . setFilterPath ( directoryName ) ; } final String selectedDirectory = dialog . open ( ) ; if ( selectedDirectory != null ) { fLinkLocation . setText ( selectedDirectory ) ; if ( fName == null ) { fFolderNameField . setText ( selectedDirectory . substring ( selectedDirectory . lastIndexOf ( File . separatorChar ) + ) ) ; } RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( DIALOGSTORE_LAST_EXTERNAL_LOC , selectedDirectory ) ; } } private void handleVariablesButtonPressed ( ) { int variableTypes = IResource . FOLDER ; PathVariableSelectionDialog dialog = new PathVariableSelectionDialog ( getShell ( ) , variableTypes ) ; if ( dialog . open ( ) == IDialogConstants . OK_ID ) { String [ ] variableNames = ( String [ ] ) dialog . getResult ( ) ; if ( variableNames != null && variableNames . length == ) { fLinkLocation . setText ( variableNames [ ] ) ; if ( fName == null ) { fFolderNameField . setText ( variableNames [ ] ) ; } } } } public void dialogFieldChanged ( DialogField field ) { fireEvent ( ) ; } private void fireEvent ( ) { setChanged ( ) ; notifyObservers ( ) ; } } private final class Validator implements Observer { public void update ( Observable o , Object arg ) { String name = fFolderNameField . getText ( ) ; IStatus nameStatus = validateFolderName ( name ) ; if ( nameStatus . matches ( IStatus . ERROR ) ) { updateStatus ( nameStatus ) ; } else { IStatus dependencyStatus = validateLinkLocation ( name ) ; updateStatus ( StatusUtil . getMoreSevere ( nameStatus , dependencyStatus ) ) ; } } private IStatus validateLinkLocation ( String name ) { IWorkspace workspace = RubyPlugin . getWorkspace ( ) ; IPath path = Path . fromOSString ( fDependenciesGroup . getLinkTarget ( ) ) ; IStatus locationStatus = workspace . validateLinkLocation ( fContainer . getFolder ( new Path ( name ) ) , path ) ; if ( locationStatus . matches ( IStatus . ERROR ) ) return locationStatus ; String resolvedLinkTarget = resolveVariable ( ) ; path = new Path ( resolvedLinkTarget ) ; File linkTargetFile = new Path ( resolvedLinkTarget ) . toFile ( ) ; if ( linkTargetFile . exists ( ) ) { IStatus fileTypeStatus = validateFileType ( linkTargetFile ) ; if ( ! fileTypeStatus . isOK ( ) ) return fileTypeStatus ; } else if ( locationStatus . isOK ( ) ) { return new StatusInfo ( IStatus . ERROR , NewWizardMessages . NewFolderDialog_linkTargetNonExistent ) ; } if ( locationStatus . isOK ( ) ) { return new StatusInfo ( ) ; } return new StatusInfo ( locationStatus . getSeverity ( ) , locationStatus . getMessage ( ) ) ; } private IStatus validateFileType ( File linkTargetFile ) { if ( ! linkTargetFile . isDirectory ( ) ) return new StatusInfo ( IStatus . ERROR , NewWizardMessages . NewFolderDialog_linkTargetNotFolder ) ; return new StatusInfo ( ) ; } private String resolveVariable ( ) { IPathVariableManager pathVariableManager = ResourcesPlugin . getWorkspace ( ) . getPathVariableManager ( ) ; IPath path = Path . fromOSString ( fDependenciesGroup . getLinkTarget ( ) ) ; IPath resolvedPath = pathVariableManager . resolvePath ( path ) ; return resolvedPath . toOSString ( ) ; } private IStatus validateFolderName ( String name ) { if ( name . length ( ) == ) { return new StatusInfo ( IStatus . ERROR , NewWizardMessages . NewFolderDialog_folderNameEmpty ) ; } IStatus nameStatus = fContainer . getWorkspace ( ) . validateName ( name , IResource . FOLDER ) ; if ( ! nameStatus . matches ( IStatus . ERROR ) ) { return nameStatus ; } IPath path = new Path ( name ) ; if ( fContainer . findMember ( path ) != null ) { return new StatusInfo ( IStatus . ERROR , Messages . format ( NewWizardMessages . NewFolderDialog_folderNameEmpty_alreadyExists , name ) ) ; } return nameStatus ; } } private FolderNameField fFolderNameField ; private LinkFields fDependenciesGroup ; private IContainer fContainer ; private IFolder fCreatedFolder ; private boolean fCreateLink ; private String fName ; private String fTarget ; public LinkFolderDialog ( Shell parentShell , IContainer container ) { this ( parentShell , container , true ) ; } public LinkFolderDialog ( Shell parentShell , IContainer container , boolean createLink ) { super ( parentShell ) ; fContainer = container ; fCreateLink = createLink ; setTitle ( NewWizardMessages . LinkFolderDialog_title ) ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; setStatusLineAboveButtons ( true ) ; } protected void configureShell ( Shell shell ) { super . configureShell ( shell ) ; } public void create ( ) { super . create ( ) ; getButton ( IDialogConstants . OK_ID ) . setEnabled ( false ) ; } public void setName ( String name ) { if ( fFolderNameField != null ) { fFolderNameField . setText ( name ) ; } fName = name ; } public void setLinkTarget ( String target ) { if ( fDependenciesGroup != null ) { fDependenciesGroup . setLinkTarget ( target ) ; } fTarget = target ; } protected Control createDialogArea ( Composite parent ) { initializeDialogUnits ( parent ) ; int numOfColumns = ; Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( numOfColumns , false ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; composite . setLayout ( layout ) ; GridData gridData = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gridData . minimumWidth = convertWidthInCharsToPixels ( ) ; composite . setLayoutData ( gridData ) ; Label label = new Label ( composite , SWT . NONE ) ; label . setFont ( composite . getFont ( ) ) ; label . setText ( Messages . format ( NewWizardMessages . LinkFolderDialog_createIn , fContainer . getFullPath ( ) . makeRelative ( ) . toString ( ) ) ) ; label . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , false , false , numOfColumns , ) ) ; fDependenciesGroup = new LinkFields ( composite , numOfColumns ) ; if ( fTarget != null ) { fDependenciesGroup . setLinkTarget ( fTarget ) ; } fFolderNameField = new FolderNameField ( composite , numOfColumns ) ; if ( fName != null ) { fFolderNameField . setText ( fName ) ; } Validator validator = new Validator ( ) ; fDependenciesGroup . addObserver ( validator ) ; fFolderNameField . addObserver ( validator ) ; return composite ; } private IFolder createFolderHandle ( String folderName ) { IWorkspaceRoot workspaceRoot = fContainer . getWorkspace ( ) . getRoot ( ) ; IPath folderPath = fContainer . getFullPath ( ) . append ( folderName ) ; IFolder folderHandle = workspaceRoot . getFolder ( folderPath ) ; return folderHandle ; } private IFolder createNewFolder ( final String folderName , final String linkTargetName ) { final IFolder folderHandle = createFolderHandle ( folderName ) ; WorkspaceModifyOperation operation = new WorkspaceModifyOperation ( ) { public void execute ( IProgressMonitor monitor ) throws CoreException { try { monitor . beginTask ( NewWizardMessages . NewFolderDialog_progress , ) ; if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; folderHandle . createLink ( Path . fromOSString ( fDependenciesGroup . getLinkTarget ( ) ) , IResource . ALLOW_MISSING_LOCAL , monitor ) ; if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; } catch ( StringIndexOutOfBoundsException e ) { e . printStackTrace ( ) ; } finally { monitor . done ( ) ; } } } ; try { new ProgressMonitorDialog ( getShell ( ) ) . run ( true , true , operation ) ; } catch ( InterruptedException exception ) { return null ; } catch ( InvocationTargetException exception ) { if ( exception . getTargetException ( ) instanceof CoreException ) { ErrorDialog . openError ( getShell ( ) , NewWizardMessages . NewFolderDialog_errorTitle , null , ( ( CoreException ) exception . getTargetException ( ) ) . getStatus ( ) ) ; } else { RubyPlugin . log ( new Exception ( Messages . format ( "" , new Object [ ] { getClass ( ) . getName ( ) , exception . getTargetException ( ) } ) ) ) ; MessageDialog . openError ( getShell ( ) , NewWizardMessages . NewFolderDialog_errorTitle , Messages . format ( NewWizardMessages . NewFolderDialog_internalError , new Object [ ] { exception . getTargetException ( ) . getMessage ( ) } ) ) ; } return null ; } return folderHandle ; } protected void updateStatus ( IStatus status ) { super . updateStatus ( status ) ; } protected void okPressed ( ) { if ( fCreateLink ) { String linkTarget = fDependenciesGroup . getLinkTarget ( ) ; linkTarget = linkTarget . length ( ) == ? null : linkTarget ; fCreatedFolder = createNewFolder ( fFolderNameField . getText ( ) , linkTarget ) ; } else { fCreatedFolder = createFolderHandle ( fFolderNameField . getText ( ) ) ; } super . okPressed ( ) ; } public IFolder getCreatedFolder ( ) { return fCreatedFolder ; } public IPath getLinkTarget ( ) { return Path . fromOSString ( fDependenciesGroup . getLinkTarget ( ) ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . ILoadpathInformationProvider ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; public abstract class LoadpathModifierOperation extends LoadpathModifier implements IRunnableWithProgress { protected ILoadpathInformationProvider fInformationProvider ; protected CoreException fException ; private int fType ; private String fName ; public LoadpathModifierOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider , String name , int type ) { super ( listener ) ; fInformationProvider = informationProvider ; fException = null ; fName = name ; fType = type ; } protected void handleResult ( List result , IProgressMonitor monitor ) throws InvocationTargetException { if ( monitor == null || fException == null ) fInformationProvider . handleResult ( result , fException , fType ) ; else throw new InvocationTargetException ( fException ) ; fException = null ; } public abstract void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException ; public String getId ( ) { return Integer . toString ( fType ) ; } public abstract boolean isValid ( List elements , int [ ] types ) throws RubyModelException ; public abstract String getDescription ( int type ) ; public String getName ( ) { return fName ; } public List getSelectedElements ( ) { return fInformationProvider . getSelection ( ) . toList ( ) ; } public int getTypeId ( ) { return fType ; } public boolean isValid ( ) throws RubyModelException { List selectedElements = getSelectedElements ( ) ; int [ ] types = new int [ selectedElements . size ( ) ] ; for ( int i = ; i < types . length ; i ++ ) { types [ i ] = DialogPackageExplorerActionGroup . getType ( selectedElements . get ( i ) , fInformationProvider . getRubyProject ( ) ) ; } return isValid ( selectedElements , types ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . ISetSelectionTarget ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; public class AddSelectedLibraryToBuildpathAction extends Action implements ISelectionChangedListener { private final IWorkbenchSite fSite ; private IFile [ ] fSelectedElements ; public AddSelectedLibraryToBuildpathAction ( IWorkbenchSite site ) { super ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddSelLibToCP_label , RubyPluginImages . DESC_OBJS_EXTJAR ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddSelLibToCP_tooltip ) ; fSite = site ; fSelectedElements = null ; } public void run ( ) { try { final IFile [ ] files = fSelectedElements ; if ( files == null ) { return ; } final IRunnableWithProgress runnable = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { try { IRubyProject project = RubyCore . create ( files [ ] . getProject ( ) ) ; List result = addLibraryEntries ( files , project , monitor ) ; selectAndReveal ( new StructuredSelection ( result ) ) ; } catch ( CoreException e ) { throw new InvocationTargetException ( e ) ; } } } ; PlatformUI . getWorkbench ( ) . getProgressService ( ) . run ( true , false , runnable ) ; } catch ( final InvocationTargetException e ) { if ( e . getCause ( ) instanceof CoreException ) { showExceptionDialog ( ( CoreException ) e . getCause ( ) ) ; } else { RubyPlugin . log ( e ) ; } } catch ( final InterruptedException e ) { } } private List addLibraryEntries ( IFile [ ] resources , IRubyProject project , IProgressMonitor monitor ) throws CoreException { List addedEntries = new ArrayList ( ) ; try { monitor . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_AddToBuildpath , ) ; for ( int i = ; i < resources . length ; i ++ ) { IResource res = resources [ i ] ; addedEntries . add ( new CPListElement ( project , ILoadpathEntry . CPE_LIBRARY , res . getFullPath ( ) , res ) ) ; } monitor . worked ( ) ; List existingEntries = LoadpathModifier . getExistingEntries ( project ) ; LoadpathModifier . setNewEntry ( existingEntries , addedEntries , project , new SubProgressMonitor ( monitor , ) ) ; LoadpathModifier . commitLoadPath ( existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; List result = new ArrayList ( addedEntries . size ( ) ) ; for ( int i = ; i < resources . length ; i ++ ) { IResource res = resources [ i ] ; IRubyElement elem = project . getSourceFolderRoot ( res ) ; if ( elem != null ) { result . add ( elem ) ; } } monitor . worked ( ) ; return result ; } finally { monitor . done ( ) ; } } public void selectionChanged ( final SelectionChangedEvent event ) { final ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { setEnabled ( canHandle ( ( IStructuredSelection ) selection ) ) ; } else { setEnabled ( canHandle ( StructuredSelection . EMPTY ) ) ; } } private boolean canHandle ( IStructuredSelection elements ) { fSelectedElements = getSelectedResources ( elements ) ; return fSelectedElements != null ; } private IFile [ ] getSelectedResources ( IStructuredSelection elements ) { if ( elements . size ( ) == ) return null ; ArrayList res = new ArrayList ( ) ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof IFile ) { IFile file = ( IFile ) element ; IRubyProject project = RubyCore . create ( file . getProject ( ) ) ; if ( project == null ) return null ; return null ; } else { return null ; } } return ( IFile [ ] ) res . toArray ( new IFile [ res . size ( ) ] ) ; } private void showExceptionDialog ( CoreException exception ) { showError ( exception , fSite . getShell ( ) , NewWizardMessages . AddSelectedLibraryToBuildpathAction_ErrorTitle , exception . getMessage ( ) ) ; } private void showError ( CoreException e , Shell shell , String title , String message ) { IStatus status = e . getStatus ( ) ; if ( status != null ) { ErrorDialog . openError ( shell , message , title , status ) ; } else { MessageDialog . openError ( shell , title , message ) ; } } private void selectAndReveal ( final ISelection selection ) { IWorkbenchPage page = fSite . getPage ( ) ; if ( page == null ) return ; List parts = new ArrayList ( ) ; IWorkbenchPartReference refs [ ] = page . getViewReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { IWorkbenchPart part = refs [ i ] . getPart ( false ) ; if ( part != null ) parts . add ( part ) ; } refs = page . getEditorReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { if ( refs [ i ] . getPart ( false ) != null ) parts . add ( refs [ i ] . getPart ( false ) ) ; } Iterator itr = parts . iterator ( ) ; while ( itr . hasNext ( ) ) { IWorkbenchPart part = ( IWorkbenchPart ) itr . next ( ) ; ISetSelectionTarget target = null ; if ( part instanceof ISetSelectionTarget ) target = ( ISetSelectionTarget ) part ; else target = ( ISetSelectionTarget ) part . getAdapter ( ISetSelectionTarget . class ) ; if ( target != null ) { final ISetSelectionTarget finalTarget = target ; page . getWorkbenchWindow ( ) . getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { finalTarget . selectReveal ( selection ) ; } } ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . action . ToolBarManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . ToolBar ; import org . eclipse . ui . actions . ActionContext ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . AddSelectedSourceFolderOperation ; import org . rubypeople . rdt . internal . corext . buildpath . CreateFolderOperation ; import org . rubypeople . rdt . internal . corext . buildpath . EditFiltersOperation ; import org . rubypeople . rdt . internal . corext . buildpath . ExcludeOperation ; import org . rubypeople . rdt . internal . corext . buildpath . ILoadpathInformationProvider ; import org . rubypeople . rdt . internal . corext . buildpath . IPackageExplorerActionListener ; import org . rubypeople . rdt . internal . corext . buildpath . LinkedSourceFolderOperation ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . corext . buildpath . PackageExplorerActionEvent ; import org . rubypeople . rdt . internal . corext . buildpath . RemoveFromLoadpathOperation ; import org . rubypeople . rdt . internal . corext . buildpath . ResetAllOperation ; import org . rubypeople . rdt . internal . corext . buildpath . UnexcludeOperation ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier . ILoadpathModifierListener ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . CompositeActionGroup ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; import org . rubypeople . rdt . internal . ui . util . ViewerPane ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElementAttribute ; public class DialogPackageExplorerActionGroup extends CompositeActionGroup { public static class DialogExplorerActionContext extends ActionContext { private IRubyProject fRubyProject ; private List fSelectedElements ; public DialogExplorerActionContext ( ISelection selection , IRubyProject jProject ) { super ( null ) ; fRubyProject = jProject ; fSelectedElements = ( ( IStructuredSelection ) selection ) . toList ( ) ; IStructuredSelection structuredSelection = new StructuredSelection ( new Object [ ] { fSelectedElements , jProject } ) ; super . setSelection ( structuredSelection ) ; } public DialogExplorerActionContext ( List selectedElements , IRubyProject jProject ) { super ( null ) ; fRubyProject = jProject ; fSelectedElements = selectedElements ; IStructuredSelection structuredSelection = new StructuredSelection ( new Object [ ] { fSelectedElements , jProject } ) ; super . setSelection ( structuredSelection ) ; } public IRubyProject getRubyProject ( ) { return fRubyProject ; } public List getSelectedElements ( ) { return fSelectedElements ; } } public static final int RUBY_PROJECT = ; public static final int SOURCE_FOLDER_ROOT = ; public static final int SOURCE_FOLDER = ; public static final int RUBY_SCRIPT = ; public static final int FILE = ; public static final int FOLDER = ; public static final int EXCLUDED_FOLDER = ; public static final int EXCLUDED_FILE = ; public static final int DEFAULT_OUTPUT = ; public static final int INCLUDED_FILE = ; public static final int INCLUDED_FOLDER = ; public static final int OUTPUT = ; public static final int ARCHIVE = ; public static final int MODIFIED_FRAGMENT_ROOT = ; public static final int DEFAULT_FRAGMENT = ; public static final int UNDEFINED = ; public static final int MULTI = ; public static final int NULL_SELECTION = ; public static final int ARCHIVE_RESOURCE = ; public static final int CONTAINER = ; private LoadpathModifierAction [ ] fActions ; private int fLastType ; private List fListeners ; private static final int fContextSensitiveActions = ; public DialogPackageExplorerActionGroup ( ILoadpathInformationProvider provider , final NewSourceContainerWorkbookPage page ) { super ( ) ; fLastType = UNDEFINED ; fListeners = new ArrayList ( ) ; fActions = new LoadpathModifierAction [ ] ; LoadpathModifierOperation op ; op = new AddSelectedSourceFolderOperation ( page , provider ) ; addAction ( new LoadpathModifierAction ( op , RubyPluginImages . DESC_ELCL_ADD_AS_SOURCE_FOLDER , null , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_label , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_tooltip , IAction . AS_PUSH_BUTTON ) , ) ; op = new RemoveFromLoadpathOperation ( page , provider ) ; addAction ( new LoadpathModifierAction ( op , RubyPluginImages . DESC_ELCL_REMOVE_AS_SOURCE_FOLDER , RubyPluginImages . DESC_DLCL_REMOVE_AS_SOURCE_FOLDER , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_label , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_tooltip , IAction . AS_PUSH_BUTTON ) , ) ; op = new ExcludeOperation ( page , provider ) ; addAction ( new LoadpathModifierAction ( op , RubyPluginImages . DESC_ELCL_EXCLUDE_FROM_BUILDPATH , RubyPluginImages . DESC_DLCL_EXCLUDE_FROM_BUILDPATH , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Exclude_label , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Exclude_tooltip , IAction . AS_PUSH_BUTTON ) , ) ; op = new UnexcludeOperation ( page , provider ) ; addAction ( new LoadpathModifierAction ( op , RubyPluginImages . DESC_ELCL_INCLUDE_ON_BUILDPATH , RubyPluginImages . DESC_DLCL_INCLUDE_ON_BUILDPATH , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Unexclude_label , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Unexclude_tooltip , IAction . AS_PUSH_BUTTON ) , ) ; op = new EditFiltersOperation ( page , provider ) ; addAction ( new LoadpathModifierAction ( op , RubyPluginImages . DESC_ELCL_CONFIGURE_BUILDPATH_FILTERS , RubyPluginImages . DESC_DLCL_CONFIGURE_BUILDPATH_FILTERS , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Edit_label , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Edit_tooltip , IAction . AS_PUSH_BUTTON ) , ) ; op = new LinkedSourceFolderOperation ( page , provider ) ; addAction ( new LoadpathModifierAction ( op , RubyPluginImages . DESC_ELCL_ADD_LINKED_SOURCE_TO_BUILDPATH , RubyPluginImages . DESC_DLCL_ADD_LINKED_SOURCE_TO_BUILDPATH , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Link_label , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Link_tooltip , IAction . AS_PUSH_BUTTON ) , ) ; op = new CreateFolderOperation ( page , provider ) ; addAction ( new LoadpathModifierAction ( op , RubyPluginImages . DESC_OBJS_SOURCE_FOLDER_ROOT , null , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_CreateSrcFolder_label , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_CreateSrcFolder_tooltip , IAction . AS_PUSH_BUTTON ) , ) ; op = new ResetAllOperation ( page , provider ) ; addAction ( new LoadpathModifierAction ( op , RubyPluginImages . DESC_ELCL_CLEAR , RubyPluginImages . DESC_DLCL_CLEAR , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_ClearAll_label , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_ClearAll_tooltip , IAction . AS_PUSH_BUTTON ) , ) ; } private void addAction ( LoadpathModifierAction action , int index ) { fActions [ index ] = action ; } public LoadpathModifierAction getAction ( int type ) { for ( int i = ; i < fActions . length ; i ++ ) { if ( fActions [ i ] . getOperation ( ) . getTypeId ( ) == type ) return fActions [ i ] ; } throw new ArrayIndexOutOfBoundsException ( ) ; } public LoadpathModifierAction [ ] getActions ( ) { List result = new ArrayList ( ) ; for ( int i = ; i < fActions . length ; i ++ ) { LoadpathModifierAction action = fActions [ i ] ; if ( action instanceof LoadpathModifierDropDownAction ) { LoadpathModifierDropDownAction dropDownAction = ( LoadpathModifierDropDownAction ) action ; LoadpathModifierAction [ ] actions = dropDownAction . getActions ( ) ; for ( int j = ; j < actions . length ; j ++ ) { result . add ( actions [ j ] ) ; } } else { result . add ( action ) ; } } return ( LoadpathModifierAction [ ] ) result . toArray ( new LoadpathModifierAction [ result . size ( ) ] ) ; } public ToolBarManager createLeftToolBarManager ( ViewerPane pane ) { ToolBarManager tbm = pane . getToolBarManager ( ) ; for ( int i = ; i < fContextSensitiveActions ; i ++ ) { tbm . add ( fActions [ i ] ) ; if ( i == || i == ) tbm . add ( new Separator ( ) ) ; } tbm . update ( true ) ; return tbm ; } public ToolBarManager createLeftToolBar ( ViewerPane pane ) { ToolBar tb = new ToolBar ( pane , SWT . FLAT ) ; pane . setTopRight ( tb ) ; ToolBarManager tbm = new ToolBarManager ( tb ) ; for ( int i = fContextSensitiveActions ; i < fActions . length ; i ++ ) { tbm . add ( fActions [ i ] ) ; } tbm . add ( new HelpAction ( ) ) ; tbm . update ( true ) ; return tbm ; } public void refresh ( DialogExplorerActionContext context ) throws RubyModelException { super . setContext ( context ) ; if ( context == null ) return ; List selectedElements = context . getSelectedElements ( ) ; IRubyProject project = context . getRubyProject ( ) ; int type = MULTI ; if ( selectedElements . size ( ) == ) { type = NULL_SELECTION ; if ( type == fLastType ) return ; } else if ( selectedElements . size ( ) == || identicalTypes ( selectedElements , project ) ) { type = getType ( selectedElements . get ( ) , project ) ; } internalSetContext ( selectedElements , project , type ) ; } public void setContext ( ActionContext context ) { try { setContext ( ( DialogExplorerActionContext ) context ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } public void setContext ( DialogExplorerActionContext context ) throws RubyModelException { super . setContext ( context ) ; if ( context == null ) return ; List selectedElements = context . getSelectedElements ( ) ; IRubyProject project = context . getRubyProject ( ) ; int type = MULTI ; if ( selectedElements . size ( ) == ) { type = NULL_SELECTION ; if ( type == fLastType ) return ; } else if ( selectedElements . size ( ) == || identicalTypes ( selectedElements , project ) ) { type = getType ( selectedElements . get ( ) , project ) ; if ( selectedElements . size ( ) > ) type = type | MULTI ; if ( type == fLastType ) return ; } internalSetContext ( selectedElements , project , type ) ; } public String getNoActionDescription ( ) { String [ ] description = noAction ( fLastType ) ; return description [ ] ; } private void internalSetContext ( List selectedElements , IRubyProject project , int type ) throws RubyModelException { fLastType = type ; List availableActions = getAvailableActions ( selectedElements , project ) ; LoadpathModifierAction [ ] actions = new LoadpathModifierAction [ availableActions . size ( ) ] ; String [ ] descriptions = new String [ availableActions . size ( ) ] ; if ( availableActions . size ( ) > ) { for ( int i = ; i < availableActions . size ( ) ; i ++ ) { LoadpathModifierAction action = ( LoadpathModifierAction ) availableActions . get ( i ) ; actions [ i ] = action ; descriptions [ i ] = action . getDescription ( type ) ; } } else descriptions = noAction ( type ) ; informListeners ( descriptions , actions ) ; } private boolean identicalTypes ( List elements , IRubyProject project ) throws RubyModelException { if ( elements . size ( ) == ) { return false ; } Object firstElement = elements . get ( ) ; int firstType = getType ( firstElement , project ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { if ( firstType != getType ( elements . get ( i ) , project ) ) return false ; } return true ; } private void informListeners ( String [ ] descriptions , LoadpathModifierAction [ ] actions ) { Iterator iterator = fListeners . iterator ( ) ; PackageExplorerActionEvent event = new PackageExplorerActionEvent ( descriptions , actions ) ; while ( iterator . hasNext ( ) ) { IPackageExplorerActionListener listener = ( IPackageExplorerActionListener ) iterator . next ( ) ; listener . handlePackageExplorerActionEvent ( event ) ; } } private String [ ] noAction ( int type ) { String reason ; switch ( type ) { case FILE : reason = NewWizardMessages . PackageExplorerActionGroup_NoAction_File ; break ; case FILE | MULTI : reason = NewWizardMessages . PackageExplorerActionGroup_NoAction_File ; break ; case DEFAULT_FRAGMENT : reason = NewWizardMessages . PackageExplorerActionGroup_NoAction_DefaultPackage ; break ; case DEFAULT_FRAGMENT | MULTI : reason = NewWizardMessages . PackageExplorerActionGroup_NoAction_DefaultPackage ; break ; case NULL_SELECTION : reason = NewWizardMessages . PackageExplorerActionGroup_NoAction_NullSelection ; break ; case MULTI : reason = NewWizardMessages . PackageExplorerActionGroup_NoAction_MultiSelection ; break ; case ARCHIVE_RESOURCE : reason = NewWizardMessages . PackageExplorerActionGroup_NoAction_ArchiveResource ; break ; default : reason = NewWizardMessages . PackageExplorerActionGroup_NoAction_NoReason ; } return new String [ ] { reason } ; } public static int getType ( Object obj , IRubyProject project ) throws RubyModelException { if ( obj instanceof IRubyProject ) return RUBY_PROJECT ; if ( obj instanceof LoadPathContainer ) return CONTAINER ; if ( obj instanceof ISourceFolderRoot ) return LoadpathModifier . filtersSet ( ( ISourceFolderRoot ) obj ) ? MODIFIED_FRAGMENT_ROOT : SOURCE_FOLDER_ROOT ; if ( obj instanceof ISourceFolder ) { if ( LoadpathModifier . isDefaultFolder ( ( ISourceFolder ) obj ) ) { if ( ( ( ISourceFolderRoot ) ( ( IRubyElement ) obj ) . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ) . isArchive ( ) ) return ARCHIVE_RESOURCE ; return DEFAULT_FRAGMENT ; } if ( LoadpathModifier . isIncluded ( ( IRubyElement ) obj , project , null ) ) return INCLUDED_FOLDER ; if ( ( ( ISourceFolderRoot ) ( ( IRubyElement ) obj ) . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ) . isArchive ( ) ) return ARCHIVE_RESOURCE ; return SOURCE_FOLDER ; } if ( obj instanceof IRubyScript ) { if ( ( ( ISourceFolderRoot ) ( ( IRubyElement ) obj ) . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ) . isArchive ( ) ) return ARCHIVE_RESOURCE ; return LoadpathModifier . isIncluded ( ( IRubyElement ) obj , project , null ) ? INCLUDED_FILE : RUBY_SCRIPT ; } if ( obj instanceof IFolder ) { return getFolderType ( ( IFolder ) obj , project ) ; } if ( obj instanceof IFile ) return getFileType ( ( IFile ) obj , project ) ; if ( obj instanceof CPListElementAttribute ) return OUTPUT ; return UNDEFINED ; } private static int getFolderType ( IFolder folder , IRubyProject project ) throws RubyModelException { IContainer folderParent = folder . getParent ( ) ; if ( folderParent . getFullPath ( ) . equals ( project . getPath ( ) ) ) return FOLDER ; if ( LoadpathModifier . getFolder ( folderParent ) != null ) return EXCLUDED_FOLDER ; ISourceFolderRoot fragmentRoot = LoadpathModifier . getFolderRoot ( folder , project , null ) ; if ( fragmentRoot == null ) return FOLDER ; if ( fragmentRoot . equals ( RubyCore . create ( folderParent ) ) ) return EXCLUDED_FOLDER ; return FOLDER ; } private static int getFileType ( IFile file , IRubyProject project ) throws RubyModelException { if ( ! RubyCore . isRubyLikeFileName ( file . getName ( ) ) ) return FILE ; IContainer fileParent = file . getParent ( ) ; if ( fileParent . getFullPath ( ) . equals ( project . getPath ( ) ) ) { if ( project . isOnLoadpath ( project ) ) return EXCLUDED_FILE ; return FILE ; } ISourceFolderRoot fragmentRoot = LoadpathModifier . getFolderRoot ( file , project , null ) ; if ( fragmentRoot == null ) return FILE ; if ( fragmentRoot . isArchive ( ) ) return ARCHIVE_RESOURCE ; if ( fragmentRoot . equals ( RubyCore . create ( fileParent ) ) ) return EXCLUDED_FILE ; if ( LoadpathModifier . getFolder ( fileParent ) == null ) { if ( LoadpathModifier . parentExcluded ( fileParent , project ) ) return FILE ; return EXCLUDED_FILE ; } return EXCLUDED_FILE ; } private List getAvailableActions ( List selectedElements , IRubyProject project ) throws RubyModelException { if ( project == null || ! project . exists ( ) ) { return new ArrayList ( ) ; } List actions = new ArrayList ( ) ; int [ ] types = new int [ selectedElements . size ( ) ] ; for ( int i = ; i < types . length ; i ++ ) { types [ i ] = getType ( selectedElements . get ( i ) , project ) ; } for ( int i = ; i < fActions . length ; i ++ ) { if ( fActions [ i ] instanceof LoadpathModifierDropDownAction ) { if ( changeEnableState ( fActions [ i ] , selectedElements , types ) ) { LoadpathModifierAction [ ] dropDownActions = ( ( LoadpathModifierDropDownAction ) fActions [ i ] ) . getActions ( ) ; for ( int j = ; j < dropDownActions . length ; j ++ ) { if ( changeEnableState ( dropDownActions [ j ] , selectedElements , types ) ) actions . add ( dropDownActions [ j ] ) ; } } } else if ( changeEnableState ( fActions [ i ] , selectedElements , types ) ) { actions . add ( fActions [ i ] ) ; } } return actions ; } private boolean changeEnableState ( LoadpathModifierAction action , List selectedElements , int [ ] types ) throws RubyModelException { if ( action . isValid ( selectedElements , types ) ) { if ( ! action . isEnabled ( ) ) action . setEnabled ( true ) ; return true ; } else { if ( action . isEnabled ( ) ) action . setEnabled ( false ) ; return false ; } } public void fillContextMenu ( IMenuManager menu ) { for ( int i = ; i < fContextSensitiveActions ; i ++ ) { IAction action = getAction ( i ) ; if ( action instanceof LoadpathModifierDropDownAction ) { if ( action . isEnabled ( ) ) { IAction [ ] actions = ( ( LoadpathModifierDropDownAction ) action ) . getActions ( ) ; for ( int j = ; j < actions . length ; j ++ ) { if ( actions [ j ] . isEnabled ( ) ) menu . add ( actions [ j ] ) ; } } } else if ( action . isEnabled ( ) ) menu . add ( action ) ; } super . fillContextMenu ( menu ) ; } public void addListener ( IPackageExplorerActionListener listener ) { fListeners . add ( listener ) ; } public void removeListener ( IPackageExplorerActionListener listener ) { fListeners . remove ( listener ) ; } public void dispose ( ) { fListeners . clear ( ) ; super . dispose ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . ISetSelectionTarget ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . IRemoveLinkedFolderQuery ; public class RemoveFromBuildpathAction extends Action implements ISelectionChangedListener { private final IWorkbenchSite fSite ; private List fSelectedElements ; public RemoveFromBuildpathAction ( IWorkbenchSite site ) { super ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_label , RubyPluginImages . DESC_ELCL_REMOVE_FROM_BP ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_tooltip ) ; fSite = site ; fSelectedElements = new ArrayList ( ) ; } public void run ( ) { try { final IRubyProject project ; Object object = fSelectedElements . get ( ) ; if ( object instanceof IRubyProject ) { project = ( IRubyProject ) object ; } else if ( object instanceof ISourceFolderRoot ) { ISourceFolderRoot root = ( ISourceFolderRoot ) object ; project = root . getRubyProject ( ) ; } else { LoadPathContainer container = ( LoadPathContainer ) object ; project = container . getRubyProject ( ) ; } final List elementsToRemove = new ArrayList ( ) ; final List foldersToDelete = new ArrayList ( ) ; queryToRemoveLinkedFolders ( elementsToRemove , foldersToDelete ) ; final IRunnableWithProgress runnable = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { try { monitor . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_RemoveFromBuildpath , elementsToRemove . size ( ) + foldersToDelete . size ( ) ) ; List result = removeFromLoadpath ( elementsToRemove , project , new SubProgressMonitor ( monitor , elementsToRemove . size ( ) ) ) ; result . removeAll ( foldersToDelete ) ; deleteFolders ( foldersToDelete , new SubProgressMonitor ( monitor , foldersToDelete . size ( ) ) ) ; if ( result . size ( ) == ) result . add ( project ) ; selectAndReveal ( new StructuredSelection ( result ) ) ; } catch ( CoreException e ) { throw new InvocationTargetException ( e ) ; } finally { monitor . done ( ) ; } } } ; PlatformUI . getWorkbench ( ) . getProgressService ( ) . run ( true , false , runnable ) ; } catch ( CoreException e ) { showExceptionDialog ( e ) ; } catch ( InvocationTargetException e ) { if ( e . getCause ( ) instanceof CoreException ) { showExceptionDialog ( ( CoreException ) e . getCause ( ) ) ; } else { RubyPlugin . log ( e ) ; } } catch ( InterruptedException e ) { } } private void deleteFolders ( List folders , IProgressMonitor monitor ) throws CoreException { try { monitor . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_RemoveFromBuildpath , folders . size ( ) ) ; for ( Iterator iter = folders . iterator ( ) ; iter . hasNext ( ) ; ) { IFolder folder = ( IFolder ) iter . next ( ) ; folder . delete ( true , true , new SubProgressMonitor ( monitor , ) ) ; } } finally { monitor . done ( ) ; } } private List removeFromLoadpath ( List elements , IRubyProject project , IProgressMonitor monitor ) throws CoreException { try { monitor . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_RemoveFromBuildpath , elements . size ( ) + ) ; List existingEntries = LoadpathModifier . getExistingEntries ( project ) ; List result = new ArrayList ( ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { Object element = elements . get ( i ) ; if ( element instanceof IRubyProject ) { Object res = LoadpathModifier . removeFromLoadpath ( ( IRubyProject ) element , existingEntries , new SubProgressMonitor ( monitor , ) ) ; result . add ( res ) ; } else if ( element instanceof ISourceFolderRoot ) { Object res = LoadpathModifier . removeFromLoadpath ( ( ISourceFolderRoot ) element , existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; if ( res != null ) result . add ( res ) ; } else { existingEntries . remove ( CPListElement . createFromExisting ( ( ( LoadPathContainer ) element ) . getLoadpathEntry ( ) , project ) ) ; } } LoadpathModifier . commitLoadPath ( existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; return result ; } finally { monitor . done ( ) ; } } private void queryToRemoveLinkedFolders ( final List elementsToRemove , final List foldersToDelete ) throws RubyModelException { final Shell shell = fSite . getShell ( ) != null ? fSite . getShell ( ) : RubyPlugin . getActiveWorkbenchShell ( ) ; for ( Iterator iter = fSelectedElements . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof ISourceFolderRoot ) { IFolder folder = getLinkedSourceFolder ( ( ISourceFolderRoot ) element ) ; if ( folder != null ) { RemoveLinkedFolderDialog dialog = new RemoveLinkedFolderDialog ( shell , folder ) ; final int result = dialog . open ( ) == Window . OK ? dialog . getRemoveStatus ( ) : IRemoveLinkedFolderQuery . REMOVE_CANCEL ; if ( result != IRemoveLinkedFolderQuery . REMOVE_CANCEL ) { if ( result == IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH ) { elementsToRemove . add ( element ) ; } else if ( result == IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH_AND_FOLDER ) { elementsToRemove . add ( element ) ; foldersToDelete . add ( folder ) ; } } } else { elementsToRemove . add ( element ) ; } } else { elementsToRemove . add ( element ) ; } } } private IFolder getLinkedSourceFolder ( ISourceFolderRoot root ) throws RubyModelException { final IResource resource = root . getCorrespondingResource ( ) ; if ( ! ( resource instanceof IFolder ) ) return null ; final IFolder folder = ( IFolder ) resource ; if ( ! folder . isLinked ( ) ) return null ; return folder ; } public void selectionChanged ( final SelectionChangedEvent event ) { final ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { setEnabled ( canHandle ( ( IStructuredSelection ) selection ) ) ; } else { setEnabled ( canHandle ( StructuredSelection . EMPTY ) ) ; } } private boolean canHandle ( IStructuredSelection elements ) { if ( elements . size ( ) == ) return false ; try { fSelectedElements . clear ( ) ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; fSelectedElements . add ( element ) ; if ( ! ( element instanceof ISourceFolderRoot || element instanceof IRubyProject || element instanceof LoadPathContainer ) ) return false ; if ( element instanceof IRubyProject ) { IRubyProject project = ( IRubyProject ) element ; if ( ! LoadpathModifier . isSourceFolder ( project ) ) return false ; } else if ( element instanceof ISourceFolderRoot ) { ILoadpathEntry entry = ( ( ISourceFolderRoot ) element ) . getRawLoadpathEntry ( ) ; if ( entry != null && entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) { return false ; } } } return true ; } catch ( RubyModelException e ) { } return false ; } private void showExceptionDialog ( CoreException exception ) { showError ( exception , fSite . getShell ( ) , NewWizardMessages . RemoveFromBuildpathAction_ErrorTitle , exception . getMessage ( ) ) ; } private void showError ( CoreException e , Shell shell , String title , String message ) { IStatus status = e . getStatus ( ) ; if ( status != null ) { ErrorDialog . openError ( shell , message , title , status ) ; } else { MessageDialog . openError ( shell , title , message ) ; } } private void selectAndReveal ( final ISelection selection ) { IWorkbenchPage page = fSite . getPage ( ) ; if ( page == null ) return ; List parts = new ArrayList ( ) ; IWorkbenchPartReference refs [ ] = page . getViewReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { IWorkbenchPart part = refs [ i ] . getPart ( false ) ; if ( part != null ) parts . add ( part ) ; } refs = page . getEditorReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { if ( refs [ i ] . getPart ( false ) != null ) parts . add ( refs [ i ] . getPart ( false ) ) ; } Iterator itr = parts . iterator ( ) ; while ( itr . hasNext ( ) ) { IWorkbenchPart part = ( IWorkbenchPart ) itr . next ( ) ; ISetSelectionTarget target = null ; if ( part instanceof ISetSelectionTarget ) target = ( ISetSelectionTarget ) part ; else target = ( ISetSelectionTarget ) part . getAdapter ( ISetSelectionTarget . class ) ; if ( target != null ) { final ISetSelectionTarget finalTarget = target ; page . getWorkbenchWindow ( ) . getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { finalTarget . selectReveal ( selection ) ; } } ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . List ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . resource . ImageDescriptor ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class LoadpathModifierAction extends Action { private LoadpathModifierOperation fOperation ; public LoadpathModifierAction ( LoadpathModifierOperation operation , ImageDescriptor imageDescriptor , ImageDescriptor disabledImageDescriptor , String text , String tooltip , int style ) { super ( text , style ) ; setImageDescriptor ( imageDescriptor ) ; setDisabledImageDescriptor ( disabledImageDescriptor ) ; setText ( text ) ; setToolTipText ( tooltip ) ; fOperation = operation ; } public void run ( ) { try { fOperation . run ( null ) ; setEnabled ( fOperation . isValid ( ) ) ; } catch ( InvocationTargetException e ) { } catch ( InterruptedException e ) { } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } public boolean isValid ( List selectedElements , int [ ] types ) throws RubyModelException { return fOperation . isValid ( selectedElements , types ) ; } public LoadpathModifierOperation getOperation ( ) { return fOperation ; } public String getDescription ( int type ) { return fOperation . getDescription ( type ) ; } public String getId ( ) { return fOperation . getId ( ) ; } public String getName ( ) { return fOperation . getName ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . ISetSelectionTarget ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; public class ExcludeFromBuildpathAction extends Action implements ISelectionChangedListener { private final IWorkbenchSite fSite ; private final List fSelectedElements ; public ExcludeFromBuildpathAction ( IWorkbenchSite site ) { super ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Exclude_label , RubyPluginImages . DESC_ELCL_EXCLUDE_FROM_BUILDPATH ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Exclude_tooltip ) ; setDisabledImageDescriptor ( RubyPluginImages . DESC_DLCL_EXCLUDE_FROM_BUILDPATH ) ; fSite = site ; fSelectedElements = new ArrayList ( ) ; } public void run ( ) { final IRubyProject project ; Object object = fSelectedElements . get ( ) ; if ( object instanceof IRubyScript ) { project = ( ( IRubyScript ) object ) . getRubyProject ( ) ; } else { project = ( ( ISourceFolder ) object ) . getRubyProject ( ) ; } try { final IRunnableWithProgress runnable = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { try { List result = exclude ( fSelectedElements , project , monitor ) ; selectAndReveal ( new StructuredSelection ( result ) ) ; } catch ( CoreException e ) { throw new InvocationTargetException ( e ) ; } } } ; PlatformUI . getWorkbench ( ) . getProgressService ( ) . run ( true , false , runnable ) ; } catch ( final InvocationTargetException e ) { if ( e . getCause ( ) instanceof CoreException ) { showExceptionDialog ( ( CoreException ) e . getCause ( ) ) ; } else { RubyPlugin . log ( e ) ; } } catch ( final InterruptedException e ) { } } private List exclude ( List javaElements , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_Excluding , javaElements . size ( ) + ) ; List existingEntries = LoadpathModifier . getExistingEntries ( project ) ; List resources = new ArrayList ( ) ; for ( int i = ; i < javaElements . size ( ) ; i ++ ) { IRubyElement javaElement = ( IRubyElement ) javaElements . get ( i ) ; ISourceFolderRoot root = ( ISourceFolderRoot ) javaElement . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; CPListElement entry = LoadpathModifier . getLoadpathEntry ( existingEntries , root ) ; IResource resource = LoadpathModifier . exclude ( javaElement , entry , project , new SubProgressMonitor ( monitor , ) ) ; if ( resource != null ) { resources . add ( resource ) ; } } LoadpathModifier . commitLoadPath ( existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; return resources ; } finally { monitor . done ( ) ; } } public void selectionChanged ( final SelectionChangedEvent event ) { final ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { setEnabled ( canHandle ( ( IStructuredSelection ) selection ) ) ; } else { setEnabled ( canHandle ( StructuredSelection . EMPTY ) ) ; } } private boolean canHandle ( IStructuredSelection elements ) { if ( elements . size ( ) == ) return false ; try { fSelectedElements . clear ( ) ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; fSelectedElements . add ( element ) ; if ( element instanceof ISourceFolder ) { int type = DialogPackageExplorerActionGroup . getType ( element , ( ( ISourceFolder ) element ) . getRubyProject ( ) ) ; if ( type != DialogPackageExplorerActionGroup . INCLUDED_FOLDER && type != DialogPackageExplorerActionGroup . SOURCE_FOLDER ) return false ; } else if ( element instanceof IRubyScript ) { } else { return false ; } } return true ; } catch ( CoreException e ) { } return false ; } private void showExceptionDialog ( CoreException exception ) { showError ( exception , fSite . getShell ( ) , NewWizardMessages . ExcludeFromBuildathAction_ErrorTitle , exception . getMessage ( ) ) ; } private void showError ( CoreException e , Shell shell , String title , String message ) { IStatus status = e . getStatus ( ) ; if ( status != null ) { ErrorDialog . openError ( shell , message , title , status ) ; } else { MessageDialog . openError ( shell , title , message ) ; } } private void selectAndReveal ( final ISelection selection ) { IWorkbenchPage page = fSite . getPage ( ) ; if ( page == null ) return ; List parts = new ArrayList ( ) ; IWorkbenchPartReference refs [ ] = page . getViewReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { IWorkbenchPart part = refs [ i ] . getPart ( false ) ; if ( part != null ) parts . add ( part ) ; } refs = page . getEditorReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { if ( refs [ i ] . getPart ( false ) != null ) parts . add ( refs [ i ] . getPart ( false ) ) ; } Iterator itr = parts . iterator ( ) ; while ( itr . hasNext ( ) ) { IWorkbenchPart part = ( IWorkbenchPart ) itr . next ( ) ; ISetSelectionTarget target = null ; if ( part instanceof ISetSelectionTarget ) target = ( ISetSelectionTarget ) part ; else target = ( ISetSelectionTarget ) part . getAdapter ( ISetSelectionTarget . class ) ; if ( target != null ) { final ISetSelectionTarget finalTarget = target ; page . getWorkbenchWindow ( ) . getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { finalTarget . selectReveal ( selection ) ; } } ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuCreator ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Menu ; import org . rubypeople . rdt . core . RubyModelException ; public class LoadpathModifierDropDownAction extends LoadpathModifierAction implements IMenuCreator { private Menu fMenu ; protected List fActions ; private int fIndex ; public LoadpathModifierDropDownAction ( LoadpathModifierAction action , String text , String toolTipText ) { super ( action . getOperation ( ) , action . getImageDescriptor ( ) , action . getDisabledImageDescriptor ( ) , text , toolTipText , IAction . AS_DROP_DOWN_MENU ) ; fActions = new ArrayList ( ) ; fActions . add ( action ) ; fIndex = ; } public void run ( ) { LoadpathModifierAction action = ( LoadpathModifierAction ) fActions . get ( fIndex ) ; action . run ( ) ; } public IMenuCreator getMenuCreator ( ) { return this ; } public Menu getMenu ( Control parent ) { if ( fMenu != null ) { fMenu . dispose ( ) ; } fMenu = new Menu ( parent ) ; createEntries ( fMenu ) ; return fMenu ; } public Menu getMenu ( Menu parent ) { return fMenu ; } public void addAction ( LoadpathModifierAction action ) { fActions . add ( action ) ; } public void addActions ( LoadpathModifierAction [ ] actions ) { for ( int i = ; i < actions . length ; i ++ ) { addAction ( actions [ i ] ) ; } } public void removeAction ( LoadpathModifierAction action ) { fActions . remove ( action ) ; } public LoadpathModifierAction [ ] getActions ( ) { return ( LoadpathModifierAction [ ] ) fActions . toArray ( new LoadpathModifierAction [ fActions . size ( ) ] ) ; } private void addActionToMenu ( Menu parent , IAction action ) { ActionContributionItem item = new ActionContributionItem ( action ) ; item . fill ( parent , - ) ; } private void createEntries ( Menu menu ) { for ( int i = ; i < fActions . size ( ) ; i ++ ) { IAction action = ( IAction ) fActions . get ( i ) ; addActionToMenu ( menu , action ) ; } } public void dispose ( ) { if ( fMenu != null ) { fMenu . dispose ( ) ; fMenu = null ; } } public boolean isValid ( List selectedElements , int [ ] types ) throws RubyModelException { for ( int i = ; i < fActions . size ( ) ; i ++ ) { LoadpathModifierAction action = ( LoadpathModifierAction ) fActions . get ( i ) ; if ( action . isValid ( selectedElements , types ) ) { fIndex = i ; return true ; } } return false ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . forms . events . HyperlinkAdapter ; import org . eclipse . ui . forms . events . HyperlinkEvent ; import org . eclipse . ui . forms . widgets . FormText ; import org . eclipse . ui . forms . widgets . FormToolkit ; import org . eclipse . ui . forms . widgets . TableWrapData ; import org . eclipse . ui . forms . widgets . TableWrapLayout ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . ILoadpathInformationProvider ; import org . rubypeople . rdt . internal . corext . buildpath . IPackageExplorerActionListener ; import org . rubypeople . rdt . internal . corext . buildpath . PackageExplorerActionEvent ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . preferences . ScrolledPageContent ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup . DialogExplorerActionContext ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . ICreateFolderQuery ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . IInclusionExclusionQuery ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . ILinkToQuery ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . IRemoveLinkedFolderQuery ; public final class HintTextGroup implements ILoadpathInformationProvider , IPackageExplorerActionListener { private final static int [ ] ACTION_ORDER = { ILoadpathInformationProvider . CREATE_FOLDER , ILoadpathInformationProvider . CREATE_LINK , ILoadpathInformationProvider . EDIT_FILTERS , ILoadpathInformationProvider . EXCLUDE , ILoadpathInformationProvider . INCLUDE , ILoadpathInformationProvider . UNEXCLUDE , ILoadpathInformationProvider . UNINCLUDE , ILoadpathInformationProvider . CREATE_OUTPUT , ILoadpathInformationProvider . ADD_SEL_SF_TO_BP , ILoadpathInformationProvider . REMOVE_FROM_BP , ILoadpathInformationProvider . ADD_SEL_LIB_TO_BP , ILoadpathInformationProvider . ADD_LIB_TO_BP , ILoadpathInformationProvider . ADD_JAR_TO_BP } ; private Composite fTopComposite ; private DialogPackageExplorerActionGroup fActionGroup ; private DialogPackageExplorer fPackageExplorer ; private IRunnableContext fRunnableContext ; private IRubyProject fCurrJProject ; private List fNewFolders ; private HashMap fImageMap ; private final NewSourceContainerWorkbookPage fPage ; public HintTextGroup ( DialogPackageExplorer packageExplorer , IRunnableContext runnableContext , NewSourceContainerWorkbookPage page ) { fPackageExplorer = packageExplorer ; fRunnableContext = runnableContext ; fPage = page ; fCurrJProject = null ; fNewFolders = new ArrayList ( ) ; fImageMap = new HashMap ( ) ; } public Composite createControl ( Composite parent ) { fTopComposite = new Composite ( parent , SWT . NONE ) ; fTopComposite . setFont ( parent . getFont ( ) ) ; GridData gridData = new GridData ( GridData . FILL_BOTH ) ; PixelConverter converter = new PixelConverter ( parent ) ; gridData . heightHint = converter . convertHeightInCharsToPixels ( ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . marginWidth = ; gridLayout . marginHeight = ; fTopComposite . setLayout ( gridLayout ) ; fTopComposite . setLayoutData ( gridData ) ; fTopComposite . setData ( null ) ; fTopComposite . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { Collection collection = fImageMap . values ( ) ; Iterator iterator = collection . iterator ( ) ; while ( iterator . hasNext ( ) ) { Image image = ( Image ) iterator . next ( ) ; image . dispose ( ) ; } } } ) ; return fTopComposite ; } private Shell getShell ( ) { return RubyPlugin . getActiveWorkbenchShell ( ) ; } public void setRubyProject ( IRubyProject jProject ) { fCurrJProject = jProject ; } public void setActionGroup ( DialogPackageExplorerActionGroup actionGroup ) { fActionGroup = actionGroup ; } private FormText createFormText ( Composite parent , String text ) { FormToolkit toolkit = new FormToolkit ( getShell ( ) . getDisplay ( ) ) ; try { FormText formText = toolkit . createFormText ( parent , true ) ; formText . setFont ( parent . getFont ( ) ) ; try { formText . setText ( text , true , false ) ; } catch ( IllegalArgumentException e ) { formText . setText ( e . getMessage ( ) , false , false ) ; RubyPlugin . log ( e ) ; } formText . marginHeight = ; formText . marginWidth = ; formText . setBackground ( null ) ; formText . setLayoutData ( new TableWrapData ( TableWrapData . FILL_GRAB ) ) ; return formText ; } finally { toolkit . dispose ( ) ; } } private void createLabel ( Composite parent , String text , final LoadpathModifierAction action , final IRunnableContext context ) { FormText formText = createFormText ( parent , text ) ; Image image = ( Image ) fImageMap . get ( action . getId ( ) ) ; if ( image == null ) { image = action . getImageDescriptor ( ) . createImage ( ) ; fImageMap . put ( action . getId ( ) , image ) ; } formText . setImage ( "" , image ) ; formText . addHyperlinkListener ( new HyperlinkAdapter ( ) { public void linkActivated ( HyperlinkEvent e ) { try { context . run ( false , false , action . getOperation ( ) ) ; } catch ( InvocationTargetException err ) { ExceptionHandler . handle ( err , getShell ( ) , Messages . format ( NewWizardMessages . HintTextGroup_Exception_Title , action . getName ( ) ) , err . getMessage ( ) ) ; } catch ( InterruptedException err ) { } } } ) ; } public IStructuredSelection getSelection ( ) { return fPackageExplorer . getSelection ( ) ; } public void setSelection ( List elements ) { fPackageExplorer . setSelection ( elements ) ; } public IRubyProject getRubyProject ( ) { return fCurrJProject ; } public void handleResult ( List resultElements , CoreException exception , int actionType ) { if ( exception != null ) { ExceptionHandler . handle ( exception , getShell ( ) , Messages . format ( NewWizardMessages . HintTextGroup_Exception_Title_refresh , fActionGroup . getAction ( actionType ) . getName ( ) ) , exception . getLocalizedMessage ( ) ) ; return ; } switch ( actionType ) { case CREATE_FOLDER : handleFolderCreation ( resultElements ) ; break ; case CREATE_LINK : handleFolderCreation ( resultElements ) ; break ; case EDIT_FILTERS : defaultHandle ( resultElements , false ) ; break ; case ADD_SEL_SF_TO_BP : case ADD_SEL_LIB_TO_BP : case ADD_JAR_TO_BP : case ADD_LIB_TO_BP : handleAddToCP ( resultElements ) ; break ; case REMOVE_FROM_BP : handleRemoveFromBP ( resultElements , false ) ; break ; case INCLUDE : defaultHandle ( resultElements , true ) ; break ; case EXCLUDE : defaultHandle ( resultElements , false ) ; break ; case UNINCLUDE : defaultHandle ( resultElements , false ) ; break ; case UNEXCLUDE : defaultHandle ( resultElements , true ) ; break ; case RESET : defaultHandle ( resultElements , false ) ; break ; case RESET_ALL : handleResetAll ( ) ; break ; default : break ; } } private void defaultHandle ( List result , boolean forceRebuild ) { try { fPackageExplorer . setSelection ( result ) ; if ( forceRebuild ) { fActionGroup . refresh ( new DialogExplorerActionContext ( result , fCurrJProject ) ) ; } } catch ( RubyModelException e ) { ExceptionHandler . handle ( e , getShell ( ) , NewWizardMessages . HintTextGroup_Exception_Title_refresh , e . getLocalizedMessage ( ) ) ; } } private void handleFolderCreation ( List result ) { if ( result . size ( ) == ) { fNewFolders . add ( result . get ( ) ) ; fPackageExplorer . setSelection ( result ) ; } } private void handleAddToCP ( List result ) { try { if ( containsRubyProject ( result ) ) { fPackageExplorer . setSelection ( result ) ; fActionGroup . refresh ( new DialogExplorerActionContext ( result , fCurrJProject ) ) ; } else fPackageExplorer . setSelection ( result ) ; } catch ( RubyModelException e ) { ExceptionHandler . handle ( e , getShell ( ) , NewWizardMessages . HintTextGroup_Exception_Title_refresh , e . getLocalizedMessage ( ) ) ; } } private void handleRemoveFromBP ( List result , boolean forceRebuild ) { fPackageExplorer . setSelection ( result ) ; try { if ( forceRebuild || containsRubyProject ( result ) ) { fActionGroup . refresh ( new DialogExplorerActionContext ( result , fCurrJProject ) ) ; } } catch ( RubyModelException e ) { ExceptionHandler . handle ( e , getShell ( ) , NewWizardMessages . HintTextGroup_Exception_Title_refresh , e . getLocalizedMessage ( ) ) ; } } private void handleResetAll ( ) { List list = new ArrayList ( ) ; list . add ( fCurrJProject ) ; setSelection ( list ) ; } private boolean containsRubyProject ( List elements ) { for ( int i = ; i < elements . size ( ) ; i ++ ) { if ( elements . get ( i ) instanceof IRubyProject ) return true ; } return false ; } public IInclusionExclusionQuery getInclusionExclusionQuery ( ) { return LoadpathModifierQueries . getDefaultInclusionExclusionQuery ( getShell ( ) ) ; } public ILinkToQuery getLinkFolderQuery ( ) throws RubyModelException { return LoadpathModifierQueries . getDefaultLinkQuery ( getShell ( ) , fCurrJProject , null ) ; } public ICreateFolderQuery getCreateFolderQuery ( ) throws RubyModelException { return LoadpathModifierQueries . getDefaultCreateFolderQuery ( getShell ( ) , fCurrJProject ) ; } public IRemoveLinkedFolderQuery getRemoveLinkedFolderQuery ( ) throws RubyModelException { return LoadpathModifierQueries . getDefaultRemoveLinkedFolderQuery ( getShell ( ) ) ; } public void deleteCreatedResources ( ) { Iterator iterator = fNewFolders . iterator ( ) ; while ( iterator . hasNext ( ) ) { Object element = iterator . next ( ) ; IFolder folder ; try { if ( element instanceof IFolder ) folder = ( IFolder ) element ; else if ( element instanceof IRubyElement ) folder = fCurrJProject . getProject ( ) . getWorkspace ( ) . getRoot ( ) . getFolder ( ( ( IRubyElement ) element ) . getPath ( ) ) ; else { ( ( IFile ) element ) . delete ( false , null ) ; continue ; } folder . delete ( false , null ) ; } catch ( CoreException e ) { } } fNewFolders = new ArrayList ( ) ; } public void handlePackageExplorerActionEvent ( PackageExplorerActionEvent event ) { Composite childComposite = ( Composite ) fTopComposite . getData ( ) ; if ( childComposite != null && childComposite . getParent ( ) != null ) childComposite . getParent ( ) . dispose ( ) ; ScrolledPageContent spc = new ScrolledPageContent ( fTopComposite , SWT . V_SCROLL ) ; spc . getVerticalBar ( ) . setIncrement ( ) ; spc . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; childComposite = spc . getBody ( ) ; TableWrapLayout tableWrapLayout = new TableWrapLayout ( ) ; tableWrapLayout . leftMargin = ; tableWrapLayout . rightMargin = ; childComposite . setLayout ( tableWrapLayout ) ; childComposite . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . GRAB_HORIZONTAL ) ) ; fTopComposite . setData ( childComposite ) ; LoadpathModifierAction [ ] actions = event . getEnabledActions ( ) ; String [ ] descriptionText = event . getEnabledActionsText ( ) ; if ( noContextHelpAvailable ( actions ) ) { String noAction = fActionGroup . getNoActionDescription ( ) ; createFormText ( childComposite , Messages . format ( NewWizardMessages . HintTextGroup_NoAction , noAction ) ) ; fTopComposite . layout ( true ) ; return ; } for ( int j = ; j < ACTION_ORDER . length ; j ++ ) { for ( int i = ; i < actions . length ; i ++ ) { int id = Integer . parseInt ( actions [ i ] . getId ( ) ) ; if ( id == ACTION_ORDER [ j ] ) { createLabel ( childComposite , descriptionText [ i ] , actions [ i ] , fRunnableContext ) ; break ; } } } fTopComposite . layout ( true ) ; } private boolean noContextHelpAvailable ( LoadpathModifierAction [ ] actions ) { if ( actions . length == ) return true ; if ( actions . length == ) { int id = Integer . parseInt ( actions [ ] . getId ( ) ) ; if ( id == ILoadpathInformationProvider . CREATE_LINK ) return true ; } if ( actions . length == ) { int idLink = Integer . parseInt ( actions [ ] . getId ( ) ) ; int idReset = Integer . parseInt ( actions [ ] . getId ( ) ) ; if ( idReset == ILoadpathInformationProvider . RESET_ALL && idLink == ILoadpathInformationProvider . CREATE_LINK ) return true ; } return false ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public class HelpAction extends Action { public HelpAction ( ) { super ( ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_HELP ) ; setText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Help_label ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Help_tooltip ) ; } public void run ( ) { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . displayHelpResource ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Help_link ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . IRemoveLinkedFolderQuery ; class RemoveLinkedFolderDialog extends MessageDialog { private int fRemoveStatus = IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH_AND_FOLDER ; private Button fRemoveBuildPathAndFolder ; private Button fRemoveBuildPath ; RemoveLinkedFolderDialog ( final Shell shell , final IFolder folder ) { super ( shell , NewWizardMessages . LoadpathModifierQueries_confirm_remove_linked_folder_label , null , Messages . format ( NewWizardMessages . LoadpathModifierQueries_confirm_remove_linked_folder_message , new Object [ ] { folder . getFullPath ( ) } ) , MessageDialog . QUESTION , new String [ ] { IDialogConstants . YES_LABEL , IDialogConstants . NO_LABEL } , ) ; Assert . isTrue ( folder . isLinked ( ) ) ; } protected Control createCustomArea ( final Composite parent ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( new GridLayout ( ) ) ; fRemoveBuildPathAndFolder = new Button ( composite , SWT . RADIO ) ; fRemoveBuildPathAndFolder . addSelectionListener ( selectionListener ) ; fRemoveBuildPathAndFolder . setText ( NewWizardMessages . LoadpathModifierQueries_delete_linked_folder ) ; fRemoveBuildPathAndFolder . setFont ( parent . getFont ( ) ) ; fRemoveBuildPath = new Button ( composite , SWT . RADIO ) ; fRemoveBuildPath . addSelectionListener ( selectionListener ) ; fRemoveBuildPath . setText ( NewWizardMessages . LoadpathModifierQueries_do_not_delete_linked_folder ) ; fRemoveBuildPath . setFont ( parent . getFont ( ) ) ; fRemoveBuildPathAndFolder . setSelection ( fRemoveStatus == IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH_AND_FOLDER ) ; fRemoveBuildPath . setSelection ( fRemoveStatus == IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH ) ; return composite ; } private SelectionListener selectionListener = new SelectionAdapter ( ) { public final void widgetSelected ( final SelectionEvent event ) { final Button button = ( Button ) event . widget ; if ( button . getSelection ( ) ) fRemoveStatus = ( button == fRemoveBuildPathAndFolder ) ? IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH_AND_FOLDER : IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH ; } } ; public final int getRemoveStatus ( ) { return fRemoveStatus ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . part . Page ; import org . eclipse . ui . texteditor . IUpdate ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . AddSourceFolderWizard ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . EditFilterWizard ; import org . rubypeople . rdt . ui . actions . AbstractOpenWizardAction ; public class GenerateBuildPathActionGroup extends ActionGroup { public static final String MENU_ID = "" ; public static final String GROUP_BUILDPATH = "" ; public static final String GROUP_FILTER = "" ; public static final String GROUP_CUSTOMIZE = "" ; private static class NoActionAvailable extends Action { public NoActionAvailable ( ) { setEnabled ( false ) ; setText ( NewWizardMessages . GenerateBuildPathActionGroup_no_action_available ) ; } } private Action fNoActionAvailable = new NoActionAvailable ( ) ; private static abstract class OpenBuildPathWizardAction extends AbstractOpenWizardAction implements ISelectionChangedListener { public void selectionChanged ( SelectionChangedEvent event ) { ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { setEnabled ( selectionChanged ( ( IStructuredSelection ) selection ) ) ; } else { setEnabled ( selectionChanged ( StructuredSelection . EMPTY ) ) ; } } public abstract boolean selectionChanged ( IStructuredSelection selection ) ; } private abstract static class CreateSourceFolderAction extends OpenBuildPathWizardAction { private AddSourceFolderWizard fAddSourceFolderWizard ; private IRubyProject fSelectedProject ; private final boolean fIsLinked ; public CreateSourceFolderAction ( boolean isLinked ) { fIsLinked = isLinked ; } protected INewWizard createWizard ( ) throws CoreException { CPListElement newEntrie = new CPListElement ( fSelectedProject , ILoadpathEntry . CPE_SOURCE ) ; CPListElement [ ] existing = CPListElement . createFromExisting ( fSelectedProject ) ; boolean isProjectSrcFolder = CPListElement . isProjectSourceFolder ( existing , fSelectedProject ) ; fAddSourceFolderWizard = new AddSourceFolderWizard ( existing , newEntrie , fIsLinked , false , false , isProjectSrcFolder , isProjectSrcFolder ) ; return fAddSourceFolderWizard ; } public boolean selectionChanged ( IStructuredSelection selection ) { if ( selection . size ( ) == && selection . getFirstElement ( ) instanceof IRubyProject ) { fSelectedProject = ( IRubyProject ) selection . getFirstElement ( ) ; return true ; } return false ; } public List getCPListElements ( ) { return fAddSourceFolderWizard . getExistingEntries ( ) ; } } public static class CreateLocalSourceFolderAction extends CreateSourceFolderAction { public CreateLocalSourceFolderAction ( ) { super ( false ) ; setText ( ActionMessages . OpenNewSourceFolderWizardAction_text2 ) ; setDescription ( ActionMessages . OpenNewSourceFolderWizardAction_description ) ; setToolTipText ( ActionMessages . OpenNewSourceFolderWizardAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_TOOL_NEWPACKROOT ) ; } } public static class CreateLinkedSourceFolderAction extends CreateSourceFolderAction { public CreateLinkedSourceFolderAction ( ) { super ( true ) ; setText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Link_label ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Link_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_ELCL_ADD_LINKED_SOURCE_TO_BUILDPATH ) ; setDescription ( NewWizardMessages . PackageExplorerActionGroup_FormText_createLinkedFolder ) ; } } public static class EditFilterAction extends OpenBuildPathWizardAction { private IRubyProject fSelectedProject ; private IRubyElement fSelectedElement ; private EditFilterWizard fEditFilterWizard ; public EditFilterAction ( ) { setText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Edit_label ) ; setDescription ( NewWizardMessages . PackageExplorerActionGroup_FormText_Edit ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Edit_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_ELCL_CONFIGURE_BUILDPATH_FILTERS ) ; setDisabledImageDescriptor ( RubyPluginImages . DESC_DLCL_CONFIGURE_BUILDPATH_FILTERS ) ; } protected INewWizard createWizard ( ) throws CoreException { CPListElement [ ] existingEntries = CPListElement . createFromExisting ( fSelectedProject ) ; CPListElement elementToEdit = findElement ( fSelectedElement , existingEntries ) ; fEditFilterWizard = new EditFilterWizard ( existingEntries , elementToEdit ) ; return fEditFilterWizard ; } public boolean selectionChanged ( IStructuredSelection selection ) { if ( selection . size ( ) != ) return false ; try { Object element = selection . getFirstElement ( ) ; if ( element instanceof IRubyProject ) { IRubyProject project = ( IRubyProject ) element ; if ( LoadpathModifier . isSourceFolder ( project ) ) { fSelectedProject = project ; fSelectedElement = ( IRubyElement ) element ; return true ; } } else if ( element instanceof ISourceFolderRoot ) { ISourceFolderRoot packageFragmentRoot = ( ( ISourceFolderRoot ) element ) ; IRubyProject project = packageFragmentRoot . getRubyProject ( ) ; if ( project != null ) { fSelectedProject = project ; fSelectedElement = ( IRubyElement ) element ; return true ; } } } catch ( RubyModelException e ) { return false ; } return false ; } private static CPListElement findElement ( IRubyElement element , CPListElement [ ] elements ) { IPath path = element . getPath ( ) ; for ( int i = ; i < elements . length ; i ++ ) { CPListElement cur = elements [ i ] ; if ( cur . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE && cur . getPath ( ) . equals ( path ) ) { return cur ; } } return null ; } public List getCPListElements ( ) { return fEditFilterWizard . getExistingEntries ( ) ; } } private IWorkbenchSite fSite ; private List fActions ; private String fGroupName = IContextMenuConstants . GROUP_REORGANIZE ; public GenerateBuildPathActionGroup ( Page page ) { this ( page . getSite ( ) ) ; } public GenerateBuildPathActionGroup ( IViewPart part ) { this ( part . getSite ( ) ) ; } private GenerateBuildPathActionGroup ( IWorkbenchSite site ) { fSite = site ; fActions = new ArrayList ( ) ; final CreateLinkedSourceFolderAction addLinkedSourceFolderAction = new CreateLinkedSourceFolderAction ( ) ; fActions . add ( addLinkedSourceFolderAction ) ; final CreateLocalSourceFolderAction addSourceFolderAction = new CreateLocalSourceFolderAction ( ) ; fActions . add ( addSourceFolderAction ) ; final AddFolderToBuildpathAction addFolder = new AddFolderToBuildpathAction ( site ) ; fActions . add ( addFolder ) ; final AddSelectedLibraryToBuildpathAction addSelectedLibrary = new AddSelectedLibraryToBuildpathAction ( site ) ; fActions . add ( addSelectedLibrary ) ; final RemoveFromBuildpathAction remove = new RemoveFromBuildpathAction ( site ) ; fActions . add ( remove ) ; final AddLibraryToBuildpathAction addLibrary = new AddLibraryToBuildpathAction ( site ) ; fActions . add ( addLibrary ) ; final ExcludeFromBuildpathAction exclude = new ExcludeFromBuildpathAction ( site ) ; fActions . add ( exclude ) ; final IncludeToBuildpathAction include = new IncludeToBuildpathAction ( site ) ; fActions . add ( include ) ; final EditFilterAction editFilterAction = new EditFilterAction ( ) ; fActions . add ( editFilterAction ) ; final ConfigureBuildPathAction configure = new ConfigureBuildPathAction ( site ) ; fActions . add ( configure ) ; final ISelectionProvider provider = fSite . getSelectionProvider ( ) ; for ( Iterator iter = fActions . iterator ( ) ; iter . hasNext ( ) ; ) { Action action = ( Action ) iter . next ( ) ; if ( action instanceof ISelectionChangedListener ) { provider . addSelectionChangedListener ( ( ISelectionChangedListener ) action ) ; } } } public void fillActionBars ( IActionBars actionBar ) { super . fillActionBars ( actionBar ) ; setGlobalActionHandlers ( actionBar ) ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; if ( ! canOperateOnSelection ( ) ) return ; String menuText = ActionMessages . BuildPath_label ; IMenuManager subMenu = new MenuManager ( menuText , MENU_ID ) ; subMenu . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager manager ) { fillViewSubMenu ( manager ) ; } } ) ; subMenu . setRemoveAllWhenShown ( true ) ; subMenu . add ( new ConfigureBuildPathAction ( fSite ) ) ; menu . appendToGroup ( fGroupName , subMenu ) ; } private void fillViewSubMenu ( IMenuManager source ) { int added = ; int i = ; for ( Iterator iter = fActions . iterator ( ) ; iter . hasNext ( ) ; ) { Action action = ( Action ) iter . next ( ) ; if ( action instanceof IUpdate ) ( ( IUpdate ) action ) . update ( ) ; if ( i == ) source . add ( new Separator ( GROUP_BUILDPATH ) ) ; else if ( i == ) source . add ( new Separator ( GROUP_FILTER ) ) ; else if ( i == ) source . add ( new Separator ( GROUP_CUSTOMIZE ) ) ; added += addAction ( source , action ) ; i ++ ; } if ( added == ) { source . add ( fNoActionAvailable ) ; } } private void setGlobalActionHandlers ( IActionBars actionBar ) { } private int addAction ( IMenuManager menu , IAction action ) { if ( action != null && action . isEnabled ( ) ) { menu . add ( action ) ; return ; } return ; } private boolean canOperateOnSelection ( ) { ISelection sel = fSite . getSelectionProvider ( ) . getSelection ( ) ; if ( ! ( sel instanceof IStructuredSelection ) ) return false ; IStructuredSelection selection = ( IStructuredSelection ) sel ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof IWorkingSet ) return false ; } return true ; } public void dispose ( ) { if ( fActions != null ) { final ISelectionProvider provider = fSite . getSelectionProvider ( ) ; for ( Iterator iter = fActions . iterator ( ) ; iter . hasNext ( ) ; ) { Action action = ( Action ) iter . next ( ) ; if ( action instanceof ISelectionChangedListener ) provider . removeSelectionChangedListener ( ( ISelectionChangedListener ) action ) ; } } fActions = null ; super . dispose ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . NewFolderDialog ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . ExclusionInclusionDialog ; public class LoadpathModifierQueries { public static interface ILinkToQuery { public boolean doQuery ( ) ; public IFolder getCreatedFolder ( ) ; } public static interface IInclusionExclusionQuery { public boolean doQuery ( CPListElement element , boolean focusOnExcluded ) ; public IPath [ ] getInclusionPattern ( ) ; public IPath [ ] getExclusionPattern ( ) ; } public static interface IRemoveLinkedFolderQuery { public static final int REMOVE_CANCEL = ; public static final int REMOVE_BUILD_PATH = ; public static final int REMOVE_BUILD_PATH_AND_FOLDER = ; public int doQuery ( IFolder folder ) ; } public static interface ICreateFolderQuery { public boolean doQuery ( ) ; public boolean isSourceFolder ( ) ; public IFolder getCreatedFolder ( ) ; } public static interface IAddLibrariesQuery { public ILoadpathEntry [ ] doQuery ( final IRubyProject project , final ILoadpathEntry [ ] entries ) ; } public static IInclusionExclusionQuery getDefaultInclusionExclusionQuery ( final Shell shell ) { return new IInclusionExclusionQuery ( ) { protected IPath [ ] fInclusionPattern ; protected IPath [ ] fExclusionPattern ; public boolean doQuery ( final CPListElement element , final boolean focusOnExcluded ) { final boolean [ ] result = { false } ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { Shell sh = shell != null ? shell : RubyPlugin . getActiveWorkbenchShell ( ) ; ExclusionInclusionDialog dialog = new ExclusionInclusionDialog ( sh , element , focusOnExcluded ) ; result [ ] = dialog . open ( ) == Window . OK ; fInclusionPattern = dialog . getInclusionPattern ( ) ; fExclusionPattern = dialog . getExclusionPattern ( ) ; } } ) ; return result [ ] ; } public IPath [ ] getInclusionPattern ( ) { return fInclusionPattern ; } public IPath [ ] getExclusionPattern ( ) { return fExclusionPattern ; } } ; } public static ILinkToQuery getDefaultLinkQuery ( final Shell shell , final IRubyProject project , final IPath desiredOutputLocation ) { return new ILinkToQuery ( ) { protected IFolder fFolder ; public boolean doQuery ( ) { final boolean [ ] isOK = { false } ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { Shell sh = shell != null ? shell : RubyPlugin . getActiveWorkbenchShell ( ) ; LinkFolderDialog dialog = new LinkFolderDialog ( sh , project . getProject ( ) ) ; isOK [ ] = dialog . open ( ) == Window . OK ; if ( isOK [ ] ) fFolder = dialog . getCreatedFolder ( ) ; } } ) ; return isOK [ ] ; } public IFolder getCreatedFolder ( ) { return fFolder ; } } ; } public static IRemoveLinkedFolderQuery getDefaultRemoveLinkedFolderQuery ( final Shell shell ) { return new IRemoveLinkedFolderQuery ( ) { public final int doQuery ( final IFolder folder ) { final int [ ] result = { IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH } ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public final void run ( ) { final RemoveLinkedFolderDialog dialog = new RemoveLinkedFolderDialog ( ( shell != null ? shell : RubyPlugin . getActiveWorkbenchShell ( ) ) , folder ) ; final int status = dialog . open ( ) ; if ( status == ) result [ ] = dialog . getRemoveStatus ( ) ; else result [ ] = IRemoveLinkedFolderQuery . REMOVE_CANCEL ; } } ) ; return result [ ] ; } } ; } public static ICreateFolderQuery getDefaultCreateFolderQuery ( final Shell shell , final IRubyProject project ) { return new ICreateFolderQuery ( ) { private IFolder fNewFolder ; public boolean doQuery ( ) { final boolean [ ] isOK = { false } ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { Shell sh = shell != null ? shell : RubyPlugin . getActiveWorkbenchShell ( ) ; NewFolderDialog dialog = new NewFolderDialog ( sh , project . getProject ( ) ) ; isOK [ ] = dialog . open ( ) == Window . OK ; if ( isOK [ ] ) { IResource sourceContainer = ( IResource ) dialog . getResult ( ) [ ] ; if ( sourceContainer instanceof IFolder ) { fNewFolder = ( IFolder ) sourceContainer ; } else { fNewFolder = null ; } } } } ) ; return isOK [ ] ; } public boolean isSourceFolder ( ) { return true ; } public IFolder getCreatedFolder ( ) { return fNewFolder ; } } ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . part . ISetSelectionTarget ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . WorkbenchRunnableAdapter ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . LoadpathContainerWizard ; public class AddLibraryToBuildpathAction extends Action implements ISelectionChangedListener { private IRubyProject fSelectedProject ; private final IWorkbenchSite fSite ; public AddLibraryToBuildpathAction ( IWorkbenchSite site ) { super ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddLibCP_label , RubyPluginImages . DESC_OBJS_LIBRARY ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddLibCP_tooltip ) ; fSite = site ; } public void run ( ) { final IRubyProject project = fSelectedProject ; Shell shell = fSite . getShell ( ) ; if ( shell == null ) { shell = RubyPlugin . getActiveWorkbenchShell ( ) ; } ILoadpathEntry [ ] classpath ; try { classpath = project . getRawLoadpath ( ) ; } catch ( RubyModelException e1 ) { showExceptionDialog ( e1 ) ; return ; } LoadpathContainerWizard wizard = new LoadpathContainerWizard ( ( ILoadpathEntry ) null , project , classpath ) { public boolean performFinish ( ) { if ( super . performFinish ( ) ) { IWorkspaceRunnable op = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException , OperationCanceledException { try { finishPage ( monitor ) ; } catch ( InterruptedException e ) { throw new OperationCanceledException ( e . getMessage ( ) ) ; } } } ; try { ISchedulingRule rule = null ; Job job = Platform . getJobManager ( ) . currentJob ( ) ; if ( job != null ) rule = job . getRule ( ) ; IRunnableWithProgress runnable = null ; if ( rule != null ) runnable = new WorkbenchRunnableAdapter ( op , rule , true ) ; else runnable = new WorkbenchRunnableAdapter ( op , ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; getContainer ( ) . run ( false , true , runnable ) ; } catch ( InvocationTargetException e ) { RubyPlugin . log ( e ) ; return false ; } catch ( InterruptedException e ) { return false ; } return true ; } return false ; } private void finishPage ( IProgressMonitor pm ) throws InterruptedException { ILoadpathEntry [ ] selected = getNewEntries ( ) ; if ( selected != null ) { try { pm . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_AddToBuildpath , ) ; List addedEntries = new ArrayList ( ) ; for ( int i = ; i < selected . length ; i ++ ) { addedEntries . add ( new CPListElement ( project , ILoadpathEntry . CPE_CONTAINER , selected [ i ] . getPath ( ) , null ) ) ; } pm . worked ( ) ; if ( pm . isCanceled ( ) ) throw new InterruptedException ( ) ; List existingEntries = LoadpathModifier . getExistingEntries ( project ) ; LoadpathModifier . setNewEntry ( existingEntries , addedEntries , project , new SubProgressMonitor ( pm , ) ) ; if ( pm . isCanceled ( ) ) throw new InterruptedException ( ) ; LoadpathModifier . commitLoadPath ( existingEntries , project , new SubProgressMonitor ( pm , ) ) ; if ( pm . isCanceled ( ) ) throw new InterruptedException ( ) ; List result = new ArrayList ( addedEntries . size ( ) ) ; for ( int i = ; i < addedEntries . size ( ) ; i ++ ) { result . add ( new LoadPathContainer ( project , selected [ i ] ) ) ; } selectAndReveal ( new StructuredSelection ( result ) ) ; pm . worked ( ) ; } catch ( CoreException e ) { showExceptionDialog ( e ) ; } finally { pm . done ( ) ; } } } } ; wizard . setNeedsProgressMonitor ( true ) ; WizardDialog dialog = new WizardDialog ( shell , wizard ) ; PixelConverter converter = new PixelConverter ( shell ) ; dialog . setMinimumPageSize ( converter . convertWidthInCharsToPixels ( ) , converter . convertHeightInCharsToPixels ( ) ) ; dialog . create ( ) ; dialog . open ( ) ; } public void selectionChanged ( SelectionChangedEvent event ) { ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { setEnabled ( canHandle ( ( IStructuredSelection ) selection ) ) ; } else { setEnabled ( canHandle ( StructuredSelection . EMPTY ) ) ; } } public boolean canHandle ( IStructuredSelection selection ) { if ( selection . size ( ) == && selection . getFirstElement ( ) instanceof IRubyProject ) { fSelectedProject = ( IRubyProject ) selection . getFirstElement ( ) ; return true ; } return false ; } private void showExceptionDialog ( CoreException exception ) { showError ( exception , fSite . getShell ( ) , NewWizardMessages . AddLibraryToBuildpathAction_ErrorTitle , exception . getMessage ( ) ) ; } private void showError ( CoreException e , Shell shell , String title , String message ) { IStatus status = e . getStatus ( ) ; if ( status != null ) { ErrorDialog . openError ( shell , message , title , status ) ; } else { MessageDialog . openError ( shell , title , message ) ; } } private void selectAndReveal ( final ISelection selection ) { IWorkbenchPage page = fSite . getPage ( ) ; if ( page == null ) return ; List parts = new ArrayList ( ) ; IWorkbenchPartReference refs [ ] = page . getViewReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { IWorkbenchPart part = refs [ i ] . getPart ( false ) ; if ( part != null ) parts . add ( part ) ; } refs = page . getEditorReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { if ( refs [ i ] . getPart ( false ) != null ) parts . add ( refs [ i ] . getPart ( false ) ) ; } Iterator itr = parts . iterator ( ) ; while ( itr . hasNext ( ) ) { IWorkbenchPart part = ( IWorkbenchPart ) itr . next ( ) ; ISetSelectionTarget target = null ; if ( part instanceof ISetSelectionTarget ) target = ( ISetSelectionTarget ) part ; else target = ( ISetSelectionTarget ) part . getAdapter ( ISetSelectionTarget . class ) ; if ( target != null ) { final ISetSelectionTarget finalTarget = target ; page . getWorkbenchWindow ( ) . getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { finalTarget . selectReveal ( selection ) ; } } ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; import org . rubypeople . rdt . internal . ui . preferences . BuildPathsPropertyPage ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public class ConfigureBuildPathAction extends Action implements ISelectionChangedListener { private final IWorkbenchSite fSite ; private IProject fProject ; public ConfigureBuildPathAction ( IWorkbenchSite site ) { super ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_ConfigureBP_label , RubyPluginImages . DESC_ELCL_CONFIGURE_BUILDPATH ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_ConfigureBP_tooltip ) ; setDisabledImageDescriptor ( RubyPluginImages . DESC_DLCL_CONFIGURE_BUILDPATH ) ; fSite = site ; } private Shell getShell ( ) { return fSite . getShell ( ) ; } public void run ( ) { if ( fProject != null ) { PreferencesUtil . createPropertyDialogOn ( getShell ( ) , fProject , BuildPathsPropertyPage . PROP_ID , null , null ) . open ( ) ; } } public void selectionChanged ( final SelectionChangedEvent event ) { final ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { setEnabled ( canHandle ( ( IStructuredSelection ) selection ) ) ; } else { setEnabled ( canHandle ( StructuredSelection . EMPTY ) ) ; } } private boolean canHandle ( IStructuredSelection elements ) { if ( elements . size ( ) != ) return false ; Object firstElement = elements . getFirstElement ( ) ; fProject = getProjectFromSelectedElement ( firstElement ) ; return fProject != null ; } private IProject getProjectFromSelectedElement ( Object firstElement ) { if ( firstElement instanceof IRubyElement ) { IRubyElement element = ( IRubyElement ) firstElement ; ISourceFolderRoot root = RubyModelUtil . getSourceFolderRoot ( element ) ; if ( root != null && root != element && root . isArchive ( ) ) { return null ; } IRubyProject project = element . getRubyProject ( ) ; if ( project != null ) { return project . getProject ( ) ; } return null ; } else if ( firstElement instanceof LoadPathContainer ) { return ( ( LoadPathContainer ) firstElement ) . getRubyProject ( ) . getProject ( ) ; } else if ( firstElement instanceof IAdaptable ) { IResource res = ( IResource ) ( ( IAdaptable ) firstElement ) . getAdapter ( IResource . class ) ; if ( res != null ) { return res . getProject ( ) ; } } return null ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . ISetSelectionTarget ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . BuildPathBasePage ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; public class AddFolderToBuildpathAction extends Action implements ISelectionChangedListener { private final IWorkbenchSite fSite ; private final List fSelectedElements ; public AddFolderToBuildpathAction ( IWorkbenchSite site ) { super ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_label , RubyPluginImages . DESC_OBJS_SOURCE_FOLDER_ROOT ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_tooltip ) ; fSite = site ; fSelectedElements = new ArrayList ( ) ; } public void run ( ) { final IRubyProject project ; Object object = fSelectedElements . get ( ) ; if ( object instanceof IRubyProject ) { project = ( IRubyProject ) object ; } else if ( object instanceof ISourceFolder ) { project = ( ( ISourceFolder ) object ) . getRubyProject ( ) ; } else { IFolder folder = ( IFolder ) object ; project = RubyCore . create ( folder . getProject ( ) ) ; if ( project == null ) return ; } final Shell shell = fSite . getShell ( ) != null ? fSite . getShell ( ) : RubyPlugin . getActiveWorkbenchShell ( ) ; IPath projPath = project . getProject ( ) . getFullPath ( ) ; try { final IRunnableWithProgress runnable = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { try { List result = addToLoadpath ( fSelectedElements , project , null , false , false , monitor ) ; selectAndReveal ( new StructuredSelection ( result ) ) ; } catch ( CoreException e ) { throw new InvocationTargetException ( e ) ; } } } ; PlatformUI . getWorkbench ( ) . getProgressService ( ) . run ( true , false , runnable ) ; } catch ( final InvocationTargetException e ) { if ( e . getCause ( ) instanceof CoreException ) { showExceptionDialog ( ( CoreException ) e . getCause ( ) ) ; } else { RubyPlugin . log ( e ) ; } } catch ( final InterruptedException e ) { } } private List addToLoadpath ( List elements , IRubyProject project , IPath outputLocation , boolean removeProjectFromLoadpath , boolean removeOldClassFiles , IProgressMonitor monitor ) throws OperationCanceledException , CoreException { if ( ! project . getProject ( ) . hasNature ( RubyCore . NATURE_ID ) ) { StatusInfo rootStatus = new StatusInfo ( ) ; rootStatus . setError ( NewWizardMessages . LoadpathModifier_Error_NoNatures ) ; throw new CoreException ( rootStatus ) ; } try { monitor . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_AddToBuildpath , elements . size ( ) + ) ; IWorkspaceRoot workspaceRoot = RubyPlugin . getWorkspace ( ) . getRoot ( ) ; monitor . worked ( ) ; List existingEntries = LoadpathModifier . getExistingEntries ( project ) ; if ( removeProjectFromLoadpath ) { LoadpathModifier . removeFromLoadpath ( project , existingEntries , new SubProgressMonitor ( monitor , ) ) ; } else { monitor . worked ( ) ; } List newEntries = new ArrayList ( ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { Object element = elements . get ( i ) ; CPListElement entry ; if ( element instanceof IResource ) entry = LoadpathModifier . addToLoadpath ( ( IResource ) element , existingEntries , newEntries , project , new SubProgressMonitor ( monitor , ) ) ; else entry = LoadpathModifier . addToLoadpath ( ( IRubyElement ) element , existingEntries , newEntries , project , new SubProgressMonitor ( monitor , ) ) ; newEntries . add ( entry ) ; } Set modifiedSourceEntries = new HashSet ( ) ; BuildPathBasePage . fixNestingConflicts ( ( CPListElement [ ] ) newEntries . toArray ( new CPListElement [ newEntries . size ( ) ] ) , ( CPListElement [ ] ) existingEntries . toArray ( new CPListElement [ existingEntries . size ( ) ] ) , modifiedSourceEntries ) ; LoadpathModifier . setNewEntry ( existingEntries , newEntries , project , new SubProgressMonitor ( monitor , ) ) ; LoadpathModifier . commitLoadPath ( existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; List result = new ArrayList ( ) ; for ( int i = ; i < newEntries . size ( ) ; i ++ ) { ILoadpathEntry entry = ( ( CPListElement ) newEntries . get ( i ) ) . getLoadpathEntry ( ) ; IRubyElement root ; if ( entry . getPath ( ) . equals ( project . getPath ( ) ) ) root = project ; else root = project . findSourceFolderRoot ( entry . getPath ( ) ) ; if ( root != null ) { result . add ( root ) ; } } return result ; } finally { monitor . done ( ) ; } } public void selectionChanged ( final SelectionChangedEvent event ) { final ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { setEnabled ( canHandle ( ( IStructuredSelection ) selection ) ) ; } else { setEnabled ( canHandle ( StructuredSelection . EMPTY ) ) ; } } private boolean canHandle ( IStructuredSelection elements ) { if ( elements . size ( ) == ) return false ; try { fSelectedElements . clear ( ) ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; fSelectedElements . add ( element ) ; if ( element instanceof IRubyProject ) { if ( LoadpathModifier . isSourceFolder ( ( IRubyProject ) element ) ) return false ; } else if ( element instanceof ISourceFolder ) { int type = DialogPackageExplorerActionGroup . getType ( element , ( ( ISourceFolder ) element ) . getRubyProject ( ) ) ; if ( type != DialogPackageExplorerActionGroup . SOURCE_FOLDER && type != DialogPackageExplorerActionGroup . INCLUDED_FOLDER ) return false ; } else if ( element instanceof IFolder ) { IProject project = ( ( IFolder ) element ) . getProject ( ) ; IRubyProject javaProject = RubyCore . create ( project ) ; if ( javaProject == null || ! javaProject . exists ( ) ) return false ; } else { return false ; } } return true ; } catch ( CoreException e ) { } return false ; } private void showExceptionDialog ( CoreException exception ) { showError ( exception , fSite . getShell ( ) , NewWizardMessages . AddSourceFolderToBuildpathAction_ErrorTitle , exception . getMessage ( ) ) ; } private void showError ( CoreException e , Shell shell , String title , String message ) { IStatus status = e . getStatus ( ) ; if ( status != null ) { ErrorDialog . openError ( shell , message , title , status ) ; } else { MessageDialog . openError ( shell , title , message ) ; } } private void selectAndReveal ( final ISelection selection ) { IWorkbenchPage page = fSite . getPage ( ) ; if ( page == null ) return ; List parts = new ArrayList ( ) ; IWorkbenchPartReference refs [ ] = page . getViewReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { IWorkbenchPart part = refs [ i ] . getPart ( false ) ; if ( part != null ) parts . add ( part ) ; } refs = page . getEditorReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { if ( refs [ i ] . getPart ( false ) != null ) parts . add ( refs [ i ] . getPart ( false ) ) ; } Iterator itr = parts . iterator ( ) ; while ( itr . hasNext ( ) ) { IWorkbenchPart part = ( IWorkbenchPart ) itr . next ( ) ; ISetSelectionTarget target = null ; if ( part instanceof ISetSelectionTarget ) target = ( ISetSelectionTarget ) part ; else target = ( ISetSelectionTarget ) part . getAdapter ( ISetSelectionTarget . class ) ; if ( target != null ) { final ISetSelectionTarget finalTarget = target ; page . getWorkbenchWindow ( ) . getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { finalTarget . selectReveal ( selection ) ; } } ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Menu ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . filters . LibraryFilter ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . DecoratingRubyLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElementAttribute ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListLabelProvider ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup . DialogExplorerActionContext ; import org . rubypeople . rdt . internal . ui . workingsets . WorkingSetModel ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . RubyElementSorter ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; public class DialogPackageExplorer implements IMenuListener , ISelectionChangedListener { private final class PackageContentProvider extends StandardRubyElementContentProvider { public PackageContentProvider ( ) { super ( ) ; } public Object [ ] getElements ( Object element ) { if ( fCurrJProject == null ) return new Object [ ] ; return new Object [ ] { fCurrJProject } ; } } private final class PackageLabelProvider extends AppearanceAwareLabelProvider { private CPListLabelProvider outputFolderLabel ; public PackageLabelProvider ( long textFlags , int imageFlags ) { super ( textFlags , imageFlags ) ; outputFolderLabel = new CPListLabelProvider ( ) ; } public String getText ( Object element ) { if ( element instanceof CPListElementAttribute ) return outputFolderLabel . getText ( element ) ; String text = super . getText ( element ) ; try { if ( element instanceof ISourceFolderRoot ) { ISourceFolderRoot root = ( ISourceFolderRoot ) element ; if ( root . exists ( ) && LoadpathModifier . filtersSet ( root ) ) { ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; int excluded = entry . getExclusionPatterns ( ) . length ; if ( excluded == ) return Messages . format ( NewWizardMessages . DialogPackageExplorer_LabelProvider_SingleExcluded , text ) ; else if ( excluded > ) return Messages . format ( NewWizardMessages . DialogPackageExplorer_LabelProvider_MultiExcluded , new Object [ ] { text , new Integer ( excluded ) } ) ; } } if ( element instanceof IRubyProject ) { IRubyProject project = ( IRubyProject ) element ; if ( project . exists ( ) && project . isOnLoadpath ( project ) ) { ISourceFolderRoot root = project . findSourceFolderRoot ( project . getPath ( ) ) ; if ( LoadpathModifier . filtersSet ( root ) ) { ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; int excluded = entry . getExclusionPatterns ( ) . length ; if ( excluded == ) return Messages . format ( NewWizardMessages . DialogPackageExplorer_LabelProvider_SingleExcluded , text ) ; else if ( excluded > ) return Messages . format ( NewWizardMessages . DialogPackageExplorer_LabelProvider_MultiExcluded , new Object [ ] { text , new Integer ( excluded ) } ) ; } } } if ( element instanceof IFile || element instanceof IFolder ) { IResource resource = ( IResource ) element ; if ( resource . exists ( ) && LoadpathModifier . isExcluded ( resource , fCurrJProject ) ) return Messages . format ( NewWizardMessages . DialogPackageExplorer_LabelProvider_Excluded , text ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return text ; } public Color getForeground ( Object element ) { try { if ( element instanceof ISourceFolderRoot ) { ISourceFolderRoot root = ( ISourceFolderRoot ) element ; if ( root . exists ( ) && LoadpathModifier . filtersSet ( root ) ) return getBlueColor ( ) ; } if ( element instanceof IRubyProject ) { IRubyProject project = ( IRubyProject ) element ; if ( project . exists ( ) && project . isOnLoadpath ( project ) ) { ISourceFolderRoot root = project . findSourceFolderRoot ( project . getPath ( ) ) ; if ( root != null && LoadpathModifier . filtersSet ( root ) ) return getBlueColor ( ) ; } } if ( element instanceof IFile || element instanceof IFolder ) { IResource resource = ( IResource ) element ; if ( resource . exists ( ) && LoadpathModifier . isExcluded ( resource , fCurrJProject ) ) return getBlueColor ( ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return null ; } private Color getBlueColor ( ) { return Display . getCurrent ( ) . getSystemColor ( SWT . COLOR_BLUE ) ; } public Image getImage ( Object element ) { if ( element instanceof CPListElementAttribute ) return outputFolderLabel . getImage ( element ) ; return super . getImage ( element ) ; } public void dispose ( ) { outputFolderLabel . dispose ( ) ; super . dispose ( ) ; } } private final class ExtendedRubyElementSorter extends RubyElementSorter { public ExtendedRubyElementSorter ( ) { super ( ) ; } public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( e1 instanceof CPListElementAttribute ) return - ; if ( e2 instanceof CPListElementAttribute ) return ; return super . compare ( viewer , e1 , e2 ) ; } } private final class PackageFilter extends LibraryFilter { public boolean select ( Viewer viewer , Object parentElement , Object element ) { try { if ( element instanceof IFile ) { IFile file = ( IFile ) element ; if ( file . getName ( ) . equals ( "" ) || file . getName ( ) . equals ( "" ) ) return false ; } if ( element instanceof ISourceFolderRoot ) { ILoadpathEntry cpe = ( ( ISourceFolderRoot ) element ) . getRawLoadpathEntry ( ) ; if ( cpe == null || cpe . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) return false ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return super . select ( viewer , parentElement , element ) ; } } private TreeViewer fPackageViewer ; private Menu fContextMenu ; private DialogPackageExplorerActionGroup fActionGroup ; private boolean fShowOutputFolders = false ; private IStructuredSelection fCurrentSelection ; private IRubyProject fCurrJProject ; public DialogPackageExplorer ( ) { fActionGroup = null ; fCurrJProject = null ; fCurrentSelection = new StructuredSelection ( ) ; } public Control createControl ( Composite parent ) { fPackageViewer = new TreeViewer ( parent , SWT . MULTI ) ; fPackageViewer . setComparer ( WorkingSetModel . COMPARER ) ; fPackageViewer . addFilter ( new PackageFilter ( ) ) ; fPackageViewer . setSorter ( new ExtendedRubyElementSorter ( ) ) ; fPackageViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { Object element = ( ( IStructuredSelection ) event . getSelection ( ) ) . getFirstElement ( ) ; if ( fPackageViewer . isExpandable ( element ) ) { fPackageViewer . setExpandedState ( element , ! fPackageViewer . getExpandedState ( element ) ) ; } } } ) ; fPackageViewer . addSelectionChangedListener ( this ) ; MenuManager menuMgr = new MenuManager ( "" ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( this ) ; fContextMenu = menuMgr . createContextMenu ( fPackageViewer . getTree ( ) ) ; fPackageViewer . getTree ( ) . setMenu ( fContextMenu ) ; parent . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { fContextMenu . dispose ( ) ; } } ) ; return fPackageViewer . getControl ( ) ; } public void setActionGroup ( final DialogPackageExplorerActionGroup actionGroup ) { fActionGroup = actionGroup ; fPackageViewer . getControl ( ) . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { if ( actionGroup != null ) actionGroup . dispose ( ) ; } } ) ; } public void menuAboutToShow ( IMenuManager manager ) { if ( fActionGroup == null ) return ; RubyPlugin . createStandardGroups ( manager ) ; fActionGroup . fillContextMenu ( manager ) ; } public void setContentProvider ( ) { PackageContentProvider contentProvider = new PackageContentProvider ( ) ; PackageLabelProvider labelProvider = new PackageLabelProvider ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS | RubyElementLabels . P_COMPRESSED , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS | RubyElementImageProvider . SMALL_ICONS ) ; fPackageViewer . setContentProvider ( contentProvider ) ; fPackageViewer . setLabelProvider ( new DecoratingRubyLabelProvider ( labelProvider , false ) ) ; } public void setInput ( IRubyProject project ) { fCurrJProject = project ; fPackageViewer . setInput ( new Object ( ) ) ; IStructuredSelection selection = new StructuredSelection ( project ) ; fPackageViewer . setSelection ( selection ) ; fPackageViewer . expandToLevel ( ) ; fCurrentSelection = selection ; try { if ( fActionGroup != null ) fActionGroup . refresh ( new DialogExplorerActionContext ( fCurrentSelection , fCurrJProject ) ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } public void refresh ( ) { fPackageViewer . refresh ( true ) ; } public void setSelection ( List elements ) { if ( elements == null || elements . size ( ) == ) return ; fPackageViewer . refresh ( ) ; IStructuredSelection selection = new StructuredSelection ( elements ) ; fPackageViewer . setSelection ( selection , true ) ; fPackageViewer . getTree ( ) . setFocus ( ) ; if ( elements . size ( ) == && elements . get ( ) instanceof IRubyProject ) fPackageViewer . expandToLevel ( elements . get ( ) , ) ; } public IStructuredSelection getSelection ( ) { return fCurrentSelection ; } public Control getViewerControl ( ) { return fPackageViewer . getControl ( ) ; } private boolean isSelected ( ) { return fShowOutputFolders ; } public void selectionChanged ( SelectionChangedEvent event ) { fCurrentSelection = ( IStructuredSelection ) event . getSelection ( ) ; try { if ( fActionGroup != null ) fActionGroup . setContext ( new DialogExplorerActionContext ( fCurrentSelection , fCurrJProject ) ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . ISetSelectionTarget ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; public class IncludeToBuildpathAction extends Action implements ISelectionChangedListener { private final IWorkbenchSite fSite ; private final List fSelectedElements ; public IncludeToBuildpathAction ( IWorkbenchSite site ) { super ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Unexclude_label , RubyPluginImages . DESC_ELCL_INCLUDE_ON_BUILDPATH ) ; setToolTipText ( NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Unexclude_tooltip ) ; setDisabledImageDescriptor ( RubyPluginImages . DESC_DLCL_INCLUDE_ON_BUILDPATH ) ; fSite = site ; fSelectedElements = new ArrayList ( ) ; } public void run ( ) { IResource resource = ( IResource ) fSelectedElements . get ( ) ; final IRubyProject project = RubyCore . create ( resource . getProject ( ) ) ; try { final IRunnableWithProgress runnable = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { try { List result = unExclude ( fSelectedElements , project , monitor ) ; selectAndReveal ( new StructuredSelection ( result ) ) ; } catch ( CoreException e ) { throw new InvocationTargetException ( e ) ; } } } ; PlatformUI . getWorkbench ( ) . getProgressService ( ) . run ( true , false , runnable ) ; } catch ( final InvocationTargetException e ) { if ( e . getCause ( ) instanceof CoreException ) { showExceptionDialog ( ( CoreException ) e . getCause ( ) ) ; } else { RubyPlugin . log ( e ) ; } } catch ( final InterruptedException e ) { } } protected List unExclude ( List elements , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_Including , * elements . size ( ) ) ; List entries = LoadpathModifier . getExistingEntries ( project ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { IResource resource = ( IResource ) elements . get ( i ) ; ISourceFolderRoot root = LoadpathModifier . getFolderRoot ( resource , project , new SubProgressMonitor ( monitor , ) ) ; if ( root != null ) { CPListElement entry = LoadpathModifier . getLoadpathEntry ( entries , root ) ; LoadpathModifier . unExclude ( resource , entry , project , new SubProgressMonitor ( monitor , ) ) ; } } LoadpathModifier . commitLoadPath ( entries , project , new SubProgressMonitor ( monitor , ) ) ; List resultElements = LoadpathModifier . getCorrespondingElements ( elements , project ) ; return resultElements ; } finally { monitor . done ( ) ; } } public void selectionChanged ( final SelectionChangedEvent event ) { final ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { setEnabled ( canHandle ( ( IStructuredSelection ) selection ) ) ; } else { setEnabled ( canHandle ( StructuredSelection . EMPTY ) ) ; } } private boolean canHandle ( IStructuredSelection elements ) { if ( elements . size ( ) == ) return false ; try { fSelectedElements . clear ( ) ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; fSelectedElements . add ( element ) ; if ( element instanceof IResource ) { IResource resource = ( IResource ) element ; IRubyProject project = RubyCore . create ( resource . getProject ( ) ) ; if ( project == null || ! project . exists ( ) ) return false ; if ( ! LoadpathModifier . isExcluded ( resource , project ) ) return false ; } else { return false ; } } return true ; } catch ( CoreException e ) { } return false ; } private void showExceptionDialog ( CoreException exception ) { showError ( exception , fSite . getShell ( ) , NewWizardMessages . IncludeToBuildpathAction_ErrorTitle , exception . getMessage ( ) ) ; } private void showError ( CoreException e , Shell shell , String title , String message ) { IStatus status = e . getStatus ( ) ; if ( status != null ) { ErrorDialog . openError ( shell , message , title , status ) ; } else { MessageDialog . openError ( shell , title , message ) ; } } private void selectAndReveal ( final ISelection selection ) { IWorkbenchPage page = fSite . getPage ( ) ; if ( page == null ) return ; List parts = new ArrayList ( ) ; IWorkbenchPartReference refs [ ] = page . getViewReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { IWorkbenchPart part = refs [ i ] . getPart ( false ) ; if ( part != null ) parts . add ( part ) ; } refs = page . getEditorReferences ( ) ; for ( int i = ; i < refs . length ; i ++ ) { if ( refs [ i ] . getPart ( false ) != null ) parts . add ( refs [ i ] . getPart ( false ) ) ; } Iterator itr = parts . iterator ( ) ; while ( itr . hasNext ( ) ) { IWorkbenchPart part = ( IWorkbenchPart ) itr . next ( ) ; ISetSelectionTarget target = null ; if ( part instanceof ISetSelectionTarget ) target = ( ISetSelectionTarget ) part ; else target = ( ISetSelectionTarget ) part . getAdapter ( ISetSelectionTarget . class ) ; if ( target != null ) { final ISetSelectionTarget finalTarget = target ; page . getWorkbenchWindow ( ) . getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { finalTarget . selectReveal ( selection ) ; } } ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . action . ToolBarManager ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . forms . events . ExpansionAdapter ; import org . eclipse . ui . forms . events . ExpansionEvent ; import org . eclipse . ui . forms . widgets . ExpandableComposite ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier . ILoadpathModifierListener ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . preferences . ScrolledPageContent ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . util . ViewerPane ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . BuildPathBasePage ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . BuildPathsBlock ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElementAttribute ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; public class NewSourceContainerWorkbookPage extends BuildPathBasePage implements ILoadpathModifierListener { public static final String OPEN_SETTING = "" ; private ListDialogField fClassPathList ; private HintTextGroup fHintTextGroup ; private DialogPackageExplorer fPackageExplorer ; private final BuildPathsBlock fBuildPathsBlock ; private IRubyProject fRubyProject ; public NewSourceContainerWorkbookPage ( ListDialogField classPathList , IRunnableContext context , BuildPathsBlock buildPathsBlock ) { fClassPathList = classPathList ; fBuildPathsBlock = buildPathsBlock ; fPackageExplorer = new DialogPackageExplorer ( ) ; fHintTextGroup = new HintTextGroup ( fPackageExplorer , context , this ) ; } public void init ( IRubyProject javaProject ) { fRubyProject = javaProject ; fHintTextGroup . setRubyProject ( javaProject ) ; fPackageExplorer . setInput ( javaProject ) ; } public Control getControl ( Composite parent ) { final int [ ] sashWeight = { } ; final IPreferenceStore preferenceStore = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; preferenceStore . setDefault ( OPEN_SETTING , true ) ; ScrolledPageContent scrolledContent = new ScrolledPageContent ( parent ) ; Composite body = scrolledContent . getBody ( ) ; body . setLayout ( new GridLayout ( ) ) ; final SashForm sashForm = new SashForm ( body , SWT . VERTICAL | SWT . NONE ) ; sashForm . setFont ( sashForm . getFont ( ) ) ; ViewerPane pane = new ViewerPane ( sashForm , SWT . BORDER | SWT . FLAT ) ; pane . setContent ( fPackageExplorer . createControl ( pane ) ) ; fPackageExplorer . setContentProvider ( ) ; final ExpandableComposite excomposite = new ExpandableComposite ( sashForm , SWT . NONE , ExpandableComposite . TWISTIE | ExpandableComposite . CLIENT_INDENT ) ; excomposite . setFont ( sashForm . getFont ( ) ) ; excomposite . setText ( NewWizardMessages . NewSourceContainerWorkbookPage_HintTextGroup_title ) ; final boolean isExpanded = preferenceStore . getBoolean ( OPEN_SETTING ) ; excomposite . setExpanded ( isExpanded ) ; excomposite . addExpansionListener ( new ExpansionAdapter ( ) { public void expansionStateChanged ( ExpansionEvent e ) { ScrolledPageContent parentScrolledComposite = getParentScrolledComposite ( excomposite ) ; if ( parentScrolledComposite != null ) { boolean expanded = excomposite . isExpanded ( ) ; parentScrolledComposite . reflow ( true ) ; adjustSashForm ( sashWeight , sashForm , expanded ) ; preferenceStore . setValue ( OPEN_SETTING , expanded ) ; } } } ) ; excomposite . setClient ( fHintTextGroup . createControl ( excomposite ) ) ; final DialogPackageExplorerActionGroup actionGroup = new DialogPackageExplorerActionGroup ( fHintTextGroup , this ) ; ToolBarManager tbm = actionGroup . createLeftToolBarManager ( pane ) ; pane . setTopCenter ( null ) ; pane . setTopLeft ( tbm . getControl ( ) ) ; tbm = actionGroup . createLeftToolBar ( pane ) ; pane . setTopRight ( tbm . getControl ( ) ) ; fHintTextGroup . setActionGroup ( actionGroup ) ; fPackageExplorer . setActionGroup ( actionGroup ) ; actionGroup . addListener ( fHintTextGroup ) ; sashForm . setWeights ( new int [ ] { , } ) ; adjustSashForm ( sashWeight , sashForm , excomposite . isExpanded ( ) ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; PixelConverter converter = new PixelConverter ( parent ) ; gd . heightHint = converter . convertHeightInCharsToPixels ( ) ; sashForm . setLayoutData ( gd ) ; parent . layout ( true ) ; return scrolledContent ; } private void adjustSashForm ( int [ ] sashWeight , SashForm sashForm , boolean isExpanded ) { if ( isExpanded ) { int upperWeight = sashWeight [ ] ; sashForm . setWeights ( new int [ ] { upperWeight , - upperWeight } ) ; } else { sashWeight [ ] = sashForm . getWeights ( ) [ ] / ; sashForm . setWeights ( new int [ ] { , } ) ; } sashForm . layout ( true ) ; } private ScrolledPageContent getParentScrolledComposite ( Control control ) { Control parent = control . getParent ( ) ; while ( ! ( parent instanceof ScrolledPageContent ) ) { parent = parent . getParent ( ) ; } if ( parent instanceof ScrolledPageContent ) { return ( ScrolledPageContent ) parent ; } return null ; } private Shell getShell ( ) { return RubyPlugin . getActiveWorkbenchShell ( ) ; } public List getSelection ( ) { List selectedList = new ArrayList ( ) ; IRubyProject project = fHintTextGroup . getRubyProject ( ) ; try { List list = fHintTextGroup . getSelection ( ) . toList ( ) ; List existingEntries = LoadpathModifier . getExistingEntries ( project ) ; for ( int i = ; i < list . size ( ) ; i ++ ) { Object obj = list . get ( i ) ; if ( obj instanceof ISourceFolderRoot ) { ISourceFolderRoot element = ( ISourceFolderRoot ) obj ; CPListElement cpElement = LoadpathModifier . getLoadpathEntry ( existingEntries , element ) ; selectedList . add ( cpElement ) ; } else if ( obj instanceof IRubyProject ) { ILoadpathEntry entry = LoadpathModifier . getLoadpathEntryFor ( project . getPath ( ) , project , ILoadpathEntry . CPE_SOURCE ) ; if ( entry == null ) continue ; CPListElement cpElement = CPListElement . createFromExisting ( entry , project ) ; selectedList . add ( cpElement ) ; } } } catch ( RubyModelException e ) { return new ArrayList ( ) ; } return selectedList ; } public void setSelection ( List selection , boolean expand ) { if ( selection . size ( ) == ) return ; List cpEntries = new ArrayList ( ) ; for ( int i = ; i < selection . size ( ) ; i ++ ) { Object obj = selection . get ( i ) ; if ( obj instanceof CPListElement ) { CPListElement element = ( CPListElement ) obj ; if ( element . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { cpEntries . add ( element ) ; } } else if ( obj instanceof CPListElementAttribute ) { CPListElementAttribute attribute = ( CPListElementAttribute ) obj ; CPListElement element = attribute . getParent ( ) ; if ( element . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { cpEntries . add ( element ) ; } } } List list = fClassPathList . getElements ( ) ; ILoadpathEntry [ ] entries = new ILoadpathEntry [ list . size ( ) ] ; for ( int i = ; i < list . size ( ) ; i ++ ) { CPListElement entry = ( CPListElement ) list . get ( i ) ; entries [ i ] = entry . getLoadpathEntry ( ) ; } try { fRubyProject . setRawLoadpath ( entries , null ) ; fPackageExplorer . refresh ( ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } fPackageExplorer . setSelection ( cpEntries ) ; } public boolean isEntryKind ( int kind ) { return kind == ILoadpathEntry . CPE_SOURCE ; } public void classpathEntryChanged ( List newEntries ) { fClassPathList . setElements ( newEntries ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . CoreUtility ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . wizards . ILoadpathContainerPage ; public class LoadpathContainerDescriptor { private IConfigurationElement fConfigElement ; private ILoadpathContainerPage fPage ; private static final String ATT_EXTENSION = "" ; private static final String ATT_ID = "" ; private static final String ATT_NAME = "" ; private static final String ATT_PAGE_CLASS = "" ; public LoadpathContainerDescriptor ( IConfigurationElement configElement ) throws CoreException { super ( ) ; fConfigElement = configElement ; fPage = null ; String id = fConfigElement . getAttribute ( ATT_ID ) ; String name = configElement . getAttribute ( ATT_NAME ) ; String pageClassName = configElement . getAttribute ( ATT_PAGE_CLASS ) ; if ( name == null ) { throw new CoreException ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , , "" + id , null ) ) ; } if ( pageClassName == null ) { throw new CoreException ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , , "" + id , null ) ) ; } } public ILoadpathContainerPage createPage ( ) throws CoreException { if ( fPage == null ) { Object elem = CoreUtility . createExtension ( fConfigElement , ATT_PAGE_CLASS ) ; if ( elem instanceof ILoadpathContainerPage ) { fPage = ( ILoadpathContainerPage ) elem ; } else { String id = fConfigElement . getAttribute ( ATT_ID ) ; throw new CoreException ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , , "" + id , null ) ) ; } } return fPage ; } public ILoadpathContainerPage getPage ( ) { return fPage ; } public void setPage ( ILoadpathContainerPage page ) { fPage = page ; } public void dispose ( ) { if ( fPage != null ) { fPage . dispose ( ) ; fPage = null ; } } public String getName ( ) { return fConfigElement . getAttribute ( ATT_NAME ) ; } public String getPageClass ( ) { return fConfigElement . getAttribute ( ATT_PAGE_CLASS ) ; } public boolean canEdit ( ILoadpathEntry entry ) { String id = fConfigElement . getAttribute ( ATT_ID ) ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) { String type = entry . getPath ( ) . segment ( ) ; return id . equals ( type ) ; } return false ; } public static LoadpathContainerDescriptor [ ] getDescriptors ( ) { ArrayList containers = new ArrayList ( ) ; IExtensionPoint extensionPoint = Platform . getExtensionRegistry ( ) . getExtensionPoint ( RubyUI . ID_PLUGIN , ATT_EXTENSION ) ; if ( extensionPoint != null ) { LoadpathContainerDescriptor defaultPage = null ; String defaultPageName = LoadpathContainerDefaultPage . class . getName ( ) ; IConfigurationElement [ ] elements = extensionPoint . getConfigurationElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { try { LoadpathContainerDescriptor curr = new LoadpathContainerDescriptor ( elements [ i ] ) ; if ( defaultPageName . equals ( curr . getPageClass ( ) ) ) { defaultPage = curr ; } else { containers . add ( curr ) ; } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } if ( defaultPageName != null && containers . isEmpty ( ) ) { containers . add ( defaultPage ) ; } } return ( LoadpathContainerDescriptor [ ] ) containers . toArray ( new LoadpathContainerDescriptor [ containers . size ( ) ] ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . ILoadpathAttribute ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . launching . RubyRuntime ; public class CPListElement { public static final String EXCLUSION = "" ; public static final String INCLUSION = "" ; private IRubyProject fProject ; private int fEntryKind ; private IPath fPath , fOrginalPath ; private IResource fResource ; private boolean fIsExported ; private boolean fIsMissing ; private Object fParentContainer ; private ILoadpathEntry fCachedEntry ; private ArrayList fChildren ; private IPath fLinkTarget , fOrginalLinkTarget ; public CPListElement ( IRubyProject project , int entryKind , IPath path , IResource res ) { this ( null , project , entryKind , path , res ) ; } public CPListElement ( Object parent , IRubyProject project , int entryKind , IPath path , IResource res ) { this ( parent , project , entryKind , path , res , null ) ; } public CPListElement ( IRubyProject project , int entryKind ) { this ( null , project , entryKind , null , null ) ; } public CPListElement ( Object parent , IRubyProject project , int entryKind , IPath path , IResource res , IPath linkTarget ) { fProject = project ; fEntryKind = entryKind ; fPath = path ; fOrginalPath = path ; fLinkTarget = linkTarget ; fOrginalLinkTarget = linkTarget ; fChildren = new ArrayList ( ) ; fResource = res ; fIsExported = false ; fIsMissing = false ; fCachedEntry = null ; fParentContainer = parent ; switch ( entryKind ) { case ILoadpathEntry . CPE_SOURCE : createAttributeElement ( INCLUSION , new Path [ ] , true ) ; createAttributeElement ( EXCLUSION , new Path [ ] , true ) ; break ; case ILoadpathEntry . CPE_LIBRARY : case ILoadpathEntry . CPE_VARIABLE : break ; case ILoadpathEntry . CPE_PROJECT : break ; case ILoadpathEntry . CPE_CONTAINER : try { ILoadpathContainer container = RubyCore . getLoadpathContainer ( fPath , fProject ) ; if ( container != null ) { ILoadpathEntry [ ] entries = container . getLoadpathEntries ( ) ; for ( int i = ; i < entries . length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry != null ) { CPListElement curr = createFromExisting ( this , entry , fProject ) ; fChildren . add ( curr ) ; } else { RubyPlugin . logErrorMessage ( "" + fPath + "" ) ; } } } } catch ( RubyModelException e ) { } break ; default : } } public ILoadpathEntry getLoadpathEntry ( ) { if ( fCachedEntry == null ) { fCachedEntry = newLoadpathEntry ( ) ; } return fCachedEntry ; } private ILoadpathAttribute [ ] getLoadpathAttributes ( ) { ArrayList res = new ArrayList ( ) ; for ( int i = ; i < fChildren . size ( ) ; i ++ ) { Object curr = fChildren . get ( i ) ; if ( curr instanceof CPListElementAttribute ) { CPListElementAttribute elem = ( CPListElementAttribute ) curr ; if ( ! elem . isBuiltIn ( ) && elem . getValue ( ) != null ) { res . add ( elem . newLoadpathAttribute ( ) ) ; } } } return ( ILoadpathAttribute [ ] ) res . toArray ( new ILoadpathAttribute [ res . size ( ) ] ) ; } private ILoadpathEntry newLoadpathEntry ( ) { ILoadpathAttribute [ ] extraAttributes = getLoadpathAttributes ( ) ; switch ( fEntryKind ) { case ILoadpathEntry . CPE_SOURCE : IPath [ ] inclusionPattern = ( IPath [ ] ) getAttribute ( INCLUSION ) ; IPath [ ] exclusionPattern = ( IPath [ ] ) getAttribute ( EXCLUSION ) ; return RubyCore . newSourceEntry ( fPath , inclusionPattern , exclusionPattern , extraAttributes ) ; case ILoadpathEntry . CPE_LIBRARY : { return RubyCore . newLibraryEntry ( fPath , extraAttributes , isExported ( ) ) ; } case ILoadpathEntry . CPE_PROJECT : { return RubyCore . newProjectEntry ( fPath , extraAttributes , isExported ( ) ) ; } case ILoadpathEntry . CPE_CONTAINER : { return RubyCore . newContainerEntry ( fPath , extraAttributes , isExported ( ) ) ; } case ILoadpathEntry . CPE_VARIABLE : { return RubyCore . newVariableEntry ( fPath , extraAttributes , isExported ( ) ) ; } default : return null ; } } public IPath getPath ( ) { return fPath ; } public int getEntryKind ( ) { return fEntryKind ; } public IResource getResource ( ) { return fResource ; } public CPListElementAttribute setAttribute ( String key , Object value ) { CPListElementAttribute attribute = findAttributeElement ( key ) ; if ( attribute == null ) { return null ; } if ( key . equals ( EXCLUSION ) || key . equals ( INCLUSION ) ) { Assert . isTrue ( value != null || fEntryKind != ILoadpathEntry . CPE_SOURCE ) ; } attribute . setValue ( value ) ; attributeChanged ( key ) ; return attribute ; } public boolean addToExclusions ( IPath path ) { String key = CPListElement . EXCLUSION ; return addFilter ( path , key ) ; } public boolean addToInclusion ( IPath path ) { String key = CPListElement . INCLUSION ; return addFilter ( path , key ) ; } public boolean removeFromExclusions ( IPath path ) { String key = CPListElement . EXCLUSION ; return removeFilter ( path , key ) ; } public boolean removeFromInclusion ( IPath path ) { String key = CPListElement . INCLUSION ; return removeFilter ( path , key ) ; } private boolean addFilter ( IPath path , String key ) { IPath [ ] exclusionFilters = ( IPath [ ] ) getAttribute ( key ) ; if ( ! RubyModelUtil . isExcludedPath ( path , exclusionFilters ) ) { IPath pathToExclude = path . removeFirstSegments ( getPath ( ) . segmentCount ( ) ) . addTrailingSeparator ( ) ; IPath [ ] newExclusionFilters = new IPath [ exclusionFilters . length + ] ; System . arraycopy ( exclusionFilters , , newExclusionFilters , , exclusionFilters . length ) ; newExclusionFilters [ exclusionFilters . length ] = pathToExclude ; setAttribute ( key , newExclusionFilters ) ; return true ; } return false ; } private boolean removeFilter ( IPath path , String key ) { IPath [ ] exclusionFilters = ( IPath [ ] ) getAttribute ( key ) ; IPath pathToExclude = path . removeFirstSegments ( getPath ( ) . segmentCount ( ) ) . addTrailingSeparator ( ) ; if ( RubyModelUtil . isExcludedPath ( pathToExclude , exclusionFilters ) ) { List l = new ArrayList ( Arrays . asList ( exclusionFilters ) ) ; l . remove ( pathToExclude ) ; IPath [ ] newExclusionFilters = ( IPath [ ] ) l . toArray ( new IPath [ l . size ( ) ] ) ; setAttribute ( key , newExclusionFilters ) ; return true ; } return false ; } public CPListElementAttribute findAttributeElement ( String key ) { for ( int i = ; i < fChildren . size ( ) ; i ++ ) { Object curr = fChildren . get ( i ) ; if ( curr instanceof CPListElementAttribute ) { CPListElementAttribute elem = ( CPListElementAttribute ) curr ; if ( key . equals ( elem . getKey ( ) ) ) { return elem ; } } } return null ; } public Object getAttribute ( String key ) { CPListElementAttribute attrib = findAttributeElement ( key ) ; if ( attrib != null ) { return attrib . getValue ( ) ; } return null ; } private void createAttributeElement ( String key , Object value , boolean builtIn ) { fChildren . add ( new CPListElementAttribute ( this , key , value , builtIn ) ) ; } private static boolean isFiltered ( Object entry , String [ ] filteredKeys ) { if ( entry instanceof CPListElementAttribute ) { String key = ( ( CPListElementAttribute ) entry ) . getKey ( ) ; for ( int i = ; i < filteredKeys . length ; i ++ ) { if ( key . equals ( filteredKeys [ i ] ) ) { return true ; } } } return false ; } private Object [ ] getFilteredChildren ( String [ ] filteredKeys ) { int nChildren = fChildren . size ( ) ; ArrayList res = new ArrayList ( nChildren ) ; for ( int i = ; i < nChildren ; i ++ ) { Object curr = fChildren . get ( i ) ; if ( ! isFiltered ( curr , filteredKeys ) ) { res . add ( curr ) ; } } return res . toArray ( ) ; } public Object [ ] getChildren ( boolean hideOutputFolder ) { if ( hideOutputFolder && fEntryKind == ILoadpathEntry . CPE_SOURCE ) { return getFilteredChildren ( new String [ ] { } ) ; } if ( fParentContainer instanceof CPListElement ) { IPath jreContainerPath = new Path ( RubyRuntime . RUBY_CONTAINER ) ; if ( jreContainerPath . isPrefixOf ( ( ( CPListElement ) fParentContainer ) . getPath ( ) ) ) { return getFilteredChildren ( new String [ ] { } ) ; } } if ( fEntryKind == ILoadpathEntry . CPE_PROJECT ) { return getFilteredChildren ( new String [ ] { } ) ; } return fChildren . toArray ( ) ; } public Object getParentContainer ( ) { return fParentContainer ; } private void attributeChanged ( String key ) { fCachedEntry = null ; } private boolean canUpdateContainer ( ) { if ( fEntryKind == ILoadpathEntry . CPE_CONTAINER && fProject != null ) { LoadpathContainerInitializer initializer = RubyCore . getLoadpathContainerInitializer ( fPath . segment ( ) ) ; return ( initializer != null && initializer . canUpdateLoadpathContainer ( fPath , fProject ) ) ; } return false ; } public boolean isInNonModifiableContainer ( ) { if ( fParentContainer instanceof CPListElement ) { return ! ( ( CPListElement ) fParentContainer ) . canUpdateContainer ( ) ; } return false ; } public boolean equals ( Object other ) { if ( other != null && other . getClass ( ) . equals ( getClass ( ) ) ) { CPListElement elem = ( CPListElement ) other ; return getLoadpathEntry ( ) . equals ( elem . getLoadpathEntry ( ) ) ; } return false ; } public int hashCode ( ) { return fPath . hashCode ( ) + fEntryKind ; } public String toString ( ) { return getLoadpathEntry ( ) . toString ( ) ; } public boolean isMissing ( ) { return fIsMissing ; } public void setIsMissing ( boolean isMissing ) { fIsMissing = isMissing ; } public boolean isExported ( ) { return fIsExported ; } public void setExported ( boolean isExported ) { if ( isExported != fIsExported ) { fIsExported = isExported ; attributeChanged ( null ) ; } } public IRubyProject getRubyProject ( ) { return fProject ; } public static CPListElement createFromExisting ( ILoadpathEntry curr , IRubyProject project ) { return createFromExisting ( null , curr , project ) ; } public static CPListElement createFromExisting ( Object parent , ILoadpathEntry curr , IRubyProject project ) { IPath path = curr . getPath ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IResource res = null ; boolean isMissing = false ; IPath linkTarget = null ; switch ( curr . getEntryKind ( ) ) { case ILoadpathEntry . CPE_CONTAINER : res = null ; try { isMissing = project != null && ( RubyCore . getLoadpathContainer ( path , project ) == null ) ; } catch ( RubyModelException e ) { isMissing = true ; } break ; case ILoadpathEntry . CPE_VARIABLE : IPath resolvedPath = RubyCore . getResolvedVariablePath ( path ) ; res = null ; if ( resolvedPath == null ) { isMissing = true ; } else { isMissing = ! resolvedPath . toFile ( ) . isDirectory ( ) ; } break ; case ILoadpathEntry . CPE_LIBRARY : res = root . findMember ( path ) ; if ( res == null ) { if ( root . getWorkspace ( ) . validatePath ( path . toString ( ) , IResource . FOLDER ) . isOK ( ) && root . getProject ( path . segment ( ) ) . exists ( ) ) { res = root . getFolder ( path ) ; } isMissing = ! path . toFile ( ) . isDirectory ( ) ; } else if ( res . isLinked ( ) ) { linkTarget = res . getLocation ( ) ; } break ; case ILoadpathEntry . CPE_SOURCE : path = path . removeTrailingSeparator ( ) ; res = root . findMember ( path ) ; if ( res == null ) { if ( root . getWorkspace ( ) . validatePath ( path . toString ( ) , IResource . FOLDER ) . isOK ( ) ) { res = root . getFolder ( path ) ; } isMissing = true ; } else if ( res . isLinked ( ) ) { linkTarget = res . getLocation ( ) ; } break ; case ILoadpathEntry . CPE_PROJECT : res = root . findMember ( path ) ; isMissing = ( res == null ) ; break ; } CPListElement elem = new CPListElement ( parent , project , curr . getEntryKind ( ) , path , res , linkTarget ) ; elem . setExported ( curr . isExported ( ) ) ; elem . setAttribute ( EXCLUSION , curr . getExclusionPatterns ( ) ) ; elem . setAttribute ( INCLUSION , curr . getInclusionPatterns ( ) ) ; ILoadpathAttribute [ ] extraAttributes = curr . getExtraAttributes ( ) ; for ( int i = ; i < extraAttributes . length ; i ++ ) { ILoadpathAttribute attrib = extraAttributes [ i ] ; elem . setAttribute ( attrib . getName ( ) , attrib . getValue ( ) ) ; } if ( project != null && project . exists ( ) ) { elem . setIsMissing ( isMissing ) ; } return elem ; } public static StringBuffer appendEncodePath ( IPath path , StringBuffer buf ) { if ( path != null ) { String str = path . toString ( ) ; buf . append ( '' ) . append ( str . length ( ) ) . append ( '' ) . append ( str ) ; } else { buf . append ( '' ) . append ( '' ) ; } return buf ; } public static StringBuffer appendEncodedString ( String str , StringBuffer buf ) { if ( str != null ) { buf . append ( '' ) . append ( str . length ( ) ) . append ( '' ) . append ( str ) ; } else { buf . append ( '' ) . append ( '' ) ; } return buf ; } public static StringBuffer appendEncodedFilter ( IPath [ ] filters , StringBuffer buf ) { if ( filters != null ) { buf . append ( '' ) . append ( filters . length ) . append ( '' ) ; for ( int i = ; i < filters . length ; i ++ ) { appendEncodePath ( filters [ i ] , buf ) . append ( '' ) ; } } else { buf . append ( '' ) . append ( '' ) ; } return buf ; } public StringBuffer appendEncodedSettings ( StringBuffer buf ) { buf . append ( fEntryKind ) . append ( '' ) ; if ( getLinkTarget ( ) == null ) { appendEncodePath ( fPath , buf ) . append ( '' ) ; } else { appendEncodePath ( fPath , buf ) . append ( '' ) . append ( '>' ) ; appendEncodePath ( getLinkTarget ( ) , buf ) . append ( '' ) ; } buf . append ( Boolean . valueOf ( fIsExported ) ) . append ( '' ) ; for ( int i = ; i < fChildren . size ( ) ; i ++ ) { Object curr = fChildren . get ( i ) ; if ( curr instanceof CPListElementAttribute ) { CPListElementAttribute elem = ( CPListElementAttribute ) curr ; if ( elem . isBuiltIn ( ) ) { String key = elem . getKey ( ) ; if ( EXCLUSION . equals ( key ) || INCLUSION . equals ( key ) ) { appendEncodedFilter ( ( IPath [ ] ) elem . getValue ( ) , buf ) . append ( '' ) ; } } else { appendEncodedString ( ( String ) elem . getValue ( ) , buf ) ; } } } return buf ; } public IPath getLinkTarget ( ) { return fLinkTarget ; } public void setPath ( IPath path ) { fCachedEntry = null ; fPath = path ; } public void setLinkTarget ( IPath linkTarget ) { fCachedEntry = null ; fLinkTarget = linkTarget ; } public static void insert ( CPListElement element , List cpList ) { int length = cpList . size ( ) ; CPListElement [ ] elements = ( CPListElement [ ] ) cpList . toArray ( new CPListElement [ length ] ) ; int i = ; while ( i < length && elements [ i ] . getEntryKind ( ) != element . getEntryKind ( ) ) { i ++ ; } if ( i < length ) { i ++ ; while ( i < length && elements [ i ] . getEntryKind ( ) == element . getEntryKind ( ) ) { i ++ ; } cpList . add ( i , element ) ; return ; } switch ( element . getEntryKind ( ) ) { case ILoadpathEntry . CPE_SOURCE : cpList . add ( , element ) ; break ; case ILoadpathEntry . CPE_CONTAINER : case ILoadpathEntry . CPE_LIBRARY : case ILoadpathEntry . CPE_PROJECT : case ILoadpathEntry . CPE_VARIABLE : default : cpList . add ( element ) ; break ; } } public static ILoadpathEntry [ ] convertToLoadpathEntries ( List cpList ) { ILoadpathEntry [ ] result = new ILoadpathEntry [ cpList . size ( ) ] ; int i = ; for ( Iterator iter = cpList . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement cur = ( CPListElement ) iter . next ( ) ; result [ i ] = cur . getLoadpathEntry ( ) ; i ++ ; } return result ; } public static CPListElement [ ] createFromExisting ( IRubyProject project ) throws RubyModelException { ILoadpathEntry [ ] rawLoadpath = project . getRawLoadpath ( ) ; CPListElement [ ] result = new CPListElement [ rawLoadpath . length ] ; for ( int i = ; i < rawLoadpath . length ; i ++ ) { result [ i ] = CPListElement . createFromExisting ( rawLoadpath [ i ] , project ) ; } return result ; } public static boolean isProjectSourceFolder ( CPListElement [ ] existing , IRubyProject project ) { IPath projPath = project . getProject ( ) . getFullPath ( ) ; for ( int i = ; i < existing . length ; i ++ ) { ILoadpathEntry curr = existing [ i ] . getLoadpathEntry ( ) ; if ( curr . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { if ( projPath . equals ( curr . getPath ( ) ) ) { return true ; } } } return false ; } public IPath getOrginalPath ( ) { return fOrginalPath ; } public IPath getOrginalLinkTarget ( ) { return fOrginalLinkTarget ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; import org . rubypeople . rdt . ui . wizards . NewElementWizardPage ; public class SetFilterWizardPage extends NewElementWizardPage { private static final String PAGE_NAME = "" ; private ListDialogField fInclusionPatternList ; private ListDialogField fExclusionPatternList ; private CPListElement fCurrElement ; private IProject fCurrProject ; private IContainer fCurrSourceFolder ; private static final int IDX_ADD = ; private static final int IDX_ADD_MULTIPLE = ; private static final int IDX_EDIT = ; private static final int IDX_REMOVE = ; private final ArrayList fExistingEntries ; public SetFilterWizardPage ( CPListElement entryToEdit , ArrayList existingEntries ) { super ( PAGE_NAME ) ; fExistingEntries = existingEntries ; setTitle ( NewWizardMessages . ExclusionInclusionDialog_title ) ; setDescription ( NewWizardMessages . ExclusionInclusionDialog_description2 ) ; fCurrElement = entryToEdit ; fCurrProject = entryToEdit . getRubyProject ( ) . getProject ( ) ; IWorkspaceRoot root = fCurrProject . getWorkspace ( ) . getRoot ( ) ; IResource res = root . findMember ( entryToEdit . getPath ( ) ) ; if ( res instanceof IContainer ) { fCurrSourceFolder = ( IContainer ) res ; } String excLabel = NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_label ; ImageDescriptor excDescriptor = RubyPluginImages . DESC_OBJS_EXCLUSION_FILTER_ATTRIB ; String [ ] excButtonLabels = new String [ ] { NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_add , NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_add_multiple , NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_edit , null , NewWizardMessages . ExclusionInclusionDialog_exclusion_pattern_remove } ; String incLabel = NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_label ; ImageDescriptor incDescriptor = RubyPluginImages . DESC_OBJS_INCLUSION_FILTER_ATTRIB ; String [ ] incButtonLabels = new String [ ] { NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_add , NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_add_multiple , NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_edit , null , NewWizardMessages . ExclusionInclusionDialog_inclusion_pattern_remove } ; fExclusionPatternList = createListContents ( entryToEdit , CPListElement . EXCLUSION , excLabel , excDescriptor , excButtonLabels ) ; fInclusionPatternList = createListContents ( entryToEdit , CPListElement . INCLUSION , incLabel , incDescriptor , incButtonLabels ) ; } public void createControl ( Composite parent ) { Composite inner = new Composite ( parent , SWT . NONE ) ; inner . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; inner . setLayout ( layout ) ; inner . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; fInclusionPatternList . doFillIntoGrid ( inner , ) ; LayoutUtil . setHorizontalSpan ( fInclusionPatternList . getLabelControl ( null ) , ) ; LayoutUtil . setHorizontalGrabbing ( fInclusionPatternList . getListControl ( null ) ) ; fExclusionPatternList . doFillIntoGrid ( inner , ) ; LayoutUtil . setHorizontalSpan ( fExclusionPatternList . getLabelControl ( null ) , ) ; LayoutUtil . setHorizontalGrabbing ( fExclusionPatternList . getListControl ( null ) ) ; setControl ( inner ) ; Dialog . applyDialogFont ( inner ) ; } private static class ExclusionInclusionLabelProvider extends LabelProvider { private Image fElementImage ; public ExclusionInclusionLabelProvider ( ImageDescriptor descriptor ) { ImageDescriptorRegistry registry = RubyPlugin . getImageDescriptorRegistry ( ) ; fElementImage = registry . get ( descriptor ) ; } public Image getImage ( Object element ) { return fElementImage ; } public String getText ( Object element ) { return ( String ) element ; } } private ListDialogField createListContents ( CPListElement entryToEdit , String key , String label , ImageDescriptor descriptor , String [ ] buttonLabels ) { ExclusionPatternAdapter adapter = new ExclusionPatternAdapter ( ) ; ListDialogField patternList = new ListDialogField ( adapter , buttonLabels , new ExclusionInclusionLabelProvider ( descriptor ) ) ; patternList . setDialogFieldListener ( adapter ) ; patternList . setLabelText ( label ) ; patternList . enableButton ( IDX_EDIT , false ) ; IPath [ ] pattern = ( IPath [ ] ) entryToEdit . getAttribute ( key ) ; ArrayList elements = new ArrayList ( pattern . length ) ; for ( int i = ; i < pattern . length ; i ++ ) { String patternName = pattern [ i ] . toString ( ) ; if ( patternName . length ( ) > ) elements . add ( patternName ) ; } patternList . setElements ( elements ) ; patternList . selectFirstElement ( ) ; patternList . enableButton ( IDX_ADD_MULTIPLE , fCurrSourceFolder != null ) ; patternList . setViewerSorter ( new ViewerSorter ( ) ) ; return patternList ; } protected void doCustomButtonPressed ( ListDialogField field , int index ) { if ( index == IDX_ADD ) { addEntry ( field ) ; } else if ( index == IDX_EDIT ) { editEntry ( field ) ; } else if ( index == IDX_ADD_MULTIPLE ) { addMultipleEntries ( field ) ; } else if ( index == IDX_REMOVE ) { field . removeElements ( field . getSelectedElements ( ) ) ; } updateStatus ( ) ; } private void updateStatus ( ) { fCurrElement . setAttribute ( CPListElement . INCLUSION , getInclusionPattern ( ) ) ; fCurrElement . setAttribute ( CPListElement . EXCLUSION , getExclusionPattern ( ) ) ; IRubyModelStatus status = RubyConventions . validateLoadpath ( fCurrElement . getRubyProject ( ) , CPListElement . convertToLoadpathEntries ( fExistingEntries ) , null ) ; if ( ! status . isOK ( ) ) { StatusInfo statusInfo = new StatusInfo ( ) ; statusInfo . setError ( status . getMessage ( ) ) ; updateStatus ( statusInfo ) ; } else { StatusInfo statusInfo = new StatusInfo ( ) ; statusInfo . setOK ( ) ; updateStatus ( statusInfo ) ; } } protected void doDoubleClicked ( ListDialogField field ) { editEntry ( field ) ; updateStatus ( ) ; } protected void doSelectionChanged ( ListDialogField field ) { List selected = field . getSelectedElements ( ) ; field . enableButton ( IDX_EDIT , canEdit ( selected ) ) ; } private boolean canEdit ( List selected ) { return selected . size ( ) == ; } private void editEntry ( ListDialogField field ) { List selElements = field . getSelectedElements ( ) ; if ( selElements . size ( ) != ) { return ; } List existing = field . getElements ( ) ; String entry = ( String ) selElements . get ( ) ; ExclusionInclusionEntryDialog dialog = new ExclusionInclusionEntryDialog ( getShell ( ) , isExclusion ( field ) , entry , existing , fCurrElement ) ; if ( dialog . open ( ) == Window . OK ) { field . replaceElement ( entry , dialog . getExclusionPattern ( ) ) ; } } private boolean isExclusion ( ListDialogField field ) { return field == fExclusionPatternList ; } private void addEntry ( ListDialogField field ) { List existing = field . getElements ( ) ; ExclusionInclusionEntryDialog dialog = new ExclusionInclusionEntryDialog ( getShell ( ) , isExclusion ( field ) , null , existing , fCurrElement ) ; if ( dialog . open ( ) == Window . OK ) { field . addElement ( dialog . getExclusionPattern ( ) ) ; } } private class ExclusionPatternAdapter implements IListAdapter , IDialogFieldListener { public void customButtonPressed ( ListDialogField field , int index ) { doCustomButtonPressed ( field , index ) ; } public void selectionChanged ( ListDialogField field ) { doSelectionChanged ( field ) ; } public void doubleClicked ( ListDialogField field ) { doDoubleClicked ( field ) ; } public void dialogFieldChanged ( DialogField field ) { } } protected void doStatusLineUpdate ( ) { } protected void checkIfPatternValid ( ) { } private IPath [ ] getPattern ( ListDialogField field ) { Object [ ] arr = field . getElements ( ) . toArray ( ) ; Arrays . sort ( arr ) ; IPath [ ] res = new IPath [ arr . length ] ; for ( int i = ; i < res . length ; i ++ ) { res [ i ] = new Path ( ( String ) arr [ i ] ) ; } return res ; } public IPath [ ] getExclusionPattern ( ) { return getPattern ( fExclusionPatternList ) ; } public IPath [ ] getInclusionPattern ( ) { return getPattern ( fInclusionPatternList ) ; } protected void configureShell ( Shell newShell ) { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . EXCLUSION_PATTERN_DIALOG ) ; } private void addMultipleEntries ( ListDialogField field ) { String title , message ; if ( isExclusion ( field ) ) { title = NewWizardMessages . ExclusionInclusionDialog_ChooseExclusionPattern_title ; message = NewWizardMessages . ExclusionInclusionDialog_ChooseExclusionPattern_description ; } else { title = NewWizardMessages . ExclusionInclusionDialog_ChooseInclusionPattern_title ; message = NewWizardMessages . ExclusionInclusionDialog_ChooseInclusionPattern_description ; } IPath [ ] res = ExclusionInclusionEntryDialog . chooseExclusionPattern ( getShell ( ) , fCurrSourceFolder , title , message , null , true ) ; if ( res != null ) { for ( int i = ; i < res . length ; i ++ ) { field . addElement ( res [ i ] . toString ( ) ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Hashtable ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . dialogs . TrayDialog ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . model . BaseWorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . TypedViewerFilter ; import org . rubypeople . rdt . ui . actions . AbstractOpenWizardAction ; public class CreateMultipleSourceFoldersDialog extends TrayDialog { private final class FakeFolderBaseWorkbenchContentProvider extends BaseWorkbenchContentProvider { public Object getParent ( Object element ) { Object object = fNonExistingFolders . get ( element ) ; if ( object != null ) return object ; return super . getParent ( element ) ; } public Object [ ] getChildren ( Object element ) { List result = new ArrayList ( ) ; Set keys = fNonExistingFolders . keySet ( ) ; for ( Iterator iter = keys . iterator ( ) ; iter . hasNext ( ) ; ) { Object key = iter . next ( ) ; if ( fNonExistingFolders . get ( key ) . equals ( element ) ) { result . add ( key ) ; } } if ( result . size ( ) == ) return super . getChildren ( element ) ; Object [ ] children = super . getChildren ( element ) ; for ( int i = ; i < children . length ; i ++ ) { result . add ( children [ i ] ) ; } return result . toArray ( ) ; } } private final IRubyProject fRubyProject ; private final CPListElement [ ] fExistingElements ; private final HashSet fRemovedElements ; private final HashSet fModifiedElements ; private final HashSet fInsertedElements ; private final Hashtable fNonExistingFolders ; public CreateMultipleSourceFoldersDialog ( final IRubyProject javaProject , final CPListElement [ ] existingElements , Shell shell ) { super ( shell ) ; fRubyProject = javaProject ; fExistingElements = existingElements ; fRemovedElements = new HashSet ( ) ; fModifiedElements = new HashSet ( ) ; fInsertedElements = new HashSet ( ) ; fNonExistingFolders = new Hashtable ( ) ; for ( int i = ; i < existingElements . length ; i ++ ) { CPListElement cur = existingElements [ i ] ; if ( cur . getResource ( ) == null || ! cur . getResource ( ) . exists ( ) ) { addFakeFolder ( fRubyProject . getProject ( ) , cur ) ; } } } public int open ( ) { Class [ ] acceptedClasses = new Class [ ] { IProject . class , IFolder . class } ; List existingContainers = getExistingContainers ( fExistingElements ) ; IProject [ ] allProjects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; ArrayList rejectedElements = new ArrayList ( allProjects . length ) ; IProject currProject = fRubyProject . getProject ( ) ; for ( int i = ; i < allProjects . length ; i ++ ) { if ( ! allProjects [ i ] . equals ( currProject ) ) { rejectedElements . add ( allProjects [ i ] ) ; } } ViewerFilter filter = new TypedViewerFilter ( acceptedClasses , rejectedElements . toArray ( ) ) ; ILabelProvider lp = new WorkbenchLabelProvider ( ) ; ITreeContentProvider cp = new FakeFolderBaseWorkbenchContentProvider ( ) ; String title = NewWizardMessages . SourceContainerWorkbookPage_ExistingSourceFolderDialog_new_title ; String message = NewWizardMessages . SourceContainerWorkbookPage_ExistingSourceFolderDialog_edit_description ; MultipleFolderSelectionDialog dialog = new MultipleFolderSelectionDialog ( getShell ( ) , lp , cp ) { protected Control createDialogArea ( Composite parent ) { Control result = super . createDialogArea ( parent ) ; return result ; } protected Object createFolder ( final IContainer container ) { final Object [ ] result = new Object [ ] ; final CPListElement newElement = new CPListElement ( fRubyProject , ILoadpathEntry . CPE_SOURCE ) ; final AddSourceFolderWizard wizard = newSourceFolderWizard ( newElement , fExistingElements , container ) ; AbstractOpenWizardAction action = new AbstractOpenWizardAction ( ) { protected INewWizard createWizard ( ) throws CoreException { return wizard ; } } ; action . addPropertyChangeListener ( new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( IAction . RESULT ) ) { if ( event . getNewValue ( ) . equals ( Boolean . TRUE ) ) { result [ ] = addFakeFolder ( fRubyProject . getProject ( ) , newElement ) ; } else { wizard . cancel ( ) ; } } } } ) ; action . run ( ) ; return result [ ] ; } } ; dialog . setExisting ( existingContainers . toArray ( ) ) ; dialog . setTitle ( title ) ; dialog . setMessage ( message ) ; dialog . addFilter ( filter ) ; dialog . setInput ( fRubyProject . getProject ( ) . getParent ( ) ) ; dialog . setInitialFocus ( fRubyProject . getProject ( ) ) ; if ( dialog . open ( ) == Window . OK ) { Object [ ] elements = dialog . getResult ( ) ; for ( int i = ; i < elements . length ; i ++ ) { IResource res = ( IResource ) elements [ i ] ; fInsertedElements . add ( new CPListElement ( fRubyProject , ILoadpathEntry . CPE_SOURCE , res . getFullPath ( ) , res ) ) ; } if ( fExistingElements . length == ) { CPListElement existingElement = fExistingElements [ ] ; if ( existingElement . getResource ( ) instanceof IProject ) { ArrayList added = new ArrayList ( fInsertedElements ) ; HashSet updatedEclusionPatterns = new HashSet ( ) ; addExlusionPatterns ( added , updatedEclusionPatterns ) ; fModifiedElements . addAll ( updatedEclusionPatterns ) ; } } else { ArrayList added = new ArrayList ( fInsertedElements ) ; HashSet updatedEclusionPatterns = new HashSet ( ) ; addExlusionPatterns ( added , updatedEclusionPatterns ) ; fModifiedElements . addAll ( updatedEclusionPatterns ) ; } return Window . OK ; } else { return Window . CANCEL ; } } public List getInsertedElements ( ) { return new ArrayList ( fInsertedElements ) ; } public List getRemovedElements ( ) { return new ArrayList ( fRemovedElements ) ; } public List getModifiedElements ( ) { return new ArrayList ( fModifiedElements ) ; } private void addExlusionPatterns ( List newEntries , Set modifiedEntries ) { BuildPathBasePage . fixNestingConflicts ( ( CPListElement [ ] ) newEntries . toArray ( new CPListElement [ newEntries . size ( ) ] ) , fExistingElements , modifiedEntries ) ; if ( ! modifiedEntries . isEmpty ( ) ) { String title = NewWizardMessages . SourceContainerWorkbookPage_exclusion_added_title ; String message = NewWizardMessages . SourceContainerWorkbookPage_exclusion_added_message ; MessageDialog . openInformation ( getShell ( ) , title , message ) ; } } private AddSourceFolderWizard newSourceFolderWizard ( CPListElement element , CPListElement [ ] existing , IContainer parent ) { AddSourceFolderWizard wizard = new AddSourceFolderWizard ( existing , element , false , true , false , false , false , parent ) ; wizard . setDoFlushChange ( false ) ; return wizard ; } private List getExistingContainers ( CPListElement [ ] existingElements ) { List res = new ArrayList ( ) ; for ( int i = ; i < existingElements . length ; i ++ ) { IResource resource = existingElements [ i ] . getResource ( ) ; if ( resource instanceof IContainer ) { res . add ( resource ) ; } } Set keys = fNonExistingFolders . keySet ( ) ; for ( Iterator iter = keys . iterator ( ) ; iter . hasNext ( ) ; ) { IFolder folder = ( IFolder ) iter . next ( ) ; res . add ( folder ) ; } return res ; } private IFolder addFakeFolder ( final IContainer container , final CPListElement element ) { IFolder result ; IPath projectPath = fRubyProject . getPath ( ) ; IPath path = element . getPath ( ) ; if ( projectPath . isPrefixOf ( path ) ) { path = path . removeFirstSegments ( projectPath . segmentCount ( ) ) ; } result = container . getFolder ( path ) ; IFolder folder = result ; do { IContainer parent = folder . getParent ( ) ; fNonExistingFolders . put ( folder , parent ) ; if ( parent instanceof IFolder ) { folder = ( IFolder ) parent ; } else { folder = null ; } } while ( folder != null && ! folder . exists ( ) ) ; return result ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . List ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; public class LoadpathOrderingWorkbookPage extends BuildPathBasePage { private ListDialogField fLoadPathList ; public LoadpathOrderingWorkbookPage ( ListDialogField loadPathList ) { fLoadPathList = loadPathList ; } public Control getControl ( Composite parent ) { PixelConverter converter = new PixelConverter ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; LayoutUtil . doDefaultLayout ( composite , new DialogField [ ] { fLoadPathList } , true , SWT . DEFAULT , SWT . DEFAULT ) ; LayoutUtil . setHorizontalGrabbing ( fLoadPathList . getListControl ( null ) ) ; int buttonBarWidth = converter . convertWidthInCharsToPixels ( ) ; fLoadPathList . setButtonsMinWidth ( buttonBarWidth ) ; return composite ; } public List getSelection ( ) { return fLoadPathList . getSelectedElements ( ) ; } public void setSelection ( List selElements , boolean expand ) { fLoadPathList . selectElements ( new StructuredSelection ( selElements ) ) ; } public boolean isEntryKind ( int kind ) { return true ; } public void init ( IRubyProject javaProject ) { } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . jface . wizard . Wizard ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . ui . wizards . ILoadpathContainerPage ; import org . rubypeople . rdt . ui . wizards . ILoadpathContainerPageExtension ; import org . rubypeople . rdt . ui . wizards . ILoadpathContainerPageExtension2 ; public class LoadpathContainerWizard extends Wizard { private LoadpathContainerDescriptor fPageDesc ; private ILoadpathEntry fEntryToEdit ; private ILoadpathEntry [ ] fNewEntries ; private ILoadpathContainerPage fContainerPage ; private IRubyProject fCurrProject ; private ILoadpathEntry [ ] fCurrLoadpath ; private LoadpathContainerSelectionPage fSelectionWizardPage ; public LoadpathContainerWizard ( ILoadpathEntry entryToEdit , IRubyProject currProject , ILoadpathEntry [ ] currEntries ) { this ( entryToEdit , null , currProject , currEntries ) ; } public LoadpathContainerWizard ( LoadpathContainerDescriptor pageDesc , IRubyProject currProject , ILoadpathEntry [ ] currEntries ) { this ( null , pageDesc , currProject , currEntries ) ; } private LoadpathContainerWizard ( ILoadpathEntry entryToEdit , LoadpathContainerDescriptor pageDesc , IRubyProject currProject , ILoadpathEntry [ ] currEntries ) { fEntryToEdit = entryToEdit ; fPageDesc = pageDesc ; fNewEntries = null ; fCurrProject = currProject ; fCurrLoadpath = currEntries ; String title ; if ( entryToEdit == null ) { title = NewWizardMessages . LoadpathContainerWizard_new_title ; } else { title = NewWizardMessages . LoadpathContainerWizard_edit_title ; } setWindowTitle ( title ) ; } public ILoadpathEntry getNewEntry ( ) { ILoadpathEntry [ ] entries = getNewEntries ( ) ; if ( entries != null ) { return entries [ ] ; } return null ; } public ILoadpathEntry [ ] getNewEntries ( ) { return fNewEntries ; } public boolean performFinish ( ) { if ( fContainerPage != null ) { if ( fContainerPage . finish ( ) ) { if ( fEntryToEdit == null && fContainerPage instanceof ILoadpathContainerPageExtension2 ) { fNewEntries = ( ( ILoadpathContainerPageExtension2 ) fContainerPage ) . getNewContainers ( ) ; } else { ILoadpathEntry entry = fContainerPage . getSelection ( ) ; fNewEntries = ( entry != null ) ? new ILoadpathEntry [ ] { entry } : null ; } return true ; } } return false ; } public void addPages ( ) { if ( fPageDesc != null ) { fContainerPage = getContainerPage ( fPageDesc ) ; addPage ( fContainerPage ) ; } else if ( fEntryToEdit == null ) { LoadpathContainerDescriptor [ ] containers = LoadpathContainerDescriptor . getDescriptors ( ) ; fSelectionWizardPage = new LoadpathContainerSelectionPage ( containers ) ; addPage ( fSelectionWizardPage ) ; fContainerPage = new LoadpathContainerDefaultPage ( ) ; addPage ( fContainerPage ) ; } else { LoadpathContainerDescriptor [ ] containers = LoadpathContainerDescriptor . getDescriptors ( ) ; LoadpathContainerDescriptor descriptor = findDescriptorPage ( containers , fEntryToEdit ) ; fContainerPage = getContainerPage ( descriptor ) ; addPage ( fContainerPage ) ; } super . addPages ( ) ; } private ILoadpathContainerPage getContainerPage ( LoadpathContainerDescriptor pageDesc ) { ILoadpathContainerPage containerPage = null ; if ( pageDesc != null ) { ILoadpathContainerPage page = pageDesc . getPage ( ) ; if ( page != null ) { return page ; } try { containerPage = pageDesc . createPage ( ) ; } catch ( CoreException e ) { handlePageCreationFailed ( e ) ; containerPage = null ; } } if ( containerPage == null ) { containerPage = new LoadpathContainerDefaultPage ( ) ; if ( pageDesc != null ) { pageDesc . setPage ( containerPage ) ; } } if ( containerPage instanceof ILoadpathContainerPageExtension ) { ( ( ILoadpathContainerPageExtension ) containerPage ) . initialize ( fCurrProject , fCurrLoadpath ) ; } containerPage . setSelection ( fEntryToEdit ) ; containerPage . setWizard ( this ) ; return containerPage ; } public IWizardPage getNextPage ( IWizardPage page ) { if ( page == fSelectionWizardPage ) { LoadpathContainerDescriptor selected = fSelectionWizardPage . getSelected ( ) ; fContainerPage = getContainerPage ( selected ) ; return fContainerPage ; } return super . getNextPage ( page ) ; } private void handlePageCreationFailed ( CoreException e ) { String title = NewWizardMessages . LoadpathContainerWizard_pagecreationerror_title ; String message = NewWizardMessages . LoadpathContainerWizard_pagecreationerror_message ; ExceptionHandler . handle ( e , getShell ( ) , title , message ) ; } private LoadpathContainerDescriptor findDescriptorPage ( LoadpathContainerDescriptor [ ] containers , ILoadpathEntry entry ) { for ( int i = ; i < containers . length ; i ++ ) { if ( containers [ i ] . canEdit ( entry ) ) { return containers [ i ] ; } } return null ; } public void dispose ( ) { if ( fSelectionWizardPage != null ) { LoadpathContainerDescriptor [ ] descriptors = fSelectionWizardPage . getContainers ( ) ; for ( int i = ; i < descriptors . length ; i ++ ) { descriptors [ i ] . dispose ( ) ; } } super . dispose ( ) ; } public boolean canFinish ( ) { if ( fSelectionWizardPage != null ) { if ( ! fContainerPage . isPageComplete ( ) ) { return false ; } } if ( fContainerPage != null ) { return fContainerPage . isPageComplete ( ) ; } return false ; } public static int openWizard ( Shell shell , LoadpathContainerWizard wizard ) { WizardDialog dialog = new WizardDialog ( shell , wizard ) ; PixelConverter converter = new PixelConverter ( shell ) ; dialog . setMinimumPageSize ( converter . convertWidthInCharsToPixels ( ) , converter . convertHeightInCharsToPixels ( ) ) ; dialog . create ( ) ; return dialog . open ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . core . resources . IContainer ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . window . Window ; 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 . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . ElementTreeSelectionDialog ; import org . eclipse . ui . dialogs . NewFolderDialog ; import org . eclipse . ui . views . navigator . ResourceSorter ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public class FolderSelectionDialog extends ElementTreeSelectionDialog implements ISelectionChangedListener { private Button fNewFolderButton ; private IContainer fSelectedContainer ; public FolderSelectionDialog ( Shell parent , ILabelProvider labelProvider , ITreeContentProvider contentProvider ) { super ( parent , labelProvider , contentProvider ) ; setSorter ( new ResourceSorter ( ResourceSorter . NAME ) ) ; } protected Control createDialogArea ( Composite parent ) { Composite result = ( Composite ) super . createDialogArea ( parent ) ; getTreeViewer ( ) . addSelectionChangedListener ( this ) ; Button button = new Button ( result , SWT . PUSH ) ; button . setText ( NewWizardMessages . FolderSelectionDialog_button ) ; button . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent event ) { newFolderButtonPressed ( ) ; } } ) ; button . setFont ( parent . getFont ( ) ) ; fNewFolderButton = button ; applyDialogFont ( result ) ; return result ; } private void updateNewFolderButtonState ( ) { IStructuredSelection selection = ( IStructuredSelection ) getTreeViewer ( ) . getSelection ( ) ; fSelectedContainer = null ; if ( selection . size ( ) == ) { Object first = selection . getFirstElement ( ) ; if ( first instanceof IContainer ) { fSelectedContainer = ( IContainer ) first ; } } fNewFolderButton . setEnabled ( fSelectedContainer != null ) ; } protected void newFolderButtonPressed ( ) { NewFolderDialog dialog = new NewFolderDialog ( getShell ( ) , fSelectedContainer ) { protected Control createContents ( Composite parent ) { return super . createContents ( parent ) ; } } ; if ( dialog . open ( ) == Window . OK ) { TreeViewer treeViewer = getTreeViewer ( ) ; treeViewer . refresh ( fSelectedContainer ) ; Object createdFolder = dialog . getResult ( ) [ ] ; treeViewer . reveal ( createdFolder ) ; treeViewer . setSelection ( new StructuredSelection ( createdFolder ) ) ; } } public void selectionChanged ( SelectionChangedEvent event ) { updateNewFolderButtonState ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . io . File ; import java . net . URI ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Hashtable ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IPathVariableManager ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . ElementTreeSelectionDialog ; import org . eclipse . ui . dialogs . ISelectionStatusValidator ; import org . eclipse . ui . ide . dialogs . PathVariableSelectionDialog ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; import org . eclipse . ui . views . navigator . ResourceSorter ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . TypedElementSelectionValidator ; import org . rubypeople . rdt . internal . ui . wizards . TypedViewerFilter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . wizards . NewElementWizardPage ; public class AddSourceFolderWizardPage extends NewElementWizardPage { private final class LinkFields implements IStringButtonAdapter , IDialogFieldListener { private StringButtonDialogField fLinkLocation ; private static final String DIALOGSTORE_LAST_EXTERNAL_LOC = RubyUI . ID_PLUGIN + "" ; private RootFieldAdapter fAdapter ; private SelectionButtonDialogField fVariables ; public LinkFields ( ) { fLinkLocation = new StringButtonDialogField ( this ) ; fLinkLocation . setLabelText ( NewWizardMessages . LinkFolderDialog_dependenciesGroup_locationLabel_desc ) ; fLinkLocation . setButtonLabel ( NewWizardMessages . LinkFolderDialog_dependenciesGroup_browseButton_desc ) ; fLinkLocation . setDialogFieldListener ( this ) ; fVariables = new SelectionButtonDialogField ( SWT . PUSH ) ; fVariables . setLabelText ( NewWizardMessages . LinkFolderDialog_dependenciesGroup_variables_desc ) ; fVariables . setDialogFieldListener ( new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { handleVariablesButtonPressed ( ) ; } } ) ; } public void setDialogFieldListener ( RootFieldAdapter adapter ) { fAdapter = adapter ; } private void doFillIntoGrid ( Composite parent , int numColumns ) { fLinkLocation . doFillIntoGrid ( parent , numColumns ) ; LayoutUtil . setHorizontalSpan ( fLinkLocation . getLabelControl ( null ) , numColumns ) ; LayoutUtil . setHorizontalGrabbing ( fLinkLocation . getTextControl ( null ) ) ; fVariables . doFillIntoGrid ( parent , ) ; } public IPath getLinkTarget ( ) { return Path . fromOSString ( fLinkLocation . getText ( ) ) ; } public void setLinkTarget ( IPath path ) { fLinkLocation . setText ( path . toOSString ( ) ) ; } public void changeControlPressed ( DialogField field ) { final DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) ) ; dialog . setMessage ( NewWizardMessages . RubyProjectWizardFirstPage_directory_message ) ; String directoryName = fLinkLocation . getText ( ) . trim ( ) ; if ( directoryName . length ( ) == ) { String prevLocation = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( DIALOGSTORE_LAST_EXTERNAL_LOC ) ; if ( prevLocation != null ) { directoryName = prevLocation ; } } if ( directoryName . length ( ) > ) { final File path = new File ( directoryName ) ; if ( path . exists ( ) ) dialog . setFilterPath ( directoryName ) ; } final String selectedDirectory = dialog . open ( ) ; if ( selectedDirectory != null ) { fLinkLocation . setText ( selectedDirectory ) ; fRootDialogField . setText ( selectedDirectory . substring ( selectedDirectory . lastIndexOf ( File . separatorChar ) + ) ) ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( DIALOGSTORE_LAST_EXTERNAL_LOC , selectedDirectory ) ; if ( fAdapter != null ) { fAdapter . dialogFieldChanged ( fRootDialogField ) ; } } } private void handleVariablesButtonPressed ( ) { int variableTypes = IResource . FOLDER ; PathVariableSelectionDialog dialog = new PathVariableSelectionDialog ( getShell ( ) , variableTypes ) ; if ( dialog . open ( ) == IDialogConstants . OK_ID ) { String [ ] variableNames = ( String [ ] ) dialog . getResult ( ) ; if ( variableNames != null && variableNames . length == ) { fLinkLocation . setText ( variableNames [ ] ) ; fRootDialogField . setText ( variableNames [ ] ) ; if ( fAdapter != null ) { fAdapter . dialogFieldChanged ( fRootDialogField ) ; } } } } public void dialogFieldChanged ( DialogField field ) { if ( fAdapter != null ) { fAdapter . dialogFieldChanged ( fLinkLocation ) ; } } } private static final String PAGE_NAME = "" ; private final StringDialogField fRootDialogField ; private final SelectionButtonDialogField fAddExclusionPatterns , fRemoveProjectFolder , fIgnoreConflicts ; private final LinkFields fLinkFields ; private final CPListElement fNewElement ; private final List fExistingEntries ; private final Hashtable fOrginalExlusionFilters , fOrginalInclusionFilters , fOrginalExlusionFiltersCopy , fOrginalInclusionFiltersCopy ; private final IPath fOrginalPath ; private final boolean fLinkedMode ; private CPListElement fOldProjectSourceFolder ; private List fModifiedElements ; private List fRemovedElements ; private final boolean fAllowConflict ; private final boolean fAllowRemoveProjectFolder ; private final boolean fAllowAddExclusionPatterns ; private final boolean fCanCommitConflictingBuildpath ; private final IContainer fParent ; public AddSourceFolderWizardPage ( CPListElement newElement , List existingEntries , boolean linkedMode , boolean canCommitConflictingBuildpath , boolean allowIgnoreConflicts , boolean allowRemoveProjectFolder , boolean allowAddExclusionPatterns , IContainer parent ) { super ( PAGE_NAME ) ; fLinkedMode = linkedMode ; fCanCommitConflictingBuildpath = canCommitConflictingBuildpath ; fAllowConflict = allowIgnoreConflicts ; fAllowRemoveProjectFolder = allowRemoveProjectFolder ; fAllowAddExclusionPatterns = allowAddExclusionPatterns ; fParent = parent ; fOrginalExlusionFilters = new Hashtable ( ) ; fOrginalInclusionFilters = new Hashtable ( ) ; fOrginalExlusionFiltersCopy = new Hashtable ( ) ; fOrginalInclusionFiltersCopy = new Hashtable ( ) ; for ( Iterator iter = existingEntries . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement element = ( CPListElement ) iter . next ( ) ; IPath [ ] exlusions = ( IPath [ ] ) element . getAttribute ( CPListElement . EXCLUSION ) ; if ( exlusions != null ) { IPath [ ] save = new IPath [ exlusions . length ] ; for ( int i = ; i < save . length ; i ++ ) { save [ i ] = exlusions [ i ] ; } fOrginalExlusionFiltersCopy . put ( element , save ) ; fOrginalExlusionFilters . put ( element , exlusions ) ; } IPath [ ] inclusions = ( IPath [ ] ) element . getAttribute ( CPListElement . INCLUSION ) ; if ( inclusions != null ) { IPath [ ] save = new IPath [ inclusions . length ] ; for ( int i = ; i < save . length ; i ++ ) { save [ i ] = inclusions [ i ] ; } fOrginalInclusionFiltersCopy . put ( element , save ) ; fOrginalInclusionFilters . put ( element , inclusions ) ; } } setTitle ( NewWizardMessages . NewSourceFolderWizardPage_title ) ; fOrginalPath = newElement . getPath ( ) ; if ( fOrginalPath == null ) { if ( linkedMode ) { setDescription ( Messages . format ( NewWizardMessages . NewFolderDialog_createIn , newElement . getRubyProject ( ) . getElementName ( ) ) ) ; } else { setDescription ( Messages . format ( NewWizardMessages . AddSourceFolderWizardPage_description , fParent . getFullPath ( ) . toString ( ) ) ) ; } } else { setDescription ( NewWizardMessages . NewSourceFolderWizardPage_edit_description ) ; } fNewElement = newElement ; fExistingEntries = existingEntries ; fModifiedElements = new ArrayList ( ) ; fRemovedElements = new ArrayList ( ) ; RootFieldAdapter adapter = new RootFieldAdapter ( ) ; fRootDialogField = new StringDialogField ( ) ; fRootDialogField . setLabelText ( NewWizardMessages . NewSourceFolderWizardPage_root_label ) ; if ( fNewElement . getPath ( ) == null ) { fRootDialogField . setText ( "" ) ; } else { setFolderDialogText ( fNewElement . getPath ( ) ) ; } fRootDialogField . setEnabled ( fNewElement . getRubyProject ( ) != null ) ; int buttonStyle = SWT . CHECK ; if ( ( fAllowConflict && fAllowAddExclusionPatterns ) || ( fAllowConflict && fAllowRemoveProjectFolder ) || ( fAllowAddExclusionPatterns && fAllowRemoveProjectFolder ) ) { buttonStyle = SWT . RADIO ; } fAddExclusionPatterns = new SelectionButtonDialogField ( buttonStyle ) ; fAddExclusionPatterns . setLabelText ( NewWizardMessages . NewSourceFolderWizardPage_exclude_label ) ; fAddExclusionPatterns . setSelection ( ! fCanCommitConflictingBuildpath && ! fAllowRemoveProjectFolder ) ; fRemoveProjectFolder = new SelectionButtonDialogField ( buttonStyle ) ; fRemoveProjectFolder . setLabelText ( NewWizardMessages . NewSourceFolderWizardPage_ReplaceExistingSourceFolder_label ) ; fRemoveProjectFolder . setSelection ( ! fCanCommitConflictingBuildpath && fAllowRemoveProjectFolder ) ; fIgnoreConflicts = new SelectionButtonDialogField ( buttonStyle ) ; fIgnoreConflicts . setLabelText ( NewWizardMessages . AddSourceFolderWizardPage_ignoreNestingConflicts ) ; fIgnoreConflicts . setSelection ( fCanCommitConflictingBuildpath ) ; fLinkFields = new LinkFields ( ) ; if ( fNewElement . getLinkTarget ( ) != null ) { fLinkFields . setLinkTarget ( fNewElement . getLinkTarget ( ) ) ; } fRemoveProjectFolder . setDialogFieldListener ( adapter ) ; fAddExclusionPatterns . setDialogFieldListener ( adapter ) ; fIgnoreConflicts . setDialogFieldListener ( adapter ) ; fRootDialogField . setDialogFieldListener ( adapter ) ; fLinkFields . setDialogFieldListener ( adapter ) ; packRootDialogFieldChanged ( ) ; } public void createControl ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; if ( fLinkedMode ) { fLinkFields . doFillIntoGrid ( composite , layout . numColumns ) ; fRootDialogField . doFillIntoGrid ( composite , layout . numColumns - ) ; } else { fRootDialogField . doFillIntoGrid ( composite , layout . numColumns - ) ; } if ( fAllowRemoveProjectFolder ) fRemoveProjectFolder . doFillIntoGrid ( composite , layout . numColumns ) ; if ( fAllowAddExclusionPatterns ) fAddExclusionPatterns . doFillIntoGrid ( composite , layout . numColumns ) ; if ( fAllowConflict ) fIgnoreConflicts . doFillIntoGrid ( composite , layout . numColumns ) ; LayoutUtil . setHorizontalSpan ( fRootDialogField . getLabelControl ( null ) , layout . numColumns ) ; LayoutUtil . setHorizontalGrabbing ( fRootDialogField . getTextControl ( null ) ) ; setControl ( composite ) ; Dialog . applyDialogFont ( composite ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( composite , IRubyHelpContextIds . NEW_PACKAGEROOT_WIZARD_PAGE ) ; } public void setVisible ( boolean visible ) { super . setVisible ( visible ) ; if ( visible ) { fRootDialogField . setFocus ( ) ; } } private class RootFieldAdapter implements IStringButtonAdapter , IDialogFieldListener { public void changeControlPressed ( DialogField field ) { packRootChangeControlPressed ( field ) ; } public void dialogFieldChanged ( DialogField field ) { packRootDialogFieldChanged ( ) ; } } protected void packRootChangeControlPressed ( DialogField field ) { if ( field == fRootDialogField ) { IPath initialPath = new Path ( fRootDialogField . getText ( ) ) ; String title = NewWizardMessages . NewSourceFolderWizardPage_ChooseExistingRootDialog_title ; String message = NewWizardMessages . NewSourceFolderWizardPage_ChooseExistingRootDialog_description ; IFolder folder = chooseFolder ( title , message , initialPath ) ; if ( folder != null ) { setFolderDialogText ( folder . getFullPath ( ) ) ; } } } private void setFolderDialogText ( IPath path ) { IPath shortPath = path . removeFirstSegments ( ) ; fRootDialogField . setText ( shortPath . toString ( ) ) ; } protected void packRootDialogFieldChanged ( ) { StatusInfo status = updateRootStatus ( ) ; updateStatus ( new IStatus [ ] { status } ) ; } private StatusInfo updateRootStatus ( ) { IRubyProject javaProject = fNewElement . getRubyProject ( ) ; IProject project = javaProject . getProject ( ) ; StatusInfo pathNameStatus = validatePathName ( fRootDialogField . getText ( ) , fParent ) ; if ( ! pathNameStatus . isOK ( ) ) return pathNameStatus ; if ( fLinkedMode ) { IStatus linkNameStatus = validateLinkLocation ( fRootDialogField . getText ( ) ) ; if ( linkNameStatus . matches ( IStatus . ERROR ) ) { StatusInfo result = new StatusInfo ( ) ; result . setError ( linkNameStatus . getMessage ( ) ) ; return result ; } } StatusInfo result = new StatusInfo ( ) ; result . setOK ( ) ; IPath projPath = project . getFullPath ( ) ; IPath path = fParent . getFullPath ( ) . append ( fRootDialogField . getText ( ) ) ; restoreCPElements ( ) ; int projectEntryIndex = - ; for ( int i = ; i < fExistingEntries . size ( ) ; i ++ ) { ILoadpathEntry curr = ( ( CPListElement ) fExistingEntries . get ( i ) ) . getLoadpathEntry ( ) ; if ( curr . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { if ( path . equals ( curr . getPath ( ) ) && fExistingEntries . get ( i ) != fNewElement ) { result . setError ( NewWizardMessages . NewSourceFolderWizardPage_error_AlreadyExisting ) ; return result ; } if ( projPath . equals ( curr . getPath ( ) ) ) { projectEntryIndex = i ; } } } IFolder folder = fParent . getFolder ( new Path ( fRootDialogField . getText ( ) ) ) ; if ( folder . exists ( ) && ! folder . getFullPath ( ) . equals ( fOrginalPath ) ) return new StatusInfo ( IStatus . ERROR , Messages . format ( NewWizardMessages . NewFolderDialog_folderNameEmpty_alreadyExists , folder . getFullPath ( ) . toString ( ) ) ) ; boolean isProjectASourceFolder = projectEntryIndex != - ; fModifiedElements . clear ( ) ; updateFilters ( fNewElement . getPath ( ) , path ) ; fNewElement . setPath ( path ) ; if ( fLinkedMode ) { fNewElement . setLinkTarget ( fLinkFields . getLinkTarget ( ) ) ; } fRemovedElements . clear ( ) ; Set modified = new HashSet ( ) ; boolean isProjectSourceFolderReplaced = false ; if ( fAddExclusionPatterns . isSelected ( ) ) { if ( fOrginalPath == null ) { addExclusionPatterns ( fNewElement , fExistingEntries , modified ) ; fModifiedElements . addAll ( modified ) ; CPListElement . insert ( fNewElement , fExistingEntries ) ; } } else { if ( isProjectASourceFolder ) { if ( fRemoveProjectFolder . isSelected ( ) ) { fOldProjectSourceFolder = ( CPListElement ) fExistingEntries . get ( projectEntryIndex ) ; fRemovedElements . add ( fOldProjectSourceFolder ) ; fExistingEntries . set ( projectEntryIndex , fNewElement ) ; isProjectSourceFolderReplaced = true ; } else { CPListElement . insert ( fNewElement , fExistingEntries ) ; } } else { CPListElement . insert ( fNewElement , fExistingEntries ) ; } } if ( ! fAllowConflict && fCanCommitConflictingBuildpath ) return new StatusInfo ( ) ; IRubyModelStatus status = RubyConventions . validateLoadpath ( javaProject , CPListElement . convertToLoadpathEntries ( fExistingEntries ) , null ) ; if ( ! status . isOK ( ) ) { if ( fCanCommitConflictingBuildpath ) { result . setInfo ( NewWizardMessages . AddSourceFolderWizardPage_conflictWarning + status . getMessage ( ) ) ; } else { result . setError ( status . getMessage ( ) ) ; } return result ; } if ( ! modified . isEmpty ( ) ) { if ( modified . size ( ) == ) { CPListElement elem = ( CPListElement ) modified . toArray ( ) [ ] ; IPath changed = elem . getPath ( ) . makeRelative ( ) ; IPath excl = fNewElement . getPath ( ) . makeRelative ( ) ; result . setInfo ( Messages . format ( NewWizardMessages . AddSourceFolderWizardPage_addSinglePattern , new Object [ ] { excl , changed } ) ) ; } else { result . setInfo ( Messages . format ( NewWizardMessages . NewSourceFolderWizardPage_warning_AddedExclusions , String . valueOf ( modified . size ( ) ) ) ) ; } return result ; } if ( isProjectSourceFolderReplaced ) { result . setInfo ( NewWizardMessages . AddSourceFolderWizardPage_replaceSourceFolderInfo ) ; return result ; } return result ; } public void restore ( ) { for ( Iterator iter = fExistingEntries . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement element = ( CPListElement ) iter . next ( ) ; if ( fOrginalExlusionFilters . containsKey ( element ) ) { element . setAttribute ( CPListElement . EXCLUSION , fOrginalExlusionFiltersCopy . get ( element ) ) ; } if ( fOrginalInclusionFilters . containsKey ( element ) ) { element . setAttribute ( CPListElement . INCLUSION , fOrginalInclusionFiltersCopy . get ( element ) ) ; } } fNewElement . setPath ( fOrginalPath ) ; } private void restoreCPElements ( ) { if ( fNewElement . getPath ( ) != null ) { for ( Iterator iter = fExistingEntries . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement element = ( CPListElement ) iter . next ( ) ; if ( fOrginalExlusionFilters . containsKey ( element ) ) { element . setAttribute ( CPListElement . EXCLUSION , fOrginalExlusionFilters . get ( element ) ) ; } if ( fOrginalInclusionFilters . containsKey ( element ) ) { element . setAttribute ( CPListElement . INCLUSION , fOrginalInclusionFilters . get ( element ) ) ; } } if ( fOldProjectSourceFolder != null ) { fExistingEntries . set ( fExistingEntries . indexOf ( fNewElement ) , fOldProjectSourceFolder ) ; fOldProjectSourceFolder = null ; } else if ( fExistingEntries . contains ( fNewElement ) ) { fExistingEntries . remove ( fNewElement ) ; } } } private void updateFilters ( IPath oldPath , IPath newPath ) { if ( oldPath == null ) return ; IPath projPath = fNewElement . getRubyProject ( ) . getProject ( ) . getFullPath ( ) ; if ( projPath . isPrefixOf ( oldPath ) ) { oldPath = oldPath . removeFirstSegments ( projPath . segmentCount ( ) ) . addTrailingSeparator ( ) ; } if ( projPath . isPrefixOf ( newPath ) ) { newPath = newPath . removeFirstSegments ( projPath . segmentCount ( ) ) . addTrailingSeparator ( ) ; } for ( Iterator iter = fExistingEntries . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement element = ( CPListElement ) iter . next ( ) ; IPath elementPath = element . getPath ( ) ; if ( projPath . isPrefixOf ( elementPath ) ) { elementPath = elementPath . removeFirstSegments ( projPath . segmentCount ( ) ) ; if ( elementPath . segmentCount ( ) > ) elementPath = elementPath . addTrailingSeparator ( ) ; } IPath [ ] exlusions = ( IPath [ ] ) element . getAttribute ( CPListElement . EXCLUSION ) ; if ( exlusions != null ) { for ( int i = ; i < exlusions . length ; i ++ ) { if ( elementPath . append ( exlusions [ i ] ) . equals ( oldPath ) ) { fModifiedElements . add ( element ) ; exlusions [ i ] = newPath . removeFirstSegments ( elementPath . segmentCount ( ) ) ; } } element . setAttribute ( CPListElement . EXCLUSION , exlusions ) ; } IPath [ ] inclusion = ( IPath [ ] ) element . getAttribute ( CPListElement . INCLUSION ) ; if ( inclusion != null ) { for ( int i = ; i < inclusion . length ; i ++ ) { if ( elementPath . append ( inclusion [ i ] ) . equals ( oldPath ) ) { fModifiedElements . add ( element ) ; inclusion [ i ] = newPath . removeFirstSegments ( elementPath . segmentCount ( ) ) ; } } element . setAttribute ( CPListElement . INCLUSION , inclusion ) ; } } } private IStatus validateLinkLocation ( String folderName ) { IWorkspace workspace = RubyPlugin . getWorkspace ( ) ; IPath path = Path . fromOSString ( fLinkFields . fLinkLocation . getText ( ) ) ; IFolder folder = fNewElement . getRubyProject ( ) . getProject ( ) . getFolder ( new Path ( folderName ) ) ; IStatus locationStatus = workspace . validateLinkLocation ( folder , path ) ; if ( locationStatus . matches ( IStatus . ERROR ) ) return locationStatus ; IPathVariableManager pathVariableManager = ResourcesPlugin . getWorkspace ( ) . getPathVariableManager ( ) ; IPath path1 = Path . fromOSString ( fLinkFields . fLinkLocation . getText ( ) ) ; IPath resolvedPath = pathVariableManager . resolvePath ( path1 ) ; String resolvedLinkTarget = resolvedPath . toOSString ( ) ; path = new Path ( resolvedLinkTarget ) ; File linkTargetFile = new Path ( resolvedLinkTarget ) . toFile ( ) ; if ( linkTargetFile . exists ( ) ) { if ( ! linkTargetFile . isDirectory ( ) ) return new StatusInfo ( IStatus . ERROR , NewWizardMessages . NewFolderDialog_linkTargetNotFolder ) ; } else { return new StatusInfo ( IStatus . ERROR , NewWizardMessages . NewFolderDialog_linkTargetNonExistent ) ; } if ( locationStatus . isOK ( ) ) { return new StatusInfo ( ) ; } return new StatusInfo ( locationStatus . getSeverity ( ) , locationStatus . getMessage ( ) ) ; } private static StatusInfo validatePathName ( String str , IContainer parent ) { StatusInfo result = new StatusInfo ( ) ; result . setOK ( ) ; IPath parentPath = parent . getFullPath ( ) ; if ( str . length ( ) == ) { result . setError ( Messages . format ( NewWizardMessages . NewSourceFolderWizardPage_error_EnterRootName , parentPath . toString ( ) ) ) ; return result ; } IPath path = parentPath . append ( str ) ; IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IStatus validate = workspaceRoot . getWorkspace ( ) . validatePath ( path . toString ( ) , IResource . FOLDER ) ; if ( validate . matches ( IStatus . ERROR ) ) { result . setError ( Messages . format ( NewWizardMessages . NewSourceFolderWizardPage_error_InvalidRootName , validate . getMessage ( ) ) ) ; return result ; } IResource res = workspaceRoot . findMember ( path ) ; if ( res != null ) { if ( res . getType ( ) != IResource . FOLDER ) { result . setError ( NewWizardMessages . NewSourceFolderWizardPage_error_NotAFolder ) ; return result ; } } else { URI parentLocation = parent . getLocationURI ( ) ; if ( parentLocation != null ) { try { IFileStore store = EFS . getStore ( parentLocation ) . getChild ( str ) ; if ( store . fetchInfo ( ) . exists ( ) ) { result . setError ( NewWizardMessages . NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase ) ; return result ; } } catch ( CoreException e ) { } } } return result ; } private void addExclusionPatterns ( CPListElement newEntry , List existing , Set modifiedEntries ) { IPath entryPath = newEntry . getPath ( ) ; for ( int i = ; i < existing . size ( ) ; i ++ ) { CPListElement curr = ( CPListElement ) existing . get ( i ) ; IPath currPath = curr . getPath ( ) ; if ( curr != newEntry && curr . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE && currPath . isPrefixOf ( entryPath ) ) { boolean added = curr . addToExclusions ( entryPath ) ; if ( added ) { modifiedEntries . add ( curr ) ; } } } } public IResource getCorrespondingResource ( ) { return fParent . getFolder ( new Path ( fRootDialogField . getText ( ) ) ) ; } private IFolder chooseFolder ( String title , String message , IPath initialPath ) { Class [ ] acceptedClasses = new Class [ ] { IFolder . class } ; ISelectionStatusValidator validator = new TypedElementSelectionValidator ( acceptedClasses , false ) ; ViewerFilter filter = new TypedViewerFilter ( acceptedClasses , null ) ; ILabelProvider lp = new WorkbenchLabelProvider ( ) ; ITreeContentProvider cp = new WorkbenchContentProvider ( ) ; IProject currProject = fNewElement . getRubyProject ( ) . getProject ( ) ; ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog ( getShell ( ) , lp , cp ) { protected Control createDialogArea ( Composite parent ) { Control result = super . createDialogArea ( parent ) ; return result ; } } ; dialog . setValidator ( validator ) ; dialog . setTitle ( title ) ; dialog . setMessage ( message ) ; dialog . addFilter ( filter ) ; dialog . setInput ( currProject ) ; dialog . setSorter ( new ResourceSorter ( ResourceSorter . NAME ) ) ; IResource res = currProject . findMember ( initialPath ) ; if ( res != null ) { dialog . setInitialSelection ( res ) ; } if ( dialog . open ( ) == Window . OK ) { return ( IFolder ) dialog . getFirstResult ( ) ; } return null ; } public List getModifiedElements ( ) { if ( fOrginalPath != null && ! fModifiedElements . contains ( fNewElement ) ) fModifiedElements . add ( fNewElement ) ; return fModifiedElements ; } public List getRemovedElements ( ) { return fRemovedElements ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . wizards . NewElementWizard ; public abstract class BuildPathWizard extends NewElementWizard { private boolean fDoFlushChange ; private final CPListElement fEntryToEdit ; private ISourceFolderRoot fSourceFolderRoot ; private final ArrayList fExistingEntries ; public BuildPathWizard ( CPListElement [ ] existingEntries , CPListElement newEntry , String titel , ImageDescriptor image ) { if ( image != null ) setDefaultPageImageDescriptor ( image ) ; setDialogSettings ( RubyPlugin . getDefault ( ) . getDialogSettings ( ) ) ; setWindowTitle ( titel ) ; fEntryToEdit = newEntry ; fExistingEntries = new ArrayList ( Arrays . asList ( existingEntries ) ) ; fDoFlushChange = true ; } protected void finishPage ( IProgressMonitor monitor ) throws InterruptedException , CoreException { if ( fDoFlushChange ) { IRubyProject rubyProject = getEntryToEdit ( ) . getRubyProject ( ) ; BuildPathsBlock . flush ( getExistingEntries ( ) , rubyProject , monitor ) ; IProject project = rubyProject . getProject ( ) ; IPath projPath = project . getFullPath ( ) ; IPath path = getEntryToEdit ( ) . getPath ( ) ; if ( ! projPath . equals ( path ) && projPath . isPrefixOf ( path ) ) { path = path . removeFirstSegments ( projPath . segmentCount ( ) ) ; } IFolder folder = project . getFolder ( path ) ; fSourceFolderRoot = rubyProject . getSourceFolderRoot ( folder ) ; } } public IRubyElement getCreatedElement ( ) { return fSourceFolderRoot ; } public void setDoFlushChange ( boolean b ) { fDoFlushChange = b ; } public ArrayList getExistingEntries ( ) { return fExistingEntries ; } protected CPListElement getEntryToEdit ( ) { return fEntryToEdit ; } public List getInsertedElements ( ) { return new ArrayList ( ) ; } public List getRemovedElements ( ) { return new ArrayList ( ) ; } public List getModifiedElements ( ) { ArrayList result = new ArrayList ( ) ; result . add ( fEntryToEdit ) ; return result ; } public abstract void cancel ( ) ; } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . INewWizard ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . corext . buildpath . LoadpathModifier ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ITreeListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . TreeListDialogField ; import org . rubypeople . rdt . ui . actions . AbstractOpenWizardAction ; public class SourceContainerWorkbookPage extends BuildPathBasePage { private class OpenBuildPathWizardAction extends AbstractOpenWizardAction implements IPropertyChangeListener { private final BuildPathWizard fWizard ; private final List fSelectedElements ; public OpenBuildPathWizardAction ( BuildPathWizard wizard ) { fWizard = wizard ; addPropertyChangeListener ( this ) ; fSelectedElements = fFoldersList . getSelectedElements ( ) ; } protected INewWizard createWizard ( ) throws CoreException { return fWizard ; } public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( IAction . RESULT ) ) { if ( event . getNewValue ( ) . equals ( Boolean . TRUE ) ) { finishWizard ( ) ; } else { fWizard . cancel ( ) ; } } } protected void finishWizard ( ) { List insertedElements = fWizard . getInsertedElements ( ) ; refresh ( insertedElements , fWizard . getRemovedElements ( ) , fWizard . getModifiedElements ( ) ) ; if ( insertedElements . isEmpty ( ) ) { fFoldersList . postSetSelection ( new StructuredSelection ( fSelectedElements ) ) ; } } } private static AddSourceFolderWizard newSourceFolderWizard ( CPListElement element , List existingElements , boolean newFolder ) { CPListElement [ ] existing = ( CPListElement [ ] ) existingElements . toArray ( new CPListElement [ existingElements . size ( ) ] ) ; AddSourceFolderWizard wizard = new AddSourceFolderWizard ( existing , element , false , newFolder , newFolder , newFolder ? CPListElement . isProjectSourceFolder ( existing , element . getRubyProject ( ) ) : false , newFolder ) ; wizard . setDoFlushChange ( false ) ; return wizard ; } private static AddSourceFolderWizard newLinkedSourceFolderWizard ( CPListElement element , List existingElements , boolean newFolder ) { CPListElement [ ] existing = ( CPListElement [ ] ) existingElements . toArray ( new CPListElement [ existingElements . size ( ) ] ) ; AddSourceFolderWizard wizard = new AddSourceFolderWizard ( existing , element , true , newFolder , newFolder , newFolder ? CPListElement . isProjectSourceFolder ( existing , element . getRubyProject ( ) ) : false , newFolder ) ; wizard . setDoFlushChange ( false ) ; return wizard ; } private static EditFilterWizard newEditFilterWizard ( CPListElement element , List existingElements ) { CPListElement [ ] existing = ( CPListElement [ ] ) existingElements . toArray ( new CPListElement [ existingElements . size ( ) ] ) ; EditFilterWizard result = new EditFilterWizard ( existing , element ) ; result . setDoFlushChange ( false ) ; return result ; } private ListDialogField fClassPathList ; private IRubyProject fCurrJProject ; private Control fSWTControl ; private TreeListDialogField fFoldersList ; private final int IDX_ADD = ; private final int IDX_ADD_LINK = ; private final int IDX_EDIT = ; private final int IDX_REMOVE = ; public SourceContainerWorkbookPage ( ListDialogField classPathList ) { fClassPathList = classPathList ; fSWTControl = null ; SourceContainerAdapter adapter = new SourceContainerAdapter ( ) ; String [ ] buttonLabels ; buttonLabels = new String [ ] { NewWizardMessages . SourceContainerWorkbookPage_folders_add_button , NewWizardMessages . SourceContainerWorkbookPage_folders_link_source_button , null , NewWizardMessages . SourceContainerWorkbookPage_folders_edit_button , NewWizardMessages . SourceContainerWorkbookPage_folders_remove_button } ; fFoldersList = new TreeListDialogField ( adapter , buttonLabels , new CPListLabelProvider ( ) ) ; fFoldersList . setDialogFieldListener ( adapter ) ; fFoldersList . setLabelText ( NewWizardMessages . SourceContainerWorkbookPage_folders_label ) ; fFoldersList . setViewerSorter ( new CPListElementSorter ( ) ) ; fFoldersList . enableButton ( IDX_EDIT , false ) ; } public void init ( IRubyProject jproject ) { fCurrJProject = jproject ; updateFoldersList ( ) ; } private void updateFoldersList ( ) { ArrayList folders = new ArrayList ( ) ; List cpelements = fClassPathList . getElements ( ) ; for ( int i = ; i < cpelements . size ( ) ; i ++ ) { CPListElement cpe = ( CPListElement ) cpelements . get ( i ) ; if ( cpe . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { folders . add ( cpe ) ; } } fFoldersList . setElements ( folders ) ; for ( int i = ; i < folders . size ( ) ; i ++ ) { CPListElement cpe = ( CPListElement ) folders . get ( i ) ; IPath [ ] ePatterns = ( IPath [ ] ) cpe . getAttribute ( CPListElement . EXCLUSION ) ; IPath [ ] iPatterns = ( IPath [ ] ) cpe . getAttribute ( CPListElement . INCLUSION ) ; if ( ePatterns . length > || iPatterns . length > ) { fFoldersList . expandElement ( cpe , ) ; } } } public Control getControl ( Composite parent ) { PixelConverter converter = new PixelConverter ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; LayoutUtil . doDefaultLayout ( composite , new DialogField [ ] { fFoldersList } , true , SWT . DEFAULT , SWT . DEFAULT ) ; LayoutUtil . setHorizontalGrabbing ( fFoldersList . getTreeControl ( null ) ) ; int buttonBarWidth = converter . convertWidthInCharsToPixels ( ) ; fFoldersList . setButtonsMinWidth ( buttonBarWidth ) ; fSWTControl = composite ; List elements = fFoldersList . getElements ( ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { CPListElement elem = ( CPListElement ) elements . get ( i ) ; IPath [ ] exclusionPatterns = ( IPath [ ] ) elem . getAttribute ( CPListElement . EXCLUSION ) ; IPath [ ] inclusionPatterns = ( IPath [ ] ) elem . getAttribute ( CPListElement . INCLUSION ) ; if ( exclusionPatterns . length > || inclusionPatterns . length > ) { fFoldersList . expandElement ( elem , ) ; } } return composite ; } private Shell getShell ( ) { if ( fSWTControl != null ) { return fSWTControl . getShell ( ) ; } return RubyPlugin . getActiveWorkbenchShell ( ) ; } private class SourceContainerAdapter implements ITreeListAdapter , IDialogFieldListener { private final Object [ ] EMPTY_ARR = new Object [ ] ; public void customButtonPressed ( TreeListDialogField field , int index ) { sourcePageCustomButtonPressed ( field , index ) ; } public void selectionChanged ( TreeListDialogField field ) { sourcePageSelectionChanged ( field ) ; } public void doubleClicked ( TreeListDialogField field ) { sourcePageDoubleClicked ( field ) ; } public void keyPressed ( TreeListDialogField field , KeyEvent event ) { sourcePageKeyPressed ( field , event ) ; } public Object [ ] getChildren ( TreeListDialogField field , Object element ) { if ( element instanceof CPListElement ) { return ( ( CPListElement ) element ) . getChildren ( true ) ; } return EMPTY_ARR ; } public Object getParent ( TreeListDialogField field , Object element ) { if ( element instanceof CPListElementAttribute ) { return ( ( CPListElementAttribute ) element ) . getParent ( ) ; } return null ; } public boolean hasChildren ( TreeListDialogField field , Object element ) { return ( element instanceof CPListElement ) ; } public void dialogFieldChanged ( DialogField field ) { sourcePageDialogFieldChanged ( field ) ; } } protected void sourcePageKeyPressed ( TreeListDialogField field , KeyEvent event ) { if ( field == fFoldersList ) { if ( event . character == SWT . DEL && event . stateMask == ) { List selection = field . getSelectedElements ( ) ; if ( canRemove ( selection ) ) { removeEntry ( ) ; } } } } protected void sourcePageDoubleClicked ( TreeListDialogField field ) { if ( field == fFoldersList ) { List selection = field . getSelectedElements ( ) ; if ( canEdit ( selection ) ) { editEntry ( ) ; } } } protected void sourcePageCustomButtonPressed ( DialogField field , int index ) { if ( field == fFoldersList ) { if ( index == IDX_ADD ) { IProject project = fCurrJProject . getProject ( ) ; if ( project . exists ( ) && hasFolders ( project ) ) { List existingElements = fFoldersList . getElements ( ) ; CPListElement [ ] existing = ( CPListElement [ ] ) existingElements . toArray ( new CPListElement [ existingElements . size ( ) ] ) ; CreateMultipleSourceFoldersDialog dialog = new CreateMultipleSourceFoldersDialog ( fCurrJProject , existing , getShell ( ) ) ; if ( dialog . open ( ) == Window . OK ) { refresh ( dialog . getInsertedElements ( ) , dialog . getRemovedElements ( ) , dialog . getModifiedElements ( ) ) ; } } else { CPListElement newElement = new CPListElement ( fCurrJProject , ILoadpathEntry . CPE_SOURCE ) ; AddSourceFolderWizard wizard = newSourceFolderWizard ( newElement , fFoldersList . getElements ( ) , true ) ; OpenBuildPathWizardAction action = new OpenBuildPathWizardAction ( wizard ) ; action . run ( ) ; } } else if ( index == IDX_ADD_LINK ) { CPListElement newElement = new CPListElement ( fCurrJProject , ILoadpathEntry . CPE_SOURCE ) ; AddSourceFolderWizard wizard = newLinkedSourceFolderWizard ( newElement , fFoldersList . getElements ( ) , true ) ; OpenBuildPathWizardAction action = new OpenBuildPathWizardAction ( wizard ) ; action . run ( ) ; } else if ( index == IDX_EDIT ) { editEntry ( ) ; } else if ( index == IDX_REMOVE ) { removeEntry ( ) ; } } } private boolean hasFolders ( IContainer container ) { try { IResource [ ] members = container . members ( ) ; for ( int i = ; i < members . length ; i ++ ) { if ( members [ i ] instanceof IContainer ) { return true ; } } } catch ( CoreException e ) { } List elements = fFoldersList . getElements ( ) ; if ( elements . size ( ) > ) return true ; if ( elements . size ( ) == ) return false ; CPListElement single = ( CPListElement ) elements . get ( ) ; if ( single . getPath ( ) . equals ( fCurrJProject . getPath ( ) ) ) return false ; return true ; } private void editEntry ( ) { List selElements = fFoldersList . getSelectedElements ( ) ; if ( selElements . size ( ) != ) { return ; } Object elem = selElements . get ( ) ; if ( fFoldersList . getIndexOfElement ( elem ) != - ) { editElementEntry ( ( CPListElement ) elem ) ; } else if ( elem instanceof CPListElementAttribute ) { editAttributeEntry ( ( CPListElementAttribute ) elem ) ; } } private void editElementEntry ( CPListElement elem ) { if ( elem . getLinkTarget ( ) != null ) { AddSourceFolderWizard wizard = newLinkedSourceFolderWizard ( elem , fFoldersList . getElements ( ) , false ) ; OpenBuildPathWizardAction action = new OpenBuildPathWizardAction ( wizard ) ; action . run ( ) ; } else { AddSourceFolderWizard wizard = newSourceFolderWizard ( elem , fFoldersList . getElements ( ) , false ) ; OpenBuildPathWizardAction action = new OpenBuildPathWizardAction ( wizard ) ; action . run ( ) ; } } private void editAttributeEntry ( CPListElementAttribute elem ) { String key = elem . getKey ( ) ; if ( key . equals ( CPListElement . EXCLUSION ) || key . equals ( CPListElement . INCLUSION ) ) { EditFilterWizard wizard = newEditFilterWizard ( elem . getParent ( ) , fFoldersList . getElements ( ) ) ; OpenBuildPathWizardAction action = new OpenBuildPathWizardAction ( wizard ) ; action . run ( ) ; } } protected void sourcePageSelectionChanged ( DialogField field ) { List selected = fFoldersList . getSelectedElements ( ) ; fFoldersList . enableButton ( IDX_EDIT , canEdit ( selected ) ) ; fFoldersList . enableButton ( IDX_REMOVE , canRemove ( selected ) ) ; boolean noAttributes = containsOnlyTopLevelEntries ( selected ) ; fFoldersList . enableButton ( IDX_ADD , noAttributes ) ; } private void removeEntry ( ) { List selElements = fFoldersList . getSelectedElements ( ) ; for ( int i = selElements . size ( ) - ; i >= ; i -- ) { Object elem = selElements . get ( i ) ; if ( elem instanceof CPListElementAttribute ) { CPListElementAttribute attrib = ( CPListElementAttribute ) elem ; String key = attrib . getKey ( ) ; Object value = null ; if ( key . equals ( CPListElement . EXCLUSION ) || key . equals ( CPListElement . INCLUSION ) ) { value = new Path [ ] ; } attrib . getParent ( ) . setAttribute ( key , value ) ; selElements . remove ( i ) ; } } if ( selElements . isEmpty ( ) ) { fFoldersList . refresh ( ) ; fClassPathList . dialogFieldChanged ( ) ; } else { for ( Iterator iter = selElements . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement element = ( CPListElement ) iter . next ( ) ; if ( element . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { List list = LoadpathModifier . removeFilters ( element . getPath ( ) , fCurrJProject , fFoldersList . getElements ( ) ) ; for ( Iterator iterator = list . iterator ( ) ; iterator . hasNext ( ) ; ) { CPListElement modified = ( CPListElement ) iterator . next ( ) ; fFoldersList . refresh ( modified ) ; fFoldersList . expandElement ( modified , ) ; } } } fFoldersList . removeElements ( selElements ) ; } } private boolean canRemove ( List selElements ) { if ( selElements . size ( ) == ) { return false ; } for ( int i = ; i < selElements . size ( ) ; i ++ ) { Object elem = selElements . get ( i ) ; if ( elem instanceof CPListElementAttribute ) { CPListElementAttribute attrib = ( CPListElementAttribute ) elem ; String key = attrib . getKey ( ) ; if ( CPListElement . INCLUSION . equals ( key ) ) { if ( ( ( IPath [ ] ) attrib . getValue ( ) ) . length == ) { return false ; } } else if ( CPListElement . EXCLUSION . equals ( key ) ) { if ( ( ( IPath [ ] ) attrib . getValue ( ) ) . length == ) { return false ; } } else if ( attrib . getValue ( ) == null ) { return false ; } } else if ( elem instanceof CPListElement ) { CPListElement curr = ( CPListElement ) elem ; if ( curr . getParentContainer ( ) != null ) { return false ; } } } return true ; } private boolean canEdit ( List selElements ) { if ( selElements . size ( ) != ) { return false ; } Object elem = selElements . get ( ) ; if ( elem instanceof CPListElement ) { CPListElement cp = ( ( CPListElement ) elem ) ; if ( cp . getPath ( ) . equals ( cp . getRubyProject ( ) . getPath ( ) ) ) return false ; return true ; } if ( elem instanceof CPListElementAttribute ) { return true ; } return false ; } private void sourcePageDialogFieldChanged ( DialogField field ) { if ( fCurrJProject == null ) { return ; } if ( field == fFoldersList ) { updateLoadpathList ( ) ; } } private void updateLoadpathList ( ) { List srcelements = fFoldersList . getElements ( ) ; List cpelements = fClassPathList . getElements ( ) ; int nEntries = cpelements . size ( ) ; int lastRemovePos = nEntries ; int afterLastSourcePos = ; for ( int i = nEntries - ; i >= ; i -- ) { CPListElement cpe = ( CPListElement ) cpelements . get ( i ) ; int kind = cpe . getEntryKind ( ) ; if ( isEntryKind ( kind ) ) { if ( ! srcelements . remove ( cpe ) ) { cpelements . remove ( i ) ; lastRemovePos = i ; } else if ( lastRemovePos == nEntries ) { afterLastSourcePos = i + ; } } } if ( ! srcelements . isEmpty ( ) ) { int insertPos = Math . min ( afterLastSourcePos , lastRemovePos ) ; cpelements . addAll ( insertPos , srcelements ) ; } if ( lastRemovePos != nEntries || ! srcelements . isEmpty ( ) ) { fClassPathList . setElements ( cpelements ) ; } } public List getSelection ( ) { return fFoldersList . getSelectedElements ( ) ; } public void setSelection ( List selElements , boolean expand ) { fFoldersList . selectElements ( new StructuredSelection ( selElements ) ) ; if ( expand ) { for ( int i = ; i < selElements . size ( ) ; i ++ ) { fFoldersList . expandElement ( selElements . get ( i ) , ) ; } } } public boolean isEntryKind ( int kind ) { return kind == ILoadpathEntry . CPE_SOURCE ; } private void refresh ( List insertedElements , List removedElements , List modifiedElements ) { fFoldersList . addElements ( insertedElements ) ; for ( Iterator iter = insertedElements . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement element = ( CPListElement ) iter . next ( ) ; fFoldersList . expandElement ( element , ) ; } fFoldersList . removeElements ( removedElements ) ; for ( Iterator iter = modifiedElements . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement element = ( CPListElement ) iter . next ( ) ; fFoldersList . refresh ( element ) ; fFoldersList . expandElement ( element , ) ; } fFoldersList . refresh ( ) ; if ( ! insertedElements . isEmpty ( ) ) { fFoldersList . postSetSelection ( new StructuredSelection ( insertedElements ) ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . util . Assert ; public class CPVariableElement { private String fName ; private IPath [ ] fPath ; private boolean fIsReserved ; public CPVariableElement ( String name , IPath [ ] path , boolean reserved ) { Assert . isNotNull ( name ) ; Assert . isNotNull ( path ) ; fName = name ; fPath = path ; fIsReserved = reserved ; } public IPath [ ] getPath ( ) { return fPath ; } public void setPath ( IPath [ ] path ) { fPath = path ; } public String getName ( ) { return fName ; } public void setName ( String name ) { fName = name ; } public boolean equals ( Object other ) { if ( other != null && other . getClass ( ) . equals ( getClass ( ) ) ) { CPVariableElement elem = ( CPVariableElement ) other ; return fName . equals ( elem . fName ) ; } return false ; } public int hashCode ( ) { return fName . hashCode ( ) ; } public boolean isReserved ( ) { return fIsReserved ; } public void setReserved ( boolean isReserved ) { fIsReserved = isReserved ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . ui . RubyUI ; public class BuildPathSupport { public static final String JRE_PREF_PAGE_ID = "" ; private BuildPathSupport ( ) { super ( ) ; } private static class UpdatedLoadpathContainer implements ILoadpathContainer { private ILoadpathEntry [ ] fNewEntries ; private ILoadpathContainer fOriginal ; public UpdatedLoadpathContainer ( ILoadpathContainer original , ILoadpathEntry [ ] newEntries ) { fNewEntries = newEntries ; fOriginal = original ; } public ILoadpathEntry [ ] getLoadpathEntries ( ) { return fNewEntries ; } public String getDescription ( ) { return fOriginal . getDescription ( ) ; } public int getKind ( ) { return fOriginal . getKind ( ) ; } public IPath getPath ( ) { return fOriginal . getPath ( ) ; } } public static void modifyLoadpathEntry ( Shell shell , ILoadpathEntry newEntry , String [ ] changedAttributes , IRubyProject jproject , IPath containerPath , IProgressMonitor monitor ) throws CoreException { if ( containerPath != null ) { updateContainerLoadpath ( jproject , containerPath , newEntry , changedAttributes , monitor ) ; } else { updateProjectLoadpath ( shell , jproject , newEntry , changedAttributes , monitor ) ; } } public static void modifyLoadpathEntry ( Shell shell , ILoadpathEntry newEntry , IRubyProject jproject , IPath containerPath , IProgressMonitor monitor ) throws CoreException { modifyLoadpathEntry ( shell , newEntry , null , jproject , containerPath , monitor ) ; } private static void updateContainerLoadpath ( IRubyProject jproject , IPath containerPath , ILoadpathEntry newEntry , String [ ] changedAttributes , IProgressMonitor monitor ) throws CoreException { ILoadpathContainer container = RubyCore . getLoadpathContainer ( containerPath , jproject ) ; if ( container == null ) { throw new CoreException ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . ERROR , "" + containerPath + "" , null ) ) ; } ILoadpathEntry [ ] entries = container . getLoadpathEntries ( ) ; ILoadpathEntry [ ] newEntries = new ILoadpathEntry [ entries . length ] ; for ( int i = ; i < entries . length ; i ++ ) { ILoadpathEntry curr = entries [ i ] ; if ( curr . getEntryKind ( ) == newEntry . getEntryKind ( ) && curr . getPath ( ) . equals ( newEntry . getPath ( ) ) ) { newEntries [ i ] = getUpdatedEntry ( curr , newEntry , changedAttributes , jproject ) ; } else { newEntries [ i ] = curr ; } } requestContainerUpdate ( jproject , container , newEntries ) ; monitor . worked ( ) ; } private static ILoadpathEntry getUpdatedEntry ( ILoadpathEntry currEntry , ILoadpathEntry updatedEntry , String [ ] updatedAttributes , IRubyProject jproject ) { if ( updatedAttributes == null ) { return updatedEntry ; } CPListElement currElem = CPListElement . createFromExisting ( currEntry , jproject ) ; CPListElement newElem = CPListElement . createFromExisting ( updatedEntry , jproject ) ; for ( int i = ; i < updatedAttributes . length ; i ++ ) { String attrib = updatedAttributes [ i ] ; currElem . setAttribute ( attrib , newElem . getAttribute ( attrib ) ) ; } return currElem . getLoadpathEntry ( ) ; } public static void requestContainerUpdate ( IRubyProject jproject , ILoadpathContainer container , ILoadpathEntry [ ] newEntries ) throws CoreException { IPath containerPath = container . getPath ( ) ; ILoadpathContainer updatedContainer = new UpdatedLoadpathContainer ( container , newEntries ) ; LoadpathContainerInitializer initializer = RubyCore . getLoadpathContainerInitializer ( containerPath . segment ( ) ) ; if ( initializer != null ) { initializer . requestLoadpathContainerUpdate ( containerPath , jproject , updatedContainer ) ; } } private static void updateProjectLoadpath ( Shell shell , IRubyProject jproject , ILoadpathEntry newEntry , String [ ] changedAttributes , IProgressMonitor monitor ) throws RubyModelException { ILoadpathEntry [ ] oldLoadpath = jproject . getRawLoadpath ( ) ; int nEntries = oldLoadpath . length ; ArrayList newEntries = new ArrayList ( nEntries + ) ; int entryKind = newEntry . getEntryKind ( ) ; IPath jarPath = newEntry . getPath ( ) ; boolean found = false ; for ( int i = ; i < nEntries ; i ++ ) { ILoadpathEntry curr = oldLoadpath [ i ] ; if ( curr . getEntryKind ( ) == entryKind && curr . getPath ( ) . equals ( jarPath ) ) { newEntries . add ( getUpdatedEntry ( curr , newEntry , changedAttributes , jproject ) ) ; found = true ; } else { newEntries . add ( curr ) ; } } if ( ! found ) { if ( ! putJarOnLoadpathDialog ( shell ) ) { return ; } newEntries . add ( newEntry ) ; } ILoadpathEntry [ ] newLoadpath = ( ILoadpathEntry [ ] ) newEntries . toArray ( new ILoadpathEntry [ newEntries . size ( ) ] ) ; jproject . setRawLoadpath ( newLoadpath , monitor ) ; } private static boolean putJarOnLoadpathDialog ( final Shell shell ) { if ( shell == null ) { return false ; } final boolean [ ] result = new boolean [ ] ; shell . getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { String title = NewWizardMessages . BuildPathSupport_putoncpdialog_title ; String message = NewWizardMessages . BuildPathSupport_putoncpdialog_message ; result [ ] = MessageDialog . openQuestion ( shell , title , message ) ; } } ) ; return result [ ] ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; public class NewVariableEntryDialog extends StatusDialog { private class VariablesAdapter implements IDialogFieldListener , IListAdapter { public void customButtonPressed ( ListDialogField field , int index ) { switch ( index ) { case IDX_EXTEND : extendButtonPressed ( ) ; break ; } } public void selectionChanged ( ListDialogField field ) { doSelectionChanged ( ) ; } public void doubleClicked ( ListDialogField field ) { doDoubleClick ( ) ; } public void dialogFieldChanged ( DialogField field ) { if ( field == fConfigButton ) { configButtonPressed ( ) ; } } } private final int IDX_EXTEND = ; private ListDialogField fVariablesList ; private boolean fCanExtend ; private boolean fIsValidSelection ; private IPath [ ] fResultPaths ; private SelectionButtonDialogField fConfigButton ; public NewVariableEntryDialog ( Shell parent ) { super ( parent ) ; setTitle ( NewWizardMessages . NewVariableEntryDialog_title ) ; int shellStyle = getShellStyle ( ) ; setShellStyle ( shellStyle | SWT . MAX | SWT . RESIZE ) ; updateStatus ( new StatusInfo ( IStatus . ERROR , "" ) ) ; String [ ] buttonLabels = new String [ ] { NewWizardMessages . NewVariableEntryDialog_vars_extend , } ; VariablesAdapter adapter = new VariablesAdapter ( ) ; CPVariableElementLabelProvider labelProvider = new CPVariableElementLabelProvider ( false ) ; fVariablesList = new ListDialogField ( adapter , buttonLabels , labelProvider ) ; fVariablesList . setDialogFieldListener ( adapter ) ; fVariablesList . setLabelText ( NewWizardMessages . NewVariableEntryDialog_vars_label ) ; fVariablesList . enableButton ( IDX_EXTEND , false ) ; fVariablesList . setViewerSorter ( new ViewerSorter ( ) { public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( e1 instanceof CPVariableElement && e2 instanceof CPVariableElement ) { return ( ( CPVariableElement ) e1 ) . getName ( ) . compareTo ( ( ( CPVariableElement ) e2 ) . getName ( ) ) ; } return super . compare ( viewer , e1 , e2 ) ; } } ) ; fConfigButton = new SelectionButtonDialogField ( SWT . PUSH ) ; fConfigButton . setLabelText ( NewWizardMessages . NewVariableEntryDialog_configbutton_label ) ; fConfigButton . setDialogFieldListener ( adapter ) ; initializeElements ( ) ; fCanExtend = false ; fIsValidSelection = false ; fResultPaths = null ; } private void initializeElements ( ) { String [ ] entries = RubyCore . getLoadpathVariableNames ( ) ; ArrayList elements = new ArrayList ( entries . length ) ; for ( int i = ; i < entries . length ; i ++ ) { String name = entries [ i ] ; IPath [ ] entryPath = RubyCore . getLoadpathVariable ( name ) ; if ( entryPath != null ) { elements . add ( new CPVariableElement ( name , entryPath , false ) ) ; } } fVariablesList . setElements ( elements ) ; } protected void configureShell ( Shell shell ) { super . configureShell ( shell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( shell , IRubyHelpContextIds . NEW_VARIABLE_ENTRY_DIALOG ) ; } protected IDialogSettings getDialogBoundsSettings ( ) { return RubyPlugin . getDefault ( ) . getDialogSettingsSection ( getClass ( ) . getName ( ) ) ; } protected Control createDialogArea ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = ( Composite ) super . createDialogArea ( parent ) ; GridLayout layout = ( GridLayout ) composite . getLayout ( ) ; layout . numColumns = ; fVariablesList . doFillIntoGrid ( composite , ) ; LayoutUtil . setHorizontalSpan ( fVariablesList . getLabelControl ( null ) , ) ; GridData listData = ( GridData ) fVariablesList . getListControl ( null ) . getLayoutData ( ) ; listData . grabExcessHorizontalSpace = true ; listData . heightHint = convertHeightInCharsToPixels ( ) ; listData . widthHint = convertWidthInCharsToPixels ( ) ; Composite lowerComposite = new Composite ( composite , SWT . NONE ) ; lowerComposite . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ) ; layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; lowerComposite . setLayout ( layout ) ; fConfigButton . doFillIntoGrid ( lowerComposite , ) ; applyDialogFont ( composite ) ; return composite ; } public IPath [ ] getResult ( ) { return fResultPaths ; } private void doDoubleClick ( ) { if ( fIsValidSelection ) { okPressed ( ) ; } else if ( fCanExtend ) { extendButtonPressed ( ) ; } } private void doSelectionChanged ( ) { boolean isValidSelection = true ; boolean canExtend = false ; StatusInfo status = new StatusInfo ( ) ; List selected = fVariablesList . getSelectedElements ( ) ; int nSelected = selected . size ( ) ; if ( nSelected > ) { fResultPaths = new Path [ nSelected ] ; for ( int i = ; i < nSelected ; i ++ ) { CPVariableElement curr = ( CPVariableElement ) selected . get ( i ) ; fResultPaths [ i ] = new Path ( curr . getName ( ) ) ; File file = curr . getPath ( ) [ ] . toFile ( ) ; if ( ! file . exists ( ) ) { status . setError ( NewWizardMessages . NewVariableEntryDialog_info_notexists ) ; isValidSelection = false ; break ; } if ( file . isDirectory ( ) ) { status . setError ( NewWizardMessages . NewVariableEntryDialog_info_isfolder ) ; canExtend = true ; isValidSelection = false ; break ; } } } else { isValidSelection = false ; status . setInfo ( NewWizardMessages . NewVariableEntryDialog_info_noselection ) ; } if ( isValidSelection && nSelected > ) { String str = Messages . format ( NewWizardMessages . NewVariableEntryDialog_info_selected , String . valueOf ( nSelected ) ) ; status . setInfo ( str ) ; } fCanExtend = nSelected == && canExtend ; fVariablesList . enableButton ( , fCanExtend ) ; updateStatus ( status ) ; fIsValidSelection = isValidSelection ; Button okButton = getButton ( IDialogConstants . OK_ID ) ; if ( okButton != null && ! okButton . isDisposed ( ) ) { okButton . setEnabled ( isValidSelection ) ; } } private IPath [ ] chooseExtensions ( CPVariableElement elem ) { File file = elem . getPath ( ) [ ] . toFile ( ) ; DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) , SWT . OPEN ) ; dialog . setText ( NewWizardMessages . NewVariableEntryDialog_ExtensionDialog_title ) ; dialog . setMessage ( Messages . format ( NewWizardMessages . NewVariableEntryDialog_ExtensionDialog_description , elem . getName ( ) ) ) ; dialog . setFilterPath ( file . toString ( ) ) ; String filename = null ; if ( ( filename = dialog . open ( ) ) != null ) { File myFile = new File ( filename ) ; IPath filePath = Path . fromOSString ( myFile . getPath ( ) ) ; IPath resPath = new Path ( elem . getName ( ) ) ; for ( int k = elem . getPath ( ) [ ] . segmentCount ( ) ; k < filePath . segmentCount ( ) ; k ++ ) { resPath = resPath . append ( filePath . segment ( k ) ) ; } return new IPath [ ] { resPath } ; } return null ; } protected final void extendButtonPressed ( ) { List selected = fVariablesList . getSelectedElements ( ) ; if ( selected . size ( ) == ) { IPath [ ] extendedPaths = chooseExtensions ( ( CPVariableElement ) selected . get ( ) ) ; if ( extendedPaths != null ) { fResultPaths = extendedPaths ; super . buttonPressed ( IDialogConstants . OK_ID ) ; } } } protected final void configButtonPressed ( ) { initializeElements ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . IPath ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; public abstract class BuildPathBasePage { public abstract List getSelection ( ) ; public abstract void setSelection ( List selection , boolean expand ) ; public void addElement ( CPListElement element ) { } public abstract boolean isEntryKind ( int kind ) ; protected void filterAndSetSelection ( List list ) { ArrayList res = new ArrayList ( list . size ( ) ) ; for ( int i = list . size ( ) - ; i >= ; i -- ) { Object curr = list . get ( i ) ; if ( curr instanceof CPListElement ) { CPListElement elem = ( CPListElement ) curr ; if ( elem . getParentContainer ( ) == null && isEntryKind ( elem . getEntryKind ( ) ) ) { res . add ( curr ) ; } } } setSelection ( res , false ) ; } public static void fixNestingConflicts ( CPListElement [ ] newEntries , CPListElement [ ] existing , Set modifiedSourceEntries ) { for ( int i = ; i < newEntries . length ; i ++ ) { addExclusionPatterns ( newEntries [ i ] , existing , modifiedSourceEntries ) ; } } private static void addExclusionPatterns ( CPListElement newEntry , CPListElement [ ] existing , Set modifiedEntries ) { IPath entryPath = newEntry . getPath ( ) ; for ( int i = ; i < existing . length ; i ++ ) { CPListElement curr = existing [ i ] ; if ( curr . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { IPath currPath = curr . getPath ( ) ; if ( ! currPath . equals ( entryPath ) ) { if ( currPath . isPrefixOf ( entryPath ) ) { if ( addToExclusions ( entryPath , curr ) ) { modifiedEntries . add ( curr ) ; } } else if ( entryPath . isPrefixOf ( currPath ) ) { if ( addToExclusions ( currPath , newEntry ) ) { modifiedEntries . add ( curr ) ; } } } } } } private static boolean addToExclusions ( IPath entryPath , CPListElement curr ) { IPath [ ] exclusionFilters = ( IPath [ ] ) curr . getAttribute ( CPListElement . EXCLUSION ) ; if ( ! RubyModelUtil . isExcludedPath ( entryPath , exclusionFilters ) ) { IPath pathToExclude = entryPath . removeFirstSegments ( curr . getPath ( ) . segmentCount ( ) ) . addTrailingSeparator ( ) ; IPath [ ] newExclusionFilters = new IPath [ exclusionFilters . length + ] ; System . arraycopy ( exclusionFilters , , newExclusionFilters , , exclusionFilters . length ) ; newExclusionFilters [ exclusionFilters . length ] = pathToExclude ; curr . setAttribute ( CPListElement . EXCLUSION , newExclusionFilters ) ; return true ; } return false ; } protected boolean containsOnlyTopLevelEntries ( List selElements ) { if ( selElements . size ( ) == ) { return true ; } for ( int i = ; i < selElements . size ( ) ; i ++ ) { Object elem = selElements . get ( i ) ; if ( elem instanceof CPListElement ) { if ( ( ( CPListElement ) elem ) . getParentContainer ( ) != null ) { return false ; } } else { return false ; } } return true ; } public abstract void init ( IRubyProject rubyProject ) ; public abstract Control getControl ( Composite parent ) ; } package org . rubypeople . rdt . internal . ui . wizards . buildpaths ; import java . io . File ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CLabel ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; public class EditVariableEntryDialog extends StatusDialog { private IPath fFileVariablePath ; private IStatus fNameStatus ; private Set fExistingEntries ; private VariablePathDialogField fFileNameField ; private CLabel fFullPathResolvedLabel ; public EditVariableEntryDialog ( Shell parent , IPath initialEntry , IPath [ ] existingEntries ) { super ( parent ) ; setTitle ( NewWizardMessages . EditVariableEntryDialog_title ) ; fExistingEntries = new HashSet ( ) ; if ( existingEntries != null ) { for ( int i = ; i < existingEntries . length ; i ++ ) { IPath curr = existingEntries [ i ] ; if ( ! curr . equals ( initialEntry ) ) { fExistingEntries . add ( curr ) ; } } } SourceAttachmentAdapter adapter = new SourceAttachmentAdapter ( ) ; fFileNameField = new VariablePathDialogField ( adapter ) ; fFileNameField . setDialogFieldListener ( adapter ) ; fFileNameField . setLabelText ( NewWizardMessages . EditVariableEntryDialog_filename_varlabel ) ; fFileNameField . setButtonLabel ( NewWizardMessages . EditVariableEntryDialog_filename_external_varbutton ) ; fFileNameField . setVariableButtonLabel ( NewWizardMessages . EditVariableEntryDialog_filename_variable_button ) ; String initialString = initialEntry != null ? initialEntry . toString ( ) : "" ; fFileNameField . setText ( initialString ) ; } public IPath getPath ( ) { return Path . fromOSString ( fFileNameField . getText ( ) ) ; } protected Control createDialogArea ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = ( Composite ) super . createDialogArea ( parent ) ; GridLayout layout = ( GridLayout ) composite . getLayout ( ) ; layout . numColumns = ; int widthHint = convertWidthInCharsToPixels ( ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; fFileNameField . doFillIntoGrid ( composite , ) ; LayoutUtil . setHorizontalSpan ( fFileNameField . getLabelControl ( null ) , ) ; LayoutUtil . setWidthHint ( fFileNameField . getTextControl ( null ) , widthHint ) ; LayoutUtil . setHorizontalGrabbing ( fFileNameField . getTextControl ( null ) ) ; fFullPathResolvedLabel = new CLabel ( composite , SWT . LEFT ) ; fFullPathResolvedLabel . setText ( getResolvedLabelString ( ) ) ; fFullPathResolvedLabel . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ) ; DialogField . createEmptySpace ( composite , ) ; fFileNameField . postSetFocusOnDialogField ( parent . getDisplay ( ) ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( composite , IRubyHelpContextIds . SOURCE_ATTACHMENT_BLOCK ) ; applyDialogFont ( composite ) ; return composite ; } private class SourceAttachmentAdapter implements IStringButtonAdapter , IDialogFieldListener { public void changeControlPressed ( DialogField field ) { attachmentChangeControlPressed ( field ) ; } public void dialogFieldChanged ( DialogField field ) { attachmentDialogFieldChanged ( field ) ; } } private void attachmentChangeControlPressed ( DialogField field ) { } private void attachmentDialogFieldChanged ( DialogField field ) { if ( field == fFileNameField ) { fNameStatus = updateFileNameStatus ( ) ; } doStatusLineUpdate ( ) ; } private IPath getResolvedPath ( IPath path ) { if ( path != null ) { String varName = path . segment ( ) ; if ( varName != null ) { IPath varPath = RubyCore . getLoadpathVariable ( varName ) [ ] ; if ( varPath != null ) { return varPath . append ( path . removeFirstSegments ( ) ) ; } } } return null ; } private IPath modifyPath ( IPath path , String varName ) { if ( varName == null || path == null ) { return null ; } if ( path . isEmpty ( ) ) { return new Path ( varName ) ; } IPath varPath = RubyCore . getLoadpathVariable ( varName ) [ ] ; if ( varPath != null ) { if ( varPath . isPrefixOf ( path ) ) { path = path . removeFirstSegments ( varPath . segmentCount ( ) ) ; } else { path = new Path ( path . lastSegment ( ) ) ; } } else { path = new Path ( path . lastSegment ( ) ) ; } return new Path ( varName ) . append ( path ) ; } private IStatus updateFileNameStatus ( ) { StatusInfo status = new StatusInfo ( ) ; fFileVariablePath = null ; String fileName = fFileNameField . getText ( ) ; if ( fileName . length ( ) == ) { status . setError ( NewWizardMessages . EditVariableEntryDialog_filename_empty ) ; return status ; } else { if ( ! Path . EMPTY . isValidPath ( fileName ) ) { status . setError ( NewWizardMessages . EditVariableEntryDialog_filename_error_notvalid ) ; return status ; } IPath filePath = Path . fromOSString ( fileName ) ; IPath resolvedPath ; if ( filePath . getDevice ( ) != null ) { status . setError ( NewWizardMessages . EditVariableEntryDialog_filename_error_deviceinpath ) ; return status ; } String varName = filePath . segment ( ) ; if ( varName == null ) { status . setError ( NewWizardMessages . EditVariableEntryDialog_filename_error_notvalid ) ; return status ; } fFileVariablePath = RubyCore . getLoadpathVariable ( varName ) [ ] ; if ( fFileVariablePath == null ) { status . setError ( NewWizardMessages . EditVariableEntryDialog_filename_error_varnotexists ) ; return status ; } resolvedPath = fFileVariablePath . append ( filePath . removeFirstSegments ( ) ) ; if ( resolvedPath . isEmpty ( ) ) { status . setWarning ( NewWizardMessages . EditVariableEntryDialog_filename_warning_varempty ) ; return status ; } File file = resolvedPath . toFile ( ) ; if ( ! file . isDirectory ( ) ) { String message = Messages . format ( NewWizardMessages . EditVariableEntryDialog_filename_error_filenotexists , resolvedPath . toOSString ( ) ) ; status . setInfo ( message ) ; return status ; } } return status ; } private String getResolvedLabelString ( ) { IPath resolvedPath = getResolvedPath ( getPath ( ) ) ; if ( resolvedPath != null ) { return resolvedPath . toOSString ( ) ; } return "" ; } private boolean canBrowseFileName ( ) { if ( fFileVariablePath != null ) { return fFileVariablePath . toFile ( ) . isDirectory ( ) ; } return false ; } private void doStatusLineUpdate ( ) { fFileNameField . enableButton ( canBrowseFileName ( ) ) ; if ( fFullPathResolvedLabel != null ) { fFullPathResolvedLabel . setText ( getResolvedLabelString ( ) ) ; } IStatus status = fNameStatus ; if ( ! status . matches ( IStatus . ERROR ) ) { IPath path = getPath ( ) ; if ( fExistingEntries . contains ( path ) ) { String message = NewWizardMessages . EditVariableEntryDialog_filename_error_alreadyexists ; status = new StatusInfo ( IStatus . ERROR , message ) ; } } updateStatus ( status ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import java . util . List ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . corext . util . TypeInfo ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . TypeSelectionDialog2 ; import org . rubypeople . rdt . ui . wizards . NewTypeWizardPage ; public class SuperModuleSelectionDialog extends TypeSelectionDialog2 { private static final int ADD_ID = IDialogConstants . CLIENT_ID + ; private NewTypeWizardPage fTypeWizardPage ; private List fOldContent ; public SuperModuleSelectionDialog ( Shell parent , IRunnableContext context , NewTypeWizardPage page , IRubyProject p ) { super ( parent , true , context , createSearchScope ( p ) , IRubySearchConstants . MODULE ) ; fTypeWizardPage = page ; fOldContent = fTypeWizardPage . getSuperModules ( ) ; setStatusLineAboveButtons ( true ) ; } protected void createButtonsForButtonBar ( Composite parent ) { createButton ( parent , ADD_ID , NewWizardMessages . SuperModuleSelectionDialog_addButton_label , true ) ; super . createButtonsForButtonBar ( parent ) ; } protected IDialogSettings getDialogBoundsSettings ( ) { return RubyPlugin . getDefault ( ) . getDialogSettingsSection ( "" ) ; } protected void updateButtonsEnableState ( IStatus status ) { super . updateButtonsEnableState ( status ) ; Button addButton = getButton ( ADD_ID ) ; if ( addButton != null && ! addButton . isDisposed ( ) ) addButton . setEnabled ( ! status . matches ( IStatus . ERROR ) ) ; } protected void handleShellCloseEvent ( ) { super . handleShellCloseEvent ( ) ; fTypeWizardPage . setSuperModules ( fOldContent , true ) ; } protected void cancelPressed ( ) { fTypeWizardPage . setSuperModules ( fOldContent , true ) ; super . cancelPressed ( ) ; } protected void buttonPressed ( int buttonId ) { if ( buttonId == ADD_ID ) { addSelectedInterface ( ) ; } super . buttonPressed ( buttonId ) ; } protected void okPressed ( ) { addSelectedInterface ( ) ; super . okPressed ( ) ; } private void addSelectedInterface ( ) { TypeInfo [ ] selection = getSelectedTypes ( ) ; if ( selection == null ) return ; for ( int i = ; i < selection . length ; i ++ ) { TypeInfo type = selection [ i ] ; String qualifiedName = type . getFullyQualifiedName ( ) ; String message ; if ( fTypeWizardPage . addSuperModule ( qualifiedName ) ) { message = Messages . format ( NewWizardMessages . SuperModuleSelectionDialog_interfaceadded_info , qualifiedName ) ; } else { message = Messages . format ( NewWizardMessages . SuperModuleSelectionDialog_interfacealreadyadded_info , qualifiedName ) ; } updateStatus ( new StatusInfo ( IStatus . INFO , message ) ) ; } } private static IRubySearchScope createSearchScope ( IRubyProject p ) { return SearchEngine . createRubySearchScope ( new IRubyProject [ ] { p } ) ; } protected void handleDefaultSelected ( TypeInfo [ ] selection ) { if ( selection . length > ) buttonPressed ( ADD_ID ) ; } protected void handleWidgetSelected ( TypeInfo [ ] selection ) { super . handleWidgetSelected ( selection ) ; getButton ( ADD_ID ) . setEnabled ( selection . length > ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . SUPER_INTERFACE_SELECTION_DIALOG ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . ui . actions . AbstractOpenWizardAction ; public class OpenNewRubyProjectWizardAction extends AbstractOpenWizardAction { public OpenNewRubyProjectWizardAction ( ) { setText ( ActionMessages . OpenNewRubyProjectWizardAction_text ) ; setDescription ( ActionMessages . OpenNewRubyProjectWizardAction_description ) ; setToolTipText ( ActionMessages . OpenNewRubyProjectWizardAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_WIZBAN_NEWJPRJ ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . OPEN_PROJECT_WIZARD_ACTION ) ; setShell ( RubyPlugin . getActiveWorkbenchShell ( ) ) ; } protected final INewWizard createWizard ( ) throws CoreException { return new RubyProjectWizard ( ) ; } protected boolean doCreateProjectFirstOnEmptyWorkspace ( Shell shell ) { return true ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; public class OpenRubyProjectWizardToolbarAction extends OpenNewRubyProjectWizardAction implements IWorkbenchWindowActionDelegate { public OpenRubyProjectWizardToolbarAction ( ) { } public void dispose ( ) { } public void init ( IWorkbenchWindow window ) { setShell ( window . getShell ( ) ) ; } public void run ( IAction action ) { super . run ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { if ( selection instanceof IStructuredSelection ) { setSelection ( ( IStructuredSelection ) selection ) ; } else { setSelection ( StructuredSelection . EMPTY ) ; } } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . core . runtime . IStatus ; public interface IStatusChangeListener { void statusChanged ( IStatus status ) ; } package org . rubypeople . rdt . internal . ui . wizards ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . wizard . Wizard ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . wizards . newresource . BasicNewResourceWizard ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . WorkbenchRunnableAdapter ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public abstract class NewElementWizard extends Wizard implements INewWizard { private IWorkbench fWorkbench ; private IStructuredSelection fSelection ; public NewElementWizard ( ) { setNeedsProgressMonitor ( true ) ; } protected void openResource ( final IFile resource ) { final IWorkbenchPage activePage = RubyPlugin . getActivePage ( ) ; if ( activePage != null ) { final Display display = getShell ( ) . getDisplay ( ) ; if ( display != null ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { try { IDE . openEditor ( activePage , resource , true ) ; } catch ( PartInitException e ) { RubyPlugin . log ( e ) ; } } } ) ; } } } protected abstract void finishPage ( IProgressMonitor monitor ) throws InterruptedException , CoreException ; protected ISchedulingRule getSchedulingRule ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; } protected boolean canRunForked ( ) { return true ; } public abstract IRubyElement getCreatedElement ( ) ; protected void handleFinishException ( Shell shell , InvocationTargetException e ) { String title = NewWizardMessages . NewElementWizard_op_error_title ; String message = NewWizardMessages . NewElementWizard_op_error_message ; ExceptionHandler . handle ( e , shell , title , message ) ; } public boolean performFinish ( ) { IWorkspaceRunnable op = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException , OperationCanceledException { try { finishPage ( monitor ) ; } catch ( InterruptedException e ) { throw new OperationCanceledException ( e . getMessage ( ) ) ; } } } ; try { ISchedulingRule rule = null ; Job job = Platform . getJobManager ( ) . currentJob ( ) ; if ( job != null ) rule = job . getRule ( ) ; IRunnableWithProgress runnable = null ; if ( rule != null ) runnable = new WorkbenchRunnableAdapter ( op , rule , true ) ; else runnable = new WorkbenchRunnableAdapter ( op , getSchedulingRule ( ) ) ; getContainer ( ) . run ( canRunForked ( ) , true , runnable ) ; } catch ( InvocationTargetException e ) { handleFinishException ( getShell ( ) , e ) ; return false ; } catch ( InterruptedException e ) { return false ; } return true ; } public void init ( IWorkbench workbench , IStructuredSelection currentSelection ) { fWorkbench = workbench ; fSelection = currentSelection ; } public IStructuredSelection getSelection ( ) { return fSelection ; } public IWorkbench getWorkbench ( ) { return fWorkbench ; } protected void selectAndReveal ( IResource newResource ) { BasicNewResourceWizard . selectAndReveal ( newResource , fWorkbench . getActiveWorkbenchWindow ( ) ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import java . net . MalformedURLException ; import java . net . URL ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . jface . wizard . Wizard ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . browser . IWebBrowser ; import org . eclipse . ui . browser . IWorkbenchBrowserSupport ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import org . rubypeople . rdt . internal . ui . RubyInstalledDetector ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class InstallStandardRubyWizard extends Wizard implements INewWizard { private static final String WINDOWS_INSTALL_URL = "" ; private static final String LINUX_INSTALL_URL = "" ; private static final String MACOSX_INSTALL_URL = "" ; private static final String RUBY_BROWSER_ID = RubyPlugin . getPluginId ( ) + "" ; public InstallStandardRubyWizard ( ) { setWindowTitle ( NewWizardMessages . InstallStandardRubyWizard_TTL_Window ) ; setNeedsProgressMonitor ( true ) ; } @ Override public void addPages ( ) { addPage ( new InstallRubyWizardPage ( ) ) ; } @ Override public boolean performFinish ( ) { IWizardPage page = getContainer ( ) . getCurrentPage ( ) ; if ( page instanceof InstallRubyWizardPage && ( ( InstallRubyWizardPage ) page ) . downloadSelected ( ) ) { openBrowser ( getURL ( ) ) ; } else if ( page instanceof BrowseToInstalledRubyWizardPage ) { ( ( BrowseToInstalledRubyWizardPage ) page ) . addVM ( ) ; } else if ( page instanceof UseJRubyWizardPage ) { Preferences store = LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) ; if ( store != null ) store . setValue ( LaunchingPlugin . USING_INCLUDED_JRUBY , true ) ; } return true ; } @ Override public void dispose ( ) { RubyInstalledDetector . markFinished ( ) ; super . dispose ( ) ; } public void init ( IWorkbench workbench , IStructuredSelection selection ) { } private String getURL ( ) { if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) return WINDOWS_INSTALL_URL ; if ( Platform . getOS ( ) . equals ( Platform . OS_MACOSX ) ) return MACOSX_INSTALL_URL ; return LINUX_INSTALL_URL ; } private void openBrowser ( String url ) { try { IWorkbenchBrowserSupport support = PlatformUI . getWorkbench ( ) . getBrowserSupport ( ) ; IWebBrowser browser = support . createBrowser ( RUBY_BROWSER_ID ) ; browser . openURL ( new URL ( url ) ) ; } catch ( PartInitException e ) { RubyPlugin . log ( e ) ; } catch ( MalformedURLException e ) { RubyPlugin . log ( e ) ; } } @ Override public boolean needsPreviousAndNextButtons ( ) { return true ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . osgi . util . NLS ; public class NewWizardMessages extends NLS { private static final String BUNDLE_NAME = "" ; private NewWizardMessages ( ) { } public static String NewContainerWizardPage_container_label ; public static String NewContainerWizardPage_container_button ; public static String NewContainerWizardPage_ChooseSourceContainerDialog_title ; public static String NewContainerWizardPage_ChooseSourceContainerDialog_description ; public static String NewContainerWizardPage_error_EnterContainerName ; public static String NewContainerWizardPage_error_ProjectClosed ; public static String NewContainerWizardPage_warning_NotARubyProject ; public static String NewContainerWizardPage_warning_NotInARubyProject ; public static String NewContainerWizardPage_error_NotAFolder ; public static String NewContainerWizardPage_error_ContainerDoesNotExist ; public static String NewContainerWizardPage_warning_NotOnLoadPath ; public static String AbstractOpenWizardAction_createerror_message ; public static String AbstractOpenWizardAction_createerror_title ; public static String AbstractOpenWizardAction_noproject_title ; public static String AbstractOpenWizardAction_noproject_message ; public static String NewTypeWizardPage_typename_label ; public static String NewTypeWizardPage_superclass_label ; public static String NewTypeWizardPage_superclass_button ; public static String NewTypeWizardPage_interfaces_add ; public static String NewTypeWizardPage_interfaces_remove ; public static String NewTypeWizardPage_interfaces_class_label ; public static String NewTypeWizardPage_interfaces_ifc_label ; public static String NewTypeWizardPage_configure_templates_title ; public static String NewTypeWizardPage_configure_templates_message ; public static String NewTypeWizardPage_InterfacesDialog_message ; public static String NewTypeWizardPage_InterfacesDialog_interface_title ; public static String NewTypeWizardPage_InterfacesDialog_class_title ; public static String NewTypeWizardPage_error_EnterTypeName ; public static String NewTypeWizardPage_operationdesc ; public static String NewTypeWizardPage_default ; public static String NewTypeWizardPage_package_button ; public static String NewTypeWizardPage_package_label ; public static String NewTypeWizardPage_error_InvalidPackageName ; public static String NewTypeWizardPage_warning_DiscouragedPackageName ; public static String NewTypeWizardPage_ChoosePackageDialog_title ; public static String NewTypeWizardPage_ChoosePackageDialog_description ; public static String NewTypeWizardPage_ChoosePackageDialog_empty ; public static String NewElementWizard_op_error_title ; public static String NewElementWizard_op_error_message ; public static String NewFileCreationWizard_title ; public static String NewFileWizardPage_title ; public static String NewFileWizardPage_description ; public static String NewFileWizardPage_scriptname_label ; public static String NewClassCreationWizard_title ; public static String NewClassWizardPage_title ; public static String NewClassWizardPage_description ; public static String NewClassWizardPage_methods_main ; public static String NewClassWizardPage_methods_constructors ; public static String NewClassWizardPage_methods_label ; public static String BrowseToInstalledRubyWizardPage_ERR_MSG_Location_empty ; public static String BrowseToInstalledRubyWizardPage_ERR_MSG_Unable_find_standard_vm_metadata ; public static String BrowseToInstalledRubyWizardPage_LBL_Browse_button ; public static String BrowseToInstalledRubyWizardPage_LBL_Standard_ruby_entry_name ; public static String BrowseToInstalledRubyWizardPage_MSG_Browse_dialog ; public static String BrowseToInstalledRubyWizardPage_MSG_Description ; public static String BrowseToInstalledRubyWizardPage_MSG_Explanation_text ; public static String BrowseToInstalledRubyWizardPage_TTL ; public static String BuildPathsBlock_operationdesc_java ; public static String CPListLabelProvider_new ; public static String CPListLabelProvider_classcontainer ; public static String CPListLabelProvider_willbecreated ; public static String CPListLabelProvider_non_modifiable_attribute ; public static String CPListLabelProvider_systemlibrary ; public static String CPListLabelProvider_none ; public static String CPListLabelProvider_exclusion_filter_separator ; public static String CPListLabelProvider_exclusion_filter_label ; public static String CPListLabelProvider_inclusion_filter_separator ; public static String CPListLabelProvider_all ; public static String CPListLabelProvider_inclusion_filter_label ; public static String CPListLabelProvider_unbound_library ; public static String CPListLabelProvider_unknown_element_label ; public static String CPListLabelProvider_twopart ; public static String ProjectsWorkbookPage_projects_add_button ; public static String ProjectsWorkbookPage_projects_edit_button ; public static String ProjectsWorkbookPage_projects_remove_button ; public static String ProjectsWorkbookPage_projects_label ; public static String ProjectsWorkbookPage_chooseProjects_message ; public static String ProjectsWorkbookPage_chooseProjects_title ; public static String MultipleFolderSelectionDialog_button ; public static String BuildPathDialogAccess_ExistingSourceFolderDialog_new_description ; public static String BuildPathDialogAccess_ExistingSourceFolderDialog_new_title ; public static String BuildPathDialogAccess_ExistingClassFolderDialog_new_description ; public static String BuildPathDialogAccess_ExistingClassFolderDialog_new_title ; public static String LibrariesWorkbookPage_libraries_label ; public static String LibrariesWorkbookPage_exclusion_added_title ; public static String LibrariesWorkbookPage_exclusion_added_message ; public static String LibrariesWorkbookPage_configurecontainer_error_title ; public static String LibrariesWorkbookPage_configurecontainer_error_message ; public static String LibrariesWorkbookPage_NewClassFolderDialog_new_title ; public static String LibrariesWorkbookPage_NewClassFolderDialog_edit_title ; public static String LibrariesWorkbookPage_NewClassFolderDialog_description ; public static String LibrariesWorkbookPage_libraries_addclassfolder_button ; public static String LibrariesWorkbookPage_libraries_edit_button ; public static String LibrariesWorkbookPage_libraries_remove_button ; public static String BuildPathSupport_putoncpdialog_title ; public static String BuildPathSupport_putoncpdialog_message ; public static String NewContainerDialog_error_enterpath ; public static String NewContainerDialog_error_invalidpath ; public static String NewContainerDialog_error_pathexists ; public static String BuildPathsBlock_classpath_up_button ; public static String BuildPathsBlock_classpath_down_button ; public static String BuildPathsBlock_classpath_checkall_button ; public static String BuildPathsBlock_classpath_uncheckall_button ; public static String BuildPathsBlock_classpath_label ; public static String BuildPathsBlock_buildpath_button ; public static String BuildPathsBlock_buildpath_label ; public static String BuildPathsBlock_tab_source ; public static String BuildPathsBlock_tab_projects ; public static String BuildPathsBlock_tab_libraries ; public static String BuildPathsBlock_tab_order ; public static String BuildPathsBlock_warning_EntryMissing ; public static String BuildPathsBlock_warning_EntriesMissing ; public static String BuildPathsBlock_error_EnterBuildPath ; public static String BuildPathsBlock_error_InvalidBuildPath ; public static String OutputLocation_SettingsAsLocation ; public static String OutputLocation_DotAsLocation ; public static String BuildPathsBlock_operationdesc_project ; public static String BuildPathsBlock_RemoveBinariesDialog_title ; public static String BuildPathsBlock_RemoveBinariesDialog_description ; public static String BuildPathsBlock_ChooseOutputFolderDialog_title ; public static String BuildPathsBlock_ChooseOutputFolderDialog_description ; public static String FolderSelectionDialog_button ; public static String LinkFolderDialog_dependenciesGroup_locationLabel_desc ; public static String LinkFolderDialog_dependenciesGroup_browseButton_desc ; public static String LinkFolderDialog_dependenciesGroup_variables_desc ; public static String RubyProjectWizardFirstPage_directory_message ; public static String NewSourceFolderWizardPage_title ; public static String NewFolderDialog_createIn ; public static String AddSourceFolderWizardPage_description ; public static String NewSourceFolderWizardPage_edit_description ; public static String NewSourceFolderWizardPage_root_label ; public static String NewSourceFolderWizardPage_exclude_label ; public static String NewSourceFolderWizardPage_ReplaceExistingSourceFolder_label ; public static String AddSourceFolderWizardPage_ignoreNestingConflicts ; public static String NewSourceFolderWizardPage_ChooseExistingRootDialog_title ; public static String NewSourceFolderWizardPage_ChooseExistingRootDialog_description ; public static String NewSourceFolderWizardPage_error_AlreadyExisting ; public static String NewFolderDialog_folderNameEmpty_alreadyExists ; public static String NewSourceFolderWizardPage_warning_ReplaceSFandOL ; public static String NewSourceFolderWizardPage_warning_ReplaceOL ; public static String AddSourceFolderWizardPage_conflictWarning ; public static String AddSourceFolderWizardPage_addSinglePattern ; public static String NewSourceFolderWizardPage_warning_AddedExclusions ; public static String AddSourceFolderWizardPage_replaceSourceFolderInfo ; public static String NewFolderDialog_linkTargetNotFolder ; public static String NewFolderDialog_linkTargetNonExistent ; public static String NewSourceFolderWizardPage_error_EnterRootName ; public static String NewSourceFolderWizardPage_error_InvalidRootName ; public static String NewSourceFolderWizardPage_error_NotAFolder ; public static String NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase ; public static String ExclusionInclusionDialog_ChooseExclusionPattern_title ; public static String ExclusionInclusionDialog_ChooseExclusionPattern_description ; public static String ExclusionInclusionDialog_ChooseInclusionPattern_title ; public static String ExclusionInclusionDialog_ChooseInclusionPattern_description ; public static String ExclusionInclusionEntryDialog_pattern_button ; public static String ExclusionInclusionEntryDialog_exclude_description ; public static String ExclusionInclusionEntryDialog_include_description ; public static String ExclusionInclusionEntryDialog_error_empty ; public static String ExclusionInclusionEntryDialog_error_notrelative ; public static String ExclusionInclusionEntryDialog_error_exists ; public static String ExclusionInclusionEntryDialog_ChooseExclusionPattern_title ; public static String ExclusionInclusionEntryDialog_ChooseExclusionPattern_description ; public static String ExclusionInclusionEntryDialog_ChooseInclusionPattern_title ; public static String ExclusionInclusionEntryDialog_ChooseInclusionPattern_description ; public static String ExclusionInclusionEntryDialog_exclude_add_title ; public static String ExclusionInclusionEntryDialog_exclude_edit_title ; public static String ExclusionInclusionEntryDialog_exclude_pattern_label ; public static String ExclusionInclusionEntryDialog_include_add_title ; public static String ExclusionInclusionEntryDialog_include_edit_title ; public static String ExclusionInclusionEntryDialog_include_pattern_label ; public static String ExclusionInclusionDialog_title ; public static String ExclusionInclusionDialog_description2 ; public static String ExclusionInclusionDialog_exclusion_pattern_label ; public static String ExclusionInclusionDialog_exclusion_pattern_add ; public static String ExclusionInclusionDialog_exclusion_pattern_add_multiple ; public static String ExclusionInclusionDialog_exclusion_pattern_edit ; public static String ExclusionInclusionDialog_exclusion_pattern_remove ; public static String ExclusionInclusionDialog_inclusion_pattern_label ; public static String ExclusionInclusionDialog_inclusion_pattern_add ; public static String ExclusionInclusionDialog_inclusion_pattern_add_multiple ; public static String ExclusionInclusionDialog_inclusion_pattern_edit ; public static String ExclusionInclusionDialog_inclusion_pattern_remove ; public static String NewSourceFolderCreationWizard_link_title ; public static String NewSourceFolderCreationWizard_title ; public static String NewSourceFolderCreationWizard_edit_title ; public static String SourceContainerWorkbookPage_folders_add_button ; public static String SourceContainerWorkbookPage_folders_link_source_button ; public static String SourceContainerWorkbookPage_folders_edit_button ; public static String SourceContainerWorkbookPage_folders_remove_button ; public static String SourceContainerWorkbookPage_folders_label ; public static String SourceContainerWorkbookPage_folders_check ; public static String SourceContainerWorkbookPage_ExistingSourceFolderDialog_new_title ; public static String SourceContainerWorkbookPage_ExistingSourceFolderDialog_edit_description ; public static String SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_and_output_message ; public static String SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_message ; public static String SourceContainerWorkbookPage_ChangeOutputLocationDialog_title ; public static String SourceContainerWorkbookPage_exclusion_added_title ; public static String SourceContainerWorkbookPage_exclusion_added_message ; public static String NewSourceContainerWorkbookPage_HintTextGroup_title ; public static String DialogPackageExplorer_LabelProvider_SingleExcluded ; public static String DialogPackageExplorer_LabelProvider_MultiExcluded ; public static String DialogPackageExplorer_LabelProvider_Excluded ; public static String DownloadRubyWizardPage_ERR_Downloading_ruby_installer ; public static String DownloadRubyWizardPage_ERR_Installer_exit_failure ; public static String DownloadRubyWizardPage_ERR_Launching_installer ; public static String DownloadRubyWizardPage_LBL_Downloading_ruby_installer ; public static String DownloadRubyWizardPage_LBL_Install_button ; public static String DownloadRubyWizardPage_MSG_Description ; public static String DownloadRubyWizardPage_MSG_Explanation_text ; public static String DownloadRubyWizardPage_TTL ; public static String ClasspathModifier_Monitor_ComparePaths ; public static String NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_tooltip ; public static String PackageExplorerActionGroup_FormText_ProjectToBuildpath ; public static String PackageExplorerActionGroup_FormText_PackageToBuildpath ; public static String PackageExplorerActionGroup_FormText_FolderToBuildpath ; public static String PackageExplorerActionGroup_FormText_Default_toBuildpath ; public static String LoadpathModifier_Error_NoNatures ; public static String LoadpathModifier_Monitor_AddToBuildpath ; public static String ClasspathModifier_Monitor_SetNewEntry ; public static String NewSourceFolderWizardPage_warning_ReplaceSF ; public static String ClasspathModifier_Monitor_AddToBuildpath ; public static String ClasspathModifier_Monitor_Excluding ; public static String ClasspathModifier_Monitor_RemovePath ; public static String NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_label ; public static String NewSourceContainerWorkbookPage_ToolBar_ClearAll_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_ClearAll_label ; public static String NewSourceContainerWorkbookPage_ToolBar_CreateSrcFolder_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_CreateSrcFolder_label ; public static String NewSourceContainerWorkbookPage_ToolBar_Link_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_Link_label ; public static String NewSourceContainerWorkbookPage_ToolBar_EditOutput_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_EditOutput_label ; public static String NewSourceContainerWorkbookPage_ToolBar_Configure_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_Configure_label ; public static String NewSourceContainerWorkbookPage_ToolBar_Edit_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_Edit_label ; public static String NewSourceContainerWorkbookPage_ToolBar_Unexclude_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_Unexclude_label ; public static String NewSourceContainerWorkbookPage_ToolBar_Exclude_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_Exclude_label ; public static String NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_label ; public static String PackageExplorerActionGroup_NoAction_File ; public static String PackageExplorerActionGroup_NoAction_DefaultPackage ; public static String PackageExplorerActionGroup_NoAction_NullSelection ; public static String PackageExplorerActionGroup_NoAction_MultiSelection ; public static String PackageExplorerActionGroup_NoAction_ArchiveResource ; public static String PackageExplorerActionGroup_NoAction_NoReason ; public static String NewSourceContainerWorkbookPage_ToolBar_Reset_tooltip ; public static String PackageExplorerActionGroup_FormText_Default_ResetAll ; public static String PackageExplorerActionGroup_FormText_createNewSourceFolder ; public static String NewSourceContainerWorkbookPage_ToolBar_AddLibCP_tooltip ; public static String PackageExplorerActionGroup_FormText_ProjectFromBuildpath ; public static String PackageExplorerActionGroup_FormText_fromBuildpath ; public static String PackageExplorerActionGroup_FormText_Default_FromBuildpath ; public static String ClasspathModifier_Monitor_RemoveFromBuildpath ; public static String PackageExplorerActionGroup_FormText_ExcludePackage ; public static String PackageExplorerActionGroup_FormText_ExcludeFile ; public static String PackageExplorerActionGroup_FormText_Default_Exclude ; public static String PackageExplorerActionGroup_FormText_UnexcludeFolder ; public static String PackageExplorerActionGroup_FormText_UnexcludeFile ; public static String PackageExplorerActionGroup_FormText_Default_Unexclude ; public static String ClasspathModifier_Monitor_Including ; public static String ClasspathModifier_Monitor_RemoveExclusion ; public static String PackageExplorerActionGroup_FormText_Edit ; public static String PackageExplorerActionGroup_FormText_Default_Edit ; public static String GenerateBuildPathActionGroup_no_action_available ; public static String PackageExplorerActionGroup_FormText_createLinkedFolder ; public static String AddSourceFolderToBuildpathAction_ErrorTitle ; public static String NewSourceContainerWorkbookPage_ToolBar_AddSelLibToCP_label ; public static String NewSourceContainerWorkbookPage_ToolBar_AddSelLibToCP_tooltip ; public static String AddSelectedLibraryToBuildpathAction_ErrorTitle ; public static String RemoveFromBuildpathAction_ErrorTitle ; public static String LoadpathModifier_Monitor_RemoveFromBuildpath ; public static String LoadpathModifierQueries_confirm_remove_linked_folder_message ; public static String LoadpathModifierQueries_delete_linked_folder ; public static String LoadpathModifierQueries_do_not_delete_linked_folder ; public static String LoadpathModifierQueries_confirm_remove_linked_folder_label ; public static String NewSourceContainerWorkbookPage_ToolBar_AddLibCP_label ; public static String AddLibraryToBuildpathAction_ErrorTitle ; public static String LoadpathContainerWizard_new_title ; public static String LoadpathContainerWizard_edit_title ; public static String LoadpathContainerWizard_pagecreationerror_title ; public static String LoadpathContainerWizard_pagecreationerror_message ; public static String ExcludeFromBuildathAction_ErrorTitle ; public static String LoadpathModifier_Monitor_Excluding ; public static String IncludeToBuildpathAction_ErrorTitle ; public static String InstallRubyWizardPage_LBL_Browse_to_installed_ruby ; public static String InstallRubyWizardPage_LBL_Install_Ruby ; public static String InstallRubyWizardPage_LBL_Options ; public static String InstallRubyWizardPage_LBL_Use_JRuby ; public static String InstallRubyWizardPage_MSG_Description ; public static String InstallRubyWizardPage_TTL ; public static String InstallStandardRubyWizard_TTL_Window ; public static String LoadpathModifier_Monitor_Including ; public static String NewSourceContainerWorkbookPage_ToolBar_ConfigureBP_label ; public static String NewSourceContainerWorkbookPage_ToolBar_ConfigureBP_tooltip ; public static String LoadpathContainerSelectionPage_title ; public static String LoadpathContainerSelectionPage_description ; public static String LoadpathContainerDefaultPage_title ; public static String LoadpathContainerDefaultPage_description ; public static String LoadpathContainerDefaultPage_path_label ; public static String LoadpathContainerDefaultPage_path_error_enterpath ; public static String LoadpathContainerDefaultPage_path_error_invalidpath ; public static String LoadpathContainerDefaultPage_path_error_needssegment ; public static String LoadpathContainerDefaultPage_path_error_alreadyexists ; public static String ExclusionInclusionDialog_description ; public static String LinkFolderDialog_folderNameGroup_label ; public static String NewFolderDialog_folderNameEmpty ; public static String LinkFolderDialog_title ; public static String LinkFolderDialog_createIn ; public static String NewFolderDialog_progress ; public static String NewFolderDialog_errorTitle ; public static String NewFolderDialog_internalError ; public static String ClasspathModifier_Monitor_ContainsPath ; public static String NewSourceContainerWorkbookPage_ToolBar_Help_label ; public static String NewSourceContainerWorkbookPage_ToolBar_Help_tooltip ; public static String NewSourceContainerWorkbookPage_ToolBar_Help_link ; public static String HintTextGroup_NoAction ; public static String HintTextGroup_Exception_Title ; public static String HintTextGroup_Exception_Title_refresh ; public static String LibrariesWorkbookPage_libraries_addextjar_button ; public static String BuildPathDialogAccess_ExtJARArchiveDialog_new_title ; public static String BuildPathDialogAccess_ExtJARArchiveDialog_edit_title ; public static String RubyProjectWizard_title ; public static String RubyProjectWizard_op_error_title ; public static String RubyProjectWizard_op_error_create_message ; public static String RubyProjectWizardFirstPage_NameGroup_label_text ; public static String RubyProjectWizardFirstPage_LocationGroup_title ; public static String RubyProjectWizardFirstPage_LocationGroup_workspace_desc ; public static String RubyProjectWizardFirstPage_LocationGroup_external_desc ; public static String RubyProjectWizardFirstPage_LocationGroup_locationLabel_desc ; public static String RubyProjectWizardFirstPage_LocationGroup_browseButton_desc ; public static String RubyProjectWizardFirstPage_LayoutGroup_title ; public static String RubyProjectWizardFirstPage_LayoutGroup_option_oneFolder ; public static String RubyProjectWizardFirstPage_LayoutGroup_option_separateFolders ; public static String RubyProjectWizardFirstPage_LayoutGroup_link_description ; public static String RubyProjectWizardFirstPage_JREGroup_title ; public static String RubyProjectWizardFirstPage_JREGroup_link_description ; public static String RubyProjectWizardFirstPage_JREGroup_specific_compliance ; public static String RubyProjectWizardFirstPage_JREGroup_default_compliance ; public static String RubyProjectWizardFirstPage_DetectGroup_message ; public static String RubyProjectWizardFirstPage_Message_cannotCreateInWorkspace ; public static String RubyProjectWizardFirstPage_Message_invalidDirectory ; public static String RubyProjectWizardFirstPage_page_pageName ; public static String RubyProjectWizardFirstPage_page_title ; public static String RubyProjectWizardFirstPage_page_description ; public static String RubyProjectWizardFirstPage_Message_enterProjectName ; public static String RubyProjectWizardFirstPage_Message_projectAlreadyExists ; public static String RubyProjectWizardFirstPage_Message_enterLocation ; public static String RubyProjectWizardSecondPage_error_title ; public static String RubyProjectWizardSecondPage_error_message ; public static String RubyProjectWizardSecondPage_operation_initialize ; public static String RubyProjectWizardSecondPage_problem_restore_project ; public static String RubyProjectWizardSecondPage_problem_restore_loadpath ; public static String RubyProjectWizardSecondPage_problem_backup ; public static String RubyProjectWizardSecondPage_operation_create ; public static String RubyProjectWizardSecondPage_error_remove_title ; public static String RubyProjectWizardSecondPage_error_remove_message ; public static String RubyProjectWizardSecondPage_operation_remove ; public static String RubyCapabilityConfigurationPage_title ; public static String RubyCapabilityConfigurationPage_description ; public static String RubyCapabilityConfigurationPage_op_desc_ruby ; public static String LoadPathDetector_operation_description ; public static String NewTypeWizardPage_SuperClassDialog_message ; public static String NewTypeWizardPage_SuperClassDialog_title ; public static String SuperModuleSelectionDialog_addButton_label ; public static String SuperModuleSelectionDialog_interfaceadded_info ; public static String SuperModuleSelectionDialog_interfacealreadyadded_info ; public static String NewVariableEntryDialog_title ; public static String NewVariableEntryDialog_vars_extend ; public static String NewVariableEntryDialog_vars_label ; public static String NewVariableEntryDialog_configbutton_label ; public static String NewVariableEntryDialog_info_notexists ; public static String NewVariableEntryDialog_info_isfolder ; public static String NewVariableEntryDialog_info_noselection ; public static String NewVariableEntryDialog_info_selected ; public static String NewVariableEntryDialog_ExtensionDialog_title ; public static String NewVariableEntryDialog_ExtensionDialog_description ; public static String CPVariableElementLabelProvider_reserved ; public static String CPVariableElementLabelProvider_empty ; public static String EditVariableEntryDialog_title ; public static String EditVariableEntryDialog_filename_varlabel ; public static String EditVariableEntryDialog_filename_external_varbutton ; public static String EditVariableEntryDialog_filename_variable_button ; public static String EditVariableEntryDialog_extvardialog_title ; public static String EditVariableEntryDialog_extvardialog_description ; public static String EditVariableEntryDialog_filename_empty ; public static String EditVariableEntryDialog_filename_error_notvalid ; public static String EditVariableEntryDialog_filename_error_deviceinpath ; public static String EditVariableEntryDialog_filename_error_varnotexists ; public static String EditVariableEntryDialog_filename_warning_varempty ; public static String EditVariableEntryDialog_filename_error_filenotexists ; public static String EditVariableEntryDialog_filename_error_alreadyexists ; public static String VariablePathDialogField_variabledialog_title ; public static String VariableBlock_vars_add_button ; public static String VariableBlock_vars_edit_button ; public static String VariableBlock_vars_remove_button ; public static String VariableBlock_vars_label ; public static String VariableBlock_needsbuild_title ; public static String VariableBlock_needsbuild_message ; public static String VariableBlock_variableSettingError_titel ; public static String VariableBlock_variableSettingError_message ; public static String VariableBlock_operation_desc ; public static String VariableCreationDialog_titlenew ; public static String VariableCreationDialog_titleedit ; public static String VariableCreationDialog_name_label ; public static String VariableCreationDialog_path_label ; public static String VariableCreationDialog_path_file_button ; public static String VariableCreationDialog_path_dir_button ; public static String VariableCreationDialog_error_entername ; public static String VariableCreationDialog_error_whitespace ; public static String VariableCreationDialog_error_invalidname ; public static String VariableCreationDialog_error_nameexists ; public static String VariableCreationDialog_error_invalidpath ; public static String VariableCreationDialog_warning_pathnotexists ; public static String VariableCreationDialog_extjardialog_text ; public static String VariableCreationDialog_extdirdialog_text ; public static String VariableCreationDialog_extdirdialog_message ; public static String LibrariesWorkbookPage_libraries_addvariable_button ; public static String UseJRubyWizardPage_MSG_Description ; public static String UseJRubyWizardPage_MSG_Explanation_text ; public static String UseJRubyWizardPage_TTL ; static { NLS . initializeMessages ( BUNDLE_NAME , NewWizardMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . ui . actions . AbstractOpenWizardAction ; public class NewClassWizardAction extends AbstractOpenWizardAction implements IWorkbenchWindowActionDelegate { public NewClassWizardAction ( ) { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . OPEN_CLASS_WIZARD_ACTION ) ; } protected INewWizard createWizard ( ) throws CoreException { return new NewClassCreationWizard ( ) ; } public void dispose ( ) { } public void init ( IWorkbenchWindow window ) { setShell ( window . getShell ( ) ) ; } public void run ( IAction action ) { super . run ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { if ( selection instanceof IStructuredSelection ) { setSelection ( ( IStructuredSelection ) selection ) ; } else { setSelection ( StructuredSelection . EMPTY ) ; } } } package org . rubypeople . rdt . internal . ui . wizards ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . lang . reflect . InvocationTargetException ; import java . net . URL ; import java . net . URLConnection ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . MouseAdapter ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; class DownloadRubyWizardPage extends WizardPage implements IWizardPage { private static final String RUBY_INSTALLER_EXE = "" ; private static final String RUBY_INSTALLER_URL = "" ; private static final int BUFFER_SIZE = * ; private static final int READ_TIMEOUT = ; private static final int CONNECT_TIMEOUT = ; private static final long SLEEP_TIME = ; protected boolean fInstalledProperly ; private IWizardPage fNextPage ; private Label downloadButton ; private Image fEnabledImage ; private Image fDisabledImage ; private MouseAdapter downloadListener ; protected DownloadRubyWizardPage ( ) { super ( "" ) ; setTitle ( NewWizardMessages . DownloadRubyWizardPage_TTL ) ; setDescription ( NewWizardMessages . DownloadRubyWizardPage_MSG_Description ) ; } public void createControl ( Composite parent ) { Composite main = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; main . setLayout ( layout ) ; main . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Label label = new Label ( main , SWT . WRAP ) ; label . setText ( NewWizardMessages . DownloadRubyWizardPage_MSG_Explanation_text ) ; GridData data = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; data . widthHint = ; label . setLayoutData ( data ) ; downloadButton = new Label ( main , SWT . None ) ; downloadButton . setImage ( getEnabledButtonImage ( ) ) ; downloadListener = new MouseAdapter ( ) { @ Override public void mouseDown ( MouseEvent e ) { Display . getCurrent ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { downloadButton . setImage ( getDisabledButtonImage ( ) ) ; } } ) ; downloadRuby ( ) ; downloadButton . removeMouseListener ( this ) ; } } ; downloadButton . addMouseListener ( downloadListener ) ; GridData downloadButtonData = new GridData ( SWT . CENTER , SWT . CENTER , true , true ) ; downloadButton . setLayoutData ( downloadButtonData ) ; setControl ( main ) ; } private Image getEnabledButtonImage ( ) { if ( fEnabledImage == null ) { fEnabledImage = RubyPlugin . imageDescriptorFromPlugin ( RubyPlugin . PLUGIN_ID , "" ) . createImage ( ) ; } return fEnabledImage ; } private Image getDisabledButtonImage ( ) { if ( fDisabledImage == null ) { fDisabledImage = RubyPlugin . imageDescriptorFromPlugin ( RubyPlugin . PLUGIN_ID , "" ) . createImage ( ) ; } return fDisabledImage ; } @ Override public void dispose ( ) { if ( fEnabledImage != null ) { fEnabledImage . dispose ( ) ; fEnabledImage = null ; } if ( fDisabledImage != null ) { fDisabledImage . dispose ( ) ; fDisabledImage = null ; } super . dispose ( ) ; } protected void downloadRuby ( ) { try { getContainer ( ) . run ( true , true , new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; download ( monitor ) ; if ( monitor . isCanceled ( ) ) return ; try { monitor . subTask ( "" ) ; Process p = Runtime . getRuntime ( ) . exec ( getSaveLocation ( ) ) ; int installerExit = p . waitFor ( ) ; if ( installerExit != ) { UIJob job = new UIJob ( "" ) { @ Override public IStatus runInUIThread ( IProgressMonitor monitor ) { setErrorMessage ( NewWizardMessages . DownloadRubyWizardPage_ERR_Installer_exit_failure ) ; return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . schedule ( ) ; return ; } fInstalledProperly = true ; } catch ( IOException e ) { setErrorMessage ( NewWizardMessages . DownloadRubyWizardPage_ERR_Launching_installer ) ; } } private void download ( IProgressMonitor monitor ) { String fileURL = RUBY_INSTALLER_URL ; InputStream inStream = null ; OutputStream outStream = null ; try { URLConnection connection = new URL ( fileURL ) . openConnection ( ) ; connection . setDoOutput ( false ) ; connection . setDoInput ( true ) ; connection . setReadTimeout ( READ_TIMEOUT ) ; connection . setAllowUserInteraction ( false ) ; connection . setConnectTimeout ( CONNECT_TIMEOUT ) ; connection . setUseCaches ( false ) ; connection . setRequestProperty ( "" , "" ) ; connection . connect ( ) ; int length = connection . getContentLength ( ) ; if ( length != - ) monitor . beginTask ( NewWizardMessages . DownloadRubyWizardPage_LBL_Downloading_ruby_installer , length ) ; inStream = connection . getInputStream ( ) ; outStream = new FileOutputStream ( getSaveLocation ( ) ) ; int chunkSize = ( int ) Math . min ( BUFFER_SIZE , length ) ; long chunks = length / chunkSize ; int lastChunkSize = ( int ) ( length % chunkSize ) ; byte [ ] ba = new byte [ chunkSize ] ; for ( long i = ; i < chunks ; i ++ ) { if ( monitor . isCanceled ( ) ) { return ; } int bytesRead = readBytesBlocking ( inStream , ba , , chunkSize , READ_TIMEOUT ) ; if ( bytesRead != chunkSize ) { throw new IOException ( ) ; } outStream . write ( ba ) ; monitor . worked ( bytesRead ) ; } if ( lastChunkSize > ) { int bytesRead = readBytesBlocking ( inStream , ba , , lastChunkSize , READ_TIMEOUT ) ; if ( bytesRead != lastChunkSize ) { throw new IOException ( ) ; } outStream . write ( ba , , lastChunkSize ) ; } } catch ( IOException e ) { UIJob job = new UIJob ( "" ) { @ Override public IStatus runInUIThread ( IProgressMonitor monitor ) { setErrorMessage ( NewWizardMessages . DownloadRubyWizardPage_ERR_Downloading_ruby_installer ) ; return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . schedule ( ) ; return ; } finally { try { if ( inStream != null ) inStream . close ( ) ; } catch ( IOException e ) { } try { if ( outStream != null ) outStream . close ( ) ; } catch ( IOException e ) { } } } private int readBytesBlocking ( InputStream in , byte b [ ] , int off , int len , int timeoutInMillis ) throws IOException { int totalBytesRead = ; int bytesRead ; long whenToGiveUp = System . currentTimeMillis ( ) + timeoutInMillis ; while ( totalBytesRead < len && ( bytesRead = in . read ( b , off + totalBytesRead , len - totalBytesRead ) ) >= ) { if ( bytesRead == ) { try { if ( System . currentTimeMillis ( ) >= whenToGiveUp ) { throw new IOException ( "" ) ; } Thread . sleep ( SLEEP_TIME ) ; } catch ( InterruptedException e ) { } } else { totalBytesRead += bytesRead ; whenToGiveUp = System . currentTimeMillis ( ) + timeoutInMillis ; } } return totalBytesRead ; } } ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } if ( fInstalledProperly ) { setNextPage ( new BrowseToInstalledRubyWizardPage ( "" ) ) ; setErrorMessage ( null ) ; getContainer ( ) . updateButtons ( ) ; getContainer ( ) . showPage ( fNextPage ) ; } } protected void setNextPage ( IWizardPage page ) { fNextPage = page ; if ( fNextPage == null ) return ; fNextPage . setWizard ( getWizard ( ) ) ; ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( false ) ; } protected String getSaveLocation ( ) { String value = System . getProperty ( "" ) ; if ( value != null && value . trim ( ) . length ( ) > ) { return value + File . separator + "" + File . separator + RUBY_INSTALLER_EXE ; } return "" + File . separator + RUBY_INSTALLER_EXE ; } @ Override public IWizardPage getNextPage ( ) { return fNextPage ; } @ Override public boolean isPageComplete ( ) { return canFlipToNextPage ( ) ; } @ Override public boolean canFlipToNextPage ( ) { return fNextPage != null ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . ui . wizards . NewFileWizardPage ; public class NewFileCreationWizard extends NewElementWizard { private NewFileWizardPage fPage ; public NewFileCreationWizard ( NewFileWizardPage page ) { setDefaultPageImageDescriptor ( RubyPluginImages . DESC_WIZBAN_NEWFILE ) ; setDialogSettings ( RubyPlugin . getDefault ( ) . getDialogSettings ( ) ) ; setWindowTitle ( NewWizardMessages . NewFileCreationWizard_title ) ; fPage = page ; } public NewFileCreationWizard ( ) { this ( null ) ; } public void addPages ( ) { super . addPages ( ) ; if ( fPage == null ) { fPage = new NewFileWizardPage ( ) ; fPage . init ( getSelection ( ) ) ; } addPage ( fPage ) ; } protected void finishPage ( IProgressMonitor monitor ) throws InterruptedException , CoreException { fPage . createScript ( monitor ) ; } public boolean performFinish ( ) { boolean res = super . performFinish ( ) ; if ( res ) { IResource resource = fPage . getModifiedResource ( ) ; if ( resource != null ) { selectAndReveal ( resource ) ; openResource ( ( IFile ) resource ) ; } } return res ; } public IRubyElement getCreatedElement ( ) { return fPage . getCreatedScript ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . ui . wizards . NewClassWizardPage ; public class NewClassCreationWizard extends NewElementWizard { private NewClassWizardPage fPage ; public NewClassCreationWizard ( NewClassWizardPage page ) { setDefaultPageImageDescriptor ( RubyPluginImages . DESC_WIZBAN_NEWCLASS ) ; setDialogSettings ( RubyPlugin . getDefault ( ) . getDialogSettings ( ) ) ; setWindowTitle ( NewWizardMessages . NewClassCreationWizard_title ) ; fPage = page ; } public NewClassCreationWizard ( ) { this ( null ) ; } public void addPages ( ) { super . addPages ( ) ; if ( fPage == null ) { fPage = new NewClassWizardPage ( ) ; fPage . init ( getSelection ( ) ) ; } addPage ( fPage ) ; } protected void finishPage ( IProgressMonitor monitor ) throws InterruptedException , CoreException { fPage . createType ( monitor ) ; } public boolean performFinish ( ) { boolean res = super . performFinish ( ) ; if ( res ) { IResource resource = fPage . getModifiedResource ( ) ; if ( resource != null ) { selectAndReveal ( resource ) ; openResource ( ( IFile ) resource ) ; } } return res ; } public IRubyElement getCreatedElement ( ) { return fPage . getCreatedType ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . jface . dialogs . IPageChangedListener ; import org . eclipse . jface . dialogs . PageChangedEvent ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; class UseJRubyWizardPage extends WizardPage implements IWizardPage , IPageChangedListener { protected UseJRubyWizardPage ( ) { super ( "" ) ; setTitle ( NewWizardMessages . UseJRubyWizardPage_TTL ) ; setDescription ( NewWizardMessages . UseJRubyWizardPage_MSG_Description ) ; } public void createControl ( Composite parent ) { Composite main = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; main . setLayout ( layout ) ; main . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Label label = new Label ( main , SWT . WRAP ) ; label . setText ( NewWizardMessages . UseJRubyWizardPage_MSG_Explanation_text ) ; GridData data = new GridData ( ) ; data . widthHint = ; label . setLayoutData ( data ) ; setControl ( main ) ; ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( true ) ; ( getWizardDialog ( ) ) . addPageChangedListener ( this ) ; } private WizardDialog getWizardDialog ( ) { return ( WizardDialog ) getContainer ( ) ; } public void dispose ( ) { if ( getWizardDialog ( ) != null ) ( getWizardDialog ( ) ) . removePageChangedListener ( this ) ; super . dispose ( ) ; } public void pageChanged ( PageChangedEvent event ) { Object page = event . getSelectedPage ( ) ; if ( page . equals ( this ) ) ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( true ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import java . lang . reflect . InvocationTargetException ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . filesystem . URIUtil ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExecutableExtension ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . wizards . newresource . BasicNewProjectResourceWizard ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . BuildPathsBlock ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyProjectWizard extends NewElementWizard implements IExecutableExtension { private RubyProjectWizardFirstPage fFirstPage ; private IConfigurationElement fConfigElement ; private URI fCurrProjectLocation ; public RubyProjectWizard ( ) { setDefaultPageImageDescriptor ( RubyPluginImages . DESC_WIZBAN_NEWJPRJ ) ; setDialogSettings ( RubyPlugin . getDefault ( ) . getDialogSettings ( ) ) ; setWindowTitle ( NewWizardMessages . RubyProjectWizard_title ) ; } public void addPages ( ) { super . addPages ( ) ; fFirstPage = new RubyProjectWizardFirstPage ( ) ; addPage ( fFirstPage ) ; } protected void finishPage ( IProgressMonitor monitor ) throws InterruptedException , CoreException { try { monitor . beginTask ( NewWizardMessages . RubyProjectWizardSecondPage_operation_create , ) ; configureRubyProject ( new SubProgressMonitor ( monitor , ) ) ; } finally { monitor . done ( ) ; } } public void configureRubyProject ( IProgressMonitor monitor ) throws CoreException , InterruptedException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } int nSteps = ; monitor . beginTask ( NewWizardMessages . RubyCapabilityConfigurationPage_op_desc_ruby , nSteps ) ; try { IProject project = fFirstPage . getProjectHandle ( ) ; fCurrProjectLocation = getProjectLocationURI ( ) ; URI realLocation = fCurrProjectLocation ; if ( fCurrProjectLocation == null ) { try { URI rootLocation = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getLocationURI ( ) ; realLocation = new URI ( rootLocation . getScheme ( ) , null , Path . fromPortableString ( rootLocation . getPath ( ) ) . append ( project . getName ( ) ) . toString ( ) , null ) ; } catch ( URISyntaxException e ) { Assert . isTrue ( false , "" ) ; } } BuildPathsBlock . createProject ( project , fCurrProjectLocation , monitor ) ; IRubyProject rubyProject = RubyCore . create ( project ) ; List < ILoadpathEntry > cpEntries = new ArrayList < ILoadpathEntry > ( ) ; IPath projectPath = project . getFullPath ( ) ; cpEntries . add ( RubyCore . newSourceEntry ( projectPath ) ) ; cpEntries . addAll ( Arrays . asList ( getDefaultLoadpathEntry ( ) ) ) ; List < CPListElement > newClassPath = new ArrayList < CPListElement > ( ) ; for ( ILoadpathEntry entry : cpEntries ) { newClassPath . add ( CPListElement . createFromExisting ( entry , rubyProject ) ) ; } monitor . worked ( ) ; BuildPathsBlock . addRubyNature ( project , new SubProgressMonitor ( monitor , ) ) ; BuildPathsBlock . flush ( newClassPath , rubyProject , new SubProgressMonitor ( monitor , ) ) ; } catch ( OperationCanceledException e ) { throw new InterruptedException ( ) ; } finally { monitor . done ( ) ; } } private ILoadpathEntry [ ] getDefaultLoadpathEntry ( ) { ILoadpathEntry [ ] defaultJRELibrary = PreferenceConstants . getDefaultRubyVMLibrary ( ) ; String compliance = fFirstPage . getCompilerCompliance ( ) ; IPath jreContainerPath = new Path ( RubyRuntime . RUBY_CONTAINER ) ; if ( compliance == null || defaultJRELibrary . length > || ! jreContainerPath . isPrefixOf ( defaultJRELibrary [ ] . getPath ( ) ) ) { return defaultJRELibrary ; } IVMInstall inst = fFirstPage . getJVM ( ) ; if ( inst != null ) { IPath newPath = jreContainerPath . append ( inst . getVMInstallType ( ) . getId ( ) ) . append ( inst . getName ( ) ) ; return new ILoadpathEntry [ ] { RubyCore . newContainerEntry ( newPath ) } ; } return defaultJRELibrary ; } public boolean performFinish ( ) { boolean res = super . performFinish ( ) ; if ( res ) { BasicNewProjectResourceWizard . updatePerspective ( fConfigElement ) ; selectAndReveal ( fFirstPage . getProjectHandle ( ) ) ; } return res ; } protected void handleFinishException ( Shell shell , InvocationTargetException e ) { String title = NewWizardMessages . RubyProjectWizard_op_error_title ; String message = NewWizardMessages . RubyProjectWizard_op_error_create_message ; ExceptionHandler . handle ( e , getShell ( ) , title , message ) ; } public void setInitializationData ( IConfigurationElement cfig , String propertyName , Object data ) { fConfigElement = cfig ; } public boolean performCancel ( ) { return super . performCancel ( ) ; } public IRubyElement getCreatedElement ( ) { return RubyCore . create ( fFirstPage . getProjectHandle ( ) ) ; } private URI getProjectLocationURI ( ) throws CoreException { if ( fFirstPage . isInWorkspace ( ) ) { return null ; } return URIUtil . toURI ( fFirstPage . getLocationPath ( ) ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import java . text . Collator ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceProxy ; import org . eclipse . core . resources . IResourceProxyVisitor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class LoadPathDetector implements IResourceProxyVisitor { private HashMap fSourceFolders ; private IProject fProject ; private ILoadpathEntry [ ] fResultLoadpath ; private IProgressMonitor fMonitor ; private static class LPSorter implements Comparator { private Collator fCollator = Collator . getInstance ( ) ; public int compare ( Object o1 , Object o2 ) { ILoadpathEntry e1 = ( ILoadpathEntry ) o1 ; ILoadpathEntry e2 = ( ILoadpathEntry ) o2 ; return fCollator . compare ( e1 . getPath ( ) . toString ( ) , e2 . getPath ( ) . toString ( ) ) ; } } public LoadPathDetector ( IProject project , IProgressMonitor monitor ) throws CoreException { fSourceFolders = new HashMap ( ) ; fProject = project ; fResultLoadpath = null ; if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } detectLoadpath ( monitor ) ; } private void detectLoadpath ( IProgressMonitor monitor ) throws CoreException { try { monitor . beginTask ( NewWizardMessages . LoadPathDetector_operation_description , ) ; fMonitor = monitor ; fProject . accept ( this , IResource . NONE ) ; monitor . worked ( ) ; ArrayList cpEntries = new ArrayList ( ) ; detectSourceFolders ( cpEntries ) ; if ( monitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } monitor . worked ( ) ; if ( cpEntries . isEmpty ( ) ) { return ; } ILoadpathEntry [ ] jreEntries = PreferenceConstants . getDefaultRubyVMLibrary ( ) ; for ( int i = ; i < jreEntries . length ; i ++ ) { cpEntries . add ( jreEntries [ i ] ) ; } ILoadpathEntry [ ] entries = ( ILoadpathEntry [ ] ) cpEntries . toArray ( new ILoadpathEntry [ cpEntries . size ( ) ] ) ; if ( ! RubyConventions . validateLoadpath ( RubyCore . create ( fProject ) , entries , null ) . isOK ( ) ) { return ; } fResultLoadpath = entries ; } finally { monitor . done ( ) ; } } private void detectSourceFolders ( ArrayList resEntries ) { ArrayList res = new ArrayList ( ) ; Set sourceFolderSet = fSourceFolders . keySet ( ) ; for ( Iterator iter = sourceFolderSet . iterator ( ) ; iter . hasNext ( ) ; ) { IPath path = ( IPath ) iter . next ( ) ; ArrayList excluded = new ArrayList ( ) ; for ( Iterator inner = sourceFolderSet . iterator ( ) ; inner . hasNext ( ) ; ) { IPath other = ( IPath ) inner . next ( ) ; if ( ! path . equals ( other ) && path . isPrefixOf ( other ) ) { IPath pathToExclude = other . removeFirstSegments ( path . segmentCount ( ) ) . addTrailingSeparator ( ) ; excluded . add ( pathToExclude ) ; } } IPath [ ] excludedPaths = ( IPath [ ] ) excluded . toArray ( new IPath [ excluded . size ( ) ] ) ; ILoadpathEntry entry = RubyCore . newSourceEntry ( path , excludedPaths ) ; res . add ( entry ) ; } Collections . sort ( res , new LPSorter ( ) ) ; resEntries . addAll ( res ) ; } private void visitRubyScript ( IFile file ) { IRubyScript cu = RubyCore . createRubyScriptFrom ( file ) ; if ( cu != null ) { IRubyScript workingCopy = null ; try { workingCopy = cu . getWorkingCopy ( null ) ; IPath packPath = file . getParent ( ) . getFullPath ( ) ; String cuName = file . getName ( ) ; addToMap ( fSourceFolders , packPath , new Path ( cuName ) ) ; } catch ( RubyModelException e ) { } finally { if ( workingCopy != null ) { try { workingCopy . discardWorkingCopy ( ) ; } catch ( RubyModelException ignore ) { } } } } } private void addToMap ( HashMap map , IPath folderPath , IPath relPath ) { List list = ( List ) map . get ( folderPath ) ; if ( list == null ) { list = new ArrayList ( ) ; map . put ( folderPath , list ) ; } list . add ( relPath ) ; } private boolean isValidScriptName ( String name ) { return ! RubyConventions . validateRubyScriptName ( name ) . matches ( IStatus . ERROR ) ; } public boolean visit ( IResourceProxy proxy ) { if ( fMonitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } if ( proxy . getType ( ) == IResource . FILE ) { String name = proxy . getName ( ) ; if ( isValidScriptName ( name ) ) { visitRubyScript ( ( IFile ) proxy . requestResource ( ) ) ; } return false ; } return true ; } public ILoadpathEntry [ ] getLoadpath ( ) { return fResultLoadpath ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; public class TypedViewerFilter extends ViewerFilter { private Class [ ] fAcceptedTypes ; private Object [ ] fRejectedElements ; public TypedViewerFilter ( Class [ ] acceptedTypes ) { this ( acceptedTypes , null ) ; } public TypedViewerFilter ( Class [ ] acceptedTypes , Object [ ] rejectedElements ) { Assert . isNotNull ( acceptedTypes ) ; fAcceptedTypes = acceptedTypes ; fRejectedElements = rejectedElements ; } public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( fRejectedElements != null ) { for ( int i = ; i < fRejectedElements . length ; i ++ ) { if ( element . equals ( fRejectedElements [ i ] ) ) { return false ; } } } for ( int i = ; i < fAcceptedTypes . length ; i ++ ) { if ( fAcceptedTypes [ i ] . isInstance ( element ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . internal . ui . wizards ; import java . io . File ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . dialogs . IMessageProvider ; import org . eclipse . jface . dialogs . IPageChangedListener ; import org . eclipse . jface . dialogs . PageChangedEvent ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; class BrowseToInstalledRubyWizardPage extends WizardPage implements IWizardPage , IPageChangedListener { private Button fBrowseButton ; private Text fText ; private String defaultValue ; protected BrowseToInstalledRubyWizardPage ( ) { this ( null ) ; } protected BrowseToInstalledRubyWizardPage ( String defaultValue ) { super ( "" ) ; setTitle ( NewWizardMessages . BrowseToInstalledRubyWizardPage_TTL ) ; setDescription ( NewWizardMessages . BrowseToInstalledRubyWizardPage_MSG_Description ) ; this . defaultValue = defaultValue ; } public void createControl ( Composite parent ) { Composite main = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( , false ) ; layout . marginHeight = ; layout . marginWidth = ; main . setLayout ( layout ) ; main . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Label label = new Label ( main , SWT . WRAP ) ; label . setText ( NewWizardMessages . BrowseToInstalledRubyWizardPage_MSG_Explanation_text ) ; GridData data = new GridData ( ) ; data . horizontalSpan = ; data . widthHint = parent . getSize ( ) . x ; label . setLayoutData ( data ) ; fText = new Text ( main , SWT . SINGLE | SWT . BORDER ) ; GridData textData = new GridData ( ) ; textData . widthHint = ; fText . setLayoutData ( textData ) ; fText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { validateVMLocation ( ) ; } } ) ; fBrowseButton = new Button ( main , SWT . PUSH | SWT . LEFT ) ; fBrowseButton . setText ( NewWizardMessages . BrowseToInstalledRubyWizardPage_LBL_Browse_button ) ; fBrowseButton . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) ) ; dialog . setFilterPath ( fText . getText ( ) ) ; dialog . setMessage ( NewWizardMessages . BrowseToInstalledRubyWizardPage_MSG_Browse_dialog ) ; String newPath = dialog . open ( ) ; fText . setText ( newPath ) ; validateVMLocation ( ) ; super . widgetSelected ( e ) ; } } ) ; setControl ( main ) ; ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( false ) ; getWizardDialog ( ) . addPageChangedListener ( this ) ; if ( defaultValue != null ) { fText . setText ( defaultValue ) ; validateVMLocation ( ) ; } } protected void validateVMLocation ( ) { final IVMInstallType type = getStandardVMType ( ) ; if ( type == null ) { setErrorMessage ( NewWizardMessages . BrowseToInstalledRubyWizardPage_ERR_MSG_Unable_find_standard_vm_metadata ) ; ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( false ) ; getContainer ( ) . updateButtons ( ) ; return ; } String location = fText . getText ( ) ; if ( location == null || location . trim ( ) . length ( ) == ) { setErrorMessage ( NewWizardMessages . BrowseToInstalledRubyWizardPage_ERR_MSG_Location_empty ) ; ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( false ) ; getContainer ( ) . updateButtons ( ) ; return ; } final IStatus [ ] temp = new IStatus [ ] ; final File tempFile = new File ( location ) ; Runnable r = new Runnable ( ) { public void run ( ) { temp [ ] = type . validateInstallLocation ( tempFile ) ; } } ; BusyIndicator . showWhile ( getShell ( ) . getDisplay ( ) , r ) ; if ( temp [ ] . getSeverity ( ) == IStatus . ERROR ) { setErrorMessage ( temp [ ] . getMessage ( ) ) ; ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( false ) ; getContainer ( ) . updateButtons ( ) ; } else if ( temp [ ] . getSeverity ( ) == IStatus . WARNING ) { setMessage ( temp [ ] . getMessage ( ) , IMessageProvider . WARNING ) ; } else { setErrorMessage ( null ) ; setMessage ( null ) ; ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( true ) ; getContainer ( ) . updateButtons ( ) ; } } private IVMInstallType getStandardVMType ( ) { return RubyRuntime . getVMInstallType ( IRubyLaunchConfigurationConstants . ID_STANDARD_VM_TYPE ) ; } public void addVM ( ) { VMStandin standin = new VMStandin ( getStandardVMType ( ) , String . valueOf ( System . currentTimeMillis ( ) ) ) ; standin . setName ( NewWizardMessages . BrowseToInstalledRubyWizardPage_LBL_Standard_ruby_entry_name ) ; standin . setInstallLocation ( new File ( fText . getText ( ) ) ) ; IVMInstall vm = standin . convertToRealVM ( ) ; try { RubyRuntime . setDefaultVMInstall ( vm , new NullProgressMonitor ( ) , true ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } } private WizardDialog getWizardDialog ( ) { return ( WizardDialog ) getContainer ( ) ; } public void dispose ( ) { if ( getWizardDialog ( ) != null ) ( getWizardDialog ( ) ) . removePageChangedListener ( this ) ; super . dispose ( ) ; } public void pageChanged ( PageChangedEvent event ) { Object page = event . getSelectedPage ( ) ; if ( page . equals ( this ) ) validateVMLocation ( ) ; } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . events . KeyEvent ; public interface ITreeListAdapter { void customButtonPressed ( TreeListDialogField field , int index ) ; void selectionChanged ( TreeListDialogField field ) ; void doubleClicked ( TreeListDialogField field ) ; void keyPressed ( TreeListDialogField field , KeyEvent event ) ; Object [ ] getChildren ( TreeListDialogField field , Object element ) ; Object getParent ( TreeListDialogField field , Object element ) ; boolean hasChildren ( TreeListDialogField field , Object element ) ; } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; public class StringButtonDialogField extends StringDialogField { private Button fBrowseButton ; private String fBrowseButtonLabel ; private IStringButtonAdapter fStringButtonAdapter ; private boolean fButtonEnabled ; public StringButtonDialogField ( IStringButtonAdapter adapter ) { super ( ) ; fStringButtonAdapter = adapter ; fBrowseButtonLabel = "" ; fButtonEnabled = true ; } public void setButtonLabel ( String label ) { fBrowseButtonLabel = label ; } public void changeControlPressed ( ) { fStringButtonAdapter . changeControlPressed ( this ) ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; Label label = getLabelControl ( parent ) ; label . setLayoutData ( gridDataForLabel ( ) ) ; Text text = getTextControl ( parent ) ; text . setLayoutData ( gridDataForText ( nColumns - ) ) ; Button button = getChangeControl ( parent ) ; button . setLayoutData ( gridDataForButton ( button , ) ) ; return new Control [ ] { label , text , button } ; } public int getNumberOfControls ( ) { return ; } protected static GridData gridDataForButton ( Button button , int span ) { GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . horizontalSpan = span ; gd . heightHint = SWTUtil . getButtonHeightHint ( button ) ; gd . widthHint = SWTUtil . getButtonWidthHint ( button ) ; return gd ; } public Button getChangeControl ( Composite parent ) { if ( fBrowseButton == null ) { assertCompositeNotNull ( parent ) ; fBrowseButton = new Button ( parent , SWT . PUSH ) ; fBrowseButton . setText ( fBrowseButtonLabel ) ; fBrowseButton . setEnabled ( isEnabled ( ) && fButtonEnabled ) ; fBrowseButton . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { changeControlPressed ( ) ; } public void widgetSelected ( SelectionEvent e ) { changeControlPressed ( ) ; } } ) ; } return fBrowseButton ; } public void enableButton ( boolean enable ) { if ( isOkToUse ( fBrowseButton ) ) { fBrowseButton . setEnabled ( isEnabled ( ) && enable ) ; } fButtonEnabled = enable ; } protected void updateEnableState ( ) { super . updateEnableState ( ) ; if ( isOkToUse ( fBrowseButton ) ) { fBrowseButton . setEnabled ( isEnabled ( ) && fButtonEnabled ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; public class StringDialogField extends DialogField { private String fText ; private Text fTextControl ; private ModifyListener fModifyListener ; public StringDialogField ( ) { super ( ) ; fText = "" ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; Label label = getLabelControl ( parent ) ; label . setLayoutData ( gridDataForLabel ( ) ) ; Text text = getTextControl ( parent ) ; text . setLayoutData ( gridDataForText ( nColumns - ) ) ; return new Control [ ] { label , text } ; } public int getNumberOfControls ( ) { return ; } protected static GridData gridDataForText ( int span ) { GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . horizontalSpan = span ; return gd ; } public boolean setFocus ( ) { if ( isOkToUse ( fTextControl ) ) { fTextControl . setFocus ( ) ; fTextControl . setSelection ( , fTextControl . getText ( ) . length ( ) ) ; } return true ; } public Text getTextControl ( Composite parent ) { if ( fTextControl == null ) { assertCompositeNotNull ( parent ) ; fModifyListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { doModifyText ( e ) ; } } ; fTextControl = new Text ( parent , SWT . SINGLE | SWT . BORDER ) ; fTextControl . setText ( fText ) ; fTextControl . setFont ( parent . getFont ( ) ) ; fTextControl . addModifyListener ( fModifyListener ) ; fTextControl . setEnabled ( isEnabled ( ) ) ; } return fTextControl ; } private void doModifyText ( ModifyEvent e ) { if ( isOkToUse ( fTextControl ) ) { fText = fTextControl . getText ( ) ; } dialogFieldChanged ( ) ; } protected void updateEnableState ( ) { super . updateEnableState ( ) ; if ( isOkToUse ( fTextControl ) ) { fTextControl . setEnabled ( isEnabled ( ) ) ; } } public String getText ( ) { return fText ; } public void setText ( String text ) { fText = text ; if ( isOkToUse ( fTextControl ) ) { fTextControl . setText ( text ) ; } else { dialogFieldChanged ( ) ; } } public void setTextWithoutUpdate ( String text ) { fText = text ; if ( isOkToUse ( fTextControl ) ) { fTextControl . removeModifyListener ( fModifyListener ) ; fTextControl . setText ( text ) ; fTextControl . addModifyListener ( fModifyListener ) ; } } public void refresh ( ) { super . refresh ( ) ; if ( isOkToUse ( fTextControl ) ) { setTextWithoutUpdate ( fText ) ; } } public String getLabelText ( ) { return fLabelText ; } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; public interface IListAdapter { void customButtonPressed ( ListDialogField field , int index ) ; void selectionChanged ( ListDialogField field ) ; void doubleClicked ( ListDialogField field ) ; } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; public interface IDialogFieldListener { void dialogFieldChanged ( DialogField field ) ; } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . swt . layout . GridData ; import org . eclipse . jface . resource . JFaceResources ; public class StringButtonStatusDialogField extends StringButtonDialogField { private Label fStatusLabelControl ; private Object fStatus ; private String fWidthHintString ; private int fWidthHint ; public StringButtonStatusDialogField ( IStringButtonAdapter adapter ) { super ( adapter ) ; fStatus = null ; fWidthHintString = null ; fWidthHint = - ; } public void setStatus ( String status ) { if ( isOkToUse ( fStatusLabelControl ) ) { fStatusLabelControl . setText ( status ) ; } fStatus = status ; } public void setStatus ( Image image ) { if ( isOkToUse ( fStatusLabelControl ) ) { if ( image == null ) { fStatusLabelControl . setImage ( null ) ; } else { fStatusLabelControl . setImage ( image ) ; } } fStatus = image ; } public void setStatusWidthHint ( String widthHintString ) { fWidthHintString = widthHintString ; fWidthHint = - ; } public void setStatusWidthHint ( int widthHint ) { fWidthHint = widthHint ; fWidthHintString = null ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; Label label = getLabelControl ( parent ) ; label . setLayoutData ( gridDataForLabel ( ) ) ; Text text = getTextControl ( parent ) ; text . setLayoutData ( gridDataForText ( nColumns - ) ) ; Label status = getStatusLabelControl ( parent ) ; status . setLayoutData ( gridDataForStatusLabel ( parent , ) ) ; Button button = getChangeControl ( parent ) ; button . setLayoutData ( gridDataForButton ( button , ) ) ; return new Control [ ] { label , text , status , button } ; } public int getNumberOfControls ( ) { return ; } protected GridData gridDataForStatusLabel ( Control aControl , int span ) { GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . BEGINNING ; gd . grabExcessHorizontalSpace = false ; gd . horizontalIndent = ; if ( fWidthHintString != null ) { GC gc = new GC ( aControl ) ; gc . setFont ( JFaceResources . getDialogFont ( ) ) ; gd . widthHint = gc . textExtent ( fWidthHintString ) . x ; gc . dispose ( ) ; } else if ( fWidthHint != - ) { gd . widthHint = fWidthHint ; } else { gd . widthHint = SWT . DEFAULT ; } return gd ; } public Label getStatusLabelControl ( Composite parent ) { if ( fStatusLabelControl == null ) { assertCompositeNotNull ( parent ) ; fStatusLabelControl = new Label ( parent , SWT . LEFT ) ; fStatusLabelControl . setFont ( parent . getFont ( ) ) ; fStatusLabelControl . setEnabled ( isEnabled ( ) ) ; if ( fStatus instanceof Image ) { fStatusLabelControl . setImage ( ( Image ) fStatus ) ; } else if ( fStatus instanceof String ) { fStatusLabelControl . setText ( ( String ) fStatus ) ; } else { } } return fStatusLabelControl ; } protected void updateEnableState ( ) { super . updateEnableState ( ) ; if ( isOkToUse ( fStatusLabelControl ) ) { fStatusLabelControl . setEnabled ( isEnabled ( ) ) ; } } public void refresh ( ) { super . refresh ( ) ; if ( fStatus instanceof String ) { setStatus ( ( String ) fStatus ) ; } else { setStatus ( ( Image ) fStatus ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . jface . util . Assert ; public class DialogField { private Label fLabel ; protected String fLabelText ; private IDialogFieldListener fDialogFieldListener ; private boolean fEnabled ; public DialogField ( ) { fEnabled = true ; fLabel = null ; fLabelText = "" ; } public void setLabelText ( String labeltext ) { fLabelText = labeltext ; if ( isOkToUse ( fLabel ) ) { fLabel . setText ( labeltext ) ; } } public final void setDialogFieldListener ( IDialogFieldListener listener ) { fDialogFieldListener = listener ; } public void dialogFieldChanged ( ) { if ( fDialogFieldListener != null ) { fDialogFieldListener . dialogFieldChanged ( this ) ; } } public boolean setFocus ( ) { return false ; } public void postSetFocusOnDialogField ( Display display ) { if ( display != null ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { setFocus ( ) ; } } ) ; } } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; Label label = getLabelControl ( parent ) ; label . setLayoutData ( gridDataForLabel ( nColumns ) ) ; return new Control [ ] { label } ; } public int getNumberOfControls ( ) { return ; } protected static GridData gridDataForLabel ( int span ) { GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = span ; return gd ; } public Label getLabelControl ( Composite parent ) { if ( fLabel == null ) { assertCompositeNotNull ( parent ) ; fLabel = new Label ( parent , SWT . LEFT | SWT . WRAP ) ; fLabel . setFont ( parent . getFont ( ) ) ; fLabel . setEnabled ( fEnabled ) ; if ( fLabelText != null && ! "" . equals ( fLabelText ) ) { fLabel . setText ( fLabelText ) ; } else { fLabel . setText ( "" ) ; fLabel . setVisible ( false ) ; } } return fLabel ; } public static Control createEmptySpace ( Composite parent ) { return createEmptySpace ( parent , ) ; } public static Control createEmptySpace ( Composite parent , int span ) { Label label = new Label ( parent , SWT . LEFT ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . BEGINNING ; gd . grabExcessHorizontalSpace = false ; gd . horizontalSpan = span ; gd . horizontalIndent = ; gd . widthHint = ; gd . heightHint = ; label . setLayoutData ( gd ) ; return label ; } protected final boolean isOkToUse ( Control control ) { return ( control != null ) && ( Display . getCurrent ( ) != null ) && ! control . isDisposed ( ) ; } public final void setEnabled ( boolean enabled ) { if ( enabled != fEnabled ) { fEnabled = enabled ; updateEnableState ( ) ; } } protected void updateEnableState ( ) { if ( fLabel != null ) { fLabel . setEnabled ( fEnabled ) ; } } public void refresh ( ) { updateEnableState ( ) ; } public final boolean isEnabled ( ) { return fEnabled ; } protected final void assertCompositeNotNull ( Composite comp ) { Assert . isNotNull ( comp , "" ) ; } protected final void assertEnoughColumns ( int nColumns ) { Assert . isTrue ( nColumns >= getNumberOfControls ( ) , "" ) ; } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Iterator ; import java . util . List ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ColumnLayoutData ; import org . eclipse . jface . viewers . ColumnWeightData ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TableLayout ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . internal . ui . util . TableLayoutComposite ; public class ListDialogField extends DialogField { public static class ColumnsDescription { private ColumnLayoutData [ ] columns ; private String [ ] headers ; private boolean drawLines ; public ColumnsDescription ( ColumnLayoutData [ ] columns , String [ ] headers , boolean drawLines ) { this . columns = columns ; this . headers = headers ; this . drawLines = drawLines ; } public ColumnsDescription ( String [ ] headers , boolean drawLines ) { this ( createColumnWeightData ( headers . length ) , headers , drawLines ) ; } public ColumnsDescription ( int nColumns , boolean drawLines ) { this ( createColumnWeightData ( nColumns ) , null , drawLines ) ; } private static ColumnLayoutData [ ] createColumnWeightData ( int nColumns ) { ColumnLayoutData [ ] data = new ColumnLayoutData [ nColumns ] ; for ( int i = ; i < nColumns ; i ++ ) { data [ i ] = new ColumnWeightData ( ) ; } return data ; } } protected TableViewer fTable ; protected Control fTableControl ; protected ILabelProvider fLabelProvider ; protected ListViewerAdapter fListViewerAdapter ; protected List fElements ; protected ViewerSorter fViewerSorter ; protected String [ ] fButtonLabels ; private Button [ ] fButtonControls ; private boolean [ ] fButtonsEnabled ; private int fRemoveButtonIndex ; private int fUpButtonIndex ; private int fDownButtonIndex ; private Label fLastSeparator ; private Composite fButtonsControl ; private ISelection fSelectionWhenEnabled ; private IListAdapter fListAdapter ; private Object fParentElement ; private ColumnsDescription fTableColumns ; public ListDialogField ( IListAdapter adapter , String [ ] buttonLabels , ILabelProvider lprovider ) { super ( ) ; fListAdapter = adapter ; fLabelProvider = lprovider ; fListViewerAdapter = new ListViewerAdapter ( ) ; fParentElement = this ; fElements = new ArrayList ( ) ; fButtonLabels = buttonLabels ; if ( fButtonLabels != null ) { int nButtons = fButtonLabels . length ; fButtonsEnabled = new boolean [ nButtons ] ; for ( int i = ; i < nButtons ; i ++ ) { fButtonsEnabled [ i ] = true ; } } fTable = null ; fTableControl = null ; fButtonsControl = null ; fTableColumns = null ; fRemoveButtonIndex = - ; fUpButtonIndex = - ; fDownButtonIndex = - ; } public void setRemoveButtonIndex ( int removeButtonIndex ) { Assert . isTrue ( removeButtonIndex < fButtonLabels . length ) ; fRemoveButtonIndex = removeButtonIndex ; } public void setUpButtonIndex ( int upButtonIndex ) { Assert . isTrue ( upButtonIndex < fButtonLabels . length ) ; fUpButtonIndex = upButtonIndex ; } public void setDownButtonIndex ( int downButtonIndex ) { Assert . isTrue ( downButtonIndex < fButtonLabels . length ) ; fDownButtonIndex = downButtonIndex ; } public void editElement ( Object element ) { if ( isOkToUse ( fTableControl ) ) { fTable . refresh ( element ) ; fTable . editElement ( element , ) ; } } public void setViewerSorter ( ViewerSorter viewerSorter ) { fViewerSorter = viewerSorter ; } public void setTableColumns ( ColumnsDescription column ) { fTableColumns = column ; } private void buttonPressed ( int index ) { if ( ! managedButtonPressed ( index ) && fListAdapter != null ) { fListAdapter . customButtonPressed ( this , index ) ; } } protected boolean managedButtonPressed ( int index ) { if ( index == fRemoveButtonIndex ) { remove ( ) ; } else if ( index == fUpButtonIndex ) { up ( ) ; if ( ! fButtonControls [ index ] . isEnabled ( ) && fDownButtonIndex != - ) { fButtonControls [ fDownButtonIndex ] . setFocus ( ) ; } } else if ( index == fDownButtonIndex ) { down ( ) ; if ( ! fButtonControls [ index ] . isEnabled ( ) && fUpButtonIndex != - ) { fButtonControls [ fUpButtonIndex ] . setFocus ( ) ; } } else { return false ; } return true ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { PixelConverter converter = new PixelConverter ( parent ) ; assertEnoughColumns ( nColumns ) ; Label label = getLabelControl ( parent ) ; GridData gd = gridDataForLabel ( ) ; gd . verticalAlignment = GridData . BEGINNING ; label . setLayoutData ( gd ) ; Control list = getListControl ( parent ) ; gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . verticalAlignment = GridData . FILL ; gd . grabExcessVerticalSpace = true ; gd . horizontalSpan = nColumns - ; gd . widthHint = converter . convertWidthInCharsToPixels ( ) ; gd . heightHint = converter . convertHeightInCharsToPixels ( ) ; list . setLayoutData ( gd ) ; Composite buttons = getButtonBox ( parent ) ; gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . verticalAlignment = GridData . FILL ; gd . grabExcessVerticalSpace = true ; gd . horizontalSpan = ; buttons . setLayoutData ( gd ) ; return new Control [ ] { label , list , buttons } ; } public int getNumberOfControls ( ) { return ; } public void setButtonsMinWidth ( int minWidth ) { if ( fLastSeparator != null ) { ( ( GridData ) fLastSeparator . getLayoutData ( ) ) . widthHint = minWidth ; } } public Control getListControl ( Composite parent ) { if ( fTableControl == null ) { assertCompositeNotNull ( parent ) ; if ( fTableColumns == null ) { fTable = createTableViewer ( parent ) ; Table tableControl = fTable . getTable ( ) ; fTableControl = tableControl ; tableControl . setLayout ( new TableLayout ( ) ) ; } else { TableLayoutComposite composite = new TableLayoutComposite ( parent , SWT . NONE ) ; fTableControl = composite ; fTable = createTableViewer ( composite ) ; Table tableControl = fTable . getTable ( ) ; tableControl . setHeaderVisible ( fTableColumns . headers != null ) ; tableControl . setLinesVisible ( fTableColumns . drawLines ) ; ColumnLayoutData [ ] columns = fTableColumns . columns ; for ( int i = ; i < columns . length ; i ++ ) { composite . addColumnData ( columns [ i ] ) ; TableColumn column = new TableColumn ( tableControl , SWT . NONE ) ; if ( fTableColumns . headers != null ) { column . setText ( fTableColumns . headers [ i ] ) ; } } } fTable . getTable ( ) . addKeyListener ( new KeyAdapter ( ) { public void keyPressed ( KeyEvent e ) { handleKeyPressed ( e ) ; } } ) ; fTable . setContentProvider ( fListViewerAdapter ) ; fTable . setLabelProvider ( fLabelProvider ) ; fTable . addSelectionChangedListener ( fListViewerAdapter ) ; fTable . addDoubleClickListener ( fListViewerAdapter ) ; fTable . setInput ( fParentElement ) ; if ( fViewerSorter != null ) { fTable . setSorter ( fViewerSorter ) ; } fTableControl . setEnabled ( isEnabled ( ) ) ; if ( fSelectionWhenEnabled != null ) { postSetSelection ( fSelectionWhenEnabled ) ; } } return fTableControl ; } public TableViewer getTableViewer ( ) { return fTable ; } protected int getListStyle ( ) { int style = SWT . BORDER | SWT . MULTI | SWT . H_SCROLL | SWT . V_SCROLL ; if ( fTableColumns != null ) { style |= SWT . FULL_SELECTION ; } return style ; } protected TableViewer createTableViewer ( Composite parent ) { Table table = new Table ( parent , getListStyle ( ) ) ; return new TableViewer ( table ) ; } protected Button createButton ( Composite parent , String label , SelectionListener listener ) { Button button = new Button ( parent , SWT . PUSH ) ; button . setText ( label ) ; button . addSelectionListener ( listener ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = true ; gd . verticalAlignment = GridData . BEGINNING ; gd . widthHint = SWTUtil . getButtonWidthHint ( button ) ; button . setLayoutData ( gd ) ; return button ; } private Label createSeparator ( Composite parent ) { Label separator = new Label ( parent , SWT . NONE ) ; separator . setVisible ( false ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . verticalAlignment = GridData . BEGINNING ; gd . heightHint = ; separator . setLayoutData ( gd ) ; return separator ; } public Composite getButtonBox ( Composite parent ) { if ( fButtonsControl == null ) { assertCompositeNotNull ( parent ) ; SelectionListener listener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { doButtonSelected ( e ) ; } public void widgetSelected ( SelectionEvent e ) { doButtonSelected ( e ) ; } } ; Composite contents = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . marginWidth = ; layout . marginHeight = ; contents . setLayout ( layout ) ; if ( fButtonLabels != null ) { fButtonControls = new Button [ fButtonLabels . length ] ; for ( int i = ; i < fButtonLabels . length ; i ++ ) { String currLabel = fButtonLabels [ i ] ; if ( currLabel != null ) { fButtonControls [ i ] = createButton ( contents , currLabel , listener ) ; fButtonControls [ i ] . setEnabled ( isEnabled ( ) && fButtonsEnabled [ i ] ) ; } else { fButtonControls [ i ] = null ; createSeparator ( contents ) ; } } } fLastSeparator = createSeparator ( contents ) ; updateButtonState ( ) ; fButtonsControl = contents ; } return fButtonsControl ; } private void doButtonSelected ( SelectionEvent e ) { if ( fButtonControls != null ) { for ( int i = ; i < fButtonControls . length ; i ++ ) { if ( e . widget == fButtonControls [ i ] ) { buttonPressed ( i ) ; return ; } } } } protected void handleKeyPressed ( KeyEvent event ) { if ( event . character == SWT . DEL && event . stateMask == ) { if ( fRemoveButtonIndex != - && isButtonEnabled ( fTable . getSelection ( ) , fRemoveButtonIndex ) ) { managedButtonPressed ( fRemoveButtonIndex ) ; } } } public void dialogFieldChanged ( ) { super . dialogFieldChanged ( ) ; updateButtonState ( ) ; } protected void updateButtonState ( ) { if ( fButtonControls != null && isOkToUse ( fTableControl ) ) { ISelection sel = fTable . getSelection ( ) ; for ( int i = ; i < fButtonControls . length ; i ++ ) { Button button = fButtonControls [ i ] ; if ( isOkToUse ( button ) ) { button . setEnabled ( isButtonEnabled ( sel , i ) ) ; } } } } protected boolean getManagedButtonState ( ISelection sel , int index ) { if ( index == fRemoveButtonIndex ) { return ! sel . isEmpty ( ) ; } else if ( index == fUpButtonIndex ) { return ! sel . isEmpty ( ) && canMoveUp ( ) ; } else if ( index == fDownButtonIndex ) { return ! sel . isEmpty ( ) && canMoveDown ( ) ; } return true ; } protected void updateEnableState ( ) { super . updateEnableState ( ) ; boolean enabled = isEnabled ( ) ; if ( isOkToUse ( fTableControl ) ) { if ( ! enabled ) { fSelectionWhenEnabled = fTable . getSelection ( ) ; selectElements ( null ) ; } else { selectElements ( fSelectionWhenEnabled ) ; fSelectionWhenEnabled = null ; } fTableControl . setEnabled ( enabled ) ; } updateButtonState ( ) ; } public void enableButton ( int index , boolean enable ) { if ( fButtonsEnabled != null && index < fButtonsEnabled . length ) { fButtonsEnabled [ index ] = enable ; updateButtonState ( ) ; } } private boolean isButtonEnabled ( ISelection sel , int index ) { boolean extraState = getManagedButtonState ( sel , index ) ; return isEnabled ( ) && extraState && fButtonsEnabled [ index ] ; } public void setElements ( Collection elements ) { fElements = new ArrayList ( elements ) ; if ( isOkToUse ( fTableControl ) ) { fTable . refresh ( ) ; } dialogFieldChanged ( ) ; } public List getElements ( ) { return new ArrayList ( fElements ) ; } public Object getElement ( int index ) { return fElements . get ( index ) ; } public int getIndexOfElement ( Object elem ) { return fElements . indexOf ( elem ) ; } public void replaceElement ( Object oldElement , Object newElement ) throws IllegalArgumentException { int idx = fElements . indexOf ( oldElement ) ; if ( idx != - ) { fElements . set ( idx , newElement ) ; if ( isOkToUse ( fTableControl ) ) { List selected = getSelectedElements ( ) ; if ( selected . remove ( oldElement ) ) { selected . add ( newElement ) ; } fTable . refresh ( ) ; selectElements ( new StructuredSelection ( selected ) ) ; } dialogFieldChanged ( ) ; } else { throw new IllegalArgumentException ( ) ; } } public boolean addElement ( Object element ) { return addElement ( element , fElements . size ( ) ) ; } public boolean addElement ( Object element , int index ) { if ( fElements . contains ( element ) ) { return false ; } fElements . add ( index , element ) ; if ( isOkToUse ( fTableControl ) ) { fTable . refresh ( ) ; fTable . setSelection ( new StructuredSelection ( element ) ) ; } dialogFieldChanged ( ) ; return true ; } public void addElements ( List elements ) { int nElements = elements . size ( ) ; if ( nElements > ) { ArrayList elementsToAdd = new ArrayList ( nElements ) ; for ( int i = ; i < nElements ; i ++ ) { Object elem = elements . get ( i ) ; if ( ! fElements . contains ( elem ) ) { elementsToAdd . add ( elem ) ; } } fElements . addAll ( elementsToAdd ) ; if ( isOkToUse ( fTableControl ) ) { fTable . add ( elementsToAdd . toArray ( ) ) ; fTable . setSelection ( new StructuredSelection ( elementsToAdd ) ) ; } dialogFieldChanged ( ) ; } } public void removeAllElements ( ) { if ( fElements . size ( ) > ) { fElements . clear ( ) ; if ( isOkToUse ( fTableControl ) ) { fTable . refresh ( ) ; } dialogFieldChanged ( ) ; } } public void removeElement ( Object element ) throws IllegalArgumentException { if ( fElements . remove ( element ) ) { if ( isOkToUse ( fTableControl ) ) { fTable . remove ( element ) ; } dialogFieldChanged ( ) ; } else { throw new IllegalArgumentException ( ) ; } } public void removeElements ( List elements ) { if ( elements . size ( ) > ) { fElements . removeAll ( elements ) ; if ( isOkToUse ( fTableControl ) ) { fTable . remove ( elements . toArray ( ) ) ; } dialogFieldChanged ( ) ; } } public int getSize ( ) { return fElements . size ( ) ; } public void selectElements ( ISelection selection ) { fSelectionWhenEnabled = selection ; if ( isOkToUse ( fTableControl ) ) { fTable . setSelection ( selection , true ) ; } } public void selectFirstElement ( ) { Object element = null ; if ( fViewerSorter != null ) { Object [ ] arr = fElements . toArray ( ) ; fViewerSorter . sort ( fTable , arr ) ; if ( arr . length > ) { element = arr [ ] ; } } else { if ( fElements . size ( ) > ) { element = fElements . get ( ) ; } } if ( element != null ) { selectElements ( new StructuredSelection ( element ) ) ; } } public void postSetSelection ( final ISelection selection ) { if ( isOkToUse ( fTableControl ) ) { Display d = fTableControl . getDisplay ( ) ; d . asyncExec ( new Runnable ( ) { public void run ( ) { if ( isOkToUse ( fTableControl ) ) { selectElements ( selection ) ; } } } ) ; } } public void refresh ( ) { super . refresh ( ) ; if ( isOkToUse ( fTableControl ) ) { fTable . refresh ( ) ; } } private List moveUp ( List elements , List move ) { int nElements = elements . size ( ) ; List res = new ArrayList ( nElements ) ; Object floating = null ; for ( int i = ; i < nElements ; i ++ ) { Object curr = elements . get ( i ) ; if ( move . contains ( curr ) ) { res . add ( curr ) ; } else { if ( floating != null ) { res . add ( floating ) ; } floating = curr ; } } if ( floating != null ) { res . add ( floating ) ; } return res ; } private void moveUp ( List toMoveUp ) { if ( toMoveUp . size ( ) > ) { setElements ( moveUp ( fElements , toMoveUp ) ) ; fTable . reveal ( toMoveUp . get ( ) ) ; } } private void moveDown ( List toMoveDown ) { if ( toMoveDown . size ( ) > ) { setElements ( reverse ( moveUp ( reverse ( fElements ) , toMoveDown ) ) ) ; fTable . reveal ( toMoveDown . get ( toMoveDown . size ( ) - ) ) ; } } private List reverse ( List p ) { List reverse = new ArrayList ( p . size ( ) ) ; for ( int i = p . size ( ) - ; i >= ; i -- ) { reverse . add ( p . get ( i ) ) ; } return reverse ; } private void remove ( ) { removeElements ( getSelectedElements ( ) ) ; } private void up ( ) { moveUp ( getSelectedElements ( ) ) ; } private void down ( ) { moveDown ( getSelectedElements ( ) ) ; } private boolean canMoveUp ( ) { if ( isOkToUse ( fTableControl ) ) { int [ ] indc = fTable . getTable ( ) . getSelectionIndices ( ) ; for ( int i = ; i < indc . length ; i ++ ) { if ( indc [ i ] != i ) { return true ; } } } return false ; } private boolean canMoveDown ( ) { if ( isOkToUse ( fTableControl ) ) { int [ ] indc = fTable . getTable ( ) . getSelectionIndices ( ) ; int k = fElements . size ( ) - ; for ( int i = indc . length - ; i >= ; i -- , k -- ) { if ( indc [ i ] != k ) { return true ; } } } return false ; } public List getSelectedElements ( ) { List result = new ArrayList ( ) ; if ( isOkToUse ( fTableControl ) ) { ISelection selection = fTable . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { Iterator iter = ( ( IStructuredSelection ) selection ) . iterator ( ) ; while ( iter . hasNext ( ) ) { result . add ( iter . next ( ) ) ; } } } return result ; } private class ListViewerAdapter implements IStructuredContentProvider , ISelectionChangedListener , IDoubleClickListener { public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public boolean isDeleted ( Object element ) { return false ; } public void dispose ( ) { } public Object [ ] getElements ( Object obj ) { return fElements . toArray ( ) ; } public void selectionChanged ( SelectionChangedEvent event ) { doListSelected ( event ) ; } public void doubleClick ( DoubleClickEvent event ) { doDoubleClick ( event ) ; } } protected void doListSelected ( SelectionChangedEvent event ) { updateButtonState ( ) ; if ( fListAdapter != null ) { fListAdapter . selectionChanged ( this ) ; } } protected void doDoubleClick ( DoubleClickEvent event ) { if ( fListAdapter != null ) { fListAdapter . doubleClicked ( this ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Table ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . TableViewer ; public class CheckedListDialogField extends ListDialogField { private int fCheckAllButtonIndex ; private int fUncheckAllButtonIndex ; private List fCheckedElements ; private List fGrayedElements ; public CheckedListDialogField ( IListAdapter adapter , String [ ] customButtonLabels , ILabelProvider lprovider ) { super ( adapter , customButtonLabels , lprovider ) ; fCheckedElements = new ArrayList ( ) ; fGrayedElements = new ArrayList ( ) ; fCheckAllButtonIndex = - ; fUncheckAllButtonIndex = - ; } public void setCheckAllButtonIndex ( int checkButtonIndex ) { Assert . isTrue ( checkButtonIndex < fButtonLabels . length ) ; fCheckAllButtonIndex = checkButtonIndex ; } public void setUncheckAllButtonIndex ( int uncheckButtonIndex ) { Assert . isTrue ( uncheckButtonIndex < fButtonLabels . length ) ; fUncheckAllButtonIndex = uncheckButtonIndex ; } protected TableViewer createTableViewer ( Composite parent ) { Table table = new Table ( parent , SWT . CHECK + getListStyle ( ) ) ; table . setFont ( parent . getFont ( ) ) ; CheckboxTableViewer tableViewer = new CheckboxTableViewer ( table ) ; tableViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent e ) { doCheckStateChanged ( e ) ; } } ) ; return tableViewer ; } public Control getListControl ( Composite parent ) { Control control = super . getListControl ( parent ) ; if ( parent != null ) { ( ( CheckboxTableViewer ) fTable ) . setCheckedElements ( fCheckedElements . toArray ( ) ) ; ( ( CheckboxTableViewer ) fTable ) . setGrayedElements ( fGrayedElements . toArray ( ) ) ; } return control ; } public void dialogFieldChanged ( ) { for ( int i = fCheckedElements . size ( ) - ; i >= ; i -- ) { if ( ! fElements . contains ( fCheckedElements . get ( i ) ) ) { fCheckedElements . remove ( i ) ; } } super . dialogFieldChanged ( ) ; } private void checkStateChanged ( ) { super . dialogFieldChanged ( ) ; } public List getCheckedElements ( ) { if ( isOkToUse ( fTableControl ) ) { Object [ ] checked = ( ( CheckboxTableViewer ) fTable ) . getCheckedElements ( ) ; ArrayList res = new ArrayList ( checked . length ) ; for ( int i = ; i < checked . length ; i ++ ) { res . add ( checked [ i ] ) ; } return res ; } return new ArrayList ( fCheckedElements ) ; } public int getCheckedSize ( ) { return fCheckedElements . size ( ) ; } public boolean isChecked ( Object obj ) { if ( isOkToUse ( fTableControl ) ) { return ( ( CheckboxTableViewer ) fTable ) . getChecked ( obj ) ; } return fCheckedElements . contains ( obj ) ; } public boolean isGrayed ( Object obj ) { if ( isOkToUse ( fTableControl ) ) { return ( ( CheckboxTableViewer ) fTable ) . getGrayed ( obj ) ; } return fGrayedElements . contains ( obj ) ; } public void setCheckedElements ( Collection list ) { fCheckedElements = new ArrayList ( list ) ; if ( isOkToUse ( fTableControl ) ) { ( ( CheckboxTableViewer ) fTable ) . setCheckedElements ( list . toArray ( ) ) ; } checkStateChanged ( ) ; } public void setChecked ( Object object , boolean state ) { setCheckedWithoutUpdate ( object , state ) ; checkStateChanged ( ) ; } public void setCheckedWithoutUpdate ( Object object , boolean state ) { if ( state ) { if ( ! fCheckedElements . contains ( object ) ) { fCheckedElements . add ( object ) ; } } else { fCheckedElements . remove ( object ) ; } if ( isOkToUse ( fTableControl ) ) { ( ( CheckboxTableViewer ) fTable ) . setChecked ( object , state ) ; } } public void setGrayedWithoutUpdate ( Object object , boolean state ) { if ( state ) { if ( ! fGrayedElements . contains ( object ) ) { fGrayedElements . add ( object ) ; } } else { fGrayedElements . remove ( object ) ; } if ( isOkToUse ( fTableControl ) ) { ( ( CheckboxTableViewer ) fTable ) . setGrayed ( object , state ) ; } } public void checkAll ( boolean state ) { if ( state ) { fCheckedElements = getElements ( ) ; } else { fCheckedElements . clear ( ) ; } if ( isOkToUse ( fTableControl ) ) { ( ( CheckboxTableViewer ) fTable ) . setAllChecked ( state ) ; } checkStateChanged ( ) ; } private void doCheckStateChanged ( CheckStateChangedEvent e ) { if ( e . getChecked ( ) ) { fCheckedElements . add ( e . getElement ( ) ) ; } else { fCheckedElements . remove ( e . getElement ( ) ) ; } checkStateChanged ( ) ; } public void replaceElement ( Object oldElement , Object newElement ) throws IllegalArgumentException { boolean wasChecked = isChecked ( oldElement ) ; super . replaceElement ( oldElement , newElement ) ; setChecked ( newElement , wasChecked ) ; } protected boolean getManagedButtonState ( ISelection sel , int index ) { if ( index == fCheckAllButtonIndex ) { return ! fElements . isEmpty ( ) ; } else if ( index == fUncheckAllButtonIndex ) { return ! fElements . isEmpty ( ) ; } return super . getManagedButtonState ( sel , index ) ; } protected boolean managedButtonPressed ( int index ) { if ( index == fCheckAllButtonIndex ) { checkAll ( true ) ; } else if ( index == fUncheckAllButtonIndex ) { checkAll ( false ) ; } else { return super . managedButtonPressed ( index ) ; } return true ; } public void refresh ( ) { super . refresh ( ) ; if ( isOkToUse ( fTableControl ) ) { ( ( CheckboxTableViewer ) fTable ) . setCheckedElements ( fCheckedElements . toArray ( ) ) ; ( ( CheckboxTableViewer ) fTable ) . setGrayedElements ( fGrayedElements . toArray ( ) ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Tree ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; public class TreeListDialogField extends DialogField { protected TreeViewer fTree ; protected ILabelProvider fLabelProvider ; protected TreeViewerAdapter fTreeViewerAdapter ; protected List fElements ; protected ViewerSorter fViewerSorter ; protected String [ ] fButtonLabels ; private Button [ ] fButtonControls ; private boolean [ ] fButtonsEnabled ; private int fRemoveButtonIndex ; private int fUpButtonIndex ; private int fDownButtonIndex ; private Label fLastSeparator ; private Tree fTreeControl ; private Composite fButtonsControl ; private ISelection fSelectionWhenEnabled ; private ITreeListAdapter fTreeAdapter ; private Object fParentElement ; private int fTreeExpandLevel ; public TreeListDialogField ( ITreeListAdapter adapter , String [ ] buttonLabels , ILabelProvider lprovider ) { super ( ) ; fTreeAdapter = adapter ; fLabelProvider = lprovider ; fTreeViewerAdapter = new TreeViewerAdapter ( ) ; fParentElement = this ; fElements = new ArrayList ( ) ; fButtonLabels = buttonLabels ; if ( fButtonLabels != null ) { int nButtons = fButtonLabels . length ; fButtonsEnabled = new boolean [ nButtons ] ; for ( int i = ; i < nButtons ; i ++ ) { fButtonsEnabled [ i ] = true ; } } fTree = null ; fTreeControl = null ; fButtonsControl = null ; fRemoveButtonIndex = - ; fUpButtonIndex = - ; fDownButtonIndex = - ; fTreeExpandLevel = ; } public void setRemoveButtonIndex ( int removeButtonIndex ) { Assert . isTrue ( removeButtonIndex < fButtonLabels . length ) ; fRemoveButtonIndex = removeButtonIndex ; } public void setUpButtonIndex ( int upButtonIndex ) { Assert . isTrue ( upButtonIndex < fButtonLabels . length ) ; fUpButtonIndex = upButtonIndex ; } public void setDownButtonIndex ( int downButtonIndex ) { Assert . isTrue ( downButtonIndex < fButtonLabels . length ) ; fDownButtonIndex = downButtonIndex ; } public void setViewerSorter ( ViewerSorter viewerSorter ) { fViewerSorter = viewerSorter ; } public void setTreeExpansionLevel ( int level ) { fTreeExpandLevel = level ; if ( isOkToUse ( fTreeControl ) && fTreeExpandLevel > ) { fTree . expandToLevel ( level ) ; } } private void buttonPressed ( int index ) { if ( ! managedButtonPressed ( index ) && fTreeAdapter != null ) { fTreeAdapter . customButtonPressed ( this , index ) ; } } protected boolean managedButtonPressed ( int index ) { if ( index == fRemoveButtonIndex ) { remove ( ) ; } else if ( index == fUpButtonIndex ) { up ( ) ; } else if ( index == fDownButtonIndex ) { down ( ) ; } else { return false ; } return true ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { PixelConverter converter = new PixelConverter ( parent ) ; assertEnoughColumns ( nColumns ) ; Label label = getLabelControl ( parent ) ; GridData gd = gridDataForLabel ( ) ; gd . verticalAlignment = GridData . BEGINNING ; label . setLayoutData ( gd ) ; Control list = getTreeControl ( parent ) ; gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . verticalAlignment = GridData . FILL ; gd . grabExcessVerticalSpace = true ; gd . horizontalSpan = nColumns - ; gd . widthHint = converter . convertWidthInCharsToPixels ( ) ; gd . heightHint = converter . convertHeightInCharsToPixels ( ) ; list . setLayoutData ( gd ) ; Composite buttons = getButtonBox ( parent ) ; gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . verticalAlignment = GridData . FILL ; gd . grabExcessVerticalSpace = true ; gd . horizontalSpan = ; buttons . setLayoutData ( gd ) ; return new Control [ ] { label , list , buttons } ; } public int getNumberOfControls ( ) { return ; } public void setButtonsMinWidth ( int minWidth ) { if ( fLastSeparator != null ) { ( ( GridData ) fLastSeparator . getLayoutData ( ) ) . widthHint = minWidth ; } } public Control getTreeControl ( Composite parent ) { if ( fTreeControl == null ) { assertCompositeNotNull ( parent ) ; fTree = createTreeViewer ( parent ) ; fTreeControl = ( Tree ) fTree . getControl ( ) ; fTreeControl . addKeyListener ( new KeyAdapter ( ) { public void keyPressed ( KeyEvent e ) { handleKeyPressed ( e ) ; } } ) ; fTree . setContentProvider ( fTreeViewerAdapter ) ; fTree . setLabelProvider ( fLabelProvider ) ; fTree . addSelectionChangedListener ( fTreeViewerAdapter ) ; fTree . addDoubleClickListener ( fTreeViewerAdapter ) ; fTree . setInput ( fParentElement ) ; fTree . expandToLevel ( fTreeExpandLevel ) ; if ( fViewerSorter != null ) { fTree . setSorter ( fViewerSorter ) ; } fTreeControl . setEnabled ( isEnabled ( ) ) ; if ( fSelectionWhenEnabled != null ) { postSetSelection ( fSelectionWhenEnabled ) ; } } return fTreeControl ; } public TreeViewer getTreeViewer ( ) { return fTree ; } protected int getTreeStyle ( ) { int style = SWT . BORDER | SWT . MULTI | SWT . H_SCROLL | SWT . V_SCROLL ; return style ; } protected TreeViewer createTreeViewer ( Composite parent ) { Tree tree = new Tree ( parent , getTreeStyle ( ) ) ; tree . setFont ( parent . getFont ( ) ) ; return new TreeViewer ( tree ) ; } protected Button createButton ( Composite parent , String label , SelectionListener listener ) { Button button = new Button ( parent , SWT . PUSH ) ; button . setFont ( parent . getFont ( ) ) ; button . setText ( label ) ; button . addSelectionListener ( listener ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = true ; gd . verticalAlignment = GridData . BEGINNING ; gd . widthHint = SWTUtil . getButtonWidthHint ( button ) ; button . setLayoutData ( gd ) ; return button ; } private Label createSeparator ( Composite parent ) { Label separator = new Label ( parent , SWT . NONE ) ; separator . setFont ( parent . getFont ( ) ) ; separator . setVisible ( false ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . verticalAlignment = GridData . BEGINNING ; gd . heightHint = ; separator . setLayoutData ( gd ) ; return separator ; } public Composite getButtonBox ( Composite parent ) { if ( fButtonsControl == null ) { assertCompositeNotNull ( parent ) ; SelectionListener listener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { doButtonSelected ( e ) ; } public void widgetSelected ( SelectionEvent e ) { doButtonSelected ( e ) ; } } ; Composite contents = new Composite ( parent , SWT . NONE ) ; contents . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginWidth = ; layout . marginHeight = ; contents . setLayout ( layout ) ; if ( fButtonLabels != null ) { fButtonControls = new Button [ fButtonLabels . length ] ; for ( int i = ; i < fButtonLabels . length ; i ++ ) { String currLabel = fButtonLabels [ i ] ; if ( currLabel != null ) { fButtonControls [ i ] = createButton ( contents , currLabel , listener ) ; fButtonControls [ i ] . setEnabled ( isEnabled ( ) && fButtonsEnabled [ i ] ) ; } else { fButtonControls [ i ] = null ; createSeparator ( contents ) ; } } } fLastSeparator = createSeparator ( contents ) ; updateButtonState ( ) ; fButtonsControl = contents ; } return fButtonsControl ; } private void doButtonSelected ( SelectionEvent e ) { if ( fButtonControls != null ) { for ( int i = ; i < fButtonControls . length ; i ++ ) { if ( e . widget == fButtonControls [ i ] ) { buttonPressed ( i ) ; return ; } } } } protected void handleKeyPressed ( KeyEvent event ) { if ( event . character == SWT . DEL && event . stateMask == ) { if ( fRemoveButtonIndex != - && isButtonEnabled ( fTree . getSelection ( ) , fRemoveButtonIndex ) ) { managedButtonPressed ( fRemoveButtonIndex ) ; return ; } } fTreeAdapter . keyPressed ( this , event ) ; } public void dialogFieldChanged ( ) { super . dialogFieldChanged ( ) ; updateButtonState ( ) ; } protected void updateButtonState ( ) { if ( fButtonControls != null && isOkToUse ( fTreeControl ) && fTreeControl . isEnabled ( ) ) { ISelection sel = fTree . getSelection ( ) ; for ( int i = ; i < fButtonControls . length ; i ++ ) { Button button = fButtonControls [ i ] ; if ( isOkToUse ( button ) ) { button . setEnabled ( isButtonEnabled ( sel , i ) ) ; } } } } protected boolean containsAttributes ( List selected ) { for ( int i = ; i < selected . size ( ) ; i ++ ) { if ( ! fElements . contains ( selected . get ( i ) ) ) { return true ; } } return false ; } protected boolean getManagedButtonState ( ISelection sel , int index ) { List selected = getSelectedElements ( ) ; boolean hasAttributes = containsAttributes ( selected ) ; if ( index == fRemoveButtonIndex ) { return ! selected . isEmpty ( ) && ! hasAttributes ; } else if ( index == fUpButtonIndex ) { return ! sel . isEmpty ( ) && ! hasAttributes && canMoveUp ( selected ) ; } else if ( index == fDownButtonIndex ) { return ! sel . isEmpty ( ) && ! hasAttributes && canMoveDown ( selected ) ; } return true ; } protected void updateEnableState ( ) { super . updateEnableState ( ) ; boolean enabled = isEnabled ( ) ; if ( isOkToUse ( fTreeControl ) ) { if ( ! enabled ) { fSelectionWhenEnabled = fTree . getSelection ( ) ; selectElements ( null ) ; } else { selectElements ( fSelectionWhenEnabled ) ; fSelectionWhenEnabled = null ; } fTreeControl . setEnabled ( enabled ) ; } updateButtonState ( ) ; } public void enableButton ( int index , boolean enable ) { if ( fButtonsEnabled != null && index < fButtonsEnabled . length ) { fButtonsEnabled [ index ] = enable ; updateButtonState ( ) ; } } private boolean isButtonEnabled ( ISelection sel , int index ) { boolean extraState = getManagedButtonState ( sel , index ) ; return isEnabled ( ) && extraState && fButtonsEnabled [ index ] ; } public void setElements ( List elements ) { fElements = new ArrayList ( elements ) ; refresh ( ) ; if ( isOkToUse ( fTreeControl ) ) { fTree . expandToLevel ( fTreeExpandLevel ) ; } dialogFieldChanged ( ) ; } public List getElements ( ) { return new ArrayList ( fElements ) ; } public Object getElement ( int index ) { return fElements . get ( index ) ; } public int getIndexOfElement ( Object elem ) { return fElements . indexOf ( elem ) ; } public void replaceElement ( Object oldElement , Object newElement ) throws IllegalArgumentException { int idx = fElements . indexOf ( oldElement ) ; if ( idx != - ) { fElements . set ( idx , newElement ) ; if ( isOkToUse ( fTreeControl ) ) { List selected = getSelectedElements ( ) ; if ( selected . remove ( oldElement ) ) { selected . add ( newElement ) ; } boolean isExpanded = fTree . getExpandedState ( oldElement ) ; fTree . remove ( oldElement ) ; fTree . add ( fParentElement , newElement ) ; if ( isExpanded ) { fTree . expandToLevel ( newElement , fTreeExpandLevel ) ; } selectElements ( new StructuredSelection ( selected ) ) ; } dialogFieldChanged ( ) ; } else { throw new IllegalArgumentException ( ) ; } } public boolean addElement ( Object element ) { if ( fElements . contains ( element ) ) { return false ; } fElements . add ( element ) ; if ( isOkToUse ( fTreeControl ) ) { fTree . add ( fParentElement , element ) ; fTree . expandToLevel ( element , fTreeExpandLevel ) ; } dialogFieldChanged ( ) ; return true ; } public boolean addElements ( List elements ) { int nElements = elements . size ( ) ; if ( nElements > ) { ArrayList elementsToAdd = new ArrayList ( nElements ) ; for ( int i = ; i < nElements ; i ++ ) { Object elem = elements . get ( i ) ; if ( ! fElements . contains ( elem ) ) { elementsToAdd . add ( elem ) ; } } if ( ! elementsToAdd . isEmpty ( ) ) { fElements . addAll ( elementsToAdd ) ; if ( isOkToUse ( fTreeControl ) ) { fTree . add ( fParentElement , elementsToAdd . toArray ( ) ) ; for ( int i = ; i < elementsToAdd . size ( ) ; i ++ ) { fTree . expandToLevel ( elementsToAdd . get ( i ) , fTreeExpandLevel ) ; } } dialogFieldChanged ( ) ; return true ; } } return false ; } public void insertElementAt ( Object element , int index ) { if ( fElements . contains ( element ) ) { return ; } fElements . add ( index , element ) ; if ( isOkToUse ( fTreeControl ) ) { fTree . add ( fParentElement , element ) ; if ( fTreeExpandLevel != - ) { fTree . expandToLevel ( element , fTreeExpandLevel ) ; } } dialogFieldChanged ( ) ; } public void removeAllElements ( ) { if ( fElements . size ( ) > ) { fElements . clear ( ) ; refresh ( ) ; dialogFieldChanged ( ) ; } } public void removeElement ( Object element ) throws IllegalArgumentException { if ( fElements . remove ( element ) ) { if ( isOkToUse ( fTreeControl ) ) { fTree . remove ( element ) ; } dialogFieldChanged ( ) ; } else { throw new IllegalArgumentException ( ) ; } } public void removeElements ( List elements ) { if ( elements . size ( ) > ) { fElements . removeAll ( elements ) ; if ( isOkToUse ( fTreeControl ) ) { fTree . remove ( elements . toArray ( ) ) ; } dialogFieldChanged ( ) ; } } public int getSize ( ) { return fElements . size ( ) ; } public void selectElements ( ISelection selection ) { fSelectionWhenEnabled = selection ; if ( isOkToUse ( fTreeControl ) ) { fTree . setSelection ( selection , true ) ; } } public void selectFirstElement ( ) { Object element = null ; if ( fViewerSorter != null ) { Object [ ] arr = fElements . toArray ( ) ; fViewerSorter . sort ( fTree , arr ) ; if ( arr . length > ) { element = arr [ ] ; } } else { if ( fElements . size ( ) > ) { element = fElements . get ( ) ; } } if ( element != null ) { selectElements ( new StructuredSelection ( element ) ) ; } } public void postSetSelection ( final ISelection selection ) { if ( isOkToUse ( fTreeControl ) ) { Display d = fTreeControl . getDisplay ( ) ; d . asyncExec ( new Runnable ( ) { public void run ( ) { if ( isOkToUse ( fTreeControl ) ) { selectElements ( selection ) ; } } } ) ; } } public void refresh ( ) { super . refresh ( ) ; if ( isOkToUse ( fTreeControl ) ) { fTree . refresh ( ) ; } } public void refresh ( Object element ) { if ( isOkToUse ( fTreeControl ) ) { fTree . refresh ( element ) ; } } public void update ( Object element ) { if ( isOkToUse ( fTreeControl ) ) { fTree . update ( element , null ) ; } } private List moveUp ( List elements , List move ) { int nElements = elements . size ( ) ; List res = new ArrayList ( nElements ) ; Object floating = null ; for ( int i = ; i < nElements ; i ++ ) { Object curr = elements . get ( i ) ; if ( move . contains ( curr ) ) { res . add ( curr ) ; } else { if ( floating != null ) { res . add ( floating ) ; } floating = curr ; } } if ( floating != null ) { res . add ( floating ) ; } return res ; } private void moveUp ( List toMoveUp ) { if ( toMoveUp . size ( ) > ) { setElements ( moveUp ( fElements , toMoveUp ) ) ; fTree . reveal ( toMoveUp . get ( ) ) ; } } private void moveDown ( List toMoveDown ) { if ( toMoveDown . size ( ) > ) { setElements ( reverse ( moveUp ( reverse ( fElements ) , toMoveDown ) ) ) ; fTree . reveal ( toMoveDown . get ( toMoveDown . size ( ) - ) ) ; } } private List reverse ( List p ) { List reverse = new ArrayList ( p . size ( ) ) ; for ( int i = p . size ( ) - ; i >= ; i -- ) { reverse . add ( p . get ( i ) ) ; } return reverse ; } private void remove ( ) { removeElements ( getSelectedElements ( ) ) ; } private void up ( ) { moveUp ( getSelectedElements ( ) ) ; } private void down ( ) { moveDown ( getSelectedElements ( ) ) ; } private boolean canMoveUp ( List selectedElements ) { if ( isOkToUse ( fTreeControl ) ) { int nSelected = selectedElements . size ( ) ; int nElements = fElements . size ( ) ; for ( int i = ; i < nElements && nSelected > ; i ++ ) { if ( ! selectedElements . contains ( fElements . get ( i ) ) ) { return true ; } nSelected -- ; } } return false ; } private boolean canMoveDown ( List selectedElements ) { if ( isOkToUse ( fTreeControl ) ) { int nSelected = selectedElements . size ( ) ; for ( int i = fElements . size ( ) - ; i >= && nSelected > ; i -- ) { if ( ! selectedElements . contains ( fElements . get ( i ) ) ) { return true ; } nSelected -- ; } } return false ; } public List getSelectedElements ( ) { ArrayList result = new ArrayList ( ) ; if ( isOkToUse ( fTreeControl ) ) { ISelection selection = fTree . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { Iterator iter = ( ( IStructuredSelection ) selection ) . iterator ( ) ; while ( iter . hasNext ( ) ) { result . add ( iter . next ( ) ) ; } } } return result ; } public void expandElement ( Object element , int level ) { if ( isOkToUse ( fTreeControl ) ) { fTree . expandToLevel ( element , level ) ; } } private class TreeViewerAdapter implements ITreeContentProvider , ISelectionChangedListener , IDoubleClickListener { private final Object [ ] NO_ELEMENTS = new Object [ ] ; public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public boolean isDeleted ( Object element ) { return false ; } public void dispose ( ) { } public Object [ ] getElements ( Object obj ) { return fElements . toArray ( ) ; } public Object [ ] getChildren ( Object element ) { if ( fTreeAdapter != null ) { return fTreeAdapter . getChildren ( TreeListDialogField . this , element ) ; } return NO_ELEMENTS ; } public Object getParent ( Object element ) { if ( ! fElements . contains ( element ) && fTreeAdapter != null ) { return fTreeAdapter . getParent ( TreeListDialogField . this , element ) ; } return fParentElement ; } public boolean hasChildren ( Object element ) { if ( fTreeAdapter != null ) { return fTreeAdapter . hasChildren ( TreeListDialogField . this , element ) ; } return false ; } public void selectionChanged ( SelectionChangedEvent event ) { doListSelected ( event ) ; } public void doubleClick ( DoubleClickEvent event ) { doDoubleClick ( event ) ; } } protected void doListSelected ( SelectionChangedEvent event ) { updateButtonState ( ) ; if ( fTreeAdapter != null ) { fTreeAdapter . selectionChanged ( this ) ; } } protected void doDoubleClick ( DoubleClickEvent event ) { if ( fTreeAdapter != null ) { fTreeAdapter . doubleClicked ( this ) ; } } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . layout . GridData ; public class Separator extends DialogField { private Label fSeparator ; private int fStyle ; public Separator ( ) { this ( SWT . NONE ) ; } public Separator ( int style ) { super ( ) ; fStyle = style ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns , int height ) { assertEnoughColumns ( nColumns ) ; Control separator = getSeparator ( parent ) ; separator . setLayoutData ( gridDataForSeperator ( nColumns , height ) ) ; return new Control [ ] { separator } ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { return doFillIntoGrid ( parent , nColumns , ) ; } public int getNumberOfControls ( ) { return ; } protected static GridData gridDataForSeperator ( int span , int height ) { GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . verticalAlignment = GridData . BEGINNING ; gd . heightHint = height ; gd . horizontalSpan = span ; return gd ; } public Control getSeparator ( Composite parent ) { if ( fSeparator == null ) { assertCompositeNotNull ( parent ) ; fSeparator = new Label ( parent , fStyle ) ; } return fSeparator ; } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . core . runtime . Assert ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; public class SelectionButtonDialogFieldGroup extends DialogField { private Composite fButtonComposite ; private Button [ ] fButtons ; private String [ ] fButtonNames ; private boolean [ ] fButtonsSelected ; private boolean [ ] fButtonsEnabled ; private int fGroupBorderStyle ; private int fGroupNumberOfColumns ; private int fButtonsStyle ; public SelectionButtonDialogFieldGroup ( int buttonsStyle , String [ ] buttonNames , int nColumns ) { this ( buttonsStyle , buttonNames , nColumns , SWT . NONE ) ; } public SelectionButtonDialogFieldGroup ( int buttonsStyle , String [ ] buttonNames , int nColumns , int borderStyle ) { super ( ) ; Assert . isTrue ( buttonsStyle == SWT . RADIO || buttonsStyle == SWT . CHECK || buttonsStyle == SWT . TOGGLE ) ; fButtonNames = buttonNames ; fButtonsStyle = buttonsStyle ; int nButtons = buttonNames . length ; fButtonsSelected = new boolean [ nButtons ] ; fButtonsEnabled = new boolean [ nButtons ] ; for ( int i = ; i < nButtons ; i ++ ) { fButtonsSelected [ i ] = false ; fButtonsEnabled [ i ] = true ; } if ( buttonsStyle == SWT . RADIO ) { fButtonsSelected [ ] = true ; } fGroupBorderStyle = borderStyle ; fGroupNumberOfColumns = ( nColumns <= ) ? nButtons : nColumns ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; if ( fGroupBorderStyle == SWT . NONE ) { Label label = getLabelControl ( parent ) ; label . setLayoutData ( gridDataForLabel ( ) ) ; Composite buttonsgroup = getSelectionButtonsGroup ( parent ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = nColumns - ; buttonsgroup . setLayoutData ( gd ) ; return new Control [ ] { label , buttonsgroup } ; } else { Composite buttonsgroup = getSelectionButtonsGroup ( parent ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = nColumns ; buttonsgroup . setLayoutData ( gd ) ; return new Control [ ] { buttonsgroup } ; } } public int getNumberOfControls ( ) { return ( fGroupBorderStyle == SWT . NONE ) ? : ; } private Button createSelectionButton ( int index , Composite group , SelectionListener listener ) { Button button = new Button ( group , fButtonsStyle | SWT . LEFT ) ; button . setFont ( group . getFont ( ) ) ; button . setText ( fButtonNames [ index ] ) ; button . setEnabled ( isEnabled ( ) && fButtonsEnabled [ index ] ) ; button . setSelection ( fButtonsSelected [ index ] ) ; button . addSelectionListener ( listener ) ; button . setLayoutData ( new GridData ( ) ) ; return button ; } public Composite getSelectionButtonsGroup ( Composite parent ) { if ( fButtonComposite == null ) { assertCompositeNotNull ( parent ) ; GridLayout layout = new GridLayout ( ) ; layout . makeColumnsEqualWidth = true ; layout . numColumns = fGroupNumberOfColumns ; if ( fGroupBorderStyle != SWT . NONE ) { Group group = new Group ( parent , fGroupBorderStyle ) ; group . setFont ( parent . getFont ( ) ) ; if ( fLabelText != null && fLabelText . length ( ) > ) { group . setText ( fLabelText ) ; } fButtonComposite = group ; } else { fButtonComposite = new Composite ( parent , SWT . NONE ) ; fButtonComposite . setFont ( parent . getFont ( ) ) ; layout . marginHeight = ; layout . marginWidth = ; } fButtonComposite . setLayout ( layout ) ; SelectionListener listener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { doWidgetSelected ( e ) ; } public void widgetSelected ( SelectionEvent e ) { doWidgetSelected ( e ) ; } } ; int nButtons = fButtonNames . length ; fButtons = new Button [ nButtons ] ; for ( int i = ; i < nButtons ; i ++ ) { fButtons [ i ] = createSelectionButton ( i , fButtonComposite , listener ) ; } int nRows = nButtons / fGroupNumberOfColumns ; int nFillElements = nRows * fGroupNumberOfColumns - nButtons ; for ( int i = ; i < nFillElements ; i ++ ) { createEmptySpace ( fButtonComposite ) ; } } return fButtonComposite ; } public Button getSelectionButton ( int index ) { if ( index >= && index < fButtons . length ) { return fButtons [ index ] ; } return null ; } private void doWidgetSelected ( SelectionEvent e ) { Button button = ( Button ) e . widget ; for ( int i = ; i < fButtons . length ; i ++ ) { if ( fButtons [ i ] == button ) { fButtonsSelected [ i ] = button . getSelection ( ) ; dialogFieldChanged ( ) ; return ; } } } public boolean isSelected ( int index ) { if ( index >= && index < fButtonsSelected . length ) { return fButtonsSelected [ index ] ; } return false ; } public void setSelection ( int index , boolean selected ) { if ( index >= && index < fButtonsSelected . length ) { if ( fButtonsSelected [ index ] != selected ) { fButtonsSelected [ index ] = selected ; if ( fButtons != null ) { Button button = fButtons [ index ] ; if ( isOkToUse ( button ) ) { button . setSelection ( selected ) ; } } } } } protected void updateEnableState ( ) { super . updateEnableState ( ) ; if ( fButtons != null ) { boolean enabled = isEnabled ( ) ; for ( int i = ; i < fButtons . length ; i ++ ) { Button button = fButtons [ i ] ; if ( isOkToUse ( button ) ) { button . setEnabled ( enabled && fButtonsEnabled [ i ] ) ; } } } } public void enableSelectionButton ( int index , boolean enable ) { if ( index >= && index < fButtonsEnabled . length ) { fButtonsEnabled [ index ] = enable ; if ( fButtons != null ) { Button button = fButtons [ index ] ; if ( isOkToUse ( button ) ) { button . setEnabled ( isEnabled ( ) && enable ) ; } } } } public void refresh ( ) { super . refresh ( ) ; for ( int i = ; i < fButtons . length ; i ++ ) { Button button = fButtons [ i ] ; if ( isOkToUse ( button ) ) { button . setSelection ( fButtonsSelected [ i ] ) ; } } } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; public class ComboDialogField extends DialogField { private String fText ; private int fSelectionIndex ; private String [ ] fItems ; private Combo fComboControl ; private ModifyListener fModifyListener ; private int fFlags ; public ComboDialogField ( int flags ) { super ( ) ; fText = "" ; fItems = new String [ ] ; fFlags = flags ; fSelectionIndex = - ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; Label label = getLabelControl ( parent ) ; label . setLayoutData ( gridDataForLabel ( ) ) ; Combo combo = getComboControl ( parent ) ; combo . setLayoutData ( gridDataForCombo ( nColumns - ) ) ; return new Control [ ] { label , combo } ; } public int getNumberOfControls ( ) { return ; } protected static GridData gridDataForCombo ( int span ) { GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . horizontalSpan = span ; return gd ; } public boolean setFocus ( ) { if ( isOkToUse ( fComboControl ) ) { fComboControl . setFocus ( ) ; } return true ; } public Combo getComboControl ( Composite parent ) { if ( fComboControl == null ) { assertCompositeNotNull ( parent ) ; fModifyListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { doModifyText ( e ) ; } } ; SelectionListener selectionListener = new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { doSelectionChanged ( e ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ; fComboControl = new Combo ( parent , fFlags ) ; fComboControl . setItems ( fItems ) ; if ( fSelectionIndex != - ) { fComboControl . select ( fSelectionIndex ) ; } else { fComboControl . setText ( fText ) ; } fComboControl . setFont ( parent . getFont ( ) ) ; fComboControl . addModifyListener ( fModifyListener ) ; fComboControl . addSelectionListener ( selectionListener ) ; fComboControl . setEnabled ( isEnabled ( ) ) ; } return fComboControl ; } private void doModifyText ( ModifyEvent e ) { if ( isOkToUse ( fComboControl ) ) { fText = fComboControl . getText ( ) ; fSelectionIndex = fComboControl . getSelectionIndex ( ) ; } dialogFieldChanged ( ) ; } private void doSelectionChanged ( SelectionEvent e ) { if ( isOkToUse ( fComboControl ) ) { fItems = fComboControl . getItems ( ) ; fText = fComboControl . getText ( ) ; fSelectionIndex = fComboControl . getSelectionIndex ( ) ; } dialogFieldChanged ( ) ; } protected void updateEnableState ( ) { super . updateEnableState ( ) ; if ( isOkToUse ( fComboControl ) ) { fComboControl . setEnabled ( isEnabled ( ) ) ; } } public String [ ] getItems ( ) { return fItems ; } public void setItems ( String [ ] items ) { fItems = items ; if ( isOkToUse ( fComboControl ) ) { fComboControl . setItems ( items ) ; } dialogFieldChanged ( ) ; } public String getText ( ) { return fText ; } public void setText ( String text ) { fText = text ; if ( isOkToUse ( fComboControl ) ) { fComboControl . setText ( text ) ; } else { dialogFieldChanged ( ) ; } } public boolean selectItem ( int index ) { boolean success = false ; if ( isOkToUse ( fComboControl ) ) { fComboControl . select ( index ) ; success = fComboControl . getSelectionIndex ( ) == index ; } else { if ( index >= && index < fItems . length ) { fText = fItems [ index ] ; fSelectionIndex = index ; success = true ; } } if ( success ) { dialogFieldChanged ( ) ; } return success ; } public boolean selectItem ( String name ) { for ( int i = ; i < fItems . length ; i ++ ) { if ( fItems [ i ] . equals ( name ) ) { return selectItem ( i ) ; } } return false ; } public int getSelectionIndex ( ) { return fSelectionIndex ; } public void setTextWithoutUpdate ( String text ) { fText = text ; if ( isOkToUse ( fComboControl ) ) { fComboControl . removeModifyListener ( fModifyListener ) ; fComboControl . setText ( text ) ; fComboControl . addModifyListener ( fModifyListener ) ; } } public void refresh ( ) { super . refresh ( ) ; setTextWithoutUpdate ( fText ) ; } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public class LayoutUtil { public static int getNumberOfColumns ( DialogField [ ] editors ) { int nCulumns = ; for ( int i = ; i < editors . length ; i ++ ) { nCulumns = Math . max ( editors [ i ] . getNumberOfControls ( ) , nCulumns ) ; } return nCulumns ; } public static void doDefaultLayout ( Composite parent , DialogField [ ] editors , boolean labelOnTop ) { doDefaultLayout ( parent , editors , labelOnTop , , ) ; } public static void doDefaultLayout ( Composite parent , DialogField [ ] editors , boolean labelOnTop , int marginWidth , int marginHeight ) { int nCulumns = getNumberOfColumns ( editors ) ; Control [ ] [ ] controls = new Control [ editors . length ] [ ] ; for ( int i = ; i < editors . length ; i ++ ) { controls [ i ] = editors [ i ] . doFillIntoGrid ( parent , nCulumns ) ; } if ( labelOnTop ) { nCulumns -- ; modifyLabelSpans ( controls , nCulumns ) ; } GridLayout layout = null ; if ( parent . getLayout ( ) instanceof GridLayout ) { layout = ( GridLayout ) parent . getLayout ( ) ; } else { layout = new GridLayout ( ) ; } if ( marginWidth != SWT . DEFAULT ) { layout . marginWidth = marginWidth ; } if ( marginHeight != SWT . DEFAULT ) { layout . marginHeight = marginHeight ; } layout . numColumns = nCulumns ; parent . setLayout ( layout ) ; } private static void modifyLabelSpans ( Control [ ] [ ] controls , int nCulumns ) { for ( int i = ; i < controls . length ; i ++ ) { setHorizontalSpan ( controls [ i ] [ ] , nCulumns ) ; } } public static void setHorizontalSpan ( Control control , int span ) { Object ld = control . getLayoutData ( ) ; if ( ld instanceof GridData ) { ( ( GridData ) ld ) . horizontalSpan = span ; } else if ( span != ) { GridData gd = new GridData ( ) ; gd . horizontalSpan = span ; control . setLayoutData ( gd ) ; } } public static void setWidthHint ( Control control , int widthHint ) { Object ld = control . getLayoutData ( ) ; if ( ld instanceof GridData ) { ( ( GridData ) ld ) . widthHint = widthHint ; } } public static void setHeightHint ( Control control , int heightHint ) { Object ld = control . getLayoutData ( ) ; if ( ld instanceof GridData ) { ( ( GridData ) ld ) . heightHint = heightHint ; } } public static void setHorizontalIndent ( Control control , int horizontalIndent ) { Object ld = control . getLayoutData ( ) ; if ( ld instanceof GridData ) { ( ( GridData ) ld ) . horizontalIndent = horizontalIndent ; } } public static void setHorizontalGrabbing ( Control control ) { Object ld = control . getLayoutData ( ) ; if ( ld instanceof GridData ) { ( ( GridData ) ld ) . grabExcessHorizontalSpace = true ; } } } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; public interface IStringButtonAdapter { void changeControlPressed ( DialogField field ) ; } package org . rubypeople . rdt . internal . ui . wizards . dialogfields ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; public class SelectionButtonDialogField extends DialogField { private Button fButton ; private boolean fIsSelected ; private DialogField [ ] fAttachedDialogFields ; private int fButtonStyle ; public SelectionButtonDialogField ( int buttonStyle ) { super ( ) ; fIsSelected = false ; fAttachedDialogFields = null ; fButtonStyle = buttonStyle ; } public void attachDialogField ( DialogField dialogField ) { attachDialogFields ( new DialogField [ ] { dialogField } ) ; } public void attachDialogFields ( DialogField [ ] dialogFields ) { fAttachedDialogFields = dialogFields ; for ( int i = ; i < dialogFields . length ; i ++ ) { dialogFields [ i ] . setEnabled ( fIsSelected ) ; } } public boolean isAttached ( DialogField editor ) { if ( fAttachedDialogFields != null ) { for ( int i = ; i < fAttachedDialogFields . length ; i ++ ) { if ( fAttachedDialogFields [ i ] == editor ) { return true ; } } } return false ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; Button button = getSelectionButton ( parent ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = nColumns ; gd . horizontalAlignment = GridData . FILL ; if ( fButtonStyle == SWT . PUSH ) { gd . widthHint = SWTUtil . getButtonWidthHint ( button ) ; } button . setLayoutData ( gd ) ; return new Control [ ] { button } ; } public int getNumberOfControls ( ) { return ; } public Button getSelectionButton ( Composite group ) { if ( fButton == null ) { assertCompositeNotNull ( group ) ; fButton = new Button ( group , fButtonStyle ) ; fButton . setFont ( group . getFont ( ) ) ; fButton . setText ( fLabelText ) ; fButton . setEnabled ( isEnabled ( ) ) ; fButton . setSelection ( fIsSelected ) ; fButton . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { doWidgetSelected ( e ) ; } public void widgetSelected ( SelectionEvent e ) { doWidgetSelected ( e ) ; } } ) ; } return fButton ; } private void doWidgetSelected ( SelectionEvent e ) { if ( isOkToUse ( fButton ) ) { changeValue ( fButton . getSelection ( ) ) ; } } private void changeValue ( boolean newState ) { if ( fIsSelected != newState ) { fIsSelected = newState ; if ( fAttachedDialogFields != null ) { boolean focusSet = false ; for ( int i = ; i < fAttachedDialogFields . length ; i ++ ) { fAttachedDialogFields [ i ] . setEnabled ( fIsSelected ) ; if ( fIsSelected && ! focusSet ) { focusSet = fAttachedDialogFields [ i ] . setFocus ( ) ; } } } dialogFieldChanged ( ) ; } else if ( fButtonStyle == SWT . PUSH ) { dialogFieldChanged ( ) ; } } public boolean isSelected ( ) { return fIsSelected ; } public void setSelection ( boolean selected ) { changeValue ( selected ) ; if ( isOkToUse ( fButton ) ) { fButton . setSelection ( selected ) ; } } protected void updateEnableState ( ) { super . updateEnableState ( ) ; if ( isOkToUse ( fButton ) ) { fButton . setEnabled ( isEnabled ( ) ) ; } } public void refresh ( ) { super . refresh ( ) ; if ( isOkToUse ( fButton ) ) { fButton . setSelection ( fIsSelected ) ; } } } package org . rubypeople . rdt . internal . ui . wizards ; import java . util . Collection ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . ui . dialogs . ISelectionStatusValidator ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; public class TypedElementSelectionValidator implements ISelectionStatusValidator { private IStatus fgErrorStatus = new StatusInfo ( IStatus . ERROR , "" ) ; private IStatus fgOKStatus = new StatusInfo ( ) ; private Class [ ] fAcceptedTypes ; private boolean fAllowMultipleSelection ; private Collection fRejectedElements ; public TypedElementSelectionValidator ( Class [ ] acceptedTypes , boolean allowMultipleSelection ) { this ( acceptedTypes , allowMultipleSelection , null ) ; } public TypedElementSelectionValidator ( Class [ ] acceptedTypes , boolean allowMultipleSelection , Collection rejectedElements ) { Assert . isNotNull ( acceptedTypes ) ; fAcceptedTypes = acceptedTypes ; fAllowMultipleSelection = allowMultipleSelection ; fRejectedElements = rejectedElements ; } public IStatus validate ( Object [ ] elements ) { if ( isValid ( elements ) ) { return fgOKStatus ; } return fgErrorStatus ; } private boolean isOfAcceptedType ( Object o ) { for ( int i = ; i < fAcceptedTypes . length ; i ++ ) { if ( fAcceptedTypes [ i ] . isInstance ( o ) ) { return true ; } } return false ; } private boolean isRejectedElement ( Object elem ) { return ( fRejectedElements != null ) && fRejectedElements . contains ( elem ) ; } protected boolean isSelectedValid ( Object elem ) { return true ; } private boolean isValid ( Object [ ] selection ) { if ( selection . length == ) { return false ; } if ( ! fAllowMultipleSelection && selection . length != ) { return false ; } for ( int i = ; i < selection . length ; i ++ ) { Object o = selection [ i ] ; if ( ! isOfAcceptedType ( o ) || isRejectedElement ( o ) || ! isSelectedValid ( o ) ) { return false ; } } return true ; } } package org . rubypeople . rdt . internal . ui . wizards ; import java . io . File ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Comparator ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Link ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . preferences . PropertyAndPreferencePage ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . BuildPathSupport ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ComboDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; import org . rubypeople . rdt . ui . RubyUI ; public class RubyProjectWizardFirstPage extends WizardPage { private final class NameGroup extends Observable implements IDialogFieldListener { protected final StringDialogField fNameField ; public NameGroup ( Composite composite , String initialName ) { final Composite nameComposite = new Composite ( composite , SWT . NONE ) ; nameComposite . setFont ( composite . getFont ( ) ) ; nameComposite . setLayout ( initGridLayout ( new GridLayout ( , false ) , false ) ) ; nameComposite . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fNameField = new StringDialogField ( ) ; fNameField . setLabelText ( NewWizardMessages . RubyProjectWizardFirstPage_NameGroup_label_text ) ; fNameField . setDialogFieldListener ( this ) ; setName ( initialName ) ; fNameField . doFillIntoGrid ( nameComposite , ) ; LayoutUtil . setHorizontalGrabbing ( fNameField . getTextControl ( null ) ) ; } protected void fireEvent ( ) { setChanged ( ) ; notifyObservers ( ) ; } public String getName ( ) { return fNameField . getText ( ) . trim ( ) ; } public void postSetFocus ( ) { fNameField . postSetFocusOnDialogField ( getShell ( ) . getDisplay ( ) ) ; } public void setName ( String name ) { fNameField . setText ( name ) ; } public void dialogFieldChanged ( DialogField field ) { fireEvent ( ) ; } } private final class LocationGroup extends Observable implements Observer , IStringButtonAdapter , IDialogFieldListener { protected final SelectionButtonDialogField fWorkspaceRadio ; protected final SelectionButtonDialogField fExternalRadio ; protected final StringButtonDialogField fLocation ; private String fPreviousExternalLocation ; private static final String DIALOGSTORE_LAST_EXTERNAL_LOC = RubyUI . ID_PLUGIN + "" ; public LocationGroup ( Composite composite ) { final int numColumns = ; final Group group = new Group ( composite , SWT . NONE ) ; group . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; group . setLayout ( initGridLayout ( new GridLayout ( numColumns , false ) , true ) ) ; group . setText ( NewWizardMessages . RubyProjectWizardFirstPage_LocationGroup_title ) ; fWorkspaceRadio = new SelectionButtonDialogField ( SWT . RADIO ) ; fWorkspaceRadio . setDialogFieldListener ( this ) ; fWorkspaceRadio . setLabelText ( NewWizardMessages . RubyProjectWizardFirstPage_LocationGroup_workspace_desc ) ; fExternalRadio = new SelectionButtonDialogField ( SWT . RADIO ) ; fExternalRadio . setLabelText ( NewWizardMessages . RubyProjectWizardFirstPage_LocationGroup_external_desc ) ; fLocation = new StringButtonDialogField ( this ) ; fLocation . setDialogFieldListener ( this ) ; fLocation . setLabelText ( NewWizardMessages . RubyProjectWizardFirstPage_LocationGroup_locationLabel_desc ) ; fLocation . setButtonLabel ( NewWizardMessages . RubyProjectWizardFirstPage_LocationGroup_browseButton_desc ) ; fExternalRadio . attachDialogField ( fLocation ) ; fWorkspaceRadio . setSelection ( true ) ; fExternalRadio . setSelection ( false ) ; fPreviousExternalLocation = "" ; fWorkspaceRadio . doFillIntoGrid ( group , numColumns ) ; fExternalRadio . doFillIntoGrid ( group , numColumns ) ; fLocation . doFillIntoGrid ( group , numColumns ) ; LayoutUtil . setHorizontalGrabbing ( fLocation . getTextControl ( null ) ) ; } protected void fireEvent ( ) { setChanged ( ) ; notifyObservers ( ) ; } protected String getDefaultPath ( String name ) { final IPath path = Platform . getLocation ( ) . append ( name ) ; return path . toOSString ( ) ; } public void update ( Observable o , Object arg ) { if ( isInWorkspace ( ) ) { fLocation . setText ( getDefaultPath ( fNameGroup . getName ( ) ) ) ; } fireEvent ( ) ; } public IPath getLocation ( ) { if ( isInWorkspace ( ) ) { return Platform . getLocation ( ) ; } return Path . fromOSString ( fLocation . getText ( ) . trim ( ) ) ; } public boolean isInWorkspace ( ) { return fWorkspaceRadio . isSelected ( ) ; } public void changeControlPressed ( DialogField field ) { final DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) ) ; dialog . setMessage ( NewWizardMessages . RubyProjectWizardFirstPage_directory_message ) ; String directoryName = fLocation . getText ( ) . trim ( ) ; if ( directoryName . length ( ) == ) { String prevLocation = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( DIALOGSTORE_LAST_EXTERNAL_LOC ) ; if ( prevLocation != null ) { directoryName = prevLocation ; } } if ( directoryName . length ( ) > ) { final File path = new File ( directoryName ) ; if ( path . exists ( ) ) dialog . setFilterPath ( directoryName ) ; } final String selectedDirectory = dialog . open ( ) ; if ( selectedDirectory != null ) { fLocation . setText ( selectedDirectory ) ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( DIALOGSTORE_LAST_EXTERNAL_LOC , selectedDirectory ) ; } } public void dialogFieldChanged ( DialogField field ) { if ( field == fWorkspaceRadio ) { final boolean checked = fWorkspaceRadio . isSelected ( ) ; if ( checked ) { fPreviousExternalLocation = fLocation . getText ( ) ; fLocation . setText ( getDefaultPath ( fNameGroup . getName ( ) ) ) ; } else { fLocation . setText ( fPreviousExternalLocation ) ; } } fireEvent ( ) ; } } private final class JREGroup implements Observer , SelectionListener , IDialogFieldListener { private final SelectionButtonDialogField fUseDefaultJRE , fUseProjectJRE ; private final ComboDialogField fJRECombo ; private final Group fGroup ; private final Link fPreferenceLink ; private IVMInstall [ ] fInstalledJVMs ; public JREGroup ( Composite composite ) { fGroup = new Group ( composite , SWT . NONE ) ; fGroup . setFont ( composite . getFont ( ) ) ; fGroup . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fGroup . setLayout ( initGridLayout ( new GridLayout ( , false ) , true ) ) ; fGroup . setText ( NewWizardMessages . RubyProjectWizardFirstPage_JREGroup_title ) ; fUseDefaultJRE = new SelectionButtonDialogField ( SWT . RADIO ) ; fUseDefaultJRE . setLabelText ( getDefaultJVMLabel ( ) ) ; fUseDefaultJRE . doFillIntoGrid ( fGroup , ) ; fPreferenceLink = new Link ( fGroup , SWT . NONE ) ; fPreferenceLink . setFont ( fGroup . getFont ( ) ) ; fPreferenceLink . setText ( NewWizardMessages . RubyProjectWizardFirstPage_JREGroup_link_description ) ; fPreferenceLink . setLayoutData ( new GridData ( GridData . END , GridData . CENTER , false , false ) ) ; fPreferenceLink . addSelectionListener ( this ) ; fUseProjectJRE = new SelectionButtonDialogField ( SWT . RADIO ) ; fUseProjectJRE . setLabelText ( NewWizardMessages . RubyProjectWizardFirstPage_JREGroup_specific_compliance ) ; fUseProjectJRE . doFillIntoGrid ( fGroup , ) ; fUseProjectJRE . setDialogFieldListener ( this ) ; fJRECombo = new ComboDialogField ( SWT . READ_ONLY ) ; fillInstalledJREs ( fJRECombo ) ; fJRECombo . setDialogFieldListener ( this ) ; Combo comboControl = fJRECombo . getComboControl ( fGroup ) ; comboControl . setLayoutData ( new GridData ( GridData . BEGINNING , GridData . CENTER , true , false ) ) ; comboControl . setVisibleItemCount ( ) ; DialogField . createEmptySpace ( fGroup ) ; fUseDefaultJRE . setSelection ( true ) ; fJRECombo . setEnabled ( fUseProjectJRE . isSelected ( ) ) ; } private void fillInstalledJREs ( ComboDialogField comboField ) { String selectedItem = null ; int selectionIndex = - ; if ( fUseProjectJRE . isSelected ( ) ) { selectionIndex = comboField . getSelectionIndex ( ) ; if ( selectionIndex != - ) { selectedItem = comboField . getItems ( ) [ selectionIndex ] ; } } fInstalledJVMs = getWorkspaceJREs ( ) ; Arrays . sort ( fInstalledJVMs , new Comparator ( ) { public int compare ( Object arg0 , Object arg1 ) { IVMInstall i0 = ( IVMInstall ) arg0 ; IVMInstall i1 = ( IVMInstall ) arg1 ; return i0 . getName ( ) . compareTo ( i1 . getName ( ) ) ; } } ) ; selectionIndex = - ; String [ ] items = new String [ fInstalledJVMs . length ] ; for ( int i = ; i < fInstalledJVMs . length ; i ++ ) { items [ i ] = fInstalledJVMs [ i ] . getName ( ) ; } fJRECombo . setItems ( items ) ; if ( selectionIndex == - ) { fJRECombo . selectItem ( getDefaultJVMName ( ) ) ; } else { fJRECombo . selectItem ( selectedItem ) ; } } private IVMInstall [ ] getWorkspaceJREs ( ) { List standins = new ArrayList ( ) ; IVMInstallType [ ] types = RubyRuntime . getVMInstallTypes ( ) ; for ( int i = ; i < types . length ; i ++ ) { IVMInstallType type = types [ i ] ; IVMInstall [ ] installs = type . getVMInstalls ( ) ; for ( int j = ; j < installs . length ; j ++ ) { IVMInstall install = installs [ j ] ; standins . add ( new VMStandin ( install ) ) ; } } return ( ( IVMInstall [ ] ) standins . toArray ( new IVMInstall [ standins . size ( ) ] ) ) ; } private String getDefaultJVMName ( ) { IVMInstall vm = RubyRuntime . getDefaultVMInstall ( ) ; if ( vm == null ) return "" ; return vm . getName ( ) ; } private String getDefaultJVMLabel ( ) { return Messages . format ( NewWizardMessages . RubyProjectWizardFirstPage_JREGroup_default_compliance , getDefaultJVMName ( ) ) ; } public void update ( Observable o , Object arg ) { updateEnableState ( ) ; } private void updateEnableState ( ) { final boolean detect = fDetectGroup . mustDetect ( ) ; fUseDefaultJRE . setEnabled ( ! detect ) ; fUseProjectJRE . setEnabled ( ! detect ) ; fJRECombo . setEnabled ( ! detect && fUseProjectJRE . isSelected ( ) ) ; fPreferenceLink . setEnabled ( ! detect ) ; fGroup . setEnabled ( ! detect ) ; } public void widgetSelected ( SelectionEvent e ) { widgetDefaultSelected ( e ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { String jreID = BuildPathSupport . JRE_PREF_PAGE_ID ; Map data = new HashMap ( ) ; data . put ( PropertyAndPreferencePage . DATA_NO_LINK , Boolean . TRUE ) ; PreferencesUtil . createPreferenceDialogOn ( getShell ( ) , jreID , new String [ ] { jreID } , data ) . open ( ) ; handlePossibleJVMChange ( ) ; fDetectGroup . handlePossibleJVMChange ( ) ; } public void handlePossibleJVMChange ( ) { fUseDefaultJRE . setLabelText ( getDefaultJVMLabel ( ) ) ; fillInstalledJREs ( fJRECombo ) ; } public void dialogFieldChanged ( DialogField field ) { updateEnableState ( ) ; fDetectGroup . handlePossibleJVMChange ( ) ; } public boolean isUseSpecific ( ) { return fUseProjectJRE . isSelected ( ) ; } public IVMInstall getSelectedJVM ( ) { if ( fUseProjectJRE . isSelected ( ) ) { int index = fJRECombo . getSelectionIndex ( ) ; if ( index >= && index < fInstalledJVMs . length ) { return fInstalledJVMs [ index ] ; } } return null ; } public String getSelectedCompilerCompliance ( ) { return null ; } } private final class DetectGroup extends Observable implements Observer , SelectionListener { private final Link fHintText ; private boolean fDetect ; public DetectGroup ( Composite composite ) { Link jre50Text = new Link ( composite , SWT . WRAP ) ; jre50Text . setFont ( composite . getFont ( ) ) ; jre50Text . addSelectionListener ( this ) ; GridData gridData = new GridData ( GridData . FILL , SWT . FILL , true , true ) ; gridData . widthHint = convertWidthInCharsToPixels ( ) ; jre50Text . setLayoutData ( gridData ) ; fHintText = jre50Text ; handlePossibleJVMChange ( ) ; } public void handlePossibleJVMChange ( ) { } public void update ( Observable o , Object arg ) { if ( o instanceof LocationGroup ) { boolean oldDetectState = fDetect ; if ( fLocationGroup . isInWorkspace ( ) ) { String name = getProjectName ( ) ; if ( name . length ( ) == || RubyPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( name ) != null ) { fDetect = false ; } else { final File directory = fLocationGroup . getLocation ( ) . append ( getProjectName ( ) ) . toFile ( ) ; fDetect = directory . isDirectory ( ) ; } } else { final File directory = fLocationGroup . getLocation ( ) . toFile ( ) ; fDetect = directory . isDirectory ( ) ; } if ( oldDetectState != fDetect ) { setChanged ( ) ; notifyObservers ( ) ; if ( fDetect ) { fHintText . setVisible ( true ) ; fHintText . setText ( NewWizardMessages . RubyProjectWizardFirstPage_DetectGroup_message ) ; } else { handlePossibleJVMChange ( ) ; } } } } public boolean mustDetect ( ) { return fDetect ; } public void widgetSelected ( SelectionEvent e ) { widgetDefaultSelected ( e ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { String jreID = BuildPathSupport . JRE_PREF_PAGE_ID ; Map data = new HashMap ( ) ; data . put ( PropertyAndPreferencePage . DATA_NO_LINK , Boolean . TRUE ) ; PreferencesUtil . createPreferenceDialogOn ( getShell ( ) , jreID , new String [ ] { jreID } , data ) . open ( ) ; fJREGroup . handlePossibleJVMChange ( ) ; handlePossibleJVMChange ( ) ; } } private final class Validator implements Observer { public void update ( Observable o , Object arg ) { final IWorkspace workspace = RubyPlugin . getWorkspace ( ) ; final String name = fNameGroup . getName ( ) ; if ( name . length ( ) == ) { setErrorMessage ( null ) ; setMessage ( NewWizardMessages . RubyProjectWizardFirstPage_Message_enterProjectName ) ; setPageComplete ( false ) ; return ; } final IStatus nameStatus = workspace . validateName ( name , IResource . PROJECT ) ; if ( ! nameStatus . isOK ( ) ) { setErrorMessage ( nameStatus . getMessage ( ) ) ; setPageComplete ( false ) ; return ; } final IProject handle = getProjectHandle ( ) ; if ( handle . exists ( ) ) { setErrorMessage ( NewWizardMessages . RubyProjectWizardFirstPage_Message_projectAlreadyExists ) ; setPageComplete ( false ) ; return ; } final String location = fLocationGroup . getLocation ( ) . toOSString ( ) ; if ( location . length ( ) == ) { setErrorMessage ( null ) ; setMessage ( NewWizardMessages . RubyProjectWizardFirstPage_Message_enterLocation ) ; setPageComplete ( false ) ; return ; } if ( ! Path . EMPTY . isValidPath ( location ) ) { setErrorMessage ( NewWizardMessages . RubyProjectWizardFirstPage_Message_invalidDirectory ) ; setPageComplete ( false ) ; return ; } IPath projectPath = Path . fromOSString ( location ) ; if ( ! fLocationGroup . isInWorkspace ( ) && Platform . getLocation ( ) . isPrefixOf ( projectPath ) ) { setErrorMessage ( NewWizardMessages . RubyProjectWizardFirstPage_Message_cannotCreateInWorkspace ) ; setPageComplete ( false ) ; return ; } if ( ! fLocationGroup . isInWorkspace ( ) ) { final IStatus locationStatus = workspace . validateProjectLocation ( handle , projectPath ) ; if ( ! locationStatus . isOK ( ) ) { setErrorMessage ( locationStatus . getMessage ( ) ) ; setPageComplete ( false ) ; return ; } } setPageComplete ( true ) ; setErrorMessage ( null ) ; setMessage ( null ) ; } } private NameGroup fNameGroup ; private LocationGroup fLocationGroup ; private JREGroup fJREGroup ; private DetectGroup fDetectGroup ; private Validator fValidator ; private String fInitialName ; private static final String PAGE_NAME = NewWizardMessages . RubyProjectWizardFirstPage_page_pageName ; public RubyProjectWizardFirstPage ( ) { super ( PAGE_NAME ) ; setPageComplete ( false ) ; setTitle ( NewWizardMessages . RubyProjectWizardFirstPage_page_title ) ; setDescription ( NewWizardMessages . RubyProjectWizardFirstPage_page_description ) ; fInitialName = "" ; initializeDefaultVM ( ) ; } private void initializeDefaultVM ( ) { RubyRuntime . getDefaultVMInstall ( ) ; } public void setName ( String name ) { fInitialName = name ; if ( fNameGroup != null ) { fNameGroup . setName ( name ) ; } } public void createControl ( Composite parent ) { initializeDialogUnits ( parent ) ; final Composite composite = new Composite ( parent , SWT . NULL ) ; composite . setFont ( parent . getFont ( ) ) ; composite . setLayout ( initGridLayout ( new GridLayout ( , false ) , true ) ) ; composite . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ) ; fNameGroup = new NameGroup ( composite , fInitialName ) ; fLocationGroup = new LocationGroup ( composite ) ; fJREGroup = new JREGroup ( composite ) ; fDetectGroup = new DetectGroup ( composite ) ; fNameGroup . addObserver ( fLocationGroup ) ; fDetectGroup . addObserver ( fJREGroup ) ; fLocationGroup . addObserver ( fDetectGroup ) ; fNameGroup . notifyObservers ( ) ; fValidator = new Validator ( ) ; fNameGroup . addObserver ( fValidator ) ; fLocationGroup . addObserver ( fValidator ) ; setControl ( composite ) ; Dialog . applyDialogFont ( composite ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( composite , IRubyHelpContextIds . NEW_JAVAPROJECT_WIZARD_PAGE ) ; } public IPath getLocationPath ( ) { return fLocationGroup . getLocation ( ) ; } public IProject getProjectHandle ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( fNameGroup . getName ( ) ) ; } public boolean isInWorkspace ( ) { return fLocationGroup . isInWorkspace ( ) ; } public String getProjectName ( ) { return fNameGroup . getName ( ) ; } public boolean getDetect ( ) { return fDetectGroup . mustDetect ( ) ; } public boolean isSrcBin ( ) { return false ; } public IVMInstall getJVM ( ) { return fJREGroup . getSelectedJVM ( ) ; } public String getCompilerCompliance ( ) { return fJREGroup . getSelectedCompilerCompliance ( ) ; } public void setVisible ( boolean visible ) { super . setVisible ( visible ) ; if ( visible ) { fNameGroup . postSetFocus ( ) ; } } protected GridLayout initGridLayout ( GridLayout layout , boolean margins ) { layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; layout . verticalSpacing = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; if ( margins ) { layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; } else { layout . marginWidth = ; layout . marginHeight = ; } return layout ; } protected GridData setButtonLayoutData ( Button button ) { return super . setButtonLayoutData ( button ) ; } } package org . rubypeople . rdt . internal . ui . wizards ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . dialogs . IPageChangedListener ; import org . eclipse . jface . dialogs . PageChangedEvent ; import org . eclipse . jface . wizard . IWizardPage ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; class InstallRubyWizardPage extends WizardPage implements IWizardPage , IPageChangedListener { protected IWizardPage fNextPage ; private Button installRubyButton ; private Button useJrubyButton ; private Button browseButton ; protected InstallRubyWizardPage ( ) { super ( "" ) ; setTitle ( NewWizardMessages . InstallRubyWizardPage_TTL ) ; setDescription ( NewWizardMessages . InstallRubyWizardPage_MSG_Description ) ; } public void createControl ( Composite parent ) { Composite main = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; main . setLayout ( layout ) ; main . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Group group = new Group ( main , SWT . NONE ) ; group . setLayout ( new GridLayout ( , false ) ) ; group . setText ( NewWizardMessages . InstallRubyWizardPage_LBL_Options ) ; GridData gridData = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; gridData . heightHint = ; group . setLayoutData ( gridData ) ; installRubyButton = new Button ( group , SWT . RADIO ) ; installRubyButton . setText ( NewWizardMessages . InstallRubyWizardPage_LBL_Install_Ruby ) ; installRubyButton . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) { setNextPage ( new DownloadRubyWizardPage ( ) ) ; } else { setNextPage ( null ) ; } super . widgetSelected ( e ) ; } } ) ; browseButton = new Button ( group , SWT . RADIO ) ; browseButton . setText ( NewWizardMessages . InstallRubyWizardPage_LBL_Browse_to_installed_ruby ) ; browseButton . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { setNextPage ( new BrowseToInstalledRubyWizardPage ( ) ) ; setPageComplete ( false ) ; super . widgetSelected ( e ) ; } } ) ; useJrubyButton = new Button ( group , SWT . RADIO ) ; useJrubyButton . setText ( NewWizardMessages . InstallRubyWizardPage_LBL_Use_JRuby ) ; useJrubyButton . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { setNextPage ( new UseJRubyWizardPage ( ) ) ; super . widgetSelected ( e ) ; } } ) ; setControl ( main ) ; setPageComplete ( false ) ; ( getWizardDialog ( ) ) . addPageChangedListener ( this ) ; } @ Override public void dispose ( ) { if ( getWizardDialog ( ) != null ) ( getWizardDialog ( ) ) . removePageChangedListener ( this ) ; super . dispose ( ) ; } private WizardDialog getWizardDialog ( ) { return ( WizardDialog ) getContainer ( ) ; } protected void setNextPage ( IWizardPage nextPage ) { fNextPage = nextPage ; if ( fNextPage != null ) fNextPage . setWizard ( getWizard ( ) ) ; else ( ( WizardPage ) getWizard ( ) . getStartingPage ( ) ) . setPageComplete ( true ) ; getContainer ( ) . updateButtons ( ) ; } @ Override public IWizardPage getNextPage ( ) { return fNextPage ; } @ Override public boolean canFlipToNextPage ( ) { return ! downloadSelected ( ) || Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ; } public boolean downloadSelected ( ) { return installRubyButton . getSelection ( ) ; } public void pageChanged ( PageChangedEvent event ) { Object page = event . getSelectedPage ( ) ; if ( page . equals ( this ) ) { setPageComplete ( false ) ; } } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IMenuCreator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; class HistoryDropDownAction extends Action implements IMenuCreator { private static class ClearHistoryAction extends Action { private CallHierarchyViewPart fView ; public ClearHistoryAction ( CallHierarchyViewPart view ) { super ( CallHierarchyMessages . HistoryDropDownAction_clearhistory_label ) ; fView = view ; } public void run ( ) { fView . setHistoryEntries ( new IMethod [ ] ) ; fView . setMethod ( null ) ; } } public static final int RESULTS_IN_DROP_DOWN = ; private CallHierarchyViewPart fView ; private Menu fMenu ; public HistoryDropDownAction ( CallHierarchyViewPart view ) { fView = view ; fMenu = null ; setToolTipText ( CallHierarchyMessages . HistoryDropDownAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_HISTORY_DROP_DOWN_ACTION ) ; setMenuCreator ( this ) ; } public Menu getMenu ( Menu parent ) { return null ; } public Menu getMenu ( Control parent ) { if ( fMenu != null ) { fMenu . dispose ( ) ; } fMenu = new Menu ( parent ) ; IMethod [ ] elements = fView . getHistoryEntries ( ) ; addEntries ( fMenu , elements ) ; new MenuItem ( fMenu , SWT . SEPARATOR ) ; addActionToMenu ( fMenu , new HistoryListAction ( fView ) ) ; addActionToMenu ( fMenu , new ClearHistoryAction ( fView ) ) ; return fMenu ; } public void dispose ( ) { fView = null ; if ( fMenu != null ) { fMenu . dispose ( ) ; fMenu = null ; } } protected void addActionToMenu ( Menu parent , Action action ) { ActionContributionItem item = new ActionContributionItem ( action ) ; item . fill ( parent , - ) ; } private boolean addEntries ( Menu menu , IMethod [ ] elements ) { boolean checked = false ; int min = Math . min ( elements . length , RESULTS_IN_DROP_DOWN ) ; for ( int i = ; i < min ; i ++ ) { HistoryAction action = new HistoryAction ( fView , elements [ i ] ) ; action . setChecked ( elements [ i ] . equals ( fView . getMethod ( ) ) ) ; checked = checked || action . isChecked ( ) ; addActionToMenu ( menu , action ) ; } return checked ; } public void run ( ) { ( new HistoryListAction ( fView ) ) . run ( ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . ILabelDecorator ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . viewsupport . ImageImageDescriptor ; public class CallHierarchyLabelDecorator implements ILabelDecorator { public CallHierarchyLabelDecorator ( ) { } public String decorateText ( String text , Object element ) { return text ; } public Image decorateImage ( Image image , Object element ) { int adornmentFlags = computeAdornmentFlags ( element ) ; if ( adornmentFlags != ) { ImageDescriptor baseImage = new ImageImageDescriptor ( image ) ; Rectangle bounds = image . getBounds ( ) ; return RubyPlugin . getImageDescriptorRegistry ( ) . get ( new CallHierarchyImageDescriptor ( baseImage , adornmentFlags , new Point ( bounds . width , bounds . height ) ) ) ; } return image ; } private int computeAdornmentFlags ( Object element ) { int flags = ; if ( element instanceof MethodWrapper ) { MethodWrapper methodWrapper = ( MethodWrapper ) element ; if ( methodWrapper . isRecursive ( ) ) { flags = CallHierarchyImageDescriptor . RECURSIVE ; } if ( isMaxCallDepthExceeded ( methodWrapper ) ) { flags |= CallHierarchyImageDescriptor . MAX_LEVEL ; } } return flags ; } private boolean isMaxCallDepthExceeded ( MethodWrapper methodWrapper ) { return methodWrapper . getLevel ( ) > CallHierarchyUI . getDefault ( ) . getMaxCallDepth ( ) ; } public void addListener ( ILabelProviderListener listener ) { } public void dispose ( ) { } public boolean isLabelProperty ( Object element , String property ) { return true ; } public void removeListener ( ILabelProviderListener listener ) { } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . StringReader ; import java . io . StringWriter ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . swt . SWTError ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . TextTransfer ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . widgets . TreeItem ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . util . SelectionUtil ; class CopyCallHierarchyAction extends Action { private static final char INDENTATION = '' ; private CallHierarchyViewPart fView ; private CallHierarchyViewer fViewer ; private final Clipboard fClipboard ; public CopyCallHierarchyAction ( CallHierarchyViewPart view , Clipboard clipboard , CallHierarchyViewer viewer ) { super ( CallHierarchyMessages . CopyCallHierarchyAction_label ) ; Assert . isNotNull ( clipboard ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_COPY_ACTION ) ; fView = view ; fClipboard = clipboard ; fViewer = viewer ; } public boolean canActionBeAdded ( ) { Object element = SelectionUtil . getSingleElement ( getSelection ( ) ) ; return element != null ; } private ISelection getSelection ( ) { ISelectionProvider provider = fView . getSite ( ) . getSelectionProvider ( ) ; if ( provider != null ) { return provider . getSelection ( ) ; } return null ; } public void run ( ) { StringBuffer buf = new StringBuffer ( ) ; addCalls ( fViewer . getTree ( ) . getSelection ( ) [ ] , , buf ) ; TextTransfer plainTextTransfer = TextTransfer . getInstance ( ) ; try { fClipboard . setContents ( new String [ ] { convertLineTerminators ( buf . toString ( ) ) } , new Transfer [ ] { plainTextTransfer } ) ; } catch ( SWTError e ) { if ( e . code != DND . ERROR_CANNOT_SET_CLIPBOARD ) throw e ; if ( MessageDialog . openQuestion ( fView . getViewSite ( ) . getShell ( ) , CallHierarchyMessages . CopyCallHierarchyAction_problem , CallHierarchyMessages . CopyCallHierarchyAction_clipboard_busy ) ) run ( ) ; } } private void addCalls ( TreeItem item , int indent , StringBuffer buf ) { for ( int i = ; i < indent ; i ++ ) { buf . append ( INDENTATION ) ; } buf . append ( item . getText ( ) ) ; buf . append ( '' ) ; if ( item . getExpanded ( ) ) { TreeItem [ ] items = item . getItems ( ) ; for ( int i = ; i < items . length ; i ++ ) { addCalls ( items [ i ] , indent + , buf ) ; } } } private String convertLineTerminators ( String in ) { StringWriter stringWriter = new StringWriter ( ) ; PrintWriter printWriter = new PrintWriter ( stringWriter ) ; StringReader stringReader = new StringReader ( in ) ; BufferedReader bufferedReader = new BufferedReader ( stringReader ) ; String line ; try { while ( ( line = bufferedReader . readLine ( ) ) != null ) { printWriter . println ( line ) ; } } catch ( IOException e ) { return in ; } return stringWriter . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . resource . CompositeImageDescriptor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . util . Assert ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . Point ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class CallHierarchyImageDescriptor extends CompositeImageDescriptor { public final static int RECURSIVE = ; public final static int MAX_LEVEL = ; private ImageDescriptor fBaseImage ; private int fFlags ; private Point fSize ; public CallHierarchyImageDescriptor ( ImageDescriptor baseImage , int flags , Point size ) { fBaseImage = baseImage ; Assert . isNotNull ( fBaseImage ) ; fFlags = flags ; Assert . isTrue ( fFlags >= ) ; fSize = size ; Assert . isNotNull ( fSize ) ; } public void setAdornments ( int adornments ) { Assert . isTrue ( adornments >= ) ; fFlags = adornments ; } public int getAdronments ( ) { return fFlags ; } public void setImageSize ( Point size ) { Assert . isNotNull ( size ) ; Assert . isTrue ( size . x >= && size . y >= ) ; fSize = size ; } public Point getImageSize ( ) { return new Point ( fSize . x , fSize . y ) ; } protected Point getSize ( ) { return fSize ; } public boolean equals ( Object object ) { if ( object == null || ! CallHierarchyImageDescriptor . class . equals ( object . getClass ( ) ) ) return false ; CallHierarchyImageDescriptor other = ( CallHierarchyImageDescriptor ) object ; return ( fBaseImage . equals ( other . fBaseImage ) && fFlags == other . fFlags && fSize . equals ( other . fSize ) ) ; } public int hashCode ( ) { return fBaseImage . hashCode ( ) | fFlags | fSize . hashCode ( ) ; } protected void drawCompositeImage ( int width , int height ) { ImageData bg = getImageData ( fBaseImage ) ; drawImage ( bg , , ) ; drawBottomLeft ( ) ; } private ImageData getImageData ( ImageDescriptor descriptor ) { ImageData data = descriptor . getImageData ( ) ; if ( data == null ) { data = DEFAULT_IMAGE_DATA ; RubyPlugin . logErrorMessage ( "" + descriptor . toString ( ) ) ; } return data ; } private void drawBottomLeft ( ) { Point size = getSize ( ) ; int x = ; ImageData data = null ; if ( ( fFlags & RECURSIVE ) != ) { data = getImageData ( RubyPluginImages . DESC_OVR_RECURSIVE ) ; drawImage ( data , x , size . y - data . height ) ; x += data . width ; } if ( ( fFlags & MAX_LEVEL ) != ) { data = getImageData ( RubyPluginImages . DESC_OVR_MAX_LEVEL ) ; drawImage ( data , x , size . y - data . height ) ; x += data . width ; } } } package org . rubypeople . rdt . internal . ui . callhierarchy ; public interface ICallHierarchyViewPart { } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; class SearchScopeWorkspaceAction extends SearchScopeAction { public SearchScopeWorkspaceAction ( SearchScopeActionGroup group ) { super ( group , CallHierarchyMessages . SearchScopeActionGroup_workspace_text ) ; setToolTipText ( CallHierarchyMessages . SearchScopeActionGroup_workspace_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_SEARCH_SCOPE_ACTION ) ; } public IRubySearchScope getSearchScope ( ) { return SearchEngine . createWorkspaceScope ( ) ; } public int getSearchScopeType ( ) { return SearchScopeActionGroup . SEARCH_SCOPE_TYPE_WORKSPACE ; } public String getFullDescription ( ) { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; return factory . getWorkspaceScopeDescription ( true ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; class ToggleOrientationAction extends Action { private CallHierarchyViewPart fView ; private int fActionOrientation ; public ToggleOrientationAction ( CallHierarchyViewPart v , int orientation ) { super ( "" , AS_RADIO_BUTTON ) ; if ( orientation == CallHierarchyViewPart . VIEW_ORIENTATION_HORIZONTAL ) { setText ( CallHierarchyMessages . ToggleOrientationAction_horizontal_label ) ; setDescription ( CallHierarchyMessages . ToggleOrientationAction_horizontal_description ) ; setToolTipText ( CallHierarchyMessages . ToggleOrientationAction_horizontal_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( orientation == CallHierarchyViewPart . VIEW_ORIENTATION_VERTICAL ) { setText ( CallHierarchyMessages . ToggleOrientationAction_vertical_label ) ; setDescription ( CallHierarchyMessages . ToggleOrientationAction_vertical_description ) ; setToolTipText ( CallHierarchyMessages . ToggleOrientationAction_vertical_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( orientation == CallHierarchyViewPart . VIEW_ORIENTATION_AUTOMATIC ) { setText ( CallHierarchyMessages . ToggleOrientationAction_automatic_label ) ; setDescription ( CallHierarchyMessages . ToggleOrientationAction_automatic_description ) ; setToolTipText ( CallHierarchyMessages . ToggleOrientationAction_automatic_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( orientation == CallHierarchyViewPart . VIEW_ORIENTATION_SINGLE ) { setText ( CallHierarchyMessages . ToggleOrientationAction_single_label ) ; setDescription ( CallHierarchyMessages . ToggleOrientationAction_single_description ) ; setToolTipText ( CallHierarchyMessages . ToggleOrientationAction_single_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else { Assert . isTrue ( false ) ; } fView = v ; fActionOrientation = orientation ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_TOGGLE_ORIENTATION_ACTION ) ; } public int getOrientation ( ) { return fActionOrientation ; } public void run ( ) { if ( isChecked ( ) ) { fView . fOrientation = fActionOrientation ; fView . computeOrientation ( ) ; } } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . viewers . AbstractTreeViewer ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . ui . progress . DeferredTreeContentManager ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public class CallHierarchyContentProvider implements ITreeContentProvider { private final static Object [ ] EMPTY_ARRAY = new Object [ ] ; private DeferredTreeContentManager fManager ; private CallHierarchyViewPart fPart ; private class MethodWrapperRunnable implements IRunnableWithProgress { private MethodWrapper fMethodWrapper ; private MethodWrapper [ ] fCalls = null ; MethodWrapperRunnable ( MethodWrapper methodWrapper ) { fMethodWrapper = methodWrapper ; } public void run ( IProgressMonitor pm ) { fCalls = fMethodWrapper . getCalls ( pm ) ; } MethodWrapper [ ] getCalls ( ) { if ( fCalls != null ) { return fCalls ; } return new MethodWrapper [ ] ; } } public CallHierarchyContentProvider ( CallHierarchyViewPart part ) { super ( ) ; fPart = part ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof TreeRoot ) { TreeRoot dummyRoot = ( TreeRoot ) parentElement ; return new Object [ ] { dummyRoot . getRoot ( ) } ; } else if ( parentElement instanceof MethodWrapper ) { MethodWrapper methodWrapper = ( ( MethodWrapper ) parentElement ) ; if ( shouldStopTraversion ( methodWrapper ) ) { return EMPTY_ARRAY ; } else { if ( fManager != null ) { Object [ ] children = fManager . getChildren ( new DeferredMethodWrapper ( this , methodWrapper ) ) ; if ( children != null ) return children ; } return fetchChildren ( methodWrapper ) ; } } return EMPTY_ARRAY ; } protected Object [ ] fetchChildren ( MethodWrapper methodWrapper ) { IRunnableContext context = RubyPlugin . getActiveWorkbenchWindow ( ) ; MethodWrapperRunnable runnable = new MethodWrapperRunnable ( methodWrapper ) ; try { context . run ( true , true , runnable ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , CallHierarchyMessages . CallHierarchyContentProvider_searchError_title , CallHierarchyMessages . CallHierarchyContentProvider_searchError_message ) ; return EMPTY_ARRAY ; } catch ( InterruptedException e ) { return new Object [ ] { TreeTermination . SEARCH_CANCELED } ; } return runnable . getCalls ( ) ; } private boolean shouldStopTraversion ( MethodWrapper methodWrapper ) { return ( methodWrapper . getLevel ( ) > CallHierarchyUI . getDefault ( ) . getMaxCallDepth ( ) ) || methodWrapper . isRecursive ( ) ; } public Object [ ] getElements ( Object inputElement ) { return getChildren ( inputElement ) ; } public Object getParent ( Object element ) { if ( element instanceof MethodWrapper ) { return ( ( MethodWrapper ) element ) . getParent ( ) ; } return null ; } public void dispose ( ) { } public boolean hasChildren ( Object element ) { if ( element == TreeRoot . EMPTY_ROOT || element == TreeTermination . SEARCH_CANCELED ) { return false ; } if ( element instanceof MethodWrapper ) { MethodWrapper methodWrapper = ( MethodWrapper ) element ; if ( methodWrapper . getMember ( ) . getElementType ( ) != IRubyElement . METHOD ) { return false ; } if ( shouldStopTraversion ( methodWrapper ) ) { return false ; } return true ; } else if ( element instanceof TreeRoot ) { return true ; } else if ( element instanceof DeferredMethodWrapper ) { return true ; } return false ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { if ( oldInput instanceof TreeRoot ) { Object root = ( ( TreeRoot ) oldInput ) . getRoot ( ) ; if ( root instanceof MethodWrapper ) { cancelJobs ( ( MethodWrapper ) root ) ; } } if ( viewer instanceof AbstractTreeViewer ) { fManager = new DeferredTreeContentManager ( this , ( AbstractTreeViewer ) viewer , fPart . getSite ( ) ) ; } } void cancelJobs ( MethodWrapper wrapper ) { if ( fManager != null && wrapper != null ) { fManager . cancel ( wrapper ) ; if ( fPart != null ) { fPart . setCancelEnabled ( false ) ; } } } public void doneFetching ( ) { if ( fPart != null ) { fPart . setCancelEnabled ( false ) ; } } public void startFetching ( ) { if ( fPart != null ) { fPart . setCancelEnabled ( true ) ; } } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; class ToggleCallModeAction extends Action { private CallHierarchyViewPart fView ; private int fMode ; public ToggleCallModeAction ( CallHierarchyViewPart v , int mode ) { super ( "" , AS_RADIO_BUTTON ) ; if ( mode == CallHierarchyViewPart . CALL_MODE_CALLERS ) { setText ( CallHierarchyMessages . ToggleCallModeAction_callers_label ) ; setDescription ( CallHierarchyMessages . ToggleCallModeAction_callers_description ) ; setToolTipText ( CallHierarchyMessages . ToggleCallModeAction_callers_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( mode == CallHierarchyViewPart . CALL_MODE_CALLEES ) { setText ( CallHierarchyMessages . ToggleCallModeAction_callees_label ) ; setDescription ( CallHierarchyMessages . ToggleCallModeAction_callees_description ) ; setToolTipText ( CallHierarchyMessages . ToggleCallModeAction_callees_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else { Assert . isTrue ( false ) ; } fView = v ; fMode = mode ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_TOGGLE_CALL_MODE_ACTION ) ; } public int getMode ( ) { return fMode ; } public void run ( ) { fView . setCallMode ( fMode ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . viewers . IOpenListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . ui . IWorkbenchPartSite ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; class CallHierarchyViewer extends TreeViewer { private CallHierarchyViewPart fPart ; private OpenLocationAction fOpen ; private CallHierarchyContentProvider fContentProvider ; CallHierarchyViewer ( Composite parent , CallHierarchyViewPart part ) { super ( new Tree ( parent , SWT . MULTI ) ) ; fPart = part ; getControl ( ) . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; setUseHashlookup ( true ) ; setAutoExpandLevel ( ) ; fContentProvider = new CallHierarchyContentProvider ( fPart ) ; setContentProvider ( fContentProvider ) ; setLabelProvider ( new CallHierarchyLabelProvider ( ) ) ; fOpen = new OpenLocationAction ( part , part . getSite ( ) ) ; addOpenListener ( new IOpenListener ( ) { public void open ( OpenEvent event ) { fOpen . run ( ) ; } } ) ; clearViewer ( ) ; } void setMethodWrapper ( MethodWrapper wrapper ) { setInput ( getTreeRoot ( wrapper ) ) ; setFocus ( ) ; setSelection ( new StructuredSelection ( wrapper ) , true ) ; } CallHierarchyViewPart getPart ( ) { return fPart ; } void setFocus ( ) { getControl ( ) . setFocus ( ) ; } boolean isInFocus ( ) { return getControl ( ) . isFocusControl ( ) ; } void addKeyListener ( KeyListener keyListener ) { getControl ( ) . addKeyListener ( keyListener ) ; } private TreeRoot getTreeRoot ( MethodWrapper root ) { TreeRoot dummyRoot = new TreeRoot ( root ) ; return dummyRoot ; } void initContextMenu ( IMenuListener menuListener , IWorkbenchPartSite viewSite , ISelectionProvider selectionProvider ) { MenuManager menuMgr = new MenuManager ( ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( menuListener ) ; Menu menu = menuMgr . createContextMenu ( getTree ( ) ) ; getTree ( ) . setMenu ( menu ) ; viewSite . registerContextMenu ( menuMgr , selectionProvider ) ; } void clearViewer ( ) { setInput ( TreeRoot . EMPTY_ROOT ) ; } void cancelJobs ( ) { if ( fPart == null ) return ; fContentProvider . cancelJobs ( fPart . getCurrentMethodWrapper ( ) ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . osgi . util . NLS ; public final class CallHierarchyMessages extends NLS { private static final String BUNDLE_NAME = "" ; private CallHierarchyMessages ( ) { } public static String HistoryDropDownAction_clearhistory_label ; public static String ToggleCallModeAction_callers_label ; public static String ToggleCallModeAction_callers_tooltip ; public static String ToggleCallModeAction_callers_description ; public static String ToggleCallModeAction_callees_label ; public static String ToggleCallModeAction_callees_tooltip ; public static String ToggleCallModeAction_callees_description ; public static String HistoryDropDownAction_tooltip ; public static String HistoryAction_description ; public static String HistoryAction_tooltip ; public static String HistoryListDialog_title ; public static String HistoryListDialog_label ; public static String HistoryListDialog_remove_button ; public static String HistoryListAction_label ; public static String ToggleOrientationAction_vertical_label ; public static String ToggleOrientationAction_vertical_description ; public static String ToggleOrientationAction_vertical_tooltip ; public static String ToggleOrientationAction_horizontal_label ; public static String ToggleOrientationAction_horizontal_tooltip ; public static String ToggleOrientationAction_horizontal_description ; public static String ToggleOrientationAction_automatic_label ; public static String ToggleOrientationAction_automatic_tooltip ; public static String ToggleOrientationAction_automatic_description ; public static String ToggleOrientationAction_single_label ; public static String ToggleOrientationAction_single_tooltip ; public static String ToggleOrientationAction_single_description ; public static String ShowFilterDialogAction_text ; public static String FiltersDialog_filter ; public static String FiltersDialog_filterOnNames ; public static String FiltersDialog_filterOnNamesSubCaption ; public static String FiltersDialog_maxCallDepth ; public static String FiltersDialog_messageMaxCallDepthInvalid ; public static String CallHierarchyContentProvider_searchError_title ; public static String CallHierarchyContentProvider_searchError_message ; public static String CallHierarchyLabelProvider_root ; public static String CallHierarchyLabelProvider_searchCanceled ; public static String CallHierarchyLabelProvider_noMethodSelected ; public static String CallHierarchyLabelProvider_updatePending ; public static String CallHierarchyLabelProvider_matches ; public static String CallHierarchyViewPart_empty ; public static String CallHierarchyViewPart_callsToMethod ; public static String CallHierarchyViewPart_callsFromMethod ; public static String FocusOnSelectionAction_focusOnSelection_text ; public static String FocusOnSelectionAction_focusOnSelection_description ; public static String FocusOnSelectionAction_focusOnSelection_tooltip ; public static String FocusOnSelectionAction_focusOn_text ; public static String RefreshAction_text ; public static String RefreshAction_tooltip ; public static String SearchScopeActionGroup_searchScope ; public static String SearchScopeActionGroup_hierarchy_text ; public static String SearchScopeActionGroup_hierarchy_tooltip ; public static String SearchScopeActionGroup_project_text ; public static String SearchScopeActionGroup_project_tooltip ; public static String SearchScopeActionGroup_workingset_tooltip ; public static String SearchScopeActionGroup_workspace_text ; public static String SearchScopeActionGroup_workspace_tooltip ; public static String SearchScopeActionGroup_workingset_select_text ; public static String SearchScopeActionGroup_workingset_select_tooltip ; public static String WorkingSetScope ; public static String SearchUtil_workingSetConcatenation ; public static String SelectWorkingSetAction_error_title ; public static String SelectWorkingSetAction_error_message ; public static String OpenLocationAction_error_title ; public static String CallHierarchyUI_open_in_editor_error_message ; public static String CallHierarchyUI_open_in_editor_error_messageArgs ; public static String CallHierarchyUI_error_open_view ; public static String CopyCallHierarchyAction_label ; public static String CopyCallHierarchyAction_problem ; public static String CopyCallHierarchyAction_clipboard_busy ; public static String OpenCallHierarchyAction_label ; public static String OpenCallHierarchyAction_tooltip ; public static String OpenCallHierarchyAction_description ; public static String OpenCallHierarchyAction_messages_no_java_element ; public static String OpenCallHierarchyAction_messages_no_valid_java_element ; public static String OpenCallHierarchyAction_messages_title ; public static String OpenCallHierarchyAction_dialog_title ; public static String CancelSearchAction_label ; public static String CancelSearchAction_tooltip ; public static String CallHierarchyUI_selectionDialog_title ; public static String CallHierarchyUI_selectionDialog_message ; public static String OpenLocationAction_label ; public static String OpenLocationAction_tooltip ; public static String LocationViewer_ColumnIcon_header ; public static String LocationViewer_ColumnLine_header ; public static String LocationViewer_ColumnInfo_header ; public static String LocationLabelProvider_unknown ; static { NLS . initializeMessages ( BUNDLE_NAME , CallHierarchyMessages . class ) ; } public static String CallHierarchyViewPart_layout_menu ; } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . ui . IContextMenuConstants ; class SearchScopeActionGroup extends ActionGroup { private static final String TAG_SEARCH_SCOPE_TYPE = "" ; private static final String TAG_SELECTED_WORKING_SET = "" ; private static final String TAG_WORKING_SET_COUNT = "" ; private static final String DIALOGSTORE_SCOPE_TYPE = "" ; private static final String DIALOGSTORE_SELECTED_WORKING_SET = "" ; static final int SEARCH_SCOPE_TYPE_WORKSPACE = ; static final int SEARCH_SCOPE_TYPE_PROJECT = ; static final int SEARCH_SCOPE_TYPE_HIERARCHY = ; static final int SEARCH_SCOPE_TYPE_WORKING_SET = ; private SearchScopeAction fSelectedAction = null ; private String [ ] fSelectedWorkingSetNames = null ; private CallHierarchyViewPart fView ; private IDialogSettings fDialogSettings ; private SearchScopeHierarchyAction fSearchScopeHierarchyAction ; private SearchScopeProjectAction fSearchScopeProjectAction ; private SearchScopeWorkspaceAction fSearchScopeWorkspaceAction ; private SelectWorkingSetAction fSelectWorkingSetAction ; public SearchScopeActionGroup ( CallHierarchyViewPart view , IDialogSettings dialogSettings ) { this . fView = view ; this . fDialogSettings = dialogSettings ; createActions ( ) ; } public IRubySearchScope getSearchScope ( ) { if ( fSelectedAction != null ) { return fSelectedAction . getSearchScope ( ) ; } return null ; } public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; fillContextMenu ( actionBars . getMenuManager ( ) ) ; } protected void setActiveWorkingSets ( IWorkingSet [ ] sets ) { if ( sets != null ) { fSelectedWorkingSetNames = getWorkingSetNames ( sets ) ; fSelectedAction = new SearchScopeWorkingSetAction ( this , sets , getScopeDescription ( sets ) ) ; } else { fSelectedWorkingSetNames = null ; fSelectedAction = null ; } } private String [ ] getWorkingSetNames ( IWorkingSet [ ] sets ) { String [ ] result = new String [ sets . length ] ; for ( int i = ; i < sets . length ; i ++ ) { result [ i ] = sets [ i ] . getName ( ) ; } return result ; } protected IWorkingSet [ ] getActiveWorkingSets ( ) { if ( fSelectedWorkingSetNames != null ) { return getWorkingSets ( fSelectedWorkingSetNames ) ; } return null ; } private IWorkingSet [ ] getWorkingSets ( String [ ] workingSetNames ) { if ( workingSetNames == null ) { return null ; } Set workingSets = new HashSet ( ) ; for ( int j = ; j < workingSetNames . length ; j ++ ) { IWorkingSet workingSet = getWorkingSetManager ( ) . getWorkingSet ( workingSetNames [ j ] ) ; if ( workingSet != null ) { workingSets . add ( workingSet ) ; } } return ( IWorkingSet [ ] ) workingSets . toArray ( new IWorkingSet [ workingSets . size ( ) ] ) ; } protected void setSelected ( SearchScopeAction newSelection , boolean ignoreUnchecked ) { if ( ! ignoreUnchecked || newSelection . isChecked ( ) ) { if ( newSelection instanceof SearchScopeWorkingSetAction ) { fSelectedWorkingSetNames = getWorkingSetNames ( ( ( SearchScopeWorkingSetAction ) newSelection ) . getWorkingSets ( ) ) ; } else { fSelectedWorkingSetNames = null ; } if ( newSelection != null ) { fSelectedAction = newSelection ; } else { fSelectedAction = fSearchScopeWorkspaceAction ; } fDialogSettings . put ( DIALOGSTORE_SCOPE_TYPE , getSearchScopeType ( ) ) ; fDialogSettings . put ( DIALOGSTORE_SELECTED_WORKING_SET , fSelectedWorkingSetNames ) ; } } protected CallHierarchyViewPart getView ( ) { return fView ; } protected IWorkingSetManager getWorkingSetManager ( ) { IWorkingSetManager workingSetManager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; return workingSetManager ; } protected void fillSearchActions ( IMenuManager javaSearchMM ) { Action [ ] actions = getActions ( ) ; for ( int i = ; i < actions . length ; i ++ ) { Action action = actions [ i ] ; if ( action . isEnabled ( ) ) { javaSearchMM . add ( action ) ; } } javaSearchMM . setVisible ( ! javaSearchMM . isEmpty ( ) ) ; } public void fillContextMenu ( IMenuManager menu ) { menu . add ( new Separator ( IContextMenuConstants . GROUP_SEARCH ) ) ; MenuManager javaSearchMM = new MenuManager ( CallHierarchyMessages . SearchScopeActionGroup_searchScope , IContextMenuConstants . GROUP_SEARCH ) ; javaSearchMM . setRemoveAllWhenShown ( true ) ; javaSearchMM . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager manager ) { fillSearchActions ( manager ) ; } } ) ; fillSearchActions ( javaSearchMM ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_SEARCH , javaSearchMM ) ; } private Action [ ] getActions ( ) { List actions = new ArrayList ( SearchUtil . LRU_WORKINGSET_LIST_SIZE + ) ; addAction ( actions , fSearchScopeWorkspaceAction ) ; addAction ( actions , fSearchScopeProjectAction ) ; addAction ( actions , fSearchScopeHierarchyAction ) ; addAction ( actions , fSelectWorkingSetAction ) ; Iterator iter = SearchUtil . getLRUWorkingSets ( ) . sortedIterator ( ) ; while ( iter . hasNext ( ) ) { IWorkingSet [ ] workingSets = ( IWorkingSet [ ] ) iter . next ( ) ; String description = SearchUtil . toString ( workingSets ) ; SearchScopeWorkingSetAction workingSetAction = new SearchScopeWorkingSetAction ( this , workingSets , description ) ; if ( isSelectedWorkingSet ( workingSets ) ) { workingSetAction . setChecked ( true ) ; } actions . add ( workingSetAction ) ; } Action [ ] result = ( Action [ ] ) actions . toArray ( new Action [ actions . size ( ) ] ) ; ensureExactlyOneCheckedAction ( result ) ; return result ; } private void ensureExactlyOneCheckedAction ( Action [ ] result ) { int checked = getCheckedActionCount ( result ) ; if ( checked != ) { if ( checked > ) { for ( int i = ; i < result . length ; i ++ ) { Action action = result [ i ] ; action . setChecked ( false ) ; } } fSearchScopeWorkspaceAction . setChecked ( true ) ; } } private int getCheckedActionCount ( Action [ ] result ) { int checked = ; for ( int i = ; i < result . length ; i ++ ) { Action action = result [ i ] ; if ( action . isChecked ( ) ) { checked ++ ; } } return checked ; } private void addAction ( List actions , Action action ) { if ( action == fSelectedAction ) { action . setChecked ( true ) ; } else { action . setChecked ( false ) ; } actions . add ( action ) ; } private void createActions ( ) { fSearchScopeWorkspaceAction = new SearchScopeWorkspaceAction ( this ) ; fSelectWorkingSetAction = new SelectWorkingSetAction ( this ) ; fSearchScopeHierarchyAction = new SearchScopeHierarchyAction ( this ) ; fSearchScopeProjectAction = new SearchScopeProjectAction ( this ) ; int searchScopeType ; try { searchScopeType = fDialogSettings . getInt ( DIALOGSTORE_SCOPE_TYPE ) ; } catch ( NumberFormatException e ) { searchScopeType = SEARCH_SCOPE_TYPE_WORKSPACE ; } String [ ] workingSetNames = fDialogSettings . getArray ( DIALOGSTORE_SELECTED_WORKING_SET ) ; setSelected ( getSearchScopeAction ( searchScopeType , workingSetNames ) , false ) ; } public void saveState ( IMemento memento ) { int type = getSearchScopeType ( ) ; memento . putInteger ( TAG_SEARCH_SCOPE_TYPE , type ) ; if ( type == SEARCH_SCOPE_TYPE_WORKING_SET ) { memento . putInteger ( TAG_WORKING_SET_COUNT , fSelectedWorkingSetNames . length ) ; for ( int i = ; i < fSelectedWorkingSetNames . length ; i ++ ) { String workingSetName = fSelectedWorkingSetNames [ i ] ; memento . putString ( TAG_SELECTED_WORKING_SET + i , workingSetName ) ; } } } public void restoreState ( IMemento memento ) { String [ ] workingSetNames = null ; Integer scopeType = memento . getInteger ( TAG_SEARCH_SCOPE_TYPE ) ; if ( scopeType != null ) { if ( scopeType . intValue ( ) == SEARCH_SCOPE_TYPE_WORKING_SET ) { Integer workingSetCount = memento . getInteger ( TAG_WORKING_SET_COUNT ) ; if ( workingSetCount != null ) { workingSetNames = new String [ workingSetCount . intValue ( ) ] ; for ( int i = ; i < workingSetCount . intValue ( ) ; i ++ ) { workingSetNames [ i ] = memento . getString ( TAG_SELECTED_WORKING_SET + i ) ; } } } setSelected ( getSearchScopeAction ( scopeType . intValue ( ) , workingSetNames ) , false ) ; } } private SearchScopeAction getSearchScopeAction ( int searchScopeType , String [ ] workingSetNames ) { switch ( searchScopeType ) { case SEARCH_SCOPE_TYPE_WORKSPACE : return fSearchScopeWorkspaceAction ; case SEARCH_SCOPE_TYPE_PROJECT : return fSearchScopeProjectAction ; case SEARCH_SCOPE_TYPE_HIERARCHY : return fSearchScopeHierarchyAction ; case SEARCH_SCOPE_TYPE_WORKING_SET : IWorkingSet [ ] workingSets = getWorkingSets ( workingSetNames ) ; if ( workingSets != null && workingSets . length > ) { return new SearchScopeWorkingSetAction ( this , workingSets , getScopeDescription ( workingSets ) ) ; } return null ; } return null ; } private int getSearchScopeType ( ) { if ( fSelectedAction != null ) { return fSelectedAction . getSearchScopeType ( ) ; } return ; } private String getScopeDescription ( IWorkingSet [ ] workingSets ) { return Messages . format ( CallHierarchyMessages . WorkingSetScope , new String [ ] { SearchUtil . toString ( workingSets ) } ) ; } private boolean isSelectedWorkingSet ( IWorkingSet [ ] workingSets ) { if ( fSelectedWorkingSetNames != null && fSelectedWorkingSetNames . length == workingSets . length ) { Set workingSetNames = new HashSet ( workingSets . length ) ; for ( int i = ; i < workingSets . length ; i ++ ) { workingSetNames . add ( workingSets [ i ] . getName ( ) ) ; } for ( int i = ; i < fSelectedWorkingSetNames . length ; i ++ ) { if ( ! workingSetNames . contains ( fSelectedWorkingSetNames [ i ] ) ) { return false ; } } return true ; } return false ; } public String getFullDescription ( ) { if ( fSelectedAction != null ) return fSelectedAction . getFullDescription ( ) ; return null ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . search . LRUWorkingSetsList ; import org . rubypeople . rdt . internal . ui . search . WorkingSetComparator ; public class SearchUtil { public static int LRU_WORKINGSET_LIST_SIZE = ; private static LRUWorkingSetsList fgLRUWorkingSets ; private static final String DIALOG_SETTINGS_KEY = "" ; private static final String STORE_LRU_WORKING_SET_NAMES = "" ; private static IDialogSettings fgSettingsStore ; public static void updateLRUWorkingSets ( IWorkingSet [ ] workingSets ) { if ( workingSets == null || workingSets . length < ) return ; SearchUtil . getLRUWorkingSets ( ) . add ( workingSets ) ; SearchUtil . saveState ( ) ; } private static void saveState ( ) { IWorkingSet [ ] workingSets ; Iterator iter = SearchUtil . fgLRUWorkingSets . iterator ( ) ; int i = ; while ( iter . hasNext ( ) ) { workingSets = ( IWorkingSet [ ] ) iter . next ( ) ; String [ ] names = new String [ workingSets . length ] ; for ( int j = ; j < workingSets . length ; j ++ ) names [ j ] = workingSets [ j ] . getName ( ) ; SearchUtil . fgSettingsStore . put ( SearchUtil . STORE_LRU_WORKING_SET_NAMES + i , names ) ; i ++ ; } } public static LRUWorkingSetsList getLRUWorkingSets ( ) { if ( SearchUtil . fgLRUWorkingSets == null ) { restoreState ( ) ; } return SearchUtil . fgLRUWorkingSets ; } static void restoreState ( ) { SearchUtil . fgLRUWorkingSets = new LRUWorkingSetsList ( SearchUtil . LRU_WORKINGSET_LIST_SIZE ) ; SearchUtil . fgSettingsStore = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( SearchUtil . DIALOG_SETTINGS_KEY ) ; if ( SearchUtil . fgSettingsStore == null ) SearchUtil . fgSettingsStore = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( SearchUtil . DIALOG_SETTINGS_KEY ) ; boolean foundLRU = false ; for ( int i = SearchUtil . LRU_WORKINGSET_LIST_SIZE - ; i >= ; i -- ) { String [ ] lruWorkingSetNames = SearchUtil . fgSettingsStore . getArray ( SearchUtil . STORE_LRU_WORKING_SET_NAMES + i ) ; if ( lruWorkingSetNames != null ) { Set workingSets = new HashSet ( ) ; for ( int j = ; j < lruWorkingSetNames . length ; j ++ ) { IWorkingSet workingSet = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSet ( lruWorkingSetNames [ j ] ) ; if ( workingSet != null ) { workingSets . add ( workingSet ) ; } } foundLRU = true ; if ( ! workingSets . isEmpty ( ) ) SearchUtil . fgLRUWorkingSets . add ( ( IWorkingSet [ ] ) workingSets . toArray ( new IWorkingSet [ workingSets . size ( ) ] ) ) ; } } if ( ! foundLRU ) restoreFromOldFormat ( ) ; } private static void restoreFromOldFormat ( ) { SearchUtil . fgLRUWorkingSets = new LRUWorkingSetsList ( SearchUtil . LRU_WORKINGSET_LIST_SIZE ) ; SearchUtil . fgSettingsStore = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( SearchUtil . DIALOG_SETTINGS_KEY ) ; if ( SearchUtil . fgSettingsStore == null ) SearchUtil . fgSettingsStore = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( SearchUtil . DIALOG_SETTINGS_KEY ) ; boolean foundLRU = false ; String [ ] lruWorkingSetNames = SearchUtil . fgSettingsStore . getArray ( SearchUtil . STORE_LRU_WORKING_SET_NAMES ) ; if ( lruWorkingSetNames != null ) { for ( int i = lruWorkingSetNames . length - ; i >= ; i -- ) { IWorkingSet workingSet = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSet ( lruWorkingSetNames [ i ] ) ; if ( workingSet != null ) { foundLRU = true ; SearchUtil . fgLRUWorkingSets . add ( new IWorkingSet [ ] { workingSet } ) ; } } } if ( foundLRU ) saveState ( ) ; } public static String toString ( IWorkingSet [ ] workingSets ) { Arrays . sort ( workingSets , new WorkingSetComparator ( ) ) ; String result = "" ; if ( workingSets != null && workingSets . length > ) { boolean firstFound = false ; for ( int i = ; i < workingSets . length ; i ++ ) { String workingSetName = workingSets [ i ] . getLabel ( ) ; if ( firstFound ) result = Messages . format ( CallHierarchyMessages . SearchUtil_workingSetConcatenation , new String [ ] { result , workingSetName } ) ; else { result = workingSetName ; firstFound = true ; } } } return result ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; class SelectWorkingSetAction extends Action { private final SearchScopeActionGroup fGroup ; public SelectWorkingSetAction ( SearchScopeActionGroup group ) { super ( CallHierarchyMessages . SearchScopeActionGroup_workingset_select_text ) ; this . fGroup = group ; setToolTipText ( CallHierarchyMessages . SearchScopeActionGroup_workingset_select_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_SEARCH_SCOPE_ACTION ) ; } public void run ( ) { try { IWorkingSet [ ] workingSets ; workingSets = RubySearchScopeFactory . getInstance ( ) . queryWorkingSets ( ) ; if ( workingSets != null ) { this . fGroup . setActiveWorkingSets ( workingSets ) ; SearchUtil . updateLRUWorkingSets ( workingSets ) ; } else { this . fGroup . setActiveWorkingSets ( null ) ; } } catch ( RubyModelException e ) { ExceptionHandler . handle ( e , RubyPlugin . getActiveWorkbenchShell ( ) , CallHierarchyMessages . SelectWorkingSetAction_error_title , CallHierarchyMessages . SelectWorkingSetAction_error_message ) ; } } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; class SearchScopeProjectAction extends SearchScopeAction { private final SearchScopeActionGroup fGroup ; public SearchScopeProjectAction ( SearchScopeActionGroup group ) { super ( group , CallHierarchyMessages . SearchScopeActionGroup_project_text ) ; this . fGroup = group ; setToolTipText ( CallHierarchyMessages . SearchScopeActionGroup_project_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_SEARCH_SCOPE_ACTION ) ; } public IRubySearchScope getSearchScope ( ) { IMethod method = this . fGroup . getView ( ) . getMethod ( ) ; if ( method == null ) { return null ; } RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; return factory . createRubyProjectSearchScope ( method . getRubyProject ( ) , true ) ; } public int getSearchScopeType ( ) { return SearchScopeActionGroup . SEARCH_SCOPE_TYPE_PROJECT ; } public String getFullDescription ( ) { IMethod method = this . fGroup . getView ( ) . getMethod ( ) ; if ( method != null ) { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; return factory . getProjectScopeDescription ( method . getRubyProject ( ) , true ) ; } return "" ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . eclipse . ui . progress . IDeferredWorkbenchAdapter ; import org . eclipse . ui . progress . IElementCollector ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class DeferredMethodWrapper extends MethodWrapperWorkbenchAdapter implements IDeferredWorkbenchAdapter { private final CallHierarchyContentProvider fProvider ; private class BatchSimilarSchedulingRule implements ISchedulingRule { public String id ; public BatchSimilarSchedulingRule ( String id ) { this . id = id ; } public boolean isConflicting ( ISchedulingRule rule ) { if ( rule instanceof BatchSimilarSchedulingRule ) { return ( ( BatchSimilarSchedulingRule ) rule ) . id . equals ( id ) ; } return false ; } public boolean contains ( ISchedulingRule rule ) { return this == rule ; } } DeferredMethodWrapper ( CallHierarchyContentProvider provider , MethodWrapper methodWrapper ) { super ( methodWrapper ) ; this . fProvider = provider ; } private Object getCalls ( IProgressMonitor monitor ) { return getMethodWrapper ( ) . getCalls ( monitor ) ; } public void fetchDeferredChildren ( Object object , IElementCollector collector , IProgressMonitor monitor ) { try { fProvider . startFetching ( ) ; DeferredMethodWrapper methodWrapper = ( DeferredMethodWrapper ) object ; collector . add ( ( Object [ ] ) methodWrapper . getCalls ( monitor ) , monitor ) ; collector . done ( ) ; } catch ( OperationCanceledException e ) { collector . add ( new Object [ ] { TreeTermination . SEARCH_CANCELED } , monitor ) ; } catch ( Exception e ) { RubyPlugin . log ( e ) ; } finally { fProvider . doneFetching ( ) ; } } public boolean isContainer ( ) { return true ; } public ISchedulingRule getRule ( Object o ) { return new BatchSimilarSchedulingRule ( "" ) ; } public Object [ ] getChildren ( Object o ) { return this . fProvider . fetchChildren ( ( ( DeferredMethodWrapper ) o ) . getMethodWrapper ( ) ) ; } public Object getAdapter ( Class adapter ) { if ( adapter == IDeferredWorkbenchAdapter . class ) return this ; return null ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; final class TreeTermination { public static final Object SEARCH_CANCELED = new Object ( ) ; } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . util . ArrayList ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . viewers . ArrayContentProvider ; import org . eclipse . jface . viewers . ColumnLayoutData ; import org . eclipse . jface . viewers . ColumnPixelData ; import org . eclipse . jface . viewers . ColumnWeightData ; import org . eclipse . jface . viewers . TableLayout ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . ui . IWorkbenchPartSite ; class LocationViewer extends TableViewer { private final String columnHeaders [ ] = { CallHierarchyMessages . LocationViewer_ColumnIcon_header , CallHierarchyMessages . LocationViewer_ColumnLine_header , CallHierarchyMessages . LocationViewer_ColumnInfo_header } ; private ColumnLayoutData columnLayouts [ ] = { new ColumnPixelData ( , false , true ) , new ColumnWeightData ( ) , new ColumnWeightData ( ) } ; LocationViewer ( Composite parent ) { super ( createTable ( parent ) ) ; setContentProvider ( new ArrayContentProvider ( ) ) ; setLabelProvider ( new LocationLabelProvider ( ) ) ; setInput ( new ArrayList ( ) ) ; createColumns ( ) ; } private static Table createTable ( Composite parent ) { return new Table ( parent , SWT . H_SCROLL | SWT . V_SCROLL | SWT . MULTI | SWT . FULL_SELECTION ) ; } private void createColumns ( ) { TableLayout layout = new TableLayout ( ) ; getTable ( ) . setLayout ( layout ) ; getTable ( ) . setHeaderVisible ( true ) ; for ( int i = ; i < columnHeaders . length ; i ++ ) { layout . addColumnData ( columnLayouts [ i ] ) ; TableColumn tc = new TableColumn ( getTable ( ) , SWT . NONE , i ) ; tc . setResizable ( columnLayouts [ i ] . resizable ) ; tc . setText ( columnHeaders [ i ] ) ; } } void initContextMenu ( IMenuListener menuListener , String popupId , IWorkbenchPartSite viewSite ) { MenuManager menuMgr = new MenuManager ( ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( menuListener ) ; Menu menu = menuMgr . createContextMenu ( getControl ( ) ) ; getControl ( ) . setMenu ( menu ) ; viewSite . registerContextMenu ( popupId , menuMgr , this ) ; } void clearViewer ( ) { setInput ( "" ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . util . Collection ; import org . eclipse . jface . viewers . ILabelDecorator ; import org . eclipse . swt . graphics . Image ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; class CallHierarchyLabelProvider extends AppearanceAwareLabelProvider { private static final long TEXTFLAGS = DEFAULT_TEXTFLAGS | RubyElementLabels . ALL_POST_QUALIFIED | RubyElementLabels . P_COMPRESSED ; private static final int IMAGEFLAGS = DEFAULT_IMAGEFLAGS | RubyElementImageProvider . SMALL_ICONS ; private ILabelDecorator fDecorator ; CallHierarchyLabelProvider ( ) { super ( TEXTFLAGS , IMAGEFLAGS ) ; fDecorator = new CallHierarchyLabelDecorator ( ) ; } public Image getImage ( Object element ) { Image result = null ; if ( element instanceof MethodWrapper ) { MethodWrapper methodWrapper = ( MethodWrapper ) element ; if ( methodWrapper . getMember ( ) != null ) { result = fDecorator . decorateImage ( super . getImage ( methodWrapper . getMember ( ) ) , methodWrapper ) ; } } else if ( isPendingUpdate ( element ) ) { return null ; } else { result = super . getImage ( element ) ; } return result ; } public String getText ( Object element ) { if ( element instanceof MethodWrapper ) { MethodWrapper methodWrapper = ( MethodWrapper ) element ; if ( methodWrapper . getMember ( ) != null ) { return getElementLabel ( methodWrapper ) ; } else { return CallHierarchyMessages . CallHierarchyLabelProvider_root ; } } else if ( element == TreeTermination . SEARCH_CANCELED ) { return CallHierarchyMessages . CallHierarchyLabelProvider_searchCanceled ; } else if ( isPendingUpdate ( element ) ) { return CallHierarchyMessages . CallHierarchyLabelProvider_updatePending ; } return CallHierarchyMessages . CallHierarchyLabelProvider_noMethodSelected ; } private boolean isPendingUpdate ( Object element ) { return element instanceof IWorkbenchAdapter ; } private String getElementLabel ( MethodWrapper methodWrapper ) { String label = super . getText ( methodWrapper . getMember ( ) ) ; Collection callLocations = methodWrapper . getMethodCall ( ) . getCallLocations ( ) ; if ( ( callLocations != null ) && ( callLocations . size ( ) > ) ) { return Messages . format ( CallHierarchyMessages . CallHierarchyLabelProvider_matches , new String [ ] { label , String . valueOf ( callLocations . size ( ) ) } ) ; } return label ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; class HistoryAction extends Action { private static RubyElementLabelProvider fLabelProvider = new RubyElementLabelProvider ( RubyElementLabelProvider . SHOW_POST_QUALIFIED ) ; private CallHierarchyViewPart fView ; private IMethod fMethod ; public HistoryAction ( CallHierarchyViewPart viewPart , IMethod element ) { super ( "" , AS_RADIO_BUTTON ) ; fView = viewPart ; fMethod = element ; String elementName = getElementLabel ( element ) ; setText ( elementName ) ; setImageDescriptor ( getImageDescriptor ( element ) ) ; setDescription ( Messages . format ( CallHierarchyMessages . HistoryAction_description , elementName ) ) ; setToolTipText ( Messages . format ( CallHierarchyMessages . HistoryAction_tooltip , elementName ) ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_HISTORY_ACTION ) ; } private ImageDescriptor getImageDescriptor ( IRubyElement elem ) { RubyElementImageProvider imageProvider = new RubyElementImageProvider ( ) ; ImageDescriptor desc = imageProvider . getBaseImageDescriptor ( elem , ) ; imageProvider . dispose ( ) ; return desc ; } public void run ( ) { fView . gotoHistoryEntry ( fMethod ) ; } private String getElementLabel ( IRubyElement element ) { Assert . isNotNull ( element ) ; return fLabelProvider . getText ( element ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class CallHierarchyFiltersActionGroup extends ActionGroup { class ShowFilterDialogAction extends Action { ShowFilterDialogAction ( ) { setText ( CallHierarchyMessages . ShowFilterDialogAction_text ) ; setImageDescriptor ( RubyPluginImages . DESC_ELCL_FILTER ) ; setDisabledImageDescriptor ( RubyPluginImages . DESC_DLCL_FILTER ) ; } public void run ( ) { openDialog ( ) ; } } private IViewPart fPart ; public CallHierarchyFiltersActionGroup ( IViewPart part , StructuredViewer viewer ) { Assert . isNotNull ( part ) ; Assert . isNotNull ( viewer ) ; fPart = part ; } public void fillActionBars ( IActionBars actionBars ) { fillViewMenu ( actionBars . getMenuManager ( ) ) ; } private void fillViewMenu ( IMenuManager viewMenu ) { viewMenu . add ( new Separator ( "" ) ) ; viewMenu . add ( new ShowFilterDialogAction ( ) ) ; } public void dispose ( ) { super . dispose ( ) ; } private void openDialog ( ) { FiltersDialog dialog = new FiltersDialog ( fPart . getViewSite ( ) . getShell ( ) ) ; dialog . open ( ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; public class MethodWrapperWorkbenchAdapter implements IWorkbenchAdapter { private final MethodWrapper fMethodWrapper ; public MethodWrapperWorkbenchAdapter ( MethodWrapper methodWrapper ) { Assert . isNotNull ( methodWrapper ) ; fMethodWrapper = methodWrapper ; } public MethodWrapper getMethodWrapper ( ) { return fMethodWrapper ; } public Object [ ] getChildren ( Object o ) { return new Object [ ] ; } public ImageDescriptor getImageDescriptor ( Object object ) { return null ; } public String getLabel ( Object o ) { return fMethodWrapper . getMember ( ) . getElementName ( ) ; } public Object getParent ( Object o ) { return fMethodWrapper . getParent ( ) ; } public boolean equals ( Object obj ) { return fMethodWrapper . equals ( obj ) ; } public int hashCode ( ) { return fMethodWrapper . hashCode ( ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; public class HistoryListAction extends Action { private class HistoryListDialog extends StatusDialog { private ListDialogField fHistoryList ; private IStatus fHistoryStatus ; private IMethod fResult ; private HistoryListDialog ( Shell shell , IMethod [ ] elements ) { super ( shell ) ; setTitle ( CallHierarchyMessages . HistoryListDialog_title ) ; String [ ] buttonLabels = new String [ ] { CallHierarchyMessages . HistoryListDialog_remove_button , } ; IListAdapter adapter = new IListAdapter ( ) { public void customButtonPressed ( ListDialogField field , int index ) { doCustomButtonPressed ( ) ; } public void selectionChanged ( ListDialogField field ) { doSelectionChanged ( ) ; } public void doubleClicked ( ListDialogField field ) { doDoubleClicked ( ) ; } } ; RubyElementLabelProvider labelProvider = new RubyElementLabelProvider ( RubyElementLabelProvider . SHOW_QUALIFIED | RubyElementLabelProvider . SHOW_ROOT ) ; fHistoryList = new ListDialogField ( adapter , buttonLabels , labelProvider ) ; fHistoryList . setLabelText ( CallHierarchyMessages . HistoryListDialog_label ) ; fHistoryList . setElements ( Arrays . asList ( elements ) ) ; ISelection sel ; if ( elements . length > ) { sel = new StructuredSelection ( elements [ ] ) ; } else { sel = new StructuredSelection ( ) ; } fHistoryList . selectElements ( sel ) ; } protected Control createDialogArea ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; inner . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; inner . setFont ( composite . getFont ( ) ) ; LayoutUtil . doDefaultLayout ( inner , new DialogField [ ] { fHistoryList } , true , , ) ; LayoutUtil . setHeightHint ( fHistoryList . getListControl ( null ) , convertHeightInCharsToPixels ( ) ) ; LayoutUtil . setHorizontalGrabbing ( fHistoryList . getListControl ( null ) ) ; applyDialogFont ( composite ) ; return composite ; } private void doCustomButtonPressed ( ) { fHistoryList . removeElements ( fHistoryList . getSelectedElements ( ) ) ; } private void doDoubleClicked ( ) { if ( fHistoryStatus . isOK ( ) ) { okPressed ( ) ; } } private void doSelectionChanged ( ) { StatusInfo status = new StatusInfo ( ) ; List selected = fHistoryList . getSelectedElements ( ) ; if ( selected . size ( ) != ) { status . setError ( "" ) ; fResult = null ; } else { fResult = ( IMethod ) selected . get ( ) ; } fHistoryList . enableButton ( , fHistoryList . getSize ( ) > selected . size ( ) && selected . size ( ) != ) ; fHistoryStatus = status ; updateStatus ( status ) ; } public IMethod getResult ( ) { return fResult ; } public IMethod [ ] getRemaining ( ) { List elems = fHistoryList . getElements ( ) ; return ( IMethod [ ] ) elems . toArray ( new IMethod [ elems . size ( ) ] ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . HISTORY_LIST_DIALOG ) ; } public void create ( ) { setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; super . create ( ) ; } } private CallHierarchyViewPart fView ; public HistoryListAction ( CallHierarchyViewPart view ) { fView = view ; setText ( CallHierarchyMessages . HistoryListAction_label ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . HISTORY_LIST_ACTION ) ; } public void run ( ) { IMethod [ ] historyEntries = fView . getHistoryEntries ( ) ; HistoryListDialog dialog = new HistoryListDialog ( RubyPlugin . getActiveWorkbenchShell ( ) , historyEntries ) ; if ( dialog . open ( ) == Window . OK ) { fView . setHistoryEntries ( dialog . getRemaining ( ) ) ; fView . setMethod ( dialog . getResult ( ) ) ; } } } package org . rubypeople . rdt . internal . ui . callhierarchy ; public class TreeRoot { public static final Object EMPTY_ROOT = new Object ( ) ; private Object fRoot ; public TreeRoot ( Object root ) { this . fRoot = root ; } Object getRoot ( ) { return fRoot ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . util . Iterator ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbenchSite ; import org . rubypeople . rdt . internal . corext . callhierarchy . CallLocation ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; import org . rubypeople . rdt . ui . actions . SelectionDispatchAction ; class OpenLocationAction extends SelectionDispatchAction { private CallHierarchyViewPart fPart ; public OpenLocationAction ( CallHierarchyViewPart part , IWorkbenchSite site ) { super ( site ) ; fPart = part ; setText ( CallHierarchyMessages . OpenLocationAction_label ) ; setToolTipText ( CallHierarchyMessages . OpenLocationAction_tooltip ) ; } private boolean checkEnabled ( IStructuredSelection selection ) { if ( selection . isEmpty ( ) ) { return false ; } for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof MethodWrapper ) { continue ; } else if ( element instanceof CallLocation ) { continue ; } return false ; } return true ; } public ISelection getSelection ( ) { return fPart . getSelection ( ) ; } public void run ( IStructuredSelection selection ) { if ( ! checkEnabled ( selection ) ) { return ; } for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { boolean noError = CallHierarchyUI . openInEditor ( iter . next ( ) , getShell ( ) , getDialogTitle ( ) ) ; if ( ! noError ) return ; } } private String getDialogTitle ( ) { return CallHierarchyMessages . OpenLocationAction_error_title ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; class SearchScopeHierarchyAction extends SearchScopeAction { private final SearchScopeActionGroup fGroup ; public SearchScopeHierarchyAction ( SearchScopeActionGroup group ) { super ( group , CallHierarchyMessages . SearchScopeActionGroup_hierarchy_text ) ; this . fGroup = group ; setToolTipText ( CallHierarchyMessages . SearchScopeActionGroup_hierarchy_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_SEARCH_SCOPE_ACTION ) ; } public IRubySearchScope getSearchScope ( ) { try { IMethod method = this . fGroup . getView ( ) . getMethod ( ) ; if ( method != null ) { return SearchEngine . createHierarchyScope ( method . getDeclaringType ( ) ) ; } else { return null ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return null ; } public int getSearchScopeType ( ) { return SearchScopeActionGroup . SEARCH_SCOPE_TYPE_HIERARCHY ; } public String getFullDescription ( ) { IMethod method = this . fGroup . getView ( ) . getMethod ( ) ; return RubySearchScopeFactory . getInstance ( ) . getHierarchyScopeDescription ( method . getDeclaringType ( ) ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . OpenStrategy ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . callhierarchy . CallHierarchy ; import org . rubypeople . rdt . internal . corext . callhierarchy . CallLocation ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyStatusConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . OpenActionUtil ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . RubyUI ; public class CallHierarchyUI { private static final int DEFAULT_MAX_CALL_DEPTH = ; private static final String PREF_MAX_CALL_DEPTH = "" ; private static CallHierarchyUI fgInstance ; private CallHierarchyUI ( ) { } public static CallHierarchyUI getDefault ( ) { if ( fgInstance == null ) { fgInstance = new CallHierarchyUI ( ) ; } return fgInstance ; } public int getMaxCallDepth ( ) { int maxCallDepth ; IPreferenceStore settings = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; maxCallDepth = settings . getInt ( PREF_MAX_CALL_DEPTH ) ; if ( maxCallDepth < || maxCallDepth > ) { maxCallDepth = DEFAULT_MAX_CALL_DEPTH ; } return maxCallDepth ; } public void setMaxCallDepth ( int maxCallDepth ) { IPreferenceStore settings = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; settings . setValue ( PREF_MAX_CALL_DEPTH , maxCallDepth ) ; } public static void jumpToMember ( IRubyElement element ) { if ( element != null ) { try { IEditorPart methodEditor = EditorUtility . openInEditor ( element , true ) ; RubyUI . revealInEditor ( methodEditor , element ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } catch ( PartInitException e ) { RubyPlugin . log ( e ) ; } } } public static void jumpToLocation ( CallLocation callLocation ) { try { IEditorPart methodEditor = EditorUtility . openInEditor ( callLocation . getMember ( ) , false ) ; if ( methodEditor instanceof ITextEditor ) { ITextEditor editor = ( ITextEditor ) methodEditor ; editor . selectAndReveal ( callLocation . getStart ( ) , ( callLocation . getEnd ( ) - callLocation . getStart ( ) ) ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } catch ( PartInitException e ) { RubyPlugin . log ( e ) ; } } public static boolean openInEditor ( Object element , Shell shell , String title ) { CallLocation callLocation = CallHierarchy . getCallLocation ( element ) ; try { IMember enclosingMember ; int selectionStart ; int selectionLength ; if ( callLocation != null ) { enclosingMember = callLocation . getMember ( ) ; selectionStart = callLocation . getStart ( ) ; selectionLength = callLocation . getEnd ( ) - selectionStart ; } else if ( element instanceof MethodWrapper ) { enclosingMember = ( ( MethodWrapper ) element ) . getMember ( ) ; ISourceRange selectionRange = enclosingMember . getNameRange ( ) ; if ( selectionRange == null ) selectionRange = enclosingMember . getSourceRange ( ) ; if ( selectionRange == null ) return true ; selectionStart = selectionRange . getOffset ( ) ; selectionLength = selectionRange . getLength ( ) ; } else { return true ; } boolean activateOnOpen = OpenStrategy . activateOnOpen ( ) ; IEditorPart methodEditor = EditorUtility . openInEditor ( enclosingMember , activateOnOpen ) ; if ( methodEditor instanceof ITextEditor ) { ITextEditor editor = ( ITextEditor ) methodEditor ; editor . selectAndReveal ( selectionStart , selectionLength ) ; } return true ; } catch ( RubyModelException e ) { RubyPlugin . log ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IRubyStatusConstants . INTERNAL_ERROR , CallHierarchyMessages . CallHierarchyUI_open_in_editor_error_message , e ) ) ; ErrorDialog . openError ( shell , title , CallHierarchyMessages . CallHierarchyUI_open_in_editor_error_message , e . getStatus ( ) ) ; return false ; } catch ( PartInitException x ) { String name ; if ( callLocation != null ) name = callLocation . getCalledMember ( ) . getElementName ( ) ; else if ( element instanceof MethodWrapper ) name = ( ( MethodWrapper ) element ) . getName ( ) ; else name = "" ; MessageDialog . openError ( shell , title , Messages . format ( CallHierarchyMessages . CallHierarchyUI_open_in_editor_error_messageArgs , new String [ ] { name , x . getMessage ( ) } ) ) ; return false ; } } public static IEditorPart isOpenInEditor ( Object elem ) { IRubyElement javaElement = null ; if ( elem instanceof MethodWrapper ) { javaElement = ( ( MethodWrapper ) elem ) . getMember ( ) ; } else if ( elem instanceof CallLocation ) { javaElement = ( ( CallLocation ) elem ) . getCalledMember ( ) ; } if ( javaElement != null ) { return EditorUtility . isOpenInEditor ( javaElement ) ; } return null ; } public static IRubyElement [ ] getCandidates ( Object input ) { if ( ! ( input instanceof IRubyElement ) ) { return null ; } IRubyElement elem = ( IRubyElement ) input ; if ( elem . getElementType ( ) == IRubyElement . METHOD ) { return new IRubyElement [ ] { elem } ; } return null ; } public static CallHierarchyViewPart open ( IRubyElement [ ] candidates , IWorkbenchWindow window ) { Assert . isTrue ( candidates != null && candidates . length != ) ; IRubyElement input = null ; if ( candidates . length > ) { String title = CallHierarchyMessages . CallHierarchyUI_selectionDialog_title ; String message = CallHierarchyMessages . CallHierarchyUI_selectionDialog_message ; input = OpenActionUtil . selectRubyElement ( candidates , window . getShell ( ) , title , message ) ; } else { input = candidates [ ] ; } if ( input == null ) return null ; return openInViewPart ( window , input ) ; } private static void openEditor ( Object input , boolean activate ) throws PartInitException , RubyModelException { IEditorPart part = EditorUtility . openInEditor ( input , activate ) ; if ( input instanceof IRubyElement ) EditorUtility . revealInEditor ( part , ( IRubyElement ) input ) ; } private static CallHierarchyViewPart openInViewPart ( IWorkbenchWindow window , IRubyElement input ) { IWorkbenchPage page = window . getActivePage ( ) ; try { CallHierarchyViewPart result = ( CallHierarchyViewPart ) page . showView ( CallHierarchyViewPart . ID_CALL_HIERARCHY ) ; result . setMethod ( ( IMethod ) input ) ; openEditor ( input , false ) ; return result ; } catch ( CoreException e ) { ExceptionHandler . handle ( e , window . getShell ( ) , CallHierarchyMessages . CallHierarchyUI_error_open_view , e . getMessage ( ) ) ; } return null ; } static ISelection convertSelection ( ISelection selection ) { if ( selection . isEmpty ( ) ) { return selection ; } if ( selection instanceof IStructuredSelection ) { IStructuredSelection structuredSelection = ( IStructuredSelection ) selection ; List javaElements = new ArrayList ( ) ; for ( Iterator iter = structuredSelection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof MethodWrapper ) { IMember member = ( ( MethodWrapper ) element ) . getMember ( ) ; if ( member != null ) { javaElements . add ( member ) ; } } else if ( element instanceof IMember ) { javaElements . add ( element ) ; } else if ( element instanceof CallLocation ) { IMember member = ( ( CallLocation ) element ) . getMember ( ) ; javaElements . add ( member ) ; } } return new StructuredSelection ( javaElements ) ; } return StructuredSelection . EMPTY ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IStatusLineManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . util . TransferDropTargetListener ; import org . eclipse . jface . viewers . IOpenListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DropTarget ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . events . ControlListener ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPartListener2 ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . part . PageBook ; import org . eclipse . ui . part . ResourceTransfer ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . views . navigator . LocalSelectionTransfer ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . corext . callhierarchy . CallHierarchy ; import org . rubypeople . rdt . internal . corext . callhierarchy . CallLocation ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . CompositeActionGroup ; import org . rubypeople . rdt . internal . ui . dnd . DelegatingDropAdapter ; import org . rubypeople . rdt . internal . ui . dnd . RdtViewerDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . ResourceTransferDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . SelectionTransferDragAdapter ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . viewsupport . SelectionProviderMediator ; import org . rubypeople . rdt . internal . ui . viewsupport . StatusBarUpdater ; import org . rubypeople . rdt . ui . IContextMenuConstants ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . actions . OpenEditorActionGroup ; import org . rubypeople . rdt . ui . actions . OpenViewActionGroup ; import org . rubypeople . rdt . ui . actions . RubySearchActionGroup ; public class CallHierarchyViewPart extends ViewPart implements ICallHierarchyViewPart , ISelectionChangedListener { private class CallHierarchySelectionProvider extends SelectionProviderMediator { public CallHierarchySelectionProvider ( StructuredViewer [ ] viewers ) { super ( viewers , null ) ; } public ISelection getSelection ( ) { ISelection selection = super . getSelection ( ) ; if ( ! selection . isEmpty ( ) ) { return CallHierarchyUI . convertSelection ( selection ) ; } return selection ; } } private static final String DIALOGSTORE_VIEWORIENTATION = "" ; private static final String DIALOGSTORE_CALL_MODE = "" ; private static final String DIALOGSTORE_RATIO = "" ; static final int VIEW_ORIENTATION_VERTICAL = ; static final int VIEW_ORIENTATION_HORIZONTAL = ; static final int VIEW_ORIENTATION_SINGLE = ; static final int VIEW_ORIENTATION_AUTOMATIC = ; static final int CALL_MODE_CALLERS = ; static final int CALL_MODE_CALLEES = ; static final String GROUP_SEARCH_SCOPE = "" ; static final String ID_CALL_HIERARCHY = "" ; private static final String GROUP_FOCUS = "" ; private static final int PAGE_EMPTY = ; private static final int PAGE_VIEWER = ; private Label fNoHierarchyShownLabel ; private PageBook fPagebook ; private IDialogSettings fDialogSettings ; private int fCurrentOrientation ; int fOrientation = VIEW_ORIENTATION_AUTOMATIC ; private int fCurrentCallMode ; private MethodWrapper fCalleeRoot ; private MethodWrapper fCallerRoot ; private IMemento fMemento ; private IMethod fShownMethod ; private CallHierarchySelectionProvider fSelectionProviderMediator ; private List fMethodHistory ; private LocationViewer fLocationViewer ; private SashForm fHierarchyLocationSplitter ; private Clipboard fClipboard ; private SearchScopeActionGroup fSearchScopeActions ; private ToggleOrientationAction [ ] fToggleOrientationActions ; private ToggleCallModeAction [ ] fToggleCallModeActions ; private CallHierarchyFiltersActionGroup fFiltersActionGroup ; private HistoryDropDownAction fHistoryDropDownAction ; private RefreshAction fRefreshAction ; private OpenLocationAction fOpenLocationAction ; private FocusOnSelectionAction fFocusOnSelectionAction ; private CopyCallHierarchyAction fCopyAction ; private CancelSearchAction fCancelSearchAction ; private CompositeActionGroup fActionGroups ; private CallHierarchyViewer fCallHierarchyViewer ; private boolean fShowCallDetails ; protected Composite fParent ; private IPartListener2 fPartListener ; public CallHierarchyViewPart ( ) { super ( ) ; fDialogSettings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; fMethodHistory = new ArrayList ( ) ; } public void setFocus ( ) { fPagebook . setFocus ( ) ; } public void setHistoryEntries ( IMethod [ ] elems ) { fMethodHistory . clear ( ) ; for ( int i = ; i < elems . length ; i ++ ) { fMethodHistory . add ( elems [ i ] ) ; } updateHistoryEntries ( ) ; } public IMethod [ ] getHistoryEntries ( ) { if ( fMethodHistory . size ( ) > ) { updateHistoryEntries ( ) ; } return ( IMethod [ ] ) fMethodHistory . toArray ( new IMethod [ fMethodHistory . size ( ) ] ) ; } public void setMethod ( IMethod method ) { if ( method == null ) { showPage ( PAGE_EMPTY ) ; return ; } if ( ! method . equals ( fShownMethod ) ) { addHistoryEntry ( method ) ; } this . fShownMethod = method ; refresh ( ) ; } public IMethod getMethod ( ) { return fShownMethod ; } public MethodWrapper getCurrentMethodWrapper ( ) { if ( fCurrentCallMode == CALL_MODE_CALLERS ) { return fCallerRoot ; } else { return fCalleeRoot ; } } void setOrientation ( int orientation ) { if ( fCurrentOrientation != orientation ) { if ( ( fLocationViewer != null ) && ! fLocationViewer . getControl ( ) . isDisposed ( ) && ( fHierarchyLocationSplitter != null ) && ! fHierarchyLocationSplitter . isDisposed ( ) ) { if ( orientation == VIEW_ORIENTATION_SINGLE ) { setShowCallDetails ( false ) ; } else { if ( fCurrentOrientation == VIEW_ORIENTATION_SINGLE ) { setShowCallDetails ( true ) ; } boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL ; fHierarchyLocationSplitter . setOrientation ( horizontal ? SWT . HORIZONTAL : SWT . VERTICAL ) ; } fHierarchyLocationSplitter . layout ( ) ; } updateCheckedState ( ) ; fCurrentOrientation = orientation ; restoreSplitterRatio ( ) ; } } private void updateCheckedState ( ) { for ( int i = ; i < fToggleOrientationActions . length ; i ++ ) { fToggleOrientationActions [ i ] . setChecked ( fOrientation == fToggleOrientationActions [ i ] . getOrientation ( ) ) ; } } void setCallMode ( int mode ) { if ( fCurrentCallMode != mode ) { for ( int i = ; i < fToggleCallModeActions . length ; i ++ ) { fToggleCallModeActions [ i ] . setChecked ( mode == fToggleCallModeActions [ i ] . getMode ( ) ) ; } fCurrentCallMode = mode ; fDialogSettings . put ( DIALOGSTORE_CALL_MODE , mode ) ; updateView ( ) ; } } public IRubySearchScope getSearchScope ( ) { return fSearchScopeActions . getSearchScope ( ) ; } public void setShowCallDetails ( boolean show ) { fShowCallDetails = show ; showOrHideCallDetailsView ( ) ; } private void initDragAndDrop ( ) { addDragAdapters ( fCallHierarchyViewer ) ; addDropAdapters ( fCallHierarchyViewer ) ; addDropAdapters ( fLocationViewer ) ; DropTarget dropTarget = new DropTarget ( fPagebook , DND . DROP_MOVE | DND . DROP_COPY | DND . DROP_LINK | DND . DROP_DEFAULT ) ; dropTarget . setTransfer ( new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) } ) ; dropTarget . addDropListener ( new CallHierarchyTransferDropAdapter ( this , fCallHierarchyViewer ) ) ; } private void addDropAdapters ( StructuredViewer viewer ) { Transfer [ ] transfers = new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) } ; int ops = DND . DROP_MOVE | DND . DROP_COPY | DND . DROP_LINK | DND . DROP_DEFAULT ; TransferDropTargetListener [ ] dropListeners = new TransferDropTargetListener [ ] { new CallHierarchyTransferDropAdapter ( this , viewer ) } ; viewer . addDropSupport ( ops , transfers , new DelegatingDropAdapter ( dropListeners ) ) ; } private void addDragAdapters ( StructuredViewer viewer ) { int ops = DND . DROP_COPY | DND . DROP_LINK ; Transfer [ ] transfers = new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) , ResourceTransfer . getInstance ( ) } ; TransferDragSourceListener [ ] dragListeners = new TransferDragSourceListener [ ] { new SelectionTransferDragAdapter ( viewer ) , new ResourceTransferDragAdapter ( viewer ) } ; viewer . addDragSupport ( ops , transfers , new RdtViewerDragAdapter ( viewer , dragListeners ) ) ; } public void createPartControl ( Composite parent ) { fParent = parent ; addResizeListener ( parent ) ; fPagebook = new PageBook ( parent , SWT . NONE ) ; createHierarchyLocationSplitter ( fPagebook ) ; createCallHierarchyViewer ( fHierarchyLocationSplitter ) ; createLocationViewer ( fHierarchyLocationSplitter ) ; fNoHierarchyShownLabel = new Label ( fPagebook , SWT . TOP + SWT . LEFT + SWT . WRAP ) ; fNoHierarchyShownLabel . setText ( CallHierarchyMessages . CallHierarchyViewPart_empty ) ; initDragAndDrop ( ) ; showPage ( PAGE_EMPTY ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( fPagebook , IRubyHelpContextIds . CALL_HIERARCHY_VIEW ) ; fSelectionProviderMediator = new CallHierarchySelectionProvider ( new StructuredViewer [ ] { fCallHierarchyViewer , fLocationViewer } ) ; IStatusLineManager slManager = getViewSite ( ) . getActionBars ( ) . getStatusLineManager ( ) ; fSelectionProviderMediator . addSelectionChangedListener ( new StatusBarUpdater ( slManager ) ) ; getSite ( ) . setSelectionProvider ( fSelectionProviderMediator ) ; fCallHierarchyViewer . initContextMenu ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager menu ) { fillCallHierarchyViewerContextMenu ( menu ) ; } } , getSite ( ) , fSelectionProviderMediator ) ; fClipboard = new Clipboard ( parent . getDisplay ( ) ) ; makeActions ( ) ; fillViewMenu ( ) ; fillActionBars ( ) ; initOrientation ( ) ; initCallMode ( ) ; if ( fMemento != null ) { restoreState ( fMemento ) ; } restoreSplitterRatio ( ) ; addPartListener ( ) ; } private void restoreSplitterRatio ( ) { String ratio = fDialogSettings . get ( DIALOGSTORE_RATIO + fCurrentOrientation ) ; if ( ratio == null ) return ; int intRatio = Integer . parseInt ( ratio ) ; fHierarchyLocationSplitter . setWeights ( new int [ ] { intRatio , - intRatio } ) ; } private void saveSplitterRatio ( ) { if ( fHierarchyLocationSplitter != null && ! fHierarchyLocationSplitter . isDisposed ( ) ) { int [ ] weigths = fHierarchyLocationSplitter . getWeights ( ) ; int ratio = ( weigths [ ] * ) / ( weigths [ ] + weigths [ ] ) ; String key = DIALOGSTORE_RATIO + fCurrentOrientation ; fDialogSettings . put ( key , ratio ) ; } } private void addPartListener ( ) { fPartListener = new IPartListener2 ( ) { public void partActivated ( IWorkbenchPartReference partRef ) { } public void partBroughtToTop ( IWorkbenchPartReference partRef ) { } public void partClosed ( IWorkbenchPartReference partRef ) { if ( ID_CALL_HIERARCHY . equals ( partRef . getId ( ) ) ) saveViewSettings ( ) ; } public void partDeactivated ( IWorkbenchPartReference partRef ) { if ( ID_CALL_HIERARCHY . equals ( partRef . getId ( ) ) ) saveViewSettings ( ) ; } public void partOpened ( IWorkbenchPartReference partRef ) { } public void partHidden ( IWorkbenchPartReference partRef ) { } public void partVisible ( IWorkbenchPartReference partRef ) { } public void partInputChanged ( IWorkbenchPartReference partRef ) { } } ; getViewSite ( ) . getPage ( ) . addPartListener ( fPartListener ) ; } protected void saveViewSettings ( ) { saveSplitterRatio ( ) ; fDialogSettings . put ( DIALOGSTORE_VIEWORIENTATION , fOrientation ) ; } private void addResizeListener ( Composite parent ) { parent . addControlListener ( new ControlListener ( ) { public void controlMoved ( ControlEvent e ) { } public void controlResized ( ControlEvent e ) { computeOrientation ( ) ; } } ) ; } void computeOrientation ( ) { saveSplitterRatio ( ) ; fDialogSettings . put ( DIALOGSTORE_VIEWORIENTATION , fOrientation ) ; if ( fOrientation != VIEW_ORIENTATION_AUTOMATIC ) { setOrientation ( fOrientation ) ; } else { if ( fOrientation == VIEW_ORIENTATION_SINGLE ) return ; Point size = fParent . getSize ( ) ; if ( size . x != && size . y != ) { if ( size . x > size . y ) setOrientation ( VIEW_ORIENTATION_HORIZONTAL ) ; else setOrientation ( VIEW_ORIENTATION_VERTICAL ) ; } } } private void showPage ( int page ) { if ( page == PAGE_EMPTY ) { fPagebook . showPage ( fNoHierarchyShownLabel ) ; } else { fPagebook . showPage ( fHierarchyLocationSplitter ) ; } } private void restoreState ( IMemento memento ) { fSearchScopeActions . restoreState ( memento ) ; } private void initCallMode ( ) { int mode ; try { mode = fDialogSettings . getInt ( DIALOGSTORE_CALL_MODE ) ; if ( ( mode < ) || ( mode > ) ) { mode = CALL_MODE_CALLERS ; } } catch ( NumberFormatException e ) { mode = CALL_MODE_CALLERS ; } fCurrentCallMode = - ; setCallMode ( mode ) ; } private void initOrientation ( ) { try { fOrientation = fDialogSettings . getInt ( DIALOGSTORE_VIEWORIENTATION ) ; if ( ( fOrientation < ) || ( fOrientation > ) ) { fOrientation = VIEW_ORIENTATION_AUTOMATIC ; } } catch ( NumberFormatException e ) { fOrientation = VIEW_ORIENTATION_AUTOMATIC ; } fCurrentOrientation = - ; setOrientation ( fOrientation ) ; } private void fillViewMenu ( ) { IActionBars actionBars = getViewSite ( ) . getActionBars ( ) ; IMenuManager viewMenu = actionBars . getMenuManager ( ) ; viewMenu . add ( new Separator ( ) ) ; for ( int i = ; i < fToggleCallModeActions . length ; i ++ ) { viewMenu . add ( fToggleCallModeActions [ i ] ) ; } viewMenu . add ( new Separator ( ) ) ; MenuManager layoutSubMenu = new MenuManager ( CallHierarchyMessages . CallHierarchyViewPart_layout_menu ) ; for ( int i = ; i < fToggleOrientationActions . length ; i ++ ) { layoutSubMenu . add ( fToggleOrientationActions [ i ] ) ; } viewMenu . add ( layoutSubMenu ) ; } public void dispose ( ) { if ( fActionGroups != null ) fActionGroups . dispose ( ) ; if ( fClipboard != null ) fClipboard . dispose ( ) ; if ( fPartListener != null ) { getViewSite ( ) . getPage ( ) . removePartListener ( fPartListener ) ; fPartListener = null ; } super . dispose ( ) ; } public void gotoHistoryEntry ( IMethod entry ) { if ( fMethodHistory . contains ( entry ) ) { setMethod ( entry ) ; } } public void init ( IViewSite site , IMemento memento ) throws PartInitException { super . init ( site , memento ) ; fMemento = memento ; } public void refresh ( ) { setCalleeRoot ( null ) ; setCallerRoot ( null ) ; updateView ( ) ; } public void saveState ( IMemento memento ) { if ( fPagebook == null ) { if ( fMemento != null ) { memento . putMemento ( fMemento ) ; } return ; } fSearchScopeActions . saveState ( memento ) ; } public void selectionChanged ( SelectionChangedEvent e ) { if ( e . getSelectionProvider ( ) == fCallHierarchyViewer ) { methodSelectionChanged ( e . getSelection ( ) ) ; } } private void methodSelectionChanged ( ISelection selection ) { if ( selection instanceof IStructuredSelection && ( ( IStructuredSelection ) selection ) . size ( ) == ) { Object selectedElement = ( ( IStructuredSelection ) selection ) . getFirstElement ( ) ; if ( selectedElement instanceof MethodWrapper ) { MethodWrapper methodWrapper = ( MethodWrapper ) selectedElement ; revealElementInEditor ( methodWrapper , fCallHierarchyViewer ) ; updateLocationsView ( methodWrapper ) ; } else { updateLocationsView ( null ) ; } } else { updateLocationsView ( null ) ; } } private void revealElementInEditor ( Object elem , Viewer originViewer ) { if ( getSite ( ) . getPage ( ) . getActivePart ( ) != this ) { return ; } if ( fSelectionProviderMediator . getViewerInFocus ( ) != originViewer ) { return ; } if ( elem instanceof MethodWrapper ) { CallLocation callLocation = CallHierarchy . getCallLocation ( elem ) ; if ( callLocation != null ) { IEditorPart editorPart = CallHierarchyUI . isOpenInEditor ( callLocation ) ; if ( editorPart != null ) { getSite ( ) . getPage ( ) . bringToTop ( editorPart ) ; if ( editorPart instanceof ITextEditor ) { ITextEditor editor = ( ITextEditor ) editorPart ; editor . selectAndReveal ( callLocation . getStart ( ) , ( callLocation . getEnd ( ) - callLocation . getStart ( ) ) ) ; } } } else { IEditorPart editorPart = CallHierarchyUI . isOpenInEditor ( elem ) ; getSite ( ) . getPage ( ) . bringToTop ( editorPart ) ; EditorUtility . revealInEditor ( editorPart , ( ( MethodWrapper ) elem ) . getMember ( ) ) ; } } else if ( elem instanceof IRubyElement ) { IEditorPart editorPart = EditorUtility . isOpenInEditor ( elem ) ; if ( editorPart != null ) { getSite ( ) . getPage ( ) . bringToTop ( editorPart ) ; EditorUtility . revealInEditor ( editorPart , ( IRubyElement ) elem ) ; } } } public Object getAdapter ( Class adapter ) { return super . getAdapter ( adapter ) ; } protected ISelection getSelection ( ) { StructuredViewer viewerInFocus = fSelectionProviderMediator . getViewerInFocus ( ) ; if ( viewerInFocus != null ) { return viewerInFocus . getSelection ( ) ; } return StructuredSelection . EMPTY ; } protected void fillLocationViewerContextMenu ( IMenuManager menu ) { RubyPlugin . createStandardGroups ( menu ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_SHOW , fOpenLocationAction ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_SHOW , fRefreshAction ) ; } protected void handleKeyEvent ( KeyEvent event ) { if ( event . stateMask == ) { if ( event . keyCode == SWT . F5 ) { if ( ( fRefreshAction != null ) && fRefreshAction . isEnabled ( ) ) { fRefreshAction . run ( ) ; return ; } } } } private IActionBars getActionBars ( ) { return getViewSite ( ) . getActionBars ( ) ; } private void setCalleeRoot ( MethodWrapper calleeRoot ) { this . fCalleeRoot = calleeRoot ; } private MethodWrapper getCalleeRoot ( ) { if ( fCalleeRoot == null ) { fCalleeRoot = CallHierarchy . getDefault ( ) . getCalleeRoot ( fShownMethod ) ; } return fCalleeRoot ; } private void setCallerRoot ( MethodWrapper callerRoot ) { this . fCallerRoot = callerRoot ; } private MethodWrapper getCallerRoot ( ) { if ( fCallerRoot == null ) { fCallerRoot = CallHierarchy . getDefault ( ) . getCallerRoot ( fShownMethod ) ; } return fCallerRoot ; } private void addHistoryEntry ( IRubyElement entry ) { if ( fMethodHistory . contains ( entry ) ) { fMethodHistory . remove ( entry ) ; } fMethodHistory . add ( , entry ) ; fHistoryDropDownAction . setEnabled ( ! fMethodHistory . isEmpty ( ) ) ; } private void createLocationViewer ( Composite parent ) { fLocationViewer = new LocationViewer ( parent ) ; fLocationViewer . getControl ( ) . addKeyListener ( createKeyListener ( ) ) ; fLocationViewer . initContextMenu ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager menu ) { fillLocationViewerContextMenu ( menu ) ; } } , ID_CALL_HIERARCHY , getSite ( ) ) ; } private void createHierarchyLocationSplitter ( Composite parent ) { fHierarchyLocationSplitter = new SashForm ( parent , SWT . NONE ) ; fHierarchyLocationSplitter . addKeyListener ( createKeyListener ( ) ) ; } private void createCallHierarchyViewer ( Composite parent ) { fCallHierarchyViewer = new CallHierarchyViewer ( parent , this ) ; fCallHierarchyViewer . addKeyListener ( createKeyListener ( ) ) ; fCallHierarchyViewer . addSelectionChangedListener ( this ) ; } protected void fillCallHierarchyViewerContextMenu ( IMenuManager menu ) { RubyPlugin . createStandardGroups ( menu ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_SHOW , fRefreshAction ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_SHOW , new Separator ( GROUP_FOCUS ) ) ; if ( fFocusOnSelectionAction . canActionBeAdded ( ) ) { menu . appendToGroup ( GROUP_FOCUS , fFocusOnSelectionAction ) ; } if ( fCopyAction . canActionBeAdded ( ) ) { menu . appendToGroup ( GROUP_FOCUS , fCopyAction ) ; } fActionGroups . setContext ( new ActionContext ( getSelection ( ) ) ) ; fActionGroups . fillContextMenu ( menu ) ; fActionGroups . setContext ( null ) ; } private void fillActionBars ( ) { IActionBars actionBars = getActionBars ( ) ; IToolBarManager toolBar = actionBars . getToolBarManager ( ) ; fActionGroups . fillActionBars ( actionBars ) ; toolBar . add ( fCancelSearchAction ) ; for ( int i = ; i < fToggleCallModeActions . length ; i ++ ) { toolBar . add ( fToggleCallModeActions [ i ] ) ; } toolBar . add ( fHistoryDropDownAction ) ; } private KeyListener createKeyListener ( ) { KeyListener keyListener = new KeyAdapter ( ) { public void keyReleased ( KeyEvent event ) { handleKeyEvent ( event ) ; } } ; return keyListener ; } private void makeActions ( ) { fRefreshAction = new RefreshAction ( this ) ; fOpenLocationAction = new OpenLocationAction ( this , getSite ( ) ) ; fLocationViewer . addOpenListener ( new IOpenListener ( ) { public void open ( OpenEvent event ) { fOpenLocationAction . run ( ) ; } } ) ; fFocusOnSelectionAction = new FocusOnSelectionAction ( this ) ; fCopyAction = new CopyCallHierarchyAction ( this , fClipboard , fCallHierarchyViewer ) ; fSearchScopeActions = new SearchScopeActionGroup ( this , fDialogSettings ) ; fFiltersActionGroup = new CallHierarchyFiltersActionGroup ( this , fCallHierarchyViewer ) ; fHistoryDropDownAction = new HistoryDropDownAction ( this ) ; fHistoryDropDownAction . setEnabled ( false ) ; fCancelSearchAction = new CancelSearchAction ( this ) ; setCancelEnabled ( false ) ; fToggleOrientationActions = new ToggleOrientationAction [ ] { new ToggleOrientationAction ( this , VIEW_ORIENTATION_VERTICAL ) , new ToggleOrientationAction ( this , VIEW_ORIENTATION_HORIZONTAL ) , new ToggleOrientationAction ( this , VIEW_ORIENTATION_AUTOMATIC ) , new ToggleOrientationAction ( this , VIEW_ORIENTATION_SINGLE ) } ; fToggleCallModeActions = new ToggleCallModeAction [ ] { new ToggleCallModeAction ( this , CALL_MODE_CALLERS ) , new ToggleCallModeAction ( this , CALL_MODE_CALLEES ) } ; fActionGroups = new CompositeActionGroup ( new ActionGroup [ ] { new OpenEditorActionGroup ( this ) , new OpenViewActionGroup ( this ) , new RubySearchActionGroup ( this ) , fSearchScopeActions , fFiltersActionGroup } ) ; } private void showOrHideCallDetailsView ( ) { if ( fShowCallDetails ) { fHierarchyLocationSplitter . setMaximizedControl ( null ) ; } else { fHierarchyLocationSplitter . setMaximizedControl ( fCallHierarchyViewer . getControl ( ) ) ; } } private void updateLocationsView ( MethodWrapper methodWrapper ) { if ( methodWrapper != null && methodWrapper . getMethodCall ( ) . hasCallLocations ( ) ) { fLocationViewer . setInput ( methodWrapper . getMethodCall ( ) . getCallLocations ( ) ) ; } else { fLocationViewer . clearViewer ( ) ; } } private void updateHistoryEntries ( ) { for ( int i = fMethodHistory . size ( ) - ; i >= ; i -- ) { IMethod method = ( IMethod ) fMethodHistory . get ( i ) ; if ( ! method . exists ( ) ) { fMethodHistory . remove ( i ) ; } } fHistoryDropDownAction . setEnabled ( ! fMethodHistory . isEmpty ( ) ) ; } private void updateView ( ) { if ( ( fShownMethod != null ) ) { showPage ( PAGE_VIEWER ) ; CallHierarchy . getDefault ( ) . setSearchScope ( getSearchScope ( ) ) ; String elementName = RubyElementLabels . getElementLabel ( fShownMethod , RubyElementLabels . ALL_DEFAULT ) ; String scopeDescription = fSearchScopeActions . getFullDescription ( ) ; String [ ] args = new String [ ] { elementName , scopeDescription } ; fCallHierarchyViewer . setInput ( null ) ; if ( fCurrentCallMode == CALL_MODE_CALLERS ) { setContentDescription ( Messages . format ( CallHierarchyMessages . CallHierarchyViewPart_callsToMethod , args ) ) ; fCallHierarchyViewer . setSorter ( new ViewerSorter ( ) ) ; fCallHierarchyViewer . setMethodWrapper ( getCallerRoot ( ) ) ; } else { setContentDescription ( Messages . format ( CallHierarchyMessages . CallHierarchyViewPart_callsFromMethod , args ) ) ; fCallHierarchyViewer . setSorter ( null ) ; fCallHierarchyViewer . setMethodWrapper ( getCalleeRoot ( ) ) ; } } } static CallHierarchyViewPart findAndShowCallersView ( IWorkbenchPartSite site ) { IWorkbenchPage workbenchPage = site . getPage ( ) ; CallHierarchyViewPart callersView = null ; try { callersView = ( CallHierarchyViewPart ) workbenchPage . showView ( CallHierarchyViewPart . ID_CALL_HIERARCHY ) ; } catch ( PartInitException e ) { RubyPlugin . log ( e ) ; } return callersView ; } void cancelJobs ( ) { fCallHierarchyViewer . cancelJobs ( ) ; } void setCancelEnabled ( boolean enabled ) { fCancelSearchAction . setEnabled ( enabled ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . rubypeople . rdt . core . search . IRubySearchScope ; abstract class SearchScopeAction extends Action { private final SearchScopeActionGroup fGroup ; public SearchScopeAction ( SearchScopeActionGroup group , String text ) { super ( text , AS_RADIO_BUTTON ) ; this . fGroup = group ; } public abstract IRubySearchScope getSearchScope ( ) ; public abstract int getSearchScopeType ( ) ; public void run ( ) { this . fGroup . setSelected ( this , true ) ; } public abstract String getFullDescription ( ) ; } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class CancelSearchAction extends Action { private CallHierarchyViewPart fView ; public CancelSearchAction ( CallHierarchyViewPart view ) { super ( CallHierarchyMessages . CancelSearchAction_label ) ; fView = view ; setToolTipText ( CallHierarchyMessages . CancelSearchAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_CANCEL_SEARCH_ACTION ) ; } public void run ( ) { fView . cancelJobs ( ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . corext . callhierarchy . MethodWrapper ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . util . SelectionUtil ; class FocusOnSelectionAction extends Action { private CallHierarchyViewPart fPart ; public FocusOnSelectionAction ( CallHierarchyViewPart part ) { super ( CallHierarchyMessages . FocusOnSelectionAction_focusOnSelection_text ) ; fPart = part ; setDescription ( CallHierarchyMessages . FocusOnSelectionAction_focusOnSelection_description ) ; setToolTipText ( CallHierarchyMessages . FocusOnSelectionAction_focusOnSelection_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_FOCUS_ON_SELECTION_ACTION ) ; } public boolean canActionBeAdded ( ) { Object element = SelectionUtil . getSingleElement ( getSelection ( ) ) ; IMethod method = getSelectedMethod ( element ) ; if ( method != null ) { setText ( Messages . format ( CallHierarchyMessages . FocusOnSelectionAction_focusOn_text , method . getElementName ( ) ) ) ; return true ; } return false ; } private IMethod getSelectedMethod ( Object element ) { IMethod method = null ; if ( element instanceof IMethod ) { method = ( IMethod ) element ; } else if ( element instanceof MethodWrapper ) { IMember member = ( ( MethodWrapper ) element ) . getMember ( ) ; if ( member . getElementType ( ) == IRubyElement . METHOD ) { method = ( IMethod ) member ; } } return method ; } public void run ( ) { Object element = SelectionUtil . getSingleElement ( getSelection ( ) ) ; IMethod method = getSelectedMethod ( element ) ; if ( method != null ) { fPart . setMethod ( method ) ; } } private ISelection getSelection ( ) { ISelectionProvider provider = fPart . getSite ( ) . getSelectionProvider ( ) ; if ( provider != null ) { return provider . getSelection ( ) ; } return null ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; class SearchScopeWorkingSetAction extends SearchScopeAction { private IWorkingSet [ ] fWorkingSets ; public SearchScopeWorkingSetAction ( SearchScopeActionGroup group , IWorkingSet [ ] workingSets , String name ) { super ( group , name ) ; setToolTipText ( CallHierarchyMessages . SearchScopeActionGroup_workingset_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_SEARCH_SCOPE_ACTION ) ; this . fWorkingSets = workingSets ; } public IRubySearchScope getSearchScope ( ) { return RubySearchScopeFactory . getInstance ( ) . createRubySearchScope ( fWorkingSets , true ) ; } public IWorkingSet [ ] getWorkingSets ( ) { return fWorkingSets ; } public int getSearchScopeType ( ) { return SearchScopeActionGroup . SEARCH_SCOPE_TYPE_WORKING_SET ; } public String getFullDescription ( ) { return RubySearchScopeFactory . getInstance ( ) . getWorkingSetScopeDescription ( fWorkingSets , true ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DropTargetEvent ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . internal . ui . packageview . SelectionTransferDropAdapter ; import org . rubypeople . rdt . internal . ui . util . SelectionUtil ; class CallHierarchyTransferDropAdapter extends SelectionTransferDropAdapter { private static final int OPERATION = DND . DROP_LINK ; private CallHierarchyViewPart fCallHierarchyViewPart ; public CallHierarchyTransferDropAdapter ( CallHierarchyViewPart viewPart , StructuredViewer viewer ) { super ( viewer ) ; setFullWidthMatchesItem ( false ) ; fCallHierarchyViewPart = viewPart ; } public void validateDrop ( Object target , DropTargetEvent event , int operation ) { event . detail = DND . DROP_NONE ; initializeSelection ( ) ; if ( target != null ) { super . validateDrop ( target , event , operation ) ; return ; } if ( getInputElement ( getSelection ( ) ) != null ) event . detail = OPERATION ; } public boolean isEnabled ( DropTargetEvent event ) { return true ; } public void drop ( Object target , DropTargetEvent event ) { if ( target != null || event . detail != OPERATION ) { super . drop ( target , event ) ; return ; } IMethod input = getInputElement ( getSelection ( ) ) ; fCallHierarchyViewPart . setMethod ( input ) ; } private static IMethod getInputElement ( ISelection selection ) { Object single = SelectionUtil . getSingleElement ( selection ) ; if ( single == null ) return null ; return getCandidate ( single ) ; } public static IMethod getCandidate ( Object input ) { if ( ! ( input instanceof IMethod ) ) { return null ; } return ( IMethod ) input ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . corext . callhierarchy . CallHierarchy ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; class FiltersDialog extends StatusDialog { private Label fNamesHelpText ; private Button fFilterOnNames ; private Text fNames ; private Text fMaxCallDepth ; protected FiltersDialog ( Shell parentShell ) { super ( parentShell ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; newShell . setText ( CallHierarchyMessages . FiltersDialog_filter ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . CALL_HIERARCHY_FILTERS_DIALOG ) ; } protected Control createDialogArea ( Composite parent ) { Composite superComposite = ( Composite ) super . createDialogArea ( parent ) ; Composite composite = new Composite ( superComposite , SWT . NONE ) ; composite . setFont ( superComposite . getFont ( ) ) ; composite . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . verticalSpacing = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; composite . setLayout ( layout ) ; createNamesArea ( composite ) ; new Label ( composite , SWT . NONE ) ; createMaxCallDepthArea ( composite ) ; updateUIFromFilter ( ) ; return composite ; } private void createMaxCallDepthArea ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; Label label = new Label ( composite , SWT . NONE ) ; label . setFont ( composite . getFont ( ) ) ; label . setText ( CallHierarchyMessages . FiltersDialog_maxCallDepth ) ; fMaxCallDepth = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; fMaxCallDepth . setFont ( composite . getFont ( ) ) ; fMaxCallDepth . setTextLimit ( ) ; fMaxCallDepth . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { validateInput ( ) ; } } ) ; GridData gridData = new GridData ( ) ; gridData . widthHint = convertWidthInCharsToPixels ( ) ; fMaxCallDepth . setLayoutData ( gridData ) ; } private void createNamesArea ( Composite parent ) { fFilterOnNames = createCheckbox ( parent , CallHierarchyMessages . FiltersDialog_filterOnNames , true ) ; fNames = new Text ( parent , SWT . SINGLE | SWT . BORDER ) ; fNames . setFont ( parent . getFont ( ) ) ; fNames . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { validateInput ( ) ; } } ) ; GridData gridData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . GRAB_HORIZONTAL ) ; gridData . widthHint = convertWidthInCharsToPixels ( ) ; fNames . setLayoutData ( gridData ) ; fNamesHelpText = new Label ( parent , SWT . LEFT ) ; fNamesHelpText . setFont ( parent . getFont ( ) ) ; fNamesHelpText . setText ( CallHierarchyMessages . FiltersDialog_filterOnNamesSubCaption ) ; } private Button createCheckbox ( Composite parent , String text , boolean grabRow ) { Button button = new Button ( parent , SWT . CHECK ) ; button . setFont ( parent . getFont ( ) ) ; if ( grabRow ) { GridData gridData = new GridData ( GridData . FILL_HORIZONTAL ) ; button . setLayoutData ( gridData ) ; } button . setText ( text ) ; button . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { validateInput ( ) ; updateEnabledState ( ) ; } } ) ; return button ; } private void updateEnabledState ( ) { fNames . setEnabled ( fFilterOnNames . getSelection ( ) ) ; fNamesHelpText . setEnabled ( fFilterOnNames . getSelection ( ) ) ; } private void updateFilterFromUI ( ) { int maxCallDepth = Integer . parseInt ( this . fMaxCallDepth . getText ( ) ) ; CallHierarchyUI . getDefault ( ) . setMaxCallDepth ( maxCallDepth ) ; CallHierarchy . getDefault ( ) . setFilters ( fNames . getText ( ) ) ; CallHierarchy . getDefault ( ) . setFilterEnabled ( fFilterOnNames . getSelection ( ) ) ; } private void updateUIFromFilter ( ) { fMaxCallDepth . setText ( String . valueOf ( CallHierarchyUI . getDefault ( ) . getMaxCallDepth ( ) ) ) ; fNames . setText ( CallHierarchy . getDefault ( ) . getFilters ( ) ) ; fFilterOnNames . setSelection ( CallHierarchy . getDefault ( ) . isFilterEnabled ( ) ) ; updateEnabledState ( ) ; } protected void okPressed ( ) { if ( ! isMaxCallDepthValid ( ) ) { if ( fMaxCallDepth . forceFocus ( ) ) { fMaxCallDepth . setSelection ( , fMaxCallDepth . getCharCount ( ) ) ; fMaxCallDepth . showSelection ( ) ; } } updateFilterFromUI ( ) ; super . okPressed ( ) ; } private boolean isMaxCallDepthValid ( ) { String text = fMaxCallDepth . getText ( ) ; if ( text . length ( ) == ) return false ; try { int maxCallDepth = Integer . parseInt ( text ) ; return ( maxCallDepth >= && maxCallDepth <= ) ; } catch ( NumberFormatException e ) { return false ; } } private void validateInput ( ) { StatusInfo status = new StatusInfo ( ) ; if ( ! isMaxCallDepthValid ( ) ) { status . setError ( CallHierarchyMessages . FiltersDialog_messageMaxCallDepthInvalid ) ; } updateStatus ( status ) ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . internal . corext . callhierarchy . CallLocation ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; class LocationLabelProvider extends LabelProvider implements ITableLabelProvider { private static final int COLUMN_ICON = ; private static final int COLUMN_LINE = ; private static final int COLUMN_INFO = ; LocationLabelProvider ( ) { } public String getText ( Object element ) { return getColumnText ( element , COLUMN_INFO ) ; } public Image getImage ( Object element ) { return getColumnImage ( element , COLUMN_ICON ) ; } private String removeWhitespaceOutsideStringLiterals ( CallLocation callLocation ) { StringBuffer buf = new StringBuffer ( ) ; boolean withinString = false ; String s = callLocation . getCallText ( ) ; for ( int i = ; i < s . length ( ) ; i ++ ) { char ch = s . charAt ( i ) ; if ( ch == '' ) { withinString = ! withinString ; } if ( withinString ) { buf . append ( ch ) ; } else if ( Character . isWhitespace ( ch ) ) { if ( ( buf . length ( ) == ) || ! Character . isWhitespace ( buf . charAt ( buf . length ( ) - ) ) ) { if ( ch != '' ) { ch = '' ; } buf . append ( ch ) ; } } else { buf . append ( ch ) ; } } return buf . toString ( ) ; } public Image getColumnImage ( Object element , int columnIndex ) { if ( columnIndex == COLUMN_ICON ) { return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_SEARCH_OCCURRENCE ) ; } return null ; } public String getColumnText ( Object element , int columnIndex ) { if ( element instanceof CallLocation ) { CallLocation callLocation = ( CallLocation ) element ; switch ( columnIndex ) { case COLUMN_LINE : int lineNumber = callLocation . getLineNumber ( ) ; if ( lineNumber == CallLocation . UNKNOWN_LINE_NUMBER ) { return CallHierarchyMessages . LocationLabelProvider_unknown ; } else { return String . valueOf ( lineNumber ) ; } case COLUMN_INFO : return removeWhitespaceOutsideStringLiterals ( callLocation ) ; } } return "" ; } } package org . rubypeople . rdt . internal . ui . callhierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; class RefreshAction extends Action { private CallHierarchyViewPart fPart ; public RefreshAction ( CallHierarchyViewPart part ) { fPart = part ; setText ( CallHierarchyMessages . RefreshAction_text ) ; setToolTipText ( CallHierarchyMessages . RefreshAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; setActionDefinitionId ( "" ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_REFRESH_ACTION ) ; } public void run ( ) { fPart . refresh ( ) ; } } package org . rubypeople . rdt . internal . ui . compare ; import org . eclipse . osgi . util . NLS ; public class CompareMessages extends NLS { private static final String BUNDLE_NAME = "" ; private CompareMessages ( ) { } public static String RubyNode_importDeclarations ; public static String RubyNode_script ; public static String RubyMergeViewer_title ; public static String RubyStructureViewer_title ; static { NLS . initializeMessages ( BUNDLE_NAME , CompareMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . compare ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . UnsupportedEncodingException ; import java . util . ArrayList ; import java . util . List ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . IEncodedStreamContentAccessor ; import org . eclipse . compare . IStreamContentAccessor ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentPartitioner ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . text . RubyTextTools ; class RubyCompareUtilities { private static final char IMPORTDECLARATION = '' ; private static final char IMPORT_CONTAINER = '' ; private static final char FIELD = '' ; private static final char METHOD = '' ; private static final char SCRIPT = '' ; private static final char TYPE = '' ; static String getString ( ResourceBundle bundle , String key , String dfltValue ) { if ( bundle != null ) { try { return bundle . getString ( key ) ; } catch ( MissingResourceException x ) { } } return dfltValue ; } static String getString ( ResourceBundle bundle , String key ) { return getString ( bundle , key , key ) ; } static int getInteger ( ResourceBundle bundle , String key , int dfltValue ) { if ( bundle != null ) { try { String s = bundle . getString ( key ) ; if ( s != null ) return Integer . parseInt ( s ) ; } catch ( NumberFormatException x ) { } catch ( MissingResourceException x ) { } } return dfltValue ; } static ImageDescriptor getImageDescriptor ( int type ) { switch ( type ) { case IRubyElement . METHOD : return getImageDescriptor ( "" ) ; case IRubyElement . FIELD : return getImageDescriptor ( "" ) ; case IRubyElement . IMPORT_DECLARATION : return RubyPluginImages . DESC_OBJS_IMPDECL ; case IRubyElement . IMPORT_CONTAINER : return RubyPluginImages . DESC_OBJS_IMPCONT ; case IRubyElement . SCRIPT : return RubyPluginImages . DESC_OBJS_SCRIPT ; } return ImageDescriptor . getMissingImageDescriptor ( ) ; } static ImageDescriptor getTypeImageDescriptor ( boolean isClass ) { if ( isClass ) return RubyPluginImages . DESC_OBJS_CLASS ; return RubyPluginImages . DESC_OBJS_MODULE ; } static ImageDescriptor getImageDescriptor ( IMember element ) { int t = element . getElementType ( ) ; if ( t == IRubyElement . TYPE ) { IType type = ( IType ) element ; return getTypeImageDescriptor ( type . isClass ( ) ) ; } return getImageDescriptor ( t ) ; } static String getRubyElementID ( IRubyElement je ) { StringBuffer sb = new StringBuffer ( ) ; switch ( je . getElementType ( ) ) { case IRubyElement . SCRIPT : sb . append ( SCRIPT ) ; break ; case IRubyElement . TYPE : sb . append ( TYPE ) ; sb . append ( je . getElementName ( ) ) ; break ; case IRubyElement . FIELD : sb . append ( FIELD ) ; sb . append ( je . getElementName ( ) ) ; break ; case IRubyElement . METHOD : sb . append ( METHOD ) ; sb . append ( RubyElementLabels . getElementLabel ( je , RubyElementLabels . M_PARAMETER_NAMES ) ) ; break ; case IRubyElement . IMPORT_CONTAINER : sb . append ( IMPORT_CONTAINER ) ; break ; case IRubyElement . IMPORT_DECLARATION : sb . append ( IMPORTDECLARATION ) ; sb . append ( je . getElementName ( ) ) ; break ; default : return null ; } return sb . toString ( ) ; } static String buildID ( int type , String name ) { StringBuffer sb = new StringBuffer ( ) ; switch ( type ) { case RubyNode . SCRIPT : sb . append ( SCRIPT ) ; break ; case RubyNode . CLASS : case RubyNode . MODULE : sb . append ( TYPE ) ; sb . append ( name ) ; break ; case RubyNode . FIELD : sb . append ( FIELD ) ; sb . append ( name ) ; break ; case RubyNode . CONSTRUCTOR : case RubyNode . METHOD : sb . append ( METHOD ) ; sb . append ( name ) ; break ; case RubyNode . IMPORT : sb . append ( IMPORTDECLARATION ) ; sb . append ( name ) ; break ; case RubyNode . IMPORT_CONTAINER : sb . append ( IMPORT_CONTAINER ) ; break ; default : Assert . isTrue ( false ) ; break ; } return sb . toString ( ) ; } static ImageDescriptor getImageDescriptor ( String relativePath ) { IPath path = RubyPluginImages . ICONS_PATH . append ( relativePath ) ; return RubyPluginImages . createImageDescriptor ( RubyPlugin . getDefault ( ) . getBundle ( ) , path , true ) ; } static boolean getBoolean ( CompareConfiguration cc , String key , boolean dflt ) { if ( cc != null ) { Object value = cc . getProperty ( key ) ; if ( value instanceof Boolean ) return ( ( Boolean ) value ) . booleanValue ( ) ; } return dflt ; } static Image getImage ( IMember member ) { ImageDescriptor id = getImageDescriptor ( member ) ; return id . createImage ( ) ; } static RubyTextTools getRubyTextTools ( ) { RubyPlugin plugin = RubyPlugin . getDefault ( ) ; if ( plugin != null ) return plugin . getRubyTextTools ( ) ; return null ; } static IDocumentPartitioner createRubyPartitioner ( ) { RubyTextTools tools = getRubyTextTools ( ) ; if ( tools != null ) return tools . createDocumentPartitioner ( ) ; return null ; } static void setupDocument ( IDocument document ) { RubyTextTools tools = getRubyTextTools ( ) ; if ( tools != null ) tools . setupRubyDocumentPartitioner ( document , IRubyPartitions . RUBY_PARTITIONING ) ; } private static String readString ( InputStream is , String encoding ) { if ( is == null ) return null ; BufferedReader reader = null ; try { StringBuffer buffer = new StringBuffer ( ) ; char [ ] part = new char [ ] ; int read = ; reader = new BufferedReader ( new InputStreamReader ( is , encoding ) ) ; while ( ( read = reader . read ( part ) ) != - ) buffer . append ( part , , read ) ; return buffer . toString ( ) ; } catch ( IOException ex ) { } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException ex ) { } } } return null ; } public static String readString ( IStreamContentAccessor sa ) throws CoreException { InputStream is = sa . getContents ( ) ; if ( is != null ) { String encoding = null ; if ( sa instanceof IEncodedStreamContentAccessor ) { try { encoding = ( ( IEncodedStreamContentAccessor ) sa ) . getCharset ( ) ; } catch ( Exception e ) { } } if ( encoding == null ) encoding = ResourcesPlugin . getEncoding ( ) ; return readString ( is , encoding ) ; } return null ; } static byte [ ] getBytes ( String s , String encoding ) { try { return s . getBytes ( encoding ) ; } catch ( UnsupportedEncodingException e ) { return s . getBytes ( ) ; } } static String [ ] readLines ( InputStream is2 , String encoding ) { BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( is2 , encoding ) ) ; StringBuffer sb = new StringBuffer ( ) ; List list = new ArrayList ( ) ; while ( true ) { int c = reader . read ( ) ; if ( c == - ) break ; sb . append ( ( char ) c ) ; if ( c == '' ) { c = reader . read ( ) ; if ( c == - ) break ; sb . append ( ( char ) c ) ; if ( c == '' ) { list . add ( sb . toString ( ) ) ; sb = new StringBuffer ( ) ; } } else if ( c == '' ) { list . add ( sb . toString ( ) ) ; sb = new StringBuffer ( ) ; } } if ( sb . length ( ) > ) list . add ( sb . toString ( ) ) ; return ( String [ ] ) list . toArray ( new String [ list . size ( ) ] ) ; } catch ( IOException ex ) { return null ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException ex ) { } } } } static void initAction ( IAction a , ResourceBundle bundle , String prefix ) { String labelKey = "" ; String tooltipKey = "" ; String imageKey = "" ; String descriptionKey = "" ; if ( prefix != null && prefix . length ( ) > ) { labelKey = prefix + labelKey ; tooltipKey = prefix + tooltipKey ; imageKey = prefix + imageKey ; descriptionKey = prefix + descriptionKey ; } a . setText ( getString ( bundle , labelKey , labelKey ) ) ; a . setToolTipText ( getString ( bundle , tooltipKey , null ) ) ; a . setDescription ( getString ( bundle , descriptionKey , null ) ) ; String relPath = getString ( bundle , imageKey , null ) ; if ( relPath != null && relPath . trim ( ) . length ( ) > ) { String dPath ; String ePath ; if ( relPath . indexOf ( "" ) >= ) { String path = relPath . substring ( ) ; dPath = '' + path ; ePath = '' + path ; } else { dPath = "" + relPath ; ePath = "" + relPath ; } ImageDescriptor id = RubyCompareUtilities . getImageDescriptor ( dPath ) ; if ( id != null ) a . setDisabledImageDescriptor ( id ) ; id = RubyCompareUtilities . getImageDescriptor ( ePath ) ; if ( id != null ) { a . setImageDescriptor ( id ) ; a . setHoverImageDescriptor ( id ) ; } } } static void initToggleAction ( IAction a , ResourceBundle bundle , String prefix , boolean checked ) { String tooltip = null ; if ( checked ) tooltip = getString ( bundle , prefix + "" , null ) ; else tooltip = getString ( bundle , prefix + "" , null ) ; if ( tooltip == null ) tooltip = getString ( bundle , prefix + "" , null ) ; if ( tooltip != null ) a . setToolTipText ( tooltip ) ; String description = null ; if ( checked ) description = getString ( bundle , prefix + "" , null ) ; else description = getString ( bundle , prefix + "" , null ) ; if ( description == null ) description = getString ( bundle , prefix + "" , null ) ; if ( description != null ) a . setDescription ( description ) ; } } package org . rubypeople . rdt . internal . ui . compare ; import org . eclipse . compare . IStreamContentAccessor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . ui . text . RubySourceViewerConfiguration ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class RubyTextViewer extends Viewer { private SourceViewer fSourceViewer ; private Object fInput ; RubyTextViewer ( Composite parent ) { fSourceViewer = new SourceViewer ( parent , null , SWT . LEFT_TO_RIGHT | SWT . H_SCROLL | SWT . V_SCROLL ) ; RubyTextTools tools = RubyCompareUtilities . getRubyTextTools ( ) ; if ( tools != null ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; fSourceViewer . configure ( new RubySourceViewerConfiguration ( tools . getColorManager ( ) , store , null , IRubyPartitions . RUBY_PARTITIONING ) ) ; } fSourceViewer . setEditable ( false ) ; String symbolicFontName = RubyMergeViewer . class . getName ( ) ; Font font = JFaceResources . getFont ( symbolicFontName ) ; if ( font != null ) fSourceViewer . getTextWidget ( ) . setFont ( font ) ; } public Control getControl ( ) { return fSourceViewer . getControl ( ) ; } public void setInput ( Object input ) { if ( input instanceof IStreamContentAccessor ) { Document document = new Document ( getString ( input ) ) ; RubyCompareUtilities . setupDocument ( document ) ; fSourceViewer . setDocument ( document ) ; } fInput = input ; } public Object getInput ( ) { return fInput ; } public ISelection getSelection ( ) { return null ; } public void setSelection ( ISelection s , boolean reveal ) { } public void refresh ( ) { } private static String getString ( Object input ) { if ( input instanceof IStreamContentAccessor ) { IStreamContentAccessor sca = ( IStreamContentAccessor ) input ; try { return RubyCompareUtilities . readString ( sca ) ; } catch ( CoreException ex ) { RubyPlugin . log ( ex ) ; } } return "" ; } } package org . rubypeople . rdt . internal . ui . compare ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . compare . contentmergeviewer . ITokenComparator ; import org . eclipse . compare . rangedifferencer . IRangeComparator ; import org . eclipse . core . runtime . Assert ; import org . rubypeople . rdt . core . ToolFactory ; import org . rubypeople . rdt . core . compiler . IScanner ; import org . rubypeople . rdt . core . compiler . InvalidInputException ; public class RubyTokenComparator implements ITokenComparator { private String fText ; private boolean fShouldEscape = true ; private List < Integer > fStarts ; private List < Integer > fLengths ; public RubyTokenComparator ( String text , boolean shouldEscape ) { Assert . isNotNull ( text ) ; fText = text ; fShouldEscape = shouldEscape ; int length = fText . length ( ) ; fStarts = new ArrayList < Integer > ( length + ) ; fLengths = new ArrayList < Integer > ( length + ) ; IScanner scanner = ToolFactory . createScanner ( true , true , false , false ) ; scanner . setSource ( fText . toCharArray ( ) ) ; try { int endPos = ; while ( scanner . getNextToken ( ) != IScanner . TokenNameEOF ) { int start = scanner . getCurrentTokenStartPosition ( ) ; int end = scanner . getCurrentTokenEndPosition ( ) + ; fStarts . add ( start ) ; fLengths . add ( end - start ) ; endPos = end ; if ( fStarts . size ( ) > ( length * ) ) break ; } if ( endPos < length ) { fStarts . add ( endPos ) ; fLengths . add ( length - endPos ) ; } } catch ( InvalidInputException ex ) { } } public int getRangeCount ( ) { return fStarts . size ( ) ; } public int getTokenStart ( int index ) { if ( index >= && index < getRangeCount ( ) ) return fStarts . get ( index ) ; if ( getRangeCount ( ) > ) return fStarts . get ( getRangeCount ( ) - ) + fLengths . get ( getRangeCount ( ) - ) ; return ; } public int getTokenLength ( int index ) { if ( index < getRangeCount ( ) ) return fStarts . get ( index ) ; return ; } public boolean rangesEqual ( int thisIndex , IRangeComparator other , int otherIndex ) { if ( other != null && getClass ( ) == other . getClass ( ) ) { RubyTokenComparator tc = ( RubyTokenComparator ) other ; int thisLen = getTokenLength ( thisIndex ) ; int otherLen = tc . getTokenLength ( otherIndex ) ; if ( thisLen == otherLen ) return fText . regionMatches ( false , getTokenStart ( thisIndex ) , tc . fText , tc . getTokenStart ( otherIndex ) , thisLen ) ; } return false ; } public boolean skipRangeComparison ( int length , int max , IRangeComparator other ) { if ( ! fShouldEscape ) return false ; if ( getRangeCount ( ) < || other . getRangeCount ( ) < ) return false ; if ( max < ) return false ; if ( length < ) return false ; if ( max > ) return true ; if ( length < max / ) return false ; return true ; } } package org . rubypeople . rdt . internal . ui . compare ; import org . eclipse . compare . ITypedElement ; import org . eclipse . compare . structuremergeviewer . DocumentRangeNode ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; class RubyNode extends DocumentRangeNode implements ITypedElement { public static final int SCRIPT = ; public static final int IMPORT_CONTAINER = ; public static final int IMPORT = ; public static final int MODULE = ; public static final int CLASS = ; public static final int FIELD = ; public static final int CONSTRUCTOR = ; public static final int METHOD = ; private int fInitializerCount = ; private boolean fIsEditable ; private RubyNode fParent ; public RubyNode ( RubyNode parent , int type , String name , int start , int length ) { super ( type , RubyCompareUtilities . buildID ( type , name ) , parent . getDocument ( ) , start , length ) ; fParent = parent ; if ( parent != null ) { parent . addChild ( this ) ; fIsEditable = parent . isEditable ( ) ; } } public RubyNode ( IDocument document , boolean editable ) { super ( SCRIPT , RubyCompareUtilities . buildID ( SCRIPT , "" ) , document , , document . getLength ( ) ) ; fIsEditable = editable ; } public String getInitializerCount ( ) { return Integer . toString ( fInitializerCount ++ ) ; } public String extractMethodName ( ) { String id = getId ( ) ; int pos = id . indexOf ( '' ) ; if ( pos > ) return id . substring ( , pos ) ; return id . substring ( ) ; } public String extractArgumentList ( ) { String id = getId ( ) ; int pos = id . indexOf ( '' ) ; if ( pos >= ) return id . substring ( pos + ) ; return id . substring ( ) ; } public String getName ( ) { switch ( getTypeCode ( ) ) { case IMPORT_CONTAINER : return CompareMessages . RubyNode_importDeclarations ; case SCRIPT : return CompareMessages . RubyNode_script ; } return getId ( ) . substring ( ) ; } public String getType ( ) { return "" ; } public boolean isEditable ( ) { return fIsEditable ; } public Image getImage ( ) { ImageDescriptor id = null ; switch ( getTypeCode ( ) ) { case SCRIPT : id = RubyCompareUtilities . getImageDescriptor ( IRubyElement . SCRIPT ) ; break ; case IMPORT : id = RubyCompareUtilities . getImageDescriptor ( IRubyElement . IMPORT_DECLARATION ) ; break ; case IMPORT_CONTAINER : id = RubyCompareUtilities . getImageDescriptor ( IRubyElement . IMPORT_CONTAINER ) ; break ; case CLASS : id = RubyCompareUtilities . getTypeImageDescriptor ( true ) ; break ; case MODULE : id = RubyCompareUtilities . getTypeImageDescriptor ( false ) ; break ; case CONSTRUCTOR : case METHOD : id = RubyCompareUtilities . getImageDescriptor ( IRubyElement . METHOD ) ; break ; case FIELD : id = RubyCompareUtilities . getImageDescriptor ( IRubyElement . FIELD ) ; break ; } return RubyPlugin . getImageDescriptorRegistry ( ) . get ( id ) ; } public void setContent ( byte [ ] content ) { super . setContent ( content ) ; nodeChanged ( this ) ; } public ITypedElement replace ( ITypedElement child , ITypedElement other ) { nodeChanged ( this ) ; return child ; } void nodeChanged ( RubyNode node ) { if ( fParent != null ) fParent . nodeChanged ( node ) ; } } package org . rubypeople . rdt . internal . ui . compare ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . IViewerCreator ; public class RubyTextViewerCreator implements IViewerCreator { public Viewer createViewer ( Composite parent , CompareConfiguration mp ) { return new RubyTextViewer ( parent ) ; } } package org . rubypeople . rdt . internal . ui . compare ; import java . util . ArrayList ; import java . util . Iterator ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . IResourceProvider ; import org . eclipse . compare . ITypedElement ; import org . eclipse . compare . contentmergeviewer . ITokenComparator ; import org . eclipse . compare . contentmergeviewer . TextMergeViewer ; import org . eclipse . compare . structuremergeviewer . ICompareInput ; import org . eclipse . compare . structuremergeviewer . IDiffContainer ; import org . eclipse . compare . structuremergeviewer . IDiffElement ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentPartitioner ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . TextViewer ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . texteditor . AbstractTextEditor ; import org . eclipse . ui . texteditor . ChainedPreferenceStore ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyColorConstants ; import org . rubypeople . rdt . internal . ui . text . PreferencesAdapter ; import org . rubypeople . rdt . ui . EclipsePreferencesAdapter ; import org . rubypeople . rdt . ui . text . RubySourceViewerConfiguration ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class RubyMergeViewer extends TextMergeViewer { private IPropertyChangeListener fPreferenceChangeListener ; private IPreferenceStore fPreferenceStore ; private boolean fUseSystemColors ; private RubySourceViewerConfiguration fSourceViewerConfiguration ; private ArrayList fSourceViewer ; public RubyMergeViewer ( Composite parent , int styles , CompareConfiguration mp ) { super ( parent , styles | SWT . LEFT_TO_RIGHT , mp ) ; getPreferenceStore ( ) ; fUseSystemColors = fPreferenceStore . getBoolean ( AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT ) ; if ( ! fUseSystemColors ) { RGB bg = createColor ( fPreferenceStore , AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND ) ; setBackgroundColor ( bg ) ; RGB fg = createColor ( fPreferenceStore , IRubyColorConstants . RUBY_DEFAULT ) ; setForegroundColor ( fg ) ; } } private IPreferenceStore getPreferenceStore ( ) { if ( fPreferenceStore == null ) setPreferenceStore ( createChainedPreferenceStore ( null ) ) ; return fPreferenceStore ; } protected void handleDispose ( DisposeEvent event ) { setPreferenceStore ( null ) ; fSourceViewer = null ; super . handleDispose ( event ) ; } public IRubyProject getRubyProject ( ICompareInput input ) { if ( input == null ) return null ; IResourceProvider rp = null ; ITypedElement te = input . getLeft ( ) ; if ( te instanceof IResourceProvider ) rp = ( IResourceProvider ) te ; if ( rp == null ) { te = input . getRight ( ) ; if ( te instanceof IResourceProvider ) rp = ( IResourceProvider ) te ; } if ( rp == null ) { te = input . getAncestor ( ) ; if ( te instanceof IResourceProvider ) rp = ( IResourceProvider ) te ; } if ( rp != null ) { IResource resource = rp . getResource ( ) ; if ( resource != null ) { IRubyElement element = RubyCore . create ( resource ) ; if ( element != null ) return element . getRubyProject ( ) ; } } return null ; } public void setInput ( Object input ) { if ( input instanceof ICompareInput ) { IRubyProject project = getRubyProject ( ( ICompareInput ) input ) ; if ( project != null ) { setPreferenceStore ( createChainedPreferenceStore ( project ) ) ; if ( fSourceViewer != null ) { Iterator iterator = fSourceViewer . iterator ( ) ; while ( iterator . hasNext ( ) ) { SourceViewer sourceViewer = ( SourceViewer ) iterator . next ( ) ; sourceViewer . unconfigure ( ) ; sourceViewer . configure ( getSourceViewerConfiguration ( ) ) ; } } } } super . setInput ( input ) ; } private ChainedPreferenceStore createChainedPreferenceStore ( IRubyProject project ) { ArrayList stores = new ArrayList ( ) ; if ( project != null ) stores . add ( new EclipsePreferencesAdapter ( new ProjectScope ( project . getProject ( ) ) , RubyCore . PLUGIN_ID ) ) ; stores . add ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; stores . add ( new PreferencesAdapter ( RubyCore . getPlugin ( ) . getPluginPreferences ( ) ) ) ; stores . add ( EditorsUI . getPreferenceStore ( ) ) ; return new ChainedPreferenceStore ( ( IPreferenceStore [ ] ) stores . toArray ( new IPreferenceStore [ stores . size ( ) ] ) ) ; } private void handlePropertyChange ( PropertyChangeEvent event ) { String key = event . getProperty ( ) ; if ( key . equals ( AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND ) ) { if ( ! fUseSystemColors ) { RGB bg = createColor ( fPreferenceStore , AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND ) ; setBackgroundColor ( bg ) ; } } else if ( key . equals ( AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT ) ) { fUseSystemColors = fPreferenceStore . getBoolean ( AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT ) ; if ( fUseSystemColors ) { setBackgroundColor ( null ) ; setForegroundColor ( null ) ; } else { RGB bg = createColor ( fPreferenceStore , AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND ) ; setBackgroundColor ( bg ) ; RGB fg = createColor ( fPreferenceStore , IRubyColorConstants . RUBY_DEFAULT ) ; setForegroundColor ( fg ) ; } } else if ( key . equals ( IRubyColorConstants . RUBY_DEFAULT ) ) { if ( ! fUseSystemColors ) { RGB fg = createColor ( fPreferenceStore , IRubyColorConstants . RUBY_DEFAULT ) ; setForegroundColor ( fg ) ; } } if ( fSourceViewerConfiguration != null && fSourceViewerConfiguration . affectsTextPresentation ( event ) ) { fSourceViewerConfiguration . handlePropertyChangeEvent ( event ) ; invalidateTextPresentation ( ) ; } } private static RGB createColor ( IPreferenceStore store , String key ) { if ( ! store . contains ( key ) ) return null ; if ( store . isDefault ( key ) ) return PreferenceConverter . getDefaultColor ( store , key ) ; return PreferenceConverter . getColor ( store , key ) ; } public String getTitle ( ) { return CompareMessages . RubyMergeViewer_title ; } protected ITokenComparator createTokenComparator ( String s ) { return new RubyTokenComparator ( s , true ) ; } protected IDocumentPartitioner getDocumentPartitioner ( ) { return RubyCompareUtilities . createRubyPartitioner ( ) ; } protected void configureTextViewer ( TextViewer textViewer ) { if ( textViewer instanceof SourceViewer ) { if ( fSourceViewer == null ) fSourceViewer = new ArrayList ( ) ; fSourceViewer . add ( textViewer ) ; RubyTextTools tools = RubyCompareUtilities . getRubyTextTools ( ) ; if ( tools != null ) ( ( SourceViewer ) textViewer ) . configure ( getSourceViewerConfiguration ( ) ) ; } } private RubySourceViewerConfiguration getSourceViewerConfiguration ( ) { if ( fSourceViewerConfiguration == null ) getPreferenceStore ( ) ; return fSourceViewerConfiguration ; } protected int findInsertionPosition ( char type , ICompareInput input ) { int pos = super . findInsertionPosition ( type , input ) ; if ( pos != ) return pos ; if ( input instanceof IDiffElement ) { RubyNode otherRubyElement = null ; ITypedElement otherElement = null ; switch ( type ) { case '' : otherElement = input . getRight ( ) ; break ; case '' : otherElement = input . getLeft ( ) ; break ; } if ( otherElement instanceof RubyNode ) otherRubyElement = ( RubyNode ) otherElement ; RubyNode javaContainer = null ; IDiffElement diffElement = ( IDiffElement ) input ; IDiffContainer container = diffElement . getParent ( ) ; if ( container instanceof ICompareInput ) { ICompareInput parent = ( ICompareInput ) container ; ITypedElement element = null ; switch ( type ) { case '' : element = parent . getLeft ( ) ; break ; case '' : element = parent . getRight ( ) ; break ; } if ( element instanceof RubyNode ) javaContainer = ( RubyNode ) element ; } if ( otherRubyElement != null && javaContainer != null ) { Object [ ] children ; Position p ; switch ( otherRubyElement . getTypeCode ( ) ) { case RubyNode . IMPORT_CONTAINER : children = javaContainer . getChildren ( ) ; if ( children . length > ) { RubyNode packageDecl = null ; for ( int i = ; i < children . length ; i ++ ) { RubyNode child = ( RubyNode ) children [ i ] ; switch ( child . getTypeCode ( ) ) { case RubyNode . CLASS : return child . getRange ( ) . getOffset ( ) ; } } if ( packageDecl != null ) { p = packageDecl . getRange ( ) ; return p . getOffset ( ) + p . getLength ( ) ; } } return javaContainer . getRange ( ) . getOffset ( ) ; case RubyNode . IMPORT : p = javaContainer . getRange ( ) ; return p . getOffset ( ) + p . getLength ( ) ; case RubyNode . CLASS : children = javaContainer . getChildren ( ) ; if ( children . length > ) { for ( int i = children . length - ; i >= ; i -- ) { RubyNode child = ( RubyNode ) children [ i ] ; switch ( child . getTypeCode ( ) ) { case RubyNode . CLASS : case RubyNode . IMPORT_CONTAINER : case RubyNode . FIELD : p = child . getRange ( ) ; return p . getOffset ( ) + p . getLength ( ) ; } } } return javaContainer . getAppendPosition ( ) . getOffset ( ) ; case RubyNode . METHOD : children = javaContainer . getChildren ( ) ; if ( children . length > ) { RubyNode child = ( RubyNode ) children [ children . length - ] ; p = child . getRange ( ) ; return findEndOfLine ( javaContainer , p . getOffset ( ) + p . getLength ( ) ) ; } return javaContainer . getAppendPosition ( ) . getOffset ( ) ; case RubyNode . FIELD : children = javaContainer . getChildren ( ) ; if ( children . length > ) { RubyNode method = null ; for ( int i = children . length - ; i >= ; i -- ) { RubyNode child = ( RubyNode ) children [ i ] ; switch ( child . getTypeCode ( ) ) { case RubyNode . METHOD : method = child ; break ; case RubyNode . FIELD : p = child . getRange ( ) ; return p . getOffset ( ) + p . getLength ( ) ; } } if ( method != null ) return method . getRange ( ) . getOffset ( ) ; } return javaContainer . getAppendPosition ( ) . getOffset ( ) ; } } if ( javaContainer != null ) { Position p = javaContainer . getRange ( ) ; return p . getOffset ( ) + p . getLength ( ) ; } } return ; } private int findEndOfLine ( RubyNode container , int pos ) { int line ; IDocument doc = container . getDocument ( ) ; try { line = doc . getLineOfOffset ( pos ) ; pos = doc . getLineOffset ( line + ) ; } catch ( BadLocationException ex ) { } Position containerRange = container . getRange ( ) ; int start = containerRange . getOffset ( ) ; int end = containerRange . getOffset ( ) + containerRange . getLength ( ) ; if ( pos < start ) return start ; if ( pos >= end ) return end - ; return pos ; } private void setPreferenceStore ( IPreferenceStore ps ) { if ( fPreferenceChangeListener != null ) { if ( fPreferenceStore != null ) fPreferenceStore . removePropertyChangeListener ( fPreferenceChangeListener ) ; fPreferenceChangeListener = null ; } fPreferenceStore = ps ; if ( fPreferenceStore != null ) { RubyTextTools tools = RubyCompareUtilities . getRubyTextTools ( ) ; fSourceViewerConfiguration = new RubySourceViewerConfiguration ( tools . getColorManager ( ) , fPreferenceStore , null , null ) ; fPreferenceChangeListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { handlePropertyChange ( event ) ; } } ; fPreferenceStore . addPropertyChangeListener ( fPreferenceChangeListener ) ; } } } package org . rubypeople . rdt . internal . ui . compare ; import java . util . Map ; import java . util . ResourceBundle ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . CompareViewerPane ; import org . eclipse . compare . IResourceProvider ; import org . eclipse . compare . ITypedElement ; import org . eclipse . compare . structuremergeviewer . DiffNode ; import org . eclipse . compare . structuremergeviewer . Differencer ; import org . eclipse . compare . structuremergeviewer . ICompareInput ; import org . eclipse . compare . structuremergeviewer . IDiffContainer ; import org . eclipse . compare . structuremergeviewer . StructureDiffViewer ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . ToolBarManager ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . ToolBar ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; class RubyStructureDiffViewer extends StructureDiffViewer { static class ChangePropertyAction extends Action { private CompareConfiguration fCompareConfiguration ; private String fPropertyKey ; private ResourceBundle fBundle ; private String fPrefix ; public ChangePropertyAction ( ResourceBundle bundle , CompareConfiguration cc , String rkey , String pkey ) { fPropertyKey = pkey ; fBundle = bundle ; fPrefix = rkey ; RubyCompareUtilities . initAction ( this , fBundle , fPrefix ) ; setCompareConfiguration ( cc ) ; } public void run ( ) { boolean b = ! RubyCompareUtilities . getBoolean ( fCompareConfiguration , fPropertyKey , false ) ; setChecked ( b ) ; if ( fCompareConfiguration != null ) fCompareConfiguration . setProperty ( fPropertyKey , new Boolean ( b ) ) ; } public void setChecked ( boolean state ) { super . setChecked ( state ) ; RubyCompareUtilities . initToggleAction ( this , fBundle , fPrefix , state ) ; } public void setCompareConfiguration ( CompareConfiguration cc ) { fCompareConfiguration = cc ; setChecked ( RubyCompareUtilities . getBoolean ( fCompareConfiguration , fPropertyKey , false ) ) ; } } private static final String SMART = "" ; private ActionContributionItem fSmartActionItem ; private RubyStructureCreator fStructureCreator ; private boolean fThreeWay ; public RubyStructureDiffViewer ( Composite parent , CompareConfiguration configuration ) { super ( parent , configuration ) ; fStructureCreator = new RubyStructureCreator ( ) ; setStructureCreator ( fStructureCreator ) ; } protected void initialSelection ( ) { Object firstClass = null ; Object o = getRoot ( ) ; if ( o != null ) { Object [ ] children = getSortedChildren ( o ) ; if ( children != null && children . length > ) { for ( int i = ; i < children . length ; i ++ ) { o = children [ i ] ; Object [ ] sortedChildren = getSortedChildren ( o ) ; if ( sortedChildren != null && sortedChildren . length > ) { for ( int j = ; j < sortedChildren . length ; j ++ ) { o = sortedChildren [ j ] ; if ( o instanceof DiffNode ) { DiffNode dn = ( DiffNode ) o ; ITypedElement e = dn . getId ( ) ; if ( e instanceof RubyNode ) { RubyNode jn = ( RubyNode ) e ; int tc = jn . getTypeCode ( ) ; if ( tc == RubyNode . CLASS || tc == RubyNode . MODULE ) { firstClass = dn ; } } } } } } } } if ( firstClass != null ) expandToLevel ( firstClass , ) ; else expandToLevel ( ) ; } protected void compareInputChanged ( ICompareInput input ) { fThreeWay = input != null ? input . getAncestor ( ) != null : false ; setSmartButtonVisible ( fThreeWay ) ; if ( input != null ) { Map compilerOptions = getCompilerOptions ( input . getAncestor ( ) ) ; if ( compilerOptions == null ) compilerOptions = getCompilerOptions ( input . getLeft ( ) ) ; if ( compilerOptions == null ) compilerOptions = getCompilerOptions ( input . getRight ( ) ) ; if ( compilerOptions != null ) fStructureCreator . setDefaultCompilerOptions ( compilerOptions ) ; } super . compareInputChanged ( input ) ; } private Map getCompilerOptions ( ITypedElement input ) { if ( input instanceof IResourceProvider ) { IResource resource = ( ( IResourceProvider ) input ) . getResource ( ) ; if ( resource != null ) { IRubyElement element = RubyCore . create ( resource ) ; if ( element != null ) { IRubyProject javaProject = element . getRubyProject ( ) ; if ( javaProject != null ) return javaProject . getOptions ( true ) ; } } } return null ; } protected void createToolItems ( ToolBarManager toolBarManager ) { super . createToolItems ( toolBarManager ) ; IAction a = new ChangePropertyAction ( getBundle ( ) , getCompareConfiguration ( ) , "" , SMART ) ; fSmartActionItem = new ActionContributionItem ( a ) ; fSmartActionItem . setVisible ( fThreeWay ) ; toolBarManager . appendToGroup ( "" , fSmartActionItem ) ; } protected void postDiffHook ( Differencer differencer , IDiffContainer root ) { if ( fStructureCreator . canRewriteTree ( ) ) { boolean smart = RubyCompareUtilities . getBoolean ( getCompareConfiguration ( ) , SMART , false ) ; if ( smart && root != null ) fStructureCreator . rewriteTree ( differencer , root ) ; } } protected void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( SMART ) ) diff ( ) ; else super . propertyChange ( event ) ; } private void setSmartButtonVisible ( boolean visible ) { if ( fSmartActionItem == null ) return ; Control c = getControl ( ) ; if ( c == null || c . isDisposed ( ) ) return ; fSmartActionItem . setVisible ( visible ) ; ToolBarManager tbm = CompareViewerPane . getToolBarManager ( c . getParent ( ) ) ; if ( tbm != null ) { tbm . update ( true ) ; ToolBar tb = tbm . getControl ( ) ; if ( ! tb . isDisposed ( ) ) tb . getParent ( ) . layout ( true ) ; } } } package org . rubypeople . rdt . internal . ui . compare ; import java . util . List ; import java . util . Stack ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . DStrNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . jruby . ast . StrNode ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; class RubyParseTreeBuilder extends InOrderVisitor { private char [ ] fBuffer ; private Stack < RubyNode > fStack = new Stack < RubyNode > ( ) ; private boolean fShowCU ; private RubyNode fImportContainer ; public RubyParseTreeBuilder ( RubyNode root , char [ ] buffer , boolean showCU ) { fBuffer = buffer ; fShowCU = showCU ; fStack . clear ( ) ; fStack . push ( root ) ; } private void pop ( ) { fStack . pop ( ) ; } private RubyNode getCurrentContainer ( ) { return fStack . peek ( ) ; } private void push ( int type , String name , int declarationStart , int length ) { while ( declarationStart > ) { char c = fBuffer [ declarationStart - ] ; if ( c != '' && c != '' ) break ; declarationStart -- ; length ++ ; } RubyNode node = new RubyNode ( getCurrentContainer ( ) , type , name , declarationStart , length ) ; if ( type == RubyNode . SCRIPT ) node . setAppendPosition ( declarationStart + length + ) ; else node . setAppendPosition ( declarationStart + length ) ; fStack . push ( node ) ; } @ Override public Object visitClassNode ( ClassNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . CLASS , ASTUtil . getFullyQualifiedName ( iVisited . getCPath ( ) ) , start , end - start ) ; Object ins = super . visitClassNode ( iVisited ) ; pop ( ) ; return ins ; } @ Override public Object visitSClassNode ( SClassNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . CLASS , ASTUtil . getNameReflectively ( iVisited . getReceiverNode ( ) ) , start , end - start ) ; Object ins = super . visitSClassNode ( iVisited ) ; pop ( ) ; return ins ; } @ Override public Object visitModuleNode ( ModuleNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . MODULE , ASTUtil . getFullyQualifiedName ( iVisited . getCPath ( ) ) , start , end - start ) ; Object ins = super . visitModuleNode ( iVisited ) ; pop ( ) ; return ins ; } @ Override public Object visitRootNode ( RootNode iVisited ) { if ( fShowCU ) push ( RubyNode . SCRIPT , null , iVisited . getPosition ( ) . getStartOffset ( ) , iVisited . getPosition ( ) . getEndOffset ( ) ) ; Object ins = super . visitRootNode ( iVisited ) ; if ( fShowCU ) pop ( ) ; return ins ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . METHOD , iVisited . getName ( ) , start , end - start ) ; Object ins = super . visitDefnNode ( iVisited ) ; pop ( ) ; return ins ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . METHOD , iVisited . getName ( ) , start , end - start ) ; Object ins = super . visitDefsNode ( iVisited ) ; pop ( ) ; return ins ; } public Object visitFCallNode ( FCallNode iVisited ) { String name = iVisited . getName ( ) ; List < String > arguments = getArgumentsFromFunctionCall ( iVisited ) ; if ( name . equals ( "" ) || name . equals ( "" ) ) { addImport ( iVisited ) ; } return super . visitFCallNode ( iVisited ) ; } private void addImport ( FCallNode iVisited ) { ArrayNode node = ( ArrayNode ) iVisited . getArgsNode ( ) ; String arg = getString ( node ) ; if ( arg != null ) { int s = node . getPosition ( ) . getStartOffset ( ) ; int declarationEnd = node . getPosition ( ) . getEndOffset ( ) ; int l = declarationEnd - s ; if ( fImportContainer == null ) fImportContainer = new RubyNode ( getCurrentContainer ( ) , RubyNode . IMPORT_CONTAINER , null , s , l ) ; new RubyNode ( fImportContainer , RubyNode . IMPORT , arg , s , l ) ; fImportContainer . setLength ( declarationEnd - fImportContainer . getRange ( ) . getOffset ( ) + ) ; fImportContainer . setAppendPosition ( declarationEnd + ) ; } } private String getString ( ArrayNode node ) { Object tmp = node . childNodes ( ) . iterator ( ) . next ( ) ; if ( tmp instanceof DStrNode ) { DStrNode dstrNode = ( DStrNode ) tmp ; tmp = dstrNode . childNodes ( ) . iterator ( ) . next ( ) ; } if ( tmp instanceof StrNode ) { StrNode strNode = ( StrNode ) tmp ; return strNode . getValue ( ) . toString ( ) ; } return null ; } @ Override public Object visitInstAsgnNode ( InstAsgnNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . FIELD , iVisited . getName ( ) , start , end - start ) ; Object ins = super . visitInstAsgnNode ( iVisited ) ; pop ( ) ; return ins ; } @ Override public Object visitClassVarDeclNode ( ClassVarDeclNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . FIELD , iVisited . getName ( ) , start , end - start ) ; Object ins = super . visitClassVarDeclNode ( iVisited ) ; pop ( ) ; return ins ; } @ Override public Object visitClassVarAsgnNode ( ClassVarAsgnNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . FIELD , iVisited . getName ( ) , start , end - start ) ; Object ins = super . visitClassVarAsgnNode ( iVisited ) ; pop ( ) ; return ins ; } @ Override public Object visitConstDeclNode ( ConstDeclNode iVisited ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) ; push ( RubyNode . FIELD , iVisited . getName ( ) , start , end - start ) ; Object ins = super . visitConstDeclNode ( iVisited ) ; pop ( ) ; return ins ; } } package org . rubypeople . rdt . internal . ui . compare ; import java . io . UnsupportedEncodingException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . compare . CompareUI ; import org . eclipse . compare . IEditableContent ; import org . eclipse . compare . IEncodedStreamContentAccessor ; import org . eclipse . compare . IResourceProvider ; import org . eclipse . compare . IStreamContentAccessor ; import org . eclipse . compare . ITypedElement ; import org . eclipse . compare . structuremergeviewer . DiffNode ; import org . eclipse . compare . structuremergeviewer . Differencer ; import org . eclipse . compare . structuremergeviewer . DocumentRangeNode ; import org . eclipse . compare . structuremergeviewer . ICompareInput ; import org . eclipse . compare . structuremergeviewer . IDiffContainer ; import org . eclipse . compare . structuremergeviewer . IDiffElement ; import org . eclipse . compare . structuremergeviewer . IStructureComparator ; import org . eclipse . compare . structuremergeviewer . IStructureCreator ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyStructureCreator implements IStructureCreator { private Map fDefaultCompilerOptions ; static class RewriteInfo { boolean fIsOut = false ; RubyNode fAncestor = null ; RubyNode fLeft = null ; RubyNode fRight = null ; ArrayList fChildren = new ArrayList ( ) ; void add ( IDiffElement diff ) { fChildren . add ( diff ) ; } void setDiff ( ICompareInput diff ) { if ( fIsOut ) return ; fIsOut = true ; RubyNode a = ( RubyNode ) diff . getAncestor ( ) ; RubyNode y = ( RubyNode ) diff . getLeft ( ) ; RubyNode m = ( RubyNode ) diff . getRight ( ) ; if ( a != null ) { if ( fAncestor != null ) return ; fAncestor = a ; } if ( y != null ) { if ( fLeft != null ) return ; fLeft = y ; } if ( m != null ) { if ( fRight != null ) return ; fRight = m ; } fIsOut = false ; } boolean matches ( ) { return ! fIsOut && fAncestor != null && fLeft != null && fRight != null ; } } public RubyStructureCreator ( ) { } void setDefaultCompilerOptions ( Map compilerSettings ) { fDefaultCompilerOptions = compilerSettings ; } public String getName ( ) { return CompareMessages . RubyStructureViewer_title ; } public IStructureComparator getStructure ( final Object input ) { String contents = null ; char [ ] buffer = null ; IDocument doc = CompareUI . getDocument ( input ) ; if ( doc == null ) { if ( input instanceof IStreamContentAccessor ) { IStreamContentAccessor sca = ( IStreamContentAccessor ) input ; try { contents = RubyCompareUtilities . readString ( sca ) ; } catch ( CoreException ex ) { return null ; } } if ( contents != null ) { int n = contents . length ( ) ; buffer = new char [ n ] ; contents . getChars ( , n , buffer , ) ; doc = new Document ( contents ) ; RubyCompareUtilities . setupDocument ( doc ) ; } } Map compilerOptions = null ; if ( input instanceof IResourceProvider ) { IResource resource = ( ( IResourceProvider ) input ) . getResource ( ) ; if ( resource != null ) { IRubyElement element = RubyCore . create ( resource ) ; if ( element != null ) { IRubyProject javaProject = element . getRubyProject ( ) ; if ( javaProject != null ) compilerOptions = javaProject . getOptions ( true ) ; } } } if ( compilerOptions == null ) compilerOptions = fDefaultCompilerOptions ; if ( doc != null ) { boolean isEditable = false ; if ( input instanceof IEditableContent ) isEditable = ( ( IEditableContent ) input ) . isEditable ( ) ; RubyNode root = new RubyNode ( doc , isEditable ) { void nodeChanged ( RubyNode node ) { save ( this , input ) ; } } ; if ( buffer == null ) { contents = doc . get ( ) ; int n = contents . length ( ) ; buffer = new char [ n ] ; contents . getChars ( , n , buffer , ) ; } try { RubyParser parser = new RubyParser ( ) ; Node astRoot = parser . parse ( new String ( buffer ) ) . getAST ( ) ; astRoot . accept ( new RubyParseTreeBuilder ( root , buffer , true ) ) ; } catch ( Exception e ) { RubyPlugin . log ( e ) ; } return root ; } return null ; } public boolean canSave ( ) { return true ; } public void save ( IStructureComparator node , Object input ) { if ( node instanceof RubyNode && input instanceof IEditableContent ) { IDocument document = ( ( RubyNode ) node ) . getDocument ( ) ; IEditableContent bca = ( IEditableContent ) input ; String contents = document . get ( ) ; String encoding = null ; if ( input instanceof IEncodedStreamContentAccessor ) { try { encoding = ( ( IEncodedStreamContentAccessor ) input ) . getCharset ( ) ; } catch ( CoreException e1 ) { } } if ( encoding == null ) encoding = ResourcesPlugin . getEncoding ( ) ; byte [ ] bytes ; try { bytes = contents . getBytes ( encoding ) ; } catch ( UnsupportedEncodingException e ) { bytes = contents . getBytes ( ) ; } bca . setContent ( bytes ) ; } } public String getContents ( Object node , boolean ignoreWhiteSpace ) { if ( ! ( node instanceof IStreamContentAccessor ) ) return null ; IStreamContentAccessor sca = ( IStreamContentAccessor ) node ; String content = null ; try { content = RubyCompareUtilities . readString ( sca ) ; } catch ( CoreException ex ) { RubyPlugin . log ( ex ) ; return null ; } return content ; } public boolean canRewriteTree ( ) { return true ; } public void rewriteTree ( Differencer differencer , IDiffContainer root ) { HashMap map = new HashMap ( ) ; Object [ ] children = root . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { DiffNode diff = ( DiffNode ) children [ i ] ; RubyNode jn = ( RubyNode ) diff . getId ( ) ; if ( jn == null ) continue ; int type = jn . getTypeCode ( ) ; if ( type == RubyNode . METHOD || type == RubyNode . CONSTRUCTOR ) { String name = jn . extractMethodName ( ) ; RewriteInfo nameInfo = ( RewriteInfo ) map . get ( name ) ; if ( nameInfo == null ) { nameInfo = new RewriteInfo ( ) ; map . put ( name , nameInfo ) ; } nameInfo . add ( diff ) ; String argList = jn . extractArgumentList ( ) ; RewriteInfo argInfo = null ; if ( argList != null && ! argList . equals ( "" ) ) { argInfo = ( RewriteInfo ) map . get ( argList ) ; if ( argInfo == null ) { argInfo = new RewriteInfo ( ) ; map . put ( argList , argInfo ) ; } argInfo . add ( diff ) ; } switch ( diff . getKind ( ) & Differencer . CHANGE_TYPE_MASK ) { case Differencer . ADDITION : case Differencer . DELETION : if ( type != RubyNode . CONSTRUCTOR ) nameInfo . setDiff ( diff ) ; if ( argInfo != null ) argInfo . setDiff ( diff ) ; break ; default : break ; } } rewriteTree ( differencer , diff ) ; } Iterator it = map . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { String name = ( String ) it . next ( ) ; RewriteInfo i = ( RewriteInfo ) map . get ( name ) ; if ( i . matches ( ) ) { DiffNode d = ( DiffNode ) differencer . findDifferences ( true , null , root , i . fAncestor , i . fLeft , i . fRight ) ; if ( d != null ) { d . setDontExpand ( true ) ; Iterator it2 = i . fChildren . iterator ( ) ; while ( it2 . hasNext ( ) ) { IDiffElement rd = ( IDiffElement ) it2 . next ( ) ; root . removeToRoot ( rd ) ; d . add ( rd ) ; } } } } } public IStructureComparator locate ( Object selector , Object input ) { if ( ! ( selector instanceof IRubyElement ) ) return null ; IStructureComparator structure = getStructure ( input ) ; if ( structure == null ) return null ; String [ ] path = createPath ( ( IRubyElement ) selector ) ; return find ( structure , path , ) ; } private static String [ ] createPath ( IRubyElement je ) { List args = new ArrayList ( ) ; while ( je != null ) { String name = RubyCompareUtilities . getRubyElementID ( je ) ; if ( name == null ) return null ; args . add ( name ) ; if ( je instanceof IRubyScript ) break ; je = je . getParent ( ) ; } int n = args . size ( ) ; String [ ] path = new String [ n ] ; for ( int i = ; i < n ; i ++ ) path [ i ] = ( String ) args . get ( n - - i ) ; return path ; } private static IStructureComparator find ( IStructureComparator tree , String [ ] path , int index ) { if ( tree != null ) { Object [ ] children = tree . getChildren ( ) ; if ( children != null ) { for ( int i = ; i < children . length ; i ++ ) { IStructureComparator child = ( IStructureComparator ) children [ i ] ; if ( child instanceof ITypedElement && child instanceof DocumentRangeNode ) { String n1 = null ; if ( child instanceof DocumentRangeNode ) n1 = ( ( DocumentRangeNode ) child ) . getId ( ) ; if ( n1 == null ) n1 = ( ( ITypedElement ) child ) . getName ( ) ; String n2 = path [ index ] ; if ( n1 . equals ( n2 ) ) { if ( index == path . length - ) return child ; IStructureComparator result = find ( child , path , index + ) ; if ( result != null ) return result ; } } } } } return null ; } static boolean hasEdition ( IRubyElement je ) { switch ( je . getElementType ( ) ) { case IRubyElement . SCRIPT : case IRubyElement . TYPE : case IRubyElement . FIELD : case IRubyElement . METHOD : case IRubyElement . IMPORT_CONTAINER : case IRubyElement . IMPORT_DECLARATION : return true ; } return false ; } } package org . rubypeople . rdt . internal . ui . compare ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . IViewerCreator ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . widgets . Composite ; public class RubyStructureDiffViewerCreator implements IViewerCreator { public Viewer createViewer ( Composite parent , CompareConfiguration cc ) { return new RubyStructureDiffViewer ( parent , cc ) ; } } package org . rubypeople . rdt . internal . ui . compare ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . IViewerCreator ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; public class RubyMergeViewCreator implements IViewerCreator { public Viewer createViewer ( Composite parent , CompareConfiguration config ) { return new RubyMergeViewer ( parent , SWT . NULL , config ) ; } } package org . rubypeople . rdt . internal . ui . rdocexport ; public interface RdocListener { void rdocChanged ( ) ; } package org . rubypeople . rdt . internal . ui . rdocexport ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IWorkbenchPart ; public class CreateRdocActionDelegate implements IObjectActionDelegate { private ISelection fCurrentSelection ; public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { } public void run ( IAction action ) { if ( fCurrentSelection instanceof IStructuredSelection ) { IStructuredSelection structuredSelection = ( IStructuredSelection ) fCurrentSelection ; Object first = structuredSelection . getFirstElement ( ) ; if ( first instanceof IResource ) { RDocUtility . generateDocumentation ( ( IResource ) first ) ; } } } public void selectionChanged ( IAction action , ISelection selection ) { fCurrentSelection = selection ; } } package org . rubypeople . rdt . internal . ui . rdocexport ; import java . io . BufferedReader ; import java . io . File ; import java . io . IOException ; import java . io . InputStreamReader ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RDocUtility { static { String generateRdocOption = Platform . getDebugOption ( RubyPlugin . PLUGIN_ID + "" ) ; RDocUtility . setDebugging ( generateRdocOption == null ? false : generateRdocOption . equalsIgnoreCase ( "" ) ) ; } private static Set < RdocListener > listeners = new HashSet < RdocListener > ( ) ; private static boolean isDebug = false ; public static void addRdocListener ( RdocListener listener ) { listeners . add ( listener ) ; } public static void removeRdocListener ( RdocListener listener ) { listeners . remove ( listener ) ; } public static void setDebugging ( boolean isDebug ) { RDocUtility . isDebug = isDebug ; } public static void generateDocumentation ( IResource resource ) { RubyInvoker invoker = new RubyInvoker ( resource ) ; invoker . invoke ( ) ; notifyListeners ( ) ; } private static class RubyInvoker { private IResource resource ; private RubyInvoker ( IResource resource ) { this . resource = resource ; findParentProject ( resource ) ; } private void findParentProject ( IResource resource ) { IResource project = resource ; while ( ! isProject ( project ) ) { project = project . getParent ( ) ; if ( project == null ) break ; } if ( project != null && isProject ( project ) ) this . resource = project ; } private boolean isProject ( IResource resource ) { return ( resource instanceof IProject ) ; } private void log ( String message ) { if ( RDocUtility . isDebug ) { System . out . println ( message ) ; } } public final void invoke ( ) { log ( "" + resource . getName ( ) ) ; File file = RubyRuntime . getRDoc ( ) ; if ( file == null || ! file . exists ( ) || ! file . isFile ( ) ) { MessageDialog . openError ( RubyPlugin . getActiveWorkbenchShell ( ) , RubyUIMessages . RDocPathErrorTitle , RubyUIMessages . RDocPathError ) ; return ; } List < String > args = new ArrayList < String > ( ) ; args . add ( file . getAbsolutePath ( ) ) ; args . add ( "" ) ; args . add ( resource . getLocation ( ) . toOSString ( ) ) ; String [ ] argArray = ( String [ ] ) args . toArray ( new String [ args . size ( ) ] ) ; try { Process process = Runtime . getRuntime ( ) . exec ( argArray ) ; if ( process != null ) { handleOutput ( process , args ) ; } } catch ( IOException e ) { RubyPlugin . log ( e ) ; log ( e . getMessage ( ) ) ; ErrorDialog . openError ( RubyPlugin . getActiveWorkbenchShell ( ) , RubyUIMessages . ErrorRunningRdocTitle , e . getMessage ( ) , new StatusInfo ( StatusInfo . ERROR , e . getMessage ( ) ) ) ; } } private void handleOutput ( Process p , List < String > cmdLine ) { BufferedReader reader = null ; String lastLine = null ; try { reader = new BufferedReader ( new InputStreamReader ( p . getErrorStream ( ) ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { log ( line ) ; lastLine = line ; } } catch ( Exception e ) { log ( e . getMessage ( ) ) ; } try { p . waitFor ( ) ; if ( p . exitValue ( ) != ) { String message = RubyUIMessages . getFormattedString ( RubyUIMessages . RDocExecutionError , Integer . toString ( p . exitValue ( ) ) ) ; String additionalMessage = null ; if ( lastLine != null ) { additionalMessage = RubyUIMessages . getFormattedString ( RubyUIMessages . RDocExecutionErrorAdditionalMessageWithStderr , new String [ ] { cmdLine . toString ( ) , lastLine } ) ; } else { additionalMessage = RubyUIMessages . getFormattedString ( RubyUIMessages . RDocExecutionErrorAdditionalMessage , cmdLine . toString ( ) ) ; } String title = RubyUIMessages . getFormattedString ( RubyUIMessages . ErrorRunningRdocTitle , Integer . toString ( p . exitValue ( ) ) ) ; ErrorDialog . openError ( RubyPlugin . getActiveWorkbenchShell ( ) , title , message , new StatusInfo ( StatusInfo . ERROR , additionalMessage ) ) ; } } catch ( InterruptedException e ) { log ( "" + e . getMessage ( ) ) ; } log ( "" ) ; } } public static void notifyListeners ( ) { for ( Iterator < RdocListener > iter = listeners . iterator ( ) ; iter . hasNext ( ) ; ) { RdocListener listener = ( RdocListener ) iter . next ( ) ; listener . rdocChanged ( ) ; } } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . util . StringMatcher ; public class NamePatternFilter extends ViewerFilter { private String [ ] fPatterns ; private StringMatcher [ ] fMatchers ; private StringMatcher [ ] getMatchers ( ) { return fMatchers ; } public String [ ] getPatterns ( ) { return fPatterns ; } public boolean select ( Viewer viewer , Object parentElement , Object element ) { String matchName = null ; if ( element instanceof IRubyElement ) { matchName = ( ( IRubyElement ) element ) . getElementName ( ) ; } else if ( element instanceof IAdaptable ) { IAdaptable adaptable = ( IAdaptable ) element ; IRubyElement javaElement = ( IRubyElement ) adaptable . getAdapter ( IRubyElement . class ) ; if ( javaElement != null ) matchName = javaElement . getElementName ( ) ; else { IResource resource = ( IResource ) adaptable . getAdapter ( IResource . class ) ; if ( resource != null ) matchName = resource . getName ( ) ; } } if ( matchName != null ) { StringMatcher [ ] testMatchers = getMatchers ( ) ; for ( int i = ; i < testMatchers . length ; i ++ ) { if ( testMatchers [ i ] . match ( matchName ) ) return false ; } return true ; } return true ; } public void setPatterns ( String [ ] newPatterns ) { fPatterns = newPatterns ; fMatchers = new StringMatcher [ newPatterns . length ] ; for ( int i = ; i < newPatterns . length ; i ++ ) { fMatchers [ i ] = new StringMatcher ( newPatterns [ i ] , true , false ) ; } } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . IRubyProject ; public class NonRubyProjectsFilter extends ViewerFilter { public boolean select ( Viewer viewer , Object parent , Object element ) { if ( element instanceof IRubyProject ) return true ; else if ( element instanceof IProject ) return ! ( ( IProject ) element ) . isOpen ( ) ; return true ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . rubypeople . rdt . internal . ui . viewsupport . MemberFilter ; public class NonPublicFilter extends MemberFilter { public NonPublicFilter ( ) { addFilter ( MemberFilter . FILTER_NONPUBLIC ) ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . IMember ; public class AllMembersFilter extends ViewerFilter { public boolean select ( Viewer viewer , Object parentElement , Object element ) { return ( ! ( element instanceof IMember ) ) ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; public class LibraryFilter extends ViewerFilter { public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( element instanceof LoadPathContainer ) return false ; if ( element instanceof ISourceFolderRoot ) { ISourceFolderRoot root = ( ISourceFolderRoot ) element ; if ( root . isExternal ( ) ) { return false ; } } return true ; } } package org . rubypeople . rdt . internal . ui . filters ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import java . util . Stack ; import java . util . StringTokenizer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ArrayContentProvider ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . SelectionDialog ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; public class CustomFiltersDialog extends SelectionDialog { private static final String SEPARATOR = "" ; private String fViewId ; private boolean fEnablePatterns ; private String [ ] fPatterns ; private String [ ] fEnabledFilterIds ; private FilterDescriptor [ ] fBuiltInFilters ; private CheckboxTableViewer fCheckBoxList ; private Button fEnableUserDefinedPatterns ; private Text fUserDefinedPatterns ; private Stack fFilterDescriptorChangeHistory ; public CustomFiltersDialog ( Shell shell , String viewId , boolean enablePatterns , String [ ] patterns , String [ ] enabledFilterIds ) { super ( shell ) ; Assert . isNotNull ( viewId ) ; Assert . isNotNull ( patterns ) ; Assert . isNotNull ( enabledFilterIds ) ; fViewId = viewId ; fPatterns = patterns ; fEnablePatterns = enablePatterns ; fEnabledFilterIds = enabledFilterIds ; fBuiltInFilters = FilterDescriptor . getFilterDescriptors ( fViewId ) ; fFilterDescriptorChangeHistory = new Stack ( ) ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; } protected void configureShell ( Shell shell ) { setTitle ( FilterMessages . CustomFiltersDialog_title ) ; setMessage ( FilterMessages . CustomFiltersDialog_filterList_label ) ; super . configureShell ( shell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( shell , IRubyHelpContextIds . CUSTOM_FILTERS_DIALOG ) ; } protected Control createDialogArea ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . verticalSpacing = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; composite . setLayout ( layout ) ; composite . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; composite . setFont ( parent . getFont ( ) ) ; Composite group = composite ; fEnableUserDefinedPatterns = new Button ( group , SWT . CHECK ) ; fEnableUserDefinedPatterns . setFocus ( ) ; fEnableUserDefinedPatterns . setText ( FilterMessages . CustomFiltersDialog_enableUserDefinedPattern ) ; fUserDefinedPatterns = new Text ( group , SWT . SINGLE | SWT . BORDER ) ; GridData data = new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . GRAB_HORIZONTAL ) ; data . widthHint = convertWidthInCharsToPixels ( ) ; fUserDefinedPatterns . setLayoutData ( data ) ; String patterns = convertToString ( fPatterns , SEPARATOR ) ; fUserDefinedPatterns . setText ( patterns ) ; final Label info = new Label ( group , SWT . LEFT ) ; info . setText ( FilterMessages . CustomFiltersDialog_patternInfo ) ; fEnableUserDefinedPatterns . setSelection ( fEnablePatterns ) ; fUserDefinedPatterns . setEnabled ( fEnablePatterns ) ; info . setEnabled ( fEnablePatterns ) ; fEnableUserDefinedPatterns . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { boolean state = fEnableUserDefinedPatterns . getSelection ( ) ; fUserDefinedPatterns . setEnabled ( state ) ; info . setEnabled ( fEnableUserDefinedPatterns . getSelection ( ) ) ; if ( state ) fUserDefinedPatterns . setFocus ( ) ; } } ) ; if ( fBuiltInFilters . length > ) createCheckBoxList ( group ) ; applyDialogFont ( parent ) ; return parent ; } private void createCheckBoxList ( Composite parent ) { new Label ( parent , SWT . NONE ) ; Label info = new Label ( parent , SWT . LEFT ) ; info . setText ( FilterMessages . CustomFiltersDialog_filterList_label ) ; fCheckBoxList = CheckboxTableViewer . newCheckList ( parent , SWT . BORDER ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . heightHint = fCheckBoxList . getTable ( ) . getItemHeight ( ) * ; fCheckBoxList . getTable ( ) . setLayoutData ( data ) ; fCheckBoxList . setLabelProvider ( createLabelPrivder ( ) ) ; fCheckBoxList . setContentProvider ( new ArrayContentProvider ( ) ) ; Arrays . sort ( fBuiltInFilters ) ; fCheckBoxList . setInput ( fBuiltInFilters ) ; setInitialSelections ( getEnabledFilterDescriptors ( ) ) ; List initialSelection = getInitialElementSelections ( ) ; if ( initialSelection != null && ! initialSelection . isEmpty ( ) ) checkInitialSelections ( ) ; info = new Label ( parent , SWT . LEFT ) ; info . setText ( FilterMessages . CustomFiltersDialog_description_label ) ; final Text description = new Text ( parent , SWT . LEFT | SWT . WRAP | SWT . MULTI | SWT . READ_ONLY | SWT . BORDER | SWT . V_SCROLL ) ; data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . heightHint = convertHeightInCharsToPixels ( ) ; description . setLayoutData ( data ) ; fCheckBoxList . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { Object selectedElement = ( ( IStructuredSelection ) selection ) . getFirstElement ( ) ; if ( selectedElement instanceof FilterDescriptor ) description . setText ( ( ( FilterDescriptor ) selectedElement ) . getDescription ( ) ) ; } } } ) ; fCheckBoxList . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { Object element = event . getElement ( ) ; if ( element instanceof FilterDescriptor ) { if ( fFilterDescriptorChangeHistory . contains ( element ) ) fFilterDescriptorChangeHistory . remove ( element ) ; fFilterDescriptorChangeHistory . push ( element ) ; } } } ) ; addSelectionButtons ( parent ) ; } private void addSelectionButtons ( Composite composite ) { Composite buttonComposite = new Composite ( composite , SWT . RIGHT ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; buttonComposite . setLayout ( layout ) ; GridData data = new GridData ( GridData . HORIZONTAL_ALIGN_END | GridData . GRAB_HORIZONTAL ) ; data . grabExcessHorizontalSpace = true ; composite . setData ( data ) ; String label = FilterMessages . CustomFiltersDialog_SelectAllButton_label ; Button selectButton = createButton ( buttonComposite , IDialogConstants . SELECT_ALL_ID , label , false ) ; SWTUtil . setButtonDimensionHint ( selectButton ) ; SelectionListener listener = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fCheckBoxList . setAllChecked ( true ) ; fFilterDescriptorChangeHistory . clear ( ) ; for ( int i = ; i < fBuiltInFilters . length ; i ++ ) fFilterDescriptorChangeHistory . push ( fBuiltInFilters [ i ] ) ; } } ; selectButton . addSelectionListener ( listener ) ; label = FilterMessages . CustomFiltersDialog_DeselectAllButton_label ; Button deselectButton = createButton ( buttonComposite , IDialogConstants . DESELECT_ALL_ID , label , false ) ; SWTUtil . setButtonDimensionHint ( deselectButton ) ; listener = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fCheckBoxList . setAllChecked ( false ) ; fFilterDescriptorChangeHistory . clear ( ) ; for ( int i = ; i < fBuiltInFilters . length ; i ++ ) fFilterDescriptorChangeHistory . push ( fBuiltInFilters [ i ] ) ; } } ; deselectButton . addSelectionListener ( listener ) ; } private void checkInitialSelections ( ) { Iterator itemsToCheck = getInitialElementSelections ( ) . iterator ( ) ; while ( itemsToCheck . hasNext ( ) ) fCheckBoxList . setChecked ( itemsToCheck . next ( ) , true ) ; } protected void okPressed ( ) { if ( fBuiltInFilters != null ) { ArrayList result = new ArrayList ( ) ; for ( int i = ; i < fBuiltInFilters . length ; ++ i ) { if ( fCheckBoxList . getChecked ( fBuiltInFilters [ i ] ) ) result . add ( fBuiltInFilters [ i ] ) ; } setResult ( result ) ; } super . okPressed ( ) ; } private ILabelProvider createLabelPrivder ( ) { return new LabelProvider ( ) { public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { if ( element instanceof FilterDescriptor ) return ( ( FilterDescriptor ) element ) . getName ( ) ; else return null ; } } ; } protected void setResult ( List newResult ) { super . setResult ( newResult ) ; if ( fUserDefinedPatterns . getText ( ) . length ( ) > ) { fEnablePatterns = fEnableUserDefinedPatterns . getSelection ( ) ; fPatterns = convertFromString ( fUserDefinedPatterns . getText ( ) , SEPARATOR ) ; } else { fEnablePatterns = false ; fPatterns = new String [ ] ; } } public String [ ] getUserDefinedPatterns ( ) { return fPatterns ; } public String [ ] getEnabledFilterIds ( ) { Object [ ] result = getResult ( ) ; Set enabledIds = new HashSet ( result . length ) ; for ( int i = ; i < result . length ; i ++ ) enabledIds . add ( ( ( FilterDescriptor ) result [ i ] ) . getId ( ) ) ; return ( String [ ] ) enabledIds . toArray ( new String [ enabledIds . size ( ) ] ) ; } public boolean areUserDefinedPatternsEnabled ( ) { return fEnablePatterns ; } public Stack getFilterDescriptorChangeHistory ( ) { return fFilterDescriptorChangeHistory ; } private FilterDescriptor [ ] getEnabledFilterDescriptors ( ) { FilterDescriptor [ ] filterDescs = fBuiltInFilters ; List result = new ArrayList ( filterDescs . length ) ; List enabledFilterIds = Arrays . asList ( fEnabledFilterIds ) ; for ( int i = ; i < filterDescs . length ; i ++ ) { String id = filterDescs [ i ] . getId ( ) ; if ( enabledFilterIds . contains ( id ) ) result . add ( filterDescs [ i ] ) ; } return ( FilterDescriptor [ ] ) result . toArray ( new FilterDescriptor [ result . size ( ) ] ) ; } public static String [ ] convertFromString ( String patterns , String separator ) { StringTokenizer tokenizer = new StringTokenizer ( patterns , separator , true ) ; int tokenCount = tokenizer . countTokens ( ) ; List result = new ArrayList ( tokenCount ) ; boolean escape = false ; boolean append = false ; while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) . trim ( ) ; if ( separator . equals ( token ) ) { if ( ! escape ) escape = true ; else { addPattern ( result , separator ) ; append = true ; } } else { if ( ! append ) result . add ( token ) ; else addPattern ( result , token ) ; append = false ; escape = false ; } } return ( String [ ] ) result . toArray ( new String [ result . size ( ) ] ) ; } private static void addPattern ( List list , String pattern ) { if ( list . isEmpty ( ) ) list . add ( pattern ) ; else { int index = list . size ( ) - ; list . set ( index , ( ( String ) list . get ( index ) ) + pattern ) ; } } public static String convertToString ( String [ ] patterns , String separator ) { int length = patterns . length ; StringBuffer strBuf = new StringBuffer ( ) ; if ( length > ) strBuf . append ( escapeSeparator ( patterns [ ] , separator ) ) ; else return "" ; int i = ; while ( i < length ) { strBuf . append ( separator ) ; strBuf . append ( "" ) ; strBuf . append ( escapeSeparator ( patterns [ i ++ ] , separator ) ) ; } return strBuf . toString ( ) ; } private static String escapeSeparator ( String pattern , String separator ) { int length = pattern . length ( ) ; StringBuffer buf = new StringBuffer ( length ) ; for ( int i = ; i < length ; i ++ ) { char ch = pattern . charAt ( i ) ; if ( separator . equals ( String . valueOf ( ch ) ) ) buf . append ( ch ) ; buf . append ( ch ) ; } return buf . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . IRubyElement ; public class ClosedProjectFilter extends ViewerFilter { public boolean select ( Viewer viewer , Object parent , Object element ) { if ( element instanceof IRubyElement ) return ( ( IRubyElement ) element ) . getRubyProject ( ) . getProject ( ) . isOpen ( ) ; if ( element instanceof IResource ) return ( ( IResource ) element ) . getProject ( ) . isOpen ( ) ; return true ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . rubypeople . rdt . internal . ui . viewsupport . MemberFilter ; public class StaticsFilter extends MemberFilter { public StaticsFilter ( ) { addFilter ( MemberFilter . FILTER_STATIC ) ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . RubyModelException ; public class RubyFileFilter extends ViewerFilter { public boolean select ( Viewer viewer , Object parent , Object element ) { if ( element instanceof IRubyScript ) return false ; if ( element instanceof ISourceFolder ) try { return ( ( ISourceFolder ) element ) . getNonRubyResources ( ) . length > ; } catch ( RubyModelException ex ) { return true ; } return true ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . osgi . util . NLS ; public final class FilterMessages extends NLS { private static final String BUNDLE_NAME = FilterMessages . class . getName ( ) ; private FilterMessages ( ) { } public static String CustomFiltersDialog_title ; public static String CustomFiltersDialog_patternInfo ; public static String CustomFiltersDialog_enableUserDefinedPattern ; public static String CustomFiltersDialog_filterList_label ; public static String CustomFiltersDialog_description_label ; public static String CustomFiltersDialog_SelectAllButton_label ; public static String CustomFiltersDialog_DeselectAllButton_label ; public static String OpenCustomFiltersDialogAction_text ; public static String FilterDescriptor_filterDescriptionCreationError_message ; public static String FilterDescriptor_filterCreationError_title ; public static String FilterDescriptor_filterCreationError_message ; static { NLS . initializeMessages ( BUNDLE_NAME , FilterMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . rubypeople . rdt . internal . ui . viewsupport . MemberFilter ; public class FieldsFilter extends MemberFilter { public FieldsFilter ( ) { addFilter ( MemberFilter . FILTER_FIELDS ) ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IStorage ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . IRubyElement ; public class NonRubyElementFilter extends ViewerFilter { public boolean select ( Viewer viewer , Object parent , Object element ) { if ( element instanceof IRubyElement ) return true ; if ( element instanceof IResource ) { IProject project = ( ( IResource ) element ) . getProject ( ) ; return project == null || ! project . isOpen ( ) ; } if ( element instanceof IStorage ) return false ; return true ; } } package org . rubypeople . rdt . internal . ui . filters ; import java . text . Collator ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . SafeRunnable ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . ui . IPluginContribution ; import org . eclipse . ui . activities . WorkbenchActivityHelper ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . ui . RubyUI ; public class FilterDescriptor implements Comparable , IPluginContribution { private static String PATTERN_FILTER_ID_PREFIX = "" ; private static final String EXTENSION_POINT_NAME = "" ; private static final String FILTER_TAG = "" ; private static final String PATTERN_ATTRIBUTE = "" ; private static final String ID_ATTRIBUTE = "" ; private static final String VIEW_ID_ATTRIBUTE = "" ; private static final String TARGET_ID_ATTRIBUTE = "" ; private static final String CLASS_ATTRIBUTE = "" ; private static final String NAME_ATTRIBUTE = "" ; private static final String ENABLED_ATTRIBUTE = "" ; private static final String DESCRIPTION_ATTRIBUTE = "" ; private static final String SELECTED_ATTRIBUTE = "" ; private static FilterDescriptor [ ] fgFilterDescriptors ; private IConfigurationElement fElement ; public static FilterDescriptor [ ] getFilterDescriptors ( ) { if ( fgFilterDescriptors == null ) { IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; IConfigurationElement [ ] elements = registry . getConfigurationElementsFor ( RubyUI . ID_PLUGIN , EXTENSION_POINT_NAME ) ; fgFilterDescriptors = createFilterDescriptors ( elements ) ; } return fgFilterDescriptors ; } public static FilterDescriptor [ ] getFilterDescriptors ( String targetId ) { FilterDescriptor [ ] filterDescs = FilterDescriptor . getFilterDescriptors ( ) ; List result = new ArrayList ( filterDescs . length ) ; for ( int i = ; i < filterDescs . length ; i ++ ) { String tid = filterDescs [ i ] . getTargetId ( ) ; if ( WorkbenchActivityHelper . filterItem ( filterDescs [ i ] ) ) continue ; if ( tid == null || tid . equals ( targetId ) ) result . add ( filterDescs [ i ] ) ; } return ( FilterDescriptor [ ] ) result . toArray ( new FilterDescriptor [ result . size ( ) ] ) ; } private FilterDescriptor ( IConfigurationElement element ) { fElement = element ; Assert . isTrue ( isPatternFilter ( ) ^ isCustomFilter ( ) , "" ) ; Assert . isNotNull ( getId ( ) , "" ) ; Assert . isNotNull ( getName ( ) , "" ) ; } public ViewerFilter createViewerFilter ( ) { if ( ! isCustomFilter ( ) ) return null ; final ViewerFilter [ ] result = new ViewerFilter [ ] ; String message = Messages . format ( FilterMessages . FilterDescriptor_filterCreationError_message , getId ( ) ) ; ISafeRunnable code = new SafeRunnable ( message ) { public void run ( ) throws Exception { result [ ] = ( ViewerFilter ) fElement . createExecutableExtension ( CLASS_ATTRIBUTE ) ; } } ; Platform . run ( code ) ; return result [ ] ; } public String getId ( ) { if ( isPatternFilter ( ) ) { String targetId = getTargetId ( ) ; if ( targetId == null ) return PATTERN_FILTER_ID_PREFIX + getPattern ( ) ; else return targetId + PATTERN_FILTER_ID_PREFIX + getPattern ( ) ; } else return fElement . getAttribute ( ID_ATTRIBUTE ) ; } public String getName ( ) { String name = fElement . getAttribute ( NAME_ATTRIBUTE ) ; if ( name == null && isPatternFilter ( ) ) name = getPattern ( ) ; return name ; } public String getPattern ( ) { return fElement . getAttribute ( PATTERN_ATTRIBUTE ) ; } public String getTargetId ( ) { String tid = fElement . getAttribute ( TARGET_ID_ATTRIBUTE ) ; if ( tid != null ) return tid ; return fElement . getAttribute ( VIEW_ID_ATTRIBUTE ) ; } public String getDescription ( ) { String description = fElement . getAttribute ( DESCRIPTION_ATTRIBUTE ) ; if ( description == null ) description = "" ; return description ; } public boolean isPatternFilter ( ) { return getPattern ( ) != null ; } public boolean isCustomFilter ( ) { return fElement . getAttribute ( CLASS_ATTRIBUTE ) != null ; } public boolean isEnabled ( ) { String strVal = fElement . getAttribute ( ENABLED_ATTRIBUTE ) ; if ( strVal == null ) strVal = fElement . getAttribute ( SELECTED_ATTRIBUTE ) ; return strVal == null || Boolean . valueOf ( strVal ) . booleanValue ( ) ; } public int compareTo ( Object o ) { if ( o instanceof FilterDescriptor ) return Collator . getInstance ( ) . compare ( getName ( ) , ( ( FilterDescriptor ) o ) . getName ( ) ) ; else return Integer . MIN_VALUE ; } private static FilterDescriptor [ ] createFilterDescriptors ( IConfigurationElement [ ] elements ) { List result = new ArrayList ( ) ; Set descIds = new HashSet ( ) ; for ( int i = ; i < elements . length ; i ++ ) { final IConfigurationElement element = elements [ i ] ; if ( FILTER_TAG . equals ( element . getName ( ) ) ) { final FilterDescriptor [ ] desc = new FilterDescriptor [ ] ; Platform . run ( new SafeRunnable ( FilterMessages . FilterDescriptor_filterDescriptionCreationError_message ) { public void run ( ) throws Exception { desc [ ] = new FilterDescriptor ( element ) ; } } ) ; if ( desc [ ] != null && ! descIds . contains ( desc [ ] . getId ( ) ) ) { result . add ( desc [ ] ) ; descIds . add ( desc [ ] . getId ( ) ) ; } } } return ( FilterDescriptor [ ] ) result . toArray ( new FilterDescriptor [ result . size ( ) ] ) ; } public String getLocalId ( ) { return fElement . getAttribute ( ID_ATTRIBUTE ) ; } public String getPluginId ( ) { return fElement . getNamespace ( ) ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . IImportDeclaration ; public class ImportDeclarationFilter extends ViewerFilter { public boolean select ( Viewer viewer , Object parent , Object element ) { return ! ( ( element instanceof IImportContainer ) || ( element instanceof IImportDeclaration ) ) ; } } package org . rubypeople . rdt . internal . ui . filters ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . team . core . RepositoryProvider ; import org . rubypeople . rdt . core . IRubyProject ; public class NonSharedProjectFilter extends ViewerFilter { public boolean select ( Viewer viewer , Object parent , Object element ) { if ( element instanceof IProject ) return isSharedProject ( ( IProject ) element ) ; if ( element instanceof IRubyProject ) return isSharedProject ( ( ( IRubyProject ) element ) . getProject ( ) ) ; return true ; } private boolean isSharedProject ( IProject project ) { return ! project . isAccessible ( ) || RepositoryProvider . isShared ( project ) ; } } package org . rubypeople . rdt . internal . ui . text ; import java . util . Arrays ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextUtilities ; public class RubyHeuristicScanner implements Symbols { public static final int NOT_FOUND = - ; public static final int UNBOUND = - ; private static final char LBRACE = '' ; private static final char RBRACE = '' ; private static final char LPAREN = '' ; private static final char RPAREN = '' ; private static final char SEMICOLON = '' ; private static final char COLON = '' ; private static final char COMMA = '' ; private static final char LBRACKET = '' ; private static final char RBRACKET = '' ; private static final char QUESTIONMARK = '' ; private static final char EQUAL = '' ; public interface StopCondition { boolean stop ( char ch , int position , boolean forward ) ; } private static class NonWhitespace implements StopCondition { public boolean stop ( char ch , int position , boolean forward ) { return ! Character . isWhitespace ( ch ) ; } } private class NonWhitespaceDefaultPartition extends NonWhitespace { public boolean stop ( char ch , int position , boolean forward ) { return super . stop ( ch , position , true ) && isDefaultPartition ( position ) ; } } private static class NonRubyIdentifierPart implements StopCondition { public boolean stop ( char ch , int position , boolean forward ) { return ! Character . isJavaIdentifierPart ( ch ) ; } } private class NonRubyIdentifierPartDefaultPartition extends NonRubyIdentifierPart { public boolean stop ( char ch , int position , boolean forward ) { return super . stop ( ch , position , true ) || ! isDefaultPartition ( position ) ; } } private class CharacterMatch implements StopCondition { private final char [ ] fChars ; public CharacterMatch ( char ch ) { this ( new char [ ] { ch } ) ; } public CharacterMatch ( char [ ] chars ) { Assert . isNotNull ( chars ) ; Assert . isTrue ( chars . length > ) ; fChars = chars ; Arrays . sort ( chars ) ; } public boolean stop ( char ch , int position , boolean forward ) { return Arrays . binarySearch ( fChars , ch ) >= && isDefaultPartition ( position ) ; } } protected class SkippingScopeMatch extends CharacterMatch { private char fOpening , fClosing ; private int fDepth = ; public SkippingScopeMatch ( char ch ) { super ( ch ) ; } public SkippingScopeMatch ( char [ ] chars ) { super ( chars ) ; } public boolean stop ( char ch , int position , boolean forward ) { if ( fDepth == && super . stop ( ch , position , true ) ) return true ; else if ( ch == fOpening ) fDepth ++ ; else if ( ch == fClosing ) { fDepth -- ; if ( fDepth == ) { fOpening = ; fClosing = ; } } else if ( fDepth == ) { fDepth = ; if ( forward ) { switch ( ch ) { case LBRACE : fOpening = LBRACE ; fClosing = RBRACE ; break ; case LPAREN : fOpening = LPAREN ; fClosing = RPAREN ; break ; case LBRACKET : fOpening = LBRACKET ; fClosing = RBRACKET ; break ; } } else { switch ( ch ) { case RBRACE : fOpening = RBRACE ; fClosing = LBRACE ; break ; case RPAREN : fOpening = RPAREN ; fClosing = LPAREN ; break ; case RBRACKET : fOpening = RBRACKET ; fClosing = LBRACKET ; break ; } } } return false ; } } private IDocument fDocument ; private String fPartitioning ; private String fPartition ; private char fChar ; private int fPos ; private final StopCondition fNonWSDefaultPart = new NonWhitespaceDefaultPartition ( ) ; private final static StopCondition fNonWS = new NonWhitespace ( ) ; private final StopCondition fNonIdent = new NonRubyIdentifierPartDefaultPartition ( ) ; public RubyHeuristicScanner ( IDocument document , String partitioning , String partition ) { Assert . isNotNull ( document ) ; Assert . isNotNull ( partitioning ) ; Assert . isNotNull ( partition ) ; fDocument = document ; fPartitioning = partitioning ; fPartition = partition ; } public RubyHeuristicScanner ( IDocument document ) { this ( document , IRubyPartitions . RUBY_PARTITIONING , IDocument . DEFAULT_CONTENT_TYPE ) ; } public int getPosition ( ) { return fPos ; } public int nextToken ( int start , int bound ) { int pos = scanForward ( start , bound , fNonWSDefaultPart ) ; if ( pos == NOT_FOUND ) return TokenEOF ; fPos ++ ; switch ( fChar ) { case LBRACE : return TokenLBRACE ; case RBRACE : return TokenRBRACE ; case LBRACKET : return TokenLBRACKET ; case RBRACKET : return TokenRBRACKET ; case LPAREN : return TokenLPAREN ; case RPAREN : return TokenRPAREN ; case SEMICOLON : return TokenSEMICOLON ; case COMMA : return TokenCOMMA ; case QUESTIONMARK : return TokenQUESTIONMARK ; case EQUAL : return TokenEQUAL ; } if ( Character . isJavaIdentifierPart ( fChar ) ) { int from = pos , to ; pos = scanForward ( pos + , bound , fNonIdent ) ; if ( pos == NOT_FOUND ) to = bound == UNBOUND ? fDocument . getLength ( ) : bound ; else to = pos ; String identOrKeyword ; try { identOrKeyword = fDocument . get ( from , to - from ) ; } catch ( BadLocationException e ) { return TokenEOF ; } return getToken ( identOrKeyword ) ; } return TokenOTHER ; } public int previousToken ( int start , int bound ) { int pos = scanBackward ( start , bound , fNonWSDefaultPart ) ; if ( pos == NOT_FOUND ) return TokenEOF ; fPos -- ; switch ( fChar ) { case LBRACE : return TokenLBRACE ; case RBRACE : return TokenRBRACE ; case LBRACKET : return TokenLBRACKET ; case RBRACKET : return TokenRBRACKET ; case LPAREN : return TokenLPAREN ; case RPAREN : return TokenRPAREN ; case SEMICOLON : return TokenSEMICOLON ; case COLON : return TokenCOLON ; case COMMA : return TokenCOMMA ; case QUESTIONMARK : return TokenQUESTIONMARK ; case EQUAL : return TokenEQUAL ; } if ( Character . isJavaIdentifierPart ( fChar ) ) { int from , to = pos + ; pos = scanBackward ( pos - , bound , fNonIdent ) ; if ( pos == NOT_FOUND ) from = bound == UNBOUND ? : bound + ; else from = pos + ; String identOrKeyword ; try { identOrKeyword = fDocument . get ( from , to - from ) ; } catch ( BadLocationException e ) { return TokenEOF ; } return getToken ( identOrKeyword ) ; } return TokenOTHER ; } private int getToken ( String s ) { Assert . isNotNull ( s ) ; switch ( s . length ( ) ) { case : if ( "" . equals ( s ) ) return TokenIF ; if ( "" . equals ( s ) ) return TokenIN ; if ( "" . equals ( s ) ) return TokenDO ; if ( "" . equals ( s ) ) return TokenOR ; break ; case : if ( "" . equals ( s ) ) return TokenEND ; if ( "" . equals ( s ) ) return TokenBIGEND ; if ( "" . equals ( s ) ) return TokenDEF ; if ( "" . equals ( s ) ) return TokenFOR ; if ( "" . equals ( s ) ) return TokenNIL ; if ( "" . equals ( s ) ) return TokenAND ; if ( "" . equals ( s ) ) return TokenNOT ; break ; case : if ( "" . equals ( s ) ) return TokenSELF ; if ( "" . equals ( s ) ) return TokenTRUE ; if ( "" . equals ( s ) ) return TokenCASE ; if ( "" . equals ( s ) ) return TokenELSE ; if ( "" . equals ( s ) ) return TokenTHEN ; if ( "" . equals ( s ) ) return TokenWHEN ; if ( "" . equals ( s ) ) return TokenNEXT ; if ( "" . equals ( s ) ) return TokenREDO ; break ; case : if ( "" . equals ( s ) ) return TokenBREAK ; if ( "" . equals ( s ) ) return TokenALIAS ; if ( "" . equals ( s ) ) return TokenCLASS ; if ( "" . equals ( s ) ) return TokenWHILE ; if ( "" . equals ( s ) ) return TokenUNDEF ; if ( "" . equals ( s ) ) return TokenBEGIN ; if ( "" . equals ( s ) ) return TokenBIGBEGIN ; if ( "" . equals ( s ) ) return TokenRETRY ; if ( "" . equals ( s ) ) return TokenYIELD ; if ( "" . equals ( s ) ) return TokenSUPER ; if ( "" . equals ( s ) ) return TokenFALSE ; if ( "" . equals ( s ) ) return TokenUNTIL ; if ( "" . equals ( s ) ) return TokenELSIF ; break ; case : if ( "" . equals ( s ) ) return TokenRETURN ; if ( "" . equals ( s ) ) return TokenMODULE ; if ( "" . equals ( s ) ) return TokenUNLESS ; if ( "" . equals ( s ) ) return TokenRESCUE ; if ( "" . equals ( s ) ) return TokenENSURE ; break ; case : if ( "" . equals ( s ) ) return TokenDEFINED ; break ; case : if ( "" . equals ( s ) ) return TokenLINE ; if ( "" . equals ( s ) ) return TokenFILE ; break ; } return TokenIDENT ; } public int findClosingPeer ( int start , final char openingPeer , final char closingPeer ) { Assert . isNotNull ( fDocument ) ; Assert . isTrue ( start >= ) ; try { int depth = ; start -= ; while ( true ) { start = scanForward ( start + , UNBOUND , new CharacterMatch ( new char [ ] { openingPeer , closingPeer } ) ) ; if ( start == NOT_FOUND ) return NOT_FOUND ; if ( fDocument . getChar ( start ) == openingPeer ) depth ++ ; else depth -- ; if ( depth == ) return start ; } } catch ( BadLocationException e ) { return NOT_FOUND ; } } public int findOpeningPeer ( int start , char openingPeer , char closingPeer ) { Assert . isTrue ( start < fDocument . getLength ( ) ) ; try { int depth = ; start += ; while ( true ) { start = scanBackward ( start - , UNBOUND , new CharacterMatch ( new char [ ] { openingPeer , closingPeer } ) ) ; if ( start == NOT_FOUND ) return NOT_FOUND ; if ( fDocument . getChar ( start ) == closingPeer ) depth ++ ; else depth -- ; if ( depth == ) return start ; } } catch ( BadLocationException e ) { return NOT_FOUND ; } } public IRegion findSurroundingBlock ( int offset ) { if ( offset < || offset >= fDocument . getLength ( ) ) return null ; int begin = findOpeningPeer ( offset - , LBRACE , RBRACE ) ; int end = findClosingPeer ( offset , LBRACE , RBRACE ) ; if ( begin == NOT_FOUND || end == NOT_FOUND ) return null ; return new Region ( begin , end + - begin ) ; } public int findNonWhitespaceForward ( int position , int bound ) { return scanForward ( position , bound , fNonWSDefaultPart ) ; } public int findNonWhitespaceForwardInAnyPartition ( int position , int bound ) { return scanForward ( position , bound , fNonWS ) ; } public int findNonWhitespaceBackward ( int position , int bound ) { return scanBackward ( position , bound , fNonWSDefaultPart ) ; } public int scanForward ( int start , int bound , StopCondition condition ) { Assert . isTrue ( start >= ) ; if ( bound == UNBOUND ) bound = fDocument . getLength ( ) ; Assert . isTrue ( bound <= fDocument . getLength ( ) ) ; try { fPos = start ; while ( fPos < bound ) { fChar = fDocument . getChar ( fPos ) ; if ( condition . stop ( fChar , fPos , true ) ) return fPos ; fPos ++ ; } } catch ( BadLocationException e ) { } return NOT_FOUND ; } public int scanForward ( int position , int bound , char ch ) { return scanForward ( position , bound , new CharacterMatch ( ch ) ) ; } public int scanForward ( int position , int bound , char [ ] chars ) { return scanForward ( position , bound , new CharacterMatch ( chars ) ) ; } public int scanBackward ( int start , int bound , StopCondition condition ) { if ( bound == UNBOUND ) bound = - ; Assert . isTrue ( bound >= - ) ; Assert . isTrue ( start < fDocument . getLength ( ) ) ; try { fPos = start ; while ( fPos > bound ) { fChar = fDocument . getChar ( fPos ) ; if ( condition . stop ( fChar , fPos , false ) ) return fPos ; fPos -- ; } } catch ( BadLocationException e ) { } return NOT_FOUND ; } public int scanBackward ( int position , int bound , char ch ) { return scanBackward ( position , bound , new CharacterMatch ( ch ) ) ; } public int scanBackward ( int position , int bound , char [ ] chars ) { return scanBackward ( position , bound , new CharacterMatch ( chars ) ) ; } public boolean isDefaultPartition ( int position ) { Assert . isTrue ( position >= ) ; Assert . isTrue ( position <= fDocument . getLength ( ) ) ; try { ITypedRegion region = TextUtilities . getPartition ( fDocument , fPartitioning , position , false ) ; return region . getType ( ) . equals ( fPartition ) ; } catch ( BadLocationException e ) { } return false ; } public boolean isBracelessBlockStart ( int position , int bound ) { if ( position < ) return false ; switch ( previousToken ( position , bound ) ) { case TokenDO : case TokenELSE : return true ; case TokenRPAREN : position = findOpeningPeer ( fPos , LPAREN , RPAREN ) ; if ( position > ) { switch ( previousToken ( position - , bound ) ) { case TokenIF : case TokenFOR : case TokenWHILE : return true ; } } } return false ; } } package org . rubypeople . rdt . internal . ui . text ; import java . io . IOException ; import java . io . StringReader ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . rules . IPartitionTokenScanner ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . Token ; import org . jruby . CompatVersion ; import org . jruby . ast . CommentNode ; import org . jruby . ast . Node ; import org . jruby . common . NullWarnings ; import org . jruby . lexer . yacc . LexerSource ; import org . jruby . lexer . yacc . RubyYaccLexer ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . lexer . yacc . RubyYaccLexer . LexState ; import org . jruby . parser . ParserConfiguration ; import org . jruby . parser . ParserSupport ; import org . jruby . parser . RubyParserResult ; import org . jruby . parser . Tokens ; import org . jruby . util . KCode ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyPartitionScanner implements IPartitionTokenScanner { private static final String BEGIN = "" ; private static class QueuedToken { private IToken token ; private int length ; private int offset ; QueuedToken ( IToken token , int offset , int length ) { this . token = token ; this . length = length ; this . offset = offset ; } public int getLength ( ) { return length ; } public int getOffset ( ) { return offset ; } public IToken getToken ( ) { return token ; } @ Override public String toString ( ) { return getToken ( ) . getData ( ) + "" + getOffset ( ) + "" + getLength ( ) ; } } private RubyYaccLexer lexer ; private ParserSupport parserSupport ; private RubyParserResult result ; private String fContents ; private LexerSource lexerSource ; private int origOffset ; private int origLength ; private int fLength ; private int fOffset ; private List < QueuedToken > fQueue = new ArrayList < QueuedToken > ( ) ; private String fContentType = RUBY_DEFAULT ; private boolean inSingleQuote ; private String fOpeningString ; public final static String RUBY_MULTI_LINE_COMMENT = IRubyPartitions . RUBY_MULTI_LINE_COMMENT ; public final static String RUBY_SINGLE_LINE_COMMENT = IRubyPartitions . RUBY_SINGLE_LINE_COMMENT ; public final static String RUBY_STRING = IRubyPartitions . RUBY_STRING ; public final static String RUBY_REGULAR_EXPRESSION = IRubyPartitions . RUBY_REGULAR_EXPRESSION ; public static final String RUBY_DEFAULT = IRubyPartitions . RUBY_DEFAULT ; public static final String RUBY_COMMAND = IRubyPartitions . RUBY_COMMAND ; public static final String [ ] LEGAL_CONTENT_TYPES = { RUBY_DEFAULT , RUBY_MULTI_LINE_COMMENT , RUBY_SINGLE_LINE_COMMENT , RUBY_REGULAR_EXPRESSION , RUBY_STRING , RUBY_COMMAND } ; public RubyPartitionScanner ( ) { lexer = new RubyYaccLexer ( ) ; parserSupport = new ParserSupport ( ) ; ParserConfiguration config = new ParserConfiguration ( KCode . NIL , , false , CompatVersion . RUBY1_8 ) ; config . setExtraPositionInformation ( true ) ; parserSupport . setConfiguration ( config ) ; result = new RubyParserResult ( ) ; parserSupport . setResult ( result ) ; lexer . setParserSupport ( parserSupport ) ; lexer . setWarnings ( new NullWarnings ( ) ) ; lexer . setEncoding ( config . getKCode ( ) . getEncoding ( ) ) ; } public void setPartialRange ( IDocument document , int offset , int length , String contentType , int partitionOffset ) { reset ( ) ; int myOffset = offset ; if ( contentType != null ) { int diff = offset - partitionOffset ; myOffset = partitionOffset ; length += diff ; this . fContentType = contentType ; } if ( myOffset == - ) myOffset = ; ParserConfiguration config = new ParserConfiguration ( KCode . NIL , , true , false , CompatVersion . RUBY1_8 ) ; try { fContents = document . get ( myOffset , length ) ; lexerSource = LexerSource . getSource ( "" , new StringReader ( fContents ) , null , config ) ; lexer . setSource ( lexerSource ) ; } catch ( BadLocationException e ) { lexerSource = LexerSource . getSource ( "" , new StringReader ( "" ) , null , config ) ; lexer . setSource ( lexerSource ) ; } origOffset = myOffset ; origLength = length ; } private void reset ( ) { lexer . reset ( ) ; lexer . setState ( LexState . EXPR_BEG ) ; parserSupport . initTopLocalVariables ( ) ; fQueue . clear ( ) ; inSingleQuote = false ; } public int getTokenLength ( ) { return fLength ; } public int getTokenOffset ( ) { return fOffset ; } public IToken nextToken ( ) { if ( ! fQueue . isEmpty ( ) ) { return popTokenOffQueue ( ) ; } fOffset = getOffset ( ) ; fLength = ; IToken returnValue = new Token ( RUBY_DEFAULT ) ; boolean isEOF = false ; try { isEOF = ! lexer . advance ( ) ; if ( isEOF ) { returnValue = Token . EOF ; } else { int lexerToken = lexer . token ( ) ; if ( ! inSingleQuote && lexerToken == Tokens . tSTRING_DVAR ) { addPoundToken ( ) ; scanDynamicVariable ( ) ; setLexerPastDynamicSectionOfString ( ) ; return popTokenOffQueue ( ) ; } else if ( ! inSingleQuote && lexerToken == Tokens . tSTRING_DBEG ) { addPoundBraceToken ( ) ; scanTokensInsideDynamicPortion ( ) ; addClosingBraceToken ( ) ; setLexerPastDynamicSectionOfString ( ) ; return popTokenOffQueue ( ) ; } else if ( lexerToken == Tokens . tSTRING_BEG ) { String opening = getUntrimmedOpeningString ( ) ; int endOfMarker = indexOf ( opening . trim ( ) , "" ) ; if ( opening . trim ( ) . startsWith ( "" ) && endOfMarker != - ) { adjustOffset ( opening ) ; addHereDocStartToken ( endOfMarker ) ; addCommaToken ( endOfMarker ) ; scanRestOfLineAfterHeredocBegins ( opening . trim ( ) , endOfMarker ) ; setLexerPastHeredocBeginning ( opening . trim ( ) ) ; return popTokenOffQueue ( ) ; } } returnValue = getToken ( lexerToken ) ; } List < CommentNode > comments = result . getCommentNodes ( ) ; if ( comments != null && ! comments . isEmpty ( ) ) { parseOutComments ( comments ) ; addQueuedToken ( returnValue , isEOF ) ; comments . clear ( ) ; return popTokenOffQueue ( ) ; } } catch ( SyntaxException se ) { if ( se . getMessage ( ) . equals ( "" ) ) { int start = se . getPosition ( ) . getStartOffset ( ) ; int length = fContents . length ( ) - start ; QueuedToken qtoken = new QueuedToken ( new Token ( RUBY_MULTI_LINE_COMMENT ) , start + origOffset , length ) ; if ( fOffset == origOffset ) { RubyPartitionScanner scanner = new RubyPartitionScanner ( ) ; String possible = new String ( fContents . substring ( , start ) ) ; IDocument document = new Document ( possible ) ; scanner . setRange ( document , origOffset , possible . length ( ) ) ; IToken token ; while ( ! ( token = scanner . nextToken ( ) ) . isEOF ( ) ) { push ( new QueuedToken ( token , scanner . getTokenOffset ( ) + fOffset , scanner . getTokenLength ( ) ) ) ; } } push ( qtoken ) ; push ( new QueuedToken ( Token . EOF , start + origOffset + length , ) ) ; return popTokenOffQueue ( ) ; } else if ( se . getMessage ( ) . equals ( "" ) ) { int start = se . getPosition ( ) . getStartOffset ( ) ; int length = fContents . length ( ) - start ; QueuedToken qtoken = new QueuedToken ( new Token ( fContentType ) , start + origOffset , length ) ; if ( fOffset == origOffset ) { RubyPartitionScanner scanner = new RubyPartitionScanner ( ) ; String possible = new String ( fContents . substring ( , start ) ) ; IDocument document = new Document ( possible ) ; scanner . setRange ( document , origOffset , possible . length ( ) ) ; IToken token ; while ( ! ( token = scanner . nextToken ( ) ) . isEOF ( ) ) { push ( new QueuedToken ( token , scanner . getTokenOffset ( ) + fOffset , scanner . getTokenLength ( ) ) ) ; } } push ( qtoken ) ; push ( new QueuedToken ( Token . EOF , start + origOffset + length , ) ) ; return popTokenOffQueue ( ) ; } if ( lexerSource . getOffset ( ) - origLength == ) return Token . EOF ; else fLength = getOffset ( ) - fOffset ; Assert . isTrue ( fLength >= ) ; return new Token ( RUBY_DEFAULT ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } if ( ! isEOF ) { fLength = getOffset ( ) - fOffset ; Assert . isTrue ( fLength >= ) ; } return returnValue ; } private void setLexerPastHeredocBeginning ( String rawBeginning ) throws IOException { StringBuffer fakeContents = new StringBuffer ( ) ; int toAdd = ; if ( rawBeginning . startsWith ( "" ) ) { toAdd = ; } int start = fOffset - ( fOpeningString . length ( ) + toAdd ) ; for ( int i = ; i < start ; i ++ ) { fakeContents . append ( "" ) ; } fakeContents . append ( "" ) ; if ( rawBeginning . startsWith ( "" ) ) { fakeContents . append ( "" ) ; } fakeContents . append ( fOpeningString . trim ( ) ) ; if ( ( fOffset - origOffset ) < origLength ) { fakeContents . append ( new String ( fContents . substring ( ( fOffset - origOffset ) ) ) ) ; } IDocument document = new Document ( fakeContents . toString ( ) ) ; List < QueuedToken > queueCopy = new ArrayList < QueuedToken > ( fQueue ) ; setPartialRange ( document , start , fakeContents . length ( ) - start , null , start ) ; fQueue = new ArrayList < QueuedToken > ( queueCopy ) ; lexer . advance ( ) ; } private void adjustOffset ( String opening ) { int index = opening . indexOf ( "" ) ; if ( index > ) setOffset ( fOffset + index ) ; } private int indexOf ( String opening , String string ) { String trimmed = opening . trim ( ) ; int diff ; if ( trimmed . length ( ) == ) { diff = opening . length ( ) ; } else { diff = opening . indexOf ( trimmed . charAt ( ) ) ; } int lowest = - ; for ( int i = ; i < string . length ( ) ; i ++ ) { char c = string . charAt ( i ) ; int value = trimmed . indexOf ( c ) ; if ( value == - ) continue ; value += diff ; if ( lowest == - ) { lowest = value ; continue ; } if ( value < lowest ) lowest = value ; } return lowest ; } private void scanRestOfLineAfterHeredocBegins ( String opening , int index ) { String possible = new String ( opening . substring ( index + ) ) ; RubyPartitionScanner scanner = new RubyPartitionScanner ( ) ; IDocument document = new Document ( possible ) ; scanner . setRange ( document , , possible . length ( ) ) ; IToken token ; while ( ! ( token = scanner . nextToken ( ) ) . isEOF ( ) ) { push ( new QueuedToken ( token , scanner . getTokenOffset ( ) + fOffset + index + , scanner . getTokenLength ( ) ) ) ; } setOffset ( fOffset + index + + possible . length ( ) ) ; if ( scanner . fOpeningString != null && scanner . fOpeningString . endsWith ( "" ) ) { fOpeningString = scanner . fOpeningString ; } else { String marker = new String ( opening . substring ( , index ) . trim ( ) ) ; fOpeningString = generateHeredocMarker ( marker ) ; } fContentType = RUBY_STRING ; } private void addCommaToken ( int index ) { push ( new QueuedToken ( new Token ( RUBY_DEFAULT ) , fOffset + index , ) ) ; } private void addHereDocStartToken ( int index ) { push ( new QueuedToken ( new Token ( RUBY_STRING ) , fOffset , index ) ) ; } private void setOffset ( int offset ) { fOffset = offset ; } private void addPoundToken ( ) { addStringToken ( ) ; } private void scanDynamicVariable ( ) { int whitespace = fContents . indexOf ( '' , fOffset - origOffset ) ; if ( whitespace == - ) whitespace = Integer . MAX_VALUE ; int doubleQuote = fContents . indexOf ( '' , fOffset - origOffset ) ; if ( doubleQuote == - ) doubleQuote = Integer . MAX_VALUE ; int end = Math . min ( whitespace , doubleQuote ) ; String possible = null ; if ( end == - ) { possible = new String ( fContents . substring ( fOffset - origOffset ) ) ; } else { possible = new String ( fContents . substring ( fOffset - origOffset , end ) ) ; } RubyPartitionScanner scanner = new RubyPartitionScanner ( ) ; IDocument document = new Document ( possible ) ; scanner . setRange ( document , , possible . length ( ) ) ; IToken token ; while ( ! ( token = scanner . nextToken ( ) ) . isEOF ( ) ) { push ( new QueuedToken ( token , scanner . getTokenOffset ( ) + ( fOffset ) , scanner . getTokenLength ( ) ) ) ; } setOffset ( fOffset + possible . length ( ) ) ; } private void scanTokensInsideDynamicPortion ( ) { String possible = new String ( fContents . substring ( fOffset - origOffset ) ) ; int end = findEnd ( possible ) ; if ( end != - ) { possible = new String ( possible . substring ( , end ) ) ; } RubyPartitionScanner scanner = new RubyPartitionScanner ( ) ; IDocument document = new Document ( possible ) ; scanner . setRange ( document , , possible . length ( ) ) ; IToken token ; while ( ! ( token = scanner . nextToken ( ) ) . isEOF ( ) ) { push ( new QueuedToken ( token , scanner . getTokenOffset ( ) + fOffset , scanner . getTokenLength ( ) ) ) ; } setOffset ( fOffset + possible . length ( ) ) ; } private int findEnd ( String possible ) { return new EndBraceFinder ( possible ) . find ( ) ; } private void addPoundBraceToken ( ) { addStringToken ( ) ; } private void addStringToken ( int length ) { push ( new QueuedToken ( new Token ( fContentType ) , fOffset , length ) ) ; setOffset ( fOffset + length ) ; } private void addClosingBraceToken ( ) { addStringToken ( ) ; } private void setLexerPastDynamicSectionOfString ( ) throws IOException { StringBuffer fakeContents = new StringBuffer ( ) ; String opening = fOpeningString ; if ( opening . endsWith ( "" ) ) { String heredocStart = "" ; int lastIndent = fContents . lastIndexOf ( "" + opening , fOffset ) ; if ( lastIndent != - ) { if ( lastIndent > fContents . lastIndexOf ( "" + opening , fOffset ) ) heredocStart = "" ; } opening = heredocStart + opening ; } int start = fOffset - opening . length ( ) ; for ( int i = ; i < start ; i ++ ) { fakeContents . append ( "" ) ; } fakeContents . append ( opening ) ; if ( ( fOffset - origOffset ) < origLength ) { fakeContents . append ( new String ( fContents . substring ( ( fOffset - origOffset ) ) ) ) ; } IDocument document = new Document ( fakeContents . toString ( ) ) ; List < QueuedToken > queueCopy = new ArrayList < QueuedToken > ( fQueue ) ; setPartialRange ( document , start , fakeContents . length ( ) - start , null , start ) ; fQueue = new ArrayList < QueuedToken > ( queueCopy ) ; lexer . advance ( ) ; } private void parseOutComments ( List < CommentNode > comments ) { for ( CommentNode comment : comments ) { int offset = correctOffset ( comment ) ; int length = comment . getContent ( ) . length ( ) ; if ( isCommentMultiLine ( comment ) ) { length = ( origOffset + comment . getPosition ( ) . getEndOffset ( ) ) - offset ; if ( comment . getContent ( ) . charAt ( ) != '' ) { length ++ ; } } Token token = new Token ( getContentType ( comment ) ) ; push ( new QueuedToken ( token , offset , length ) ) ; } } private IToken popTokenOffQueue ( ) { QueuedToken token = fQueue . remove ( ) ; setOffset ( token . getOffset ( ) ) ; Assert . isTrue ( token . getLength ( ) >= ) ; fLength = token . getLength ( ) ; return token . getToken ( ) ; } private IToken getToken ( int i ) { if ( i == ) { return new Token ( fContentType ) ; } switch ( i ) { case Tokens . tSTRING_CONTENT : return new Token ( fContentType ) ; case Tokens . tSTRING_BEG : fOpeningString = getOpeningString ( ) ; if ( fOpeningString . equals ( "" ) || fOpeningString . startsWith ( "" ) ) { inSingleQuote = true ; } else if ( fOpeningString . startsWith ( "" ) ) { fOpeningString = generateHeredocMarker ( fOpeningString ) ; } fContentType = RUBY_STRING ; return new Token ( RUBY_STRING ) ; case Tokens . tXSTRING_BEG : fOpeningString = getOpeningString ( ) ; fContentType = RUBY_COMMAND ; return new Token ( RUBY_COMMAND ) ; case Tokens . tQWORDS_BEG : case Tokens . tWORDS_BEG : fOpeningString = getOpeningString ( ) ; fContentType = RUBY_STRING ; return new Token ( RUBY_STRING ) ; case Tokens . tSTRING_END : String oldContentType = fContentType ; fContentType = RUBY_DEFAULT ; inSingleQuote = false ; return new Token ( oldContentType ) ; case Tokens . tREGEXP_BEG : fOpeningString = getOpeningString ( ) ; fContentType = RUBY_REGULAR_EXPRESSION ; return new Token ( RUBY_REGULAR_EXPRESSION ) ; case Tokens . tREGEXP_END : fContentType = RUBY_DEFAULT ; return new Token ( RUBY_REGULAR_EXPRESSION ) ; case Tokens . tSYMBEG : int nextCharOffset = ( fOffset + ) ; int charAt = nextCharOffset - origOffset ; if ( fContents . length ( ) <= charAt ) { return new Token ( RUBY_DEFAULT ) ; } char c = fContents . charAt ( charAt ) ; if ( c == '' ) { if ( fContents . length ( ) <= charAt + ) { return new Token ( RUBY_DEFAULT ) ; } nextCharOffset ++ ; c = fContents . charAt ( charAt + ) ; } if ( c == '' ) { fOpeningString = "" ; push ( new QueuedToken ( new Token ( RUBY_STRING ) , nextCharOffset , ) ) ; fContentType = RUBY_STRING ; } return new Token ( RUBY_DEFAULT ) ; default : return new Token ( RUBY_DEFAULT ) ; } } private String generateHeredocMarker ( String marker ) { if ( marker . startsWith ( "" ) ) { marker = marker . substring ( ) ; } if ( marker . startsWith ( "" ) ) { marker = marker . substring ( ) ; } return marker + "" ; } private String getOpeningString ( ) { return getUntrimmedOpeningString ( ) . trim ( ) ; } private String getUntrimmedOpeningString ( ) { int start = fOffset - origOffset ; List < CommentNode > comments = result . getCommentNodes ( ) ; if ( comments != null && ! comments . isEmpty ( ) ) { Node comment = ( Node ) comments . get ( comments . size ( ) - ) ; int end = comment . getPosition ( ) . getEndOffset ( ) ; start = end ; } return new String ( fContents . substring ( start , lexerSource . getOffset ( ) ) ) ; } private int correctOffset ( CommentNode comment ) { return origOffset + comment . getPosition ( ) . getStartOffset ( ) ; } private boolean isCommentMultiLine ( CommentNode comment ) { String src = ASTUtil . getSource ( fContents , comment ) ; if ( src != null && src . startsWith ( BEGIN ) ) return true ; return false ; } private String getContentType ( CommentNode comment ) { if ( isCommentMultiLine ( comment ) ) return RUBY_MULTI_LINE_COMMENT ; return RUBY_SINGLE_LINE_COMMENT ; } private void addQueuedToken ( IToken returnValue , boolean isEOF ) { QueuedToken token = peek ( ) ; setOffset ( token . getOffset ( ) + token . getLength ( ) ) ; int length = getOffset ( ) - fOffset ; if ( length < ) { length = ; } push ( new QueuedToken ( returnValue , fOffset , length ) ) ; } private QueuedToken peek ( ) { return fQueue . get ( fQueue . size ( ) - ) ; } private void push ( QueuedToken token ) { Assert . isTrue ( token . getLength ( ) >= ) ; fQueue . add ( token ) ; } private int getOffset ( ) { return lexerSource . getOffset ( ) + origOffset ; } public void setRange ( IDocument document , int offset , int length ) { setPartialRange ( document , offset , length , RUBY_DEFAULT , ) ; } public static class EndBraceFinder { private String input ; private List < String > stack ; public EndBraceFinder ( String possible ) { this . input = possible ; stack = new ArrayList < String > ( ) ; } public int find ( ) { for ( int i = ; i < input . length ( ) ; i ++ ) { char c = input . charAt ( i ) ; switch ( c ) { case '' : case '' : i ++ ; break ; case '' : if ( topEquals ( "" ) ) { pop ( ) ; } else { if ( ! topEquals ( "" ) ) push ( "" ) ; } break ; case '' : if ( topEquals ( "" ) ) { pop ( ) ; } else { push ( "" ) ; } break ; case '' : if ( topEquals ( "" ) ) { pop ( ) ; } else if ( ! topEquals ( "" ) && ! topEquals ( "" ) ) { push ( "" ) ; } break ; case '' : if ( ! topEquals ( "" ) && ! topEquals ( "" ) ) { push ( "" ) ; } break ; case '' : if ( topEquals ( "" ) ) { c = input . charAt ( i + ) ; if ( c == '' ) push ( "" ) ; } break ; case '' : if ( stack . isEmpty ( ) ) { return i ; } if ( topEquals ( "" ) || topEquals ( "" ) ) { pop ( ) ; } break ; default : break ; } } return - ; } private boolean topEquals ( String string ) { String open = peek ( ) ; return open != null && open . equals ( string ) ; } private boolean push ( String string ) { return stack . add ( string ) ; } private String pop ( ) { return stack . remove ( stack . size ( ) - ) ; } private String peek ( ) { if ( stack . isEmpty ( ) ) return null ; return stack . get ( stack . size ( ) - ) ; } } } package org . rubypeople . rdt . internal . ui . text ; public interface IReconcilingParticipant { void reconciled ( ) ; } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . text . source . ICharacterPairMatcher ; import org . jruby . ast . BeginNode ; import org . jruby . ast . CaseNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . ForNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . SClassNode ; import org . jruby . ast . WhenNode ; import org . jruby . ast . WhileNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyPairMatcher implements ICharacterPairMatcher { protected char [ ] fPairs ; protected IDocument fDocument ; protected int fOffset ; protected int fStartPos ; protected int fEndPos ; protected int fAnchor ; public RubyPairMatcher ( char [ ] pairs ) { fPairs = pairs ; } public IRegion match ( IDocument document , int offset ) { fOffset = offset ; if ( fOffset < ) return null ; fDocument = document ; if ( fDocument != null && matchPairsAt ( ) && fStartPos != fEndPos ) return new Region ( fStartPos , fEndPos - fStartPos + ) ; if ( fDocument != null && matchBlocksAt ( ) && fStartPos != fEndPos ) return new Region ( fStartPos , fEndPos - fStartPos + ) ; return null ; } private boolean matchBlocksAt ( ) { fStartPos = - ; fEndPos = - ; String src = fDocument . get ( ) ; if ( src . length ( ) == ) { return false ; } Node root ; try { RubyParser parser = new RubyParser ( ) ; root = parser . parse ( src ) . getAST ( ) ; } catch ( SyntaxException e ) { return false ; } catch ( RuntimeException e ) { RubyPlugin . log ( e ) ; return false ; } Node spanning = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( root , fOffset , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( node instanceof IfNode ) { IfNode ifNode = ( IfNode ) node ; } return node instanceof ModuleNode || node instanceof SClassNode || node instanceof ClassNode || node instanceof DefnNode || node instanceof DefsNode || node instanceof BeginNode || node instanceof WhileNode || node instanceof CaseNode || node instanceof ForNode || node instanceof IfNode || node instanceof IterNode ; } } ) ; if ( spanning == null ) return false ; if ( ! isOnEnd ( spanning ) && ! isOnBeginning ( spanning ) ) { return false ; } if ( isOnEnd ( spanning ) ) { fAnchor = RIGHT ; } else { fAnchor = LEFT ; } fStartPos = spanning . getPosition ( ) . getStartOffset ( ) ; fEndPos = spanning . getPosition ( ) . getEndOffset ( ) ; if ( src . length ( ) == fEndPos ) { fEndPos -= ; } return true ; } private boolean isOnBeginning ( Node spanning ) { return ( fOffset >= spanning . getPosition ( ) . getStartOffset ( ) ) && ( fOffset <= spanning . getPosition ( ) . getStartOffset ( ) + getKeywordLength ( spanning ) ) ; } private boolean isOnEnd ( Node spanning ) { return ( fOffset >= spanning . getPosition ( ) . getEndOffset ( ) - ) && ( fOffset <= spanning . getPosition ( ) . getEndOffset ( ) ) ; } private int getKeywordLength ( Node spanning ) { if ( ( spanning instanceof ClassNode ) || ( spanning instanceof BeginNode ) || ( spanning instanceof WhileNode ) ) { return ; } if ( ( spanning instanceof DefnNode ) || ( spanning instanceof DefsNode ) || ( spanning instanceof ForNode ) ) { return ; } if ( spanning instanceof WhenNode ) { return ; } if ( spanning instanceof ModuleNode ) { return ; } if ( ( spanning instanceof IfNode ) || ( spanning instanceof IterNode ) ) { return ; } return ; } public int getAnchor ( ) { return fAnchor ; } public void dispose ( ) { clear ( ) ; fDocument = null ; } public void clear ( ) { } protected boolean matchPairsAt ( ) { int i ; int pairIndex1 = fPairs . length ; int pairIndex2 = fPairs . length ; fStartPos = - ; fEndPos = - ; try { char prevChar = fDocument . getChar ( Math . max ( fOffset - , ) ) ; for ( i = ; i < fPairs . length ; i = i + ) { if ( prevChar == fPairs [ i ] ) { fStartPos = fOffset - ; pairIndex1 = i ; } } for ( i = ; i < fPairs . length ; i = i + ) { if ( prevChar == fPairs [ i ] ) { fEndPos = fOffset - ; pairIndex2 = i ; } } if ( fEndPos > - ) { fAnchor = RIGHT ; fStartPos = searchForOpeningPeer ( fEndPos , fPairs [ pairIndex2 - ] , fPairs [ pairIndex2 ] , fDocument ) ; if ( fStartPos > - ) return true ; else fEndPos = - ; } else if ( fStartPos > - ) { fAnchor = LEFT ; fEndPos = searchForClosingPeer ( fStartPos , fPairs [ pairIndex1 ] , fPairs [ pairIndex1 + ] , fDocument ) ; if ( fEndPos > - ) return true ; else fStartPos = - ; } } catch ( BadLocationException x ) { } return false ; } protected int searchForClosingPeer ( int offset , char openingPeer , char closingPeer , IDocument document ) throws BadLocationException { RubyHeuristicScanner scanner = new RubyHeuristicScanner ( document , IRubyPartitions . RUBY_PARTITIONING , TextUtilities . getContentType ( document , IRubyPartitions . RUBY_PARTITIONING , offset , false ) ) ; return scanner . findClosingPeer ( offset + , openingPeer , closingPeer ) ; } protected int searchForOpeningPeer ( int offset , char openingPeer , char closingPeer , IDocument document ) throws BadLocationException { RubyHeuristicScanner scanner = new RubyHeuristicScanner ( document , IRubyPartitions . RUBY_PARTITIONING , TextUtilities . getContentType ( document , IRubyPartitions . RUBY_PARTITIONING , offset , false ) ) ; int peer = scanner . findOpeningPeer ( offset - , openingPeer , closingPeer ) ; if ( peer == RubyHeuristicScanner . NOT_FOUND ) return - ; return peer ; } } package org . rubypeople . rdt . internal . ui . text . folding ; import org . eclipse . osgi . util . NLS ; class FoldingMessages extends NLS { private static final String BUNDLE_NAME = FoldingMessages . class . getName ( ) ; private FoldingMessages ( ) { } public static String DefaultRubyFoldingPreferenceBlock_title ; public static String DefaultRubyFoldingPreferenceBlock_comments ; public static String DefaultRubyFoldingPreferenceBlock_innerTypes ; public static String DefaultRubyFoldingPreferenceBlock_methods ; public static String EmptyRubyFoldingPreferenceBlock_emptyCaption ; static { NLS . initializeMessages ( BUNDLE_NAME , FoldingMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . text . folding ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . Platform ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingStructureProvider ; public class RubyFoldingStructureProviderRegistry { private static final String EXTENSION_POINT = "" ; private Map fDescriptors ; public RubyFoldingStructureProviderRegistry ( ) { } public RubyFoldingStructureProviderDescriptor [ ] getFoldingProviderDescriptors ( ) { synchronized ( this ) { ensureRegistered ( ) ; return ( RubyFoldingStructureProviderDescriptor [ ] ) fDescriptors . values ( ) . toArray ( new RubyFoldingStructureProviderDescriptor [ fDescriptors . size ( ) ] ) ; } } public RubyFoldingStructureProviderDescriptor getFoldingProviderDescriptor ( String id ) { synchronized ( this ) { ensureRegistered ( ) ; return ( RubyFoldingStructureProviderDescriptor ) fDescriptors . get ( id ) ; } } public IRubyFoldingStructureProvider getCurrentFoldingProvider ( ) { String id = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getString ( PreferenceConstants . EDITOR_FOLDING_PROVIDER ) ; RubyFoldingStructureProviderDescriptor desc = getFoldingProviderDescriptor ( id ) ; if ( desc != null ) { try { return desc . createProvider ( ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } return null ; } private void ensureRegistered ( ) { if ( fDescriptors == null ) reloadExtensions ( ) ; } public void reloadExtensions ( ) { IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; Map map = new HashMap ( ) ; IConfigurationElement [ ] elements = registry . getConfigurationElementsFor ( RubyPlugin . getPluginId ( ) , EXTENSION_POINT ) ; for ( int i = ; i < elements . length ; i ++ ) { RubyFoldingStructureProviderDescriptor desc = new RubyFoldingStructureProviderDescriptor ( elements [ i ] ) ; map . put ( desc . getId ( ) , desc ) ; } synchronized ( this ) { fDescriptors = Collections . unmodifiableMap ( map ) ; } } } package org . rubypeople . rdt . internal . ui . text . folding ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . jface . preference . IPreferenceStore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . preferences . OverlayPreferenceStore ; import org . rubypeople . rdt . internal . ui . preferences . OverlayPreferenceStore . OverlayKey ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingPreferenceBlock ; public class DefaultRubyFoldingPreferenceBlock implements IRubyFoldingPreferenceBlock { private IPreferenceStore fStore ; private OverlayPreferenceStore fOverlayStore ; private OverlayKey [ ] fKeys ; private Map fCheckBoxes = new HashMap ( ) ; private SelectionListener fCheckBoxListener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { Button button = ( Button ) e . widget ; fOverlayStore . setValue ( ( String ) fCheckBoxes . get ( button ) , button . getSelection ( ) ) ; } } ; public DefaultRubyFoldingPreferenceBlock ( ) { fStore = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; fKeys = createKeys ( ) ; fOverlayStore = new OverlayPreferenceStore ( fStore , fKeys ) ; } private OverlayKey [ ] createKeys ( ) { ArrayList overlayKeys = new ArrayList ( ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_FOLDING_RDOC ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_FOLDING_INNERTYPES ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_FOLDING_METHODS ) ) ; return ( OverlayKey [ ] ) overlayKeys . toArray ( new OverlayKey [ overlayKeys . size ( ) ] ) ; } public Control createControl ( Composite composite ) { fOverlayStore . load ( ) ; fOverlayStore . start ( ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( , true ) ; layout . verticalSpacing = ; layout . marginWidth = ; inner . setLayout ( layout ) ; Label label = new Label ( inner , SWT . LEFT ) ; label . setText ( FoldingMessages . DefaultRubyFoldingPreferenceBlock_title ) ; addCheckBox ( inner , FoldingMessages . DefaultRubyFoldingPreferenceBlock_comments , PreferenceConstants . EDITOR_FOLDING_RDOC , ) ; addCheckBox ( inner , FoldingMessages . DefaultRubyFoldingPreferenceBlock_innerTypes , PreferenceConstants . EDITOR_FOLDING_INNERTYPES , ) ; addCheckBox ( inner , FoldingMessages . DefaultRubyFoldingPreferenceBlock_methods , PreferenceConstants . EDITOR_FOLDING_METHODS , ) ; return inner ; } private Button addCheckBox ( Composite parent , String label , String key , int indentation ) { Button checkBox = new Button ( parent , SWT . CHECK ) ; checkBox . setText ( label ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = indentation ; gd . horizontalSpan = ; gd . grabExcessVerticalSpace = false ; checkBox . setLayoutData ( gd ) ; checkBox . addSelectionListener ( fCheckBoxListener ) ; fCheckBoxes . put ( checkBox , key ) ; return checkBox ; } private void initializeFields ( ) { Iterator it = fCheckBoxes . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Button b = ( Button ) it . next ( ) ; String key = ( String ) fCheckBoxes . get ( b ) ; b . setSelection ( fOverlayStore . getBoolean ( key ) ) ; } } public void performOk ( ) { fOverlayStore . propagate ( ) ; } public void initialize ( ) { initializeFields ( ) ; } public void performDefaults ( ) { fOverlayStore . loadDefaults ( ) ; initializeFields ( ) ; } public void dispose ( ) { fOverlayStore . stop ( ) ; } } package org . rubypeople . rdt . internal . ui . text . folding ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . projection . IProjectionListener ; import org . eclipse . jface . text . source . projection . IProjectionPosition ; import org . eclipse . jface . text . source . projection . ProjectionAnnotation ; import org . eclipse . jface . text . source . projection . ProjectionAnnotationModel ; import org . eclipse . jface . text . source . projection . ProjectionViewer ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . RDocUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyAbstractEditor ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingStructureProvider ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingStructureProviderExtension ; public class DefaultRubyFoldingStructureProvider implements IProjectionListener , IRubyFoldingStructureProvider , IRubyFoldingStructureProviderExtension { private ITextEditor fEditor ; private ProjectionViewer fViewer ; private IDocument fCachedDocument ; private ProjectionAnnotationModel fCachedModel ; private boolean fAllowCollapsing ; private IRubyElement fInput ; private IElementChangedListener fElementListener ; private boolean fCollapseInnerTypes ; private boolean fCollapseRubydoc ; private boolean fCollapseMethods ; public void install ( ITextEditor editor , ProjectionViewer viewer ) { if ( editor instanceof RubyAbstractEditor ) { fEditor = editor ; fViewer = viewer ; fViewer . addProjectionListener ( this ) ; } } public void uninstall ( ) { if ( isInstalled ( ) ) { projectionDisabled ( ) ; fViewer . removeProjectionListener ( this ) ; fViewer = null ; fEditor = null ; } } protected boolean isInstalled ( ) { return fEditor != null ; } public void initialize ( ) { if ( ! isInstalled ( ) ) return ; initializePreferences ( ) ; try { IDocumentProvider provider = fEditor . getDocumentProvider ( ) ; fCachedDocument = provider . getDocument ( fEditor . getEditorInput ( ) ) ; fAllowCollapsing = true ; if ( fEditor instanceof RubyEditor ) { IWorkingCopyManager manager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; fInput = manager . getWorkingCopy ( fEditor . getEditorInput ( ) ) ; } if ( fInput != null ) { ProjectionAnnotationModel model = ( ProjectionAnnotationModel ) fEditor . getAdapter ( ProjectionAnnotationModel . class ) ; if ( model != null ) { fCachedModel = model ; if ( fInput instanceof IRubyScript ) { IRubyScript unit = ( IRubyScript ) fInput ; synchronized ( unit ) { try { unit . reconcile ( ) ; } catch ( RubyModelException e ) { } } } Map < RubyProjectionAnnotation , Position > additions = computeAdditions ( ( IParent ) fInput ) ; List removals = new LinkedList ( ) ; Iterator existing = model . getAnnotationIterator ( ) ; while ( existing . hasNext ( ) ) removals . add ( existing . next ( ) ) ; model . replaceAnnotations ( ( Annotation [ ] ) removals . toArray ( new Annotation [ removals . size ( ) ] ) , additions ) ; } } } finally { fCachedDocument = null ; fAllowCollapsing = false ; fCachedModel = null ; } } private Map < RubyProjectionAnnotation , Position > computeAdditions ( IParent parent ) { Map < RubyProjectionAnnotation , Position > map = new HashMap < RubyProjectionAnnotation , Position > ( ) ; try { computeAdditions ( parent . getChildren ( ) , map ) ; } catch ( RubyModelException x ) { RubyPlugin . log ( x ) ; } return map ; } private void computeAdditions ( IRubyElement [ ] elements , Map < RubyProjectionAnnotation , Position > map ) throws RubyModelException { for ( int i = ; i < elements . length ; i ++ ) { IRubyElement element = elements [ i ] ; computeAdditions ( element , map ) ; if ( element instanceof IParent ) { IParent parent = ( IParent ) element ; computeAdditions ( parent . getChildren ( ) , map ) ; } } } private void computeAdditions ( IRubyElement element , Map < RubyProjectionAnnotation , Position > map ) { boolean createProjection = false ; boolean collapse = false ; switch ( element . getElementType ( ) ) { case IRubyElement . TYPE : collapse = fAllowCollapsing && fCollapseInnerTypes && isInnerType ( ( IType ) element ) ; createProjection = true ; break ; case IRubyElement . METHOD : collapse = fAllowCollapsing && fCollapseMethods ; createProjection = true ; break ; case IRubyElement . BLOCK : collapse = false ; createProjection = true ; break ; } if ( createProjection ) { IRegion [ ] regions = computeProjectionRanges ( element ) ; if ( regions != null ) { for ( int i = ; i < regions . length - ; i ++ ) { Position position = createProjectionPosition ( regions [ i ] ) ; if ( position != null ) map . put ( new RubyProjectionAnnotation ( element , fAllowCollapsing && fCollapseRubydoc , true ) , position ) ; } Position position = createProjectionPosition ( regions [ regions . length - ] ) ; if ( position != null ) map . put ( new RubyProjectionAnnotation ( element , collapse , false ) , position ) ; } } } private void initializePreferences ( ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; fCollapseInnerTypes = store . getBoolean ( PreferenceConstants . EDITOR_FOLDING_INNERTYPES ) ; fCollapseRubydoc = store . getBoolean ( PreferenceConstants . EDITOR_FOLDING_RDOC ) ; fCollapseMethods = store . getBoolean ( PreferenceConstants . EDITOR_FOLDING_METHODS ) ; } private boolean isInnerType ( IType type ) { IRubyElement parent = type . getParent ( ) ; if ( parent != null ) { int parentType = parent . getElementType ( ) ; return ( parentType != IRubyElement . SCRIPT ) ; } return false ; } private IRegion [ ] computeProjectionRanges ( IRubyElement element ) { try { if ( element instanceof ISourceReference ) { ISourceReference reference = ( ISourceReference ) element ; ISourceRange range = reference . getSourceRange ( ) ; String contents = reference . getSource ( ) ; if ( contents == null ) return null ; List < IRegion > regions = new ArrayList < IRegion > ( ) ; int shift = range . getOffset ( ) ; int start = shift ; IRegion region = null ; if ( element instanceof IMember ) region = RDocUtil . getDocumentationRegion ( ( IMember ) element ) ; if ( region != null ) regions . add ( region ) ; regions . add ( new Region ( start , range . getOffset ( ) + range . getLength ( ) - start ) ) ; if ( regions . size ( ) > ) { IRegion [ ] result = new IRegion [ regions . size ( ) ] ; regions . toArray ( result ) ; return result ; } } } catch ( RubyModelException e ) { } return null ; } private Position createProjectionPosition ( IRegion region ) { if ( fCachedDocument == null ) return null ; try { int start = fCachedDocument . getLineOfOffset ( region . getOffset ( ) ) ; int end = fCachedDocument . getLineOfOffset ( region . getOffset ( ) + region . getLength ( ) ) ; if ( start != end ) { int offset = fCachedDocument . getLineOffset ( start ) ; int endOffset = - ; if ( ( end + ) == fCachedDocument . getNumberOfLines ( ) ) { endOffset = fCachedDocument . getLength ( ) ; } else { endOffset = fCachedDocument . getLineOffset ( end + ) ; } return new Position ( offset , endOffset - offset ) ; } } catch ( BadLocationException x ) { } return null ; } public void projectionEnabled ( ) { projectionDisabled ( ) ; if ( fEditor instanceof RubyAbstractEditor ) { initialize ( ) ; fElementListener = new ElementChangedListener ( ) ; RubyCore . addElementChangedListener ( fElementListener ) ; } } public void projectionDisabled ( ) { fCachedDocument = null ; if ( fElementListener != null ) { RubyCore . removeElementChangedListener ( fElementListener ) ; fElementListener = null ; } } protected void processDelta ( IRubyElementDelta delta ) { if ( ! isInstalled ( ) ) return ; if ( ( delta . getFlags ( ) & ( IRubyElementDelta . F_CONTENT | IRubyElementDelta . F_CHILDREN ) ) == ) return ; ProjectionAnnotationModel model = ( ProjectionAnnotationModel ) fEditor . getAdapter ( ProjectionAnnotationModel . class ) ; if ( model == null ) return ; try { IDocumentProvider provider = fEditor . getDocumentProvider ( ) ; fCachedDocument = provider . getDocument ( fEditor . getEditorInput ( ) ) ; fCachedModel = model ; fAllowCollapsing = false ; Map additions = new HashMap ( ) ; List deletions = new ArrayList ( ) ; List updates = new ArrayList ( ) ; Map updated = computeAdditions ( ( IParent ) fInput ) ; Map previous = createAnnotationMap ( model ) ; Iterator e = updated . keySet ( ) . iterator ( ) ; while ( e . hasNext ( ) ) { RubyProjectionAnnotation newAnnotation = ( RubyProjectionAnnotation ) e . next ( ) ; IRubyElement element = newAnnotation . getElement ( ) ; Position newPosition = ( Position ) updated . get ( newAnnotation ) ; List annotations = ( List ) previous . get ( element ) ; if ( annotations == null ) { additions . put ( newAnnotation , newPosition ) ; } else { Iterator x = annotations . iterator ( ) ; boolean matched = false ; while ( x . hasNext ( ) ) { Tuple tuple = ( Tuple ) x . next ( ) ; RubyProjectionAnnotation existingAnnotation = tuple . annotation ; Position existingPosition = tuple . position ; if ( newAnnotation . isComment ( ) == existingAnnotation . isComment ( ) ) { if ( existingPosition != null && ( ! newPosition . equals ( existingPosition ) ) ) { existingPosition . setOffset ( newPosition . getOffset ( ) ) ; existingPosition . setLength ( newPosition . getLength ( ) ) ; updates . add ( existingAnnotation ) ; } matched = true ; x . remove ( ) ; break ; } } if ( ! matched ) additions . put ( newAnnotation , newPosition ) ; if ( annotations . isEmpty ( ) ) previous . remove ( element ) ; } } e = previous . values ( ) . iterator ( ) ; while ( e . hasNext ( ) ) { List list = ( List ) e . next ( ) ; int size = list . size ( ) ; for ( int i = ; i < size ; i ++ ) deletions . add ( ( ( Tuple ) list . get ( i ) ) . annotation ) ; } match ( deletions , additions , updates ) ; Annotation [ ] removals = new Annotation [ deletions . size ( ) ] ; deletions . toArray ( removals ) ; Annotation [ ] changes = new Annotation [ updates . size ( ) ] ; updates . toArray ( changes ) ; model . modifyAnnotations ( removals , additions , changes ) ; } finally { fCachedDocument = null ; fAllowCollapsing = true ; fCachedModel = null ; } } private Map createAnnotationMap ( IAnnotationModel model ) { Map map = new HashMap ( ) ; Iterator e = model . getAnnotationIterator ( ) ; while ( e . hasNext ( ) ) { Object annotation = e . next ( ) ; if ( annotation instanceof RubyProjectionAnnotation ) { RubyProjectionAnnotation ruby = ( RubyProjectionAnnotation ) annotation ; Position position = model . getPosition ( ruby ) ; Assert . isNotNull ( position ) ; List list = ( List ) map . get ( ruby . getElement ( ) ) ; if ( list == null ) { list = new ArrayList ( ) ; map . put ( ruby . getElement ( ) , list ) ; } list . add ( new Tuple ( ruby , position ) ) ; } } Comparator comparator = new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { return ( ( Tuple ) o1 ) . position . getOffset ( ) - ( ( Tuple ) o2 ) . position . getOffset ( ) ; } } ; for ( Iterator it = map . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { List list = ( List ) it . next ( ) ; Collections . sort ( list , comparator ) ; } return map ; } private void match ( List deletions , Map additions , List changes ) { if ( deletions . isEmpty ( ) || ( additions . isEmpty ( ) && changes . isEmpty ( ) ) ) return ; List newDeletions = new ArrayList ( ) ; List newChanges = new ArrayList ( ) ; Iterator deletionIterator = deletions . iterator ( ) ; while ( deletionIterator . hasNext ( ) ) { RubyProjectionAnnotation deleted = ( RubyProjectionAnnotation ) deletionIterator . next ( ) ; if ( fCachedModel == null ) continue ; Position deletedPosition = fCachedModel . getPosition ( deleted ) ; if ( deletedPosition == null ) continue ; Tuple deletedTuple = new Tuple ( deleted , deletedPosition ) ; Tuple match = findMatch ( deletedTuple , changes , null ) ; boolean addToDeletions = true ; if ( match == null ) { match = findMatch ( deletedTuple , additions . keySet ( ) , additions ) ; addToDeletions = false ; } if ( match != null ) { IRubyElement element = match . annotation . getElement ( ) ; deleted . setElement ( element ) ; deletedPosition . setLength ( match . position . getLength ( ) ) ; if ( deletedPosition instanceof RubyElementPosition && element instanceof IMember ) { RubyElementPosition jep = ( RubyElementPosition ) deletedPosition ; jep . setMember ( ( IMember ) element ) ; } deletionIterator . remove ( ) ; newChanges . add ( deleted ) ; if ( addToDeletions ) newDeletions . add ( match . annotation ) ; } } deletions . addAll ( newDeletions ) ; changes . addAll ( newChanges ) ; } private Tuple findMatch ( Tuple tuple , Collection annotations , Map positionMap ) { Iterator it = annotations . iterator ( ) ; while ( it . hasNext ( ) ) { RubyProjectionAnnotation annotation = ( RubyProjectionAnnotation ) it . next ( ) ; if ( tuple . annotation . isComment ( ) == annotation . isComment ( ) ) { Position position = positionMap == null ? fCachedModel . getPosition ( annotation ) : ( Position ) positionMap . get ( annotation ) ; if ( position == null ) continue ; if ( tuple . position . getOffset ( ) == position . getOffset ( ) ) { it . remove ( ) ; return new Tuple ( annotation , position ) ; } } } return null ; } private static final class Tuple { RubyProjectionAnnotation annotation ; Position position ; Tuple ( RubyProjectionAnnotation annotation , Position position ) { this . annotation = annotation ; this . position = position ; } } private class ElementChangedListener implements IElementChangedListener { public void elementChanged ( ElementChangedEvent e ) { IRubyElementDelta delta = findElement ( fInput , e . getDelta ( ) ) ; if ( delta != null ) { if ( delta . getRubyScriptAST ( ) == null ) return ; processDelta ( delta ) ; } } private IRubyElementDelta findElement ( IRubyElement target , IRubyElementDelta delta ) { if ( delta == null || target == null ) return null ; IRubyElement element = delta . getElement ( ) ; if ( element . getElementType ( ) > IRubyElement . SCRIPT ) return null ; if ( target . equals ( element ) ) return delta ; IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { IRubyElementDelta d = findElement ( target , children [ i ] ) ; if ( d != null ) return d ; } return null ; } } private static class RubyProjectionAnnotation extends ProjectionAnnotation { private IRubyElement fRubyElement ; private boolean fIsComment ; public RubyProjectionAnnotation ( IRubyElement element , boolean isCollapsed , boolean isComment ) { super ( isCollapsed ) ; fRubyElement = element ; fIsComment = isComment ; } public IRubyElement getElement ( ) { return fRubyElement ; } public void setElement ( IRubyElement element ) { fRubyElement = element ; } public boolean isComment ( ) { return fIsComment ; } public void setIsComment ( boolean isComment ) { fIsComment = isComment ; } } private static final class RubyElementPosition extends Position implements IProjectionPosition { private IMember fMember ; public RubyElementPosition ( int offset , int length , IMember member ) { super ( offset , length ) ; Assert . isNotNull ( member ) ; fMember = member ; } public void setMember ( IMember member ) { Assert . isNotNull ( member ) ; fMember = member ; } public IRegion [ ] computeProjectionRegions ( IDocument document ) throws BadLocationException { int nameStart = offset ; try { ISourceRange nameRange = fMember . getNameRange ( ) ; if ( nameRange != null ) nameStart = nameRange . getOffset ( ) ; } catch ( RubyModelException e ) { } int firstLine = document . getLineOfOffset ( offset ) ; int captionLine = document . getLineOfOffset ( nameStart ) ; int lastLine = document . getLineOfOffset ( offset + length ) ; if ( captionLine < firstLine ) captionLine = firstLine ; if ( captionLine > lastLine ) captionLine = lastLine ; IRegion preRegion ; if ( firstLine < captionLine ) { int preOffset = document . getLineOffset ( firstLine ) ; IRegion preEndLineInfo = document . getLineInformation ( captionLine ) ; int preEnd = preEndLineInfo . getOffset ( ) ; preRegion = new Region ( preOffset , preEnd - preOffset ) ; } else { preRegion = null ; } if ( captionLine < lastLine ) { int postOffset = document . getLineOffset ( captionLine + ) ; IRegion postRegion = new Region ( postOffset , offset + length - postOffset ) ; if ( preRegion == null ) return new IRegion [ ] { postRegion } ; return new IRegion [ ] { preRegion , postRegion } ; } if ( preRegion != null ) return new IRegion [ ] { preRegion } ; return null ; } public int computeCaptionOffset ( IDocument document ) throws BadLocationException { int nameStart = offset ; try { ISourceRange nameRange = fMember . getNameRange ( ) ; if ( nameRange != null ) nameStart = nameRange . getOffset ( ) ; } catch ( RubyModelException e ) { } return nameStart - offset ; } } private static interface Filter { boolean match ( RubyProjectionAnnotation annotation ) ; } private static final class RubyElementSetFilter implements Filter { private final Set < IRubyElement > fSet ; private final boolean fMatchCollapsed ; private RubyElementSetFilter ( Set < IRubyElement > set , boolean matchCollapsed ) { fSet = set ; fMatchCollapsed = matchCollapsed ; } public boolean match ( RubyProjectionAnnotation annotation ) { boolean stateMatch = fMatchCollapsed == annotation . isCollapsed ( ) ; if ( stateMatch && ! annotation . isComment ( ) && ! annotation . isMarkedDeleted ( ) ) { IRubyElement element = annotation . getElement ( ) ; if ( fSet . contains ( element ) ) { return true ; } } return false ; } } private final Filter fMemberFilter = new Filter ( ) { public boolean match ( RubyProjectionAnnotation annotation ) { if ( ! annotation . isCollapsed ( ) && ! annotation . isComment ( ) && ! annotation . isMarkedDeleted ( ) ) { IRubyElement element = annotation . getElement ( ) ; if ( element instanceof IMember ) { if ( element . getElementType ( ) != IRubyElement . TYPE || ( ( IMember ) element ) . getDeclaringType ( ) != null ) { return true ; } } } return false ; } } ; private final Filter fCommentFilter = new Filter ( ) { public boolean match ( RubyProjectionAnnotation annotation ) { if ( ! annotation . isCollapsed ( ) && annotation . isComment ( ) && ! annotation . isMarkedDeleted ( ) ) { return true ; } return false ; } } ; public void collapseMembers ( ) { modifyFiltered ( fMemberFilter , false ) ; } public void collapseComments ( ) { modifyFiltered ( fCommentFilter , false ) ; } public void collapseElements ( IRubyElement [ ] elements ) { Set < IRubyElement > set = new HashSet < IRubyElement > ( Arrays . asList ( elements ) ) ; modifyFiltered ( new RubyElementSetFilter ( set , false ) , false ) ; } public void expandElements ( IRubyElement [ ] elements ) { Set < IRubyElement > set = new HashSet < IRubyElement > ( Arrays . asList ( elements ) ) ; modifyFiltered ( new RubyElementSetFilter ( set , true ) , true ) ; } private void modifyFiltered ( Filter filter , boolean expand ) { if ( ! isInstalled ( ) ) return ; ProjectionAnnotationModel model = ( ProjectionAnnotationModel ) fEditor . getAdapter ( ProjectionAnnotationModel . class ) ; if ( model == null ) return ; List modified = new ArrayList ( ) ; Iterator iter = model . getAnnotationIterator ( ) ; while ( iter . hasNext ( ) ) { Object annotation = iter . next ( ) ; if ( annotation instanceof RubyProjectionAnnotation ) { RubyProjectionAnnotation ruby = ( RubyProjectionAnnotation ) annotation ; if ( filter . match ( ruby ) ) { if ( expand ) ruby . markExpanded ( ) ; else ruby . markCollapsed ( ) ; modified . add ( ruby ) ; } } } model . modifyAnnotations ( null , null , ( Annotation [ ] ) modified . toArray ( new Annotation [ modified . size ( ) ] ) ) ; } } package org . rubypeople . rdt . internal . ui . text . folding ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingPreferenceBlock ; class EmptyRubyFoldingPreferenceBlock implements IRubyFoldingPreferenceBlock { public Control createControl ( Composite composite ) { Composite inner = new Composite ( composite , SWT . NONE ) ; inner . setLayout ( new GridLayout ( , false ) ) ; Label label = new Label ( inner , SWT . CENTER ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; gd . widthHint = ; label . setLayoutData ( gd ) ; label = new Label ( inner , SWT . CENTER ) ; label . setText ( FoldingMessages . EmptyRubyFoldingPreferenceBlock_emptyCaption ) ; gd = new GridData ( GridData . CENTER ) ; label . setLayoutData ( gd ) ; label = new Label ( inner , SWT . CENTER ) ; gd = new GridData ( GridData . FILL_BOTH ) ; gd . widthHint = ; label . setLayoutData ( gd ) ; return inner ; } public void initialize ( ) { } public void performOk ( ) { } public void performDefaults ( ) { } public void dispose ( ) { } } package org . rubypeople . rdt . internal . ui . text . folding ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . jface . text . Assert ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingPreferenceBlock ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingStructureProvider ; public final class RubyFoldingStructureProviderDescriptor { private static final String PREFERENCES_CLASS = "" ; private static final String CLASS = "" ; private static final String NAME = "" ; private static final String ID = "" ; private String fId ; private String fName ; private String fClass ; private boolean fHasPreferences ; private IConfigurationElement fElement ; RubyFoldingStructureProviderDescriptor ( IConfigurationElement element ) { fElement = element ; fId = element . getAttributeAsIs ( ID ) ; Assert . isLegal ( fId != null ) ; fName = element . getAttribute ( NAME ) ; if ( fName == null ) fName = fId ; fClass = element . getAttributeAsIs ( CLASS ) ; Assert . isLegal ( fClass != null ) ; if ( element . getAttributeAsIs ( PREFERENCES_CLASS ) == null ) fHasPreferences = false ; else fHasPreferences = true ; } public IRubyFoldingStructureProvider createProvider ( ) throws CoreException { IRubyFoldingStructureProvider prov = ( IRubyFoldingStructureProvider ) fElement . createExecutableExtension ( CLASS ) ; return prov ; } public IRubyFoldingPreferenceBlock createPreferences ( ) throws CoreException { if ( fHasPreferences ) { IRubyFoldingPreferenceBlock prefs = ( IRubyFoldingPreferenceBlock ) fElement . createExecutableExtension ( PREFERENCES_CLASS ) ; return prefs ; } return new EmptyRubyFoldingPreferenceBlock ( ) ; } public String getId ( ) { return fId ; } public String getName ( ) { return fName ; } } package org . rubypeople . rdt . internal . ui . text ; import com . ibm . icu . text . BreakIterator ; import java . text . CharacterIterator ; import org . eclipse . jface . text . Assert ; public class RubyBreakIterator extends BreakIterator { protected static abstract class Run { protected int length ; public Run ( ) { init ( ) ; } protected boolean consume ( char ch ) { if ( isValid ( ch ) ) { length ++ ; return true ; } return false ; } protected abstract boolean isValid ( char ch ) ; protected void init ( ) { length = ; } } static final class Whitespace extends Run { protected boolean isValid ( char ch ) { return Character . isWhitespace ( ch ) && ch != '' && ch != '' ; } } static final class LineDelimiter extends Run { private char fState ; private static final char INIT = '' ; private static final char EXIT = '' ; protected void init ( ) { super . init ( ) ; fState = INIT ; } protected boolean consume ( char ch ) { if ( ! isValid ( ch ) || fState == EXIT ) return false ; if ( fState == INIT ) { fState = ch ; length ++ ; return true ; } else if ( fState != ch ) { fState = EXIT ; length ++ ; return true ; } else { return false ; } } protected boolean isValid ( char ch ) { return ch == '' || ch == '' ; } } static final class Identifier extends Run { protected boolean isValid ( char ch ) { return Character . isJavaIdentifierPart ( ch ) ; } } static final class CamelCaseIdentifier extends Run { private static final int S_INIT = ; private static final int S_LOWER = ; private static final int S_ONE_CAP = ; private static final int S_ALL_CAPS = ; private static final int S_EXIT = ; private static final int S_EXIT_MINUS_ONE = ; private static final int K_INVALID = ; private static final int K_LOWER = ; private static final int K_UPPER = ; private static final int K_OTHER = ; private int fState ; private final static int [ ] [ ] MATRIX = new int [ ] [ ] { { S_EXIT , S_LOWER , S_ONE_CAP , S_LOWER } , { S_EXIT , S_LOWER , S_EXIT , S_LOWER } , { S_EXIT , S_LOWER , S_ALL_CAPS , S_LOWER } , { S_EXIT , S_EXIT_MINUS_ONE , S_ALL_CAPS , S_LOWER } , } ; protected void init ( ) { super . init ( ) ; fState = S_INIT ; } protected boolean consume ( char ch ) { int kind = getKind ( ch ) ; fState = MATRIX [ fState ] [ kind ] ; switch ( fState ) { case S_LOWER : case S_ONE_CAP : case S_ALL_CAPS : length ++ ; return true ; case S_EXIT : return false ; case S_EXIT_MINUS_ONE : length -- ; return false ; default : Assert . isTrue ( false ) ; return false ; } } private int getKind ( char ch ) { if ( Character . isUpperCase ( ch ) ) return K_UPPER ; if ( Character . isLowerCase ( ch ) ) return K_LOWER ; if ( Character . isJavaIdentifierPart ( ch ) ) return K_OTHER ; return K_INVALID ; } protected boolean isValid ( char ch ) { return Character . isJavaIdentifierPart ( ch ) ; } } static final class Other extends Run { protected boolean isValid ( char ch ) { return ! Character . isWhitespace ( ch ) && ! Character . isJavaIdentifierPart ( ch ) ; } } private static final Run WHITESPACE = new Whitespace ( ) ; private static final Run DELIMITER = new LineDelimiter ( ) ; private static final Run CAMELCASE = new CamelCaseIdentifier ( ) ; private static final Run OTHER = new Other ( ) ; protected final BreakIterator fIterator ; protected CharSequence fText ; private int fIndex ; public RubyBreakIterator ( ) { fIterator = BreakIterator . getWordInstance ( ) ; fIndex = fIterator . current ( ) ; } public int current ( ) { return fIndex ; } public int first ( ) { fIndex = fIterator . first ( ) ; return fIndex ; } public int following ( int offset ) { if ( offset == getText ( ) . getEndIndex ( ) ) return DONE ; int next = fIterator . following ( offset ) ; if ( next == DONE ) return DONE ; Run run = consumeRun ( offset ) ; return offset + run . length ; } private Run consumeRun ( int offset ) { char ch = fText . charAt ( offset ) ; int length = fText . length ( ) ; Run run = getRun ( ch ) ; while ( run . consume ( ch ) && offset < length - ) { offset ++ ; ch = fText . charAt ( offset ) ; } return run ; } private Run getRun ( char ch ) { Run run ; if ( WHITESPACE . isValid ( ch ) ) run = WHITESPACE ; else if ( DELIMITER . isValid ( ch ) ) run = DELIMITER ; else if ( CAMELCASE . isValid ( ch ) ) run = CAMELCASE ; else if ( OTHER . isValid ( ch ) ) run = OTHER ; else { Assert . isTrue ( false ) ; return null ; } run . init ( ) ; return run ; } public CharacterIterator getText ( ) { return fIterator . getText ( ) ; } public boolean isBoundary ( int offset ) { if ( offset == getText ( ) . getBeginIndex ( ) ) return true ; else return following ( offset - ) == offset ; } public int last ( ) { fIndex = fIterator . last ( ) ; return fIndex ; } public int next ( ) { fIndex = following ( fIndex ) ; return fIndex ; } public int next ( int n ) { return fIterator . next ( n ) ; } public int preceding ( int offset ) { if ( offset == getText ( ) . getBeginIndex ( ) ) return DONE ; if ( isBoundary ( offset - ) ) return offset - ; int previous = offset - ; do { previous = fIterator . preceding ( previous ) ; } while ( ! isBoundary ( previous ) ) ; int last = DONE ; while ( previous < offset ) { last = previous ; previous = following ( previous ) ; } return last ; } public int previous ( ) { fIndex = preceding ( fIndex ) ; return fIndex ; } public void setText ( String newText ) { setText ( ( CharSequence ) newText ) ; } public void setText ( CharSequence newText ) { fText = newText ; fIterator . setText ( new SequenceCharacterIterator ( newText ) ) ; first ( ) ; } public void setText ( CharacterIterator newText ) { if ( newText instanceof CharSequence ) { fText = ( CharSequence ) newText ; fIterator . setText ( newText ) ; first ( ) ; } else { throw new UnsupportedOperationException ( "" ) ; } } } package org . rubypeople . rdt . internal . ui . text ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . PopupDialog ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlExtension ; import org . eclipse . jface . text . IInformationControlExtension2 ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . MouseAdapter ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . events . MouseMoveListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . FontMetrics ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . TreeItem ; import org . eclipse . ui . IKeyBindingService ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . commands . ActionHandler ; import org . eclipse . ui . commands . HandlerSubmission ; import org . eclipse . ui . commands . ICommand ; import org . eclipse . ui . commands . ICommandManager ; import org . eclipse . ui . commands . IKeySequenceBinding ; import org . eclipse . ui . commands . Priority ; import org . eclipse . ui . contexts . IWorkbenchContextSupport ; import org . eclipse . ui . keys . KeySequence ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . OpenActionUtil ; import org . rubypeople . rdt . internal . ui . util . StringMatcher ; import org . rubypeople . rdt . ui . actions . CustomFiltersActionGroup ; public abstract class AbstractInformationControl extends PopupDialog implements IInformationControl , IInformationControlExtension , IInformationControlExtension2 , DisposeListener { protected class NamePatternFilter extends ViewerFilter { public NamePatternFilter ( ) { } public boolean select ( Viewer viewer , Object parentElement , Object element ) { StringMatcher matcher = getMatcher ( ) ; if ( matcher == null || ! ( viewer instanceof TreeViewer ) ) return true ; TreeViewer treeViewer = ( TreeViewer ) viewer ; String matchName = ( ( ILabelProvider ) treeViewer . getLabelProvider ( ) ) . getText ( element ) ; if ( matchName != null && matcher . match ( matchName ) ) return true ; return hasUnfilteredChild ( treeViewer , element ) ; } private boolean hasUnfilteredChild ( TreeViewer viewer , Object element ) { if ( element instanceof IParent ) { Object [ ] children = ( ( ITreeContentProvider ) viewer . getContentProvider ( ) ) . getChildren ( element ) ; for ( int i = ; i < children . length ; i ++ ) if ( select ( viewer , element , children [ i ] ) ) return true ; } return false ; } } private Text fFilterText ; private TreeViewer fTreeViewer ; protected StringMatcher fStringMatcher ; private ICommand fInvokingCommand ; private KeySequence [ ] fInvokingCommandKeySequences ; private Composite fViewMenuButtonComposite ; private CustomFiltersActionGroup fCustomFiltersActionGroup ; private IKeyBindingService fKeyBindingService ; private String [ ] fKeyBindingScopes ; private IAction fShowViewMenuAction ; private HandlerSubmission fShowViewMenuHandlerSubmission ; private int fTreeStyle ; public AbstractInformationControl ( Shell parent , int shellStyle , int treeStyle , String invokingCommandId , boolean showStatusField ) { super ( parent , shellStyle , true , true , true , true , null , null ) ; if ( invokingCommandId != null ) { ICommandManager commandManager = PlatformUI . getWorkbench ( ) . getCommandSupport ( ) . getCommandManager ( ) ; fInvokingCommand = commandManager . getCommand ( invokingCommandId ) ; if ( fInvokingCommand != null && ! fInvokingCommand . isDefined ( ) ) fInvokingCommand = null ; else getInvokingCommandKeySequences ( ) ; } fTreeStyle = treeStyle ; if ( hasHeader ( ) ) setTitleText ( "" ) ; setInfoText ( "" ) ; create ( ) ; setInfoText ( getStatusFieldText ( ) ) ; } protected Control createDialogArea ( Composite parent ) { fTreeViewer = createTreeViewer ( parent , fTreeStyle ) ; fCustomFiltersActionGroup = new CustomFiltersActionGroup ( getId ( ) , fTreeViewer ) ; final Tree tree = fTreeViewer . getTree ( ) ; tree . addKeyListener ( new KeyListener ( ) { public void keyPressed ( KeyEvent e ) { if ( e . character == ) dispose ( ) ; } public void keyReleased ( KeyEvent e ) { } } ) ; tree . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { } public void widgetDefaultSelected ( SelectionEvent e ) { gotoSelectedElement ( ) ; } } ) ; tree . addMouseMoveListener ( new MouseMoveListener ( ) { TreeItem fLastItem = null ; public void mouseMove ( MouseEvent e ) { if ( tree . equals ( e . getSource ( ) ) ) { Object o = tree . getItem ( new Point ( e . x , e . y ) ) ; if ( o instanceof TreeItem ) { if ( ! o . equals ( fLastItem ) ) { fLastItem = ( TreeItem ) o ; tree . setSelection ( new TreeItem [ ] { fLastItem } ) ; } else if ( e . y < tree . getItemHeight ( ) / ) { Point p = tree . toDisplay ( e . x , e . y ) ; Item item = fTreeViewer . scrollUp ( p . x , p . y ) ; if ( item instanceof TreeItem ) { fLastItem = ( TreeItem ) item ; tree . setSelection ( new TreeItem [ ] { fLastItem } ) ; } } else if ( e . y > tree . getBounds ( ) . height - tree . getItemHeight ( ) / ) { Point p = tree . toDisplay ( e . x , e . y ) ; Item item = fTreeViewer . scrollDown ( p . x , p . y ) ; if ( item instanceof TreeItem ) { fLastItem = ( TreeItem ) item ; tree . setSelection ( new TreeItem [ ] { fLastItem } ) ; } } } } } } ) ; tree . addMouseListener ( new MouseAdapter ( ) { public void mouseUp ( MouseEvent e ) { if ( tree . getSelectionCount ( ) < ) return ; if ( e . button != ) return ; if ( tree . equals ( e . getSource ( ) ) ) { Object o = tree . getItem ( new Point ( e . x , e . y ) ) ; TreeItem selection = tree . getSelection ( ) [ ] ; if ( selection . equals ( o ) ) gotoSelectedElement ( ) ; } } } ) ; installFilter ( ) ; addDisposeListener ( this ) ; return fTreeViewer . getControl ( ) ; } public AbstractInformationControl ( Shell parent , int shellStyle , int treeStyle ) { this ( parent , shellStyle , treeStyle , null , false ) ; } protected abstract TreeViewer createTreeViewer ( Composite parent , int style ) ; protected abstract String getId ( ) ; protected TreeViewer getTreeViewer ( ) { return fTreeViewer ; } protected boolean hasHeader ( ) { return false ; } protected Text getFilterText ( ) { return fFilterText ; } protected Text createFilterText ( Composite parent ) { fFilterText = new Text ( parent , SWT . NONE ) ; GridData data = new GridData ( GridData . FILL_HORIZONTAL ) ; GC gc = new GC ( parent ) ; gc . setFont ( parent . getFont ( ) ) ; FontMetrics fontMetrics = gc . getFontMetrics ( ) ; gc . dispose ( ) ; data . heightHint = Dialog . convertHeightInCharsToPixels ( fontMetrics , ) ; data . horizontalAlignment = GridData . FILL ; data . verticalAlignment = GridData . CENTER ; fFilterText . setLayoutData ( data ) ; fFilterText . addKeyListener ( new KeyListener ( ) { public void keyPressed ( KeyEvent e ) { if ( e . keyCode == ) gotoSelectedElement ( ) ; if ( e . keyCode == SWT . ARROW_DOWN ) fTreeViewer . getTree ( ) . setFocus ( ) ; if ( e . keyCode == SWT . ARROW_UP ) fTreeViewer . getTree ( ) . setFocus ( ) ; if ( e . character == ) dispose ( ) ; } public void keyReleased ( KeyEvent e ) { } } ) ; return fFilterText ; } protected void createHorizontalSeparator ( Composite parent ) { Label separator = new Label ( parent , SWT . SEPARATOR | SWT . HORIZONTAL | SWT . LINE_DOT ) ; separator . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; } protected void updateStatusFieldText ( ) { setInfoText ( getStatusFieldText ( ) ) ; } protected void handleStatusFieldClicked ( ) { } protected String getStatusFieldText ( ) { return "" ; } private void installFilter ( ) { fFilterText . setText ( "" ) ; fFilterText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { String text = ( ( Text ) e . widget ) . getText ( ) ; int length = text . length ( ) ; if ( length > && text . charAt ( length - ) != '' ) { text = text + '' ; } setMatcherString ( text , true ) ; } } ) ; } protected void stringMatcherUpdated ( ) { fTreeViewer . getControl ( ) . setRedraw ( false ) ; fTreeViewer . refresh ( ) ; fTreeViewer . expandAll ( ) ; selectFirstMatch ( ) ; fTreeViewer . getControl ( ) . setRedraw ( true ) ; } protected void setMatcherString ( String pattern , boolean update ) { if ( pattern . length ( ) == ) { fStringMatcher = null ; } else { boolean ignoreCase = pattern . toLowerCase ( ) . equals ( pattern ) ; fStringMatcher = new StringMatcher ( pattern , ignoreCase , false ) ; } if ( update ) stringMatcherUpdated ( ) ; } protected StringMatcher getMatcher ( ) { return fStringMatcher ; } protected Object getSelectedElement ( ) { if ( fTreeViewer == null ) return null ; return ( ( IStructuredSelection ) fTreeViewer . getSelection ( ) ) . getFirstElement ( ) ; } private void gotoSelectedElement ( ) { Object selectedElement = getSelectedElement ( ) ; if ( selectedElement != null ) { try { dispose ( ) ; OpenActionUtil . open ( selectedElement , true ) ; } catch ( CoreException ex ) { RubyPlugin . log ( ex ) ; } } } protected void selectFirstMatch ( ) { Tree tree = fTreeViewer . getTree ( ) ; Object element = findElement ( tree . getItems ( ) ) ; if ( element != null ) fTreeViewer . setSelection ( new StructuredSelection ( element ) , true ) ; else fTreeViewer . setSelection ( StructuredSelection . EMPTY ) ; } private IRubyElement findElement ( TreeItem [ ] items ) { ILabelProvider labelProvider = ( ILabelProvider ) fTreeViewer . getLabelProvider ( ) ; for ( int i = ; i < items . length ; i ++ ) { IRubyElement element = ( IRubyElement ) items [ i ] . getData ( ) ; if ( fStringMatcher == null ) return element ; if ( element != null ) { String label = labelProvider . getText ( element ) ; if ( fStringMatcher . match ( label ) ) return element ; } element = findElement ( items [ i ] . getItems ( ) ) ; if ( element != null ) return element ; } return null ; } public void setInformation ( String information ) { } public abstract void setInput ( Object information ) ; protected void fillViewMenu ( IMenuManager viewMenu ) { fCustomFiltersActionGroup . fillViewMenu ( viewMenu ) ; } protected void fillDialogMenu ( IMenuManager dialogMenu ) { super . fillDialogMenu ( dialogMenu ) ; fillViewMenu ( dialogMenu ) ; } protected void inputChanged ( Object newInput , Object newSelection ) { fFilterText . setText ( "" ) ; fTreeViewer . setInput ( newInput ) ; if ( newSelection != null ) { fTreeViewer . setSelection ( new StructuredSelection ( newSelection ) ) ; } } public void setVisible ( boolean visible ) { if ( visible ) { addHandlerAndKeyBindingSupport ( ) ; open ( ) ; } else { removeHandlerAndKeyBindingSupport ( ) ; saveDialogBounds ( getShell ( ) ) ; getShell ( ) . setVisible ( false ) ; removeHandlerAndKeyBindingSupport ( ) ; } } public final void dispose ( ) { close ( ) ; } public void widgetDisposed ( DisposeEvent event ) { removeHandlerAndKeyBindingSupport ( ) ; fTreeViewer = null ; fFilterText = null ; fKeyBindingService = null ; } protected void addHandlerAndKeyBindingSupport ( ) { if ( fKeyBindingScopes == null && fKeyBindingService != null ) { fKeyBindingScopes = fKeyBindingService . getScopes ( ) ; fKeyBindingService . setScopes ( new String [ ] { IWorkbenchContextSupport . CONTEXT_ID_WINDOW } ) ; } if ( fShowViewMenuHandlerSubmission == null ) { fShowViewMenuHandlerSubmission = new HandlerSubmission ( null , getShell ( ) , null , fShowViewMenuAction . getActionDefinitionId ( ) , new ActionHandler ( fShowViewMenuAction ) , Priority . MEDIUM ) ; PlatformUI . getWorkbench ( ) . getCommandSupport ( ) . addHandlerSubmission ( fShowViewMenuHandlerSubmission ) ; } } protected void removeHandlerAndKeyBindingSupport ( ) { if ( fShowViewMenuHandlerSubmission != null ) PlatformUI . getWorkbench ( ) . getCommandSupport ( ) . removeHandlerSubmission ( fShowViewMenuHandlerSubmission ) ; if ( fKeyBindingService != null && fKeyBindingScopes != null ) { fKeyBindingService . setScopes ( fKeyBindingScopes ) ; fKeyBindingScopes = null ; } } public boolean hasContents ( ) { return fTreeViewer != null && fTreeViewer . getInput ( ) != null ; } public void setSizeConstraints ( int maxWidth , int maxHeight ) { } public Point computeSizeHint ( ) { return getShell ( ) . getSize ( ) ; } public void setLocation ( Point location ) { if ( ! getPersistBounds ( ) || getDialogSettings ( ) == null ) getShell ( ) . setLocation ( location ) ; } public void setSize ( int width , int height ) { getShell ( ) . setSize ( width , height ) ; } public void addDisposeListener ( DisposeListener listener ) { getShell ( ) . addDisposeListener ( listener ) ; } public void removeDisposeListener ( DisposeListener listener ) { getShell ( ) . removeDisposeListener ( listener ) ; } public void setForegroundColor ( Color foreground ) { applyForegroundColor ( foreground , getContents ( ) ) ; } public void setBackgroundColor ( Color background ) { applyBackgroundColor ( background , getContents ( ) ) ; } public boolean isFocusControl ( ) { return fTreeViewer . getControl ( ) . isFocusControl ( ) || fFilterText . isFocusControl ( ) ; } public void setFocus ( ) { getShell ( ) . forceFocus ( ) ; fFilterText . setFocus ( ) ; } public void addFocusListener ( FocusListener listener ) { getShell ( ) . addFocusListener ( listener ) ; } public void removeFocusListener ( FocusListener listener ) { getShell ( ) . removeFocusListener ( listener ) ; } final protected ICommand getInvokingCommand ( ) { return fInvokingCommand ; } final protected KeySequence [ ] getInvokingCommandKeySequences ( ) { if ( fInvokingCommandKeySequences == null ) { if ( getInvokingCommand ( ) != null ) { List list = getInvokingCommand ( ) . getKeySequenceBindings ( ) ; if ( ! list . isEmpty ( ) ) { fInvokingCommandKeySequences = new KeySequence [ list . size ( ) ] ; for ( int i = ; i < fInvokingCommandKeySequences . length ; i ++ ) { fInvokingCommandKeySequences [ i ] = ( ( IKeySequenceBinding ) list . get ( i ) ) . getKeySequence ( ) ; } return fInvokingCommandKeySequences ; } } } return fInvokingCommandKeySequences ; } protected IDialogSettings getDialogSettings ( ) { String sectionName = getId ( ) ; IDialogSettings settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( sectionName ) ; if ( settings == null ) settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( sectionName ) ; return settings ; } protected Control createTitleMenuArea ( Composite parent ) { fViewMenuButtonComposite = ( Composite ) super . createTitleMenuArea ( parent ) ; if ( hasHeader ( ) ) { fFilterText = createFilterText ( parent ) ; } IWorkbenchPart part = RubyPlugin . getActivePage ( ) . getActivePart ( ) ; IWorkbenchPartSite site = part . getSite ( ) ; fKeyBindingService = site . getKeyBindingService ( ) ; fShowViewMenuAction = new Action ( "" ) { public void run ( ) { showDialogMenu ( ) ; } } ; fShowViewMenuAction . setEnabled ( true ) ; fShowViewMenuAction . setActionDefinitionId ( "" ) ; addHandlerAndKeyBindingSupport ( ) ; return fViewMenuButtonComposite ; } protected Control createTitleControl ( Composite parent ) { if ( hasHeader ( ) ) { return super . createTitleControl ( parent ) ; } fFilterText = createFilterText ( parent ) ; return fFilterText ; } protected void setTabOrder ( Composite composite ) { if ( hasHeader ( ) ) { composite . setTabList ( new Control [ ] { fFilterText , fTreeViewer . getTree ( ) } ) ; } else { fViewMenuButtonComposite . setTabList ( new Control [ ] { fFilterText } ) ; composite . setTabList ( new Control [ ] { fViewMenuButtonComposite , fTreeViewer . getTree ( ) } ) ; } } } package org . rubypeople . rdt . internal . ui . text ; import java . io . IOException ; import java . io . PushbackReader ; import java . io . Reader ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . jface . text . TextPresentation ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; public class HTML2TextReader extends SubstitutionTextReader { private static final String EMPTY_STRING = "" ; private static final Map fgEntityLookup ; private static final Set fgTags ; static { fgTags = new HashSet ( ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgTags . add ( "" ) ; fgEntityLookup = new HashMap ( ) ; fgEntityLookup . put ( "" , "" ) ; fgEntityLookup . put ( "" , ">" ) ; fgEntityLookup . put ( "" , "" ) ; fgEntityLookup . put ( "" , "" ) ; fgEntityLookup . put ( "" , "" ) ; fgEntityLookup . put ( "" , "" ) ; fgEntityLookup . put ( "" , "" ) ; } private int fCounter = ; private TextPresentation fTextPresentation ; private int fBold = ; private int fStartOffset = - ; private boolean fInParagraph = false ; private boolean fIsPreformattedText = false ; public HTML2TextReader ( Reader reader , TextPresentation presentation ) { super ( new PushbackReader ( reader ) ) ; fTextPresentation = presentation ; } public int read ( ) throws IOException { int c = super . read ( ) ; if ( c != - ) ++ fCounter ; return c ; } protected void startBold ( ) { if ( fBold == ) fStartOffset = fCounter ; ++ fBold ; } protected void startPreformattedText ( ) { fIsPreformattedText = true ; setSkipWhitespace ( false ) ; } protected void stopPreformattedText ( ) { fIsPreformattedText = false ; setSkipWhitespace ( true ) ; } protected void stopBold ( ) { -- fBold ; if ( fBold == ) { if ( fTextPresentation != null ) { fTextPresentation . addStyleRange ( new StyleRange ( fStartOffset , fCounter - fStartOffset , null , null , SWT . BOLD ) ) ; } fStartOffset = - ; } } protected String computeSubstitution ( int c ) throws IOException { if ( c == '' ) return processHTMLTag ( ) ; else if ( c == '' ) return processEntity ( ) ; else if ( fIsPreformattedText ) return processPreformattedText ( c ) ; return null ; } private String html2Text ( String html ) { if ( html == null || html . length ( ) == ) return EMPTY_STRING ; String tag = html ; if ( '' == tag . charAt ( ) ) tag = tag . substring ( ) ; if ( ! fgTags . contains ( tag ) ) return EMPTY_STRING ; if ( "" . equals ( html ) ) { startPreformattedText ( ) ; return EMPTY_STRING ; } if ( "" . equals ( html ) ) { stopPreformattedText ( ) ; return EMPTY_STRING ; } if ( fIsPreformattedText ) return EMPTY_STRING ; if ( "" . equals ( html ) ) { startBold ( ) ; return EMPTY_STRING ; } if ( "" . equals ( html ) || "" . equals ( html ) ) { startBold ( ) ; return EMPTY_STRING ; } if ( "" . equals ( html ) ) return LINE_DELIM ; if ( "" . equals ( html ) ) return "" ; if ( "" . equals ( html ) ) return LINE_DELIM + RubyUIMessages . HTML2TextReader_listItemPrefix ; if ( "" . equals ( html ) ) { stopBold ( ) ; return EMPTY_STRING ; } if ( "" . equals ( html ) ) { fInParagraph = true ; return LINE_DELIM ; } if ( "" . equals ( html ) ) return LINE_DELIM ; if ( "" . equals ( html ) ) { boolean inParagraph = fInParagraph ; fInParagraph = false ; return inParagraph ? EMPTY_STRING : LINE_DELIM ; } if ( "" . equals ( html ) || "" . equals ( html ) ) { stopBold ( ) ; return LINE_DELIM ; } if ( "" . equals ( html ) ) return LINE_DELIM ; return EMPTY_STRING ; } private String processHTMLTag ( ) throws IOException { StringBuffer buf = new StringBuffer ( ) ; int ch ; do { ch = nextChar ( ) ; while ( ch != - && ch != '>' ) { buf . append ( Character . toLowerCase ( ( char ) ch ) ) ; ch = nextChar ( ) ; if ( ch == '' ) { buf . append ( Character . toLowerCase ( ( char ) ch ) ) ; ch = nextChar ( ) ; while ( ch != - && ch != '' ) { buf . append ( Character . toLowerCase ( ( char ) ch ) ) ; ch = nextChar ( ) ; } } if ( ch == '' ) { unread ( ch ) ; return '' + buf . toString ( ) ; } } if ( ch == - ) return null ; int tagLen = buf . length ( ) ; if ( ( tagLen >= && "" . equals ( buf . substring ( , ) ) ) && ! ( tagLen >= && "" . equals ( buf . substring ( tagLen - ) ) ) ) { buf . append ( ch ) ; } else { break ; } } while ( true ) ; return html2Text ( buf . toString ( ) ) ; } private String processPreformattedText ( int c ) { if ( c == '' || c == '' ) fCounter ++ ; return null ; } private void unread ( int ch ) throws IOException { ( ( PushbackReader ) getReader ( ) ) . unread ( ch ) ; } protected String entity2Text ( String symbol ) { if ( symbol . length ( ) > && symbol . charAt ( ) == '' ) { int ch ; try { if ( symbol . charAt ( ) == '' ) { ch = Integer . parseInt ( symbol . substring ( ) , ) ; } else { ch = Integer . parseInt ( symbol . substring ( ) , ) ; } return EMPTY_STRING + ( char ) ch ; } catch ( NumberFormatException e ) { } } else { String str = ( String ) fgEntityLookup . get ( symbol ) ; if ( str != null ) { return str ; } } return "" + symbol ; } private String processEntity ( ) throws IOException { StringBuffer buf = new StringBuffer ( ) ; int ch = nextChar ( ) ; while ( Character . isLetterOrDigit ( ( char ) ch ) || ch == '' ) { buf . append ( ( char ) ch ) ; ch = nextChar ( ) ; } if ( ch == '' ) return entity2Text ( buf . toString ( ) ) ; buf . insert ( , '' ) ; if ( ch != - ) buf . append ( ( char ) ch ) ; return buf . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . IAutoEditStrategy ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . jface . text . formatter . IContentFormatter ; import org . eclipse . jface . text . hyperlink . IHyperlinkDetector ; import org . eclipse . jface . text . information . IInformationPresenter ; import org . eclipse . jface . text . source . IAnnotationHover ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . ui . text . IColorManager ; import org . rubypeople . rdt . ui . text . RubySourceViewerConfiguration ; public class SimpleRubySourceViewerConfiguration extends RubySourceViewerConfiguration { private boolean fConfigureFormatter ; public SimpleRubySourceViewerConfiguration ( IColorManager colorManager , IPreferenceStore preferenceStore , ITextEditor editor , String partitioning , boolean configureFormatter ) { super ( colorManager , preferenceStore , editor , partitioning ) ; fConfigureFormatter = configureFormatter ; } public IAutoEditStrategy [ ] getAutoEditStrategies ( ISourceViewer sourceViewer , String contentType ) { return null ; } public IAnnotationHover getAnnotationHover ( ISourceViewer sourceViewer ) { return null ; } public IAnnotationHover getOverviewRulerAnnotationHover ( ISourceViewer sourceViewer ) { return null ; } public int [ ] getConfiguredTextHoverStateMasks ( ISourceViewer sourceViewer , String contentType ) { return null ; } public ITextHover getTextHover ( ISourceViewer sourceViewer , String contentType , int stateMask ) { return null ; } public ITextHover getTextHover ( ISourceViewer sourceViewer , String contentType ) { return null ; } public IContentFormatter getContentFormatter ( ISourceViewer sourceViewer ) { if ( fConfigureFormatter ) return super . getContentFormatter ( sourceViewer ) ; else return null ; } public IInformationControlCreator getInformationControlCreator ( ISourceViewer sourceViewer ) { return null ; } public IInformationPresenter getInformationPresenter ( ISourceViewer sourceViewer ) { return null ; } public IInformationPresenter getOutlinePresenter ( ISourceViewer sourceViewer , boolean doCodeResolve ) { return null ; } public IInformationPresenter getHierarchyPresenter ( ISourceViewer sourceViewer , boolean doCodeResolve ) { return null ; } public IHyperlinkDetector [ ] getHyperlinkDetectors ( ISourceViewer sourceViewer ) { return null ; } } package org . rubypeople . rdt . internal . ui . text ; import java . io . IOException ; import java . io . Reader ; import org . eclipse . swt . SWT ; import org . eclipse . swt . SWTError ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Display ; public class HTMLPrinter { private static RGB BG_COLOR_RGB = null ; static { final Display display = Display . getDefault ( ) ; if ( display != null && ! display . isDisposed ( ) ) { try { display . asyncExec ( new Runnable ( ) { public void run ( ) { BG_COLOR_RGB = display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) . getRGB ( ) ; } } ) ; } catch ( SWTError err ) { if ( err . code != SWT . ERROR_DEVICE_DISPOSED ) throw err ; } } } private HTMLPrinter ( ) { } private static String replace ( String text , char c , String s ) { int previous = ; int current = text . indexOf ( c , previous ) ; if ( current == - ) return text ; StringBuffer buffer = new StringBuffer ( ) ; while ( current > - ) { buffer . append ( text . substring ( previous , current ) ) ; buffer . append ( s ) ; previous = current + ; current = text . indexOf ( c , previous ) ; } buffer . append ( text . substring ( previous ) ) ; return buffer . toString ( ) ; } public static String convertToHTMLContent ( String content ) { content = replace ( content , '' , "" ) ; content = replace ( content , '' , "" ) ; content = replace ( content , '' , "" ) ; return replace ( content , '>' , "" ) ; } public static String read ( Reader rd ) { StringBuffer buffer = new StringBuffer ( ) ; char [ ] readBuffer = new char [ ] ; try { int n = rd . read ( readBuffer ) ; while ( n > ) { buffer . append ( readBuffer , , n ) ; n = rd . read ( readBuffer ) ; } return buffer . toString ( ) ; } catch ( IOException x ) { } return null ; } public static void insertStyles ( StringBuffer buffer , String [ ] styles ) { if ( styles == null || styles . length == ) return ; StringBuffer styleBuf = new StringBuffer ( * styles . length ) ; for ( int i = ; styles != null && i < styles . length ; i ++ ) { styleBuf . append ( "" ) ; styleBuf . append ( styles [ i ] ) ; styleBuf . append ( '' ) ; } int index = buffer . indexOf ( "" ) ; if ( index == - ) return ; buffer . insert ( index + , styleBuf ) ; } public static void insertPageProlog ( StringBuffer buffer , int position , RGB bgRGB ) { if ( bgRGB == null ) insertPageProlog ( buffer , position ) ; else { StringBuffer pageProlog = new StringBuffer ( ) ; pageProlog . append ( "" ) ; appendColor ( pageProlog , bgRGB ) ; pageProlog . append ( "" ) ; buffer . insert ( position , pageProlog . toString ( ) ) ; } } public static void insertPageProlog ( StringBuffer buffer , int position , String styleSheet ) { insertPageProlog ( buffer , position , getBgColor ( ) , styleSheet ) ; } public static void insertPageProlog ( StringBuffer buffer , int position , RGB bgRGB , String styleSheet ) { if ( bgRGB == null ) insertPageProlog ( buffer , position , styleSheet ) ; else { StringBuffer pageProlog = new StringBuffer ( ) ; pageProlog . append ( "" ) ; appendStyleSheetURL ( pageProlog , styleSheet ) ; pageProlog . append ( "" ) ; appendColor ( pageProlog , bgRGB ) ; pageProlog . append ( "" ) ; buffer . insert ( position , pageProlog . toString ( ) ) ; } } private static void appendStyleSheetURL ( StringBuffer buffer , String styleSheet ) { if ( styleSheet == null ) return ; buffer . append ( "" ) ; buffer . append ( styleSheet ) ; buffer . append ( "" ) ; } private static void appendColor ( StringBuffer buffer , RGB rgb ) { buffer . append ( '' ) ; buffer . append ( Integer . toHexString ( rgb . red ) ) ; buffer . append ( Integer . toHexString ( rgb . green ) ) ; buffer . append ( Integer . toHexString ( rgb . blue ) ) ; } public static void insertPageProlog ( StringBuffer buffer , int position ) { insertPageProlog ( buffer , position , getBgColor ( ) ) ; } private static RGB getBgColor ( ) { if ( BG_COLOR_RGB != null ) return BG_COLOR_RGB ; return new RGB ( , , ) ; } public static void addPageProlog ( StringBuffer buffer ) { insertPageProlog ( buffer , buffer . length ( ) ) ; } public static void addPageEpilog ( StringBuffer buffer ) { buffer . append ( "" ) ; } public static void startBulletList ( StringBuffer buffer ) { buffer . append ( "" ) ; } public static void endBulletList ( StringBuffer buffer ) { buffer . append ( "" ) ; } public static void addBullet ( StringBuffer buffer , String bullet ) { if ( bullet != null ) { buffer . append ( "" ) ; buffer . append ( bullet ) ; buffer . append ( "" ) ; } } public static void addSmallHeader ( StringBuffer buffer , String header ) { if ( header != null ) { buffer . append ( "" ) ; buffer . append ( header ) ; buffer . append ( "" ) ; } } public static void addParagraph ( StringBuffer buffer , String paragraph ) { if ( paragraph != null ) { buffer . append ( "" ) ; buffer . append ( paragraph ) ; } } public static void addParagraph ( StringBuffer buffer , Reader paragraphReader ) { if ( paragraphReader != null ) addParagraph ( buffer , read ( paragraphReader ) ) ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; public class RubyWordFinder { private static final char [ ] BOUNDARIES = { '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '>' , '' } ; public static IRegion findWord ( IDocument document , int offset ) { int start = - ; int end = - ; try { int pos = offset ; char c ; while ( pos >= ) { c = document . getChar ( pos ) ; if ( ! isRubyWordPart ( c ) ) break ; -- pos ; } start = pos ; pos = offset ; int length = document . getLength ( ) ; while ( pos < length ) { c = document . getChar ( pos ) ; if ( ! isRubyWordPart ( c ) ) break ; ++ pos ; } end = pos ; } catch ( BadLocationException x ) { return null ; } if ( start >= - && end > - ) { if ( start == offset && end == offset ) return new Region ( offset , ) ; else if ( start == offset ) return new Region ( start , end - start ) ; else return new Region ( start + , end - start - ) ; } return null ; } private static boolean isRubyWordPart ( char c ) { return ! isBoundary ( c ) ; } private static boolean isBoundary ( char c ) { return contains ( BOUNDARIES , c ) ; } private static boolean contains ( char [ ] boundaries2 , char c ) { if ( boundaries2 == null || boundaries2 . length == ) return false ; for ( int i = ; i < boundaries2 . length ; i ++ ) { if ( boundaries2 [ i ] == c ) return true ; } return false ; } } package org . rubypeople . rdt . internal . ui . text ; public interface IRubyColorConstants { public static final String RUBY_COLOR_PREFIX = "" ; public static final String RUBY_DEFAULT = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_KEYWORD = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_ERROR = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_STRING = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_REGEXP = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_COMMAND = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_FIXNUM = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_CHARACTER = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_SYMBOL = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_CLASS_VARIABLE = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_INSTANCE_VARIABLE = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_GLOBAL = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_MULTI_LINE_COMMENT = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_SINGLE_LINE_COMMENT = RUBY_COLOR_PREFIX + "" ; public static final String TASK_TAG = RUBY_COLOR_PREFIX + "" ; public static final String RUBY_CONTENT_ASSISTANT_BACKGROUND = RUBY_COLOR_PREFIX + "" ; } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . osgi . util . NLS ; public class TextMessages extends NLS { private static final String BUNDLE_NAME = TextMessages . class . getName ( ) ; public static String RubyOutlineInformationControl_GoIntoTopLevelType_label ; public static String RubyOutlineInformationControl_GoIntoTopLevelType_tooltip ; public static String RubyOutlineInformationControl_GoIntoTopLevelType_description ; public static String RubyOutlineInformationControl_LexicalSortingAction_label ; public static String RubyOutlineInformationControl_LexicalSortingAction_tooltip ; public static String RubyOutlineInformationControl_LexicalSortingAction_description ; public static String RubyOutlineInformationControl_SortByDefiningTypeAction_label ; public static String RubyOutlineInformationControl_SortByDefiningTypeAction_description ; public static String RubyOutlineInformationControl_SortByDefiningTypeAction_tooltip ; public static String RubyElementsHyperlinkProvider_SelectInstance ; public static String RubyElementsHyperlinkProvider_SelectDefinition_msg ; static { NLS . initializeMessages ( BUNDLE_NAME , TextMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . text ; import java . io . IOException ; import java . io . Reader ; public abstract class SingleCharReader extends Reader { public abstract int read ( ) throws IOException ; public int read ( char cbuf [ ] , int off , int len ) throws IOException { int end = off + len ; for ( int i = off ; i < end ; i ++ ) { int ch = read ( ) ; if ( ch == - ) { if ( i == off ) return - ; return i - off ; } cbuf [ i ] = ( char ) ch ; } return len ; } public boolean ready ( ) throws IOException { return true ; } public String getString ( ) throws IOException { StringBuffer buf = new StringBuffer ( ) ; int ch ; while ( ( ch = read ( ) ) != - ) { buf . append ( ( char ) ch ) ; } return buf . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . rubypeople . rdt . core . IRubyProject ; public class RubyIndenter { private IDocument fDocument ; private IRubyProject fProject ; private RubyHeuristicScanner fScanner ; public RubyIndenter ( IDocument d , RubyHeuristicScanner scanner , IRubyProject project ) { fDocument = d ; fScanner = scanner ; fProject = project ; } public StringBuffer computeIndentation ( int offset ) { StringBuffer buf = getLeadingWhitespace ( offset ) ; return buf ; } private StringBuffer getLeadingWhitespace ( int offset ) { StringBuffer indent = new StringBuffer ( ) ; try { IRegion line = fDocument . getLineInformationOfOffset ( offset ) ; int lineOffset = line . getOffset ( ) ; int nonWS = fScanner . findNonWhitespaceForwardInAnyPartition ( lineOffset , lineOffset + line . getLength ( ) ) ; if ( nonWS == - ) { indent . append ( fDocument . get ( lineOffset , line . getLength ( ) ) ) ; return indent ; } indent . append ( fDocument . get ( lineOffset , nonWS - lineOffset ) ) ; return indent ; } catch ( BadLocationException e ) { return indent ; } } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . information . IInformationProvider ; import org . eclipse . jface . text . information . IInformationProviderExtension ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; public class RubyElementProvider implements IInformationProvider , IInformationProviderExtension { private RubyEditor fEditor ; private boolean fUseCodeResolve ; public RubyElementProvider ( IEditorPart editor ) { fUseCodeResolve = false ; if ( editor instanceof RubyEditor ) fEditor = ( RubyEditor ) editor ; } public RubyElementProvider ( IEditorPart editor , boolean useCodeResolve ) { this ( editor ) ; fUseCodeResolve = useCodeResolve ; } public IRegion getSubject ( ITextViewer textViewer , int offset ) { if ( textViewer != null && fEditor != null ) { IRegion region = RubyWordFinder . findWord ( textViewer . getDocument ( ) , offset ) ; if ( region != null ) return region ; else return new Region ( offset , ) ; } return null ; } public String getInformation ( ITextViewer textViewer , IRegion subject ) { return getInformation2 ( textViewer , subject ) . toString ( ) ; } public Object getInformation2 ( ITextViewer textViewer , IRegion subject ) { if ( fEditor == null ) return null ; try { if ( fUseCodeResolve ) { IStructuredSelection sel = SelectionConverter . getStructuredSelection ( fEditor ) ; if ( ! sel . isEmpty ( ) ) return sel . getFirstElement ( ) ; } IRubyElement element = SelectionConverter . getElementAtOffset ( fEditor ) ; if ( element != null ) return element ; return EditorUtility . getEditorInputRubyElement ( fEditor , false ) ; } catch ( RubyModelException e ) { return null ; } } } package org . rubypeople . rdt . internal . ui . text ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationHover ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . texteditor . AnnotationPreference ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; public class RubyAnnotationHover implements IAnnotationHover { private static class RubyAnnotationHoverType { } public static final RubyAnnotationHoverType OVERVIEW_RULER_HOVER = new RubyAnnotationHoverType ( ) ; public static final RubyAnnotationHoverType TEXT_RULER_HOVER = new RubyAnnotationHoverType ( ) ; public static final RubyAnnotationHoverType VERTICAL_RULER_HOVER = new RubyAnnotationHoverType ( ) ; private IPreferenceStore fStore = RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; private RubyAnnotationHoverType fType ; public RubyAnnotationHover ( RubyAnnotationHoverType type ) { Assert . isTrue ( OVERVIEW_RULER_HOVER . equals ( type ) || TEXT_RULER_HOVER . equals ( type ) || VERTICAL_RULER_HOVER . equals ( type ) ) ; fType = type ; } private boolean isDuplicateRubyAnnotation ( Map messagesAtPosition , Position position , String message ) { if ( messagesAtPosition . containsKey ( position ) ) { Object value = messagesAtPosition . get ( position ) ; if ( message . equals ( value ) ) return true ; if ( value instanceof List ) { List messages = ( List ) value ; if ( messages . contains ( message ) ) return true ; messages . add ( message ) ; } else { ArrayList messages = new ArrayList ( ) ; messages . add ( value ) ; messages . add ( message ) ; messagesAtPosition . put ( position , messages ) ; } } else messagesAtPosition . put ( position , message ) ; return false ; } protected List getRubyAnnotationsForLine ( ISourceViewer viewer , int line ) { IDocument document = viewer . getDocument ( ) ; IAnnotationModel model = viewer . getAnnotationModel ( ) ; if ( model == null ) return null ; List exact = new ArrayList ( ) ; List including = new ArrayList ( ) ; Iterator e = model . getAnnotationIterator ( ) ; HashMap messagesAtPosition = new HashMap ( ) ; while ( e . hasNext ( ) ) { Annotation annotation = ( Annotation ) e . next ( ) ; if ( annotation . getText ( ) == null ) continue ; Position position = model . getPosition ( annotation ) ; if ( position == null ) continue ; AnnotationPreference preference = getAnnotationPreference ( annotation ) ; if ( preference == null ) continue ; if ( OVERVIEW_RULER_HOVER . equals ( fType ) ) { String key = preference . getOverviewRulerPreferenceKey ( ) ; if ( key == null || ! fStore . getBoolean ( key ) ) continue ; } else if ( TEXT_RULER_HOVER . equals ( fType ) ) { String key = preference . getTextPreferenceKey ( ) ; if ( key != null ) { if ( ! fStore . getBoolean ( key ) ) continue ; } else { key = preference . getHighlightPreferenceKey ( ) ; if ( key == null || ! fStore . getBoolean ( key ) ) continue ; } } else if ( VERTICAL_RULER_HOVER . equals ( fType ) ) { String key = preference . getVerticalRulerPreferenceKey ( ) ; if ( key != null && ! fStore . getBoolean ( key ) ) continue ; } if ( isDuplicateRubyAnnotation ( messagesAtPosition , position , annotation . getText ( ) ) ) continue ; switch ( compareRulerLine ( position , document , line ) ) { case : exact . add ( annotation ) ; break ; case : including . add ( annotation ) ; break ; } } return select ( exact , including ) ; } protected List select ( List exactMatch , List including ) { return exactMatch ; } protected int compareRulerLine ( Position position , IDocument document , int line ) { if ( position . getOffset ( ) > - && position . getLength ( ) > - ) { try { int javaAnnotationLine = document . getLineOfOffset ( position . getOffset ( ) ) ; if ( line == javaAnnotationLine ) return ; if ( javaAnnotationLine <= line && line <= document . getLineOfOffset ( position . getOffset ( ) + position . getLength ( ) ) ) return ; } catch ( BadLocationException x ) { } } return ; } public String getHoverInfo ( ISourceViewer sourceViewer , int lineNumber ) { List javaAnnotations = getRubyAnnotationsForLine ( sourceViewer , lineNumber ) ; if ( javaAnnotations != null ) { if ( javaAnnotations . size ( ) == ) { Annotation annotation = ( Annotation ) javaAnnotations . get ( ) ; String message = annotation . getText ( ) ; if ( message != null && message . trim ( ) . length ( ) > ) return formatSingleMessage ( message ) ; } else { List messages = new ArrayList ( ) ; Iterator e = javaAnnotations . iterator ( ) ; while ( e . hasNext ( ) ) { Annotation annotation = ( Annotation ) e . next ( ) ; String message = annotation . getText ( ) ; if ( message != null && message . trim ( ) . length ( ) > ) messages . add ( message . trim ( ) ) ; } if ( messages . size ( ) == ) return formatSingleMessage ( ( String ) messages . get ( ) ) ; if ( messages . size ( ) > ) return formatMultipleMessages ( messages ) ; } } return null ; } private String formatSingleMessage ( String message ) { StringBuffer buffer = new StringBuffer ( ) ; HTMLPrinter . addPageProlog ( buffer ) ; HTMLPrinter . addParagraph ( buffer , HTMLPrinter . convertToHTMLContent ( message ) ) ; HTMLPrinter . addPageEpilog ( buffer ) ; return buffer . toString ( ) ; } private String formatMultipleMessages ( List messages ) { StringBuffer buffer = new StringBuffer ( ) ; HTMLPrinter . addPageProlog ( buffer ) ; HTMLPrinter . addParagraph ( buffer , HTMLPrinter . convertToHTMLContent ( RubyUIMessages . RubyAnnotationHover_multipleMarkersAtThisLine ) ) ; HTMLPrinter . startBulletList ( buffer ) ; Iterator e = messages . iterator ( ) ; while ( e . hasNext ( ) ) HTMLPrinter . addBullet ( buffer , HTMLPrinter . convertToHTMLContent ( ( String ) e . next ( ) ) ) ; HTMLPrinter . endBulletList ( buffer ) ; HTMLPrinter . addPageEpilog ( buffer ) ; return buffer . toString ( ) ; } private AnnotationPreference getAnnotationPreference ( Annotation annotation ) { return EditorsUI . getAnnotationPreferenceLookup ( ) . getAnnotationPreference ( annotation ) ; } } package org . rubypeople . rdt . internal . ui . text ; public interface Symbols { int TokenEOF = - ; int TokenLBRACE = ; int TokenRBRACE = ; int TokenLBRACKET = ; int TokenRBRACKET = ; int TokenLPAREN = ; int TokenRPAREN = ; int TokenSEMICOLON = ; int TokenOTHER = ; int TokenCOLON = ; int TokenQUESTIONMARK = ; int TokenCOMMA = ; int TokenEQUAL = ; int TokenLESSTHAN = ; int TokenGREATERTHAN = ; int TokenIF = ; int TokenIN = ; int TokenDO = ; int TokenFOR = ; int TokenBEGIN = ; int TokenEND = ; int TokenCASE = ; int TokenELSE = ; int TokenBREAK = ; int TokenRESCUE = ; int TokenWHILE = ; int TokenRETURN = ; int TokenUNLESS = ; int TokenCLASS = ; int TokenMODULE = ; int TokenNIL = ; int TokenOR = ; int TokenAND = ; int TokenNOT = ; int TokenDEF = ; int TokenTHEN = ; int TokenWHEN = ; int TokenNEXT = ; int TokenREDO = ; int TokenSELF = ; int TokenTRUE = ; int TokenUNDEF = ; int TokenENSURE = ; int TokenRETRY = ; int TokenYIELD = ; int TokenSUPER = ; int TokenFALSE = ; int TokenBIGEND = ; int TokenBIGBEGIN = ; int TokenALIAS = ; int TokenUNTIL = ; int TokenELSIF = ; int TokenDEFINED = ; int TokenLINE = ; int TokenFILE = ; int TokenIDENT = ; } package org . rubypeople . rdt . internal . ui . text ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . Reader ; import java . text . BreakIterator ; import org . eclipse . swt . graphics . GC ; public class LineBreakingReader { private BufferedReader fReader ; private GC fGC ; private int fMaxWidth ; private String fLine ; private int fOffset ; private BreakIterator fLineBreakIterator ; public LineBreakingReader ( Reader reader , GC gc , int maxLineWidth ) { fReader = new BufferedReader ( reader ) ; fGC = gc ; fMaxWidth = maxLineWidth ; fOffset = ; fLine = null ; fLineBreakIterator = BreakIterator . getLineInstance ( ) ; } public boolean isFormattedLine ( ) { return fLine != null ; } public String readLine ( ) throws IOException { if ( fLine == null ) { String line = fReader . readLine ( ) ; if ( line == null ) return null ; int lineLen = fGC . textExtent ( line ) . x ; if ( lineLen < fMaxWidth ) { return line ; } fLine = line ; fLineBreakIterator . setText ( line ) ; fOffset = ; } int breakOffset = findNextBreakOffset ( fOffset ) ; String res ; if ( breakOffset != BreakIterator . DONE ) { res = fLine . substring ( fOffset , breakOffset ) ; fOffset = findWordBegin ( breakOffset ) ; if ( fOffset == fLine . length ( ) ) { fLine = null ; } } else { res = fLine . substring ( fOffset ) ; fLine = null ; } return res ; } private int findNextBreakOffset ( int currOffset ) { int currWidth = ; int nextOffset = fLineBreakIterator . following ( currOffset ) ; while ( nextOffset != BreakIterator . DONE ) { String word = fLine . substring ( currOffset , nextOffset ) ; int wordWidth = fGC . textExtent ( word ) . x ; int nextWidth = wordWidth + currWidth ; if ( nextWidth > fMaxWidth ) { if ( currWidth > ) { return currOffset ; } return nextOffset ; } currWidth = nextWidth ; currOffset = nextOffset ; nextOffset = fLineBreakIterator . next ( ) ; } return nextOffset ; } private int findWordBegin ( int idx ) { while ( idx < fLine . length ( ) && Character . isWhitespace ( fLine . charAt ( idx ) ) ) { idx ++ ; } return idx ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . templates . ContextTypeRegistry ; import org . eclipse . jface . text . templates . persistence . TemplatePersistenceData ; import org . eclipse . jface . text . templates . persistence . TemplateStore ; import org . eclipse . ui . editors . text . templates . ContributionContextTypeRegistry ; import org . eclipse . ui . editors . text . templates . ContributionTemplateStore ; import org . rubypeople . rdt . internal . corext . template . ruby . RubyContextType ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . extensions . IRubyTemplateProvider ; public class RubyTemplateAccess { private static final String CUSTOM_TEMPLATES_KEY = "" ; private static RubyTemplateAccess fgInstance ; private TemplateStore fStore ; private ContributionContextTypeRegistry fContextTypeRegistry ; private RubyTemplateAccess ( ) { } public static RubyTemplateAccess getDefault ( ) { if ( fgInstance == null ) { fgInstance = new RubyTemplateAccess ( ) ; } return fgInstance ; } public TemplateStore getTemplateStore ( ) { if ( fStore == null ) { fStore = new ContributionTemplateStore ( getContextTypeRegistry ( ) , RubyPlugin . getDefault ( ) . getPreferenceStore ( ) , CUSTOM_TEMPLATES_KEY ) ; try { fStore . load ( ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } TemplatePersistenceData [ ] tempData = getExtensionTemplateData ( ) ; if ( tempData != null ) { for ( int i = ; i < tempData . length ; i ++ ) { fStore . add ( tempData [ i ] ) ; } } } return fStore ; } private TemplatePersistenceData [ ] getExtensionTemplateData ( ) { List extensions = new ArrayList ( ) ; IExtensionRegistry reg = Platform . getExtensionRegistry ( ) ; IExtensionPoint [ ] points = reg . getExtensionPoints ( RubyPlugin . PLUGIN_ID ) ; IExtensionPoint point = null ; if ( points != null ) { for ( int i = ; i < points . length ; i ++ ) { IExtensionPoint currentPoint = points [ i ] ; if ( currentPoint . getUniqueIdentifier ( ) . endsWith ( "" ) ) { point = currentPoint ; break ; } } if ( point != null ) { IExtension [ ] exts = point . getExtensions ( ) ; IRubyTemplateProvider prov = null ; for ( int i = ; i < exts . length ; i ++ ) { IConfigurationElement [ ] elem = exts [ i ] . getConfigurationElements ( ) ; String attrs [ ] = elem [ ] . getAttributeNames ( ) ; try { Object tempProv = elem [ ] . createExecutableExtension ( "" ) ; if ( tempProv instanceof IRubyTemplateProvider ) { prov = ( IRubyTemplateProvider ) tempProv ; extensions . add ( prov ) ; } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } } } if ( extensions . size ( ) > ) { for ( int i = ; i < extensions . size ( ) ; i ++ ) { IRubyTemplateProvider currentProvider = ( IRubyTemplateProvider ) extensions . get ( i ) ; TemplatePersistenceData [ ] templates = currentProvider . getTemplateData ( ) ; if ( templates != null ) { return templates ; } } } return null ; } public ContextTypeRegistry getContextTypeRegistry ( ) { if ( fContextTypeRegistry == null ) { fContextTypeRegistry = new ContributionContextTypeRegistry ( ) ; fContextTypeRegistry . addContextType ( new RubyContextType ( ) ) ; } return fContextTypeRegistry ; } public IPreferenceStore getPreferenceStore ( ) { return RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; } public void savePluginPreferences ( ) { RubyPlugin . getDefault ( ) . savePluginPreferences ( ) ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import org . eclipse . osgi . util . NLS ; final class TemplateContentAssistMessages extends NLS { private static final String BUNDLE_NAME = TemplateContentAssistMessages . class . getName ( ) ; private TemplateContentAssistMessages ( ) { } public static String TemplateProposal_displayString ; public static String TemplateEvaluator_error_title ; static { NLS . initializeMessages ( BUNDLE_NAME , TemplateContentAssistMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . templates . TemplateVariable ; public class MultiVariable extends TemplateVariable { private final Map fValueMap = new HashMap ( ) ; private Object fSet ; private Object fDefaultKey = null ; public MultiVariable ( String type , String defaultValue , int [ ] offsets ) { super ( type , defaultValue , offsets ) ; fValueMap . put ( fDefaultKey , new String [ ] { defaultValue } ) ; fSet = getDefaultValue ( ) ; } public void setValues ( Object set , String [ ] values ) { Assert . isNotNull ( set ) ; Assert . isTrue ( values . length > ) ; fValueMap . put ( set , values ) ; if ( fDefaultKey == null ) { fDefaultKey = set ; fSet = getDefaultValue ( ) ; } } public void setValues ( String [ ] values ) { if ( fValueMap != null ) { Assert . isNotNull ( values ) ; Assert . isTrue ( values . length > ) ; fValueMap . put ( fDefaultKey , values ) ; fSet = getDefaultValue ( ) ; } } public String [ ] getValues ( ) { return ( String [ ] ) fValueMap . get ( fDefaultKey ) ; } public String [ ] getValues ( Object set ) { return ( String [ ] ) fValueMap . get ( set ) ; } public Object getSet ( ) { return fSet ; } public void setSet ( Object set ) { fSet = set ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IInformationControlCreatorExtension ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . SourceViewerInformationControl ; final public class TemplateInformationControlCreator implements IInformationControlCreator , IInformationControlCreatorExtension { private SourceViewerInformationControl fControl ; public TemplateInformationControlCreator ( ) { } public IInformationControl createInformationControl ( Shell parent ) { fControl = new SourceViewerInformationControl ( parent ) ; fControl . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { fControl = null ; } } ) ; return fControl ; } public boolean canReuse ( IInformationControl control ) { return fControl == control && fControl != null ; } public boolean canReplace ( IInformationControlCreator creator ) { return ( creator != null && getClass ( ) == creator . getClass ( ) ) ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension2 ; import org . eclipse . jface . text . contentassist . IContextInformation ; public class PositionBasedCompletionProposal implements ICompletionProposal , ICompletionProposalExtension , ICompletionProposalExtension2 { private String fDisplayString ; private String fReplacementString ; private Position fReplacementPosition ; private int fCursorPosition ; private Image fImage ; private IContextInformation fContextInformation ; private String fAdditionalProposalInfo ; public PositionBasedCompletionProposal ( String replacementString , Position replacementPosition , int cursorPosition ) { this ( replacementString , replacementPosition , cursorPosition , null , null , null , null ) ; } public PositionBasedCompletionProposal ( String replacementString , Position replacementPosition , int cursorPosition , Image image , String displayString , IContextInformation contextInformation , String additionalProposalInfo ) { Assert . isNotNull ( replacementString ) ; Assert . isTrue ( replacementPosition != null ) ; fReplacementString = replacementString ; fReplacementPosition = replacementPosition ; fCursorPosition = cursorPosition ; fImage = image ; fDisplayString = displayString ; fContextInformation = contextInformation ; fAdditionalProposalInfo = additionalProposalInfo ; } public void apply ( IDocument document ) { try { document . replace ( fReplacementPosition . getOffset ( ) , fReplacementPosition . getLength ( ) , fReplacementString ) ; } catch ( BadLocationException x ) { } } public Point getSelection ( IDocument document ) { return new Point ( fReplacementPosition . getOffset ( ) + fCursorPosition , ) ; } public IContextInformation getContextInformation ( ) { return fContextInformation ; } public Image getImage ( ) { return fImage ; } public String getDisplayString ( ) { if ( fDisplayString != null ) return fDisplayString ; return fReplacementString ; } public String getAdditionalProposalInfo ( ) { return fAdditionalProposalInfo ; } public void apply ( ITextViewer viewer , char trigger , int stateMask , int offset ) { apply ( viewer . getDocument ( ) ) ; } public void selected ( ITextViewer viewer , boolean smartToggle ) { } public void unselected ( ITextViewer viewer ) { } public boolean validate ( IDocument document , int offset , DocumentEvent event ) { try { String content = document . get ( fReplacementPosition . getOffset ( ) , offset - fReplacementPosition . getOffset ( ) ) ; if ( fReplacementString . startsWith ( content ) ) return true ; } catch ( BadLocationException e ) { } return false ; } public void apply ( IDocument document , char trigger , int offset ) { } public boolean isValidFor ( IDocument document , int offset ) { return false ; } public char [ ] getTriggerCharacters ( ) { return null ; } public int getContextInformationPosition ( ) { return fReplacementPosition . getOffset ( ) ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import java . util . ArrayList ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . templates . GlobalTemplateVariables ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . eclipse . swt . graphics . Point ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . corext . template . ruby . RubyScriptContext ; import org . rubypeople . rdt . internal . corext . template . ruby . RubyScriptContextType ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class TemplateEngine { private static final String $_LINE_SELECTION = "" + GlobalTemplateVariables . LineSelection . NAME + "" ; private static final String $_WORD_SELECTION = "" + GlobalTemplateVariables . WordSelection . NAME + "" ; private TemplateContextType fContextType ; private ArrayList fProposals = new ArrayList ( ) ; public TemplateEngine ( TemplateContextType contextType ) { Assert . isNotNull ( contextType ) ; fContextType = contextType ; } public void reset ( ) { fProposals . clear ( ) ; } public TemplateProposal [ ] getResults ( ) { return ( TemplateProposal [ ] ) fProposals . toArray ( new TemplateProposal [ fProposals . size ( ) ] ) ; } public void complete ( ITextViewer viewer , int completionPosition , IRubyScript compilationUnit ) { IDocument document = viewer . getDocument ( ) ; if ( ! ( fContextType instanceof RubyScriptContextType ) ) return ; Point selection = viewer . getSelectedRange ( ) ; String selectedText = null ; if ( selection . y != ) { try { selectedText = document . get ( selection . x , selection . y ) ; } catch ( BadLocationException e ) { } } RubyScriptContext context = ( ( RubyScriptContextType ) fContextType ) . createContext ( document , completionPosition , selection . y , compilationUnit ) ; context . setVariable ( "" , selectedText ) ; int start = context . getStart ( ) ; int end = context . getEnd ( ) ; IRegion region = new Region ( start , end - start ) ; Template [ ] templates = RubyPlugin . getDefault ( ) . getTemplateStore ( ) . getTemplates ( ) ; if ( selection . y == ) { for ( int i = ; i != templates . length ; i ++ ) if ( context . canEvaluate ( templates [ i ] ) ) fProposals . add ( new TemplateProposal ( templates [ i ] , context , region , RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_TEMPLATE ) ) ) ; } else { if ( context . getKey ( ) . length ( ) == ) context . setForceEvaluation ( true ) ; boolean multipleLinesSelected = areMultipleLinesSelected ( viewer ) ; for ( int i = ; i != templates . length ; i ++ ) { Template template = templates [ i ] ; if ( context . canEvaluate ( template ) && template . getContextTypeId ( ) . equals ( context . getContextType ( ) . getId ( ) ) && ( ! multipleLinesSelected && template . getPattern ( ) . indexOf ( $_WORD_SELECTION ) != - || ( multipleLinesSelected && template . getPattern ( ) . indexOf ( $_LINE_SELECTION ) != - ) ) ) { fProposals . add ( new TemplateProposal ( templates [ i ] , context , region , RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_TEMPLATE ) ) ) ; } } } } private boolean areMultipleLinesSelected ( ITextViewer viewer ) { if ( viewer == null ) return false ; Point s = viewer . getSelectedRange ( ) ; if ( s . y == ) return false ; try { IDocument document = viewer . getDocument ( ) ; int startLine = document . getLineOfOffset ( s . x ) ; int endLine = document . getLineOfOffset ( s . x + s . y ) ; IRegion line = document . getLineInformation ( startLine ) ; return startLine != endLine || ( s . x == line . getOffset ( ) && s . y == line . getLength ( ) ) ; } catch ( BadLocationException x ) { return false ; } } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . link . LinkedPositionGroup ; import org . eclipse . jface . text . link . ProposalPosition ; public class VariablePosition extends ProposalPosition { private MultiVariableGuess fGuess ; private MultiVariable fVariable ; public VariablePosition ( IDocument document , int offset , int length , MultiVariableGuess guess , MultiVariable variable ) { this ( document , offset , length , LinkedPositionGroup . NO_STOP , guess , variable ) ; } public VariablePosition ( IDocument document , int offset , int length , int sequence , MultiVariableGuess guess , MultiVariable variable ) { super ( document , offset , length , sequence , null ) ; Assert . isNotNull ( guess ) ; Assert . isNotNull ( variable ) ; fVariable = variable ; fGuess = guess ; } public boolean equals ( Object o ) { if ( o instanceof VariablePosition && super . equals ( o ) ) { return fGuess . equals ( ( ( VariablePosition ) o ) . fGuess ) ; } return false ; } public int hashCode ( ) { return super . hashCode ( ) | fGuess . hashCode ( ) ; } public ICompletionProposal [ ] getChoices ( ) { return fGuess . getProposals ( fVariable , offset , length ) ; } public MultiVariable getVariable ( ) { return fVariable ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import java . util . Iterator ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . eclipse . jface . text . templates . TemplateVariableResolver ; import org . rubypeople . rdt . internal . corext . template . ruby . RubyContextType ; public class RubyTemplateVariableTextHover implements ITextHover { public RubyTemplateVariableTextHover ( ) { } public String getHoverInfo ( ITextViewer textViewer , IRegion subject ) { try { IDocument doc = textViewer . getDocument ( ) ; int offset = subject . getOffset ( ) ; if ( offset >= && "" . equals ( doc . get ( offset - , ) ) ) { String varName = doc . get ( offset , subject . getLength ( ) ) ; TemplateContextType contextType = RubyTemplateAccess . getDefault ( ) . getContextTypeRegistry ( ) . getContextType ( RubyContextType . NAME ) ; if ( contextType != null ) { Iterator iter = contextType . resolvers ( ) ; while ( iter . hasNext ( ) ) { TemplateVariableResolver var = ( TemplateVariableResolver ) iter . next ( ) ; if ( varName . equals ( var . getType ( ) ) ) { return var . getDescription ( ) ; } } } } } catch ( BadLocationException e ) { } return null ; } public IRegion getHoverRegion ( ITextViewer textViewer , int offset ) { if ( textViewer != null ) { IDocument document = textViewer . getDocument ( ) ; int start = - ; int end = - ; try { int pos = offset ; char c ; while ( pos >= ) { c = document . getChar ( pos ) ; if ( c != '' && c != '' && c != '' && c != '' && ! Character . isJavaIdentifierPart ( c ) ) break ; -- pos ; } start = pos ; pos = offset ; int length = document . getLength ( ) ; while ( pos < length ) { c = document . getChar ( pos ) ; if ( c != '' && c != '' && ! Character . isJavaIdentifierPart ( c ) ) break ; ++ pos ; } end = pos ; } catch ( BadLocationException x ) { } if ( start > - && end > - ) { if ( start == offset && end == offset ) return new Region ( offset , ) ; else if ( start == offset ) return new Region ( start , end - start ) ; else return new Region ( start + , end - start - ) ; } return null ; } return null ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPositionCategoryException ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension2 ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension3 ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension4 ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . link . ILinkedModeListener ; import org . eclipse . jface . text . link . InclusivePositionUpdater ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . jface . text . link . LinkedModeUI ; import org . eclipse . jface . text . link . LinkedPosition ; import org . eclipse . jface . text . link . LinkedPositionGroup ; import org . eclipse . jface . text . link . ProposalPosition ; import org . eclipse . jface . text . templates . DocumentTemplateContext ; import org . eclipse . jface . text . templates . GlobalTemplateVariables ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . TemplateBuffer ; import org . eclipse . jface . text . templates . TemplateContext ; import org . eclipse . jface . text . templates . TemplateException ; import org . eclipse . jface . text . templates . TemplateVariable ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . texteditor . link . EditorLinkedModeUI ; import org . rubypeople . rdt . internal . corext . template . ruby . RubyScriptContext ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorHighlightingSynchronizer ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class TemplateProposal implements IRubyCompletionProposal , ICompletionProposalExtension2 , ICompletionProposalExtension3 , ICompletionProposalExtension4 { private final Template fTemplate ; private final TemplateContext fContext ; private final Image fImage ; private IRegion fRegion ; private int fRelevance ; private IRegion fSelectedRegion ; private String fDisplayString ; public TemplateProposal ( Template template , TemplateContext context , IRegion region , Image image ) { Assert . isNotNull ( template ) ; Assert . isNotNull ( context ) ; Assert . isNotNull ( region ) ; fTemplate = template ; fContext = context ; fImage = image ; fRegion = region ; fDisplayString = null ; fRelevance = computeRelevance ( ) ; } private int computeRelevance ( ) { final int R_DEFAULT = ; final int R_INTERESTING = ; final int R_CASE = ; final int R_NON_RESTRICTED = ; final int R_EXACT_NAME = ; final int R_INLINE_TAG = ; int base = R_DEFAULT + R_INTERESTING + R_NON_RESTRICTED ; try { if ( fContext instanceof DocumentTemplateContext ) { DocumentTemplateContext templateContext = ( DocumentTemplateContext ) fContext ; IDocument document = templateContext . getDocument ( ) ; String content = document . get ( fRegion . getOffset ( ) , fRegion . getLength ( ) ) ; if ( fTemplate . getName ( ) . startsWith ( content ) ) base += R_CASE ; if ( fTemplate . getName ( ) . equalsIgnoreCase ( content ) ) base += R_EXACT_NAME ; } } catch ( BadLocationException e ) { } final int TEMPLATE_RELEVANCE = ; return base * + TEMPLATE_RELEVANCE ; } public final void apply ( IDocument document ) { } public void apply ( ITextViewer viewer , char trigger , int stateMask , int offset ) { try { fContext . setReadOnly ( false ) ; TemplateBuffer templateBuffer ; try { templateBuffer = fContext . evaluate ( fTemplate ) ; } catch ( TemplateException e1 ) { fSelectedRegion = fRegion ; return ; } int start = getReplaceOffset ( ) ; int end = getReplaceEndOffset ( ) ; end = Math . max ( end , offset ) ; IDocument document = viewer . getDocument ( ) ; String templateString = templateBuffer . getString ( ) ; document . replace ( start , end - start , templateString ) ; LinkedModeModel model = new LinkedModeModel ( ) ; TemplateVariable [ ] variables = templateBuffer . getVariables ( ) ; MultiVariableGuess guess = fContext instanceof RubyScriptContext ? ( ( RubyScriptContext ) fContext ) . getMultiVariableGuess ( ) : null ; boolean hasPositions = false ; for ( int i = ; i != variables . length ; i ++ ) { TemplateVariable variable = variables [ i ] ; if ( variable . isUnambiguous ( ) ) continue ; LinkedPositionGroup group = new LinkedPositionGroup ( ) ; int [ ] offsets = variable . getOffsets ( ) ; int length = variable . getLength ( ) ; LinkedPosition first ; if ( guess != null && variable instanceof MultiVariable ) { first = new VariablePosition ( document , offsets [ ] + start , length , guess , ( MultiVariable ) variable ) ; guess . addSlave ( ( VariablePosition ) first ) ; } else { String [ ] values = variable . getValues ( ) ; ICompletionProposal [ ] proposals = new ICompletionProposal [ values . length ] ; for ( int j = ; j < values . length ; j ++ ) { ensurePositionCategoryInstalled ( document , model ) ; Position pos = new Position ( offsets [ ] + start , length ) ; document . addPosition ( getCategory ( ) , pos ) ; proposals [ j ] = new PositionBasedCompletionProposal ( values [ j ] , pos , length ) ; } if ( proposals . length > ) first = new ProposalPosition ( document , offsets [ ] + start , length , proposals ) ; else first = new LinkedPosition ( document , offsets [ ] + start , length ) ; } for ( int j = ; j != offsets . length ; j ++ ) if ( j == ) group . addPosition ( first ) ; else group . addPosition ( new LinkedPosition ( document , offsets [ j ] + start , length ) ) ; model . addGroup ( group ) ; hasPositions = true ; } if ( hasPositions ) { model . forceInstall ( ) ; RubyEditor editor = getRubyEditor ( ) ; if ( editor != null ) { model . addLinkingListener ( new EditorHighlightingSynchronizer ( editor ) ) ; } LinkedModeUI ui = new EditorLinkedModeUI ( model , viewer ) ; ui . setExitPosition ( viewer , getCaretOffset ( templateBuffer ) + start , , Integer . MAX_VALUE ) ; ui . enter ( ) ; fSelectedRegion = ui . getSelectedRegion ( ) ; } else fSelectedRegion = new Region ( getCaretOffset ( templateBuffer ) + start , ) ; } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; openErrorDialog ( viewer . getTextWidget ( ) . getShell ( ) , e ) ; fSelectedRegion = fRegion ; } catch ( BadPositionCategoryException e ) { RubyPlugin . log ( e ) ; openErrorDialog ( viewer . getTextWidget ( ) . getShell ( ) , e ) ; fSelectedRegion = fRegion ; } } private RubyEditor getRubyEditor ( ) { IEditorPart part = RubyPlugin . getActivePage ( ) . getActiveEditor ( ) ; if ( part instanceof RubyEditor ) return ( RubyEditor ) part ; else return null ; } private int getReplaceOffset ( ) { int start ; if ( fContext instanceof DocumentTemplateContext ) { DocumentTemplateContext docContext = ( DocumentTemplateContext ) fContext ; start = docContext . getStart ( ) ; } else { start = fRegion . getOffset ( ) ; } return start ; } private int getReplaceEndOffset ( ) { int end ; if ( fContext instanceof DocumentTemplateContext ) { DocumentTemplateContext docContext = ( DocumentTemplateContext ) fContext ; end = docContext . getEnd ( ) ; } else { end = fRegion . getOffset ( ) + fRegion . getLength ( ) ; } return end ; } private void ensurePositionCategoryInstalled ( final IDocument document , LinkedModeModel model ) { if ( ! document . containsPositionCategory ( getCategory ( ) ) ) { document . addPositionCategory ( getCategory ( ) ) ; final InclusivePositionUpdater updater = new InclusivePositionUpdater ( getCategory ( ) ) ; document . addPositionUpdater ( updater ) ; model . addLinkingListener ( new ILinkedModeListener ( ) { public void left ( LinkedModeModel environment , int flags ) { try { document . removePositionCategory ( getCategory ( ) ) ; } catch ( BadPositionCategoryException e ) { } document . removePositionUpdater ( updater ) ; } public void suspend ( LinkedModeModel environment ) { } public void resume ( LinkedModeModel environment , int flags ) { } } ) ; } } private String getCategory ( ) { return "" + toString ( ) ; } private int getCaretOffset ( TemplateBuffer buffer ) { TemplateVariable [ ] variables = buffer . getVariables ( ) ; for ( int i = ; i != variables . length ; i ++ ) { TemplateVariable variable = variables [ i ] ; if ( variable . getType ( ) . equals ( GlobalTemplateVariables . Cursor . NAME ) ) return variable . getOffsets ( ) [ ] ; } return buffer . getString ( ) . length ( ) ; } public Point getSelection ( IDocument document ) { return new Point ( fSelectedRegion . getOffset ( ) , fSelectedRegion . getLength ( ) ) ; } public String getAdditionalProposalInfo ( ) { try { fContext . setReadOnly ( true ) ; TemplateBuffer templateBuffer ; try { templateBuffer = fContext . evaluate ( fTemplate ) ; } catch ( TemplateException e1 ) { return null ; } return templateBuffer . getString ( ) ; } catch ( BadLocationException e ) { handleException ( RubyPlugin . getActiveWorkbenchShell ( ) , new CoreException ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , e ) ) ) ; return null ; } } public String getDisplayString ( ) { if ( fDisplayString == null ) { String [ ] arguments = new String [ ] { fTemplate . getName ( ) , fTemplate . getDescription ( ) } ; fDisplayString = Messages . format ( TemplateContentAssistMessages . TemplateProposal_displayString , arguments ) ; } return fDisplayString ; } public void setDisplayString ( String displayString ) { fDisplayString = displayString ; } public Image getImage ( ) { return fImage ; } public IContextInformation getContextInformation ( ) { return null ; } private void openErrorDialog ( Shell shell , Exception e ) { MessageDialog . openError ( shell , TemplateContentAssistMessages . TemplateEvaluator_error_title , e . getMessage ( ) ) ; } private void handleException ( Shell shell , CoreException e ) { ExceptionHandler . handle ( e , shell , TemplateContentAssistMessages . TemplateEvaluator_error_title , null ) ; } public int getRelevance ( ) { return fRelevance ; } public void setRelevance ( int relevance ) { fRelevance = relevance ; } public Template getTemplate ( ) { return fTemplate ; } public IInformationControlCreator getInformationControlCreator ( ) { return new TemplateInformationControlCreator ( ) ; } public void selected ( ITextViewer viewer , boolean smartToggle ) { } public void unselected ( ITextViewer viewer ) { } public boolean validate ( IDocument document , int offset , DocumentEvent event ) { try { int replaceOffset = getReplaceOffset ( ) ; if ( offset >= replaceOffset ) { String content = document . get ( replaceOffset , offset - replaceOffset ) ; return fTemplate . getName ( ) . toLowerCase ( ) . startsWith ( content . toLowerCase ( ) ) ; } } catch ( BadLocationException e ) { } return false ; } public CharSequence getPrefixCompletionText ( IDocument document , int completionOffset ) { if ( isSelectionTemplate ( ) ) return "" ; return fTemplate . getName ( ) ; } public int getPrefixCompletionStart ( IDocument document , int completionOffset ) { return getReplaceOffset ( ) ; } public boolean isAutoInsertable ( ) { if ( isSelectionTemplate ( ) ) return false ; return fTemplate . isAutoInsertable ( ) ; } private boolean isSelectionTemplate ( ) { if ( fContext instanceof DocumentTemplateContext ) { DocumentTemplateContext ctx = ( DocumentTemplateContext ) fContext ; if ( ctx . getCompletionLength ( ) > ) return true ; } return false ; } } package org . rubypeople . rdt . internal . ui . text . template . contentassist ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension2 ; import org . eclipse . jface . text . contentassist . IContextInformation ; public class MultiVariableGuess { class Proposal implements ICompletionProposal , ICompletionProposalExtension2 { private String fDisplayString ; String fReplacementString ; private int fReplacementOffset ; private int fReplacementLength ; private int fCursorPosition ; private Image fImage ; private IContextInformation fContextInformation ; private String fAdditionalProposalInfo ; public Proposal ( String replacementString , int replacementOffset , int replacementLength , int cursorPosition ) { this ( replacementString , replacementOffset , replacementLength , cursorPosition , null , null , null , null ) ; } public Proposal ( String replacementString , int replacementOffset , int replacementLength , int cursorPosition , Image image , String displayString , IContextInformation contextInformation , String additionalProposalInfo ) { Assert . isNotNull ( replacementString ) ; Assert . isTrue ( replacementOffset >= ) ; Assert . isTrue ( replacementLength >= ) ; Assert . isTrue ( cursorPosition >= ) ; fReplacementString = replacementString ; fReplacementOffset = replacementOffset ; fReplacementLength = replacementLength ; fCursorPosition = cursorPosition ; fImage = image ; fDisplayString = displayString ; fContextInformation = contextInformation ; fAdditionalProposalInfo = additionalProposalInfo ; } public void apply ( IDocument document ) { try { document . replace ( fReplacementOffset , fReplacementLength , fReplacementString ) ; } catch ( BadLocationException x ) { } } public Point getSelection ( IDocument document ) { return new Point ( fReplacementOffset + fCursorPosition , ) ; } public IContextInformation getContextInformation ( ) { return fContextInformation ; } public Image getImage ( ) { return fImage ; } public String getDisplayString ( ) { if ( fDisplayString != null ) return fDisplayString ; return fReplacementString ; } public String getAdditionalProposalInfo ( ) { return fAdditionalProposalInfo ; } public void apply ( ITextViewer viewer , char trigger , int stateMask , int offset ) { apply ( viewer . getDocument ( ) ) ; } public void selected ( ITextViewer viewer , boolean smartToggle ) { } public void unselected ( ITextViewer viewer ) { } public boolean validate ( IDocument document , int offset , DocumentEvent event ) { try { String content = document . get ( fReplacementOffset , fReplacementLength ) ; if ( content . startsWith ( fReplacementString ) ) return true ; } catch ( BadLocationException e ) { } return false ; } } private final List fSlaves = new ArrayList ( ) ; private MultiVariable fMaster ; public MultiVariableGuess ( MultiVariable mv ) { fMaster = mv ; } public ICompletionProposal [ ] getProposals ( MultiVariable variable , int offset , int length ) { if ( variable . equals ( fMaster ) ) { String [ ] choices = variable . getValues ( ) ; ICompletionProposal [ ] ret = new ICompletionProposal [ choices . length ] ; for ( int i = ; i < ret . length ; i ++ ) { ret [ i ] = new Proposal ( choices [ i ] , offset , length , offset + length ) { public void apply ( IDocument document ) { super . apply ( document ) ; try { Object old = fMaster . getSet ( ) ; fMaster . setSet ( fReplacementString ) ; if ( ! fReplacementString . equals ( old ) ) { for ( Iterator it = fSlaves . iterator ( ) ; it . hasNext ( ) ; ) { VariablePosition pos = ( VariablePosition ) it . next ( ) ; String [ ] values = pos . getVariable ( ) . getValues ( fReplacementString ) ; if ( values != null ) document . replace ( pos . getOffset ( ) , pos . getLength ( ) , values [ ] ) ; } } } catch ( BadLocationException e ) { } } } ; } return ret ; } else { String [ ] choices = variable . getValues ( fMaster . getSet ( ) ) ; if ( choices == null || choices . length < ) return null ; ICompletionProposal [ ] ret = new ICompletionProposal [ choices . length ] ; for ( int i = ; i < ret . length ; i ++ ) { ret [ i ] = new Proposal ( choices [ i ] , offset , length , offset + length ) ; } return ret ; } } public void addSlave ( VariablePosition position ) { fSlaves . add ( position ) ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . SafeRunner ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . contentassist . ContentAssistEvent ; import org . eclipse . jface . text . contentassist . ICompletionListener ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . quickassist . IQuickAssistInvocationContext ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . ltk . core . refactoring . NullChange ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IMarkerHelpRegistry ; import org . eclipse . ui . IMarkerResolution ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . texteditor . SimpleMarkerAnnotation ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyAnnotation ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . correction . ChangeCorrectionProposal ; import org . rubypeople . rdt . ui . text . ruby . CompletionProposalComparator ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; import org . rubypeople . rdt . ui . text . ruby . IQuickAssistProcessor ; import org . rubypeople . rdt . ui . text . ruby . IQuickFixProcessor ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class RubyCorrectionProcessor implements org . eclipse . jface . text . quickassist . IQuickAssistProcessor { private static final String QUICKFIX_PROCESSOR_CONTRIBUTION_ID = "" ; private static final String QUICKASSIST_PROCESSOR_CONTRIBUTION_ID = "" ; private static ContributedProcessorDescriptor [ ] fContributedAssistProcessors = null ; private static ContributedProcessorDescriptor [ ] fContributedCorrectionProcessors = null ; private static ContributedProcessorDescriptor [ ] getProcessorDescriptors ( String contributionId , boolean testMarkerTypes ) { IConfigurationElement [ ] elements = Platform . getExtensionRegistry ( ) . getConfigurationElementsFor ( RubyUI . ID_PLUGIN , contributionId ) ; ArrayList res = new ArrayList ( elements . length ) ; for ( int i = ; i < elements . length ; i ++ ) { ContributedProcessorDescriptor desc = new ContributedProcessorDescriptor ( elements [ i ] , testMarkerTypes ) ; IStatus status = desc . checkSyntax ( ) ; if ( status . isOK ( ) ) { res . add ( desc ) ; } else { RubyPlugin . log ( status ) ; } } return ( ContributedProcessorDescriptor [ ] ) res . toArray ( new ContributedProcessorDescriptor [ res . size ( ) ] ) ; } private static ContributedProcessorDescriptor [ ] getCorrectionProcessors ( ) { if ( fContributedCorrectionProcessors == null ) { fContributedCorrectionProcessors = getProcessorDescriptors ( QUICKFIX_PROCESSOR_CONTRIBUTION_ID , true ) ; } return fContributedCorrectionProcessors ; } private static ContributedProcessorDescriptor [ ] getAssistProcessors ( ) { if ( fContributedAssistProcessors == null ) { fContributedAssistProcessors = getProcessorDescriptors ( QUICKASSIST_PROCESSOR_CONTRIBUTION_ID , false ) ; } return fContributedAssistProcessors ; } public static boolean hasCorrections ( IRubyScript cu , int problemId , String markerType ) { ContributedProcessorDescriptor [ ] processors = getCorrectionProcessors ( ) ; SafeHasCorrections collector = new SafeHasCorrections ( cu , problemId ) ; for ( int i = ; i < processors . length ; i ++ ) { if ( processors [ i ] . canHandleMarkerType ( markerType ) ) { collector . process ( processors [ i ] ) ; if ( collector . hasCorrections ( ) ) { return true ; } } } return false ; } public static boolean isQuickFixableType ( Annotation annotation ) { return ( annotation instanceof IRubyAnnotation || annotation instanceof SimpleMarkerAnnotation ) && ! annotation . isMarkedDeleted ( ) ; } public static boolean hasCorrections ( Annotation annotation ) { if ( annotation instanceof IRubyAnnotation ) { IRubyAnnotation javaAnnotation = ( IRubyAnnotation ) annotation ; int problemId = javaAnnotation . getId ( ) ; if ( problemId != - ) { IRubyScript cu = javaAnnotation . getRubyScript ( ) ; if ( cu != null ) { return hasCorrections ( cu , problemId , javaAnnotation . getMarkerType ( ) ) ; } } } if ( annotation instanceof SimpleMarkerAnnotation ) { return hasCorrections ( ( ( SimpleMarkerAnnotation ) annotation ) . getMarker ( ) ) ; } return false ; } private static boolean hasCorrections ( IMarker marker ) { if ( marker == null || ! marker . exists ( ) ) return false ; IMarkerHelpRegistry registry = IDE . getMarkerHelpRegistry ( ) ; return registry != null && registry . hasResolutions ( marker ) ; } public static boolean hasAssists ( IInvocationContext context ) { ContributedProcessorDescriptor [ ] processors = getAssistProcessors ( ) ; SafeHasAssist collector = new SafeHasAssist ( context ) ; for ( int i = ; i < processors . length ; i ++ ) { collector . process ( processors [ i ] ) ; if ( collector . hasAssists ( ) ) { return true ; } } return false ; } private RubyCorrectionAssistant fAssistant ; private String fErrorMessage ; public RubyCorrectionProcessor ( RubyCorrectionAssistant assistant ) { fAssistant = assistant ; fAssistant . addCompletionListener ( new ICompletionListener ( ) { public void assistSessionEnded ( ContentAssistEvent event ) { fAssistant . setStatusLineVisible ( false ) ; } public void assistSessionStarted ( ContentAssistEvent event ) { fAssistant . setStatusLineVisible ( true ) ; } public void selectionChanged ( ICompletionProposal proposal , boolean smartToggle ) { if ( proposal instanceof IStatusLineProposal ) { IStatusLineProposal statusLineProposal = ( IStatusLineProposal ) proposal ; String message = statusLineProposal . getStatusMessage ( ) ; if ( message != null ) { fAssistant . setStatusMessage ( message ) ; } else { fAssistant . setStatusMessage ( "" ) ; } } else { fAssistant . setStatusMessage ( "" ) ; } } } ) ; } public ICompletionProposal [ ] computeQuickAssistProposals ( IQuickAssistInvocationContext quickAssistContext ) { ITextViewer viewer = quickAssistContext . getSourceViewer ( ) ; int documentOffset = quickAssistContext . getOffset ( ) ; IEditorPart part = fAssistant . getEditor ( ) ; IRubyScript cu = RubyUI . getWorkingCopyManager ( ) . getWorkingCopy ( part . getEditorInput ( ) ) ; IAnnotationModel model = RubyUI . getDocumentProvider ( ) . getAnnotationModel ( part . getEditorInput ( ) ) ; int length = viewer != null ? viewer . getSelectedRange ( ) . y : ; AssistContext context = new AssistContext ( cu , documentOffset , length ) ; Annotation [ ] annotations = fAssistant . getAnnotationsAtOffset ( ) ; fErrorMessage = null ; ICompletionProposal [ ] res = null ; if ( model != null && annotations != null ) { ArrayList proposals = new ArrayList ( ) ; IStatus status = collectProposals ( context , model , annotations , true , ! fAssistant . isUpdatedOffset ( ) , proposals ) ; res = ( ICompletionProposal [ ] ) proposals . toArray ( new ICompletionProposal [ proposals . size ( ) ] ) ; if ( ! status . isOK ( ) ) { fErrorMessage = status . getMessage ( ) ; RubyPlugin . log ( status ) ; } } if ( res == null || res . length == ) { return new ICompletionProposal [ ] { new ChangeCorrectionProposal ( CorrectionMessages . NoCorrectionProposal_description , new NullChange ( "" ) , , null ) } ; } if ( res . length > ) { Arrays . sort ( res , new CompletionProposalComparator ( ) ) ; } return res ; } public static IStatus collectProposals ( IInvocationContext context , IAnnotationModel model , Annotation [ ] annotations , boolean addQuickFixes , boolean addQuickAssists , Collection proposals ) { ArrayList problems = new ArrayList ( ) ; for ( int i = ; i < annotations . length ; i ++ ) { Annotation curr = annotations [ i ] ; if ( curr instanceof IRubyAnnotation ) { ProblemLocation problemLocation = getProblemLocation ( ( IRubyAnnotation ) curr , model ) ; if ( problemLocation != null ) { problems . add ( problemLocation ) ; } } else if ( addQuickFixes && curr instanceof SimpleMarkerAnnotation ) { collectMarkerProposals ( ( SimpleMarkerAnnotation ) curr , proposals ) ; } } MultiStatus resStatus = null ; IProblemLocation [ ] problemLocations = ( IProblemLocation [ ] ) problems . toArray ( new IProblemLocation [ problems . size ( ) ] ) ; if ( addQuickFixes ) { IStatus status = collectCorrections ( context , problemLocations , proposals ) ; if ( ! status . isOK ( ) ) { resStatus = new MultiStatus ( RubyUI . ID_PLUGIN , IStatus . ERROR , CorrectionMessages . RubyCorrectionProcessor_error_quickfix_message , null ) ; resStatus . add ( status ) ; } } if ( addQuickAssists ) { IStatus status = collectAssists ( context , problemLocations , proposals ) ; if ( ! status . isOK ( ) ) { if ( resStatus == null ) { resStatus = new MultiStatus ( RubyUI . ID_PLUGIN , IStatus . ERROR , CorrectionMessages . RubyCorrectionProcessor_error_quickassist_message , null ) ; } resStatus . add ( status ) ; } } if ( resStatus != null ) { return resStatus ; } return Status . OK_STATUS ; } private static ProblemLocation getProblemLocation ( IRubyAnnotation javaAnnotation , IAnnotationModel model ) { int problemId = javaAnnotation . getId ( ) ; if ( problemId != - ) { Position pos = model . getPosition ( ( Annotation ) javaAnnotation ) ; if ( pos != null ) { return new ProblemLocation ( pos . getOffset ( ) , pos . getLength ( ) , javaAnnotation ) ; } } return null ; } private static void collectMarkerProposals ( SimpleMarkerAnnotation annotation , Collection proposals ) { IMarker marker = annotation . getMarker ( ) ; IMarkerResolution [ ] res = IDE . getMarkerHelpRegistry ( ) . getResolutions ( marker ) ; if ( res . length > ) { for ( int i = ; i < res . length ; i ++ ) { proposals . add ( new MarkerResolutionProposal ( res [ i ] , marker ) ) ; } } } private static abstract class SafeCorrectionProcessorAccess implements ISafeRunnable { private MultiStatus fMulti = null ; private ContributedProcessorDescriptor fDescriptor ; public void process ( ContributedProcessorDescriptor [ ] desc ) { for ( int i = ; i < desc . length ; i ++ ) { fDescriptor = desc [ i ] ; SafeRunner . run ( this ) ; } } public void process ( ContributedProcessorDescriptor desc ) { fDescriptor = desc ; SafeRunner . run ( this ) ; } public void run ( ) throws Exception { safeRun ( fDescriptor ) ; } protected abstract void safeRun ( ContributedProcessorDescriptor processor ) throws Exception ; public void handleException ( Throwable exception ) { if ( fMulti == null ) { fMulti = new MultiStatus ( RubyUI . ID_PLUGIN , IStatus . OK , CorrectionMessages . RubyCorrectionProcessor_error_status , null ) ; } fMulti . merge ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . ERROR , CorrectionMessages . RubyCorrectionProcessor_error_status , exception ) ) ; } public IStatus getStatus ( ) { if ( fMulti == null ) { return Status . OK_STATUS ; } return fMulti ; } } private static class SafeCorrectionCollector extends SafeCorrectionProcessorAccess { private final IInvocationContext fContext ; private final Collection fProposals ; private IProblemLocation [ ] fLocations ; public SafeCorrectionCollector ( IInvocationContext context , Collection proposals ) { fContext = context ; fProposals = proposals ; } public void setProblemLocations ( IProblemLocation [ ] locations ) { fLocations = locations ; } public void safeRun ( ContributedProcessorDescriptor desc ) throws Exception { IQuickFixProcessor curr = ( IQuickFixProcessor ) desc . getProcessor ( fContext . getRubyScript ( ) ) ; if ( curr != null ) { IRubyCompletionProposal [ ] res = curr . getCorrections ( fContext , fLocations ) ; if ( res != null ) { for ( int k = ; k < res . length ; k ++ ) { fProposals . add ( res [ k ] ) ; } } } } } private static class SafeAssistCollector extends SafeCorrectionProcessorAccess { private final IInvocationContext fContext ; private final IProblemLocation [ ] fLocations ; private final Collection fProposals ; public SafeAssistCollector ( IInvocationContext context , IProblemLocation [ ] locations , Collection proposals ) { fContext = context ; fLocations = locations ; fProposals = proposals ; } public void safeRun ( ContributedProcessorDescriptor desc ) throws Exception { IQuickAssistProcessor curr = ( IQuickAssistProcessor ) desc . getProcessor ( fContext . getRubyScript ( ) ) ; if ( curr != null ) { IRubyCompletionProposal [ ] res = curr . getAssists ( fContext , fLocations ) ; if ( res != null ) { for ( int k = ; k < res . length ; k ++ ) { fProposals . add ( res [ k ] ) ; } } } } } private static class SafeHasAssist extends SafeCorrectionProcessorAccess { private final IInvocationContext fContext ; private boolean fHasAssists ; public SafeHasAssist ( IInvocationContext context ) { fContext = context ; fHasAssists = false ; } public boolean hasAssists ( ) { return fHasAssists ; } public void safeRun ( ContributedProcessorDescriptor desc ) throws Exception { IQuickAssistProcessor processor = ( IQuickAssistProcessor ) desc . getProcessor ( fContext . getRubyScript ( ) ) ; if ( processor != null && processor . hasAssists ( fContext ) ) { fHasAssists = true ; } } } private static class SafeHasCorrections extends SafeCorrectionProcessorAccess { private final IRubyScript fCu ; private final int fProblemId ; private boolean fHasCorrections ; public SafeHasCorrections ( IRubyScript cu , int problemId ) { fCu = cu ; fProblemId = problemId ; fHasCorrections = false ; } public boolean hasCorrections ( ) { return fHasCorrections ; } public void safeRun ( ContributedProcessorDescriptor desc ) throws Exception { IQuickFixProcessor processor = ( IQuickFixProcessor ) desc . getProcessor ( fCu ) ; if ( processor != null && processor . hasCorrections ( fCu , fProblemId ) ) { fHasCorrections = true ; } } } public static IStatus collectCorrections ( IInvocationContext context , IProblemLocation [ ] locations , Collection proposals ) { ContributedProcessorDescriptor [ ] processors = getCorrectionProcessors ( ) ; SafeCorrectionCollector collector = new SafeCorrectionCollector ( context , proposals ) ; for ( int i = ; i < processors . length ; i ++ ) { ContributedProcessorDescriptor curr = processors [ i ] ; IProblemLocation [ ] handled = getHandledProblems ( locations , curr ) ; if ( handled != null ) { collector . setProblemLocations ( handled ) ; collector . process ( curr ) ; } } return collector . getStatus ( ) ; } private static IProblemLocation [ ] getHandledProblems ( IProblemLocation [ ] locations , ContributedProcessorDescriptor processor ) { boolean allHandled = true ; ArrayList res = null ; for ( int i = ; i < locations . length ; i ++ ) { IProblemLocation curr = locations [ i ] ; if ( processor . canHandleMarkerType ( curr . getMarkerType ( ) ) ) { if ( ! allHandled ) { if ( res == null ) { res = new ArrayList ( locations . length - i ) ; } res . add ( curr ) ; } } else if ( allHandled ) { if ( i > ) { res = new ArrayList ( locations . length - i ) ; for ( int k = ; k < i ; k ++ ) { res . add ( locations [ k ] ) ; } } allHandled = false ; } } if ( allHandled ) { return locations ; } if ( res == null ) { return null ; } return ( IProblemLocation [ ] ) res . toArray ( new IProblemLocation [ res . size ( ) ] ) ; } public static IStatus collectAssists ( IInvocationContext context , IProblemLocation [ ] locations , Collection proposals ) { ContributedProcessorDescriptor [ ] processors = getAssistProcessors ( ) ; SafeAssistCollector collector = new SafeAssistCollector ( context , locations , proposals ) ; collector . process ( processors ) ; return collector . getStatus ( ) ; } public String getErrorMessage ( ) { return fErrorMessage ; } public boolean canFix ( Annotation annotation ) { return hasCorrections ( annotation ) ; } public boolean canAssist ( IQuickAssistInvocationContext invocationContext ) { if ( invocationContext instanceof IInvocationContext ) return hasAssists ( ( IInvocationContext ) invocationContext ) ; return false ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; public class HashSyntaxCorrectionProposal extends CUCorrectionProposal { private static final String NAME = "" ; private IInvocationContext context ; private IProblemLocation problem ; public HashSyntaxCorrectionProposal ( IInvocationContext context , IProblemLocation problem , int relevance ) { super ( NAME , context . getRubyScript ( ) , relevance , RubyUI . getSharedImages ( ) . getImage ( org . rubypeople . rdt . ui . ISharedImages . IMG_OBJS_CORRECTION_CHANGE ) ) ; this . context = context ; this . problem = problem ; } @ Override protected void addEdits ( IDocument document , TextEdit editRoot ) throws CoreException { String src = getRubyScript ( ) . getSource ( ) ; ArrayNode covering = ( ArrayNode ) problem . getCoveringNode ( context . getASTRoot ( ) ) ; List < Node > children = covering . childNodes ( ) ; for ( int i = ; i < children . size ( ) ; i += ) { if ( children . size ( ) <= ( + ) ) break ; Node key = children . get ( i ) ; if ( key == null ) continue ; Node value = children . get ( i + ) ; if ( value == null ) continue ; ISourcePosition pos = key . getPosition ( ) ; String between = src . substring ( pos . getEndOffset ( ) , value . getPosition ( ) . getStartOffset ( ) ) ; String corrected = "" ; if ( ! between . startsWith ( "" ) ) corrected += "" ; corrected += "" ; if ( ! between . endsWith ( "" ) ) corrected += "" ; ReplaceEdit edit = new ReplaceEdit ( pos . getEndOffset ( ) + between . indexOf ( "" ) , , corrected ) ; editRoot . addChild ( edit ) ; } } } package org . rubypeople . rdt . internal . ui . text . correction ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Iterator ; import org . eclipse . core . commands . AbstractHandler ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . jface . bindings . TriggerSequence ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension2 ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . keys . IBindingService ; import org . eclipse . ui . texteditor . ITextEditor ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . correction . ICommandAccess ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; public class CorrectionCommandHandler extends AbstractHandler { private final ITextEditor fEditor ; private final String fId ; private final boolean fIsAssist ; public CorrectionCommandHandler ( ITextEditor editor , String id , boolean isAssist ) { fEditor = editor ; fId = id ; fIsAssist = isAssist ; } public Object execute ( ExecutionEvent event ) throws ExecutionException { ISelection selection = fEditor . getSelectionProvider ( ) . getSelection ( ) ; IRubyScript cu = RubyUI . getWorkingCopyManager ( ) . getWorkingCopy ( fEditor . getEditorInput ( ) ) ; IAnnotationModel model = RubyUI . getDocumentProvider ( ) . getAnnotationModel ( fEditor . getEditorInput ( ) ) ; if ( selection instanceof ITextSelection && cu != null && model != null ) { ICompletionProposal proposal = findCorrection ( fId , fIsAssist , ( ITextSelection ) selection , cu , model ) ; if ( proposal != null ) { invokeProposal ( proposal , ( ( ITextSelection ) selection ) . getOffset ( ) ) ; } } return null ; } private ICompletionProposal findCorrection ( String id , boolean isAssist , ITextSelection selection , IRubyScript cu , IAnnotationModel model ) { AssistContext context = new AssistContext ( cu , selection . getOffset ( ) , selection . getLength ( ) ) ; Collection proposals = new ArrayList ( ) ; if ( isAssist ) { RubyCorrectionProcessor . collectAssists ( context , new ProblemLocation [ ] , proposals ) ; } else { try { boolean goToClosest = selection . getLength ( ) == ; Annotation [ ] annotations = getAnnotations ( selection . getOffset ( ) , goToClosest ) ; RubyCorrectionProcessor . collectProposals ( context , model , annotations , true , false , proposals ) ; } catch ( BadLocationException e ) { return null ; } } for ( Iterator iter = proposals . iterator ( ) ; iter . hasNext ( ) ; ) { Object curr = iter . next ( ) ; if ( curr instanceof ICommandAccess ) { if ( id . equals ( ( ( ICommandAccess ) curr ) . getCommandId ( ) ) ) { return ( ICompletionProposal ) curr ; } } } return null ; } private Annotation [ ] getAnnotations ( int offset , boolean goToClosest ) throws BadLocationException { ArrayList resultingAnnotations = new ArrayList ( ) ; RubyCorrectionAssistant . collectQuickFixableAnnotations ( fEditor , offset , goToClosest , resultingAnnotations ) ; return ( Annotation [ ] ) resultingAnnotations . toArray ( new Annotation [ resultingAnnotations . size ( ) ] ) ; } private ICompletionProposal getLocalRenameProposal ( IInvocationContext context ) { Node node = context . getCoveredNode ( ) ; return null ; } private ITextViewer getTextViewer ( ) { if ( fEditor instanceof RubyEditor ) { return ( ( RubyEditor ) fEditor ) . getViewer ( ) ; } return null ; } private IDocument getDocument ( ) { return RubyUI . getDocumentProvider ( ) . getDocument ( fEditor . getEditorInput ( ) ) ; } private void invokeProposal ( ICompletionProposal proposal , int offset ) { if ( proposal instanceof ICompletionProposalExtension2 ) { ITextViewer viewer = getTextViewer ( ) ; if ( viewer != null ) { ( ( ICompletionProposalExtension2 ) proposal ) . apply ( viewer , ( char ) , , offset ) ; return ; } } else if ( proposal instanceof ICompletionProposalExtension ) { IDocument document = getDocument ( ) ; if ( document != null ) { ( ( ICompletionProposalExtension ) proposal ) . apply ( document , ( char ) , offset ) ; return ; } } IDocument document = getDocument ( ) ; if ( document != null ) { proposal . apply ( document ) ; } } public static String getShortCutString ( String proposalId ) { if ( proposalId != null ) { IBindingService bindingService = ( IBindingService ) PlatformUI . getWorkbench ( ) . getAdapter ( IBindingService . class ) ; if ( bindingService != null ) { TriggerSequence [ ] activeBindingsFor = bindingService . getActiveBindingsFor ( proposalId ) ; if ( activeBindingsFor . length > ) { return activeBindingsFor [ ] . format ( ) ; } } } return null ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; public class AssistContext implements IInvocationContext { private IRubyScript fRubyScript ; private int fOffset ; private int fLength ; private RootNode fASTRoot ; public AssistContext ( IRubyScript cu , int offset , int length ) { fRubyScript = cu ; fOffset = offset ; fLength = length ; fASTRoot = null ; } public IRubyScript getRubyScript ( ) { return fRubyScript ; } public int getSelectionLength ( ) { return fLength ; } public int getSelectionOffset ( ) { return fOffset ; } public RootNode getASTRoot ( ) { if ( fASTRoot == null ) { fASTRoot = ( RootNode ) ASTProvider . getASTProvider ( ) . getAST ( fRubyScript , ASTProvider . WAIT_YES , null ) ; } return fASTRoot ; } public void setASTRoot ( RootNode root ) { fASTRoot = root ; } public Node getCoveringNode ( ) { return ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( getASTRoot ( ) , fOffset , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return true ; } } ) ; } public Node getCoveredNode ( ) { return OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( getASTRoot ( ) , fOffset ) ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import org . eclipse . compare . rangedifferencer . IRangeComparator ; import org . eclipse . compare . rangedifferencer . RangeDifference ; import org . eclipse . compare . rangedifferencer . RangeDifferencer ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . DocumentChange ; import org . eclipse . ltk . core . refactoring . TextChange ; import org . eclipse . ltk . core . refactoring . TextFileChange ; import org . eclipse . ltk . internal . core . refactoring . Resources ; import org . eclipse . swt . graphics . Image ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . TextEdit ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . codemanipulation . StubUtility ; import org . rubypeople . rdt . internal . corext . refactoring . changes . RubyScriptChange ; import org . rubypeople . rdt . internal . corext . util . Strings ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIStatus ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . correction . ChangeCorrectionProposal ; public class CUCorrectionProposal extends ChangeCorrectionProposal { private IRubyScript fRubyScript ; public CUCorrectionProposal ( String name , IRubyScript cu , TextChange change , int relevance , Image image ) { super ( name , change , relevance , image ) ; if ( cu == null ) { throw new IllegalArgumentException ( "" ) ; } fRubyScript = cu ; } protected CUCorrectionProposal ( String name , IRubyScript cu , int relevance , Image image ) { this ( name , cu , null , relevance , image ) ; } protected void addEdits ( IDocument document , TextEdit editRoot ) throws CoreException { if ( false ) { throw new CoreException ( RubyUIStatus . createError ( IStatus . ERROR , "" , null ) ) ; } } public String getAdditionalProposalInfo ( ) { StringBuffer buf = new StringBuffer ( ) ; return buf . toString ( ) ; } private final int surroundLines = ; private void appendContent ( IDocument text , int startOffset , int endOffset , StringBuffer buf , boolean surroundLinesOnly ) throws BadLocationException { int startLine = text . getLineOfOffset ( startOffset ) ; int endLine = text . getLineOfOffset ( endOffset ) ; boolean dotsAdded = false ; if ( surroundLinesOnly && startOffset == ) { startLine = Math . max ( endLine - surroundLines , ) ; buf . append ( "" ) ; dotsAdded = true ; } for ( int i = startLine ; i <= endLine ; i ++ ) { if ( surroundLinesOnly ) { if ( ( i - startLine > surroundLines ) && ( endLine - i > surroundLines ) ) { if ( ! dotsAdded ) { buf . append ( "" ) ; dotsAdded = true ; } else if ( endOffset == text . getLength ( ) ) { return ; } continue ; } } IRegion lineInfo = text . getLineInformation ( i ) ; int start = lineInfo . getOffset ( ) ; int end = start + lineInfo . getLength ( ) ; int from = Math . max ( start , startOffset ) ; int to = Math . min ( end , endOffset ) ; String content = text . get ( from , to - from ) ; if ( surroundLinesOnly && ( from == start ) && Strings . containsOnlyWhitespaces ( content ) ) { continue ; } for ( int k = ; k < content . length ( ) ; k ++ ) { char ch = content . charAt ( k ) ; if ( ch == '' ) { buf . append ( "" ) ; } else if ( ch == '>' ) { buf . append ( "" ) ; } else { buf . append ( ch ) ; } } if ( to == end && to != endOffset ) { buf . append ( "" ) ; } } } public void apply ( IDocument document ) { try { IRubyScript unit = getRubyScript ( ) ; IEditorPart part = null ; if ( unit . getResource ( ) . exists ( ) ) { boolean canEdit = performValidateEdit ( unit ) ; if ( ! canEdit ) { return ; } part = EditorUtility . isOpenInEditor ( unit ) ; if ( part == null ) { part = EditorUtility . openInEditor ( unit , true ) ; if ( part != null ) { document = RubyUI . getDocumentProvider ( ) . getDocument ( part . getEditorInput ( ) ) ; } } IWorkbenchPage page = RubyPlugin . getActivePage ( ) ; if ( page != null && part != null ) { page . bringToTop ( part ) ; } if ( part != null ) { part . setFocus ( ) ; } } performChange ( part , document ) ; } catch ( CoreException e ) { ExceptionHandler . handle ( e , CorrectionMessages . CUCorrectionProposal_error_title , CorrectionMessages . CUCorrectionProposal_error_message ) ; } } private boolean performValidateEdit ( IRubyScript unit ) { IStatus status = Resources . makeCommittable ( unit . getResource ( ) , RubyPlugin . getActiveWorkbenchShell ( ) ) ; if ( ! status . isOK ( ) ) { String label = CorrectionMessages . CUCorrectionProposal_error_title ; String message = CorrectionMessages . CUCorrectionProposal_error_message ; ErrorDialog . openError ( RubyPlugin . getActiveWorkbenchShell ( ) , label , message , status ) ; return false ; } return true ; } protected TextChange createTextChange ( ) throws CoreException { IRubyScript cu = getRubyScript ( ) ; String name = getDisplayString ( ) ; TextChange change ; if ( ! cu . getResource ( ) . exists ( ) ) { String source ; try { source = cu . getSource ( ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; source = new String ( ) ; } Document document = new Document ( source ) ; document . setInitialLineDelimiter ( StubUtility . getLineDelimiterUsed ( cu ) ) ; change = new DocumentChange ( name , document ) ; } else { RubyScriptChange cuChange = new RubyScriptChange ( name , cu ) ; cuChange . setSaveMode ( TextFileChange . LEAVE_DIRTY ) ; change = cuChange ; } TextEdit rootEdit = new MultiTextEdit ( ) ; change . setEdit ( rootEdit ) ; IDocument document = change . getCurrentDocument ( new NullProgressMonitor ( ) ) ; addEdits ( document , rootEdit ) ; return change ; } protected final Change createChange ( ) throws CoreException { return createTextChange ( ) ; } public final TextChange getTextChange ( ) throws CoreException { return ( TextChange ) getChange ( ) ; } public final IRubyScript getRubyScript ( ) { return fRubyScript ; } public String getPreviewContent ( ) throws CoreException { return getTextChange ( ) . getPreviewContent ( new NullProgressMonitor ( ) ) ; } public String toString ( ) { try { return getPreviewContent ( ) ; } catch ( CoreException e ) { } return super . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . expressions . EvaluationContext ; import org . eclipse . core . expressions . EvaluationResult ; import org . eclipse . core . expressions . Expression ; import org . eclipse . core . expressions . ExpressionConverter ; import org . eclipse . core . expressions . ExpressionTagNames ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IStatus ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; public final class ContributedProcessorDescriptor { private final IConfigurationElement fConfigurationElement ; private Object fProcessorInstance ; private Boolean fStatus ; private boolean fLastResult ; private final Set fHandledMarkerTypes ; private static final String ID = "" ; private static final String CLASS = "" ; private static final String HANDLED_MARKER_TYPES = "" ; private static final String MARKER_TYPE = "" ; public ContributedProcessorDescriptor ( IConfigurationElement element , boolean testMarkerTypes ) { fConfigurationElement = element ; fProcessorInstance = null ; fStatus = null ; if ( fConfigurationElement . getChildren ( ExpressionTagNames . ENABLEMENT ) . length == ) { fStatus = Boolean . TRUE ; } fHandledMarkerTypes = testMarkerTypes ? getHandledMarkerTypes ( element ) : null ; } private Set getHandledMarkerTypes ( IConfigurationElement element ) { HashSet map = new HashSet ( ) ; IConfigurationElement [ ] children = element . getChildren ( HANDLED_MARKER_TYPES ) ; for ( int i = ; i < children . length ; i ++ ) { IConfigurationElement [ ] types = children [ i ] . getChildren ( MARKER_TYPE ) ; for ( int k = ; k < types . length ; k ++ ) { String attribute = types [ k ] . getAttribute ( ID ) ; if ( attribute != null ) { map . add ( attribute ) ; } } } if ( map . isEmpty ( ) ) { map . add ( IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER ) ; map . add ( IRubyModelMarker . BUILDPATH_PROBLEM_MARKER ) ; map . add ( IRubyModelMarker . TASK_MARKER ) ; } return map ; } public IStatus checkSyntax ( ) { IConfigurationElement [ ] children = fConfigurationElement . getChildren ( ExpressionTagNames . ENABLEMENT ) ; if ( children . length > ) { String id = fConfigurationElement . getAttribute ( ID ) ; return new StatusInfo ( IStatus . ERROR , "" + id ) ; } return new StatusInfo ( IStatus . OK , "" ) ; } private boolean matches ( IRubyScript cunit ) { if ( fStatus != null ) { return fStatus . booleanValue ( ) ; } IConfigurationElement [ ] children = fConfigurationElement . getChildren ( ExpressionTagNames . ENABLEMENT ) ; if ( children . length == ) { try { ExpressionConverter parser = ExpressionConverter . getDefault ( ) ; Expression expression = parser . perform ( children [ ] ) ; EvaluationContext evalContext = new EvaluationContext ( null , cunit ) ; evalContext . addVariable ( "" , cunit ) ; IRubyProject javaProject = cunit . getRubyProject ( ) ; String [ ] natures = javaProject . getProject ( ) . getDescription ( ) . getNatureIds ( ) ; evalContext . addVariable ( "" , Arrays . asList ( natures ) ) ; fLastResult = ! ( expression . evaluate ( evalContext ) != EvaluationResult . TRUE ) ; return fLastResult ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } fStatus = Boolean . FALSE ; return false ; } public Object getProcessor ( IRubyScript cunit ) throws CoreException { if ( matches ( cunit ) ) { if ( fProcessorInstance == null ) { fProcessorInstance = fConfigurationElement . createExecutableExtension ( CLASS ) ; } return fProcessorInstance ; } return null ; } public boolean canHandleMarkerType ( String markerType ) { return fHandledMarkerTypes == null || fHandledMarkerTypes . contains ( markerType ) ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyAnnotation ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyMarkerAnnotation ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; public class ProblemLocation implements IProblemLocation { private final int fId ; private final String [ ] fArguments ; private final int fOffset ; private final int fLength ; private final boolean fIsError ; private final String fMarkerType ; public ProblemLocation ( int offset , int length , IRubyAnnotation annotation ) { fId = annotation . getId ( ) ; fArguments = annotation . getArguments ( ) ; fOffset = offset ; fLength = length ; fIsError = RubyMarkerAnnotation . ERROR_ANNOTATION_TYPE . equals ( annotation . getType ( ) ) ; String markerType = annotation . getMarkerType ( ) ; fMarkerType = markerType != null ? markerType : IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER ; } public ProblemLocation ( int offset , int length , int id , String [ ] arguments , boolean isError , String markerType ) { fId = id ; fArguments = arguments ; fOffset = offset ; fLength = length ; fIsError = isError ; fMarkerType = markerType ; } public ProblemLocation ( IProblem problem ) { fId = problem . getID ( ) ; fArguments = problem . getArguments ( ) ; fOffset = problem . getSourceStart ( ) ; fLength = problem . getSourceEnd ( ) - fOffset + ; fIsError = problem . isError ( ) ; fMarkerType = problem instanceof CategorizedProblem ? ( ( CategorizedProblem ) problem ) . getMarkerType ( ) : IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER ; } public int getProblemId ( ) { return fId ; } public String [ ] getProblemArguments ( ) { return fArguments ; } public int getLength ( ) { return fLength ; } public int getOffset ( ) { return fOffset ; } public boolean isError ( ) { return fIsError ; } public String getMarkerType ( ) { return fMarkerType ; } public Node getCoveringNode ( RootNode astRoot ) { return ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( astRoot , fOffset - , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node . getPosition ( ) . getEndOffset ( ) >= fOffset + fLength ; } } ) ; } public Node getCoveredNode ( RootNode astRoot ) { return ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( astRoot , fOffset , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node . getPosition ( ) . getEndOffset ( ) >= fOffset + fLength ; } } ) ; } public String toString ( ) { StringBuffer buf = new StringBuffer ( ) ; buf . append ( "" ) . append ( getErrorCode ( fId ) ) . append ( '' ) ; buf . append ( '' ) . append ( fOffset ) . append ( "" ) . append ( fLength ) . append ( '' ) . append ( '' ) ; return buf . toString ( ) ; } private String getErrorCode ( int code ) { StringBuffer buf = new StringBuffer ( ) ; if ( ( code & IProblem . TypeRelated ) != ) { buf . append ( "" ) ; } if ( ( code & IProblem . FieldRelated ) != ) { buf . append ( "" ) ; } if ( ( code & IProblem . ConstructorRelated ) != ) { buf . append ( "" ) ; } if ( ( code & IProblem . MethodRelated ) != ) { buf . append ( "" ) ; } if ( ( code & IProblem . ImportRelated ) != ) { buf . append ( "" ) ; } if ( ( code & IProblem . Internal ) != ) { buf . append ( "" ) ; } if ( ( code & IProblem . Syntax ) != ) { buf . append ( "" ) ; } buf . append ( code & IProblem . IgnoreCategoriesMask ) ; return buf . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import java . util . ArrayList ; import java . util . Iterator ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . quickassist . IQuickAssistAssistant ; import org . eclipse . jface . text . quickassist . QuickAssistAssistant ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . util . Assert ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . internal . ui . text . HTMLTextPresenter ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . IColorManager ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class RubyCorrectionAssistant extends QuickAssistAssistant { private ITextViewer fViewer ; private ITextEditor fEditor ; private Position fPosition ; private Annotation [ ] fCurrentAnnotations ; private QuickAssistLightBulbUpdater fLightBulbUpdater ; public RubyCorrectionAssistant ( ITextEditor editor ) { super ( ) ; Assert . isNotNull ( editor ) ; fEditor = editor ; RubyCorrectionProcessor processor = new RubyCorrectionProcessor ( this ) ; setQuickAssistProcessor ( processor ) ; setInformationControlCreator ( getInformationControlCreator ( ) ) ; RubyTextTools textTools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; IColorManager manager = textTools . getColorManager ( ) ; IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; Color c = getColor ( store , PreferenceConstants . CODEASSIST_PROPOSALS_FOREGROUND , manager ) ; setProposalSelectorForeground ( c ) ; c = getColor ( store , PreferenceConstants . CODEASSIST_PROPOSALS_BACKGROUND , manager ) ; setProposalSelectorBackground ( c ) ; } public IEditorPart getEditor ( ) { return fEditor ; } private IInformationControlCreator getInformationControlCreator ( ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { return new DefaultInformationControl ( parent , new HTMLTextPresenter ( ) ) ; } } ; } private static Color getColor ( IPreferenceStore store , String key , IColorManager manager ) { RGB rgb = PreferenceConverter . getColor ( store , key ) ; return manager . getColor ( rgb ) ; } public void install ( ISourceViewer sourceViewer ) { super . install ( sourceViewer ) ; fViewer = sourceViewer ; fLightBulbUpdater = new QuickAssistLightBulbUpdater ( fEditor , sourceViewer ) ; fLightBulbUpdater . install ( ) ; } public void uninstall ( ) { if ( fLightBulbUpdater != null ) { fLightBulbUpdater . uninstall ( ) ; fLightBulbUpdater = null ; } super . uninstall ( ) ; } public String showPossibleQuickAssists ( ) { fPosition = null ; fCurrentAnnotations = null ; if ( fViewer == null || fViewer . getDocument ( ) == null ) return super . showPossibleQuickAssists ( ) ; ArrayList resultingAnnotations = new ArrayList ( ) ; try { Point selectedRange = fViewer . getSelectedRange ( ) ; int currOffset = selectedRange . x ; int currLength = selectedRange . y ; boolean goToClosest = ( currLength == ) ; int newOffset = collectQuickFixableAnnotations ( fEditor , currOffset , goToClosest , resultingAnnotations ) ; if ( newOffset != currOffset ) { storePosition ( currOffset , currLength ) ; fViewer . setSelectedRange ( newOffset , ) ; fViewer . revealRange ( newOffset , ) ; } } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; } fCurrentAnnotations = ( Annotation [ ] ) resultingAnnotations . toArray ( new Annotation [ resultingAnnotations . size ( ) ] ) ; return super . showPossibleQuickAssists ( ) ; } private static IRegion getRegionOfInterest ( ITextEditor editor , int invocationLocation ) throws BadLocationException { IDocumentProvider documentProvider = editor . getDocumentProvider ( ) ; if ( documentProvider == null ) { return null ; } IDocument document = documentProvider . getDocument ( editor . getEditorInput ( ) ) ; if ( document == null ) { return null ; } return document . getLineInformationOfOffset ( invocationLocation ) ; } public static int collectQuickFixableAnnotations ( ITextEditor editor , int invocationLocation , boolean goToClosest , ArrayList resultingAnnotations ) throws BadLocationException { IAnnotationModel model = RubyUI . getDocumentProvider ( ) . getAnnotationModel ( editor . getEditorInput ( ) ) ; if ( model == null ) { return invocationLocation ; } ensureUpdatedAnnotations ( editor ) ; Iterator iter = model . getAnnotationIterator ( ) ; if ( goToClosest ) { IRegion lineInfo = getRegionOfInterest ( editor , invocationLocation ) ; if ( lineInfo == null ) { return invocationLocation ; } int rangeStart = lineInfo . getOffset ( ) ; int rangeEnd = rangeStart + lineInfo . getLength ( ) ; ArrayList allAnnotations = new ArrayList ( ) ; ArrayList allPositions = new ArrayList ( ) ; int bestOffset = Integer . MAX_VALUE ; while ( iter . hasNext ( ) ) { Annotation annot = ( Annotation ) iter . next ( ) ; if ( RubyCorrectionProcessor . isQuickFixableType ( annot ) ) { Position pos = model . getPosition ( annot ) ; if ( pos != null && isInside ( pos . offset , rangeStart , rangeEnd ) ) { allAnnotations . add ( annot ) ; allPositions . add ( pos ) ; bestOffset = processAnnotation ( annot , pos , invocationLocation , bestOffset ) ; } } } if ( bestOffset == Integer . MAX_VALUE ) { return invocationLocation ; } for ( int i = ; i < allPositions . size ( ) ; i ++ ) { Position pos = ( Position ) allPositions . get ( i ) ; if ( isInside ( bestOffset , pos . offset , pos . offset + pos . length ) ) { resultingAnnotations . add ( allAnnotations . get ( i ) ) ; } } return bestOffset ; } else { while ( iter . hasNext ( ) ) { Annotation annot = ( Annotation ) iter . next ( ) ; if ( RubyCorrectionProcessor . isQuickFixableType ( annot ) ) { Position pos = model . getPosition ( annot ) ; if ( pos != null && isInside ( invocationLocation , pos . offset , pos . offset + pos . length ) ) { resultingAnnotations . add ( annot ) ; } } } return invocationLocation ; } } private static void ensureUpdatedAnnotations ( ITextEditor editor ) { Object inputElement = editor . getEditorInput ( ) . getAdapter ( IRubyElement . class ) ; if ( inputElement instanceof IRubyScript ) { RubyPlugin . getDefault ( ) . getASTProvider ( ) . getAST ( ( IRubyScript ) inputElement , ASTProvider . WAIT_ACTIVE_ONLY , null ) ; } } private static int processAnnotation ( Annotation annot , Position pos , int invocationLocation , int bestOffset ) { int posBegin = pos . offset ; int posEnd = posBegin + pos . length ; if ( isInside ( invocationLocation , posBegin , posEnd ) ) { return invocationLocation ; } else if ( bestOffset != invocationLocation ) { int newClosestPosition = computeBestOffset ( posBegin , invocationLocation , bestOffset ) ; if ( newClosestPosition != - ) { if ( newClosestPosition != bestOffset ) { if ( RubyCorrectionProcessor . hasCorrections ( annot ) ) { return newClosestPosition ; } } } } return bestOffset ; } private static boolean isInside ( int offset , int start , int end ) { return offset == start || ( offset > start && offset < end ) ; } private static int computeBestOffset ( int newOffset , int invocationLocation , int bestOffset ) { if ( newOffset <= invocationLocation ) { if ( bestOffset > invocationLocation ) { return newOffset ; } else if ( bestOffset <= newOffset ) { return newOffset ; } return - ; } if ( newOffset <= bestOffset ) return newOffset ; return - ; } protected void possibleCompletionsClosed ( ) { super . possibleCompletionsClosed ( ) ; restorePosition ( ) ; } private void storePosition ( int currOffset , int currLength ) { fPosition = new Position ( currOffset , currLength ) ; } private void restorePosition ( ) { if ( fPosition != null && ! fPosition . isDeleted ( ) && fViewer . getDocument ( ) != null ) { fViewer . setSelectedRange ( fPosition . offset , fPosition . length ) ; fViewer . revealRange ( fPosition . offset , fPosition . length ) ; } fPosition = null ; } public boolean isUpdatedOffset ( ) { return fPosition != null ; } public Annotation [ ] getAnnotationsAtOffset ( ) { return fCurrentAnnotations ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import org . eclipse . osgi . util . NLS ; public class CorrectionMessages extends NLS { private static final String BUNDLE_NAME = CorrectionMessages . class . getName ( ) ; public static String RubyCorrectionProcessor_error_status ; public static String RubyCorrectionProcessor_error_quickfix_message ; public static String MarkerResolutionProposal_additionaldesc ; public static String ChangeCorrectionProposal_error_title ; public static String ChangeCorrectionProposal_error_message ; public static String ChangeCorrectionProposal_name_with_shortcut ; public static String CUCorrectionProposal_error_title ; public static String CUCorrectionProposal_error_message ; public static String NoCorrectionProposal_description ; public static String RubyCorrectionProcessor_error_quickassist_message ; static { NLS . initializeMessages ( BUNDLE_NAME , CorrectionMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . ui . IMarkerResolution ; import org . eclipse . ui . IMarkerResolution2 ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class MarkerResolutionProposal implements IRubyCompletionProposal { private IMarkerResolution fResolution ; private IMarker fMarker ; public MarkerResolutionProposal ( IMarkerResolution resolution , IMarker marker ) { fResolution = resolution ; fMarker = marker ; } public void apply ( IDocument document ) { fResolution . run ( fMarker ) ; } public String getAdditionalProposalInfo ( ) { if ( fResolution instanceof IMarkerResolution2 ) { return ( ( IMarkerResolution2 ) fResolution ) . getDescription ( ) ; } try { String problemDesc = ( String ) fMarker . getAttribute ( IMarker . MESSAGE ) ; return Messages . format ( CorrectionMessages . MarkerResolutionProposal_additionaldesc , problemDesc ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } return null ; } public IContextInformation getContextInformation ( ) { return null ; } public String getDisplayString ( ) { return fResolution . getLabel ( ) ; } public Image getImage ( ) { if ( fResolution instanceof IMarkerResolution2 ) { return ( ( IMarkerResolution2 ) fResolution ) . getImage ( ) ; } return RubyPluginImages . get ( RubyPluginImages . IMG_CORRECTION_CHANGE ) ; } public int getRelevance ( ) { return ; } public Point getSelection ( IDocument document ) { return null ; } } package org . rubypeople . rdt . internal . ui . text . correction ; public interface IStatusLineProposal { public String getStatusMessage ( ) ; } package org . rubypeople . rdt . internal . ui . text . correction ; import java . util . Iterator ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . ui . IFileEditorInput ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . core . parser . MarkerUtility ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyAnnotation ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class IgnoreWarningProposal implements IRubyCompletionProposal { private IProblemLocation problem ; private IInvocationContext context ; public IgnoreWarningProposal ( IInvocationContext context , IProblemLocation problem ) { this . context = context ; this . problem = problem ; } public int getRelevance ( ) { return ; } public void apply ( IDocument document ) { try { IRubyScript script = context . getRubyScript ( ) ; IFileEditorInput editorInput = ( IFileEditorInput ) EditorUtility . getEditorInput ( script ) ; IAnnotationModel anoteModel = RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) . getAnnotationModel ( editorInput ) ; Iterator iter = anoteModel . getAnnotationIterator ( ) ; while ( iter . hasNext ( ) ) { Annotation anote = ( Annotation ) iter . next ( ) ; if ( anote instanceof IRubyAnnotation ) { IRubyAnnotation markerAnote = ( IRubyAnnotation ) anote ; if ( markerAnote . getId ( ) != problem . getProblemId ( ) ) continue ; Position pos = anoteModel . getPosition ( anote ) ; if ( pos . getOffset ( ) != problem . getOffset ( ) ) continue ; if ( pos . getLength ( ) != problem . getLength ( ) ) continue ; anoteModel . removeAnnotation ( anote ) ; MarkerUtility . ignore ( script . getResource ( ) , problem . getProblemId ( ) , problem . getOffset ( ) , problem . getLength ( ) ) ; } } IResource resource = script . getUnderlyingResource ( ) ; IMarker [ ] markers = resource . findMarkers ( problem . getMarkerType ( ) , true , IResource . DEPTH_ZERO ) ; boolean needToRebuild = false ; for ( int i = ; i < markers . length ; i ++ ) { if ( ! MarkerUtility . markerMatches ( problem . getProblemId ( ) , problem . getOffset ( ) , problem . getOffset ( ) + problem . getLength ( ) , markers [ i ] ) ) continue ; MarkerUtility . ignore ( markers [ i ] ) ; needToRebuild = true ; } if ( needToRebuild ) { resource . touch ( new NullProgressMonitor ( ) ) ; } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } public String getAdditionalProposalInfo ( ) { return null ; } public IContextInformation getContextInformation ( ) { return null ; } public String getDisplayString ( ) { return "" ; } public Image getImage ( ) { return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_LIGHTBULB ) ; } public Point getSelection ( IDocument document ) { return null ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import java . util . ConcurrentModificationException ; import java . util . Iterator ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationAccessExtension ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . IAnnotationPresentation ; import org . eclipse . jface . text . source . ImageUtilities ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Canvas ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . texteditor . AnnotationPreference ; import org . eclipse . ui . texteditor . ITextEditor ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . ISelectionListenerWithAST ; import org . rubypeople . rdt . internal . ui . viewsupport . SelectionListenerWithASTManager ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; public class QuickAssistLightBulbUpdater { public static class AssistAnnotation extends Annotation implements IAnnotationPresentation { private static final int LAYER ; static { Annotation annotation = new Annotation ( "" , false , null ) ; AnnotationPreference preference = EditorsUI . getAnnotationPreferenceLookup ( ) . getAnnotationPreference ( annotation ) ; if ( preference != null ) LAYER = preference . getPresentationLayer ( ) - ; else LAYER = IAnnotationAccessExtension . DEFAULT_LAYER ; } private Image fImage ; public AssistAnnotation ( ) { } public int getLayer ( ) { return LAYER ; } private Image getImage ( ) { if ( fImage == null ) { fImage = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_QUICK_ASSIST ) ; } return fImage ; } public void paint ( GC gc , Canvas canvas , Rectangle r ) { ImageUtilities . drawImage ( getImage ( ) , gc , canvas , r , SWT . CENTER , SWT . TOP ) ; } } private final Annotation fAnnotation ; private boolean fIsAnnotationShown ; private ITextEditor fEditor ; private ITextViewer fViewer ; private ISelectionListenerWithAST fListener ; private IPropertyChangeListener fPropertyChangeListener ; public QuickAssistLightBulbUpdater ( ITextEditor part , ITextViewer viewer ) { fEditor = part ; fViewer = viewer ; fAnnotation = new AssistAnnotation ( ) ; fIsAnnotationShown = false ; fPropertyChangeListener = null ; } public boolean isSetInPreferences ( ) { return PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . EDITOR_QUICKASSIST_LIGHTBULB ) ; } private void installSelectionListener ( ) { fListener = new ISelectionListenerWithAST ( ) { public void selectionChanged ( IEditorPart part , ITextSelection selection , RootNode astRoot ) { doSelectionChanged ( selection . getOffset ( ) , selection . getLength ( ) , astRoot ) ; } } ; SelectionListenerWithASTManager . getDefault ( ) . addListener ( fEditor , fListener ) ; } private void uninstallSelectionListener ( ) { if ( fListener != null ) { SelectionListenerWithASTManager . getDefault ( ) . removeListener ( fEditor , fListener ) ; fListener = null ; } IAnnotationModel model = getAnnotationModel ( ) ; if ( model != null ) { removeLightBulb ( model ) ; } } public void install ( ) { if ( isSetInPreferences ( ) ) { installSelectionListener ( ) ; } if ( fPropertyChangeListener == null ) { fPropertyChangeListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { doPropertyChanged ( event . getProperty ( ) ) ; } } ; PreferenceConstants . getPreferenceStore ( ) . addPropertyChangeListener ( fPropertyChangeListener ) ; } } public void uninstall ( ) { uninstallSelectionListener ( ) ; if ( fPropertyChangeListener != null ) { PreferenceConstants . getPreferenceStore ( ) . removePropertyChangeListener ( fPropertyChangeListener ) ; fPropertyChangeListener = null ; } } protected void doPropertyChanged ( String property ) { if ( property . equals ( PreferenceConstants . EDITOR_QUICKASSIST_LIGHTBULB ) ) { if ( isSetInPreferences ( ) ) { IRubyScript cu = getRubyScript ( ) ; if ( cu != null ) { installSelectionListener ( ) ; Point point = fViewer . getSelectedRange ( ) ; RootNode astRoot = ( RootNode ) ASTProvider . getASTProvider ( ) . getAST ( cu , ASTProvider . WAIT_ACTIVE_ONLY , null ) ; if ( astRoot != null ) { doSelectionChanged ( point . x , point . y , astRoot ) ; } } } else { uninstallSelectionListener ( ) ; } } } private IRubyScript getRubyScript ( ) { IRubyElement elem = RubyUI . getEditorInputRubyElement ( fEditor . getEditorInput ( ) ) ; if ( elem instanceof IRubyScript ) { return ( IRubyScript ) elem ; } return null ; } private IAnnotationModel getAnnotationModel ( ) { return RubyUI . getDocumentProvider ( ) . getAnnotationModel ( fEditor . getEditorInput ( ) ) ; } private IDocument getDocument ( ) { return RubyUI . getDocumentProvider ( ) . getDocument ( fEditor . getEditorInput ( ) ) ; } private void doSelectionChanged ( int offset , int length , RootNode astRoot ) { final IAnnotationModel model = getAnnotationModel ( ) ; final IRubyScript cu = getRubyScript ( ) ; if ( model == null || cu == null ) { return ; } final AssistContext context = new AssistContext ( cu , offset , length ) ; context . setASTRoot ( astRoot ) ; boolean hasQuickFix = hasQuickFixLightBulb ( model , context . getSelectionOffset ( ) ) ; if ( hasQuickFix ) { removeLightBulb ( model ) ; return ; } calculateLightBulb ( model , context ) ; } private void calculateLightBulb ( IAnnotationModel model , IInvocationContext context ) { boolean needsAnnotation = RubyCorrectionProcessor . hasAssists ( context ) ; if ( fIsAnnotationShown ) { model . removeAnnotation ( fAnnotation ) ; } if ( needsAnnotation ) { model . addAnnotation ( fAnnotation , new Position ( context . getSelectionOffset ( ) , context . getSelectionLength ( ) ) ) ; } fIsAnnotationShown = needsAnnotation ; } private void removeLightBulb ( IAnnotationModel model ) { synchronized ( this ) { if ( fIsAnnotationShown ) { model . removeAnnotation ( fAnnotation ) ; fIsAnnotationShown = false ; } } } private boolean hasQuickFixLightBulb ( IAnnotationModel model , int offset ) { try { IDocument document = getDocument ( ) ; if ( document == null ) { return false ; } int currLine = document . getLineOfOffset ( offset ) ; Iterator iter = model . getAnnotationIterator ( ) ; while ( iter . hasNext ( ) ) { Annotation annot = ( Annotation ) iter . next ( ) ; if ( RubyCorrectionProcessor . isQuickFixableType ( annot ) ) { Position pos = model . getPosition ( annot ) ; if ( pos != null ) { int startLine = document . getLineOfOffset ( pos . getOffset ( ) ) ; if ( startLine == currLine && RubyCorrectionProcessor . hasCorrections ( annot ) ) { return true ; } } } } } catch ( BadLocationException e ) { } catch ( IndexOutOfBoundsException e ) { } catch ( ConcurrentModificationException e ) { } return false ; } } package org . rubypeople . rdt . internal . ui . text . correction ; import java . io . StringWriter ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . swt . graphics . Image ; import org . eclipse . ui . ISharedImages ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . FormatHelper ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . correction . CorrectionProposal ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; import org . rubypeople . rdt . ui . text . ruby . IQuickFixProcessor ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class QuickFixProcessor implements IQuickFixProcessor { public IRubyCompletionProposal [ ] getCorrections ( IInvocationContext context , IProblemLocation [ ] locations ) throws CoreException { if ( locations == null || locations . length == ) { return null ; } HashSet < Integer > handledProblems = new HashSet < Integer > ( locations . length ) ; ArrayList < IRubyCompletionProposal > resultingCollections = new ArrayList < IRubyCompletionProposal > ( ) ; for ( int i = ; i < locations . length ; i ++ ) { IProblemLocation curr = locations [ i ] ; Integer id = new Integer ( curr . getProblemId ( ) ) ; if ( handledProblems . add ( id ) ) { process ( context , curr , resultingCollections ) ; } } return ( IRubyCompletionProposal [ ] ) resultingCollections . toArray ( new IRubyCompletionProposal [ resultingCollections . size ( ) ] ) ; } private void process ( IInvocationContext context , IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) throws CoreException { int id = problem . getProblemId ( ) ; if ( id == ) { return ; } switch ( id ) { case IProblem . UnusedPrivateMethod : case IProblem . UnusedPrivateField : case IProblem . LocalVariableIsNeverUsed : case IProblem . ArgumentIsNeverUsed : addUnusedMemberProposal ( context , problem , proposals ) ; break ; case IProblem . MultineCommentNotAtFirstColumn : addShiftMultilineCommentProposal ( context , problem , proposals ) ; break ; case IProblem . ParenthesizeArguments : addParenthesizeArgumentsProposal ( context , problem , proposals ) ; break ; case IProblem . HashCommaSyntax : addFixHashSyntaxProposal ( context , problem , proposals ) ; break ; case IProblem . ColonAfterWhenStatement : addFixWhenStatementProposal ( context , problem , proposals ) ; break ; default : addIgnoreWarningFix ( context , problem , proposals ) ; } } private void addFixWhenStatementProposal ( IInvocationContext context , IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) { String corrected = "" ; Image image = RubyUI . getSharedImages ( ) . getImage ( org . rubypeople . rdt . ui . ISharedImages . IMG_OBJS_CORRECTION_CHANGE ) ; CorrectionProposal proposal = new CorrectionProposal ( corrected , problem . getOffset ( ) , , image , "" , ) ; proposals . add ( proposal ) ; } private void addFixHashSyntaxProposal ( IInvocationContext context , IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) { HashSyntaxCorrectionProposal proposal = new HashSyntaxCorrectionProposal ( context , problem , ) ; proposals . add ( proposal ) ; } private void addIgnoreWarningFix ( IInvocationContext context , IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) { proposals . add ( new IgnoreWarningProposal ( context , problem ) ) ; } private void addParenthesizeArgumentsProposal ( IInvocationContext context , IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) throws RubyModelException { Image image = RubyPlugin . getDefault ( ) . getWorkbench ( ) . getSharedImages ( ) . getImage ( ISharedImages . IMG_TOOL_DELETE ) ; StringWriter out = new StringWriter ( ) ; String src = getSource ( context ) ; ReWriterContext config = new ReWriterContext ( out , getSource ( context ) , getFormatHelper ( ) ) ; ReWriteVisitor visitor = new ReWriteVisitor ( config ) ; Node covering = problem . getCoveredNode ( context . getASTRoot ( ) ) ; String corrected = ASTUtil . stringRepresentation ( covering ) + "" ; ISourcePosition pos = covering . getPosition ( ) ; covering . accept ( visitor ) ; corrected += out . toString ( ) + "" ; CorrectionProposal proposal = new CorrectionProposal ( corrected , pos . getStartOffset ( ) , corrected . length ( ) , image , "" , ) ; proposals . add ( proposal ) ; } private void addShiftMultilineCommentProposal ( IInvocationContext context , IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) throws RubyModelException { Image image = RubyPlugin . getDefault ( ) . getWorkbench ( ) . getSharedImages ( ) . getImage ( ISharedImages . IMG_TOOL_DELETE ) ; String contents = getSource ( context ) ; String doc = contents . substring ( problem . getOffset ( ) , problem . getOffset ( ) + problem . getLength ( ) ) ; String before = contents . substring ( , problem . getOffset ( ) ) ; int replaceOffset = before . lastIndexOf ( "" ) + ; int shift = problem . getOffset ( ) - replaceOffset ; String [ ] lines = doc . split ( "" ) ; String indent = "" ; for ( int i = ; i < shift ; i ++ ) { indent += "" ; } StringBuffer correctedDoc = new StringBuffer ( ) ; for ( int j = ; j < lines . length ; j ++ ) { String line = lines [ j ] ; if ( line . startsWith ( indent ) ) { line = line . substring ( indent . length ( ) ) ; } correctedDoc . append ( line ) ; } CorrectionProposal proposal = new CorrectionProposal ( correctedDoc . toString ( ) , replaceOffset , problem . getLength ( ) + shift , image , "" , ) ; proposals . add ( proposal ) ; } private String getSource ( IInvocationContext context ) throws RubyModelException { return context . getRubyScript ( ) . getBuffer ( ) . getContents ( ) ; } protected FormatHelper getFormatHelper ( ) { EditableFormatHelper helper = new EditableFormatHelper ( ) ; helper . setAlwaysParanthesizeMethodCalls ( true ) ; helper . setAlwaysParanthesizeMethodDefs ( true ) ; helper . setSpacesAroundHashAssignment ( true ) ; return helper ; } public boolean hasCorrections ( IRubyScript unit , int problemId ) { return true ; } public static void addUnusedMemberProposal ( IInvocationContext context , IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) { Image image = RubyPlugin . getDefault ( ) . getWorkbench ( ) . getSharedImages ( ) . getImage ( ISharedImages . IMG_TOOL_DELETE ) ; CorrectionProposal proposal = new CorrectionProposal ( "" , problem . getOffset ( ) , problem . getLength ( ) , image , "" , ) ; proposals . add ( proposal ) ; } } package org . rubypeople . rdt . internal . ui . text ; import java . io . IOException ; import java . io . Reader ; import java . io . StringReader ; import java . util . Iterator ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextPresentation ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . graphics . Drawable ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; public class HTMLTextPresenter implements DefaultInformationControl . IInformationPresenter , DefaultInformationControl . IInformationPresenterExtension { private static final String LINE_DELIM = System . getProperty ( "" , "" ) ; private int fCounter ; private boolean fEnforceUpperLineLimit ; public HTMLTextPresenter ( boolean enforceUpperLineLimit ) { super ( ) ; fEnforceUpperLineLimit = enforceUpperLineLimit ; } public HTMLTextPresenter ( ) { this ( true ) ; } protected Reader createReader ( String hoverInfo , TextPresentation presentation ) { return new HTML2TextReader ( new StringReader ( hoverInfo ) , presentation ) ; } protected void adaptTextPresentation ( TextPresentation presentation , int offset , int insertLength ) { int yoursStart = offset ; int yoursEnd = offset + insertLength - ; yoursEnd = Math . max ( yoursStart , yoursEnd ) ; Iterator e = presentation . getAllStyleRangeIterator ( ) ; while ( e . hasNext ( ) ) { StyleRange range = ( StyleRange ) e . next ( ) ; int myStart = range . start ; int myEnd = range . start + range . length - ; myEnd = Math . max ( myStart , myEnd ) ; if ( myEnd < yoursStart ) continue ; if ( myStart < yoursStart ) range . length += insertLength ; else range . start += insertLength ; } } private void append ( StringBuffer buffer , String string , TextPresentation presentation ) { int length = string . length ( ) ; buffer . append ( string ) ; if ( presentation != null ) adaptTextPresentation ( presentation , fCounter , length ) ; fCounter += length ; } private String getIndent ( String line ) { int length = line . length ( ) ; int i = ; while ( i < length && Character . isWhitespace ( line . charAt ( i ) ) ) ++ i ; return ( i == length ? line : line . substring ( , i ) ) + "" ; } public String updatePresentation ( Drawable drawable , String hoverInfo , TextPresentation presentation , int maxWidth , int maxHeight ) { if ( hoverInfo == null ) return null ; GC gc = new GC ( drawable ) ; try { StringBuffer buffer = new StringBuffer ( ) ; int maxNumberOfLines = Math . round ( maxHeight / gc . getFontMetrics ( ) . getHeight ( ) ) ; fCounter = ; LineBreakingReader reader = new LineBreakingReader ( createReader ( hoverInfo , presentation ) , gc , maxWidth ) ; boolean lastLineFormatted = false ; String lastLineIndent = null ; String line = reader . readLine ( ) ; boolean lineFormatted = reader . isFormattedLine ( ) ; boolean firstLineProcessed = false ; while ( line != null ) { if ( fEnforceUpperLineLimit && maxNumberOfLines <= ) break ; if ( firstLineProcessed ) { if ( ! lastLineFormatted ) append ( buffer , LINE_DELIM , null ) ; else { append ( buffer , LINE_DELIM , presentation ) ; if ( lastLineIndent != null ) append ( buffer , lastLineIndent , presentation ) ; } } append ( buffer , line , null ) ; firstLineProcessed = true ; lastLineFormatted = lineFormatted ; if ( ! lineFormatted ) lastLineIndent = null ; else if ( lastLineIndent == null ) lastLineIndent = getIndent ( line ) ; line = reader . readLine ( ) ; lineFormatted = reader . isFormattedLine ( ) ; maxNumberOfLines -- ; } if ( line != null && buffer . length ( ) > ) { append ( buffer , LINE_DELIM , lineFormatted ? presentation : null ) ; append ( buffer , RubyUIMessages . HTMLTextPresenter_ellipsis , presentation ) ; } return trim ( buffer , presentation ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; return null ; } finally { gc . dispose ( ) ; } } private String trim ( StringBuffer buffer , TextPresentation presentation ) { int length = buffer . length ( ) ; int end = length - ; while ( end >= && Character . isWhitespace ( buffer . charAt ( end ) ) ) -- end ; if ( end == - ) return "" ; if ( end < length - ) buffer . delete ( end + , length ) ; else end = length ; int start = ; while ( start < end && Character . isWhitespace ( buffer . charAt ( start ) ) ) ++ start ; buffer . delete ( , start ) ; presentation . setResultWindow ( new Region ( start , buffer . length ( ) ) ) ; return buffer . toString ( ) ; } public String updatePresentation ( Display display , String hoverInfo , TextPresentation presentation , int maxWidth , int maxHeight ) { return updatePresentation ( ( Drawable ) display , hoverInfo , presentation , maxWidth , maxHeight ) ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . reconciler . DirtyRegion ; import org . eclipse . jface . text . reconciler . IReconcilingStrategy ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . ruby . IProblemRequestorExtension ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyReconcilingStrategy ; import org . rubypeople . rdt . internal . ui . text . spelling . RubySpellingReconcileStrategy ; public class RubyCompositeReconcilingStrategy extends CompositeReconcilingStrategy { private ITextEditor fEditor ; private RubyReconcilingStrategy fRubyStrategy ; public RubyCompositeReconcilingStrategy ( ITextEditor editor , String documentPartitioning ) { fEditor = editor ; fRubyStrategy = new RubyReconcilingStrategy ( editor ) ; setReconcilingStrategies ( new IReconcilingStrategy [ ] { fRubyStrategy , new RubySpellingReconcileStrategy ( editor ) } ) ; } private IProblemRequestorExtension getProblemRequestorExtension ( ) { IDocumentProvider p = fEditor . getDocumentProvider ( ) ; if ( p == null ) { p = RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) ; } IAnnotationModel m = p . getAnnotationModel ( fEditor . getEditorInput ( ) ) ; if ( m instanceof IProblemRequestorExtension ) return ( IProblemRequestorExtension ) m ; return null ; } public void reconcile ( DirtyRegion dirtyRegion , IRegion subRegion ) { IProblemRequestorExtension e = getProblemRequestorExtension ( ) ; if ( e != null ) { try { e . beginReportingSequence ( ) ; super . reconcile ( dirtyRegion , subRegion ) ; } finally { e . endReportingSequence ( ) ; } } else { super . reconcile ( dirtyRegion , subRegion ) ; } } public void reconcile ( IRegion partition ) { IProblemRequestorExtension e = getProblemRequestorExtension ( ) ; if ( e != null ) { try { e . beginReportingSequence ( ) ; super . reconcile ( partition ) ; } finally { e . endReportingSequence ( ) ; } } else { super . reconcile ( partition ) ; } } public void notifyListeners ( boolean notify ) { fRubyStrategy . notifyListeners ( notify ) ; } public void initialReconcile ( ) { IProblemRequestorExtension e = getProblemRequestorExtension ( ) ; if ( e != null ) { try { e . beginReportingSequence ( ) ; super . initialReconcile ( ) ; } finally { e . endReportingSequence ( ) ; } } else { super . initialReconcile ( ) ; } } public void aboutToBeReconciled ( ) { fRubyStrategy . aboutToBeReconciled ( ) ; } } package org . rubypeople . rdt . internal . ui . text . hyperlinks ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . hyperlink . IHyperlink ; import org . eclipse . jface . text . hyperlink . IHyperlinkDetector ; import org . eclipse . ui . IEditorInput ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . text . hyperlinks . IHyperlinkProvider ; public class RubyHyperLinkDetector implements IHyperlinkDetector { public static final String RDT_UI_NAMESPACE = "" ; public static final String RDT_UI_HYPERLINKPROVIDER = "" ; private List fExtensions ; private final IEditorInput fEditorInput ; public RubyHyperLinkDetector ( IEditorInput editorInput ) { this . fEditorInput = editorInput ; } private IExtensionPoint [ ] getExtensionPoints ( ) { IExtensionRegistry reg = Platform . getExtensionRegistry ( ) ; return reg . getExtensionPoints ( RDT_UI_NAMESPACE ) ; } private List initExtensions ( ) { if ( fExtensions != null ) return fExtensions ; fExtensions = new ArrayList ( ) ; IExtensionPoint [ ] points = getExtensionPoints ( ) ; IExtensionPoint point = getExtensionPoint ( points ) ; if ( point != null ) { IExtension [ ] exts = point . getExtensions ( ) ; for ( int i = ; i < exts . length ; i ++ ) { IConfigurationElement [ ] elem = exts [ i ] . getConfigurationElements ( ) ; String attrs [ ] = elem [ ] . getAttributeNames ( ) ; try { Object tempProv = elem [ ] . createExecutableExtension ( "" ) ; if ( tempProv instanceof IHyperlinkProvider ) { IHyperlinkProvider prov = ( IHyperlinkProvider ) tempProv ; fExtensions . add ( prov ) ; } } catch ( Exception e ) { RubyPlugin . log ( e ) ; } } } return fExtensions ; } private IExtensionPoint getExtensionPoint ( IExtensionPoint [ ] points ) { for ( int i = ; i < points . length ; i ++ ) { IExtensionPoint currentPoint = points [ i ] ; String uniqueIdentifier = currentPoint . getUniqueIdentifier ( ) ; if ( uniqueIdentifier . endsWith ( RDT_UI_HYPERLINKPROVIDER ) ) { return currentPoint ; } } return null ; } public IHyperlink [ ] detectHyperlinks ( ITextViewer textViewer , IRegion region , boolean canShowMultipleHyperlinks ) { List extensions = initExtensions ( ) ; if ( extensions . isEmpty ( ) ) return null ; for ( int i = ; i < extensions . size ( ) ; i ++ ) { IHyperlinkProvider currentProvider = ( IHyperlinkProvider ) extensions . get ( i ) ; IHyperlink link = currentProvider . getHyperlink ( fEditorInput , textViewer , null , region , canShowMultipleHyperlinks ) ; if ( link != null ) { return new IHyperlink [ ] { link } ; } } return null ; } } package org . rubypeople . rdt . internal . ui . text . hyperlinks ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . text . hyperlink . IHyperlink ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . PartInitException ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . OpenActionUtil ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . RubyWordFinder ; import org . rubypeople . rdt . internal . ui . text . TextMessages ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; import org . rubypeople . rdt . ui . text . hyperlinks . IHyperlinkProvider ; public class RubyElementsHyperlinkProvider implements IHyperlinkProvider { public RubyElementsHyperlinkProvider ( ) { } class LazyRubyHyperlink implements IHyperlink { private IRegion fRegion ; private IRubyScript script ; public LazyRubyHyperlink ( IRubyScript script , IRegion region ) { fRegion = region ; this . script = script ; } public IRegion getHyperlinkRegion ( ) { return fRegion ; } public String getHyperlinkText ( ) { return null ; } public String getTypeLabel ( ) { return "" ; } public void open ( ) { try { IRubyElement [ ] elements = SelectionConverter . codeResolve ( script , fRegion . getOffset ( ) , fRegion . getLength ( ) ) ; if ( elements != null && elements . length > ) { if ( elements . length > ) { IRubyElement selected = OpenActionUtil . selectRubyElement ( elements , Display . getDefault ( ) . getActiveShell ( ) , TextMessages . RubyElementsHyperlinkProvider_SelectInstance , TextMessages . RubyElementsHyperlinkProvider_SelectDefinition_msg ) ; if ( selected != null ) OpenActionUtil . open ( selected , true ) ; } else { OpenActionUtil . open ( elements [ ] , true ) ; } } } catch ( PartInitException e ) { RubyPlugin . log ( e ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } } public IHyperlink getHyperlink ( IEditorInput input , ITextViewer textViewer , Node node , IRegion region , boolean canShowMultipleHyperlinks ) { if ( ! inCode ( textViewer , region ) ) return null ; IRegion newRegion = RubyWordFinder . findWord ( textViewer . getDocument ( ) , region . getOffset ( ) ) ; try { IWorkingCopyManager manager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; IRubyScript script = manager . getWorkingCopy ( input ) ; if ( script != null ) { String contents = textViewer . getDocument ( ) . get ( newRegion . getOffset ( ) , newRegion . getLength ( ) ) ; if ( Util . isOperator ( contents ) || Util . isKeyword ( contents ) ) { return null ; } return new LazyRubyHyperlink ( script , newRegion ) ; } } catch ( Exception e ) { RubyPlugin . log ( e ) ; } return null ; } private boolean inCode ( ITextViewer textViewer , IRegion region ) { try { ITypedRegion [ ] regions = TextUtilities . computePartitioning ( textViewer . getDocument ( ) , IRubyPartitions . RUBY_PARTITIONING , region . getOffset ( ) , region . getLength ( ) , false ) ; if ( regions == null ) return false ; for ( int i = ; i < regions . length ; i ++ ) { String type = regions [ i ] . getType ( ) ; if ( type . equals ( IDocument . DEFAULT_CONTENT_TYPE ) ) { return true ; } } } catch ( BadLocationException e1 ) { } return false ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . IDocument ; public interface IRubyPartitions { public final static String RUBY_PARTITIONING = "" ; String RUBY_DEFAULT = IDocument . DEFAULT_CONTENT_TYPE ; String RUBY_SINGLE_LINE_COMMENT = "" ; String RUBY_MULTI_LINE_COMMENT = "" ; String RUBY_REGULAR_EXPRESSION = "" ; String RUBY_STRING = "" ; String RUBY_COMMAND = "" ; } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . core . resources . IMarkerDelta ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . reconciler . DirtyRegion ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; public class RubyReconciler extends NotifyingReconciler { class ResourceChangeListener implements IResourceChangeListener { private IResource getResource ( ) { if ( fTextEditor == null ) return null ; IEditorInput input = fTextEditor . getEditorInput ( ) ; if ( input instanceof IFileEditorInput ) { IFileEditorInput fileInput = ( IFileEditorInput ) input ; return fileInput . getFile ( ) ; } return null ; } public void resourceChanged ( IResourceChangeEvent e ) { IResourceDelta delta = e . getDelta ( ) ; IResource resource = getResource ( ) ; if ( delta != null && resource != null ) { IResourceDelta child = delta . findMember ( resource . getFullPath ( ) ) ; if ( child != null ) { IMarkerDelta [ ] deltas = child . getMarkerDeltas ( ) ; if ( deltas . length > ) forceReconciling ( ) ; } } } } private Object fMutex ; private boolean fIninitalProcessDone = false ; private ResourceChangeListener fResourceChangeListener ; private ITextEditor fTextEditor ; public RubyReconciler ( ITextEditor editor , RubyCompositeReconcilingStrategy strategy , boolean isIncremental ) { super ( strategy , isIncremental ) ; this . fTextEditor = editor ; if ( editor instanceof RubyEditor ) fMutex = ( ( RubyEditor ) editor ) . getReconcilerLock ( ) ; else fMutex = new Object ( ) ; } protected void process ( DirtyRegion dirtyRegion ) { synchronized ( fMutex ) { super . process ( dirtyRegion ) ; } } public void install ( ITextViewer textViewer ) { super . install ( textViewer ) ; fResourceChangeListener = new ResourceChangeListener ( ) ; IWorkspace workspace = RubyCore . getWorkspace ( ) ; workspace . addResourceChangeListener ( fResourceChangeListener ) ; } protected void forceReconciling ( ) { if ( ! fIninitalProcessDone ) return ; super . forceReconciling ( ) ; RubyCompositeReconcilingStrategy strategy = ( RubyCompositeReconcilingStrategy ) getReconcilingStrategy ( IDocument . DEFAULT_CONTENT_TYPE ) ; strategy . notifyListeners ( false ) ; } protected void initialProcess ( ) { synchronized ( fMutex ) { super . initialProcess ( ) ; } fIninitalProcessDone = true ; } @ Override protected void reconcilerReset ( ) { super . reconcilerReset ( ) ; RubyCompositeReconcilingStrategy strategy = ( RubyCompositeReconcilingStrategy ) getReconcilingStrategy ( IDocument . DEFAULT_CONTENT_TYPE ) ; strategy . notifyListeners ( true ) ; } @ Override protected void aboutToBeReconciled ( ) { RubyCompositeReconcilingStrategy strategy = ( RubyCompositeReconcilingStrategy ) getReconcilingStrategy ( IDocument . DEFAULT_CONTENT_TYPE ) ; strategy . aboutToBeReconciled ( ) ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . ListenerList ; import org . eclipse . jface . util . PropertyChangeEvent ; public class PreferencesAdapter implements IPreferenceStore { private class PropertyChangeListener implements Preferences . IPropertyChangeListener { public void propertyChange ( Preferences . PropertyChangeEvent event ) { firePropertyChangeEvent ( event . getProperty ( ) , event . getOldValue ( ) , event . getNewValue ( ) ) ; } } private ListenerList fListeners = new ListenerList ( ) ; private PropertyChangeListener fListener = new PropertyChangeListener ( ) ; private Preferences fPreferences ; private boolean fSilent ; public PreferencesAdapter ( ) { this ( new Preferences ( ) ) ; } public PreferencesAdapter ( Preferences preferences ) { fPreferences = preferences ; } public void addPropertyChangeListener ( IPropertyChangeListener listener ) { if ( fListeners . size ( ) == ) fPreferences . addPropertyChangeListener ( fListener ) ; fListeners . add ( listener ) ; } public void removePropertyChangeListener ( IPropertyChangeListener listener ) { fListeners . remove ( listener ) ; if ( fListeners . size ( ) == ) fPreferences . removePropertyChangeListener ( fListener ) ; } public boolean contains ( String name ) { return fPreferences . contains ( name ) ; } public void firePropertyChangeEvent ( String name , Object oldValue , Object newValue ) { if ( ! fSilent ) { PropertyChangeEvent event = new PropertyChangeEvent ( this , name , oldValue , newValue ) ; Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) ( ( IPropertyChangeListener ) listeners [ i ] ) . propertyChange ( event ) ; } } public boolean getBoolean ( String name ) { return fPreferences . getBoolean ( name ) ; } public boolean getDefaultBoolean ( String name ) { return fPreferences . getDefaultBoolean ( name ) ; } public double getDefaultDouble ( String name ) { return fPreferences . getDefaultDouble ( name ) ; } public float getDefaultFloat ( String name ) { return fPreferences . getDefaultFloat ( name ) ; } public int getDefaultInt ( String name ) { return fPreferences . getDefaultInt ( name ) ; } public long getDefaultLong ( String name ) { return fPreferences . getDefaultLong ( name ) ; } public String getDefaultString ( String name ) { return fPreferences . getDefaultString ( name ) ; } public double getDouble ( String name ) { return fPreferences . getDouble ( name ) ; } public float getFloat ( String name ) { return fPreferences . getFloat ( name ) ; } public int getInt ( String name ) { return fPreferences . getInt ( name ) ; } public long getLong ( String name ) { return fPreferences . getLong ( name ) ; } public String getString ( String name ) { return fPreferences . getString ( name ) ; } public boolean isDefault ( String name ) { return fPreferences . isDefault ( name ) ; } public boolean needsSaving ( ) { return fPreferences . needsSaving ( ) ; } public void putValue ( String name , String value ) { try { fSilent = true ; fPreferences . setValue ( name , value ) ; } finally { fSilent = false ; } } public void setDefault ( String name , double value ) { fPreferences . setDefault ( name , value ) ; } public void setDefault ( String name , float value ) { fPreferences . setDefault ( name , value ) ; } public void setDefault ( String name , int value ) { fPreferences . setDefault ( name , value ) ; } public void setDefault ( String name , long value ) { fPreferences . setDefault ( name , value ) ; } public void setDefault ( String name , String defaultObject ) { fPreferences . setDefault ( name , defaultObject ) ; } public void setDefault ( String name , boolean value ) { fPreferences . setDefault ( name , value ) ; } public void setToDefault ( String name ) { fPreferences . setToDefault ( name ) ; } public void setValue ( String name , double value ) { fPreferences . setValue ( name , value ) ; } public void setValue ( String name , float value ) { fPreferences . setValue ( name , value ) ; } public void setValue ( String name , int value ) { fPreferences . setValue ( name , value ) ; } public void setValue ( String name , long value ) { fPreferences . setValue ( name , value ) ; } public void setValue ( String name , String value ) { fPreferences . setValue ( name , value ) ; } public void setValue ( String name , boolean value ) { fPreferences . setValue ( name , value ) ; } } package org . rubypeople . rdt . internal . ui . text ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . ui . text . IColorManager ; import org . rubypeople . rdt . ui . text . IColorManagerExtension ; public class RubyColorManager implements IColorManager , IColorManagerExtension { protected Map fKeyTable = new HashMap ( ) ; protected Map fDisplayTable = new HashMap ( ) ; private boolean fAutoDisposeOnDisplayDispose ; public RubyColorManager ( ) { this ( true ) ; } public RubyColorManager ( boolean autoDisposeOnDisplayDispose ) { fAutoDisposeOnDisplayDispose = autoDisposeOnDisplayDispose ; } public void dispose ( Display display ) { Map colorTable = ( Map ) fDisplayTable . get ( display ) ; if ( colorTable != null ) { Iterator e = colorTable . values ( ) . iterator ( ) ; while ( e . hasNext ( ) ) { Color color = ( Color ) e . next ( ) ; if ( color != null && ! color . isDisposed ( ) ) color . dispose ( ) ; } } } public Color getColor ( RGB rgb ) { if ( rgb == null ) return null ; final Display display = Display . getCurrent ( ) ; Map colorTable = ( Map ) fDisplayTable . get ( display ) ; if ( colorTable == null ) { colorTable = new HashMap ( ) ; fDisplayTable . put ( display , colorTable ) ; if ( fAutoDisposeOnDisplayDispose ) { display . disposeExec ( new Runnable ( ) { public void run ( ) { dispose ( display ) ; } } ) ; } } Color color = ( Color ) colorTable . get ( rgb ) ; if ( color == null ) { color = new Color ( Display . getCurrent ( ) , rgb ) ; colorTable . put ( rgb , color ) ; } return color ; } public void dispose ( ) { if ( ! fAutoDisposeOnDisplayDispose ) dispose ( Display . getCurrent ( ) ) ; } public Color getColor ( String key ) { if ( key == null ) return null ; RGB rgb = ( RGB ) fKeyTable . get ( key ) ; return getColor ( rgb ) ; } public void bindColor ( String key , RGB rgb ) { Object value = fKeyTable . get ( key ) ; if ( value != null ) throw new UnsupportedOperationException ( ) ; fKeyTable . put ( key , rgb ) ; } public void unbindColor ( String key ) { fKeyTable . remove ( key ) ; } } package org . rubypeople . rdt . internal . ui . text ; import java . io . IOException ; import java . io . Reader ; public abstract class SubstitutionTextReader extends SingleCharReader { protected static final String LINE_DELIM = System . getProperty ( "" , "" ) ; private Reader fReader ; private boolean fWasWhiteSpace ; private int fCharAfterWhiteSpace ; private boolean fSkipWhiteSpace = true ; private boolean fReadFromBuffer ; private StringBuffer fBuffer ; private int fIndex ; protected SubstitutionTextReader ( Reader reader ) { fReader = reader ; fBuffer = new StringBuffer ( ) ; fIndex = ; fReadFromBuffer = false ; fCharAfterWhiteSpace = - ; fWasWhiteSpace = true ; } protected abstract String computeSubstitution ( int c ) throws IOException ; protected Reader getReader ( ) { return fReader ; } protected int nextChar ( ) throws IOException { fReadFromBuffer = ( fBuffer . length ( ) > ) ; if ( fReadFromBuffer ) { char ch = fBuffer . charAt ( fIndex ++ ) ; if ( fIndex >= fBuffer . length ( ) ) { fBuffer . setLength ( ) ; fIndex = ; } return ch ; } int ch = fCharAfterWhiteSpace ; if ( ch == - ) { ch = fReader . read ( ) ; } if ( fSkipWhiteSpace && Character . isWhitespace ( ( char ) ch ) ) { do { ch = fReader . read ( ) ; } while ( Character . isWhitespace ( ( char ) ch ) ) ; if ( ch != - ) { fCharAfterWhiteSpace = ch ; return '' ; } } else { fCharAfterWhiteSpace = - ; } return ch ; } public int read ( ) throws IOException { int c ; do { c = nextChar ( ) ; while ( ! fReadFromBuffer ) { String s = computeSubstitution ( c ) ; if ( s == null ) break ; if ( s . length ( ) > ) fBuffer . insert ( , s ) ; c = nextChar ( ) ; } } while ( fSkipWhiteSpace && fWasWhiteSpace && ( c == '' ) ) ; fWasWhiteSpace = ( c == '' || c == '' || c == '' ) ; return c ; } public boolean ready ( ) throws IOException { return fReader . ready ( ) ; } public void close ( ) throws IOException { fReader . close ( ) ; } public void reset ( ) throws IOException { fReader . reset ( ) ; fWasWhiteSpace = true ; fCharAfterWhiteSpace = - ; fBuffer . setLength ( ) ; fIndex = ; } protected final void setSkipWhitespace ( boolean state ) { fSkipWhiteSpace = state ; } protected final boolean isSkippingWhitespace ( ) { return fSkipWhiteSpace ; } } package org . rubypeople . rdt . internal . ui . text ; import com . ibm . icu . text . BreakIterator ; import java . text . CharacterIterator ; import org . eclipse . jface . text . Assert ; public class RubyWordIterator extends BreakIterator { private RubyBreakIterator fIterator ; private int fIndex ; public RubyWordIterator ( ) { fIterator = new RubyBreakIterator ( ) ; first ( ) ; } public int first ( ) { fIndex = fIterator . first ( ) ; return fIndex ; } public int last ( ) { fIndex = fIterator . last ( ) ; return fIndex ; } public int next ( int n ) { int next = ; while ( -- n > && next != DONE ) { next = next ( ) ; } return next ; } public int next ( ) { fIndex = following ( fIndex ) ; return fIndex ; } public int previous ( ) { fIndex = preceding ( fIndex ) ; return fIndex ; } public int preceding ( int offset ) { int first = fIterator . preceding ( offset ) ; if ( isWhitespace ( first , offset ) ) { int second = fIterator . preceding ( first ) ; if ( second != DONE && ! isDelimiter ( second , first ) ) return second ; } return first ; } public int following ( int offset ) { int first = fIterator . following ( offset ) ; if ( eatFollowingWhitespace ( offset , first ) ) { int second = fIterator . following ( first ) ; if ( isWhitespace ( first , second ) ) return second ; } return first ; } private boolean eatFollowingWhitespace ( int offset , int exclusiveEnd ) { if ( exclusiveEnd == DONE || offset == DONE ) return false ; if ( isWhitespace ( offset , exclusiveEnd ) ) return false ; if ( isDelimiter ( offset , exclusiveEnd ) ) return false ; return true ; } private boolean isDelimiter ( int offset , int exclusiveEnd ) { if ( exclusiveEnd == DONE || offset == DONE ) return false ; Assert . isTrue ( offset >= ) ; Assert . isTrue ( exclusiveEnd <= getText ( ) . getEndIndex ( ) ) ; Assert . isTrue ( exclusiveEnd > offset ) ; CharSequence seq = fIterator . fText ; while ( offset < exclusiveEnd ) { char ch = seq . charAt ( offset ) ; if ( ch != '' && ch != '' ) return false ; offset ++ ; } return true ; } private boolean isWhitespace ( int offset , int exclusiveEnd ) { if ( exclusiveEnd == DONE || offset == DONE ) return false ; Assert . isTrue ( offset >= ) ; Assert . isTrue ( exclusiveEnd <= getText ( ) . getEndIndex ( ) ) ; Assert . isTrue ( exclusiveEnd > offset ) ; CharSequence seq = fIterator . fText ; while ( offset < exclusiveEnd ) { char ch = seq . charAt ( offset ) ; if ( ! Character . isWhitespace ( ch ) ) return false ; if ( ch == '' || ch == '' ) return false ; offset ++ ; } return true ; } public int current ( ) { return fIndex ; } public CharacterIterator getText ( ) { return fIterator . getText ( ) ; } public void setText ( CharSequence newText ) { fIterator . setText ( newText ) ; first ( ) ; } public void setText ( CharacterIterator newText ) { fIterator . setText ( newText ) ; first ( ) ; } public void setText ( String newText ) { setText ( ( CharSequence ) newText ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; public class CoreSpellingProblem extends CategorizedProblem { public static final String MARKER_TYPE = "" ; private int fSourceEnd = ; private int fLineNumber = ; private int fSourceStart = ; private String fMessage ; private String fWord ; private boolean fMatch ; private boolean fSentence ; private IDocument fDocument ; private String fOrigin ; public CoreSpellingProblem ( int start , int end , int line , String message , String word , boolean match , boolean sentence , IDocument document , String origin ) { super ( ) ; fSourceStart = start ; fSourceEnd = end ; fLineNumber = line ; fMessage = message ; fWord = word ; fMatch = match ; fSentence = sentence ; fDocument = document ; fOrigin = origin ; } public String [ ] getArguments ( ) { String prefix = "" ; String postfix = "" ; try { IRegion line = fDocument . getLineInformationOfOffset ( fSourceStart ) ; prefix = fDocument . get ( line . getOffset ( ) , fSourceStart - line . getOffset ( ) ) ; postfix = fDocument . get ( fSourceEnd + , line . getOffset ( ) + line . getLength ( ) - fSourceEnd ) ; } catch ( BadLocationException exception ) { } return new String [ ] { fWord , prefix , postfix , fSentence ? Boolean . toString ( true ) : Boolean . toString ( false ) , fMatch ? Boolean . toString ( true ) : Boolean . toString ( false ) } ; } public int getID ( ) { return RubySpellingReconcileStrategy . SPELLING_PROBLEM_ID ; } public String getMessage ( ) { return fMessage ; } public char [ ] getOriginatingFileName ( ) { return fOrigin . toCharArray ( ) ; } public int getSourceEnd ( ) { return fSourceEnd ; } public int getSourceLineNumber ( ) { return fLineNumber ; } public int getSourceStart ( ) { return fSourceStart ; } public boolean isError ( ) { return false ; } public boolean isWarning ( ) { return true ; } public void setSourceStart ( int sourceStart ) { fSourceStart = sourceStart ; } public void setSourceEnd ( int sourceEnd ) { fSourceEnd = sourceEnd ; } public void setSourceLineNumber ( int lineNumber ) { fLineNumber = lineNumber ; } public int getCategoryID ( ) { return CAT_JAVADOC ; } public String getMarkerType ( ) { return MARKER_TYPE ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . Locale ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; public class ChangeCaseProposal extends WordCorrectionProposal { public ChangeCaseProposal ( final String [ ] arguments , final int offset , final int length , final IInvocationContext context , final Locale locale ) { super ( Character . isLowerCase ( arguments [ ] . charAt ( ) ) ? Character . toUpperCase ( arguments [ ] . charAt ( ) ) + arguments [ ] . substring ( ) : arguments [ ] , arguments , offset , length , context , Integer . MAX_VALUE ) ; } public String getDisplayString ( ) { return RubyUIMessages . Spelling_case_label ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . LinkedList ; import java . util . Locale ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextUtilities ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . DefaultSpellChecker ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellCheckIterator ; import com . ibm . icu . text . BreakIterator ; public class SpellCheckIterator implements ISpellCheckIterator { private final String fContent ; private final String fDelimiter ; private String fLastToken = null ; private int fNext = ; private final int fOffset ; private int fPredecessor ; private int fPrevious = ; private final LinkedList fSentenceBreaks = new LinkedList ( ) ; private boolean fStartsSentence = false ; private int fSuccessor ; private final BreakIterator fWordIterator ; public SpellCheckIterator ( IDocument document , IRegion region , Locale locale ) { this ( document , region , locale , BreakIterator . getWordInstance ( locale ) ) ; } public SpellCheckIterator ( IDocument document , IRegion region , Locale locale , BreakIterator breakIterator ) { fOffset = region . getOffset ( ) ; fWordIterator = breakIterator ; fDelimiter = TextUtilities . getDefaultLineDelimiter ( document ) ; String content ; try { content = document . get ( region . getOffset ( ) , region . getLength ( ) ) ; } catch ( Exception exception ) { content = "" ; } fContent = content ; fWordIterator . setText ( content ) ; fPredecessor = fWordIterator . first ( ) ; fSuccessor = fWordIterator . next ( ) ; final BreakIterator iterator = BreakIterator . getSentenceInstance ( locale ) ; iterator . setText ( content ) ; int offset = iterator . current ( ) ; while ( offset != BreakIterator . DONE ) { fSentenceBreaks . add ( new Integer ( offset ) ) ; offset = iterator . next ( ) ; } } public final int getBegin ( ) { return fPrevious + fOffset ; } public final int getEnd ( ) { return fNext + fOffset - ; } public final boolean hasNext ( ) { return fSuccessor != BreakIterator . DONE ; } protected final boolean isAlphaNumeric ( final int begin , final int end ) { char character = ; boolean letter = false ; for ( int index = begin ; index < end ; index ++ ) { character = fContent . charAt ( index ) ; if ( Character . isLetter ( character ) ) letter = true ; if ( ! Character . isLetterOrDigit ( character ) ) return false ; } return letter ; } protected final boolean isJavadocToken ( final String [ ] tags ) { if ( fLastToken != null ) { for ( int index = ; index < tags . length ; index ++ ) { if ( fLastToken . equals ( tags [ index ] ) ) return true ; } } return false ; } protected final boolean isSingleLetter ( final int begin ) { if ( begin > && begin < fContent . length ( ) - ) return Character . isWhitespace ( fContent . charAt ( begin - ) ) && Character . isLetter ( fContent . charAt ( begin ) ) && Character . isWhitespace ( fContent . charAt ( begin + ) ) ; return false ; } protected final boolean isUrlToken ( final int begin ) { for ( int index = ; index < DefaultSpellChecker . URL_PREFIXES . length ; index ++ ) { if ( fContent . startsWith ( DefaultSpellChecker . URL_PREFIXES [ index ] , begin ) ) return true ; } return false ; } protected final boolean isWhitespace ( final int begin , final int end ) { for ( int index = begin ; index < end ; index ++ ) { if ( ! Character . isWhitespace ( fContent . charAt ( index ) ) ) return false ; } return true ; } public final Object next ( ) { String token = nextToken ( ) ; while ( token == null && fSuccessor != BreakIterator . DONE ) token = nextToken ( ) ; fLastToken = token ; return token ; } protected final void nextBreak ( ) { fNext = fSuccessor ; fPredecessor = fSuccessor ; fSuccessor = fWordIterator . next ( ) ; } protected final int nextSentence ( ) { return ( ( Integer ) fSentenceBreaks . getFirst ( ) ) . intValue ( ) ; } protected String nextToken ( ) { String token = null ; fPrevious = fPredecessor ; fStartsSentence = false ; nextBreak ( ) ; boolean update = false ; if ( fNext - fPrevious > ) { if ( ! isWhitespace ( fPrevious , fNext ) && isAlphaNumeric ( fPrevious , fNext ) ) { if ( isUrlToken ( fPrevious ) ) skipTokens ( fPrevious , '' ) ; else if ( fNext - fPrevious > || isSingleLetter ( fPrevious ) ) token = fContent . substring ( fPrevious , fNext ) ; update = true ; } } if ( update && fSentenceBreaks . size ( ) > ) { if ( fPrevious >= nextSentence ( ) ) { while ( fSentenceBreaks . size ( ) > && fPrevious >= nextSentence ( ) ) fSentenceBreaks . removeFirst ( ) ; fStartsSentence = ( fLastToken == null ) || ( token != null ) ; } } return token ; } public final void remove ( ) { throw new UnsupportedOperationException ( ) ; } protected final void skipTokens ( final int begin , final char stop ) { int end = begin ; while ( end < fContent . length ( ) && fContent . charAt ( end ) != stop ) end ++ ; if ( end < fContent . length ( ) ) { fNext = end ; fPredecessor = fNext ; fSuccessor = fWordIterator . following ( fNext ) ; } else fSuccessor = BreakIterator . DONE ; } public final boolean startsSentence ( ) { return fStartsSentence ; } } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; public class RankedWordProposal implements Comparable { private int fRank ; private final String fText ; public RankedWordProposal ( final String text , final int rank ) { fText = text ; fRank = rank ; } public final int compareTo ( Object object ) { final RankedWordProposal word = ( RankedWordProposal ) object ; final int rank = word . getRank ( ) ; if ( fRank < rank ) return - ; if ( fRank > rank ) return ; return ; } public final boolean equals ( Object object ) { if ( object instanceof RankedWordProposal ) return object . hashCode ( ) == hashCode ( ) ; return false ; } public final int getRank ( ) { return fRank ; } public final String getText ( ) { return fText ; } public final int hashCode ( ) { return fText . hashCode ( ) ; } public final void setRank ( final int rank ) { fRank = rank ; } } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; public final class DefaultPhoneticDistanceAlgorithm implements IPhoneticDistanceAlgorithm { public static final int COST_CASE = ; public static final int COST_INSERT = ; public static final int COST_REMOVE = ; public static final int COST_SUBSTITUTE = ; public static final int COST_SWAP = ; public final int getDistance ( final String from , final String to ) { final char [ ] first = ( "" + from ) . toCharArray ( ) ; final char [ ] second = ( "" + to ) . toCharArray ( ) ; final int rows = first . length ; final int columns = second . length ; final int [ ] [ ] metric = new int [ rows ] [ columns ] ; for ( int column = ; column < columns ; column ++ ) metric [ ] [ column ] = metric [ ] [ column - ] + COST_REMOVE ; for ( int row = ; row < rows ; row ++ ) metric [ row ] [ ] = metric [ row - ] [ ] + COST_INSERT ; char source , target ; int swap = Integer . MAX_VALUE ; int change = Integer . MAX_VALUE ; int minimum , diagonal , insert , remove ; for ( int row = ; row < rows ; row ++ ) { source = first [ row ] ; for ( int column = ; column < columns ; column ++ ) { target = second [ column ] ; diagonal = metric [ row - ] [ column - ] ; if ( source == target ) { metric [ row ] [ column ] = diagonal ; continue ; } change = Integer . MAX_VALUE ; if ( Character . toLowerCase ( source ) == Character . toLowerCase ( target ) ) change = COST_CASE + diagonal ; swap = Integer . MAX_VALUE ; if ( row != && column != && source == second [ column - ] && first [ row - ] == target ) swap = COST_SWAP + metric [ row - ] [ column - ] ; minimum = COST_SUBSTITUTE + diagonal ; if ( swap < minimum ) minimum = swap ; remove = metric [ row ] [ column - ] ; if ( COST_REMOVE + remove < minimum ) minimum = COST_REMOVE + remove ; insert = metric [ row - ] [ column ] ; if ( COST_INSERT + insert < minimum ) minimum = COST_INSERT + insert ; if ( change < minimum ) minimum = change ; metric [ row ] [ column ] = minimum ; } } return metric [ rows - ] [ columns - ] ; } } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . util . Set ; public interface ISpellEvent { public int getBegin ( ) ; public int getEnd ( ) ; public Set getProposals ( ) ; public String getWord ( ) ; public boolean isMatch ( ) ; public boolean isStart ( ) ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; public interface ISpellEventListener { public void handle ( ISpellEvent event ) ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . io . FileWriter ; import java . io . IOException ; import java . net . URL ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class PersistentSpellDictionary extends AbstractSpellDictionary { private final URL fLocation ; public PersistentSpellDictionary ( final URL url ) { fLocation = url ; } public boolean acceptsWords ( ) { return true ; } public void addWord ( final String word ) { if ( ! isCorrect ( word ) ) { hashWord ( word ) ; FileWriter writer = null ; try { writer = new FileWriter ( fLocation . getPath ( ) , true ) ; writer . write ( word ) ; writer . write ( "" ) ; } catch ( IOException exception ) { RubyPlugin . log ( exception ) ; } finally { try { if ( writer != null ) writer . close ( ) ; } catch ( IOException e ) { } } } } protected final URL getURL ( ) { return fLocation ; } } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . util . Set ; public class SpellEvent implements ISpellEvent { private final int fBegin ; private final ISpellChecker fChecker ; private final int fEnd ; private final boolean fMatch ; private final boolean fSentence ; private final String fWord ; protected SpellEvent ( final ISpellChecker checker , final String word , final int begin , final int end , final boolean sentence , final boolean match ) { fChecker = checker ; fEnd = end ; fBegin = begin ; fWord = word ; fSentence = sentence ; fMatch = match ; } public final int getBegin ( ) { return fBegin ; } public final int getEnd ( ) { return fEnd ; } public final Set getProposals ( ) { return fChecker . getProposals ( fWord , fSentence ) ; } public final String getWord ( ) { return fWord ; } public final boolean isMatch ( ) { return fMatch ; } public final boolean isStart ( ) { return fSentence ; } } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; import org . eclipse . jface . preference . IPreferenceStore ; public class DefaultSpellChecker implements ISpellChecker { public static final String [ ] URL_PREFIXES = new String [ ] { "" , "" , "" , "" , "" , "" , "" } ; protected static boolean isDigits ( final String word ) { for ( int index = ; index < word . length ( ) ; index ++ ) { if ( Character . isDigit ( word . charAt ( index ) ) ) return true ; } return false ; } protected static boolean isMixedCase ( final String word , final boolean sentence ) { final int length = word . length ( ) ; boolean upper = Character . isUpperCase ( word . charAt ( ) ) ; if ( sentence && upper && ( length > ) ) upper = Character . isUpperCase ( word . charAt ( ) ) ; if ( upper ) { for ( int index = length - ; index > ; index -- ) { if ( Character . isLowerCase ( word . charAt ( index ) ) ) return true ; } } else { for ( int index = length - ; index > ; index -- ) { if ( Character . isUpperCase ( word . charAt ( index ) ) ) return true ; } } return false ; } protected static boolean isUpperCase ( final String word ) { for ( int index = word . length ( ) - ; index >= ; index -- ) { if ( Character . isLowerCase ( word . charAt ( index ) ) ) return false ; } return true ; } protected static boolean isUrl ( final String word ) { for ( int index = ; index < URL_PREFIXES . length ; index ++ ) { if ( word . startsWith ( URL_PREFIXES [ index ] ) ) return true ; } return false ; } private final Set fDictionaries = Collections . synchronizedSet ( new HashSet ( ) ) ; private final Set fIgnored = Collections . synchronizedSet ( new HashSet ( ) ) ; private final Set fListeners = Collections . synchronizedSet ( new HashSet ( ) ) ; private final IPreferenceStore fPreferences ; public DefaultSpellChecker ( final IPreferenceStore store ) { fPreferences = store ; } public final void addDictionary ( final ISpellDictionary dictionary ) { fDictionaries . add ( dictionary ) ; } public final void addListener ( final ISpellEventListener listener ) { fListeners . add ( listener ) ; } public boolean acceptsWords ( ) { Set copy ; synchronized ( fDictionaries ) { copy = new HashSet ( fDictionaries ) ; } ISpellDictionary dictionary = null ; for ( final Iterator iterator = copy . iterator ( ) ; iterator . hasNext ( ) ; ) { dictionary = ( ISpellDictionary ) iterator . next ( ) ; if ( dictionary . acceptsWords ( ) ) return true ; } return false ; } public void addWord ( final String word ) { Set copy ; synchronized ( fDictionaries ) { copy = new HashSet ( fDictionaries ) ; } final String addable = word . toLowerCase ( ) ; fIgnored . add ( addable ) ; ISpellDictionary dictionary = null ; for ( final Iterator iterator = copy . iterator ( ) ; iterator . hasNext ( ) ; ) { dictionary = ( ISpellDictionary ) iterator . next ( ) ; dictionary . addWord ( addable ) ; } } public final void checkWord ( final String word ) { fIgnored . remove ( word . toLowerCase ( ) ) ; } public void execute ( final ISpellCheckIterator iterator ) { final boolean ignoreDigits = fPreferences . getBoolean ( ISpellCheckPreferenceKeys . SPELLING_IGNORE_DIGITS ) ; final boolean ignoreMixed = fPreferences . getBoolean ( ISpellCheckPreferenceKeys . SPELLING_IGNORE_MIXED ) ; final boolean ignoreSentence = fPreferences . getBoolean ( ISpellCheckPreferenceKeys . SPELLING_IGNORE_SENTENCE ) ; final boolean ignoreUpper = fPreferences . getBoolean ( ISpellCheckPreferenceKeys . SPELLING_IGNORE_UPPER ) ; final boolean ignoreURLS = fPreferences . getBoolean ( ISpellCheckPreferenceKeys . SPELLING_IGNORE_URLS ) ; String word = null ; boolean starts = false ; while ( iterator . hasNext ( ) ) { word = ( String ) iterator . next ( ) ; if ( word != null ) { if ( ! fIgnored . contains ( word ) ) { starts = iterator . startsSentence ( ) ; if ( ! isCorrect ( word ) ) { boolean isMixed = isMixedCase ( word , true ) ; boolean isUpper = isUpperCase ( word ) ; boolean isDigits = isDigits ( word ) ; boolean isURL = isUrl ( word ) ; if ( ! ignoreMixed && isMixed || ! ignoreUpper && isUpper || ! ignoreDigits && isDigits || ! ignoreURLS && isURL || ! ( isMixed || isUpper || isDigits || isURL ) ) fireEvent ( new SpellEvent ( this , word , iterator . getBegin ( ) , iterator . getEnd ( ) , starts , false ) ) ; } else { if ( ! ignoreSentence && starts && Character . isLowerCase ( word . charAt ( ) ) ) fireEvent ( new SpellEvent ( this , word , iterator . getBegin ( ) , iterator . getEnd ( ) , true , true ) ) ; } } } } } protected final void fireEvent ( final ISpellEvent event ) { Set copy ; synchronized ( fListeners ) { copy = new HashSet ( fListeners ) ; } for ( final Iterator iterator = copy . iterator ( ) ; iterator . hasNext ( ) ; ) { ( ( ISpellEventListener ) iterator . next ( ) ) . handle ( event ) ; } } public Set getProposals ( final String word , final boolean sentence ) { Set copy ; synchronized ( fDictionaries ) { copy = new HashSet ( fDictionaries ) ; } ISpellDictionary dictionary = null ; final HashSet proposals = new HashSet ( ) ; for ( final Iterator iterator = copy . iterator ( ) ; iterator . hasNext ( ) ; ) { dictionary = ( ISpellDictionary ) iterator . next ( ) ; proposals . addAll ( dictionary . getProposals ( word , sentence ) ) ; } return proposals ; } public final void ignoreWord ( final String word ) { fIgnored . add ( word . toLowerCase ( ) ) ; } public final boolean isCorrect ( final String word ) { Set copy ; synchronized ( fDictionaries ) { copy = new HashSet ( fDictionaries ) ; } if ( fIgnored . contains ( word . toLowerCase ( ) ) ) return true ; ISpellDictionary dictionary = null ; for ( final Iterator iterator = copy . iterator ( ) ; iterator . hasNext ( ) ; ) { dictionary = ( ISpellDictionary ) iterator . next ( ) ; if ( dictionary . isCorrect ( word ) ) return true ; } return false ; } public final void removeDictionary ( final ISpellDictionary dictionary ) { fDictionaries . remove ( dictionary ) ; } public final void removeListener ( final ISpellEventListener listener ) { fListeners . remove ( listener ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . util . Set ; public interface ISpellDictionary { public boolean acceptsWords ( ) ; public void addWord ( String word ) ; public Set getProposals ( String word , boolean sentence ) ; public boolean isCorrect ( String word ) ; public boolean isLoaded ( ) ; public void unload ( ) ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; public interface IPhoneticHashProvider { public String getHash ( String word ) ; public char [ ] getMutators ( ) ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . util . Set ; public interface ISpellChecker { public void addDictionary ( ISpellDictionary dictionary ) ; public void addListener ( ISpellEventListener listener ) ; public boolean acceptsWords ( ) ; public void addWord ( String word ) ; public void checkWord ( String word ) ; public void execute ( ISpellCheckIterator iterator ) ; public Set getProposals ( String word , boolean sentence ) ; public void ignoreWord ( String word ) ; public boolean isCorrect ( String word ) ; public void removeDictionary ( ISpellDictionary dictionary ) ; public void removeListener ( ISpellEventListener listener ) ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . util . Locale ; import org . eclipse . jface . preference . IPreferenceStore ; public interface ISpellCheckEngine { ISpellChecker createSpellChecker ( Locale locale , IPreferenceStore store ) ; Locale getLocale ( ) ; void registerDictionary ( ISpellDictionary dictionary ) ; void registerDictionary ( Locale locale , ISpellDictionary dictionary ) ; void unload ( ) ; void unregisterDictionary ( ISpellDictionary dictionary ) ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; public interface IPhoneticDistanceAlgorithm { public int getDistance ( String from , String to ) ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; public final class DefaultPhoneticHashProvider implements IPhoneticHashProvider { private static final String [ ] meta01 = { "" , "" } ; private static final String [ ] meta02 = { "" , "" , "" } ; private static final String [ ] meta03 = { "" , "" } ; private static final String [ ] meta04 = { "" , "" } ; private static final String [ ] meta05 = { "" , "" } ; private static final String [ ] meta06 = { "" , "" } ; private static final String [ ] meta07 = { "" , "" , "" } ; private static final String [ ] meta08 = { "" , "" , "" , "" , "" } ; private static final String [ ] meta09 = { "" , "" } ; private static final String [ ] meta10 = { "" , "" , "" } ; private static final String [ ] meta11 = { "" , "" } ; private static final String [ ] meta12 = { "" , "" , "" , "" } ; private static final String [ ] meta13 = { "" , "" , "" } ; private static final String [ ] meta14 = { "" , "" , "" , "" , "" } ; private static final String [ ] meta15 = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private static final String [ ] meta16 = { "" , "" } ; private static final String [ ] meta17 = { "" , "" } ; private static final String [ ] meta18 = { "" , "" } ; private static final String [ ] meta19 = { "" , "" } ; private static final String [ ] meta20 = { "" , "" } ; private static final String [ ] meta21 = { "" , "" , "" , "" } ; private static final String [ ] meta22 = { "" , "" } ; private static final String [ ] meta23 = { "" , "" , "" } ; private static final String [ ] meta24 = { "" , "" , "" , "" } ; private static final String [ ] meta25 = { "" , "" , "" , "" } ; private static final String [ ] meta26 = { "" , "" , "" , "" , "" , "" } ; private static final String [ ] meta27 = { "" , "" , "" , "" } ; private static final String [ ] meta28 = { "" , "" , "" , "" } ; private static final String [ ] meta29 = { "" , "" , "" } ; private static final String [ ] meta30 = { "" , "" } ; private static final String [ ] meta31 = { "" , "" , "" , "" } ; private static final String [ ] meta32 = { "" , "" , "" } ; private static final String [ ] meta33 = { "" , "" , "" , "" } ; private static final String [ ] meta34 = { "" , "" , "" , "" } ; private static final String [ ] meta35 = { "" , "" , "" } ; private static final String [ ] meta36 = { "" , "" , "" , "" , "" , "" } ; private static final String [ ] meta37 = { "" , "" } ; private static final String [ ] meta38 = { "" , "" } ; private static final String [ ] meta39 = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private static final String [ ] meta40 = { "" , "" } ; private static final String [ ] meta41 = { "" , "" , "" , "" } ; private static final String [ ] meta42 = { "" , "" , "" } ; private static final String [ ] meta43 = { "" , "" , "" } ; private static final String [ ] meta44 = { "" , "" , "" , "" } ; private static final String [ ] meta45 = { "" , "" , "" } ; private static final String [ ] meta46 = { "" , "" , "" } ; private static final String [ ] meta47 = { "" , "" } ; private static final String [ ] meta48 = { "" , "" } ; private static final String [ ] meta49 = { "" , "" , "" } ; private static final String [ ] meta50 = { "" , "" } ; private static final String [ ] meta51 = { "" , "" } ; private static final String [ ] meta52 = { "" , "" } ; private static final String [ ] meta53 = { "" , "" } ; private static final String [ ] meta54 = { "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private static final String [ ] meta55 = { "" , "" , "" , "" } ; private static final String [ ] meta56 = { "" , "" , "" , "" } ; private static final String [ ] meta57 = { "" , "" , "" } ; private static final String [ ] meta58 = { "" , "" , "" } ; private static final String [ ] meta59 = { "" , "" } ; private static final String [ ] meta60 = { "" , "" } ; private static final String [ ] meta61 = { "" , "" } ; private static final String [ ] meta62 = { "" , "" , "" } ; private static final String [ ] meta63 = { "" , "" } ; private static final String [ ] meta64 = { "" , "" , "" } ; private static final String [ ] meta65 = { "" , "" , "" } ; private static final String [ ] meta66 = { "" , "" } ; private static final String [ ] meta67 = { "" , "" } ; private static final String [ ] meta68 = { "" , "" , "" , "" , "" } ; private static final String [ ] meta69 = { "" , "" , "" } ; private static final String [ ] meta70 = { "" , "" } ; private static final String [ ] meta71 = { "" , "" , "" , "" , "" } ; private static final String [ ] meta72 = { "" , "" } ; private static final String [ ] meta73 = { "" , "" } ; private static final String [ ] meta74 = { "" , "" } ; private static final String [ ] meta75 = { "" , "" , "" , "" , "" , "" , "" } ; private static final String [ ] meta76 = { "" , "" , "" } ; private static final String [ ] meta77 = { "" , "" , "" , "" } ; private static final String [ ] meta78 = { "" , "" , "" } ; private static final String [ ] meta79 = { "" , "" , "" } ; private static final String [ ] meta80 = { "" , "" } ; private static final String [ ] meta81 = { "" , "" , "" } ; private static final String [ ] meta82 = { "" , "" } ; private static final String [ ] meta83 = { "" , "" } ; private static final String [ ] meta84 = { "" , "" , "" } ; private static final String [ ] meta85 = { "" , "" , "" } ; private static final String [ ] meta86 = { "" , "" } ; private static final String [ ] meta87 = { "" , "" , "" } ; private static final String [ ] meta88 = { "" , "" } ; private static final String [ ] meta89 = { "" , "" } ; private static final String [ ] meta90 = { "" , "" , "" , "" , "" } ; private static final String [ ] meta91 = { "" , "" } ; private static final String [ ] meta92 = { "" , "" , "" } ; private static final String [ ] meta93 = { "" , "" , "" } ; private static final String [ ] meta94 = { "" , "" , "" } ; private static final String [ ] meta95 = { "" , "" , "" , "" } ; private static final char [ ] MUTATOR_CHARACTERS = { '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' } ; private static final char [ ] VOWEL_CHARACTERS = new char [ ] { '' , '' , '' , '' , '' , '' } ; protected static final boolean hasOneOf ( final String [ ] candidates , final char [ ] token , final int offset , final int length ) { if ( offset < || offset >= token . length || candidates . length == ) return false ; final String checkable = new String ( token , offset , length ) ; for ( int index = ; index < candidates . length ; index ++ ) { if ( candidates [ index ] . equals ( checkable ) ) return true ; } return false ; } protected static final boolean hasOneOf ( final String [ ] candidates , final String token ) { for ( int index = ; index < candidates . length ; index ++ ) { if ( token . indexOf ( candidates [ index ] ) >= ) return true ; } return false ; } protected static final boolean hasVowel ( final char [ ] token , final int offset , final int length ) { if ( offset >= && offset < length ) { final char character = token [ offset ] ; for ( int index = ; index < VOWEL_CHARACTERS . length ; index ++ ) { if ( VOWEL_CHARACTERS [ index ] == character ) return true ; } } return false ; } public final String getHash ( final String word ) { final String input = word . toUpperCase ( ) + "" ; final char [ ] hashable = input . toCharArray ( ) ; final boolean has95 = hasOneOf ( meta95 , input ) ; final StringBuffer buffer = new StringBuffer ( hashable . length ) ; int offset = ; if ( hasOneOf ( meta26 , hashable , , ) ) offset += ; if ( hashable [ ] == '' ) { buffer . append ( '' ) ; offset += ; } while ( offset < hashable . length ) { switch ( hashable [ offset ] ) { case '' : case '' : case '' : case '' : case '' : case '' : if ( offset == ) buffer . append ( '' ) ; offset += ; break ; case '' : buffer . append ( '' ) ; if ( hashable [ offset + ] == '' ) offset += ; else offset += ; break ; case '' : if ( ( offset > ) && ! hasVowel ( hashable , offset - , hashable . length ) && hasOneOf ( meta01 , hashable , ( offset - ) , ) && ( hashable [ offset + ] != '' ) && ( hashable [ offset + ] != '' ) || hasOneOf ( meta02 , hashable , ( offset - ) , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( ( offset == ) && hasOneOf ( meta03 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta04 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta05 , hashable , offset , ) ) { if ( ( offset > ) && hasOneOf ( meta06 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( ( offset == ) && hasOneOf ( meta07 , hashable , ( offset + ) , ) || hasOneOf ( meta08 , hashable , offset + , ) && ! hasOneOf ( meta09 , hashable , , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta10 , hashable , , ) || hasOneOf ( meta11 , hashable , , ) || hasOneOf ( meta12 , hashable , offset - , ) || hasOneOf ( meta13 , hashable , offset + , ) || ( hasOneOf ( meta14 , hashable , offset - , ) || ( offset == ) ) && hasOneOf ( meta15 , hashable , offset + , ) ) { buffer . append ( '' ) ; } else { if ( offset > ) { if ( hasOneOf ( meta16 , hashable , , ) ) buffer . append ( '' ) ; else buffer . append ( '' ) ; } else { buffer . append ( '' ) ; } } offset += ; break ; } if ( hasOneOf ( meta17 , hashable , offset , ) && ! hasOneOf ( meta18 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta19 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta20 , hashable , offset , ) && ! ( ( offset == ) && hashable [ ] == '' ) ) { if ( hasOneOf ( meta21 , hashable , offset + , ) && ! hasOneOf ( meta22 , hashable , offset + , ) ) { if ( ( ( offset == ) && ( hashable [ offset - ] == '' ) ) || hasOneOf ( meta23 , hashable , ( offset - ) , ) ) buffer . append ( "" ) ; else buffer . append ( '' ) ; offset += ; break ; } else { buffer . append ( '' ) ; offset += ; break ; } } if ( hasOneOf ( meta24 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } else if ( hasOneOf ( meta25 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } buffer . append ( '' ) ; if ( hasOneOf ( meta27 , hashable , offset + , ) ) offset += ; else if ( hasOneOf ( meta28 , hashable , offset + , ) && ! hasOneOf ( meta29 , hashable , offset + , ) ) offset += ; else offset += ; break ; case '' : buffer . append ( '' ) ; offset += ; break ; case '' : if ( hasOneOf ( meta30 , hashable , offset , ) ) { if ( hasOneOf ( meta31 , hashable , offset + , ) ) { buffer . append ( '' ) ; offset += ; break ; } else { buffer . append ( "" ) ; offset += ; break ; } } buffer . append ( '' ) ; if ( hasOneOf ( meta32 , hashable , offset , ) ) { offset += ; } else { offset += ; } break ; case '' : if ( hashable [ offset + ] == '' ) offset += ; else offset += ; buffer . append ( '' ) ; break ; case '' : if ( hashable [ offset + ] == '' ) { if ( ( offset > ) && ! hasVowel ( hashable , offset - , hashable . length ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( offset < ) { if ( offset == ) { if ( hashable [ offset + ] == '' ) buffer . append ( '' ) ; else buffer . append ( '' ) ; offset += ; break ; } } if ( ( offset > ) && hasOneOf ( meta33 , hashable , offset - , ) || ( ( offset > ) && hasOneOf ( meta34 , hashable , offset - , ) ) || ( ( offset > ) && hasOneOf ( meta35 , hashable , offset - , ) ) ) { offset += ; break ; } else { if ( ( offset > ) && ( hashable [ offset - ] == '' ) && hasOneOf ( meta36 , hashable , offset - , ) ) { buffer . append ( '' ) ; } else { if ( ( offset > ) && ( hashable [ offset - ] != '' ) ) buffer . append ( '' ) ; } offset += ; break ; } } if ( hashable [ offset + ] == '' ) { if ( ( offset == ) && hasVowel ( hashable , , hashable . length ) && ! has95 ) { buffer . append ( "" ) ; } else { if ( ! hasOneOf ( meta37 , hashable , offset + , ) && ( hashable [ offset + ] != '' ) && ! has95 ) { buffer . append ( "" ) ; } else { buffer . append ( "" ) ; } } offset += ; break ; } if ( hasOneOf ( meta38 , hashable , offset + , ) && ! has95 ) { buffer . append ( "" ) ; offset += ; break ; } if ( ( offset == ) && ( ( hashable [ offset + ] == '' ) || hasOneOf ( meta39 , hashable , offset + , ) ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( ( hasOneOf ( meta40 , hashable , offset + , ) || ( hashable [ offset + ] == '' ) ) && ! hasOneOf ( meta41 , hashable , , ) && ! hasOneOf ( meta42 , hashable , offset - , ) && ! hasOneOf ( meta43 , hashable , offset - , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta44 , hashable , offset + , ) || hasOneOf ( meta45 , hashable , offset - , ) ) { if ( hasOneOf ( meta46 , hashable , , ) || hasOneOf ( meta47 , hashable , , ) || hasOneOf ( meta48 , hashable , offset + , ) ) { buffer . append ( '' ) ; } else { buffer . append ( '' ) ; } offset += ; break ; } if ( hashable [ offset + ] == '' ) offset += ; else offset += ; buffer . append ( '' ) ; break ; case '' : if ( ( ( offset == ) || hasVowel ( hashable , offset - , hashable . length ) ) && hasVowel ( hashable , offset + , hashable . length ) ) { buffer . append ( '' ) ; offset += ; } else { offset += ; } break ; case '' : if ( hasOneOf ( meta50 , hashable , offset , ) || hasOneOf ( meta51 , hashable , , ) ) { if ( ( offset == ) && ( hashable [ offset + ] == '' ) || hasOneOf ( meta52 , hashable , , ) ) { buffer . append ( '' ) ; } else { buffer . append ( '' ) ; } offset += ; break ; } if ( ( offset == ) && ! hasOneOf ( meta53 , hashable , offset , ) ) { buffer . append ( '' ) ; } else { if ( hasVowel ( hashable , offset - , hashable . length ) && ! has95 && ( ( hashable [ offset + ] == '' ) || hashable [ offset + ] == '' ) ) { buffer . append ( '' ) ; } else { if ( offset == ( hashable . length - ) ) { buffer . append ( '' ) ; } else { if ( ! hasOneOf ( meta54 , hashable , offset + , ) && ! hasOneOf ( meta55 , hashable , offset - , ) ) { buffer . append ( '' ) ; } } } } if ( hashable [ offset + ] == '' ) offset += ; else offset += ; break ; case '' : if ( hashable [ offset + ] == '' ) offset += ; else offset += ; buffer . append ( '' ) ; break ; case '' : if ( hashable [ offset + ] == '' ) { if ( ( ( offset == ( hashable . length - ) ) && hasOneOf ( meta56 , hashable , offset - , ) ) || ( ( hasOneOf ( meta57 , hashable , ( hashable . length - ) - , ) || hasOneOf ( meta58 , hashable , hashable . length - , ) ) && hasOneOf ( meta59 , hashable , offset - , ) ) ) { buffer . append ( '' ) ; offset += ; break ; } offset += ; } else offset += ; buffer . append ( '' ) ; break ; case '' : if ( ( hasOneOf ( meta60 , hashable , offset - , ) && ( ( ( offset + ) == ( hashable . length - ) ) || hasOneOf ( meta61 , hashable , offset + , ) ) ) || ( hashable [ offset + ] == '' ) ) offset += ; else offset += ; buffer . append ( '' ) ; break ; case '' : if ( hashable [ offset + ] == '' ) offset += ; else offset += ; buffer . append ( '' ) ; break ; case '' : offset += ; buffer . append ( '' ) ; break ; case '' : if ( hashable [ offset + ] == '' ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta62 , hashable , offset + , ) ) offset += ; else offset += ; buffer . append ( '' ) ; break ; case '' : if ( hashable [ offset + ] == '' ) offset += ; else offset += ; buffer . append ( '' ) ; break ; case '' : if ( ! ( ( offset == ( hashable . length - ) ) && ! has95 && hasOneOf ( meta63 , hashable , offset - , ) && ! hasOneOf ( meta64 , hashable , offset - , ) ) ) buffer . append ( '' ) ; if ( hashable [ offset + ] == '' ) offset += ; else offset += ; break ; case '' : if ( hasOneOf ( meta65 , hashable , offset - , ) ) { offset += ; break ; } if ( ( offset == ) && hasOneOf ( meta66 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta67 , hashable , offset , ) ) { if ( hasOneOf ( meta68 , hashable , offset + , ) ) buffer . append ( '' ) ; else buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta69 , hashable , offset , ) || hasOneOf ( meta70 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( ( ( offset == ) && hasOneOf ( meta71 , hashable , offset + , ) ) || hasOneOf ( meta72 , hashable , offset + , ) ) { buffer . append ( '' ) ; if ( hasOneOf ( meta73 , hashable , offset + , ) ) offset += ; else offset += ; break ; } if ( hasOneOf ( meta74 , hashable , offset , ) ) { if ( hashable [ offset + ] == '' ) if ( hasOneOf ( meta75 , hashable , offset + , ) ) { if ( hasOneOf ( meta76 , hashable , offset + , ) ) { buffer . append ( "" ) ; } else { buffer . append ( "" ) ; } offset += ; break ; } else { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta77 , hashable , offset + , ) ) { buffer . append ( '' ) ; offset += ; break ; } buffer . append ( "" ) ; offset += ; break ; } if ( ! ( ( offset == ( hashable . length - ) ) && hasOneOf ( meta78 , hashable , offset - , ) ) ) buffer . append ( '' ) ; if ( hasOneOf ( meta79 , hashable , offset + , ) ) offset += ; else offset += ; break ; case '' : if ( hasOneOf ( meta80 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta81 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta82 , hashable , offset , ) || hasOneOf ( meta83 , hashable , offset , ) ) { if ( hasOneOf ( meta84 , hashable , ( offset + ) , ) || hasOneOf ( meta85 , hashable , , ) || hasOneOf ( meta86 , hashable , , ) ) { buffer . append ( '' ) ; } else { buffer . append ( '' ) ; } offset += ; break ; } if ( hasOneOf ( meta87 , hashable , offset + , ) ) { offset += ; } else offset += ; buffer . append ( '' ) ; break ; case '' : if ( hashable [ offset + ] == '' ) offset += ; else offset += ; buffer . append ( '' ) ; break ; case '' : if ( hasOneOf ( meta88 , hashable , offset , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( ( offset == ) && ( hasVowel ( hashable , offset + , hashable . length ) || hasOneOf ( meta89 , hashable , offset , ) ) ) { buffer . append ( '' ) ; } if ( ( ( offset == ( hashable . length - ) ) && hasVowel ( hashable , offset - , hashable . length ) ) || hasOneOf ( meta90 , hashable , offset - , ) || hasOneOf ( meta91 , hashable , , ) ) { buffer . append ( '' ) ; offset += ; break ; } if ( hasOneOf ( meta92 , hashable , offset , ) ) { buffer . append ( "" ) ; offset += ; break ; } offset += ; break ; case '' : if ( ! ( ( offset == ( hashable . length - ) ) && ( hasOneOf ( meta93 , hashable , offset - , ) || hasOneOf ( meta94 , hashable , offset - , ) ) ) ) buffer . append ( "" ) ; if ( hasOneOf ( meta49 , hashable , offset + , ) ) offset += ; else offset += ; break ; case '' : if ( hashable [ offset + ] == '' ) { buffer . append ( '' ) ; offset += ; break ; } else { buffer . append ( '' ) ; } if ( hashable [ offset + ] == '' ) offset += ; else offset += ; break ; default : offset += ; } } return buffer . toString ( ) ; } public final char [ ] getMutators ( ) { return MUTATOR_CHARACTERS ; } } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . net . MalformedURLException ; import java . net . URL ; import java . nio . charset . Charset ; import java . nio . charset . CharsetDecoder ; import java . nio . charset . CodingErrorAction ; import java . nio . charset . MalformedInputException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . ui . RubyUI ; public abstract class AbstractSpellDictionary implements ISpellDictionary { protected static final int BUCKET_CAPACITY = ; protected static final int BUFFER_CAPACITY = ; protected static final int DISTANCE_THRESHOLD = ; protected static final int HASH_CAPACITY = * ; private IPhoneticDistanceAlgorithm fDistanceAlgorithm = new DefaultPhoneticDistanceAlgorithm ( ) ; private final Map fHashBuckets = new HashMap ( HASH_CAPACITY ) ; private IPhoneticHashProvider fHashProvider = new DefaultPhoneticHashProvider ( ) ; private boolean fLoaded = false ; private boolean fMustLoad = true ; protected final ArrayList getCandidates ( final String hash ) { ArrayList list = ( ArrayList ) fHashBuckets . get ( hash ) ; if ( list == null ) list = new ArrayList ( ) ; return list ; } protected final HashSet getCandidates ( final String word , final boolean sentence , final ArrayList hashs ) { int distance = ; String hash = null ; String candidate = null ; List candidates = null ; final StringBuffer buffer = new StringBuffer ( BUFFER_CAPACITY ) ; final HashSet result = new HashSet ( BUCKET_CAPACITY * hashs . size ( ) ) ; for ( int index = ; index < hashs . size ( ) ; index ++ ) { hash = ( String ) hashs . get ( index ) ; candidates = getCandidates ( hash ) ; for ( int offset = ; offset < candidates . size ( ) ; offset ++ ) { candidate = ( String ) candidates . get ( offset ) ; distance = fDistanceAlgorithm . getDistance ( word , candidate ) ; if ( distance < DISTANCE_THRESHOLD ) { buffer . setLength ( ) ; buffer . append ( candidate ) ; if ( sentence ) buffer . setCharAt ( , Character . toUpperCase ( buffer . charAt ( ) ) ) ; result . add ( new RankedWordProposal ( buffer . toString ( ) , - distance ) ) ; } } } return result ; } protected final void getCandidates ( final String word , final boolean sentence , final HashSet result ) { int distance = ; int minimum = Integer . MAX_VALUE ; String candidate = null ; StringBuffer buffer = new StringBuffer ( BUFFER_CAPACITY ) ; final ArrayList candidates = getCandidates ( fHashProvider . getHash ( word ) ) ; final ArrayList matches = new ArrayList ( candidates . size ( ) ) ; for ( int index = ; index < candidates . size ( ) ; index ++ ) { candidate = ( String ) candidates . get ( index ) ; distance = fDistanceAlgorithm . getDistance ( word , candidate ) ; if ( distance <= minimum ) { buffer . setLength ( ) ; buffer . append ( candidate ) ; if ( sentence ) buffer . setCharAt ( , Character . toUpperCase ( buffer . charAt ( ) ) ) ; matches . add ( new RankedWordProposal ( buffer . toString ( ) , - distance ) ) ; minimum = distance ; } } RankedWordProposal match = null ; for ( int index = ; index < matches . size ( ) ; index ++ ) { match = ( RankedWordProposal ) matches . get ( index ) ; if ( match . getRank ( ) == minimum ) result . add ( match ) ; } } protected final IPhoneticDistanceAlgorithm getDistanceAlgorithm ( ) { return fDistanceAlgorithm ; } protected final IPhoneticHashProvider getHashProvider ( ) { return fHashProvider ; } public Set getProposals ( final String word , final boolean sentence ) { try { if ( ! fLoaded ) fLoaded = load ( getURL ( ) ) ; } catch ( MalformedURLException exception ) { } final String hash = fHashProvider . getHash ( word ) ; final char [ ] mutators = fHashProvider . getMutators ( ) ; final ArrayList neighborhood = new ArrayList ( ( word . length ( ) + ) * ( mutators . length + ) ) ; neighborhood . add ( hash ) ; final HashSet candidates = getCandidates ( word , sentence , neighborhood ) ; neighborhood . clear ( ) ; char previous = ; char next = ; char [ ] characters = word . toCharArray ( ) ; for ( int index = ; index < word . length ( ) - ; index ++ ) { next = characters [ index ] ; previous = characters [ index + ] ; characters [ index ] = previous ; characters [ index + ] = next ; neighborhood . add ( fHashProvider . getHash ( new String ( characters ) ) ) ; characters [ index ] = next ; characters [ index + ] = previous ; } final String sentinel = word + "" ; characters = sentinel . toCharArray ( ) ; int offset = characters . length - ; while ( true ) { for ( int index = ; index < mutators . length ; index ++ ) { characters [ offset ] = mutators [ index ] ; neighborhood . add ( fHashProvider . getHash ( new String ( characters ) ) ) ; } if ( offset == ) break ; characters [ offset ] = characters [ offset - ] ; -- offset ; } char mutated = ; characters = word . toCharArray ( ) ; for ( int index = ; index < word . length ( ) ; index ++ ) { mutated = characters [ index ] ; for ( int mutator = ; mutator < mutators . length ; mutator ++ ) { characters [ index ] = mutators [ mutator ] ; neighborhood . add ( fHashProvider . getHash ( new String ( characters ) ) ) ; } characters [ index ] = mutated ; } characters = word . toCharArray ( ) ; final char [ ] deleted = new char [ characters . length - ] ; for ( int index = ; index < deleted . length ; index ++ ) deleted [ index ] = characters [ index ] ; next = characters [ characters . length - ] ; offset = deleted . length ; while ( true ) { neighborhood . add ( fHashProvider . getHash ( new String ( characters ) ) ) ; if ( offset == ) break ; previous = next ; next = deleted [ offset - ] ; deleted [ offset - ] = previous ; -- offset ; } neighborhood . remove ( hash ) ; final HashSet matches = getCandidates ( word , sentence , neighborhood ) ; if ( matches . size ( ) == && candidates . size ( ) == ) getCandidates ( word , sentence , candidates ) ; candidates . addAll ( matches ) ; return candidates ; } protected abstract URL getURL ( ) throws MalformedURLException ; protected final void hashWord ( final String word ) { final String hash = fHashProvider . getHash ( word ) ; ArrayList bucket = ( ArrayList ) fHashBuckets . get ( hash ) ; if ( bucket == null ) { bucket = new ArrayList ( BUCKET_CAPACITY ) ; fHashBuckets . put ( hash , bucket ) ; } bucket . add ( word ) ; } public boolean isCorrect ( final String word ) { try { if ( ! fLoaded ) fLoaded = load ( getURL ( ) ) ; } catch ( MalformedURLException exception ) { } final ArrayList candidates = getCandidates ( fHashProvider . getHash ( word ) ) ; if ( candidates . contains ( word ) || candidates . contains ( word . toLowerCase ( ) ) ) return true ; return false ; } public final synchronized boolean isLoaded ( ) { return fLoaded || fHashBuckets . size ( ) > ; } protected synchronized boolean load ( final URL url ) { if ( ! fMustLoad ) return fLoaded ; if ( url != null ) { InputStream stream = null ; int line = ; try { stream = url . openStream ( ) ; if ( stream != null ) { String word = null ; CharsetDecoder decoder = Charset . forName ( System . getProperty ( "" ) ) . newDecoder ( ) ; decoder . replaceWith ( "" ) ; decoder . onMalformedInput ( CodingErrorAction . REPORT ) ; decoder . onUnmappableCharacter ( CodingErrorAction . REPORT ) ; final BufferedReader reader = new BufferedReader ( new InputStreamReader ( stream , decoder ) ) ; boolean doRead = true ; while ( doRead ) { try { word = reader . readLine ( ) ; } catch ( MalformedInputException ex ) { decoder . onMalformedInput ( CodingErrorAction . REPLACE ) ; decoder . reset ( ) ; word = reader . readLine ( ) ; decoder . onMalformedInput ( CodingErrorAction . REPORT ) ; String message = Messages . format ( RubyUIMessages . AbstractSpellingDictionary_encodingError , new String [ ] { word , decoder . replacement ( ) , url . toString ( ) } ) ; IStatus status = new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . OK , message , ex ) ; RubyPlugin . log ( status ) ; doRead = word != null ; continue ; } doRead = word != null ; if ( doRead ) hashWord ( word ) ; } return true ; } } catch ( IOException exception ) { if ( line > ) { String message = Messages . format ( RubyUIMessages . AbstractSpellingDictionary_encodingError , new Object [ ] { new Integer ( line ) , url . toString ( ) } ) ; IStatus status = new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . OK , message , exception ) ; RubyPlugin . log ( status ) ; } else RubyPlugin . log ( exception ) ; } finally { fMustLoad = false ; try { if ( stream != null ) stream . close ( ) ; } catch ( IOException x ) { } } } return false ; } protected final void setDistanceAlgorithm ( final IPhoneticDistanceAlgorithm algorithm ) { fDistanceAlgorithm = algorithm ; } protected final void setHashProvider ( final IPhoneticHashProvider provider ) { fHashProvider = provider ; } public synchronized void unload ( ) { fLoaded = false ; fMustLoad = true ; fHashBuckets . clear ( ) ; } public boolean acceptsWords ( ) { return false ; } public void addWord ( final String word ) { } } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; public interface ISpellCheckPreferenceKeys { public final static String SPELLING_IGNORE_DIGITS = "" ; public final static String SPELLING_IGNORE_MIXED = "" ; public final static String SPELLING_IGNORE_SENTENCE = "" ; public final static String SPELLING_IGNORE_UPPER = "" ; public final static String SPELLING_IGNORE_URLS = "" ; public final static String SPELLING_LOCALE = "" ; public final static String SPELLING_PROPOSAL_THRESHOLD = "" ; public final static String SPELLING_USER_DICTIONARY = "" ; public final static String SPELLING_ENABLE_CONTENTASSIST = "" ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . util . Iterator ; public interface ISpellCheckIterator extends Iterator { public int getBegin ( ) ; public int getEnd ( ) ; public boolean startsSentence ( ) ; } package org . rubypeople . rdt . internal . ui . text . spelling . engine ; import java . net . MalformedURLException ; import java . net . URL ; import java . util . Locale ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; public class LocaleSensitiveSpellDictionary extends AbstractSpellDictionary { private final Locale fLocale ; private final URL fLocation ; public LocaleSensitiveSpellDictionary ( final Locale locale , final URL location ) { fLocation = location ; fLocale = locale ; } public final Locale getLocale ( ) { return fLocale ; } protected final URL getURL ( ) throws MalformedURLException { return new URL ( fLocation , fLocale . toString ( ) + "" + RubyUIMessages . Spelling_dictionary_file_extension ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellCheckEngine ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellChecker ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class WordIgnoreProposal implements IRubyCompletionProposal { private IInvocationContext fContext ; private String fWord ; public WordIgnoreProposal ( final String word , final IInvocationContext context ) { fWord = word ; fContext = context ; } public final void apply ( final IDocument document ) { final ISpellCheckEngine engine = SpellCheckEngine . getInstance ( ) ; final ISpellChecker checker = engine . createSpellChecker ( engine . getLocale ( ) , PreferenceConstants . getPreferenceStore ( ) ) ; if ( checker != null ) { checker . ignoreWord ( fWord ) ; RubySpellingProblem . removeAllInActiveEditor ( fWord ) ; } } public String getAdditionalProposalInfo ( ) { return Messages . format ( RubyUIMessages . Spelling_ignore_info , new String [ ] { WordCorrectionProposal . getHtmlRepresentation ( fWord ) } ) ; } public final IContextInformation getContextInformation ( ) { return null ; } public String getDisplayString ( ) { return Messages . format ( RubyUIMessages . Spelling_ignore_label , new String [ ] { fWord } ) ; } public Image getImage ( ) { return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_NLS_NEVER_TRANSLATE ) ; } public final int getRelevance ( ) { return Integer . MIN_VALUE + ; } public final Point getSelection ( final IDocument document ) { return new Point ( fContext . getSelectionOffset ( ) , fContext . getSelectionLength ( ) ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . Locale ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . ui . texteditor . spelling . ISpellingEngine ; import org . eclipse . ui . texteditor . spelling . ISpellingProblemCollector ; import org . eclipse . ui . texteditor . spelling . SpellingContext ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellCheckPreferenceKeys ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellChecker ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellEvent ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellEventListener ; import org . rubypeople . rdt . ui . PreferenceConstants ; public abstract class SpellingEngine implements ISpellingEngine { protected static class SpellEventListener implements ISpellEventListener { private ISpellingProblemCollector fCollector ; public SpellEventListener ( ISpellingProblemCollector collector ) { super ( ) ; fCollector = collector ; } public void handle ( ISpellEvent event ) { fCollector . accept ( new RubySpellingProblem ( event ) ) ; } } public void check ( IDocument document , IRegion [ ] regions , SpellingContext context , ISpellingProblemCollector collector , IProgressMonitor monitor ) { IPreferenceStore preferences = PreferenceConstants . getPreferenceStore ( ) ; if ( collector != null ) { Locale locale = getLocale ( preferences ) ; ISpellChecker checker = SpellCheckEngine . getInstance ( ) . createSpellChecker ( locale , preferences ) ; if ( checker != null ) check ( document , regions , checker , locale , collector , monitor ) ; } } protected abstract void check ( IDocument document , IRegion [ ] regions , ISpellChecker checker , Locale locale , ISpellingProblemCollector collector , IProgressMonitor monitor ) ; private Locale getLocale ( IPreferenceStore preferences ) { Locale defaultLocale = SpellCheckEngine . getDefaultLocale ( ) ; String locale = preferences . getString ( ISpellCheckPreferenceKeys . SPELLING_LOCALE ) ; if ( locale . equals ( defaultLocale . toString ( ) ) ) return defaultLocale ; if ( locale . length ( ) >= ) return new Locale ( locale . substring ( , ) , locale . substring ( , ) ) ; return defaultLocale ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . net . URL ; import java . util . StringTokenizer ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . core . runtime . Preferences . IPropertyChangeListener ; import org . eclipse . core . runtime . Preferences . PropertyChangeEvent ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . AbstractSpellDictionary ; public class TaskTagDictionary extends AbstractSpellDictionary implements IPropertyChangeListener { protected final URL getURL ( ) { return null ; } protected boolean load ( final URL url ) { final Plugin plugin = RubyCore . getPlugin ( ) ; if ( plugin != null ) { plugin . getPluginPreferences ( ) . addPropertyChangeListener ( this ) ; return updateTaskTags ( ) ; } return false ; } public void propertyChange ( final PropertyChangeEvent event ) { if ( RubyCore . COMPILER_TASK_TAGS . equals ( event . getProperty ( ) ) ) updateTaskTags ( ) ; } public void unload ( ) { final Plugin plugin = RubyCore . getPlugin ( ) ; if ( plugin != null ) plugin . getPluginPreferences ( ) . removePropertyChangeListener ( this ) ; super . unload ( ) ; } protected boolean updateTaskTags ( ) { final String tags = RubyCore . getOption ( RubyCore . COMPILER_TASK_TAGS ) ; if ( tags != null ) { unload ( ) ; final StringTokenizer tokenizer = new StringTokenizer ( tags , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) hashWord ( tokenizer . nextToken ( ) ) ; return true ; } return false ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . reconciler . DirtyRegion ; import org . eclipse . jface . text . reconciler . IReconcilingStrategy ; import org . eclipse . jface . text . reconciler . IReconcilingStrategyExtension ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . spelling . ISpellingProblemCollector ; import org . eclipse . ui . texteditor . spelling . SpellingContext ; import org . eclipse . ui . texteditor . spelling . SpellingProblem ; import org . eclipse . ui . texteditor . spelling . SpellingService ; import org . rubypeople . rdt . core . IProblemRequestor ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . IProblem ; public class RubySpellingReconcileStrategy implements IReconcilingStrategy , IReconcilingStrategyExtension { private class SpellingProblemCollector implements ISpellingProblemCollector { public void accept ( SpellingProblem problem ) { IProblemRequestor requestor = fRequestor ; if ( requestor != null ) { try { int line = fDocument . getLineOfOffset ( problem . getOffset ( ) ) + ; String word = fDocument . get ( problem . getOffset ( ) , problem . getLength ( ) ) ; boolean dictionaryMatch = false ; boolean sentenceStart = false ; if ( problem instanceof RubySpellingProblem ) { dictionaryMatch = ( ( RubySpellingProblem ) problem ) . isDictionaryMatch ( ) ; sentenceStart = ( ( RubySpellingProblem ) problem ) . isSentenceStart ( ) ; } IEditorInput editorInput = fEditor . getEditorInput ( ) ; if ( editorInput != null ) { CoreSpellingProblem iProblem = new CoreSpellingProblem ( problem . getOffset ( ) , problem . getOffset ( ) + problem . getLength ( ) - , line , problem . getMessage ( ) , word , dictionaryMatch , sentenceStart , fDocument , editorInput . getName ( ) ) ; requestor . acceptProblem ( iProblem ) ; } } catch ( BadLocationException x ) { } } } public void beginCollecting ( ) { if ( fRequestor != null ) fRequestor . beginReporting ( ) ; } public void endCollecting ( ) { if ( fRequestor != null ) fRequestor . endReporting ( ) ; } } public static final int SPELLING_PROBLEM_ID = ; private ITextEditor fEditor ; private IDocument fDocument ; private IProgressMonitor fProgressMonitor ; private IProblemRequestor fRequestor ; private ISpellingProblemCollector fCollector ; private SpellingContext fSpellingContext ; public RubySpellingReconcileStrategy ( ITextEditor editor ) { fEditor = editor ; fCollector = new SpellingProblemCollector ( ) ; fSpellingContext = new SpellingContext ( ) ; fSpellingContext . setContentType ( Platform . getContentTypeManager ( ) . getContentType ( RubyCore . RUBY_SOURCE_CONTENT_TYPE ) ) ; updateProblemRequester ( ) ; } public void initialReconcile ( ) { reconcile ( new Region ( , fDocument . getLength ( ) ) ) ; } public void reconcile ( DirtyRegion dirtyRegion , IRegion subRegion ) { reconcile ( subRegion ) ; } public void reconcile ( IRegion region ) { if ( fRequestor != null && isSpellingEnabled ( ) ) { boolean force = false ; Display display = null ; final String currentEngine = EditorsUI . getPreferenceStore ( ) . getString ( SpellingService . PREFERENCE_SPELLING_ENGINE ) ; if ( currentEngine == null || ! currentEngine . equals ( "" ) ) { force = true ; display = Display . getCurrent ( ) ; if ( display == null ) { display = Display . getDefault ( ) ; } display . syncExec ( new Runnable ( ) { public void run ( ) { EditorsUI . getPreferenceStore ( ) . setValue ( SpellingService . PREFERENCE_SPELLING_ENGINE , "" ) ; } } ) ; } EditorsUI . getSpellingService ( ) . check ( fDocument , fSpellingContext , fCollector , fProgressMonitor ) ; if ( force ) { display . syncExec ( new Runnable ( ) { public void run ( ) { EditorsUI . getPreferenceStore ( ) . setValue ( SpellingService . PREFERENCE_SPELLING_ENGINE , currentEngine ) ; } } ) ; } } } private boolean isSpellingEnabled ( ) { return EditorsUI . getPreferenceStore ( ) . getBoolean ( SpellingService . PREFERENCE_SPELLING_ENABLED ) ; } public void setDocument ( IDocument document ) { fDocument = document ; updateProblemRequester ( ) ; } public void setProgressMonitor ( IProgressMonitor monitor ) { fProgressMonitor = monitor ; } private void updateProblemRequester ( ) { IAnnotationModel model = fEditor . getDocumentProvider ( ) . getAnnotationModel ( fEditor . getEditorInput ( ) ) ; fRequestor = ( model instanceof IProblemRequestor ) ? ( IProblemRequestor ) model : null ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . net . URL ; import java . util . Locale ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . LocaleSensitiveSpellDictionary ; public class SpellReconcileDictionary extends LocaleSensitiveSpellDictionary { public SpellReconcileDictionary ( final Locale locale , final URL location ) { super ( locale , location ) ; } public boolean isCorrect ( final String word ) { return super . isCorrect ( word ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class WordCorrectionProposal implements IRubyCompletionProposal { public static String getHtmlRepresentation ( final String string ) { final int length = string . length ( ) ; final StringBuffer buffer = new StringBuffer ( string ) ; return buffer . toString ( ) ; } private final IInvocationContext fContext ; private final int fLength ; private final String fLine ; private final int fOffset ; private final int fRelevance ; private final String fWord ; public WordCorrectionProposal ( final String word , final String [ ] arguments , final int offset , final int length , final IInvocationContext context , final int relevance ) { fWord = Character . isUpperCase ( arguments [ ] . charAt ( ) ) ? Character . toUpperCase ( word . charAt ( ) ) + word . substring ( ) : word ; fOffset = offset ; fLength = length ; fContext = context ; fRelevance = relevance ; final StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( getHtmlRepresentation ( arguments [ ] ) ) ; buffer . append ( "" ) ; buffer . append ( getHtmlRepresentation ( fWord ) ) ; buffer . append ( "" ) ; buffer . append ( getHtmlRepresentation ( arguments [ ] ) ) ; buffer . append ( "" ) ; fLine = buffer . toString ( ) ; } public final void apply ( final IDocument document ) { try { document . replace ( fOffset , fLength , fWord ) ; } catch ( BadLocationException exception ) { } } public String getAdditionalProposalInfo ( ) { return fLine ; } public final IContextInformation getContextInformation ( ) { return null ; } public String getDisplayString ( ) { return Messages . format ( RubyUIMessages . Spelling_correct_label , new String [ ] { fWord } ) ; } public Image getImage ( ) { return RubyPluginImages . get ( RubyPluginImages . IMG_CORRECTION_RENAME ) ; } public final int getRelevance ( ) { return fRelevance ; } public final Point getSelection ( final IDocument document ) { int offset = fContext . getSelectionOffset ( ) ; int length = fContext . getSelectionLength ( ) ; final int delta = fWord . length ( ) - fLength ; if ( offset <= fOffset && offset + length >= fOffset ) length += delta ; else if ( offset > fOffset && offset + length > fOffset + fLength ) { offset += delta ; length -= delta ; } else length += delta ; return new Point ( offset , length ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellCheckEngine ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellChecker ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class AddWordProposal implements IRubyCompletionProposal { private final IInvocationContext fContext ; private final String fWord ; public AddWordProposal ( final String word , final IInvocationContext context ) { fContext = context ; fWord = word ; } public final void apply ( final IDocument document ) { final ISpellCheckEngine engine = SpellCheckEngine . getInstance ( ) ; final ISpellChecker checker = engine . createSpellChecker ( engine . getLocale ( ) , PreferenceConstants . getPreferenceStore ( ) ) ; if ( checker != null ) { checker . addWord ( fWord ) ; RubySpellingProblem . removeAllInActiveEditor ( fWord ) ; } } public String getAdditionalProposalInfo ( ) { return Messages . format ( RubyUIMessages . Spelling_add_info , new String [ ] { WordCorrectionProposal . getHtmlRepresentation ( fWord ) } ) ; } public final IContextInformation getContextInformation ( ) { return null ; } public String getDisplayString ( ) { return Messages . format ( RubyUIMessages . Spelling_add_label , new String [ ] { fWord } ) ; } public Image getImage ( ) { return RubyPluginImages . get ( RubyPluginImages . IMG_CORRECTION_ADD ) ; } public int getRelevance ( ) { return Integer . MIN_VALUE ; } public final Point getSelection ( final IDocument document ) { return new Point ( fContext . getSelectionOffset ( ) , fContext . getSelectionLength ( ) ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . io . IOException ; import java . io . InputStream ; import java . net . MalformedURLException ; import java . net . URL ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Locale ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . DefaultSpellChecker ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellCheckEngine ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellCheckPreferenceKeys ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellChecker ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellDictionary ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . PersistentSpellDictionary ; public class SpellCheckEngine implements ISpellCheckEngine , IPropertyChangeListener { public static final String DICTIONARY_LOCATION = "" ; private static ISpellCheckEngine fgEngine = null ; public static Set < Locale > getAvailableLocales ( ) { URL url = null ; Locale locale = null ; InputStream stream = null ; final Set < Locale > result = new HashSet < Locale > ( ) ; try { final URL location = getDictionaryLocation ( ) ; if ( location == null ) return Collections . EMPTY_SET ; final Locale [ ] locales = Locale . getAvailableLocales ( ) ; for ( int index = ; index < locales . length ; index ++ ) { locale = locales [ index ] ; url = new URL ( location , locale . toString ( ) + "" ) ; try { stream = url . openStream ( ) ; if ( stream != null ) { try { result . add ( locale ) ; } finally { stream . close ( ) ; } } } catch ( IOException exception ) { } } } catch ( MalformedURLException exception ) { } return result ; } public static Locale getDefaultLocale ( ) { return Locale . getDefault ( ) ; } private static URL getDictionaryLocation ( ) throws MalformedURLException { final Plugin plugin = RubyPlugin . getDefault ( ) ; if ( plugin != null ) return plugin . getBundle ( ) . getEntry ( "" + DICTIONARY_LOCATION ) ; return null ; } public static final synchronized ISpellCheckEngine getInstance ( ) { if ( fgEngine == null ) fgEngine = new SpellCheckEngine ( ) ; return fgEngine ; } private final Set < ISpellDictionary > fGlobalDictionaries = new HashSet < ISpellDictionary > ( ) ; private Locale fLocale = null ; private ISpellChecker fChecker = null ; private final Map < Locale , ISpellDictionary > fLocaleDictionaries = new HashMap < Locale , ISpellDictionary > ( ) ; private IPreferenceStore fPreferences = null ; private ISpellDictionary fUserDictionary = null ; private SpellCheckEngine ( ) { fGlobalDictionaries . add ( new TaskTagDictionary ( ) ) ; try { Locale locale = null ; final URL location = getDictionaryLocation ( ) ; for ( final Iterator < Locale > iterator = getAvailableLocales ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { locale = iterator . next ( ) ; fLocaleDictionaries . put ( locale , new SpellReconcileDictionary ( locale , location ) ) ; } } catch ( MalformedURLException exception ) { } } public final synchronized ISpellChecker createSpellChecker ( final Locale locale , final IPreferenceStore store ) { if ( fLocale != null && fLocale . equals ( locale ) ) return fChecker ; if ( fChecker == null ) { fChecker = new DefaultSpellChecker ( store ) ; store . addPropertyChangeListener ( this ) ; fPreferences = store ; ISpellDictionary dictionary = null ; for ( Iterator < ISpellDictionary > iterator = fGlobalDictionaries . iterator ( ) ; iterator . hasNext ( ) ; ) { dictionary = iterator . next ( ) ; fChecker . addDictionary ( dictionary ) ; } } ISpellDictionary dictionary = null ; if ( fLocale != null ) { dictionary = ( ISpellDictionary ) fLocaleDictionaries . get ( fLocale ) ; if ( dictionary != null ) { fChecker . removeDictionary ( dictionary ) ; dictionary . unload ( ) ; } } fLocale = locale ; dictionary = ( ISpellDictionary ) fLocaleDictionaries . get ( locale ) ; if ( dictionary == null ) { if ( ! getDefaultLocale ( ) . equals ( locale ) ) { if ( fPreferences != null ) fPreferences . removePropertyChangeListener ( this ) ; fChecker = null ; fLocale = null ; } } else fChecker . addDictionary ( dictionary ) ; if ( fPreferences != null ) propertyChange ( new PropertyChangeEvent ( this , ISpellCheckPreferenceKeys . SPELLING_USER_DICTIONARY , null , fPreferences . getString ( ISpellCheckPreferenceKeys . SPELLING_USER_DICTIONARY ) ) ) ; return fChecker ; } public final Locale getLocale ( ) { return fLocale ; } public final void propertyChange ( final PropertyChangeEvent event ) { if ( fChecker != null && event . getProperty ( ) . equals ( ISpellCheckPreferenceKeys . SPELLING_USER_DICTIONARY ) ) { if ( fUserDictionary != null ) { fChecker . removeDictionary ( fUserDictionary ) ; fUserDictionary = null ; } final String file = ( String ) event . getNewValue ( ) ; if ( file . length ( ) > ) { try { final URL url = new URL ( "" , null , file ) ; InputStream stream = url . openStream ( ) ; if ( stream != null ) { try { fUserDictionary = new PersistentSpellDictionary ( url ) ; fChecker . addDictionary ( fUserDictionary ) ; } finally { stream . close ( ) ; } } } catch ( MalformedURLException exception ) { } catch ( IOException exception ) { } } } } public synchronized final void registerDictionary ( final ISpellDictionary dictionary ) { fGlobalDictionaries . add ( dictionary ) ; if ( fChecker != null ) fChecker . addDictionary ( dictionary ) ; } public synchronized final void registerDictionary ( final Locale locale , final ISpellDictionary dictionary ) { fLocaleDictionaries . put ( locale , dictionary ) ; if ( fChecker != null && fLocale != null && fLocale . equals ( locale ) ) fChecker . addDictionary ( dictionary ) ; } public synchronized final void unload ( ) { ISpellDictionary dictionary = null ; for ( final Iterator < ISpellDictionary > iterator = fGlobalDictionaries . iterator ( ) ; iterator . hasNext ( ) ; ) { dictionary = iterator . next ( ) ; dictionary . unload ( ) ; } for ( final Iterator < ISpellDictionary > iterator = fLocaleDictionaries . values ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { dictionary = iterator . next ( ) ; dictionary . unload ( ) ; } if ( fPreferences != null ) fPreferences . removePropertyChangeListener ( this ) ; fUserDictionary = null ; fChecker = null ; } public synchronized final void unregisterDictionary ( final ISpellDictionary dictionary ) { fGlobalDictionaries . remove ( dictionary ) ; fLocaleDictionaries . values ( ) . remove ( dictionary ) ; if ( fChecker != null ) fChecker . removeDictionary ( dictionary ) ; dictionary . unload ( ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . content . IContentType ; import org . eclipse . core . runtime . content . IContentTypeManager ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . texteditor . spelling . ISpellingEngine ; import org . eclipse . ui . texteditor . spelling . ISpellingProblemCollector ; import org . eclipse . ui . texteditor . spelling . SpellingContext ; import org . eclipse . ui . texteditor . spelling . SpellingEngineDescriptor ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class DefaultSpellingEngine implements ISpellingEngine { private static final IContentType TEXT_CONTENT_TYPE = Platform . getContentTypeManager ( ) . getContentType ( IContentTypeManager . CT_TEXT ) ; private static final IContentType RUBY_CONTENT_TYPE = Platform . getContentTypeManager ( ) . getContentType ( RubyCore . RUBY_SOURCE_CONTENT_TYPE ) ; private static final IContentType JAVA_CONTENT_TYPE = Platform . getContentTypeManager ( ) . getContentType ( "" ) ; private static final IContentType PROPERTIES_CONTENT_TYPE = Platform . getContentTypeManager ( ) . getContentType ( "" ) ; private Map < IContentType , ISpellingEngine > fEngines = new HashMap < IContentType , ISpellingEngine > ( ) ; public DefaultSpellingEngine ( ) { if ( RUBY_CONTENT_TYPE != null ) fEngines . put ( RUBY_CONTENT_TYPE , new RubySpellingEngine ( ) ) ; if ( TEXT_CONTENT_TYPE != null ) fEngines . put ( TEXT_CONTENT_TYPE , new TextSpellingEngine ( ) ) ; } public void check ( IDocument document , IRegion [ ] regions , SpellingContext context , ISpellingProblemCollector collector , IProgressMonitor monitor ) { ISpellingEngine engine = getEngine ( context . getContentType ( ) ) ; if ( engine == null ) engine = getEngine ( TEXT_CONTENT_TYPE ) ; if ( engine != null ) engine . check ( document , regions , context , collector , monitor ) ; } private ISpellingEngine getEngine ( IContentType contentType ) { if ( contentType == null ) return null ; if ( fEngines . containsKey ( contentType ) ) return ( ISpellingEngine ) fEngines . get ( contentType ) ; if ( contentType . equals ( JAVA_CONTENT_TYPE ) || contentType . equals ( PROPERTIES_CONTENT_TYPE ) ) { SpellingEngineDescriptor [ ] descriptors = EditorsUI . getSpellingService ( ) . getSpellingEngineDescriptors ( ) ; for ( SpellingEngineDescriptor desc : descriptors ) { String id = desc . getId ( ) ; if ( id . equals ( "" ) ) { try { return desc . createEngine ( ) ; } catch ( CoreException e ) { RubyPlugin . log ( e . getStatus ( ) ) ; } } } } return getEngine ( contentType . getBaseType ( ) ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . Locale ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . ui . texteditor . spelling . ISpellingProblemCollector ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellChecker ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellEventListener ; public class TextSpellingEngine extends SpellingEngine { protected void check ( IDocument document , IRegion [ ] regions , ISpellChecker checker , Locale locale , ISpellingProblemCollector collector , IProgressMonitor monitor ) { ISpellEventListener listener = new SpellEventListener ( collector ) ; try { checker . addListener ( listener ) ; for ( int i = ; i < regions . length ; i ++ ) { if ( monitor != null && monitor . isCanceled ( ) ) return ; checker . execute ( new SpellCheckIterator ( document , regions [ i ] , locale ) ) ; } } finally { checker . removeListener ( listener ) ; } } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellCheckEngine ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellChecker ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . RankedWordProposal ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; import org . rubypeople . rdt . ui . text . ruby . IQuickFixProcessor ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class WordQuickFixProcessor implements IQuickFixProcessor { public IRubyCompletionProposal [ ] getCorrections ( IInvocationContext context , IProblemLocation [ ] locations ) throws CoreException { final int threshold = PreferenceConstants . getPreferenceStore ( ) . getInt ( PreferenceConstants . SPELLING_PROPOSAL_THRESHOLD ) ; int size = ; List proposals = null ; String [ ] arguments = null ; IProblemLocation location = null ; RankedWordProposal proposal = null ; IRubyCompletionProposal [ ] result = null ; boolean fixed = false ; boolean match = false ; boolean sentence = false ; final ISpellCheckEngine engine = SpellCheckEngine . getInstance ( ) ; final ISpellChecker checker = engine . createSpellChecker ( engine . getLocale ( ) , PreferenceConstants . getPreferenceStore ( ) ) ; if ( checker != null ) { for ( int index = ; index < locations . length ; index ++ ) { location = locations [ index ] ; if ( location . getProblemId ( ) == RubySpellingReconcileStrategy . SPELLING_PROBLEM_ID ) { arguments = location . getProblemArguments ( ) ; if ( arguments != null && arguments . length > ) { sentence = Boolean . valueOf ( arguments [ ] ) . booleanValue ( ) ; match = Boolean . valueOf ( arguments [ ] ) . booleanValue ( ) ; if ( ( sentence && match ) && ! fixed ) result = new IRubyCompletionProposal [ ] { new ChangeCaseProposal ( arguments , location . getOffset ( ) , location . getLength ( ) , context , engine . getLocale ( ) ) } ; else { proposals = new ArrayList ( checker . getProposals ( arguments [ ] , sentence ) ) ; size = proposals . size ( ) ; if ( threshold > && size > threshold ) { Collections . sort ( proposals ) ; proposals = proposals . subList ( size - threshold - , size - ) ; size = proposals . size ( ) ; } boolean extendable = ! fixed ? checker . acceptsWords ( ) : false ; result = new IRubyCompletionProposal [ size + ( extendable ? : ) ] ; for ( index = ; index < size ; index ++ ) { proposal = ( RankedWordProposal ) proposals . get ( index ) ; result [ index ] = new WordCorrectionProposal ( proposal . getText ( ) , arguments , location . getOffset ( ) , location . getLength ( ) , context , proposal . getRank ( ) ) ; } if ( extendable ) result [ index ++ ] = new AddWordProposal ( arguments [ ] , context ) ; result [ index ++ ] = new WordIgnoreProposal ( arguments [ ] , context ) ; } break ; } } } } return result ; } public boolean hasCorrections ( IRubyScript unit , int id ) { return id == RubySpellingReconcileStrategy . SPELLING_PROBLEM_ID ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . IAnnotationModelExtension ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . spelling . SpellingProblem ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyDocumentProvider . ProblemAnnotation ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellEvent ; public class RubySpellingProblem extends SpellingProblem { private ISpellEvent fSpellEvent ; public RubySpellingProblem ( ISpellEvent spellEvent ) { super ( ) ; fSpellEvent = spellEvent ; } public int getOffset ( ) { return fSpellEvent . getBegin ( ) ; } public int getLength ( ) { return fSpellEvent . getEnd ( ) - fSpellEvent . getBegin ( ) + ; } public String getMessage ( ) { if ( isSentenceStart ( ) && isDictionaryMatch ( ) ) return Messages . format ( RubyUIMessages . Spelling_error_case_label , new String [ ] { fSpellEvent . getWord ( ) } ) ; return Messages . format ( RubyUIMessages . Spelling_error_label , new String [ ] { fSpellEvent . getWord ( ) } ) ; } public ICompletionProposal [ ] getProposals ( ) { return new ICompletionProposal [ ] ; } public boolean isDictionaryMatch ( ) { return fSpellEvent . isMatch ( ) ; } public boolean isSentenceStart ( ) { return fSpellEvent . isStart ( ) ; } public static void removeAllInActiveEditor ( String word ) { if ( word == null ) return ; IWorkbenchPage activePage = RubyPlugin . getActivePage ( ) ; if ( activePage == null ) return ; IEditorPart editor = activePage . getActiveEditor ( ) ; if ( activePage . getActivePart ( ) != editor || ! ( editor instanceof ITextEditor ) ) return ; IDocumentProvider documentProvider = ( ( ITextEditor ) editor ) . getDocumentProvider ( ) ; if ( documentProvider == null ) return ; IAnnotationModel model = documentProvider . getAnnotationModel ( editor . getEditorInput ( ) ) ; if ( model == null ) return ; boolean supportsBatchReplace = ( model instanceof IAnnotationModelExtension ) ; List toBeRemovedAnnotations = new ArrayList ( ) ; Iterator iter = model . getAnnotationIterator ( ) ; while ( iter . hasNext ( ) ) { Annotation annotation = ( Annotation ) iter . next ( ) ; if ( ProblemAnnotation . SPELLING_ANNOTATION_TYPE . equals ( annotation . getType ( ) ) && annotation instanceof ProblemAnnotation ) { String [ ] arguments = ( ( ProblemAnnotation ) annotation ) . getArguments ( ) ; if ( arguments != null && arguments . length > && word . equals ( arguments [ ] ) ) if ( supportsBatchReplace ) toBeRemovedAnnotations . add ( annotation ) ; else model . removeAnnotation ( annotation ) ; } } if ( supportsBatchReplace && ! toBeRemovedAnnotations . isEmpty ( ) ) { Annotation [ ] annotationArray = ( Annotation [ ] ) toBeRemovedAnnotations . toArray ( new Annotation [ toBeRemovedAnnotations . size ( ) ] ) ; ( ( IAnnotationModelExtension ) model ) . replaceAnnotations ( annotationArray , null ) ; } } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . Locale ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . ui . texteditor . spelling . ISpellingProblemCollector ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellChecker ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellEventListener ; public class RubySpellingEngine extends SpellingEngine { protected void check ( IDocument document , IRegion [ ] regions , ISpellChecker checker , Locale locale , ISpellingProblemCollector collector , IProgressMonitor monitor ) { ISpellEventListener listener = new SpellEventListener ( collector ) ; try { checker . addListener ( listener ) ; try { for ( int i = ; i < regions . length ; i ++ ) { IRegion region = regions [ i ] ; ITypedRegion [ ] partitions = TextUtilities . computePartitioning ( document , IRubyPartitions . RUBY_PARTITIONING , region . getOffset ( ) , region . getLength ( ) , false ) ; for ( int index = ; index < partitions . length ; index ++ ) { if ( monitor != null && monitor . isCanceled ( ) ) return ; ITypedRegion partition = partitions [ index ] ; if ( partition . getType ( ) . equals ( IRubyPartitions . RUBY_MULTI_LINE_COMMENT ) || partition . getType ( ) . equals ( IRubyPartitions . RUBY_SINGLE_LINE_COMMENT ) ) checker . execute ( new SpellCheckIterator ( document , partition , locale ) ) ; } } } catch ( BadLocationException x ) { RubyPlugin . log ( x ) ; } } finally { checker . removeListener ( listener ) ; } } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . reconciler . DirtyRegion ; import org . eclipse . jface . text . reconciler . IReconcilingStrategy ; import org . eclipse . jface . text . reconciler . IReconcilingStrategyExtension ; public class CompositeReconcilingStrategy implements IReconcilingStrategy , IReconcilingStrategyExtension { private IReconcilingStrategy [ ] fStrategies ; public CompositeReconcilingStrategy ( ) { } public void setReconcilingStrategies ( IReconcilingStrategy [ ] strategies ) { fStrategies = strategies ; } public IReconcilingStrategy [ ] getReconcilingStrategies ( ) { return fStrategies ; } public void setDocument ( IDocument document ) { if ( fStrategies == null ) return ; for ( int i = ; i < fStrategies . length ; i ++ ) fStrategies [ i ] . setDocument ( document ) ; } public void reconcile ( DirtyRegion dirtyRegion , IRegion subRegion ) { if ( fStrategies == null ) return ; for ( int i = ; i < fStrategies . length ; i ++ ) fStrategies [ i ] . reconcile ( dirtyRegion , subRegion ) ; } public void reconcile ( IRegion partition ) { if ( fStrategies == null ) return ; for ( int i = ; i < fStrategies . length ; i ++ ) fStrategies [ i ] . reconcile ( partition ) ; } public void setProgressMonitor ( IProgressMonitor monitor ) { if ( fStrategies == null ) return ; for ( int i = ; i < fStrategies . length ; i ++ ) { if ( fStrategies [ i ] instanceof IReconcilingStrategyExtension ) { IReconcilingStrategyExtension extension = ( IReconcilingStrategyExtension ) fStrategies [ i ] ; extension . setProgressMonitor ( monitor ) ; } } } public void initialReconcile ( ) { if ( fStrategies == null ) return ; for ( int i = ; i < fStrategies . length ; i ++ ) { if ( fStrategies [ i ] instanceof IReconcilingStrategyExtension ) { IReconcilingStrategyExtension extension = ( IReconcilingStrategyExtension ) fStrategies [ i ] ; extension . initialReconcile ( ) ; } } } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IContributor ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . InvalidRegistryObjectException ; import org . eclipse . core . runtime . PerformanceStats ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . IDocument ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposalComputer ; final class CompletionProposalComputerDescriptor { private static final String DEFAULT_CATEGORY_ID = "" ; private static final String CATEGORY_ID = "" ; private static final String TYPE = "" ; private static final String CLASS = "" ; private static final String ACTIVATE = "" ; private static final String PARTITION = "" ; private static final Set < String > PARTITION_SET ; private static final String PERFORMANCE_EVENT = RubyPlugin . getPluginId ( ) + "" ; private static final boolean MEASURE_PERFORMANCE = PerformanceStats . isEnabled ( PERFORMANCE_EVENT ) ; private static final long MAX_DELAY = ; private static final String COMPUTE_COMPLETION_PROPOSALS = "" ; private static final String COMPUTE_CONTEXT_INFORMATION = "" ; private static final String SESSION_STARTED = "" ; private static final String SESSION_ENDED = "" ; static { Set < String > partitions = new HashSet < String > ( ) ; partitions . add ( IDocument . DEFAULT_CONTENT_TYPE ) ; partitions . add ( IRubyPartitions . RUBY_MULTI_LINE_COMMENT ) ; partitions . add ( IRubyPartitions . RUBY_SINGLE_LINE_COMMENT ) ; partitions . add ( IRubyPartitions . RUBY_REGULAR_EXPRESSION ) ; partitions . add ( IRubyPartitions . RUBY_STRING ) ; partitions . add ( IRubyPartitions . RUBY_COMMAND ) ; PARTITION_SET = Collections . unmodifiableSet ( partitions ) ; } private final String fId ; private final String fName ; private final String fClass ; private final boolean fActivate ; private final Set < String > fPartitions ; private final IConfigurationElement fElement ; private final CompletionProposalComputerRegistry fRegistry ; private IRubyCompletionProposalComputer fComputer ; private final CompletionProposalCategory fCategory ; private String fLastError ; private boolean fIsReportingDelay = false ; private long fStart ; CompletionProposalComputerDescriptor ( IConfigurationElement element , CompletionProposalComputerRegistry registry , List < CompletionProposalCategory > categories ) throws InvalidRegistryObjectException { Assert . isLegal ( registry != null ) ; Assert . isLegal ( element != null ) ; fRegistry = registry ; fElement = element ; IExtension extension = element . getDeclaringExtension ( ) ; fId = extension . getUniqueIdentifier ( ) ; checkNotNull ( fId , "" ) ; String name = extension . getLabel ( ) ; if ( name . length ( ) == ) fName = fId ; else fName = name ; Set < String > partitions = new HashSet < String > ( ) ; IConfigurationElement [ ] children = element . getChildren ( PARTITION ) ; if ( children . length == ) { fPartitions = PARTITION_SET ; } else { for ( int i = ; i < children . length ; i ++ ) { String type = children [ i ] . getAttribute ( TYPE ) ; checkNotNull ( type , TYPE ) ; partitions . add ( type ) ; } fPartitions = Collections . unmodifiableSet ( partitions ) ; } String activateAttribute = element . getAttribute ( ACTIVATE ) ; fActivate = Boolean . valueOf ( activateAttribute ) . booleanValue ( ) ; fClass = element . getAttribute ( CLASS ) ; checkNotNull ( fClass , CLASS ) ; String categoryId = element . getAttribute ( CATEGORY_ID ) ; if ( categoryId == null ) categoryId = DEFAULT_CATEGORY_ID ; CompletionProposalCategory category = null ; for ( CompletionProposalCategory cat : categories ) { if ( cat . getId ( ) . equals ( categoryId ) ) { category = cat ; break ; } } if ( category == null ) { fCategory = new CompletionProposalCategory ( categoryId , fName , registry ) ; categories . add ( fCategory ) ; } else { fCategory = category ; } } private void checkNotNull ( Object obj , String attribute ) throws InvalidRegistryObjectException { if ( obj == null ) { Object [ ] args = { getId ( ) , fElement . getContributor ( ) . getName ( ) , attribute } ; String message = Messages . format ( RubyTextMessages . CompletionProposalComputerDescriptor_illegal_attribute_message , args ) ; IStatus status = new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , message , null ) ; RubyPlugin . log ( status ) ; throw new InvalidRegistryObjectException ( ) ; } } public String getId ( ) { return fId ; } public String getName ( ) { return fName ; } public Set < String > getPartitions ( ) { return fPartitions ; } private synchronized IRubyCompletionProposalComputer getComputer ( ) throws CoreException , InvalidRegistryObjectException { if ( fComputer == null && ( fActivate || isPluginLoaded ( ) ) ) fComputer = createComputer ( ) ; return fComputer ; } private boolean isPluginLoaded ( ) { Bundle bundle = getBundle ( ) ; return bundle != null && bundle . getState ( ) == Bundle . ACTIVE ; } private Bundle getBundle ( ) { String namespace = fElement . getDeclaringExtension ( ) . getContributor ( ) . getName ( ) ; Bundle bundle = Platform . getBundle ( namespace ) ; return bundle ; } public IRubyCompletionProposalComputer createComputer ( ) throws CoreException , InvalidRegistryObjectException { return ( IRubyCompletionProposalComputer ) fElement . createExecutableExtension ( CLASS ) ; } public List computeCompletionProposals ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { if ( ! isEnabled ( ) ) return Collections . EMPTY_LIST ; IStatus status ; try { IRubyCompletionProposalComputer computer = getComputer ( ) ; if ( computer == null ) return Collections . EMPTY_LIST ; try { PerformanceStats stats = startMeter ( context , computer ) ; List proposals = computer . computeCompletionProposals ( context , monitor ) ; stopMeter ( stats , COMPUTE_COMPLETION_PROPOSALS ) ; if ( proposals != null ) { fLastError = computer . getErrorMessage ( ) ; return proposals ; } } finally { fIsReportingDelay = true ; } status = createAPIViolationStatus ( COMPUTE_COMPLETION_PROPOSALS ) ; } catch ( InvalidRegistryObjectException x ) { status = createExceptionStatus ( x ) ; } catch ( CoreException x ) { status = createExceptionStatus ( x ) ; } catch ( RuntimeException x ) { status = createExceptionStatus ( x ) ; } finally { monitor . done ( ) ; } fRegistry . informUser ( this , status ) ; return Collections . EMPTY_LIST ; } public List computeContextInformation ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { if ( ! isEnabled ( ) ) return Collections . EMPTY_LIST ; IStatus status ; try { IRubyCompletionProposalComputer computer = getComputer ( ) ; if ( computer == null ) return Collections . EMPTY_LIST ; PerformanceStats stats = startMeter ( context , computer ) ; List proposals = computer . computeContextInformation ( context , monitor ) ; stopMeter ( stats , COMPUTE_CONTEXT_INFORMATION ) ; if ( proposals != null ) { fLastError = computer . getErrorMessage ( ) ; return proposals ; } status = createAPIViolationStatus ( COMPUTE_CONTEXT_INFORMATION ) ; } catch ( InvalidRegistryObjectException x ) { status = createExceptionStatus ( x ) ; } catch ( CoreException x ) { status = createExceptionStatus ( x ) ; } catch ( RuntimeException x ) { status = createExceptionStatus ( x ) ; } finally { monitor . done ( ) ; } fRegistry . informUser ( this , status ) ; return Collections . EMPTY_LIST ; } public void sessionStarted ( ) { if ( ! isEnabled ( ) ) return ; IStatus status ; try { IRubyCompletionProposalComputer computer = getComputer ( ) ; if ( computer == null ) return ; PerformanceStats stats = startMeter ( SESSION_STARTED , computer ) ; computer . sessionStarted ( ) ; stopMeter ( stats , SESSION_ENDED ) ; return ; } catch ( InvalidRegistryObjectException x ) { status = createExceptionStatus ( x ) ; } catch ( CoreException x ) { status = createExceptionStatus ( x ) ; } catch ( RuntimeException x ) { status = createExceptionStatus ( x ) ; } fRegistry . informUser ( this , status ) ; } public void sessionEnded ( ) { if ( ! isEnabled ( ) ) return ; IStatus status ; try { IRubyCompletionProposalComputer computer = getComputer ( ) ; if ( computer == null ) return ; PerformanceStats stats = startMeter ( SESSION_ENDED , computer ) ; computer . sessionEnded ( ) ; stopMeter ( stats , SESSION_ENDED ) ; return ; } catch ( InvalidRegistryObjectException x ) { status = createExceptionStatus ( x ) ; } catch ( CoreException x ) { status = createExceptionStatus ( x ) ; } catch ( RuntimeException x ) { status = createExceptionStatus ( x ) ; } fRegistry . informUser ( this , status ) ; } private PerformanceStats startMeter ( Object context , IRubyCompletionProposalComputer computer ) { final PerformanceStats stats ; if ( MEASURE_PERFORMANCE ) { stats = PerformanceStats . getStats ( PERFORMANCE_EVENT , computer ) ; stats . startRun ( context . toString ( ) ) ; } else { stats = null ; } if ( fIsReportingDelay ) { fStart = System . currentTimeMillis ( ) ; } return stats ; } private void stopMeter ( final PerformanceStats stats , String operation ) { if ( MEASURE_PERFORMANCE ) { stats . endRun ( ) ; if ( stats . isFailure ( ) ) { IStatus status = createPerformanceStatus ( operation ) ; fRegistry . informUser ( this , status ) ; return ; } } if ( fIsReportingDelay ) { long current = System . currentTimeMillis ( ) ; if ( current - fStart > MAX_DELAY ) { IStatus status = createPerformanceStatus ( operation ) ; fRegistry . informUser ( this , status ) ; } } } private IStatus createExceptionStatus ( InvalidRegistryObjectException x ) { String blame = createBlameMessage ( ) ; String reason = RubyTextMessages . CompletionProposalComputerDescriptor_reason_invalid ; return new Status ( IStatus . INFO , RubyPlugin . getPluginId ( ) , IStatus . OK , blame + "" + reason , x ) ; } private IStatus createExceptionStatus ( CoreException x ) { String blame = createBlameMessage ( ) ; String reason = RubyTextMessages . CompletionProposalComputerDescriptor_reason_instantiation ; return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . OK , blame + "" + reason , x ) ; } private IStatus createExceptionStatus ( RuntimeException x ) { String blame = createBlameMessage ( ) ; String reason = RubyTextMessages . CompletionProposalComputerDescriptor_reason_runtime_ex ; return new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , blame + "" + reason , x ) ; } private IStatus createAPIViolationStatus ( String operation ) { String blame = createBlameMessage ( ) ; Object [ ] args = { operation } ; String reason = Messages . format ( RubyTextMessages . CompletionProposalComputerDescriptor_reason_API , args ) ; return new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , blame + "" + reason , null ) ; } private IStatus createPerformanceStatus ( String operation ) { String blame = createBlameMessage ( ) ; Object [ ] args = { operation } ; String reason = Messages . format ( RubyTextMessages . CompletionProposalComputerDescriptor_reason_performance , args ) ; return new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , blame + "" + reason , null ) ; } private String createBlameMessage ( ) { Object [ ] args = { getName ( ) , fElement . getDeclaringExtension ( ) . getContributor ( ) . getName ( ) } ; String disable = Messages . format ( RubyTextMessages . CompletionProposalComputerDescriptor_blame_message , args ) ; return disable ; } private boolean isEnabled ( ) { return fCategory . isEnabled ( ) ; } CompletionProposalCategory getCategory ( ) { return fCategory ; } public String getErrorMessage ( ) { return fLastError ; } IContributor getContributor ( ) { try { return fElement . getContributor ( ) ; } catch ( InvalidRegistryObjectException e ) { return null ; } } } package org . rubypeople . rdt . internal . ui . text . ruby ; public interface IInformationControlExtension4 { public void setStatusText ( String statusFieldText ) ; } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . InvalidRegistryObjectException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . PreferenceConstants ; public final class ProposalSorterRegistry { private static final String EXTENSION_POINT = "" ; private static final String DEFAULT_ID = "" ; private static ProposalSorterRegistry fInstance ; public static synchronized ProposalSorterRegistry getDefault ( ) { if ( fInstance == null ) fInstance = new ProposalSorterRegistry ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) , PreferenceConstants . CODEASSIST_SORTER ) ; return fInstance ; } private final IPreferenceStore fPreferenceStore ; private final String fKey ; private Map fSorters = null ; private ProposalSorterHandle fDefaultSorter ; private ProposalSorterRegistry ( final IPreferenceStore preferenceStore , final String key ) { Assert . isTrue ( preferenceStore != null ) ; Assert . isTrue ( key != null ) ; fPreferenceStore = preferenceStore ; fKey = key ; } public ProposalSorterHandle getCurrentSorter ( ) { ensureSortersRead ( ) ; String id = fPreferenceStore . getString ( fKey ) ; ProposalSorterHandle sorter = ( ProposalSorterHandle ) fSorters . get ( id ) ; return sorter != null ? sorter : fDefaultSorter ; } private synchronized void ensureSortersRead ( ) { if ( fSorters != null ) return ; Map sorters = new LinkedHashMap ( ) ; IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; List elements = new ArrayList ( Arrays . asList ( registry . getConfigurationElementsFor ( RubyPlugin . getPluginId ( ) , EXTENSION_POINT ) ) ) ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { IConfigurationElement element = ( IConfigurationElement ) iter . next ( ) ; try { ProposalSorterHandle handle = new ProposalSorterHandle ( element ) ; final String id = handle . getId ( ) ; sorters . put ( id , handle ) ; if ( DEFAULT_ID . equals ( id ) ) fDefaultSorter = handle ; } catch ( InvalidRegistryObjectException x ) { Object [ ] args = { element . toString ( ) } ; String message = Messages . format ( RubyTextMessages . CompletionProposalComputerRegistry_invalid_message , args ) ; IStatus status = new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , message , x ) ; informUser ( status ) ; } } fSorters = sorters ; } private void informUser ( IStatus status ) { RubyPlugin . log ( status ) ; String title = RubyTextMessages . CompletionProposalComputerRegistry_error_dialog_title ; String message = status . getMessage ( ) ; MessageDialog . openError ( RubyPlugin . getActiveWorkbenchShell ( ) , title , message ) ; } public ProposalSorterHandle [ ] getSorters ( ) { ensureSortersRead ( ) ; Collection sorters = fSorters . values ( ) ; return ( ProposalSorterHandle [ ] ) sorters . toArray ( new ProposalSorterHandle [ sorters . size ( ) ] ) ; } public void select ( ProposalSorterHandle handle ) { Assert . isTrue ( handle != null ) ; String id = handle . getId ( ) ; fPreferenceStore . setValue ( fKey , id ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . reconciler . DirtyRegion ; import org . eclipse . jface . text . reconciler . IReconcilingStrategy ; import org . eclipse . jface . text . reconciler . IReconcilingStrategyExtension ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; import org . rubypeople . rdt . ui . RubyUI ; public class RubyReconcilingStrategy implements IReconcilingStrategy , IReconcilingStrategyExtension { private ITextEditor fEditor ; private IWorkingCopyManager fManager ; private IDocumentProvider fDocumentProvider ; private IProgressMonitor fProgressMonitor ; private boolean fNotify = true ; private IRubyReconcilingListener fRubyReconcilingListener ; private boolean fIsRubyReconcilingListener ; public RubyReconcilingStrategy ( ITextEditor editor ) { fEditor = editor ; fManager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; fDocumentProvider = RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) ; fIsRubyReconcilingListener = fEditor instanceof IRubyReconcilingListener ; if ( fIsRubyReconcilingListener ) fRubyReconcilingListener = ( IRubyReconcilingListener ) fEditor ; } private IProblemRequestorExtension getProblemRequestorExtension ( ) { IAnnotationModel model = fDocumentProvider . getAnnotationModel ( fEditor . getEditorInput ( ) ) ; if ( model instanceof IProblemRequestorExtension ) return ( IProblemRequestorExtension ) model ; return null ; } private void reconcile ( final boolean initialReconcile ) { final RootNode [ ] ast = new RootNode [ ] ; final IRubyScript unit = fManager . getWorkingCopy ( fEditor . getEditorInput ( ) ) ; try { if ( unit != null ) { Platform . run ( new ISafeRunnable ( ) { public void run ( ) { try { IProblemRequestorExtension extension = getProblemRequestorExtension ( ) ; if ( extension != null ) { extension . setProgressMonitor ( fProgressMonitor ) ; extension . setIsActive ( true ) ; } try { ast [ ] = unit . reconcile ( true , null , fProgressMonitor ) ; } catch ( OperationCanceledException ex ) { Assert . isTrue ( fProgressMonitor == null || fProgressMonitor . isCanceled ( ) ) ; ast [ ] = null ; } finally { if ( extension != null ) { extension . setProgressMonitor ( null ) ; extension . setIsActive ( false ) ; } } } catch ( RubyModelException ex ) { handleException ( ex ) ; } } public void handleException ( Throwable ex ) { IStatus status = new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . OK , "" , ex ) ; RubyPlugin . getDefault ( ) . getLog ( ) . log ( status ) ; } } ) ; } } finally { try { if ( fIsRubyReconcilingListener ) { IProgressMonitor pm = fProgressMonitor ; if ( pm == null ) pm = new NullProgressMonitor ( ) ; fRubyReconcilingListener . reconciled ( unit , ast [ ] , ! fNotify , pm ) ; } } finally { fNotify = true ; } } } public void reconcile ( IRegion partition ) { reconcile ( false ) ; } public void reconcile ( DirtyRegion dirtyRegion , IRegion subRegion ) { reconcile ( false ) ; } public void setDocument ( IDocument document ) { } public void setProgressMonitor ( IProgressMonitor monitor ) { fProgressMonitor = monitor ; } public void initialReconcile ( ) { reconcile ( true ) ; } public void notifyListeners ( boolean notify ) { fNotify = notify ; } public void aboutToBeReconciled ( ) { if ( fIsRubyReconcilingListener ) fRubyReconcilingListener . aboutToBeReconciled ( ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyMethodCompletionProposal extends LazyRubyCompletionProposal { protected final static char [ ] METHOD_TRIGGERS = new char [ ] { '' , '' , '' , '' , '' } ; protected final static char [ ] METHOD_WITH_ARGUMENTS_TRIGGERS = new char [ ] { '' , '' , '' } ; protected final static char [ ] METHOD_NAME_TRIGGERS = new char [ ] { '' } ; private boolean fHasParameters ; private boolean fHasParametersComputed = false ; private int fContextInformationPosition ; public RubyMethodCompletionProposal ( CompletionProposal proposal , RubyContentAssistInvocationContext context ) { super ( proposal , context ) ; } public void apply ( IDocument document , char trigger , int offset ) { if ( trigger == '' || trigger == '' ) trigger = '' ; super . apply ( document , trigger , offset ) ; if ( needsLinkedMode ( ) ) { setUpLinkedMode ( document , '' ) ; } } protected boolean needsLinkedMode ( ) { return hasArgumentList ( ) && hasParameters ( ) ; } public CharSequence getPrefixCompletionText ( IDocument document , int completionOffset ) { if ( hasArgumentList ( ) ) { String completion = String . valueOf ( fProposal . getName ( ) ) ; return completion ; } return super . getPrefixCompletionText ( document , completionOffset ) ; } protected IContextInformation computeContextInformation ( ) { if ( fProposal . getKind ( ) == CompletionProposal . METHOD_REF && hasParameters ( ) && ( getReplacementString ( ) . endsWith ( RPAREN ) || getReplacementString ( ) . length ( ) == ) ) { ProposalContextInformation contextInformation = new ProposalContextInformation ( fProposal ) ; if ( fContextInformationPosition != && fProposal . getCompletion ( ) . length ( ) == ) contextInformation . setContextInformationPosition ( fContextInformationPosition ) ; return contextInformation ; } return super . computeContextInformation ( ) ; } protected char [ ] computeTriggerCharacters ( ) { if ( fProposal . getKind ( ) == CompletionProposal . METHOD_NAME_REFERENCE ) return METHOD_NAME_TRIGGERS ; if ( hasParameters ( ) ) return METHOD_WITH_ARGUMENTS_TRIGGERS ; return METHOD_TRIGGERS ; } protected final boolean hasParameters ( ) { if ( ! fHasParametersComputed ) { fHasParametersComputed = true ; fHasParameters = computeHasParameters ( ) ; } return fHasParameters ; } private boolean computeHasParameters ( ) throws IllegalArgumentException { return fProposal . getParameterNames ( ) != null && fProposal . getParameterNames ( ) . length > ; } protected boolean hasArgumentList ( ) { if ( CompletionProposal . METHOD_NAME_REFERENCE == fProposal . getKind ( ) ) return false ; IPreferenceStore preferenceStore = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; boolean noOverwrite = preferenceStore . getBoolean ( PreferenceConstants . CODEASSIST_INSERT_COMPLETION ) ^ isToggleEating ( ) ; String completion = fProposal . getCompletion ( ) ; return ! isInRubydoc ( ) && completion . length ( ) > && ( noOverwrite || completion . charAt ( completion . length ( ) - ) == '' ) ; } protected String computeReplacementString ( ) { if ( ! hasArgumentList ( ) ) return super . computeReplacementString ( ) ; StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( fProposal . getName ( ) ) ; buffer . append ( LPAREN ) ; if ( hasParameters ( ) ) { setCursorPosition ( buffer . length ( ) ) ; } else { } buffer . append ( RPAREN ) ; return buffer . toString ( ) ; } protected ProposalInfo computeProposalInfo ( ) { IRubyProject project = fInvocationContext . getProject ( ) ; if ( project != null ) return new ProposalInfo ( ( IMember ) fProposal . getElement ( ) ) ; return super . computeProposalInfo ( ) ; } public void setContextInformationPosition ( int contextInformationPosition ) { fContextInformationPosition = contextInformationPosition ; } protected String computeSortString ( ) { String name = fProposal . getName ( ) ; String parameterList = toCharArray ( fProposal . getParameterNames ( ) , '' ) ; int parameterCount = fProposal . getParameterNames ( ) . length % ; StringBuffer buf = new StringBuffer ( name . length ( ) + + parameterList . length ( ) ) ; buf . append ( name ) ; buf . append ( '' ) ; buf . append ( parameterCount ) ; buf . append ( parameterList ) ; return buf . toString ( ) ; } private String toCharArray ( String [ ] parameterNames , char c ) { if ( parameterNames == null ) return "" ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < parameterNames . length ; i ++ ) { if ( i > ) buffer . append ( c ) ; buffer . append ( parameterNames [ i ] ) ; } return buffer . toString ( ) ; } protected boolean isValidPrefix ( String prefix ) { if ( super . isValidPrefix ( prefix ) ) return true ; String word = getDisplayString ( ) ; return isPrefix ( prefix , word ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . lang . reflect . Field ; public class RubyTokenCategories { protected RubyTokenCategories ( ) { } public static final int UNKNOWN = - ; public static final int ERROR = ; public static final int WHITESPACE = ; public static final int IDENTIFIER = ; public static final int KEYWORD = ; public static final int PUNCTUATOR = ; public static final int LITERAL = ; public static final int COMMENT = ; public static final int MAX_VALUE = COMMENT ; public static String [ ] getNames ( ) { String [ ] result = new String [ MAX_VALUE + ] ; for ( int i = ; i <= MAX_VALUE ; i ++ ) { result [ i ] = getName ( i ) ; } return result ; } public static String getName ( int category ) { switch ( category ) { case ERROR : return "" ; case IDENTIFIER : return "" ; case WHITESPACE : return "" ; case KEYWORD : return "" ; case PUNCTUATOR : return "" ; case LITERAL : return "" ; case COMMENT : return "" ; default : return "" ; } } public static int getIntValue ( String name ) { Class c = RubyTokenCategories . class ; int result = - ; try { Field f = c . getField ( name ) ; result = f . getInt ( c ) ; } catch ( SecurityException e ) { } catch ( NoSuchFieldException e ) { } catch ( IllegalArgumentException e ) { } catch ( IllegalAccessException e ) { } return result ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . jface . text . link . LinkedModeUI ; import org . eclipse . jface . text . link . LinkedPosition ; import org . eclipse . jface . text . link . LinkedPositionGroup ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . texteditor . link . EditorLinkedModeUI ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorHighlightingSynchronizer ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . text . ruby . AbstractRubyCompletionProposal . ExitPolicy ; public final class FillMethodArgumentsProposal extends RubyMethodCompletionProposal { private IRegion fSelectedRegion ; private int [ ] fArgumentOffsets ; private int [ ] fArgumentLengths ; public FillMethodArgumentsProposal ( CompletionProposal proposal , RubyContentAssistInvocationContext context ) { super ( proposal , context ) ; } public void apply ( IDocument document , char trigger , int offset ) { super . apply ( document , trigger , offset ) ; int baseOffset = getReplacementOffset ( ) ; String replacement = getReplacementString ( ) ; if ( fArgumentOffsets != null && getTextViewer ( ) != null ) { try { LinkedModeModel model = new LinkedModeModel ( ) ; for ( int i = ; i != fArgumentOffsets . length ; i ++ ) { LinkedPositionGroup group = new LinkedPositionGroup ( ) ; group . addPosition ( new LinkedPosition ( document , baseOffset + fArgumentOffsets [ i ] , fArgumentLengths [ i ] , LinkedPositionGroup . NO_STOP ) ) ; model . addGroup ( group ) ; } model . forceInstall ( ) ; RubyEditor editor = getRubyEditor ( ) ; if ( editor != null ) { model . addLinkingListener ( new EditorHighlightingSynchronizer ( editor ) ) ; } LinkedModeUI ui = new EditorLinkedModeUI ( model , getTextViewer ( ) ) ; ui . setExitPosition ( getTextViewer ( ) , baseOffset + replacement . length ( ) , , Integer . MAX_VALUE ) ; ui . setExitPolicy ( new ExitPolicy ( '' , document ) ) ; ui . setDoContextInfo ( true ) ; ui . setCyclingMode ( LinkedModeUI . CYCLE_WHEN_NO_PARENT ) ; ui . enter ( ) ; fSelectedRegion = ui . getSelectedRegion ( ) ; } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; openErrorDialog ( e ) ; } } else { fSelectedRegion = new Region ( baseOffset + replacement . length ( ) , ) ; } } protected boolean needsLinkedMode ( ) { return false ; } protected String computeReplacementString ( ) { if ( ! hasParameters ( ) || ! hasArgumentList ( ) ) return super . computeReplacementString ( ) ; String [ ] parameterNames = fProposal . getParameterNames ( ) ; int count = parameterNames . length ; fArgumentOffsets = new int [ count ] ; fArgumentLengths = new int [ count ] ; StringBuffer buffer = new StringBuffer ( String . valueOf ( fProposal . getName ( ) ) ) ; buffer . append ( LPAREN ) ; setCursorPosition ( buffer . length ( ) ) ; for ( int i = ; i != count ; i ++ ) { if ( i != ) { buffer . append ( COMMA ) ; } fArgumentOffsets [ i ] = buffer . length ( ) ; buffer . append ( parameterNames [ i ] ) ; fArgumentLengths [ i ] = parameterNames [ i ] . length ( ) ; } buffer . append ( RPAREN ) ; return buffer . toString ( ) ; } private RubyEditor getRubyEditor ( ) { IEditorPart part = RubyPlugin . getActivePage ( ) . getActiveEditor ( ) ; if ( part instanceof RubyEditor ) return ( RubyEditor ) part ; else return null ; } public Point getSelection ( IDocument document ) { if ( fSelectedRegion == null ) return new Point ( getReplacementOffset ( ) , ) ; return new Point ( fSelectedRegion . getOffset ( ) , fSelectedRegion . getLength ( ) ) ; } private void openErrorDialog ( BadLocationException e ) { Shell shell = getTextViewer ( ) . getTextWidget ( ) . getShell ( ) ; MessageDialog . openError ( shell , RubyTextMessages . ExperimentalProposal_error_msg , e . getMessage ( ) ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . rules . ICharacterScanner ; import org . eclipse . jface . text . rules . IRule ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . IWordDetector ; import org . eclipse . jface . text . rules . Token ; public class CombinedWordRule implements IRule { public static class WordMatcher { private Map fWords = new HashMap ( ) ; public void addWord ( String word , IToken token ) { Assert . isNotNull ( word ) ; Assert . isNotNull ( token ) ; fWords . put ( new CharacterBuffer ( word ) , token ) ; } public IToken evaluate ( ICharacterScanner scanner , CharacterBuffer word ) { IToken token = ( IToken ) fWords . get ( word ) ; if ( token != null ) return token ; return Token . UNDEFINED ; } public void clearWords ( ) { fWords . clear ( ) ; } } public static class CharacterBuffer { private char [ ] fContent ; private int fLength = ; private boolean fIsHashCached = false ; private int fHashCode ; public CharacterBuffer ( int capacity ) { fContent = new char [ capacity ] ; } public CharacterBuffer ( String content ) { fContent = content . toCharArray ( ) ; fLength = content . length ( ) ; } public void clear ( ) { fIsHashCached = false ; fLength = ; } public void append ( char c ) { fIsHashCached = false ; if ( fLength == fContent . length ) { char [ ] old = fContent ; fContent = new char [ old . length << ] ; System . arraycopy ( old , , fContent , , old . length ) ; } fContent [ fLength ++ ] = c ; } public int length ( ) { return fLength ; } public String toString ( ) { return new String ( fContent , , fLength ) ; } public char charAt ( int i ) { return fContent [ i ] ; } public int hashCode ( ) { if ( fIsHashCached ) return fHashCode ; int hash = ; for ( int i = , n = fLength ; i < n ; i ++ ) hash = * hash + fContent [ i ] ; fHashCode = hash ; fIsHashCached = true ; return hash ; } public boolean equals ( Object obj ) { if ( obj == this ) return true ; if ( ! ( obj instanceof CharacterBuffer ) ) return false ; CharacterBuffer buffer = ( CharacterBuffer ) obj ; int length = buffer . length ( ) ; if ( length != fLength ) return false ; for ( int i = ; i < length ; i ++ ) if ( buffer . charAt ( i ) != fContent [ i ] ) return false ; return true ; } public boolean equals ( String string ) { int length = string . length ( ) ; if ( length != fLength ) return false ; for ( int i = ; i < length ; i ++ ) if ( string . charAt ( i ) != fContent [ i ] ) return false ; return true ; } } private static final int UNDEFINED = - ; private IWordDetector fDetector ; private IToken fDefaultToken ; private int fColumn = UNDEFINED ; private CharacterBuffer fBuffer = new CharacterBuffer ( ) ; private List fMatchers = new ArrayList ( ) ; public CombinedWordRule ( IWordDetector detector ) { this ( detector , null , Token . UNDEFINED ) ; } public CombinedWordRule ( IWordDetector detector , IToken defaultToken ) { this ( detector , null , defaultToken ) ; } public CombinedWordRule ( IWordDetector detector , WordMatcher matcher ) { this ( detector , matcher , Token . UNDEFINED ) ; } public CombinedWordRule ( IWordDetector detector , WordMatcher matcher , IToken defaultToken ) { Assert . isNotNull ( detector ) ; Assert . isNotNull ( defaultToken ) ; fDetector = detector ; fDefaultToken = defaultToken ; if ( matcher != null ) addWordMatcher ( matcher ) ; } public void addWordMatcher ( WordMatcher matcher ) { fMatchers . add ( matcher ) ; } public void setColumnConstraint ( int column ) { if ( column < ) column = UNDEFINED ; fColumn = column ; } public IToken evaluate ( ICharacterScanner scanner ) { int c = scanner . read ( ) ; if ( fDetector . isWordStart ( ( char ) c ) ) { if ( fColumn == UNDEFINED || ( fColumn == scanner . getColumn ( ) - ) ) { fBuffer . clear ( ) ; do { fBuffer . append ( ( char ) c ) ; c = scanner . read ( ) ; } while ( c != ICharacterScanner . EOF && fDetector . isWordPart ( ( char ) c ) ) ; scanner . unread ( ) ; for ( int i = , n = fMatchers . size ( ) ; i < n ; i ++ ) { IToken token = ( ( WordMatcher ) fMatchers . get ( i ) ) . evaluate ( scanner , fBuffer ) ; if ( ! token . isUndefined ( ) ) return token ; } if ( fDefaultToken . isUndefined ( ) ) unreadBuffer ( scanner ) ; return fDefaultToken ; } } scanner . unread ( ) ; return Token . UNDEFINED ; } private void unreadBuffer ( ICharacterScanner scanner ) { for ( int i = fBuffer . length ( ) - ; i >= ; i -- ) scanner . unread ( ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . io . IOException ; import java . io . StringReader ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . ITokenScanner ; import org . eclipse . jface . text . rules . Token ; import org . jruby . CompatVersion ; import org . jruby . common . NullWarnings ; import org . jruby . lexer . yacc . LexerSource ; import org . jruby . lexer . yacc . RubyYaccLexer ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . lexer . yacc . RubyYaccLexer . LexState ; import org . jruby . parser . ParserConfiguration ; import org . jruby . parser . ParserSupport ; import org . jruby . parser . RubyParserResult ; import org . jruby . parser . Tokens ; import org . jruby . util . KCode ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyTokenScanner implements ITokenScanner { private static final int COMMA = ; private static final int COLON = ; private static final int NEWLINE = ; public static final int CHARACTER = ; static final int MIN_KEYWORD = ; static final int MAX_KEYWORD = ; private RubyYaccLexer lexer ; private LexerSource lexerSource ; private ParserSupport parserSupport ; private int fTokenLength ; private int fOffset ; private boolean isInSymbol ; private boolean inAlias ; private RubyParserResult result ; private int origOffset ; private int origLength ; private String fContents ; public RubyTokenScanner ( ) { lexer = new RubyYaccLexer ( ) ; parserSupport = new ParserSupport ( ) ; ParserConfiguration config = new ParserConfiguration ( KCode . NIL , , true , false , CompatVersion . RUBY1_8 ) ; parserSupport . setConfiguration ( config ) ; result = new RubyParserResult ( ) ; parserSupport . setResult ( result ) ; lexer . setParserSupport ( parserSupport ) ; lexer . setWarnings ( new NullWarnings ( ) ) ; lexer . setEncoding ( config . getKCode ( ) . getEncoding ( ) ) ; } public int getTokenLength ( ) { return fTokenLength ; } public int getTokenOffset ( ) { return fOffset ; } public IToken nextToken ( ) { fOffset = getOffset ( ) ; fTokenLength = ; IToken returnValue = new Token ( Tokens . tIDENTIFIER ) ; boolean isEOF = false ; try { isEOF = ! lexer . advance ( ) ; if ( isEOF ) { returnValue = Token . EOF ; } else { fTokenLength = getOffset ( ) - fOffset ; returnValue = token ( lexer . token ( ) ) ; } } catch ( SyntaxException se ) { if ( lexerSource . getOffset ( ) - origLength == ) return Token . EOF ; fTokenLength = getOffset ( ) - fOffset ; return token ( Tokens . yyErrorCode ) ; } catch ( NumberFormatException nfe ) { fTokenLength = getOffset ( ) - fOffset ; return returnValue ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } return returnValue ; } private int getOffset ( ) { return lexerSource . getOffset ( ) + origOffset ; } private IToken token ( int i ) { if ( isInSymbol ) { if ( isSymbolTerminator ( i ) ) { isInSymbol = false ; if ( shouldReturnDefault ( i ) ) return new Token ( new Integer ( i ) ) ; } return new Token ( new Integer ( Tokens . tSYMBEG ) ) ; } if ( i == Tokens . kALIAS ) { inAlias = true ; } if ( i == COLON && inAlias ) { isInSymbol = true ; inAlias = false ; return new Token ( new Integer ( Tokens . tSYMBEG ) ) ; } if ( isKeyword ( i ) ) return new Token ( new Integer ( Tokens . k__FILE__ ) ) ; switch ( i ) { case Tokens . tSYMBEG : if ( looksLikeTertiaryConditionalWithNoSpaces ( ) ) { return new Token ( new Integer ( Tokens . tCOLON2 ) ) ; } isInSymbol = true ; return new Token ( new Integer ( Tokens . tSYMBEG ) ) ; case Tokens . tGVAR : case Tokens . tBACK_REF : return new Token ( new Integer ( Tokens . tGVAR ) ) ; case Tokens . tFLOAT : case Tokens . tINTEGER : if ( ( ( ( fOffset - origOffset ) + ) < fContents . length ( ) ) && ( fContents . charAt ( ( fOffset - origOffset ) + ) == '' ) ) return new Token ( new Integer ( CHARACTER ) ) ; return new Token ( new Integer ( i ) ) ; default : return new Token ( new Integer ( i ) ) ; } } private boolean looksLikeTertiaryConditionalWithNoSpaces ( ) { if ( fTokenLength > ) return false ; int index = ( fOffset - origOffset ) - ; if ( index < ) return false ; try { char c = fContents . charAt ( index ) ; return ! Character . isWhitespace ( c ) && Character . isUnicodeIdentifierPart ( c ) ; } catch ( RuntimeException e ) { return false ; } } private boolean shouldReturnDefault ( int i ) { switch ( i ) { case NEWLINE : case COMMA : case Tokens . tASSOC : case Tokens . tRPAREN : return true ; default : return false ; } } private boolean isSymbolTerminator ( int i ) { if ( isRealKeyword ( i ) ) return true ; switch ( i ) { case Tokens . tAREF : case Tokens . tCVAR : case Tokens . tMINUS : case Tokens . tPLUS : case Tokens . tPIPE : case Tokens . tCARET : case Tokens . tLT : case Tokens . tGT : case Tokens . tAMPER : case Tokens . tSTAR2 : case Tokens . tDIVIDE : case Tokens . tPERCENT : case Tokens . tBACK_REF2 : case Tokens . tTILDE : case Tokens . tCONSTANT : case Tokens . tFID : case Tokens . tASET : case Tokens . tIDENTIFIER : case Tokens . tIVAR : case Tokens . tGVAR : case Tokens . tASSOC : case Tokens . tLSHFT : case Tokens . tRPAREN : case COMMA : case NEWLINE : return true ; default : return false ; } } private boolean isRealKeyword ( int i ) { if ( i >= MIN_KEYWORD && i <= MAX_KEYWORD ) return true ; return false ; } private boolean isKeyword ( int i ) { if ( i != Tokens . tIDENTIFIER ) return false ; String src ; try { src = fContents . substring ( ( fOffset - origOffset ) , ( fOffset - origOffset ) + fTokenLength ) ; } catch ( RuntimeException e ) { RubyPlugin . log ( e ) ; return false ; } if ( src == null || src . trim ( ) . length ( ) == ) return false ; Preferences prefs = RubyPlugin . getDefault ( ) . getPluginPreferences ( ) ; if ( prefs == null ) return false ; String rawKeywords = prefs . getString ( PreferenceConstants . EDITOR_USER_KEYWORDS ) ; if ( rawKeywords == null || rawKeywords . length ( ) == ) { return false ; } String [ ] keywords = rawKeywords . split ( "" ) ; if ( keywords == null || keywords . length == ) { return false ; } for ( int j = ; j < keywords . length ; j ++ ) { if ( keywords [ j ] == null ) continue ; if ( keywords [ j ] . equals ( src . trim ( ) ) ) return true ; } return false ; } public void setRange ( IDocument document , int offset , int length ) { lexer . reset ( ) ; lexer . setState ( LexState . EXPR_BEG ) ; parserSupport . initTopLocalVariables ( ) ; isInSymbol = false ; ParserConfiguration config = new ParserConfiguration ( KCode . NIL , , true , false , CompatVersion . RUBY1_8 ) ; try { fContents = document . get ( offset , length ) ; lexerSource = LexerSource . getSource ( "" , new StringReader ( fContents ) , null , config ) ; lexer . setSource ( lexerSource ) ; } catch ( BadLocationException e ) { lexerSource = LexerSource . getSource ( "" , new StringReader ( "" ) , null , config ) ; lexer . setSource ( lexerSource ) ; } origOffset = offset ; origLength = length ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . RDocUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . infoviews . RiUtility ; public class ProposalInfo { private boolean fRubydocResolved = false ; private String fRubydoc = null ; protected IRubyElement fElement ; public ProposalInfo ( IMember member ) { fElement = member ; } protected ProposalInfo ( ) { fElement = null ; } public IRubyElement getRubyElement ( ) throws RubyModelException { return fElement ; } public final String getInfo ( IProgressMonitor monitor ) { if ( ! fRubydocResolved ) { fRubydocResolved = true ; fRubydoc = computeInfo ( monitor ) ; } return fRubydoc ; } private String computeInfo ( IProgressMonitor monitor ) { try { final IRubyElement rubyElement = getRubyElement ( ) ; if ( rubyElement instanceof IMember ) { IMember member = ( IMember ) rubyElement ; String inSource = extractRubydoc ( member , monitor ) ; if ( inSource != null && inSource . trim ( ) . length ( ) > ) return inSource ; IType type = member . getDeclaringType ( ) ; if ( type == null ) return null ; List < String > args = new ArrayList < String > ( ) ; String divider = "" ; if ( member instanceof IMethod ) { IMethod method = ( IMethod ) member ; if ( method . isSingleton ( ) ) divider = "" ; } args . add ( type . getFullyQualifiedName ( ) + divider + member . getElementName ( ) ) ; String riResult = RiUtility . getRIHTMLContents ( args ) ; if ( riResult . trim ( ) . equals ( "" ) ) return null ; riResult = riResult . replace ( "" , "" ) ; riResult = riResult . replace ( "" , "" ) ; return riResult ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } return null ; } private String extractRubydoc ( IMember member , IProgressMonitor monitor ) throws RubyModelException , IOException { if ( member != null && member . getRubyScript ( ) != null ) { return RDocUtil . getHTMLDocumentation ( member ) ; } return null ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . resource . StringConverter ; import org . eclipse . jface . text . TextAttribute ; import org . eclipse . jface . text . rules . ITokenScanner ; import org . eclipse . jface . text . rules . Token ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . IAbstractManagedScanner ; import org . rubypeople . rdt . ui . text . IColorManager ; import org . rubypeople . rdt . ui . text . IColorManagerExtension ; public abstract class AbstractRubyTokenScanner implements ITokenScanner , IAbstractManagedScanner { private String [ ] fPropertyNamesColor ; private String [ ] fPropertyNamesBgColor ; private String [ ] fPropertyNamesBold ; private String [ ] fPropertyNamesBGEnabled ; private String [ ] fPropertyNamesItalic ; private String [ ] fPropertyNamesStrikethrough ; private String [ ] fPropertyNamesUnderline ; private IColorManager fColorManager ; private IPreferenceStore fPreferenceStore ; private boolean fNeedsLazyColorLoading ; private Map fTokenMap = new HashMap ( ) ; public AbstractRubyTokenScanner ( IColorManager manager , IPreferenceStore store ) { super ( ) ; fColorManager = manager ; fPreferenceStore = store ; } protected IPreferenceStore getPreferenceStore ( ) { return fPreferenceStore ; } abstract protected String [ ] getTokenProperties ( ) ; public final void initialize ( ) { fPropertyNamesColor = getTokenProperties ( ) ; int length = fPropertyNamesColor . length ; fPropertyNamesBgColor = new String [ length ] ; fPropertyNamesBGEnabled = new String [ length ] ; fPropertyNamesBold = new String [ length ] ; fPropertyNamesItalic = new String [ length ] ; fPropertyNamesStrikethrough = new String [ length ] ; fPropertyNamesUnderline = new String [ length ] ; for ( int i = ; i < length ; i ++ ) { fPropertyNamesBgColor [ i ] = getBGKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesBold [ i ] = getBoldKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesBGEnabled [ i ] = getBGEnabledKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesItalic [ i ] = getItalicKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesStrikethrough [ i ] = getStrikethroughKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesUnderline [ i ] = getUnderlineKey ( fPropertyNamesColor [ i ] ) ; } fNeedsLazyColorLoading = Display . getCurrent ( ) == null ; for ( int i = ; i < length ; i ++ ) { if ( fNeedsLazyColorLoading ) addTokenWithProxyAttribute ( fPropertyNamesColor [ i ] , fPropertyNamesBgColor [ i ] , fPropertyNamesBGEnabled [ i ] , fPropertyNamesBold [ i ] , fPropertyNamesItalic [ i ] , fPropertyNamesStrikethrough [ i ] , fPropertyNamesUnderline [ i ] ) ; else addToken ( fPropertyNamesColor [ i ] , fPropertyNamesBgColor [ i ] , fPropertyNamesBGEnabled [ i ] , fPropertyNamesBold [ i ] , fPropertyNamesItalic [ i ] , fPropertyNamesStrikethrough [ i ] , fPropertyNamesUnderline [ i ] ) ; } } protected String getBoldKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_BOLD_SUFFIX ; } protected String getBGKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_BG_SUFFIX ; } protected String getBGEnabledKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_BG_ENABLED_SUFFIX ; } protected String getItalicKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_ITALIC_SUFFIX ; } protected String getStrikethroughKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_STRIKETHROUGH_SUFFIX ; } protected String getUnderlineKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_UNDERLINE_SUFFIX ; } private void addTokenWithProxyAttribute ( String colorKey , String bgColorKey , String bgEnabledKey , String boldKey , String italicKey , String strikethroughKey , String underlineKey ) { fTokenMap . put ( colorKey , new Token ( createTextAttribute ( null , null , bgEnabledKey , boldKey , italicKey , strikethroughKey , underlineKey ) ) ) ; } private void resolveProxyAttributes ( ) { if ( fNeedsLazyColorLoading && Display . getCurrent ( ) != null ) { for ( int i = ; i < fPropertyNamesColor . length ; i ++ ) { addToken ( fPropertyNamesColor [ i ] , fPropertyNamesBgColor [ i ] , fPropertyNamesBGEnabled [ i ] , fPropertyNamesBold [ i ] , fPropertyNamesItalic [ i ] , fPropertyNamesStrikethrough [ i ] , fPropertyNamesUnderline [ i ] ) ; } fNeedsLazyColorLoading = false ; } } private void addToken ( String colorKey , String bgColorKey , String bgEnabledKey , String boldKey , String italicKey , String strikethroughKey , String underlineKey ) { bindColor ( colorKey ) ; bindColor ( bgColorKey ) ; if ( ! fNeedsLazyColorLoading ) fTokenMap . put ( colorKey , new Token ( createTextAttribute ( colorKey , bgColorKey , bgEnabledKey , boldKey , italicKey , strikethroughKey , underlineKey ) ) ) ; else { Token token = ( ( Token ) fTokenMap . get ( colorKey ) ) ; if ( token != null ) token . setData ( createTextAttribute ( colorKey , bgColorKey , bgEnabledKey , boldKey , italicKey , strikethroughKey , underlineKey ) ) ; } } private void bindColor ( String colorKey ) { if ( fColorManager != null && colorKey != null && fColorManager . getColor ( colorKey ) == null ) { RGB rgb = PreferenceConverter . getColor ( fPreferenceStore , colorKey ) ; if ( rgb == PreferenceConverter . COLOR_DEFAULT_DEFAULT && ! colorKey . endsWith ( PreferenceConstants . EDITOR_BG_SUFFIX ) ) return ; if ( fColorManager instanceof IColorManagerExtension ) { IColorManagerExtension ext = ( IColorManagerExtension ) fColorManager ; ext . unbindColor ( colorKey ) ; ext . bindColor ( colorKey , rgb ) ; } } } public Token getToken ( String key ) { if ( fNeedsLazyColorLoading ) resolveProxyAttributes ( ) ; return ( Token ) fTokenMap . get ( key ) ; } private TextAttribute createTextAttribute ( String colorKey , String bgColorKey , String bgEnabledKey , String boldKey , String italicKey , String strikethroughKey , String underlineKey ) { Color color = null ; if ( colorKey != null ) color = fColorManager . getColor ( colorKey ) ; boolean useBG = fPreferenceStore . getBoolean ( bgEnabledKey ) ; Color bgColor = null ; if ( bgColorKey != null && useBG ) bgColor = fColorManager . getColor ( bgColorKey ) ; int style = fPreferenceStore . getBoolean ( boldKey ) ? SWT . BOLD : SWT . NORMAL ; if ( fPreferenceStore . getBoolean ( italicKey ) ) style |= SWT . ITALIC ; if ( fPreferenceStore . getBoolean ( strikethroughKey ) ) style |= TextAttribute . STRIKETHROUGH ; if ( fPreferenceStore . getBoolean ( underlineKey ) ) style |= TextAttribute . UNDERLINE ; return new TextAttribute ( color , bgColor , style ) ; } public boolean affectsBehavior ( PropertyChangeEvent event ) { return indexOf ( event . getProperty ( ) ) >= ; } public void adaptToPreferenceChange ( PropertyChangeEvent event ) { String p = event . getProperty ( ) ; int index = indexOf ( p ) ; Token token = getToken ( fPropertyNamesColor [ index ] ) ; if ( fPropertyNamesColor [ index ] . equals ( p ) ) adaptToColorChange ( token , event ) ; if ( fPropertyNamesBgColor [ index ] . equals ( p ) || fPropertyNamesBGEnabled [ index ] . equals ( p ) ) adaptToBgColorChange ( token , event ) ; else if ( fPropertyNamesBold [ index ] . equals ( p ) ) adaptToStyleChange ( token , event , SWT . BOLD ) ; else if ( fPropertyNamesItalic [ index ] . equals ( p ) ) adaptToStyleChange ( token , event , SWT . ITALIC ) ; else if ( fPropertyNamesStrikethrough [ index ] . equals ( p ) ) adaptToStyleChange ( token , event , TextAttribute . STRIKETHROUGH ) ; else if ( fPropertyNamesUnderline [ index ] . equals ( p ) ) adaptToStyleChange ( token , event , TextAttribute . UNDERLINE ) ; } private void adaptToStyleChange ( Token token , PropertyChangeEvent event , int styleAttribute ) { boolean eventValue = false ; Object value = event . getNewValue ( ) ; if ( value instanceof Boolean ) eventValue = ( ( Boolean ) value ) . booleanValue ( ) ; else if ( IPreferenceStore . TRUE . equals ( value ) ) eventValue = true ; Object data = token . getData ( ) ; if ( data instanceof TextAttribute ) { TextAttribute oldAttr = ( TextAttribute ) data ; boolean activeValue = ( oldAttr . getStyle ( ) & styleAttribute ) == styleAttribute ; if ( activeValue != eventValue ) token . setData ( new TextAttribute ( oldAttr . getForeground ( ) , oldAttr . getBackground ( ) , eventValue ? oldAttr . getStyle ( ) | styleAttribute : oldAttr . getStyle ( ) & ~ styleAttribute ) ) ; } } private void adaptToColorChange ( Token token , PropertyChangeEvent event ) { adaptToSomeColorChange ( token , event , true ) ; } private void adaptToBgColorChange ( Token token , PropertyChangeEvent event ) { adaptToSomeColorChange ( token , event , false ) ; } private void adaptToSomeColorChange ( Token token , PropertyChangeEvent event , boolean isForeground ) { if ( event . getProperty ( ) . endsWith ( PreferenceConstants . EDITOR_BG_ENABLED_SUFFIX ) ) { Object value = event . getNewValue ( ) ; boolean enabling = false ; if ( value instanceof Boolean ) { enabling = ( ( Boolean ) value ) . booleanValue ( ) ; } else if ( value instanceof String ) { enabling = Boolean . parseBoolean ( ( String ) value ) ; } Object data = token . getData ( ) ; if ( data instanceof TextAttribute ) { TextAttribute oldAttr = ( TextAttribute ) data ; Color foreGround = oldAttr . getForeground ( ) ; if ( enabling ) { String property = getBGKey ( event . getProperty ( ) . substring ( , event . getProperty ( ) . length ( ) - PreferenceConstants . EDITOR_BG_ENABLED_SUFFIX . length ( ) ) ) ; RGB rgb = PreferenceConverter . getColor ( getPreferenceStore ( ) , property ) ; Color color = fColorManager . getColor ( property ) ; if ( ( color == null || ! rgb . equals ( color . getRGB ( ) ) ) && fColorManager instanceof IColorManagerExtension ) { IColorManagerExtension ext = ( IColorManagerExtension ) fColorManager ; ext . unbindColor ( property ) ; ext . bindColor ( property , rgb ) ; color = fColorManager . getColor ( property ) ; } token . setData ( new TextAttribute ( foreGround , color , oldAttr . getStyle ( ) ) ) ; } else { token . setData ( new TextAttribute ( foreGround , null , oldAttr . getStyle ( ) ) ) ; } return ; } } RGB rgb = null ; Object value = event . getNewValue ( ) ; if ( value instanceof RGB ) rgb = ( RGB ) value ; else if ( value instanceof String ) rgb = StringConverter . asRGB ( ( String ) value ) ; if ( rgb != null ) { String property = event . getProperty ( ) ; Color color = fColorManager . getColor ( property ) ; if ( ( color == null || ! rgb . equals ( color . getRGB ( ) ) ) && fColorManager instanceof IColorManagerExtension ) { IColorManagerExtension ext = ( IColorManagerExtension ) fColorManager ; ext . unbindColor ( property ) ; ext . bindColor ( property , rgb ) ; color = fColorManager . getColor ( property ) ; } Object data = token . getData ( ) ; if ( data instanceof TextAttribute ) { TextAttribute oldAttr = ( TextAttribute ) data ; Color foreGround ; Color backGround ; if ( ! isForeground ) { foreGround = oldAttr . getForeground ( ) ; backGround = color ; } else { foreGround = color ; backGround = oldAttr . getBackground ( ) ; } token . setData ( new TextAttribute ( foreGround , backGround , oldAttr . getStyle ( ) ) ) ; } } } private int indexOf ( String property ) { if ( property != null ) { int length = fPropertyNamesColor . length ; for ( int i = ; i < length ; i ++ ) { if ( property . equals ( fPropertyNamesColor [ i ] ) || property . equals ( fPropertyNamesBgColor [ i ] ) || property . equals ( fPropertyNamesBGEnabled [ i ] ) || property . equals ( fPropertyNamesBold [ i ] ) || property . equals ( fPropertyNamesItalic [ i ] ) || property . equals ( fPropertyNamesStrikethrough [ i ] ) || property . equals ( fPropertyNamesUnderline [ i ] ) ) return i ; } } return - ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . IDocument ; import org . eclipse . swt . graphics . Image ; public class RubyCompletionProposal extends AbstractRubyCompletionProposal { public RubyCompletionProposal ( String replacementString , int replacementOffset , int replacementLength , Image image , String displayString , int relevance ) { this ( replacementString , replacementOffset , replacementLength , image , displayString , relevance , false ) ; } public RubyCompletionProposal ( String replacementString , int replacementOffset , int replacementLength , Image image , String displayString , int relevance , boolean inRubydoc ) { Assert . isNotNull ( replacementString ) ; Assert . isTrue ( replacementOffset >= ) ; Assert . isTrue ( replacementLength >= ) ; setReplacementString ( replacementString ) ; setReplacementOffset ( replacementOffset ) ; setReplacementLength ( replacementLength ) ; setImage ( image ) ; setDisplayString ( displayString == null ? replacementString : displayString ) ; setRelevance ( relevance ) ; setCursorPosition ( replacementString . length ( ) ) ; setInRubydoc ( inRubydoc ) ; setSortString ( displayString == null ? replacementString : displayString ) ; } protected boolean isValidPrefix ( String prefix ) { String word = getReplacementString ( ) ; return isPrefix ( prefix , word ) ; } public CharSequence getPrefixCompletionText ( IDocument document , int completionOffset ) { String string = getReplacementString ( ) ; int pos = string . indexOf ( '' ) ; if ( pos > ) return string . subSequence ( , pos ) ; else return string ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . Collection ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . commands . IParameterValues ; public final class ContentAssistComputerParameter implements IParameterValues { public Map getParameterValues ( ) { Collection descriptors = CompletionProposalComputerRegistry . getDefault ( ) . getProposalCategories ( ) ; Map map = new HashMap ( descriptors . size ( ) ) ; for ( Iterator it = descriptors . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalCategory category = ( CompletionProposalCategory ) it . next ( ) ; map . put ( category . getDisplayName ( ) , category . getId ( ) ) ; } return map ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . core . runtime . IProgressMonitor ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyScript ; public interface IRubyReconcilingListener { void aboutToBeReconciled ( ) ; void reconciled ( IRubyScript script , RootNode ast , boolean forced , IProgressMonitor progressMonitor ) ; } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . resource . StringConverter ; import org . eclipse . jface . text . TextAttribute ; import org . eclipse . jface . text . rules . BufferedRuleBasedScanner ; import org . eclipse . jface . text . rules . IRule ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . Token ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . IAbstractManagedScanner ; import org . rubypeople . rdt . ui . text . IColorManager ; import org . rubypeople . rdt . ui . text . IColorManagerExtension ; public abstract class AbstractRubyScanner extends BufferedRuleBasedScanner implements IAbstractManagedScanner { private String [ ] fPropertyNamesColor ; private String [ ] fPropertyNamesBgColor ; private String [ ] fPropertyNamesBgEnabled ; private String [ ] fPropertyNamesBold ; private String [ ] fPropertyNamesItalic ; private String [ ] fPropertyNamesStrikethrough ; private String [ ] fPropertyNamesUnderline ; private IColorManager fColorManager ; private IPreferenceStore fPreferenceStore ; private boolean fNeedsLazyColorLoading ; private Map fTokenMap = new HashMap ( ) ; public AbstractRubyScanner ( IColorManager manager , IPreferenceStore store ) { super ( ) ; fColorManager = manager ; fPreferenceStore = store ; } protected IPreferenceStore getPreferenceStore ( ) { return fPreferenceStore ; } private void initializeRules ( ) { List rules = createRules ( ) ; if ( rules != null ) { IRule [ ] result = new IRule [ rules . size ( ) ] ; rules . toArray ( result ) ; setRules ( result ) ; } } public IToken nextToken ( ) { if ( fNeedsLazyColorLoading ) resolveProxyAttributes ( ) ; return super . nextToken ( ) ; } abstract protected String [ ] getTokenProperties ( ) ; protected abstract List createRules ( ) ; public final void initialize ( ) { fPropertyNamesColor = getTokenProperties ( ) ; int length = fPropertyNamesColor . length ; fPropertyNamesBgEnabled = new String [ length ] ; fPropertyNamesBgColor = new String [ length ] ; fPropertyNamesBold = new String [ length ] ; fPropertyNamesItalic = new String [ length ] ; fPropertyNamesStrikethrough = new String [ length ] ; fPropertyNamesUnderline = new String [ length ] ; for ( int i = ; i < length ; i ++ ) { fPropertyNamesBgColor [ i ] = getBGKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesBgEnabled [ i ] = getBGEnabledKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesBold [ i ] = getBoldKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesItalic [ i ] = getItalicKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesStrikethrough [ i ] = getStrikethroughKey ( fPropertyNamesColor [ i ] ) ; fPropertyNamesUnderline [ i ] = getUnderlineKey ( fPropertyNamesColor [ i ] ) ; } fNeedsLazyColorLoading = Display . getCurrent ( ) == null ; for ( int i = ; i < length ; i ++ ) { if ( fNeedsLazyColorLoading ) addTokenWithProxyAttribute ( fPropertyNamesColor [ i ] , fPropertyNamesBgColor [ i ] , fPropertyNamesBgEnabled [ i ] , fPropertyNamesBold [ i ] , fPropertyNamesItalic [ i ] , fPropertyNamesStrikethrough [ i ] , fPropertyNamesUnderline [ i ] ) ; else addToken ( fPropertyNamesColor [ i ] , fPropertyNamesBgColor [ i ] , fPropertyNamesBold [ i ] , fPropertyNamesBgEnabled [ i ] , fPropertyNamesItalic [ i ] , fPropertyNamesStrikethrough [ i ] , fPropertyNamesUnderline [ i ] ) ; } initializeRules ( ) ; } protected String getBoldKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_BOLD_SUFFIX ; } protected String getBGEnabledKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_BG_ENABLED_SUFFIX ; } protected String getBGKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_BG_SUFFIX ; } protected String getItalicKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_ITALIC_SUFFIX ; } protected String getStrikethroughKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_STRIKETHROUGH_SUFFIX ; } protected String getUnderlineKey ( String colorKey ) { return colorKey + PreferenceConstants . EDITOR_UNDERLINE_SUFFIX ; } private void addTokenWithProxyAttribute ( String colorKey , String bgColorKey , String bgEnabledKey , String boldKey , String italicKey , String strikethroughKey , String underlineKey ) { fTokenMap . put ( colorKey , new Token ( createTextAttribute ( null , null , bgEnabledKey , boldKey , italicKey , strikethroughKey , underlineKey ) ) ) ; } private void resolveProxyAttributes ( ) { if ( fNeedsLazyColorLoading && Display . getCurrent ( ) != null ) { for ( int i = ; i < fPropertyNamesColor . length ; i ++ ) { addToken ( fPropertyNamesColor [ i ] , fPropertyNamesBgColor [ i ] , fPropertyNamesBgEnabled [ i ] , fPropertyNamesBold [ i ] , fPropertyNamesItalic [ i ] , fPropertyNamesStrikethrough [ i ] , fPropertyNamesUnderline [ i ] ) ; } fNeedsLazyColorLoading = false ; } } private void addToken ( String colorKey , String bgColorKey , String bgEnabledKey , String boldKey , String italicKey , String strikethroughKey , String underlineKey ) { bindColor ( colorKey ) ; bindColor ( bgColorKey ) ; if ( ! fNeedsLazyColorLoading ) fTokenMap . put ( colorKey , new Token ( createTextAttribute ( colorKey , bgColorKey , bgEnabledKey , boldKey , italicKey , strikethroughKey , underlineKey ) ) ) ; else { Token token = ( ( Token ) fTokenMap . get ( colorKey ) ) ; if ( token != null ) token . setData ( createTextAttribute ( colorKey , bgColorKey , bgEnabledKey , boldKey , italicKey , strikethroughKey , underlineKey ) ) ; } } private void bindColor ( String colorKey ) { if ( fColorManager != null && colorKey != null && fColorManager . getColor ( colorKey ) == null ) { RGB rgb = PreferenceConverter . getColor ( fPreferenceStore , colorKey ) ; if ( rgb == PreferenceConverter . COLOR_DEFAULT_DEFAULT && ! colorKey . endsWith ( PreferenceConstants . EDITOR_BG_SUFFIX ) ) return ; if ( fColorManager instanceof IColorManagerExtension ) { IColorManagerExtension ext = ( IColorManagerExtension ) fColorManager ; ext . unbindColor ( colorKey ) ; ext . bindColor ( colorKey , rgb ) ; } } } protected Token getToken ( String key ) { if ( fNeedsLazyColorLoading ) resolveProxyAttributes ( ) ; return ( Token ) fTokenMap . get ( key ) ; } private TextAttribute createTextAttribute ( String colorKey , String bgColorKey , String bgEnabledKey , String boldKey , String italicKey , String strikethroughKey , String underlineKey ) { Color color = null ; if ( colorKey != null ) color = fColorManager . getColor ( colorKey ) ; boolean useBG = fPreferenceStore . getBoolean ( boldKey ) ; Color bgColor = null ; if ( bgColorKey != null && useBG ) bgColor = fColorManager . getColor ( bgColorKey ) ; int style = fPreferenceStore . getBoolean ( boldKey ) ? SWT . BOLD : SWT . NORMAL ; if ( fPreferenceStore . getBoolean ( italicKey ) ) style |= SWT . ITALIC ; if ( fPreferenceStore . getBoolean ( strikethroughKey ) ) style |= TextAttribute . STRIKETHROUGH ; if ( fPreferenceStore . getBoolean ( underlineKey ) ) style |= TextAttribute . UNDERLINE ; return new TextAttribute ( color , bgColor , style ) ; } public boolean affectsBehavior ( PropertyChangeEvent event ) { return indexOf ( event . getProperty ( ) ) >= ; } public void adaptToPreferenceChange ( PropertyChangeEvent event ) { String p = event . getProperty ( ) ; int index = indexOf ( p ) ; Token token = getToken ( fPropertyNamesColor [ index ] ) ; if ( fPropertyNamesColor [ index ] . equals ( p ) ) adaptToColorChange ( token , event ) ; if ( fPropertyNamesBgColor [ index ] . equals ( p ) || fPropertyNamesBgEnabled [ index ] . equals ( p ) ) adaptToBgColorChange ( token , event ) ; else if ( fPropertyNamesBold [ index ] . equals ( p ) ) adaptToStyleChange ( token , event , SWT . BOLD ) ; else if ( fPropertyNamesItalic [ index ] . equals ( p ) ) adaptToStyleChange ( token , event , SWT . ITALIC ) ; else if ( fPropertyNamesStrikethrough [ index ] . equals ( p ) ) adaptToStyleChange ( token , event , TextAttribute . STRIKETHROUGH ) ; else if ( fPropertyNamesUnderline [ index ] . equals ( p ) ) adaptToStyleChange ( token , event , TextAttribute . UNDERLINE ) ; } private void adaptToStyleChange ( Token token , PropertyChangeEvent event , int styleAttribute ) { boolean eventValue = false ; Object value = event . getNewValue ( ) ; if ( value instanceof Boolean ) eventValue = ( ( Boolean ) value ) . booleanValue ( ) ; else if ( IPreferenceStore . TRUE . equals ( value ) ) eventValue = true ; Object data = token . getData ( ) ; if ( data instanceof TextAttribute ) { TextAttribute oldAttr = ( TextAttribute ) data ; boolean activeValue = ( oldAttr . getStyle ( ) & styleAttribute ) == styleAttribute ; if ( activeValue != eventValue ) token . setData ( new TextAttribute ( oldAttr . getForeground ( ) , oldAttr . getBackground ( ) , eventValue ? oldAttr . getStyle ( ) | styleAttribute : oldAttr . getStyle ( ) & ~ styleAttribute ) ) ; } } private void adaptToColorChange ( Token token , PropertyChangeEvent event ) { adaptToSomeColorChange ( token , event , true ) ; } private void adaptToBgColorChange ( Token token , PropertyChangeEvent event ) { adaptToSomeColorChange ( token , event , false ) ; } private void adaptToSomeColorChange ( Token token , PropertyChangeEvent event , boolean isForeground ) { if ( event . getProperty ( ) . endsWith ( PreferenceConstants . EDITOR_BG_ENABLED_SUFFIX ) ) { Object value = event . getNewValue ( ) ; boolean enabling = false ; if ( value instanceof Boolean ) { enabling = ( ( Boolean ) value ) . booleanValue ( ) ; } else if ( value instanceof String ) { enabling = Boolean . parseBoolean ( ( String ) value ) ; } Object data = token . getData ( ) ; if ( data instanceof TextAttribute ) { TextAttribute oldAttr = ( TextAttribute ) data ; Color foreGround = oldAttr . getForeground ( ) ; if ( enabling ) { String property = getBGKey ( event . getProperty ( ) . substring ( , event . getProperty ( ) . length ( ) - PreferenceConstants . EDITOR_BG_ENABLED_SUFFIX . length ( ) ) ) ; RGB rgb = PreferenceConverter . getColor ( getPreferenceStore ( ) , property ) ; Color color = fColorManager . getColor ( property ) ; if ( ( color == null || ! rgb . equals ( color . getRGB ( ) ) ) && fColorManager instanceof IColorManagerExtension ) { IColorManagerExtension ext = ( IColorManagerExtension ) fColorManager ; ext . unbindColor ( property ) ; ext . bindColor ( property , rgb ) ; color = fColorManager . getColor ( property ) ; } token . setData ( new TextAttribute ( foreGround , color , oldAttr . getStyle ( ) ) ) ; } else { token . setData ( new TextAttribute ( foreGround , null , oldAttr . getStyle ( ) ) ) ; } return ; } } RGB rgb = null ; Object value = event . getNewValue ( ) ; if ( value instanceof RGB ) rgb = ( RGB ) value ; else if ( value instanceof String ) rgb = StringConverter . asRGB ( ( String ) value ) ; if ( rgb != null ) { String property = event . getProperty ( ) ; Color color = fColorManager . getColor ( property ) ; if ( ( color == null || ! rgb . equals ( color . getRGB ( ) ) ) && fColorManager instanceof IColorManagerExtension ) { IColorManagerExtension ext = ( IColorManagerExtension ) fColorManager ; ext . unbindColor ( property ) ; ext . bindColor ( property , rgb ) ; color = fColorManager . getColor ( property ) ; } Object data = token . getData ( ) ; if ( data instanceof TextAttribute ) { TextAttribute oldAttr = ( TextAttribute ) data ; Color foreGround ; Color backGround ; if ( ! isForeground ) { foreGround = oldAttr . getForeground ( ) ; backGround = color ; } else { foreGround = color ; backGround = oldAttr . getBackground ( ) ; } token . setData ( new TextAttribute ( foreGround , backGround , oldAttr . getStyle ( ) ) ) ; } } } private int indexOf ( String property ) { if ( property != null ) { int length = fPropertyNamesColor . length ; for ( int i = ; i < length ; i ++ ) { if ( property . equals ( fPropertyNamesColor [ i ] ) || property . equals ( fPropertyNamesBgColor [ i ] ) || property . equals ( fPropertyNamesBgEnabled [ i ] ) || property . equals ( fPropertyNamesBold [ i ] ) || property . equals ( fPropertyNamesItalic [ i ] ) || property . equals ( fPropertyNamesStrikethrough [ i ] ) || property . equals ( fPropertyNamesUnderline [ i ] ) ) return i ; } } return - ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . ui . texteditor . HippieProposalProcessor ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposalComputer ; public final class HippieProposalComputer implements IRubyCompletionProposalComputer { private final HippieProposalProcessor fProcessor = new HippieProposalProcessor ( ) ; public HippieProposalComputer ( ) { } public List computeCompletionProposals ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { return Arrays . asList ( fProcessor . computeCompletionProposals ( context . getViewer ( ) , context . getInvocationOffset ( ) ) ) ; } public List computeContextInformation ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { return Arrays . asList ( fProcessor . computeContextInformation ( context . getViewer ( ) , context . getInvocationOffset ( ) ) ) ; } public String getErrorMessage ( ) { return fProcessor . getErrorMessage ( ) ; } public void sessionStarted ( ) { } public void sessionEnded ( ) { } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . StringTokenizer ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . Assert ; import org . eclipse . swt . SWT ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . ruby . hover . IRubyEditorTextHover ; public class RubyEditorTextHoverDescriptor { private static final String RUBY_EDITOR_TEXT_HOVER_EXTENSION_POINT = "" ; private static final String HOVER_TAG = "" ; private static final String ID_ATTRIBUTE = "" ; private static final String CLASS_ATTRIBUTE = "" ; private static final String LABEL_ATTRIBUTE = "" ; private static final String ACTIVATE_PLUG_IN_ATTRIBUTE = "" ; private static final String DESCRIPTION_ATTRIBUTE = "" ; public static final String NO_MODIFIER = "" ; public static final String DISABLED_TAG = "" ; public static final String VALUE_SEPARATOR = "" ; private int fStateMask ; private String fModifierString ; private boolean fIsEnabled ; private IConfigurationElement fElement ; public static RubyEditorTextHoverDescriptor [ ] getContributedHovers ( ) { IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; IConfigurationElement [ ] elements = registry . getConfigurationElementsFor ( RUBY_EDITOR_TEXT_HOVER_EXTENSION_POINT ) ; RubyEditorTextHoverDescriptor [ ] hoverDescs = createDescriptors ( elements ) ; initializeFromPreferences ( hoverDescs ) ; return hoverDescs ; } public static int computeStateMask ( String modifiers ) { if ( modifiers == null ) return - ; if ( modifiers . length ( ) == ) return SWT . NONE ; int stateMask = ; StringTokenizer modifierTokenizer = new StringTokenizer ( modifiers , "" ) ; while ( modifierTokenizer . hasMoreTokens ( ) ) { int modifier = EditorUtility . findLocalizedModifier ( modifierTokenizer . nextToken ( ) ) ; if ( modifier == || ( stateMask & modifier ) == modifier ) return - ; stateMask = stateMask | modifier ; } return stateMask ; } private RubyEditorTextHoverDescriptor ( IConfigurationElement element ) { Assert . isNotNull ( element ) ; fElement = element ; } public IRubyEditorTextHover createTextHover ( ) { String pluginId = fElement . getContributor ( ) . getName ( ) ; boolean isHoversPlugInActivated = Platform . getBundle ( pluginId ) . getState ( ) == Bundle . ACTIVE ; if ( isHoversPlugInActivated || canActivatePlugIn ( ) ) { try { return ( IRubyEditorTextHover ) fElement . createExecutableExtension ( CLASS_ATTRIBUTE ) ; } catch ( CoreException x ) { RubyPlugin . log ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , RubyHoverMessages . RubyTextHover_createTextHover , null ) ) ; } } return null ; } public String getId ( ) { return fElement . getAttribute ( ID_ATTRIBUTE ) ; } public String getHoverClassName ( ) { return fElement . getAttribute ( CLASS_ATTRIBUTE ) ; } public String getLabel ( ) { String label = fElement . getAttribute ( LABEL_ATTRIBUTE ) ; if ( label != null ) return label ; label = getHoverClassName ( ) ; int lastDot = label . lastIndexOf ( '' ) ; if ( lastDot >= && lastDot < label . length ( ) - ) return label . substring ( lastDot + ) ; else return label ; } public String getDescription ( ) { return fElement . getAttribute ( DESCRIPTION_ATTRIBUTE ) ; } public boolean canActivatePlugIn ( ) { return Boolean . valueOf ( fElement . getAttribute ( ACTIVATE_PLUG_IN_ATTRIBUTE ) ) . booleanValue ( ) ; } public boolean equals ( Object obj ) { if ( obj == null || ! obj . getClass ( ) . equals ( this . getClass ( ) ) || getId ( ) == null ) return false ; return getId ( ) . equals ( ( ( RubyEditorTextHoverDescriptor ) obj ) . getId ( ) ) ; } public int hashCode ( ) { return getId ( ) . hashCode ( ) ; } private static RubyEditorTextHoverDescriptor [ ] createDescriptors ( IConfigurationElement [ ] elements ) { List result = new ArrayList ( elements . length ) ; for ( int i = ; i < elements . length ; i ++ ) { IConfigurationElement element = elements [ i ] ; if ( HOVER_TAG . equals ( element . getName ( ) ) ) { RubyEditorTextHoverDescriptor desc = new RubyEditorTextHoverDescriptor ( element ) ; result . add ( desc ) ; } } return ( RubyEditorTextHoverDescriptor [ ] ) result . toArray ( new RubyEditorTextHoverDescriptor [ result . size ( ) ] ) ; } private static void initializeFromPreferences ( RubyEditorTextHoverDescriptor [ ] hovers ) { String compiledTextHoverModifiers = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getString ( PreferenceConstants . EDITOR_TEXT_HOVER_MODIFIERS ) ; StringTokenizer tokenizer = new StringTokenizer ( compiledTextHoverModifiers , VALUE_SEPARATOR ) ; HashMap idToModifier = new HashMap ( tokenizer . countTokens ( ) / ) ; while ( tokenizer . hasMoreTokens ( ) ) { String id = tokenizer . nextToken ( ) ; if ( tokenizer . hasMoreTokens ( ) ) idToModifier . put ( id , tokenizer . nextToken ( ) ) ; } String compiledTextHoverModifierMasks = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getString ( PreferenceConstants . EDITOR_TEXT_HOVER_MODIFIER_MASKS ) ; tokenizer = new StringTokenizer ( compiledTextHoverModifierMasks , VALUE_SEPARATOR ) ; HashMap idToModifierMask = new HashMap ( tokenizer . countTokens ( ) / ) ; while ( tokenizer . hasMoreTokens ( ) ) { String id = tokenizer . nextToken ( ) ; if ( tokenizer . hasMoreTokens ( ) ) idToModifierMask . put ( id , tokenizer . nextToken ( ) ) ; } for ( int i = ; i < hovers . length ; i ++ ) { String modifierString = ( String ) idToModifier . get ( hovers [ i ] . getId ( ) ) ; boolean enabled = true ; if ( modifierString == null ) modifierString = DISABLED_TAG ; if ( modifierString . startsWith ( DISABLED_TAG ) ) { enabled = false ; modifierString = modifierString . substring ( ) ; } if ( modifierString . equals ( NO_MODIFIER ) ) modifierString = "" ; hovers [ i ] . fModifierString = modifierString ; hovers [ i ] . fIsEnabled = enabled ; hovers [ i ] . fStateMask = computeStateMask ( modifierString ) ; if ( hovers [ i ] . fStateMask == - ) { try { hovers [ i ] . fStateMask = Integer . parseInt ( ( String ) idToModifierMask . get ( hovers [ i ] . getId ( ) ) ) ; } catch ( NumberFormatException ex ) { hovers [ i ] . fStateMask = - ; } int stateMask = hovers [ i ] . fStateMask ; if ( stateMask == - ) hovers [ i ] . fModifierString = "" ; else hovers [ i ] . fModifierString = EditorUtility . getModifierString ( stateMask ) ; } } } public int getStateMask ( ) { return fStateMask ; } public String getModifierString ( ) { return fModifierString ; } public boolean isEnabled ( ) { return fIsEnabled ; } public IConfigurationElement getConfigurationElement ( ) { return fElement ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import java . text . MessageFormat ; import org . eclipse . osgi . util . NLS ; class RubyHoverMessages extends NLS { private static final String BUNDLE_NAME = RubyHoverMessages . class . getName ( ) ; private RubyHoverMessages ( ) { } public static String RubyTextHover_makeStickyHint ; public static String RubyTextHover_createTextHover ; static { NLS . initializeMessages ( BUNDLE_NAME , RubyHoverMessages . class ) ; } public static String getFormattedString ( String key , Object arg ) { return MessageFormat . format ( key , new Object [ ] { arg } ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . information . IInformationProviderExtension2 ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . corext . util . RDocUtil ; import org . rubypeople . rdt . internal . ui . text . HTMLPrinter ; import org . rubypeople . rdt . internal . ui . text . HTMLTextPresenter ; import org . rubypeople . rdt . internal . ui . text . ruby . IInformationControlExtension4 ; public class CommentHoverProvider extends AbstractRubyEditorTextHover implements IInformationProviderExtension2 { private IInformationControlCreator fHoverControlCreator ; private IInformationControlCreator fPresenterControlCreator ; protected String getHoverInfo ( IRubyElement [ ] result ) { StringBuffer buffer = new StringBuffer ( ) ; String contents = RDocUtil . getHTMLDocumentation ( result ) ; if ( contents != null ) buffer . append ( contents ) ; if ( buffer . length ( ) > ) { HTMLPrinter . insertPageProlog ( buffer , , getStyleSheet ( ) ) ; HTMLPrinter . addPageEpilog ( buffer ) ; return buffer . toString ( ) ; } return null ; } public IInformationControlCreator getInformationPresenterControlCreator ( ) { if ( fPresenterControlCreator == null ) { fPresenterControlCreator = new AbstractReusableInformationControlCreator ( ) { public IInformationControl doCreateInformationControl ( Shell parent ) { int shellStyle = SWT . RESIZE | SWT . TOOL ; int style = SWT . V_SCROLL | SWT . H_SCROLL ; if ( BrowserInformationControl . isAvailable ( parent ) ) return new BrowserInformationControl ( parent , shellStyle , style ) ; else return new DefaultInformationControl ( parent , shellStyle , style , new HTMLTextPresenter ( false ) ) ; } } ; } return fPresenterControlCreator ; } public IInformationControlCreator getHoverControlCreator ( ) { if ( fHoverControlCreator == null ) { fHoverControlCreator = new AbstractReusableInformationControlCreator ( ) { public IInformationControl doCreateInformationControl ( Shell parent ) { if ( BrowserInformationControl . isAvailable ( parent ) ) return new BrowserInformationControl ( parent , SWT . TOOL | SWT . NO_TRIM , SWT . NONE , getTooltipAffordanceString ( ) ) ; else return new DefaultInformationControl ( parent , SWT . NONE , new HTMLTextPresenter ( true ) , getTooltipAffordanceString ( ) ) ; } public boolean canReuse ( IInformationControl control ) { boolean canReuse = super . canReuse ( control ) ; if ( canReuse && control instanceof IInformationControlExtension4 ) ( ( IInformationControlExtension4 ) control ) . setStatusText ( getTooltipAffordanceString ( ) ) ; return canReuse ; } } ; } return fHoverControlCreator ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IInformationControlCreatorExtension ; public abstract class AbstractReusableInformationControlCreator implements IInformationControlCreator , IInformationControlCreatorExtension , DisposeListener { private Map fInformationControls = new HashMap ( ) ; protected abstract IInformationControl doCreateInformationControl ( Shell parent ) ; public IInformationControl createInformationControl ( Shell parent ) { IInformationControl control = ( IInformationControl ) fInformationControls . get ( parent ) ; if ( control == null ) { control = doCreateInformationControl ( parent ) ; control . addDisposeListener ( this ) ; fInformationControls . put ( parent , control ) ; } return control ; } public void widgetDisposed ( DisposeEvent e ) { Composite parent = null ; if ( e . widget instanceof Shell ) parent = ( ( Shell ) e . widget ) . getParent ( ) ; if ( parent instanceof Shell ) fInformationControls . remove ( parent ) ; } public boolean canReuse ( IInformationControl control ) { return fInformationControls . containsValue ( control ) ; } public boolean canReplace ( IInformationControlCreator creator ) { return creator . getClass ( ) == getClass ( ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . jface . text . ITextHoverExtension ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . information . IInformationProviderExtension2 ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . ruby . hover . IRubyEditorTextHover ; public class BestMatchHover extends AbstractRubyEditorTextHover implements ITextHoverExtension , IInformationProviderExtension2 { private List < RubyEditorTextHoverDescriptor > fTextHoverSpecifications ; private List < ITextHover > fInstantiatedTextHovers ; private ITextHover fBestHover ; public BestMatchHover ( ) { installTextHovers ( ) ; } public BestMatchHover ( IEditorPart editor ) { this ( ) ; setEditor ( editor ) ; } private void installTextHovers ( ) { fTextHoverSpecifications = new ArrayList < RubyEditorTextHoverDescriptor > ( ) ; fInstantiatedTextHovers = new ArrayList < ITextHover > ( ) ; RubyEditorTextHoverDescriptor [ ] hoverDescs = RubyPlugin . getDefault ( ) . getRubyEditorTextHoverDescriptors ( ) ; for ( int i = ; i < hoverDescs . length ; i ++ ) { if ( ! PreferenceConstants . ID_BESTMATCH_HOVER . equals ( hoverDescs [ i ] . getId ( ) ) ) fTextHoverSpecifications . add ( hoverDescs [ i ] ) ; } } private void checkTextHovers ( ) { if ( fTextHoverSpecifications . size ( ) == ) return ; for ( Iterator < RubyEditorTextHoverDescriptor > iterator = new ArrayList < RubyEditorTextHoverDescriptor > ( fTextHoverSpecifications ) . iterator ( ) ; iterator . hasNext ( ) ; ) { RubyEditorTextHoverDescriptor spec = iterator . next ( ) ; IRubyEditorTextHover hover = spec . createTextHover ( ) ; if ( hover != null ) { hover . setEditor ( getEditor ( ) ) ; addTextHover ( hover ) ; fTextHoverSpecifications . remove ( spec ) ; } } } protected void addTextHover ( ITextHover hover ) { if ( ! fInstantiatedTextHovers . contains ( hover ) ) fInstantiatedTextHovers . add ( hover ) ; } public String getHoverInfo ( ITextViewer textViewer , IRegion hoverRegion ) { checkTextHovers ( ) ; fBestHover = null ; if ( fInstantiatedTextHovers == null ) return null ; for ( Iterator < ITextHover > iterator = fInstantiatedTextHovers . iterator ( ) ; iterator . hasNext ( ) ; ) { ITextHover hover = iterator . next ( ) ; try { String s = hover . getHoverInfo ( textViewer , hoverRegion ) ; if ( s != null && s . trim ( ) . length ( ) > ) { fBestHover = hover ; return s ; } } catch ( Exception e ) { } } return null ; } public IInformationControlCreator getHoverControlCreator ( ) { if ( fBestHover instanceof ITextHoverExtension ) return ( ( ITextHoverExtension ) fBestHover ) . getHoverControlCreator ( ) ; return null ; } public IInformationControlCreator getInformationPresenterControlCreator ( ) { if ( fBestHover instanceof IInformationProviderExtension2 ) return ( ( IInformationProviderExtension2 ) fBestHover ) . getInformationPresenterControlCreator ( ) ; return null ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . information . IInformationProvider ; import org . eclipse . jface . text . information . IInformationProviderExtension2 ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IPartListener ; import org . eclipse . ui . IPerspectiveDescriptor ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . rubypeople . rdt . internal . ui . text . HTMLTextPresenter ; import org . rubypeople . rdt . internal . ui . text . RubyWordFinder ; import org . rubypeople . rdt . ui . text . ruby . hover . IRubyEditorTextHover ; public class RubyInformationProvider implements IInformationProvider , IInformationProviderExtension2 { class EditorWatcher implements IPartListener { public void partOpened ( IWorkbenchPart part ) { } public void partDeactivated ( IWorkbenchPart part ) { } public void partClosed ( IWorkbenchPart part ) { if ( part == fEditor ) { fEditor . getSite ( ) . getWorkbenchWindow ( ) . getPartService ( ) . removePartListener ( fPartListener ) ; fPartListener = null ; } } public void partActivated ( IWorkbenchPart part ) { update ( ) ; } public void partBroughtToTop ( IWorkbenchPart part ) { update ( ) ; } } protected IEditorPart fEditor ; protected IPartListener fPartListener ; protected String fCurrentPerspective ; protected IRubyEditorTextHover fImplementation ; private IInformationControlCreator fPresenterControlCreator ; public RubyInformationProvider ( IEditorPart editor ) { fEditor = editor ; if ( fEditor != null ) { fPartListener = new EditorWatcher ( ) ; IWorkbenchWindow window = fEditor . getSite ( ) . getWorkbenchWindow ( ) ; window . getPartService ( ) . addPartListener ( fPartListener ) ; update ( ) ; } } protected void update ( ) { IWorkbenchWindow window = fEditor . getSite ( ) . getWorkbenchWindow ( ) ; IWorkbenchPage page = window . getActivePage ( ) ; if ( page != null ) { IPerspectiveDescriptor perspective = page . getPerspective ( ) ; if ( perspective != null ) { String perspectiveId = perspective . getId ( ) ; if ( fCurrentPerspective == null || fCurrentPerspective != perspectiveId ) { fCurrentPerspective = perspectiveId ; fImplementation = new RubyTypeHover ( ) ; fImplementation . setEditor ( fEditor ) ; } } } } public IRegion getSubject ( ITextViewer textViewer , int offset ) { if ( textViewer != null ) return RubyWordFinder . findWord ( textViewer . getDocument ( ) , offset ) ; return null ; } public String getInformation ( ITextViewer textViewer , IRegion subject ) { if ( fImplementation != null ) { String s = fImplementation . getHoverInfo ( textViewer , subject ) ; if ( s != null && s . trim ( ) . length ( ) > ) { return s ; } } return null ; } public IInformationControlCreator getInformationPresenterControlCreator ( ) { if ( fPresenterControlCreator == null ) { fPresenterControlCreator = new AbstractReusableInformationControlCreator ( ) { public IInformationControl doCreateInformationControl ( Shell parent ) { int shellStyle = SWT . RESIZE | SWT . TOOL ; int style = SWT . V_SCROLL | SWT . H_SCROLL ; if ( BrowserInformationControl . isAvailable ( parent ) ) return new BrowserInformationControl ( parent , shellStyle , style ) ; else return new DefaultInformationControl ( parent , shellStyle , style , new HTMLTextPresenter ( false ) ) ; } } ; } return fPresenterControlCreator ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; public class ProblemHover extends AbstractAnnotationHover { public ProblemHover ( ) { super ( false ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextHoverExtension ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . information . IInformationProviderExtension2 ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . ui . text . ruby . hover . IRubyEditorTextHover ; public class RubyEditorTextHoverProxy extends AbstractRubyEditorTextHover implements ITextHoverExtension , IInformationProviderExtension2 { private RubyEditorTextHoverDescriptor fHoverDescriptor ; private IRubyEditorTextHover fHover ; public RubyEditorTextHoverProxy ( RubyEditorTextHoverDescriptor descriptor , IEditorPart editor ) { fHoverDescriptor = descriptor ; setEditor ( editor ) ; } public void setEditor ( IEditorPart editor ) { super . setEditor ( editor ) ; if ( fHover != null ) fHover . setEditor ( getEditor ( ) ) ; } public boolean isEnabled ( ) { return true ; } public IRegion getHoverRegion ( ITextViewer textViewer , int offset ) { if ( ensureHoverCreated ( ) ) return fHover . getHoverRegion ( textViewer , offset ) ; return null ; } public String getHoverInfo ( ITextViewer textViewer , IRegion hoverRegion ) { if ( ensureHoverCreated ( ) ) return fHover . getHoverInfo ( textViewer , hoverRegion ) ; return null ; } private boolean ensureHoverCreated ( ) { if ( ! isEnabled ( ) || fHoverDescriptor == null ) return false ; return isCreated ( ) || createHover ( ) ; } private boolean isCreated ( ) { return fHover != null ; } private boolean createHover ( ) { fHover = fHoverDescriptor . createTextHover ( ) ; if ( fHover != null ) fHover . setEditor ( getEditor ( ) ) ; return isCreated ( ) ; } public IInformationControlCreator getHoverControlCreator ( ) { if ( ensureHoverCreated ( ) && ( fHover instanceof ITextHoverExtension ) ) return ( ( ITextHoverExtension ) fHover ) . getHoverControlCreator ( ) ; return null ; } public IInformationControlCreator getInformationPresenterControlCreator ( ) { if ( ensureHoverCreated ( ) && ( fHover instanceof IInformationProviderExtension2 ) ) return ( ( IInformationProviderExtension2 ) fHover ) . getInformationPresenterControlCreator ( ) ; return null ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . ui . text . ruby . hover . IRubyEditorTextHover ; public class RubyTypeHover implements IRubyEditorTextHover { private IRubyEditorTextHover fProblemHover ; private IRubyEditorTextHover fRubydocHover ; public RubyTypeHover ( ) { fProblemHover = new ProblemHover ( ) ; fRubydocHover = new CommentHoverProvider ( ) ; } public void setEditor ( IEditorPart editor ) { fProblemHover . setEditor ( editor ) ; fRubydocHover . setEditor ( editor ) ; } public IRegion getHoverRegion ( ITextViewer textViewer , int offset ) { return fRubydocHover . getHoverRegion ( textViewer , offset ) ; } public String getHoverInfo ( ITextViewer textViewer , IRegion hoverRegion ) { String hoverInfo = fProblemHover . getHoverInfo ( textViewer , hoverRegion ) ; if ( hoverInfo != null ) return hoverInfo ; return fRubydocHover . getHoverInfo ( textViewer , hoverRegion ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . ITextHoverExtension ; import org . eclipse . jface . text . information . IInformationProviderExtension2 ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . part . IWorkbenchPartOrientation ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . codemanipulation . StubUtility ; import org . rubypeople . rdt . internal . corext . util . Strings ; public class RubySourceHover extends AbstractRubyEditorTextHover implements ITextHoverExtension , IInformationProviderExtension2 { protected String getHoverInfo ( IRubyElement [ ] result ) { int nResults = result . length ; if ( nResults > ) return null ; IRubyElement curr = result [ ] ; if ( ( curr instanceof IMember ) && curr instanceof ISourceReference ) { try { String source = ( ( ISourceReference ) curr ) . getSource ( ) ; if ( source == null ) return null ; source = removeLeadingComments ( source ) ; String delim = StubUtility . getLineDelimiterUsed ( result [ ] ) ; String [ ] sourceLines = Strings . convertIntoLines ( source ) ; String firstLine = sourceLines [ ] ; if ( ! Character . isWhitespace ( firstLine . charAt ( ) ) ) sourceLines [ ] = "" ; Strings . trimIndentation ( sourceLines , curr . getRubyProject ( ) ) ; if ( ! Character . isWhitespace ( firstLine . charAt ( ) ) ) sourceLines [ ] = firstLine ; source = Strings . concatenate ( sourceLines , delim ) ; return source ; } catch ( RubyModelException ex ) { } } return null ; } private String removeLeadingComments ( String source ) { return source ; } public IInformationControlCreator getHoverControlCreator ( ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { IEditorPart editor = getEditor ( ) ; int shellStyle = SWT . TOOL | SWT . NO_TRIM ; if ( editor instanceof IWorkbenchPartOrientation ) shellStyle |= ( ( IWorkbenchPartOrientation ) editor ) . getOrientation ( ) ; return new SourceViewerInformationControl ( parent , shellStyle , SWT . NONE , getTooltipAffordanceString ( ) ) ; } } ; } public IInformationControlCreator getInformationPresenterControlCreator ( ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { int style = SWT . V_SCROLL | SWT . H_SCROLL ; int shellStyle = SWT . RESIZE | SWT . TOOL ; IEditorPart editor = getEditor ( ) ; if ( editor instanceof IWorkbenchPartOrientation ) shellStyle |= ( ( IWorkbenchPartOrientation ) editor ) . getOrientation ( ) ; return new SourceViewerInformationControl ( parent , shellStyle , style ) ; } } ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import java . util . ArrayList ; import java . util . List ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . internal . ui . infoviews . RiUtility ; public class RiDocHoverProvider extends AbstractRubyEditorTextHover { protected String getHoverInfo ( IRubyElement [ ] rubyElements ) { if ( rubyElements == null || rubyElements . length == ) return null ; String symbol = getRICompatibleName ( rubyElements [ ] ) ; if ( symbol == null ) return null ; return getRIResult ( symbol ) ; } private String getRIResult ( String symbol ) { if ( symbol == null || symbol . trim ( ) . length ( ) == ) return null ; List < String > args = new ArrayList < String > ( ) ; args . add ( "" ) ; args . add ( symbol ) ; String content = RiUtility . getRIHTMLContents ( args ) ; if ( content == null ) return null ; if ( content . indexOf ( "" ) > - ) return null ; content = content . replace ( "" , "" ) ; content = content . replace ( "" , "" ) ; return content ; } private String getRICompatibleName ( IRubyElement element ) { switch ( element . getElementType ( ) ) { case IRubyElement . TYPE : return ( ( IType ) element ) . getFullyQualifiedName ( ) ; case IRubyElement . METHOD : IMethod method = ( IMethod ) element ; String delimeter = method . isSingleton ( ) ? "" : "" ; return method . getDeclaringType ( ) . getFullyQualifiedName ( ) + delimeter + element . getElementName ( ) ; default : return null ; } } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . net . URL ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPartitioningException ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextHoverExtension ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . keys . IBindingService ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . core . ICodeAssist ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyScriptEditorInput ; import org . rubypeople . rdt . internal . ui . rubyeditor . WorkingCopyManager ; import org . rubypeople . rdt . internal . ui . text . HTMLTextPresenter ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . RubyWordFinder ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . actions . IRubyEditorActionDefinitionIds ; import org . rubypeople . rdt . ui . text . ruby . hover . IRubyEditorTextHover ; public abstract class AbstractRubyEditorTextHover implements IRubyEditorTextHover , ITextHoverExtension { private static String fgStyleSheet ; private IEditorPart fEditor ; private IBindingService fBindingService ; { fBindingService = ( IBindingService ) PlatformUI . getWorkbench ( ) . getAdapter ( IBindingService . class ) ; } public void setEditor ( IEditorPart editor ) { fEditor = editor ; } protected IEditorPart getEditor ( ) { return fEditor ; } protected ICodeAssist getCodeAssist ( ) { if ( fEditor != null ) { IEditorInput input = fEditor . getEditorInput ( ) ; if ( input instanceof RubyScriptEditorInput ) { RubyScriptEditorInput cfeInput = ( RubyScriptEditorInput ) input ; return cfeInput . getRubyScript ( ) ; } WorkingCopyManager manager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; return manager . getWorkingCopy ( input , false ) ; } return null ; } public IRegion getHoverRegion ( ITextViewer textViewer , int offset ) { return RubyWordFinder . findWord ( textViewer . getDocument ( ) , offset ) ; } public String getHoverInfo ( ITextViewer textViewer , IRegion hoverRegion ) { if ( hoverRegion . getLength ( ) == ) return null ; try { IDocument doc = textViewer . getDocument ( ) ; if ( doc == null ) return null ; String contentType = null ; if ( doc instanceof IDocumentExtension3 ) { IDocumentExtension3 extension = ( IDocumentExtension3 ) doc ; try { contentType = extension . getContentType ( IRubyPartitions . RUBY_PARTITIONING , hoverRegion . getOffset ( ) , false ) ; } catch ( BadPartitioningException e ) { } } if ( contentType != null && ! contentType . equals ( IRubyPartitions . RUBY_DEFAULT ) ) { return null ; } } catch ( BadLocationException e ) { } ICodeAssist resolve = getCodeAssist ( ) ; if ( resolve != null ) { try { IRubyElement [ ] result = resolve . codeSelect ( hoverRegion . getOffset ( ) , hoverRegion . getLength ( ) ) ; if ( result == null ) return null ; int nResults = result . length ; if ( nResults == ) return null ; return getHoverInfo ( result ) ; } catch ( RubyModelException x ) { return null ; } } return null ; } protected String getHoverInfo ( IRubyElement [ ] rubyElements ) { return null ; } public IInformationControlCreator getHoverControlCreator ( ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { return new DefaultInformationControl ( parent , SWT . NONE , new HTMLTextPresenter ( true ) , getTooltipAffordanceString ( ) ) ; } } ; } protected String getTooltipAffordanceString ( ) { if ( fBindingService == null || ! RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . EDITOR_SHOW_TEXT_HOVER_AFFORDANCE ) ) return null ; String keySequence = fBindingService . getBestActiveBindingFormattedFor ( IRubyEditorActionDefinitionIds . SHOW_RDOC ) ; if ( keySequence == null ) return null ; return Messages . format ( RubyHoverMessages . RubyTextHover_makeStickyHint , keySequence == null ? "" : keySequence ) ; } public static String getStyleSheet ( ) { if ( fgStyleSheet == null ) { Bundle bundle = Platform . getBundle ( RubyPlugin . getPluginId ( ) ) ; URL styleSheetURL = bundle . getEntry ( "" ) ; if ( styleSheetURL != null ) { try { styleSheetURL = FileLocator . toFileURL ( styleSheetURL ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( styleSheetURL . openStream ( ) ) ) ; StringBuffer buffer = new StringBuffer ( ) ; String line = reader . readLine ( ) ; while ( line != null ) { buffer . append ( line ) ; buffer . append ( '' ) ; line = reader . readLine ( ) ; } fgStyleSheet = buffer . toString ( ) ; } catch ( IOException ex ) { RubyPlugin . log ( ex ) ; fgStyleSheet = "" ; } } } return fgStyleSheet ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlExtension ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubySourceViewer ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . SimpleRubySourceViewerConfiguration ; public class SourceViewerInformationControl implements IInformationControl , IInformationControlExtension , DisposeListener { private static final int BORDER = ; private Shell fShell ; private StyledText fText ; private SourceViewer fViewer ; private Label fStatusField ; private Label fSeparator ; private Font fStatusTextFont ; public SourceViewerInformationControl ( Shell parent , int shellStyle , int style ) { this ( parent , shellStyle , style , null ) ; } public SourceViewerInformationControl ( Shell parent , int shellStyle , int style , String statusFieldText ) { GridLayout layout ; GridData gd ; fShell = new Shell ( parent , SWT . NO_FOCUS | SWT . ON_TOP | shellStyle ) ; Display display = fShell . getDisplay ( ) ; fShell . setBackground ( display . getSystemColor ( SWT . COLOR_BLACK ) ) ; Composite composite = fShell ; layout = new GridLayout ( , false ) ; int border = ( ( shellStyle & SWT . NO_TRIM ) == ) ? : BORDER ; layout . marginHeight = border ; layout . marginWidth = border ; composite . setLayout ( layout ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; composite . setLayoutData ( gd ) ; if ( statusFieldText != null ) { composite = new Composite ( composite , SWT . NONE ) ; layout = new GridLayout ( , false ) ; layout . marginHeight = ; layout . marginWidth = ; composite . setLayout ( layout ) ; gd = new GridData ( GridData . FILL_BOTH ) ; composite . setLayoutData ( gd ) ; composite . setForeground ( display . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; composite . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; } IPreferenceStore store = RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; fViewer = new RubySourceViewer ( composite , null , null , false , style , store ) ; fViewer . configure ( new SimpleRubySourceViewerConfiguration ( RubyPlugin . getDefault ( ) . getRubyTextTools ( ) . getColorManager ( ) , store , null , IRubyPartitions . RUBY_PARTITIONING , false ) ) ; fViewer . setEditable ( false ) ; fText = fViewer . getTextWidget ( ) ; gd = new GridData ( GridData . BEGINNING | GridData . FILL_BOTH ) ; fText . setLayoutData ( gd ) ; fText . setForeground ( parent . getDisplay ( ) . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; fText . setBackground ( parent . getDisplay ( ) . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; initializeFont ( ) ; fText . addKeyListener ( new KeyListener ( ) { public void keyPressed ( KeyEvent e ) { if ( e . character == ) fShell . dispose ( ) ; } public void keyReleased ( KeyEvent e ) { } } ) ; if ( statusFieldText != null ) { fSeparator = new Label ( composite , SWT . SEPARATOR | SWT . HORIZONTAL | SWT . LINE_DOT ) ; fSeparator . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fStatusField = new Label ( composite , SWT . RIGHT ) ; fStatusField . setText ( statusFieldText ) ; Font font = fStatusField . getFont ( ) ; FontData [ ] fontDatas = font . getFontData ( ) ; for ( int i = ; i < fontDatas . length ; i ++ ) fontDatas [ i ] . setHeight ( fontDatas [ i ] . getHeight ( ) * / ) ; fStatusTextFont = new Font ( fStatusField . getDisplay ( ) , fontDatas ) ; fStatusField . setFont ( fStatusTextFont ) ; GridData gd2 = new GridData ( GridData . FILL_VERTICAL | GridData . FILL_HORIZONTAL | GridData . HORIZONTAL_ALIGN_BEGINNING | GridData . VERTICAL_ALIGN_BEGINNING ) ; fStatusField . setLayoutData ( gd2 ) ; fStatusField . setForeground ( display . getSystemColor ( SWT . COLOR_WIDGET_DARK_SHADOW ) ) ; fStatusField . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; } addDisposeListener ( this ) ; } public SourceViewerInformationControl ( Shell parent , int style ) { this ( parent , SWT . NO_TRIM | SWT . TOOL , style ) ; } public SourceViewerInformationControl ( Shell parent , int style , String statusFieldText ) { this ( parent , SWT . NO_TRIM | SWT . TOOL , style , statusFieldText ) ; } public SourceViewerInformationControl ( Shell parent ) { this ( parent , SWT . NONE ) ; } public SourceViewerInformationControl ( Shell parent , String statusFieldText ) { this ( parent , SWT . NONE , statusFieldText ) ; } private void initializeFont ( ) { Font font = JFaceResources . getFont ( "" ) ; StyledText styledText = getViewer ( ) . getTextWidget ( ) ; styledText . setFont ( font ) ; } public void setInput ( Object input ) { if ( input instanceof String ) setInformation ( ( String ) input ) ; else setInformation ( null ) ; } public void setInformation ( String content ) { if ( content == null ) { fViewer . setInput ( null ) ; return ; } IDocument doc = new Document ( content ) ; RubyPlugin . getDefault ( ) . getRubyTextTools ( ) . setupRubyDocumentPartitioner ( doc , IRubyPartitions . RUBY_PARTITIONING ) ; fViewer . setInput ( doc ) ; } public void setVisible ( boolean visible ) { fShell . setVisible ( visible ) ; } public void widgetDisposed ( DisposeEvent event ) { if ( fStatusTextFont != null && ! fStatusTextFont . isDisposed ( ) ) fStatusTextFont . dispose ( ) ; fStatusTextFont = null ; fShell = null ; fText = null ; } public final void dispose ( ) { if ( fShell != null && ! fShell . isDisposed ( ) ) fShell . dispose ( ) ; else widgetDisposed ( null ) ; } public void setSize ( int width , int height ) { if ( fStatusField != null ) { GridData gd = ( GridData ) fViewer . getTextWidget ( ) . getLayoutData ( ) ; Point statusSize = fStatusField . computeSize ( SWT . DEFAULT , SWT . DEFAULT , true ) ; Point separatorSize = fSeparator . computeSize ( SWT . DEFAULT , SWT . DEFAULT , true ) ; gd . heightHint = height - statusSize . y - separatorSize . y ; } fShell . setSize ( width , height ) ; if ( fStatusField != null ) fShell . pack ( true ) ; } public void setLocation ( Point location ) { Rectangle trim = fShell . computeTrim ( , , , ) ; Point textLocation = fText . getLocation ( ) ; location . x += trim . x - textLocation . x ; location . y += trim . y - textLocation . y ; fShell . setLocation ( location ) ; } public void setSizeConstraints ( int maxWidth , int maxHeight ) { maxWidth = maxHeight ; } public Point computeSizeHint ( ) { return fShell . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; } public void addDisposeListener ( DisposeListener listener ) { fShell . addDisposeListener ( listener ) ; } public void removeDisposeListener ( DisposeListener listener ) { fShell . removeDisposeListener ( listener ) ; } public void setForegroundColor ( Color foreground ) { fText . setForeground ( foreground ) ; } public void setBackgroundColor ( Color background ) { fText . setBackground ( background ) ; } public boolean isFocusControl ( ) { return fText . isFocusControl ( ) ; } public void setFocus ( ) { fShell . forceFocus ( ) ; fText . setFocus ( ) ; } public void addFocusListener ( FocusListener listener ) { fText . addFocusListener ( listener ) ; } public void removeFocusListener ( FocusListener listener ) { fText . removeFocusListener ( listener ) ; } public boolean hasContents ( ) { return fText . getCharCount ( ) > ; } protected ISourceViewer getViewer ( ) { return fViewer ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import java . util . Iterator ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . filebuffers . FileBuffers ; import org . eclipse . core . filebuffers . ITextFileBufferManager ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IStorageEditorInput ; import org . eclipse . ui . texteditor . AnnotationPreference ; import org . eclipse . ui . texteditor . DefaultMarkerAnnotationAccess ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyAnnotationIterator ; import org . rubypeople . rdt . internal . ui . text . HTMLPrinter ; public abstract class AbstractAnnotationHover extends AbstractRubyEditorTextHover { private IPreferenceStore fStore = RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; private DefaultMarkerAnnotationAccess fAnnotationAccess = new DefaultMarkerAnnotationAccess ( ) ; private boolean fAllAnnotations ; public AbstractAnnotationHover ( boolean allAnnotations ) { fAllAnnotations = allAnnotations ; } private String formatMessage ( String message ) { StringBuffer buffer = new StringBuffer ( ) ; HTMLPrinter . addPageProlog ( buffer ) ; HTMLPrinter . addParagraph ( buffer , HTMLPrinter . convertToHTMLContent ( message ) ) ; HTMLPrinter . addPageEpilog ( buffer ) ; return buffer . toString ( ) ; } public String getHoverInfo ( ITextViewer textViewer , IRegion hoverRegion ) { IPath path ; IAnnotationModel model ; if ( textViewer instanceof ISourceViewer ) { path = null ; model = ( ( ISourceViewer ) textViewer ) . getAnnotationModel ( ) ; } else { path = getEditorInputPath ( ) ; model = getAnnotationModel ( path ) ; } if ( model == null ) return null ; try { Iterator e = new RubyAnnotationIterator ( model , true , fAllAnnotations ) ; int layer = - ; String message = null ; while ( e . hasNext ( ) ) { Annotation a = ( Annotation ) e . next ( ) ; AnnotationPreference preference = getAnnotationPreference ( a ) ; if ( preference == null || ! ( preference . getTextPreferenceKey ( ) != null && fStore . getBoolean ( preference . getTextPreferenceKey ( ) ) || ( preference . getHighlightPreferenceKey ( ) != null && fStore . getBoolean ( preference . getHighlightPreferenceKey ( ) ) ) ) ) continue ; Position p = model . getPosition ( a ) ; int l = fAnnotationAccess . getLayer ( a ) ; if ( l > layer && p != null && p . overlapsWith ( hoverRegion . getOffset ( ) , hoverRegion . getLength ( ) ) ) { String msg = a . getText ( ) ; if ( msg != null && msg . trim ( ) . length ( ) > ) { message = msg ; layer = l ; } } } if ( layer > - ) return formatMessage ( message ) ; } finally { try { if ( path != null ) { ITextFileBufferManager manager = FileBuffers . getTextFileBufferManager ( ) ; manager . disconnect ( path , null ) ; } } catch ( CoreException ex ) { RubyPlugin . log ( ex . getStatus ( ) ) ; } } return null ; } private IPath getEditorInputPath ( ) { if ( getEditor ( ) == null ) return null ; IEditorInput input = getEditor ( ) . getEditorInput ( ) ; if ( input instanceof IStorageEditorInput ) { try { return ( ( IStorageEditorInput ) input ) . getStorage ( ) . getFullPath ( ) ; } catch ( CoreException ex ) { RubyPlugin . log ( ex . getStatus ( ) ) ; } } return null ; } private IAnnotationModel getAnnotationModel ( IPath path ) { if ( path == null ) return null ; ITextFileBufferManager manager = FileBuffers . getTextFileBufferManager ( ) ; try { manager . connect ( path , null ) ; } catch ( CoreException ex ) { RubyPlugin . log ( ex . getStatus ( ) ) ; return null ; } IAnnotationModel model = null ; try { model = manager . getTextFileBuffer ( path ) . getAnnotationModel ( ) ; return model ; } finally { if ( model == null ) { try { manager . disconnect ( path , null ) ; } catch ( CoreException ex ) { RubyPlugin . log ( ex . getStatus ( ) ) ; } } } } private AnnotationPreference getAnnotationPreference ( Annotation annotation ) { if ( annotation . isMarkedDeleted ( ) ) return null ; return EditorsUI . getAnnotationPreferenceLookup ( ) . getAnnotationPreference ( annotation ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; public class AnnotationHover extends AbstractAnnotationHover { public AnnotationHover ( ) { super ( true ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby . hover ; import java . io . IOException ; import java . io . StringReader ; import java . util . Iterator ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlExtension ; import org . eclipse . jface . text . IInformationControlExtension3 ; import org . eclipse . jface . text . TextPresentation ; import org . eclipse . swt . SWT ; import org . eclipse . swt . SWTError ; import org . eclipse . swt . browser . Browser ; import org . eclipse . swt . browser . LocationAdapter ; import org . eclipse . swt . browser . LocationEvent ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . graphics . TextLayout ; import org . eclipse . swt . graphics . TextStyle ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . HTML2TextReader ; import org . rubypeople . rdt . internal . ui . text . HTMLPrinter ; import org . rubypeople . rdt . internal . ui . text . ruby . IInformationControlExtension4 ; public class BrowserInformationControl implements IInformationControl , IInformationControlExtension , IInformationControlExtension3 , IInformationControlExtension4 , DisposeListener { public static boolean isAvailable ( Composite parent ) { if ( ! fgAvailabilityChecked ) { try { if ( parent == null ) parent = RubyPlugin . getActiveWorkbenchShell ( ) ; if ( parent == null ) return false ; Browser browser = new Browser ( parent , SWT . NONE ) ; browser . dispose ( ) ; fgIsAvailable = true ; } catch ( SWTError er ) { fgIsAvailable = false ; } finally { fgAvailabilityChecked = true ; } } return fgIsAvailable ; } private static final int BORDER = ; private static final int MIN_WIDTH = ; private static final int MIN_HEIGHT = ; private static boolean fgIsAvailable = false ; private static boolean fgAvailabilityChecked = false ; private Shell fShell ; private Browser fBrowser ; private boolean fBrowserHasContent ; private int fMaxWidth = - ; private int fMaxHeight = - ; private Font fStatusTextFont ; private Label fStatusTextField ; private String fStatusFieldText ; private boolean fHideScrollBars ; private Listener fDeactivateListener ; private ListenerList fFocusListeners = new ListenerList ( ) ; private Label fSeparator ; private String fInputText ; private TextLayout fTextLayout ; private TextStyle fBoldStyle ; public BrowserInformationControl ( Shell parent , int shellStyle , int style ) { this ( parent , shellStyle , style , null ) ; } public BrowserInformationControl ( Shell parent , int shellStyle , int style , String statusFieldText ) { fStatusFieldText = statusFieldText ; fShell = new Shell ( parent , SWT . NO_FOCUS | SWT . ON_TOP | shellStyle ) ; Display display = fShell . getDisplay ( ) ; fShell . setBackground ( display . getSystemColor ( SWT . COLOR_BLACK ) ) ; fTextLayout = new TextLayout ( display ) ; Composite composite = fShell ; GridLayout layout = new GridLayout ( , false ) ; int border = ( ( shellStyle & SWT . NO_TRIM ) == ) ? : BORDER ; layout . marginHeight = border ; layout . marginWidth = border ; composite . setLayout ( layout ) ; if ( statusFieldText != null ) { composite = new Composite ( composite , SWT . NONE ) ; layout = new GridLayout ( , false ) ; layout . marginHeight = ; layout . marginWidth = ; layout . verticalSpacing = ; layout . horizontalSpacing = ; composite . setLayout ( layout ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; composite . setLayoutData ( gd ) ; composite . setForeground ( display . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; composite . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; } fBrowser = new Browser ( composite , SWT . NONE ) ; fHideScrollBars = ( style & SWT . V_SCROLL ) == && ( style & SWT . H_SCROLL ) == ; GridData gd = new GridData ( GridData . BEGINNING | GridData . FILL_BOTH ) ; fBrowser . setLayoutData ( gd ) ; fBrowser . setForeground ( display . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; fBrowser . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; fBrowser . addKeyListener ( new KeyListener ( ) { public void keyPressed ( KeyEvent e ) { if ( e . character == ) fShell . dispose ( ) ; } public void keyReleased ( KeyEvent e ) { } } ) ; fBrowser . addLocationListener ( new LocationAdapter ( ) { public void changing ( LocationEvent event ) { String location = event . location ; if ( ! "" . equals ( location ) && ! ( "" . equals ( SWT . getPlatform ( ) ) && location . startsWith ( "" ) ) ) event . doit = false ; } } ) ; fBrowser . setMenu ( new Menu ( fShell , SWT . NONE ) ) ; if ( statusFieldText != null ) { fSeparator = new Label ( composite , SWT . SEPARATOR | SWT . HORIZONTAL | SWT . LINE_DOT ) ; fSeparator . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fStatusTextField = new Label ( composite , SWT . RIGHT ) ; fStatusTextField . setText ( statusFieldText ) ; Font font = fStatusTextField . getFont ( ) ; FontData [ ] fontDatas = font . getFontData ( ) ; for ( int i = ; i < fontDatas . length ; i ++ ) fontDatas [ i ] . setHeight ( fontDatas [ i ] . getHeight ( ) * / ) ; fStatusTextFont = new Font ( fStatusTextField . getDisplay ( ) , fontDatas ) ; fStatusTextField . setFont ( fStatusTextFont ) ; gd = new GridData ( GridData . FILL_HORIZONTAL | GridData . HORIZONTAL_ALIGN_BEGINNING | GridData . VERTICAL_ALIGN_BEGINNING ) ; fStatusTextField . setLayoutData ( gd ) ; fStatusTextField . setForeground ( display . getSystemColor ( SWT . COLOR_WIDGET_DARK_SHADOW ) ) ; fStatusTextField . setBackground ( display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ) ; } addDisposeListener ( this ) ; createTextLayout ( ) ; } public BrowserInformationControl ( Shell parent , int style ) { this ( parent , SWT . TOOL | SWT . NO_TRIM , style ) ; } public BrowserInformationControl ( Shell parent ) { this ( parent , SWT . NONE ) ; } public void setInformation ( String content ) { fBrowserHasContent = content != null && content . length ( ) > ; if ( ! fBrowserHasContent ) content = "" ; fInputText = content ; int shellStyle = fShell . getStyle ( ) ; boolean RTL = ( shellStyle & SWT . RIGHT_TO_LEFT ) != ; String [ ] styles = null ; if ( RTL && ! fHideScrollBars ) styles = new String [ ] { "" , "" } ; else if ( RTL && fHideScrollBars ) styles = new String [ ] { "" , "" , "" } ; else if ( fHideScrollBars && true ) styles = new String [ ] { "" , "" } ; if ( styles != null ) { StringBuffer buffer = new StringBuffer ( content ) ; HTMLPrinter . insertStyles ( buffer , styles ) ; content = buffer . toString ( ) ; } fBrowser . setText ( content ) ; } public void setStatusText ( String statusFieldText ) { fStatusFieldText = statusFieldText ; } public void setVisible ( boolean visible ) { if ( fShell . isVisible ( ) == visible ) return ; if ( visible ) { if ( fStatusTextField != null ) { boolean state = fStatusFieldText != null ; if ( state ) fStatusTextField . setText ( fStatusFieldText ) ; fStatusTextField . setVisible ( state ) ; fSeparator . setVisible ( state ) ; } } fShell . setVisible ( visible ) ; if ( ! visible ) setInformation ( "" ) ; } private void createTextLayout ( ) { fTextLayout = new TextLayout ( fBrowser . getDisplay ( ) ) ; Font font = fBrowser . getFont ( ) ; fTextLayout . setFont ( font ) ; fTextLayout . setWidth ( - ) ; FontData [ ] fontData = font . getFontData ( ) ; for ( int i = ; i < fontData . length ; i ++ ) fontData [ i ] . setStyle ( SWT . BOLD ) ; font = new Font ( fShell . getDisplay ( ) , fontData ) ; fBoldStyle = new TextStyle ( font , null , null ) ; fTextLayout . setText ( "" ) ; int tabWidth = fTextLayout . getBounds ( ) . width ; fTextLayout . setTabs ( new int [ ] { tabWidth } ) ; fTextLayout . setText ( "" ) ; } public void dispose ( ) { fTextLayout . dispose ( ) ; fTextLayout = null ; fBoldStyle . font . dispose ( ) ; fBoldStyle = null ; if ( fShell != null && ! fShell . isDisposed ( ) ) fShell . dispose ( ) ; else widgetDisposed ( null ) ; } public void widgetDisposed ( DisposeEvent event ) { if ( fStatusTextFont != null && ! fStatusTextFont . isDisposed ( ) ) fStatusTextFont . dispose ( ) ; fShell = null ; fBrowser = null ; fStatusTextFont = null ; } public void setSize ( int width , int height ) { fShell . setSize ( Math . min ( width , fMaxWidth ) , Math . min ( height , fMaxHeight ) ) ; } public void setLocation ( Point location ) { fShell . setLocation ( location ) ; } public void setSizeConstraints ( int maxWidth , int maxHeight ) { fMaxWidth = maxWidth ; fMaxHeight = maxHeight ; } public Point computeSizeHint ( ) { TextPresentation presentation = new TextPresentation ( ) ; HTML2TextReader reader = new HTML2TextReader ( new StringReader ( fInputText ) , presentation ) ; String text ; try { text = reader . getString ( ) ; } catch ( IOException e ) { text = "" ; } fTextLayout . setText ( text ) ; Iterator iter = presentation . getAllStyleRangeIterator ( ) ; while ( iter . hasNext ( ) ) { StyleRange sr = ( StyleRange ) iter . next ( ) ; if ( sr . fontStyle == SWT . BOLD ) fTextLayout . setStyle ( fBoldStyle , sr . start , sr . start + sr . length - ) ; } Rectangle bounds = fTextLayout . getBounds ( ) ; int width = bounds . width ; int height = bounds . height ; width += ; height += ; if ( fStatusFieldText != null && fSeparator != null ) { fTextLayout . setText ( fStatusFieldText ) ; Rectangle statusBounds = fTextLayout . getBounds ( ) ; Rectangle separatorBounds = fSeparator . getBounds ( ) ; width = Math . max ( width , statusBounds . width ) ; height = height + statusBounds . height + separatorBounds . height ; } if ( fMaxWidth != SWT . DEFAULT ) width = Math . min ( fMaxWidth , width ) ; if ( fMaxHeight != SWT . DEFAULT ) height = Math . min ( fMaxHeight , height ) ; width = Math . max ( MIN_WIDTH , width ) ; height = Math . max ( MIN_HEIGHT , height ) ; return new Point ( width , height ) ; } public Rectangle computeTrim ( ) { return fShell . computeTrim ( , , , ) ; } public Rectangle getBounds ( ) { return fShell . getBounds ( ) ; } public boolean restoresLocation ( ) { return false ; } public boolean restoresSize ( ) { return false ; } public void addDisposeListener ( DisposeListener listener ) { fShell . addDisposeListener ( listener ) ; } public void removeDisposeListener ( DisposeListener listener ) { fShell . removeDisposeListener ( listener ) ; } public void setForegroundColor ( Color foreground ) { fBrowser . setForeground ( foreground ) ; } public void setBackgroundColor ( Color background ) { fBrowser . setBackground ( background ) ; } public boolean isFocusControl ( ) { return fBrowser . isFocusControl ( ) ; } public void setFocus ( ) { fShell . forceFocus ( ) ; fBrowser . setFocus ( ) ; } public void addFocusListener ( final FocusListener listener ) { fBrowser . addFocusListener ( listener ) ; if ( fFocusListeners . isEmpty ( ) ) { fDeactivateListener = new Listener ( ) { public void handleEvent ( Event event ) { Object [ ] listeners = fFocusListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) ( ( FocusListener ) listeners [ i ] ) . focusLost ( new FocusEvent ( event ) ) ; } } ; fBrowser . getShell ( ) . addListener ( SWT . Deactivate , fDeactivateListener ) ; } fFocusListeners . add ( listener ) ; } public void removeFocusListener ( FocusListener listener ) { fBrowser . removeFocusListener ( listener ) ; fFocusListeners . remove ( listener ) ; if ( fFocusListeners . isEmpty ( ) ) { fBrowser . getShell ( ) . removeListener ( SWT . Deactivate , fDeactivateListener ) ; fDeactivateListener = null ; } } public boolean hasContents ( ) { return fBrowserHasContent ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . InvalidRegistryObjectException ; import org . eclipse . core . runtime . PerformanceStats ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . Assert ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . text . ruby . AbstractProposalSorter ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; public final class ProposalSorterHandle { private static final String ID = "" ; private static final String NAME = "" ; private static final String CLASS = "" ; private static final String ACTIVATE = "" ; private static final String PERFORMANCE_EVENT = RubyPlugin . getPluginId ( ) + "" ; private static final boolean MEASURE_PERFORMANCE = PerformanceStats . isEnabled ( PERFORMANCE_EVENT ) ; private static final String SORT = "" ; private final String fId ; private final String fName ; private final String fClass ; private final boolean fActivate ; private final IConfigurationElement fElement ; private AbstractProposalSorter fSorter ; ProposalSorterHandle ( IConfigurationElement element ) throws InvalidRegistryObjectException { Assert . isLegal ( element != null ) ; fElement = element ; fId = element . getAttribute ( ID ) ; checkNotNull ( fId , ID ) ; String name = element . getAttribute ( NAME ) ; if ( name == null ) fName = fId ; else fName = name ; String activateAttribute = element . getAttribute ( ACTIVATE ) ; fActivate = Boolean . valueOf ( activateAttribute ) . booleanValue ( ) ; fClass = element . getAttribute ( CLASS ) ; checkNotNull ( fClass , CLASS ) ; } private void checkNotNull ( Object obj , String attribute ) throws InvalidRegistryObjectException { if ( obj == null ) { Object [ ] args = { getId ( ) , fElement . getContributor ( ) . getName ( ) , attribute } ; String message = Messages . format ( RubyTextMessages . CompletionProposalComputerDescriptor_illegal_attribute_message , args ) ; IStatus status = new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , message , null ) ; RubyPlugin . log ( status ) ; throw new InvalidRegistryObjectException ( ) ; } } public String getId ( ) { return fId ; } public String getName ( ) { return fName ; } private synchronized AbstractProposalSorter getSorter ( ) throws CoreException , InvalidRegistryObjectException { if ( fSorter == null && ( fActivate || isPluginLoaded ( ) ) ) fSorter = createSorter ( ) ; return fSorter ; } private boolean isPluginLoaded ( ) throws InvalidRegistryObjectException { Bundle bundle = getBundle ( ) ; return bundle != null && bundle . getState ( ) == Bundle . ACTIVE ; } private Bundle getBundle ( ) throws InvalidRegistryObjectException { String symbolicName = fElement . getContributor ( ) . getName ( ) ; Bundle bundle = Platform . getBundle ( symbolicName ) ; return bundle ; } private AbstractProposalSorter createSorter ( ) throws CoreException , InvalidRegistryObjectException { return ( AbstractProposalSorter ) fElement . createExecutableExtension ( CLASS ) ; } public void sortProposals ( ContentAssistInvocationContext context , List proposals ) { IStatus status ; try { AbstractProposalSorter sorter = getSorter ( ) ; PerformanceStats stats = startMeter ( SORT , sorter ) ; sorter . beginSorting ( context ) ; Collections . sort ( proposals , sorter ) ; sorter . endSorting ( ) ; status = stopMeter ( stats , SORT ) ; if ( status == null ) return ; status = createAPIViolationStatus ( SORT ) ; } catch ( InvalidRegistryObjectException x ) { status = createExceptionStatus ( x ) ; } catch ( CoreException x ) { status = createExceptionStatus ( x ) ; } catch ( RuntimeException x ) { status = createExceptionStatus ( x ) ; } RubyPlugin . log ( status ) ; return ; } private IStatus stopMeter ( final PerformanceStats stats , String operation ) { if ( MEASURE_PERFORMANCE ) { stats . endRun ( ) ; if ( stats . isFailure ( ) ) return createPerformanceStatus ( operation ) ; } return null ; } private PerformanceStats startMeter ( String context , AbstractProposalSorter sorter ) { final PerformanceStats stats ; if ( MEASURE_PERFORMANCE ) { stats = PerformanceStats . getStats ( PERFORMANCE_EVENT , sorter ) ; stats . startRun ( context ) ; } else { stats = null ; } return stats ; } private Status createExceptionStatus ( InvalidRegistryObjectException x ) { String disable = createBlameMessage ( ) ; String reason = RubyTextMessages . CompletionProposalComputerDescriptor_reason_invalid ; return new Status ( IStatus . INFO , RubyPlugin . getPluginId ( ) , IStatus . OK , disable + "" + reason , x ) ; } private Status createExceptionStatus ( CoreException x ) { String disable = createBlameMessage ( ) ; String reason = RubyTextMessages . CompletionProposalComputerDescriptor_reason_instantiation ; return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . OK , disable + "" + reason , x ) ; } private Status createExceptionStatus ( RuntimeException x ) { String disable = createBlameMessage ( ) ; String reason = RubyTextMessages . CompletionProposalComputerDescriptor_reason_runtime_ex ; return new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , disable + "" + reason , x ) ; } private Status createAPIViolationStatus ( String operation ) { String disable = createBlameMessage ( ) ; Object [ ] args = { operation } ; String reason = Messages . format ( RubyTextMessages . CompletionProposalComputerDescriptor_reason_API , args ) ; return new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , disable + "" + reason , null ) ; } private Status createPerformanceStatus ( String operation ) { String disable = createBlameMessage ( ) ; Object [ ] args = { operation } ; String reason = Messages . format ( RubyTextMessages . CompletionProposalComputerDescriptor_reason_performance , args ) ; return new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , disable + "" + reason , null ) ; } private String createBlameMessage ( ) { Object [ ] args = { getName ( ) , getId ( ) } ; String disable = Messages . format ( RubyTextMessages . ProposalSorterHandle_blame , args ) ; return disable ; } public String getErrorMessage ( ) { return null ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IProblemRequestorExtension { void setProgressMonitor ( IProgressMonitor monitor ) ; void setIsActive ( boolean isActive ) ; void beginReportingSequence ( ) ; void endReportingSequence ( ) ; void setIsHandlingTemporaryProblems ( boolean enable ) ; } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . contentassist . ContentAssistant ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; public class RubyCompletionProcessor extends ContentAssistProcessor { protected final IEditorPart fEditor ; public RubyCompletionProcessor ( IEditorPart editor , ContentAssistant assistant , String partition ) { super ( assistant , partition ) ; fEditor = editor ; } protected ContentAssistInvocationContext createContext ( ITextViewer viewer , int offset ) { return new RubyContentAssistInvocationContext ( viewer , offset , fEditor ) ; } protected List filterAndSortProposals ( List proposals , IProgressMonitor monitor , ContentAssistInvocationContext context ) { ProposalSorterRegistry . getDefault ( ) . getCurrentSorter ( ) . sortProposals ( context , proposals ) ; return proposals ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . StringTokenizer ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . rules . ICharacterScanner ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . IWordDetector ; import org . eclipse . jface . text . rules . Token ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . text . IRubyColorConstants ; import org . rubypeople . rdt . internal . ui . text . ruby . CombinedWordRule . WordMatcher ; import org . rubypeople . rdt . ui . text . IColorManager ; public class RubyCommentScanner extends AbstractRubyScanner { private static class AtRubyIdentifierDetector implements IWordDetector { public boolean isWordStart ( char c ) { return c == '' || Character . isJavaIdentifierStart ( c ) ; } public boolean isWordPart ( char c ) { return Character . isJavaIdentifierPart ( c ) ; } } private class TaskTagMatcher extends CombinedWordRule . WordMatcher { private IToken fToken ; private Map fUppercaseWords = new HashMap ( ) ; private boolean fCaseSensitive = true ; private CombinedWordRule . CharacterBuffer fBuffer = new CombinedWordRule . CharacterBuffer ( ) ; public TaskTagMatcher ( IToken token ) { fToken = token ; } public synchronized void clearWords ( ) { super . clearWords ( ) ; fUppercaseWords . clear ( ) ; } public synchronized void addTaskTags ( String value ) { String [ ] tasks = split ( value , "" ) ; for ( int i = ; i < tasks . length ; i ++ ) { if ( tasks [ i ] . length ( ) > ) { addWord ( tasks [ i ] , fToken ) ; } } } private String [ ] split ( String value , String delimiters ) { StringTokenizer tokenizer = new StringTokenizer ( value , delimiters ) ; int size = tokenizer . countTokens ( ) ; String [ ] tokens = new String [ size ] ; int i = ; while ( i < size ) tokens [ i ++ ] = tokenizer . nextToken ( ) ; return tokens ; } public synchronized void addWord ( String word , IToken token ) { Assert . isNotNull ( word ) ; Assert . isNotNull ( token ) ; super . addWord ( word , token ) ; fUppercaseWords . put ( new CombinedWordRule . CharacterBuffer ( word . toUpperCase ( ) ) , token ) ; } public synchronized IToken evaluate ( ICharacterScanner scanner , CombinedWordRule . CharacterBuffer word ) { if ( fCaseSensitive ) return super . evaluate ( scanner , word ) ; fBuffer . clear ( ) ; for ( int i = , n = word . length ( ) ; i < n ; i ++ ) fBuffer . append ( Character . toUpperCase ( word . charAt ( i ) ) ) ; IToken token = ( IToken ) fUppercaseWords . get ( fBuffer ) ; if ( token != null ) return token ; return Token . UNDEFINED ; } public boolean isCaseSensitive ( ) { return fCaseSensitive ; } public void setCaseSensitive ( boolean caseSensitive ) { fCaseSensitive = caseSensitive ; } } private static final String COMPILER_TASK_TAGS = RubyCore . COMPILER_TASK_TAGS ; protected static final String TASK_TAG = IRubyColorConstants . TASK_TAG ; private static final String COMPILER_TASK_CASE_SENSITIVE = RubyCore . COMPILER_TASK_CASE_SENSITIVE ; private static final String ENABLED = RubyCore . ENABLED ; private Preferences fCorePreferenceStore ; private String fDefaultTokenProperty ; private String [ ] fTokenProperties ; private TaskTagMatcher fTaskTagMatcher ; public RubyCommentScanner ( IColorManager manager , IPreferenceStore store , Preferences coreStore , String defaultTokenProperty ) { this ( manager , store , coreStore , defaultTokenProperty , new String [ ] { defaultTokenProperty , TASK_TAG } ) ; } public RubyCommentScanner ( IColorManager manager , IPreferenceStore store , Preferences coreStore , String defaultTokenProperty , String [ ] tokenProperties ) { super ( manager , store ) ; fCorePreferenceStore = coreStore ; fDefaultTokenProperty = defaultTokenProperty ; fTokenProperties = tokenProperties ; initialize ( ) ; } public RubyCommentScanner ( IColorManager manager , IPreferenceStore store , String defaultTokenProperty ) { this ( manager , store , null , defaultTokenProperty , new String [ ] { defaultTokenProperty , TASK_TAG } ) ; } public boolean affectsBehavior ( PropertyChangeEvent event ) { return event . getProperty ( ) . equals ( COMPILER_TASK_TAGS ) || event . getProperty ( ) . equals ( COMPILER_TASK_CASE_SENSITIVE ) || super . affectsBehavior ( event ) ; } public void adaptToPreferenceChange ( PropertyChangeEvent event ) { if ( fTaskTagMatcher != null && event . getProperty ( ) . equals ( COMPILER_TASK_TAGS ) ) { Object value = event . getNewValue ( ) ; if ( value instanceof String ) { synchronized ( fTaskTagMatcher ) { fTaskTagMatcher . clearWords ( ) ; fTaskTagMatcher . addTaskTags ( ( String ) value ) ; } } } else if ( fTaskTagMatcher != null && event . getProperty ( ) . equals ( COMPILER_TASK_CASE_SENSITIVE ) ) { Object value = event . getNewValue ( ) ; if ( value instanceof String ) fTaskTagMatcher . setCaseSensitive ( ENABLED . equals ( value ) ) ; } else if ( super . affectsBehavior ( event ) ) super . adaptToPreferenceChange ( event ) ; } protected String [ ] getTokenProperties ( ) { return fTokenProperties ; } protected List createRules ( ) { List list = new ArrayList ( ) ; Token defaultToken = getToken ( fDefaultTokenProperty ) ; List matchers = createMatchers ( ) ; if ( matchers . size ( ) > ) { CombinedWordRule combinedWordRule = new CombinedWordRule ( new AtRubyIdentifierDetector ( ) , defaultToken ) ; for ( int i = , n = matchers . size ( ) ; i < n ; i ++ ) combinedWordRule . addWordMatcher ( ( WordMatcher ) matchers . get ( i ) ) ; list . add ( combinedWordRule ) ; } setDefaultReturnToken ( defaultToken ) ; return list ; } protected List createMatchers ( ) { List list = new ArrayList ( ) ; boolean isCaseSensitive = true ; String tasks = null ; if ( getPreferenceStore ( ) . contains ( COMPILER_TASK_TAGS ) ) { tasks = getPreferenceStore ( ) . getString ( COMPILER_TASK_TAGS ) ; isCaseSensitive = ENABLED . equals ( getPreferenceStore ( ) . getString ( COMPILER_TASK_CASE_SENSITIVE ) ) ; } else if ( fCorePreferenceStore != null ) { tasks = fCorePreferenceStore . getString ( COMPILER_TASK_TAGS ) ; isCaseSensitive = ENABLED . equals ( fCorePreferenceStore . getString ( COMPILER_TASK_CASE_SENSITIVE ) ) ; } if ( tasks != null ) { fTaskTagMatcher = new TaskTagMatcher ( getToken ( TASK_TAG ) ) ; fTaskTagMatcher . addTaskTags ( tasks ) ; fTaskTagMatcher . setCaseSensitive ( isCaseSensitive ) ; list . add ( fTaskTagMatcher ) ; } return list ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . regex . Pattern ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultIndentLineAutoEditStrategy ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . corext . util . CodeFormatterUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . RubyHeuristicScanner ; import org . rubypeople . rdt . internal . ui . text . RubyIndenter ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy implements IPropertyChangeListener { private final static String END_STATEMENTS = PreferenceConstants . EDITOR_END_STATEMENTS ; private final Pattern openBlockPattern = Pattern . compile ( "" ) ; private static final String BLOCK_CLOSER = "" ; private String fPartitioning ; private final IRubyProject fProject ; private boolean endStatements ; private IPreferenceStore fPreferenceStore ; public RubyAutoIndentStrategy ( String partitioning , IRubyProject project ) { fPartitioning = partitioning ; fProject = project ; fPreferenceStore = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; endStatements = fPreferenceStore . getBoolean ( END_STATEMENTS ) ; fPreferenceStore . addPropertyChangeListener ( this ) ; } public void customizeDocumentCommand ( IDocument d , DocumentCommand c ) { if ( c . doit == false ) return ; if ( c . length == && c . text != null && isLineDelimiter ( d , c . text ) ) smartIndentAfterNewLine ( d , c ) ; } private boolean isLineDelimiter ( IDocument document , String text ) { String [ ] delimiters = document . getLegalLineDelimiters ( ) ; if ( delimiters != null ) return TextUtilities . equals ( delimiters , text ) > - ; return false ; } private void smartIndentAfterNewLine ( IDocument d , DocumentCommand c ) { RubyHeuristicScanner scanner = new RubyHeuristicScanner ( d ) ; RubyIndenter indenter = new RubyIndenter ( d , scanner , fProject ) ; StringBuffer indent = indenter . computeIndentation ( c . offset ) ; if ( indent == null ) indent = new StringBuffer ( ) ; int docLength = d . getLength ( ) ; if ( c . offset == - || docLength == ) return ; try { int p = ( c . offset == docLength ? c . offset - : c . offset ) ; int line = d . getLineOfOffset ( p ) ; StringBuffer buf = new StringBuffer ( c . text + indent ) ; IRegion currentLineRegion = d . getLineInformation ( line ) ; int lineEnd = currentLineRegion . getOffset ( ) + currentLineRegion . getLength ( ) ; int contentStart = findEndOfWhiteSpace ( d , c . offset , lineEnd ) ; c . length = Math . max ( contentStart - c . offset , ) ; int startOfCurrentLine = currentLineRegion . getOffset ( ) ; String trimmed = getTrimmedLine ( d , startOfCurrentLine , c . offset ) ; if ( mightHaveToShiftCurrentLine ( trimmed ) ) { IRegion previousLineRegion = d . getLineInformation ( line - ) ; String previousLine = getTrimmedLine ( d , previousLineRegion . getOffset ( ) , previousLineRegion . getOffset ( ) + previousLineRegion . getLength ( ) ) ; String previousIndent = indenter . computeIndentation ( previousLineRegion . getOffset ( ) ) . toString ( ) ; String unindented = "" ; if ( middleOfBlockRightAfterBeginning ( trimmed , previousLine ) ) { unindented = previousIndent ; if ( whenAfterCase ( trimmed , previousLine ) ) { if ( RubyCore . getPlugin ( ) . getPluginPreferences ( ) . getBoolean ( DefaultCodeFormatterConstants . FORMATTER_INDENT_CASE_BODY ) ) { unindented += CodeFormatterUtil . createIndentString ( , fProject ) ; } } } else { int length = previousIndent . length ( ) - CodeFormatterUtil . createIndentString ( , fProject ) . length ( ) ; int nextCalculated = nextMeaningfulIndentLength ( d , indenter , line ) ; int unit = CodeFormatterUtil . createIndentString ( , fProject ) . length ( ) ; if ( nextCalculated != - && ( length > ( nextCalculated + unit ) ) ) { unindented = previousIndent . substring ( , length - unit ) ; } else if ( length <= ) { unindented = "" ; } else { unindented = previousIndent . substring ( , length ) ; } } if ( unindented . length ( ) < indent . length ( ) ) { d . replace ( startOfCurrentLine , c . offset - startOfCurrentLine , unindented + trimmed ) ; int shift = indent . length ( ) - unindented . length ( ) ; c . offset = c . offset - shift ; buf . delete ( buf . length ( ) - shift , buf . length ( ) ) ; } } if ( atIndentPoint ( trimmed ) ) { buf . append ( CodeFormatterUtil . createIndentString ( , fProject ) ) ; c . caretOffset = c . offset + buf . length ( ) ; c . shiftsCaret = false ; } if ( trimmed . equals ( "" ) ) { buf . append ( CodeFormatterUtil . createIndentString ( , fProject ) ) ; c . caretOffset = c . offset + buf . length ( ) ; c . shiftsCaret = false ; buf . append ( TextUtilities . getDefaultLineDelimiter ( d ) ) ; buf . append ( "" ) ; } if ( closeBlock ( ) && unclosedBlock ( d , trimmed , c . offset ) ) { if ( lineEnd - contentStart > ) { c . length = lineEnd - c . offset ; buf . append ( d . get ( contentStart , lineEnd - contentStart ) . toCharArray ( ) ) ; } buf . append ( TextUtilities . getDefaultLineDelimiter ( d ) ) ; buf . append ( indent ) ; buf . append ( BLOCK_CLOSER ) ; } c . text = buf . toString ( ) ; } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; } } private int nextMeaningfulIndentLength ( IDocument d , RubyIndenter indenter , int line ) throws BadLocationException { for ( int i = line + ; i < d . getNumberOfLines ( ) ; i ++ ) { IRegion nextLineRegion = d . getLineInformation ( i ) ; String trimmed = getTrimmedLine ( d , nextLineRegion . getOffset ( ) , nextLineRegion . getOffset ( ) + nextLineRegion . getLength ( ) ) ; if ( trimmed == null || trimmed . length ( ) == ) continue ; String nextIndent = indenter . computeIndentation ( nextLineRegion . getOffset ( ) ) . toString ( ) ; return nextIndent . length ( ) ; } return - ; } private boolean middleOfBlockRightAfterBeginning ( String trimmed , String previousLine ) { return middleOfIfRightAfterBeginning ( trimmed , previousLine ) || middleOfBeginRightAfterBeginning ( trimmed , previousLine ) || elseRightAfterElsif ( trimmed , previousLine ) || ensureRightAfterRescue ( trimmed , previousLine ) || whenAfterCase ( trimmed , previousLine ) || elsifRightAfterElsif ( trimmed , previousLine ) ; } private boolean middleOfBeginRightAfterBeginning ( String trimmed , String previousLine ) { return previousLine . equals ( "" ) && ( trimmed . startsWith ( "" ) || trimmed . equals ( "" ) || trimmed . equals ( "" ) ) ; } private boolean middleOfIfRightAfterBeginning ( String trimmed , String previousLine ) { return previousLine . startsWith ( "" ) && ( trimmed . startsWith ( "" ) || trimmed . equals ( "" ) ) ; } private boolean ensureRightAfterRescue ( String trimmed , String previousLine ) { return ( previousLine . startsWith ( "" ) || previousLine . equals ( "" ) ) && trimmed . equals ( "" ) ; } private boolean elseRightAfterElsif ( String trimmed , String previousLine ) { return previousLine . startsWith ( "" ) && trimmed . equals ( "" ) ; } private boolean elsifRightAfterElsif ( String trimmed , String previousLine ) { return previousLine . startsWith ( "" ) && trimmed . startsWith ( "" ) ; } private boolean whenAfterCase ( String trimmed , String previousLine ) { return previousLine . startsWith ( "" ) && trimmed . startsWith ( "" ) ; } private boolean atIndentPoint ( String trimmed ) { if ( trimmed == null || trimmed . length ( ) == ) return false ; return atStartOfBlock ( trimmed ) || isMiddleOfBlockKeyword ( trimmed ) ; } private boolean isMiddleOfBlockKeyword ( String trimmed ) { if ( trimmed == null || trimmed . length ( ) == ) return false ; return trimmed . equals ( "" ) || trimmed . equals ( "" ) || trimmed . equals ( "" ) || trimmed . startsWith ( "" ) || trimmed . startsWith ( "" ) || trimmed . startsWith ( "" ) ; } private boolean mightHaveToShiftCurrentLine ( String trimmed ) { if ( trimmed == null || trimmed . length ( ) == ) return false ; return isMiddleOfBlockKeyword ( trimmed ) || trimmed . equals ( BLOCK_CLOSER ) ; } private boolean unclosedBlock ( IDocument d , String trimmed , int offset ) { if ( ! atStartOfBlock ( trimmed ) ) { return false ; } RubyParser parser = new RubyParser ( ) ; try { parser . parse ( d . get ( ) ) ; } catch ( SyntaxException e ) { String msg = e . getMessage ( ) ; if ( msg . contains ( "" ) && ( msg . contains ( "" ) || msg . contains ( "" ) ) ) return true ; try { StringBuffer buffer = new StringBuffer ( d . get ( ) ) ; buffer . insert ( offset , TextUtilities . getDefaultLineDelimiter ( d ) + BLOCK_CLOSER ) ; parser . parse ( buffer . toString ( ) ) ; } catch ( SyntaxException syntaxException ) { return false ; } return true ; } return false ; } private String getTrimmedLine ( IDocument d , int start , int offset ) throws BadLocationException { String line = d . get ( start , offset - start ) ; return line . trim ( ) ; } private boolean atStartOfBlock ( String line ) { return line . startsWith ( "" ) || line . startsWith ( "" ) || line . startsWith ( "" ) || line . startsWith ( "" ) || line . startsWith ( "" ) || line . equals ( "" ) || line . startsWith ( "" ) || line . startsWith ( "" ) || openBlockPattern . matcher ( line ) . matches ( ) ; } private boolean closeBlock ( ) { return endStatements ; } public void propertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( END_STATEMENTS . equals ( property ) ) { endStatements = fPreferenceStore . getBoolean ( property ) ; return ; } } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . List ; import org . eclipse . jface . preference . IPreferenceStore ; import org . rubypeople . rdt . ui . text . IColorManager ; public class SingleTokenRubyScanner extends AbstractRubyScanner { private String [ ] fProperty ; public SingleTokenRubyScanner ( IColorManager manager , IPreferenceStore store , String property ) { super ( manager , store ) ; fProperty = new String [ ] { property } ; initialize ( ) ; } protected String [ ] getTokenProperties ( ) { return fProperty ; } protected List createRules ( ) { setDefaultReturnToken ( getToken ( fProperty [ ] ) ) ; return null ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; public class RubyContentAssistInvocationContext extends ContentAssistInvocationContext { private final IEditorPart fEditor ; private IRubyScript fCU = null ; private boolean fCUComputed = false ; private CompletionProposalLabelProvider fLabelProvider ; public RubyContentAssistInvocationContext ( ITextViewer viewer , int offset , IEditorPart editor ) { super ( viewer , offset ) ; Assert . isNotNull ( editor ) ; fEditor = editor ; } public RubyContentAssistInvocationContext ( IRubyScript unit ) { super ( ) ; fCU = unit ; fCUComputed = true ; fEditor = null ; } public IRubyScript getRubyScript ( ) { if ( ! fCUComputed ) { fCUComputed = true ; IRubyElement re = EditorUtility . getEditorInputRubyElement ( fEditor , false ) ; if ( re instanceof IRubyScript ) fCU = ( IRubyScript ) re ; } return fCU ; } public IRubyProject getProject ( ) { IRubyScript unit = getRubyScript ( ) ; return unit == null ? null : unit . getRubyProject ( ) ; } public CompletionProposalLabelProvider getLabelProvider ( ) { if ( fLabelProvider == null ) { fLabelProvider = new CompletionProposalLabelProvider ( ) ; } return fLabelProvider ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . core . commands . AbstractHandler ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . rubyeditor . SpecificContentAssistExecutor ; public final class RubyContentAssistHandler extends AbstractHandler { private final SpecificContentAssistExecutor fExecutor = new SpecificContentAssistExecutor ( CompletionProposalComputerRegistry . getDefault ( ) ) ; public RubyContentAssistHandler ( ) { } public Object execute ( ExecutionEvent event ) throws ExecutionException { ITextEditor editor = getActiveEditor ( ) ; if ( editor == null ) return null ; String categoryId = event . getParameter ( "" ) ; if ( categoryId == null ) return null ; fExecutor . invokeContentAssist ( editor , categoryId ) ; return null ; } private ITextEditor getActiveEditor ( ) { IWorkbenchWindow window = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; if ( window != null ) { IWorkbenchPage page = window . getActivePage ( ) ; if ( page != null ) { IEditorPart editor = page . getActiveEditor ( ) ; if ( editor instanceof ITextEditor ) return ( RubyEditor ) editor ; } } return null ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . action . LegacyActionTools ; import org . eclipse . jface . bindings . TriggerSequence ; import org . eclipse . jface . bindings . keys . KeySequence ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . contentassist . ContentAssistEvent ; import org . eclipse . jface . text . contentassist . ContentAssistant ; import org . eclipse . jface . text . contentassist . ICompletionListener ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . IContentAssistProcessor ; import org . eclipse . jface . text . contentassist . IContentAssistantExtension2 ; import org . eclipse . jface . text . contentassist . IContentAssistantExtension3 ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . contentassist . IContextInformationValidator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Link ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . eclipse . ui . keys . IBindingService ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . dialogs . OptionalMessageDialog ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; public class ContentAssistProcessor implements IContentAssistProcessor { private static final boolean DEBUG = "" . equalsIgnoreCase ( Platform . getDebugOption ( "" ) ) ; private static final String PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY = "" ; private static final Comparator ORDER_COMPARATOR = new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { CompletionProposalCategory d1 = ( CompletionProposalCategory ) o1 ; CompletionProposalCategory d2 = ( CompletionProposalCategory ) o2 ; return d1 . getSortOrder ( ) - d2 . getSortOrder ( ) ; } } ; private final List fCategories ; private final String fPartition ; private final ContentAssistant fAssistant ; private char [ ] fCompletionAutoActivationCharacters ; private int fRepetition = - ; private List < List < CompletionProposalCategory > > fCategoryIteration = null ; private String fIterationGesture = null ; private int fNumberOfComputedResults = ; private String fErrorMessage ; public ContentAssistProcessor ( ContentAssistant assistant , String partition ) { Assert . isNotNull ( partition ) ; Assert . isNotNull ( assistant ) ; fPartition = partition ; fCategories = CompletionProposalComputerRegistry . getDefault ( ) . getProposalCategories ( ) ; fAssistant = assistant ; fAssistant . addCompletionListener ( new ICompletionListener ( ) { public void assistSessionStarted ( ContentAssistEvent event ) { if ( event . processor != ContentAssistProcessor . this ) return ; fIterationGesture = getIterationGesture ( ) ; KeySequence binding = getIterationBinding ( ) ; fCategoryIteration = getCategoryIteration ( ) ; for ( Iterator it = fCategories . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalCategory cat = ( CompletionProposalCategory ) it . next ( ) ; cat . sessionStarted ( ) ; } fRepetition = ; if ( event . assistant instanceof IContentAssistantExtension2 ) { IContentAssistantExtension2 extension = ( IContentAssistantExtension2 ) event . assistant ; if ( fCategoryIteration . size ( ) == ) { extension . setRepeatedInvocationMode ( false ) ; extension . setShowEmptyList ( false ) ; } else { extension . setRepeatedInvocationMode ( true ) ; extension . setStatusLineVisible ( true ) ; extension . setStatusMessage ( createIterationMessage ( ) ) ; extension . setShowEmptyList ( true ) ; if ( extension instanceof IContentAssistantExtension3 ) { IContentAssistantExtension3 ext3 = ( IContentAssistantExtension3 ) extension ; ( ( ContentAssistant ) ext3 ) . setRepeatedInvocationTrigger ( binding ) ; } } } } public void assistSessionEnded ( ContentAssistEvent event ) { if ( event . processor != ContentAssistProcessor . this ) return ; for ( Iterator it = fCategories . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalCategory cat = ( CompletionProposalCategory ) it . next ( ) ; cat . sessionEnded ( ) ; } fCategoryIteration = null ; fRepetition = - ; fIterationGesture = null ; if ( event . assistant instanceof IContentAssistantExtension2 ) { IContentAssistantExtension2 extension = ( IContentAssistantExtension2 ) event . assistant ; extension . setShowEmptyList ( false ) ; extension . setRepeatedInvocationMode ( false ) ; extension . setStatusLineVisible ( false ) ; if ( extension instanceof IContentAssistantExtension3 ) { IContentAssistantExtension3 ext3 = ( IContentAssistantExtension3 ) extension ; ( ( ContentAssistant ) ext3 ) . setRepeatedInvocationTrigger ( null ) ; } } } public void selectionChanged ( ICompletionProposal proposal , boolean smartToggle ) { } } ) ; } public final ICompletionProposal [ ] computeCompletionProposals ( ITextViewer viewer , int offset ) { long start = DEBUG ? System . currentTimeMillis ( ) : ; clearState ( ) ; IProgressMonitor monitor = createProgressMonitor ( ) ; monitor . beginTask ( RubyTextMessages . ContentAssistProcessor_computing_proposals , fCategories . size ( ) + ) ; ContentAssistInvocationContext context = createContext ( viewer , offset ) ; long setup = DEBUG ? System . currentTimeMillis ( ) : ; monitor . subTask ( RubyTextMessages . ContentAssistProcessor_collecting_proposals ) ; List proposals = collectProposals ( viewer , offset , monitor , context ) ; long collect = DEBUG ? System . currentTimeMillis ( ) : ; monitor . subTask ( RubyTextMessages . ContentAssistProcessor_sorting_proposals ) ; List filtered = filterAndSortProposals ( proposals , monitor , context ) ; fNumberOfComputedResults = filtered . size ( ) ; long filter = DEBUG ? System . currentTimeMillis ( ) : ; ICompletionProposal [ ] result = ( ICompletionProposal [ ] ) filtered . toArray ( new ICompletionProposal [ filtered . size ( ) ] ) ; monitor . done ( ) ; if ( DEBUG ) { System . err . println ( "" + result . length + "" ) ; System . err . println ( "" + ( setup - start ) ) ; System . err . println ( "" + ( collect - setup ) ) ; System . err . println ( "" + ( filter - collect ) ) ; } return result ; } private void clearState ( ) { fErrorMessage = null ; fNumberOfComputedResults = ; } private List collectProposals ( ITextViewer viewer , int offset , IProgressMonitor monitor , ContentAssistInvocationContext context ) { List proposals = new ArrayList ( ) ; List < CompletionProposalCategory > providers = getCategories ( ) ; for ( CompletionProposalCategory cat : providers ) { List computed = cat . computeCompletionProposals ( context , fPartition , new SubProgressMonitor ( monitor , ) ) ; proposals . addAll ( computed ) ; if ( fErrorMessage == null ) fErrorMessage = cat . getErrorMessage ( ) ; } return proposals ; } protected List filterAndSortProposals ( List proposals , IProgressMonitor monitor , ContentAssistInvocationContext context ) { return proposals ; } public IContextInformation [ ] computeContextInformation ( ITextViewer viewer , int offset ) { clearState ( ) ; IProgressMonitor monitor = createProgressMonitor ( ) ; monitor . beginTask ( RubyTextMessages . ContentAssistProcessor_computing_contexts , fCategories . size ( ) + ) ; monitor . subTask ( RubyTextMessages . ContentAssistProcessor_collecting_contexts ) ; List proposals = collectContextInformation ( viewer , offset , monitor ) ; monitor . subTask ( RubyTextMessages . ContentAssistProcessor_sorting_contexts ) ; List filtered = filterAndSortContextInformation ( proposals , monitor ) ; fNumberOfComputedResults = filtered . size ( ) ; IContextInformation [ ] result = ( IContextInformation [ ] ) filtered . toArray ( new IContextInformation [ filtered . size ( ) ] ) ; monitor . done ( ) ; return result ; } private List collectContextInformation ( ITextViewer viewer , int offset , IProgressMonitor monitor ) { List proposals = new ArrayList ( ) ; ContentAssistInvocationContext context = createContext ( viewer , offset ) ; List providers = getCategories ( ) ; for ( Iterator it = providers . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalCategory cat = ( CompletionProposalCategory ) it . next ( ) ; List computed = cat . computeContextInformation ( context , fPartition , new SubProgressMonitor ( monitor , ) ) ; proposals . addAll ( computed ) ; if ( fErrorMessage == null ) fErrorMessage = cat . getErrorMessage ( ) ; } return proposals ; } protected List filterAndSortContextInformation ( List contexts , IProgressMonitor monitor ) { return contexts ; } public final void setCompletionProposalAutoActivationCharacters ( char [ ] activationSet ) { fCompletionAutoActivationCharacters = activationSet ; } public final char [ ] getCompletionProposalAutoActivationCharacters ( ) { return fCompletionAutoActivationCharacters ; } public char [ ] getContextInformationAutoActivationCharacters ( ) { return null ; } public String getErrorMessage ( ) { if ( fNumberOfComputedResults > ) return null ; if ( fErrorMessage != null ) return fErrorMessage ; return RubyUIMessages . RubyEditor_codeassist_noCompletions ; } public IContextInformationValidator getContextInformationValidator ( ) { return null ; } protected IProgressMonitor createProgressMonitor ( ) { return new NullProgressMonitor ( ) ; } protected ContentAssistInvocationContext createContext ( ITextViewer viewer , int offset ) { return new ContentAssistInvocationContext ( viewer , offset ) ; } private List getCategories ( ) { if ( fCategoryIteration == null ) return fCategories ; int iteration = fRepetition % fCategoryIteration . size ( ) ; fAssistant . setStatusMessage ( createIterationMessage ( ) ) ; fAssistant . setEmptyMessage ( createEmptyMessage ( ) ) ; fRepetition ++ ; return ( List < CompletionProposalCategory > ) fCategoryIteration . get ( iteration ) ; } private List getCategoryIteration ( ) { List sequence = new ArrayList ( ) ; sequence . add ( getDefaultCategories ( ) ) ; for ( Iterator it = getSeparateCategories ( ) . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalCategory cat = ( CompletionProposalCategory ) it . next ( ) ; sequence . add ( Collections . singletonList ( cat ) ) ; } return sequence ; } private List getDefaultCategories ( ) { List included = getDefaultCategoriesUnchecked ( ) ; if ( IDocument . DEFAULT_CONTENT_TYPE . equals ( fPartition ) && included . isEmpty ( ) && ! fCategories . isEmpty ( ) ) if ( informUserAboutEmptyDefaultCategory ( ) ) included = getDefaultCategoriesUnchecked ( ) ; return included ; } private List getDefaultCategoriesUnchecked ( ) { List included = new ArrayList ( ) ; for ( Iterator it = fCategories . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalCategory category = ( CompletionProposalCategory ) it . next ( ) ; if ( category . isIncluded ( ) && category . hasComputers ( fPartition ) ) included . add ( category ) ; } return included ; } private boolean informUserAboutEmptyDefaultCategory ( ) { if ( OptionalMessageDialog . isDialogEnabled ( PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY ) ) { final Shell shell = RubyPlugin . getActiveWorkbenchShell ( ) ; String title = RubyTextMessages . ContentAssistProcessor_all_disabled_title ; String message = RubyTextMessages . ContentAssistProcessor_all_disabled_message ; final String restoreButtonLabel = JFaceResources . getString ( "" ) ; final String linkMessage = Messages . format ( RubyTextMessages . ContentAssistProcessor_all_disabled_preference_link , LegacyActionTools . removeMnemonics ( restoreButtonLabel ) ) ; final int restoreId = IDialogConstants . CLIENT_ID + ; final OptionalMessageDialog dialog = new OptionalMessageDialog ( PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY , shell , title , null , message , MessageDialog . WARNING , new String [ ] { restoreButtonLabel , IDialogConstants . CLOSE_LABEL } , ) { protected Control createCustomArea ( Composite composite ) { Composite parent = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . verticalSpacing = ; parent . setLayout ( layout ) ; Composite linkComposite = new Composite ( parent , SWT . NONE ) ; layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; linkComposite . setLayout ( layout ) ; Link link = new Link ( linkComposite , SWT . NONE ) ; link . setText ( linkMessage ) ; link . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { close ( ) ; PreferencesUtil . createPreferenceDialogOn ( shell , "" , null , null ) . open ( ) ; } } ) ; GridData gridData = new GridData ( SWT . FILL , SWT . BEGINNING , true , false ) ; gridData . widthHint = this . getMinimumMessageWidth ( ) ; link . setLayoutData ( gridData ) ; super . createCustomArea ( parent ) ; return parent ; } protected void createButtonsForButtonBar ( Composite parent ) { Button [ ] buttons = new Button [ ] ; buttons [ ] = createButton ( parent , restoreId , restoreButtonLabel , false ) ; buttons [ ] = createButton ( parent , IDialogConstants . CLOSE_ID , IDialogConstants . CLOSE_LABEL , true ) ; setButtons ( buttons ) ; } } ; if ( restoreId == dialog . open ( ) ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; store . setToDefault ( PreferenceConstants . CODEASSIST_CATEGORY_ORDER ) ; store . setToDefault ( PreferenceConstants . CODEASSIST_EXCLUDED_CATEGORIES ) ; CompletionProposalComputerRegistry registry = CompletionProposalComputerRegistry . getDefault ( ) ; registry . reload ( ) ; return true ; } } return false ; } private List getSeparateCategories ( ) { ArrayList sorted = new ArrayList ( ) ; for ( Iterator it = fCategories . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalCategory category = ( CompletionProposalCategory ) it . next ( ) ; if ( category . isSeparateCommand ( ) && category . hasComputers ( fPartition ) ) sorted . add ( category ) ; } Collections . sort ( sorted , ORDER_COMPARATOR ) ; return sorted ; } private String createEmptyMessage ( ) { return Messages . format ( RubyTextMessages . ContentAssistProcessor_empty_message , new String [ ] { getCategoryLabel ( fRepetition ) } ) ; } private String createIterationMessage ( ) { return Messages . format ( RubyTextMessages . ContentAssistProcessor_toggle_affordance_update_message , new String [ ] { getCategoryLabel ( fRepetition ) , fIterationGesture , getCategoryLabel ( fRepetition + ) } ) ; } private String getCategoryLabel ( int repetition ) { int iteration = repetition % fCategoryIteration . size ( ) ; if ( iteration == ) return RubyTextMessages . ContentAssistProcessor_defaultProposalCategory ; return toString ( ( CompletionProposalCategory ) ( ( List ) fCategoryIteration . get ( iteration ) ) . get ( ) ) ; } private String toString ( CompletionProposalCategory category ) { return category . getDisplayName ( ) ; } private String getIterationGesture ( ) { TriggerSequence binding = getIterationBinding ( ) ; return binding != null ? Messages . format ( RubyTextMessages . ContentAssistProcessor_toggle_affordance_press_gesture , new Object [ ] { binding . format ( ) } ) : RubyTextMessages . ContentAssistProcessor_toggle_affordance_click_gesture ; } private KeySequence getIterationBinding ( ) { final IBindingService bindingSvc = ( IBindingService ) PlatformUI . getWorkbench ( ) . getAdapter ( IBindingService . class ) ; TriggerSequence binding = bindingSvc . getBestActiveBindingFor ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS ) ; if ( binding instanceof KeySequence ) return ( KeySequence ) binding ; return null ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . osgi . util . NLS ; final class RubyTextMessages extends NLS { private static final String BUNDLE_NAME = RubyTextMessages . class . getName ( ) ; private RubyTextMessages ( ) { } public static String CompletionProcessor_error_accessing_title ; public static String CompletionProcessor_error_accessing_message ; public static String CompletionProcessor_error_notOnBuildPath_title ; public static String CompletionProcessor_error_notOnBuildPath_message ; public static String CompletionProposalComputerRegistry_messageAvoidanceHint ; public static String CompletionProposalComputerRegistry_messageAvoidanceHintWithWarning ; public static String ContentAssistProcessor_all_disabled_message ; public static String ContentAssistProcessor_all_disabled_preference_link ; public static String ContentAssistProcessor_all_disabled_title ; public static String ExperimentalProposal_error_msg ; public static String ParameterGuessingProposal_error_msg ; public static String ProposalInfo_more_to_come ; public static String GetterSetterCompletionProposal_getter_label ; public static String GetterSetterCompletionProposal_setter_label ; public static String MethodCompletionProposal_constructor_label ; public static String MethodCompletionProposal_method_label ; static { NLS . initializeMessages ( BUNDLE_NAME , RubyTextMessages . class ) ; } public static String ContentAssistProcessor_computing_proposals ; public static String ContentAssistProcessor_collecting_proposals ; public static String ContentAssistProcessor_sorting_proposals ; public static String ContentAssistProcessor_computing_contexts ; public static String ContentAssistProcessor_collecting_contexts ; public static String ContentAssistProcessor_sorting_contexts ; public static String CompletionProposalComputerDescriptor_illegal_attribute_message ; public static String CompletionProposalComputerDescriptor_reason_invalid ; public static String CompletionProposalComputerDescriptor_reason_instantiation ; public static String CompletionProposalComputerDescriptor_reason_runtime_ex ; public static String CompletionProposalComputerDescriptor_reason_API ; public static String CompletionProposalComputerDescriptor_reason_performance ; public static String CompletionProposalComputerDescriptor_blame_message ; public static String CompletionProposalComputerRegistry_invalid_message ; public static String CompletionProposalComputerRegistry_error_dialog_title ; public static String ContentAssistProcessor_defaultProposalCategory ; public static String ContentAssistProcessor_toggle_affordance_press_gesture ; public static String ContentAssistProcessor_toggle_affordance_click_gesture ; public static String ContentAssistProcessor_toggle_affordance_update_message ; public static String ContentAssistProcessor_empty_message ; public static String ContentAssistHistory_serialize_error ; public static String ContentAssistHistory_deserialize_error ; public static String ProposalSorterHandle_blame ; } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . rubypeople . rdt . ui . text . ruby . AbstractProposalSorter ; import org . rubypeople . rdt . ui . text . ruby . CompletionProposalComparator ; public final class AlphabeticSorter extends AbstractProposalSorter { private final CompletionProposalComparator fComparator = new CompletionProposalComparator ( ) ; public AlphabeticSorter ( ) { fComparator . setOrderAlphabetically ( true ) ; } public int compare ( ICompletionProposal p1 , ICompletionProposal p2 ) { return fComparator . compare ( p1 , p2 ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . contentassist . IContextInformationExtension ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public final class ProposalContextInformation implements IContextInformation , IContextInformationExtension { private final String fContextDisplayString ; private final String fInformationDisplayString ; private final Image fImage ; private int fPosition ; public ProposalContextInformation ( CompletionProposal proposal ) { CompletionProposalLabelProvider labelProvider = new CompletionProposalLabelProvider ( ) ; fInformationDisplayString = labelProvider . createParameterList ( proposal ) ; ImageDescriptor descriptor = labelProvider . createImageDescriptor ( proposal ) ; if ( descriptor != null ) fImage = RubyPlugin . getImageDescriptorRegistry ( ) . get ( descriptor ) ; else fImage = null ; if ( proposal . getCompletion ( ) . length ( ) == ) fPosition = proposal . getCompletionLocation ( ) + ; else fPosition = - ; fContextDisplayString = labelProvider . createLabel ( proposal ) ; } public boolean equals ( Object object ) { if ( object instanceof IContextInformation ) { IContextInformation contextInformation = ( IContextInformation ) object ; boolean equals = getInformationDisplayString ( ) . equalsIgnoreCase ( contextInformation . getInformationDisplayString ( ) ) ; if ( getContextDisplayString ( ) != null ) equals = equals && getContextDisplayString ( ) . equalsIgnoreCase ( contextInformation . getContextDisplayString ( ) ) ; return equals ; } return false ; } public String getInformationDisplayString ( ) { return fInformationDisplayString ; } public Image getImage ( ) { return fImage ; } public String getContextDisplayString ( ) { return fContextDisplayString ; } public int getContextInformationPosition ( ) { return fPosition ; } public void setContextInformationPosition ( int position ) { fPosition = position ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . ITokenScanner ; import org . eclipse . jface . text . rules . Token ; import org . jruby . parser . Tokens ; import org . rubypeople . rdt . internal . ui . text . IRubyColorConstants ; import org . rubypeople . rdt . ui . text . IColorManager ; public class RubyColoringTokenScanner extends AbstractRubyTokenScanner { private static String [ ] fgTokenProperties = { IRubyColorConstants . RUBY_KEYWORD , IRubyColorConstants . RUBY_DEFAULT , IRubyColorConstants . RUBY_FIXNUM , IRubyColorConstants . RUBY_CHARACTER , IRubyColorConstants . RUBY_SYMBOL , IRubyColorConstants . RUBY_CLASS_VARIABLE , IRubyColorConstants . RUBY_INSTANCE_VARIABLE , IRubyColorConstants . RUBY_GLOBAL , IRubyColorConstants . RUBY_ERROR } ; private ITokenScanner fScanner ; public RubyColoringTokenScanner ( IColorManager manager , IPreferenceStore store ) { super ( manager , store ) ; fScanner = new RubyTokenScanner ( ) ; initialize ( ) ; } public int getTokenLength ( ) { return fScanner . getTokenLength ( ) ; } public int getTokenOffset ( ) { return fScanner . getTokenOffset ( ) ; } public IToken nextToken ( ) { IToken intToken = fScanner . nextToken ( ) ; if ( intToken == null || intToken . isEOF ( ) ) return Token . EOF ; Integer data = ( Integer ) intToken . getData ( ) ; if ( data == null ) return Token . EOF ; if ( isKeyword ( data . intValue ( ) ) ) { return getToken ( IRubyColorConstants . RUBY_KEYWORD ) ; } switch ( data . intValue ( ) ) { case RubyTokenScanner . CHARACTER : return getToken ( IRubyColorConstants . RUBY_CHARACTER ) ; case Tokens . tFLOAT : case Tokens . tINTEGER : return getToken ( IRubyColorConstants . RUBY_FIXNUM ) ; case Tokens . tSYMBEG : return getToken ( IRubyColorConstants . RUBY_SYMBOL ) ; case Tokens . tGVAR : return getToken ( IRubyColorConstants . RUBY_GLOBAL ) ; case Tokens . tIVAR : return getToken ( IRubyColorConstants . RUBY_INSTANCE_VARIABLE ) ; case Tokens . tCVAR : return getToken ( IRubyColorConstants . RUBY_CLASS_VARIABLE ) ; case Tokens . yyErrorCode : return getToken ( IRubyColorConstants . RUBY_ERROR ) ; default : return getToken ( IRubyColorConstants . RUBY_DEFAULT ) ; } } private boolean isKeyword ( int i ) { if ( i >= RubyTokenScanner . MIN_KEYWORD && i <= RubyTokenScanner . MAX_KEYWORD ) return true ; return false ; } public void setRange ( IDocument document , int offset , int length ) { fScanner . setRange ( document , offset , length ) ; } protected String [ ] getTokenProperties ( ) { return fgTokenProperties ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . Assert ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementImageDescriptor ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class CompletionProposalLabelProvider { public ImageDescriptor createImageDescriptor ( CompletionProposal proposal ) { final int flags = proposal . getFlags ( ) ; ImageDescriptor descriptor ; switch ( proposal . getKind ( ) ) { case CompletionProposal . METHOD_DECLARATION : case CompletionProposal . METHOD_NAME_REFERENCE : case CompletionProposal . METHOD_REF : case CompletionProposal . POTENTIAL_METHOD_DECLARATION : descriptor = RubyElementImageProvider . getMethodImageDescriptor ( flags ) ; break ; case CompletionProposal . TYPE_REF : descriptor = RubyElementImageProvider . getTypeImageDescriptor ( false , false , false ) ; break ; case CompletionProposal . CONSTANT_REF : descriptor = RubyElementImageProvider . getConstantImageDescriptor ( ) ; break ; case CompletionProposal . GLOBAL_REF : descriptor = RubyElementImageProvider . getGlobalVariableImageDescriptor ( ) ; break ; case CompletionProposal . INSTANCE_VARIABLE_REF : descriptor = RubyElementImageProvider . getInstanceVariableImageDescriptor ( ) ; break ; case CompletionProposal . CLASS_VARIABLE_REF : descriptor = RubyElementImageProvider . getClassVariableImageDescriptor ( ) ; break ; case CompletionProposal . LOCAL_VARIABLE_REF : case CompletionProposal . VARIABLE_DECLARATION : descriptor = RubyPluginImages . DESC_OBJS_LOCAL_VAR ; break ; case CompletionProposal . KEYWORD : descriptor = null ; break ; default : descriptor = null ; Assert . isTrue ( false ) ; } if ( descriptor == null ) return null ; return decorateImageDescriptor ( descriptor , proposal ) ; } private ImageDescriptor decorateImageDescriptor ( ImageDescriptor descriptor , CompletionProposal proposal ) { int adornments = ; int flags = proposal . getFlags ( ) ; int kind = proposal . getKind ( ) ; if ( kind == CompletionProposal . CONSTANT_REF || kind == CompletionProposal . METHOD_DECLARATION || kind == CompletionProposal . METHOD_DECLARATION || kind == CompletionProposal . METHOD_NAME_REFERENCE || kind == CompletionProposal . METHOD_REF ) if ( Flags . isStatic ( flags ) ) adornments |= RubyElementImageDescriptor . STATIC ; return new RubyElementImageDescriptor ( descriptor , adornments , RubyElementImageProvider . SMALL_SIZE ) ; } public String createLabel ( CompletionProposal proposal ) { switch ( proposal . getKind ( ) ) { case CompletionProposal . METHOD_NAME_REFERENCE : case CompletionProposal . METHOD_REF : case CompletionProposal . POTENTIAL_METHOD_DECLARATION : return createMethodProposalLabel ( proposal ) ; case CompletionProposal . TYPE_REF : return createTypeProposalLabel ( proposal ) ; case CompletionProposal . CONSTANT_REF : case CompletionProposal . CLASS_VARIABLE_REF : case CompletionProposal . INSTANCE_VARIABLE_REF : case CompletionProposal . GLOBAL_REF : case CompletionProposal . LOCAL_VARIABLE_REF : case CompletionProposal . VARIABLE_DECLARATION : case CompletionProposal . METHOD_DECLARATION : return createSimpleLabelWithType ( proposal ) ; case CompletionProposal . KEYWORD : return createSimpleLabel ( proposal ) ; default : Assert . isTrue ( false ) ; return null ; } } String createTypeProposalLabel ( CompletionProposal typeProposal ) { return typeProposal . getType ( ) ; } String createMethodProposalLabel ( CompletionProposal methodProposal ) { StringBuffer nameBuffer = new StringBuffer ( ) ; nameBuffer . append ( methodProposal . getName ( ) ) ; appendUnboundedParameterList ( nameBuffer , methodProposal ) ; nameBuffer . append ( RubyElementLabels . CONCAT_STRING ) ; String declaringType = methodProposal . getDeclaringType ( ) ; nameBuffer . append ( declaringType ) ; return nameBuffer . toString ( ) ; } private final StringBuffer appendUnboundedParameterList ( StringBuffer buffer , CompletionProposal methodProposal ) { String [ ] names = methodProposal . getParameterNames ( ) ; if ( names == null ) return buffer ; if ( names . length > ) { buffer . append ( '' ) ; } for ( int i = ; i < names . length ; i ++ ) { if ( i > ) { buffer . append ( '' ) ; buffer . append ( '' ) ; } buffer . append ( names [ i ] ) ; } if ( names . length > ) { buffer . append ( '' ) ; } return buffer ; } String createSimpleLabel ( CompletionProposal proposal ) { return String . valueOf ( proposal . getCompletion ( ) ) ; } String createSimpleLabelWithType ( CompletionProposal proposal ) { StringBuffer buf = new StringBuffer ( ) ; buf . append ( proposal . getCompletion ( ) ) ; String typeName = proposal . getType ( ) ; if ( typeName . length ( ) > ) { buf . append ( "" ) ; buf . append ( typeName ) ; } return buf . toString ( ) ; } public String createParameterList ( CompletionProposal methodProposal ) { Assert . isTrue ( methodProposal . getKind ( ) == CompletionProposal . METHOD_REF ) ; return appendUnboundedParameterList ( new StringBuffer ( ) , methodProposal ) . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . StringTokenizer ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IContributor ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . InvalidRegistryObjectException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Link ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . PreferenceConstants ; public final class CompletionProposalComputerRegistry { private static final String EXTENSION_POINT = "" ; private static CompletionProposalComputerRegistry fgSingleton = null ; public static synchronized CompletionProposalComputerRegistry getDefault ( ) { if ( fgSingleton == null ) { fgSingleton = new CompletionProposalComputerRegistry ( ) ; } return fgSingleton ; } private final Map < String , List < CompletionProposalComputerDescriptor > > fDescriptorsByPartition = new HashMap < String , List < CompletionProposalComputerDescriptor > > ( ) ; private final Map < String , List < CompletionProposalComputerDescriptor > > fPublicDescriptorsByPartition = new HashMap < String , List < CompletionProposalComputerDescriptor > > ( ) ; private final List < CompletionProposalComputerDescriptor > fDescriptors = new ArrayList < CompletionProposalComputerDescriptor > ( ) ; private final List < CompletionProposalComputerDescriptor > fPublicDescriptors = Collections . unmodifiableList ( fDescriptors ) ; private final List < CompletionProposalCategory > fCategories = new ArrayList < CompletionProposalCategory > ( ) ; private final List < CompletionProposalCategory > fPublicCategories = Collections . unmodifiableList ( fCategories ) ; private boolean fLoaded = false ; public CompletionProposalComputerRegistry ( ) { } List < CompletionProposalComputerDescriptor > getProposalComputerDescriptors ( String partition ) { ensureExtensionPointRead ( ) ; List < CompletionProposalComputerDescriptor > result = fPublicDescriptorsByPartition . get ( partition ) ; return ( List < CompletionProposalComputerDescriptor > ) ( result != null ? result : Collections . emptyList ( ) ) ; } List < CompletionProposalComputerDescriptor > getProposalComputerDescriptors ( ) { ensureExtensionPointRead ( ) ; return fPublicDescriptors ; } public List < CompletionProposalCategory > getProposalCategories ( ) { ensureExtensionPointRead ( ) ; return fPublicCategories ; } private void ensureExtensionPointRead ( ) { boolean reload ; synchronized ( this ) { reload = ! fLoaded ; fLoaded = true ; } if ( reload ) reload ( ) ; } public void reload ( ) { IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; List < IConfigurationElement > elements = new ArrayList < IConfigurationElement > ( Arrays . asList ( registry . getConfigurationElementsFor ( RubyPlugin . getPluginId ( ) , EXTENSION_POINT ) ) ) ; Map < String , List < CompletionProposalComputerDescriptor > > map = new HashMap < String , List < CompletionProposalComputerDescriptor > > ( ) ; List < CompletionProposalComputerDescriptor > all = new ArrayList < CompletionProposalComputerDescriptor > ( ) ; List < CompletionProposalCategory > categories = getCategories ( elements ) ; for ( Iterator < IConfigurationElement > iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { IConfigurationElement element = ( IConfigurationElement ) iter . next ( ) ; try { CompletionProposalComputerDescriptor desc = new CompletionProposalComputerDescriptor ( element , this , categories ) ; Set < String > partitions = desc . getPartitions ( ) ; for ( String partition : partitions ) { List < CompletionProposalComputerDescriptor > list = map . get ( partition ) ; if ( list == null ) { list = new ArrayList < CompletionProposalComputerDescriptor > ( ) ; map . put ( partition , list ) ; } list . add ( desc ) ; } all . add ( desc ) ; } catch ( InvalidRegistryObjectException x ) { Object [ ] args = { element . toString ( ) } ; String message = Messages . format ( RubyTextMessages . CompletionProposalComputerRegistry_invalid_message , args ) ; IStatus status = new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , message , x ) ; informUser ( status ) ; } } synchronized ( this ) { fCategories . clear ( ) ; fCategories . addAll ( categories ) ; Set < String > partitions = map . keySet ( ) ; fDescriptorsByPartition . keySet ( ) . retainAll ( partitions ) ; fPublicDescriptorsByPartition . keySet ( ) . retainAll ( partitions ) ; for ( String partition : partitions ) { List < CompletionProposalComputerDescriptor > old = fDescriptorsByPartition . get ( partition ) ; List < CompletionProposalComputerDescriptor > current = map . get ( partition ) ; if ( old != null ) { old . clear ( ) ; old . addAll ( current ) ; } else { fDescriptorsByPartition . put ( partition , current ) ; fPublicDescriptorsByPartition . put ( partition , Collections . unmodifiableList ( current ) ) ; } } fDescriptors . clear ( ) ; fDescriptors . addAll ( all ) ; } } private List < CompletionProposalCategory > getCategories ( List < IConfigurationElement > elements ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; String preference = store . getString ( PreferenceConstants . CODEASSIST_EXCLUDED_CATEGORIES ) ; Set < String > disabled = new HashSet < String > ( ) ; StringTokenizer tok = new StringTokenizer ( preference , "" ) ; while ( tok . hasMoreTokens ( ) ) disabled . add ( tok . nextToken ( ) ) ; Map < String , Integer > ordered = new HashMap < String , Integer > ( ) ; preference = store . getString ( PreferenceConstants . CODEASSIST_CATEGORY_ORDER ) ; tok = new StringTokenizer ( preference , "" ) ; while ( tok . hasMoreTokens ( ) ) { StringTokenizer inner = new StringTokenizer ( tok . nextToken ( ) , "" ) ; String id = inner . nextToken ( ) ; int rank = Integer . parseInt ( inner . nextToken ( ) ) ; ordered . put ( id , new Integer ( rank ) ) ; } List < CompletionProposalCategory > categories = new ArrayList < CompletionProposalCategory > ( ) ; for ( Iterator < IConfigurationElement > iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { IConfigurationElement element = iter . next ( ) ; try { if ( element . getName ( ) . equals ( "" ) ) { iter . remove ( ) ; CompletionProposalCategory category = new CompletionProposalCategory ( element , this ) ; categories . add ( category ) ; category . setIncluded ( ! disabled . contains ( category . getId ( ) ) ) ; Integer rank = ordered . get ( category . getId ( ) ) ; if ( rank != null ) { int r = rank . intValue ( ) ; boolean separate = r < ; category . setSeparateCommand ( separate ) ; category . setSortOrder ( r ) ; } } } catch ( InvalidRegistryObjectException x ) { Object [ ] args = { element . toString ( ) } ; String message = Messages . format ( RubyTextMessages . CompletionProposalComputerRegistry_invalid_message , args ) ; IStatus status = new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , message , x ) ; informUser ( status ) ; } } return categories ; } void informUser ( CompletionProposalComputerDescriptor descriptor , IStatus status ) { RubyPlugin . log ( status ) ; String title = RubyTextMessages . CompletionProposalComputerRegistry_error_dialog_title ; CompletionProposalCategory category = descriptor . getCategory ( ) ; IContributor culprit = descriptor . getContributor ( ) ; Set < String > affectedPlugins = getAffectedContributors ( category , culprit ) ; final String avoidHint ; final String culpritName = culprit == null ? null : culprit . getName ( ) ; if ( affectedPlugins . isEmpty ( ) ) avoidHint = Messages . format ( RubyTextMessages . CompletionProposalComputerRegistry_messageAvoidanceHint , new Object [ ] { culpritName , category . getDisplayName ( ) } ) ; else avoidHint = Messages . format ( RubyTextMessages . CompletionProposalComputerRegistry_messageAvoidanceHintWithWarning , new Object [ ] { culpritName , category . getDisplayName ( ) , toString ( affectedPlugins ) } ) ; String message = status . getMessage ( ) ; MessageDialog dialog = new MessageDialog ( RubyPlugin . getActiveWorkbenchShell ( ) , title , null , message , MessageDialog . ERROR , new String [ ] { IDialogConstants . OK_LABEL } , ) { protected Control createCustomArea ( Composite parent ) { Link link = new Link ( parent , SWT . NONE ) ; link . setText ( avoidHint ) ; link . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { PreferencesUtil . createPreferenceDialogOn ( getShell ( ) , "" , null , null ) . open ( ) ; } } ) ; GridData gridData = new GridData ( SWT . FILL , SWT . BEGINNING , true , false ) ; gridData . widthHint = this . getMinimumMessageWidth ( ) ; link . setLayoutData ( gridData ) ; return link ; } } ; dialog . open ( ) ; } private Set < String > getAffectedContributors ( CompletionProposalCategory category , IContributor culprit ) { Set < String > affectedPlugins = new HashSet < String > ( ) ; for ( CompletionProposalComputerDescriptor desc : getProposalComputerDescriptors ( ) ) { CompletionProposalCategory cat = desc . getCategory ( ) ; if ( cat . equals ( category ) ) { IContributor contributor = desc . getContributor ( ) ; if ( contributor != null && ! culprit . equals ( contributor ) ) affectedPlugins . add ( contributor . getName ( ) ) ; } } return affectedPlugins ; } private Object toString ( Collection collection ) { String string = collection . toString ( ) ; return string . substring ( , string . length ( ) - ) ; } private void informUser ( IStatus status ) { RubyPlugin . log ( status ) ; String title = RubyTextMessages . CompletionProposalComputerRegistry_error_dialog_title ; String message = status . getMessage ( ) ; MessageDialog . openError ( RubyPlugin . getActiveWorkbenchShell ( ) , title , message ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class LazyRubyCompletionProposal extends AbstractRubyCompletionProposal { protected static final String LPAREN = "" ; protected static final String RPAREN = "" ; protected static final String COMMA = "" ; protected static final String SPACE = "" ; private boolean fDisplayStringComputed ; private boolean fReplacementStringComputed ; private boolean fReplacementOffsetComputed ; private boolean fReplacementLengthComputed ; private boolean fCursorPositionComputed ; private boolean fImageComputed ; private boolean fContextInformationComputed ; private boolean fProposalInfoComputed ; private boolean fTriggerCharactersComputed ; private boolean fSortStringComputed ; private boolean fRelevanceComputed ; protected final CompletionProposal fProposal ; protected final RubyContentAssistInvocationContext fInvocationContext ; public LazyRubyCompletionProposal ( CompletionProposal proposal , RubyContentAssistInvocationContext context ) { Assert . isNotNull ( proposal ) ; Assert . isNotNull ( context ) ; fInvocationContext = context ; fProposal = proposal ; } public final char [ ] getTriggerCharacters ( ) { if ( ! fTriggerCharactersComputed ) setTriggerCharacters ( computeTriggerCharacters ( ) ) ; return super . getTriggerCharacters ( ) ; } protected char [ ] computeTriggerCharacters ( ) { return new char [ ] ; } public final void setTriggerCharacters ( char [ ] triggerCharacters ) { fTriggerCharactersComputed = true ; super . setTriggerCharacters ( triggerCharacters ) ; } public final void setProposalInfo ( ProposalInfo proposalInfo ) { fProposalInfoComputed = true ; super . setProposalInfo ( proposalInfo ) ; } protected final ProposalInfo getProposalInfo ( ) { if ( ! fProposalInfoComputed ) setProposalInfo ( computeProposalInfo ( ) ) ; return super . getProposalInfo ( ) ; } protected ProposalInfo computeProposalInfo ( ) { return null ; } public final void setCursorPosition ( int cursorPosition ) { fCursorPositionComputed = true ; super . setCursorPosition ( cursorPosition ) ; } protected final int getCursorPosition ( ) { if ( ! fCursorPositionComputed ) setCursorPosition ( computeCursorPosition ( ) ) ; return super . getCursorPosition ( ) ; } protected int computeCursorPosition ( ) { return getReplacementString ( ) . length ( ) ; } public final IContextInformation getContextInformation ( ) { if ( ! fContextInformationComputed ) setContextInformation ( computeContextInformation ( ) ) ; return super . getContextInformation ( ) ; } protected IContextInformation computeContextInformation ( ) { return null ; } public final void setContextInformation ( IContextInformation contextInformation ) { fContextInformationComputed = true ; super . setContextInformation ( contextInformation ) ; } public final String getDisplayString ( ) { if ( ! fDisplayStringComputed ) setDisplayString ( computeDisplayString ( ) ) ; return super . getDisplayString ( ) ; } protected final void setDisplayString ( String string ) { fDisplayStringComputed = true ; super . setDisplayString ( string ) ; } protected String computeDisplayString ( ) { return fInvocationContext . getLabelProvider ( ) . createLabel ( fProposal ) ; } public final String getAdditionalProposalInfo ( ) { return super . getAdditionalProposalInfo ( ) ; } public final int getContextInformationPosition ( ) { if ( getContextInformation ( ) == null ) return getReplacementOffset ( ) - ; return getReplacementOffset ( ) + getCursorPosition ( ) ; } public final int getReplacementOffset ( ) { if ( ! fReplacementOffsetComputed ) setReplacementOffset ( fProposal . getReplaceStart ( ) ) ; return super . getReplacementOffset ( ) ; } public final void setReplacementOffset ( int replacementOffset ) { fReplacementOffsetComputed = true ; super . setReplacementOffset ( replacementOffset ) ; } public final int getPrefixCompletionStart ( IDocument document , int completionOffset ) { return getReplacementOffset ( ) ; } public final int getReplacementLength ( ) { if ( ! fReplacementLengthComputed ) setReplacementLength ( fProposal . getReplaceEnd ( ) - fProposal . getReplaceStart ( ) ) ; return super . getReplacementLength ( ) ; } public final void setReplacementLength ( int replacementLength ) { fReplacementLengthComputed = true ; super . setReplacementLength ( replacementLength ) ; } public final String getReplacementString ( ) { if ( ! fReplacementStringComputed ) setReplacementString ( computeReplacementString ( ) ) ; return super . getReplacementString ( ) ; } protected String computeReplacementString ( ) { return String . valueOf ( fProposal . getCompletion ( ) ) ; } public final void setReplacementString ( String replacementString ) { fReplacementStringComputed = true ; super . setReplacementString ( replacementString ) ; } public final Image getImage ( ) { if ( ! fImageComputed ) setImage ( computeImage ( ) ) ; return super . getImage ( ) ; } protected Image computeImage ( ) { return RubyPlugin . getImageDescriptorRegistry ( ) . get ( fInvocationContext . getLabelProvider ( ) . createImageDescriptor ( fProposal ) ) ; } public final void setImage ( Image image ) { fImageComputed = true ; super . setImage ( image ) ; } protected boolean isValidPrefix ( String prefix ) { if ( super . isValidPrefix ( prefix ) ) return true ; if ( fProposal . getKind ( ) == CompletionProposal . METHOD_NAME_REFERENCE ) { return isPrefix ( prefix , getDisplayString ( ) ) ; } return false ; } public final int getRelevance ( ) { if ( ! fRelevanceComputed ) setRelevance ( computeRelevance ( ) ) ; return super . getRelevance ( ) ; } public final void setRelevance ( int relevance ) { fRelevanceComputed = true ; super . setRelevance ( relevance ) ; } protected int computeRelevance ( ) { final int baseRelevance = fProposal . getRelevance ( ) * ; switch ( fProposal . getKind ( ) ) { case CompletionProposal . KEYWORD : return baseRelevance + ; case CompletionProposal . TYPE_REF : return baseRelevance + ; case CompletionProposal . METHOD_REF : case CompletionProposal . METHOD_NAME_REFERENCE : case CompletionProposal . METHOD_DECLARATION : return baseRelevance + ; case CompletionProposal . POTENTIAL_METHOD_DECLARATION : return baseRelevance + ; case CompletionProposal . LOCAL_VARIABLE_REF : case CompletionProposal . VARIABLE_DECLARATION : return baseRelevance + ; default : return baseRelevance ; } } public final String getSortString ( ) { if ( ! fSortStringComputed ) setSortString ( computeSortString ( ) ) ; return super . getSortString ( ) ; } protected final void setSortString ( String string ) { fSortStringComputed = true ; super . setSortString ( string ) ; } protected String computeSortString ( ) { return getDisplayString ( ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . net . URL ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . InvalidRegistryObjectException ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . action . LegacyActionTools ; import org . eclipse . jface . resource . ImageDescriptor ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposalComputer ; public final class CompletionProposalCategory { private static final String ICON = "" ; private final String fId ; private final String fName ; private final IConfigurationElement fElement ; private final ImageDescriptor fImage ; private boolean fIsSeparateCommand = true ; private boolean fIsEnabled = true ; private boolean fIsIncluded = true ; private final CompletionProposalComputerRegistry fRegistry ; private int fSortOrder = ; private String fLastError = null ; CompletionProposalCategory ( IConfigurationElement element , CompletionProposalComputerRegistry registry ) { fElement = element ; fRegistry = registry ; IExtension parent = ( IExtension ) element . getParent ( ) ; fId = parent . getUniqueIdentifier ( ) ; checkNotNull ( fId , "" ) ; String name = parent . getLabel ( ) ; if ( name == null ) fName = fId ; else fName = name ; String icon = element . getAttribute ( ICON ) ; ImageDescriptor img = null ; if ( icon != null ) { Bundle bundle = getBundle ( ) ; if ( bundle != null ) { Path path = new Path ( icon ) ; URL url = FileLocator . find ( bundle , path , null ) ; img = ImageDescriptor . createFromURL ( url ) ; } } fImage = img ; } CompletionProposalCategory ( String id , String name , CompletionProposalComputerRegistry registry ) { fRegistry = registry ; fId = id ; fName = name ; fElement = null ; fImage = null ; } private Bundle getBundle ( ) { String namespace = fElement . getDeclaringExtension ( ) . getContributor ( ) . getName ( ) ; Bundle bundle = Platform . getBundle ( namespace ) ; return bundle ; } private void checkNotNull ( Object obj , String attribute ) throws InvalidRegistryObjectException { if ( obj == null ) { Object [ ] args = { getId ( ) , fElement . getContributor ( ) . getName ( ) , attribute } ; String message = Messages . format ( RubyTextMessages . CompletionProposalComputerDescriptor_illegal_attribute_message , args ) ; IStatus status = new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , message , null ) ; RubyPlugin . log ( status ) ; throw new InvalidRegistryObjectException ( ) ; } } public String getId ( ) { return fId ; } public String getName ( ) { return fName ; } public String getDisplayName ( ) { return LegacyActionTools . removeMnemonics ( fName ) ; } public ImageDescriptor getImageDescriptor ( ) { return fImage ; } public void setSeparateCommand ( boolean enabled ) { fIsSeparateCommand = enabled ; } public boolean isSeparateCommand ( ) { return fIsSeparateCommand ; } public void setIncluded ( boolean included ) { fIsIncluded = included ; } public boolean isIncluded ( ) { return fIsIncluded ; } public boolean isEnabled ( ) { return fIsEnabled ; } public void setEnabled ( boolean isEnabled ) { fIsEnabled = isEnabled ; } public boolean hasComputers ( ) { List descriptors = fRegistry . getProposalComputerDescriptors ( ) ; for ( Iterator it = descriptors . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalComputerDescriptor desc = ( CompletionProposalComputerDescriptor ) it . next ( ) ; if ( desc . getCategory ( ) == this ) return true ; } return false ; } public boolean hasComputers ( String partition ) { List descriptors = fRegistry . getProposalComputerDescriptors ( partition ) ; for ( Iterator it = descriptors . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalComputerDescriptor desc = ( CompletionProposalComputerDescriptor ) it . next ( ) ; if ( desc . getCategory ( ) == this ) return true ; } return false ; } public int getSortOrder ( ) { return fSortOrder ; } public void setSortOrder ( int sortOrder ) { fSortOrder = sortOrder ; } public List computeCompletionProposals ( ContentAssistInvocationContext context , String partition , SubProgressMonitor monitor ) { fLastError = null ; List result = new ArrayList ( ) ; List descriptors = new ArrayList ( fRegistry . getProposalComputerDescriptors ( partition ) ) ; for ( Iterator it = descriptors . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalComputerDescriptor desc = ( CompletionProposalComputerDescriptor ) it . next ( ) ; if ( desc . getCategory ( ) == this ) result . addAll ( desc . computeCompletionProposals ( context , monitor ) ) ; if ( fLastError == null ) fLastError = desc . getErrorMessage ( ) ; } return result ; } public List computeContextInformation ( ContentAssistInvocationContext context , String partition , SubProgressMonitor monitor ) { fLastError = null ; List result = new ArrayList ( ) ; List descriptors = new ArrayList ( fRegistry . getProposalComputerDescriptors ( partition ) ) ; for ( Iterator it = descriptors . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalComputerDescriptor desc = ( CompletionProposalComputerDescriptor ) it . next ( ) ; if ( desc . getCategory ( ) == this ) result . addAll ( desc . computeContextInformation ( context , monitor ) ) ; if ( fLastError == null ) fLastError = desc . getErrorMessage ( ) ; } return result ; } public String getErrorMessage ( ) { return fLastError ; } public void sessionStarted ( ) { List descriptors = new ArrayList ( fRegistry . getProposalComputerDescriptors ( ) ) ; for ( Iterator it = descriptors . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalComputerDescriptor desc = ( CompletionProposalComputerDescriptor ) it . next ( ) ; if ( desc . getCategory ( ) == this ) desc . sessionStarted ( ) ; if ( fLastError == null ) fLastError = desc . getErrorMessage ( ) ; } } public void sessionEnded ( ) { List descriptors = new ArrayList ( fRegistry . getProposalComputerDescriptors ( ) ) ; for ( Iterator it = descriptors . iterator ( ) ; it . hasNext ( ) ; ) { CompletionProposalComputerDescriptor desc = ( CompletionProposalComputerDescriptor ) it . next ( ) ; if ( desc . getCategory ( ) == this ) desc . sessionEnded ( ) ; if ( fLastError == null ) fLastError = desc . getErrorMessage ( ) ; } } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . corext . template . ruby . RubyContextType ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . text . template . contentassist . TemplateEngine ; import org . rubypeople . rdt . internal . ui . text . template . contentassist . TemplateProposal ; import org . rubypeople . rdt . ui . text . RubyTextTools ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposalComputer ; public class TemplateCompletionProposalComputer implements IRubyCompletionProposalComputer { private TemplateEngine fRubyTemplateEngine ; public TemplateCompletionProposalComputer ( ) { TemplateContextType contextType = RubyPlugin . getDefault ( ) . getTemplateContextRegistry ( ) . getContextType ( RubyContextType . NAME ) ; if ( contextType == null ) { contextType = new RubyContextType ( ) ; RubyPlugin . getDefault ( ) . getTemplateContextRegistry ( ) . addContextType ( contextType ) ; } if ( contextType != null ) fRubyTemplateEngine = new TemplateEngine ( contextType ) ; else fRubyTemplateEngine = null ; } public List computeCompletionProposals ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { TemplateEngine engine = fRubyTemplateEngine ; if ( engine != null ) { IRubyScript unit = null ; if ( context instanceof RubyContentAssistInvocationContext ) { RubyContentAssistInvocationContext rContext = ( RubyContentAssistInvocationContext ) context ; unit = rContext . getRubyScript ( ) ; } if ( unit == null ) return Collections . EMPTY_LIST ; engine . reset ( ) ; engine . complete ( context . getViewer ( ) , context . getInvocationOffset ( ) , unit ) ; TemplateProposal [ ] templateProposals = engine . getResults ( ) ; List result = new ArrayList ( Arrays . asList ( templateProposals ) ) ; IRubyCompletionProposal [ ] keyWordResults = getKeywordProposals ( context ) ; if ( keyWordResults . length > ) { if ( keyWordResults . length > ) { outer : for ( int k = ; k < templateProposals . length ; k ++ ) { TemplateProposal curr = templateProposals [ k ] ; String name = curr . getTemplate ( ) . getName ( ) ; for ( int i = ; i < keyWordResults . length ; i ++ ) { String keyword = keyWordResults [ i ] . getDisplayString ( ) ; if ( name . startsWith ( keyword ) ) { curr . setRelevance ( keyWordResults [ i ] . getRelevance ( ) + ) ; continue outer ; } } } } } return result ; } return Collections . EMPTY_LIST ; } private IRubyCompletionProposal [ ] getKeywordProposals ( ContentAssistInvocationContext context ) { List keywords = getKeywords ( ) ; List fKeywords = new ArrayList ( ) ; for ( Iterator iter = keywords . iterator ( ) ; iter . hasNext ( ) ; ) { String keyword = ( String ) iter . next ( ) ; String prefix = getCurrentPrefix ( context . getDocument ( ) . get ( ) , context . getInvocationOffset ( ) ) ; if ( prefix . length ( ) >= keyword . length ( ) ) continue ; fKeywords . add ( createKeywordProposal ( keyword , prefix , context . getInvocationOffset ( ) ) ) ; } return ( IRubyCompletionProposal [ ] ) fKeywords . toArray ( new RubyCompletionProposal [ fKeywords . size ( ) ] ) ; } protected String getCurrentPrefix ( String documentString , int documentOffset ) { int tokenLength = ; while ( ( documentOffset - tokenLength > ) && ! Character . isWhitespace ( documentString . charAt ( documentOffset - tokenLength - ) ) ) tokenLength ++ ; return documentString . substring ( ( documentOffset - tokenLength ) , documentOffset ) ; } private IRubyCompletionProposal createKeywordProposal ( String keyword , String prefix , int documentOffset ) { String completion = keyword . substring ( prefix . length ( ) , keyword . length ( ) ) ; return new RubyCompletionProposal ( completion , documentOffset , completion . length ( ) , RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_TEMPLATE ) , keyword , ) ; } private List getKeywords ( ) { List list = new ArrayList ( ) ; String [ ] keywords = RubyTextTools . getKeyWords ( ) ; for ( int i = ; i < keywords . length ; i ++ ) { list . add ( keywords [ i ] ) ; } return list ; } public List computeContextInformation ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { return Collections . EMPTY_LIST ; } public String getErrorMessage ( ) { return null ; } public void sessionEnded ( ) { } public void sessionStarted ( ) { } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . jface . text . link . LinkedModeUI ; import org . eclipse . jface . text . link . LinkedPosition ; import org . eclipse . jface . text . link . LinkedPositionGroup ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . texteditor . link . EditorLinkedModeUI ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorHighlightingSynchronizer ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . text . ruby . AbstractRubyCompletionProposal . ExitPolicy ; public final class FillArgsAndBlockProposal extends RubyMethodCompletionProposal { private IRegion fSelectedRegion ; private int [ ] fArgumentOffsets ; private int [ ] fArgumentLengths ; public FillArgsAndBlockProposal ( CompletionProposal proposal , RubyContentAssistInvocationContext context ) { super ( proposal , context ) ; } public void apply ( IDocument document , char trigger , int offset ) { super . apply ( document , trigger , offset ) ; int baseOffset = getReplacementOffset ( ) ; String replacement = getReplacementString ( ) ; if ( fArgumentOffsets != null && getTextViewer ( ) != null ) { try { LinkedModeModel model = new LinkedModeModel ( ) ; for ( int i = ; i != fArgumentOffsets . length ; i ++ ) { LinkedPositionGroup group = new LinkedPositionGroup ( ) ; group . addPosition ( new LinkedPosition ( document , baseOffset + fArgumentOffsets [ i ] , fArgumentLengths [ i ] , LinkedPositionGroup . NO_STOP ) ) ; model . addGroup ( group ) ; } model . forceInstall ( ) ; RubyEditor editor = getRubyEditor ( ) ; if ( editor != null ) { model . addLinkingListener ( new EditorHighlightingSynchronizer ( editor ) ) ; } LinkedModeUI ui = new EditorLinkedModeUI ( model , getTextViewer ( ) ) ; ui . setExitPosition ( getTextViewer ( ) , baseOffset + replacement . length ( ) - , , Integer . MAX_VALUE ) ; ui . setExitPolicy ( new ExitPolicy ( '' , document ) ) ; ui . setDoContextInfo ( true ) ; ui . setCyclingMode ( LinkedModeUI . CYCLE_WHEN_NO_PARENT ) ; ui . enter ( ) ; fSelectedRegion = ui . getSelectedRegion ( ) ; } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; openErrorDialog ( e ) ; } } else { fSelectedRegion = new Region ( baseOffset + replacement . length ( ) , ) ; } } protected boolean needsLinkedMode ( ) { return false ; } protected String computeReplacementString ( ) { if ( ! hasBlockVars ( ) && ( ! hasParameters ( ) || ! hasArgumentList ( ) ) ) return super . computeReplacementString ( ) ; String [ ] parameterNames = fProposal . getParameterNames ( ) ; String [ ] blockVars = fProposal . getBlockVars ( ) ; int parameterCount = parameterNames . length ; int blockVarsCount = blockVars . length ; fArgumentOffsets = new int [ parameterCount + blockVarsCount ] ; fArgumentLengths = new int [ parameterCount + blockVarsCount ] ; StringBuffer buffer = new StringBuffer ( String . valueOf ( fProposal . getName ( ) ) ) ; buffer . append ( LPAREN ) ; setCursorPosition ( buffer . length ( ) ) ; for ( int i = ; i != parameterCount ; i ++ ) { if ( i != ) { buffer . append ( COMMA ) ; buffer . append ( SPACE ) ; } fArgumentOffsets [ i ] = buffer . length ( ) ; buffer . append ( parameterNames [ i ] ) ; fArgumentLengths [ i ] = parameterNames [ i ] . length ( ) ; } buffer . append ( RPAREN ) ; if ( blockVarsCount > ) { buffer . append ( SPACE ) ; buffer . append ( "" ) ; buffer . append ( "" ) ; for ( int x = ; x < blockVars . length ; x ++ ) { if ( x != ) { buffer . append ( COMMA ) ; buffer . append ( SPACE ) ; } fArgumentOffsets [ parameterCount + x ] = buffer . length ( ) ; buffer . append ( blockVars [ x ] ) ; fArgumentLengths [ parameterCount + x ] = blockVars [ x ] . length ( ) ; } buffer . append ( "" ) ; buffer . append ( SPACE ) ; buffer . append ( SPACE ) ; buffer . append ( "" ) ; } return buffer . toString ( ) ; } private boolean hasBlockVars ( ) { String [ ] vars = fProposal . getBlockVars ( ) ; if ( vars == null ) return false ; return vars . length > ; } private RubyEditor getRubyEditor ( ) { IEditorPart part = RubyPlugin . getActivePage ( ) . getActiveEditor ( ) ; if ( part instanceof RubyEditor ) return ( RubyEditor ) part ; else return null ; } public Point getSelection ( IDocument document ) { if ( fSelectedRegion == null ) return new Point ( getReplacementOffset ( ) , ) ; return new Point ( fSelectedRegion . getOffset ( ) , fSelectedRegion . getLength ( ) ) ; } private void openErrorDialog ( BadLocationException e ) { Shell shell = getTextViewer ( ) . getTextWidget ( ) . getShell ( ) ; MessageDialog . openError ( shell , RubyTextMessages . ExperimentalProposal_error_msg , e . getMessage ( ) ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . net . URL ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPositionCategoryException ; import org . eclipse . jface . text . DefaultPositionUpdater ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . IPositionUpdater ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . ITextViewerExtension2 ; import org . eclipse . jface . text . ITextViewerExtension5 ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension2 ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension3 ; import org . eclipse . jface . text . contentassist . ICompletionProposalExtension5 ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . link . ILinkedModeListener ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . jface . text . link . LinkedModeUI ; import org . eclipse . jface . text . link . LinkedPosition ; import org . eclipse . jface . text . link . LinkedPositionGroup ; import org . eclipse . jface . text . link . LinkedModeUI . ExitFlags ; import org . eclipse . jface . text . link . LinkedModeUI . IExitPolicy ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . events . VerifyEvent ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . texteditor . link . EditorLinkedModeUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . HTMLPrinter ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . AbstractReusableInformationControlCreator ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . AbstractRubyEditorTextHover ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . BrowserInformationControl ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . RubyTextTools ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public abstract class AbstractRubyCompletionProposal implements IRubyCompletionProposal , ICompletionProposalExtension , ICompletionProposalExtension2 , ICompletionProposalExtension3 , ICompletionProposalExtension5 { static final class ReferenceTracker { private static final String CATEGORY = "" ; private final IPositionUpdater fPositionUpdater = new DefaultPositionUpdater ( CATEGORY ) ; private final Position fPosition = new Position ( ) ; public void preReplace ( IDocument document , int offset ) throws BadLocationException { fPosition . setOffset ( offset ) ; try { document . addPositionCategory ( CATEGORY ) ; document . addPositionUpdater ( fPositionUpdater ) ; document . addPosition ( CATEGORY , fPosition ) ; } catch ( BadPositionCategoryException e ) { RubyPlugin . log ( e ) ; } } public int postReplace ( IDocument document ) { try { document . removePosition ( CATEGORY , fPosition ) ; document . removePositionUpdater ( fPositionUpdater ) ; document . removePositionCategory ( CATEGORY ) ; } catch ( BadPositionCategoryException e ) { RubyPlugin . log ( e ) ; } return fPosition . getOffset ( ) ; } } protected static final class ExitPolicy implements IExitPolicy { final char fExitCharacter ; private final IDocument fDocument ; public ExitPolicy ( char exitCharacter , IDocument document ) { fExitCharacter = exitCharacter ; fDocument = document ; } public ExitFlags doExit ( LinkedModeModel environment , VerifyEvent event , int offset , int length ) { if ( event . character == fExitCharacter ) { if ( environment . anyPositionContains ( offset ) ) return new ExitFlags ( ILinkedModeListener . UPDATE_CARET , false ) ; else return new ExitFlags ( ILinkedModeListener . UPDATE_CARET , true ) ; } switch ( event . character ) { case '' : return new ExitFlags ( ILinkedModeListener . NONE , true ) ; case SWT . CR : if ( offset > ) { try { if ( fDocument . getChar ( offset - ) == '' ) return new ExitFlags ( ILinkedModeListener . EXIT_ALL , true ) ; } catch ( BadLocationException e ) { } } default : return null ; } } } private String fDisplayString ; private String fReplacementString ; private int fReplacementOffset ; private int fReplacementLength ; private int fCursorPosition ; private Image fImage ; private IContextInformation fContextInformation ; private ProposalInfo fProposalInfo ; private char [ ] fTriggerCharacters ; private String fSortString ; private int fRelevance ; private boolean fIsInRubydoc ; private StyleRange fRememberedStyleRange ; private boolean fToggleEating ; private ITextViewer fTextViewer ; private IInformationControlCreator fCreator ; private URL fStyleSheetURL ; protected AbstractRubyCompletionProposal ( ) { } public char [ ] getTriggerCharacters ( ) { return fTriggerCharacters ; } public void setTriggerCharacters ( char [ ] triggerCharacters ) { fTriggerCharacters = triggerCharacters ; } public void setProposalInfo ( ProposalInfo proposalInfo ) { fProposalInfo = proposalInfo ; } protected ProposalInfo getProposalInfo ( ) { return fProposalInfo ; } public void setCursorPosition ( int cursorPosition ) { Assert . isTrue ( cursorPosition >= ) ; fCursorPosition = cursorPosition ; } protected int getCursorPosition ( ) { return fCursorPosition ; } public final void apply ( IDocument document ) { apply ( document , ( char ) , getReplacementOffset ( ) + getReplacementLength ( ) ) ; } public void apply ( IDocument document , char trigger , int offset ) { try { int delta = offset - ( getReplacementOffset ( ) + getReplacementLength ( ) ) ; if ( delta > ) setReplacementLength ( getReplacementLength ( ) + delta ) ; String replacement ; if ( trigger == ( char ) ) { replacement = getReplacementString ( ) ; } else { StringBuffer buffer = new StringBuffer ( getReplacementString ( ) ) ; if ( ( getCursorPosition ( ) > && getCursorPosition ( ) <= buffer . length ( ) && buffer . charAt ( getCursorPosition ( ) - ) != trigger ) ) { buffer . insert ( getCursorPosition ( ) , trigger ) ; setCursorPosition ( getCursorPosition ( ) + ) ; } replacement = buffer . toString ( ) ; setReplacementString ( replacement ) ; } int referenceOffset = getReplacementOffset ( ) + getReplacementLength ( ) ; final ReferenceTracker referenceTracker = new ReferenceTracker ( ) ; referenceTracker . preReplace ( document , referenceOffset ) ; replace ( document , getReplacementOffset ( ) , getReplacementLength ( ) , replacement ) ; referenceOffset = referenceTracker . postReplace ( document ) ; setReplacementOffset ( referenceOffset - ( replacement == null ? : replacement . length ( ) ) ) ; } catch ( BadLocationException x ) { } } protected final void replace ( IDocument document , int offset , int length , String string ) throws BadLocationException { if ( ! document . get ( offset , length ) . equals ( string ) ) document . replace ( offset , length , string ) ; } public void apply ( ITextViewer viewer , char trigger , int stateMask , int offset ) { IDocument document = viewer . getDocument ( ) ; if ( fTextViewer == null ) fTextViewer = viewer ; if ( ! isInRubydoc ( ) && ! validate ( document , offset , null ) ) { setCursorPosition ( offset - getReplacementOffset ( ) ) ; if ( trigger != '' ) { try { document . replace ( offset , , String . valueOf ( trigger ) ) ; setCursorPosition ( getCursorPosition ( ) + ) ; if ( trigger == '' && autocloseBrackets ( ) ) { document . replace ( getReplacementOffset ( ) + getCursorPosition ( ) , , "" ) ; setUpLinkedMode ( document , '' ) ; } } catch ( BadLocationException x ) { } } return ; } Point selection = viewer . getSelectedRange ( ) ; fToggleEating = ( stateMask & SWT . MOD1 ) != ; int newLength = selection . x + selection . y - getReplacementOffset ( ) ; if ( ( insertCompletion ( ) ^ fToggleEating ) && newLength >= ) setReplacementLength ( newLength ) ; apply ( document , trigger , offset ) ; fToggleEating = false ; } protected boolean isInRubydoc ( ) { return fIsInRubydoc ; } protected void setInRubydoc ( boolean isInRubydoc ) { fIsInRubydoc = isInRubydoc ; } public Point getSelection ( IDocument document ) { return new Point ( getReplacementOffset ( ) + getCursorPosition ( ) , ) ; } public IContextInformation getContextInformation ( ) { return fContextInformation ; } public void setContextInformation ( IContextInformation contextInformation ) { fContextInformation = contextInformation ; } public String getDisplayString ( ) { return fDisplayString ; } public String getAdditionalProposalInfo ( ) { if ( getProposalInfo ( ) != null ) { String info = getProposalInfo ( ) . getInfo ( null ) ; if ( info != null && info . length ( ) > ) { StringBuffer buffer = new StringBuffer ( ) ; HTMLPrinter . insertPageProlog ( buffer , , AbstractRubyEditorTextHover . getStyleSheet ( ) ) ; buffer . append ( info ) ; HTMLPrinter . addPageEpilog ( buffer ) ; info = buffer . toString ( ) ; } return info ; } return null ; } public Object getAdditionalProposalInfo ( IProgressMonitor monitor ) { if ( getProposalInfo ( ) != null ) { String info = getProposalInfo ( ) . getInfo ( monitor ) ; if ( info != null && info . length ( ) > ) { StringBuffer buffer = new StringBuffer ( ) ; HTMLPrinter . insertPageProlog ( buffer , , AbstractRubyEditorTextHover . getStyleSheet ( ) ) ; buffer . append ( info ) ; HTMLPrinter . addPageEpilog ( buffer ) ; info = buffer . toString ( ) ; } return info ; } return null ; } public int getContextInformationPosition ( ) { if ( getContextInformation ( ) == null ) return getReplacementOffset ( ) - ; return getReplacementOffset ( ) + getCursorPosition ( ) ; } public int getReplacementOffset ( ) { return fReplacementOffset ; } public void setReplacementOffset ( int replacementOffset ) { Assert . isTrue ( replacementOffset >= ) ; fReplacementOffset = replacementOffset ; } public int getPrefixCompletionStart ( IDocument document , int completionOffset ) { return getReplacementOffset ( ) ; } public int getReplacementLength ( ) { return fReplacementLength ; } public void setReplacementLength ( int replacementLength ) { Assert . isTrue ( replacementLength >= ) ; fReplacementLength = replacementLength ; } public String getReplacementString ( ) { return fReplacementString ; } public void setReplacementString ( String replacementString ) { Assert . isNotNull ( replacementString ) ; fReplacementString = replacementString ; } public CharSequence getPrefixCompletionText ( IDocument document , int completionOffset ) { return getReplacementString ( ) ; } public Image getImage ( ) { return fImage ; } public void setImage ( Image image ) { fImage = image ; } public boolean isValidFor ( IDocument document , int offset ) { return validate ( document , offset , null ) ; } public boolean validate ( IDocument document , int offset , DocumentEvent event ) { if ( offset < getReplacementOffset ( ) ) return false ; boolean validated = isValidPrefix ( getPrefix ( document , offset ) ) ; if ( validated && event != null ) { int delta = ( event . fText == null ? : event . fText . length ( ) ) - event . fLength ; final int newLength = Math . max ( getReplacementLength ( ) + delta , ) ; setReplacementLength ( newLength ) ; } return validated ; } protected boolean isValidPrefix ( String prefix ) { return isPrefix ( prefix , getDisplayString ( ) ) ; } public int getRelevance ( ) { return fRelevance ; } public void setRelevance ( int relevance ) { fRelevance = relevance ; } protected String getPrefix ( IDocument document , int offset ) { try { int length = offset - getReplacementOffset ( ) ; if ( length > ) return document . get ( getReplacementOffset ( ) , length ) ; } catch ( BadLocationException x ) { } return "" ; } protected boolean isPrefix ( String prefix , String string ) { if ( prefix == null || string == null || prefix . length ( ) > string . length ( ) ) return false ; String start = string . substring ( , prefix . length ( ) ) ; return start . equalsIgnoreCase ( prefix ) ; } private IRubyProject getProject ( ) { return null ; } private static boolean insertCompletion ( ) { IPreferenceStore preference = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; return preference . getBoolean ( PreferenceConstants . CODEASSIST_INSERT_COMPLETION ) ; } private static Color getForegroundColor ( StyledText text ) { IPreferenceStore preference = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; RGB rgb = PreferenceConverter . getColor ( preference , PreferenceConstants . CODEASSIST_REPLACEMENT_FOREGROUND ) ; RubyTextTools textTools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; return textTools . getColorManager ( ) . getColor ( rgb ) ; } private static Color getBackgroundColor ( StyledText text ) { IPreferenceStore preference = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; RGB rgb = PreferenceConverter . getColor ( preference , PreferenceConstants . CODEASSIST_REPLACEMENT_BACKGROUND ) ; RubyTextTools textTools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; return textTools . getColorManager ( ) . getColor ( rgb ) ; } private void repairPresentation ( ITextViewer viewer ) { if ( fRememberedStyleRange != null ) { if ( viewer instanceof ITextViewerExtension2 ) { ITextViewerExtension2 viewer2 = ( ITextViewerExtension2 ) viewer ; if ( viewer instanceof ITextViewerExtension5 ) { ITextViewerExtension5 extension = ( ITextViewerExtension5 ) viewer ; IRegion modelRange = extension . widgetRange2ModelRange ( new Region ( fRememberedStyleRange . start , fRememberedStyleRange . length ) ) ; if ( modelRange != null ) viewer2 . invalidateTextPresentation ( modelRange . getOffset ( ) , modelRange . getLength ( ) ) ; } else { viewer2 . invalidateTextPresentation ( fRememberedStyleRange . start + viewer . getVisibleRegion ( ) . getOffset ( ) , fRememberedStyleRange . length ) ; } } else viewer . invalidateTextPresentation ( ) ; } } private void updateStyle ( ITextViewer viewer ) { StyledText text = viewer . getTextWidget ( ) ; if ( text == null || text . isDisposed ( ) ) return ; int widgetCaret = text . getCaretOffset ( ) ; int modelCaret = ; if ( viewer instanceof ITextViewerExtension5 ) { ITextViewerExtension5 extension = ( ITextViewerExtension5 ) viewer ; modelCaret = extension . widgetOffset2ModelOffset ( widgetCaret ) ; } else { IRegion visibleRegion = viewer . getVisibleRegion ( ) ; modelCaret = widgetCaret + visibleRegion . getOffset ( ) ; } if ( modelCaret >= getReplacementOffset ( ) + getReplacementLength ( ) ) { repairPresentation ( viewer ) ; return ; } int offset = widgetCaret ; int length = getReplacementOffset ( ) + getReplacementLength ( ) - modelCaret ; Color foreground = getForegroundColor ( text ) ; Color background = getBackgroundColor ( text ) ; StyleRange range = text . getStyleRangeAtOffset ( offset ) ; int fontStyle = range != null ? range . fontStyle : SWT . NORMAL ; repairPresentation ( viewer ) ; fRememberedStyleRange = new StyleRange ( offset , length , foreground , background , fontStyle ) ; if ( range != null ) { fRememberedStyleRange . strikeout = range . strikeout ; fRememberedStyleRange . underline = range . underline ; } try { text . setStyleRange ( fRememberedStyleRange ) ; } catch ( IllegalArgumentException x ) { fRememberedStyleRange = null ; } } public void selected ( ITextViewer viewer , boolean smartToggle ) { if ( ! insertCompletion ( ) ^ smartToggle ) updateStyle ( viewer ) ; else { repairPresentation ( viewer ) ; fRememberedStyleRange = null ; } } public void unselected ( ITextViewer viewer ) { repairPresentation ( viewer ) ; fRememberedStyleRange = null ; } public IInformationControlCreator getInformationControlCreator ( ) { if ( ! BrowserInformationControl . isAvailable ( null ) ) return null ; if ( fCreator == null ) { fCreator = new AbstractReusableInformationControlCreator ( ) { public IInformationControl doCreateInformationControl ( Shell parent ) { return new BrowserInformationControl ( parent , SWT . NO_TRIM | SWT . TOOL , SWT . NONE , null ) ; } } ; } return fCreator ; } public String getSortString ( ) { return fSortString ; } protected void setSortString ( String string ) { fSortString = string ; } protected ITextViewer getTextViewer ( ) { return fTextViewer ; } protected boolean isToggleEating ( ) { return fToggleEating ; } protected void setUpLinkedMode ( IDocument document , char closingCharacter ) { if ( getTextViewer ( ) != null && autocloseBrackets ( ) ) { int offset = getReplacementOffset ( ) + getCursorPosition ( ) ; int exit = getReplacementOffset ( ) + getReplacementString ( ) . length ( ) ; try { LinkedPositionGroup group = new LinkedPositionGroup ( ) ; group . addPosition ( new LinkedPosition ( document , offset , , LinkedPositionGroup . NO_STOP ) ) ; LinkedModeModel model = new LinkedModeModel ( ) ; model . addGroup ( group ) ; model . forceInstall ( ) ; LinkedModeUI ui = new EditorLinkedModeUI ( model , getTextViewer ( ) ) ; ui . setSimpleMode ( true ) ; ui . setExitPolicy ( new ExitPolicy ( closingCharacter , document ) ) ; ui . setExitPosition ( getTextViewer ( ) , exit , , Integer . MAX_VALUE ) ; ui . setCyclingMode ( LinkedModeUI . CYCLE_NEVER ) ; ui . enter ( ) ; } catch ( BadLocationException x ) { RubyPlugin . log ( x ) ; } } } protected boolean autocloseBrackets ( ) { IPreferenceStore preferenceStore = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; return preferenceStore . getBoolean ( PreferenceConstants . EDITOR_CLOSE_BRACKETS ) ; } protected void setDisplayString ( String string ) { fDisplayString = string ; } public String toString ( ) { return getDisplayString ( ) ; } public IRubyElement getRubyElement ( ) { if ( getProposalInfo ( ) != null ) try { return getProposalInfo ( ) . getRubyElement ( ) ; } catch ( RubyModelException x ) { RubyPlugin . log ( x ) ; } return null ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . Comparator ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . rubypeople . rdt . ui . text . ruby . AbstractProposalSorter ; import org . rubypeople . rdt . ui . text . ruby . CompletionProposalComparator ; public final class RelevanceSorter extends AbstractProposalSorter { private final Comparator fComparator = new CompletionProposalComparator ( ) ; public RelevanceSorter ( ) { } public int compare ( ICompletionProposal p1 , ICompletionProposal p2 ) { return fComparator . compare ( p1 , p2 ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . ui . text . ruby . ContentAssistInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposalComputer ; public class LegacyRubyCompletionProposalComputer implements IRubyCompletionProposalComputer { private LegacyRubyCompletionProcessor fProcessor = new LegacyRubyCompletionProcessor ( ) ; public List computeCompletionProposals ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { if ( context instanceof RubyContentAssistInvocationContext ) { fProcessor . setRubyContentAssistInvocationContext ( ( RubyContentAssistInvocationContext ) context ) ; } return Arrays . asList ( fProcessor . computeCompletionProposals ( context . getViewer ( ) , context . getInvocationOffset ( ) ) ) ; } public List computeContextInformation ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { if ( context instanceof RubyContentAssistInvocationContext ) { fProcessor . setRubyContentAssistInvocationContext ( ( RubyContentAssistInvocationContext ) context ) ; } return Arrays . asList ( fProcessor . computeContextInformation ( context . getViewer ( ) , context . getInvocationOffset ( ) ) ) ; } public String getErrorMessage ( ) { return fProcessor . getErrorMessage ( ) ; } public void sessionEnded ( ) { } public void sessionStarted ( ) { } } package org . rubypeople . rdt . internal . ui . text . ruby ; import java . util . LinkedList ; import java . util . Map ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . text . TypedPosition ; import org . eclipse . jface . text . formatter . ContextBasedFormattingStrategy ; import org . eclipse . jface . text . formatter . FormattingContextProperties ; import org . eclipse . jface . text . formatter . IFormattingContext ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . rubypeople . rdt . internal . corext . util . CodeFormatterUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyFormattingStrategy extends ContextBasedFormattingStrategy { private final LinkedList fDocuments = new LinkedList ( ) ; private final LinkedList fPartitions = new LinkedList ( ) ; public RubyFormattingStrategy ( ) { super ( ) ; } public void format ( ) { super . format ( ) ; final IDocument document = ( IDocument ) fDocuments . removeFirst ( ) ; final TypedPosition partition = ( TypedPosition ) fPartitions . removeFirst ( ) ; if ( document != null && partition != null ) { try { final TextEdit edit = CodeFormatterUtil . format2 ( CodeFormatter . K_RUBY_SCRIPT , document . get ( ) , partition . getOffset ( ) , partition . getLength ( ) , , TextUtilities . getDefaultLineDelimiter ( document ) , getPreferences ( ) ) ; if ( edit != null ) { Map partitioners = null ; if ( edit . getChildrenSize ( ) > ) partitioners = TextUtilities . removeDocumentPartitioners ( document ) ; edit . apply ( document ) ; if ( partitioners != null ) TextUtilities . addDocumentPartitioners ( document , partitioners ) ; } } catch ( MalformedTreeException exception ) { RubyPlugin . log ( exception ) ; } catch ( BadLocationException exception ) { RubyPlugin . log ( exception ) ; } } } public void formatterStarts ( final IFormattingContext context ) { super . formatterStarts ( context ) ; fPartitions . addLast ( context . getProperty ( FormattingContextProperties . CONTEXT_PARTITION ) ) ; fDocuments . addLast ( context . getProperty ( FormattingContextProperties . CONTEXT_MEDIUM ) ) ; } public void formatterStops ( ) { super . formatterStops ( ) ; fPartitions . clear ( ) ; fDocuments . clear ( ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . TextPresentation ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . IContentAssistProcessor ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . contentassist . IContextInformationPresenter ; import org . eclipse . jface . text . contentassist . IContextInformationValidator ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . TemplateCompletionProcessor ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . template . ruby . RubyContextType ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . text . template . contentassist . RubyTemplateAccess ; import org . rubypeople . rdt . ui . text . ruby . CompletionProposalCollector ; public class LegacyRubyCompletionProcessor extends TemplateCompletionProcessor implements IContentAssistProcessor { protected IContextInformationValidator contextInformationValidator = new RubyContextInformationValidator ( ) ; private RubyContentAssistInvocationContext context ; public LegacyRubyCompletionProcessor ( ) { super ( ) ; } public ICompletionProposal [ ] computeCompletionProposals ( ITextViewer viewer , int documentOffset ) { ITextSelection selection = ( ITextSelection ) viewer . getSelectionProvider ( ) . getSelection ( ) ; return codeComplete ( documentOffset ) ; } private ICompletionProposal [ ] codeComplete ( int offset ) { try { IRubyScript script = getRubyScript ( ) ; if ( script == null ) return new ICompletionProposal [ ] ; CompletionProposalCollector requestor = new CompletionProposalCollector ( context ) ; script . codeComplete ( offset - , requestor ) ; return requestor . getRubyCompletionProposals ( ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; return new ICompletionProposal [ ] ; } } protected Image getImage ( Template template ) { return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_TEMPLATE ) ; } public TemplateContextType getContextType ( ITextViewer textViewer , IRegion region ) { return RubyTemplateAccess . getDefault ( ) . getContextTypeRegistry ( ) . getContextType ( RubyContextType . NAME ) ; } public void setRubyContentAssistInvocationContext ( RubyContentAssistInvocationContext context ) { this . context = context ; } private IRubyScript getRubyScript ( ) { return this . context . getRubyScript ( ) ; } protected String getCurrentPrefix ( String documentString , int documentOffset ) { int tokenLength = ; while ( ( documentOffset - tokenLength > ) && ! Character . isWhitespace ( documentString . charAt ( documentOffset - tokenLength - ) ) ) tokenLength ++ ; return documentString . substring ( ( documentOffset - tokenLength ) , documentOffset ) ; } public Template [ ] getTemplates ( String contextTypeId ) { return RubyTemplateAccess . getDefault ( ) . getTemplateStore ( ) . getTemplates ( ) ; } public IContextInformation [ ] computeContextInformation ( ITextViewer viewer , int documentOffset ) { return new IContextInformation [ ] ; } public char [ ] getCompletionProposalAutoActivationCharacters ( ) { return null ; } public char [ ] getContextInformationAutoActivationCharacters ( ) { return new char [ ] { '' } ; } public IContextInformationValidator getContextInformationValidator ( ) { return contextInformationValidator ; } public String getErrorMessage ( ) { return null ; } protected class RubyContextInformationValidator implements IContextInformationValidator , IContextInformationPresenter { protected int installDocumentPosition ; public void install ( IContextInformation info , ITextViewer viewer , int documentPosition ) { installDocumentPosition = documentPosition ; } public boolean isContextInformationValid ( int documentPosition ) { return Math . abs ( installDocumentPosition - documentPosition ) < ; } public boolean updatePresentation ( int documentPosition , TextPresentation presentation ) { return false ; } } } package org . rubypeople . rdt . internal . ui . text ; import java . text . CharacterIterator ; import org . eclipse . jface . text . Assert ; public class SequenceCharacterIterator implements CharacterIterator { private int fIndex = - ; private final CharSequence fSequence ; private final int fFirst ; private final int fLast ; private void invariant ( ) { Assert . isTrue ( fIndex >= fFirst ) ; Assert . isTrue ( fIndex <= fLast ) ; } public SequenceCharacterIterator ( CharSequence sequence ) { this ( sequence , ) ; } public SequenceCharacterIterator ( CharSequence sequence , int first ) throws IllegalArgumentException { this ( sequence , first , sequence . length ( ) ) ; } public SequenceCharacterIterator ( CharSequence sequence , int first , int last ) throws IllegalArgumentException { if ( sequence == null ) throw new NullPointerException ( ) ; if ( first < || first > last ) throw new IllegalArgumentException ( ) ; if ( last > sequence . length ( ) ) throw new IllegalArgumentException ( ) ; fSequence = sequence ; fFirst = first ; fLast = last ; fIndex = first ; invariant ( ) ; } public char first ( ) { return setIndex ( getBeginIndex ( ) ) ; } public char last ( ) { if ( fFirst == fLast ) return setIndex ( getEndIndex ( ) ) ; else return setIndex ( getEndIndex ( ) - ) ; } public char current ( ) { if ( fIndex >= fFirst && fIndex < fLast ) return fSequence . charAt ( fIndex ) ; else return DONE ; } public char next ( ) { return setIndex ( Math . min ( fIndex + , getEndIndex ( ) ) ) ; } public char previous ( ) { if ( fIndex > getBeginIndex ( ) ) { return setIndex ( fIndex - ) ; } else { return DONE ; } } public char setIndex ( int position ) { if ( position >= getBeginIndex ( ) && position <= getEndIndex ( ) ) fIndex = position ; else throw new IllegalArgumentException ( ) ; invariant ( ) ; return current ( ) ; } public int getBeginIndex ( ) { return fFirst ; } public int getEndIndex ( ) { return fLast ; } public int getIndex ( ) { return fIndex ; } public Object clone ( ) { try { return super . clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new InternalError ( ) ; } } } package org . rubypeople . rdt . internal . ui . text ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . viewers . AbstractTreeViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . IDecoratorManager ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . keys . KeySequence ; import org . eclipse . ui . keys . SWTKeySupport ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . corext . util . MethodOverrideTester ; import org . rubypeople . rdt . internal . corext . util . SuperTypeHierarchyCache ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . typehierarchy . AbstractHierarchyViewerSorter ; import org . rubypeople . rdt . internal . ui . util . StringMatcher ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . MemberFilter ; import org . rubypeople . rdt . ui . OverrideIndicatorLabelDecorator ; import org . rubypeople . rdt . ui . ProblemsLabelDecorator ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; public class RubyOutlineInformationControl extends AbstractInformationControl { private KeyAdapter fKeyAdapter ; private OutlineContentProvider fOutlineContentProvider ; private IRubyElement fInput = null ; private OutlineSorter fOutlineSorter ; private OutlineLabelProvider fInnerLabelProvider ; protected Color fForegroundColor ; private boolean fShowOnlyMainType ; private LexicalSortingAction fLexicalSortingAction ; private SortByDefiningTypeAction fSortByDefiningTypeAction ; private ShowOnlyMainTypeAction fShowOnlyMainTypeAction ; private Map fTypeHierarchies = new HashMap ( ) ; private String fPattern ; private class OutlineLabelProvider extends AppearanceAwareLabelProvider { private boolean fShowDefiningType ; private OutlineLabelProvider ( ) { super ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS ) ; } public String getText ( Object element ) { String text = super . getText ( element ) ; if ( fShowDefiningType ) { try { IType type = getDefiningType ( element ) ; if ( type != null ) { StringBuffer buf = new StringBuffer ( super . getText ( type ) ) ; buf . append ( RubyElementLabels . CONCAT_STRING ) ; buf . append ( text ) ; return buf . toString ( ) ; } } catch ( RubyModelException e ) { } } return text ; } public Color getForeground ( Object element ) { if ( fOutlineContentProvider . isShowingInheritedMembers ( ) ) { if ( element instanceof IRubyElement ) { IRubyElement je = ( IRubyElement ) element ; je = je . getAncestor ( IRubyElement . SCRIPT ) ; if ( fInput . equals ( je ) ) { return null ; } } return fForegroundColor ; } return null ; } public void setShowDefiningType ( boolean showDefiningType ) { fShowDefiningType = showDefiningType ; } public boolean isShowDefiningType ( ) { return fShowDefiningType ; } private IType getDefiningType ( Object element ) throws RubyModelException { int kind = ( ( IRubyElement ) element ) . getElementType ( ) ; if ( kind != IRubyElement . METHOD && kind != IRubyElement . FIELD ) { return null ; } IType declaringType = ( ( IMember ) element ) . getDeclaringType ( ) ; if ( kind != IRubyElement . METHOD ) { return declaringType ; } ITypeHierarchy hierarchy = getSuperTypeHierarchy ( declaringType ) ; if ( hierarchy == null ) { return declaringType ; } IMethod method = ( IMethod ) element ; MethodOverrideTester tester = new MethodOverrideTester ( declaringType , hierarchy ) ; IMethod res = tester . findDeclaringMethod ( method , true ) ; if ( res == null || method . equals ( res ) ) { return declaringType ; } return res . getDeclaringType ( ) ; } } private class OutlineTreeViewer extends TreeViewer { private boolean fIsFiltering = false ; private OutlineTreeViewer ( Tree tree ) { super ( tree ) ; } protected Object [ ] getFilteredChildren ( Object parent ) { Object [ ] result = getRawChildren ( parent ) ; int unfilteredChildren = result . length ; ViewerFilter [ ] filters = getFilters ( ) ; if ( filters != null ) { for ( int i = ; i < filters . length ; i ++ ) result = filters [ i ] . filter ( this , parent , result ) ; } fIsFiltering = unfilteredChildren != result . length ; return result ; } protected void internalExpandToLevel ( Widget node , int level ) { if ( ! fIsFiltering && node instanceof Item ) { Item i = ( Item ) node ; if ( i . getData ( ) instanceof IRubyElement ) { IRubyElement je = ( IRubyElement ) i . getData ( ) ; if ( je . getElementType ( ) == IRubyElement . IMPORT_CONTAINER || isInnerType ( je ) ) { setExpanded ( i , false ) ; return ; } } } super . internalExpandToLevel ( node , level ) ; } private boolean isInnerType ( IRubyElement element ) { if ( element != null && element . getElementType ( ) == IRubyElement . TYPE ) { IType type = ( IType ) element ; try { return type . isMember ( ) ; } catch ( RubyModelException e ) { IRubyElement parent = type . getParent ( ) ; if ( parent != null ) { int parentElementType = parent . getElementType ( ) ; return ( parentElementType != IRubyElement . SCRIPT ) ; } } } return false ; } } private class OutlineContentProvider extends StandardRubyElementContentProvider { private boolean fShowInheritedMembers ; private OutlineContentProvider ( boolean showInheritedMembers ) { super ( true ) ; fShowInheritedMembers = showInheritedMembers ; } public boolean isShowingInheritedMembers ( ) { return fShowInheritedMembers ; } public void toggleShowInheritedMembers ( ) { Tree tree = getTreeViewer ( ) . getTree ( ) ; tree . setRedraw ( false ) ; fShowInheritedMembers = ! fShowInheritedMembers ; getTreeViewer ( ) . refresh ( ) ; getTreeViewer ( ) . expandToLevel ( ) ; Object selectedElement = getSelectedElement ( ) ; if ( selectedElement != null ) getTreeViewer ( ) . reveal ( selectedElement ) ; tree . setRedraw ( true ) ; } public Object [ ] getChildren ( Object element ) { if ( fShowOnlyMainType ) { if ( element instanceof IRubyScript ) { element = getMainType ( ( IRubyScript ) element ) ; } if ( element == null ) return NO_CHILDREN ; } if ( fShowInheritedMembers && element instanceof IType ) { IType type = ( IType ) element ; if ( type . getDeclaringType ( ) == null ) { ITypeHierarchy th = getSuperTypeHierarchy ( type ) ; if ( th != null ) { List children = new ArrayList ( ) ; IType [ ] superClasses = th . getAllSupertypes ( type ) ; children . addAll ( Arrays . asList ( super . getChildren ( type ) ) ) ; for ( int i = , scLength = superClasses . length ; i < scLength ; i ++ ) children . addAll ( Arrays . asList ( super . getChildren ( superClasses [ i ] ) ) ) ; return children . toArray ( ) ; } } } return super . getChildren ( element ) ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { super . inputChanged ( viewer , oldInput , newInput ) ; fTypeHierarchies . clear ( ) ; } public void dispose ( ) { super . dispose ( ) ; fTypeHierarchies . clear ( ) ; } } private class ShowOnlyMainTypeAction extends Action { private static final String STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED = "" ; private TreeViewer fOutlineViewer ; private ShowOnlyMainTypeAction ( TreeViewer outlineViewer ) { super ( TextMessages . RubyOutlineInformationControl_GoIntoTopLevelType_label , IAction . AS_CHECK_BOX ) ; setToolTipText ( TextMessages . RubyOutlineInformationControl_GoIntoTopLevelType_tooltip ) ; setDescription ( TextMessages . RubyOutlineInformationControl_GoIntoTopLevelType_description ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . GO_INTO_TOP_LEVEL_TYPE_ACTION ) ; fOutlineViewer = outlineViewer ; boolean showclass = getDialogSettings ( ) . getBoolean ( STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED ) ; setTopLevelTypeOnly ( showclass ) ; } public void run ( ) { setTopLevelTypeOnly ( ! fShowOnlyMainType ) ; } private void setTopLevelTypeOnly ( boolean show ) { fShowOnlyMainType = show ; setChecked ( show ) ; Tree tree = fOutlineViewer . getTree ( ) ; tree . setRedraw ( false ) ; fOutlineViewer . refresh ( false ) ; if ( ! fShowOnlyMainType ) fOutlineViewer . expandToLevel ( ) ; Object selectedElement = getSelectedElement ( ) ; if ( selectedElement != null ) fOutlineViewer . reveal ( selectedElement ) ; tree . setRedraw ( true ) ; getDialogSettings ( ) . put ( STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED , show ) ; } } private class OutlineSorter extends AbstractHierarchyViewerSorter { protected ITypeHierarchy getHierarchy ( IType type ) { return getSuperTypeHierarchy ( type ) ; } public boolean isSortByDefiningType ( ) { return fSortByDefiningTypeAction . isChecked ( ) ; } public boolean isSortAlphabetically ( ) { return fLexicalSortingAction . isChecked ( ) ; } } private class LexicalSortingAction extends Action { private static final String STORE_LEXICAL_SORTING_CHECKED = "" ; private TreeViewer fOutlineViewer ; private LexicalSortingAction ( TreeViewer outlineViewer ) { super ( TextMessages . RubyOutlineInformationControl_LexicalSortingAction_label , IAction . AS_CHECK_BOX ) ; setToolTipText ( TextMessages . RubyOutlineInformationControl_LexicalSortingAction_tooltip ) ; setDescription ( TextMessages . RubyOutlineInformationControl_LexicalSortingAction_description ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; fOutlineViewer = outlineViewer ; boolean checked = getDialogSettings ( ) . getBoolean ( STORE_LEXICAL_SORTING_CHECKED ) ; setChecked ( checked ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . LEXICAL_SORTING_BROWSING_ACTION ) ; } public void run ( ) { valueChanged ( isChecked ( ) , true ) ; } private void valueChanged ( final boolean on , boolean store ) { setChecked ( on ) ; BusyIndicator . showWhile ( fOutlineViewer . getControl ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fOutlineViewer . refresh ( false ) ; } } ) ; if ( store ) getDialogSettings ( ) . put ( STORE_LEXICAL_SORTING_CHECKED , on ) ; } } private class SortByDefiningTypeAction extends Action { private static final String STORE_SORT_BY_DEFINING_TYPE_CHECKED = "" ; private TreeViewer fOutlineViewer ; private SortByDefiningTypeAction ( TreeViewer outlineViewer ) { super ( TextMessages . RubyOutlineInformationControl_SortByDefiningTypeAction_label ) ; setDescription ( TextMessages . RubyOutlineInformationControl_SortByDefiningTypeAction_description ) ; setToolTipText ( TextMessages . RubyOutlineInformationControl_SortByDefiningTypeAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; fOutlineViewer = outlineViewer ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . SORT_BY_DEFINING_TYPE_ACTION ) ; boolean state = getDialogSettings ( ) . getBoolean ( STORE_SORT_BY_DEFINING_TYPE_CHECKED ) ; setChecked ( state ) ; fInnerLabelProvider . setShowDefiningType ( state ) ; } public void run ( ) { BusyIndicator . showWhile ( fOutlineViewer . getControl ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fInnerLabelProvider . setShowDefiningType ( isChecked ( ) ) ; getDialogSettings ( ) . put ( STORE_SORT_BY_DEFINING_TYPE_CHECKED , isChecked ( ) ) ; setMatcherString ( fPattern , false ) ; fOutlineViewer . refresh ( true ) ; Object selectedElement = getSelectedElement ( ) ; if ( selectedElement != null ) fOutlineViewer . reveal ( selectedElement ) ; } } ) ; } } private static class OrStringMatcher extends StringMatcher { private StringMatcher fMatcher1 ; private StringMatcher fMatcher2 ; private OrStringMatcher ( String pattern1 , String pattern2 , boolean ignoreCase , boolean foo ) { super ( "" , false , false ) ; fMatcher1 = new StringMatcher ( pattern1 , ignoreCase , false ) ; fMatcher2 = new StringMatcher ( pattern2 , ignoreCase , false ) ; } public boolean match ( String text ) { return fMatcher2 . match ( text ) || fMatcher1 . match ( text ) ; } } public RubyOutlineInformationControl ( Shell parent , int shellStyle , int treeStyle , String commandId ) { super ( parent , shellStyle , treeStyle , commandId , true ) ; } protected Text createFilterText ( Composite parent ) { Text text = super . createFilterText ( parent ) ; text . addKeyListener ( getKeyAdapter ( ) ) ; return text ; } protected TreeViewer createTreeViewer ( Composite parent , int style ) { Tree tree = new Tree ( parent , SWT . SINGLE | ( style & ~ SWT . MULTI ) ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; gd . heightHint = tree . getItemHeight ( ) * ; tree . setLayoutData ( gd ) ; final TreeViewer treeViewer = new OutlineTreeViewer ( tree ) ; treeViewer . addFilter ( new NamePatternFilter ( ) ) ; treeViewer . addFilter ( new MemberFilter ( ) ) ; fForegroundColor = parent . getDisplay ( ) . getSystemColor ( SWT . COLOR_DARK_GRAY ) ; fInnerLabelProvider = new OutlineLabelProvider ( ) ; fInnerLabelProvider . addLabelDecorator ( new ProblemsLabelDecorator ( null ) ) ; IDecoratorManager decoratorMgr = PlatformUI . getWorkbench ( ) . getDecoratorManager ( ) ; if ( decoratorMgr . getEnabled ( "" ) ) fInnerLabelProvider . addLabelDecorator ( new OverrideIndicatorLabelDecorator ( null ) ) ; treeViewer . setLabelProvider ( fInnerLabelProvider ) ; fLexicalSortingAction = new LexicalSortingAction ( treeViewer ) ; fSortByDefiningTypeAction = new SortByDefiningTypeAction ( treeViewer ) ; fShowOnlyMainTypeAction = new ShowOnlyMainTypeAction ( treeViewer ) ; fOutlineContentProvider = new OutlineContentProvider ( false ) ; treeViewer . setContentProvider ( fOutlineContentProvider ) ; fOutlineSorter = new OutlineSorter ( ) ; treeViewer . setSorter ( fOutlineSorter ) ; treeViewer . setAutoExpandLevel ( AbstractTreeViewer . ALL_LEVELS ) ; treeViewer . getTree ( ) . addKeyListener ( getKeyAdapter ( ) ) ; return treeViewer ; } protected String getStatusFieldText ( ) { KeySequence [ ] sequences = getInvokingCommandKeySequences ( ) ; if ( sequences == null || sequences . length == ) return "" ; String keySequence = sequences [ ] . format ( ) ; if ( fOutlineContentProvider . isShowingInheritedMembers ( ) ) return Messages . format ( RubyUIMessages . RubyOutlineControl_statusFieldText_hideInheritedMembers , keySequence ) ; else return Messages . format ( RubyUIMessages . RubyOutlineControl_statusFieldText_showInheritedMembers , keySequence ) ; } protected String getId ( ) { return "" ; } public void setInput ( Object information ) { if ( information == null || information instanceof String ) { inputChanged ( null , null ) ; return ; } IRubyElement je = ( IRubyElement ) information ; IRubyScript cu = ( IRubyScript ) je . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) fInput = cu ; inputChanged ( fInput , information ) ; } private KeyAdapter getKeyAdapter ( ) { if ( fKeyAdapter == null ) { fKeyAdapter = new KeyAdapter ( ) { public void keyPressed ( KeyEvent e ) { int accelerator = SWTKeySupport . convertEventToUnmodifiedAccelerator ( e ) ; KeySequence keySequence = KeySequence . getInstance ( SWTKeySupport . convertAcceleratorToKeyStroke ( accelerator ) ) ; KeySequence [ ] sequences = getInvokingCommandKeySequences ( ) ; if ( sequences == null ) return ; for ( int i = ; i < sequences . length ; i ++ ) { if ( sequences [ i ] . equals ( keySequence ) ) { e . doit = false ; toggleShowInheritedMembers ( ) ; return ; } } } } ; } return fKeyAdapter ; } protected void handleStatusFieldClicked ( ) { toggleShowInheritedMembers ( ) ; } protected void toggleShowInheritedMembers ( ) { long flags = fInnerLabelProvider . getTextFlags ( ) ; flags ^= RubyElementLabels . ALL_POST_QUALIFIED ; fInnerLabelProvider . setTextFlags ( flags ) ; fOutlineContentProvider . toggleShowInheritedMembers ( ) ; updateStatusFieldText ( ) ; } protected void fillViewMenu ( IMenuManager viewMenu ) { super . fillViewMenu ( viewMenu ) ; viewMenu . add ( fShowOnlyMainTypeAction ) ; viewMenu . add ( new Separator ( "" ) ) ; viewMenu . add ( fLexicalSortingAction ) ; } protected void setMatcherString ( String pattern , boolean update ) { fPattern = pattern ; if ( pattern . length ( ) == || ! fSortByDefiningTypeAction . isChecked ( ) ) { super . setMatcherString ( pattern , update ) ; return ; } boolean ignoreCase = pattern . toLowerCase ( ) . equals ( pattern ) ; String pattern2 = "" + RubyElementLabels . CONCAT_STRING + pattern ; fStringMatcher = new OrStringMatcher ( pattern , pattern2 , ignoreCase , false ) ; if ( update ) stringMatcherUpdated ( ) ; } private ITypeHierarchy getSuperTypeHierarchy ( IType type ) { ITypeHierarchy th = ( ITypeHierarchy ) fTypeHierarchies . get ( type ) ; if ( th == null ) { try { th = SuperTypeHierarchyCache . getTypeHierarchy ( type , getProgressMonitor ( ) ) ; } catch ( RubyModelException e ) { return null ; } catch ( OperationCanceledException e ) { return null ; } fTypeHierarchies . put ( type , th ) ; } return th ; } private IProgressMonitor getProgressMonitor ( ) { IWorkbenchPage wbPage = RubyPlugin . getActivePage ( ) ; if ( wbPage == null ) return null ; IEditorPart editor = wbPage . getActiveEditor ( ) ; if ( editor == null ) return null ; return editor . getEditorSite ( ) . getActionBars ( ) . getStatusLineManager ( ) . getProgressMonitor ( ) ; } private IType getMainType ( IRubyScript compilationUnit ) { if ( compilationUnit == null ) return null ; return compilationUnit . findPrimaryType ( ) ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextDoubleClickStrategy ; import org . eclipse . jface . text . ITextViewer ; public class RubyDoubleClickSelector implements ITextDoubleClickStrategy { public void doubleClicked ( ITextViewer text ) { int position = text . getSelectedRange ( ) . x ; if ( position < ) return ; IRegion region = RubyWordFinder . findWord ( text . getDocument ( ) , position ) ; if ( region != null && region . getLength ( ) != ) text . setSelectedRange ( region . getOffset ( ) , region . getLength ( ) ) ; } } package org . rubypeople . rdt . internal . ui . text . comment ; import org . eclipse . jface . text . formatter . FormattingContext ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; public class CommentFormattingContext extends FormattingContext { public String [ ] getPreferenceKeys ( ) { return new String [ ] { DefaultCodeFormatterConstants . FORMATTER_COMMENT_FORMAT , DefaultCodeFormatterConstants . FORMATTER_COMMENT_FORMAT_HEADER , DefaultCodeFormatterConstants . FORMATTER_COMMENT_LINE_LENGTH , DefaultCodeFormatterConstants . FORMATTER_COMMENT_CLEAR_BLANK_LINES } ; } public boolean isBooleanPreference ( String key ) { return ! key . equals ( DefaultCodeFormatterConstants . FORMATTER_COMMENT_LINE_LENGTH ) ; } public boolean isIntegerPreference ( String key ) { return key . equals ( DefaultCodeFormatterConstants . FORMATTER_COMMENT_LINE_LENGTH ) ; } } package org . rubypeople . rdt . internal . ui . text . comment ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultIndentLineAutoEditStrategy ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . ui . texteditor . ITextEditor ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . corext . util . CodeFormatterUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . WorkingCopyManager ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; public class RubyCommentAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { private String fPartitioning ; private ITextEditor fEditor ; private WorkingCopyManager fManager ; private IRubyProject fProject ; public RubyCommentAutoIndentStrategy ( ITextEditor textEditor , String partitioning , IRubyProject project ) { fPartitioning = partitioning ; fEditor = textEditor ; fManager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; fProject = project ; } public void customizeDocumentCommand ( IDocument document , DocumentCommand command ) { if ( command . text != null ) { if ( command . length == ) { String [ ] lineDelimiters = document . getLegalLineDelimiters ( ) ; int index = TextUtilities . endsWith ( lineDelimiters , command . text ) ; if ( index > - ) { if ( lineDelimiters [ index ] . equals ( command . text ) ) indentAfterNewLine ( document , command ) ; return ; } } } } private void indentAfterNewLine ( IDocument d , DocumentCommand c ) { if ( fPartitioning . equals ( IRubyPartitions . RUBY_SINGLE_LINE_COMMENT ) ) { doSingleLineComment ( d , c ) ; } else { doMultiLineComment ( d , c ) ; } } private void doMultiLineComment ( IDocument d , DocumentCommand c ) { int offset = c . offset ; if ( offset == - || d . getLength ( ) == ) return ; try { int p = ( offset == d . getLength ( ) ? offset - : offset ) ; try { new RubyParser ( ) . parse ( d . get ( ) ) ; return ; } catch ( SyntaxException se ) { if ( ! se . getMessage ( ) . equals ( "" ) ) { return ; } } int lineNumber = d . getLineOfOffset ( p ) ; IRegion line = d . getLineInformation ( lineNumber ) ; String aLine = getLine ( d , lineNumber - ) ; StringBuffer buf = new StringBuffer ( c . text ) ; if ( aLine . trim ( ) . equals ( "" ) ) { buf . append ( CodeFormatterUtil . createIndentString ( , fProject ) ) ; c . caretOffset = c . offset + buf . length ( ) ; c . shiftsCaret = false ; buf . append ( TextUtilities . getDefaultLineDelimiter ( d ) ) ; buf . append ( "" ) ; } c . text = buf . toString ( ) ; } catch ( BadLocationException excp ) { } } private void doSingleLineComment ( IDocument d , DocumentCommand c ) { int offset = c . offset ; if ( offset == - || d . getLength ( ) == ) return ; try { int p = ( offset == d . getLength ( ) ? offset - : offset ) ; int lineNumber = d . getLineOfOffset ( p ) ; IRegion line = d . getLineInformation ( lineNumber ) ; if ( lineNumber != ) { String nextLine = getLine ( d , lineNumber + ) ; if ( ! ( isComment ( nextLine ) || isClassDefinition ( nextLine ) || isMethodDeclaration ( nextLine ) || isAttributeCall ( nextLine ) || isAliasCall ( nextLine ) || isModuleDeclaration ( nextLine ) || isConstantAssignment ( nextLine ) ) ) { String previousLine = getLine ( d , lineNumber - ) ; if ( ! isComment ( previousLine ) ) return ; } } int lineOffset = line . getOffset ( ) ; int firstNonWS = findEndOfWhiteSpace ( d , lineOffset , offset ) ; Assert . isTrue ( firstNonWS >= lineOffset , "" ) ; StringBuffer buf = new StringBuffer ( c . text ) ; IRegion prefix = findPrefixRange ( d , line ) ; String indentation = d . get ( prefix . getOffset ( ) , prefix . getLength ( ) ) ; int lengthToAdd = Math . min ( offset - prefix . getOffset ( ) , prefix . getLength ( ) ) ; buf . append ( indentation . substring ( , lengthToAdd ) ) ; String src = getRDoc ( d , c . text , lineNumber + ) ; if ( src != null ) buf . append ( src ) ; if ( lengthToAdd < prefix . getLength ( ) ) c . caretOffset = offset + prefix . getLength ( ) - lengthToAdd ; c . text = buf . toString ( ) ; } catch ( BadLocationException excp ) { } } private String getRDoc ( IDocument d , String newLine , int line ) { IRubyScript script = fManager . getWorkingCopy ( fEditor . getEditorInput ( ) ) ; int pos ; try { IRegion region = d . getLineInformation ( line ) ; pos = findEndOfWhiteSpace ( d , region . getOffset ( ) , region . getOffset ( ) + region . getLength ( ) ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; return null ; } IRubyElement element = null ; try { element = script . getElementAt ( pos ) ; if ( element == null ) return null ; StringBuffer buffer = new StringBuffer ( ) ; if ( element instanceof IMethod ) { IMethod method = ( IMethod ) element ; String [ ] names = method . getParameterNames ( ) ; for ( int i = ; i < names . length ; i ++ ) { String name = names [ i ] ; int end = name . indexOf ( '' ) ; if ( end != - ) { name = name . substring ( , end ) ; } buffer . append ( "" ) ; buffer . append ( name ) ; buffer . append ( "" ) ; buffer . append ( newLine ) ; } } return buffer . toString ( ) ; } catch ( RubyModelException e ) { e . printStackTrace ( ) ; return null ; } } private boolean isComment ( String nextLineText ) { return nextLineText . matches ( "" ) ; } private boolean isClassDefinition ( String nextLineText ) { return nextLineText . matches ( "" ) ; } private boolean isAliasCall ( String nextLineText ) { return nextLineText . matches ( "" ) ; } private boolean isModuleDeclaration ( String nextLineText ) { return nextLineText . matches ( "" ) ; } private boolean isMethodDeclaration ( String nextLineText ) { return nextLineText . matches ( "" ) ; } private boolean isAttributeCall ( String nextLineText ) { return nextLineText . matches ( "" ) ; } private boolean isConstantAssignment ( String nextLineText ) { return nextLineText . matches ( "" ) ; } private String getLine ( IDocument d , int lineNum ) throws BadLocationException { IRegion nextLineRegion = d . getLineInformation ( lineNum + ) ; return d . get ( nextLineRegion . getOffset ( ) , nextLineRegion . getLength ( ) ) ; } private IRegion findPrefixRange ( IDocument document , IRegion line ) throws BadLocationException { int lineOffset = line . getOffset ( ) ; int lineEnd = lineOffset + line . getLength ( ) ; int indentEnd = findEndOfWhiteSpace ( document , lineOffset , lineEnd ) ; if ( indentEnd < lineEnd && document . getChar ( indentEnd ) == '' ) { indentEnd ++ ; while ( indentEnd < lineEnd && document . getChar ( indentEnd ) == '' ) indentEnd ++ ; } return new Region ( lineOffset , indentEnd - lineOffset ) ; } } package org . rubypeople . rdt . internal . ui . text . comment ; import java . util . LinkedList ; import java . util . Map ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . text . TypedPosition ; import org . eclipse . jface . text . formatter . ContextBasedFormattingStrategy ; import org . eclipse . jface . text . formatter . FormattingContextProperties ; import org . eclipse . jface . text . formatter . IFormattingContext ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . core . ToolFactory ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; public class CommentFormattingStrategy extends ContextBasedFormattingStrategy { private final LinkedList fDocuments = new LinkedList ( ) ; private final LinkedList fPartitions = new LinkedList ( ) ; private int fLastDocumentHash ; private int fLastHeaderHash ; private int fLastMainTokenEnd = - ; private int fLastDocumentsHeaderEnd ; public void format ( ) { super . format ( ) ; final IDocument document = ( IDocument ) fDocuments . removeFirst ( ) ; final TypedPosition position = ( TypedPosition ) fPartitions . removeFirst ( ) ; if ( document == null || position == null ) return ; Map preferences = getPreferences ( ) ; final boolean isFormattingHeader = Boolean . toString ( true ) . equals ( preferences . get ( DefaultCodeFormatterConstants . FORMATTER_COMMENT_FORMAT_HEADER ) ) ; int documentsHeaderEnd = computeHeaderEnd ( document ) ; if ( isFormattingHeader || position . offset >= documentsHeaderEnd ) { TextEdit edit = null ; try { int sourceOffset = document . getLineOffset ( document . getLineOfOffset ( position . getOffset ( ) ) ) ; int partitionOffset = position . getOffset ( ) - sourceOffset ; int sourceLength = partitionOffset + position . getLength ( ) ; String source = document . get ( sourceOffset , sourceLength ) ; CodeFormatter commentFormatter = ToolFactory . createCodeFormatter ( preferences ) ; int indentationLevel = inferIndentationLevel ( source . substring ( , partitionOffset ) , getTabSize ( preferences ) ) ; edit = commentFormatter . format ( getKindForPartitionType ( position . getType ( ) ) , source , partitionOffset , position . getLength ( ) , indentationLevel , TextUtilities . getDefaultLineDelimiter ( document ) ) ; if ( edit != null ) edit . moveTree ( sourceOffset ) ; } catch ( BadLocationException x ) { RubyPlugin . log ( x ) ; } try { if ( edit != null ) edit . apply ( document ) ; } catch ( MalformedTreeException x ) { RubyPlugin . log ( x ) ; } catch ( BadLocationException x ) { RubyPlugin . log ( x ) ; } } } public void formatterStarts ( IFormattingContext context ) { super . formatterStarts ( context ) ; fPartitions . addLast ( context . getProperty ( FormattingContextProperties . CONTEXT_PARTITION ) ) ; fDocuments . addLast ( context . getProperty ( FormattingContextProperties . CONTEXT_MEDIUM ) ) ; } public void formatterStops ( ) { fPartitions . clear ( ) ; fDocuments . clear ( ) ; super . formatterStops ( ) ; } private static int getKindForPartitionType ( String type ) { if ( IRubyPartitions . RUBY_SINGLE_LINE_COMMENT . equals ( type ) ) return CodeFormatter . K_SINGLE_LINE_COMMENT ; if ( IRubyPartitions . RUBY_MULTI_LINE_COMMENT . equals ( type ) ) return CodeFormatter . K_MULTI_LINE_COMMENT ; return CodeFormatter . K_UNKNOWN ; } private int inferIndentationLevel ( String reference , int tabSize ) { StringBuffer expanded = expandTabs ( reference , tabSize ) ; int referenceWidth = expanded . length ( ) ; if ( tabSize == ) return referenceWidth ; int spaceWidth = ; int level = referenceWidth / ( tabSize * spaceWidth ) ; if ( referenceWidth % ( tabSize * spaceWidth ) > ) level ++ ; return level ; } private static StringBuffer expandTabs ( String string , int tabSize ) { StringBuffer expanded = new StringBuffer ( ) ; for ( int i = , n = string . length ( ) , chars = ; i < n ; i ++ ) { char ch = string . charAt ( i ) ; if ( ch == '' ) { for ( ; chars < tabSize ; chars ++ ) expanded . append ( '' ) ; chars = ; } else { expanded . append ( ch ) ; chars ++ ; if ( chars >= tabSize ) chars = ; } } return expanded ; } private static int getTabSize ( Map preferences ) { if ( preferences . containsKey ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) ) try { return Integer . parseInt ( ( String ) preferences . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) ) ; } catch ( NumberFormatException e ) { } return ; } private int computeHeaderEnd ( IDocument document ) { if ( document == null ) return - ; try { if ( fLastMainTokenEnd >= && document . hashCode ( ) == fLastDocumentHash && fLastMainTokenEnd < document . getLength ( ) && document . get ( , fLastMainTokenEnd ) . hashCode ( ) == fLastHeaderHash ) return fLastDocumentsHeaderEnd ; } catch ( BadLocationException e ) { } return - ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . ContentAssistant ; import org . eclipse . jface . text . contentassist . IContentAssistProcessor ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyCompletionProcessor ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . IColorManager ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class ContentAssistPreference { private final static String AUTOACTIVATION = PreferenceConstants . CODEASSIST_AUTOACTIVATION ; private final static String AUTOACTIVATION_DELAY = PreferenceConstants . CODEASSIST_AUTOACTIVATION_DELAY ; private final static String PROPOSALS_FOREGROUND = PreferenceConstants . CODEASSIST_PROPOSALS_FOREGROUND ; private final static String PROPOSALS_BACKGROUND = PreferenceConstants . CODEASSIST_PROPOSALS_BACKGROUND ; private final static String PARAMETERS_FOREGROUND = PreferenceConstants . CODEASSIST_PARAMETERS_FOREGROUND ; private final static String PARAMETERS_BACKGROUND = PreferenceConstants . CODEASSIST_PARAMETERS_BACKGROUND ; private final static String AUTOINSERT = PreferenceConstants . CODEASSIST_AUTOINSERT ; private static final String PREFIX_COMPLETION = PreferenceConstants . CODEASSIST_PREFIX_COMPLETION ; private final static String AUTOACTIVATION_TRIGGERS_RUBY = PreferenceConstants . CODEASSIST_AUTOACTIVATION_TRIGGERS_RUBY ; public static void changeConfiguration ( ContentAssistant assistant , IPreferenceStore store , PropertyChangeEvent event ) { String p = event . getProperty ( ) ; if ( AUTOACTIVATION . equals ( p ) ) { boolean enabled = store . getBoolean ( AUTOACTIVATION ) ; assistant . enableAutoActivation ( enabled ) ; } else if ( AUTOACTIVATION_DELAY . equals ( p ) ) { int delay = store . getInt ( AUTOACTIVATION_DELAY ) ; assistant . setAutoActivationDelay ( delay ) ; } else if ( PROPOSALS_FOREGROUND . equals ( p ) ) { Color c = getColor ( store , PROPOSALS_FOREGROUND ) ; assistant . setProposalSelectorForeground ( c ) ; } else if ( PROPOSALS_BACKGROUND . equals ( p ) ) { Color c = getColor ( store , PROPOSALS_BACKGROUND ) ; assistant . setProposalSelectorBackground ( c ) ; } else if ( PARAMETERS_FOREGROUND . equals ( p ) ) { Color c = getColor ( store , PARAMETERS_FOREGROUND ) ; assistant . setContextInformationPopupForeground ( c ) ; assistant . setContextSelectorForeground ( c ) ; } else if ( PARAMETERS_BACKGROUND . equals ( p ) ) { Color c = getColor ( store , PARAMETERS_BACKGROUND ) ; assistant . setContextInformationPopupBackground ( c ) ; assistant . setContextSelectorBackground ( c ) ; } else if ( AUTOINSERT . equals ( p ) ) { boolean enabled = store . getBoolean ( AUTOINSERT ) ; assistant . enableAutoInsert ( enabled ) ; } else if ( PREFIX_COMPLETION . equals ( p ) ) { boolean enabled = store . getBoolean ( PREFIX_COMPLETION ) ; assistant . enablePrefixCompletion ( enabled ) ; } changeRubyProcessor ( assistant , store , p ) ; } public static void configure ( ContentAssistant assistant , IPreferenceStore store ) { RubyTextTools textTools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; IColorManager manager = textTools . getColorManager ( ) ; boolean enabled = store . getBoolean ( AUTOACTIVATION ) ; assistant . enableAutoActivation ( enabled ) ; int delay = store . getInt ( AUTOACTIVATION_DELAY ) ; assistant . setAutoActivationDelay ( delay ) ; Color c = getColor ( store , PROPOSALS_FOREGROUND , manager ) ; assistant . setProposalSelectorForeground ( c ) ; c = getColor ( store , PROPOSALS_BACKGROUND , manager ) ; assistant . setProposalSelectorBackground ( c ) ; c = getColor ( store , PARAMETERS_FOREGROUND , manager ) ; assistant . setContextInformationPopupForeground ( c ) ; assistant . setContextSelectorForeground ( c ) ; c = getColor ( store , PARAMETERS_BACKGROUND , manager ) ; assistant . setContextInformationPopupBackground ( c ) ; assistant . setContextSelectorBackground ( c ) ; enabled = store . getBoolean ( AUTOINSERT ) ; assistant . enableAutoInsert ( enabled ) ; enabled = store . getBoolean ( PREFIX_COMPLETION ) ; assistant . enablePrefixCompletion ( enabled ) ; configureRubyProcessor ( assistant , store ) ; } private static void configureRubyProcessor ( ContentAssistant assistant , IPreferenceStore store ) { RubyCompletionProcessor jcp = getRubyProcessor ( assistant ) ; if ( jcp == null ) return ; String triggers = store . getString ( AUTOACTIVATION_TRIGGERS_RUBY ) ; if ( triggers != null ) jcp . setCompletionProposalAutoActivationCharacters ( triggers . toCharArray ( ) ) ; } private static Color getColor ( IPreferenceStore store , String key , IColorManager manager ) { RGB rgb = PreferenceConverter . getColor ( store , key ) ; return manager . getColor ( rgb ) ; } private static Color getColor ( IPreferenceStore store , String key ) { RubyTextTools textTools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; return getColor ( store , key , textTools . getColorManager ( ) ) ; } private static void changeRubyProcessor ( ContentAssistant assistant , IPreferenceStore store , String key ) { RubyCompletionProcessor jcp = getRubyProcessor ( assistant ) ; if ( jcp == null ) return ; if ( AUTOACTIVATION_TRIGGERS_RUBY . equals ( key ) ) { String triggers = store . getString ( AUTOACTIVATION_TRIGGERS_RUBY ) ; if ( triggers != null ) jcp . setCompletionProposalAutoActivationCharacters ( triggers . toCharArray ( ) ) ; } } private static RubyCompletionProcessor getRubyProcessor ( ContentAssistant assistant ) { IContentAssistProcessor p = assistant . getContentAssistProcessor ( IDocument . DEFAULT_CONTENT_TYPE ) ; if ( p instanceof RubyCompletionProcessor ) return ( RubyCompletionProcessor ) p ; return null ; } } package org . rubypeople . rdt . internal . ui . text ; import java . io . EOFException ; import org . eclipse . jface . text . rules . ICharacterScanner ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . MultiLineRule ; public class DocumentationCommentRule extends MultiLineRule { private final static String endSequence = "" ; public DocumentationCommentRule ( IToken token ) { super ( "" , "" , token ) ; setColumnConstraint ( ) ; } @ Override protected boolean endSequenceDetected ( ICharacterScanner scanner ) { if ( scanner . getColumn ( ) != ) return false ; String line = "" ; do { try { line = readLine ( scanner ) ; } catch ( EOFException e ) { return true ; } } while ( ! endSequence . equals ( line ) ) ; return true ; } private String readLine ( ICharacterScanner scanner ) throws EOFException { StringBuffer line = new StringBuffer ( ) ; while ( true ) { int c = scanner . read ( ) ; if ( ( char ) c == '' || ( char ) c == '' ) break ; else if ( c == ICharacterScanner . EOF ) throw new EOFException ( ) ; else line . append ( ( char ) c ) ; } return line . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . text ; import java . util . ArrayList ; import java . util . Iterator ; import org . eclipse . jface . text . reconciler . DirtyRegion ; import org . eclipse . jface . text . reconciler . IReconcilingStrategy ; import org . eclipse . jface . text . reconciler . MonoReconciler ; public class NotifyingReconciler extends MonoReconciler { private ArrayList fReconcilingParticipants = new ArrayList ( ) ; public NotifyingReconciler ( IReconcilingStrategy strategy , boolean isIncremental ) { super ( strategy , isIncremental ) ; } protected void process ( DirtyRegion dirtyRegion ) { super . process ( dirtyRegion ) ; notifyReconcilingParticipants ( ) ; } public void addReconcilingParticipant ( IReconcilingParticipant participant ) { fReconcilingParticipants . add ( participant ) ; } public void removeReconcilingParticipant ( IReconcilingParticipant participant ) { fReconcilingParticipants . remove ( participant ) ; } protected void notifyReconcilingParticipants ( ) { Iterator i = new ArrayList ( fReconcilingParticipants ) . iterator ( ) ; while ( i . hasNext ( ) ) { ( ( IReconcilingParticipant ) i . next ( ) ) . reconciled ( ) ; } } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . rules . IPartitionTokenScanner ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . Token ; public class MergingPartitionScanner implements IPartitionTokenScanner { private RubyPartitionScanner fScanner ; private int fOffset ; private int fLength ; private int newOffset = ; private int newLength = ; private IToken lastToken ; public MergingPartitionScanner ( ) { fScanner = new RubyPartitionScanner ( ) ; } public void setPartialRange ( IDocument document , int offset , int length , String contentType , int partitionOffset ) { clear ( ) ; fScanner . setPartialRange ( document , offset , length , contentType , partitionOffset ) ; } public int getTokenLength ( ) { return fLength ; } public int getTokenOffset ( ) { return fOffset ; } public IToken nextToken ( ) { setLength ( newLength ) ; setOffset ( newOffset ) ; if ( lastToken != null && lastToken . isEOF ( ) ) { return lastToken ; } IToken token = null ; while ( ! ( token = fScanner . nextToken ( ) ) . isEOF ( ) ) { if ( lastToken != null && token . getData ( ) . equals ( lastToken . getData ( ) ) ) { continue ; } if ( lastToken == null ) { lastToken = token ; setOffset ( fScanner . getTokenOffset ( ) ) ; setLength ( fScanner . getTokenLength ( ) ) ; continue ; } return wrapUp ( token ) ; } if ( lastToken == null ) { return Token . EOF ; } return wrapUp ( token ) ; } private IToken wrapUp ( IToken token ) { setLength ( fScanner . getTokenOffset ( ) - fOffset ) ; newOffset = fScanner . getTokenOffset ( ) ; newLength = fScanner . getTokenLength ( ) ; Assert . isTrue ( newLength >= ) ; IToken returnToken = lastToken ; lastToken = token ; return returnToken ; } private void setOffset ( int tokenOffset ) { fOffset = tokenOffset ; } private void setLength ( int tokenLength ) { Assert . isTrue ( tokenLength >= ) ; fLength = tokenLength ; } public void setRange ( IDocument document , int offset , int length ) { clear ( ) ; fScanner . setRange ( document , offset , length ) ; } private void clear ( ) { lastToken = null ; fLength = ; fOffset = ; newLength = ; newOffset = ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextPresentation ; import org . eclipse . jface . text . presentation . PresentationReconciler ; public class RubyPresentationReconciler extends PresentationReconciler { private IDocument fLastDocument ; public TextPresentation createRepairDescription ( IRegion damage , IDocument document ) { if ( document != fLastDocument ) { setDocumentToDamagers ( document ) ; setDocumentToRepairers ( document ) ; fLastDocument = document ; } return createPresentation ( damage , document ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . IWorkingSetUpdater ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class OthersWorkingSetUpdater implements IWorkingSetUpdater { public static final String ID = "" ; private IWorkingSet fWorkingSet ; private WorkingSetModel fWorkingSetModel ; private class ResourceChangeListener implements IResourceChangeListener { public void resourceChanged ( IResourceChangeEvent event ) { if ( fWorkingSet == null ) return ; IResourceDelta delta = event . getDelta ( ) ; IResourceDelta [ ] affectedChildren = delta . getAffectedChildren ( IResourceDelta . ADDED | IResourceDelta . REMOVED , IResource . PROJECT ) ; if ( affectedChildren . length > ) { updateElements ( ) ; } else { affectedChildren = delta . getAffectedChildren ( IResourceDelta . CHANGED , IResource . PROJECT ) ; for ( int i = ; i < affectedChildren . length ; i ++ ) { IResourceDelta projectDelta = affectedChildren [ i ] ; if ( ( projectDelta . getFlags ( ) & IResourceDelta . DESCRIPTION ) != ) { updateElements ( ) ; return ; } } } } } private IResourceChangeListener fResourceChangeListener ; private class WorkingSetListener implements IPropertyChangeListener { public void propertyChange ( PropertyChangeEvent event ) { if ( IWorkingSetManager . CHANGE_WORKING_SET_CONTENT_CHANGE . equals ( event . getProperty ( ) ) ) { IWorkingSet changedWorkingSet = ( IWorkingSet ) event . getNewValue ( ) ; if ( changedWorkingSet != fWorkingSet && fWorkingSetModel . isActiveWorkingSet ( changedWorkingSet ) ) { updateElements ( ) ; } } } } private IPropertyChangeListener fWorkingSetListener ; private class RubyElementChangeListener implements IElementChangedListener { public void elementChanged ( ElementChangedEvent event ) { if ( fWorkingSet == null ) return ; processRubyDelta ( new ArrayList ( Arrays . asList ( fWorkingSet . getElements ( ) ) ) , event . getDelta ( ) ) ; } private void processRubyDelta ( List elements , IRubyElementDelta delta ) { IRubyElement jElement = delta . getElement ( ) ; int type = jElement . getElementType ( ) ; if ( type == IRubyElement . RUBY_PROJECT ) { int index = elements . indexOf ( jElement ) ; int kind = delta . getKind ( ) ; int flags = delta . getFlags ( ) ; if ( kind == IRubyElementDelta . CHANGED ) { if ( index != - && ( flags & IRubyElementDelta . F_CLOSED ) != ) { elements . set ( index , ( ( IRubyProject ) jElement ) . getProject ( ) ) ; fWorkingSet . setElements ( ( IAdaptable [ ] ) elements . toArray ( new IAdaptable [ elements . size ( ) ] ) ) ; } else if ( ( flags & IRubyElementDelta . F_OPENED ) != ) { index = elements . indexOf ( ( ( IRubyProject ) jElement ) . getProject ( ) ) ; if ( index != - ) { elements . set ( index , jElement ) ; fWorkingSet . setElements ( ( IAdaptable [ ] ) elements . toArray ( new IAdaptable [ elements . size ( ) ] ) ) ; } } } return ; } IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { processRubyDelta ( elements , children [ i ] ) ; } } } private IElementChangedListener fRubyElementChangeListener ; public void add ( IWorkingSet workingSet ) { Assert . isTrue ( fWorkingSet == null && fWorkingSetModel != null ) ; fWorkingSet = workingSet ; } public boolean remove ( IWorkingSet workingSet ) { Assert . isTrue ( fWorkingSet == workingSet ) ; fWorkingSet = null ; return true ; } public boolean contains ( IWorkingSet workingSet ) { return fWorkingSet == workingSet ; } public void init ( WorkingSetModel model ) { fWorkingSetModel = model ; fResourceChangeListener = new ResourceChangeListener ( ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( fResourceChangeListener , IResourceChangeEvent . POST_CHANGE ) ; fWorkingSetListener = new WorkingSetListener ( ) ; PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . addPropertyChangeListener ( fWorkingSetListener ) ; fRubyElementChangeListener = new RubyElementChangeListener ( ) ; RubyCore . addElementChangedListener ( fRubyElementChangeListener , ElementChangedEvent . POST_CHANGE ) ; } public void dispose ( ) { if ( fResourceChangeListener != null ) { ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( fResourceChangeListener ) ; fResourceChangeListener = null ; } if ( fWorkingSetListener != null ) { PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . removePropertyChangeListener ( fWorkingSetListener ) ; fWorkingSetListener = null ; } if ( fRubyElementChangeListener != null ) { RubyCore . removeElementChangedListener ( fRubyElementChangeListener ) ; } } public void updateElements ( ) { Assert . isTrue ( fWorkingSet != null && fWorkingSetModel != null ) ; IWorkingSet [ ] activeWorkingSets = fWorkingSetModel . getActiveWorkingSets ( ) ; List result = new ArrayList ( ) ; Set projects = new HashSet ( ) ; for ( int i = ; i < activeWorkingSets . length ; i ++ ) { if ( activeWorkingSets [ i ] == fWorkingSet ) continue ; IAdaptable [ ] elements = activeWorkingSets [ i ] . getElements ( ) ; for ( int j = ; j < elements . length ; j ++ ) { IAdaptable element = elements [ j ] ; IResource resource = ( IResource ) element . getAdapter ( IResource . class ) ; if ( resource != null && resource . getType ( ) == IResource . PROJECT ) { projects . add ( resource ) ; } } } IRubyModel model = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; try { IRubyProject [ ] jProjects = model . getRubyProjects ( ) ; for ( int i = ; i < jProjects . length ; i ++ ) { if ( ! projects . contains ( jProjects [ i ] . getProject ( ) ) ) result . add ( jProjects [ i ] ) ; } Object [ ] rProjects = model . getNonRubyResources ( ) ; for ( int i = ; i < rProjects . length ; i ++ ) { if ( ! projects . contains ( rProjects [ i ] ) ) result . add ( rProjects [ i ] ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } fWorkingSet . setElements ( ( IAdaptable [ ] ) result . toArray ( new IAdaptable [ result . size ( ) ] ) ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetUpdater ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; public class RubyWorkingSetUpdater implements IWorkingSetUpdater , IElementChangedListener { public static final String ID = "" ; private List fWorkingSets ; private static class WorkingSetDelta { private IWorkingSet fWorkingSet ; private List fElements ; private boolean fChanged ; public WorkingSetDelta ( IWorkingSet workingSet ) { fWorkingSet = workingSet ; fElements = new ArrayList ( Arrays . asList ( workingSet . getElements ( ) ) ) ; } public int indexOf ( Object element ) { return fElements . indexOf ( element ) ; } public void set ( int index , Object element ) { fElements . set ( index , element ) ; fChanged = true ; } public void remove ( int index ) { if ( fElements . remove ( index ) != null ) { fChanged = true ; } } public void process ( ) { if ( fChanged ) { fWorkingSet . setElements ( ( IAdaptable [ ] ) fElements . toArray ( new IAdaptable [ fElements . size ( ) ] ) ) ; } } } public RubyWorkingSetUpdater ( ) { fWorkingSets = new ArrayList ( ) ; RubyCore . addElementChangedListener ( this ) ; } public void add ( IWorkingSet workingSet ) { checkElementExistence ( workingSet ) ; synchronized ( fWorkingSets ) { fWorkingSets . add ( workingSet ) ; } } public boolean remove ( IWorkingSet workingSet ) { boolean result ; synchronized ( fWorkingSets ) { result = fWorkingSets . remove ( workingSet ) ; } return result ; } public boolean contains ( IWorkingSet workingSet ) { synchronized ( fWorkingSets ) { return fWorkingSets . contains ( workingSet ) ; } } public void dispose ( ) { synchronized ( fWorkingSets ) { fWorkingSets . clear ( ) ; } RubyCore . removeElementChangedListener ( this ) ; } public void elementChanged ( ElementChangedEvent event ) { IWorkingSet [ ] workingSets ; synchronized ( fWorkingSets ) { workingSets = ( IWorkingSet [ ] ) fWorkingSets . toArray ( new IWorkingSet [ fWorkingSets . size ( ) ] ) ; } for ( int w = ; w < workingSets . length ; w ++ ) { WorkingSetDelta workingSetDelta = new WorkingSetDelta ( workingSets [ w ] ) ; processRubyDelta ( workingSetDelta , event . getDelta ( ) ) ; IResourceDelta [ ] resourceDeltas = event . getDelta ( ) . getResourceDeltas ( ) ; if ( resourceDeltas != null ) { for ( int r = ; r < resourceDeltas . length ; r ++ ) { processResourceDelta ( workingSetDelta , resourceDeltas [ r ] ) ; } } workingSetDelta . process ( ) ; } } private void processRubyDelta ( WorkingSetDelta result , IRubyElementDelta delta ) { IRubyElement jElement = delta . getElement ( ) ; int index = result . indexOf ( jElement ) ; int type = jElement . getElementType ( ) ; int kind = delta . getKind ( ) ; int flags = delta . getFlags ( ) ; if ( type == IRubyElement . RUBY_PROJECT && kind == IRubyElementDelta . CHANGED ) { if ( index != - && ( flags & IRubyElementDelta . F_CLOSED ) != ) { result . set ( index , ( ( IRubyProject ) jElement ) . getProject ( ) ) ; } else if ( ( flags & IRubyElementDelta . F_OPENED ) != ) { index = result . indexOf ( ( ( IRubyProject ) jElement ) . getProject ( ) ) ; if ( index != - ) result . set ( index , jElement ) ; } } if ( index != - ) { if ( kind == IRubyElementDelta . REMOVED ) { if ( ( flags & IRubyElementDelta . F_MOVED_TO ) != ) { result . set ( index , delta . getMovedToElement ( ) ) ; } else { result . remove ( index ) ; } } } IResourceDelta [ ] resourceDeltas = delta . getResourceDeltas ( ) ; if ( resourceDeltas != null ) { for ( int i = ; i < resourceDeltas . length ; i ++ ) { processResourceDelta ( result , resourceDeltas [ i ] ) ; } } IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { processRubyDelta ( result , children [ i ] ) ; } } private void processResourceDelta ( WorkingSetDelta result , IResourceDelta delta ) { IResource resource = delta . getResource ( ) ; int type = resource . getType ( ) ; int index = result . indexOf ( resource ) ; int kind = delta . getKind ( ) ; int flags = delta . getFlags ( ) ; if ( kind == IResourceDelta . CHANGED && type == IResource . PROJECT && index != - ) { if ( ( flags & IResourceDelta . OPEN ) != ) { result . set ( index , resource ) ; } } if ( index != - && kind == IResourceDelta . REMOVED ) { if ( ( flags & IResourceDelta . MOVED_TO ) != ) { result . set ( index , ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( delta . getMovedToPath ( ) ) ) ; } else { result . remove ( index ) ; } } if ( projectGotClosedOrOpened ( resource , kind , flags ) ) return ; IResourceDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { processResourceDelta ( result , children [ i ] ) ; } } private boolean projectGotClosedOrOpened ( IResource resource , int kind , int flags ) { return resource . getType ( ) == IResource . PROJECT && kind == IResourceDelta . CHANGED && ( flags & IResourceDelta . OPEN ) != ; } private void checkElementExistence ( IWorkingSet workingSet ) { List elements = new ArrayList ( Arrays . asList ( workingSet . getElements ( ) ) ) ; boolean changed = false ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { IAdaptable element = ( IAdaptable ) iter . next ( ) ; boolean remove = false ; if ( element instanceof IRubyElement ) { IRubyElement jElement = ( IRubyElement ) element ; if ( jElement instanceof IRubyProject ) { remove = ! jElement . exists ( ) ; } else { IProject project = jElement . getRubyProject ( ) . getProject ( ) ; remove = project . isOpen ( ) && ! jElement . exists ( ) ; } } else if ( element instanceof IResource ) { IResource resource = ( IResource ) element ; if ( resource instanceof IProject ) { remove = ! resource . exists ( ) ; } else { IProject project = resource . getProject ( ) ; remove = ( project != null ? project . isOpen ( ) : true ) && ! resource . exists ( ) ; } } if ( remove ) { iter . remove ( ) ; changed = true ; } } if ( changed ) { workingSet . setElements ( ( IAdaptable [ ] ) elements . toArray ( new IAdaptable [ elements . size ( ) ] ) ) ; } } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IContributionItem ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . actions . ActionGroup ; public class WorkingSetShowActionGroup extends ActionGroup implements IWorkingSetActionGroup { private List fContributions = new ArrayList ( ) ; private ConfigureWorkingSetAction fConfigureWorkingSetAction ; private WorkingSetModel fWorkingSetModel ; private final IWorkbenchPartSite fSite ; public WorkingSetShowActionGroup ( IWorkbenchPartSite site ) { Assert . isNotNull ( site ) ; fSite = site ; } public void setWorkingSetMode ( WorkingSetModel model ) { Assert . isNotNull ( model ) ; fWorkingSetModel = model ; if ( fConfigureWorkingSetAction != null ) fConfigureWorkingSetAction . setWorkingSetModel ( fWorkingSetModel ) ; } public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; IMenuManager menuManager = actionBars . getMenuManager ( ) ; fillViewMenu ( menuManager ) ; } public void fillViewMenu ( IMenuManager menuManager ) { fConfigureWorkingSetAction = new ConfigureWorkingSetAction ( fSite ) ; if ( fWorkingSetModel != null ) fConfigureWorkingSetAction . setWorkingSetModel ( fWorkingSetModel ) ; addAction ( menuManager , fConfigureWorkingSetAction ) ; } public void cleanViewMenu ( IMenuManager menuManager ) { for ( Iterator iter = fContributions . iterator ( ) ; iter . hasNext ( ) ; ) { menuManager . remove ( ( IContributionItem ) iter . next ( ) ) ; } fContributions . clear ( ) ; } private void addAction ( IMenuManager menuManager , Action action ) { IContributionItem item = new ActionContributionItem ( action ) ; menuManager . appendToGroup ( ACTION_GROUP , item ) ; fContributions . add ( item ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . osgi . util . NLS ; public class WorkingSetMessages extends NLS { private static final String BUNDLE_NAME = WorkingSetMessages . class . getName ( ) ; public static String WorkingSetModel_others_name ; public static String ClearWorkingSetAction_text ; public static String ClearWorkingSetAction_toolTip ; public static String SelectWorkingSetAction_text ; public static String SelectWorkingSetAction_toolTip ; public static String EditWorkingSetAction_text ; public static String EditWorkingSetAction_toolTip ; public static String EditWorkingSetAction_error_nowizard_title ; public static String EditWorkingSetAction_error_nowizard_message ; public static String WorkingSetConfigurationDialog_title ; public static String WorkingSetConfigurationDialog_message ; public static String WorkingSetConfigurationDialog_new_label ; public static String WorkingSetConfigurationDialog_edit_label ; public static String WorkingSetConfigurationDialog_remove_label ; public static String WorkingSetConfigurationDialog_up_label ; public static String WorkingSetConfigurationDialog_down_label ; public static String WorkingSetConfigurationDialog_selectAll_label ; public static String WorkingSetConfigurationDialog_deselectAll_label ; public static String ConfigureWorkingSetAction_label ; public static String ViewActionGroup_show_label ; public static String ViewActionGroup_projects_label ; public static String ViewActionGroup_workingSets_label ; public static String RemoveWorkingSetElementAction_label ; public static String OpenPropertiesWorkingSetAction_label ; public static String OpenCloseWorkingSetAction_close_error_title ; public static String OpenCloseWorkingSetAction_close_error_message ; public static String OpenCloseWorkingSetAction_open_error_title ; public static String OpenCloseWorkingSetAction_open_error_message ; public static String OpenCloseWorkingSetAction_close_label ; public static String OpenCloseWorkingSetAction_open_label ; public static String RubyWorkingSetPage_title ; public static String RubyWorkingSetPage_workingSet_description ; public static String RubyWorkingSetPage_workingSet_name ; public static String RubyWorkingSetPage_workingSet_content ; public static String RubyWorkingSetPage_selectAll_label ; public static String RubyWorkingSetPage_selectAll_toolTip ; public static String RubyWorkingSetPage_deselectAll_label ; public static String RubyWorkingSetPage_deselectAll_toolTip ; public static String RubyWorkingSetPage_warning_nameWhitespace ; public static String RubyWorkingSetPage_warning_nameMustNotBeEmpty ; public static String RubyWorkingSetPage_warning_workingSetExists ; public static String RubyWorkingSetPage_warning_resourceMustBeChecked ; static { NLS . initializeMessages ( BUNDLE_NAME , WorkingSetMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Hashtable ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . window . Window ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . IWorkingSetEditWizard ; import org . eclipse . ui . dialogs . IWorkingSetNewWizard ; import org . eclipse . ui . dialogs . SelectionDialog ; import org . rubypeople . rdt . internal . ui . util . CollectionContentProvider ; public class WorkingSetConfigurationDialog extends SelectionDialog { private static class WorkingSetLabelProvider extends LabelProvider { private Map fIcons ; public WorkingSetLabelProvider ( ) { fIcons = new Hashtable ( ) ; } public void dispose ( ) { Iterator iterator = fIcons . values ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Image icon = ( Image ) iterator . next ( ) ; icon . dispose ( ) ; } super . dispose ( ) ; } public Image getImage ( Object object ) { Assert . isTrue ( object instanceof IWorkingSet ) ; IWorkingSet workingSet = ( IWorkingSet ) object ; ImageDescriptor imageDescriptor = workingSet . getImage ( ) ; if ( imageDescriptor == null ) return null ; Image icon = ( Image ) fIcons . get ( imageDescriptor ) ; if ( icon == null ) { icon = imageDescriptor . createImage ( ) ; fIcons . put ( imageDescriptor , icon ) ; } return icon ; } public String getText ( Object object ) { Assert . isTrue ( object instanceof IWorkingSet ) ; IWorkingSet workingSet = ( IWorkingSet ) object ; return workingSet . getName ( ) ; } } private class Filter extends ViewerFilter { public boolean select ( Viewer viewer , Object parentElement , Object element ) { IWorkingSet ws = ( IWorkingSet ) element ; String id = ws . getId ( ) ; return OthersWorkingSetUpdater . ID . equals ( id ) || RubyWorkingSetUpdater . ID . equals ( id ) || isCompatible ( ws ) || isActive ( ws ) ; } private boolean isCompatible ( IWorkingSet set ) { if ( ! set . isSelfUpdating ( ) || set . isAggregateWorkingSet ( ) ) return false ; IAdaptable [ ] elements = set . getElements ( ) ; if ( elements . length == ) return false ; for ( int i = ; i < elements . length ; i ++ ) { IAdaptable element = elements [ i ] ; IProject p = ( IProject ) element . getAdapter ( IProject . class ) ; if ( p == null || ! p . exists ( ) ) return false ; } return true ; } private boolean isActive ( IWorkingSet workingSet ) { return fActiveWorkingSets . contains ( workingSet ) ; } } private List fAllWorkingSets ; private List fActiveWorkingSets ; private CheckboxTableViewer fTableViewer ; private Button fNewButton ; private Button fEditButton ; private Button fRemoveButton ; private Button fUpButton ; private Button fDownButton ; private Button fSelectAll ; private Button fDeselectAll ; private IWorkingSet [ ] fResult ; private List fAddedWorkingSets ; private List fRemovedWorkingSets ; private Map fEditedWorkingSets ; private List fRemovedMRUWorkingSets ; private int nextButtonId = IDialogConstants . CLIENT_ID + ; public WorkingSetConfigurationDialog ( Shell parentShell , IWorkingSet [ ] allWorkingSets , IWorkingSet [ ] activeWorkingSets ) { super ( parentShell ) ; setTitle ( WorkingSetMessages . WorkingSetConfigurationDialog_title ) ; setMessage ( WorkingSetMessages . WorkingSetConfigurationDialog_message ) ; fAllWorkingSets = new ArrayList ( allWorkingSets . length ) ; fActiveWorkingSets = Arrays . asList ( activeWorkingSets ) ; Filter filter = new Filter ( ) ; for ( int i = ; i < allWorkingSets . length ; i ++ ) { if ( filter . select ( null , null , allWorkingSets [ i ] ) ) fAllWorkingSets . add ( allWorkingSets [ i ] ) ; } setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; } public IWorkingSet [ ] getSelection ( ) { return fResult ; } public void setSelection ( IWorkingSet [ ] workingSets ) { fResult = workingSets ; setInitialSelections ( workingSets ) ; } protected Control createContents ( Composite parent ) { Control control = super . createContents ( parent ) ; setInitialSelection ( ) ; updateButtonAvailability ( ) ; return control ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; composite . setFont ( parent . getFont ( ) ) ; createMessageArea ( composite ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; inner . setFont ( composite . getFont ( ) ) ; inner . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginHeight = ; layout . marginWidth = ; inner . setLayout ( layout ) ; createTableViewer ( inner ) ; createOrderButtons ( inner ) ; createModifyButtons ( composite ) ; fTableViewer . setInput ( fAllWorkingSets ) ; return composite ; } private void createTableViewer ( Composite parent ) { fTableViewer = CheckboxTableViewer . newCheckList ( parent , SWT . BORDER | SWT . MULTI ) ; fTableViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { updateButtonAvailability ( ) ; } } ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . heightHint = convertHeightInCharsToPixels ( ) ; data . widthHint = convertWidthInCharsToPixels ( ) ; fTableViewer . getTable ( ) . setLayoutData ( data ) ; fTableViewer . getTable ( ) . setFont ( parent . getFont ( ) ) ; fTableViewer . addFilter ( new Filter ( ) ) ; fTableViewer . setLabelProvider ( new WorkingSetLabelProvider ( ) ) ; fTableViewer . setContentProvider ( new CollectionContentProvider ( ) ) ; fTableViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { handleSelectionChanged ( ) ; } } ) ; } private void createModifyButtons ( Composite composite ) { Composite buttonComposite = new Composite ( composite , SWT . RIGHT ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; buttonComposite . setLayout ( layout ) ; GridData data = new GridData ( GridData . HORIZONTAL_ALIGN_END | GridData . GRAB_HORIZONTAL ) ; data . grabExcessHorizontalSpace = true ; composite . setData ( data ) ; fNewButton = createButton ( buttonComposite , nextButtonId ++ , WorkingSetMessages . WorkingSetConfigurationDialog_new_label , false ) ; fNewButton . setFont ( composite . getFont ( ) ) ; fNewButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { createWorkingSet ( ) ; } } ) ; fEditButton = createButton ( buttonComposite , nextButtonId ++ , WorkingSetMessages . WorkingSetConfigurationDialog_edit_label , false ) ; fEditButton . setFont ( composite . getFont ( ) ) ; fEditButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { editSelectedWorkingSet ( ) ; } } ) ; fRemoveButton = createButton ( buttonComposite , nextButtonId ++ , WorkingSetMessages . WorkingSetConfigurationDialog_remove_label , false ) ; fRemoveButton . setFont ( composite . getFont ( ) ) ; fRemoveButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { removeSelectedWorkingSets ( ) ; } } ) ; } private void createOrderButtons ( Composite parent ) { Composite buttons = new Composite ( parent , SWT . NONE ) ; buttons . setFont ( parent . getFont ( ) ) ; buttons . setLayoutData ( new GridData ( GridData . FILL_VERTICAL ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; buttons . setLayout ( layout ) ; fUpButton = new Button ( buttons , SWT . PUSH ) ; fUpButton . setText ( WorkingSetMessages . WorkingSetConfigurationDialog_up_label ) ; fUpButton . setFont ( parent . getFont ( ) ) ; setButtonLayoutData ( fUpButton ) ; fUpButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { moveUp ( ( ( IStructuredSelection ) fTableViewer . getSelection ( ) ) . toList ( ) ) ; } } ) ; fDownButton = new Button ( buttons , SWT . PUSH ) ; fDownButton . setText ( WorkingSetMessages . WorkingSetConfigurationDialog_down_label ) ; fDownButton . setFont ( parent . getFont ( ) ) ; setButtonLayoutData ( fDownButton ) ; fDownButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { moveDown ( ( ( IStructuredSelection ) fTableViewer . getSelection ( ) ) . toList ( ) ) ; } } ) ; fSelectAll = new Button ( buttons , SWT . PUSH ) ; fSelectAll . setText ( WorkingSetMessages . WorkingSetConfigurationDialog_selectAll_label ) ; fSelectAll . setFont ( parent . getFont ( ) ) ; setButtonLayoutData ( fSelectAll ) ; fSelectAll . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { selectAll ( ) ; } } ) ; fDeselectAll = new Button ( buttons , SWT . PUSH ) ; fDeselectAll . setText ( WorkingSetMessages . WorkingSetConfigurationDialog_deselectAll_label ) ; fDeselectAll . setFont ( parent . getFont ( ) ) ; setButtonLayoutData ( fDeselectAll ) ; fDeselectAll . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { deselectAll ( ) ; } } ) ; } protected void okPressed ( ) { List newResult = getResultWorkingSets ( ) ; fResult = ( IWorkingSet [ ] ) newResult . toArray ( new IWorkingSet [ newResult . size ( ) ] ) ; setResult ( newResult ) ; super . okPressed ( ) ; } private List getResultWorkingSets ( ) { Object [ ] checked = fTableViewer . getCheckedElements ( ) ; return new ArrayList ( Arrays . asList ( checked ) ) ; } protected void cancelPressed ( ) { restoreAddedWorkingSets ( ) ; restoreChangedWorkingSets ( ) ; restoreRemovedWorkingSets ( ) ; super . cancelPressed ( ) ; } private void setInitialSelection ( ) { List selections = getInitialElementSelections ( ) ; if ( ! selections . isEmpty ( ) ) { fTableViewer . setCheckedElements ( selections . toArray ( ) ) ; } } private void createWorkingSet ( ) { IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; IWorkingSetNewWizard wizard = manager . createWorkingSetNewWizard ( new String [ ] { RubyWorkingSetUpdater . ID } ) ; WizardDialog dialog = new WizardDialog ( getShell ( ) , wizard ) ; dialog . create ( ) ; if ( dialog . open ( ) == Window . OK ) { IWorkingSet workingSet = wizard . getSelection ( ) ; Filter filter = new Filter ( ) ; if ( filter . select ( null , null , workingSet ) ) { fAllWorkingSets . add ( workingSet ) ; fTableViewer . add ( workingSet ) ; fTableViewer . setSelection ( new StructuredSelection ( workingSet ) , true ) ; fTableViewer . setChecked ( workingSet , true ) ; manager . addWorkingSet ( workingSet ) ; fAddedWorkingSets . add ( workingSet ) ; } } } private void editSelectedWorkingSet ( ) { IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; IWorkingSet editWorkingSet = ( IWorkingSet ) ( ( IStructuredSelection ) fTableViewer . getSelection ( ) ) . getFirstElement ( ) ; IWorkingSetEditWizard wizard = manager . createWorkingSetEditWizard ( editWorkingSet ) ; WizardDialog dialog = new WizardDialog ( getShell ( ) , wizard ) ; IWorkingSet originalWorkingSet = ( IWorkingSet ) fEditedWorkingSets . get ( editWorkingSet ) ; boolean firstEdit = originalWorkingSet == null ; if ( firstEdit ) { originalWorkingSet = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . createWorkingSet ( editWorkingSet . getName ( ) , editWorkingSet . getElements ( ) ) ; } else { fEditedWorkingSets . remove ( editWorkingSet ) ; } dialog . create ( ) ; if ( dialog . open ( ) == Window . OK ) { editWorkingSet = wizard . getSelection ( ) ; fTableViewer . update ( editWorkingSet , null ) ; updateButtonAvailability ( ) ; } fEditedWorkingSets . put ( editWorkingSet , originalWorkingSet ) ; } void handleSelectionChanged ( ) { updateButtonAvailability ( ) ; } public int open ( ) { fAddedWorkingSets = new ArrayList ( ) ; fRemovedWorkingSets = new ArrayList ( ) ; fEditedWorkingSets = new HashMap ( ) ; fRemovedMRUWorkingSets = new ArrayList ( ) ; return super . open ( ) ; } private void removeSelectedWorkingSets ( ) { ISelection selection = fTableViewer . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; Iterator iter = ( ( IStructuredSelection ) selection ) . iterator ( ) ; while ( iter . hasNext ( ) ) { IWorkingSet workingSet = ( IWorkingSet ) iter . next ( ) ; if ( fAddedWorkingSets . contains ( workingSet ) ) { fAddedWorkingSets . remove ( workingSet ) ; } else { IWorkingSet [ ] recentWorkingSets = manager . getRecentWorkingSets ( ) ; for ( int i = ; i < recentWorkingSets . length ; i ++ ) { if ( workingSet . equals ( recentWorkingSets [ i ] ) ) { fRemovedMRUWorkingSets . add ( workingSet ) ; break ; } } fRemovedWorkingSets . add ( workingSet ) ; } fAllWorkingSets . remove ( workingSet ) ; manager . removeWorkingSet ( workingSet ) ; } fTableViewer . remove ( ( ( IStructuredSelection ) selection ) . toArray ( ) ) ; } } private void restoreAddedWorkingSets ( ) { IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; Iterator iterator = fAddedWorkingSets . iterator ( ) ; while ( iterator . hasNext ( ) ) { manager . removeWorkingSet ( ( ( IWorkingSet ) iterator . next ( ) ) ) ; } } private void restoreChangedWorkingSets ( ) { Iterator iterator = fEditedWorkingSets . keySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { IWorkingSet editedWorkingSet = ( IWorkingSet ) iterator . next ( ) ; IWorkingSet originalWorkingSet = ( IWorkingSet ) fEditedWorkingSets . get ( editedWorkingSet ) ; if ( editedWorkingSet . getName ( ) . equals ( originalWorkingSet . getName ( ) ) == false ) { editedWorkingSet . setName ( originalWorkingSet . getName ( ) ) ; } if ( editedWorkingSet . getElements ( ) . equals ( originalWorkingSet . getElements ( ) ) == false ) { editedWorkingSet . setElements ( originalWorkingSet . getElements ( ) ) ; } } } private void restoreRemovedWorkingSets ( ) { IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; Iterator iterator = fRemovedWorkingSets . iterator ( ) ; while ( iterator . hasNext ( ) ) { manager . addWorkingSet ( ( ( IWorkingSet ) iterator . next ( ) ) ) ; } iterator = fRemovedMRUWorkingSets . iterator ( ) ; while ( iterator . hasNext ( ) ) { manager . addRecentWorkingSet ( ( ( IWorkingSet ) iterator . next ( ) ) ) ; } } private void updateButtonAvailability ( ) { IStructuredSelection selection = ( IStructuredSelection ) fTableViewer . getSelection ( ) ; boolean hasSelection = ! selection . isEmpty ( ) ; boolean hasSingleSelection = selection . size ( ) == ; fRemoveButton . setEnabled ( hasSelection && areAllGlobalWorkingSets ( selection ) ) ; fEditButton . setEnabled ( hasSingleSelection && ( ( IWorkingSet ) selection . getFirstElement ( ) ) . isEditable ( ) ) ; if ( fUpButton != null ) { fUpButton . setEnabled ( canMoveUp ( ) ) ; } if ( fDownButton != null ) { fDownButton . setEnabled ( canMoveDown ( ) ) ; } } private boolean areAllGlobalWorkingSets ( IStructuredSelection selection ) { Set globals = new HashSet ( Arrays . asList ( PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSets ( ) ) ) ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { if ( ! globals . contains ( iter . next ( ) ) ) return false ; } return true ; } private void moveUp ( List toMoveUp ) { if ( toMoveUp . size ( ) > ) { setElements ( moveUp ( fAllWorkingSets , toMoveUp ) ) ; fTableViewer . reveal ( toMoveUp . get ( ) ) ; } } private void moveDown ( List toMoveDown ) { if ( toMoveDown . size ( ) > ) { setElements ( reverse ( moveUp ( reverse ( fAllWorkingSets ) , toMoveDown ) ) ) ; fTableViewer . reveal ( toMoveDown . get ( toMoveDown . size ( ) - ) ) ; } } private void setElements ( List elements ) { fAllWorkingSets = elements ; fTableViewer . setInput ( fAllWorkingSets ) ; updateButtonAvailability ( ) ; } private List moveUp ( List elements , List move ) { int nElements = elements . size ( ) ; List res = new ArrayList ( nElements ) ; Object floating = null ; for ( int i = ; i < nElements ; i ++ ) { Object curr = elements . get ( i ) ; if ( move . contains ( curr ) ) { res . add ( curr ) ; } else { if ( floating != null ) { res . add ( floating ) ; } floating = curr ; } } if ( floating != null ) { res . add ( floating ) ; } return res ; } private List reverse ( List p ) { List reverse = new ArrayList ( p . size ( ) ) ; for ( int i = p . size ( ) - ; i >= ; i -- ) { reverse . add ( p . get ( i ) ) ; } return reverse ; } private boolean canMoveUp ( ) { int [ ] indc = fTableViewer . getTable ( ) . getSelectionIndices ( ) ; for ( int i = ; i < indc . length ; i ++ ) { if ( indc [ i ] != i ) { return true ; } } return false ; } private boolean canMoveDown ( ) { int [ ] indc = fTableViewer . getTable ( ) . getSelectionIndices ( ) ; int k = fAllWorkingSets . size ( ) - ; for ( int i = indc . length - ; i >= ; i -- , k -- ) { if ( indc [ i ] != k ) { return true ; } } return false ; } private void selectAll ( ) { fTableViewer . setAllChecked ( true ) ; } private void deselectAll ( ) { fTableViewer . setAllChecked ( false ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . ui . IContextMenuConstants ; public class WorkingSetActionGroup extends ActionGroup { private static final String GROUP_WORKINGSETS = "" ; private IViewSite fSite ; private ISelectionChangedListener fLazyInitializer = new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { ISelectionProvider selectionProvider = fSite . getSelectionProvider ( ) ; selectionProvider . removeSelectionChangedListener ( fLazyInitializer ) ; ISelection selection = event . getSelection ( ) ; fRemoveAction = new RemoveWorkingSetElementAction ( fSite ) ; fRemoveAction . update ( selection ) ; selectionProvider . addSelectionChangedListener ( fRemoveAction ) ; fEditAction = new OpenPropertiesWorkingSetAction ( fSite ) ; fEditAction . update ( selection ) ; selectionProvider . addSelectionChangedListener ( fEditAction ) ; fCloseAction = OpenCloseWorkingSetAction . createCloseAction ( fSite ) ; fCloseAction . update ( selection ) ; selectionProvider . addSelectionChangedListener ( fCloseAction ) ; fOpenAction = OpenCloseWorkingSetAction . createOpenAction ( fSite ) ; fOpenAction . update ( selection ) ; selectionProvider . addSelectionChangedListener ( fOpenAction ) ; } } ; private RemoveWorkingSetElementAction fRemoveAction ; private OpenPropertiesWorkingSetAction fEditAction ; private OpenCloseWorkingSetAction fCloseAction ; private OpenCloseWorkingSetAction fOpenAction ; public WorkingSetActionGroup ( IViewPart part ) { fSite = part . getViewSite ( ) ; fSite . getSelectionProvider ( ) . addSelectionChangedListener ( fLazyInitializer ) ; } public void dispose ( ) { ISelectionProvider selectionProvider = fSite . getSelectionProvider ( ) ; if ( fRemoveAction != null ) selectionProvider . removeSelectionChangedListener ( fRemoveAction ) ; if ( fEditAction != null ) selectionProvider . removeSelectionChangedListener ( fEditAction ) ; if ( fCloseAction != null ) { selectionProvider . removeSelectionChangedListener ( fCloseAction ) ; fCloseAction . dispose ( ) ; } if ( fOpenAction != null ) { selectionProvider . removeSelectionChangedListener ( fOpenAction ) ; fOpenAction . dispose ( ) ; } } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_REORGANIZE , new Separator ( GROUP_WORKINGSETS ) ) ; if ( fRemoveAction != null && fRemoveAction . isEnabled ( ) ) menu . appendToGroup ( GROUP_WORKINGSETS , fRemoveAction ) ; if ( fCloseAction != null && fCloseAction . isEnabled ( ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_BUILD , fCloseAction ) ; if ( fOpenAction != null && fOpenAction . isEnabled ( ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_BUILD , fOpenAction ) ; if ( fEditAction != null && fEditAction . isEnabled ( ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_PROPERTIES , fEditAction ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . IWorkingSetSelectionDialog ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class SelectWorkingSetAction extends Action { private IWorkbenchPartSite fSite ; private Shell fShell ; private WorkingSetFilterActionGroup fActionGroup ; public SelectWorkingSetAction ( WorkingSetFilterActionGroup actionGroup , IWorkbenchPartSite site ) { this ( actionGroup ) ; fSite = site ; } public SelectWorkingSetAction ( WorkingSetFilterActionGroup actionGroup , Shell shell ) { this ( actionGroup ) ; fShell = shell ; } private SelectWorkingSetAction ( WorkingSetFilterActionGroup actionGroup ) { super ( WorkingSetMessages . SelectWorkingSetAction_text ) ; Assert . isNotNull ( actionGroup ) ; setToolTipText ( WorkingSetMessages . SelectWorkingSetAction_toolTip ) ; fActionGroup = actionGroup ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . SELECT_WORKING_SET_ACTION ) ; } public void run ( ) { Shell shell = getShell ( ) ; IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; IWorkingSetSelectionDialog dialog = manager . createWorkingSetSelectionDialog ( shell , false ) ; IWorkingSet workingSet = fActionGroup . getWorkingSet ( ) ; if ( workingSet != null ) dialog . setSelection ( new IWorkingSet [ ] { workingSet } ) ; if ( dialog . open ( ) == Window . OK ) { IWorkingSet [ ] result = dialog . getSelection ( ) ; if ( result != null && result . length > ) { fActionGroup . setWorkingSet ( result [ ] , true ) ; manager . addRecentWorkingSet ( result [ ] ) ; } else fActionGroup . setWorkingSet ( null , true ) ; } } private Shell getShell ( ) { if ( fSite != null ) { return fSite . getShell ( ) ; } else if ( fShell != null ) { return fShell ; } else { return RubyPlugin . getActiveWorkbenchShell ( ) ; } } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . IdentityHashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . IElementComparer ; import org . eclipse . ui . ILocalWorkingSetManager ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . IWorkingSetUpdater ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyProject ; public class WorkingSetModel { public static final String CHANGE_WORKING_SET_MODEL_CONTENT = "" ; public static final IElementComparer COMPARER = new WorkingSetComparar ( ) ; private static final String TAG_LOCAL_WORKING_SET_MANAGER = "" ; private static final String TAG_ACTIVE_WORKING_SET = "" ; private static final String TAG_WORKING_SET_NAME = "" ; private static final String TAG_CONFIGURED = "" ; private ILocalWorkingSetManager fLocalWorkingSetManager ; private List < IWorkingSet > fActiveWorkingSets ; private ListenerList fListeners ; private IPropertyChangeListener fWorkingSetManagerListener ; private OthersWorkingSetUpdater fOthersWorkingSetUpdater ; private ElementMapper fElementMapper = new ElementMapper ( ) ; private boolean fConfigured ; private static class WorkingSetComparar implements IElementComparer { public boolean equals ( Object o1 , Object o2 ) { IWorkingSet w1 = o1 instanceof IWorkingSet ? ( IWorkingSet ) o1 : null ; IWorkingSet w2 = o2 instanceof IWorkingSet ? ( IWorkingSet ) o2 : null ; if ( w1 == null || w2 == null ) return o1 . equals ( o2 ) ; return w1 == w2 ; } public int hashCode ( Object element ) { if ( element instanceof IWorkingSet ) return System . identityHashCode ( element ) ; return element . hashCode ( ) ; } } private static class ElementMapper { private Map fElementToWorkingSet = new HashMap ( ) ; private Map < IWorkingSet , IAdaptable [ ] > fWorkingSetToElement = new IdentityHashMap < IWorkingSet , IAdaptable [ ] > ( ) ; private Map fResourceToWorkingSet = new HashMap ( ) ; private List fNonProjectTopLevelElements = new ArrayList ( ) ; public void clear ( ) { fElementToWorkingSet . clear ( ) ; fWorkingSetToElement . clear ( ) ; fResourceToWorkingSet . clear ( ) ; fNonProjectTopLevelElements . clear ( ) ; } public void rebuild ( IWorkingSet [ ] workingSets ) { clear ( ) ; for ( int i = ; i < workingSets . length ; i ++ ) { put ( workingSets [ i ] ) ; } } public IAdaptable [ ] remove ( IWorkingSet ws ) { IAdaptable [ ] elements = fWorkingSetToElement . remove ( ws ) ; if ( elements != null ) { for ( int i = ; i < elements . length ; i ++ ) { removeElement ( elements [ i ] , ws ) ; } } return elements ; } public IAdaptable [ ] refresh ( IWorkingSet ws ) { IAdaptable [ ] oldElements = fWorkingSetToElement . get ( ws ) ; if ( oldElements == null ) return null ; IAdaptable [ ] newElements = ws . getElements ( ) ; List < IAdaptable > toRemove = new ArrayList < IAdaptable > ( Arrays . asList ( oldElements ) ) ; List < IAdaptable > toAdd = new ArrayList < IAdaptable > ( Arrays . asList ( newElements ) ) ; computeDelta ( toRemove , toAdd , oldElements , newElements ) ; for ( Iterator < IAdaptable > iter = toAdd . iterator ( ) ; iter . hasNext ( ) ; ) { addElement ( iter . next ( ) , ws ) ; } for ( Iterator < IAdaptable > iter = toRemove . iterator ( ) ; iter . hasNext ( ) ; ) { removeElement ( iter . next ( ) , ws ) ; } if ( toRemove . size ( ) > || toAdd . size ( ) > ) fWorkingSetToElement . put ( ws , newElements ) ; return oldElements ; } private void computeDelta ( List toRemove , List toAdd , IAdaptable [ ] oldElements , IAdaptable [ ] newElements ) { for ( int i = ; i < oldElements . length ; i ++ ) { toAdd . remove ( oldElements [ i ] ) ; } for ( int i = ; i < newElements . length ; i ++ ) { toRemove . remove ( newElements [ i ] ) ; } } public IWorkingSet getFirstWorkingSet ( Object element ) { return ( IWorkingSet ) getFirstElement ( fElementToWorkingSet , element ) ; } public List getAllWorkingSets ( Object element ) { return getAllElements ( fElementToWorkingSet , element ) ; } public IWorkingSet getFirstWorkingSetForResource ( IResource resource ) { return ( IWorkingSet ) getFirstElement ( fResourceToWorkingSet , resource ) ; } public List getAllWorkingSetsForResource ( IResource resource ) { return getAllElements ( fResourceToWorkingSet , resource ) ; } public List getNonProjectTopLevelElements ( ) { return fNonProjectTopLevelElements ; } private void put ( IWorkingSet ws ) { if ( fWorkingSetToElement . containsKey ( ws ) ) return ; IAdaptable [ ] elements = ws . getElements ( ) ; fWorkingSetToElement . put ( ws , elements ) ; for ( int i = ; i < elements . length ; i ++ ) { IAdaptable element = elements [ i ] ; addElement ( element , ws ) ; if ( ! ( element instanceof IProject ) && ! ( element instanceof IRubyProject ) ) { fNonProjectTopLevelElements . add ( element ) ; } } } private void addElement ( IAdaptable element , IWorkingSet ws ) { addToMap ( fElementToWorkingSet , element , ws ) ; IResource resource = ( IResource ) element . getAdapter ( IResource . class ) ; if ( resource != null ) { addToMap ( fResourceToWorkingSet , resource , ws ) ; } } private void removeElement ( IAdaptable element , IWorkingSet ws ) { removeFromMap ( fElementToWorkingSet , element , ws ) ; IResource resource = ( IResource ) element . getAdapter ( IResource . class ) ; if ( resource != null ) { removeFromMap ( fResourceToWorkingSet , resource , ws ) ; } } private void addToMap ( Map map , IAdaptable key , IWorkingSet value ) { Object obj = map . get ( key ) ; if ( obj == null ) { map . put ( key , value ) ; } else if ( obj instanceof IWorkingSet ) { List l = new ArrayList ( ) ; l . add ( obj ) ; l . add ( value ) ; map . put ( key , l ) ; } else if ( obj instanceof List ) { ( ( List ) obj ) . add ( value ) ; } } private void removeFromMap ( Map map , IAdaptable key , IWorkingSet value ) { Object current = map . get ( key ) ; if ( current == null ) { return ; } else if ( current instanceof List ) { List list = ( List ) current ; list . remove ( value ) ; switch ( list . size ( ) ) { case : map . remove ( key ) ; break ; case : map . put ( key , list . get ( ) ) ; break ; } } else if ( current == value ) { map . remove ( key ) ; } } private Object getFirstElement ( Map map , Object key ) { Object obj = map . get ( key ) ; if ( obj instanceof List ) return ( ( List ) obj ) . get ( ) ; return obj ; } private List getAllElements ( Map map , Object key ) { Object obj = map . get ( key ) ; if ( obj instanceof List ) return ( List ) obj ; if ( obj == null ) return Collections . EMPTY_LIST ; List result = new ArrayList ( ) ; result . add ( obj ) ; return result ; } } public WorkingSetModel ( ) { fLocalWorkingSetManager = PlatformUI . getWorkbench ( ) . createLocalWorkingSetManager ( ) ; addListenersToWorkingSetManagers ( ) ; fActiveWorkingSets = new ArrayList < IWorkingSet > ( ) ; IWorkingSet others = fLocalWorkingSetManager . createWorkingSet ( WorkingSetMessages . WorkingSetModel_others_name , new IAdaptable [ ] ) ; others . setId ( OthersWorkingSetUpdater . ID ) ; fLocalWorkingSetManager . addWorkingSet ( others ) ; Assert . isNotNull ( fOthersWorkingSetUpdater ) ; fActiveWorkingSets . add ( others ) ; fElementMapper . rebuild ( getActiveWorkingSets ( ) ) ; fOthersWorkingSetUpdater . updateElements ( ) ; } public WorkingSetModel ( IMemento memento ) { fLocalWorkingSetManager = PlatformUI . getWorkbench ( ) . createLocalWorkingSetManager ( ) ; addListenersToWorkingSetManagers ( ) ; fActiveWorkingSets = new ArrayList < IWorkingSet > ( ) ; restoreState ( memento ) ; Assert . isNotNull ( fOthersWorkingSetUpdater ) ; fElementMapper . rebuild ( getActiveWorkingSets ( ) ) ; fOthersWorkingSetUpdater . updateElements ( ) ; } private void addListenersToWorkingSetManagers ( ) { fListeners = new ListenerList ( ListenerList . IDENTITY ) ; fWorkingSetManagerListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { workingSetManagerChanged ( event ) ; } } ; PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . addPropertyChangeListener ( fWorkingSetManagerListener ) ; fLocalWorkingSetManager . addPropertyChangeListener ( fWorkingSetManagerListener ) ; } public void dispose ( ) { if ( fWorkingSetManagerListener != null ) { PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . removePropertyChangeListener ( fWorkingSetManagerListener ) ; fLocalWorkingSetManager . removePropertyChangeListener ( fWorkingSetManagerListener ) ; fLocalWorkingSetManager . dispose ( ) ; fWorkingSetManagerListener = null ; } } public IAdaptable [ ] getChildren ( IWorkingSet workingSet ) { return workingSet . getElements ( ) ; } public Object getParent ( Object element ) { if ( element instanceof IWorkingSet && fActiveWorkingSets . contains ( element ) ) return this ; return fElementMapper . getFirstWorkingSet ( element ) ; } public Object [ ] getAllParents ( Object element ) { if ( element instanceof IWorkingSet && fActiveWorkingSets . contains ( element ) ) return new Object [ ] { this } ; return fElementMapper . getAllWorkingSets ( element ) . toArray ( ) ; } public Object [ ] addWorkingSets ( Object [ ] elements ) { List result = null ; for ( int i = ; i < elements . length ; i ++ ) { Object element = elements [ i ] ; List sets = null ; if ( element instanceof IResource ) { sets = fElementMapper . getAllWorkingSetsForResource ( ( IResource ) element ) ; } else { sets = fElementMapper . getAllWorkingSets ( element ) ; } if ( sets != null && sets . size ( ) > ) { if ( result == null ) result = new ArrayList ( Arrays . asList ( elements ) ) ; result . addAll ( sets ) ; } } if ( result == null ) return elements ; return result . toArray ( ) ; } public boolean needsConfiguration ( ) { return ! fConfigured && fActiveWorkingSets . size ( ) == && OthersWorkingSetUpdater . ID . equals ( ( ( IWorkingSet ) fActiveWorkingSets . get ( ) ) . getId ( ) ) ; } public void configured ( ) { fConfigured = true ; } public void addPropertyChangeListener ( IPropertyChangeListener listener ) { fListeners . add ( listener ) ; } public void removePropertyChangeListener ( IPropertyChangeListener listener ) { fListeners . remove ( listener ) ; } public IWorkingSet [ ] getActiveWorkingSets ( ) { return ( IWorkingSet [ ] ) fActiveWorkingSets . toArray ( new IWorkingSet [ fActiveWorkingSets . size ( ) ] ) ; } public IWorkingSet [ ] getAllWorkingSets ( ) { List < IWorkingSet > result = new ArrayList < IWorkingSet > ( ) ; result . addAll ( fActiveWorkingSets ) ; IWorkingSet [ ] locals = fLocalWorkingSetManager . getWorkingSets ( ) ; for ( int i = ; i < locals . length ; i ++ ) { if ( ! result . contains ( locals [ i ] ) ) result . add ( locals [ i ] ) ; } IWorkingSet [ ] globals = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSets ( ) ; for ( int i = ; i < globals . length ; i ++ ) { if ( ! result . contains ( globals [ i ] ) ) result . add ( globals [ i ] ) ; } return ( IWorkingSet [ ] ) result . toArray ( new IWorkingSet [ result . size ( ) ] ) ; } public void setActiveWorkingSets ( IWorkingSet [ ] workingSets ) { fActiveWorkingSets = new ArrayList < IWorkingSet > ( Arrays . asList ( workingSets ) ) ; fElementMapper . rebuild ( getActiveWorkingSets ( ) ) ; fOthersWorkingSetUpdater . updateElements ( ) ; fireEvent ( new PropertyChangeEvent ( this , CHANGE_WORKING_SET_MODEL_CONTENT , null , null ) ) ; } public void saveState ( IMemento memento ) { memento . putString ( TAG_CONFIGURED , Boolean . toString ( fConfigured ) ) ; fLocalWorkingSetManager . saveState ( memento . createChild ( TAG_LOCAL_WORKING_SET_MANAGER ) ) ; for ( Iterator < IWorkingSet > iter = fActiveWorkingSets . iterator ( ) ; iter . hasNext ( ) ; ) { IMemento active = memento . createChild ( TAG_ACTIVE_WORKING_SET ) ; IWorkingSet workingSet = ( IWorkingSet ) iter . next ( ) ; active . putString ( TAG_WORKING_SET_NAME , workingSet . getName ( ) ) ; } } public List getNonProjectTopLevelElements ( ) { return fElementMapper . getNonProjectTopLevelElements ( ) ; } private void restoreState ( IMemento memento ) { String configured = memento . getString ( TAG_CONFIGURED ) ; fConfigured = configured != null && Boolean . valueOf ( configured ) . booleanValue ( ) ; fLocalWorkingSetManager . restoreState ( memento . getChild ( TAG_LOCAL_WORKING_SET_MANAGER ) ) ; IMemento [ ] actives = memento . getChildren ( TAG_ACTIVE_WORKING_SET ) ; for ( int i = ; i < actives . length ; i ++ ) { String name = actives [ i ] . getString ( TAG_WORKING_SET_NAME ) ; if ( name != null ) { IWorkingSet ws = fLocalWorkingSetManager . getWorkingSet ( name ) ; if ( ws == null ) { ws = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSet ( name ) ; } if ( ws != null ) { fActiveWorkingSets . add ( ws ) ; } } } } private void workingSetManagerChanged ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( IWorkingSetManager . CHANGE_WORKING_SET_UPDATER_INSTALLED . equals ( property ) && event . getSource ( ) == fLocalWorkingSetManager ) { IWorkingSetUpdater updater = ( IWorkingSetUpdater ) event . getNewValue ( ) ; if ( updater instanceof OthersWorkingSetUpdater ) { fOthersWorkingSetUpdater = ( OthersWorkingSetUpdater ) updater ; fOthersWorkingSetUpdater . init ( this ) ; } return ; } if ( ! isAffected ( event ) ) return ; if ( IWorkingSetManager . CHANGE_WORKING_SET_CONTENT_CHANGE . equals ( property ) ) { IWorkingSet workingSet = ( IWorkingSet ) event . getNewValue ( ) ; IAdaptable [ ] elements = fElementMapper . refresh ( workingSet ) ; if ( elements != null ) { fireEvent ( event ) ; } } else if ( IWorkingSetManager . CHANGE_WORKING_SET_REMOVE . equals ( property ) ) { IWorkingSet workingSet = ( IWorkingSet ) event . getOldValue ( ) ; List < IWorkingSet > elements = new ArrayList < IWorkingSet > ( fActiveWorkingSets ) ; elements . remove ( workingSet ) ; setActiveWorkingSets ( elements . toArray ( new IWorkingSet [ elements . size ( ) ] ) ) ; } else if ( IWorkingSetManager . CHANGE_WORKING_SET_NAME_CHANGE . equals ( property ) ) { fireEvent ( event ) ; } } private void fireEvent ( PropertyChangeEvent event ) { Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { ( ( IPropertyChangeListener ) listeners [ i ] ) . propertyChange ( event ) ; } } private boolean isAffected ( PropertyChangeEvent event ) { if ( fActiveWorkingSets == null ) return false ; Object oldValue = event . getOldValue ( ) ; Object newValue = event . getNewValue ( ) ; if ( ( oldValue != null && fActiveWorkingSets . contains ( oldValue ) ) || ( newValue != null && fActiveWorkingSets . contains ( newValue ) ) ) { return true ; } return false ; } public boolean isActiveWorkingSet ( IWorkingSet changedWorkingSet ) { return fActiveWorkingSets . contains ( changedWorkingSet ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . window . Window ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . IWorkingSetEditWizard ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class EditWorkingSetAction extends Action { private IWorkbenchPartSite fSite ; private Shell fShell ; private WorkingSetFilterActionGroup fActionGroup ; public EditWorkingSetAction ( WorkingSetFilterActionGroup actionGroup , IWorkbenchPartSite site ) { this ( actionGroup ) ; fSite = site ; } public EditWorkingSetAction ( WorkingSetFilterActionGroup actionGroup , Shell shell ) { this ( actionGroup ) ; fShell = shell ; } private EditWorkingSetAction ( WorkingSetFilterActionGroup actionGroup ) { super ( WorkingSetMessages . EditWorkingSetAction_text ) ; Assert . isNotNull ( actionGroup ) ; setToolTipText ( WorkingSetMessages . EditWorkingSetAction_toolTip ) ; setEnabled ( actionGroup . getWorkingSet ( ) != null ) ; fActionGroup = actionGroup ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . EDIT_WORKING_SET_ACTION ) ; } public void run ( ) { Shell shell = getShell ( ) ; IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; IWorkingSet workingSet = fActionGroup . getWorkingSet ( ) ; if ( workingSet == null || workingSet . isAggregateWorkingSet ( ) ) { setEnabled ( false ) ; return ; } IWorkingSetEditWizard wizard = manager . createWorkingSetEditWizard ( workingSet ) ; if ( wizard == null ) { String title = WorkingSetMessages . EditWorkingSetAction_error_nowizard_title ; String message = WorkingSetMessages . EditWorkingSetAction_error_nowizard_message ; MessageDialog . openError ( shell , title , message ) ; return ; } WizardDialog dialog = new WizardDialog ( shell , wizard ) ; dialog . create ( ) ; if ( dialog . open ( ) == Window . OK ) fActionGroup . setWorkingSet ( wizard . getSelection ( ) , true ) ; } private Shell getShell ( ) { if ( fSite != null ) { return fSite . getShell ( ) ; } else if ( fShell != null ) { return fShell ; } else { return RubyPlugin . getActiveWorkbenchShell ( ) ; } } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . IWorkingSetEditWizard ; import org . rubypeople . rdt . ui . actions . SelectionDispatchAction ; public class OpenPropertiesWorkingSetAction extends SelectionDispatchAction { public OpenPropertiesWorkingSetAction ( IWorkbenchSite site ) { super ( site ) ; setText ( WorkingSetMessages . OpenPropertiesWorkingSetAction_label ) ; } public void selectionChanged ( IStructuredSelection selection ) { setEnabled ( getWorkingSet ( selection ) != null ) ; } private IWorkingSet getWorkingSet ( IStructuredSelection selection ) { if ( selection . size ( ) != ) return null ; Object element = selection . getFirstElement ( ) ; if ( ! ( element instanceof IWorkingSet ) ) return null ; IWorkingSet ws = ( IWorkingSet ) element ; if ( ! ws . isEditable ( ) ) return null ; return ws ; } public void run ( IStructuredSelection selection ) { IWorkingSet ws = getWorkingSet ( selection ) ; if ( ws == null ) return ; IWorkingSetEditWizard wizard = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . createWorkingSetEditWizard ( ws ) ; WizardDialog dialog = new WizardDialog ( getShell ( ) , wizard ) ; dialog . open ( ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeSelection ; import org . eclipse . jface . viewers . TreePath ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . rubypeople . rdt . ui . actions . SelectionDispatchAction ; public class RemoveWorkingSetElementAction extends SelectionDispatchAction { public RemoveWorkingSetElementAction ( IWorkbenchSite site ) { super ( site ) ; setText ( WorkingSetMessages . RemoveWorkingSetElementAction_label ) ; } public void selectionChanged ( IStructuredSelection selection ) { IWorkingSet workingSet = getWorkingSet ( selection ) ; setEnabled ( workingSet != null && ! OthersWorkingSetUpdater . ID . equals ( workingSet . getId ( ) ) ) ; } private IWorkingSet getWorkingSet ( IStructuredSelection selection ) { if ( ! ( selection instanceof ITreeSelection ) ) return null ; ITreeSelection treeSelection = ( ITreeSelection ) selection ; List elements = treeSelection . toList ( ) ; IWorkingSet result = null ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; TreePath [ ] paths = treeSelection . getPathsFor ( element ) ; if ( paths . length != ) return null ; TreePath path = paths [ ] ; if ( path . getSegmentCount ( ) != ) return null ; Object candidate = path . getSegment ( ) ; if ( ! ( candidate instanceof IWorkingSet ) ) return null ; if ( result == null ) { result = ( IWorkingSet ) candidate ; } else { if ( result != candidate ) return null ; } } return result ; } public void run ( IStructuredSelection selection ) { IWorkingSet ws = getWorkingSet ( selection ) ; if ( ws == null ) return ; List elements = new ArrayList ( Arrays . asList ( ws . getElements ( ) ) ) ; List selectedElements = selection . toList ( ) ; for ( Iterator iter = selectedElements . iterator ( ) ; iter . hasNext ( ) ; ) { elements . remove ( iter . next ( ) ) ; } ws . setElements ( ( IAdaptable [ ] ) elements . toArray ( new IAdaptable [ elements . size ( ) ] ) ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IContributionItem ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . IWorkbenchPreferenceConstants ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . internal . ui . search . WorkingSetComparator ; public class WorkingSetFilterActionGroup extends ActionGroup implements IWorkingSetActionGroup { private static final String TAG_WORKING_SET_NAME = "" ; private static final String TAG_IS_WINDOW_WORKING_SET = "" ; private static final String LRU_GROUP = "" ; private final WorkingSetFilter fWorkingSetFilter ; private IWorkingSet fWorkingSet = null ; private final ClearWorkingSetAction fClearWorkingSetAction ; private final SelectWorkingSetAction fSelectWorkingSetAction ; private final EditWorkingSetAction fEditWorkingSetAction ; private IPropertyChangeListener fWorkingSetListener ; private IPropertyChangeListener fChangeListener ; private int fLRUMenuCount ; private IMenuManager fMenuManager ; private IMenuListener fMenuListener ; private List fContributions = new ArrayList ( ) ; private final IWorkbenchPage fWorkbenchPage ; private boolean fAllowWindowWorkingSetByDefault ; public WorkingSetFilterActionGroup ( IWorkbenchPartSite site , IPropertyChangeListener changeListener ) { Assert . isNotNull ( site ) ; Assert . isNotNull ( changeListener ) ; fChangeListener = changeListener ; fWorkbenchPage = site . getPage ( ) ; fAllowWindowWorkingSetByDefault = true ; fClearWorkingSetAction = new ClearWorkingSetAction ( this ) ; fSelectWorkingSetAction = new SelectWorkingSetAction ( this , site ) ; fEditWorkingSetAction = new EditWorkingSetAction ( this , site ) ; fWorkingSetListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { doPropertyChange ( event ) ; } } ; fWorkingSetFilter = new WorkingSetFilter ( ) ; IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; manager . addPropertyChangeListener ( fWorkingSetListener ) ; if ( useWindowWorkingSetByDefault ( ) ) { setWorkingSet ( site . getPage ( ) . getAggregateWorkingSet ( ) , false ) ; } } public WorkingSetFilterActionGroup ( Shell shell , IWorkbenchPage page , IPropertyChangeListener changeListener ) { Assert . isNotNull ( shell ) ; Assert . isNotNull ( changeListener ) ; fWorkbenchPage = page ; fAllowWindowWorkingSetByDefault = false ; fChangeListener = changeListener ; fClearWorkingSetAction = new ClearWorkingSetAction ( this ) ; fSelectWorkingSetAction = new SelectWorkingSetAction ( this , shell ) ; fEditWorkingSetAction = new EditWorkingSetAction ( this , shell ) ; fWorkingSetListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { doPropertyChange ( event ) ; } } ; fWorkingSetFilter = new WorkingSetFilter ( ) ; IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; manager . addPropertyChangeListener ( fWorkingSetListener ) ; setWorkingSet ( null , false ) ; } public boolean isFiltered ( Object parent , Object object ) { if ( fWorkingSetFilter == null ) return false ; return ! fWorkingSetFilter . select ( null , parent , object ) ; } public IWorkingSet getWorkingSet ( ) { return fWorkingSet ; } public void setWorkingSet ( IWorkingSet workingSet , boolean refreshViewer ) { fClearWorkingSetAction . setEnabled ( workingSet != null ) ; fEditWorkingSetAction . setEnabled ( workingSet != null && ! workingSet . isAggregateWorkingSet ( ) ) ; fWorkingSet = workingSet ; fWorkingSetFilter . setWorkingSet ( workingSet ) ; if ( refreshViewer ) { fChangeListener . propertyChange ( new PropertyChangeEvent ( this , IWorkingSetManager . CHANGE_WORKING_SET_CONTENT_CHANGE , null , workingSet ) ) ; } } public void saveState ( IMemento memento ) { String workingSetName = "" ; boolean isWindowWorkingSet = false ; if ( fWorkingSet != null ) { if ( fWorkingSet . isAggregateWorkingSet ( ) ) { isWindowWorkingSet = true ; } else { workingSetName = fWorkingSet . getName ( ) ; } } memento . putString ( TAG_IS_WINDOW_WORKING_SET , Boolean . toString ( isWindowWorkingSet ) ) ; memento . putString ( TAG_WORKING_SET_NAME , workingSetName ) ; } public void restoreState ( IMemento memento ) { boolean isWindowWorkingSet ; if ( memento . getString ( TAG_IS_WINDOW_WORKING_SET ) != null ) { isWindowWorkingSet = Boolean . valueOf ( memento . getString ( TAG_IS_WINDOW_WORKING_SET ) ) . booleanValue ( ) ; } else { isWindowWorkingSet = useWindowWorkingSetByDefault ( ) ; } String workingSetName = memento . getString ( TAG_WORKING_SET_NAME ) ; boolean hasWorkingSetName = workingSetName != null && workingSetName . length ( ) > ; IWorkingSet ws = null ; if ( hasWorkingSetName ) { ws = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSet ( workingSetName ) ; } else if ( isWindowWorkingSet && fWorkbenchPage != null ) { ws = fWorkbenchPage . getAggregateWorkingSet ( ) ; } setWorkingSet ( ws , false ) ; } private boolean useWindowWorkingSetByDefault ( ) { return fAllowWindowWorkingSetByDefault && PlatformUI . getPreferenceStore ( ) . getBoolean ( IWorkbenchPreferenceConstants . USE_WINDOW_WORKING_SET_BY_DEFAULT ) ; } public void fillActionBars ( IActionBars actionBars ) { fillToolBar ( actionBars . getToolBarManager ( ) ) ; fillViewMenu ( actionBars . getMenuManager ( ) ) ; } private void fillToolBar ( IToolBarManager tbm ) { } public void fillViewMenu ( IMenuManager mm ) { if ( mm . find ( IWorkingSetActionGroup . ACTION_GROUP ) == null ) { mm . add ( new Separator ( IWorkingSetActionGroup . ACTION_GROUP ) ) ; } add ( mm , fSelectWorkingSetAction ) ; add ( mm , fClearWorkingSetAction ) ; add ( mm , fEditWorkingSetAction ) ; add ( mm , new Separator ( ) ) ; add ( mm , new Separator ( LRU_GROUP ) ) ; fMenuManager = mm ; fMenuListener = new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager manager ) { removePreviousLRUWorkingSetActions ( manager ) ; addLRUWorkingSetActions ( manager ) ; } } ; fMenuManager . addMenuListener ( fMenuListener ) ; } private void add ( IMenuManager mm , IAction action ) { IContributionItem item = new ActionContributionItem ( action ) ; mm . appendToGroup ( ACTION_GROUP , item ) ; fContributions . add ( item ) ; } private void add ( IMenuManager mm , IContributionItem item ) { mm . appendToGroup ( ACTION_GROUP , item ) ; fContributions . add ( item ) ; } private void removePreviousLRUWorkingSetActions ( IMenuManager mm ) { for ( int i = ; i < fLRUMenuCount ; i ++ ) { String id = WorkingSetMenuContributionItem . getId ( i ) ; IContributionItem item = mm . remove ( id ) ; fContributions . remove ( item ) ; } } private void addLRUWorkingSetActions ( IMenuManager mm ) { IWorkingSet [ ] workingSets = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getRecentWorkingSets ( ) ; Arrays . sort ( workingSets , new WorkingSetComparator ( ) ) ; int currId = ; if ( fWorkbenchPage != null ) { addLRUWorkingSetAction ( mm , currId ++ , fWorkbenchPage . getAggregateWorkingSet ( ) ) ; } for ( int i = ; i < workingSets . length ; i ++ ) { if ( ! workingSets [ i ] . isAggregateWorkingSet ( ) ) { addLRUWorkingSetAction ( mm , currId ++ , workingSets [ i ] ) ; } } fLRUMenuCount = currId ; } private void addLRUWorkingSetAction ( IMenuManager mm , int id , IWorkingSet workingSet ) { IContributionItem item = new WorkingSetMenuContributionItem ( id , this , workingSet ) ; mm . insertBefore ( LRU_GROUP , item ) ; fContributions . add ( item ) ; } public void cleanViewMenu ( IMenuManager menuManager ) { for ( Iterator iter = fContributions . iterator ( ) ; iter . hasNext ( ) ; ) { menuManager . remove ( ( IContributionItem ) iter . next ( ) ) ; } fContributions . clear ( ) ; fMenuManager . removeMenuListener ( fMenuListener ) ; fMenuListener = null ; } public void dispose ( ) { if ( fMenuManager != null && fMenuListener != null ) fMenuManager . removeMenuListener ( fMenuListener ) ; if ( fWorkingSetListener != null ) { PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . removePropertyChangeListener ( fWorkingSetListener ) ; fWorkingSetListener = null ; } fChangeListener = null ; super . dispose ( ) ; } public ViewerFilter getWorkingSetFilter ( ) { return fWorkingSetFilter ; } private void doPropertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( IWorkingSetManager . CHANGE_WORKING_SET_NAME_CHANGE . equals ( property ) ) { fChangeListener . propertyChange ( event ) ; } else if ( IWorkingSetManager . CHANGE_WORKING_SET_CONTENT_CHANGE . equals ( property ) ) { IWorkingSet newWorkingSet = ( IWorkingSet ) event . getNewValue ( ) ; if ( newWorkingSet . equals ( fWorkingSet ) ) { fChangeListener . propertyChange ( event ) ; } } } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; import org . eclipse . jface . action . ContributionItem ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PlatformUI ; public class WorkingSetMenuContributionItem extends ContributionItem { private int fId ; private IWorkingSet fWorkingSet ; private WorkingSetFilterActionGroup fActionGroup ; private Image fImage ; public WorkingSetMenuContributionItem ( int id , WorkingSetFilterActionGroup actionGroup , IWorkingSet workingSet ) { super ( getId ( id ) ) ; Assert . isNotNull ( actionGroup ) ; Assert . isNotNull ( workingSet ) ; fId = id ; fActionGroup = actionGroup ; fWorkingSet = workingSet ; } public void fill ( Menu menu , int index ) { MenuItem mi = new MenuItem ( menu , SWT . RADIO , index ) ; String name = fWorkingSet . getLabel ( ) ; mi . setText ( "" + fId + "" + name ) ; if ( fImage == null ) { ImageDescriptor imageDescriptor = fWorkingSet . getImage ( ) ; if ( imageDescriptor != null ) fImage = imageDescriptor . createImage ( ) ; } mi . setImage ( fImage ) ; mi . setSelection ( fWorkingSet . equals ( fActionGroup . getWorkingSet ( ) ) ) ; mi . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { IWorkingSetManager manager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; fActionGroup . setWorkingSet ( fWorkingSet , true ) ; manager . addRecentWorkingSet ( fWorkingSet ) ; } } ) ; } public void dispose ( ) { if ( fImage != null && ! fImage . isDisposed ( ) ) fImage . dispose ( ) ; fImage = null ; super . dispose ( ) ; } public boolean isDynamic ( ) { return true ; } static String getId ( int id ) { return WorkingSetMenuContributionItem . class . getName ( ) + "" + id ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; public class ClearWorkingSetAction extends Action { private WorkingSetFilterActionGroup fActionGroup ; public ClearWorkingSetAction ( WorkingSetFilterActionGroup actionGroup ) { super ( WorkingSetMessages . ClearWorkingSetAction_text ) ; Assert . isNotNull ( actionGroup ) ; setToolTipText ( WorkingSetMessages . ClearWorkingSetAction_toolTip ) ; setEnabled ( actionGroup . getWorkingSet ( ) != null ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CLEAR_WORKING_SET_ACTION ) ; fActionGroup = actionGroup ; } public void run ( ) { fActionGroup . setWorkingSet ( null , true ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . actions . ActionGroup ; public class ViewActionGroup extends ActionGroup { public static final int SHOW_PROJECTS = ; public static final int SHOW_WORKING_SETS = ; public static final String MODE_CHANGED = ViewActionGroup . class . getName ( ) + "" ; private static final Integer INT_SHOW_PROJECTS = new Integer ( SHOW_PROJECTS ) ; private static final Integer INT_SHOW_WORKING_SETS = new Integer ( SHOW_WORKING_SETS ) ; private IPropertyChangeListener fChangeListener ; private int fMode ; private IMenuManager fMenuManager ; private IWorkingSetActionGroup fActiveActionGroup ; private WorkingSetShowActionGroup fShowActionGroup ; private WorkingSetFilterActionGroup fFilterActionGroup ; public ViewActionGroup ( int mode , IPropertyChangeListener changeListener , IWorkbenchPartSite site ) { fChangeListener = changeListener ; if ( fChangeListener == null ) { fChangeListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { } } ; } fFilterActionGroup = new WorkingSetFilterActionGroup ( site , fChangeListener ) ; fShowActionGroup = new WorkingSetShowActionGroup ( site ) ; fMode = mode ; if ( showWorkingSets ( ) ) fActiveActionGroup = fShowActionGroup ; else fActiveActionGroup = fFilterActionGroup ; } public void dispose ( ) { fFilterActionGroup . dispose ( ) ; fShowActionGroup . dispose ( ) ; fChangeListener = null ; super . dispose ( ) ; } public void setWorkingSetModel ( WorkingSetModel model ) { fShowActionGroup . setWorkingSetMode ( model ) ; } public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; fMenuManager = actionBars . getMenuManager ( ) ; fillViewMenu ( fMenuManager ) ; if ( fActiveActionGroup == null ) fActiveActionGroup = fFilterActionGroup ; ( ( ActionGroup ) fActiveActionGroup ) . fillActionBars ( actionBars ) ; } private void fillViewMenu ( IMenuManager menu ) { IMenuManager showMenu = new MenuManager ( WorkingSetMessages . ViewActionGroup_show_label ) ; fillShowMenu ( showMenu ) ; menu . add ( showMenu ) ; menu . add ( new Separator ( IWorkingSetActionGroup . ACTION_GROUP ) ) ; } private void fillShowMenu ( IMenuManager menu ) { ViewAction projects = new ViewAction ( this , SHOW_PROJECTS ) ; projects . setText ( WorkingSetMessages . ViewActionGroup_projects_label ) ; menu . add ( projects ) ; ViewAction workingSets = new ViewAction ( this , SHOW_WORKING_SETS ) ; workingSets . setText ( WorkingSetMessages . ViewActionGroup_workingSets_label ) ; menu . add ( workingSets ) ; if ( fMode == SHOW_PROJECTS ) { projects . setChecked ( true ) ; } else { workingSets . setChecked ( true ) ; } } public void fillFilters ( StructuredViewer viewer ) { ViewerFilter workingSetFilter = fFilterActionGroup . getWorkingSetFilter ( ) ; if ( showProjects ( ) ) { viewer . addFilter ( workingSetFilter ) ; } else if ( showWorkingSets ( ) ) { viewer . removeFilter ( workingSetFilter ) ; } } public void setMode ( int mode ) { fMode = mode ; fActiveActionGroup . cleanViewMenu ( fMenuManager ) ; PropertyChangeEvent event ; if ( mode == SHOW_PROJECTS ) { fActiveActionGroup = fFilterActionGroup ; event = new PropertyChangeEvent ( this , MODE_CHANGED , INT_SHOW_WORKING_SETS , INT_SHOW_PROJECTS ) ; } else { fActiveActionGroup = fShowActionGroup ; event = new PropertyChangeEvent ( this , MODE_CHANGED , INT_SHOW_PROJECTS , INT_SHOW_WORKING_SETS ) ; } fActiveActionGroup . fillViewMenu ( fMenuManager ) ; fMenuManager . updateAll ( true ) ; if ( fChangeListener != null ) fChangeListener . propertyChange ( event ) ; } public WorkingSetFilterActionGroup getFilterGroup ( ) { return fFilterActionGroup ; } public void restoreState ( IMemento memento ) { fFilterActionGroup . restoreState ( memento ) ; } public void saveState ( IMemento memento ) { fFilterActionGroup . saveState ( memento ) ; } private boolean showProjects ( ) { return fMode == SHOW_PROJECTS ; } private boolean showWorkingSets ( ) { return fMode == SHOW_WORKING_SETS ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . jface . action . IMenuManager ; public interface IWorkingSetActionGroup { public static final String ACTION_GROUP = "" ; public void fillViewMenu ( IMenuManager mm ) ; public void cleanViewMenu ( IMenuManager menuManager ) ; } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . IWorkingSet ; public class ConfigureWorkingSetAction extends Action { private final IWorkbenchPartSite fSite ; private WorkingSetModel fWorkingSetModel ; public ConfigureWorkingSetAction ( IWorkbenchPartSite site ) { super ( WorkingSetMessages . ConfigureWorkingSetAction_label ) ; fSite = site ; } public void setWorkingSetModel ( WorkingSetModel model ) { fWorkingSetModel = model ; } public void run ( ) { List workingSets = new ArrayList ( Arrays . asList ( fWorkingSetModel . getAllWorkingSets ( ) ) ) ; IWorkingSet [ ] activeWorkingSets = fWorkingSetModel . getActiveWorkingSets ( ) ; WorkingSetConfigurationDialog dialog = new WorkingSetConfigurationDialog ( fSite . getShell ( ) , ( IWorkingSet [ ] ) workingSets . toArray ( new IWorkingSet [ workingSets . size ( ) ] ) , activeWorkingSets ) ; dialog . setSelection ( activeWorkingSets ) ; if ( dialog . open ( ) == IDialogConstants . OK_ID ) { IWorkingSet [ ] selection = dialog . getSelection ( ) ; fWorkingSetModel . setActiveWorkingSets ( selection ) ; } } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . ide . IDEActionFactory ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . ui . actions . WorkbenchRunnableAdapter ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . actions . SelectionDispatchAction ; public abstract class OpenCloseWorkingSetAction extends SelectionDispatchAction implements IResourceChangeListener { private static final class CloseWorkingSetAction extends OpenCloseWorkingSetAction { private IAction fProjectAction ; private CloseWorkingSetAction ( IWorkbenchSite site , String label ) { super ( site , label ) ; IActionBars actionBars = getActionBars ( ) ; if ( actionBars != null ) { fProjectAction = actionBars . getGlobalActionHandler ( IDEActionFactory . CLOSE_PROJECT . getId ( ) ) ; } } protected boolean validate ( IProject project ) { return project . isOpen ( ) ; } protected void performOperation ( IProject project , IProgressMonitor monitor ) throws CoreException { project . close ( monitor ) ; } protected void connectToActionBar ( IActionBars actionBars ) { actionBars . setGlobalActionHandler ( IDEActionFactory . CLOSE_PROJECT . getId ( ) , this ) ; actionBars . updateActionBars ( ) ; } protected void disconnectFromActionBar ( IActionBars actionBars ) { actionBars . setGlobalActionHandler ( IDEActionFactory . CLOSE_PROJECT . getId ( ) , fProjectAction ) ; actionBars . updateActionBars ( ) ; } protected String getErrorTitle ( ) { return WorkingSetMessages . OpenCloseWorkingSetAction_close_error_title ; } protected String getErrorMessage ( ) { return WorkingSetMessages . OpenCloseWorkingSetAction_close_error_message ; } } private static final class OpenWorkingSetAction extends OpenCloseWorkingSetAction { private IAction fProjectAction ; private OpenWorkingSetAction ( IWorkbenchSite site , String label ) { super ( site , label ) ; IActionBars actionBars = getActionBars ( ) ; if ( actionBars != null ) { fProjectAction = actionBars . getGlobalActionHandler ( IDEActionFactory . OPEN_PROJECT . getId ( ) ) ; } } protected boolean validate ( IProject project ) { return ! project . isOpen ( ) ; } protected void performOperation ( IProject project , IProgressMonitor monitor ) throws CoreException { project . open ( monitor ) ; } protected void connectToActionBar ( IActionBars actionBars ) { actionBars . setGlobalActionHandler ( IDEActionFactory . OPEN_PROJECT . getId ( ) , this ) ; actionBars . updateActionBars ( ) ; } protected void disconnectFromActionBar ( IActionBars actionBars ) { actionBars . setGlobalActionHandler ( IDEActionFactory . OPEN_PROJECT . getId ( ) , fProjectAction ) ; actionBars . updateActionBars ( ) ; } protected String getErrorTitle ( ) { return WorkingSetMessages . OpenCloseWorkingSetAction_open_error_title ; } protected String getErrorMessage ( ) { return WorkingSetMessages . OpenCloseWorkingSetAction_open_error_message ; } } private OpenCloseWorkingSetAction ( IWorkbenchSite site , String label ) { super ( site ) ; setText ( label ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( this , IResourceChangeEvent . POST_CHANGE ) ; } public static OpenCloseWorkingSetAction createCloseAction ( IWorkbenchSite site ) { return new CloseWorkingSetAction ( site , WorkingSetMessages . OpenCloseWorkingSetAction_close_label ) ; } public static OpenCloseWorkingSetAction createOpenAction ( IWorkbenchSite site ) { return new OpenWorkingSetAction ( site , WorkingSetMessages . OpenCloseWorkingSetAction_open_label ) ; } public void dispose ( ) { ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( this ) ; } public void selectionChanged ( IStructuredSelection selection ) { List projects = getProjects ( selection ) ; IActionBars actionBars = getActionBars ( ) ; if ( projects != null && projects . size ( ) > ) { setEnabled ( true ) ; if ( actionBars != null ) { connectToActionBar ( actionBars ) ; } } else { setEnabled ( false ) ; if ( actionBars != null ) { disconnectFromActionBar ( actionBars ) ; } } } public void run ( IStructuredSelection selection ) { final List projects = getProjects ( selection ) ; if ( projects != null && projects . size ( ) > ) { try { PlatformUI . getWorkbench ( ) . getProgressService ( ) . busyCursorWhile ( new WorkbenchRunnableAdapter ( new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { monitor . beginTask ( "" , projects . size ( ) ) ; for ( Iterator iter = projects . iterator ( ) ; iter . hasNext ( ) ; ) { IProject project = ( IProject ) iter . next ( ) ; performOperation ( project , new SubProgressMonitor ( monitor , ) ) ; } monitor . done ( ) ; } } ) ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , getShell ( ) , getErrorTitle ( ) , getErrorMessage ( ) ) ; } catch ( InterruptedException e ) { } } } protected abstract boolean validate ( IProject project ) ; protected abstract void performOperation ( IProject project , IProgressMonitor monitor ) throws CoreException ; protected abstract void connectToActionBar ( IActionBars actionBars ) ; protected abstract void disconnectFromActionBar ( IActionBars actionBars ) ; protected abstract String getErrorTitle ( ) ; protected abstract String getErrorMessage ( ) ; private List getProjects ( IStructuredSelection selection ) { List result = new ArrayList ( ) ; List elements = selection . toList ( ) ; for ( Iterator iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( ! ( element instanceof IWorkingSet ) ) return null ; List projects = getProjects ( ( IWorkingSet ) element ) ; if ( projects == null ) return null ; result . addAll ( projects ) ; } return result ; } private List getProjects ( IWorkingSet set ) { List result = new ArrayList ( ) ; IAdaptable [ ] elements = set . getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { Object element = elements [ i ] ; IProject project = null ; if ( element instanceof IProject ) { project = ( IProject ) element ; } else if ( element instanceof IRubyProject ) { project = ( ( IRubyProject ) element ) . getProject ( ) ; } if ( project != null && validate ( project ) ) result . add ( project ) ; } return result ; } protected IActionBars getActionBars ( ) { if ( getSite ( ) instanceof IViewSite ) { return ( ( IViewSite ) getSite ( ) ) . getActionBars ( ) ; } else { return null ; } } public void resourceChanged ( IResourceChangeEvent event ) { IResourceDelta delta = event . getDelta ( ) ; if ( delta != null ) { IResourceDelta [ ] projDeltas = delta . getAffectedChildren ( IResourceDelta . CHANGED ) ; for ( int i = ; i < projDeltas . length ; ++ i ) { IResourceDelta projDelta = projDeltas [ i ] ; if ( ( projDelta . getFlags ( ) & IResourceDelta . OPEN ) != ) { Shell shell = getShell ( ) ; if ( ! shell . isDisposed ( ) ) { shell . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { update ( getSelection ( ) ) ; } } ) ; } return ; } } } } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; public class ViewAction extends Action { private final ViewActionGroup fActionGroup ; private final int fMode ; public ViewAction ( ViewActionGroup group , int mode ) { super ( "" , AS_RADIO_BUTTON ) ; Assert . isNotNull ( group ) ; fActionGroup = group ; fMode = mode ; } public void run ( ) { if ( isChecked ( ) ) fActionGroup . setMode ( fMode ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; class RubyWorkingSetPageContentProvider extends StandardRubyElementContentProvider { public boolean hasChildren ( Object element ) { if ( element instanceof IProject && ! ( ( IProject ) element ) . isAccessible ( ) ) return false ; return super . hasChildren ( element ) ; } public Object [ ] getChildren ( Object parentElement ) { try { if ( parentElement instanceof IRubyModel ) return concatenate ( super . getChildren ( parentElement ) , getNonRubyProjects ( ( IRubyModel ) parentElement ) ) ; if ( parentElement instanceof IProject ) return ( ( IProject ) parentElement ) . members ( ) ; return super . getChildren ( parentElement ) ; } catch ( CoreException e ) { return NO_CHILDREN ; } } private Object [ ] getNonRubyProjects ( IRubyModel model ) throws RubyModelException { return model . getNonRubyResources ( ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTreeViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . ITreeViewerListener ; import org . eclipse . jface . viewers . TreeExpansionEvent ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . swt . widgets . TreeItem ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . IWorkingSetPage ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . DecoratingRubyLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . RubyElementSorter ; public class RubyWorkingSetPage extends WizardPage implements IWorkingSetPage { final private static String PAGE_TITLE = WorkingSetMessages . RubyWorkingSetPage_title ; final private static String PAGE_ID = "" ; private Text fWorkingSetName ; private CheckboxTreeViewer fTree ; private ITreeContentProvider fTreeContentProvider ; private boolean fFirstCheck ; private IWorkingSet fWorkingSet ; public RubyWorkingSetPage ( ) { super ( PAGE_ID , PAGE_TITLE , RubyPluginImages . DESC_WIZBAN_RUBY_WORKINGSET ) ; setDescription ( WorkingSetMessages . RubyWorkingSetPage_workingSet_description ) ; fFirstCheck = true ; } public void createControl ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( new GridLayout ( ) ) ; composite . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ) ; setControl ( composite ) ; Label label = new Label ( composite , SWT . WRAP ) ; label . setText ( WorkingSetMessages . RubyWorkingSetPage_workingSet_name ) ; GridData gd = new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL | GridData . VERTICAL_ALIGN_CENTER ) ; label . setLayoutData ( gd ) ; fWorkingSetName = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; fWorkingSetName . setLayoutData ( new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL ) ) ; fWorkingSetName . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { validateInput ( ) ; } } ) ; fWorkingSetName . setFocus ( ) ; label = new Label ( composite , SWT . WRAP ) ; label . setText ( WorkingSetMessages . RubyWorkingSetPage_workingSet_content ) ; gd = new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL | GridData . VERTICAL_ALIGN_CENTER ) ; label . setLayoutData ( gd ) ; fTree = new CheckboxTreeViewer ( composite , SWT . BORDER | SWT . H_SCROLL | SWT . V_SCROLL ) ; gd = new GridData ( GridData . FILL_BOTH | GridData . GRAB_VERTICAL ) ; gd . heightHint = convertHeightInCharsToPixels ( ) ; fTree . getControl ( ) . setLayoutData ( gd ) ; fTreeContentProvider = new RubyWorkingSetPageContentProvider ( ) ; fTree . setContentProvider ( fTreeContentProvider ) ; AppearanceAwareLabelProvider fRubyElementLabelProvider = new AppearanceAwareLabelProvider ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS | RubyElementLabels . P_COMPRESSED , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS | RubyElementImageProvider . SMALL_ICONS ) ; fTree . setLabelProvider ( new DecoratingRubyLabelProvider ( fRubyElementLabelProvider ) ) ; fTree . setSorter ( new RubyElementSorter ( ) ) ; fTree . setUseHashlookup ( true ) ; fTree . setInput ( RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ) ; fTree . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { handleCheckStateChange ( event ) ; } } ) ; fTree . addTreeListener ( new ITreeViewerListener ( ) { public void treeCollapsed ( TreeExpansionEvent event ) { } public void treeExpanded ( TreeExpansionEvent event ) { final Object element = event . getElement ( ) ; if ( fTree . getGrayed ( element ) == false ) BusyIndicator . showWhile ( getShell ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { setSubtreeChecked ( element , fTree . getChecked ( element ) , false ) ; } } ) ; } } ) ; Composite buttonComposite = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( , false ) ; layout . marginWidth = ; layout . marginHeight = ; buttonComposite . setLayout ( layout ) ; buttonComposite . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ) ; Button selectAllButton = new Button ( buttonComposite , SWT . PUSH ) ; selectAllButton . setText ( WorkingSetMessages . RubyWorkingSetPage_selectAll_label ) ; selectAllButton . setToolTipText ( WorkingSetMessages . RubyWorkingSetPage_selectAll_toolTip ) ; selectAllButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent selectionEvent ) { fTree . setCheckedElements ( fTreeContentProvider . getElements ( fTree . getInput ( ) ) ) ; validateInput ( ) ; } } ) ; selectAllButton . setLayoutData ( new GridData ( ) ) ; SWTUtil . setButtonDimensionHint ( selectAllButton ) ; Button deselectAllButton = new Button ( buttonComposite , SWT . PUSH ) ; deselectAllButton . setText ( WorkingSetMessages . RubyWorkingSetPage_deselectAll_label ) ; deselectAllButton . setToolTipText ( WorkingSetMessages . RubyWorkingSetPage_deselectAll_toolTip ) ; deselectAllButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent selectionEvent ) { fTree . setCheckedElements ( new Object [ ] ) ; validateInput ( ) ; } } ) ; deselectAllButton . setLayoutData ( new GridData ( ) ) ; SWTUtil . setButtonDimensionHint ( deselectAllButton ) ; if ( fWorkingSet != null ) fWorkingSetName . setText ( fWorkingSet . getName ( ) ) ; initializeCheckedState ( ) ; validateInput ( ) ; Dialog . applyDialogFont ( composite ) ; } public IWorkingSet getSelection ( ) { return fWorkingSet ; } public void setSelection ( IWorkingSet workingSet ) { Assert . isNotNull ( workingSet , "" ) ; fWorkingSet = workingSet ; if ( getContainer ( ) != null && getShell ( ) != null && fWorkingSetName != null ) { fFirstCheck = false ; fWorkingSetName . setText ( fWorkingSet . getName ( ) ) ; initializeCheckedState ( ) ; validateInput ( ) ; } } public void finish ( ) { String workingSetName = fWorkingSetName . getText ( ) ; ArrayList elements = new ArrayList ( ) ; findCheckedElements ( elements , fTree . getInput ( ) ) ; if ( fWorkingSet == null ) { IWorkingSetManager workingSetManager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; fWorkingSet = workingSetManager . createWorkingSet ( workingSetName , ( IAdaptable [ ] ) elements . toArray ( new IAdaptable [ elements . size ( ) ] ) ) ; } else { IAdaptable [ ] oldItems = fWorkingSet . getElements ( ) ; ArrayList closedWithChildren = new ArrayList ( elements . size ( ) ) ; for ( int i = ; i < oldItems . length ; i ++ ) { IResource oldResource = null ; if ( oldItems [ i ] instanceof IResource ) { oldResource = ( IResource ) oldItems [ i ] ; } else { oldResource = ( IResource ) oldItems [ i ] . getAdapter ( IResource . class ) ; } if ( oldResource != null && oldResource . isAccessible ( ) == false ) { IProject project = oldResource . getProject ( ) ; if ( elements . contains ( project ) || closedWithChildren . contains ( project ) ) { elements . add ( oldItems [ i ] ) ; elements . remove ( project ) ; closedWithChildren . add ( project ) ; } } } fWorkingSet . setName ( workingSetName ) ; fWorkingSet . setElements ( ( IAdaptable [ ] ) elements . toArray ( new IAdaptable [ elements . size ( ) ] ) ) ; } } private void validateInput ( ) { String errorMessage = null ; String infoMessage = null ; String newText = fWorkingSetName . getText ( ) ; if ( newText . equals ( newText . trim ( ) ) == false ) errorMessage = WorkingSetMessages . RubyWorkingSetPage_warning_nameWhitespace ; if ( newText . equals ( "" ) ) { if ( fFirstCheck ) { setPageComplete ( false ) ; fFirstCheck = false ; return ; } else errorMessage = WorkingSetMessages . RubyWorkingSetPage_warning_nameMustNotBeEmpty ; } fFirstCheck = false ; if ( errorMessage == null && ( fWorkingSet == null || newText . equals ( fWorkingSet . getName ( ) ) == false ) ) { IWorkingSet [ ] workingSets = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSets ( ) ; for ( int i = ; i < workingSets . length ; i ++ ) { if ( newText . equals ( workingSets [ i ] . getName ( ) ) ) { errorMessage = WorkingSetMessages . RubyWorkingSetPage_warning_workingSetExists ; } } } if ( ! hasCheckedElement ( ) ) infoMessage = WorkingSetMessages . RubyWorkingSetPage_warning_resourceMustBeChecked ; setMessage ( infoMessage , INFORMATION ) ; setErrorMessage ( errorMessage ) ; setPageComplete ( errorMessage == null ) ; } private boolean hasCheckedElement ( ) { TreeItem [ ] items = fTree . getTree ( ) . getItems ( ) ; for ( int i = ; i < items . length ; i ++ ) { if ( items [ i ] . getChecked ( ) ) return true ; } return false ; } private void findCheckedElements ( List checkedResources , Object parent ) { Object [ ] children = fTreeContentProvider . getChildren ( parent ) ; for ( int i = ; i < children . length ; i ++ ) { if ( fTree . getGrayed ( children [ i ] ) ) findCheckedElements ( checkedResources , children [ i ] ) ; else if ( fTree . getChecked ( children [ i ] ) ) checkedResources . add ( children [ i ] ) ; } } void handleCheckStateChange ( final CheckStateChangedEvent event ) { BusyIndicator . showWhile ( getShell ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { IAdaptable element = ( IAdaptable ) event . getElement ( ) ; boolean state = event . getChecked ( ) ; fTree . setGrayed ( element , false ) ; if ( isExpandable ( element ) ) setSubtreeChecked ( element , state , state ) ; updateParentState ( element , state ) ; validateInput ( ) ; } } ) ; } private void setSubtreeChecked ( Object parent , boolean state , boolean checkExpandedState ) { if ( ! ( parent instanceof IAdaptable ) ) return ; IContainer container = ( IContainer ) ( ( IAdaptable ) parent ) . getAdapter ( IContainer . class ) ; if ( ( ! fTree . getExpandedState ( parent ) && checkExpandedState ) || ( container != null && ! container . isAccessible ( ) ) ) return ; Object [ ] children = fTreeContentProvider . getChildren ( parent ) ; for ( int i = children . length - ; i >= ; i -- ) { Object element = children [ i ] ; if ( state ) { fTree . setChecked ( element , true ) ; fTree . setGrayed ( element , false ) ; } else fTree . setGrayChecked ( element , false ) ; if ( isExpandable ( element ) ) setSubtreeChecked ( element , state , true ) ; } } private void updateParentState ( Object child , boolean baseChildState ) { if ( child == null ) return ; if ( child instanceof IAdaptable ) { IResource resource = ( IResource ) ( ( IAdaptable ) child ) . getAdapter ( IResource . class ) ; if ( resource != null && ! resource . isAccessible ( ) ) return ; } Object parent = fTreeContentProvider . getParent ( child ) ; if ( parent == null ) return ; boolean allSameState = true ; Object [ ] children = null ; children = fTreeContentProvider . getChildren ( parent ) ; for ( int i = children . length - ; i >= ; i -- ) { if ( fTree . getChecked ( children [ i ] ) != baseChildState || fTree . getGrayed ( children [ i ] ) ) { allSameState = false ; break ; } } fTree . setGrayed ( parent , ! allSameState ) ; fTree . setChecked ( parent , ! allSameState || baseChildState ) ; updateParentState ( parent , baseChildState ) ; } private void initializeCheckedState ( ) { BusyIndicator . showWhile ( getShell ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { Object [ ] elements ; if ( fWorkingSet == null ) { IWorkbenchPage page = RubyPlugin . getActivePage ( ) ; if ( page == null ) return ; IWorkbenchPart part = RubyPlugin . getActivePage ( ) . getActivePart ( ) ; if ( part == null ) return ; try { elements = SelectionConverter . getStructuredSelection ( part ) . toArray ( ) ; for ( int i = ; i < elements . length ; i ++ ) { if ( elements [ i ] instanceof IResource ) { IRubyElement je = ( IRubyElement ) ( ( IResource ) elements [ i ] ) . getAdapter ( IRubyElement . class ) ; if ( je != null && je . exists ( ) && je . getRubyProject ( ) . isOnLoadpath ( ( IResource ) elements [ i ] ) ) elements [ i ] = je ; } } } catch ( RubyModelException e ) { return ; } } else elements = fWorkingSet . getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { Object element = elements [ i ] ; if ( element instanceof IResource ) { IProject project = ( ( IResource ) element ) . getProject ( ) ; if ( ! project . isAccessible ( ) ) elements [ i ] = project ; } if ( element instanceof IRubyElement ) { IRubyProject jProject = ( ( IRubyElement ) element ) . getRubyProject ( ) ; if ( jProject != null && ! jProject . getProject ( ) . isAccessible ( ) ) elements [ i ] = jProject . getProject ( ) ; } } fTree . setCheckedElements ( elements ) ; for ( int i = ; i < elements . length ; i ++ ) { Object element = elements [ i ] ; if ( isExpandable ( element ) ) setSubtreeChecked ( element , true , true ) ; updateParentState ( element , true ) ; } } } ) ; } private boolean isExpandable ( Object element ) { return ( element instanceof IRubyProject || element instanceof ISourceFolderRoot || element instanceof ISourceFolder || element instanceof IRubyModel || element instanceof IContainer ) ; } } package org . rubypeople . rdt . internal . ui . workingsets ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IStorage ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . ui . IWorkingSet ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; public class WorkingSetFilter extends ViewerFilter { private IWorkingSet fWorkingSet = null ; private IAdaptable [ ] fCachedWorkingSet = null ; public IWorkingSet getWorkingSet ( ) { return fWorkingSet ; } public void setWorkingSet ( IWorkingSet workingSet ) { fWorkingSet = workingSet ; } public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( fWorkingSet == null || ( fWorkingSet . isAggregateWorkingSet ( ) && fWorkingSet . getElements ( ) . length == ) ) return true ; if ( element instanceof IRubyElement ) return isEnclosing ( ( IRubyElement ) element ) ; if ( element instanceof IResource ) return isEnclosing ( ( ( IResource ) element ) . getFullPath ( ) ) ; if ( element instanceof LoadPathContainer ) { return isEnclosing ( ( LoadPathContainer ) element ) ; } if ( element instanceof IAdaptable ) { IAdaptable adaptable = ( IAdaptable ) element ; IRubyElement je = ( IRubyElement ) adaptable . getAdapter ( IRubyElement . class ) ; if ( je != null ) return isEnclosing ( je ) ; IResource resource = ( IResource ) adaptable . getAdapter ( IResource . class ) ; if ( resource != null ) return isEnclosing ( resource . getFullPath ( ) ) ; } return true ; } private boolean isEnclosing ( LoadPathContainer container ) { Object [ ] roots = container . getSourceFolderRoots ( ) ; if ( roots . length > ) return isEnclosing ( ( ISourceFolderRoot ) roots [ ] ) ; return false ; } public Object [ ] filter ( Viewer viewer , Object parent , Object [ ] elements ) { Object [ ] result = null ; if ( fWorkingSet != null ) fCachedWorkingSet = fWorkingSet . getElements ( ) ; try { result = super . filter ( viewer , parent , elements ) ; } finally { fCachedWorkingSet = null ; } return result ; } private boolean isEnclosing ( IPath elementPath ) { if ( elementPath == null ) return false ; IAdaptable [ ] cachedWorkingSet = fCachedWorkingSet ; if ( cachedWorkingSet == null ) cachedWorkingSet = fWorkingSet . getElements ( ) ; int length = cachedWorkingSet . length ; for ( int i = ; i < length ; i ++ ) { if ( isEnclosing ( cachedWorkingSet [ i ] , elementPath ) ) return true ; } return false ; } public boolean isEnclosing ( IRubyElement element ) { Assert . isNotNull ( element ) ; IAdaptable [ ] cachedWorkingSet = fCachedWorkingSet ; if ( cachedWorkingSet == null ) cachedWorkingSet = fWorkingSet . getElements ( ) ; boolean isElementPathComputed = false ; IPath elementPath = null ; int length = cachedWorkingSet . length ; for ( int i = ; i < length ; i ++ ) { IRubyElement scopeElement = ( IRubyElement ) cachedWorkingSet [ i ] . getAdapter ( IRubyElement . class ) ; if ( scopeElement != null ) { IRubyElement searchedElement = element ; while ( searchedElement != null ) { if ( searchedElement . equals ( scopeElement ) ) return true ; else { if ( scopeElement . getElementType ( ) == IRubyElement . RUBY_PROJECT && searchedElement . getElementType ( ) == IRubyElement . SOURCE_FOLDER_ROOT ) { ISourceFolderRoot pkgRoot = ( ISourceFolderRoot ) searchedElement ; if ( pkgRoot . isExternal ( ) && pkgRoot . isArchive ( ) ) { if ( ( ( IRubyProject ) scopeElement ) . isOnLoadpath ( searchedElement ) ) return true ; } } if ( searchedElement . getElementType ( ) == IRubyElement . SOURCE_FOLDER && scopeElement . getElementType ( ) == IRubyElement . SOURCE_FOLDER ) { IPath searchPath = searchedElement . getPath ( ) ; IPath scopePath = scopeElement . getPath ( ) ; ISourceFolderRoot root = ( ISourceFolderRoot ) searchedElement . getParent ( ) ; IPath rootPath = root . getPath ( ) ; IPath parentFolderPath = searchPath . removeFirstSegments ( rootPath . segmentCount ( ) ) . removeLastSegments ( ) ; searchedElement = root . getSourceFolder ( parentFolderPath . segments ( ) ) ; } else { searchedElement = searchedElement . getParent ( ) ; } if ( searchedElement != null && searchedElement . getElementType ( ) == IRubyElement . SCRIPT ) { IRubyScript unit = ( IRubyScript ) searchedElement ; unit = unit . getPrimary ( ) ; } } } while ( scopeElement != null ) { if ( element . equals ( scopeElement ) ) return true ; else scopeElement = scopeElement . getParent ( ) ; } } else { if ( ! isElementPathComputed ) { IResource elementResource = ( IResource ) element . getAdapter ( IResource . class ) ; if ( elementResource != null ) elementPath = elementResource . getFullPath ( ) ; } if ( isEnclosing ( cachedWorkingSet [ i ] , elementPath ) ) return true ; } } return false ; } private boolean isEnclosing ( IAdaptable element , IPath path ) { if ( path == null ) return false ; IPath elementPath = null ; IResource elementResource = ( IResource ) element . getAdapter ( IResource . class ) ; if ( elementResource != null ) elementPath = elementResource . getFullPath ( ) ; if ( elementPath == null ) { IRubyElement javaElement = ( IRubyElement ) element . getAdapter ( IRubyElement . class ) ; if ( javaElement != null ) elementPath = javaElement . getPath ( ) ; } if ( elementPath == null && element instanceof IStorage ) elementPath = ( ( IStorage ) element ) . getFullPath ( ) ; if ( elementPath == null ) return false ; if ( elementPath . isPrefixOf ( path ) ) return true ; if ( path . isPrefixOf ( elementPath ) ) return true ; return false ; } } package org . rubypeople . rdt . internal . ui ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . ui . IViewPart ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . packageview . PackageExplorerPart ; public class RubyExplorerTracker implements ISelectionChangedListener { private IProject currentlySelectedProject ; private Set < IRubyProjectListener > projectListeners ; public RubyExplorerTracker ( ) { currentlySelectedProject = null ; projectListeners = new HashSet < IRubyProjectListener > ( ) ; } public void selectionChanged ( SelectionChangedEvent event ) { if ( event == null ) return ; ISelection sel = event . getSelection ( ) ; if ( ! ( sel instanceof IStructuredSelection ) ) return ; IProject inProject = getProjectFromSelection ( sel ) ; if ( inProject == null ) return ; if ( ! inProject . isOpen ( ) ) { setSelectedProject ( null ) ; } else { setSelectedProject ( inProject ) ; } } public void addProjectListener ( IRubyProjectListener listener ) { projectListeners . add ( listener ) ; listener . projectSelected ( currentlySelectedProject ) ; } public void removeProjectListener ( IRubyProjectListener listener ) { projectListeners . remove ( listener ) ; } private void notifyObservers ( ) { for ( IRubyProjectListener listener : projectListeners ) { listener . projectSelected ( currentlySelectedProject ) ; } } private void setSelectedProject ( IProject currentSelectedProject ) { if ( currentSelectedProject != this . currentlySelectedProject ) { this . currentlySelectedProject = currentSelectedProject ; notifyObservers ( ) ; } } public IProject getSelectedProject ( ) { return currentlySelectedProject ; } public IProject getSelectedByNatureID ( String natureId ) { try { if ( currentlySelectedProject == null ) { IViewPart part = PackageExplorerPart . getFromActivePerspective ( ) ; if ( part != null ) { ISelection selection = part . getSite ( ) . getSelectionProvider ( ) . getSelection ( ) ; currentlySelectedProject = getProjectFromSelection ( selection ) ; } } if ( ( currentlySelectedProject != null ) && currentlySelectedProject . hasNature ( natureId ) ) { return currentlySelectedProject ; } } catch ( CoreException e ) { RubyPlugin . log ( Status . ERROR , "" + currentlySelectedProject . getName ( ) , e ) ; } return null ; } private static IProject getProjectFromSelection ( ISelection sel ) { if ( ! ( sel instanceof IStructuredSelection ) ) return null ; IStructuredSelection selection = ( IStructuredSelection ) sel ; if ( selection == null || selection . getFirstElement ( ) == null ) { return null ; } Object element = selection . getFirstElement ( ) ; if ( element instanceof IRubyElement ) { return ( ( IRubyElement ) selection . getFirstElement ( ) ) . getRubyProject ( ) . getProject ( ) ; } else if ( element instanceof IResource ) { return ( ( IResource ) element ) . getProject ( ) ; } return null ; } public IProject getSelectedRubyProject ( ) { return getSelectedByNatureID ( RubyCore . NATURE_ID ) ; } public interface IRubyProjectListener { void projectSelected ( IProject project ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . Iterator ; import java . util . ResourceBundle ; import java . util . Stack ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . GroupMarker ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . AbstractInformationControlManager ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPositionCategoryException ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension ; import org . eclipse . jface . text . IDocumentListener ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . ILineTracker ; import org . eclipse . jface . text . IPositionUpdater ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . ITextViewerExtension ; import org . eclipse . jface . text . ITextViewerExtension2 ; import org . eclipse . jface . text . ITextViewerExtension4 ; import org . eclipse . jface . text . ITextViewerExtension5 ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . text . information . IInformationProvider ; import org . eclipse . jface . text . information . IInformationProviderExtension ; import org . eclipse . jface . text . information . IInformationProviderExtension2 ; import org . eclipse . jface . text . information . InformationPresenter ; import org . eclipse . jface . text . link . ILinkedModeListener ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . jface . text . link . LinkedModeUI ; import org . eclipse . jface . text . link . LinkedPosition ; import org . eclipse . jface . text . link . LinkedPositionGroup ; import org . eclipse . jface . text . link . LinkedModeUI . ExitFlags ; import org . eclipse . jface . text . link . LinkedModeUI . IExitPolicy ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationHover ; import org . eclipse . jface . text . source . IAnnotationHoverExtension ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . ICharacterPairMatcher ; import org . eclipse . jface . text . source . ILineRange ; import org . eclipse . jface . text . source . IOverviewRuler ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . ISourceViewerExtension3 ; import org . eclipse . jface . text . source . IVerticalRuler ; import org . eclipse . jface . text . source . IVerticalRulerInfo ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . jface . text . source . projection . ProjectionSupport ; import org . eclipse . jface . text . source . projection . ProjectionViewer ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . custom . VerifyKeyListener ; import org . eclipse . swt . events . VerifyEvent ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IPartListener2 ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . SelectionEnabler ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . editors . text . IEncodingSupport ; import org . eclipse . ui . help . WorkbenchHelp ; import org . eclipse . ui . part . IShowInSource ; import org . eclipse . ui . part . IShowInTargetList ; import org . eclipse . ui . part . ShowInContext ; import org . eclipse . ui . texteditor . AnnotationPreference ; import org . eclipse . ui . texteditor . ContentAssistAction ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . IEditorStatusLine ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . eclipse . ui . texteditor . MarkerAnnotation ; import org . eclipse . ui . texteditor . ResourceAction ; import org . eclipse . ui . texteditor . TextEditorAction ; import org . eclipse . ui . texteditor . TextOperationAction ; import org . eclipse . ui . texteditor . link . EditorLinkedModeUI ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . corext . util . CodeFormatterUtil ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . CompositeActionGroup ; import org . rubypeople . rdt . internal . ui . actions . FoldingActionGroup ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . text . HTMLTextPresenter ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . RubyHeuristicScanner ; import org . rubypeople . rdt . internal . ui . text . Symbols ; import org . rubypeople . rdt . internal . ui . text . ruby . IRubyReconcilingListener ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . SourceViewerInformationControl ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . actions . FormatAction ; import org . rubypeople . rdt . ui . actions . IRubyEditorActionDefinitionIds ; import org . rubypeople . rdt . ui . actions . OpenEditorActionGroup ; import org . rubypeople . rdt . ui . actions . OpenViewActionGroup ; import org . rubypeople . rdt . ui . actions . RubyActionGroup ; import org . rubypeople . rdt . ui . actions . RubySearchActionGroup ; import org . rubypeople . rdt . ui . actions . ShowInRubyExplorerViewAction ; import org . rubypeople . rdt . ui . actions . SurroundWithBeginRescueAction ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingStructureProvider ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingStructureProviderExtension ; public class RubyEditor extends RubyAbstractEditor implements IRubyReconcilingListener { private ProjectionSupport fProjectionSupport ; private TabConverter fTabConverter ; private final static String CLOSE_STRINGS = PreferenceConstants . EDITOR_CLOSE_STRINGS ; private final static String CLOSE_BRACKETS = PreferenceConstants . EDITOR_CLOSE_BRACKETS ; private final static String CLOSE_BRACES = PreferenceConstants . EDITOR_CLOSE_BRACES ; private final static String CODE_FORMATTER_TAB_SIZE = DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ; private final static String SPACES_FOR_TABS = DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ; private final Object fReconcilerLock = new Object ( ) ; private IRubyFoldingStructureProvider fProjectionModelUpdater ; protected OverrideIndicatorManager fOverrideIndicatorManager ; private boolean fIsUpdatingAnnotationViews = false ; private IMarker fLastMarkerTarget = null ; private ToggleFoldingRunner fFoldingRunner ; private FoldingActionGroup fFoldingGroup ; private ListenerList fReconcilingListeners = new ListenerList ( ListenerList . IDENTITY ) ; private BracketInserter fBracketInserter = new BracketInserter ( ) ; private CompositeActionGroup fActionGroups ; private CompositeActionGroup fContextMenuGroup ; private RubyActionGroup fGenerateActionGroup ; private InformationPresenter fInformationPresenter ; private StringSubstitutionConverter fStringConverter ; public RubyEditor ( ) { super ( ) ; setDocumentProvider ( RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) ) ; this . setRulerContextMenuId ( RubyUI . ID_RULER_CONTEXT_MENU ) ; this . setEditorContextMenuId ( RubyUI . ID_EDITOR_CONTEXT_MENU ) ; setKeyBindingScopes ( new String [ ] { "" } ) ; setOutlinerContextMenuId ( "" ) ; } protected ActionGroup getActionGroup ( ) { return fActionGroups ; } protected void createActions ( ) { super . createActions ( ) ; ActionGroup oeg , ovg , rsg ; fActionGroups = new CompositeActionGroup ( new ActionGroup [ ] { oeg = new OpenEditorActionGroup ( this ) , ovg = new OpenViewActionGroup ( this ) , rsg = new RubySearchActionGroup ( this ) } ) ; fGenerateActionGroup = new RubyActionGroup ( this , ITextEditorActionConstants . GROUP_EDIT ) ; fContextMenuGroup = new CompositeActionGroup ( new ActionGroup [ ] { oeg , ovg , rsg , fGenerateActionGroup } ) ; fFoldingGroup = new FoldingActionGroup ( this , getViewer ( ) ) ; ISelectionProvider provider = getSite ( ) . getSelectionProvider ( ) ; ISelection selection = provider . getSelection ( ) ; ResourceAction resAction = new TextOperationAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this , ISourceViewer . INFORMATION , true ) ; resAction = new InformationDispatchAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , ( TextOperationAction ) resAction ) ; resAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SHOW_RDOC ) ; setAction ( "" , resAction ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( resAction , IRubyHelpContextIds . SHOW_JAVADOC_ACTION ) ; SurroundWithBeginRescueAction beginRescueAction = new SurroundWithBeginRescueAction ( this ) ; beginRescueAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SURROUND_WITH_BEGIN_RESCUE ) ; beginRescueAction . update ( selection ) ; provider . addSelectionChangedListener ( beginRescueAction ) ; setAction ( SurroundWithBeginRescueAction . SURROUND_WTH_BEGIN_RESCUE , beginRescueAction ) ; Action action = new ContentAssistAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS ) ; setAction ( "" , action ) ; action = new TextOperationAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this , ITextOperationTarget . PREFIX ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . COMMENT ) ; setAction ( "" , action ) ; action = new TextOperationAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this , ITextOperationTarget . STRIP_PREFIX ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . UNCOMMENT ) ; setAction ( "" , action ) ; action = new ToggleCommentAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . TOGGLE_COMMENT ) ; setAction ( "" , action ) ; markAsStateDependentAction ( "" , true ) ; WorkbenchHelp . setHelp ( action , IRubyHelpContextIds . TOGGLE_COMMENT_ACTION ) ; configureToggleCommentAction ( ) ; action = new RubySelectMarkerRulerAction2 ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this ) ; setAction ( "" , action ) ; action = new ShowInRubyExplorerViewAction ( this ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SHOW_IN_RUBY_RESOURCES_VIEW ) ; setAction ( "" , action ) ; action = new GotoMatchingBracketAction ( this ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . GOTO_MATCHING_BRACKET ) ; setAction ( GotoMatchingBracketAction . GOTO_MATCHING_BRACKET , action ) ; action = new TextOperationAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this , RubySourceViewer . SHOW_OUTLINE , true ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SHOW_OUTLINE ) ; setAction ( IRubyEditorActionDefinitionIds . SHOW_OUTLINE , action ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( action , IRubyHelpContextIds . SHOW_OUTLINE_ACTION ) ; action = new TextOperationAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this , RubySourceViewer . OPEN_STRUCTURE , true ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_STRUCTURE ) ; setAction ( IRubyEditorActionDefinitionIds . OPEN_STRUCTURE , action ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( action , IRubyHelpContextIds . OPEN_STRUCTURE_ACTION ) ; action = new TextOperationAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this , RubySourceViewer . SHOW_HIERARCHY , true ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_HIERARCHY ) ; setAction ( IRubyEditorActionDefinitionIds . OPEN_HIERARCHY , action ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( action , IRubyHelpContextIds . OPEN_HIERARCHY_ACTION ) ; action = new FormatAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , this ) ; action . setActionDefinitionId ( IRubyEditorActionDefinitionIds . FORMAT ) ; setAction ( "" , action ) ; } private void configureToggleCommentAction ( ) { IAction action = getAction ( "" ) ; if ( action instanceof ToggleCommentAction ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; SourceViewerConfiguration configuration = getSourceViewerConfiguration ( ) ; ( ( ToggleCommentAction ) action ) . configure ( sourceViewer , configuration ) ; } } public void createPartControl ( Composite parent ) { super . createPartControl ( parent ) ; IInformationControlCreator informationControlCreator = new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell shell ) { boolean cutDown = false ; int style = cutDown ? SWT . NONE : ( SWT . V_SCROLL | SWT . H_SCROLL ) ; return new DefaultInformationControl ( shell , SWT . RESIZE | SWT . TOOL , style , new HTMLTextPresenter ( cutDown ) ) ; } } ; fInformationPresenter = new InformationPresenter ( informationControlCreator ) ; fInformationPresenter . setSizeConstraints ( , , true , true ) ; fInformationPresenter . install ( getSourceViewer ( ) ) ; fInformationPresenter . setDocumentPartitioning ( IRubyPartitions . RUBY_PARTITIONING ) ; if ( isTabConversionEnabled ( ) ) startTabConversion ( ) ; startStringSubstitutionConverter ( ) ; ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer instanceof ITextViewerExtension ) { IPreferenceStore preferenceStore = getPreferenceStore ( ) ; boolean closeBrackets = preferenceStore . getBoolean ( CLOSE_BRACKETS ) ; boolean closeBraces = preferenceStore . getBoolean ( CLOSE_BRACES ) ; boolean closeStrings = preferenceStore . getBoolean ( CLOSE_STRINGS ) ; fBracketInserter . setCloseBracketsEnabled ( closeBrackets ) ; fBracketInserter . setCloseBracesEnabled ( closeBraces ) ; fBracketInserter . setCloseStringsEnabled ( closeStrings ) ; ( ( ITextViewerExtension ) sourceViewer ) . prependVerifyKeyListener ( fBracketInserter ) ; } if ( sourceViewer instanceof ProjectionViewer ) { if ( isFoldingEnabled ( ) ) { ProjectionViewer pv = ( ProjectionViewer ) sourceViewer ; pv . doOperation ( ProjectionViewer . TOGGLE ) ; } } } public void resetProjection ( ) { if ( fProjectionModelUpdater != null ) { fProjectionModelUpdater . initialize ( ) ; } } protected void rulerContextMenuAboutToShow ( IMenuManager menu ) { super . rulerContextMenuAboutToShow ( menu ) ; IMenuManager foldingMenu = new MenuManager ( RubyEditorMessages . Editor_FoldingMenu_name , "" ) ; menu . appendToGroup ( ITextEditorActionConstants . GROUP_RULERS , foldingMenu ) ; IAction action = getAction ( "" ) ; foldingMenu . add ( action ) ; action = getAction ( "" ) ; foldingMenu . add ( action ) ; action = getAction ( "" ) ; foldingMenu . add ( action ) ; action = getAction ( "" ) ; foldingMenu . add ( action ) ; action = getAction ( "" ) ; foldingMenu . add ( action ) ; action = getAction ( "" ) ; foldingMenu . add ( action ) ; } private Annotation getAnnotation ( int offset , int length ) { IAnnotationModel model = getDocumentProvider ( ) . getAnnotationModel ( getEditorInput ( ) ) ; Iterator e = new RubyAnnotationIterator ( model , true , true ) ; while ( e . hasNext ( ) ) { Annotation a = ( Annotation ) e . next ( ) ; if ( ! isNavigationTarget ( a ) ) continue ; Position p = model . getPosition ( a ) ; if ( p != null && p . overlapsWith ( offset , length ) ) return a ; } return null ; } private Annotation getNextAnnotation ( final int offset , final int length , boolean forward , Position annotationPosition ) { Annotation nextAnnotation = null ; Position nextAnnotationPosition = null ; Annotation containingAnnotation = null ; Position containingAnnotationPosition = null ; boolean currentAnnotation = false ; IDocument document = getDocumentProvider ( ) . getDocument ( getEditorInput ( ) ) ; int endOfDocument = document . getLength ( ) ; int distance = Integer . MAX_VALUE ; IAnnotationModel model = getDocumentProvider ( ) . getAnnotationModel ( getEditorInput ( ) ) ; Iterator e = new RubyAnnotationIterator ( model , true , true ) ; while ( e . hasNext ( ) ) { Annotation a = ( Annotation ) e . next ( ) ; if ( ( a instanceof IRubyAnnotation ) && ( ( IRubyAnnotation ) a ) . hasOverlay ( ) || ! isNavigationTarget ( a ) ) continue ; Position p = model . getPosition ( a ) ; if ( p == null ) continue ; if ( forward && p . offset == offset || ! forward && p . offset + p . getLength ( ) == offset + length ) { if ( containingAnnotation == null || ( forward && p . length >= containingAnnotationPosition . length || ! forward && p . length >= containingAnnotationPosition . length ) ) { containingAnnotation = a ; containingAnnotationPosition = p ; currentAnnotation = p . length == length ; } } else { int currentDistance = ; if ( forward ) { currentDistance = p . getOffset ( ) - offset ; if ( currentDistance < ) currentDistance = endOfDocument + currentDistance ; if ( currentDistance < distance || currentDistance == distance && p . length < nextAnnotationPosition . length ) { distance = currentDistance ; nextAnnotation = a ; nextAnnotationPosition = p ; } } else { currentDistance = offset + length - ( p . getOffset ( ) + p . length ) ; if ( currentDistance < ) currentDistance = endOfDocument + currentDistance ; if ( currentDistance < distance || currentDistance == distance && p . length < nextAnnotationPosition . length ) { distance = currentDistance ; nextAnnotation = a ; nextAnnotationPosition = p ; } } } } if ( containingAnnotationPosition != null && ( ! currentAnnotation || nextAnnotation == null ) ) { annotationPosition . setOffset ( containingAnnotationPosition . getOffset ( ) ) ; annotationPosition . setLength ( containingAnnotationPosition . getLength ( ) ) ; return containingAnnotation ; } if ( nextAnnotationPosition != null ) { annotationPosition . setOffset ( nextAnnotationPosition . getOffset ( ) ) ; annotationPosition . setLength ( nextAnnotationPosition . getLength ( ) ) ; } return nextAnnotation ; } protected boolean isNavigationTarget ( Annotation annotation ) { Preferences preferences = EditorsUI . getPluginPreferences ( ) ; AnnotationPreference preference = getAnnotationPreferenceLookup ( ) . getAnnotationPreference ( annotation ) ; String key = preference == null ? null : preference . getIsGoToNextNavigationTargetKey ( ) ; return ( key != null && preferences . getBoolean ( key ) ) ; } public Annotation gotoAnnotation ( boolean forward ) { Annotation annotation = null ; ITextSelection selection = ( ITextSelection ) getSelectionProvider ( ) . getSelection ( ) ; Position position = new Position ( , ) ; if ( false ) { getNextAnnotation ( selection . getOffset ( ) , selection . getLength ( ) , forward , position ) ; selectAndReveal ( position . getOffset ( ) , position . getLength ( ) ) ; } else { annotation = getNextAnnotation ( selection . getOffset ( ) , selection . getLength ( ) , forward , position ) ; setStatusLineErrorMessage ( null ) ; setStatusLineMessage ( null ) ; if ( annotation != null ) { updateAnnotationViews ( annotation ) ; selectAndReveal ( position . getOffset ( ) , position . getLength ( ) ) ; setStatusLineMessage ( annotation . getText ( ) ) ; } } return annotation ; } private void updateAnnotationViews ( Annotation annotation ) { IMarker marker = null ; if ( annotation instanceof MarkerAnnotation ) marker = ( ( MarkerAnnotation ) annotation ) . getMarker ( ) ; else if ( annotation instanceof IRubyAnnotation ) { Iterator e = ( ( IRubyAnnotation ) annotation ) . getOverlaidIterator ( ) ; if ( e != null ) { while ( e . hasNext ( ) ) { Object o = e . next ( ) ; if ( o instanceof MarkerAnnotation ) { marker = ( ( MarkerAnnotation ) o ) . getMarker ( ) ; break ; } } } } if ( marker != null && ! marker . equals ( fLastMarkerTarget ) ) { try { boolean isProblem = marker . isSubtypeOf ( IMarker . PROBLEM ) ; IWorkbenchPage page = getSite ( ) . getPage ( ) ; IViewPart view = page . findView ( isProblem ? IPageLayout . ID_PROBLEM_VIEW : IPageLayout . ID_TASK_LIST ) ; if ( view != null ) { Method method = view . getClass ( ) . getMethod ( "" , new Class [ ] { IStructuredSelection . class , boolean . class } ) ; method . invoke ( view , new Object [ ] { new StructuredSelection ( marker ) , Boolean . TRUE } ) ; } } catch ( CoreException x ) { } catch ( NoSuchMethodException x ) { } catch ( IllegalAccessException x ) { } catch ( InvocationTargetException x ) { } } } public void gotoMarker ( IMarker marker ) { fLastMarkerTarget = marker ; if ( ! fIsUpdatingAnnotationViews ) { super . gotoMarker ( marker ) ; } } protected void updateStatusLine ( ) { ITextSelection selection = ( ITextSelection ) getSelectionProvider ( ) . getSelection ( ) ; Annotation annotation = getAnnotation ( selection . getOffset ( ) , selection . getLength ( ) ) ; setStatusLineErrorMessage ( null ) ; setStatusLineMessage ( null ) ; if ( annotation != null ) { try { fIsUpdatingAnnotationViews = true ; updateAnnotationViews ( annotation ) ; } finally { fIsUpdatingAnnotationViews = false ; } if ( annotation instanceof IRubyAnnotation && ( ( IRubyAnnotation ) annotation ) . isProblem ( ) ) setStatusLineMessage ( annotation . getText ( ) ) ; } } protected void setStatusLineErrorMessage ( String msg ) { IEditorStatusLine statusLine = ( IEditorStatusLine ) getAdapter ( IEditorStatusLine . class ) ; if ( statusLine != null ) statusLine . setMessage ( true , msg , null ) ; } protected void setStatusLineMessage ( String msg ) { IEditorStatusLine statusLine = ( IEditorStatusLine ) getAdapter ( IEditorStatusLine . class ) ; if ( statusLine != null ) statusLine . setMessage ( false , msg , null ) ; } boolean isFoldingEnabled ( ) { return RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . EDITOR_FOLDING_ENABLED ) ; } public void dispose ( ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer instanceof ITextViewerExtension ) { ( ( ITextViewerExtension ) sourceViewer ) . removeVerifyKeyListener ( fBracketInserter ) ; } if ( fProjectionModelUpdater != null ) { fProjectionModelUpdater . uninstall ( ) ; fProjectionModelUpdater = null ; } if ( fProjectionSupport != null ) { fProjectionSupport . dispose ( ) ; fProjectionSupport = null ; } if ( fActionGroups != null ) { fActionGroups . dispose ( ) ; fActionGroups = null ; } super . dispose ( ) ; } protected void performRevert ( ) { ProjectionViewer projectionViewer = ( ProjectionViewer ) getSourceViewer ( ) ; projectionViewer . setRedraw ( false ) ; try { boolean projectionMode = projectionViewer . isProjectionMode ( ) ; if ( projectionMode ) { projectionViewer . disableProjection ( ) ; if ( fProjectionModelUpdater != null ) fProjectionModelUpdater . uninstall ( ) ; } super . performRevert ( ) ; if ( projectionMode ) { if ( fProjectionModelUpdater != null ) fProjectionModelUpdater . install ( this , projectionViewer ) ; projectionViewer . enableProjection ( ) ; } } finally { projectionViewer . setRedraw ( true ) ; } } public Object getAdapter ( Class required ) { if ( IEncodingSupport . class . equals ( required ) ) return fEncodingSupport ; if ( required == IShowInTargetList . class ) { return new IShowInTargetList ( ) { public String [ ] getShowInTargetIds ( ) { return new String [ ] { RubyUI . ID_RUBY_EXPLORER , IPageLayout . ID_OUTLINE , IPageLayout . ID_RES_NAV } ; } } ; } if ( required == IShowInSource . class ) { return new IShowInSource ( ) { public ShowInContext getShowInContext ( ) { return new ShowInContext ( getEditorInput ( ) , null ) { public ISelection getSelection ( ) { IRubyElement re = null ; try { re = SelectionConverter . getElementAtOffset ( RubyEditor . this ) ; if ( re == null ) return null ; return new StructuredSelection ( re ) ; } catch ( RubyModelException ex ) { return null ; } } } ; } } ; } if ( required == IRubyFoldingStructureProvider . class ) return fProjectionModelUpdater ; if ( fProjectionSupport != null ) { Object adapter = fProjectionSupport . getAdapter ( getSourceViewer ( ) , required ) ; if ( adapter != null ) return adapter ; } return super . getAdapter ( required ) ; } protected void doSetInput ( IEditorInput input ) throws CoreException { super . doSetInput ( input ) ; configureTabConverter ( ) ; if ( fProjectionModelUpdater != null ) fProjectionModelUpdater . initialize ( ) ; if ( isShowingOverrideIndicators ( ) ) installOverrideIndicator ( false ) ; } protected void editorContextMenuAboutToShow ( IMenuManager menu ) { super . editorContextMenuAboutToShow ( menu ) ; menu . insertAfter ( IContextMenuConstants . GROUP_OPEN , new GroupMarker ( IContextMenuConstants . GROUP_SHOW ) ) ; ActionContext context = new ActionContext ( getSelectionProvider ( ) . getSelection ( ) ) ; fContextMenuGroup . setContext ( context ) ; fContextMenuGroup . fillContextMenu ( menu ) ; fContextMenuGroup . setContext ( null ) ; IAction action = getAction ( IRubyEditorActionDefinitionIds . SHOW_OUTLINE ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_OPEN , action ) ; action = getAction ( IRubyEditorActionDefinitionIds . OPEN_HIERARCHY ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_OPEN , action ) ; addExtensionMenuItems ( menu ) ; } private void addExtensionMenuItems ( IMenuManager menu ) { IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; IExtensionPoint extensionPoint = registry . getExtensionPoint ( "" ) ; IExtension [ ] extensions = extensionPoint . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] elements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < elements . length ; j ++ ) { IConfigurationElement element = elements [ j ] ; SelectionEnabler selectionEnabler = new SelectionEnabler ( element ) ; if ( selectionEnabler . isEnabledForSelection ( this . getSelectionProvider ( ) . getSelection ( ) ) ) { try { Object menuExtender = element . createExecutableExtension ( "" ) ; if ( ! ( menuExtender instanceof ActionGroup ) ) { String message = "" + element . getName ( ) + "" + menuExtender . getClass ( ) . getName ( ) + "" ; RubyPlugin . log ( IStatus . ERROR , message , null ) ; continue ; } ActionGroup menuExtenderActionGroup = ( ActionGroup ) menuExtender ; menuExtenderActionGroup . setContext ( new ActionContext ( this . getSelectionProvider ( ) . getSelection ( ) ) ) ; menuExtenderActionGroup . fillContextMenu ( menu ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } } } } protected void handlePreferenceStoreChanged ( PropertyChangeEvent event ) { super . handlePreferenceStoreChanged ( event ) ; String property = event . getProperty ( ) ; if ( CLOSE_BRACKETS . equals ( property ) ) { fBracketInserter . setCloseBracketsEnabled ( getPreferenceStore ( ) . getBoolean ( property ) ) ; return ; } if ( CLOSE_BRACES . equals ( property ) ) { fBracketInserter . setCloseBracesEnabled ( getPreferenceStore ( ) . getBoolean ( property ) ) ; return ; } if ( CLOSE_STRINGS . equals ( property ) ) { fBracketInserter . setCloseStringsEnabled ( getPreferenceStore ( ) . getBoolean ( property ) ) ; return ; } AdaptedSourceViewer sourceViewer = ( AdaptedSourceViewer ) getSourceViewer ( ) ; if ( sourceViewer == null ) return ; if ( SPACES_FOR_TABS . equals ( property ) ) { if ( isTabConversionEnabled ( ) ) startTabConversion ( ) ; else stopTabConversion ( ) ; return ; } if ( CODE_FORMATTER_TAB_SIZE . equals ( property ) ) { sourceViewer . updateIndentationPrefixes ( ) ; if ( fTabConverter != null ) fTabConverter . setNumberOfSpacesPerTab ( getTabSize ( ) ) ; } if ( PreferenceConstants . EDITOR_FOLDING_PROVIDER . equals ( property ) ) { if ( sourceViewer instanceof ProjectionViewer ) { ProjectionViewer projectionViewer = ( ProjectionViewer ) sourceViewer ; if ( fProjectionModelUpdater != null ) fProjectionModelUpdater . uninstall ( ) ; fProjectionModelUpdater = RubyPlugin . getDefault ( ) . getFoldingStructureProviderRegistry ( ) . getCurrentFoldingProvider ( ) ; if ( fProjectionModelUpdater != null ) { fProjectionModelUpdater . install ( this , projectionViewer ) ; } } return ; } if ( PreferenceConstants . EDITOR_FOLDING_ENABLED . equals ( property ) ) { if ( sourceViewer instanceof ProjectionViewer ) { new ToggleFoldingRunner ( ) . runWhenNextVisible ( ) ; } return ; } } protected ISourceViewer createRubySourceViewer ( Composite parent , IVerticalRuler verticalRuler , IOverviewRuler overviewRuler , boolean isOverviewRulerVisible , int styles , IPreferenceStore store ) { ISourceViewer viewer = new AdaptedSourceViewer ( parent , verticalRuler , overviewRuler , isOverviewRulerVisible , styles , store ) ; RubySourceViewer rubySourceViewer = null ; if ( viewer instanceof RubySourceViewer ) rubySourceViewer = ( RubySourceViewer ) viewer ; ProjectionViewer projectionViewer = ( ProjectionViewer ) viewer ; fProjectionSupport = new ProjectionSupport ( projectionViewer , getAnnotationAccess ( ) , getSharedColors ( ) ) ; fProjectionSupport . addSummarizableAnnotationType ( "" ) ; fProjectionSupport . addSummarizableAnnotationType ( "" ) ; fProjectionSupport . setHoverControlCreator ( new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell shell ) { return new SourceViewerInformationControl ( shell , SWT . TOOL | SWT . NO_TRIM | getOrientation ( ) , SWT . NONE ) ; } } ) ; fProjectionSupport . install ( ) ; fProjectionModelUpdater = RubyPlugin . getDefault ( ) . getFoldingStructureProviderRegistry ( ) . getCurrentFoldingProvider ( ) ; if ( fProjectionModelUpdater != null ) fProjectionModelUpdater . install ( this , projectionViewer ) ; if ( isFoldingEnabled ( ) ) projectionViewer . doOperation ( ProjectionViewer . TOGGLE ) ; return viewer ; } public Object getReconcilerLock ( ) { return fReconcilerLock ; } private static char getEscapeCharacter ( char character ) { switch ( character ) { case '' : case '' : return '' ; default : return ; } } private static char getPeerCharacter ( char character ) { switch ( character ) { case '' : return '' ; case '' : return '' ; case '' : return '' ; case '' : return '' ; case '' : return '' ; case '' : return '' ; case '' : return character ; case '' : return character ; case '' : return character ; default : throw new IllegalArgumentException ( ) ; } } public void setCaretPosition ( CaretPosition pos ) { try { int lineOffset = this . getSourceViewer ( ) . getDocument ( ) . getLineOffset ( pos . line ) ; this . selectAndReveal ( lineOffset + pos . column , ) ; } catch ( BadLocationException e ) { } } public class CaretPosition { public CaretPosition ( int line , int column ) { this . line = line ; this . column = column ; } public CaretPosition ( int line , int column , int offset ) { this ( line , column ) ; this . offset = offset ; } public int getColumn ( ) { return column ; } public int getLine ( ) { return line ; } public int getOffset ( ) { return offset ; } private int line ; private int column ; private int offset ; } private class ExitPolicy implements IExitPolicy { final char fExitCharacter ; final char fEscapeCharacter ; final Stack fStack ; final int fSize ; public ExitPolicy ( char exitCharacter , char escapeCharacter , Stack stack ) { fExitCharacter = exitCharacter ; fEscapeCharacter = escapeCharacter ; fStack = stack ; fSize = fStack . size ( ) ; } public ExitFlags doExit ( LinkedModeModel model , VerifyEvent event , int offset , int length ) { if ( event . character == fExitCharacter ) { if ( fSize == fStack . size ( ) && ! isMasked ( offset ) ) { BracketLevel level = ( BracketLevel ) fStack . peek ( ) ; if ( level . fFirstPosition . offset > offset || level . fSecondPosition . offset < offset ) return null ; if ( level . fSecondPosition . offset == offset && length == ) return new ExitFlags ( ILinkedModeListener . UPDATE_CARET , false ) ; } } return null ; } private boolean isMasked ( int offset ) { IDocument document = getSourceViewer ( ) . getDocument ( ) ; try { return fEscapeCharacter == document . getChar ( offset - ) ; } catch ( BadLocationException e ) { } return false ; } } private static class BracketLevel { int fOffset ; int fLength ; LinkedModeUI fUI ; Position fFirstPosition ; Position fSecondPosition ; } private static class ExclusivePositionUpdater implements IPositionUpdater { private final String fCategory ; public ExclusivePositionUpdater ( String category ) { fCategory = category ; } public void update ( DocumentEvent event ) { int eventOffset = event . getOffset ( ) ; int eventOldLength = event . getLength ( ) ; int eventNewLength = event . getText ( ) == null ? : event . getText ( ) . length ( ) ; int deltaLength = eventNewLength - eventOldLength ; try { Position [ ] positions = event . getDocument ( ) . getPositions ( fCategory ) ; for ( int i = ; i != positions . length ; i ++ ) { Position position = positions [ i ] ; if ( position . isDeleted ( ) ) continue ; int offset = position . getOffset ( ) ; int length = position . getLength ( ) ; int end = offset + length ; if ( offset >= eventOffset + eventOldLength ) position . setOffset ( offset + deltaLength ) ; else if ( end <= eventOffset ) { } else if ( offset <= eventOffset && end >= eventOffset + eventOldLength ) { position . setLength ( length + deltaLength ) ; } else if ( offset < eventOffset ) { int newEnd = eventOffset ; position . setLength ( newEnd - offset ) ; } else if ( end > eventOffset + eventOldLength ) { int newOffset = eventOffset + eventNewLength ; position . setOffset ( newOffset ) ; position . setLength ( end - newOffset ) ; } else { position . delete ( ) ; } } } catch ( BadPositionCategoryException e ) { } } public String getCategory ( ) { return fCategory ; } } private class BracketInserter implements VerifyKeyListener , ILinkedModeListener { private boolean fCloseBrackets = true ; private boolean fCloseStrings = true ; private boolean fCloseBraces = true ; private final String CATEGORY = toString ( ) ; private IPositionUpdater fUpdater = new ExclusivePositionUpdater ( CATEGORY ) ; private Stack fBracketLevelStack = new Stack ( ) ; public void setCloseBracketsEnabled ( boolean enabled ) { fCloseBrackets = enabled ; } public void setCloseStringsEnabled ( boolean enabled ) { fCloseStrings = enabled ; } public void setCloseBracesEnabled ( boolean enabled ) { fCloseBraces = enabled ; } public void verifyKey ( VerifyEvent event ) { if ( ! event . doit ) return ; switch ( event . character ) { case '' : case '' : case '' : case '' : case '' : case '' : break ; default : return ; } final ISourceViewer sourceViewer = getSourceViewer ( ) ; IDocument document = sourceViewer . getDocument ( ) ; final Point selection = sourceViewer . getSelectedRange ( ) ; final int offset = selection . x ; final int length = selection . y ; try { String selected = document . get ( offset , length ) ; if ( selected != null && selected . length ( ) > && ( event . character == '' || event . character == '' ) ) { return ; } IRegion startLine = document . getLineInformationOfOffset ( offset ) ; IRegion endLine = document . getLineInformationOfOffset ( offset + length ) ; RubyHeuristicScanner scanner = new RubyHeuristicScanner ( document ) ; int nextToken = scanner . nextToken ( offset + length , endLine . getOffset ( ) + endLine . getLength ( ) ) ; String next = nextToken == Symbols . TokenEOF ? null : document . get ( offset , scanner . getPosition ( ) - offset ) . trim ( ) ; int prevToken = scanner . previousToken ( offset - , startLine . getOffset ( ) ) ; int prevTokenOffset = scanner . getPosition ( ) + ; String previous = prevToken == Symbols . TokenEOF ? null : document . get ( prevTokenOffset , offset - prevTokenOffset ) . trim ( ) ; switch ( event . character ) { case '' : if ( ! fCloseBrackets || nextToken == Symbols . TokenLPAREN || nextToken == Symbols . TokenIDENT || next != null && next . length ( ) > ) return ; break ; case '' : if ( ! fCloseBraces || nextToken == Symbols . TokenLBRACE || nextToken == Symbols . TokenIDENT || next != null && next . length ( ) > ) return ; break ; case '' : if ( ! fCloseBrackets || nextToken == Symbols . TokenIDENT || next != null && next . length ( ) > ) return ; break ; case '' : case '' : case '' : if ( ! fCloseStrings || nextToken == Symbols . TokenIDENT || next != null && next . length ( ) > ) return ; break ; default : return ; } ITypedRegion partition = TextUtilities . getPartition ( document , IRubyPartitions . RUBY_PARTITIONING , offset - , true ) ; if ( event . character == '' && previous != null && previous . endsWith ( "" ) && partition != null && partition . getType ( ) != null ) { if ( ! IDocument . DEFAULT_CONTENT_TYPE . equals ( partition . getType ( ) ) && ! IRubyPartitions . RUBY_STRING . equals ( partition . getType ( ) ) ) return ; } else { if ( ! IDocument . DEFAULT_CONTENT_TYPE . equals ( partition . getType ( ) ) ) return ; } if ( ! validateEditorInputState ( ) ) return ; final char character = event . character ; final char closingCharacter = getPeerCharacter ( character ) ; final StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( character ) ; buffer . append ( closingCharacter ) ; document . replace ( offset , length , buffer . toString ( ) ) ; BracketLevel level = new BracketLevel ( ) ; fBracketLevelStack . push ( level ) ; LinkedPositionGroup group = new LinkedPositionGroup ( ) ; group . addPosition ( new LinkedPosition ( document , offset + , , LinkedPositionGroup . NO_STOP ) ) ; LinkedModeModel model = new LinkedModeModel ( ) ; model . addLinkingListener ( this ) ; model . addGroup ( group ) ; model . forceInstall ( ) ; level . fOffset = offset ; level . fLength = ; if ( fBracketLevelStack . size ( ) == ) { document . addPositionCategory ( CATEGORY ) ; document . addPositionUpdater ( fUpdater ) ; } level . fFirstPosition = new Position ( offset , ) ; level . fSecondPosition = new Position ( offset + , ) ; document . addPosition ( CATEGORY , level . fFirstPosition ) ; document . addPosition ( CATEGORY , level . fSecondPosition ) ; level . fUI = new EditorLinkedModeUI ( model , sourceViewer ) ; level . fUI . setSimpleMode ( true ) ; level . fUI . setExitPolicy ( new ExitPolicy ( closingCharacter , getEscapeCharacter ( closingCharacter ) , fBracketLevelStack ) ) ; level . fUI . setExitPosition ( sourceViewer , offset + , , Integer . MAX_VALUE ) ; level . fUI . setCyclingMode ( LinkedModeUI . CYCLE_NEVER ) ; level . fUI . enter ( ) ; IRegion newSelection = level . fUI . getSelectedRegion ( ) ; sourceViewer . setSelectedRange ( newSelection . getOffset ( ) , newSelection . getLength ( ) ) ; event . doit = false ; } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; } catch ( BadPositionCategoryException e ) { RubyPlugin . log ( e ) ; } } public void left ( LinkedModeModel environment , int flags ) { final BracketLevel level = ( BracketLevel ) fBracketLevelStack . pop ( ) ; if ( flags != ILinkedModeListener . EXTERNAL_MODIFICATION ) return ; final ISourceViewer sourceViewer = getSourceViewer ( ) ; final IDocument document = sourceViewer . getDocument ( ) ; if ( document instanceof IDocumentExtension ) { IDocumentExtension extension = ( IDocumentExtension ) document ; extension . registerPostNotificationReplace ( null , new IDocumentExtension . IReplace ( ) { public void perform ( IDocument d , IDocumentListener owner ) { if ( ( level . fFirstPosition . isDeleted || level . fFirstPosition . length == ) && ! level . fSecondPosition . isDeleted && level . fSecondPosition . offset == level . fFirstPosition . offset ) { try { document . replace ( level . fSecondPosition . offset , level . fSecondPosition . length , null ) ; } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; } } if ( fBracketLevelStack . size ( ) == ) { document . removePositionUpdater ( fUpdater ) ; try { document . removePositionCategory ( CATEGORY ) ; } catch ( BadPositionCategoryException e ) { RubyPlugin . log ( e ) ; } } } } ) ; } } public void suspend ( LinkedModeModel environment ) { } public void resume ( LinkedModeModel environment , int flags ) { } } public CaretPosition getCaretPosition ( ) { StyledText styledText = this . getSourceViewer ( ) . getTextWidget ( ) ; int caret = widgetOffset2ModelOffset ( getSourceViewer ( ) , styledText . getCaretOffset ( ) ) ; IDocument document = getSourceViewer ( ) . getDocument ( ) ; try { int line = document . getLineOfOffset ( caret ) ; int lineOffset = document . getLineOffset ( line ) ; return new CaretPosition ( line , caret - lineOffset , caret ) ; } catch ( BadLocationException e ) { return new CaretPosition ( , ) ; } } protected IRubyElement getElementAt ( int offset , boolean reconcile ) { IWorkingCopyManager manager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; IRubyScript unit = manager . getWorkingCopy ( getEditorInput ( ) ) ; if ( unit != null ) { try { if ( reconcile ) { RubyModelUtil . reconcile ( unit ) ; return unit . getElementAt ( offset ) ; } else if ( unit . isConsistent ( ) ) return unit . getElementAt ( offset ) ; } catch ( RubyModelException x ) { if ( ! x . isDoesNotExist ( ) ) RubyPlugin . log ( x . getStatus ( ) ) ; } } return null ; } protected IRubyElement getElementAt ( int offset ) { return getElementAt ( offset , true ) ; } public void gotoMatchingBracket ( ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; IDocument document = sourceViewer . getDocument ( ) ; if ( document == null ) return ; IRegion selection = getSignedSelection ( sourceViewer ) ; int selectionLength = Math . abs ( selection . getLength ( ) ) ; if ( selectionLength > ) { setStatusLineErrorMessage ( RubyEditorMessages . GotoMatchingBracket_error_invalidSelection ) ; sourceViewer . getTextWidget ( ) . getDisplay ( ) . beep ( ) ; return ; } int sourceCaretOffset = selection . getOffset ( ) + selection . getLength ( ) ; if ( isSurroundedByBrackets ( document , sourceCaretOffset ) ) sourceCaretOffset -= selection . getLength ( ) ; IRegion region = fBracketMatcher . match ( document , sourceCaretOffset ) ; if ( region == null ) { setStatusLineErrorMessage ( RubyEditorMessages . GotoMatchingBracket_error_noMatchingBracket ) ; sourceViewer . getTextWidget ( ) . getDisplay ( ) . beep ( ) ; return ; } int offset = region . getOffset ( ) ; int length = region . getLength ( ) ; if ( length < ) return ; int anchor = fBracketMatcher . getAnchor ( ) ; int targetOffset = ( ICharacterPairMatcher . RIGHT == anchor ) ? offset + : offset + length ; boolean visible = false ; if ( sourceViewer instanceof ITextViewerExtension5 ) { ITextViewerExtension5 extension = ( ITextViewerExtension5 ) sourceViewer ; visible = ( extension . modelOffset2WidgetOffset ( targetOffset ) > - ) ; } else { IRegion visibleRegion = sourceViewer . getVisibleRegion ( ) ; visible = ( targetOffset >= visibleRegion . getOffset ( ) && targetOffset <= visibleRegion . getOffset ( ) + visibleRegion . getLength ( ) ) ; } if ( ! visible ) { setStatusLineErrorMessage ( RubyEditorMessages . GotoMatchingBracket_error_bracketOutsideSelectedElement ) ; sourceViewer . getTextWidget ( ) . getDisplay ( ) . beep ( ) ; return ; } if ( selection . getLength ( ) < ) targetOffset -= selection . getLength ( ) ; sourceViewer . setSelectedRange ( targetOffset , selection . getLength ( ) ) ; sourceViewer . revealRange ( targetOffset , selection . getLength ( ) ) ; } protected IRegion getSignedSelection ( ISourceViewer sourceViewer ) { StyledText text = sourceViewer . getTextWidget ( ) ; Point selection = text . getSelectionRange ( ) ; if ( text . getCaretOffset ( ) == selection . x ) { selection . x = selection . x + selection . y ; selection . y = - selection . y ; } selection . x = widgetOffset2ModelOffset ( sourceViewer , selection . x ) ; return new Region ( selection . x , selection . y ) ; } private static boolean isSurroundedByBrackets ( IDocument document , int offset ) { if ( offset == || offset == document . getLength ( ) ) return false ; try { return isBracket ( document . getChar ( offset - ) ) && isBracket ( document . getChar ( offset ) ) ; } catch ( BadLocationException e ) { return false ; } } private static boolean isBracket ( char character ) { for ( int i = ; i != BRACKETS . length ; ++ i ) if ( character == BRACKETS [ i ] ) return true ; return false ; } private final class ToggleFoldingRunner implements IPartListener2 { private IWorkbenchPage fPage ; private void toggleFolding ( ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer instanceof ProjectionViewer ) { ProjectionViewer pv = ( ProjectionViewer ) sourceViewer ; if ( pv . isProjectionMode ( ) != isFoldingEnabled ( ) ) { if ( pv . canDoOperation ( ProjectionViewer . TOGGLE ) ) pv . doOperation ( ProjectionViewer . TOGGLE ) ; } } } public void runWhenNextVisible ( ) { if ( fFoldingRunner != null ) { fFoldingRunner . cancel ( ) ; return ; } IWorkbenchPartSite site = getSite ( ) ; if ( site != null ) { IWorkbenchPage page = site . getPage ( ) ; if ( ! page . isPartVisible ( RubyEditor . this ) ) { fPage = page ; fFoldingRunner = this ; page . addPartListener ( this ) ; return ; } } toggleFolding ( ) ; } private void cancel ( ) { if ( fPage != null ) { fPage . removePartListener ( this ) ; fPage = null ; } if ( fFoldingRunner == this ) fFoldingRunner = null ; } public void partVisible ( IWorkbenchPartReference partRef ) { if ( RubyEditor . this . equals ( partRef . getPart ( false ) ) ) { cancel ( ) ; toggleFolding ( ) ; } } public void partClosed ( IWorkbenchPartReference partRef ) { if ( RubyEditor . this . equals ( partRef . getPart ( false ) ) ) { cancel ( ) ; } } public void partActivated ( IWorkbenchPartReference partRef ) { } public void partBroughtToTop ( IWorkbenchPartReference partRef ) { } public void partDeactivated ( IWorkbenchPartReference partRef ) { } public void partOpened ( IWorkbenchPartReference partRef ) { } public void partHidden ( IWorkbenchPartReference partRef ) { } public void partInputChanged ( IWorkbenchPartReference partRef ) { } } interface ITextConverter { void customizeDocumentCommand ( IDocument document , DocumentCommand command ) ; } public static class TabConverter implements ITextConverter { private int fTabRatio ; private ILineTracker fLineTracker ; public TabConverter ( ) { } public void setNumberOfSpacesPerTab ( int ratio ) { fTabRatio = ratio ; } public void setLineTracker ( ILineTracker lineTracker ) { fLineTracker = lineTracker ; } private int insertTabString ( StringBuffer buffer , int offsetInLine ) { if ( fTabRatio == ) return ; int remainder = offsetInLine % fTabRatio ; remainder = fTabRatio - remainder ; for ( int i = ; i < remainder ; i ++ ) buffer . append ( '' ) ; return remainder ; } public void customizeDocumentCommand ( IDocument document , DocumentCommand command ) { String text = command . text ; if ( text == null ) return ; int index = text . indexOf ( '' ) ; if ( index > - ) { StringBuffer buffer = new StringBuffer ( ) ; fLineTracker . set ( command . text ) ; int lines = fLineTracker . getNumberOfLines ( ) ; try { for ( int i = ; i < lines ; i ++ ) { int offset = fLineTracker . getLineOffset ( i ) ; int endOffset = offset + fLineTracker . getLineLength ( i ) ; String line = text . substring ( offset , endOffset ) ; int position = ; if ( i == ) { IRegion firstLine = document . getLineInformationOfOffset ( command . offset ) ; position = command . offset - firstLine . getOffset ( ) ; } int length = line . length ( ) ; for ( int j = ; j < length ; j ++ ) { char c = line . charAt ( j ) ; if ( c == '' ) { position += insertTabString ( buffer , position ) ; } else { buffer . append ( c ) ; ++ position ; } } } command . text = buffer . toString ( ) ; } catch ( BadLocationException x ) { } } } } public void collapseMembers ( ) { if ( fProjectionModelUpdater instanceof IRubyFoldingStructureProviderExtension ) { IRubyFoldingStructureProviderExtension extension = ( IRubyFoldingStructureProviderExtension ) fProjectionModelUpdater ; extension . collapseMembers ( ) ; } } public void collapseComments ( ) { if ( fProjectionModelUpdater instanceof IRubyFoldingStructureProviderExtension ) { IRubyFoldingStructureProviderExtension extension = ( IRubyFoldingStructureProviderExtension ) fProjectionModelUpdater ; extension . collapseComments ( ) ; } } public FoldingActionGroup getFoldingActionGroup ( ) { return fFoldingGroup ; } private int getTabSize ( ) { IRubyElement element = getInputRubyElement ( ) ; IRubyProject project = element == null ? null : element . getRubyProject ( ) ; return CodeFormatterUtil . getTabWidth ( project ) ; } private void startTabConversion ( ) { if ( fTabConverter == null ) { fTabConverter = new TabConverter ( ) ; configureTabConverter ( ) ; fTabConverter . setNumberOfSpacesPerTab ( getTabSize ( ) ) ; AdaptedSourceViewer asv = ( AdaptedSourceViewer ) getSourceViewer ( ) ; asv . addTextConverter ( fTabConverter ) ; asv . updateIndentationPrefixes ( ) ; } } private void startStringSubstitutionConverter ( ) { if ( fStringConverter == null ) { fStringConverter = new StringSubstitutionConverter ( this ) ; IDocumentProvider provider = getDocumentProvider ( ) ; if ( provider instanceof IRubyScriptDocumentProvider ) { IRubyScriptDocumentProvider cup = ( IRubyScriptDocumentProvider ) provider ; fStringConverter . setLineTracker ( cup . createLineTracker ( getEditorInput ( ) ) ) ; } AdaptedSourceViewer asv = ( AdaptedSourceViewer ) getSourceViewer ( ) ; asv . addTextConverter ( fStringConverter ) ; } } private void configureTabConverter ( ) { if ( fTabConverter != null ) { IDocumentProvider provider = getDocumentProvider ( ) ; if ( provider instanceof IRubyScriptDocumentProvider ) { IRubyScriptDocumentProvider cup = ( IRubyScriptDocumentProvider ) provider ; fTabConverter . setLineTracker ( cup . createLineTracker ( getEditorInput ( ) ) ) ; } } } private void stopTabConversion ( ) { if ( fTabConverter != null ) { AdaptedSourceViewer asv = ( AdaptedSourceViewer ) getSourceViewer ( ) ; asv . removeTextConverter ( fTabConverter ) ; asv . updateIndentationPrefixes ( ) ; fTabConverter = null ; } } private boolean isTabConversionEnabled ( ) { IRubyElement element = getInputRubyElement ( ) ; IRubyProject project = element == null ? null : element . getRubyProject ( ) ; String option ; if ( project == null ) option = RubyCore . getOption ( SPACES_FOR_TABS ) ; else option = project . getOption ( SPACES_FOR_TABS , true ) ; return RubyCore . SPACE . equals ( option ) ; } protected boolean isShowingOverrideIndicators ( ) { AnnotationPreference preference = getAnnotationPreferenceLookup ( ) . getAnnotationPreference ( OverrideIndicatorManager . ANNOTATION_TYPE ) ; IPreferenceStore store = getPreferenceStore ( ) ; return getBoolean ( store , preference . getHighlightPreferenceKey ( ) ) || getBoolean ( store , preference . getVerticalRulerPreferenceKey ( ) ) || getBoolean ( store , preference . getOverviewRulerPreferenceKey ( ) ) || getBoolean ( store , preference . getTextPreferenceKey ( ) ) ; } private boolean getBoolean ( IPreferenceStore store , String key ) { return key != null && store . getBoolean ( key ) ; } protected void installOverrideIndicator ( boolean provideAST ) { uninstallOverrideIndicator ( ) ; IAnnotationModel model = getDocumentProvider ( ) . getAnnotationModel ( getEditorInput ( ) ) ; final IRubyElement inputElement = getInputRubyElement ( ) ; if ( model == null || inputElement == null ) return ; fOverrideIndicatorManager = new OverrideIndicatorManager ( model , inputElement , null ) ; if ( provideAST ) { Job job = new Job ( "" ) { protected IStatus run ( IProgressMonitor monitor ) { if ( fOverrideIndicatorManager != null ) fOverrideIndicatorManager . reconciled ( ( IRubyScript ) inputElement , null , true , monitor ) ; return Status . OK_STATUS ; } } ; job . setPriority ( Job . DECORATE ) ; job . setSystem ( true ) ; job . schedule ( ) ; } if ( fOverrideIndicatorManager == null ) return ; addReconcileListener ( fOverrideIndicatorManager ) ; } final void addReconcileListener ( IRubyReconcilingListener listener ) { synchronized ( fReconcilingListeners ) { fReconcilingListeners . add ( listener ) ; } } protected void uninstallOverrideIndicator ( ) { if ( fOverrideIndicatorManager != null ) { fOverrideIndicatorManager . removeAnnotations ( ) ; fOverrideIndicatorManager = null ; } } protected boolean affectsOverrideIndicatorAnnotations ( PropertyChangeEvent event ) { String key = event . getProperty ( ) ; AnnotationPreference preference = getAnnotationPreferenceLookup ( ) . getAnnotationPreference ( OverrideIndicatorManager . ANNOTATION_TYPE ) ; if ( key == null || preference == null ) return false ; return key . equals ( preference . getHighlightPreferenceKey ( ) ) || key . equals ( preference . getVerticalRulerPreferenceKey ( ) ) || key . equals ( preference . getOverviewRulerPreferenceKey ( ) ) || key . equals ( preference . getTextPreferenceKey ( ) ) ; } public void aboutToBeReconciled ( ) { RubyPlugin . getDefault ( ) . getASTProvider ( ) . aboutToBeReconciled ( getInputRubyElement ( ) ) ; Object [ ] listeners = fReconcilingListeners . getListeners ( ) ; for ( int i = , length = listeners . length ; i < length ; ++ i ) ( ( IRubyReconcilingListener ) listeners [ i ] ) . aboutToBeReconciled ( ) ; } public void reconciled ( IRubyScript script , RootNode ast , boolean forced , IProgressMonitor progressMonitor ) { RubyPlugin javaPlugin = RubyPlugin . getDefault ( ) ; if ( javaPlugin == null ) return ; javaPlugin . getASTProvider ( ) . reconciled ( ast , getInputRubyElement ( ) , progressMonitor ) ; Object [ ] listeners = fReconcilingListeners . getListeners ( ) ; for ( int i = , length = listeners . length ; i < length ; ++ i ) ( ( IRubyReconcilingListener ) listeners [ i ] ) . reconciled ( script , ast , forced , progressMonitor ) ; if ( ! forced && ! progressMonitor . isCanceled ( ) ) { Shell shell = getSite ( ) . getShell ( ) ; if ( shell != null && ! shell . isDisposed ( ) ) { shell . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { selectionChanged ( ) ; } } ) ; } } } protected void selectionChanged ( ) { if ( getSelectionProvider ( ) == null ) return ; } class InformationDispatchAction extends TextEditorAction { private final TextOperationAction fTextOperationAction ; public InformationDispatchAction ( ResourceBundle resourceBundle , String prefix , final TextOperationAction textOperationAction ) { super ( resourceBundle , prefix , RubyEditor . this ) ; if ( textOperationAction == null ) throw new IllegalArgumentException ( ) ; fTextOperationAction = textOperationAction ; } public void run ( ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer == null ) { fTextOperationAction . run ( ) ; return ; } if ( sourceViewer instanceof ITextViewerExtension4 ) { ITextViewerExtension4 extension4 = ( ITextViewerExtension4 ) sourceViewer ; if ( extension4 . moveFocusToWidgetToken ( ) ) return ; } if ( sourceViewer instanceof ITextViewerExtension2 ) { ITextHover textHover = ( ( ITextViewerExtension2 ) sourceViewer ) . getCurrentTextHover ( ) ; if ( textHover != null && makeTextHoverFocusable ( sourceViewer , textHover ) ) return ; } if ( sourceViewer instanceof ISourceViewerExtension3 ) { IAnnotationHover annotationHover = ( ( ISourceViewerExtension3 ) sourceViewer ) . getCurrentAnnotationHover ( ) ; if ( annotationHover != null && makeAnnotationHoverFocusable ( sourceViewer , annotationHover ) ) return ; } fTextOperationAction . run ( ) ; } private boolean makeTextHoverFocusable ( ISourceViewer sourceViewer , ITextHover textHover ) { Point hoverEventLocation = ( ( ITextViewerExtension2 ) sourceViewer ) . getHoverEventLocation ( ) ; int offset = computeOffsetAtLocation ( sourceViewer , hoverEventLocation . x , hoverEventLocation . y ) ; if ( offset == - ) return false ; try { IRegion hoverRegion = textHover . getHoverRegion ( sourceViewer , offset ) ; if ( hoverRegion == null ) return false ; String hoverInfo = textHover . getHoverInfo ( sourceViewer , hoverRegion ) ; IInformationControlCreator controlCreator = null ; if ( textHover instanceof IInformationProviderExtension2 ) controlCreator = ( ( IInformationProviderExtension2 ) textHover ) . getInformationPresenterControlCreator ( ) ; IInformationProvider informationProvider = new InformationProvider ( hoverRegion , hoverInfo , controlCreator ) ; fInformationPresenter . setOffset ( offset ) ; fInformationPresenter . setAnchor ( AbstractInformationControlManager . ANCHOR_BOTTOM ) ; fInformationPresenter . setMargins ( , ) ; String contentType = TextUtilities . getContentType ( sourceViewer . getDocument ( ) , IRubyPartitions . RUBY_PARTITIONING , offset , true ) ; fInformationPresenter . setInformationProvider ( informationProvider , contentType ) ; fInformationPresenter . showInformation ( ) ; return true ; } catch ( BadLocationException e ) { return false ; } } private boolean makeAnnotationHoverFocusable ( ISourceViewer sourceViewer , IAnnotationHover annotationHover ) { IVerticalRulerInfo info = getVerticalRuler ( ) ; int line = info . getLineOfLastMouseButtonActivity ( ) ; if ( line == - ) return false ; try { Object hoverInfo ; if ( annotationHover instanceof IAnnotationHoverExtension ) { IAnnotationHoverExtension extension = ( IAnnotationHoverExtension ) annotationHover ; ILineRange hoverLineRange = extension . getHoverLineRange ( sourceViewer , line ) ; if ( hoverLineRange == null ) return false ; final int maxVisibleLines = Integer . MAX_VALUE ; hoverInfo = extension . getHoverInfo ( sourceViewer , hoverLineRange , maxVisibleLines ) ; } else { hoverInfo = annotationHover . getHoverInfo ( sourceViewer , line ) ; } IDocument document = sourceViewer . getDocument ( ) ; int offset = document . getLineOffset ( line ) ; String contentType = TextUtilities . getContentType ( document , IRubyPartitions . RUBY_PARTITIONING , offset , true ) ; IInformationControlCreator controlCreator = null ; if ( "" . equals ( annotationHover . getClass ( ) . getName ( ) ) ) { controlCreator = new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell shell ) { int shellStyle = SWT . RESIZE | SWT . TOOL | getOrientation ( ) ; int style = SWT . V_SCROLL | SWT . H_SCROLL ; return new SourceViewerInformationControl ( shell , shellStyle , style ) ; } } ; } else { if ( annotationHover instanceof IInformationProviderExtension2 ) controlCreator = ( ( IInformationProviderExtension2 ) annotationHover ) . getInformationPresenterControlCreator ( ) ; else if ( annotationHover instanceof IAnnotationHoverExtension ) controlCreator = ( ( IAnnotationHoverExtension ) annotationHover ) . getHoverControlCreator ( ) ; } IInformationProvider informationProvider = new InformationProvider ( new Region ( offset , ) , hoverInfo , controlCreator ) ; fInformationPresenter . setOffset ( offset ) ; fInformationPresenter . setAnchor ( AbstractInformationControlManager . ANCHOR_RIGHT ) ; fInformationPresenter . setMargins ( , ) ; fInformationPresenter . setInformationProvider ( informationProvider , contentType ) ; fInformationPresenter . showInformation ( ) ; return true ; } catch ( BadLocationException e ) { return false ; } } private int computeOffsetAtLocation ( ITextViewer textViewer , int x , int y ) { StyledText styledText = textViewer . getTextWidget ( ) ; IDocument document = textViewer . getDocument ( ) ; if ( document == null ) return - ; try { int widgetOffset = styledText . getOffsetAtLocation ( new Point ( x , y ) ) ; Point p = styledText . getLocationAtOffset ( widgetOffset ) ; if ( p . x > x ) widgetOffset -- ; if ( textViewer instanceof ITextViewerExtension5 ) { ITextViewerExtension5 extension = ( ITextViewerExtension5 ) textViewer ; return extension . widgetOffset2ModelOffset ( widgetOffset ) ; } else { IRegion visibleRegion = textViewer . getVisibleRegion ( ) ; return widgetOffset + visibleRegion . getOffset ( ) ; } } catch ( IllegalArgumentException e ) { return - ; } } } private static final class InformationProvider implements IInformationProvider , IInformationProviderExtension , IInformationProviderExtension2 { private IRegion fHoverRegion ; private Object fHoverInfo ; private IInformationControlCreator fControlCreator ; InformationProvider ( IRegion hoverRegion , Object hoverInfo , IInformationControlCreator controlCreator ) { fHoverRegion = hoverRegion ; fHoverInfo = hoverInfo ; fControlCreator = controlCreator ; } public IRegion getSubject ( ITextViewer textViewer , int invocationOffset ) { return fHoverRegion ; } public String getInformation ( ITextViewer textViewer , IRegion subject ) { return fHoverInfo . toString ( ) ; } public Object getInformation2 ( ITextViewer textViewer , IRegion subject ) { return fHoverInfo ; } public IInformationControlCreator getInformationPresenterControlCreator ( ) { return fControlCreator ; } } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . Iterator ; import org . rubypeople . rdt . core . IRubyScript ; public interface IRubyAnnotation { String getType ( ) ; boolean isPersistent ( ) ; boolean isMarkedDeleted ( ) ; String getText ( ) ; boolean hasOverlay ( ) ; IRubyAnnotation getOverlay ( ) ; Iterator getOverlaidIterator ( ) ; void addOverlaid ( IRubyAnnotation annotation ) ; void removeOverlaid ( IRubyAnnotation annotation ) ; boolean isProblem ( ) ; IRubyScript getRubyScript ( ) ; int getId ( ) ; String getMarkerType ( ) ; String [ ] getArguments ( ) ; } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . io . BufferedReader ; import java . io . FileReader ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . ui . internal . editors . text . WorkspaceOperationRunner ; import org . eclipse . ui . texteditor . AbstractDocumentProvider ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class ExternalRubyDocumentProvider extends AbstractDocumentProvider { private WorkspaceOperationRunner fOperationRunner ; public ExternalRubyDocumentProvider ( ) { super ( ) ; } protected IDocument createDocument ( Object element ) throws CoreException { if ( ! ( element instanceof ExternalRubyFileEditorInput ) ) { return null ; } ExternalRubyFileEditorInput editorInput = ( ExternalRubyFileEditorInput ) element ; StringBuffer fileContent = new StringBuffer ( ) ; try { BufferedReader fr = new BufferedReader ( new FileReader ( editorInput . getFilesystemFile ( ) ) ) ; while ( fr . ready ( ) ) { fileContent . append ( fr . readLine ( ) ) ; fileContent . append ( "" ) ; } } catch ( Exception e ) { String message = RubyUIMessages . getFormattedString ( "" , editorInput . getFilesystemFile ( ) . getAbsolutePath ( ) ) ; RubyPlugin . log ( IStatus . ERROR , message , e ) ; } Document document = new Document ( ) ; document . set ( fileContent . toString ( ) ) ; if ( document != null ) { RubyTextTools tools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; tools . setupRubyDocumentPartitioner ( document , IRubyPartitions . RUBY_PARTITIONING ) ; } return document ; } protected IAnnotationModel createAnnotationModel ( Object element ) throws CoreException { return new ExternalFileRubyAnnotationModel ( null ) ; } protected void doSaveDocument ( IProgressMonitor monitor , Object element , IDocument document , boolean overwrite ) throws CoreException { } protected IRunnableContext getOperationRunner ( IProgressMonitor monitor ) { if ( fOperationRunner == null ) fOperationRunner = new WorkspaceOperationRunner ( ) ; fOperationRunner . setProgressMonitor ( monitor ) ; return fOperationRunner ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ILineTracker ; import org . eclipse . jface . text . source . IAnnotationModelListener ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . IDocumentProviderExtension2 ; import org . eclipse . ui . texteditor . IDocumentProviderExtension3 ; import org . rubypeople . rdt . core . IRubyScript ; public interface IRubyScriptDocumentProvider extends IDocumentProvider , IDocumentProviderExtension2 , IDocumentProviderExtension3 { void shutdown ( ) ; IRubyScript getWorkingCopy ( Object element ) ; void saveDocumentContent ( IProgressMonitor monitor , Object element , IDocument document , boolean overwrite ) throws CoreException ; ILineTracker createLineTracker ( Object element ) ; void setSavePolicy ( ISavePolicy savePolicy ) ; void addGlobalAnnotationModelListener ( IAnnotationModelListener listener ) ; void removeGlobalAnnotationModelListener ( IAnnotationModelListener listener ) ; } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . rubypeople . rdt . core . IRubyElement ; public class ExternalRubyEditor extends RubyAbstractEditor { public ExternalRubyEditor ( ) { super ( ) ; } public boolean isEditable ( ) { return false ; } protected IRubyElement getElementAt ( int caret , boolean b ) { return null ; } protected IRubyElement getElementAt ( int offset ) { return null ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultLineTracker ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ILineTracker ; import org . eclipse . jface . text . ISynchronizable ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . AnnotationModelEvent ; import org . eclipse . jface . text . source . IAnnotationAccessExtension ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . IAnnotationModelListener ; import org . eclipse . jface . text . source . IAnnotationModelListenerExtension ; import org . eclipse . jface . text . source . IAnnotationPresentation ; import org . eclipse . jface . text . source . ImageUtilities ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . ListenerList ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Canvas ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . editors . text . TextFileDocumentProvider ; import org . eclipse . ui . texteditor . AbstractMarkerAnnotationModel ; import org . eclipse . ui . texteditor . AnnotationPreference ; import org . eclipse . ui . texteditor . AnnotationPreferenceLookup ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . MarkerAnnotation ; import org . eclipse . ui . texteditor . MarkerUtilities ; import org . eclipse . ui . texteditor . ResourceMarkerAnnotationModel ; import org . rubypeople . rdt . core . IProblemRequestor ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . text . ruby . IProblemRequestorExtension ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyDocumentProvider extends TextFileDocumentProvider implements IRubyScriptDocumentProvider { static protected class RubyScriptInfo extends FileInfo { public IRubyScript fCopy ; } protected static class GlobalAnnotationModelListener implements IAnnotationModelListener , IAnnotationModelListenerExtension { private ListenerList fListenerList ; public GlobalAnnotationModelListener ( ) { fListenerList = new ListenerList ( ) ; } public void modelChanged ( IAnnotationModel model ) { Object [ ] listeners = fListenerList . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { ( ( IAnnotationModelListener ) listeners [ i ] ) . modelChanged ( model ) ; } } public void modelChanged ( AnnotationModelEvent event ) { Object [ ] listeners = fListenerList . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { Object curr = listeners [ i ] ; if ( curr instanceof IAnnotationModelListenerExtension ) { ( ( IAnnotationModelListenerExtension ) curr ) . modelChanged ( event ) ; } } } public void addListener ( IAnnotationModelListener listener ) { fListenerList . add ( listener ) ; } public void removeListener ( IAnnotationModelListener listener ) { fListenerList . remove ( listener ) ; } } private final static String HANDLE_TEMPORARY_PROBLEMS = PreferenceConstants . EDITOR_EVALUTE_TEMPORARY_PROBLEMS ; private boolean fIsAboutToSave = false ; private ISavePolicy fSavePolicy ; private IPropertyChangeListener fPropertyListener ; private GlobalAnnotationModelListener fGlobalAnnotationModelListener ; public RubyDocumentProvider ( ) { IDocumentProvider provider = new TextFileDocumentProvider ( ) ; setParentDocumentProvider ( provider ) ; fGlobalAnnotationModelListener = new GlobalAnnotationModelListener ( ) ; fPropertyListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { if ( HANDLE_TEMPORARY_PROBLEMS . equals ( event . getProperty ( ) ) ) enableHandlingTemporaryProblems ( ) ; } } ; RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . addPropertyChangeListener ( fPropertyListener ) ; } protected IAnnotationModel createAnnotationModel ( IFile file ) { return new RubyScriptAnnotationModel ( file ) ; } protected IRubyScript createRubyScript ( IFile file ) { Object element = RubyCore . create ( file ) ; if ( element instanceof IRubyScript ) return ( IRubyScript ) element ; return null ; } protected FileInfo createEmptyFileInfo ( ) { return new RubyScriptInfo ( ) ; } protected void enableHandlingTemporaryProblems ( ) { boolean enable = isHandlingTemporaryProblems ( ) ; for ( Iterator iter = getFileInfosIterator ( ) ; iter . hasNext ( ) ; ) { FileInfo info = ( FileInfo ) iter . next ( ) ; if ( info . fModel instanceof IProblemRequestorExtension ) { IProblemRequestorExtension extension = ( IProblemRequestorExtension ) info . fModel ; extension . setIsHandlingTemporaryProblems ( enable ) ; } } } public void addGlobalAnnotationModelListener ( IAnnotationModelListener listener ) { fGlobalAnnotationModelListener . addListener ( listener ) ; } public void removeGlobalAnnotationModelListener ( IAnnotationModelListener listener ) { fGlobalAnnotationModelListener . removeListener ( listener ) ; } protected FileInfo createFileInfo ( Object element ) throws CoreException { if ( ! ( element instanceof IFileEditorInput ) ) return null ; IFileEditorInput input = ( IFileEditorInput ) element ; IRubyScript original = createRubyScript ( input . getFile ( ) ) ; if ( original == null ) return null ; FileInfo info = super . createFileInfo ( element ) ; if ( ! ( info instanceof RubyScriptInfo ) ) return null ; RubyScriptInfo cuInfo = ( RubyScriptInfo ) info ; setUpSynchronization ( cuInfo ) ; IProblemRequestor requestor = cuInfo . fModel instanceof IProblemRequestor ? ( IProblemRequestor ) cuInfo . fModel : null ; if ( requestor instanceof IProblemRequestorExtension ) { IProblemRequestorExtension extension = ( IProblemRequestorExtension ) requestor ; extension . setIsActive ( false ) ; extension . setIsHandlingTemporaryProblems ( isHandlingTemporaryProblems ( ) ) ; } IProject iProject = input . getFile ( ) . getProject ( ) ; if ( ! RubyProject . hasRubyNature ( iProject ) ) { RubyCore . addRubyNature ( iProject , null ) ; } original . becomeWorkingCopy ( requestor , getProgressMonitor ( ) ) ; cuInfo . fCopy = original ; if ( cuInfo . fModel instanceof RubyScriptAnnotationModel ) { RubyScriptAnnotationModel model = ( RubyScriptAnnotationModel ) cuInfo . fModel ; model . setRubyScript ( cuInfo . fCopy ) ; } if ( cuInfo . fModel != null ) cuInfo . fModel . addAnnotationModelListener ( fGlobalAnnotationModelListener ) ; return cuInfo ; } protected boolean isHandlingTemporaryProblems ( ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; return store . getBoolean ( HANDLE_TEMPORARY_PROBLEMS ) ; } public void saveDocumentContent ( IProgressMonitor monitor , Object element , IDocument document , boolean overwrite ) throws CoreException { if ( ! fIsAboutToSave ) return ; super . saveDocument ( monitor , element , document , overwrite ) ; } private void setUpSynchronization ( RubyScriptInfo cuInfo ) { IDocument document = cuInfo . fTextFileBuffer . getDocument ( ) ; IAnnotationModel model = cuInfo . fModel ; if ( document instanceof ISynchronizable && model instanceof ISynchronizable ) { Object lock = ( ( ISynchronizable ) document ) . getLockObject ( ) ; ( ( ISynchronizable ) model ) . setLockObject ( lock ) ; } } protected void disposeFileInfo ( Object element , FileInfo info ) { if ( info instanceof RubyScriptInfo ) { RubyScriptInfo cuInfo = ( RubyScriptInfo ) info ; try { cuInfo . fCopy . discardWorkingCopy ( ) ; } catch ( RubyModelException x ) { handleCoreException ( x , x . getMessage ( ) ) ; } if ( cuInfo . fModel != null ) cuInfo . fModel . removeAnnotationModelListener ( fGlobalAnnotationModelListener ) ; } super . disposeFileInfo ( element , info ) ; } protected DocumentProviderOperation createSaveOperation ( final Object element , final IDocument document , final boolean overwrite ) throws CoreException { final FileInfo info = getFileInfo ( element ) ; if ( info instanceof RubyScriptInfo ) { return new DocumentProviderOperation ( ) { protected void execute ( IProgressMonitor monitor ) throws CoreException { commitWorkingCopy ( monitor , element , ( RubyScriptInfo ) info , overwrite ) ; } public ISchedulingRule getSchedulingRule ( ) { if ( info . fElement instanceof IFileEditorInput ) { IFile file = ( ( IFileEditorInput ) info . fElement ) . getFile ( ) ; return computeSchedulingRule ( file ) ; } return null ; } } ; } return null ; } protected void commitWorkingCopy ( IProgressMonitor monitor , Object element , RubyScriptInfo info , boolean overwrite ) throws CoreException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; try { IProgressMonitor subMonitor = getSubProgressMonitor ( monitor , ) ; try { synchronized ( info . fCopy ) { info . fCopy . reconcile ( false , null , subMonitor ) ; } } catch ( RubyModelException ex ) { } finally { subMonitor . done ( ) ; } IDocument document = info . fTextFileBuffer . getDocument ( ) ; IResource resource = info . fCopy . getResource ( ) ; Assert . isTrue ( resource instanceof IFile ) ; if ( ! resource . exists ( ) ) { subMonitor = getSubProgressMonitor ( monitor , ) ; try { createFileFromDocument ( subMonitor , ( IFile ) resource , document ) ; } finally { subMonitor . done ( ) ; } return ; } if ( fSavePolicy != null ) fSavePolicy . preSave ( info . fCopy ) ; try { subMonitor = getSubProgressMonitor ( monitor , ) ; fIsAboutToSave = true ; info . fCopy . commitWorkingCopy ( overwrite , subMonitor ) ; } catch ( CoreException x ) { fireElementStateChangeFailed ( element ) ; throw x ; } catch ( RuntimeException x ) { fireElementStateChangeFailed ( element ) ; throw x ; } finally { fIsAboutToSave = false ; subMonitor . done ( ) ; } if ( info . fModel instanceof AbstractMarkerAnnotationModel ) { AbstractMarkerAnnotationModel model = ( AbstractMarkerAnnotationModel ) info . fModel ; model . updateMarkers ( document ) ; } if ( fSavePolicy != null ) { IRubyScript unit = fSavePolicy . postSave ( info . fCopy ) ; if ( unit != null && info . fModel instanceof AbstractMarkerAnnotationModel ) { IResource r = unit . getResource ( ) ; IMarker [ ] markers = r . findMarkers ( IMarker . MARKER , true , IResource . DEPTH_ZERO ) ; if ( markers != null && markers . length > ) { AbstractMarkerAnnotationModel model = ( AbstractMarkerAnnotationModel ) info . fModel ; for ( int i = ; i < markers . length ; i ++ ) model . updateMarker ( document , markers [ i ] , null ) ; } } } } finally { monitor . done ( ) ; } } private IProgressMonitor getSubProgressMonitor ( IProgressMonitor monitor , int ticks ) { if ( monitor != null ) return new SubProgressMonitor ( monitor , ticks , SubProgressMonitor . PREPEND_MAIN_LABEL_TO_SUBTASK ) ; return new NullProgressMonitor ( ) ; } public IRubyScript getWorkingCopy ( Object element ) { FileInfo fileInfo = getFileInfo ( element ) ; if ( fileInfo instanceof RubyScriptInfo ) { RubyScriptInfo info = ( RubyScriptInfo ) fileInfo ; return info . fCopy ; } return null ; } public void shutdown ( ) { Iterator e = getConnectedElementsIterator ( ) ; while ( e . hasNext ( ) ) disconnect ( e . next ( ) ) ; } static public class ProblemAnnotation extends Annotation implements IRubyAnnotation , IAnnotationPresentation { public static final String SPELLING_ANNOTATION_TYPE = "" ; private static final int TASK_LAYER ; private static final int INFO_LAYER ; private static final int WARNING_LAYER ; private static final int ERROR_LAYER ; static { AnnotationPreferenceLookup lookup = EditorsUI . getAnnotationPreferenceLookup ( ) ; TASK_LAYER = computeLayer ( "" , lookup ) ; INFO_LAYER = computeLayer ( "" , lookup ) ; WARNING_LAYER = computeLayer ( "" , lookup ) ; ERROR_LAYER = computeLayer ( "" , lookup ) ; } private static int computeLayer ( String annotationType , AnnotationPreferenceLookup lookup ) { Annotation annotation = new Annotation ( annotationType , false , null ) ; AnnotationPreference preference = lookup . getAnnotationPreference ( annotation ) ; if ( preference != null ) return preference . getPresentationLayer ( ) + ; return IAnnotationAccessExtension . DEFAULT_LAYER + ; } private static Image fgQuickFixImage ; private static Image fgQuickFixErrorImage ; private static boolean fgQuickFixImagesInitialized = false ; private IRubyScript fRubyScript ; private List fOverlaids ; private IProblem fProblem ; private Image fImage ; private boolean fQuickFixImagesInitialized = false ; private int fLayer = IAnnotationAccessExtension . DEFAULT_LAYER ; public ProblemAnnotation ( IProblem problem , IRubyScript cu ) { fProblem = problem ; fRubyScript = cu ; if ( fProblem . isTask ( ) ) { setType ( RubyMarkerAnnotation . TASK_ANNOTATION_TYPE ) ; fLayer = TASK_LAYER ; } else if ( fProblem . isWarning ( ) ) { setType ( RubyMarkerAnnotation . WARNING_ANNOTATION_TYPE ) ; fLayer = WARNING_LAYER ; } else if ( fProblem . isError ( ) ) { setType ( RubyMarkerAnnotation . ERROR_ANNOTATION_TYPE ) ; fLayer = ERROR_LAYER ; } else { setType ( RubyMarkerAnnotation . INFO_ANNOTATION_TYPE ) ; fLayer = INFO_LAYER ; } } public int getLayer ( ) { return fLayer ; } private void initializeImages ( ) { if ( ! fQuickFixImagesInitialized ) { if ( isProblem ( ) && indicateQuixFixableProblems ( ) ) { if ( ! fgQuickFixImagesInitialized ) { fgQuickFixImage = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_WARNING ) ; fgQuickFixErrorImage = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_ERROR ) ; fgQuickFixImage = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_FIXABLE_PROBLEM ) ; fgQuickFixImagesInitialized = true ; } if ( RubyMarkerAnnotation . ERROR_ANNOTATION_TYPE . equals ( getType ( ) ) ) fImage = fgQuickFixErrorImage ; else fImage = fgQuickFixImage ; } fQuickFixImagesInitialized = true ; } } private boolean indicateQuixFixableProblems ( ) { return PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . EDITOR_CORRECTION_INDICATION ) ; } public void paint ( GC gc , Canvas canvas , Rectangle r ) { initializeImages ( ) ; if ( fImage != null ) ImageUtilities . drawImage ( fImage , gc , canvas , r , SWT . CENTER , SWT . TOP ) ; } public Image getImage ( Display display ) { initializeImages ( ) ; return fImage ; } public String getText ( ) { return fProblem . getMessage ( ) ; } public String [ ] getArguments ( ) { return isProblem ( ) ? fProblem . getArguments ( ) : null ; } public boolean isProblem ( ) { String type = getType ( ) ; return RubyMarkerAnnotation . WARNING_ANNOTATION_TYPE . equals ( type ) || RubyMarkerAnnotation . ERROR_ANNOTATION_TYPE . equals ( type ) || SPELLING_ANNOTATION_TYPE . equals ( type ) ; } public boolean hasOverlay ( ) { return false ; } public IRubyAnnotation getOverlay ( ) { return null ; } public void addOverlaid ( IRubyAnnotation annotation ) { if ( fOverlaids == null ) fOverlaids = new ArrayList ( ) ; fOverlaids . add ( annotation ) ; } public void removeOverlaid ( IRubyAnnotation annotation ) { if ( fOverlaids != null ) { fOverlaids . remove ( annotation ) ; if ( fOverlaids . size ( ) == ) fOverlaids = null ; } } public Iterator getOverlaidIterator ( ) { if ( fOverlaids != null ) return fOverlaids . iterator ( ) ; return null ; } public IRubyScript getRubyScript ( ) { return fRubyScript ; } public int getId ( ) { return fProblem . getID ( ) ; } public String getMarkerType ( ) { if ( fProblem instanceof CategorizedProblem ) return ( ( CategorizedProblem ) fProblem ) . getMarkerType ( ) ; return null ; } } protected static class ReverseMap { static class Entry { Position fPosition ; Object fValue ; } private List fList = new ArrayList ( ) ; private int fAnchor = ; public ReverseMap ( ) { } public Object get ( Position position ) { Entry entry ; int length = fList . size ( ) ; for ( int i = fAnchor ; i < length ; i ++ ) { entry = ( Entry ) fList . get ( i ) ; if ( entry . fPosition . equals ( position ) ) { fAnchor = i ; return entry . fValue ; } } for ( int i = ; i < fAnchor ; i ++ ) { entry = ( Entry ) fList . get ( i ) ; if ( entry . fPosition . equals ( position ) ) { fAnchor = i ; return entry . fValue ; } } return null ; } private int getIndex ( Position position ) { Entry entry ; int length = fList . size ( ) ; for ( int i = ; i < length ; i ++ ) { entry = ( Entry ) fList . get ( i ) ; if ( entry . fPosition . equals ( position ) ) return i ; } return - ; } public void put ( Position position , Object value ) { int index = getIndex ( position ) ; if ( index == - ) { Entry entry = new Entry ( ) ; entry . fPosition = position ; entry . fValue = value ; fList . add ( entry ) ; } else { Entry entry = ( Entry ) fList . get ( index ) ; entry . fValue = value ; } } public void remove ( Position position ) { int index = getIndex ( position ) ; if ( index > - ) fList . remove ( index ) ; } public void clear ( ) { fList . clear ( ) ; } } protected static class RubyScriptAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor , IProblemRequestorExtension { private static class ProblemRequestorState { boolean fInsideReportingSequence = false ; List fReportedProblems ; } private ThreadLocal fProblemRequestorState = new ThreadLocal ( ) ; private int fStateCount = ; private IRubyScript fRubyScript ; private List fGeneratedAnnotations ; private IProgressMonitor fProgressMonitor ; private boolean fIsActive = false ; private boolean fIsHandlingTemporaryProblems ; private ReverseMap fReverseMap = new ReverseMap ( ) ; private List fPreviouslyOverlaid = null ; private List fCurrentlyOverlaid = new ArrayList ( ) ; public RubyScriptAnnotationModel ( IResource resource ) { super ( resource ) ; } public void setRubyScript ( IRubyScript unit ) { fRubyScript = unit ; } protected MarkerAnnotation createMarkerAnnotation ( IMarker marker ) { String markerType = MarkerUtilities . getMarkerType ( marker ) ; if ( markerType != null && markerType . startsWith ( RubyMarkerAnnotation . RUBY_MARKER_TYPE_PREFIX ) ) return new RubyMarkerAnnotation ( marker ) ; return super . createMarkerAnnotation ( marker ) ; } protected AnnotationModelEvent createAnnotationModelEvent ( ) { return new RubyScriptAnnotationModelEvent ( this , getResource ( ) ) ; } protected Position createPositionFromProblem ( IProblem problem ) { int start = problem . getSourceStart ( ) ; if ( start < ) return null ; int length = problem . getSourceEnd ( ) - problem . getSourceStart ( ) + ; if ( length < ) return null ; return new Position ( start , length ) ; } public void beginReporting ( ) { ProblemRequestorState state = ( ProblemRequestorState ) fProblemRequestorState . get ( ) ; if ( state == null ) internalBeginReporting ( false ) ; } public void beginReportingSequence ( ) { ProblemRequestorState state = ( ProblemRequestorState ) fProblemRequestorState . get ( ) ; if ( state == null ) internalBeginReporting ( true ) ; } private void internalBeginReporting ( boolean insideReportingSequence ) { if ( fRubyScript != null ) { ProblemRequestorState state = new ProblemRequestorState ( ) ; state . fInsideReportingSequence = insideReportingSequence ; state . fReportedProblems = new ArrayList ( ) ; synchronized ( getLockObject ( ) ) { fProblemRequestorState . set ( state ) ; ++ fStateCount ; } } } public void acceptProblem ( IProblem problem ) { if ( fIsHandlingTemporaryProblems ) { ProblemRequestorState state = ( ProblemRequestorState ) fProblemRequestorState . get ( ) ; if ( state != null ) state . fReportedProblems . add ( problem ) ; } } public void endReporting ( ) { ProblemRequestorState state = ( ProblemRequestorState ) fProblemRequestorState . get ( ) ; if ( state != null && ! state . fInsideReportingSequence ) internalEndReporting ( state ) ; } public void endReportingSequence ( ) { ProblemRequestorState state = ( ProblemRequestorState ) fProblemRequestorState . get ( ) ; if ( state != null && state . fInsideReportingSequence ) internalEndReporting ( state ) ; } private void internalEndReporting ( ProblemRequestorState state ) { int stateCount = ; synchronized ( getLockObject ( ) ) { -- fStateCount ; stateCount = fStateCount ; fProblemRequestorState . set ( null ) ; } if ( stateCount == && fIsHandlingTemporaryProblems ) reportProblems ( state . fReportedProblems ) ; } private void reportProblems ( List reportedProblems ) { if ( fProgressMonitor != null && fProgressMonitor . isCanceled ( ) ) return ; boolean temporaryProblemsChanged = false ; synchronized ( getLockObject ( ) ) { boolean isCanceled = false ; fPreviouslyOverlaid = fCurrentlyOverlaid ; fCurrentlyOverlaid = new ArrayList ( ) ; if ( fGeneratedAnnotations . size ( ) > ) { temporaryProblemsChanged = true ; removeAnnotations ( fGeneratedAnnotations , false , true ) ; fGeneratedAnnotations . clear ( ) ; } if ( reportedProblems != null && reportedProblems . size ( ) > ) { Iterator e = reportedProblems . iterator ( ) ; while ( e . hasNext ( ) ) { if ( fProgressMonitor != null && fProgressMonitor . isCanceled ( ) ) { isCanceled = true ; break ; } IProblem problem = ( IProblem ) e . next ( ) ; Position position = createPositionFromProblem ( problem ) ; if ( position != null ) { try { ProblemAnnotation annotation = new ProblemAnnotation ( problem , fRubyScript ) ; overlayMarkers ( position , annotation ) ; addAnnotation ( annotation , position , false ) ; fGeneratedAnnotations . add ( annotation ) ; temporaryProblemsChanged = true ; } catch ( BadLocationException x ) { } } } } removeMarkerOverlays ( isCanceled ) ; fPreviouslyOverlaid = null ; } if ( temporaryProblemsChanged ) fireModelChanged ( ) ; } private void removeMarkerOverlays ( boolean isCanceled ) { if ( isCanceled ) { fCurrentlyOverlaid . addAll ( fPreviouslyOverlaid ) ; } else if ( fPreviouslyOverlaid != null ) { Iterator e = fPreviouslyOverlaid . iterator ( ) ; while ( e . hasNext ( ) ) { RubyMarkerAnnotation annotation = ( RubyMarkerAnnotation ) e . next ( ) ; annotation . setOverlay ( null ) ; } } } private void setOverlay ( Object value , ProblemAnnotation problemAnnotation ) { if ( value instanceof RubyMarkerAnnotation ) { RubyMarkerAnnotation annotation = ( RubyMarkerAnnotation ) value ; if ( annotation . isProblem ( ) ) { annotation . setOverlay ( problemAnnotation ) ; fPreviouslyOverlaid . remove ( annotation ) ; fCurrentlyOverlaid . add ( annotation ) ; } } else { } } private void overlayMarkers ( Position position , ProblemAnnotation problemAnnotation ) { Object value = getAnnotations ( position ) ; if ( value instanceof List ) { List list = ( List ) value ; for ( Iterator e = list . iterator ( ) ; e . hasNext ( ) ; ) setOverlay ( e . next ( ) , problemAnnotation ) ; } else { setOverlay ( value , problemAnnotation ) ; } } private void startCollectingProblems ( ) { fGeneratedAnnotations = new ArrayList ( ) ; } private void stopCollectingProblems ( ) { if ( fGeneratedAnnotations != null ) removeAnnotations ( fGeneratedAnnotations , true , true ) ; fGeneratedAnnotations = null ; } public boolean isActive ( ) { return fIsActive ; } public void setProgressMonitor ( IProgressMonitor monitor ) { fProgressMonitor = monitor ; } public void setIsActive ( boolean isActive ) { fIsActive = isActive ; } public void setIsHandlingTemporaryProblems ( boolean enable ) { if ( fIsHandlingTemporaryProblems != enable ) { fIsHandlingTemporaryProblems = enable ; if ( fIsHandlingTemporaryProblems ) startCollectingProblems ( ) ; else stopCollectingProblems ( ) ; } } private Object getAnnotations ( Position position ) { synchronized ( getLockObject ( ) ) { return fReverseMap . get ( position ) ; } } protected void addAnnotation ( Annotation annotation , Position position , boolean fireModelChanged ) throws BadLocationException { super . addAnnotation ( annotation , position , fireModelChanged ) ; synchronized ( getLockObject ( ) ) { Object cached = fReverseMap . get ( position ) ; if ( cached == null ) fReverseMap . put ( position , annotation ) ; else if ( cached instanceof List ) { List list = ( List ) cached ; list . add ( annotation ) ; } else if ( cached instanceof Annotation ) { List list = new ArrayList ( ) ; list . add ( cached ) ; list . add ( annotation ) ; fReverseMap . put ( position , list ) ; } } } protected void removeAllAnnotations ( boolean fireModelChanged ) { super . removeAllAnnotations ( fireModelChanged ) ; synchronized ( getLockObject ( ) ) { fReverseMap . clear ( ) ; } } protected void removeAnnotation ( Annotation annotation , boolean fireModelChanged ) { Position position = getPosition ( annotation ) ; synchronized ( getLockObject ( ) ) { Object cached = fReverseMap . get ( position ) ; if ( cached instanceof List ) { List list = ( List ) cached ; list . remove ( annotation ) ; if ( list . size ( ) == ) { fReverseMap . put ( position , list . get ( ) ) ; list . clear ( ) ; } } else if ( cached instanceof Annotation ) { fReverseMap . remove ( position ) ; } } super . removeAnnotation ( annotation , fireModelChanged ) ; } } public ILineTracker createLineTracker ( Object element ) { return new DefaultLineTracker ( ) ; } public void setSavePolicy ( ISavePolicy savePolicy ) { fSavePolicy = savePolicy ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . io . File ; import org . eclipse . core . resources . IStorage ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPersistableElement ; import org . eclipse . ui . IStorageEditorInput ; import org . eclipse . ui . editors . text . ILocationProvider ; import org . rubypeople . rdt . core . LocalFileStorage ; public class ExternalRubyFileEditorInput implements IStorageEditorInput , ILocationProvider , IPersistableElement { private LocalFileStorage storage ; public ExternalRubyFileEditorInput ( File file ) { storage = new LocalFileStorage ( file ) ; } public ExternalRubyFileEditorInput ( LocalFileStorage file ) { storage = file ; } public boolean exists ( ) { return storage . getFile ( ) . exists ( ) ; } public ImageDescriptor getImageDescriptor ( ) { return null ; } public String getName ( ) { return storage . getFile ( ) . getName ( ) ; } public void saveState ( IMemento memento ) { memento . putString ( RubyExternalEditorFactory . MEMENTO_ABSOLUTE_PATH_KEY , storage . getFile ( ) . getAbsolutePath ( ) ) ; } public String getFactoryId ( ) { return RubyExternalEditorFactory . FACTORY_ID ; } public IStorage getStorage ( ) { return storage ; } public IPersistableElement getPersistable ( ) { return this ; } public String getToolTipText ( ) { return storage . getFile ( ) . getAbsolutePath ( ) ; } public Object getAdapter ( Class adapter ) { if ( ILocationProvider . class . equals ( adapter ) ) return this ; return Platform . getAdapterManager ( ) . getAdapter ( this , adapter ) ; } public IPath getPath ( Object element ) { if ( element instanceof ExternalRubyFileEditorInput ) { ExternalRubyFileEditorInput input = ( ExternalRubyFileEditorInput ) element ; return new Path ( input . getFilesystemFile ( ) . getAbsolutePath ( ) ) ; } return null ; } public File getFilesystemFile ( ) { return this . storage . getFile ( ) ; } public boolean equals ( Object object ) { return object instanceof ExternalRubyFileEditorInput && getStorage ( ) . equals ( ( ( ExternalRubyFileEditorInput ) object ) . getStorage ( ) ) ; } public int hashCode ( ) { return getStorage ( ) . hashCode ( ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . Collection ; import java . util . Iterator ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . internal . ui . text . ruby . CompletionProposalCategory ; import org . rubypeople . rdt . internal . ui . text . ruby . CompletionProposalComputerRegistry ; public final class SpecificContentAssistExecutor { private final CompletionProposalComputerRegistry fRegistry ; public SpecificContentAssistExecutor ( CompletionProposalComputerRegistry registry ) { Assert . isNotNull ( registry ) ; fRegistry = registry ; } public void invokeContentAssist ( final ITextEditor editor , String categoryId ) { Collection < CompletionProposalCategory > categories = fRegistry . getProposalCategories ( ) ; boolean [ ] inclusionState = new boolean [ categories . size ( ) ] ; boolean [ ] separateState = new boolean [ categories . size ( ) ] ; int i = ; for ( Iterator < CompletionProposalCategory > it = categories . iterator ( ) ; it . hasNext ( ) ; i ++ ) { CompletionProposalCategory cat = it . next ( ) ; inclusionState [ i ] = cat . isIncluded ( ) ; cat . setIncluded ( cat . getId ( ) . equals ( categoryId ) ) ; separateState [ i ] = cat . isSeparateCommand ( ) ; cat . setSeparateCommand ( false ) ; } try { ITextOperationTarget target = ( ITextOperationTarget ) editor . getAdapter ( ITextOperationTarget . class ) ; if ( target != null && target . canDoOperation ( ISourceViewer . CONTENTASSIST_PROPOSALS ) ) target . doOperation ( ISourceViewer . CONTENTASSIST_PROPOSALS ) ; } finally { i = ; for ( Iterator < CompletionProposalCategory > it = categories . iterator ( ) ; it . hasNext ( ) ; i ++ ) { CompletionProposalCategory cat = it . next ( ) ; cat . setIncluded ( inclusionState [ i ] ) ; cat . setSeparateCommand ( separateState [ i ] ) ; } } } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ResourceBundle ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . VerticalRulerEvent ; import org . eclipse . ui . ISelectionListener ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . eclipse . ui . texteditor . IUpdate ; import org . eclipse . ui . texteditor . SelectAnnotationRulerAction ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . text . correction . RubyCorrectionProcessor ; public class RubySelectMarkerRulerAction2 extends SelectAnnotationRulerAction { public RubySelectMarkerRulerAction2 ( ResourceBundle bundle , String prefix , ITextEditor editor ) { super ( bundle , prefix , editor ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . JAVA_SELECT_MARKER_RULER_ACTION ) ; } public void annotationDefaultSelected ( VerticalRulerEvent event ) { Annotation annotation = event . getSelectedAnnotation ( ) ; IAnnotationModel model = getAnnotationModel ( ) ; if ( isOverrideIndicator ( annotation ) ) { ( ( OverrideIndicatorManager . OverrideIndicator ) annotation ) . open ( ) ; return ; } if ( isBreakpoint ( annotation ) ) triggerAction ( ITextEditorActionConstants . RULER_DOUBLE_CLICK ) ; Position position = model . getPosition ( annotation ) ; if ( position == null ) return ; if ( isQuickFixTarget ( annotation ) ) { ITextOperationTarget operation = ( ITextOperationTarget ) getTextEditor ( ) . getAdapter ( ITextOperationTarget . class ) ; final int opCode = ISourceViewer . QUICK_ASSIST ; if ( operation != null && operation . canDoOperation ( opCode ) ) { getTextEditor ( ) . selectAndReveal ( position . getOffset ( ) , position . getLength ( ) ) ; operation . doOperation ( opCode ) ; return ; } } super . annotationDefaultSelected ( event ) ; } private boolean isOverrideIndicator ( Annotation annotation ) { return annotation instanceof OverrideIndicatorManager . OverrideIndicator ; } private boolean isBreakpoint ( Annotation annotation ) { return annotation . getType ( ) . equals ( "" ) ; } private boolean isQuickFixTarget ( Annotation a ) { return RubyCorrectionProcessor . hasCorrections ( a ) ; } private void triggerAction ( String actionID ) { IAction action = getTextEditor ( ) . getAction ( actionID ) ; if ( action != null ) { if ( action instanceof IUpdate ) ( ( IUpdate ) action ) . update ( ) ; if ( action instanceof ISelectionListener ) { ( ( ISelectionListener ) action ) . selectionChanged ( null , null ) ; } if ( action . isEnabled ( ) ) action . run ( ) ; } } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . filebuffers . FileBuffers ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ISynchronizable ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . editors . text . FileDocumentProvider ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class RubyScriptDocumentProvider extends FileDocumentProvider { public interface InputChangeListener { void inputChanged ( IRubyScriptEditorInput input ) ; } protected class RubyScriptSynchronizer implements IElementChangedListener { protected IRubyScriptEditorInput fInput ; protected ISourceFolderRoot fSourceFolderRoot ; public RubyScriptSynchronizer ( IRubyScriptEditorInput input ) { fInput = input ; IRubyElement parent = fInput . getRubyScript ( ) . getParent ( ) ; while ( parent != null && ! ( parent instanceof ISourceFolderRoot ) ) { parent = parent . getParent ( ) ; } fSourceFolderRoot = ( ISourceFolderRoot ) parent ; } public void install ( ) { RubyCore . addElementChangedListener ( this ) ; } public void uninstall ( ) { RubyCore . removeElementChangedListener ( this ) ; } public void elementChanged ( ElementChangedEvent e ) { check ( fSourceFolderRoot , e . getDelta ( ) ) ; } protected boolean check ( ISourceFolderRoot input , IRubyElementDelta delta ) { IRubyElement element = delta . getElement ( ) ; if ( ( delta . getKind ( ) & IRubyElementDelta . REMOVED ) != || ( delta . getFlags ( ) & IRubyElementDelta . F_CLOSED ) != ) { if ( element . equals ( input . getRubyProject ( ) ) || element . equals ( input ) ) { handleDeleted ( fInput ) ; return true ; } } if ( ( ( delta . getFlags ( ) & IRubyElementDelta . F_ARCHIVE_CONTENT_CHANGED ) != ) && input . equals ( element ) ) { handleDeleted ( fInput ) ; return true ; } if ( ( ( delta . getFlags ( ) & IRubyElementDelta . F_REMOVED_FROM_CLASSPATH ) != ) && input . equals ( element ) ) { handleDeleted ( fInput ) ; return true ; } IRubyElementDelta [ ] subdeltas = delta . getAffectedChildren ( ) ; for ( int i = ; i < subdeltas . length ; i ++ ) { if ( check ( input , subdeltas [ i ] ) ) return true ; } if ( ( delta . getFlags ( ) & IRubyElementDelta . F_SOURCEDETACHED ) != || ( delta . getFlags ( ) & IRubyElementDelta . F_SOURCEATTACHED ) != ) { IRubyScript file = fInput != null ? fInput . getRubyScript ( ) : null ; IRubyProject project = input != null ? input . getRubyProject ( ) : null ; boolean isOnClasspath = false ; if ( file != null && project != null ) isOnClasspath = project . isOnLoadpath ( file ) ; if ( isOnClasspath ) { fireInputChanged ( fInput ) ; return false ; } else { handleDeleted ( fInput ) ; return true ; } } return false ; } } protected class _FileSynchronizer extends FileSynchronizer { public _FileSynchronizer ( IFileEditorInput fileEditorInput ) { super ( fileEditorInput ) ; } } protected class RubyScriptInfo extends FileInfo { RubyScriptSynchronizer fRubyScriptSynchronizer = null ; RubyScriptInfo ( IDocument document , IAnnotationModel model , _FileSynchronizer fileSynchronizer ) { super ( document , model , fileSynchronizer ) ; } RubyScriptInfo ( IDocument document , IAnnotationModel model , RubyScriptSynchronizer classFileSynchronizer ) { super ( document , model , null ) ; fRubyScriptSynchronizer = classFileSynchronizer ; } } private List fInputListeners = new ArrayList ( ) ; public RubyScriptDocumentProvider ( ) { super ( ) ; } protected boolean setDocumentContent ( IDocument document , IEditorInput editorInput , String encoding ) throws CoreException { if ( editorInput instanceof IRubyScriptEditorInput ) { IRubyScript rubyScript = ( ( IRubyScriptEditorInput ) editorInput ) . getRubyScript ( ) ; document . set ( rubyScript . getSource ( ) ) ; return true ; } return super . setDocumentContent ( document , editorInput , encoding ) ; } protected IAnnotationModel createRubyScriptAnnotationModel ( IRubyScriptEditorInput rubyScriptEditorInput ) throws CoreException { IRubyScript script = rubyScriptEditorInput . getRubyScript ( ) ; ExternalFileRubyAnnotationModel model = new ExternalFileRubyAnnotationModel ( script ) ; return model ; } protected IDocument createEmptyDocument ( ) { IDocument document = FileBuffers . getTextFileBufferManager ( ) . createEmptyDocument ( null ) ; if ( document instanceof ISynchronizable ) ( ( ISynchronizable ) document ) . setLockObject ( new Object ( ) ) ; return document ; } protected IDocument createDocument ( Object element ) throws CoreException { IDocument document = super . createDocument ( element ) ; if ( document != null ) { RubyTextTools tools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; tools . setupRubyDocumentPartitioner ( document , IRubyPartitions . RUBY_PARTITIONING ) ; } return document ; } protected ElementInfo createElementInfo ( Object element ) throws CoreException { if ( element instanceof IRubyScriptEditorInput ) { IRubyScriptEditorInput input = ( IRubyScriptEditorInput ) element ; IDocument d = createDocument ( input ) ; IAnnotationModel m = createRubyScriptAnnotationModel ( input ) ; if ( input instanceof RubyScriptEditorInput ) { RubyScriptSynchronizer s = new RubyScriptSynchronizer ( input ) ; s . install ( ) ; RubyScriptInfo info = new RubyScriptInfo ( d , m , s ) ; info . fEncoding = getPersistedEncoding ( element ) ; return info ; } } return null ; } protected void disposeElementInfo ( Object element , ElementInfo info ) { RubyScriptInfo classFileInfo = ( RubyScriptInfo ) info ; if ( classFileInfo . fRubyScriptSynchronizer != null ) { classFileInfo . fRubyScriptSynchronizer . uninstall ( ) ; classFileInfo . fRubyScriptSynchronizer = null ; } super . disposeElementInfo ( element , info ) ; } protected void doSaveDocument ( IProgressMonitor monitor , Object element , IDocument document ) throws CoreException { } public boolean isSynchronized ( Object element ) { Object elementInfo = getElementInfo ( element ) ; if ( elementInfo instanceof RubyScriptInfo ) { IRubyScriptEditorInput input = ( IRubyScriptEditorInput ) element ; IResource resource ; try { resource = input . getRubyScript ( ) . getUnderlyingResource ( ) ; } catch ( RubyModelException e ) { return true ; } return resource == null || resource . isSynchronized ( IResource . DEPTH_ZERO ) ; } return false ; } protected void handleDeleted ( IRubyScriptEditorInput input ) { fireElementDeleted ( input ) ; } protected void fireInputChanged ( IRubyScriptEditorInput input ) { List list = new ArrayList ( fInputListeners ) ; for ( Iterator i = list . iterator ( ) ; i . hasNext ( ) ; ) ( ( InputChangeListener ) i . next ( ) ) . inputChanged ( input ) ; } public void addInputChangeListener ( InputChangeListener listener ) { fInputListeners . add ( listener ) ; } public void removeInputChangeListener ( InputChangeListener listener ) { fInputListeners . remove ( listener ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . AnnotationModelEvent ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . ui . texteditor . MarkerAnnotation ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyScriptAnnotationModelEvent extends AnnotationModelEvent { private boolean fIncludesProblemMarkerAnnotations ; private IResource fUnderlyingResource ; public RubyScriptAnnotationModelEvent ( IAnnotationModel model , IResource underlyingResource ) { super ( model ) ; fUnderlyingResource = underlyingResource ; fIncludesProblemMarkerAnnotations = false ; } private void testIfProblemMarker ( Annotation annotation ) { if ( fIncludesProblemMarkerAnnotations ) { return ; } if ( annotation instanceof RubyMarkerAnnotation ) { fIncludesProblemMarkerAnnotations = ( ( RubyMarkerAnnotation ) annotation ) . isProblem ( ) ; } else if ( annotation instanceof MarkerAnnotation ) { try { IMarker marker = ( ( MarkerAnnotation ) annotation ) . getMarker ( ) ; if ( ! marker . exists ( ) || marker . isSubtypeOf ( IMarker . PROBLEM ) ) { fIncludesProblemMarkerAnnotations = true ; } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } } public void annotationAdded ( Annotation annotation ) { super . annotationAdded ( annotation ) ; testIfProblemMarker ( annotation ) ; } public void annotationRemoved ( Annotation annotation ) { super . annotationRemoved ( annotation ) ; testIfProblemMarker ( annotation ) ; } public void annotationRemoved ( Annotation annotation , Position position ) { super . annotationRemoved ( annotation , position ) ; testIfProblemMarker ( annotation ) ; } public void annotationChanged ( Annotation annotation ) { testIfProblemMarker ( annotation ) ; super . annotationChanged ( annotation ) ; } public boolean includesProblemMarkerAnnotationChanges ( ) { return fIncludesProblemMarkerAnnotations ; } public IResource getUnderlyingResource ( ) { return fUnderlyingResource ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class TogglePresentationAction extends TextEditorAction implements IPropertyChangeListener { private IPreferenceStore fStore ; public TogglePresentationAction ( ) { super ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , null , IAction . AS_CHECK_BOX ) ; RubyPluginImages . setToolImageDescriptors ( this , "" ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . TOGGLE_PRESENTATION_ACTION ) ; update ( ) ; } public void run ( ) { ITextEditor editor = getTextEditor ( ) ; if ( editor == null ) return ; IRegion remembered = editor . getHighlightRange ( ) ; editor . resetHighlightRange ( ) ; boolean showAll = ! editor . showsHighlightRangeOnly ( ) ; setChecked ( showAll ) ; editor . showHighlightRangeOnly ( showAll ) ; if ( remembered != null ) editor . setHighlightRange ( remembered . getOffset ( ) , remembered . getLength ( ) , true ) ; fStore . removePropertyChangeListener ( this ) ; fStore . setValue ( PreferenceConstants . EDITOR_SHOW_SEGMENTS , showAll ) ; fStore . addPropertyChangeListener ( this ) ; } public void update ( ) { ITextEditor editor = getTextEditor ( ) ; boolean checked = ( editor != null && editor . showsHighlightRangeOnly ( ) ) ; setChecked ( checked ) ; if ( editor instanceof RubyEditor ) { IWorkingCopyManager manager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; setEnabled ( manager . getWorkingCopy ( editor . getEditorInput ( ) ) != null ) ; } else setEnabled ( editor != null ) ; } public void setEditor ( ITextEditor editor ) { super . setEditor ( editor ) ; if ( editor != null ) { if ( fStore == null ) { fStore = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; fStore . addPropertyChangeListener ( this ) ; } synchronizeWithPreference ( editor ) ; } else if ( fStore != null ) { fStore . removePropertyChangeListener ( this ) ; fStore = null ; } update ( ) ; } private void synchronizeWithPreference ( ITextEditor editor ) { if ( editor == null ) return ; boolean showSegments = fStore . getBoolean ( PreferenceConstants . EDITOR_SHOW_SEGMENTS ) ; setChecked ( showSegments ) ; if ( editor . showsHighlightRangeOnly ( ) != showSegments ) { IRegion remembered = editor . getHighlightRange ( ) ; editor . resetHighlightRange ( ) ; editor . showHighlightRangeOnly ( showSegments ) ; if ( remembered != null ) editor . setHighlightRange ( remembered . getOffset ( ) , remembered . getLength ( ) , true ) ; } } public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( PreferenceConstants . EDITOR_SHOW_SEGMENTS ) ) synchronizeWithPreference ( getTextEditor ( ) ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . text . Assert ; import org . eclipse . ui . IEditorInput ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; import org . rubypeople . rdt . ui . IWorkingCopyManagerExtension ; public class WorkingCopyManager implements IWorkingCopyManager , IWorkingCopyManagerExtension { private RubyDocumentProvider fDocumentProvider ; private Map fMap ; private boolean fIsShuttingDown ; public WorkingCopyManager ( RubyDocumentProvider provider ) { Assert . isNotNull ( provider ) ; fDocumentProvider = provider ; } public void connect ( IEditorInput input ) throws CoreException { fDocumentProvider . connect ( input ) ; } public void disconnect ( IEditorInput input ) { fDocumentProvider . disconnect ( input ) ; } public void shutdown ( ) { if ( ! fIsShuttingDown ) { fIsShuttingDown = true ; try { if ( fMap != null ) { fMap . clear ( ) ; fMap = null ; } fDocumentProvider . shutdown ( ) ; } finally { fIsShuttingDown = false ; } } } public IRubyScript getWorkingCopy ( IEditorInput input ) { return getWorkingCopy ( input , true ) ; } public IRubyScript getWorkingCopy ( IEditorInput input , boolean primaryOnly ) { IRubyScript unit = fMap == null ? null : ( IRubyScript ) fMap . get ( input ) ; if ( unit == null ) unit = fDocumentProvider . getWorkingCopy ( input ) ; if ( unit == null && input instanceof IRubyScriptEditorInput ) { IRubyScriptEditorInput rseInput = ( IRubyScriptEditorInput ) input ; unit = rseInput . getRubyScript ( ) ; } if ( unit != null && ( ! primaryOnly || RubyModelUtil . isPrimary ( unit ) ) ) return unit ; return null ; } public void setWorkingCopy ( IEditorInput input , IRubyScript workingCopy ) { if ( fDocumentProvider . getDocument ( input ) != null ) { if ( fMap == null ) fMap = new HashMap ( ) ; fMap . put ( input , workingCopy ) ; } } public void removeWorkingCopy ( IEditorInput input ) { fMap . remove ( input ) ; if ( fMap . isEmpty ( ) ) fMap = null ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . HashMap ; import java . util . Map ; import java . util . ResourceBundle ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . ResourceAction ; import org . eclipse . ui . texteditor . TextEditorAction ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class ToggleCommentAction extends TextEditorAction { private ITextOperationTarget fOperationTarget ; protected String fDocumentPartitioning ; protected Map fPrefixesMap ; public ToggleCommentAction ( ResourceBundle bundle , String prefix , ITextEditor editor ) { super ( bundle , prefix , editor ) ; } public void run ( ) { if ( fOperationTarget == null || fDocumentPartitioning == null || fPrefixesMap == null ) return ; ITextEditor editor = getTextEditor ( ) ; if ( editor == null ) return ; if ( ! validateEditorInputState ( ) ) return ; final int operationCode ; if ( isSelectionCommented ( editor . getSelectionProvider ( ) . getSelection ( ) ) ) operationCode = ITextOperationTarget . STRIP_PREFIX ; else operationCode = ITextOperationTarget . PREFIX ; Shell shell = editor . getSite ( ) . getShell ( ) ; if ( ! fOperationTarget . canDoOperation ( operationCode ) ) { if ( shell != null ) MessageDialog . openError ( shell , RubyEditorMessages . ToggleComment_error_title , RubyEditorMessages . ToggleComment_error_message ) ; return ; } Display display = null ; if ( shell != null && ! shell . isDisposed ( ) ) display = shell . getDisplay ( ) ; BusyIndicator . showWhile ( display , new Runnable ( ) { public void run ( ) { fOperationTarget . doOperation ( operationCode ) ; } } ) ; } private boolean isSelectionCommented ( ISelection selection ) { if ( ! ( selection instanceof ITextSelection ) ) return false ; ITextSelection textSelection = ( ITextSelection ) selection ; if ( textSelection . getStartLine ( ) < || textSelection . getEndLine ( ) < ) return false ; IDocument document = getTextEditor ( ) . getDocumentProvider ( ) . getDocument ( getTextEditor ( ) . getEditorInput ( ) ) ; try { IRegion block = getTextBlockFromSelection ( textSelection , document ) ; ITypedRegion [ ] regions = TextUtilities . computePartitioning ( document , fDocumentPartitioning , block . getOffset ( ) , block . getLength ( ) , false ) ; int lineCount = ; int [ ] lines = new int [ regions . length * ] ; for ( int i = , j = ; i < regions . length ; i ++ , j += ) { lines [ j ] = getFirstCompleteLineOfRegion ( regions [ i ] , document ) ; int length = regions [ i ] . getLength ( ) ; int offset = regions [ i ] . getOffset ( ) + length ; if ( length > ) offset -- ; lines [ j + ] = ( lines [ j ] == - ? - : document . getLineOfOffset ( offset ) ) ; lineCount += lines [ j + ] - lines [ j ] + ; } for ( int i = , j = ; i < regions . length ; i ++ , j += ) { String [ ] prefixes = ( String [ ] ) fPrefixesMap . get ( regions [ i ] . getType ( ) ) ; if ( prefixes != null && prefixes . length > && lines [ j ] >= && lines [ j + ] >= ) if ( ! isBlockCommented ( lines [ j ] , lines [ j + ] , prefixes , document ) ) return false ; } return true ; } catch ( BadLocationException x ) { RubyPlugin . log ( x ) ; } return false ; } private IRegion getTextBlockFromSelection ( ITextSelection selection , IDocument document ) { try { IRegion line = document . getLineInformationOfOffset ( selection . getOffset ( ) ) ; int length = selection . getLength ( ) == ? line . getLength ( ) : selection . getLength ( ) + ( selection . getOffset ( ) - line . getOffset ( ) ) ; return new Region ( line . getOffset ( ) , length ) ; } catch ( BadLocationException x ) { RubyPlugin . log ( x ) ; } return null ; } private int getFirstCompleteLineOfRegion ( IRegion region , IDocument document ) { try { int startLine = document . getLineOfOffset ( region . getOffset ( ) ) ; int offset = document . getLineOffset ( startLine ) ; if ( offset >= region . getOffset ( ) ) return startLine ; offset = document . getLineOffset ( startLine + ) ; return ( offset > region . getOffset ( ) + region . getLength ( ) ? - : startLine + ) ; } catch ( BadLocationException x ) { RubyPlugin . log ( x ) ; } return - ; } private boolean isBlockCommented ( int startLine , int endLine , String [ ] prefixes , IDocument document ) { try { for ( int i = startLine ; i <= endLine ; i ++ ) { IRegion line = document . getLineInformation ( i ) ; String text = document . get ( line . getOffset ( ) , line . getLength ( ) ) ; int [ ] found = TextUtilities . indexOf ( prefixes , text , ) ; if ( found [ ] == - ) return false ; String s = document . get ( line . getOffset ( ) , found [ ] ) ; s = s . trim ( ) ; if ( s . length ( ) != ) return false ; } return true ; } catch ( BadLocationException x ) { RubyPlugin . log ( x ) ; } return false ; } public void update ( ) { super . update ( ) ; if ( ! canModifyEditor ( ) ) { setEnabled ( false ) ; return ; } ITextEditor editor = getTextEditor ( ) ; if ( fOperationTarget == null && editor != null ) fOperationTarget = ( ITextOperationTarget ) editor . getAdapter ( ITextOperationTarget . class ) ; boolean isEnabled = ( fOperationTarget != null && fOperationTarget . canDoOperation ( ITextOperationTarget . PREFIX ) && fOperationTarget . canDoOperation ( ITextOperationTarget . STRIP_PREFIX ) ) ; setEnabled ( isEnabled ) ; } public void setEditor ( ITextEditor editor ) { super . setEditor ( editor ) ; fOperationTarget = null ; } public void configure ( ISourceViewer sourceViewer , SourceViewerConfiguration configuration ) { fPrefixesMap = null ; String [ ] types = configuration . getConfiguredContentTypes ( sourceViewer ) ; Map prefixesMap = new HashMap ( types . length ) ; for ( int i = ; i < types . length ; i ++ ) { String type = types [ i ] ; String [ ] prefixes = getDefaultPrefixes ( configuration , sourceViewer , type ) ; if ( prefixes != null && prefixes . length > ) { int emptyPrefixes = ; for ( int j = ; j < prefixes . length ; j ++ ) if ( prefixes [ j ] . length ( ) == ) emptyPrefixes ++ ; if ( emptyPrefixes > ) { String [ ] nonemptyPrefixes = new String [ prefixes . length - emptyPrefixes ] ; for ( int j = , k = ; j < prefixes . length ; j ++ ) { String prefix = prefixes [ j ] ; if ( prefix . length ( ) != ) { nonemptyPrefixes [ k ] = prefix ; k ++ ; } } prefixes = nonemptyPrefixes ; } prefixesMap . put ( type , prefixes ) ; } } fDocumentPartitioning = configuration . getConfiguredDocumentPartitioning ( sourceViewer ) ; fPrefixesMap = prefixesMap ; } protected String [ ] getDefaultPrefixes ( SourceViewerConfiguration configuration , ISourceViewer sourceViewer , String type ) { return configuration . getDefaultPrefixes ( sourceViewer , type ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . ui . IElementFactory ; import org . eclipse . ui . IMemento ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; public class RubyScriptEditorInputFactory implements IElementFactory { public final static String ID = "" ; public final static String KEY = "" ; public IAdaptable createElement ( IMemento memento ) { String identifier = memento . getString ( KEY ) ; if ( identifier != null ) { IRubyElement element = RubyCore . create ( identifier ) ; try { return EditorUtility . getEditorInput ( element ) ; } catch ( RubyModelException x ) { } } return null ; } public static void saveState ( IMemento memento , RubyScriptEditorInput input ) { IRubyScript c = input . getRubyScript ( ) ; memento . putString ( KEY , c . getHandleIdentifier ( ) ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . net . URI ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension4 ; import org . eclipse . jface . text . IDocumentListener ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ISelectionValidator ; import org . eclipse . jface . text . ISynchronizable ; import org . eclipse . jface . text . ITextInputListener ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . ITextViewerExtension5 ; import org . eclipse . jface . text . IWidgetTokenKeeper ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . jface . text . contentassist . ContentAssistant ; import org . eclipse . jface . text . contentassist . IContentAssistant ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . IAnnotationModelExtension ; import org . eclipse . jface . text . source . IOverviewRuler ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . IVerticalRuler ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . ListenerList ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IPartService ; import org . eclipse . ui . IWindowListener ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . editors . text . TextEditor ; import org . eclipse . ui . texteditor . AbstractDecoratedTextEditorPreferenceConstants ; import org . eclipse . ui . texteditor . ChainedPreferenceStore ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . SourceViewerDecorationSupport ; import org . eclipse . ui . views . contentoutline . ContentOutline ; import org . eclipse . ui . views . contentoutline . IContentOutlinePage ; import org . jruby . ast . RootNode ; import org . osgi . service . prefs . BackingStoreException ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . ExternalRubyScript ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor . ITextConverter ; import org . rubypeople . rdt . internal . ui . search . IOccurrencesFinder ; import org . rubypeople . rdt . internal . ui . search . OccurrencesFinder ; import org . rubypeople . rdt . internal . ui . text . ContentAssistPreference ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . PreferencesAdapter ; import org . rubypeople . rdt . internal . ui . text . RubyPairMatcher ; import org . rubypeople . rdt . internal . ui . text . RubyWordFinder ; import org . rubypeople . rdt . internal . ui . viewsupport . ISelectionListenerWithAST ; import org . rubypeople . rdt . internal . ui . viewsupport . SelectionListenerWithASTManager ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . rubyeditor . ICustomRubyOutlinePage ; import org . rubypeople . rdt . ui . text . RubySourceViewerConfiguration ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public abstract class RubyAbstractEditor extends TextEditor { private static final boolean CODE_ASSIST_DEBUG = "" . equalsIgnoreCase ( Platform . getDebugOption ( "" ) ) ; protected RubyTextTools textTools ; private ISourceReference reference ; protected String fOutlinerContextMenuId ; protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener ( ) ; private ICustomRubyOutlinePage fOutlinePage ; protected final static String MATCHING_BRACKETS = PreferenceConstants . EDITOR_MATCHING_BRACKETS ; protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants . EDITOR_MATCHING_BRACKETS_COLOR ; protected final static char [ ] BRACKETS = { '' , '' , '' , '' , '' , '' } ; private static final String CUSTOM_OUTLINE_EXTPOINT_ID = "" ; protected RubyPairMatcher fBracketMatcher = new RubyPairMatcher ( BRACKETS ) ; private Annotation [ ] fOccurrenceAnnotations = null ; private boolean fMarkOccurrenceAnnotations ; private boolean fStickyOccurrenceAnnotations ; private boolean fMarkTypeOccurrences ; private boolean fMarkMethodOccurrences ; private boolean fMarkConstantOccurrences ; private boolean fMarkFieldOccurrences ; private boolean fMarkLocalVariableOccurrences ; private boolean fMarkMethodExitPoints ; private ISelection fForcedMarkOccurrencesSelection ; private long fMarkOccurrenceModificationStamp = IDocumentExtension4 . UNKNOWN_MODIFICATION_STAMP ; private ActivationListener fActivationListener = new ActivationListener ( ) ; private ISelectionListenerWithAST fPostSelectionListenerWithAST ; private OccurrencesFinderJob fOccurrencesFinderJob ; private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler ; private IRegion fMarkOccurrenceTargetRegion ; private IPreferenceStore createCombinedPreferenceStore ( IEditorInput input ) { List stores = new ArrayList ( ) ; IRubyProject project = EditorUtility . getRubyProject ( input ) ; if ( project != null ) { stores . add ( new EclipsePreferencesAdapter ( new ProjectScope ( project . getProject ( ) ) , RubyCore . PLUGIN_ID ) ) ; } stores . add ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; stores . add ( new PreferencesAdapter ( RubyCore . getPlugin ( ) . getPluginPreferences ( ) ) ) ; stores . add ( EditorsUI . getPreferenceStore ( ) ) ; return new ChainedPreferenceStore ( ( IPreferenceStore [ ] ) stores . toArray ( new IPreferenceStore [ stores . size ( ) ] ) ) ; } public void outlinePageClosed ( ) { if ( fOutlinePage != null ) { fOutlineSelectionChangedListener . uninstall ( fOutlinePage ) ; fOutlinePage = null ; resetHighlightRange ( ) ; } } protected void configureSourceViewerDecorationSupport ( SourceViewerDecorationSupport support ) { support . setCharacterPairMatcher ( fBracketMatcher ) ; support . setMatchingCharacterPainterPreferenceKeys ( MATCHING_BRACKETS , MATCHING_BRACKETS_COLOR ) ; super . configureSourceViewerDecorationSupport ( support ) ; } protected ISourceViewer createSourceViewer ( Composite parent , IVerticalRuler ruler , int styles ) { fAnnotationAccess = createAnnotationAccess ( ) ; fOverviewRuler = createOverviewRuler ( getSharedColors ( ) ) ; IPreferenceStore store = getPreferenceStore ( ) ; ISourceViewer viewer = createRubySourceViewer ( parent , ruler , getOverviewRuler ( ) , isOverviewRulerVisible ( ) , styles , store ) ; getSourceViewerDecorationSupport ( viewer ) ; return viewer ; } protected ISourceViewer createRubySourceViewer ( Composite parent , IVerticalRuler verticalRuler , IOverviewRuler overviewRuler , boolean isOverviewRulerVisible , int styles , IPreferenceStore store ) { return new AdaptedSourceViewer ( parent , verticalRuler , overviewRuler , isOverviewRulerVisible , styles , store ) ; } protected void setOutlinerContextMenuId ( String menuId ) { fOutlinerContextMenuId = menuId ; } protected void initializeEditor ( ) { super . initializeEditor ( ) ; IPreferenceStore store = createCombinedPreferenceStore ( null ) ; setPreferenceStore ( store ) ; RubyTextTools textTools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; setSourceViewerConfiguration ( new RubySourceViewerConfiguration ( textTools . getColorManager ( ) , store , this , IRubyPartitions . RUBY_PARTITIONING ) ) ; fMarkOccurrenceAnnotations = store . getBoolean ( PreferenceConstants . EDITOR_MARK_OCCURRENCES ) ; fStickyOccurrenceAnnotations = store . getBoolean ( PreferenceConstants . EDITOR_STICKY_OCCURRENCES ) ; fMarkTypeOccurrences = store . getBoolean ( PreferenceConstants . EDITOR_MARK_TYPE_OCCURRENCES ) ; fMarkMethodOccurrences = store . getBoolean ( PreferenceConstants . EDITOR_MARK_METHOD_OCCURRENCES ) ; fMarkConstantOccurrences = store . getBoolean ( PreferenceConstants . EDITOR_MARK_CONSTANT_OCCURRENCES ) ; fMarkFieldOccurrences = store . getBoolean ( PreferenceConstants . EDITOR_MARK_FIELD_OCCURRENCES ) ; fMarkLocalVariableOccurrences = store . getBoolean ( PreferenceConstants . EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES ) ; fMarkMethodExitPoints = store . getBoolean ( PreferenceConstants . EDITOR_MARK_METHOD_EXIT_POINTS ) ; } protected void setPreferenceStore ( IPreferenceStore store ) { super . setPreferenceStore ( store ) ; if ( getSourceViewerConfiguration ( ) instanceof RubySourceViewerConfiguration ) { RubyTextTools textTools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; setSourceViewerConfiguration ( new RubySourceViewerConfiguration ( textTools . getColorManager ( ) , store , this , IRubyPartitions . RUBY_PARTITIONING ) ) ; } if ( getSourceViewer ( ) instanceof RubySourceViewer ) ( ( RubySourceViewer ) getSourceViewer ( ) ) . setPreferenceStore ( store ) ; } public void dispose ( ) { super . dispose ( ) ; fMarkOccurrenceAnnotations = false ; uninstallOccurrencesFinder ( ) ; if ( fActivationListener != null ) { PlatformUI . getWorkbench ( ) . removeWindowListener ( fActivationListener ) ; fActivationListener = null ; } } public Object getAdapter ( Class required ) { if ( IContentOutlinePage . class . equals ( required ) ) { if ( fOutlinePage == null ) fOutlinePage = createRubyOutlinePage ( ) ; return fOutlinePage ; } return super . getAdapter ( required ) ; } public void createPartControl ( Composite parent ) { super . createPartControl ( parent ) ; if ( fMarkOccurrenceAnnotations ) installOccurrencesFinder ( false ) ; } protected ICustomRubyOutlinePage createRubyOutlinePage ( ) { IRubyElement element = getInputRubyElement ( ) ; ICustomRubyOutlinePage outlinePage = null ; List < ICustomRubyOutlinePage > customPages = getCustomOutlines ( ) ; for ( ICustomRubyOutlinePage customRubyOutlinePage : customPages ) { if ( customRubyOutlinePage . isEnabled ( element ) ) { customRubyOutlinePage . init ( fOutlinerContextMenuId , this ) ; outlinePage = ( RubyOutlinePage ) customRubyOutlinePage ; break ; } } if ( outlinePage == null ) { outlinePage = new RubyOutlinePage ( ) ; outlinePage . init ( fOutlinerContextMenuId , this ) ; } fOutlineSelectionChangedListener . install ( outlinePage ) ; setOutlinePageInput ( outlinePage , getEditorInput ( ) ) ; return outlinePage ; } private List < ICustomRubyOutlinePage > getCustomOutlines ( ) { List < ICustomRubyOutlinePage > list = new ArrayList < ICustomRubyOutlinePage > ( ) ; IExtensionPoint extension = Platform . getExtensionRegistry ( ) . getExtensionPoint ( RubyPlugin . PLUGIN_ID , CUSTOM_OUTLINE_EXTPOINT_ID ) ; if ( extension == null ) return list ; IExtension [ ] extensions = extension . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] configElements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < configElements . length ; j ++ ) { final IConfigurationElement configElement = configElements [ j ] ; String elementName = configElement . getName ( ) ; if ( ! ( "" . equals ( elementName ) ) ) { continue ; } try { ICustomRubyOutlinePage customPage = ( ICustomRubyOutlinePage ) configElement . createExecutableExtension ( "" ) ; list . add ( customPage ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } } return list ; } protected void doSetInput ( IEditorInput input ) throws CoreException { IPath path = null ; if ( externalFileOpenedInEclipse32 ( input ) ) { try { Method method = input . getClass ( ) . getDeclaredMethod ( "" , new Class [ ] ) ; if ( method != null ) { path = ( IPath ) method . invoke ( input , new Object [ ] ) ; } } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } else if ( externalFileOpenedInEclipse33 ( input ) ) { try { Method method = input . getClass ( ) . getDeclaredMethod ( "" , new Class [ ] ) ; if ( method != null ) { URI uri = ( URI ) method . invoke ( input , new Object [ ] ) ; if ( uri != null && uri . getScheme ( ) . equals ( "" ) ) { path = new Path ( uri . getPath ( ) ) ; } } } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } if ( path != null && ( externalFileOpenedInEclipse32 ( input ) || externalFileOpenedInEclipse33 ( input ) ) ) { IProject [ ] projects = RubyCore . getRubyProjects ( ) ; if ( projects != null && projects . length > ) { IRubyProject proj = RubyCore . create ( projects [ ] ) ; ISourceFolderRoot root = proj . getSourceFolderRoot ( path . removeLastSegments ( ) . toPortableString ( ) ) ; ISourceFolder folder = root . getSourceFolder ( "" ) ; IRubyScript script = folder . getRubyScript ( path . lastSegment ( ) ) ; input = new RubyScriptEditorInput ( ( ExternalRubyScript ) script ) ; } } if ( input instanceof IRubyScriptEditorInput ) { setDocumentProvider ( RubyPlugin . getDefault ( ) . getExternalDocumentProvider ( ) ) ; } else { setDocumentProvider ( RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) ) ; } super . doSetInput ( input ) ; setOutlinePageInput ( fOutlinePage , input ) ; } private boolean externalFileOpenedInEclipse33 ( IEditorInput input ) { return input . getClass ( ) . getName ( ) . equals ( "" ) ; } private boolean externalFileOpenedInEclipse32 ( IEditorInput input ) { return input . getClass ( ) . getName ( ) . equals ( "" ) ; } protected void setOutlinePageInput ( ICustomRubyOutlinePage page , IEditorInput input ) { if ( page == null ) return ; IRubyElement re = getInputRubyElement ( ) ; if ( re != null && re . exists ( ) ) page . setInput ( re ) ; else page . setInput ( null ) ; } protected void handlePreferenceStoreChanged ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_TAB_WIDTH . equals ( property ) ) { return ; } try { boolean newBooleanValue = false ; Object newValue = event . getNewValue ( ) ; if ( newValue != null ) newBooleanValue = Boolean . valueOf ( newValue . toString ( ) ) . booleanValue ( ) ; if ( PreferenceConstants . EDITOR_MARK_OCCURRENCES . equals ( property ) ) { if ( newBooleanValue != fMarkOccurrenceAnnotations ) { fMarkOccurrenceAnnotations = newBooleanValue ; if ( ! fMarkOccurrenceAnnotations ) uninstallOccurrencesFinder ( ) ; else installOccurrencesFinder ( true ) ; } return ; } if ( PreferenceConstants . EDITOR_MARK_TYPE_OCCURRENCES . equals ( property ) ) { fMarkTypeOccurrences = newBooleanValue ; return ; } if ( PreferenceConstants . EDITOR_MARK_METHOD_OCCURRENCES . equals ( property ) ) { fMarkMethodOccurrences = newBooleanValue ; return ; } if ( PreferenceConstants . EDITOR_MARK_CONSTANT_OCCURRENCES . equals ( property ) ) { fMarkConstantOccurrences = newBooleanValue ; return ; } if ( PreferenceConstants . EDITOR_MARK_FIELD_OCCURRENCES . equals ( property ) ) { fMarkFieldOccurrences = newBooleanValue ; return ; } if ( PreferenceConstants . EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES . equals ( property ) ) { fMarkLocalVariableOccurrences = newBooleanValue ; return ; } if ( PreferenceConstants . EDITOR_MARK_METHOD_EXIT_POINTS . equals ( property ) ) { fMarkMethodExitPoints = newBooleanValue ; return ; } if ( PreferenceConstants . EDITOR_STICKY_OCCURRENCES . equals ( property ) ) { fStickyOccurrenceAnnotations = newBooleanValue ; return ; } AdaptedSourceViewer sourceViewer = ( AdaptedSourceViewer ) getSourceViewer ( ) ; if ( sourceViewer == null ) return ; ( ( RubySourceViewerConfiguration ) getSourceViewerConfiguration ( ) ) . handlePropertyChangeEvent ( event ) ; IContentAssistant c = sourceViewer . getContentAssistant ( ) ; if ( c instanceof ContentAssistant ) ContentAssistPreference . changeConfiguration ( ( ContentAssistant ) c , getPreferenceStore ( ) , event ) ; } finally { super . handlePreferenceStoreChanged ( event ) ; } if ( AbstractDecoratedTextEditorPreferenceConstants . SHOW_RANGE_INDICATOR . equals ( property ) ) { Object newValue = event . getNewValue ( ) ; ISourceViewer viewer = getSourceViewer ( ) ; if ( newValue != null && viewer != null ) { if ( Boolean . valueOf ( newValue . toString ( ) ) . booleanValue ( ) ) { Point selection = viewer . getSelectedRange ( ) ; adjustHighlightRange ( selection . x , selection . y ) ; } } } } protected IRubyElement getInputRubyElement ( ) { IEditorInput editorInput = getEditorInput ( ) ; if ( editorInput == null ) return null ; return RubyUI . getEditorInputRubyElement ( getEditorInput ( ) ) ; } protected void handleOutlinePageSelection ( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) event . getSelection ( ) ; Iterator iter = ( ( IStructuredSelection ) selection ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Object o = iter . next ( ) ; if ( o instanceof ISourceReference ) { reference = ( ISourceReference ) o ; break ; } } if ( ! isActivePart ( ) && RubyPlugin . getActivePage ( ) != null ) RubyPlugin . getActivePage ( ) . bringToTop ( this ) ; setSelection ( reference , true ) ; } protected boolean isActivePart ( ) { IWorkbenchPart part = getActivePart ( ) ; return part != null && part . equals ( this ) ; } private IWorkbenchPart getActivePart ( ) { IWorkbenchWindow window = getSite ( ) . getWorkbenchWindow ( ) ; IPartService service = window . getPartService ( ) ; IWorkbenchPart part = service . getActivePart ( ) ; return part ; } public void setSelection ( IRubyElement element ) { if ( element == null || element instanceof IRubyScript ) { return ; } IRubyElement corresponding = getCorrespondingElement ( element ) ; if ( corresponding instanceof ISourceReference ) { ISourceReference reference = ( ISourceReference ) corresponding ; setSelection ( reference , true ) ; if ( fOutlinePage != null ) { fOutlineSelectionChangedListener . uninstall ( fOutlinePage ) ; fOutlinePage . select ( reference ) ; fOutlineSelectionChangedListener . install ( fOutlinePage ) ; } } } protected IRubyElement getCorrespondingElement ( IRubyElement element ) { return element ; } protected void synchronizeOutlinePage ( ISourceReference element , boolean checkIfOutlinePageActive ) { if ( fOutlinePage != null && element != null && ! ( checkIfOutlinePageActive && isRubyOutlinePageActive ( ) ) ) { fOutlineSelectionChangedListener . uninstall ( fOutlinePage ) ; fOutlinePage . select ( element ) ; fOutlineSelectionChangedListener . install ( fOutlinePage ) ; } } private boolean isRubyOutlinePageActive ( ) { IWorkbenchPart part = getActivePart ( ) ; return part instanceof ContentOutline && ( ( ContentOutline ) part ) . getCurrentPage ( ) == fOutlinePage ; } protected void setSelection ( ISourceReference reference , boolean moveCursor ) { if ( getSelectionProvider ( ) == null ) return ; ISelection selection = getSelectionProvider ( ) . getSelection ( ) ; if ( selection instanceof TextSelection ) { TextSelection textSelection = ( TextSelection ) selection ; if ( moveCursor && ( textSelection . getOffset ( ) != || textSelection . getLength ( ) != ) ) markInNavigationHistory ( ) ; } if ( reference != null ) { StyledText textWidget = null ; ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer != null ) textWidget = sourceViewer . getTextWidget ( ) ; if ( textWidget == null ) return ; try { ISourceRange range = null ; range = reference . getSourceRange ( ) ; if ( range == null ) return ; int offset = range . getOffset ( ) ; int length = range . getLength ( ) ; if ( offset < || length < ) return ; setHighlightRange ( offset , length , moveCursor ) ; if ( ! moveCursor ) return ; offset = - ; length = - ; if ( reference instanceof IMember ) { range = ( ( IMember ) reference ) . getNameRange ( ) ; if ( range != null ) { offset = range . getOffset ( ) ; length = range . getLength ( ) ; } } else if ( reference instanceof IImportDeclaration ) { String name = ( ( IImportDeclaration ) reference ) . getElementName ( ) ; if ( name != null && name . length ( ) > ) { String content = reference . getSource ( ) ; if ( content != null ) { offset = range . getOffset ( ) + content . indexOf ( name ) ; length = name . length ( ) ; } } } if ( offset > - && length > ) { try { textWidget . setRedraw ( false ) ; sourceViewer . revealRange ( offset , length ) ; sourceViewer . setSelectedRange ( offset , length ) ; } finally { textWidget . setRedraw ( true ) ; } markInNavigationHistory ( ) ; } } catch ( RubyModelException x ) { } catch ( IllegalArgumentException x ) { } } else if ( moveCursor ) { resetHighlightRange ( ) ; markInNavigationHistory ( ) ; } } protected boolean affectsTextPresentation ( PropertyChangeEvent event ) { return ( ( RubySourceViewerConfiguration ) getSourceViewerConfiguration ( ) ) . affectsTextPresentation ( event ) || super . affectsTextPresentation ( event ) ; } protected void doSelectionChanged ( SelectionChangedEvent event ) { ISourceReference reference = null ; ISelection selection = event . getSelection ( ) ; Iterator iter = ( ( IStructuredSelection ) selection ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Object o = iter . next ( ) ; if ( o instanceof ISourceReference ) { reference = ( ISourceReference ) o ; break ; } } if ( ! isActivePart ( ) && RubyPlugin . getActivePage ( ) != null ) RubyPlugin . getActivePage ( ) . bringToTop ( this ) ; setSelection ( reference , ! isActivePart ( ) ) ; } class OutlineSelectionChangedListener extends AbstractSelectionChangedListener { public void selectionChanged ( SelectionChangedEvent event ) { boolean isLinkingEnabled = PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE ) ; if ( isLinkingEnabled ) { doSelectionChanged ( event ) ; } } } protected ISourceReference computeHighlightRangeSourceReference ( ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer == null ) return null ; StyledText styledText = sourceViewer . getTextWidget ( ) ; if ( styledText == null ) return null ; int caret = ; if ( sourceViewer instanceof ITextViewerExtension5 ) { ITextViewerExtension5 extension = ( ITextViewerExtension5 ) sourceViewer ; caret = extension . widgetOffset2ModelOffset ( styledText . getCaretOffset ( ) ) ; } else { int offset = sourceViewer . getVisibleRegion ( ) . getOffset ( ) ; caret = offset + styledText . getCaretOffset ( ) ; } IRubyElement element = getElementAt ( caret , false ) ; if ( ! ( element instanceof ISourceReference ) ) return null ; if ( element . getElementType ( ) == IRubyElement . IMPORT_DECLARATION ) { IImportDeclaration declaration = ( IImportDeclaration ) element ; IImportContainer container = ( IImportContainer ) declaration . getParent ( ) ; ISourceRange srcRange = null ; try { srcRange = container . getSourceRange ( ) ; } catch ( RubyModelException e ) { } if ( srcRange != null && srcRange . getOffset ( ) == caret ) return container ; } return ( ISourceReference ) element ; } protected abstract IRubyElement getElementAt ( int caret , boolean b ) ; protected abstract IRubyElement getElementAt ( int offset ) ; public final ISourceViewer getViewer ( ) { return getSourceViewer ( ) ; } private static class EclipsePreferencesAdapter implements IPreferenceStore { private class PreferenceChangeListener implements IEclipsePreferences . IPreferenceChangeListener { public void preferenceChange ( final IEclipsePreferences . PreferenceChangeEvent event ) { if ( Display . getCurrent ( ) == null ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { firePropertyChangeEvent ( event . getKey ( ) , event . getOldValue ( ) , event . getNewValue ( ) ) ; } } ) ; } else { firePropertyChangeEvent ( event . getKey ( ) , event . getOldValue ( ) , event . getNewValue ( ) ) ; } } } private ListenerList fListeners = new ListenerList ( ) ; private IEclipsePreferences . IPreferenceChangeListener fListener = new PreferenceChangeListener ( ) ; private final IScopeContext fContext ; private final String fQualifier ; public EclipsePreferencesAdapter ( IScopeContext context , String qualifier ) { fContext = context ; fQualifier = qualifier ; } private IEclipsePreferences getNode ( ) { return fContext . getNode ( fQualifier ) ; } public void addPropertyChangeListener ( IPropertyChangeListener listener ) { if ( fListeners . size ( ) == ) getNode ( ) . addPreferenceChangeListener ( fListener ) ; fListeners . add ( listener ) ; } public void removePropertyChangeListener ( IPropertyChangeListener listener ) { fListeners . remove ( listener ) ; if ( fListeners . size ( ) == ) { getNode ( ) . removePreferenceChangeListener ( fListener ) ; } } public boolean contains ( String name ) { return getNode ( ) . get ( name , null ) != null ; } public void firePropertyChangeEvent ( String name , Object oldValue , Object newValue ) { PropertyChangeEvent event = new PropertyChangeEvent ( this , name , oldValue , newValue ) ; Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) ( ( IPropertyChangeListener ) listeners [ i ] ) . propertyChange ( event ) ; } public boolean getBoolean ( String name ) { return getNode ( ) . getBoolean ( name , BOOLEAN_DEFAULT_DEFAULT ) ; } public boolean getDefaultBoolean ( String name ) { return BOOLEAN_DEFAULT_DEFAULT ; } public double getDefaultDouble ( String name ) { return DOUBLE_DEFAULT_DEFAULT ; } public float getDefaultFloat ( String name ) { return FLOAT_DEFAULT_DEFAULT ; } public int getDefaultInt ( String name ) { return INT_DEFAULT_DEFAULT ; } public long getDefaultLong ( String name ) { return LONG_DEFAULT_DEFAULT ; } public String getDefaultString ( String name ) { return STRING_DEFAULT_DEFAULT ; } public double getDouble ( String name ) { return getNode ( ) . getDouble ( name , DOUBLE_DEFAULT_DEFAULT ) ; } public float getFloat ( String name ) { return getNode ( ) . getFloat ( name , FLOAT_DEFAULT_DEFAULT ) ; } public int getInt ( String name ) { return getNode ( ) . getInt ( name , INT_DEFAULT_DEFAULT ) ; } public long getLong ( String name ) { return getNode ( ) . getLong ( name , LONG_DEFAULT_DEFAULT ) ; } public String getString ( String name ) { return getNode ( ) . get ( name , STRING_DEFAULT_DEFAULT ) ; } public boolean isDefault ( String name ) { return false ; } public boolean needsSaving ( ) { try { return getNode ( ) . keys ( ) . length > ; } catch ( BackingStoreException e ) { } return true ; } public void putValue ( String name , String value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , double value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , float value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , int value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , long value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , String defaultObject ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , boolean value ) { throw new UnsupportedOperationException ( ) ; } public void setToDefault ( String name ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , double value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , float value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , int value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , long value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , String value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , boolean value ) { throw new UnsupportedOperationException ( ) ; } } class AdaptedSourceViewer extends RubySourceViewer { private List fTextConverters ; private boolean fIgnoreTextConverters = false ; public AdaptedSourceViewer ( Composite parent , IVerticalRuler verticalRuler , IOverviewRuler overviewRuler , boolean showAnnotationsOverview , int styles , IPreferenceStore store ) { super ( parent , verticalRuler , overviewRuler , showAnnotationsOverview , styles , store ) ; } public IContentAssistant getContentAssistant ( ) { return fContentAssistant ; } public void addTextConverter ( ITextConverter textConverter ) { if ( fTextConverters == null ) { fTextConverters = new ArrayList ( ) ; fTextConverters . add ( textConverter ) ; } else if ( ! fTextConverters . contains ( textConverter ) ) fTextConverters . add ( textConverter ) ; } public void removeTextConverter ( ITextConverter textConverter ) { if ( fTextConverters != null ) { fTextConverters . remove ( textConverter ) ; if ( fTextConverters . size ( ) == ) fTextConverters = null ; } } protected void customizeDocumentCommand ( DocumentCommand command ) { super . customizeDocumentCommand ( command ) ; if ( ! fIgnoreTextConverters && fTextConverters != null ) { for ( Iterator e = fTextConverters . iterator ( ) ; e . hasNext ( ) ; ) ( ( ITextConverter ) e . next ( ) ) . customizeDocumentCommand ( getDocument ( ) , command ) ; } } public void updateIndentationPrefixes ( ) { SourceViewerConfiguration configuration = getSourceViewerConfiguration ( ) ; String [ ] types = configuration . getConfiguredContentTypes ( this ) ; for ( int i = ; i < types . length ; i ++ ) { String [ ] prefixes = configuration . getIndentPrefixes ( this , types [ i ] ) ; if ( prefixes != null && prefixes . length > ) setIndentPrefixes ( prefixes , types [ i ] ) ; } } public boolean requestWidgetToken ( IWidgetTokenKeeper requester ) { if ( PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . isContextHelpDisplayed ( ) ) return false ; return super . requestWidgetToken ( requester ) ; } public boolean requestWidgetToken ( IWidgetTokenKeeper requester , int priority ) { if ( PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . isContextHelpDisplayed ( ) ) return false ; return super . requestWidgetToken ( requester , priority ) ; } public void doOperation ( int operation ) { if ( getTextWidget ( ) == null ) return ; switch ( operation ) { case CONTENTASSIST_PROPOSALS : long time = CODE_ASSIST_DEBUG ? System . currentTimeMillis ( ) : ; String msg = fContentAssistant . showPossibleCompletions ( ) ; if ( CODE_ASSIST_DEBUG ) { long delta = System . currentTimeMillis ( ) - time ; System . err . println ( "" + delta ) ; } setStatusLineErrorMessage ( msg ) ; return ; case QUICK_ASSIST : msg = fQuickAssistAssistant . showPossibleQuickAssists ( ) ; setStatusLineErrorMessage ( msg ) ; return ; case UNDO : fIgnoreTextConverters = true ; super . doOperation ( operation ) ; fIgnoreTextConverters = false ; return ; case REDO : fIgnoreTextConverters = true ; super . doOperation ( operation ) ; fIgnoreTextConverters = false ; return ; } super . doOperation ( operation ) ; } } private class ActivationListener implements IWindowListener { public void windowActivated ( IWorkbenchWindow window ) { if ( window == getEditorSite ( ) . getWorkbenchWindow ( ) && fMarkOccurrenceAnnotations && isActivePart ( ) ) { fForcedMarkOccurrencesSelection = getSelectionProvider ( ) . getSelection ( ) ; updateOccurrenceAnnotations ( ( ITextSelection ) fForcedMarkOccurrencesSelection , RubyPlugin . getDefault ( ) . getASTProvider ( ) . getAST ( getInputRubyElement ( ) , ASTProvider . WAIT_NO , getProgressMonitor ( ) ) ) ; } } public void windowDeactivated ( IWorkbenchWindow window ) { if ( window == getEditorSite ( ) . getWorkbenchWindow ( ) && fMarkOccurrenceAnnotations && isActivePart ( ) ) removeOccurrenceAnnotations ( ) ; } public void windowClosed ( IWorkbenchWindow window ) { } public void windowOpened ( IWorkbenchWindow window ) { } } class OccurrencesFinderJobCanceler implements IDocumentListener , ITextInputListener { public void install ( ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer == null ) return ; StyledText text = sourceViewer . getTextWidget ( ) ; if ( text == null || text . isDisposed ( ) ) return ; sourceViewer . addTextInputListener ( this ) ; IDocument document = sourceViewer . getDocument ( ) ; if ( document != null ) document . addDocumentListener ( this ) ; } public void uninstall ( ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer != null ) sourceViewer . removeTextInputListener ( this ) ; IDocumentProvider documentProvider = getDocumentProvider ( ) ; if ( documentProvider != null ) { IDocument document = documentProvider . getDocument ( getEditorInput ( ) ) ; if ( document != null ) document . removeDocumentListener ( this ) ; } } public void documentAboutToBeChanged ( DocumentEvent event ) { if ( fOccurrencesFinderJob != null ) fOccurrencesFinderJob . doCancel ( ) ; } public void documentChanged ( DocumentEvent event ) { } public void inputDocumentAboutToBeChanged ( IDocument oldInput , IDocument newInput ) { if ( oldInput == null ) return ; oldInput . removeDocumentListener ( this ) ; } public void inputDocumentChanged ( IDocument oldInput , IDocument newInput ) { if ( newInput == null ) return ; newInput . addDocumentListener ( this ) ; } } class OccurrencesFinderJob extends Job { private IDocument fDocument ; private ISelection fSelection ; private ISelectionValidator fPostSelectionValidator ; private boolean fCanceled = false ; private IProgressMonitor fProgressMonitor ; private Position [ ] fPositions ; public OccurrencesFinderJob ( IDocument document , Position [ ] positions , ISelection selection ) { super ( "" ) ; fDocument = document ; fSelection = selection ; fPositions = positions ; if ( getSelectionProvider ( ) instanceof ISelectionValidator ) fPostSelectionValidator = ( ISelectionValidator ) getSelectionProvider ( ) ; } void doCancel ( ) { fCanceled = true ; cancel ( ) ; } private boolean isCanceled ( ) { return fCanceled || fProgressMonitor . isCanceled ( ) || fPostSelectionValidator != null && ! ( fPostSelectionValidator . isValid ( fSelection ) || fForcedMarkOccurrencesSelection == fSelection ) || LinkedModeModel . hasInstalledModel ( fDocument ) ; } public IStatus run ( IProgressMonitor progressMonitor ) { fProgressMonitor = progressMonitor ; if ( isCanceled ( ) ) return Status . CANCEL_STATUS ; ITextViewer textViewer = getViewer ( ) ; if ( textViewer == null ) return Status . CANCEL_STATUS ; IDocument document = textViewer . getDocument ( ) ; if ( document == null ) return Status . CANCEL_STATUS ; IDocumentProvider documentProvider = getDocumentProvider ( ) ; if ( documentProvider == null ) return Status . CANCEL_STATUS ; IAnnotationModel annotationModel = documentProvider . getAnnotationModel ( getEditorInput ( ) ) ; if ( annotationModel == null ) return Status . CANCEL_STATUS ; int length = fPositions . length ; Map annotationMap = new HashMap ( length ) ; for ( int i = ; i < length ; i ++ ) { if ( isCanceled ( ) ) return Status . CANCEL_STATUS ; String message ; Position position = fPositions [ i ] ; try { message = document . get ( position . offset , position . length ) ; } catch ( BadLocationException ex ) { continue ; } annotationMap . put ( new Annotation ( "" , false , message ) , position ) ; } if ( isCanceled ( ) ) return Status . CANCEL_STATUS ; synchronized ( getLockObject ( annotationModel ) ) { if ( annotationModel instanceof IAnnotationModelExtension ) { ( ( IAnnotationModelExtension ) annotationModel ) . replaceAnnotations ( fOccurrenceAnnotations , annotationMap ) ; } else { removeOccurrenceAnnotations ( ) ; Iterator iter = annotationMap . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry mapEntry = ( Map . Entry ) iter . next ( ) ; annotationModel . addAnnotation ( ( Annotation ) mapEntry . getKey ( ) , ( Position ) mapEntry . getValue ( ) ) ; } } fOccurrenceAnnotations = ( Annotation [ ] ) annotationMap . keySet ( ) . toArray ( new Annotation [ annotationMap . keySet ( ) . size ( ) ] ) ; } return Status . OK_STATUS ; } } protected void updateOccurrenceAnnotations ( ITextSelection selection , RootNode ast ) { if ( fOccurrencesFinderJob != null ) fOccurrencesFinderJob . cancel ( ) ; if ( ! fMarkOccurrenceAnnotations ) return ; if ( selection == null ) return ; IDocument document = getDocumentProvider ( ) . getDocument ( getEditorInput ( ) ) ; if ( document == null ) return ; if ( document instanceof IDocumentExtension4 ) { int offset = selection . getOffset ( ) ; long currentModificationStamp = ( ( IDocumentExtension4 ) document ) . getModificationStamp ( ) ; if ( fMarkOccurrenceTargetRegion != null && currentModificationStamp == fMarkOccurrenceModificationStamp ) { if ( fMarkOccurrenceTargetRegion . getOffset ( ) <= offset && offset <= fMarkOccurrenceTargetRegion . getOffset ( ) + fMarkOccurrenceTargetRegion . getLength ( ) ) return ; } fMarkOccurrenceTargetRegion = RubyWordFinder . findWord ( document , offset ) ; fMarkOccurrenceModificationStamp = currentModificationStamp ; } String source = document . get ( ) ; OccurrencesFinder finder = new OccurrencesFinder ( ) ; finder . setFMarkConstantOccurrences ( fMarkConstantOccurrences ) ; finder . setFMarkFieldOccurrences ( fMarkFieldOccurrences ) ; finder . setFMarkLocalVariableOccurrences ( fMarkLocalVariableOccurrences ) ; finder . setFMarkMethodExitPoints ( fMarkMethodExitPoints ) ; finder . setFMarkMethodOccurrences ( fMarkMethodOccurrences ) ; finder . setFMarkOccurrenceAnnotations ( fMarkOccurrenceAnnotations ) ; finder . setFMarkTypeOccurrences ( fMarkTypeOccurrences ) ; finder . setFStickyOccurrenceAnnotations ( fStickyOccurrenceAnnotations ) ; finder . initialize ( ast , selection . getOffset ( ) , selection . getLength ( ) ) ; List < Position > matches = finder . perform ( ) ; if ( matches == null || matches . isEmpty ( ) ) { if ( ! fStickyOccurrenceAnnotations ) { removeOccurrenceAnnotations ( ) ; } return ; } Position [ ] positions = matches . toArray ( new Position [ matches . size ( ) ] ) ; fOccurrencesFinderJob = new OccurrencesFinderJob ( document , positions , selection ) ; fOccurrencesFinderJob . run ( new NullProgressMonitor ( ) ) ; } protected void setMarkOccurrencePreferences ( IOccurrencesFinder occurrencesFinder ) { } protected void installOccurrencesFinder ( boolean forceUpdate ) { fMarkOccurrenceAnnotations = true ; fPostSelectionListenerWithAST = new ISelectionListenerWithAST ( ) { public void selectionChanged ( IEditorPart part , ITextSelection selection , RootNode astRoot ) { updateOccurrenceAnnotations ( selection , astRoot ) ; } } ; SelectionListenerWithASTManager . getDefault ( ) . addListener ( this , fPostSelectionListenerWithAST ) ; if ( forceUpdate && getSelectionProvider ( ) != null ) { fForcedMarkOccurrencesSelection = getSelectionProvider ( ) . getSelection ( ) ; updateOccurrenceAnnotations ( ( ITextSelection ) fForcedMarkOccurrencesSelection , RubyPlugin . getDefault ( ) . getASTProvider ( ) . getAST ( getInputRubyElement ( ) , ASTProvider . WAIT_NO , getProgressMonitor ( ) ) ) ; } if ( fOccurrencesFinderJobCanceler == null ) { fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler ( ) ; fOccurrencesFinderJobCanceler . install ( ) ; } } protected void uninstallOccurrencesFinder ( ) { fMarkOccurrenceAnnotations = false ; if ( fOccurrencesFinderJob != null ) { fOccurrencesFinderJob . cancel ( ) ; fOccurrencesFinderJob = null ; } if ( fOccurrencesFinderJobCanceler != null ) { fOccurrencesFinderJobCanceler . uninstall ( ) ; fOccurrencesFinderJobCanceler = null ; } if ( fPostSelectionListenerWithAST != null ) { SelectionListenerWithASTManager . getDefault ( ) . removeListener ( this , fPostSelectionListenerWithAST ) ; fPostSelectionListenerWithAST = null ; } removeOccurrenceAnnotations ( ) ; } protected boolean isMarkingOccurrences ( ) { return fMarkOccurrenceAnnotations ; } void removeOccurrenceAnnotations ( ) { fMarkOccurrenceModificationStamp = IDocumentExtension4 . UNKNOWN_MODIFICATION_STAMP ; fMarkOccurrenceTargetRegion = null ; IDocumentProvider documentProvider = getDocumentProvider ( ) ; if ( documentProvider == null ) return ; IAnnotationModel annotationModel = documentProvider . getAnnotationModel ( getEditorInput ( ) ) ; if ( annotationModel == null || fOccurrenceAnnotations == null ) return ; synchronized ( getLockObject ( annotationModel ) ) { if ( annotationModel instanceof IAnnotationModelExtension ) { ( ( IAnnotationModelExtension ) annotationModel ) . replaceAnnotations ( fOccurrenceAnnotations , null ) ; } else { for ( int i = , length = fOccurrenceAnnotations . length ; i < length ; i ++ ) annotationModel . removeAnnotation ( fOccurrenceAnnotations [ i ] ) ; } fOccurrenceAnnotations = null ; } } private Object getLockObject ( IAnnotationModel annotationModel ) { if ( annotationModel instanceof ISynchronizable ) { Object lock = ( ( ISynchronizable ) annotationModel ) . getLockObject ( ) ; if ( lock != null ) return lock ; } return annotationModel ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . core . filebuffers . IDocumentSetupParticipant ; import org . eclipse . jface . text . IDocument ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class RubyDocumentSetupParticipant implements IDocumentSetupParticipant { public RubyDocumentSetupParticipant ( ) { } public void setup ( IDocument document ) { RubyTextTools tools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; tools . setupRubyDocumentPartitioner ( document , IRubyPartitions . RUBY_PARTITIONING ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ILineTracker ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . viewers . ISelection ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor . ITextConverter ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; class StringSubstitutionConverter implements ITextConverter { private ILineTracker fLineTracker ; private RubyEditor editor ; public StringSubstitutionConverter ( RubyEditor rubyEditor ) { this . editor = rubyEditor ; } public void setLineTracker ( ILineTracker lineTracker ) { fLineTracker = lineTracker ; } public void customizeDocumentCommand ( IDocument document , DocumentCommand command ) { String text = command . text ; if ( text == null ) return ; String textSelected = "" ; ISelection selection = editor . getSelectionProvider ( ) . getSelection ( ) ; if ( selection instanceof ITextSelection ) { ITextSelection textSelect = ( ITextSelection ) selection ; textSelected = textSelect . getText ( ) ; } if ( textSelected == null || textSelected . trim ( ) . length ( ) == ) return ; if ( text . equals ( "" ) ) { doStringSubstitution ( document , command , textSelected ) ; return ; } else if ( text . equals ( "" ) || text . equals ( "" ) || text . equals ( "" ) ) { doStringWrapping ( document , command , textSelected ) ; return ; } } private void doStringSubstitution ( IDocument document , DocumentCommand command , String textSelected ) { fLineTracker . set ( command . text ) ; try { ITypedRegion partition = TextUtilities . getPartition ( document , IRubyPartitions . RUBY_PARTITIONING , command . offset , true ) ; if ( ! partition . getType ( ) . equals ( IRubyPartitions . RUBY_STRING ) && ! partition . getType ( ) . equals ( IRubyPartitions . RUBY_COMMAND ) ) return ; command . text = "" + textSelected + "" ; } catch ( BadLocationException x ) { } } private void doStringWrapping ( IDocument document , DocumentCommand command , String textSelected ) { String character = command . text ; fLineTracker . set ( command . text ) ; try { ITypedRegion partition = TextUtilities . getPartition ( document , IRubyPartitions . RUBY_PARTITIONING , command . offset , true ) ; if ( partition . getType ( ) . equals ( IRubyPartitions . RUBY_STRING ) || partition . getType ( ) . equals ( IRubyPartitions . RUBY_COMMAND ) ) return ; command . text = character + textSelected + character ; } catch ( BadLocationException x ) { } } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . ISynchronizable ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . IAnnotationModelExtension ; import org . eclipse . ui . PartInitException ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . OpenActionUtil ; import org . rubypeople . rdt . internal . ui . text . ruby . IRubyReconcilingListener ; class OverrideIndicatorManager implements IRubyReconcilingListener { class OverrideIndicator extends Annotation { private boolean fIsOverwriteIndicator ; private String fHandleIdentifier ; OverrideIndicator ( boolean isOverwriteIndicator , String text , String handleIdentifier ) { super ( ANNOTATION_TYPE , false , text ) ; fIsOverwriteIndicator = isOverwriteIndicator ; fHandleIdentifier = handleIdentifier ; } public boolean isOverwriteIndicator ( ) { return fIsOverwriteIndicator ; } public void open ( ) { try { OpenActionUtil . open ( RubyCore . create ( fHandleIdentifier ) , true ) ; } catch ( PartInitException e ) { RubyPlugin . log ( e ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } } static final String ANNOTATION_TYPE = "" ; private IAnnotationModel fAnnotationModel ; private Object fAnnotationModelLockObject ; private Annotation [ ] fOverrideAnnotations ; public OverrideIndicatorManager ( IAnnotationModel annotationModel , IRubyElement rubyElement , Node ast ) { Assert . isNotNull ( annotationModel ) ; Assert . isNotNull ( rubyElement ) ; fAnnotationModel = annotationModel ; fAnnotationModelLockObject = getLockObject ( fAnnotationModel ) ; if ( ast != null ) updateAnnotations ( ( IRubyScript ) rubyElement , new NullProgressMonitor ( ) ) ; } private Object getLockObject ( IAnnotationModel annotationModel ) { if ( annotationModel instanceof ISynchronizable ) { Object lock = ( ( ISynchronizable ) annotationModel ) . getLockObject ( ) ; if ( lock != null ) return lock ; } return annotationModel ; } protected void updateAnnotations ( IRubyScript ast , IProgressMonitor progressMonitor ) { if ( ast == null || progressMonitor . isCanceled ( ) ) return ; final Map annotationMap = new HashMap ( ) ; try { IType [ ] types = ast . getAllTypes ( ) ; for ( int i = ; i < types . length ; i ++ ) { IMethod [ ] methods = types [ i ] . getMethods ( ) ; List < IMethod > filtered = filterToPublic ( methods ) ; if ( filtered . isEmpty ( ) ) continue ; ITypeHierarchy hierarchy = types [ i ] . newSupertypeHierarchy ( new NullProgressMonitor ( ) ) ; if ( hierarchy != null ) { IType [ ] supers = hierarchy . getAllTypes ( ) ; for ( IMethod method : filtered ) { for ( int k = ; k < supers . length ; k ++ ) { if ( supers [ k ] . equals ( types [ i ] ) ) continue ; IMethod [ ] superMethods = supers [ k ] . getMethods ( ) ; for ( int l = ; l < superMethods . length ; l ++ ) { IMethod overridenMethod = superMethods [ l ] ; if ( ! overridenMethod . getElementName ( ) . equals ( method . getElementName ( ) ) ) continue ; Position position = new Position ( method . getSourceRange ( ) . getOffset ( ) , method . getSourceRange ( ) . getLength ( ) ) ; String qualifiedMethodName = overridenMethod . getDeclaringType ( ) . getFullyQualifiedName ( ) + "" + overridenMethod . getElementName ( ) ; String text = Messages . format ( RubyEditorMessages . OverrideIndicatorManager_overrides , qualifiedMethodName ) ; annotationMap . put ( new OverrideIndicator ( false , text , overridenMethod . getHandleIdentifier ( ) ) , position ) ; } } } } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } if ( progressMonitor . isCanceled ( ) ) return ; synchronized ( fAnnotationModelLockObject ) { if ( fAnnotationModel instanceof IAnnotationModelExtension ) { ( ( IAnnotationModelExtension ) fAnnotationModel ) . replaceAnnotations ( fOverrideAnnotations , annotationMap ) ; } else { removeAnnotations ( ) ; Iterator iter = annotationMap . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry mapEntry = ( Map . Entry ) iter . next ( ) ; fAnnotationModel . addAnnotation ( ( Annotation ) mapEntry . getKey ( ) , ( Position ) mapEntry . getValue ( ) ) ; } } fOverrideAnnotations = ( Annotation [ ] ) annotationMap . keySet ( ) . toArray ( new Annotation [ annotationMap . keySet ( ) . size ( ) ] ) ; } } private List < IMethod > filterToPublic ( IMethod [ ] methods ) { List < IMethod > filtered = new ArrayList < IMethod > ( ) ; if ( methods == null || methods . length == ) return filtered ; for ( int i = ; i < methods . length ; i ++ ) { try { if ( ! methods [ i ] . isPublic ( ) ) continue ; filtered . add ( methods [ i ] ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } return filtered ; } void removeAnnotations ( ) { if ( fOverrideAnnotations == null ) return ; synchronized ( fAnnotationModelLockObject ) { if ( fAnnotationModel instanceof IAnnotationModelExtension ) { ( ( IAnnotationModelExtension ) fAnnotationModel ) . replaceAnnotations ( fOverrideAnnotations , null ) ; } else { for ( int i = , length = fOverrideAnnotations . length ; i < length ; i ++ ) fAnnotationModel . removeAnnotation ( fOverrideAnnotations [ i ] ) ; } fOverrideAnnotations = null ; } } public void aboutToBeReconciled ( ) { } public void reconciled ( IRubyScript script , RootNode ast , boolean forced , IProgressMonitor progressMonitor ) { updateAnnotations ( script , progressMonitor ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . io . File ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . ui . IElementFactory ; import org . eclipse . ui . IMemento ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyExternalEditorFactory implements IElementFactory { public final static String MEMENTO_ABSOLUTE_PATH_KEY = "" ; public static final String FACTORY_ID = RubyPlugin . PLUGIN_ID + "" ; public IAdaptable createElement ( IMemento memento ) { String absolutePath = memento . getString ( MEMENTO_ABSOLUTE_PATH_KEY ) ; if ( absolutePath == null ) { return null ; } return new ExternalRubyFileEditorInput ( new File ( absolutePath ) ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . swt . graphics . Image ; import org . eclipse . ui . texteditor . IAnnotationImageProvider ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class OverrideIndicatorImageProvider implements IAnnotationImageProvider { private static final String OVERRIDE_IMG_DESC_ID = "" ; private static final String OVERWRITE_IMG_DESC_ID = "" ; public Image getManagedImage ( Annotation annotation ) { return null ; } public String getImageDescriptorId ( Annotation annotation ) { if ( ! isImageProviderFor ( annotation ) ) return null ; if ( isOverwriting ( annotation ) ) return OVERWRITE_IMG_DESC_ID ; else return OVERRIDE_IMG_DESC_ID ; } public ImageDescriptor getImageDescriptor ( String imageDescritporId ) { if ( OVERWRITE_IMG_DESC_ID . equals ( imageDescritporId ) ) return RubyPluginImages . DESC_OBJ_IMPLEMENTS ; else if ( OVERRIDE_IMG_DESC_ID . equals ( imageDescritporId ) ) return RubyPluginImages . DESC_OBJ_OVERRIDES ; return null ; } private boolean isImageProviderFor ( Annotation annotation ) { return annotation != null && OverrideIndicatorManager . ANNOTATION_TYPE . equals ( annotation . getType ( ) ) ; } private boolean isOverwriting ( Annotation annotation ) { return ( ( OverrideIndicatorManager . OverrideIndicator ) annotation ) . isOverwriteIndicator ( ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . link . ILinkedModeListener ; import org . eclipse . jface . text . link . LinkedModeModel ; public class EditorHighlightingSynchronizer implements ILinkedModeListener { private final RubyEditor fEditor ; private final boolean fWasOccurrencesOn ; public EditorHighlightingSynchronizer ( RubyEditor editor ) { Assert . isLegal ( editor != null ) ; fEditor = editor ; fWasOccurrencesOn = fEditor . isMarkingOccurrences ( ) ; if ( fWasOccurrencesOn && ! isEditorDisposed ( ) ) fEditor . uninstallOccurrencesFinder ( ) ; } public void left ( LinkedModeModel environment , int flags ) { if ( fWasOccurrencesOn && ! isEditorDisposed ( ) ) fEditor . installOccurrencesFinder ( true ) ; } private boolean isEditorDisposed ( ) { return fEditor == null || fEditor . getSelectionProvider ( ) == null ; } public void suspend ( LinkedModeModel environment ) { } public void resume ( LinkedModeModel environment , int flags ) { } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; public class RubyEditorPreferences { private static final String RESOURCE_BUNDLE = "" ; private static ResourceBundle resourceBundle = ResourceBundle . getBundle ( RESOURCE_BUNDLE ) ; private RubyEditorPreferences ( ) { } public static String getString ( String key ) { try { return resourceBundle . getString ( key ) ; } catch ( MissingResourceException e ) { return '' + key + '' ; } } public static ResourceBundle getResourceBundle ( ) { return resourceBundle ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ArrayList ; import java . util . List ; import java . util . regex . Pattern ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . link . LinkedPosition ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . templates . DocumentTemplateContext ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . TemplateBuffer ; import org . eclipse . jface . text . templates . TemplateContext ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . eclipse . jface . text . templates . TemplateException ; import org . eclipse . jface . text . templates . TemplateVariable ; import org . rubypeople . rdt . internal . ui . text . ruby . LegacyRubyCompletionProcessor ; public class RubyAutoEditStrategy implements ILinkedModeEditStrategy { private LegacyRubyCompletionProcessor fRubyCp ; private ISourceViewer fViewer ; protected final List fPositionList = new ArrayList ( ) ; public RubyAutoEditStrategy ( String partition , ISourceViewer viewer , LegacyRubyCompletionProcessor rhtmlCp ) { fViewer = viewer ; fRubyCp = rhtmlCp ; } public void customizeDocumentCommand ( IDocument document , DocumentCommand command ) { fPositionList . clear ( ) ; if ( command . text . length ( ) == ) { if ( command . text . charAt ( ) == '' ) { try { int length = ; while ( ( command . offset - length > ) && Pattern . matches ( "" , document . get ( command . offset - length - , ) ) ) { length ++ ; } String prefix = document . get ( command . offset - length , length ) ; Region region = new Region ( command . offset - prefix . length ( ) , prefix . length ( ) ) ; if ( prefix . length ( ) > ) { Template [ ] templates = fRubyCp . getTemplates ( "" ) ; for ( int i = ; i < templates . length ; i ++ ) { Template template = templates [ i ] ; if ( template . getName ( ) . equals ( prefix ) ) { final int offset = command . offset - prefix . length ( ) ; TemplateContextType contextType = fRubyCp . getContextType ( fViewer , region ) ; TemplateContext context = new DocumentTemplateContext ( contextType , document , region . getOffset ( ) , region . getLength ( ) ) ; context . setReadOnly ( false ) ; TemplateBuffer templateBuffer ; try { templateBuffer = context . evaluate ( template ) ; } catch ( TemplateException e1 ) { return ; } int start = getReplaceOffset ( context , region ) ; int end = Math . max ( getReplaceEndOffset ( context , region ) , offset ) ; String templateString = templateBuffer . getString ( ) ; command . text = templateString ; command . offset = start ; command . length = end - start ; fPositionList . add ( new LinkedPosition ( document , offset + templateString . length ( ) , ) ) ; TemplateVariable [ ] variables = templateBuffer . getVariables ( ) ; for ( int z = ; z != variables . length ; z ++ ) { TemplateVariable variable = variables [ z ] ; if ( variable . isUnambiguous ( ) ) continue ; int [ ] offsets = variable . getOffsets ( ) ; int variablelength = variable . getLength ( ) ; for ( int j = ; j != offsets . length ; j ++ ) fPositionList . add ( new LinkedPosition ( document , offsets [ j ] + start , variablelength ) ) ; } break ; } } } } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } public LinkedPosition [ ] getLinkedPositions ( ) { final int size = fPositionList . size ( ) ; if ( size > ) { final LinkedPosition [ ] positions = new LinkedPosition [ size ] ; fPositionList . toArray ( positions ) ; return positions ; } return null ; } protected final int getReplaceOffset ( TemplateContext context , Region region ) { int start ; if ( context instanceof DocumentTemplateContext ) { DocumentTemplateContext docContext = ( DocumentTemplateContext ) context ; start = docContext . getStart ( ) ; } else { start = region . getOffset ( ) ; } return start ; } protected final int getReplaceEndOffset ( TemplateContext context , Region region ) { int end ; if ( context instanceof DocumentTemplateContext ) { DocumentTemplateContext docContext = ( DocumentTemplateContext ) context ; end = docContext . getEnd ( ) ; } else { end = region . getOffset ( ) + region . getLength ( ) ; } return end ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . core . resources . IMarker ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . Position ; import org . eclipse . ui . texteditor . IMarkerUpdater ; import org . eclipse . ui . texteditor . MarkerUtilities ; public class RubyBreakpointMarkerUpdater implements IMarkerUpdater { private final static String [ ] ATTRIBUTES = { IMarker . LINE_NUMBER } ; public String getMarkerType ( ) { return "" ; } public String [ ] getAttribute ( ) { return ATTRIBUTES ; } public boolean updateMarker ( IMarker marker , IDocument document , Position position ) { if ( position == null ) { return true ; } if ( position . isDeleted ( ) ) { return false ; } try { MarkerUtilities . setLineNumber ( marker , document . getLineOfOffset ( position . getOffset ( ) ) + ) ; } catch ( BadLocationException x ) { } return true ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . Collections ; import java . util . Iterator ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; public class RubyAnnotationIterator implements Iterator { private Iterator fIterator ; private Annotation fNext ; private boolean fSkipIrrelevants ; private boolean fReturnAllAnnotations ; public RubyAnnotationIterator ( IAnnotationModel model , boolean skipIrrelevants ) { this ( model , skipIrrelevants , false ) ; } public RubyAnnotationIterator ( IAnnotationModel model , boolean skipIrrelevants , boolean returnAllAnnotations ) { fReturnAllAnnotations = returnAllAnnotations ; if ( model != null ) fIterator = model . getAnnotationIterator ( ) ; else fIterator = Collections . EMPTY_LIST . iterator ( ) ; fSkipIrrelevants = skipIrrelevants ; skip ( ) ; } private void skip ( ) { while ( fIterator . hasNext ( ) ) { Annotation next = ( Annotation ) fIterator . next ( ) ; if ( next instanceof IRubyAnnotation ) { if ( fSkipIrrelevants ) { if ( ! next . isMarkedDeleted ( ) ) { fNext = next ; return ; } } else { fNext = next ; return ; } } else if ( fReturnAllAnnotations ) { fNext = next ; return ; } } fNext = null ; } public boolean hasNext ( ) { return fNext != null ; } public Object next ( ) { try { return fNext ; } finally { skip ( ) ; } } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPersistableElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . core . ExternalRubyScript ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class RubyScriptEditorInput implements IRubyScriptEditorInput , IPersistableElement { private ExternalRubyScript fScript ; public RubyScriptEditorInput ( ExternalRubyScript script ) { this . fScript = script ; } public IRubyScript getRubyScript ( ) { return fScript ; } public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( ! ( obj instanceof RubyScriptEditorInput ) ) return false ; RubyScriptEditorInput other = ( RubyScriptEditorInput ) obj ; return fScript . equals ( other . fScript ) ; } public int hashCode ( ) { return fScript . hashCode ( ) ; } public IPersistableElement getPersistable ( ) { return this ; } public String getName ( ) { return fScript . getElementName ( ) ; } public String getToolTipText ( ) { return fScript . getElementName ( ) ; } public ImageDescriptor getImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_SCRIPT ; } public boolean exists ( ) { return fScript . exists ( ) ; } public Object getAdapter ( Class adapter ) { if ( adapter == IRubyScript . class ) return fScript ; return fScript . getAdapter ( adapter ) ; } public String getFactoryId ( ) { return RubyScriptEditorInputFactory . ID ; } public void saveState ( IMemento memento ) { RubyScriptEditorInputFactory . saveState ( memento , this ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPositionCategoryException ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IAutoEditStrategy ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IPositionUpdater ; import org . eclipse . jface . text . information . IInformationPresenter ; import org . eclipse . jface . text . link . ILinkedModeListener ; import org . eclipse . jface . text . link . InclusivePositionUpdater ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . jface . text . link . LinkedModeUI ; import org . eclipse . jface . text . link . LinkedPosition ; import org . eclipse . jface . text . link . LinkedPositionGroup ; import org . eclipse . jface . text . source . IOverviewRuler ; import org . eclipse . jface . text . source . IVerticalRuler ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . jface . text . source . projection . ProjectionViewer ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . texteditor . AbstractDecoratedTextEditorPreferenceConstants ; import org . eclipse . ui . texteditor . AbstractTextEditor ; import org . rubypeople . rdt . ui . text . RubySourceViewerConfiguration ; public class RubySourceViewer extends ProjectionViewer implements IPropertyChangeListener { public static final int SHOW_OUTLINE = ; public static final int OPEN_STRUCTURE = ; public static final int SHOW_HIERARCHY = ; private boolean fIgnoreTextConverters = false ; protected final LinkedList fPositionList = new LinkedList ( ) ; private IInformationPresenter fOutlinePresenter ; private IInformationPresenter fStructurePresenter ; private Color fForegroundColor ; private Color fBackgroundColor ; private Color fSelectionForegroundColor ; private Color fSelectionBackgroundColor ; private IPreferenceStore fPreferenceStore ; private boolean fIsConfigured ; protected static final String CATEGORY_AUTO_EDIT = "" + "" + System . currentTimeMillis ( ) ; protected final IPositionUpdater fAutoEditUpdater ; public RubySourceViewer ( Composite composite , IVerticalRuler verticalRuler , IOverviewRuler overviewRuler , boolean overviewRulerVisible , int styles , IPreferenceStore store ) { super ( composite , verticalRuler , overviewRuler , overviewRulerVisible , styles ) ; setPreferenceStore ( store ) ; fAutoEditUpdater = new InclusivePositionUpdater ( CATEGORY_AUTO_EDIT ) ; } public void setPreferenceStore ( IPreferenceStore store ) { if ( fIsConfigured && fPreferenceStore != null ) fPreferenceStore . removePropertyChangeListener ( this ) ; fPreferenceStore = store ; if ( fIsConfigured && fPreferenceStore != null ) { fPreferenceStore . addPropertyChangeListener ( this ) ; initializeViewerColors ( ) ; } } protected void initializeViewerColors ( ) { if ( fPreferenceStore != null ) { StyledText styledText = getTextWidget ( ) ; Color color = fPreferenceStore . getBoolean ( AbstractTextEditor . PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT ) ? null : createColor ( fPreferenceStore , AbstractTextEditor . PREFERENCE_COLOR_FOREGROUND , styledText . getDisplay ( ) ) ; styledText . setForeground ( color ) ; if ( fForegroundColor != null ) fForegroundColor . dispose ( ) ; fForegroundColor = color ; color = fPreferenceStore . getBoolean ( AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT ) ? null : createColor ( fPreferenceStore , AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND , styledText . getDisplay ( ) ) ; styledText . setBackground ( color ) ; if ( fBackgroundColor != null ) fBackgroundColor . dispose ( ) ; fBackgroundColor = color ; color = fPreferenceStore . getBoolean ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR ) ? null : createColor ( fPreferenceStore , AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SELECTION_FOREGROUND_COLOR , styledText . getDisplay ( ) ) ; styledText . setSelectionForeground ( color ) ; if ( fSelectionForegroundColor != null ) fSelectionForegroundColor . dispose ( ) ; fSelectionForegroundColor = color ; color = fPreferenceStore . getBoolean ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR ) ? null : createColor ( fPreferenceStore , AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SELECTION_BACKGROUND_COLOR , styledText . getDisplay ( ) ) ; styledText . setSelectionBackground ( color ) ; if ( fSelectionBackgroundColor != null ) fSelectionBackgroundColor . dispose ( ) ; fSelectionBackgroundColor = color ; } } public void configure ( SourceViewerConfiguration configuration ) { StyledText textWidget = getTextWidget ( ) ; if ( textWidget != null && ! textWidget . isDisposed ( ) ) { Color foregroundColor = textWidget . getForeground ( ) ; if ( foregroundColor != null && foregroundColor . isDisposed ( ) ) textWidget . setForeground ( null ) ; Color backgroundColor = textWidget . getBackground ( ) ; if ( backgroundColor != null && backgroundColor . isDisposed ( ) ) textWidget . setBackground ( null ) ; } super . configure ( configuration ) ; if ( configuration instanceof RubySourceViewerConfiguration ) { RubySourceViewerConfiguration javaSVCconfiguration = ( RubySourceViewerConfiguration ) configuration ; fOutlinePresenter = javaSVCconfiguration . getOutlinePresenter ( this , false ) ; if ( fOutlinePresenter != null ) fOutlinePresenter . install ( this ) ; fStructurePresenter = javaSVCconfiguration . getOutlinePresenter ( this , true ) ; if ( fStructurePresenter != null ) fStructurePresenter . install ( this ) ; } if ( fPreferenceStore != null ) { fPreferenceStore . addPropertyChangeListener ( this ) ; initializeViewerColors ( ) ; } fIsConfigured = true ; } public void unconfigure ( ) { if ( fOutlinePresenter != null ) { fOutlinePresenter . uninstall ( ) ; fOutlinePresenter = null ; } if ( fStructurePresenter != null ) { fStructurePresenter . uninstall ( ) ; fStructurePresenter = null ; } if ( fForegroundColor != null ) { fForegroundColor . dispose ( ) ; fForegroundColor = null ; } if ( fBackgroundColor != null ) { fBackgroundColor . dispose ( ) ; fBackgroundColor = null ; } if ( fPreferenceStore != null ) fPreferenceStore . removePropertyChangeListener ( this ) ; super . unconfigure ( ) ; fIsConfigured = false ; } public void propertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( AbstractTextEditor . PREFERENCE_COLOR_FOREGROUND . equals ( property ) || AbstractTextEditor . PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT . equals ( property ) || AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND . equals ( property ) || AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT . equals ( property ) || AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SELECTION_FOREGROUND_COLOR . equals ( property ) || AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR . equals ( property ) || AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SELECTION_BACKGROUND_COLOR . equals ( property ) || AbstractDecoratedTextEditorPreferenceConstants . EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR . equals ( property ) ) { initializeViewerColors ( ) ; } } private Color createColor ( IPreferenceStore store , String key , Display display ) { RGB rgb = null ; if ( store . contains ( key ) ) { if ( store . isDefault ( key ) ) rgb = PreferenceConverter . getDefaultColor ( store , key ) ; else rgb = PreferenceConverter . getColor ( store , key ) ; if ( rgb != null ) return new Color ( display , rgb ) ; } return null ; } public boolean canDoOperation ( int operation ) { if ( operation == SHOW_OUTLINE ) return fOutlinePresenter != null ; if ( operation == OPEN_STRUCTURE ) return fStructurePresenter != null ; return super . canDoOperation ( operation ) ; } public void doOperation ( int operation ) { if ( getTextWidget ( ) == null ) return ; switch ( operation ) { case SHOW_OUTLINE : if ( fOutlinePresenter != null ) fOutlinePresenter . showInformation ( ) ; return ; case OPEN_STRUCTURE : if ( fStructurePresenter != null ) fStructurePresenter . showInformation ( ) ; return ; } super . doOperation ( operation ) ; } protected final void handleVisibleDocumentChanged ( final DocumentEvent event ) { super . handleVisibleDocumentChanged ( event ) ; if ( ! fPositionList . isEmpty ( ) ) { try { final IDocument document = event . getDocument ( ) ; final LinkedModeModel model = new LinkedModeModel ( ) ; final String category = CATEGORY_AUTO_EDIT ; if ( ! document . containsPositionCategory ( category ) ) { document . addPositionCategory ( category ) ; document . addPositionUpdater ( fAutoEditUpdater ) ; model . addLinkingListener ( new ILinkedModeListener ( ) { public final void left ( final LinkedModeModel dummy , final int flags ) { if ( document . containsPositionCategory ( category ) ) { try { document . removePositionCategory ( category ) ; } catch ( BadPositionCategoryException exception ) { } document . removePositionUpdater ( fAutoEditUpdater ) ; } } public final void resume ( final LinkedModeModel dummy , final int flags ) { } public final void suspend ( final LinkedModeModel dummy ) { } } ) ; } LinkedPosition position = null ; LinkedPositionGroup group = null ; for ( final Iterator iterator = fPositionList . iterator ( ) ; iterator . hasNext ( ) ; ) { position = ( LinkedPosition ) iterator . next ( ) ; group = new LinkedPositionGroup ( ) ; group . addPosition ( position ) ; model . addGroup ( group ) ; } model . forceInstall ( ) ; final LinkedModeUI handler = new LinkedModeUI ( model , this ) ; final LinkedPosition exit = ( LinkedPosition ) fPositionList . getFirst ( ) ; final LinkedPosition entry = ( LinkedPosition ) fPositionList . getLast ( ) ; addSelectionChangedListener ( new ISelectionChangedListener ( ) { private boolean fHandled = false ; public final void selectionChanged ( final SelectionChangedEvent dummy ) { if ( ! fHandled ) { fHandled = true ; removeSelectionChangedListener ( this ) ; } } } ) ; addPostSelectionChangedListener ( new ISelectionChangedListener ( ) { private boolean fHandled = false ; public final void selectionChanged ( final SelectionChangedEvent dummy ) { if ( ! fHandled ) { setSelectedRange ( entry . offset , entry . length ) ; invalidateTextPresentation ( entry . offset , ) ; fHandled = true ; removePostSelectionChangedListener ( this ) ; } } } ) ; handler . setExitPosition ( this , exit . offset , , LinkedPositionGroup . NO_STOP ) ; handler . enter ( ) ; } catch ( BadLocationException exception ) { } finally { fPositionList . clear ( ) ; } } } protected void customizeDocumentCommand ( DocumentCommand command ) { if ( isIgnoringAutoEditStrategies ( ) ) return ; List strategies = ( List ) selectContentTypePlugin ( command . offset , fAutoIndentStrategies ) ; if ( strategies == null ) return ; IDocument document = getDocument ( ) ; if ( ! strategies . isEmpty ( ) ) { fPositionList . clear ( ) ; String originalCommandText = command . text ; LinkedPosition [ ] result = null ; IAutoEditStrategy strategy = null ; for ( final Iterator iterator = new ArrayList ( strategies ) . iterator ( ) ; iterator . hasNext ( ) ; ) { strategy = ( IAutoEditStrategy ) iterator . next ( ) ; strategy . customizeDocumentCommand ( document , command ) ; if ( ( strategy instanceof ILinkedModeEditStrategy ) && originalCommandText . equals ( "" ) ) { result = ( ( ILinkedModeEditStrategy ) strategy ) . getLinkedPositions ( ) ; if ( result != null && result . length > ) fPositionList . addAll ( Arrays . asList ( result ) ) ; } } } } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . Iterator ; import java . util . ResourceBundle ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationAccessExtension ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . IVerticalRulerInfo ; import org . eclipse . swt . widgets . Event ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . texteditor . AbstractMarkerAnnotationModel ; import org . eclipse . ui . texteditor . AnnotationPreference ; import org . eclipse . ui . texteditor . AnnotationPreferenceLookup ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . ITextEditorExtension ; import org . eclipse . ui . texteditor . SelectMarkerRulerAction ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . correction . RubyCorrectionProcessor ; public class RubySelectAnnotationRulerAction extends SelectMarkerRulerAction { private ITextEditor fTextEditor ; private Position fPosition ; private Annotation fAnnotation ; private AnnotationPreferenceLookup fAnnotationPreferenceLookup ; private IPreferenceStore fStore ; private boolean fHasCorrection ; private ResourceBundle fBundle ; public RubySelectAnnotationRulerAction ( ResourceBundle bundle , String prefix , ITextEditor editor , IVerticalRulerInfo ruler ) { super ( bundle , prefix , editor , ruler ) ; fBundle = bundle ; fTextEditor = editor ; fAnnotationPreferenceLookup = EditorsUI . getAnnotationPreferenceLookup ( ) ; fStore = RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . JAVA_SELECT_MARKER_RULER_ACTION ) ; } public void run ( ) { runWithEvent ( null ) ; } public void runWithEvent ( Event event ) { if ( fAnnotation instanceof OverrideIndicatorManager . OverrideIndicator ) { ( ( OverrideIndicatorManager . OverrideIndicator ) fAnnotation ) . open ( ) ; return ; } if ( fHasCorrection ) { ITextOperationTarget operation = ( ITextOperationTarget ) fTextEditor . getAdapter ( ITextOperationTarget . class ) ; final int opCode = ISourceViewer . QUICK_ASSIST ; if ( operation != null && operation . canDoOperation ( opCode ) ) { fTextEditor . selectAndReveal ( fPosition . getOffset ( ) , fPosition . getLength ( ) ) ; operation . doOperation ( opCode ) ; } return ; } super . run ( ) ; } public void update ( ) { findRubyAnnotation ( ) ; setEnabled ( true ) ; if ( fAnnotation instanceof OverrideIndicatorManager . OverrideIndicator ) { initialize ( fBundle , "" ) ; return ; } if ( fHasCorrection ) { initialize ( fBundle , "" ) ; return ; } initialize ( fBundle , "" ) ; super . update ( ) ; } private void findRubyAnnotation ( ) { fPosition = null ; fAnnotation = null ; fHasCorrection = false ; AbstractMarkerAnnotationModel model = getAnnotationModel ( ) ; IAnnotationAccessExtension annotationAccess = getAnnotationAccessExtension ( ) ; IDocument document = getDocument ( ) ; if ( model == null ) return ; boolean hasAssistLightbulb = false ; Iterator iter = model . getAnnotationIterator ( ) ; int layer = Integer . MIN_VALUE ; while ( iter . hasNext ( ) ) { Annotation annotation = ( Annotation ) iter . next ( ) ; if ( annotation . isMarkedDeleted ( ) ) continue ; int annotationLayer = annotationAccess . getLayer ( annotation ) ; if ( annotationAccess != null ) { if ( annotationLayer < layer ) continue ; } Position position = model . getPosition ( annotation ) ; if ( ! includesRulerLine ( position , document ) ) continue ; boolean isReadOnly = fTextEditor instanceof ITextEditorExtension && ( ( ITextEditorExtension ) fTextEditor ) . isEditorInputReadOnly ( ) ; if ( ! isReadOnly && ( RubyCorrectionProcessor . hasCorrections ( annotation ) ) ) { fPosition = position ; fAnnotation = annotation ; fHasCorrection = true ; layer = annotationLayer ; continue ; } else { AnnotationPreference preference = fAnnotationPreferenceLookup . getAnnotationPreference ( annotation ) ; if ( preference == null ) continue ; String key = preference . getVerticalRulerPreferenceKey ( ) ; if ( key == null ) continue ; if ( fStore . getBoolean ( key ) ) { fPosition = position ; fAnnotation = annotation ; fHasCorrection = false ; layer = annotationLayer ; } } } } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . text . IAutoEditStrategy ; import org . eclipse . jface . text . link . LinkedPosition ; public interface ILinkedModeEditStrategy extends IAutoEditStrategy { public LinkedPosition [ ] getLinkedPositions ( ) ; } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . Position ; import org . eclipse . ui . texteditor . AbstractMarkerAnnotationModel ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . core . ExternalRubyScript ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class ExternalFileRubyAnnotationModel extends AbstractMarkerAnnotationModel { private IWorkspace fWorkspace ; private IRubyScript fScript ; public ExternalFileRubyAnnotationModel ( IRubyScript script ) { fScript = script ; fWorkspace = ResourcesPlugin . getWorkspace ( ) ; } protected void deleteMarkers ( final IMarker [ ] markers ) throws CoreException { fWorkspace . run ( new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { for ( int i = ; i < markers . length ; ++ i ) { markers [ i ] . delete ( ) ; } } } , null , IWorkspace . AVOID_UPDATE , null ) ; } protected boolean isAcceptable ( IMarker marker ) { return marker != null && marker . getResource ( ) . equals ( getResource ( ) ) && getFileName ( marker ) . equals ( getFileName ( ) ) ; } private String getFileName ( IMarker marker ) { return marker . getAttribute ( "" , "" ) ; } protected void listenToMarkerChanges ( boolean listen ) { } protected IMarker [ ] retrieveMarkers ( ) throws CoreException { IMarker [ ] markers = getResource ( ) . findMarkers ( IMarker . MARKER , true , IResource . DEPTH_INFINITE ) ; List < IMarker > filtered = new ArrayList < IMarker > ( ) ; for ( int i = ; i < markers . length ; i ++ ) { if ( getFileName ( markers [ i ] ) . equals ( getFileName ( ) ) ) { filtered . add ( markers [ i ] ) ; } } return filtered . toArray ( new IMarker [ filtered . size ( ) ] ) ; } private String getFileName ( ) { if ( fScript == null ) return null ; if ( fScript instanceof ExternalRubyScript ) { ExternalRubyScript script = ( ExternalRubyScript ) fScript ; return script . getFile ( ) . getAbsolutePath ( ) ; } return fScript . getPath ( ) . toPortableString ( ) ; } private IResource getResource ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . text . Assert ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; public class GotoMatchingBracketAction extends Action { public final static String GOTO_MATCHING_BRACKET = "" ; private final RubyEditor fEditor ; public GotoMatchingBracketAction ( RubyEditor editor ) { super ( RubyEditorMessages . GotoMatchingBracket_label ) ; Assert . isNotNull ( editor ) ; fEditor = editor ; setEnabled ( true ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . GOTO_MATCHING_BRACKET_ACTION ) ; } public void run ( ) { fEditor . gotoMatchingBracket ( ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . filebuffers . FileBuffers ; import org . eclipse . core . filebuffers . ITextFileBuffer ; import org . eclipse . core . filebuffers . ITextFileBufferManager ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultLineTracker ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentListener ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . core . BufferChangedEvent ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IBufferChangedListener ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class DocumentAdapter implements IBuffer , IDocumentListener { static private class NullBuffer implements IBuffer { public void addBufferChangedListener ( IBufferChangedListener listener ) { } public void append ( char [ ] text ) { } public void append ( String text ) { } public void close ( ) { } public char getChar ( int position ) { return ; } public char [ ] getCharacters ( ) { return null ; } public String getContents ( ) { return null ; } public int getLength ( ) { return ; } public IOpenable getOwner ( ) { return null ; } public String getText ( int offset , int length ) { return null ; } public IResource getUnderlyingResource ( ) { return null ; } public boolean hasUnsavedChanges ( ) { return false ; } public boolean isClosed ( ) { return false ; } public boolean isReadOnly ( ) { return true ; } public void removeBufferChangedListener ( IBufferChangedListener listener ) { } public void replace ( int position , int length , char [ ] text ) { } public void replace ( int position , int length , String text ) { } public void save ( IProgressMonitor progress , boolean force ) { } public void setContents ( char [ ] contents ) { } public void setContents ( String contents ) { } } public final static IBuffer NULL = new NullBuffer ( ) ; protected class DocumentSetCommand implements Runnable { private String fContents ; public void run ( ) { fDocument . set ( fContents ) ; } public void set ( String contents ) { fContents = contents ; Display . getDefault ( ) . syncExec ( this ) ; } } protected class DocumentReplaceCommand implements Runnable { private int fOffset ; private int fLength ; private String fText ; public void run ( ) { try { fDocument . replace ( fOffset , fLength , fText ) ; } catch ( BadLocationException x ) { } } public void replace ( int offset , int length , String text ) { fOffset = offset ; fLength = length ; fText = text ; Display . getDefault ( ) . syncExec ( this ) ; } } private static final boolean DEBUG_LINE_DELIMITERS = true ; private IOpenable fOwner ; private IFile fFile ; private ITextFileBuffer fTextFileBuffer ; private IDocument fDocument ; private DocumentSetCommand fSetCmd = new DocumentSetCommand ( ) ; private DocumentReplaceCommand fReplaceCmd = new DocumentReplaceCommand ( ) ; private Set fLegalLineDelimiters ; private List fBufferListeners = new ArrayList ( ) ; private IStatus fStatus ; public DocumentAdapter ( IOpenable owner , IFile file ) { fOwner = owner ; fFile = file ; initialize ( ) ; } private void initialize ( ) { ITextFileBufferManager manager = FileBuffers . getTextFileBufferManager ( ) ; IPath location = fFile . getFullPath ( ) ; try { manager . connect ( location , new NullProgressMonitor ( ) ) ; fTextFileBuffer = manager . getTextFileBuffer ( location ) ; fDocument = fTextFileBuffer . getDocument ( ) ; } catch ( CoreException x ) { fStatus = x . getStatus ( ) ; fDocument = manager . createEmptyDocument ( location ) ; } fDocument . addPrenotifiedDocumentListener ( this ) ; } public IStatus getStatus ( ) { if ( fStatus != null ) return fStatus ; if ( fTextFileBuffer != null ) return fTextFileBuffer . getStatus ( ) ; return null ; } public IDocument getDocument ( ) { return fDocument ; } public void addBufferChangedListener ( IBufferChangedListener listener ) { Assert . isNotNull ( listener ) ; if ( ! fBufferListeners . contains ( listener ) ) fBufferListeners . add ( listener ) ; } public void removeBufferChangedListener ( IBufferChangedListener listener ) { Assert . isNotNull ( listener ) ; fBufferListeners . remove ( listener ) ; } public void append ( char [ ] text ) { append ( new String ( text ) ) ; } public void append ( String text ) { if ( DEBUG_LINE_DELIMITERS ) { validateLineDelimiters ( text ) ; } fReplaceCmd . replace ( fDocument . getLength ( ) , , text ) ; } public void close ( ) { if ( isClosed ( ) ) return ; IDocument d = fDocument ; fDocument = null ; d . removePrenotifiedDocumentListener ( this ) ; if ( fTextFileBuffer != null ) { ITextFileBufferManager manager = FileBuffers . getTextFileBufferManager ( ) ; try { manager . disconnect ( fTextFileBuffer . getLocation ( ) , new NullProgressMonitor ( ) ) ; } catch ( CoreException x ) { } fTextFileBuffer = null ; } fireBufferChanged ( new BufferChangedEvent ( this , , , null ) ) ; fBufferListeners . clear ( ) ; } public char getChar ( int position ) { try { return fDocument . getChar ( position ) ; } catch ( BadLocationException x ) { throw new ArrayIndexOutOfBoundsException ( ) ; } } public char [ ] getCharacters ( ) { String content = getContents ( ) ; return content == null ? null : content . toCharArray ( ) ; } public String getContents ( ) { return fDocument . get ( ) ; } public int getLength ( ) { return fDocument . getLength ( ) ; } public IOpenable getOwner ( ) { return fOwner ; } public String getText ( int offset , int length ) { try { return fDocument . get ( offset , length ) ; } catch ( BadLocationException x ) { throw new ArrayIndexOutOfBoundsException ( ) ; } } public IResource getUnderlyingResource ( ) { return fFile ; } public boolean hasUnsavedChanges ( ) { return fTextFileBuffer != null ? fTextFileBuffer . isDirty ( ) : false ; } public boolean isClosed ( ) { return fDocument == null ; } public boolean isReadOnly ( ) { IResource resource = getUnderlyingResource ( ) ; return resource == null ? true : resource . isReadOnly ( ) ; } public void replace ( int position , int length , char [ ] text ) { replace ( position , length , new String ( text ) ) ; } public void replace ( int position , int length , String text ) { if ( DEBUG_LINE_DELIMITERS ) { validateLineDelimiters ( text ) ; } fReplaceCmd . replace ( position , length , text ) ; } public void save ( IProgressMonitor progress , boolean force ) throws RubyModelException { try { if ( fTextFileBuffer != null ) fTextFileBuffer . commit ( progress , force ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } public void setContents ( char [ ] contents ) { setContents ( new String ( contents ) ) ; } public void setContents ( String contents ) { int oldLength = fDocument . getLength ( ) ; if ( contents == null ) { if ( oldLength != ) fSetCmd . set ( "" ) ; } else { if ( DEBUG_LINE_DELIMITERS ) { validateLineDelimiters ( contents ) ; } if ( ! contents . equals ( fDocument . get ( ) ) ) fSetCmd . set ( contents ) ; } } private void validateLineDelimiters ( String contents ) { if ( fLegalLineDelimiters == null ) { HashSet existingDelimiters = new HashSet ( ) ; for ( int i = fDocument . getNumberOfLines ( ) - ; i >= ; i -- ) { try { String curr = fDocument . getLineDelimiter ( i ) ; if ( curr != null ) { existingDelimiters . add ( curr ) ; } } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; } } if ( existingDelimiters . isEmpty ( ) ) { return ; } fLegalLineDelimiters = existingDelimiters ; } DefaultLineTracker tracker = new DefaultLineTracker ( ) ; tracker . set ( contents ) ; int lines = tracker . getNumberOfLines ( ) ; if ( lines <= ) return ; for ( int i = ; i < lines ; i ++ ) { try { String curr = tracker . getLineDelimiter ( i ) ; if ( curr != null && ! fLegalLineDelimiters . contains ( curr ) ) { StringBuffer buf = new StringBuffer ( "" ) ; for ( int k = ; k < curr . length ( ) ; k ++ ) { buf . append ( String . valueOf ( ( int ) curr . charAt ( k ) ) ) ; } RubyPlugin . log ( new Exception ( buf . toString ( ) ) ) ; } } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; } } } public void documentAboutToBeChanged ( DocumentEvent event ) { } public void documentChanged ( DocumentEvent event ) { fireBufferChanged ( new BufferChangedEvent ( this , event . getOffset ( ) , event . getLength ( ) , event . getText ( ) ) ) ; } private void fireBufferChanged ( BufferChangedEvent event ) { if ( fBufferListeners != null && fBufferListeners . size ( ) > ) { Iterator e = new ArrayList ( fBufferListeners ) . iterator ( ) ; while ( e . hasNext ( ) ) ( ( IBufferChangedListener ) e . next ( ) ) . bufferChanged ( event ) ; } } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import java . util . ResourceBundle ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . actions . RetargetAction ; import org . eclipse . ui . ide . IDEActionFactory ; import org . eclipse . ui . texteditor . BasicTextEditorActionContributor ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . eclipse . ui . texteditor . RetargetTextEditorAction ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . actions . FoldingActionGroup ; import org . rubypeople . rdt . ui . actions . IRubyEditorActionDefinitionIds ; import org . rubypeople . rdt . ui . actions . RdtActionConstants ; import org . rubypeople . rdt . ui . actions . RubyActionIds ; public class RubyEditorActionContributor extends BasicTextEditorActionContributor { private List fPartListeners = new ArrayList ( ) ; protected RetargetTextEditorAction contentAssistProposal ; private RetargetTextEditorAction fGotoMatchingBracket ; private RetargetTextEditorAction fShowOutline ; private RetargetTextEditorAction fOpenHierarchy ; private RetargetTextEditorAction fQuickAssistAction ; private RetargetAction fRetargetShowRubyDoc ; private RetargetTextEditorAction fShowRubyDoc ; public RubyEditorActionContributor ( ) { super ( ) ; ResourceBundle b = RubyEditorMessages . getBundleForConstructedKeys ( ) ; fRetargetShowRubyDoc = new RetargetAction ( RdtActionConstants . SHOW_RUBY_DOC , RubyEditorMessages . ShowRDoc_label ) ; fRetargetShowRubyDoc . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SHOW_RDOC ) ; markAsPartListener ( fRetargetShowRubyDoc ) ; fShowOutline = new RetargetTextEditorAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" ) ; fShowOutline . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SHOW_OUTLINE ) ; fOpenHierarchy = new RetargetTextEditorAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" ) ; fOpenHierarchy . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_HIERARCHY ) ; contentAssistProposal = new RetargetTextEditorAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" ) ; fGotoMatchingBracket = new RetargetTextEditorAction ( b , "" ) ; fGotoMatchingBracket . setActionDefinitionId ( IRubyEditorActionDefinitionIds . GOTO_MATCHING_BRACKET ) ; fQuickAssistAction = new RetargetTextEditorAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" ) ; fQuickAssistAction . setActionDefinitionId ( ITextEditorActionDefinitionIds . QUICK_ASSIST ) ; fShowRubyDoc = new RetargetTextEditorAction ( b , "" ) ; fShowRubyDoc . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SHOW_RDOC ) ; } protected final void markAsPartListener ( RetargetAction action ) { fPartListeners . add ( action ) ; } public void contributeToMenu ( IMenuManager menu ) { IMenuManager editMenu = menu . findMenuUsingPath ( IWorkbenchActionConstants . M_EDIT ) ; if ( editMenu != null ) { editMenu . add ( new Separator ( ) ) ; editMenu . add ( contentAssistProposal ) ; editMenu . add ( fQuickAssistAction ) ; } IMenuManager navigateMenu = menu . findMenuUsingPath ( IWorkbenchActionConstants . M_NAVIGATE ) ; if ( navigateMenu != null ) { navigateMenu . appendToGroup ( IWorkbenchActionConstants . SHOW_EXT , fShowOutline ) ; navigateMenu . appendToGroup ( IWorkbenchActionConstants . SHOW_EXT , fOpenHierarchy ) ; } IMenuManager gotoMenu = menu . findMenuUsingPath ( "" ) ; if ( gotoMenu != null ) { gotoMenu . add ( new Separator ( "" ) ) ; gotoMenu . appendToGroup ( "" , fGotoMatchingBracket ) ; } } public void setActiveEditor ( IEditorPart part ) { super . setActiveEditor ( part ) ; ITextEditor textEditor = null ; if ( part instanceof ITextEditor ) textEditor = ( ITextEditor ) part ; contentAssistProposal . setAction ( getAction ( textEditor , "" ) ) ; fGotoMatchingBracket . setAction ( getAction ( textEditor , GotoMatchingBracketAction . GOTO_MATCHING_BRACKET ) ) ; fQuickAssistAction . setAction ( getAction ( textEditor , ITextEditorActionConstants . QUICK_ASSIST ) ) ; fShowOutline . setAction ( getAction ( textEditor , IRubyEditorActionDefinitionIds . SHOW_OUTLINE ) ) ; fOpenHierarchy . setAction ( getAction ( textEditor , IRubyEditorActionDefinitionIds . OPEN_HIERARCHY ) ) ; fShowRubyDoc . setAction ( getAction ( textEditor , "" ) ) ; if ( part instanceof RubyEditor ) { RubyEditor javaEditor = ( RubyEditor ) part ; javaEditor . getActionGroup ( ) . fillActionBars ( getActionBars ( ) ) ; FoldingActionGroup foldingActions = javaEditor . getFoldingActionGroup ( ) ; if ( foldingActions != null ) foldingActions . updateActionBars ( ) ; } IActionBars actionBars = getActionBars ( ) ; actionBars . setGlobalActionHandler ( RubyActionIds . COMMENT , getAction ( textEditor , "" ) ) ; actionBars . setGlobalActionHandler ( RubyActionIds . UNCOMMENT , getAction ( textEditor , "" ) ) ; actionBars . setGlobalActionHandler ( RubyActionIds . TOGGLE_COMMENT , getAction ( textEditor , "" ) ) ; actionBars . setGlobalActionHandler ( RubyActionIds . FORMAT , getAction ( textEditor , "" ) ) ; IAction action = getAction ( textEditor , ITextEditorActionConstants . NEXT ) ; actionBars . setGlobalActionHandler ( ITextEditorActionDefinitionIds . GOTO_NEXT_ANNOTATION , action ) ; actionBars . setGlobalActionHandler ( ITextEditorActionConstants . NEXT , action ) ; action = getAction ( textEditor , ITextEditorActionConstants . PREVIOUS ) ; actionBars . setGlobalActionHandler ( ITextEditorActionDefinitionIds . GOTO_PREVIOUS_ANNOTATION , action ) ; actionBars . setGlobalActionHandler ( ITextEditorActionConstants . PREVIOUS , action ) ; actionBars . setGlobalActionHandler ( IDEActionFactory . ADD_TASK . getId ( ) , getAction ( textEditor , IDEActionFactory . ADD_TASK . getId ( ) ) ) ; actionBars . setGlobalActionHandler ( IDEActionFactory . BOOKMARK . getId ( ) , getAction ( textEditor , IDEActionFactory . BOOKMARK . getId ( ) ) ) ; } @ Override public void init ( IActionBars bars , IWorkbenchPage page ) { Iterator e = fPartListeners . iterator ( ) ; while ( e . hasNext ( ) ) page . addPartListener ( ( RetargetAction ) e . next ( ) ) ; super . init ( bars , page ) ; bars . setGlobalActionHandler ( RdtActionConstants . SHOW_RUBY_DOC , fShowRubyDoc ) ; } public void dispose ( ) { Iterator e = fPartListeners . iterator ( ) ; while ( e . hasNext ( ) ) getPage ( ) . removePartListener ( ( RetargetAction ) e . next ( ) ) ; fPartListeners . clear ( ) ; if ( fRetargetShowRubyDoc != null ) { fRetargetShowRubyDoc . dispose ( ) ; fRetargetShowRubyDoc = null ; } setActiveEditor ( null ) ; super . dispose ( ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . resource . ImageRegistry ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . IAnnotationImageProvider ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . text . correction . RubyCorrectionProcessor ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyAnnotationImageProvider implements IAnnotationImageProvider { private final static int NO_IMAGE = ; private final static int GRAY_IMAGE = ; private final static int OVERLAY_IMAGE = ; private final static int QUICKFIX_IMAGE = ; private final static int QUICKFIX_ERROR_IMAGE = ; private static Image fgQuickFixImage ; private static Image fgQuickFixErrorImage ; private static ImageRegistry fgImageRegistry ; private boolean fShowQuickFixIcon ; private int fCachedImageType ; private Image fCachedImage ; public RubyAnnotationImageProvider ( ) { fShowQuickFixIcon = PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . EDITOR_CORRECTION_INDICATION ) ; } public Image getManagedImage ( Annotation annotation ) { if ( annotation instanceof IRubyAnnotation ) { IRubyAnnotation javaAnnotation = ( IRubyAnnotation ) annotation ; int imageType = getImageType ( javaAnnotation ) ; return getImage ( javaAnnotation , imageType , Display . getCurrent ( ) ) ; } return null ; } public String getImageDescriptorId ( Annotation annotation ) { return null ; } public ImageDescriptor getImageDescriptor ( String symbolicName ) { return null ; } private boolean showQuickFix ( IRubyAnnotation annotation ) { return fShowQuickFixIcon && annotation . isProblem ( ) && RubyCorrectionProcessor . hasCorrections ( ( Annotation ) annotation ) ; } private Image getQuickFixImage ( ) { if ( fgQuickFixImage == null ) fgQuickFixImage = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_FIXABLE_PROBLEM ) ; return fgQuickFixImage ; } private Image getQuickFixErrorImage ( ) { if ( fgQuickFixErrorImage == null ) fgQuickFixErrorImage = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_FIXABLE_ERROR ) ; return fgQuickFixErrorImage ; } private ImageRegistry getImageRegistry ( Display display ) { if ( fgImageRegistry == null ) fgImageRegistry = new ImageRegistry ( display ) ; return fgImageRegistry ; } private int getImageType ( IRubyAnnotation annotation ) { int imageType = NO_IMAGE ; if ( annotation . hasOverlay ( ) ) imageType = OVERLAY_IMAGE ; else if ( ! annotation . isMarkedDeleted ( ) ) { if ( showQuickFix ( annotation ) ) imageType = RubyMarkerAnnotation . ERROR_ANNOTATION_TYPE . equals ( annotation . getType ( ) ) ? QUICKFIX_ERROR_IMAGE : QUICKFIX_IMAGE ; } else { imageType = GRAY_IMAGE ; } return imageType ; } private Image getImage ( IRubyAnnotation annotation , int imageType , Display display ) { if ( ( imageType == QUICKFIX_IMAGE || imageType == QUICKFIX_ERROR_IMAGE ) && fCachedImageType == imageType ) return fCachedImage ; Image image = null ; switch ( imageType ) { case OVERLAY_IMAGE : IRubyAnnotation overlay = annotation . getOverlay ( ) ; image = getManagedImage ( ( Annotation ) overlay ) ; fCachedImageType = - ; break ; case QUICKFIX_IMAGE : image = getQuickFixImage ( ) ; fCachedImageType = imageType ; fCachedImage = image ; break ; case QUICKFIX_ERROR_IMAGE : image = getQuickFixErrorImage ( ) ; fCachedImageType = imageType ; fCachedImage = image ; break ; case GRAY_IMAGE : { ISharedImages sharedImages = PlatformUI . getWorkbench ( ) . getSharedImages ( ) ; String annotationType = annotation . getType ( ) ; if ( RubyMarkerAnnotation . ERROR_ANNOTATION_TYPE . equals ( annotationType ) ) { image = sharedImages . getImage ( ISharedImages . IMG_OBJS_ERROR_TSK ) ; } else if ( RubyMarkerAnnotation . WARNING_ANNOTATION_TYPE . equals ( annotationType ) ) { image = sharedImages . getImage ( ISharedImages . IMG_OBJS_WARN_TSK ) ; } else if ( RubyMarkerAnnotation . INFO_ANNOTATION_TYPE . equals ( annotationType ) ) { image = sharedImages . getImage ( ISharedImages . IMG_OBJS_INFO_TSK ) ; } if ( image != null ) { ImageRegistry registry = getImageRegistry ( display ) ; String key = Integer . toString ( image . hashCode ( ) ) ; Image grayImage = registry . get ( key ) ; if ( grayImage == null ) { grayImage = new Image ( display , image , SWT . IMAGE_GRAY ) ; registry . put ( key , grayImage ) ; } image = grayImage ; } fCachedImageType = - ; break ; } } return image ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . text . source . IVerticalRulerInfo ; import org . eclipse . ui . texteditor . AbstractRulerActionDelegate ; import org . eclipse . ui . texteditor . ITextEditor ; public class RubySelectRulerAction extends AbstractRulerActionDelegate { protected IAction createAction ( ITextEditor editor , IVerticalRulerInfo rulerInfo ) { return new RubySelectAnnotationRulerAction ( RubyEditorMessages . getBundleForConstructedKeys ( ) , "" , editor , rulerInfo ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . swt . SWT ; import org . eclipse . ui . IEditorDescriptor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IEditorSite ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . actions . WorkspaceModifyOperation ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . ide . IGotoMarker ; import org . eclipse . ui . part . FileEditorInput ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . eclipse . ui . texteditor . TextEditorAction ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . LocalFileStorage ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . ExternalRubyScript ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; public class EditorUtility { public static IEditorPart openInEditor ( Object inputElement ) throws RubyModelException , PartInitException { return openInEditor ( inputElement , true ) ; } public static IEditorPart openInEditor ( Object inputElement , boolean activate ) throws RubyModelException , PartInitException { if ( inputElement instanceof IFile ) return openInEditor ( ( IFile ) inputElement , activate ) ; IEditorInput input = getEditorInput ( inputElement ) ; if ( input instanceof IFileEditorInput ) { IFileEditorInput fileInput = ( IFileEditorInput ) input ; return openInEditor ( fileInput . getFile ( ) , activate ) ; } if ( input != null ) return openInEditor ( input , getEditorID ( input , inputElement ) , activate ) ; return null ; } private static IEditorPart openInEditor ( IFile file , boolean activate ) throws PartInitException { if ( file != null ) { IWorkbenchPage p = RubyPlugin . getActivePage ( ) ; if ( p != null ) { IEditorPart editorPart = IDE . openEditor ( p , file , activate ) ; initializeHighlightRange ( editorPart ) ; return editorPart ; } } return null ; } private static IEditorPart openInEditor ( IEditorInput input , String editorID , boolean activate ) throws PartInitException { if ( input != null ) { IWorkbenchPage p = RubyPlugin . getActivePage ( ) ; if ( p != null ) { IEditorPart editorPart = p . openEditor ( input , editorID , activate ) ; initializeHighlightRange ( editorPart ) ; return editorPart ; } } return null ; } private static void initializeHighlightRange ( IEditorPart editorPart ) { if ( editorPart instanceof ITextEditor ) { IAction toggleAction = editorPart . getEditorSite ( ) . getActionBars ( ) . getGlobalActionHandler ( ITextEditorActionDefinitionIds . TOGGLE_SHOW_SELECTED_ELEMENT_ONLY ) ; boolean enable = toggleAction != null ; if ( enable && editorPart instanceof RubyEditor ) enable = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . EDITOR_SHOW_SEGMENTS ) ; else enable = enable && toggleAction . isEnabled ( ) && toggleAction . isChecked ( ) ; if ( enable ) { if ( toggleAction instanceof TextEditorAction ) { ( ( TextEditorAction ) toggleAction ) . setEditor ( null ) ; ( ( TextEditorAction ) toggleAction ) . setEditor ( ( ITextEditor ) editorPart ) ; } else { toggleAction . run ( ) ; toggleAction . run ( ) ; } } } } private static String getEditorID ( IEditorInput input , Object inputObject ) { IEditorDescriptor editorDescriptor ; try { editorDescriptor = IDE . getEditorDescriptor ( input . getName ( ) ) ; } catch ( PartInitException e ) { return null ; } if ( editorDescriptor != null ) return editorDescriptor . getId ( ) ; return null ; } public static IEditorInput getEditorInput ( Object input ) throws RubyModelException { if ( input instanceof IRubyElement ) return getEditorInput ( ( IRubyElement ) input ) ; if ( input instanceof IFile ) return new FileEditorInput ( ( IFile ) input ) ; if ( input instanceof LocalFileStorage ) { return new ExternalRubyFileEditorInput ( ( LocalFileStorage ) input ) ; } return null ; } private static IEditorInput getEditorInput ( IRubyElement element ) throws RubyModelException { while ( element != null ) { if ( element instanceof IRubyScript ) { IRubyScript unit = RubyModelUtil . toOriginal ( ( IRubyScript ) element ) ; IResource resource = unit . getResource ( ) ; if ( resource instanceof IFile ) return new FileEditorInput ( ( IFile ) resource ) ; } if ( element instanceof ExternalRubyScript ) return new RubyScriptEditorInput ( ( ( ExternalRubyScript ) element ) ) ; element = element . getParent ( ) ; } return null ; } public static void revealInEditor ( IEditorPart part , IRubyElement element ) { if ( element == null ) return ; if ( part instanceof RubyEditor ) { ( ( RubyEditor ) part ) . setSelection ( element ) ; return ; } try { ISourceRange range = null ; if ( element instanceof IRubyScript ) range = null ; else if ( element instanceof IMember ) range = ( ( IMember ) element ) . getNameRange ( ) ; else if ( element instanceof ISourceReference ) range = ( ( ISourceReference ) element ) . getSourceRange ( ) ; if ( range != null ) revealInEditor ( part , range . getOffset ( ) , range . getLength ( ) ) ; } catch ( RubyModelException e ) { } } public static void revealInEditor ( IEditorPart editor , final int offset , final int length ) { if ( editor instanceof ITextEditor ) { ( ( ITextEditor ) editor ) . selectAndReveal ( offset , length ) ; return ; } if ( editor instanceof IGotoMarker ) { final IEditorInput input = editor . getEditorInput ( ) ; if ( input instanceof IFileEditorInput ) { final IGotoMarker gotoMarkerTarget = ( IGotoMarker ) editor ; WorkspaceModifyOperation op = new WorkspaceModifyOperation ( ) { protected void execute ( IProgressMonitor monitor ) throws CoreException { IMarker marker = null ; try { marker = ( ( IFileEditorInput ) input ) . getFile ( ) . createMarker ( IMarker . TEXT ) ; marker . setAttribute ( IMarker . CHAR_START , offset ) ; marker . setAttribute ( IMarker . CHAR_END , offset + length ) ; gotoMarkerTarget . gotoMarker ( marker ) ; } finally { if ( marker != null ) marker . delete ( ) ; } } } ; try { op . run ( null ) ; } catch ( InvocationTargetException ex ) { } catch ( InterruptedException e ) { Assert . isTrue ( false , "" ) ; } } return ; } if ( editor != null && editor . getEditorSite ( ) . getSelectionProvider ( ) != null ) { IEditorSite site = editor . getEditorSite ( ) ; if ( site == null ) return ; ISelectionProvider provider = editor . getEditorSite ( ) . getSelectionProvider ( ) ; if ( provider == null ) return ; provider . setSelection ( new TextSelection ( offset , length ) ) ; } } public static IRubyProject getRubyProject ( IEditorInput input ) { IRubyProject rProject = null ; if ( input instanceof IFileEditorInput ) { IProject project = ( ( IFileEditorInput ) input ) . getFile ( ) . getProject ( ) ; if ( project != null ) { rProject = RubyCore . create ( project ) ; if ( ! rProject . exists ( ) ) rProject = null ; } } return rProject ; } public static IEditorPart isOpenInEditor ( Object inputElement ) { IEditorInput input = null ; try { input = getEditorInput ( inputElement ) ; } catch ( RubyModelException x ) { RubyPlugin . log ( x . getStatus ( ) ) ; } if ( input != null ) { IWorkbenchPage p = RubyPlugin . getActivePage ( ) ; if ( p != null ) { return p . findEditor ( input ) ; } } return null ; } public static int findLocalizedModifier ( String modifierName ) { if ( modifierName == null ) return ; if ( modifierName . equalsIgnoreCase ( Action . findModifierString ( SWT . CTRL ) ) ) return SWT . CTRL ; if ( modifierName . equalsIgnoreCase ( Action . findModifierString ( SWT . SHIFT ) ) ) return SWT . SHIFT ; if ( modifierName . equalsIgnoreCase ( Action . findModifierString ( SWT . ALT ) ) ) return SWT . ALT ; if ( modifierName . equalsIgnoreCase ( Action . findModifierString ( SWT . COMMAND ) ) ) return SWT . COMMAND ; return ; } public static String getModifierString ( int stateMask ) { String modifierString = "" ; if ( ( stateMask & SWT . CTRL ) == SWT . CTRL ) modifierString = appendModifierString ( modifierString , SWT . CTRL ) ; if ( ( stateMask & SWT . ALT ) == SWT . ALT ) modifierString = appendModifierString ( modifierString , SWT . ALT ) ; if ( ( stateMask & SWT . SHIFT ) == SWT . SHIFT ) modifierString = appendModifierString ( modifierString , SWT . SHIFT ) ; if ( ( stateMask & SWT . COMMAND ) == SWT . COMMAND ) modifierString = appendModifierString ( modifierString , SWT . COMMAND ) ; return modifierString ; } private static String appendModifierString ( String modifierString , int modifier ) { if ( modifierString == null ) modifierString = "" ; String newModifierString = Action . findModifierString ( modifier ) ; if ( modifierString . length ( ) == ) return newModifierString ; return Messages . format ( RubyEditorMessages . EditorUtility_concatModifierStrings , new String [ ] { modifierString , newModifierString } ) ; } public static IRubyElement getEditorInputRubyElement ( IEditorPart editor , boolean primaryOnly ) { Assert . isNotNull ( editor ) ; IEditorInput editorInput = editor . getEditorInput ( ) ; if ( editorInput == null ) return null ; IRubyElement je = RubyUI . getEditorInputRubyElement ( editorInput ) ; if ( je != null || primaryOnly ) return je ; return RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) . getWorkingCopy ( editorInput , false ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . SafeRunner ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . Assert ; import org . eclipse . ui . IPartListener2 ; import org . eclipse . ui . IWindowListener ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PlatformUI ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . RubyUI ; public final class ASTProvider { public static final class WAIT_FLAG { String fName ; private WAIT_FLAG ( String name ) { fName = name ; } public String toString ( ) { return fName ; } } public static final WAIT_FLAG WAIT_YES = new WAIT_FLAG ( "" ) ; public static final WAIT_FLAG WAIT_ACTIVE_ONLY = new WAIT_FLAG ( "" ) ; public static final WAIT_FLAG WAIT_NO = new WAIT_FLAG ( "" ) ; private static final boolean DEBUG = "" . equalsIgnoreCase ( Platform . getDebugOption ( "" ) ) ; private class ActivationListener implements IPartListener2 , IWindowListener { public void partActivated ( IWorkbenchPartReference ref ) { if ( isRubyEditor ( ref ) && ! isActiveEditor ( ref ) ) activeRubyEditorChanged ( ref . getPart ( true ) ) ; } public void partBroughtToTop ( IWorkbenchPartReference ref ) { if ( isRubyEditor ( ref ) && ! isActiveEditor ( ref ) ) activeRubyEditorChanged ( ref . getPart ( true ) ) ; } public void partClosed ( IWorkbenchPartReference ref ) { if ( isActiveEditor ( ref ) ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + ref . getTitle ( ) ) ; activeRubyEditorChanged ( null ) ; } } public void partDeactivated ( IWorkbenchPartReference ref ) { } public void partOpened ( IWorkbenchPartReference ref ) { if ( isRubyEditor ( ref ) && ! isActiveEditor ( ref ) ) activeRubyEditorChanged ( ref . getPart ( true ) ) ; } public void partHidden ( IWorkbenchPartReference ref ) { } public void partVisible ( IWorkbenchPartReference ref ) { if ( isRubyEditor ( ref ) && ! isActiveEditor ( ref ) ) activeRubyEditorChanged ( ref . getPart ( true ) ) ; } public void partInputChanged ( IWorkbenchPartReference ref ) { if ( isRubyEditor ( ref ) && isActiveEditor ( ref ) ) activeRubyEditorChanged ( ref . getPart ( true ) ) ; } public void windowActivated ( IWorkbenchWindow window ) { IWorkbenchPartReference ref = window . getPartService ( ) . getActivePartReference ( ) ; if ( isRubyEditor ( ref ) && ! isActiveEditor ( ref ) ) activeRubyEditorChanged ( ref . getPart ( true ) ) ; } public void windowDeactivated ( IWorkbenchWindow window ) { } public void windowClosed ( IWorkbenchWindow window ) { if ( fActiveEditor != null && fActiveEditor . getSite ( ) != null && window == fActiveEditor . getSite ( ) . getWorkbenchWindow ( ) ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + fActiveEditor . getTitle ( ) ) ; activeRubyEditorChanged ( null ) ; } window . getPartService ( ) . removePartListener ( this ) ; } public void windowOpened ( IWorkbenchWindow window ) { window . getPartService ( ) . addPartListener ( this ) ; } private boolean isActiveEditor ( IWorkbenchPartReference ref ) { return ref != null && isActiveEditor ( ref . getPart ( false ) ) ; } private boolean isActiveEditor ( IWorkbenchPart part ) { return part != null && ( part == fActiveEditor ) ; } private boolean isRubyEditor ( IWorkbenchPartReference ref ) { if ( ref == null ) return false ; String id = ref . getId ( ) ; return RubyUI . ID_RUBY_EDITOR . equals ( id ) || RubyUI . ID_EXTERNAL_EDITOR . equals ( id ) || ref . getPart ( false ) instanceof RubyEditor ; } } public static final boolean SHARED_AST_STATEMENT_RECOVERY = true ; private static final String DEBUG_PREFIX = "" ; private IRubyElement fReconcilingRubyElement ; private IRubyElement fActiveRubyElement ; private RootNode fAST ; private ActivationListener fActivationListener ; private Object fReconcileLock = new Object ( ) ; private Object fWaitLock = new Object ( ) ; private boolean fIsReconciling ; private IWorkbenchPart fActiveEditor ; public static ASTProvider getASTProvider ( ) { return RubyPlugin . getDefault ( ) . getASTProvider ( ) ; } public ASTProvider ( ) { install ( ) ; } void install ( ) { fActivationListener = new ActivationListener ( ) ; PlatformUI . getWorkbench ( ) . addWindowListener ( fActivationListener ) ; IWorkbenchWindow [ ] windows = PlatformUI . getWorkbench ( ) . getWorkbenchWindows ( ) ; for ( int i = , length = windows . length ; i < length ; i ++ ) windows [ i ] . getPartService ( ) . addPartListener ( fActivationListener ) ; } private void activeRubyEditorChanged ( IWorkbenchPart editor ) { IRubyElement rubyElement = null ; if ( editor instanceof RubyEditor ) rubyElement = ( ( RubyEditor ) editor ) . getInputRubyElement ( ) ; synchronized ( this ) { fActiveEditor = editor ; fActiveRubyElement = rubyElement ; cache ( null , rubyElement ) ; } if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + toString ( rubyElement ) ) ; synchronized ( fReconcileLock ) { if ( fIsReconciling && ( fReconcilingRubyElement == null || ! fReconcilingRubyElement . equals ( rubyElement ) ) ) { fIsReconciling = false ; fReconcilingRubyElement = null ; } else if ( rubyElement == null ) { fIsReconciling = false ; fReconcilingRubyElement = null ; } } } public boolean isCached ( Node ast ) { return ast != null && fAST == ast ; } public boolean isActive ( IRubyScript cu ) { return cu != null && cu . equals ( fActiveRubyElement ) ; } void aboutToBeReconciled ( IRubyElement rubyElement ) { if ( rubyElement == null ) return ; if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + toString ( rubyElement ) ) ; synchronized ( fReconcileLock ) { fIsReconciling = true ; fReconcilingRubyElement = rubyElement ; } cache ( null , rubyElement ) ; } private synchronized void disposeAST ( ) { if ( fAST == null ) return ; if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + toString ( fAST ) + "" + toString ( fActiveRubyElement ) ) ; fAST = null ; cache ( null , null ) ; } private String toString ( IRubyElement javaElement ) { if ( javaElement == null ) return "" ; else return javaElement . getElementName ( ) ; } private String toString ( Node ast ) { if ( ast == null ) return "" ; return ASTUtil . stringRepresentation ( ast ) ; } private synchronized void cache ( RootNode ast , IRubyElement javaElement ) { if ( fActiveRubyElement != null && ! fActiveRubyElement . equals ( javaElement ) ) { if ( DEBUG && javaElement != null ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + toString ( javaElement ) ) ; return ; } if ( DEBUG && ( javaElement != null || ast != null ) ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + toString ( ast ) + "" + toString ( javaElement ) ) ; if ( fAST != null ) disposeAST ( ) ; fAST = ast ; synchronized ( fWaitLock ) { fWaitLock . notifyAll ( ) ; } } public RootNode getAST ( IRubyElement re , WAIT_FLAG waitFlag , IProgressMonitor progressMonitor ) { if ( re == null ) return null ; Assert . isTrue ( re . getElementType ( ) == IRubyElement . SCRIPT ) ; if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) return null ; boolean isActiveElement ; synchronized ( this ) { isActiveElement = re . equals ( fActiveRubyElement ) ; if ( isActiveElement ) { if ( fAST != null ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + toString ( fAST ) + "" + re . getElementName ( ) ) ; return fAST ; } if ( waitFlag == WAIT_NO ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + re . getElementName ( ) ) ; return null ; } } } if ( isActiveElement && isReconciling ( re ) ) { try { final IRubyElement activeElement = fReconcilingRubyElement ; synchronized ( fWaitLock ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + re . getElementName ( ) ) ; fWaitLock . wait ( ) ; } synchronized ( this ) { if ( activeElement == fActiveRubyElement && fAST != null ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + re . getElementName ( ) ) ; return fAST ; } } return getAST ( re , waitFlag , progressMonitor ) ; } catch ( InterruptedException e ) { return null ; } } else if ( waitFlag == WAIT_NO || ( waitFlag == WAIT_ACTIVE_ONLY && ! ( isActiveElement && fAST == null ) ) ) return null ; if ( isActiveElement ) aboutToBeReconciled ( re ) ; RootNode ast = null ; try { ast = createAST ( re , progressMonitor ) ; if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) ast = null ; else if ( DEBUG && ast != null ) System . err . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + re . getElementName ( ) ) ; } finally { if ( isActiveElement ) { if ( fAST != null ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + re . getElementName ( ) + "" ) ; reconciled ( fAST , re , null ) ; } else reconciled ( ast , re , null ) ; } } return ast ; } private boolean isReconciling ( IRubyElement javaElement ) { synchronized ( fReconcileLock ) { return javaElement != null && javaElement . equals ( fReconcilingRubyElement ) && fIsReconciling ; } } private RootNode createAST ( IRubyElement je , final IProgressMonitor progressMonitor ) { if ( ! hasSource ( je ) ) return null ; if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) return null ; final RubyParser parser = new RubyParser ( ) ; if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) return null ; if ( je . getElementType ( ) != IRubyElement . SCRIPT ) return null ; IRubyScript script = ( IRubyScript ) je ; String source = null ; try { source = script . getSource ( ) ; } catch ( RubyModelException e ) { return null ; } final String goodSource = source ; if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) return null ; final RootNode root [ ] = new RootNode [ ] ; SafeRunner . run ( new ISafeRunnable ( ) { public void run ( ) { try { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) root [ ] = null ; root [ ] = ( RootNode ) parser . parse ( goodSource ) . getAST ( ) ; } catch ( OperationCanceledException ex ) { root [ ] = null ; } catch ( SyntaxException ex ) { root [ ] = null ; } } public void handleException ( Throwable ex ) { IStatus status = new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . OK , "" , ex ) ; RubyPlugin . getDefault ( ) . getLog ( ) . log ( status ) ; } } ) ; return root [ ] ; } private boolean hasSource ( IRubyElement re ) { if ( re == null || ! re . exists ( ) ) return false ; try { return re instanceof ISourceReference && ( ( ISourceReference ) re ) . getSource ( ) != null ; } catch ( RubyModelException ex ) { IStatus status = new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . OK , "" , ex ) ; RubyPlugin . getDefault ( ) . getLog ( ) . log ( status ) ; } return false ; } public void dispose ( ) { PlatformUI . getWorkbench ( ) . removeWindowListener ( fActivationListener ) ; fActivationListener = null ; disposeAST ( ) ; synchronized ( fWaitLock ) { fWaitLock . notifyAll ( ) ; } } void reconciled ( RootNode ast , IRubyElement javaElement , IProgressMonitor progressMonitor ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" + toString ( javaElement ) + "" + toString ( ast ) ) ; synchronized ( fReconcileLock ) { fIsReconciling = progressMonitor != null && progressMonitor . isCanceled ( ) ; if ( javaElement == null || ! javaElement . equals ( fReconcilingRubyElement ) ) { if ( DEBUG ) System . out . println ( getThreadName ( ) + "" + DEBUG_PREFIX + "" ) ; synchronized ( fWaitLock ) { fWaitLock . notifyAll ( ) ; } return ; } cache ( ast , javaElement ) ; } } private String getThreadName ( ) { String name = Thread . currentThread ( ) . getName ( ) ; if ( name != null ) return name ; else return Thread . currentThread ( ) . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . text . MessageFormat ; import java . util . ResourceBundle ; import org . eclipse . osgi . util . NLS ; public class RubyEditorMessages extends NLS { private static final String BUNDLE_NAME = RubyEditorMessages . class . getName ( ) ; public static String RubyOutlinePage_Sort_label ; public static String RubyOutlinePage_Sort_tooltip ; public static String RubyOutlinePage_Sort_description ; public static String RubyOutlinePage_GoIntoTopLevelType_label ; public static String RubyOutlinePage_GoIntoTopLevelType_tooltip ; public static String RubyOutlinePage_GoIntoTopLevelType_description ; public static String RubyOutlinePage_error_NoTopLevelType ; public static String GotoMatchingBracket_label ; public static String GotoMatchingBracket_error_bracketOutsideSelectedElement ; public static String GotoMatchingBracket_error_invalidSelection ; public static String GotoMatchingBracket_error_noMatchingBracket ; public static String Editor_FoldingMenu_name ; public static String ToggleComment_error_title ; public static String ToggleComment_error_message ; public static String EditorUtility_concatModifierStrings ; public static String ShowRDoc_label ; public static String OverrideIndicatorManager_overrides ; private static ResourceBundle fgResourceBundle = ResourceBundle . getBundle ( BUNDLE_NAME ) ; private static final String BUNDLE_FOR_CONSTRUCTED_KEYS = "" ; private static ResourceBundle fgBundleForConstructedKeys = ResourceBundle . getBundle ( BUNDLE_FOR_CONSTRUCTED_KEYS ) ; public static ResourceBundle getBundleForConstructedKeys ( ) { return fgBundleForConstructedKeys ; } private RubyEditorMessages ( ) { } public static ResourceBundle getResourceBundle ( ) { return fgResourceBundle ; } public static String getFormattedString ( String key , Object [ ] args ) { return MessageFormat . format ( key , args ) ; } public static String getFormattedString ( String key , Object arg ) { return MessageFormat . format ( key , new Object [ ] { arg } ) ; } static { NLS . initializeMessages ( BUNDLE_NAME , RubyEditorMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . Enumeration ; import java . util . Hashtable ; import java . util . List ; import java . util . Vector ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IStatusLineManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . ListenerList ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . IPostSelectionProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . LabelProviderChangedEvent ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . eclipse . ui . model . WorkbenchAdapter ; import org . eclipse . ui . part . IPageSite ; import org . eclipse . ui . part . IShowInSource ; import org . eclipse . ui . part . IShowInTarget ; import org . eclipse . ui . part . IShowInTargetList ; import org . eclipse . ui . part . Page ; import org . eclipse . ui . part . ShowInContext ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . eclipse . ui . texteditor . IUpdate ; import org . eclipse . ui . views . contentoutline . IContentOutlinePage ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . AbstractToggleLinkingAction ; import org . rubypeople . rdt . internal . ui . actions . CompositeActionGroup ; import org . rubypeople . rdt . internal . ui . preferences . MembersOrderPreferenceCache ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . DecoratingRubyLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . StatusBarUpdater ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementSorter ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . actions . CustomFiltersActionGroup ; import org . rubypeople . rdt . ui . actions . MemberFilterActionGroup ; import org . rubypeople . rdt . ui . actions . OpenViewActionGroup ; import org . rubypeople . rdt . ui . actions . RubySearchActionGroup ; import org . rubypeople . rdt . ui . rubyeditor . ICustomRubyOutlinePage ; public class RubyOutlinePage extends Page implements IContentOutlinePage , IAdaptable , IPostSelectionProvider , ICustomRubyOutlinePage { static Object [ ] NO_CHILDREN = new Object [ ] ; class ElementChangedListener implements IElementChangedListener { public void elementChanged ( final ElementChangedEvent e ) { if ( getControl ( ) == null ) return ; Display d = getControl ( ) . getDisplay ( ) ; if ( d != null ) { d . asyncExec ( new Runnable ( ) { public void run ( ) { IRubyScript cu = ( IRubyScript ) fInput ; IRubyElement base = cu ; if ( fTopLevelTypeOnly ) { base = getMainType ( cu ) ; if ( base == null ) { if ( fOutlineViewer != null ) fOutlineViewer . refresh ( true ) ; return ; } } IRubyElementDelta delta = findElement ( base , e . getDelta ( ) ) ; if ( delta != null && fOutlineViewer != null ) { fOutlineViewer . reconcile ( delta ) ; } } } ) ; } } private boolean isPossibleStructuralChange ( IRubyElementDelta cuDelta ) { if ( cuDelta . getKind ( ) != IRubyElementDelta . CHANGED ) { return true ; } int flags = cuDelta . getFlags ( ) ; if ( ( flags & IRubyElementDelta . F_CHILDREN ) != ) { return true ; } return ( flags & ( IRubyElementDelta . F_CONTENT | IRubyElementDelta . F_FINE_GRAINED ) ) == IRubyElementDelta . F_CONTENT ; } protected IRubyElementDelta findElement ( IRubyElement unit , IRubyElementDelta delta ) { if ( delta == null || unit == null ) return null ; IRubyElement element = delta . getElement ( ) ; if ( unit . equals ( element ) ) { if ( isPossibleStructuralChange ( delta ) ) { return delta ; } return null ; } IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; if ( children == null || children . length == ) return null ; for ( int i = ; i < children . length ; i ++ ) { IRubyElementDelta d = findElement ( unit , children [ i ] ) ; if ( d != null ) return d ; } return null ; } } static class NoClassElement extends WorkbenchAdapter implements IAdaptable { public String toString ( ) { return RubyEditorMessages . RubyOutlinePage_error_NoTopLevelType ; } public Object getAdapter ( Class clas ) { if ( clas == IWorkbenchAdapter . class ) return this ; return null ; } } protected class ChildrenProvider implements ITreeContentProvider { private Object [ ] NO_CLASS = new Object [ ] { new NoClassElement ( ) } ; private ElementChangedListener fListener ; protected boolean matches ( IRubyElement element ) { if ( element . getElementType ( ) == IRubyElement . BLOCK ) return true ; return false ; } protected IRubyElement [ ] filter ( IRubyElement [ ] children ) { boolean hasFilterMatches = false ; for ( int i = ; i < children . length ; i ++ ) { if ( matches ( children [ i ] ) ) { hasFilterMatches = true ; break ; } } if ( ! hasFilterMatches ) return children ; Vector < IRubyElement > v = new Vector < IRubyElement > ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( matches ( children [ i ] ) ) continue ; v . addElement ( children [ i ] ) ; } IRubyElement [ ] result = new IRubyElement [ v . size ( ) ] ; v . copyInto ( result ) ; return result ; } public Object [ ] getChildren ( Object parent ) { if ( parent instanceof IParent ) { IParent c = ( IParent ) parent ; try { return filter ( c . getChildren ( ) ) ; } catch ( RubyModelException x ) { if ( RubyPlugin . isDebug ( ) || ! x . isDoesNotExist ( ) ) RubyPlugin . log ( x ) ; } } return NO_CHILDREN ; } public Object [ ] getElements ( Object parent ) { if ( fTopLevelTypeOnly ) { if ( parent instanceof IRubyScript ) { try { IType type = getMainType ( ( IRubyScript ) parent ) ; return type != null ? type . getChildren ( ) : NO_CLASS ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } } return getChildren ( parent ) ; } public Object getParent ( Object child ) { if ( child instanceof IRubyElement ) { IRubyElement e = ( IRubyElement ) child ; return e . getParent ( ) ; } return null ; } public boolean hasChildren ( Object parent ) { if ( parent instanceof IParent ) { IParent c = ( IParent ) parent ; try { IRubyElement [ ] children = filter ( c . getChildren ( ) ) ; return ( children != null && children . length > ) ; } catch ( RubyModelException x ) { if ( RubyPlugin . isDebug ( ) || ! x . isDoesNotExist ( ) ) RubyPlugin . log ( x ) ; } } return false ; } public boolean isDeleted ( Object o ) { return false ; } public void dispose ( ) { if ( fListener != null ) { RubyCore . removeElementChangedListener ( fListener ) ; fListener = null ; } } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { boolean isCU = ( newInput instanceof IRubyScript ) ; if ( isCU && fListener == null ) { fListener = new ElementChangedListener ( ) ; RubyCore . addElementChangedListener ( fListener ) ; } else if ( ! isCU && fListener != null ) { RubyCore . removeElementChangedListener ( fListener ) ; fListener = null ; } } } class RubyOutlineViewer extends TreeViewer { private Item fReusedExpandedItem ; private boolean fReorderedMembers ; private boolean fForceFireSelectionChanged ; public RubyOutlineViewer ( Tree tree ) { super ( tree ) ; setAutoExpandLevel ( ALL_LEVELS ) ; setUseHashlookup ( true ) ; } public void reconcile ( IRubyElementDelta delta ) { fReorderedMembers = false ; fForceFireSelectionChanged = false ; if ( getSorter ( ) == null ) { if ( fTopLevelTypeOnly && delta . getElement ( ) instanceof IType && ( delta . getKind ( ) & IRubyElementDelta . ADDED ) != ) { refresh ( true ) ; } else { if ( fInput instanceof IRubyScript ) { try { IRubyScript script = ( IRubyScript ) fInput ; boolean hasChildren = script . hasChildren ( ) ; if ( ! hasChildren ) { return ; } } catch ( RubyModelException e ) { e . printStackTrace ( ) ; } } Widget w = findItem ( fInput ) ; if ( w != null && ! w . isDisposed ( ) ) update ( w , delta ) ; if ( fForceFireSelectionChanged ) fireSelectionChanged ( new SelectionChangedEvent ( getSite ( ) . getSelectionProvider ( ) , this . getSelection ( ) ) ) ; if ( fReorderedMembers ) { refresh ( false ) ; fReorderedMembers = false ; } } } else { refresh ( true ) ; } } protected void internalExpandToLevel ( Widget node , int level ) { if ( node instanceof Item ) { Item i = ( Item ) node ; if ( i . getData ( ) instanceof IRubyElement ) { IRubyElement je = ( IRubyElement ) i . getData ( ) ; if ( je . getElementType ( ) == IRubyElement . IMPORT_CONTAINER || je . getElementType ( ) == IRubyElement . METHOD ) { if ( i != fReusedExpandedItem ) { setExpanded ( i , false ) ; return ; } } } } super . internalExpandToLevel ( node , level ) ; } protected void reuseTreeItem ( Item item , Object element ) { Item [ ] c = getChildren ( item ) ; if ( c != null && c . length > ) { if ( getExpanded ( item ) ) fReusedExpandedItem = item ; for ( int k = ; k < c . length ; k ++ ) { if ( c [ k ] . getData ( ) != null ) disassociate ( c [ k ] ) ; c [ k ] . dispose ( ) ; } } updateItem ( item , element ) ; updatePlus ( item , element ) ; internalExpandToLevel ( item , ALL_LEVELS ) ; fReusedExpandedItem = null ; fForceFireSelectionChanged = true ; } protected boolean mustUpdateParent ( IRubyElementDelta delta , IRubyElement element ) { return false ; } public boolean isExpandable ( Object element ) { if ( hasFilters ( ) ) { return getFilteredChildren ( element ) . length > ; } return super . isExpandable ( element ) ; } protected ISourceRange getSourceRange ( IRubyElement element ) throws RubyModelException { if ( element instanceof ISourceReference ) return ( ( ISourceReference ) element ) . getSourceRange ( ) ; if ( element instanceof IMember ) return ( ( IMember ) element ) . getNameRange ( ) ; return null ; } protected boolean overlaps ( ISourceRange range , int start , int end ) { return start <= ( range . getOffset ( ) + range . getLength ( ) - ) && range . getOffset ( ) <= end ; } protected boolean filtered ( IRubyElement parent , IRubyElement child ) { Object [ ] result = new Object [ ] { child } ; ViewerFilter [ ] filters = getFilters ( ) ; for ( int i = ; i < filters . length ; i ++ ) { result = filters [ i ] . filter ( this , parent , result ) ; if ( result . length == ) return true ; } return false ; } protected void update ( Widget w , IRubyElementDelta delta ) { Item item ; IRubyElement parent = delta . getElement ( ) ; IRubyElementDelta [ ] affected = delta . getAffectedChildren ( ) ; Item [ ] children = getChildren ( w ) ; boolean doUpdateParent = false ; boolean doUpdateParentsPlus = false ; Vector deletions = new Vector ( ) ; Vector additions = new Vector ( ) ; for ( int i = ; i < affected . length ; i ++ ) { IRubyElementDelta affectedDelta = affected [ i ] ; IRubyElement affectedElement = affectedDelta . getElement ( ) ; int status = affected [ i ] . getKind ( ) ; int j ; for ( j = ; j < children . length ; j ++ ) if ( affectedElement . equals ( children [ j ] . getData ( ) ) ) break ; if ( j == children . length ) { if ( ( status & IRubyElementDelta . REMOVED ) != ) { doUpdateParentsPlus = true ; continue ; } if ( ( status & IRubyElementDelta . CHANGED ) != && ( affectedDelta . getFlags ( ) & IRubyElementDelta . F_MODIFIERS ) != && ! filtered ( parent , affectedElement ) ) { additions . addElement ( affectedDelta ) ; } continue ; } item = children [ j ] ; if ( ( status & IRubyElementDelta . REMOVED ) != ) { deletions . addElement ( item ) ; doUpdateParent = doUpdateParent || mustUpdateParent ( affectedDelta , affectedElement ) ; } else if ( ( status & IRubyElementDelta . CHANGED ) != ) { int change = affectedDelta . getFlags ( ) ; doUpdateParent = doUpdateParent || mustUpdateParent ( affectedDelta , affectedElement ) ; if ( ( change & IRubyElementDelta . F_MODIFIERS ) != ) { if ( filtered ( parent , affectedElement ) ) deletions . addElement ( item ) ; else updateItem ( item , affectedElement ) ; } if ( ( change & IRubyElementDelta . F_CONTENT ) != ) updateItem ( item , affectedElement ) ; if ( ( change & IRubyElementDelta . F_CHILDREN ) != ) update ( item , affectedDelta ) ; if ( ( change & IRubyElementDelta . F_REORDER ) != ) fReorderedMembers = true ; } } IRubyElementDelta [ ] add = delta . getAddedChildren ( ) ; if ( additions . size ( ) > ) { IRubyElementDelta [ ] tmp = new IRubyElementDelta [ add . length + additions . size ( ) ] ; System . arraycopy ( add , , tmp , , add . length ) ; for ( int i = ; i < additions . size ( ) ; i ++ ) tmp [ i + add . length ] = ( IRubyElementDelta ) additions . elementAt ( i ) ; add = tmp ; } go2 : for ( int i = ; i < add . length ; i ++ ) { try { IRubyElement e = add [ i ] . getElement ( ) ; if ( filtered ( parent , e ) ) continue go2 ; doUpdateParent = doUpdateParent || mustUpdateParent ( add [ i ] , e ) ; ISourceRange rng = getSourceRange ( e ) ; int start = rng . getOffset ( ) ; int end = start + rng . getLength ( ) - ; int nameOffset = Integer . MAX_VALUE ; if ( e instanceof IField ) { ISourceRange nameRange = ( ( IField ) e ) . getNameRange ( ) ; if ( nameRange != null ) nameOffset = nameRange . getOffset ( ) ; } Item last = null ; item = null ; children = getChildren ( w ) ; for ( int j = ; j < children . length ; j ++ ) { item = children [ j ] ; IRubyElement r = ( IRubyElement ) item . getData ( ) ; if ( r == null ) { continue go2 ; } try { rng = getSourceRange ( r ) ; boolean multiFieldDeclaration = r . getElementType ( ) == IRubyElement . FIELD && e . getElementType ( ) == IRubyElement . FIELD && rng . getOffset ( ) == start ; boolean multiFieldOrderBefore = false ; if ( multiFieldDeclaration ) { if ( r instanceof IField ) { ISourceRange nameRange = ( ( IField ) r ) . getNameRange ( ) ; if ( nameRange != null ) { if ( nameRange . getOffset ( ) > nameOffset ) multiFieldOrderBefore = true ; } } } if ( ! multiFieldDeclaration && overlaps ( rng , start , end ) ) { reuseTreeItem ( item , e ) ; continue go2 ; } else if ( multiFieldOrderBefore || rng . getOffset ( ) > start ) { if ( last != null && deletions . contains ( last ) ) { deletions . removeElement ( last ) ; reuseTreeItem ( last , e ) ; } else { createTreeItem ( w , e , j ) ; } continue go2 ; } } catch ( RubyModelException x ) { } last = item ; } if ( last != null && deletions . contains ( last ) ) { deletions . removeElement ( last ) ; reuseTreeItem ( last , e ) ; } else { createTreeItem ( w , e , - ) ; } } catch ( RubyModelException x ) { } } Enumeration e = deletions . elements ( ) ; while ( e . hasMoreElements ( ) ) { item = ( Item ) e . nextElement ( ) ; disassociate ( item ) ; item . dispose ( ) ; } if ( doUpdateParent ) updateItem ( w , delta . getElement ( ) ) ; if ( ! doUpdateParent && doUpdateParentsPlus && w instanceof Item ) updatePlus ( ( Item ) w , delta . getElement ( ) ) ; } protected void handleLabelProviderChanged ( LabelProviderChangedEvent event ) { Object input = getInput ( ) ; Object [ ] changed = event . getElements ( ) ; if ( changed != null ) { IResource resource = getUnderlyingResource ( ) ; if ( resource != null ) { for ( int i = ; i < changed . length ; i ++ ) { if ( changed [ i ] != null && changed [ i ] . equals ( resource ) ) { event = new LabelProviderChangedEvent ( ( IBaseLabelProvider ) event . getSource ( ) ) ; break ; } } } } super . handleLabelProviderChanged ( event ) ; } private IResource getUnderlyingResource ( ) { Object input = getInput ( ) ; if ( input instanceof IRubyScript ) { IRubyScript cu = ( IRubyScript ) input ; cu = RubyModelUtil . toOriginal ( cu ) ; return cu . getResource ( ) ; } return null ; } } class LexicalSortingAction extends Action { private RubyElementSorter fSorter = new RubyElementSorter ( ) ; public LexicalSortingAction ( ) { super ( ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . LEXICAL_SORTING_OUTLINE_ACTION ) ; setText ( RubyEditorMessages . RubyOutlinePage_Sort_label ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; setToolTipText ( RubyEditorMessages . RubyOutlinePage_Sort_tooltip ) ; setDescription ( RubyEditorMessages . RubyOutlinePage_Sort_description ) ; boolean checked = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( "" ) ; valueChanged ( checked , false ) ; } public void run ( ) { valueChanged ( isChecked ( ) , true ) ; } private void valueChanged ( final boolean on , boolean store ) { setChecked ( on ) ; BusyIndicator . showWhile ( fOutlineViewer . getControl ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fOutlineViewer . setSorter ( on ? fSorter : null ) ; } } ) ; if ( store ) RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( "" , on ) ; } } class ClassOnlyAction extends Action { public ClassOnlyAction ( ) { super ( ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . GO_INTO_TOP_LEVEL_TYPE_ACTION ) ; setText ( RubyEditorMessages . RubyOutlinePage_GoIntoTopLevelType_label ) ; setToolTipText ( RubyEditorMessages . RubyOutlinePage_GoIntoTopLevelType_tooltip ) ; setDescription ( RubyEditorMessages . RubyOutlinePage_GoIntoTopLevelType_description ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; IPreferenceStore preferenceStore = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; boolean showclass = preferenceStore . getBoolean ( "" ) ; setTopLevelTypeOnly ( showclass ) ; } public void run ( ) { setTopLevelTypeOnly ( ! fTopLevelTypeOnly ) ; } private void setTopLevelTypeOnly ( boolean show ) { fTopLevelTypeOnly = show ; setChecked ( show ) ; fOutlineViewer . refresh ( false ) ; IPreferenceStore preferenceStore = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; preferenceStore . setValue ( "" , show ) ; } } public class ToggleLinkingAction extends AbstractToggleLinkingAction { RubyOutlinePage fRubyOutlinePage ; public ToggleLinkingAction ( RubyOutlinePage outlinePage ) { boolean isLinkingEnabled = PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE ) ; setChecked ( isLinkingEnabled ) ; fRubyOutlinePage = outlinePage ; } public void run ( ) { PreferenceConstants . getPreferenceStore ( ) . setValue ( PreferenceConstants . EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE , isChecked ( ) ) ; if ( isChecked ( ) && fEditor != null ) fEditor . synchronizeOutlinePage ( fEditor . computeHighlightRangeSourceReference ( ) , false ) ; } } private static final class EmptySelectionProvider implements ISelectionProvider { public void addSelectionChangedListener ( ISelectionChangedListener listener ) { } public ISelection getSelection ( ) { return StructuredSelection . EMPTY ; } public void removeSelectionChangedListener ( ISelectionChangedListener listener ) { } public void setSelection ( ISelection selection ) { } } private boolean fTopLevelTypeOnly ; private IRubyElement fInput ; private String fContextMenuID ; private Menu fMenu ; private RubyOutlineViewer fOutlineViewer ; private RubyAbstractEditor fEditor ; private MemberFilterActionGroup fMemberFilterActionGroup ; private ListenerList fSelectionChangedListeners = new ListenerList ( ) ; private ListenerList fPostSelectionChangedListeners = new ListenerList ( ) ; private Hashtable fActions = new Hashtable ( ) ; private TogglePresentationAction fTogglePresentation ; private ToggleLinkingAction fToggleLinkingAction ; private IPropertyChangeListener fPropertyChangeListener ; private CustomFiltersActionGroup fCustomFiltersActionGroup ; private CompositeActionGroup fActionGroups ; public RubyOutlinePage ( ) { super ( ) ; } public void init ( String contextMenuID , RubyAbstractEditor editor ) { Assert . isNotNull ( editor ) ; fContextMenuID = contextMenuID ; fEditor = editor ; fTogglePresentation = new TogglePresentationAction ( ) ; fTogglePresentation . setEditor ( editor ) ; fPropertyChangeListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { doPropertyChange ( event ) ; } } ; RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . addPropertyChangeListener ( fPropertyChangeListener ) ; } protected IType getMainType ( IRubyScript compilationUnit ) { if ( compilationUnit == null ) return null ; String name = compilationUnit . getElementName ( ) ; int index = name . indexOf ( '' ) ; if ( index != - ) name = name . substring ( , index ) ; name = Util . underscoresToCamelCase ( name ) ; IType type = compilationUnit . getType ( name ) ; if ( type . exists ( ) ) return type ; try { IType [ ] types = compilationUnit . getTypes ( ) ; if ( types != null && types . length > ) return types [ ] ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return null ; } public void init ( IPageSite pageSite ) { super . init ( pageSite ) ; } private void doPropertyChange ( PropertyChangeEvent event ) { if ( fOutlineViewer != null ) { if ( MembersOrderPreferenceCache . isMemberOrderProperty ( event . getProperty ( ) ) ) { fOutlineViewer . refresh ( false ) ; } } } public void addSelectionChangedListener ( ISelectionChangedListener listener ) { if ( fOutlineViewer != null ) fOutlineViewer . addSelectionChangedListener ( listener ) ; else fSelectionChangedListeners . add ( listener ) ; } public void removeSelectionChangedListener ( ISelectionChangedListener listener ) { if ( fOutlineViewer != null ) fOutlineViewer . removeSelectionChangedListener ( listener ) ; else fSelectionChangedListeners . remove ( listener ) ; } public void setSelection ( ISelection selection ) { if ( fOutlineViewer != null ) fOutlineViewer . setSelection ( selection ) ; } public ISelection getSelection ( ) { if ( fOutlineViewer == null ) return StructuredSelection . EMPTY ; return fOutlineViewer . getSelection ( ) ; } public void addPostSelectionChangedListener ( ISelectionChangedListener listener ) { if ( fOutlineViewer != null ) fOutlineViewer . addPostSelectionChangedListener ( listener ) ; else fPostSelectionChangedListeners . add ( listener ) ; } public void removePostSelectionChangedListener ( ISelectionChangedListener listener ) { if ( fOutlineViewer != null ) fOutlineViewer . removePostSelectionChangedListener ( listener ) ; else fPostSelectionChangedListeners . remove ( listener ) ; } private void registerToolbarActions ( IActionBars actionBars ) { IToolBarManager toolBarManager = actionBars . getToolBarManager ( ) ; if ( toolBarManager != null ) { toolBarManager . add ( new LexicalSortingAction ( ) ) ; fMemberFilterActionGroup = new MemberFilterActionGroup ( fOutlineViewer , "" ) ; fMemberFilterActionGroup . contributeToToolBar ( toolBarManager ) ; fCustomFiltersActionGroup . fillActionBars ( actionBars ) ; IMenuManager menu = actionBars . getMenuManager ( ) ; menu . add ( new Separator ( "" ) ) ; fToggleLinkingAction = new ToggleLinkingAction ( this ) ; menu . add ( new ClassOnlyAction ( ) ) ; menu . add ( fToggleLinkingAction ) ; } } public void createControl ( Composite parent ) { Tree tree = new Tree ( parent , SWT . MULTI ) ; fOutlineViewer = new RubyOutlineViewer ( tree ) ; fOutlineViewer . setContentProvider ( getContentProvider ( ) ) ; fOutlineViewer . setLabelProvider ( getLabelProvider ( ) ) ; Object [ ] listeners = fSelectionChangedListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { fSelectionChangedListeners . remove ( listeners [ i ] ) ; fOutlineViewer . addSelectionChangedListener ( ( ISelectionChangedListener ) listeners [ i ] ) ; } listeners = fPostSelectionChangedListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { fPostSelectionChangedListeners . remove ( listeners [ i ] ) ; fOutlineViewer . addPostSelectionChangedListener ( ( ISelectionChangedListener ) listeners [ i ] ) ; } MenuManager manager = new MenuManager ( fContextMenuID , fContextMenuID ) ; manager . setRemoveAllWhenShown ( true ) ; manager . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager m ) { contextMenuAboutToShow ( m ) ; } } ) ; fMenu = manager . createContextMenu ( tree ) ; tree . setMenu ( fMenu ) ; IPageSite site = getSite ( ) ; site . registerContextMenu ( RubyPlugin . getPluginId ( ) + "" , manager , fOutlineViewer ) ; updateSelectionProvider ( site ) ; fActionGroups = new CompositeActionGroup ( new ActionGroup [ ] { new OpenViewActionGroup ( this ) , new RubySearchActionGroup ( this ) } ) ; IActionBars actionBars = site . getActionBars ( ) ; actionBars . setGlobalActionHandler ( ITextEditorActionConstants . UNDO , fEditor . getAction ( ITextEditorActionConstants . UNDO ) ) ; actionBars . setGlobalActionHandler ( ITextEditorActionConstants . REDO , fEditor . getAction ( ITextEditorActionConstants . REDO ) ) ; IAction action = fEditor . getAction ( ITextEditorActionConstants . NEXT ) ; actionBars . setGlobalActionHandler ( ITextEditorActionDefinitionIds . GOTO_NEXT_ANNOTATION , action ) ; actionBars . setGlobalActionHandler ( ITextEditorActionConstants . NEXT , action ) ; action = fEditor . getAction ( ITextEditorActionConstants . PREVIOUS ) ; actionBars . setGlobalActionHandler ( ITextEditorActionDefinitionIds . GOTO_PREVIOUS_ANNOTATION , action ) ; actionBars . setGlobalActionHandler ( ITextEditorActionConstants . PREVIOUS , action ) ; actionBars . setGlobalActionHandler ( ITextEditorActionDefinitionIds . TOGGLE_SHOW_SELECTED_ELEMENT_ONLY , fTogglePresentation ) ; IStatusLineManager statusLineManager = actionBars . getStatusLineManager ( ) ; if ( statusLineManager != null ) { StatusBarUpdater updater = new StatusBarUpdater ( statusLineManager ) ; fOutlineViewer . addPostSelectionChangedListener ( updater ) ; } fCustomFiltersActionGroup = new CustomFiltersActionGroup ( "" , fOutlineViewer ) ; registerToolbarActions ( actionBars ) ; fOutlineViewer . setInput ( fInput ) ; } protected IBaseLabelProvider getLabelProvider ( ) { AppearanceAwareLabelProvider lprovider = new AppearanceAwareLabelProvider ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS ) ; return new DecoratingRubyLabelProvider ( lprovider ) ; } protected ITreeContentProvider getContentProvider ( ) { return new ChildrenProvider ( ) ; } private void updateSelectionProvider ( IPageSite site ) { ISelectionProvider provider = fOutlineViewer ; if ( fInput != null ) { IRubyScript cu = ( IRubyScript ) fInput . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null && ! RubyModelUtil . isPrimary ( cu ) ) provider = new EmptySelectionProvider ( ) ; } site . setSelectionProvider ( provider ) ; } public void dispose ( ) { if ( fEditor == null ) return ; if ( fMemberFilterActionGroup != null ) { fMemberFilterActionGroup . dispose ( ) ; fMemberFilterActionGroup = null ; } if ( fCustomFiltersActionGroup != null ) { fCustomFiltersActionGroup . dispose ( ) ; fCustomFiltersActionGroup = null ; } fEditor . outlinePageClosed ( ) ; fEditor = null ; fSelectionChangedListeners . clear ( ) ; fSelectionChangedListeners = null ; fPostSelectionChangedListeners . clear ( ) ; fPostSelectionChangedListeners = null ; if ( fPropertyChangeListener != null ) { RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . removePropertyChangeListener ( fPropertyChangeListener ) ; fPropertyChangeListener = null ; } if ( fMenu != null && ! fMenu . isDisposed ( ) ) { fMenu . dispose ( ) ; fMenu = null ; } if ( fActionGroups != null ) fActionGroups . dispose ( ) ; fTogglePresentation . setEditor ( null ) ; fOutlineViewer = null ; super . dispose ( ) ; } public Control getControl ( ) { if ( fOutlineViewer != null ) return fOutlineViewer . getControl ( ) ; return null ; } public void setInput ( IRubyElement inputElement ) { fInput = inputElement ; if ( fOutlineViewer != null ) { fOutlineViewer . setInput ( fInput ) ; updateSelectionProvider ( getSite ( ) ) ; } } public void select ( ISourceReference reference ) { if ( fOutlineViewer != null ) { ISelection s = fOutlineViewer . getSelection ( ) ; if ( s instanceof IStructuredSelection ) { IStructuredSelection ss = ( IStructuredSelection ) s ; List elements = ss . toList ( ) ; if ( ! elements . contains ( reference ) ) { s = ( reference == null ? StructuredSelection . EMPTY : new StructuredSelection ( reference ) ) ; fOutlineViewer . setSelection ( s , true ) ; } } } } public void setAction ( String actionID , IAction action ) { Assert . isNotNull ( actionID ) ; if ( action == null ) fActions . remove ( actionID ) ; else fActions . put ( actionID , action ) ; } public IAction getAction ( String actionID ) { Assert . isNotNull ( actionID ) ; return ( IAction ) fActions . get ( actionID ) ; } public Object getAdapter ( Class key ) { if ( key == IShowInSource . class ) { return getShowInSource ( ) ; } if ( key == IShowInTargetList . class ) { return new IShowInTargetList ( ) { public String [ ] getShowInTargetIds ( ) { return new String [ ] { RubyUI . ID_RUBY_EXPLORER } ; } } ; } if ( key == IShowInTarget . class ) { return getShowInTarget ( ) ; } return null ; } protected void addAction ( IMenuManager menu , String group , String actionID ) { IAction action = getAction ( actionID ) ; if ( action != null ) { if ( action instanceof IUpdate ) ( ( IUpdate ) action ) . update ( ) ; if ( action . isEnabled ( ) ) { IMenuManager subMenu = menu . findMenuUsingPath ( group ) ; if ( subMenu != null ) subMenu . add ( action ) ; else menu . appendToGroup ( group , action ) ; } } } protected void contextMenuAboutToShow ( IMenuManager menu ) { RubyPlugin . createStandardGroups ( menu ) ; IStructuredSelection selection = ( IStructuredSelection ) getSelection ( ) ; fActionGroups . setContext ( new ActionContext ( selection ) ) ; fActionGroups . fillContextMenu ( menu ) ; } public void setFocus ( ) { if ( fOutlineViewer != null ) fOutlineViewer . getControl ( ) . setFocus ( ) ; } protected IShowInSource getShowInSource ( ) { return new IShowInSource ( ) { public ShowInContext getShowInContext ( ) { return new ShowInContext ( null , getSite ( ) . getSelectionProvider ( ) . getSelection ( ) ) ; } } ; } protected IShowInTarget getShowInTarget ( ) { return new IShowInTarget ( ) { public boolean show ( ShowInContext context ) { ISelection sel = context . getSelection ( ) ; if ( sel instanceof ITextSelection ) { ITextSelection tsel = ( ITextSelection ) sel ; int offset = tsel . getOffset ( ) ; IRubyElement element = fEditor . getElementAt ( offset ) ; if ( element != null ) { setSelection ( new StructuredSelection ( element ) ) ; return true ; } } return false ; } } ; } public boolean isEnabled ( IRubyElement inputElement ) { return false ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextSelection ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . dom . Selection ; import org . rubypeople . rdt . internal . corext . dom . SelectionAnalyzer ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; public class RubyTextSelection extends TextSelection { private IRubyElement fElement ; private IRubyElement [ ] fResolvedElements ; private boolean fEnclosingElementRequested ; private IRubyElement fEnclosingElement ; private boolean fPartialASTRequested ; private RootNode fPartialAST ; private boolean fNodesRequested ; private Node [ ] fSelectedNodes ; private Node fCoveringNode ; private boolean fInMethodBodyRequested ; private boolean fInMethodBody ; public RubyTextSelection ( IRubyElement element , IDocument document , int offset , int length ) { super ( document , offset , length ) ; fElement = element ; } public IRubyElement [ ] resolveElementAtOffset ( ) throws RubyModelException { if ( fResolvedElements != null ) return fResolvedElements ; fResolvedElements = SelectionConverter . codeResolve ( fElement , this ) ; return fResolvedElements ; } public IRubyElement resolveEnclosingElement ( ) throws RubyModelException { if ( fEnclosingElementRequested ) return fEnclosingElement ; fEnclosingElementRequested = true ; fEnclosingElement = SelectionConverter . resolveEnclosingElement ( fElement , this ) ; return fEnclosingElement ; } public RootNode resolvePartialAstAtOffset ( ) { if ( fPartialASTRequested ) return fPartialAST ; fPartialASTRequested = true ; if ( ! ( fElement instanceof IRubyScript ) ) return null ; fPartialAST = ( RootNode ) RubyPlugin . getDefault ( ) . getASTProvider ( ) . getAST ( fElement , ASTProvider . WAIT_YES , null ) ; return fPartialAST ; } public Node [ ] resolveSelectedNodes ( ) { if ( fNodesRequested ) return fSelectedNodes ; fNodesRequested = true ; RootNode root = resolvePartialAstAtOffset ( ) ; if ( root == null ) return null ; Selection ds = Selection . createFromStartLength ( getOffset ( ) , getLength ( ) ) ; SelectionAnalyzer analyzer = new SelectionAnalyzer ( ds , false ) ; root . accept ( analyzer ) ; fSelectedNodes = analyzer . getSelectedNodes ( ) ; fCoveringNode = analyzer . getLastCoveringNode ( ) ; return fSelectedNodes ; } public Node resolveCoveringNode ( ) { if ( fNodesRequested ) return fCoveringNode ; resolveSelectedNodes ( ) ; return fCoveringNode ; } public boolean resolveInMethodBody ( ) { if ( fInMethodBodyRequested ) return fInMethodBody ; fInMethodBodyRequested = true ; resolveSelectedNodes ( ) ; Node node = getStartNode ( ) ; if ( node == null ) { fInMethodBody = true ; } else { Node spanner = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( resolvePartialAstAtOffset ( ) , node . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof MethodDefNode ; } } ) ; if ( spanner != null ) fInMethodBody = true ; } return fInMethodBody ; } private Node getStartNode ( ) { if ( fSelectedNodes != null && fSelectedNodes . length > ) return fSelectedNodes [ ] ; else return fCoveringNode ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . rubypeople . rdt . core . IRubyScript ; public interface ISavePolicy { void preSave ( IRubyScript unit ) ; IRubyScript postSave ( IRubyScript unit ) ; } package org . rubypeople . rdt . internal . ui . rubyeditor ; import java . util . Iterator ; import org . eclipse . core . resources . IMarker ; import org . eclipse . ui . texteditor . MarkerAnnotation ; import org . eclipse . ui . texteditor . MarkerUtilities ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; public class RubyMarkerAnnotation extends MarkerAnnotation implements IRubyAnnotation { public static final String RUBY_MARKER_TYPE_PREFIX = "" ; public static final String ERROR_ANNOTATION_TYPE = "" ; public static final String WARNING_ANNOTATION_TYPE = "" ; public static final String INFO_ANNOTATION_TYPE = "" ; public static final String TASK_ANNOTATION_TYPE = "" ; private IRubyAnnotation fOverlay ; public RubyMarkerAnnotation ( IMarker marker ) { super ( marker ) ; } public String [ ] getArguments ( ) { return null ; } public int getId ( ) { IMarker marker = getMarker ( ) ; if ( marker == null || ! marker . exists ( ) ) return - ; if ( isProblem ( ) ) return marker . getAttribute ( IRubyModelMarker . ID , - ) ; return - ; } public boolean isProblem ( ) { String type = getType ( ) ; return WARNING_ANNOTATION_TYPE . equals ( type ) || ERROR_ANNOTATION_TYPE . equals ( type ) ; } public void setOverlay ( IRubyAnnotation RubyAnnotation ) { if ( fOverlay != null ) fOverlay . removeOverlaid ( this ) ; fOverlay = RubyAnnotation ; if ( ! isMarkedDeleted ( ) ) markDeleted ( fOverlay != null ) ; if ( fOverlay != null ) fOverlay . addOverlaid ( this ) ; } public boolean hasOverlay ( ) { return fOverlay != null ; } public IRubyAnnotation getOverlay ( ) { return fOverlay ; } public void addOverlaid ( IRubyAnnotation annotation ) { } public void removeOverlaid ( IRubyAnnotation annotation ) { } public Iterator getOverlaidIterator ( ) { return null ; } public IRubyScript getRubyScript ( ) { IRubyElement element = RubyCore . create ( getMarker ( ) . getResource ( ) ) ; if ( element instanceof IRubyScript ) { return ( IRubyScript ) element ; } return null ; } public String getMarkerType ( ) { IMarker marker = getMarker ( ) ; if ( marker == null || ! marker . exists ( ) ) return null ; return MarkerUtilities . getMarkerType ( getMarker ( ) ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; public class GotoAnnotationAction extends TextEditorAction { private boolean fForward ; public GotoAnnotationAction ( String prefix , boolean forward ) { super ( RubyEditorMessages . getResourceBundle ( ) , prefix , null ) ; fForward = forward ; if ( forward ) { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . GOTO_NEXT_ERROR_ACTION ) ; } else { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . GOTO_PREVIOUS_ERROR_ACTION ) ; } } public void run ( ) { RubyEditor e = ( RubyEditor ) getTextEditor ( ) ; e . gotoAnnotation ( fForward ) ; } public void setEditor ( ITextEditor editor ) { if ( editor instanceof RubyEditor ) super . setEditor ( editor ) ; update ( ) ; } public void update ( ) { setEnabled ( getTextEditor ( ) instanceof RubyEditor ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import org . eclipse . ui . IEditorInput ; import org . rubypeople . rdt . core . IRubyScript ; public interface IRubyScriptEditorInput extends IEditorInput { public IRubyScript getRubyScript ( ) ; } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdapterFactory ; import org . rubypeople . rdt . core . IRubyProject ; public class RubyProjectAdapterFactory implements IAdapterFactory { private static Class [ ] PROPERTIES = new Class [ ] { IProject . class , } ; public Class [ ] getAdapterList ( ) { return PROPERTIES ; } public Object getAdapter ( Object element , Class key ) { if ( IProject . class . equals ( key ) ) { IRubyProject rubyProject = ( IRubyProject ) element ; return rubyProject . getProject ( ) ; } return null ; } } package org . rubypeople . rdt . internal . ui . util ; import java . io . StringWriter ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; public class ExceptionHandler { private static ExceptionHandler fgInstance = new ExceptionHandler ( ) ; public static void log ( Throwable t , String message ) { RubyPlugin . getDefault ( ) . getLog ( ) . log ( new Status ( IStatus . ERROR , RubyPlugin . PLUGIN_ID , IStatus . ERROR , message , t ) ) ; } public static void handle ( CoreException e , String title , String message ) { handle ( e , RubyPlugin . getActiveWorkbenchShell ( ) , title , message ) ; } public static void handle ( CoreException e , Shell parent , String title , String message ) { fgInstance . perform ( e , parent , title , message ) ; } public static void handle ( InvocationTargetException e , String title , String message ) { handle ( e , RubyPlugin . getActiveWorkbenchShell ( ) , title , message ) ; } public static void handle ( InvocationTargetException e , Shell parent , String title , String message ) { fgInstance . perform ( e , parent , title , message ) ; } protected void perform ( CoreException e , Shell shell , String title , String message ) { RubyPlugin . log ( e ) ; IStatus status = e . getStatus ( ) ; if ( status != null ) { ErrorDialog . openError ( shell , title , message , status ) ; } else { displayMessageDialog ( e , e . getMessage ( ) , shell , title , message ) ; } } protected void perform ( InvocationTargetException e , Shell shell , String title , String message ) { Throwable target = e . getTargetException ( ) ; if ( target instanceof CoreException ) { perform ( ( CoreException ) target , shell , title , message ) ; } else { RubyPlugin . log ( e ) ; if ( e . getMessage ( ) != null && e . getMessage ( ) . length ( ) > ) { displayMessageDialog ( e , e . getMessage ( ) , shell , title , message ) ; } else { displayMessageDialog ( e , target . getMessage ( ) , shell , title , message ) ; } } } private void displayMessageDialog ( Throwable t , String exceptionMessage , Shell shell , String title , String message ) { StringWriter msg = new StringWriter ( ) ; if ( message != null ) { msg . write ( message ) ; msg . write ( "" ) ; } if ( exceptionMessage == null || exceptionMessage . length ( ) == ) msg . write ( RubyUIMessages . ExceptionDialog_seeErrorLogMessage ) ; else msg . write ( exceptionMessage ) ; MessageDialog . openError ( shell , title , msg . toString ( ) ) ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . internal . corext . util . TypeInfo ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class TypeInfoLabelProvider extends LabelProvider { public static final int SHOW_FULLYQUALIFIED = ; public static final int SHOW_PACKAGE_POSTFIX = ; public static final int SHOW_PACKAGE_ONLY = ; public static final int SHOW_ROOT_POSTFIX = ; public static final int SHOW_TYPE_ONLY = ; public static final int SHOW_TYPE_CONTAINER_ONLY = ; public static final int SHOW_POST_QUALIFIED = ; private static final Image CLASS_ICON = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_CLASS ) ; private static final Image MODULE_ICON = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_MODULE ) ; private static final Image PKG_ICON = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_SOURCE_FOLDER ) ; private int fFlags ; public TypeInfoLabelProvider ( int flags ) { fFlags = flags ; } private boolean isSet ( int flag ) { return ( fFlags & flag ) != ; } private String getPackageName ( String packName ) { if ( packName . length ( ) == ) return RubyUIMessages . TypeInfoLabelProvider_default_package ; else return packName ; } public String getText ( Object element ) { if ( ! ( element instanceof TypeInfo ) ) return super . getText ( element ) ; TypeInfo typeRef = ( TypeInfo ) element ; StringBuffer buf = new StringBuffer ( ) ; if ( isSet ( SHOW_TYPE_ONLY ) ) { buf . append ( typeRef . getTypeName ( ) ) ; } else if ( isSet ( SHOW_TYPE_CONTAINER_ONLY ) ) { String containerName = typeRef . getTypeContainerName ( ) ; buf . append ( getPackageName ( containerName ) ) ; } else if ( isSet ( SHOW_PACKAGE_ONLY ) ) { String packName = typeRef . getPackageName ( ) ; buf . append ( getPackageName ( packName ) ) ; } else { if ( isSet ( SHOW_FULLYQUALIFIED ) ) { buf . append ( typeRef . getFullyQualifiedName ( ) ) ; } else if ( isSet ( SHOW_POST_QUALIFIED ) ) { buf . append ( typeRef . getTypeName ( ) ) ; String containerName = typeRef . getTypeContainerName ( ) ; if ( containerName != null && containerName . length ( ) > ) { buf . append ( RubyElementLabels . CONCAT_STRING ) ; buf . append ( containerName ) ; } } else { buf . append ( typeRef . getTypeQualifiedName ( ) ) ; } if ( isSet ( SHOW_PACKAGE_POSTFIX ) ) { buf . append ( RubyElementLabels . CONCAT_STRING ) ; String packName = typeRef . getPackageName ( ) ; buf . append ( getPackageName ( packName ) ) ; } } if ( isSet ( SHOW_ROOT_POSTFIX ) ) { buf . append ( RubyElementLabels . CONCAT_STRING ) ; buf . append ( typeRef . getPackageFragmentRootPath ( ) . toString ( ) ) ; } return buf . toString ( ) ; } public Image getImage ( Object element ) { if ( ! ( element instanceof TypeInfo ) ) return super . getImage ( element ) ; if ( isSet ( SHOW_TYPE_CONTAINER_ONLY ) ) { TypeInfo typeRef = ( TypeInfo ) element ; if ( typeRef . getPackageName ( ) . equals ( typeRef . getTypeContainerName ( ) ) ) return PKG_ICON ; return CLASS_ICON ; } else if ( isSet ( SHOW_PACKAGE_ONLY ) ) { return PKG_ICON ; } else { boolean isModule = ( ( TypeInfo ) element ) . isModule ( ) ; if ( isModule ) { return MODULE_ICON ; } return CLASS_ICON ; } } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . WorkbenchException ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . actions . OpenActionUtil ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . typehierarchy . TypeHierarchyViewPart ; import org . rubypeople . rdt . ui . RubyUI ; public class OpenTypeHierarchyUtil { private OpenTypeHierarchyUtil ( ) { } public static TypeHierarchyViewPart open ( IRubyElement element , IWorkbenchWindow window ) { IRubyElement [ ] candidates = getCandidates ( element ) ; if ( candidates != null ) { return open ( candidates , window ) ; } return null ; } public static TypeHierarchyViewPart open ( IRubyElement [ ] candidates , IWorkbenchWindow window ) { Assert . isTrue ( candidates != null && candidates . length != ) ; IRubyElement input = null ; if ( candidates . length > ) { String title = RubyUIMessages . OpenTypeHierarchyUtil_selectionDialog_title ; String message = RubyUIMessages . OpenTypeHierarchyUtil_selectionDialog_message ; input = OpenActionUtil . selectRubyElement ( candidates , window . getShell ( ) , title , message ) ; } else { input = candidates [ ] ; } if ( input == null ) return null ; return openInViewPart ( window , input ) ; } private static TypeHierarchyViewPart openInViewPart ( IWorkbenchWindow window , IRubyElement input ) { IWorkbenchPage page = window . getActivePage ( ) ; try { TypeHierarchyViewPart result = ( TypeHierarchyViewPart ) page . findView ( RubyUI . ID_TYPE_HIERARCHY ) ; if ( result != null ) { result . clearNeededRefresh ( ) ; } result = ( TypeHierarchyViewPart ) page . showView ( RubyUI . ID_TYPE_HIERARCHY ) ; result . setInputElement ( input ) ; return result ; } catch ( CoreException e ) { ExceptionHandler . handle ( e , window . getShell ( ) , RubyUIMessages . OpenTypeHierarchyUtil_error_open_view , e . getMessage ( ) ) ; } return null ; } private static TypeHierarchyViewPart openInPerspective ( IWorkbenchWindow window , IRubyElement input ) throws WorkbenchException , RubyModelException { IWorkbench workbench = RubyPlugin . getDefault ( ) . getWorkbench ( ) ; IRubyElement perspectiveInput = input ; if ( input instanceof IMember ) { if ( input . getElementType ( ) != IRubyElement . TYPE ) { perspectiveInput = ( ( IMember ) input ) . getDeclaringType ( ) ; } else { perspectiveInput = input ; } } IWorkbenchPage page = workbench . showPerspective ( RubyUI . ID_HIERARCHYPERSPECTIVE , window , perspectiveInput ) ; TypeHierarchyViewPart part = ( TypeHierarchyViewPart ) page . findView ( RubyUI . ID_TYPE_HIERARCHY ) ; if ( part != null ) { part . clearNeededRefresh ( ) ; } part = ( TypeHierarchyViewPart ) page . showView ( RubyUI . ID_TYPE_HIERARCHY ) ; part . setInputElement ( input ) ; if ( input instanceof IMember ) { if ( page . getEditorReferences ( ) . length == ) { openEditor ( input , false ) ; } } return part ; } private static void openEditor ( Object input , boolean activate ) throws PartInitException , RubyModelException { IEditorPart part = EditorUtility . openInEditor ( input , activate ) ; if ( input instanceof IRubyElement ) EditorUtility . revealInEditor ( part , ( IRubyElement ) input ) ; } public static IRubyElement [ ] getCandidates ( Object input ) { if ( ! ( input instanceof IRubyElement ) ) { return null ; } try { IRubyElement elem = ( IRubyElement ) input ; switch ( elem . getElementType ( ) ) { case IRubyElement . METHOD : case IRubyElement . FIELD : case IRubyElement . TYPE : case IRubyElement . SOURCE_FOLDER_ROOT : case IRubyElement . RUBY_PROJECT : return new IRubyElement [ ] { elem } ; case IRubyElement . SOURCE_FOLDER : if ( ( ( ISourceFolder ) elem ) . containsRubyResources ( ) ) return new IRubyElement [ ] { elem } ; break ; case IRubyElement . IMPORT_DECLARATION : IImportDeclaration decl = ( IImportDeclaration ) elem ; elem = elem . getRubyProject ( ) . findType ( elem . getElementName ( ) ) ; if ( elem == null ) return null ; return new IRubyElement [ ] { elem } ; case IRubyElement . SCRIPT : { IRubyScript cu = ( IRubyScript ) elem . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) { IType [ ] types = cu . getTypes ( ) ; if ( types . length > ) { return types ; } } break ; } default : } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return null ; } } package org . rubypeople . rdt . internal . ui . util ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ControlAdapter ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ColumnLayoutData ; import org . eclipse . jface . viewers . ColumnPixelData ; import org . eclipse . jface . viewers . ColumnWeightData ; public class TableLayoutComposite extends Composite { private List columns = new ArrayList ( ) ; public TableLayoutComposite ( Composite parent , int style ) { super ( parent , style ) ; addControlListener ( new ControlAdapter ( ) { public void controlResized ( ControlEvent e ) { Rectangle area = getClientArea ( ) ; Table table = ( Table ) getChildren ( ) [ ] ; Point preferredSize = computeTableSize ( table ) ; int width = area . width - * table . getBorderWidth ( ) ; if ( preferredSize . y > area . height ) { Point vBarSize = table . getVerticalBar ( ) . getSize ( ) ; width -= vBarSize . x ; } layoutTable ( table , width , area , table . getSize ( ) . x < area . width ) ; } } ) ; } public void addColumnData ( ColumnLayoutData data ) { columns . add ( data ) ; } private Point computeTableSize ( Table table ) { Point result = table . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; int width = ; int size = columns . size ( ) ; for ( int i = ; i < size ; ++ i ) { ColumnLayoutData layoutData = ( ColumnLayoutData ) columns . get ( i ) ; if ( layoutData instanceof ColumnPixelData ) { ColumnPixelData col = ( ColumnPixelData ) layoutData ; width += col . width ; } else if ( layoutData instanceof ColumnWeightData ) { ColumnWeightData col = ( ColumnWeightData ) layoutData ; width += col . minimumWidth ; } else { Assert . isTrue ( false , "" ) ; } } if ( width > result . x ) result . x = width ; return result ; } private void layoutTable ( Table table , int width , Rectangle area , boolean increase ) { if ( width <= ) return ; TableColumn [ ] tableColumns = table . getColumns ( ) ; int size = Math . min ( columns . size ( ) , tableColumns . length ) ; int [ ] widths = new int [ size ] ; int fixedWidth = ; int numberOfWeightColumns = ; int totalWeight = ; for ( int i = ; i < size ; i ++ ) { ColumnLayoutData col = ( ColumnLayoutData ) columns . get ( i ) ; if ( col instanceof ColumnPixelData ) { int pixels = ( ( ColumnPixelData ) col ) . width ; widths [ i ] = pixels ; fixedWidth += pixels ; } else if ( col instanceof ColumnWeightData ) { ColumnWeightData cw = ( ColumnWeightData ) col ; numberOfWeightColumns ++ ; int weight = cw . weight ; totalWeight += weight ; } else { Assert . isTrue ( false , "" ) ; } } if ( numberOfWeightColumns > ) { int rest = width - fixedWidth ; int totalDistributed = ; for ( int i = ; i < size ; ++ i ) { ColumnLayoutData col = ( ColumnLayoutData ) columns . get ( i ) ; if ( col instanceof ColumnWeightData ) { ColumnWeightData cw = ( ColumnWeightData ) col ; int weight = cw . weight ; int pixels = totalWeight == ? : weight * rest / totalWeight ; if ( pixels < cw . minimumWidth ) pixels = cw . minimumWidth ; totalDistributed += pixels ; widths [ i ] = pixels ; } } int diff = rest - totalDistributed ; for ( int i = ; diff > ; ++ i ) { if ( i == size ) i = ; ColumnLayoutData col = ( ColumnLayoutData ) columns . get ( i ) ; if ( col instanceof ColumnWeightData ) { ++ widths [ i ] ; -- diff ; } } } if ( increase ) { table . setSize ( area . width , area . height ) ; } for ( int i = ; i < size ; i ++ ) { tableColumns [ i ] . setWidth ( widths [ i ] ) ; } if ( ! increase ) { table . setSize ( area . width , area . height ) ; } } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . model . WorkbenchLabelProvider ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . ElementListSelectionDialog ; public class RubyProjectSelector extends ResourceSelector { public RubyProjectSelector ( Composite parent ) { super ( parent ) ; browseDialogTitle = "" ; } public IProject getSelection ( ) { String projectName = getSelectionText ( ) ; if ( projectName != null && ! projectName . equals ( "" ) ) return RubyPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; return null ; } protected void handleBrowseSelected ( ) { ElementListSelectionDialog dialog = new ElementListSelectionDialog ( getShell ( ) , new WorkbenchLabelProvider ( ) ) ; dialog . setTitle ( browseDialogTitle ) ; dialog . setMessage ( browseDialogMessage ) ; dialog . setElements ( RubyCore . getRubyProjects ( ) ) ; if ( dialog . open ( ) == Dialog . OK ) { textField . setText ( ( ( IProject ) dialog . getFirstResult ( ) ) . getName ( ) ) ; } } protected String validateResourceSelection ( ) { IProject project = getSelection ( ) ; return project == null ? EMPTY_STRING : project . getName ( ) ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public abstract class ResourceSelector { protected final static String EMPTY_STRING = "" ; protected Composite composite ; protected Button browseButton ; protected Text textField ; protected String browseDialogMessage = EMPTY_STRING ; protected String browseDialogTitle = EMPTY_STRING ; protected String validatedSelectionText = EMPTY_STRING ; public ResourceSelector ( Composite parent ) { composite = new Composite ( parent , SWT . NONE ) ; GridLayout compositeLayout = new GridLayout ( ) ; compositeLayout . marginWidth = ; compositeLayout . marginHeight = ; compositeLayout . numColumns = ; composite . setLayout ( compositeLayout ) ; textField = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; textField . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; textField . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { validatedSelectionText = validateResourceSelection ( ) ; } } ) ; browseButton = new Button ( composite , SWT . PUSH ) ; browseButton . setText ( "" ) ; browseButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { handleBrowseSelected ( ) ; } } ) ; } protected abstract void handleBrowseSelected ( ) ; protected abstract String validateResourceSelection ( ) ; protected Shell getShell ( ) { return composite . getShell ( ) ; } public void setLayoutData ( Object layoutData ) { composite . setLayoutData ( layoutData ) ; } public void addModifyListener ( ModifyListener aListener ) { textField . addModifyListener ( aListener ) ; } public void setBrowseDialogMessage ( String aMessage ) { browseDialogMessage = aMessage ; } public void setBrowseDialogTitle ( String aTitle ) { browseDialogTitle = aTitle ; } public void setEnabled ( boolean enabled ) { composite . setEnabled ( enabled ) ; textField . setEnabled ( enabled ) ; browseButton . setEnabled ( enabled ) ; } public String getSelectionText ( ) { return textField . getText ( ) ; } public String getValidatedSelectionText ( ) { return validatedSelectionText ; } public void setSelectionText ( String newText ) { textField . setText ( newText ) ; } } package org . rubypeople . rdt . internal . ui . util ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceVisitor ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyFileMatcher ; public class RubyElementVisitor implements IResourceVisitor { protected List rubyFiles ; protected RubyFileMatcher rubyFileMatcher ; public RubyElementVisitor ( ) { rubyFiles = new ArrayList ( ) ; rubyFileMatcher = RubyPlugin . getDefault ( ) . getRubyFileMatcher ( ) ; } public boolean visit ( IResource resource ) throws CoreException { switch ( resource . getType ( ) ) { case IResource . PROJECT : return true ; case IResource . FOLDER : return true ; case IResource . FILE : IFile fileResource = ( IFile ) resource ; if ( rubyFileMatcher . hasRubyEditorAssociation ( fileResource ) ) { this . rubyFiles . add ( resource ) ; return true ; } return false ; default : return false ; } } public Object [ ] getCollectedRubyFiles ( ) { return rubyFiles . toArray ( ) ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . util . Assert ; import org . eclipse . swt . SWT ; import org . eclipse . swt . dnd . DragSource ; import org . eclipse . swt . dnd . DropTarget ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Caret ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . ScrollBar ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . Widget ; public class SWTUtil { public static Display getStandardDisplay ( ) { Display display ; display = Display . getCurrent ( ) ; if ( display == null ) display = Display . getDefault ( ) ; return display ; } public static Shell getShell ( Widget widget ) { if ( widget instanceof Control ) return ( ( Control ) widget ) . getShell ( ) ; if ( widget instanceof Caret ) return ( ( Caret ) widget ) . getParent ( ) . getShell ( ) ; if ( widget instanceof DragSource ) return ( ( DragSource ) widget ) . getControl ( ) . getShell ( ) ; if ( widget instanceof DropTarget ) return ( ( DropTarget ) widget ) . getControl ( ) . getShell ( ) ; if ( widget instanceof Menu ) return ( ( Menu ) widget ) . getParent ( ) . getShell ( ) ; if ( widget instanceof ScrollBar ) return ( ( ScrollBar ) widget ) . getParent ( ) . getShell ( ) ; return null ; } public static int getButtonWidthHint ( Button button ) { button . setFont ( JFaceResources . getDialogFont ( ) ) ; PixelConverter converter = new PixelConverter ( button ) ; int widthHint = converter . convertHorizontalDLUsToPixels ( IDialogConstants . BUTTON_WIDTH ) ; return Math . max ( widthHint , button . computeSize ( SWT . DEFAULT , SWT . DEFAULT , true ) . x ) ; } public static void setButtonDimensionHint ( Button button ) { Assert . isNotNull ( button ) ; Object gd = button . getLayoutData ( ) ; if ( gd instanceof GridData ) { ( ( GridData ) gd ) . widthHint = getButtonWidthHint ( button ) ; ( ( GridData ) gd ) . horizontalAlignment = GridData . FILL ; } } public static int getTableHeightHint ( Table table , int rows ) { if ( table . getFont ( ) . equals ( JFaceResources . getDefaultFont ( ) ) ) table . setFont ( JFaceResources . getDialogFont ( ) ) ; int result = table . getItemHeight ( ) * rows + table . getHeaderHeight ( ) ; if ( table . getLinesVisible ( ) ) result += table . getGridLineWidth ( ) * ( rows - ) ; return result ; } public static int getButtonHeightHint ( Button button ) { button . setFont ( JFaceResources . getDialogFont ( ) ) ; PixelConverter converter = new PixelConverter ( button ) ; return converter . convertVerticalDLUsToPixels ( IDialogConstants . BUTTON_HEIGHT ) ; } } package org . rubypeople . rdt . internal . ui . util ; import java . util . List ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; public class SelectionUtil { public static List toList ( ISelection selection ) { if ( selection instanceof IStructuredSelection ) return ( ( IStructuredSelection ) selection ) . toList ( ) ; return null ; } public static Object getSingleElement ( ISelection s ) { if ( ! ( s instanceof IStructuredSelection ) ) return null ; IStructuredSelection selection = ( IStructuredSelection ) s ; if ( selection . size ( ) != ) return null ; return selection . getFirstElement ( ) ; } } package org . rubypeople . rdt . internal . ui . util ; import java . util . Comparator ; import org . eclipse . core . runtime . Assert ; public class TwoArrayQuickSorter { private Comparator fComparator ; public static final class StringComparator implements Comparator < String > { private boolean fIgnoreCase ; StringComparator ( boolean ignoreCase ) { fIgnoreCase = ignoreCase ; } public int compare ( String left , String right ) { return fIgnoreCase ? left . compareToIgnoreCase ( right ) : left . compareTo ( right ) ; } } public TwoArrayQuickSorter ( boolean ignoreCase ) { fComparator = new StringComparator ( ignoreCase ) ; } public TwoArrayQuickSorter ( Comparator < ? extends Object > comparator ) { fComparator = comparator ; } public void sort ( Object [ ] keys , Object [ ] values ) { if ( ( keys == null ) || ( values == null ) ) { Assert . isTrue ( false , "" ) ; return ; } if ( keys . length <= ) return ; internalSort ( keys , values , , keys . length - ) ; } private void internalSort ( Object [ ] keys , Object [ ] values , int left , int right ) { int original_left = left ; int original_right = right ; Object mid = keys [ ( left + right ) / ] ; do { while ( fComparator . compare ( keys [ left ] , mid ) < ) left ++ ; while ( fComparator . compare ( mid , keys [ right ] ) < ) right -- ; if ( left <= right ) { swap ( keys , left , right ) ; swap ( values , left , right ) ; left ++ ; right -- ; } } while ( left <= right ) ; if ( original_left < right ) internalSort ( keys , values , original_left , right ) ; if ( left < original_right ) internalSort ( keys , values , left , original_right ) ; } private static final void swap ( Object x [ ] , int a , int b ) { Object t = x [ a ] ; x [ a ] = x [ b ] ; x [ b ] = t ; } } package org . rubypeople . rdt . internal . ui . util ; import java . io . File ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . eclipse . core . resources . IProject ; import org . rubypeople . rdt . core . IRubyProject ; public class StackTraceLine { private static Pattern OPEN_TRACE_LINE_PATTERN = Pattern . compile ( "" ) ; private static Pattern BRACKETED_TRACE_LINE_PATTERN = Pattern . compile ( "" ) ; private static Pattern OPTIONAL_PREFIX = Pattern . compile ( "" ) ; private String fFilename ; private int fLineNumber ; private int length ; private int offset ; public static boolean isTraceLine ( String line ) { Matcher bracketedMatcher = BRACKETED_TRACE_LINE_PATTERN . matcher ( line ) ; Matcher openMatcher = OPEN_TRACE_LINE_PATTERN . matcher ( line ) ; return bracketedMatcher . find ( ) || openMatcher . find ( ) ; } public StackTraceLine ( String traceLine ) { this ( traceLine , ( IProject ) null ) ; } public StackTraceLine ( String traceLine , IRubyProject launchedProject ) { this ( traceLine , launchedProject . getProject ( ) ) ; } public StackTraceLine ( String traceLine , IProject launchedProject ) { int prefix = ; Matcher matcher = OPTIONAL_PREFIX . matcher ( traceLine ) ; if ( matcher . find ( ) ) { traceLine = traceLine . substring ( matcher . group ( ) . length ( ) ) ; prefix = matcher . group ( ) . length ( ) ; } matcher = BRACKETED_TRACE_LINE_PATTERN . matcher ( traceLine ) ; if ( ! matcher . find ( ) ) { matcher = OPEN_TRACE_LINE_PATTERN . matcher ( traceLine ) ; if ( ! matcher . find ( ) ) return ; } fFilename = matcher . group ( ) ; offset = matcher . start ( ) + prefix ; if ( fFilename . startsWith ( "" ) ) { fFilename = fFilename . substring ( ) ; offset ++ ; } String lineNumber = matcher . group ( ) ; fLineNumber = Integer . parseInt ( lineNumber ) ; length = fFilename . length ( ) + lineNumber . length ( ) + ; if ( isRelativePath ( ) && launchedProject != null ) { makeRelativeToWorkspace ( launchedProject ) ; } } private void makeRelativeToWorkspace ( IProject launchedProject ) { if ( fFilename . startsWith ( "" ) ) { fFilename = launchedProject . getFullPath ( ) . toPortableString ( ) + fFilename . substring ( ) ; } else if ( fFilename . startsWith ( "" ) ) { fFilename = launchedProject . getFullPath ( ) . toPortableString ( ) + fFilename ; } else { fFilename = launchedProject . getFullPath ( ) . toPortableString ( ) + '' + fFilename ; } } private boolean isRelativePath ( ) { if ( fFilename . startsWith ( "" ) ) return true ; if ( fFilename . startsWith ( "" ) ) { File file = new File ( fFilename ) ; if ( file . exists ( ) ) return false ; return true ; } if ( fFilename . contains ( "" ) ) return false ; return false ; } public void openEditor ( ) { if ( fFilename == null ) return ; new LineBasedEditorOpener ( fFilename , fLineNumber ) . open ( ) ; } public int getLineNumber ( ) { return fLineNumber ; } public String getFilename ( ) { return fFilename ; } public int offset ( ) { return offset ; } public int length ( ) { return length ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceDescription ; import org . eclipse . core . resources . IncrementalProjectBuilder ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . swt . custom . BusyIndicator ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; public class CoreUtility { public static void createFolder ( IFolder folder , boolean force , boolean local , IProgressMonitor monitor ) throws CoreException { if ( ! folder . exists ( ) ) { IContainer parent = folder . getParent ( ) ; if ( parent instanceof IFolder ) { createFolder ( ( IFolder ) parent , force , local , null ) ; } folder . create ( force , local , monitor ) ; } } public static Object createExtension ( final IConfigurationElement element , final String classAttribute ) throws CoreException { String pluginId = element . getNamespace ( ) ; Bundle bundle = Platform . getBundle ( pluginId ) ; if ( bundle != null && bundle . getState ( ) == Bundle . ACTIVE ) { return element . createExecutableExtension ( classAttribute ) ; } else { final Object [ ] ret = new Object [ ] ; final CoreException [ ] exc = new CoreException [ ] ; BusyIndicator . showWhile ( null , new Runnable ( ) { public void run ( ) { try { ret [ ] = element . createExecutableExtension ( classAttribute ) ; } catch ( CoreException e ) { exc [ ] = e ; } } } ) ; if ( exc [ ] != null ) throw exc [ ] ; else return ret [ ] ; } } public static void startBuildInBackground ( final IProject project ) { getBuildJob ( project ) . schedule ( ) ; } private static final class BuildJob extends Job { private final IProject fProject ; private BuildJob ( String name , IProject project ) { super ( name ) ; fProject = project ; } public boolean isCoveredBy ( BuildJob other ) { if ( other . fProject == null ) { return true ; } return fProject != null && fProject . equals ( other . fProject ) ; } protected IStatus run ( IProgressMonitor monitor ) { synchronized ( getClass ( ) ) { if ( monitor . isCanceled ( ) ) { return Status . CANCEL_STATUS ; } Job [ ] buildJobs = Platform . getJobManager ( ) . find ( ResourcesPlugin . FAMILY_MANUAL_BUILD ) ; for ( int i = ; i < buildJobs . length ; i ++ ) { Job curr = buildJobs [ i ] ; if ( curr != this && curr instanceof BuildJob ) { BuildJob job = ( BuildJob ) curr ; if ( job . isCoveredBy ( this ) ) { curr . cancel ( ) ; } } } } try { if ( fProject != null ) { monitor . beginTask ( Messages . format ( RubyUIMessages . CoreUtility_buildproject_taskname , fProject . getName ( ) ) , ) ; fProject . build ( IncrementalProjectBuilder . FULL_BUILD , new SubProgressMonitor ( monitor , ) ) ; RubyPlugin . getWorkspace ( ) . build ( IncrementalProjectBuilder . INCREMENTAL_BUILD , new SubProgressMonitor ( monitor , ) ) ; } else { monitor . beginTask ( RubyUIMessages . CoreUtility_buildall_taskname , ) ; RubyPlugin . getWorkspace ( ) . build ( IncrementalProjectBuilder . FULL_BUILD , new SubProgressMonitor ( monitor , ) ) ; } } catch ( CoreException e ) { return e . getStatus ( ) ; } catch ( OperationCanceledException e ) { return Status . CANCEL_STATUS ; } finally { monitor . done ( ) ; } return Status . OK_STATUS ; } public boolean belongsTo ( Object family ) { return ResourcesPlugin . FAMILY_MANUAL_BUILD == family ; } } public static Job getBuildJob ( final IProject project ) { Job buildJob = new BuildJob ( RubyUIMessages . CoreUtility_job_title , project ) ; buildJob . setRule ( ResourcesPlugin . getWorkspace ( ) . getRuleFactory ( ) . buildRule ( ) ) ; buildJob . setUser ( true ) ; return buildJob ; } public static boolean enableAutoBuild ( boolean state ) throws CoreException { IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; IWorkspaceDescription desc = workspace . getDescription ( ) ; boolean isAutoBuilding = desc . isAutoBuilding ( ) ; if ( isAutoBuilding != state ) { desc . setAutoBuilding ( state ) ; workspace . setDescription ( desc ) ; } return isAutoBuilding ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . ui . IEditorDescriptor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorRegistry ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . FileEditorInput ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . ExternalRubyFileEditorInput ; public abstract class EditorOpener { private final String filename ; public EditorOpener ( String filename ) { this . filename = filename ; } public void open ( ) { try { IEditorInput fileEditorInput = createEditorInput ( filename ) ; IWorkbench workbench = PlatformUI . getWorkbench ( ) ; IEditorRegistry editorRegistry = workbench . getEditorRegistry ( ) ; IWorkbenchPage page = workbench . getActiveWorkbenchWindow ( ) . getActivePage ( ) ; IEditorDescriptor descriptor = editorRegistry . getDefaultEditor ( filename ) ; if ( descriptor == null ) return ; ITextEditor editor = ( ITextEditor ) page . openEditor ( fileEditorInput , editorId ( descriptor ) ) ; setEditorPosition ( editor ) ; } catch ( PartInitException e ) { RubyPlugin . log ( e ) ; } } protected abstract void setEditorPosition ( ITextEditor editor ) ; private String editorId ( IEditorDescriptor descriptor ) { String editorId ; if ( descriptor == null ) { editorId = "" ; } else { editorId = descriptor . getId ( ) ; } return editorId ; } private IEditorInput createEditorInput ( String filename ) { IFile file = getWorkspaceFile ( filename ) ; if ( file == null ) return new ExternalRubyFileEditorInput ( new java . io . File ( filename ) ) ; return new FileEditorInput ( file ) ; } private IFile getWorkspaceFile ( String filename ) { IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; IWorkspaceRoot root = workspace . getRoot ( ) ; IPath filepath = new Path ( filename ) ; IFile file = root . getFileForLocation ( filepath ) ; return file ; } } package org . rubypeople . rdt . internal . ui . util ; import java . util . Vector ; public class StringMatcher { protected String fPattern ; protected int fLength ; protected boolean fIgnoreWildCards ; protected boolean fIgnoreCase ; protected boolean fHasLeadingStar ; protected boolean fHasTrailingStar ; protected String fSegments [ ] ; protected int fBound = ; protected static final char fSingleWildCard = '' ; public static class Position { int start ; int end ; public Position ( int start , int end ) { this . start = start ; this . end = end ; } public int getStart ( ) { return start ; } public int getEnd ( ) { return end ; } } public StringMatcher ( String pattern , boolean ignoreCase , boolean ignoreWildCards ) { if ( pattern == null ) throw new IllegalArgumentException ( ) ; fIgnoreCase = ignoreCase ; fIgnoreWildCards = ignoreWildCards ; fPattern = pattern ; fLength = pattern . length ( ) ; if ( fIgnoreWildCards ) { parseNoWildCards ( ) ; } else { parseWildCards ( ) ; } } public StringMatcher . Position find ( String text , int start , int end ) { if ( text == null ) throw new IllegalArgumentException ( ) ; int tlen = text . length ( ) ; if ( start < ) start = ; if ( end > tlen ) end = tlen ; if ( end < || start >= end ) return null ; if ( fLength == ) return new Position ( start , start ) ; if ( fIgnoreWildCards ) { int x = posIn ( text , start , end ) ; if ( x < ) return null ; return new Position ( x , x + fLength ) ; } int segCount = fSegments . length ; if ( segCount == ) return new Position ( start , end ) ; int curPos = start ; int matchStart = - ; int i ; for ( i = ; i < segCount && curPos < end ; ++ i ) { String current = fSegments [ i ] ; int nextMatch = regExpPosIn ( text , curPos , end , current ) ; if ( nextMatch < ) return null ; if ( i == ) matchStart = nextMatch ; curPos = nextMatch + current . length ( ) ; } if ( i < segCount ) return null ; return new Position ( matchStart , curPos ) ; } public boolean match ( String text ) { if ( null == text ) throw new IllegalArgumentException ( ) ; return match ( text , , text . length ( ) ) ; } public boolean match ( String text , int start , int end ) { if ( null == text ) throw new IllegalArgumentException ( ) ; if ( start > end ) return false ; if ( fIgnoreWildCards ) return ( end - start == fLength ) && fPattern . regionMatches ( fIgnoreCase , , text , start , fLength ) ; int segCount = fSegments . length ; if ( segCount == && ( fHasLeadingStar || fHasTrailingStar ) ) return true ; if ( start == end ) return fLength == ; if ( fLength == ) return start == end ; int tlen = text . length ( ) ; if ( start < ) start = ; if ( end > tlen ) end = tlen ; int tCurPos = start ; int bound = end - fBound ; if ( bound < ) return false ; int i = ; String current = fSegments [ i ] ; int segLength = current . length ( ) ; if ( ! fHasLeadingStar ) { if ( ! regExpRegionMatches ( text , start , current , , segLength ) ) { return false ; } ++ i ; tCurPos = tCurPos + segLength ; } while ( i < segCount ) { current = fSegments [ i ] ; int currentMatch ; int k = current . indexOf ( fSingleWildCard ) ; if ( k < ) { currentMatch = textPosIn ( text , tCurPos , end , current ) ; if ( currentMatch < ) return false ; } else { currentMatch = regExpPosIn ( text , tCurPos , end , current ) ; if ( currentMatch < ) return false ; } tCurPos = currentMatch + current . length ( ) ; i ++ ; } if ( ! fHasTrailingStar && tCurPos != end ) { int clen = current . length ( ) ; return regExpRegionMatches ( text , end - clen , current , , clen ) ; } return i == segCount ; } private void parseNoWildCards ( ) { fSegments = new String [ ] ; fSegments [ ] = fPattern ; fBound = fLength ; } private void parseWildCards ( ) { if ( fPattern . startsWith ( "" ) ) fHasLeadingStar = true ; if ( fPattern . endsWith ( "" ) ) { if ( fLength > && fPattern . charAt ( fLength - ) != '' ) { fHasTrailingStar = true ; } } Vector temp = new Vector ( ) ; int pos = ; StringBuffer buf = new StringBuffer ( ) ; while ( pos < fLength ) { char c = fPattern . charAt ( pos ++ ) ; switch ( c ) { case '' : if ( pos >= fLength ) { buf . append ( c ) ; } else { char next = fPattern . charAt ( pos ++ ) ; if ( next == '' || next == '' || next == '' ) { buf . append ( next ) ; } else { buf . append ( c ) ; buf . append ( next ) ; } } break ; case '' : if ( buf . length ( ) > ) { temp . addElement ( buf . toString ( ) ) ; fBound += buf . length ( ) ; buf . setLength ( ) ; } break ; case '' : buf . append ( fSingleWildCard ) ; break ; default : buf . append ( c ) ; } } if ( buf . length ( ) > ) { temp . addElement ( buf . toString ( ) ) ; fBound += buf . length ( ) ; } fSegments = new String [ temp . size ( ) ] ; temp . copyInto ( fSegments ) ; } protected int posIn ( String text , int start , int end ) { int max = end - fLength ; if ( ! fIgnoreCase ) { int i = text . indexOf ( fPattern , start ) ; if ( i == - || i > max ) return - ; return i ; } for ( int i = start ; i <= max ; ++ i ) { if ( text . regionMatches ( true , i , fPattern , , fLength ) ) return i ; } return - ; } protected int regExpPosIn ( String text , int start , int end , String p ) { int plen = p . length ( ) ; int max = end - plen ; for ( int i = start ; i <= max ; ++ i ) { if ( regExpRegionMatches ( text , i , p , , plen ) ) return i ; } return - ; } protected boolean regExpRegionMatches ( String text , int tStart , String p , int pStart , int plen ) { while ( plen -- > ) { char tchar = text . charAt ( tStart ++ ) ; char pchar = p . charAt ( pStart ++ ) ; if ( ! fIgnoreWildCards ) { if ( pchar == fSingleWildCard ) { continue ; } } if ( pchar == tchar ) continue ; if ( fIgnoreCase ) { if ( Character . toUpperCase ( tchar ) == Character . toUpperCase ( pchar ) ) continue ; if ( Character . toLowerCase ( tchar ) == Character . toLowerCase ( pchar ) ) continue ; } return false ; } return true ; } protected int textPosIn ( String text , int start , int end , String p ) { int plen = p . length ( ) ; int max = end - plen ; if ( ! fIgnoreCase ) { int i = text . indexOf ( p , start ) ; if ( i == - || i > max ) return - ; return i ; } for ( int i = start ; i <= max ; ++ i ) { if ( text . regionMatches ( true , i , p , , plen ) ) return i ; } return - ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . jface . text . IDocument ; import org . eclipse . ui . texteditor . ITextEditor ; import org . jruby . lexer . yacc . ISourcePosition ; public class PositionBasedEditorOpener extends EditorOpener { private final ISourcePosition position ; public PositionBasedEditorOpener ( String filename , ISourcePosition position ) { super ( filename ) ; this . position = position ; } protected void setEditorPosition ( ITextEditor editor ) { IDocument document = editor . getDocumentProvider ( ) . getDocument ( editor . getEditorInput ( ) ) ; int start = position . getStartOffset ( ) ; int end = position . getEndOffset ( ) ; editor . selectAndReveal ( start , end - start ) ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . ui . texteditor . ITextEditor ; public class LineBasedEditorOpener extends EditorOpener { private final int lineNumber ; public LineBasedEditorOpener ( String filename , int lineNumber ) { super ( filename ) ; this . lineNumber = lineNumber ; } protected void setEditorPosition ( ITextEditor editor ) { try { if ( lineNumber > ) { IDocument document = editor . getDocumentProvider ( ) . getDocument ( editor . getEditorInput ( ) ) ; int offset = document . getLineOffset ( lineNumber - ) ; int length = document . getLineLength ( lineNumber - ) ; editor . selectAndReveal ( offset , length ) ; } } catch ( BadLocationException doNothing ) { } } } package org . rubypeople . rdt . internal . ui . util ; import java . io . File ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . FileDialog ; public class FileSelector extends ResourceSelector { public FileSelector ( Composite parent ) { super ( parent ) ; } @ Override protected void handleBrowseSelected ( ) { FileDialog dialog = new FileDialog ( getShell ( ) ) ; dialog . setText ( browseDialogMessage ) ; setFilterPath ( dialog ) ; String selectedFile = dialog . open ( ) ; if ( selectedFile != null ) { setText ( selectedFile ) ; } } protected void setText ( String selectedFile ) { textField . setText ( selectedFile ) ; } protected boolean setFilterPath ( FileDialog dialog ) { String currentWorkingDir = textField . getText ( ) ; if ( ! currentWorkingDir . trim ( ) . equals ( "" ) ) { File path = new File ( currentWorkingDir ) ; if ( path . exists ( ) ) { dialog . setFilterPath ( currentWorkingDir ) ; return true ; } } return false ; } @ Override protected String validateResourceSelection ( ) { String file = textField . getText ( ) ; File directoryFile = new File ( file ) ; if ( directoryFile . exists ( ) && directoryFile . isFile ( ) ) return file ; return EMPTY_STRING ; } public File getSelection ( ) { return new File ( getSelectionText ( ) ) ; } } package org . rubypeople . rdt . internal . ui . util ; import java . io . File ; import org . eclipse . core . resources . IProject ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . FileDialog ; public class ProjectFileSelector extends FileSelector { private RubyProjectSelector selector ; public ProjectFileSelector ( Composite parent , RubyProjectSelector selector ) { super ( parent ) ; this . selector = selector ; } @ Override protected boolean setFilterPath ( FileDialog dialog ) { boolean set = super . setFilterPath ( dialog ) ; if ( ! set ) { IProject project = selector . getSelection ( ) ; if ( project == null ) return false ; String filename = textField . getText ( ) ; if ( filename != null && filename . trim ( ) . length ( ) != ) { File projectFile = project . getLocation ( ) . append ( filename ) . toFile ( ) ; if ( projectFile . exists ( ) ) { dialog . setFilterPath ( projectFile . getParent ( ) ) ; return true ; } } dialog . setFilterPath ( project . getLocation ( ) . toOSString ( ) ) ; return true ; } return set ; } @ Override protected void setText ( String selectedFile ) { IProject project = selector . getSelection ( ) ; if ( project != null ) { String projectAbsolutePath = project . getLocation ( ) . toFile ( ) . toString ( ) ; if ( selectedFile . startsWith ( projectAbsolutePath ) ) { selectedFile = selectedFile . substring ( projectAbsolutePath . length ( ) + ) ; } } super . setText ( selectedFile ) ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . swt . graphics . FontMetrics ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . widgets . Control ; import org . eclipse . jface . dialogs . Dialog ; public class PixelConverter { private FontMetrics fFontMetrics ; public PixelConverter ( Control control ) { GC gc = new GC ( control ) ; gc . setFont ( control . getFont ( ) ) ; fFontMetrics = gc . getFontMetrics ( ) ; gc . dispose ( ) ; } public int convertHeightInCharsToPixels ( int chars ) { return Dialog . convertHeightInCharsToPixels ( fFontMetrics , chars ) ; } public int convertHorizontalDLUsToPixels ( int dlus ) { return Dialog . convertHorizontalDLUsToPixels ( fFontMetrics , dlus ) ; } public int convertVerticalDLUsToPixels ( int dlus ) { return Dialog . convertVerticalDLUsToPixels ( fFontMetrics , dlus ) ; } public int convertWidthInCharsToPixels ( int chars ) { return Dialog . convertWidthInCharsToPixels ( fFontMetrics , chars ) ; } } package org . rubypeople . rdt . internal . ui . util ; import java . util . Collection ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . Viewer ; public class CollectionContentProvider implements IStructuredContentProvider { public Object [ ] getElements ( Object inputElement ) { Object [ ] res = null ; if ( inputElement instanceof Collection ) { res = ( ( Collection ) inputElement ) . toArray ( ) ; } return res ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void dispose ( ) { } } package org . rubypeople . rdt . internal . ui . util ; import java . util . Comparator ; import java . util . HashSet ; import java . util . Set ; import java . util . Vector ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; public class FilteredList extends Composite { public interface FilterMatcher { void setFilter ( String pattern , boolean ignoreCase , boolean ignoreWildCards ) ; boolean match ( Object element ) ; } private class DefaultFilterMatcher implements FilterMatcher { private StringMatcher fMatcher ; public void setFilter ( String pattern , boolean ignoreCase , boolean ignoreWildCards ) { fMatcher = new StringMatcher ( pattern + '' , ignoreCase , ignoreWildCards ) ; } public boolean match ( Object element ) { return fMatcher . match ( fRenderer . getText ( element ) ) ; } } private Table fList ; private ILabelProvider fRenderer ; private boolean fMatchEmtpyString = true ; private boolean fIgnoreCase ; private boolean fAllowDuplicates ; private String fFilter = "" ; private TwoArrayQuickSorter fSorter ; private Object [ ] fElements = new Object [ ] ; private Label [ ] fLabels ; private Vector fImages = new Vector ( ) ; private int [ ] fFoldedIndices ; private int fFoldedCount ; private int [ ] fFilteredIndices ; private int fFilteredCount ; private FilterMatcher fFilterMatcher = new DefaultFilterMatcher ( ) ; private Comparator fComparator ; private static class Label { public final String string ; public final Image image ; public Label ( String string , Image image ) { this . string = string ; this . image = image ; } public boolean equals ( Label label ) { if ( label == null ) return false ; return string . equals ( label . string ) && image . equals ( label . image ) ; } } private final class LabelComparator implements Comparator { private boolean fIgnoreCase ; LabelComparator ( boolean ignoreCase ) { fIgnoreCase = ignoreCase ; } public int compare ( Object left , Object right ) { Label leftLabel = ( Label ) left ; Label rightLabel = ( Label ) right ; int value ; if ( fComparator == null ) { value = fIgnoreCase ? leftLabel . string . compareToIgnoreCase ( rightLabel . string ) : leftLabel . string . compareTo ( rightLabel . string ) ; } else { value = fComparator . compare ( leftLabel . string , rightLabel . string ) ; } if ( value != ) return value ; if ( leftLabel . image == null ) { return ( rightLabel . image == null ) ? : - ; } else if ( rightLabel . image == null ) { return + ; } else { return fImages . indexOf ( leftLabel . image ) - fImages . indexOf ( rightLabel . image ) ; } } } public FilteredList ( Composite parent , int style , ILabelProvider renderer , boolean ignoreCase , boolean allowDuplicates , boolean matchEmptyString ) { super ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; setLayout ( layout ) ; fList = new Table ( this , style ) ; fList . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; fList . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { fRenderer . dispose ( ) ; } } ) ; fRenderer = renderer ; fIgnoreCase = ignoreCase ; fSorter = new TwoArrayQuickSorter ( new LabelComparator ( ignoreCase ) ) ; fAllowDuplicates = allowDuplicates ; fMatchEmtpyString = matchEmptyString ; } public void setElements ( Object [ ] elements ) { if ( elements == null ) { fElements = new Object [ ] ; } else { fElements = new Object [ elements . length ] ; System . arraycopy ( elements , , fElements , , elements . length ) ; } int length = fElements . length ; fLabels = new Label [ length ] ; Set imageSet = new HashSet ( ) ; for ( int i = ; i != length ; i ++ ) { String text = fRenderer . getText ( fElements [ i ] ) ; Image image = fRenderer . getImage ( fElements [ i ] ) ; fLabels [ i ] = new Label ( text , image ) ; imageSet . add ( image ) ; } fImages . clear ( ) ; fImages . addAll ( imageSet ) ; fSorter . sort ( fLabels , fElements ) ; fFilteredIndices = new int [ length ] ; fFilteredCount = filter ( ) ; fFoldedIndices = new int [ length ] ; fFoldedCount = fold ( ) ; updateList ( ) ; } public boolean isEmpty ( ) { return ( fElements == null ) || ( fElements . length == ) ; } public void setFilterMatcher ( FilterMatcher filterMatcher ) { Assert . isNotNull ( filterMatcher ) ; fFilterMatcher = filterMatcher ; } public void setComparator ( Comparator comparator ) { Assert . isNotNull ( comparator ) ; fComparator = comparator ; } public void addSelectionListener ( SelectionListener listener ) { fList . addSelectionListener ( listener ) ; } public void removeSelectionListener ( SelectionListener listener ) { fList . removeSelectionListener ( listener ) ; } public void setSelection ( int [ ] selection ) { fList . setSelection ( selection ) ; } public int [ ] getSelectionIndices ( ) { return fList . getSelectionIndices ( ) ; } public int getSelectionIndex ( ) { return fList . getSelectionIndex ( ) ; } public void setSelection ( Object [ ] elements ) { if ( ( elements == null ) || ( fElements == null ) ) return ; int [ ] indices = new int [ elements . length ] ; for ( int i = ; i != elements . length ; i ++ ) { int j ; for ( j = ; j != fFoldedCount ; j ++ ) { int max = ( j == fFoldedCount - ) ? fFilteredCount : fFoldedIndices [ j + ] ; int l ; for ( l = fFoldedIndices [ j ] ; l != max ; l ++ ) { if ( fElements [ fFilteredIndices [ l ] ] . equals ( elements [ i ] ) ) { indices [ i ] = j ; break ; } } if ( l != max ) break ; } if ( j == fFoldedCount ) indices [ i ] = ; } fList . setSelection ( indices ) ; } public Object [ ] getSelection ( ) { if ( fList . isDisposed ( ) || ( fList . getSelectionCount ( ) == ) ) return new Object [ ] ; int [ ] indices = fList . getSelectionIndices ( ) ; Object [ ] elements = new Object [ indices . length ] ; for ( int i = ; i != indices . length ; i ++ ) elements [ i ] = fElements [ fFilteredIndices [ fFoldedIndices [ indices [ i ] ] ] ] ; return elements ; } public void setFilter ( String filter ) { fFilter = ( filter == null ) ? "" : filter ; fFilteredCount = filter ( ) ; fFoldedCount = fold ( ) ; updateList ( ) ; } public String getFilter ( ) { return fFilter ; } public Object [ ] getFoldedElements ( int index ) { if ( ( index < ) || ( index >= fFoldedCount ) ) return null ; int start = fFoldedIndices [ index ] ; int count = ( index == fFoldedCount - ) ? fFilteredCount - start : fFoldedIndices [ index + ] - start ; Object [ ] elements = new Object [ count ] ; for ( int i = ; i != count ; i ++ ) elements [ i ] = fElements [ fFilteredIndices [ start + i ] ] ; return elements ; } private int fold ( ) { if ( fAllowDuplicates ) { for ( int i = ; i != fFilteredCount ; i ++ ) fFoldedIndices [ i ] = i ; return fFilteredCount ; } int k = ; Label last = null ; for ( int i = ; i != fFilteredCount ; i ++ ) { int j = fFilteredIndices [ i ] ; Label current = fLabels [ j ] ; if ( ! current . equals ( last ) ) { fFoldedIndices [ k ] = i ; k ++ ; last = current ; } } return k ; } private int filter ( ) { if ( ( ( fFilter == null ) || ( fFilter . length ( ) == ) ) && ! fMatchEmtpyString ) return ; fFilterMatcher . setFilter ( fFilter . trim ( ) , fIgnoreCase , false ) ; int k = ; for ( int i = ; i != fElements . length ; i ++ ) { if ( fFilterMatcher . match ( fElements [ i ] ) ) fFilteredIndices [ k ++ ] = i ; } return k ; } private void updateList ( ) { if ( fList . isDisposed ( ) ) return ; fList . setRedraw ( false ) ; int itemCount = fList . getItemCount ( ) ; if ( fFoldedCount < itemCount ) fList . remove ( , itemCount - fFoldedCount - ) ; else if ( fFoldedCount > itemCount ) for ( int i = ; i != fFoldedCount - itemCount ; i ++ ) new TableItem ( fList , SWT . NONE ) ; TableItem [ ] items = fList . getItems ( ) ; for ( int i = ; i != fFoldedCount ; i ++ ) { TableItem item = items [ i ] ; Label label = fLabels [ fFilteredIndices [ fFoldedIndices [ i ] ] ] ; item . setText ( label . string ) ; item . setImage ( label . image ) ; } if ( fList . getItemCount ( ) > ) fList . setSelection ( ) ; fList . setRedraw ( true ) ; fList . notifyListeners ( SWT . Selection , new Event ( ) ) ; } } package org . rubypeople . rdt . internal . ui . util ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CLabel ; import org . eclipse . swt . custom . ViewForm ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . ToolBar ; import org . eclipse . jface . action . ToolBarManager ; public class ViewerPane extends ViewForm { private ToolBarManager fToolBarManager ; public ViewerPane ( Composite parent , int style ) { super ( parent , style ) ; marginWidth = ; marginHeight = ; CLabel label = new CLabel ( this , SWT . NONE ) ; setTopLeft ( label ) ; ToolBar tb = new ToolBar ( this , SWT . FLAT ) ; setTopCenter ( tb ) ; fToolBarManager = new ToolBarManager ( tb ) ; } public void setText ( String label ) { CLabel cl = ( CLabel ) getTopLeft ( ) ; cl . setText ( label ) ; } public String getText ( ) { CLabel cl = ( CLabel ) getTopLeft ( ) ; return cl . getText ( ) ; } public void setImage ( Image image ) { CLabel cl = ( CLabel ) getTopLeft ( ) ; cl . setImage ( image ) ; } public Image getImage ( ) { CLabel cl = ( CLabel ) getTopLeft ( ) ; return cl . getImage ( ) ; } public ToolBarManager getToolBarManager ( ) { return fToolBarManager ; } } package org . rubypeople . rdt . internal . ui . util ; import java . io . File ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . DirectoryDialog ; public class DirectorySelector extends ResourceSelector { public DirectorySelector ( Composite parent ) { super ( parent ) ; } protected void handleBrowseSelected ( ) { DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) ) ; dialog . setMessage ( browseDialogMessage ) ; String currentWorkingDir = textField . getText ( ) ; if ( ! currentWorkingDir . trim ( ) . equals ( "" ) ) { File path = new File ( currentWorkingDir ) ; if ( path . exists ( ) ) { dialog . setFilterPath ( currentWorkingDir ) ; } } String selectedDirectory = dialog . open ( ) ; if ( selectedDirectory != null ) { textField . setText ( selectedDirectory ) ; } } protected String validateResourceSelection ( ) { String directory = textField . getText ( ) ; File directoryFile = new File ( directory ) ; if ( directoryFile . exists ( ) && directoryFile . isDirectory ( ) ) return directory ; return EMPTY_STRING ; } } package org . rubypeople . rdt . internal . ui . commands ; import org . eclipse . core . commands . AbstractParameterValueConverter ; import org . eclipse . core . commands . ParameterValueConversionException ; import org . eclipse . core . resources . ResourcesPlugin ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; public class RubyElementReferenceConverter extends AbstractParameterValueConverter { private static final char PROJECT_END_CHAR = '' ; private static final char TYPE_END_CHAR = '' ; public Object convertToObject ( String parameterValue ) throws ParameterValueConversionException { assertWellFormed ( parameterValue != null ) ; final int projectEndPosition = parameterValue . indexOf ( PROJECT_END_CHAR ) ; assertWellFormed ( projectEndPosition != - ) ; String projectName = parameterValue . substring ( , projectEndPosition ) ; String javaElementRef = parameterValue . substring ( projectEndPosition + ) ; IRubyModel javaModel = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; assertExists ( javaModel ) ; IRubyProject javaProject = javaModel . getRubyProject ( projectName ) ; assertExists ( javaProject ) ; final int typeEndPosition = javaElementRef . indexOf ( TYPE_END_CHAR ) ; String typeName ; if ( typeEndPosition == - ) { typeName = javaElementRef ; } else { typeName = javaElementRef . substring ( , typeEndPosition ) ; } IType type = null ; try { type = javaProject . findType ( typeName ) ; } catch ( RubyModelException ex ) { } assertExists ( type ) ; if ( typeEndPosition == - ) { return type ; } String memberRef = javaElementRef . substring ( typeEndPosition + ) ; IField field = type . getField ( memberRef ) ; if ( field != null && field . exists ( ) ) { return field ; } String [ ] parameterTypes = null ; IMethod method = type . getMethod ( memberRef , parameterTypes ) ; assertExists ( method ) ; return method ; } private void assertWellFormed ( boolean assertion ) throws ParameterValueConversionException { if ( ! assertion ) { throw new ParameterValueConversionException ( "" ) ; } } private void assertExists ( IRubyElement javaElement ) throws ParameterValueConversionException { if ( ( javaElement == null ) || ( ! javaElement . exists ( ) ) ) { throw new ParameterValueConversionException ( "" ) ; } } public String convertToString ( Object parameterValue ) throws ParameterValueConversionException { if ( ! ( parameterValue instanceof IRubyElement ) ) { throw new ParameterValueConversionException ( "" ) ; } IRubyElement javaElement = ( IRubyElement ) parameterValue ; IRubyProject javaProject = javaElement . getRubyProject ( ) ; if ( javaProject == null ) { throw new ParameterValueConversionException ( "" ) ; } StringBuffer buffer ; if ( javaElement instanceof IType ) { IType type = ( IType ) javaElement ; buffer = composeTypeReference ( type ) ; } else if ( javaElement instanceof IMethod ) { IMethod method = ( IMethod ) javaElement ; buffer = composeTypeReference ( method . getDeclaringType ( ) ) ; buffer . append ( TYPE_END_CHAR ) ; buffer . append ( method . getElementName ( ) ) ; } else if ( javaElement instanceof IField ) { IField field = ( IField ) javaElement ; buffer = composeTypeReference ( field . getDeclaringType ( ) ) ; buffer . append ( TYPE_END_CHAR ) ; buffer . append ( field . getElementName ( ) ) ; } else { throw new ParameterValueConversionException ( "" ) ; } return buffer . toString ( ) ; } private StringBuffer composeTypeReference ( IType type ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( type . getRubyProject ( ) . getElementName ( ) ) ; buffer . append ( PROJECT_END_CHAR ) ; buffer . append ( type . getFullyQualifiedName ( ) ) ; return buffer ; } } package org . rubypeople . rdt . internal . ui . commands ; import org . eclipse . core . commands . AbstractHandler ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . ui . IWorkbenchWindow ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . OpenTypeHierarchyUtil ; public class ShowElementInTypeHierarchyViewHandler extends AbstractHandler { private static final String PARAM_ID_ELEMENT_REF = "" ; public Object execute ( ExecutionEvent event ) throws ExecutionException { IWorkbenchWindow window = RubyPlugin . getActiveWorkbenchWindow ( ) ; if ( window == null ) return null ; IRubyElement rubyElement = ( IRubyElement ) event . getObjectParameterForExecution ( PARAM_ID_ELEMENT_REF ) ; OpenTypeHierarchyUtil . open ( rubyElement , window ) ; return null ; } } package org . rubypeople . rdt . internal . ui ; public interface IRubyStatusConstants { public static final int INTERNAL_ERROR = ; public static final int VALIDATE_EDIT_CHANGED_CONTENT = ; } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class ShowInheritedMembersAction extends Action { private MethodsViewer fMethodsViewer ; public ShowInheritedMembersAction ( MethodsViewer viewer , boolean initValue ) { super ( TypeHierarchyMessages . ShowInheritedMembersAction_label ) ; setDescription ( TypeHierarchyMessages . ShowInheritedMembersAction_description ) ; setToolTipText ( TypeHierarchyMessages . ShowInheritedMembersAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; fMethodsViewer = viewer ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . SHOW_INHERITED_ACTION ) ; setChecked ( initValue ) ; } public void run ( ) { BusyIndicator . showWhile ( fMethodsViewer . getControl ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fMethodsViewer . showInheritedMethods ( isChecked ( ) ) ; } } ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . rubypeople . rdt . internal . ui . actions . AbstractToggleLinkingAction ; public class ToggleLinkingAction extends AbstractToggleLinkingAction { TypeHierarchyViewPart fHierarchyViewPart ; public ToggleLinkingAction ( TypeHierarchyViewPart part ) { setChecked ( part . isLinkingEnabled ( ) ) ; fHierarchyViewPart = part ; } public void run ( ) { fHierarchyViewPart . setLinkingEnabled ( isChecked ( ) ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; public class HierarchyViewerSorter extends AbstractHierarchyViewerSorter { private final TypeHierarchyLifeCycle fHierarchy ; private boolean fSortByDefiningType ; public HierarchyViewerSorter ( TypeHierarchyLifeCycle cycle ) { fHierarchy = cycle ; } public void setSortByDefiningType ( boolean sortByDefiningType ) { fSortByDefiningType = sortByDefiningType ; } protected int getTypeFlags ( IType type ) { ITypeHierarchy hierarchy = getHierarchy ( type ) ; if ( hierarchy != null ) { return fHierarchy . getHierarchy ( ) . getCachedFlags ( type ) ; } return ; } public boolean isSortByDefiningType ( ) { return fSortByDefiningType ; } public boolean isSortAlphabetically ( ) { return true ; } protected ITypeHierarchy getHierarchy ( IType type ) { return fHierarchy . getHierarchy ( ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class ToggleOrientationAction extends Action { private TypeHierarchyViewPart fView ; private int fActionOrientation ; public ToggleOrientationAction ( TypeHierarchyViewPart v , int orientation ) { super ( "" , AS_RADIO_BUTTON ) ; if ( orientation == TypeHierarchyViewPart . VIEW_ORIENTATION_HORIZONTAL ) { setText ( TypeHierarchyMessages . ToggleOrientationAction_horizontal_label ) ; setDescription ( TypeHierarchyMessages . ToggleOrientationAction_horizontal_description ) ; setToolTipText ( TypeHierarchyMessages . ToggleOrientationAction_horizontal_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( orientation == TypeHierarchyViewPart . VIEW_ORIENTATION_VERTICAL ) { setText ( TypeHierarchyMessages . ToggleOrientationAction_vertical_label ) ; setDescription ( TypeHierarchyMessages . ToggleOrientationAction_vertical_description ) ; setToolTipText ( TypeHierarchyMessages . ToggleOrientationAction_vertical_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( orientation == TypeHierarchyViewPart . VIEW_ORIENTATION_AUTOMATIC ) { setText ( TypeHierarchyMessages . ToggleOrientationAction_automatic_label ) ; setDescription ( TypeHierarchyMessages . ToggleOrientationAction_automatic_description ) ; setToolTipText ( TypeHierarchyMessages . ToggleOrientationAction_automatic_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( orientation == TypeHierarchyViewPart . VIEW_ORIENTATION_SINGLE ) { setText ( TypeHierarchyMessages . ToggleOrientationAction_single_label ) ; setDescription ( TypeHierarchyMessages . ToggleOrientationAction_single_description ) ; setToolTipText ( TypeHierarchyMessages . ToggleOrientationAction_single_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else { Assert . isTrue ( false ) ; } fView = v ; fActionOrientation = orientation ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . TOGGLE_ORIENTATION_ACTION ) ; } public int getOrientation ( ) { return fActionOrientation ; } public void run ( ) { if ( isChecked ( ) ) { fView . fOrientation = fActionOrientation ; fView . computeOrientation ( ) ; } } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . util . Arrays ; import java . util . List ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . IWorkbenchPart ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; public class TraditionalHierarchyViewer extends TypeHierarchyViewer { public TraditionalHierarchyViewer ( Composite parent , TypeHierarchyLifeCycle lifeCycle , IWorkbenchPart part ) { super ( parent , new TraditionalHierarchyContentProvider ( lifeCycle ) , lifeCycle , part ) ; } public String getTitle ( ) { if ( isMethodFiltering ( ) ) { return TypeHierarchyMessages . TraditionalHierarchyViewer_filtered_title ; } else { return TypeHierarchyMessages . TraditionalHierarchyViewer_title ; } } public void updateContent ( boolean expand ) { getTree ( ) . setRedraw ( false ) ; refresh ( ) ; if ( expand ) { TraditionalHierarchyContentProvider contentProvider = ( TraditionalHierarchyContentProvider ) getContentProvider ( ) ; int expandLevel = contentProvider . getExpandLevel ( ) ; if ( isMethodFiltering ( ) ) { expandLevel ++ ; } expandToLevel ( expandLevel ) ; } getTree ( ) . setRedraw ( true ) ; } public static class TraditionalHierarchyContentProvider extends TypeHierarchyContentProvider { public TraditionalHierarchyContentProvider ( TypeHierarchyLifeCycle provider ) { super ( provider ) ; } public int getExpandLevel ( ) { ITypeHierarchy hierarchy = getHierarchy ( ) ; if ( hierarchy != null ) { IType input = hierarchy . getType ( ) ; if ( input != null ) { return getDepth ( hierarchy , input ) + ; } else { return ; } } return ; } private int getDepth ( ITypeHierarchy hierarchy , IType input ) { int count = ; IType superType = hierarchy . getSuperclass ( input ) ; while ( superType != null ) { count ++ ; superType = hierarchy . getSuperclass ( superType ) ; } return count ; } protected final void getRootTypes ( List res ) { ITypeHierarchy hierarchy = getHierarchy ( ) ; if ( hierarchy != null ) { IType input = hierarchy . getType ( ) ; if ( input == null ) { IType [ ] classes = hierarchy . getRootClasses ( ) ; for ( int i = ; i < classes . length ; i ++ ) { res . add ( classes [ i ] ) ; } IType [ ] interfaces = hierarchy . getRootModules ( ) ; for ( int i = ; i < interfaces . length ; i ++ ) { res . add ( interfaces [ i ] ) ; } } else { if ( Flags . isModule ( hierarchy . getCachedFlags ( input ) ) ) { res . add ( input ) ; } else if ( isAnonymousFromInterface ( input ) ) { res . add ( hierarchy . getSuperModules ( input ) [ ] ) ; } else { IType [ ] roots = hierarchy . getRootClasses ( ) ; for ( int i = ; i < roots . length ; i ++ ) { if ( isObject ( roots [ i ] ) ) { res . add ( roots [ i ] ) ; return ; } } res . addAll ( Arrays . asList ( roots ) ) ; } } } } protected final void getTypesInHierarchy ( IType type , List res ) { ITypeHierarchy hierarchy = getHierarchy ( ) ; if ( hierarchy != null ) { IType [ ] types = hierarchy . getSubtypes ( type ) ; if ( isObject ( type ) ) { for ( int i = ; i < types . length ; i ++ ) { IType curr = types [ i ] ; if ( ! isAnonymousFromInterface ( curr ) ) { res . add ( curr ) ; } } } else { boolean isHierarchyOnType = ( hierarchy . getType ( ) != null ) ; boolean isClass = ! Flags . isModule ( hierarchy . getCachedFlags ( type ) ) ; if ( isClass || isHierarchyOnType ) { for ( int i = ; i < types . length ; i ++ ) { res . add ( types [ i ] ) ; } } else { for ( int i = ; i < types . length ; i ++ ) { IType curr = types [ i ] ; if ( Flags . isModule ( hierarchy . getCachedFlags ( curr ) ) || isAnonymous ( curr ) ) { res . add ( curr ) ; } } } } } } protected IType getParentType ( IType type ) { ITypeHierarchy hierarchy = getHierarchy ( ) ; if ( hierarchy != null ) { return hierarchy . getSuperclass ( type ) ; } return null ; } } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . action . ToolBarManager ; import org . eclipse . jface . viewers . IOpenListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . ScrollBar ; import org . eclipse . swt . widgets . Table ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartSite ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . SelectionUtil ; import org . rubypeople . rdt . internal . ui . viewsupport . DecoratingRubyLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTableViewer ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . actions . MemberFilterActionGroup ; import org . rubypeople . rdt . ui . actions . OpenAction ; public class MethodsViewer extends ProblemTableViewer { private static final String TAG_SHOWINHERITED = "" ; private static final String TAG_SORTBYDEFININGTYPE = "" ; private static final String TAG_VERTICAL_SCROLL = "" ; private MethodsLabelProvider fLabelProvider ; private MemberFilterActionGroup fMemberFilterActionGroup ; private OpenAction fOpen ; private ShowInheritedMembersAction fShowInheritedMembersAction ; private SortByDefiningTypeAction fSortByDefiningTypeAction ; public MethodsViewer ( Composite parent , final TypeHierarchyLifeCycle lifeCycle , IWorkbenchPart part ) { super ( new Table ( parent , SWT . MULTI ) ) ; fLabelProvider = new MethodsLabelProvider ( lifeCycle , this ) ; setLabelProvider ( new DecoratingRubyLabelProvider ( fLabelProvider , true ) ) ; setContentProvider ( new MethodsContentProvider ( lifeCycle ) ) ; HierarchyViewerSorter sorter = new HierarchyViewerSorter ( lifeCycle ) ; sorter . setSortByDefiningType ( false ) ; setSorter ( sorter ) ; fOpen = new OpenAction ( part . getSite ( ) ) ; addOpenListener ( new IOpenListener ( ) { public void open ( OpenEvent event ) { fOpen . run ( ) ; } } ) ; fMemberFilterActionGroup = new MemberFilterActionGroup ( this , "" , false , MemberFilterActionGroup . ALL_FILTERS & ~ MemberFilterActionGroup . FILTER_LOCALTYPES ) ; fShowInheritedMembersAction = new ShowInheritedMembersAction ( this , false ) ; fSortByDefiningTypeAction = new SortByDefiningTypeAction ( this , false ) ; showInheritedMethodsNoRedraw ( false ) ; sortByDefiningTypeNoRedraw ( false ) ; } private void showInheritedMethodsNoRedraw ( boolean on ) { MethodsContentProvider cprovider = ( MethodsContentProvider ) getContentProvider ( ) ; cprovider . showInheritedMethods ( on ) ; fShowInheritedMembersAction . setChecked ( on ) ; if ( on ) { fLabelProvider . setTextFlags ( fLabelProvider . getTextFlags ( ) | RubyElementLabels . ALL_POST_QUALIFIED ) ; } else { fLabelProvider . setTextFlags ( fLabelProvider . getTextFlags ( ) & ~ RubyElementLabels . ALL_POST_QUALIFIED ) ; } if ( on ) { sortByDefiningTypeNoRedraw ( false ) ; } fSortByDefiningTypeAction . setEnabled ( ! on ) ; } public void showInheritedMethods ( boolean on ) { if ( on == isShowInheritedMethods ( ) ) { return ; } try { getTable ( ) . setRedraw ( false ) ; showInheritedMethodsNoRedraw ( on ) ; refresh ( ) ; } finally { getTable ( ) . setRedraw ( true ) ; } } private void sortByDefiningTypeNoRedraw ( boolean on ) { fSortByDefiningTypeAction . setChecked ( on ) ; fLabelProvider . setShowDefiningType ( on ) ; ( ( HierarchyViewerSorter ) getSorter ( ) ) . setSortByDefiningType ( on ) ; } public void sortByDefiningType ( boolean on ) { if ( on == isShowDefiningTypes ( ) ) { return ; } try { getTable ( ) . setRedraw ( false ) ; sortByDefiningTypeNoRedraw ( on ) ; refresh ( ) ; } finally { getTable ( ) . setRedraw ( true ) ; } } protected void inputChanged ( Object input , Object oldInput ) { super . inputChanged ( input , oldInput ) ; } public boolean isShowInheritedMethods ( ) { return ( ( MethodsContentProvider ) getContentProvider ( ) ) . isShowInheritedMethods ( ) ; } public boolean isShowDefiningTypes ( ) { return fLabelProvider . isShowDefiningType ( ) ; } public void saveState ( IMemento memento ) { fMemberFilterActionGroup . saveState ( memento ) ; memento . putString ( TAG_SHOWINHERITED , String . valueOf ( isShowInheritedMethods ( ) ) ) ; memento . putString ( TAG_SORTBYDEFININGTYPE , String . valueOf ( isShowDefiningTypes ( ) ) ) ; ScrollBar bar = getTable ( ) . getVerticalBar ( ) ; int position = bar != null ? bar . getSelection ( ) : ; memento . putString ( TAG_VERTICAL_SCROLL , String . valueOf ( position ) ) ; } public void restoreState ( IMemento memento ) { fMemberFilterActionGroup . restoreState ( memento ) ; getControl ( ) . setRedraw ( false ) ; refresh ( ) ; getControl ( ) . setRedraw ( true ) ; boolean showInherited = Boolean . valueOf ( memento . getString ( TAG_SHOWINHERITED ) ) . booleanValue ( ) ; showInheritedMethods ( showInherited ) ; boolean showDefiningTypes = Boolean . valueOf ( memento . getString ( TAG_SORTBYDEFININGTYPE ) ) . booleanValue ( ) ; sortByDefiningType ( showDefiningTypes ) ; ScrollBar bar = getTable ( ) . getVerticalBar ( ) ; if ( bar != null ) { Integer vScroll = memento . getInteger ( TAG_VERTICAL_SCROLL ) ; if ( vScroll != null ) { bar . setSelection ( vScroll . intValue ( ) ) ; } } } public void initContextMenu ( IMenuListener menuListener , String popupId , IWorkbenchPartSite viewSite ) { MenuManager menuMgr = new MenuManager ( ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( menuListener ) ; Menu menu = menuMgr . createContextMenu ( getTable ( ) ) ; getTable ( ) . setMenu ( menu ) ; viewSite . registerContextMenu ( popupId , menuMgr , this ) ; } public void contributeToContextMenu ( IMenuManager menu ) { } public void contributeToToolBar ( ToolBarManager tbm ) { tbm . add ( fShowInheritedMembersAction ) ; tbm . add ( fSortByDefiningTypeAction ) ; tbm . add ( new Separator ( ) ) ; fMemberFilterActionGroup . contributeToToolBar ( tbm ) ; } public void dispose ( ) { if ( fMemberFilterActionGroup != null ) { fMemberFilterActionGroup . dispose ( ) ; fMemberFilterActionGroup = null ; } } protected void handleInvalidSelection ( ISelection invalidSelection , ISelection newSelection ) { List oldSelections = SelectionUtil . toList ( invalidSelection ) ; List newSelections = SelectionUtil . toList ( newSelection ) ; if ( ! oldSelections . isEmpty ( ) ) { ArrayList newSelectionElements = new ArrayList ( newSelections ) ; try { Object [ ] currElements = getFilteredChildren ( getInput ( ) ) ; for ( int i = ; i < oldSelections . size ( ) ; i ++ ) { Object curr = oldSelections . get ( i ) ; if ( curr instanceof IMethod && ! newSelections . contains ( curr ) ) { IMethod method = ( IMethod ) curr ; if ( method . exists ( ) ) { IMethod similar = findSimilarMethod ( method , currElements ) ; if ( similar != null ) { newSelectionElements . add ( similar ) ; } } } } if ( ! newSelectionElements . isEmpty ( ) ) { newSelection = new StructuredSelection ( newSelectionElements ) ; } else if ( currElements . length > ) { newSelection = new StructuredSelection ( currElements [ ] ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } setSelection ( newSelection ) ; updateSelection ( newSelection ) ; } private IMethod findSimilarMethod ( IMethod meth , Object [ ] elements ) throws RubyModelException { String name = meth . getElementName ( ) ; String [ ] paramTypes = null ; boolean isConstructor = meth . isConstructor ( ) ; for ( int i = ; i < elements . length ; i ++ ) { Object curr = elements [ i ] ; if ( curr instanceof IMethod && RubyModelUtil . isSameMethodSignature ( name , paramTypes , isConstructor , ( IMethod ) curr ) ) { return ( IMethod ) curr ; } } return null ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . resource . CompositeImageDescriptor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementImageDescriptor ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class HierarchyLabelProvider extends AppearanceAwareLabelProvider { private static class FocusDescriptor extends CompositeImageDescriptor { private ImageDescriptor fBase ; public FocusDescriptor ( ImageDescriptor base ) { fBase = base ; } protected void drawCompositeImage ( int width , int height ) { drawImage ( getImageData ( fBase ) , , ) ; drawImage ( getImageData ( RubyPluginImages . DESC_OVR_FOCUS ) , , ) ; } private ImageData getImageData ( ImageDescriptor descriptor ) { ImageData data = descriptor . getImageData ( ) ; if ( data == null ) { data = DEFAULT_IMAGE_DATA ; RubyPlugin . logErrorMessage ( "" + descriptor . toString ( ) ) ; } return data ; } protected Point getSize ( ) { return RubyElementImageProvider . BIG_SIZE ; } public int hashCode ( ) { return fBase . hashCode ( ) ; } public boolean equals ( Object object ) { return object != null && FocusDescriptor . class . equals ( object . getClass ( ) ) && ( ( FocusDescriptor ) object ) . fBase . equals ( fBase ) ; } } private Color fGrayedColor ; private Color fSpecialColor ; private ViewerFilter fFilter ; private TypeHierarchyLifeCycle fHierarchy ; public HierarchyLabelProvider ( TypeHierarchyLifeCycle lifeCycle ) { super ( DEFAULT_TEXTFLAGS | RubyElementLabels . T_NAME_FULLY_QUALIFIED | RubyElementLabels . USE_RESOLVED , DEFAULT_IMAGEFLAGS ) ; fHierarchy = lifeCycle ; fFilter = null ; } public ViewerFilter getFilter ( ) { return fFilter ; } public void setFilter ( ViewerFilter filter ) { fFilter = filter ; } protected boolean isDifferentScope ( IType type ) { if ( fFilter != null && ! fFilter . select ( null , null , type ) ) { return true ; } IRubyElement input = fHierarchy . getInputElement ( ) ; if ( input == null || input . getElementType ( ) == IRubyElement . TYPE ) { return false ; } IRubyElement parent = type . getAncestor ( input . getElementType ( ) ) ; if ( input . getElementType ( ) == IRubyElement . SOURCE_FOLDER ) { if ( parent == null || parent . getElementName ( ) . equals ( input . getElementName ( ) ) ) { return false ; } } else if ( input . equals ( parent ) ) { return false ; } return true ; } public String getText ( Object element ) { String text = super . getText ( element ) ; return decorateText ( text , element ) ; } public Image getImage ( Object element ) { Image result = null ; if ( element instanceof IType ) { ImageDescriptor desc = getTypeImageDescriptor ( ( IType ) element ) ; if ( desc != null ) { if ( element . equals ( fHierarchy . getInputElement ( ) ) ) { desc = new FocusDescriptor ( desc ) ; } result = RubyPlugin . getImageDescriptorRegistry ( ) . get ( desc ) ; } } else { result = fImageLabelProvider . getImageLabel ( element , evaluateImageFlags ( element ) ) ; } return decorateImage ( result , element ) ; } private ImageDescriptor getTypeImageDescriptor ( IType type ) { ITypeHierarchy hierarchy = fHierarchy . getHierarchy ( ) ; if ( hierarchy == null ) { return new RubyElementImageDescriptor ( RubyPluginImages . DESC_OBJS_CLASS , , RubyElementImageProvider . BIG_SIZE ) ; } boolean isModule = type . isModule ( ) ; boolean isInner = ( type . getDeclaringType ( ) != null ) ; ImageDescriptor desc = RubyElementImageProvider . getTypeImageDescriptor ( isModule , isInner , isDifferentScope ( type ) ) ; int adornmentFlags = ; return new RubyElementImageDescriptor ( desc , adornmentFlags , RubyElementImageProvider . BIG_SIZE ) ; } public Color getForeground ( Object element ) { if ( element instanceof IMethod ) { if ( fSpecialColor == null ) { fSpecialColor = Display . getCurrent ( ) . getSystemColor ( SWT . COLOR_DARK_BLUE ) ; } return fSpecialColor ; } else if ( element instanceof IType && isDifferentScope ( ( IType ) element ) ) { if ( fGrayedColor == null ) { fGrayedColor = Display . getCurrent ( ) . getSystemColor ( SWT . COLOR_DARK_GRAY ) ; } return fGrayedColor ; } return null ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . MethodOverrideTester ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . viewsupport . SourcePositionSorter ; import org . rubypeople . rdt . ui . RubyElementSorter ; public abstract class AbstractHierarchyViewerSorter extends ViewerSorter { private static final int OTHER = ; private static final int CLASS = ; private static final int MODULE = ; private static final int ANONYM = ; private RubyElementSorter fNormalSorter ; private SourcePositionSorter fSourcePositonSorter ; public AbstractHierarchyViewerSorter ( ) { fNormalSorter = new RubyElementSorter ( ) ; fSourcePositonSorter = new SourcePositionSorter ( ) ; } protected abstract ITypeHierarchy getHierarchy ( IType type ) ; public abstract boolean isSortByDefiningType ( ) ; public abstract boolean isSortAlphabetically ( ) ; public int category ( Object element ) { if ( element instanceof IType ) { IType type = ( IType ) element ; if ( type . getElementName ( ) . length ( ) == ) { return ANONYM ; } if ( type . isModule ( ) ) { return MODULE ; } else { return CLASS ; } } return OTHER ; } public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( ! isSortAlphabetically ( ) && ! isSortByDefiningType ( ) ) { return fSourcePositonSorter . compare ( viewer , e1 , e2 ) ; } int cat1 = category ( e1 ) ; int cat2 = category ( e2 ) ; if ( cat1 != cat2 ) return cat1 - cat2 ; if ( cat1 == OTHER ) { if ( isSortByDefiningType ( ) ) { try { IType def1 = ( e1 instanceof IMethod ) ? getDefiningType ( ( IMethod ) e1 ) : null ; IType def2 = ( e2 instanceof IMethod ) ? getDefiningType ( ( IMethod ) e2 ) : null ; if ( def1 != null ) { if ( def2 != null ) { if ( ! def2 . equals ( def1 ) ) { return compareInHierarchy ( def1 , def2 ) ; } } else { return - ; } } else { if ( def2 != null ) { return ; } } } catch ( RubyModelException e ) { } } if ( isSortAlphabetically ( ) ) { return fNormalSorter . compare ( viewer , e1 , e2 ) ; } return ; } else if ( cat1 == ANONYM ) { return ; } else if ( isSortAlphabetically ( ) ) { String name1 = ( ( IType ) e1 ) . getFullyQualifiedName ( ) ; String name2 = ( ( IType ) e2 ) . getFullyQualifiedName ( ) ; return getCollator ( ) . compare ( name1 , name2 ) ; } return ; } private IType getDefiningType ( IMethod method ) throws RubyModelException { if ( method . getVisibility ( ) == IMethod . PRIVATE || method . isSingleton ( ) || method . isConstructor ( ) ) { return null ; } IType declaringType = method . getDeclaringType ( ) ; MethodOverrideTester tester = new MethodOverrideTester ( declaringType , getHierarchy ( declaringType ) ) ; IMethod res = tester . findDeclaringMethod ( method , true ) ; if ( res == null ) { return null ; } return res . getDeclaringType ( ) ; } private int compareInHierarchy ( IType def1 , IType def2 ) { if ( RubyModelUtil . isSuperType ( getHierarchy ( def1 ) , def2 , def1 ) ) { return ; } else if ( RubyModelUtil . isSuperType ( getHierarchy ( def2 ) , def1 , def2 ) ) { return - ; } if ( def1 . isModule ( ) ) { if ( ! def2 . isModule ( ) ) { return ; } } else if ( def2 . isModule ( ) ) { return - ; } String name1 = def1 . getElementName ( ) ; String name2 = def2 . getElementName ( ) ; return getCollator ( ) . compare ( name1 , name2 ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IRegion ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . ITypeHierarchyChangedListener ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . codeassist . RubyElementRequestor ; import org . rubypeople . rdt . internal . core . LogicalType ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class TypeHierarchyLifeCycle implements ITypeHierarchyChangedListener , IElementChangedListener { private boolean fHierarchyRefreshNeeded ; private ITypeHierarchy fHierarchy ; private IRubyElement fInputElement ; private boolean fIsSuperTypesOnly ; private List fChangeListeners ; public TypeHierarchyLifeCycle ( ) { this ( false ) ; } public TypeHierarchyLifeCycle ( boolean isSuperTypesOnly ) { fHierarchy = null ; fInputElement = null ; fIsSuperTypesOnly = isSuperTypesOnly ; fChangeListeners = new ArrayList ( ) ; } public ITypeHierarchy getHierarchy ( ) { return fHierarchy ; } public IRubyElement getInputElement ( ) { return fInputElement ; } public void freeHierarchy ( ) { if ( fHierarchy != null ) { fHierarchy . removeTypeHierarchyChangedListener ( this ) ; RubyCore . removeElementChangedListener ( this ) ; fHierarchy = null ; fInputElement = null ; } } public void removeChangedListener ( ITypeHierarchyLifeCycleListener listener ) { fChangeListeners . remove ( listener ) ; } public void addChangedListener ( ITypeHierarchyLifeCycleListener listener ) { if ( ! fChangeListeners . contains ( listener ) ) { fChangeListeners . add ( listener ) ; } } private void fireChange ( IType [ ] changedTypes ) { for ( int i = fChangeListeners . size ( ) - ; i >= ; i -- ) { ITypeHierarchyLifeCycleListener curr = ( ITypeHierarchyLifeCycleListener ) fChangeListeners . get ( i ) ; curr . typeHierarchyChanged ( this , changedTypes ) ; } } public void ensureRefreshedTypeHierarchy ( final IRubyElement element , IRunnableContext context ) throws InvocationTargetException , InterruptedException { if ( element == null || ! element . exists ( ) ) { freeHierarchy ( ) ; return ; } boolean hierachyCreationNeeded = ( fHierarchy == null || ! element . equals ( fInputElement ) ) ; if ( hierachyCreationNeeded || fHierarchyRefreshNeeded ) { IRunnableWithProgress op = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor pm ) throws InvocationTargetException , InterruptedException { try { doHierarchyRefresh ( element , pm ) ; } catch ( RubyModelException e ) { throw new InvocationTargetException ( e ) ; } catch ( OperationCanceledException e ) { throw new InterruptedException ( ) ; } } } ; fHierarchyRefreshNeeded = true ; context . run ( true , true , op ) ; fHierarchyRefreshNeeded = false ; } } private IType getLogicalType ( IType type , String name ) { RubyElementRequestor requestor = new RubyElementRequestor ( type . getRubyScript ( ) ) ; IType [ ] types = requestor . findType ( name ) ; if ( types == null || types . length == ) return null ; return new LogicalType ( types ) ; } private ITypeHierarchy createTypeHierarchy ( IRubyElement element , IProgressMonitor pm ) throws RubyModelException { if ( element . getElementType ( ) == IRubyElement . TYPE ) { IType type = ( IType ) element ; type = getLogicalType ( type , type . getFullyQualifiedName ( ) ) ; if ( fIsSuperTypesOnly ) { return type . newSupertypeHierarchy ( pm ) ; } else { return type . newTypeHierarchy ( pm ) ; } } else { IRegion region = RubyCore . newRegion ( ) ; if ( element . getElementType ( ) == IRubyElement . RUBY_PROJECT ) { ISourceFolderRoot [ ] roots = ( ( IRubyProject ) element ) . getSourceFolderRoots ( ) ; for ( int i = ; i < roots . length ; i ++ ) { if ( ! roots [ i ] . isExternal ( ) ) { region . add ( roots [ i ] ) ; } } } else if ( element . getElementType ( ) == IRubyElement . SOURCE_FOLDER ) { ISourceFolderRoot [ ] roots = element . getRubyProject ( ) . getSourceFolderRoots ( ) ; String name = element . getElementName ( ) ; for ( int i = ; i < roots . length ; i ++ ) { ISourceFolder pack = roots [ i ] . getSourceFolder ( name ) ; if ( pack . exists ( ) ) { region . add ( pack ) ; } } } else { region . add ( element ) ; } IRubyProject jproject = element . getRubyProject ( ) ; return jproject . newTypeHierarchy ( region , pm ) ; } } public synchronized void doHierarchyRefresh ( IRubyElement element , IProgressMonitor pm ) throws RubyModelException { boolean hierachyCreationNeeded = ( fHierarchy == null || ! element . equals ( fInputElement ) ) ; if ( fHierarchy != null ) { fHierarchy . removeTypeHierarchyChangedListener ( this ) ; RubyCore . removeElementChangedListener ( this ) ; } if ( hierachyCreationNeeded ) { fHierarchy = createTypeHierarchy ( element , pm ) ; if ( pm != null && pm . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } fInputElement = element ; } else { fHierarchy . refresh ( pm ) ; } if ( fHierarchy != null ) { fHierarchy . addTypeHierarchyChangedListener ( this ) ; RubyCore . addElementChangedListener ( this ) ; fHierarchyRefreshNeeded = false ; } } public void typeHierarchyChanged ( ITypeHierarchy typeHierarchy ) { fHierarchyRefreshNeeded = true ; fireChange ( null ) ; } public void elementChanged ( ElementChangedEvent event ) { if ( fChangeListeners . isEmpty ( ) ) { return ; } if ( fHierarchyRefreshNeeded ) { return ; } else { ArrayList changedTypes = new ArrayList ( ) ; processDelta ( event . getDelta ( ) , changedTypes ) ; if ( changedTypes . size ( ) > ) { fireChange ( ( IType [ ] ) changedTypes . toArray ( new IType [ changedTypes . size ( ) ] ) ) ; } } } private void processDelta ( IRubyElementDelta delta , ArrayList changedTypes ) { IRubyElement element = delta . getElement ( ) ; switch ( element . getElementType ( ) ) { case IRubyElement . TYPE : processTypeDelta ( ( IType ) element , changedTypes ) ; processChildrenDelta ( delta , changedTypes ) ; break ; case IRubyElement . RUBY_MODEL : case IRubyElement . RUBY_PROJECT : case IRubyElement . SOURCE_FOLDER_ROOT : case IRubyElement . SOURCE_FOLDER : processChildrenDelta ( delta , changedTypes ) ; break ; case IRubyElement . SCRIPT : IRubyScript cu = ( IRubyScript ) element ; if ( ! RubyModelUtil . isPrimary ( cu ) ) { return ; } if ( delta . getKind ( ) == IRubyElementDelta . CHANGED && isPossibleStructuralChange ( delta . getFlags ( ) ) ) { try { if ( cu . exists ( ) ) { IType [ ] types = cu . getAllTypes ( ) ; for ( int i = ; i < types . length ; i ++ ) { processTypeDelta ( types [ i ] , changedTypes ) ; } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } else { processChildrenDelta ( delta , changedTypes ) ; } break ; } } private boolean isPossibleStructuralChange ( int flags ) { return ( flags & ( IRubyElementDelta . F_CONTENT | IRubyElementDelta . F_FINE_GRAINED ) ) == IRubyElementDelta . F_CONTENT ; } private void processTypeDelta ( IType type , ArrayList changedTypes ) { if ( getHierarchy ( ) . contains ( type ) ) { changedTypes . add ( type ) ; } } private void processChildrenDelta ( IRubyElementDelta delta , ArrayList changedTypes ) { IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { processDelta ( children [ i ] , changedTypes ) ; } } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IStatusLineManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . action . ToolBarManager ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . viewers . AbstractTreeViewer ; import org . eclipse . jface . viewers . IBasicPropertyConstants ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . custom . CLabel ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . custom . ViewForm ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DropTarget ; import org . eclipse . swt . dnd . DropTargetAdapter ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . events . ControlListener ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . ScrollBar ; import org . eclipse . swt . widgets . ToolBar ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IPartListener2 ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . part . IShowInSource ; import org . eclipse . ui . part . IShowInTargetList ; import org . eclipse . ui . part . PageBook ; import org . eclipse . ui . part . ResourceTransfer ; import org . eclipse . ui . part . ShowInContext ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . views . navigator . LocalSelectionTransfer ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . CompositeActionGroup ; import org . rubypeople . rdt . internal . ui . actions . NewWizardsActionGroup ; import org . rubypeople . rdt . internal . ui . actions . SelectAllAction ; import org . rubypeople . rdt . internal . ui . dnd . RdtViewerDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . ResourceTransferDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . SelectionTransferDragAdapter ; import org . rubypeople . rdt . internal . ui . preferences . MembersOrderPreferenceCache ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . viewsupport . IViewPartInputProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyUILabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . SelectionProviderMediator ; import org . rubypeople . rdt . internal . ui . viewsupport . StatusBarUpdater ; import org . rubypeople . rdt . internal . ui . workingsets . WorkingSetFilterActionGroup ; import org . rubypeople . rdt . ui . IContextMenuConstants ; import org . rubypeople . rdt . ui . ITypeHierarchyViewPart ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . actions . OpenEditorActionGroup ; import org . rubypeople . rdt . ui . actions . OpenViewActionGroup ; import org . rubypeople . rdt . ui . actions . RubySearchActionGroup ; public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart , IViewPartInputProvider { public static final int VIEW_ID_TYPE = ; public static final int VIEW_ID_SUPER = ; public static final int VIEW_ID_SUB = ; public static final int VIEW_ORIENTATION_VERTICAL = ; public static final int VIEW_ORIENTATION_HORIZONTAL = ; public static final int VIEW_ORIENTATION_SINGLE = ; public static final int VIEW_ORIENTATION_AUTOMATIC = ; private static final String DIALOGSTORE_HIERARCHYVIEW = "" ; private static final String DIALOGSTORE_VIEWORIENTATION = "" ; private static final String TAG_INPUT = "" ; private static final String TAG_VIEW = "" ; private static final String TAG_ORIENTATION = "" ; private static final String TAG_RATIO = "" ; private static final String TAG_SELECTION = "" ; private static final String TAG_VERTICAL_SCROLL = "" ; private static final String GROUP_FOCUS = "" ; private IType fSelectedType ; private IRubyElement fInputElement ; private ArrayList fInputHistory ; private IMemento fMemento ; private IDialogSettings fDialogSettings ; private TypeHierarchyLifeCycle fHierarchyLifeCycle ; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener ; private IPropertyChangeListener fPropertyChangeListener ; private SelectionProviderMediator fSelectionProviderMediator ; private ISelectionChangedListener fSelectionChangedListener ; private IPartListener2 fPartListener ; private int fCurrentOrientation ; int fOrientation = VIEW_ORIENTATION_AUTOMATIC ; boolean fInComputeOrientation = false ; private boolean fLinkingEnabled ; private boolean fSelectInEditor ; private boolean fIsVisible ; private boolean fNeedRefresh ; private boolean fIsEnableMemberFilter ; private boolean fIsRefreshRunnablePosted ; private int fCurrentViewerIndex ; private TypeHierarchyViewer [ ] fAllViewers ; private MethodsViewer fMethodsViewer ; private SashForm fTypeMethodsSplitter ; private PageBook fViewerbook ; private PageBook fPagebook ; private Label fNoHierarchyShownLabel ; private Label fEmptyTypesViewer ; private ViewForm fTypeViewerViewForm ; private ViewForm fMethodViewerViewForm ; private CLabel fMethodViewerPaneLabel ; private RubyUILabelProvider fPaneLabelProvider ; private Composite fParent ; private ToggleViewAction [ ] fViewActions ; private ToggleLinkingAction fToggleLinkingAction ; private HistoryDropDownAction fHistoryDropDownAction ; private ToggleOrientationAction [ ] fToggleOrientationActions ; private EnableMemberFilterAction fEnableMemberFilterAction ; private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction ; private FocusOnTypeAction fFocusOnTypeAction ; private FocusOnSelectionAction fFocusOnSelectionAction ; private CompositeActionGroup fActionGroups ; private SelectAllAction fSelectAllAction ; private WorkingSetFilterActionGroup fWorkingSetActionGroup ; private Job fRestoreStateJob ; public TypeHierarchyViewPart ( ) { fSelectedType = null ; fInputElement = null ; fIsVisible = false ; fIsRefreshRunnablePosted = false ; fSelectInEditor = true ; fRestoreStateJob = null ; fHierarchyLifeCycle = new TypeHierarchyLifeCycle ( ) ; fTypeHierarchyLifeCycleListener = new ITypeHierarchyLifeCycleListener ( ) { public void typeHierarchyChanged ( TypeHierarchyLifeCycle typeHierarchy , IType [ ] changedTypes ) { doTypeHierarchyChanged ( typeHierarchy , changedTypes ) ; } } ; fHierarchyLifeCycle . addChangedListener ( fTypeHierarchyLifeCycleListener ) ; fPropertyChangeListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { doPropertyChange ( event ) ; } } ; PreferenceConstants . getPreferenceStore ( ) . addPropertyChangeListener ( fPropertyChangeListener ) ; fIsEnableMemberFilter = false ; fInputHistory = new ArrayList ( ) ; fAllViewers = null ; fViewActions = new ToggleViewAction [ ] { new ToggleViewAction ( this , VIEW_ID_TYPE ) , new ToggleViewAction ( this , VIEW_ID_SUPER ) , new ToggleViewAction ( this , VIEW_ID_SUB ) } ; fDialogSettings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; fHistoryDropDownAction = new HistoryDropDownAction ( this ) ; fHistoryDropDownAction . setEnabled ( false ) ; fToggleOrientationActions = new ToggleOrientationAction [ ] { new ToggleOrientationAction ( this , VIEW_ORIENTATION_VERTICAL ) , new ToggleOrientationAction ( this , VIEW_ORIENTATION_HORIZONTAL ) , new ToggleOrientationAction ( this , VIEW_ORIENTATION_AUTOMATIC ) , new ToggleOrientationAction ( this , VIEW_ORIENTATION_SINGLE ) } ; fEnableMemberFilterAction = new EnableMemberFilterAction ( this , false ) ; fShowQualifiedTypeNamesAction = new ShowQualifiedTypeNamesAction ( this , false ) ; fFocusOnTypeAction = new FocusOnTypeAction ( this ) ; fPaneLabelProvider = new RubyUILabelProvider ( ) ; fFocusOnSelectionAction = new FocusOnSelectionAction ( this ) ; fPartListener = new IPartListener2 ( ) { public void partVisible ( IWorkbenchPartReference ref ) { IWorkbenchPart part = ref . getPart ( false ) ; if ( part == TypeHierarchyViewPart . this ) { visibilityChanged ( true ) ; } } public void partHidden ( IWorkbenchPartReference ref ) { IWorkbenchPart part = ref . getPart ( false ) ; if ( part == TypeHierarchyViewPart . this ) { visibilityChanged ( false ) ; } } public void partActivated ( IWorkbenchPartReference ref ) { IWorkbenchPart part = ref . getPart ( false ) ; if ( part instanceof IEditorPart ) editorActivated ( ( IEditorPart ) part ) ; } public void partInputChanged ( IWorkbenchPartReference ref ) { IWorkbenchPart part = ref . getPart ( false ) ; if ( part instanceof IEditorPart ) editorActivated ( ( IEditorPart ) part ) ; } public void partBroughtToTop ( IWorkbenchPartReference ref ) { } public void partClosed ( IWorkbenchPartReference ref ) { } public void partDeactivated ( IWorkbenchPartReference ref ) { } public void partOpened ( IWorkbenchPartReference ref ) { } } ; fSelectionChangedListener = new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { doSelectionChanged ( event ) ; } } ; fLinkingEnabled = PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . LINK_TYPEHIERARCHY_TO_EDITOR ) ; } protected void doPropertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( fMethodsViewer != null ) { if ( MembersOrderPreferenceCache . isMemberOrderProperty ( event . getProperty ( ) ) ) { fMethodsViewer . refresh ( ) ; } } if ( IWorkingSetManager . CHANGE_WORKING_SET_CONTENT_CHANGE . equals ( property ) ) { updateHierarchyViewer ( true ) ; updateTitle ( ) ; } } private void addHistoryEntry ( IRubyElement entry ) { if ( fInputHistory . contains ( entry ) ) { fInputHistory . remove ( entry ) ; } fInputHistory . add ( , entry ) ; fHistoryDropDownAction . setEnabled ( true ) ; } private void updateHistoryEntries ( ) { for ( int i = fInputHistory . size ( ) - ; i >= ; i -- ) { IRubyElement type = ( IRubyElement ) fInputHistory . get ( i ) ; if ( ! type . exists ( ) ) { fInputHistory . remove ( i ) ; } } fHistoryDropDownAction . setEnabled ( ! fInputHistory . isEmpty ( ) ) ; } public void gotoHistoryEntry ( IRubyElement entry ) { if ( fInputHistory . contains ( entry ) ) { updateInput ( entry ) ; } } public IRubyElement [ ] getHistoryEntries ( ) { if ( fInputHistory . size ( ) > ) { updateHistoryEntries ( ) ; } return ( IRubyElement [ ] ) fInputHistory . toArray ( new IRubyElement [ fInputHistory . size ( ) ] ) ; } public void setHistoryEntries ( IRubyElement [ ] elems ) { fInputHistory . clear ( ) ; for ( int i = ; i < elems . length ; i ++ ) { fInputHistory . add ( elems [ i ] ) ; } updateHistoryEntries ( ) ; } public void selectMember ( IMember member ) { fSelectInEditor = false ; if ( member . getElementType ( ) != IRubyElement . TYPE ) { Control methodControl = fMethodsViewer . getControl ( ) ; if ( methodControl != null && ! methodControl . isDisposed ( ) ) { methodControl . setFocus ( ) ; } fMethodsViewer . setSelection ( new StructuredSelection ( member ) , true ) ; } else { Control viewerControl = getCurrentViewer ( ) . getControl ( ) ; if ( viewerControl != null && ! viewerControl . isDisposed ( ) ) { viewerControl . setFocus ( ) ; } if ( ! member . equals ( fSelectedType ) ) { getCurrentViewer ( ) . setSelection ( new StructuredSelection ( member ) , true ) ; } } fSelectInEditor = true ; } public IType getInput ( ) { if ( fInputElement instanceof IType ) { return ( IType ) fInputElement ; } return null ; } public void setInput ( IType type ) { setInputElement ( type ) ; } public IRubyElement getInputElement ( ) { return fInputElement ; } public void setInputElement ( IRubyElement element ) { IMember memberToSelect = null ; if ( element != null ) { if ( element instanceof IMember ) { if ( element . getElementType ( ) != IRubyElement . TYPE ) { memberToSelect = ( IMember ) element ; element = memberToSelect . getDeclaringType ( ) ; } if ( ! element . exists ( ) ) { MessageDialog . openError ( getSite ( ) . getShell ( ) , TypeHierarchyMessages . TypeHierarchyViewPart_error_title , TypeHierarchyMessages . TypeHierarchyViewPart_error_message ) ; return ; } } else { int kind = element . getElementType ( ) ; if ( kind != IRubyElement . RUBY_PROJECT && kind != IRubyElement . SOURCE_FOLDER_ROOT && kind != IRubyElement . SOURCE_FOLDER ) { element = null ; RubyPlugin . logErrorMessage ( "" ) ; } } } if ( element != null && ! element . equals ( fInputElement ) ) { addHistoryEntry ( element ) ; } updateInput ( element ) ; if ( memberToSelect != null ) { selectMember ( memberToSelect ) ; } } private void updateInput ( IRubyElement inputElement ) { IRubyElement prevInput = fInputElement ; synchronized ( this ) { if ( fRestoreStateJob != null ) { fRestoreStateJob . cancel ( ) ; try { fRestoreStateJob . join ( ) ; } catch ( InterruptedException e ) { } finally { fRestoreStateJob = null ; } } } processOutstandingEvents ( ) ; if ( inputElement == null ) { clearInput ( ) ; } else { fInputElement = inputElement ; try { fHierarchyLifeCycle . ensureRefreshedTypeHierarchy ( inputElement , RubyPlugin . getActiveWorkbenchWindow ( ) ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , getSite ( ) . getShell ( ) , TypeHierarchyMessages . TypeHierarchyViewPart_exception_title , TypeHierarchyMessages . TypeHierarchyViewPart_exception_message ) ; clearInput ( ) ; return ; } catch ( InterruptedException e ) { return ; } if ( inputElement . getElementType ( ) != IRubyElement . TYPE ) { setView ( VIEW_ID_TYPE ) ; } fSelectInEditor = false ; setMemberFilter ( null ) ; internalSelectType ( null , false ) ; fIsEnableMemberFilter = false ; if ( ! inputElement . equals ( prevInput ) ) { updateHierarchyViewer ( true ) ; } IType root = getSelectableType ( inputElement ) ; internalSelectType ( root , true ) ; updateMethodViewer ( root ) ; updateToolbarButtons ( ) ; updateTitle ( ) ; enableMemberFilter ( false ) ; fPagebook . showPage ( fTypeMethodsSplitter ) ; fSelectInEditor = true ; } } private void processOutstandingEvents ( ) { Display display = getDisplay ( ) ; if ( display != null && ! display . isDisposed ( ) ) display . update ( ) ; } private void clearInput ( ) { fInputElement = null ; fHierarchyLifeCycle . freeHierarchy ( ) ; updateHierarchyViewer ( false ) ; updateToolbarButtons ( ) ; } public void setFocus ( ) { fPagebook . setFocus ( ) ; } public void dispose ( ) { fHierarchyLifeCycle . freeHierarchy ( ) ; fHierarchyLifeCycle . removeChangedListener ( fTypeHierarchyLifeCycleListener ) ; fPaneLabelProvider . dispose ( ) ; if ( fMethodsViewer != null ) { fMethodsViewer . dispose ( ) ; } if ( fPropertyChangeListener != null ) { RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . removePropertyChangeListener ( fPropertyChangeListener ) ; fPropertyChangeListener = null ; } getSite ( ) . getPage ( ) . removePartListener ( fPartListener ) ; if ( fActionGroups != null ) fActionGroups . dispose ( ) ; if ( fWorkingSetActionGroup != null ) { fWorkingSetActionGroup . dispose ( ) ; } super . dispose ( ) ; } public Object getAdapter ( Class key ) { if ( key == IShowInSource . class ) { return getShowInSource ( ) ; } if ( key == IShowInTargetList . class ) { return new IShowInTargetList ( ) { public String [ ] getShowInTargetIds ( ) { return new String [ ] { RubyUI . ID_RUBY_EXPLORER , IPageLayout . ID_RES_NAV } ; } } ; } return super . getAdapter ( key ) ; } private Control createTypeViewerControl ( Composite parent ) { fViewerbook = new PageBook ( parent , SWT . NULL ) ; KeyListener keyListener = createKeyListener ( ) ; TypeHierarchyViewer superTypesViewer = new SuperTypeHierarchyViewer ( fViewerbook , fHierarchyLifeCycle , this ) ; initializeTypesViewer ( superTypesViewer , keyListener , IContextMenuConstants . TARGET_ID_SUPERTYPES_VIEW ) ; TypeHierarchyViewer subTypesViewer = new SubTypeHierarchyViewer ( fViewerbook , fHierarchyLifeCycle , this ) ; initializeTypesViewer ( subTypesViewer , keyListener , IContextMenuConstants . TARGET_ID_SUBTYPES_VIEW ) ; TypeHierarchyViewer vajViewer = new TraditionalHierarchyViewer ( fViewerbook , fHierarchyLifeCycle , this ) ; initializeTypesViewer ( vajViewer , keyListener , IContextMenuConstants . TARGET_ID_HIERARCHY_VIEW ) ; fAllViewers = new TypeHierarchyViewer [ ] ; fAllViewers [ VIEW_ID_SUPER ] = superTypesViewer ; fAllViewers [ VIEW_ID_SUB ] = subTypesViewer ; fAllViewers [ VIEW_ID_TYPE ] = vajViewer ; int currViewerIndex ; try { currViewerIndex = fDialogSettings . getInt ( DIALOGSTORE_HIERARCHYVIEW ) ; if ( currViewerIndex < || currViewerIndex > ) { currViewerIndex = VIEW_ID_TYPE ; } } catch ( NumberFormatException e ) { currViewerIndex = VIEW_ID_TYPE ; } fEmptyTypesViewer = new Label ( fViewerbook , SWT . TOP | SWT . LEFT | SWT . WRAP ) ; for ( int i = ; i < fAllViewers . length ; i ++ ) { fAllViewers [ i ] . setInput ( fAllViewers [ i ] ) ; } fCurrentViewerIndex = - ; setView ( currViewerIndex ) ; return fViewerbook ; } private KeyListener createKeyListener ( ) { return new KeyAdapter ( ) { public void keyReleased ( KeyEvent event ) { if ( event . stateMask == ) { if ( event . keyCode == SWT . F5 ) { ITypeHierarchy hierarchy = fHierarchyLifeCycle . getHierarchy ( ) ; if ( hierarchy != null ) { fHierarchyLifeCycle . typeHierarchyChanged ( hierarchy ) ; doTypeHierarchyChangedOnViewers ( null ) ; } updateHierarchyViewer ( false ) ; return ; } } } } ; } private void initializeTypesViewer ( final TypeHierarchyViewer typesViewer , KeyListener keyListener , String cotextHelpId ) { typesViewer . getControl ( ) . setVisible ( false ) ; typesViewer . getControl ( ) . addKeyListener ( keyListener ) ; typesViewer . initContextMenu ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager menu ) { fillTypesViewerContextMenu ( typesViewer , menu ) ; } } , cotextHelpId , getSite ( ) ) ; typesViewer . addPostSelectionChangedListener ( fSelectionChangedListener ) ; typesViewer . setQualifiedTypeName ( isShowQualifiedTypeNames ( ) ) ; typesViewer . setWorkingSetFilter ( fWorkingSetActionGroup . getWorkingSetFilter ( ) ) ; } private Control createMethodViewerControl ( Composite parent ) { fMethodsViewer = new MethodsViewer ( parent , fHierarchyLifeCycle , this ) ; fMethodsViewer . initContextMenu ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager menu ) { fillMethodsViewerContextMenu ( menu ) ; } } , IContextMenuConstants . TARGET_ID_MEMBERS_VIEW , getSite ( ) ) ; fMethodsViewer . addPostSelectionChangedListener ( fSelectionChangedListener ) ; Control control = fMethodsViewer . getTable ( ) ; control . addKeyListener ( createKeyListener ( ) ) ; control . addFocusListener ( new FocusListener ( ) { public void focusGained ( FocusEvent e ) { fSelectAllAction . setEnabled ( true ) ; } public void focusLost ( FocusEvent e ) { fSelectAllAction . setEnabled ( false ) ; } } ) ; return control ; } private void initDragAndDrop ( ) { for ( int i = ; i < fAllViewers . length ; i ++ ) { addDragAdapters ( fAllViewers [ i ] ) ; addDropAdapters ( fAllViewers [ i ] ) ; } addDragAdapters ( fMethodsViewer ) ; fMethodsViewer . addDropSupport ( DND . DROP_NONE , new Transfer [ ] , new DropTargetAdapter ( ) ) ; DropTarget dropTarget = new DropTarget ( fPagebook , DND . DROP_MOVE | DND . DROP_COPY | DND . DROP_LINK | DND . DROP_DEFAULT ) ; dropTarget . setTransfer ( new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) } ) ; } private void addDropAdapters ( AbstractTreeViewer viewer ) { } private void addDragAdapters ( StructuredViewer viewer ) { int ops = DND . DROP_COPY | DND . DROP_LINK ; Transfer [ ] transfers = new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) , ResourceTransfer . getInstance ( ) } ; TransferDragSourceListener [ ] dragListeners = new TransferDragSourceListener [ ] { new SelectionTransferDragAdapter ( viewer ) , new ResourceTransferDragAdapter ( viewer ) } ; viewer . addDragSupport ( ops , transfers , new RdtViewerDragAdapter ( viewer , dragListeners ) ) ; } public void createPartControl ( Composite container ) { fParent = container ; addResizeListener ( container ) ; fPagebook = new PageBook ( container , SWT . NONE ) ; fWorkingSetActionGroup = new WorkingSetFilterActionGroup ( getSite ( ) , fPropertyChangeListener ) ; fNoHierarchyShownLabel = new Label ( fPagebook , SWT . TOP + SWT . LEFT + SWT . WRAP ) ; fNoHierarchyShownLabel . setText ( TypeHierarchyMessages . TypeHierarchyViewPart_empty ) ; fTypeMethodsSplitter = new SashForm ( fPagebook , SWT . VERTICAL ) ; fTypeMethodsSplitter . setVisible ( false ) ; fTypeViewerViewForm = new ViewForm ( fTypeMethodsSplitter , SWT . NONE ) ; Control typeViewerControl = createTypeViewerControl ( fTypeViewerViewForm ) ; fTypeViewerViewForm . setContent ( typeViewerControl ) ; fMethodViewerViewForm = new ViewForm ( fTypeMethodsSplitter , SWT . NONE ) ; fTypeMethodsSplitter . setWeights ( new int [ ] { , } ) ; Control methodViewerPart = createMethodViewerControl ( fMethodViewerViewForm ) ; fMethodViewerViewForm . setContent ( methodViewerPart ) ; fMethodViewerPaneLabel = new CLabel ( fMethodViewerViewForm , SWT . NONE ) ; fMethodViewerViewForm . setTopLeft ( fMethodViewerPaneLabel ) ; ToolBar methodViewerToolBar = new ToolBar ( fMethodViewerViewForm , SWT . FLAT | SWT . WRAP ) ; fMethodViewerViewForm . setTopCenter ( methodViewerToolBar ) ; initDragAndDrop ( ) ; MenuManager menu = new MenuManager ( ) ; menu . add ( fFocusOnTypeAction ) ; fNoHierarchyShownLabel . setMenu ( menu . createContextMenu ( fNoHierarchyShownLabel ) ) ; fPagebook . showPage ( fNoHierarchyShownLabel ) ; try { fOrientation = fDialogSettings . getInt ( DIALOGSTORE_VIEWORIENTATION ) ; if ( fOrientation < || fOrientation > ) { fOrientation = VIEW_ORIENTATION_VERTICAL ; } } catch ( NumberFormatException e ) { fOrientation = VIEW_ORIENTATION_AUTOMATIC ; } fCurrentOrientation = - ; setOrientation ( fOrientation ) ; if ( fMemento != null ) { restoreLinkingEnabled ( fMemento ) ; } fToggleLinkingAction = new ToggleLinkingAction ( this ) ; IActionBars actionBars = getViewSite ( ) . getActionBars ( ) ; IMenuManager viewMenu = actionBars . getMenuManager ( ) ; for ( int i = ; i < fViewActions . length ; i ++ ) { ToggleViewAction action = fViewActions [ i ] ; viewMenu . add ( action ) ; action . setEnabled ( false ) ; } viewMenu . add ( new Separator ( ) ) ; fWorkingSetActionGroup . fillViewMenu ( viewMenu ) ; viewMenu . add ( new Separator ( ) ) ; IMenuManager layoutSubMenu = new MenuManager ( TypeHierarchyMessages . TypeHierarchyViewPart_layout_submenu ) ; viewMenu . add ( layoutSubMenu ) ; for ( int i = ; i < fToggleOrientationActions . length ; i ++ ) { layoutSubMenu . add ( fToggleOrientationActions [ i ] ) ; } viewMenu . add ( new Separator ( IWorkbenchActionConstants . MB_ADDITIONS ) ) ; viewMenu . add ( fShowQualifiedTypeNamesAction ) ; viewMenu . add ( fToggleLinkingAction ) ; ToolBarManager lowertbmanager = new ToolBarManager ( methodViewerToolBar ) ; lowertbmanager . add ( fEnableMemberFilterAction ) ; lowertbmanager . add ( new Separator ( ) ) ; fMethodsViewer . contributeToToolBar ( lowertbmanager ) ; lowertbmanager . update ( true ) ; int nHierarchyViewers = fAllViewers . length ; StructuredViewer [ ] trackedViewers = new StructuredViewer [ nHierarchyViewers + ] ; for ( int i = ; i < nHierarchyViewers ; i ++ ) { trackedViewers [ i ] = fAllViewers [ i ] ; } trackedViewers [ nHierarchyViewers ] = fMethodsViewer ; fSelectionProviderMediator = new SelectionProviderMediator ( trackedViewers , getCurrentViewer ( ) ) ; IStatusLineManager slManager = getViewSite ( ) . getActionBars ( ) . getStatusLineManager ( ) ; fSelectionProviderMediator . addSelectionChangedListener ( new StatusBarUpdater ( slManager ) ) ; getSite ( ) . setSelectionProvider ( fSelectionProviderMediator ) ; getSite ( ) . getPage ( ) . addPartListener ( fPartListener ) ; IRubyElement input = null ; if ( fMemento != null ) { restoreState ( fMemento , input ) ; } else if ( input != null ) { setInputElement ( input ) ; } else { setViewerVisibility ( false ) ; } PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( fPagebook , IRubyHelpContextIds . TYPE_HIERARCHY_VIEW ) ; fActionGroups = new CompositeActionGroup ( new ActionGroup [ ] { new NewWizardsActionGroup ( this . getSite ( ) ) , new OpenEditorActionGroup ( this ) , new OpenViewActionGroup ( this ) , new RubySearchActionGroup ( this ) } ) ; fActionGroups . fillActionBars ( actionBars ) ; fSelectAllAction = new SelectAllAction ( fMethodsViewer ) ; actionBars . setGlobalActionHandler ( ActionFactory . SELECT_ALL . getId ( ) , fSelectAllAction ) ; } private void addResizeListener ( Composite parent ) { parent . addControlListener ( new ControlListener ( ) { public void controlMoved ( ControlEvent e ) { } public void controlResized ( ControlEvent e ) { computeOrientation ( ) ; } } ) ; } void computeOrientation ( ) { if ( fInComputeOrientation ) { return ; } fInComputeOrientation = true ; try { if ( fOrientation != VIEW_ORIENTATION_AUTOMATIC ) { setOrientation ( fOrientation ) ; } else { if ( fOrientation == VIEW_ORIENTATION_SINGLE ) return ; Point size = fParent . getSize ( ) ; if ( size . x != && size . y != ) { if ( size . x > size . y ) setOrientation ( VIEW_ORIENTATION_HORIZONTAL ) ; else setOrientation ( VIEW_ORIENTATION_VERTICAL ) ; } } } finally { fInComputeOrientation = false ; } } public void setOrientation ( int orientation ) { if ( fCurrentOrientation != orientation ) { boolean methodViewerNeedsUpdate = false ; if ( fMethodViewerViewForm != null && ! fMethodViewerViewForm . isDisposed ( ) && fTypeMethodsSplitter != null && ! fTypeMethodsSplitter . isDisposed ( ) ) { if ( orientation == VIEW_ORIENTATION_SINGLE ) { fMethodViewerViewForm . setVisible ( false ) ; enableMemberFilter ( false ) ; updateMethodViewer ( null ) ; } else { if ( fCurrentOrientation == VIEW_ORIENTATION_SINGLE ) { fMethodViewerViewForm . setVisible ( true ) ; methodViewerNeedsUpdate = true ; } boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL ; fTypeMethodsSplitter . setOrientation ( horizontal ? SWT . HORIZONTAL : SWT . VERTICAL ) ; } updateMainToolbar ( orientation ) ; fTypeMethodsSplitter . layout ( ) ; } updateCheckedState ( ) ; if ( methodViewerNeedsUpdate ) { updateMethodViewer ( fSelectedType ) ; } fDialogSettings . put ( DIALOGSTORE_VIEWORIENTATION , orientation ) ; fCurrentOrientation = orientation ; } } private void updateCheckedState ( ) { for ( int i = ; i < fToggleOrientationActions . length ; i ++ ) { fToggleOrientationActions [ i ] . setChecked ( fOrientation == fToggleOrientationActions [ i ] . getOrientation ( ) ) ; } } private void updateMainToolbar ( int orientation ) { IActionBars actionBars = getViewSite ( ) . getActionBars ( ) ; IToolBarManager tbmanager = actionBars . getToolBarManager ( ) ; if ( orientation == VIEW_ORIENTATION_HORIZONTAL ) { clearMainToolBar ( tbmanager ) ; ToolBar typeViewerToolBar = new ToolBar ( fTypeViewerViewForm , SWT . FLAT | SWT . WRAP ) ; fillMainToolBar ( new ToolBarManager ( typeViewerToolBar ) ) ; fTypeViewerViewForm . setTopLeft ( typeViewerToolBar ) ; } else { fTypeViewerViewForm . setTopLeft ( null ) ; fillMainToolBar ( tbmanager ) ; } } private void fillMainToolBar ( IToolBarManager tbmanager ) { tbmanager . removeAll ( ) ; for ( int i = ; i < fViewActions . length ; i ++ ) { tbmanager . add ( fViewActions [ i ] ) ; } tbmanager . add ( fHistoryDropDownAction ) ; tbmanager . update ( false ) ; } private void clearMainToolBar ( IToolBarManager tbmanager ) { tbmanager . removeAll ( ) ; tbmanager . update ( false ) ; } private void fillTypesViewerContextMenu ( TypeHierarchyViewer viewer , IMenuManager menu ) { RubyPlugin . createStandardGroups ( menu ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_SHOW , new Separator ( GROUP_FOCUS ) ) ; viewer . contributeToContextMenu ( menu ) ; if ( fFocusOnSelectionAction . canActionBeAdded ( ) ) menu . appendToGroup ( GROUP_FOCUS , fFocusOnSelectionAction ) ; menu . appendToGroup ( GROUP_FOCUS , fFocusOnTypeAction ) ; fActionGroups . setContext ( new ActionContext ( getSite ( ) . getSelectionProvider ( ) . getSelection ( ) ) ) ; fActionGroups . fillContextMenu ( menu ) ; fActionGroups . setContext ( null ) ; } private void fillMethodsViewerContextMenu ( IMenuManager menu ) { RubyPlugin . createStandardGroups ( menu ) ; fMethodsViewer . contributeToContextMenu ( menu ) ; fActionGroups . setContext ( new ActionContext ( getSite ( ) . getSelectionProvider ( ) . getSelection ( ) ) ) ; fActionGroups . fillContextMenu ( menu ) ; fActionGroups . setContext ( null ) ; } private void setViewerVisibility ( boolean showHierarchy ) { if ( showHierarchy ) { fViewerbook . showPage ( getCurrentViewer ( ) . getControl ( ) ) ; } else { fViewerbook . showPage ( fEmptyTypesViewer ) ; } } private void setMemberFilter ( IMember [ ] memberFilter ) { Assert . isNotNull ( fAllViewers ) ; for ( int i = ; i < fAllViewers . length ; i ++ ) { fAllViewers [ i ] . setMemberFilter ( memberFilter ) ; } } private IType getSelectableType ( IRubyElement elem ) { if ( elem . getElementType ( ) != IRubyElement . TYPE ) { return getCurrentViewer ( ) . getTreeRootType ( ) ; } else { return ( IType ) elem ; } } private void internalSelectType ( IMember elem , boolean reveal ) { TypeHierarchyViewer viewer = getCurrentViewer ( ) ; viewer . removePostSelectionChangedListener ( fSelectionChangedListener ) ; viewer . setSelection ( elem != null ? new StructuredSelection ( elem ) : StructuredSelection . EMPTY , reveal ) ; viewer . addPostSelectionChangedListener ( fSelectionChangedListener ) ; } private void updateHierarchyViewer ( final boolean doExpand ) { if ( fInputElement == null ) { fNoHierarchyShownLabel . setText ( TypeHierarchyMessages . TypeHierarchyViewPart_empty ) ; fPagebook . showPage ( fNoHierarchyShownLabel ) ; } else { if ( getCurrentViewer ( ) . containsElements ( ) != null ) { Runnable runnable = new Runnable ( ) { public void run ( ) { getCurrentViewer ( ) . updateContent ( doExpand ) ; } } ; BusyIndicator . showWhile ( getDisplay ( ) , runnable ) ; if ( ! isChildVisible ( fViewerbook , getCurrentViewer ( ) . getControl ( ) ) ) { setViewerVisibility ( true ) ; } } else { fEmptyTypesViewer . setText ( Messages . format ( TypeHierarchyMessages . TypeHierarchyViewPart_nodecl , fInputElement . getElementName ( ) ) ) ; setViewerVisibility ( false ) ; } } } private void updateMethodViewer ( final IType input ) { if ( ! fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE ) { if ( input == fMethodsViewer . getInput ( ) ) { if ( input != null ) { Runnable runnable = new Runnable ( ) { public void run ( ) { fMethodsViewer . refresh ( ) ; } } ; BusyIndicator . showWhile ( getDisplay ( ) , runnable ) ; } } else { if ( input != null ) { fMethodViewerPaneLabel . setText ( fPaneLabelProvider . getText ( input ) ) ; fMethodViewerPaneLabel . setImage ( fPaneLabelProvider . getImage ( input ) ) ; } else { fMethodViewerPaneLabel . setText ( "" ) ; fMethodViewerPaneLabel . setImage ( null ) ; } Runnable runnable = new Runnable ( ) { public void run ( ) { fMethodsViewer . setInput ( input ) ; } } ; BusyIndicator . showWhile ( getDisplay ( ) , runnable ) ; } } } protected void doSelectionChanged ( SelectionChangedEvent e ) { if ( e . getSelectionProvider ( ) == fMethodsViewer ) { methodSelectionChanged ( e . getSelection ( ) ) ; } else { typeSelectionChanged ( e . getSelection ( ) ) ; } } private void methodSelectionChanged ( ISelection sel ) { if ( sel instanceof IStructuredSelection ) { List selected = ( ( IStructuredSelection ) sel ) . toList ( ) ; int nSelected = selected . size ( ) ; if ( fIsEnableMemberFilter ) { IMember [ ] memberFilter = null ; if ( nSelected > ) { memberFilter = new IMember [ nSelected ] ; selected . toArray ( memberFilter ) ; } setMemberFilter ( memberFilter ) ; updateHierarchyViewer ( true ) ; updateTitle ( ) ; internalSelectType ( fSelectedType , true ) ; } if ( nSelected == && fSelectInEditor ) { revealElementInEditor ( selected . get ( ) , fMethodsViewer ) ; } } } private void typeSelectionChanged ( ISelection sel ) { if ( sel instanceof IStructuredSelection ) { List selected = ( ( IStructuredSelection ) sel ) . toList ( ) ; int nSelected = selected . size ( ) ; if ( nSelected != ) { List types = new ArrayList ( nSelected ) ; for ( int i = nSelected - ; i >= ; i -- ) { Object elem = selected . get ( i ) ; if ( elem instanceof IType && ! types . contains ( elem ) ) { types . add ( elem ) ; } } if ( types . size ( ) == ) { fSelectedType = ( IType ) types . get ( ) ; updateMethodViewer ( fSelectedType ) ; } else if ( types . size ( ) == ) { } if ( nSelected == && fSelectInEditor ) { revealElementInEditor ( selected . get ( ) , getCurrentViewer ( ) ) ; } } else { fSelectedType = null ; updateMethodViewer ( null ) ; } } } private void revealElementInEditor ( Object elem , StructuredViewer originViewer ) { if ( getSite ( ) . getPage ( ) . getActivePart ( ) != this ) { return ; } if ( fSelectionProviderMediator . getViewerInFocus ( ) != originViewer ) { return ; } IEditorPart editorPart = EditorUtility . isOpenInEditor ( elem ) ; if ( editorPart != null && ( elem instanceof IRubyElement ) ) { getSite ( ) . getPage ( ) . removePartListener ( fPartListener ) ; getSite ( ) . getPage ( ) . bringToTop ( editorPart ) ; EditorUtility . revealInEditor ( editorPart , ( IRubyElement ) elem ) ; getSite ( ) . getPage ( ) . addPartListener ( fPartListener ) ; } } private Display getDisplay ( ) { if ( fPagebook != null && ! fPagebook . isDisposed ( ) ) { return fPagebook . getDisplay ( ) ; } return null ; } private boolean isChildVisible ( Composite pb , Control child ) { Control [ ] children = pb . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( children [ i ] == child && children [ i ] . isVisible ( ) ) return true ; } return false ; } private void updateTitle ( ) { String viewerTitle = getCurrentViewer ( ) . getTitle ( ) ; String tooltip ; String title ; if ( fInputElement != null ) { IWorkingSet workingSet = fWorkingSetActionGroup . getWorkingSet ( ) ; if ( workingSet == null ) { String [ ] args = new String [ ] { viewerTitle , RubyElementLabels . getElementLabel ( fInputElement , RubyElementLabels . ALL_DEFAULT ) } ; title = Messages . format ( TypeHierarchyMessages . TypeHierarchyViewPart_title , args ) ; tooltip = Messages . format ( TypeHierarchyMessages . TypeHierarchyViewPart_tooltip , args ) ; } else { String [ ] args = new String [ ] { viewerTitle , RubyElementLabels . getElementLabel ( fInputElement , RubyElementLabels . ALL_DEFAULT ) , workingSet . getLabel ( ) } ; title = Messages . format ( TypeHierarchyMessages . TypeHierarchyViewPart_ws_title , args ) ; tooltip = Messages . format ( TypeHierarchyMessages . TypeHierarchyViewPart_ws_tooltip , args ) ; } } else { title = "" ; tooltip = viewerTitle ; } setContentDescription ( title ) ; setTitleToolTip ( tooltip ) ; } private void updateToolbarButtons ( ) { boolean isType = fInputElement instanceof IType ; for ( int i = ; i < fViewActions . length ; i ++ ) { ToggleViewAction action = fViewActions [ i ] ; if ( action . getViewerIndex ( ) == VIEW_ID_TYPE ) { action . setEnabled ( fInputElement != null ) ; } else { action . setEnabled ( isType ) ; } } } public void setView ( int viewerIndex ) { Assert . isNotNull ( fAllViewers ) ; if ( viewerIndex < fAllViewers . length && fCurrentViewerIndex != viewerIndex ) { fCurrentViewerIndex = viewerIndex ; updateHierarchyViewer ( true ) ; if ( fInputElement != null ) { ISelection currSelection = getCurrentViewer ( ) . getSelection ( ) ; if ( currSelection == null || currSelection . isEmpty ( ) ) { internalSelectType ( getSelectableType ( fInputElement ) , false ) ; currSelection = getCurrentViewer ( ) . getSelection ( ) ; } if ( ! fIsEnableMemberFilter ) { typeSelectionChanged ( currSelection ) ; } } updateTitle ( ) ; fDialogSettings . put ( DIALOGSTORE_HIERARCHYVIEW , viewerIndex ) ; getCurrentViewer ( ) . getTree ( ) . setFocus ( ) ; } for ( int i = ; i < fViewActions . length ; i ++ ) { ToggleViewAction action = fViewActions [ i ] ; action . setChecked ( fCurrentViewerIndex == action . getViewerIndex ( ) ) ; } } public int getViewIndex ( ) { return fCurrentViewerIndex ; } private TypeHierarchyViewer getCurrentViewer ( ) { return fAllViewers [ fCurrentViewerIndex ] ; } public void enableMemberFilter ( boolean on ) { if ( on != fIsEnableMemberFilter ) { fIsEnableMemberFilter = on ; if ( ! on ) { IType methodViewerInput = ( IType ) fMethodsViewer . getInput ( ) ; setMemberFilter ( null ) ; updateHierarchyViewer ( true ) ; updateTitle ( ) ; if ( methodViewerInput != null && getCurrentViewer ( ) . isElementShown ( methodViewerInput ) ) { internalSelectType ( methodViewerInput , true ) ; } else if ( fSelectedType != null ) { internalSelectType ( fSelectedType , true ) ; updateMethodViewer ( fSelectedType ) ; } } else { methodSelectionChanged ( fMethodsViewer . getSelection ( ) ) ; } } fEnableMemberFilterAction . setChecked ( on ) ; } public void showQualifiedTypeNames ( boolean on ) { if ( fAllViewers == null ) { return ; } for ( int i = ; i < fAllViewers . length ; i ++ ) { fAllViewers [ i ] . setQualifiedTypeName ( on ) ; } } private boolean isShowQualifiedTypeNames ( ) { return fShowQualifiedTypeNamesAction . isChecked ( ) ; } protected void doTypeHierarchyChanged ( final TypeHierarchyLifeCycle typeHierarchy , final IType [ ] changedTypes ) { if ( ! fIsVisible ) { fNeedRefresh = true ; return ; } if ( fIsRefreshRunnablePosted ) { return ; } Display display = getDisplay ( ) ; if ( display != null ) { fIsRefreshRunnablePosted = true ; display . asyncExec ( new Runnable ( ) { public void run ( ) { try { if ( fPagebook != null && ! fPagebook . isDisposed ( ) ) { doTypeHierarchyChangedOnViewers ( changedTypes ) ; } } finally { fIsRefreshRunnablePosted = false ; } } } ) ; } } protected void doTypeHierarchyChangedOnViewers ( IType [ ] changedTypes ) { if ( fHierarchyLifeCycle . getHierarchy ( ) == null || ! fHierarchyLifeCycle . getHierarchy ( ) . exists ( ) ) { clearInput ( ) ; } else { if ( changedTypes == null ) { try { fHierarchyLifeCycle . ensureRefreshedTypeHierarchy ( fInputElement , getSite ( ) . getWorkbenchWindow ( ) ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , getSite ( ) . getShell ( ) , TypeHierarchyMessages . TypeHierarchyViewPart_exception_title , TypeHierarchyMessages . TypeHierarchyViewPart_exception_message ) ; clearInput ( ) ; return ; } catch ( InterruptedException e ) { return ; } fMethodsViewer . refresh ( ) ; updateHierarchyViewer ( false ) ; } else { Object methodViewerInput = fMethodsViewer . getInput ( ) ; fMethodsViewer . refresh ( ) ; fMethodViewerPaneLabel . setText ( fPaneLabelProvider . getText ( methodViewerInput ) ) ; fMethodViewerPaneLabel . setImage ( fPaneLabelProvider . getImage ( methodViewerInput ) ) ; if ( getCurrentViewer ( ) . isMethodFiltering ( ) ) { if ( changedTypes . length == ) { getCurrentViewer ( ) . refresh ( changedTypes [ ] ) ; } else { updateHierarchyViewer ( false ) ; } } else { getCurrentViewer ( ) . update ( changedTypes , new String [ ] { IBasicPropertyConstants . P_TEXT , IBasicPropertyConstants . P_IMAGE } ) ; } } } } public void init ( IViewSite site , IMemento memento ) throws PartInitException { super . init ( site , memento ) ; fMemento = memento ; } public void saveState ( IMemento memento ) { if ( fPagebook == null ) { if ( fMemento != null ) { memento . putMemento ( fMemento ) ; } return ; } if ( fInputElement != null ) { String handleIndentifier = fInputElement . getHandleIdentifier ( ) ; memento . putString ( TAG_INPUT , handleIndentifier ) ; } memento . putInteger ( TAG_VIEW , getViewIndex ( ) ) ; memento . putInteger ( TAG_ORIENTATION , fOrientation ) ; int weigths [ ] = fTypeMethodsSplitter . getWeights ( ) ; int ratio = ( weigths [ ] * ) / ( weigths [ ] + weigths [ ] ) ; memento . putInteger ( TAG_RATIO , ratio ) ; ScrollBar bar = getCurrentViewer ( ) . getTree ( ) . getVerticalBar ( ) ; int position = bar != null ? bar . getSelection ( ) : ; memento . putInteger ( TAG_VERTICAL_SCROLL , position ) ; IRubyElement selection = ( IRubyElement ) ( ( IStructuredSelection ) getCurrentViewer ( ) . getSelection ( ) ) . getFirstElement ( ) ; if ( selection != null ) { memento . putString ( TAG_SELECTION , selection . getHandleIdentifier ( ) ) ; } fWorkingSetActionGroup . saveState ( memento ) ; fMethodsViewer . saveState ( memento ) ; saveLinkingEnabled ( memento ) ; } private void saveLinkingEnabled ( IMemento memento ) { memento . putInteger ( PreferenceConstants . LINK_TYPEHIERARCHY_TO_EDITOR , fLinkingEnabled ? : ) ; } private void restoreState ( final IMemento memento , IRubyElement defaultInput ) { IRubyElement input = defaultInput ; String elementId = memento . getString ( TAG_INPUT ) ; if ( elementId != null ) { input = RubyCore . create ( elementId ) ; if ( input != null && ! input . exists ( ) ) { input = null ; } } if ( input == null ) { doRestoreState ( memento , input ) ; } else { final IRubyElement hierarchyInput = input ; synchronized ( this ) { String label = Messages . format ( TypeHierarchyMessages . TypeHierarchyViewPart_restoreinput , hierarchyInput . getElementName ( ) ) ; fNoHierarchyShownLabel . setText ( label ) ; fRestoreStateJob = new Job ( label ) { protected IStatus run ( IProgressMonitor monitor ) { try { doRestoreInBackground ( memento , hierarchyInput , monitor ) ; } catch ( RubyModelException e ) { return e . getStatus ( ) ; } catch ( OperationCanceledException e ) { return Status . CANCEL_STATUS ; } return Status . OK_STATUS ; } } ; fRestoreStateJob . schedule ( ) ; } } } private void doRestoreInBackground ( final IMemento memento , final IRubyElement hierarchyInput , IProgressMonitor monitor ) throws RubyModelException { fHierarchyLifeCycle . doHierarchyRefresh ( hierarchyInput , monitor ) ; if ( ! monitor . isCanceled ( ) ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { if ( fPagebook != null && ! fPagebook . isDisposed ( ) ) { doRestoreState ( memento , hierarchyInput ) ; } } } ) ; } } final void doRestoreState ( IMemento memento , IRubyElement input ) { synchronized ( this ) { if ( fRestoreStateJob == null ) { return ; } fRestoreStateJob = null ; } fWorkingSetActionGroup . restoreState ( memento ) ; setInputElement ( input ) ; Integer viewerIndex = memento . getInteger ( TAG_VIEW ) ; if ( viewerIndex != null ) { setView ( viewerIndex . intValue ( ) ) ; } Integer orientation = memento . getInteger ( TAG_ORIENTATION ) ; if ( orientation != null ) { fOrientation = orientation . intValue ( ) ; } computeOrientation ( ) ; updateCheckedState ( ) ; Integer ratio = memento . getInteger ( TAG_RATIO ) ; if ( ratio != null ) { fTypeMethodsSplitter . setWeights ( new int [ ] { ratio . intValue ( ) , - ratio . intValue ( ) } ) ; } ScrollBar bar = getCurrentViewer ( ) . getTree ( ) . getVerticalBar ( ) ; if ( bar != null ) { Integer vScroll = memento . getInteger ( TAG_VERTICAL_SCROLL ) ; if ( vScroll != null ) { bar . setSelection ( vScroll . intValue ( ) ) ; } } fMethodsViewer . restoreState ( memento ) ; } private void restoreLinkingEnabled ( IMemento memento ) { Integer val = memento . getInteger ( PreferenceConstants . LINK_TYPEHIERARCHY_TO_EDITOR ) ; if ( val != null ) { fLinkingEnabled = val . intValue ( ) != ; } } protected void visibilityChanged ( boolean isVisible ) { fIsVisible = isVisible ; if ( isVisible && fNeedRefresh ) { doTypeHierarchyChangedOnViewers ( null ) ; } fNeedRefresh = false ; } protected void editorActivated ( IEditorPart editor ) { if ( ! isLinkingEnabled ( ) ) { return ; } if ( fInputElement == null ) { return ; } IRubyElement elem = ( IRubyElement ) editor . getEditorInput ( ) . getAdapter ( IRubyElement . class ) ; IType type = null ; if ( elem instanceof IRubyScript ) { type = ( ( IRubyScript ) elem ) . findPrimaryType ( ) ; } if ( type != null ) { internalSelectType ( type , true ) ; if ( getCurrentViewer ( ) . getSelection ( ) . isEmpty ( ) ) { updateMethodViewer ( null ) ; } else { updateMethodViewer ( type ) ; } } } public Object getViewPartInput ( ) { return fInputElement ; } protected IShowInSource getShowInSource ( ) { return new IShowInSource ( ) { public ShowInContext getShowInContext ( ) { return new ShowInContext ( null , getSite ( ) . getSelectionProvider ( ) . getSelection ( ) ) ; } } ; } boolean isLinkingEnabled ( ) { return fLinkingEnabled ; } public void setLinkingEnabled ( boolean enabled ) { fLinkingEnabled = enabled ; PreferenceConstants . getPreferenceStore ( ) . setValue ( PreferenceConstants . LINK_TYPEHIERARCHY_TO_EDITOR , enabled ) ; if ( enabled ) { IEditorPart editor = getSite ( ) . getPage ( ) . getActiveEditor ( ) ; if ( editor != null ) { editorActivated ( editor ) ; } } } public void clearNeededRefresh ( ) { fNeedRefresh = false ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . IWorkingCopyProvider ; public class MethodsContentProvider implements IStructuredContentProvider , IWorkingCopyProvider { private static final Object [ ] NO_ELEMENTS = new Object [ ] ; private boolean fShowInheritedMethods ; private TypeHierarchyLifeCycle fHierarchyLifeCycle ; private TableViewer fViewer ; public MethodsContentProvider ( TypeHierarchyLifeCycle lifecycle ) { fHierarchyLifeCycle = lifecycle ; fShowInheritedMethods = false ; fViewer = null ; } public void showInheritedMethods ( boolean show ) { if ( show != fShowInheritedMethods ) { fShowInheritedMethods = show ; if ( fViewer != null ) { fViewer . refresh ( ) ; } } } public boolean providesWorkingCopies ( ) { return true ; } public boolean isShowInheritedMethods ( ) { return fShowInheritedMethods ; } private void addAll ( Object [ ] arr , List res ) { if ( arr != null ) { for ( int j = ; j < arr . length ; j ++ ) { res . add ( arr [ j ] ) ; } } } public Object [ ] getElements ( Object element ) { if ( element instanceof IType ) { IType type = ( IType ) element ; List res = new ArrayList ( ) ; try { ITypeHierarchy hierarchy = fHierarchyLifeCycle . getHierarchy ( ) ; if ( fShowInheritedMethods && hierarchy != null ) { IType [ ] allSupertypes = hierarchy . getAllSupertypes ( type ) ; for ( int i = allSupertypes . length - ; i >= ; i -- ) { IType superType = allSupertypes [ i ] ; if ( superType . exists ( ) ) { addAll ( superType . getMethods ( ) , res ) ; addAll ( superType . getFields ( ) , res ) ; } } } if ( type . exists ( ) ) { addAll ( type . getMethods ( ) , res ) ; addAll ( type . getFields ( ) , res ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return res . toArray ( ) ; } return NO_ELEMENTS ; } public void inputChanged ( Viewer input , Object oldInput , Object newInput ) { Assert . isTrue ( input instanceof TableViewer ) ; fViewer = ( TableViewer ) input ; } public void dispose ( ) { } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . util . List ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . IWorkbenchPart ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; public class SubTypeHierarchyViewer extends TypeHierarchyViewer { public SubTypeHierarchyViewer ( Composite parent , TypeHierarchyLifeCycle lifeCycle , IWorkbenchPart part ) { super ( parent , new SubTypeHierarchyContentProvider ( lifeCycle ) , lifeCycle , part ) ; } public String getTitle ( ) { if ( isMethodFiltering ( ) ) { return TypeHierarchyMessages . SubTypeHierarchyViewer_filtered_title ; } else { return TypeHierarchyMessages . SubTypeHierarchyViewer_title ; } } public void updateContent ( boolean expand ) { getTree ( ) . setRedraw ( false ) ; refresh ( ) ; if ( expand ) { int expandLevel = ; if ( isMethodFiltering ( ) ) { expandLevel ++ ; } expandToLevel ( expandLevel ) ; } getTree ( ) . setRedraw ( true ) ; } public static class SubTypeHierarchyContentProvider extends TypeHierarchyContentProvider { public SubTypeHierarchyContentProvider ( TypeHierarchyLifeCycle lifeCycle ) { super ( lifeCycle ) ; } protected final void getTypesInHierarchy ( IType type , List res ) { ITypeHierarchy hierarchy = getHierarchy ( ) ; if ( hierarchy != null ) { IType [ ] types = hierarchy . getSubtypes ( type ) ; if ( isObject ( type ) ) { for ( int i = ; i < types . length ; i ++ ) { IType curr = types [ i ] ; if ( ! isAnonymousFromInterface ( curr ) ) { res . add ( curr ) ; } } } else { for ( int i = ; i < types . length ; i ++ ) { res . add ( types [ i ] ) ; } } } } protected IType getParentType ( IType type ) { ITypeHierarchy hierarchy = getHierarchy ( ) ; if ( hierarchy != null ) { return hierarchy . getSuperclass ( type ) ; } return null ; } } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . MethodOverrideTester ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class MethodsLabelProvider extends AppearanceAwareLabelProvider { private Color fResolvedBackground ; private boolean fShowDefiningType ; private TypeHierarchyLifeCycle fHierarchy ; private MethodsViewer fMethodsViewer ; public MethodsLabelProvider ( TypeHierarchyLifeCycle lifeCycle , MethodsViewer methodsViewer ) { super ( DEFAULT_TEXTFLAGS , DEFAULT_IMAGEFLAGS ) ; fHierarchy = lifeCycle ; fShowDefiningType = false ; fMethodsViewer = methodsViewer ; fResolvedBackground = null ; } public void setShowDefiningType ( boolean showDefiningType ) { fShowDefiningType = showDefiningType ; } public boolean isShowDefiningType ( ) { return fShowDefiningType ; } private IType getDefiningType ( Object element ) throws RubyModelException { int kind = ( ( IRubyElement ) element ) . getElementType ( ) ; if ( kind != IRubyElement . METHOD && kind != IRubyElement . FIELD && kind != IRubyElement . CONSTANT && kind != IRubyElement . INSTANCE_VAR && kind != IRubyElement . CLASS_VAR ) { return null ; } IType declaringType = ( ( IMember ) element ) . getDeclaringType ( ) ; if ( kind != IRubyElement . METHOD ) { return declaringType ; } ITypeHierarchy hierarchy = fHierarchy . getHierarchy ( ) ; if ( hierarchy == null ) { return declaringType ; } IMethod method = ( IMethod ) element ; MethodOverrideTester tester = new MethodOverrideTester ( declaringType , hierarchy ) ; IMethod res = tester . findDeclaringMethod ( method , true ) ; if ( res == null || method . equals ( res ) ) { return declaringType ; } return res . getDeclaringType ( ) ; } public String getText ( Object element ) { String text = super . getText ( element ) ; if ( fShowDefiningType ) { try { IType type = getDefiningType ( element ) ; if ( type != null ) { StringBuffer buf = new StringBuffer ( super . getText ( type ) ) ; buf . append ( RubyElementLabels . CONCAT_STRING ) ; buf . append ( text ) ; return buf . toString ( ) ; } } catch ( RubyModelException e ) { } } return text ; } public Color getForeground ( Object element ) { if ( fMethodsViewer . isShowInheritedMethods ( ) && element instanceof IMethod ) { IMethod curr = ( IMethod ) element ; IMember declaringType = curr . getDeclaringType ( ) ; if ( declaringType . equals ( fMethodsViewer . getInput ( ) ) ) { if ( fResolvedBackground == null ) { Display display = Display . getCurrent ( ) ; fResolvedBackground = display . getSystemColor ( SWT . COLOR_DARK_BLUE ) ; } return fResolvedBackground ; } } return null ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . MethodOverrideTester ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . ui . IWorkingCopyProvider ; public abstract class TypeHierarchyContentProvider implements ITreeContentProvider , IWorkingCopyProvider { protected static final Object [ ] NO_ELEMENTS = new Object [ ] ; protected TypeHierarchyLifeCycle fTypeHierarchy ; protected IMember [ ] fMemberFilter ; protected TreeViewer fViewer ; private ViewerFilter fWorkingSetFilter ; private MethodOverrideTester fMethodOverrideTester ; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener ; public TypeHierarchyContentProvider ( TypeHierarchyLifeCycle lifecycle ) { fTypeHierarchy = lifecycle ; fMemberFilter = null ; fWorkingSetFilter = null ; fMethodOverrideTester = null ; fTypeHierarchyLifeCycleListener = new ITypeHierarchyLifeCycleListener ( ) { public void typeHierarchyChanged ( TypeHierarchyLifeCycle typeHierarchyProvider , IType [ ] changedTypes ) { if ( changedTypes == null ) { fMethodOverrideTester = null ; } } } ; lifecycle . addChangedListener ( fTypeHierarchyLifeCycleListener ) ; } public final void setMemberFilter ( IMember [ ] memberFilter ) { fMemberFilter = memberFilter ; } private boolean initializeMethodOverrideTester ( IMethod filterMethod , IType typeToFindIn ) { IType filterType = filterMethod . getDeclaringType ( ) ; ITypeHierarchy hierarchy = fTypeHierarchy . getHierarchy ( ) ; boolean filterOverrides = RubyModelUtil . isSuperType ( hierarchy , typeToFindIn , filterType ) ; IType focusType = filterOverrides ? filterType : typeToFindIn ; if ( fMethodOverrideTester == null || ! fMethodOverrideTester . getFocusType ( ) . equals ( focusType ) ) { fMethodOverrideTester = new MethodOverrideTester ( focusType , hierarchy ) ; } return filterOverrides ; } private void addCompatibleMethods ( IMethod filterMethod , IType typeToFindIn , List children ) throws RubyModelException { boolean filterMethodOverrides = initializeMethodOverrideTester ( filterMethod , typeToFindIn ) ; IMethod [ ] methods = typeToFindIn . getMethods ( ) ; for ( int i = ; i < methods . length ; i ++ ) { IMethod curr = methods [ i ] ; if ( isCompatibleMethod ( filterMethod , curr , filterMethodOverrides ) && ! children . contains ( curr ) ) { children . add ( curr ) ; } } } private boolean hasCompatibleMethod ( IMethod filterMethod , IType typeToFindIn ) throws RubyModelException { boolean filterMethodOverrides = initializeMethodOverrideTester ( filterMethod , typeToFindIn ) ; IMethod [ ] methods = typeToFindIn . getMethods ( ) ; for ( int i = ; i < methods . length ; i ++ ) { if ( isCompatibleMethod ( filterMethod , methods [ i ] , filterMethodOverrides ) ) { return true ; } } return false ; } private boolean isCompatibleMethod ( IMethod filterMethod , IMethod method , boolean filterOverrides ) throws RubyModelException { if ( filterOverrides ) { return fMethodOverrideTester . isSubsignature ( filterMethod , method ) ; } else { return fMethodOverrideTester . isSubsignature ( method , filterMethod ) ; } } public IMember [ ] getMemberFilter ( ) { return fMemberFilter ; } public void setWorkingSetFilter ( ViewerFilter filter ) { fWorkingSetFilter = filter ; } protected final ITypeHierarchy getHierarchy ( ) { return fTypeHierarchy . getHierarchy ( ) ; } public boolean providesWorkingCopies ( ) { return true ; } public Object [ ] getElements ( Object parent ) { ArrayList types = new ArrayList ( ) ; getRootTypes ( types ) ; for ( int i = types . size ( ) - ; i >= ; i -- ) { IType curr = ( IType ) types . get ( i ) ; try { if ( ! isInTree ( curr ) ) { types . remove ( i ) ; } } catch ( RubyModelException e ) { } } return types . toArray ( ) ; } protected void getRootTypes ( List res ) { ITypeHierarchy hierarchy = getHierarchy ( ) ; if ( hierarchy != null ) { IType input = hierarchy . getType ( ) ; if ( input != null ) { res . add ( input ) ; } } } protected abstract void getTypesInHierarchy ( IType type , List res ) ; protected abstract IType getParentType ( IType type ) ; private boolean isInScope ( IType type ) { if ( fWorkingSetFilter != null && ! fWorkingSetFilter . select ( null , null , type ) ) { return false ; } IRubyElement input = fTypeHierarchy . getInputElement ( ) ; int inputType = input . getElementType ( ) ; if ( inputType == IRubyElement . TYPE ) { return true ; } IRubyElement parent = type . getAncestor ( input . getElementType ( ) ) ; if ( inputType == IRubyElement . SOURCE_FOLDER ) { if ( parent == null || parent . getElementName ( ) . equals ( input . getElementName ( ) ) ) { return true ; } } else if ( input . equals ( parent ) ) { return true ; } return false ; } public Object [ ] getChildren ( Object element ) { if ( element instanceof IType ) { try { IType type = ( IType ) element ; List children = new ArrayList ( ) ; if ( fMemberFilter != null ) { addFilteredMemberChildren ( type , children ) ; } addTypeChildren ( type , children ) ; return children . toArray ( ) ; } catch ( RubyModelException e ) { } } return NO_ELEMENTS ; } public boolean hasChildren ( Object element ) { if ( element instanceof IType ) { try { IType type = ( IType ) element ; return hasTypeChildren ( type ) || ( fMemberFilter != null && hasMemberFilterChildren ( type ) ) ; } catch ( RubyModelException e ) { return false ; } } return false ; } private void addFilteredMemberChildren ( IType parent , List children ) throws RubyModelException { for ( int i = ; i < fMemberFilter . length ; i ++ ) { IMember member = fMemberFilter [ i ] ; if ( parent . equals ( member . getDeclaringType ( ) ) ) { if ( ! children . contains ( member ) ) { children . add ( member ) ; } } else if ( member instanceof IMethod ) { addCompatibleMethods ( ( IMethod ) member , parent , children ) ; } } } private void addTypeChildren ( IType type , List children ) throws RubyModelException { ArrayList types = new ArrayList ( ) ; getTypesInHierarchy ( type , types ) ; int len = types . size ( ) ; for ( int i = ; i < len ; i ++ ) { IType curr = ( IType ) types . get ( i ) ; if ( isInTree ( curr ) ) { children . add ( curr ) ; } } } protected final boolean isInTree ( IType type ) throws RubyModelException { if ( isInScope ( type ) ) { if ( fMemberFilter != null ) { return hasMemberFilterChildren ( type ) || hasTypeChildren ( type ) ; } else { return true ; } } return hasTypeChildren ( type ) ; } private boolean hasMemberFilterChildren ( IType type ) throws RubyModelException { for ( int i = ; i < fMemberFilter . length ; i ++ ) { IMember member = fMemberFilter [ i ] ; if ( type . equals ( member . getDeclaringType ( ) ) ) { return true ; } else if ( member instanceof IMethod ) { if ( hasCompatibleMethod ( ( IMethod ) member , type ) ) { return true ; } } } return false ; } private boolean hasTypeChildren ( IType type ) throws RubyModelException { ArrayList types = new ArrayList ( ) ; getTypesInHierarchy ( type , types ) ; int len = types . size ( ) ; for ( int i = ; i < len ; i ++ ) { IType curr = ( IType ) types . get ( i ) ; if ( isInTree ( curr ) ) { return true ; } } return false ; } public void inputChanged ( Viewer part , Object oldInput , Object newInput ) { Assert . isTrue ( part instanceof TreeViewer ) ; fViewer = ( TreeViewer ) part ; } public void dispose ( ) { fTypeHierarchy . removeChangedListener ( fTypeHierarchyLifeCycleListener ) ; } public Object getParent ( Object element ) { if ( element instanceof IMember ) { IMember member = ( IMember ) element ; if ( member . getElementType ( ) == IRubyElement . TYPE ) { return getParentType ( ( IType ) member ) ; } return member . getDeclaringType ( ) ; } return null ; } protected final boolean isAnonymous ( IType type ) { return type . getElementName ( ) . length ( ) == ; } protected final boolean isAnonymousFromInterface ( IType type ) { return isAnonymous ( type ) && fTypeHierarchy . getHierarchy ( ) . getSuperModules ( type ) . length != ; } protected final boolean isObject ( IType type ) { return "" . equals ( type . getElementName ( ) ) && type . getDeclaringType ( ) == null && "" . equals ( type . getSourceFolder ( ) . getElementName ( ) ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . rubypeople . rdt . core . IType ; public interface ITypeHierarchyLifeCycleListener { void typeHierarchyChanged ( TypeHierarchyLifeCycle typeHierarchyProvider , IType [ ] changedTypes ) ; } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; public class HistoryListAction extends Action { private class HistoryListDialog extends StatusDialog { private ListDialogField fHistoryList ; private IStatus fHistoryStatus ; private IRubyElement fResult ; private HistoryListDialog ( Shell shell , IRubyElement [ ] elements ) { super ( shell ) ; setTitle ( TypeHierarchyMessages . HistoryListDialog_title ) ; String [ ] buttonLabels = new String [ ] { TypeHierarchyMessages . HistoryListDialog_remove_button , } ; IListAdapter adapter = new IListAdapter ( ) { public void customButtonPressed ( ListDialogField field , int index ) { doCustomButtonPressed ( ) ; } public void selectionChanged ( ListDialogField field ) { doSelectionChanged ( ) ; } public void doubleClicked ( ListDialogField field ) { doDoubleClicked ( ) ; } } ; RubyElementLabelProvider labelProvider = new RubyElementLabelProvider ( RubyElementLabelProvider . SHOW_QUALIFIED | RubyElementLabelProvider . SHOW_ROOT ) ; fHistoryList = new ListDialogField ( adapter , buttonLabels , labelProvider ) ; fHistoryList . setLabelText ( TypeHierarchyMessages . HistoryListDialog_label ) ; fHistoryList . setElements ( Arrays . asList ( elements ) ) ; ISelection sel ; if ( elements . length > ) { sel = new StructuredSelection ( elements [ ] ) ; } else { sel = new StructuredSelection ( ) ; } fHistoryList . selectElements ( sel ) ; } protected Control createDialogArea ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; inner . setFont ( parent . getFont ( ) ) ; inner . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; LayoutUtil . doDefaultLayout ( inner , new DialogField [ ] { fHistoryList } , true , , ) ; LayoutUtil . setHeightHint ( fHistoryList . getListControl ( null ) , convertHeightInCharsToPixels ( ) ) ; LayoutUtil . setHorizontalGrabbing ( fHistoryList . getListControl ( null ) ) ; applyDialogFont ( composite ) ; return composite ; } private void doCustomButtonPressed ( ) { fHistoryList . removeElements ( fHistoryList . getSelectedElements ( ) ) ; } private void doDoubleClicked ( ) { if ( fHistoryStatus . isOK ( ) ) { okPressed ( ) ; } } private void doSelectionChanged ( ) { StatusInfo status = new StatusInfo ( ) ; List selected = fHistoryList . getSelectedElements ( ) ; if ( selected . size ( ) != ) { status . setError ( "" ) ; fResult = null ; } else { fResult = ( IRubyElement ) selected . get ( ) ; } fHistoryList . enableButton ( , fHistoryList . getSize ( ) > selected . size ( ) && selected . size ( ) != ) ; fHistoryStatus = status ; updateStatus ( status ) ; } public IRubyElement getResult ( ) { return fResult ; } public IRubyElement [ ] getRemaining ( ) { List elems = fHistoryList . getElements ( ) ; return ( IRubyElement [ ] ) elems . toArray ( new IRubyElement [ elems . size ( ) ] ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . HISTORY_LIST_DIALOG ) ; } public void create ( ) { setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; super . create ( ) ; } } private TypeHierarchyViewPart fView ; public HistoryListAction ( TypeHierarchyViewPart view ) { fView = view ; setText ( TypeHierarchyMessages . HistoryListAction_label ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . HISTORY_LIST_ACTION ) ; } public void run ( ) { IRubyElement [ ] historyEntries = fView . getHistoryEntries ( ) ; HistoryListDialog dialog = new HistoryListDialog ( RubyPlugin . getActiveWorkbenchShell ( ) , historyEntries ) ; if ( dialog . open ( ) == Window . OK ) { fView . setHistoryEntries ( dialog . getRemaining ( ) ) ; fView . setInputElement ( dialog . getResult ( ) ) ; } } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class EnableMemberFilterAction extends Action { private TypeHierarchyViewPart fView ; public EnableMemberFilterAction ( TypeHierarchyViewPart v , boolean initValue ) { super ( TypeHierarchyMessages . EnableMemberFilterAction_label ) ; setDescription ( TypeHierarchyMessages . EnableMemberFilterAction_description ) ; setToolTipText ( TypeHierarchyMessages . EnableMemberFilterAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; fView = v ; setChecked ( initValue ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . ENABLE_METHODFILTER_ACTION ) ; } public void run ( ) { BusyIndicator . showWhile ( fView . getSite ( ) . getShell ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fView . enableMemberFilter ( isChecked ( ) ) ; } } ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class HistoryAction extends Action { private TypeHierarchyViewPart fViewPart ; private IRubyElement fElement ; public HistoryAction ( TypeHierarchyViewPart viewPart , IRubyElement element ) { super ( "" , AS_RADIO_BUTTON ) ; fViewPart = viewPart ; fElement = element ; String elementName = RubyElementLabels . getElementLabel ( element , RubyElementLabels . ALL_POST_QUALIFIED | RubyElementLabels . ALL_DEFAULT ) ; setText ( elementName ) ; setImageDescriptor ( getImageDescriptor ( element ) ) ; setDescription ( Messages . format ( TypeHierarchyMessages . HistoryAction_description , elementName ) ) ; setToolTipText ( Messages . format ( TypeHierarchyMessages . HistoryAction_tooltip , elementName ) ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . HISTORY_ACTION ) ; } private ImageDescriptor getImageDescriptor ( IRubyElement elem ) { RubyElementImageProvider imageProvider = new RubyElementImageProvider ( ) ; ImageDescriptor desc = imageProvider . getBaseImageDescriptor ( elem , ) ; imageProvider . dispose ( ) ; return desc ; } public void run ( ) { fViewPart . gotoHistoryEntry ( fElement ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . osgi . util . NLS ; public final class TypeHierarchyMessages extends NLS { private static final String BUNDLE_NAME = TypeHierarchyMessages . class . getName ( ) ; private TypeHierarchyMessages ( ) { } public static String EnableMemberFilterAction_label ; public static String EnableMemberFilterAction_tooltip ; public static String EnableMemberFilterAction_description ; public static String HistoryDropDownAction_clearhistory_label ; public static String ToggleOrientationAction_horizontal_label ; public static String ToggleOrientationAction_horizontal_tooltip ; public static String ToggleOrientationAction_horizontal_description ; public static String ToggleOrientationAction_vertical_label ; public static String ToggleOrientationAction_vertical_tooltip ; public static String ToggleOrientationAction_vertical_description ; public static String ToggleOrientationAction_automatic_label ; public static String ToggleOrientationAction_automatic_tooltip ; public static String ToggleOrientationAction_automatic_description ; public static String ToggleOrientationAction_single_label ; public static String ToggleOrientationAction_single_tooltip ; public static String ToggleOrientationAction_single_description ; public static String FocusOnSelectionAction_label ; public static String FocusOnSelectionAction_tooltip ; public static String FocusOnSelectionAction_description ; public static String FocusOnTypeAction_label ; public static String FocusOnTypeAction_tooltip ; public static String FocusOnTypeAction_description ; public static String FocusOnTypeAction_dialog_title ; public static String FocusOnTypeAction_dialog_message ; public static String HistoryDropDownAction_tooltip ; public static String HistoryAction_description ; public static String HistoryAction_tooltip ; public static String HistoryListDialog_title ; public static String HistoryListDialog_label ; public static String HistoryListDialog_remove_button ; public static String HistoryListAction_label ; public static String ShowInheritedMembersAction_label ; public static String ShowInheritedMembersAction_tooltip ; public static String ShowInheritedMembersAction_description ; public static String ShowQualifiedTypeNamesAction_label ; public static String ShowQualifiedTypeNamesAction_tooltip ; public static String ShowQualifiedTypeNamesAction_description ; public static String SortByDefiningTypeAction_label ; public static String SortByDefiningTypeAction_tooltip ; public static String SortByDefiningTypeAction_description ; public static String SubTypeHierarchyViewer_title ; public static String SubTypeHierarchyViewer_filtered_title ; public static String SuperTypeHierarchyViewer_title ; public static String SuperTypeHierarchyViewer_filtered_title ; public static String TraditionalHierarchyViewer_title ; public static String TraditionalHierarchyViewer_filtered_title ; public static String TypeHierarchyViewPart_error_title ; public static String TypeHierarchyViewPart_error_message ; public static String TypeHierarchyViewPart_empty ; public static String TypeHierarchyViewPart_nodecl ; public static String TypeHierarchyViewPart_exception_title ; public static String TypeHierarchyViewPart_exception_message ; public static String TypeHierarchyViewPart_title ; public static String TypeHierarchyViewPart_tooltip ; public static String TypeHierarchyViewPart_ws_title ; public static String TypeHierarchyViewPart_ws_tooltip ; public static String TypeHierarchyViewPart_restoreinput ; public static String TypeHierarchyViewPart_layout_submenu ; public static String ToggleViewAction_subtypes_label ; public static String ToggleViewAction_subtypes_tooltip ; public static String ToggleViewAction_subtypes_description ; public static String ToggleViewAction_supertypes_label ; public static String ToggleViewAction_supertypes_tooltip ; public static String ToggleViewAction_supertypes_description ; public static String ToggleViewAction_vajhierarchy_label ; public static String ToggleViewAction_vajhierarchy_tooltip ; public static String ToggleViewAction_vajhierarchy_description ; public static String HierarchyInformationControl_methodhierarchy_label ; public static String HierarchyInformationControl_hierarchy_label ; public static String HierarchyInformationControl_toggle_traditionalhierarchy_label ; public static String HierarchyInformationControl_toggle_superhierarchy_label ; static { NLS . initializeMessages ( BUNDLE_NAME , TypeHierarchyMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . IOpenListener ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartSite ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . internal . ui . viewsupport . DecoratingRubyLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTreeViewer ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . actions . OpenAction ; public abstract class TypeHierarchyViewer extends ProblemTreeViewer { private OpenAction fOpen ; private HierarchyLabelProvider fLabelProvider ; public TypeHierarchyViewer ( Composite parent , IContentProvider contentProvider , TypeHierarchyLifeCycle lifeCycle , IWorkbenchPart part ) { super ( new Tree ( parent , SWT . SINGLE ) ) ; fLabelProvider = new HierarchyLabelProvider ( lifeCycle ) ; setLabelProvider ( new DecoratingRubyLabelProvider ( fLabelProvider , true ) ) ; setUseHashlookup ( true ) ; setContentProvider ( contentProvider ) ; setSorter ( new HierarchyViewerSorter ( lifeCycle ) ) ; fOpen = new OpenAction ( part . getSite ( ) ) ; addOpenListener ( new IOpenListener ( ) { public void open ( OpenEvent event ) { fOpen . run ( ) ; } } ) ; } public void setQualifiedTypeName ( boolean on ) { if ( on ) { fLabelProvider . setTextFlags ( fLabelProvider . getTextFlags ( ) | RubyElementLabels . T_POST_QUALIFIED ) ; } else { fLabelProvider . setTextFlags ( fLabelProvider . getTextFlags ( ) & ~ RubyElementLabels . T_POST_QUALIFIED ) ; } refresh ( ) ; } public void initContextMenu ( IMenuListener menuListener , String popupId , IWorkbenchPartSite viewSite ) { MenuManager menuMgr = new MenuManager ( ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( menuListener ) ; Menu menu = menuMgr . createContextMenu ( getTree ( ) ) ; getTree ( ) . setMenu ( menu ) ; viewSite . registerContextMenu ( popupId , menuMgr , this ) ; } public void contributeToContextMenu ( IMenuManager menu ) { } public void setMemberFilter ( IMember [ ] memberFilter ) { TypeHierarchyContentProvider contentProvider = getHierarchyContentProvider ( ) ; if ( contentProvider != null ) { contentProvider . setMemberFilter ( memberFilter ) ; } } public boolean isMethodFiltering ( ) { TypeHierarchyContentProvider contentProvider = getHierarchyContentProvider ( ) ; if ( contentProvider != null ) { return contentProvider . getMemberFilter ( ) != null ; } return false ; } public void setWorkingSetFilter ( ViewerFilter filter ) { fLabelProvider . setFilter ( filter ) ; TypeHierarchyContentProvider contentProvider = getHierarchyContentProvider ( ) ; if ( contentProvider != null ) { contentProvider . setWorkingSetFilter ( filter ) ; } } public Object containsElements ( ) { TypeHierarchyContentProvider contentProvider = getHierarchyContentProvider ( ) ; if ( contentProvider != null ) { Object [ ] elements = contentProvider . getElements ( null ) ; if ( elements . length > ) { return elements [ ] ; } } return null ; } public IType getTreeRootType ( ) { TypeHierarchyContentProvider contentProvider = getHierarchyContentProvider ( ) ; if ( contentProvider != null ) { Object [ ] elements = contentProvider . getElements ( null ) ; if ( elements . length > && elements [ ] instanceof IType ) { return ( IType ) elements [ ] ; } } return null ; } public boolean isElementShown ( Object element ) { return findItem ( element ) != null ; } public abstract void updateContent ( boolean doExpand ) ; public abstract String getTitle ( ) ; public void setContentProvider ( IContentProvider cp ) { Assert . isTrue ( cp instanceof TypeHierarchyContentProvider ) ; super . setContentProvider ( cp ) ; } protected TypeHierarchyContentProvider getHierarchyContentProvider ( ) { return ( TypeHierarchyContentProvider ) getContentProvider ( ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class SortByDefiningTypeAction extends Action { private MethodsViewer fMethodsViewer ; public SortByDefiningTypeAction ( MethodsViewer viewer , boolean initValue ) { super ( TypeHierarchyMessages . SortByDefiningTypeAction_label ) ; setDescription ( TypeHierarchyMessages . SortByDefiningTypeAction_description ) ; setToolTipText ( TypeHierarchyMessages . SortByDefiningTypeAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; fMethodsViewer = viewer ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . SORT_BY_DEFINING_TYPE_ACTION ) ; setChecked ( initValue ) ; } public void run ( ) { BusyIndicator . showWhile ( fMethodsViewer . getControl ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fMethodsViewer . sortByDefiningType ( isChecked ( ) ) ; } } ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class ShowQualifiedTypeNamesAction extends Action { private TypeHierarchyViewPart fView ; public ShowQualifiedTypeNamesAction ( TypeHierarchyViewPart v , boolean initValue ) { super ( TypeHierarchyMessages . ShowQualifiedTypeNamesAction_label ) ; setDescription ( TypeHierarchyMessages . ShowQualifiedTypeNamesAction_description ) ; setToolTipText ( TypeHierarchyMessages . ShowQualifiedTypeNamesAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; fView = v ; setChecked ( initValue ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . SHOW_QUALIFIED_NAMES_ACTION ) ; } public void run ( ) { BusyIndicator . showWhile ( fView . getSite ( ) . getShell ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fView . showQualifiedTypeNames ( isChecked ( ) ) ; } } ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . dialogs . TypeSelectionDialog2 ; public class FocusOnTypeAction extends Action { private TypeHierarchyViewPart fViewPart ; public FocusOnTypeAction ( TypeHierarchyViewPart part ) { super ( TypeHierarchyMessages . FocusOnTypeAction_label ) ; setDescription ( TypeHierarchyMessages . FocusOnTypeAction_description ) ; setToolTipText ( TypeHierarchyMessages . FocusOnTypeAction_tooltip ) ; fViewPart = part ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FOCUS_ON_TYPE_ACTION ) ; } public void run ( ) { Shell parent = fViewPart . getSite ( ) . getShell ( ) ; TypeSelectionDialog2 dialog = new TypeSelectionDialog2 ( parent , false , PlatformUI . getWorkbench ( ) . getProgressService ( ) , SearchEngine . createWorkspaceScope ( ) , IRubySearchConstants . TYPE ) ; dialog . setTitle ( TypeHierarchyMessages . FocusOnTypeAction_dialog_title ) ; dialog . setMessage ( TypeHierarchyMessages . FocusOnTypeAction_dialog_message ) ; if ( dialog . open ( ) != IDialogConstants . OK_ID ) { return ; } Object [ ] types = dialog . getResult ( ) ; if ( types != null && types . length > ) { IType type = ( IType ) types [ ] ; fViewPart . setInputElement ( type ) ; } } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import java . util . List ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . IWorkbenchPart ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; public class SuperTypeHierarchyViewer extends TypeHierarchyViewer { public SuperTypeHierarchyViewer ( Composite parent , TypeHierarchyLifeCycle lifeCycle , IWorkbenchPart part ) { super ( parent , new SuperTypeHierarchyContentProvider ( lifeCycle ) , lifeCycle , part ) ; } public String getTitle ( ) { if ( isMethodFiltering ( ) ) { return TypeHierarchyMessages . SuperTypeHierarchyViewer_filtered_title ; } else { return TypeHierarchyMessages . SuperTypeHierarchyViewer_title ; } } public void updateContent ( boolean expand ) { getTree ( ) . setRedraw ( false ) ; refresh ( ) ; if ( expand ) { expandAll ( ) ; } getTree ( ) . setRedraw ( true ) ; } public static class SuperTypeHierarchyContentProvider extends TypeHierarchyContentProvider { public SuperTypeHierarchyContentProvider ( TypeHierarchyLifeCycle lifeCycle ) { super ( lifeCycle ) ; } protected final void getTypesInHierarchy ( IType type , List res ) { ITypeHierarchy hierarchy = getHierarchy ( ) ; if ( hierarchy != null ) { IType [ ] types = hierarchy . getSupertypes ( type ) ; for ( int i = ; i < types . length ; i ++ ) { res . add ( types [ i ] ) ; } } } protected IType getParentType ( IType type ) { return null ; } } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class ToggleViewAction extends Action { private TypeHierarchyViewPart fViewPart ; private int fViewerIndex ; public ToggleViewAction ( TypeHierarchyViewPart v , int viewerIndex ) { super ( "" , AS_RADIO_BUTTON ) ; String contextHelpId = null ; if ( viewerIndex == TypeHierarchyViewPart . VIEW_ID_SUPER ) { setText ( TypeHierarchyMessages . ToggleViewAction_supertypes_label ) ; contextHelpId = IRubyHelpContextIds . SHOW_SUPERTYPES ; setDescription ( TypeHierarchyMessages . ToggleViewAction_supertypes_description ) ; setToolTipText ( TypeHierarchyMessages . ToggleViewAction_supertypes_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( viewerIndex == TypeHierarchyViewPart . VIEW_ID_SUB ) { setText ( TypeHierarchyMessages . ToggleViewAction_subtypes_label ) ; contextHelpId = IRubyHelpContextIds . SHOW_SUBTYPES ; setDescription ( TypeHierarchyMessages . ToggleViewAction_subtypes_description ) ; setToolTipText ( TypeHierarchyMessages . ToggleViewAction_subtypes_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else if ( viewerIndex == TypeHierarchyViewPart . VIEW_ID_TYPE ) { setText ( TypeHierarchyMessages . ToggleViewAction_vajhierarchy_label ) ; contextHelpId = IRubyHelpContextIds . SHOW_HIERARCHY ; setDescription ( TypeHierarchyMessages . ToggleViewAction_vajhierarchy_description ) ; setToolTipText ( TypeHierarchyMessages . ToggleViewAction_vajhierarchy_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; } else { Assert . isTrue ( false ) ; } fViewPart = v ; fViewerIndex = viewerIndex ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , contextHelpId ) ; } public int getViewerIndex ( ) { return fViewerIndex ; } public void run ( ) { fViewPart . setView ( fViewerIndex ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IMenuCreator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class HistoryDropDownAction extends Action implements IMenuCreator { public static class ClearHistoryAction extends Action { private TypeHierarchyViewPart fView ; public ClearHistoryAction ( TypeHierarchyViewPart view ) { super ( TypeHierarchyMessages . HistoryDropDownAction_clearhistory_label ) ; fView = view ; } public void run ( ) { fView . setHistoryEntries ( new IRubyElement [ ] ) ; fView . setInputElement ( null ) ; } } public static final int RESULTS_IN_DROP_DOWN = ; private TypeHierarchyViewPart fHierarchyView ; private Menu fMenu ; public HistoryDropDownAction ( TypeHierarchyViewPart view ) { fHierarchyView = view ; fMenu = null ; setToolTipText ( TypeHierarchyMessages . HistoryDropDownAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . TYPEHIERARCHY_HISTORY_ACTION ) ; setMenuCreator ( this ) ; } public void dispose ( ) { if ( fMenu != null ) { fMenu . dispose ( ) ; fMenu = null ; } } public Menu getMenu ( Menu parent ) { return null ; } public Menu getMenu ( Control parent ) { if ( fMenu != null ) { fMenu . dispose ( ) ; } fMenu = new Menu ( parent ) ; IRubyElement [ ] elements = fHierarchyView . getHistoryEntries ( ) ; addEntries ( fMenu , elements ) ; new MenuItem ( fMenu , SWT . SEPARATOR ) ; addActionToMenu ( fMenu , new HistoryListAction ( fHierarchyView ) ) ; addActionToMenu ( fMenu , new ClearHistoryAction ( fHierarchyView ) ) ; return fMenu ; } private boolean addEntries ( Menu menu , IRubyElement [ ] elements ) { boolean checked = false ; int min = Math . min ( elements . length , RESULTS_IN_DROP_DOWN ) ; for ( int i = ; i < min ; i ++ ) { HistoryAction action = new HistoryAction ( fHierarchyView , elements [ i ] ) ; action . setChecked ( elements [ i ] . equals ( fHierarchyView . getInputElement ( ) ) ) ; checked = checked || action . isChecked ( ) ; addActionToMenu ( menu , action ) ; } return checked ; } protected void addActionToMenu ( Menu parent , Action action ) { ActionContributionItem item = new ActionContributionItem ( action ) ; item . fill ( parent , - ) ; } public void run ( ) { ( new HistoryListAction ( fHierarchyView ) ) . run ( ) ; } } package org . rubypeople . rdt . internal . ui . typehierarchy ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . util . SelectionUtil ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class FocusOnSelectionAction extends Action { private TypeHierarchyViewPart fViewPart ; public FocusOnSelectionAction ( TypeHierarchyViewPart part ) { super ( TypeHierarchyMessages . FocusOnSelectionAction_label ) ; setDescription ( TypeHierarchyMessages . FocusOnSelectionAction_description ) ; setToolTipText ( TypeHierarchyMessages . FocusOnSelectionAction_tooltip ) ; fViewPart = part ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FOCUS_ON_SELECTION_ACTION ) ; } private ISelection getSelection ( ) { ISelectionProvider provider = fViewPart . getSite ( ) . getSelectionProvider ( ) ; if ( provider != null ) { return provider . getSelection ( ) ; } return null ; } public void run ( ) { Object element = SelectionUtil . getSingleElement ( getSelection ( ) ) ; if ( element instanceof IType ) { fViewPart . setInputElement ( ( IType ) element ) ; } } public boolean canActionBeAdded ( ) { Object element = SelectionUtil . getSingleElement ( getSelection ( ) ) ; if ( element instanceof IType ) { IType type = ( IType ) element ; setText ( Messages . format ( TypeHierarchyMessages . FocusOnSelectionAction_label , RubyElementLabels . getTextLabel ( type , ) ) ) ; return true ; } return false ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . ui . IFolderLayout ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IPerspectiveFactory ; import org . eclipse . ui . console . IConsoleConstants ; import org . eclipse . ui . progress . IProgressConstants ; import org . rubypeople . rdt . ui . IRubyConstants ; import org . rubypeople . rdt . ui . RubyUI ; public class RdtPerspectiveFactory implements IPerspectiveFactory { public RdtPerspectiveFactory ( ) { super ( ) ; } public void createInitialLayout ( IPageLayout layout ) { String editorArea = layout . getEditorArea ( ) ; IFolderLayout folder = layout . createFolder ( "" , IPageLayout . LEFT , ( float ) , editorArea ) ; folder . addView ( RubyUI . ID_RUBY_EXPLORER ) ; folder . addView ( RubyUI . ID_TYPE_HIERARCHY ) ; folder . addPlaceholder ( IPageLayout . ID_RES_NAV ) ; IFolderLayout consoleArea = layout . createFolder ( "" , IPageLayout . BOTTOM , ( float ) , editorArea ) ; consoleArea . addView ( IPageLayout . ID_PROBLEM_VIEW ) ; consoleArea . addView ( IPageLayout . ID_TASK_LIST ) ; consoleArea . addPlaceholder ( IRubyConstants . RI_VIEW_ID ) ; consoleArea . addPlaceholder ( NewSearchUI . SEARCH_VIEW_ID ) ; consoleArea . addPlaceholder ( IConsoleConstants . ID_CONSOLE_VIEW ) ; consoleArea . addPlaceholder ( IPageLayout . ID_BOOKMARKS ) ; consoleArea . addPlaceholder ( IProgressConstants . PROGRESS_VIEW_ID ) ; layout . addView ( IPageLayout . ID_OUTLINE , IPageLayout . RIGHT , ( float ) , editorArea ) ; layout . addActionSet ( IDebugUIConstants . LAUNCH_ACTION_SET ) ; layout . addActionSet ( RubyUI . ID_ACTION_SET ) ; layout . addActionSet ( RubyUI . ID_ELEMENT_CREATION_ACTION_SET ) ; layout . addActionSet ( IPageLayout . ID_NAVIGATE_ACTION_SET ) ; layout . addShowViewShortcut ( RubyUI . ID_RUBY_EXPLORER ) ; layout . addShowViewShortcut ( RubyUI . ID_TYPE_HIERARCHY ) ; layout . addShowViewShortcut ( NewSearchUI . SEARCH_VIEW_ID ) ; layout . addShowViewShortcut ( IConsoleConstants . ID_CONSOLE_VIEW ) ; layout . addShowViewShortcut ( IPageLayout . ID_OUTLINE ) ; layout . addShowViewShortcut ( IPageLayout . ID_PROBLEM_VIEW ) ; layout . addShowViewShortcut ( IPageLayout . ID_RES_NAV ) ; layout . addShowViewShortcut ( IPageLayout . ID_TASK_LIST ) ; layout . addShowViewShortcut ( IProgressConstants . PROGRESS_VIEW_ID ) ; layout . addNewWizardShortcut ( IRubyConstants . ID_NEW_CLASS_WIZARD ) ; layout . addNewWizardShortcut ( "" ) ; layout . addNewWizardShortcut ( "" ) ; layout . addNewWizardShortcut ( "" ) ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . ui . editors . text . EditorsUI ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyUIPreferenceInitializer extends AbstractPreferenceInitializer { public void initializeDefaultPreferences ( ) { IPreferenceStore store = PreferenceConstants . getPreferenceStore ( ) ; EditorsUI . useAnnotationsPreferencePage ( store ) ; EditorsUI . useQuickDiffPreferencePage ( store ) ; PreferenceConstants . initializeDefaultValues ( store ) ; } } package org . rubypeople . rdt . internal . ui ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . ide . IDE . SharedImages ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyProject ; public class RubyProjectLibraryPage { protected RubyProject workingProject ; protected RubyProjectLibraryPage ( RubyProject theWorkingProject ) { super ( ) ; workingProject = theWorkingProject ; } protected Control getControl ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( new FillLayout ( ) ) ; Table projectsTable = new Table ( composite , SWT . CHECK | SWT . BORDER | SWT . MULTI | SWT . FULL_SELECTION ) ; projectsTable . setHeaderVisible ( false ) ; projectsTable . setLinesVisible ( false ) ; projectsTable . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; TableColumn tableColumn = new TableColumn ( projectsTable , SWT . NONE ) ; tableColumn . setWidth ( ) ; tableColumn . setText ( RubyUIMessages . RubyProjectLibraryPage_project ) ; CheckboxTableViewer projectsTableViewer = new CheckboxTableViewer ( projectsTable ) ; projectsTableViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { projectCheckedUnchecked ( event ) ; } } ) ; projectsTableViewer . setContentProvider ( getContentProvider ( ) ) ; projectsTableViewer . setLabelProvider ( getLabelProvider ( ) ) ; projectsTableViewer . setInput ( getWorkspaceProjects ( ) ) ; List < IProject > referencedProjects = new ArrayList ( ) ; try { String [ ] names = workingProject . getRequiredProjectNames ( ) ; for ( int i = ; i < names . length ; i ++ ) { List < IProject > workspaceProjects = getWorkspaceProjects ( ) ; for ( IProject workspaceProject : workspaceProjects ) { if ( workspaceProject . getName ( ) . equals ( names [ i ] ) ) referencedProjects . add ( workspaceProject ) ; } } } catch ( RubyModelException e ) { } projectsTableViewer . setCheckedElements ( referencedProjects . toArray ( ) ) ; return composite ; } protected void projectCheckedUnchecked ( CheckStateChangedEvent event ) { IProject checkEventProject = ( IProject ) event . getElement ( ) ; IRubyProject working = getWorkingProject ( ) ; } protected RubyProject getWorkingProject ( ) { return workingProject ; } protected List < IProject > getWorkspaceProjects ( ) { IWorkspaceRoot root = RubyPlugin . getWorkspace ( ) . getRoot ( ) ; return Arrays . asList ( root . getProjects ( ) ) ; } protected ITableLabelProvider getLabelProvider ( ) { ITableLabelProvider labelProvider = new ITableLabelProvider ( ) { public Image getColumnImage ( Object element , int columnIndex ) { IWorkbench workbench = RubyPlugin . getDefault ( ) . getWorkbench ( ) ; return workbench . getSharedImages ( ) . getImage ( SharedImages . IMG_OBJ_PROJECT ) ; } public String getColumnText ( Object element , int columnIndex ) { if ( element instanceof IProject ) return ( ( IProject ) element ) . getName ( ) ; return RubyUIMessages . RubyProjectLibraryPage_elementNotIProject ; } public void addListener ( ILabelProviderListener listener ) { } public void dispose ( ) { } public boolean isLabelProperty ( Object element , String property ) { return false ; } public void removeListener ( ILabelProviderListener listener ) { } } ; return labelProvider ; } protected IContentProvider getContentProvider ( ) { IStructuredContentProvider contentProvider = new IStructuredContentProvider ( ) { protected List rubyProjects ; public Object [ ] getElements ( Object inputElement ) { return rubyProjects . toArray ( ) ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { rubyProjects = new ArrayList ( ) ; if ( ! ( newInput instanceof List ) ) return ; Iterator workspaceProjectsIterator = ( ( List ) newInput ) . iterator ( ) ; while ( workspaceProjectsIterator . hasNext ( ) ) { Object anObject = workspaceProjectsIterator . next ( ) ; if ( anObject instanceof IProject ) { IProject project = ( IProject ) anObject ; if ( project . getName ( ) != workingProject . getProject ( ) . getName ( ) ) { try { if ( project . hasNature ( RubyCore . NATURE_ID ) ) rubyProjects . add ( project ) ; } catch ( CoreException e ) { } } } } } } ; return contentProvider ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdapterFactory ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; public class ResourceAdapterFactory implements IAdapterFactory { private static Class [ ] PROPERTIES = new Class [ ] { IRubyElement . class } ; public Class [ ] getAdapterList ( ) { return PROPERTIES ; } public Object getAdapter ( Object element , Class key ) { if ( IRubyElement . class . equals ( key ) ) { return RubyCore . create ( ( IResource ) element ) ; } return null ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptEditorInput ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class RubyWorkbenchAdapter implements IWorkbenchAdapter { protected static final Object [ ] NO_CHILDREN = new Object [ ] ; private RubyElementImageProvider fImageProvider ; public RubyWorkbenchAdapter ( ) { fImageProvider = new RubyElementImageProvider ( ) ; } public Object [ ] getChildren ( Object element ) { IRubyElement je = getRubyElement ( element ) ; if ( je instanceof IParent ) { try { return ( ( IParent ) je ) . getChildren ( ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } return NO_CHILDREN ; } public ImageDescriptor getImageDescriptor ( Object element ) { IRubyElement je = getRubyElement ( element ) ; if ( je != null ) return fImageProvider . getRubyImageDescriptor ( je , RubyElementImageProvider . OVERLAY_ICONS | RubyElementImageProvider . SMALL_ICONS ) ; return null ; } public String getLabel ( Object element ) { return RubyElementLabels . getTextLabel ( getRubyElement ( element ) , RubyElementLabels . ALL_DEFAULT ) ; } public Object getParent ( Object element ) { IRubyElement je = getRubyElement ( element ) ; return je != null ? je . getParent ( ) : null ; } private IRubyElement getRubyElement ( Object element ) { if ( element instanceof IRubyElement ) return ( IRubyElement ) element ; if ( element instanceof IRubyScriptEditorInput ) return ( ( IRubyScriptEditorInput ) element ) . getRubyScript ( ) . getPrimaryElement ( ) ; return null ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . Iterator ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; public class TypesContentProvider extends RubyBrowsingContentProvider { TypesContentProvider ( RubyBrowsingPart browsingPart ) { super ( false , browsingPart ) ; } public Object [ ] getChildren ( Object element ) { if ( ! exists ( element ) ) return NO_CHILDREN ; try { startReadInDisplayThread ( ) ; if ( element instanceof IStructuredSelection ) { Assert . isLegal ( false ) ; Object [ ] result = new Object [ ] ; Class clazz = null ; Iterator iter = ( ( IStructuredSelection ) element ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Object item = iter . next ( ) ; if ( clazz == null ) clazz = item . getClass ( ) ; if ( clazz == item . getClass ( ) ) result = concatenate ( result , getChildren ( item ) ) ; else return NO_CHILDREN ; } return result ; } if ( element instanceof IStructuredSelection ) { Assert . isLegal ( false ) ; Object [ ] result = new Object [ ] ; Iterator iter = ( ( IStructuredSelection ) element ) . iterator ( ) ; while ( iter . hasNext ( ) ) result = concatenate ( result , getChildren ( iter . next ( ) ) ) ; return result ; } if ( element instanceof ISourceFolderRoot ) { ISourceFolderRoot root = ( ISourceFolderRoot ) element ; IRubyElement [ ] children = root . getChildren ( ) ; Object [ ] result = new Object [ ] ; for ( int i = ; i < children . length ; i ++ ) { result = concatenate ( result , getChildren ( children [ i ] ) ) ; } return result ; } if ( element instanceof IRubyProject ) { IRubyProject project = ( IRubyProject ) element ; ISourceFolderRoot [ ] roots = project . getSourceFolderRoots ( ) ; Object [ ] result = new Object [ ] ; for ( int i = ; i < roots . length ; i ++ ) { result = concatenate ( result , getChildren ( roots [ i ] ) ) ; } return result ; } if ( element instanceof ISourceFolder ) return getFolderContents ( ( ISourceFolder ) element ) ; if ( element instanceof IRubyScript ) return getTopLevelTypes ( ( IRubyScript ) element ) ; if ( element instanceof IType ) return getSubTypes ( ( IType ) element ) ; return super . getChildren ( element ) ; } catch ( RubyModelException e ) { return NO_CHILDREN ; } finally { finishedReadInDisplayThread ( ) ; } } private Object [ ] getTopLevelTypes ( IRubyScript script ) throws RubyModelException { return script . getTypes ( ) ; } private Object [ ] getSubTypes ( IType type ) throws RubyModelException { return type . getTypes ( ) ; } public boolean hasChildren ( Object element ) { return element instanceof ISourceFolder || ( element instanceof IType && super . hasChildren ( element ) ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . List ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . IOpenListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . events . HelpListener ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Widget ; import org . rubypeople . rdt . core . ISourceFolder ; class PackageViewerWrapper extends StructuredViewer { private StructuredViewer fViewer ; private ListenerList fListenerList ; private ListenerList fSelectionChangedListenerList ; private ListenerList fPostSelectionChangedListenerList ; public PackageViewerWrapper ( ) { fListenerList = new ListenerList ( ListenerList . IDENTITY ) ; fPostSelectionChangedListenerList = new ListenerList ( ListenerList . IDENTITY ) ; fSelectionChangedListenerList = new ListenerList ( ListenerList . IDENTITY ) ; } public void setViewer ( StructuredViewer viewer ) { Assert . isNotNull ( viewer ) ; StructuredViewer oldViewer = fViewer ; fViewer = viewer ; if ( fViewer . getContentProvider ( ) != null ) super . setContentProvider ( fViewer . getContentProvider ( ) ) ; transferFilters ( oldViewer ) ; transferListeners ( ) ; } StructuredViewer getViewer ( ) { return fViewer ; } private void transferFilters ( StructuredViewer oldViewer ) { if ( oldViewer != null ) { ViewerFilter [ ] filters = oldViewer . getFilters ( ) ; for ( int i = ; i < filters . length ; i ++ ) { ViewerFilter filter = filters [ i ] ; fViewer . addFilter ( filter ) ; } } } private void transferListeners ( ) { Object [ ] listeners = fPostSelectionChangedListenerList . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { Object object = listeners [ i ] ; ISelectionChangedListener listener = ( ISelectionChangedListener ) object ; fViewer . addPostSelectionChangedListener ( listener ) ; } listeners = fSelectionChangedListenerList . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { Object object = listeners [ i ] ; ISelectionChangedListener listener = ( ISelectionChangedListener ) object ; fViewer . addSelectionChangedListener ( listener ) ; } listeners = fListenerList . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { Object object = listeners [ i ] ; if ( object instanceof IOpenListener ) { IOpenListener listener = ( IOpenListener ) object ; addOpenListener ( listener ) ; } else if ( object instanceof HelpListener ) { HelpListener listener = ( HelpListener ) object ; addHelpListener ( listener ) ; } else if ( object instanceof IDoubleClickListener ) { IDoubleClickListener listener = ( IDoubleClickListener ) object ; addDoubleClickListener ( listener ) ; } } } public void setSelection ( ISelection selection , boolean reveal ) { fViewer . setSelection ( selection , reveal ) ; } public void addPostSelectionChangedListener ( ISelectionChangedListener listener ) { fPostSelectionChangedListenerList . add ( listener ) ; fViewer . addPostSelectionChangedListener ( listener ) ; } public void addSelectionChangedListener ( ISelectionChangedListener listener ) { fSelectionChangedListenerList . add ( listener ) ; fViewer . addSelectionChangedListener ( listener ) ; } public void addDoubleClickListener ( IDoubleClickListener listener ) { fViewer . addDoubleClickListener ( listener ) ; fListenerList . add ( listener ) ; } public void addOpenListener ( IOpenListener listener ) { fViewer . addOpenListener ( listener ) ; fListenerList . add ( listener ) ; } public void addHelpListener ( HelpListener listener ) { fViewer . addHelpListener ( listener ) ; fListenerList . add ( listener ) ; } public void removeSelectionChangedListener ( ISelectionChangedListener listener ) { fViewer . removeSelectionChangedListener ( listener ) ; fSelectionChangedListenerList . remove ( listener ) ; } public void removePostSelectionChangedListener ( ISelectionChangedListener listener ) { fViewer . removePostSelectionChangedListener ( listener ) ; fPostSelectionChangedListenerList . remove ( listener ) ; } public void removeHelpListener ( HelpListener listener ) { fListenerList . remove ( listener ) ; fViewer . removeHelpListener ( listener ) ; } public void removeDoubleClickListener ( IDoubleClickListener listener ) { fViewer . removeDoubleClickListener ( listener ) ; fListenerList . remove ( listener ) ; } public void removeOpenListener ( IOpenListener listener ) { fViewer . removeOpenListener ( listener ) ; fListenerList . remove ( listener ) ; } public Control getControl ( ) { return fViewer . getControl ( ) ; } public void addFilter ( ViewerFilter filter ) { fViewer . addFilter ( filter ) ; } public void refresh ( ) { fViewer . refresh ( ) ; } public void removeFilter ( ViewerFilter filter ) { fViewer . removeFilter ( filter ) ; } public ISelection getSelection ( ) { return fViewer . getSelection ( ) ; } public void refresh ( boolean updateLabels ) { fViewer . refresh ( updateLabels ) ; } public void refresh ( Object element , boolean updateLabels ) { fViewer . refresh ( element , updateLabels ) ; } public void refresh ( Object element ) { fViewer . refresh ( element ) ; } public void resetFilters ( ) { fViewer . resetFilters ( ) ; } public void reveal ( Object element ) { fViewer . reveal ( element ) ; } public void setContentProvider ( IContentProvider contentProvider ) { fViewer . setContentProvider ( contentProvider ) ; } public void setSorter ( ViewerSorter sorter ) { fViewer . setSorter ( sorter ) ; } public void setUseHashlookup ( boolean enable ) { fViewer . setUseHashlookup ( enable ) ; } public Widget testFindItem ( Object element ) { return fViewer . testFindItem ( element ) ; } public void update ( Object element , String [ ] properties ) { fViewer . update ( element , properties ) ; } public void update ( Object [ ] elements , String [ ] properties ) { fViewer . update ( elements , properties ) ; } public IContentProvider getContentProvider ( ) { return fViewer . getContentProvider ( ) ; } public Object getInput ( ) { return fViewer . getInput ( ) ; } public IBaseLabelProvider getLabelProvider ( ) { return fViewer . getLabelProvider ( ) ; } public void setLabelProvider ( IBaseLabelProvider labelProvider ) { fViewer . setLabelProvider ( labelProvider ) ; } public Object getData ( String key ) { return fViewer . getData ( key ) ; } public Item scrollDown ( int x , int y ) { return fViewer . scrollDown ( x , y ) ; } public Item scrollUp ( int x , int y ) { return fViewer . scrollUp ( x , y ) ; } public void setData ( String key , Object value ) { fViewer . setData ( key , value ) ; } public void setSelection ( ISelection selection ) { fViewer . setSelection ( selection ) ; } public boolean equals ( Object obj ) { return fViewer . equals ( obj ) ; } public int hashCode ( ) { return fViewer . hashCode ( ) ; } public String toString ( ) { return fViewer . toString ( ) ; } public void setViewerInput ( Object input ) { fViewer . setInput ( input ) ; } protected Widget doFindInputItem ( Object element ) { return ( ( IPackagesViewViewer ) fViewer ) . doFindInputItem ( element ) ; } protected Widget doFindItem ( Object element ) { return ( ( IPackagesViewViewer ) fViewer ) . doFindItem ( element ) ; } protected void doUpdateItem ( Widget item , Object element , boolean fullMap ) { ( ( IPackagesViewViewer ) fViewer ) . doUpdateItem ( item , element , fullMap ) ; } protected List getSelectionFromWidget ( ) { return ( ( IPackagesViewViewer ) fViewer ) . getSelectionFromWidget ( ) ; } protected void internalRefresh ( Object element ) { ( ( IPackagesViewViewer ) fViewer ) . internalRefresh ( element ) ; } protected void setSelectionToWidget ( List l , boolean reveal ) { ( ( IPackagesViewViewer ) fViewer ) . setSelectionToWidget ( l , reveal ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . AbstractTreeViewer ; import org . eclipse . jface . viewers . IBasicPropertyConstants ; import org . eclipse . jface . viewers . ListViewer ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . LogicalType ; import org . rubypeople . rdt . internal . core . RubyBlock ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; public class RubyBrowsingContentProvider extends StandardRubyElementContentProvider implements IElementChangedListener { private RubyBrowsingPart fBrowsingPart ; private StructuredViewer fViewer ; private int fReadsInDisplayThread ; private Object fInput ; public RubyBrowsingContentProvider ( boolean provideMembers , RubyBrowsingPart browsingPart ) { super ( provideMembers ) ; fBrowsingPart = browsingPart ; fViewer = fBrowsingPart . getViewer ( ) ; RubyCore . addElementChangedListener ( this ) ; } public boolean hasChildren ( Object element ) { startReadInDisplayThread ( ) ; try { return super . hasChildren ( element ) ; } finally { finishedReadInDisplayThread ( ) ; } } public Object [ ] getChildren ( Object element ) { if ( ! exists ( element ) ) return NO_CHILDREN ; startReadInDisplayThread ( ) ; try { if ( element instanceof Collection ) { Collection elements = ( Collection ) element ; if ( elements . isEmpty ( ) ) return NO_CHILDREN ; Object [ ] result = new Object [ ] ; Iterator iter = ( ( Collection ) element ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Object [ ] children = getChildren ( iter . next ( ) ) ; if ( children != NO_CHILDREN ) result = concatenate ( result , children ) ; } return result ; } if ( element instanceof ISourceFolder ) return getFolderContents ( ( ISourceFolder ) element ) ; if ( fProvideMembers && element instanceof IType ) return removeBlocks ( getChildren ( ( IType ) element ) ) ; if ( fProvideMembers && element instanceof ISourceReference && element instanceof IParent ) return removeBlocks ( removeImportDeclarations ( super . getChildren ( element ) ) ) ; if ( element instanceof IRubyProject ) return getSourceFolderRoots ( ( IRubyProject ) element ) ; return removeBlocks ( super . getChildren ( element ) ) ; } catch ( RubyModelException e ) { return NO_CHILDREN ; } finally { finishedReadInDisplayThread ( ) ; } } private Object [ ] removeImportDeclarations ( Object [ ] members ) { ArrayList tempResult = new ArrayList ( members . length ) ; for ( int i = ; i < members . length ; i ++ ) if ( ! ( members [ i ] instanceof IImportContainer ) ) tempResult . add ( members [ i ] ) ; return tempResult . toArray ( ) ; } protected Object [ ] getFolderContents ( ISourceFolder fragment ) throws RubyModelException { ISourceReference [ ] sourceRefs = fragment . getRubyScripts ( ) ; Object [ ] result = new Object [ ] ; for ( int i = ; i < sourceRefs . length ; i ++ ) result = concatenate ( result , getChildren ( sourceRefs [ i ] ) ) ; result = includeSubtypes ( result ) ; result = convertToLogicalTypes ( result ) ; return result ; } private Object [ ] includeSubtypes ( Object [ ] result ) throws RubyModelException { List < Object > list = new ArrayList < Object > ( ) ; for ( int j = ; j < result . length ; j ++ ) { if ( result [ j ] instanceof IType ) { IType type = ( IType ) result [ j ] ; list . addAll ( Arrays . asList ( includeSubtypes ( type . getTypes ( ) ) ) ) ; } list . add ( result [ j ] ) ; } return list . toArray ( new Object [ list . size ( ) ] ) ; } private Object [ ] convertToLogicalTypes ( Object [ ] result ) { Map < String , IType > uniques = new HashMap < String , IType > ( ) ; for ( int j = ; j < result . length ; j ++ ) { if ( result [ j ] instanceof IType ) { IType type = ( IType ) result [ j ] ; String name = type . getFullyQualifiedName ( ) ; if ( ! uniques . containsKey ( name ) ) { uniques . put ( name , type ) ; } else { IType other = uniques . get ( name ) ; LogicalType logical = new LogicalType ( new IType [ ] { other , type } ) ; uniques . put ( name , logical ) ; } } } Collection values = uniques . values ( ) ; result = values . toArray ( new Object [ values . size ( ) ] ) ; return result ; } protected Object [ ] getSourceFolderRoots ( IRubyProject project ) throws RubyModelException { if ( ! project . getProject ( ) . isOpen ( ) ) return NO_CHILDREN ; ISourceFolderRoot [ ] roots = project . getSourceFolderRoots ( ) ; List list = new ArrayList ( roots . length ) ; for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; if ( ! root . isExternal ( ) ) { Object [ ] children = root . getChildren ( ) ; for ( int k = ; k < children . length ; k ++ ) list . add ( children [ k ] ) ; } else if ( hasChildren ( root ) ) { list . add ( root ) ; } } return concatenate ( list . toArray ( ) , project . getNonRubyResources ( ) ) ; } private Object [ ] getChildren ( IType type ) throws RubyModelException { IParent parent = type . getRubyScript ( ) ; if ( type . getDeclaringType ( ) != null ) return type . getChildren ( ) ; IRubyElement [ ] members = parent . getChildren ( ) ; ArrayList tempResult = new ArrayList ( members . length ) ; for ( int i = ; i < members . length ; i ++ ) if ( ( members [ i ] instanceof IImportContainer ) ) tempResult . add ( members [ i ] ) ; tempResult . addAll ( Arrays . asList ( type . getChildren ( ) ) ) ; return tempResult . toArray ( ) ; } private boolean isDisplayThread ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl == null ) return false ; Display currentDisplay = Display . getCurrent ( ) ; return currentDisplay != null && currentDisplay . equals ( ctrl . getDisplay ( ) ) ; } protected void startReadInDisplayThread ( ) { if ( isDisplayThread ( ) ) fReadsInDisplayThread ++ ; } protected void finishedReadInDisplayThread ( ) { if ( isDisplayThread ( ) ) fReadsInDisplayThread -- ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { super . inputChanged ( viewer , oldInput , newInput ) ; if ( newInput instanceof Collection ) { Collection col = ( Collection ) newInput ; if ( ! col . isEmpty ( ) ) newInput = col . iterator ( ) . next ( ) ; else newInput = null ; } fInput = newInput ; } public void dispose ( ) { super . dispose ( ) ; RubyCore . removeElementChangedListener ( this ) ; } protected Object internalGetParent ( Object element ) { if ( element instanceof IRubyProject ) { return ( ( IRubyProject ) element ) . getRubyModel ( ) ; } if ( element instanceof IResource ) { IResource parent = ( ( IResource ) element ) . getParent ( ) ; Object jParent = RubyCore . create ( parent ) ; if ( jParent != null ) return jParent ; return parent ; } if ( element instanceof IRubyElement ) return ( ( IRubyElement ) element ) . getParent ( ) ; return null ; } public void elementChanged ( final ElementChangedEvent event ) { try { processDelta ( event . getDelta ( ) ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e . getStatus ( ) ) ; } } protected void processDelta ( IRubyElementDelta delta ) throws RubyModelException { int kind = delta . getKind ( ) ; int flags = delta . getFlags ( ) ; final IRubyElement element = delta . getElement ( ) ; final boolean isElementValidForView = fBrowsingPart . isValidElement ( element ) ; if ( ! getProvideWorkingCopy ( ) && element instanceof IRubyScript && ( ( IRubyScript ) element ) . isWorkingCopy ( ) ) return ; if ( element != null && element . getElementType ( ) == IRubyElement . SCRIPT && ! isOnClassPath ( ( IRubyScript ) element ) ) return ; if ( ( ( flags & IRubyElementDelta . F_CLOSED ) != ) || ( ( flags & IRubyElementDelta . F_OPENED ) != ) ) { postRefresh ( null ) ; return ; } if ( kind == IRubyElementDelta . REMOVED ) { Object parent = internalGetParent ( element ) ; if ( isElementValidForView ) { if ( element instanceof IRubyScript && ! ( ( IRubyScript ) element ) . isWorkingCopy ( ) ) { postRefresh ( null ) ; } else if ( element instanceof IRubyScript && ( ( IRubyScript ) element ) . isWorkingCopy ( ) ) { if ( getProvideWorkingCopy ( ) ) postRefresh ( null ) ; } else if ( parent instanceof IRubyScript && getProvideWorkingCopy ( ) && ! ( ( IRubyScript ) parent ) . isWorkingCopy ( ) ) { if ( element instanceof IRubyScript && ( ( IRubyScript ) element ) . isWorkingCopy ( ) ) { postRefresh ( null ) ; } } else if ( element instanceof IRubyScript && ( ( IRubyScript ) element ) . isWorkingCopy ( ) && parent != null && parent . equals ( fInput ) ) postRefresh ( null ) ; else postRemove ( element ) ; } if ( fBrowsingPart . isAncestorOf ( element , fInput ) ) { if ( element instanceof IRubyScript && ( ( IRubyScript ) element ) . isWorkingCopy ( ) ) { postAdjustInputAndSetSelection ( RubyModelUtil . toOriginal ( ( IRubyElement ) fInput ) ) ; } else postAdjustInputAndSetSelection ( null ) ; } if ( fInput != null && fInput . equals ( element ) ) postRefresh ( null ) ; return ; } if ( kind == IRubyElementDelta . ADDED && delta . getMovedFromElement ( ) != null && element instanceof IRubyScript ) return ; if ( kind == IRubyElementDelta . ADDED ) { if ( isElementValidForView ) { Object parent = internalGetParent ( element ) ; if ( element instanceof IRubyScript && ! ( ( IRubyScript ) element ) . isWorkingCopy ( ) ) { postAdd ( parent , ( ( IRubyScript ) element ) . getTypes ( ) ) ; } else if ( parent instanceof IRubyScript && getProvideWorkingCopy ( ) && ! ( ( IRubyScript ) parent ) . isWorkingCopy ( ) ) { } else if ( element instanceof IRubyScript && ( ( IRubyScript ) element ) . isWorkingCopy ( ) ) { postRefresh ( null ) ; } else postAdd ( parent , element ) ; } else if ( fInput == null ) { IRubyElement newInput = fBrowsingPart . findInputForRubyElement ( element ) ; if ( newInput != null ) postAdjustInputAndSetSelection ( element ) ; } else if ( element instanceof IType && fBrowsingPart . isValidInput ( element ) ) { IRubyElement cu1 = element . getAncestor ( IRubyElement . SCRIPT ) ; IRubyElement cu2 = ( ( IRubyElement ) fInput ) . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu1 != null && cu2 != null && cu1 . equals ( cu2 ) ) postAdjustInputAndSetSelection ( element ) ; } return ; } if ( kind == IRubyElementDelta . CHANGED ) { if ( fInput != null && fInput . equals ( element ) && ( flags & IRubyElementDelta . F_CHILDREN ) != && ( flags & IRubyElementDelta . F_FINE_GRAINED ) != ) { postRefresh ( null , true ) ; return ; } if ( isElementValidForView && ( flags & IRubyElementDelta . F_MODIFIERS ) != ) { postUpdateIcon ( element ) ; } } if ( isClassPathChange ( delta ) ) postRefresh ( null ) ; IRubyElementDelta [ ] affectedChildren = delta . getAffectedChildren ( ) ; for ( int i = ; i < affectedChildren . length ; i ++ ) { processDelta ( affectedChildren [ i ] ) ; } } private boolean isOnClassPath ( IRubyScript element ) throws RubyModelException { IRubyProject project = element . getRubyProject ( ) ; if ( project == null || ! project . exists ( ) ) return false ; return project . isOnLoadpath ( element ) ; } private void postUpdateIcon ( final IRubyElement element ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) fViewer . update ( element , new String [ ] { IBasicPropertyConstants . P_IMAGE } ) ; } } ) ; } private void postRefresh ( final Object root , final boolean updateLabels ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) fViewer . refresh ( root , updateLabels ) ; } } ) ; } private void postRefresh ( final Object root ) { postRefresh ( root , false ) ; } private void postAdd ( final Object parent , final Object element ) { postAdd ( parent , new Object [ ] { element } ) ; } private void postAdd ( final Object parent , final Object [ ] elements ) { if ( elements == null || elements . length <= ) return ; postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { Object [ ] newElements = getNewElements ( elements ) ; if ( fViewer instanceof AbstractTreeViewer ) { if ( fViewer . testFindItem ( parent ) == null ) { Object root = ( ( AbstractTreeViewer ) fViewer ) . getInput ( ) ; if ( root != null ) ( ( AbstractTreeViewer ) fViewer ) . add ( root , newElements ) ; } else ( ( AbstractTreeViewer ) fViewer ) . add ( parent , newElements ) ; } else if ( fViewer instanceof ListViewer ) ( ( ListViewer ) fViewer ) . add ( newElements ) ; else if ( fViewer instanceof TableViewer ) ( ( TableViewer ) fViewer ) . add ( newElements ) ; if ( fViewer . testFindItem ( elements [ ] ) != null ) fBrowsingPart . adjustInputAndSetSelection ( elements [ ] ) ; } } } ) ; } private Object [ ] getNewElements ( Object [ ] elements ) { int elementsLength = elements . length ; ArrayList result = new ArrayList ( elementsLength ) ; for ( int i = ; i < elementsLength ; i ++ ) { Object element = elements [ i ] ; if ( fViewer . testFindItem ( element ) == null ) result . add ( element ) ; } return result . toArray ( ) ; } private void postRemove ( final Object element ) { postRemove ( new Object [ ] { element } ) ; } private void postRemove ( final Object [ ] elements ) { if ( elements . length <= ) return ; postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { if ( fViewer instanceof AbstractTreeViewer ) ( ( AbstractTreeViewer ) fViewer ) . remove ( elements ) ; else if ( fViewer instanceof ListViewer ) ( ( ListViewer ) fViewer ) . remove ( elements ) ; else if ( fViewer instanceof TableViewer ) ( ( TableViewer ) fViewer ) . remove ( elements ) ; } } } ) ; } private void postAdjustInputAndSetSelection ( final Object element ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { ctrl . setRedraw ( false ) ; fBrowsingPart . adjustInputAndSetSelection ( element ) ; ctrl . setRedraw ( true ) ; } } } ) ; } private void postRunnable ( final Runnable r ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { fBrowsingPart . setProcessSelectionEvents ( false ) ; try { if ( isDisplayThread ( ) && fReadsInDisplayThread == ) ctrl . getDisplay ( ) . syncExec ( r ) ; else ctrl . getDisplay ( ) . asyncExec ( r ) ; } finally { fBrowsingPart . setProcessSelectionEvents ( true ) ; } } } } package org . rubypeople . rdt . internal . ui . browsing ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . actions . OpenInNewWindowAction ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; public class PatchedOpenInNewWindowAction extends OpenInNewWindowAction { private IWorkbenchWindow fWorkbenchWindow ; public PatchedOpenInNewWindowAction ( IWorkbenchWindow window , IAdaptable input ) { super ( window , input ) ; fWorkbenchWindow = window ; } public void run ( ) { RubyBrowsingPerspectiveFactory . setInputFromAction ( getSelectedRubyElement ( ) ) ; try { super . run ( ) ; } finally { RubyBrowsingPerspectiveFactory . setInputFromAction ( null ) ; } } private IRubyElement getSelectedRubyElement ( ) { if ( fWorkbenchWindow . getActivePage ( ) != null ) { ISelection selection = fWorkbenchWindow . getActivePage ( ) . getSelection ( ) ; if ( selection instanceof IStructuredSelection && ! selection . isEmpty ( ) ) { Object selectedElement = ( ( IStructuredSelection ) selection ) . getFirstElement ( ) ; if ( selectedElement instanceof IRubyElement ) return ( IRubyElement ) selectedElement ; if ( ! ( selectedElement instanceof IRubyElement ) && selectedElement instanceof IAdaptable ) return ( IRubyElement ) ( ( IAdaptable ) selectedElement ) . getAdapter ( IRubyElement . class ) ; else if ( selectedElement instanceof IWorkspace ) return RubyCore . create ( ( ( IWorkspace ) selectedElement ) . getRoot ( ) ) ; } } return null ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Widget ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTreeViewer ; public class PackagesViewTreeViewer extends ProblemTreeViewer implements IPackagesViewViewer { public PackagesViewTreeViewer ( Composite parent , int style ) { super ( parent , style ) ; } @ Override public void unmapElement ( Object element ) { super . unmapElement ( element ) ; } @ Override public void unmapElement ( Object element , Widget item ) { super . unmapElement ( element , item ) ; } @ Override public void mapElement ( Object element , Widget item ) { super . mapElement ( element , item ) ; } protected Object [ ] getFilteredChildren ( Object parent ) { List list = new ArrayList ( ) ; Object [ ] result = getRawChildren ( parent ) ; if ( result != null ) { Object [ ] toBeFiltered = new Object [ ] ; for ( int i = ; i < result . length ; i ++ ) { Object object = result [ i ] ; toBeFiltered [ ] = object ; if ( isEssential ( object ) || filter ( toBeFiltered ) . length == ) list . add ( object ) ; } } return list . toArray ( ) ; } protected Object [ ] filter ( Object [ ] elements ) { ViewerFilter [ ] filters = getFilters ( ) ; if ( filters == null || filters . length == ) return elements ; ArrayList filtered = new ArrayList ( elements . length ) ; Object root = getRoot ( ) ; for ( int i = ; i < elements . length ; i ++ ) { boolean add = true ; if ( ! isEssential ( elements [ i ] ) ) { for ( int j = ; j < filters . length ; j ++ ) { add = filters [ j ] . select ( this , root , elements [ i ] ) ; if ( ! add ) break ; } } if ( add ) filtered . add ( elements [ i ] ) ; } return filtered . toArray ( ) ; } public boolean isExpandable ( Object parent ) { Object [ ] children = ( ( ITreeContentProvider ) getContentProvider ( ) ) . getChildren ( parent ) ; Object [ ] toBeFiltered = new Object [ ] ; for ( int i = ; i < children . length ; i ++ ) { Object object = children [ i ] ; if ( isEssential ( object ) ) return true ; toBeFiltered [ ] = object ; Object [ ] filtered = filter ( toBeFiltered ) ; if ( filtered . length > ) return true ; } return false ; } private boolean isEssential ( Object object ) { try { if ( object instanceof ISourceFolder ) { ISourceFolder fragment = ( ISourceFolder ) object ; return ! fragment . isDefaultPackage ( ) && fragment . hasSubfolders ( ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return false ; } public Widget doFindItem ( Object element ) { return super . doFindItem ( element ) ; } public Widget doFindInputItem ( Object element ) { return super . doFindInputItem ( element ) ; } public List getSelectionFromWidget ( ) { return super . getSelectionFromWidget ( ) ; } public void doUpdateItem ( Widget item , Object element , boolean fullMap ) { super . doUpdateItem ( item , element , fullMap ) ; } public void internalRefresh ( Object element ) { super . internalRefresh ( element ) ; } public void setSelectionToWidget ( List l , boolean reveal ) { super . setSelectionToWidget ( l , reveal ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import org . eclipse . osgi . util . NLS ; public final class RubyBrowsingMessages extends NLS { private static final String BUNDLE_NAME = RubyBrowsingMessages . class . getName ( ) ; private RubyBrowsingMessages ( ) { } public static String RubyBrowsingPart_toolTip ; public static String RubyBrowsingPart_toolTip2 ; public static String LexicalSortingAction_label ; public static String LexicalSortingAction_tooltip ; public static String LexicalSortingAction_description ; public static String StatusBar_concat ; public static String PackagesView_flatLayoutAction_label ; public static String PackagesView_HierarchicalLayoutAction_label ; public static String PackagesView_LayoutActionGroup_layout_label ; static { NLS . initializeMessages ( BUNDLE_NAME , RubyBrowsingMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . part . IShowInTargetList ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . viewsupport . FilterUpdater ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTreeViewer ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . actions . ProjectActionGroup ; public class ProjectsView extends RubyBrowsingPart { private FilterUpdater fFilterUpdater ; protected StructuredViewer createViewer ( Composite parent ) { ProblemTreeViewer result = new ProblemTreeViewer ( parent , SWT . MULTI ) ; fFilterUpdater = new FilterUpdater ( result ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( fFilterUpdater ) ; return result ; } public void dispose ( ) { if ( fFilterUpdater != null ) ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( fFilterUpdater ) ; super . dispose ( ) ; } public Object getAdapter ( Class key ) { if ( key == IShowInTargetList . class ) { return new IShowInTargetList ( ) { public String [ ] getShowInTargetIds ( ) { return new String [ ] { RubyUI . ID_RUBY_EXPLORER , IPageLayout . ID_RES_NAV } ; } } ; } return super . getAdapter ( key ) ; } protected IContentProvider createContentProvider ( ) { return new ProjectAndSourceFolderContentProvider ( this ) ; } protected String getHelpContextId ( ) { return IRubyHelpContextIds . PROJECTS_VIEW ; } protected String getLinkToEditorKey ( ) { return PreferenceConstants . LINK_BROWSING_PROJECTS_TO_EDITOR ; } protected void hookViewerListeners ( ) { super . hookViewerListeners ( ) ; getViewer ( ) . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { TreeViewer viewer = ( TreeViewer ) getViewer ( ) ; Object element = ( ( IStructuredSelection ) event . getSelection ( ) ) . getFirstElement ( ) ; if ( viewer . isExpandable ( element ) ) viewer . setExpandedState ( element , ! viewer . getExpandedState ( element ) ) ; } } ) ; } protected void setInitialInput ( ) { IRubyElement root = RubyCore . create ( RubyPlugin . getWorkspace ( ) . getRoot ( ) ) ; getViewer ( ) . setInput ( root ) ; updateTitle ( ) ; } protected boolean isValidInput ( Object element ) { return element instanceof IRubyModel ; } protected boolean isValidElement ( Object element ) { return element instanceof IRubyProject || element instanceof ISourceFolderRoot ; } protected IRubyElement findElementToSelect ( IRubyElement je ) { if ( je == null ) return null ; switch ( je . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : return null ; case IRubyElement . RUBY_PROJECT : return je ; case IRubyElement . SOURCE_FOLDER_ROOT : if ( je . getElementName ( ) . equals ( ISourceFolderRoot . DEFAULT_PACKAGEROOT_PATH ) ) return je . getParent ( ) ; else return je ; default : return findElementToSelect ( je . getParent ( ) ) ; } } protected void setInput ( Object input ) { if ( input != null ) super . setInput ( input ) ; else getViewer ( ) . setSelection ( null ) ; } protected void createActions ( ) { super . createActions ( ) ; fActionGroups . addGroup ( new ProjectActionGroup ( this ) ) ; } public void selectionChanged ( IWorkbenchPart part , ISelection selection ) { if ( ! needsToProcessSelectionChanged ( part , selection ) ) return ; super . selectionChanged ( part , selection ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Comparator ; import java . util . Iterator ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IStatusLineManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . util . TransferDropTargetListener ; import org . eclipse . jface . viewers . DecoratingLabelProvider ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . IOpenListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . search . ui . ISearchResultView ; import org . eclipse . search . ui . ISearchResultViewPart ; import org . eclipse . swt . SWT ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPartListener2 ; import org . eclipse . ui . ISelectionListener ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . part . IShowInSource ; import org . eclipse . ui . part . ResourceTransfer ; import org . eclipse . ui . part . ShowInContext ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . views . navigator . LocalSelectionTransfer ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . CompositeActionGroup ; import org . rubypeople . rdt . internal . ui . actions . NewWizardsActionGroup ; import org . rubypeople . rdt . internal . ui . dnd . DelegatingDropAdapter ; import org . rubypeople . rdt . internal . ui . dnd . RdtViewerDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . ResourceTransferDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . SelectionTransferDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . SelectionTransferDropAdapter ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . DecoratingRubyLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTableViewer ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyUILabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . StatusBarUpdater ; import org . rubypeople . rdt . internal . ui . workingsets . WorkingSetFilterActionGroup ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . RubyElementSorter ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; import org . rubypeople . rdt . ui . actions . BuildActionGroup ; import org . rubypeople . rdt . ui . actions . CCPActionGroup ; import org . rubypeople . rdt . ui . actions . CustomFiltersActionGroup ; import org . rubypeople . rdt . ui . actions . OpenEditorActionGroup ; import org . rubypeople . rdt . ui . actions . OpenViewActionGroup ; import org . rubypeople . rdt . ui . actions . RubySearchActionGroup ; abstract class RubyBrowsingPart extends ViewPart implements ISelectionListener , IMenuListener { private static final String TAG_SELECTED_ELEMENTS = "" ; private static final String TAG_SELECTED_ELEMENT = "" ; private static final String TAG_SELECTED_ELEMENT_PATH = "" ; private StructuredViewer fViewer ; private IMemento fMemento ; private RubyUILabelProvider fLabelProvider ; protected IWorkbenchPart fPreviousSelectionProvider ; protected Object fPreviousSelectedElement ; private ILabelProvider fTitleProvider ; private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup ; private boolean fHasWorkingSetFilter = true ; private boolean fHasCustomFilter = true ; private OpenEditorActionGroup fOpenEditorGroup ; protected CompositeActionGroup fActionGroups ; private ToggleLinkingAction fToggleLinkingAction ; private CustomFiltersActionGroup fCustomFiltersActionGroup ; private boolean fLinkingEnabled ; private boolean fProcessSelectionEvents = true ; private RubyElementTypeComparator fTypeComparator ; private IPartListener2 fPartListener = new IPartListener2 ( ) { public void partActivated ( IWorkbenchPartReference ref ) { } public void partBroughtToTop ( IWorkbenchPartReference ref ) { } public void partInputChanged ( IWorkbenchPartReference ref ) { } public void partClosed ( IWorkbenchPartReference ref ) { } public void partDeactivated ( IWorkbenchPartReference ref ) { } public void partOpened ( IWorkbenchPartReference ref ) { } public void partVisible ( IWorkbenchPartReference ref ) { if ( ref != null && ref . getId ( ) == getSite ( ) . getId ( ) ) { fProcessSelectionEvents = true ; IWorkbenchPage page = getSite ( ) . getWorkbenchWindow ( ) . getActivePage ( ) ; if ( page != null ) selectionChanged ( page . getActivePart ( ) , page . getSelection ( ) ) ; } } public void partHidden ( IWorkbenchPartReference ref ) { if ( ref != null && ref . getId ( ) == getSite ( ) . getId ( ) ) fProcessSelectionEvents = false ; } } ; private CCPActionGroup fCCPActionGroup ; private BuildActionGroup fBuildActionGroup ; public RubyBrowsingPart ( ) { super ( ) ; initLinkingEnabled ( ) ; } protected void createActions ( ) { fActionGroups = new CompositeActionGroup ( new ActionGroup [ ] { new NewWizardsActionGroup ( this . getSite ( ) ) , fOpenEditorGroup = new OpenEditorActionGroup ( this ) , new OpenViewActionGroup ( this ) , fCCPActionGroup = new CCPActionGroup ( this ) , fBuildActionGroup = new BuildActionGroup ( this ) , new RubySearchActionGroup ( this ) } ) ; if ( fHasWorkingSetFilter ) { String viewId = getConfigurationElement ( ) . getAttribute ( "" ) ; Assert . isNotNull ( viewId ) ; IPropertyChangeListener workingSetListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { doWorkingSetChanged ( event ) ; } } ; fWorkingSetFilterActionGroup = new WorkingSetFilterActionGroup ( getSite ( ) , workingSetListener ) ; fViewer . addFilter ( fWorkingSetFilterActionGroup . getWorkingSetFilter ( ) ) ; } if ( fHasCustomFilter ) fCustomFiltersActionGroup = new CustomFiltersActionGroup ( this , fViewer ) ; fToggleLinkingAction = new ToggleLinkingAction ( this ) ; } protected void addFilters ( ) { } protected void addKeyListener ( ) { fViewer . getControl ( ) . addKeyListener ( new KeyAdapter ( ) { public void keyReleased ( KeyEvent event ) { handleKeyReleased ( event ) ; } } ) ; } protected void handleKeyReleased ( KeyEvent event ) { if ( event . stateMask != ) return ; int key = event . keyCode ; if ( key == SWT . F5 ) { IAction action = fBuildActionGroup . getRefreshAction ( ) ; if ( action . isEnabled ( ) ) action . run ( ) ; } } protected void initDragAndDrop ( ) { int ops = DND . DROP_COPY | DND . DROP_MOVE | DND . DROP_LINK ; Transfer [ ] dropTransfers = new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) } ; TransferDropTargetListener [ ] dropListeners = new TransferDropTargetListener [ ] { new SelectionTransferDropAdapter ( fViewer ) } ; fViewer . addDropSupport ( ops | DND . DROP_DEFAULT , dropTransfers , new DelegatingDropAdapter ( dropListeners ) ) ; Transfer [ ] dragTransfers = new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) , ResourceTransfer . getInstance ( ) } ; TransferDragSourceListener [ ] dragListeners = new TransferDragSourceListener [ ] { new SelectionTransferDragAdapter ( fViewer ) , new ResourceTransferDragAdapter ( fViewer ) } ; fViewer . addDragSupport ( ops , dragTransfers , new RdtViewerDragAdapter ( fViewer , dragListeners ) ) ; } protected void createContextMenu ( ) { MenuManager menuManager = new MenuManager ( "" ) ; menuManager . setRemoveAllWhenShown ( true ) ; menuManager . addMenuListener ( this ) ; Menu contextMenu = menuManager . createContextMenu ( fViewer . getControl ( ) ) ; fViewer . getControl ( ) . setMenu ( contextMenu ) ; getSite ( ) . registerContextMenu ( menuManager , fViewer ) ; } private void doWorkingSetChanged ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( IWorkingSetManager . CHANGE_WORKING_SET_NAME_CHANGE . equals ( property ) ) updateTitle ( ) ; else if ( IWorkingSetManager . CHANGE_WORKING_SET_CONTENT_CHANGE . equals ( property ) ) { updateTitle ( ) ; fViewer . getControl ( ) . setRedraw ( false ) ; fViewer . refresh ( ) ; fViewer . getControl ( ) . setRedraw ( true ) ; } } protected void hookViewerListeners ( ) { fViewer . addOpenListener ( new IOpenListener ( ) { public void open ( OpenEvent event ) { IAction open = fOpenEditorGroup . getOpenAction ( ) ; if ( open . isEnabled ( ) ) { open . run ( ) ; restoreSelection ( ) ; } } } ) ; } void setHasCustomSetFilter ( boolean state ) { fHasCustomFilter = state ; } protected boolean hasCustomFilter ( ) { return fHasCustomFilter ; } protected void setCustomFiltersActionGroup ( CustomFiltersActionGroup customFiltersActionGroup ) { fCustomFiltersActionGroup = customFiltersActionGroup ; } void restoreSelection ( ) { } protected void setOpenEditorGroup ( OpenEditorActionGroup openEditorGroup ) { fOpenEditorGroup = openEditorGroup ; } protected OpenEditorActionGroup getOpenEditorGroup ( ) { return fOpenEditorGroup ; } public void createPartControl ( Composite parent ) { Assert . isTrue ( fViewer == null ) ; fViewer = createViewer ( parent ) ; fTypeComparator = new RubyElementTypeComparator ( ) ; fLabelProvider = createLabelProvider ( ) ; fViewer . setLabelProvider ( createDecoratingLabelProvider ( fLabelProvider ) ) ; fViewer . setSorter ( createRubyElementSorter ( ) ) ; fViewer . setUseHashlookup ( true ) ; fTitleProvider = createTitleProvider ( ) ; getSite ( ) . setSelectionProvider ( fViewer ) ; if ( fMemento != null ) { restoreLinkingEnabled ( fMemento ) ; } createActions ( ) ; if ( fMemento != null ) restoreState ( fMemento ) ; getSite ( ) . setSelectionProvider ( fViewer ) ; hookViewerListeners ( ) ; fViewer . setContentProvider ( createContentProvider ( ) ) ; setInitialInput ( ) ; setInitialSelection ( ) ; getViewSite ( ) . getPage ( ) . addPostSelectionListener ( this ) ; getViewSite ( ) . getPage ( ) . addPartListener ( fPartListener ) ; fillActionBars ( getViewSite ( ) . getActionBars ( ) ) ; } protected StatusBarUpdater createStatusBarUpdater ( IStatusLineManager slManager ) { return new StatusBarUpdater ( slManager ) ; } protected ILabelProvider createTitleProvider ( ) { return new RubyElementLabelProvider ( RubyElementLabelProvider . SHOW_BASICS | RubyElementLabelProvider . SHOW_SMALL_ICONS ) ; } public void init ( IViewSite site , IMemento memento ) throws PartInitException { super . init ( site , memento ) ; fMemento = memento ; } private void restoreLinkingEnabled ( IMemento memento ) { Integer val = memento . getInteger ( getLinkToEditorKey ( ) ) ; if ( val != null ) { fLinkingEnabled = val . intValue ( ) != ; } } private void saveSelectionState ( IMemento memento ) { Object elements [ ] = ( ( IStructuredSelection ) fViewer . getSelection ( ) ) . toArray ( ) ; if ( elements . length > ) { IMemento selectionMem = memento . createChild ( TAG_SELECTED_ELEMENTS ) ; for ( int i = ; i < elements . length ; i ++ ) { IMemento elementMem = selectionMem . createChild ( TAG_SELECTED_ELEMENT ) ; Object o = elements [ i ] ; if ( o instanceof IRubyElement ) elementMem . putString ( TAG_SELECTED_ELEMENT_PATH , ( ( IRubyElement ) elements [ i ] ) . getHandleIdentifier ( ) ) ; } } } protected void restoreState ( IMemento memento ) { if ( fHasWorkingSetFilter ) fWorkingSetFilterActionGroup . restoreState ( memento ) ; if ( fHasCustomFilter ) fCustomFiltersActionGroup . restoreState ( memento ) ; if ( fHasCustomFilter ) { fViewer . getControl ( ) . setRedraw ( false ) ; fViewer . refresh ( ) ; fViewer . getControl ( ) . setRedraw ( true ) ; } } protected StructuredViewer createViewer ( Composite parent ) { return new ProblemTableViewer ( parent ) ; } protected void fillActionBars ( IActionBars actionBars ) { IToolBarManager toolBar = actionBars . getToolBarManager ( ) ; fillToolBar ( toolBar ) ; if ( fHasWorkingSetFilter ) fWorkingSetFilterActionGroup . fillActionBars ( getViewSite ( ) . getActionBars ( ) ) ; actionBars . updateActionBars ( ) ; fActionGroups . fillActionBars ( actionBars ) ; if ( fHasCustomFilter ) fCustomFiltersActionGroup . fillActionBars ( actionBars ) ; IMenuManager menu = actionBars . getMenuManager ( ) ; menu . add ( fToggleLinkingAction ) ; } protected boolean hasWorkingSetFilter ( ) { return fHasWorkingSetFilter ; } protected void fillToolBar ( IToolBarManager tbm ) { } protected IContentProvider createContentProvider ( ) { return new RubyBrowsingContentProvider ( true , this ) ; } protected final StructuredViewer getViewer ( ) { return fViewer ; } protected void setInitialInput ( ) { ISelection selection = getSite ( ) . getPage ( ) . getSelection ( ) ; Object input = getSingleElementFromSelection ( selection ) ; if ( ! ( input instanceof IRubyElement ) ) { input = getSite ( ) . getPage ( ) . getInput ( ) ; if ( ! ( input instanceof IRubyElement ) && input instanceof IAdaptable ) input = ( ( IAdaptable ) input ) . getAdapter ( IRubyElement . class ) ; } setInput ( findInputForRubyElement ( ( IRubyElement ) input ) ) ; } protected RubyUILabelProvider createLabelProvider ( ) { return new AppearanceAwareLabelProvider ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS | RubyElementImageProvider . SMALL_ICONS ) ; } protected void setInput ( Object input ) { setViewerInput ( input ) ; updateTitle ( ) ; } void updateTitle ( ) { setTitleToolTip ( getToolTipText ( fViewer . getInput ( ) ) ) ; } String getToolTipText ( Object element ) { String result ; if ( ! ( element instanceof IResource ) ) { result = RubyElementLabels . getTextLabel ( element , AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS ) ; } else { IPath path = ( ( IResource ) element ) . getFullPath ( ) ; if ( path . isRoot ( ) ) { result = getConfigurationElement ( ) . getAttribute ( "" ) ; } else { result = path . makeRelative ( ) . toString ( ) ; } } if ( fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup . getWorkingSet ( ) == null ) return result ; IWorkingSet ws = fWorkingSetFilterActionGroup . getWorkingSet ( ) ; String wsstr = Messages . format ( RubyBrowsingMessages . RubyBrowsingPart_toolTip , new String [ ] { ws . getLabel ( ) } ) ; if ( result . length ( ) == ) return wsstr ; return Messages . format ( RubyBrowsingMessages . RubyBrowsingPart_toolTip2 , new String [ ] { result , ws . getLabel ( ) } ) ; } protected final void setViewer ( StructuredViewer viewer ) { fViewer = viewer ; } private void setViewerInput ( Object input ) { fProcessSelectionEvents = false ; fViewer . setInput ( input ) ; fProcessSelectionEvents = true ; } private boolean isSearchResultView ( IWorkbenchPart part ) { return isSearchPlugInActivated ( ) && ( part instanceof ISearchResultView || part instanceof ISearchResultViewPart ) ; } public static boolean isSearchPlugInActivated ( ) { return Platform . getBundle ( "" ) . getState ( ) == Bundle . ACTIVE ; } protected boolean needsToProcessSelectionChanged ( IWorkbenchPart part , ISelection selection ) { if ( ! fProcessSelectionEvents || part == this || isSearchResultView ( part ) ) { if ( part == this ) fPreviousSelectionProvider = part ; return false ; } return true ; } public void selectionChanged ( IWorkbenchPart part , ISelection selection ) { if ( ! needsToProcessSelectionChanged ( part , selection ) ) return ; if ( fToggleLinkingAction . isChecked ( ) && ( part instanceof ITextEditor ) ) { setSelectionFromEditor ( part , selection ) ; return ; } if ( ! ( selection instanceof IStructuredSelection ) ) return ; Object selectedElement = getSingleElementFromSelection ( selection ) ; if ( selectedElement != null && ( part == null || part . equals ( fPreviousSelectionProvider ) ) && selectedElement . equals ( fPreviousSelectedElement ) ) return ; fPreviousSelectedElement = selectedElement ; Object currentInput = getViewer ( ) . getInput ( ) ; if ( selectedElement != null && selectedElement . equals ( currentInput ) ) { IRubyElement elementToSelect = findElementToSelect ( selectedElement ) ; if ( elementToSelect != null && getTypeComparator ( ) . compare ( selectedElement , elementToSelect ) < ) setSelection ( new StructuredSelection ( elementToSelect ) , true ) ; else if ( elementToSelect == null && ( this instanceof MembersView ) ) { setSelection ( StructuredSelection . EMPTY , true ) ; fPreviousSelectedElement = StructuredSelection . EMPTY ; } fPreviousSelectionProvider = part ; return ; } if ( part != fPreviousSelectionProvider && selectedElement != null && ! selectedElement . equals ( currentInput ) && isInputResetBy ( selectedElement , currentInput , part ) ) { if ( ! isAncestorOf ( selectedElement , currentInput ) ) setInput ( null ) ; fPreviousSelectionProvider = part ; return ; } else if ( selection . isEmpty ( ) && ! isInputResetBy ( part ) ) { fPreviousSelectionProvider = part ; return ; } else if ( selectedElement == null && part == fPreviousSelectionProvider ) { setInput ( null ) ; fPreviousSelectionProvider = part ; return ; } fPreviousSelectionProvider = part ; adjustInputAndSetSelection ( selectedElement ) ; } void setSelection ( ISelection selection , boolean reveal ) { if ( selection != null && selection . equals ( fViewer . getSelection ( ) ) ) return ; fProcessSelectionEvents = false ; fViewer . setSelection ( selection , reveal ) ; fProcessSelectionEvents = true ; } protected Object getInput ( ) { return fViewer . getInput ( ) ; } public void setFocus ( ) { fViewer . getControl ( ) . setFocus ( ) ; } public Object getAdapter ( Class key ) { if ( key == IShowInSource . class ) { return getShowInSource ( ) ; } return super . getAdapter ( key ) ; } protected IShowInSource getShowInSource ( ) { return new IShowInSource ( ) { public ShowInContext getShowInContext ( ) { return new ShowInContext ( null , getSite ( ) . getSelectionProvider ( ) . getSelection ( ) ) ; } } ; } void adjustInputAndSetSelection ( Object o ) { if ( ! ( o instanceof IRubyElement ) ) { if ( o == null ) setInput ( null ) ; setSelection ( StructuredSelection . EMPTY , true ) ; return ; } IRubyElement je = ( IRubyElement ) o ; IRubyElement elementToSelect = getSuitableRubyElement ( findElementToSelect ( je ) ) ; IRubyElement newInput = findInputForRubyElement ( je ) ; IRubyElement oldInput = null ; if ( getInput ( ) instanceof IRubyElement ) oldInput = ( IRubyElement ) getInput ( ) ; if ( elementToSelect == null && ! isValidInput ( newInput ) && ( newInput == null && ! isAncestorOf ( je , oldInput ) ) ) setInput ( null ) ; else if ( mustSetNewInput ( elementToSelect , oldInput , newInput ) ) { setInput ( newInput ) ; elementToSelect = getSuitableRubyElement ( elementToSelect ) ; } if ( elementToSelect != null && elementToSelect . exists ( ) ) setSelection ( new StructuredSelection ( elementToSelect ) , true ) ; else setSelection ( StructuredSelection . EMPTY , true ) ; } IRubyElement getSuitableRubyElement ( Object obj ) { if ( ! ( obj instanceof IRubyElement ) ) return null ; IRubyElement element = ( IRubyElement ) obj ; if ( fTypeComparator . compare ( element , IRubyElement . SCRIPT ) > ) return element ; if ( isInputAWorkingCopy ( ) ) { IRubyElement wc = getWorkingCopy ( element ) ; if ( wc != null ) element = wc ; return element ; } else { return element . getPrimaryElement ( ) ; } } boolean isInputAWorkingCopy ( ) { return ( ( StandardRubyElementContentProvider ) getViewer ( ) . getContentProvider ( ) ) . getProvideWorkingCopy ( ) ; } protected static IRubyElement getWorkingCopy ( IRubyElement input ) { return input ; } private boolean mustSetNewInput ( IRubyElement elementToSelect , IRubyElement oldInput , IRubyElement newInput ) { return ( newInput == null || ! newInput . equals ( oldInput ) ) && ( elementToSelect == null || oldInput == null || ( ! ( false && ( elementToSelect . getParent ( ) . equals ( oldInput . getParent ( ) ) ) && ( ! isAncestorOf ( getViewPartInput ( ) , elementToSelect ) ) ) ) ) ; } public Object getViewPartInput ( ) { if ( fViewer != null ) { return fViewer . getInput ( ) ; } return null ; } protected Comparator getTypeComparator ( ) { return fTypeComparator ; } private boolean isInputResetBy ( Object newInput , Object input , IWorkbenchPart part ) { if ( newInput == null ) return part == fPreviousSelectionProvider ; if ( input instanceof IRubyElement && newInput instanceof IRubyElement ) return getTypeComparator ( ) . compare ( newInput , input ) > ; else return false ; } private boolean isInputResetBy ( IWorkbenchPart part ) { if ( ! ( part instanceof RubyBrowsingPart ) ) return true ; Object thisInput = getViewer ( ) . getInput ( ) ; Object partInput = ( ( RubyBrowsingPart ) part ) . getViewer ( ) . getInput ( ) ; if ( thisInput instanceof Collection ) thisInput = ( ( Collection ) thisInput ) . iterator ( ) . next ( ) ; if ( partInput instanceof Collection ) partInput = ( ( Collection ) partInput ) . iterator ( ) . next ( ) ; if ( thisInput instanceof IRubyElement && partInput instanceof IRubyElement ) return getTypeComparator ( ) . compare ( partInput , thisInput ) > ; else return true ; } protected boolean isAncestorOf ( Object ancestor , Object element ) { if ( element instanceof IRubyElement && ancestor instanceof IRubyElement ) return ! element . equals ( ancestor ) && internalIsAncestorOf ( ( IRubyElement ) ancestor , ( IRubyElement ) element ) ; return false ; } private boolean internalIsAncestorOf ( IRubyElement ancestor , IRubyElement element ) { if ( element != null ) return element . equals ( ancestor ) || internalIsAncestorOf ( ancestor , element . getParent ( ) ) ; else return false ; } protected final IRubyElement findElementToSelect ( Object obj ) { if ( obj instanceof IRubyElement ) return findElementToSelect ( ( IRubyElement ) obj ) ; return null ; } abstract protected IRubyElement findElementToSelect ( IRubyElement je ) ; protected final Object getSingleElementFromSelection ( ISelection selection ) { if ( ! ( selection instanceof StructuredSelection ) || selection . isEmpty ( ) ) return null ; Iterator iter = ( ( StructuredSelection ) selection ) . iterator ( ) ; Object firstElement = iter . next ( ) ; if ( ! ( firstElement instanceof IRubyElement ) ) { if ( firstElement instanceof IMarker ) firstElement = ( ( IMarker ) firstElement ) . getResource ( ) ; if ( firstElement instanceof IAdaptable ) { IRubyElement je = ( IRubyElement ) ( ( IAdaptable ) firstElement ) . getAdapter ( IRubyElement . class ) ; if ( je == null && firstElement instanceof IFile ) { IContainer parent = ( ( IFile ) firstElement ) . getParent ( ) ; if ( parent != null ) return ( IRubyElement ) parent . getAdapter ( IRubyElement . class ) ; else return null ; } else return je ; } else return firstElement ; } Object currentInput = getViewer ( ) . getInput ( ) ; if ( currentInput == null || ! currentInput . equals ( findInputForRubyElement ( ( IRubyElement ) firstElement ) ) ) if ( iter . hasNext ( ) ) return null ; else return firstElement ; while ( iter . hasNext ( ) ) { Object element = iter . next ( ) ; if ( ! ( element instanceof IRubyElement ) ) return null ; if ( ! currentInput . equals ( findInputForRubyElement ( ( IRubyElement ) element ) ) ) return null ; } return firstElement ; } protected IRubyElement findInputForRubyElement ( IRubyElement je ) { if ( je == null || ! je . exists ( ) ) return null ; if ( isValidInput ( je ) ) return je ; return findInputForRubyElement ( je . getParent ( ) ) ; } protected RubyElementSorter createRubyElementSorter ( ) { return new RubyElementSorter ( ) { @ Override protected String getElementName ( Object element ) { if ( element instanceof IType ) { IType type = ( IType ) element ; return type . getFullyQualifiedName ( ) ; } return super . getElementName ( element ) ; } } ; } Shell getShell ( ) { return fViewer . getControl ( ) . getShell ( ) ; } protected final Display getDisplay ( ) { return fViewer . getControl ( ) . getDisplay ( ) ; } ISelectionProvider getSelectionProvider ( ) { return fViewer ; } abstract protected boolean isValidInput ( Object element ) ; protected boolean isValidElement ( Object element ) { if ( element == null ) return false ; element = getSuitableRubyElement ( element ) ; if ( element == null ) return false ; Object input = getViewer ( ) . getInput ( ) ; if ( input == null ) return false ; if ( input instanceof Collection ) return ( ( Collection ) input ) . contains ( element ) ; else return input . equals ( element ) ; } protected DecoratingLabelProvider createDecoratingLabelProvider ( RubyUILabelProvider provider ) { return new DecoratingRubyLabelProvider ( provider ) ; } protected IType getTypeForRubyScript ( IRubyScript script ) { script = ( IRubyScript ) getSuitableRubyElement ( script ) ; IType primaryType = script . findPrimaryType ( ) ; if ( primaryType != null ) return primaryType ; try { IType [ ] types = script . getTypes ( ) ; if ( types . length > ) return types [ ] ; else return null ; } catch ( RubyModelException ex ) { return null ; } } public void dispose ( ) { if ( fViewer != null ) { getViewSite ( ) . getPage ( ) . removePostSelectionListener ( this ) ; getViewSite ( ) . getPage ( ) . removePartListener ( fPartListener ) ; fViewer = null ; } if ( fActionGroups != null ) fActionGroups . dispose ( ) ; super . dispose ( ) ; } void setProcessSelectionEvents ( boolean state ) { fProcessSelectionEvents = state ; } public void menuAboutToShow ( IMenuManager menu ) { RubyPlugin . createStandardGroups ( menu ) ; IStructuredSelection selection = ( IStructuredSelection ) fViewer . getSelection ( ) ; int size = selection . size ( ) ; Object element = selection . getFirstElement ( ) ; if ( size == ) addOpenNewWindowAction ( menu , element ) ; fActionGroups . setContext ( new ActionContext ( selection ) ) ; fActionGroups . fillContextMenu ( menu ) ; fActionGroups . setContext ( null ) ; } private void addOpenNewWindowAction ( IMenuManager menu , Object element ) { if ( element instanceof IRubyElement ) { element = ( ( IRubyElement ) element ) . getResource ( ) ; } if ( ! ( element instanceof IContainer ) ) return ; menu . appendToGroup ( IContextMenuConstants . GROUP_OPEN , new PatchedOpenInNewWindowAction ( getSite ( ) . getWorkbenchWindow ( ) , ( IContainer ) element ) ) ; } public void saveState ( IMemento memento ) { if ( fViewer == null ) { if ( fMemento != null ) memento . putMemento ( fMemento ) ; return ; } if ( fHasWorkingSetFilter ) fWorkingSetFilterActionGroup . saveState ( memento ) ; if ( fHasCustomFilter ) fCustomFiltersActionGroup . saveState ( memento ) ; saveSelectionState ( memento ) ; saveLinkingEnabled ( memento ) ; } void setHasWorkingSetFilter ( boolean state ) { fHasWorkingSetFilter = state ; } private void saveLinkingEnabled ( IMemento memento ) { memento . putInteger ( getLinkToEditorKey ( ) , fLinkingEnabled ? : ) ; } protected void setInitialSelection ( ) { Object input ; IWorkbenchPage page = getSite ( ) . getPage ( ) ; ISelection selection = null ; if ( page != null ) selection = page . getSelection ( ) ; if ( selection instanceof ITextSelection ) { Object part = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . getActivePart ( ) ; if ( part instanceof IEditorPart ) { setSelectionFromEditor ( ( IEditorPart ) part ) ; if ( fViewer . getSelection ( ) != null ) return ; } } if ( selection == null || selection . isEmpty ( ) ) selection = restoreSelectionState ( fMemento ) ; if ( selection == null || selection . isEmpty ( ) ) { input = getSite ( ) . getPage ( ) . getInput ( ) ; if ( ! ( input instanceof IRubyElement ) ) { if ( input instanceof IAdaptable ) input = ( ( IAdaptable ) input ) . getAdapter ( IRubyElement . class ) ; else return ; } selection = new StructuredSelection ( input ) ; } selectionChanged ( null , selection ) ; } private ISelection restoreSelectionState ( IMemento memento ) { if ( memento == null ) return null ; IMemento childMem ; childMem = memento . getChild ( TAG_SELECTED_ELEMENTS ) ; if ( childMem != null ) { ArrayList list = new ArrayList ( ) ; IMemento [ ] elementMem = childMem . getChildren ( TAG_SELECTED_ELEMENT ) ; for ( int i = ; i < elementMem . length ; i ++ ) { String javaElementHandle = elementMem [ i ] . getString ( TAG_SELECTED_ELEMENT_PATH ) ; IRubyElement element = RubyCore . create ( javaElementHandle ) ; if ( element != null && element . exists ( ) ) list . add ( element ) ; } return new StructuredSelection ( list ) ; } return null ; } boolean isLinkingEnabled ( ) { return fLinkingEnabled ; } private void initLinkingEnabled ( ) { fLinkingEnabled = PreferenceConstants . getPreferenceStore ( ) . getBoolean ( getLinkToEditorKey ( ) ) ; } private boolean linkBrowsingViewSelectionToEditor ( ) { return isLinkingEnabled ( ) ; } public void setLinkingEnabled ( boolean enabled ) { fLinkingEnabled = enabled ; PreferenceConstants . getPreferenceStore ( ) . setValue ( getLinkToEditorKey ( ) , enabled ) ; if ( enabled ) { IEditorPart editor = getSite ( ) . getPage ( ) . getActiveEditor ( ) ; if ( editor != null ) { setSelectionFromEditor ( editor ) ; } } } protected final ILabelProvider getLabelProvider ( ) { return fLabelProvider ; } protected final ILabelProvider getTitleProvider ( ) { return fTitleProvider ; } abstract protected String getLinkToEditorKey ( ) ; void setSelectionFromEditor ( IWorkbenchPart part ) { if ( ! fProcessSelectionEvents || ! linkBrowsingViewSelectionToEditor ( ) || ! ( part instanceof IEditorPart ) ) return ; IWorkbenchPartSite site = part . getSite ( ) ; if ( site == null ) return ; ISelectionProvider provider = site . getSelectionProvider ( ) ; if ( provider != null ) setSelectionFromEditor ( part , provider . getSelection ( ) ) ; } private void setSelectionFromEditor ( IWorkbenchPart part , ISelection selection ) { if ( part instanceof IEditorPart ) { IRubyElement element = null ; if ( selection instanceof IStructuredSelection ) { Object obj = getSingleElementFromSelection ( selection ) ; if ( obj instanceof IRubyElement ) element = ( IRubyElement ) obj ; } IEditorInput ei = ( ( IEditorPart ) part ) . getEditorInput ( ) ; if ( selection instanceof ITextSelection ) { int offset = ( ( ITextSelection ) selection ) . getOffset ( ) ; element = getElementAt ( ei , offset ) ; } if ( element != null ) { adjustInputAndSetSelection ( element ) ; return ; } if ( ei instanceof IFileEditorInput ) { IFile file = ( ( IFileEditorInput ) ei ) . getFile ( ) ; IRubyElement je = ( IRubyElement ) file . getAdapter ( IRubyElement . class ) ; if ( je == null ) { IContainer container = ( ( IFileEditorInput ) ei ) . getFile ( ) . getParent ( ) ; if ( container != null ) je = ( IRubyElement ) container . getAdapter ( IRubyElement . class ) ; } if ( je == null ) { setSelection ( null , false ) ; return ; } adjustInputAndSetSelection ( je ) ; } } } protected IRubyElement getElementAt ( IEditorInput input , int offset ) { IWorkingCopyManager manager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; IRubyScript unit = manager . getWorkingCopy ( input ) ; if ( unit != null ) try { if ( unit . isConsistent ( ) ) return unit . getElementAt ( offset ) ; else { } } catch ( RubyModelException ex ) { } return null ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . Comparator ; import org . rubypeople . rdt . core . IRubyElement ; public class RubyElementTypeComparator implements Comparator { public int compare ( Object o1 , Object o2 ) { if ( ! ( o1 instanceof IRubyElement ) || ! ( o2 instanceof IRubyElement ) ) throw new ClassCastException ( ) ; return getIdForRubyElement ( ( IRubyElement ) o1 ) - getIdForRubyElement ( ( IRubyElement ) o2 ) ; } public int compare ( Object o1 , int elementType ) { if ( ! ( o1 instanceof IRubyElement ) ) throw new ClassCastException ( ) ; return getIdForRubyElement ( ( IRubyElement ) o1 ) - getIdForRubyElementType ( elementType ) ; } int getIdForRubyElement ( IRubyElement element ) { return getIdForRubyElementType ( element . getElementType ( ) ) ; } int getIdForRubyElementType ( int elementType ) { switch ( elementType ) { case IRubyElement . RUBY_MODEL : return ; case IRubyElement . RUBY_PROJECT : return ; case IRubyElement . SCRIPT : return ; case IRubyElement . TYPE : return ; case IRubyElement . FIELD : return ; case IRubyElement . METHOD : return ; case IRubyElement . IMPORT_CONTAINER : return ; case IRubyElement . IMPORT_DECLARATION : return ; default : return ; } } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; class ProjectAndSourceFolderContentProvider extends RubyBrowsingContentProvider { ProjectAndSourceFolderContentProvider ( RubyBrowsingPart browsingPart ) { super ( false , browsingPart ) ; } public Object [ ] getChildren ( Object element ) { if ( ! exists ( element ) ) return NO_CHILDREN ; try { startReadInDisplayThread ( ) ; if ( element instanceof IStructuredSelection ) { Assert . isLegal ( false ) ; Object [ ] result = new Object [ ] ; Class clazz = null ; Iterator iter = ( ( IStructuredSelection ) element ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Object item = iter . next ( ) ; if ( clazz == null ) clazz = item . getClass ( ) ; if ( clazz == item . getClass ( ) ) result = concatenate ( result , getChildren ( item ) ) ; else return NO_CHILDREN ; } return result ; } if ( element instanceof IStructuredSelection ) { Assert . isLegal ( false ) ; Object [ ] result = new Object [ ] ; Iterator iter = ( ( IStructuredSelection ) element ) . iterator ( ) ; while ( iter . hasNext ( ) ) result = concatenate ( result , getChildren ( iter . next ( ) ) ) ; return result ; } if ( element instanceof IRubyProject ) return getSourceFolderRoots ( ( IRubyProject ) element ) ; if ( element instanceof ISourceFolderRoot ) return NO_CHILDREN ; return super . getChildren ( element ) ; } catch ( RubyModelException e ) { return NO_CHILDREN ; } finally { finishedReadInDisplayThread ( ) ; } } protected Object [ ] getSourceFolderRoots ( IRubyProject project ) throws RubyModelException { if ( ! project . getProject ( ) . isOpen ( ) ) return NO_CHILDREN ; ISourceFolderRoot [ ] roots = project . getSourceFolderRoots ( ) ; List list = new ArrayList ( roots . length ) ; for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; if ( ! isProjectSourceFolderRoot ( root ) ) list . add ( root ) ; } return list . toArray ( ) ; } public boolean hasChildren ( Object element ) { return element instanceof IRubyProject && super . hasChildren ( element ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Widget ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTableViewer ; class PackagesViewTableViewer extends ProblemTableViewer implements IPackagesViewViewer { public PackagesViewTableViewer ( Composite parent , int style ) { super ( parent , style ) ; } public void mapElement ( Object element , Widget item ) { super . mapElement ( element , item ) ; } public void unmapElement ( Object element , Widget item ) { super . unmapElement ( element , item ) ; } protected Object [ ] getFilteredChildren ( Object parent ) { Object [ ] result = getRawChildren ( parent ) ; List list = new ArrayList ( ) ; if ( result != null ) { Object [ ] toBeFiltered = new Object [ ] ; for ( int i = ; i < result . length ; i ++ ) { Object object = result [ i ] ; toBeFiltered [ ] = object ; if ( filter ( toBeFiltered ) . length == ) list . add ( object ) ; } } return list . toArray ( ) ; } public Widget doFindItem ( Object element ) { return super . doFindItem ( element ) ; } public Widget doFindInputItem ( Object element ) { return super . doFindInputItem ( element ) ; } public List getSelectionFromWidget ( ) { return super . getSelectionFromWidget ( ) ; } public void doUpdateItem ( Widget item , Object element , boolean fullMap ) { super . doUpdateItem ( item , element , fullMap ) ; } public void internalRefresh ( Object element ) { super . internalRefresh ( element ) ; } public void setSelectionToWidget ( List l , boolean reveal ) { super . setSelectionToWidget ( l , reveal ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . ui . ProblemsLabelDecorator ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; class TopLevelTypeProblemsLabelDecorator extends ProblemsLabelDecorator { public TopLevelTypeProblemsLabelDecorator ( ImageDescriptorRegistry registry ) { super ( registry ) ; } protected boolean isInside ( int pos , ISourceReference sourceElement ) throws CoreException { if ( ! ( sourceElement instanceof IType ) || ( ( IType ) sourceElement ) . getDeclaringType ( ) != null ) return false ; IRubyScript cu = ( ( IType ) sourceElement ) . getRubyScript ( ) ; if ( cu == null ) return false ; IType [ ] types = cu . getTypes ( ) ; if ( types . length < ) return false ; int firstTypeStartOffset = - ; ISourceRange range = types [ ] . getSourceRange ( ) ; if ( range != null ) firstTypeStartOffset = range . getOffset ( ) ; int lastTypeEndOffset = - ; range = types [ types . length - ] . getSourceRange ( ) ; if ( range != null ) lastTypeEndOffset = range . getOffset ( ) + range . getLength ( ) - ; return pos < firstTypeStartOffset || pos > lastTypeEndOffset || isInside ( pos , sourceElement . getSourceRange ( ) ) ; } private boolean isInside ( int pos , ISourceRange range ) { if ( range == null ) return false ; int offset = range . getOffset ( ) ; return offset <= pos && pos < offset + range . getLength ( ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . List ; import org . eclipse . swt . widgets . Widget ; interface IPackagesViewViewer { public void mapElement ( Object element , Widget item ) ; public void unmapElement ( Object element , Widget item ) ; public Widget doFindInputItem ( Object element ) ; public Widget doFindItem ( Object element ) ; public void doUpdateItem ( Widget item , Object element , boolean fullMap ) ; public List getSelectionFromWidget ( ) ; public void internalRefresh ( Object element ) ; public void setSelectionToWidget ( List l , boolean reveal ) ; } package org . rubypeople . rdt . internal . ui . browsing ; import org . rubypeople . rdt . internal . ui . actions . AbstractToggleLinkingAction ; public class ToggleLinkingAction extends AbstractToggleLinkingAction { RubyBrowsingPart fRubyBrowsingPart ; public ToggleLinkingAction ( RubyBrowsingPart part ) { setChecked ( part . isLinkingEnabled ( ) ) ; fRubyBrowsingPart = part ; } public void run ( ) { fRubyBrowsingPart . setLinkingEnabled ( isChecked ( ) ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import java . util . Arrays ; import java . util . List ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . IWorkbenchPart ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . LogicalType ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . LexicalSortingAction ; import org . rubypeople . rdt . internal . ui . preferences . MembersOrderPreferenceCache ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . ColoredViewersManager ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTreeViewer ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyUILabelProvider ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . actions . MemberFilterActionGroup ; public class MembersView extends RubyBrowsingPart implements IPropertyChangeListener { private MemberFilterActionGroup fMemberFilterActionGroup ; public MembersView ( ) { setHasCustomSetFilter ( true ) ; RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; } protected RubyUILabelProvider createLabelProvider ( ) { return new AppearanceAwareLabelProvider ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS | RubyElementLabels . M_PARAMETER_NAMES , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS ) ; } protected String getLinkToEditorKey ( ) { return PreferenceConstants . LINK_BROWSING_MEMBERS_TO_EDITOR ; } protected boolean isValidInput ( Object element ) { if ( element instanceof IType ) { IType type = ( IType ) element ; return type . getDeclaringType ( ) == null ; } return false ; } protected boolean isValidElement ( Object element ) { if ( element instanceof IMember ) return super . isValidElement ( ( ( IMember ) element ) . getDeclaringType ( ) ) ; else if ( element instanceof IImportDeclaration ) return isValidElement ( ( ( IRubyElement ) element ) . getParent ( ) ) ; else if ( element instanceof IImportContainer ) { Object input = getViewer ( ) . getInput ( ) ; if ( input instanceof IRubyElement ) { IRubyScript cu = ( IRubyScript ) ( ( IRubyElement ) input ) . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) { IRubyScript importContainerCu = ( IRubyScript ) ( ( IRubyElement ) element ) . getAncestor ( IRubyElement . SCRIPT ) ; return cu . equals ( importContainerCu ) ; } } } return false ; } protected void hookViewerListeners ( ) { super . hookViewerListeners ( ) ; getViewer ( ) . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { TreeViewer viewer = ( TreeViewer ) getViewer ( ) ; Object element = ( ( IStructuredSelection ) event . getSelection ( ) ) . getFirstElement ( ) ; if ( viewer . isExpandable ( element ) ) viewer . setExpandedState ( element , ! viewer . getExpandedState ( element ) ) ; } } ) ; } protected IRubyElement findElementToSelect ( IRubyElement je ) { if ( je == null ) return null ; switch ( je . getElementType ( ) ) { case IRubyElement . TYPE : if ( ( ( IType ) je ) . getDeclaringType ( ) == null ) return null ; case IRubyElement . METHOD : case IRubyElement . FIELD : case IRubyElement . IMPORT_CONTAINER : return getSuitableRubyElement ( je ) ; case IRubyElement . IMPORT_DECLARATION : je = getSuitableRubyElement ( je ) ; if ( je != null ) { IRubyScript cu = ( IRubyScript ) je . getParent ( ) . getParent ( ) ; try { if ( cu . getImports ( ) [ ] . equals ( je ) ) { Object selectedElement = getSingleElementFromSelection ( getViewer ( ) . getSelection ( ) ) ; if ( selectedElement instanceof IImportContainer ) return ( IImportContainer ) selectedElement ; } } catch ( RubyModelException ex ) { } return je ; } break ; } return null ; } protected IRubyElement findInputForRubyElement ( IRubyElement je ) { if ( je == null || ! je . exists ( ) ) return null ; switch ( je . getElementType ( ) ) { case IRubyElement . TYPE : return je ; case IRubyElement . SCRIPT : return getTypeForRubyScript ( ( IRubyScript ) je ) ; case IRubyElement . IMPORT_DECLARATION : return findInputForRubyElement ( je . getParent ( ) ) ; case IRubyElement . IMPORT_CONTAINER : IRubyElement parent = je . getParent ( ) ; if ( parent instanceof IRubyScript ) { return getTypeForRubyScript ( ( IRubyScript ) parent ) ; } default : if ( je instanceof IMember ) return findInputForRubyElement ( ( ( IMember ) je ) . getDeclaringType ( ) ) ; } return null ; } boolean isInputAWorkingCopy ( ) { Object input = getViewer ( ) . getInput ( ) ; if ( input instanceof IRubyElement ) { IRubyScript cu = ( IRubyScript ) ( ( IRubyElement ) input ) . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) return cu . isWorkingCopy ( ) ; } return false ; } public void propertyChange ( PropertyChangeEvent event ) { if ( MembersOrderPreferenceCache . isMemberOrderProperty ( event . getProperty ( ) ) ) { getViewer ( ) . refresh ( ) ; } } public void dispose ( ) { if ( fMemberFilterActionGroup != null ) { fMemberFilterActionGroup . dispose ( ) ; fMemberFilterActionGroup = null ; } super . dispose ( ) ; RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; } protected StructuredViewer createViewer ( Composite parent ) { ProblemTreeViewer viewer = new ProblemTreeViewer ( parent , SWT . MULTI ) ; ColoredViewersManager . install ( viewer ) ; fMemberFilterActionGroup = new MemberFilterActionGroup ( viewer , RubyUI . ID_MEMBERS_VIEW ) ; return viewer ; } protected void fillToolBar ( IToolBarManager tbm ) { tbm . add ( new LexicalSortingAction ( getViewer ( ) , RubyUI . ID_MEMBERS_VIEW ) ) ; fMemberFilterActionGroup . contributeToToolBar ( tbm ) ; super . fillToolBar ( tbm ) ; } @ Override public void selectionChanged ( IWorkbenchPart part , ISelection selection ) { if ( ! needsToProcessSelectionChanged ( part , selection ) ) return ; if ( selection instanceof IStructuredSelection ) { IStructuredSelection sel = ( IStructuredSelection ) selection ; Object selectedElement = sel . getFirstElement ( ) ; if ( sel . size ( ) == && ( selectedElement instanceof LogicalType ) ) { IType [ ] fragments = ( ( LogicalType ) selectedElement ) . getOriginalTypes ( ) ; List selectedElements = Arrays . asList ( fragments ) ; if ( selectedElements . size ( ) > ) { adjustInput ( part , selectedElements ) ; fPreviousSelectedElement = selectedElements ; fPreviousSelectionProvider = part ; } else if ( selectedElements . size ( ) == ) super . selectionChanged ( part , new StructuredSelection ( selectedElements . get ( ) ) ) ; else Assert . isLegal ( false ) ; return ; } } super . selectionChanged ( part , selection ) ; } private void adjustInput ( IWorkbenchPart part , List selectedElements ) { Object currentInput = getViewer ( ) . getInput ( ) ; if ( ! selectedElements . equals ( currentInput ) ) setInput ( selectedElements ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . viewers . DecoratingLabelProvider ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . part . IShowInTargetList ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . actions . SelectAllAction ; import org . rubypeople . rdt . internal . ui . filters . NonRubyElementFilter ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyUILabelProvider ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . RubyUI ; public class TypesView extends RubyBrowsingPart { private SelectAllAction fSelectAllAction ; private boolean fLastInputWasProject ; protected RubyUILabelProvider createLabelProvider ( ) { return new AppearanceAwareLabelProvider ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS | RubyElementLabels . T_CATEGORY | RubyElementLabels . T_NAME_FULLY_QUALIFIED , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS ) ; } public Object getAdapter ( Class key ) { if ( key == IShowInTargetList . class ) { return new IShowInTargetList ( ) { public String [ ] getShowInTargetIds ( ) { return new String [ ] { RubyUI . ID_RUBY_EXPLORER , IPageLayout . ID_RES_NAV } ; } } ; } return super . getAdapter ( key ) ; } protected void addFilters ( ) { super . addFilters ( ) ; getViewer ( ) . addFilter ( new NonRubyElementFilter ( ) ) ; } protected boolean isValidInput ( Object element ) { if ( element instanceof IRubyProject || ( element instanceof ISourceFolderRoot && ( ( IRubyElement ) element ) . getElementName ( ) != ISourceFolderRoot . DEFAULT_PACKAGEROOT_PATH ) ) try { IRubyProject jProject = ( ( IRubyElement ) element ) . getRubyProject ( ) ; if ( jProject != null ) return jProject . getProject ( ) . hasNature ( RubyCore . NATURE_ID ) ; } catch ( CoreException ex ) { return false ; } return false ; } @ Override protected IContentProvider createContentProvider ( ) { return new TypesContentProvider ( this ) ; } protected boolean isValidElement ( Object element ) { if ( element instanceof IRubyScript ) return super . isValidElement ( ( ( IRubyScript ) element ) . getParent ( ) ) ; else if ( element instanceof IType ) { IType type = ( IType ) element ; return isValidElement ( type . getRubyScript ( ) ) ; } return false ; } protected IRubyElement findElementToSelect ( IRubyElement je ) { if ( je == null ) return null ; switch ( je . getElementType ( ) ) { case IRubyElement . TYPE : IType type = ( ( IType ) je ) . getDeclaringType ( ) ; if ( type == null ) type = ( IType ) je ; return getSuitableRubyElement ( type ) ; case IRubyElement . SCRIPT : return getTypeForRubyScript ( ( IRubyScript ) je ) ; case IRubyElement . IMPORT_CONTAINER : case IRubyElement . IMPORT_DECLARATION : return findElementToSelect ( je . getParent ( ) ) ; default : if ( je instanceof IMember ) return findElementToSelect ( ( ( IMember ) je ) . getDeclaringType ( ) ) ; return null ; } } protected IRubyElement findInputForRubyElement ( IRubyElement je ) { if ( je == null ) return null ; if ( je . getElementType ( ) == IRubyElement . SOURCE_FOLDER_ROOT || je . getElementType ( ) == IRubyElement . RUBY_PROJECT ) return findInputForRubyElement ( je , true ) ; else return findInputForRubyElement ( je , false ) ; } protected IRubyElement findInputForRubyElement ( IRubyElement je , boolean canChangeInputType ) { if ( je == null || ! je . exists ( ) ) return null ; if ( isValidInput ( je ) ) { if ( canChangeInputType ) fLastInputWasProject = je . getElementType ( ) == IRubyElement . RUBY_PROJECT ; return je ; } else if ( fLastInputWasProject ) { ISourceFolderRoot packageFragmentRoot = ( ISourceFolderRoot ) je . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; if ( ! packageFragmentRoot . isExternal ( ) ) return je . getRubyProject ( ) ; } return findInputForRubyElement ( je . getParent ( ) , canChangeInputType ) ; } protected String getHelpContextId ( ) { return IRubyHelpContextIds . TYPES_VIEW ; } protected String getLinkToEditorKey ( ) { return PreferenceConstants . LINK_BROWSING_TYPES_TO_EDITOR ; } protected void createActions ( ) { super . createActions ( ) ; fSelectAllAction = new SelectAllAction ( ( TableViewer ) getViewer ( ) ) ; } protected void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; actionBars . setGlobalActionHandler ( IWorkbenchActionConstants . SELECT_ALL , fSelectAllAction ) ; } protected DecoratingLabelProvider createDecoratingLabelProvider ( RubyUILabelProvider provider ) { DecoratingLabelProvider decoratingLabelProvider = super . createDecoratingLabelProvider ( provider ) ; provider . addLabelDecorator ( new TopLevelTypeProblemsLabelDecorator ( null ) ) ; return decoratingLabelProvider ; } @ Override public void selectionChanged ( IWorkbenchPart part , ISelection selection ) { if ( part instanceof MembersView ) return ; super . selectionChanged ( part , selection ) ; } } package org . rubypeople . rdt . internal . ui . browsing ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IPerspectiveFactory ; import org . eclipse . ui . IPlaceholderFolderLayout ; import org . eclipse . ui . console . IConsoleConstants ; import org . eclipse . ui . progress . IProgressConstants ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; public class RubyBrowsingPerspectiveFactory implements IPerspectiveFactory { static IRubyElement fgRubyElementFromAction ; public RubyBrowsingPerspectiveFactory ( ) { super ( ) ; } public void createInitialLayout ( IPageLayout layout ) { if ( stackBrowsingViewsVertically ( ) ) createVerticalLayout ( layout ) ; else createHorizontalLayout ( layout ) ; layout . addActionSet ( IDebugUIConstants . LAUNCH_ACTION_SET ) ; layout . addActionSet ( RubyUI . ID_ACTION_SET ) ; layout . addActionSet ( RubyUI . ID_ELEMENT_CREATION_ACTION_SET ) ; layout . addActionSet ( IPageLayout . ID_NAVIGATE_ACTION_SET ) ; layout . addShowViewShortcut ( RubyUI . ID_PROJECTS_VIEW ) ; layout . addShowViewShortcut ( RubyUI . ID_TYPES_VIEW ) ; layout . addShowViewShortcut ( RubyUI . ID_MEMBERS_VIEW ) ; layout . addShowViewShortcut ( NewSearchUI . SEARCH_VIEW_ID ) ; layout . addShowViewShortcut ( IConsoleConstants . ID_CONSOLE_VIEW ) ; layout . addShowViewShortcut ( IPageLayout . ID_OUTLINE ) ; layout . addShowViewShortcut ( IPageLayout . ID_PROBLEM_VIEW ) ; layout . addShowViewShortcut ( IPageLayout . ID_RES_NAV ) ; layout . addNewWizardShortcut ( "" ) ; layout . addNewWizardShortcut ( "" ) ; layout . addNewWizardShortcut ( "" ) ; layout . addNewWizardShortcut ( "" ) ; layout . addNewWizardShortcut ( "" ) ; } private void createVerticalLayout ( IPageLayout layout ) { String relativePartId = IPageLayout . ID_EDITOR_AREA ; int relativePos = IPageLayout . LEFT ; IPlaceholderFolderLayout placeHolderLeft = layout . createPlaceholderFolder ( "" , IPageLayout . LEFT , ( float ) , IPageLayout . ID_EDITOR_AREA ) ; placeHolderLeft . addPlaceholder ( IPageLayout . ID_OUTLINE ) ; placeHolderLeft . addPlaceholder ( IPageLayout . ID_RES_NAV ) ; if ( shouldShowProjectsView ( ) ) { layout . addView ( RubyUI . ID_PROJECTS_VIEW , IPageLayout . LEFT , ( float ) , IPageLayout . ID_EDITOR_AREA ) ; relativePartId = RubyUI . ID_PROJECTS_VIEW ; relativePos = IPageLayout . BOTTOM ; } layout . addView ( RubyUI . ID_TYPES_VIEW , relativePos , ( float ) , relativePartId ) ; layout . addView ( RubyUI . ID_MEMBERS_VIEW , IPageLayout . BOTTOM , ( float ) , RubyUI . ID_TYPES_VIEW ) ; IPlaceholderFolderLayout placeHolderBottom = layout . createPlaceholderFolder ( "" , IPageLayout . BOTTOM , ( float ) , IPageLayout . ID_EDITOR_AREA ) ; placeHolderBottom . addPlaceholder ( IPageLayout . ID_PROBLEM_VIEW ) ; placeHolderBottom . addPlaceholder ( NewSearchUI . SEARCH_VIEW_ID ) ; placeHolderBottom . addPlaceholder ( IConsoleConstants . ID_CONSOLE_VIEW ) ; placeHolderBottom . addPlaceholder ( IPageLayout . ID_BOOKMARKS ) ; placeHolderBottom . addPlaceholder ( IProgressConstants . PROGRESS_VIEW_ID ) ; } private void createHorizontalLayout ( IPageLayout layout ) { String relativePartId = IPageLayout . ID_EDITOR_AREA ; int relativePos = IPageLayout . TOP ; if ( shouldShowProjectsView ( ) ) { layout . addView ( RubyUI . ID_PROJECTS_VIEW , IPageLayout . TOP , ( float ) , IPageLayout . ID_EDITOR_AREA ) ; relativePartId = RubyUI . ID_PROJECTS_VIEW ; relativePos = IPageLayout . RIGHT ; } layout . addView ( RubyUI . ID_TYPES_VIEW , relativePos , ( float ) , relativePartId ) ; layout . addView ( RubyUI . ID_MEMBERS_VIEW , IPageLayout . RIGHT , ( float ) , RubyUI . ID_TYPES_VIEW ) ; IPlaceholderFolderLayout placeHolderLeft = layout . createPlaceholderFolder ( "" , IPageLayout . LEFT , ( float ) , IPageLayout . ID_EDITOR_AREA ) ; placeHolderLeft . addPlaceholder ( IPageLayout . ID_OUTLINE ) ; placeHolderLeft . addPlaceholder ( IPageLayout . ID_RES_NAV ) ; IPlaceholderFolderLayout placeHolderBottom = layout . createPlaceholderFolder ( "" , IPageLayout . BOTTOM , ( float ) , IPageLayout . ID_EDITOR_AREA ) ; placeHolderBottom . addPlaceholder ( IPageLayout . ID_PROBLEM_VIEW ) ; placeHolderBottom . addPlaceholder ( NewSearchUI . SEARCH_VIEW_ID ) ; placeHolderBottom . addPlaceholder ( IConsoleConstants . ID_CONSOLE_VIEW ) ; placeHolderBottom . addPlaceholder ( IPageLayout . ID_BOOKMARKS ) ; placeHolderBottom . addPlaceholder ( IProgressConstants . PROGRESS_VIEW_ID ) ; } private boolean shouldShowProjectsView ( ) { return fgRubyElementFromAction == null || fgRubyElementFromAction . getElementType ( ) == IRubyElement . RUBY_MODEL ; } private boolean stackBrowsingViewsVertically ( ) { return PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . BROWSING_STACK_VERTICALLY ) ; } static void setInputFromAction ( IAdaptable input ) { if ( input instanceof IRubyElement ) fgRubyElementFromAction = ( IRubyElement ) input ; else fgRubyElementFromAction = null ; } } package org . rubypeople . rdt . internal . ui . browsing ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . GroupMarker ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IContributionItem ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . DecoratingLabelProvider ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . IShowInTargetList ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . MultiActionGroup ; import org . rubypeople . rdt . internal . ui . actions . SelectAllAction ; import org . rubypeople . rdt . internal . ui . filters . LibraryFilter ; import org . rubypeople . rdt . internal . ui . filters . NonRubyElementFilter ; import org . rubypeople . rdt . internal . ui . packageview . PackageExplorerContentProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . DecoratingRubyLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTableViewer ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTreeViewer ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyUILabelProvider ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementSorter ; import org . rubypeople . rdt . ui . RubyUI ; public class PackagesView extends RubyBrowsingPart { private static final String TAG_VIEW_STATE = "" ; private static final int LIST_VIEW_STATE = ; private static final int TREE_VIEW_STATE = ; private SelectAllAction fSelectAllAction ; private int fCurrViewState ; private PackageViewerWrapper fWrappedViewer ; private MultiActionGroup fSwitchActionGroup ; private boolean fLastInputWasProject ; protected void addFilters ( ) { super . addFilters ( ) ; getViewer ( ) . addFilter ( createNonRubyElementFilter ( ) ) ; getViewer ( ) . addFilter ( new LibraryFilter ( ) ) ; } protected NonRubyElementFilter createNonRubyElementFilter ( ) { return new NonRubyElementFilter ( ) { public boolean select ( Viewer viewer , Object parent , Object element ) { return ( ( element instanceof IRubyElement ) || ( element instanceof IFolder ) ) ; } } ; } public void init ( IViewSite site , IMemento memento ) throws PartInitException { super . init ( site , memento ) ; fWrappedViewer = new PackageViewerWrapper ( ) ; restoreLayoutState ( memento ) ; } private void restoreLayoutState ( IMemento memento ) { if ( memento == null ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; fCurrViewState = store . getInt ( this . getViewSite ( ) . getId ( ) + TAG_VIEW_STATE ) ; } else { Integer integer = memento . getInteger ( this . getViewSite ( ) . getId ( ) + TAG_VIEW_STATE ) ; if ( ( integer == null ) || ! isValidState ( integer . intValue ( ) ) ) { fCurrViewState = LIST_VIEW_STATE ; } else fCurrViewState = integer . intValue ( ) ; } } private boolean isValidState ( int state ) { return ( state == LIST_VIEW_STATE ) || ( state == TREE_VIEW_STATE ) ; } public void saveState ( IMemento memento ) { super . saveState ( memento ) ; memento . putInteger ( this . getViewSite ( ) . getId ( ) + TAG_VIEW_STATE , fCurrViewState ) ; } protected StructuredViewer createViewer ( Composite parent ) { StructuredViewer viewer ; if ( isInListState ( ) ) viewer = createTableViewer ( parent ) ; else viewer = createTreeViewer ( parent ) ; fWrappedViewer . setViewer ( viewer ) ; return fWrappedViewer ; } public Object getAdapter ( Class key ) { if ( key == IShowInTargetList . class ) { return new IShowInTargetList ( ) { public String [ ] getShowInTargetIds ( ) { return new String [ ] { RubyUI . ID_RUBY_EXPLORER , IPageLayout . ID_RES_NAV } ; } } ; } return super . getAdapter ( key ) ; } protected boolean isInListState ( ) { return false ; } private ProblemTableViewer createTableViewer ( Composite parent ) { return new PackagesViewTableViewer ( parent , SWT . MULTI ) ; } private ProblemTreeViewer createTreeViewer ( Composite parent ) { return new PackagesViewTreeViewer ( parent , SWT . MULTI ) ; } protected IContentProvider createContentProvider ( ) { return new PackageExplorerContentProvider ( false ) ; } protected String getHelpContextId ( ) { return IRubyHelpContextIds . PACKAGES_BROWSING_VIEW ; } protected String getLinkToEditorKey ( ) { return PreferenceConstants . LINK_BROWSING_PACKAGES_TO_EDITOR ; } protected boolean isValidInput ( Object element ) { if ( element instanceof IRubyProject || ( element instanceof ISourceFolderRoot && ( ( IRubyElement ) element ) . getElementName ( ) != ISourceFolderRoot . DEFAULT_PACKAGEROOT_PATH ) ) try { IRubyProject jProject = ( ( IRubyElement ) element ) . getRubyProject ( ) ; if ( jProject != null ) return jProject . getProject ( ) . hasNature ( RubyCore . NATURE_ID ) ; } catch ( CoreException ex ) { return false ; } return false ; } protected boolean isValidElement ( Object element ) { if ( element instanceof ISourceFolder ) { IRubyElement parent = ( ( ISourceFolder ) element ) . getParent ( ) ; if ( parent != null ) return super . isValidElement ( parent ) || super . isValidElement ( parent . getRubyProject ( ) ) ; } return false ; } protected IRubyElement findElementToSelect ( IRubyElement je ) { if ( je == null ) return null ; switch ( je . getElementType ( ) ) { case IRubyElement . SOURCE_FOLDER : return je ; case IRubyElement . SCRIPT : return ( ( IRubyScript ) je ) . getParent ( ) ; case IRubyElement . TYPE : return ( ( IType ) je ) . getSourceFolder ( ) ; default : return findElementToSelect ( je . getParent ( ) ) ; } } protected void setInput ( Object input ) { setViewerWrapperInput ( input ) ; super . updateTitle ( ) ; } private void setViewerWrapperInput ( Object input ) { fWrappedViewer . setViewerInput ( input ) ; } protected void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; fSwitchActionGroup . fillActionBars ( actionBars ) ; } private void setUpViewer ( StructuredViewer viewer ) { Assert . isTrue ( viewer != null ) ; RubyUILabelProvider labelProvider = createLabelProvider ( ) ; viewer . setLabelProvider ( createDecoratingLabelProvider ( labelProvider ) ) ; viewer . setSorter ( createRubyElementSorter ( ) ) ; viewer . setUseHashlookup ( true ) ; createContextMenu ( ) ; addKeyListener ( ) ; hookViewerListeners ( ) ; viewer . setContentProvider ( createContentProvider ( ) ) ; initDragAndDrop ( ) ; } protected RubyElementSorter createRubyElementSorter ( ) { return new RubyElementSorter ( ) ; } protected void setSiteSelectionProvider ( ) { getSite ( ) . setSelectionProvider ( fWrappedViewer ) ; } protected void createActions ( ) { super . createActions ( ) ; createSelectAllAction ( ) ; fSwitchActionGroup = createSwitchActionGroup ( ) ; } private MultiActionGroup createSwitchActionGroup ( ) { LayoutAction switchToFlatViewAction = new LayoutAction ( RubyBrowsingMessages . PackagesView_flatLayoutAction_label , LIST_VIEW_STATE ) ; LayoutAction switchToHierarchicalViewAction = new LayoutAction ( RubyBrowsingMessages . PackagesView_HierarchicalLayoutAction_label , TREE_VIEW_STATE ) ; RubyPluginImages . setLocalImageDescriptors ( switchToFlatViewAction , "" ) ; RubyPluginImages . setLocalImageDescriptors ( switchToHierarchicalViewAction , "" ) ; return new LayoutActionGroup ( new IAction [ ] { switchToFlatViewAction , switchToHierarchicalViewAction } , fCurrViewState ) ; } private static class LayoutActionGroup extends MultiActionGroup { LayoutActionGroup ( IAction [ ] actions , int index ) { super ( actions , index ) ; } public void fillActionBars ( IActionBars actionBars ) { IMenuManager manager = actionBars . getMenuManager ( ) ; final IContributionItem groupMarker = new GroupMarker ( "" ) ; manager . add ( groupMarker ) ; IMenuManager newManager = new MenuManager ( RubyBrowsingMessages . PackagesView_LayoutActionGroup_layout_label ) ; manager . appendToGroup ( "" , newManager ) ; super . addActions ( newManager ) ; } } private class LayoutAction extends Action { private int fState ; public LayoutAction ( String text , int state ) { super ( text , IAction . AS_RADIO_BUTTON ) ; fState = state ; if ( state == PackagesView . LIST_VIEW_STATE ) PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . LAYOUT_FLAT_ACTION ) ; else PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . LAYOUT_HIERARCHICAL_ACTION ) ; } public int getState ( ) { return fState ; } public void setRunnable ( Runnable runnable ) { Assert . isNotNull ( runnable ) ; } public void run ( ) { switchViewer ( fState ) ; } } private void switchViewer ( int state ) { if ( fCurrViewState == state ) return ; else { fCurrViewState = state ; IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; store . setValue ( getViewSite ( ) . getId ( ) + TAG_VIEW_STATE , state ) ; } StructuredViewer viewer = fWrappedViewer . getViewer ( ) ; Object object = viewer . getInput ( ) ; ISelection selection = viewer . getSelection ( ) ; Control control = createViewer ( fWrappedViewer . getControl ( ) . getParent ( ) ) . getControl ( ) ; setUpViewer ( fWrappedViewer ) ; createSelectAllAction ( ) ; fWrappedViewer . setViewerInput ( object ) ; fWrappedViewer . getControl ( ) . setFocus ( ) ; fWrappedViewer . setSelection ( selection , true ) ; viewer . getContentProvider ( ) . dispose ( ) ; viewer . getControl ( ) . dispose ( ) ; if ( control != null && ! control . isDisposed ( ) ) { control . setVisible ( true ) ; control . getParent ( ) . layout ( true ) ; } } private void createSelectAllAction ( ) { IActionBars actionBars = getViewSite ( ) . getActionBars ( ) ; if ( isInListState ( ) ) { fSelectAllAction = new SelectAllAction ( ( TableViewer ) fWrappedViewer . getViewer ( ) ) ; actionBars . setGlobalActionHandler ( IWorkbenchActionConstants . SELECT_ALL , fSelectAllAction ) ; } else { actionBars . setGlobalActionHandler ( IWorkbenchActionConstants . SELECT_ALL , null ) ; fSelectAllAction = null ; } actionBars . updateActionBars ( ) ; } protected IRubyElement findInputForRubyElement ( IRubyElement je ) { if ( je == null ) return null ; if ( je . getElementType ( ) == IRubyElement . SOURCE_FOLDER_ROOT || je . getElementType ( ) == IRubyElement . RUBY_PROJECT ) return findInputForRubyElement ( je , true ) ; else return findInputForRubyElement ( je , false ) ; } protected IRubyElement findInputForRubyElement ( IRubyElement je , boolean canChangeInputType ) { if ( je == null || ! je . exists ( ) ) return null ; if ( isValidInput ( je ) ) { if ( canChangeInputType ) fLastInputWasProject = je . getElementType ( ) == IRubyElement . RUBY_PROJECT ; return je ; } else if ( fLastInputWasProject ) { ISourceFolderRoot packageFragmentRoot = ( ISourceFolderRoot ) je . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; if ( ! packageFragmentRoot . isExternal ( ) ) return je . getRubyProject ( ) ; } return findInputForRubyElement ( je . getParent ( ) , canChangeInputType ) ; } protected DecoratingLabelProvider createDecoratingLabelProvider ( RubyUILabelProvider provider ) { return new DecoratingRubyLabelProvider ( provider , false ) ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Observable ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . osgi . service . prefs . BackingStoreException ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . preferences . PreferencesAccess ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; public class ProfileManager extends Observable { private final static String ID_PREFIX = "" ; public static abstract class Profile implements Comparable { public abstract String getName ( ) ; public abstract Profile rename ( String name , ProfileManager manager ) ; public abstract Map getSettings ( ) ; public abstract void setSettings ( Map settings ) ; public int getVersion ( ) { return ProfileVersioner . CURRENT_VERSION ; } public boolean hasEqualSettings ( Map otherMap , List allKeys ) { Map settings = getSettings ( ) ; for ( Iterator iter = allKeys . iterator ( ) ; iter . hasNext ( ) ; ) { String key = ( String ) iter . next ( ) ; Object other = otherMap . get ( key ) ; Object curr = settings . get ( key ) ; if ( other == null ) { if ( curr != null ) { return false ; } } else if ( ! other . equals ( curr ) ) { return false ; } } return true ; } public abstract boolean isProfileToSave ( ) ; public abstract String getID ( ) ; public boolean isSharedProfile ( ) { return false ; } public boolean isBuiltInProfile ( ) { return false ; } } public final static class BuiltInProfile extends Profile { private final String fName ; private final String fID ; private final Map fSettings ; private final int fOrder ; protected BuiltInProfile ( String ID , String name , Map settings , int order ) { fName = name ; fID = ID ; fSettings = settings ; fOrder = order ; } public String getName ( ) { return fName ; } public Profile rename ( String name , ProfileManager manager ) { final String trimmed = name . trim ( ) ; CustomProfile newProfile = new CustomProfile ( trimmed , fSettings , ProfileVersioner . CURRENT_VERSION ) ; manager . addProfile ( newProfile ) ; return newProfile ; } public Map getSettings ( ) { return fSettings ; } public void setSettings ( Map settings ) { } public String getID ( ) { return fID ; } public final int compareTo ( Object o ) { if ( o instanceof BuiltInProfile ) { return fOrder - ( ( BuiltInProfile ) o ) . fOrder ; } return - ; } public boolean isProfileToSave ( ) { return false ; } public boolean isBuiltInProfile ( ) { return true ; } } public static class CustomProfile extends Profile { private String fName ; private Map fSettings ; protected ProfileManager fManager ; private int fVersion ; public CustomProfile ( String name , Map settings , int version ) { fName = name ; fSettings = settings ; fVersion = version ; } public String getName ( ) { return fName ; } public Profile rename ( String name , ProfileManager manager ) { final String trimmed = name . trim ( ) ; if ( trimmed . equals ( getName ( ) ) ) return this ; String oldID = getID ( ) ; fName = trimmed ; manager . profileRenamed ( this , oldID ) ; return this ; } public Map getSettings ( ) { return fSettings ; } public void setSettings ( Map settings ) { if ( settings == null ) throw new IllegalArgumentException ( ) ; fSettings = settings ; if ( fManager != null ) { fManager . profileChanged ( this ) ; } } public String getID ( ) { return ID_PREFIX + fName ; } public void setManager ( ProfileManager profileManager ) { fManager = profileManager ; } public ProfileManager getManager ( ) { return fManager ; } public int getVersion ( ) { return fVersion ; } public void setVersion ( int version ) { fVersion = version ; } public int compareTo ( Object o ) { if ( o instanceof SharedProfile ) { return - ; } if ( o instanceof CustomProfile ) { return getName ( ) . compareToIgnoreCase ( ( ( Profile ) o ) . getName ( ) ) ; } return ; } public boolean isProfileToSave ( ) { return true ; } } public final static class SharedProfile extends CustomProfile { public SharedProfile ( String oldName , Map options ) { super ( oldName , options , ProfileVersioner . CURRENT_VERSION ) ; } public Profile rename ( String name , ProfileManager manager ) { CustomProfile profile = new CustomProfile ( name . trim ( ) , getSettings ( ) , getVersion ( ) ) ; manager . profileReplaced ( this , profile ) ; return profile ; } public String getID ( ) { return SHARED_PROFILE ; } public final int compareTo ( Object o ) { return ; } public boolean isProfileToSave ( ) { return false ; } public boolean isSharedProfile ( ) { return true ; } } public final static int SELECTION_CHANGED_EVENT = ; public final static int PROFILE_DELETED_EVENT = ; public final static int PROFILE_RENAMED_EVENT = ; public final static int PROFILE_CREATED_EVENT = ; public final static int SETTINGS_CHANGED_EVENT = ; private final static String PROFILE_KEY = PreferenceConstants . FORMATTER_PROFILE ; private final static String FORMATTER_SETTINGS_VERSION = "" ; public final static String ECLIPSE_PROFILE = "" ; public final static String RUBY_PROFILE = "" ; public final static String SHARED_PROFILE = "" ; public final static String DEFAULT_PROFILE = ECLIPSE_PROFILE ; private final Map fProfiles ; private final List fProfilesByName ; private Profile fSelected ; private final static List fUIKeys = Collections . EMPTY_LIST ; private final static List fCoreKeys = new ArrayList ( DefaultCodeFormatterConstants . getRubyConventionsSettings ( ) . keySet ( ) ) ; private final static List fKeys ; private final PreferencesAccess fPreferencesAccess ; static { fKeys = new ArrayList ( ) ; fKeys . addAll ( fUIKeys ) ; fKeys . addAll ( fCoreKeys ) ; Collections . sort ( fKeys ) ; } public ProfileManager ( List profiles , IScopeContext context , PreferencesAccess preferencesAccess ) { fPreferencesAccess = preferencesAccess ; fProfiles = new HashMap ( ) ; fProfilesByName = new ArrayList ( ) ; addBuiltinProfiles ( fProfiles , fProfilesByName ) ; for ( final Iterator iter = profiles . iterator ( ) ; iter . hasNext ( ) ; ) { final CustomProfile profile = ( CustomProfile ) iter . next ( ) ; profile . setManager ( this ) ; fProfiles . put ( profile . getID ( ) , profile ) ; fProfilesByName . add ( profile ) ; } Collections . sort ( fProfilesByName ) ; IScopeContext instanceScope = fPreferencesAccess . getInstanceScope ( ) ; String profileId = instanceScope . getNode ( RubyUI . ID_PLUGIN ) . get ( PROFILE_KEY , null ) ; if ( profileId == null ) { profileId = DEFAULT_PROFILE ; IEclipsePreferences node = instanceScope . getNode ( RubyCore . PLUGIN_ID ) ; if ( node != null ) { String tabSetting = node . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , null ) ; if ( RubyCore . SPACE . equals ( tabSetting ) ) { profileId = RUBY_PROFILE ; } } } Profile profile = ( Profile ) fProfiles . get ( profileId ) ; if ( profile == null ) { profile = ( Profile ) fProfiles . get ( DEFAULT_PROFILE ) ; } fSelected = profile ; if ( context . getName ( ) == ProjectScope . SCOPE && hasProjectSpecificSettings ( context ) ) { Map map = readFromPreferenceStore ( context , profile ) ; if ( map != null ) { Profile matching = null ; String projProfileId = context . getNode ( RubyUI . ID_PLUGIN ) . get ( PROFILE_KEY , null ) ; if ( projProfileId != null ) { Profile curr = ( Profile ) fProfiles . get ( projProfileId ) ; if ( curr != null && ( curr . isBuiltInProfile ( ) || curr . hasEqualSettings ( map , getKeys ( ) ) ) ) { matching = curr ; } } else { for ( final Iterator iter = fProfilesByName . iterator ( ) ; iter . hasNext ( ) ; ) { Profile curr = ( Profile ) iter . next ( ) ; if ( curr . hasEqualSettings ( map , getKeys ( ) ) ) { matching = curr ; break ; } } } if ( matching == null ) { String name ; if ( projProfileId != null && ! fProfiles . containsKey ( projProfileId ) ) { name = Messages . format ( FormatterMessages . ProfileManager_unmanaged_profile_with_name , projProfileId . substring ( ID_PREFIX . length ( ) ) ) ; } else { name = FormatterMessages . ProfileManager_unmanaged_profile ; } SharedProfile shared = new SharedProfile ( name , map ) ; shared . setManager ( this ) ; fProfiles . put ( shared . getID ( ) , shared ) ; fProfilesByName . add ( shared ) ; matching = shared ; } fSelected = matching ; } } } protected void notifyObservers ( int message ) { setChanged ( ) ; notifyObservers ( new Integer ( message ) ) ; } public static boolean hasProjectSpecificSettings ( IScopeContext context ) { IEclipsePreferences corePrefs = context . getNode ( RubyCore . PLUGIN_ID ) ; for ( final Iterator keyIter = fCoreKeys . iterator ( ) ; keyIter . hasNext ( ) ; ) { final String key = ( String ) keyIter . next ( ) ; Object val = corePrefs . get ( key , null ) ; if ( val != null ) { return true ; } } IEclipsePreferences uiPrefs = context . getNode ( RubyUI . ID_PLUGIN ) ; for ( final Iterator keyIter = fUIKeys . iterator ( ) ; keyIter . hasNext ( ) ; ) { final String key = ( String ) keyIter . next ( ) ; Object val = uiPrefs . get ( key , null ) ; if ( val != null ) { return true ; } } return false ; } public Map readFromPreferenceStore ( IScopeContext context , Profile workspaceProfile ) { final Map profileOptions = new HashMap ( ) ; IEclipsePreferences uiPrefs = context . getNode ( RubyUI . ID_PLUGIN ) ; IEclipsePreferences corePrefs = context . getNode ( RubyCore . PLUGIN_ID ) ; int version = uiPrefs . getInt ( FORMATTER_SETTINGS_VERSION , ProfileVersioner . VERSION_1 ) ; if ( version != ProfileVersioner . CURRENT_VERSION ) { Map allOptions = new HashMap ( ) ; addAll ( uiPrefs , allOptions ) ; addAll ( corePrefs , allOptions ) ; return ProfileVersioner . updateAndComplete ( allOptions , version ) ; } boolean hasValues = false ; for ( final Iterator keyIter = fCoreKeys . iterator ( ) ; keyIter . hasNext ( ) ; ) { final String key = ( String ) keyIter . next ( ) ; Object val = corePrefs . get ( key , null ) ; if ( val != null ) { hasValues = true ; } else { val = workspaceProfile . getSettings ( ) . get ( key ) ; } profileOptions . put ( key , val ) ; } for ( final Iterator keyIter = fUIKeys . iterator ( ) ; keyIter . hasNext ( ) ; ) { final String key = ( String ) keyIter . next ( ) ; Object val = uiPrefs . get ( key , null ) ; if ( val != null ) { hasValues = true ; } else { val = workspaceProfile . getSettings ( ) . get ( key ) ; } profileOptions . put ( key , val ) ; } if ( ! hasValues ) { return null ; } return profileOptions ; } private void addAll ( IEclipsePreferences uiPrefs , Map allOptions ) { try { String [ ] keys = uiPrefs . keys ( ) ; for ( int i = ; i < keys . length ; i ++ ) { String key = keys [ i ] ; String val = uiPrefs . get ( key , null ) ; if ( val != null ) { allOptions . put ( key , val ) ; } } } catch ( BackingStoreException e ) { } } private boolean updatePreferences ( IEclipsePreferences prefs , List keys , Map profileOptions ) { boolean hasChanges = false ; for ( final Iterator keyIter = keys . iterator ( ) ; keyIter . hasNext ( ) ; ) { final String key = ( String ) keyIter . next ( ) ; final String oldVal = prefs . get ( key , null ) ; final String val = ( String ) profileOptions . get ( key ) ; if ( val == null ) { if ( oldVal != null ) { prefs . remove ( key ) ; hasChanges = true ; } } else if ( ! val . equals ( oldVal ) ) { prefs . put ( key , val ) ; hasChanges = true ; } } return hasChanges ; } private void writeToPreferenceStore ( Profile profile , IScopeContext context ) { final Map profileOptions = profile . getSettings ( ) ; final IEclipsePreferences corePrefs = context . getNode ( RubyCore . PLUGIN_ID ) ; updatePreferences ( corePrefs , fCoreKeys , profileOptions ) ; final IEclipsePreferences uiPrefs = context . getNode ( RubyUI . ID_PLUGIN ) ; updatePreferences ( uiPrefs , fUIKeys , profileOptions ) ; if ( uiPrefs . getInt ( FORMATTER_SETTINGS_VERSION , ) != ProfileVersioner . CURRENT_VERSION ) { uiPrefs . putInt ( FORMATTER_SETTINGS_VERSION , ProfileVersioner . CURRENT_VERSION ) ; } if ( context . getName ( ) == InstanceScope . SCOPE ) { uiPrefs . put ( PROFILE_KEY , profile . getID ( ) ) ; } else if ( context . getName ( ) == ProjectScope . SCOPE && ! profile . isSharedProfile ( ) ) { uiPrefs . put ( PROFILE_KEY , profile . getID ( ) ) ; } } private void addBuiltinProfiles ( Map profiles , List profilesByName ) { final Profile javaProfile = new BuiltInProfile ( RUBY_PROFILE , FormatterMessages . ProfileManager_ruby_conventions_profile_name , getRubySettings ( ) , ) ; profiles . put ( javaProfile . getID ( ) , javaProfile ) ; profilesByName . add ( javaProfile ) ; final Profile eclipseProfile = new BuiltInProfile ( ECLIPSE_PROFILE , FormatterMessages . ProfileManager_eclipse_profile_name , getEclipseSettings ( ) , ) ; profiles . put ( eclipseProfile . getID ( ) , eclipseProfile ) ; profilesByName . add ( eclipseProfile ) ; } public static Map getEclipseSettings ( ) { final Map options = DefaultCodeFormatterConstants . getEclipseDefaultSettings ( ) ; return options ; } public static Map getRubySettings ( ) { final Map options = DefaultCodeFormatterConstants . getRubyConventionsSettings ( ) ; return options ; } public static Map getDefaultSettings ( ) { return getEclipseSettings ( ) ; } public static List getKeys ( ) { return fKeys ; } public List getSortedProfiles ( ) { return Collections . unmodifiableList ( fProfilesByName ) ; } public String [ ] getSortedDisplayNames ( ) { final String [ ] sortedNames = new String [ fProfilesByName . size ( ) ] ; int i = ; for ( final Iterator iter = fProfilesByName . iterator ( ) ; iter . hasNext ( ) ; ) { Profile curr = ( Profile ) iter . next ( ) ; sortedNames [ i ++ ] = curr . getName ( ) ; } return sortedNames ; } public Profile getProfile ( String ID ) { return ( Profile ) fProfiles . get ( ID ) ; } public void commitChanges ( IScopeContext scopeContext ) { if ( fSelected != null ) { writeToPreferenceStore ( fSelected , scopeContext ) ; } } public void clearAllSettings ( IScopeContext context ) { final IEclipsePreferences corePrefs = context . getNode ( RubyCore . PLUGIN_ID ) ; updatePreferences ( corePrefs , fCoreKeys , Collections . EMPTY_MAP ) ; final IEclipsePreferences uiPrefs = context . getNode ( RubyUI . ID_PLUGIN ) ; updatePreferences ( uiPrefs , fUIKeys , Collections . EMPTY_MAP ) ; uiPrefs . remove ( PROFILE_KEY ) ; } public Profile getSelected ( ) { return fSelected ; } public void setSelected ( Profile profile ) { final Profile newSelected = ( Profile ) fProfiles . get ( profile . getID ( ) ) ; if ( newSelected != null && ! newSelected . equals ( fSelected ) ) { fSelected = newSelected ; notifyObservers ( SELECTION_CHANGED_EVENT ) ; } } public boolean containsName ( String name ) { for ( final Iterator iter = fProfilesByName . iterator ( ) ; iter . hasNext ( ) ; ) { Profile curr = ( Profile ) iter . next ( ) ; if ( name . equals ( curr . getName ( ) ) ) { return true ; } } return false ; } public void addProfile ( CustomProfile profile ) { profile . setManager ( this ) ; final CustomProfile oldProfile = ( CustomProfile ) fProfiles . get ( profile . getID ( ) ) ; if ( oldProfile != null ) { fProfiles . remove ( oldProfile . getID ( ) ) ; fProfilesByName . remove ( oldProfile ) ; oldProfile . setManager ( null ) ; } fProfiles . put ( profile . getID ( ) , profile ) ; fProfilesByName . add ( profile ) ; Collections . sort ( fProfilesByName ) ; fSelected = profile ; notifyObservers ( PROFILE_CREATED_EVENT ) ; } public boolean deleteSelected ( ) { if ( ! ( fSelected instanceof CustomProfile ) ) return false ; Profile removedProfile = fSelected ; int index = fProfilesByName . indexOf ( removedProfile ) ; fProfiles . remove ( removedProfile . getID ( ) ) ; fProfilesByName . remove ( removedProfile ) ; ( ( CustomProfile ) removedProfile ) . setManager ( null ) ; if ( index >= fProfilesByName . size ( ) ) index -- ; fSelected = ( Profile ) fProfilesByName . get ( index ) ; if ( ! removedProfile . isSharedProfile ( ) ) { updateProfilesWithName ( removedProfile . getID ( ) , null , false ) ; } notifyObservers ( PROFILE_DELETED_EVENT ) ; return true ; } public void profileRenamed ( CustomProfile profile , String oldID ) { fProfiles . remove ( oldID ) ; fProfiles . put ( profile . getID ( ) , profile ) ; if ( ! profile . isSharedProfile ( ) ) { updateProfilesWithName ( oldID , profile , false ) ; } Collections . sort ( fProfilesByName ) ; notifyObservers ( PROFILE_RENAMED_EVENT ) ; } public void profileReplaced ( CustomProfile oldProfile , CustomProfile newProfile ) { fProfiles . remove ( oldProfile . getID ( ) ) ; fProfiles . put ( newProfile . getID ( ) , newProfile ) ; fProfilesByName . remove ( oldProfile ) ; fProfilesByName . add ( newProfile ) ; Collections . sort ( fProfilesByName ) ; if ( ! oldProfile . isSharedProfile ( ) ) { updateProfilesWithName ( oldProfile . getID ( ) , null , false ) ; } setSelected ( newProfile ) ; notifyObservers ( PROFILE_CREATED_EVENT ) ; notifyObservers ( SELECTION_CHANGED_EVENT ) ; } public void profileChanged ( CustomProfile profile ) { if ( ! profile . isSharedProfile ( ) ) { updateProfilesWithName ( profile . getID ( ) , profile , true ) ; } notifyObservers ( SETTINGS_CHANGED_EVENT ) ; } private void updateProfilesWithName ( String oldName , Profile newProfile , boolean applySettings ) { IProject [ ] projects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; for ( int i = ; i < projects . length ; i ++ ) { IScopeContext projectScope = fPreferencesAccess . getProjectScope ( projects [ i ] ) ; IEclipsePreferences node = projectScope . getNode ( RubyUI . ID_PLUGIN ) ; String profileId = node . get ( PROFILE_KEY , null ) ; if ( oldName . equals ( profileId ) ) { if ( newProfile == null ) { node . remove ( PROFILE_KEY ) ; } else { if ( applySettings ) { writeToPreferenceStore ( newProfile , projectScope ) ; } else { node . put ( PROFILE_KEY , newProfile . getID ( ) ) ; } } } } IScopeContext instanceScope = fPreferencesAccess . getInstanceScope ( ) ; final IEclipsePreferences uiPrefs = instanceScope . getNode ( RubyUI . ID_PLUGIN ) ; if ( newProfile != null && oldName . equals ( uiPrefs . get ( PROFILE_KEY , null ) ) ) { writeToPreferenceStore ( newProfile , instanceScope ) ; } } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . Map ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . jface . text . Assert ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; public class IndentationTabPage extends ModifyDialogTabPage { private final String PREVIEW = createPreviewHeader ( FormatterMessages . IndentationTabPage_preview_header ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private RubyScriptPreview fPreview ; private String fOldTabChar = null ; public IndentationTabPage ( ModifyDialog modifyDialog , Map workingValues ) { super ( modifyDialog , workingValues ) ; } protected void doCreatePreferences ( Composite composite , int numColumns ) { final Group generalGroup = createGroup ( numColumns , composite , FormatterMessages . IndentationTabPage_general_group_title ) ; final String [ ] tabPolicyValues = new String [ ] { RubyCore . SPACE , RubyCore . TAB , DefaultCodeFormatterConstants . MIXED } ; final String [ ] tabPolicyLabels = new String [ ] { FormatterMessages . IndentationTabPage_general_group_option_tab_policy_SPACE , FormatterMessages . IndentationTabPage_general_group_option_tab_policy_TAB , FormatterMessages . IndentationTabPage_general_group_option_tab_policy_MIXED } ; final ComboPreference tabPolicy = createComboPref ( generalGroup , numColumns , FormatterMessages . IndentationTabPage_general_group_option_tab_policy , DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , tabPolicyValues , tabPolicyLabels ) ; final CheckboxPreference onlyForLeading = createCheckboxPref ( generalGroup , numColumns , FormatterMessages . IndentationTabPage_use_tabs_only_for_leading_indentations , DefaultCodeFormatterConstants . FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS , FALSE_TRUE ) ; final NumberPreference indentSize = createNumberPref ( generalGroup , numColumns , FormatterMessages . IndentationTabPage_general_group_option_indent_size , DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE , , ) ; final NumberPreference tabSize = createNumberPref ( generalGroup , numColumns , FormatterMessages . IndentationTabPage_general_group_option_tab_size , DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE , , ) ; String tabchar = ( String ) fWorkingValues . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ) ; updateTabPreferences ( tabchar , tabSize , indentSize , onlyForLeading ) ; tabPolicy . addObserver ( new Observer ( ) { public void update ( Observable o , Object arg ) { updateTabPreferences ( ( String ) arg , tabSize , indentSize , onlyForLeading ) ; } } ) ; tabSize . addObserver ( new Observer ( ) { public void update ( Observable o , Object arg ) { indentSize . updateWidget ( ) ; } } ) ; final Group classGroup = createGroup ( numColumns , composite , FormatterMessages . IndentationTabPage_indent_group_title ) ; createCheckboxPref ( classGroup , numColumns , FormatterMessages . IndentationTabPage_switch_group_option_indent_statements_within_case_body , DefaultCodeFormatterConstants . FORMATTER_INDENT_CASE_BODY , FALSE_TRUE ) ; createCheckboxPref ( classGroup , numColumns , FormatterMessages . IndentationTabPage_indent_empty_lines , DefaultCodeFormatterConstants . FORMATTER_INDENT_EMPTY_LINES , FALSE_TRUE ) ; } public void initializePage ( ) { fPreview . setPreviewText ( PREVIEW ) ; } protected RubyPreview doCreateRubyPreview ( Composite parent ) { fPreview = new RubyScriptPreview ( fWorkingValues , parent ) ; return fPreview ; } protected void doUpdatePreview ( ) { fPreview . update ( ) ; } private void updateTabPreferences ( String tabPolicy , NumberPreference tabPreference , NumberPreference indentPreference , CheckboxPreference onlyForLeading ) { if ( DefaultCodeFormatterConstants . MIXED . equals ( tabPolicy ) ) { if ( RubyCore . SPACE . equals ( fOldTabChar ) || RubyCore . TAB . equals ( fOldTabChar ) ) swapTabValues ( ) ; tabPreference . setEnabled ( true ) ; tabPreference . setKey ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) ; indentPreference . setEnabled ( true ) ; indentPreference . setKey ( DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE ) ; onlyForLeading . setEnabled ( true ) ; } else if ( RubyCore . SPACE . equals ( tabPolicy ) ) { if ( DefaultCodeFormatterConstants . MIXED . equals ( fOldTabChar ) ) swapTabValues ( ) ; tabPreference . setEnabled ( true ) ; tabPreference . setKey ( DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE ) ; indentPreference . setEnabled ( true ) ; indentPreference . setKey ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) ; onlyForLeading . setEnabled ( false ) ; } else if ( RubyCore . TAB . equals ( tabPolicy ) ) { if ( DefaultCodeFormatterConstants . MIXED . equals ( fOldTabChar ) ) swapTabValues ( ) ; tabPreference . setEnabled ( true ) ; tabPreference . setKey ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) ; indentPreference . setEnabled ( false ) ; indentPreference . setKey ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) ; onlyForLeading . setEnabled ( true ) ; } else { Assert . isTrue ( false ) ; } fOldTabChar = tabPolicy ; } private void swapTabValues ( ) { Object tabSize = fWorkingValues . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) ; Object indentSize = fWorkingValues . get ( DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE ) ; fWorkingValues . put ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE , indentSize ) ; fWorkingValues . put ( DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE , tabSize ) ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . TabFolder ; import org . eclipse . swt . widgets . TabItem ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . Profile ; import org . rubypeople . rdt . ui . RubyUI ; public class ModifyDialog extends StatusDialog { private static final String DS_KEY_PREFERRED_WIDTH = RubyUI . ID_PLUGIN + "" ; private static final String DS_KEY_PREFERRED_HEIGHT = RubyUI . ID_PLUGIN + "" ; private static final String DS_KEY_PREFERRED_X = RubyUI . ID_PLUGIN + "" ; private static final String DS_KEY_PREFERRED_Y = RubyUI . ID_PLUGIN + "" ; private static final String DS_KEY_LAST_FOCUS = RubyUI . ID_PLUGIN + "" ; private final String fTitle ; private final boolean fNewProfile ; private Profile fProfile ; private final Map fWorkingValues ; private IStatus fStandardStatus ; protected final List fTabPages ; final IDialogSettings fDialogSettings ; private TabFolder fTabFolder ; private ProfileManager fProfileManager ; private Button fApplyButton ; protected ModifyDialog ( Shell parentShell , Profile profile , ProfileManager profileManager , boolean newProfile ) { super ( parentShell ) ; fProfileManager = profileManager ; fNewProfile = newProfile ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE | SWT . MAX ) ; fProfile = profile ; if ( fProfile . isBuiltInProfile ( ) ) { fStandardStatus = new Status ( IStatus . INFO , RubyPlugin . getPluginId ( ) , IStatus . OK , FormatterMessages . ModifyDialog_dialog_show_warning_builtin , null ) ; fTitle = Messages . format ( FormatterMessages . ModifyDialog_dialog_show_title , profile . getName ( ) ) ; } else { fStandardStatus = new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; fTitle = Messages . format ( FormatterMessages . ModifyDialog_dialog_title , profile . getName ( ) ) ; } fWorkingValues = new HashMap ( fProfile . getSettings ( ) ) ; updateStatus ( fStandardStatus ) ; setStatusLineAboveButtons ( false ) ; fTabPages = new ArrayList ( ) ; fDialogSettings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; } public void create ( ) { super . create ( ) ; int lastFocusNr = ; try { lastFocusNr = fDialogSettings . getInt ( DS_KEY_LAST_FOCUS ) ; if ( lastFocusNr < ) lastFocusNr = ; if ( lastFocusNr > fTabPages . size ( ) - ) lastFocusNr = fTabPages . size ( ) - ; } catch ( NumberFormatException x ) { lastFocusNr = ; } if ( ! fNewProfile ) { fTabFolder . setSelection ( lastFocusNr ) ; ( ( ModifyDialogTabPage ) fTabFolder . getSelection ( ) [ ] . getData ( ) ) . setInitialFocus ( ) ; } } protected void configureShell ( Shell shell ) { super . configureShell ( shell ) ; shell . setText ( fTitle ) ; } protected Control createDialogArea ( Composite parent ) { final Composite composite = ( Composite ) super . createDialogArea ( parent ) ; fTabFolder = new TabFolder ( composite , SWT . NONE ) ; fTabFolder . setFont ( composite . getFont ( ) ) ; fTabFolder . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; addTabPage ( fTabFolder , FormatterMessages . ModifyDialog_tabpage_indentation_title , new IndentationTabPage ( this , fWorkingValues ) ) ; addTabPage ( fTabFolder , FormatterMessages . ModifyDialog_tabpage_comments_title , new CommentsTabPage ( this , fWorkingValues ) ) ; applyDialogFont ( composite ) ; fTabFolder . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { final TabItem tabItem = ( TabItem ) e . item ; final ModifyDialogTabPage page = ( ModifyDialogTabPage ) tabItem . getData ( ) ; fDialogSettings . put ( DS_KEY_LAST_FOCUS , fTabPages . indexOf ( page ) ) ; page . makeVisible ( ) ; } } ) ; return composite ; } public void updateStatus ( IStatus status ) { super . updateStatus ( status != null ? status : fStandardStatus ) ; } protected Point getInitialSize ( ) { Point initialSize = super . getInitialSize ( ) ; try { int lastWidth = fDialogSettings . getInt ( DS_KEY_PREFERRED_WIDTH ) ; if ( initialSize . x > lastWidth ) lastWidth = initialSize . x ; int lastHeight = fDialogSettings . getInt ( DS_KEY_PREFERRED_HEIGHT ) ; if ( initialSize . y > lastHeight ) lastHeight = initialSize . x ; return new Point ( lastWidth , lastHeight ) ; } catch ( NumberFormatException ex ) { } return initialSize ; } protected Point getInitialLocation ( Point initialSize ) { try { return new Point ( fDialogSettings . getInt ( DS_KEY_PREFERRED_X ) , fDialogSettings . getInt ( DS_KEY_PREFERRED_Y ) ) ; } catch ( NumberFormatException ex ) { return super . getInitialLocation ( initialSize ) ; } } public boolean close ( ) { final Rectangle shell = getShell ( ) . getBounds ( ) ; fDialogSettings . put ( DS_KEY_PREFERRED_WIDTH , shell . width ) ; fDialogSettings . put ( DS_KEY_PREFERRED_HEIGHT , shell . height ) ; fDialogSettings . put ( DS_KEY_PREFERRED_X , shell . x ) ; fDialogSettings . put ( DS_KEY_PREFERRED_Y , shell . y ) ; return super . close ( ) ; } protected void okPressed ( ) { applyPressed ( ) ; super . okPressed ( ) ; } protected void buttonPressed ( int buttonId ) { if ( buttonId == IDialogConstants . CLIENT_ID ) { applyPressed ( ) ; } else { super . buttonPressed ( buttonId ) ; } } private void applyPressed ( ) { if ( fProfile . isBuiltInProfile ( ) || fProfile . isSharedProfile ( ) ) { RenameProfileDialog dialog = new RenameProfileDialog ( getShell ( ) , fProfile , fProfileManager ) ; if ( dialog . open ( ) != Window . OK ) { return ; } fProfile = dialog . getRenamedProfile ( ) ; fStandardStatus = new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; updateStatus ( fStandardStatus ) ; } fProfile . setSettings ( new HashMap ( fWorkingValues ) ) ; fApplyButton . setEnabled ( false ) ; } protected void createButtonsForButtonBar ( Composite parent ) { fApplyButton = createButton ( parent , IDialogConstants . CLIENT_ID , FormatterMessages . ModifyDialog_apply_button , false ) ; fApplyButton . setEnabled ( false ) ; GridLayout layout = ( GridLayout ) parent . getLayout ( ) ; layout . numColumns ++ ; layout . makeColumnsEqualWidth = false ; Label label = new Label ( parent , SWT . NONE ) ; GridData data = new GridData ( ) ; data . widthHint = layout . horizontalSpacing ; label . setLayoutData ( data ) ; super . createButtonsForButtonBar ( parent ) ; } private final void addTabPage ( TabFolder tabFolder , String title , ModifyDialogTabPage tabPage ) { final TabItem tabItem = new TabItem ( tabFolder , SWT . NONE ) ; applyDialogFont ( tabItem . getControl ( ) ) ; tabItem . setText ( title ) ; tabItem . setData ( tabPage ) ; tabItem . setControl ( tabPage . createContents ( tabFolder ) ) ; fTabPages . add ( tabPage ) ; } public void valuesModified ( ) { if ( fApplyButton != null && ! fApplyButton . isDisposed ( ) ) { fApplyButton . setEnabled ( hasChanges ( ) ) ; } } private boolean hasChanges ( ) { Iterator iter = fProfile . getSettings ( ) . entrySet ( ) . iterator ( ) ; for ( ; iter . hasNext ( ) ; ) { Map . Entry curr = ( Map . Entry ) iter . next ( ) ; if ( ! fWorkingValues . get ( curr . getKey ( ) ) . equals ( curr . getValue ( ) ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . io . File ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . preferences . PreferencesAccess ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . CustomProfile ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . Profile ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . ui . RubyUI ; public class CodeFormatterConfigurationBlock { private static final String DIALOGSTORE_LASTLOADPATH = RubyUI . ID_PLUGIN + "" ; private static final String DIALOGSTORE_LASTSAVEPATH = RubyUI . ID_PLUGIN + "" ; private class StoreUpdater implements Observer { public StoreUpdater ( ) { fProfileManager . addObserver ( this ) ; } public void update ( Observable o , Object arg ) { final int value = ( ( Integer ) arg ) . intValue ( ) ; switch ( value ) { case ProfileManager . PROFILE_DELETED_EVENT : case ProfileManager . PROFILE_RENAMED_EVENT : case ProfileManager . PROFILE_CREATED_EVENT : case ProfileManager . SETTINGS_CHANGED_EVENT : try { ProfileStore . writeProfiles ( fProfileManager . getSortedProfiles ( ) , fInstanceScope ) ; fProfileManager . commitChanges ( fCurrContext ) ; } catch ( CoreException x ) { RubyPlugin . log ( x ) ; } break ; case ProfileManager . SELECTION_CHANGED_EVENT : fProfileManager . commitChanges ( fCurrContext ) ; break ; } } } private class ProfileComboController implements Observer , SelectionListener { private final List fSortedProfiles ; public ProfileComboController ( ) { fSortedProfiles = fProfileManager . getSortedProfiles ( ) ; fProfileCombo . addSelectionListener ( this ) ; fProfileManager . addObserver ( this ) ; updateProfiles ( ) ; updateSelection ( ) ; } public void widgetSelected ( SelectionEvent e ) { final int index = fProfileCombo . getSelectionIndex ( ) ; fProfileManager . setSelected ( ( Profile ) fSortedProfiles . get ( index ) ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } public void update ( Observable o , Object arg ) { if ( arg == null ) return ; final int value = ( ( Integer ) arg ) . intValue ( ) ; switch ( value ) { case ProfileManager . PROFILE_CREATED_EVENT : case ProfileManager . PROFILE_DELETED_EVENT : case ProfileManager . PROFILE_RENAMED_EVENT : updateProfiles ( ) ; case ProfileManager . SELECTION_CHANGED_EVENT : updateSelection ( ) ; } } private void updateProfiles ( ) { fProfileCombo . setItems ( fProfileManager . getSortedDisplayNames ( ) ) ; } private void updateSelection ( ) { fProfileCombo . setText ( fProfileManager . getSelected ( ) . getName ( ) ) ; } } private class ButtonController implements Observer , SelectionListener { public ButtonController ( ) { fProfileManager . addObserver ( this ) ; fNewButton . addSelectionListener ( this ) ; fRenameButton . addSelectionListener ( this ) ; fEditButton . addSelectionListener ( this ) ; fDeleteButton . addSelectionListener ( this ) ; fSaveButton . addSelectionListener ( this ) ; fLoadButton . addSelectionListener ( this ) ; update ( fProfileManager , null ) ; } public void update ( Observable o , Object arg ) { Profile selected = ( ( ProfileManager ) o ) . getSelected ( ) ; final boolean notBuiltIn = ! selected . isBuiltInProfile ( ) ; fEditButton . setText ( notBuiltIn ? FormatterMessages . CodingStyleConfigurationBlock_edit_button_desc : FormatterMessages . CodingStyleConfigurationBlock_show_button_desc ) ; fDeleteButton . setEnabled ( notBuiltIn ) ; fSaveButton . setEnabled ( notBuiltIn ) ; fRenameButton . setEnabled ( notBuiltIn ) ; } public void widgetSelected ( SelectionEvent e ) { final Button button = ( Button ) e . widget ; if ( button == fSaveButton ) saveButtonPressed ( ) ; else if ( button == fEditButton ) modifyButtonPressed ( ) ; else if ( button == fDeleteButton ) deleteButtonPressed ( ) ; else if ( button == fNewButton ) newButtonPressed ( ) ; else if ( button == fLoadButton ) loadButtonPressed ( ) ; else if ( button == fRenameButton ) renameButtonPressed ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } private void renameButtonPressed ( ) { if ( fProfileManager . getSelected ( ) . isBuiltInProfile ( ) ) return ; final CustomProfile profile = ( CustomProfile ) fProfileManager . getSelected ( ) ; final RenameProfileDialog renameDialog = new RenameProfileDialog ( fComposite . getShell ( ) , profile , fProfileManager ) ; if ( renameDialog . open ( ) == Window . OK ) { fProfileManager . setSelected ( renameDialog . getRenamedProfile ( ) ) ; } } private void modifyButtonPressed ( ) { final ModifyDialog modifyDialog = new ModifyDialog ( fComposite . getShell ( ) , fProfileManager . getSelected ( ) , fProfileManager , false ) ; modifyDialog . open ( ) ; } private void deleteButtonPressed ( ) { if ( MessageDialog . openQuestion ( fComposite . getShell ( ) , FormatterMessages . CodingStyleConfigurationBlock_delete_confirmation_title , Messages . format ( FormatterMessages . CodingStyleConfigurationBlock_delete_confirmation_question , fProfileManager . getSelected ( ) . getName ( ) ) ) ) { fProfileManager . deleteSelected ( ) ; } } private void newButtonPressed ( ) { final CreateProfileDialog p = new CreateProfileDialog ( fComposite . getShell ( ) , fProfileManager ) ; if ( p . open ( ) != Window . OK ) return ; if ( ! p . openEditDialog ( ) ) return ; final ModifyDialog modifyDialog = new ModifyDialog ( fComposite . getShell ( ) , p . getCreatedProfile ( ) , fProfileManager , true ) ; modifyDialog . open ( ) ; } private void saveButtonPressed ( ) { Profile selected = fProfileManager . getSelected ( ) ; if ( selected . isSharedProfile ( ) ) { final RenameProfileDialog renameDialog = new RenameProfileDialog ( fComposite . getShell ( ) , selected , fProfileManager ) ; if ( renameDialog . open ( ) != Window . OK ) { return ; } selected = renameDialog . getRenamedProfile ( ) ; fProfileManager . setSelected ( selected ) ; } final FileDialog dialog = new FileDialog ( fComposite . getShell ( ) , SWT . SAVE ) ; dialog . setText ( FormatterMessages . CodingStyleConfigurationBlock_save_profile_dialog_title ) ; dialog . setFilterExtensions ( new String [ ] { "" } ) ; final String lastPath = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( DIALOGSTORE_LASTSAVEPATH ) ; if ( lastPath != null ) { dialog . setFilterPath ( lastPath ) ; } final String path = dialog . open ( ) ; if ( path == null ) return ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( DIALOGSTORE_LASTSAVEPATH , dialog . getFilterPath ( ) ) ; final File file = new File ( path ) ; if ( file . exists ( ) && ! MessageDialog . openQuestion ( fComposite . getShell ( ) , FormatterMessages . CodingStyleConfigurationBlock_save_profile_overwrite_title , Messages . format ( FormatterMessages . CodingStyleConfigurationBlock_save_profile_overwrite_message , path ) ) ) { return ; } final Collection profiles = new ArrayList ( ) ; profiles . add ( selected ) ; try { ProfileStore . writeProfilesToFile ( profiles , file ) ; } catch ( CoreException e ) { final String title = FormatterMessages . CodingStyleConfigurationBlock_save_profile_error_title ; final String message = FormatterMessages . CodingStyleConfigurationBlock_save_profile_error_message ; ExceptionHandler . handle ( e , fComposite . getShell ( ) , title , message ) ; } } private void loadButtonPressed ( ) { final FileDialog dialog = new FileDialog ( fComposite . getShell ( ) , SWT . OPEN ) ; dialog . setText ( FormatterMessages . CodingStyleConfigurationBlock_load_profile_dialog_title ) ; dialog . setFilterExtensions ( new String [ ] { "" } ) ; final String lastPath = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( DIALOGSTORE_LASTLOADPATH ) ; if ( lastPath != null ) { dialog . setFilterPath ( lastPath ) ; } final String path = dialog . open ( ) ; if ( path == null ) return ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( DIALOGSTORE_LASTLOADPATH , dialog . getFilterPath ( ) ) ; final File file = new File ( path ) ; Collection profiles = null ; try { profiles = ProfileStore . readProfilesFromFile ( file ) ; } catch ( CoreException e ) { final String title = FormatterMessages . CodingStyleConfigurationBlock_load_profile_error_title ; final String message = FormatterMessages . CodingStyleConfigurationBlock_load_profile_error_message ; ExceptionHandler . handle ( e , fComposite . getShell ( ) , title , message ) ; } if ( profiles == null || profiles . isEmpty ( ) ) return ; final CustomProfile profile = ( CustomProfile ) profiles . iterator ( ) . next ( ) ; if ( ProfileVersioner . getVersionStatus ( profile ) > ) { final String title = FormatterMessages . CodingStyleConfigurationBlock_load_profile_error_too_new_title ; final String message = FormatterMessages . CodingStyleConfigurationBlock_load_profile_error_too_new_message ; MessageDialog . openWarning ( fComposite . getShell ( ) , title , message ) ; } if ( fProfileManager . containsName ( profile . getName ( ) ) ) { final AlreadyExistsDialog aeDialog = new AlreadyExistsDialog ( fComposite . getShell ( ) , profile , fProfileManager ) ; if ( aeDialog . open ( ) != Window . OK ) return ; } ProfileVersioner . updateAndComplete ( profile ) ; fProfileManager . addProfile ( profile ) ; } } private class PreviewController implements Observer { public PreviewController ( ) { fProfileManager . addObserver ( this ) ; fRubyPreview . setWorkingValues ( fProfileManager . getSelected ( ) . getSettings ( ) ) ; fRubyPreview . update ( ) ; } public void update ( Observable o , Object arg ) { final int value = ( ( Integer ) arg ) . intValue ( ) ; switch ( value ) { case ProfileManager . PROFILE_CREATED_EVENT : case ProfileManager . PROFILE_DELETED_EVENT : case ProfileManager . SELECTION_CHANGED_EVENT : case ProfileManager . SETTINGS_CHANGED_EVENT : fRubyPreview . setWorkingValues ( ( ( ProfileManager ) o ) . getSelected ( ) . getSettings ( ) ) ; fRubyPreview . update ( ) ; } } } private final static String PREVIEW = "" + FormatterMessages . CodingStyleConfigurationBlock_preview_title + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; protected Composite fComposite ; protected Combo fProfileCombo ; protected Button fEditButton ; protected Button fRenameButton ; protected Button fDeleteButton ; protected Button fNewButton ; protected Button fLoadButton ; protected Button fSaveButton ; protected final ProfileManager fProfileManager ; protected RubyScriptPreview fRubyPreview ; private PixelConverter fPixConv ; private IScopeContext fCurrContext ; private IScopeContext fInstanceScope ; public CodeFormatterConfigurationBlock ( IProject project , PreferencesAccess access ) { fInstanceScope = access . getInstanceScope ( ) ; List profiles = null ; try { profiles = ProfileStore . readProfiles ( fInstanceScope ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } if ( profiles == null ) profiles = new ArrayList ( ) ; if ( project != null ) { fCurrContext = access . getProjectScope ( project ) ; } else { fCurrContext = fInstanceScope ; } fProfileManager = new ProfileManager ( profiles , fCurrContext , access ) ; new StoreUpdater ( ) ; } public Composite createContents ( Composite parent ) { final int numColumns = ; fPixConv = new PixelConverter ( parent ) ; fComposite = createComposite ( parent , numColumns ) ; fProfileCombo = createProfileCombo ( fComposite , numColumns - , fPixConv . convertWidthInCharsToPixels ( ) ) ; fEditButton = createButton ( fComposite , FormatterMessages . CodingStyleConfigurationBlock_edit_button_desc , GridData . HORIZONTAL_ALIGN_BEGINNING ) ; fRenameButton = createButton ( fComposite , FormatterMessages . CodingStyleConfigurationBlock_rename_button_desc , GridData . HORIZONTAL_ALIGN_BEGINNING ) ; fDeleteButton = createButton ( fComposite , FormatterMessages . CodingStyleConfigurationBlock_remove_button_desc , GridData . HORIZONTAL_ALIGN_BEGINNING ) ; final Composite group = createComposite ( fComposite , ) ; final GridData groupData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; groupData . horizontalSpan = numColumns ; group . setLayoutData ( groupData ) ; fNewButton = createButton ( group , FormatterMessages . CodingStyleConfigurationBlock_new_button_desc , GridData . HORIZONTAL_ALIGN_BEGINNING ) ; ( ( GridData ) createLabel ( group , "" , ) . getLayoutData ( ) ) . grabExcessHorizontalSpace = true ; fLoadButton = createButton ( group , FormatterMessages . CodingStyleConfigurationBlock_load_button_desc , GridData . HORIZONTAL_ALIGN_END ) ; fSaveButton = createButton ( group , FormatterMessages . CodingStyleConfigurationBlock_save_button_desc , GridData . HORIZONTAL_ALIGN_END ) ; createLabel ( fComposite , FormatterMessages . CodingStyleConfigurationBlock_preview_label_text , numColumns ) ; configurePreview ( fComposite , numColumns ) ; new ButtonController ( ) ; new ProfileComboController ( ) ; new PreviewController ( ) ; return fComposite ; } private static Button createButton ( Composite composite , String text , final int style ) { final Button button = new Button ( composite , SWT . PUSH ) ; button . setFont ( composite . getFont ( ) ) ; button . setText ( text ) ; final GridData gd = new GridData ( style ) ; gd . widthHint = SWTUtil . getButtonWidthHint ( button ) ; button . setLayoutData ( gd ) ; return button ; } private static Combo createProfileCombo ( Composite composite , int span , int widthHint ) { final GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = span ; gd . widthHint = widthHint ; final Combo combo = new Combo ( composite , SWT . DROP_DOWN | SWT . READ_ONLY ) ; combo . setFont ( composite . getFont ( ) ) ; combo . setLayoutData ( gd ) ; return combo ; } private Label createLabel ( Composite composite , String text , int numColumns ) { final GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = numColumns ; gd . widthHint = ; final Label label = new Label ( composite , SWT . WRAP ) ; label . setFont ( composite . getFont ( ) ) ; label . setText ( text ) ; label . setLayoutData ( gd ) ; return label ; } private Composite createComposite ( Composite parent , int numColumns ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; final GridLayout layout = new GridLayout ( numColumns , false ) ; layout . marginHeight = ; layout . marginWidth = ; composite . setLayout ( layout ) ; return composite ; } private void configurePreview ( Composite composite , int numColumns ) { fRubyPreview = new RubyScriptPreview ( fProfileManager . getSelected ( ) . getSettings ( ) , composite ) ; fRubyPreview . setPreviewText ( PREVIEW ) ; final GridData gd = new GridData ( GridData . FILL_VERTICAL | GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = numColumns ; gd . verticalSpan = ; gd . widthHint = ; gd . heightHint = ; fRubyPreview . getControl ( ) . setLayoutData ( gd ) ; } public final boolean hasProjectSpecificOptions ( IProject project ) { if ( project != null ) { return ProfileManager . hasProjectSpecificSettings ( new ProjectScope ( project ) ) ; } return false ; } public boolean performOk ( ) { return true ; } public void performDefaults ( ) { Profile profile = fProfileManager . getProfile ( ProfileManager . DEFAULT_PROFILE ) ; if ( profile != null ) { int defaultIndex = fProfileManager . getSortedProfiles ( ) . indexOf ( profile ) ; if ( defaultIndex != - ) { fProfileManager . setSelected ( profile ) ; } } } public void dispose ( ) { } public void enableProjectSpecificSettings ( boolean useProjectSpecificSettings ) { if ( useProjectSpecificSettings ) { fProfileManager . commitChanges ( fCurrContext ) ; } else { fProfileManager . clearAllSettings ( fCurrContext ) ; } } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . Iterator ; import java . util . Map ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . CustomProfile ; public class ProfileVersioner { public static final int VERSION_1 = ; public static final int CURRENT_VERSION = VERSION_1 ; public static void updateAndComplete ( CustomProfile profile ) { final Map oldSettings = profile . getSettings ( ) ; Map newSettings = updateAndComplete ( oldSettings , profile . getVersion ( ) ) ; profile . setVersion ( CURRENT_VERSION ) ; profile . setSettings ( newSettings ) ; } public static Map updateAndComplete ( Map oldSettings , int version ) { final Map newSettings = ProfileManager . getDefaultSettings ( ) ; switch ( version ) { case VERSION_1 : default : for ( final Iterator iter = oldSettings . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final String key = ( String ) iter . next ( ) ; if ( ! newSettings . containsKey ( key ) ) continue ; final String value = ( String ) oldSettings . get ( key ) ; if ( value != null ) { newSettings . put ( key , value ) ; } } } return newSettings ; } public static int getVersionStatus ( CustomProfile profile ) { final int version = profile . getVersion ( ) ; if ( version < CURRENT_VERSION ) return - ; else if ( version > CURRENT_VERSION ) return ; else return ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . events . FocusAdapter ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . ui . RubyUI ; public abstract class ModifyDialogTabPage { protected final Observer fUpdater = new Observer ( ) { public void update ( Observable o , Object arg ) { doUpdatePreview ( ) ; notifyValuesModified ( ) ; } } ; protected abstract class Preference extends Observable { private final Map fPreferences ; private boolean fEnabled ; private String fKey ; public Preference ( Map preferences , String key ) { fPreferences = preferences ; fEnabled = true ; fKey = key ; } protected final Map getPreferences ( ) { return fPreferences ; } public final void setEnabled ( boolean enabled ) { fEnabled = enabled ; updateWidget ( ) ; } public final boolean getEnabled ( ) { return fEnabled ; } public final void setKey ( String key ) { if ( key == null || ! fKey . equals ( key ) ) { fKey = key ; updateWidget ( ) ; } } public final String getKey ( ) { return fKey ; } public abstract Control getControl ( ) ; protected abstract void updateWidget ( ) ; } protected final class CheckboxPreference extends Preference { private final String [ ] fValues ; private final Button fCheckbox ; public CheckboxPreference ( Composite composite , int numColumns , Map preferences , String key , String [ ] values , String text ) { super ( preferences , key ) ; if ( values == null || text == null ) throw new IllegalArgumentException ( FormatterMessages . ModifyDialogTabPage_error_msg_values_text_unassigned ) ; fValues = values ; fCheckbox = new Button ( composite , SWT . CHECK ) ; fCheckbox . setText ( text ) ; fCheckbox . setLayoutData ( createGridData ( numColumns , GridData . FILL_HORIZONTAL , SWT . DEFAULT ) ) ; fCheckbox . setFont ( composite . getFont ( ) ) ; updateWidget ( ) ; fCheckbox . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { checkboxChecked ( ( ( Button ) e . widget ) . getSelection ( ) ) ; } } ) ; } protected void checkboxChecked ( boolean state ) { getPreferences ( ) . put ( getKey ( ) , state ? fValues [ ] : fValues [ ] ) ; setChanged ( ) ; notifyObservers ( ) ; } protected void updateWidget ( ) { if ( getKey ( ) != null ) { fCheckbox . setEnabled ( getEnabled ( ) ) ; fCheckbox . setSelection ( getChecked ( ) ) ; } else { fCheckbox . setSelection ( false ) ; fCheckbox . setEnabled ( false ) ; } } public boolean getChecked ( ) { return fValues [ ] . equals ( getPreferences ( ) . get ( getKey ( ) ) ) ; } public Control getControl ( ) { return fCheckbox ; } } protected final class ComboPreference extends Preference { private final String [ ] fItems ; private final String [ ] fValues ; private final Combo fCombo ; public ComboPreference ( Composite composite , int numColumns , Map preferences , String key , String [ ] values , String text , String [ ] items ) { super ( preferences , key ) ; if ( values == null || items == null || text == null ) throw new IllegalArgumentException ( FormatterMessages . ModifyDialogTabPage_error_msg_values_items_text_unassigned ) ; fValues = values ; fItems = items ; createLabel ( numColumns - , composite , text ) ; fCombo = new Combo ( composite , SWT . SINGLE | SWT . READ_ONLY ) ; fCombo . setFont ( composite . getFont ( ) ) ; fCombo . setItems ( items ) ; int max = ; for ( int i = ; i < items . length ; i ++ ) if ( items [ i ] . length ( ) > max ) max = items [ i ] . length ( ) ; fCombo . setLayoutData ( createGridData ( , GridData . HORIZONTAL_ALIGN_FILL , fCombo . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) . x ) ) ; updateWidget ( ) ; fCombo . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { comboSelected ( ( ( Combo ) e . widget ) . getSelectionIndex ( ) ) ; } } ) ; } protected void comboSelected ( int index ) { getPreferences ( ) . put ( getKey ( ) , fValues [ index ] ) ; setChanged ( ) ; notifyObservers ( fValues [ index ] ) ; } protected void updateWidget ( ) { if ( getKey ( ) != null ) { fCombo . setEnabled ( getEnabled ( ) ) ; fCombo . setText ( getSelectedItem ( ) ) ; } else { fCombo . setText ( "" ) ; fCombo . setEnabled ( false ) ; } } public String getSelectedItem ( ) { final String selected = ( String ) getPreferences ( ) . get ( getKey ( ) ) ; for ( int i = ; i < fValues . length ; i ++ ) { if ( fValues [ i ] . equals ( selected ) ) { return fItems [ i ] ; } } return "" ; } public boolean hasValue ( String value ) { return value . equals ( getPreferences ( ) . get ( getKey ( ) ) ) ; } public Control getControl ( ) { return fCombo ; } } protected final class NumberPreference extends Preference { private final int fMinValue , fMaxValue ; private final Label fNumberLabel ; private final Text fNumberText ; protected int fSelected ; protected int fOldSelected ; public NumberPreference ( Composite composite , int numColumns , Map preferences , String key , int minValue , int maxValue , String text ) { super ( preferences , key ) ; fNumberLabel = createLabel ( numColumns - , composite , text , GridData . FILL_HORIZONTAL ) ; fNumberText = new Text ( composite , SWT . SINGLE | SWT . BORDER | SWT . RIGHT ) ; fNumberText . setFont ( composite . getFont ( ) ) ; final int length = Integer . toString ( maxValue ) . length ( ) + ; fNumberText . setLayoutData ( createGridData ( , GridData . HORIZONTAL_ALIGN_END , fPixelConverter . convertWidthInCharsToPixels ( length ) ) ) ; fMinValue = minValue ; fMaxValue = maxValue ; updateWidget ( ) ; fNumberText . addFocusListener ( new FocusListener ( ) { public void focusGained ( FocusEvent e ) { NumberPreference . this . focusGained ( ) ; } public void focusLost ( FocusEvent e ) { NumberPreference . this . focusLost ( ) ; } } ) ; fNumberText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { fieldModified ( ) ; } } ) ; } private IStatus createErrorStatus ( ) { return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , Messages . format ( FormatterMessages . ModifyDialogTabPage_NumberPreference_error_invalid_value , new String [ ] { Integer . toString ( fMinValue ) , Integer . toString ( fMaxValue ) } ) , null ) ; } protected void focusGained ( ) { fOldSelected = fSelected ; fNumberText . setSelection ( , fNumberText . getCharCount ( ) ) ; } protected void focusLost ( ) { updateStatus ( null ) ; final String input = fNumberText . getText ( ) ; if ( ! validInput ( input ) ) fSelected = fOldSelected ; else fSelected = Integer . parseInt ( input ) ; if ( fSelected != fOldSelected ) { saveSelected ( ) ; fNumberText . setText ( Integer . toString ( fSelected ) ) ; } } protected void fieldModified ( ) { final String trimInput = fNumberText . getText ( ) . trim ( ) ; final boolean valid = validInput ( trimInput ) ; updateStatus ( valid ? null : createErrorStatus ( ) ) ; if ( valid ) { final int number = Integer . parseInt ( trimInput ) ; if ( fSelected != number ) { fSelected = number ; saveSelected ( ) ; } } } private boolean validInput ( String trimInput ) { int number ; try { number = Integer . parseInt ( trimInput ) ; } catch ( NumberFormatException x ) { return false ; } if ( number < fMinValue ) return false ; if ( number > fMaxValue ) return false ; return true ; } private void saveSelected ( ) { getPreferences ( ) . put ( getKey ( ) , Integer . toString ( fSelected ) ) ; setChanged ( ) ; notifyObservers ( ) ; } protected void updateWidget ( ) { final boolean hasKey = getKey ( ) != null ; fNumberLabel . setEnabled ( hasKey && getEnabled ( ) ) ; fNumberText . setEnabled ( hasKey && getEnabled ( ) ) ; if ( hasKey ) { String s = ( String ) getPreferences ( ) . get ( getKey ( ) ) ; try { fSelected = Integer . parseInt ( s ) ; } catch ( NumberFormatException e ) { final String message = Messages . format ( FormatterMessages . ModifyDialogTabPage_NumberPreference_error_invalid_key , getKey ( ) ) ; RubyPlugin . log ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . OK , message , e ) ) ; s = "" ; } fNumberText . setText ( s ) ; } else { fNumberText . setText ( "" ) ; } } public Control getControl ( ) { return fNumberText ; } } protected final static class DefaultFocusManager extends FocusAdapter { private final static String PREF_LAST_FOCUS_INDEX = RubyUI . ID_PLUGIN + "" ; private final IDialogSettings fDialogSettings ; private final Map fItemMap ; private final List fItemList ; private int fIndex ; public DefaultFocusManager ( ) { fDialogSettings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; fItemMap = new HashMap ( ) ; fItemList = new ArrayList ( ) ; fIndex = ; } public void focusGained ( FocusEvent e ) { fDialogSettings . put ( PREF_LAST_FOCUS_INDEX , ( ( Integer ) fItemMap . get ( e . widget ) ) . intValue ( ) ) ; } public void add ( Control control ) { control . addFocusListener ( this ) ; fItemList . add ( fIndex , control ) ; fItemMap . put ( control , new Integer ( fIndex ++ ) ) ; } public void add ( Preference preference ) { final Control control = preference . getControl ( ) ; if ( control != null ) add ( control ) ; } public boolean isUsed ( ) { return fIndex != ; } public void restoreFocus ( ) { int index = ; try { index = fDialogSettings . getInt ( PREF_LAST_FOCUS_INDEX ) ; if ( ( index >= ) && ( index <= fItemList . size ( ) - ) ) { ( ( Control ) fItemList . get ( index ) ) . setFocus ( ) ; } } catch ( NumberFormatException ex ) { } } public void resetFocus ( ) { fDialogSettings . put ( PREF_LAST_FOCUS_INDEX , - ) ; } } protected final DefaultFocusManager fDefaultFocusManager ; protected static String [ ] FALSE_TRUE = { DefaultCodeFormatterConstants . FALSE , DefaultCodeFormatterConstants . TRUE } ; protected static String [ ] DO_NOT_INSERT_INSERT = { RubyCore . DO_NOT_INSERT , RubyCore . INSERT } ; protected PixelConverter fPixelConverter ; protected final Map fWorkingValues ; private final ModifyDialog fModifyDialog ; public ModifyDialogTabPage ( ModifyDialog modifyDialog , Map workingValues ) { fWorkingValues = workingValues ; fModifyDialog = modifyDialog ; fDefaultFocusManager = new DefaultFocusManager ( ) ; } public final Composite createContents ( Composite parent ) { final int numColumns = ; if ( fPixelConverter == null ) { fPixelConverter = new PixelConverter ( parent ) ; } final SashForm fSashForm = new SashForm ( parent , SWT . HORIZONTAL ) ; fSashForm . setFont ( parent . getFont ( ) ) ; final Composite settingsPane = new Composite ( fSashForm , SWT . NONE ) ; settingsPane . setFont ( fSashForm . getFont ( ) ) ; final GridLayout layout = new GridLayout ( numColumns , false ) ; layout . verticalSpacing = ( int ) ( * fPixelConverter . convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ) ; layout . horizontalSpacing = fPixelConverter . convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; layout . marginHeight = fPixelConverter . convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = fPixelConverter . convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; settingsPane . setLayout ( layout ) ; doCreatePreferences ( settingsPane , numColumns ) ; final Composite previewPane = new Composite ( fSashForm , SWT . NONE ) ; previewPane . setLayout ( createGridLayout ( numColumns , true ) ) ; previewPane . setFont ( fSashForm . getFont ( ) ) ; doCreatePreviewPane ( previewPane , numColumns ) ; initializePage ( ) ; fSashForm . setWeights ( new int [ ] { , } ) ; return fSashForm ; } protected abstract void initializePage ( ) ; protected abstract void doCreatePreferences ( Composite composite , int numColumns ) ; protected Composite doCreatePreviewPane ( Composite composite , int numColumns ) { createLabel ( numColumns , composite , FormatterMessages . ModifyDialogTabPage_preview_label_text ) ; final RubyPreview preview = doCreateRubyPreview ( composite ) ; fDefaultFocusManager . add ( preview . getControl ( ) ) ; final GridData gd = createGridData ( numColumns , GridData . FILL_BOTH , ) ; gd . widthHint = ; gd . heightHint = ; preview . getControl ( ) . setLayoutData ( gd ) ; return composite ; } protected abstract RubyPreview doCreateRubyPreview ( Composite parent ) ; final public void makeVisible ( ) { fDefaultFocusManager . resetFocus ( ) ; doUpdatePreview ( ) ; } protected abstract void doUpdatePreview ( ) ; protected void notifyValuesModified ( ) { fModifyDialog . valuesModified ( ) ; } public void setInitialFocus ( ) { if ( fDefaultFocusManager . isUsed ( ) ) { fDefaultFocusManager . restoreFocus ( ) ; } } protected void updateStatus ( IStatus status ) { fModifyDialog . updateStatus ( status ) ; } protected GridLayout createGridLayout ( int numColumns , boolean margins ) { final GridLayout layout = new GridLayout ( numColumns , false ) ; layout . verticalSpacing = fPixelConverter . convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; layout . horizontalSpacing = fPixelConverter . convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; if ( margins ) { layout . marginHeight = fPixelConverter . convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = fPixelConverter . convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; } else { layout . marginHeight = ; layout . marginWidth = ; } return layout ; } protected static GridData createGridData ( int numColumns , int style , int widthHint ) { final GridData gd = new GridData ( style ) ; gd . horizontalSpan = numColumns ; gd . widthHint = widthHint ; return gd ; } protected static Label createLabel ( int numColumns , Composite parent , String text ) { return createLabel ( numColumns , parent , text , GridData . FILL_HORIZONTAL ) ; } protected static Label createLabel ( int numColumns , Composite parent , String text , int gridDataStyle ) { final Label label = new Label ( parent , SWT . WRAP ) ; label . setFont ( parent . getFont ( ) ) ; label . setText ( text ) ; label . setLayoutData ( createGridData ( numColumns , gridDataStyle , SWT . DEFAULT ) ) ; return label ; } protected Group createGroup ( int numColumns , Composite parent , String text ) { final Group group = new Group ( parent , SWT . NONE ) ; group . setFont ( parent . getFont ( ) ) ; group . setLayoutData ( createGridData ( numColumns , GridData . FILL_HORIZONTAL , SWT . DEFAULT ) ) ; final GridLayout layout = new GridLayout ( numColumns , false ) ; layout . verticalSpacing = fPixelConverter . convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; layout . horizontalSpacing = fPixelConverter . convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; layout . marginHeight = fPixelConverter . convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; group . setLayout ( layout ) ; group . setText ( text ) ; return group ; } protected NumberPreference createNumberPref ( Composite composite , int numColumns , String name , String key , int minValue , int maxValue ) { final NumberPreference pref = new NumberPreference ( composite , numColumns , fWorkingValues , key , minValue , maxValue , name ) ; fDefaultFocusManager . add ( pref ) ; pref . addObserver ( fUpdater ) ; return pref ; } protected ComboPreference createComboPref ( Composite composite , int numColumns , String name , String key , String [ ] values , String [ ] items ) { final ComboPreference pref = new ComboPreference ( composite , numColumns , fWorkingValues , key , values , name , items ) ; fDefaultFocusManager . add ( pref ) ; pref . addObserver ( fUpdater ) ; return pref ; } protected CheckboxPreference createCheckboxPref ( Composite composite , int numColumns , String name , String key , String [ ] values ) { final CheckboxPreference pref = new CheckboxPreference ( composite , numColumns , fWorkingValues , key , values , name ) ; fDefaultFocusManager . add ( pref ) ; pref . addObserver ( fUpdater ) ; return pref ; } protected static String createPreviewHeader ( String title ) { return "" + title + "" ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . FileReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . UnsupportedEncodingException ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . parsers . SAXParser ; import javax . xml . parsers . SAXParserFactory ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . Transformer ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . osgi . service . prefs . BackingStoreException ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIException ; import org . rubypeople . rdt . internal . ui . RubyUIStatus ; import org . rubypeople . rdt . internal . ui . preferences . PreferencesAccess ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . CustomProfile ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . Profile ; import org . rubypeople . rdt . ui . RubyUI ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . xml . sax . Attributes ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; import org . xml . sax . helpers . DefaultHandler ; public class ProfileStore { private final static class ProfileDefaultHandler extends DefaultHandler { private List fProfiles ; private int fVersion ; private String fName ; private Map fSettings ; public void startElement ( String uri , String localName , String qName , Attributes attributes ) throws SAXException { if ( qName . equals ( XML_NODE_SETTING ) ) { final String key = attributes . getValue ( XML_ATTRIBUTE_ID ) ; final String value = attributes . getValue ( XML_ATTRIBUTE_VALUE ) ; fSettings . put ( key , value ) ; } else if ( qName . equals ( XML_NODE_PROFILE ) ) { fName = attributes . getValue ( XML_ATTRIBUTE_NAME ) ; fSettings = new HashMap ( ) ; } else if ( qName . equals ( XML_NODE_ROOT ) ) { fProfiles = new ArrayList ( ) ; try { fVersion = Integer . parseInt ( attributes . getValue ( XML_ATTRIBUTE_VERSION ) ) ; } catch ( NumberFormatException ex ) { throw new SAXException ( ex ) ; } } } public void endElement ( String uri , String localName , String qName ) { if ( qName . equals ( XML_NODE_PROFILE ) ) { fProfiles . add ( new CustomProfile ( fName , fSettings , fVersion ) ) ; fName = null ; fSettings = null ; } } public List getProfiles ( ) { return fProfiles ; } } private static final String PREF_FORMATTER_PROFILES = "" ; private static final String PREF_FORMATTER_PROFILES_VERSION = "" ; private final static String XML_NODE_ROOT = "" ; private final static String XML_NODE_PROFILE = "" ; private final static String XML_NODE_SETTING = "" ; private final static String XML_ATTRIBUTE_VERSION = "" ; private final static String XML_ATTRIBUTE_ID = "" ; private final static String XML_ATTRIBUTE_NAME = "" ; private final static String XML_ATTRIBUTE_VALUE = "" ; private ProfileStore ( ) { } public static List readProfiles ( IScopeContext instanceScope ) throws CoreException { List res = readProfilesFromPreferences ( PREF_FORMATTER_PROFILES , instanceScope ) ; if ( res == null ) { return readOldForCompatibility ( instanceScope ) ; } return res ; } public static void writeProfiles ( Collection profiles , IScopeContext instanceScope ) throws CoreException { ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; try { writeProfilesToStream ( profiles , stream ) ; String val ; try { val = stream . toString ( "" ) ; } catch ( UnsupportedEncodingException e ) { val = stream . toString ( ) ; } IEclipsePreferences uiPreferences = instanceScope . getNode ( RubyUI . ID_PLUGIN ) ; uiPreferences . put ( PREF_FORMATTER_PROFILES , val ) ; uiPreferences . putInt ( PREF_FORMATTER_PROFILES_VERSION , ProfileVersioner . CURRENT_VERSION ) ; } finally { try { stream . close ( ) ; } catch ( IOException e ) { } } } private static List readProfilesFromPreferences ( String key , IScopeContext instanceScope ) throws CoreException { String string = instanceScope . getNode ( RubyUI . ID_PLUGIN ) . get ( key , null ) ; if ( string != null && string . length ( ) > ) { byte [ ] bytes ; try { bytes = string . getBytes ( "" ) ; } catch ( UnsupportedEncodingException e ) { bytes = string . getBytes ( ) ; } InputStream is = new ByteArrayInputStream ( bytes ) ; try { List res = readProfilesFromStream ( new InputSource ( is ) ) ; if ( res != null ) { for ( int i = ; i < res . size ( ) ; i ++ ) { ProfileVersioner . updateAndComplete ( ( CustomProfile ) res . get ( i ) ) ; } } return res ; } finally { try { is . close ( ) ; } catch ( IOException e ) { } } } return null ; } private static List readOldForCompatibility ( IScopeContext instanceScope ) { final String STORE_FILE = "" ; File file = RubyPlugin . getDefault ( ) . getStateLocation ( ) . append ( STORE_FILE ) . toFile ( ) ; if ( ! file . exists ( ) ) return null ; try { final FileReader reader = new FileReader ( file ) ; try { List res = readProfilesFromStream ( new InputSource ( reader ) ) ; if ( res != null ) { for ( int i = ; i < res . size ( ) ; i ++ ) { ProfileVersioner . updateAndComplete ( ( CustomProfile ) res . get ( i ) ) ; } writeProfiles ( res , instanceScope ) ; } file . delete ( ) ; return res ; } finally { reader . close ( ) ; } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } return null ; } public static List readProfilesFromFile ( File file ) throws CoreException { try { final FileInputStream reader = new FileInputStream ( file ) ; try { return readProfilesFromStream ( new InputSource ( reader ) ) ; } finally { try { reader . close ( ) ; } catch ( IOException e ) { } } } catch ( IOException e ) { throw createException ( e , FormatterMessages . CodingStyleConfigurationBlock_error_reading_xml_message ) ; } } private static List readProfilesFromStream ( InputSource inputSource ) throws CoreException { final ProfileDefaultHandler handler = new ProfileDefaultHandler ( ) ; try { final SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; final SAXParser parser = factory . newSAXParser ( ) ; parser . parse ( inputSource , handler ) ; } catch ( SAXException e ) { throw createException ( e , FormatterMessages . CodingStyleConfigurationBlock_error_reading_xml_message ) ; } catch ( IOException e ) { throw createException ( e , FormatterMessages . CodingStyleConfigurationBlock_error_reading_xml_message ) ; } catch ( ParserConfigurationException e ) { throw createException ( e , FormatterMessages . CodingStyleConfigurationBlock_error_reading_xml_message ) ; } return handler . getProfiles ( ) ; } public static void writeProfilesToFile ( Collection profiles , File file ) throws CoreException { final OutputStream writer ; try { writer = new FileOutputStream ( file ) ; try { writeProfilesToStream ( profiles , writer ) ; } finally { try { writer . close ( ) ; } catch ( IOException e ) { } } } catch ( IOException e ) { throw createException ( e , FormatterMessages . CodingStyleConfigurationBlock_error_serializing_xml_message ) ; } } private static void writeProfilesToStream ( Collection profiles , OutputStream stream ) throws CoreException { try { final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; final DocumentBuilder builder = factory . newDocumentBuilder ( ) ; final Document document = builder . newDocument ( ) ; final Element rootElement = document . createElement ( XML_NODE_ROOT ) ; rootElement . setAttribute ( XML_ATTRIBUTE_VERSION , Integer . toString ( ProfileVersioner . CURRENT_VERSION ) ) ; document . appendChild ( rootElement ) ; for ( final Iterator iter = profiles . iterator ( ) ; iter . hasNext ( ) ; ) { final Profile profile = ( Profile ) iter . next ( ) ; if ( profile . isProfileToSave ( ) ) { final Element profileElement = createProfileElement ( profile , document ) ; rootElement . appendChild ( profileElement ) ; } } Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . METHOD , "" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , "" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "" ) ; transformer . transform ( new DOMSource ( document ) , new StreamResult ( stream ) ) ; } catch ( TransformerException e ) { throw createException ( e , FormatterMessages . CodingStyleConfigurationBlock_error_serializing_xml_message ) ; } catch ( ParserConfigurationException e ) { throw createException ( e , FormatterMessages . CodingStyleConfigurationBlock_error_serializing_xml_message ) ; } } private static Element createProfileElement ( Profile profile , Document document ) { final Element element = document . createElement ( XML_NODE_PROFILE ) ; element . setAttribute ( XML_ATTRIBUTE_NAME , profile . getName ( ) ) ; element . setAttribute ( XML_ATTRIBUTE_VERSION , Integer . toString ( profile . getVersion ( ) ) ) ; final Iterator keyIter = ProfileManager . getKeys ( ) . iterator ( ) ; while ( keyIter . hasNext ( ) ) { final String key = ( String ) keyIter . next ( ) ; final String value = ( String ) profile . getSettings ( ) . get ( key ) ; if ( value != null ) { final Element setting = document . createElement ( XML_NODE_SETTING ) ; setting . setAttribute ( XML_ATTRIBUTE_ID , key ) ; setting . setAttribute ( XML_ATTRIBUTE_VALUE , value ) ; element . appendChild ( setting ) ; } else { RubyPlugin . logErrorMessage ( "" + key ) ; } } return element ; } public static void checkCurrentOptionsVersion ( ) { PreferencesAccess access = PreferencesAccess . getOriginalPreferences ( ) ; IScopeContext instanceScope = access . getInstanceScope ( ) ; IEclipsePreferences uiPreferences = instanceScope . getNode ( RubyUI . ID_PLUGIN ) ; int version = uiPreferences . getInt ( PREF_FORMATTER_PROFILES_VERSION , ) ; if ( version >= ProfileVersioner . CURRENT_VERSION ) { return ; } try { List profiles = ProfileStore . readProfiles ( instanceScope ) ; if ( profiles == null ) { profiles = Collections . EMPTY_LIST ; } ProfileManager manager = new ProfileManager ( profiles , instanceScope , access ) ; if ( manager . getSelected ( ) instanceof CustomProfile ) { manager . commitChanges ( instanceScope ) ; } uiPreferences . putInt ( PREF_FORMATTER_PROFILES_VERSION , ProfileVersioner . CURRENT_VERSION ) ; savePreferences ( instanceScope ) ; IProject [ ] projects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; for ( int i = ; i < projects . length ; i ++ ) { IScopeContext scope = access . getProjectScope ( projects [ i ] ) ; if ( ProfileManager . hasProjectSpecificSettings ( scope ) ) { manager = new ProfileManager ( profiles , scope , access ) ; manager . commitChanges ( scope ) ; savePreferences ( scope ) ; } } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } catch ( BackingStoreException e ) { RubyPlugin . log ( e ) ; } } private static void savePreferences ( final IScopeContext context ) throws BackingStoreException { try { context . getNode ( RubyUI . ID_PLUGIN ) . flush ( ) ; } finally { context . getNode ( RubyCore . PLUGIN_ID ) . flush ( ) ; } } private static RubyUIException createException ( Throwable t , String message ) { return new RubyUIException ( RubyUIStatus . createError ( IStatus . ERROR , message , t ) ) ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Iterator ; import java . util . Map ; import java . util . Observable ; import java . util . Observer ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; public class CommentsTabPage extends ModifyDialogTabPage { private final static class Controller implements Observer { private final Collection fMasters ; private final Collection fSlaves ; public Controller ( Collection masters , Collection slaves ) { fMasters = masters ; fSlaves = slaves ; for ( final Iterator iter = fMasters . iterator ( ) ; iter . hasNext ( ) ; ) { ( ( CheckboxPreference ) iter . next ( ) ) . addObserver ( this ) ; } update ( null , null ) ; } public void update ( Observable o , Object arg ) { boolean enabled = true ; for ( final Iterator iter = fMasters . iterator ( ) ; iter . hasNext ( ) ; ) { enabled &= ( ( CheckboxPreference ) iter . next ( ) ) . getChecked ( ) ; } for ( final Iterator iter = fSlaves . iterator ( ) ; iter . hasNext ( ) ; ) { final Object obj = iter . next ( ) ; if ( obj instanceof Preference ) { ( ( Preference ) obj ) . setEnabled ( enabled ) ; } else if ( obj instanceof Control ) { ( ( Group ) obj ) . setEnabled ( enabled ) ; } } } } private final static String PREVIEW = createPreviewHeader ( "" ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private RubyScriptPreview fPreview ; public CommentsTabPage ( ModifyDialog modifyDialog , Map workingValues ) { super ( modifyDialog , workingValues ) ; } protected void doCreatePreferences ( Composite composite , int numColumns ) { final Group globalGroup = createGroup ( numColumns , composite , FormatterMessages . CommentsTabPage_group1_title ) ; final CheckboxPreference global = createPrefTrueFalse ( globalGroup , numColumns , FormatterMessages . CommentsTabPage_enable_comment_formatting , DefaultCodeFormatterConstants . FORMATTER_COMMENT_FORMAT ) ; final Group settingsGroup = createGroup ( numColumns , composite , FormatterMessages . CommentsTabPage_group2_title ) ; final CheckboxPreference blankComments = createPrefTrueFalse ( settingsGroup , numColumns , FormatterMessages . CommentsTabPage_clear_blank_lines , DefaultCodeFormatterConstants . FORMATTER_COMMENT_CLEAR_BLANK_LINES ) ; final Group widthGroup = createGroup ( numColumns , composite , FormatterMessages . CommentsTabPage_group3_title ) ; final NumberPreference lineWidth = createNumberPref ( widthGroup , numColumns , FormatterMessages . CommentsTabPage_line_width , DefaultCodeFormatterConstants . FORMATTER_COMMENT_LINE_LENGTH , , ) ; Collection masters , slaves ; masters = new ArrayList ( ) ; masters . add ( global ) ; slaves = new ArrayList ( ) ; slaves . add ( settingsGroup ) ; slaves . add ( blankComments ) ; slaves . add ( lineWidth ) ; new Controller ( masters , slaves ) ; masters = new ArrayList ( ) ; masters . add ( global ) ; slaves = new ArrayList ( ) ; new Controller ( masters , slaves ) ; } protected void initializePage ( ) { fPreview . setPreviewText ( PREVIEW ) ; } protected RubyPreview doCreateRubyPreview ( Composite parent ) { fPreview = new RubyScriptPreview ( fWorkingValues , parent ) ; return fPreview ; } protected void doUpdatePreview ( ) { fPreview . update ( ) ; } private CheckboxPreference createPrefTrueFalse ( Composite composite , int numColumns , String text , String key ) { return createCheckboxPref ( composite , numColumns , text , key , FALSE_TRUE ) ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import org . eclipse . osgi . util . NLS ; final class FormatterMessages extends NLS { private static final String BUNDLE_NAME = FormatterMessages . class . getName ( ) ; private FormatterMessages ( ) { } public static String WhiteSpaceTabPage_assignments ; public static String WhiteSpaceTabPage_assignments_before_assignment_operator ; public static String WhiteSpaceTabPage_assignments_after_assignment_operator ; public static String WhiteSpaceTabPage_operators ; public static String WhiteSpaceTabPage_operators_before_binary_operators ; public static String WhiteSpaceTabPage_operators_after_binary_operators ; public static String WhiteSpaceTabPage_operators_before_unary_operators ; public static String WhiteSpaceTabPage_operators_after_unary_operators ; public static String WhiteSpaceTabPage_operators_before_prefix_operators ; public static String WhiteSpaceTabPage_operators_after_prefix_operators ; public static String WhiteSpaceTabPage_operators_before_postfix_operators ; public static String WhiteSpaceTabPage_operators_after_postfix_operators ; public static String WhiteSpaceTabPage_classes ; public static String WhiteSpaceTabPage_classes_before_opening_brace_of_a_class ; public static String WhiteSpaceTabPage_classes_before_opening_brace_of_anon_class ; public static String WhiteSpaceTabPage_classes_before_comma_implements ; public static String WhiteSpaceTabPage_classes_after_comma_implements ; public static String WhiteSpaceTabPage_methods ; public static String WhiteSpaceTabPage_constructors ; public static String WhiteSpaceTabPage_fields ; public static String WhiteSpaceTabPage_fields_before_comma ; public static String WhiteSpaceTabPage_fields_after_comma ; public static String WhiteSpaceTabPage_localvars ; public static String WhiteSpaceTabPage_localvars_before_comma ; public static String WhiteSpaceTabPage_localvars_after_comma ; public static String WhiteSpaceTabPage_arrayinit ; public static String WhiteSpaceTabPage_arraydecls ; public static String WhiteSpaceTabPage_arrayelem ; public static String WhiteSpaceTabPage_arrayalloc ; public static String WhiteSpaceTabPage_calls ; public static String WhiteSpaceTabPage_calls_before_comma_in_method_args ; public static String WhiteSpaceTabPage_calls_after_comma_in_method_args ; public static String WhiteSpaceTabPage_calls_before_comma_in_alloc ; public static String WhiteSpaceTabPage_calls_after_comma_in_alloc ; public static String WhiteSpaceTabPage_calls_before_comma_in_qalloc ; public static String WhiteSpaceTabPage_calls_after_comma_in_qalloc ; public static String WhiteSpaceTabPage_statements ; public static String WhiteSpaceTabPage_blocks ; public static String WhiteSpaceTabPage_switch ; public static String WhiteSpaceTabPage_switch_before_case_colon ; public static String WhiteSpaceTabPage_switch_before_default_colon ; public static String WhiteSpaceTabPage_do ; public static String WhiteSpaceTabPage_synchronized ; public static String WhiteSpaceTabPage_try ; public static String WhiteSpaceTabPage_if ; public static String WhiteSpaceTabPage_assert ; public static String WhiteSpaceTabPage_for ; public static String WhiteSpaceTabPage_for_before_comma_init ; public static String WhiteSpaceTabPage_for_after_comma_init ; public static String WhiteSpaceTabPage_for_before_comma_inc ; public static String WhiteSpaceTabPage_for_after_comma_inc ; public static String WhiteSpaceTabPage_labels ; public static String WhiteSpaceTabPage_annotations ; public static String WhiteSpaceTabPage_annotation_types ; public static String WhiteSpaceTabPage_enums ; public static String WhiteSpaceTabPage_wildcardtype ; public static String WhiteSpaceTabPage_param_type_ref ; public static String WhiteSpaceTabPage_type_arguments ; public static String WhiteSpaceTabPage_type_parameters ; public static String WhiteSpaceTabPage_conditionals ; public static String WhiteSpaceTabPage_typecasts ; public static String WhiteSpaceTabPage_parenexpr ; public static String WhiteSpaceTabPage_declarations ; public static String WhiteSpaceTabPage_expressions ; public static String WhiteSpaceTabPage_arrays ; public static String WhiteSpaceTabPage_parameterized_types ; public static String WhiteSpaceTabPage_after_opening_brace ; public static String WhiteSpaceTabPage_after_closing_brace ; public static String WhiteSpaceTabPage_before_opening_brace ; public static String WhiteSpaceTabPage_before_closing_brace ; public static String WhiteSpaceTabPage_between_empty_braces ; public static String WhiteSpaceTabPage_after_opening_paren ; public static String WhiteSpaceTabPage_after_closing_paren ; public static String WhiteSpaceTabPage_before_opening_paren ; public static String WhiteSpaceTabPage_before_closing_paren ; public static String WhiteSpaceTabPage_between_empty_parens ; public static String WhiteSpaceTabPage_after_opening_bracket ; public static String WhiteSpaceTabPage_before_opening_bracket ; public static String WhiteSpaceTabPage_before_closing_bracket ; public static String WhiteSpaceTabPage_between_empty_brackets ; public static String WhiteSpaceTabPage_before_comma_in_params ; public static String WhiteSpaceTabPage_after_comma_in_params ; public static String WhiteSpaceTabPage_before_comma_in_throws ; public static String WhiteSpaceTabPage_after_comma_in_throws ; public static String WhiteSpaceTabPage_before_ellipsis ; public static String WhiteSpaceTabPage_after_ellipsis ; public static String WhiteSpaceTabPage_before_comma ; public static String WhiteSpaceTabPage_after_comma ; public static String WhiteSpaceTabPage_after_semicolon ; public static String WhiteSpaceTabPage_before_semicolon ; public static String WhiteSpaceTabPage_before_colon ; public static String WhiteSpaceTabPage_after_colon ; public static String WhiteSpaceTabPage_before_question ; public static String WhiteSpaceTabPage_after_question ; public static String WhiteSpaceTabPage_before_at ; public static String WhiteSpaceTabPage_after_at ; public static String WhiteSpaceTabPage_after_opening_angle_bracket ; public static String WhiteSpaceTabPage_after_closing_angle_bracket ; public static String WhiteSpaceTabPage_before_opening_angle_bracket ; public static String WhiteSpaceTabPage_before_closing_angle_bracket ; public static String WhiteSpaceTabPage_before_and_list ; public static String WhiteSpaceTabPage_after_and_list ; public static String WhiteSpaceTabPage_enum_decl_before_opening_brace ; public static String WhiteSpaceTabPage_enum_decl_before_comma ; public static String WhiteSpaceTabPage_enum_decl_after_comma ; public static String WhiteSpaceTabPage_enum_const_arg_before_opening_paren ; public static String WhiteSpaceTabPage_enum_const_arg_after_opening_paren ; public static String WhiteSpaceTabPage_enum_const_arg_between_empty_parens ; public static String WhiteSpaceTabPage_enum_const_arg_before_comma ; public static String WhiteSpaceTabPage_enum_const_arg_after_comma ; public static String WhiteSpaceTabPage_enum_const_arg_before_closing_paren ; public static String WhiteSpaceTabPage_enum_const_before_opening_brace ; public static String WhiteSpaceTabPage_annot_type_method_before_opening_paren ; public static String WhiteSpaceTabPage_annot_type_method_between_empty_parens ; public static String WhiteSpaceTabPage_before_parenthesized_expressions ; public static String WhiteSpaceTabPage_insert_space ; public static String WhiteSpaceOptions_return ; public static String WhiteSpaceOptions_before ; public static String WhiteSpaceOptions_after ; public static String WhiteSpaceOptions_operator ; public static String WhiteSpaceOptions_assignment_operator ; public static String WhiteSpaceOptions_binary_operator ; public static String WhiteSpaceOptions_unary_operator ; public static String WhiteSpaceOptions_prefix_operator ; public static String WhiteSpaceOptions_postfix_operator ; public static String WhiteSpaceOptions_opening_paren ; public static String WhiteSpaceOptions_catch ; public static String WhiteSpaceOptions_for ; public static String WhiteSpaceOptions_if ; public static String WhiteSpaceOptions_switch ; public static String WhiteSpaceOptions_synchronized ; public static String WhiteSpaceOptions_while ; public static String WhiteSpaceOptions_assert ; public static String WhiteSpaceOptions_member_function_declaration ; public static String WhiteSpaceOptions_constructor ; public static String WhiteSpaceOptions_method ; public static String WhiteSpaceOptions_method_call ; public static String WhiteSpaceOptions_paren_expr ; public static String WhiteSpaceOptions_enum_constant_body ; public static String WhiteSpaceOptions_enum_constant_arguments ; public static String WhiteSpaceOptions_enum_declaration ; public static String WhiteSpaceOptions_annotation_modifier ; public static String WhiteSpaceOptions_annotation_modifier_args ; public static String WhiteSpaceOptions_annotation_type_member ; public static String WhiteSpaceOptions_annotation_type ; public static String WhiteSpaceOptions_type_cast ; public static String WhiteSpaceOptions_parameterized_type ; public static String WhiteSpaceOptions_type_arguments ; public static String WhiteSpaceOptions_type_parameters ; public static String WhiteSpaceOptions_vararg_parameter ; public static String WhiteSpaceOptions_closing_paren ; public static String WhiteSpaceOptions_opening_brace ; public static String WhiteSpaceOptions_closing_brace ; public static String WhiteSpaceOptions_opening_bracket ; public static String WhiteSpaceOptions_closing_bracket ; public static String WhiteSpaceOptions_class_decl ; public static String WhiteSpaceOptions_anon_class_decl ; public static String WhiteSpaceOptions_initializer ; public static String WhiteSpaceOptions_block ; public static String WhiteSpaceOptions_array_decl ; public static String WhiteSpaceOptions_array_element_access ; public static String WhiteSpaceOptions_array_alloc ; public static String WhiteSpaceOptions_array_init ; public static String WhiteSpaceOptions_arguments ; public static String WhiteSpaceOptions_initialization ; public static String WhiteSpaceOptions_incrementation ; public static String WhiteSpaceOptions_parameters ; public static String WhiteSpaceOptions_explicit_constructor_call ; public static String WhiteSpaceOptions_alloc_expr ; public static String WhiteSpaceOptions_throws ; public static String WhiteSpaceOptions_mult_decls ; public static String WhiteSpaceOptions_local_vars ; public static String WhiteSpaceOptions_fields ; public static String WhiteSpaceOptions_implements_clause ; public static String WhiteSpaceOptions_colon ; public static String WhiteSpaceOptions_conditional ; public static String WhiteSpaceOptions_wildcard ; public static String WhiteSpaceOptions_label ; public static String WhiteSpaceOptions_comma ; public static String WhiteSpaceOptions_semicolon ; public static String WhiteSpaceOptions_question_mark ; public static String WhiteSpaceOptions_between_empty_parens ; public static String WhiteSpaceOptions_between_empty_braces ; public static String WhiteSpaceOptions_between_empty_brackets ; public static String WhiteSpaceOptions_constructor_decl ; public static String WhiteSpaceOptions_method_decl ; public static String WhiteSpaceOptions_case ; public static String WhiteSpaceOptions_default ; public static String WhiteSpaceOptions_statements ; public static String WhiteSpaceOptions_before_opening_paren ; public static String WhiteSpaceOptions_after_opening_paren ; public static String WhiteSpaceOptions_before_closing_paren ; public static String WhiteSpaceOptions_after_closing_paren ; public static String WhiteSpaceOptions_before_opening_brace ; public static String WhiteSpaceOptions_after_opening_brace ; public static String WhiteSpaceOptions_after_closing_brace ; public static String WhiteSpaceOptions_before_closing_brace ; public static String WhiteSpaceOptions_before_opening_bracket ; public static String WhiteSpaceOptions_after_opening_bracket ; public static String WhiteSpaceOptions_before_closing_bracket ; public static String WhiteSpaceOptions_before_opening_angle_bracket ; public static String WhiteSpaceOptions_after_opening_angle_bracket ; public static String WhiteSpaceOptions_before_closing_angle_bracket ; public static String WhiteSpaceOptions_after_closing_angle_bracket ; public static String WhiteSpaceOptions_before_operator ; public static String WhiteSpaceOptions_after_operator ; public static String WhiteSpaceOptions_before_comma ; public static String WhiteSpaceOptions_after_comma ; public static String WhiteSpaceOptions_after_colon ; public static String WhiteSpaceOptions_before_colon ; public static String WhiteSpaceOptions_before_semicolon ; public static String WhiteSpaceOptions_after_semicolon ; public static String WhiteSpaceOptions_before_question_mark ; public static String WhiteSpaceOptions_after_question_mark ; public static String WhiteSpaceOptions_before_at ; public static String WhiteSpaceOptions_after_at ; public static String WhiteSpaceOptions_before_and ; public static String WhiteSpaceOptions_after_and ; public static String WhiteSpaceOptions_before_ellipsis ; public static String WhiteSpaceOptions_after_ellipsis ; public static String WhiteSpaceOptions_return_with_parenthesized_expression ; public static String LineWrappingTabPage_compact_if_else ; public static String LineWrappingTabPage_extends_clause ; public static String LineWrappingTabPage_enum_constant_arguments ; public static String LineWrappingTabPage_enum_constants ; public static String LineWrappingTabPage_implements_clause ; public static String LineWrappingTabPage_parameters ; public static String LineWrappingTabPage_arguments ; public static String LineWrappingTabPage_qualified_invocations ; public static String LineWrappingTabPage_throws_clause ; public static String LineWrappingTabPage_object_allocation ; public static String LineWrappingTabPage_qualified_object_allocation ; public static String LineWrappingTabPage_array_init ; public static String LineWrappingTabPage_explicit_constructor_invocations ; public static String LineWrappingTabPage_conditionals ; public static String LineWrappingTabPage_binary_exprs ; public static String LineWrappingTabPage_indentation_default ; public static String LineWrappingTabPage_indentation_on_column ; public static String LineWrappingTabPage_indentation_by_one ; public static String LineWrappingTabPage_class_decls ; public static String LineWrappingTabPage_method_decls ; public static String LineWrappingTabPage_constructor_decls ; public static String LineWrappingTabPage_function_calls ; public static String LineWrappingTabPage_expressions ; public static String LineWrappingTabPage_statements ; public static String LineWrappingTabPage_enum_decls ; public static String LineWrappingTabPage_wrapping_policy_label_text ; public static String LineWrappingTabPage_indentation_policy_label_text ; public static String LineWrappingTabPage_force_split_checkbox_text ; public static String LineWrappingTabPage_force_split_checkbox_multi_text ; public static String LineWrappingTabPage_line_width_for_preview_label_text ; public static String LineWrappingTabPage_group ; public static String LineWrappingTabPage_multi_group ; public static String LineWrappingTabPage_multiple_selections ; public static String LineWrappingTabPage_occurences ; public static String LineWrappingTabPage_splitting_do_not_split ; public static String LineWrappingTabPage_splitting_wrap_when_necessary ; public static String LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary ; public static String LineWrappingTabPage_splitting_wrap_always ; public static String LineWrappingTabPage_splitting_wrap_always_indent_all_but_first ; public static String LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary ; public static String LineWrappingTabPage_width_indent ; public static String LineWrappingTabPage_width_indent_option_max_line_width ; public static String LineWrappingTabPage_width_indent_option_default_indent_wrapped ; public static String LineWrappingTabPage_width_indent_option_default_indent_array ; public static String LineWrappingTabPage_error_invalid_value ; public static String LineWrappingTabPage_enum_superinterfaces ; public static String LineWrappingTabPage_assignment_alignment ; public static String AlreadyExistsDialog_message_profile_already_exists ; public static String AlreadyExistsDialog_message_profile_name_empty ; public static String AlreadyExistsDialog_dialog_title ; public static String AlreadyExistsDialog_dialog_label ; public static String AlreadyExistsDialog_rename_radio_button_desc ; public static String AlreadyExistsDialog_overwrite_radio_button_desc ; public static String BlankLinesTabPage_preview_header ; public static String BlankLinesTabPage_compilation_unit_group_title ; public static String BlankLinesTabPage_compilation_unit_option_before_package ; public static String BlankLinesTabPage_compilation_unit_option_after_package ; public static String BlankLinesTabPage_compilation_unit_option_before_import ; public static String BlankLinesTabPage_compilation_unit_option_after_import ; public static String BlankLinesTabPage_compilation_unit_option_between_type_declarations ; public static String BlankLinesTabPage_class_group_title ; public static String BlankLinesTabPage_class_option_before_first_decl ; public static String BlankLinesTabPage_class_option_before_decls_of_same_kind ; public static String BlankLinesTabPage_class_option_before_member_class_decls ; public static String BlankLinesTabPage_class_option_before_field_decls ; public static String BlankLinesTabPage_class_option_before_method_decls ; public static String BlankLinesTabPage_class_option_at_beginning_of_method_body ; public static String BlankLinesTabPage_blank_lines_group_title ; public static String BlankLinesTabPage_blank_lines_option_empty_lines_to_preserve ; public static String BracesTabPage_preview_header ; public static String BracesTabPage_position_same_line ; public static String BracesTabPage_position_next_line ; public static String BracesTabPage_position_next_line_indented ; public static String BracesTabPage_position_next_line_on_wrap ; public static String BracesTabPage_group_brace_positions_title ; public static String BracesTabPage_option_class_declaration ; public static String BracesTabPage_option_anonymous_class_declaration ; public static String BracesTabPage_option_method_declaration ; public static String BracesTabPage_option_constructor_declaration ; public static String BracesTabPage_option_blocks ; public static String BracesTabPage_option_blocks_in_case ; public static String BracesTabPage_option_switch_case ; public static String BracesTabPage_option_array_initializer ; public static String BracesTabPage_option_keep_empty_array_initializer_on_one_line ; public static String BracesTabPage_option_enum_declaration ; public static String BracesTabPage_option_enumconst_declaration ; public static String BracesTabPage_option_annotation_type_declaration ; public static String CodingStyleConfigurationBlock_save_profile_dialog_title ; public static String CodingStyleConfigurationBlock_save_profile_error_title ; public static String CodingStyleConfigurationBlock_save_profile_error_message ; public static String CodingStyleConfigurationBlock_load_profile_dialog_title ; public static String CodingStyleConfigurationBlock_load_profile_error_title ; public static String CodingStyleConfigurationBlock_load_profile_error_message ; public static String CodingStyleConfigurationBlock_load_profile_error_too_new_title ; public static String CodingStyleConfigurationBlock_load_profile_error_too_new_message ; public static String CodingStyleConfigurationBlock_preview_title ; public static String CodingStyleConfigurationBlock_save_profile_overwrite_title ; public static String CodingStyleConfigurationBlock_save_profile_overwrite_message ; public static String CodingStyleConfigurationBlock_edit_button_desc ; public static String CodingStyleConfigurationBlock_show_button_desc ; public static String CodingStyleConfigurationBlock_rename_button_desc ; public static String CodingStyleConfigurationBlock_remove_button_desc ; public static String CodingStyleConfigurationBlock_new_button_desc ; public static String CodingStyleConfigurationBlock_load_button_desc ; public static String CodingStyleConfigurationBlock_save_button_desc ; public static String CodingStyleConfigurationBlock_preview_label_text ; public static String CodingStyleConfigurationBlock_error_reading_xml_message ; public static String CodingStyleConfigurationBlock_error_serializing_xml_message ; public static String CodingStyleConfigurationBlock_delete_confirmation_title ; public static String CodingStyleConfigurationBlock_delete_confirmation_question ; public static String CommentsTabPage_group1_title ; public static String CommentsTabPage_enable_comment_formatting ; public static String CommentsTabPage_format_header ; public static String CommentsTabPage_format_html ; public static String CommentsTabPage_format_code_snippets ; public static String CommentsTabPage_group2_title ; public static String CommentsTabPage_clear_blank_lines ; public static String CommentsTabPage_blank_line_before_javadoc_tags ; public static String CommentsTabPage_indent_javadoc_tags ; public static String CommentsTabPage_indent_description_after_param ; public static String CommentsTabPage_new_line_after_param_tags ; public static String CommentsTabPage_group3_title ; public static String CommentsTabPage_line_width ; public static String ControlStatementsTabPage_preview_header ; public static String ControlStatementsTabPage_general_group_title ; public static String ControlStatementsTabPage_general_group_insert_new_line_before_else_statements ; public static String ControlStatementsTabPage_general_group_insert_new_line_before_catch_statements ; public static String ControlStatementsTabPage_general_group_insert_new_line_before_finally_statements ; public static String ControlStatementsTabPage_general_group_insert_new_line_before_while_in_do_statements ; public static String ControlStatementsTabPage_if_else_group_title ; public static String ControlStatementsTabPage_if_else_group_keep_then_on_same_line ; public static String ControlStatementsTabPage_if_else_group_keep_simple_if_on_one_line ; public static String ControlStatementsTabPage_if_else_group_keep_else_on_same_line ; public static String ControlStatementsTabPage_if_else_group_keep_else_if_on_one_line ; public static String ControlStatementsTabPage_if_else_group_keep_guardian_clause_on_one_line ; public static String CreateProfileDialog_status_message_profile_with_this_name_already_exists ; public static String CreateProfileDialog_status_message_profile_name_is_empty ; public static String CreateProfileDialog_dialog_title ; public static String CreateProfileDialog_profile_name_label_text ; public static String CreateProfileDialog_base_profile_label_text ; public static String CreateProfileDialog_open_edit_dialog_checkbox_text ; public static String IndentationTabPage_preview_header ; public static String IndentationTabPage_general_group_title ; public static String IndentationTabPage_general_group_option_tab_policy ; public static String IndentationTabPage_general_group_option_tab_policy_SPACE ; public static String IndentationTabPage_general_group_option_tab_policy_TAB ; public static String IndentationTabPage_general_group_option_tab_policy_MIXED ; public static String IndentationTabPage_general_group_option_tab_size ; public static String IndentationTabPage_general_group_option_indent_size ; public static String IndentationTabPage_indent_group_title ; public static String IndentationTabPage_class_group_option_indent_declarations_within_class_body ; public static String IndentationTabPage_class_group_option_indent_declarations_within_enum_const ; public static String IndentationTabPage_class_group_option_indent_declarations_within_enum_decl ; public static String IndentationTabPage_block_group_option_indent_statements_compare_to_body ; public static String IndentationTabPage_block_group_option_indent_statements_compare_to_block ; public static String IndentationTabPage_switch_group_option_indent_statements_within_switch_body ; public static String IndentationTabPage_switch_group_option_indent_statements_within_case_body ; public static String IndentationTabPage_switch_group_option_indent_break_statements ; public static String IndentationTabPage_indent_empty_lines ; public static String IndentationTabPage_use_tabs_only_for_leading_indentations ; public static String ModifyDialog_dialog_title ; public static String ModifyDialog_apply_button ; public static String ModifyDialog_dialog_show_title ; public static String ModifyDialog_dialog_show_warning_builtin ; public static String ModifyDialog_tabpage_braces_title ; public static String ModifyDialog_tabpage_indentation_title ; public static String ModifyDialog_tabpage_whitespace_title ; public static String ModifyDialog_tabpage_blank_lines_title ; public static String ModifyDialog_tabpage_new_lines_title ; public static String ModifyDialog_tabpage_control_statements_title ; public static String ModifyDialog_tabpage_line_wrapping_title ; public static String ModifyDialog_tabpage_comments_title ; public static String ModifyDialogTabPage_preview_label_text ; public static String NewLinesTabPage_preview_header ; public static String NewLinesTabPage_newlines_group_title ; public static String NewLinesTabPage_newlines_group_option_empty_class_body ; public static String NewLinesTabPage_newlines_group_option_empty_anonymous_class_body ; public static String NewLinesTabPage_newlines_group_option_empty_enum_declaration ; public static String NewLinesTabPage_newlines_group_option_empty_enum_constant ; public static String NewLinesTabPage_newlines_group_option_empty_method_body ; public static String NewLinesTabPage_newlines_group_option_empty_block ; public static String NewLinesTabPage_newlines_group_option_empty_end_of_file ; public static String NewLinesTabPage_empty_statement_group_title ; public static String NewLinesTabPage_emtpy_statement_group_option_empty_statement_on_new_line ; public static String NewLinesTabPage_arrayInitializer_group_title ; public static String NewLinesTabPage_array_group_option_after_opening_brace_of_array_initializer ; public static String NewLinesTabPage_array_group_option_before_closing_brace_of_array_initializer ; public static String NewLinesTabPage_annotations_group_title ; public static String NewLinesTabPage_annotations_group_option_after_annotation ; public static String ProfileManager_eclipse_profile_name ; public static String ProfileManager_ruby_conventions_profile_name ; public static String ProfileManager_unmanaged_profile ; public static String ProfileManager_unmanaged_profile_with_name ; public static String RenameProfileDialog_status_message_profile_with_this_name_already_exists ; public static String RenameProfileDialog_status_message_profile_name_empty ; public static String RenameProfileDialog_dialog_title ; public static String RenameProfileDialog_dialog_label_enter_a_new_name ; public static String ModifyDialogTabPage_error_msg_values_text_unassigned ; public static String ModifyDialogTabPage_error_msg_values_items_text_unassigned ; public static String ModifyDialogTabPage_NumberPreference_error_invalid_key ; public static String ModifyDialogTabPage_NumberPreference_error_invalid_value ; public static String RubyPreview_formatter_exception ; public static String WhiteSpaceTabPage_sort_by_java_element ; public static String WhiteSpaceTabPage_sort_by_syntax_element ; static { NLS . initializeMessages ( BUNDLE_NAME , FormatterMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . CustomProfile ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . Profile ; import org . rubypeople . rdt . ui . RubyUI ; public class CreateProfileDialog extends StatusDialog { private static final String PREF_OPEN_EDIT_DIALOG = RubyUI . ID_PLUGIN + "" ; private Text fNameText ; private Combo fProfileCombo ; private Button fEditCheckbox ; private final static StatusInfo fOk = new StatusInfo ( ) ; private final static StatusInfo fEmpty = new StatusInfo ( IStatus . ERROR , FormatterMessages . CreateProfileDialog_status_message_profile_name_is_empty ) ; private final static StatusInfo fDuplicate = new StatusInfo ( IStatus . ERROR , FormatterMessages . CreateProfileDialog_status_message_profile_with_this_name_already_exists ) ; private final ProfileManager fProfileManager ; private final List fSortedProfiles ; private final String [ ] fSortedNames ; private CustomProfile fCreatedProfile ; protected boolean fOpenEditDialog ; public CreateProfileDialog ( Shell parentShell , ProfileManager profileManager ) { super ( parentShell ) ; fProfileManager = profileManager ; fSortedProfiles = fProfileManager . getSortedProfiles ( ) ; fSortedNames = fProfileManager . getSortedDisplayNames ( ) ; } public void create ( ) { super . create ( ) ; setTitle ( FormatterMessages . CreateProfileDialog_dialog_title ) ; } public Control createDialogArea ( Composite parent ) { final int numColumns = ; GridData gd ; final GridLayout layout = new GridLayout ( numColumns , false ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . verticalSpacing = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; final Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( layout ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = numColumns ; gd . widthHint = convertWidthInCharsToPixels ( ) ; final Label nameLabel = new Label ( composite , SWT . WRAP ) ; nameLabel . setText ( FormatterMessages . CreateProfileDialog_profile_name_label_text ) ; nameLabel . setLayoutData ( gd ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = numColumns ; fNameText = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; fNameText . setLayoutData ( gd ) ; fNameText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { doValidation ( ) ; } } ) ; gd = new GridData ( ) ; gd . horizontalSpan = numColumns ; Label profileLabel = new Label ( composite , SWT . WRAP ) ; profileLabel . setText ( FormatterMessages . CreateProfileDialog_base_profile_label_text ) ; profileLabel . setLayoutData ( gd ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = numColumns ; fProfileCombo = new Combo ( composite , SWT . DROP_DOWN | SWT . READ_ONLY ) ; fProfileCombo . setLayoutData ( gd ) ; gd = new GridData ( ) ; gd . horizontalSpan = numColumns ; fEditCheckbox = new Button ( composite , SWT . CHECK ) ; fEditCheckbox . setText ( FormatterMessages . CreateProfileDialog_open_edit_dialog_checkbox_text ) ; fEditCheckbox . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { fOpenEditDialog = ( ( Button ) e . widget ) . getSelection ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; final IDialogSettings dialogSettings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; if ( dialogSettings . get ( PREF_OPEN_EDIT_DIALOG ) != null ) { fOpenEditDialog = dialogSettings . getBoolean ( PREF_OPEN_EDIT_DIALOG ) ; } else { fOpenEditDialog = true ; } fEditCheckbox . setSelection ( fOpenEditDialog ) ; fProfileCombo . setItems ( fSortedNames ) ; fProfileCombo . setText ( fProfileManager . getProfile ( ProfileManager . DEFAULT_PROFILE ) . getName ( ) ) ; updateStatus ( fEmpty ) ; applyDialogFont ( composite ) ; fNameText . setFocus ( ) ; return composite ; } protected void doValidation ( ) { final String name = fNameText . getText ( ) . trim ( ) ; if ( fProfileManager . containsName ( name ) ) { updateStatus ( fDuplicate ) ; return ; } if ( name . length ( ) == ) { updateStatus ( fEmpty ) ; return ; } updateStatus ( fOk ) ; } protected void okPressed ( ) { if ( ! getStatus ( ) . isOK ( ) ) return ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( PREF_OPEN_EDIT_DIALOG , fOpenEditDialog ) ; final Map baseSettings = new HashMap ( ( ( Profile ) fSortedProfiles . get ( fProfileCombo . getSelectionIndex ( ) ) ) . getSettings ( ) ) ; final String profileName = fNameText . getText ( ) ; fCreatedProfile = new CustomProfile ( profileName , baseSettings , ProfileVersioner . CURRENT_VERSION ) ; fProfileManager . addProfile ( fCreatedProfile ) ; super . okPressed ( ) ; } public final CustomProfile getCreatedProfile ( ) { return fCreatedProfile ; } public final boolean openEditDialog ( ) { return fOpenEditDialog ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . Profile ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . SharedProfile ; public class RenameProfileDialog extends StatusDialog { private Label fNameLabel ; private Text fNameText ; private final StatusInfo fOk ; private final StatusInfo fEmpty ; private final StatusInfo fDuplicate ; private final StatusInfo fNoMessage ; private final Profile fProfile ; private final ProfileManager fManager ; private Profile fRenamedProfile ; public RenameProfileDialog ( Shell parentShell , Profile profile , ProfileManager manager ) { super ( parentShell ) ; fManager = manager ; setTitle ( FormatterMessages . RenameProfileDialog_dialog_title ) ; fProfile = profile ; fOk = new StatusInfo ( ) ; fDuplicate = new StatusInfo ( IStatus . ERROR , FormatterMessages . RenameProfileDialog_status_message_profile_with_this_name_already_exists ) ; fEmpty = new StatusInfo ( IStatus . ERROR , FormatterMessages . RenameProfileDialog_status_message_profile_name_empty ) ; fNoMessage = new StatusInfo ( IStatus . ERROR , new String ( ) ) ; } public Control createDialogArea ( Composite parent ) { final int numColumns = ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . verticalSpacing = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; layout . numColumns = numColumns ; final Composite composite = new Composite ( parent , SWT . NULL ) ; composite . setLayout ( layout ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = numColumns ; gd . widthHint = convertWidthInCharsToPixels ( ) ; fNameLabel = new Label ( composite , SWT . NONE ) ; fNameLabel . setText ( FormatterMessages . RenameProfileDialog_dialog_label_enter_a_new_name ) ; fNameLabel . setLayoutData ( gd ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = numColumns ; fNameText = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; if ( fProfile instanceof SharedProfile ) { fNameText . setText ( fProfile . getName ( ) ) ; } fNameText . setSelection ( , fProfile . getName ( ) . length ( ) ) ; fNameText . setLayoutData ( gd ) ; fNameText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { doValidation ( ) ; } } ) ; fNameText . setText ( fProfile . getName ( ) ) ; fNameText . selectAll ( ) ; applyDialogFont ( composite ) ; return composite ; } protected void doValidation ( ) { final String name = fNameText . getText ( ) . trim ( ) ; if ( name . length ( ) == ) { updateStatus ( fEmpty ) ; return ; } if ( name . equals ( fProfile . getName ( ) ) ) { updateStatus ( fNoMessage ) ; return ; } if ( fManager . containsName ( name ) ) { updateStatus ( fDuplicate ) ; return ; } updateStatus ( fOk ) ; } public Profile getRenamedProfile ( ) { return fRenamedProfile ; } protected void okPressed ( ) { if ( ! getStatus ( ) . isOK ( ) ) return ; fRenamedProfile = fProfile . rename ( fNameText . getText ( ) , fManager ) ; super . okPressed ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . Map ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . MarginPainter ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . texteditor . AbstractDecoratedTextEditorPreferenceConstants ; import org . eclipse . ui . texteditor . ChainedPreferenceStore ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubySourceViewer ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . SimpleRubySourceViewerConfiguration ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public abstract class RubyPreview { private final class RubySourcePreviewerUpdater { final IPropertyChangeListener fontListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( PreferenceConstants . EDITOR_TEXT_FONT ) ) { final Font font = JFaceResources . getFont ( PreferenceConstants . EDITOR_TEXT_FONT ) ; fSourceViewer . getTextWidget ( ) . setFont ( font ) ; if ( fMarginPainter != null ) { fMarginPainter . initialize ( ) ; } } } } ; final IPropertyChangeListener propertyListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { if ( fViewerConfiguration . affectsTextPresentation ( event ) ) { fViewerConfiguration . handlePropertyChangeEvent ( event ) ; fSourceViewer . invalidateTextPresentation ( ) ; } } } ; public RubySourcePreviewerUpdater ( ) { JFaceResources . getFontRegistry ( ) . addListener ( fontListener ) ; fPreferenceStore . addPropertyChangeListener ( propertyListener ) ; fSourceViewer . getTextWidget ( ) . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { JFaceResources . getFontRegistry ( ) . removeListener ( fontListener ) ; fPreferenceStore . removePropertyChangeListener ( propertyListener ) ; } } ) ; } } protected final SimpleRubySourceViewerConfiguration fViewerConfiguration ; protected final Document fPreviewDocument ; protected final SourceViewer fSourceViewer ; protected final IPreferenceStore fPreferenceStore ; protected final MarginPainter fMarginPainter ; protected Map fWorkingValues ; private int fTabSize = ; public RubyPreview ( Map workingValues , Composite parent ) { RubyTextTools tools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; fPreviewDocument = new Document ( ) ; fWorkingValues = workingValues ; tools . setupRubyDocumentPartitioner ( fPreviewDocument , IRubyPartitions . RUBY_PARTITIONING ) ; IPreferenceStore [ ] chain = { RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) } ; fPreferenceStore = new ChainedPreferenceStore ( chain ) ; fSourceViewer = new RubySourceViewer ( parent , null , null , false , SWT . READ_ONLY | SWT . V_SCROLL | SWT . H_SCROLL | SWT . BORDER , fPreferenceStore ) ; fViewerConfiguration = new SimpleRubySourceViewerConfiguration ( tools . getColorManager ( ) , fPreferenceStore , null , IRubyPartitions . RUBY_PARTITIONING , true ) ; fSourceViewer . configure ( fViewerConfiguration ) ; fSourceViewer . getTextWidget ( ) . setFont ( JFaceResources . getFont ( PreferenceConstants . EDITOR_TEXT_FONT ) ) ; fMarginPainter = new MarginPainter ( fSourceViewer ) ; final RGB rgb = PreferenceConverter . getColor ( fPreferenceStore , AbstractDecoratedTextEditorPreferenceConstants . EDITOR_PRINT_MARGIN_COLOR ) ; fMarginPainter . setMarginRulerColor ( tools . getColorManager ( ) . getColor ( rgb ) ) ; fSourceViewer . addPainter ( fMarginPainter ) ; new RubySourcePreviewerUpdater ( ) ; fSourceViewer . setDocument ( fPreviewDocument ) ; } public Control getControl ( ) { return fSourceViewer . getControl ( ) ; } public StyledText getTextWidget ( ) { return fSourceViewer . getTextWidget ( ) ; } public void update ( ) { if ( fWorkingValues == null ) { fPreviewDocument . set ( "" ) ; return ; } final String value = ( String ) fWorkingValues . get ( DefaultCodeFormatterConstants . FORMATTER_LINE_SPLIT ) ; final int lineWidth = getPositiveIntValue ( value , ) ; fMarginPainter . setMarginRulerColumn ( lineWidth ) ; final int tabSize = getPositiveIntValue ( ( String ) fWorkingValues . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) , ) ; if ( tabSize != fTabSize ) fSourceViewer . getTextWidget ( ) . setTabs ( tabSize ) ; fTabSize = tabSize ; final StyledText widget = ( StyledText ) fSourceViewer . getControl ( ) ; final int height = widget . getClientArea ( ) . height ; final int top0 = widget . getTopPixel ( ) ; final int totalPixels0 = getHeightOfAllLines ( widget ) ; final int topPixelRange0 = totalPixels0 > height ? totalPixels0 - height : ; widget . setRedraw ( false ) ; doFormatPreview ( ) ; fSourceViewer . setSelection ( null ) ; final int totalPixels1 = getHeightOfAllLines ( widget ) ; final int topPixelRange1 = totalPixels1 > height ? totalPixels1 - height : ; final int top1 = topPixelRange0 > ? ( int ) ( topPixelRange1 * top0 / ( double ) topPixelRange0 ) : ; widget . setTopPixel ( top1 ) ; widget . setRedraw ( true ) ; } private int getHeightOfAllLines ( StyledText styledText ) { int height = ; int lineCount = styledText . getLineCount ( ) ; for ( int i = ; i < lineCount ; i ++ ) { height = height + styledText . getLineHeight ( ) ; } return height ; } protected abstract void doFormatPreview ( ) ; private static int getPositiveIntValue ( String string , int defaultValue ) { try { int i = Integer . parseInt ( string ) ; if ( i >= ) { return i ; } } catch ( NumberFormatException e ) { } return defaultValue ; } public final Map getWorkingValues ( ) { return fWorkingValues ; } public final void setWorkingValues ( Map workingValues ) { fWorkingValues = workingValues ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import java . util . Map ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . formatter . FormattingContextProperties ; import org . eclipse . jface . text . formatter . IContentFormatter ; import org . eclipse . jface . text . formatter . IContentFormatterExtension ; import org . eclipse . jface . text . formatter . IFormattingContext ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . internal . ui . IRubyStatusConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . comment . CommentFormattingContext ; public class RubyScriptPreview extends RubyPreview { protected String fPreviewText ; public RubyScriptPreview ( Map workingValues , Composite parent ) { super ( workingValues , parent ) ; } protected void doFormatPreview ( ) { if ( fPreviewText == null ) { fPreviewDocument . set ( "" ) ; return ; } fPreviewDocument . set ( fPreviewText ) ; fSourceViewer . setRedraw ( false ) ; final IFormattingContext context = new CommentFormattingContext ( ) ; try { final IContentFormatter formatter = fViewerConfiguration . getContentFormatter ( fSourceViewer ) ; if ( formatter instanceof IContentFormatterExtension ) { final IContentFormatterExtension extension = ( IContentFormatterExtension ) formatter ; context . setProperty ( FormattingContextProperties . CONTEXT_PREFERENCES , fWorkingValues ) ; context . setProperty ( FormattingContextProperties . CONTEXT_DOCUMENT , Boolean . valueOf ( true ) ) ; extension . format ( fPreviewDocument , context ) ; } else formatter . format ( fPreviewDocument , new Region ( , fPreviewDocument . getLength ( ) ) ) ; } catch ( Exception e ) { final IStatus status = new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IRubyStatusConstants . INTERNAL_ERROR , FormatterMessages . RubyPreview_formatter_exception , e ) ; RubyPlugin . log ( status ) ; } finally { context . dispose ( ) ; fSourceViewer . setRedraw ( true ) ; } } public void setPreviewText ( String previewText ) { fPreviewText = previewText ; update ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences . formatter ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager . CustomProfile ; public class AlreadyExistsDialog extends StatusDialog { private Composite fComposite ; protected Text fNameText ; private Button fRenameRadio , fOverwriteRadio ; private final int NUM_COLUMNS = ; private final StatusInfo fOk ; private final StatusInfo fEmpty ; private final StatusInfo fDuplicate ; private final CustomProfile fProfile ; private final ProfileManager fProfileManager ; public AlreadyExistsDialog ( Shell parentShell , CustomProfile profile , ProfileManager profileManager ) { super ( parentShell ) ; fProfile = profile ; fProfileManager = profileManager ; fOk = new StatusInfo ( ) ; fDuplicate = new StatusInfo ( IStatus . ERROR , FormatterMessages . AlreadyExistsDialog_message_profile_already_exists ) ; fEmpty = new StatusInfo ( IStatus . ERROR , FormatterMessages . AlreadyExistsDialog_message_profile_name_empty ) ; } public void create ( ) { super . create ( ) ; setTitle ( FormatterMessages . AlreadyExistsDialog_dialog_title ) ; } public Control createDialogArea ( Composite parent ) { initializeComposite ( parent ) ; createLabel ( Messages . format ( FormatterMessages . AlreadyExistsDialog_dialog_label , fProfile . getName ( ) ) ) ; fRenameRadio = createRadioButton ( FormatterMessages . AlreadyExistsDialog_rename_radio_button_desc ) ; fNameText = createTextField ( ) ; fOverwriteRadio = createRadioButton ( FormatterMessages . AlreadyExistsDialog_overwrite_radio_button_desc ) ; fRenameRadio . setSelection ( true ) ; fNameText . setText ( fProfile . getName ( ) ) ; fNameText . setSelection ( , fProfile . getName ( ) . length ( ) ) ; fNameText . setFocus ( ) ; fNameText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { doValidation ( ) ; } } ) ; fRenameRadio . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { fNameText . setEnabled ( true ) ; fNameText . setFocus ( ) ; fNameText . setSelection ( , fNameText . getText ( ) . length ( ) ) ; doValidation ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; fOverwriteRadio . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { fNameText . setEnabled ( false ) ; doValidation ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; updateStatus ( fDuplicate ) ; applyDialogFont ( fComposite ) ; return fComposite ; } private void initializeComposite ( Composite parent ) { fComposite = new Composite ( parent , SWT . NULL ) ; final GridLayout layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . verticalSpacing = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_SPACING ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; layout . numColumns = NUM_COLUMNS ; fComposite . setLayout ( layout ) ; } private Label createLabel ( String text ) { final GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = NUM_COLUMNS ; gd . widthHint = convertWidthInCharsToPixels ( ) ; final Label label = new Label ( fComposite , SWT . WRAP ) ; label . setText ( text ) ; label . setLayoutData ( gd ) ; return label ; } private Button createRadioButton ( String text ) { final GridData gd = new GridData ( ) ; gd . horizontalSpan = NUM_COLUMNS ; gd . widthHint = convertWidthInCharsToPixels ( ) ; final Button radio = new Button ( fComposite , SWT . RADIO ) ; radio . setLayoutData ( gd ) ; radio . setText ( text ) ; return radio ; } private Text createTextField ( ) { final GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = NUM_COLUMNS ; final Text text = new Text ( fComposite , SWT . SINGLE | SWT . BORDER ) ; text . setLayoutData ( gd ) ; return text ; } protected void doValidation ( ) { if ( fOverwriteRadio . getSelection ( ) ) { updateStatus ( fOk ) ; return ; } final String name = fNameText . getText ( ) . trim ( ) ; if ( name . length ( ) == ) { updateStatus ( fEmpty ) ; return ; } if ( fProfileManager . containsName ( name ) ) { updateStatus ( fDuplicate ) ; return ; } updateStatus ( fOk ) ; } protected void okPressed ( ) { if ( ! getStatus ( ) . isOK ( ) ) return ; if ( fRenameRadio . getSelection ( ) ) fProfile . rename ( fNameText . getText ( ) . trim ( ) , fProfileManager ) ; super . okPressed ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . ColorDialog ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . jface . resource . JFaceResources ; class ColorEditor { private Point fExtent ; private Image fImage ; private RGB fColorValue ; private Color fColor ; private Button fButton ; public ColorEditor ( Composite parent ) { fButton = new Button ( parent , SWT . PUSH ) ; fExtent = computeImageSize ( parent ) ; fImage = new Image ( parent . getDisplay ( ) , fExtent . x , fExtent . y ) ; GC gc = new GC ( fImage ) ; gc . setBackground ( fButton . getBackground ( ) ) ; gc . fillRectangle ( , , fExtent . x , fExtent . y ) ; gc . dispose ( ) ; fButton . setImage ( fImage ) ; fButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent event ) { ColorDialog colorDialog = new ColorDialog ( fButton . getShell ( ) ) ; colorDialog . setRGB ( fColorValue ) ; RGB newColor = colorDialog . open ( ) ; if ( newColor != null ) { fColorValue = newColor ; updateColorImage ( ) ; } } } ) ; fButton . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent event ) { if ( fImage != null ) { fImage . dispose ( ) ; fImage = null ; } if ( fColor != null ) { fColor . dispose ( ) ; fColor = null ; } } } ) ; } public RGB getColorValue ( ) { return fColorValue ; } public void setColorValue ( RGB rgb ) { fColorValue = rgb ; updateColorImage ( ) ; } public Button getButton ( ) { return fButton ; } protected void updateColorImage ( ) { Display display = fButton . getDisplay ( ) ; GC gc = new GC ( fImage ) ; gc . setForeground ( display . getSystemColor ( SWT . COLOR_BLACK ) ) ; gc . drawRectangle ( , , fExtent . x - , fExtent . y - ) ; if ( fColor != null ) fColor . dispose ( ) ; fColor = new Color ( display , fColorValue ) ; gc . setBackground ( fColor ) ; gc . fillRectangle ( , , fExtent . x - , fExtent . y - ) ; gc . dispose ( ) ; fButton . setImage ( fImage ) ; } protected Point computeImageSize ( Control window ) { GC gc = new GC ( window ) ; Font f = JFaceResources . getFontRegistry ( ) . get ( JFaceResources . DEFAULT_FONT ) ; gc . setFont ( f ) ; int height = gc . getFontMetrics ( ) . getHeight ( ) ; gc . dispose ( ) ; Point p = new Point ( height * - , height ) ; return p ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . StringTokenizer ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class MembersOrderPreferenceCache implements IPropertyChangeListener { public static final int TYPE_INDEX = ; public static final int CONSTRUCTORS_INDEX = ; public static final int METHOD_INDEX = ; public static final int FIELDS_INDEX = ; public static final int STATIC_FIELDS_INDEX = ; public static final int STATIC_METHODS_INDEX = ; public static final int N_CATEGORIES = STATIC_METHODS_INDEX + ; private static final int PUBLIC_INDEX = ; private static final int PRIVATE_INDEX = ; private static final int PROTECTED_INDEX = ; private static final int N_VISIBILITIES = PROTECTED_INDEX + ; private int [ ] fCategoryOffsets = null ; private boolean fSortByVisibility ; private int [ ] fVisibilityOffsets = null ; private IPreferenceStore fPreferenceStore ; public MembersOrderPreferenceCache ( ) { fPreferenceStore = null ; fCategoryOffsets = null ; fSortByVisibility = false ; fVisibilityOffsets = null ; } public void install ( IPreferenceStore store ) { fPreferenceStore = store ; store . addPropertyChangeListener ( this ) ; fSortByVisibility = store . getBoolean ( PreferenceConstants . APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER ) ; } public void dispose ( ) { fPreferenceStore . removePropertyChangeListener ( this ) ; fPreferenceStore = null ; } public static boolean isMemberOrderProperty ( String property ) { return PreferenceConstants . APPEARANCE_MEMBER_SORT_ORDER . equals ( property ) || PreferenceConstants . APPEARANCE_VISIBILITY_SORT_ORDER . equals ( property ) || PreferenceConstants . APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER . equals ( property ) ; } public void propertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( PreferenceConstants . APPEARANCE_MEMBER_SORT_ORDER . equals ( property ) ) { fCategoryOffsets = null ; } else if ( PreferenceConstants . APPEARANCE_VISIBILITY_SORT_ORDER . equals ( property ) ) { fVisibilityOffsets = null ; } else if ( PreferenceConstants . APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER . equals ( property ) ) { fSortByVisibility = fPreferenceStore . getBoolean ( PreferenceConstants . APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER ) ; } } public int getCategoryIndex ( int kind ) { if ( fCategoryOffsets == null ) { fCategoryOffsets = getCategoryOffsets ( ) ; } return fCategoryOffsets [ kind ] ; } private int [ ] getCategoryOffsets ( ) { int [ ] offsets = new int [ N_CATEGORIES ] ; IPreferenceStore store = fPreferenceStore ; String key = PreferenceConstants . APPEARANCE_MEMBER_SORT_ORDER ; boolean success = fillCategoryOffsetsFromPreferenceString ( store . getString ( key ) , offsets ) ; if ( ! success ) { store . setToDefault ( key ) ; fillCategoryOffsetsFromPreferenceString ( store . getDefaultString ( key ) , offsets ) ; } return offsets ; } private boolean fillCategoryOffsetsFromPreferenceString ( String str , int [ ] offsets ) { StringTokenizer tokenizer = new StringTokenizer ( str , "" ) ; int i = ; while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) . trim ( ) ; if ( "" . equals ( token ) ) { offsets [ TYPE_INDEX ] = i ++ ; } else if ( "" . equals ( token ) ) { offsets [ METHOD_INDEX ] = i ++ ; } else if ( "" . equals ( token ) ) { offsets [ FIELDS_INDEX ] = i ++ ; } else if ( "" . equals ( token ) ) { offsets [ STATIC_FIELDS_INDEX ] = i ++ ; } else if ( "" . equals ( token ) ) { offsets [ STATIC_METHODS_INDEX ] = i ++ ; } else if ( "" . equals ( token ) ) { offsets [ CONSTRUCTORS_INDEX ] = i ++ ; } } return i == N_CATEGORIES ; } public boolean isSortByVisibility ( ) { return fSortByVisibility ; } public int getVisibilityIndex ( int modifierFlags ) { if ( fVisibilityOffsets == null ) { fVisibilityOffsets = getVisibilityOffsets ( ) ; } int kind = PUBLIC_INDEX ; if ( Flags . isPublic ( modifierFlags ) ) { kind = PUBLIC_INDEX ; } else if ( Flags . isProtected ( modifierFlags ) ) { kind = PROTECTED_INDEX ; } else if ( Flags . isPrivate ( modifierFlags ) ) { kind = PRIVATE_INDEX ; } return fVisibilityOffsets [ kind ] ; } private int [ ] getVisibilityOffsets ( ) { int [ ] offsets = new int [ N_VISIBILITIES ] ; IPreferenceStore store = fPreferenceStore ; String key = PreferenceConstants . APPEARANCE_VISIBILITY_SORT_ORDER ; boolean success = fillVisibilityOffsetsFromPreferenceString ( store . getString ( key ) , offsets ) ; if ( ! success ) { store . setToDefault ( key ) ; fillVisibilityOffsetsFromPreferenceString ( store . getDefaultString ( key ) , offsets ) ; } return offsets ; } private boolean fillVisibilityOffsetsFromPreferenceString ( String str , int [ ] offsets ) { StringTokenizer tokenizer = new StringTokenizer ( str , "" ) ; int i = ; while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) . trim ( ) ; if ( "" . equals ( token ) ) { offsets [ PUBLIC_INDEX ] = i ++ ; } else if ( "" . equals ( token ) ) { offsets [ PRIVATE_INDEX ] = i ++ ; } else if ( "" . equals ( token ) ) { offsets [ PROTECTED_INDEX ] = i ++ ; } } return i == N_VISIBILITIES ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . viewers . ComboViewer ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StackLayout ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . FillLayout ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . text . folding . RubyFoldingStructureProviderDescriptor ; import org . rubypeople . rdt . internal . ui . text . folding . RubyFoldingStructureProviderRegistry ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . folding . IRubyFoldingPreferenceBlock ; class FoldingConfigurationBlock implements IPreferenceConfigurationBlock { private static class ErrorPreferences implements IRubyFoldingPreferenceBlock { private String fMessage ; protected ErrorPreferences ( String message ) { fMessage = message ; } public Control createControl ( Composite composite ) { Composite inner = new Composite ( composite , SWT . NONE ) ; inner . setLayout ( new FillLayout ( SWT . VERTICAL ) ) ; Label label = new Label ( inner , SWT . CENTER ) ; label . setText ( fMessage ) ; return inner ; } public void initialize ( ) { } public void performOk ( ) { } public void performDefaults ( ) { } public void dispose ( ) { } } private final OverlayPreferenceStore fStore ; private Combo fProviderCombo ; private Button fFoldingCheckbox ; private ComboViewer fProviderViewer ; private Map fProviderDescriptors ; private Composite fGroup ; private Map fProviderPreferences ; private Map fProviderControls ; private StackLayout fStackLayout ; public FoldingConfigurationBlock ( OverlayPreferenceStore store ) { Assert . isNotNull ( store ) ; fStore = store ; fStore . addKeys ( createOverlayStoreKeys ( ) ) ; fProviderDescriptors = createListModel ( ) ; fProviderPreferences = new HashMap ( ) ; fProviderControls = new HashMap ( ) ; } private Map createListModel ( ) { RubyFoldingStructureProviderRegistry reg = RubyPlugin . getDefault ( ) . getFoldingStructureProviderRegistry ( ) ; reg . reloadExtensions ( ) ; RubyFoldingStructureProviderDescriptor [ ] descs = reg . getFoldingProviderDescriptors ( ) ; Map map = new HashMap ( ) ; for ( int i = ; i < descs . length ; i ++ ) { map . put ( descs [ i ] . getId ( ) , descs [ i ] ) ; } return map ; } private OverlayPreferenceStore . OverlayKey [ ] createOverlayStoreKeys ( ) { ArrayList overlayKeys = new ArrayList ( ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_FOLDING_ENABLED ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , PreferenceConstants . EDITOR_FOLDING_PROVIDER ) ) ; OverlayPreferenceStore . OverlayKey [ ] keys = new OverlayPreferenceStore . OverlayKey [ overlayKeys . size ( ) ] ; overlayKeys . toArray ( keys ) ; return keys ; } public Control createControl ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NULL ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_CENTER | GridData . VERTICAL_ALIGN_FILL ) ; composite . setLayoutData ( gd ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; PixelConverter pc = new PixelConverter ( composite ) ; layout . verticalSpacing = pc . convertHeightInCharsToPixels ( ) / ; composite . setLayout ( layout ) ; fFoldingCheckbox = new Button ( composite , SWT . CHECK ) ; fFoldingCheckbox . setText ( PreferencesMessages . FoldingConfigurationBlock_enable ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING | GridData . VERTICAL_ALIGN_BEGINNING ) ; fFoldingCheckbox . setLayoutData ( gd ) ; fFoldingCheckbox . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { boolean enabled = fFoldingCheckbox . getSelection ( ) ; fStore . setValue ( PreferenceConstants . EDITOR_FOLDING_ENABLED , enabled ) ; updateCheckboxDependencies ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; Label label = new Label ( composite , SWT . CENTER ) ; gd = new GridData ( GridData . FILL_HORIZONTAL | GridData . VERTICAL_ALIGN_BEGINNING ) ; label . setLayoutData ( gd ) ; Composite comboComp = new Composite ( composite , SWT . NONE ) ; gd = new GridData ( GridData . FILL_HORIZONTAL | GridData . VERTICAL_ALIGN_BEGINNING ) ; GridLayout gridLayout = new GridLayout ( , false ) ; gridLayout . marginWidth = ; comboComp . setLayout ( gridLayout ) ; Label comboLabel = new Label ( comboComp , SWT . CENTER ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING | GridData . VERTICAL_ALIGN_CENTER ) ; comboLabel . setLayoutData ( gd ) ; comboLabel . setText ( PreferencesMessages . FoldingConfigurationBlock_combo_caption ) ; label = new Label ( composite , SWT . CENTER ) ; gd = new GridData ( GridData . FILL_HORIZONTAL | GridData . VERTICAL_ALIGN_BEGINNING ) ; label . setLayoutData ( gd ) ; fProviderCombo = new Combo ( comboComp , SWT . READ_ONLY | SWT . DROP_DOWN ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_END | GridData . VERTICAL_ALIGN_CENTER ) ; fProviderCombo . setLayoutData ( gd ) ; fProviderViewer = new ComboViewer ( fProviderCombo ) ; fProviderViewer . setContentProvider ( new IStructuredContentProvider ( ) { public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public Object [ ] getElements ( Object inputElement ) { return fProviderDescriptors . values ( ) . toArray ( ) ; } } ) ; fProviderViewer . setLabelProvider ( new LabelProvider ( ) { public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { return ( ( RubyFoldingStructureProviderDescriptor ) element ) . getName ( ) ; } } ) ; fProviderViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection sel = ( IStructuredSelection ) event . getSelection ( ) ; if ( ! sel . isEmpty ( ) ) { fStore . setValue ( PreferenceConstants . EDITOR_FOLDING_PROVIDER , ( ( RubyFoldingStructureProviderDescriptor ) sel . getFirstElement ( ) ) . getId ( ) ) ; updateListDependencies ( ) ; } } } ) ; fProviderViewer . setInput ( fProviderDescriptors ) ; fProviderViewer . refresh ( ) ; Composite groupComp = new Composite ( composite , SWT . NONE ) ; gd = new GridData ( GridData . FILL_BOTH ) ; gd . horizontalSpan = ; groupComp . setLayoutData ( gd ) ; gridLayout = new GridLayout ( , false ) ; gridLayout . marginWidth = ; groupComp . setLayout ( gridLayout ) ; fGroup = new Composite ( groupComp , SWT . NONE ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING | GridData . VERTICAL_ALIGN_BEGINNING ) ; fGroup . setLayoutData ( gd ) ; fStackLayout = new StackLayout ( ) ; fGroup . setLayout ( fStackLayout ) ; return composite ; } private void updateCheckboxDependencies ( ) { } void updateListDependencies ( ) { String id = fStore . getString ( PreferenceConstants . EDITOR_FOLDING_PROVIDER ) ; RubyFoldingStructureProviderDescriptor desc = ( RubyFoldingStructureProviderDescriptor ) fProviderDescriptors . get ( id ) ; IRubyFoldingPreferenceBlock prefs ; if ( desc == null ) { String message = RubyUIMessages . FoldingConfigurationBlock_error_not_exist ; RubyPlugin . log ( new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , IStatus . OK , message , null ) ) ; prefs = new ErrorPreferences ( message ) ; } else { prefs = ( IRubyFoldingPreferenceBlock ) fProviderPreferences . get ( id ) ; if ( prefs == null ) { try { prefs = desc . createPreferences ( ) ; fProviderPreferences . put ( id , prefs ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; prefs = new ErrorPreferences ( e . getLocalizedMessage ( ) ) ; } } } Control control = ( Control ) fProviderControls . get ( id ) ; if ( control == null ) { control = prefs . createControl ( fGroup ) ; if ( control == null ) { String message = RubyUIMessages . FoldingConfigurationBlock_info_no_preferences ; control = new ErrorPreferences ( message ) . createControl ( fGroup ) ; } else { fProviderControls . put ( id , control ) ; } } fStackLayout . topControl = control ; control . pack ( ) ; fGroup . layout ( ) ; fGroup . getParent ( ) . layout ( ) ; prefs . initialize ( ) ; } public void initialize ( ) { restoreFromPreferences ( ) ; } public void performOk ( ) { for ( Iterator it = fProviderPreferences . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { IRubyFoldingPreferenceBlock prefs = ( IRubyFoldingPreferenceBlock ) it . next ( ) ; prefs . performOk ( ) ; } } public void performDefaults ( ) { restoreFromPreferences ( ) ; for ( Iterator it = fProviderPreferences . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { IRubyFoldingPreferenceBlock prefs = ( IRubyFoldingPreferenceBlock ) it . next ( ) ; prefs . performDefaults ( ) ; } } public void dispose ( ) { for ( Iterator it = fProviderPreferences . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { IRubyFoldingPreferenceBlock prefs = ( IRubyFoldingPreferenceBlock ) it . next ( ) ; prefs . dispose ( ) ; } } private void restoreFromPreferences ( ) { boolean enabled = fStore . getBoolean ( PreferenceConstants . EDITOR_FOLDING_ENABLED ) ; fFoldingCheckbox . setSelection ( enabled ) ; updateCheckboxDependencies ( ) ; String id = fStore . getString ( PreferenceConstants . EDITOR_FOLDING_PROVIDER ) ; Object provider = fProviderDescriptors . get ( id ) ; if ( provider != null ) { fProviderViewer . setSelection ( new StructuredSelection ( provider ) , true ) ; updateListDependencies ( ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public final class FoldingPreferencePage extends AbstractConfigurationBlockPreferencePage { protected String getHelpId ( ) { return null ; } protected void setDescription ( ) { String description = PreferencesMessages . RubyEditorPreferencePage_folding_title ; setDescription ( description ) ; } protected void setPreferenceStore ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; } protected Label createDescriptionLabel ( Composite parent ) { return null ; } protected IPreferenceConfigurationBlock createConfigurationBlock ( OverlayPreferenceStore overlayPreferenceStore ) { return new FoldingConfigurationBlock ( overlayPreferenceStore ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . texteditor . spelling . IPreferenceStatusMonitor ; import org . eclipse . ui . texteditor . spelling . ISpellingPreferenceBlock ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; public class SpellingPreferenceBlock implements ISpellingPreferenceBlock { private class NullStatusChangeListener implements IStatusChangeListener { public void statusChanged ( IStatus status ) { } } private class StatusChangeListenerAdapter implements IStatusChangeListener { private IPreferenceStatusMonitor fMonitor ; private IStatus fStatus ; public StatusChangeListenerAdapter ( IPreferenceStatusMonitor monitor ) { super ( ) ; fMonitor = monitor ; } public void statusChanged ( IStatus status ) { fStatus = status ; fMonitor . statusChanged ( status ) ; } public IStatus getStatus ( ) { return fStatus ; } } private SpellingConfigurationBlock fBlock = new SpellingConfigurationBlock ( new NullStatusChangeListener ( ) , null , null ) ; private SpellingPreferenceBlock . StatusChangeListenerAdapter fStatusMonitor ; public Control createControl ( Composite parent ) { return fBlock . createContents ( parent ) ; } public void initialize ( IPreferenceStatusMonitor statusMonitor ) { fStatusMonitor = new StatusChangeListenerAdapter ( statusMonitor ) ; fBlock . fContext = fStatusMonitor ; } public boolean canPerformOk ( ) { return fStatusMonitor == null || fStatusMonitor . getStatus ( ) == null || ! fStatusMonitor . getStatus ( ) . matches ( IStatus . ERROR ) ; } public void performOk ( ) { fBlock . performOk ( ) ; } public void performDefaults ( ) { fBlock . performDefaults ( ) ; } public void performRevert ( ) { fBlock . performRevert ( ) ; } public void dispose ( ) { fBlock . dispose ( ) ; } public void setEnabled ( boolean enabled ) { fBlock . setEnabled ( enabled ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyEditorColoringPreferencePage extends AbstractConfigurationBlockPreferencePage { protected String getHelpId ( ) { return null ; } protected void setDescription ( ) { String description = PreferencesMessages . RubyEditorPreferencePage_colors ; setDescription ( description ) ; } protected Label createDescriptionLabel ( Composite parent ) { return null ; } protected void setPreferenceStore ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; } protected IPreferenceConfigurationBlock createConfigurationBlock ( OverlayPreferenceStore overlayPreferenceStore ) { return new RubyEditorColoringConfigurationBlock ( overlayPreferenceStore ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . IdentityHashMap ; import java . util . List ; import java . util . Map ; import java . util . StringTokenizer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Link ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . forms . events . ExpansionAdapter ; import org . eclipse . ui . forms . events . ExpansionEvent ; import org . eclipse . ui . forms . widgets . ExpandableComposite ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . eclipse . ui . preferences . IWorkingCopyManager ; import org . eclipse . ui . preferences . WorkingCopyManager ; import org . osgi . service . prefs . BackingStoreException ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . CoreUtility ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . ui . RubyUI ; public abstract class OptionsConfigurationBlock { public static final class Key { private String fQualifier ; private String fKey ; public Key ( String qualifier , String key ) { fQualifier = qualifier ; fKey = key ; } public String getName ( ) { return fKey ; } private IEclipsePreferences getNode ( IScopeContext context , IWorkingCopyManager manager ) { IEclipsePreferences node = context . getNode ( fQualifier ) ; if ( manager != null ) { return manager . getWorkingCopy ( node ) ; } return node ; } public String getStoredValue ( IScopeContext context , IWorkingCopyManager manager ) { return getNode ( context , manager ) . get ( fKey , null ) ; } public String getStoredValue ( IScopeContext [ ] lookupOrder , boolean ignoreTopScope , IWorkingCopyManager manager ) { for ( int i = ignoreTopScope ? : ; i < lookupOrder . length ; i ++ ) { String value = getStoredValue ( lookupOrder [ i ] , manager ) ; if ( value != null ) { return value ; } } return null ; } public void setStoredValue ( IScopeContext context , String value , IWorkingCopyManager manager ) { if ( value != null ) { getNode ( context , manager ) . put ( fKey , value ) ; } else { getNode ( context , manager ) . remove ( fKey ) ; } } public String toString ( ) { return fQualifier + '' + fKey ; } public String getQualifier ( ) { return fQualifier ; } } protected static class ControlData { private Key fKey ; private String [ ] fValues ; public ControlData ( Key key , String [ ] values ) { fKey = key ; fValues = values ; } public Key getKey ( ) { return fKey ; } public String getValue ( boolean selection ) { int index = selection ? : ; return fValues [ index ] ; } public String getValue ( int index ) { return fValues [ index ] ; } public int getSelection ( String value ) { if ( value != null ) { for ( int i = ; i < fValues . length ; i ++ ) { if ( value . equals ( fValues [ i ] ) ) { return i ; } } } return fValues . length - ; } } private static final String REBUILD_COUNT_KEY = "" ; private static final String SETTINGS_EXPANDED = "" ; protected final List < Button > fCheckBoxes ; protected final List < Combo > fComboBoxes ; protected final List < Text > fTextBoxes ; protected final HashMap < Object , Label > fLabels ; protected final List < ExpandableComposite > fExpandedComposites ; private SelectionListener fSelectionListener ; private ModifyListener fTextModifyListener ; protected IStatusChangeListener fContext ; protected final IProject fProject ; protected final Key [ ] fAllKeys ; private IScopeContext [ ] fLookupOrder ; private Shell fShell ; private final IWorkingCopyManager fManager ; private IWorkbenchPreferenceContainer fContainer ; private Map < Key , String > fDisabledProjectSettings ; private int fRebuildCount ; public OptionsConfigurationBlock ( IStatusChangeListener context , IProject project , Key [ ] allKeys , IWorkbenchPreferenceContainer container ) { fContext = context ; fProject = project ; fAllKeys = allKeys ; fContainer = container ; if ( container == null ) { fManager = new WorkingCopyManager ( ) ; } else { fManager = container . getWorkingCopyManager ( ) ; } if ( fProject != null ) { fLookupOrder = new IScopeContext [ ] { new ProjectScope ( fProject ) , new InstanceScope ( ) , new DefaultScope ( ) } ; } else { fLookupOrder = new IScopeContext [ ] { new InstanceScope ( ) , new DefaultScope ( ) } ; } testIfOptionsComplete ( allKeys ) ; if ( fProject == null || hasProjectSpecificOptions ( fProject ) ) { fDisabledProjectSettings = null ; } else { fDisabledProjectSettings = new IdentityHashMap < Key , String > ( ) ; for ( int i = ; i < allKeys . length ; i ++ ) { Key curr = allKeys [ i ] ; fDisabledProjectSettings . put ( curr , curr . getStoredValue ( fLookupOrder , false , fManager ) ) ; } } settingsUpdated ( ) ; fCheckBoxes = new ArrayList < Button > ( ) ; fComboBoxes = new ArrayList < Combo > ( ) ; fTextBoxes = new ArrayList < Text > ( ) ; fLabels = new HashMap < Object , Label > ( ) ; fExpandedComposites = new ArrayList < ExpandableComposite > ( ) ; fRebuildCount = getRebuildCount ( ) ; } protected final IWorkbenchPreferenceContainer getPreferenceContainer ( ) { return fContainer ; } protected static Key getKey ( String plugin , String key ) { return new Key ( plugin , key ) ; } protected final static Key getRDTCoreKey ( String key ) { return getKey ( RubyCore . PLUGIN_ID , key ) ; } protected final static Key getRDTUIKey ( String key ) { return getKey ( RubyUI . ID_PLUGIN , key ) ; } private void testIfOptionsComplete ( Key [ ] allKeys ) { for ( int i = ; i < allKeys . length ; i ++ ) { if ( allKeys [ i ] . getStoredValue ( fLookupOrder , false , fManager ) == null ) { RubyPlugin . logErrorMessage ( "" + allKeys [ i ] + "" + this . getClass ( ) . getName ( ) + '' ) ; } } } private int getRebuildCount ( ) { return fManager . getWorkingCopy ( new DefaultScope ( ) . getNode ( RubyUI . ID_PLUGIN ) ) . getInt ( REBUILD_COUNT_KEY , ) ; } private void incrementRebuildCount ( ) { fRebuildCount ++ ; fManager . getWorkingCopy ( new DefaultScope ( ) . getNode ( RubyUI . ID_PLUGIN ) ) . putInt ( REBUILD_COUNT_KEY , fRebuildCount ) ; } protected void settingsUpdated ( ) { } public void selectOption ( String key , String qualifier ) { for ( int i = ; i < fAllKeys . length ; i ++ ) { Key curr = fAllKeys [ i ] ; if ( curr . getName ( ) . equals ( key ) && curr . getQualifier ( ) . equals ( qualifier ) ) { selectOption ( curr ) ; } } } public void selectOption ( Key key ) { Control control = findControl ( key ) ; if ( control != null ) { if ( ! fExpandedComposites . isEmpty ( ) ) { ExpandableComposite expandable = getParentExpandableComposite ( control ) ; if ( expandable != null ) { for ( int i = ; i < fExpandedComposites . size ( ) ; i ++ ) { ExpandableComposite curr = ( ExpandableComposite ) fExpandedComposites . get ( i ) ; curr . setExpanded ( curr == expandable ) ; } expandedStateChanged ( expandable ) ; } } control . setFocus ( ) ; } } public final boolean hasProjectSpecificOptions ( IProject project ) { if ( project != null ) { IScopeContext projectContext = new ProjectScope ( project ) ; Key [ ] allKeys = fAllKeys ; for ( int i = ; i < allKeys . length ; i ++ ) { if ( allKeys [ i ] . getStoredValue ( projectContext , fManager ) != null ) { return true ; } } } return false ; } protected Shell getShell ( ) { return fShell ; } protected void setShell ( Shell shell ) { fShell = shell ; } protected abstract Control createContents ( Composite parent ) ; protected Button addCheckBox ( Composite parent , String label , Key key , String [ ] values , int indent ) { ControlData data = new ControlData ( key , values ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; gd . horizontalIndent = indent ; Button checkBox = new Button ( parent , SWT . CHECK ) ; checkBox . setFont ( JFaceResources . getDialogFont ( ) ) ; checkBox . setText ( label ) ; checkBox . setData ( data ) ; checkBox . setLayoutData ( gd ) ; checkBox . addSelectionListener ( getSelectionListener ( ) ) ; makeScrollableCompositeAware ( checkBox ) ; String currValue = getValue ( key ) ; checkBox . setSelection ( data . getSelection ( currValue ) == ) ; fCheckBoxes . add ( checkBox ) ; return checkBox ; } protected Button addCheckBoxWithLink ( Composite parent , String label , Key key , String [ ] values , int indent , int widthHint , SelectionListener listener ) { ControlData data = new ControlData ( key , values ) ; GridData gd = new GridData ( GridData . FILL , GridData . FILL , true , false ) ; gd . horizontalSpan = ; gd . horizontalIndent = indent ; Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; composite . setLayout ( layout ) ; composite . setLayoutData ( gd ) ; Button checkBox = new Button ( composite , SWT . CHECK ) ; checkBox . setFont ( JFaceResources . getDialogFont ( ) ) ; checkBox . setData ( data ) ; checkBox . setLayoutData ( new GridData ( GridData . FILL , GridData . BEGINNING , false , false ) ) ; checkBox . addSelectionListener ( getSelectionListener ( ) ) ; gd = new GridData ( GridData . FILL , GridData . CENTER , true , false ) ; gd . widthHint = widthHint ; Link link = new Link ( composite , SWT . NONE ) ; link . setText ( label ) ; link . setLayoutData ( gd ) ; if ( listener != null ) { link . addSelectionListener ( listener ) ; } makeScrollableCompositeAware ( link ) ; makeScrollableCompositeAware ( checkBox ) ; String currValue = getValue ( key ) ; checkBox . setSelection ( data . getSelection ( currValue ) == ) ; fCheckBoxes . add ( checkBox ) ; return checkBox ; } protected Combo addComboBox ( Composite parent , String label , Key key , String [ ] values , String [ ] valueLabels , int indent ) { GridData gd = new GridData ( GridData . FILL , GridData . CENTER , true , false , , ) ; gd . horizontalIndent = indent ; Label labelControl = new Label ( parent , SWT . LEFT ) ; labelControl . setFont ( JFaceResources . getDialogFont ( ) ) ; labelControl . setText ( label ) ; labelControl . setLayoutData ( gd ) ; Combo comboBox = newComboControl ( parent , key , values , valueLabels ) ; comboBox . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ) ; fLabels . put ( comboBox , labelControl ) ; return comboBox ; } protected Combo addInversedComboBox ( Composite parent , String label , Key key , String [ ] values , String [ ] valueLabels , int indent ) { GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = indent ; gd . horizontalSpan = ; Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; composite . setLayout ( layout ) ; composite . setLayoutData ( gd ) ; Combo comboBox = newComboControl ( composite , key , values , valueLabels ) ; comboBox . setFont ( JFaceResources . getDialogFont ( ) ) ; comboBox . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ) ; Label labelControl = new Label ( composite , SWT . LEFT | SWT . WRAP ) ; labelControl . setText ( label ) ; labelControl . setLayoutData ( new GridData ( ) ) ; fLabels . put ( comboBox , labelControl ) ; return comboBox ; } protected Combo newComboControl ( Composite composite , Key key , String [ ] values , String [ ] valueLabels ) { ControlData data = new ControlData ( key , values ) ; Combo comboBox = new Combo ( composite , SWT . READ_ONLY ) ; comboBox . setItems ( valueLabels ) ; comboBox . setData ( data ) ; comboBox . addSelectionListener ( getSelectionListener ( ) ) ; comboBox . setFont ( JFaceResources . getDialogFont ( ) ) ; makeScrollableCompositeAware ( comboBox ) ; String currValue = getValue ( key ) ; comboBox . select ( data . getSelection ( currValue ) ) ; fComboBoxes . add ( comboBox ) ; return comboBox ; } protected Text addTextField ( Composite parent , String label , Key key , int indent , int widthHint ) { Label labelControl = new Label ( parent , SWT . WRAP | SWT . RIGHT ) ; labelControl . setText ( label ) ; labelControl . setFont ( JFaceResources . getDialogFont ( ) ) ; labelControl . setLayoutData ( new GridData ( ) ) ; Text textBox = new Text ( parent , SWT . BORDER | SWT . SINGLE ) ; textBox . setData ( key ) ; textBox . setLayoutData ( new GridData ( ) ) ; makeScrollableCompositeAware ( textBox ) ; fLabels . put ( textBox , labelControl ) ; String currValue = getValue ( key ) ; if ( currValue != null ) { textBox . setText ( currValue ) ; } textBox . addModifyListener ( getTextModifyListener ( ) ) ; GridData data = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; if ( widthHint != ) { data . widthHint = widthHint ; } data . horizontalIndent = indent ; data . horizontalSpan = ; textBox . setLayoutData ( data ) ; fTextBoxes . add ( textBox ) ; return textBox ; } protected ScrolledPageContent getParentScrolledComposite ( Control control ) { Control parent = control . getParent ( ) ; while ( ! ( parent instanceof ScrolledPageContent ) && parent != null ) { parent = parent . getParent ( ) ; } if ( parent instanceof ScrolledPageContent ) { return ( ScrolledPageContent ) parent ; } return null ; } protected ExpandableComposite getParentExpandableComposite ( Control control ) { Control parent = control . getParent ( ) ; while ( ! ( parent instanceof ExpandableComposite ) && parent != null ) { parent = parent . getParent ( ) ; } if ( parent instanceof ExpandableComposite ) { return ( ExpandableComposite ) parent ; } return null ; } private void makeScrollableCompositeAware ( Control control ) { ScrolledPageContent parentScrolledComposite = getParentScrolledComposite ( control ) ; if ( parentScrolledComposite != null ) { parentScrolledComposite . adaptChild ( control ) ; } } protected ExpandableComposite createStyleSection ( Composite parent , String label , int nColumns ) { ExpandableComposite excomposite = new ExpandableComposite ( parent , SWT . NONE , ExpandableComposite . TWISTIE | ExpandableComposite . CLIENT_INDENT ) ; excomposite . setText ( label ) ; excomposite . setExpanded ( false ) ; excomposite . setFont ( JFaceResources . getFontRegistry ( ) . getBold ( JFaceResources . DIALOG_FONT ) ) ; excomposite . setLayoutData ( new GridData ( GridData . FILL , GridData . FILL , true , false , nColumns , ) ) ; excomposite . addExpansionListener ( new ExpansionAdapter ( ) { public void expansionStateChanged ( ExpansionEvent e ) { expandedStateChanged ( ( ExpandableComposite ) e . getSource ( ) ) ; } } ) ; fExpandedComposites . add ( excomposite ) ; makeScrollableCompositeAware ( excomposite ) ; return excomposite ; } protected final void expandedStateChanged ( ExpandableComposite expandable ) { ScrolledPageContent parentScrolledComposite = getParentScrolledComposite ( expandable ) ; if ( parentScrolledComposite != null ) { parentScrolledComposite . reflow ( true ) ; } } protected void restoreSectionExpansionStates ( IDialogSettings settings ) { for ( int i = ; i < fExpandedComposites . size ( ) ; i ++ ) { ExpandableComposite excomposite = ( ExpandableComposite ) fExpandedComposites . get ( i ) ; if ( settings == null ) { excomposite . setExpanded ( i == ) ; } else { excomposite . setExpanded ( settings . getBoolean ( SETTINGS_EXPANDED + String . valueOf ( i ) ) ) ; } } } protected void storeSectionExpansionStates ( IDialogSettings settings ) { for ( int i = ; i < fExpandedComposites . size ( ) ; i ++ ) { ExpandableComposite curr = ( ExpandableComposite ) fExpandedComposites . get ( i ) ; settings . put ( SETTINGS_EXPANDED + String . valueOf ( i ) , curr . isExpanded ( ) ) ; } } protected SelectionListener getSelectionListener ( ) { if ( fSelectionListener == null ) { fSelectionListener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { controlChanged ( e . widget ) ; } } ; } return fSelectionListener ; } protected ModifyListener getTextModifyListener ( ) { if ( fTextModifyListener == null ) { fTextModifyListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { textChanged ( ( Text ) e . widget ) ; } } ; } return fTextModifyListener ; } protected void controlChanged ( Widget widget ) { ControlData data = ( ControlData ) widget . getData ( ) ; String newValue = null ; if ( widget instanceof Button ) { newValue = data . getValue ( ( ( Button ) widget ) . getSelection ( ) ) ; } else if ( widget instanceof Combo ) { newValue = data . getValue ( ( ( Combo ) widget ) . getSelectionIndex ( ) ) ; } else { return ; } String oldValue = setValue ( data . getKey ( ) , newValue ) ; validateSettings ( data . getKey ( ) , oldValue , newValue ) ; } protected void textChanged ( Text textControl ) { Key key = ( Key ) textControl . getData ( ) ; String number = textControl . getText ( ) ; String oldValue = setValue ( key , number ) ; validateSettings ( key , oldValue , number ) ; } protected boolean checkValue ( Key key , String value ) { return value . equals ( getValue ( key ) ) ; } protected String getValue ( Key key ) { if ( fDisabledProjectSettings != null ) { return ( String ) fDisabledProjectSettings . get ( key ) ; } return key . getStoredValue ( fLookupOrder , false , fManager ) ; } protected boolean getBooleanValue ( Key key ) { return Boolean . valueOf ( getValue ( key ) ) . booleanValue ( ) ; } protected String setValue ( Key key , String value ) { if ( fDisabledProjectSettings != null ) { return ( String ) fDisabledProjectSettings . put ( key , value ) ; } String oldValue = getValue ( key ) ; key . setStoredValue ( fLookupOrder [ ] , value , fManager ) ; return oldValue ; } protected String setValue ( Key key , boolean value ) { return setValue ( key , String . valueOf ( value ) ) ; } protected String getStoredValue ( Key key ) { return key . getStoredValue ( fLookupOrder , false , fManager ) ; } protected abstract void validateSettings ( Key changedKey , String oldValue , String newValue ) ; protected String [ ] getTokens ( String text , String separator ) { StringTokenizer tok = new StringTokenizer ( text , separator ) ; int nTokens = tok . countTokens ( ) ; String [ ] res = new String [ nTokens ] ; for ( int i = ; i < res . length ; i ++ ) { res [ i ] = tok . nextToken ( ) . trim ( ) ; } return res ; } private boolean getChanges ( IScopeContext currContext , List < Key > changedSettings ) { boolean needsBuild = false ; for ( int i = ; i < fAllKeys . length ; i ++ ) { Key key = fAllKeys [ i ] ; String oldVal = key . getStoredValue ( currContext , null ) ; String val = key . getStoredValue ( currContext , fManager ) ; if ( val == null ) { if ( oldVal != null ) { changedSettings . add ( key ) ; needsBuild |= ! oldVal . equals ( key . getStoredValue ( fLookupOrder , true , fManager ) ) ; } } else if ( ! val . equals ( oldVal ) ) { changedSettings . add ( key ) ; needsBuild |= oldVal != null || ! val . equals ( key . getStoredValue ( fLookupOrder , true , fManager ) ) ; } } return needsBuild ; } public void useProjectSpecificSettings ( boolean enable ) { boolean hasProjectSpecificOption = fDisabledProjectSettings == null ; if ( enable != hasProjectSpecificOption && fProject != null ) { if ( enable ) { for ( int i = ; i < fAllKeys . length ; i ++ ) { Key curr = fAllKeys [ i ] ; String val = ( String ) fDisabledProjectSettings . get ( curr ) ; curr . setStoredValue ( fLookupOrder [ ] , val , fManager ) ; } fDisabledProjectSettings = null ; updateControls ( ) ; validateSettings ( null , null , null ) ; } else { fDisabledProjectSettings = new IdentityHashMap < Key , String > ( ) ; for ( int i = ; i < fAllKeys . length ; i ++ ) { Key curr = fAllKeys [ i ] ; String oldSetting = curr . getStoredValue ( fLookupOrder , false , fManager ) ; fDisabledProjectSettings . put ( curr , oldSetting ) ; curr . setStoredValue ( fLookupOrder [ ] , null , fManager ) ; } } } } public boolean areSettingsEnabled ( ) { return fDisabledProjectSettings == null || fProject == null ; } public boolean performOk ( ) { return processChanges ( fContainer ) ; } public boolean performApply ( ) { return processChanges ( null ) ; } protected boolean processChanges ( IWorkbenchPreferenceContainer container ) { IScopeContext currContext = fLookupOrder [ ] ; List < Key > changedOptions = new ArrayList < Key > ( ) ; boolean needsBuild = getChanges ( currContext , changedOptions ) ; if ( changedOptions . isEmpty ( ) ) { return true ; } if ( needsBuild ) { int count = getRebuildCount ( ) ; if ( count > fRebuildCount ) { needsBuild = false ; fRebuildCount = count ; } } boolean doBuild = false ; if ( needsBuild ) { String [ ] strings = getFullBuildDialogStrings ( fProject == null ) ; if ( strings != null ) { MessageDialog dialog = new MessageDialog ( getShell ( ) , strings [ ] , null , strings [ ] , MessageDialog . QUESTION , new String [ ] { IDialogConstants . YES_LABEL , IDialogConstants . NO_LABEL , IDialogConstants . CANCEL_LABEL } , ) ; int res = dialog . open ( ) ; if ( res == ) { doBuild = true ; } else if ( res != ) { return false ; } } } if ( container != null ) { if ( doBuild ) { incrementRebuildCount ( ) ; container . registerUpdateJob ( CoreUtility . getBuildJob ( fProject ) ) ; } } else { try { fManager . applyChanges ( ) ; } catch ( BackingStoreException e ) { RubyPlugin . log ( e ) ; return false ; } if ( doBuild ) { CoreUtility . getBuildJob ( fProject ) . schedule ( ) ; } } return true ; } protected abstract String [ ] getFullBuildDialogStrings ( boolean workspaceSettings ) ; public void performDefaults ( ) { for ( int i = ; i < fAllKeys . length ; i ++ ) { Key curr = fAllKeys [ i ] ; String defValue = curr . getStoredValue ( fLookupOrder , true , fManager ) ; setValue ( curr , defValue ) ; } settingsUpdated ( ) ; updateControls ( ) ; validateSettings ( null , null , null ) ; } public void performRevert ( ) { for ( int i = ; i < fAllKeys . length ; i ++ ) { Key curr = fAllKeys [ i ] ; String origValue = curr . getStoredValue ( fLookupOrder , false , null ) ; setValue ( curr , origValue ) ; } settingsUpdated ( ) ; updateControls ( ) ; validateSettings ( null , null , null ) ; } public void dispose ( ) { } protected void updateControls ( ) { for ( int i = fCheckBoxes . size ( ) - ; i >= ; i -- ) { updateCheckBox ( fCheckBoxes . get ( i ) ) ; } for ( int i = fComboBoxes . size ( ) - ; i >= ; i -- ) { updateCombo ( fComboBoxes . get ( i ) ) ; } for ( int i = fTextBoxes . size ( ) - ; i >= ; i -- ) { updateText ( fTextBoxes . get ( i ) ) ; } } protected void updateCombo ( Combo curr ) { ControlData data = ( ControlData ) curr . getData ( ) ; String currValue = getValue ( data . getKey ( ) ) ; curr . select ( data . getSelection ( currValue ) ) ; } protected void updateCheckBox ( Button curr ) { ControlData data = ( ControlData ) curr . getData ( ) ; String currValue = getValue ( data . getKey ( ) ) ; curr . setSelection ( data . getSelection ( currValue ) == ) ; } protected void updateText ( Text curr ) { Key key = ( Key ) curr . getData ( ) ; String currValue = getValue ( key ) ; if ( currValue != null ) { curr . setText ( currValue ) ; } } protected Button getCheckBox ( Key key ) { for ( int i = fCheckBoxes . size ( ) - ; i >= ; i -- ) { Button curr = ( Button ) fCheckBoxes . get ( i ) ; ControlData data = ( ControlData ) curr . getData ( ) ; if ( key . equals ( data . getKey ( ) ) ) { return curr ; } } return null ; } protected Combo getComboBox ( Key key ) { for ( int i = fComboBoxes . size ( ) - ; i >= ; i -- ) { Combo curr = ( Combo ) fComboBoxes . get ( i ) ; ControlData data = ( ControlData ) curr . getData ( ) ; if ( key . equals ( data . getKey ( ) ) ) { return curr ; } } return null ; } protected Text getTextControl ( Key key ) { for ( int i = fTextBoxes . size ( ) - ; i >= ; i -- ) { Text curr = ( Text ) fTextBoxes . get ( i ) ; ControlData data = ( ControlData ) curr . getData ( ) ; if ( key . equals ( data . getKey ( ) ) ) { return curr ; } } return null ; } protected Control findControl ( Key key ) { Combo comboBox = getComboBox ( key ) ; if ( comboBox != null ) { return comboBox ; } Button checkBox = getCheckBox ( key ) ; if ( checkBox != null ) { return checkBox ; } Text text = getTextControl ( key ) ; if ( text != null ) { return text ; } return null ; } protected void setComboEnabled ( Key key , boolean enabled ) { Combo combo = getComboBox ( key ) ; Label label = fLabels . get ( combo ) ; combo . setEnabled ( enabled ) ; label . setEnabled ( enabled ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . io . UnsupportedEncodingException ; import java . net . URLDecoder ; import java . net . URLEncoder ; import java . util . ArrayList ; import java . util . NoSuchElementException ; import java . util . StringTokenizer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; public class NewRubyProjectPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { public static final String ID = "" ; private static final String SRCBIN_FOLDERS_IN_NEWPROJ = PreferenceConstants . SRCBIN_FOLDERS_IN_NEWPROJ ; private static final String SRCBIN_SRCNAME = PreferenceConstants . SRCBIN_SRCNAME ; private static final String LOADPATH_JRELIBRARY_INDEX = PreferenceConstants . NEWPROJECT_JRELIBRARY_INDEX ; private static final String LOADPATH_JRELIBRARY_LIST = PreferenceConstants . NEWPROJECT_JRELIBRARY_LIST ; private static String fgDefaultEncoding = System . getProperty ( "" ) ; public static ILoadpathEntry [ ] getDefaultJRELibrary ( ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; String str = store . getString ( LOADPATH_JRELIBRARY_LIST ) ; int index = store . getInt ( LOADPATH_JRELIBRARY_INDEX ) ; StringTokenizer tok = new StringTokenizer ( str , "" ) ; while ( tok . hasMoreTokens ( ) && index > ) { tok . nextToken ( ) ; index -- ; } if ( tok . hasMoreTokens ( ) ) { ILoadpathEntry [ ] res = decodeJRELibraryLoadpathEntries ( tok . nextToken ( ) ) ; if ( res . length > ) { return res ; } } return new ILoadpathEntry [ ] { getJREContainerEntry ( ) } ; } public static String decodeJRELibraryDescription ( String encoded ) { int end = encoded . indexOf ( '' ) ; if ( end != - ) { return decode ( encoded . substring ( , end ) ) ; } return "" ; } private static String decode ( String str ) { try { return URLDecoder . decode ( str , fgDefaultEncoding ) ; } catch ( UnsupportedEncodingException e ) { RubyPlugin . log ( e ) ; } return "" ; } private static String encode ( String str ) { try { return URLEncoder . encode ( str , fgDefaultEncoding ) ; } catch ( UnsupportedEncodingException e ) { RubyPlugin . log ( e ) ; } return "" ; } public static ILoadpathEntry [ ] decodeJRELibraryLoadpathEntries ( String encoded ) { StringTokenizer tok = new StringTokenizer ( encoded , "" ) ; ArrayList res = new ArrayList ( ) ; while ( tok . hasMoreTokens ( ) ) { try { tok . nextToken ( ) ; int kind = Integer . parseInt ( tok . nextToken ( ) ) ; IPath path = decodePath ( tok . nextToken ( ) ) ; boolean isExported = Boolean . valueOf ( tok . nextToken ( ) ) . booleanValue ( ) ; switch ( kind ) { case ILoadpathEntry . CPE_SOURCE : res . add ( RubyCore . newSourceEntry ( path ) ) ; break ; case ILoadpathEntry . CPE_LIBRARY : res . add ( RubyCore . newLibraryEntry ( path , isExported ) ) ; break ; case ILoadpathEntry . CPE_VARIABLE : res . add ( RubyCore . newVariableEntry ( path , isExported ) ) ; break ; case ILoadpathEntry . CPE_PROJECT : res . add ( RubyCore . newProjectEntry ( path , isExported ) ) ; break ; case ILoadpathEntry . CPE_CONTAINER : res . add ( RubyCore . newContainerEntry ( path , isExported ) ) ; break ; } } catch ( NumberFormatException e ) { String message = PreferencesMessages . NewRubyProjectPreferencePage_error_decode ; RubyPlugin . log ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . ERROR , message , e ) ) ; } catch ( NoSuchElementException e ) { String message = PreferencesMessages . NewRubyProjectPreferencePage_error_decode ; RubyPlugin . log ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . ERROR , message , e ) ) ; } } return ( ILoadpathEntry [ ] ) res . toArray ( new ILoadpathEntry [ res . size ( ) ] ) ; } public static String encodeJRELibrary ( String desc , ILoadpathEntry [ ] cpentries ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < cpentries . length ; i ++ ) { ILoadpathEntry entry = cpentries [ i ] ; buf . append ( encode ( desc ) ) ; buf . append ( '' ) ; buf . append ( entry . getEntryKind ( ) ) ; buf . append ( '' ) ; buf . append ( encodePath ( entry . getPath ( ) ) ) ; buf . append ( '' ) ; buf . append ( entry . isExported ( ) ) ; buf . append ( '' ) ; } return buf . toString ( ) ; } private static String encodePath ( IPath path ) { if ( path == null ) { return "" ; } else if ( path . isEmpty ( ) ) { return "" ; } else { return encode ( path . toPortableString ( ) ) ; } } private static IPath decodePath ( String str ) { if ( "" . equals ( str ) ) { return null ; } else if ( "" . equals ( str ) ) { return Path . EMPTY ; } else { return Path . fromPortableString ( decode ( str ) ) ; } } private ArrayList fCheckBoxes ; private ArrayList fRadioButtons ; private ArrayList fTextControls ; private SelectionListener fSelectionListener ; private ModifyListener fModifyListener ; private Text fSrcFolderNameText ; private Combo fJRECombo ; private Button fProjectAsSourceFolder ; private Button fFoldersAsSourceFolder ; private Label fSrcFolderNameLabel ; public NewRubyProjectPreferencePage ( ) { super ( ) ; setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( PreferencesMessages . NewRubyProjectPreferencePage_description ) ; setTitle ( PreferencesMessages . NewRubyProjectPreferencePage_title ) ; fRadioButtons = new ArrayList ( ) ; fCheckBoxes = new ArrayList ( ) ; fTextControls = new ArrayList ( ) ; fSelectionListener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { controlChanged ( e . widget ) ; } } ; fModifyListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { controlModified ( e . widget ) ; } } ; } public static void initDefaults ( IPreferenceStore store ) { store . setDefault ( SRCBIN_FOLDERS_IN_NEWPROJ , false ) ; store . setDefault ( SRCBIN_SRCNAME , "" ) ; store . setDefault ( LOADPATH_JRELIBRARY_LIST , getDefaultJRELibraries ( ) ) ; store . setDefault ( LOADPATH_JRELIBRARY_INDEX , ) ; } private static String getDefaultJRELibraries ( ) { StringBuffer buf = new StringBuffer ( ) ; ILoadpathEntry cntentry = getJREContainerEntry ( ) ; buf . append ( encodeJRELibrary ( PreferencesMessages . NewRubyProjectPreferencePage_jre_container_description , new ILoadpathEntry [ ] { cntentry } ) ) ; buf . append ( '' ) ; ILoadpathEntry varentry = getJREVariableEntry ( ) ; buf . append ( encodeJRELibrary ( PreferencesMessages . NewRubyProjectPreferencePage_jre_variable_description , new ILoadpathEntry [ ] { varentry } ) ) ; buf . append ( '' ) ; return buf . toString ( ) ; } private static ILoadpathEntry getJREContainerEntry ( ) { return RubyCore . newContainerEntry ( new Path ( RubyRuntime . RUBY_CONTAINER ) ) ; } private static ILoadpathEntry getJREVariableEntry ( ) { return RubyCore . newVariableEntry ( new Path ( RubyRuntime . RUBYLIB_VARIABLE ) ) ; } public void init ( IWorkbench workbench ) { } public void createControl ( Composite parent ) { super . createControl ( parent ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . NEW_JAVA_PROJECT_PREFERENCE_PAGE ) ; } private Button addRadioButton ( Composite parent , String label , String key , String value , int indent ) { GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; gd . horizontalIndent = indent ; Button button = new Button ( parent , SWT . RADIO ) ; button . setText ( label ) ; button . setData ( new String [ ] { key , value } ) ; button . setLayoutData ( gd ) ; button . setSelection ( value . equals ( getPreferenceStore ( ) . getString ( key ) ) ) ; fRadioButtons . add ( button ) ; return button ; } private Text addTextControl ( Composite parent , Label labelControl , String key , int indent ) { GridData gd = new GridData ( ) ; gd . horizontalIndent = indent ; labelControl . setLayoutData ( gd ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . widthHint = convertWidthInCharsToPixels ( ) ; Text text = new Text ( parent , SWT . SINGLE | SWT . BORDER ) ; text . setText ( getPreferenceStore ( ) . getString ( key ) ) ; text . setData ( key ) ; text . setLayoutData ( gd ) ; fTextControls . add ( text ) ; return text ; } protected Control createContents ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite result = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = ; layout . verticalSpacing = convertVerticalDLUsToPixels ( ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; layout . numColumns = ; result . setLayout ( layout ) ; GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = ; Group sourceFolderGroup = new Group ( result , SWT . NONE ) ; layout = new GridLayout ( ) ; layout . numColumns = ; sourceFolderGroup . setLayout ( layout ) ; sourceFolderGroup . setLayoutData ( gd ) ; sourceFolderGroup . setText ( PreferencesMessages . NewRubyProjectPreferencePage_sourcefolder_label ) ; int indent = ; fProjectAsSourceFolder = addRadioButton ( sourceFolderGroup , PreferencesMessages . NewRubyProjectPreferencePage_sourcefolder_project , SRCBIN_FOLDERS_IN_NEWPROJ , IPreferenceStore . FALSE , indent ) ; fProjectAsSourceFolder . addSelectionListener ( fSelectionListener ) ; fFoldersAsSourceFolder = addRadioButton ( sourceFolderGroup , PreferencesMessages . NewRubyProjectPreferencePage_sourcefolder_folder , SRCBIN_FOLDERS_IN_NEWPROJ , IPreferenceStore . TRUE , indent ) ; fFoldersAsSourceFolder . addSelectionListener ( fSelectionListener ) ; indent = convertWidthInCharsToPixels ( ) ; fSrcFolderNameLabel = new Label ( sourceFolderGroup , SWT . NONE ) ; fSrcFolderNameLabel . setText ( PreferencesMessages . NewRubyProjectPreferencePage_folders_src ) ; fSrcFolderNameText = addTextControl ( sourceFolderGroup , fSrcFolderNameLabel , SRCBIN_SRCNAME , indent ) ; fSrcFolderNameText . addModifyListener ( fModifyListener ) ; String [ ] jreNames = getJRENames ( ) ; if ( jreNames . length > ) { Label jreSelectionLabel = new Label ( result , SWT . NONE ) ; jreSelectionLabel . setText ( PreferencesMessages . NewRubyProjectPreferencePage_jrelibrary_label ) ; jreSelectionLabel . setLayoutData ( new GridData ( ) ) ; int index = getPreferenceStore ( ) . getInt ( LOADPATH_JRELIBRARY_INDEX ) ; fJRECombo = new Combo ( result , SWT . READ_ONLY ) ; fJRECombo . setItems ( jreNames ) ; fJRECombo . select ( index ) ; fJRECombo . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ) ; } validateFolders ( ) ; Dialog . applyDialogFont ( result ) ; return result ; } private void validateFolders ( ) { boolean useFolders = fFoldersAsSourceFolder . getSelection ( ) ; fSrcFolderNameText . setEnabled ( useFolders ) ; fSrcFolderNameLabel . setEnabled ( useFolders ) ; if ( useFolders ) { String srcName = fSrcFolderNameText . getText ( ) ; if ( srcName . length ( ) == ) { updateStatus ( new StatusInfo ( IStatus . ERROR , PreferencesMessages . NewRubyProjectPreferencePage_folders_error_namesempty ) ) ; return ; } IWorkspace workspace = RubyPlugin . getWorkspace ( ) ; IProject dmy = workspace . getRoot ( ) . getProject ( "" ) ; IStatus status ; IPath srcPath = dmy . getFullPath ( ) . append ( srcName ) ; if ( srcName . length ( ) != ) { status = workspace . validatePath ( srcPath . toString ( ) , IResource . FOLDER ) ; if ( ! status . isOK ( ) ) { String message = Messages . format ( PreferencesMessages . NewRubyProjectPreferencePage_folders_error_invalidsrcname , status . getMessage ( ) ) ; updateStatus ( new StatusInfo ( IStatus . ERROR , message ) ) ; return ; } } ILoadpathEntry entry = RubyCore . newSourceEntry ( srcPath ) ; status = RubyConventions . validateLoadpath ( RubyCore . create ( dmy ) , new ILoadpathEntry [ ] { entry } , null ) ; if ( ! status . isOK ( ) ) { String message = PreferencesMessages . NewRubyProjectPreferencePage_folders_error_invalidcp ; updateStatus ( new StatusInfo ( IStatus . ERROR , message ) ) ; return ; } } updateStatus ( new StatusInfo ( ) ) ; } private void updateStatus ( IStatus status ) { setValid ( ! status . matches ( IStatus . ERROR ) ) ; StatusUtil . applyToStatusLine ( this , status ) ; } private void controlChanged ( Widget widget ) { if ( widget == fFoldersAsSourceFolder || widget == fProjectAsSourceFolder ) { validateFolders ( ) ; } } private void controlModified ( Widget widget ) { if ( widget == fSrcFolderNameText ) { validateFolders ( ) ; } } protected void performDefaults ( ) { IPreferenceStore store = getPreferenceStore ( ) ; for ( int i = ; i < fCheckBoxes . size ( ) ; i ++ ) { Button button = ( Button ) fCheckBoxes . get ( i ) ; String key = ( String ) button . getData ( ) ; button . setSelection ( store . getDefaultBoolean ( key ) ) ; } for ( int i = ; i < fRadioButtons . size ( ) ; i ++ ) { Button button = ( Button ) fRadioButtons . get ( i ) ; String [ ] info = ( String [ ] ) button . getData ( ) ; button . setSelection ( info [ ] . equals ( store . getDefaultString ( info [ ] ) ) ) ; } for ( int i = ; i < fTextControls . size ( ) ; i ++ ) { Text text = ( Text ) fTextControls . get ( i ) ; String key = ( String ) text . getData ( ) ; text . setText ( store . getDefaultString ( key ) ) ; } if ( fJRECombo != null ) { fJRECombo . select ( store . getDefaultInt ( LOADPATH_JRELIBRARY_INDEX ) ) ; } validateFolders ( ) ; super . performDefaults ( ) ; } public boolean performOk ( ) { IPreferenceStore store = getPreferenceStore ( ) ; for ( int i = ; i < fCheckBoxes . size ( ) ; i ++ ) { Button button = ( Button ) fCheckBoxes . get ( i ) ; String key = ( String ) button . getData ( ) ; store . setValue ( key , button . getSelection ( ) ) ; } for ( int i = ; i < fRadioButtons . size ( ) ; i ++ ) { Button button = ( Button ) fRadioButtons . get ( i ) ; if ( button . getSelection ( ) ) { String [ ] info = ( String [ ] ) button . getData ( ) ; store . setValue ( info [ ] , info [ ] ) ; } } for ( int i = ; i < fTextControls . size ( ) ; i ++ ) { Text text = ( Text ) fTextControls . get ( i ) ; String key = ( String ) text . getData ( ) ; store . setValue ( key , text . getText ( ) ) ; } if ( fJRECombo != null ) { store . setValue ( LOADPATH_JRELIBRARY_INDEX , fJRECombo . getSelectionIndex ( ) ) ; } RubyPlugin . getDefault ( ) . savePluginPreferences ( ) ; return super . performOk ( ) ; } private String [ ] getJRENames ( ) { String prefString = getPreferenceStore ( ) . getString ( LOADPATH_JRELIBRARY_LIST ) ; ArrayList list = new ArrayList ( ) ; StringTokenizer tok = new StringTokenizer ( prefString , "" ) ; while ( tok . hasMoreTokens ( ) ) { list . add ( decodeJRELibraryDescription ( tok . nextToken ( ) ) ) ; } return ( String [ ] ) list . toArray ( new String [ list . size ( ) ] ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . persistence . TemplatePersistenceData ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . texteditor . templates . TemplatePreferencePage ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubySourceViewer ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . SimpleRubySourceViewerConfiguration ; import org . rubypeople . rdt . internal . ui . text . template . contentassist . RubyTemplateAccess ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class RubyTemplatePreferencePage extends TemplatePreferencePage { public RubyTemplatePreferencePage ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setTemplateStore ( RubyTemplateAccess . getDefault ( ) . getTemplateStore ( ) ) ; setContextTypeRegistry ( RubyTemplateAccess . getDefault ( ) . getContextTypeRegistry ( ) ) ; } public boolean performOk ( ) { boolean ok = super . performOk ( ) ; RubyPlugin . getDefault ( ) . savePluginPreferences ( ) ; return ok ; } protected SourceViewer createViewer ( Composite parent ) { IDocument document = new Document ( ) ; RubyTextTools tools = RubyPlugin . getDefault ( ) . getRubyTextTools ( ) ; tools . setupRubyDocumentPartitioner ( document , IRubyPartitions . RUBY_PARTITIONING ) ; IPreferenceStore store = RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; SourceViewer viewer = new RubySourceViewer ( parent , null , null , false , SWT . BORDER | SWT . V_SCROLL | SWT . H_SCROLL , store ) ; SimpleRubySourceViewerConfiguration configuration = new SimpleRubySourceViewerConfiguration ( tools . getColorManager ( ) , store , null , IRubyPartitions . RUBY_PARTITIONING , false ) ; viewer . configure ( configuration ) ; viewer . setEditable ( false ) ; viewer . setDocument ( document ) ; Font font = JFaceResources . getFont ( PreferenceConstants . EDITOR_TEXT_FONT ) ; viewer . getTextWidget ( ) . setFont ( font ) ; new RubySourcePreviewerUpdater ( viewer , configuration , store ) ; Control control = viewer . getControl ( ) ; GridData data = new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . FILL_VERTICAL ) ; control . setLayoutData ( data ) ; return viewer ; } protected String getFormatterPreferenceKey ( ) { return PreferenceConstants . TEMPLATES_USE_CODEFORMATTER ; } protected void updateViewerInput ( ) { IStructuredSelection selection = ( IStructuredSelection ) getTableViewer ( ) . getSelection ( ) ; SourceViewer viewer = getViewer ( ) ; if ( selection . size ( ) == && selection . getFirstElement ( ) instanceof TemplatePersistenceData ) { TemplatePersistenceData data = ( TemplatePersistenceData ) selection . getFirstElement ( ) ; Template template = data . getTemplate ( ) ; String contextId = template . getContextTypeId ( ) ; IDocument doc = viewer . getDocument ( ) ; String start = null ; if ( "" . equals ( contextId ) ) { start = "" + doc . getLegalLineDelimiters ( ) [ ] ; } else start = "" ; doc . set ( start + template . getPattern ( ) ) ; int startLen = start . length ( ) ; viewer . setDocument ( doc , startLen , doc . getLength ( ) - startLen ) ; } else { viewer . getDocument ( ) . set ( "" ) ; } } protected boolean isShowFormatterSetting ( ) { return false ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . viewers . IFontProvider ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class KeywordConfigurationBlock extends OptionsConfigurationBlock { private static final Key PREF_COMPILER_TASK_TAGS = getRDTUIKey ( PreferenceConstants . EDITOR_USER_KEYWORDS ) ; private static final String ENABLED = RubyCore . ENABLED ; private static final String DISABLED = RubyCore . DISABLED ; public static class Keyword { public String name ; } private class KeywordLabelProvider extends LabelProvider implements ITableLabelProvider , IFontProvider { public KeywordLabelProvider ( ) { } public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { return getColumnText ( element , ) ; } public Image getColumnImage ( Object element , int columnIndex ) { return null ; } public String getColumnText ( Object element , int columnIndex ) { Keyword task = ( Keyword ) element ; if ( columnIndex == ) { return task . name ; } return "" ; } public Font getFont ( Object element ) { return null ; } } private static class TodoTaskSorter extends ViewerSorter { public int compare ( Viewer viewer , Object e1 , Object e2 ) { return collator . compare ( ( ( Keyword ) e1 ) . name , ( ( Keyword ) e2 ) . name ) ; } } private static final int IDX_ADD = ; private static final int IDX_EDIT = ; private static final int IDX_REMOVE = ; private IStatus fTaskTagsStatus ; private ListDialogField fTodoTasksList ; public KeywordConfigurationBlock ( IStatusChangeListener context , IProject project , IWorkbenchPreferenceContainer container ) { super ( context , project , getKeys ( ) , container ) ; KeywordAdapter adapter = new KeywordAdapter ( ) ; String [ ] buttons = new String [ ] { PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_add_button , PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_edit_button , PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_remove_button } ; fTodoTasksList = new ListDialogField ( adapter , buttons , new KeywordLabelProvider ( ) ) ; fTodoTasksList . setDialogFieldListener ( adapter ) ; fTodoTasksList . setRemoveButtonIndex ( IDX_REMOVE ) ; String [ ] columnsHeaders = new String [ ] { PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_name_column } ; fTodoTasksList . setTableColumns ( new ListDialogField . ColumnsDescription ( columnsHeaders , true ) ) ; fTodoTasksList . setViewerSorter ( new TodoTaskSorter ( ) ) ; unpackTodoTasks ( ) ; if ( fTodoTasksList . getSize ( ) > ) { fTodoTasksList . selectFirstElement ( ) ; } else { fTodoTasksList . enableButton ( IDX_EDIT , false ) ; } fTaskTagsStatus = new StatusInfo ( ) ; } public void setEnabled ( boolean isEnabled ) { fTodoTasksList . setEnabled ( isEnabled ) ; } private static Key [ ] getKeys ( ) { return new Key [ ] { PREF_COMPILER_TASK_TAGS } ; } public class KeywordAdapter implements IListAdapter , IDialogFieldListener { private boolean canEdit ( List selectedElements ) { return selectedElements . size ( ) == ; } public void customButtonPressed ( ListDialogField field , int index ) { doTodoButtonPressed ( index ) ; } public void selectionChanged ( ListDialogField field ) { List selectedElements = field . getSelectedElements ( ) ; field . enableButton ( IDX_EDIT , canEdit ( selectedElements ) ) ; } public void doubleClicked ( ListDialogField field ) { if ( canEdit ( field . getSelectedElements ( ) ) ) { doTodoButtonPressed ( IDX_EDIT ) ; } } public void dialogFieldChanged ( DialogField field ) { updateModel ( field ) ; } } protected Control createContents ( Composite parent ) { setShell ( parent . getShell ( ) ) ; Composite markersComposite = createMarkersTabContent ( parent ) ; validateSettings ( null , null , null ) ; return markersComposite ; } private Composite createMarkersTabContent ( Composite folder ) { GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; PixelConverter conv = new PixelConverter ( folder ) ; Composite markersComposite = new Composite ( folder , SWT . NULL ) ; markersComposite . setLayout ( layout ) ; markersComposite . setFont ( folder . getFont ( ) ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . widthHint = conv . convertWidthInCharsToPixels ( ) ; Control listControl = fTodoTasksList . getListControl ( markersComposite ) ; listControl . setLayoutData ( data ) ; Control buttonsControl = fTodoTasksList . getButtonBox ( markersComposite ) ; buttonsControl . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . VERTICAL_ALIGN_BEGINNING ) ) ; return markersComposite ; } protected void validateSettings ( Key changedKey , String oldValue , String newValue ) { if ( ! areSettingsEnabled ( ) ) { return ; } if ( changedKey != null ) { if ( PREF_COMPILER_TASK_TAGS . equals ( changedKey ) ) { fTaskTagsStatus = validateTaskTags ( ) ; } else { return ; } } else { fTaskTagsStatus = validateTaskTags ( ) ; } IStatus status = fTaskTagsStatus ; fContext . statusChanged ( status ) ; } private IStatus validateTaskTags ( ) { return new StatusInfo ( ) ; } protected final void updateModel ( DialogField field ) { if ( field == fTodoTasksList ) { StringBuffer tags = new StringBuffer ( ) ; List list = fTodoTasksList . getElements ( ) ; for ( int i = ; i < list . size ( ) ; i ++ ) { if ( i > ) { tags . append ( '' ) ; } Keyword elem = ( Keyword ) list . get ( i ) ; tags . append ( elem . name ) ; } setValue ( PREF_COMPILER_TASK_TAGS , tags . toString ( ) ) ; validateSettings ( PREF_COMPILER_TASK_TAGS , null , null ) ; } } protected String [ ] getFullBuildDialogStrings ( boolean workspaceSettings ) { return null ; } protected void updateControls ( ) { unpackTodoTasks ( ) ; } private void unpackTodoTasks ( ) { String currTags = getValue ( PREF_COMPILER_TASK_TAGS ) ; String [ ] tags = getTokens ( currTags , "" ) ; ArrayList elements = new ArrayList ( tags . length ) ; for ( int i = ; i < tags . length ; i ++ ) { Keyword task = new Keyword ( ) ; task . name = tags [ i ] . trim ( ) ; elements . add ( task ) ; } fTodoTasksList . setElements ( elements ) ; } private void doTodoButtonPressed ( int index ) { Keyword edited = null ; if ( index != IDX_ADD ) { edited = ( Keyword ) fTodoTasksList . getSelectedElements ( ) . get ( ) ; } if ( index == IDX_ADD || index == IDX_EDIT ) { KeywordInputDialog dialog = new KeywordInputDialog ( getShell ( ) , edited , fTodoTasksList . getElements ( ) ) ; if ( dialog . open ( ) == Window . OK ) { if ( edited != null ) { fTodoTasksList . replaceElement ( edited , dialog . getResult ( ) ) ; } else { fTodoTasksList . addElement ( dialog . getResult ( ) ) ; } } } } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . Set ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . SelectionStatusDialog ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; import org . rubypeople . rdt . ui . RubyElementSorter ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; public class ProjectSelectionDialog extends SelectionStatusDialog { private TableViewer fTableViewer ; private Set fProjectsWithSpecifics ; private final static int SIZING_SELECTION_WIDGET_HEIGHT = ; private final static int SIZING_SELECTION_WIDGET_WIDTH = ; private final static String DIALOG_SETTINGS_SHOW_ALL = "" ; private ViewerFilter fFilter ; public ProjectSelectionDialog ( Shell parentShell , Set projectsWithSpecifics ) { super ( parentShell ) ; setTitle ( PreferencesMessages . ProjectSelectionDialog_title ) ; setMessage ( PreferencesMessages . ProjectSelectionDialog_desciption ) ; fProjectsWithSpecifics = projectsWithSpecifics ; int shellStyle = getShellStyle ( ) ; setShellStyle ( shellStyle | SWT . MAX | SWT . RESIZE ) ; fFilter = new ViewerFilter ( ) { public boolean select ( Viewer viewer , Object parentElement , Object element ) { return fProjectsWithSpecifics . contains ( element ) ; } } ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Font font = parent . getFont ( ) ; composite . setFont ( font ) ; createMessageArea ( composite ) ; fTableViewer = new TableViewer ( composite , SWT . H_SCROLL | SWT . V_SCROLL | SWT . BORDER ) ; fTableViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { doSelectionChanged ( ( ( IStructuredSelection ) event . getSelection ( ) ) . toArray ( ) ) ; } } ) ; fTableViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { okPressed ( ) ; } } ) ; GridData data = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; data . heightHint = SIZING_SELECTION_WIDGET_HEIGHT ; data . widthHint = SIZING_SELECTION_WIDGET_WIDTH ; fTableViewer . getTable ( ) . setLayoutData ( data ) ; fTableViewer . setLabelProvider ( new RubyElementLabelProvider ( ) ) ; fTableViewer . setContentProvider ( new StandardRubyElementContentProvider ( ) ) ; fTableViewer . setSorter ( new RubyElementSorter ( ) ) ; fTableViewer . getControl ( ) . setFont ( font ) ; Button checkbox = new Button ( composite , SWT . CHECK ) ; checkbox . setText ( PreferencesMessages . ProjectSelectionDialog_filter ) ; checkbox . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . CENTER , true , false ) ) ; checkbox . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { updateFilter ( ( ( Button ) e . widget ) . getSelection ( ) ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { updateFilter ( ( ( Button ) e . widget ) . getSelection ( ) ) ; } } ) ; IDialogSettings dialogSettings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; boolean doFilter = ! dialogSettings . getBoolean ( DIALOG_SETTINGS_SHOW_ALL ) && ! fProjectsWithSpecifics . isEmpty ( ) ; checkbox . setSelection ( doFilter ) ; updateFilter ( doFilter ) ; IRubyModel input = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; fTableViewer . setInput ( input ) ; doSelectionChanged ( new Object [ ] ) ; Dialog . applyDialogFont ( composite ) ; return composite ; } protected void updateFilter ( boolean selected ) { if ( selected ) { fTableViewer . addFilter ( fFilter ) ; } else { fTableViewer . removeFilter ( fFilter ) ; } RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( DIALOG_SETTINGS_SHOW_ALL , ! selected ) ; } private void doSelectionChanged ( Object [ ] objects ) { if ( objects . length != ) { updateStatus ( new StatusInfo ( IStatus . ERROR , "" ) ) ; setSelectionResult ( null ) ; } else { updateStatus ( new StatusInfo ( ) ) ; setSelectionResult ( objects ) ; } } protected void computeResult ( ) { } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class TodoTaskPreferencePage extends PropertyAndPreferencePage { public static final String PREF_ID = "" ; public static final String PROP_ID = "" ; private TodoTaskConfigurationBlock fConfigurationBlock ; public TodoTaskPreferencePage ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( PreferencesMessages . TodoTaskPreferencePage_description ) ; setTitle ( PreferencesMessages . TodoTaskPreferencePage_title ) ; } public void createControl ( Composite parent ) { IWorkbenchPreferenceContainer container = ( IWorkbenchPreferenceContainer ) getContainer ( ) ; fConfigurationBlock = new TodoTaskConfigurationBlock ( getNewStatusChangedListener ( ) , getProject ( ) , container ) ; super . createControl ( parent ) ; if ( isProjectPreferencePage ( ) ) { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . TODOTASK_PROPERTY_PAGE ) ; } else { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . TODOTASK_PREFERENCE_PAGE ) ; } } protected Control createPreferenceContent ( Composite composite ) { return fConfigurationBlock . createContents ( composite ) ; } protected boolean hasProjectSpecificOptions ( IProject project ) { return fConfigurationBlock . hasProjectSpecificOptions ( project ) ; } protected String getPreferencePageID ( ) { return PREF_ID ; } protected String getPropertyPageID ( ) { return PROP_ID ; } protected void enableProjectSpecificSettings ( boolean useProjectSpecificSettings ) { super . enableProjectSpecificSettings ( useProjectSpecificSettings ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . useProjectSpecificSettings ( useProjectSpecificSettings ) ; } } protected void performDefaults ( ) { super . performDefaults ( ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . performDefaults ( ) ; } } public boolean performOk ( ) { if ( fConfigurationBlock != null && ! fConfigurationBlock . performOk ( ) ) { return false ; } return super . performOk ( ) ; } public void performApply ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . performApply ( ) ; } } public void dispose ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . dispose ( ) ; } super . dispose ( ) ; } public void setElement ( IAdaptable element ) { super . setElement ( element ) ; setDescription ( null ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . rubypeople . rdt . ui . PreferenceConstants ; class SmartTypingConfigurationBlock extends AbstractConfigurationBlock { public SmartTypingConfigurationBlock ( OverlayPreferenceStore store ) { super ( store ) ; store . addKeys ( createOverlayStoreKeys ( ) ) ; } private OverlayPreferenceStore . OverlayKey [ ] createOverlayStoreKeys ( ) { return new OverlayPreferenceStore . OverlayKey [ ] { new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_CLOSE_STRINGS ) , new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_CLOSE_BRACKETS ) , new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_CLOSE_BRACES ) , new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_END_STATEMENTS ) } ; } public Control createControl ( Composite parent ) { ScrolledPageContent scrolled = new ScrolledPageContent ( parent , SWT . H_SCROLL | SWT . V_SCROLL ) ; scrolled . setExpandHorizontal ( true ) ; scrolled . setExpandVertical ( true ) ; Composite control = new Composite ( scrolled , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; control . setLayout ( layout ) ; Composite composite ; composite = createSubsection ( control , null , PreferencesMessages . SmartTypingConfigurationBlock_autoclose_title ) ; addAutoclosingSection ( composite ) ; scrolled . setContent ( control ) ; final Point size = control . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; scrolled . setMinSize ( size . x , size . y ) ; return scrolled ; } private void addAutoclosingSection ( Composite composite ) { GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; String label ; label = PreferencesMessages . RubyEditorPreferencePage_closeStrings ; addCheckBox ( composite , label , PreferenceConstants . EDITOR_CLOSE_STRINGS , ) ; label = PreferencesMessages . RubyEditorPreferencePage_closeBrackets ; addCheckBox ( composite , label , PreferenceConstants . EDITOR_CLOSE_BRACKETS , ) ; label = PreferencesMessages . RubyEditorPreferencePage_closeBraces ; addCheckBox ( composite , label , PreferenceConstants . EDITOR_CLOSE_BRACES , ) ; label = PreferencesMessages . RubyEditorPreferencePage_endStatements ; addCheckBox ( composite , label , PreferenceConstants . EDITOR_END_STATEMENTS , ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Font ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . RubySourceViewerConfiguration ; class RubySourcePreviewerUpdater { RubySourcePreviewerUpdater ( final SourceViewer viewer , final RubySourceViewerConfiguration configuration , final IPreferenceStore preferenceStore ) { Assert . isNotNull ( viewer ) ; Assert . isNotNull ( configuration ) ; Assert . isNotNull ( preferenceStore ) ; final IPropertyChangeListener fontChangeListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( PreferenceConstants . EDITOR_TEXT_FONT ) ) { Font font = JFaceResources . getFont ( PreferenceConstants . EDITOR_TEXT_FONT ) ; viewer . getTextWidget ( ) . setFont ( font ) ; } } } ; final IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { if ( configuration . affectsTextPresentation ( event ) ) { configuration . handlePropertyChangeEvent ( event ) ; viewer . invalidateTextPresentation ( ) ; } } } ; viewer . getTextWidget ( ) . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { preferenceStore . removePropertyChangeListener ( propertyChangeListener ) ; JFaceResources . getFontRegistry ( ) . removeListener ( fontChangeListener ) ; } } ) ; JFaceResources . getFontRegistry ( ) . addListener ( fontChangeListener ) ; preferenceStore . addPropertyChangeListener ( propertyChangeListener ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . Separator ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class AppearancePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String PREF_METHOD_PARAMETER_NAMES = PreferenceConstants . APPEARANCE_METHOD_PARAMETER_NAMES ; private static final String STACK_BROWSING_VIEWS_VERTICALLY = PreferenceConstants . BROWSING_STACK_VERTICALLY ; public static final String PREF_COLORED_LABELS = "" ; private SelectionButtonDialogField fStackBrowsingViewsVertically ; private SelectionButtonDialogField fShowMethodParameterNames ; public AppearancePreferencePage ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( PreferencesMessages . AppearancePreferencePage_description ) ; IDialogFieldListener listener = new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { doDialogFieldChanged ( field ) ; } } ; fShowMethodParameterNames = new SelectionButtonDialogField ( SWT . CHECK ) ; fShowMethodParameterNames . setDialogFieldListener ( listener ) ; fShowMethodParameterNames . setLabelText ( PreferencesMessages . AppearancePreferencePage_methodtypeparams_label ) ; fStackBrowsingViewsVertically = new SelectionButtonDialogField ( SWT . CHECK ) ; fStackBrowsingViewsVertically . setDialogFieldListener ( listener ) ; fStackBrowsingViewsVertically . setLabelText ( PreferencesMessages . AppearancePreferencePage_stackViewsVerticallyInTheRubyBrowsingPerspective ) ; } private void initFields ( ) { IPreferenceStore prefs = getPreferenceStore ( ) ; fShowMethodParameterNames . setSelection ( prefs . getBoolean ( PREF_METHOD_PARAMETER_NAMES ) ) ; fStackBrowsingViewsVertically . setSelection ( prefs . getBoolean ( STACK_BROWSING_VIEWS_VERTICALLY ) ) ; } public void createControl ( Composite parent ) { super . createControl ( parent ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . APPEARANCE_PREFERENCE_PAGE ) ; } protected Control createContents ( Composite parent ) { initializeDialogUnits ( parent ) ; int nColumns = ; Composite result = new Composite ( parent , SWT . NONE ) ; result . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = ; layout . numColumns = nColumns ; result . setLayout ( layout ) ; fShowMethodParameterNames . doFillIntoGrid ( result , nColumns ) ; new Separator ( ) . doFillIntoGrid ( result , nColumns ) ; fStackBrowsingViewsVertically . doFillIntoGrid ( result , nColumns ) ; String noteTitle = PreferencesMessages . AppearancePreferencePage_note ; String noteMessage = PreferencesMessages . AppearancePreferencePage_preferenceOnlyEffectiveForNewPerspectives ; Composite noteControl = createNoteComposite ( JFaceResources . getDialogFont ( ) , result , noteTitle , noteMessage ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; noteControl . setLayoutData ( gd ) ; initFields ( ) ; Dialog . applyDialogFont ( result ) ; return result ; } private void doDialogFieldChanged ( DialogField field ) { updateStatus ( getValidationStatus ( ) ) ; } private IStatus getValidationStatus ( ) { return new StatusInfo ( ) ; } private void updateStatus ( IStatus status ) { setValid ( ! status . matches ( IStatus . ERROR ) ) ; StatusUtil . applyToStatusLine ( this , status ) ; } public void init ( IWorkbench workbench ) { } public boolean performOk ( ) { IPreferenceStore prefs = getPreferenceStore ( ) ; prefs . setValue ( PREF_METHOD_PARAMETER_NAMES , fShowMethodParameterNames . isSelected ( ) ) ; prefs . setValue ( STACK_BROWSING_VIEWS_VERTICALLY , fStackBrowsingViewsVertically . isSelected ( ) ) ; RubyPlugin . getDefault ( ) . savePluginPreferences ( ) ; return super . performOk ( ) ; } protected void performDefaults ( ) { IPreferenceStore prefs = getPreferenceStore ( ) ; fShowMethodParameterNames . setSelection ( prefs . getDefaultBoolean ( PREF_METHOD_PARAMETER_NAMES ) ) ; fStackBrowsingViewsVertically . setSelection ( prefs . getDefaultBoolean ( STACK_BROWSING_VIEWS_VERTICALLY ) ) ; super . performDefaults ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . io . IOException ; import java . net . URL ; import java . text . MessageFormat ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . jface . preference . BooleanFieldEditor ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import org . rubypeople . rdt . internal . ui . text . PreferencesAdapter ; public class DebuggerPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public DebuggerPreferencePage ( ) { super ( GRID ) ; Preferences launchingPreferences = LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) ; setPreferenceStore ( new PreferencesAdapter ( launchingPreferences ) ) ; setDescription ( PreferencesMessages . DebuggerPreferencePage_description_label ) ; } public void createFieldEditors ( ) { addField ( new BooleanFieldEditor ( org . rubypeople . rdt . internal . launching . PreferenceConstants . USE_RUBY_DEBUG , PreferencesMessages . DebuggerPreferencePage_useRubyDebug_label , getFieldEditorParent ( ) ) ) ; addField ( new BooleanFieldEditor ( org . rubypeople . rdt . internal . launching . PreferenceConstants . VERBOSE_DEBUGGER , PreferencesMessages . DebuggerPreferencePage_verboseDebugger_label , getFieldEditorParent ( ) ) ) ; } protected Control createContents ( Composite parent ) { Control result = super . createContents ( parent ) ; Label label = new Label ( parent , SWT . WRAP ) ; URL entry = LaunchingPlugin . getDefault ( ) . getBundle ( ) . getEntry ( "" ) ; String installLocation ; try { installLocation = FileLocator . resolve ( entry ) . toString ( ) ; } catch ( IOException e ) { installLocation = "" ; } String message = MessageFormat . format ( PreferencesMessages . DebuggerPreferencePage_useRubyDebug_comment , new Object [ ] { installLocation } ) ; label . setText ( message ) ; FontData [ ] fontData = getFont ( ) . getFontData ( ) ; if ( fontData . length > ) { FontData italicFont = new FontData ( fontData [ ] . getName ( ) , fontData [ ] . getHeight ( ) , SWT . ITALIC ) ; label . setFont ( new Font ( null , italicFont ) ) ; } return result ; } public void init ( IWorkbench workbench ) { } } package org . rubypeople . rdt . internal . ui . preferences ; import java . lang . reflect . InvocationTargetException ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . jface . preference . IPreferencePageContainer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . dialogs . PropertyPage ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . BusyIndicatorRunnableContext ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . WorkbenchRunnableAdapter ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . BuildPathsBlock ; public class BuildPathsPropertyPage extends PropertyPage implements IStatusChangeListener { public static final String PROP_ID = "" ; private static final String PAGE_SETTINGS = "" ; private static final String INDEX = "" ; public static final Object DATA_ADD_ENTRY = "" ; public static final Object DATA_REVEAL_ENTRY = "" ; public static final Object DATA_REVEAL_ATTRIBUTE_KEY = "" ; public static final Object DATA_BLOCK = "" ; private BuildPathsBlock fBuildPathsBlock ; private boolean fBlockOnApply = false ; protected Control createContents ( Composite parent ) { noDefaultAndApplyButton ( ) ; IProject project = getProject ( ) ; Control result ; if ( project == null || ! isRubyProject ( project ) ) { result = createWithoutRuby ( parent ) ; } else if ( ! project . isOpen ( ) ) { result = createForClosedProject ( parent ) ; } else { result = createWithRuby ( parent , project ) ; } Dialog . applyDialogFont ( result ) ; return result ; } public void createControl ( Composite parent ) { super . createControl ( parent ) ; } private IDialogSettings getSettings ( ) { IDialogSettings javaSettings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; IDialogSettings pageSettings = javaSettings . getSection ( PAGE_SETTINGS ) ; if ( pageSettings == null ) { pageSettings = javaSettings . addNewSection ( PAGE_SETTINGS ) ; pageSettings . put ( INDEX , ) ; } return pageSettings ; } public void setVisible ( boolean visible ) { if ( fBuildPathsBlock != null ) { if ( ! visible ) { if ( fBuildPathsBlock . hasChangesInDialog ( ) ) { String title = PreferencesMessages . BuildPathsPropertyPage_unsavedchanges_title ; String message = PreferencesMessages . BuildPathsPropertyPage_unsavedchanges_message ; String [ ] buttonLabels = new String [ ] { PreferencesMessages . BuildPathsPropertyPage_unsavedchanges_button_save , PreferencesMessages . BuildPathsPropertyPage_unsavedchanges_button_discard , PreferencesMessages . BuildPathsPropertyPage_unsavedchanges_button_ignore } ; MessageDialog dialog = new MessageDialog ( getShell ( ) , title , null , message , MessageDialog . QUESTION , buttonLabels , ) ; int res = dialog . open ( ) ; if ( res == ) { performOk ( ) ; } else if ( res == ) { fBuildPathsBlock . init ( RubyCore . create ( getProject ( ) ) , null , null ) ; } else { } } } else { if ( ! fBuildPathsBlock . hasChangesInDialog ( ) && fBuildPathsBlock . hasChangesInLoadpathFile ( ) ) { fBuildPathsBlock . init ( RubyCore . create ( getProject ( ) ) , null , null ) ; } } } super . setVisible ( visible ) ; } private Control createWithRuby ( Composite parent , IProject project ) { IWorkbenchPreferenceContainer pageContainer = null ; IPreferencePageContainer container = getContainer ( ) ; if ( container instanceof IWorkbenchPreferenceContainer ) { pageContainer = ( IWorkbenchPreferenceContainer ) container ; } fBuildPathsBlock = new BuildPathsBlock ( new BusyIndicatorRunnableContext ( ) , this , getSettings ( ) . getInt ( INDEX ) , false , pageContainer ) ; fBuildPathsBlock . init ( RubyCore . create ( project ) , null , null ) ; return fBuildPathsBlock . createControl ( parent ) ; } private Control createWithoutRuby ( Composite parent ) { Label label = new Label ( parent , SWT . LEFT ) ; label . setText ( PreferencesMessages . BuildPathsPropertyPage_no_java_project_message ) ; fBuildPathsBlock = null ; setValid ( true ) ; return label ; } private Control createForClosedProject ( Composite parent ) { Label label = new Label ( parent , SWT . LEFT ) ; label . setText ( PreferencesMessages . BuildPathsPropertyPage_closed_project_message ) ; fBuildPathsBlock = null ; setValid ( true ) ; return label ; } private IProject getProject ( ) { IAdaptable adaptable = getElement ( ) ; if ( adaptable != null ) { IRubyElement elem = ( IRubyElement ) adaptable . getAdapter ( IRubyElement . class ) ; if ( elem instanceof IRubyProject ) { return ( ( IRubyProject ) elem ) . getProject ( ) ; } } return null ; } private boolean isRubyProject ( IProject proj ) { try { return proj . hasNature ( RubyCore . NATURE_ID ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } return false ; } public boolean performOk ( ) { if ( fBuildPathsBlock != null ) { getSettings ( ) . put ( INDEX , fBuildPathsBlock . getPageIndex ( ) ) ; if ( fBuildPathsBlock . hasChangesInDialog ( ) ) { IWorkspaceRunnable runnable = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException , OperationCanceledException { fBuildPathsBlock . configureRubyProject ( monitor ) ; } } ; WorkbenchRunnableAdapter op = new WorkbenchRunnableAdapter ( runnable ) ; if ( fBlockOnApply ) { try { new ProgressMonitorDialog ( getShell ( ) ) . run ( true , true , op ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , getShell ( ) , PreferencesMessages . BuildPathsPropertyPage_error_title , PreferencesMessages . BuildPathsPropertyPage_error_message ) ; return false ; } catch ( InterruptedException e ) { return false ; } } else { op . runAsUserJob ( PreferencesMessages . BuildPathsPropertyPage_job_title , null ) ; } } } return true ; } public void statusChanged ( IStatus status ) { setValid ( ! status . matches ( IStatus . ERROR ) ) ; StatusUtil . applyToStatusLine ( this , status ) ; } public void applyData ( Object data ) { if ( data instanceof Map ) { Map map = ( Map ) data ; Object selectedLibrary = map . get ( DATA_REVEAL_ENTRY ) ; if ( selectedLibrary instanceof ILoadpathEntry ) { ILoadpathEntry entry = ( ILoadpathEntry ) selectedLibrary ; Object attr = map . get ( DATA_REVEAL_ATTRIBUTE_KEY ) ; String attributeKey = attr instanceof String ? ( String ) attr : null ; if ( fBuildPathsBlock != null ) { fBuildPathsBlock . setElementToReveal ( entry , attributeKey ) ; } } Object entryToAdd = map . get ( DATA_ADD_ENTRY ) ; if ( entryToAdd instanceof ILoadpathEntry ) { if ( fBuildPathsBlock != null ) { fBuildPathsBlock . addElement ( ( ILoadpathEntry ) entryToAdd ) ; } } fBlockOnApply = Boolean . TRUE . equals ( map . get ( DATA_BLOCK ) ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . jface . preference . IPreferenceNode ; import org . eclipse . jface . preference . IPreferencePage ; import org . eclipse . jface . preference . PreferenceDialog ; import org . eclipse . jface . preference . PreferenceManager ; import org . eclipse . jface . preference . PreferenceNode ; import org . eclipse . jface . window . Window ; public class PreferencePageSupport { private PreferencePageSupport ( ) { super ( ) ; } public static boolean showPreferencePage ( Shell shell , String id , IPreferencePage page ) { final IPreferenceNode targetNode = new PreferenceNode ( id , page ) ; PreferenceManager manager = new PreferenceManager ( ) ; manager . addToRoot ( targetNode ) ; final PreferenceDialog dialog = new PreferenceDialog ( shell , manager ) ; final boolean [ ] result = new boolean [ ] { false } ; BusyIndicator . showWhile ( shell . getDisplay ( ) , new Runnable ( ) { public void run ( ) { dialog . create ( ) ; dialog . setMessage ( targetNode . getLabelText ( ) ) ; result [ ] = ( dialog . open ( ) == Window . OK ) ; } } ) ; return result [ ] ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . dialogs . StatusDialog ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ComboDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; import org . rubypeople . rdt . internal . ui . preferences . TodoTaskConfigurationBlock . TodoTask ; public class TodoTaskInputDialog extends StatusDialog { private class CompilerTodoTaskInputAdapter implements IDialogFieldListener { public void dialogFieldChanged ( DialogField field ) { doValidation ( ) ; } } private StringDialogField fNameDialogField ; private ComboDialogField fPriorityDialogField ; private List fExistingNames ; public TodoTaskInputDialog ( Shell parent , TodoTask task , List existingEntries ) { super ( parent ) ; fExistingNames = new ArrayList ( existingEntries . size ( ) ) ; for ( int i = ; i < existingEntries . size ( ) ; i ++ ) { TodoTask curr = ( TodoTask ) existingEntries . get ( i ) ; if ( ! curr . equals ( task ) ) { fExistingNames . add ( curr . name ) ; } } if ( task == null ) { setTitle ( PreferencesMessages . TodoTaskInputDialog_new_title ) ; } else { setTitle ( PreferencesMessages . TodoTaskInputDialog_edit_title ) ; } CompilerTodoTaskInputAdapter adapter = new CompilerTodoTaskInputAdapter ( ) ; fNameDialogField = new StringDialogField ( ) ; fNameDialogField . setLabelText ( PreferencesMessages . TodoTaskInputDialog_name_label ) ; fNameDialogField . setDialogFieldListener ( adapter ) ; fNameDialogField . setText ( ( task != null ) ? task . name : "" ) ; String [ ] items = new String [ ] { PreferencesMessages . TodoTaskInputDialog_priority_high , PreferencesMessages . TodoTaskInputDialog_priority_normal , PreferencesMessages . TodoTaskInputDialog_priority_low } ; fPriorityDialogField = new ComboDialogField ( SWT . READ_ONLY ) ; fPriorityDialogField . setLabelText ( PreferencesMessages . TodoTaskInputDialog_priority_label ) ; fPriorityDialogField . setItems ( items ) ; if ( task != null ) { if ( RubyCore . COMPILER_TASK_PRIORITY_HIGH . equals ( task . priority ) ) { fPriorityDialogField . selectItem ( ) ; } else if ( RubyCore . COMPILER_TASK_PRIORITY_NORMAL . equals ( task . priority ) ) { fPriorityDialogField . selectItem ( ) ; } else { fPriorityDialogField . selectItem ( ) ; } } else { fPriorityDialogField . selectItem ( ) ; } } public TodoTask getResult ( ) { TodoTask task = new TodoTask ( ) ; task . name = fNameDialogField . getText ( ) . trim ( ) ; switch ( fPriorityDialogField . getSelectionIndex ( ) ) { case : task . priority = RubyCore . COMPILER_TASK_PRIORITY_HIGH ; break ; case : task . priority = RubyCore . COMPILER_TASK_PRIORITY_NORMAL ; break ; default : task . priority = RubyCore . COMPILER_TASK_PRIORITY_LOW ; break ; } return task ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; inner . setLayout ( layout ) ; fNameDialogField . doFillIntoGrid ( inner , ) ; fPriorityDialogField . doFillIntoGrid ( inner , ) ; LayoutUtil . setHorizontalGrabbing ( fNameDialogField . getTextControl ( null ) ) ; LayoutUtil . setWidthHint ( fNameDialogField . getTextControl ( null ) , convertWidthInCharsToPixels ( ) ) ; fNameDialogField . postSetFocusOnDialogField ( parent . getDisplay ( ) ) ; applyDialogFont ( composite ) ; return composite ; } private void doValidation ( ) { StatusInfo status = new StatusInfo ( ) ; String newText = fNameDialogField . getText ( ) ; if ( newText . length ( ) == ) { status . setError ( PreferencesMessages . TodoTaskInputDialog_error_enterName ) ; } else { if ( newText . indexOf ( '' ) != - ) { status . setError ( PreferencesMessages . TodoTaskInputDialog_error_comma ) ; } else if ( fExistingNames . contains ( newText ) ) { status . setError ( PreferencesMessages . TodoTaskInputDialog_error_entryExists ) ; } else if ( Character . isWhitespace ( newText . charAt ( ) ) || Character . isWhitespace ( newText . charAt ( newText . length ( ) - ) ) ) { status . setError ( PreferencesMessages . TodoTaskInputDialog_error_noSpace ) ; } } updateStatus ( status ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . forms . widgets . ExpandableComposite ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; public class ProblemSeveritiesConfigurationBlock extends OptionsConfigurationBlock { private static final String SETTINGS_SECTION_NAME = null ; private static final String ERROR = RubyCore . ERROR ; private static final String WARNING = RubyCore . WARNING ; private static final String IGNORE = RubyCore . IGNORE ; private static final String ENABLED = RubyCore . ENABLED ; private static final String DISABLED = RubyCore . DISABLED ; private static Key [ ] fgKeys ; private static Map < String , String > fgCategories ; private static HashMap < String , List < Error > > fgErrors ; private PixelConverter fPixelConverter ; private IStatus fStatus ; public ProblemSeveritiesConfigurationBlock ( IStatusChangeListener context , IProject project , IWorkbenchPreferenceContainer container ) { super ( context , project , getKeys ( ) , container ) ; fStatus = new StatusInfo ( ) ; } private static List < IConfigurationElement > getErrorProviderElements ( ) { List < IConfigurationElement > elements = new ArrayList < IConfigurationElement > ( ) ; IExtensionPoint extension = Platform . getExtensionRegistry ( ) . getExtensionPoint ( RubyCore . PLUGIN_ID , "" ) ; if ( extension == null ) return elements ; IExtension [ ] extensions = extension . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] configElements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < configElements . length ; j ++ ) elements . add ( configElements [ j ] ) ; } return elements ; } private static Map < String , String > getErrorCategories ( ) { if ( fgCategories != null ) return fgCategories ; Map < String , String > categories = new HashMap < String , String > ( ) ; List < IConfigurationElement > configElements = getErrorProviderElements ( ) ; for ( IConfigurationElement configElement : configElements ) { String name = configElement . getName ( ) ; String contributorName = configElement . getContributor ( ) . getName ( ) ; if ( name . equals ( "" ) ) { categories . put ( configElement . getAttribute ( "" ) , configElement . getAttribute ( "" ) ) ; } } fgCategories = categories ; return fgCategories ; } private static class Error { private String id ; private String label ; private String contributor ; private String argument ; private String type ; private String argumentLabel ; Error ( IConfigurationElement element ) { this . id = element . getAttribute ( "" ) ; this . label = element . getAttribute ( "" ) ; this . contributor = element . getContributor ( ) . getName ( ) ; IConfigurationElement [ ] elements = element . getChildren ( "" ) ; if ( elements != null && elements . length > ) { this . argument = elements [ ] . getAttribute ( "" ) ; this . type = elements [ ] . getAttribute ( "" ) ; if ( type == null ) { type = "" ; } this . argumentLabel = elements [ ] . getAttribute ( "" ) ; if ( this . argumentLabel == null ) { this . argumentLabel = "" ; } } } public boolean hasArgument ( ) { return argument != null ; } public String getContributor ( ) { return contributor ; } public String getId ( ) { return id ; } public String getLabel ( ) { return label ; } public String getArgument ( ) { return argument ; } public String getArgumentLabel ( ) { return argumentLabel ; } public boolean argumentIsInt ( ) { return hasArgument ( ) && type . equals ( "" ) ; } } private static Key [ ] getKeys ( ) { if ( fgKeys != null ) return fgKeys ; List < Key > keys = new ArrayList < Key > ( ) ; Map < String , String > categories = getErrorCategories ( ) ; for ( String categoryId : categories . keySet ( ) ) { List < Error > errors = getErrors ( categoryId ) ; for ( Error error : errors ) { keys . add ( getKey ( error . getContributor ( ) , error . getId ( ) ) ) ; } } fgKeys = keys . toArray ( new Key [ keys . size ( ) ] ) ; return fgKeys ; } protected Control createContents ( Composite parent ) { fPixelConverter = new PixelConverter ( parent ) ; setShell ( parent . getShell ( ) ) ; Composite mainComp = new Composite ( parent , SWT . NONE ) ; mainComp . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; mainComp . setLayout ( layout ) ; Composite commonComposite = createStyleTabContent ( mainComp ) ; GridData gridData = new GridData ( GridData . FILL , GridData . FILL , true , true ) ; gridData . heightHint = fPixelConverter . convertHeightInCharsToPixels ( ) ; commonComposite . setLayoutData ( gridData ) ; validateSettings ( null , null , null ) ; return mainComp ; } private Composite createStyleTabContent ( Composite folder ) { String [ ] errorWarningIgnore = new String [ ] { ERROR , WARNING , IGNORE } ; String [ ] errorWarningIgnoreLabels = new String [ ] { PreferencesMessages . ProblemSeveritiesConfigurationBlock_error , PreferencesMessages . ProblemSeveritiesConfigurationBlock_warning , PreferencesMessages . ProblemSeveritiesConfigurationBlock_ignore } ; String [ ] enabledDisabled = new String [ ] { ENABLED , DISABLED } ; int nColumns = ; final ScrolledPageContent sc1 = new ScrolledPageContent ( folder ) ; Composite composite = sc1 . getBody ( ) ; GridLayout layout = new GridLayout ( nColumns , false ) ; layout . marginHeight = ; layout . marginWidth = ; composite . setLayout ( layout ) ; Label description = new Label ( composite , SWT . LEFT | SWT . WRAP ) ; description . setFont ( description . getFont ( ) ) ; description . setText ( PreferencesMessages . ProblemSeveritiesConfigurationBlock_common_description ) ; description . setLayoutData ( new GridData ( GridData . BEGINNING , GridData . CENTER , true , false , nColumns - , ) ) ; int indentStep = fPixelConverter . convertWidthInCharsToPixels ( ) ; int defaultIndent = indentStep * ; int extraIndent = indentStep * ; String label ; ExpandableComposite excomposite ; Composite inner ; Map < String , String > categories = getErrorCategories ( ) ; for ( String categoryId : categories . keySet ( ) ) { List < Error > errors = getErrors ( categoryId ) ; if ( errors == null || errors . isEmpty ( ) ) continue ; excomposite = createStyleSection ( composite , categories . get ( categoryId ) , nColumns ) ; inner = new Composite ( excomposite , SWT . NONE ) ; inner . setFont ( composite . getFont ( ) ) ; inner . setLayout ( new GridLayout ( nColumns , false ) ) ; excomposite . setClient ( inner ) ; for ( Error error : errors ) { addComboBox ( inner , error . label + '' , getKey ( error . getContributor ( ) , error . getId ( ) ) , errorWarningIgnore , errorWarningIgnoreLabels , defaultIndent ) ; if ( error . hasArgument ( ) ) { Text text = addTextField ( inner , error . getArgumentLabel ( ) , getKey ( error . getContributor ( ) , error . getArgument ( ) ) , , ) ; GridData gd = ( GridData ) text . getLayoutData ( ) ; gd . widthHint = fPixelConverter . convertWidthInCharsToPixels ( ) ; gd . horizontalAlignment = GridData . END ; text . setTextLimit ( ) ; } } } IDialogSettings section = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( SETTINGS_SECTION_NAME ) ; restoreSectionExpansionStates ( section ) ; return sc1 ; } private static List < Error > getErrors ( String categoryId ) { if ( fgErrors == null ) { fgErrors = new HashMap < String , List < Error > > ( ) ; } if ( fgErrors . get ( categoryId ) != null ) return fgErrors . get ( categoryId ) ; List < Error > categories = new ArrayList < Error > ( ) ; List < IConfigurationElement > configElements = getErrorProviderElements ( ) ; for ( IConfigurationElement configElement : configElements ) { String name = configElement . getName ( ) ; if ( name . equals ( "" ) && configElement . getAttribute ( "" ) . equals ( categoryId ) ) { categories . add ( new Error ( configElement ) ) ; } } fgErrors . put ( categoryId , categories ) ; return categories ; } protected void validateSettings ( Key changedKey , String oldValue , String newValue ) { if ( ! areSettingsEnabled ( ) ) { return ; } if ( changedKey != null ) { List < Error > errors = getErrors ( ) ; for ( Error error : errors ) { if ( error . hasArgument ( ) && error . argumentIsInt ( ) && changedKey . getName ( ) . equals ( error . getArgument ( ) ) ) { fStatus = validateMaxNumber ( changedKey , error . getLabel ( ) ) ; fContext . statusChanged ( fStatus ) ; return ; } } } else { updateEnableStates ( ) ; } IStatus status = StatusUtil . getMostSevere ( new IStatus [ ] { fStatus } ) ; fContext . statusChanged ( status ) ; } private static List < Error > getErrors ( ) { List < Error > errors = new ArrayList < Error > ( ) ; Map < String , String > categories = getErrorCategories ( ) ; for ( String categoryId : categories . keySet ( ) ) { errors . addAll ( getErrors ( categoryId ) ) ; } return errors ; } private IStatus validateMaxNumber ( Key key , String label ) { String number = getValue ( key ) ; StatusInfo status = new StatusInfo ( ) ; if ( number . length ( ) == ) { status . setError ( PreferencesMessages . RubyBuildConfigurationBlock_empty_input ) ; } else { try { int value = Integer . parseInt ( number ) ; if ( value <= ) { status . setError ( Messages . format ( PreferencesMessages . RubyBuildConfigurationBlock_invalid_input , new Object [ ] { number , label } ) ) ; } } catch ( NumberFormatException e ) { status . setError ( Messages . format ( PreferencesMessages . RubyBuildConfigurationBlock_invalid_input , new Object [ ] { number , label } ) ) ; } } return status ; } private void updateEnableStates ( ) { } protected String [ ] getFullBuildDialogStrings ( boolean workspaceSettings ) { String title = PreferencesMessages . ProblemSeveritiesConfigurationBlock_needsbuild_title ; String message ; if ( workspaceSettings ) { message = PreferencesMessages . ProblemSeveritiesConfigurationBlock_needsfullbuild_message ; } else { message = PreferencesMessages . ProblemSeveritiesConfigurationBlock_needsprojectbuild_message ; } return new String [ ] { title , message } ; } public void dispose ( ) { IDialogSettings section = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( SETTINGS_SECTION_NAME ) ; storeSectionExpansionStates ( section ) ; super . dispose ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public abstract class RubyAbstractPreferencePage extends PreferencePage { protected OverlayPreferenceStore fOverlayStore ; protected Map fCheckBoxes = new HashMap ( ) ; private SelectionListener fCheckBoxListener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { Button button = ( Button ) e . widget ; fOverlayStore . setValue ( ( String ) fCheckBoxes . get ( button ) , button . getSelection ( ) ) ; } } ; protected Button addCheckBox ( Composite parent , String label , String key , int indentation ) { Button checkBox = new Button ( parent , SWT . CHECK ) ; checkBox . setText ( label ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = indentation ; gd . horizontalSpan = ; checkBox . setLayoutData ( gd ) ; checkBox . addSelectionListener ( fCheckBoxListener ) ; fCheckBoxes . put ( checkBox , key ) ; return checkBox ; } protected IPreferenceStore doGetPreferenceStore ( ) { return RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; } protected Map fTextFields = new HashMap ( ) ; protected void initializeFields ( ) { Iterator e = fCheckBoxes . keySet ( ) . iterator ( ) ; while ( e . hasNext ( ) ) { Button b = ( Button ) e . next ( ) ; String key = ( String ) fCheckBoxes . get ( b ) ; b . setSelection ( fOverlayStore . getBoolean ( key ) ) ; } e = fTextFields . keySet ( ) . iterator ( ) ; while ( e . hasNext ( ) ) { Text t = ( Text ) e . next ( ) ; String key = ( String ) fTextFields . get ( t ) ; t . setText ( fOverlayStore . getString ( key ) ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public final class RubyEditorPreferencePage extends AbstractConfigurationBlockPreferencePage { protected String getHelpId ( ) { return IRubyHelpContextIds . RUBY_EDITOR_PREFERENCE_PAGE ; } protected void setDescription ( ) { String description = PreferencesMessages . RubyEditorPreferencePage_general ; setDescription ( description ) ; } protected void setPreferenceStore ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; } protected Label createDescriptionLabel ( Composite parent ) { return null ; } protected IPreferenceConfigurationBlock createConfigurationBlock ( OverlayPreferenceStore overlayPreferenceStore ) { return new RubyEditorAppearanceConfigurationBlock ( this , overlayPreferenceStore ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . Assert ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . forms . events . ExpansionAdapter ; import org . eclipse . ui . forms . events . ExpansionEvent ; import org . eclipse . ui . forms . widgets . ExpandableComposite ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; public abstract class AbstractConfigurationBlock implements IPreferenceConfigurationBlock { protected final class SectionManager { private static final String __NONE = "" ; private Set fSections = new HashSet ( ) ; private boolean fIsBeingManaged = false ; private ExpansionAdapter fListener = new ExpansionAdapter ( ) { public void expansionStateChanged ( ExpansionEvent e ) { ExpandableComposite source = ( ExpandableComposite ) e . getSource ( ) ; updateSectionStyle ( source ) ; if ( fIsBeingManaged ) return ; if ( e . getState ( ) ) { try { fIsBeingManaged = true ; for ( Iterator iter = fSections . iterator ( ) ; iter . hasNext ( ) ; ) { ExpandableComposite composite = ( ExpandableComposite ) iter . next ( ) ; if ( composite != source ) composite . setExpanded ( false ) ; } } finally { fIsBeingManaged = false ; } if ( fLastOpenKey != null && fDialogSettingsStore != null ) fDialogSettingsStore . setValue ( fLastOpenKey , source . getText ( ) ) ; } else { if ( ! fIsBeingManaged && fLastOpenKey != null && fDialogSettingsStore != null ) fDialogSettingsStore . setValue ( fLastOpenKey , __NONE ) ; } ExpandableComposite exComp = getParentExpandableComposite ( source ) ; if ( exComp != null ) exComp . layout ( true , true ) ; ScrolledPageContent parentScrolledComposite = getParentScrolledComposite ( source ) ; if ( parentScrolledComposite != null ) { parentScrolledComposite . reflow ( true ) ; } } } ; private Composite fBody ; private final String fLastOpenKey ; private final IPreferenceStore fDialogSettingsStore ; private ExpandableComposite fFirstChild = null ; public SectionManager ( ) { this ( null , null ) ; } public SectionManager ( IPreferenceStore dialogSettingsStore , String lastOpenKey ) { fDialogSettingsStore = dialogSettingsStore ; fLastOpenKey = lastOpenKey ; } private void manage ( ExpandableComposite section ) { if ( section == null ) throw new NullPointerException ( ) ; if ( fSections . add ( section ) ) section . addExpansionListener ( fListener ) ; makeScrollableCompositeAware ( section ) ; } public Composite createSectionComposite ( Composite parent ) { Assert . isTrue ( fBody == null ) ; boolean isNested = isNestedInScrolledComposite ( parent ) ; Composite composite ; if ( isNested ) { composite = new Composite ( parent , SWT . NONE ) ; fBody = composite ; } else { composite = new ScrolledPageContent ( parent ) ; fBody = ( ( ScrolledPageContent ) composite ) . getBody ( ) ; } fBody . setLayout ( new GridLayout ( ) ) ; return composite ; } public Composite createSection ( String label ) { Assert . isNotNull ( fBody ) ; final ExpandableComposite excomposite = new ExpandableComposite ( fBody , SWT . NONE , ExpandableComposite . TWISTIE | ExpandableComposite . CLIENT_INDENT | ExpandableComposite . COMPACT ) ; if ( fFirstChild == null ) fFirstChild = excomposite ; excomposite . setText ( label ) ; String last = null ; if ( fLastOpenKey != null && fDialogSettingsStore != null ) last = fDialogSettingsStore . getString ( fLastOpenKey ) ; if ( fFirstChild == excomposite && ! __NONE . equals ( last ) || label . equals ( last ) ) { excomposite . setExpanded ( true ) ; if ( fFirstChild != excomposite ) fFirstChild . setExpanded ( false ) ; } else { excomposite . setExpanded ( false ) ; } excomposite . setLayoutData ( new GridData ( GridData . FILL , GridData . BEGINNING , true , false ) ) ; updateSectionStyle ( excomposite ) ; manage ( excomposite ) ; Composite contents = new Composite ( excomposite , SWT . NONE ) ; excomposite . setClient ( contents ) ; return contents ; } } protected static final int INDENT = ; private OverlayPreferenceStore fStore ; private Map fCheckBoxes = new HashMap ( ) ; private SelectionListener fCheckBoxListener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { Button button = ( Button ) e . widget ; fStore . setValue ( ( String ) fCheckBoxes . get ( button ) , button . getSelection ( ) ) ; } } ; private Map fTextFields = new HashMap ( ) ; private ModifyListener fTextFieldListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { Text text = ( Text ) e . widget ; fStore . setValue ( ( String ) fTextFields . get ( text ) , text . getText ( ) ) ; } } ; private ArrayList fNumberFields = new ArrayList ( ) ; private ModifyListener fNumberFieldListener = new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { numberFieldChanged ( ( Text ) e . widget ) ; } } ; private ArrayList fMasterSlaveListeners = new ArrayList ( ) ; private StatusInfo fStatus ; private final PreferencePage fMainPage ; public AbstractConfigurationBlock ( OverlayPreferenceStore store ) { Assert . isNotNull ( store ) ; fStore = store ; fMainPage = null ; } public AbstractConfigurationBlock ( OverlayPreferenceStore store , PreferencePage mainPreferencePage ) { Assert . isNotNull ( store ) ; Assert . isNotNull ( mainPreferencePage ) ; fStore = store ; fMainPage = mainPreferencePage ; } protected final ScrolledPageContent getParentScrolledComposite ( Control control ) { Control parent = control . getParent ( ) ; while ( ! ( parent instanceof ScrolledPageContent ) && parent != null ) { parent = parent . getParent ( ) ; } if ( parent instanceof ScrolledPageContent ) { return ( ScrolledPageContent ) parent ; } return null ; } private final ExpandableComposite getParentExpandableComposite ( Control control ) { Control parent = control . getParent ( ) ; while ( ! ( parent instanceof ExpandableComposite ) && parent != null ) { parent = parent . getParent ( ) ; } if ( parent instanceof ExpandableComposite ) { return ( ExpandableComposite ) parent ; } return null ; } protected void updateSectionStyle ( ExpandableComposite excomposite ) { excomposite . setFont ( JFaceResources . getFontRegistry ( ) . getBold ( JFaceResources . DIALOG_FONT ) ) ; } private void makeScrollableCompositeAware ( Control control ) { ScrolledPageContent parentScrolledComposite = getParentScrolledComposite ( control ) ; if ( parentScrolledComposite != null ) { parentScrolledComposite . adaptChild ( control ) ; } } private boolean isNestedInScrolledComposite ( Composite parent ) { return getParentScrolledComposite ( parent ) != null ; } protected Button addCheckBox ( Composite parent , String label , String key , int indentation ) { Button checkBox = new Button ( parent , SWT . CHECK ) ; checkBox . setText ( label ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = indentation ; gd . horizontalSpan = ; checkBox . setLayoutData ( gd ) ; checkBox . addSelectionListener ( fCheckBoxListener ) ; makeScrollableCompositeAware ( checkBox ) ; fCheckBoxes . put ( checkBox , key ) ; return checkBox ; } protected Control [ ] addLabelledTextField ( Composite composite , String label , String key , int textLimit , int indentation , boolean isNumber ) { return addLabelledTextField ( composite , label , key , textLimit , indentation , isNumber , SWT . BORDER | SWT . SINGLE , , textLimit ) ; } protected Control [ ] addLabelledTextField ( Composite composite , String label , String key , int textLimit , int indentation , boolean isNumber , int textStyle , int height , int width ) { PixelConverter pixelConverter = new PixelConverter ( composite ) ; Label labelControl = new Label ( composite , SWT . NONE ) ; labelControl . setText ( label ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = indentation ; labelControl . setLayoutData ( gd ) ; Text textControl = new Text ( composite , textStyle ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . widthHint = pixelConverter . convertWidthInCharsToPixels ( width + ) ; textControl . setLayoutData ( gd ) ; textControl . setTextLimit ( textLimit ) ; gd . heightHint = pixelConverter . convertHeightInCharsToPixels ( height ) ; fTextFields . put ( textControl , key ) ; if ( isNumber ) { fNumberFields . add ( textControl ) ; textControl . addModifyListener ( fNumberFieldListener ) ; } else { textControl . addModifyListener ( fTextFieldListener ) ; } return new Control [ ] { labelControl , textControl } ; } protected void createDependency ( final Button master , final Control slave ) { createDependency ( master , new Control [ ] { slave } ) ; } protected void createDependency ( final Button master , final Control [ ] slaves ) { Assert . isTrue ( slaves . length > ) ; indent ( slaves [ ] ) ; SelectionListener listener = new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { boolean state = master . getSelection ( ) ; for ( int i = ; i < slaves . length ; i ++ ) { slaves [ i ] . setEnabled ( state ) ; } } public void widgetDefaultSelected ( SelectionEvent e ) { } } ; master . addSelectionListener ( listener ) ; fMasterSlaveListeners . add ( listener ) ; } protected static void indent ( Control control ) { ( ( GridData ) control . getLayoutData ( ) ) . horizontalIndent += INDENT ; } public void initialize ( ) { initializeFields ( ) ; } private void initializeFields ( ) { Iterator iter = fCheckBoxes . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Button b = ( Button ) iter . next ( ) ; String key = ( String ) fCheckBoxes . get ( b ) ; b . setSelection ( fStore . getBoolean ( key ) ) ; } iter = fTextFields . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Text t = ( Text ) iter . next ( ) ; String key = ( String ) fTextFields . get ( t ) ; t . setText ( fStore . getString ( key ) ) ; } iter = fMasterSlaveListeners . iterator ( ) ; while ( iter . hasNext ( ) ) { SelectionListener listener = ( SelectionListener ) iter . next ( ) ; listener . widgetSelected ( null ) ; } updateStatus ( new StatusInfo ( ) ) ; } public void performOk ( ) { } public void performDefaults ( ) { initializeFields ( ) ; } IStatus getStatus ( ) { if ( fStatus == null ) fStatus = new StatusInfo ( ) ; return fStatus ; } public void dispose ( ) { } private void numberFieldChanged ( Text textControl ) { String number = textControl . getText ( ) ; IStatus status = validatePositiveNumber ( number ) ; if ( ! status . matches ( IStatus . ERROR ) ) fStore . setValue ( ( String ) fTextFields . get ( textControl ) , number ) ; updateStatus ( status ) ; } private IStatus validatePositiveNumber ( String number ) { StatusInfo status = new StatusInfo ( ) ; if ( number . length ( ) == ) { status . setError ( PreferencesMessages . RubyEditorPreferencePage_empty_input ) ; } else { try { int value = Integer . parseInt ( number ) ; if ( value < ) status . setError ( Messages . format ( PreferencesMessages . RubyEditorPreferencePage_invalid_input , number ) ) ; } catch ( NumberFormatException e ) { status . setError ( Messages . format ( PreferencesMessages . RubyEditorPreferencePage_invalid_input , number ) ) ; } } return status ; } protected void updateStatus ( IStatus status ) { if ( fMainPage == null ) return ; fMainPage . setValid ( status . isOK ( ) ) ; StatusUtil . applyToStatusLine ( fMainPage , status ) ; } protected final OverlayPreferenceStore getPreferenceStore ( ) { return fStore ; } protected Composite createSubsection ( Composite parent , SectionManager manager , String label ) { if ( manager != null ) { return manager . createSection ( label ) ; } else { Group group = new Group ( parent , SWT . SHADOW_NONE ) ; group . setText ( label ) ; GridData data = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; group . setLayoutData ( data ) ; return group ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class ProblemSeveritiesPreferencePage extends PropertyAndPreferencePage { public static final String PREF_ID = "" ; public static final String PROP_ID = "" ; public static final String DATA_SELECT_OPTION_KEY = "" ; public static final String DATA_SELECT_OPTION_QUALIFIER = "" ; private ProblemSeveritiesConfigurationBlock fConfigurationBlock ; public ProblemSeveritiesPreferencePage ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setTitle ( PreferencesMessages . ProblemSeveritiesPreferencePage_title ) ; } public void createControl ( Composite parent ) { IWorkbenchPreferenceContainer container = ( IWorkbenchPreferenceContainer ) getContainer ( ) ; fConfigurationBlock = new ProblemSeveritiesConfigurationBlock ( getNewStatusChangedListener ( ) , getProject ( ) , container ) ; super . createControl ( parent ) ; if ( isProjectPreferencePage ( ) ) { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . COMPILER_PROPERTY_PAGE ) ; } else { PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . COMPILER_PREFERENCE_PAGE ) ; } } protected Control createPreferenceContent ( Composite composite ) { return fConfigurationBlock . createContents ( composite ) ; } protected boolean hasProjectSpecificOptions ( IProject project ) { return fConfigurationBlock . hasProjectSpecificOptions ( project ) ; } protected String getPreferencePageID ( ) { return PREF_ID ; } protected String getPropertyPageID ( ) { return PROP_ID ; } public void dispose ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . dispose ( ) ; } super . dispose ( ) ; } protected void enableProjectSpecificSettings ( boolean useProjectSpecificSettings ) { super . enableProjectSpecificSettings ( useProjectSpecificSettings ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . useProjectSpecificSettings ( useProjectSpecificSettings ) ; } } protected void performDefaults ( ) { super . performDefaults ( ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . performDefaults ( ) ; } } public boolean performOk ( ) { if ( fConfigurationBlock != null && ! fConfigurationBlock . performOk ( ) ) { return false ; } return super . performOk ( ) ; } public void performApply ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . performApply ( ) ; } } public void applyData ( Object data ) { super . applyData ( data ) ; if ( data instanceof Map && fConfigurationBlock != null ) { Map map = ( Map ) data ; Object key = map . get ( DATA_SELECT_OPTION_KEY ) ; Object qualifier = map . get ( DATA_SELECT_OPTION_QUALIFIER ) ; if ( key instanceof String && qualifier instanceof String ) { fConfigurationBlock . selectOption ( ( String ) key , ( String ) qualifier ) ; } } } public void setElement ( IAdaptable element ) { super . setElement ( element ) ; setDescription ( null ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public abstract class AbstractConfigurationBlockPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private IPreferenceConfigurationBlock fConfigurationBlock ; private OverlayPreferenceStore fOverlayStore ; public AbstractConfigurationBlockPreferencePage ( ) { setDescription ( ) ; setPreferenceStore ( ) ; fOverlayStore = new OverlayPreferenceStore ( getPreferenceStore ( ) , new OverlayPreferenceStore . OverlayKey [ ] { } ) ; fConfigurationBlock = createConfigurationBlock ( fOverlayStore ) ; } protected abstract IPreferenceConfigurationBlock createConfigurationBlock ( OverlayPreferenceStore overlayPreferenceStore ) ; protected abstract String getHelpId ( ) ; protected abstract void setDescription ( ) ; protected abstract void setPreferenceStore ( ) ; public void init ( IWorkbench workbench ) { } public void createControl ( Composite parent ) { super . createControl ( parent ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , getHelpId ( ) ) ; } protected Control createContents ( Composite parent ) { fOverlayStore . load ( ) ; fOverlayStore . start ( ) ; Control content = fConfigurationBlock . createControl ( parent ) ; initialize ( ) ; Dialog . applyDialogFont ( content ) ; return content ; } private void initialize ( ) { fConfigurationBlock . initialize ( ) ; } public boolean performOk ( ) { fConfigurationBlock . performOk ( ) ; fOverlayStore . propagate ( ) ; RubyPlugin . getDefault ( ) . savePluginPreferences ( ) ; return true ; } public void performDefaults ( ) { fOverlayStore . loadDefaults ( ) ; fConfigurationBlock . performDefaults ( ) ; super . performDefaults ( ) ; } public void dispose ( ) { fConfigurationBlock . dispose ( ) ; if ( fOverlayStore != null ) { fOverlayStore . stop ( ) ; fOverlayStore = null ; } super . dispose ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . preference . ColorSelector ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . FontMetrics ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Link ; import org . eclipse . swt . widgets . List ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . ui . PreferenceConstants ; class RubyEditorAppearanceConfigurationBlock extends AbstractConfigurationBlock { private final String [ ] [ ] fAppearanceColorListModel = new String [ ] [ ] { { PreferencesMessages . RubyEditorPreferencePage_matchingBracketsHighlightColor2 , PreferenceConstants . EDITOR_MATCHING_BRACKETS_COLOR , null } , { PreferencesMessages . RubyEditorPreferencePage_backgroundForCompletionProposals , PreferenceConstants . CODEASSIST_PROPOSALS_BACKGROUND , null } , { PreferencesMessages . RubyEditorPreferencePage_foregroundForCompletionProposals , PreferenceConstants . CODEASSIST_PROPOSALS_FOREGROUND , null } , { PreferencesMessages . RubyEditorPreferencePage_backgroundForMethodParameters , PreferenceConstants . CODEASSIST_PARAMETERS_BACKGROUND , null } , { PreferencesMessages . RubyEditorPreferencePage_foregroundForMethodParameters , PreferenceConstants . CODEASSIST_PARAMETERS_FOREGROUND , null } , { PreferencesMessages . RubyEditorPreferencePage_backgroundForCompletionReplacement , PreferenceConstants . CODEASSIST_REPLACEMENT_BACKGROUND , null } , { PreferencesMessages . RubyEditorPreferencePage_foregroundForCompletionReplacement , PreferenceConstants . CODEASSIST_REPLACEMENT_FOREGROUND , null } , } ; private List fAppearanceColorList ; private ColorSelector fAppearanceColorEditor ; private Button fAppearanceColorDefault ; private FontMetrics fFontMetrics ; public RubyEditorAppearanceConfigurationBlock ( PreferencePage mainPreferencePage , OverlayPreferenceStore store ) { super ( store , mainPreferencePage ) ; getPreferenceStore ( ) . addKeys ( createOverlayStoreKeys ( ) ) ; } private OverlayPreferenceStore . OverlayKey [ ] createOverlayStoreKeys ( ) { ArrayList overlayKeys = new ArrayList ( ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , PreferenceConstants . EDITOR_MATCHING_BRACKETS_COLOR ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . HOVERS_ENABLED ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_MATCHING_BRACKETS ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_QUICKASSIST_LIGHTBULB ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_EVALUTE_TEMPORARY_PROBLEMS ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_SMART_HOME_END ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , PreferenceConstants . CODEASSIST_PROPOSALS_BACKGROUND ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , PreferenceConstants . CODEASSIST_PROPOSALS_FOREGROUND ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , PreferenceConstants . CODEASSIST_PARAMETERS_BACKGROUND ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , PreferenceConstants . CODEASSIST_PARAMETERS_FOREGROUND ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , PreferenceConstants . CODEASSIST_REPLACEMENT_BACKGROUND ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , PreferenceConstants . CODEASSIST_REPLACEMENT_FOREGROUND ) ) ; OverlayPreferenceStore . OverlayKey [ ] keys = new OverlayPreferenceStore . OverlayKey [ overlayKeys . size ( ) ] ; overlayKeys . toArray ( keys ) ; return keys ; } public Control createControl ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( new GridLayout ( ) ) ; createHeader ( composite ) ; createAppearancePage ( composite ) ; return composite ; } private void createHeader ( Composite contents ) { final Shell shell = contents . getShell ( ) ; String text = PreferencesMessages . RubyEditorPreferencePage_link ; Link link = new Link ( contents , SWT . NONE ) ; link . setText ( text ) ; link . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { PreferencesUtil . createPreferenceDialogOn ( shell , "" , null , null ) ; } } ) ; link . setToolTipText ( PreferencesMessages . RubyEditorPreferencePage_link_tooltip ) ; GridData gridData = new GridData ( SWT . FILL , SWT . BEGINNING , true , false ) ; gridData . widthHint = ; link . setLayoutData ( gridData ) ; addFiller ( contents ) ; } private void addFiller ( Composite composite ) { PixelConverter pixelConverter = new PixelConverter ( composite ) ; Label filler = new Label ( composite , SWT . LEFT ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; gd . heightHint = pixelConverter . convertHeightInCharsToPixels ( ) / ; filler . setLayoutData ( gd ) ; } protected int convertWidthInCharsToPixels ( int chars ) { if ( fFontMetrics == null ) return ; return Dialog . convertWidthInCharsToPixels ( fFontMetrics , chars ) ; } protected int convertHeightInCharsToPixels ( int chars ) { if ( fFontMetrics == null ) return ; return Dialog . convertHeightInCharsToPixels ( fFontMetrics , chars ) ; } private Control createAppearancePage ( Composite parent ) { Composite appearanceComposite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; appearanceComposite . setLayout ( layout ) ; String label ; label = PreferencesMessages . RubyEditorPreferencePage_smartHomeEnd ; addCheckBox ( appearanceComposite , label , PreferenceConstants . EDITOR_SMART_HOME_END , ) ; label = PreferencesMessages . RubyEditorPreferencePage_subWordNavigation ; addCheckBox ( appearanceComposite , label , PreferenceConstants . EDITOR_SUB_WORD_NAVIGATION , ) ; label = PreferencesMessages . RubyEditorPreferencePage_analyseAnnotationsWhileTyping ; addCheckBox ( appearanceComposite , label , PreferenceConstants . EDITOR_EVALUTE_TEMPORARY_PROBLEMS , ) ; String text = PreferencesMessages . SmartTypingConfigurationBlock_annotationReporting_link ; addLink ( appearanceComposite , text , INDENT ) ; Label spacer = new Label ( appearanceComposite , SWT . LEFT ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; gd . heightHint = convertHeightInCharsToPixels ( ) / ; spacer . setLayoutData ( gd ) ; label = PreferencesMessages . RubyEditorPreferencePage_highlightMatchingBrackets ; addCheckBox ( appearanceComposite , label , PreferenceConstants . EDITOR_MATCHING_BRACKETS , ) ; label = PreferencesMessages . RubyEditorPreferencePage_quickassist_lightbulb ; addCheckBox ( appearanceComposite , label , PreferenceConstants . EDITOR_QUICKASSIST_LIGHTBULB , ) ; label = PreferencesMessages . RubyEditorPreferencePage_enableHovers ; addCheckBox ( appearanceComposite , label , PreferenceConstants . HOVERS_ENABLED , ) ; Label l = new Label ( appearanceComposite , SWT . LEFT ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; gd . heightHint = convertHeightInCharsToPixels ( ) / ; l . setLayoutData ( gd ) ; l = new Label ( appearanceComposite , SWT . LEFT ) ; l . setText ( PreferencesMessages . RubyEditorPreferencePage_appearanceOptions ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; l . setLayoutData ( gd ) ; Composite editorComposite = new Composite ( appearanceComposite , SWT . NONE ) ; layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginHeight = ; layout . marginWidth = ; editorComposite . setLayout ( layout ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . FILL_VERTICAL ) ; gd . horizontalSpan = ; editorComposite . setLayoutData ( gd ) ; fAppearanceColorList = new List ( editorComposite , SWT . SINGLE | SWT . V_SCROLL | SWT . BORDER ) ; gd = new GridData ( GridData . VERTICAL_ALIGN_BEGINNING | GridData . FILL_HORIZONTAL ) ; gd . heightHint = convertHeightInCharsToPixels ( ) ; fAppearanceColorList . setLayoutData ( gd ) ; Composite stylesComposite = new Composite ( editorComposite , SWT . NONE ) ; layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; stylesComposite . setLayout ( layout ) ; stylesComposite . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; l = new Label ( stylesComposite , SWT . LEFT ) ; l . setText ( PreferencesMessages . RubyEditorPreferencePage_color ) ; gd = new GridData ( ) ; gd . horizontalAlignment = GridData . BEGINNING ; l . setLayoutData ( gd ) ; fAppearanceColorEditor = new ColorSelector ( stylesComposite ) ; Button foregroundColorButton = fAppearanceColorEditor . getButton ( ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalAlignment = GridData . BEGINNING ; foregroundColorButton . setLayoutData ( gd ) ; SelectionListener colorDefaultSelectionListener = new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { boolean systemDefault = fAppearanceColorDefault . getSelection ( ) ; fAppearanceColorEditor . getButton ( ) . setEnabled ( ! systemDefault ) ; int i = fAppearanceColorList . getSelectionIndex ( ) ; if ( i == - ) return ; String key = fAppearanceColorListModel [ i ] [ ] ; if ( key != null ) getPreferenceStore ( ) . setValue ( key , systemDefault ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ; fAppearanceColorDefault = new Button ( stylesComposite , SWT . CHECK ) ; fAppearanceColorDefault . setText ( PreferencesMessages . RubyEditorPreferencePage_systemDefault ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalAlignment = GridData . BEGINNING ; gd . horizontalSpan = ; fAppearanceColorDefault . setLayoutData ( gd ) ; fAppearanceColorDefault . setVisible ( false ) ; fAppearanceColorDefault . addSelectionListener ( colorDefaultSelectionListener ) ; fAppearanceColorList . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { handleAppearanceColorListSelection ( ) ; } } ) ; foregroundColorButton . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { int i = fAppearanceColorList . getSelectionIndex ( ) ; if ( i == - ) return ; String key = fAppearanceColorListModel [ i ] [ ] ; PreferenceConverter . setValue ( getPreferenceStore ( ) , key , fAppearanceColorEditor . getColorValue ( ) ) ; } } ) ; return appearanceComposite ; } private void addLink ( Composite composite , String text , int indent ) { GridData gd ; final Link link = new Link ( composite , SWT . NONE ) ; link . setText ( text ) ; gd = new GridData ( SWT . FILL , SWT . BEGINNING , true , false ) ; gd . widthHint = ; gd . horizontalSpan = ; gd . horizontalIndent = indent ; link . setLayoutData ( gd ) ; link . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { PreferencesUtil . createPreferenceDialogOn ( link . getShell ( ) , e . text , null , null ) ; } } ) ; } private void handleAppearanceColorListSelection ( ) { int i = fAppearanceColorList . getSelectionIndex ( ) ; if ( i == - ) return ; String key = fAppearanceColorListModel [ i ] [ ] ; RGB rgb = PreferenceConverter . getColor ( getPreferenceStore ( ) , key ) ; fAppearanceColorEditor . setColorValue ( rgb ) ; updateAppearanceColorWidgets ( fAppearanceColorListModel [ i ] [ ] ) ; } private void updateAppearanceColorWidgets ( String systemDefaultKey ) { if ( systemDefaultKey == null ) { fAppearanceColorDefault . setSelection ( false ) ; fAppearanceColorDefault . setVisible ( false ) ; fAppearanceColorEditor . getButton ( ) . setEnabled ( true ) ; } else { boolean systemDefault = getPreferenceStore ( ) . getBoolean ( systemDefaultKey ) ; fAppearanceColorDefault . setSelection ( systemDefault ) ; fAppearanceColorDefault . setVisible ( true ) ; fAppearanceColorEditor . getButton ( ) . setEnabled ( ! systemDefault ) ; } } public void initialize ( ) { super . initialize ( ) ; for ( int i = ; i < fAppearanceColorListModel . length ; i ++ ) fAppearanceColorList . add ( fAppearanceColorListModel [ i ] [ ] ) ; fAppearanceColorList . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { if ( fAppearanceColorList != null && ! fAppearanceColorList . isDisposed ( ) ) { fAppearanceColorList . select ( ) ; handleAppearanceColorListSelection ( ) ; } } } ) ; } public void performDefaults ( ) { super . performDefaults ( ) ; handleAppearanceColorListSelection ( ) ; } protected void initializeDialogUnits ( Control testControl ) { GC gc = new GC ( testControl ) ; gc . setFont ( JFaceResources . getDialogFont ( ) ) ; fFontMetrics = gc . getFontMetrics ( ) ; gc . dispose ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . preference . IPreferencePageContainer ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . eclipse . ui . preferences . IWorkingCopyManager ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . preferences . formatter . CodeFormatterConfigurationBlock ; public class CodeFormatterPreferencePage extends PropertyAndPreferencePage { public static final String PREF_ID = "" ; public static final String PROP_ID = "" ; private CodeFormatterConfigurationBlock fConfigurationBlock ; public CodeFormatterPreferencePage ( ) { setDescription ( PreferencesMessages . CodeFormatterPreferencePage_description ) ; setTitle ( PreferencesMessages . CodeFormatterPreferencePage_title ) ; } public void createControl ( Composite parent ) { IPreferencePageContainer container = getContainer ( ) ; PreferencesAccess access ; if ( container instanceof IWorkbenchPreferenceContainer ) { IWorkingCopyManager workingCopyManager = ( ( IWorkbenchPreferenceContainer ) container ) . getWorkingCopyManager ( ) ; access = PreferencesAccess . getWorkingCopyPreferences ( workingCopyManager ) ; } else { access = PreferencesAccess . getOriginalPreferences ( ) ; } fConfigurationBlock = new CodeFormatterConfigurationBlock ( getProject ( ) , access ) ; super . createControl ( parent ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . CODEFORMATTER_PREFERENCE_PAGE ) ; } protected Control createPreferenceContent ( Composite composite ) { return fConfigurationBlock . createContents ( composite ) ; } protected boolean hasProjectSpecificOptions ( IProject project ) { return fConfigurationBlock . hasProjectSpecificOptions ( project ) ; } protected void enableProjectSpecificSettings ( boolean useProjectSpecificSettings ) { super . enableProjectSpecificSettings ( useProjectSpecificSettings ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . enableProjectSpecificSettings ( useProjectSpecificSettings ) ; } } protected String getPreferencePageID ( ) { return PREF_ID ; } protected String getPropertyPageID ( ) { return PROP_ID ; } public void dispose ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . dispose ( ) ; } super . dispose ( ) ; } protected void performDefaults ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . performDefaults ( ) ; } super . performDefaults ( ) ; } public boolean performOk ( ) { if ( fConfigurationBlock != null && ! fConfigurationBlock . performOk ( ) ) { return false ; } return super . performOk ( ) ; } public void setElement ( IAdaptable element ) { super . setElement ( element ) ; setDescription ( null ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Layout ; class TabFolderLayout extends Layout { protected Point computeSize ( Composite composite , int wHint , int hHint , boolean flushCache ) { if ( wHint != SWT . DEFAULT && hHint != SWT . DEFAULT ) return new Point ( wHint , hHint ) ; Control [ ] children = composite . getChildren ( ) ; int count = children . length ; int maxWidth = , maxHeight = ; for ( int i = ; i < count ; i ++ ) { Control child = children [ i ] ; Point pt = child . computeSize ( SWT . DEFAULT , SWT . DEFAULT , flushCache ) ; maxWidth = Math . max ( maxWidth , pt . x ) ; maxHeight = Math . max ( maxHeight , pt . y ) ; } if ( wHint != SWT . DEFAULT ) maxWidth = wHint ; if ( hHint != SWT . DEFAULT ) maxHeight = hHint ; return new Point ( maxWidth , maxHeight ) ; } protected void layout ( Composite composite , boolean flushCache ) { Rectangle rect = composite . getClientArea ( ) ; Control [ ] children = composite . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { children [ i ] . setBounds ( rect ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . ControlEnableState ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Link ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . IWorkbenchPropertyPage ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; public abstract class PropertyAndPreferencePage extends PreferencePage implements IWorkbenchPreferencePage , IWorkbenchPropertyPage { private Control fConfigurationBlockControl ; private ControlEnableState fBlockEnableState ; private Link fChangeWorkspaceSettings ; private SelectionButtonDialogField fUseProjectSettings ; private IStatus fBlockStatus ; private Composite fParentComposite ; private IProject fProject ; private Map fData ; public static final String DATA_NO_LINK = "" ; public PropertyAndPreferencePage ( ) { fBlockStatus = new StatusInfo ( ) ; fBlockEnableState = null ; fProject = null ; fData = null ; } protected abstract Control createPreferenceContent ( Composite composite ) ; protected abstract boolean hasProjectSpecificOptions ( IProject project ) ; protected abstract String getPreferencePageID ( ) ; protected abstract String getPropertyPageID ( ) ; protected boolean supportsProjectSpecificOptions ( ) { return getPropertyPageID ( ) != null ; } protected boolean offerLink ( ) { return fData == null || ! Boolean . TRUE . equals ( fData . get ( DATA_NO_LINK ) ) ; } protected Label createDescriptionLabel ( Composite parent ) { fParentComposite = parent ; if ( isProjectPreferencePage ( ) ) { Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; composite . setLayout ( layout ) ; composite . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; IDialogFieldListener listener = new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { enableProjectSpecificSettings ( ( ( SelectionButtonDialogField ) field ) . isSelected ( ) ) ; } } ; fUseProjectSettings = new SelectionButtonDialogField ( SWT . CHECK ) ; fUseProjectSettings . setDialogFieldListener ( listener ) ; fUseProjectSettings . setLabelText ( PreferencesMessages . PropertyAndPreferencePage_useprojectsettings_label ) ; fUseProjectSettings . doFillIntoGrid ( composite , ) ; LayoutUtil . setHorizontalGrabbing ( fUseProjectSettings . getSelectionButton ( null ) ) ; if ( offerLink ( ) ) { fChangeWorkspaceSettings = createLink ( composite , PreferencesMessages . PropertyAndPreferencePage_useworkspacesettings_change ) ; fChangeWorkspaceSettings . setLayoutData ( new GridData ( SWT . END , SWT . CENTER , false , false ) ) ; } else { LayoutUtil . setHorizontalSpan ( fUseProjectSettings . getSelectionButton ( null ) , ) ; } Label horizontalLine = new Label ( composite , SWT . SEPARATOR | SWT . HORIZONTAL ) ; horizontalLine . setLayoutData ( new GridData ( GridData . FILL , GridData . FILL , true , false , , ) ) ; horizontalLine . setFont ( composite . getFont ( ) ) ; } else if ( supportsProjectSpecificOptions ( ) && offerLink ( ) ) { fChangeWorkspaceSettings = createLink ( parent , PreferencesMessages . PropertyAndPreferencePage_showprojectspecificsettings_label ) ; fChangeWorkspaceSettings . setLayoutData ( new GridData ( SWT . END , SWT . CENTER , true , false ) ) ; } return super . createDescriptionLabel ( parent ) ; } protected Control createContents ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; composite . setLayout ( layout ) ; composite . setFont ( parent . getFont ( ) ) ; GridData data = new GridData ( GridData . FILL , GridData . FILL , true , true ) ; fConfigurationBlockControl = createPreferenceContent ( composite ) ; fConfigurationBlockControl . setLayoutData ( data ) ; if ( isProjectPreferencePage ( ) ) { boolean useProjectSettings = hasProjectSpecificOptions ( getProject ( ) ) ; enableProjectSpecificSettings ( useProjectSettings ) ; } Dialog . applyDialogFont ( composite ) ; return composite ; } private Link createLink ( Composite composite , String text ) { Link link = new Link ( composite , SWT . NONE ) ; link . setFont ( composite . getFont ( ) ) ; link . setText ( "" + text + "" ) ; link . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { doLinkActivated ( ( Link ) e . widget ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { doLinkActivated ( ( Link ) e . widget ) ; } } ) ; return link ; } protected boolean useProjectSettings ( ) { return isProjectPreferencePage ( ) && fUseProjectSettings != null && fUseProjectSettings . isSelected ( ) ; } protected boolean isProjectPreferencePage ( ) { return fProject != null ; } protected IProject getProject ( ) { return fProject ; } final void doLinkActivated ( Link link ) { Map data = new HashMap ( ) ; data . put ( DATA_NO_LINK , Boolean . TRUE ) ; if ( isProjectPreferencePage ( ) ) { openWorkspacePreferences ( data ) ; } else { HashSet projectsWithSpecifics = new HashSet ( ) ; try { IRubyProject [ ] projects = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) . getRubyProjects ( ) ; for ( int i = ; i < projects . length ; i ++ ) { IRubyProject curr = projects [ i ] ; if ( hasProjectSpecificOptions ( curr . getProject ( ) ) ) { projectsWithSpecifics . add ( curr ) ; } } } catch ( RubyModelException e ) { } ProjectSelectionDialog dialog = new ProjectSelectionDialog ( getShell ( ) , projectsWithSpecifics ) ; if ( dialog . open ( ) == Window . OK ) { IRubyProject res = ( IRubyProject ) dialog . getFirstResult ( ) ; openProjectProperties ( res . getProject ( ) , data ) ; } } } protected final void openWorkspacePreferences ( Object data ) { String id = getPreferencePageID ( ) ; PreferencesUtil . createPreferenceDialogOn ( getShell ( ) , id , new String [ ] { id } , data ) . open ( ) ; } protected final void openProjectProperties ( IProject project , Object data ) { String id = getPropertyPageID ( ) ; if ( id != null ) { PreferencesUtil . createPropertyDialogOn ( getShell ( ) , project , id , new String [ ] { id } , data ) . open ( ) ; } } protected void enableProjectSpecificSettings ( boolean useProjectSpecificSettings ) { fUseProjectSettings . setSelection ( useProjectSpecificSettings ) ; enablePreferenceContent ( useProjectSpecificSettings ) ; updateLinkVisibility ( ) ; doStatusChanged ( ) ; } private void updateLinkVisibility ( ) { if ( fChangeWorkspaceSettings == null || fChangeWorkspaceSettings . isDisposed ( ) ) { return ; } if ( isProjectPreferencePage ( ) ) { fChangeWorkspaceSettings . setEnabled ( ! useProjectSettings ( ) ) ; } } protected void setPreferenceContentStatus ( IStatus status ) { fBlockStatus = status ; doStatusChanged ( ) ; } protected IStatusChangeListener getNewStatusChangedListener ( ) { return new IStatusChangeListener ( ) { public void statusChanged ( IStatus status ) { setPreferenceContentStatus ( status ) ; } } ; } protected IStatus getPreferenceContentStatus ( ) { return fBlockStatus ; } protected void doStatusChanged ( ) { if ( ! isProjectPreferencePage ( ) || useProjectSettings ( ) ) { updateStatus ( fBlockStatus ) ; } else { updateStatus ( new StatusInfo ( ) ) ; } } protected void enablePreferenceContent ( boolean enable ) { if ( enable ) { if ( fBlockEnableState != null ) { fBlockEnableState . restore ( ) ; fBlockEnableState = null ; } } else { if ( fBlockEnableState == null ) { fBlockEnableState = ControlEnableState . disable ( fConfigurationBlockControl ) ; } } } protected void performDefaults ( ) { if ( useProjectSettings ( ) ) { enableProjectSpecificSettings ( false ) ; } super . performDefaults ( ) ; } private void updateStatus ( IStatus status ) { setValid ( ! status . matches ( IStatus . ERROR ) ) ; StatusUtil . applyToStatusLine ( this , status ) ; } public void init ( IWorkbench workbench ) { } public IAdaptable getElement ( ) { return fProject ; } public void setElement ( IAdaptable element ) { fProject = ( IProject ) element . getAdapter ( IResource . class ) ; } public void applyData ( Object data ) { if ( data instanceof Map ) { fData = ( Map ) data ; } if ( fChangeWorkspaceSettings != null ) { if ( ! offerLink ( ) ) { fChangeWorkspaceSettings . dispose ( ) ; fParentComposite . layout ( true , true ) ; } } } protected Map getData ( ) { return fData ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . io . File ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import java . util . Locale ; import java . util . Set ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; import org . rubypeople . rdt . internal . ui . text . spelling . SpellCheckEngine ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class SpellingConfigurationBlock extends OptionsConfigurationBlock { private static final Key PREF_SPELLING_IGNORE_DIGITS = getRDTUIKey ( PreferenceConstants . SPELLING_IGNORE_DIGITS ) ; private static final Key PREF_SPELLING_IGNORE_MIXED = getRDTUIKey ( PreferenceConstants . SPELLING_IGNORE_MIXED ) ; private static final Key PREF_SPELLING_IGNORE_SENTENCE = getRDTUIKey ( PreferenceConstants . SPELLING_IGNORE_SENTENCE ) ; private static final Key PREF_SPELLING_IGNORE_UPPER = getRDTUIKey ( PreferenceConstants . SPELLING_IGNORE_UPPER ) ; private static final Key PREF_SPELLING_IGNORE_URLS = getRDTUIKey ( PreferenceConstants . SPELLING_IGNORE_URLS ) ; private static final Key PREF_SPELLING_LOCALE = getRDTUIKey ( PreferenceConstants . SPELLING_LOCALE ) ; private static final Key PREF_SPELLING_PROPOSAL_THRESHOLD = getRDTUIKey ( PreferenceConstants . SPELLING_PROPOSAL_THRESHOLD ) ; private static final Key PREF_SPELLING_USER_DICTIONARY = getRDTUIKey ( PreferenceConstants . SPELLING_USER_DICTIONARY ) ; private static final Key PREF_SPELLING_ENABLE_CONTENTASSIST = getRDTUIKey ( PreferenceConstants . SPELLING_ENABLE_CONTENTASSIST ) ; protected static void createSelectionDependency ( final Button master , final Control slave ) { master . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent event ) { } public void widgetSelected ( SelectionEvent event ) { slave . setEnabled ( master . getSelection ( ) ) ; } } ) ; slave . setEnabled ( master . getSelection ( ) ) ; } protected static String [ ] getDictionaryCodes ( final Set locales ) { int index = ; Locale locale = null ; final String [ ] codes = new String [ locales . size ( ) ] ; for ( final Iterator iterator = locales . iterator ( ) ; iterator . hasNext ( ) ; ) { locale = ( Locale ) iterator . next ( ) ; codes [ index ++ ] = locale . toString ( ) ; } return codes ; } protected static String [ ] getDictionaryLabels ( final Set locales ) { int index = ; Locale locale = null ; final String [ ] labels = new String [ locales . size ( ) ] ; for ( final Iterator iterator = locales . iterator ( ) ; iterator . hasNext ( ) ; ) { locale = ( Locale ) iterator . next ( ) ; labels [ index ++ ] = locale . getDisplayName ( ) ; } return labels ; } protected static IStatus validateAbsoluteFilePath ( final String path ) { final StatusInfo status = new StatusInfo ( ) ; if ( path . length ( ) > ) { final File file = new File ( path ) ; if ( ! file . isFile ( ) || ! file . isAbsolute ( ) || ! file . exists ( ) || ! file . canRead ( ) || ! file . canWrite ( ) ) status . setError ( PreferencesMessages . SpellingPreferencePage_dictionary_error ) ; } return status ; } protected static IStatus validateLocale ( final String locale ) { final StatusInfo status = new StatusInfo ( IStatus . ERROR , PreferencesMessages . SpellingPreferencePage_locale_error ) ; final Set locales = SpellCheckEngine . getAvailableLocales ( ) ; Locale current = null ; for ( final Iterator iterator = locales . iterator ( ) ; iterator . hasNext ( ) ; ) { current = ( Locale ) iterator . next ( ) ; if ( current . toString ( ) . equals ( locale ) ) return new StatusInfo ( ) ; } return status ; } protected static IStatus validatePositiveNumber ( final String number ) { final StatusInfo status = new StatusInfo ( ) ; if ( number . length ( ) == ) { status . setError ( PreferencesMessages . SpellingPreferencePage_empty_threshold ) ; } else { try { final int value = Integer . parseInt ( number ) ; if ( value < ) { status . setError ( Messages . format ( PreferencesMessages . SpellingPreferencePage_invalid_threshold , number ) ) ; } } catch ( NumberFormatException exception ) { status . setError ( Messages . format ( PreferencesMessages . SpellingPreferencePage_invalid_threshold , number ) ) ; } } return status ; } private Text fDictionaryPath = null ; private IStatus fFileStatus = new StatusInfo ( ) ; private IStatus fThresholdStatus = new StatusInfo ( ) ; private Control [ ] fAllControls ; private Control [ ] fEnabledControls ; public SpellingConfigurationBlock ( final IStatusChangeListener context , final IProject project , IWorkbenchPreferenceContainer container ) { super ( context , project , getAllKeys ( ) , container ) ; IStatus status = validateAbsoluteFilePath ( getValue ( PREF_SPELLING_USER_DICTIONARY ) ) ; if ( status . getSeverity ( ) != IStatus . OK ) setValue ( PREF_SPELLING_USER_DICTIONARY , "" ) ; status = validateLocale ( getValue ( PREF_SPELLING_LOCALE ) ) ; if ( status . getSeverity ( ) != IStatus . OK ) setValue ( PREF_SPELLING_LOCALE , SpellCheckEngine . getDefaultLocale ( ) . toString ( ) ) ; } protected Combo addComboBox ( Composite parent , String label , Key key , String [ ] values , String [ ] valueLabels , int indent ) { ControlData data = new ControlData ( key , values ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = indent ; Label labelControl = new Label ( parent , SWT . LEFT | SWT . WRAP ) ; labelControl . setText ( label ) ; labelControl . setLayoutData ( gd ) ; Combo comboBox = new Combo ( parent , SWT . READ_ONLY ) ; comboBox . setItems ( valueLabels ) ; comboBox . setData ( data ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; comboBox . setLayoutData ( gd ) ; comboBox . addSelectionListener ( getSelectionListener ( ) ) ; fLabels . put ( comboBox , labelControl ) ; String currValue = getValue ( key ) ; comboBox . select ( data . getSelection ( currValue ) ) ; fComboBoxes . add ( comboBox ) ; return comboBox ; } protected Control createContents ( final Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayout ( new GridLayout ( ) ) ; List allControls = new ArrayList ( ) ; final PixelConverter converter = new PixelConverter ( parent ) ; final String [ ] trueFalse = new String [ ] { IPreferenceStore . TRUE , IPreferenceStore . FALSE } ; Group user = new Group ( composite , SWT . NONE ) ; user . setText ( PreferencesMessages . SpellingPreferencePage_preferences_user ) ; user . setLayout ( new GridLayout ( ) ) ; user . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; allControls . add ( user ) ; String label = PreferencesMessages . SpellingPreferencePage_ignore_digits_label ; Control slave = addCheckBox ( user , label , PREF_SPELLING_IGNORE_DIGITS , trueFalse , ) ; allControls . add ( slave ) ; label = PreferencesMessages . SpellingPreferencePage_ignore_mixed_label ; slave = addCheckBox ( user , label , PREF_SPELLING_IGNORE_MIXED , trueFalse , ) ; allControls . add ( slave ) ; label = PreferencesMessages . SpellingPreferencePage_ignore_sentence_label ; slave = addCheckBox ( user , label , PREF_SPELLING_IGNORE_SENTENCE , trueFalse , ) ; allControls . add ( slave ) ; label = PreferencesMessages . SpellingPreferencePage_ignore_upper_label ; slave = addCheckBox ( user , label , PREF_SPELLING_IGNORE_UPPER , trueFalse , ) ; allControls . add ( slave ) ; label = PreferencesMessages . SpellingPreferencePage_ignore_url_label ; slave = addCheckBox ( user , label , PREF_SPELLING_IGNORE_URLS , trueFalse , ) ; allControls . add ( slave ) ; final Group engine = new Group ( composite , SWT . NONE ) ; engine . setText ( PreferencesMessages . SpellingPreferencePage_preferences_engine ) ; engine . setLayout ( new GridLayout ( , false ) ) ; engine . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; allControls . add ( engine ) ; label = PreferencesMessages . SpellingPreferencePage_dictionary_label ; final Set locales = SpellCheckEngine . getAvailableLocales ( ) ; Combo combo = addComboBox ( engine , label , PREF_SPELLING_LOCALE , getDictionaryCodes ( locales ) , getDictionaryLabels ( locales ) , ) ; combo . setEnabled ( locales . size ( ) > ) ; allControls . add ( combo ) ; allControls . add ( fLabels . get ( combo ) ) ; new Label ( engine , SWT . NONE ) ; label = PreferencesMessages . SpellingPreferencePage_workspace_dictionary_label ; fDictionaryPath = addTextField ( engine , label , PREF_SPELLING_USER_DICTIONARY , , ) ; GridData gd = ( GridData ) fDictionaryPath . getLayoutData ( ) ; gd . grabExcessHorizontalSpace = true ; gd . widthHint = converter . convertWidthInCharsToPixels ( ) ; allControls . add ( fDictionaryPath ) ; allControls . add ( fLabels . get ( fDictionaryPath ) ) ; Button button = new Button ( engine , SWT . PUSH ) ; button . setText ( PreferencesMessages . SpellingPreferencePage_browse_label ) ; button . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( final SelectionEvent event ) { handleBrowseButtonSelected ( ) ; } } ) ; button . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_END ) ) ; SWTUtil . setButtonDimensionHint ( button ) ; allControls . add ( button ) ; Group advanced = new Group ( composite , SWT . NONE ) ; advanced . setText ( PreferencesMessages . SpellingPreferencePage_preferences_advanced ) ; advanced . setLayout ( new GridLayout ( , false ) ) ; advanced . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; allControls . add ( advanced ) ; label = PreferencesMessages . SpellingPreferencePage_proposals_threshold ; Text text = addTextField ( advanced , label , PREF_SPELLING_PROPOSAL_THRESHOLD , , ) ; text . setTextLimit ( ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . widthHint = converter . convertWidthInCharsToPixels ( ) ; text . setLayoutData ( gd ) ; allControls . add ( text ) ; allControls . add ( fLabels . get ( text ) ) ; label = PreferencesMessages . SpellingPreferencePage_enable_contentassist_label ; button = addCheckBox ( advanced , label , PREF_SPELLING_ENABLE_CONTENTASSIST , trueFalse , ) ; allControls . add ( button ) ; fAllControls = ( Control [ ] ) allControls . toArray ( new Control [ allControls . size ( ) ] ) ; return composite ; } private static Key [ ] getAllKeys ( ) { return new Key [ ] { PREF_SPELLING_USER_DICTIONARY , PREF_SPELLING_IGNORE_DIGITS , PREF_SPELLING_IGNORE_MIXED , PREF_SPELLING_IGNORE_SENTENCE , PREF_SPELLING_IGNORE_UPPER , PREF_SPELLING_IGNORE_URLS , PREF_SPELLING_LOCALE , PREF_SPELLING_PROPOSAL_THRESHOLD , PREF_SPELLING_ENABLE_CONTENTASSIST } ; } protected final String [ ] getFullBuildDialogStrings ( final boolean workspace ) { return null ; } protected void handleBrowseButtonSelected ( ) { final FileDialog dialog = new FileDialog ( fDictionaryPath . getShell ( ) , SWT . OPEN ) ; dialog . setText ( PreferencesMessages . SpellingPreferencePage_filedialog_title ) ; dialog . setFilterExtensions ( new String [ ] { PreferencesMessages . SpellingPreferencePage_filter_dictionary_extension , PreferencesMessages . SpellingPreferencePage_filter_all_extension } ) ; dialog . setFilterNames ( new String [ ] { PreferencesMessages . SpellingPreferencePage_filter_dictionary_label , PreferencesMessages . SpellingPreferencePage_filter_all_label } ) ; final String path = dialog . open ( ) ; if ( path != null ) fDictionaryPath . setText ( path ) ; } protected void validateSettings ( final Key key , final String oldValue , final String newValue ) { if ( key == null || PREF_SPELLING_PROPOSAL_THRESHOLD . equals ( key ) ) fThresholdStatus = validatePositiveNumber ( getValue ( PREF_SPELLING_PROPOSAL_THRESHOLD ) ) ; if ( key == null || PREF_SPELLING_USER_DICTIONARY . equals ( key ) ) fFileStatus = validateAbsoluteFilePath ( getValue ( PREF_SPELLING_USER_DICTIONARY ) ) ; fContext . statusChanged ( StatusUtil . getMostSevere ( new IStatus [ ] { fThresholdStatus , fFileStatus } ) ) ; } protected void updateCheckBox ( Button curr ) { super . updateCheckBox ( curr ) ; Event event = new Event ( ) ; event . type = SWT . Selection ; event . display = curr . getDisplay ( ) ; event . widget = curr ; curr . notifyListeners ( SWT . Selection , event ) ; } protected void setEnabled ( boolean enabled ) { if ( enabled && fEnabledControls != null ) { for ( int i = fEnabledControls . length - ; i >= ; i -- ) fEnabledControls [ i ] . setEnabled ( true ) ; fEnabledControls = null ; } if ( ! enabled && fEnabledControls == null ) { List enabledControls = new ArrayList ( ) ; for ( int i = fAllControls . length - ; i >= ; i -- ) { Control control = fAllControls [ i ] ; if ( control . isEnabled ( ) ) { enabledControls . add ( control ) ; control . setEnabled ( false ) ; } } fEnabledControls = ( Control [ ] ) enabledControls . toArray ( new Control [ enabledControls . size ( ) ] ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . text . ruby . ProposalSorterHandle ; import org . rubypeople . rdt . internal . ui . text . ruby . ProposalSorterRegistry ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . ui . PreferenceConstants ; class CodeAssistConfigurationBlock extends OptionsConfigurationBlock { private static final Key PREF_CODEASSIST_AUTOACTIVATION = getRDTUIKey ( PreferenceConstants . CODEASSIST_AUTOACTIVATION ) ; private static final Key PREF_CODEASSIST_AUTOACTIVATION_DELAY = getRDTUIKey ( PreferenceConstants . CODEASSIST_AUTOACTIVATION_DELAY ) ; private static final Key PREF_CODEASSIST_AUTOINSERT = getRDTUIKey ( PreferenceConstants . CODEASSIST_AUTOINSERT ) ; private static final Key PREF_CODEASSIST_SORTER = getRDTUIKey ( PreferenceConstants . CODEASSIST_SORTER ) ; private static final Key PREF_CODEASSIST_INSERT_COMPLETION = getRDTUIKey ( PreferenceConstants . CODEASSIST_INSERT_COMPLETION ) ; private static final Key PREF_CODEASSIST_FILL_ARGUMENT_NAMES = getRDTUIKey ( PreferenceConstants . CODEASSIST_FILL_ARGUMENT_NAMES ) ; private static final Key PREF_CODEASSIST_FILL_METHOD_BLOCK_ARGUMENTS = getRDTUIKey ( PreferenceConstants . CODEASSIST_FILL_METHOD_BLOCK_ARGUMENTS ) ; private static final Key PREF_CODEASSIST_PREFIX_COMPLETION = getRDTUIKey ( PreferenceConstants . CODEASSIST_PREFIX_COMPLETION ) ; private static final Key PREF_CODEASSIST_CAMEL_CASE_MATCH = getRDTCoreKey ( RubyCore . CODEASSIST_CAMEL_CASE_MATCH ) ; private static Key [ ] getAllKeys ( ) { return new Key [ ] { PREF_CODEASSIST_AUTOACTIVATION , PREF_CODEASSIST_AUTOACTIVATION_DELAY , PREF_CODEASSIST_AUTOINSERT , PREF_CODEASSIST_SORTER , PREF_CODEASSIST_INSERT_COMPLETION , PREF_CODEASSIST_FILL_ARGUMENT_NAMES , PREF_CODEASSIST_FILL_METHOD_BLOCK_ARGUMENTS , PREF_CODEASSIST_PREFIX_COMPLETION , PREF_CODEASSIST_CAMEL_CASE_MATCH } ; } private static final String [ ] trueFalse = new String [ ] { IPreferenceStore . TRUE , IPreferenceStore . FALSE } ; private Button fCompletionInsertsRadioButton ; private Button fCompletionOverwritesRadioButton ; public CodeAssistConfigurationBlock ( IStatusChangeListener statusListener , IWorkbenchPreferenceContainer workbenchcontainer ) { super ( statusListener , null , getAllKeys ( ) , workbenchcontainer ) ; } protected Control createContents ( Composite parent ) { ScrolledPageContent scrolled = new ScrolledPageContent ( parent , SWT . H_SCROLL | SWT . V_SCROLL ) ; scrolled . setExpandHorizontal ( true ) ; scrolled . setExpandVertical ( true ) ; Composite control = new Composite ( scrolled , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; control . setLayout ( layout ) ; Composite composite ; composite = createSubsection ( control , PreferencesMessages . CodeAssistConfigurationBlock_insertionSection_title ) ; addInsertionSection ( composite ) ; composite = createSubsection ( control , PreferencesMessages . CodeAssistConfigurationBlock_sortingSection_title ) ; addSortingSection ( composite ) ; composite = createSubsection ( control , PreferencesMessages . CodeAssistConfigurationBlock_autoactivationSection_title ) ; addAutoActivationSection ( composite ) ; initialize ( ) ; scrolled . setContent ( control ) ; final Point size = control . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; scrolled . setMinSize ( size . x , size . y ) ; return scrolled ; } protected Composite createSubsection ( Composite parent , String label ) { Group group = new Group ( parent , SWT . SHADOW_NONE ) ; group . setText ( label ) ; GridData data = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; group . setLayoutData ( data ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; group . setLayout ( layout ) ; return group ; } private void addInsertionSection ( Composite composite ) { addCompletionRadioButtons ( composite ) ; String label ; label = PreferencesMessages . RubyEditorPreferencePage_insertSingleProposalsAutomatically ; addCheckBox ( composite , label , PREF_CODEASSIST_AUTOINSERT , trueFalse , ) ; label = PreferencesMessages . RubyEditorPreferencePage_completePrefixes ; addCheckBox ( composite , label , PREF_CODEASSIST_PREFIX_COMPLETION , trueFalse , ) ; label = PreferencesMessages . RubyEditorPreferencePage_fillArgumentNamesOnMethodCompletion ; Button master = addCheckBox ( composite , label , PREF_CODEASSIST_FILL_ARGUMENT_NAMES , trueFalse , ) ; label = PreferencesMessages . RubyEditorPreferencePage_fillBlockArgumentNamesOnMethodCompletion ; Button slave = addCheckBox ( composite , label , PREF_CODEASSIST_FILL_METHOD_BLOCK_ARGUMENTS , trueFalse , ) ; createSelectionDependency ( master , slave ) ; } protected static void createSelectionDependency ( final Button master , final Control slave ) { master . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent event ) { } public void widgetSelected ( SelectionEvent event ) { slave . setEnabled ( master . getSelection ( ) ) ; } } ) ; slave . setEnabled ( master . getSelection ( ) ) ; } private void addSortingSection ( Composite composite ) { String label ; label = PreferencesMessages . RubyEditorPreferencePage_presentProposalsInAlphabeticalOrder ; ProposalSorterHandle [ ] sorters = ProposalSorterRegistry . getDefault ( ) . getSorters ( ) ; String [ ] labels = new String [ sorters . length ] ; String [ ] values = new String [ sorters . length ] ; for ( int i = ; i < sorters . length ; i ++ ) { ProposalSorterHandle handle = sorters [ i ] ; labels [ i ] = handle . getName ( ) ; values [ i ] = handle . getId ( ) ; } addComboBox ( composite , label , PREF_CODEASSIST_SORTER , values , labels , ) ; label = PreferencesMessages . CodeAssistConfigurationBlock_restricted_link ; String [ ] enabledDisabled = new String [ ] { RubyCore . ENABLED , RubyCore . DISABLED } ; label = PreferencesMessages . CodeAssistConfigurationBlock_matchCamelCase_label ; addCheckBox ( composite , label , PREF_CODEASSIST_CAMEL_CASE_MATCH , enabledDisabled , ) ; } private void addAutoActivationSection ( Composite composite ) { String label ; label = PreferencesMessages . RubyEditorPreferencePage_enableAutoActivation ; final Button autoactivation = addCheckBox ( composite , label , PREF_CODEASSIST_AUTOACTIVATION , trueFalse , ) ; autoactivation . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { updateAutoactivationControls ( ) ; } } ) ; label = PreferencesMessages . RubyEditorPreferencePage_autoActivationDelay ; addLabelledTextField ( composite , label , PREF_CODEASSIST_AUTOACTIVATION_DELAY , , , true ) ; } protected Text addLabelledTextField ( Composite parent , String label , Key key , int textlimit , int indent , boolean dummy ) { PixelConverter pixelConverter = new PixelConverter ( parent ) ; Label labelControl = new Label ( parent , SWT . WRAP ) ; labelControl . setText ( label ) ; labelControl . setLayoutData ( new GridData ( ) ) ; Text textBox = new Text ( parent , SWT . BORDER | SWT . SINGLE ) ; textBox . setData ( key ) ; textBox . setLayoutData ( new GridData ( ) ) ; fLabels . put ( textBox , labelControl ) ; String currValue = getValue ( key ) ; if ( currValue != null ) { textBox . setText ( currValue ) ; } textBox . addModifyListener ( getTextModifyListener ( ) ) ; GridData data = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; if ( textlimit != ) { textBox . setTextLimit ( textlimit ) ; data . widthHint = pixelConverter . convertWidthInCharsToPixels ( textlimit + ) ; } data . horizontalIndent = indent ; data . horizontalSpan = ; textBox . setLayoutData ( data ) ; fTextBoxes . add ( textBox ) ; return textBox ; } private void addCompletionRadioButtons ( Composite contentAssistComposite ) { Composite completionComposite = new Composite ( contentAssistComposite , SWT . NONE ) ; GridData ccgd = new GridData ( ) ; ccgd . horizontalSpan = ; completionComposite . setLayoutData ( ccgd ) ; GridLayout ccgl = new GridLayout ( ) ; ccgl . marginWidth = ; ccgl . numColumns = ; completionComposite . setLayout ( ccgl ) ; SelectionListener completionSelectionListener = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { boolean insert = fCompletionInsertsRadioButton . getSelection ( ) ; setValue ( PREF_CODEASSIST_INSERT_COMPLETION , insert ) ; } } ; fCompletionInsertsRadioButton = new Button ( completionComposite , SWT . RADIO | SWT . LEFT ) ; fCompletionInsertsRadioButton . setText ( PreferencesMessages . RubyEditorPreferencePage_completionInserts ) ; fCompletionInsertsRadioButton . setLayoutData ( new GridData ( ) ) ; fCompletionInsertsRadioButton . addSelectionListener ( completionSelectionListener ) ; fCompletionOverwritesRadioButton = new Button ( completionComposite , SWT . RADIO | SWT . LEFT ) ; fCompletionOverwritesRadioButton . setText ( PreferencesMessages . RubyEditorPreferencePage_completionOverwrites ) ; fCompletionOverwritesRadioButton . setLayoutData ( new GridData ( ) ) ; fCompletionOverwritesRadioButton . addSelectionListener ( completionSelectionListener ) ; Label label = new Label ( completionComposite , SWT . NONE ) ; label . setText ( PreferencesMessages . RubyEditorPreferencePage_completionToggleHint ) ; GridData gd = new GridData ( ) ; gd . horizontalIndent = ; gd . horizontalSpan = ; label . setLayoutData ( gd ) ; } public void initialize ( ) { initializeFields ( ) ; } private void initializeFields ( ) { boolean completionInserts = getBooleanValue ( PREF_CODEASSIST_INSERT_COMPLETION ) ; fCompletionInsertsRadioButton . setSelection ( completionInserts ) ; fCompletionOverwritesRadioButton . setSelection ( ! completionInserts ) ; updateAutoactivationControls ( ) ; } private void updateAutoactivationControls ( ) { boolean autoactivation = getBooleanValue ( PREF_CODEASSIST_AUTOACTIVATION ) ; setControlEnabled ( PREF_CODEASSIST_AUTOACTIVATION_DELAY , autoactivation ) ; setControlEnabled ( PREF_CODEASSIST_FILL_METHOD_BLOCK_ARGUMENTS , getBooleanValue ( PREF_CODEASSIST_FILL_ARGUMENT_NAMES ) ) ; } public void performDefaults ( ) { super . performDefaults ( ) ; initializeFields ( ) ; } protected String [ ] getFullBuildDialogStrings ( boolean workspaceSettings ) { return null ; } protected static IStatus validatePositiveNumber ( final String number ) { final StatusInfo status = new StatusInfo ( ) ; if ( number . length ( ) == ) { status . setError ( PreferencesMessages . SpellingPreferencePage_empty_threshold ) ; } else { try { final int value = Integer . parseInt ( number ) ; if ( value < ) { status . setError ( Messages . format ( PreferencesMessages . SpellingPreferencePage_invalid_threshold , number ) ) ; } } catch ( NumberFormatException exception ) { status . setError ( Messages . format ( PreferencesMessages . SpellingPreferencePage_invalid_threshold , number ) ) ; } } return status ; } protected void validateSettings ( Key key , String oldValue , String newValue ) { if ( key == null || PREF_CODEASSIST_AUTOACTIVATION_DELAY . equals ( key ) ) fContext . statusChanged ( validatePositiveNumber ( getValue ( PREF_CODEASSIST_AUTOACTIVATION_DELAY ) ) ) ; } public Control createControl ( Composite parent ) { ScrolledPageContent scrolled = new ScrolledPageContent ( parent , SWT . H_SCROLL | SWT . V_SCROLL ) ; scrolled . setDelayedReflow ( true ) ; scrolled . setExpandHorizontal ( true ) ; scrolled . setExpandVertical ( true ) ; Control control = createContents ( scrolled ) ; scrolled . setContent ( control ) ; final Point size = control . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; scrolled . setMinSize ( size . x , size . y ) ; return scrolled ; } protected void setControlEnabled ( Key key , boolean enabled ) { Control control = getControl ( key ) ; control . setEnabled ( enabled ) ; Label label = ( Label ) fLabels . get ( control ) ; if ( label != null ) label . setEnabled ( enabled ) ; } private Control getControl ( Key key ) { for ( int i = fComboBoxes . size ( ) - ; i >= ; i -- ) { Control curr = ( Control ) fComboBoxes . get ( i ) ; ControlData data = ( ControlData ) curr . getData ( ) ; if ( key . equals ( data . getKey ( ) ) ) { return curr ; } } for ( int i = fCheckBoxes . size ( ) - ; i >= ; i -- ) { Control curr = ( Control ) fCheckBoxes . get ( i ) ; ControlData data = ( ControlData ) curr . getData ( ) ; if ( key . equals ( data . getKey ( ) ) ) { return curr ; } } for ( int i = fTextBoxes . size ( ) - ; i >= ; i -- ) { Control curr = ( Control ) fTextBoxes . get ( i ) ; Key currKey = ( Key ) curr . getData ( ) ; if ( key . equals ( currKey ) ) { return curr ; } } return null ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import java . util . StringTokenizer ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementImageDescriptor ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; public class MembersOrderPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { public static final String PREF_ID = "" ; private static final String ALL_SORTMEMBER_ENTRIES = "" ; private static final String ALL_VISIBILITY_ENTRIES = "" ; private static final String PREF_OUTLINE_SORT_OPTION = PreferenceConstants . APPEARANCE_MEMBER_SORT_ORDER ; private static final String PREF_VISIBILITY_SORT_OPTION = PreferenceConstants . APPEARANCE_VISIBILITY_SORT_ORDER ; private static final String PREF_USE_VISIBILITY_SORT_OPTION = PreferenceConstants . APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER ; public static final String CONSTRUCTORS = "" ; public static final String FIELDS = "" ; public static final String METHODS = "" ; public static final String STATIC_METHODS = "" ; public static final String STATIC_FIELDS = "" ; public static final String TYPES = "" ; public static final String PUBLIC = "" ; public static final String PRIVATE = "" ; public static final String PROTECTED = "" ; private boolean fUseVisibilitySort ; private ListDialogField fSortOrderList ; private ListDialogField fVisibilityOrderList ; private SelectionButtonDialogField fUseVisibilitySortField ; private static boolean isValidEntries ( List entries , String entryString ) { StringTokenizer tokenizer = new StringTokenizer ( entryString , "" ) ; int i = ; for ( ; tokenizer . hasMoreTokens ( ) ; i ++ ) { String token = tokenizer . nextToken ( ) ; if ( ! entries . contains ( token ) ) return false ; } return i == entries . size ( ) ; } public MembersOrderPreferencePage ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( PreferencesMessages . MembersOrderPreferencePage_label_description ) ; String memberSortString = getPreferenceStore ( ) . getString ( PREF_OUTLINE_SORT_OPTION ) ; String upLabel = PreferencesMessages . MembersOrderPreferencePage_category_button_up ; String downLabel = PreferencesMessages . MembersOrderPreferencePage_category_button_down ; fSortOrderList = new ListDialogField ( null , new String [ ] { upLabel , downLabel } , new MemberSortLabelProvider ( ) ) ; fSortOrderList . setDownButtonIndex ( ) ; fSortOrderList . setUpButtonIndex ( ) ; List entries = parseList ( memberSortString ) ; if ( ! isValidEntries ( entries , ALL_SORTMEMBER_ENTRIES ) ) { memberSortString = getPreferenceStore ( ) . getDefaultString ( PREF_OUTLINE_SORT_OPTION ) ; entries = parseList ( memberSortString ) ; } fSortOrderList . setElements ( entries ) ; fUseVisibilitySort = getPreferenceStore ( ) . getBoolean ( PREF_USE_VISIBILITY_SORT_OPTION ) ; String visibilitySortString = getPreferenceStore ( ) . getString ( PREF_VISIBILITY_SORT_OPTION ) ; upLabel = PreferencesMessages . MembersOrderPreferencePage_visibility_button_up ; downLabel = PreferencesMessages . MembersOrderPreferencePage_visibility_button_down ; fVisibilityOrderList = new ListDialogField ( null , new String [ ] { upLabel , downLabel } , new VisibilitySortLabelProvider ( ) ) ; fVisibilityOrderList . setDownButtonIndex ( ) ; fVisibilityOrderList . setUpButtonIndex ( ) ; entries = parseList ( visibilitySortString ) ; if ( ! isValidEntries ( entries , ALL_VISIBILITY_ENTRIES ) ) { visibilitySortString = getPreferenceStore ( ) . getDefaultString ( PREF_VISIBILITY_SORT_OPTION ) ; entries = parseList ( visibilitySortString ) ; } fVisibilityOrderList . setElements ( entries ) ; } private static List parseList ( String string ) { StringTokenizer tokenizer = new StringTokenizer ( string , "" ) ; List entries = new ArrayList ( ) ; for ( int i = ; tokenizer . hasMoreTokens ( ) ; i ++ ) { String token = tokenizer . nextToken ( ) ; entries . add ( token ) ; } return entries ; } public void createControl ( Composite parent ) { super . createControl ( parent ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . SORT_ORDER_PREFERENCE_PAGE ) ; } protected Control createContents ( Composite parent ) { Composite sortComposite = new Composite ( parent , SWT . NONE ) ; sortComposite . setFont ( parent . getFont ( ) ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginWidth = ; layout . marginHeight = ; sortComposite . setLayout ( layout ) ; GridData gd = new GridData ( ) ; gd . verticalAlignment = GridData . FILL ; gd . horizontalAlignment = GridData . FILL_HORIZONTAL ; sortComposite . setLayoutData ( gd ) ; createListDialogField ( sortComposite , fSortOrderList ) ; fUseVisibilitySortField = new SelectionButtonDialogField ( SWT . CHECK ) ; fUseVisibilitySortField . setDialogFieldListener ( new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { fVisibilityOrderList . setEnabled ( fUseVisibilitySortField . isSelected ( ) ) ; } } ) ; fUseVisibilitySortField . setLabelText ( PreferencesMessages . MembersOrderPreferencePage_usevisibilitysort_label ) ; fUseVisibilitySortField . doFillIntoGrid ( sortComposite , ) ; fUseVisibilitySortField . setSelection ( fUseVisibilitySort ) ; createListDialogField ( sortComposite , fVisibilityOrderList ) ; fVisibilityOrderList . setEnabled ( fUseVisibilitySortField . isSelected ( ) ) ; Dialog . applyDialogFont ( sortComposite ) ; return sortComposite ; } private void createListDialogField ( Composite composite , ListDialogField dialogField ) { Control list = dialogField . getListControl ( composite ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = true ; gd . verticalAlignment = GridData . FILL ; gd . grabExcessVerticalSpace = true ; gd . widthHint = convertWidthInCharsToPixels ( ) ; list . setLayoutData ( gd ) ; Composite buttons = dialogField . getButtonBox ( composite ) ; gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . verticalAlignment = GridData . FILL ; gd . grabExcessVerticalSpace = true ; buttons . setLayoutData ( gd ) ; } public void init ( IWorkbench workbench ) { } protected void performDefaults ( ) { IPreferenceStore prefs = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; String str = prefs . getDefaultString ( PREF_OUTLINE_SORT_OPTION ) ; if ( str != null ) fSortOrderList . setElements ( parseList ( str ) ) ; else fSortOrderList . setElements ( parseList ( ALL_SORTMEMBER_ENTRIES ) ) ; str = prefs . getDefaultString ( PREF_VISIBILITY_SORT_OPTION ) ; if ( str != null ) fVisibilityOrderList . setElements ( parseList ( str ) ) ; else fVisibilityOrderList . setElements ( parseList ( ALL_VISIBILITY_ENTRIES ) ) ; fUseVisibilitySortField . setSelection ( prefs . getDefaultBoolean ( PREF_USE_VISIBILITY_SORT_OPTION ) ) ; super . performDefaults ( ) ; } public boolean performOk ( ) { IPreferenceStore store = getPreferenceStore ( ) ; updateList ( store , fSortOrderList , PREF_OUTLINE_SORT_OPTION ) ; updateList ( store , fVisibilityOrderList , PREF_VISIBILITY_SORT_OPTION ) ; store . setValue ( PREF_USE_VISIBILITY_SORT_OPTION , fUseVisibilitySortField . isSelected ( ) ) ; RubyPlugin . getDefault ( ) . savePluginPreferences ( ) ; return true ; } private void updateList ( IPreferenceStore store , ListDialogField list , String str ) { StringBuffer buf = new StringBuffer ( ) ; List curr = list . getElements ( ) ; for ( Iterator iter = curr . iterator ( ) ; iter . hasNext ( ) ; ) { String s = ( String ) iter . next ( ) ; buf . append ( s ) ; buf . append ( '' ) ; } store . setValue ( str , buf . toString ( ) ) ; } private class MemberSortLabelProvider extends LabelProvider { public MemberSortLabelProvider ( ) { } public Image getImage ( Object element ) { ImageDescriptorRegistry registry = RubyPlugin . getImageDescriptorRegistry ( ) ; ImageDescriptor descriptor = null ; if ( element instanceof String ) { int visibility = IMethod . PUBLIC ; String s = ( String ) element ; if ( s . equals ( FIELDS ) ) { descriptor = RubyElementImageProvider . getConstantImageDescriptor ( ) ; } else if ( s . equals ( CONSTRUCTORS ) ) { descriptor = RubyElementImageProvider . getMethodImageDescriptor ( visibility ) ; descriptor = new RubyElementImageDescriptor ( descriptor , RubyElementImageDescriptor . CONSTRUCTOR , RubyElementImageProvider . SMALL_SIZE ) ; } else if ( s . equals ( METHODS ) ) { descriptor = RubyElementImageProvider . getMethodImageDescriptor ( visibility ) ; } else if ( s . equals ( STATIC_FIELDS ) ) { descriptor = RubyElementImageProvider . getConstantImageDescriptor ( ) ; descriptor = new RubyElementImageDescriptor ( descriptor , RubyElementImageDescriptor . STATIC , RubyElementImageProvider . SMALL_SIZE ) ; } else if ( s . equals ( STATIC_METHODS ) ) { descriptor = RubyElementImageProvider . getMethodImageDescriptor ( visibility ) ; descriptor = new RubyElementImageDescriptor ( descriptor , RubyElementImageDescriptor . STATIC , RubyElementImageProvider . SMALL_SIZE ) ; } else if ( s . equals ( TYPES ) ) { descriptor = RubyElementImageProvider . getTypeImageDescriptor ( false , false , false ) ; } else { descriptor = RubyElementImageProvider . getMethodImageDescriptor ( IMethod . PUBLIC ) ; } return registry . get ( descriptor ) ; } return null ; } public String getText ( Object element ) { if ( element instanceof String ) { String s = ( String ) element ; if ( s . equals ( FIELDS ) ) { return PreferencesMessages . MembersOrderPreferencePage_fields_label ; } else if ( s . equals ( METHODS ) ) { return PreferencesMessages . MembersOrderPreferencePage_methods_label ; } else if ( s . equals ( STATIC_FIELDS ) ) { return PreferencesMessages . MembersOrderPreferencePage_staticfields_label ; } else if ( s . equals ( STATIC_METHODS ) ) { return PreferencesMessages . MembersOrderPreferencePage_staticmethods_label ; } else if ( s . equals ( CONSTRUCTORS ) ) { return PreferencesMessages . MembersOrderPreferencePage_constructors_label ; } else if ( s . equals ( TYPES ) ) { return PreferencesMessages . MembersOrderPreferencePage_types_label ; } } return "" ; } } private class VisibilitySortLabelProvider extends LabelProvider { public VisibilitySortLabelProvider ( ) { } public Image getImage ( Object element ) { ImageDescriptorRegistry registry = RubyPlugin . getImageDescriptorRegistry ( ) ; ImageDescriptor descriptor = null ; if ( element instanceof String ) { String s = ( String ) element ; if ( s . equals ( PUBLIC ) ) { descriptor = RubyElementImageProvider . getMethodImageDescriptor ( IMethod . PUBLIC ) ; } else if ( s . equals ( PRIVATE ) ) { descriptor = RubyElementImageProvider . getMethodImageDescriptor ( IMethod . PRIVATE ) ; } else if ( s . equals ( PROTECTED ) ) { descriptor = RubyElementImageProvider . getMethodImageDescriptor ( IMethod . PROTECTED ) ; } return registry . get ( descriptor ) ; } return null ; } public String getText ( Object element ) { if ( element instanceof String ) { String s = ( String ) element ; if ( s . equals ( PUBLIC ) ) { return PreferencesMessages . MembersOrderPreferencePage_public_label ; } else if ( s . equals ( PRIVATE ) ) { return PreferencesMessages . MembersOrderPreferencePage_private_label ; } else if ( s . equals ( PROTECTED ) ) { return PreferencesMessages . MembersOrderPreferencePage_protected_label ; } } return "" ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public interface IPreferenceConfigurationBlock { Control createControl ( Composite parent ) ; void initialize ( ) ; void performOk ( ) ; void performDefaults ( ) ; void dispose ( ) ; } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . viewers . IFontProvider ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogField ; public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock { private static final Key PREF_COMPILER_TASK_TAGS = getRDTCoreKey ( RubyCore . COMPILER_TASK_TAGS ) ; private static final Key PREF_COMPILER_TASK_PRIORITIES = getRDTCoreKey ( RubyCore . COMPILER_TASK_PRIORITIES ) ; private static final Key PREF_COMPILER_TASK_CASE_SENSITIVE = getRDTCoreKey ( RubyCore . COMPILER_TASK_CASE_SENSITIVE ) ; private static final String PRIORITY_HIGH = RubyCore . COMPILER_TASK_PRIORITY_HIGH ; private static final String PRIORITY_NORMAL = RubyCore . COMPILER_TASK_PRIORITY_NORMAL ; private static final String PRIORITY_LOW = RubyCore . COMPILER_TASK_PRIORITY_LOW ; private static final String ENABLED = RubyCore . ENABLED ; private static final String DISABLED = RubyCore . DISABLED ; public static class TodoTask { public String name ; public String priority ; } private class TodoTaskLabelProvider extends LabelProvider implements ITableLabelProvider , IFontProvider { public TodoTaskLabelProvider ( ) { } public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { return getColumnText ( element , ) ; } public Image getColumnImage ( Object element , int columnIndex ) { return null ; } public String getColumnText ( Object element , int columnIndex ) { TodoTask task = ( TodoTask ) element ; if ( columnIndex == ) { String name = task . name ; if ( isDefaultTask ( task ) ) { name = Messages . format ( PreferencesMessages . TodoTaskConfigurationBlock_tasks_default , name ) ; } return name ; } else { if ( PRIORITY_HIGH . equals ( task . priority ) ) { return PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_high_priority ; } else if ( PRIORITY_NORMAL . equals ( task . priority ) ) { return PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_normal_priority ; } else if ( PRIORITY_LOW . equals ( task . priority ) ) { return PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_low_priority ; } return "" ; } } public Font getFont ( Object element ) { if ( isDefaultTask ( ( TodoTask ) element ) ) { return JFaceResources . getFontRegistry ( ) . getBold ( JFaceResources . DIALOG_FONT ) ; } return null ; } } private static class TodoTaskSorter extends ViewerSorter { public int compare ( Viewer viewer , Object e1 , Object e2 ) { return collator . compare ( ( ( TodoTask ) e1 ) . name , ( ( TodoTask ) e2 ) . name ) ; } } private static final int IDX_ADD = ; private static final int IDX_EDIT = ; private static final int IDX_REMOVE = ; private static final int IDX_DEFAULT = ; private IStatus fTaskTagsStatus ; private ListDialogField fTodoTasksList ; private SelectionButtonDialogField fCaseSensitiveCheckBox ; public TodoTaskConfigurationBlock ( IStatusChangeListener context , IProject project , IWorkbenchPreferenceContainer container ) { super ( context , project , getKeys ( ) , container ) ; TaskTagAdapter adapter = new TaskTagAdapter ( ) ; String [ ] buttons = new String [ ] { PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_add_button , PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_edit_button , PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_remove_button , null , PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_setdefault_button , } ; fTodoTasksList = new ListDialogField ( adapter , buttons , new TodoTaskLabelProvider ( ) ) ; fTodoTasksList . setDialogFieldListener ( adapter ) ; fTodoTasksList . setRemoveButtonIndex ( IDX_REMOVE ) ; String [ ] columnsHeaders = new String [ ] { PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_name_column , PreferencesMessages . TodoTaskConfigurationBlock_markers_tasks_priority_column , } ; fTodoTasksList . setTableColumns ( new ListDialogField . ColumnsDescription ( columnsHeaders , true ) ) ; fTodoTasksList . setViewerSorter ( new TodoTaskSorter ( ) ) ; fCaseSensitiveCheckBox = new SelectionButtonDialogField ( SWT . CHECK ) ; fCaseSensitiveCheckBox . setLabelText ( PreferencesMessages . TodoTaskConfigurationBlock_casesensitive_label ) ; fCaseSensitiveCheckBox . setDialogFieldListener ( adapter ) ; unpackTodoTasks ( ) ; if ( fTodoTasksList . getSize ( ) > ) { fTodoTasksList . selectFirstElement ( ) ; } else { fTodoTasksList . enableButton ( IDX_EDIT , false ) ; fTodoTasksList . enableButton ( IDX_DEFAULT , false ) ; } fTaskTagsStatus = new StatusInfo ( ) ; } public void setEnabled ( boolean isEnabled ) { fTodoTasksList . setEnabled ( isEnabled ) ; fCaseSensitiveCheckBox . setEnabled ( isEnabled ) ; } final boolean isDefaultTask ( TodoTask task ) { return fTodoTasksList . getIndexOfElement ( task ) == ; } private void setToDefaultTask ( TodoTask task ) { List elements = fTodoTasksList . getElements ( ) ; elements . remove ( task ) ; elements . add ( , task ) ; fTodoTasksList . setElements ( elements ) ; fTodoTasksList . enableButton ( IDX_DEFAULT , false ) ; } private static Key [ ] getKeys ( ) { return new Key [ ] { PREF_COMPILER_TASK_TAGS , PREF_COMPILER_TASK_PRIORITIES , PREF_COMPILER_TASK_CASE_SENSITIVE } ; } public class TaskTagAdapter implements IListAdapter , IDialogFieldListener { private boolean canEdit ( List selectedElements ) { return selectedElements . size ( ) == ; } private boolean canSetToDefault ( List selectedElements ) { return selectedElements . size ( ) == && ! isDefaultTask ( ( TodoTask ) selectedElements . get ( ) ) ; } public void customButtonPressed ( ListDialogField field , int index ) { doTodoButtonPressed ( index ) ; } public void selectionChanged ( ListDialogField field ) { List selectedElements = field . getSelectedElements ( ) ; field . enableButton ( IDX_EDIT , canEdit ( selectedElements ) ) ; field . enableButton ( IDX_DEFAULT , canSetToDefault ( selectedElements ) ) ; } public void doubleClicked ( ListDialogField field ) { if ( canEdit ( field . getSelectedElements ( ) ) ) { doTodoButtonPressed ( IDX_EDIT ) ; } } public void dialogFieldChanged ( DialogField field ) { updateModel ( field ) ; } } protected Control createContents ( Composite parent ) { setShell ( parent . getShell ( ) ) ; Composite markersComposite = createMarkersTabContent ( parent ) ; validateSettings ( null , null , null ) ; return markersComposite ; } private Composite createMarkersTabContent ( Composite folder ) { GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; PixelConverter conv = new PixelConverter ( folder ) ; Composite markersComposite = new Composite ( folder , SWT . NULL ) ; markersComposite . setLayout ( layout ) ; markersComposite . setFont ( folder . getFont ( ) ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . widthHint = conv . convertWidthInCharsToPixels ( ) ; Control listControl = fTodoTasksList . getListControl ( markersComposite ) ; listControl . setLayoutData ( data ) ; Control buttonsControl = fTodoTasksList . getButtonBox ( markersComposite ) ; buttonsControl . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . VERTICAL_ALIGN_BEGINNING ) ) ; fCaseSensitiveCheckBox . doFillIntoGrid ( markersComposite , ) ; return markersComposite ; } protected void validateSettings ( Key changedKey , String oldValue , String newValue ) { if ( ! areSettingsEnabled ( ) ) { return ; } if ( changedKey != null ) { if ( PREF_COMPILER_TASK_TAGS . equals ( changedKey ) ) { fTaskTagsStatus = validateTaskTags ( ) ; } else { return ; } } else { fTaskTagsStatus = validateTaskTags ( ) ; } IStatus status = fTaskTagsStatus ; fContext . statusChanged ( status ) ; } private IStatus validateTaskTags ( ) { return new StatusInfo ( ) ; } protected final void updateModel ( DialogField field ) { if ( field == fTodoTasksList ) { StringBuffer tags = new StringBuffer ( ) ; StringBuffer prios = new StringBuffer ( ) ; List list = fTodoTasksList . getElements ( ) ; for ( int i = ; i < list . size ( ) ; i ++ ) { if ( i > ) { tags . append ( '' ) ; prios . append ( '' ) ; } TodoTask elem = ( TodoTask ) list . get ( i ) ; tags . append ( elem . name ) ; prios . append ( elem . priority ) ; } setValue ( PREF_COMPILER_TASK_TAGS , tags . toString ( ) ) ; setValue ( PREF_COMPILER_TASK_PRIORITIES , prios . toString ( ) ) ; validateSettings ( PREF_COMPILER_TASK_TAGS , null , null ) ; } else if ( field == fCaseSensitiveCheckBox ) { String state = fCaseSensitiveCheckBox . isSelected ( ) ? ENABLED : DISABLED ; setValue ( PREF_COMPILER_TASK_CASE_SENSITIVE , state ) ; } } protected String [ ] getFullBuildDialogStrings ( boolean workspaceSettings ) { String title = PreferencesMessages . TodoTaskConfigurationBlock_needsbuild_title ; String message ; if ( fProject == null ) { message = PreferencesMessages . TodoTaskConfigurationBlock_needsfullbuild_message ; } else { message = PreferencesMessages . TodoTaskConfigurationBlock_needsprojectbuild_message ; } return new String [ ] { title , message } ; } protected void updateControls ( ) { unpackTodoTasks ( ) ; } private void unpackTodoTasks ( ) { String currTags = getValue ( PREF_COMPILER_TASK_TAGS ) ; String currPrios = getValue ( PREF_COMPILER_TASK_PRIORITIES ) ; String [ ] tags = getTokens ( currTags , "" ) ; String [ ] prios = getTokens ( currPrios , "" ) ; ArrayList elements = new ArrayList ( tags . length ) ; for ( int i = ; i < tags . length ; i ++ ) { TodoTask task = new TodoTask ( ) ; task . name = tags [ i ] . trim ( ) ; task . priority = ( i < prios . length ) ? prios [ i ] : PRIORITY_NORMAL ; elements . add ( task ) ; } fTodoTasksList . setElements ( elements ) ; boolean isCaseSensitive = checkValue ( PREF_COMPILER_TASK_CASE_SENSITIVE , ENABLED ) ; fCaseSensitiveCheckBox . setSelection ( isCaseSensitive ) ; } private void doTodoButtonPressed ( int index ) { TodoTask edited = null ; if ( index != IDX_ADD ) { edited = ( TodoTask ) fTodoTasksList . getSelectedElements ( ) . get ( ) ; } if ( index == IDX_ADD || index == IDX_EDIT ) { TodoTaskInputDialog dialog = new TodoTaskInputDialog ( getShell ( ) , edited , fTodoTasksList . getElements ( ) ) ; if ( dialog . open ( ) == Window . OK ) { if ( edited != null ) { fTodoTasksList . replaceElement ( edited , dialog . getResult ( ) ) ; } else { fTodoTasksList . addElement ( dialog . getResult ( ) ) ; } } } else if ( index == IDX_DEFAULT ) { setToDefaultTask ( edited ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . resources . IProject ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; public class CodeAssistPreferencePage extends PropertyAndPreferencePage implements IWorkbenchPreferencePage { private CodeAssistConfigurationBlock fConfigurationBlock ; public void createControl ( Composite parent ) { IWorkbenchPreferenceContainer container = ( IWorkbenchPreferenceContainer ) getContainer ( ) ; fConfigurationBlock = new CodeAssistConfigurationBlock ( getNewStatusChangedListener ( ) , container ) ; super . createControl ( parent ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . RUBY_EDITOR_PREFERENCE_PAGE ) ; } protected Control createPreferenceContent ( Composite composite ) { return fConfigurationBlock . createContents ( composite ) ; } protected boolean hasProjectSpecificOptions ( IProject project ) { return false ; } protected String getPreferencePageID ( ) { return "" ; } protected String getPropertyPageID ( ) { return null ; } public void dispose ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . dispose ( ) ; } super . dispose ( ) ; } protected void performDefaults ( ) { super . performDefaults ( ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . performDefaults ( ) ; } } public boolean performOk ( ) { if ( fConfigurationBlock != null && ! fConfigurationBlock . performOk ( ) ) { return false ; } return super . performOk ( ) ; } public void performApply ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . performApply ( ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . commands . Command ; import org . eclipse . core . commands . CommandManager ; import org . eclipse . core . commands . IParameter ; import org . eclipse . core . commands . Parameterization ; import org . eclipse . core . commands . ParameterizedCommand ; import org . eclipse . core . commands . common . NotDefinedException ; import org . eclipse . core . commands . contexts . ContextManager ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . bindings . BindingManager ; import org . eclipse . jface . bindings . Scheme ; import org . eclipse . jface . bindings . TriggerSequence ; import org . eclipse . jface . layout . PixelConverter ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . viewers . ArrayContentProvider ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . ViewerComparator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Link ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . commands . ICommandService ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . eclipse . ui . keys . IBindingService ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . ruby . CompletionProposalCategory ; import org . rubypeople . rdt . internal . ui . text . ruby . CompletionProposalComputerRegistry ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . ui . PreferenceConstants ; final class CodeAssistAdvancedConfigurationBlock extends OptionsConfigurationBlock { private static final Key PREF_EXCLUDED_CATEGORIES = getRDTUIKey ( PreferenceConstants . CODEASSIST_EXCLUDED_CATEGORIES ) ; private static final Key PREF_CATEGORY_ORDER = getRDTUIKey ( PreferenceConstants . CODEASSIST_CATEGORY_ORDER ) ; private static Key [ ] getAllKeys ( ) { return new Key [ ] { PREF_EXCLUDED_CATEGORIES , PREF_CATEGORY_ORDER } ; } private final class DefaultTableLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage ( Object element , int columnIndex ) { if ( columnIndex == ) return ( ( ModelElement ) element ) . getImage ( ) ; return null ; } public String getColumnText ( Object element , int columnIndex ) { switch ( columnIndex ) { case : return ( ( ModelElement ) element ) . getName ( ) ; case : return ( ( ModelElement ) element ) . getKeybindingAsString ( ) ; default : Assert . isTrue ( false ) ; return null ; } } public String getText ( Object element ) { return getColumnText ( element , ) ; } } private final class SeparateTableLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage ( Object element , int columnIndex ) { if ( columnIndex == ) return ( ( ModelElement ) element ) . getImage ( ) ; return null ; } public String getColumnText ( Object element , int columnIndex ) { switch ( columnIndex ) { case : return ( ( ModelElement ) element ) . getName ( ) ; default : Assert . isTrue ( false ) ; return null ; } } } private final Comparator fCategoryComparator = new Comparator ( ) { private int getRank ( Object o ) { return ( ( ModelElement ) o ) . getRank ( ) ; } public int compare ( Object o1 , Object o2 ) { return getRank ( o1 ) - getRank ( o2 ) ; } } ; private final class PreferenceModel { private static final int LIMIT = ; private static final String COLON = "" ; private static final String SEPARATOR = "" ; private final List < ModelElement > fElements ; final List < ModelElement > elements ; public PreferenceModel ( CompletionProposalComputerRegistry registry ) { List < CompletionProposalCategory > categories = registry . getProposalCategories ( ) ; fElements = new ArrayList < ModelElement > ( ) ; for ( CompletionProposalCategory category : categories ) { if ( category . hasComputers ( ) ) { fElements . add ( new ModelElement ( category , this ) ) ; } } Collections . sort ( fElements , fCategoryComparator ) ; elements = Collections . unmodifiableList ( fElements ) ; } public void moveUp ( ModelElement category ) { int index = fElements . indexOf ( category ) ; if ( index > ) { ModelElement item = fElements . remove ( index ) ; fElements . add ( index - , item ) ; writeOrderPreference ( null , false ) ; } } public void moveDown ( ModelElement category ) { int index = fElements . indexOf ( category ) ; if ( index < fElements . size ( ) - ) { ModelElement item = fElements . remove ( index ) ; fElements . add ( index + , item ) ; writeOrderPreference ( null , false ) ; } } private void writeInclusionPreference ( ModelElement changed , boolean isInDefaultCategory ) { StringBuffer buf = new StringBuffer ( ) ; for ( ModelElement item : fElements ) { boolean included = changed == item ? isInDefaultCategory : item . isInDefaultCategory ( ) ; if ( ! included ) buf . append ( item . getId ( ) + SEPARATOR ) ; } String newValue = buf . toString ( ) ; String oldValue = setValue ( PREF_EXCLUDED_CATEGORIES , newValue ) ; validateSettings ( PREF_EXCLUDED_CATEGORIES , oldValue , newValue ) ; } private void writeOrderPreference ( ModelElement changed , boolean isSeparate ) { StringBuffer buf = new StringBuffer ( ) ; int i = ; for ( Iterator it = fElements . iterator ( ) ; it . hasNext ( ) ; i ++ ) { ModelElement item = ( ModelElement ) it . next ( ) ; boolean separate = changed == item ? isSeparate : item . isSeparateCommand ( ) ; int rank = separate ? i : i + LIMIT ; buf . append ( item . getId ( ) + COLON + rank + SEPARATOR ) ; } String newValue = buf . toString ( ) ; String oldValue = setValue ( PREF_CATEGORY_ORDER , newValue ) ; validateSettings ( PREF_CATEGORY_ORDER , oldValue , newValue ) ; } private boolean readInclusionPreference ( CompletionProposalCategory cat ) { String [ ] ids = getTokens ( getValue ( PREF_EXCLUDED_CATEGORIES ) , SEPARATOR ) ; for ( int i = ; i < ids . length ; i ++ ) { if ( ids [ i ] . equals ( cat . getId ( ) ) ) return false ; } return true ; } private int readOrderPreference ( CompletionProposalCategory cat ) { String [ ] sortOrderIds = getTokens ( getValue ( PREF_CATEGORY_ORDER ) , SEPARATOR ) ; for ( int i = ; i < sortOrderIds . length ; i ++ ) { String [ ] idAndRank = getTokens ( sortOrderIds [ i ] , COLON ) ; if ( idAndRank [ ] . equals ( cat . getId ( ) ) ) return Integer . parseInt ( idAndRank [ ] ) ; } return LIMIT - ; } public void update ( ) { Collections . sort ( fElements , fCategoryComparator ) ; } } private final class ModelElement { private final CompletionProposalCategory fCategory ; private final Command fCommand ; private final IParameter fParam ; private final PreferenceModel fPreferenceModel ; ModelElement ( CompletionProposalCategory category , PreferenceModel model ) { fCategory = category ; ICommandService commandSvc = ( ICommandService ) PlatformUI . getWorkbench ( ) . getAdapter ( ICommandService . class ) ; fCommand = commandSvc . getCommand ( "" ) ; IParameter type ; try { type = fCommand . getParameters ( ) [ ] ; } catch ( NotDefinedException x ) { Assert . isTrue ( false ) ; type = null ; } fParam = type ; fPreferenceModel = model ; } Image getImage ( ) { return CodeAssistAdvancedConfigurationBlock . this . getImage ( fCategory . getImageDescriptor ( ) ) ; } String getName ( ) { return fCategory . getDisplayName ( ) ; } String getKeybindingAsString ( ) { final Parameterization [ ] params = { new Parameterization ( fParam , fCategory . getId ( ) ) } ; final ParameterizedCommand pCmd = new ParameterizedCommand ( fCommand , params ) ; String key = getKeyboardShortcut ( pCmd ) ; return key ; } boolean isInDefaultCategory ( ) { return fPreferenceModel . readInclusionPreference ( fCategory ) ; } void setInDefaultCategory ( boolean included ) { if ( included != isInDefaultCategory ( ) ) fPreferenceModel . writeInclusionPreference ( this , included ) ; } String getId ( ) { return fCategory . getId ( ) ; } int getRank ( ) { int rank = getInternalRank ( ) ; if ( rank > PreferenceModel . LIMIT ) return rank - PreferenceModel . LIMIT ; return rank ; } void moveUp ( ) { fPreferenceModel . moveUp ( this ) ; } void moveDown ( ) { fPreferenceModel . moveDown ( this ) ; } private int getInternalRank ( ) { return fPreferenceModel . readOrderPreference ( fCategory ) ; } boolean isSeparateCommand ( ) { return getInternalRank ( ) < PreferenceModel . LIMIT ; } void setSeparateCommand ( boolean separate ) { if ( separate != isSeparateCommand ( ) ) fPreferenceModel . writeOrderPreference ( this , separate ) ; } void update ( ) { fCategory . setIncluded ( isInDefaultCategory ( ) ) ; int rank = getInternalRank ( ) ; fCategory . setSortOrder ( rank ) ; fCategory . setSeparateCommand ( rank < PreferenceModel . LIMIT ) ; } } private final PreferenceModel fModel ; private final Map fImages = new HashMap ( ) ; private CheckboxTableViewer fDefaultViewer ; private CheckboxTableViewer fSeparateViewer ; private Button fUpButton ; private Button fDownButton ; CodeAssistAdvancedConfigurationBlock ( IStatusChangeListener statusListener , IWorkbenchPreferenceContainer container ) { super ( statusListener , null , getAllKeys ( ) , container ) ; fModel = new PreferenceModel ( CompletionProposalComputerRegistry . getDefault ( ) ) ; } protected Control createContents ( Composite parent ) { ScrolledPageContent scrolled = new ScrolledPageContent ( parent , SWT . H_SCROLL | SWT . V_SCROLL ) ; scrolled . setExpandHorizontal ( true ) ; scrolled . setExpandVertical ( true ) ; Composite composite = new Composite ( scrolled , SWT . NONE ) ; int columns = ; GridLayout layout = new GridLayout ( columns , false ) ; layout . marginWidth = ; layout . marginHeight = ; composite . setLayout ( layout ) ; createDefaultLabel ( composite , columns ) ; createDefaultViewer ( composite , columns ) ; createKeysLink ( composite , columns ) ; createFiller ( composite , columns ) ; createSeparateLabel ( composite , columns ) ; createSeparateSection ( composite ) ; createFiller ( composite , columns ) ; updateControls ( ) ; if ( fModel . elements . size ( ) > ) { fDefaultViewer . getTable ( ) . select ( ) ; fSeparateViewer . getTable ( ) . select ( ) ; handleTableSelection ( ) ; } scrolled . setContent ( composite ) ; scrolled . setMinSize ( composite . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ) ; return scrolled ; } private void createDefaultLabel ( Composite composite , int h_span ) { final ICommandService commandSvc = ( ICommandService ) PlatformUI . getWorkbench ( ) . getAdapter ( ICommandService . class ) ; final Command command = commandSvc . getCommand ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS ) ; ParameterizedCommand pCmd = new ParameterizedCommand ( command , null ) ; String key = getKeyboardShortcut ( pCmd ) ; if ( key == null ) key = PreferencesMessages . CodeAssistAdvancedConfigurationBlock_no_shortcut ; PixelConverter pixelConverter = new PixelConverter ( composite ) ; int width = pixelConverter . convertWidthInCharsToPixels ( ) ; Label label = new Label ( composite , SWT . NONE | SWT . WRAP ) ; label . setText ( Messages . format ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_page_description , new Object [ ] { key } ) ) ; GridData gd = new GridData ( GridData . FILL , GridData . FILL , true , false , h_span , ) ; gd . widthHint = width ; label . setLayoutData ( gd ) ; createFiller ( composite , h_span ) ; label = new Label ( composite , SWT . NONE | SWT . WRAP ) ; label . setText ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_default_table_description ) ; gd = new GridData ( GridData . FILL , GridData . FILL , true , false , h_span , ) ; gd . widthHint = width ; label . setLayoutData ( gd ) ; } private void createDefaultViewer ( Composite composite , int h_span ) { fDefaultViewer = CheckboxTableViewer . newCheckList ( composite , SWT . SINGLE | SWT . BORDER ) ; Table table = fDefaultViewer . getTable ( ) ; table . setHeaderVisible ( true ) ; table . setLinesVisible ( false ) ; table . setLayoutData ( new GridData ( GridData . FILL , GridData . BEGINNING , false , false , h_span , ) ) ; TableColumn nameColumn = new TableColumn ( table , SWT . NONE ) ; nameColumn . setText ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_default_table_category_column_title ) ; nameColumn . setResizable ( false ) ; TableColumn keyColumn = new TableColumn ( table , SWT . NONE ) ; keyColumn . setText ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_default_table_keybinding_column_title ) ; keyColumn . setResizable ( false ) ; fDefaultViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { boolean checked = event . getChecked ( ) ; ModelElement element = ( ModelElement ) event . getElement ( ) ; element . setInDefaultCategory ( checked ) ; } } ) ; fDefaultViewer . setContentProvider ( new ArrayContentProvider ( ) ) ; DefaultTableLabelProvider labelProvider = new DefaultTableLabelProvider ( ) ; fDefaultViewer . setLabelProvider ( labelProvider ) ; fDefaultViewer . setInput ( fModel . elements ) ; fDefaultViewer . setComparator ( new ViewerComparator ( ) ) ; final int ICON_AND_CHECKBOX_WITH = ; final int HEADER_MARGIN = ; int minNameWidth = computeWidth ( table , nameColumn . getText ( ) ) + HEADER_MARGIN ; int minKeyWidth = computeWidth ( table , keyColumn . getText ( ) ) + HEADER_MARGIN ; for ( int i = ; i < fModel . elements . size ( ) ; i ++ ) { minNameWidth = Math . max ( minNameWidth , computeWidth ( table , labelProvider . getColumnText ( fModel . elements . get ( i ) , ) ) + ICON_AND_CHECKBOX_WITH ) ; minKeyWidth = Math . max ( minKeyWidth , computeWidth ( table , labelProvider . getColumnText ( fModel . elements . get ( i ) , ) ) ) ; } nameColumn . setWidth ( minNameWidth ) ; keyColumn . setWidth ( minKeyWidth ) ; } private void createKeysLink ( Composite composite , int h_span ) { Link link = new Link ( composite , SWT . NONE | SWT . WRAP ) ; link . setText ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_key_binding_hint ) ; link . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { PreferencesUtil . createPreferenceDialogOn ( getShell ( ) , e . text , null , null ) ; } } ) ; PixelConverter pixelConverter = new PixelConverter ( composite ) ; int width = pixelConverter . convertWidthInCharsToPixels ( ) ; GridData gd = new GridData ( GridData . FILL , GridData . FILL , false , false , h_span , ) ; gd . widthHint = width ; link . setLayoutData ( gd ) ; } private void createFiller ( Composite composite , int h_span ) { Label filler = new Label ( composite , SWT . NONE ) ; filler . setVisible ( false ) ; filler . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , false , h_span , ) ) ; } private void createSeparateLabel ( Composite composite , int h_span ) { PixelConverter pixelConverter = new PixelConverter ( composite ) ; int width = pixelConverter . convertWidthInCharsToPixels ( ) ; Label label = new Label ( composite , SWT . NONE | SWT . WRAP ) ; label . setText ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_separate_table_description ) ; GridData gd = new GridData ( GridData . FILL , GridData . FILL , false , false , h_span , ) ; gd . widthHint = width ; label . setLayoutData ( gd ) ; } private void createSeparateSection ( Composite composite ) { createSeparateViewer ( composite ) ; createButtonList ( composite ) ; } private void createSeparateViewer ( Composite composite ) { fSeparateViewer = CheckboxTableViewer . newCheckList ( composite , SWT . SINGLE | SWT . BORDER ) ; Table table = fSeparateViewer . getTable ( ) ; table . setHeaderVisible ( false ) ; table . setLinesVisible ( false ) ; table . setLayoutData ( new GridData ( GridData . FILL , GridData . BEGINNING , true , false , , ) ) ; TableColumn nameColumn = new TableColumn ( table , SWT . NONE ) ; nameColumn . setText ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title ) ; nameColumn . setResizable ( false ) ; fSeparateViewer . setContentProvider ( new ArrayContentProvider ( ) ) ; ITableLabelProvider labelProvider = new SeparateTableLabelProvider ( ) ; fSeparateViewer . setLabelProvider ( labelProvider ) ; fSeparateViewer . setInput ( fModel . elements ) ; final int ICON_AND_CHECKBOX_WITH = ; final int HEADER_MARGIN = ; int minNameWidth = computeWidth ( table , nameColumn . getText ( ) ) + HEADER_MARGIN ; for ( int i = ; i < fModel . elements . size ( ) ; i ++ ) { minNameWidth = Math . max ( minNameWidth , computeWidth ( table , labelProvider . getColumnText ( fModel . elements . get ( i ) , ) ) + ICON_AND_CHECKBOX_WITH ) ; } nameColumn . setWidth ( minNameWidth ) ; fSeparateViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { boolean checked = event . getChecked ( ) ; ModelElement element = ( ModelElement ) event . getElement ( ) ; element . setSeparateCommand ( checked ) ; } } ) ; table . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { handleTableSelection ( ) ; } } ) ; } private void createButtonList ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . BEGINNING , false , false ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginWidth = ; layout . marginHeight = ; composite . setLayout ( layout ) ; fUpButton = new Button ( composite , SWT . PUSH | SWT . CENTER ) ; fUpButton . setText ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_Up ) ; fUpButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { int index = getSelectionIndex ( ) ; if ( index != - ) { ( ( ModelElement ) fModel . elements . get ( index ) ) . moveUp ( ) ; fSeparateViewer . refresh ( ) ; handleTableSelection ( ) ; } } } ) ; fUpButton . setLayoutData ( new GridData ( ) ) ; SWTUtil . setButtonDimensionHint ( fUpButton ) ; fDownButton = new Button ( composite , SWT . PUSH | SWT . CENTER ) ; fDownButton . setText ( PreferencesMessages . CodeAssistAdvancedConfigurationBlock_Down ) ; fDownButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { int index = getSelectionIndex ( ) ; if ( index != - ) { ( ( ModelElement ) fModel . elements . get ( index ) ) . moveDown ( ) ; fSeparateViewer . refresh ( ) ; handleTableSelection ( ) ; } } } ) ; fDownButton . setLayoutData ( new GridData ( ) ) ; SWTUtil . setButtonDimensionHint ( fDownButton ) ; } private void handleTableSelection ( ) { ModelElement item = getSelectedItem ( ) ; if ( item != null ) { int index = getSelectionIndex ( ) ; fUpButton . setEnabled ( index > ) ; fDownButton . setEnabled ( index < fModel . elements . size ( ) - ) ; } else { fUpButton . setEnabled ( false ) ; fDownButton . setEnabled ( false ) ; } } private ModelElement getSelectedItem ( ) { return ( ModelElement ) ( ( IStructuredSelection ) fSeparateViewer . getSelection ( ) ) . getFirstElement ( ) ; } private int getSelectionIndex ( ) { return fSeparateViewer . getTable ( ) . getSelectionIndex ( ) ; } protected void updateControls ( ) { super . updateControls ( ) ; fModel . update ( ) ; updateCheckedState ( ) ; fDefaultViewer . refresh ( ) ; fSeparateViewer . refresh ( ) ; handleTableSelection ( ) ; } private void updateCheckedState ( ) { final int size = fModel . elements . size ( ) ; List defaultChecked = new ArrayList ( size ) ; List separateChecked = new ArrayList ( size ) ; for ( Iterator it = fModel . elements . iterator ( ) ; it . hasNext ( ) ; ) { ModelElement element = ( ModelElement ) it . next ( ) ; if ( element . isInDefaultCategory ( ) ) defaultChecked . add ( element ) ; if ( element . isSeparateCommand ( ) ) separateChecked . add ( element ) ; } fDefaultViewer . setCheckedElements ( defaultChecked . toArray ( new Object [ defaultChecked . size ( ) ] ) ) ; fSeparateViewer . setCheckedElements ( separateChecked . toArray ( new Object [ separateChecked . size ( ) ] ) ) ; } protected boolean processChanges ( IWorkbenchPreferenceContainer container ) { for ( Iterator it = fModel . elements . iterator ( ) ; it . hasNext ( ) ; ) { ModelElement item = ( ModelElement ) it . next ( ) ; item . update ( ) ; } return super . processChanges ( container ) ; } protected String [ ] getFullBuildDialogStrings ( boolean workspaceSettings ) { return null ; } public void dispose ( ) { for ( Iterator it = fImages . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Image image = ( Image ) it . next ( ) ; image . dispose ( ) ; } super . dispose ( ) ; } private int computeWidth ( Control control , String name ) { if ( name == null ) return ; GC gc = new GC ( control ) ; try { gc . setFont ( JFaceResources . getDialogFont ( ) ) ; return gc . stringExtent ( name ) . x + ; } finally { gc . dispose ( ) ; } } private static BindingManager fgLocalBindingManager ; static { fgLocalBindingManager = new BindingManager ( new ContextManager ( ) , new CommandManager ( ) ) ; final IBindingService bindingService = ( IBindingService ) PlatformUI . getWorkbench ( ) . getService ( IBindingService . class ) ; final Scheme [ ] definedSchemes = bindingService . getDefinedSchemes ( ) ; if ( definedSchemes != null ) { try { for ( int i = ; i < definedSchemes . length ; i ++ ) { final Scheme scheme = definedSchemes [ i ] ; final Scheme copy = fgLocalBindingManager . getScheme ( scheme . getId ( ) ) ; copy . define ( scheme . getName ( ) , scheme . getDescription ( ) , scheme . getParentId ( ) ) ; } } catch ( final NotDefinedException e ) { RubyPlugin . log ( e ) ; } } fgLocalBindingManager . setLocale ( bindingService . getLocale ( ) ) ; fgLocalBindingManager . setPlatform ( bindingService . getPlatform ( ) ) ; } private static String getKeyboardShortcut ( ParameterizedCommand command ) { IBindingService bindingService = ( IBindingService ) PlatformUI . getWorkbench ( ) . getAdapter ( IBindingService . class ) ; fgLocalBindingManager . setBindings ( bindingService . getBindings ( ) ) ; try { Scheme activeScheme = bindingService . getActiveScheme ( ) ; if ( activeScheme != null ) fgLocalBindingManager . setActiveScheme ( activeScheme ) ; } catch ( NotDefinedException e ) { RubyPlugin . log ( e ) ; } TriggerSequence [ ] bindings = fgLocalBindingManager . getActiveBindingsDisregardingContextFor ( command ) ; if ( bindings . length > ) return bindings [ ] . format ( ) ; return null ; } private Image getImage ( ImageDescriptor imgDesc ) { if ( imgDesc == null ) return null ; Image img = ( Image ) fImages . get ( imgDesc ) ; if ( img == null ) { img = imgDesc . createImage ( false ) ; fImages . put ( imgDesc , img ) ; } return img ; } @ Override protected void validateSettings ( Key changedKey , String oldValue , String newValue ) { } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public final class MarkOccurrencesPreferencePage extends AbstractConfigurationBlockPreferencePage { protected String getHelpId ( ) { return IRubyHelpContextIds . RUBY_EDITOR_PREFERENCE_PAGE ; } protected void setDescription ( ) { String description = PreferencesMessages . MarkOccurrencesConfigurationBlock_title ; setDescription ( description ) ; } protected void setPreferenceStore ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; } protected Label createDescriptionLabel ( Composite parent ) { return null ; } protected IPreferenceConfigurationBlock createConfigurationBlock ( OverlayPreferenceStore overlayPreferenceStore ) { return new MarkOccurrencesConfigurationBlock ( overlayPreferenceStore ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceStore ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; public class OverlayPreferenceStore implements IPreferenceStore { public static final class TypeDescriptor { private TypeDescriptor ( ) { } } public static final TypeDescriptor BOOLEAN = new TypeDescriptor ( ) ; public static final TypeDescriptor DOUBLE = new TypeDescriptor ( ) ; public static final TypeDescriptor FLOAT = new TypeDescriptor ( ) ; public static final TypeDescriptor INT = new TypeDescriptor ( ) ; public static final TypeDescriptor LONG = new TypeDescriptor ( ) ; public static final TypeDescriptor STRING = new TypeDescriptor ( ) ; public static class OverlayKey { TypeDescriptor fDescriptor ; String fKey ; public OverlayKey ( TypeDescriptor descriptor , String key ) { fDescriptor = descriptor ; fKey = key ; } } private class PropertyListener implements IPropertyChangeListener { public void propertyChange ( PropertyChangeEvent event ) { OverlayKey key = findOverlayKey ( event . getProperty ( ) ) ; if ( key != null ) propagateProperty ( fParent , key , fStore ) ; } } private IPreferenceStore fParent ; private IPreferenceStore fStore ; private OverlayKey [ ] fOverlayKeys ; private PropertyListener fPropertyListener ; private boolean fLoaded ; public OverlayPreferenceStore ( IPreferenceStore parent , OverlayKey [ ] overlayKeys ) { fParent = parent ; fOverlayKeys = overlayKeys ; fStore = new PreferenceStore ( ) ; } private OverlayKey findOverlayKey ( String key ) { for ( int i = ; i < fOverlayKeys . length ; i ++ ) { if ( fOverlayKeys [ i ] . fKey . equals ( key ) ) return fOverlayKeys [ i ] ; } return null ; } private boolean covers ( String key ) { return ( findOverlayKey ( key ) != null ) ; } private void propagateProperty ( IPreferenceStore orgin , OverlayKey key , IPreferenceStore target ) { if ( orgin . isDefault ( key . fKey ) ) { if ( ! target . isDefault ( key . fKey ) ) target . setToDefault ( key . fKey ) ; return ; } TypeDescriptor d = key . fDescriptor ; if ( BOOLEAN == d ) { boolean originValue = orgin . getBoolean ( key . fKey ) ; boolean targetValue = target . getBoolean ( key . fKey ) ; if ( targetValue != originValue ) target . setValue ( key . fKey , originValue ) ; } else if ( DOUBLE == d ) { double originValue = orgin . getDouble ( key . fKey ) ; double targetValue = target . getDouble ( key . fKey ) ; if ( targetValue != originValue ) target . setValue ( key . fKey , originValue ) ; } else if ( FLOAT == d ) { float originValue = orgin . getFloat ( key . fKey ) ; float targetValue = target . getFloat ( key . fKey ) ; if ( targetValue != originValue ) target . setValue ( key . fKey , originValue ) ; } else if ( INT == d ) { int originValue = orgin . getInt ( key . fKey ) ; int targetValue = target . getInt ( key . fKey ) ; if ( targetValue != originValue ) target . setValue ( key . fKey , originValue ) ; } else if ( LONG == d ) { long originValue = orgin . getLong ( key . fKey ) ; long targetValue = target . getLong ( key . fKey ) ; if ( targetValue != originValue ) target . setValue ( key . fKey , originValue ) ; } else if ( STRING == d ) { String originValue = orgin . getString ( key . fKey ) ; String targetValue = target . getString ( key . fKey ) ; if ( targetValue != null && originValue != null && ! targetValue . equals ( originValue ) ) target . setValue ( key . fKey , originValue ) ; } } public void propagate ( ) { for ( int i = ; i < fOverlayKeys . length ; i ++ ) propagateProperty ( fStore , fOverlayKeys [ i ] , fParent ) ; } private void loadProperty ( IPreferenceStore orgin , OverlayKey key , IPreferenceStore target , boolean forceInitialization ) { TypeDescriptor d = key . fDescriptor ; if ( BOOLEAN == d ) { if ( forceInitialization ) target . setValue ( key . fKey , true ) ; target . setValue ( key . fKey , orgin . getBoolean ( key . fKey ) ) ; target . setDefault ( key . fKey , orgin . getDefaultBoolean ( key . fKey ) ) ; } else if ( DOUBLE == d ) { if ( forceInitialization ) target . setValue ( key . fKey , ) ; target . setValue ( key . fKey , orgin . getDouble ( key . fKey ) ) ; target . setDefault ( key . fKey , orgin . getDefaultDouble ( key . fKey ) ) ; } else if ( FLOAT == d ) { if ( forceInitialization ) target . setValue ( key . fKey , ) ; target . setValue ( key . fKey , orgin . getFloat ( key . fKey ) ) ; target . setDefault ( key . fKey , orgin . getDefaultFloat ( key . fKey ) ) ; } else if ( INT == d ) { if ( forceInitialization ) target . setValue ( key . fKey , ) ; target . setValue ( key . fKey , orgin . getInt ( key . fKey ) ) ; target . setDefault ( key . fKey , orgin . getDefaultInt ( key . fKey ) ) ; } else if ( LONG == d ) { if ( forceInitialization ) target . setValue ( key . fKey , ) ; target . setValue ( key . fKey , orgin . getLong ( key . fKey ) ) ; target . setDefault ( key . fKey , orgin . getDefaultLong ( key . fKey ) ) ; } else if ( STRING == d ) { if ( forceInitialization ) target . setValue ( key . fKey , "" ) ; target . setValue ( key . fKey , orgin . getString ( key . fKey ) ) ; target . setDefault ( key . fKey , orgin . getDefaultString ( key . fKey ) ) ; } } public void load ( ) { for ( int i = ; i < fOverlayKeys . length ; i ++ ) loadProperty ( fParent , fOverlayKeys [ i ] , fStore , true ) ; fLoaded = true ; } public void loadDefaults ( ) { for ( int i = ; i < fOverlayKeys . length ; i ++ ) setToDefault ( fOverlayKeys [ i ] . fKey ) ; } public void start ( ) { if ( fPropertyListener == null ) { fPropertyListener = new PropertyListener ( ) ; fParent . addPropertyChangeListener ( fPropertyListener ) ; } } public void stop ( ) { if ( fPropertyListener != null ) { fParent . removePropertyChangeListener ( fPropertyListener ) ; fPropertyListener = null ; } } public void addPropertyChangeListener ( IPropertyChangeListener listener ) { fStore . addPropertyChangeListener ( listener ) ; } public void removePropertyChangeListener ( IPropertyChangeListener listener ) { fStore . removePropertyChangeListener ( listener ) ; } public void firePropertyChangeEvent ( String name , Object oldValue , Object newValue ) { fStore . firePropertyChangeEvent ( name , oldValue , newValue ) ; } public boolean contains ( String name ) { return fStore . contains ( name ) ; } public boolean getBoolean ( String name ) { return fStore . getBoolean ( name ) ; } public boolean getDefaultBoolean ( String name ) { return fStore . getDefaultBoolean ( name ) ; } public double getDefaultDouble ( String name ) { return fStore . getDefaultDouble ( name ) ; } public float getDefaultFloat ( String name ) { return fStore . getDefaultFloat ( name ) ; } public int getDefaultInt ( String name ) { return fStore . getDefaultInt ( name ) ; } public long getDefaultLong ( String name ) { return fStore . getDefaultLong ( name ) ; } public String getDefaultString ( String name ) { return fStore . getDefaultString ( name ) ; } public double getDouble ( String name ) { return fStore . getDouble ( name ) ; } public float getFloat ( String name ) { return fStore . getFloat ( name ) ; } public int getInt ( String name ) { return fStore . getInt ( name ) ; } public long getLong ( String name ) { return fStore . getLong ( name ) ; } public String getString ( String name ) { return fStore . getString ( name ) ; } public boolean isDefault ( String name ) { return fStore . isDefault ( name ) ; } public boolean needsSaving ( ) { return fStore . needsSaving ( ) ; } public void putValue ( String name , String value ) { if ( covers ( name ) ) fStore . putValue ( name , value ) ; } public void setDefault ( String name , double value ) { if ( covers ( name ) ) fStore . setDefault ( name , value ) ; } public void setDefault ( String name , float value ) { if ( covers ( name ) ) fStore . setDefault ( name , value ) ; } public void setDefault ( String name , int value ) { if ( covers ( name ) ) fStore . setDefault ( name , value ) ; } public void setDefault ( String name , long value ) { if ( covers ( name ) ) fStore . setDefault ( name , value ) ; } public void setDefault ( String name , String value ) { if ( covers ( name ) ) fStore . setDefault ( name , value ) ; } public void setDefault ( String name , boolean value ) { if ( covers ( name ) ) fStore . setDefault ( name , value ) ; } public void setToDefault ( String name ) { fStore . setToDefault ( name ) ; } public void setValue ( String name , double value ) { if ( covers ( name ) ) fStore . setValue ( name , value ) ; } public void setValue ( String name , float value ) { if ( covers ( name ) ) fStore . setValue ( name , value ) ; } public void setValue ( String name , int value ) { if ( covers ( name ) ) fStore . setValue ( name , value ) ; } public void setValue ( String name , long value ) { if ( covers ( name ) ) fStore . setValue ( name , value ) ; } public void setValue ( String name , String value ) { if ( covers ( name ) ) fStore . setValue ( name , value ) ; } public void setValue ( String name , boolean value ) { if ( covers ( name ) ) fStore . setValue ( name , value ) ; } public void addKeys ( OverlayKey [ ] keys ) { Assert . isTrue ( ! fLoaded ) ; Assert . isNotNull ( keys ) ; int overlayKeysLength = fOverlayKeys . length ; OverlayKey [ ] result = new OverlayKey [ keys . length + overlayKeysLength ] ; for ( int i = , length = overlayKeysLength ; i < length ; i ++ ) result [ i ] = fOverlayKeys [ i ] ; for ( int i = , length = keys . length ; i < length ; i ++ ) result [ overlayKeysLength + i ] = keys [ i ] ; fOverlayKeys = result ; if ( fLoaded ) load ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . ui . preferences . IWorkingCopyManager ; public class PreferencesAccess { public static PreferencesAccess getOriginalPreferences ( ) { return new PreferencesAccess ( ) ; } public static PreferencesAccess getWorkingCopyPreferences ( IWorkingCopyManager workingCopyManager ) { return new WorkingCopyPreferencesAccess ( workingCopyManager ) ; } private PreferencesAccess ( ) { } public IScopeContext getDefaultScope ( ) { return new DefaultScope ( ) ; } public IScopeContext getInstanceScope ( ) { return new InstanceScope ( ) ; } public IScopeContext getProjectScope ( IProject project ) { return new ProjectScope ( project ) ; } private static class WorkingCopyPreferencesAccess extends PreferencesAccess { private final IWorkingCopyManager fWorkingCopyManager ; private WorkingCopyPreferencesAccess ( IWorkingCopyManager workingCopyManager ) { fWorkingCopyManager = workingCopyManager ; } private final IScopeContext getWorkingCopyScopeContext ( IScopeContext original ) { return new WorkingCopyScopeContext ( fWorkingCopyManager , original ) ; } public IScopeContext getDefaultScope ( ) { return getWorkingCopyScopeContext ( super . getDefaultScope ( ) ) ; } public IScopeContext getInstanceScope ( ) { return getWorkingCopyScopeContext ( super . getInstanceScope ( ) ) ; } public IScopeContext getProjectScope ( IProject project ) { return getWorkingCopyScopeContext ( super . getProjectScope ( project ) ) ; } } private static class WorkingCopyScopeContext implements IScopeContext { private final IWorkingCopyManager fWorkingCopyManager ; private final IScopeContext fOriginal ; public WorkingCopyScopeContext ( IWorkingCopyManager workingCopyManager , IScopeContext original ) { fWorkingCopyManager = workingCopyManager ; fOriginal = original ; } public String getName ( ) { return fOriginal . getName ( ) ; } public IEclipsePreferences getNode ( String qualifier ) { return fWorkingCopyManager . getWorkingCopy ( fOriginal . getNode ( qualifier ) ) ; } public IPath getLocation ( ) { return fOriginal . getLocation ( ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . ListenerList ; import org . eclipse . jface . util . PropertyChangeEvent ; public class MockupPreferenceStore implements IPreferenceStore { private ListenerList fListeners = new ListenerList ( ) ; public void addPropertyChangeListener ( IPropertyChangeListener listener ) { fListeners . add ( listener ) ; } public void removePropertyChangeListener ( IPropertyChangeListener listener ) { fListeners . remove ( listener ) ; } public boolean contains ( String name ) { throw new UnsupportedOperationException ( ) ; } public void firePropertyChangeEvent ( String name , Object oldValue , Object newValue ) { firePropertyChangeEvent ( this , name , oldValue , newValue ) ; } public void firePropertyChangeEvent ( Object source , String name , Object oldValue , Object newValue ) { PropertyChangeEvent event = new PropertyChangeEvent ( source , name , oldValue , newValue ) ; Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) ( ( IPropertyChangeListener ) listeners [ i ] ) . propertyChange ( event ) ; } public boolean getBoolean ( String name ) { throw new UnsupportedOperationException ( ) ; } public boolean getDefaultBoolean ( String name ) { throw new UnsupportedOperationException ( ) ; } public double getDefaultDouble ( String name ) { throw new UnsupportedOperationException ( ) ; } public float getDefaultFloat ( String name ) { throw new UnsupportedOperationException ( ) ; } public int getDefaultInt ( String name ) { throw new UnsupportedOperationException ( ) ; } public long getDefaultLong ( String name ) { throw new UnsupportedOperationException ( ) ; } public String getDefaultString ( String name ) { throw new UnsupportedOperationException ( ) ; } public double getDouble ( String name ) { throw new UnsupportedOperationException ( ) ; } public float getFloat ( String name ) { throw new UnsupportedOperationException ( ) ; } public int getInt ( String name ) { throw new UnsupportedOperationException ( ) ; } public long getLong ( String name ) { throw new UnsupportedOperationException ( ) ; } public String getString ( String name ) { throw new UnsupportedOperationException ( ) ; } public boolean isDefault ( String name ) { throw new UnsupportedOperationException ( ) ; } public boolean needsSaving ( ) { throw new UnsupportedOperationException ( ) ; } public void putValue ( String name , String value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , double value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , float value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , int value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , long value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , String defaultObject ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , boolean value ) { throw new UnsupportedOperationException ( ) ; } public void setToDefault ( String name ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , double value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , float value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , int value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , long value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , String value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , boolean value ) { throw new UnsupportedOperationException ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . io . BufferedReader ; import java . io . File ; import java . io . IOException ; import java . io . InputStreamReader ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . ColorSelector ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontMetrics ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Link ; import org . eclipse . swt . widgets . ScrollBar ; import org . eclipse . swt . widgets . Scrollable ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . texteditor . ChainedPreferenceStore ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubySourceViewer ; import org . rubypeople . rdt . internal . ui . text . IRubyColorConstants ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . PreferencesAdapter ; import org . rubypeople . rdt . internal . ui . text . RubyColorManager ; import org . rubypeople . rdt . internal . ui . text . SimpleRubySourceViewerConfiguration ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . IColorManager ; class RubyEditorColoringConfigurationBlock extends AbstractConfigurationBlock { private static final String DIALOGSTORE_LASTLOADPATH = RubyUI . ID_PLUGIN + "" ; private static final String DIALOGSTORE_LASTSAVEPATH = RubyUI . ID_PLUGIN + "" ; public static class HighlightingColorListItem { private String fDisplayName ; private String fColorKey ; private String fBoldKey ; private String fBackgroundKey ; private String fItalicKey ; private String fStrikethroughKey ; private String fUnderlineKey ; private String fBackgroundEnabledKey ; public HighlightingColorListItem ( String displayName , String colorKey , String bgColorKey , String bgEnabledKey , String boldKey , String italicKey , String strikethroughKey , String underlineKey ) { fDisplayName = displayName ; fColorKey = colorKey ; fBackgroundKey = bgColorKey ; fBackgroundEnabledKey = bgEnabledKey ; fBoldKey = boldKey ; fItalicKey = italicKey ; fStrikethroughKey = strikethroughKey ; fUnderlineKey = underlineKey ; } public String getBoldKey ( ) { return fBoldKey ; } public String getBackgroundKey ( ) { return fBackgroundKey ; } public String getItalicKey ( ) { return fItalicKey ; } public String getStrikethroughKey ( ) { return fStrikethroughKey ; } public String getUnderlineKey ( ) { return fUnderlineKey ; } public String getColorKey ( ) { return fColorKey ; } public String getDisplayName ( ) { return fDisplayName ; } public String getBackgroundEnabledKey ( ) { return fBackgroundEnabledKey ; } } private static class SemanticHighlightingColorListItem extends HighlightingColorListItem { private final String fEnableKey ; public SemanticHighlightingColorListItem ( String displayName , String colorKey , String bgColorKey , String bgEnabledKey , String boldKey , String italicKey , String strikethroughKey , String underlineKey , String enableKey ) { super ( displayName , colorKey , bgColorKey , bgEnabledKey , boldKey , italicKey , strikethroughKey , underlineKey ) ; fEnableKey = enableKey ; } public String getEnableKey ( ) { return fEnableKey ; } } private class ColorListLabelProvider extends LabelProvider { public String getText ( Object element ) { if ( element instanceof String ) return ( String ) element ; return ( ( HighlightingColorListItem ) element ) . getDisplayName ( ) ; } } private class ColorListContentProvider implements ITreeContentProvider { public Object [ ] getElements ( Object inputElement ) { return new String [ ] { fRubyCategory } ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof String ) { String entry = ( String ) parentElement ; if ( fRubyCategory . equals ( entry ) ) return fListModel . toArray ( ) ; } return new Object [ ] ; } public Object getParent ( Object element ) { if ( element instanceof String ) return null ; return fRubyCategory ; } public boolean hasChildren ( Object element ) { return element instanceof String ; } } private static final String BOLD = PreferenceConstants . EDITOR_BOLD_SUFFIX ; private static final String BACKGROUND = PreferenceConstants . EDITOR_BG_SUFFIX ; private static final String BACKGROUND_ENABLED = PreferenceConstants . EDITOR_BG_ENABLED_SUFFIX ; private static final String ITALIC = PreferenceConstants . EDITOR_ITALIC_SUFFIX ; private static final String STRIKETHROUGH = PreferenceConstants . EDITOR_STRIKETHROUGH_SUFFIX ; private static final String UNDERLINE = PreferenceConstants . EDITOR_UNDERLINE_SUFFIX ; private static final String COMPILER_TASK_TAGS = RubyCore . COMPILER_TASK_TAGS ; private final String [ ] [ ] fSyntaxColorListModel = new String [ ] [ ] { { PreferencesMessages . RubyEditorPreferencePage_multiLineComment , IRubyColorConstants . RUBY_MULTI_LINE_COMMENT } , { PreferencesMessages . RubyEditorPreferencePage_singleLineComment , IRubyColorConstants . RUBY_SINGLE_LINE_COMMENT } , { PreferencesMessages . RubyEditorPreferencePage_rubyCommentTaskTags , IRubyColorConstants . TASK_TAG } , { PreferencesMessages . RubyEditorPreferencePage_keywords , IRubyColorConstants . RUBY_KEYWORD } , { PreferencesMessages . RubyEditorPreferencePage_strings , IRubyColorConstants . RUBY_STRING } , { PreferencesMessages . RubyEditorPreferencePage_characters , IRubyColorConstants . RUBY_CHARACTER } , { PreferencesMessages . RubyEditorPreferencePage_commands , IRubyColorConstants . RUBY_COMMAND } , { PreferencesMessages . RubyEditorPreferencePage_fixnums , IRubyColorConstants . RUBY_FIXNUM } , { PreferencesMessages . RubyEditorPreferencePage_globals , IRubyColorConstants . RUBY_GLOBAL } , { PreferencesMessages . RubyEditorPreferencePage_regular_expressions , IRubyColorConstants . RUBY_REGEXP } , { PreferencesMessages . RubyEditorPreferencePage_symbols , IRubyColorConstants . RUBY_SYMBOL } , { PreferencesMessages . RubyEditorPreferencePage_instance_variables , IRubyColorConstants . RUBY_INSTANCE_VARIABLE } , { PreferencesMessages . RubyEditorPreferencePage_class_variables , IRubyColorConstants . RUBY_CLASS_VARIABLE } , { PreferencesMessages . RubyEditorPreferencePage_others , IRubyColorConstants . RUBY_DEFAULT } } ; private final String fRubyCategory = PreferencesMessages . RubyEditorPreferencePage_coloring_category_ruby ; private ColorSelector fSyntaxForegroundColorEditor ; private ColorSelector fSyntaxBackgroundColorEditor ; private Label fColorEditorLabel ; private Button fBoldCheckBox ; private Button fEnableCheckbox ; private Button fItalicCheckBox ; private Button fStrikethroughCheckBox ; private Button fUnderlineCheckBox ; private final java . util . List fListModel = new ArrayList ( ) ; private StructuredViewer fListViewer ; private RubySourceViewer fPreviewViewer ; private IColorManager fColorManager ; private FontMetrics fFontMetrics ; private Button fLoadButton ; private Button fSaveButton ; private Composite fComposite ; private Button fEnableBackgroundCheckbox ; public RubyEditorColoringConfigurationBlock ( OverlayPreferenceStore store ) { super ( store ) ; fColorManager = new RubyColorManager ( false ) ; for ( int i = , n = fSyntaxColorListModel . length ; i < n ; i ++ ) fListModel . add ( new HighlightingColorListItem ( fSyntaxColorListModel [ i ] [ ] , fSyntaxColorListModel [ i ] [ ] , fSyntaxColorListModel [ i ] [ ] + BACKGROUND , fSyntaxColorListModel [ i ] [ ] + BACKGROUND_ENABLED , fSyntaxColorListModel [ i ] [ ] + BOLD , fSyntaxColorListModel [ i ] [ ] + ITALIC , fSyntaxColorListModel [ i ] [ ] + STRIKETHROUGH , fSyntaxColorListModel [ i ] [ ] + UNDERLINE ) ) ; store . addKeys ( createOverlayStoreKeys ( ) ) ; } private OverlayPreferenceStore . OverlayKey [ ] createOverlayStoreKeys ( ) { ArrayList overlayKeys = new ArrayList ( ) ; for ( int i = , n = fListModel . size ( ) ; i < n ; i ++ ) { HighlightingColorListItem item = ( HighlightingColorListItem ) fListModel . get ( i ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , item . getColorKey ( ) ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . STRING , item . getBackgroundKey ( ) ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , item . getBackgroundEnabledKey ( ) ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , item . getBoldKey ( ) ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , item . getItalicKey ( ) ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , item . getStrikethroughKey ( ) ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , item . getUnderlineKey ( ) ) ) ; if ( item instanceof SemanticHighlightingColorListItem ) overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , ( ( SemanticHighlightingColorListItem ) item ) . getEnableKey ( ) ) ) ; } OverlayPreferenceStore . OverlayKey [ ] keys = new OverlayPreferenceStore . OverlayKey [ overlayKeys . size ( ) ] ; overlayKeys . toArray ( keys ) ; return keys ; } public Control createControl ( Composite parent ) { initializeDialogUnits ( parent ) ; return createSyntaxPage ( parent ) ; } private int convertWidthInCharsToPixels ( int chars ) { if ( fFontMetrics == null ) return ; return Dialog . convertWidthInCharsToPixels ( fFontMetrics , chars ) ; } private int convertHeightInCharsToPixels ( int chars ) { if ( fFontMetrics == null ) return ; return Dialog . convertHeightInCharsToPixels ( fFontMetrics , chars ) ; } public void initialize ( ) { super . initialize ( ) ; fListViewer . setInput ( fListModel ) ; fListViewer . setSelection ( new StructuredSelection ( fRubyCategory ) ) ; } public void performDefaults ( ) { super . performDefaults ( ) ; handleSyntaxColorListSelection ( ) ; fPreviewViewer . invalidateTextPresentation ( ) ; } public void dispose ( ) { fColorManager . dispose ( ) ; super . dispose ( ) ; } private void handleSyntaxColorListSelection ( ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; if ( item == null ) { fEnableCheckbox . setEnabled ( false ) ; fSyntaxForegroundColorEditor . getButton ( ) . setEnabled ( false ) ; fSyntaxBackgroundColorEditor . getButton ( ) . setEnabled ( false ) ; fColorEditorLabel . setEnabled ( false ) ; fBoldCheckBox . setEnabled ( false ) ; fItalicCheckBox . setEnabled ( false ) ; fStrikethroughCheckBox . setEnabled ( false ) ; fUnderlineCheckBox . setEnabled ( false ) ; return ; } RGB rgb = PreferenceConverter . getColor ( getPreferenceStore ( ) , item . getColorKey ( ) ) ; fSyntaxForegroundColorEditor . setColorValue ( rgb ) ; rgb = PreferenceConverter . getColor ( getPreferenceStore ( ) , item . getBackgroundKey ( ) ) ; fSyntaxBackgroundColorEditor . setColorValue ( rgb ) ; fBoldCheckBox . setSelection ( getPreferenceStore ( ) . getBoolean ( item . getBoldKey ( ) ) ) ; fItalicCheckBox . setSelection ( getPreferenceStore ( ) . getBoolean ( item . getItalicKey ( ) ) ) ; fStrikethroughCheckBox . setSelection ( getPreferenceStore ( ) . getBoolean ( item . getStrikethroughKey ( ) ) ) ; fUnderlineCheckBox . setSelection ( getPreferenceStore ( ) . getBoolean ( item . getUnderlineKey ( ) ) ) ; if ( item instanceof SemanticHighlightingColorListItem ) { fEnableCheckbox . setEnabled ( true ) ; boolean enable = getPreferenceStore ( ) . getBoolean ( ( ( SemanticHighlightingColorListItem ) item ) . getEnableKey ( ) ) ; fEnableCheckbox . setSelection ( enable ) ; fSyntaxForegroundColorEditor . getButton ( ) . setEnabled ( enable ) ; fColorEditorLabel . setEnabled ( enable ) ; fBoldCheckBox . setEnabled ( enable ) ; fItalicCheckBox . setEnabled ( enable ) ; fStrikethroughCheckBox . setEnabled ( enable ) ; fUnderlineCheckBox . setEnabled ( enable ) ; fEnableBackgroundCheckbox . setEnabled ( enable ) ; boolean bgEnabled = getPreferenceStore ( ) . getBoolean ( ( ( SemanticHighlightingColorListItem ) item ) . getBackgroundEnabledKey ( ) ) ; fEnableBackgroundCheckbox . setSelection ( bgEnabled ) ; fSyntaxBackgroundColorEditor . getButton ( ) . setEnabled ( bgEnabled ) ; } else { fSyntaxForegroundColorEditor . getButton ( ) . setEnabled ( true ) ; fColorEditorLabel . setEnabled ( true ) ; fBoldCheckBox . setEnabled ( true ) ; fItalicCheckBox . setEnabled ( true ) ; fStrikethroughCheckBox . setEnabled ( true ) ; fUnderlineCheckBox . setEnabled ( true ) ; fEnableCheckbox . setEnabled ( false ) ; fEnableCheckbox . setSelection ( true ) ; fEnableBackgroundCheckbox . setEnabled ( true ) ; boolean bgEnabled = getPreferenceStore ( ) . getBoolean ( item . getBackgroundEnabledKey ( ) ) ; fEnableBackgroundCheckbox . setSelection ( bgEnabled ) ; fSyntaxBackgroundColorEditor . getButton ( ) . setEnabled ( bgEnabled ) ; } } private Control createSyntaxPage ( final Composite parent ) { Composite colorComposite = new Composite ( parent , SWT . NONE ) ; fComposite = colorComposite ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; colorComposite . setLayout ( layout ) ; Link link = new Link ( colorComposite , SWT . NONE ) ; link . setText ( PreferencesMessages . RubyEditorColoringConfigurationBlock_link ) ; link . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { PreferencesUtil . createPreferenceDialogOn ( parent . getShell ( ) , e . text , null , null ) ; } } ) ; GridData gridData = new GridData ( SWT . FILL , SWT . BEGINNING , true , false ) ; gridData . widthHint = ; gridData . horizontalSpan = ; link . setLayoutData ( gridData ) ; addFiller ( colorComposite , ) ; final Composite group = createComposite ( colorComposite , ) ; final GridData groupData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; groupData . horizontalSpan = ; group . setLayoutData ( groupData ) ; fLoadButton = createButton ( group , "" , GridData . HORIZONTAL_ALIGN_END ) ; fSaveButton = createButton ( group , "" , GridData . HORIZONTAL_ALIGN_END ) ; new ButtonController ( ) ; Label label ; label = new Label ( colorComposite , SWT . LEFT ) ; label . setText ( PreferencesMessages . RubyEditorPreferencePage_coloring_element ) ; label . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; Composite editorComposite = new Composite ( colorComposite , SWT . NONE ) ; layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginHeight = ; layout . marginWidth = ; editorComposite . setLayout ( layout ) ; GridData gd = new GridData ( SWT . FILL , SWT . BEGINNING , true , false ) ; editorComposite . setLayoutData ( gd ) ; fListViewer = new TreeViewer ( editorComposite , SWT . SINGLE | SWT . BORDER ) ; fListViewer . setLabelProvider ( new ColorListLabelProvider ( ) ) ; fListViewer . setContentProvider ( new ColorListContentProvider ( ) ) ; fListViewer . setSorter ( new ViewerSorter ( ) { public int category ( Object element ) { if ( fRubyCategory . equals ( element ) ) return ; return ; } } ) ; gd = new GridData ( SWT . BEGINNING , SWT . BEGINNING , false , true ) ; gd . heightHint = convertHeightInCharsToPixels ( ) ; int maxWidth = ; for ( Iterator it = fListModel . iterator ( ) ; it . hasNext ( ) ; ) { HighlightingColorListItem item = ( HighlightingColorListItem ) it . next ( ) ; maxWidth = Math . max ( maxWidth , convertWidthInCharsToPixels ( item . getDisplayName ( ) . length ( ) ) ) ; } ScrollBar vBar = ( ( Scrollable ) fListViewer . getControl ( ) ) . getVerticalBar ( ) ; if ( vBar != null ) maxWidth += vBar . getSize ( ) . x * ; gd . widthHint = maxWidth ; fListViewer . getControl ( ) . setLayoutData ( gd ) ; Composite stylesComposite = new Composite ( editorComposite , SWT . NONE ) ; layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; stylesComposite . setLayout ( layout ) ; stylesComposite . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; fEnableCheckbox = new Button ( stylesComposite , SWT . CHECK ) ; fEnableCheckbox . setText ( PreferencesMessages . RubyEditorPreferencePage_enable ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalAlignment = GridData . BEGINNING ; gd . horizontalSpan = ; fEnableCheckbox . setLayoutData ( gd ) ; fColorEditorLabel = new Label ( stylesComposite , SWT . LEFT ) ; fColorEditorLabel . setText ( PreferencesMessages . RubyEditorPreferencePage_color ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = ; fColorEditorLabel . setLayoutData ( gd ) ; fSyntaxForegroundColorEditor = new ColorSelector ( stylesComposite ) ; Button foregroundColorButton = fSyntaxForegroundColorEditor . getButton ( ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; foregroundColorButton . setLayoutData ( gd ) ; fEnableBackgroundCheckbox = new Button ( stylesComposite , SWT . CHECK | SWT . LEFT ) ; fEnableBackgroundCheckbox . setText ( PreferencesMessages . RubyEditorPreferencePage_background_color ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = ; fEnableBackgroundCheckbox . setLayoutData ( gd ) ; fEnableBackgroundCheckbox . setEnabled ( false ) ; fSyntaxBackgroundColorEditor = new ColorSelector ( stylesComposite ) ; Button backgroundColorButton = fSyntaxBackgroundColorEditor . getButton ( ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; backgroundColorButton . setLayoutData ( gd ) ; fBoldCheckBox = new Button ( stylesComposite , SWT . CHECK ) ; fBoldCheckBox . setText ( PreferencesMessages . RubyEditorPreferencePage_bold ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = ; gd . horizontalSpan = ; fBoldCheckBox . setLayoutData ( gd ) ; fItalicCheckBox = new Button ( stylesComposite , SWT . CHECK ) ; fItalicCheckBox . setText ( PreferencesMessages . RubyEditorPreferencePage_italic ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = ; gd . horizontalSpan = ; fItalicCheckBox . setLayoutData ( gd ) ; fStrikethroughCheckBox = new Button ( stylesComposite , SWT . CHECK ) ; fStrikethroughCheckBox . setText ( PreferencesMessages . RubyEditorPreferencePage_strikethrough ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = ; gd . horizontalSpan = ; fStrikethroughCheckBox . setLayoutData ( gd ) ; fUnderlineCheckBox = new Button ( stylesComposite , SWT . CHECK ) ; fUnderlineCheckBox . setText ( PreferencesMessages . RubyEditorPreferencePage_underline ) ; gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = ; gd . horizontalSpan = ; fUnderlineCheckBox . setLayoutData ( gd ) ; label = new Label ( colorComposite , SWT . LEFT ) ; label . setText ( PreferencesMessages . RubyEditorPreferencePage_preview ) ; label . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; Control previewer = createPreviewer ( colorComposite ) ; gd = new GridData ( GridData . FILL_BOTH ) ; gd . widthHint = convertWidthInCharsToPixels ( ) ; gd . heightHint = convertHeightInCharsToPixels ( ) ; previewer . setLayoutData ( gd ) ; fListViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { handleSyntaxColorListSelection ( ) ; } } ) ; foregroundColorButton . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; PreferenceConverter . setValue ( getPreferenceStore ( ) , item . getColorKey ( ) , fSyntaxForegroundColorEditor . getColorValue ( ) ) ; } } ) ; backgroundColorButton . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; PreferenceConverter . setValue ( getPreferenceStore ( ) , item . getBackgroundKey ( ) , fSyntaxBackgroundColorEditor . getColorValue ( ) ) ; } } ) ; fBoldCheckBox . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; getPreferenceStore ( ) . setValue ( item . getBoldKey ( ) , fBoldCheckBox . getSelection ( ) ) ; } } ) ; fItalicCheckBox . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; getPreferenceStore ( ) . setValue ( item . getItalicKey ( ) , fItalicCheckBox . getSelection ( ) ) ; } } ) ; fStrikethroughCheckBox . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; getPreferenceStore ( ) . setValue ( item . getStrikethroughKey ( ) , fStrikethroughCheckBox . getSelection ( ) ) ; } } ) ; fUnderlineCheckBox . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; getPreferenceStore ( ) . setValue ( item . getUnderlineKey ( ) , fUnderlineCheckBox . getSelection ( ) ) ; } } ) ; fEnableCheckbox . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; if ( item instanceof SemanticHighlightingColorListItem ) { boolean enable = fEnableCheckbox . getSelection ( ) ; getPreferenceStore ( ) . setValue ( ( ( SemanticHighlightingColorListItem ) item ) . getEnableKey ( ) , enable ) ; fEnableCheckbox . setSelection ( enable ) ; fEnableBackgroundCheckbox . setEnabled ( enable ) ; fSyntaxForegroundColorEditor . getButton ( ) . setEnabled ( enable ) ; fSyntaxBackgroundColorEditor . getButton ( ) . setEnabled ( enable ) ; fColorEditorLabel . setEnabled ( enable ) ; fBoldCheckBox . setEnabled ( enable ) ; fItalicCheckBox . setEnabled ( enable ) ; fStrikethroughCheckBox . setEnabled ( enable ) ; fUnderlineCheckBox . setEnabled ( enable ) ; } } } ) ; fEnableBackgroundCheckbox . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { HighlightingColorListItem item = getHighlightingColorListItem ( ) ; boolean enable = fEnableBackgroundCheckbox . getSelection ( ) ; getPreferenceStore ( ) . setValue ( item . getBackgroundEnabledKey ( ) , enable ) ; fSyntaxBackgroundColorEditor . getButton ( ) . setEnabled ( enable ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; colorComposite . layout ( false ) ; return colorComposite ; } private Composite createComposite ( Composite parent , int numColumns ) { final Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; final GridLayout layout = new GridLayout ( numColumns , false ) ; layout . marginHeight = ; layout . marginWidth = ; composite . setLayout ( layout ) ; return composite ; } private static Button createButton ( Composite composite , String text , final int style ) { final Button button = new Button ( composite , SWT . PUSH ) ; button . setFont ( composite . getFont ( ) ) ; button . setText ( text ) ; final GridData gd = new GridData ( style ) ; gd . widthHint = SWTUtil . getButtonWidthHint ( button ) ; button . setLayoutData ( gd ) ; return button ; } private void addFiller ( Composite composite , int horizontalSpan ) { PixelConverter pixelConverter = new PixelConverter ( composite ) ; Label filler = new Label ( composite , SWT . LEFT ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = horizontalSpan ; gd . heightHint = pixelConverter . convertHeightInCharsToPixels ( ) / ; filler . setLayoutData ( gd ) ; } private Control createPreviewer ( Composite parent ) { IPreferenceStore generalTextStore = EditorsUI . getPreferenceStore ( ) ; IPreferenceStore store = new ChainedPreferenceStore ( new IPreferenceStore [ ] { getPreferenceStore ( ) , new PreferencesAdapter ( createTemporaryCorePreferenceStore ( ) ) , generalTextStore } ) ; fPreviewViewer = new RubySourceViewer ( parent , null , null , false , SWT . V_SCROLL | SWT . H_SCROLL | SWT . BORDER , store ) ; SimpleRubySourceViewerConfiguration configuration = new SimpleRubySourceViewerConfiguration ( fColorManager , store , null , IRubyPartitions . RUBY_PARTITIONING , false ) ; fPreviewViewer . configure ( configuration ) ; Font font = JFaceResources . getFont ( PreferenceConstants . EDITOR_TEXT_FONT ) ; fPreviewViewer . getTextWidget ( ) . setFont ( font ) ; new RubySourcePreviewerUpdater ( fPreviewViewer , configuration , store ) ; fPreviewViewer . setEditable ( false ) ; String content = loadPreviewContentFromFile ( "" ) ; IDocument document = new Document ( content ) ; RubyPlugin . getDefault ( ) . getRubyTextTools ( ) . setupRubyDocumentPartitioner ( document , IRubyPartitions . RUBY_PARTITIONING ) ; fPreviewViewer . setDocument ( document ) ; return fPreviewViewer . getControl ( ) ; } private Preferences createTemporaryCorePreferenceStore ( ) { Preferences result = new Preferences ( ) ; result . setValue ( COMPILER_TASK_TAGS , "" ) ; return result ; } private String loadPreviewContentFromFile ( String filename ) { String line ; String separator = System . getProperty ( "" ) ; StringBuffer buffer = new StringBuffer ( ) ; BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( getClass ( ) . getResourceAsStream ( filename ) ) ) ; while ( ( line = reader . readLine ( ) ) != null ) { buffer . append ( line ) ; buffer . append ( separator ) ; } } catch ( IOException io ) { RubyPlugin . log ( io ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { } } } return buffer . toString ( ) ; } private HighlightingColorListItem getHighlightingColorListItem ( ) { IStructuredSelection selection = ( IStructuredSelection ) fListViewer . getSelection ( ) ; Object element = selection . getFirstElement ( ) ; if ( element instanceof String ) return null ; return ( HighlightingColorListItem ) element ; } private void initializeDialogUnits ( Control testControl ) { GC gc = new GC ( testControl ) ; gc . setFont ( JFaceResources . getDialogFont ( ) ) ; fFontMetrics = gc . getFontMetrics ( ) ; gc . dispose ( ) ; } private class ButtonController implements SelectionListener { public ButtonController ( ) { fLoadButton . addSelectionListener ( this ) ; fSaveButton . addSelectionListener ( this ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { final Button button = ( Button ) e . widget ; if ( button == fSaveButton ) saveButtonPressed ( ) ; else if ( button == fLoadButton ) loadButtonPressed ( ) ; } private void loadButtonPressed ( ) { final FileDialog dialog = new FileDialog ( fComposite . getShell ( ) , SWT . OPEN ) ; dialog . setText ( "" ) ; dialog . setFilterExtensions ( new String [ ] { "" } ) ; final String lastPath = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( DIALOGSTORE_LASTLOADPATH ) ; if ( lastPath != null ) { dialog . setFilterPath ( lastPath ) ; } final String path = dialog . open ( ) ; if ( path == null ) return ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( DIALOGSTORE_LASTLOADPATH , dialog . getFilterPath ( ) ) ; final File file = new File ( path ) ; Map < String , String > profiles = null ; try { profiles = SyntaxColoringStore . readFromFile ( file ) ; } catch ( CoreException e ) { final String title = "" ; final String message = "" ; ExceptionHandler . handle ( e , fComposite . getShell ( ) , title , message ) ; } if ( profiles == null || profiles . isEmpty ( ) ) return ; for ( String key : profiles . keySet ( ) ) { getPreferenceStore ( ) . setValue ( key , profiles . get ( key ) ) ; } performDefaults ( ) ; } private void saveButtonPressed ( ) { final FileDialog dialog = new FileDialog ( fComposite . getShell ( ) , SWT . SAVE ) ; dialog . setText ( "" ) ; dialog . setFilterExtensions ( new String [ ] { "" } ) ; final String lastPath = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( DIALOGSTORE_LASTSAVEPATH ) ; if ( lastPath != null ) { dialog . setFilterPath ( lastPath ) ; } final String path = dialog . open ( ) ; if ( path == null ) return ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( DIALOGSTORE_LASTSAVEPATH , dialog . getFilterPath ( ) ) ; final File file = new File ( path ) ; if ( file . exists ( ) && ! MessageDialog . openQuestion ( fComposite . getShell ( ) , "" , Messages . format ( "" , path ) ) ) { return ; } try { SyntaxColoringStore . write ( fListModel , file ) ; } catch ( CoreException e ) { final String title = "" ; final String message = "" ; ExceptionHandler . handle ( e , fComposite . getShell ( ) , title , message ) ; } } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . osgi . util . NLS ; public final class PreferencesMessages extends NLS { private static final String BUNDLE_NAME = "" ; private PreferencesMessages ( ) { } public static String RiPreferencePage_description_label ; public static String DebuggerPreferencePage_description_label ; public static String CodeFormatterPreferencePage_title ; public static String CodeFormatterPreferencePage_description ; public static String MembersOrderPreferencePage_category_button_up ; public static String MembersOrderPreferencePage_category_button_down ; public static String MembersOrderPreferencePage_visibility_button_up ; public static String MembersOrderPreferencePage_visibility_button_down ; public static String MembersOrderPreferencePage_label_description ; public static String MembersOrderPreferencePage_fields_label ; public static String MembersOrderPreferencePage_constructors_label ; public static String MembersOrderPreferencePage_methods_label ; public static String MembersOrderPreferencePage_staticfields_label ; public static String MembersOrderPreferencePage_staticmethods_label ; public static String MembersOrderPreferencePage_types_label ; public static String MembersOrderPreferencePage_public_label ; public static String MembersOrderPreferencePage_private_label ; public static String MembersOrderPreferencePage_protected_label ; public static String MembersOrderPreferencePage_usevisibilitysort_label ; public static String TodoTaskPreferencePage_description ; public static String TodoTaskPreferencePage_title ; public static String TodoTaskInputDialog_new_title ; public static String TodoTaskInputDialog_edit_title ; public static String TodoTaskInputDialog_priority_high ; public static String TodoTaskInputDialog_name_label ; public static String TodoTaskInputDialog_priority_normal ; public static String TodoTaskInputDialog_priority_low ; public static String TodoTaskInputDialog_priority_label ; public static String TodoTaskInputDialog_error_noSpace ; public static String TodoTaskInputDialog_error_entryExists ; public static String TodoTaskInputDialog_error_comma ; public static String TodoTaskInputDialog_error_enterName ; public static String RubyEditorPreferencePage_link_tooltip ; public static String RubyEditorPreferencePage_link ; public static String RiPreferencePage_ripath_label ; public static String RiPreferencePage_rdocpath_label ; public static String DebuggerPreferencePage_useRubyDebug_label ; public static String DebuggerPreferencePage_verboseDebugger_label ; public static String DebuggerPreferencePage_useRubyDebug_comment ; public static String TodoTaskConfigurationBlock_tasks_default ; public static String TodoTaskConfigurationBlock_markers_tasks_high_priority ; public static String TodoTaskConfigurationBlock_markers_tasks_normal_priority ; public static String TodoTaskConfigurationBlock_markers_tasks_low_priority ; public static String TodoTaskConfigurationBlock_markers_tasks_name_column ; public static String TodoTaskConfigurationBlock_markers_tasks_priority_column ; public static String TodoTaskConfigurationBlock_casesensitive_label ; public static String TodoTaskConfigurationBlock_markers_tasks_add_button ; public static String TodoTaskConfigurationBlock_markers_tasks_edit_button ; public static String TodoTaskConfigurationBlock_markers_tasks_remove_button ; public static String TodoTaskConfigurationBlock_markers_tasks_setdefault_button ; public static String TodoTaskConfigurationBlock_needsbuild_title ; public static String TodoTaskConfigurationBlock_needsfullbuild_message ; public static String TodoTaskConfigurationBlock_needsprojectbuild_message ; public static String AppearancePreferencePage_note ; public static String AppearancePreferencePage_preferenceOnlyEffectiveForNewPerspectives ; public static String AppearancePreferencePage_methodtypeparams_label ; public static String AppearancePreferencePage_stackViewsVerticallyInTheRubyBrowsingPerspective ; public static String AppearancePreferencePage_description ; public static String RubyEditorColoringConfigurationBlock_link ; public static String RubyEditorPreferencePage_coloring_element ; public static String RubyEditorPreferencePage_enable ; public static String RubyEditorPreferencePage_color ; public static String RubyEditorPreferencePage_bold ; public static String RubyEditorPreferencePage_italic ; public static String RubyEditorPreferencePage_strikethrough ; public static String RubyEditorPreferencePage_underline ; public static String RubyEditorPreferencePage_preview ; public static String RubyEditorPreferencePage_multiLineComment ; public static String RubyEditorPreferencePage_coloring_category_ruby ; public static String RubyEditorPreferencePage_singleLineComment ; public static String RubyEditorPreferencePage_rubyCommentTaskTags ; public static String RubyEditorPreferencePage_keywords ; public static String RubyEditorPreferencePage_strings ; public static String RubyEditorPreferencePage_characters ; public static String RubyEditorPreferencePage_commands ; public static String RubyEditorPreferencePage_fixnums ; public static String RubyEditorPreferencePage_globals ; public static String RubyEditorPreferencePage_regular_expressions ; public static String RubyEditorPreferencePage_symbols ; public static String RubyEditorPreferencePage_instance_variables ; public static String RubyEditorPreferencePage_class_variables ; public static String RubyEditorPreferencePage_others ; public static String RubyEditorPreferencePage_colors ; public static String RubyEditorPreferencePage_empty_input ; public static String RubyEditorPreferencePage_invalid_input ; public static String RubyEditorPreferencePage_folding_title ; public static String RubyEditorPreferencePage_matchingBracketsHighlightColor2 ; public static String RubyEditorPreferencePage_backgroundForCompletionProposals ; public static String RubyEditorPreferencePage_foregroundForCompletionProposals ; public static String RubyEditorPreferencePage_backgroundForMethodParameters ; public static String RubyEditorPreferencePage_foregroundForMethodParameters ; public static String RubyEditorPreferencePage_backgroundForCompletionReplacement ; public static String RubyEditorPreferencePage_foregroundForCompletionReplacement ; public static String RubyEditorPreferencePage_analyseAnnotationsWhileTyping ; public static String SmartTypingConfigurationBlock_annotationReporting_link ; public static String RubyEditorPreferencePage_highlightMatchingBrackets ; public static String RubyEditorPreferencePage_appearanceOptions ; public static String RubyEditorPreferencePage_systemDefault ; public static String RubyEditorPreferencePage_general ; public static String RubyEditorPreferencePage_typing_tabTitle ; public static String SmartTypingConfigurationBlock_autoclose_title ; public static String RubyEditorPreferencePage_closeStrings ; public static String RubyEditorPreferencePage_closeBrackets ; public static String RubyEditorPreferencePage_closeBraces ; public static String RubyEditorPreferencePage_endStatements ; public static String RubyEditorPreferencePage_smartHomeEnd ; public static String ProblemSeveritiesPreferencePage_title ; public static String ProblemSeveritiesConfigurationBlock_needsbuild_title ; public static String ProblemSeveritiesConfigurationBlock_needsfullbuild_message ; public static String ProblemSeveritiesConfigurationBlock_needsprojectbuild_message ; public static String ProblemSeveritiesConfigurationBlock_error ; public static String ProblemSeveritiesConfigurationBlock_warning ; public static String ProblemSeveritiesConfigurationBlock_ignore ; public static String ProblemSeveritiesConfigurationBlock_common_description ; public static String ProblemSeveritiesConfigurationBlock_pb_empty_statement_label ; public static String ProblemSeveritiesConfigurationBlock_pb_unreachable_code_label ; public static String RubyEditorPreferencePage_background_color ; public static String MarkOccurrencesConfigurationBlock_markOccurrences ; public static String MarkOccurrencesConfigurationBlock_markTypeOccurrences ; public static String MarkOccurrencesConfigurationBlock_markMethodOccurrences ; public static String MarkOccurrencesConfigurationBlock_markConstantOccurrences ; public static String MarkOccurrencesConfigurationBlock_markFieldOccurrences ; public static String MarkOccurrencesConfigurationBlock_markLocalVariableOccurrences ; public static String MarkOccurrencesConfigurationBlock_markMethodExitPoints ; public static String MarkOccurrencesConfigurationBlock_stickyOccurrences ; public static String MarkOccurrencesConfigurationBlock_title ; public static String PropertyAndPreferencePage_useprojectsettings_label ; public static String PropertyAndPreferencePage_useworkspacesettings_change ; public static String PropertyAndPreferencePage_showprojectspecificsettings_label ; public static String ProjectSelectionDialog_title ; public static String ProjectSelectionDialog_desciption ; public static String ProjectSelectionDialog_filter ; public static String FoldingConfigurationBlock_enable ; public static String FoldingConfigurationBlock_combo_caption ; public static String RubyBuildConfigurationBlock_empty_input ; public static String RubyBuildConfigurationBlock_invalid_input ; public static String BuildPathsPropertyPage_unsavedchanges_title ; public static String BuildPathsPropertyPage_unsavedchanges_message ; public static String BuildPathsPropertyPage_unsavedchanges_button_save ; public static String BuildPathsPropertyPage_unsavedchanges_button_discard ; public static String BuildPathsPropertyPage_no_java_project_message ; public static String BuildPathsPropertyPage_closed_project_message ; public static String BuildPathsPropertyPage_error_title ; public static String BuildPathsPropertyPage_error_message ; public static String BuildPathsPropertyPage_job_title ; public static String BuildPathsPropertyPage_unsavedchanges_button_ignore ; public static String NewRubyProjectPreferencePage_error_decode ; public static String NewRubyProjectPreferencePage_description ; public static String NewRubyProjectPreferencePage_title ; public static String NewRubyProjectPreferencePage_jre_container_description ; public static String NewRubyProjectPreferencePage_jre_variable_description ; public static String NewRubyProjectPreferencePage_sourcefolder_label ; public static String NewRubyProjectPreferencePage_sourcefolder_project ; public static String NewRubyProjectPreferencePage_sourcefolder_folder ; public static String NewRubyProjectPreferencePage_folders_src ; public static String NewRubyProjectPreferencePage_jrelibrary_label ; public static String NewRubyProjectPreferencePage_folders_error_invalidcp ; public static String NewRubyProjectPreferencePage_folders_error_invalidsrcname ; public static String NewRubyProjectPreferencePage_folders_error_namesempty ; public static String KeywordPreferencePage_description ; public static String KeywordPreferencePage_title ; public static String KeywordInputDialog_new_title ; public static String KeywordInputDialog_edit_title ; public static String KeywordInputDialog_name_label ; public static String KeywordInputDialog_error_enterName ; public static String KeywordInputDialog_error_comma ; public static String KeywordInputDialog_error_entryExists ; public static String KeywordInputDialog_error_noSpace ; public static String RubyEditorPreferencePage_enableHovers ; public static String SpellingPreferencePage_dictionary_error ; public static String SpellingPreferencePage_locale_error ; public static String SpellingPreferencePage_empty_threshold ; public static String SpellingPreferencePage_invalid_threshold ; public static String SpellingPreferencePage_preferences_user ; public static String SpellingPreferencePage_ignore_digits_label ; public static String SpellingPreferencePage_ignore_mixed_label ; public static String SpellingPreferencePage_ignore_sentence_label ; public static String SpellingPreferencePage_ignore_upper_label ; public static String SpellingPreferencePage_ignore_url_label ; public static String SpellingPreferencePage_preferences_engine ; public static String SpellingPreferencePage_dictionary_label ; public static String SpellingPreferencePage_workspace_dictionary_label ; public static String SpellingPreferencePage_browse_label ; public static String SpellingPreferencePage_preferences_advanced ; public static String SpellingPreferencePage_proposals_threshold ; public static String SpellingPreferencePage_enable_contentassist_label ; public static String SpellingPreferencePage_filedialog_title ; public static String SpellingPreferencePage_filter_dictionary_extension ; public static String SpellingPreferencePage_filter_all_extension ; public static String SpellingPreferencePage_filter_dictionary_label ; public static String SpellingPreferencePage_filter_all_label ; public static String RubyBasePreferencePage_description ; public static String RubyBasePreferencePage_doubleclick_action ; public static String RubyBasePreferencePage_doubleclick_gointo ; public static String RubyBasePreferencePage_doubleclick_expand ; public static String RubyBasePreferencePage_search ; public static String RubyBasePreferencePage_search_small_menu ; public static String RubyBasePreferencePage_dialogs ; public static String RubyBasePreferencePage_do_not_hide_description ; public static String RubyBasePreferencePage_do_not_hide_button ; public static String RubyBasePreferencePage_do_not_hide_dialog_title ; public static String RubyBasePreferencePage_do_not_hide_dialog_message ; public static String RubyEditorPreferencePage_subWordNavigation ; public static String RubyEditorPreferencePage_quickassist_lightbulb ; public static String CodeAssistConfigurationBlock_insertionSection_title ; public static String CodeAssistConfigurationBlock_sortingSection_title ; public static String CodeAssistConfigurationBlock_autoactivationSection_title ; public static String RubyEditorPreferencePage_insertSingleProposalsAutomatically ; public static String RubyEditorPreferencePage_completePrefixes ; public static String RubyEditorPreferencePage_fillArgumentNamesOnMethodCompletion ; public static String RubyEditorPreferencePage_fillBlockArgumentNamesOnMethodCompletion ; public static String RubyEditorPreferencePage_presentProposalsInAlphabeticalOrder ; public static String CodeAssistConfigurationBlock_restricted_link ; public static String CodeAssistConfigurationBlock_matchCamelCase_label ; public static String RubyEditorPreferencePage_enableAutoActivation ; public static String RubyEditorPreferencePage_autoActivationDelay ; public static String RubyEditorPreferencePage_completionInserts ; public static String RubyEditorPreferencePage_completionOverwrites ; public static String RubyEditorPreferencePage_completionToggleHint ; public static String CodeAssistAdvancedConfigurationBlock_no_shortcut ; public static String CodeAssistAdvancedConfigurationBlock_page_description ; public static String CodeAssistAdvancedConfigurationBlock_default_table_description ; public static String CodeAssistAdvancedConfigurationBlock_default_table_category_column_title ; public static String CodeAssistAdvancedConfigurationBlock_default_table_keybinding_column_title ; public static String CodeAssistAdvancedConfigurationBlock_key_binding_hint ; public static String CodeAssistAdvancedConfigurationBlock_separate_table_description ; public static String CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title ; public static String CodeAssistAdvancedConfigurationBlock_Up ; public static String CodeAssistAdvancedConfigurationBlock_Down ; static { NLS . initializeMessages ( BUNDLE_NAME , PreferencesMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . FocusAdapter ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . forms . widgets . SharedScrolledComposite ; import org . eclipse . ui . internal . forms . widgets . FormUtil ; public class ScrolledPageContent extends SharedScrolledComposite { private KeyboardHandler fKeyboardHandler ; private VisibilityHandler fVisibilityHandler ; private class VisibilityHandler extends FocusAdapter { public void focusGained ( FocusEvent e ) { Widget w = e . widget ; if ( w instanceof Control ) { FormUtil . ensureVisible ( ScrolledPageContent . this , ( Control ) w ) ; } } } private class KeyboardHandler extends KeyAdapter { public void keyPressed ( KeyEvent e ) { Widget w = e . widget ; if ( w instanceof Control ) { if ( e . doit ) FormUtil . processKey ( e . keyCode , ScrolledPageContent . this ) ; } } } public ScrolledPageContent ( Composite parent ) { this ( parent , SWT . V_SCROLL | SWT . H_SCROLL ) ; } public ScrolledPageContent ( Composite parent , int style ) { super ( parent , style ) ; setExpandHorizontal ( true ) ; setExpandVertical ( true ) ; setContent ( new Composite ( this , SWT . NONE ) ) ; fVisibilityHandler = new VisibilityHandler ( ) ; fKeyboardHandler = new KeyboardHandler ( ) ; addListener ( SWT . Activate , new Listener ( ) { public void handleEvent ( Event event ) { if ( event . type == SWT . Activate ) { forceFocus ( ) ; } } } ) ; } public void adaptChild ( Control childControl ) { childControl . addKeyListener ( fKeyboardHandler ) ; childControl . addFocusListener ( fVisibilityHandler ) ; } public Composite getBody ( ) { return ( Composite ) getContent ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . internal . ui . dialogs . StatusDialog ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . preferences . KeywordConfigurationBlock . Keyword ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; public class KeywordInputDialog extends StatusDialog { private class KeywordInputAdapter implements IDialogFieldListener { public void dialogFieldChanged ( DialogField field ) { doValidation ( ) ; } } private StringDialogField fNameDialogField ; private List fExistingNames ; public KeywordInputDialog ( Shell parent , Keyword task , List existingEntries ) { super ( parent ) ; fExistingNames = new ArrayList ( existingEntries . size ( ) ) ; for ( int i = ; i < existingEntries . size ( ) ; i ++ ) { Keyword curr = ( Keyword ) existingEntries . get ( i ) ; if ( ! curr . equals ( task ) ) { fExistingNames . add ( curr . name ) ; } } if ( task == null ) { setTitle ( PreferencesMessages . KeywordInputDialog_new_title ) ; } else { setTitle ( PreferencesMessages . KeywordInputDialog_edit_title ) ; } KeywordInputAdapter adapter = new KeywordInputAdapter ( ) ; fNameDialogField = new StringDialogField ( ) ; fNameDialogField . setLabelText ( PreferencesMessages . KeywordInputDialog_name_label ) ; fNameDialogField . setDialogFieldListener ( adapter ) ; fNameDialogField . setText ( ( task != null ) ? task . name : "" ) ; } public Keyword getResult ( ) { Keyword task = new Keyword ( ) ; task . name = fNameDialogField . getText ( ) . trim ( ) ; return task ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Composite inner = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; layout . numColumns = ; inner . setLayout ( layout ) ; fNameDialogField . doFillIntoGrid ( inner , ) ; LayoutUtil . setHorizontalGrabbing ( fNameDialogField . getTextControl ( null ) ) ; LayoutUtil . setWidthHint ( fNameDialogField . getTextControl ( null ) , convertWidthInCharsToPixels ( ) ) ; fNameDialogField . postSetFocusOnDialogField ( parent . getDisplay ( ) ) ; applyDialogFont ( composite ) ; return composite ; } private void doValidation ( ) { StatusInfo status = new StatusInfo ( ) ; String newText = fNameDialogField . getText ( ) ; if ( newText . length ( ) == ) { status . setError ( PreferencesMessages . KeywordInputDialog_error_enterName ) ; } else { if ( newText . indexOf ( '' ) != - ) { status . setError ( PreferencesMessages . KeywordInputDialog_error_comma ) ; } else if ( fExistingNames . contains ( newText ) ) { status . setError ( PreferencesMessages . KeywordInputDialog_error_entryExists ) ; } else if ( Character . isWhitespace ( newText . charAt ( ) ) || Character . isWhitespace ( newText . charAt ( newText . length ( ) - ) ) ) { status . setError ( PreferencesMessages . KeywordInputDialog_error_noSpace ) ; } } updateStatus ( status ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . resources . IProject ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; public final class CodeAssistAdvancedPreferencePage extends PropertyAndPreferencePage { private CodeAssistAdvancedConfigurationBlock fConfigurationBlock ; public void createControl ( Composite parent ) { IWorkbenchPreferenceContainer container = ( IWorkbenchPreferenceContainer ) getContainer ( ) ; fConfigurationBlock = new CodeAssistAdvancedConfigurationBlock ( getNewStatusChangedListener ( ) , container ) ; super . createControl ( parent ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . RUBY_EDITOR_PREFERENCE_PAGE ) ; } protected Control createPreferenceContent ( Composite composite ) { return fConfigurationBlock . createContents ( composite ) ; } protected boolean hasProjectSpecificOptions ( IProject project ) { return false ; } protected String getPreferencePageID ( ) { return "" ; } protected String getPropertyPageID ( ) { return null ; } public void dispose ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . dispose ( ) ; } super . dispose ( ) ; } protected void performDefaults ( ) { super . performDefaults ( ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . performDefaults ( ) ; } } public boolean performOk ( ) { if ( fConfigurationBlock != null && ! fConfigurationBlock . performOk ( ) ) { return false ; } return super . performOk ( ) ; } public void performApply ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . performApply ( ) ; } } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . preferences . IWorkbenchPreferenceContainer ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class KeywordPreferencePage extends PropertyAndPreferencePage { public static final String PREF_ID = "" ; public static final String PROP_ID = "" ; private KeywordConfigurationBlock fConfigurationBlock ; public KeywordPreferencePage ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( PreferencesMessages . KeywordPreferencePage_description ) ; setTitle ( PreferencesMessages . KeywordPreferencePage_title ) ; } public void createControl ( Composite parent ) { IWorkbenchPreferenceContainer container = ( IWorkbenchPreferenceContainer ) getContainer ( ) ; fConfigurationBlock = new KeywordConfigurationBlock ( getNewStatusChangedListener ( ) , getProject ( ) , container ) ; super . createControl ( parent ) ; } protected Control createPreferenceContent ( Composite composite ) { return fConfigurationBlock . createContents ( composite ) ; } protected boolean hasProjectSpecificOptions ( IProject project ) { return fConfigurationBlock . hasProjectSpecificOptions ( project ) ; } protected String getPreferencePageID ( ) { return PREF_ID ; } protected String getPropertyPageID ( ) { return PROP_ID ; } protected void enableProjectSpecificSettings ( boolean useProjectSpecificSettings ) { super . enableProjectSpecificSettings ( useProjectSpecificSettings ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . useProjectSpecificSettings ( useProjectSpecificSettings ) ; } } protected void performDefaults ( ) { super . performDefaults ( ) ; if ( fConfigurationBlock != null ) { fConfigurationBlock . performDefaults ( ) ; } } public boolean performOk ( ) { if ( fConfigurationBlock != null && ! fConfigurationBlock . performOk ( ) ) { return false ; } return super . performOk ( ) ; } public void performApply ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . performApply ( ) ; } } public void dispose ( ) { if ( fConfigurationBlock != null ) { fConfigurationBlock . dispose ( ) ; } super . dispose ( ) ; } public void setElement ( IAdaptable element ) { super . setElement ( element ) ; setDescription ( null ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . text . Assert ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . ui . PreferenceConstants ; class MarkOccurrencesConfigurationBlock implements IPreferenceConfigurationBlock { private OverlayPreferenceStore fStore ; private Map fCheckBoxes = new HashMap ( ) ; private SelectionListener fCheckBoxListener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { Button button = ( Button ) e . widget ; fStore . setValue ( ( String ) fCheckBoxes . get ( button ) , button . getSelection ( ) ) ; } } ; private ArrayList fMasterSlaveListeners = new ArrayList ( ) ; private StatusInfo fStatus ; public MarkOccurrencesConfigurationBlock ( OverlayPreferenceStore store ) { Assert . isNotNull ( store ) ; fStore = store ; fStore . addKeys ( createOverlayStoreKeys ( ) ) ; } private OverlayPreferenceStore . OverlayKey [ ] createOverlayStoreKeys ( ) { ArrayList overlayKeys = new ArrayList ( ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_MARK_OCCURRENCES ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_MARK_TYPE_OCCURRENCES ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_MARK_METHOD_OCCURRENCES ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_MARK_CONSTANT_OCCURRENCES ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_MARK_FIELD_OCCURRENCES ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_MARK_METHOD_EXIT_POINTS ) ) ; overlayKeys . add ( new OverlayPreferenceStore . OverlayKey ( OverlayPreferenceStore . BOOLEAN , PreferenceConstants . EDITOR_STICKY_OCCURRENCES ) ) ; OverlayPreferenceStore . OverlayKey [ ] keys = new OverlayPreferenceStore . OverlayKey [ overlayKeys . size ( ) ] ; overlayKeys . toArray ( keys ) ; return keys ; } public Control createControl ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; String label ; label = PreferencesMessages . MarkOccurrencesConfigurationBlock_markOccurrences ; Button master = addCheckBox ( composite , label , PreferenceConstants . EDITOR_MARK_OCCURRENCES , ) ; label = PreferencesMessages . MarkOccurrencesConfigurationBlock_markTypeOccurrences ; Button slave = addCheckBox ( composite , label , PreferenceConstants . EDITOR_MARK_TYPE_OCCURRENCES , ) ; createDependency ( master , PreferenceConstants . EDITOR_STICKY_OCCURRENCES , slave ) ; label = PreferencesMessages . MarkOccurrencesConfigurationBlock_markConstantOccurrences ; slave = addCheckBox ( composite , label , PreferenceConstants . EDITOR_MARK_CONSTANT_OCCURRENCES , ) ; createDependency ( master , PreferenceConstants . EDITOR_MARK_CONSTANT_OCCURRENCES , slave ) ; label = PreferencesMessages . MarkOccurrencesConfigurationBlock_markLocalVariableOccurrences ; slave = addCheckBox ( composite , label , PreferenceConstants . EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES , ) ; createDependency ( master , PreferenceConstants . EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES , slave ) ; label = PreferencesMessages . MarkOccurrencesConfigurationBlock_markMethodExitPoints ; slave = addCheckBox ( composite , label , PreferenceConstants . EDITOR_MARK_METHOD_EXIT_POINTS , ) ; createDependency ( master , PreferenceConstants . EDITOR_MARK_METHOD_EXIT_POINTS , slave ) ; addFiller ( composite ) ; label = PreferencesMessages . MarkOccurrencesConfigurationBlock_stickyOccurrences ; slave = addCheckBox ( composite , label , PreferenceConstants . EDITOR_STICKY_OCCURRENCES , ) ; createDependency ( master , PreferenceConstants . EDITOR_STICKY_OCCURRENCES , slave ) ; return composite ; } private void addFiller ( Composite composite ) { PixelConverter pixelConverter = new PixelConverter ( composite ) ; Label filler = new Label ( composite , SWT . LEFT ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; gd . horizontalSpan = ; gd . heightHint = pixelConverter . convertHeightInCharsToPixels ( ) / ; filler . setLayoutData ( gd ) ; } private Button addCheckBox ( Composite parent , String label , String key , int indentation ) { Button checkBox = new Button ( parent , SWT . CHECK ) ; checkBox . setText ( label ) ; GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ; gd . horizontalIndent = indentation ; gd . horizontalSpan = ; checkBox . setLayoutData ( gd ) ; checkBox . addSelectionListener ( fCheckBoxListener ) ; fCheckBoxes . put ( checkBox , key ) ; return checkBox ; } private void createDependency ( final Button master , String masterKey , final Control slave ) { indent ( slave ) ; boolean masterState = fStore . getBoolean ( masterKey ) ; slave . setEnabled ( masterState ) ; SelectionListener listener = new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { slave . setEnabled ( master . getSelection ( ) ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ; master . addSelectionListener ( listener ) ; fMasterSlaveListeners . add ( listener ) ; } private static void indent ( Control control ) { GridData gridData = new GridData ( ) ; gridData . horizontalIndent = ; control . setLayoutData ( gridData ) ; } public void initialize ( ) { initializeFields ( ) ; } void initializeFields ( ) { Iterator iter = fCheckBoxes . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Button b = ( Button ) iter . next ( ) ; String key = ( String ) fCheckBoxes . get ( b ) ; b . setSelection ( fStore . getBoolean ( key ) ) ; } iter = fMasterSlaveListeners . iterator ( ) ; while ( iter . hasNext ( ) ) { SelectionListener listener = ( SelectionListener ) iter . next ( ) ; listener . widgetSelected ( null ) ; } } public void performOk ( ) { } public void performDefaults ( ) { restoreFromPreferences ( ) ; initializeFields ( ) ; } private void restoreFromPreferences ( ) { } IStatus getStatus ( ) { if ( fStatus == null ) fStatus = new StatusInfo ( ) ; return fStatus ; } public void dispose ( ) { } } package org . rubypeople . rdt . internal . ui . preferences ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public final class SmartTypingPreferencePage extends AbstractConfigurationBlockPreferencePage { protected String getHelpId ( ) { return IRubyHelpContextIds . RUBY_EDITOR_PREFERENCE_PAGE ; } protected void setDescription ( ) { String description = PreferencesMessages . RubyEditorPreferencePage_typing_tabTitle ; setDescription ( description ) ; } protected void setPreferenceStore ( ) { setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; } protected Label createDescriptionLabel ( Composite parent ) { return null ; } protected IPreferenceConfigurationBlock createConfigurationBlock ( OverlayPreferenceStore overlayPreferenceStore ) { return new SmartTypingConfigurationBlock ( overlayPreferenceStore ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . util . ArrayList ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . OptionalMessageDialog ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyBasePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String DOUBLE_CLICK = PreferenceConstants . DOUBLE_CLICK ; private static final String DOUBLE_CLICK_GOES_INTO = PreferenceConstants . DOUBLE_CLICK_GOES_INTO ; private static final String DOUBLE_CLICK_EXPANDS = PreferenceConstants . DOUBLE_CLICK_EXPANDS ; private ArrayList fCheckBoxes ; private ArrayList fRadioButtons ; private ArrayList fTextControls ; public RubyBasePreferencePage ( ) { super ( ) ; setPreferenceStore ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( PreferencesMessages . RubyBasePreferencePage_description ) ; fRadioButtons = new ArrayList ( ) ; fCheckBoxes = new ArrayList ( ) ; fTextControls = new ArrayList ( ) ; } public void init ( IWorkbench workbench ) { } public void createControl ( Composite parent ) { super . createControl ( parent ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IRubyHelpContextIds . JAVA_BASE_PREFERENCE_PAGE ) ; } private Button addRadioButton ( Composite parent , String label , String key , String value ) { GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; Button button = new Button ( parent , SWT . RADIO ) ; button . setText ( label ) ; button . setData ( new String [ ] { key , value } ) ; button . setLayoutData ( gd ) ; button . setSelection ( value . equals ( getPreferenceStore ( ) . getString ( key ) ) ) ; fRadioButtons . add ( button ) ; return button ; } private Button addCheckBox ( Composite parent , String label , String key ) { GridData gd = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; Button button = new Button ( parent , SWT . CHECK ) ; button . setText ( label ) ; button . setData ( key ) ; button . setLayoutData ( gd ) ; button . setSelection ( getPreferenceStore ( ) . getBoolean ( key ) ) ; fCheckBoxes . add ( button ) ; return button ; } protected Control createContents ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite result = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = ; layout . verticalSpacing = convertVerticalDLUsToPixels ( ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; result . setLayout ( layout ) ; Group doubleClickGroup = new Group ( result , SWT . NONE ) ; doubleClickGroup . setLayout ( new GridLayout ( ) ) ; doubleClickGroup . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; doubleClickGroup . setText ( PreferencesMessages . RubyBasePreferencePage_doubleclick_action ) ; addRadioButton ( doubleClickGroup , PreferencesMessages . RubyBasePreferencePage_doubleclick_gointo , DOUBLE_CLICK , DOUBLE_CLICK_GOES_INTO ) ; addRadioButton ( doubleClickGroup , PreferencesMessages . RubyBasePreferencePage_doubleclick_expand , DOUBLE_CLICK , DOUBLE_CLICK_EXPANDS ) ; Group group = new Group ( result , SWT . NONE ) ; group . setLayout ( new GridLayout ( ) ) ; group . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; group . setText ( PreferencesMessages . RubyBasePreferencePage_search ) ; addCheckBox ( group , PreferencesMessages . RubyBasePreferencePage_search_small_menu , PreferenceConstants . SEARCH_USE_REDUCED_MENU ) ; layout = new GridLayout ( ) ; layout . numColumns = ; Group dontAskGroup = new Group ( result , SWT . NONE ) ; dontAskGroup . setLayout ( layout ) ; dontAskGroup . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; dontAskGroup . setText ( PreferencesMessages . RubyBasePreferencePage_dialogs ) ; Label label = new Label ( dontAskGroup , SWT . WRAP ) ; label . setText ( PreferencesMessages . RubyBasePreferencePage_do_not_hide_description ) ; GridData data = new GridData ( GridData . FILL , GridData . CENTER , true , false ) ; data . widthHint = convertVerticalDLUsToPixels ( ) ; label . setLayoutData ( data ) ; Button clearButton = new Button ( dontAskGroup , SWT . PUSH ) ; clearButton . setText ( PreferencesMessages . RubyBasePreferencePage_do_not_hide_button ) ; clearButton . setLayoutData ( new GridData ( GridData . FILL , GridData . BEGINNING , false , false ) ) ; clearButton . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { unhideAllDialogs ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { unhideAllDialogs ( ) ; } } ) ; SWTUtil . setButtonDimensionHint ( clearButton ) ; Dialog . applyDialogFont ( result ) ; return result ; } protected final void unhideAllDialogs ( ) { OptionalMessageDialog . clearAllRememberedStates ( ) ; MessageDialog . openInformation ( getShell ( ) , PreferencesMessages . RubyBasePreferencePage_do_not_hide_dialog_title , PreferencesMessages . RubyBasePreferencePage_do_not_hide_dialog_message ) ; } protected void performDefaults ( ) { IPreferenceStore store = getPreferenceStore ( ) ; for ( int i = ; i < fCheckBoxes . size ( ) ; i ++ ) { Button button = ( Button ) fCheckBoxes . get ( i ) ; String key = ( String ) button . getData ( ) ; button . setSelection ( store . getDefaultBoolean ( key ) ) ; } for ( int i = ; i < fRadioButtons . size ( ) ; i ++ ) { Button button = ( Button ) fRadioButtons . get ( i ) ; String [ ] info = ( String [ ] ) button . getData ( ) ; button . setSelection ( info [ ] . equals ( store . getDefaultString ( info [ ] ) ) ) ; } for ( int i = ; i < fTextControls . size ( ) ; i ++ ) { Text text = ( Text ) fTextControls . get ( i ) ; String key = ( String ) text . getData ( ) ; text . setText ( store . getDefaultString ( key ) ) ; } super . performDefaults ( ) ; } public boolean performOk ( ) { IPreferenceStore store = getPreferenceStore ( ) ; for ( int i = ; i < fCheckBoxes . size ( ) ; i ++ ) { Button button = ( Button ) fCheckBoxes . get ( i ) ; String key = ( String ) button . getData ( ) ; store . setValue ( key , button . getSelection ( ) ) ; } for ( int i = ; i < fRadioButtons . size ( ) ; i ++ ) { Button button = ( Button ) fRadioButtons . get ( i ) ; if ( button . getSelection ( ) ) { String [ ] info = ( String [ ] ) button . getData ( ) ; store . setValue ( info [ ] , info [ ] ) ; } } for ( int i = ; i < fTextControls . size ( ) ; i ++ ) { Text text = ( Text ) fTextControls . get ( i ) ; String key = ( String ) text . getData ( ) ; store . setValue ( key , text . getText ( ) ) ; } RubyPlugin . getDefault ( ) . savePluginPreferences ( ) ; return super . performOk ( ) ; } } package org . rubypeople . rdt . internal . ui . preferences ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . parsers . SAXParser ; import javax . xml . parsers . SAXParserFactory ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . Transformer ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; import org . eclipse . core . runtime . IStatus ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIException ; import org . rubypeople . rdt . internal . ui . RubyUIStatus ; import org . rubypeople . rdt . internal . ui . preferences . RubyEditorColoringConfigurationBlock . HighlightingColorListItem ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . xml . sax . Attributes ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; import org . xml . sax . helpers . DefaultHandler ; public class SyntaxColoringStore { private static final int CURRENT_VERSION = ; private final static String XML_NODE_ROOT = "" ; private final static String XML_NODE_SETTING = "" ; private final static String XML_ATTRIBUTE_VERSION = "" ; private final static String XML_ATTRIBUTE_ID = "" ; private final static String XML_ATTRIBUTE_VALUE = "" ; public static void write ( List < HighlightingColorListItem > colors , File file ) throws RubyUIException { final OutputStream writer ; try { writer = new FileOutputStream ( file ) ; try { writeToStream ( colors , writer ) ; } finally { try { writer . close ( ) ; } catch ( IOException e ) { } } } catch ( IOException e ) { throw createException ( e , "" ) ; } } private static void writeToStream ( List < HighlightingColorListItem > colors , OutputStream stream ) throws RubyUIException { try { final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; final DocumentBuilder builder = factory . newDocumentBuilder ( ) ; final Document document = builder . newDocument ( ) ; final Element rootElement = document . createElement ( XML_NODE_ROOT ) ; rootElement . setAttribute ( XML_ATTRIBUTE_VERSION , Integer . toString ( CURRENT_VERSION ) ) ; document . appendChild ( rootElement ) ; for ( HighlightingColorListItem item : colors ) { addKeyValuePair ( document , rootElement , item . getColorKey ( ) , "" ) ; addKeyValuePair ( document , rootElement , item . getBackgroundKey ( ) , "" ) ; addKeyValuePair ( document , rootElement , item . getBackgroundEnabledKey ( ) , "" ) ; addKeyValuePair ( document , rootElement , item . getBoldKey ( ) , "" ) ; addKeyValuePair ( document , rootElement , item . getItalicKey ( ) , "" ) ; addKeyValuePair ( document , rootElement , item . getStrikethroughKey ( ) , "" ) ; addKeyValuePair ( document , rootElement , item . getUnderlineKey ( ) , "" ) ; } Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . METHOD , "" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , "" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "" ) ; transformer . transform ( new DOMSource ( document ) , new StreamResult ( stream ) ) ; } catch ( TransformerException e ) { throw createException ( e , "" ) ; } catch ( ParserConfigurationException e ) { throw createException ( e , "" ) ; } } private static void addKeyValuePair ( final Document document , final Element rootElement , String key , String defaultValue ) { String value = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getString ( key ) ; if ( value == null || value . trim ( ) . length ( ) == ) { value = defaultValue ; } final Element setting = document . createElement ( XML_NODE_SETTING ) ; setting . setAttribute ( XML_ATTRIBUTE_ID , key ) ; setting . setAttribute ( XML_ATTRIBUTE_VALUE , value ) ; rootElement . appendChild ( setting ) ; } private static RubyUIException createException ( Throwable t , String message ) { return new RubyUIException ( RubyUIStatus . createError ( IStatus . ERROR , message , t ) ) ; } public static Map < String , String > readFromFile ( File file ) throws RubyUIException { try { final FileInputStream reader = new FileInputStream ( file ) ; try { return readFromStream ( new InputSource ( reader ) ) ; } finally { try { reader . close ( ) ; } catch ( IOException e ) { } } } catch ( IOException e ) { throw createException ( e , "" ) ; } } private static Map < String , String > readFromStream ( InputSource inputSource ) throws RubyUIException { final ProfileDefaultHandler handler = new ProfileDefaultHandler ( ) ; try { final SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; final SAXParser parser = factory . newSAXParser ( ) ; parser . parse ( inputSource , handler ) ; } catch ( SAXException e ) { throw createException ( e , "" ) ; } catch ( IOException e ) { throw createException ( e , "" ) ; } catch ( ParserConfigurationException e ) { throw createException ( e , "" ) ; } return handler . getProfiles ( ) ; } private final static class ProfileDefaultHandler extends DefaultHandler { private Map fSettings ; public void startElement ( String uri , String localName , String qName , Attributes attributes ) throws SAXException { if ( qName . equals ( XML_NODE_SETTING ) ) { final String key = attributes . getValue ( XML_ATTRIBUTE_ID ) ; final String value = attributes . getValue ( XML_ATTRIBUTE_VALUE ) ; fSettings . put ( key , value ) ; } else if ( qName . equals ( XML_NODE_ROOT ) ) { fSettings = new HashMap ( ) ; } } public void endElement ( String uri , String localName , String qName ) { } public Map getProfiles ( ) { return fSettings ; } } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IMenuCreator ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyExplorerTracker . IRubyProjectListener ; import org . rubypeople . rdt . internal . ui . wizards . OpenNewRubyProjectWizardAction ; public class RubyProjectSelectionAction extends Action implements IMenuCreator { private Menu fMenu ; private IRubyProjectListener listener ; public RubyProjectSelectionAction ( ) { this ( "" ) ; } public RubyProjectSelectionAction ( String tooltip ) { setEnabled ( RubyCore . getRubyProjects ( ) . length > ) ; setToolTipText ( tooltip ) ; setImageDescriptor ( RubyPlugin . getImageDescriptor ( "" ) ) ; setMenuCreator ( this ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( new IResourceChangeListener ( ) { public void resourceChanged ( IResourceChangeEvent event ) { IResource source = event . getResource ( ) ; if ( source != null ) return ; IResourceDelta [ ] deltas = event . getDelta ( ) . getAffectedChildren ( IResourceDelta . ADDED | IResourceDelta . CHANGED | IResourceDelta . REMOVED , IResource . PROJECT ) ; if ( deltas != null && deltas . length > ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { if ( fMenu != null && ! fMenu . isDisposed ( ) ) { fMenu . dispose ( ) ; } fMenu = null ; setEnabled ( RubyCore . getRubyProjects ( ) . length > ) ; } } ) ; } } } , IResourceChangeEvent . POST_CHANGE ) ; } public void dispose ( ) { } public Menu getMenu ( Control parent ) { if ( fMenu != null && ! fMenu . isDisposed ( ) ) { fMenu . dispose ( ) ; } fMenu = new Menu ( parent ) ; int accel = ; IProject [ ] projects = RubyCore . getRubyProjects ( ) ; for ( IProject project : projects ) { String label = project . getName ( ) ; ImageDescriptor image = null ; addActionToMenu ( fMenu , new RubyProjectAction ( label , image , project ) , accel ) ; accel ++ ; } MenuItem addProjectItem = new MenuItem ( fMenu , SWT . PUSH ) ; addProjectItem . setText ( "" ) ; final Image projectImage = RubyPlugin . getImageDescriptor ( "" ) . createImage ( ) ; addProjectItem . setImage ( projectImage ) ; addProjectItem . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { if ( projectImage != null && ! projectImage . isDisposed ( ) ) { projectImage . dispose ( ) ; } } } ) ; addProjectItem . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { new OpenNewRubyProjectWizardAction ( ) . run ( ) ; } } ) ; return fMenu ; } private void addActionToMenu ( Menu parent , Action action , int accelerator ) { if ( accelerator < ) { StringBuffer label = new StringBuffer ( ) ; label . append ( '' ) ; label . append ( accelerator ) ; label . append ( '' ) ; label . append ( action . getText ( ) ) ; action . setText ( label . toString ( ) ) ; } ActionContributionItem item = new ActionContributionItem ( action ) ; item . fill ( parent , - ) ; } public Menu getMenu ( Menu parent ) { return null ; } private class RubyProjectAction extends Action { private IProject project ; public RubyProjectAction ( String label , ImageDescriptor image , IProject project ) { setText ( label ) ; if ( image != null ) { setImageDescriptor ( image ) ; } this . project = project ; } public void run ( ) { if ( listener != null ) { listener . projectSelected ( project ) ; } } public void runWithEvent ( Event event ) { run ( ) ; } } public IRubyProjectListener getListener ( ) { return listener ; } public void setListener ( IRubyProjectListener listener ) { this . listener = listener ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . mapping . ResourceMapping ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IAdapterFactory ; import org . eclipse . search . ui . ISearchPageScoreComputer ; import org . eclipse . ui . IContainmentAdapter ; import org . eclipse . ui . IContributorResourceAdapter ; import org . eclipse . ui . IPersistableElement ; import org . eclipse . ui . ide . IContributorResourceAdapter2 ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . eclipse . ui . views . properties . FilePropertySource ; import org . eclipse . ui . views . properties . IPropertySource ; import org . eclipse . ui . views . properties . ResourcePropertySource ; import org . eclipse . ui . views . tasklist . ITaskListResourceAdapter ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . internal . corext . util . RubyElementResourceMapping ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptEditorInput ; import org . rubypeople . rdt . internal . ui . search . RubySearchPageScoreComputer ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; public class RubyElementAdapterFactory implements IAdapterFactory , IContributorResourceAdapter , IContributorResourceAdapter2 { private static Class [ ] PROPERTIES = new Class [ ] { IPropertySource . class , IResource . class , IWorkbenchAdapter . class , IResourceLocator . class , IPersistableElement . class , IContributorResourceAdapter . class , IContributorResourceAdapter2 . class , ITaskListResourceAdapter . class , IContainmentAdapter . class } ; private Object fSearchPageScoreComputer ; private static IResourceLocator fgResourceLocator ; private static RubyWorkbenchAdapter fgRubyWorkbenchAdapter ; private static ITaskListResourceAdapter fgTaskListAdapter ; private static RubyElementContainmentAdapter fgRubyElementContainmentAdapter ; public Class [ ] getAdapterList ( ) { updateLazyLoadedAdapters ( ) ; return PROPERTIES ; } public Object getAdapter ( Object element , Class key ) { updateLazyLoadedAdapters ( ) ; IRubyElement java = getRubyElement ( element ) ; if ( IPropertySource . class . equals ( key ) ) { return getProperties ( java ) ; } if ( IResource . class . equals ( key ) ) { return getResource ( java ) ; } if ( fSearchPageScoreComputer != null && ISearchPageScoreComputer . class . equals ( key ) ) { return fSearchPageScoreComputer ; } if ( IWorkbenchAdapter . class . equals ( key ) ) { return getRubyWorkbenchAdapter ( ) ; } if ( IResourceLocator . class . equals ( key ) ) { return getResourceLocator ( ) ; } if ( IPersistableElement . class . equals ( key ) ) { return new PersistableRubyElementFactory ( java ) ; } if ( IContributorResourceAdapter . class . equals ( key ) ) { return this ; } if ( IContributorResourceAdapter2 . class . equals ( key ) ) { return this ; } if ( ITaskListResourceAdapter . class . equals ( key ) ) { return getTaskListAdapter ( ) ; } if ( IContainmentAdapter . class . equals ( key ) ) { return getRubyElementContainmentAdapter ( ) ; } return null ; } private IResource getResource ( IRubyElement element ) { switch ( element . getElementType ( ) ) { case IRubyElement . TYPE : IRubyElement parent = element . getParent ( ) ; if ( parent instanceof IRubyScript ) { return ( ( IRubyScript ) parent ) . getPrimary ( ) . getResource ( ) ; } return null ; case IRubyElement . SCRIPT : return ( ( IRubyScript ) element ) . getPrimary ( ) . getResource ( ) ; case IRubyElement . SOURCE_FOLDER : ISourceFolderRoot root = ( ISourceFolderRoot ) element . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; if ( ! root . isExternal ( ) ) { return element . getResource ( ) ; } return null ; case IRubyElement . SOURCE_FOLDER_ROOT : case IRubyElement . RUBY_PROJECT : case IRubyElement . RUBY_MODEL : return element . getResource ( ) ; default : return null ; } } public IResource getAdaptedResource ( IAdaptable adaptable ) { IRubyElement je = getRubyElement ( adaptable ) ; if ( je != null ) return getResource ( je ) ; return null ; } public ResourceMapping getAdaptedResourceMapping ( IAdaptable adaptable ) { IRubyElement je = getRubyElement ( adaptable ) ; if ( je != null ) return RubyElementResourceMapping . create ( je ) ; return null ; } private IRubyElement getRubyElement ( Object element ) { if ( element instanceof IRubyElement ) return ( IRubyElement ) element ; if ( element instanceof IRubyScriptEditorInput ) return ( ( IRubyScriptEditorInput ) element ) . getRubyScript ( ) . getPrimaryElement ( ) ; return null ; } private IPropertySource getProperties ( IRubyElement element ) { IResource resource = getResource ( element ) ; if ( resource == null ) return new RubyElementProperties ( element ) ; if ( resource . getType ( ) == IResource . FILE ) return new FilePropertySource ( ( IFile ) resource ) ; return new ResourcePropertySource ( resource ) ; } private void updateLazyLoadedAdapters ( ) { if ( fSearchPageScoreComputer == null && SearchUtil . isSearchPlugInActivated ( ) ) createSearchPageScoreComputer ( ) ; } private void createSearchPageScoreComputer ( ) { fSearchPageScoreComputer = new RubySearchPageScoreComputer ( ) ; PROPERTIES = new Class [ ] { IPropertySource . class , IResource . class , ISearchPageScoreComputer . class , IWorkbenchAdapter . class , IResourceLocator . class , IPersistableElement . class , IProject . class , IContributorResourceAdapter . class , IContributorResourceAdapter2 . class , ITaskListResourceAdapter . class , IContainmentAdapter . class } ; } private static IResourceLocator getResourceLocator ( ) { if ( fgResourceLocator == null ) fgResourceLocator = new ResourceLocator ( ) ; return fgResourceLocator ; } private static RubyWorkbenchAdapter getRubyWorkbenchAdapter ( ) { if ( fgRubyWorkbenchAdapter == null ) fgRubyWorkbenchAdapter = new RubyWorkbenchAdapter ( ) ; return fgRubyWorkbenchAdapter ; } private static ITaskListResourceAdapter getTaskListAdapter ( ) { if ( fgTaskListAdapter == null ) fgTaskListAdapter = new RubyTaskListAdapter ( ) ; return fgTaskListAdapter ; } private static RubyElementContainmentAdapter getRubyElementContainmentAdapter ( ) { if ( fgRubyElementContainmentAdapter == null ) fgRubyElementContainmentAdapter = new RubyElementContainmentAdapter ( ) ; return fgRubyElementContainmentAdapter ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . search . ui . text . AbstractTextSearchResult ; public class TextSearchTableContentProvider implements IStructuredContentProvider { protected final Object [ ] EMPTY_ARRAY = new Object [ ] ; private AbstractTextSearchResult fSearchResult ; private TableViewer fTableViewer ; public Object [ ] getElements ( Object inputElement ) { if ( inputElement instanceof AbstractTextSearchResult ) return ( ( AbstractTextSearchResult ) inputElement ) . getElements ( ) ; return EMPTY_ARRAY ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fTableViewer = ( TableViewer ) viewer ; fSearchResult = ( AbstractTextSearchResult ) newInput ; } public void elementsChanged ( Object [ ] updatedElements ) { int addCount = ; int removeCount = ; for ( int i = ; i < updatedElements . length ; i ++ ) { if ( fSearchResult . getMatchCount ( updatedElements [ i ] ) > ) { if ( fTableViewer . testFindItem ( updatedElements [ i ] ) != null ) fTableViewer . refresh ( updatedElements [ i ] ) ; else fTableViewer . add ( updatedElements [ i ] ) ; addCount ++ ; } else { fTableViewer . remove ( updatedElements [ i ] ) ; removeCount ++ ; } } } public void clear ( ) { fTableViewer . refresh ( ) ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . search . ui . ISearchQuery ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class SearchUtil { public static final int LRU_WORKINGSET_LIST_SIZE = ; private static LRUWorkingSetsList fgLRUWorkingSets ; private static final String DIALOG_SETTINGS_KEY = "" ; private static final String STORE_LRU_WORKING_SET_NAMES = "" ; public static boolean isSearchPlugInActivated ( ) { return Platform . getBundle ( "" ) . getState ( ) == Bundle . ACTIVE ; } public static void runQueryInBackground ( Object query ) { NewSearchUI . runQueryInBackground ( ( ISearchQuery ) query ) ; } public static IStatus runQueryInForeground ( IRunnableContext context , Object query ) { return NewSearchUI . runQueryInForeground ( context , ( ISearchQuery ) query ) ; } static IRubyScript findCompilationUnit ( IRubyElement element ) { if ( element == null ) return null ; return ( IRubyScript ) element . getAncestor ( IRubyElement . SCRIPT ) ; } public static String toString ( IWorkingSet [ ] workingSets ) { Arrays . sort ( workingSets , new WorkingSetComparator ( ) ) ; String result = "" ; if ( workingSets != null && workingSets . length > ) { boolean firstFound = false ; for ( int i = ; i < workingSets . length ; i ++ ) { String workingSetLabel = workingSets [ i ] . getLabel ( ) ; if ( firstFound ) result = Messages . format ( SearchMessages . SearchUtil_workingSetConcatenation , new String [ ] { result , workingSetLabel } ) ; else { result = workingSetLabel ; firstFound = true ; } } } return result ; } public static void updateLRUWorkingSets ( IWorkingSet [ ] workingSets ) { if ( workingSets == null || workingSets . length < ) return ; getLRUWorkingSets ( ) . add ( workingSets ) ; saveState ( getDialogStoreSection ( ) ) ; } private static void saveState ( IDialogSettings settingsStore ) { IWorkingSet [ ] workingSets ; Iterator iter = fgLRUWorkingSets . iterator ( ) ; int i = ; while ( iter . hasNext ( ) ) { workingSets = ( IWorkingSet [ ] ) iter . next ( ) ; String [ ] names = new String [ workingSets . length ] ; for ( int j = ; j < workingSets . length ; j ++ ) names [ j ] = workingSets [ j ] . getName ( ) ; settingsStore . put ( STORE_LRU_WORKING_SET_NAMES + i , names ) ; i ++ ; } } public static LRUWorkingSetsList getLRUWorkingSets ( ) { if ( fgLRUWorkingSets == null ) { restoreState ( ) ; } return fgLRUWorkingSets ; } private static void restoreState ( ) { fgLRUWorkingSets = new LRUWorkingSetsList ( LRU_WORKINGSET_LIST_SIZE ) ; IDialogSettings settingsStore = getDialogStoreSection ( ) ; boolean foundLRU = false ; for ( int i = LRU_WORKINGSET_LIST_SIZE - ; i >= ; i -- ) { String [ ] lruWorkingSetNames = settingsStore . getArray ( STORE_LRU_WORKING_SET_NAMES + i ) ; if ( lruWorkingSetNames != null ) { Set workingSets = new HashSet ( ) ; for ( int j = ; j < lruWorkingSetNames . length ; j ++ ) { IWorkingSet workingSet = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSet ( lruWorkingSetNames [ j ] ) ; if ( workingSet != null ) { workingSets . add ( workingSet ) ; } } foundLRU = true ; if ( ! workingSets . isEmpty ( ) ) fgLRUWorkingSets . add ( ( IWorkingSet [ ] ) workingSets . toArray ( new IWorkingSet [ workingSets . size ( ) ] ) ) ; } } if ( ! foundLRU ) restoreFromOldFormat ( ) ; } private static IDialogSettings getDialogStoreSection ( ) { IDialogSettings settingsStore = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( DIALOG_SETTINGS_KEY ) ; if ( settingsStore == null ) settingsStore = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( DIALOG_SETTINGS_KEY ) ; return settingsStore ; } private static void restoreFromOldFormat ( ) { fgLRUWorkingSets = new LRUWorkingSetsList ( LRU_WORKINGSET_LIST_SIZE ) ; IDialogSettings settingsStore = getDialogStoreSection ( ) ; boolean foundLRU = false ; String [ ] lruWorkingSetNames = settingsStore . getArray ( STORE_LRU_WORKING_SET_NAMES ) ; if ( lruWorkingSetNames != null ) { for ( int i = lruWorkingSetNames . length - ; i >= ; i -- ) { IWorkingSet workingSet = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSet ( lruWorkingSetNames [ i ] ) ; if ( workingSet != null ) { foundLRU = true ; fgLRUWorkingSets . add ( new IWorkingSet [ ] { workingSet } ) ; } } } if ( foundLRU ) saveState ( settingsStore ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . window . Window ; public class FiltersDialogAction extends Action { private RubySearchResultPage fPage ; public FiltersDialogAction ( RubySearchResultPage page ) { super ( SearchMessages . FiltersDialogAction_label ) ; fPage = page ; } public void run ( ) { FiltersDialog dialog = new FiltersDialog ( fPage ) ; if ( dialog . open ( ) == Window . OK ) { fPage . setFilters ( dialog . getEnabledFilters ( ) ) ; fPage . enableLimit ( dialog . isLimitEnabled ( ) ) ; fPage . setElementLimit ( dialog . getElementLimit ( ) ) ; } } } package org . rubypeople . rdt . internal . ui . search ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . TableViewer ; public class RubySearchTableContentProvider extends RubySearchContentProvider implements IStructuredContentProvider { public RubySearchTableContentProvider ( RubySearchResultPage page ) { super ( page ) ; } public Object [ ] getElements ( Object inputElement ) { if ( inputElement instanceof RubySearchResult ) { Set filteredElements = new HashSet ( ) ; Object [ ] rawElements = ( ( RubySearchResult ) inputElement ) . getElements ( ) ; for ( int i = ; i < rawElements . length ; i ++ ) { if ( getPage ( ) . getDisplayedMatchCount ( rawElements [ i ] ) > ) filteredElements . add ( rawElements [ i ] ) ; } return filteredElements . toArray ( ) ; } return EMPTY_ARR ; } public void elementsChanged ( Object [ ] updatedElements ) { if ( fResult == null ) return ; int addCount = ; int removeCount = ; TableViewer viewer = ( TableViewer ) getPage ( ) . getViewer ( ) ; Set updated = new HashSet ( ) ; Set added = new HashSet ( ) ; Set removed = new HashSet ( ) ; for ( int i = ; i < updatedElements . length ; i ++ ) { if ( getPage ( ) . getDisplayedMatchCount ( updatedElements [ i ] ) > ) { if ( viewer . testFindItem ( updatedElements [ i ] ) != null ) updated . add ( updatedElements [ i ] ) ; else added . add ( updatedElements [ i ] ) ; addCount ++ ; } else { removed . add ( updatedElements [ i ] ) ; removeCount ++ ; } } viewer . add ( added . toArray ( ) ) ; viewer . update ( updated . toArray ( ) , new String [ ] { SearchLabelProvider . PROPERTY_MATCH_COUNT } ) ; viewer . remove ( removed . toArray ( ) ) ; } public void filtersChanged ( MatchFilter [ ] filters ) { super . filtersChanged ( filters ) ; getPage ( ) . getViewer ( ) . refresh ( ) ; } public void clear ( ) { getPage ( ) . getViewer ( ) . refresh ( ) ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . Collection ; import java . util . List ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . Position ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyElement ; public interface IOccurrencesFinder { public String initialize ( Node root , int offset , int length ) ; public List < Position > perform ( ) ; public String getJobLabel ( ) ; public String getUnformattedPluralLabel ( ) ; public String getUnformattedSingularLabel ( ) ; public String getElementName ( ) ; public void collectOccurrenceMatches ( IRubyElement element , IDocument document , Collection resultingMatches ) ; public void setFMarkConstantOccurrences ( boolean markConstantOccurrences ) ; public void setFMarkFieldOccurrences ( boolean markFieldOccurrences ) ; public void setFMarkLocalVariableOccurrences ( boolean markLocalVariableOccurrences ) ; public void setFMarkMethodExitPoints ( boolean markMethodExitPoints ) ; public void setFMarkMethodOccurrences ( boolean markMethodOccurrences ) ; public void setFMarkOccurrenceAnnotations ( boolean markOccurrenceAnnotations ) ; public void setFMarkTypeOccurrences ( boolean markTypeOccurrences ) ; public void setFStickyOccurrenceAnnotations ( boolean stickyOccurrenceAnnotations ) ; } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . search . ui . text . AbstractTextSearchViewPage ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; class OccurrencesSearchLabelProvider extends TextSearchLabelProvider { public OccurrencesSearchLabelProvider ( AbstractTextSearchViewPage page ) { super ( page ) ; } protected String doGetText ( Object element ) { RubyElementLine jel = ( RubyElementLine ) element ; return jel . getLineContents ( ) . replace ( '' , '' ) ; } public Image getImage ( Object element ) { if ( element instanceof OccurrencesGroupKey ) { OccurrencesGroupKey group = ( OccurrencesGroupKey ) element ; if ( group . isVariable ( ) ) { if ( group . isWriteAccess ( ) ) return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_SEARCH_WRITEACCESS ) ; else return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_SEARCH_READACCESS ) ; } } return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_SEARCH_OCCURRENCE ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . rubypeople . rdt . core . IRubyElement ; public class OccurrencesGroupKey extends RubyElementLine { private boolean fIsWriteAccess ; private boolean fIsVariable ; public OccurrencesGroupKey ( IRubyElement element , int line , String lineContents , boolean isWriteAccess , boolean isVariable ) { super ( element , line , lineContents ) ; fIsWriteAccess = isWriteAccess ; fIsVariable = isVariable ; } public boolean isVariable ( ) { return fIsVariable ; } public boolean isWriteAccess ( ) { return fIsWriteAccess ; } public void setWriteAccess ( boolean isWriteAccess ) { fIsWriteAccess = isWriteAccess ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . LabelProviderChangedEvent ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . search . ui . text . AbstractTextSearchResult ; import org . eclipse . search . ui . text . Match ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . ui . preferences . ScopedPreferenceStore ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . ui . ProblemsLabelDecorator ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . search . IMatchPresentation ; public abstract class SearchLabelProvider extends AppearanceAwareLabelProvider { public static final String PROPERTY_MATCH_COUNT = "" ; private static final String EMPHASIZE_POTENTIAL_MATCHES = "" ; private static final String POTENTIAL_MATCH_FG_COLOR = "" ; protected static final long DEFAULT_SEARCH_TEXTFLAGS = ( DEFAULT_TEXTFLAGS | RubyElementLabels . P_COMPRESSED ) ; protected static final int DEFAULT_SEARCH_IMAGEFLAGS = DEFAULT_IMAGEFLAGS ; private Color fPotentialMatchFgColor ; private Map fLabelProviderMap ; protected RubySearchResultPage fPage ; private ScopedPreferenceStore fSearchPreferences ; private IPropertyChangeListener fSearchPropertyListener ; public SearchLabelProvider ( RubySearchResultPage page ) { super ( DEFAULT_SEARCH_TEXTFLAGS , DEFAULT_SEARCH_IMAGEFLAGS ) ; addLabelDecorator ( new ProblemsLabelDecorator ( ) ) ; fPage = page ; fLabelProviderMap = new HashMap ( ) ; fSearchPreferences = new ScopedPreferenceStore ( new InstanceScope ( ) , NewSearchUI . PLUGIN_ID ) ; fSearchPropertyListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { doSearchPropertyChange ( event ) ; } } ; fSearchPreferences . addPropertyChangeListener ( fSearchPropertyListener ) ; } final void doSearchPropertyChange ( PropertyChangeEvent event ) { if ( fPotentialMatchFgColor == null ) return ; if ( POTENTIAL_MATCH_FG_COLOR . equals ( event . getProperty ( ) ) || EMPHASIZE_POTENTIAL_MATCHES . equals ( event . getProperty ( ) ) ) { fPotentialMatchFgColor . dispose ( ) ; fPotentialMatchFgColor = null ; LabelProviderChangedEvent lpEvent = new LabelProviderChangedEvent ( SearchLabelProvider . this , null ) ; fireLabelProviderChanged ( lpEvent ) ; } } public Color getForeground ( Object element ) { if ( arePotentialMatchesEmphasized ( ) ) { if ( getNumberOfPotentialMatches ( element ) > ) return getForegroundColor ( ) ; } return super . getForeground ( element ) ; } private Color getForegroundColor ( ) { if ( fPotentialMatchFgColor == null ) { fPotentialMatchFgColor = new Color ( RubyPlugin . getActiveWorkbenchShell ( ) . getDisplay ( ) , getPotentialMatchForegroundColor ( ) ) ; } return fPotentialMatchFgColor ; } protected final int getNumberOfPotentialMatches ( Object element ) { int res = ; AbstractTextSearchResult result = fPage . getInput ( ) ; if ( result != null ) { Match [ ] matches = result . getMatches ( element ) ; for ( int i = ; i < matches . length ; i ++ ) { if ( ( matches [ i ] ) instanceof RubyElementMatch ) { if ( ( ( RubyElementMatch ) matches [ i ] ) . getAccuracy ( ) == SearchMatch . A_INACCURATE ) res ++ ; } } } return res ; } protected final String getLabelWithCounts ( Object element , String elementName ) { int matchCount = fPage . getDisplayedMatchCount ( element ) ; int potentialCount = getNumberOfPotentialMatches ( element ) ; if ( matchCount < ) { if ( matchCount == && hasChildren ( element ) ) { if ( potentialCount > ) return Messages . format ( SearchMessages . SearchLabelProvider_potential_singular , elementName ) ; return Messages . format ( SearchMessages . SearchLabelProvider_exact_singular , elementName ) ; } if ( potentialCount > ) return Messages . format ( SearchMessages . SearchLabelProvider_potential_noCount , elementName ) ; return Messages . format ( SearchMessages . SearchLabelProvider_exact_noCount , elementName ) ; } else { int exactCount = matchCount - potentialCount ; if ( potentialCount > && exactCount > ) { String [ ] args = new String [ ] { elementName , String . valueOf ( matchCount ) , String . valueOf ( exactCount ) , String . valueOf ( potentialCount ) } ; return Messages . format ( SearchMessages . SearchLabelProvider_exact_and_potential_plural , args ) ; } else if ( exactCount == ) { String [ ] args = new String [ ] { elementName , String . valueOf ( matchCount ) } ; return Messages . format ( SearchMessages . SearchLabelProvider_potential_plural , args ) ; } String [ ] args = new String [ ] { elementName , String . valueOf ( matchCount ) } ; return Messages . format ( SearchMessages . SearchLabelProvider_exact_plural , args ) ; } } protected boolean hasChildren ( Object elem ) { return false ; } public void dispose ( ) { if ( fPotentialMatchFgColor != null ) { fPotentialMatchFgColor . dispose ( ) ; fPotentialMatchFgColor = null ; } fSearchPreferences . removePropertyChangeListener ( fSearchPropertyListener ) ; for ( Iterator labelProviders = fLabelProviderMap . values ( ) . iterator ( ) ; labelProviders . hasNext ( ) ; ) { ILabelProvider labelProvider = ( ILabelProvider ) labelProviders . next ( ) ; labelProvider . dispose ( ) ; } fSearchPreferences = null ; fSearchPropertyListener = null ; fLabelProviderMap . clear ( ) ; super . dispose ( ) ; } public void addListener ( ILabelProviderListener listener ) { super . addListener ( listener ) ; for ( Iterator labelProviders = fLabelProviderMap . values ( ) . iterator ( ) ; labelProviders . hasNext ( ) ; ) { ILabelProvider labelProvider = ( ILabelProvider ) labelProviders . next ( ) ; labelProvider . addListener ( listener ) ; } } public boolean isLabelProperty ( Object element , String property ) { if ( PROPERTY_MATCH_COUNT . equals ( property ) ) return true ; return getLabelProvider ( element ) . isLabelProperty ( element , property ) ; } public void removeListener ( ILabelProviderListener listener ) { super . removeListener ( listener ) ; for ( Iterator labelProviders = fLabelProviderMap . values ( ) . iterator ( ) ; labelProviders . hasNext ( ) ; ) { ILabelProvider labelProvider = ( ILabelProvider ) labelProviders . next ( ) ; labelProvider . removeListener ( listener ) ; } } protected String getParticipantText ( Object element ) { ILabelProvider labelProvider = getLabelProvider ( element ) ; if ( labelProvider != null ) return labelProvider . getText ( element ) ; return "" ; } protected Image getParticipantImage ( Object element ) { ILabelProvider lp = getLabelProvider ( element ) ; if ( lp == null ) return null ; return lp . getImage ( element ) ; } private ILabelProvider getLabelProvider ( Object element ) { IMatchPresentation participant = ( ( RubySearchResult ) fPage . getInput ( ) ) . getSearchParticpant ( element ) ; if ( participant == null ) return null ; ILabelProvider lp = ( ILabelProvider ) fLabelProviderMap . get ( participant ) ; if ( lp == null ) { lp = participant . createLabelProvider ( ) ; fLabelProviderMap . put ( participant , lp ) ; Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { lp . addListener ( ( ILabelProviderListener ) listeners [ i ] ) ; } } return lp ; } private boolean arePotentialMatchesEmphasized ( ) { return fSearchPreferences . getBoolean ( EMPHASIZE_POTENTIAL_MATCHES ) ; } private RGB getPotentialMatchForegroundColor ( ) { return PreferenceConverter . getColor ( fSearchPreferences , POTENTIAL_MATCH_FG_COLOR ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . search . ui . NewSearchUI ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; public abstract class FindOccurrencesEngine { private IOccurrencesFinder fFinder ; private static class FindOccurencesCUEngine extends FindOccurrencesEngine { private IRubyScript fScript ; public FindOccurencesCUEngine ( IRubyScript unit , IOccurrencesFinder finder ) { super ( finder ) ; fScript = unit ; } protected Node createAST ( ) { return RubyPlugin . getDefault ( ) . getASTProvider ( ) . getAST ( fScript , ASTProvider . WAIT_YES , null ) ; } protected IRubyElement getInput ( ) { return fScript ; } protected ISourceReference getSourceReference ( ) { return fScript ; } } protected FindOccurrencesEngine ( IOccurrencesFinder finder ) { fFinder = finder ; } public static FindOccurrencesEngine create ( IRubyElement root , IOccurrencesFinder finder ) { if ( root == null || finder == null ) return null ; IRubyScript unit = ( IRubyScript ) root . getAncestor ( IRubyElement . SCRIPT ) ; if ( unit != null ) return new FindOccurencesCUEngine ( unit , finder ) ; return null ; } protected abstract Node createAST ( ) ; protected abstract IRubyElement getInput ( ) ; protected abstract ISourceReference getSourceReference ( ) ; protected IOccurrencesFinder getOccurrencesFinder ( ) { return fFinder ; } public String run ( int offset , int length ) throws RubyModelException { ISourceReference sr = getSourceReference ( ) ; if ( sr . getSourceRange ( ) == null ) { return SearchMessages . FindOccurrencesEngine_noSource_text ; } final Node root = createAST ( ) ; if ( root == null ) { return SearchMessages . FindOccurrencesEngine_cannotParse_text ; } String message = fFinder . initialize ( root , offset , length ) ; if ( message != null ) return message ; fFinder . setFMarkConstantOccurrences ( true ) ; fFinder . setFMarkFieldOccurrences ( true ) ; fFinder . setFMarkLocalVariableOccurrences ( true ) ; fFinder . setFMarkTypeOccurrences ( true ) ; fFinder . setFMarkMethodOccurrences ( true ) ; final IDocument document = new Document ( getSourceReference ( ) . getSource ( ) ) ; performNewSearch ( fFinder , document , getInput ( ) ) ; return null ; } private void performNewSearch ( IOccurrencesFinder finder , IDocument document , IRubyElement element ) { NewSearchUI . runQueryInBackground ( new OccurrencesSearchQuery ( finder , document , element ) ) ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; public class LRUWorkingSetsList { private final ArrayList fLRUList ; private final int fSize ; private final WorkingSetsComparator fComparator = new WorkingSetsComparator ( ) ; public LRUWorkingSetsList ( int size ) { fSize = size ; fLRUList = new ArrayList ( size ) ; } public void add ( IWorkingSet [ ] workingSets ) { removeDeletedWorkingSets ( ) ; IWorkingSet [ ] existingWorkingSets = find ( fLRUList , workingSets ) ; if ( existingWorkingSets != null ) fLRUList . remove ( existingWorkingSets ) ; else if ( fLRUList . size ( ) == fSize ) fLRUList . remove ( fSize - ) ; fLRUList . add ( , workingSets ) ; } public Iterator iterator ( ) { removeDeletedWorkingSets ( ) ; return fLRUList . iterator ( ) ; } public Iterator sortedIterator ( ) { removeDeletedWorkingSets ( ) ; ArrayList sortedList = new ArrayList ( fLRUList ) ; Collections . sort ( sortedList , fComparator ) ; return sortedList . iterator ( ) ; } private void removeDeletedWorkingSets ( ) { Iterator iter = new ArrayList ( fLRUList ) . iterator ( ) ; while ( iter . hasNext ( ) ) { IWorkingSet [ ] workingSets = ( IWorkingSet [ ] ) iter . next ( ) ; for ( int i = ; i < workingSets . length ; i ++ ) { if ( PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . getWorkingSet ( workingSets [ i ] . getName ( ) ) == null ) { fLRUList . remove ( workingSets ) ; break ; } } } } private IWorkingSet [ ] find ( ArrayList list , IWorkingSet [ ] workingSets ) { Set workingSetList = new HashSet ( Arrays . asList ( workingSets ) ) ; Iterator iter = list . iterator ( ) ; while ( iter . hasNext ( ) ) { IWorkingSet [ ] lruWorkingSets = ( IWorkingSet [ ] ) iter . next ( ) ; Set lruWorkingSetList = new HashSet ( Arrays . asList ( lruWorkingSets ) ) ; if ( lruWorkingSetList . equals ( workingSetList ) ) return lruWorkingSets ; } return null ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class SearchParticipantsExtensionPoint { private Set fActiveParticipants = null ; private static SearchParticipantsExtensionPoint fgInstance ; public boolean hasAnyParticipants ( ) { return Platform . getExtensionRegistry ( ) . getConfigurationElementsFor ( RubySearchPage . PARTICIPANT_EXTENSION_POINT ) . length > ; } private synchronized Set getAllParticipants ( ) { if ( fActiveParticipants != null ) return fActiveParticipants ; IConfigurationElement [ ] allParticipants = Platform . getExtensionRegistry ( ) . getConfigurationElementsFor ( RubySearchPage . PARTICIPANT_EXTENSION_POINT ) ; fActiveParticipants = new HashSet ( allParticipants . length ) ; for ( int i = ; i < allParticipants . length ; i ++ ) { SearchParticipantDescriptor descriptor = new SearchParticipantDescriptor ( allParticipants [ i ] ) ; IStatus status = descriptor . checkSyntax ( ) ; if ( status . isOK ( ) ) { fActiveParticipants . add ( descriptor ) ; } else { RubyPlugin . log ( status ) ; } } return fActiveParticipants ; } private void collectParticipants ( Set participants , IProject [ ] projects ) { Iterator activeParticipants = getAllParticipants ( ) . iterator ( ) ; Set seenParticipants = new HashSet ( ) ; while ( activeParticipants . hasNext ( ) ) { SearchParticipantDescriptor participant = ( SearchParticipantDescriptor ) activeParticipants . next ( ) ; if ( participant . isEnabled ( ) ) { String id = participant . getID ( ) ; for ( int i = ; i < projects . length ; i ++ ) { if ( seenParticipants . contains ( id ) ) continue ; try { if ( projects [ i ] . hasNature ( participant . getNature ( ) ) ) { participants . add ( new SearchParticipantRecord ( participant , participant . create ( ) ) ) ; seenParticipants . add ( id ) ; } } catch ( CoreException e ) { RubyPlugin . log ( e . getStatus ( ) ) ; participant . disable ( ) ; } } } } } public SearchParticipantRecord [ ] getSearchParticipants ( IProject [ ] concernedProjects ) throws CoreException { Set participantSet = new HashSet ( ) ; collectParticipants ( participantSet , concernedProjects ) ; SearchParticipantRecord [ ] participants = new SearchParticipantRecord [ participantSet . size ( ) ] ; return ( SearchParticipantRecord [ ] ) participantSet . toArray ( participants ) ; } public static SearchParticipantsExtensionPoint getInstance ( ) { if ( fgInstance == null ) fgInstance = new SearchParticipantsExtensionPoint ( ) ; return fgInstance ; } public static void debugSetInstance ( SearchParticipantsExtensionPoint instance ) { fgInstance = instance ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . FieldReferenceMatch ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchRequestor ; public class NewSearchResultCollector extends SearchRequestor { private RubySearchResult fSearch ; private boolean fIgnorePotentials ; public NewSearchResultCollector ( RubySearchResult search , boolean ignorePotentials ) { super ( ) ; fSearch = search ; fIgnorePotentials = ignorePotentials ; } public void acceptSearchMatch ( SearchMatch match ) throws CoreException { IRubyElement enclosingElement = ( IRubyElement ) match . getElement ( ) ; if ( enclosingElement != null ) { if ( fIgnorePotentials && ( match . getAccuracy ( ) == SearchMatch . A_INACCURATE ) ) return ; boolean isWriteAccess = false ; boolean isReadAccess = false ; if ( match instanceof FieldReferenceMatch ) { FieldReferenceMatch fieldRef = ( ( FieldReferenceMatch ) match ) ; isWriteAccess = fieldRef . isWriteAccess ( ) ; isReadAccess = fieldRef . isReadAccess ( ) ; } fSearch . addMatch ( new RubyElementMatch ( enclosingElement , match . getRule ( ) , match . getOffset ( ) , match . getLength ( ) , match . getAccuracy ( ) , isReadAccess , isWriteAccess , match . isInsideDocComment ( ) ) ) ; } } public void beginReporting ( ) { } public void endReporting ( ) { } public void enterParticipant ( SearchParticipant participant ) { } public void exitParticipant ( SearchParticipant participant ) { } } package org . rubypeople . rdt . internal . ui . search ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . search . ui . ISearchQuery ; import org . eclipse . search . ui . ISearchResult ; import org . eclipse . search . ui . SearchResultEvent ; import org . eclipse . search . ui . text . AbstractTextSearchResult ; import org . eclipse . search . ui . text . IEditorMatchAdapter ; import org . eclipse . search . ui . text . IFileMatchAdapter ; import org . eclipse . search . ui . text . Match ; import org . eclipse . search . ui . text . MatchEvent ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . search . IMatchPresentation ; public class RubySearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter , IFileMatchAdapter { public static class MatchFilterEvent extends SearchResultEvent { private static final long serialVersionUID = ; private final MatchFilter [ ] fActivatedFilters ; public MatchFilterEvent ( ISearchResult searchResult , MatchFilter [ ] activatedFilters ) { super ( searchResult ) ; fActivatedFilters = activatedFilters ; } public MatchFilter [ ] getActivatedFilters ( ) { return fActivatedFilters ; } } private RubySearchQuery fQuery ; private Map fElementsToParticipants ; private static final Match [ ] NO_MATCHES = new Match [ ] ; private MatchFilter [ ] fActivatedMatchFilters ; public RubySearchResult ( RubySearchQuery query ) { fQuery = query ; fElementsToParticipants = new HashMap ( ) ; fActivatedMatchFilters = MatchFilter . getLastUsedFilters ( ) ; } public ImageDescriptor getImageDescriptor ( ) { return fQuery . getImageDescriptor ( ) ; } public String getLabel ( ) { return fQuery . getResultLabel ( getMatchCount ( ) ) ; } public String getTooltip ( ) { return getLabel ( ) ; } public void setActivatedFilters ( MatchFilter [ ] matchFilters ) { fActivatedMatchFilters = matchFilters ; MatchFilter . setLastUsedFilters ( matchFilters ) ; updateFilterStateForAllMarkers ( ) ; fireChange ( new MatchFilterEvent ( this , matchFilters ) ) ; } public MatchFilter [ ] getActivatedMatchFilters ( ) { return fActivatedMatchFilters ; } public boolean hasMatchFilterActivated ( MatchFilter filter ) { String id = filter . getID ( ) ; for ( int i = ; i < fActivatedMatchFilters . length ; i ++ ) { if ( fActivatedMatchFilters [ i ] . getID ( ) . equals ( id ) ) { return true ; } } return false ; } protected void fireChange ( SearchResultEvent e ) { if ( e instanceof MatchEvent && ( ( MatchEvent ) e ) . getKind ( ) == MatchEvent . ADDED ) { updateFilterState ( ( ( MatchEvent ) e ) . getMatches ( ) ) ; } super . fireChange ( e ) ; } private void updateFilterStateForAllMarkers ( ) { Object [ ] elements = getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { updateFilterState ( getMatches ( elements [ i ] ) ) ; } } private void updateFilterState ( Match [ ] matches ) { for ( int i = ; i < matches . length ; i ++ ) { Object match = matches [ i ] ; if ( match instanceof RubyElementMatch ) { updateFilterState ( ( RubyElementMatch ) match ) ; } } } private void updateFilterState ( RubyElementMatch match ) { for ( int i = ; i < fActivatedMatchFilters . length ; i ++ ) { if ( fActivatedMatchFilters [ i ] . filters ( match ) ) { match . setFiltered ( true ) ; return ; } } match . setFiltered ( false ) ; } public Match [ ] computeContainedMatches ( AbstractTextSearchResult result , IEditorPart editor ) { return computeContainedMatches ( editor . getEditorInput ( ) ) ; } public Match [ ] computeContainedMatches ( AbstractTextSearchResult result , IFile file ) { return computeContainedMatches ( file ) ; } private Match [ ] computeContainedMatches ( IAdaptable adaptable ) { IRubyElement javaElement = ( IRubyElement ) adaptable . getAdapter ( IRubyElement . class ) ; Set matches = new HashSet ( ) ; if ( javaElement != null ) { collectMatches ( matches , javaElement ) ; } IFile file = ( IFile ) adaptable . getAdapter ( IFile . class ) ; if ( file != null ) { collectMatches ( matches , file ) ; } if ( ! matches . isEmpty ( ) ) { return ( Match [ ] ) matches . toArray ( new Match [ matches . size ( ) ] ) ; } return NO_MATCHES ; } private void collectMatches ( Set matches , IFile element ) { Match [ ] m = getMatches ( element ) ; if ( m . length != ) { for ( int i = ; i < m . length ; i ++ ) { matches . add ( m [ i ] ) ; } } } private void collectMatches ( Set matches , IRubyElement element ) { Match [ ] m = getMatches ( element ) ; if ( m . length != ) { for ( int i = ; i < m . length ; i ++ ) { matches . add ( m [ i ] ) ; } } if ( element instanceof IParent ) { IParent parent = ( IParent ) element ; try { IRubyElement [ ] children = parent . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { collectMatches ( matches , children [ i ] ) ; } } catch ( RubyModelException e ) { } } } public IFile getFile ( Object element ) { if ( element instanceof IRubyElement ) { IRubyElement javaElement = ( IRubyElement ) element ; IRubyScript cu = ( IRubyScript ) javaElement . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) { return ( IFile ) cu . getResource ( ) ; } return null ; } if ( element instanceof IFile ) return ( IFile ) element ; return null ; } public boolean isShownInEditor ( Match match , IEditorPart editor ) { Object element = match . getElement ( ) ; if ( element instanceof IRubyElement ) { element = ( ( IRubyElement ) element ) . getOpenable ( ) ; return element != null && element . equals ( editor . getEditorInput ( ) . getAdapter ( IRubyElement . class ) ) ; } else if ( element instanceof IFile ) { return element . equals ( editor . getEditorInput ( ) . getAdapter ( IFile . class ) ) ; } return false ; } public ISearchQuery getQuery ( ) { return fQuery ; } synchronized IMatchPresentation getSearchParticpant ( Object element ) { return ( IMatchPresentation ) fElementsToParticipants . get ( element ) ; } boolean addMatch ( Match match , IMatchPresentation participant ) { Object element = match . getElement ( ) ; if ( fElementsToParticipants . get ( element ) != null ) { RubyPlugin . log ( new Status ( IStatus . WARNING , RubyPlugin . getPluginId ( ) , , "" , null ) ) ; return false ; } fElementsToParticipants . put ( element , participant ) ; addMatch ( match ) ; return true ; } public void removeAll ( ) { synchronized ( this ) { fElementsToParticipants . clear ( ) ; } super . removeAll ( ) ; } public void removeMatch ( Match match ) { synchronized ( this ) { if ( getMatchCount ( match . getElement ( ) ) == ) fElementsToParticipants . remove ( match . getElement ( ) ) ; } super . removeMatch ( match ) ; } public IFileMatchAdapter getFileMatchAdapter ( ) { return this ; } public IEditorMatchAdapter getEditorMatchAdapter ( ) { return this ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . search . ui . text . AbstractTextSearchViewPage ; import org . rubypeople . rdt . internal . corext . util . Messages ; public abstract class TextSearchLabelProvider extends LabelProvider { private AbstractTextSearchViewPage fPage ; private String fMatchCountFormat ; public TextSearchLabelProvider ( AbstractTextSearchViewPage page ) { fPage = page ; fMatchCountFormat = SearchMessages . TextSearchLabelProvider_matchCountFormat ; } public final String getText ( Object element ) { int matchCount = fPage . getInput ( ) . getMatchCount ( element ) ; String text = doGetText ( element ) ; if ( matchCount < ) return text ; else { return Messages . format ( fMatchCountFormat , new Object [ ] { text , new Integer ( matchCount ) } ) ; } } protected abstract String doGetText ( Object element ) ; } package org . rubypeople . rdt . internal . ui . search ; import java . util . StringTokenizer ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . PatternQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; abstract class MatchFilter { private static final String SETTINGS_LAST_USED_FILTERS = "" ; public static MatchFilter [ ] getLastUsedFilters ( ) { String string = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( SETTINGS_LAST_USED_FILTERS ) ; if ( string != null && string . length ( ) > ) { return decodeFiltersString ( string ) ; } return getDefaultFilters ( ) ; } public static void setLastUsedFilters ( MatchFilter [ ] filters ) { String encoded = encodeFilters ( filters ) ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( SETTINGS_LAST_USED_FILTERS , encoded ) ; } public static MatchFilter [ ] getDefaultFilters ( ) { return new MatchFilter [ ] { IMPORT_FILTER } ; } private static String encodeFilters ( MatchFilter [ ] enabledFilters ) { StringBuffer buf = new StringBuffer ( ) ; buf . append ( enabledFilters . length ) ; for ( int i = ; i < enabledFilters . length ; i ++ ) { buf . append ( '' ) ; buf . append ( enabledFilters [ i ] . getID ( ) ) ; } return buf . toString ( ) ; } private static MatchFilter [ ] decodeFiltersString ( String encodedString ) { StringTokenizer tokenizer = new StringTokenizer ( encodedString , String . valueOf ( '' ) ) ; MatchFilter [ ] res ; try { int count = Integer . valueOf ( tokenizer . nextToken ( ) ) . intValue ( ) ; res = new MatchFilter [ count ] ; for ( int i = ; i < count ; i ++ ) { res [ i ] = findMatchFilter ( tokenizer . nextToken ( ) ) ; } } catch ( NumberFormatException e ) { res = getDefaultFilters ( ) ; } return res ; } public abstract boolean isApplicable ( RubySearchQuery query ) ; public abstract boolean filters ( RubyElementMatch match ) ; public abstract String getName ( ) ; public abstract String getActionLabel ( ) ; public abstract String getDescription ( ) ; public abstract String getID ( ) ; private static final MatchFilter POTENTIAL_FILTER = new PotentialFilter ( ) ; private static final MatchFilter IMPORT_FILTER = new ImportFilter ( ) ; private static final MatchFilter JAVADOC_FILTER = new RubydocFilter ( ) ; private static final MatchFilter READ_FILTER = new ReadFilter ( ) ; private static final MatchFilter WRITE_FILTER = new WriteFilter ( ) ; private static final MatchFilter [ ] ALL_FILTERS = new MatchFilter [ ] { POTENTIAL_FILTER , IMPORT_FILTER , JAVADOC_FILTER , READ_FILTER , WRITE_FILTER } ; public static MatchFilter [ ] allFilters ( ) { return ALL_FILTERS ; } private static MatchFilter findMatchFilter ( String id ) { for ( int i = ; i < ALL_FILTERS . length ; i ++ ) { if ( ALL_FILTERS [ i ] . getID ( ) . equals ( id ) ) return ALL_FILTERS [ i ] ; } return IMPORT_FILTER ; } } class PotentialFilter extends MatchFilter { public boolean filters ( RubyElementMatch match ) { return match . getAccuracy ( ) == SearchMatch . A_INACCURATE ; } public String getName ( ) { return SearchMessages . MatchFilter_PotentialFilter_name ; } public String getActionLabel ( ) { return SearchMessages . MatchFilter_PotentialFilter_actionLabel ; } public String getDescription ( ) { return SearchMessages . MatchFilter_PotentialFilter_description ; } public boolean isApplicable ( RubySearchQuery query ) { return true ; } public String getID ( ) { return "" ; } } class ImportFilter extends MatchFilter { public boolean filters ( RubyElementMatch match ) { return match . getElement ( ) instanceof IImportDeclaration ; } public String getName ( ) { return SearchMessages . MatchFilter_ImportFilter_name ; } public String getActionLabel ( ) { return SearchMessages . MatchFilter_ImportFilter_actionLabel ; } public String getDescription ( ) { return SearchMessages . MatchFilter_ImportFilter_description ; } public boolean isApplicable ( RubySearchQuery query ) { QuerySpecification spec = query . getSpecification ( ) ; if ( spec instanceof ElementQuerySpecification ) { ElementQuerySpecification elementSpec = ( ElementQuerySpecification ) spec ; return elementSpec . getElement ( ) instanceof IType ; } else if ( spec instanceof PatternQuerySpecification ) { PatternQuerySpecification patternSpec = ( PatternQuerySpecification ) spec ; return patternSpec . getSearchFor ( ) == IRubySearchConstants . TYPE ; } return false ; } public String getID ( ) { return "" ; } } abstract class FieldFilter extends MatchFilter { public boolean isApplicable ( RubySearchQuery query ) { QuerySpecification spec = query . getSpecification ( ) ; if ( spec instanceof ElementQuerySpecification ) { ElementQuerySpecification elementSpec = ( ElementQuerySpecification ) spec ; return elementSpec . getElement ( ) instanceof IField ; } else if ( spec instanceof PatternQuerySpecification ) { PatternQuerySpecification patternSpec = ( PatternQuerySpecification ) spec ; return patternSpec . getSearchFor ( ) == IRubySearchConstants . FIELD ; } return false ; } } class WriteFilter extends FieldFilter { public boolean filters ( RubyElementMatch match ) { return match . isWriteAccess ( ) && ! match . isReadAccess ( ) ; } public String getName ( ) { return SearchMessages . MatchFilter_WriteFilter_name ; } public String getActionLabel ( ) { return SearchMessages . MatchFilter_WriteFilter_actionLabel ; } public String getDescription ( ) { return SearchMessages . MatchFilter_WriteFilter_description ; } public String getID ( ) { return "" ; } } class ReadFilter extends FieldFilter { public boolean filters ( RubyElementMatch match ) { return match . isReadAccess ( ) && ! match . isWriteAccess ( ) ; } public String getName ( ) { return SearchMessages . MatchFilter_ReadFilter_name ; } public String getActionLabel ( ) { return SearchMessages . MatchFilter_ReadFilter_actionLabel ; } public String getDescription ( ) { return SearchMessages . MatchFilter_ReadFilter_description ; } public String getID ( ) { return "" ; } } class RubydocFilter extends MatchFilter { public boolean filters ( RubyElementMatch match ) { return match . isRubydoc ( ) ; } public String getName ( ) { return SearchMessages . MatchFilter_RubydocFilter_name ; } public String getActionLabel ( ) { return SearchMessages . MatchFilter_RubydocFilter_actionLabel ; } public String getDescription ( ) { return SearchMessages . MatchFilter_RubydocFilter_description ; } public boolean isApplicable ( RubySearchQuery query ) { return true ; } public String getID ( ) { return "" ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . search . IQueryParticipant ; public class SearchParticipantDescriptor { private static final String CLASS = "" ; private static final String NATURE = "" ; private static final String ID = "" ; private IConfigurationElement fConfigurationElement ; private boolean fEnabled ; protected SearchParticipantDescriptor ( IConfigurationElement configElement ) { fConfigurationElement = configElement ; fEnabled = true ; } protected IStatus checkSyntax ( ) { if ( fConfigurationElement . getAttribute ( ID ) == null ) { String format = SearchMessages . SearchParticipant_error_noID ; String message = Messages . format ( format , new String [ ] { fConfigurationElement . getDeclaringExtension ( ) . getUniqueIdentifier ( ) } ) ; return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , message , null ) ; } if ( fConfigurationElement . getAttribute ( NATURE ) == null ) { String format = SearchMessages . SearchParticipant_error_noNature ; String message = Messages . format ( format , new String [ ] { fConfigurationElement . getAttribute ( ID ) } ) ; return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , message , null ) ; } if ( fConfigurationElement . getAttribute ( CLASS ) == null ) { String format = SearchMessages . SearchParticipant_error_noClass ; String message = Messages . format ( format , new String [ ] { fConfigurationElement . getAttribute ( ID ) } ) ; return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , message , null ) ; } return Status . OK_STATUS ; } public String getID ( ) { return fConfigurationElement . getAttribute ( ID ) ; } public void disable ( ) { fEnabled = false ; } public boolean isEnabled ( ) { return fEnabled ; } protected IQueryParticipant create ( ) throws CoreException { try { return ( IQueryParticipant ) fConfigurationElement . createExecutableExtension ( CLASS ) ; } catch ( ClassCastException e ) { throw new CoreException ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , SearchMessages . SearchParticipant_error_classCast , e ) ) ; } } protected String getNature ( ) { return fConfigurationElement . getAttribute ( NATURE ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . core . resources . IFile ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . search . ui . text . Match ; import org . eclipse . ui . IEditorDescriptor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IEditorReference ; import org . eclipse . ui . IEditorRegistry ; import org . eclipse . ui . IPartListener ; import org . eclipse . ui . IPartService ; import org . eclipse . ui . IReusableEditor ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . part . FileEditorInput ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; public class RubySearchEditorOpener { private static class ReusedEditorWatcher implements IPartListener { private IEditorPart fReusedEditor ; private IPartService fPartService ; public ReusedEditorWatcher ( ) { fReusedEditor = null ; fPartService = null ; } public IEditorPart getReusedEditor ( ) { return fReusedEditor ; } public void initialize ( IEditorPart editor ) { if ( fReusedEditor != null ) { fPartService . removePartListener ( this ) ; } fReusedEditor = editor ; if ( editor != null ) { fPartService = editor . getSite ( ) . getWorkbenchWindow ( ) . getPartService ( ) ; fPartService . addPartListener ( this ) ; } else { fPartService = null ; } } public void partOpened ( IWorkbenchPart part ) { } public void partDeactivated ( IWorkbenchPart part ) { } public void partClosed ( IWorkbenchPart part ) { if ( part == fReusedEditor ) { initialize ( null ) ; } } public void partActivated ( IWorkbenchPart part ) { } public void partBroughtToTop ( IWorkbenchPart part ) { } } private ReusedEditorWatcher fReusedEditorWatcher ; public IEditorPart openElement ( Object element ) throws PartInitException , RubyModelException { IWorkbenchPage wbPage = RubyPlugin . getActivePage ( ) ; if ( NewSearchUI . reuseEditor ( ) ) return showWithReuse ( element , wbPage ) ; else return showWithoutReuse ( element , wbPage ) ; } public IEditorPart openMatch ( Match match ) throws PartInitException , RubyModelException { Object element = getElementToOpen ( match ) ; return openElement ( element ) ; } protected Object getElementToOpen ( Match match ) { return match . getElement ( ) ; } private IEditorPart showWithoutReuse ( Object element , IWorkbenchPage wbPage ) throws PartInitException , RubyModelException { return EditorUtility . openInEditor ( element , false ) ; } private IEditorPart showWithReuse ( Object element , IWorkbenchPage wbPage ) throws RubyModelException , PartInitException { IFile file = getFile ( element ) ; if ( file != null ) { String editorID = getEditorID ( file ) ; return showInEditor ( wbPage , new FileEditorInput ( file ) , editorID ) ; } return showWithoutReuse ( element , wbPage ) ; } private IFile getFile ( Object element ) throws RubyModelException { if ( element instanceof IFile ) return ( IFile ) element ; if ( element instanceof IRubyElement ) { IRubyElement jElement = ( IRubyElement ) element ; IRubyScript cu = ( IRubyScript ) jElement . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) { return ( IFile ) cu . getCorrespondingResource ( ) ; } } return null ; } private String getEditorID ( IFile file ) throws PartInitException { IEditorDescriptor desc = IDE . getEditorDescriptor ( file ) ; if ( desc == null ) return RubyPlugin . getDefault ( ) . getWorkbench ( ) . getEditorRegistry ( ) . findEditor ( IEditorRegistry . SYSTEM_EXTERNAL_EDITOR_ID ) . getId ( ) ; else return desc . getId ( ) ; } private boolean isPinned ( IEditorPart editor ) { if ( editor == null ) return false ; IEditorReference [ ] editorRefs = editor . getEditorSite ( ) . getPage ( ) . getEditorReferences ( ) ; int i = ; while ( i < editorRefs . length ) { if ( editor . equals ( editorRefs [ i ] . getEditor ( false ) ) ) return editorRefs [ i ] . isPinned ( ) ; i ++ ; } return false ; } private IEditorPart showInEditor ( IWorkbenchPage page , IEditorInput input , String editorId ) { IEditorPart editor = page . findEditor ( input ) ; if ( editor != null ) page . bringToTop ( editor ) ; else { IEditorPart reusedEditor = getReusedEditor ( ) ; boolean isOpen = false ; if ( reusedEditor != null ) { IEditorReference [ ] parts = page . getEditorReferences ( ) ; int i = ; while ( ! isOpen && i < parts . length ) isOpen = reusedEditor == parts [ i ++ ] . getEditor ( false ) ; } boolean canBeReused = isOpen && ! reusedEditor . isDirty ( ) && ! isPinned ( reusedEditor ) ; boolean showsSameInputType = reusedEditor != null && reusedEditor . getSite ( ) . getId ( ) . equals ( editorId ) ; if ( canBeReused && ! showsSameInputType ) { page . closeEditor ( reusedEditor , false ) ; setReusedEditor ( null ) ; } if ( canBeReused && showsSameInputType ) { ( ( IReusableEditor ) reusedEditor ) . setInput ( input ) ; page . bringToTop ( reusedEditor ) ; editor = reusedEditor ; } else { try { editor = page . openEditor ( input , editorId , false ) ; if ( editor instanceof IReusableEditor ) setReusedEditor ( editor ) ; else setReusedEditor ( null ) ; } catch ( PartInitException ex ) { MessageDialog . openError ( RubyPlugin . getActiveWorkbenchShell ( ) , SearchMessages . Search_Error_openEditor_title , SearchMessages . Search_Error_openEditor_message ) ; return null ; } } } return editor ; } private IEditorPart getReusedEditor ( ) { if ( fReusedEditorWatcher != null ) return fReusedEditorWatcher . getReusedEditor ( ) ; return null ; } private void setReusedEditor ( IEditorPart editor ) { if ( fReusedEditorWatcher == null ) { fReusedEditorWatcher = new ReusedEditorWatcher ( ) ; } fReusedEditorWatcher . initialize ( editor ) ; } } package org . rubypeople . rdt . internal . ui . search ; import com . ibm . icu . text . Collator ; import java . util . Comparator ; import org . eclipse . ui . IWorkingSet ; public class WorkingSetComparator implements Comparator { private Collator fCollator = Collator . getInstance ( ) ; public int compare ( Object o1 , Object o2 ) { String name1 = null ; String name2 = null ; if ( o1 instanceof IWorkingSet ) name1 = ( ( IWorkingSet ) o1 ) . getLabel ( ) ; if ( o2 instanceof IWorkingSet ) name2 = ( ( IWorkingSet ) o2 ) . getLabel ( ) ; return fCollator . compare ( name1 , name2 ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . rubypeople . rdt . ui . search . IQueryParticipant ; public class SearchParticipantRecord { private SearchParticipantDescriptor fDescriptor ; private IQueryParticipant fParticipant ; public SearchParticipantRecord ( SearchParticipantDescriptor descriptor , IQueryParticipant participant ) { super ( ) ; fDescriptor = descriptor ; fParticipant = participant ; } public SearchParticipantDescriptor getDescriptor ( ) { return fDescriptor ; } public IQueryParticipant getParticipant ( ) { return fParticipant ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Position ; import org . eclipse . search . ui . text . Match ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . BlockArgNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . Colon3Node ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . ReturnNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . ti . util . FirstPrecursorNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; import org . rubypeople . rdt . internal . ti . util . ScopedNodeLocator ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class OccurrencesFinder extends AbstractOccurencesFinder { private Node root ; private Node fSelectedNode ; private List < Node > fUsages = new ArrayList < Node > ( ) ; private List < Node > fWriteUsages = new ArrayList < Node > ( ) ; public String getJobLabel ( ) { return SearchMessages . OccurrencesFinder_searchfor ; } public String getUnformattedPluralLabel ( ) { return SearchMessages . OccurrencesFinder_label_plural ; } public String getUnformattedSingularLabel ( ) { return SearchMessages . OccurrencesFinder_label_singular ; } public void collectOccurrenceMatches ( IRubyElement element , IDocument document , Collection resultingMatches ) { HashMap lineToGroup = new HashMap ( ) ; for ( Iterator iter = fUsages . iterator ( ) ; iter . hasNext ( ) ; ) { Node node = ( Node ) iter . next ( ) ; ISourcePosition position ; try { position = getPositionOfName ( node ) ; } catch ( RuntimeException e ) { RubyPlugin . log ( e ) ; continue ; } if ( position == null ) continue ; int startPosition = position . getStartOffset ( ) ; if ( startPosition < ) continue ; int length = position . getEndOffset ( ) - position . getStartOffset ( ) ; try { boolean isWriteAccess = fWriteUsages . contains ( node ) ; int line = document . getLineOfOffset ( startPosition ) ; Integer lineInteger = new Integer ( line ) ; OccurrencesGroupKey groupKey = ( OccurrencesGroupKey ) lineToGroup . get ( lineInteger ) ; if ( groupKey == null ) { IRegion region = document . getLineInformation ( line ) ; String lineContents = document . get ( region . getOffset ( ) , region . getLength ( ) ) . trim ( ) ; groupKey = new OccurrencesGroupKey ( element , line , lineContents , isWriteAccess , isVariable ( fSelectedNode ) ) ; lineToGroup . put ( lineInteger , groupKey ) ; } else if ( isWriteAccess ) { groupKey . setWriteAccess ( true ) ; } Match match = new Match ( groupKey , startPosition , length ) ; resultingMatches . add ( match ) ; } catch ( BadLocationException e ) { } } } private boolean isVariable ( Node node ) { return ASTUtil . isVariable ( node ) ; } public String initialize ( Node root , int offset , int length ) { if ( root == null ) { return null ; } this . root = root ; this . fSelectedNode = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( root , offset ) ; if ( fSelectedNode == null ) { return SearchMessages . OccurrencesFinder_no_element ; } fUsages . clear ( ) ; fWriteUsages . clear ( ) ; return null ; } public List < Position > perform ( ) { if ( root == null ) return new LinkedList < Position > ( ) ; if ( fSelectedNode == null ) return new LinkedList < Position > ( ) ; if ( fMarkLocalVariableOccurrences && isLocalVarRef ( fSelectedNode ) ) { pushLocalVarRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkLocalVariableOccurrences && isDVarRef ( fSelectedNode ) ) { pushDVarRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkLocalVariableOccurrences && isInstanceVarRef ( fSelectedNode ) ) { pushInstVarRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkLocalVariableOccurrences && isClassVarRef ( fSelectedNode ) ) { pushClassVarRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkLocalVariableOccurrences && isGlobalVarRef ( fSelectedNode ) ) { pushGlobalVarRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkConstantOccurrences && fSelectedNode instanceof SymbolNode ) { pushSymbolRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkMethodOccurrences && ( isMethodRefNode ( fSelectedNode ) || isMethodDefNode ( fSelectedNode ) ) ) { pushMethodRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkConstantOccurrences && isConstRef ( fSelectedNode ) ) { pushConstRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkTypeOccurrences && isTypeRef ( fSelectedNode ) ) { pushTypeRefs ( root , fSelectedNode , fUsages ) ; } if ( fMarkMethodExitPoints ) { pushReturns ( root , fSelectedNode , fUsages ) ; } List < Position > positions = new LinkedList < Position > ( ) ; for ( Node node : fUsages ) { try { ISourcePosition occurrence = getPositionOfName ( node ) ; if ( occurrence == null ) continue ; Position position = new Position ( occurrence . getStartOffset ( ) , occurrence . getEndOffset ( ) - occurrence . getStartOffset ( ) ) ; positions . add ( position ) ; } catch ( RuntimeException re ) { RubyPlugin . log ( re ) ; } } positions = new LinkedList < Position > ( new HashSet < Position > ( positions ) ) ; return positions ; } private boolean isMethodRefNode ( Node selectedNode ) { return selectedNode instanceof VCallNode || selectedNode instanceof FCallNode || selectedNode instanceof CallNode ; } private boolean isLocalVarRef ( Node node ) { return ( ( node instanceof LocalAsgnNode ) || ( node instanceof ArgumentNode ) || ( node instanceof LocalVarNode ) ) ; } private boolean isDVarRef ( Node node ) { return ( ( node instanceof DVarNode ) || ( node instanceof DAsgnNode ) ) ; } private boolean isInstanceVarRef ( Node node ) { return ( ( node instanceof InstAsgnNode ) || ( node instanceof InstVarNode ) ) ; } private boolean isClassVarRef ( Node node ) { return ( ( node instanceof ClassVarNode ) || ( node instanceof ClassVarAsgnNode ) || ( node instanceof ClassVarDeclNode ) ) ; } private boolean isGlobalVarRef ( Node node ) { return ( ( node instanceof GlobalAsgnNode ) || ( node instanceof GlobalVarNode ) ) ; } private boolean isConstRef ( Node node ) { return ( node instanceof ConstNode ) || ( node instanceof ConstDeclNode ) ; } private boolean isTypeRef ( Node node ) { return ( ( node instanceof ClassNode ) || ( node instanceof ModuleNode ) || ( node instanceof ConstNode ) ) ; } private void pushLocalVarRefs ( Node root , Node orig , List < Node > occurrences ) { Node searchSpace = FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( root , orig . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( ( node instanceof DefnNode ) || ( node instanceof DefsNode ) ) ; } } ) ; if ( searchSpace == null ) { searchSpace = root ; } final Node finalSearchSpace = searchSpace ; final String origName = ASTUtil . getNameReflectively ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { String name = ASTUtil . getNameReflectively ( node ) ; return ( name != null && name . equals ( origName ) ) ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; if ( searchResult instanceof LocalAsgnNode ) fWriteUsages . add ( searchResult ) ; } } private void pushDVarRefs ( Node root , Node orig , List < Node > occurrences ) { Node searchSpace = FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( root , orig . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( ( node instanceof DefnNode ) || ( node instanceof DefsNode ) ) ; } } ) ; if ( searchSpace == null ) { searchSpace = root ; } final String origName = ASTUtil . getNameReflectively ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( isDVarRef ( node ) ) { String name = ASTUtil . getNameReflectively ( node ) ; return ( name != null && name . equals ( origName ) ) ; } return false ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; if ( searchResult instanceof DAsgnNode ) fWriteUsages . add ( searchResult ) ; } } private void pushInstVarRefs ( Node root , Node orig , List < Node > occurrences ) { Node searchSpace = determineSearchSpace ( root , orig ) ; final String origName = ASTUtil . getNameReflectively ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( isInstanceVarRef ( node ) ) { String name = ASTUtil . getNameReflectively ( node ) ; return ( name != null && name . equals ( origName ) ) ; } return false ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; if ( searchResult instanceof InstAsgnNode ) fWriteUsages . add ( searchResult ) ; } } private Node determineSearchSpace ( Node root , Node orig ) { ClassNode enclosingClass = ( ClassNode ) FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( root , orig . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ClassNode ) ; } } ) ; if ( enclosingClass == null ) { return root ; } else { final String className = getClassNodeName ( enclosingClass ) ; List < Node > classNodes = ScopedNodeLocator . Instance ( ) . findNodesInScope ( root , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( node instanceof ClassNode ) { return getClassNodeName ( ( ClassNode ) node ) . equals ( className ) ; } return false ; } } ) ; BlockNode blockNode = new BlockNode ( new IDESourcePosition ( ) ) ; for ( Node classNode : classNodes ) { blockNode . add ( classNode ) ; } return blockNode ; } } private void pushClassVarRefs ( Node root , Node orig , List < Node > occurrences ) { Node searchSpace = determineSearchSpace ( root , orig ) ; final String origName = ASTUtil . getNameReflectively ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( isClassVarRef ( node ) ) { String name = ASTUtil . getNameReflectively ( node ) ; return ( name != null && name . equals ( origName ) ) ; } return false ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; if ( ( searchResult instanceof ClassVarAsgnNode ) || ( searchResult instanceof ClassVarDeclNode ) ) fWriteUsages . add ( searchResult ) ; } } private void pushGlobalVarRefs ( Node root , Node orig , List < Node > occurrences ) { final Node searchSpace = root ; final String origName = ASTUtil . getNameReflectively ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return isGlobalVarRef ( node ) && ASTUtil . getNameReflectively ( node ) . equals ( origName ) ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; if ( searchResult instanceof GlobalAsgnNode ) fWriteUsages . add ( searchResult ) ; } } private void pushSymbolRefs ( Node root , Node orig , List < Node > occurrences ) { final Node searchSpace = root ; final String origName = ( ( SymbolNode ) orig ) . getName ( ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof SymbolNode ) && ( ( SymbolNode ) node ) . getName ( ) . equals ( origName ) ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; } } private void pushConstRefs ( Node root , Node orig , List < Node > occurrences ) { if ( ! isConstRef ( orig ) ) { return ; } final String matchName = ASTUtil . getNameReflectively ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( root , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( isConstRef ( node ) ) { return ASTUtil . getNameReflectively ( node ) . equals ( matchName ) ; } return false ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; if ( searchResult instanceof ConstDeclNode ) fWriteUsages . add ( searchResult ) ; } } private void pushMethodRefs ( Node root , Node orig , List < Node > occurrences ) { if ( ! isMethodRefNode ( orig ) && ! isMethodDefNode ( orig ) ) { return ; } final String matchName = ASTUtil . getNameReflectively ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( root , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( isMethodRefNode ( node ) || isMethodDefNode ( node ) ) { return ASTUtil . getNameReflectively ( node ) . equals ( matchName ) ; } return false ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; } } protected boolean isMethodDefNode ( Node node ) { return node instanceof MethodDefNode ; } private void pushTypeRefs ( Node root , Node orig , List < Node > occurrences ) { if ( ! isTypeRef ( orig ) ) { return ; } final String matchName = ASTUtil . getNameReflectively ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( root , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( isTypeRef ( node ) ) { return getTypeRefName ( node ) . equals ( matchName ) ; } return false ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; } } private void pushReturns ( Node root , Node orig , List < Node > occurrences ) { Node searchSpace = FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( root , orig . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( ( node instanceof DefnNode ) || ( node instanceof DefsNode ) ) ; } } ) ; if ( searchSpace == null ) { searchSpace = root ; } List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ReturnNode ) ; } } ) ; for ( Node searchResult : searchResults ) { occurrences . add ( searchResult ) ; } } private ISourcePosition getPositionOfName ( Node node ) { ISourcePosition pos = node . getPosition ( ) ; String name = null ; if ( node instanceof ReturnNode ) { return node . getPosition ( ) ; } else if ( isLocalVarRef ( node ) || isDVarRef ( node ) || isInstanceVarRef ( node ) || isGlobalVarRef ( node ) || isClassVarRef ( node ) || isConstRef ( node ) || node instanceof BlockArgNode ) { name = ASTUtil . getNameReflectively ( node ) ; } else if ( node instanceof ClassNode ) { return ( ( ClassNode ) node ) . getCPath ( ) . getPosition ( ) ; } else if ( node instanceof ModuleNode ) { return ( ( ModuleNode ) node ) . getCPath ( ) . getPosition ( ) ; } else if ( node instanceof SymbolNode ) { name = ( ( SymbolNode ) node ) . getName ( ) ; return new IDESourcePosition ( pos . getFile ( ) , pos . getStartLine ( ) , pos . getEndLine ( ) , pos . getStartOffset ( ) , pos . getStartOffset ( ) + name . length ( ) + ) ; } else if ( node instanceof CallNode ) { CallNode vcall = ( CallNode ) node ; name = vcall . getName ( ) ; Node receiver = vcall . getReceiverNode ( ) ; int start = receiver . getPosition ( ) . getEndOffset ( ) + ; return new IDESourcePosition ( pos . getFile ( ) , pos . getStartLine ( ) , pos . getEndLine ( ) , start , start + name . length ( ) ) ; } else if ( node instanceof MethodDefNode ) { MethodDefNode def = ( MethodDefNode ) node ; return def . getNameNode ( ) . getPosition ( ) ; } else if ( node instanceof INameNode ) { INameNode vcall = ( INameNode ) node ; name = vcall . getName ( ) ; return new IDESourcePosition ( pos . getFile ( ) , pos . getStartLine ( ) , pos . getEndLine ( ) , pos . getStartOffset ( ) , pos . getStartOffset ( ) + name . length ( ) ) ; } if ( name == null ) { throw new RuntimeException ( "" + node . toString ( ) ) ; } return new IDESourcePosition ( pos . getFile ( ) , pos . getStartLine ( ) , pos . getEndLine ( ) , pos . getStartOffset ( ) , pos . getStartOffset ( ) + name . length ( ) ) ; } private String getClassNodeName ( ClassNode classNode ) { if ( classNode . getCPath ( ) instanceof Colon2Node ) { Colon2Node c2node = ( Colon2Node ) classNode . getCPath ( ) ; return c2node . getName ( ) ; } else if ( classNode . getCPath ( ) instanceof Colon3Node ) { Colon3Node c2node = ( Colon3Node ) classNode . getCPath ( ) ; return c2node . getName ( ) ; } throw new RuntimeException ( "" + classNode . getCPath ( ) . toString ( ) ) ; } private String getModuleNodeName ( ModuleNode moduleNode ) { if ( moduleNode . getCPath ( ) instanceof Colon2Node ) { Colon2Node c2node = ( Colon2Node ) moduleNode . getCPath ( ) ; return c2node . getName ( ) ; } else if ( moduleNode . getCPath ( ) instanceof Colon3Node ) { Colon3Node c2node = ( Colon3Node ) moduleNode . getCPath ( ) ; return c2node . getName ( ) ; } throw new RuntimeException ( "" + moduleNode . getCPath ( ) . toString ( ) ) ; } private String getTypeRefName ( Node node ) { if ( node instanceof ClassNode ) { return getClassNodeName ( ( ClassNode ) node ) ; } if ( node instanceof ModuleNode ) { return getModuleNodeName ( ( ModuleNode ) node ) ; } return ASTUtil . getNameReflectively ( node ) ; } public String getElementName ( ) { if ( fSelectedNode != null ) { return ASTUtil . stringRepresentation ( fSelectedNode ) ; } return null ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . internal . ui . actions . CompositeActionGroup ; import org . rubypeople . rdt . ui . actions . NavigateActionGroup ; class NewSearchViewActionGroup extends CompositeActionGroup { NavigateActionGroup fNavigateActionGroup ; public NewSearchViewActionGroup ( IViewPart part ) { Assert . isNotNull ( part ) ; setGroups ( new ActionGroup [ ] { fNavigateActionGroup = new NavigateActionGroup ( part ) , } ) ; } public void handleOpen ( OpenEvent event ) { IAction openAction = fNavigateActionGroup . getOpenAction ( ) ; if ( openAction != null && openAction . isEnabled ( ) ) { openAction . run ( ) ; return ; } } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . PerformanceStats ; import org . eclipse . core . runtime . SafeRunner ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . search . internal . ui . text . SearchResultUpdater ; import org . eclipse . search . ui . ISearchQuery ; import org . eclipse . search . ui . ISearchResult ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . search . ui . text . Match ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . corext . util . SearchUtils ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . IMatchPresentation ; import org . rubypeople . rdt . ui . search . IQueryParticipant ; import org . rubypeople . rdt . ui . search . ISearchRequestor ; import org . rubypeople . rdt . ui . search . PatternQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class RubySearchQuery implements ISearchQuery { private static final String PERF_SEARCH_PARTICIPANT = "" ; private ISearchResult fResult ; private final QuerySpecification fPatternData ; public RubySearchQuery ( QuerySpecification data ) { if ( data == null ) { throw new IllegalArgumentException ( "" ) ; } fPatternData = data ; } private static class SearchRequestor implements ISearchRequestor { private IQueryParticipant fParticipant ; private RubySearchResult fSearchResult ; public void reportMatch ( Match match ) { IMatchPresentation participant = fParticipant . getUIParticipant ( ) ; if ( participant == null || match . getElement ( ) instanceof IRubyElement || match . getElement ( ) instanceof IResource ) { fSearchResult . addMatch ( match ) ; } else { fSearchResult . addMatch ( match , participant ) ; } } protected SearchRequestor ( IQueryParticipant participant , RubySearchResult result ) { super ( ) ; fParticipant = participant ; fSearchResult = result ; } } public IStatus run ( IProgressMonitor monitor ) { final RubySearchResult textResult = ( RubySearchResult ) getSearchResult ( ) ; textResult . removeAll ( ) ; SearchEngine engine = new SearchEngine ( ) ; try { int totalTicks = ; IProject [ ] projects = RubySearchScopeFactory . getInstance ( ) . getProjects ( fPatternData . getScope ( ) ) ; final SearchParticipantRecord [ ] participantDescriptors = SearchParticipantsExtensionPoint . getInstance ( ) . getSearchParticipants ( projects ) ; final int [ ] ticks = new int [ participantDescriptors . length ] ; for ( int i = ; i < participantDescriptors . length ; i ++ ) { final int iPrime = i ; ISafeRunnable runnable = new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { ticks [ iPrime ] = ; String message = SearchMessages . RubySearchQuery_error_participant_estimate ; RubyPlugin . log ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , message , exception ) ) ; } public void run ( ) throws Exception { ticks [ iPrime ] = participantDescriptors [ iPrime ] . getParticipant ( ) . estimateTicks ( fPatternData ) ; } } ; SafeRunner . run ( runnable ) ; totalTicks += ticks [ i ] ; } SearchPattern pattern ; String stringPattern ; if ( fPatternData instanceof ElementQuerySpecification ) { IRubyElement element = ( ( ElementQuerySpecification ) fPatternData ) . getElement ( ) ; stringPattern = RubyElementLabels . getElementLabel ( element , RubyElementLabels . ALL_DEFAULT ) ; if ( ! element . exists ( ) ) { return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , Messages . format ( SearchMessages . RubySearchQuery_error_element_does_not_exist , stringPattern ) , null ) ; } pattern = SearchPattern . createPattern ( element , fPatternData . getLimitTo ( ) , SearchUtils . GENERICS_AGNOSTIC_MATCH_RULE ) ; } else { PatternQuerySpecification patternSpec = ( PatternQuerySpecification ) fPatternData ; stringPattern = patternSpec . getPattern ( ) ; int matchMode = getMatchMode ( stringPattern ) | SearchPattern . R_ERASURE_MATCH ; if ( patternSpec . isCaseSensitive ( ) ) matchMode |= SearchPattern . R_CASE_SENSITIVE ; pattern = SearchPattern . createPattern ( patternSpec . getPattern ( ) , patternSpec . getSearchFor ( ) , patternSpec . getLimitTo ( ) , matchMode ) ; } if ( pattern == null ) { return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , Messages . format ( SearchMessages . RubySearchQuery_error_unsupported_pattern , stringPattern ) , null ) ; } monitor . beginTask ( Messages . format ( SearchMessages . RubySearchQuery_task_label , stringPattern ) , totalTicks ) ; IProgressMonitor mainSearchPM = new SubProgressMonitor ( monitor , ) ; boolean ignorePotentials = NewSearchUI . arePotentialMatchesIgnored ( ) ; NewSearchResultCollector collector = new NewSearchResultCollector ( textResult , ignorePotentials ) ; engine . search ( pattern , new SearchParticipant [ ] { SearchEngine . getDefaultSearchParticipant ( ) } , fPatternData . getScope ( ) , collector , mainSearchPM ) ; for ( int i = ; i < participantDescriptors . length ; i ++ ) { final ISearchRequestor requestor = new SearchRequestor ( participantDescriptors [ i ] . getParticipant ( ) , textResult ) ; final IProgressMonitor participantPM = new SubProgressMonitor ( monitor , ticks [ i ] ) ; final int iPrime = i ; ISafeRunnable runnable = new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { participantDescriptors [ iPrime ] . getDescriptor ( ) . disable ( ) ; String message = SearchMessages . RubySearchQuery_error_participant_search ; RubyPlugin . log ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , message , exception ) ) ; } public void run ( ) throws Exception { final IQueryParticipant participant = participantDescriptors [ iPrime ] . getParticipant ( ) ; final PerformanceStats stats = PerformanceStats . getStats ( PERF_SEARCH_PARTICIPANT , participant ) ; stats . startRun ( ) ; participant . search ( requestor , fPatternData , participantPM ) ; stats . endRun ( ) ; } } ; SafeRunner . run ( runnable ) ; } } catch ( CoreException e ) { return e . getStatus ( ) ; } String message = Messages . format ( SearchMessages . RubySearchQuery_status_ok_message , String . valueOf ( textResult . getMatchCount ( ) ) ) ; return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , , message , null ) ; } private int getMatchMode ( String pattern ) { if ( pattern . indexOf ( '' ) != - || pattern . indexOf ( '' ) != - ) { return SearchPattern . R_PATTERN_MATCH ; } else if ( SearchUtils . isCamelCasePattern ( pattern ) ) { return SearchPattern . R_CAMELCASE_MATCH ; } return SearchPattern . R_EXACT_MATCH ; } public String getLabel ( ) { return SearchMessages . RubySearchQuery_label ; } public String getResultLabel ( int nMatches ) { if ( nMatches == ) { String [ ] args = { getSearchPatternDescription ( ) , fPatternData . getScopeDescription ( ) } ; switch ( fPatternData . getLimitTo ( ) ) { case IRubySearchConstants . DECLARATIONS : return Messages . format ( SearchMessages . RubySearchOperation_singularDeclarationsPostfix , args ) ; case IRubySearchConstants . REFERENCES : return Messages . format ( SearchMessages . RubySearchOperation_singularReferencesPostfix , args ) ; case IRubySearchConstants . ALL_OCCURRENCES : return Messages . format ( SearchMessages . RubySearchOperation_singularOccurrencesPostfix , args ) ; case IRubySearchConstants . READ_ACCESSES : return Messages . format ( SearchMessages . RubySearchOperation_singularReadReferencesPostfix , args ) ; case IRubySearchConstants . WRITE_ACCESSES : return Messages . format ( SearchMessages . RubySearchOperation_singularWriteReferencesPostfix , args ) ; default : return Messages . format ( SearchMessages . RubySearchOperation_singularOccurrencesPostfix , args ) ; } } else { Object [ ] args = { getSearchPatternDescription ( ) , new Integer ( nMatches ) , fPatternData . getScopeDescription ( ) } ; switch ( fPatternData . getLimitTo ( ) ) { case IRubySearchConstants . DECLARATIONS : return Messages . format ( SearchMessages . RubySearchOperation_pluralDeclarationsPostfix , args ) ; case IRubySearchConstants . REFERENCES : return Messages . format ( SearchMessages . RubySearchOperation_pluralReferencesPostfix , args ) ; case IRubySearchConstants . ALL_OCCURRENCES : return Messages . format ( SearchMessages . RubySearchOperation_pluralOccurrencesPostfix , args ) ; case IRubySearchConstants . READ_ACCESSES : return Messages . format ( SearchMessages . RubySearchOperation_pluralReadReferencesPostfix , args ) ; case IRubySearchConstants . WRITE_ACCESSES : return Messages . format ( SearchMessages . RubySearchOperation_pluralWriteReferencesPostfix , args ) ; default : return Messages . format ( SearchMessages . RubySearchOperation_pluralOccurrencesPostfix , args ) ; } } } private String getSearchPatternDescription ( ) { if ( fPatternData instanceof ElementQuerySpecification ) { IRubyElement element = ( ( ElementQuerySpecification ) fPatternData ) . getElement ( ) ; return RubyElementLabels . getElementLabel ( element , RubyElementLabels . ALL_DEFAULT | RubyElementLabels . ALL_FULLY_QUALIFIED | RubyElementLabels . USE_RESOLVED ) ; } return ( ( PatternQuerySpecification ) fPatternData ) . getPattern ( ) ; } ImageDescriptor getImageDescriptor ( ) { if ( fPatternData . getLimitTo ( ) == IRubySearchConstants . DECLARATIONS ) return RubyPluginImages . DESC_OBJS_SEARCH_DECL ; else return RubyPluginImages . DESC_OBJS_SEARCH_REF ; } public boolean canRerun ( ) { return true ; } public boolean canRunInBackground ( ) { return true ; } public ISearchResult getSearchResult ( ) { if ( fResult == null ) { fResult = new RubySearchResult ( this ) ; new SearchResultUpdater ( ( RubySearchResult ) fResult ) ; } return fResult ; } QuerySpecification getSpecification ( ) { return fPatternData ; } } package org . rubypeople . rdt . internal . ui . search ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class PatternStrings { public static String getSignature ( IRubyElement element ) { if ( element == null ) return null ; else switch ( element . getElementType ( ) ) { case IRubyElement . METHOD : return getMethodSignature ( ( IMethod ) element ) ; case IRubyElement . TYPE : return getTypeSignature ( ( IType ) element ) ; case IRubyElement . FIELD : return getFieldSignature ( ( IField ) element ) ; default : return element . getElementName ( ) ; } } public static String getMethodSignature ( IMethod method ) { StringBuffer buffer = new StringBuffer ( ) ; if ( method . isSingleton ( ) || method . isConstructor ( ) ) { buffer . append ( RubyElementLabels . getElementLabel ( method . getDeclaringType ( ) , RubyElementLabels . USE_RESOLVED ) ) ; buffer . append ( '' ) ; } boolean isConstructor = method . isConstructor ( ) ; if ( ! isConstructor ) { buffer . append ( getUnqualifiedMethodSignature ( method , ! isConstructor ) ) ; } else { buffer . append ( "" ) ; } return buffer . toString ( ) ; } private static String getUnqualifiedMethodSignature ( IMethod method , boolean isNotConstructor ) { StringBuffer buffer = new StringBuffer ( ) ; if ( isNotConstructor ) { buffer . append ( method . getElementName ( ) ) ; } return buffer . toString ( ) ; } public static String getUnqualifiedMethodSignature ( IMethod method ) { return getUnqualifiedMethodSignature ( method , true ) ; } public static String getTypeSignature ( IType field ) { return RubyElementLabels . getElementLabel ( field , RubyElementLabels . USE_RESOLVED ) ; } public static String getFieldSignature ( IField field ) { return RubyElementLabels . getElementLabel ( field , ) ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . Arrays ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . viewers . ArrayContentProvider ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . dialogs . SelectionStatusDialog ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class FiltersDialog extends SelectionStatusDialog { private CheckboxTableViewer fListViewer ; private RubySearchResultPage fPage ; private Button fLimitElementsCheckbox ; private Text fLimitElementsField ; private int fLimitElementCount = ; private boolean fLimitElements = false ; public FiltersDialog ( RubySearchResultPage page ) { super ( page . getSite ( ) . getShell ( ) ) ; setTitle ( org . rubypeople . rdt . internal . ui . search . SearchMessages . FiltersDialog_title ) ; setStatusLineAboveButtons ( true ) ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; fPage = page ; } public MatchFilter [ ] getEnabledFilters ( ) { Object [ ] result = getResult ( ) ; MatchFilter [ ] filters = new MatchFilter [ result . length ] ; System . arraycopy ( result , , filters , , filters . length ) ; return filters ; } public boolean isLimitEnabled ( ) { return fLimitElements ; } public int getElementLimit ( ) { return fLimitElementCount ; } protected Control createDialogArea ( Composite composite ) { Composite parent = ( Composite ) super . createDialogArea ( composite ) ; initializeDialogUnits ( composite ) ; createTableLimit ( parent ) ; Label l = new Label ( parent , SWT . NONE ) ; l . setFont ( parent . getFont ( ) ) ; l . setText ( org . rubypeople . rdt . internal . ui . search . SearchMessages . FiltersDialog_filters_label ) ; Table table = new Table ( parent , SWT . CHECK | SWT . BORDER ) ; table . setFont ( parent . getFont ( ) ) ; fListViewer = new CheckboxTableViewer ( table ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . minimumHeight = convertHeightInCharsToPixels ( ) ; table . setLayoutData ( data ) ; fListViewer . setLabelProvider ( new LabelProvider ( ) { public String getText ( Object element ) { return ( ( MatchFilter ) element ) . getName ( ) ; } } ) ; ArrayContentProvider cp = new ArrayContentProvider ( ) ; fListViewer . setContentProvider ( cp ) ; fListViewer . setInput ( MatchFilter . allFilters ( ) ) ; fListViewer . setCheckedElements ( fPage . getMatchFilters ( ) ) ; l = new Label ( parent , SWT . NONE ) ; l . setFont ( parent . getFont ( ) ) ; l . setText ( org . rubypeople . rdt . internal . ui . search . SearchMessages . FiltersDialog_description_label ) ; final Text description = new Text ( parent , SWT . LEFT | SWT . WRAP | SWT . MULTI | SWT . READ_ONLY | SWT . BORDER | SWT . V_SCROLL ) ; description . setFont ( parent . getFont ( ) ) ; data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . heightHint = convertHeightInCharsToPixels ( ) ; description . setLayoutData ( data ) ; fListViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { Object selectedElement = ( ( IStructuredSelection ) event . getSelection ( ) ) . getFirstElement ( ) ; if ( selectedElement != null ) description . setText ( ( ( MatchFilter ) selectedElement ) . getDescription ( ) ) ; else description . setText ( "" ) ; } } ) ; return parent ; } private void createTableLimit ( Composite ancestor ) { Composite parent = new Composite ( ancestor , SWT . NONE ) ; GridLayout gl = new GridLayout ( ) ; gl . numColumns = ; gl . marginWidth = ; gl . marginHeight = ; parent . setLayout ( gl ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = ; parent . setLayoutData ( gd ) ; fLimitElementsCheckbox = new Button ( parent , SWT . CHECK ) ; fLimitElementsCheckbox . setText ( org . rubypeople . rdt . internal . ui . search . SearchMessages . FiltersDialog_limit_label ) ; fLimitElementsCheckbox . setLayoutData ( new GridData ( ) ) ; fLimitElementsField = new Text ( parent , SWT . BORDER ) ; gd = new GridData ( ) ; gd . widthHint = convertWidthInCharsToPixels ( ) ; fLimitElementsField . setLayoutData ( gd ) ; applyDialogFont ( parent ) ; fLimitElementsCheckbox . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { updateLimitValueEnablement ( ) ; } } ) ; fLimitElementsField . addKeyListener ( new KeyAdapter ( ) { public void keyReleased ( KeyEvent e ) { validateText ( ) ; } } ) ; initLimit ( ) ; } private void initLimit ( ) { boolean limit = fPage . limitElements ( ) ; int count = fPage . getElementLimit ( ) ; fLimitElementsCheckbox . setSelection ( limit ) ; fLimitElementsField . setText ( String . valueOf ( count ) ) ; updateLimitValueEnablement ( ) ; } private void updateLimitValueEnablement ( ) { fLimitElementsField . setEnabled ( fLimitElementsCheckbox . getSelection ( ) ) ; } protected void validateText ( ) { String text = fLimitElementsField . getText ( ) ; int value = - ; try { value = Integer . valueOf ( text ) . intValue ( ) ; } catch ( NumberFormatException e ) { } if ( fLimitElementsCheckbox . getSelection ( ) && value <= ) updateStatus ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , , org . rubypeople . rdt . internal . ui . search . SearchMessages . FiltersDialog_limit_error , null ) ) ; else updateStatus ( new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , , "" , null ) ) ; } protected void computeResult ( ) { fLimitElementCount = Integer . valueOf ( fLimitElementsField . getText ( ) ) . intValue ( ) ; fLimitElements = fLimitElementsCheckbox . getSelection ( ) ; setResult ( Arrays . asList ( fListViewer . getCheckedElements ( ) ) ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . viewers . DecoratingLabelProvider ; import org . eclipse . jface . viewers . IColorProvider ; import org . eclipse . jface . viewers . ILabelDecorator ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . swt . graphics . Color ; public class ColorDecoratingLabelProvider extends DecoratingLabelProvider implements IColorProvider { public ColorDecoratingLabelProvider ( ILabelProvider provider , ILabelDecorator decorator ) { super ( provider , decorator ) ; } public Color getForeground ( Object element ) { ILabelProvider labelProvider = getLabelProvider ( ) ; if ( labelProvider instanceof IColorProvider ) return ( ( IColorProvider ) labelProvider ) . getForeground ( element ) ; return null ; } public Color getBackground ( Object element ) { ILabelProvider labelProvider = getLabelProvider ( ) ; if ( labelProvider instanceof IColorProvider ) return ( ( IColorProvider ) labelProvider ) . getBackground ( element ) ; return null ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; public class RubyElementLineSorter extends ViewerSorter { public int compare ( Viewer viewer , Object e1 , Object e2 ) { RubyElementLine jel1 = ( RubyElementLine ) e1 ; RubyElementLine jel2 = ( RubyElementLine ) e2 ; return jel1 . getLine ( ) - jel2 . getLine ( ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . custom . BusyIndicator ; public class SortAction extends Action { private int fSortOrder ; private RubySearchResultPage fPage ; public SortAction ( String label , RubySearchResultPage page , int sortOrder ) { super ( label ) ; fPage = page ; fSortOrder = sortOrder ; } public void run ( ) { BusyIndicator . showWhile ( fPage . getViewer ( ) . getControl ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fPage . setSortOrder ( fSortOrder ) ; } } ) ; } public int getSortOrder ( ) { return fSortOrder ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . AbstractTreeViewer ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; public class LevelTreeContentProvider extends RubySearchContentProvider implements ITreeContentProvider { private Map fChildrenMap ; private StandardRubyElementContentProvider fContentProvider ; public static final int LEVEL_TYPE = ; public static final int LEVEL_FILE = ; public static final int LEVEL_PACKAGE = ; public static final int LEVEL_PROJECT = ; private static int [ ] [ ] JAVA_ELEMENT_TYPES = { { IRubyElement . TYPE } , { IRubyElement . SCRIPT } , { IRubyElement . SOURCE_FOLDER } , { IRubyElement . RUBY_PROJECT , IRubyElement . SOURCE_FOLDER_ROOT } , { IRubyElement . RUBY_MODEL } } ; private static int [ ] [ ] RESOURCE_TYPES = { { } , { IResource . FILE } , { IResource . FOLDER } , { IResource . PROJECT } , { IResource . ROOT } } ; private static final int MAX_LEVEL = JAVA_ELEMENT_TYPES . length - ; private int fCurrentLevel ; static class FastRubyElementProvider extends StandardRubyElementContentProvider { public Object getParent ( Object element ) { return internalGetParent ( element ) ; } } public LevelTreeContentProvider ( RubySearchResultPage page , int level ) { super ( page ) ; fCurrentLevel = level ; fContentProvider = new FastRubyElementProvider ( ) ; } public Object getParent ( Object child ) { Object possibleParent = internalGetParent ( child ) ; if ( possibleParent instanceof IRubyElement ) { IRubyElement javaElement = ( IRubyElement ) possibleParent ; for ( int j = fCurrentLevel ; j < MAX_LEVEL + ; j ++ ) { for ( int i = ; i < JAVA_ELEMENT_TYPES [ j ] . length ; i ++ ) { if ( javaElement . getElementType ( ) == JAVA_ELEMENT_TYPES [ j ] [ i ] ) { return null ; } } } } else if ( possibleParent instanceof IResource ) { IResource resource = ( IResource ) possibleParent ; for ( int j = fCurrentLevel ; j < MAX_LEVEL + ; j ++ ) { for ( int i = ; i < RESOURCE_TYPES [ j ] . length ; i ++ ) { if ( resource . getType ( ) == RESOURCE_TYPES [ j ] [ i ] ) { return null ; } } } } if ( fCurrentLevel != LEVEL_FILE && child instanceof IType ) { IType type = ( IType ) child ; if ( possibleParent instanceof IRubyScript ) possibleParent = type . getSourceFolder ( ) ; } return possibleParent ; } private Object internalGetParent ( Object child ) { return fContentProvider . getParent ( child ) ; } public Object [ ] getElements ( Object inputElement ) { return getChildren ( inputElement ) ; } protected synchronized void initialize ( RubySearchResult result ) { super . initialize ( result ) ; fChildrenMap = new HashMap ( ) ; if ( result != null ) { Object [ ] elements = result . getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { if ( getPage ( ) . getDisplayedMatchCount ( elements [ i ] ) > ) { insert ( null , null , elements [ i ] ) ; } } } } protected void insert ( Map toAdd , Set toUpdate , Object child ) { Object parent = getParent ( child ) ; while ( parent != null ) { if ( insertChild ( parent , child ) ) { if ( toAdd != null ) insertInto ( parent , child , toAdd ) ; } else { if ( toUpdate != null ) toUpdate . add ( parent ) ; return ; } child = parent ; parent = getParent ( child ) ; } if ( insertChild ( fResult , child ) ) { if ( toAdd != null ) insertInto ( fResult , child , toAdd ) ; } } private boolean insertChild ( Object parent , Object child ) { return insertInto ( parent , child , fChildrenMap ) ; } private boolean insertInto ( Object parent , Object child , Map map ) { Set children = ( Set ) map . get ( parent ) ; if ( children == null ) { children = new HashSet ( ) ; map . put ( parent , children ) ; } return children . add ( child ) ; } protected void remove ( Set toRemove , Set toUpdate , Object element ) { if ( hasChildren ( element ) ) { if ( toUpdate != null ) toUpdate . add ( element ) ; } else { if ( getPage ( ) . getDisplayedMatchCount ( element ) == ) { fChildrenMap . remove ( element ) ; Object parent = getParent ( element ) ; if ( parent != null ) { if ( removeFromSiblings ( element , parent ) ) { remove ( toRemove , toUpdate , parent ) ; } } else { if ( removeFromSiblings ( element , fResult ) ) { if ( toRemove != null ) toRemove . add ( element ) ; } } } else { if ( toUpdate != null ) { toUpdate . add ( element ) ; } } } } private boolean removeFromSiblings ( Object element , Object parent ) { Set siblings = ( Set ) fChildrenMap . get ( parent ) ; if ( siblings != null ) { return siblings . remove ( element ) ; } else { return false ; } } public Object [ ] getChildren ( Object parentElement ) { Set children = ( Set ) fChildrenMap . get ( parentElement ) ; if ( children == null ) return EMPTY_ARR ; return children . toArray ( ) ; } public boolean hasChildren ( Object element ) { return getChildren ( element ) . length > ; } public synchronized void elementsChanged ( Object [ ] updatedElements ) { AbstractTreeViewer viewer = ( AbstractTreeViewer ) getPage ( ) . getViewer ( ) ; if ( fResult == null ) return ; Set toRemove = new HashSet ( ) ; Set toUpdate = new HashSet ( ) ; Map toAdd = new HashMap ( ) ; for ( int i = ; i < updatedElements . length ; i ++ ) { if ( getPage ( ) . getDisplayedMatchCount ( updatedElements [ i ] ) > ) insert ( toAdd , toUpdate , updatedElements [ i ] ) ; else remove ( toRemove , toUpdate , updatedElements [ i ] ) ; } viewer . remove ( toRemove . toArray ( ) ) ; for ( Iterator iter = toAdd . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Object parent = iter . next ( ) ; HashSet children = ( HashSet ) toAdd . get ( parent ) ; viewer . add ( parent , children . toArray ( ) ) ; } for ( Iterator elementsToUpdate = toUpdate . iterator ( ) ; elementsToUpdate . hasNext ( ) ; ) { viewer . refresh ( elementsToUpdate . next ( ) ) ; } } public void clear ( ) { initialize ( fResult ) ; getPage ( ) . getViewer ( ) . refresh ( ) ; } public void setLevel ( int level ) { fCurrentLevel = level ; initialize ( fResult ) ; getPage ( ) . getViewer ( ) . refresh ( ) ; } public void filtersChanged ( MatchFilter [ ] filters ) { super . filtersChanged ( filters ) ; initialize ( fResult ) ; getPage ( ) . getViewer ( ) . refresh ( ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . IColorProvider ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class SortingLabelProvider extends SearchLabelProvider implements IColorProvider { public static final int SHOW_ELEMENT_CONTAINER = ; public static final int SHOW_CONTAINER_ELEMENT = ; public static final int SHOW_PATH = ; public SortingLabelProvider ( RubySearchResultPage page ) { super ( page ) ; } public Image getImage ( Object element ) { Image image = null ; if ( element instanceof IRubyElement || element instanceof IResource ) image = super . getImage ( element ) ; if ( image != null ) return image ; return getParticipantImage ( element ) ; } public final String getText ( Object element ) { return getLabelWithCounts ( element , internalGetText ( element ) ) ; } private String internalGetText ( Object o ) { if ( o instanceof IImportDeclaration ) o = ( ( IImportDeclaration ) o ) . getParent ( ) . getParent ( ) ; String text = super . getText ( o ) ; if ( text != null && ( text . length ( ) > ) ) return text ; return getParticipantText ( o ) ; } public void setOrder ( int orderFlag ) { long flags = DEFAULT_SEARCH_TEXTFLAGS ; if ( orderFlag == SHOW_ELEMENT_CONTAINER ) flags |= RubyElementLabels . F_POST_QUALIFIED | RubyElementLabels . M_POST_QUALIFIED | RubyElementLabels . I_POST_QUALIFIED | RubyElementLabels . T_POST_QUALIFIED | RubyElementLabels . D_POST_QUALIFIED | RubyElementLabels . CF_POST_QUALIFIED | RubyElementLabels . CU_POST_QUALIFIED ; else if ( orderFlag == SHOW_CONTAINER_ELEMENT ) flags |= RubyElementLabels . F_FULLY_QUALIFIED | RubyElementLabels . M_FULLY_QUALIFIED | RubyElementLabels . I_FULLY_QUALIFIED | RubyElementLabels . T_FILENAME_QUALIFIED | RubyElementLabels . D_QUALIFIED | RubyElementLabels . CF_QUALIFIED | RubyElementLabels . CU_QUALIFIED ; else if ( orderFlag == SHOW_PATH ) { flags |= RubyElementLabels . F_FULLY_QUALIFIED | RubyElementLabels . M_FULLY_QUALIFIED | RubyElementLabels . I_FULLY_QUALIFIED | RubyElementLabels . T_FILENAME_QUALIFIED | RubyElementLabels . D_QUALIFIED | RubyElementLabels . CF_QUALIFIED | RubyElementLabels . CU_QUALIFIED ; flags |= RubyElementLabels . PREPEND_ROOT_PATH ; } setTextFlags ( flags ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; public class FilterAction extends Action { private MatchFilter fFilter ; private RubySearchResultPage fPage ; public FilterAction ( RubySearchResultPage page , MatchFilter filter ) { super ( filter . getActionLabel ( ) , IAction . AS_CHECK_BOX ) ; fPage = page ; fFilter = filter ; } public void run ( ) { if ( fPage . hasMatchFilter ( getFilter ( ) ) ) { fPage . removeMatchFilter ( fFilter ) ; } else { fPage . addMatchFilter ( fFilter ) ; } } public MatchFilter getFilter ( ) { return fFilter ; } public void updateCheckState ( ) { setChecked ( fPage . hasMatchFilter ( getFilter ( ) ) ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class PostfixLabelProvider extends SearchLabelProvider { private ITreeContentProvider fContentProvider ; public PostfixLabelProvider ( RubySearchResultPage page ) { super ( page ) ; fContentProvider = new LevelTreeContentProvider . FastRubyElementProvider ( ) ; } public Image getImage ( Object element ) { Image image = super . getImage ( element ) ; if ( image != null ) return image ; return getParticipantImage ( element ) ; } public String getText ( Object element ) { String labelWithCounts = getLabelWithCounts ( element , internalGetText ( element ) ) ; StringBuffer res = new StringBuffer ( labelWithCounts ) ; ITreeContentProvider provider = ( ITreeContentProvider ) fPage . getViewer ( ) . getContentProvider ( ) ; Object visibleParent = provider . getParent ( element ) ; Object realParent = fContentProvider . getParent ( element ) ; Object lastElement = element ; while ( realParent != null && ! ( realParent instanceof IRubyModel ) && ! realParent . equals ( visibleParent ) ) { if ( ! isSameInformation ( realParent , lastElement ) ) { res . append ( RubyElementLabels . CONCAT_STRING ) . append ( internalGetText ( realParent ) ) ; } lastElement = realParent ; realParent = fContentProvider . getParent ( realParent ) ; } return res . toString ( ) ; } protected boolean hasChildren ( Object element ) { ITreeContentProvider contentProvider = ( ITreeContentProvider ) fPage . getViewer ( ) . getContentProvider ( ) ; return contentProvider . hasChildren ( element ) ; } private String internalGetText ( Object element ) { String text = super . getText ( element ) ; if ( text != null && text . length ( ) > ) return text ; return getParticipantText ( element ) ; } private boolean isSameInformation ( Object realParent , Object lastElement ) { if ( lastElement instanceof IType ) { IType type = ( IType ) lastElement ; if ( realParent instanceof IRubyScript ) { if ( type . getRubyScript ( ) . equals ( realParent ) ) return true ; } } return false ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . ArrayList ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . IDocument ; import org . eclipse . search . ui . ISearchQuery ; import org . eclipse . search . ui . ISearchResult ; import org . eclipse . search . ui . text . Match ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; public class OccurrencesSearchQuery implements ISearchQuery { private final OccurrencesSearchResult fResult ; private IOccurrencesFinder fFinder ; private IDocument fDocument ; private final IRubyElement fElement ; private final String fJobLabel ; private final String fSingularLabel ; private final String fPluralLabel ; private final String fName ; public OccurrencesSearchQuery ( IOccurrencesFinder finder , IDocument document , IRubyElement element ) { fFinder = finder ; fDocument = document ; fElement = element ; fJobLabel = fFinder . getJobLabel ( ) ; fResult = new OccurrencesSearchResult ( this ) ; fSingularLabel = fFinder . getUnformattedSingularLabel ( ) ; fPluralLabel = fFinder . getUnformattedPluralLabel ( ) ; fName = fFinder . getElementName ( ) ; } public IStatus run ( IProgressMonitor monitor ) { if ( fFinder == null ) { new StatusInfo ( IStatus . ERROR , "" ) ; } try { fFinder . perform ( ) ; ArrayList resultingMatches = new ArrayList ( ) ; fFinder . collectOccurrenceMatches ( fElement , fDocument , resultingMatches ) ; if ( ! resultingMatches . isEmpty ( ) ) { fResult . addMatches ( ( Match [ ] ) resultingMatches . toArray ( new Match [ resultingMatches . size ( ) ] ) ) ; } fFinder = null ; fDocument = null ; } finally { monitor . done ( ) ; } return Status . OK_STATUS ; } public String getLabel ( ) { return fJobLabel ; } public String getResultLabel ( int nMatches ) { if ( nMatches == ) { return Messages . format ( fSingularLabel , new Object [ ] { fName , fElement . getElementName ( ) } ) ; } else { return Messages . format ( fPluralLabel , new Object [ ] { fName , new Integer ( nMatches ) , fElement . getElementName ( ) } ) ; } } public boolean canRerun ( ) { return false ; } public boolean canRunInBackground ( ) { return true ; } public ISearchResult getSearchResult ( ) { return fResult ; } } package org . rubypeople . rdt . internal . ui . search ; public abstract class AbstractOccurencesFinder implements IOccurrencesFinder { protected boolean fMarkOccurrenceAnnotations ; protected boolean fStickyOccurrenceAnnotations ; protected boolean fMarkTypeOccurrences ; protected boolean fMarkMethodOccurrences ; protected boolean fMarkConstantOccurrences ; protected boolean fMarkFieldOccurrences ; protected boolean fMarkLocalVariableOccurrences ; protected boolean fMarkMethodExitPoints ; public void setFMarkConstantOccurrences ( boolean markConstantOccurrences ) { fMarkConstantOccurrences = markConstantOccurrences ; } public void setFMarkFieldOccurrences ( boolean markFieldOccurrences ) { fMarkFieldOccurrences = markFieldOccurrences ; } public void setFMarkLocalVariableOccurrences ( boolean markLocalVariableOccurrences ) { fMarkLocalVariableOccurrences = markLocalVariableOccurrences ; } public void setFMarkMethodExitPoints ( boolean markMethodExitPoints ) { fMarkMethodExitPoints = markMethodExitPoints ; } public void setFMarkMethodOccurrences ( boolean markMethodOccurrences ) { fMarkMethodOccurrences = markMethodOccurrences ; } public void setFMarkOccurrenceAnnotations ( boolean markOccurrenceAnnotations ) { fMarkOccurrenceAnnotations = markOccurrenceAnnotations ; } public void setFMarkTypeOccurrences ( boolean markTypeOccurrences ) { fMarkTypeOccurrences = markTypeOccurrences ; } public void setFStickyOccurrenceAnnotations ( boolean stickyOccurrenceAnnotations ) { fStickyOccurrenceAnnotations = stickyOccurrenceAnnotations ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . osgi . util . NLS ; public class SearchMessages extends NLS { private static final String BUNDLE_NAME = SearchMessages . class . getName ( ) ; public static String WorkspaceScope ; public static String WorkspaceScopeNoJRE ; public static String RubySearchScopeFactory_undefined_projects ; public static String EnclosingProjectScope ; public static String EnclosingProjectScopeNoJRE ; public static String EnclosingProjectsScope2 ; public static String EnclosingProjectsScope2NoJRE ; public static String EnclosingProjectsScope ; public static String EnclosingProjectsScopeNoJRE ; public static String ProjectScope ; public static String ProjectScopeNoJRE ; public static String HierarchyScope ; public static String RubySearchScopeFactory_undefined_selection ; public static String SingleSelectionScope ; public static String SingleSelectionScopeNoJRE ; public static String DoubleSelectionScope ; public static String DoubleSelectionScopeNoJRE ; public static String SelectionScope ; public static String SelectionScopeNoJRE ; public static String RubySearchScopeFactory_undefined_workingsets ; public static String SingleWorkingSetScope ; public static String SingleWorkingSetScopeNoJRE ; public static String DoubleWorkingSetScope ; public static String DoubleWorkingSetScopeNoJRE ; public static String WorkingSetsScope ; public static String WorkingSetsScopeNoJRE ; public static String SearchPage_searchFor_type ; public static String SearchPage_searchFor_method ; public static String SearchPage_searchFor_constructor ; public static String SearchPage_searchFor_field ; public static String SearchPage_limitTo_declarations ; public static String SearchPage_limitTo_references ; public static String SearchPage_limitTo_allOccurrences ; public static String SearchPage_limitTo_readReferences ; public static String SearchPage_limitTo_writeReferences ; public static String SearchPage_searchJRE_label ; public static String SearchPage_searchFor_label ; public static String SearchPage_limitTo_label ; public static String SearchPage_expression_caseSensitive ; public static String SearchPage_expression_label ; public static String SearchUtil_workingSetConcatenation ; public static String RubySearchQuery_error_participant_estimate ; public static String RubySearchQuery_error_element_does_not_exist ; public static String RubySearchQuery_error_unsupported_pattern ; public static String RubySearchQuery_task_label ; public static String RubySearchQuery_error_participant_search ; public static String RubySearchQuery_status_ok_message ; public static String RubySearchQuery_label ; public static String RubySearchOperation_singularDeclarationsPostfix ; public static String RubySearchOperation_singularReferencesPostfix ; public static String RubySearchOperation_singularOccurrencesPostfix ; public static String RubySearchOperation_singularReadReferencesPostfix ; public static String RubySearchOperation_singularWriteReferencesPostfix ; public static String RubySearchOperation_pluralDeclarationsPostfix ; public static String RubySearchOperation_pluralReferencesPostfix ; public static String RubySearchOperation_pluralOccurrencesPostfix ; public static String RubySearchOperation_pluralReadReferencesPostfix ; public static String RubySearchOperation_pluralWriteReferencesPostfix ; public static String MatchFilter_PotentialFilter_name ; public static String MatchFilter_PotentialFilter_actionLabel ; public static String MatchFilter_PotentialFilter_description ; public static String MatchFilter_ImportFilter_name ; public static String MatchFilter_ImportFilter_actionLabel ; public static String MatchFilter_ImportFilter_description ; public static String MatchFilter_WriteFilter_name ; public static String MatchFilter_WriteFilter_actionLabel ; public static String MatchFilter_WriteFilter_description ; public static String MatchFilter_ReadFilter_name ; public static String MatchFilter_ReadFilter_actionLabel ; public static String MatchFilter_ReadFilter_description ; public static String MatchFilter_RubydocFilter_name ; public static String MatchFilter_RubydocFilter_actionLabel ; public static String MatchFilter_RubydocFilter_description ; public static String SearchParticipant_error_noID ; public static String SearchParticipant_error_noNature ; public static String SearchParticipant_error_noClass ; public static String SearchParticipant_error_classCast ; public static String RubySearchResultPage_error_marker ; public static String RubySearchResultPage_sortBylabel ; public static String RubySearchResultPage_preferences_label ; public static String RubySearchResultPage_filtered_message ; public static String RubySearchResultPage_filteredWithCount_message ; public static String RubySearchResultPage_open_editor_error_title ; public static String RubySearchResultPage_open_editor_error_message ; public static String RubySearchResultPage_sortByName ; public static String RubySearchResultPage_sortByPath ; public static String RubySearchResultPage_sortByParentName ; public static String RubySearchResultPage_groupby_project ; public static String RubySearchResultPage_groupby_project_tooltip ; public static String RubySearchResultPage_groupby_package ; public static String RubySearchResultPage_groupby_package_tooltip ; public static String RubySearchResultPage_groupby_file ; public static String RubySearchResultPage_groupby_file_tooltip ; public static String RubySearchResultPage_groupby_type ; public static String RubySearchResultPage_groupby_type_tooltip ; public static String Search_Error_openEditor_title ; public static String Search_Error_openEditor_message ; public static String FiltersDialogAction_label ; public static String FiltersDialog_limit_error ; public static String FiltersDialog_limit_label ; public static String FiltersDialog_description_label ; public static String FiltersDialog_filters_label ; public static String FiltersDialog_title ; public static String SearchLabelProvider_potential_singular ; public static String SearchLabelProvider_exact_singular ; public static String SearchLabelProvider_potential_noCount ; public static String SearchLabelProvider_exact_noCount ; public static String SearchLabelProvider_exact_and_potential_plural ; public static String SearchLabelProvider_potential_plural ; public static String SearchLabelProvider_exact_plural ; public static String group_references ; public static String group_readReferences ; public static String group_search ; public static String group_occurrences ; public static String group_declarations ; public static String group_writeReferences ; public static String group_occurrences_quickMenu_noEntriesAvailable ; public static String RubyElementAction_operationUnavailable_title ; public static String RubyElementAction_operationUnavailable_generic ; public static String RubyElementAction_error_open_message ; public static String RubyElementAction_typeSelectionDialog_title ; public static String RubyElementAction_typeSelectionDialog_message ; public static String RubyElementAction_operationUnavailable_field ; public static String SearchElementSelectionDialog_title ; public static String SearchElementSelectionDialog_message ; public static String Search_Error_search_title ; public static String Search_Error_codeResolve ; public static String Search_Error_search_notsuccessful_title ; public static String Search_Error_search_notsuccessful_message ; public static String Search_Error_search_message ; public static String Search_FindReferencesAction_label ; public static String Search_FindReferencesAction_tooltip ; public static String Search_FindReferencesInProjectAction_label ; public static String Search_FindReferencesInProjectAction_tooltip ; public static String Search_FindReferencesInWorkingSetAction_label ; public static String Search_FindReferencesInWorkingSetAction_tooltip ; public static String Search_FindReadReferencesAction_label ; public static String Search_FindReadReferencesAction_tooltip ; public static String Search_FindReadReferencesInProjectAction_label ; public static String Search_FindReadReferencesInProjectAction_tooltip ; public static String Search_FindReadReferencesInWorkingSetAction_label ; public static String Search_FindReadReferencesInWorkingSetAction_tooltip ; public static String OccurrencesFinder_searchfor ; public static String OccurrencesFinder_label_plural ; public static String OccurrencesFinder_label_singular ; public static String OccurrencesFinder_no_element ; public static String Search_FindOccurrencesInFile_tooltip ; public static String Search_FindOccurrencesInFile_label ; public static String Search_FindOccurrencesInFile_shortLabel ; public static String FindOccurrencesEngine_noSource_text ; public static String FindOccurrencesEngine_cannotParse_text ; public static String TextSearchLabelProvider_matchCountFormat ; public static String Search_FindDeclarationAction_label ; public static String Search_FindDeclarationAction_tooltip ; public static String Search_FindDeclarationsInProjectAction_label ; public static String Search_FindDeclarationsInProjectAction_tooltip ; public static String Search_FindDeclarationsInWorkingSetAction_label ; public static String Search_FindDeclarationsInWorkingSetAction_tooltip ; public static String Search_FindWriteReferencesAction_label ; public static String Search_FindWriteReferencesAction_tooltip ; public static String Search_FindWriteReferencesInWorkingSetAction_label ; public static String Search_FindWriteReferencesInWorkingSetAction_tooltip ; public static String Search_FindWriteReferencesInProjectAction_label ; public static String Search_FindWriteReferencesInProjectAction_tooltip ; public static String Search_FindHierarchyReferencesAction_label ; public static String Search_FindHierarchyReferencesAction_tooltip ; static { NLS . initializeMessages ( BUNDLE_NAME , SearchMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . Viewer ; public abstract class RubySearchContentProvider implements IStructuredContentProvider { protected final Object [ ] EMPTY_ARR = new Object [ ] ; protected RubySearchResult fResult ; private RubySearchResultPage fPage ; RubySearchContentProvider ( RubySearchResultPage page ) { fPage = page ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { initialize ( ( RubySearchResult ) newInput ) ; } protected void initialize ( RubySearchResult result ) { fResult = result ; } public abstract void elementsChanged ( Object [ ] updatedElements ) ; public abstract void clear ( ) ; public void filtersChanged ( MatchFilter [ ] filters ) { } public void dispose ( ) { } RubySearchResultPage getPage ( ) { return fPage ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . DialogPage ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . search . ui . ISearchPage ; import org . eclipse . search . ui . ISearchPageContainer ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . formatter . IndentManipulation ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . dialogs . TextFieldNavigationHandler ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . PatternQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class RubySearchPage extends DialogPage implements ISearchPage , IRubySearchConstants { private static class SearchPatternData { private int searchFor ; private int limitTo ; private String pattern ; private boolean isCaseSensitive ; private IRubyElement rubyElement ; private boolean includeRubyVMLibraries ; private int scope ; private IWorkingSet [ ] workingSets ; public SearchPatternData ( int searchFor , int limitTo , boolean isCaseSensitive , String pattern , IRubyElement element , boolean includeJRE ) { this ( searchFor , limitTo , pattern , isCaseSensitive , element , ISearchPageContainer . WORKSPACE_SCOPE , null , includeJRE ) ; } public SearchPatternData ( int searchFor , int limitTo , String pattern , boolean isCaseSensitive , IRubyElement element , int scope , IWorkingSet [ ] workingSets , boolean includeJRE ) { this . searchFor = searchFor ; this . limitTo = limitTo ; this . pattern = pattern ; this . isCaseSensitive = isCaseSensitive ; this . scope = scope ; this . workingSets = workingSets ; this . includeRubyVMLibraries = includeJRE ; setRubyElement ( element ) ; } public void setRubyElement ( IRubyElement rubyElement ) { this . rubyElement = rubyElement ; } public boolean isCaseSensitive ( ) { return isCaseSensitive ; } public IRubyElement getRubyElement ( ) { return rubyElement ; } public int getLimitTo ( ) { return limitTo ; } public String getPattern ( ) { return pattern ; } public int getScope ( ) { return scope ; } public int getSearchFor ( ) { return searchFor ; } public IWorkingSet [ ] getWorkingSets ( ) { return workingSets ; } public boolean includesRubyVMLibraries ( ) { return includeRubyVMLibraries ; } public void store ( IDialogSettings settings ) { settings . put ( "" , searchFor ) ; settings . put ( "" , scope ) ; settings . put ( "" , pattern ) ; settings . put ( "" , limitTo ) ; settings . put ( "" , rubyElement != null ? rubyElement . getHandleIdentifier ( ) : "" ) ; settings . put ( "" , isCaseSensitive ) ; if ( workingSets != null ) { String [ ] wsIds = new String [ workingSets . length ] ; for ( int i = ; i < workingSets . length ; i ++ ) { wsIds [ i ] = workingSets [ i ] . getName ( ) ; } settings . put ( "" , wsIds ) ; } else { settings . put ( "" , new String [ ] ) ; } settings . put ( "" , includeRubyVMLibraries ) ; } public static SearchPatternData create ( IDialogSettings settings ) { String pattern = settings . get ( "" ) ; if ( pattern . length ( ) == ) { return null ; } IRubyElement elem = null ; String handleId = settings . get ( "" ) ; if ( handleId != null && handleId . length ( ) > ) { IRubyElement restored = RubyCore . create ( handleId ) ; if ( restored != null && isSearchableType ( restored ) && restored . exists ( ) ) { elem = restored ; } } String [ ] wsIds = settings . getArray ( "" ) ; IWorkingSet [ ] workingSets = null ; if ( wsIds != null && wsIds . length > ) { IWorkingSetManager workingSetManager = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) ; workingSets = new IWorkingSet [ wsIds . length ] ; for ( int i = ; workingSets != null && i < wsIds . length ; i ++ ) { workingSets [ i ] = workingSetManager . getWorkingSet ( wsIds [ i ] ) ; if ( workingSets [ i ] == null ) { workingSets = null ; } } } try { int searchFor = settings . getInt ( "" ) ; int scope = settings . getInt ( "" ) ; int limitTo = settings . getInt ( "" ) ; boolean isCaseSensitive = settings . getBoolean ( "" ) ; boolean includeJRE ; if ( settings . get ( "" ) != null ) { includeJRE = settings . getBoolean ( "" ) ; } else { includeJRE = forceIncludeRubyVMLibraries ( limitTo ) ; } return new SearchPatternData ( searchFor , limitTo , pattern , isCaseSensitive , elem , scope , workingSets , includeJRE ) ; } catch ( NumberFormatException e ) { return null ; } } } public static final String PARTICIPANT_EXTENSION_POINT = "" ; public static final String EXTENSION_POINT_ID = "" ; private static final int HISTORY_SIZE = ; private final static String PAGE_NAME = "" ; private final static String STORE_CASE_SENSITIVE = "" ; private final static String STORE_HISTORY = "" ; private final static String STORE_HISTORY_SIZE = "" ; private final List fPreviousSearchPatterns ; private SearchPatternData fInitialData ; private IRubyElement fRubyElement ; private boolean fFirstTime = true ; private IDialogSettings fDialogSettings ; private boolean fIsCaseSensitive ; private Combo fPattern ; private ISearchPageContainer fContainer ; private Button fCaseSensitive ; private Button [ ] fSearchFor ; private String [ ] fSearchForText = { SearchMessages . SearchPage_searchFor_type , SearchMessages . SearchPage_searchFor_method , SearchMessages . SearchPage_searchFor_constructor , SearchMessages . SearchPage_searchFor_field } ; private Button [ ] fLimitTo ; private String [ ] fLimitToText = { SearchMessages . SearchPage_limitTo_declarations , SearchMessages . SearchPage_limitTo_references , SearchMessages . SearchPage_limitTo_allOccurrences , SearchMessages . SearchPage_limitTo_readReferences , SearchMessages . SearchPage_limitTo_writeReferences } ; private Button fIncludeRubyVMLibrariesCheckbox ; public RubySearchPage ( ) { fPreviousSearchPatterns = new ArrayList ( ) ; } public boolean performAction ( ) { return performNewSearch ( ) ; } private boolean performNewSearch ( ) { SearchPatternData data = getPatternData ( ) ; IRubySearchScope scope = null ; String scopeDescription = "" ; boolean includeRubyVMLibraries = data . includesRubyVMLibraries ( ) ; RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; switch ( getContainer ( ) . getSelectedScope ( ) ) { case ISearchPageContainer . WORKSPACE_SCOPE : scopeDescription = factory . getWorkspaceScopeDescription ( includeRubyVMLibraries ) ; scope = factory . createWorkspaceScope ( includeRubyVMLibraries ) ; break ; case ISearchPageContainer . SELECTION_SCOPE : IRubyElement [ ] javaElements = factory . getRubyElements ( getContainer ( ) . getSelection ( ) ) ; scope = factory . createRubySearchScope ( javaElements , includeRubyVMLibraries ) ; scopeDescription = factory . getSelectionScopeDescription ( javaElements , includeRubyVMLibraries ) ; break ; case ISearchPageContainer . SELECTED_PROJECTS_SCOPE : { String [ ] projectNames = getContainer ( ) . getSelectedProjectNames ( ) ; scope = factory . createRubyProjectSearchScope ( projectNames , includeRubyVMLibraries ) ; scopeDescription = factory . getProjectScopeDescription ( projectNames , includeRubyVMLibraries ) ; break ; } case ISearchPageContainer . WORKING_SET_SCOPE : { IWorkingSet [ ] workingSets = getContainer ( ) . getSelectedWorkingSets ( ) ; if ( workingSets == null || workingSets . length < ) return false ; scopeDescription = factory . getWorkingSetScopeDescription ( workingSets , includeRubyVMLibraries ) ; scope = factory . createRubySearchScope ( workingSets , includeRubyVMLibraries ) ; SearchUtil . updateLRUWorkingSets ( workingSets ) ; } } QuerySpecification querySpec = null ; if ( data . getRubyElement ( ) != null && getPattern ( ) . equals ( fInitialData . getPattern ( ) ) ) { querySpec = new ElementQuerySpecification ( data . getRubyElement ( ) , data . getLimitTo ( ) , scope , scopeDescription ) ; } else { querySpec = new PatternQuerySpecification ( data . getPattern ( ) , data . getSearchFor ( ) , data . isCaseSensitive ( ) , data . getLimitTo ( ) , scope , scopeDescription ) ; data . setRubyElement ( null ) ; } RubySearchQuery textSearchJob = new RubySearchQuery ( querySpec ) ; NewSearchUI . runQueryInBackground ( textSearchJob ) ; return true ; } private int getLimitTo ( ) { for ( int i = ; i < fLimitTo . length ; i ++ ) { if ( fLimitTo [ i ] . getSelection ( ) ) return i ; } return - ; } private void setLimitTo ( int searchFor , int limitTo ) { if ( ! ( searchFor == FIELD ) && ( limitTo == READ_ACCESSES || limitTo == WRITE_ACCESSES ) ) { limitTo = REFERENCES ; } for ( int i = ; i < fLimitTo . length ; i ++ ) { fLimitTo [ i ] . setSelection ( limitTo == i ) ; } fLimitTo [ DECLARATIONS ] . setEnabled ( true ) ; fLimitTo [ REFERENCES ] . setEnabled ( true ) ; fLimitTo [ ALL_OCCURRENCES ] . setEnabled ( true ) ; fLimitTo [ READ_ACCESSES ] . setEnabled ( searchFor == FIELD ) ; fLimitTo [ WRITE_ACCESSES ] . setEnabled ( searchFor == FIELD ) ; } private String [ ] getPreviousSearchPatterns ( ) { int patternCount = fPreviousSearchPatterns . size ( ) ; String [ ] patterns = new String [ patternCount ] ; for ( int i = ; i < patternCount ; i ++ ) patterns [ i ] = ( ( SearchPatternData ) fPreviousSearchPatterns . get ( i ) ) . getPattern ( ) ; return patterns ; } private int getSearchFor ( ) { for ( int i = ; i < fSearchFor . length ; i ++ ) { if ( fSearchFor [ i ] . getSelection ( ) ) return i ; } Assert . isTrue ( false , "" ) ; return - ; } private String getPattern ( ) { return fPattern . getText ( ) ; } private SearchPatternData findInPrevious ( String pattern ) { for ( Iterator iter = fPreviousSearchPatterns . iterator ( ) ; iter . hasNext ( ) ; ) { SearchPatternData element = ( SearchPatternData ) iter . next ( ) ; if ( pattern . equals ( element . getPattern ( ) ) ) { return element ; } } return null ; } private SearchPatternData getPatternData ( ) { String pattern = getPattern ( ) ; SearchPatternData match = findInPrevious ( pattern ) ; if ( match != null ) { fPreviousSearchPatterns . remove ( match ) ; } match = new SearchPatternData ( getSearchFor ( ) , getLimitTo ( ) , pattern , fCaseSensitive . getSelection ( ) , fRubyElement , getContainer ( ) . getSelectedScope ( ) , getContainer ( ) . getSelectedWorkingSets ( ) , fIncludeRubyVMLibrariesCheckbox . getSelection ( ) ) ; fPreviousSearchPatterns . add ( , match ) ; return match ; } public void setVisible ( boolean visible ) { if ( visible && fPattern != null ) { if ( fFirstTime ) { fFirstTime = false ; fPattern . setItems ( getPreviousSearchPatterns ( ) ) ; initSelections ( ) ; } fPattern . setFocus ( ) ; } updateOKStatus ( ) ; super . setVisible ( visible ) ; } public boolean isValid ( ) { return true ; } public void createControl ( Composite parent ) { initializeDialogUnits ( parent ) ; readConfiguration ( ) ; Composite result = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( , false ) ; layout . horizontalSpacing = ; result . setLayout ( layout ) ; Control expressionComposite = createExpression ( result ) ; expressionComposite . setLayoutData ( new GridData ( GridData . FILL , GridData . CENTER , true , false , , ) ) ; Label separator = new Label ( result , SWT . NONE ) ; separator . setVisible ( false ) ; GridData data = new GridData ( GridData . FILL , GridData . FILL , false , false , , ) ; data . heightHint = convertHeightInCharsToPixels ( ) / ; separator . setLayoutData ( data ) ; Control searchFor = createSearchFor ( result ) ; searchFor . setLayoutData ( new GridData ( GridData . FILL , GridData . FILL , true , false , , ) ) ; Control limitTo = createLimitTo ( result ) ; limitTo . setLayoutData ( new GridData ( GridData . FILL , GridData . FILL , true , false , , ) ) ; fIncludeRubyVMLibrariesCheckbox = new Button ( result , SWT . CHECK ) ; fIncludeRubyVMLibrariesCheckbox . setText ( SearchMessages . SearchPage_searchJRE_label ) ; fIncludeRubyVMLibrariesCheckbox . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , false , false , , ) ) ; SelectionAdapter rubyElementInitializer = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent event ) { if ( getSearchFor ( ) == fInitialData . getSearchFor ( ) ) fRubyElement = fInitialData . getRubyElement ( ) ; else fRubyElement = null ; setLimitTo ( getSearchFor ( ) , getLimitTo ( ) ) ; doPatternModified ( ) ; } } ; fSearchFor [ TYPE ] . addSelectionListener ( rubyElementInitializer ) ; fSearchFor [ METHOD ] . addSelectionListener ( rubyElementInitializer ) ; fSearchFor [ FIELD ] . addSelectionListener ( rubyElementInitializer ) ; fSearchFor [ CONSTRUCTOR ] . addSelectionListener ( rubyElementInitializer ) ; setControl ( result ) ; Dialog . applyDialogFont ( result ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( result , IRubyHelpContextIds . RUBY_SEARCH_PAGE ) ; } private Control createExpression ( Composite parent ) { Composite result = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( , false ) ; layout . marginWidth = ; layout . marginHeight = ; result . setLayout ( layout ) ; Label label = new Label ( result , SWT . LEFT ) ; label . setText ( SearchMessages . SearchPage_expression_label ) ; label . setLayoutData ( new GridData ( GridData . FILL , GridData . FILL , false , false , , ) ) ; fPattern = new Combo ( result , SWT . SINGLE | SWT . BORDER ) ; fPattern . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { handlePatternSelected ( ) ; updateOKStatus ( ) ; } } ) ; fPattern . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { doPatternModified ( ) ; updateOKStatus ( ) ; } } ) ; TextFieldNavigationHandler . install ( fPattern ) ; GridData data = new GridData ( GridData . FILL , GridData . FILL , true , false , , ) ; data . widthHint = convertWidthInCharsToPixels ( ) ; fPattern . setLayoutData ( data ) ; fCaseSensitive = new Button ( result , SWT . CHECK ) ; fCaseSensitive . setText ( SearchMessages . SearchPage_expression_caseSensitive ) ; fCaseSensitive . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fIsCaseSensitive = fCaseSensitive . getSelection ( ) ; } } ) ; fCaseSensitive . setLayoutData ( new GridData ( GridData . FILL , GridData . FILL , false , false , , ) ) ; return result ; } final void updateOKStatus ( ) { boolean isValid = isValidSearchPattern ( ) ; getContainer ( ) . setPerformActionEnabled ( isValid ) ; } private boolean isValidSearchPattern ( ) { if ( getPattern ( ) . length ( ) == ) { return false ; } if ( fRubyElement != null ) { return true ; } return SearchPattern . createPattern ( getPattern ( ) , getSearchFor ( ) , getLimitTo ( ) , SearchPattern . R_EXACT_MATCH ) != null ; } public void dispose ( ) { writeConfiguration ( ) ; super . dispose ( ) ; } private void doPatternModified ( ) { if ( fInitialData != null && getPattern ( ) . equals ( fInitialData . getPattern ( ) ) && fInitialData . getRubyElement ( ) != null && fInitialData . getSearchFor ( ) == getSearchFor ( ) ) { fCaseSensitive . setEnabled ( false ) ; fCaseSensitive . setSelection ( true ) ; fRubyElement = fInitialData . getRubyElement ( ) ; } else { fCaseSensitive . setEnabled ( true ) ; fCaseSensitive . setSelection ( fIsCaseSensitive ) ; fRubyElement = null ; } } private void handlePatternSelected ( ) { int selectionIndex = fPattern . getSelectionIndex ( ) ; if ( selectionIndex < || selectionIndex >= fPreviousSearchPatterns . size ( ) ) return ; SearchPatternData initialData = ( SearchPatternData ) fPreviousSearchPatterns . get ( selectionIndex ) ; setSearchFor ( initialData . getSearchFor ( ) ) ; setLimitTo ( initialData . getSearchFor ( ) , initialData . getLimitTo ( ) ) ; fPattern . setText ( initialData . getPattern ( ) ) ; fIsCaseSensitive = initialData . isCaseSensitive ( ) ; fRubyElement = initialData . getRubyElement ( ) ; fCaseSensitive . setEnabled ( fRubyElement == null ) ; fCaseSensitive . setSelection ( initialData . isCaseSensitive ( ) ) ; if ( initialData . getWorkingSets ( ) != null ) getContainer ( ) . setSelectedWorkingSets ( initialData . getWorkingSets ( ) ) ; else getContainer ( ) . setSelectedScope ( initialData . getScope ( ) ) ; fInitialData = initialData ; } private void setSearchFor ( int searchFor ) { for ( int i = ; i < fSearchFor . length ; i ++ ) { fSearchFor [ i ] . setSelection ( searchFor == i ) ; } } private Control createSearchFor ( Composite parent ) { Group result = new Group ( parent , SWT . NONE ) ; result . setText ( SearchMessages . SearchPage_searchFor_label ) ; result . setLayout ( new GridLayout ( , true ) ) ; fSearchFor = new Button [ fSearchForText . length ] ; for ( int i = ; i < fSearchForText . length ; i ++ ) { Button button = new Button ( result , SWT . RADIO ) ; button . setText ( fSearchForText [ i ] ) ; button . setSelection ( i == TYPE ) ; button . setLayoutData ( new GridData ( ) ) ; fSearchFor [ i ] = button ; } Label filler = new Label ( result , SWT . NONE ) ; filler . setVisible ( false ) ; filler . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , false , , ) ) ; return result ; } private Control createLimitTo ( Composite parent ) { Group result = new Group ( parent , SWT . NONE ) ; result . setText ( SearchMessages . SearchPage_limitTo_label ) ; result . setLayout ( new GridLayout ( , true ) ) ; SelectionAdapter listener = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { updateUseJRE ( ) ; } } ; fLimitTo = new Button [ fLimitToText . length ] ; for ( int i = ; i < fLimitToText . length ; i ++ ) { Button button = new Button ( result , SWT . RADIO ) ; button . setText ( fLimitToText [ i ] ) ; fLimitTo [ i ] = button ; button . setSelection ( i == REFERENCES ) ; button . addSelectionListener ( listener ) ; button . setLayoutData ( new GridData ( ) ) ; } return result ; } private void initSelections ( ) { ISelection sel = getContainer ( ) . getSelection ( ) ; SearchPatternData initData = null ; if ( sel instanceof IStructuredSelection ) { initData = tryStructuredSelection ( ( IStructuredSelection ) sel ) ; } else if ( sel instanceof ITextSelection ) { IEditorPart activePart = getActiveEditor ( ) ; if ( activePart instanceof RubyEditor ) { try { IRubyElement [ ] elements = SelectionConverter . codeResolve ( ( RubyEditor ) activePart ) ; if ( elements != null && elements . length > ) { initData = determineInitValuesFrom ( elements [ ] ) ; } } catch ( RubyModelException e ) { } } if ( initData == null ) { initData = trySimpleTextSelection ( ( ITextSelection ) sel ) ; } } if ( initData == null ) { initData = getDefaultInitValues ( ) ; } fInitialData = initData ; fRubyElement = initData . getRubyElement ( ) ; fCaseSensitive . setSelection ( initData . isCaseSensitive ( ) ) ; fCaseSensitive . setEnabled ( fRubyElement == null ) ; setSearchFor ( initData . getSearchFor ( ) ) ; setLimitTo ( initData . getSearchFor ( ) , initData . getLimitTo ( ) ) ; fPattern . setText ( initData . getPattern ( ) ) ; boolean forceIncludeRubyVMLibraries = forceIncludeRubyVMLibraries ( getLimitTo ( ) ) ; fIncludeRubyVMLibrariesCheckbox . setEnabled ( ! forceIncludeRubyVMLibraries ) ; fIncludeRubyVMLibrariesCheckbox . setSelection ( forceIncludeRubyVMLibraries || initData . includesRubyVMLibraries ( ) ) ; } private void updateUseJRE ( ) { boolean forceIncludeRubyVMLibraries = forceIncludeRubyVMLibraries ( getLimitTo ( ) ) ; fIncludeRubyVMLibrariesCheckbox . setEnabled ( ! forceIncludeRubyVMLibraries ) ; boolean isSelected = true ; if ( ! forceIncludeRubyVMLibraries ) { isSelected = fIncludeRubyVMLibrariesCheckbox . getSelection ( ) ; } else { isSelected = true ; } fIncludeRubyVMLibrariesCheckbox . setSelection ( isSelected ) ; } private static boolean forceIncludeRubyVMLibraries ( int limitTo ) { return limitTo == DECLARATIONS ; } private SearchPatternData tryStructuredSelection ( IStructuredSelection selection ) { if ( selection == null || selection . size ( ) > ) return null ; Object o = selection . getFirstElement ( ) ; SearchPatternData res = null ; if ( o instanceof IRubyElement ) { res = determineInitValuesFrom ( ( IRubyElement ) o ) ; } else if ( o instanceof IAdaptable ) { IRubyElement element = ( IRubyElement ) ( ( IAdaptable ) o ) . getAdapter ( IRubyElement . class ) ; if ( element != null ) { res = determineInitValuesFrom ( element ) ; } } if ( res == null && o instanceof IAdaptable ) { IWorkbenchAdapter adapter = ( IWorkbenchAdapter ) ( ( IAdaptable ) o ) . getAdapter ( IWorkbenchAdapter . class ) ; if ( adapter != null ) { return new SearchPatternData ( TYPE , REFERENCES , fIsCaseSensitive , adapter . getLabel ( o ) , null , false ) ; } } return res ; } final static boolean isSearchableType ( IRubyElement element ) { switch ( element . getElementType ( ) ) { case IRubyElement . SOURCE_FOLDER : case IRubyElement . IMPORT_DECLARATION : case IRubyElement . TYPE : case IRubyElement . FIELD : case IRubyElement . METHOD : return true ; } return false ; } private SearchPatternData determineInitValuesFrom ( IRubyElement element ) { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; boolean isInsideJRE = factory . isInsideRubyVMLibraries ( element ) ; switch ( element . getElementType ( ) ) { case IRubyElement . IMPORT_DECLARATION : { IImportDeclaration declaration = ( IImportDeclaration ) element ; return new SearchPatternData ( TYPE , DECLARATIONS , true , element . getElementName ( ) , element , true ) ; } case IRubyElement . TYPE : return new SearchPatternData ( TYPE , REFERENCES , true , PatternStrings . getTypeSignature ( ( IType ) element ) , element , isInsideJRE ) ; case IRubyElement . SCRIPT : { IType mainType = ( ( IRubyScript ) element ) . findPrimaryType ( ) ; if ( mainType != null ) { return new SearchPatternData ( TYPE , REFERENCES , true , PatternStrings . getTypeSignature ( mainType ) , mainType , isInsideJRE ) ; } break ; } case IRubyElement . FIELD : case IRubyElement . INSTANCE_VAR : case IRubyElement . LOCAL_VARIABLE : case IRubyElement . CLASS_VAR : case IRubyElement . GLOBAL : case IRubyElement . CONSTANT : return new SearchPatternData ( FIELD , REFERENCES , true , PatternStrings . getFieldSignature ( ( IField ) element ) , element , isInsideJRE ) ; case IRubyElement . METHOD : IMethod method = ( IMethod ) element ; int searchFor = method . isConstructor ( ) ? CONSTRUCTOR : METHOD ; return new SearchPatternData ( searchFor , REFERENCES , true , PatternStrings . getMethodSignature ( method ) , element , isInsideJRE ) ; } return null ; } private SearchPatternData trySimpleTextSelection ( ITextSelection selection ) { String selectedText = selection . getText ( ) ; if ( selectedText != null && selectedText . length ( ) > ) { int i = ; while ( i < selectedText . length ( ) && ! IndentManipulation . isLineDelimiterChar ( selectedText . charAt ( i ) ) ) { i ++ ; } if ( i > ) { return new SearchPatternData ( TYPE , REFERENCES , fIsCaseSensitive , selectedText . substring ( , i ) , null , true ) ; } } return null ; } private SearchPatternData getDefaultInitValues ( ) { if ( ! fPreviousSearchPatterns . isEmpty ( ) ) { return ( SearchPatternData ) fPreviousSearchPatterns . get ( ) ; } return new SearchPatternData ( TYPE , REFERENCES , fIsCaseSensitive , "" , null , false ) ; } public void setContainer ( ISearchPageContainer container ) { fContainer = container ; } private ISearchPageContainer getContainer ( ) { return fContainer ; } private IEditorPart getActiveEditor ( ) { IWorkbenchPage activePage = RubyPlugin . getActivePage ( ) ; if ( activePage != null ) { return activePage . getActiveEditor ( ) ; } return null ; } private IDialogSettings getDialogSettings ( ) { IDialogSettings settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; fDialogSettings = settings . getSection ( PAGE_NAME ) ; if ( fDialogSettings == null ) fDialogSettings = settings . addNewSection ( PAGE_NAME ) ; return fDialogSettings ; } private void readConfiguration ( ) { IDialogSettings s = getDialogSettings ( ) ; fIsCaseSensitive = s . getBoolean ( STORE_CASE_SENSITIVE ) ; try { int historySize = s . getInt ( STORE_HISTORY_SIZE ) ; for ( int i = ; i < historySize ; i ++ ) { IDialogSettings histSettings = s . getSection ( STORE_HISTORY + i ) ; if ( histSettings != null ) { SearchPatternData data = SearchPatternData . create ( histSettings ) ; if ( data != null ) { fPreviousSearchPatterns . add ( data ) ; } } } } catch ( NumberFormatException e ) { } } private void writeConfiguration ( ) { IDialogSettings s = getDialogSettings ( ) ; s . put ( STORE_CASE_SENSITIVE , fIsCaseSensitive ) ; int historySize = Math . min ( fPreviousSearchPatterns . size ( ) , HISTORY_SIZE ) ; s . put ( STORE_HISTORY_SIZE , historySize ) ; for ( int i = ; i < historySize ; i ++ ) { IDialogSettings histSettings = s . addNewSection ( STORE_HISTORY + i ) ; SearchPatternData data = ( ( SearchPatternData ) fPreviousSearchPatterns . get ( i ) ) ; data . store ( histSettings ) ; } } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class OpenRubySearchPageAction implements IWorkbenchWindowActionDelegate { private static final String RUBY_SEARCH_PAGE_ID = "" ; private IWorkbenchWindow fWindow ; public OpenRubySearchPageAction ( ) { } public void init ( IWorkbenchWindow window ) { fWindow = window ; } public void run ( IAction action ) { if ( fWindow == null || fWindow . getActivePage ( ) == null ) { beep ( ) ; RubyPlugin . logErrorMessage ( "" ) ; return ; } NewSearchUI . openSearchDialog ( fWindow , RUBY_SEARCH_PAGE_ID ) ; } public void selectionChanged ( IAction action , ISelection selection ) { } public void dispose ( ) { fWindow = null ; } protected void beep ( ) { Shell shell = RubyPlugin . getActiveWorkbenchShell ( ) ; if ( shell != null && shell . getDisplay ( ) != null ) shell . getDisplay ( ) . beep ( ) ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . ArrayList ; import java . util . HashMap ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . viewers . DecoratingLabelProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . search . ui . ISearchResult ; import org . eclipse . search . ui . ISearchResultViewPart ; import org . eclipse . search . ui . NewSearchUI ; import org . eclipse . search . ui . SearchResultEvent ; import org . eclipse . search . ui . text . AbstractTextSearchResult ; import org . eclipse . search . ui . text . AbstractTextSearchViewPage ; import org . eclipse . search . ui . text . Match ; import org . eclipse . swt . SWT ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . dialogs . PreferencesUtil ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . part . IPageSite ; import org . eclipse . ui . part . IShowInTargetList ; import org . eclipse . ui . part . ResourceTransfer ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . views . navigator . LocalSelectionTransfer ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . dnd . RdtViewerDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . ResourceTransferDragAdapter ; import org . rubypeople . rdt . internal . ui . packageview . SelectionTransferDragAdapter ; import org . rubypeople . rdt . internal . ui . search . RubySearchResult . MatchFilterEvent ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTableViewer ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTreeViewer ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . search . IMatchPresentation ; import com . ibm . icu . text . Collator ; public class RubySearchResultPage extends AbstractTextSearchViewPage implements IAdaptable { public static class DecoratorIgnoringViewerSorter extends ViewerSorter { private final ILabelProvider fLabelProvider ; private Collator fNewCollator ; public DecoratorIgnoringViewerSorter ( ILabelProvider labelProvider ) { super ( null ) ; fLabelProvider = labelProvider ; fNewCollator = null ; } public int compare ( Viewer viewer , Object e1 , Object e2 ) { String name1 = fLabelProvider . getText ( e1 ) ; String name2 = fLabelProvider . getText ( e2 ) ; if ( name1 == null ) name1 = "" ; if ( name2 == null ) name2 = "" ; return getNewCollator ( ) . compare ( name1 , name2 ) ; } public final java . text . Collator getCollator ( ) { if ( collator == null ) { collator = java . text . Collator . getInstance ( ) ; } return collator ; } private final Collator getNewCollator ( ) { if ( fNewCollator == null ) { fNewCollator = Collator . getInstance ( ) ; } return fNewCollator ; } } private static final int DEFAULT_ELEMENT_LIMIT = ; private static final String FALSE = "" ; private static final String TRUE = "" ; private static final String KEY_GROUPING = "" ; private static final String KEY_SORTING = "" ; private static final String KEY_LIMIT_ENABLED = "" ; private static final String KEY_LIMIT = "" ; private static final String GROUP_GROUPING = "" ; private static final String GROUP_FILTERING = "" ; private NewSearchViewActionGroup fActionGroup ; private RubySearchContentProvider fContentProvider ; private int fCurrentSortOrder ; private SortAction fSortByNameAction ; private SortAction fSortByParentName ; private SortAction fSortByPathAction ; private GroupAction fGroupTypeAction ; private GroupAction fGroupFileAction ; private GroupAction fGroupPackageAction ; private GroupAction fGroupProjectAction ; private int fCurrentGrouping ; private FilterAction [ ] fFilterActions ; private FiltersDialogAction fFilterDialogAction ; private static final String [ ] SHOW_IN_TARGETS = new String [ ] { RubyUI . ID_RUBY_EXPLORER , IPageLayout . ID_RES_NAV } ; public static final IShowInTargetList SHOW_IN_TARGET_LIST = new IShowInTargetList ( ) { public String [ ] getShowInTargetIds ( ) { return SHOW_IN_TARGETS ; } } ; private RubySearchEditorOpener fEditorOpener = new RubySearchEditorOpener ( ) ; private boolean fLimitElements = false ; private int fElementLimit ; public RubySearchResultPage ( ) { initSortActions ( ) ; initGroupingActions ( ) ; initFilterActions ( ) ; } private void initFilterActions ( ) { MatchFilter [ ] allFilters = MatchFilter . allFilters ( ) ; fFilterActions = new FilterAction [ allFilters . length ] ; for ( int i = ; i < fFilterActions . length ; i ++ ) { fFilterActions [ i ] = new FilterAction ( this , allFilters [ i ] ) ; fFilterActions [ i ] . setId ( "" + i ) ; } fFilterDialogAction = new FiltersDialogAction ( this ) ; fFilterDialogAction . setId ( "" + allFilters . length ) ; RubyPluginImages . setLocalImageDescriptors ( fFilterDialogAction , "" ) ; } private void initSortActions ( ) { fSortByNameAction = new SortAction ( SearchMessages . RubySearchResultPage_sortByName , this , SortingLabelProvider . SHOW_ELEMENT_CONTAINER ) ; fSortByPathAction = new SortAction ( SearchMessages . RubySearchResultPage_sortByPath , this , SortingLabelProvider . SHOW_PATH ) ; fSortByParentName = new SortAction ( SearchMessages . RubySearchResultPage_sortByParentName , this , SortingLabelProvider . SHOW_CONTAINER_ELEMENT ) ; } private void initGroupingActions ( ) { fGroupProjectAction = new GroupAction ( SearchMessages . RubySearchResultPage_groupby_project , SearchMessages . RubySearchResultPage_groupby_project_tooltip , this , LevelTreeContentProvider . LEVEL_PROJECT ) ; RubyPluginImages . setLocalImageDescriptors ( fGroupProjectAction , "" ) ; fGroupPackageAction = new GroupAction ( SearchMessages . RubySearchResultPage_groupby_package , SearchMessages . RubySearchResultPage_groupby_package_tooltip , this , LevelTreeContentProvider . LEVEL_PACKAGE ) ; RubyPluginImages . setLocalImageDescriptors ( fGroupPackageAction , "" ) ; fGroupFileAction = new GroupAction ( SearchMessages . RubySearchResultPage_groupby_file , SearchMessages . RubySearchResultPage_groupby_file_tooltip , this , LevelTreeContentProvider . LEVEL_FILE ) ; RubyPluginImages . setLocalImageDescriptors ( fGroupFileAction , "" ) ; fGroupTypeAction = new GroupAction ( SearchMessages . RubySearchResultPage_groupby_type , SearchMessages . RubySearchResultPage_groupby_type_tooltip , this , LevelTreeContentProvider . LEVEL_TYPE ) ; RubyPluginImages . setLocalImageDescriptors ( fGroupTypeAction , "" ) ; } public void setViewPart ( ISearchResultViewPart part ) { super . setViewPart ( part ) ; fActionGroup = new NewSearchViewActionGroup ( part ) ; } public void showMatch ( Match match , int offset , int length , boolean activate ) throws PartInitException { IEditorPart editor ; try { editor = fEditorOpener . openMatch ( match ) ; } catch ( RubyModelException e ) { throw new PartInitException ( e . getStatus ( ) ) ; } if ( editor != null && activate ) editor . getEditorSite ( ) . getPage ( ) . activate ( editor ) ; Object element = match . getElement ( ) ; if ( editor instanceof ITextEditor ) { ITextEditor textEditor = ( ITextEditor ) editor ; textEditor . selectAndReveal ( offset , length ) ; } else if ( editor != null ) { if ( element instanceof IFile ) { IFile file = ( IFile ) element ; showWithMarker ( editor , file , offset , length ) ; } } else { RubySearchResult result = ( RubySearchResult ) getInput ( ) ; IMatchPresentation participant = result . getSearchParticpant ( element ) ; if ( participant != null ) participant . showMatch ( match , offset , length , activate ) ; } } private void showWithMarker ( IEditorPart editor , IFile file , int offset , int length ) throws PartInitException { try { IMarker marker = file . createMarker ( NewSearchUI . SEARCH_MARKER ) ; HashMap attributes = new HashMap ( ) ; attributes . put ( IMarker . CHAR_START , new Integer ( offset ) ) ; attributes . put ( IMarker . CHAR_END , new Integer ( offset + length ) ) ; marker . setAttributes ( attributes ) ; IDE . gotoMarker ( editor , marker ) ; marker . delete ( ) ; } catch ( CoreException e ) { throw new PartInitException ( SearchMessages . RubySearchResultPage_error_marker , e ) ; } } protected void fillContextMenu ( IMenuManager mgr ) { super . fillContextMenu ( mgr ) ; addSortActions ( mgr ) ; fActionGroup . setContext ( new ActionContext ( getSite ( ) . getSelectionProvider ( ) . getSelection ( ) ) ) ; fActionGroup . fillContextMenu ( mgr ) ; } private void addSortActions ( IMenuManager mgr ) { if ( getLayout ( ) != FLAG_LAYOUT_FLAT ) return ; MenuManager sortMenu = new MenuManager ( SearchMessages . RubySearchResultPage_sortBylabel ) ; sortMenu . add ( fSortByNameAction ) ; sortMenu . add ( fSortByPathAction ) ; sortMenu . add ( fSortByParentName ) ; fSortByNameAction . setChecked ( fCurrentSortOrder == fSortByNameAction . getSortOrder ( ) ) ; fSortByPathAction . setChecked ( fCurrentSortOrder == fSortByPathAction . getSortOrder ( ) ) ; fSortByParentName . setChecked ( fCurrentSortOrder == fSortByParentName . getSortOrder ( ) ) ; mgr . appendToGroup ( IContextMenuConstants . GROUP_VIEWER_SETUP , sortMenu ) ; } protected void fillToolbar ( IToolBarManager tbm ) { super . fillToolbar ( tbm ) ; if ( getLayout ( ) != FLAG_LAYOUT_FLAT ) addGroupActions ( tbm ) ; } private void addGroupActions ( IToolBarManager mgr ) { mgr . appendToGroup ( IContextMenuConstants . GROUP_VIEWER_SETUP , new Separator ( GROUP_GROUPING ) ) ; mgr . appendToGroup ( GROUP_GROUPING , fGroupProjectAction ) ; mgr . appendToGroup ( GROUP_GROUPING , fGroupPackageAction ) ; mgr . appendToGroup ( GROUP_GROUPING , fGroupFileAction ) ; mgr . appendToGroup ( GROUP_GROUPING , fGroupTypeAction ) ; updateGroupingActions ( ) ; } private void updateGroupingActions ( ) { fGroupProjectAction . setChecked ( fCurrentGrouping == LevelTreeContentProvider . LEVEL_PROJECT ) ; fGroupPackageAction . setChecked ( fCurrentGrouping == LevelTreeContentProvider . LEVEL_PACKAGE ) ; fGroupFileAction . setChecked ( fCurrentGrouping == LevelTreeContentProvider . LEVEL_FILE ) ; fGroupTypeAction . setChecked ( fCurrentGrouping == LevelTreeContentProvider . LEVEL_TYPE ) ; } public void dispose ( ) { fActionGroup . dispose ( ) ; super . dispose ( ) ; } protected void elementsChanged ( Object [ ] objects ) { if ( fContentProvider != null ) fContentProvider . elementsChanged ( objects ) ; } protected void clear ( ) { if ( fContentProvider != null ) fContentProvider . clear ( ) ; } private void addDragAdapters ( StructuredViewer viewer ) { Transfer [ ] transfers = new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) , ResourceTransfer . getInstance ( ) } ; int ops = DND . DROP_COPY | DND . DROP_LINK ; TransferDragSourceListener [ ] dragListeners = new TransferDragSourceListener [ ] { new SelectionTransferDragAdapter ( viewer ) , new ResourceTransferDragAdapter ( viewer ) } ; viewer . addDragSupport ( ops , transfers , new RdtViewerDragAdapter ( viewer , dragListeners ) ) ; } protected void configureTableViewer ( TableViewer viewer ) { viewer . setUseHashlookup ( true ) ; SortingLabelProvider sortingLabelProvider = new SortingLabelProvider ( this ) ; viewer . setLabelProvider ( new ColorDecoratingLabelProvider ( sortingLabelProvider , PlatformUI . getWorkbench ( ) . getDecoratorManager ( ) . getLabelDecorator ( ) ) ) ; fContentProvider = new RubySearchTableContentProvider ( this ) ; viewer . setContentProvider ( fContentProvider ) ; viewer . setSorter ( new DecoratorIgnoringViewerSorter ( sortingLabelProvider ) ) ; setSortOrder ( fCurrentSortOrder ) ; addDragAdapters ( viewer ) ; } protected void configureTreeViewer ( TreeViewer viewer ) { PostfixLabelProvider postfixLabelProvider = new PostfixLabelProvider ( this ) ; viewer . setUseHashlookup ( true ) ; viewer . setSorter ( new DecoratorIgnoringViewerSorter ( postfixLabelProvider ) ) ; viewer . setLabelProvider ( new ColorDecoratingLabelProvider ( postfixLabelProvider , PlatformUI . getWorkbench ( ) . getDecoratorManager ( ) . getLabelDecorator ( ) ) ) ; fContentProvider = new LevelTreeContentProvider ( this , fCurrentGrouping ) ; viewer . setContentProvider ( fContentProvider ) ; addDragAdapters ( viewer ) ; } protected TreeViewer createTreeViewer ( Composite parent ) { return new ProblemTreeViewer ( parent , SWT . MULTI | SWT . H_SCROLL | SWT . V_SCROLL ) { public void add ( Object parentElement , Object [ ] childElements ) { if ( limitElements ( ) && parentElement . equals ( getInput ( ) ) ) { int elementLimit = getElementLimit ( ) ; Widget parentWidget = findItem ( parentElement ) ; if ( parentWidget == null ) return ; Item [ ] children = getChildren ( parentWidget ) ; if ( children . length >= elementLimit ) return ; if ( children . length + childElements . length <= elementLimit ) { super . add ( parentElement , childElements ) ; return ; } int toAdd = elementLimit - children . length ; Object [ ] limited = new Object [ toAdd ] ; System . arraycopy ( childElements , , limited , , limited . length ) ; super . add ( parentElement , limited ) ; return ; } else { super . add ( parentElement , childElements ) ; } } protected Object [ ] getFilteredChildren ( Object parentElement ) { if ( parentElement == null ) return new Object [ ] ; Object [ ] filtered = super . getFilteredChildren ( parentElement ) ; int elementLimit = getElementLimit ( ) ; if ( limitElements ( ) && parentElement . equals ( getInput ( ) ) && filtered . length > elementLimit ) { Object [ ] limited = new Object [ elementLimit ] ; System . arraycopy ( filtered , , limited , , limited . length ) ; return limited ; } else return filtered ; } } ; } public Integer getElementLimit ( ) { return fElementLimit ; } protected TableViewer createTableViewer ( Composite parent ) { return new ProblemTableViewer ( parent , SWT . MULTI | SWT . H_SCROLL | SWT . V_SCROLL ) { public void add ( Object [ ] elements ) { if ( limitElements ( ) ) { int elementLimit = getElementLimit ( ) ; int currentCount = getTable ( ) . getItemCount ( ) ; if ( currentCount >= elementLimit ) return ; if ( currentCount + elements . length <= elementLimit ) { super . add ( elements ) ; return ; } int toAdd = elementLimit - currentCount ; Object [ ] limited = new Object [ toAdd ] ; System . arraycopy ( elements , , limited , , limited . length ) ; super . add ( limited ) ; return ; } else { super . add ( elements ) ; } } protected Object [ ] getFilteredChildren ( Object parentElement ) { if ( parentElement == null ) return new Object [ ] ; Object [ ] filtered = super . getFilteredChildren ( parentElement ) ; int elementLimit = getElementLimit ( ) ; if ( limitElements ( ) && parentElement . equals ( getInput ( ) ) && filtered . length > elementLimit ) { Object [ ] limited = new Object [ elementLimit ] ; System . arraycopy ( filtered , , limited , , limited . length ) ; return limited ; } else return filtered ; } } ; } void setSortOrder ( int order ) { fCurrentSortOrder = order ; StructuredViewer viewer = getViewer ( ) ; viewer . getControl ( ) . setRedraw ( false ) ; DecoratingLabelProvider dlp = ( DecoratingLabelProvider ) viewer . getLabelProvider ( ) ; ( ( SortingLabelProvider ) dlp . getLabelProvider ( ) ) . setOrder ( order ) ; viewer . getControl ( ) . setRedraw ( true ) ; viewer . refresh ( ) ; getSettings ( ) . put ( KEY_SORTING , fCurrentSortOrder ) ; } public void init ( IPageSite site ) { super . init ( site ) ; IMenuManager menuManager = site . getActionBars ( ) . getMenuManager ( ) ; menuManager . insertBefore ( IContextMenuConstants . GROUP_PROPERTIES , new Separator ( GROUP_FILTERING ) ) ; fActionGroup . fillActionBars ( site . getActionBars ( ) ) ; menuManager . appendToGroup ( GROUP_FILTERING , fFilterDialogAction ) ; menuManager . appendToGroup ( IContextMenuConstants . GROUP_PROPERTIES , new Action ( SearchMessages . RubySearchResultPage_preferences_label ) { public void run ( ) { String pageId = "" ; PreferencesUtil . createPreferenceDialogOn ( RubyPlugin . getActiveWorkbenchShell ( ) , pageId , null , null ) . open ( ) ; } } ) ; } void setGrouping ( int grouping ) { fCurrentGrouping = grouping ; StructuredViewer viewer = getViewer ( ) ; LevelTreeContentProvider cp = ( LevelTreeContentProvider ) viewer . getContentProvider ( ) ; cp . setLevel ( grouping ) ; updateGroupingActions ( ) ; getSettings ( ) . put ( KEY_GROUPING , fCurrentGrouping ) ; getViewPart ( ) . updateLabel ( ) ; } protected StructuredViewer getViewer ( ) { return super . getViewer ( ) ; } public void restoreState ( IMemento memento ) { super . restoreState ( memento ) ; try { fCurrentSortOrder = getSettings ( ) . getInt ( KEY_SORTING ) ; } catch ( NumberFormatException e ) { fCurrentSortOrder = SortingLabelProvider . SHOW_ELEMENT_CONTAINER ; } try { fCurrentGrouping = getSettings ( ) . getInt ( KEY_GROUPING ) ; } catch ( NumberFormatException e ) { fCurrentGrouping = LevelTreeContentProvider . LEVEL_PACKAGE ; } fLimitElements = ! FALSE . equals ( getSettings ( ) . get ( KEY_LIMIT_ENABLED ) ) ; try { fElementLimit = getSettings ( ) . getInt ( KEY_LIMIT ) ; } catch ( NumberFormatException e ) { fElementLimit = DEFAULT_ELEMENT_LIMIT ; } if ( memento != null ) { Integer value = memento . getInteger ( KEY_GROUPING ) ; if ( value != null ) fCurrentGrouping = value . intValue ( ) ; value = memento . getInteger ( KEY_SORTING ) ; if ( value != null ) fCurrentSortOrder = value . intValue ( ) ; fLimitElements = ! FALSE . equals ( memento . getString ( KEY_LIMIT_ENABLED ) ) ; value = memento . getInteger ( KEY_LIMIT ) ; if ( value != null ) fElementLimit = value . intValue ( ) ; } } public void saveState ( IMemento memento ) { super . saveState ( memento ) ; memento . putInteger ( KEY_GROUPING , fCurrentGrouping ) ; memento . putInteger ( KEY_SORTING , fCurrentSortOrder ) ; if ( fLimitElements ) memento . putString ( KEY_LIMIT_ENABLED , TRUE ) ; else memento . putString ( KEY_LIMIT_ENABLED , FALSE ) ; memento . putInteger ( KEY_LIMIT , getElementLimit ( ) ) ; } void enableLimit ( boolean enable ) { fLimitElements = enable ; if ( fLimitElements ) getSettings ( ) . put ( KEY_LIMIT_ENABLED , TRUE ) ; else getSettings ( ) . put ( KEY_LIMIT_ENABLED , FALSE ) ; limitChanged ( ) ; } private void limitChanged ( ) { getViewer ( ) . refresh ( ) ; getViewPart ( ) . updateLabel ( ) ; } boolean limitElements ( ) { return fLimitElements ; } void removeMatchFilter ( MatchFilter filter ) { String id = filter . getID ( ) ; MatchFilter [ ] matchFilters = getMatchFilters ( ) ; ArrayList res = new ArrayList ( matchFilters . length ) ; for ( int i = ; i < matchFilters . length ; i ++ ) { if ( ! id . equals ( matchFilters [ i ] . getID ( ) ) ) { res . add ( matchFilters [ i ] ) ; } } MatchFilter [ ] newFilters = ( MatchFilter [ ] ) res . toArray ( new MatchFilter [ res . size ( ) ] ) ; setFilters ( newFilters ) ; } void addMatchFilter ( MatchFilter filter ) { String id = filter . getID ( ) ; MatchFilter [ ] matchFilters = getMatchFilters ( ) ; ArrayList res = new ArrayList ( matchFilters . length ) ; for ( int i = ; i < matchFilters . length ; i ++ ) { if ( ! id . equals ( matchFilters [ i ] . getID ( ) ) ) { res . add ( matchFilters [ i ] ) ; } } res . add ( filter ) ; MatchFilter [ ] newFilters = ( MatchFilter [ ] ) res . toArray ( new MatchFilter [ res . size ( ) ] ) ; setFilters ( newFilters ) ; } protected synchronized void handleSearchResultChanged ( SearchResultEvent e ) { super . handleSearchResultChanged ( e ) ; if ( e instanceof MatchFilterEvent ) { filtersChanged ( ( ( MatchFilterEvent ) e ) . getActivatedFilters ( ) ) ; } } private void filtersChanged ( MatchFilter [ ] newFilters ) { StructuredViewer viewer = getViewer ( ) ; RubySearchContentProvider cp = ( RubySearchContentProvider ) viewer . getContentProvider ( ) ; cp . filtersChanged ( getMatchFilters ( ) ) ; updateFilterActions ( ) ; getViewer ( ) . refresh ( ) ; getViewPart ( ) . updateLabel ( ) ; } private void updateFilterActions ( ) { IMenuManager menu = getSite ( ) . getActionBars ( ) . getMenuManager ( ) ; for ( int i = ; i < fFilterActions . length ; i ++ ) { fFilterActions [ i ] . updateCheckState ( ) ; } getSite ( ) . getActionBars ( ) . updateActionBars ( ) ; menu . updateAll ( true ) ; } boolean hasMatchFilter ( MatchFilter filter ) { RubySearchResult input = ( RubySearchResult ) getInput ( ) ; if ( input != null ) { return ( input ) . hasMatchFilterActivated ( filter ) ; } return false ; } MatchFilter [ ] getMatchFilters ( ) { RubySearchResult input = ( RubySearchResult ) getInput ( ) ; if ( input != null ) { return input . getActivatedMatchFilters ( ) ; } return new MatchFilter [ ] ; } public int getDisplayedMatchCount ( Object element ) { if ( getMatchFilters ( ) . length == ) return super . getDisplayedMatchCount ( element ) ; Match [ ] matches = super . getDisplayedMatches ( element ) ; int count = ; for ( int i = ; i < matches . length ; i ++ ) { if ( ! matches [ i ] . isFiltered ( ) ) count ++ ; } return count ; } public Match [ ] getDisplayedMatches ( Object element ) { if ( getMatchFilters ( ) . length == ) return super . getDisplayedMatches ( element ) ; Match [ ] matches = super . getDisplayedMatches ( element ) ; int count = ; for ( int i = ; i < matches . length ; i ++ ) { if ( matches [ i ] . isFiltered ( ) ) matches [ i ] = null ; else count ++ ; } Match [ ] filteredMatches = new Match [ count ] ; int writeIndex = ; for ( int i = ; i < matches . length ; i ++ ) { if ( matches [ i ] != null ) filteredMatches [ writeIndex ++ ] = matches [ i ] ; } return filteredMatches ; } public void setInput ( ISearchResult search , Object viewState ) { super . setInput ( search , viewState ) ; RubySearchResult input = ( RubySearchResult ) search ; updateFilterEnablement ( input ) ; } private void updateFilterEnablement ( RubySearchResult result ) { IActionBars bars = getSite ( ) . getActionBars ( ) ; IMenuManager menu = bars . getMenuManager ( ) ; for ( int i = ; i < fFilterActions . length ; i ++ ) { menu . remove ( fFilterActions [ i ] . getId ( ) ) ; } for ( int i = fFilterActions . length - ; i >= ; i -- ) { FilterAction filterAction = fFilterActions [ i ] ; if ( shouldEnable ( result , filterAction ) ) menu . prependToGroup ( GROUP_FILTERING , filterAction ) ; filterAction . updateCheckState ( ) ; } menu . updateAll ( true ) ; bars . updateActionBars ( ) ; } private boolean shouldEnable ( RubySearchResult result , FilterAction filterAction ) { if ( result == null ) { return false ; } RubySearchQuery query = ( RubySearchQuery ) result . getQuery ( ) ; if ( query == null ) return false ; return filterAction . getFilter ( ) . isApplicable ( query ) ; } private boolean isQueryRunning ( ) { AbstractTextSearchResult result = getInput ( ) ; if ( result != null ) { return NewSearchUI . isQueryRunning ( result . getQuery ( ) ) ; } return false ; } public String getLabel ( ) { String label = super . getLabel ( ) ; if ( getInput ( ) != null ) { int filteredOut = getInput ( ) . getMatchCount ( ) - getFilteredMatchCount ( ) ; if ( filteredOut > || getMatchFiltersCount ( ) > ) { if ( isQueryRunning ( ) ) { String message = SearchMessages . RubySearchResultPage_filtered_message ; return Messages . format ( message , new Object [ ] { label } ) ; } else { String message = SearchMessages . RubySearchResultPage_filteredWithCount_message ; return Messages . format ( message , new Object [ ] { label , String . valueOf ( filteredOut ) } ) ; } } } return label ; } private int getMatchFiltersCount ( ) { MatchFilter [ ] filters = getMatchFilters ( ) ; AbstractTextSearchResult result = getInput ( ) ; if ( result == null ) return ; int filterCount = ; for ( int i = ; i < filters . length ; i ++ ) { if ( filters [ i ] . isApplicable ( ( RubySearchQuery ) result . getQuery ( ) ) ) filterCount ++ ; } return filterCount ; } private int getFilteredMatchCount ( ) { StructuredViewer viewer = getViewer ( ) ; if ( viewer instanceof TreeViewer ) { ITreeContentProvider tp = ( ITreeContentProvider ) viewer . getContentProvider ( ) ; return getMatchCount ( tp , getRootElements ( ( TreeViewer ) getViewer ( ) ) ) ; } else { return getMatchCount ( ( TableViewer ) viewer ) ; } } private Object [ ] getRootElements ( TreeViewer viewer ) { Tree t = viewer . getTree ( ) ; Item [ ] roots = t . getItems ( ) ; Object [ ] elements = new Object [ roots . length ] ; for ( int i = ; i < elements . length ; i ++ ) { elements [ i ] = roots [ i ] . getData ( ) ; } return elements ; } private Object [ ] getRootElements ( TableViewer viewer ) { Table t = viewer . getTable ( ) ; Item [ ] roots = t . getItems ( ) ; Object [ ] elements = new Object [ roots . length ] ; for ( int i = ; i < elements . length ; i ++ ) { elements [ i ] = roots [ i ] . getData ( ) ; } return elements ; } private int getMatchCount ( ITreeContentProvider cp , Object [ ] elements ) { int count = ; for ( int j = ; j < elements . length ; j ++ ) { count += getDisplayedMatchCount ( elements [ j ] ) ; Object [ ] children = cp . getChildren ( elements [ j ] ) ; count += getMatchCount ( cp , children ) ; } return count ; } private int getMatchCount ( TableViewer viewer ) { Object [ ] elements = getRootElements ( viewer ) ; int count = ; for ( int i = ; i < elements . length ; i ++ ) { count += getDisplayedMatchCount ( elements [ i ] ) ; } return count ; } public Object getAdapter ( Class adapter ) { if ( IShowInTargetList . class . equals ( adapter ) ) { return SHOW_IN_TARGET_LIST ; } return null ; } protected void handleOpen ( OpenEvent event ) { Object firstElement = ( ( IStructuredSelection ) event . getSelection ( ) ) . getFirstElement ( ) ; if ( firstElement instanceof IRubyScript || firstElement instanceof IMember ) { if ( getDisplayedMatchCount ( firstElement ) == ) { try { fEditorOpener . openElement ( firstElement ) ; } catch ( CoreException e ) { ExceptionHandler . handle ( e , getSite ( ) . getShell ( ) , SearchMessages . RubySearchResultPage_open_editor_error_title , SearchMessages . RubySearchResultPage_open_editor_error_message ) ; } return ; } } super . handleOpen ( event ) ; } public void setFilters ( MatchFilter [ ] enabledFilters ) { RubySearchResult input = ( RubySearchResult ) getInput ( ) ; if ( input != null ) { input . setActivatedFilters ( enabledFilters ) ; } } void setElementLimit ( int elementLimit ) { fElementLimit = elementLimit ; getSettings ( ) . put ( KEY_LIMIT , elementLimit ) ; limitChanged ( ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . search . ui . ISearchPageScoreComputer ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptEditorInput ; public class RubySearchPageScoreComputer implements ISearchPageScoreComputer { public int computeScore ( String id , Object element ) { if ( ! RubySearchPage . EXTENSION_POINT_ID . equals ( id ) ) return ISearchPageScoreComputer . UNKNOWN ; if ( element instanceof IRubyElement || element instanceof IRubyScriptEditorInput ) return ; return ISearchPageScoreComputer . LOWEST ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IPath ; import org . eclipse . debug . internal . ui . launchConfigurations . WorkingSetComparator ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . IWorkingSetSelectionDialog ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . RubyUI ; public class RubySearchScopeFactory { private static RubySearchScopeFactory fgInstance ; private final IRubySearchScope EMPTY_SCOPE = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { } ) ; private RubySearchScopeFactory ( ) { } public static RubySearchScopeFactory getInstance ( ) { if ( fgInstance == null ) fgInstance = new RubySearchScopeFactory ( ) ; return fgInstance ; } public IWorkingSet [ ] queryWorkingSets ( ) throws RubyModelException { Shell shell = RubyPlugin . getActiveWorkbenchShell ( ) ; if ( shell == null ) return null ; IWorkingSetSelectionDialog dialog = PlatformUI . getWorkbench ( ) . getWorkingSetManager ( ) . createWorkingSetSelectionDialog ( shell , true ) ; if ( dialog . open ( ) == Window . OK ) { IWorkingSet [ ] workingSets = dialog . getSelection ( ) ; if ( workingSets . length > ) return workingSets ; } return null ; } public IRubySearchScope createRubySearchScope ( IWorkingSet [ ] workingSets , boolean includeRubyVMLibraries ) { if ( workingSets == null || workingSets . length < ) return EMPTY_SCOPE ; Set rubyElements = new HashSet ( workingSets . length * ) ; for ( int i = ; i < workingSets . length ; i ++ ) { IWorkingSet workingSet = workingSets [ i ] ; if ( workingSet . isEmpty ( ) && workingSet . isAggregateWorkingSet ( ) ) { return createWorkspaceScope ( includeRubyVMLibraries ) ; } addRubyElements ( rubyElements , workingSet ) ; } return createRubySearchScope ( rubyElements , includeRubyVMLibraries ) ; } public IRubySearchScope createRubySearchScope ( IWorkingSet workingSet , boolean includeRubyVMLibraries ) { Set rubyElements = new HashSet ( ) ; if ( workingSet . isEmpty ( ) && workingSet . isAggregateWorkingSet ( ) ) { return createWorkspaceScope ( includeRubyVMLibraries ) ; } addRubyElements ( rubyElements , workingSet ) ; return createRubySearchScope ( rubyElements , includeRubyVMLibraries ) ; } public IRubySearchScope createRubySearchScope ( IResource [ ] resources , boolean includeRubyVMLibraries ) { if ( resources == null ) return EMPTY_SCOPE ; Set rubyElements = new HashSet ( resources . length ) ; addRubyElements ( rubyElements , resources ) ; return createRubySearchScope ( rubyElements , includeRubyVMLibraries ) ; } public IRubySearchScope createRubySearchScope ( ISelection selection , boolean includeRubyVMLibraries ) { return createRubySearchScope ( getRubyElements ( selection ) , includeRubyVMLibraries ) ; } public IRubySearchScope createRubyProjectSearchScope ( String [ ] projectNames , boolean includeRubyVMLibraries ) { ArrayList res = new ArrayList ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( int i = ; i < projectNames . length ; i ++ ) { IRubyProject project = RubyCore . create ( root . getProject ( projectNames [ i ] ) ) ; if ( project . exists ( ) ) { res . add ( project ) ; } } return createRubySearchScope ( res , includeRubyVMLibraries ) ; } public IRubySearchScope createRubyProjectSearchScope ( IRubyProject project , boolean includeRubyVMLibraries ) { return SearchEngine . createRubySearchScope ( new IRubyElement [ ] { project } , getSearchFlags ( includeRubyVMLibraries ) ) ; } public IRubySearchScope createRubyProjectSearchScope ( IEditorInput editorInput , boolean includeRubyVMLibraries ) { IRubyElement elem = RubyUI . getEditorInputRubyElement ( editorInput ) ; if ( elem != null ) { IRubyProject project = elem . getRubyProject ( ) ; if ( project != null ) { return createRubyProjectSearchScope ( project , includeRubyVMLibraries ) ; } } return EMPTY_SCOPE ; } public String getWorkspaceScopeDescription ( boolean includeRubyVMLibraries ) { return includeRubyVMLibraries ? SearchMessages . WorkspaceScope : SearchMessages . WorkspaceScopeNoJRE ; } public String getProjectScopeDescription ( String [ ] projectNames , boolean includeRubyVMLibraries ) { if ( projectNames . length == ) { return SearchMessages . RubySearchScopeFactory_undefined_projects ; } String scopeDescription ; if ( projectNames . length == ) { String label = includeRubyVMLibraries ? SearchMessages . EnclosingProjectScope : SearchMessages . EnclosingProjectScopeNoJRE ; scopeDescription = Messages . format ( label , projectNames [ ] ) ; } else if ( projectNames . length == ) { String label = includeRubyVMLibraries ? SearchMessages . EnclosingProjectsScope2 : SearchMessages . EnclosingProjectsScope2NoJRE ; scopeDescription = Messages . format ( label , new String [ ] { projectNames [ ] , projectNames [ ] } ) ; } else { String label = includeRubyVMLibraries ? SearchMessages . EnclosingProjectsScope : SearchMessages . EnclosingProjectsScopeNoJRE ; scopeDescription = Messages . format ( label , new String [ ] { projectNames [ ] , projectNames [ ] } ) ; } return scopeDescription ; } public String getProjectScopeDescription ( IRubyProject project , boolean includeRubyVMLibraries ) { if ( includeRubyVMLibraries ) { return Messages . format ( SearchMessages . ProjectScope , project . getElementName ( ) ) ; } else { return Messages . format ( SearchMessages . ProjectScopeNoJRE , project . getElementName ( ) ) ; } } public String getProjectScopeDescription ( IEditorInput editorInput , boolean includeRubyVMLibraries ) { IRubyElement elem = RubyUI . getEditorInputRubyElement ( editorInput ) ; if ( elem != null ) { IRubyProject project = elem . getRubyProject ( ) ; if ( project != null ) { return getProjectScopeDescription ( project , includeRubyVMLibraries ) ; } } return Messages . format ( SearchMessages . ProjectScope , "" ) ; } public String getHierarchyScopeDescription ( IType type ) { return Messages . format ( SearchMessages . HierarchyScope , new String [ ] { type . getElementName ( ) } ) ; } public String getSelectionScopeDescription ( IRubyElement [ ] rubyElements , boolean includeRubyVMLibraries ) { if ( rubyElements . length == ) { return SearchMessages . RubySearchScopeFactory_undefined_selection ; } String scopeDescription ; if ( rubyElements . length == ) { String label = includeRubyVMLibraries ? SearchMessages . SingleSelectionScope : SearchMessages . SingleSelectionScopeNoJRE ; scopeDescription = Messages . format ( label , rubyElements [ ] . getElementName ( ) ) ; } else if ( rubyElements . length == ) { String label = includeRubyVMLibraries ? SearchMessages . DoubleSelectionScope : SearchMessages . DoubleSelectionScopeNoJRE ; scopeDescription = Messages . format ( label , new String [ ] { rubyElements [ ] . getElementName ( ) , rubyElements [ ] . getElementName ( ) } ) ; } else { String label = includeRubyVMLibraries ? SearchMessages . SelectionScope : SearchMessages . SelectionScopeNoJRE ; scopeDescription = Messages . format ( label , new String [ ] { rubyElements [ ] . getElementName ( ) , rubyElements [ ] . getElementName ( ) } ) ; } return scopeDescription ; } public String getWorkingSetScopeDescription ( IWorkingSet [ ] workingSets , boolean includeRubyVMLibraries ) { if ( workingSets . length == ) { return SearchMessages . RubySearchScopeFactory_undefined_workingsets ; } if ( workingSets . length == ) { String label = includeRubyVMLibraries ? SearchMessages . SingleWorkingSetScope : SearchMessages . SingleWorkingSetScopeNoJRE ; return Messages . format ( label , workingSets [ ] . getLabel ( ) ) ; } Arrays . sort ( workingSets , new WorkingSetComparator ( ) ) ; if ( workingSets . length == ) { String label = includeRubyVMLibraries ? SearchMessages . DoubleWorkingSetScope : SearchMessages . DoubleWorkingSetScopeNoJRE ; return Messages . format ( label , new String [ ] { workingSets [ ] . getLabel ( ) , workingSets [ ] . getLabel ( ) } ) ; } String label = includeRubyVMLibraries ? SearchMessages . WorkingSetsScope : SearchMessages . WorkingSetsScopeNoJRE ; return Messages . format ( label , new String [ ] { workingSets [ ] . getLabel ( ) , workingSets [ ] . getLabel ( ) } ) ; } public IProject [ ] getProjects ( IRubySearchScope scope ) { IPath [ ] paths = scope . enclosingProjectsAndJars ( ) ; HashSet temp = new HashSet ( ) ; for ( int i = ; i < paths . length ; i ++ ) { IResource resource = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( paths [ i ] ) ; if ( resource != null && resource . getType ( ) == IResource . PROJECT ) temp . add ( resource ) ; } return ( IProject [ ] ) temp . toArray ( new IProject [ temp . size ( ) ] ) ; } public IRubyElement [ ] getRubyElements ( ISelection selection ) { if ( selection instanceof IStructuredSelection && ! selection . isEmpty ( ) ) { return getRubyElements ( ( ( IStructuredSelection ) selection ) . toArray ( ) ) ; } else { return new IRubyElement [ ] ; } } private IRubyElement [ ] getRubyElements ( Object [ ] elements ) { if ( elements . length == ) return new IRubyElement [ ] ; Set result = new HashSet ( elements . length ) ; for ( int i = ; i < elements . length ; i ++ ) { Object selectedElement = elements [ i ] ; if ( selectedElement instanceof IRubyElement ) { addRubyElements ( result , ( IRubyElement ) selectedElement ) ; } else if ( selectedElement instanceof IResource ) { addRubyElements ( result , ( IResource ) selectedElement ) ; } else if ( selectedElement instanceof IWorkingSet ) { IWorkingSet ws = ( IWorkingSet ) selectedElement ; addRubyElements ( result , ws ) ; } else if ( selectedElement instanceof IAdaptable ) { IResource resource = ( IResource ) ( ( IAdaptable ) selectedElement ) . getAdapter ( IResource . class ) ; if ( resource != null ) addRubyElements ( result , resource ) ; } } return ( IRubyElement [ ] ) result . toArray ( new IRubyElement [ result . size ( ) ] ) ; } public IRubySearchScope createRubySearchScope ( IRubyElement [ ] rubyElements , boolean includeRubyVMLibraries ) { if ( rubyElements . length == ) return EMPTY_SCOPE ; return SearchEngine . createRubySearchScope ( rubyElements , getSearchFlags ( includeRubyVMLibraries ) ) ; } private IRubySearchScope createRubySearchScope ( Collection rubyElements , boolean includeRubyVMLibraries ) { if ( rubyElements . isEmpty ( ) ) return EMPTY_SCOPE ; IRubyElement [ ] elementArray = ( IRubyElement [ ] ) rubyElements . toArray ( new IRubyElement [ rubyElements . size ( ) ] ) ; return SearchEngine . createRubySearchScope ( elementArray , getSearchFlags ( includeRubyVMLibraries ) ) ; } private static int getSearchFlags ( boolean includeRubyVMLibraries ) { int flags = IRubySearchScope . SOURCES | IRubySearchScope . APPLICATION_LIBRARIES ; if ( includeRubyVMLibraries ) flags |= IRubySearchScope . SYSTEM_LIBRARIES ; return flags ; } private void addRubyElements ( Set rubyElements , IResource [ ] resources ) { for ( int i = ; i < resources . length ; i ++ ) addRubyElements ( rubyElements , resources [ i ] ) ; } private void addRubyElements ( Set rubyElements , IResource resource ) { IRubyElement javaElement = ( IRubyElement ) resource . getAdapter ( IRubyElement . class ) ; if ( javaElement == null ) return ; if ( javaElement . getElementType ( ) == IRubyElement . SOURCE_FOLDER ) { try { addRubyElements ( rubyElements , ( ( IFolder ) resource ) . members ( ) ) ; } catch ( CoreException ex ) { } } rubyElements . add ( javaElement ) ; } private void addRubyElements ( Set rubyElements , IRubyElement rubyElement ) { rubyElements . add ( rubyElement ) ; } private void addRubyElements ( Set rubyElements , IWorkingSet workingSet ) { if ( workingSet == null ) return ; if ( workingSet . isAggregateWorkingSet ( ) && workingSet . isEmpty ( ) ) { try { IRubyProject [ ] projects = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) . getRubyProjects ( ) ; rubyElements . addAll ( Arrays . asList ( projects ) ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return ; } IAdaptable [ ] elements = workingSet . getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { IRubyElement rubyElement = ( IRubyElement ) elements [ i ] . getAdapter ( IRubyElement . class ) ; if ( rubyElement != null ) { addRubyElements ( rubyElements , rubyElement ) ; continue ; } IResource resource = ( IResource ) elements [ i ] . getAdapter ( IResource . class ) ; if ( resource != null ) { addRubyElements ( rubyElements , resource ) ; } } } public IRubySearchScope createWorkspaceScope ( boolean includeRubyVMLibraries ) { if ( ! includeRubyVMLibraries ) { try { IRubyProject [ ] projects = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) . getRubyProjects ( ) ; return SearchEngine . createRubySearchScope ( projects , getSearchFlags ( includeRubyVMLibraries ) ) ; } catch ( RubyModelException e ) { } } return SearchEngine . createWorkspaceScope ( ) ; } public boolean isInsideRubyVMLibraries ( IRubyElement element ) { ISourceFolderRoot root = ( ISourceFolderRoot ) element . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; if ( root != null ) { try { ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) { ILoadpathContainer container = RubyCore . getLoadpathContainer ( entry . getPath ( ) , root . getRubyProject ( ) ) ; return container != null && container . getKind ( ) == ILoadpathContainer . K_DEFAULT_SYSTEM ; } return false ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } return true ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . search . ui . ISearchQuery ; import org . eclipse . search . ui . text . AbstractTextSearchResult ; import org . eclipse . search . ui . text . IEditorMatchAdapter ; import org . eclipse . search . ui . text . IFileMatchAdapter ; import org . eclipse . search . ui . text . Match ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IFileEditorInput ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptEditorInput ; public class OccurrencesSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter , IFileMatchAdapter { protected static final Match [ ] NO_MATCHES = new Match [ ] ; private OccurrencesSearchQuery fQuery ; public OccurrencesSearchResult ( OccurrencesSearchQuery query ) { fQuery = query ; } public Match [ ] computeContainedMatches ( AbstractTextSearchResult result , IFile file ) { Object [ ] elements = getElements ( ) ; if ( elements . length == ) return NO_MATCHES ; RubyElementLine jel = ( RubyElementLine ) elements [ ] ; try { if ( file . equals ( jel . getRubyElement ( ) . getCorrespondingResource ( ) ) ) return collectMatches ( elements ) ; } catch ( RubyModelException e ) { } return NO_MATCHES ; } public Match [ ] computeContainedMatches ( AbstractTextSearchResult result , IEditorPart editor ) { IEditorInput editorInput = editor . getEditorInput ( ) ; if ( editorInput instanceof IFileEditorInput ) { IFileEditorInput fileEditorInput = ( IFileEditorInput ) editorInput ; return computeContainedMatches ( result , fileEditorInput . getFile ( ) ) ; } else if ( editorInput instanceof IRubyScriptEditorInput ) { IRubyScriptEditorInput classFileEditorInput = ( IRubyScriptEditorInput ) editorInput ; IRubyScript classFile = classFileEditorInput . getRubyScript ( ) ; Object [ ] elements = getElements ( ) ; if ( elements . length == ) return NO_MATCHES ; RubyElementLine jel = ( RubyElementLine ) elements [ ] ; if ( jel . getRubyElement ( ) . equals ( classFile ) ) return collectMatches ( elements ) ; } return NO_MATCHES ; } public IFile getFile ( Object element ) { RubyElementLine jel = ( RubyElementLine ) element ; IResource resource = null ; try { resource = jel . getRubyElement ( ) . getCorrespondingResource ( ) ; } catch ( RubyModelException e ) { } if ( resource instanceof IFile ) return ( IFile ) resource ; else return null ; } public boolean isShownInEditor ( Match match , IEditorPart editor ) { Object element = match . getElement ( ) ; IRubyElement je = ( ( RubyElementLine ) element ) . getRubyElement ( ) ; IEditorInput editorInput = editor . getEditorInput ( ) ; if ( editorInput instanceof IFileEditorInput ) { try { return ( ( IFileEditorInput ) editorInput ) . getFile ( ) . equals ( je . getCorrespondingResource ( ) ) ; } catch ( RubyModelException e ) { return false ; } } else if ( editorInput instanceof IRubyScriptEditorInput ) { return ( ( IRubyScriptEditorInput ) editorInput ) . getRubyScript ( ) . equals ( je ) ; } return false ; } public String getLabel ( ) { return fQuery . getResultLabel ( getMatchCount ( ) ) ; } public String getTooltip ( ) { return getLabel ( ) ; } public ImageDescriptor getImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_SEARCH_REF ; } public ISearchQuery getQuery ( ) { return fQuery ; } public IFileMatchAdapter getFileMatchAdapter ( ) { return this ; } public IEditorMatchAdapter getEditorMatchAdapter ( ) { return this ; } private Match [ ] collectMatches ( Object [ ] elements ) { Match [ ] matches = new Match [ getMatchCount ( ) ] ; int writeIndex = ; for ( int i = ; i < elements . length ; i ++ ) { Match [ ] perElement = getMatches ( elements [ i ] ) ; for ( int j = ; j < perElement . length ; j ++ ) { matches [ writeIndex ++ ] = perElement [ j ] ; } } return matches ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . search . ui . text . Match ; public class RubyElementMatch extends Match { private int fAccuracy ; private int fMatchRule ; private boolean fIsWriteAccess ; private boolean fIsReadAccess ; private boolean fIsRubydoc ; RubyElementMatch ( Object element , int matchRule , int offset , int length , int accuracy , boolean isReadAccess , boolean isWriteAccess , boolean isRubydoc ) { super ( element , offset , length ) ; fAccuracy = accuracy ; fMatchRule = matchRule ; fIsWriteAccess = isWriteAccess ; fIsReadAccess = isReadAccess ; fIsRubydoc = isRubydoc ; } public int getAccuracy ( ) { return fAccuracy ; } public boolean isWriteAccess ( ) { return fIsWriteAccess ; } public boolean isReadAccess ( ) { return fIsReadAccess ; } public boolean isRubydoc ( ) { return fIsRubydoc ; } public int getMatchRule ( ) { return fMatchRule ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . action . Action ; public class GroupAction extends Action { private int fGrouping ; private RubySearchResultPage fPage ; public GroupAction ( String label , String tooltip , RubySearchResultPage page , int grouping ) { super ( label ) ; setToolTipText ( tooltip ) ; fPage = page ; fGrouping = grouping ; } public void run ( ) { fPage . setGrouping ( fGrouping ) ; } public int getGrouping ( ) { return fGrouping ; } } package org . rubypeople . rdt . internal . ui . search ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . search . ui . text . AbstractTextSearchViewPage ; import org . eclipse . search . ui . text . Match ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; public class OccurrencesSearchResultPage extends AbstractTextSearchViewPage { private TextSearchTableContentProvider fContentProvider ; public OccurrencesSearchResultPage ( ) { super ( AbstractTextSearchViewPage . FLAG_LAYOUT_FLAT ) ; } protected void showMatch ( Match match , int currentOffset , int currentLength , boolean activate ) throws PartInitException { IEditorPart editor = null ; RubyElementLine element = ( RubyElementLine ) match . getElement ( ) ; IRubyElement javaElement = element . getRubyElement ( ) ; try { editor = EditorUtility . openInEditor ( javaElement , false ) ; } catch ( PartInitException e1 ) { return ; } catch ( RubyModelException e1 ) { return ; } if ( editor != null && activate ) editor . getEditorSite ( ) . getPage ( ) . activate ( editor ) ; if ( editor instanceof ITextEditor ) { ITextEditor textEditor = ( ITextEditor ) editor ; textEditor . selectAndReveal ( currentOffset , currentLength ) ; } } protected void elementsChanged ( Object [ ] objects ) { if ( fContentProvider != null ) fContentProvider . elementsChanged ( objects ) ; } protected void clear ( ) { if ( fContentProvider != null ) fContentProvider . clear ( ) ; } protected void configureTreeViewer ( TreeViewer viewer ) { throw new IllegalStateException ( "" ) ; } protected void configureTableViewer ( TableViewer viewer ) { viewer . setSorter ( new RubyElementLineSorter ( ) ) ; viewer . setLabelProvider ( new OccurrencesSearchLabelProvider ( this ) ) ; fContentProvider = new TextSearchTableContentProvider ( ) ; viewer . setContentProvider ( fContentProvider ) ; } } package org . rubypeople . rdt . internal . ui . search ; import org . rubypeople . rdt . core . IRubyElement ; public class RubyElementLine { private IRubyElement fElement ; private int fLine ; private String fLineContents ; public RubyElementLine ( IRubyElement element , int line , String lineContents ) { fElement = element ; fLine = line ; fLineContents = lineContents ; } public IRubyElement getRubyElement ( ) { return fElement ; } public int getLine ( ) { return fLine ; } public String getLineContents ( ) { return fLineContents ; } } package org . rubypeople . rdt . internal . ui . search ; import com . ibm . icu . text . Collator ; import java . util . Comparator ; import org . eclipse . ui . IWorkingSet ; class WorkingSetsComparator implements Comparator { private Collator fCollator = Collator . getInstance ( ) ; public int compare ( Object o1 , Object o2 ) { String name1 = null ; String name2 = null ; if ( o1 instanceof IWorkingSet [ ] ) { IWorkingSet [ ] workingSets = ( IWorkingSet [ ] ) o1 ; if ( workingSets . length > ) name1 = workingSets [ ] . getLabel ( ) ; } if ( o2 instanceof IWorkingSet [ ] ) { IWorkingSet [ ] workingSets = ( IWorkingSet [ ] ) o1 ; if ( workingSets . length > ) name2 = workingSets [ ] . getLabel ( ) ; } return fCollator . compare ( name1 , name2 ) ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . RubyModelException ; public interface IResourceLocator { IResource getUnderlyingResource ( Object element ) throws RubyModelException ; IResource getCorrespondingResource ( Object element ) throws RubyModelException ; IResource getContainingResource ( Object element ) throws RubyModelException ; } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . ui . RubyUI ; public class InitializeAfterLoadJob extends UIJob { private final class RealJob extends Job { public RealJob ( String name ) { super ( name ) ; } protected IStatus run ( IProgressMonitor monitor ) { monitor . beginTask ( "" , ) ; try { RubyCore . initializeAfterLoad ( new SubProgressMonitor ( monitor , ) ) ; RubyPlugin . getDefault ( ) . initializeAfterLoad ( new SubProgressMonitor ( monitor , ) ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; return e . getStatus ( ) ; } return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } public boolean belongsTo ( Object family ) { return RubyUI . ID_PLUGIN . equals ( family ) ; } } public InitializeAfterLoadJob ( ) { super ( RubyUIMessages . InitializeAfterLoadJob_starter_job_name ) ; setSystem ( true ) ; } public IStatus runInUIThread ( IProgressMonitor monitor ) { Job job = new RealJob ( RubyUIMessages . RubyPlugin_initializing_ui ) ; job . setPriority ( Job . SHORT ) ; job . schedule ( ) ; return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } } package org . rubypeople . rdt . internal . ui ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . util . ListenerList ; import org . eclipse . jface . util . SafeRunnable ; import org . eclipse . ui . IEditorDescriptor ; import org . eclipse . ui . IEditorRegistry ; import org . eclipse . ui . IFileEditorMapping ; import org . eclipse . ui . IPropertyListener ; import org . eclipse . ui . internal . WorkbenchPlugin ; import org . rubypeople . rdt . ui . RubyUI ; public class RubyFileMatcher { private static final String RUBY = "" ; private static final String SHEBANG = "" ; public static final int PROP_MATCH_CRITERIA = ; private String [ ] rubyFileExtensions ; private String [ ] rubyFileNames ; private ListenerList propChangeListeners ; private IPropertyListener propertyListener = new IPropertyListener ( ) { public void propertyChanged ( Object source , int property ) { if ( property == IEditorRegistry . PROP_CONTENTS && source instanceof IEditorRegistry ) { createFileExtensions ( ) ; firePropertyChange ( PROP_MATCH_CRITERIA ) ; } } } ; private static Set RUBY_NON_EDITABLE_EXTENSIONS = new HashSet ( ) ; static { RUBY_NON_EDITABLE_EXTENSIONS . add ( "" ) ; RUBY_NON_EDITABLE_EXTENSIONS . add ( "" ) ; RUBY_NON_EDITABLE_EXTENSIONS . add ( "" ) ; RUBY_NON_EDITABLE_EXTENSIONS . add ( "" ) ; RUBY_NON_EDITABLE_EXTENSIONS . add ( "" ) ; } public RubyFileMatcher ( ) { propChangeListeners = new ListenerList ( ) ; this . createFileExtensions ( ) ; WorkbenchPlugin . getDefault ( ) . getEditorRegistry ( ) . addPropertyListener ( propertyListener ) ; } public void addPropertyChangeListener ( IPropertyListener propListener ) { propChangeListeners . add ( propListener ) ; } private void firePropertyChange ( final int type ) { Object [ ] array = propChangeListeners . getListeners ( ) ; for ( int nX = ; nX < array . length ; nX ++ ) { final IPropertyListener l = ( IPropertyListener ) array [ nX ] ; Platform . run ( new SafeRunnable ( ) { public void run ( ) { l . propertyChanged ( this , type ) ; } } ) ; } } public void createFileExtensions ( ) { List extensions = new ArrayList ( ) ; extensions . addAll ( createDefaultExtensions ( ) ) ; List filenames = new ArrayList ( ) ; filenames . addAll ( createDefaultFilenames ( ) ) ; IFileEditorMapping [ ] mappings = WorkbenchPlugin . getDefault ( ) . getEditorRegistry ( ) . getFileEditorMappings ( ) ; for ( int i = ; i < mappings . length ; i ++ ) { IFileEditorMapping mapping = mappings [ i ] ; IEditorDescriptor [ ] editors = mapping . getEditors ( ) ; for ( int j = ; j < editors . length ; j ++ ) { IEditorDescriptor descriptor = editors [ j ] ; if ( descriptor . getId ( ) . equals ( RubyUI . ID_RUBY_EDITOR ) ) { if ( mapping . getExtension ( ) != null && mapping . getExtension ( ) . length ( ) != ) { extensions . add ( mapping . getExtension ( ) ) ; break ; } if ( mapping . getName ( ) != null && mapping . getName ( ) . length ( ) != ) { filenames . add ( mapping . getName ( ) ) ; break ; } } } } this . rubyFileExtensions = ( String [ ] ) extensions . toArray ( new String [ extensions . size ( ) ] ) ; this . rubyFileNames = ( String [ ] ) filenames . toArray ( new String [ filenames . size ( ) ] ) ; } private Collection createDefaultFilenames ( ) { Set set = new HashSet ( ) ; set . add ( "" ) ; return set ; } private Collection createDefaultExtensions ( ) { return RUBY_NON_EDITABLE_EXTENSIONS ; } public boolean hasRubyEditorAssociation ( IFile file ) { String fileExtension = file . getFileExtension ( ) ; for ( int i = ; i < rubyFileExtensions . length ; i ++ ) { if ( rubyFileExtensions [ i ] . equalsIgnoreCase ( fileExtension ) ) { return true ; } } String fileName = file . getName ( ) ; for ( int i = ; i < rubyFileNames . length ; i ++ ) { if ( rubyFileNames [ i ] . equalsIgnoreCase ( fileName ) ) { return true ; } } return containsRubyShebang ( file ) ; } private boolean containsRubyShebang ( IFile file ) { BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( file . getContents ( ) ) ) ; String firstLine = reader . readLine ( ) ; if ( firstLine == null ) return false ; if ( firstLine . indexOf ( SHEBANG ) > - && firstLine . indexOf ( RUBY ) > - ) return true ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { try { if ( reader != null ) reader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return false ; } } package org . rubypeople . rdt . internal . ui . dnd ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . swt . dnd . DragSource ; import org . eclipse . swt . dnd . DragSourceEvent ; import org . eclipse . swt . dnd . DragSourceListener ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . dnd . TransferData ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . TransferDragSourceListener ; public class DelegatingDragAdapter implements DragSourceListener { private TransferDragSourceListener [ ] fPossibleListeners ; private List fActiveListeners ; private TransferDragSourceListener fFinishListener ; public DelegatingDragAdapter ( TransferDragSourceListener [ ] listeners ) { setPossibleListeners ( listeners ) ; } protected void setPossibleListeners ( TransferDragSourceListener [ ] listeners ) { Assert . isNotNull ( listeners ) ; Assert . isTrue ( fActiveListeners == null , "" ) ; fPossibleListeners = listeners ; } public void dragStart ( DragSourceEvent event ) { fFinishListener = null ; boolean saveDoit = event . doit ; Object saveData = event . data ; boolean doIt = false ; List transfers = new ArrayList ( fPossibleListeners . length ) ; fActiveListeners = new ArrayList ( fPossibleListeners . length ) ; for ( int i = ; i < fPossibleListeners . length ; i ++ ) { TransferDragSourceListener listener = fPossibleListeners [ i ] ; event . doit = saveDoit ; listener . dragStart ( event ) ; if ( event . doit ) { transfers . add ( listener . getTransfer ( ) ) ; fActiveListeners . add ( listener ) ; } doIt = doIt || event . doit ; } if ( doIt ) { ( ( DragSource ) event . widget ) . setTransfer ( ( Transfer [ ] ) transfers . toArray ( new Transfer [ transfers . size ( ) ] ) ) ; } event . data = saveData ; event . doit = doIt ; } public void dragSetData ( DragSourceEvent event ) { fFinishListener = getListener ( event . dataType ) ; if ( fFinishListener != null ) fFinishListener . dragSetData ( event ) ; } public void dragFinished ( DragSourceEvent event ) { try { if ( fFinishListener != null ) { fFinishListener . dragFinished ( event ) ; } else { fFinishListener = getListener ( event . dataType ) ; if ( fFinishListener != null ) fFinishListener . dragFinished ( event ) ; } } finally { fFinishListener = null ; fActiveListeners = null ; } } private TransferDragSourceListener getListener ( TransferData type ) { if ( type == null ) return null ; for ( Iterator iter = fActiveListeners . iterator ( ) ; iter . hasNext ( ) ; ) { TransferDragSourceListener listener = ( TransferDragSourceListener ) iter . next ( ) ; if ( listener . getTransfer ( ) . isSupportedType ( type ) ) { return listener ; } } return null ; } } package org . rubypeople . rdt . internal . ui . dnd ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . swt . dnd . DragSourceEvent ; public class RdtViewerDragAdapter extends DelegatingDragAdapter { private StructuredViewer fViewer ; public RdtViewerDragAdapter ( StructuredViewer viewer , TransferDragSourceListener [ ] listeners ) { super ( listeners ) ; Assert . isNotNull ( viewer ) ; fViewer = viewer ; } public void dragStart ( DragSourceEvent event ) { IStructuredSelection selection = ( IStructuredSelection ) fViewer . getSelection ( ) ; if ( selection . isEmpty ( ) ) { event . doit = false ; return ; } super . dragStart ( event ) ; } } package org . rubypeople . rdt . internal . ui . dnd ; import org . eclipse . core . runtime . SafeRunner ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DropTargetEvent ; import org . eclipse . swt . dnd . DropTargetListener ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . dnd . TransferData ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . SafeRunnable ; import org . eclipse . jface . util . TransferDropTargetListener ; public class DelegatingDropAdapter implements DropTargetListener { private TransferDropTargetListener [ ] fListeners ; private TransferDropTargetListener fCurrentListener ; private int fOriginalDropType ; public DelegatingDropAdapter ( TransferDropTargetListener [ ] listeners ) { Assert . isNotNull ( listeners ) ; fListeners = listeners ; } public void dragEnter ( DropTargetEvent event ) { fOriginalDropType = event . detail ; updateCurrentListener ( event ) ; } public void dragLeave ( final DropTargetEvent event ) { setCurrentListener ( null , event ) ; } public void dragOperationChanged ( final DropTargetEvent event ) { fOriginalDropType = event . detail ; TransferDropTargetListener oldListener = getCurrentListener ( ) ; updateCurrentListener ( event ) ; final TransferDropTargetListener newListener = getCurrentListener ( ) ; if ( newListener != null && newListener == oldListener ) { SafeRunner . run ( new SafeRunnable ( ) { public void run ( ) throws Exception { newListener . dragOperationChanged ( event ) ; } } ) ; } } public void dragOver ( final DropTargetEvent event ) { TransferDropTargetListener oldListener = getCurrentListener ( ) ; updateCurrentListener ( event ) ; final TransferDropTargetListener newListener = getCurrentListener ( ) ; if ( newListener != null && newListener == oldListener ) { SafeRunner . run ( new SafeRunnable ( ) { public void run ( ) throws Exception { newListener . dragOver ( event ) ; } } ) ; } } public void drop ( final DropTargetEvent event ) { updateCurrentListener ( event ) ; if ( getCurrentListener ( ) != null ) { SafeRunner . run ( new SafeRunnable ( ) { public void run ( ) throws Exception { getCurrentListener ( ) . drop ( event ) ; } } ) ; } setCurrentListener ( null , event ) ; } public void dropAccept ( final DropTargetEvent event ) { if ( getCurrentListener ( ) != null ) { SafeRunner . run ( new SafeRunnable ( ) { public void run ( ) throws Exception { getCurrentListener ( ) . dropAccept ( event ) ; } } ) ; } } private TransferDropTargetListener getCurrentListener ( ) { return fCurrentListener ; } private TransferData getSupportedTransferType ( TransferData [ ] dataTypes , TransferDropTargetListener listener ) { for ( int i = ; i < dataTypes . length ; i ++ ) { if ( listener . getTransfer ( ) . isSupportedType ( dataTypes [ i ] ) ) { return dataTypes [ i ] ; } } return null ; } public Transfer [ ] getTransfers ( ) { Transfer [ ] types = new Transfer [ fListeners . length ] ; for ( int i = ; i < fListeners . length ; i ++ ) { types [ i ] = fListeners [ i ] . getTransfer ( ) ; } return types ; } private boolean setCurrentListener ( TransferDropTargetListener listener , final DropTargetEvent event ) { if ( fCurrentListener == listener ) return false ; if ( fCurrentListener != null ) { SafeRunner . run ( new SafeRunnable ( ) { public void run ( ) throws Exception { fCurrentListener . dragLeave ( event ) ; } } ) ; } fCurrentListener = listener ; if ( fCurrentListener != null ) { SafeRunner . run ( new SafeRunnable ( ) { public void run ( ) throws Exception { fCurrentListener . dragEnter ( event ) ; } } ) ; } return true ; } private void updateCurrentListener ( DropTargetEvent event ) { int originalDetail = event . detail ; event . detail = fOriginalDropType ; for ( int i = ; i < fListeners . length ; i ++ ) { TransferDropTargetListener listener = fListeners [ i ] ; TransferData dataType = getSupportedTransferType ( event . dataTypes , listener ) ; if ( dataType != null ) { TransferData originalDataType = event . currentDataType ; event . currentDataType = dataType ; if ( listener . isEnabled ( event ) ) { if ( ! setCurrentListener ( listener , event ) ) event . detail = originalDetail ; return ; } else { event . currentDataType = originalDataType ; } } } setCurrentListener ( null , event ) ; event . detail = DND . DROP_NONE ; } } package org . rubypeople . rdt . internal . ui . dnd ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DragSourceAdapter ; import org . eclipse . swt . dnd . DragSourceEvent ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . ui . views . navigator . LocalSelectionTransfer ; public class BasicSelectionTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener { private ISelectionProvider fProvider ; public BasicSelectionTransferDragAdapter ( ISelectionProvider provider ) { Assert . isNotNull ( provider ) ; fProvider = provider ; } public Transfer getTransfer ( ) { return LocalSelectionTransfer . getInstance ( ) ; } public void dragStart ( DragSourceEvent event ) { ISelection selection = fProvider . getSelection ( ) ; LocalSelectionTransfer . getInstance ( ) . setSelection ( selection ) ; LocalSelectionTransfer . getInstance ( ) . setSelectionSetTime ( event . time & ) ; event . doit = isDragable ( selection ) ; } protected boolean isDragable ( ISelection selection ) { return true ; } public void dragSetData ( DragSourceEvent event ) { event . data = LocalSelectionTransfer . getInstance ( ) . getSelection ( ) ; } public void dragFinished ( DragSourceEvent event ) { Assert . isTrue ( event . detail != DND . DROP_MOVE ) ; LocalSelectionTransfer . getInstance ( ) . setSelection ( null ) ; LocalSelectionTransfer . getInstance ( ) . setSelectionSetTime ( ) ; } } package org . rubypeople . rdt . internal . ui . dnd ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DropTargetEvent ; import org . eclipse . swt . dnd . DropTargetListener ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . TableItem ; import org . eclipse . swt . widgets . TreeItem ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . StructuredViewer ; public class RdtViewerDropAdapter implements DropTargetListener { public static final int LOCATION_NONE = DND . FEEDBACK_NONE ; public static final int LOCATION_ON = DND . FEEDBACK_SELECT ; public static final int LOCATION_BEFORE = DND . FEEDBACK_INSERT_BEFORE ; public static final int LOCATION_AFTER = DND . FEEDBACK_INSERT_AFTER ; private static final int LOCATION_EPSILON = ; private static final int ITEM_MARGIN_LEFT = ; private static final int ITEM_MARGIN_RIGTH = ; public static final int INSERTION_FEEDBACK = << ; private StructuredViewer fViewer ; private int fFeedback ; private boolean fShowInsertionFeedback ; private boolean fFullWidthMatchesItem ; private int fRequestedOperation ; private int fLastOperation ; protected int fLocation ; protected Object fTarget ; public RdtViewerDropAdapter ( StructuredViewer viewer , int feedback ) { Assert . isNotNull ( viewer ) ; fViewer = viewer ; fFeedback = feedback ; fLastOperation = - ; fFullWidthMatchesItem = true ; } public void showInsertionFeedback ( boolean showInsertionFeedback ) { fShowInsertionFeedback = showInsertionFeedback ; } protected void setFullWidthMatchesItem ( boolean enable ) { fFullWidthMatchesItem = enable ; } protected StructuredViewer getViewer ( ) { return fViewer ; } public void drop ( DropTargetEvent event ) { drop ( fTarget , event ) ; } public void drop ( Object target , DropTargetEvent event ) { } public void validateDrop ( DropTargetEvent event ) { validateDrop ( fTarget , event , fRequestedOperation ) ; } public void validateDrop ( Object target , DropTargetEvent event , int operation ) { } public void dragEnter ( DropTargetEvent event ) { dragOperationChanged ( event ) ; } public void dragLeave ( DropTargetEvent event ) { fTarget = null ; fLocation = LOCATION_NONE ; } public void dragOperationChanged ( DropTargetEvent event ) { fRequestedOperation = event . detail ; fTarget = computeTarget ( event ) ; fLocation = computeLocation ( event ) ; validateDrop ( event ) ; fLastOperation = event . detail ; computeFeedback ( event ) ; } public void dragOver ( DropTargetEvent event ) { Object oldTarget = fTarget ; fTarget = computeTarget ( event ) ; int oldLocation = fLocation ; fLocation = computeLocation ( event ) ; if ( oldLocation != fLocation || oldTarget != fTarget || fLastOperation != event . detail ) { validateDrop ( event ) ; fLastOperation = event . detail ; } else { event . detail = fLastOperation ; } computeFeedback ( event ) ; } public void dropAccept ( DropTargetEvent event ) { fTarget = computeTarget ( event ) ; validateDrop ( event ) ; fLastOperation = event . detail ; } protected Object computeTarget ( DropTargetEvent event ) { if ( event . item == null ) { return null ; } if ( ! fFullWidthMatchesItem ) { Point coordinates = fViewer . getControl ( ) . toControl ( new Point ( event . x , event . y ) ) ; Rectangle bounds = getBounds ( ( Item ) event . item ) ; if ( coordinates . x < bounds . x - ITEM_MARGIN_LEFT || coordinates . x >= bounds . x + bounds . width + ITEM_MARGIN_RIGTH ) { event . item = null ; return null ; } } return event . item . getData ( ) ; } protected int computeLocation ( DropTargetEvent event ) { if ( ! ( event . item instanceof Item ) ) return LOCATION_NONE ; Item item = ( Item ) event . item ; Point coordinates = fViewer . getControl ( ) . toControl ( new Point ( event . x , event . y ) ) ; Rectangle bounds = getBounds ( item ) ; if ( bounds == null ) { return LOCATION_NONE ; } if ( ( coordinates . y - bounds . y ) < LOCATION_EPSILON ) { return LOCATION_BEFORE ; } if ( ( bounds . y + bounds . height - coordinates . y ) < LOCATION_EPSILON ) { return LOCATION_AFTER ; } return LOCATION_ON ; } private Rectangle getBounds ( Item item ) { if ( item instanceof TreeItem ) return ( ( TreeItem ) item ) . getBounds ( ) ; if ( item instanceof TableItem ) return ( ( TableItem ) item ) . getBounds ( ) ; return null ; } protected void computeFeedback ( DropTargetEvent event ) { if ( ! fShowInsertionFeedback && fLocation != LOCATION_NONE ) { event . feedback = DND . FEEDBACK_SELECT ; } else { event . feedback = fLocation ; } event . feedback |= fFeedback ; } protected void clearDropOperation ( DropTargetEvent event ) { event . detail = DND . DROP_NONE ; } protected int getRequestedOperation ( ) { return fRequestedOperation ; } protected void setDefaultFeedback ( int feedback ) { fFeedback = feedback ; } public void internalTestSetLocation ( int location ) { fLocation = location ; } } package org . rubypeople . rdt . internal . ui ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public interface IRubyHelpContextIds { public static final String PREFIX = RubyPlugin . PLUGIN_ID + '' ; public static final String GETTERSETTER_ACTION = PREFIX + "" ; public static final String ADD_METHODSTUB_ACTION = PREFIX + "" ; public static final String ADD_UNIMPLEMENTED_METHODS_ACTION = PREFIX + "" ; public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION = PREFIX + "" ; public static final String CREATE_NEW_CONSTRUCTOR_ACTION = PREFIX + "" ; public static final String SHOW_IN_PACKAGEVIEW_ACTION = PREFIX + "" ; public static final String SHOW_IN_HIERARCHYVIEW_ACTION = PREFIX + "" ; public static final String FOCUS_ON_SELECTION_ACTION = PREFIX + "" ; public static final String FOCUS_ON_TYPE_ACTION = PREFIX + "" ; public static final String TYPEHIERARCHY_HISTORY_ACTION = PREFIX + "" ; public static final String FILTER_PUBLIC_ACTION = PREFIX + "" ; public static final String FILTER_FIELDS_ACTION = PREFIX + "" ; public static final String FILTER_STATIC_ACTION = PREFIX + "" ; public static final String FILTER_LOCALTYPES_ACTION = PREFIX + "" ; public static final String SHOW_INHERITED_ACTION = PREFIX + "" ; public static final String SHOW_SUPERTYPES = PREFIX + "" ; public static final String SHOW_SUBTYPES = PREFIX + "" ; public static final String SHOW_HIERARCHY = PREFIX + "" ; public static final String ENABLE_METHODFILTER_ACTION = PREFIX + "" ; public static final String ADD_IMPORT_ON_SELECTION_ACTION = PREFIX + "" ; public static final String ORGANIZE_IMPORTS_ACTION = PREFIX + "" ; public static final String ADD_TO_CLASSPATH_ACTION = PREFIX + "" ; public static final String REMOVE_FROM_CLASSPATH_ACTION = PREFIX + "" ; public static final String TOGGLE_PRESENTATION_ACTION = PREFIX + "" ; public static final String TOGGLE_MARK_OCCURRENCES_ACTION = PREFIX + "" ; public static final String TOGGLE_TEXTHOVER_ACTION = PREFIX + "" ; public static final String OPEN_CLASS_WIZARD_ACTION = PREFIX + "" ; public static final String OPEN_INTERFACE_WIZARD_ACTION = PREFIX + "" ; public static final String SORT_MEMBERS_ACTION = PREFIX + "" ; public static final String OPEN_PACKAGE_WIZARD_ACTION = PREFIX + "" ; public static final String OPEN_PROJECT_WIZARD_ACTION = PREFIX + "" ; public static final String EDIT_WORKING_SET_ACTION = PREFIX + "" ; public static final String CLEAR_WORKING_SET_ACTION = PREFIX + "" ; public static final String GOTO_MARKER_ACTION = PREFIX + "" ; public static final String GOTO_PACKAGE_ACTION = PREFIX + "" ; public static final String GOTO_TYPE_ACTION = PREFIX + "" ; public static final String GOTO_MATCHING_BRACKET_ACTION = PREFIX + "" ; public static final String FORMAT_ALL = PREFIX + "" ; public static final String GOTO_NEXT_MEMBER_ACTION = PREFIX + "" ; public static final String GOTO_PREVIOUS_MEMBER_ACTION = PREFIX + "" ; public static final String HISTORY_ACTION = PREFIX + "" ; public static final String HISTORY_LIST_ACTION = PREFIX + "" ; public static final String LEXICAL_SORTING_OUTLINE_ACTION = PREFIX + "" ; public static final String LEXICAL_SORTING_BROWSING_ACTION = PREFIX + "" ; public static final String OPEN_JAVA_PERSPECTIVE_ACTION = PREFIX + "" ; public static final String ADD_DELEGATE_METHODS_ACTION = PREFIX + "" ; public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION = PREFIX + "" ; public static final String OPEN_PROJECT_ACTION = PREFIX + "" ; public static final String OPEN_TYPE_ACTION = PREFIX + "" ; public static final String OPEN_TYPE_IN_HIERARCHY_ACTION = PREFIX + "" ; public static final String CONFIG_CONTAINER_ACTION = PREFIX + "" ; public static final String ADD_JAVADOC_STUB_ACTION = PREFIX + "" ; public static final String ADD_TASK_ACTION = PREFIX + "" ; public static final String EXTERNALIZE_STRINGS_ACTION = PREFIX + "" ; public static final String EXTRACT_METHOD_ACTION = PREFIX + "" ; public static final String EXTRACT_TEMP_ACTION = PREFIX + "" ; public static final String PROMOTE_TEMP_TO_FIELD_ACTION = PREFIX + "" ; public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION = PREFIX + "" ; public static final String EXTRACT_CONSTANT_ACTION = PREFIX + "" ; public static final String INTRODUCE_PARAMETER_ACTION = PREFIX + "" ; public static final String INTRODUCE_FACTORY_ACTION = PREFIX + "" ; public static final String EXTRACT_INTERFACE_ACTION = PREFIX + "" ; public static final String CHANGE_TYPE_ACTION = PREFIX + "" ; public static final String MOVE_INNER_TO_TOP_ACTION = PREFIX + "" ; public static final String USE_SUPERTYPE_ACTION = PREFIX + "" ; public static final String FIND_DECLARATIONS_IN_WORKSPACE_ACTION = PREFIX + "" ; public static final String FIND_DECLARATIONS_IN_PROJECT_ACTION = PREFIX + "" ; public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION = PREFIX + "" ; public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION = PREFIX + "" ; public static final String FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION = PREFIX + "" ; public static final String FIND_IMPLEMENTORS_IN_PROJECT_ACTION = PREFIX + "" ; public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION = PREFIX + "" ; public static final String FIND_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + "" ; public static final String FIND_REFERENCES_IN_PROJECT_ACTION = PREFIX + "" ; public static final String FIND_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + "" ; public static final String FIND_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + "" ; public static final String FIND_READ_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + "" ; public static final String FIND_READ_REFERENCES_IN_PROJECT_ACTION = PREFIX + "" ; public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + "" ; public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + "" ; public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + "" ; public static final String FIND_WRITE_REFERENCES_IN_PROJECT_ACTION = PREFIX + "" ; public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + "" ; public static final String FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + "" ; public static final String FIND_OCCURRENCES_IN_FILE_ACTION = PREFIX + "" ; public static final String FIND_EXCEPTION_OCCURRENCES = PREFIX + "" ; public static final String FIND_IMPLEMENT_OCCURRENCES = PREFIX + "" ; public static final String WORKING_SET_FIND_ACTION = PREFIX + "" ; public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION = PREFIX + "" ; public static final String INLINE_ACTION = PREFIX + "" ; public static final String MODIFY_PARAMETERS_ACTION = PREFIX + "" ; public static final String MOVE_ACTION = PREFIX + "" ; public static final String OPEN_ACTION = PREFIX + "" ; public static final String OPEN_EXTERNAL_JAVADOC_ACTION = PREFIX + "" ; public static final String OPEN_INPUT_ACTION = PREFIX + "" ; public static final String OPEN_SUPER_IMPLEMENTATION_ACTION = PREFIX + "" ; public static final String PULL_UP_ACTION = PREFIX + "" ; public static final String PUSH_DOWN_ACTION = PREFIX + "" ; public static final String REFRESH_ACTION = PREFIX + "" ; public static final String RENAME_ACTION = PREFIX + "" ; public static final String SELF_ENCAPSULATE_ACTION = PREFIX + "" ; public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION = PREFIX + "" ; public static final String SURROUND_WITH_TRY_CATCH_ACTION = PREFIX + "" ; public static final String OPEN_RESOURCE_ACTION = PREFIX + "" ; public static final String SELECT_WORKING_SET_ACTION = PREFIX + "" ; public static final String STRUCTURED_SELECTION_HISTORY_ACTION = PREFIX + "" ; public static final String STRUCTURED_SELECT_ENCLOSING_ACTION = PREFIX + "" ; public static final String STRUCTURED_SELECT_NEXT_ACTION = PREFIX + "" ; public static final String STRUCTURED_SELECT_PREVIOUS_ACTION = PREFIX + "" ; public static final String TOGGLE_ORIENTATION_ACTION = PREFIX + "" ; public static final String CUT_ACTION = PREFIX + "" ; public static final String COPY_ACTION = PREFIX + "" ; public static final String PASTE_ACTION = PREFIX + "" ; public static final String DELETE_ACTION = PREFIX + "" ; public static final String SELECT_ALL_ACTION = PREFIX + "" ; public static final String OPEN_TYPE_HIERARCHY_ACTION = PREFIX + "" ; public static final String COLLAPSE_ALL_ACTION = PREFIX + "" ; public static final String GOTO_RESOURCE_ACTION = PREFIX + "" ; public static final String LINK_EDITOR_ACTION = PREFIX + "" ; public static final String GO_INTO_TOP_LEVEL_TYPE_ACTION = PREFIX + "" ; public static final String COMPARE_WITH_HISTORY_ACTION = PREFIX + "" ; public static final String REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION = PREFIX + "" ; public static final String REPLACE_WITH_HISTORY_ACTION = PREFIX + "" ; public static final String ADD_FROM_HISTORY_ACTION = PREFIX + "" ; public static final String LAYOUT_FLAT_ACTION = PREFIX + "" ; public static final String LAYOUT_HIERARCHICAL_ACTION = PREFIX + "" ; public static final String NEXT_CHANGE_ACTION = PREFIX + "" ; public static final String PREVIOUS_CHANGE_ACTION = PREFIX + "" ; public static final String NEXT_PROBLEM_ACTION = PREFIX + "" ; public static final String PREVIOUS_PROBLEM_ACTION = PREFIX + "" ; public static final String JAVA_SELECT_MARKER_RULER_ACTION = PREFIX + "" ; public static final String GOTO_NEXT_ERROR_ACTION = PREFIX + "" ; public static final String GOTO_PREVIOUS_ERROR_ACTION = PREFIX + "" ; public static final String SHOW_QUALIFIED_NAMES_ACTION = PREFIX + "" ; public static final String SORT_BY_DEFINING_TYPE_ACTION = PREFIX + "" ; public static final String FORMAT_ACTION = PREFIX + "" ; public static final String COMMENT_ACTION = PREFIX + "" ; public static final String UNCOMMENT_ACTION = PREFIX + "" ; public static final String TOGGLE_COMMENT_ACTION = PREFIX + "" ; public static final String ADD_BLOCK_COMMENT_ACTION = PREFIX + "" ; public static final String REMOVE_BLOCK_COMMENT_ACTION = PREFIX + "" ; public static final String QUICK_FIX_ACTION = PREFIX + "" ; public static final String CONTENT_ASSIST_ACTION = PREFIX + "" ; public static final String PARAMETER_HINTS_ACTION = PREFIX + "" ; public static final String SHOW_JAVADOC_ACTION = PREFIX + "" ; public static final String SHOW_OUTLINE_ACTION = PREFIX + "" ; public static final String OPEN_STRUCTURE_ACTION = PREFIX + "" ; public static final String OPEN_HIERARCHY_ACTION = PREFIX + "" ; public static final String TOGGLE_SMART_TYPING_ACTION = PREFIX + "" ; public static final String INDENT_ACTION = PREFIX + "" ; public static final String MAINTYPE_SELECTION_DIALOG = PREFIX + "" ; public static final String OPEN_TYPE_DIALOG = PREFIX + "" ; public static final String OPEN_PACKAGE_DIALOG = PREFIX + "" ; public static final String SOURCE_ATTACHMENT_DIALOG = PREFIX + "" ; public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG = PREFIX + "" ; public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG = PREFIX + "" ; public static final String NEW_VARIABLE_ENTRY_DIALOG = PREFIX + "" ; public static final String NONNLS_DIALOG = PREFIX + "" ; public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG = PREFIX + "" ; public static final String MULTI_TYPE_SELECTION_DIALOG = PREFIX + "" ; public static final String SUPER_INTERFACE_SELECTION_DIALOG = PREFIX + "" ; public static final String OVERRIDE_TREE_SELECTION_DIALOG = PREFIX + "" ; public static final String MOVE_DESTINATION_DIALOG = PREFIX + "" ; public static final String CHOOSE_VARIABLE_DIALOG = PREFIX + "" ; public static final String EDIT_TEMPLATE_DIALOG = PREFIX + "" ; public static final String HISTORY_LIST_DIALOG = PREFIX + "" ; public static final String IMPORT_ORGANIZE_INPUT_DIALOG = PREFIX + "" ; public static final String TODO_TASK_INPUT_DIALOG = PREFIX + "" ; public static final String JAVADOC_PROPERTY_DIALOG = PREFIX + "" ; public static final String NEW_CONTAINER_DIALOG = PREFIX + "" ; public static final String EXCLUSION_PATTERN_DIALOG = PREFIX + "" ; public static final String OUTPUT_LOCATION_DIALOG = PREFIX + "" ; public static final String VARIABLE_CREATION_DIALOG = PREFIX + "" ; public static final String RUBY_SEARCH_PAGE = PREFIX + "" ; public static final String NLS_SEARCH_PAGE = PREFIX + "" ; public static final String JAVA_EDITOR = PREFIX + "" ; public static final String GOTO_RESOURCE_DIALOG = PREFIX + "" ; public static final String COMPARE_DIALOG = PREFIX + "" ; public static final String ADD_ELEMENT_FROM_HISTORY_DIALOG = PREFIX + "" ; public static final String COMPARE_ELEMENT_WITH_HISTORY_DIALOG = PREFIX + "" ; public static final String REPLACE_ELEMENT_WITH_HISTORY_DIALOG = PREFIX + "" ; public static final String TYPE_HIERARCHY_VIEW = PREFIX + "" ; public static final String PACKAGES_VIEW = PREFIX + "" ; public static final String PROJECTS_VIEW = PREFIX + "" ; public static final String PACKAGES_BROWSING_VIEW = PREFIX + "" ; public static final String TYPES_VIEW = PREFIX + "" ; public static final String MEMBERS_VIEW = PREFIX + "" ; public static final String RDOC_VIEW = PREFIX + "" ; public static final String APPEARANCE_PREFERENCE_PAGE = PREFIX + "" ; public static final String SORT_ORDER_PREFERENCE_PAGE = PREFIX + "" ; public static final String BUILD_PATH_PROPERTY_PAGE = PREFIX + "" ; public static final String CP_VARIABLES_PREFERENCE_PAGE = PREFIX + "" ; public static final String CP_USERLIBRARIES_PREFERENCE_PAGE = PREFIX + "" ; public static final String CODEFORMATTER_PREFERENCE_PAGE = PREFIX + "" ; public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE = PREFIX + "" ; public static final String COMPILER_PROPERTY_PAGE = PREFIX + "" ; public static final String TODOTASK_PROPERTY_PAGE = PREFIX + "" ; public static final String CODE_TEMPLATES_PREFERENCE_PAGE = PREFIX + "" ; public static final String CODE_MANIPULATION_PREFERENCE_PAGE = PREFIX + "" ; public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE = PREFIX + "" ; public static final String JAVA_BASE_PREFERENCE_PAGE = PREFIX + "" ; public static final String REFACTORING_PREFERENCE_PAGE = PREFIX + "" ; public static final String RUBY_EDITOR_PREFERENCE_PAGE = PREFIX + "" ; public static final String COMPILER_PREFERENCE_PAGE = PREFIX + "" ; public static final String TODOTASK_PREFERENCE_PAGE = PREFIX + "" ; public static final String TEMPLATE_PREFERENCE_PAGE = PREFIX + "" ; public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE = PREFIX + "" ; public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE = PREFIX + "" ; public static final String JAVA_ELEMENT_INFO_PAGE = PREFIX + "" ; public static final String NEW_JAVAPROJECT_WIZARD_PAGE = PREFIX + "" ; public static final String NEW_PACKAGE_WIZARD_PAGE = PREFIX + "" ; public static final String NEW_CLASS_WIZARD_PAGE = PREFIX + "" ; public static final String NEW_INTERFACE_WIZARD_PAGE = PREFIX + "" ; public static final String NEW_ENUM_WIZARD_PAGE = PREFIX + "" ; public static final String NEW_ANNOTATION_WIZARD_PAGE = PREFIX + "" ; public static final String NEW_PACKAGEROOT_WIZARD_PAGE = PREFIX + "" ; public static final String JARPACKAGER_WIZARD_PAGE = PREFIX + "" ; public static final String JARMANIFEST_WIZARD_PAGE = PREFIX + "" ; public static final String JAROPTIONS_WIZARD_PAGE = PREFIX + "" ; public static final String JAVA_WORKING_SET_PAGE = PREFIX + "" ; public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE = PREFIX + "" ; public static final String REFACTORING_ERROR_WIZARD_PAGE = PREFIX + "" ; public static final String REFACTORING_PREVIEW_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_PARAMS_WIZARD_PAGE = PREFIX + "" ; public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE = PREFIX + "" ; public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE = PREFIX + "" ; public static final String EXTRACT_INTERFACE_WIZARD_PAGE = PREFIX + "" ; public static final String EXTRACT_METHOD_WIZARD_PAGE = PREFIX + "" ; public static final String EXTRACT_TEMP_WIZARD_PAGE = PREFIX + "" ; public static final String EXTRACT_CONSTANT_WIZARD_PAGE = PREFIX + "" ; public static final String INTRODUCE_PARAMETER_WIZARD_PAGE = PREFIX + "" ; public static final String INTRODUCE_FACTORY_WIZARD_PAGE = PREFIX + "" ; public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE = PREFIX + "" ; public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE = PREFIX + "" ; public static final String MODIFY_PARAMETERS_WIZARD_PAGE = PREFIX + "" ; public static final String MOVE_MEMBERS_WIZARD_PAGE = PREFIX + "" ; public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE = PREFIX + "" ; public static final String PULL_UP_WIZARD_PAGE = PREFIX + "" ; public static final String PUSH_DOWN_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_PACKAGE_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_TYPE_PARAMETER_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_LOCAL_VARIABLE_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_CU_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_METHOD_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_TYPE_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_FIELD_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_RESOURCE_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_JAVA_PROJECT_WIZARD_PAGE = PREFIX + "" ; public static final String RENAME_SOURCE_FOLDER_WIZARD_PAGE = PREFIX + "" ; public static final String SEF_WIZARD_PAGE = PREFIX + "" ; public static final String USE_SUPERTYPE_WIZARD_PAGE = PREFIX + "" ; public static final String INLINE_METHOD_WIZARD_PAGE = PREFIX + "" ; public static final String INLINE_CONSTANT_WIZARD_PAGE = PREFIX + "" ; public static final String BUILD_PATH_BLOCK = PREFIX + "" ; public static final String SOURCE_ATTACHMENT_BLOCK = PREFIX + "" ; public static final String CUSTOM_FILTERS_DIALOG = PREFIX + "" ; public static final String CALL_HIERARCHY_VIEW = PREFIX + "" ; public static final String CALL_HIERARCHY_FILTERS_DIALOG = PREFIX + "" ; public static final String CALL_HIERARCHY_FOCUS_ON_SELECTION_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_HISTORY_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_HISTORY_DROP_DOWN_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_REFRESH_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_SEARCH_SCOPE_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_TOGGLE_CALL_MODE_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_TOGGLE_JAVA_LABEL_FORMAT_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_TOGGLE_ORIENTATION_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_COPY_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_TOGGLE_IMPLEMENTORS_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_OPEN_ACTION = PREFIX + "" ; public static final String CALL_HIERARCHY_CANCEL_SEARCH_ACTION = PREFIX + "" ; } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . rubypeople . rdt . internal . ui . dnd . BasicSelectionTransferDragAdapter ; public class SelectionTransferDragAdapter extends BasicSelectionTransferDragAdapter { public SelectionTransferDragAdapter ( ISelectionProvider provider ) { super ( provider ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . swt . dnd . DragSourceAdapter ; import org . eclipse . swt . dnd . DragSourceEvent ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . part . ResourceTransfer ; public class ResourceTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener { private ISelectionProvider fProvider ; public ResourceTransferDragAdapter ( ISelectionProvider provider ) { fProvider = provider ; Assert . isNotNull ( fProvider ) ; } public Transfer getTransfer ( ) { return ResourceTransfer . getInstance ( ) ; } public void dragStart ( DragSourceEvent event ) { event . doit = convertSelection ( ) . size ( ) > ; } public void dragSetData ( DragSourceEvent event ) { List resources = convertSelection ( ) ; event . data = resources . toArray ( new IResource [ resources . size ( ) ] ) ; } public void dragFinished ( DragSourceEvent event ) { if ( ! event . doit ) return ; } private List convertSelection ( ) { ISelection s = fProvider . getSelection ( ) ; if ( ! ( s instanceof IStructuredSelection ) ) return Collections . EMPTY_LIST ; IStructuredSelection selection = ( IStructuredSelection ) s ; List result = new ArrayList ( selection . size ( ) ) ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof IResource ) { result . add ( element ) ; } } return result ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . ResourceListSelectionDialog ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; public class GotoResourceAction extends Action { private PackageExplorerPart fPackageExplorer ; private static class GotoResourceDialog extends ResourceListSelectionDialog { private IRubyModel fRubyModel ; public GotoResourceDialog ( Shell parentShell , IContainer container , StructuredViewer viewer ) { super ( parentShell , container , IResource . FILE | IResource . FOLDER | IResource . PROJECT ) ; fRubyModel = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; setTitle ( PackagesMessages . GotoResource_dialog_title ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( parentShell , IRubyHelpContextIds . GOTO_RESOURCE_DIALOG ) ; } protected boolean select ( IResource resource ) { IProject project = resource . getProject ( ) ; try { if ( project . getNature ( RubyCore . NATURE_ID ) != null ) return fRubyModel . contains ( resource ) ; } catch ( CoreException e ) { } return true ; } } public GotoResourceAction ( PackageExplorerPart explorer ) { setText ( PackagesMessages . GotoResource_action_label ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . GOTO_RESOURCE_ACTION ) ; fPackageExplorer = explorer ; } public void run ( ) { TreeViewer viewer = fPackageExplorer . getViewer ( ) ; GotoResourceDialog dialog = new GotoResourceDialog ( fPackageExplorer . getSite ( ) . getShell ( ) , ResourcesPlugin . getWorkspace ( ) . getRoot ( ) , viewer ) ; dialog . open ( ) ; Object [ ] result = dialog . getResult ( ) ; if ( result == null || result . length == || ! ( result [ ] instanceof IResource ) ) return ; StructuredSelection selection = null ; IRubyElement element = RubyCore . create ( ( IResource ) result [ ] ) ; if ( element != null && element . exists ( ) ) selection = new StructuredSelection ( element ) ; else selection = new StructuredSelection ( result [ ] ) ; viewer . setSelection ( selection , true ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . OpenStrategy ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeSelection ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . jface . viewers . TreePath ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . actions . OpenInNewWindowAction ; import org . eclipse . ui . views . framelist . BackAction ; import org . eclipse . ui . views . framelist . ForwardAction ; import org . eclipse . ui . views . framelist . Frame ; import org . eclipse . ui . views . framelist . FrameAction ; import org . eclipse . ui . views . framelist . FrameList ; import org . eclipse . ui . views . framelist . GoIntoAction ; import org . eclipse . ui . views . framelist . TreeFrame ; import org . eclipse . ui . views . framelist . UpAction ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . actions . CompositeActionGroup ; import org . rubypeople . rdt . internal . ui . actions . NewWizardsActionGroup ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . GenerateBuildPathActionGroup ; import org . rubypeople . rdt . internal . ui . workingsets . ViewActionGroup ; import org . rubypeople . rdt . internal . ui . workingsets . WorkingSetActionGroup ; import org . rubypeople . rdt . ui . IContextMenuConstants ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . actions . BuildActionGroup ; import org . rubypeople . rdt . ui . actions . CCPActionGroup ; import org . rubypeople . rdt . ui . actions . CustomFiltersActionGroup ; import org . rubypeople . rdt . ui . actions . NavigateActionGroup ; import org . rubypeople . rdt . ui . actions . ProjectActionGroup ; import org . rubypeople . rdt . ui . actions . RubySearchActionGroup ; class RubyExplorerActionGroup extends CompositeActionGroup { private PackageExplorerPart fPart ; private FrameList fFrameList ; private GoIntoAction fZoomInAction ; private BackAction fBackAction ; private ForwardAction fForwardAction ; private UpAction fUpAction ; private GotoTypeAction fGotoTypeAction ; private GotoResourceAction fGotoResourceAction ; private CollapseAllAction fCollapseAllAction ; private ToggleLinkingAction fToggleLinkingAction ; private NavigateActionGroup fNavigateActionGroup ; private ViewActionGroup fViewActionGroup ; private CustomFiltersActionGroup fCustomFiltersActionGroup ; private IAction fGotoRequiredProjectAction ; public RubyExplorerActionGroup ( PackageExplorerPart part ) { super ( ) ; fPart = part ; TreeViewer viewer = part . getViewer ( ) ; IPropertyChangeListener workingSetListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { doWorkingSetChanged ( event ) ; } } ; IWorkbenchPartSite site = fPart . getSite ( ) ; setGroups ( new ActionGroup [ ] { new NewWizardsActionGroup ( site ) , fNavigateActionGroup = new NavigateActionGroup ( fPart ) , new CCPActionGroup ( fPart ) , new GenerateBuildPathActionGroup ( fPart ) , new BuildActionGroup ( fPart ) , new RubySearchActionGroup ( fPart ) , new ProjectActionGroup ( fPart ) , fViewActionGroup = new ViewActionGroup ( fPart . getRootMode ( ) , workingSetListener , site ) , fCustomFiltersActionGroup = new CustomFiltersActionGroup ( fPart , viewer ) , new WorkingSetActionGroup ( fPart ) } ) ; fViewActionGroup . fillFilters ( viewer ) ; PackagesFrameSource frameSource = new PackagesFrameSource ( fPart ) ; fFrameList = new FrameList ( frameSource ) ; frameSource . connectTo ( fFrameList ) ; fZoomInAction = new GoIntoAction ( fFrameList ) ; fBackAction = new BackAction ( fFrameList ) ; fForwardAction = new ForwardAction ( fFrameList ) ; fUpAction = new UpAction ( fFrameList ) ; fGotoTypeAction = new GotoTypeAction ( fPart ) ; fGotoResourceAction = new GotoResourceAction ( fPart ) ; fCollapseAllAction = new CollapseAllAction ( fPart ) ; fToggleLinkingAction = new ToggleLinkingAction ( fPart ) ; } public void dispose ( ) { super . dispose ( ) ; } void restoreFilterAndSorterState ( IMemento memento ) { fViewActionGroup . restoreState ( memento ) ; fCustomFiltersActionGroup . restoreState ( memento ) ; } void saveFilterAndSorterState ( IMemento memento ) { fViewActionGroup . saveState ( memento ) ; fCustomFiltersActionGroup . saveState ( memento ) ; } public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; setGlobalActionHandlers ( actionBars ) ; fillToolBar ( actionBars . getToolBarManager ( ) ) ; fillViewMenu ( actionBars . getMenuManager ( ) ) ; } void updateActionBars ( IActionBars actionBars ) { actionBars . getToolBarManager ( ) . removeAll ( ) ; actionBars . getMenuManager ( ) . removeAll ( ) ; fillActionBars ( actionBars ) ; actionBars . updateActionBars ( ) ; fZoomInAction . setEnabled ( true ) ; } private void setGlobalActionHandlers ( IActionBars actionBars ) { actionBars . setGlobalActionHandler ( IWorkbenchActionConstants . GO_INTO , fZoomInAction ) ; actionBars . setGlobalActionHandler ( ActionFactory . BACK . getId ( ) , fBackAction ) ; actionBars . setGlobalActionHandler ( ActionFactory . FORWARD . getId ( ) , fForwardAction ) ; actionBars . setGlobalActionHandler ( IWorkbenchActionConstants . UP , fUpAction ) ; actionBars . setGlobalActionHandler ( IWorkbenchActionConstants . GO_TO_RESOURCE , fGotoResourceAction ) ; } void fillToolBar ( IToolBarManager toolBar ) { toolBar . add ( fBackAction ) ; toolBar . add ( fForwardAction ) ; toolBar . add ( fUpAction ) ; toolBar . add ( new Separator ( ) ) ; toolBar . add ( fCollapseAllAction ) ; toolBar . add ( fToggleLinkingAction ) ; } void fillViewMenu ( IMenuManager menu ) { menu . add ( fToggleLinkingAction ) ; menu . add ( new Separator ( IWorkbenchActionConstants . MB_ADDITIONS ) ) ; menu . add ( new Separator ( IWorkbenchActionConstants . MB_ADDITIONS + "" ) ) ; } public void fillContextMenu ( IMenuManager menu ) { IStructuredSelection selection = ( IStructuredSelection ) getContext ( ) . getSelection ( ) ; int size = selection . size ( ) ; Object element = selection . getFirstElement ( ) ; if ( element instanceof LoadPathContainer . RequiredProjectWrapper ) menu . appendToGroup ( IContextMenuConstants . GROUP_SHOW , fGotoRequiredProjectAction ) ; addGotoMenu ( menu , element , size ) ; addOpenNewWindowAction ( menu , element ) ; super . fillContextMenu ( menu ) ; } private void addGotoMenu ( IMenuManager menu , Object element , int size ) { boolean enabled = size == && fPart . getViewer ( ) . isExpandable ( element ) && ( isGoIntoTarget ( element ) || element instanceof IContainer ) ; fZoomInAction . setEnabled ( enabled ) ; if ( enabled ) menu . appendToGroup ( IContextMenuConstants . GROUP_GOTO , fZoomInAction ) ; } private boolean isGoIntoTarget ( Object element ) { if ( element == null ) return false ; if ( element instanceof IRubyElement ) { int type = ( ( IRubyElement ) element ) . getElementType ( ) ; return type == IRubyElement . RUBY_PROJECT || type == IRubyElement . SOURCE_FOLDER_ROOT || type == IRubyElement . SOURCE_FOLDER ; } if ( element instanceof IWorkingSet ) { return true ; } return false ; } private void addOpenNewWindowAction ( IMenuManager menu , Object element ) { if ( element instanceof IRubyElement ) { element = ( ( IRubyElement ) element ) . getResource ( ) ; } if ( element instanceof IProject && ! ( ( IProject ) element ) . isOpen ( ) ) return ; if ( ! ( element instanceof IContainer ) ) return ; menu . appendToGroup ( IContextMenuConstants . GROUP_OPEN , new OpenInNewWindowAction ( fPart . getSite ( ) . getWorkbenchWindow ( ) , ( IContainer ) element ) ) ; } void handleDoubleClick ( DoubleClickEvent event ) { TreeViewer viewer = fPart . getViewer ( ) ; IStructuredSelection selection = ( IStructuredSelection ) event . getSelection ( ) ; Object element = selection . getFirstElement ( ) ; if ( viewer . isExpandable ( element ) ) { if ( doubleClickGoesInto ( ) ) { if ( element instanceof IRubyScript ) return ; if ( element instanceof IOpenable || element instanceof IContainer || element instanceof IWorkingSet ) { fZoomInAction . run ( ) ; } } else { IAction openAction = fNavigateActionGroup . getOpenAction ( ) ; if ( openAction != null && openAction . isEnabled ( ) && OpenStrategy . getOpenMethod ( ) == OpenStrategy . DOUBLE_CLICK ) return ; if ( selection instanceof ITreeSelection ) { TreePath [ ] paths = ( ( ITreeSelection ) selection ) . getPathsFor ( element ) ; for ( int i = ; i < paths . length ; i ++ ) { viewer . setExpandedState ( paths [ i ] , ! viewer . getExpandedState ( paths [ i ] ) ) ; } } else { viewer . setExpandedState ( element , ! viewer . getExpandedState ( element ) ) ; } } } } void handleOpen ( OpenEvent event ) { IAction openAction = fNavigateActionGroup . getOpenAction ( ) ; if ( openAction != null && openAction . isEnabled ( ) ) { openAction . run ( ) ; return ; } } void handleKeyEvent ( KeyEvent event ) { if ( event . stateMask != ) return ; if ( event . keyCode == SWT . BS ) { if ( fUpAction != null && fUpAction . isEnabled ( ) ) { fUpAction . run ( ) ; event . doit = false ; } } } private void doWorkingSetChanged ( PropertyChangeEvent event ) { if ( ViewActionGroup . MODE_CHANGED . equals ( event . getProperty ( ) ) ) { fPart . rootModeChanged ( ( ( Integer ) event . getNewValue ( ) ) . intValue ( ) ) ; Object oldInput = null ; Object newInput = null ; if ( fPart . showProjects ( ) ) { oldInput = fPart . getWorkingSetModel ( ) ; newInput = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; } else if ( fPart . showWorkingSets ( ) ) { oldInput = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; newInput = fPart . getWorkingSetModel ( ) ; } if ( oldInput != null && newInput != null ) { Frame frame ; for ( int i = ; ( frame = fFrameList . getFrame ( i ) ) != null ; i ++ ) { if ( frame instanceof TreeFrame ) { TreeFrame treeFrame = ( TreeFrame ) frame ; if ( oldInput . equals ( treeFrame . getInput ( ) ) ) treeFrame . setInput ( newInput ) ; } } } } else { IWorkingSet workingSet = ( IWorkingSet ) event . getNewValue ( ) ; String workingSetLabel = null ; if ( workingSet != null ) workingSetLabel = workingSet . getLabel ( ) ; fPart . setWorkingSetLabel ( workingSetLabel ) ; fPart . updateTitle ( ) ; String property = event . getProperty ( ) ; if ( IWorkingSetManager . CHANGE_WORKING_SET_CONTENT_CHANGE . equals ( property ) ) { TreeViewer viewer = fPart . getViewer ( ) ; viewer . getControl ( ) . setRedraw ( false ) ; viewer . refresh ( ) ; viewer . getControl ( ) . setRedraw ( true ) ; } } } private boolean doubleClickGoesInto ( ) { return PreferenceConstants . DOUBLE_CLICK_GOES_INTO . equals ( PreferenceConstants . getPreferenceStore ( ) . getString ( PreferenceConstants . DOUBLE_CLICK ) ) ; } public FrameAction getUpAction ( ) { return fUpAction ; } public FrameAction getBackAction ( ) { return fBackAction ; } public FrameAction getForwardAction ( ) { return fForwardAction ; } public ViewActionGroup getWorkingSetActionGroup ( ) { return fViewActionGroup ; } public CustomFiltersActionGroup getCustomFilterActionGroup ( ) { return fCustomFiltersActionGroup ; } public FrameList getFrameList ( ) { return fFrameList ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; class CollapseAllAction extends Action { private PackageExplorerPart fPackageExplorer ; CollapseAllAction ( PackageExplorerPart part ) { super ( PackagesMessages . CollapseAllAction_label ) ; setDescription ( PackagesMessages . CollapseAllAction_description ) ; setToolTipText ( PackagesMessages . CollapseAllAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; fPackageExplorer = part ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . COLLAPSE_ALL_ACTION ) ; } public void run ( ) { fPackageExplorer . collapseAll ( ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DragSourceAdapter ; import org . eclipse . swt . dnd . DragSourceEvent ; import org . eclipse . swt . dnd . FileTransfer ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . actions . WorkspaceModifyOperation ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . internal . corext . util . Resources ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; class FileTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener { private ISelectionProvider fProvider ; FileTransferDragAdapter ( ISelectionProvider provider ) { fProvider = provider ; Assert . isNotNull ( fProvider ) ; } public Transfer getTransfer ( ) { return FileTransfer . getInstance ( ) ; } public void dragStart ( DragSourceEvent event ) { event . doit = isDragable ( fProvider . getSelection ( ) ) ; } private boolean isDragable ( ISelection s ) { if ( ! ( s instanceof IStructuredSelection ) ) return false ; IStructuredSelection selection = ( IStructuredSelection ) s ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof IRubyElement ) { IRubyElement jElement = ( IRubyElement ) element ; int type = jElement . getElementType ( ) ; if ( type != IRubyElement . SOURCE_FOLDER_ROOT && type != IRubyElement . SCRIPT && type != IRubyElement . TYPE ) return false ; ISourceFolderRoot root = ( ISourceFolderRoot ) jElement . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; if ( root != null && root . isArchive ( ) ) return false ; } } List resources = convertIntoResources ( selection ) ; return resources . size ( ) == selection . size ( ) ; } public void dragSetData ( DragSourceEvent event ) { List elements = getResources ( ) ; if ( elements == null || elements . size ( ) == ) { event . data = null ; return ; } event . data = getResourceLocations ( elements ) ; } private static String [ ] getResourceLocations ( List resources ) { return Resources . getLocationOSStrings ( ( IResource [ ] ) resources . toArray ( new IResource [ resources . size ( ) ] ) ) ; } public void dragFinished ( DragSourceEvent event ) { if ( ! event . doit ) return ; if ( event . detail == DND . DROP_MOVE ) { } else if ( event . detail == DND . DROP_NONE || event . detail == DND . DROP_TARGET_MOVE ) { handleRefresh ( event ) ; } } void handleDropMove ( DragSourceEvent event ) { final List elements = getResources ( ) ; if ( elements == null || elements . size ( ) == ) return ; WorkspaceModifyOperation op = new WorkspaceModifyOperation ( ) { public void execute ( IProgressMonitor monitor ) throws CoreException { try { monitor . beginTask ( PackagesMessages . DragAdapter_deleting , elements . size ( ) ) ; MultiStatus status = createMultiStatus ( ) ; Iterator iter = elements . iterator ( ) ; while ( iter . hasNext ( ) ) { IResource resource = ( IResource ) iter . next ( ) ; try { monitor . subTask ( resource . getFullPath ( ) . toOSString ( ) ) ; resource . delete ( true , null ) ; } catch ( CoreException e ) { status . add ( e . getStatus ( ) ) ; } finally { monitor . worked ( ) ; } } if ( ! status . isOK ( ) ) { throw new CoreException ( status ) ; } } finally { monitor . done ( ) ; } } } ; runOperation ( op , true , false ) ; } private void handleRefresh ( DragSourceEvent event ) { final Set roots = collectRoots ( getResources ( ) ) ; WorkspaceModifyOperation op = new WorkspaceModifyOperation ( ) { public void execute ( IProgressMonitor monitor ) throws CoreException { try { monitor . beginTask ( PackagesMessages . DragAdapter_refreshing , roots . size ( ) ) ; MultiStatus status = createMultiStatus ( ) ; Iterator iter = roots . iterator ( ) ; while ( iter . hasNext ( ) ) { IResource r = ( IResource ) iter . next ( ) ; try { r . refreshLocal ( IResource . DEPTH_ONE , new SubProgressMonitor ( monitor , ) ) ; } catch ( CoreException e ) { status . add ( e . getStatus ( ) ) ; } } if ( ! status . isOK ( ) ) { throw new CoreException ( status ) ; } } finally { monitor . done ( ) ; } } } ; runOperation ( op , true , false ) ; } protected Set collectRoots ( final List elements ) { final Set roots = new HashSet ( ) ; Iterator iter = elements . iterator ( ) ; while ( iter . hasNext ( ) ) { IResource resource = ( IResource ) iter . next ( ) ; IResource parent = resource . getParent ( ) ; if ( parent == null ) { roots . add ( resource ) ; } else { roots . add ( parent ) ; } } return roots ; } private List getResources ( ) { ISelection s = fProvider . getSelection ( ) ; if ( ! ( s instanceof IStructuredSelection ) ) return null ; return convertIntoResources ( ( IStructuredSelection ) s ) ; } private List convertIntoResources ( IStructuredSelection selection ) { List result = new ArrayList ( selection . size ( ) ) ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object o = iter . next ( ) ; IResource r = null ; if ( o instanceof IResource ) { r = ( IResource ) o ; } else if ( o instanceof IAdaptable ) { r = ( IResource ) ( ( IAdaptable ) o ) . getAdapter ( IResource . class ) ; } if ( r != null && r . getLocation ( ) != null ) { result . add ( r ) ; } } return result ; } private MultiStatus createMultiStatus ( ) { return new MultiStatus ( RubyPlugin . getPluginId ( ) , IStatus . OK , PackagesMessages . DragAdapter_problem , null ) ; } private void runOperation ( IRunnableWithProgress op , boolean fork , boolean cancelable ) { try { Shell parent = RubyPlugin . getActiveWorkbenchShell ( ) ; new ProgressMonitorDialog ( parent ) . run ( fork , cancelable , op ) ; } catch ( InvocationTargetException e ) { String message = PackagesMessages . DragAdapter_problem ; String title = PackagesMessages . DragAdapter_problemTitle ; ExceptionHandler . handle ( e , title , message ) ; } catch ( InterruptedException e ) { } } } package org . rubypeople . rdt . internal . ui . packageview ; import java . util . Enumeration ; import java . util . NoSuchElementException ; import org . eclipse . jface . viewers . IElementComparer ; final class CustomHashtable { private static class HashMapEntry { Object key , value ; HashMapEntry next ; HashMapEntry ( Object theKey , Object theValue ) { key = theKey ; value = theValue ; } } private static final class EmptyEnumerator implements Enumeration { public boolean hasMoreElements ( ) { return false ; } public Object nextElement ( ) { throw new NoSuchElementException ( ) ; } } private class HashEnumerator implements Enumeration { boolean key ; int start ; HashMapEntry entry ; HashEnumerator ( boolean isKey ) { key = isKey ; start = firstSlot ; } public boolean hasMoreElements ( ) { if ( entry != null ) return true ; while ( start <= lastSlot ) if ( elementData [ start ++ ] != null ) { entry = elementData [ start - ] ; return true ; } return false ; } public Object nextElement ( ) { if ( hasMoreElements ( ) ) { Object result = key ? entry . key : entry . value ; entry = entry . next ; return result ; } else throw new NoSuchElementException ( ) ; } } transient int elementCount ; transient HashMapEntry [ ] elementData ; private float loadFactor ; private int threshold ; transient int firstSlot = ; transient int lastSlot = - ; transient private IElementComparer comparer ; private static final EmptyEnumerator emptyEnumerator = new EmptyEnumerator ( ) ; public static final int DEFAULT_CAPACITY = ; public CustomHashtable ( ) { this ( ) ; } public CustomHashtable ( int capacity ) { this ( capacity , null ) ; } public CustomHashtable ( IElementComparer comparer ) { this ( DEFAULT_CAPACITY , comparer ) ; } public CustomHashtable ( int capacity , IElementComparer comparer ) { if ( capacity >= ) { elementCount = ; elementData = new HashMapEntry [ capacity == ? : capacity ] ; firstSlot = elementData . length ; loadFactor = ; computeMaxSize ( ) ; } else throw new IllegalArgumentException ( ) ; this . comparer = comparer ; } public CustomHashtable ( CustomHashtable table , IElementComparer comparer ) { this ( table . size ( ) * , comparer ) ; for ( int i = table . elementData . length ; -- i >= ; ) { HashMapEntry entry = table . elementData [ i ] ; while ( entry != null ) { put ( entry . key , entry . value ) ; entry = entry . next ; } } } private void computeMaxSize ( ) { threshold = ( int ) ( elementData . length * loadFactor ) ; } public boolean containsKey ( Object key ) { return getEntry ( key ) != null ; } public Enumeration elements ( ) { if ( elementCount == ) return emptyEnumerator ; return new HashEnumerator ( false ) ; } public Object get ( Object key ) { int index = ( hashCode ( key ) & ) % elementData . length ; HashMapEntry entry = elementData [ index ] ; while ( entry != null ) { if ( keyEquals ( key , entry . key ) ) return entry . value ; entry = entry . next ; } return null ; } private HashMapEntry getEntry ( Object key ) { int index = ( hashCode ( key ) & ) % elementData . length ; HashMapEntry entry = elementData [ index ] ; while ( entry != null ) { if ( keyEquals ( key , entry . key ) ) return entry ; entry = entry . next ; } return null ; } private int hashCode ( Object key ) { if ( comparer == null ) return key . hashCode ( ) ; else return comparer . hashCode ( key ) ; } private boolean keyEquals ( Object a , Object b ) { if ( comparer == null ) return a . equals ( b ) ; else return comparer . equals ( a , b ) ; } public Enumeration keys ( ) { if ( elementCount == ) return emptyEnumerator ; return new HashEnumerator ( true ) ; } public Object put ( Object key , Object value ) { if ( key != null && value != null ) { int index = ( hashCode ( key ) & ) % elementData . length ; HashMapEntry entry = elementData [ index ] ; while ( entry != null && ! keyEquals ( key , entry . key ) ) entry = entry . next ; if ( entry == null ) { if ( ++ elementCount > threshold ) { rehash ( ) ; index = ( hashCode ( key ) & ) % elementData . length ; } if ( index < firstSlot ) firstSlot = index ; if ( index > lastSlot ) lastSlot = index ; entry = new HashMapEntry ( key , value ) ; entry . next = elementData [ index ] ; elementData [ index ] = entry ; return null ; } Object result = entry . value ; entry . key = key ; entry . value = value ; return result ; } else throw new NullPointerException ( ) ; } private void rehash ( ) { int length = elementData . length << ; if ( length == ) length = ; firstSlot = length ; lastSlot = - ; HashMapEntry [ ] newData = new HashMapEntry [ length ] ; for ( int i = elementData . length ; -- i >= ; ) { HashMapEntry entry = elementData [ i ] ; while ( entry != null ) { int index = ( hashCode ( entry . key ) & ) % length ; if ( index < firstSlot ) firstSlot = index ; if ( index > lastSlot ) lastSlot = index ; HashMapEntry next = entry . next ; entry . next = newData [ index ] ; newData [ index ] = entry ; entry = next ; } } elementData = newData ; computeMaxSize ( ) ; } public Object remove ( Object key ) { HashMapEntry last = null ; int index = ( hashCode ( key ) & ) % elementData . length ; HashMapEntry entry = elementData [ index ] ; while ( entry != null && ! keyEquals ( key , entry . key ) ) { last = entry ; entry = entry . next ; } if ( entry != null ) { if ( last == null ) elementData [ index ] = entry . next ; else last . next = entry . next ; elementCount -- ; return entry . value ; } return null ; } public int size ( ) { return elementCount ; } public String toString ( ) { if ( size ( ) == ) return "" ; StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( '' ) ; for ( int i = elementData . length ; -- i >= ; ) { HashMapEntry entry = elementData [ i ] ; while ( entry != null ) { buffer . append ( entry . key ) ; buffer . append ( '' ) ; buffer . append ( entry . value ) ; buffer . append ( "" ) ; entry = entry . next ; } } if ( elementCount > ) buffer . setLength ( buffer . length ( ) - ) ; buffer . append ( '' ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . util . TransferDropTargetListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DropTargetEvent ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . views . navigator . LocalSelectionTransfer ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . dnd . RdtViewerDropAdapter ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public class SelectionTransferDropAdapter extends RdtViewerDropAdapter implements TransferDropTargetListener { private List fElements ; private int fCanMoveElements ; private int fCanCopyElements ; private ISelection fSelection ; private static final long DROP_TIME_DIFF_TRESHOLD = ; public SelectionTransferDropAdapter ( StructuredViewer viewer ) { super ( viewer , DND . FEEDBACK_SCROLL | DND . FEEDBACK_EXPAND ) ; } public Transfer getTransfer ( ) { return LocalSelectionTransfer . getInstance ( ) ; } public boolean isEnabled ( DropTargetEvent event ) { Object target = event . item != null ? event . item . getData ( ) : null ; if ( target == null ) return false ; return target instanceof IRubyElement || target instanceof IResource ; } public void dragEnter ( DropTargetEvent event ) { clear ( ) ; super . dragEnter ( event ) ; } public void dragLeave ( DropTargetEvent event ) { clear ( ) ; super . dragLeave ( event ) ; } private void clear ( ) { fElements = null ; fSelection = null ; fCanMoveElements = ; fCanCopyElements = ; } public void validateDrop ( Object target , DropTargetEvent event , int operation ) { event . detail = DND . DROP_NONE ; if ( tooFast ( event ) ) return ; initializeSelection ( ) ; try { switch ( operation ) { case DND . DROP_DEFAULT : event . detail = handleValidateDefault ( target , event ) ; break ; case DND . DROP_COPY : event . detail = handleValidateCopy ( target , event ) ; break ; case DND . DROP_MOVE : event . detail = handleValidateMove ( target , event ) ; break ; } } catch ( RubyModelException e ) { ExceptionHandler . handle ( e , PackagesMessages . SelectionTransferDropAdapter_error_title , PackagesMessages . SelectionTransferDropAdapter_error_message ) ; event . detail = DND . DROP_NONE ; } } protected void initializeSelection ( ) { if ( fElements != null ) return ; ISelection s = LocalSelectionTransfer . getInstance ( ) . getSelection ( ) ; if ( ! ( s instanceof IStructuredSelection ) ) return ; fSelection = s ; fElements = ( ( IStructuredSelection ) s ) . toList ( ) ; } protected ISelection getSelection ( ) { return fSelection ; } private boolean tooFast ( DropTargetEvent event ) { return Math . abs ( LocalSelectionTransfer . getInstance ( ) . getSelectionSetTime ( ) - ( event . time & ) ) < DROP_TIME_DIFF_TRESHOLD ; } public void drop ( Object target , DropTargetEvent event ) { try { switch ( event . detail ) { case DND . DROP_MOVE : handleDropMove ( target , event ) ; break ; case DND . DROP_COPY : handleDropCopy ( target , event ) ; break ; } } catch ( RubyModelException e ) { ExceptionHandler . handle ( e , PackagesMessages . SelectionTransferDropAdapter_error_title , PackagesMessages . SelectionTransferDropAdapter_error_message ) ; } catch ( InterruptedException e ) { } finally { event . detail = DND . DROP_NONE ; } } private int handleValidateDefault ( Object target , DropTargetEvent event ) throws RubyModelException { if ( target == null ) return DND . DROP_NONE ; if ( ( event . operations & DND . DROP_MOVE ) != ) { return handleValidateMove ( target , event ) ; } if ( ( event . operations & DND . DROP_COPY ) != ) { return handleValidateCopy ( target , event ) ; } return DND . DROP_NONE ; } private int handleValidateMove ( Object target , DropTargetEvent event ) throws RubyModelException { if ( target == null ) return DND . DROP_NONE ; return DND . DROP_MOVE ; } private void handleDropMove ( final Object target , DropTargetEvent event ) throws RubyModelException , InterruptedException { try { if ( ! ( event . data instanceof IStructuredSelection ) ) return ; IStructuredSelection selection = ( IStructuredSelection ) event . data ; IResource resource = null ; if ( selection . getFirstElement ( ) instanceof IResource ) { resource = ( IResource ) selection . getFirstElement ( ) ; } else if ( selection . getFirstElement ( ) instanceof IAdaptable ) { IAdaptable adaptable = ( IAdaptable ) selection . getFirstElement ( ) ; resource = ( IResource ) adaptable . getAdapter ( IResource . class ) ; } if ( resource == null ) return ; IContainer container = null ; if ( target instanceof IContainer ) { container = ( IContainer ) target ; } else if ( target instanceof IRubyElement ) { IRubyElement element = ( IRubyElement ) target ; IResource blah = element . getCorrespondingResource ( ) ; if ( blah instanceof IContainer ) { container = ( IContainer ) blah ; } } if ( container == null ) return ; if ( container . equals ( resource . getParent ( ) ) ) return ; resource . move ( container . getFullPath ( ) . append ( resource . getName ( ) ) , false , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } private int handleValidateCopy ( Object target , DropTargetEvent event ) throws RubyModelException { return DND . DROP_COPY ; } private void handleDropCopy ( final Object target , DropTargetEvent event ) throws RubyModelException , InterruptedException { } private Shell getShell ( ) { return getViewer ( ) . getControl ( ) . getShell ( ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . swt . graphics . Image ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . IWorkingSet ; public class WorkingSetAwareLabelProvider extends PackageExplorerLabelProvider { private Map fImages = new HashMap ( ) ; public WorkingSetAwareLabelProvider ( long textFlags , int imageFlags , PackageExplorerContentProvider cp ) { super ( textFlags , imageFlags , cp ) ; } public String getText ( Object element ) { if ( element instanceof IWorkingSet ) { return decorateText ( ( ( IWorkingSet ) element ) . getLabel ( ) , element ) ; } return super . getText ( element ) ; } public Image getImage ( Object element ) { if ( element instanceof IWorkingSet ) { ImageDescriptor image = ( ( IWorkingSet ) element ) . getImage ( ) ; Image result = ( Image ) fImages . get ( image ) ; if ( result == null ) { result = image . createImage ( ) ; fImages . put ( image , result ) ; } return decorateImage ( result , element ) ; } return super . getImage ( element ) ; } public void dispose ( ) { for ( Iterator iter = fImages . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { ( ( Image ) iter . next ( ) ) . dispose ( ) ; } super . dispose ( ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . SelectionDialog ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . RubyUI ; class GotoTypeAction extends Action { private PackageExplorerPart fPackageExplorer ; GotoTypeAction ( PackageExplorerPart part ) { super ( ) ; setText ( PackagesMessages . GotoType_action_label ) ; setDescription ( PackagesMessages . GotoType_action_description ) ; fPackageExplorer = part ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . GOTO_TYPE_ACTION ) ; } public void run ( ) { Shell shell = RubyPlugin . getActiveWorkbenchShell ( ) ; SelectionDialog dialog = null ; try { dialog = RubyUI . createTypeDialog ( shell , new ProgressMonitorDialog ( shell ) , SearchEngine . createWorkspaceScope ( ) , IRubySearchConstants . TYPE , false ) ; } catch ( RubyModelException e ) { String title = getDialogTitle ( ) ; String message = PackagesMessages . GotoType_error_message ; ExceptionHandler . handle ( e , title , message ) ; return ; } dialog . setTitle ( getDialogTitle ( ) ) ; dialog . setMessage ( PackagesMessages . GotoType_dialog_message ) ; if ( dialog . open ( ) == IDialogConstants . CANCEL_ID ) { return ; } Object [ ] types = dialog . getResult ( ) ; if ( types != null && types . length > ) { gotoType ( ( IType ) types [ ] ) ; } } private void gotoType ( IType type ) { IRubyScript cu = ( IRubyScript ) type . getAncestor ( IRubyElement . SCRIPT ) ; IRubyElement element = null ; if ( cu != null ) { element = cu . getPrimary ( ) ; } if ( element != null ) { PackageExplorerPart view = PackageExplorerPart . openInActivePerspective ( ) ; if ( view != null ) { view . selectReveal ( new StructuredSelection ( element ) ) ; if ( ! element . equals ( getSelectedElement ( view ) ) ) { MessageDialog . openInformation ( fPackageExplorer . getSite ( ) . getShell ( ) , getDialogTitle ( ) , Messages . format ( PackagesMessages . PackageExplorer_element_not_present , element . getElementName ( ) ) ) ; } } } } private Object getSelectedElement ( PackageExplorerPart view ) { return ( ( IStructuredSelection ) view . getSite ( ) . getSelectionProvider ( ) . getSelection ( ) ) . getFirstElement ( ) ; } private String getDialogTitle ( ) { return PackagesMessages . GotoType_dialog_title ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . io . IOException ; import java . io . StringReader ; import java . io . StringWriter ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . PerformanceStats ; import org . eclipse . core . runtime . SafeRunner ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IStatusLineManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . util . TransferDragSourceListener ; import org . eclipse . jface . util . TransferDropTargetListener ; import org . eclipse . jface . viewers . AbstractTreeViewer ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . IElementComparer ; import org . eclipse . jface . viewers . ILabelDecorator ; import org . eclipse . jface . viewers . IOpenListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeSelection ; import org . eclipse . jface . viewers . ITreeViewerListener ; import org . eclipse . jface . viewers . OpenEvent ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeExpansionEvent ; import org . eclipse . jface . viewers . TreePath ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . FileTransfer ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . ScrollBar ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . TreeItem ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IPartListener ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . WorkbenchException ; import org . eclipse . ui . XMLMemento ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . part . ISetSelectionTarget ; import org . eclipse . ui . part . IShowInSource ; import org . eclipse . ui . part . IShowInTarget ; import org . eclipse . ui . part . IShowInTargetList ; import org . eclipse . ui . part . ResourceTransfer ; import org . eclipse . ui . part . ShowInContext ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . views . framelist . Frame ; import org . eclipse . ui . views . framelist . FrameAction ; import org . eclipse . ui . views . framelist . FrameList ; import org . eclipse . ui . views . framelist . IFrameSource ; import org . eclipse . ui . views . framelist . TreeFrame ; import org . eclipse . ui . views . navigator . LocalSelectionTransfer ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dnd . DelegatingDropAdapter ; import org . rubypeople . rdt . internal . ui . dnd . RdtViewerDragAdapter ; import org . rubypeople . rdt . internal . ui . preferences . MembersOrderPreferenceCache ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . rubyeditor . ExternalRubyFileEditorInput ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptEditorInput ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . DecoratingRubyLabelProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . FilterUpdater ; import org . rubypeople . rdt . internal . ui . viewsupport . IViewPartInputProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemTreeViewer ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . StatusBarUpdater ; import org . rubypeople . rdt . internal . ui . workingsets . ConfigureWorkingSetAction ; import org . rubypeople . rdt . internal . ui . workingsets . ViewActionGroup ; import org . rubypeople . rdt . internal . ui . workingsets . WorkingSetFilterActionGroup ; import org . rubypeople . rdt . internal . ui . workingsets . WorkingSetModel ; import org . rubypeople . rdt . ui . IPackagesViewPart ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . RubyElementSorter ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; import org . rubypeople . rdt . ui . actions . CustomFiltersActionGroup ; public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget , IMenuListener , IShowInTarget , IPackagesViewPart , IPropertyChangeListener , IViewPartInputProvider { private static final String PERF_CREATE_PART_CONTROL = "" ; private static final String PERF_MAKE_ACTIONS = "" ; private boolean fIsCurrentLayoutFlat ; private static final int HIERARCHICAL_LAYOUT = ; private static final int FLAT_LAYOUT = ; public final static String VIEW_ID = RubyUI . ID_RUBY_EXPLORER ; static final String TAG_SELECTION = "" ; static final String TAG_EXPANDED = "" ; static final String TAG_ELEMENT = "" ; static final String TAG_PATH = "" ; static final String TAG_VERTICAL_POSITION = "" ; static final String TAG_HORIZONTAL_POSITION = "" ; static final String TAG_FILTERS = "" ; static final String TAG_FILTER = "" ; static final String TAG_LAYOUT = "" ; static final String TAG_CURRENT_FRAME = "" ; static final String TAG_ROOT_MODE = "" ; static final String SETTING_MEMENTO = "" ; private int fRootMode ; private WorkingSetModel fWorkingSetModel ; private PackageExplorerLabelProvider fLabelProvider ; private PackageExplorerContentProvider fContentProvider ; private FilterUpdater fFilterUpdater ; private RubyExplorerActionGroup fActionSet ; private ProblemTreeViewer fViewer ; private Menu fContextMenu ; private IMemento fMemento ; private ISelection fLastOpenSelection ; private ISelectionChangedListener fPostSelectionListener ; private String fWorkingSetLabel ; private IPartListener fPartListener = new IPartListener ( ) { public void partActivated ( IWorkbenchPart part ) { if ( part instanceof IEditorPart ) editorActivated ( ( IEditorPart ) part ) ; } public void partBroughtToTop ( IWorkbenchPart part ) { } public void partClosed ( IWorkbenchPart part ) { } public void partDeactivated ( IWorkbenchPart part ) { } public void partOpened ( IWorkbenchPart part ) { } } ; private ITreeViewerListener fExpansionListener = new ITreeViewerListener ( ) { public void treeCollapsed ( TreeExpansionEvent event ) { } public void treeExpanded ( TreeExpansionEvent event ) { Object element = event . getElement ( ) ; if ( element instanceof IRubyScript ) expandMainType ( element ) ; } } ; private class PackageExplorerProblemTreeViewer extends ProblemTreeViewer { private List fPendingRefreshes ; public PackageExplorerProblemTreeViewer ( Composite parent , int style ) { super ( parent , style ) ; fPendingRefreshes = Collections . synchronizedList ( new ArrayList ( ) ) ; } public void add ( Object parentElement , Object [ ] childElements ) { if ( fPendingRefreshes . contains ( parentElement ) ) { return ; } super . add ( parentElement , childElements ) ; } protected void internalRefresh ( Object element , boolean updateLabels ) { try { fPendingRefreshes . add ( element ) ; super . internalRefresh ( element , updateLabels ) ; } finally { fPendingRefreshes . remove ( element ) ; } } protected Object [ ] getFilteredChildren ( Object parent ) { Object [ ] children = getRawChildren ( parent ) ; if ( ! hasFilters ( ) ) { return children ; } List list = new ArrayList ( ) ; ViewerFilter [ ] filters = getFilters ( ) ; for ( int i = ; i < children . length ; i ++ ) { Object object = children [ i ] ; if ( ! isFiltered ( object , parent , filters ) ) { list . add ( object ) ; } } return list . toArray ( ) ; } protected boolean evaluateExpandableWithFilters ( Object parent ) { if ( parent instanceof IRubyProject || parent instanceof IRubyScript || parent instanceof LoadPathContainer ) { return false ; } if ( parent instanceof ISourceFolderRoot && ( ( ISourceFolderRoot ) parent ) . isArchive ( ) ) { return false ; } return true ; } protected boolean isFiltered ( Object object , Object parent , ViewerFilter [ ] filters ) { boolean res = super . isFiltered ( object , parent , filters ) ; if ( res && isEssential ( object ) ) { return false ; } return res ; } protected Object [ ] filter ( Object [ ] elements ) { if ( isFlatLayout ( ) ) return super . filter ( elements ) ; ViewerFilter [ ] filters = getFilters ( ) ; if ( filters == null || filters . length == ) return elements ; ArrayList filtered = new ArrayList ( elements . length ) ; Object root = getRoot ( ) ; for ( int i = ; i < elements . length ; i ++ ) { boolean add = true ; if ( ! isEssential ( elements [ i ] ) ) { for ( int j = ; j < filters . length ; j ++ ) { add = filters [ j ] . select ( this , root , elements [ i ] ) ; if ( ! add ) break ; } } if ( add ) filtered . add ( elements [ i ] ) ; } return filtered . toArray ( ) ; } private boolean isEssential ( Object object ) { return false ; } protected void handleInvalidSelection ( ISelection invalidSelection , ISelection newSelection ) { IStructuredSelection is = ( IStructuredSelection ) invalidSelection ; List ns = null ; if ( newSelection instanceof IStructuredSelection ) { ns = new ArrayList ( ( ( IStructuredSelection ) newSelection ) . toList ( ) ) ; } else { ns = new ArrayList ( ) ; } boolean changed = false ; for ( Iterator iter = is . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof IRubyProject ) { IProject project = ( ( IRubyProject ) element ) . getProject ( ) ; if ( ! project . isOpen ( ) && project . exists ( ) ) { ns . add ( project ) ; changed = true ; } } else if ( element instanceof IProject ) { IProject project = ( IProject ) element ; if ( project . isOpen ( ) ) { IRubyProject jProject = RubyCore . create ( project ) ; if ( jProject != null && jProject . exists ( ) ) ns . add ( jProject ) ; changed = true ; } } } if ( changed ) { newSelection = new StructuredSelection ( ns ) ; setSelection ( newSelection ) ; } super . handleInvalidSelection ( invalidSelection , newSelection ) ; } protected Object [ ] addAditionalProblemParents ( Object [ ] elements ) { if ( showWorkingSets ( ) && elements != null ) { return fWorkingSetModel . addWorkingSets ( elements ) ; } return elements ; } private boolean fInPreserveSelection ; protected void preservingSelection ( Runnable updateCode ) { try { fInPreserveSelection = true ; super . preservingSelection ( updateCode ) ; } finally { fInPreserveSelection = false ; } } protected void setSelectionToWidget ( ISelection selection , boolean reveal ) { if ( true ) { super . setSelectionToWidget ( selection , reveal ) ; return ; } if ( ! fInPreserveSelection || ! ( selection instanceof ITreeSelection ) ) { super . setSelectionToWidget ( selection , reveal ) ; return ; } IContentProvider cp = getContentProvider ( ) ; if ( ! ( cp instanceof IMultiElementTreeContentProvider ) ) { super . setSelectionToWidget ( selection , reveal ) ; return ; } IMultiElementTreeContentProvider contentProvider = ( IMultiElementTreeContentProvider ) cp ; ITreeSelection toRestore = ( ITreeSelection ) selection ; List pathsToSelect = new ArrayList ( ) ; for ( Iterator iter = toRestore . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; TreePath [ ] pathsToRestore = toRestore . getPathsFor ( element ) ; CustomHashtable currentParents = createRootAccessedMap ( contentProvider . getTreePaths ( element ) ) ; for ( int i = ; i < pathsToRestore . length ; i ++ ) { TreePath path = pathsToRestore [ i ] ; Object root = path . getFirstSegment ( ) ; if ( root != null && path . equals ( ( TreePath ) currentParents . get ( root ) , getComparer ( ) ) ) { pathsToSelect . add ( path ) ; } } } List toSelect = new ArrayList ( ) ; for ( Iterator iter = pathsToSelect . iterator ( ) ; iter . hasNext ( ) ; ) { TreePath path = ( TreePath ) iter . next ( ) ; int size = path . getSegmentCount ( ) ; if ( size == ) continue ; Widget current = getTree ( ) ; int last = size - ; Object segment ; for ( int i = ; i < size && current != null && ( segment = path . getSegment ( i ) ) != null ; i ++ ) { internalExpandToLevel ( current , ) ; current = internalFindChild ( current , segment ) ; if ( i == last && current != null ) toSelect . add ( current ) ; } } getTree ( ) . setSelection ( ( TreeItem [ ] ) toSelect . toArray ( new TreeItem [ toSelect . size ( ) ] ) ) ; } private Widget internalFindChild ( Widget parent , Object element ) { Item [ ] items = getChildren ( parent ) ; for ( int i = ; i < items . length ; i ++ ) { Item item = items [ i ] ; Object data = item . getData ( ) ; if ( data != null && equals ( data , element ) ) return item ; } return null ; } private CustomHashtable createRootAccessedMap ( TreePath [ ] paths ) { CustomHashtable result = new CustomHashtable ( getComparer ( ) ) ; for ( int i = ; i < paths . length ; i ++ ) { TreePath path = paths [ i ] ; Object root = path . getFirstSegment ( ) ; if ( root != null ) { result . put ( root , path ) ; } } return result ; } } private boolean fLinkingEnabled ; public void init ( IViewSite site , IMemento memento ) throws PartInitException { super . init ( site , memento ) ; fMemento = memento ; if ( fMemento == null ) { IDialogSettings section = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( getSectionName ( ) ) ; if ( section != null ) { String settings = section . get ( SETTING_MEMENTO ) ; if ( settings != null ) { try { fMemento = XMLMemento . createReadRoot ( new StringReader ( settings ) ) ; } catch ( WorkbenchException e ) { } } } } restoreRootMode ( fMemento ) ; if ( showWorkingSets ( ) ) { createWorkingSetModel ( ) ; } restoreLayoutState ( memento ) ; } private String getSectionName ( ) { return "" ; } private void restoreRootMode ( IMemento memento ) { if ( memento != null ) { Integer value = fMemento . getInteger ( TAG_ROOT_MODE ) ; fRootMode = value == null ? ViewActionGroup . SHOW_PROJECTS : value . intValue ( ) ; if ( fRootMode != ViewActionGroup . SHOW_PROJECTS && fRootMode != ViewActionGroup . SHOW_WORKING_SETS ) fRootMode = ViewActionGroup . SHOW_PROJECTS ; } else { fRootMode = ViewActionGroup . SHOW_PROJECTS ; } } private void restoreLayoutState ( IMemento memento ) { Integer state = null ; if ( memento != null ) state = memento . getInteger ( TAG_LAYOUT ) ; if ( state == null ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; state = new Integer ( store . getInt ( TAG_LAYOUT ) ) ; } if ( state . intValue ( ) == FLAT_LAYOUT ) fIsCurrentLayoutFlat = true ; else if ( state . intValue ( ) == HIERARCHICAL_LAYOUT ) fIsCurrentLayoutFlat = false ; } public static PackageExplorerPart getFromActivePerspective ( ) { IWorkbenchPage activePage = RubyPlugin . getActivePage ( ) ; if ( activePage == null ) return null ; IViewPart view = activePage . findView ( VIEW_ID ) ; if ( view instanceof PackageExplorerPart ) return ( PackageExplorerPart ) view ; return null ; } public static PackageExplorerPart openInActivePerspective ( ) { try { return ( PackageExplorerPart ) RubyPlugin . getActivePage ( ) . showView ( VIEW_ID ) ; } catch ( PartInitException pe ) { return null ; } } public void dispose ( ) { if ( fContextMenu != null && ! fContextMenu . isDisposed ( ) ) fContextMenu . dispose ( ) ; getSite ( ) . getPage ( ) . removePartListener ( fPartListener ) ; RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; if ( fViewer != null ) { fViewer . removeTreeListener ( fExpansionListener ) ; XMLMemento memento = XMLMemento . createWriteRoot ( "" ) ; saveState ( memento ) ; StringWriter writer = new StringWriter ( ) ; try { memento . save ( writer ) ; String sectionName = getSectionName ( ) ; IDialogSettings section = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( sectionName ) ; if ( section == null ) { section = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( sectionName ) ; } section . put ( SETTING_MEMENTO , writer . getBuffer ( ) . toString ( ) ) ; } catch ( IOException e ) { } } if ( fActionSet != null ) fActionSet . dispose ( ) ; if ( fFilterUpdater != null ) ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( fFilterUpdater ) ; if ( fWorkingSetModel != null ) fWorkingSetModel . dispose ( ) ; super . dispose ( ) ; } public void createPartControl ( Composite parent ) { final PerformanceStats stats = PerformanceStats . getStats ( PERF_CREATE_PART_CONTROL , this ) ; stats . startRun ( ) ; fViewer = createViewer ( parent ) ; fViewer . setUseHashlookup ( true ) ; initDragAndDrop ( ) ; setProviders ( ) ; RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; MenuManager menuMgr = new MenuManager ( "" ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( this ) ; fContextMenu = menuMgr . createContextMenu ( fViewer . getTree ( ) ) ; fViewer . getTree ( ) . setMenu ( fContextMenu ) ; IWorkbenchPartSite site = getSite ( ) ; site . registerContextMenu ( menuMgr , fViewer ) ; site . setSelectionProvider ( fViewer ) ; site . getPage ( ) . addPartListener ( fPartListener ) ; if ( fMemento != null ) { restoreLinkingEnabled ( fMemento ) ; } makeActions ( ) ; restoreFilterAndSorter ( ) ; fViewer . setInput ( findInputElement ( ) ) ; initFrameActions ( ) ; initKeyListener ( ) ; fViewer . addPostSelectionChangedListener ( fPostSelectionListener ) ; fViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent event ) { fActionSet . handleDoubleClick ( event ) ; } } ) ; fViewer . addOpenListener ( new IOpenListener ( ) { public void open ( OpenEvent event ) { fActionSet . handleOpen ( event ) ; fLastOpenSelection = event . getSelection ( ) ; } } ) ; IStatusLineManager slManager = getViewSite ( ) . getActionBars ( ) . getStatusLineManager ( ) ; fViewer . addSelectionChangedListener ( new StatusBarUpdater ( slManager ) ) ; fViewer . addTreeListener ( fExpansionListener ) ; if ( fMemento != null ) restoreUIState ( fMemento ) ; fMemento = null ; fillActionBars ( ) ; updateTitle ( ) ; fFilterUpdater = new FilterUpdater ( fViewer ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( fFilterUpdater ) ; if ( isLinkingEnabled ( ) ) { IEditorPart editor = getViewSite ( ) . getPage ( ) . getActiveEditor ( ) ; if ( editor != null ) { editorActivated ( editor ) ; } } stats . endRun ( ) ; } private void initFrameActions ( ) { fActionSet . getUpAction ( ) . update ( ) ; fActionSet . getBackAction ( ) . update ( ) ; fActionSet . getForwardAction ( ) . update ( ) ; } private ProblemTreeViewer createViewer ( Composite composite ) { return new PackageExplorerProblemTreeViewer ( composite , SWT . MULTI | SWT . H_SCROLL | SWT . V_SCROLL ) ; } public boolean isFlatLayout ( ) { return fIsCurrentLayoutFlat ; } private void setProviders ( ) { fContentProvider = createContentProvider ( ) ; fContentProvider . setIsFlatLayout ( fIsCurrentLayoutFlat ) ; fViewer . setComparer ( createElementComparer ( ) ) ; fViewer . setContentProvider ( fContentProvider ) ; fLabelProvider = createLabelProvider ( ) ; fLabelProvider . setIsFlatLayout ( fIsCurrentLayoutFlat ) ; fViewer . setLabelProvider ( new DecoratingRubyLabelProvider ( fLabelProvider , false ) ) ; } void toggleLayout ( ) { fIsCurrentLayoutFlat = ! fIsCurrentLayoutFlat ; saveLayoutState ( null ) ; fContentProvider . setIsFlatLayout ( isFlatLayout ( ) ) ; fLabelProvider . setIsFlatLayout ( isFlatLayout ( ) ) ; fViewer . getControl ( ) . setRedraw ( false ) ; fViewer . refresh ( ) ; fViewer . getControl ( ) . setRedraw ( true ) ; } public PackageExplorerContentProvider createContentProvider ( ) { IPreferenceStore store = PreferenceConstants . getPreferenceStore ( ) ; boolean showCUChildren = store . getBoolean ( PreferenceConstants . SHOW_CU_CHILDREN ) ; if ( showProjects ( ) ) return new PackageExplorerContentProvider ( showCUChildren ) ; else return new WorkingSetAwareContentProvider ( showCUChildren , fWorkingSetModel ) ; } private PackageExplorerLabelProvider createLabelProvider ( ) { if ( showProjects ( ) ) return new PackageExplorerLabelProvider ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS | RubyElementLabels . P_COMPRESSED | RubyElementLabels . ALL_CATEGORY , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS | RubyElementImageProvider . SMALL_ICONS , fContentProvider ) ; else return new WorkingSetAwareLabelProvider ( AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS | RubyElementLabels . P_COMPRESSED , AppearanceAwareLabelProvider . DEFAULT_IMAGEFLAGS | RubyElementImageProvider . SMALL_ICONS , fContentProvider ) ; } private IElementComparer createElementComparer ( ) { if ( showProjects ( ) ) return null ; else return WorkingSetModel . COMPARER ; } private void fillActionBars ( ) { IActionBars actionBars = getViewSite ( ) . getActionBars ( ) ; fActionSet . fillActionBars ( actionBars ) ; } private Object findInputElement ( ) { if ( showWorkingSets ( ) ) { return fWorkingSetModel ; } else { Object input = getSite ( ) . getPage ( ) . getInput ( ) ; if ( input instanceof IWorkspace ) { return RubyCore . create ( ( ( IWorkspace ) input ) . getRoot ( ) ) ; } else if ( input instanceof IContainer ) { IRubyElement element = RubyCore . create ( ( IContainer ) input ) ; if ( element != null && element . exists ( ) ) return element ; return input ; } return RubyCore . create ( RubyPlugin . getWorkspace ( ) . getRoot ( ) ) ; } } public Object getAdapter ( Class key ) { if ( key . equals ( ISelectionProvider . class ) ) return fViewer ; if ( key == IShowInSource . class ) { return getShowInSource ( ) ; } if ( key == IShowInTargetList . class ) { return new IShowInTargetList ( ) { public String [ ] getShowInTargetIds ( ) { return new String [ ] { IPageLayout . ID_RES_NAV } ; } } ; } return super . getAdapter ( key ) ; } String getToolTipText ( Object element ) { String result ; if ( ! ( element instanceof IResource ) ) { if ( element instanceof IRubyModel ) { result = PackagesMessages . PackageExplorerPart_workspace ; } else if ( element instanceof IRubyElement ) { result = RubyElementLabels . getTextLabel ( element , RubyElementLabels . ALL_FULLY_QUALIFIED ) ; } else if ( element instanceof IWorkingSet ) { result = ( ( IWorkingSet ) element ) . getLabel ( ) ; } else if ( element instanceof WorkingSetModel ) { result = PackagesMessages . PackageExplorerPart_workingSetModel ; } else { result = fLabelProvider . getText ( element ) ; } } else { IPath path = ( ( IResource ) element ) . getFullPath ( ) ; if ( path . isRoot ( ) ) { result = PackagesMessages . PackageExplorer_title ; } else { result = path . makeRelative ( ) . toString ( ) ; } } if ( fRootMode == ViewActionGroup . SHOW_PROJECTS ) { if ( fWorkingSetLabel == null ) return result ; if ( result . length ( ) == ) return Messages . format ( PackagesMessages . PackageExplorer_toolTip , new String [ ] { fWorkingSetLabel } ) ; return Messages . format ( PackagesMessages . PackageExplorer_toolTip2 , new String [ ] { result , fWorkingSetLabel } ) ; } else { if ( element != null && ! ( element instanceof IWorkingSet ) && ! ( element instanceof WorkingSetModel ) && fActionSet != null ) { FrameList frameList = fActionSet . getFrameList ( ) ; int index = frameList . getCurrentIndex ( ) ; IWorkingSet ws = null ; while ( index >= ) { Frame frame = frameList . getFrame ( index ) ; if ( frame instanceof TreeFrame ) { Object input = ( ( TreeFrame ) frame ) . getInput ( ) ; if ( input instanceof IWorkingSet ) { ws = ( IWorkingSet ) input ; break ; } } index -- ; } if ( ws != null ) { return Messages . format ( PackagesMessages . PackageExplorer_toolTip3 , new String [ ] { ws . getLabel ( ) , result } ) ; } else { return result ; } } else { return result ; } } } public String getTitleToolTip ( ) { if ( fViewer == null ) return super . getTitleToolTip ( ) ; return getToolTipText ( fViewer . getInput ( ) ) ; } public void setFocus ( ) { fViewer . getTree ( ) . setFocus ( ) ; } private ISelection getSelection ( ) { return fViewer . getSelection ( ) ; } public void menuAboutToShow ( IMenuManager menu ) { RubyPlugin . createStandardGroups ( menu ) ; fActionSet . setContext ( new ActionContext ( getSelection ( ) ) ) ; fActionSet . fillContextMenu ( menu ) ; fActionSet . setContext ( null ) ; } private void makeActions ( ) { final PerformanceStats stats = PerformanceStats . getStats ( PERF_MAKE_ACTIONS , this ) ; stats . startRun ( ) ; fActionSet = new RubyExplorerActionGroup ( this ) ; if ( fWorkingSetModel != null ) fActionSet . getWorkingSetActionGroup ( ) . setWorkingSetModel ( fWorkingSetModel ) ; stats . endRun ( ) ; } private void initDragAndDrop ( ) { initDrag ( ) ; initDrop ( ) ; } private void initDrag ( ) { int ops = DND . DROP_COPY | DND . DROP_MOVE | DND . DROP_LINK ; Transfer [ ] transfers = new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) , ResourceTransfer . getInstance ( ) , FileTransfer . getInstance ( ) } ; TransferDragSourceListener [ ] dragListeners = new TransferDragSourceListener [ ] { new SelectionTransferDragAdapter ( fViewer ) , new ResourceTransferDragAdapter ( fViewer ) , new FileTransferDragAdapter ( fViewer ) } ; fViewer . addDragSupport ( ops , transfers , new RdtViewerDragAdapter ( fViewer , dragListeners ) ) ; } private void initDrop ( ) { int ops = DND . DROP_COPY | DND . DROP_MOVE | DND . DROP_LINK | DND . DROP_DEFAULT ; Transfer [ ] transfers = new Transfer [ ] { LocalSelectionTransfer . getInstance ( ) , FileTransfer . getInstance ( ) } ; TransferDropTargetListener [ ] dropListeners = new TransferDropTargetListener [ ] { new SelectionTransferDropAdapter ( fViewer ) , new FileTransferDropAdapter ( fViewer ) , } ; fViewer . addDropSupport ( ops , transfers , new DelegatingDropAdapter ( dropListeners ) ) ; } private void handlePostSelectionChanged ( SelectionChangedEvent event ) { ISelection selection = event . getSelection ( ) ; RubyPlugin . getDefault ( ) . getProjectTracker ( ) . selectionChanged ( event ) ; if ( isLinkingEnabled ( ) && ! selection . equals ( fLastOpenSelection ) ) { linkToEditor ( ( IStructuredSelection ) selection ) ; } fLastOpenSelection = null ; } public void selectReveal ( ISelection selection ) { selectReveal ( selection , ) ; } private void selectReveal ( final ISelection selection , final int count ) { Control ctrl = getViewer ( ) . getControl ( ) ; if ( ctrl == null || ctrl . isDisposed ( ) ) return ; ISelection javaSelection = convertSelection ( selection ) ; fViewer . setSelection ( javaSelection , true ) ; PackageExplorerContentProvider provider = ( PackageExplorerContentProvider ) getViewer ( ) . getContentProvider ( ) ; ISelection cs = fViewer . getSelection ( ) ; if ( count == && provider . hasPendingChanges ( ) && ! javaSelection . equals ( cs ) ) { ctrl . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { selectReveal ( selection , count + ) ; } } ) ; } } public ISelection convertSelection ( ISelection s ) { if ( ! ( s instanceof IStructuredSelection ) ) return s ; Object [ ] elements = ( ( IStructuredSelection ) s ) . toArray ( ) ; boolean changed = false ; for ( int i = ; i < elements . length ; i ++ ) { Object convertedElement = convertElement ( elements [ i ] ) ; changed = changed || convertedElement != elements [ i ] ; elements [ i ] = convertedElement ; } if ( changed ) return new StructuredSelection ( elements ) ; else return s ; } private Object convertElement ( Object original ) { if ( original instanceof IRubyElement ) { return original ; } else if ( original instanceof IResource ) { IRubyElement je = RubyCore . create ( ( IResource ) original ) ; if ( je != null && je . exists ( ) ) return je ; } else if ( original instanceof IAdaptable ) { IAdaptable adaptable = ( IAdaptable ) original ; IRubyElement je = ( IRubyElement ) adaptable . getAdapter ( IRubyElement . class ) ; if ( je != null && je . exists ( ) ) return je ; IResource r = ( IResource ) adaptable . getAdapter ( IResource . class ) ; if ( r != null ) { je = RubyCore . create ( r ) ; if ( je != null && je . exists ( ) ) return je ; else return r ; } } return original ; } public void selectAndReveal ( Object element ) { selectReveal ( new StructuredSelection ( element ) ) ; } public boolean isLinkingEnabled ( ) { return fLinkingEnabled ; } private void initLinkingEnabled ( ) { fLinkingEnabled = PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . LINK_PACKAGES_TO_EDITOR ) ; } private void linkToEditor ( IStructuredSelection selection ) { if ( ! isActivePart ( ) ) return ; Object obj = selection . getFirstElement ( ) ; if ( selection . size ( ) == ) { IEditorPart part = EditorUtility . isOpenInEditor ( obj ) ; if ( part != null ) { IWorkbenchPage page = getSite ( ) . getPage ( ) ; page . bringToTop ( part ) ; if ( obj instanceof IRubyElement ) EditorUtility . revealInEditor ( part , ( IRubyElement ) obj ) ; } } } private boolean isActivePart ( ) { return this == getSite ( ) . getPage ( ) . getActivePart ( ) ; } public void saveState ( IMemento memento ) { if ( fViewer == null ) { if ( fMemento != null ) memento . putMemento ( fMemento ) ; return ; } memento . putInteger ( TAG_ROOT_MODE , fRootMode ) ; if ( fWorkingSetModel != null ) fWorkingSetModel . saveState ( memento ) ; saveLayoutState ( memento ) ; saveLinkingEnabled ( memento ) ; fActionSet . saveFilterAndSorterState ( memento ) ; } private void saveLinkingEnabled ( IMemento memento ) { memento . putInteger ( PreferenceConstants . LINK_PACKAGES_TO_EDITOR , fLinkingEnabled ? : ) ; } private void saveLayoutState ( IMemento memento ) { if ( memento != null ) { memento . putInteger ( TAG_LAYOUT , getLayoutAsInt ( ) ) ; } else { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; store . setValue ( TAG_LAYOUT , getLayoutAsInt ( ) ) ; } } private int getLayoutAsInt ( ) { if ( fIsCurrentLayoutFlat ) return FLAT_LAYOUT ; else return HIERARCHICAL_LAYOUT ; } protected void saveScrollState ( IMemento memento , Tree tree ) { ScrollBar bar = tree . getVerticalBar ( ) ; int position = bar != null ? bar . getSelection ( ) : ; memento . putString ( TAG_VERTICAL_POSITION , String . valueOf ( position ) ) ; bar = tree . getHorizontalBar ( ) ; position = bar != null ? bar . getSelection ( ) : ; memento . putString ( TAG_HORIZONTAL_POSITION , String . valueOf ( position ) ) ; } protected void saveSelectionState ( IMemento memento ) { Object elements [ ] = ( ( IStructuredSelection ) fViewer . getSelection ( ) ) . toArray ( ) ; if ( elements . length > ) { IMemento selectionMem = memento . createChild ( TAG_SELECTION ) ; for ( int i = ; i < elements . length ; i ++ ) { IMemento elementMem = selectionMem . createChild ( TAG_ELEMENT ) ; Object o = elements [ i ] ; if ( o instanceof IRubyElement ) elementMem . putString ( TAG_PATH , ( ( IRubyElement ) elements [ i ] ) . getHandleIdentifier ( ) ) ; } } } protected void saveExpansionState ( IMemento memento ) { Object expandedElements [ ] = fViewer . getVisibleExpandedElements ( ) ; if ( expandedElements . length > ) { IMemento expandedMem = memento . createChild ( TAG_EXPANDED ) ; for ( int i = ; i < expandedElements . length ; i ++ ) { IMemento elementMem = expandedMem . createChild ( TAG_ELEMENT ) ; Object o = expandedElements [ i ] ; if ( o instanceof IRubyElement ) elementMem . putString ( TAG_PATH , ( ( IRubyElement ) expandedElements [ i ] ) . getHandleIdentifier ( ) ) ; } } } private void restoreFilterAndSorter ( ) { setSorter ( ) ; if ( fMemento != null ) fActionSet . restoreFilterAndSorterState ( fMemento ) ; } private void restoreUIState ( IMemento memento ) { } private void restoreLinkingEnabled ( IMemento memento ) { Integer val = memento . getInteger ( PreferenceConstants . LINK_PACKAGES_TO_EDITOR ) ; if ( val != null ) { fLinkingEnabled = val . intValue ( ) != ; } } protected void restoreScrollState ( IMemento memento , Tree tree ) { ScrollBar bar = tree . getVerticalBar ( ) ; if ( bar != null ) { try { String posStr = memento . getString ( TAG_VERTICAL_POSITION ) ; int position ; position = new Integer ( posStr ) . intValue ( ) ; bar . setSelection ( position ) ; } catch ( NumberFormatException e ) { } } bar = tree . getHorizontalBar ( ) ; if ( bar != null ) { try { String posStr = memento . getString ( TAG_HORIZONTAL_POSITION ) ; int position ; position = new Integer ( posStr ) . intValue ( ) ; bar . setSelection ( position ) ; } catch ( NumberFormatException e ) { } } } protected void restoreSelectionState ( IMemento memento ) { IMemento childMem ; childMem = memento . getChild ( TAG_SELECTION ) ; if ( childMem != null ) { ArrayList list = new ArrayList ( ) ; IMemento [ ] elementMem = childMem . getChildren ( TAG_ELEMENT ) ; for ( int i = ; i < elementMem . length ; i ++ ) { Object element = RubyCore . create ( elementMem [ i ] . getString ( TAG_PATH ) ) ; if ( element != null ) list . add ( element ) ; } fViewer . setSelection ( new StructuredSelection ( list ) ) ; } } protected void restoreExpansionState ( IMemento memento ) { IMemento childMem = memento . getChild ( TAG_EXPANDED ) ; if ( childMem != null ) { ArrayList elements = new ArrayList ( ) ; IMemento [ ] elementMem = childMem . getChildren ( TAG_ELEMENT ) ; for ( int i = ; i < elementMem . length ; i ++ ) { Object element = RubyCore . create ( elementMem [ i ] . getString ( TAG_PATH ) ) ; if ( element != null ) elements . add ( element ) ; } fViewer . setExpandedElements ( elements . toArray ( ) ) ; } } private void initKeyListener ( ) { fViewer . getControl ( ) . addKeyListener ( new KeyAdapter ( ) { public void keyReleased ( KeyEvent event ) { fActionSet . handleKeyEvent ( event ) ; } } ) ; } void editorActivated ( IEditorPart editor ) { if ( ! isLinkingEnabled ( ) ) return ; Object input = getElementOfInput ( editor . getEditorInput ( ) ) ; if ( input == null ) return ; if ( ! inputIsSelected ( editor . getEditorInput ( ) ) ) showInput ( input ) ; else getTreeViewer ( ) . getTree ( ) . showSelection ( ) ; } private boolean inputIsSelected ( IEditorInput input ) { IStructuredSelection selection = ( IStructuredSelection ) fViewer . getSelection ( ) ; if ( selection . size ( ) != ) return false ; IEditorInput selectionAsInput = null ; try { selectionAsInput = EditorUtility . getEditorInput ( selection . getFirstElement ( ) ) ; } catch ( RubyModelException e1 ) { return false ; } return input . equals ( selectionAsInput ) ; } boolean showInput ( Object input ) { Object element = null ; if ( input instanceof IFile && isOnClassPath ( ( IFile ) input ) ) { element = RubyCore . create ( ( IFile ) input ) ; } if ( element == null ) element = input ; if ( element != null ) { ISelection newSelection = new StructuredSelection ( element ) ; if ( fViewer . getSelection ( ) . equals ( newSelection ) ) { fViewer . reveal ( element ) ; } else { try { fViewer . removePostSelectionChangedListener ( fPostSelectionListener ) ; fViewer . setSelection ( newSelection , true ) ; while ( element != null && fViewer . getSelection ( ) . isEmpty ( ) ) { element = getParent ( element ) ; if ( element != null ) { newSelection = new StructuredSelection ( element ) ; fViewer . setSelection ( newSelection , true ) ; } } } finally { fViewer . addPostSelectionChangedListener ( fPostSelectionListener ) ; } } return true ; } return false ; } private boolean isOnClassPath ( IFile file ) { IRubyProject jproject = RubyCore . create ( file . getProject ( ) ) ; return jproject . isOnLoadpath ( file ) ; } private Object getParent ( Object element ) { if ( element instanceof IRubyElement ) return ( ( IRubyElement ) element ) . getParent ( ) ; else if ( element instanceof IResource ) return ( ( IResource ) element ) . getParent ( ) ; return null ; } void expandMainType ( Object element ) { try { IType type = null ; if ( element instanceof IRubyScript ) { IRubyScript cu = ( IRubyScript ) element ; IType [ ] types = cu . getTypes ( ) ; if ( types . length > ) type = types [ ] ; } if ( type != null ) { final IType type2 = type ; Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { ctrl . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { Control ctrl2 = fViewer . getControl ( ) ; if ( ctrl2 != null && ! ctrl2 . isDisposed ( ) ) fViewer . expandToLevel ( type2 , ) ; } } ) ; } } } catch ( RubyModelException e ) { } } Object getElementOfInput ( IEditorInput input ) { if ( input instanceof IRubyScriptEditorInput ) return ( ( IRubyScriptEditorInput ) input ) . getRubyScript ( ) ; else if ( input instanceof IFileEditorInput ) return ( ( IFileEditorInput ) input ) . getFile ( ) ; else if ( input instanceof ExternalRubyFileEditorInput ) return ( ( ExternalRubyFileEditorInput ) input ) . getStorage ( ) ; return null ; } TreeViewer getViewer ( ) { return fViewer ; } public TreeViewer getTreeViewer ( ) { return fViewer ; } boolean isExpandable ( Object element ) { if ( fViewer == null ) return false ; return fViewer . isExpandable ( element ) ; } void setWorkingSetLabel ( String workingSetName ) { fWorkingSetLabel = workingSetName ; setTitleToolTip ( getTitleToolTip ( ) ) ; } void updateTitle ( ) { Object input = fViewer . getInput ( ) ; if ( input == null || ( input instanceof IRubyModel ) ) { setContentDescription ( "" ) ; setTitleToolTip ( "" ) ; } else { String inputText = RubyElementLabels . getTextLabel ( input , AppearanceAwareLabelProvider . DEFAULT_TEXTFLAGS ) ; setContentDescription ( inputText ) ; setTitleToolTip ( getToolTipText ( input ) ) ; } } public void setLabelDecorator ( ILabelDecorator decorator ) { } public void propertyChange ( PropertyChangeEvent event ) { if ( fViewer == null ) return ; boolean refreshViewer = false ; if ( PreferenceConstants . SHOW_CU_CHILDREN . equals ( event . getProperty ( ) ) ) { fActionSet . updateActionBars ( getViewSite ( ) . getActionBars ( ) ) ; boolean showCUChildren = PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . SHOW_CU_CHILDREN ) ; ( ( StandardRubyElementContentProvider ) fViewer . getContentProvider ( ) ) . setProvideMembers ( showCUChildren ) ; refreshViewer = true ; } else if ( MembersOrderPreferenceCache . isMemberOrderProperty ( event . getProperty ( ) ) ) { refreshViewer = true ; } if ( refreshViewer ) fViewer . refresh ( ) ; } public Object getViewPartInput ( ) { if ( fViewer != null ) { return fViewer . getInput ( ) ; } return null ; } public void collapseAll ( ) { try { fViewer . getControl ( ) . setRedraw ( false ) ; fViewer . collapseToLevel ( getViewPartInput ( ) , AbstractTreeViewer . ALL_LEVELS ) ; } finally { fViewer . getControl ( ) . setRedraw ( true ) ; } } public PackageExplorerPart ( ) { initLinkingEnabled ( ) ; fPostSelectionListener = new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { handlePostSelectionChanged ( event ) ; } } ; } public boolean show ( ShowInContext context ) { ISelection selection = context . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { IStructuredSelection structuredSelection = ( ( IStructuredSelection ) selection ) ; if ( structuredSelection . size ( ) == && tryToReveal ( structuredSelection . getFirstElement ( ) ) ) return true ; } Object input = context . getInput ( ) ; if ( input instanceof IEditorInput ) { Object elementOfInput = getElementOfInput ( ( IEditorInput ) context . getInput ( ) ) ; return elementOfInput != null && tryToReveal ( elementOfInput ) ; } return false ; } protected IShowInSource getShowInSource ( ) { return new IShowInSource ( ) { public ShowInContext getShowInContext ( ) { return new ShowInContext ( getViewer ( ) . getInput ( ) , getViewer ( ) . getSelection ( ) ) ; } } ; } public void setLinkingEnabled ( boolean enabled ) { fLinkingEnabled = enabled ; PreferenceConstants . getPreferenceStore ( ) . setValue ( PreferenceConstants . LINK_PACKAGES_TO_EDITOR , enabled ) ; if ( enabled ) { IEditorPart editor = getSite ( ) . getPage ( ) . getActiveEditor ( ) ; if ( editor != null ) { editorActivated ( editor ) ; } } } String getFrameName ( Object element ) { if ( element instanceof IRubyElement ) { return ( ( IRubyElement ) element ) . getElementName ( ) ; } else if ( element instanceof WorkingSetModel ) { return "" ; } else { return fLabelProvider . getText ( element ) ; } } void projectStateChanged ( Object root ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { fViewer . refresh ( root , true ) ; fViewer . setSelection ( fViewer . getSelection ( ) ) ; } } public boolean tryToReveal ( Object element ) { if ( revealElementOrParent ( element ) ) return true ; WorkingSetFilterActionGroup workingSetGroup = fActionSet . getWorkingSetActionGroup ( ) . getFilterGroup ( ) ; if ( workingSetGroup != null ) { IWorkingSet workingSet = workingSetGroup . getWorkingSet ( ) ; if ( workingSetGroup . isFiltered ( getVisibleParent ( element ) , element ) ) { String message = Messages . format ( PackagesMessages . PackageExplorer_notFound , workingSet . getLabel ( ) ) ; if ( MessageDialog . openQuestion ( getSite ( ) . getShell ( ) , PackagesMessages . PackageExplorer_filteredDialog_title , message ) ) { workingSetGroup . setWorkingSet ( null , true ) ; if ( revealElementOrParent ( element ) ) return true ; } } } CustomFiltersActionGroup filterGroup = fActionSet . getCustomFilterActionGroup ( ) ; String [ ] currentFilters = filterGroup . internalGetEnabledFilterIds ( ) ; String [ ] newFilters = filterGroup . removeFiltersFor ( getVisibleParent ( element ) , element , getTreeViewer ( ) . getContentProvider ( ) ) ; if ( currentFilters . length > newFilters . length ) { String message = PackagesMessages . PackageExplorer_removeFilters ; if ( MessageDialog . openQuestion ( getSite ( ) . getShell ( ) , PackagesMessages . PackageExplorer_filteredDialog_title , message ) ) { filterGroup . setFilters ( newFilters ) ; if ( revealElementOrParent ( element ) ) return true ; } } FrameAction action = fActionSet . getUpAction ( ) ; while ( action . getFrameList ( ) . getCurrentIndex ( ) > ) { if ( action . getFrameList ( ) . getSource ( ) . getFrame ( IFrameSource . PARENT_FRAME , ) == null ) break ; action . run ( ) ; if ( revealElementOrParent ( element ) ) return true ; } return false ; } private boolean revealElementOrParent ( Object element ) { if ( revealAndVerify ( element ) ) return true ; element = getVisibleParent ( element ) ; if ( element != null ) { if ( revealAndVerify ( element ) ) return true ; if ( element instanceof IRubyElement ) { IResource resource = ( ( IRubyElement ) element ) . getResource ( ) ; if ( resource != null ) { if ( revealAndVerify ( resource ) ) return true ; } } } return false ; } private Object getVisibleParent ( Object object ) { if ( object == null ) return null ; if ( ! ( object instanceof IRubyElement ) ) return object ; IRubyElement element2 = ( IRubyElement ) object ; switch ( element2 . getElementType ( ) ) { case IRubyElement . IMPORT_DECLARATION : case IRubyElement . IMPORT_CONTAINER : case IRubyElement . TYPE : case IRubyElement . METHOD : case IRubyElement . FIELD : element2 = ( IRubyElement ) element2 . getOpenable ( ) ; break ; case IRubyElement . RUBY_MODEL : element2 = null ; break ; } return element2 ; } private boolean revealAndVerify ( Object element ) { if ( element == null ) return false ; selectReveal ( new StructuredSelection ( element ) ) ; return ! getSite ( ) . getSelectionProvider ( ) . getSelection ( ) . isEmpty ( ) ; } public void rootModeChanged ( int newMode ) { fRootMode = newMode ; if ( showWorkingSets ( ) && fWorkingSetModel == null ) { createWorkingSetModel ( ) ; if ( fActionSet != null ) { fActionSet . getWorkingSetActionGroup ( ) . setWorkingSetModel ( fWorkingSetModel ) ; } } IStructuredSelection selection = new StructuredSelection ( ( ( IStructuredSelection ) fViewer . getSelection ( ) ) . toArray ( ) ) ; Object input = fViewer . getInput ( ) ; boolean isRootInputChange = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) . equals ( input ) || ( fWorkingSetModel != null && fWorkingSetModel . equals ( input ) ) || input instanceof IWorkingSet ; try { fViewer . getControl ( ) . setRedraw ( false ) ; if ( isRootInputChange ) { fViewer . setInput ( null ) ; } setProviders ( ) ; setSorter ( ) ; fActionSet . getWorkingSetActionGroup ( ) . fillFilters ( fViewer ) ; if ( isRootInputChange ) { fViewer . setInput ( findInputElement ( ) ) ; } fViewer . setSelection ( selection , true ) ; } finally { fViewer . getControl ( ) . setRedraw ( true ) ; } if ( isRootInputChange && showWorkingSets ( ) && fWorkingSetModel . needsConfiguration ( ) ) { ConfigureWorkingSetAction action = new ConfigureWorkingSetAction ( getSite ( ) ) ; action . setWorkingSetModel ( fWorkingSetModel ) ; action . run ( ) ; fWorkingSetModel . configured ( ) ; } setTitleToolTip ( getTitleToolTip ( ) ) ; } private void createWorkingSetModel ( ) { SafeRunner . run ( new ISafeRunnable ( ) { public void run ( ) throws Exception { fWorkingSetModel = fMemento != null ? new WorkingSetModel ( fMemento ) : new WorkingSetModel ( ) ; } public void handleException ( Throwable exception ) { fWorkingSetModel = new WorkingSetModel ( ) ; } } ) ; } public WorkingSetModel getWorkingSetModel ( ) { return fWorkingSetModel ; } public int getRootMode ( ) { return fRootMode ; } boolean showProjects ( ) { return fRootMode == ViewActionGroup . SHOW_PROJECTS ; } boolean showWorkingSets ( ) { return fRootMode == ViewActionGroup . SHOW_WORKING_SETS ; } private void setSorter ( ) { if ( showWorkingSets ( ) ) { fViewer . setSorter ( new WorkingSetAwareRubyElementSorter ( ) ) ; } else { fViewer . setSorter ( new RubyElementSorter ( ) ) ; } } public void internalTestShowWorkingSets ( IWorkingSet [ ] workingSets ) { if ( fWorkingSetModel == null ) createWorkingSetModel ( ) ; fWorkingSetModel . setActiveWorkingSets ( workingSets ) ; fWorkingSetModel . configured ( ) ; rootModeChanged ( ViewActionGroup . SHOW_WORKING_SETS ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class SourceFolderProvider implements IPropertyChangeListener { private TreeViewer fViewer ; private boolean fFoldPackages ; public SourceFolderProvider ( ) { fFoldPackages = arePackagesFoldedInHierarchicalLayout ( ) ; RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; } public Object [ ] getChildren ( Object parentElement ) { try { if ( parentElement instanceof IFolder ) { IResource [ ] resources = ( ( IFolder ) parentElement ) . members ( ) ; return filter ( getFolders ( resources ) ) . toArray ( ) ; } else if ( parentElement instanceof IRubyElement ) { IRubyElement iRubyElement = ( IRubyElement ) parentElement ; int type = iRubyElement . getElementType ( ) ; switch ( type ) { case IRubyElement . RUBY_PROJECT : { IRubyProject project = ( IRubyProject ) iRubyElement ; ISourceFolderRoot root = project . findSourceFolderRoot ( project . getPath ( ) ) ; if ( root != null ) { List children = getTopLevelChildren ( root ) ; return filter ( children ) . toArray ( ) ; } break ; } case IRubyElement . SOURCE_FOLDER_ROOT : { ISourceFolderRoot root = ( ISourceFolderRoot ) parentElement ; if ( root . exists ( ) ) { return filter ( getTopLevelChildren ( root ) ) . toArray ( ) ; } break ; } case IRubyElement . SOURCE_FOLDER : { ISourceFolder packageFragment = ( ISourceFolder ) parentElement ; if ( ! packageFragment . isDefaultPackage ( ) ) { ISourceFolderRoot root = ( ISourceFolderRoot ) packageFragment . getParent ( ) ; List children = getPackageChildren ( root , packageFragment ) ; return filter ( children ) . toArray ( ) ; } break ; } default : } } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } return new Object [ ] ; } private List filter ( List children ) throws RubyModelException { if ( fFoldPackages ) { int size = children . size ( ) ; for ( int i = ; i < size ; i ++ ) { Object curr = children . get ( i ) ; if ( curr instanceof ISourceFolder ) { ISourceFolder fragment = ( ISourceFolder ) curr ; if ( ! fragment . isDefaultPackage ( ) && isEmpty ( fragment ) ) { ISourceFolder collapsed = getCollapsed ( fragment ) ; if ( collapsed != null ) { children . set ( i , collapsed ) ; } } } } } return children ; } private ISourceFolder getCollapsed ( ISourceFolder pack ) throws RubyModelException { IRubyElement [ ] children = ( ( ISourceFolderRoot ) pack . getParent ( ) ) . getChildren ( ) ; ISourceFolder child = getSinglePackageChild ( pack , children ) ; while ( child != null && isEmpty ( child ) ) { ISourceFolder collapsed = getSinglePackageChild ( child , children ) ; if ( collapsed == null ) { return child ; } child = collapsed ; } return child ; } private boolean isEmpty ( ISourceFolder fragment ) throws RubyModelException { return ! fragment . containsRubyResources ( ) && fragment . getNonRubyResources ( ) . length == ; } private static ISourceFolder getSinglePackageChild ( ISourceFolder fragment , IRubyElement [ ] children ) { String prefix = fragment . getElementName ( ) + '' ; int prefixLen = prefix . length ( ) ; ISourceFolder found = null ; for ( int i = ; i < children . length ; i ++ ) { IRubyElement element = children [ i ] ; String name = element . getElementName ( ) ; if ( name . startsWith ( prefix ) && name . length ( ) > prefixLen && name . indexOf ( '' , prefixLen ) == - ) { if ( found == null ) { found = ( ISourceFolder ) element ; } else { return null ; } } } return found ; } private static List getPackageChildren ( ISourceFolderRoot parent , ISourceFolder fragment ) throws RubyModelException { IRubyElement [ ] children = parent . getChildren ( ) ; ArrayList list = new ArrayList ( children . length ) ; String prefix = fragment . getElementName ( ) + File . separatorChar ; int prefixLen = prefix . length ( ) ; for ( int i = ; i < children . length ; i ++ ) { IRubyElement element = children [ i ] ; if ( element instanceof ISourceFolder ) { String name = element . getElementName ( ) ; if ( name . startsWith ( prefix ) && name . length ( ) > prefixLen && name . indexOf ( File . separatorChar , prefixLen ) == - ) { list . add ( element ) ; } } } return list ; } private static List < IRubyElement > getTopLevelChildren ( ISourceFolderRoot root ) throws RubyModelException { IRubyElement [ ] elements = root . getChildren ( ) ; ArrayList < IRubyElement > topLevelElements = new ArrayList < IRubyElement > ( elements . length ) ; for ( int i = ; i < elements . length ; i ++ ) { IRubyElement iRubyElement = elements [ i ] ; if ( iRubyElement instanceof ISourceFolder && ( iRubyElement . getElementName ( ) . indexOf ( File . separatorChar ) == - ) && ! ( ( ( ISourceFolder ) iRubyElement ) . isDefaultPackage ( ) ) ) { topLevelElements . add ( iRubyElement ) ; } } return topLevelElements ; } private List getFolders ( IResource [ ] resources ) throws RubyModelException { List list = new ArrayList ( resources . length ) ; for ( int i = ; i < resources . length ; i ++ ) { IResource resource = resources [ i ] ; if ( resource instanceof IFolder ) { IFolder folder = ( IFolder ) resource ; IRubyElement element = RubyCore . create ( folder ) ; if ( element instanceof ISourceFolder ) { list . add ( element ) ; } } } return list ; } public Object getParent ( Object element ) { if ( element instanceof ISourceFolder ) { ISourceFolder frag = ( ISourceFolder ) element ; return filterParent ( getActualParent ( frag ) ) ; } return null ; } private Object getActualParent ( ISourceFolder fragment ) { try { if ( fragment . exists ( ) ) { IRubyElement parent = fragment . getParent ( ) ; if ( ( parent instanceof ISourceFolderRoot ) && parent . exists ( ) ) { ISourceFolderRoot root = ( ISourceFolderRoot ) parent ; if ( root . isExternal ( ) ) { return findNextLevelParentByElementName ( fragment ) ; } else { IResource resource = fragment . getUnderlyingResource ( ) ; if ( ( resource != null ) && ( resource instanceof IFolder ) ) { IFolder folder = ( IFolder ) resource ; IResource res = folder . getParent ( ) ; IRubyElement el = RubyCore . create ( res ) ; if ( el != null ) { return el ; } else { return res ; } } } return parent ; } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return null ; } private Object filterParent ( Object parent ) { if ( fFoldPackages && ( parent != null ) ) { try { if ( parent instanceof ISourceFolder ) { ISourceFolder fragment = ( ISourceFolder ) parent ; if ( isEmpty ( fragment ) && hasSingleChild ( fragment ) ) { return filterParent ( getActualParent ( fragment ) ) ; } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } return parent ; } private boolean hasSingleChild ( ISourceFolder fragment ) { return getChildren ( fragment ) . length == ; } private Object findNextLevelParentByElementName ( ISourceFolder child ) { String name = child . getElementName ( ) ; int index = name . lastIndexOf ( File . separatorChar ) ; if ( index != - ) { String realParentName = name . substring ( , index ) ; ISourceFolder element = ( ( ISourceFolderRoot ) child . getParent ( ) ) . getSourceFolder ( realParentName ) ; if ( element . exists ( ) ) { return element ; } } return child . getParent ( ) ; } public boolean hasChildren ( Object element ) { if ( element instanceof ISourceFolder ) { ISourceFolder fragment = ( ISourceFolder ) element ; if ( fragment . isDefaultPackage ( ) ) return false ; } return getChildren ( element ) . length > ; } public Object [ ] getElements ( Object inputElement ) { return getChildren ( inputElement ) ; } public void dispose ( ) { RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fViewer = ( TreeViewer ) viewer ; } public void elementChanged ( ElementChangedEvent event ) { processDelta ( event . getDelta ( ) ) ; } public void processDelta ( IRubyElementDelta delta ) { int kind = delta . getKind ( ) ; final IRubyElement element = delta . getElement ( ) ; if ( element instanceof ISourceFolder ) { if ( kind == IRubyElementDelta . REMOVED ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { if ( ! fFoldPackages ) fViewer . remove ( element ) ; else refreshGrandParent ( element ) ; } } } ) ; return ; } else if ( kind == IRubyElementDelta . ADDED ) { final Object parent = getParent ( element ) ; if ( parent != null ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { if ( ! fFoldPackages ) fViewer . add ( parent , element ) ; else refreshGrandParent ( element ) ; } } } ) ; } return ; } } } private void refreshGrandParent ( final IRubyElement element ) { if ( element instanceof ISourceFolder ) { Object gp = getGrandParent ( ( ISourceFolder ) element ) ; if ( gp instanceof IRubyElement ) { IRubyElement el = ( IRubyElement ) gp ; if ( el . exists ( ) ) fViewer . refresh ( gp ) ; } else if ( gp instanceof IFolder ) { IFolder folder = ( IFolder ) gp ; if ( folder . exists ( ) ) fViewer . refresh ( folder ) ; } } } private Object getGrandParent ( ISourceFolder element ) { Object parent = findNextLevelParentByElementName ( element ) ; if ( parent instanceof ISourceFolderRoot ) { ISourceFolderRoot root = ( ISourceFolderRoot ) parent ; if ( isRootProject ( root ) ) return root . getRubyProject ( ) ; else return root ; } Object grandParent = getParent ( parent ) ; if ( grandParent == null ) { return parent ; } return grandParent ; } private boolean isRootProject ( ISourceFolderRoot root ) { if ( ISourceFolderRoot . DEFAULT_PACKAGEROOT_PATH . equals ( root . getElementName ( ) ) ) return true ; return false ; } private void postRunnable ( final Runnable r ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { Display currentDisplay = Display . getCurrent ( ) ; if ( currentDisplay != null && currentDisplay . equals ( ctrl . getDisplay ( ) ) ) ctrl . getDisplay ( ) . syncExec ( r ) ; else ctrl . getDisplay ( ) . asyncExec ( r ) ; } } public void propertyChange ( PropertyChangeEvent event ) { if ( arePackagesFoldedInHierarchicalLayout ( ) != fFoldPackages ) { fFoldPackages = arePackagesFoldedInHierarchicalLayout ( ) ; if ( fViewer != null && ! fViewer . getControl ( ) . isDisposed ( ) ) { fViewer . getControl ( ) . setRedraw ( false ) ; Object [ ] expandedObjects = fViewer . getExpandedElements ( ) ; fViewer . refresh ( ) ; fViewer . setExpandedElements ( expandedObjects ) ; fViewer . getControl ( ) . setRedraw ( true ) ; } } } private boolean arePackagesFoldedInHierarchicalLayout ( ) { return false ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . util . TransferDropTargetListener ; import org . eclipse . jface . viewers . AbstractTreeViewer ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . DropTargetEvent ; import org . eclipse . swt . dnd . FileTransfer ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . actions . CopyFilesAndFoldersOperation ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Resources ; import org . rubypeople . rdt . internal . ui . dnd . RdtViewerDropAdapter ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; class FileTransferDropAdapter extends RdtViewerDropAdapter implements TransferDropTargetListener { FileTransferDropAdapter ( AbstractTreeViewer viewer ) { super ( viewer , DND . FEEDBACK_SCROLL | DND . FEEDBACK_EXPAND ) ; } public Transfer getTransfer ( ) { return FileTransfer . getInstance ( ) ; } public boolean isEnabled ( DropTargetEvent event ) { Object target = event . item != null ? event . item . getData ( ) : null ; if ( target == null ) return false ; return target instanceof IRubyElement || target instanceof IResource ; } public void validateDrop ( Object target , DropTargetEvent event , int operation ) { event . detail = DND . DROP_NONE ; boolean isPackageFragment = target instanceof ISourceFolder ; boolean isRubyProject = target instanceof IRubyProject ; boolean isPackageFragmentRoot = target instanceof ISourceFolderRoot ; boolean isContainer = target instanceof IContainer ; if ( ! ( isPackageFragment || isRubyProject || isPackageFragmentRoot || isContainer ) ) return ; if ( isContainer ) { IContainer container = ( IContainer ) target ; if ( container . isAccessible ( ) && ! Resources . isReadOnly ( container ) ) event . detail = DND . DROP_COPY ; } else { IRubyElement element = ( IRubyElement ) target ; if ( ! element . isReadOnly ( ) ) event . detail = DND . DROP_COPY ; } return ; } public void drop ( Object dropTarget , final DropTargetEvent event ) { try { int operation = event . detail ; event . detail = DND . DROP_NONE ; final Object data = event . data ; if ( data == null || ! ( data instanceof String [ ] ) || operation != DND . DROP_COPY ) return ; final IContainer target = getActualTarget ( dropTarget ) ; if ( target == null ) return ; Display . getCurrent ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { getShell ( ) . forceActive ( ) ; new CopyFilesAndFoldersOperation ( getShell ( ) ) . copyFiles ( ( String [ ] ) data , target ) ; event . detail = DND . DROP_COPY ; } } ) ; } catch ( RubyModelException e ) { String title = PackagesMessages . DropAdapter_errorTitle ; String message = PackagesMessages . DropAdapter_errorMessage ; ExceptionHandler . handle ( e , getShell ( ) , title , message ) ; } } private IContainer getActualTarget ( Object dropTarget ) throws RubyModelException { if ( dropTarget instanceof IContainer ) return ( IContainer ) dropTarget ; else if ( dropTarget instanceof IRubyElement ) return getActualTarget ( ( ( IRubyElement ) dropTarget ) . getCorrespondingResource ( ) ) ; return null ; } private Shell getShell ( ) { return getViewer ( ) . getControl ( ) . getShell ( ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . ui . views . framelist . TreeFrame ; import org . eclipse . ui . views . framelist . TreeViewerFrameSource ; class PackagesFrameSource extends TreeViewerFrameSource { private PackageExplorerPart fPackagesExplorer ; PackagesFrameSource ( PackageExplorerPart explorer ) { super ( explorer . getViewer ( ) ) ; fPackagesExplorer = explorer ; } protected TreeFrame createFrame ( Object input ) { TreeFrame frame = super . createFrame ( input ) ; frame . setName ( fPackagesExplorer . getFrameName ( input ) ) ; frame . setToolTipText ( fPackagesExplorer . getToolTipText ( input ) ) ; return frame ; } protected void frameChanged ( TreeFrame frame ) { super . frameChanged ( frame ) ; fPackagesExplorer . updateTitle ( ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . TreePath ; public interface IMultiElementTreeContentProvider extends ITreeContentProvider { public TreePath [ ] getTreePaths ( Object element ) ; } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . core . resources . IFolder ; import org . eclipse . jface . util . Assert ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . internal . ui . viewsupport . AppearanceAwareLabelProvider ; public class PackageExplorerLabelProvider extends AppearanceAwareLabelProvider { private PackageExplorerContentProvider fContentProvider ; private boolean fIsFlatLayout ; private PackageExplorerProblemsDecorator fProblemDecorator ; public PackageExplorerLabelProvider ( long textFlags , int imageFlags , PackageExplorerContentProvider cp ) { super ( textFlags , imageFlags ) ; fProblemDecorator = new PackageExplorerProblemsDecorator ( ) ; addLabelDecorator ( fProblemDecorator ) ; Assert . isNotNull ( cp ) ; fContentProvider = cp ; } public String getText ( Object element ) { if ( fIsFlatLayout || ! ( element instanceof ISourceFolder ) ) return super . getText ( element ) ; ISourceFolder fragment = ( ISourceFolder ) element ; if ( fragment . isDefaultPackage ( ) ) { return super . getText ( fragment ) ; } else { Object parent = fContentProvider . getSourceFolderProvider ( ) . getParent ( fragment ) ; if ( parent instanceof ISourceFolder ) { return getNameDelta ( ( ISourceFolder ) parent , fragment ) ; } else if ( parent instanceof IFolder ) { int prefixLength = getPrefixLength ( ( IFolder ) parent ) ; return fragment . getElementName ( ) . substring ( prefixLength ) ; } else return super . getText ( fragment ) ; } } private int getPrefixLength ( IFolder folder ) { Object parent = fContentProvider . getParent ( folder ) ; int folderNameLenght = folder . getName ( ) . length ( ) + ; if ( parent instanceof ISourceFolder ) { String fragmentName = ( ( ISourceFolder ) parent ) . getElementName ( ) ; return fragmentName . length ( ) + + folderNameLenght ; } else if ( parent instanceof IFolder ) { return getPrefixLength ( ( IFolder ) parent ) + folderNameLenght ; } else { return folderNameLenght ; } } private String getNameDelta ( ISourceFolder topFragment , ISourceFolder bottomFragment ) { String topName = topFragment . getElementName ( ) ; String bottomName = bottomFragment . getElementName ( ) ; if ( topName . equals ( bottomName ) ) return topName ; if ( bottomName . startsWith ( topName ) ) { String deltaname = bottomName . substring ( topName . length ( ) + ) ; return deltaname ; } else { return bottomName ; } } public void setIsFlatLayout ( boolean state ) { fIsFlatLayout = state ; fProblemDecorator . setIsFlatLayout ( state ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class LoadPathContainer implements IAdaptable , IWorkbenchAdapter { private IRubyProject fProject ; private ILoadpathEntry fClassPathEntry ; private ILoadpathContainer fContainer ; public static class RequiredProjectWrapper implements IAdaptable , IWorkbenchAdapter { private final IRubyElement fProject ; private static ImageDescriptor DESC_OBJ_PROJECT ; { ISharedImages images = RubyPlugin . getDefault ( ) . getWorkbench ( ) . getSharedImages ( ) ; DESC_OBJ_PROJECT = images . getImageDescriptor ( IDE . SharedImages . IMG_OBJ_PROJECT ) ; } public RequiredProjectWrapper ( IRubyElement project ) { this . fProject = project ; } public IRubyElement getProject ( ) { return fProject ; } public Object getAdapter ( Class adapter ) { if ( adapter == IWorkbenchAdapter . class ) return this ; return null ; } public Object [ ] getChildren ( Object o ) { return null ; } public ImageDescriptor getImageDescriptor ( Object object ) { return DESC_OBJ_PROJECT ; } public String getLabel ( Object o ) { return fProject . getElementName ( ) ; } public Object getParent ( Object o ) { return null ; } } public LoadPathContainer ( IRubyProject parent , ILoadpathEntry entry ) { fProject = parent ; fClassPathEntry = entry ; try { fContainer = RubyCore . getLoadpathContainer ( entry . getPath ( ) , parent ) ; } catch ( RubyModelException e ) { fContainer = null ; } } public boolean equals ( Object obj ) { if ( obj instanceof LoadPathContainer ) { LoadPathContainer other = ( LoadPathContainer ) obj ; if ( fProject . equals ( other . fProject ) && fClassPathEntry . equals ( other . fClassPathEntry ) ) { return true ; } } return false ; } public int hashCode ( ) { return fProject . hashCode ( ) * + fClassPathEntry . hashCode ( ) ; } public Object [ ] getSourceFolderRoots ( ) { return fProject . findSourceFolderRoots ( fClassPathEntry ) ; } public Object getAdapter ( Class adapter ) { if ( adapter == IWorkbenchAdapter . class ) return this ; if ( ( adapter == IResource . class ) && ( fContainer instanceof IAdaptable ) ) return ( ( IAdaptable ) fContainer ) . getAdapter ( IResource . class ) ; return null ; } public Object [ ] getChildren ( Object o ) { return concatenate ( getSourceFolderRoots ( ) , getRequiredProjects ( ) ) ; } private Object [ ] getRequiredProjects ( ) { List list = new ArrayList ( ) ; if ( fContainer != null ) { ILoadpathEntry [ ] classpathEntries = fContainer . getLoadpathEntries ( ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( int i = ; i < classpathEntries . length ; i ++ ) { ILoadpathEntry entry = classpathEntries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { IResource resource = root . findMember ( entry . getPath ( ) ) ; if ( resource instanceof IProject ) list . add ( new RequiredProjectWrapper ( RubyCore . create ( resource ) ) ) ; } } } return list . toArray ( ) ; } protected static Object [ ] concatenate ( Object [ ] a1 , Object [ ] a2 ) { int a1Len = a1 . length ; int a2Len = a2 . length ; Object [ ] res = new Object [ a1Len + a2Len ] ; System . arraycopy ( a1 , , res , , a1Len ) ; System . arraycopy ( a2 , , res , a1Len , a2Len ) ; return res ; } public ImageDescriptor getImageDescriptor ( Object object ) { return RubyPluginImages . DESC_OBJS_LIBRARY ; } public String getLabel ( Object o ) { if ( fContainer != null ) return fContainer . getDescription ( ) ; IPath path = fClassPathEntry . getPath ( ) ; String containerId = path . segment ( ) ; LoadpathContainerInitializer initializer = RubyCore . getLoadpathContainerInitializer ( containerId ) ; if ( initializer != null ) { String description = initializer . getDescription ( path , fProject ) ; return Messages . format ( PackagesMessages . ClassPathContainer_unbound_label , description ) ; } return Messages . format ( PackagesMessages . ClassPathContainer_unknown_label , path . toString ( ) ) ; } public Object getParent ( Object o ) { return getRubyProject ( ) ; } public IRubyProject getRubyProject ( ) { return fProject ; } public ILoadpathEntry getLoadpathEntry ( ) { return fClassPathEntry ; } static boolean contains ( IRubyProject project , ILoadpathEntry entry , ISourceFolderRoot root ) { ISourceFolderRoot [ ] roots = project . findSourceFolderRoots ( entry ) ; for ( int i = ; i < roots . length ; i ++ ) { if ( roots [ i ] . equals ( root ) ) return true ; } return false ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . osgi . util . NLS ; public class PackagesMessages extends NLS { private static final String BUNDLE_NAME = PackagesMessages . class . getName ( ) ; public static String ClassPathContainer_unbound_label ; public static String ClassPathContainer_unknown_label ; public static String CollapseAllAction_label ; public static String CollapseAllAction_description ; public static String CollapseAllAction_tooltip ; public static String GotoResource_dialog_title ; public static String GotoResource_action_label ; public static String GotoType_action_label ; public static String GotoType_action_description ; public static String GotoType_error_message ; public static String GotoType_dialog_message ; public static String GotoType_dialog_title ; public static String PackageExplorer_element_not_present ; public static String PackageExplorerPart_workspace ; public static String PackageExplorerPart_workingSetModel ; public static String PackageExplorer_title ; public static String PackageExplorer_toolTip ; public static String PackageExplorer_toolTip2 ; public static String PackageExplorer_toolTip3 ; public static String PackageExplorer_notFound ; public static String PackageExplorer_filteredDialog_title ; public static String PackageExplorer_removeFilters ; public static String DragAdapter_deleting ; public static String DragAdapter_refreshing ; public static String DragAdapter_problem ; public static String DragAdapter_problemTitle ; public static String DropAdapter_errorTitle ; public static String DropAdapter_errorMessage ; public static String SelectionTransferDropAdapter_error_title ; public static String SelectionTransferDropAdapter_error_message ; static { NLS . initializeMessages ( BUNDLE_NAME , PackagesMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . viewers . IBasicPropertyConstants ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IWorkingSet ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . ERBScript ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . workingsets . WorkingSetModel ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; public class PackageExplorerContentProvider extends StandardRubyElementContentProvider implements ITreeContentProvider , IElementChangedListener { protected static final int ORIGINAL = ; protected static final int PARENT = << ; protected static final int GRANT_PARENT = << ; protected static final int PROJECT = << ; private TreeViewer fViewer ; private Object fInput ; private boolean fIsFlatLayout ; private SourceFolderProvider fSourceFolderProvider ; private int fPendingChanges ; public PackageExplorerContentProvider ( boolean provideMembers ) { super ( provideMembers ) ; fSourceFolderProvider = new SourceFolderProvider ( ) ; } SourceFolderProvider getSourceFolderProvider ( ) { return fSourceFolderProvider ; } protected Object getViewerInput ( ) { return fInput ; } public void elementChanged ( final ElementChangedEvent event ) { try { if ( inputDeleted ( ) ) return ; processDelta ( event . getDelta ( ) ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } private boolean inputDeleted ( ) { if ( fInput == null ) return false ; if ( ( fInput instanceof IRubyElement ) && ( ( IRubyElement ) fInput ) . exists ( ) ) return false ; if ( ( fInput instanceof IResource ) && ( ( IResource ) fInput ) . exists ( ) ) return false ; if ( fInput instanceof WorkingSetModel ) return false ; if ( fInput instanceof IWorkingSet ) return false ; postRefresh ( fInput , ORIGINAL , fInput ) ; return true ; } public void dispose ( ) { super . dispose ( ) ; RubyCore . removeElementChangedListener ( this ) ; fSourceFolderProvider . dispose ( ) ; } private boolean needsToDelegateGetChildren ( Object element ) { int type = - ; if ( element instanceof IFolder ) { IFolder folder = ( IFolder ) element ; if ( RubyProject . hasRubyNature ( folder . getProject ( ) ) ) return true ; return false ; } if ( element instanceof IRubyElement ) type = ( ( IRubyElement ) element ) . getElementType ( ) ; return ( ! fIsFlatLayout && ( type == IRubyElement . SOURCE_FOLDER || type == IRubyElement . SOURCE_FOLDER_ROOT || type == IRubyElement . RUBY_PROJECT ) ) ; } public Object [ ] getChildren ( Object parentElement ) { Object [ ] children = NO_CHILDREN ; try { if ( parentElement instanceof IRubyModel ) return concatenate ( getRubyProjects ( ( IRubyModel ) parentElement ) , getNonRubyProjects ( ( IRubyModel ) parentElement ) ) ; if ( parentElement instanceof LoadPathContainer ) return getContainerSourceFolderRoots ( ( LoadPathContainer ) parentElement ) ; if ( parentElement instanceof IProject ) return ( ( IProject ) parentElement ) . members ( ) ; if ( needsToDelegateGetChildren ( parentElement ) ) { Object [ ] packageFragments = fSourceFolderProvider . getChildren ( parentElement ) ; children = getWithParentsResources ( packageFragments , parentElement ) ; } else { children = super . getChildren ( parentElement ) ; } if ( parentElement instanceof IRubyProject ) { IRubyProject project = ( IRubyProject ) parentElement ; return rootsAndContainers ( project , children ) ; } else return children ; } catch ( CoreException e ) { return NO_CHILDREN ; } } private Object [ ] rootsAndContainers ( IRubyProject project , Object [ ] roots ) throws RubyModelException { List result = new ArrayList ( roots . length ) ; Set containers = new HashSet ( roots . length ) ; Set containedRoots = new HashSet ( roots . length ) ; ILoadpathEntry [ ] entries = project . getRawLoadpath ( ) ; for ( int i = ; i < entries . length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry != null && entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) { ISourceFolderRoot [ ] roots1 = project . findSourceFolderRoots ( entry ) ; containedRoots . addAll ( Arrays . asList ( roots1 ) ) ; containers . add ( entry ) ; } } for ( int i = ; i < roots . length ; i ++ ) { if ( roots [ i ] instanceof ISourceFolderRoot ) { if ( ! containedRoots . contains ( roots [ i ] ) ) { result . add ( roots [ i ] ) ; } } else { result . add ( roots [ i ] ) ; } } for ( Iterator each = containers . iterator ( ) ; each . hasNext ( ) ; ) { ILoadpathEntry element = ( ILoadpathEntry ) each . next ( ) ; result . add ( new LoadPathContainer ( project , element ) ) ; } return result . toArray ( ) ; } private Object [ ] getContainerSourceFolderRoots ( LoadPathContainer container ) { return container . getChildren ( container ) ; } private Object [ ] getNonRubyProjects ( IRubyModel model ) throws RubyModelException { return model . getNonRubyResources ( ) ; } public Object getParent ( Object child ) { if ( needsToDelegateGetParent ( child ) ) { return fSourceFolderProvider . getParent ( child ) ; } else return super . getParent ( child ) ; } protected Object internalGetParent ( Object element ) { if ( element instanceof ISourceFolderRoot ) { ISourceFolderRoot root = ( ISourceFolderRoot ) element ; IRubyProject project = root . getRubyProject ( ) ; try { ILoadpathEntry [ ] entries = project . getRawLoadpath ( ) ; for ( int i = ; i < entries . length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) { if ( LoadPathContainer . contains ( project , entry , root ) ) return new LoadPathContainer ( project , entry ) ; } } } catch ( RubyModelException e ) { } } if ( element instanceof LoadPathContainer ) { return ( ( LoadPathContainer ) element ) . getRubyProject ( ) ; } return super . internalGetParent ( element ) ; } private boolean needsToDelegateGetParent ( Object element ) { int type = - ; if ( element instanceof IRubyElement ) type = ( ( IRubyElement ) element ) . getElementType ( ) ; return ( ! fIsFlatLayout && type == IRubyElement . SOURCE_FOLDER ) ; } private Object [ ] getWithParentsResources ( Object [ ] existingObject , Object parent ) { Object [ ] objects = super . getChildren ( parent ) ; List list = new ArrayList ( ) ; for ( int i = ; i < objects . length ; i ++ ) { Object object = objects [ i ] ; if ( ! ( object instanceof ISourceFolder ) ) { if ( ! list . contains ( object ) ) { list . add ( object ) ; } } } if ( existingObject != null ) list . addAll ( Arrays . asList ( existingObject ) ) ; return list . toArray ( ) ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { super . inputChanged ( viewer , oldInput , newInput ) ; fSourceFolderProvider . inputChanged ( viewer , oldInput , newInput ) ; fViewer = ( TreeViewer ) viewer ; if ( oldInput == null && newInput != null ) { RubyCore . addElementChangedListener ( this ) ; } else if ( oldInput != null && newInput == null ) { RubyCore . removeElementChangedListener ( this ) ; } fInput = newInput ; } private void processDelta ( IRubyElementDelta delta ) throws RubyModelException { int kind = delta . getKind ( ) ; int flags = delta . getFlags ( ) ; IRubyElement element = delta . getElement ( ) ; int elementType = element . getElementType ( ) ; if ( elementType != IRubyElement . RUBY_MODEL && elementType != IRubyElement . RUBY_PROJECT ) { IRubyProject proj = element . getRubyProject ( ) ; if ( proj == null || ! proj . getProject ( ) . isOpen ( ) ) return ; } if ( ! fIsFlatLayout && elementType == IRubyElement . SOURCE_FOLDER ) { fSourceFolderProvider . processDelta ( delta ) ; if ( processResourceDeltas ( delta . getResourceDeltas ( ) , element ) ) return ; handleAffectedChildren ( delta , element ) ; return ; } if ( elementType == IRubyElement . SCRIPT ) { IRubyScript cu = ( IRubyScript ) element ; if ( ! RubyModelUtil . isPrimary ( cu ) ) { return ; } if ( ! getProvideMembers ( ) && cu . isWorkingCopy ( ) && kind == IRubyElementDelta . CHANGED ) { return ; } if ( ( kind == IRubyElementDelta . CHANGED ) && ! isStructuralCUChange ( flags ) ) { return ; } if ( ! isOnClassPath ( cu ) ) { return ; } } if ( elementType == IRubyElement . RUBY_PROJECT ) { if ( ( flags & ( IRubyElementDelta . F_CLOSED | IRubyElementDelta . F_OPENED ) ) != ) { postRefresh ( element , ORIGINAL , element ) ; return ; } if ( ( flags & IRubyElementDelta . F_CLASSPATH_CHANGED ) != ) { postRefresh ( element , ORIGINAL , element ) ; return ; } } if ( kind == IRubyElementDelta . REMOVED ) { Object parent = internalGetParent ( element ) ; if ( element instanceof ISourceFolder ) { if ( fViewer . testFindItem ( parent ) != null ) postRefresh ( parent , PARENT , element ) ; return ; } postRemove ( element ) ; if ( parent instanceof ISourceFolder ) postUpdateIcon ( ( ISourceFolder ) parent ) ; if ( isSourceFolderEmpty ( element . getParent ( ) ) ) { if ( fViewer . testFindItem ( parent ) != null ) postRefresh ( internalGetParent ( parent ) , GRANT_PARENT , element ) ; } return ; } if ( kind == IRubyElementDelta . ADDED ) { Object parent = internalGetParent ( element ) ; if ( parent instanceof ISourceFolder ) { Object grandparent = internalGetParent ( parent ) ; if ( ( ( ISourceFolder ) parent ) . isDefaultPackage ( ) ) { parent = grandparent ; grandparent = internalGetParent ( parent ) ; } if ( parent . equals ( fInput ) ) { postRefresh ( parent , PARENT , element ) ; } else { if ( fViewer . testFindItem ( parent ) == null ) postRefresh ( grandparent , GRANT_PARENT , element ) ; else { postRefresh ( parent , PARENT , element ) ; } } return ; } else { if ( ( flags & IRubyElementDelta . F_MOVED_FROM ) != ) { postRemove ( delta . getMovedFromElement ( ) ) ; } postAdd ( parent , element ) ; } } if ( elementType == IRubyElement . SCRIPT ) { if ( kind == IRubyElementDelta . CHANGED ) { postRefresh ( element , ORIGINAL , element ) ; updateSelection ( delta ) ; } return ; } if ( elementType == IRubyElement . SOURCE_FOLDER_ROOT ) { if ( ( flags & IRubyElementDelta . F_ARCHIVE_CONTENT_CHANGED ) != ) { postRefresh ( element , ORIGINAL , element ) ; return ; } if ( ( flags & ( IRubyElementDelta . F_SOURCEATTACHED | IRubyElementDelta . F_SOURCEDETACHED ) ) != ) postUpdateIcon ( element ) ; if ( isClassPathChange ( delta ) ) { postRefresh ( element . getRubyProject ( ) , PROJECT , element ) ; return ; } } if ( processResourceDeltas ( delta . getResourceDeltas ( ) , element ) ) return ; handleAffectedChildren ( delta , element ) ; } private static boolean isStructuralCUChange ( int flags ) { return ( ( flags & IRubyElementDelta . F_CHILDREN ) != ) || ( ( flags & ( IRubyElementDelta . F_CONTENT | IRubyElementDelta . F_FINE_GRAINED ) ) == IRubyElementDelta . F_CONTENT ) ; } void handleAffectedChildren ( IRubyElementDelta delta , IRubyElement element ) throws RubyModelException { IRubyElementDelta [ ] affectedChildren = delta . getAffectedChildren ( ) ; if ( affectedChildren . length > ) { if ( element instanceof ISourceFolder ) { IRubyElement parent = ( IRubyElement ) internalGetParent ( element ) ; if ( parent instanceof ISourceFolderRoot ) { parent = ( IRubyElement ) internalGetParent ( parent ) ; } if ( element . equals ( fInput ) ) { postRefresh ( element , ORIGINAL , element ) ; } else { postRefresh ( parent , PARENT , element ) ; } return ; } if ( element instanceof ISourceFolderRoot ) { Object toRefresh = skipProjectSourceFolderRoot ( ( ISourceFolderRoot ) element ) ; postRefresh ( toRefresh , ORIGINAL , toRefresh ) ; } else { postRefresh ( element , ORIGINAL , element ) ; } return ; } processAffectedChildren ( affectedChildren ) ; } protected void processAffectedChildren ( IRubyElementDelta [ ] affectedChildren ) throws RubyModelException { for ( int i = ; i < affectedChildren . length ; i ++ ) { processDelta ( affectedChildren [ i ] ) ; } } private boolean isOnClassPath ( IRubyScript element ) { IRubyProject project = element . getRubyProject ( ) ; if ( project == null || ! project . exists ( ) ) return false ; return project . isOnLoadpath ( element ) ; } private void updateSelection ( IRubyElementDelta delta ) { final IRubyElement addedElement = findAddedElement ( delta ) ; if ( addedElement != null ) { final StructuredSelection selection = new StructuredSelection ( addedElement ) ; postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { if ( fViewer . testFindItem ( addedElement ) != null ) fViewer . setSelection ( selection ) ; } } } ) ; } } private IRubyElement findAddedElement ( IRubyElementDelta delta ) { if ( delta . getKind ( ) == IRubyElementDelta . ADDED ) return delta . getElement ( ) ; IRubyElementDelta [ ] affectedChildren = delta . getAffectedChildren ( ) ; for ( int i = ; i < affectedChildren . length ; i ++ ) return findAddedElement ( affectedChildren [ i ] ) ; return null ; } private void postUpdateIcon ( final IRubyElement element ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) fViewer . update ( element , new String [ ] { IBasicPropertyConstants . P_IMAGE } ) ; } } ) ; } private boolean processResourceDelta ( IResourceDelta delta , Object parent ) { int status = delta . getKind ( ) ; int flags = delta . getFlags ( ) ; IResource resource = delta . getResource ( ) ; if ( resource == null ) return false ; if ( ( status & IResourceDelta . REMOVED ) != ) { if ( parent instanceof ISourceFolder ) { Object grandparent = internalGetParent ( parent ) ; if ( grandparent instanceof ISourceFolderRoot && ( ( ISourceFolderRoot ) grandparent ) . getResource ( ) . equals ( ( ( ISourceFolderRoot ) grandparent ) . getRubyProject ( ) . getProject ( ) ) ) { parent = grandparent ; grandparent = internalGetParent ( parent ) ; } postRefresh ( grandparent , PARENT , parent ) ; return true ; } else postRemove ( resource ) ; } if ( ( status & IResourceDelta . ADDED ) != ) { if ( parent instanceof ISourceFolder ) { Object grandparent = internalGetParent ( parent ) ; if ( grandparent instanceof ISourceFolderRoot && ( ( ISourceFolderRoot ) grandparent ) . getResource ( ) . equals ( ( ( ISourceFolderRoot ) grandparent ) . getRubyProject ( ) . getProject ( ) ) ) { parent = grandparent ; grandparent = internalGetParent ( parent ) ; } postRefresh ( grandparent , PARENT , parent ) ; return true ; } else postAdd ( parent , resource ) ; } if ( ( flags & IResourceDelta . OPEN ) != ) { postProjectStateChanged ( internalGetParent ( parent ) ) ; return true ; } processResourceDeltas ( delta . getAffectedChildren ( ) , resource ) ; return false ; } public void setIsFlatLayout ( boolean state ) { fIsFlatLayout = state ; } private boolean processResourceDeltas ( IResourceDelta [ ] deltas , Object parent ) { if ( deltas == null ) return false ; if ( deltas . length > ) { postRefresh ( parent , ORIGINAL , parent ) ; return true ; } for ( int i = ; i < deltas . length ; i ++ ) { if ( processResourceDelta ( deltas [ i ] , parent ) ) return true ; } return false ; } private void postRefresh ( Object root , int relation , Object affectedElement ) { if ( isParent ( root , fInput ) ) root = fInput ; List toRefresh = new ArrayList ( ) ; toRefresh . add ( root ) ; augmentElementToRefresh ( toRefresh , relation , affectedElement ) ; postRefresh ( toRefresh , true ) ; } protected void augmentElementToRefresh ( List toRefresh , int relation , Object affectedElement ) { } boolean isParent ( Object root , Object child ) { Object parent = getParent ( child ) ; if ( parent == null ) return false ; if ( parent . equals ( root ) ) return true ; return isParent ( root , parent ) ; } protected void postRefresh ( final List toRefresh , final boolean updateLabels ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { for ( Iterator iter = toRefresh . iterator ( ) ; iter . hasNext ( ) ; ) { fViewer . refresh ( iter . next ( ) , updateLabels ) ; } } } } ) ; } protected void postAdd ( final Object parent , final Object element ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { if ( fViewer . testFindItem ( element ) == null ) fViewer . add ( parent , element ) ; } } } ) ; } protected void postRemove ( final Object element ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { fViewer . remove ( element ) ; } } } ) ; } protected void postProjectStateChanged ( final Object root ) { postRunnable ( new Runnable ( ) { public void run ( ) { Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { fViewer . refresh ( root , true ) ; fViewer . setSelection ( fViewer . getSelection ( ) ) ; } } } ) ; } void postRunnable ( final Runnable r ) { Control ctrl = fViewer . getControl ( ) ; final Runnable trackedRunnable = new Runnable ( ) { public void run ( ) { try { r . run ( ) ; } finally { removePendingChange ( ) ; } } } ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { addPendingChange ( ) ; try { ctrl . getDisplay ( ) . asyncExec ( trackedRunnable ) ; } catch ( RuntimeException e ) { removePendingChange ( ) ; throw e ; } catch ( Error e ) { removePendingChange ( ) ; throw e ; } } } public synchronized boolean hasPendingChanges ( ) { return fPendingChanges > ; } private synchronized void addPendingChange ( ) { fPendingChanges ++ ; } synchronized void removePendingChange ( ) { fPendingChanges -- ; if ( fPendingChanges < ) fPendingChanges = ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . rubypeople . rdt . internal . ui . actions . AbstractToggleLinkingAction ; import org . rubypeople . rdt . ui . IPackagesViewPart ; public class ToggleLinkingAction extends AbstractToggleLinkingAction { private IPackagesViewPart fPackageExplorerPart ; public ToggleLinkingAction ( IPackagesViewPart explorer ) { setChecked ( explorer . isLinkingEnabled ( ) ) ; fPackageExplorerPart = explorer ; } public void run ( ) { fPackageExplorerPart . setLinkingEnabled ( isChecked ( ) ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . ui . IWorkingSet ; import org . rubypeople . rdt . ui . RubyElementSorter ; public class WorkingSetAwareRubyElementSorter extends RubyElementSorter { public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( e1 instanceof IWorkingSet || e2 instanceof IWorkingSet ) return ; return super . compare ( viewer , e1 , e2 ) ; } } package org . rubypeople . rdt . internal . ui . packageview ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . TreePath ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . IWorkingSetManager ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . workingsets . OthersWorkingSetUpdater ; import org . rubypeople . rdt . internal . ui . workingsets . RubyWorkingSetUpdater ; import org . rubypeople . rdt . internal . ui . workingsets . WorkingSetModel ; public class WorkingSetAwareContentProvider extends PackageExplorerContentProvider implements IMultiElementTreeContentProvider { private WorkingSetModel fWorkingSetModel ; private IPropertyChangeListener fListener ; public WorkingSetAwareContentProvider ( boolean provideMembers , WorkingSetModel model ) { super ( provideMembers ) ; fWorkingSetModel = model ; fListener = new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { workingSetModelChanged ( event ) ; } } ; fWorkingSetModel . addPropertyChangeListener ( fListener ) ; } public void dispose ( ) { fWorkingSetModel . removePropertyChangeListener ( fListener ) ; super . dispose ( ) ; } public boolean hasChildren ( Object element ) { if ( element instanceof IWorkingSet ) return true ; return super . hasChildren ( element ) ; } public Object [ ] getChildren ( Object element ) { Object [ ] children ; if ( element instanceof WorkingSetModel ) { Assert . isTrue ( fWorkingSetModel == element ) ; return fWorkingSetModel . getActiveWorkingSets ( ) ; } else if ( element instanceof IWorkingSet ) { children = getWorkingSetChildren ( ( IWorkingSet ) element ) ; } else { children = super . getChildren ( element ) ; } return children ; } private Object [ ] getWorkingSetChildren ( IWorkingSet set ) { IAdaptable [ ] elements = fWorkingSetModel . getChildren ( set ) ; boolean isKnownWorkingSet = isKnownWorkingSet ( set ) ; List result = new ArrayList ( elements . length ) ; for ( int i = ; i < elements . length ; i ++ ) { IAdaptable element = elements [ i ] ; boolean add = false ; if ( element instanceof IProject ) { add = true ; } else if ( element instanceof IResource ) { IProject project = ( ( IResource ) element ) . getProject ( ) ; add = project == null || project . isOpen ( ) ; } else if ( element instanceof IRubyProject ) { add = true ; } else if ( element instanceof IRubyElement ) { IProject project = getProject ( ( IRubyElement ) element ) ; add = project == null || project . isOpen ( ) ; } if ( add ) { if ( isKnownWorkingSet ) { result . add ( element ) ; } else { IProject project = ( IProject ) element . getAdapter ( IProject . class ) ; if ( project != null && project . exists ( ) ) { IRubyProject jp = RubyCore . create ( project ) ; if ( jp != null && jp . exists ( ) ) { result . add ( jp ) ; } else { result . add ( project ) ; } } } } } return result . toArray ( ) ; } private boolean isKnownWorkingSet ( IWorkingSet set ) { String id = set . getId ( ) ; return OthersWorkingSetUpdater . ID . equals ( id ) || RubyWorkingSetUpdater . ID . equals ( id ) ; } private IProject getProject ( IRubyElement element ) { if ( element == null ) return null ; IRubyProject project = element . getRubyProject ( ) ; if ( project == null ) return null ; return project . getProject ( ) ; } public TreePath [ ] getTreePaths ( Object element ) { if ( element instanceof IWorkingSet ) { TreePath path = new TreePath ( new Object [ ] { element } ) ; return new TreePath [ ] { path } ; } List modelParents = getModelPath ( element ) ; List result = new ArrayList ( ) ; for ( int i = ; i < modelParents . size ( ) ; i ++ ) { result . addAll ( getTreePaths ( modelParents , i ) ) ; } return ( TreePath [ ] ) result . toArray ( new TreePath [ result . size ( ) ] ) ; } private List getModelPath ( Object element ) { List result = new ArrayList ( ) ; result . add ( element ) ; Object parent = super . getParent ( element ) ; Object input = getViewerInput ( ) ; while ( parent != null && ! parent . equals ( input ) && ! ( parent instanceof IRubyModel ) ) { result . add ( parent ) ; parent = super . getParent ( parent ) ; } Collections . reverse ( result ) ; return result ; } private List getTreePaths ( List modelParents , int index ) { List result = new ArrayList ( ) ; Object input = getViewerInput ( ) ; Object element = modelParents . get ( index ) ; Object [ ] parents = fWorkingSetModel . getAllParents ( element ) ; for ( int i = ; i < parents . length ; i ++ ) { List chain = new ArrayList ( ) ; if ( ! parents [ i ] . equals ( input ) ) chain . add ( parents [ i ] ) ; for ( int m = index ; m < modelParents . size ( ) ; m ++ ) { chain . add ( modelParents . get ( m ) ) ; } result . add ( new TreePath ( chain . toArray ( ) ) ) ; } return result ; } public Object getParent ( Object child ) { Object [ ] parents = fWorkingSetModel . getAllParents ( child ) ; if ( parents . length == ) return super . getParent ( child ) ; Object first = parents [ ] ; return first ; } protected void augmentElementToRefresh ( List toRefresh , int relation , Object affectedElement ) { if ( RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) . equals ( affectedElement ) ) { toRefresh . remove ( affectedElement ) ; toRefresh . add ( fWorkingSetModel ) ; } else if ( relation == GRANT_PARENT ) { Object parent = internalGetParent ( affectedElement ) ; if ( parent != null ) { toRefresh . addAll ( Arrays . asList ( fWorkingSetModel . getAllParents ( parent ) ) ) ; } } List nonProjetTopLevelElemens = fWorkingSetModel . getNonProjectTopLevelElements ( ) ; if ( nonProjetTopLevelElemens . isEmpty ( ) ) return ; List toAdd = new ArrayList ( ) ; for ( Iterator iter = nonProjetTopLevelElemens . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( isChildOf ( element , toRefresh ) ) toAdd . add ( element ) ; } toRefresh . addAll ( toAdd ) ; } private void workingSetModelChanged ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; Object newValue = event . getNewValue ( ) ; List toRefresh = new ArrayList ( ) ; if ( WorkingSetModel . CHANGE_WORKING_SET_MODEL_CONTENT . equals ( property ) ) { toRefresh . add ( fWorkingSetModel ) ; } else if ( IWorkingSetManager . CHANGE_WORKING_SET_CONTENT_CHANGE . equals ( property ) ) { toRefresh . add ( newValue ) ; } else if ( IWorkingSetManager . CHANGE_WORKING_SET_NAME_CHANGE . equals ( property ) ) { toRefresh . add ( newValue ) ; } postRefresh ( toRefresh , true ) ; } private boolean isChildOf ( Object element , List potentialParents ) { Object parent = super . getParent ( element ) ; if ( parent == null ) return false ; for ( Iterator iter = potentialParents . iterator ( ) ; iter . hasNext ( ) ; ) { Object potentialParent = iter . next ( ) ; while ( parent != null ) { if ( parent . equals ( potentialParent ) ) return true ; parent = super . getParent ( parent ) ; } } return false ; } } package org . rubypeople . rdt . internal . ui . packageview ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . ui . IWorkingSet ; import org . rubypeople . rdt . internal . ui . viewsupport . TreeHierarchyLayoutProblemsDecorator ; import org . rubypeople . rdt . ui . RubyElementImageDescriptor ; public class PackageExplorerProblemsDecorator extends TreeHierarchyLayoutProblemsDecorator { public PackageExplorerProblemsDecorator ( ) { super ( ) ; } public PackageExplorerProblemsDecorator ( boolean isFlatLayout ) { super ( isFlatLayout ) ; } protected int computeAdornmentFlags ( Object obj ) { if ( ! ( obj instanceof IWorkingSet ) ) return super . computeAdornmentFlags ( obj ) ; IWorkingSet workingSet = ( IWorkingSet ) obj ; IAdaptable [ ] elements = workingSet . getElements ( ) ; int result = ; for ( int i = ; i < elements . length ; i ++ ) { IAdaptable element = elements [ i ] ; int flags = super . computeAdornmentFlags ( element ) ; if ( ( flags & RubyElementImageDescriptor . ERROR ) != ) return RubyElementImageDescriptor . ERROR ; if ( ( flags & RubyElementImageDescriptor . WARNING ) != ) result = RubyElementImageDescriptor . WARNING ; } return result ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; public class ResourceLocator implements IResourceLocator { public IResource getUnderlyingResource ( Object element ) throws RubyModelException { if ( element instanceof IRubyElement ) return ( ( IRubyElement ) element ) . getUnderlyingResource ( ) ; else return null ; } public IResource getCorrespondingResource ( Object element ) throws RubyModelException { if ( element instanceof IRubyElement ) return ( ( IRubyElement ) element ) . getCorrespondingResource ( ) ; else return null ; } public IResource getContainingResource ( Object element ) throws RubyModelException { IResource resource = null ; if ( element instanceof IResource ) resource = ( IResource ) element ; if ( element instanceof IRubyElement ) { resource = ( ( IRubyElement ) element ) . getResource ( ) ; if ( resource == null ) resource = ( ( IRubyElement ) element ) . getRubyProject ( ) . getProject ( ) ; } return resource ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . ui . views . tasklist . ITaskListResourceAdapter ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; public class RubyTaskListAdapter implements ITaskListResourceAdapter { public IResource getAffectedResource ( IAdaptable element ) { IRubyElement ruby = ( IRubyElement ) element ; IResource resource = ruby . getResource ( ) ; if ( resource != null ) return resource ; IRubyScript script = ( IRubyScript ) ruby . getAncestor ( IRubyElement . SCRIPT ) ; if ( script != null ) { return RubyModelUtil . toOriginal ( script ) . getResource ( ) ; } return null ; } } package org . rubypeople . rdt . internal . ui ; import org . rubypeople . rdt . ui . RubyUI ; public interface IUIConstants { public static final String DIALOGSTORE_TYPECOMMENT_DEPRECATED = RubyUI . ID_PLUGIN + "" ; public static final String DIALOGSTORE_LASTEXTJAR = RubyUI . ID_PLUGIN + "" ; } package org . rubypeople . rdt . internal . ui ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . ui . ISharedImages ; public class SharedImages implements ISharedImages { public SharedImages ( ) { } public Image getImage ( String key ) { return RubyPluginImages . get ( key ) ; } public ImageDescriptor getImageDescriptor ( String key ) { return RubyPluginImages . getDescriptor ( key ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . core . runtime . IStatus ; public interface ISelectionValidator { IStatus validate ( Object [ ] selection ) ; } package org . rubypeople . rdt . internal . ui . dialogs ; import java . io . IOException ; import java . io . StringWriter ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . dialogs . DialogSettings ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . swt . SWT ; import org . eclipse . swt . accessibility . AccessibleAdapter ; import org . eclipse . swt . accessibility . AccessibleEvent ; import org . eclipse . swt . custom . CLabel ; import org . eclipse . swt . custom . ViewForm ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . events . TraverseEvent ; import org . eclipse . swt . events . TraverseListener ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . Text ; import org . eclipse . swt . widgets . ToolBar ; import org . eclipse . swt . widgets . ToolItem ; import org . eclipse . ui . XMLMemento ; import org . eclipse . ui . actions . WorkingSetFilterActionGroup ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . corext . util . Strings ; import org . rubypeople . rdt . internal . corext . util . TypeInfo ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . internal . ui . util . TypeInfoLabelProvider ; import org . rubypeople . rdt . ui . dialogs . ITypeSelectionComponent ; import org . rubypeople . rdt . ui . dialogs . TypeSelectionExtension ; public class TypeSelectionComponent extends Composite implements ITypeSelectionComponent { private IDialogSettings fSettings ; private boolean fMultipleSelection ; private ITitleLabel fTitleLabel ; private ToolBar fToolBar ; private ToolItem fToolItem ; private MenuManager fMenuManager ; private WorkingSetFilterActionGroup fFilterActionGroup ; private TypeSelectionExtension fTypeSelectionExtension ; private Text fFilter ; private String fInitialFilterText ; private IRubySearchScope fScope ; private TypeInfoViewer fViewer ; private ViewForm fForm ; private CLabel fLabel ; public static final int NONE = ; public static final int CARET_BEGINNING = ; public static final int FULL_SELECTION = ; private static final String DIALOG_SETTINGS = "" ; private static final String SHOW_STATUS_LINE = "" ; private static final String FULLY_QUALIFY_DUPLICATES = "" ; private static final String WORKINGS_SET_SETTINGS = "" ; private class ToggleStatusLineAction extends Action { public ToggleStatusLineAction ( ) { super ( RubyUIMessages . TypeSelectionComponent_show_status_line_label , IAction . AS_CHECK_BOX ) ; } public void run ( ) { if ( fForm == null ) return ; GridData gd = ( GridData ) fForm . getLayoutData ( ) ; boolean checked = isChecked ( ) ; gd . exclude = ! checked ; fForm . setVisible ( checked ) ; fSettings . put ( SHOW_STATUS_LINE , checked ) ; TypeSelectionComponent . this . layout ( ) ; } } private class FullyQualifyDuplicatesAction extends Action { public FullyQualifyDuplicatesAction ( ) { super ( RubyUIMessages . TypeSelectionComponent_fully_qualify_duplicates_label , IAction . AS_CHECK_BOX ) ; } public void run ( ) { boolean checked = isChecked ( ) ; fViewer . setFullyQualifyDuplicates ( checked , true ) ; fSettings . put ( FULLY_QUALIFY_DUPLICATES , checked ) ; } } public interface ITitleLabel { public void setText ( String text ) ; } public TypeSelectionComponent ( Composite parent , int style , String message , boolean multi , IRubySearchScope scope , int elementKind , String initialFilter , ITitleLabel titleLabel , TypeSelectionExtension extension ) { super ( parent , style ) ; setFont ( parent . getFont ( ) ) ; fMultipleSelection = multi ; fScope = scope ; fInitialFilterText = initialFilter ; fTitleLabel = titleLabel ; fTypeSelectionExtension = extension ; IDialogSettings settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; fSettings = settings . getSection ( DIALOG_SETTINGS ) ; if ( fSettings == null ) { fSettings = new DialogSettings ( DIALOG_SETTINGS ) ; settings . addSection ( fSettings ) ; } if ( fSettings . get ( SHOW_STATUS_LINE ) == null ) { fSettings . put ( SHOW_STATUS_LINE , true ) ; } createContent ( message , elementKind ) ; } public void triggerSearch ( ) { fViewer . forceSearch ( ) ; } public TypeInfo [ ] getSelection ( ) { return fViewer . getSelection ( ) ; } public IRubySearchScope getScope ( ) { return fScope ; } private void createContent ( final String message , int elementKind ) { GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginWidth = ; layout . marginHeight = ; setLayout ( layout ) ; Font font = getFont ( ) ; Control header = createHeader ( this , font , message ) ; GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = ; header . setLayoutData ( gd ) ; fFilter = new Text ( this , SWT . BORDER | SWT . FLAT ) ; fFilter . setFont ( font ) ; if ( fInitialFilterText != null ) { fFilter . setText ( fInitialFilterText ) ; } gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = ; fFilter . setLayoutData ( gd ) ; fFilter . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { patternChanged ( ( Text ) e . widget ) ; } } ) ; fFilter . addKeyListener ( new KeyListener ( ) { public void keyReleased ( KeyEvent e ) { } public void keyPressed ( KeyEvent e ) { if ( e . keyCode == SWT . ARROW_DOWN ) { fViewer . setFocus ( ) ; } } } ) ; fFilter . getAccessible ( ) . addAccessibleListener ( new AccessibleAdapter ( ) { public void getName ( AccessibleEvent e ) { e . result = Strings . removeMnemonicIndicator ( message ) ; } } ) ; TextFieldNavigationHandler . install ( fFilter ) ; Label label = new Label ( this , SWT . NONE ) ; label . setFont ( font ) ; label . setText ( RubyUIMessages . TypeSelectionComponent_label ) ; label . addTraverseListener ( new TraverseListener ( ) { public void keyTraversed ( TraverseEvent e ) { if ( e . detail == SWT . TRAVERSE_MNEMONIC && e . doit ) { e . detail = SWT . TRAVERSE_NONE ; fViewer . setFocus ( ) ; } } } ) ; label = new Label ( this , SWT . RIGHT ) ; label . setFont ( font ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; label . setLayoutData ( gd ) ; fViewer = new TypeInfoViewer ( this , fMultipleSelection ? SWT . MULTI : SWT . NONE , label , fScope , elementKind , fInitialFilterText , fTypeSelectionExtension != null ? fTypeSelectionExtension . getFilterExtension ( ) : null , fTypeSelectionExtension != null ? fTypeSelectionExtension . getImageProvider ( ) : null ) ; gd = new GridData ( GridData . FILL_BOTH ) ; final Table table = fViewer . getTable ( ) ; PixelConverter converter = new PixelConverter ( table ) ; gd . widthHint = converter . convertWidthInCharsToPixels ( ) ; gd . heightHint = SWTUtil . getTableHeightHint ( table , ) ; gd . horizontalSpan = ; table . setLayoutData ( gd ) ; table . getAccessible ( ) . addAccessibleListener ( new AccessibleAdapter ( ) { public void getName ( AccessibleEvent e ) { if ( table . getSelectionCount ( ) == ) { e . result = Strings . removeMnemonicIndicator ( RubyUIMessages . TypeSelectionComponent_label ) ; } } } ) ; fViewer . setFullyQualifyDuplicates ( fSettings . getBoolean ( FULLY_QUALIFY_DUPLICATES ) , false ) ; if ( fTypeSelectionExtension != null ) { Control addition = fTypeSelectionExtension . createContentArea ( this ) ; if ( addition != null ) { addition . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; } } if ( ! fMultipleSelection ) { fForm = new ViewForm ( this , SWT . BORDER | SWT . FLAT ) ; fForm . setFont ( font ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = ; boolean showStatusLine = fSettings . getBoolean ( SHOW_STATUS_LINE ) ; gd . exclude = ! showStatusLine ; fForm . setVisible ( showStatusLine ) ; fForm . setLayoutData ( gd ) ; fLabel = new CLabel ( fForm , SWT . FLAT ) ; fLabel . setFont ( fForm . getFont ( ) ) ; fForm . setContent ( fLabel ) ; table . addSelectionListener ( new SelectionAdapter ( ) { private TypeInfoLabelProvider fLabelProvider = new TypeInfoLabelProvider ( TypeInfoLabelProvider . SHOW_TYPE_CONTAINER_ONLY + TypeInfoLabelProvider . SHOW_ROOT_POSTFIX ) ; public void widgetSelected ( SelectionEvent event ) { TypeInfo [ ] selection = fViewer . getSelection ( ) ; if ( selection . length != ) { fLabel . setText ( "" ) ; fLabel . setImage ( null ) ; } else { TypeInfo type = selection [ ] ; fLabel . setText ( fViewer . getLabelProvider ( ) . getQualificationText ( type ) ) ; fLabel . setImage ( fLabelProvider . getImage ( type ) ) ; } } } ) ; } addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent event ) { disposeComponent ( ) ; } } ) ; if ( fTypeSelectionExtension != null ) { fTypeSelectionExtension . initialize ( this ) ; } } public void addSelectionListener ( SelectionListener listener ) { fViewer . getTable ( ) . addSelectionListener ( listener ) ; } public void populate ( int selectionMode ) { if ( fInitialFilterText != null ) { switch ( selectionMode ) { case CARET_BEGINNING : fFilter . setSelection ( , ) ; break ; case FULL_SELECTION : fFilter . setSelection ( , fInitialFilterText . length ( ) ) ; break ; } } fFilter . setFocus ( ) ; fViewer . startup ( ) ; } private void patternChanged ( Text text ) { fViewer . setSearchPattern ( text . getText ( ) ) ; } private Control createHeader ( Composite parent , Font font , String message ) { Composite header = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginWidth = ; layout . marginHeight = ; header . setLayout ( layout ) ; header . setFont ( font ) ; Label label = new Label ( header , SWT . NONE ) ; label . setText ( message ) ; label . setFont ( font ) ; label . addTraverseListener ( new TraverseListener ( ) { public void keyTraversed ( TraverseEvent e ) { if ( e . detail == SWT . TRAVERSE_MNEMONIC && e . doit ) { e . detail = SWT . TRAVERSE_NONE ; fFilter . setFocus ( ) ; } } } ) ; GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; label . setLayoutData ( gd ) ; createViewMenu ( header ) ; return header ; } private void createViewMenu ( Composite parent ) { fToolBar = new ToolBar ( parent , SWT . FLAT ) ; fToolItem = new ToolItem ( fToolBar , SWT . PUSH , ) ; GridData data = new GridData ( ) ; data . horizontalAlignment = GridData . END ; fToolBar . setLayoutData ( data ) ; fToolItem . setImage ( RubyPluginImages . get ( RubyPluginImages . IMG_ELCL_VIEW_MENU ) ) ; fToolItem . setDisabledImage ( RubyPluginImages . get ( RubyPluginImages . IMG_DLCL_VIEW_MENU ) ) ; fToolItem . setToolTipText ( RubyUIMessages . TypeSelectionComponent_menu ) ; fToolItem . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { showViewMenu ( ) ; } } ) ; fMenuManager = new MenuManager ( ) ; fillViewMenu ( fMenuManager ) ; } private void showViewMenu ( ) { Menu menu = fMenuManager . createContextMenu ( getShell ( ) ) ; Rectangle bounds = fToolItem . getBounds ( ) ; Point topLeft = new Point ( bounds . x , bounds . y + bounds . height ) ; topLeft = fToolBar . toDisplay ( topLeft ) ; menu . setLocation ( topLeft . x , topLeft . y ) ; menu . setVisible ( true ) ; } private void fillViewMenu ( IMenuManager viewMenu ) { if ( ! fMultipleSelection ) { ToggleStatusLineAction showStatusLineAction = new ToggleStatusLineAction ( ) ; showStatusLineAction . setChecked ( fSettings . getBoolean ( SHOW_STATUS_LINE ) ) ; viewMenu . add ( showStatusLineAction ) ; } FullyQualifyDuplicatesAction fullyQualifyDuplicatesAction = new FullyQualifyDuplicatesAction ( ) ; fullyQualifyDuplicatesAction . setChecked ( fSettings . getBoolean ( FULLY_QUALIFY_DUPLICATES ) ) ; viewMenu . add ( fullyQualifyDuplicatesAction ) ; if ( fScope == null ) { fScope = SearchEngine . createWorkspaceScope ( ) ; fTitleLabel . setText ( null ) ; } } private void disposeComponent ( ) { if ( fFilterActionGroup != null ) { XMLMemento memento = XMLMemento . createWriteRoot ( "" ) ; fFilterActionGroup . dispose ( ) ; StringWriter writer = new StringWriter ( ) ; try { memento . save ( writer ) ; fSettings . put ( WORKINGS_SET_SETTINGS , writer . getBuffer ( ) . toString ( ) ) ; } catch ( IOException e ) { } } } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . internal . ui . util . FilteredList ; public abstract class AbstractElementListSelectionDialog extends SelectionStatusDialog { private ILabelProvider fRenderer ; private boolean fIgnoreCase = true ; private boolean fIsMultipleSelection = false ; private boolean fMatchEmptyString = true ; private boolean fAllowDuplicates = true ; private Label fMessage ; protected FilteredList fFilteredList ; private Text fFilterText ; private ISelectionValidator fValidator ; private String fFilter = null ; private String fEmptyListMessage = "" ; private String fEmptySelectionMessage = "" ; private int fWidth = ; private int fHeight = ; private Object [ ] fSelection = new Object [ ] ; protected AbstractElementListSelectionDialog ( Shell parent , ILabelProvider renderer ) { super ( parent ) ; fRenderer = renderer ; int shellStyle = getShellStyle ( ) ; setShellStyle ( shellStyle | SWT . MAX | SWT . RESIZE ) ; } protected void handleDefaultSelected ( ) { if ( validateCurrentSelection ( ) ) buttonPressed ( IDialogConstants . OK_ID ) ; } public void setIgnoreCase ( boolean ignoreCase ) { fIgnoreCase = ignoreCase ; } public boolean isCaseIgnored ( ) { return fIgnoreCase ; } public void setMatchEmptyString ( boolean matchEmptyString ) { fMatchEmptyString = matchEmptyString ; } public void setMultipleSelection ( boolean multipleSelection ) { fIsMultipleSelection = multipleSelection ; } public void setAllowDuplicates ( boolean allowDuplicates ) { fAllowDuplicates = allowDuplicates ; } public void setSize ( int width , int height ) { fWidth = width ; fHeight = height ; } public void setEmptyListMessage ( String message ) { fEmptyListMessage = message ; } public void setEmptySelectionMessage ( String message ) { fEmptySelectionMessage = message ; } public void setValidator ( ISelectionValidator validator ) { fValidator = validator ; } protected void setListElements ( Object [ ] elements ) { Assert . isNotNull ( fFilteredList ) ; fFilteredList . setElements ( elements ) ; } public void setFilter ( String filter ) { if ( fFilterText == null ) fFilter = filter ; else fFilterText . setText ( filter ) ; } public String getFilter ( ) { if ( fFilteredList == null ) return fFilter ; return fFilteredList . getFilter ( ) ; } protected int [ ] getSelectionIndices ( ) { Assert . isNotNull ( fFilteredList ) ; return fFilteredList . getSelectionIndices ( ) ; } protected int getSelectionIndex ( ) { Assert . isNotNull ( fFilteredList ) ; return fFilteredList . getSelectionIndex ( ) ; } protected void setSelection ( Object [ ] selection ) { Assert . isNotNull ( fFilteredList ) ; fFilteredList . setSelection ( selection ) ; } protected Object [ ] getSelectedElements ( ) { Assert . isNotNull ( fFilteredList ) ; return fFilteredList . getSelection ( ) ; } public Object [ ] getFoldedElements ( int index ) { Assert . isNotNull ( fFilteredList ) ; return fFilteredList . getFoldedElements ( index ) ; } protected Label createMessageArea ( Composite composite ) { Label label = super . createMessageArea ( composite ) ; GridData data = new GridData ( ) ; data . grabExcessVerticalSpace = false ; data . grabExcessHorizontalSpace = true ; data . horizontalAlignment = GridData . FILL ; data . verticalAlignment = GridData . BEGINNING ; label . setLayoutData ( data ) ; fMessage = label ; return label ; } protected void handleSelectionChanged ( ) { validateCurrentSelection ( ) ; } protected boolean validateCurrentSelection ( ) { Assert . isNotNull ( fFilteredList ) ; IStatus status ; Object [ ] elements = getSelectedElements ( ) ; if ( elements . length > ) { if ( fValidator != null ) { status = fValidator . validate ( elements ) ; } else { status = new StatusInfo ( ) ; } } else { if ( fFilteredList . isEmpty ( ) ) { status = new StatusInfo ( IStatus . ERROR , fEmptyListMessage ) ; } else { status = new StatusInfo ( IStatus . ERROR , fEmptySelectionMessage ) ; } } updateStatus ( status ) ; return status . isOK ( ) ; } protected void cancelPressed ( ) { setResult ( null ) ; super . cancelPressed ( ) ; } protected FilteredList createFilteredList ( Composite parent ) { int flags = SWT . BORDER | SWT . V_SCROLL | SWT . H_SCROLL | ( fIsMultipleSelection ? SWT . MULTI : SWT . SINGLE ) ; FilteredList list = new FilteredList ( parent , flags , fRenderer , fIgnoreCase , fAllowDuplicates , fMatchEmptyString ) ; GridData data = new GridData ( ) ; data . widthHint = convertWidthInCharsToPixels ( fWidth ) ; data . heightHint = convertHeightInCharsToPixels ( fHeight ) ; data . grabExcessVerticalSpace = true ; data . grabExcessHorizontalSpace = true ; data . horizontalAlignment = GridData . FILL ; data . verticalAlignment = GridData . FILL ; list . setLayoutData ( data ) ; list . setFilter ( ( fFilter == null ? "" : fFilter ) ) ; list . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { handleDefaultSelected ( ) ; } public void widgetSelected ( SelectionEvent e ) { handleWidgetSelected ( ) ; } } ) ; fFilteredList = list ; return list ; } private void handleWidgetSelected ( ) { Object [ ] newSelection = fFilteredList . getSelection ( ) ; if ( newSelection . length != fSelection . length ) { fSelection = newSelection ; handleSelectionChanged ( ) ; } else { for ( int i = ; i != newSelection . length ; i ++ ) { if ( ! newSelection [ i ] . equals ( fSelection [ i ] ) ) { fSelection = newSelection ; handleSelectionChanged ( ) ; break ; } } } } protected Text createFilterText ( Composite parent ) { Text text = new Text ( parent , SWT . BORDER ) ; GridData data = new GridData ( ) ; data . grabExcessVerticalSpace = false ; data . grabExcessHorizontalSpace = true ; data . horizontalAlignment = GridData . FILL ; data . verticalAlignment = GridData . BEGINNING ; text . setLayoutData ( data ) ; text . setText ( ( fFilter == null ? "" : fFilter ) ) ; Listener listener = new Listener ( ) { public void handleEvent ( Event e ) { fFilteredList . setFilter ( fFilterText . getText ( ) ) ; } } ; text . addListener ( SWT . Modify , listener ) ; text . addKeyListener ( new KeyListener ( ) { public void keyPressed ( KeyEvent e ) { if ( e . keyCode == SWT . ARROW_DOWN ) fFilteredList . setFocus ( ) ; } public void keyReleased ( KeyEvent e ) { } } ) ; fFilterText = text ; return text ; } public int open ( ) { BusyIndicator . showWhile ( null , new Runnable ( ) { public void run ( ) { access$superOpen ( ) ; } } ) ; return getReturnCode ( ) ; } private void access$superOpen ( ) { super . open ( ) ; } public void create ( ) { super . create ( ) ; Assert . isNotNull ( fFilteredList ) ; if ( fFilteredList . isEmpty ( ) ) { handleEmptyList ( ) ; } else { validateCurrentSelection ( ) ; fFilterText . selectAll ( ) ; fFilterText . setFocus ( ) ; } } protected void handleEmptyList ( ) { fMessage . setEnabled ( false ) ; fFilterText . setEnabled ( false ) ; fFilteredList . setEnabled ( false ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTreeViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Tree ; import org . rubypeople . rdt . internal . ui . viewsupport . ContainerCheckedTreeViewer ; public class CheckedTreeSelectionDialog extends SelectionStatusDialog { private CheckboxTreeViewer fViewer ; private ILabelProvider fLabelProvider ; private ITreeContentProvider fContentProvider ; private ISelectionValidator fValidator = null ; private ViewerSorter fSorter ; private String fEmptyListMessage = "" ; private IStatus fCurrStatus = new StatusInfo ( ) ; private List fFilters ; private Object fInput ; private boolean fIsEmpty ; private int fWidth = ; private int fHeight = ; private boolean fContainerMode ; private Object [ ] fExpandedElements ; public CheckedTreeSelectionDialog ( Shell parent , ILabelProvider labelProvider , ITreeContentProvider contentProvider ) { super ( parent ) ; fLabelProvider = labelProvider ; fContentProvider = contentProvider ; setResult ( new ArrayList ( ) ) ; setStatusLineAboveButtons ( true ) ; fContainerMode = false ; fExpandedElements = null ; int shellStyle = getShellStyle ( ) ; setShellStyle ( shellStyle | SWT . MAX | SWT . RESIZE ) ; } public void setContainerMode ( boolean containerMode ) { fContainerMode = containerMode ; } public void setInitialSelection ( Object selection ) { setInitialSelections ( new Object [ ] { selection } ) ; } public void setEmptyListMessage ( String message ) { fEmptyListMessage = message ; } public void setSorter ( ViewerSorter sorter ) { fSorter = sorter ; } public void addFilter ( ViewerFilter filter ) { if ( fFilters == null ) fFilters = new ArrayList ( ) ; fFilters . add ( filter ) ; } public void setValidator ( ISelectionValidator validator ) { fValidator = validator ; } public void setInput ( Object input ) { fInput = input ; } public void setExpandedElements ( Object [ ] elements ) { fExpandedElements = elements ; } public void setSize ( int width , int height ) { fWidth = width ; fHeight = height ; } protected void updateOKStatus ( ) { if ( ! fIsEmpty ) { if ( fValidator != null ) { fCurrStatus = fValidator . validate ( fViewer . getCheckedElements ( ) ) ; updateStatus ( fCurrStatus ) ; } else if ( ! fCurrStatus . isOK ( ) ) { fCurrStatus = new StatusInfo ( ) ; } } else { fCurrStatus = new StatusInfo ( IStatus . ERROR , fEmptyListMessage ) ; } updateStatus ( fCurrStatus ) ; } public int open ( ) { fIsEmpty = evaluateIfTreeEmpty ( fInput ) ; BusyIndicator . showWhile ( null , new Runnable ( ) { public void run ( ) { access$superOpen ( ) ; } } ) ; return getReturnCode ( ) ; } private void access$superOpen ( ) { super . open ( ) ; } protected void cancelPressed ( ) { setResult ( null ) ; super . cancelPressed ( ) ; } protected void computeResult ( ) { setResult ( Arrays . asList ( fViewer . getCheckedElements ( ) ) ) ; } public void create ( ) { super . create ( ) ; List initialSelections = getInitialElementSelections ( ) ; if ( initialSelections != null ) { fViewer . setCheckedElements ( initialSelections . toArray ( ) ) ; } if ( fExpandedElements != null ) { fViewer . setExpandedElements ( fExpandedElements ) ; } updateOKStatus ( ) ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Label messageLabel = createMessageArea ( composite ) ; Control treeWidget = createTreeViewer ( composite ) ; Control buttonComposite = createSelectionButtons ( composite ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . widthHint = convertWidthInCharsToPixels ( fWidth ) ; data . heightHint = convertHeightInCharsToPixels ( fHeight ) ; treeWidget . setLayoutData ( data ) ; if ( fIsEmpty ) { messageLabel . setEnabled ( false ) ; treeWidget . setEnabled ( false ) ; buttonComposite . setEnabled ( false ) ; } return composite ; } private Tree createTreeViewer ( Composite parent ) { if ( fContainerMode ) { fViewer = new ContainerCheckedTreeViewer ( parent , SWT . BORDER ) ; } else { fViewer = new CheckboxTreeViewer ( parent , SWT . BORDER ) ; } fViewer . setContentProvider ( fContentProvider ) ; fViewer . setLabelProvider ( fLabelProvider ) ; fViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { updateOKStatus ( ) ; } } ) ; fViewer . setSorter ( fSorter ) ; if ( fFilters != null ) { for ( int i = ; i != fFilters . size ( ) ; i ++ ) fViewer . addFilter ( ( ViewerFilter ) fFilters . get ( i ) ) ; } fViewer . setInput ( fInput ) ; return fViewer . getTree ( ) ; } private Composite createSelectionButtons ( Composite composite ) { Composite buttonComposite = new Composite ( composite , SWT . RIGHT ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; buttonComposite . setLayout ( layout ) ; GridData data = new GridData ( GridData . HORIZONTAL_ALIGN_END | GridData . GRAB_HORIZONTAL ) ; data . grabExcessHorizontalSpace = true ; composite . setData ( data ) ; Button selectButton = createButton ( buttonComposite , IDialogConstants . SELECT_ALL_ID , "" , false ) ; SelectionListener listener = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fViewer . setCheckedElements ( fContentProvider . getElements ( fInput ) ) ; updateOKStatus ( ) ; } } ; selectButton . addSelectionListener ( listener ) ; Button deselectButton = createButton ( buttonComposite , IDialogConstants . DESELECT_ALL_ID , "" , false ) ; listener = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fViewer . setCheckedElements ( new Object [ ] ) ; updateOKStatus ( ) ; } } ; deselectButton . addSelectionListener ( listener ) ; return buttonComposite ; } private boolean evaluateIfTreeEmpty ( Object input ) { Object [ ] elements = fContentProvider . getElements ( input ) ; if ( elements . length > ) { if ( fFilters != null ) { for ( int i = ; i < fFilters . size ( ) ; i ++ ) { ViewerFilter curr = ( ViewerFilter ) fFilters . get ( i ) ; elements = curr . filter ( fViewer , input , elements ) ; } } } return elements . length == ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . DialogPage ; import org . eclipse . jface . dialogs . IMessageProvider ; public class StatusUtil { public static IStatus getMoreSevere ( IStatus s1 , IStatus s2 ) { if ( s1 . getSeverity ( ) > s2 . getSeverity ( ) ) { return s1 ; } return s2 ; } public static IStatus getMostSevere ( IStatus [ ] status ) { IStatus max = null ; for ( int i = ; i < status . length ; i ++ ) { IStatus curr = status [ i ] ; if ( curr . matches ( IStatus . ERROR ) ) { return curr ; } if ( max == null || curr . getSeverity ( ) > max . getSeverity ( ) ) { max = curr ; } } return max ; } public static void applyToStatusLine ( DialogPage page , IStatus status ) { String message = status . getMessage ( ) ; switch ( status . getSeverity ( ) ) { case IStatus . OK : page . setMessage ( message , IMessageProvider . NONE ) ; page . setErrorMessage ( null ) ; break ; case IStatus . WARNING : page . setMessage ( message , IMessageProvider . WARNING ) ; page . setErrorMessage ( null ) ; break ; case IStatus . INFO : page . setMessage ( message , IMessageProvider . INFORMATION ) ; page . setErrorMessage ( null ) ; break ; default : if ( message . length ( ) == ) { message = null ; } page . setMessage ( null ) ; page . setErrorMessage ( message ) ; break ; } } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import java . util . List ; import java . util . Arrays ; import org . eclipse . jface . viewers . ILabelProvider ; public class ElementListSelectionDialog extends AbstractElementListSelectionDialog { private Object [ ] fElements ; public ElementListSelectionDialog ( Shell parent , ILabelProvider renderer ) { super ( parent , renderer ) ; } public void setElements ( Object [ ] elements ) { fElements = elements ; } protected void computeResult ( ) { setResult ( Arrays . asList ( getSelectedElements ( ) ) ) ; } protected Control createDialogArea ( Composite parent ) { Composite contents = ( Composite ) super . createDialogArea ( parent ) ; createMessageArea ( contents ) ; createFilterText ( contents ) ; createFilteredList ( contents ) ; setListElements ( fElements ) ; List initialSelections = getInitialElementSelections ( ) ; if ( initialSelections != null ) setSelection ( initialSelections . toArray ( ) ) ; return contents ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . jface . dialogs . DialogSettings ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . ui . dialogs . TypeSelectionExtension ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class OpenTypeSelectionDialog2 extends TypeSelectionDialog2 { private IDialogSettings fSettings ; private Point fLocation ; private Point fSize ; private static final String DIALOG_SETTINGS = "" ; private static final String WIDTH = "" ; private static final String HEIGHT = "" ; public OpenTypeSelectionDialog2 ( Shell parent , boolean multi , IRunnableContext context , IRubySearchScope scope , int elementKinds ) { this ( parent , multi , context , scope , elementKinds , null ) ; } public OpenTypeSelectionDialog2 ( Shell parent , boolean multi , IRunnableContext context , IRubySearchScope scope , int elementKinds , TypeSelectionExtension extension ) { super ( parent , multi , context , scope , elementKinds , extension ) ; IDialogSettings settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; fSettings = settings . getSection ( DIALOG_SETTINGS ) ; if ( fSettings == null ) { fSettings = new DialogSettings ( DIALOG_SETTINGS ) ; settings . addSection ( fSettings ) ; fSettings . put ( WIDTH , ) ; fSettings . put ( HEIGHT , ) ; } } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( newShell , IRubyHelpContextIds . OPEN_TYPE_DIALOG ) ; } protected Point getInitialSize ( ) { Point result = super . getInitialSize ( ) ; if ( fSize != null ) { result . x = Math . max ( result . x , fSize . x ) ; result . y = Math . max ( result . y , fSize . y ) ; Rectangle display = getShell ( ) . getDisplay ( ) . getClientArea ( ) ; result . x = Math . min ( result . x , display . width ) ; result . y = Math . min ( result . y , display . height ) ; } return result ; } protected Point getInitialLocation ( Point initialSize ) { Point result = super . getInitialLocation ( initialSize ) ; if ( fLocation != null ) { result . x = fLocation . x ; result . y = fLocation . y ; Rectangle display = getShell ( ) . getDisplay ( ) . getClientArea ( ) ; int xe = result . x + initialSize . x ; if ( xe > display . width ) { result . x -= xe - display . width ; } int ye = result . y + initialSize . y ; if ( ye > display . height ) { result . y -= ye - display . height ; } } return result ; } protected Control createDialogArea ( Composite parent ) { readSettings ( ) ; return super . createDialogArea ( parent ) ; } public boolean close ( ) { writeSettings ( ) ; return super . close ( ) ; } private void readSettings ( ) { try { int x = fSettings . getInt ( "" ) ; int y = fSettings . getInt ( "" ) ; fLocation = new Point ( x , y ) ; } catch ( NumberFormatException e ) { fLocation = null ; } try { int width = fSettings . getInt ( "" ) ; int height = fSettings . getInt ( "" ) ; fSize = new Point ( width , height ) ; } catch ( NumberFormatException e ) { fSize = null ; } } private void writeSettings ( ) { Point location = getShell ( ) . getLocation ( ) ; fSettings . put ( "" , location . x ) ; fSettings . put ( "" , location . y ) ; Point size = getShell ( ) . getSize ( ) ; fSettings . put ( "" , size . x ) ; fSettings . put ( "" , size . y ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import java . text . BreakIterator ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . jface . bindings . TriggerSequence ; import org . eclipse . jface . bindings . keys . KeySequence ; import org . eclipse . jface . bindings . keys . SWTKeySupport ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . MouseAdapter ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . commands . ICommandService ; import org . eclipse . ui . contexts . IContextActivation ; import org . eclipse . ui . contexts . IContextService ; import org . eclipse . ui . handlers . IHandlerService ; import org . eclipse . ui . keys . IBindingService ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . RubyWordIterator ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class TextFieldNavigationHandler { public static void install ( Text text ) { if ( isSubWordNavigationEnabled ( ) ) new FocusHandler ( new TextNavigable ( text ) ) ; } public static void install ( StyledText styledText ) { if ( isSubWordNavigationEnabled ( ) ) new FocusHandler ( new StyledTextNavigable ( styledText ) ) ; } public static void install ( Combo combo ) { if ( isSubWordNavigationEnabled ( ) ) new FocusHandler ( new ComboNavigable ( combo ) ) ; } private static boolean isSubWordNavigationEnabled ( ) { IPreferenceStore preferenceStore = RubyPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; return preferenceStore . getBoolean ( PreferenceConstants . EDITOR_SUB_WORD_NAVIGATION ) ; } private abstract static class WorkaroundNavigable extends Navigable { Point fLastSelection ; int fCaretPosition ; void selectionChanged ( ) { Point selection = getSelection ( ) ; if ( selection . equals ( fLastSelection ) ) { } else if ( selection . x == selection . y ) { fCaretPosition = selection . x ; } else if ( fLastSelection . y == selection . y ) { fCaretPosition = selection . x ; } else { fCaretPosition = selection . y ; } fLastSelection = selection ; } } private abstract static class Navigable { public abstract Control getControl ( ) ; public abstract String getText ( ) ; public abstract void setText ( String text ) ; public abstract Point getSelection ( ) ; public abstract void setSelection ( int start , int end ) ; public abstract int getCaretPosition ( ) ; } private static class TextNavigable extends WorkaroundNavigable { static final boolean BUG_106024_TEXT_SELECTION = "" . equals ( SWT . getPlatform ( ) ) || "" . equals ( SWT . getPlatform ( ) ) ; private final Text fText ; public TextNavigable ( Text text ) { fText = text ; if ( BUG_106024_TEXT_SELECTION ) { fLastSelection = getSelection ( ) ; fCaretPosition = fLastSelection . y ; fText . addKeyListener ( new KeyAdapter ( ) { public void keyReleased ( KeyEvent e ) { selectionChanged ( ) ; } } ) ; fText . addMouseListener ( new MouseAdapter ( ) { public void mouseUp ( MouseEvent e ) { selectionChanged ( ) ; } } ) ; } } public Control getControl ( ) { return fText ; } public String getText ( ) { return fText . getText ( ) ; } public void setText ( String text ) { fText . setText ( text ) ; } public Point getSelection ( ) { return fText . getSelection ( ) ; } public int getCaretPosition ( ) { if ( BUG_106024_TEXT_SELECTION ) { selectionChanged ( ) ; return fCaretPosition ; } else { return fText . getCaretPosition ( ) ; } } public void setSelection ( int start , int end ) { fText . setSelection ( start , end ) ; } } private static class StyledTextNavigable extends Navigable { private final StyledText fStyledText ; public StyledTextNavigable ( StyledText styledText ) { fStyledText = styledText ; } public Control getControl ( ) { return fStyledText ; } public String getText ( ) { return fStyledText . getText ( ) ; } public void setText ( String text ) { fStyledText . setText ( text ) ; } public Point getSelection ( ) { return fStyledText . getSelection ( ) ; } public int getCaretPosition ( ) { return fStyledText . getCaretOffset ( ) ; } public void setSelection ( int start , int end ) { fStyledText . setSelection ( start , end ) ; } } private static class ComboNavigable extends WorkaroundNavigable { private final Combo fCombo ; public ComboNavigable ( Combo combo ) { fCombo = combo ; fLastSelection = getSelection ( ) ; fCaretPosition = fLastSelection . y ; fCombo . addKeyListener ( new KeyAdapter ( ) { public void keyReleased ( KeyEvent e ) { selectionChanged ( ) ; } } ) ; fCombo . addMouseListener ( new MouseAdapter ( ) { public void mouseUp ( MouseEvent e ) { selectionChanged ( ) ; } } ) ; } public Control getControl ( ) { return fCombo ; } public String getText ( ) { return fCombo . getText ( ) ; } public void setText ( String text ) { fCombo . setText ( text ) ; } public Point getSelection ( ) { return fCombo . getSelection ( ) ; } public int getCaretPosition ( ) { selectionChanged ( ) ; return fCaretPosition ; } public void setSelection ( int start , int end ) { fCombo . setSelection ( new Point ( start , end ) ) ; } } private static class FocusHandler implements FocusListener { private static final String EMPTY_TEXT = "" ; private final RubyWordIterator fIterator ; private final Navigable fNavigable ; private KeyAdapter fKeyListener ; private FocusHandler ( Navigable navigable ) { fIterator = new RubyWordIterator ( ) ; fNavigable = navigable ; Control control = navigable . getControl ( ) ; control . addFocusListener ( this ) ; if ( control . isFocusControl ( ) ) activate ( ) ; control . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { deactivate ( ) ; } } ) ; } public void focusGained ( FocusEvent e ) { activate ( ) ; } public void focusLost ( FocusEvent e ) { deactivate ( ) ; } private void activate ( ) { fNavigable . getControl ( ) . addKeyListener ( getKeyListener ( ) ) ; } private void deactivate ( ) { if ( fKeyListener != null ) { Control control = fNavigable . getControl ( ) ; if ( ! control . isDisposed ( ) ) control . removeKeyListener ( fKeyListener ) ; fKeyListener = null ; } } private KeyAdapter getKeyListener ( ) { if ( fKeyListener == null ) { fKeyListener = new KeyAdapter ( ) { private static final String TEXT_EDITOR_CONTEXT_ID = "" ; private final boolean IS_WORKAROUND = ( fNavigable instanceof ComboNavigable ) || ( fNavigable instanceof TextNavigable && TextNavigable . BUG_106024_TEXT_SELECTION ) ; private List fSubmissions ; public void keyPressed ( KeyEvent e ) { if ( IS_WORKAROUND ) { if ( e . keyCode == SWT . ARROW_LEFT && e . stateMask == SWT . MOD2 ) { int caretPosition = fNavigable . getCaretPosition ( ) ; if ( caretPosition != ) { Point selection = fNavigable . getSelection ( ) ; if ( caretPosition == selection . x ) fNavigable . setSelection ( selection . y , caretPosition - ) ; else fNavigable . setSelection ( selection . x , caretPosition - ) ; } e . doit = false ; return ; } else if ( e . keyCode == SWT . ARROW_RIGHT && e . stateMask == SWT . MOD2 ) { String text = fNavigable . getText ( ) ; int caretPosition = fNavigable . getCaretPosition ( ) ; if ( caretPosition != text . length ( ) ) { Point selection = fNavigable . getSelection ( ) ; if ( caretPosition == selection . y ) fNavigable . setSelection ( selection . x , caretPosition + ) ; else fNavigable . setSelection ( selection . y , caretPosition + ) ; } e . doit = false ; return ; } } int accelerator = SWTKeySupport . convertEventToUnmodifiedAccelerator ( e ) ; KeySequence keySequence = KeySequence . getInstance ( SWTKeySupport . convertAcceleratorToKeyStroke ( accelerator ) ) ; getSubmissions ( ) ; for ( Iterator iter = getSubmissions ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Submission submission = ( Submission ) iter . next ( ) ; TriggerSequence [ ] triggerSequences = submission . getTriggerSequences ( ) ; for ( int i = ; i < triggerSequences . length ; i ++ ) { if ( triggerSequences [ i ] . equals ( keySequence ) ) { e . doit = false ; submission . execute ( ) ; return ; } } } } private List getSubmissions ( ) { if ( fSubmissions != null ) return fSubmissions ; fSubmissions = new ArrayList ( ) ; IContextService contextService = ( IContextService ) PlatformUI . getWorkbench ( ) . getAdapter ( IContextService . class ) ; ICommandService commandService = ( ICommandService ) PlatformUI . getWorkbench ( ) . getAdapter ( ICommandService . class ) ; IHandlerService handlerService = ( IHandlerService ) PlatformUI . getWorkbench ( ) . getAdapter ( IHandlerService . class ) ; IBindingService bindingService = ( IBindingService ) PlatformUI . getWorkbench ( ) . getAdapter ( IBindingService . class ) ; if ( contextService == null || commandService == null || handlerService == null || bindingService == null ) return fSubmissions ; IContextActivation [ ] contextActivations ; contextActivations = new IContextActivation [ ] { contextService . activateContext ( IContextService . CONTEXT_ID_WINDOW ) , contextService . activateContext ( TEXT_EDITOR_CONTEXT_ID ) } ; fSubmissions . add ( new Submission ( bindingService . getActiveBindingsFor ( ITextEditorActionDefinitionIds . SELECT_WORD_NEXT ) ) { public void execute ( ) { fIterator . setText ( fNavigable . getText ( ) ) ; int caretPosition = fNavigable . getCaretPosition ( ) ; int newCaret = fIterator . following ( caretPosition ) ; if ( newCaret != BreakIterator . DONE ) { Point selection = fNavigable . getSelection ( ) ; if ( caretPosition == selection . y ) fNavigable . setSelection ( selection . x , newCaret ) ; else fNavigable . setSelection ( selection . y , newCaret ) ; } fIterator . setText ( EMPTY_TEXT ) ; } } ) ; fSubmissions . add ( new Submission ( bindingService . getActiveBindingsFor ( ITextEditorActionDefinitionIds . SELECT_WORD_PREVIOUS ) ) { public void execute ( ) { fIterator . setText ( fNavigable . getText ( ) ) ; int caretPosition = fNavigable . getCaretPosition ( ) ; int newCaret = fIterator . preceding ( caretPosition ) ; if ( newCaret != BreakIterator . DONE ) { Point selection = fNavigable . getSelection ( ) ; if ( caretPosition == selection . x ) fNavigable . setSelection ( selection . y , newCaret ) ; else fNavigable . setSelection ( selection . x , newCaret ) ; } fIterator . setText ( EMPTY_TEXT ) ; } } ) ; fSubmissions . add ( new Submission ( bindingService . getActiveBindingsFor ( ITextEditorActionDefinitionIds . WORD_NEXT ) ) { public void execute ( ) { fIterator . setText ( fNavigable . getText ( ) ) ; int caretPosition = fNavigable . getCaretPosition ( ) ; int newCaret = fIterator . following ( caretPosition ) ; if ( newCaret != BreakIterator . DONE ) fNavigable . setSelection ( newCaret , newCaret ) ; fIterator . setText ( EMPTY_TEXT ) ; } } ) ; fSubmissions . add ( new Submission ( bindingService . getActiveBindingsFor ( ITextEditorActionDefinitionIds . WORD_PREVIOUS ) ) { public void execute ( ) { fIterator . setText ( fNavigable . getText ( ) ) ; int caretPosition = fNavigable . getCaretPosition ( ) ; int newCaret = fIterator . preceding ( caretPosition ) ; if ( newCaret != BreakIterator . DONE ) fNavigable . setSelection ( newCaret , newCaret ) ; fIterator . setText ( EMPTY_TEXT ) ; } } ) ; fSubmissions . add ( new Submission ( bindingService . getActiveBindingsFor ( ITextEditorActionDefinitionIds . DELETE_NEXT_WORD ) ) { public void execute ( ) { Point selection = fNavigable . getSelection ( ) ; String text = fNavigable . getText ( ) ; int start ; int end ; if ( selection . x != selection . y ) { start = selection . x ; end = selection . y ; } else { fIterator . setText ( text ) ; start = fNavigable . getCaretPosition ( ) ; end = fIterator . following ( start ) ; fIterator . setText ( EMPTY_TEXT ) ; if ( end == BreakIterator . DONE ) return ; } fNavigable . setText ( text . substring ( , start ) + text . substring ( end ) ) ; fNavigable . setSelection ( start , start ) ; } } ) ; fSubmissions . add ( new Submission ( bindingService . getActiveBindingsFor ( ITextEditorActionDefinitionIds . DELETE_PREVIOUS_WORD ) ) { public void execute ( ) { Point selection = fNavigable . getSelection ( ) ; String text = fNavigable . getText ( ) ; int start ; int end ; if ( selection . x != selection . y ) { start = selection . x ; end = selection . y ; } else { fIterator . setText ( text ) ; end = fNavigable . getCaretPosition ( ) ; start = fIterator . preceding ( end ) ; fIterator . setText ( EMPTY_TEXT ) ; if ( start == BreakIterator . DONE ) return ; } fNavigable . setText ( text . substring ( , start ) + text . substring ( end ) ) ; fNavigable . setSelection ( start , start ) ; } } ) ; for ( int i = ; i < contextActivations . length ; i ++ ) { contextService . deactivateContext ( contextActivations [ i ] ) ; } return fSubmissions ; } } ; } return fKeyListener ; } } private abstract static class Submission { private TriggerSequence [ ] fTriggerSequences ; public Submission ( TriggerSequence [ ] triggerSequences ) { fTriggerSequences = triggerSequences ; } public TriggerSequence [ ] getTriggerSequences ( ) { return fTriggerSequences ; } public abstract void execute ( ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; public abstract class StatusDialog extends Dialog { private Button fOkButton ; private MessageLine fStatusLine ; private IStatus fLastStatus ; private String fTitle ; private Image fImage ; public StatusDialog ( Shell parent ) { super ( parent ) ; } public void setStatusLineAboveButtons ( boolean aboveButtons ) { } protected void updateStatus ( IStatus status ) { fLastStatus = status ; if ( fStatusLine != null && ! fStatusLine . isDisposed ( ) ) { updateButtonsEnableState ( status ) ; fStatusLine . setErrorStatus ( status ) ; } } public IStatus getStatus ( ) { return fLastStatus ; } protected void updateButtonsEnableState ( IStatus status ) { if ( fOkButton != null && ! fOkButton . isDisposed ( ) ) fOkButton . setEnabled ( ! status . matches ( IStatus . ERROR ) ) ; } protected void configureShell ( Shell shell ) { super . configureShell ( shell ) ; if ( fTitle != null ) shell . setText ( fTitle ) ; } public void create ( ) { super . create ( ) ; if ( fLastStatus != null ) { if ( fLastStatus . matches ( IStatus . ERROR ) ) { StatusInfo status = new StatusInfo ( ) ; status . setError ( "" ) ; fLastStatus = status ; } updateStatus ( fLastStatus ) ; } } protected void createButtonsForButtonBar ( Composite parent ) { fOkButton = createButton ( parent , IDialogConstants . OK_ID , IDialogConstants . OK_LABEL , true ) ; createButton ( parent , IDialogConstants . CANCEL_ID , IDialogConstants . CANCEL_LABEL , false ) ; } protected Control createButtonBar ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginHeight = ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; composite . setLayout ( layout ) ; composite . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fStatusLine = new MessageLine ( composite ) ; fStatusLine . setAlignment ( SWT . LEFT ) ; fStatusLine . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fStatusLine . setErrorStatus ( null ) ; super . createButtonBar ( composite ) ; return composite ; } public void setTitle ( String title ) { fTitle = title != null ? title : "" ; Shell shell = getShell ( ) ; if ( ( shell != null ) && ! shell . isDisposed ( ) ) shell . setText ( fTitle ) ; } public void setImage ( Image image ) { fImage = image ; Shell shell = getShell ( ) ; if ( ( shell != null ) && ! shell . isDisposed ( ) ) shell . setImage ( fImage ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CLabel ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class MessageLine extends CLabel { private Color fNormalMsgAreaBackground ; private Color fErrorMsgAreaBackground ; public MessageLine ( Composite parent ) { this ( parent , SWT . LEFT ) ; } public void setErrorBackground ( Color color ) { fErrorMsgAreaBackground = color ; } public MessageLine ( Composite parent , int style ) { super ( parent , style ) ; fNormalMsgAreaBackground = getBackground ( ) ; fErrorMsgAreaBackground = null ; } private Image findImage ( IStatus status ) { if ( status . isOK ( ) ) { return null ; } else if ( status . matches ( IStatus . ERROR ) ) { return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_ERROR ) ; } else if ( status . matches ( IStatus . WARNING ) ) { return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_WARNING ) ; } else if ( status . matches ( IStatus . INFO ) ) { return RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_INFO ) ; } return null ; } public void setErrorStatus ( IStatus status ) { if ( status != null ) { String message = status . getMessage ( ) ; if ( message != null && message . length ( ) > ) { setText ( message ) ; setImage ( findImage ( status ) ) ; if ( fErrorMsgAreaBackground == null ) { setBackground ( fNormalMsgAreaBackground ) ; } else { setBackground ( fErrorMsgAreaBackground ) ; } return ; } } setText ( "" ) ; setImage ( null ) ; setBackground ( fNormalMsgAreaBackground ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; public class OptionalMessageDialog extends MessageDialog { private static final String CHECKBOX_TEXT = RubyUIMessages . OptionalMessageDialog_dontShowAgain ; private static final String STORE_ID = "" ; public static final int NOT_SHOWN = IDialogConstants . CLIENT_ID + ; private Button fHideDialogCheckBox ; private String fId ; public static int open ( String id , Shell parent , String title , Image titleImage , String message , int dialogType , String [ ] buttonLabels , int defaultButtonIndex ) { if ( ! isDialogEnabled ( id ) ) return OptionalMessageDialog . NOT_SHOWN ; MessageDialog dialog = new OptionalMessageDialog ( id , parent , title , titleImage , message , dialogType , buttonLabels , defaultButtonIndex ) ; return dialog . open ( ) ; } protected OptionalMessageDialog ( String id , Shell parent , String title , Image titleImage , String message , int dialogType , String [ ] buttonLabels , int defaultButtonIndex ) { super ( parent , title , titleImage , message , dialogType , buttonLabels , defaultButtonIndex ) ; fId = id ; } protected Control createCustomArea ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = convertVerticalDLUsToPixels ( IDialogConstants . VERTICAL_MARGIN ) ; layout . marginWidth = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_MARGIN ) ; layout . horizontalSpacing = convertHorizontalDLUsToPixels ( IDialogConstants . HORIZONTAL_SPACING ) ; composite . setLayout ( layout ) ; composite . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; fHideDialogCheckBox = new Button ( composite , SWT . CHECK | SWT . LEFT ) ; fHideDialogCheckBox . setText ( CHECKBOX_TEXT ) ; fHideDialogCheckBox . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { setDialogEnabled ( fId , ! ( ( Button ) e . widget ) . getSelection ( ) ) ; } } ) ; applyDialogFont ( fHideDialogCheckBox ) ; return fHideDialogCheckBox ; } private static IDialogSettings getDialogSettings ( ) { IDialogSettings settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; settings = settings . getSection ( STORE_ID ) ; if ( settings == null ) settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( STORE_ID ) ; return settings ; } public static boolean isDialogEnabled ( String key ) { IDialogSettings settings = getDialogSettings ( ) ; return ! settings . getBoolean ( key ) ; } public static void setDialogEnabled ( String key , boolean isEnabled ) { IDialogSettings settings = getDialogSettings ( ) ; settings . put ( key , ! isEnabled ) ; } public static void clearAllRememberedStates ( ) { IDialogSettings settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) ; settings . addNewSection ( STORE_ID ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Comparator ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . ProgressMonitorWrapper ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ControlAdapter ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . MenuAdapter ; import org . eclipse . swt . events . MenuEvent ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . core . search . TypeNameRequestor ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . corext . util . OpenTypeHistory ; import org . rubypeople . rdt . internal . corext . util . Strings ; import org . rubypeople . rdt . internal . corext . util . TypeFilter ; import org . rubypeople . rdt . internal . corext . util . TypeInfo ; import org . rubypeople . rdt . internal . corext . util . TypeInfoFactory ; import org . rubypeople . rdt . internal . corext . util . TypeInfoFilter ; import org . rubypeople . rdt . internal . corext . util . UnresolvableTypeInfo ; import org . rubypeople . rdt . internal . corext . util . TypeInfo . TypeInfoAdapter ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . dialogs . ITypeInfoFilterExtension ; import org . rubypeople . rdt . ui . dialogs . ITypeInfoImageProvider ; public class TypeInfoViewer { private static class SearchRequestor extends TypeNameRequestor { private volatile boolean fStop ; private Set fHistory ; private TypeInfoFilter fFilter ; private TypeInfoFactory fFactory = new TypeInfoFactory ( ) ; private List fResult ; public SearchRequestor ( TypeInfoFilter filter ) { super ( ) ; fResult = new ArrayList ( ) ; fFilter = filter ; } public TypeInfo [ ] getResult ( ) { return ( TypeInfo [ ] ) fResult . toArray ( new TypeInfo [ fResult . size ( ) ] ) ; } public void cancel ( ) { fStop = true ; } public void setHistory ( Set history ) { fHistory = history ; } public void acceptType ( boolean isModule , char [ ] packageName , char [ ] simpleTypeName , char [ ] [ ] enclosingTypeNames , String path ) { if ( fStop ) return ; if ( TypeFilter . isFiltered ( packageName , simpleTypeName ) ) return ; TypeInfo type = fFactory . create ( packageName , simpleTypeName , enclosingTypeNames , isModule , path ) ; if ( fHistory . contains ( type ) ) return ; if ( fFilter . matchesFilterExtension ( type ) ) fResult . add ( type ) ; } } protected static class TypeInfoComparator implements Comparator { private TypeInfoLabelProvider fLabelProvider ; private TypeInfoFilter fFilter ; public TypeInfoComparator ( TypeInfoLabelProvider labelProvider , TypeInfoFilter filter ) { fLabelProvider = labelProvider ; fFilter = filter ; } public int compare ( Object left , Object right ) { TypeInfo leftInfo = ( TypeInfo ) left ; TypeInfo rightInfo = ( TypeInfo ) right ; int leftCategory = getCamelCaseCategory ( leftInfo ) ; int rightCategory = getCamelCaseCategory ( rightInfo ) ; if ( leftCategory < rightCategory ) return - ; if ( leftCategory > rightCategory ) return + ; int result = compareName ( leftInfo . getTypeName ( ) , rightInfo . getTypeName ( ) ) ; if ( result != ) return result ; result = compareTypeContainerName ( leftInfo . getTypeContainerName ( ) , rightInfo . getTypeContainerName ( ) ) ; if ( result != ) return result ; leftCategory = getElementTypeCategory ( leftInfo ) ; rightCategory = getElementTypeCategory ( rightInfo ) ; if ( leftCategory < rightCategory ) return - ; if ( leftCategory > rightCategory ) return + ; return compareContainerName ( leftInfo , rightInfo ) ; } private int compareName ( String leftString , String rightString ) { int result = leftString . compareToIgnoreCase ( rightString ) ; if ( result != ) { return result ; } else if ( Strings . isLowerCase ( leftString . charAt ( ) ) && ! Strings . isLowerCase ( rightString . charAt ( ) ) ) { return + ; } else if ( Strings . isLowerCase ( rightString . charAt ( ) ) && ! Strings . isLowerCase ( leftString . charAt ( ) ) ) { return - ; } else { return leftString . compareTo ( rightString ) ; } } private int compareTypeContainerName ( String leftString , String rightString ) { int leftLength = leftString . length ( ) ; int rightLength = rightString . length ( ) ; if ( leftLength == && rightLength > ) return - ; if ( leftLength == && rightLength == ) return ; if ( leftLength > && rightLength == ) return + ; return compareName ( leftString , rightString ) ; } private int compareContainerName ( TypeInfo leftType , TypeInfo rightType ) { return fLabelProvider . getContainerName ( leftType ) . compareTo ( fLabelProvider . getContainerName ( rightType ) ) ; } private int getCamelCaseCategory ( TypeInfo type ) { if ( fFilter == null ) return ; if ( ! fFilter . isCamelCasePattern ( ) ) return ; return fFilter . matchesRawNamePattern ( type ) ? : ; } private int getElementTypeCategory ( TypeInfo type ) { if ( type . getElementType ( ) == TypeInfo . IFILE_TYPE_INFO ) return ; if ( type . getElementType ( ) == TypeInfo . JAR_FILE_ENTRY_TYPE_INFO ) return ; return ; } } protected static class TypeInfoLabelProvider { private ITypeInfoImageProvider fProviderExtension ; private TypeInfoAdapter fAdapter = new TypeInfoAdapter ( ) ; private Map fLib2Name = new HashMap ( ) ; private String [ ] fInstallLocations ; private String [ ] fVMNames ; private boolean fFullyQualifyDuplicates ; public TypeInfoLabelProvider ( ITypeInfoImageProvider extension ) { fProviderExtension = extension ; List locations = new ArrayList ( ) ; List labels = new ArrayList ( ) ; IVMInstallType [ ] installs = RubyRuntime . getVMInstallTypes ( ) ; for ( int i = ; i < installs . length ; i ++ ) { processVMInstallType ( installs [ i ] , locations , labels ) ; } fInstallLocations = ( String [ ] ) locations . toArray ( new String [ locations . size ( ) ] ) ; fVMNames = ( String [ ] ) labels . toArray ( new String [ labels . size ( ) ] ) ; } public void setFullyQualifyDuplicates ( boolean value ) { fFullyQualifyDuplicates = value ; } private void processVMInstallType ( IVMInstallType installType , List locations , List labels ) { if ( installType != null ) { IVMInstall [ ] installs = installType . getVMInstalls ( ) ; boolean isMac = Platform . OS_MACOSX . equals ( Platform . getOS ( ) ) ; final String HOME_SUFFIX = "" ; for ( int i = ; i < installs . length ; i ++ ) { String label = getFormattedLabel ( installs [ i ] . getName ( ) ) ; IPath [ ] libLocations = installs [ i ] . getLibraryLocations ( ) ; if ( libLocations != null ) { processLibraryLocation ( libLocations , label ) ; } else { String filePath = installs [ i ] . getInstallLocation ( ) . getAbsolutePath ( ) ; if ( isMac && filePath . endsWith ( HOME_SUFFIX ) ) filePath = filePath . substring ( , filePath . length ( ) - HOME_SUFFIX . length ( ) + ) ; locations . add ( filePath ) ; labels . add ( label ) ; } } } } private void processLibraryLocation ( IPath [ ] libLocations , String label ) { for ( int l = ; l < libLocations . length ; l ++ ) { IPath location = libLocations [ l ] ; fLib2Name . put ( location . toString ( ) , label ) ; } } private String getFormattedLabel ( String name ) { return Messages . format ( RubyUIMessages . TypeInfoViewer_library_name_format , name ) ; } public String getText ( Object element ) { return ( ( TypeInfo ) element ) . getTypeName ( ) ; } public String getQualifiedText ( TypeInfo type ) { StringBuffer result = new StringBuffer ( ) ; result . append ( type . getTypeName ( ) ) ; String containerName = type . getTypeContainerName ( ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; if ( containerName . length ( ) > ) { result . append ( containerName ) ; } else { result . append ( RubyUIMessages . TypeInfoViewer_default_package ) ; } return result . toString ( ) ; } public String getFullyQualifiedText ( TypeInfo type ) { StringBuffer result = new StringBuffer ( ) ; result . append ( type . getTypeName ( ) ) ; String containerName = type . getTypeContainerName ( ) ; if ( containerName . length ( ) > ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( containerName ) ; } result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( getContainerName ( type ) ) ; return result . toString ( ) ; } public String getText ( TypeInfo last , TypeInfo current , TypeInfo next ) { StringBuffer result = new StringBuffer ( ) ; int qualifications = ; String currentTN = current . getTypeName ( ) ; result . append ( currentTN ) ; String currentTCN = getTypeContainerName ( current ) ; if ( last != null ) { String lastTN = last . getTypeName ( ) ; String lastTCN = getTypeContainerName ( last ) ; if ( currentTCN . equals ( lastTCN ) ) { if ( currentTN . equals ( lastTN ) ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( currentTCN ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( getContainerName ( current ) ) ; return result . toString ( ) ; } } else if ( currentTN . equals ( lastTN ) ) { qualifications = ; } } if ( next != null ) { String nextTN = next . getTypeName ( ) ; String nextTCN = getTypeContainerName ( next ) ; if ( currentTCN . equals ( nextTCN ) ) { if ( currentTN . equals ( nextTN ) ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( currentTCN ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( getContainerName ( current ) ) ; return result . toString ( ) ; } } else if ( currentTN . equals ( nextTN ) ) { qualifications = ; } } if ( qualifications > ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( currentTCN ) ; if ( fFullyQualifyDuplicates ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( getContainerName ( current ) ) ; } } return result . toString ( ) ; } public String getQualificationText ( TypeInfo type ) { StringBuffer result = new StringBuffer ( ) ; String containerName = type . getTypeContainerName ( ) ; if ( containerName . length ( ) > ) { result . append ( containerName ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; } result . append ( getContainerName ( type ) ) ; return result . toString ( ) ; } public ImageDescriptor getImageDescriptor ( Object element ) { TypeInfo type = ( TypeInfo ) element ; if ( fProviderExtension != null ) { fAdapter . setInfo ( type ) ; ImageDescriptor descriptor = fProviderExtension . getImageDescriptor ( fAdapter ) ; if ( descriptor != null ) return descriptor ; } return RubyElementImageProvider . getTypeImageDescriptor ( type . isModule ( ) , type . isInnerType ( ) , false ) ; } private String getTypeContainerName ( TypeInfo info ) { String result = info . getTypeContainerName ( ) ; if ( result . length ( ) > ) return result ; return RubyUIMessages . TypeInfoViewer_default_package ; } private String getContainerName ( TypeInfo type ) { String name = type . getPackageFragmentRootName ( ) ; for ( int i = ; i < fInstallLocations . length ; i ++ ) { if ( name . startsWith ( fInstallLocations [ i ] ) ) { return fVMNames [ i ] ; } } String lib = ( String ) fLib2Name . get ( name ) ; if ( lib != null ) return lib ; return name ; } } private static class ProgressUpdateJob extends UIJob { private TypeInfoViewer fViewer ; private boolean fStopped ; public ProgressUpdateJob ( Display display , TypeInfoViewer viewer ) { super ( display , RubyUIMessages . TypeInfoViewer_progressJob_label ) ; fViewer = viewer ; } public void stop ( ) { fStopped = true ; cancel ( ) ; } public IStatus runInUIThread ( IProgressMonitor monitor ) { if ( stopped ( ) ) return new Status ( IStatus . CANCEL , RubyPlugin . getPluginId ( ) , IStatus . CANCEL , "" , null ) ; fViewer . updateProgressMessage ( ) ; if ( ! stopped ( ) ) schedule ( ) ; return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } private boolean stopped ( ) { return fStopped || fViewer . getTable ( ) . isDisposed ( ) ; } } private static class ProgressMonitor extends ProgressMonitorWrapper { private TypeInfoViewer fViewer ; private String fName ; private int fTotalWork ; private double fWorked ; private boolean fDone ; public ProgressMonitor ( IProgressMonitor monitor , TypeInfoViewer viewer ) { super ( monitor ) ; fViewer = viewer ; } public void setTaskName ( String name ) { super . setTaskName ( name ) ; fName = name ; } public void beginTask ( String name , int totalWork ) { super . beginTask ( name , totalWork ) ; if ( fName == null ) fName = name ; fTotalWork = totalWork ; } public void worked ( int work ) { super . worked ( work ) ; internalWorked ( work ) ; } public void done ( ) { fDone = true ; fViewer . setProgressMessage ( "" ) ; super . done ( ) ; } public void internalWorked ( double work ) { fWorked = fWorked + work ; fViewer . setProgressMessage ( getMessage ( ) ) ; } private String getMessage ( ) { if ( fDone ) { return "" ; } else if ( fTotalWork == ) { return fName ; } else { return Messages . format ( RubyUIMessages . TypeInfoViewer_progress_label , new Object [ ] { fName , new Integer ( ( int ) ( ( fWorked * ) / fTotalWork ) ) } ) ; } } } private static abstract class AbstractJob extends Job { protected TypeInfoViewer fViewer ; protected AbstractJob ( String name , TypeInfoViewer viewer ) { super ( name ) ; fViewer = viewer ; setSystem ( true ) ; } protected final IStatus run ( IProgressMonitor parent ) { ProgressMonitor monitor = new ProgressMonitor ( parent , fViewer ) ; try { fViewer . scheduleProgressUpdateJob ( ) ; return doRun ( monitor ) ; } finally { fViewer . stopProgressUpdateJob ( ) ; } } protected abstract IStatus doRun ( ProgressMonitor monitor ) ; } private static abstract class AbstractSearchJob extends AbstractJob { private int fMode ; protected int fTicket ; protected TypeInfoLabelProvider fLabelProvider ; protected TypeInfoFilter fFilter ; protected OpenTypeHistory fHistory ; protected AbstractSearchJob ( int ticket , TypeInfoViewer viewer , TypeInfoFilter filter , OpenTypeHistory history , int numberOfVisibleItems , int mode ) { super ( RubyUIMessages . TypeInfoViewer_job_label , viewer ) ; fMode = mode ; fTicket = ticket ; fViewer = viewer ; fLabelProvider = fViewer . getLabelProvider ( ) ; fFilter = filter ; fHistory = history ; } public void stop ( ) { cancel ( ) ; } protected IStatus doRun ( ProgressMonitor monitor ) { try { if ( VIRTUAL ) { internalRunVirtual ( monitor ) ; } else { internalRun ( monitor ) ; } } catch ( CoreException e ) { fViewer . searchJobFailed ( fTicket , e ) ; return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . ERROR , RubyUIMessages . TypeInfoViewer_job_error , e ) ; } catch ( InterruptedException e ) { return canceled ( e , true ) ; } catch ( OperationCanceledException e ) { return canceled ( e , false ) ; } fViewer . searchJobDone ( fTicket ) ; return ok ( ) ; } protected abstract TypeInfo [ ] getSearchResult ( Set filteredHistory , ProgressMonitor monitor ) throws CoreException ; private void internalRun ( ProgressMonitor monitor ) throws CoreException , InterruptedException { if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; fViewer . clear ( fTicket ) ; TypeInfo last = null ; TypeInfo type = null ; TypeInfo next = null ; List elements = new ArrayList ( ) ; List imageDescriptors = new ArrayList ( ) ; List labels = new ArrayList ( ) ; Set filteredHistory = new HashSet ( ) ; TypeInfo [ ] matchingTypes = fHistory . getFilteredTypeInfos ( fFilter ) ; if ( matchingTypes . length > ) { Arrays . sort ( matchingTypes , new TypeInfoComparator ( fLabelProvider , fFilter ) ) ; type = matchingTypes [ ] ; int i = ; while ( type != null ) { next = ( i == matchingTypes . length ) ? null : matchingTypes [ i ] ; filteredHistory . add ( type ) ; elements . add ( type ) ; imageDescriptors . add ( fLabelProvider . getImageDescriptor ( type ) ) ; labels . add ( fLabelProvider . getText ( last , type , next ) ) ; last = type ; type = next ; i ++ ; } } matchingTypes = null ; fViewer . fExpectedItemCount = elements . size ( ) ; fViewer . addHistory ( fTicket , elements , imageDescriptors , labels ) ; if ( ( fMode & INDEX ) == ) { return ; } TypeInfo [ ] result = getSearchResult ( filteredHistory , monitor ) ; fViewer . fExpectedItemCount += result . length ; if ( result . length == ) { return ; } if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; int processed = ; int nextIndex = ; type = result [ ] ; if ( filteredHistory . size ( ) > ) { fViewer . addDashLineAndUpdateLastHistoryEntry ( fTicket , type ) ; } while ( true ) { long startTime = System . currentTimeMillis ( ) ; elements . clear ( ) ; imageDescriptors . clear ( ) ; labels . clear ( ) ; int delta = Math . min ( nextIndex == ? fViewer . getNumberOfVisibleItems ( ) : , result . length - processed ) ; if ( delta == ) break ; processed = processed + delta ; while ( delta > ) { next = ( nextIndex == result . length ) ? null : result [ nextIndex ] ; elements . add ( type ) ; labels . add ( fLabelProvider . getText ( last , type , next ) ) ; imageDescriptors . add ( fLabelProvider . getImageDescriptor ( type ) ) ; last = type ; type = next ; nextIndex ++ ; delta -- ; } fViewer . addAll ( fTicket , elements , imageDescriptors , labels ) ; long sleep = - ( System . currentTimeMillis ( ) - startTime ) ; if ( false ) System . out . println ( "" + sleep ) ; if ( sleep > ) Thread . sleep ( sleep ) ; if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; } } private void internalRunVirtual ( ProgressMonitor monitor ) throws CoreException , InterruptedException { if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; fViewer . clear ( fTicket ) ; TypeInfo [ ] matchingTypes = fHistory . getFilteredTypeInfos ( fFilter ) ; fViewer . setHistoryResult ( fTicket , matchingTypes ) ; if ( ( fMode & INDEX ) == ) return ; TypeInfo [ ] result = getSearchResult ( new HashSet ( Arrays . asList ( matchingTypes ) ) , monitor ) ; if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; fViewer . setSearchResult ( fTicket , result ) ; } private IStatus canceled ( Exception e , boolean removePendingItems ) { fViewer . searchJobCanceled ( fTicket , removePendingItems ) ; return new Status ( IStatus . CANCEL , RubyPlugin . getPluginId ( ) , IStatus . CANCEL , RubyUIMessages . TypeInfoViewer_job_cancel , e ) ; } private IStatus ok ( ) { return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } } private static class SearchEngineJob extends AbstractSearchJob { private IRubySearchScope fScope ; private int fElementKind ; private SearchRequestor fReqestor ; public SearchEngineJob ( int ticket , TypeInfoViewer viewer , TypeInfoFilter filter , OpenTypeHistory history , int numberOfVisibleItems , int mode , IRubySearchScope scope , int elementKind ) { super ( ticket , viewer , filter , history , numberOfVisibleItems , mode ) ; fScope = scope ; fElementKind = elementKind ; fReqestor = new SearchRequestor ( filter ) ; } public void stop ( ) { fReqestor . cancel ( ) ; super . stop ( ) ; } protected TypeInfo [ ] getSearchResult ( Set filteredHistory , ProgressMonitor monitor ) throws CoreException { long start = System . currentTimeMillis ( ) ; fReqestor . setHistory ( filteredHistory ) ; SearchEngine engine = new SearchEngine ( ( WorkingCopyOwner ) null ) ; String packPattern = fFilter . getPackagePattern ( ) ; monitor . setTaskName ( RubyUIMessages . TypeInfoViewer_searchJob_taskName ) ; engine . searchAllTypeNames ( packPattern == null ? null : packPattern . toCharArray ( ) , fFilter . getNamePattern ( ) . toCharArray ( ) , fFilter . getSearchFlags ( ) , fElementKind , fScope , fReqestor , IRubySearchConstants . WAIT_UNTIL_READY_TO_SEARCH , monitor ) ; if ( DEBUG ) System . out . println ( "" + ( System . currentTimeMillis ( ) - start ) ) ; TypeInfo [ ] result = fReqestor . getResult ( ) ; Arrays . sort ( result , new TypeInfoComparator ( fLabelProvider , fFilter ) ) ; if ( DEBUG ) System . out . println ( "" + ( System . currentTimeMillis ( ) - start ) ) ; fViewer . rememberResult ( fTicket , result ) ; return result ; } } private static class CachedResultJob extends AbstractSearchJob { private TypeInfo [ ] fLastResult ; public CachedResultJob ( int ticket , TypeInfo [ ] lastResult , TypeInfoViewer viewer , TypeInfoFilter filter , OpenTypeHistory history , int numberOfVisibleItems , int mode ) { super ( ticket , viewer , filter , history , numberOfVisibleItems , mode ) ; fLastResult = lastResult ; } protected TypeInfo [ ] getSearchResult ( Set filteredHistory , ProgressMonitor monitor ) throws CoreException { List result = new ArrayList ( ) ; for ( int i = ; i < fLastResult . length ; i ++ ) { TypeInfo type = fLastResult [ i ] ; if ( filteredHistory . contains ( type ) ) continue ; if ( fFilter . matchesCachedResult ( type ) ) result . add ( type ) ; } TypeInfo [ ] types = ( TypeInfo [ ] ) result . toArray ( new TypeInfo [ result . size ( ) ] ) ; if ( fFilter . isCamelCasePattern ( ) ) { Arrays . sort ( types , new TypeInfoComparator ( fLabelProvider , fFilter ) ) ; } return types ; } } private static class SyncJob extends AbstractJob { public SyncJob ( TypeInfoViewer viewer ) { super ( RubyUIMessages . TypeInfoViewer_syncJob_label , viewer ) ; } public void stop ( ) { cancel ( ) ; } protected IStatus doRun ( ProgressMonitor monitor ) { try { monitor . setTaskName ( RubyUIMessages . TypeInfoViewer_syncJob_taskName ) ; new SearchEngine ( ) . searchAllTypeNames ( null , "" . toCharArray ( ) , SearchPattern . R_EXACT_MATCH | SearchPattern . R_CASE_SENSITIVE , IRubySearchConstants . MODULE , SearchEngine . createWorkspaceScope ( ) , new TypeNameRequestor ( ) { } , IRubySearchConstants . WAIT_UNTIL_READY_TO_SEARCH , monitor ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; return new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . ERROR , RubyUIMessages . TypeInfoViewer_job_error , e ) ; } catch ( OperationCanceledException e ) { return new Status ( IStatus . CANCEL , RubyPlugin . getPluginId ( ) , IStatus . CANCEL , RubyUIMessages . TypeInfoViewer_job_cancel , e ) ; } finally { fViewer . syncJobDone ( ) ; } return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } } private static class DashLine { private int fSeparatorWidth ; private String fMessage ; private int fMessageLength ; public String getText ( int width ) { StringBuffer dashes = new StringBuffer ( ) ; int chars = ( ( ( width - fMessageLength ) / fSeparatorWidth ) / ) - ; for ( int i = ; i < chars ; i ++ ) { dashes . append ( SEPARATOR ) ; } StringBuffer result = new StringBuffer ( ) ; result . append ( dashes ) ; result . append ( fMessage ) ; result . append ( dashes ) ; return result . toString ( ) ; } public void initialize ( GC gc ) { fSeparatorWidth = gc . getAdvanceWidth ( SEPARATOR ) ; fMessage = "" + RubyUIMessages . TypeInfoViewer_separator_message + "" ; fMessageLength = gc . textExtent ( fMessage ) . x ; } } private static class ImageManager { private Map fImages = new HashMap ( ) ; public Image get ( ImageDescriptor descriptor ) { if ( descriptor == null ) descriptor = ImageDescriptor . getMissingImageDescriptor ( ) ; Image result = ( Image ) fImages . get ( descriptor ) ; if ( result != null ) return result ; result = descriptor . createImage ( ) ; if ( result != null ) fImages . put ( descriptor , result ) ; return result ; } public void dispose ( ) { for ( Iterator iter = fImages . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Image image = ( Image ) iter . next ( ) ; image . dispose ( ) ; } fImages . clear ( ) ; } } private Display fDisplay ; private String fProgressMessage ; private Label fProgressLabel ; private int fProgressCounter ; private ProgressUpdateJob fProgressUpdateJob ; private OpenTypeHistory fHistory ; private int fNextElement ; private List fItems ; private TypeInfo [ ] fHistoryMatches ; private TypeInfo [ ] fSearchMatches ; private int fNumberOfVisibleItems ; private int fExpectedItemCount ; private Color fDashLineColor ; private int fScrollbarWidth ; private int fTableWidthDelta ; private int fDashLineIndex = - ; private Image fSeparatorIcon ; private DashLine fDashLine = new DashLine ( ) ; private boolean fFullyQualifySelection ; private TableItem [ ] fLastSelection ; private String [ ] fLastLabels ; private TypeInfoLabelProvider fLabelProvider ; private ImageManager fImageManager ; private Table fTable ; private SyncJob fSyncJob ; private TypeInfoFilter fTypeInfoFilter ; private ITypeInfoFilterExtension fFilterExtension ; private TypeInfo [ ] fLastCompletedResult ; private TypeInfoFilter fLastCompletedFilter ; private int fSearchJobTicket ; protected int fElementKind ; protected IRubySearchScope fSearchScope ; private AbstractSearchJob fSearchJob ; private static final int HISTORY = ; private static final int INDEX = ; private static final int FULL = HISTORY | INDEX ; private static final char SEPARATOR = '' ; private static final boolean DEBUG = false ; private static final boolean VIRTUAL = false ; private static final TypeInfo [ ] EMTPY_TYPE_INFO_ARRAY = new TypeInfo [ ] ; private static final TypeInfo DASH_LINE = new UnresolvableTypeInfo ( null , null , null , false , null ) ; public TypeInfoViewer ( Composite parent , int flags , Label progressLabel , IRubySearchScope scope , int elementKind , String initialFilter , ITypeInfoFilterExtension filterExtension , ITypeInfoImageProvider imageExtension ) { Assert . isNotNull ( scope ) ; fDisplay = parent . getDisplay ( ) ; fProgressLabel = progressLabel ; fSearchScope = scope ; fElementKind = elementKind ; fFilterExtension = filterExtension ; fFullyQualifySelection = ( flags & SWT . MULTI ) != ; fTable = new Table ( parent , SWT . V_SCROLL | SWT . H_SCROLL | SWT . BORDER | SWT . FLAT | flags | ( VIRTUAL ? SWT . VIRTUAL : SWT . NONE ) ) ; fTable . setFont ( parent . getFont ( ) ) ; fLabelProvider = new TypeInfoLabelProvider ( imageExtension ) ; fItems = new ArrayList ( ) ; fTable . setHeaderVisible ( false ) ; addPopupMenu ( ) ; fTable . addControlListener ( new ControlAdapter ( ) { public void controlResized ( ControlEvent event ) { int itemHeight = fTable . getItemHeight ( ) ; Rectangle clientArea = fTable . getClientArea ( ) ; fNumberOfVisibleItems = ( clientArea . height / itemHeight ) + ; } } ) ; fTable . addKeyListener ( new KeyAdapter ( ) { public void keyPressed ( KeyEvent e ) { if ( e . keyCode == SWT . DEL ) { deleteHistoryEntry ( ) ; } else if ( e . keyCode == SWT . ARROW_DOWN ) { int index = fTable . getSelectionIndex ( ) ; if ( index == fDashLineIndex - ) { e . doit = false ; setTableSelection ( index + ) ; } } else if ( e . keyCode == SWT . ARROW_UP ) { int index = fTable . getSelectionIndex ( ) ; if ( fDashLineIndex != - && index == fDashLineIndex + ) { e . doit = false ; setTableSelection ( index - ) ; } } } } ) ; fTable . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { if ( fLastSelection != null ) { for ( int i = ; i < fLastSelection . length ; i ++ ) { TableItem item = fLastSelection [ i ] ; if ( ! item . isDisposed ( ) ) item . setText ( fLastLabels [ i ] ) ; } } TableItem [ ] items = fTable . getSelection ( ) ; fLastSelection = new TableItem [ items . length ] ; fLastLabels = new String [ items . length ] ; for ( int i = ; i < items . length ; i ++ ) { TableItem item = items [ i ] ; fLastSelection [ i ] = item ; fLastLabels [ i ] = item . getText ( ) ; Object data = item . getData ( ) ; if ( data instanceof TypeInfo ) { String qualifiedText = getQualifiedText ( ( TypeInfo ) data ) ; if ( qualifiedText . length ( ) > fLastLabels [ i ] . length ( ) ) item . setText ( qualifiedText ) ; } } } } ) ; fTable . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { stop ( true , true ) ; fDashLineColor . dispose ( ) ; fSeparatorIcon . dispose ( ) ; fImageManager . dispose ( ) ; if ( fProgressUpdateJob != null ) { fProgressUpdateJob . stop ( ) ; fProgressUpdateJob = null ; } } } ) ; if ( VIRTUAL ) { fHistoryMatches = EMTPY_TYPE_INFO_ARRAY ; fSearchMatches = EMTPY_TYPE_INFO_ARRAY ; fTable . addListener ( SWT . SetData , new Listener ( ) { public void handleEvent ( Event event ) { TableItem item = ( TableItem ) event . item ; setData ( item ) ; } } ) ; } fDashLineColor = computeDashLineColor ( ) ; fScrollbarWidth = computeScrollBarWidth ( ) ; fTableWidthDelta = fTable . computeTrim ( , , , ) . width - fScrollbarWidth ; fSeparatorIcon = RubyPluginImages . DESC_OBJS_TYPE_SEPARATOR . createImage ( fTable . getDisplay ( ) ) ; fImageManager = new ImageManager ( ) ; fHistory = OpenTypeHistory . getInstance ( ) ; if ( initialFilter != null && initialFilter . length ( ) > ) fTypeInfoFilter = createTypeInfoFilter ( initialFilter ) ; GC gc = null ; try { gc = new GC ( fTable ) ; gc . setFont ( fTable . getFont ( ) ) ; fDashLine . initialize ( gc ) ; } finally { gc . dispose ( ) ; } if ( fTypeInfoFilter == null ) { scheduleSyncJob ( ) ; } } void startup ( ) { if ( fTypeInfoFilter == null ) { reset ( ) ; } else { scheduleSearchJob ( FULL ) ; } } public Table getTable ( ) { return fTable ; } TypeInfoLabelProvider getLabelProvider ( ) { return fLabelProvider ; } private int getNumberOfVisibleItems ( ) { return fNumberOfVisibleItems ; } public void setFocus ( ) { fTable . setFocus ( ) ; } public void setQualificationStyle ( boolean value ) { if ( fFullyQualifySelection == value ) return ; fFullyQualifySelection = value ; if ( fLastSelection != null ) { for ( int i = ; i < fLastSelection . length ; i ++ ) { TableItem item = fLastSelection [ i ] ; Object data = item . getData ( ) ; if ( data instanceof TypeInfo ) { item . setText ( getQualifiedText ( ( TypeInfo ) data ) ) ; } } } } public TypeInfo [ ] getSelection ( ) { TableItem [ ] items = fTable . getSelection ( ) ; List result = new ArrayList ( items . length ) ; for ( int i = ; i < items . length ; i ++ ) { Object data = items [ i ] . getData ( ) ; if ( data instanceof TypeInfo ) { result . add ( data ) ; } } return ( TypeInfo [ ] ) result . toArray ( new TypeInfo [ result . size ( ) ] ) ; } public void stop ( ) { stop ( true , false ) ; } public void stop ( boolean stopSyncJob , boolean dispose ) { if ( fSyncJob != null && stopSyncJob ) { fSyncJob . stop ( ) ; fSyncJob = null ; } if ( fSearchJob != null ) { fSearchJob . stop ( ) ; fSearchJob = null ; } } public void forceSearch ( ) { stop ( false , false ) ; if ( fTypeInfoFilter == null ) { reset ( ) ; } else { fLastCompletedFilter = null ; fLastCompletedResult = null ; scheduleSearchJob ( isSyncJobRunning ( ) ? HISTORY : FULL ) ; } } public void setSearchPattern ( String text ) { stop ( false , false ) ; if ( text . length ( ) == || "" . equals ( text ) ) { fTypeInfoFilter = null ; reset ( ) ; } else { fTypeInfoFilter = createTypeInfoFilter ( text ) ; scheduleSearchJob ( isSyncJobRunning ( ) ? HISTORY : FULL ) ; } } public void setSearchScope ( IRubySearchScope scope , boolean refresh ) { fSearchScope = scope ; if ( ! refresh ) return ; stop ( false , false ) ; fLastCompletedFilter = null ; fLastCompletedResult = null ; if ( fTypeInfoFilter == null ) { reset ( ) ; } else { scheduleSearchJob ( isSyncJobRunning ( ) ? HISTORY : FULL ) ; } } public void setFullyQualifyDuplicates ( boolean value , boolean refresh ) { fLabelProvider . setFullyQualifyDuplicates ( value ) ; if ( ! refresh ) return ; stop ( false , false ) ; if ( fTypeInfoFilter == null ) { reset ( ) ; } else { scheduleSearchJob ( isSyncJobRunning ( ) ? HISTORY : FULL ) ; } } public void reset ( ) { fLastSelection = null ; fLastLabels = null ; fExpectedItemCount = ; fDashLineIndex = - ; TypeInfoFilter filter = ( fTypeInfoFilter != null ) ? fTypeInfoFilter : new TypeInfoFilter ( "" , fSearchScope , fElementKind , fFilterExtension ) ; if ( VIRTUAL ) { fHistoryMatches = fHistory . getFilteredTypeInfos ( filter ) ; fExpectedItemCount = fHistoryMatches . length ; fTable . setItemCount ( fHistoryMatches . length ) ; if ( fHistoryMatches . length == ) { fTable . redraw ( ) ; } fTable . clear ( , fHistoryMatches . length - ) ; } else { fNextElement = ; TypeInfo [ ] historyItems = fHistory . getFilteredTypeInfos ( filter ) ; if ( historyItems . length == ) { shortenTable ( ) ; return ; } fExpectedItemCount = historyItems . length ; int lastIndex = historyItems . length - ; TypeInfo last = null ; TypeInfo type = historyItems [ ] ; for ( int i = ; i < historyItems . length ; i ++ ) { TypeInfo next = i == lastIndex ? null : historyItems [ i + ] ; addSingleElement ( type , fLabelProvider . getImageDescriptor ( type ) , fLabelProvider . getText ( last , type , next ) ) ; last = type ; type = next ; } shortenTable ( ) ; } } protected TypeInfoFilter createTypeInfoFilter ( String text ) { if ( "" . equals ( text ) ) text = "" ; return new TypeInfoFilter ( text , fSearchScope , fElementKind , fFilterExtension ) ; } private void addPopupMenu ( ) { Menu menu = new Menu ( fTable . getShell ( ) , SWT . POP_UP ) ; fTable . setMenu ( menu ) ; final MenuItem remove = new MenuItem ( menu , SWT . NONE ) ; remove . setText ( RubyUIMessages . TypeInfoViewer_remove_from_history ) ; menu . addMenuListener ( new MenuAdapter ( ) { public void menuShown ( MenuEvent e ) { TableItem [ ] selection = fTable . getSelection ( ) ; remove . setEnabled ( canEnable ( selection ) ) ; } } ) ; remove . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { deleteHistoryEntry ( ) ; } } ) ; } private boolean canEnable ( TableItem [ ] selection ) { if ( selection . length == ) return false ; for ( int i = ; i < selection . length ; i ++ ) { TableItem item = selection [ i ] ; Object data = item . getData ( ) ; if ( ! ( data instanceof TypeInfo ) ) return false ; if ( ! ( fHistory . contains ( ( TypeInfo ) data ) ) ) return false ; } return true ; } private void deleteHistoryEntry ( ) { int index = fTable . getSelectionIndex ( ) ; if ( index == - ) return ; TableItem item = fTable . getItem ( index ) ; Object element = item . getData ( ) ; if ( ! ( element instanceof TypeInfo ) ) return ; if ( fHistory . remove ( ( TypeInfo ) element ) != null ) { item . dispose ( ) ; fItems . remove ( index ) ; int count = fTable . getItemCount ( ) ; if ( count > ) { item = fTable . getItem ( ) ; if ( item . getData ( ) instanceof DashLine ) { item . dispose ( ) ; fItems . remove ( ) ; fDashLineIndex = - ; if ( count > ) { setTableSelection ( ) ; } } else { if ( index >= count ) { index = count - ; } setTableSelection ( index ) ; } } else { fTable . notifyListeners ( SWT . Selection , new Event ( ) ) ; } } } private void clear ( int ticket ) { syncExec ( ticket , new Runnable ( ) { public void run ( ) { fNextElement = ; fDashLineIndex = - ; fLastSelection = null ; fLastLabels = null ; fExpectedItemCount = ; } } ) ; } private void rememberResult ( int ticket , final TypeInfo [ ] result ) { syncExec ( ticket , new Runnable ( ) { public void run ( ) { if ( fLastCompletedResult == null ) { fLastCompletedFilter = fTypeInfoFilter ; fLastCompletedResult = result ; } } } ) ; } private void addHistory ( int ticket , final List elements , final List imageDescriptors , final List labels ) { addAll ( ticket , elements , imageDescriptors , labels ) ; } private void addAll ( int ticket , final List elements , final List imageDescriptors , final List labels ) { syncExec ( ticket , new Runnable ( ) { public void run ( ) { int size = elements . size ( ) ; for ( int i = ; i < size ; i ++ ) { addSingleElement ( elements . get ( i ) , ( ImageDescriptor ) imageDescriptors . get ( i ) , ( String ) labels . get ( i ) ) ; } } } ) ; } private void addDashLineAndUpdateLastHistoryEntry ( int ticket , final TypeInfo next ) { syncExec ( ticket , new Runnable ( ) { public void run ( ) { if ( fNextElement > ) { TableItem item = fTable . getItem ( fNextElement - ) ; String label = item . getText ( ) ; String newLabel = fLabelProvider . getText ( null , ( TypeInfo ) item . getData ( ) , next ) ; if ( newLabel . length ( ) > label . length ( ) ) item . setText ( newLabel ) ; if ( fLastSelection != null && fLastSelection . length > ) { TableItem last = fLastSelection [ fLastSelection . length - ] ; if ( last == item ) { fLastLabels [ fLastLabels . length - ] = newLabel ; } } } fDashLineIndex = fNextElement ; addDashLine ( ) ; } } ) ; } private void addDashLine ( ) { TableItem item = null ; if ( fItems . size ( ) > fNextElement ) { item = ( TableItem ) fItems . get ( fNextElement ) ; } else { item = new TableItem ( fTable , SWT . NONE ) ; fItems . add ( item ) ; } fillDashLine ( item ) ; fNextElement ++ ; } private void addSingleElement ( Object element , ImageDescriptor imageDescriptor , String label ) { TableItem item = null ; Object old = null ; if ( fItems . size ( ) > fNextElement ) { item = ( TableItem ) fItems . get ( fNextElement ) ; old = item . getData ( ) ; item . setForeground ( null ) ; } else { item = new TableItem ( fTable , SWT . NONE ) ; fItems . add ( item ) ; } item . setData ( element ) ; item . setImage ( fImageManager . get ( imageDescriptor ) ) ; if ( fNextElement == ) { if ( needsSelectionChange ( old , element ) || fLastSelection != null ) { item . setText ( label ) ; fTable . setSelection ( ) ; fTable . notifyListeners ( SWT . Selection , new Event ( ) ) ; } else { fLastSelection = new TableItem [ ] { item } ; fLastLabels = new String [ ] { label } ; } } else { item . setText ( label ) ; } fNextElement ++ ; } private boolean needsSelectionChange ( Object oldElement , Object newElement ) { int [ ] selected = fTable . getSelectionIndices ( ) ; if ( selected . length != ) return true ; if ( selected [ ] != ) return true ; if ( oldElement == null ) return true ; return ! oldElement . equals ( newElement ) ; } private void scheduleSearchJob ( int mode ) { fSearchJobTicket ++ ; if ( fLastCompletedFilter != null && fTypeInfoFilter . isSubFilter ( fLastCompletedFilter . getText ( ) ) ) { fSearchJob = new CachedResultJob ( fSearchJobTicket , fLastCompletedResult , this , fTypeInfoFilter , fHistory , fNumberOfVisibleItems , mode ) ; } else { fLastCompletedFilter = null ; fLastCompletedResult = null ; fSearchJob = new SearchEngineJob ( fSearchJobTicket , this , fTypeInfoFilter , fHistory , fNumberOfVisibleItems , mode , fSearchScope , fElementKind ) ; } fSearchJob . schedule ( ) ; } private void searchJobDone ( int ticket ) { syncExec ( ticket , new Runnable ( ) { public void run ( ) { shortenTable ( ) ; checkEmptyList ( ) ; fSearchJob = null ; } } ) ; } private void searchJobCanceled ( int ticket , final boolean removePendingItems ) { syncExec ( ticket , new Runnable ( ) { public void run ( ) { if ( removePendingItems ) { shortenTable ( ) ; checkEmptyList ( ) ; } fSearchJob = null ; } } ) ; } private synchronized void searchJobFailed ( int ticket , CoreException e ) { searchJobDone ( ticket ) ; RubyPlugin . log ( e ) ; } private void setHistoryResult ( int ticket , final TypeInfo [ ] types ) { syncExec ( ticket , new Runnable ( ) { public void run ( ) { fExpectedItemCount = types . length ; int lastHistoryLength = fHistoryMatches . length ; fHistoryMatches = types ; int length = fHistoryMatches . length + fSearchMatches . length ; int dash = ( fHistoryMatches . length > && fSearchMatches . length > ) ? : ; fTable . setItemCount ( length + dash ) ; if ( length == ) { fTable . redraw ( ) ; return ; } int update = Math . max ( lastHistoryLength , fHistoryMatches . length ) ; if ( update > ) { fTable . clear ( , update + dash - ) ; } } } ) ; } private void setSearchResult ( int ticket , final TypeInfo [ ] types ) { syncExec ( ticket , new Runnable ( ) { public void run ( ) { fExpectedItemCount += types . length ; fSearchMatches = types ; int length = fHistoryMatches . length + fSearchMatches . length ; int dash = ( fHistoryMatches . length > && fSearchMatches . length > ) ? : ; fTable . setItemCount ( length + dash ) ; if ( length == ) { fTable . redraw ( ) ; return ; } if ( fHistoryMatches . length == ) { fTable . clear ( , length + dash - ) ; } else { fTable . clear ( fHistoryMatches . length - , length + dash - ) ; } } } ) ; } private void setData ( TableItem item ) { int index = fTable . indexOf ( item ) ; TypeInfo type = getTypeInfo ( index ) ; if ( type == DASH_LINE ) { item . setData ( fDashLine ) ; fillDashLine ( item ) ; } else { item . setData ( type ) ; item . setImage ( fImageManager . get ( fLabelProvider . getImageDescriptor ( type ) ) ) ; item . setText ( fLabelProvider . getText ( getTypeInfo ( index - ) , type , getTypeInfo ( index + ) ) ) ; item . setForeground ( null ) ; } } private TypeInfo getTypeInfo ( int index ) { if ( index < ) return null ; if ( index < fHistoryMatches . length ) { return fHistoryMatches [ index ] ; } int dash = ( fHistoryMatches . length > && fSearchMatches . length > ) ? : ; if ( index == fHistoryMatches . length && dash == ) { return DASH_LINE ; } index = index - fHistoryMatches . length - dash ; if ( index >= fSearchMatches . length ) return null ; return fSearchMatches [ index ] ; } private void scheduleSyncJob ( ) { fSyncJob = new SyncJob ( this ) ; fSyncJob . schedule ( ) ; } private void syncJobDone ( ) { syncExec ( new Runnable ( ) { public void run ( ) { fSyncJob = null ; if ( fTypeInfoFilter != null ) { scheduleSearchJob ( FULL ) ; } } } ) ; } private boolean isSyncJobRunning ( ) { return fSyncJob != null ; } private void scheduleProgressUpdateJob ( ) { syncExec ( new Runnable ( ) { public void run ( ) { if ( fProgressCounter == ) { clearProgressMessage ( ) ; fProgressUpdateJob = new ProgressUpdateJob ( fDisplay , TypeInfoViewer . this ) ; fProgressUpdateJob . schedule ( ) ; } fProgressCounter ++ ; } } ) ; } private void stopProgressUpdateJob ( ) { syncExec ( new Runnable ( ) { public void run ( ) { fProgressCounter -- ; if ( fProgressCounter == && fProgressUpdateJob != null ) { fProgressUpdateJob . stop ( ) ; fProgressUpdateJob = null ; clearProgressMessage ( ) ; } } } ) ; } private void setProgressMessage ( String message ) { fProgressMessage = message ; } private void clearProgressMessage ( ) { fProgressMessage = "" ; fProgressLabel . setText ( fProgressMessage ) ; } private void updateProgressMessage ( ) { fProgressLabel . setText ( fProgressMessage ) ; } private void syncExec ( final Runnable runnable ) { if ( fDisplay . isDisposed ( ) ) return ; fDisplay . syncExec ( new Runnable ( ) { public void run ( ) { if ( fTable . isDisposed ( ) ) return ; runnable . run ( ) ; } } ) ; } private void syncExec ( final int ticket , final Runnable runnable ) { if ( fDisplay . isDisposed ( ) ) return ; fDisplay . syncExec ( new Runnable ( ) { public void run ( ) { if ( fTable . isDisposed ( ) || ticket != fSearchJobTicket ) return ; runnable . run ( ) ; } } ) ; } private void fillDashLine ( TableItem item ) { Rectangle bounds = item . getImageBounds ( ) ; Rectangle area = fTable . getBounds ( ) ; boolean willHaveScrollBar = fExpectedItemCount + > fNumberOfVisibleItems ; item . setText ( fDashLine . getText ( area . width - bounds . x - bounds . width - fTableWidthDelta - ( willHaveScrollBar ? fScrollbarWidth : ) ) ) ; item . setImage ( fSeparatorIcon ) ; item . setForeground ( fDashLineColor ) ; item . setData ( fDashLine ) ; } private void shortenTable ( ) { if ( VIRTUAL ) return ; if ( fNextElement < fItems . size ( ) ) { fTable . setRedraw ( false ) ; fTable . remove ( fNextElement , fItems . size ( ) - ) ; fTable . setRedraw ( true ) ; } for ( int i = fItems . size ( ) - ; i >= fNextElement ; i -- ) { fItems . remove ( i ) ; } } private void checkEmptyList ( ) { if ( fTable . getItemCount ( ) == ) { fTable . notifyListeners ( SWT . Selection , new Event ( ) ) ; } } private void setTableSelection ( int index ) { fTable . setSelection ( index ) ; fTable . notifyListeners ( SWT . Selection , new Event ( ) ) ; } private Color computeDashLineColor ( ) { Color fg = fTable . getForeground ( ) ; int fGray = ( int ) ( * fg . getRed ( ) + * fg . getGreen ( ) + * fg . getBlue ( ) ) ; Color bg = fTable . getBackground ( ) ; int bGray = ( int ) ( * bg . getRed ( ) + * bg . getGreen ( ) + * bg . getBlue ( ) ) ; int gray = ( int ) ( ( fGray + bGray ) * ) ; return new Color ( fDisplay , gray , gray , gray ) ; } private int computeScrollBarWidth ( ) { Composite t = new Composite ( fTable . getShell ( ) , SWT . V_SCROLL ) ; int result = t . computeTrim ( , , , ) . width ; t . dispose ( ) ; return result ; } private String getQualifiedText ( TypeInfo type ) { return fFullyQualifySelection ? fLabelProvider . getFullyQualifiedText ( type ) : fLabelProvider . getQualifiedText ( type ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . IJobManager ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . ISelectionStatusValidator ; import org . eclipse . ui . dialogs . SelectionStatusDialog ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . core . search . TypeNameRequestor ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . corext . util . OpenTypeHistory ; import org . rubypeople . rdt . internal . corext . util . TypeInfo ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . dialogs . TypeSelectionExtension ; public class TypeSelectionDialog2 extends SelectionStatusDialog { private String fTitle ; private boolean fMultipleSelection ; private IRunnableContext fRunnableContext ; private IRubySearchScope fScope ; private int fElementKind ; private String fInitialFilter ; private int fSelectionMode ; private ISelectionStatusValidator fValidator ; private TypeSelectionComponent fContent ; private TypeSelectionExtension fExtension ; public static final int NONE = TypeSelectionComponent . NONE ; public static final int CARET_BEGINNING = TypeSelectionComponent . CARET_BEGINNING ; public static final int FULL_SELECTION = TypeSelectionComponent . FULL_SELECTION ; private static boolean fgFirstTime = true ; private class TitleLabel implements TypeSelectionComponent . ITitleLabel { public void setText ( String text ) { if ( text == null || text . length ( ) == ) { getShell ( ) . setText ( fTitle ) ; } else { getShell ( ) . setText ( Messages . format ( RubyUIMessages . TypeSelectionDialog2_title_format , new String [ ] { fTitle , text } ) ) ; } } } public TypeSelectionDialog2 ( Shell parent , boolean multi , IRunnableContext context , IRubySearchScope scope , int elementKinds ) { this ( parent , multi , context , scope , elementKinds , null ) ; } public TypeSelectionDialog2 ( Shell parent , boolean multi , IRunnableContext context , IRubySearchScope scope , int elementKinds , TypeSelectionExtension extension ) { super ( parent ) ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; fMultipleSelection = multi ; fRunnableContext = context ; fScope = scope ; fElementKind = elementKinds ; fSelectionMode = NONE ; fExtension = extension ; if ( fExtension != null ) { fValidator = fExtension . getSelectionValidator ( ) ; } } public void setFilter ( String filter ) { setFilter ( filter , FULL_SELECTION ) ; } public void setFilter ( String filter , int selectionMode ) { fInitialFilter = filter ; fSelectionMode = selectionMode ; } public void setValidator ( ISelectionStatusValidator validator ) { fValidator = validator ; } protected TypeInfo [ ] getSelectedTypes ( ) { if ( fContent == null || fContent . isDisposed ( ) ) return null ; return fContent . getSelection ( ) ; } public void create ( ) { super . create ( ) ; fContent . populate ( fSelectionMode ) ; getOkButton ( ) . setEnabled ( fContent . getSelection ( ) . length > ) ; } protected void configureShell ( Shell shell ) { super . configureShell ( shell ) ; } protected Control createDialogArea ( Composite parent ) { Composite area = ( Composite ) super . createDialogArea ( parent ) ; fContent = new TypeSelectionComponent ( area , SWT . NONE , getMessage ( ) , fMultipleSelection , fScope , fElementKind , fInitialFilter , new TitleLabel ( ) , fExtension ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; fContent . setLayoutData ( gd ) ; fContent . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { handleDefaultSelected ( fContent . getSelection ( ) ) ; } public void widgetSelected ( SelectionEvent e ) { handleWidgetSelected ( fContent . getSelection ( ) ) ; } } ) ; return area ; } protected void handleDefaultSelected ( TypeInfo [ ] selection ) { if ( selection . length == ) return ; okPressed ( ) ; } protected void handleWidgetSelected ( TypeInfo [ ] selection ) { IStatus status = null ; if ( selection . length == ) { status = new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . ERROR , "" , null ) ; } else { try { if ( fValidator != null ) { List jElements = new ArrayList ( ) ; for ( int i = ; i < selection . length ; i ++ ) { IType type = selection [ i ] . resolveType ( fScope ) ; if ( type != null ) { jElements . add ( type ) ; } else { status = new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . ERROR , Messages . format ( RubyUIMessages . TypeSelectionDialog_error_type_doesnot_exist , selection [ i ] . getFullyQualifiedName ( ) ) , null ) ; break ; } } if ( status == null ) { status = fValidator . validate ( jElements . toArray ( ) ) ; } } else { status = new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } } catch ( RubyModelException e ) { status = new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . ERROR , e . getStatus ( ) . getMessage ( ) , null ) ; } } updateStatus ( status ) ; } public int open ( ) { try { ensureConsistency ( ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , RubyUIMessages . TypeSelectionDialog_error3Title , RubyUIMessages . TypeSelectionDialog_error3Message ) ; return CANCEL ; } catch ( InterruptedException e ) { return CANCEL ; } if ( fInitialFilter == null ) { IWorkbenchWindow window = RubyPlugin . getActiveWorkbenchWindow ( ) ; if ( window != null ) { ISelection selection = window . getSelectionService ( ) . getSelection ( ) ; if ( selection instanceof ITextSelection ) { String text = ( ( ITextSelection ) selection ) . getText ( ) ; if ( text != null ) { text = text . trim ( ) ; if ( text . length ( ) > && RubyConventions . validateRubyTypeName ( text ) . isOK ( ) ) { fInitialFilter = text ; fSelectionMode = FULL_SELECTION ; } } } } } return super . open ( ) ; } public boolean close ( ) { boolean result ; try { if ( getReturnCode ( ) == OK ) { OpenTypeHistory . getInstance ( ) . save ( ) ; } } finally { result = super . close ( ) ; } return result ; } public void setTitle ( String title ) { super . setTitle ( title ) ; fTitle = title ; } protected void computeResult ( ) { TypeInfo [ ] selected = fContent . getSelection ( ) ; if ( selected == null || selected . length == ) { setResult ( null ) ; return ; } if ( fScope == null ) { fScope = fContent . getScope ( ) ; } OpenTypeHistory history = OpenTypeHistory . getInstance ( ) ; List result = new ArrayList ( selected . length ) ; for ( int i = ; i < selected . length ; i ++ ) { try { TypeInfo typeInfo = selected [ i ] ; IType type = typeInfo . resolveType ( fScope ) ; if ( type == null ) { String title = RubyUIMessages . TypeSelectionDialog_errorTitle ; String message = Messages . format ( RubyUIMessages . TypeSelectionDialog_dialogMessage , typeInfo . getPath ( ) ) ; MessageDialog . openError ( getShell ( ) , title , message ) ; history . remove ( typeInfo ) ; setResult ( null ) ; } else { history . accessed ( typeInfo ) ; result . add ( type ) ; } } catch ( RubyModelException e ) { String title = RubyUIMessages . MultiTypeSelectionDialog_errorTitle ; String message = RubyUIMessages . MultiTypeSelectionDialog_errorMessage ; ErrorDialog . openError ( getShell ( ) , title , message , e . getStatus ( ) ) ; } } setResult ( result ) ; } private void ensureConsistency ( ) throws InvocationTargetException , InterruptedException { class ConsistencyRunnable implements IRunnableWithProgress { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { if ( fgFirstTime ) { IJobManager manager = Platform . getJobManager ( ) ; manager . join ( RubyUI . ID_PLUGIN , monitor ) ; } OpenTypeHistory history = OpenTypeHistory . getInstance ( ) ; if ( fgFirstTime || history . isEmpty ( ) ) { monitor . beginTask ( RubyUIMessages . TypeSelectionDialog_progress_consistency , ) ; if ( history . needConsistencyCheck ( ) ) { refreshSearchIndices ( new SubProgressMonitor ( monitor , ) ) ; history . checkConsistency ( new SubProgressMonitor ( monitor , ) ) ; } else { refreshSearchIndices ( monitor ) ; } monitor . done ( ) ; fgFirstTime = false ; } else { history . checkConsistency ( monitor ) ; } } public boolean needsExecution ( ) { OpenTypeHistory history = OpenTypeHistory . getInstance ( ) ; return fgFirstTime || history . isEmpty ( ) || history . needConsistencyCheck ( ) ; } private void refreshSearchIndices ( IProgressMonitor monitor ) throws InvocationTargetException { try { new SearchEngine ( ) . searchAllTypeNames ( null , "" . toCharArray ( ) , SearchPattern . R_EXACT_MATCH | SearchPattern . R_CASE_SENSITIVE , IRubySearchConstants . MODULE , SearchEngine . createWorkspaceScope ( ) , new TypeNameRequestor ( ) { } , IRubySearchConstants . WAIT_UNTIL_READY_TO_SEARCH , monitor ) ; } catch ( RubyModelException e ) { throw new InvocationTargetException ( e ) ; } } } ConsistencyRunnable runnable = new ConsistencyRunnable ( ) ; if ( ! runnable . needsExecution ( ) ) return ; IRunnableContext context = fRunnableContext != null ? fRunnableContext : PlatformUI . getWorkbench ( ) . getProgressService ( ) ; context . run ( true , true , runnable ) ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . util . Assert ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class StatusInfo implements IStatus { private String fStatusMessage ; private int fSeverity ; public StatusInfo ( ) { this ( OK , null ) ; } public StatusInfo ( int severity , String message ) { fStatusMessage = message ; fSeverity = severity ; } public boolean isOK ( ) { return fSeverity == IStatus . OK ; } public boolean isWarning ( ) { return fSeverity == IStatus . WARNING ; } public boolean isInfo ( ) { return fSeverity == IStatus . INFO ; } public boolean isError ( ) { return fSeverity == IStatus . ERROR ; } public String getMessage ( ) { return fStatusMessage ; } public void setError ( String errorMessage ) { Assert . isNotNull ( errorMessage ) ; fStatusMessage = errorMessage ; fSeverity = IStatus . ERROR ; } public void setWarning ( String warningMessage ) { Assert . isNotNull ( warningMessage ) ; fStatusMessage = warningMessage ; fSeverity = IStatus . WARNING ; } public void setInfo ( String infoMessage ) { Assert . isNotNull ( infoMessage ) ; fStatusMessage = infoMessage ; fSeverity = IStatus . INFO ; } public void setOK ( ) { fStatusMessage = null ; fSeverity = IStatus . OK ; } public boolean matches ( int severityMask ) { return ( fSeverity & severityMask ) != ; } public boolean isMultiStatus ( ) { return false ; } public int getSeverity ( ) { return fSeverity ; } public String getPlugin ( ) { return RubyPlugin . PLUGIN_ID ; } public Throwable getException ( ) { return null ; } public int getCode ( ) { return fSeverity ; } public IStatus [ ] getChildren ( ) { return new IStatus [ ] ; } } package org . rubypeople . rdt . internal . ui . dialogs ; import java . util . Arrays ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . SelectionDialog ; public abstract class SelectionStatusDialog extends SelectionDialog { private MessageLine fStatusLine ; private IStatus fLastStatus ; private Image fImage ; private boolean fStatusLineAboveButtons = false ; public SelectionStatusDialog ( Shell parent ) { super ( parent ) ; } public void setStatusLineAboveButtons ( boolean aboveButtons ) { fStatusLineAboveButtons = aboveButtons ; } public void setImage ( Image image ) { fImage = image ; } public Object getFirstResult ( ) { Object [ ] result = getResult ( ) ; if ( result == null || result . length == ) return null ; return result [ ] ; } protected void setResult ( int position , Object element ) { Object [ ] result = getResult ( ) ; result [ position ] = element ; setResult ( Arrays . asList ( result ) ) ; } protected abstract void computeResult ( ) ; protected void configureShell ( Shell shell ) { super . configureShell ( shell ) ; if ( fImage != null ) shell . setImage ( fImage ) ; } protected void updateStatus ( IStatus status ) { fLastStatus = status ; if ( fStatusLine != null && ! fStatusLine . isDisposed ( ) ) { updateButtonsEnableState ( status ) ; fStatusLine . setErrorStatus ( status ) ; } } protected void updateButtonsEnableState ( IStatus status ) { Button okButton = getOkButton ( ) ; if ( okButton != null && ! okButton . isDisposed ( ) ) okButton . setEnabled ( ! status . matches ( IStatus . ERROR ) ) ; } protected void okPressed ( ) { computeResult ( ) ; super . okPressed ( ) ; } public void create ( ) { super . create ( ) ; if ( fLastStatus != null ) updateStatus ( fLastStatus ) ; } protected Control createButtonBar ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; if ( fStatusLineAboveButtons ) { layout . marginWidth = ; } else { layout . numColumns = ; } layout . marginHeight = ; layout . marginWidth = ; composite . setLayout ( layout ) ; composite . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fStatusLine = new MessageLine ( composite ) ; fStatusLine . setAlignment ( SWT . LEFT ) ; fStatusLine . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fStatusLine . setErrorStatus ( null ) ; GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalIndent = convertWidthInCharsToPixels ( ) ; fStatusLine . setLayoutData ( gd ) ; super . createButtonBar ( composite ) ; return composite ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . jface . viewers . IBasicPropertyConstants ; import org . eclipse . ui . views . properties . IPropertyDescriptor ; import org . eclipse . ui . views . properties . IPropertySource ; import org . eclipse . ui . views . properties . PropertyDescriptor ; import org . rubypeople . rdt . core . IRubyElement ; public class RubyElementProperties implements IPropertySource { private IRubyElement fSource ; private static final IPropertyDescriptor [ ] fgPropertyDescriptors = new IPropertyDescriptor [ ] ; static { PropertyDescriptor descriptor ; descriptor = new PropertyDescriptor ( IBasicPropertyConstants . P_TEXT , RubyUIMessages . RubyElementProperties_name ) ; descriptor . setAlwaysIncompatible ( true ) ; fgPropertyDescriptors [ ] = descriptor ; } public RubyElementProperties ( IRubyElement source ) { fSource = source ; } public IPropertyDescriptor [ ] getPropertyDescriptors ( ) { return fgPropertyDescriptors ; } public Object getPropertyValue ( Object name ) { if ( name . equals ( IBasicPropertyConstants . P_TEXT ) ) { return fSource . getElementName ( ) ; } return null ; } public void setPropertyValue ( Object name , Object value ) { } public Object getEditableValue ( ) { return this ; } public boolean isPropertySet ( Object property ) { return false ; } public void resetPropertyValue ( Object property ) { } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . ui . actions . * ; public class MemberFilterAction extends Action { private int fFilterProperty ; private MemberFilterActionGroup fFilterActionGroup ; public MemberFilterAction ( MemberFilterActionGroup actionGroup , String title , int property , String contextHelpId , boolean initValue ) { super ( title ) ; fFilterActionGroup = actionGroup ; fFilterProperty = property ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , contextHelpId ) ; setChecked ( initValue ) ; } public int getFilterProperty ( ) { return fFilterProperty ; } public void run ( ) { fFilterActionGroup . setMemberFilter ( fFilterProperty , isChecked ( ) ) ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . HashSet ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IMarkerDelta ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IResourceDeltaVisitor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . jface . text . source . AnnotationModelEvent ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . text . source . IAnnotationModelListener ; import org . eclipse . jface . text . source . IAnnotationModelListenerExtension ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyScriptAnnotationModelEvent ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; public class ProblemMarkerManager implements IResourceChangeListener , IAnnotationModelListener , IAnnotationModelListenerExtension { private static class ProjectErrorVisitor implements IResourceDeltaVisitor { private HashSet fChangedElements ; public ProjectErrorVisitor ( HashSet changedElements ) { fChangedElements = changedElements ; } public boolean visit ( IResourceDelta delta ) throws CoreException { IResource res = delta . getResource ( ) ; if ( res instanceof IProject && delta . getKind ( ) == IResourceDelta . CHANGED ) { IProject project = ( IProject ) res ; if ( ! project . isAccessible ( ) ) { return false ; } } checkInvalidate ( delta , res ) ; return true ; } private void checkInvalidate ( IResourceDelta delta , IResource resource ) { int kind = delta . getKind ( ) ; if ( kind == IResourceDelta . REMOVED || kind == IResourceDelta . ADDED || ( kind == IResourceDelta . CHANGED && isErrorDelta ( delta ) ) ) { while ( resource . getType ( ) != IResource . ROOT && fChangedElements . add ( resource ) ) { resource = resource . getParent ( ) ; } } } private boolean isErrorDelta ( IResourceDelta delta ) { if ( ( delta . getFlags ( ) & IResourceDelta . MARKERS ) != ) { IMarkerDelta [ ] markerDeltas = delta . getMarkerDeltas ( ) ; for ( int i = ; i < markerDeltas . length ; i ++ ) { if ( markerDeltas [ i ] . isSubtypeOf ( IMarker . PROBLEM ) ) { int kind = markerDeltas [ i ] . getKind ( ) ; if ( kind == IResourceDelta . ADDED || kind == IResourceDelta . REMOVED ) return true ; int severity = markerDeltas [ i ] . getAttribute ( IMarker . SEVERITY , - ) ; int newSeverity = markerDeltas [ i ] . getMarker ( ) . getAttribute ( IMarker . SEVERITY , - ) ; if ( newSeverity != severity ) return true ; } } } return false ; } } private ListenerList fListeners ; public ProblemMarkerManager ( ) { fListeners = new ListenerList ( ) ; } public void resourceChanged ( IResourceChangeEvent event ) { HashSet changedElements = new HashSet ( ) ; try { IResourceDelta delta = event . getDelta ( ) ; if ( delta != null ) delta . accept ( new ProjectErrorVisitor ( changedElements ) ) ; } catch ( CoreException e ) { RubyPlugin . log ( e . getStatus ( ) ) ; } if ( ! changedElements . isEmpty ( ) ) { IResource [ ] changes = ( IResource [ ] ) changedElements . toArray ( new IResource [ changedElements . size ( ) ] ) ; fireChanges ( changes , true ) ; } } public void modelChanged ( IAnnotationModel model ) { } public void modelChanged ( AnnotationModelEvent event ) { if ( event instanceof RubyScriptAnnotationModelEvent ) { RubyScriptAnnotationModelEvent cuEvent = ( RubyScriptAnnotationModelEvent ) event ; if ( cuEvent . includesProblemMarkerAnnotationChanges ( ) ) { IResource [ ] changes = new IResource [ ] { cuEvent . getUnderlyingResource ( ) } ; fireChanges ( changes , false ) ; } } } public void addListener ( IProblemChangedListener listener ) { if ( fListeners . isEmpty ( ) ) { RubyPlugin . getWorkspace ( ) . addResourceChangeListener ( this ) ; RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) . addGlobalAnnotationModelListener ( this ) ; } fListeners . add ( listener ) ; } public void removeListener ( IProblemChangedListener listener ) { fListeners . remove ( listener ) ; if ( fListeners . isEmpty ( ) ) { RubyPlugin . getWorkspace ( ) . removeResourceChangeListener ( this ) ; RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) . removeGlobalAnnotationModelListener ( this ) ; } } private void fireChanges ( final IResource [ ] changes , final boolean isMarkerChange ) { Display display = SWTUtil . getStandardDisplay ( ) ; if ( display != null && ! display . isDisposed ( ) ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { IProblemChangedListener curr = ( IProblemChangedListener ) listeners [ i ] ; curr . problemsChanged ( changes , isMarkerChange ) ; } } } ) ; } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . core . resources . IResource ; public interface IProblemChangedListener { void problemsChanged ( IResource [ ] changedResources , boolean isMarkerChange ) ; } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . action . IStatusLineManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class StatusBarUpdater implements ISelectionChangedListener { private final long LABEL_FLAGS = RubyElementLabels . DEFAULT_QUALIFIED | RubyElementLabels . ROOT_POST_QUALIFIED | RubyElementLabels . APPEND_ROOT_PATH | RubyElementLabels . M_PARAMETER_NAMES ; private IStatusLineManager fStatusLineManager ; public StatusBarUpdater ( IStatusLineManager statusLineManager ) { fStatusLineManager = statusLineManager ; } public void selectionChanged ( SelectionChangedEvent event ) { String statusBarMessage = formatMessage ( event . getSelection ( ) ) ; fStatusLineManager . setMessage ( statusBarMessage ) ; } protected String formatMessage ( ISelection sel ) { if ( sel instanceof IStructuredSelection && ! sel . isEmpty ( ) ) { IStructuredSelection selection = ( IStructuredSelection ) sel ; int nElements = selection . size ( ) ; if ( nElements > ) { return Messages . format ( RubyUIMessages . StatusBarUpdater_num_elements_selected , String . valueOf ( nElements ) ) ; } else { Object elem = selection . getFirstElement ( ) ; if ( elem instanceof IRubyElement ) { return formatRubyElementMessage ( ( IRubyElement ) elem ) ; } else if ( elem instanceof IResource ) { return formatResourceMessage ( ( IResource ) elem ) ; } } } return "" ; } private String formatRubyElementMessage ( IRubyElement element ) { return RubyElementLabels . getElementLabel ( element , LABEL_FLAGS ) ; } private String formatResourceMessage ( IResource element ) { IContainer parent = element . getParent ( ) ; if ( parent != null && parent . getType ( ) != IResource . ROOT ) return element . getName ( ) + RubyElementLabels . CONCAT_STRING + parent . getFullPath ( ) . makeRelative ( ) . toString ( ) ; else return element . getName ( ) ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . LabelProviderChangedEvent ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class AppearanceAwareLabelProvider extends RubyUILabelProvider implements IPropertyChangeListener { public final static long DEFAULT_TEXTFLAGS = RubyElementLabels . M_PARAMETER_NAMES | RubyElementLabels . ROOT_VARIABLE | RubyElementLabels . REFERENCED_ROOT_POST_QUALIFIED ; public final static int DEFAULT_IMAGEFLAGS = RubyElementImageProvider . OVERLAY_ICONS ; private long fTextFlagMask ; private int fImageFlagMask ; public AppearanceAwareLabelProvider ( long textFlags , int imageFlags ) { super ( textFlags , imageFlags ) ; initMasks ( ) ; PreferenceConstants . getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; } public AppearanceAwareLabelProvider ( ) { this ( DEFAULT_TEXTFLAGS , DEFAULT_IMAGEFLAGS ) ; } private void initMasks ( ) { IPreferenceStore store = PreferenceConstants . getPreferenceStore ( ) ; fTextFlagMask = - ; if ( ! store . getBoolean ( PreferenceConstants . APPEARANCE_COMPRESS_PACKAGE_NAMES ) ) { fTextFlagMask ^= RubyElementLabels . P_COMPRESSED ; } fImageFlagMask = - ; } public void propertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( property . equals ( PreferenceConstants . APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW ) || property . equals ( PreferenceConstants . APPEARANCE_COMPRESS_PACKAGE_NAMES ) ) { initMasks ( ) ; LabelProviderChangedEvent lpEvent = new LabelProviderChangedEvent ( this , null ) ; fireLabelProviderChanged ( lpEvent ) ; } } public void dispose ( ) { PreferenceConstants . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; super . dispose ( ) ; } protected int evaluateImageFlags ( Object element ) { return getImageFlags ( ) & fImageFlagMask ; } protected long evaluateTextFlags ( Object element ) { return getTextFlags ( ) & fTextFlagMask ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . resources . IStorage ; import org . eclipse . swt . graphics . Image ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . ui . IEditorRegistry ; import org . eclipse . ui . IFileEditorMapping ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . PlatformUI ; public class StorageLabelProvider extends LabelProvider { private IEditorRegistry fEditorRegistry = null ; private Map fJarImageMap = new HashMap ( ) ; private Image fDefaultImage ; private IEditorRegistry getEditorRegistry ( ) { if ( fEditorRegistry == null ) fEditorRegistry = PlatformUI . getWorkbench ( ) . getEditorRegistry ( ) ; return fEditorRegistry ; } public Image getImage ( Object element ) { if ( element instanceof IStorage ) return getImageForJarEntry ( ( IStorage ) element ) ; return super . getImage ( element ) ; } public String getText ( Object element ) { if ( element instanceof IStorage ) return ( ( IStorage ) element ) . getName ( ) ; return super . getText ( element ) ; } public void dispose ( ) { if ( fJarImageMap != null ) { Iterator each = fJarImageMap . values ( ) . iterator ( ) ; while ( each . hasNext ( ) ) { Image image = ( Image ) each . next ( ) ; image . dispose ( ) ; } fJarImageMap = null ; } fDefaultImage = null ; } private Image getImageForJarEntry ( IStorage element ) { if ( fJarImageMap == null ) return getDefaultImage ( ) ; if ( element == null || element . getName ( ) == null ) return getDefaultImage ( ) ; String name = element . getName ( ) ; Image image = ( Image ) fJarImageMap . get ( name ) ; if ( image != null ) return image ; IFileEditorMapping [ ] mappings = getEditorRegistry ( ) . getFileEditorMappings ( ) ; int i = ; while ( i < mappings . length ) { if ( mappings [ i ] . getLabel ( ) . equals ( name ) ) break ; i ++ ; } String key = name ; if ( i == mappings . length ) { IPath path = element . getFullPath ( ) ; if ( path == null ) return getDefaultImage ( ) ; key = path . getFileExtension ( ) ; if ( key == null ) return getDefaultImage ( ) ; image = ( Image ) fJarImageMap . get ( key ) ; if ( image != null ) return image ; } ImageDescriptor desc = getEditorRegistry ( ) . getImageDescriptor ( name ) ; image = desc . createImage ( ) ; fJarImageMap . put ( key , image ) ; return image ; } private Image getDefaultImage ( ) { if ( fDefaultImage == null ) fDefaultImage = PlatformUI . getWorkbench ( ) . getSharedImages ( ) . getImage ( ISharedImages . IMG_OBJ_FILE ) ; return fDefaultImage ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . ArrayList ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTreeViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ITreeViewerListener ; import org . eclipse . jface . viewers . TreeExpansionEvent ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . TreeItem ; import org . eclipse . swt . widgets . Widget ; public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { public ContainerCheckedTreeViewer ( Composite parent ) { super ( parent ) ; initViewer ( ) ; } public ContainerCheckedTreeViewer ( Composite parent , int style ) { super ( parent , style ) ; initViewer ( ) ; } public ContainerCheckedTreeViewer ( Tree tree ) { super ( tree ) ; initViewer ( ) ; } private void initViewer ( ) { setUseHashlookup ( true ) ; addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { doCheckStateChanged ( event . getElement ( ) ) ; } } ) ; addTreeListener ( new ITreeViewerListener ( ) { public void treeCollapsed ( TreeExpansionEvent event ) { } public void treeExpanded ( TreeExpansionEvent event ) { Widget item = findItem ( event . getElement ( ) ) ; if ( item instanceof TreeItem ) { initializeItem ( ( TreeItem ) item ) ; } } } ) ; } protected void doCheckStateChanged ( Object element ) { Widget item = findItem ( element ) ; if ( item instanceof TreeItem ) { TreeItem treeItem = ( TreeItem ) item ; treeItem . setGrayed ( false ) ; updateChildrenItems ( treeItem ) ; updateParentItems ( treeItem . getParentItem ( ) ) ; } } private void initializeItem ( TreeItem item ) { if ( item . getChecked ( ) && ! item . getGrayed ( ) ) { updateChildrenItems ( item ) ; } } private void updateChildrenItems ( TreeItem parent ) { Item [ ] children = getChildren ( parent ) ; boolean state = parent . getChecked ( ) ; for ( int i = ; i < children . length ; i ++ ) { TreeItem curr = ( TreeItem ) children [ i ] ; if ( curr . getData ( ) != null && ( ( curr . getChecked ( ) != state ) || curr . getGrayed ( ) ) ) { curr . setChecked ( state ) ; curr . setGrayed ( false ) ; updateChildrenItems ( curr ) ; } } } private void updateParentItems ( TreeItem item ) { if ( item != null ) { Item [ ] children = getChildren ( item ) ; boolean containsChecked = false ; boolean containsUnchecked = false ; for ( int i = ; i < children . length ; i ++ ) { TreeItem curr = ( TreeItem ) children [ i ] ; containsChecked |= curr . getChecked ( ) ; containsUnchecked |= ( ! curr . getChecked ( ) || curr . getGrayed ( ) ) ; } item . setChecked ( containsChecked ) ; item . setGrayed ( containsChecked && containsUnchecked ) ; updateParentItems ( item . getParentItem ( ) ) ; } } public boolean setChecked ( Object element , boolean state ) { if ( super . setChecked ( element , state ) ) { doCheckStateChanged ( element ) ; return true ; } return false ; } public void setCheckedElements ( Object [ ] elements ) { super . setCheckedElements ( elements ) ; for ( int i = ; i < elements . length ; i ++ ) { doCheckStateChanged ( elements [ i ] ) ; } } protected void setExpanded ( Item item , boolean expand ) { super . setExpanded ( item , expand ) ; if ( expand && item instanceof TreeItem ) { initializeItem ( ( TreeItem ) item ) ; } } public Object [ ] getCheckedElements ( ) { Object [ ] checked = super . getCheckedElements ( ) ; ArrayList result = new ArrayList ( ) ; for ( int i = ; i < checked . length ; i ++ ) { Object curr = checked [ i ] ; result . add ( curr ) ; Widget item = findItem ( curr ) ; if ( item != null ) { Item [ ] children = getChildren ( item ) ; if ( children . length == && children [ ] . getData ( ) == null ) { collectChildren ( curr , result ) ; } } } return result . toArray ( ) ; } private void collectChildren ( Object element , ArrayList result ) { Object [ ] filteredChildren = getFilteredChildren ( element ) ; for ( int i = ; i < filteredChildren . length ; i ++ ) { Object curr = filteredChildren [ i ] ; result . add ( curr ) ; collectChildren ( curr , result ) ; } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . jface . resource . ColorRegistry ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . TreeItem ; import org . rubypeople . rdt . internal . ui . preferences . AppearancePreferencePage ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class ColoredViewersManager implements IPropertyChangeListener { public static final String QUALIFIER_COLOR_NAME = "" ; public static final String DECORATIONS_COLOR_NAME = "" ; public static final String COUNTER_COLOR_NAME = "" ; public static final String INHERITED_COLOR_NAME = "" ; private static ColoredViewersManager fgInstance = new ColoredViewersManager ( ) ; private Map fManagedViewers ; private ColorRegistry fColorRegisty ; public ColoredViewersManager ( ) { fManagedViewers = new HashMap ( ) ; fColorRegisty = JFaceResources . getColorRegistry ( ) ; } public void installColoredLabels ( StructuredViewer viewer ) { if ( fManagedViewers . containsKey ( viewer ) ) { return ; } if ( fManagedViewers . isEmpty ( ) ) { PreferenceConstants . getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; fColorRegisty . addListener ( this ) ; } fManagedViewers . put ( viewer , new ManagedViewer ( viewer ) ) ; } public void uninstallColoredLabels ( StructuredViewer viewer ) { ManagedViewer mv = ( ManagedViewer ) fManagedViewers . remove ( viewer ) ; if ( mv == null ) return ; if ( fManagedViewers . isEmpty ( ) ) { PreferenceConstants . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; fColorRegisty . removeListener ( this ) ; } } public Color getColorForName ( String symbolicName ) { return fColorRegisty . get ( symbolicName ) ; } public void propertyChange ( PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( property . equals ( QUALIFIER_COLOR_NAME ) || property . equals ( COUNTER_COLOR_NAME ) || property . equals ( DECORATIONS_COLOR_NAME ) || property . equals ( AppearancePreferencePage . PREF_COLORED_LABELS ) ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { refreshAllViewers ( ) ; } } ) ; } } protected final void refreshAllViewers ( ) { for ( Iterator iterator = fManagedViewers . values ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { ManagedViewer viewer = ( ManagedViewer ) iterator . next ( ) ; viewer . refresh ( ) ; } } private class ManagedViewer implements DisposeListener { private static final String COLORED_LABEL_KEY = "" ; private StructuredViewer fViewer ; private OwnerDrawSupport fOwnerDrawSupport ; private ManagedViewer ( StructuredViewer viewer ) { fViewer = viewer ; fOwnerDrawSupport = null ; fViewer . getControl ( ) . addDisposeListener ( this ) ; if ( showColoredLabels ( ) ) { installOwnerDraw ( ) ; } } public void widgetDisposed ( DisposeEvent e ) { uninstallColoredLabels ( fViewer ) ; } public final void refresh ( ) { Control control = fViewer . getControl ( ) ; if ( ! control . isDisposed ( ) ) { if ( showColoredLabels ( ) ) { installOwnerDraw ( ) ; } else { uninstallOwnerDraw ( ) ; } } } protected void installOwnerDraw ( ) { if ( fOwnerDrawSupport == null ) { fOwnerDrawSupport = new OwnerDrawSupport ( fViewer . getControl ( ) ) { public ColoredString getColoredLabel ( Item item ) { return getColoredLabelForView ( item ) ; } public Color getColor ( String foregroundColorName , Display display ) { return getColorForName ( foregroundColorName ) ; } } ; } refreshViewer ( ) ; } protected void uninstallOwnerDraw ( ) { if ( fOwnerDrawSupport == null ) return ; fOwnerDrawSupport . dispose ( ) ; fOwnerDrawSupport = null ; refreshViewer ( ) ; } private void refreshViewer ( ) { Control control = fViewer . getControl ( ) ; if ( ! control . isDisposed ( ) ) { if ( control instanceof Tree ) { refresh ( ( ( Tree ) control ) . getItems ( ) ) ; } else if ( control instanceof Table ) { refresh ( ( ( Table ) control ) . getItems ( ) ) ; } } } private void refresh ( Item [ ] items ) { for ( int i = ; i < items . length ; i ++ ) { Item item = items [ i ] ; item . setData ( COLORED_LABEL_KEY , null ) ; String text = item . getText ( ) ; item . setText ( "" ) ; item . setText ( text ) ; if ( item instanceof TreeItem ) { refresh ( ( ( TreeItem ) item ) . getItems ( ) ) ; } } } private ColoredString getColoredLabelForView ( Item item ) { ColoredString oldLabel = ( ColoredString ) item . getData ( COLORED_LABEL_KEY ) ; String itemText = item . getText ( ) ; if ( oldLabel != null && oldLabel . getString ( ) . equals ( itemText ) ) { return oldLabel ; } ColoredString newLabel = null ; IBaseLabelProvider labelProvider = fViewer . getLabelProvider ( ) ; if ( labelProvider instanceof IRichLabelProvider ) { newLabel = ( ( IRichLabelProvider ) labelProvider ) . getRichTextLabel ( item . getData ( ) ) ; } if ( newLabel == null ) { newLabel = new ColoredString ( itemText ) ; } else if ( ! newLabel . getString ( ) . equals ( itemText ) ) { newLabel = ColoredRubyElementLabels . decorateColoredString ( newLabel , itemText , ColoredRubyElementLabels . DECORATIONS_STYLE ) ; } item . setData ( COLORED_LABEL_KEY , newLabel ) ; return newLabel ; } } public static boolean showColoredLabels ( ) { String preference = PreferenceConstants . getPreference ( AppearancePreferencePage . PREF_COLORED_LABELS , null ) ; return preference != null && Boolean . valueOf ( preference ) . booleanValue ( ) ; } public static void install ( StructuredViewer viewer ) { fgInstance . installColoredLabels ( viewer ) ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . util . Assert ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . ERBScript ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . ui . RubyElementImageDescriptor ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; public class RubyElementImageProvider { public final static int OVERLAY_ICONS = ; public final static int SMALL_ICONS = ; public final static int LIGHT_TYPE_ICONS = ; public static final Point SMALL_SIZE = new Point ( , ) ; public static final Point BIG_SIZE = new Point ( , ) ; private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED ; private static ImageDescriptor DESC_OBJ_PROJECT ; { ISharedImages images = RubyPlugin . getDefault ( ) . getWorkbench ( ) . getSharedImages ( ) ; DESC_OBJ_PROJECT_CLOSED = images . getImageDescriptor ( IDE . SharedImages . IMG_OBJ_PROJECT_CLOSED ) ; DESC_OBJ_PROJECT = images . getImageDescriptor ( IDE . SharedImages . IMG_OBJ_PROJECT ) ; } private ImageDescriptorRegistry fRegistry ; public RubyElementImageProvider ( ) { fRegistry = null ; } public Image getImageLabel ( Object element , int flags ) { return getImageLabel ( computeDescriptor ( element , flags ) ) ; } private Image getImageLabel ( ImageDescriptor descriptor ) { if ( descriptor == null ) return null ; return getRegistry ( ) . get ( descriptor ) ; } private ImageDescriptorRegistry getRegistry ( ) { if ( fRegistry == null ) { fRegistry = RubyPlugin . getImageDescriptorRegistry ( ) ; } return fRegistry ; } private ImageDescriptor computeDescriptor ( Object element , int flags ) { if ( element instanceof IRubyElement ) { return getRubyImageDescriptor ( ( IRubyElement ) element , flags ) ; } else if ( element instanceof IAdaptable ) { return getWorkbenchImageDescriptor ( ( IAdaptable ) element , flags ) ; } else if ( element instanceof IFile ) { IFile file = ( IFile ) element ; if ( RubyCore . isRubyLikeFileName ( file . getName ( ) ) ) { return getCUResourceImageDescriptor ( file , flags ) ; } return getWorkbenchImageDescriptor ( file , flags ) ; } return null ; } private static boolean showOverlayIcons ( int flags ) { return ( flags & OVERLAY_ICONS ) != ; } private static boolean useSmallSize ( int flags ) { return ( flags & SMALL_ICONS ) != ; } private static boolean useLightIcons ( int flags ) { return ( flags & LIGHT_TYPE_ICONS ) != ; } public ImageDescriptor getCUResourceImageDescriptor ( IFile file , int flags ) { Point size = useSmallSize ( flags ) ? SMALL_SIZE : BIG_SIZE ; return new RubyElementImageDescriptor ( RubyPluginImages . DESC_OBJS_RUBY_RESOURCE , , size ) ; } public ImageDescriptor getRubyImageDescriptor ( IRubyElement element , int flags ) { int adornmentFlags = computeRubyAdornmentFlags ( element , flags ) ; Point size = useSmallSize ( flags ) ? SMALL_SIZE : BIG_SIZE ; return new RubyElementImageDescriptor ( getBaseImageDescriptor ( element , flags ) , adornmentFlags , size ) ; } public ImageDescriptor getWorkbenchImageDescriptor ( IAdaptable adaptable , int flags ) { IWorkbenchAdapter wbAdapter = ( IWorkbenchAdapter ) adaptable . getAdapter ( IWorkbenchAdapter . class ) ; if ( wbAdapter == null ) { return null ; } ImageDescriptor descriptor = wbAdapter . getImageDescriptor ( adaptable ) ; if ( descriptor == null ) { return null ; } Point size = useSmallSize ( flags ) ? SMALL_SIZE : BIG_SIZE ; return new RubyElementImageDescriptor ( descriptor , , size ) ; } public ImageDescriptor getBaseImageDescriptor ( IRubyElement element , int renderFlags ) { try { switch ( element . getElementType ( ) ) { case IRubyElement . METHOD : { IMethod method = ( IMethod ) element ; IType declType = method . getDeclaringType ( ) ; int flags = method . getVisibility ( ) ; return getMethodImageDescriptor ( flags ) ; } case IRubyElement . GLOBAL : return RubyPluginImages . DESC_OBJS_GLOBAL ; case IRubyElement . CLASS_VAR : return RubyPluginImages . DESC_OBJS_CLASS_VAR ; case IRubyElement . CONSTANT : return RubyPluginImages . DESC_OBJS_CONSTANT ; case IRubyElement . LOCAL_VARIABLE : case IRubyElement . DYNAMIC_VAR : return RubyPluginImages . DESC_OBJS_LOCAL_VAR ; case IRubyElement . INSTANCE_VAR : return RubyPluginImages . DESC_OBJS_INSTANCE_VAR ; case IRubyElement . IMPORT_DECLARATION : return RubyPluginImages . DESC_OBJS_IMPDECL ; case IRubyElement . IMPORT_CONTAINER : return RubyPluginImages . DESC_OBJS_IMPCONT ; case IRubyElement . BLOCK : return RubyPluginImages . DESC_OBJS_BLOCK ; case IRubyElement . TYPE : { IType type = ( IType ) element ; IType declType = type . getDeclaringType ( ) ; boolean isInner = declType != null ; return getTypeImageDescriptor ( type . isModule ( ) , isInner , useLightIcons ( renderFlags ) ) ; } case IRubyElement . SCRIPT : if ( element instanceof ERBScript ) { return RubyPluginImages . DESC_OBJS_ERB_SCRIPT ; } return RubyPluginImages . DESC_OBJS_SCRIPT ; case IRubyElement . SOURCE_FOLDER : return RubyPluginImages . DESC_OBJS_SOURCE_FOLDER ; case IRubyElement . SOURCE_FOLDER_ROOT : ISourceFolderRoot root = ( ISourceFolderRoot ) element ; if ( root . isExternal ( ) ) { return RubyPluginImages . DESC_OBJS_LIBRARY ; } else { return RubyPluginImages . DESC_OBJS_SOURCE_FOLDER_ROOT ; } case IRubyElement . RUBY_PROJECT : IRubyProject jp = ( IRubyProject ) element ; if ( jp . getProject ( ) . isOpen ( ) ) { IProject project = jp . getProject ( ) ; IWorkbenchAdapter adapter = ( IWorkbenchAdapter ) project . getAdapter ( IWorkbenchAdapter . class ) ; if ( adapter != null ) { ImageDescriptor result = adapter . getImageDescriptor ( project ) ; if ( result != null ) return result ; } return DESC_OBJ_PROJECT ; } return DESC_OBJ_PROJECT_CLOSED ; case IRubyElement . RUBY_MODEL : return RubyPluginImages . DESC_OBJS_RUBY_MODEL ; } Assert . isTrue ( false , RubyUIMessages . RubyImageLabelprovider_assert_wrongImage ) ; return RubyPluginImages . DESC_OBJS_GHOST ; } catch ( RubyModelException e ) { return RubyPluginImages . DESC_OBJS_UNKNOWN ; } } public void dispose ( ) { } private int computeRubyAdornmentFlags ( IRubyElement element , int renderFlags ) { int flags = ; if ( showOverlayIcons ( renderFlags ) && element instanceof IMember ) { IMember member = ( IMember ) element ; if ( element . getElementType ( ) == IRubyElement . METHOD && ( ( IMethod ) element ) . isConstructor ( ) ) flags |= RubyElementImageDescriptor . CONSTRUCTOR ; if ( element . getElementType ( ) == IRubyElement . METHOD && ( ( IMethod ) element ) . isSingleton ( ) ) flags |= RubyElementImageDescriptor . STATIC ; } return flags ; } public static ImageDescriptor getMethodImageDescriptor ( int flags ) { if ( Flags . isPublic ( flags ) ) return RubyPluginImages . DESC_MISC_PUBLIC ; if ( Flags . isProtected ( flags ) ) return RubyPluginImages . DESC_MISC_PROTECTED ; return RubyPluginImages . DESC_MISC_PRIVATE ; } public static ImageDescriptor getTypeImageDescriptor ( boolean isModule , boolean isInner , boolean useLightIcons ) { if ( isModule ) { if ( useLightIcons ) { return RubyPluginImages . DESC_OBJS_MODULEALT ; } if ( isInner ) { return getInnerModuleImageDescriptor ( ) ; } return RubyPluginImages . DESC_OBJS_MODULE ; } if ( useLightIcons ) { return RubyPluginImages . DESC_OBJS_CLASSALT ; } if ( isInner ) { return getInnerClassImageDescriptor ( ) ; } return getClassImageDescriptor ( ) ; } public static Image getDecoratedImage ( ImageDescriptor baseImage , int adornments , Point size ) { return RubyPlugin . getImageDescriptorRegistry ( ) . get ( new RubyElementImageDescriptor ( baseImage , adornments , size ) ) ; } private static ImageDescriptor getClassImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_CLASS ; } private static ImageDescriptor getInnerClassImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_INNER_CLASS ; } private static ImageDescriptor getInnerModuleImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_MODULE ; } public static ImageDescriptor getConstantImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_CONSTANT ; } public static ImageDescriptor getClassVariableImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_CLASS_VAR ; } public static ImageDescriptor getInstanceVariableImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_INSTANCE_VAR ; } public static ImageDescriptor getGlobalVariableImageDescriptor ( ) { return RubyPluginImages . DESC_OBJS_GLOBAL ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . ArrayList ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeSelection ; import org . eclipse . jface . viewers . LabelProviderChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . Widget ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . ui . IWorkingCopyProvider ; import org . rubypeople . rdt . ui . ProblemsLabelDecorator . ProblemsLabelChangedEvent ; public class ProblemTreeViewer extends TreeViewer implements ResourceToItemsMapper . IContentViewerAccessor { protected ResourceToItemsMapper fResourceToItemsMapper ; public ProblemTreeViewer ( Composite parent ) { super ( parent ) ; initMapper ( ) ; } public ProblemTreeViewer ( Composite parent , int style ) { super ( parent , style ) ; initMapper ( ) ; } public ProblemTreeViewer ( Tree tree ) { super ( tree ) ; initMapper ( ) ; } public void doUpdateItem ( Widget item ) { doUpdateItem ( item , item . getData ( ) , true ) ; } private void initMapper ( ) { fResourceToItemsMapper = new ResourceToItemsMapper ( this ) ; } protected void mapElement ( Object element , Widget item ) { super . mapElement ( element , item ) ; if ( item instanceof Item ) { fResourceToItemsMapper . addToMap ( element , ( Item ) item ) ; } } protected void unmapElement ( Object element , Widget item ) { if ( item instanceof Item ) { fResourceToItemsMapper . removeFromMap ( element , ( Item ) item ) ; } super . unmapElement ( element , item ) ; } protected void unmapAllElements ( ) { fResourceToItemsMapper . clearMap ( ) ; super . unmapAllElements ( ) ; } protected void handleLabelProviderChanged ( LabelProviderChangedEvent event ) { if ( event instanceof ProblemsLabelChangedEvent ) { ProblemsLabelChangedEvent e = ( ProblemsLabelChangedEvent ) event ; if ( ! e . isMarkerChange ( ) && canIgnoreChangesFromAnnotionModel ( ) ) { return ; } } Object [ ] changed = addAditionalProblemParents ( event . getElements ( ) ) ; if ( changed != null && ! fResourceToItemsMapper . isEmpty ( ) ) { ArrayList others = new ArrayList ( ) ; for ( int i = ; i < changed . length ; i ++ ) { Object curr = changed [ i ] ; if ( curr instanceof IResource ) { fResourceToItemsMapper . resourceChanged ( ( IResource ) curr ) ; } else { others . add ( curr ) ; } } if ( others . isEmpty ( ) ) { return ; } event = new LabelProviderChangedEvent ( ( IBaseLabelProvider ) event . getSource ( ) , others . toArray ( ) ) ; } else { if ( event . getElements ( ) != changed ) event = new LabelProviderChangedEvent ( ( IBaseLabelProvider ) event . getSource ( ) , changed ) ; } super . handleLabelProviderChanged ( event ) ; } private boolean canIgnoreChangesFromAnnotionModel ( ) { Object contentProvider = getContentProvider ( ) ; return contentProvider instanceof IWorkingCopyProvider && ! ( ( IWorkingCopyProvider ) contentProvider ) . providesWorkingCopies ( ) ; } protected boolean evaluateExpandableWithFilters ( Object parent ) { return parent instanceof IMember ; } public boolean isExpandable ( Object parent ) { if ( hasFilters ( ) && evaluateExpandableWithFilters ( parent ) ) { Object [ ] children = getRawChildren ( parent ) ; if ( children . length > ) { ViewerFilter [ ] filters = getFilters ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( ! isFiltered ( children [ i ] , parent , filters ) ) { return true ; } } } return false ; } return super . isExpandable ( parent ) ; } protected boolean isFiltered ( Object object , Object parent , ViewerFilter [ ] filters ) { for ( int i = ; i < filters . length ; i ++ ) { ViewerFilter filter = filters [ i ] ; if ( ! filter . select ( this , parent , object ) ) return true ; } return false ; } protected Object [ ] addAditionalProblemParents ( Object [ ] elements ) { return elements ; } protected void handleInvalidSelection ( ISelection invalidSelection , ISelection newSelection ) { if ( ! invalidSelection . isEmpty ( ) && newSelection . isEmpty ( ) && invalidSelection instanceof ITreeSelection ) { newSelection = new StructuredSelection ( ( ( IStructuredSelection ) invalidSelection ) . toArray ( ) ) ; setSelection ( newSelection ) ; } super . handleInvalidSelection ( invalidSelection , newSelection ) ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Stack ; import org . eclipse . core . resources . IResource ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Widget ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; public class ResourceToItemsMapper { public static interface IContentViewerAccessor { public void doUpdateItem ( Widget item ) ; } private static final int NUMBER_LIST_REUSE = ; private HashMap fResourceToItem ; private Stack fReuseLists ; private IContentViewerAccessor fContentViewerAccess ; public ResourceToItemsMapper ( IContentViewerAccessor viewer ) { fResourceToItem = new HashMap ( ) ; fReuseLists = new Stack ( ) ; fContentViewerAccess = viewer ; } public void resourceChanged ( IResource changedResource ) { Object obj = fResourceToItem . get ( changedResource ) ; if ( obj == null ) { } else if ( obj instanceof Item ) { updateItem ( ( Item ) obj ) ; } else { List list = ( List ) obj ; for ( int k = ; k < list . size ( ) ; k ++ ) { updateItem ( ( Item ) list . get ( k ) ) ; } } } private void updateItem ( Item item ) { if ( ! item . isDisposed ( ) ) { fContentViewerAccess . doUpdateItem ( item ) ; } } public void addToMap ( Object element , Item item ) { IResource resource = getCorrespondingResource ( element ) ; if ( resource != null ) { Object existingMapping = fResourceToItem . get ( resource ) ; if ( existingMapping == null ) { fResourceToItem . put ( resource , item ) ; } else if ( existingMapping instanceof Item ) { if ( existingMapping != item ) { List list = getNewList ( ) ; list . add ( existingMapping ) ; list . add ( item ) ; fResourceToItem . put ( resource , list ) ; } } else { List list = ( List ) existingMapping ; if ( ! list . contains ( item ) ) { list . add ( item ) ; } } } } public void removeFromMap ( Object element , Item item ) { IResource resource = getCorrespondingResource ( element ) ; if ( resource != null ) { Object existingMapping = fResourceToItem . get ( resource ) ; if ( existingMapping == null ) { return ; } else if ( existingMapping instanceof Item ) { fResourceToItem . remove ( resource ) ; } else { List list = ( List ) existingMapping ; list . remove ( item ) ; if ( list . isEmpty ( ) ) { fResourceToItem . remove ( list ) ; releaseList ( list ) ; } } } } private List getNewList ( ) { if ( ! fReuseLists . isEmpty ( ) ) { return ( List ) fReuseLists . pop ( ) ; } return new ArrayList ( ) ; } private void releaseList ( List list ) { if ( fReuseLists . size ( ) < NUMBER_LIST_REUSE ) { fReuseLists . push ( list ) ; } } public void clearMap ( ) { fResourceToItem . clear ( ) ; } public boolean isEmpty ( ) { return fResourceToItem . isEmpty ( ) ; } private static IResource getCorrespondingResource ( Object element ) { if ( element instanceof IRubyElement ) { IRubyElement elem = ( IRubyElement ) element ; IResource res = elem . getResource ( ) ; if ( res == null ) { IRubyScript cu = ( IRubyScript ) elem . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) { res = cu . getResource ( ) ; } } return res ; } else if ( element instanceof IResource ) { return ( IResource ) element ; } return null ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; public class ColoredString { public static class Style { private final String fForegroundColorName ; public Style ( String foregroundColorName ) { fForegroundColorName = foregroundColorName ; } public String getForegroundColorName ( ) { return fForegroundColorName ; } } public static final Style DEFAULT_STYLE = null ; private StringBuffer fBuffer ; private ArrayList fRanges ; public ColoredString ( ) { fBuffer = new StringBuffer ( ) ; fRanges = null ; } public ColoredString ( String text ) { this ( text , ColoredString . DEFAULT_STYLE ) ; } public ColoredString ( String text , Style style ) { this ( ) ; append ( text , style ) ; } public String getString ( ) { return fBuffer . toString ( ) ; } public int length ( ) { return fBuffer . length ( ) ; } public Iterator getRanges ( ) { if ( ! hasRanges ( ) ) return Collections . EMPTY_LIST . iterator ( ) ; return getRangesList ( ) . iterator ( ) ; } public ColoredString append ( String text ) { return append ( text , DEFAULT_STYLE ) ; } public ColoredString append ( char ch ) { return append ( String . valueOf ( ch ) , DEFAULT_STYLE ) ; } public ColoredString append ( ColoredString string ) { int offset = fBuffer . length ( ) ; fBuffer . append ( string . getString ( ) ) ; for ( Iterator iterator = string . getRanges ( ) ; iterator . hasNext ( ) ; ) { StyleRange curr = ( StyleRange ) iterator . next ( ) ; addRange ( new StyleRange ( offset + curr . offset , curr . length , curr . style ) ) ; } return this ; } public ColoredString append ( String text , Style style ) { if ( text . length ( ) == ) return this ; int offset = fBuffer . length ( ) ; fBuffer . append ( text ) ; if ( style != null ) { int nRanges = getNumberOfRanges ( ) ; if ( nRanges > ) { StyleRange last = getRange ( nRanges - ) ; if ( last . offset + last . length == offset && style . equals ( last . style ) ) { last . length += text . length ( ) ; return this ; } } addRange ( new StyleRange ( offset , text . length ( ) , style ) ) ; } return this ; } public void colorize ( int offset , int length , Style style ) { if ( offset < || offset + length > fBuffer . length ( ) ) { throw new IllegalArgumentException ( "" + offset + "" + length + "" ) ; } int insertPos = ; int nRanges = getNumberOfRanges ( ) ; for ( int i = ; i < nRanges ; i ++ ) { StyleRange curr = getRange ( i ) ; if ( curr . offset + curr . length <= offset ) { insertPos = i + ; } } if ( insertPos < nRanges ) { StyleRange curr = getRange ( insertPos ) ; if ( curr . offset > offset + length ) { throw new IllegalArgumentException ( "" ) ; } } addRange ( insertPos , new StyleRange ( offset , length , style ) ) ; } public String toString ( ) { return fBuffer . toString ( ) ; } private boolean hasRanges ( ) { return fRanges != null && ! fRanges . isEmpty ( ) ; } private int getNumberOfRanges ( ) { return fRanges == null ? : fRanges . size ( ) ; } private StyleRange getRange ( int index ) { if ( fRanges != null ) { return ( StyleRange ) fRanges . get ( index ) ; } throw new IndexOutOfBoundsException ( ) ; } private void addRange ( StyleRange range ) { getRangesList ( ) . add ( range ) ; } private void addRange ( int index , StyleRange range ) { getRangesList ( ) . add ( index , range ) ; } private List getRangesList ( ) { if ( fRanges == null ) fRanges = new ArrayList ( ) ; return fRanges ; } public static class StyleRange { public int offset ; public int length ; public Style style ; public StyleRange ( int offset , int length , Style style ) { this . offset = offset ; this . length = length ; this . style = style ; } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . IPostSelectionProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . StructuredViewer ; public class SelectionProviderMediator implements IPostSelectionProvider { private class InternalListener implements ISelectionChangedListener , FocusListener { public void selectionChanged ( SelectionChangedEvent event ) { doSelectionChanged ( event ) ; } public void focusGained ( FocusEvent e ) { doFocusChanged ( e . widget ) ; } public void focusLost ( FocusEvent e ) { } } private class InternalPostSelectionListener implements ISelectionChangedListener { public void selectionChanged ( SelectionChangedEvent event ) { doPostSelectionChanged ( event ) ; } } private StructuredViewer [ ] fViewers ; private StructuredViewer fViewerInFocus ; private ListenerList fSelectionChangedListeners ; private ListenerList fPostSelectionChangedListeners ; public SelectionProviderMediator ( StructuredViewer [ ] viewers , StructuredViewer viewerInFocus ) { Assert . isNotNull ( viewers ) ; fViewers = viewers ; InternalListener listener = new InternalListener ( ) ; fSelectionChangedListeners = new ListenerList ( ) ; fPostSelectionChangedListeners = new ListenerList ( ) ; fViewerInFocus = viewerInFocus ; for ( int i = ; i < fViewers . length ; i ++ ) { StructuredViewer viewer = fViewers [ i ] ; viewer . addSelectionChangedListener ( listener ) ; viewer . addPostSelectionChangedListener ( new InternalPostSelectionListener ( ) ) ; Control control = viewer . getControl ( ) ; control . addFocusListener ( listener ) ; } } private void doFocusChanged ( Widget control ) { for ( int i = ; i < fViewers . length ; i ++ ) { if ( fViewers [ i ] . getControl ( ) == control ) { propagateFocusChanged ( fViewers [ i ] ) ; return ; } } } final void doPostSelectionChanged ( SelectionChangedEvent event ) { ISelectionProvider provider = event . getSelectionProvider ( ) ; if ( provider == fViewerInFocus ) { firePostSelectionChanged ( ) ; } } final void doSelectionChanged ( SelectionChangedEvent event ) { ISelectionProvider provider = event . getSelectionProvider ( ) ; if ( provider == fViewerInFocus ) { fireSelectionChanged ( ) ; } } final void propagateFocusChanged ( StructuredViewer viewer ) { if ( viewer != fViewerInFocus ) { fViewerInFocus = viewer ; fireSelectionChanged ( ) ; firePostSelectionChanged ( ) ; } } private void fireSelectionChanged ( ) { if ( fSelectionChangedListeners != null ) { SelectionChangedEvent event = new SelectionChangedEvent ( this , getSelection ( ) ) ; Object [ ] listeners = fSelectionChangedListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { ISelectionChangedListener listener = ( ISelectionChangedListener ) listeners [ i ] ; listener . selectionChanged ( event ) ; } } } private void firePostSelectionChanged ( ) { if ( fPostSelectionChangedListeners != null ) { SelectionChangedEvent event = new SelectionChangedEvent ( this , getSelection ( ) ) ; Object [ ] listeners = fPostSelectionChangedListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { ISelectionChangedListener listener = ( ISelectionChangedListener ) listeners [ i ] ; listener . selectionChanged ( event ) ; } } } public void addSelectionChangedListener ( ISelectionChangedListener listener ) { fSelectionChangedListeners . add ( listener ) ; } public void removeSelectionChangedListener ( ISelectionChangedListener listener ) { fSelectionChangedListeners . remove ( listener ) ; } public void addPostSelectionChangedListener ( ISelectionChangedListener listener ) { fPostSelectionChangedListeners . add ( listener ) ; } public void removePostSelectionChangedListener ( ISelectionChangedListener listener ) { fPostSelectionChangedListeners . remove ( listener ) ; } public ISelection getSelection ( ) { if ( fViewerInFocus != null ) { return fViewerInFocus . getSelection ( ) ; } return StructuredSelection . EMPTY ; } public void setSelection ( ISelection selection ) { if ( fViewerInFocus != null ) { fViewerInFocus . setSelection ( selection ) ; } } public void setSelection ( ISelection selection , boolean reveal ) { if ( fViewerInFocus != null ) { fViewerInFocus . setSelection ( selection , reveal ) ; } } public StructuredViewer getViewerInFocus ( ) { return fViewerInFocus ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . ui . ISelectionListener ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . texteditor . ITextEditor ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; public class SelectionListenerWithASTManager { private static SelectionListenerWithASTManager fgDefault ; public static SelectionListenerWithASTManager getDefault ( ) { if ( fgDefault == null ) { fgDefault = new SelectionListenerWithASTManager ( ) ; } return fgDefault ; } private final static class PartListenerGroup { private ITextEditor fPart ; private ISelectionListener fPostSelectionListener ; private ISelectionChangedListener fSelectionListener ; private Job fCurrentJob ; private ListenerList fAstListeners ; private final Object fJobLock = new Object ( ) ; public PartListenerGroup ( ITextEditor editorPart ) { fPart = editorPart ; fCurrentJob = null ; fAstListeners = new ListenerList ( ListenerList . IDENTITY ) ; fSelectionListener = new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { ISelection selection = event . getSelection ( ) ; if ( selection instanceof ITextSelection ) { fireSelectionChanged ( ( ITextSelection ) selection ) ; } } } ; fPostSelectionListener = new ISelectionListener ( ) { public void selectionChanged ( IWorkbenchPart part , ISelection selection ) { if ( part == fPart && selection instanceof ITextSelection ) firePostSelectionChanged ( ( ITextSelection ) selection ) ; } } ; } public boolean isEmpty ( ) { return fAstListeners . isEmpty ( ) ; } public void install ( ISelectionListenerWithAST listener ) { if ( isEmpty ( ) ) { fPart . getEditorSite ( ) . getPage ( ) . addPostSelectionListener ( fPostSelectionListener ) ; ISelectionProvider selectionProvider = fPart . getSelectionProvider ( ) ; if ( selectionProvider != null ) selectionProvider . addSelectionChangedListener ( fSelectionListener ) ; } fAstListeners . add ( listener ) ; } public void uninstall ( ISelectionListenerWithAST listener ) { fAstListeners . remove ( listener ) ; if ( isEmpty ( ) ) { fPart . getEditorSite ( ) . getPage ( ) . removePostSelectionListener ( fPostSelectionListener ) ; ISelectionProvider selectionProvider = fPart . getSelectionProvider ( ) ; if ( selectionProvider != null ) selectionProvider . removeSelectionChangedListener ( fSelectionListener ) ; } } public void fireSelectionChanged ( final ITextSelection selection ) { if ( fCurrentJob != null ) { fCurrentJob . cancel ( ) ; } } public void firePostSelectionChanged ( final ITextSelection selection ) { if ( fCurrentJob != null ) { fCurrentJob . cancel ( ) ; } final IRubyElement input = EditorUtility . getEditorInputRubyElement ( fPart , false ) ; if ( input == null ) { return ; } fCurrentJob = new Job ( RubyUIMessages . SelectionListenerWithASTManager_job_title ) { public IStatus run ( IProgressMonitor monitor ) { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } synchronized ( fJobLock ) { return calculateASTandInform ( input , selection , monitor ) ; } } } ; fCurrentJob . setPriority ( Job . DECORATE ) ; fCurrentJob . setSystem ( true ) ; fCurrentJob . schedule ( ) ; } protected IStatus calculateASTandInform ( IRubyElement input , ITextSelection selection , IProgressMonitor monitor ) { if ( monitor . isCanceled ( ) ) { return Status . CANCEL_STATUS ; } try { RootNode astRoot = ( RootNode ) RubyPlugin . getDefault ( ) . getASTProvider ( ) . getAST ( input , ASTProvider . WAIT_ACTIVE_ONLY , monitor ) ; if ( astRoot != null && ! monitor . isCanceled ( ) ) { Object [ ] listeners ; synchronized ( PartListenerGroup . this ) { listeners = fAstListeners . getListeners ( ) ; } for ( int i = ; i < listeners . length ; i ++ ) { ( ( ISelectionListenerWithAST ) listeners [ i ] ) . selectionChanged ( fPart , selection , astRoot ) ; if ( monitor . isCanceled ( ) ) { return Status . CANCEL_STATUS ; } } return Status . OK_STATUS ; } } catch ( OperationCanceledException e ) { } return Status . CANCEL_STATUS ; } } private Map fListenerGroups ; private SelectionListenerWithASTManager ( ) { fListenerGroups = new HashMap ( ) ; } public void addListener ( ITextEditor part , ISelectionListenerWithAST listener ) { synchronized ( this ) { PartListenerGroup partListener = ( PartListenerGroup ) fListenerGroups . get ( part ) ; if ( partListener == null ) { partListener = new PartListenerGroup ( part ) ; fListenerGroups . put ( part , partListener ) ; } partListener . install ( listener ) ; } } public void removeListener ( ITextEditor part , ISelectionListenerWithAST listener ) { synchronized ( this ) { PartListenerGroup partListener = ( PartListenerGroup ) fListenerGroups . get ( part ) ; if ( partListener != null ) { partListener . uninstall ( listener ) ; if ( partListener . isEmpty ( ) ) { fListenerGroups . remove ( part ) ; } } } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . ArrayList ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . LabelProviderChangedEvent ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . Widget ; import org . rubypeople . rdt . ui . IWorkingCopyProvider ; import org . rubypeople . rdt . ui . ProblemsLabelDecorator . ProblemsLabelChangedEvent ; public class ProblemTableViewer extends TableViewer implements ResourceToItemsMapper . IContentViewerAccessor { protected ResourceToItemsMapper fResourceToItemsMapper ; public ProblemTableViewer ( Composite parent ) { super ( parent ) ; initMapper ( ) ; } public ProblemTableViewer ( Composite parent , int style ) { super ( parent , style ) ; initMapper ( ) ; } public ProblemTableViewer ( Table table ) { super ( table ) ; initMapper ( ) ; } private void initMapper ( ) { fResourceToItemsMapper = new ResourceToItemsMapper ( this ) ; } public void doUpdateItem ( Widget item ) { doUpdateItem ( item , item . getData ( ) , true ) ; } protected void mapElement ( Object element , Widget item ) { super . mapElement ( element , item ) ; if ( item instanceof Item ) { fResourceToItemsMapper . addToMap ( element , ( Item ) item ) ; } } protected void unmapElement ( Object element , Widget item ) { if ( item instanceof Item ) { fResourceToItemsMapper . removeFromMap ( element , ( Item ) item ) ; } super . unmapElement ( element , item ) ; } protected void unmapAllElements ( ) { fResourceToItemsMapper . clearMap ( ) ; super . unmapAllElements ( ) ; } protected void handleLabelProviderChanged ( LabelProviderChangedEvent event ) { if ( event instanceof ProblemsLabelChangedEvent ) { ProblemsLabelChangedEvent e = ( ProblemsLabelChangedEvent ) event ; if ( ! e . isMarkerChange ( ) && canIgnoreChangesFromAnnotionModel ( ) ) { return ; } } Object [ ] changed = event . getElements ( ) ; if ( changed != null && ! fResourceToItemsMapper . isEmpty ( ) ) { ArrayList others = new ArrayList ( changed . length ) ; for ( int i = ; i < changed . length ; i ++ ) { Object curr = changed [ i ] ; if ( curr instanceof IResource ) { fResourceToItemsMapper . resourceChanged ( ( IResource ) curr ) ; } else { others . add ( curr ) ; } } if ( others . isEmpty ( ) ) { return ; } event = new LabelProviderChangedEvent ( ( IBaseLabelProvider ) event . getSource ( ) , others . toArray ( ) ) ; } super . handleLabelProviderChanged ( event ) ; } private boolean canIgnoreChangesFromAnnotionModel ( ) { Object contentProvider = getContentProvider ( ) ; return contentProvider instanceof IWorkingCopyProvider && ! ( ( IWorkingCopyProvider ) contentProvider ) . providesWorkingCopies ( ) ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . ui . IEditorPart ; import org . jruby . ast . RootNode ; public interface ISelectionListenerWithAST { void selectionChanged ( IEditorPart part , ITextSelection selection , RootNode astRoot ) ; } package org . rubypeople . rdt . internal . ui . viewsupport ; public interface IViewPartInputProvider { public Object getViewPartInput ( ) ; } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; public class MemberFilter extends ViewerFilter { public static final int FILTER_NONPUBLIC = ; public static final int FILTER_STATIC = ; public static final int FILTER_FIELDS = ; public static final int FILTER_LOCALTYPES = ; private int fFilterProperties ; public final void addFilter ( int filter ) { fFilterProperties |= filter ; } public final void removeFilter ( int filter ) { fFilterProperties &= ( - ^ filter ) ; } public final boolean hasFilter ( int filter ) { return ( fFilterProperties & filter ) != ; } public boolean isFilterProperty ( Object element , Object property ) { return false ; } public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( element instanceof IMember ) { IMember member = ( IMember ) element ; int memberType = member . getElementType ( ) ; if ( hasFilter ( FILTER_FIELDS ) ) { if ( ( memberType == IRubyElement . CLASS_VAR ) || ( memberType == IRubyElement . CONSTANT ) || ( memberType == IRubyElement . INSTANCE_VAR ) || ( memberType == IRubyElement . LOCAL_VARIABLE ) ) { return false ; } } if ( member . isType ( IRubyElement . METHOD ) ) { IMethod method = ( IMethod ) member ; try { if ( hasFilter ( FILTER_NONPUBLIC ) && ! Flags . isPublic ( method . getVisibility ( ) ) ) { return false ; } } catch ( RubyModelException e ) { return true ; } if ( hasFilter ( FILTER_STATIC ) && method . isSingleton ( ) ) { return false ; } } if ( hasFilter ( FILTER_LOCALTYPES ) && ( memberType == IRubyElement . LOCAL_VARIABLE || memberType == IRubyElement . DYNAMIC_VAR ) ) { return false ; } } return true ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . ui . ProblemsLabelDecorator ; public class TreeHierarchyLayoutProblemsDecorator extends ProblemsLabelDecorator { private boolean fIsFlatLayout ; public TreeHierarchyLayoutProblemsDecorator ( ) { this ( false ) ; } public TreeHierarchyLayoutProblemsDecorator ( boolean isFlatLayout ) { super ( null ) ; fIsFlatLayout = isFlatLayout ; } protected int computePackageAdornmentFlags ( ISourceFolder fragment ) { if ( ! fIsFlatLayout && ! fragment . isDefaultPackage ( ) ) { return super . computeAdornmentFlags ( fragment . getResource ( ) ) ; } return super . computeAdornmentFlags ( fragment ) ; } protected int computeAdornmentFlags ( Object element ) { if ( element instanceof ISourceFolder ) { return computePackageAdornmentFlags ( ( ISourceFolder ) element ) ; } return super . computeAdornmentFlags ( element ) ; } public void setIsFlatLayout ( boolean state ) { fIsFlatLayout = state ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; public class SourcePositionSorter extends ViewerSorter { public int compare ( Viewer viewer , Object e1 , Object e2 ) { if ( ! ( e1 instanceof ISourceReference ) ) return ; if ( ! ( e2 instanceof ISourceReference ) ) return ; if ( ( ( IRubyElement ) e1 ) . getParent ( ) != ( ( IRubyElement ) e2 ) . getParent ( ) ) return ; try { ISourceRange sr1 = ( ( ISourceReference ) e1 ) . getSourceRange ( ) ; ISourceRange sr2 = ( ( ISourceReference ) e2 ) . getSourceRange ( ) ; if ( sr1 == null || sr2 == null ) return ; return sr1 . getOffset ( ) - sr2 . getOffset ( ) ; } catch ( RubyModelException e ) { return ; } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . swt . widgets . Control ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; public class FilterUpdater implements IResourceChangeListener { private StructuredViewer fViewer ; public FilterUpdater ( StructuredViewer viewer ) { Assert . isNotNull ( viewer ) ; fViewer = viewer ; } public void resourceChanged ( IResourceChangeEvent event ) { IResourceDelta delta = event . getDelta ( ) ; if ( delta == null ) return ; IResourceDelta [ ] projDeltas = delta . getAffectedChildren ( IResourceDelta . CHANGED ) ; for ( int i = ; i < projDeltas . length ; i ++ ) { IResourceDelta pDelta = projDeltas [ i ] ; if ( ( pDelta . getFlags ( ) & IResourceDelta . DESCRIPTION ) != ) { final Control ctrl = fViewer . getControl ( ) ; if ( ctrl != null && ! ctrl . isDisposed ( ) ) { ctrl . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { if ( ! ctrl . isDisposed ( ) ) fViewer . refresh ( false ) ; } } ) ; } } } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . jface . util . Assert ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Image ; public class ImageDisposer implements DisposeListener { private Image [ ] fImages ; public ImageDisposer ( Image image ) { this ( new Image [ ] { image } ) ; } public ImageDisposer ( Image [ ] images ) { Assert . isNotNull ( images ) ; fImages = images ; } public void widgetDisposed ( DisposeEvent e ) { if ( fImages != null ) { for ( int i = ; i < fImages . length ; i ++ ) { fImages [ i ] . dispose ( ) ; } } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . jface . viewers . DecoratingLabelProvider ; import org . eclipse . jface . viewers . IColorProvider ; import org . eclipse . swt . graphics . Color ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . ui . ProblemsLabelDecorator ; public class DecoratingRubyLabelProvider extends DecoratingLabelProvider implements IColorProvider { public DecoratingRubyLabelProvider ( RubyUILabelProvider labelProvider ) { this ( labelProvider , true ) ; } public DecoratingRubyLabelProvider ( RubyUILabelProvider labelProvider , boolean errorTick ) { super ( labelProvider , PlatformUI . getWorkbench ( ) . getDecoratorManager ( ) . getLabelDecorator ( ) ) ; if ( errorTick ) { labelProvider . addLabelDecorator ( new ProblemsLabelDecorator ( null ) ) ; } } public Color getForeground ( Object element ) { return ( ( IColorProvider ) getLabelProvider ( ) ) . getForeground ( element ) ; } public Color getBackground ( Object element ) { return ( ( IColorProvider ) getLabelProvider ( ) ) . getBackground ( element ) ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . Iterator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . graphics . TextLayout ; import org . eclipse . swt . graphics . TextStyle ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . TableItem ; import org . eclipse . swt . widgets . TreeItem ; public abstract class OwnerDrawSupport implements Listener { private TextLayout fTextLayout ; private final Control fControl ; public OwnerDrawSupport ( Control control ) { fControl = control ; fTextLayout = new TextLayout ( control . getDisplay ( ) ) ; control . addListener ( SWT . PaintItem , this ) ; control . addListener ( SWT . EraseItem , this ) ; control . addListener ( SWT . Dispose , this ) ; } public abstract ColoredString getColoredLabel ( Item item ) ; public abstract Color getColor ( String foregroundColorName , Display display ) ; public void handleEvent ( Event event ) { if ( event . type == SWT . PaintItem ) { performPaint ( event ) ; } else if ( event . type == SWT . EraseItem ) { performErase ( event ) ; } else if ( event . type == SWT . Dispose ) { dispose ( ) ; } } private void performErase ( Event event ) { event . detail &= ~ SWT . FOREGROUND ; } private void performPaint ( Event event ) { Item item = ( Item ) event . item ; GC gc = event . gc ; ColoredString coloredLabel = getColoredLabel ( item ) ; boolean isSelected = ( event . detail & SWT . SELECTED ) != && fControl . isFocusControl ( ) ; if ( item instanceof TreeItem ) { TreeItem treeItem = ( TreeItem ) item ; Image image = treeItem . getImage ( event . index ) ; if ( image != null ) { processImage ( image , gc , treeItem . getImageBounds ( event . index ) ) ; } Rectangle textBounds = treeItem . getBounds ( event . index ) ; Font font = treeItem . getFont ( event . index ) ; processColoredLabel ( coloredLabel , gc , textBounds , isSelected , font ) ; Rectangle bounds = treeItem . getBounds ( ) ; if ( ( event . detail & SWT . FOCUSED ) != ) { gc . drawFocus ( bounds . x , bounds . y , bounds . width , bounds . height ) ; } } else if ( item instanceof TableItem ) { TableItem tableItem = ( TableItem ) item ; Image image = tableItem . getImage ( event . index ) ; if ( image != null ) { processImage ( image , gc , tableItem . getImageBounds ( event . index ) ) ; } Rectangle textBounds = tableItem . getBounds ( event . index ) ; Font font = tableItem . getFont ( event . index ) ; processColoredLabel ( coloredLabel , gc , textBounds , isSelected , font ) ; Rectangle bounds = tableItem . getBounds ( ) ; if ( ( event . detail & SWT . FOCUSED ) != ) { gc . drawFocus ( bounds . x , bounds . y , bounds . width , bounds . height ) ; } } } private void processImage ( Image image , GC gc , Rectangle imageBounds ) { Rectangle bounds = image . getBounds ( ) ; int x = imageBounds . x + Math . max ( , ( imageBounds . width - bounds . width ) / ) ; int y = imageBounds . y + Math . max ( , ( imageBounds . height - bounds . height ) / ) ; gc . drawImage ( image , x , y ) ; } private void processColoredLabel ( ColoredString richLabel , GC gc , Rectangle textBounds , boolean isSelected , Font font ) { String text = richLabel . getString ( ) ; fTextLayout . setText ( text ) ; fTextLayout . setFont ( font ) ; if ( ! isSelected ) { Display display = ( Display ) gc . getDevice ( ) ; Iterator ranges = richLabel . getRanges ( ) ; while ( ranges . hasNext ( ) ) { ColoredString . StyleRange curr = ( ColoredString . StyleRange ) ranges . next ( ) ; ColoredString . Style style = curr . style ; if ( style != null ) { Color foreground = getColor ( style . getForegroundColorName ( ) , display ) ; TextStyle textStyle = new TextStyle ( null , foreground , null ) ; fTextLayout . setStyle ( textStyle , curr . offset , curr . offset + curr . length - ) ; } } } Rectangle bounds = fTextLayout . getBounds ( ) ; int x = textBounds . x ; int y = textBounds . y + Math . max ( , ( textBounds . height - bounds . height ) / ) ; fTextLayout . draw ( gc , x , y ) ; fTextLayout . setText ( "" ) ; } public void dispose ( ) { if ( fTextLayout != null ) { fTextLayout . dispose ( ) ; fTextLayout = null ; } if ( ! fControl . isDisposed ( ) ) { fControl . removeListener ( SWT . PaintItem , this ) ; fControl . removeListener ( SWT . EraseItem , this ) ; fControl . removeListener ( SWT . Dispose , this ) ; } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . ILocalVariable ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; import org . rubypeople . rdt . internal . ui . viewsupport . ColoredString . Style ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class ColoredRubyElementLabels { public static final Style QUALIFIER_STYLE = new Style ( ColoredViewersManager . QUALIFIER_COLOR_NAME ) ; public static final Style COUNTER_STYLE = new Style ( ColoredViewersManager . COUNTER_COLOR_NAME ) ; public static final Style DECORATIONS_STYLE = new Style ( ColoredViewersManager . DECORATIONS_COLOR_NAME ) ; private static final Style APPENDED_TYPE_STYLE = DECORATIONS_STYLE ; public final static long COLORIZE = << ; private final static long QUALIFIER_FLAGS = RubyElementLabels . P_COMPRESSED | RubyElementLabels . USE_RESOLVED ; private static final boolean getFlag ( long flags , long flag ) { return ( flags & flag ) != ; } public static ColoredString getTextLabel ( Object obj , long flags ) { if ( obj instanceof IRubyElement ) { return getElementLabel ( ( IRubyElement ) obj , flags ) ; } else if ( obj instanceof IResource ) { return new ColoredString ( ( ( IResource ) obj ) . getName ( ) ) ; } else if ( obj instanceof LoadPathContainer ) { LoadPathContainer container = ( LoadPathContainer ) obj ; return getContainerEntryLabel ( container . getLoadpathEntry ( ) . getPath ( ) , container . getRubyProject ( ) ) ; } return new ColoredString ( RubyElementLabels . getTextLabel ( obj , flags ) ) ; } public static ColoredString getElementLabel ( IRubyElement element , long flags ) { ColoredString result = new ColoredString ( ) ; getElementLabel ( element , flags , result ) ; return result ; } public static void getElementLabel ( IRubyElement element , long flags , ColoredString result ) { int type = element . getElementType ( ) ; ISourceFolderRoot root = null ; if ( type != IRubyElement . RUBY_MODEL && type != IRubyElement . RUBY_PROJECT && type != IRubyElement . SOURCE_FOLDER_ROOT ) root = RubyModelUtil . getSourceFolderRoot ( element ) ; if ( root != null && getFlag ( flags , RubyElementLabels . PREPEND_ROOT_PATH ) ) { getSourceFolderRootLabel ( root , RubyElementLabels . ROOT_QUALIFIED , result ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; } switch ( type ) { case IRubyElement . METHOD : getMethodLabel ( ( IMethod ) element , flags , result ) ; break ; case IRubyElement . FIELD : getFieldLabel ( ( IField ) element , flags , result ) ; break ; case IRubyElement . LOCAL_VARIABLE : getLocalVariableLabel ( ( ILocalVariable ) element , flags , result ) ; break ; case IRubyElement . TYPE : getTypeLabel ( ( IType ) element , flags , result ) ; break ; case IRubyElement . SCRIPT : getCompilationUnitLabel ( ( IRubyScript ) element , flags , result ) ; break ; case IRubyElement . SOURCE_FOLDER : getSourceFolderLabel ( ( ISourceFolder ) element , flags , result ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : getSourceFolderRootLabel ( ( ISourceFolderRoot ) element , flags , result ) ; break ; case IRubyElement . IMPORT_CONTAINER : case IRubyElement . IMPORT_DECLARATION : getDeclarationLabel ( element , flags , result ) ; break ; case IRubyElement . RUBY_PROJECT : case IRubyElement . RUBY_MODEL : result . append ( element . getElementName ( ) ) ; break ; default : result . append ( element . getElementName ( ) ) ; } if ( root != null && getFlag ( flags , RubyElementLabels . APPEND_ROOT_PATH ) ) { int offset = result . length ( ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; getSourceFolderRootLabel ( root , RubyElementLabels . ROOT_QUALIFIED , result ) ; if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } public static void getMethodLabel ( IMethod method , long flags , ColoredString result ) { try { if ( getFlag ( flags , RubyElementLabels . M_FULLY_QUALIFIED ) ) { getTypeLabel ( method . getDeclaringType ( ) , RubyElementLabels . T_NAME_FULLY_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , result ) ; result . append ( '' ) ; } result . append ( method . getElementName ( ) ) ; result . append ( '' ) ; if ( getFlag ( flags , RubyElementLabels . M_PARAMETER_NAMES ) ) { int nParams = ; boolean renderVarargs = false ; String [ ] names = null ; if ( getFlag ( flags , RubyElementLabels . M_PARAMETER_NAMES ) && method . exists ( ) ) { names = method . getParameterNames ( ) ; nParams = names . length ; } for ( int i = ; i < nParams ; i ++ ) { if ( i > ) { result . append ( RubyElementLabels . COMMA_STRING ) ; } if ( names != null ) { result . append ( names [ i ] ) ; } } } result . append ( '' ) ; if ( getFlag ( flags , RubyElementLabels . M_CATEGORY ) && method . exists ( ) ) getCategoryLabel ( method , result ) ; if ( getFlag ( flags , RubyElementLabels . M_POST_QUALIFIED ) ) { int offset = result . length ( ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; getTypeLabel ( method . getDeclaringType ( ) , RubyElementLabels . T_NAME_FULLY_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , result ) ; if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } private static void getCategoryLabel ( IMember member , ColoredString result ) throws RubyModelException { } public static void getFieldLabel ( IField field , long flags , ColoredString result ) { try { if ( getFlag ( flags , RubyElementLabels . F_FULLY_QUALIFIED ) ) { getTypeLabel ( field . getDeclaringType ( ) , RubyElementLabels . T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , result ) ; result . append ( '' ) ; } result . append ( field . getElementName ( ) ) ; if ( getFlag ( flags , RubyElementLabels . F_CATEGORY ) && field . exists ( ) ) getCategoryLabel ( field , result ) ; if ( getFlag ( flags , RubyElementLabels . F_POST_QUALIFIED ) ) { int offset = result . length ( ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; getTypeLabel ( field . getDeclaringType ( ) , RubyElementLabels . T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , result ) ; if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } public static void getLocalVariableLabel ( ILocalVariable localVariable , long flags , ColoredString result ) { if ( getFlag ( flags , RubyElementLabels . F_FULLY_QUALIFIED ) ) { getElementLabel ( localVariable . getParent ( ) , RubyElementLabels . M_FULLY_QUALIFIED | RubyElementLabels . T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , result ) ; result . append ( '' ) ; } result . append ( localVariable . getElementName ( ) ) ; if ( getFlag ( flags , RubyElementLabels . F_POST_QUALIFIED ) ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; getElementLabel ( localVariable . getParent ( ) , RubyElementLabels . M_FULLY_QUALIFIED | RubyElementLabels . T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , result ) ; } } public static void getTypeLabel ( IType type , long flags , ColoredString result ) { if ( getFlag ( flags , RubyElementLabels . T_FILENAME_QUALIFIED ) ) { ISourceFolder folder = type . getSourceFolder ( ) ; if ( ! folder . isDefaultPackage ( ) ) { getSourceFolderLabel ( folder , ( flags & QUALIFIER_FLAGS ) , result ) ; result . append ( '' ) ; } getCompilationUnitLabel ( type . getRubyScript ( ) , ( flags & QUALIFIER_FLAGS ) , result ) ; result . append ( '' ) ; } if ( getFlag ( flags , RubyElementLabels . T_FILENAME_QUALIFIED | RubyElementLabels . T_NAME_FULLY_QUALIFIED ) ) { IType declaringType = type . getDeclaringType ( ) ; if ( declaringType != null ) { getTypeLabel ( declaringType , RubyElementLabels . T_NAME_FULLY_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , result ) ; result . append ( "" ) ; } int parentType = type . getParent ( ) . getElementType ( ) ; if ( parentType == IRubyElement . METHOD || parentType == IRubyElement . FIELD ) { getElementLabel ( type . getParent ( ) , , result ) ; result . append ( '' ) ; } } String typeName = type . getElementName ( ) ; if ( typeName . length ( ) == ) { try { String supertypeName = type . getSuperclassName ( ) ; typeName = Messages . format ( RubyUIMessages . RubyElementLabels_anonym_type , supertypeName ) ; } catch ( RubyModelException e ) { typeName = RubyUIMessages . RubyElementLabels_anonym ; } } result . append ( typeName ) ; if ( getFlag ( flags , RubyElementLabels . T_CATEGORY ) && type . exists ( ) ) { try { getCategoryLabel ( type , result ) ; } catch ( RubyModelException e ) { } } if ( getFlag ( flags , RubyElementLabels . T_POST_QUALIFIED ) ) { int offset = result . length ( ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; IType declaringType = type . getDeclaringType ( ) ; if ( declaringType != null ) { getTypeLabel ( declaringType , RubyElementLabels . T_NAME_FULLY_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , result ) ; int parentType = type . getParent ( ) . getElementType ( ) ; if ( parentType == IRubyElement . METHOD || parentType == IRubyElement . FIELD ) { result . append ( '' ) ; getElementLabel ( type . getParent ( ) , , result ) ; } ISourceFolder folder = type . getSourceFolder ( ) ; if ( ! folder . isDefaultPackage ( ) ) { getSourceFolderLabel ( folder , flags & QUALIFIER_FLAGS , result ) ; result . append ( '' ) ; } getCompilationUnitLabel ( type . getRubyScript ( ) , ( flags & QUALIFIER_FLAGS ) , result ) ; try { int other = type . getNameRange ( ) . getOffset ( ) ; result . append ( "" + other ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } else { getSourceFolderLabel ( type . getSourceFolder ( ) , flags & QUALIFIER_FLAGS , result ) ; } if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } public static void getDeclarationLabel ( IRubyElement declaration , long flags , ColoredString result ) { if ( getFlag ( flags , RubyElementLabels . D_QUALIFIED ) ) { IRubyElement openable = ( IRubyElement ) declaration . getOpenable ( ) ; if ( openable != null ) { result . append ( getElementLabel ( openable , RubyElementLabels . CF_QUALIFIED | RubyElementLabels . CU_QUALIFIED | ( flags & QUALIFIER_FLAGS ) ) ) ; result . append ( '' ) ; } } if ( declaration . getElementType ( ) == IRubyElement . IMPORT_CONTAINER ) { result . append ( RubyUIMessages . RubyElementLabels_import_container ) ; } else { result . append ( declaration . getElementName ( ) ) ; } if ( getFlag ( flags , RubyElementLabels . D_POST_QUALIFIED ) ) { int offset = result . length ( ) ; IRubyElement openable = ( IRubyElement ) declaration . getOpenable ( ) ; if ( openable != null ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( getElementLabel ( openable , RubyElementLabels . CF_QUALIFIED | RubyElementLabels . CU_QUALIFIED | ( flags & QUALIFIER_FLAGS ) ) ) ; } if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } public static void getCompilationUnitLabel ( IRubyScript cu , long flags , ColoredString result ) { if ( getFlag ( flags , RubyElementLabels . CU_QUALIFIED ) ) { ISourceFolder pack = ( ISourceFolder ) cu . getParent ( ) ; if ( ! pack . isDefaultPackage ( ) ) { getSourceFolderLabel ( pack , ( flags & QUALIFIER_FLAGS ) , result ) ; result . append ( '' ) ; } } result . append ( cu . getElementName ( ) ) ; if ( getFlag ( flags , RubyElementLabels . CU_POST_QUALIFIED ) ) { int offset = result . length ( ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; getSourceFolderLabel ( ( ISourceFolder ) cu . getParent ( ) , flags & QUALIFIER_FLAGS , result ) ; if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } public static void getSourceFolderLabel ( ISourceFolder pack , long flags , ColoredString result ) { if ( getFlag ( flags , RubyElementLabels . P_QUALIFIED ) ) { getSourceFolderRootLabel ( ( ISourceFolderRoot ) pack . getParent ( ) , RubyElementLabels . ROOT_QUALIFIED , result ) ; result . append ( '' ) ; } if ( pack . isDefaultPackage ( ) ) { result . append ( RubyElementLabels . DEFAULT_PACKAGE ) ; } else if ( getFlag ( flags , RubyElementLabels . P_COMPRESSED ) ) { StringBuffer buf = new StringBuffer ( ) ; RubyElementLabels . getSourceFolderLabel ( pack , RubyElementLabels . P_COMPRESSED , buf ) ; result . append ( buf . toString ( ) ) ; } else { result . append ( pack . getElementName ( ) ) ; } if ( getFlag ( flags , RubyElementLabels . P_POST_QUALIFIED ) ) { int offset = result . length ( ) ; result . append ( RubyElementLabels . CONCAT_STRING ) ; getSourceFolderRootLabel ( ( ISourceFolderRoot ) pack . getParent ( ) , RubyElementLabels . ROOT_QUALIFIED , result ) ; if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } public static void getSourceFolderRootLabel ( ISourceFolderRoot root , long flags , ColoredString result ) { if ( root . isArchive ( ) ) getArchiveLabel ( root , flags , result ) ; else getFolderLabel ( root , flags , result ) ; } private static void getArchiveLabel ( ISourceFolderRoot root , long flags , ColoredString result ) { if ( getFlag ( flags , RubyElementLabels . ROOT_VARIABLE ) && getVariableLabel ( root , flags , result ) ) return ; boolean external = root . isExternal ( ) ; if ( external ) getExternalArchiveLabel ( root , flags , result ) ; else getInternalArchiveLabel ( root , flags , result ) ; } private static boolean getVariableLabel ( ISourceFolderRoot root , long flags , ColoredString result ) { try { ILoadpathEntry rawEntry = root . getRawLoadpathEntry ( ) ; if ( rawEntry != null && rawEntry . getEntryKind ( ) == ILoadpathEntry . CPE_VARIABLE ) { IPath path = rawEntry . getPath ( ) . makeRelative ( ) ; int offset = result . length ( ) ; if ( getFlag ( flags , RubyElementLabels . REFERENCED_ROOT_POST_QUALIFIED ) ) { int segements = path . segmentCount ( ) ; if ( segements > ) { result . append ( path . segment ( segements - ) ) ; if ( segements > ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( path . removeLastSegments ( ) . toOSString ( ) ) ; } } else { result . append ( path . toString ( ) ) ; } } else { result . append ( path . toString ( ) ) ; } result . append ( RubyElementLabels . CONCAT_STRING ) ; if ( root . isExternal ( ) ) result . append ( root . getPath ( ) . toOSString ( ) ) ; else result . append ( root . getPath ( ) . makeRelative ( ) . toString ( ) ) ; if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } return true ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return false ; } private static void getExternalArchiveLabel ( ISourceFolderRoot root , long flags , ColoredString result ) { IPath path = root . getPath ( ) ; if ( getFlag ( flags , RubyElementLabels . REFERENCED_ROOT_POST_QUALIFIED ) ) { int segements = path . segmentCount ( ) ; if ( segements > ) { result . append ( path . segment ( segements - ) ) ; int offset = result . length ( ) ; if ( segements > || path . getDevice ( ) != null ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( path . removeLastSegments ( ) . toOSString ( ) ) ; } if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } else { result . append ( path . toOSString ( ) ) ; } } else { result . append ( path . toOSString ( ) ) ; } } private static void getInternalArchiveLabel ( ISourceFolderRoot root , long flags , ColoredString result ) { IResource resource = root . getResource ( ) ; boolean rootQualified = getFlag ( flags , RubyElementLabels . ROOT_QUALIFIED ) ; boolean referencedQualified = getFlag ( flags , RubyElementLabels . REFERENCED_ROOT_POST_QUALIFIED ) && isReferenced ( root ) ; if ( rootQualified ) { result . append ( root . getPath ( ) . makeRelative ( ) . toString ( ) ) ; } else { result . append ( root . getElementName ( ) ) ; int offset = result . length ( ) ; if ( referencedQualified ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( resource . getParent ( ) . getFullPath ( ) . makeRelative ( ) . toString ( ) ) ; } else if ( getFlag ( flags , RubyElementLabels . ROOT_POST_QUALIFIED ) ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( root . getParent ( ) . getPath ( ) . makeRelative ( ) . toString ( ) ) ; } else { return ; } if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } private static void getFolderLabel ( ISourceFolderRoot root , long flags , ColoredString result ) { IResource resource = root . getResource ( ) ; boolean rootQualified = getFlag ( flags , RubyElementLabels . ROOT_QUALIFIED ) ; boolean referencedQualified = getFlag ( flags , RubyElementLabels . REFERENCED_ROOT_POST_QUALIFIED ) && isReferenced ( root ) ; if ( rootQualified ) { result . append ( root . getPath ( ) . makeRelative ( ) . toString ( ) ) ; } else { if ( resource != null ) { IPath projectRelativePath = resource . getProjectRelativePath ( ) ; if ( projectRelativePath . segmentCount ( ) == ) { result . append ( resource . getName ( ) ) ; referencedQualified = false ; } else { result . append ( projectRelativePath . toString ( ) ) ; } } else result . append ( root . getElementName ( ) ) ; int offset = result . length ( ) ; if ( referencedQualified ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( resource . getProject ( ) . getName ( ) ) ; } else if ( getFlag ( flags , RubyElementLabels . ROOT_POST_QUALIFIED ) ) { result . append ( RubyElementLabels . CONCAT_STRING ) ; result . append ( root . getParent ( ) . getElementName ( ) ) ; } else { return ; } if ( getFlag ( flags , COLORIZE ) ) { result . colorize ( offset , result . length ( ) - offset , QUALIFIER_STYLE ) ; } } } private static boolean isReferenced ( ISourceFolderRoot root ) { IResource resource = root . getResource ( ) ; if ( resource != null ) { IProject jarProject = resource . getProject ( ) ; IProject container = root . getRubyProject ( ) . getProject ( ) ; return ! container . equals ( jarProject ) ; } return false ; } public static ColoredString getContainerEntryLabel ( IPath containerPath , IRubyProject project ) { try { ILoadpathContainer container = RubyCore . getLoadpathContainer ( containerPath , project ) ; String description = null ; if ( container != null ) { description = container . getDescription ( ) ; } if ( description == null ) { LoadpathContainerInitializer initializer = RubyCore . getLoadpathContainerInitializer ( containerPath . segment ( ) ) ; if ( initializer != null ) { description = initializer . getDescription ( containerPath , project ) ; } } if ( description != null ) { ColoredString str = new ColoredString ( description ) ; if ( containerPath . segmentCount ( ) > && RubyRuntime . RUBY_CONTAINER . equals ( containerPath . segment ( ) ) ) { int index = description . indexOf ( '' ) ; if ( index != - ) { str . colorize ( index , description . length ( ) - index , DECORATIONS_STYLE ) ; } } return str ; } } catch ( RubyModelException e ) { } return new ColoredString ( containerPath . toString ( ) ) ; } public static ColoredString decorateColoredString ( ColoredString string , String decorated , Style color ) { String label = string . getString ( ) ; int originalStart = decorated . indexOf ( label ) ; if ( originalStart == - ) { return new ColoredString ( decorated ) ; } if ( originalStart > ) { ColoredString newString = new ColoredString ( decorated . substring ( , originalStart ) , color ) ; newString . append ( string ) ; string = newString ; } if ( decorated . length ( ) > originalStart + label . length ( ) ) { return string . append ( decorated . substring ( originalStart + label . length ( ) ) , color ) ; } return string ; } } package org . rubypeople . rdt . internal . ui . viewsupport ; import java . util . ArrayList ; import org . eclipse . core . resources . IStorage ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . util . ListenerList ; import org . eclipse . jface . util . SafeRunnable ; import org . eclipse . jface . viewers . IColorProvider ; import org . eclipse . jface . viewers . ILabelDecorator ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . LabelProviderChangedEvent ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class RubyUILabelProvider implements ILabelProvider , IColorProvider { protected ListenerList fListeners = new ListenerList ( ) ; protected RubyElementImageProvider fImageLabelProvider ; protected StorageLabelProvider fStorageLabelProvider ; private ArrayList fLabelDecorators ; private int fImageFlags ; private long fTextFlags ; public RubyUILabelProvider ( ) { this ( RubyElementLabels . ALL_DEFAULT , RubyElementImageProvider . OVERLAY_ICONS ) ; } public RubyUILabelProvider ( long textFlags , int imageFlags ) { fImageLabelProvider = new RubyElementImageProvider ( ) ; fLabelDecorators = null ; fStorageLabelProvider = new StorageLabelProvider ( ) ; fImageFlags = imageFlags ; fTextFlags = textFlags ; } public void addLabelDecorator ( ILabelDecorator decorator ) { if ( fLabelDecorators == null ) { fLabelDecorators = new ArrayList ( ) ; } fLabelDecorators . add ( decorator ) ; } public final void setTextFlags ( long textFlags ) { fTextFlags = textFlags ; } public final void setImageFlags ( int imageFlags ) { fImageFlags = imageFlags ; } public final int getImageFlags ( ) { return fImageFlags ; } public final long getTextFlags ( ) { return fTextFlags ; } protected int evaluateImageFlags ( Object element ) { return getImageFlags ( ) ; } protected long evaluateTextFlags ( Object element ) { return getTextFlags ( ) ; } protected Image decorateImage ( Image image , Object element ) { if ( fLabelDecorators != null && image != null ) { for ( int i = ; i < fLabelDecorators . size ( ) ; i ++ ) { ILabelDecorator decorator = ( ILabelDecorator ) fLabelDecorators . get ( i ) ; image = decorator . decorateImage ( image , element ) ; } } return image ; } public Image getImage ( Object element ) { Image result = fImageLabelProvider . getImageLabel ( element , evaluateImageFlags ( element ) ) ; if ( result == null && ( element instanceof IStorage ) ) { result = fStorageLabelProvider . getImage ( element ) ; } return decorateImage ( result , element ) ; } protected String decorateText ( String text , Object element ) { if ( fLabelDecorators != null && text . length ( ) > ) { for ( int i = ; i < fLabelDecorators . size ( ) ; i ++ ) { ILabelDecorator decorator = ( ILabelDecorator ) fLabelDecorators . get ( i ) ; text = decorator . decorateText ( text , element ) ; } } return text ; } public String getText ( Object element ) { String result = RubyElementLabels . getTextLabel ( element , evaluateTextFlags ( element ) ) ; if ( result . length ( ) == && ( element instanceof IStorage ) ) { result = fStorageLabelProvider . getText ( element ) ; } return decorateText ( result , element ) ; } public void dispose ( ) { if ( fLabelDecorators != null ) { for ( int i = ; i < fLabelDecorators . size ( ) ; i ++ ) { ILabelDecorator decorator = ( ILabelDecorator ) fLabelDecorators . get ( i ) ; decorator . dispose ( ) ; } fLabelDecorators = null ; } fStorageLabelProvider . dispose ( ) ; fImageLabelProvider . dispose ( ) ; } public void addListener ( ILabelProviderListener listener ) { if ( fLabelDecorators != null ) { for ( int i = ; i < fLabelDecorators . size ( ) ; i ++ ) { ILabelDecorator decorator = ( ILabelDecorator ) fLabelDecorators . get ( i ) ; decorator . addListener ( listener ) ; } } fListeners . add ( listener ) ; } public boolean isLabelProperty ( Object element , String property ) { return true ; } public void removeListener ( ILabelProviderListener listener ) { if ( fLabelDecorators != null ) { for ( int i = ; i < fLabelDecorators . size ( ) ; i ++ ) { ILabelDecorator decorator = ( ILabelDecorator ) fLabelDecorators . get ( i ) ; decorator . removeListener ( listener ) ; } } fListeners . remove ( listener ) ; } public static ILabelDecorator [ ] getDecorators ( boolean errortick , ILabelDecorator extra ) { if ( errortick ) { if ( extra == null ) { return new ILabelDecorator [ ] { } ; } else { return new ILabelDecorator [ ] { extra } ; } } if ( extra != null ) { return new ILabelDecorator [ ] { extra } ; } return null ; } public Color getForeground ( Object element ) { return null ; } public Color getBackground ( Object element ) { return null ; } protected void fireLabelProviderChanged ( final LabelProviderChangedEvent event ) { Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; ++ i ) { final ILabelProviderListener l = ( ILabelProviderListener ) listeners [ i ] ; Platform . run ( new SafeRunnable ( ) { public void run ( ) { l . labelProviderChanged ( event ) ; } } ) ; } } } package org . rubypeople . rdt . internal . ui . viewsupport ; import org . eclipse . jface . viewers . ILabelProvider ; public interface IRichLabelProvider extends ILabelProvider { ColoredString getRichTextLabel ( Object object ) ; } package org . rubypeople . rdt . internal . ui . model ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . mapping . ResourceMapping ; import org . eclipse . core . resources . mapping . ResourceMappingContext ; import org . eclipse . core . resources . mapping . ResourceTraversal ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IProgressMonitor ; public final class RubyResourceMapping extends ResourceMapping { private final IResource fResource ; public RubyResourceMapping ( final IResource resource ) { Assert . isNotNull ( resource ) ; fResource = resource ; } public Object getModelObject ( ) { return fResource ; } public String getModelProviderId ( ) { return RubyModelProvider . RUBY_MODEL_PROVIDER_ID ; } public IProject [ ] getProjects ( ) { return new IProject [ ] { fResource . getProject ( ) } ; } public ResourceTraversal [ ] getTraversals ( final ResourceMappingContext context , final IProgressMonitor monitor ) { return new ResourceTraversal [ ] { new ResourceTraversal ( new IResource [ ] { fResource } , IResource . DEPTH_INFINITE , IResource . NONE ) } ; } } package org . rubypeople . rdt . internal . ui . model ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . mapping . ModelProvider ; import org . eclipse . core . resources . mapping . ResourceMapping ; import org . eclipse . core . resources . mapping . ResourceMappingContext ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . RubyElementResourceMapping ; public final class RubyModelProvider extends ModelProvider { public static final String RUBY_MODEL_PROVIDER_ID = "" ; public static IResource getResource ( final Object element ) { IResource resource = null ; if ( element instanceof IRubyElement ) { resource = ( ( IRubyElement ) element ) . getResource ( ) ; } else if ( element instanceof IResource ) { resource = ( IResource ) element ; } else if ( element instanceof IAdaptable ) { final IAdaptable adaptable = ( IAdaptable ) element ; final Object adapted = adaptable . getAdapter ( IResource . class ) ; if ( adapted instanceof IResource ) resource = ( IResource ) adapted ; } else { final Object adapted = Platform . getAdapterManager ( ) . getAdapter ( element , IResource . class ) ; if ( adapted instanceof IResource ) resource = ( IResource ) adapted ; } return resource ; } public RubyModelProvider ( ) { } public ResourceMapping [ ] getMappings ( final IResource resource , final ResourceMappingContext context , final IProgressMonitor monitor ) throws CoreException { final IRubyElement element = RubyCore . create ( resource ) ; if ( element != null ) return new ResourceMapping [ ] { RubyElementResourceMapping . create ( element ) } ; final Object adapted = resource . getAdapter ( ResourceMapping . class ) ; if ( adapted instanceof ResourceMapping ) return new ResourceMapping [ ] { ( ( ResourceMapping ) adapted ) } ; return new ResourceMapping [ ] { new RubyResourceMapping ( resource ) } ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . ui . IElementFactory ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPersistableElement ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; public class PersistableRubyElementFactory implements IElementFactory , IPersistableElement { private static final String KEY = "" ; private static final String FACTORY_ID = "" ; private IRubyElement fElement ; public PersistableRubyElementFactory ( ) { } public PersistableRubyElementFactory ( IRubyElement element ) { fElement = element ; } public IAdaptable createElement ( IMemento memento ) { String identifier = memento . getString ( KEY ) ; if ( identifier != null ) { return RubyCore . create ( identifier ) ; } return null ; } public String getFactoryId ( ) { return FACTORY_ID ; } public void saveState ( IMemento memento ) { memento . putString ( KEY , fElement . getHandleIdentifier ( ) ) ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . InvalidRegistryObjectException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . internal . ui . DebugUIPlugin ; import org . eclipse . debug . internal . ui . views . console . ProcessConsole ; import org . eclipse . debug . internal . ui . views . console . ProcessConsoleManager ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . debug . ui . console . IConsoleColorProvider ; import org . eclipse . ui . console . ConsolePlugin ; import org . eclipse . ui . console . IConsole ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . ITerminal ; public class AptanaProcessConsoleManager extends ProcessConsoleManager { private static final String RESET_AUTO_REMOVE_TERMINATED_LAUNCHES_PREF = "" ; private static final String TERMINALS_EXTENSION_POINT = "" ; public AptanaProcessConsoleManager ( ) { if ( RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( RESET_AUTO_REMOVE_TERMINATED_LAUNCHES_PREF ) ) return ; if ( ! DebugUIPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( IDebugUIConstants . PREF_AUTO_REMOVE_OLD_LAUNCHES ) ) { DebugUIPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( IDebugUIConstants . PREF_AUTO_REMOVE_OLD_LAUNCHES , true ) ; RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( RESET_AUTO_REMOVE_TERMINATED_LAUNCHES_PREF , true ) ; } } public void launchChanged ( final ILaunch launch ) { String terminalType = launch . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_USE_TERMINAL ) ; IConsole console = findConsole ( terminalType ) ; if ( console != null ) { if ( console instanceof ITerminal ) { ITerminal terminal = ( ITerminal ) console ; String projectName = launch . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME ) ; if ( projectName != null ) { IProject project = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; if ( project != null ) terminal . setProject ( project ) ; } String command = launch . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_TERMINAL_COMMAND ) ; if ( command != null ) { terminal . write ( IDebugUIConstants . ID_STANDARD_INPUT_STREAM , command + "" ) ; } if ( launch . getProcesses ( ) != null && launch . getProcesses ( ) . length > ) terminal . attach ( launch . getProcesses ( ) [ ] ) ; return ; } String toDisplay = getDisplayString ( launch ) ; if ( toDisplay == null ) toDisplay = terminalType ; Job job = new Job ( toDisplay ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { while ( ! launch . isTerminated ( ) ) { if ( monitor . isCanceled ( ) ) { try { launch . terminate ( ) ; } catch ( DebugException e ) { RubyPlugin . log ( e ) ; } return Status . CANCEL_STATUS ; } Thread . yield ( ) ; } monitor . done ( ) ; return Status . OK_STATUS ; } } ; job . setPriority ( Job . DECORATE ) ; job . schedule ( ) ; } String force = launch . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_FORCE_NO_CONSOLE ) ; if ( force != null && Boolean . parseBoolean ( force ) ) { handleButDontAddConsole ( launch ) ; } else { super . launchChanged ( launch ) ; } } private String getDisplayString ( ILaunch launch ) { StringBuffer buffer = new StringBuffer ( ) ; String fileName = launch . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME ) ; if ( fileName != null ) buffer . append ( fileName ) ; String args = launch . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROGRAM_ARGUMENTS ) ; if ( args != null ) buffer . append ( "" + args ) ; if ( buffer . toString ( ) . length ( ) == ) return null ; return buffer . toString ( ) ; } private IConsole findConsole ( String type ) { IConsole [ ] consoles = ConsolePlugin . getDefault ( ) . getConsoleManager ( ) . getConsoles ( ) ; for ( int i = ; i < consoles . length ; i ++ ) { if ( consoles [ i ] . getType ( ) != null && consoles [ i ] . getType ( ) . equals ( type ) ) return consoles [ i ] ; } ITerminal terminal = getTerminal ( type ) ; if ( terminal != null ) { ConsolePlugin . getDefault ( ) . getConsoleManager ( ) . addConsoles ( new IConsole [ ] { terminal } ) ; terminal . activate ( ) ; } return terminal ; } public static ITerminal getTerminal ( String id ) { try { IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; IConfigurationElement [ ] elements = registry . getConfigurationElementsFor ( TERMINALS_EXTENSION_POINT ) ; for ( int i = ; i < elements . length ; i ++ ) { String terminalId = elements [ i ] . getAttribute ( "" ) ; if ( terminalId . equals ( id ) ) return ( ITerminal ) elements [ i ] . createExecutableExtension ( "" ) ; } } catch ( InvalidRegistryObjectException e ) { RubyPlugin . log ( e ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } return null ; } public void launchAdded ( ILaunch launch ) { DebugPlugin . getDefault ( ) . getLaunchManager ( ) . removeLaunchListener ( DebugUIPlugin . getDefault ( ) . getProcessConsoleManager ( ) ) ; super . launchAdded ( launch ) ; } private void handleButDontAddConsole ( ILaunch launch ) { IProcess [ ] processes = launch . getProcesses ( ) ; for ( int i = ; i < processes . length ; i ++ ) { if ( getConsoleDocument ( processes [ i ] ) == null ) { IProcess process = processes [ i ] ; if ( process . getStreamsProxy ( ) == null ) { continue ; } ILaunchConfiguration launchConfiguration = launch . getLaunchConfiguration ( ) ; IConsoleColorProvider colorProvider = getColorProvider ( process . getAttribute ( IProcess . ATTR_PROCESS_TYPE ) ) ; String encoding = null ; try { if ( launchConfiguration != null ) { encoding = launchConfiguration . getAttribute ( DebugPlugin . ATTR_CONSOLE_ENCODING , ( String ) null ) ; } } catch ( CoreException e ) { } ProcessConsole pc = new ProcessConsole ( process , colorProvider , encoding ) ; } } } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectNature ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; public class ActionUtil { private ActionUtil ( ) { } public static boolean isProcessable ( Shell shell , IEditorPart editor ) { if ( editor == null ) return true ; IRubyElement input = SelectionConverter . getInput ( editor ) ; if ( input == null ) { MessageDialog . openInformation ( shell , ActionMessages . ActionUtil_notOnBuildPath_title , ActionMessages . ActionUtil_notOnBuildPath_message ) ; return false ; } return isProcessable ( shell , input ) ; } public static boolean isProcessable ( Shell shell , Object element ) { if ( ! ( element instanceof IRubyElement ) ) return true ; if ( isOnBuildPath ( ( IRubyElement ) element ) ) return true ; MessageDialog . openInformation ( shell , ActionMessages . ActionUtil_notOnBuildPath_title , ActionMessages . ActionUtil_notOnBuildPath_message ) ; return false ; } public static boolean isOnBuildPath ( IRubyElement element ) { if ( element . getElementType ( ) == IRubyElement . RUBY_PROJECT ) return true ; IRubyProject project = element . getRubyProject ( ) ; try { IProject resourceProject = project . getProject ( ) ; if ( resourceProject == null ) return false ; IProjectNature nature = resourceProject . getNature ( RubyCore . NATURE_ID ) ; if ( nature != null ) return true ; } catch ( CoreException e ) { } return false ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewerExtension5 ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . graphics . Point ; import org . eclipse . ui . internal . ide . actions . QuickMenuAction ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . text . RubyWordFinder ; public abstract class RDTQuickMenuAction extends QuickMenuAction { private RubyEditor fEditor ; public RDTQuickMenuAction ( String commandId ) { super ( commandId ) ; } public RDTQuickMenuAction ( RubyEditor editor , String commandId ) { super ( commandId ) ; fEditor = editor ; } protected Point computeMenuLocation ( StyledText text ) { if ( fEditor == null || text != fEditor . getViewer ( ) . getTextWidget ( ) ) return null ; return computeWordStart ( ) ; } private Point computeWordStart ( ) { ITextSelection selection = ( ITextSelection ) fEditor . getSelectionProvider ( ) . getSelection ( ) ; IRegion textRegion = RubyWordFinder . findWord ( fEditor . getViewer ( ) . getDocument ( ) , selection . getOffset ( ) ) ; if ( textRegion == null ) return null ; IRegion widgetRegion = modelRange2WidgetRange ( textRegion ) ; if ( widgetRegion == null ) return null ; int start = widgetRegion . getOffset ( ) ; StyledText styledText = fEditor . getViewer ( ) . getTextWidget ( ) ; Point result = styledText . getLocationAtOffset ( start ) ; result . y += styledText . getLineHeight ( start ) ; if ( ! styledText . getClientArea ( ) . contains ( result ) ) return null ; return result ; } private IRegion modelRange2WidgetRange ( IRegion region ) { ISourceViewer viewer = fEditor . getViewer ( ) ; if ( viewer instanceof ITextViewerExtension5 ) { ITextViewerExtension5 extension = ( ITextViewerExtension5 ) viewer ; return extension . modelRange2WidgetRange ( region ) ; } IRegion visibleRegion = viewer . getVisibleRegion ( ) ; int start = region . getOffset ( ) - visibleRegion . getOffset ( ) ; int end = start + region . getLength ( ) ; if ( end > visibleRegion . getLength ( ) ) end = visibleRegion . getLength ( ) ; return new Region ( start , end - start ) ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . dialogs . ElementListSelectionDialog ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; public class OpenActionUtil { public static void open ( Object element , boolean activate ) throws RubyModelException , PartInitException { IEditorPart part = EditorUtility . openInEditor ( element , activate ) ; if ( element instanceof IRubyElement ) EditorUtility . revealInEditor ( part , ( IRubyElement ) element ) ; } public static IRubyElement selectRubyElement ( IRubyElement [ ] elements , Shell shell , String title , String message ) { int nResults = elements . length ; if ( nResults == ) return null ; if ( nResults == ) return elements [ ] ; int flags = RubyElementLabelProvider . SHOW_DEFAULT | RubyElementLabelProvider . SHOW_POST_QUALIFIED | RubyElementLabelProvider . SHOW_ROOT ; ElementListSelectionDialog dialog = new ElementListSelectionDialog ( shell , new RubyElementLabelProvider ( flags ) ) ; dialog . setTitle ( title ) ; dialog . setMessage ( message ) ; dialog . setElements ( elements ) ; if ( dialog . open ( ) == Window . OK ) { Object [ ] selection = dialog . getResult ( ) ; if ( selection != null && selection . length > ) { nResults = selection . length ; for ( int i = ; i < nResults ; i ++ ) { Object current = selection [ i ] ; if ( current instanceof IRubyElement ) return ( IRubyElement ) current ; } } } return null ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rdocexport . RDocUtility ; public class GenerateRdocAction implements IWorkbenchWindowActionDelegate { private ISelection fSelection ; private Shell fCurrentShell ; public void dispose ( ) { } public void init ( IWorkbenchWindow window ) { fCurrentShell = window . getShell ( ) ; } private void showNoSelectionMessage ( ) { MessageDialog . openInformation ( fCurrentShell . getShell ( ) , "" , "" ) ; return ; } private IResource findSelectedResource ( ) { if ( fSelection instanceof IStructuredSelection ) { IStructuredSelection selection = ( IStructuredSelection ) fSelection ; Object first = selection . getFirstElement ( ) ; if ( first instanceof IResource ) { return ( ( IResource ) first ) ; } } IWorkbenchPage page = RubyPlugin . getActivePage ( ) ; if ( page == null ) { return null ; } IEditorPart editor = page . getActiveEditor ( ) ; if ( editor == null ) { return null ; } IEditorInput input = editor . getEditorInput ( ) ; if ( input == null ) { return null ; } IRubyElement rubyElement = ( IRubyElement ) input . getAdapter ( IRubyElement . class ) ; if ( rubyElement == null ) { return null ; } return rubyElement . getResource ( ) ; } public void run ( IAction action ) { IResource resource = this . findSelectedResource ( ) ; if ( resource == null ) { showNoSelectionMessage ( ) ; } else { RDocUtility . generateDocumentation ( resource ) ; } } public void selectionChanged ( IAction action , ISelection selection ) { fSelection = selection ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . action . ContributionItem ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class MultiActionGroup extends ActionGroup { public IAction [ ] NO_ACTIONS = new IAction [ ] ; private IAction [ ] fActions ; private int fCurrentSelection ; private MenuItem [ ] fItems ; public MultiActionGroup ( IAction [ ] actions , int currentSelection ) { super ( ) ; setActions ( actions , currentSelection ) ; } protected MultiActionGroup ( ) { super ( ) ; } protected final void setActions ( IAction [ ] actions , int currentSelection ) { fCurrentSelection = currentSelection ; fActions = actions ; } protected void addActions ( IMenuManager viewMenu ) { viewMenu . add ( new Separator ( ) ) ; fItems = new MenuItem [ fActions . length ] ; for ( int i = ; i < fActions . length ; i ++ ) { final int j = i ; viewMenu . add ( new ContributionItem ( ) { public void fill ( Menu menu , int index ) { int style = SWT . CHECK ; if ( ( fActions [ j ] . getStyle ( ) & IAction . AS_RADIO_BUTTON ) != ) style = SWT . RADIO ; MenuItem mi = new MenuItem ( menu , style , index ) ; ImageDescriptor d = fActions [ j ] . getImageDescriptor ( ) ; mi . setImage ( RubyPlugin . getImageDescriptorRegistry ( ) . get ( d ) ) ; fItems [ j ] = mi ; mi . setText ( fActions [ j ] . getText ( ) ) ; mi . setSelection ( fCurrentSelection == j ) ; mi . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { if ( fCurrentSelection == j ) { fItems [ fCurrentSelection ] . setSelection ( true ) ; return ; } fActions [ j ] . run ( ) ; fItems [ fCurrentSelection ] . setSelection ( false ) ; fCurrentSelection = j ; fItems [ fCurrentSelection ] . setSelection ( true ) ; } } ) ; } public boolean isDynamic ( ) { return false ; } } ) ; } } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . OpenTypeSelectionDialog2 ; import org . rubypeople . rdt . internal . ui . util . OpenTypeHierarchyUtil ; public class OpenTypeInHierarchyAction extends Action implements IWorkbenchWindowActionDelegate { private IWorkbenchWindow fWindow ; public OpenTypeInHierarchyAction ( ) { super ( ) ; setText ( ActionMessages . OpenTypeInHierarchyAction_label ) ; setDescription ( ActionMessages . OpenTypeInHierarchyAction_description ) ; setToolTipText ( ActionMessages . OpenTypeInHierarchyAction_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . OPEN_TYPE_IN_HIERARCHY_ACTION ) ; } public void run ( ) { Shell parent = RubyPlugin . getActiveWorkbenchShell ( ) ; OpenTypeSelectionDialog2 dialog = new OpenTypeSelectionDialog2 ( parent , false , PlatformUI . getWorkbench ( ) . getProgressService ( ) , SearchEngine . createWorkspaceScope ( ) , IRubySearchConstants . TYPE ) ; dialog . setTitle ( ActionMessages . OpenTypeInHierarchyAction_dialogTitle ) ; dialog . setMessage ( ActionMessages . OpenTypeInHierarchyAction_dialogMessage ) ; int result = dialog . open ( ) ; if ( result != IDialogConstants . OK_ID ) return ; Object [ ] types = dialog . getResult ( ) ; if ( types != null && types . length > ) { IType type = ( IType ) types [ ] ; OpenTypeHierarchyUtil . open ( new IType [ ] { type } , fWindow ) ; } } public void run ( IAction action ) { run ( ) ; } public void dispose ( ) { fWindow = null ; } public void init ( IWorkbenchWindow window ) { fWindow = window ; } public void selectionChanged ( IAction action , ISelection selection ) { } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . browsing . RubyBrowsingMessages ; import org . rubypeople . rdt . internal . ui . viewsupport . SourcePositionSorter ; import org . rubypeople . rdt . ui . RubyElementSorter ; public class LexicalSortingAction extends Action { private RubyElementSorter fSorter = new RubyElementSorter ( ) ; private SourcePositionSorter fSourcePositonSorter = new SourcePositionSorter ( ) ; private StructuredViewer fViewer ; private String fPreferenceKey ; public LexicalSortingAction ( StructuredViewer viewer , String id ) { super ( ) ; fViewer = viewer ; fPreferenceKey = "" + id + "" ; setText ( RubyBrowsingMessages . LexicalSortingAction_label ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; setToolTipText ( RubyBrowsingMessages . LexicalSortingAction_tooltip ) ; setDescription ( RubyBrowsingMessages . LexicalSortingAction_description ) ; boolean checked = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( fPreferenceKey ) ; valueChanged ( checked , false ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . LEXICAL_SORTING_BROWSING_ACTION ) ; } public void run ( ) { valueChanged ( isChecked ( ) , true ) ; } private void valueChanged ( final boolean on , boolean store ) { setChecked ( on ) ; BusyIndicator . showWhile ( fViewer . getControl ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { if ( on ) fViewer . setSorter ( fSorter ) ; else fViewer . setSorter ( fSourcePositonSorter ) ; } } ) ; if ( store ) RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . setValue ( fPreferenceKey , on ) ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . core . resources . IResource ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . actions . NewWizardMenu ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . ui . IContextMenuConstants ; public class NewWizardsActionGroup extends ActionGroup { private IWorkbenchSite fSite ; public NewWizardsActionGroup ( IWorkbenchSite site ) { fSite = site ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; ISelection selection = getContext ( ) . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { IStructuredSelection sel = ( IStructuredSelection ) selection ; if ( sel . size ( ) <= && isNewTarget ( sel . getFirstElement ( ) ) ) { MenuManager newMenu = new MenuManager ( ActionMessages . NewWizardsActionGroup_new ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_NEW , newMenu ) ; newMenu . add ( new NewWizardMenu ( fSite . getWorkbenchWindow ( ) ) ) ; } } } private boolean isNewTarget ( Object element ) { if ( element == null ) return true ; if ( element instanceof IResource ) { return true ; } if ( element instanceof IRubyElement ) { int type = ( ( IRubyElement ) element ) . getElementType ( ) ; return type == IRubyElement . RUBY_PROJECT || type == IRubyElement . SOURCE_FOLDER_ROOT || type == IRubyElement . SOURCE_FOLDER || type == IRubyElement . SCRIPT || type == IRubyElement . TYPE ; } return false ; } } package org . rubypeople . rdt . internal . ui . actions ; import java . util . ResourceBundle ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . source . projection . IProjectionListener ; import org . eclipse . jface . text . source . projection . ProjectionViewer ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . editors . text . IFoldingCommandIds ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . IUpdate ; import org . eclipse . ui . texteditor . ResourceAction ; import org . eclipse . ui . texteditor . TextOperationAction ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . actions . IRubyEditorActionDefinitionIds ; public class FoldingActionGroup extends ActionGroup { private static abstract class PreferenceAction extends ResourceAction implements IUpdate { PreferenceAction ( ResourceBundle bundle , String prefix , int style ) { super ( bundle , prefix , style ) ; } } private class FoldingAction extends PreferenceAction { FoldingAction ( ResourceBundle bundle , String prefix ) { super ( bundle , prefix , IAction . AS_PUSH_BUTTON ) ; } public void update ( ) { setEnabled ( FoldingActionGroup . this . isEnabled ( ) && fViewer . isProjectionMode ( ) ) ; } } private ProjectionViewer fViewer ; private final PreferenceAction fToggle ; private final TextOperationAction fExpand ; private final TextOperationAction fCollapse ; private final TextOperationAction fExpandAll ; private final PreferenceAction fRestoreDefaults ; private final FoldingAction fCollapseMembers ; private final FoldingAction fCollapseComments ; private final TextOperationAction fCollapseAll ; private final IProjectionListener fProjectionListener ; public FoldingActionGroup ( final ITextEditor editor , ITextViewer viewer ) { if ( ! ( viewer instanceof ProjectionViewer ) ) { fToggle = null ; fExpand = null ; fCollapse = null ; fExpandAll = null ; fCollapseAll = null ; fRestoreDefaults = null ; fCollapseMembers = null ; fCollapseComments = null ; fProjectionListener = null ; return ; } fViewer = ( ProjectionViewer ) viewer ; fProjectionListener = new IProjectionListener ( ) { public void projectionEnabled ( ) { update ( ) ; } public void projectionDisabled ( ) { update ( ) ; } } ; fViewer . addProjectionListener ( fProjectionListener ) ; fToggle = new PreferenceAction ( FoldingMessages . getResourceBundle ( ) , "" , IAction . AS_CHECK_BOX ) { public void run ( ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; boolean current = store . getBoolean ( PreferenceConstants . EDITOR_FOLDING_ENABLED ) ; store . setValue ( PreferenceConstants . EDITOR_FOLDING_ENABLED , ! current ) ; } public void update ( ) { ITextOperationTarget target = ( ITextOperationTarget ) editor . getAdapter ( ITextOperationTarget . class ) ; boolean isEnabled = ( target != null && target . canDoOperation ( ProjectionViewer . TOGGLE ) ) ; setEnabled ( isEnabled ) ; } } ; fToggle . setChecked ( true ) ; fToggle . setActionDefinitionId ( IFoldingCommandIds . FOLDING_TOGGLE ) ; editor . setAction ( "" , fToggle ) ; fExpandAll = new TextOperationAction ( FoldingMessages . getResourceBundle ( ) , "" , editor , ProjectionViewer . EXPAND_ALL , true ) ; fExpandAll . setActionDefinitionId ( IFoldingCommandIds . FOLDING_EXPAND_ALL ) ; editor . setAction ( "" , fExpandAll ) ; fCollapseAll = new TextOperationAction ( FoldingMessages . getResourceBundle ( ) , "" , editor , ProjectionViewer . COLLAPSE_ALL , true ) ; fCollapseAll . setActionDefinitionId ( IFoldingCommandIds . FOLDING_COLLAPSE_ALL ) ; editor . setAction ( "" , fCollapseAll ) ; fExpand = new TextOperationAction ( FoldingMessages . getResourceBundle ( ) , "" , editor , ProjectionViewer . EXPAND , true ) ; fExpand . setActionDefinitionId ( IFoldingCommandIds . FOLDING_EXPAND ) ; editor . setAction ( "" , fExpand ) ; fCollapse = new TextOperationAction ( FoldingMessages . getResourceBundle ( ) , "" , editor , ProjectionViewer . COLLAPSE , true ) ; fCollapse . setActionDefinitionId ( IFoldingCommandIds . FOLDING_COLLAPSE ) ; editor . setAction ( "" , fCollapse ) ; fRestoreDefaults = new FoldingAction ( FoldingMessages . getResourceBundle ( ) , "" ) { public void run ( ) { if ( editor instanceof RubyEditor ) { RubyEditor javaEditor = ( RubyEditor ) editor ; javaEditor . resetProjection ( ) ; } } } ; fRestoreDefaults . setActionDefinitionId ( IFoldingCommandIds . FOLDING_RESTORE ) ; editor . setAction ( "" , fRestoreDefaults ) ; fCollapseMembers = new FoldingAction ( FoldingMessages . getResourceBundle ( ) , "" ) { public void run ( ) { if ( editor instanceof RubyEditor ) { RubyEditor javaEditor = ( RubyEditor ) editor ; javaEditor . collapseMembers ( ) ; } } } ; fCollapseMembers . setActionDefinitionId ( IRubyEditorActionDefinitionIds . FOLDING_COLLAPSE_MEMBERS ) ; editor . setAction ( "" , fCollapseMembers ) ; fCollapseComments = new FoldingAction ( FoldingMessages . getResourceBundle ( ) , "" ) { public void run ( ) { if ( editor instanceof RubyEditor ) { RubyEditor javaEditor = ( RubyEditor ) editor ; javaEditor . collapseComments ( ) ; } } } ; fCollapseComments . setActionDefinitionId ( IRubyEditorActionDefinitionIds . FOLDING_COLLAPSE_COMMENTS ) ; editor . setAction ( "" , fCollapseComments ) ; } protected boolean isEnabled ( ) { return fViewer != null ; } public void dispose ( ) { if ( isEnabled ( ) ) { fViewer . removeProjectionListener ( fProjectionListener ) ; fViewer = null ; } super . dispose ( ) ; } protected void update ( ) { if ( isEnabled ( ) ) { fToggle . update ( ) ; fToggle . setChecked ( fViewer . isProjectionMode ( ) ) ; fExpand . update ( ) ; fExpandAll . update ( ) ; fCollapse . update ( ) ; fCollapseAll . update ( ) ; fRestoreDefaults . update ( ) ; fCollapseMembers . update ( ) ; fCollapseComments . update ( ) ; } } public void fillMenu ( IMenuManager manager ) { if ( isEnabled ( ) ) { update ( ) ; manager . add ( fToggle ) ; manager . add ( fExpandAll ) ; manager . add ( fExpand ) ; manager . add ( fCollapse ) ; manager . add ( fCollapseAll ) ; manager . add ( fRestoreDefaults ) ; manager . add ( fCollapseMembers ) ; manager . add ( fCollapseComments ) ; } } public void updateActionBars ( ) { update ( ) ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . ui . IPartService ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowPulldownDelegate2 ; import org . eclipse . ui . actions . RetargetAction ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . ui . actions . IRubyEditorActionDefinitionIds ; import org . rubypeople . rdt . ui . actions . RdtActionConstants ; public class OccurrencesSearchMenuAction implements IWorkbenchWindowPulldownDelegate2 { private static Action NO_ACTION_AVAILABLE = new Action ( SearchMessages . group_occurrences_quickMenu_noEntriesAvailable ) { public boolean isEnabled ( ) { return false ; } } ; private Menu fMenu ; private IPartService fPartService ; private RetargetAction [ ] fRetargetActions ; public Menu getMenu ( Menu parent ) { setMenu ( new Menu ( parent ) ) ; fillMenu ( fMenu ) ; return fMenu ; } public Menu getMenu ( Control parent ) { setMenu ( new Menu ( parent ) ) ; fillMenu ( fMenu ) ; return fMenu ; } public void dispose ( ) { setMenu ( null ) ; disposeSubmenuActions ( ) ; } private RetargetAction createSubmenuAction ( IPartService partService , String actionID , String text , String actionDefinitionId ) { RetargetAction action = new RetargetAction ( actionID , text ) ; action . setActionDefinitionId ( actionDefinitionId ) ; partService . addPartListener ( action ) ; IWorkbenchPart activePart = partService . getActivePart ( ) ; if ( activePart != null ) { action . partActivated ( activePart ) ; } return action ; } private void disposeSubmenuActions ( ) { if ( fPartService != null && fRetargetActions != null ) { for ( int i = ; i < fRetargetActions . length ; i ++ ) { fPartService . removePartListener ( fRetargetActions [ i ] ) ; fRetargetActions [ i ] . dispose ( ) ; } } fRetargetActions = null ; fPartService = null ; } public void init ( IWorkbenchWindow window ) { disposeSubmenuActions ( ) ; if ( window != null ) { fPartService = window . getPartService ( ) ; if ( fPartService != null ) { fRetargetActions = new RetargetAction [ ] { createSubmenuAction ( fPartService , RdtActionConstants . FIND_OCCURRENCES_IN_FILE , SearchMessages . Search_FindOccurrencesInFile_shortLabel , IRubyEditorActionDefinitionIds . SEARCH_OCCURRENCES_IN_FILE ) } ; } } } public void run ( IAction action ) { RubyEditor editor = null ; IWorkbenchPart activePart = RubyPlugin . getActivePage ( ) . getActivePart ( ) ; if ( activePart instanceof RubyEditor ) editor = ( RubyEditor ) activePart ; ( new RDTQuickMenuAction ( editor , IRubyEditorActionDefinitionIds . SEARCH_OCCURRENCES_IN_FILE_QUICK_MENU ) { protected void fillMenu ( IMenuManager menu ) { fillQuickMenu ( menu ) ; } } ) . run ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { } private void fillQuickMenu ( IMenuManager manager ) { IAction [ ] actions = fRetargetActions ; if ( actions != null ) { boolean hasAction = false ; for ( int i = ; i < actions . length ; i ++ ) { IAction action = actions [ i ] ; if ( action . isEnabled ( ) ) { hasAction = true ; manager . add ( action ) ; } } if ( ! hasAction ) { manager . add ( NO_ACTION_AVAILABLE ) ; } } else { manager . add ( NO_ACTION_AVAILABLE ) ; } } private void fillMenu ( Menu menu ) { if ( fRetargetActions != null ) { for ( int i = ; i < fRetargetActions . length ; i ++ ) { ActionContributionItem item = new ActionContributionItem ( fRetargetActions [ i ] ) ; item . fill ( menu , - ) ; } } else { ActionContributionItem item = new ActionContributionItem ( NO_ACTION_AVAILABLE ) ; item . fill ( menu , - ) ; } } private void setMenu ( Menu menu ) { if ( fMenu != null ) { fMenu . dispose ( ) ; } fMenu = menu ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . osgi . util . NLS ; public final class ActionMessages extends NLS { private static final String BUNDLE_NAME = ActionMessages . class . getName ( ) ; private ActionMessages ( ) { } public static String ToggleLinkingAction_label ; public static String ToggleLinkingAction_tooltip ; public static String ToggleLinkingAction_description ; public static String MemberFilterActionGroup_hide_fields_label ; public static String MemberFilterActionGroup_hide_fields_tooltip ; public static String MemberFilterActionGroup_hide_fields_description ; public static String MemberFilterActionGroup_hide_static_label ; public static String MemberFilterActionGroup_hide_static_tooltip ; public static String MemberFilterActionGroup_hide_static_description ; public static String MemberFilterActionGroup_hide_nonpublic_label ; public static String MemberFilterActionGroup_hide_nonpublic_tooltip ; public static String MemberFilterActionGroup_hide_nonpublic_description ; public static String MemberFilterActionGroup_hide_localtypes_label ; public static String MemberFilterActionGroup_hide_localtypes_tooltip ; public static String MemberFilterActionGroup_hide_localtypes_description ; public static String OpenAction_label ; public static String OpenAction_tooltip ; public static String OpenAction_description ; public static String OpenAction_declaration_label ; public static String OpenAction_select_element ; public static String OpenAction_error_messageBadSelection ; public static String OpenAction_error_message ; public static String OpenAction_error_messageProblems ; public static String OpenAction_error_messageArgs ; public static String OpenAction_error_title ; public static String ActionUtil_notOnBuildPath_title ; public static String ActionUtil_notOnBuildPath_message ; public static String OpenWithMenu_label ; public static String OpenTypeAction_error_title ; public static String OpenTypeAction_error_messageProblems ; public static String OpenTypeAction_message ; public static String OpenNewSourceFolderWizardAction_text2 ; public static String OpenNewSourceFolderWizardAction_description ; public static String OpenNewSourceFolderWizardAction_tooltip ; public static String BuildPath_label ; public static String OpenNewRubyProjectWizardAction_text ; public static String OpenNewRubyProjectWizardAction_description ; public static String OpenNewRubyProjectWizardAction_tooltip ; public static String SelectAllAction_label ; public static String SelectAllAction_tooltip ; public static String NewWizardsActionGroup_new ; public static String OpenTypeInHierarchyAction_label ; public static String OpenTypeInHierarchyAction_description ; public static String OpenTypeInHierarchyAction_tooltip ; public static String OpenTypeInHierarchyAction_dialogTitle ; public static String OpenTypeInHierarchyAction_dialogMessage ; public static String SelectionConverter_codeResolve_failed ; public static String OpenTypeHierarchyAction_label ; public static String OpenTypeHierarchyAction_tooltip ; public static String OpenTypeHierarchyAction_description ; public static String OpenTypeHierarchyAction_messages_no_ruby_element ; public static String OpenTypeHierarchyAction_messages_title ; public static String OpenTypeHierarchyAction_dialog_title ; public static String OpenTypeHierarchyAction_messages_no_ruby_resources ; public static String OpenTypeHierarchyAction_messages_unknown_import_decl ; public static String OpenTypeHierarchyAction_messages_no_types ; public static String OpenTypeHierarchyAction_messages_no_valid_ruby_element ; public static String SurroundWithBeginRescueAction_label ; public static String SurroundWithBeginRescueAction_error ; public static String SurroundWithBeginRescueAction_dialog_title ; public static String QuickMenuAction_menuTextWithShortcut ; public static String ShowInPackageViewAction_label ; public static String ShowInPackageViewAction_description ; public static String ShowInPackageViewAction_tooltip ; public static String ShowInPackageViewAction_error_message ; public static String ShowInPackageViewAction_dialog_title ; public static String OpenProjectAction_dialog_title ; public static String OpenProjectAction_dialog_message ; public static String OpenProjectAction_error_message ; public static String RefreshAction_label ; public static String RefreshAction_toolTip ; public static String RefreshAction_progressMessage ; public static String RefreshAction_error_title ; public static String RefreshAction_error_message ; public static String RefreshAction_locationDeleted_message ; public static String RefreshAction_locationDeleted_title ; public static String BuildAction_label ; static { NLS . initializeMessages ( BUNDLE_NAME , ActionMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public abstract class AbstractToggleLinkingAction extends Action { public AbstractToggleLinkingAction ( ) { super ( ActionMessages . ToggleLinkingAction_label ) ; setDescription ( ActionMessages . ToggleLinkingAction_description ) ; setToolTipText ( ActionMessages . ToggleLinkingAction_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . LINK_EDITOR_ACTION ) ; } public abstract void run ( ) ; } package org . rubypeople . rdt . internal . ui . actions ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . AbstractTextEditor ; import org . rubypeople . rdt . core . ICodeAssist ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptEditorInput ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; public class SelectionConverter { public static IStructuredSelection getStructuredSelection ( IWorkbenchPart part ) throws RubyModelException { if ( part instanceof RubyEditor ) return new StructuredSelection ( codeResolve ( ( RubyEditor ) part ) ) ; ISelectionProvider provider = part . getSite ( ) . getSelectionProvider ( ) ; if ( provider != null ) { ISelection selection = provider . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) return ( IStructuredSelection ) selection ; } return StructuredSelection . EMPTY ; } public static IRubyElement getElementAtOffset ( RubyEditor editor ) throws RubyModelException { return getElementAtOffset ( editor , true ) ; } private static IRubyElement getElementAtOffset ( RubyEditor editor , boolean primaryOnly ) throws RubyModelException { return getElementAtOffset ( getInput ( editor , primaryOnly ) , ( ITextSelection ) editor . getSelectionProvider ( ) . getSelection ( ) ) ; } public static IRubyElement getElementAtOffset ( IRubyElement input , ITextSelection selection ) throws RubyModelException { if ( input instanceof IRubyScript ) { IRubyScript cunit = ( IRubyScript ) input ; RubyModelUtil . reconcile ( cunit ) ; IRubyElement ref = cunit . getElementAt ( selection . getOffset ( ) ) ; if ( ref == null ) return input ; else return ref ; } return null ; } public static IRubyScript getInputAsRubyScript ( RubyEditor editor ) { Object editorInput = SelectionConverter . getInput ( editor ) ; if ( editorInput instanceof IRubyScript ) return ( IRubyScript ) editorInput ; else return null ; } public static IRubyElement getInput ( IEditorPart editor ) { if ( editor == null ) return null ; IEditorInput input = editor . getEditorInput ( ) ; if ( input instanceof IRubyScriptEditorInput ) { IRubyScriptEditorInput scriptEditor = ( IRubyScriptEditorInput ) input ; return scriptEditor . getRubyScript ( ) ; } IWorkingCopyManager manager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; return manager . getWorkingCopy ( input ) ; } public static boolean canOperateOn ( IEditorPart editor ) { if ( editor == null ) return false ; return getInput ( editor ) != null ; } private static final IRubyElement [ ] EMPTY_RESULT = new IRubyElement [ ] ; public static IRubyElement codeResolve ( AbstractTextEditor editor , Shell shell , String title , String message ) throws RubyModelException { IRubyElement [ ] elements = codeResolve ( editor ) ; if ( elements == null || elements . length == ) return null ; IRubyElement candidate = elements [ ] ; if ( elements . length > ) { candidate = OpenActionUtil . selectRubyElement ( elements , shell , title , message ) ; } return candidate ; } public static IRubyElement [ ] codeResolve ( AbstractTextEditor editor ) throws RubyModelException { return codeResolve ( getInput ( editor ) , ( ITextSelection ) editor . getSelectionProvider ( ) . getSelection ( ) ) ; } public static IRubyElement [ ] codeResolve ( IRubyElement input , ITextSelection selection ) throws RubyModelException { return codeResolve ( input , selection . getOffset ( ) , selection . getLength ( ) ) ; } public static IRubyElement [ ] codeResolve ( IRubyElement input , int offset , int length ) throws RubyModelException { if ( input instanceof ICodeAssist ) { if ( input instanceof IRubyScript ) { RubyModelUtil . reconcile ( ( IRubyScript ) input ) ; } IRubyElement [ ] elements = ( ( ICodeAssist ) input ) . codeSelect ( offset , length ) ; if ( elements != null && elements . length > ) return elements ; } return EMPTY_RESULT ; } public static IRubyElement [ ] codeResolveForked ( RubyEditor editor , boolean primaryOnly ) throws InvocationTargetException , InterruptedException { return performForkedCodeResolve ( getInput ( editor , primaryOnly ) , ( ITextSelection ) editor . getSelectionProvider ( ) . getSelection ( ) ) ; } private static IRubyElement getInput ( RubyEditor editor , boolean primaryOnly ) { if ( editor == null ) return null ; return EditorUtility . getEditorInputRubyElement ( editor , primaryOnly ) ; } private static IRubyElement [ ] performForkedCodeResolve ( final IRubyElement input , final ITextSelection selection ) throws InvocationTargetException , InterruptedException { final class CodeResolveRunnable implements IRunnableWithProgress { IRubyElement [ ] result ; public void run ( IProgressMonitor monitor ) throws InvocationTargetException { try { result = codeResolve ( input , selection ) ; } catch ( RubyModelException e ) { throw new InvocationTargetException ( e ) ; } } } CodeResolveRunnable runnable = new CodeResolveRunnable ( ) ; PlatformUI . getWorkbench ( ) . getProgressService ( ) . busyCursorWhile ( runnable ) ; return runnable . result ; } public static IRubyElement [ ] codeResolveOrInputForked ( RubyEditor editor ) throws InvocationTargetException , InterruptedException { IRubyElement input = getInput ( editor ) ; ITextSelection selection = ( ITextSelection ) editor . getSelectionProvider ( ) . getSelection ( ) ; IRubyElement [ ] result = performForkedCodeResolve ( input , selection ) ; if ( result . length == ) { result = new IRubyElement [ ] { input } ; } return result ; } public static IRubyElement resolveEnclosingElement ( RubyEditor editor , ITextSelection selection ) throws RubyModelException { return resolveEnclosingElement ( getInput ( editor ) , selection ) ; } public static IRubyElement resolveEnclosingElement ( IRubyElement input , ITextSelection selection ) throws RubyModelException { IRubyElement atOffset = null ; if ( input instanceof IRubyScript ) { IRubyScript cunit = ( IRubyScript ) input ; RubyModelUtil . reconcile ( cunit ) ; atOffset = cunit . getElementAt ( selection . getOffset ( ) ) ; } else { return null ; } if ( atOffset == null ) { return input ; } else { int selectionEnd = selection . getOffset ( ) + selection . getLength ( ) ; IRubyElement result = atOffset ; if ( atOffset instanceof ISourceReference ) { ISourceRange range = ( ( ISourceReference ) atOffset ) . getSourceRange ( ) ; while ( range . getOffset ( ) + range . getLength ( ) < selectionEnd ) { result = result . getParent ( ) ; if ( ! ( result instanceof ISourceReference ) ) { result = input ; break ; } range = ( ( ISourceReference ) result ) . getSourceRange ( ) ; } } return result ; } } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class AddRubyNatureAction implements IWorkbenchWindowActionDelegate { private Shell fCurrentShell ; private ISelection fSelection ; public void dispose ( ) { } public void init ( IWorkbenchWindow window ) { fCurrentShell = window . getShell ( ) ; } public void run ( IAction action ) { IResource resource = findSelectedResource ( ) ; if ( resource == null ) { MessageDialog . openInformation ( fCurrentShell . getShell ( ) , "" , "" ) ; return ; } try { RubyCore . addRubyNature ( resource . getProject ( ) , null ) ; } catch ( CoreException e ) { MessageDialog . openInformation ( fCurrentShell . getShell ( ) , "" , e . getMessage ( ) ) ; } } private IResource findSelectedResource ( ) { if ( fSelection instanceof IStructuredSelection ) { IStructuredSelection selection = ( IStructuredSelection ) fSelection ; Object first = selection . getFirstElement ( ) ; if ( first instanceof IResource ) { return ( ( IResource ) first ) ; } } IWorkbenchPage page = RubyPlugin . getActivePage ( ) ; if ( page == null ) { return null ; } IEditorPart editor = page . getActiveEditor ( ) ; if ( editor == null ) { return null ; } IEditorInput input = editor . getEditorInput ( ) ; if ( input == null ) { return null ; } IRubyElement rubyElement = ( IRubyElement ) input . getAdapter ( IRubyElement . class ) ; if ( rubyElement == null ) { return null ; } return rubyElement . getResource ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { fSelection = selection ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; public class SelectAllAction extends Action { private TableViewer fViewer ; public SelectAllAction ( TableViewer viewer ) { super ( "" ) ; setText ( ActionMessages . SelectAllAction_label ) ; setToolTipText ( ActionMessages . SelectAllAction_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . SELECT_ALL_ACTION ) ; Assert . isNotNull ( viewer ) ; fViewer = viewer ; } public void run ( ) { fViewer . getTable ( ) . selectAll ( ) ; fViewer . setSelection ( fViewer . getSelection ( ) ) ; } } package org . rubypeople . rdt . internal . ui . actions ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyUIStatus ; public class WorkbenchRunnableAdapter implements IRunnableWithProgress { private boolean fTransfer = false ; private IWorkspaceRunnable fWorkspaceRunnable ; private ISchedulingRule fRule ; public WorkbenchRunnableAdapter ( IWorkspaceRunnable runnable ) { this ( runnable , ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; } public WorkbenchRunnableAdapter ( IWorkspaceRunnable runnable , ISchedulingRule rule ) { fWorkspaceRunnable = runnable ; fRule = rule ; } public WorkbenchRunnableAdapter ( IWorkspaceRunnable runnable , ISchedulingRule rule , boolean transfer ) { fWorkspaceRunnable = runnable ; fRule = rule ; fTransfer = transfer ; } public ISchedulingRule getSchedulingRule ( ) { return fRule ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { try { RubyCore . run ( fWorkspaceRunnable , fRule , monitor ) ; } catch ( OperationCanceledException e ) { throw new InterruptedException ( e . getMessage ( ) ) ; } catch ( CoreException e ) { throw new InvocationTargetException ( e ) ; } } public void threadChange ( Thread thread ) { if ( fTransfer ) Platform . getJobManager ( ) . transferRule ( fRule , thread ) ; } public void runAsUserJob ( String name , final Object jobFamiliy ) { Job buildJob = new Job ( name ) { protected IStatus run ( IProgressMonitor monitor ) { try { WorkbenchRunnableAdapter . this . run ( monitor ) ; } catch ( InvocationTargetException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof CoreException ) { return ( ( CoreException ) cause ) . getStatus ( ) ; } else { return RubyUIStatus . createError ( IStatus . ERROR , cause ) ; } } catch ( InterruptedException e ) { return Status . CANCEL_STATUS ; } finally { monitor . done ( ) ; } return Status . OK_STATUS ; } public boolean belongsTo ( Object family ) { return jobFamiliy == family ; } } ; buildJob . setRule ( fRule ) ; buildJob . setUser ( true ) ; buildJob . schedule ( ) ; } } package org . rubypeople . rdt . internal . ui . actions ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . actions . ActionGroup ; public class CompositeActionGroup extends ActionGroup { private ActionGroup [ ] fGroups ; public CompositeActionGroup ( ) { } public CompositeActionGroup ( ActionGroup [ ] groups ) { setGroups ( groups ) ; } protected void setGroups ( ActionGroup [ ] groups ) { Assert . isTrue ( fGroups == null ) ; Assert . isNotNull ( groups ) ; fGroups = groups ; } public ActionGroup get ( int index ) { if ( fGroups == null ) return null ; return fGroups [ index ] ; } public void addGroup ( ActionGroup group ) { if ( fGroups == null ) { fGroups = new ActionGroup [ ] { group } ; } else { ActionGroup [ ] newGroups = new ActionGroup [ fGroups . length + ] ; System . arraycopy ( fGroups , , newGroups , , fGroups . length ) ; newGroups [ fGroups . length ] = group ; fGroups = newGroups ; } } public void dispose ( ) { super . dispose ( ) ; if ( fGroups == null ) return ; for ( int i = ; i < fGroups . length ; i ++ ) { fGroups [ i ] . dispose ( ) ; } } public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; if ( fGroups == null ) return ; for ( int i = ; i < fGroups . length ; i ++ ) { fGroups [ i ] . fillActionBars ( actionBars ) ; } } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; if ( fGroups == null ) return ; for ( int i = ; i < fGroups . length ; i ++ ) { fGroups [ i ] . fillContextMenu ( menu ) ; } } public void setContext ( ActionContext context ) { super . setContext ( context ) ; if ( fGroups == null ) return ; for ( int i = ; i < fGroups . length ; i ++ ) { fGroups [ i ] . setContext ( context ) ; } } public void updateActionBars ( ) { super . updateActionBars ( ) ; if ( fGroups == null ) return ; for ( int i = ; i < fGroups . length ; i ++ ) { fGroups [ i ] . updateActionBars ( ) ; } } } package org . rubypeople . rdt . internal . ui . actions ; import java . text . MessageFormat ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; public class FoldingMessages { private static final String BUNDLE_NAME = "" ; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle . getBundle ( BUNDLE_NAME ) ; private FoldingMessages ( ) { } public static String getString ( String key ) { try { return RESOURCE_BUNDLE . getString ( key ) ; } catch ( MissingResourceException e ) { return '' + key + '' ; } } public static ResourceBundle getResourceBundle ( ) { return RESOURCE_BUNDLE ; } public static String getFormattedString ( String key , Object arg ) { return getFormattedString ( key , new Object [ ] { arg } ) ; } public static String getFormattedString ( String key , Object [ ] args ) { return MessageFormat . format ( getString ( key ) , args ) ; } } package org . rubypeople . rdt . internal . ui . infoviews ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . ui . IEditorInput ; import org . rubypeople . rdt . core . ICodeAssist ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; class TextSelectionConverter { private static final IRubyElement [ ] EMPTY_RESULT = new IRubyElement [ ] ; private TextSelectionConverter ( ) { } public static IRubyElement [ ] codeResolve ( RubyEditor editor , ITextSelection selection ) throws RubyModelException { return codeResolve ( getInput ( editor ) , selection ) ; } public static IRubyElement getElementAtOffset ( RubyEditor editor , ITextSelection selection ) throws RubyModelException { return getElementAtOffset ( getInput ( editor ) , selection ) ; } private static IRubyElement getInput ( RubyEditor editor ) { if ( editor == null ) return null ; IEditorInput input = editor . getEditorInput ( ) ; IWorkingCopyManager manager = RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; return manager . getWorkingCopy ( input ) ; } private static IRubyElement [ ] codeResolve ( IRubyElement input , ITextSelection selection ) throws RubyModelException { if ( input instanceof ICodeAssist ) { if ( input instanceof IRubyScript ) { IRubyScript cunit = ( IRubyScript ) input ; if ( cunit . isWorkingCopy ( ) ) RubyModelUtil . reconcile ( cunit ) ; } IRubyElement [ ] elements = ( ( ICodeAssist ) input ) . codeSelect ( selection . getOffset ( ) , selection . getLength ( ) ) ; if ( elements != null && elements . length > ) return elements ; } return EMPTY_RESULT ; } private static IRubyElement getElementAtOffset ( IRubyElement input , ITextSelection selection ) throws RubyModelException { if ( input instanceof IRubyScript ) { IRubyScript cunit = ( IRubyScript ) input ; if ( cunit . isWorkingCopy ( ) ) RubyModelUtil . reconcile ( cunit ) ; IRubyElement ref = cunit . getElementAt ( selection . getOffset ( ) ) ; if ( ref == null ) return input ; else return ref ; } return null ; } } package org . rubypeople . rdt . internal . ui . infoviews ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . net . URL ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialogWithToggle ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPartitioningException ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . TextPresentation ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . SWTError ; import org . eclipse . swt . browser . Browser ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . events . ControlAdapter ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . IAbstractTextEditorHelpContextIds ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . RDocUtil ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . text . HTMLPrinter ; import org . rubypeople . rdt . internal . ui . text . HTMLTextPresenter ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; public class RDocView extends AbstractInfoView { private static final String DO_NOT_WARN_PREFERENCE_KEY = "" ; private static final boolean WARNING_DIALOG_ENABLED = false ; private Browser fBrowser ; private StyledText fText ; private DefaultInformationControl . IInformationPresenter fPresenter ; private TextPresentation fPresentation = new TextPresentation ( ) ; private SelectAllAction fSelectAllAction ; private static String fgStyleSheet ; private boolean fIsUsingBrowserWidget ; private RGB fBackgroundColorRGB ; private class SelectAllAction extends Action { private Control fControl ; private SelectionProvider fSelectionProvider ; public SelectAllAction ( Control control , SelectionProvider selectionProvider ) { super ( "" ) ; Assert . isNotNull ( control ) ; Assert . isNotNull ( selectionProvider ) ; fControl = control ; fSelectionProvider = selectionProvider ; setEnabled ( ! fIsUsingBrowserWidget ) ; setText ( InfoViewMessages . SelectAllAction_label ) ; setToolTipText ( InfoViewMessages . SelectAllAction_tooltip ) ; setDescription ( InfoViewMessages . SelectAllAction_description ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IAbstractTextEditorHelpContextIds . SELECT_ALL_ACTION ) ; } public void run ( ) { if ( fControl instanceof StyledText ) ( ( StyledText ) fControl ) . selectAll ( ) ; else { if ( fSelectionProvider != null ) fSelectionProvider . fireSelectionChanged ( ) ; } } } private static class SelectionProvider implements ISelectionProvider { private ListenerList fListeners = new ListenerList ( ListenerList . IDENTITY ) ; private Control fControl ; public SelectionProvider ( Control control ) { Assert . isNotNull ( control ) ; fControl = control ; if ( fControl instanceof StyledText ) { ( ( StyledText ) fControl ) . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fireSelectionChanged ( ) ; } } ) ; } else { } } public void fireSelectionChanged ( ) { ISelection selection = getSelection ( ) ; SelectionChangedEvent event = new SelectionChangedEvent ( this , selection ) ; Object [ ] selectionChangedListeners = fListeners . getListeners ( ) ; for ( int i = ; i < selectionChangedListeners . length ; i ++ ) ( ( ISelectionChangedListener ) selectionChangedListeners [ i ] ) . selectionChanged ( event ) ; } public void addSelectionChangedListener ( ISelectionChangedListener listener ) { fListeners . add ( listener ) ; } public ISelection getSelection ( ) { if ( fControl instanceof StyledText ) { IDocument document = new Document ( ( ( StyledText ) fControl ) . getSelectionText ( ) ) ; return new TextSelection ( document , , document . getLength ( ) ) ; } else { return StructuredSelection . EMPTY ; } } public void removeSelectionChangedListener ( ISelectionChangedListener listener ) { fListeners . remove ( listener ) ; } public void setSelection ( ISelection selection ) { } } protected void internalCreatePartControl ( Composite parent ) { try { fBrowser = new Browser ( parent , SWT . NONE ) ; fIsUsingBrowserWidget = true ; } catch ( SWTError er ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; boolean doNotWarn = store . getBoolean ( DO_NOT_WARN_PREFERENCE_KEY ) ; if ( WARNING_DIALOG_ENABLED && ! doNotWarn ) { String title = InfoViewMessages . RubydocView_error_noBrowser_title ; String message = InfoViewMessages . RubydocView_error_noBrowser_message ; String toggleMessage = InfoViewMessages . RubydocView_error_noBrowser_doNotWarn ; MessageDialogWithToggle dialog = MessageDialogWithToggle . openError ( parent . getShell ( ) , title , message , toggleMessage , false , null , null ) ; if ( dialog . getReturnCode ( ) == Window . OK ) store . setValue ( DO_NOT_WARN_PREFERENCE_KEY , dialog . getToggleState ( ) ) ; } fIsUsingBrowserWidget = false ; } if ( ! fIsUsingBrowserWidget ) { fText = new StyledText ( parent , SWT . V_SCROLL | SWT . H_SCROLL ) ; fText . setEditable ( false ) ; fPresenter = new HTMLTextPresenter ( false ) ; fText . addControlListener ( new ControlAdapter ( ) { public void controlResized ( ControlEvent e ) { setInput ( fText . getText ( ) ) ; } } ) ; } initStyleSheet ( ) ; getViewSite ( ) . setSelectionProvider ( new SelectionProvider ( getControl ( ) ) ) ; } private static void initStyleSheet ( ) { Bundle bundle = Platform . getBundle ( RubyPlugin . getPluginId ( ) ) ; URL styleSheetURL = bundle . getEntry ( "" ) ; if ( styleSheetURL == null ) return ; try { styleSheetURL = FileLocator . toFileURL ( styleSheetURL ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( styleSheetURL . openStream ( ) ) ) ; StringBuffer buffer = new StringBuffer ( ) ; String line = reader . readLine ( ) ; while ( line != null ) { buffer . append ( line ) ; buffer . append ( '' ) ; line = reader . readLine ( ) ; } fgStyleSheet = buffer . toString ( ) ; } catch ( IOException ex ) { RubyPlugin . log ( ex ) ; } } protected void createActions ( ) { super . createActions ( ) ; fSelectAllAction = new SelectAllAction ( getControl ( ) , ( SelectionProvider ) getSelectionProvider ( ) ) ; } protected IAction getSelectAllAction ( ) { if ( fIsUsingBrowserWidget ) return null ; return fSelectAllAction ; } protected void setForeground ( Color color ) { getControl ( ) . setForeground ( color ) ; } protected void setBackground ( Color color ) { getControl ( ) . setBackground ( color ) ; fBackgroundColorRGB = color . getRGB ( ) ; if ( getInput ( ) == null ) { StringBuffer buffer = new StringBuffer ( "" ) ; HTMLPrinter . insertPageProlog ( buffer , , fBackgroundColorRGB , fgStyleSheet ) ; setInput ( buffer . toString ( ) ) ; } else { setInput ( computeInput ( getInput ( ) ) ) ; } } protected String getBackgroundColorKey ( ) { return "" ; } protected void internalDispose ( ) { fText = null ; fBrowser = null ; } public void setFocus ( ) { getControl ( ) . setFocus ( ) ; } protected Object computeInput ( Object input ) { if ( getControl ( ) == null || ! ( input instanceof IRubyElement ) ) return null ; IRubyElement je = ( IRubyElement ) input ; String javadocHtml ; switch ( je . getElementType ( ) ) { case IRubyElement . SCRIPT : try { javadocHtml = getRubydocHtml ( ( ( IRubyScript ) je ) . getTypes ( ) ) ; } catch ( RubyModelException ex ) { javadocHtml = null ; } break ; default : javadocHtml = getRubydocHtml ( new IRubyElement [ ] { je } ) ; } if ( javadocHtml == null ) return "" ; return javadocHtml ; } protected void setInput ( Object input ) { String javadocHtml = ( String ) input ; if ( fIsUsingBrowserWidget ) { if ( javadocHtml != null && javadocHtml . length ( ) > ) { boolean RTL = ( getSite ( ) . getShell ( ) . getStyle ( ) & SWT . RIGHT_TO_LEFT ) != ; if ( RTL ) { StringBuffer buffer = new StringBuffer ( javadocHtml ) ; HTMLPrinter . insertStyles ( buffer , new String [ ] { "" } ) ; javadocHtml = buffer . toString ( ) ; } } fBrowser . setText ( javadocHtml ) ; } else { fPresentation . clear ( ) ; Rectangle size = fText . getClientArea ( ) ; try { javadocHtml = ( ( DefaultInformationControl . IInformationPresenterExtension ) fPresenter ) . updatePresentation ( getSite ( ) . getShell ( ) , javadocHtml , fPresentation , size . width , size . height ) ; } catch ( IllegalArgumentException ex ) { return ; } fText . setText ( javadocHtml ) ; TextPresentation . applyTextPresentation ( fPresentation , fText ) ; } } private String getRubydocHtml ( IRubyElement [ ] result ) { StringBuffer buffer = new StringBuffer ( ) ; String contents = RDocUtil . getHTMLDocumentation ( result ) ; if ( contents != null ) { buffer . append ( contents ) ; } else { HTMLPrinter . addParagraph ( buffer , InfoViewMessages . RubydocView_noAttachedInformation ) ; } if ( buffer . length ( ) > ) { HTMLPrinter . insertPageProlog ( buffer , , fBackgroundColorRGB , fgStyleSheet ) ; HTMLPrinter . addPageEpilog ( buffer ) ; return buffer . toString ( ) ; } return null ; } protected boolean isIgnoringNewInput ( IRubyElement je , IWorkbenchPart part , ISelection selection ) { if ( super . isIgnoringNewInput ( je , part , selection ) && part instanceof ITextEditor && selection instanceof ITextSelection ) { ITextEditor editor = ( ITextEditor ) part ; IDocumentProvider docProvider = editor . getDocumentProvider ( ) ; if ( docProvider == null ) return false ; IDocument document = docProvider . getDocument ( editor . getEditorInput ( ) ) ; if ( ! ( document instanceof IDocumentExtension3 ) ) return false ; try { int offset = ( ( ITextSelection ) selection ) . getOffset ( ) ; String partition = ( ( IDocumentExtension3 ) document ) . getContentType ( IRubyPartitions . RUBY_PARTITIONING , offset , false ) ; return partition != IRubyPartitions . RUBY_SINGLE_LINE_COMMENT && partition != IRubyPartitions . RUBY_MULTI_LINE_COMMENT ; } catch ( BadPartitioningException ex ) { return false ; } catch ( BadLocationException ex ) { return false ; } } return false ; } protected IRubyElement findSelectedRubyElement ( IWorkbenchPart part , ISelection selection ) { IRubyElement element ; try { element = super . findSelectedRubyElement ( part , selection ) ; if ( element == null && part instanceof RubyEditor && selection instanceof ITextSelection ) { RubyEditor editor = ( RubyEditor ) part ; ITextSelection textSelection = ( ITextSelection ) selection ; IDocumentProvider documentProvider = editor . getDocumentProvider ( ) ; if ( documentProvider == null ) return null ; IDocument document = documentProvider . getDocument ( editor . getEditorInput ( ) ) ; if ( document == null ) return null ; ITypedRegion typedRegion = TextUtilities . getPartition ( document , IRubyPartitions . RUBY_PARTITIONING , textSelection . getOffset ( ) , false ) ; if ( IRubyPartitions . RUBY_MULTI_LINE_COMMENT . equals ( typedRegion . getType ( ) ) || IRubyPartitions . RUBY_SINGLE_LINE_COMMENT . equals ( typedRegion . getType ( ) ) ) return TextSelectionConverter . getElementAtOffset ( ( RubyEditor ) part , textSelection ) ; else return null ; } else return element ; } catch ( RubyModelException e ) { return null ; } catch ( BadLocationException e ) { return null ; } } protected Control getControl ( ) { if ( fIsUsingBrowserWidget ) return fBrowser ; else return fText ; } protected String getHelpContextId ( ) { return IRubyHelpContextIds . RDOC_VIEW ; } } package org . rubypeople . rdt . internal . ui . infoviews ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . resource . ColorRegistry ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IPartListener2 ; import org . eclipse . ui . ISelectionListener ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . rubypeople . rdt . core . ILocalVariable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . util . SelectionUtil ; import org . rubypeople . rdt . ui . IContextMenuConstants ; import org . rubypeople . rdt . ui . RubyElementLabels ; abstract class AbstractInfoView extends ViewPart implements ISelectionListener , IMenuListener , IPropertyChangeListener { private final long TITLE_FLAGS = RubyElementLabels . ALL_FULLY_QUALIFIED | RubyElementLabels . M_PARAMETER_NAMES | RubyElementLabels . USE_RESOLVED ; private final long LOCAL_VARIABLE_TITLE_FLAGS = TITLE_FLAGS & ~ RubyElementLabels . F_FULLY_QUALIFIED | RubyElementLabels . F_POST_QUALIFIED ; private static final long TOOLTIP_LABEL_FLAGS = RubyElementLabels . DEFAULT_QUALIFIED | RubyElementLabels . ROOT_POST_QUALIFIED | RubyElementLabels . APPEND_ROOT_PATH | RubyElementLabels . M_PARAMETER_NAMES ; private IPartListener2 fPartListener = new IPartListener2 ( ) { public void partVisible ( IWorkbenchPartReference ref ) { if ( ref . getId ( ) . equals ( getSite ( ) . getId ( ) ) ) { IWorkbenchPart activePart = ref . getPage ( ) . getActivePart ( ) ; if ( activePart != null ) selectionChanged ( activePart , ref . getPage ( ) . getSelection ( ) ) ; startListeningForSelectionChanges ( ) ; } } public void partHidden ( IWorkbenchPartReference ref ) { if ( ref . getId ( ) . equals ( getSite ( ) . getId ( ) ) ) stopListeningForSelectionChanges ( ) ; } public void partInputChanged ( IWorkbenchPartReference ref ) { if ( ! ref . getId ( ) . equals ( getSite ( ) . getId ( ) ) ) computeAndSetInput ( ref . getPart ( false ) ) ; } public void partActivated ( IWorkbenchPartReference ref ) { } public void partBroughtToTop ( IWorkbenchPartReference ref ) { } public void partClosed ( IWorkbenchPartReference ref ) { } public void partDeactivated ( IWorkbenchPartReference ref ) { } public void partOpened ( IWorkbenchPartReference ref ) { } } ; protected IRubyElement fCurrentViewInput ; private GotoInputAction fGotoInputAction ; private volatile int fComputeCount ; private Color fBackgroundColor ; private RGB fBackgroundColorRGB ; abstract protected void setInput ( Object input ) ; abstract protected Object computeInput ( Object element ) ; abstract protected void internalCreatePartControl ( Composite parent ) ; abstract protected void setForeground ( Color color ) ; abstract protected void setBackground ( Color color ) ; abstract Control getControl ( ) ; abstract protected String getHelpContextId ( ) ; public final void createPartControl ( Composite parent ) { internalCreatePartControl ( parent ) ; inititalizeColors ( ) ; getSite ( ) . getWorkbenchWindow ( ) . getPartService ( ) . addPartListener ( fPartListener ) ; createContextMenu ( ) ; createActions ( ) ; fillActionBars ( getViewSite ( ) . getActionBars ( ) ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , getHelpContextId ( ) ) ; } protected void createActions ( ) { fGotoInputAction = new GotoInputAction ( this ) ; fGotoInputAction . setEnabled ( false ) ; } protected void createContextMenu ( ) { MenuManager menuManager = new MenuManager ( "" ) ; menuManager . setRemoveAllWhenShown ( true ) ; menuManager . addMenuListener ( this ) ; Menu contextMenu = menuManager . createContextMenu ( getControl ( ) ) ; getControl ( ) . setMenu ( contextMenu ) ; getSite ( ) . registerContextMenu ( menuManager , getSelectionProvider ( ) ) ; } public void menuAboutToShow ( IMenuManager menu ) { menu . add ( new Separator ( IContextMenuConstants . GROUP_OPEN ) ) ; menu . add ( new Separator ( ITextEditorActionConstants . GROUP_EDIT ) ) ; IAction action ; action = getSelectAllAction ( ) ; if ( action != null ) menu . appendToGroup ( ITextEditorActionConstants . GROUP_EDIT , action ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_OPEN , fGotoInputAction ) ; } protected IAction getSelectAllAction ( ) { return null ; } protected IRubyElement getInput ( ) { return fCurrentViewInput ; } ISelectionProvider getSelectionProvider ( ) { return getViewSite ( ) . getSelectionProvider ( ) ; } protected void fillActionBars ( IActionBars actionBars ) { IToolBarManager toolBar = actionBars . getToolBarManager ( ) ; fillToolBar ( toolBar ) ; IAction action ; action = getSelectAllAction ( ) ; if ( action != null ) actionBars . setGlobalActionHandler ( ActionFactory . SELECT_ALL . getId ( ) , action ) ; } protected void fillToolBar ( IToolBarManager tbm ) { tbm . add ( fGotoInputAction ) ; } private void inititalizeColors ( ) { if ( getSite ( ) . getShell ( ) . isDisposed ( ) ) return ; Display display = getSite ( ) . getShell ( ) . getDisplay ( ) ; if ( display == null || display . isDisposed ( ) ) return ; setForeground ( display . getSystemColor ( SWT . COLOR_INFO_FOREGROUND ) ) ; ColorRegistry registry = JFaceResources . getColorRegistry ( ) ; registry . addListener ( this ) ; fBackgroundColorRGB = registry . getRGB ( getBackgroundColorKey ( ) ) ; Color bgColor ; if ( fBackgroundColorRGB == null ) { bgColor = display . getSystemColor ( SWT . COLOR_INFO_BACKGROUND ) ; fBackgroundColorRGB = bgColor . getRGB ( ) ; } else { bgColor = new Color ( display , fBackgroundColorRGB ) ; fBackgroundColor = bgColor ; } setBackground ( bgColor ) ; } abstract protected String getBackgroundColorKey ( ) ; public void propertyChange ( PropertyChangeEvent event ) { if ( getBackgroundColorKey ( ) . equals ( event . getProperty ( ) ) ) inititalizeColors ( ) ; } protected void startListeningForSelectionChanges ( ) { getSite ( ) . getPage ( ) . addPostSelectionListener ( this ) ; } protected void stopListeningForSelectionChanges ( ) { getSite ( ) . getPage ( ) . removePostSelectionListener ( this ) ; } public void selectionChanged ( IWorkbenchPart part , ISelection selection ) { if ( part . equals ( this ) ) return ; computeAndSetInput ( part ) ; } protected boolean isIgnoringNewInput ( IRubyElement je , IWorkbenchPart part , ISelection selection ) { return fCurrentViewInput != null && fCurrentViewInput . equals ( je ) && je != null ; } protected IRubyElement findSelectedRubyElement ( IWorkbenchPart part , ISelection selection ) { Object element ; try { if ( part instanceof RubyEditor && selection instanceof ITextSelection ) { IRubyElement [ ] elements = TextSelectionConverter . codeResolve ( ( RubyEditor ) part , ( ITextSelection ) selection ) ; if ( elements != null && elements . length > ) return elements [ ] ; else return null ; } else if ( selection instanceof IStructuredSelection ) { element = SelectionUtil . getSingleElement ( selection ) ; } else { return null ; } } catch ( RubyModelException e ) { return null ; } return findRubyElement ( element ) ; } private IRubyElement findRubyElement ( Object element ) { if ( element == null ) return null ; IRubyElement je = null ; if ( element instanceof IAdaptable ) je = ( IRubyElement ) ( ( IAdaptable ) element ) . getAdapter ( IRubyElement . class ) ; return je ; } protected IType getTypeForCU ( IRubyScript cu ) { if ( cu == null || ! cu . exists ( ) ) return null ; IType primaryType = cu . findPrimaryType ( ) ; if ( primaryType != null ) return primaryType ; try { IType [ ] types = cu . getTypes ( ) ; if ( types . length > ) return types [ ] ; else return null ; } catch ( RubyModelException ex ) { return null ; } } final public void dispose ( ) { fComputeCount ++ ; getSite ( ) . getWorkbenchWindow ( ) . getPartService ( ) . removePartListener ( fPartListener ) ; JFaceResources . getColorRegistry ( ) . removeListener ( this ) ; fBackgroundColorRGB = null ; if ( fBackgroundColor != null ) { fBackgroundColor . dispose ( ) ; fBackgroundColor = null ; } internalDispose ( ) ; } abstract protected void internalDispose ( ) ; private void computeAndSetInput ( final IWorkbenchPart part ) { final int currentCount = ++ fComputeCount ; ISelectionProvider provider = part . getSite ( ) . getSelectionProvider ( ) ; if ( provider == null ) return ; final ISelection selection = provider . getSelection ( ) ; if ( selection == null || selection . isEmpty ( ) ) return ; Thread thread = new Thread ( "" ) { public void run ( ) { if ( currentCount != fComputeCount ) return ; final IRubyElement je = findSelectedRubyElement ( part , selection ) ; if ( isIgnoringNewInput ( je , part , selection ) ) return ; final Object input = computeInput ( je ) ; if ( input == null ) return ; Shell shell = getSite ( ) . getShell ( ) ; if ( shell . isDisposed ( ) ) return ; Display display = shell . getDisplay ( ) ; if ( display . isDisposed ( ) ) return ; display . asyncExec ( new Runnable ( ) { public void run ( ) { if ( fComputeCount != currentCount || getViewSite ( ) . getShell ( ) . isDisposed ( ) ) return ; fCurrentViewInput = je ; doSetInput ( input ) ; } } ) ; } } ; thread . setDaemon ( true ) ; thread . setPriority ( Thread . MIN_PRIORITY ) ; thread . start ( ) ; } private void doSetInput ( Object input ) { setInput ( input ) ; fGotoInputAction . setEnabled ( true ) ; long flags ; if ( getInput ( ) instanceof ILocalVariable ) flags = LOCAL_VARIABLE_TITLE_FLAGS ; else flags = TITLE_FLAGS ; setContentDescription ( RubyElementLabels . getElementLabel ( getInput ( ) , flags ) ) ; setTitleToolTip ( RubyElementLabels . getElementLabel ( getInput ( ) , TOOLTIP_LABEL_FLAGS ) ) ; } } package org . rubypeople . rdt . internal . ui . infoviews ; import java . util . LinkedList ; import java . util . List ; import org . rubypeople . rdt . ui . text . ansi . ANSIParser ; import org . rubypeople . rdt . ui . text . ansi . ANSIToken ; public class FastRIParser extends ANSIParser { public List < ANSIToken > parse ( String s ) { if ( s == null ) return null ; List < ANSIToken > tokens = new LinkedList < ANSIToken > ( ) ; ANSIToken t = new ANSIToken ( ) ; char open = ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == '' || c == '' ) { if ( open != && ( i + < s . length ( ) ) ) { char next = s . charAt ( i + ) ; if ( ! Character . isWhitespace ( next ) && next != '' && next != '' ) { t . add ( c ) ; continue ; } } tokens . add ( t ) ; t = new ANSIToken ( ) ; if ( open == ) { t . addProperty ( getColor ( c ) ) ; open = c ; } else { open = ; } } else { t . add ( c ) ; } } tokens . add ( t ) ; return tokens ; } private static int getColor ( char c ) { if ( c == '' ) return ANSIToken . YELLOW ; if ( c == '' ) return ANSIToken . CYAN ; return ANSIToken . RED ; } } package org . rubypeople . rdt . internal . ui . infoviews ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . Reader ; import java . io . StringReader ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . StringTokenizer ; import java . util . Timer ; import java . util . TimerTask ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . browser . Browser ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . events . FocusAdapter ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . part . PageBook ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rdocexport . RDocUtility ; import org . rubypeople . rdt . internal . ui . rdocexport . RdocListener ; import org . rubypeople . rdt . internal . ui . util . CollectionContentProvider ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RIView extends ViewPart implements RdocListener , IVMInstallChangedListener { private PageBook pageBook ; private SashForm form ; private Text searchStr ; private TableViewer searchListViewer ; private Browser searchResult ; private static List < String > fgPossibleMatches = new ArrayList < String > ( ) ; private IStructuredContentProvider contentProvider = new CollectionContentProvider ( ) ; private RubyInvokerJob latestJob ; private MyViewerFilter filter ; private Timer timer ; private Table searchTable ; public RIView ( ) { RubyRuntime . addVMInstallChangedListener ( this ) ; } public void createPartControl ( Composite parent ) { contributeToActionBars ( ) ; pageBook = new PageBook ( parent , SWT . NONE ) ; Label inProgressLabel = new Label ( pageBook , SWT . LEFT | SWT . TOP | SWT . WRAP ) ; inProgressLabel . setText ( InfoViewMessages . RubyInformation_please_wait ) ; form = new SashForm ( pageBook , SWT . HORIZONTAL ) ; Composite panel = new Composite ( form , SWT . NONE ) ; panel . setLayout ( new GridLayout ( , false ) ) ; timer = new Timer ( ) ; searchStr = new Text ( panel , SWT . BORDER | SWT . SEARCH ) ; GridData data = new GridData ( ) ; data . horizontalAlignment = SWT . FILL ; searchStr . setLayoutData ( data ) ; searchStr . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { if ( timer != null ) timer . cancel ( ) ; timer = new Timer ( ) ; TimerTask task = new TimerTask ( ) { @ Override public void run ( ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { filterSearchList ( ) ; } } ) ; } } ; timer . schedule ( task , ) ; } } ) ; searchStr . setMessage ( "" ) ; searchStr . addKeyListener ( new KeyAdapter ( ) { public void keyPressed ( KeyEvent e ) { super . keyPressed ( e ) ; if ( e . keyCode == || e . keyCode == ) { searchListViewer . getTable ( ) . setFocus ( ) ; } else if ( e . keyCode == SWT . ESC ) { searchStr . setText ( "" ) ; } } } ) ; searchTable = new Table ( panel , SWT . BORDER | SWT . V_SCROLL | SWT . H_SCROLL | SWT . VIRTUAL ) ; searchListViewer = new TableViewer ( searchTable ) ; searchListViewer . setContentProvider ( contentProvider ) ; data = new GridData ( GridData . FILL_VERTICAL | GridData . FILL_HORIZONTAL ) ; searchListViewer . getTable ( ) . setLayoutData ( data ) ; searchListViewer . getTable ( ) . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { widgetSelected ( e ) ; } public void widgetSelected ( SelectionEvent e ) { showSelectedItem ( ) ; } } ) ; searchStr . addFocusListener ( new FocusAdapter ( ) { public void focusGained ( FocusEvent e ) { searchStr . selectAll ( ) ; } } ) ; filter = new MyViewerFilter ( ) ; try { searchResult = new Browser ( form , SWT . BORDER ) ; searchResult . setText ( "" ) ; } catch ( Exception e ) { MessageDialog . openError ( Display . getDefault ( ) . getActiveShell ( ) , "" , "" ) ; } form . setWeights ( new int [ ] { , } ) ; pageBook . showPage ( inProgressLabel ) ; updatePage ( ) ; RDocUtility . addRdocListener ( this ) ; } private void contributeToActionBars ( ) { IAction refreshAction = new Action ( ) { public void run ( ) { Job job = new Job ( "" ) { @ Override public IStatus run ( IProgressMonitor monitor ) { RiUtility . rebuildIndex ( ) ; updatePage ( ) ; return Status . OK_STATUS ; } } ; job . schedule ( ) ; } } ; refreshAction . setText ( InfoViewMessages . RubyInformation_refresh ) ; refreshAction . setToolTipText ( InfoViewMessages . RubyInformation_refresh_tooltip ) ; refreshAction . setImageDescriptor ( RubyPluginImages . TOOLBAR_REFRESH ) ; IToolBarManager manager = getViewSite ( ) . getActionBars ( ) . getToolBarManager ( ) ; manager . add ( refreshAction ) ; } private void updatePage ( ) { initSearchList ( ) ; Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { pageBook . showPage ( form ) ; } } ) ; } private void showSelectedItem ( ) { String searchText = ( String ) ( ( IStructuredSelection ) searchListViewer . getSelection ( ) ) . getFirstElement ( ) ; if ( latestJob != null && latestJob . getState ( ) != Job . NONE ) { latestJob . cancel ( ) ; } latestJob = new RubyInvokerJob ( new RIDescriptionUpdater ( searchText ) ) ; latestJob . setPriority ( Job . INTERACTIVE ) ; latestJob . schedule ( ) ; } public void dispose ( ) { RDocUtility . removeRdocListener ( this ) ; RubyRuntime . removeVMInstallChangedListener ( this ) ; filter = null ; super . dispose ( ) ; } private synchronized void initSearchList ( ) { RubyInvoker invoker = new RIPopulator ( ) ; Job job = new RubyInvokerJob ( invoker ) ; job . setPriority ( Job . LONG ) ; job . schedule ( ) ; } protected List < String > read ( Reader reader ) { Set < String > results = new HashSet < String > ( ) ; BufferedReader reader2 = null ; try { reader2 = new BufferedReader ( reader ) ; String line = null ; while ( ( line = reader2 . readLine ( ) ) != null ) { results . add ( line . trim ( ) ) ; } } catch ( IOException e ) { RubyPlugin . log ( e ) ; } finally { try { if ( reader2 != null ) reader2 . close ( ) ; } catch ( IOException e ) { } } List < String > list = new ArrayList < String > ( results ) ; Collections . sort ( list ) ; return list ; } private static class RubyInvokerJob extends Job { private RubyInvoker invoker ; public RubyInvokerJob ( RubyInvoker invoker ) { super ( InfoViewMessages . RubyInformation_update_job_title ) ; this . invoker = invoker ; } @ Override protected IStatus run ( IProgressMonitor monitor ) { invoker . invoke ( ) ; return Status . OK_STATUS ; } } private void filterSearchList ( ) { UIJob job = new UIJob ( "" ) { @ Override public IStatus runInUIThread ( IProgressMonitor monitor ) { List < String > filtered = filter ( searchStr . getText ( ) ) ; searchTable . setItemCount ( filtered . size ( ) ) ; searchTable . clearAll ( ) ; searchListViewer . setInput ( filtered ) ; if ( searchTable . getItemCount ( ) > ) searchTable . setSelection ( ) ; if ( searchTable . getItemCount ( ) == ) showSelectedItem ( ) ; return Status . OK_STATUS ; } } ; job . schedule ( ) ; } protected List < String > filter ( String text ) { filter . setText ( text ) ; List < String > filtered = new ArrayList < String > ( ) ; for ( String possible : fgPossibleMatches ) { if ( filter . select ( null , null , possible ) ) filtered . add ( possible ) ; } return filtered ; } public void setFocus ( ) { form . setFocus ( ) ; } abstract class RubyInvoker { protected abstract List < String > getArgList ( ) ; protected abstract void handleOutput ( String content ) ; protected void beforeInvoke ( ) { } public abstract void invoke ( ) ; } private class RIDescriptionUpdater extends RubyInvoker { private String searchValue ; private StringBuilder buffer ; RIDescriptionUpdater ( String value ) { this . searchValue = value ; } @ Override public void invoke ( ) { String content = RiUtility . getRIHTMLContents ( getArgList ( ) ) ; if ( content == null ) { content = "" ; } handleOutput ( content ) ; } protected List < String > getArgList ( ) { List < String > args = new ArrayList < String > ( ) ; args . add ( searchValue ) ; return args ; } protected void beforeInvoke ( ) { searchResult . setText ( InfoViewMessages . RubyInformation_please_wait ) ; } protected void handleOutput ( final String content ) { if ( content == null ) return ; buffer = new StringBuilder ( ) ; buffer . append ( content ) ; int index = buffer . indexOf ( "" ) ; buffer . replace ( index , index + , "" ) ; final String text = buffer . toString ( ) ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { searchResult . setText ( text ) ; } } ) ; } } public void rdocChanged ( ) { updatePage ( ) ; } private class RIPopulator extends RubyInvoker { @ Override public void invoke ( ) { String content = RiUtility . getRIContents ( getArgList ( ) ) ; if ( content == null ) { content = "" ; } handleOutput ( content ) ; } @ Override protected List < String > getArgList ( ) { List < String > args = new ArrayList < String > ( ) ; args . add ( "" ) ; args . add ( "" ) ; return args ; } @ Override protected void handleOutput ( String content ) { if ( content == null ) return ; BufferedReader reader = new BufferedReader ( new StringReader ( content ) ) ; String line = null ; fgPossibleMatches = read ( new StringReader ( content ) ) ; Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { searchListViewer . setInput ( fgPossibleMatches ) ; filterSearchList ( ) ; pageBook . showPage ( form ) ; } } ) ; } } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { updatePage ( ) ; } public void vmAdded ( IVMInstall newVm ) { } public void vmChanged ( PropertyChangeEvent event ) { } public void vmRemoved ( IVMInstall removedVm ) { } private static class MyViewerFilter extends ViewerFilter { private List < String > userTokens ; public void setText ( String value ) { if ( value == null || value . trim ( ) . length ( ) == ) { this . userTokens = null ; } else { this . userTokens = getTokens ( value ) ; } } @ Override public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( userTokens == null ) return true ; String riEntry = ( String ) element ; List < String > riListTokens = getTokens ( riEntry ) ; if ( userTokens . size ( ) == ) { String userInput = userTokens . get ( ) ; for ( int i = ; i < riListTokens . size ( ) ; i ++ ) { if ( riListTokens . get ( i ) . startsWith ( userInput ) ) { return true ; } } return false ; } else { if ( userTokens . size ( ) > riListTokens . size ( ) ) return false ; for ( int i = ; i < userTokens . size ( ) ; i ++ ) { if ( ! riListTokens . get ( i ) . startsWith ( userTokens . get ( i ) ) ) { return false ; } } return true ; } } private List < String > getTokens ( String raw ) { List < String > tokens = new ArrayList < String > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( raw , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) { tokens . add ( tokenizer . nextToken ( ) . toLowerCase ( ) ) ; } return tokens ; } } } package org . rubypeople . rdt . internal . ui . infoviews ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . ui . actions . OpenAction ; class GotoInputAction extends Action { private AbstractInfoView fInfoView ; public GotoInputAction ( AbstractInfoView infoView ) { Assert . isNotNull ( infoView ) ; fInfoView = infoView ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; setText ( InfoViewMessages . GotoInputAction_label ) ; setToolTipText ( InfoViewMessages . GotoInputAction_tooltip ) ; setDescription ( InfoViewMessages . GotoInputAction_description ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . OPEN_INPUT_ACTION ) ; } public void run ( ) { IRubyElement inputElement = fInfoView . getInput ( ) ; new OpenAction ( fInfoView . getViewSite ( ) ) . run ( new Object [ ] { inputElement } ) ; } } package org . rubypeople . rdt . internal . ui . infoviews ; import org . eclipse . osgi . util . NLS ; class InfoViewMessages extends NLS { private static final String BUNDLE_NAME = InfoViewMessages . class . getName ( ) ; public static String RubyInformation_ri_not_found ; public static String RubyInformation_please_wait ; public static String RubyInformation_refresh ; public static String RubyInformation_refresh_tooltip ; public static String RubyInformation_update_job_title ; public static String SelectAllAction_label ; public static String SelectAllAction_tooltip ; public static String SelectAllAction_description ; public static String RubydocView_error_noBrowser_title ; public static String RubydocView_error_noBrowser_message ; public static String RubydocView_error_noBrowser_doNotWarn ; public static String RubydocView_noAttachedInformation ; public static String GotoInputAction_label ; public static String GotoInputAction_tooltip ; public static String GotoInputAction_description ; static { NLS . initializeMessages ( BUNDLE_NAME , InfoViewMessages . class ) ; } } package org . rubypeople . rdt . internal . ui . infoviews ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileReader ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . core . IStreamListener ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . core . model . IStreamMonitor ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . swt . SWT ; import org . rubypeople . rdt . core . IRubyInformation ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . ui . text . ansi . ANSIParser ; import org . rubypeople . rdt . ui . text . ansi . ANSIToken ; import com . aptana . rdt . AptanaRDTPlugin ; public class RiUtility implements IRubyInformation { private final static String HEADER = "" ; private final static String TAIL = "" ; private static final String FASTRI_INDEX = "" ; public String getDocs ( String token ) { List < String > args = new ArrayList < String > ( ) ; args . add ( token ) ; return getRIContents ( args ) ; } public static String getRIContents ( List < String > args ) { File file = getFRIIndexFile ( ) ; if ( ! file . exists ( ) ) { buildIndex ( ) ; } args . add ( , "" ) ; return execAndReadOutput ( getFastRiPath ( ) , args ) ; } public static String getRIHTMLContents ( List < String > args ) { String result = getRIContents ( args ) ; if ( result == null ) return result ; StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( checkForANSIColors ( escapeHTML ( result ) ) ) ; buffer . insert ( , HEADER ) ; buffer . append ( TAIL ) ; return buffer . toString ( ) ; } private static String checkForANSIColors ( String string ) { StringBuilder buffer = new StringBuilder ( ) ; List < ANSIToken > tokens = getParser ( string ) . parse ( string ) ; for ( ANSIToken token : tokens ) { String endTag = "" ; if ( token . hasFontStyle ( ) ) { if ( token . getFontStyle ( ) == SWT . BOLD ) { buffer . append ( "" ) ; endTag = "" ; } else if ( token . getFontStyle ( ) == SWT . ITALIC ) { buffer . append ( "" ) ; endTag = "" ; } } if ( token . hasForegroundColor ( ) ) { buffer . append ( "" ) ; buffer . append ( pad ( Integer . toHexString ( token . getForegroundRGB ( ) . red ) ) ) ; buffer . append ( pad ( Integer . toHexString ( token . getForegroundRGB ( ) . green ) ) ) ; buffer . append ( pad ( Integer . toHexString ( token . getForegroundRGB ( ) . blue ) ) ) ; buffer . append ( "" ) ; endTag = "" + endTag ; } buffer . append ( token . toString ( ) ) ; buffer . append ( endTag ) ; } return buffer . toString ( ) ; } private static ANSIParser getParser ( String content ) { if ( content . indexOf ( ANSIParser . ESC ) != - ) return new ANSIParser ( ) ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) && ! RubyRuntime . currentVMIsCygwin ( ) && ! RubyRuntime . currentVMIsJRuby ( ) ) return new FastRIParser ( ) ; return new ANSIParser ( ) ; } private static String pad ( String hexString ) { if ( hexString . length ( ) == ) return "" + hexString ; return hexString ; } private static String escapeHTML ( final String content ) { String escaped = content . replace ( "" , "" ) ; escaped = escaped . replace ( "" , "" ) ; escaped = escaped . replace ( ">" , "" ) ; escaped = escaped . replace ( "" , "" ) ; escaped = escaped . replace ( "" , "" ) ; escaped = escaped . replace ( "" , "" ) ; return escaped ; } static void rebuildIndex ( ) { File file = getFRIIndexFile ( ) ; file . delete ( ) ; buildIndex ( ) ; } static void buildIndex ( ) { List < String > commands = new ArrayList < String > ( ) ; commands . add ( "" ) ; String output = execAndReadOutput ( getFastRiServerPath ( ) , commands ) ; } private static File getFRIIndexFile ( ) { if ( RubyRuntime . currentVMIsCygwin ( ) ) { return new File ( RubyRuntime . getDefaultVMInstall ( ) . getInstallLocation ( ) , FASTRI_INDEX ) ; } String homePath = System . getProperty ( "" ) ; return new File ( homePath + File . separator + FASTRI_INDEX ) ; } private static String getFastRiPath ( ) { copyFastRIFiles ( ) ; File file = LaunchingPlugin . getFileInPlugin ( new Path ( "" ) ) ; if ( file == null || ! file . exists ( ) || ! file . isFile ( ) ) return null ; return file . getAbsolutePath ( ) ; } private static void copyFastRIFiles ( ) { RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) ) ; } private static String getFastRiServerPath ( ) { copyFastRIFiles ( ) ; File file = LaunchingPlugin . getFileInPlugin ( new Path ( "" ) ) ; if ( file == null || ! file . exists ( ) || ! file . isFile ( ) ) return null ; return file . getAbsolutePath ( ) ; } private static ILaunchConfigurationType getRubyApplicationConfigType ( ) { return getLaunchManager ( ) . getLaunchConfigurationType ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ; } private static ILaunchManager getLaunchManager ( ) { return DebugPlugin . getDefault ( ) . getLaunchManager ( ) ; } private synchronized static String execAndReadOutput ( String file , List < String > commands ) { if ( file == null || file . trim ( ) . length ( ) == ) { RubyPlugin . log ( IStatus . ERROR , "" + commands . toString ( ) ) ; return "" ; } ILaunchConfiguration config = createConfiguration ( file , listToCommandLine ( commands ) ) ; File output = RubyPlugin . getDefault ( ) . getStateLocation ( ) . append ( "" ) . toFile ( ) ; return launchInBackgroundAndRead ( config , output ) ; } private static String listToCommandLine ( List < String > commands ) { String arguments = "" ; for ( String command : commands ) { arguments += command ; arguments += "" ; } if ( arguments . length ( ) > ) arguments = arguments . substring ( , arguments . length ( ) - ) ; return arguments ; } private static ILaunchConfiguration createConfiguration ( String file , String arguments ) { ILaunchConfiguration config = null ; try { ILaunchConfigurationType configType = getRubyApplicationConfigType ( ) ; ILaunchConfigurationWorkingCopy wc = configType . newInstance ( null , RubyRuntime . generateUniqueLaunchConfigurationNameFrom ( file ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , file ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , RubyRuntime . getDefaultVMInstall ( ) . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE , RubyRuntime . getDefaultVMInstall ( ) . getVMInstallType ( ) . getId ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROGRAM_ARGUMENTS , arguments ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_ARGUMENTS , "" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( IRubyLaunchConfigurationConstants . ATTR_RUBY_COMMAND , "" ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE_SPECIFIC_ATTRS_MAP , map ) ; wc . setAttribute ( IDebugUIConstants . ATTR_PRIVATE , true ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , LaunchingPlugin . getFileInPlugin ( new Path ( "" ) ) . getAbsolutePath ( ) ) ; wc . setAttribute ( IDebugUIConstants . ATTR_LAUNCH_IN_BACKGROUND , false ) ; config = wc . doSave ( ) ; } catch ( CoreException ce ) { } return config ; } private static String launchInBackgroundAndRead ( ILaunchConfiguration config , File file ) { final StringBuffer buf = new StringBuffer ( ) ; try { ILaunchConfigurationWorkingCopy wc = config . getWorkingCopy ( ) ; wc . setAttribute ( IDebugUIConstants . ATTR_LAUNCH_IN_BACKGROUND , true ) ; wc . setAttribute ( IDebugUIConstants . ATTR_CAPTURE_IN_CONSOLE , false ) ; wc . setAttribute ( IDebugUIConstants . ATTR_CAPTURE_IN_FILE , file . getAbsolutePath ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FORCE_NO_CONSOLE , true ) ; config = wc . doSave ( ) ; ILaunch launch = config . launch ( ILaunchManager . RUN_MODE , new NullProgressMonitor ( ) ) ; IProcess iproc = launch . getProcesses ( ) [ ] ; IStreamMonitor stdOut = iproc . getStreamsProxy ( ) . getOutputStreamMonitor ( ) ; stdOut . addListener ( new IStreamListener ( ) { public void streamAppended ( final String text , IStreamMonitor monitor ) { buf . append ( text ) ; } } ) ; while ( ! launch . isTerminated ( ) ) { Thread . yield ( ) ; } if ( buf . toString ( ) . trim ( ) . length ( ) == ) { buf . append ( readFile ( file ) ) ; } return buf . toString ( ) ; } catch ( Exception e ) { AptanaRDTPlugin . log ( e ) ; } return null ; } private static String readFile ( File file ) { StringBuffer buf = new StringBuffer ( ) ; BufferedReader reader = null ; try { reader = new BufferedReader ( new FileReader ( file ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { buf . append ( line ) ; buf . append ( "" ) ; } } catch ( FileNotFoundException e ) { AptanaRDTPlugin . log ( e ) ; } catch ( IOException e ) { AptanaRDTPlugin . log ( e ) ; } finally { try { if ( reader != null ) reader . close ( ) ; } catch ( IOException e ) { } } return buf . toString ( ) ; } } package org . rubypeople . rdt . internal . ui ; import java . io . IOException ; import java . util . PropertyResourceBundle ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunchListener ; import org . eclipse . jface . action . GroupMarker ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . templates . ContextTypeRegistry ; import org . eclipse . jface . text . templates . persistence . TemplateStore ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . navigator . ICommonMenuConstants ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . eclipse . ui . texteditor . ChainedPreferenceStore ; import org . eclipse . ui . texteditor . ConfigurationElementSorter ; import org . osgi . framework . Bundle ; import org . osgi . framework . BundleContext ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IRubyInformation ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . corext . util . OpenTypeHistory ; import org . rubypeople . rdt . internal . corext . util . TypeFilter ; import org . rubypeople . rdt . internal . formatter . OldCodeFormatter ; import org . rubypeople . rdt . internal . ui . infoviews . RiUtility ; import org . rubypeople . rdt . internal . ui . packageview . PackageExplorerPart ; import org . rubypeople . rdt . internal . ui . preferences . MembersOrderPreferenceCache ; import org . rubypeople . rdt . internal . ui . preferences . MockupPreferenceStore ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . internal . ui . rubyeditor . DocumentAdapter ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyDocumentProvider ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyScriptDocumentProvider ; import org . rubypeople . rdt . internal . ui . rubyeditor . WorkingCopyManager ; import org . rubypeople . rdt . internal . ui . text . PreferencesAdapter ; import org . rubypeople . rdt . internal . ui . text . folding . RubyFoldingStructureProviderRegistry ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . RubyEditorTextHoverDescriptor ; import org . rubypeople . rdt . internal . ui . text . template . contentassist . RubyTemplateAccess ; import org . rubypeople . rdt . internal . ui . viewsupport . ProblemMarkerManager ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . RubyTextTools ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; public class RubyPlugin extends AbstractUIPlugin { protected static RubyPlugin plugin ; public static final String PLUGIN_ID = "" ; protected RubyTextTools textTools ; protected RubyFileMatcher rubyFileMatcher ; private WorkingCopyManager fWorkingCopyManager ; private RubyDocumentProvider fDocumentProvider ; protected PropertyResourceBundle pluginProperties ; private IPreferenceStore fCombinedPreferenceStore ; private MockupPreferenceStore fMockupPreferenceStore ; private RubyFoldingStructureProviderRegistry fFoldingStructureProviderRegistry ; private ImageDescriptorRegistry fImageDescriptorRegistry ; private MembersOrderPreferenceCache fMembersOrderPreferenceCache ; private RubyScriptDocumentProvider fExternalRubyDocumentProvider ; private RubyEditorTextHoverDescriptor [ ] fRubyEditorTextHoverDescriptors ; private TypeFilter fTypeFilter ; private ProblemMarkerManager fProblemMarkerManager ; private ASTProvider fASTProvider ; private ILaunchListener launchListener ; private RubyExplorerTracker fRubyExplorerTracker ; public RubyPlugin ( ) { super ( ) ; } public MockupPreferenceStore getMockupPreferenceStore ( ) { if ( fMockupPreferenceStore == null ) fMockupPreferenceStore = new MockupPreferenceStore ( ) ; return fMockupPreferenceStore ; } public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; WorkingCopyOwner . setPrimaryBufferProvider ( new WorkingCopyOwner ( ) { public IBuffer createBuffer ( IRubyScript workingCopy ) { IRubyScript original = workingCopy . getPrimary ( ) ; IResource resource = original . getResource ( ) ; if ( resource instanceof IFile ) return new DocumentAdapter ( workingCopy , ( IFile ) resource ) ; return DocumentAdapter . NULL ; } } ) ; ensurePreferenceStoreBackwardsCompatibility ( ) ; if ( PlatformUI . isWorkbenchRunning ( ) ) { getASTProvider ( ) ; new InitializeAfterLoadJob ( ) . schedule ( ) ; } } private void ensurePreferenceStoreBackwardsCompatibility ( ) { IPreferenceStore store = getPreferenceStore ( ) ; fMembersOrderPreferenceCache = new MembersOrderPreferenceCache ( ) ; fMembersOrderPreferenceCache . install ( store ) ; } void initializeAfterLoad ( IProgressMonitor monitor ) { launchListener = new AptanaProcessConsoleManager ( ) ; DebugPlugin . getDefault ( ) . getLaunchManager ( ) . addLaunchListener ( launchListener ) ; getBundle ( ) . getBundleContext ( ) . registerService ( IRubyInformation . class . getName ( ) , new RiUtility ( ) , null ) ; OpenTypeHistory . getInstance ( ) . checkConsistency ( monitor ) ; new RubyInstalledDetector ( ) . schedule ( ) ; forceRDTUIPluginToLoad ( ) ; } private static void forceRDTUIPluginToLoad ( ) { try { Bundle b = Platform . getBundle ( "" ) ; if ( b == null ) return ; Class c = b . loadClass ( "" ) ; if ( c == null ) return ; c . newInstance ( ) ; } catch ( Exception e ) { } } public void stop ( BundleContext context ) throws Exception { try { if ( fWorkingCopyManager != null ) { fWorkingCopyManager . shutdown ( ) ; fWorkingCopyManager = null ; } if ( fDocumentProvider != null ) { fDocumentProvider . shutdown ( ) ; fDocumentProvider = null ; } if ( textTools != null ) { textTools . dispose ( ) ; textTools = null ; } if ( fTypeFilter != null ) { fTypeFilter . dispose ( ) ; fTypeFilter = null ; } if ( fMembersOrderPreferenceCache != null ) { fMembersOrderPreferenceCache . dispose ( ) ; fMembersOrderPreferenceCache = null ; } if ( fRubyExplorerTracker != null ) { PackageExplorerPart explorer = PackageExplorerPart . getFromActivePerspective ( ) ; if ( explorer != null ) { explorer . getSite ( ) . getSelectionProvider ( ) . removeSelectionChangedListener ( fRubyExplorerTracker ) ; } fRubyExplorerTracker = null ; } if ( launchListener != null ) { DebugPlugin . getDefault ( ) . getLaunchManager ( ) . removeLaunchListener ( launchListener ) ; launchListener = null ; } } finally { super . stop ( context ) ; } } public static void log ( String string ) { log ( IStatus . OK , string ) ; } public static RubyPlugin getDefault ( ) { return plugin ; } public static IWorkspace getWorkspace ( ) { return RubyCore . getWorkspace ( ) ; } public static IWorkbenchWindow getActiveWorkbenchWindow ( ) { return getDefault ( ) . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; } public static void log ( IStatus status ) { getDefault ( ) . getLog ( ) . log ( status ) ; System . out . println ( status . getMessage ( ) ) ; if ( status . getException ( ) != null ) status . getException ( ) . printStackTrace ( ) ; } public static void log ( Throwable e ) { log ( new Status ( IStatus . ERROR , PLUGIN_ID , IStatus . ERROR , RubyUIMessages . RdtUiPlugin_internalErrorOccurred , e ) ) ; } public static void log ( int severity , String message , Throwable e ) { Status status = new Status ( severity , PLUGIN_ID , IStatus . OK , message , e ) ; RubyPlugin . log ( status ) ; } public static Shell getActiveWorkbenchShell ( ) { return getActiveWorkbenchWindow ( ) . getShell ( ) ; } public synchronized RubyTextTools getRubyTextTools ( ) { if ( textTools == null ) textTools = new RubyTextTools ( getPreferenceStore ( ) , RubyCore . getPlugin ( ) . getPluginPreferences ( ) ) ; return textTools ; } public OldCodeFormatter getCodeFormatter ( ) { return new OldCodeFormatter ( RubyCore . getOptions ( ) ) ; } public static IWorkbenchPage getActivePage ( ) { IWorkbenchWindow window = getDefault ( ) . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; if ( window == null ) return null ; return window . getActivePage ( ) ; } public RubyFileMatcher getRubyFileMatcher ( ) { if ( rubyFileMatcher == null ) { rubyFileMatcher = new RubyFileMatcher ( ) ; } return rubyFileMatcher ; } public IResource getSelectedResource ( ) { IWorkbenchPage page = RubyPlugin . getActivePage ( ) ; if ( page == null ) { return null ; } ISelection selection = page . getSelection ( ) ; if ( selection instanceof IStructuredSelection && ! selection . isEmpty ( ) ) { IStructuredSelection structuredSelection = ( IStructuredSelection ) selection ; Object obj = structuredSelection . getFirstElement ( ) ; if ( obj instanceof IResource ) { return ( IResource ) obj ; } } IEditorPart part = page . getActiveEditor ( ) ; if ( part == null ) { return null ; } IEditorInput input = part . getEditorInput ( ) ; return ( IResource ) input . getAdapter ( IResource . class ) ; } public boolean isRubyFile ( IFile file ) { return this . getRubyFileMatcher ( ) . hasRubyEditorAssociation ( file ) ; } public boolean isRubyFile ( IResource resource ) { if ( resource == null || ! ( resource instanceof IFile ) ) { return false ; } return isRubyFile ( ( IFile ) resource ) ; } public WorkingCopyManager getWorkingCopyManager ( ) { if ( fWorkingCopyManager == null ) { RubyDocumentProvider provider = getRubyDocumentProvider ( ) ; fWorkingCopyManager = new WorkingCopyManager ( provider ) ; } return fWorkingCopyManager ; } public synchronized RubyDocumentProvider getRubyDocumentProvider ( ) { if ( fDocumentProvider == null ) fDocumentProvider = new RubyDocumentProvider ( ) ; return fDocumentProvider ; } public synchronized RubyFoldingStructureProviderRegistry getFoldingStructureProviderRegistry ( ) { if ( fFoldingStructureProviderRegistry == null ) fFoldingStructureProviderRegistry = new RubyFoldingStructureProviderRegistry ( ) ; return fFoldingStructureProviderRegistry ; } public static String getPluginId ( ) { return PLUGIN_ID ; } public static void log ( int severity , String string ) { log ( new Status ( severity , PLUGIN_ID , IStatus . OK , string , null ) ) ; } public IPreferenceStore getCombinedPreferenceStore ( ) { if ( fCombinedPreferenceStore == null ) { IPreferenceStore generalTextStore = EditorsUI . getPreferenceStore ( ) ; fCombinedPreferenceStore = new ChainedPreferenceStore ( new IPreferenceStore [ ] { getPreferenceStore ( ) , new PreferencesAdapter ( RubyCore . getPlugin ( ) . getPluginPreferences ( ) ) , generalTextStore } ) ; } return fCombinedPreferenceStore ; } public static void logErrorMessage ( String message ) { log ( new Status ( IStatus . ERROR , getPluginId ( ) , IRubyStatusConstants . INTERNAL_ERROR , message , null ) ) ; } public TemplateStore getTemplateStore ( ) { return RubyTemplateAccess . getDefault ( ) . getTemplateStore ( ) ; } public ContextTypeRegistry getTemplateContextRegistry ( ) { return RubyTemplateAccess . getDefault ( ) . getContextTypeRegistry ( ) ; } public static boolean isDebug ( ) { return getDefault ( ) . isDebugging ( ) ; } public static void createStandardGroups ( IMenuManager menu ) { if ( ! menu . isEmpty ( ) ) return ; menu . add ( new Separator ( IContextMenuConstants . GROUP_NEW ) ) ; menu . add ( new GroupMarker ( IContextMenuConstants . GROUP_GOTO ) ) ; menu . add ( new Separator ( IContextMenuConstants . GROUP_OPEN ) ) ; menu . add ( new GroupMarker ( IContextMenuConstants . GROUP_SHOW ) ) ; menu . add ( new Separator ( ICommonMenuConstants . GROUP_EDIT ) ) ; menu . add ( new Separator ( IContextMenuConstants . GROUP_REORGANIZE ) ) ; menu . add ( new Separator ( IContextMenuConstants . GROUP_GENERATE ) ) ; menu . add ( new Separator ( IContextMenuConstants . GROUP_SEARCH ) ) ; menu . add ( new Separator ( IContextMenuConstants . GROUP_BUILD ) ) ; menu . add ( new Separator ( IContextMenuConstants . GROUP_ADDITIONS ) ) ; menu . add ( new Separator ( IContextMenuConstants . GROUP_VIEWER_SETUP ) ) ; menu . add ( new Separator ( IContextMenuConstants . GROUP_PROPERTIES ) ) ; } public static ImageDescriptorRegistry getImageDescriptorRegistry ( ) { return getDefault ( ) . internalGetImageDescriptorRegistry ( ) ; } private synchronized ImageDescriptorRegistry internalGetImageDescriptorRegistry ( ) { if ( fImageDescriptorRegistry == null ) fImageDescriptorRegistry = new ImageDescriptorRegistry ( ) ; return fImageDescriptorRegistry ; } public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache ( ) { return fMembersOrderPreferenceCache ; } public synchronized RubyScriptDocumentProvider getExternalDocumentProvider ( ) { if ( fExternalRubyDocumentProvider == null ) fExternalRubyDocumentProvider = new RubyScriptDocumentProvider ( ) ; return fExternalRubyDocumentProvider ; } public PropertyResourceBundle getPluginProperties ( ) { if ( pluginProperties == null ) { try { pluginProperties = new PropertyResourceBundle ( FileLocator . openStream ( this . getBundle ( ) , new Path ( "" ) , false ) ) ; } catch ( IOException e ) { log ( e ) ; } } return pluginProperties ; } public synchronized TypeFilter getTypeFilter ( ) { if ( fTypeFilter == null ) fTypeFilter = new TypeFilter ( ) ; return fTypeFilter ; } public IDialogSettings getDialogSettingsSection ( String name ) { IDialogSettings dialogSettings = getDialogSettings ( ) ; IDialogSettings section = dialogSettings . getSection ( name ) ; if ( section == null ) { section = dialogSettings . addNewSection ( name ) ; } return section ; } public RubyEditorTextHoverDescriptor [ ] getRubyEditorTextHoverDescriptors ( ) { Preferences prefs = getPluginPreferences ( ) ; if ( prefs != null && ! prefs . getBoolean ( PreferenceConstants . HOVERS_ENABLED ) ) { return new RubyEditorTextHoverDescriptor [ ] ; } if ( fRubyEditorTextHoverDescriptors == null ) { fRubyEditorTextHoverDescriptors = RubyEditorTextHoverDescriptor . getContributedHovers ( ) ; ConfigurationElementSorter sorter = new ConfigurationElementSorter ( ) { public IConfigurationElement getConfigurationElement ( Object object ) { return ( ( RubyEditorTextHoverDescriptor ) object ) . getConfigurationElement ( ) ; } } ; sorter . sort ( fRubyEditorTextHoverDescriptors ) ; for ( int i = ; i < fRubyEditorTextHoverDescriptors . length - ; i ++ ) { if ( PreferenceConstants . ID_BESTMATCH_HOVER . equals ( fRubyEditorTextHoverDescriptors [ i ] . getId ( ) ) ) { RubyEditorTextHoverDescriptor hoverDescriptor = fRubyEditorTextHoverDescriptors [ i ] ; for ( int j = i ; j > ; j -- ) fRubyEditorTextHoverDescriptors [ j ] = fRubyEditorTextHoverDescriptors [ j - ] ; fRubyEditorTextHoverDescriptors [ ] = hoverDescriptor ; break ; } } } return fRubyEditorTextHoverDescriptors ; } public synchronized ProblemMarkerManager getProblemMarkerManager ( ) { if ( fProblemMarkerManager == null ) fProblemMarkerManager = new ProblemMarkerManager ( ) ; return fProblemMarkerManager ; } public synchronized ASTProvider getASTProvider ( ) { if ( fASTProvider == null ) fASTProvider = new ASTProvider ( ) ; return fASTProvider ; } public RubyExplorerTracker getProjectTracker ( ) { if ( fRubyExplorerTracker == null ) { fRubyExplorerTracker = new RubyExplorerTracker ( ) ; } return fRubyExplorerTracker ; } public static ImageDescriptor getImageDescriptor ( String path ) { return AbstractUIPlugin . imageDescriptorFromPlugin ( PLUGIN_ID , path ) ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . TabFolder ; import org . eclipse . swt . widgets . TabItem ; import org . eclipse . ui . IWorkbenchPropertyPage ; import org . eclipse . ui . dialogs . PropertyPage ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public class RubyProjectPropertyPage extends PropertyPage implements IWorkbenchPropertyPage { protected RubyProjectLibraryPage projectsPage ; protected RubyProject workingProject ; public RubyProjectPropertyPage ( ) { } protected Control createContents ( Composite parent ) { noDefaultAndApplyButton ( ) ; workingProject = getRubyProject ( ) ; if ( workingProject == null || ! workingProject . getProject ( ) . isOpen ( ) ) return createClosedProjectPageContents ( parent ) ; return createProjectPageContents ( parent ) ; } protected RubyProject getRubyProject ( ) { IAdaptable selectedElement = getElement ( ) ; if ( selectedElement == null ) return null ; if ( selectedElement instanceof RubyProject ) return ( RubyProject ) selectedElement ; if ( selectedElement instanceof IProject ) { IProject simpleProject = ( IProject ) selectedElement ; try { if ( simpleProject . hasNature ( RubyCore . NATURE_ID ) ) { RubyProject theRubyProject = new RubyProject ( ) ; theRubyProject . setProject ( simpleProject ) ; return theRubyProject ; } } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } return null ; } protected Control createClosedProjectPageContents ( Composite parent ) { Label label = new Label ( parent , SWT . NONE ) ; label . setText ( RubyUIMessages . RubyProjectPropertyPage_rubyProjectClosed ) ; return label ; } protected Control createProjectPageContents ( Composite parent ) { TabFolder tabFolder = new TabFolder ( parent , SWT . NONE ) ; tabFolder . setLayout ( new GridLayout ( ) ) ; tabFolder . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; tabFolder . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { } } ) ; projectsPage = new RubyProjectLibraryPage ( workingProject ) ; TabItem tabItem = new TabItem ( tabFolder , SWT . NONE ) ; tabItem . setText ( RubyUIMessages . RubyProjectLibraryPage_tabName ) ; tabItem . setControl ( projectsPage . getControl ( tabFolder ) ) ; return tabFolder ; } public boolean performOk ( ) { try { projectsPage . getWorkingProject ( ) . save ( null , true ) ; } catch ( CoreException e ) { ExceptionHandler . handle ( e , RubyUIMessages . RubyProjectPropertyPage_performOkException , RubyUIMessages . RubyProjectPropertyPage_performOkExceptionDialogMessage ) ; } return super . performOk ( ) ; } } package org . rubypeople . rdt . internal . corext . dom ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . jruby . ast . Node ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; public class SelectionAnalyzer extends InOrderVisitor { private Selection fSelection ; private boolean fTraverseSelectedNode ; private Node fLastCoveringNode ; private List < Node > fSelectedNodes ; public SelectionAnalyzer ( Selection selection , boolean traverseSelectedNode ) { Assert . isNotNull ( selection ) ; fSelection = selection ; fTraverseSelectedNode = traverseSelectedNode ; } public boolean hasSelectedNodes ( ) { return fSelectedNodes != null && ! fSelectedNodes . isEmpty ( ) ; } public Node [ ] getSelectedNodes ( ) { if ( fSelectedNodes == null || fSelectedNodes . isEmpty ( ) ) return new Node [ ] ; return ( Node [ ] ) fSelectedNodes . toArray ( new Node [ fSelectedNodes . size ( ) ] ) ; } public Node getFirstSelectedNode ( ) { if ( fSelectedNodes == null || fSelectedNodes . isEmpty ( ) ) return null ; return ( Node ) fSelectedNodes . get ( ) ; } public Node getLastSelectedNode ( ) { if ( fSelectedNodes == null || fSelectedNodes . isEmpty ( ) ) return null ; return ( Node ) fSelectedNodes . get ( fSelectedNodes . size ( ) - ) ; } public IRegion getSelectedNodeRange ( ) { if ( fSelectedNodes == null || fSelectedNodes . isEmpty ( ) ) return null ; Node firstNode = ( Node ) fSelectedNodes . get ( ) ; Node lastNode = ( Node ) fSelectedNodes . get ( fSelectedNodes . size ( ) - ) ; int start = firstNode . getPosition ( ) . getStartOffset ( ) ; return new Region ( start , lastNode . getPosition ( ) . getEndOffset ( ) - start ) ; } public Node getLastCoveringNode ( ) { return fLastCoveringNode ; } protected Selection getSelection ( ) { return fSelection ; } protected Object visitNode ( Node node ) { if ( fSelection . liesOutside ( node ) ) { return null ; } else if ( fSelection . covers ( node ) ) { if ( isFirstNode ( ) ) { handleFirstSelectedNode ( node ) ; } else { handleNextSelectedNode ( node ) ; } return null ; } else if ( fSelection . coveredBy ( node ) ) { fLastCoveringNode = node ; return null ; } else if ( fSelection . endsIn ( node ) ) { handleSelectionEndsIn ( node ) ; return null ; } return null ; } protected void reset ( ) { fSelectedNodes = null ; } protected void handleFirstSelectedNode ( Node node ) { fSelectedNodes = new ArrayList < Node > ( ) ; fSelectedNodes . add ( node ) ; } protected void handleNextSelectedNode ( Node node ) { fSelectedNodes . add ( node ) ; } protected boolean handleSelectionEndsIn ( Node node ) { return false ; } protected List < Node > internalGetSelectedNodes ( ) { return fSelectedNodes ; } private boolean isFirstNode ( ) { return fSelectedNodes == null ; } } package org . rubypeople . rdt . internal . corext . dom ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . IRegion ; import org . jruby . ast . Node ; public class Selection { public static final int INTERSECTS = ; public static final int BEFORE = ; public static final int SELECTED = ; public static final int AFTER = ; private int fStart ; private int fLength ; private int fExclusiveEnd ; protected Selection ( ) { } public static Selection createFromStartLength ( int s , int l ) { Assert . isTrue ( s >= && l >= ) ; Selection result = new Selection ( ) ; result . fStart = s ; result . fLength = l ; result . fExclusiveEnd = s + l ; return result ; } public static Selection createFromStartEnd ( int s , int e ) { Assert . isTrue ( s >= && e >= s ) ; Selection result = new Selection ( ) ; result . fStart = s ; result . fLength = e - s + ; result . fExclusiveEnd = result . fStart + result . fLength ; return result ; } public int getOffset ( ) { return fStart ; } public int getLength ( ) { return fLength ; } public int getInclusiveEnd ( ) { return fExclusiveEnd - ; } public int getExclusiveEnd ( ) { return fExclusiveEnd ; } public int getVisitSelectionMode ( Node node ) { int nodeStart = node . getPosition ( ) . getStartOffset ( ) ; int nodeEnd = node . getPosition ( ) . getEndOffset ( ) ; if ( nodeEnd <= fStart ) return BEFORE ; else if ( covers ( node ) ) return SELECTED ; else if ( fExclusiveEnd <= nodeStart ) return AFTER ; return INTERSECTS ; } public int getEndVisitSelectionMode ( Node node ) { int nodeStart = node . getPosition ( ) . getStartOffset ( ) ; int nodeEnd = node . getPosition ( ) . getEndOffset ( ) ; if ( nodeEnd <= fStart ) return BEFORE ; else if ( covers ( node ) ) return SELECTED ; else if ( nodeEnd >= fExclusiveEnd ) return AFTER ; return INTERSECTS ; } public boolean covers ( int position ) { return fStart <= position && position < fStart + fLength ; } public boolean covers ( Node node ) { int nodeStart = node . getPosition ( ) . getStartOffset ( ) ; return fStart <= nodeStart && node . getPosition ( ) . getEndOffset ( ) <= fExclusiveEnd ; } public boolean coveredBy ( Node node ) { int nodeStart = node . getPosition ( ) . getStartOffset ( ) ; return nodeStart <= fStart && fExclusiveEnd <= node . getPosition ( ) . getEndOffset ( ) ; } public boolean coveredBy ( IRegion region ) { int rangeStart = region . getOffset ( ) ; return rangeStart <= fStart && fExclusiveEnd <= rangeStart + region . getLength ( ) ; } public boolean endsIn ( Node node ) { int nodeStart = node . getPosition ( ) . getStartOffset ( ) ; return nodeStart < fExclusiveEnd && fExclusiveEnd < node . getPosition ( ) . getEndOffset ( ) ; } public boolean liesOutside ( Node node ) { int nodeStart = node . getPosition ( ) . getStartOffset ( ) ; int nodeEnd = node . getPosition ( ) . getEndOffset ( ) ; boolean nodeBeforeSelection = nodeEnd < fStart ; boolean selectionBeforeNode = fExclusiveEnd < nodeStart ; return nodeBeforeSelection || selectionBeforeNode ; } public String toString ( ) { return "" + fStart + "" + fLength + "" ; } } package org . rubypeople . rdt . internal . corext . template . ruby ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . templates . DocumentTemplateContext ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . text . template . contentassist . MultiVariableGuess ; public class RubyScriptContext extends DocumentTemplateContext { private IRubyScript fRubyScript ; protected boolean fForceEvaluation ; protected MultiVariableGuess fMultiVariableGuess ; protected RubyScriptContext ( TemplateContextType type , IDocument document , int completionOffset , int completionLength , IRubyScript rubyScript ) { super ( type , document , completionOffset , completionLength ) ; fRubyScript = rubyScript ; } public final IRubyScript getRubyScript ( ) { return fRubyScript ; } public void setForceEvaluation ( boolean evaluate ) { fForceEvaluation = evaluate ; } public MultiVariableGuess getMultiVariableGuess ( ) { return fMultiVariableGuess ; } public void setMultiVariableGuess ( MultiVariableGuess multiVariableGuess ) { fMultiVariableGuess = multiVariableGuess ; } } package org . rubypeople . rdt . internal . corext . template . ruby ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . templates . DocumentTemplateContext ; import org . eclipse . jface . text . templates . GlobalTemplateVariables ; import org . eclipse . jface . text . templates . TemplateBuffer ; import org . eclipse . jface . text . templates . TemplateContext ; import org . eclipse . jface . text . templates . TemplateVariable ; import org . eclipse . text . edits . DeleteEdit ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . RangeMarker ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . rubypeople . rdt . internal . corext . util . CodeFormatterUtil ; import org . rubypeople . rdt . internal . corext . util . Strings ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . RubyHeuristicScanner ; public class RubyFormatter { private static final String MARKER = "" + GlobalTemplateVariables . Cursor . NAME + "" ; private final String fLineDelimiter ; private final int fInitialIndentLevel ; private boolean fUseCodeFormatter ; private final IRubyProject fProject ; public RubyFormatter ( String lineDelimiter , int initialIndentLevel , boolean useCodeFormatter , IRubyProject project ) { fLineDelimiter = lineDelimiter ; fUseCodeFormatter = useCodeFormatter ; fInitialIndentLevel = initialIndentLevel ; fProject = project ; } public void format ( TemplateBuffer buffer , TemplateContext context ) throws BadLocationException { try { if ( fUseCodeFormatter ) try { format ( buffer , ( RubyContext ) context ) ; } catch ( BadLocationException e ) { indent ( buffer ) ; } catch ( MalformedTreeException e ) { indent ( buffer ) ; } else indent ( buffer ) ; if ( context instanceof DocumentTemplateContext ) { DocumentTemplateContext dtc = ( DocumentTemplateContext ) context ; if ( dtc . getStart ( ) == dtc . getCompletionOffset ( ) ) if ( dtc . getDocument ( ) . get ( dtc . getStart ( ) , dtc . getEnd ( ) - dtc . getStart ( ) ) . trim ( ) . length ( ) == ) return ; } trimBegin ( buffer ) ; } catch ( MalformedTreeException e ) { throw new BadLocationException ( ) ; } } private static int getCaretOffset ( TemplateVariable [ ] variables ) { for ( int i = ; i != variables . length ; i ++ ) { TemplateVariable variable = variables [ i ] ; if ( variable . getType ( ) . equals ( GlobalTemplateVariables . Cursor . NAME ) ) return variable . getOffsets ( ) [ ] ; } return - ; } private boolean isInsideCommentOrString ( String string , int offset ) { IDocument document = new Document ( string ) ; RubyPlugin . getDefault ( ) . getRubyTextTools ( ) . setupRubyDocumentPartitioner ( document ) ; try { ITypedRegion partition = document . getPartition ( offset ) ; String partitionType = partition . getType ( ) ; return partitionType != null && ( partitionType . equals ( IRubyPartitions . RUBY_MULTI_LINE_COMMENT ) || partitionType . equals ( IRubyPartitions . RUBY_SINGLE_LINE_COMMENT ) ) ; } catch ( BadLocationException e ) { return false ; } } private void format ( TemplateBuffer templateBuffer , RubyContext context ) throws BadLocationException { String string = templateBuffer . getString ( ) ; TemplateVariable [ ] variables = templateBuffer . getVariables ( ) ; int caretOffset = getCaretOffset ( variables ) ; if ( ( caretOffset > ) && Character . isWhitespace ( string . charAt ( caretOffset - ) ) && ( caretOffset < string . length ( ) ) && Character . isWhitespace ( string . charAt ( caretOffset ) ) && ! isInsideCommentOrString ( string , caretOffset ) ) { List positions = variablesToPositions ( variables ) ; TextEdit insert = new InsertEdit ( caretOffset , MARKER ) ; string = edit ( string , positions , insert ) ; positionsToVariables ( positions , variables ) ; templateBuffer . setContent ( string , variables ) ; try { plainFormat ( templateBuffer , context ) ; string = templateBuffer . getString ( ) ; variables = templateBuffer . getVariables ( ) ; caretOffset = getCaretOffset ( variables ) ; } finally { positions = variablesToPositions ( variables ) ; TextEdit delete = new DeleteEdit ( caretOffset , MARKER . length ( ) ) ; string = edit ( string , positions , delete ) ; positionsToVariables ( positions , variables ) ; templateBuffer . setContent ( string , variables ) ; } } else { plainFormat ( templateBuffer , context ) ; } } private void plainFormat ( TemplateBuffer templateBuffer , RubyContext context ) throws BadLocationException { IDocument doc = new Document ( templateBuffer . getString ( ) ) ; TemplateVariable [ ] variables = templateBuffer . getVariables ( ) ; List offsets = variablesToPositions ( variables ) ; Map options ; if ( context . getRubyScript ( ) != null ) options = context . getRubyScript ( ) . getRubyProject ( ) . getOptions ( true ) ; else options = RubyCore . getOptions ( ) ; String contents = doc . get ( ) ; int [ ] kinds = { CodeFormatter . K_EXPRESSION , CodeFormatter . K_STATEMENTS , CodeFormatter . K_UNKNOWN } ; TextEdit edit = null ; for ( int i = ; i < kinds . length && edit == null ; i ++ ) { edit = CodeFormatterUtil . format2 ( kinds [ i ] , contents , fInitialIndentLevel , fLineDelimiter , options ) ; } if ( edit == null ) throw new BadLocationException ( ) ; MultiTextEdit root ; if ( edit instanceof MultiTextEdit ) root = ( MultiTextEdit ) edit ; else { root = new MultiTextEdit ( , doc . getLength ( ) ) ; root . addChild ( edit ) ; } for ( Iterator it = offsets . iterator ( ) ; it . hasNext ( ) ; ) { TextEdit position = ( TextEdit ) it . next ( ) ; try { root . addChild ( position ) ; } catch ( MalformedTreeException e ) { } } root . apply ( doc , TextEdit . UPDATE_REGIONS ) ; positionsToVariables ( offsets , variables ) ; templateBuffer . setContent ( doc . get ( ) , variables ) ; } private void indent ( TemplateBuffer templateBuffer ) throws BadLocationException , MalformedTreeException { TemplateVariable [ ] variables = templateBuffer . getVariables ( ) ; List positions = variablesToPositions ( variables ) ; IDocument document = new Document ( templateBuffer . getString ( ) ) ; MultiTextEdit root = new MultiTextEdit ( , document . getLength ( ) ) ; root . addChildren ( ( TextEdit [ ] ) positions . toArray ( new TextEdit [ positions . size ( ) ] ) ) ; int offset = document . getLineOffset ( ) ; String indent = CodeFormatterUtil . createIndentString ( fInitialIndentLevel , fProject ) ; TextEdit edit = new InsertEdit ( offset , indent ) ; root . addChild ( edit ) ; root . apply ( document , TextEdit . UPDATE_REGIONS ) ; root . removeChild ( edit ) ; formatDelimiter ( document , root , ) ; int lineCount = document . getNumberOfLines ( ) ; RubyHeuristicScanner scanner = new RubyHeuristicScanner ( document ) ; for ( int line = ; line < lineCount ; line ++ ) { IRegion region = document . getLineInformation ( line ) ; offset = region . getOffset ( ) ; if ( indent == null ) continue ; edit = new ReplaceEdit ( offset , , indent . toString ( ) ) ; root . addChild ( edit ) ; root . apply ( document , TextEdit . UPDATE_REGIONS ) ; root . removeChild ( edit ) ; formatDelimiter ( document , root , line ) ; } positionsToVariables ( positions , variables ) ; templateBuffer . setContent ( document . get ( ) , variables ) ; } private void formatDelimiter ( IDocument document , MultiTextEdit root , int line ) throws BadLocationException { IRegion region = document . getLineInformation ( line ) ; String lineDelimiter = document . getLineDelimiter ( line ) ; if ( lineDelimiter != null ) { TextEdit edit = new ReplaceEdit ( region . getOffset ( ) + region . getLength ( ) , lineDelimiter . length ( ) , fLineDelimiter ) ; root . addChild ( edit ) ; root . apply ( document , TextEdit . UPDATE_REGIONS ) ; root . removeChild ( edit ) ; } } private static void trimBegin ( TemplateBuffer templateBuffer ) throws BadLocationException { String string = templateBuffer . getString ( ) ; TemplateVariable [ ] variables = templateBuffer . getVariables ( ) ; List positions = variablesToPositions ( variables ) ; int i = ; while ( ( i != string . length ( ) ) && Character . isWhitespace ( string . charAt ( i ) ) ) i ++ ; string = edit ( string , positions , new DeleteEdit ( , i ) ) ; positionsToVariables ( positions , variables ) ; templateBuffer . setContent ( string , variables ) ; } private static String edit ( String string , List positions , TextEdit edit ) throws BadLocationException { MultiTextEdit root = new MultiTextEdit ( , string . length ( ) ) ; root . addChildren ( ( TextEdit [ ] ) positions . toArray ( new TextEdit [ positions . size ( ) ] ) ) ; root . addChild ( edit ) ; IDocument document = new Document ( string ) ; root . apply ( document ) ; return document . get ( ) ; } private static List variablesToPositions ( TemplateVariable [ ] variables ) { List positions = new ArrayList ( ) ; for ( int i = ; i != variables . length ; i ++ ) { int [ ] offsets = variables [ i ] . getOffsets ( ) ; String value = variables [ i ] . getDefaultValue ( ) ; int wsStart = ; while ( wsStart < value . length ( ) && Character . isWhitespace ( value . charAt ( wsStart ) ) && ! Strings . isLineDelimiterChar ( value . charAt ( wsStart ) ) ) wsStart ++ ; variables [ i ] . getValues ( ) [ ] = value . substring ( wsStart ) ; for ( int j = ; j != offsets . length ; j ++ ) { offsets [ j ] += wsStart ; positions . add ( new RangeMarker ( offsets [ j ] , ) ) ; } } return positions ; } private static void positionsToVariables ( List positions , TemplateVariable [ ] variables ) { Iterator iterator = positions . iterator ( ) ; for ( int i = ; i != variables . length ; i ++ ) { TemplateVariable variable = variables [ i ] ; int [ ] offsets = new int [ variable . getOffsets ( ) . length ] ; for ( int j = ; j != offsets . length ; j ++ ) offsets [ j ] = ( ( TextEdit ) iterator . next ( ) ) . getOffset ( ) ; variable . setOffsets ( offsets ) ; } } } package org . rubypeople . rdt . internal . corext . template . ruby ; import org . eclipse . osgi . util . NLS ; public class RubyTemplateMessages extends NLS { private static final String BUNDLE_NAME = RubyTemplateMessages . class . getName ( ) ; private RubyTemplateMessages ( ) { } public static String ContextType_error_multiple_cursor_variables ; public static String Context_error_cannot_evaluate ; static { NLS . initializeMessages ( BUNDLE_NAME , RubyTemplateMessages . class ) ; } } package org . rubypeople . rdt . internal . corext . template . ruby ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . templates . GlobalTemplateVariables ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . eclipse . jface . text . templates . TemplateException ; import org . eclipse . jface . text . templates . TemplateVariable ; import org . rubypeople . rdt . core . IRubyScript ; public abstract class RubyScriptContextType extends TemplateContextType { public RubyScriptContextType ( String name ) { super ( name ) ; } public abstract RubyScriptContext createContext ( IDocument document , int completionPosition , int length , IRubyScript script ) ; protected void validateVariables ( TemplateVariable [ ] variables ) throws TemplateException { for ( int i = ; i < variables . length ; i ++ ) { TemplateVariable var = variables [ i ] ; if ( var . getType ( ) . equals ( GlobalTemplateVariables . Cursor . NAME ) ) { if ( var . getOffsets ( ) . length > ) { throw new TemplateException ( RubyTemplateMessages . ContextType_error_multiple_cursor_variables ) ; } } } } } package org . rubypeople . rdt . internal . corext . template . ruby ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . jface . text . templates . Template ; import org . eclipse . jface . text . templates . TemplateBuffer ; import org . eclipse . jface . text . templates . TemplateContextType ; import org . eclipse . jface . text . templates . TemplateException ; import org . eclipse . jface . text . templates . TemplateTranslator ; import org . eclipse . jface . text . templates . TemplateVariable ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . corext . util . Strings ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . template . contentassist . MultiVariable ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubyContext extends RubyScriptContext { public RubyContext ( TemplateContextType type , IDocument document , int completionOffset , int completionLength , IRubyScript compilationUnit ) { super ( type , document , completionOffset , completionLength , compilationUnit ) ; } public TemplateBuffer evaluate ( Template template ) throws BadLocationException , TemplateException { if ( ! canEvaluate ( template ) ) throw new TemplateException ( RubyTemplateMessages . Context_error_cannot_evaluate ) ; TemplateTranslator translator = new TemplateTranslator ( ) { protected TemplateVariable createVariable ( String type , String name , int [ ] offsets ) { return new MultiVariable ( type , name , offsets ) ; } } ; TemplateBuffer buffer = translator . translate ( template ) ; getContextType ( ) . resolve ( buffer , this ) ; IPreferenceStore prefs = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; boolean useCodeFormatter = prefs . getBoolean ( PreferenceConstants . TEMPLATES_USE_CODEFORMATTER ) ; IRubyProject project = getRubyScript ( ) != null ? getRubyScript ( ) . getRubyProject ( ) : null ; RubyFormatter formatter = new RubyFormatter ( TextUtilities . getDefaultLineDelimiter ( getDocument ( ) ) , getIndentation ( ) , useCodeFormatter , project ) ; formatter . format ( buffer , this ) ; return buffer ; } private int getIndentation ( ) { int start = getStart ( ) ; IDocument document = getDocument ( ) ; try { IRegion region = document . getLineInformationOfOffset ( start ) ; String lineContent = document . get ( region . getOffset ( ) , region . getLength ( ) ) ; IRubyScript compilationUnit = getRubyScript ( ) ; IRubyProject project = compilationUnit == null ? null : compilationUnit . getRubyProject ( ) ; return Strings . computeIndentUnits ( lineContent , project ) ; } catch ( BadLocationException e ) { return ; } } public boolean canEvaluate ( Template template ) { if ( fForceEvaluation ) return true ; String key = getKey ( ) ; return template . matches ( key , getContextType ( ) . getId ( ) ) && key . length ( ) != && template . getName ( ) . toLowerCase ( ) . startsWith ( key . toLowerCase ( ) ) ; } public String getKey ( ) { if ( getCompletionLength ( ) == ) return super . getKey ( ) ; try { IDocument document = getDocument ( ) ; int start = getStart ( ) ; int end = getCompletionOffset ( ) ; return start <= end ? document . get ( start , end - start ) : "" ; } catch ( BadLocationException e ) { return super . getKey ( ) ; } } public int getEnd ( ) { if ( getCompletionLength ( ) == ) return super . getEnd ( ) ; try { IDocument document = getDocument ( ) ; int start = getCompletionOffset ( ) ; int end = getCompletionOffset ( ) + getCompletionLength ( ) ; while ( start != end && Character . isWhitespace ( document . getChar ( end - ) ) ) end -- ; return end ; } catch ( BadLocationException e ) { return super . getEnd ( ) ; } } public int getStart ( ) { try { IDocument document = getDocument ( ) ; int start = getCompletionOffset ( ) ; int end = getCompletionOffset ( ) + getCompletionLength ( ) ; while ( start != && Character . isUnicodeIdentifierPart ( document . getChar ( start - ) ) ) start -- ; while ( start != end && Character . isWhitespace ( document . getChar ( start ) ) ) start ++ ; if ( start == end ) start = getCompletionOffset ( ) ; return start ; } catch ( BadLocationException e ) { return super . getStart ( ) ; } } } package org . rubypeople . rdt . internal . corext . template . ruby ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . templates . GlobalTemplateVariables ; import org . eclipse . jface . text . templates . SimpleTemplateVariableResolver ; import org . eclipse . jface . text . templates . TemplateContext ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyContextType extends RubyScriptContextType { public static final String NAME = "" ; public RubyContextType ( ) { super ( NAME ) ; addResolver ( new GlobalTemplateVariables . Cursor ( ) ) ; addResolver ( new GlobalTemplateVariables . WordSelection ( ) ) ; addResolver ( new GlobalTemplateVariables . LineSelection ( ) ) ; addResolver ( new GlobalTemplateVariables . Dollar ( ) ) ; addResolver ( new GlobalTemplateVariables . Date ( ) ) ; addResolver ( new GlobalTemplateVariables . Year ( ) ) ; addResolver ( new GlobalTemplateVariables . Time ( ) ) ; addResolver ( new GlobalTemplateVariables . User ( ) ) ; addResolver ( new File ( ) ) ; addResolver ( new Path ( ) ) ; addResolver ( new Class ( ) ) ; addResolver ( new ClassFullyQualifiedName ( ) ) ; addResolver ( new Method ( ) ) ; addResolver ( new MethodFullyQualifiedName ( ) ) ; } public RubyScriptContext createContext ( IDocument document , int offset , int length , IRubyScript script ) { return new RubyContext ( this , document , offset , length , script ) ; } public static class File extends SimpleTemplateVariableResolver { public File ( ) { super ( "" , "" ) ; } protected String resolve ( TemplateContext context ) { if ( context instanceof RubyScriptContext ) { RubyScriptContext rsContext = ( RubyScriptContext ) context ; IRubyScript script = rsContext . getRubyScript ( ) ; return script . getElementName ( ) ; } return "" ; } } public static class Path extends SimpleTemplateVariableResolver { public Path ( ) { super ( "" , "" ) ; } protected String resolve ( TemplateContext context ) { if ( context instanceof RubyScriptContext ) { RubyScriptContext rsContext = ( RubyScriptContext ) context ; IRubyScript script = rsContext . getRubyScript ( ) ; IPath path = script . getPath ( ) ; if ( path . segmentCount ( ) > && path . segment ( ) . equals ( script . getRubyProject ( ) . getElementName ( ) ) ) { path = path . removeFirstSegments ( ) ; } return path . toPortableString ( ) ; } return "" ; } } public static class Class extends SimpleTemplateVariableResolver { public Class ( ) { super ( "" , "" ) ; } protected String resolve ( TemplateContext context ) { try { if ( context instanceof RubyScriptContext ) { RubyScriptContext rsContext = ( RubyScriptContext ) context ; IRubyScript script = rsContext . getRubyScript ( ) ; IRubyElement element = script . getElementAt ( rsContext . getStart ( ) ) ; if ( element == null ) return "" ; IType type = null ; if ( element . isType ( IRubyElement . TYPE ) ) { type = ( IType ) element ; } else { type = ( IType ) element . getAncestor ( IRubyElement . TYPE ) ; } if ( type != null ) return type . getElementName ( ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return "" ; } } public static class ClassFullyQualifiedName extends SimpleTemplateVariableResolver { public ClassFullyQualifiedName ( ) { super ( "" , "" ) ; } protected String resolve ( TemplateContext context ) { try { if ( context instanceof RubyScriptContext ) { RubyScriptContext rsContext = ( RubyScriptContext ) context ; IRubyScript script = rsContext . getRubyScript ( ) ; IRubyElement element = script . getElementAt ( rsContext . getStart ( ) ) ; if ( element == null ) return "" ; IType type = null ; if ( element . isType ( IRubyElement . TYPE ) ) { type = ( IType ) element ; } else { type = ( IType ) element . getAncestor ( IRubyElement . TYPE ) ; } if ( type != null ) return type . getFullyQualifiedName ( ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return "" ; } } public static class Method extends SimpleTemplateVariableResolver { public Method ( ) { super ( "" , "" ) ; } protected String resolve ( TemplateContext context ) { try { if ( context instanceof RubyScriptContext ) { RubyScriptContext rsContext = ( RubyScriptContext ) context ; IRubyScript script = rsContext . getRubyScript ( ) ; IRubyElement element = script . getElementAt ( rsContext . getStart ( ) ) ; if ( element == null ) return "" ; IMethod method = null ; if ( element . isType ( IRubyElement . METHOD ) ) { method = ( IMethod ) element ; } else { method = ( IMethod ) element . getAncestor ( IRubyElement . METHOD ) ; } if ( method != null ) return method . getElementName ( ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return "" ; } } public static class MethodFullyQualifiedName extends SimpleTemplateVariableResolver { public MethodFullyQualifiedName ( ) { super ( "" , "" ) ; } protected String resolve ( TemplateContext context ) { try { if ( context instanceof RubyScriptContext ) { RubyScriptContext rsContext = ( RubyScriptContext ) context ; IRubyScript script = rsContext . getRubyScript ( ) ; IRubyElement element = script . getElementAt ( rsContext . getStart ( ) ) ; if ( element == null ) return "" ; IMethod method = null ; if ( element . isType ( IRubyElement . METHOD ) ) { method = ( IMethod ) element ; } else { method = ( IMethod ) element . getAncestor ( IRubyElement . METHOD ) ; } if ( method != null ) { IType type = method . getDeclaringType ( ) ; String name = "" ; if ( type != null ) { name += type . getFullyQualifiedName ( ) ; } if ( method . isSingleton ( ) ) { name += "" ; } else { name += "" ; } name += method . getElementName ( ) ; return name ; } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return "" ; } } } package org . rubypeople . rdt . internal . corext . codemanipulation ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; public class StubUtility { public static String getLineDelimiterUsed ( IRubyProject project ) { return getProjectLineDelimiter ( project ) ; } private static String getProjectLineDelimiter ( IRubyProject javaProject ) { IProject project = null ; if ( javaProject != null ) project = javaProject . getProject ( ) ; String lineDelimiter = getLineDelimiterPreference ( project ) ; if ( lineDelimiter != null ) return lineDelimiter ; return System . getProperty ( "" , "" ) ; } public static String getLineDelimiterPreference ( IProject project ) { IScopeContext [ ] scopeContext ; if ( project != null ) { scopeContext = new IScopeContext [ ] { new ProjectScope ( project ) } ; String lineDelimiter = Platform . getPreferencesService ( ) . getString ( Platform . PI_RUNTIME , Platform . PREF_LINE_SEPARATOR , null , scopeContext ) ; if ( lineDelimiter != null ) return lineDelimiter ; } scopeContext = new IScopeContext [ ] { new InstanceScope ( ) } ; String platformDefault = System . getProperty ( "" , "" ) ; return Platform . getPreferencesService ( ) . getString ( Platform . PI_RUNTIME , Platform . PREF_LINE_SEPARATOR , platformDefault , scopeContext ) ; } public static String getLineDelimiterUsed ( IRubyElement elem ) { while ( elem != null && ! ( elem instanceof IOpenable ) ) { elem = elem . getParent ( ) ; } if ( elem != null ) { try { return ( ( IOpenable ) elem ) . findRecommendedLineSeparator ( ) ; } catch ( RubyModelException exception ) { } } return getProjectLineDelimiter ( null ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . changes ; import org . eclipse . osgi . util . NLS ; public class RefactoringCoreMessages extends NLS { private static final String BUNDLE_NAME = RefactoringCoreMessages . class . getName ( ) ; public static String UndoRubyScriptChange_no_resource ; static { NLS . initializeMessages ( BUNDLE_NAME , RefactoringCoreMessages . class ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . changes ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . text . IDocument ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . ContentStamp ; import org . eclipse . ltk . core . refactoring . TextFileChange ; import org . eclipse . text . edits . UndoEdit ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyScriptChange extends TextFileChange { private IRubyScript fCUnit ; public RubyScriptChange ( String name , IRubyScript cunit ) { super ( name , getFile ( cunit ) ) ; Assert . isNotNull ( cunit ) ; fCUnit = cunit ; setTextType ( "" ) ; } private static IFile getFile ( IRubyScript cunit ) { return ( IFile ) cunit . getResource ( ) ; } public Object getModifiedElement ( ) { return fCUnit ; } public IRubyScript getRubyScript ( ) { return fCUnit ; } protected IDocument acquireDocument ( IProgressMonitor pm ) throws CoreException { pm . beginTask ( "" , ) ; fCUnit . becomeWorkingCopy ( null , new SubProgressMonitor ( pm , ) ) ; return super . acquireDocument ( new SubProgressMonitor ( pm , ) ) ; } protected void releaseDocument ( IDocument document , IProgressMonitor pm ) throws CoreException { super . releaseDocument ( document , pm ) ; try { fCUnit . discardWorkingCopy ( ) ; } finally { if ( ! isDocumentAcquired ( ) ) { if ( fCUnit . isWorkingCopy ( ) ) RubyModelUtil . reconcile ( fCUnit ) ; else fCUnit . makeConsistent ( pm ) ; } } } protected Change createUndoChange ( UndoEdit edit , ContentStamp stampToRestore ) { try { return new UndoRubyScriptChange ( getName ( ) , fCUnit , edit , stampToRestore , getSaveMode ( ) ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; return null ; } } public Object getAdapter ( Class adapter ) { if ( IRubyScript . class . equals ( adapter ) ) return fCUnit ; return super . getAdapter ( adapter ) ; } } package org . rubypeople . rdt . internal . corext . refactoring . changes ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . ContentStamp ; import org . eclipse . ltk . core . refactoring . UndoTextFileChange ; import org . eclipse . text . edits . UndoEdit ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; class UndoRubyScriptChange extends UndoTextFileChange { private IRubyScript fCUnit ; public UndoRubyScriptChange ( String name , IRubyScript unit , UndoEdit undo , ContentStamp stampToRestore , int saveMode ) throws CoreException { super ( name , getFile ( unit ) , undo , stampToRestore , saveMode ) ; fCUnit = unit ; } private static IFile getFile ( IRubyScript cunit ) throws CoreException { IFile file = ( IFile ) cunit . getResource ( ) ; if ( file == null ) throw new CoreException ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . ERROR , Messages . format ( RefactoringCoreMessages . UndoRubyScriptChange_no_resource , cunit . getElementName ( ) ) , null ) ) ; return file ; } public Object getModifiedElement ( ) { return fCUnit ; } protected Change createUndoChange ( UndoEdit edit , ContentStamp stampToRestore ) throws CoreException { return new UndoRubyScriptChange ( getName ( ) , fCUnit , edit , stampToRestore , getSaveMode ( ) ) ; } public Change perform ( IProgressMonitor pm ) throws CoreException { pm . beginTask ( "" , ) ; fCUnit . becomeWorkingCopy ( null , new SubProgressMonitor ( pm , ) ) ; try { return super . perform ( new SubProgressMonitor ( pm , ) ) ; } finally { fCUnit . discardWorkingCopy ( ) ; } } } package org . rubypeople . rdt . internal . corext ; import org . eclipse . osgi . util . NLS ; public class CorextMessages extends NLS { private static final String BUNDLE_NAME = CorextMessages . class . getName ( ) ; public static String History_error_serialize ; public static String History_error_read ; public static String TypeInfoHistory_consistency_check ; public static String Resources_fileModified ; public static String Resources_modifiedResources ; public static String Resources_outOfSync ; public static String Resources_outOfSyncResources ; static { NLS . initializeMessages ( BUNDLE_NAME , CorextMessages . class ) ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . viewers . StructuredSelection ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierOperation ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . GenerateBuildPathActionGroup . CreateLinkedSourceFolderAction ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . ILinkToQuery ; public class LinkedSourceFolderOperation extends LoadpathModifierOperation { private ILoadpathModifierListener fListener ; private ILoadpathInformationProvider fCPInformationProvider ; public LinkedSourceFolderOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider ) { super ( listener , informationProvider , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Link_tooltip , ILoadpathInformationProvider . CREATE_LINK ) ; fListener = listener ; fCPInformationProvider = informationProvider ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { CreateLinkedSourceFolderAction action = new CreateLinkedSourceFolderAction ( ) ; action . selectionChanged ( new StructuredSelection ( fCPInformationProvider . getRubyProject ( ) ) ) ; action . run ( ) ; ISourceFolderRoot createdElement = ( ISourceFolderRoot ) action . getCreatedElement ( ) ; if ( createdElement == null ) { return ; } try { IResource correspondingResource = createdElement . getCorrespondingResource ( ) ; List result = new ArrayList ( ) ; result . add ( correspondingResource ) ; if ( fListener != null ) { List entries = action . getCPListElements ( ) ; fListener . classpathEntryChanged ( entries ) ; } fCPInformationProvider . handleResult ( result , null , ILoadpathInformationProvider . CREATE_LINK ) ; } catch ( RubyModelException e ) { if ( monitor == null ) { fCPInformationProvider . handleResult ( Collections . EMPTY_LIST , e , ILoadpathInformationProvider . CREATE_LINK ) ; } else { throw new InvocationTargetException ( e ) ; } } } public boolean isValid ( List elements , int [ ] types ) throws RubyModelException { return types . length == && types [ ] == DialogPackageExplorerActionGroup . RUBY_PROJECT ; } public String getDescription ( int type ) { return NewWizardMessages . PackageExplorerActionGroup_FormText_createLinkedFolder ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . viewers . StructuredSelection ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierOperation ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . GenerateBuildPathActionGroup . CreateLocalSourceFolderAction ; public class CreateFolderOperation extends LoadpathModifierOperation { private final ILoadpathModifierListener fListener ; private final ILoadpathInformationProvider fCPInformationProvider ; public CreateFolderOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider ) { super ( listener , informationProvider , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddLibCP_tooltip , ILoadpathInformationProvider . CREATE_FOLDER ) ; fListener = listener ; fCPInformationProvider = informationProvider ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { CreateLocalSourceFolderAction action = new CreateLocalSourceFolderAction ( ) ; action . selectionChanged ( new StructuredSelection ( fCPInformationProvider . getRubyProject ( ) ) ) ; action . run ( ) ; ISourceFolderRoot createdElement = ( ISourceFolderRoot ) action . getCreatedElement ( ) ; if ( createdElement == null ) { return ; } try { IResource correspondingResource = createdElement . getCorrespondingResource ( ) ; List result = new ArrayList ( ) ; result . add ( correspondingResource ) ; if ( fListener != null ) { List entries = action . getCPListElements ( ) ; fListener . classpathEntryChanged ( entries ) ; } fCPInformationProvider . handleResult ( result , null , ILoadpathInformationProvider . CREATE_FOLDER ) ; } catch ( RubyModelException e ) { if ( monitor == null ) { fCPInformationProvider . handleResult ( Collections . EMPTY_LIST , e , ILoadpathInformationProvider . CREATE_FOLDER ) ; } else { throw new InvocationTargetException ( e ) ; } } } public boolean isValid ( List elements , int [ ] types ) throws RubyModelException { return types . length == && types [ ] == DialogPackageExplorerActionGroup . RUBY_PROJECT ; } public String getDescription ( int type ) { return NewWizardMessages . PackageExplorerActionGroup_FormText_createNewSourceFolder ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import java . lang . reflect . InvocationTargetException ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierOperation ; public class ResetAllOperation extends LoadpathModifierOperation { private ILoadpathEntry [ ] fEntries ; public ResetAllOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider ) { super ( listener , informationProvider , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Reset_tooltip , ILoadpathInformationProvider . RESET_ALL ) ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException { fException = null ; try { fInformationProvider . getRubyProject ( ) . setRawLoadpath ( fEntries , null , monitor ) ; fInformationProvider . deleteCreatedResources ( ) ; fEntries = null ; } catch ( CoreException e ) { fException = e ; } super . handleResult ( null , monitor ) ; } public boolean isValid ( List elements , int [ ] types ) throws RubyModelException { IRubyProject project = fInformationProvider . getRubyProject ( ) ; if ( project == null ) return false ; if ( fEntries == null ) { fEntries = project . getRawLoadpath ( ) ; } ILoadpathEntry [ ] currentEntries = project . getRawLoadpath ( ) ; if ( currentEntries . length != fEntries . length ) return true ; for ( int i = ; i < fEntries . length ; i ++ ) { if ( ! fEntries [ i ] . equals ( currentEntries [ i ] ) ) return true ; } return false ; } public String getDescription ( int type ) { return NewWizardMessages . PackageExplorerActionGroup_FormText_Default_ResetAll ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import java . lang . reflect . InvocationTargetException ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierOperation ; public class ExcludeOperation extends LoadpathModifierOperation { public ExcludeOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider ) { super ( listener , informationProvider , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Exclude_tooltip , ILoadpathInformationProvider . EXCLUDE ) ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException { List result = null ; fException = null ; try { List javaElements = getSelectedElements ( ) ; IRubyProject project = fInformationProvider . getRubyProject ( ) ; result = exclude ( javaElements , project , monitor ) ; } catch ( CoreException e ) { fException = e ; result = null ; } super . handleResult ( result , monitor ) ; } public boolean isValid ( List elements , int [ ] types ) throws RubyModelException { if ( elements . size ( ) == ) return false ; for ( int i = ; i < elements . size ( ) ; i ++ ) { Object element = elements . get ( i ) ; int type = types [ i ] ; if ( ! ( type == DialogPackageExplorerActionGroup . SOURCE_FOLDER || type == DialogPackageExplorerActionGroup . INCLUDED_FOLDER || element instanceof IRubyScript ) ) return false ; } return true ; } public String getDescription ( int type ) { IRubyElement elem = ( IRubyElement ) getSelectedElements ( ) . get ( ) ; String name = escapeSpecialChars ( elem . getElementName ( ) ) ; if ( type == DialogPackageExplorerActionGroup . SOURCE_FOLDER ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_ExcludePackage , name ) ; if ( type == DialogPackageExplorerActionGroup . INCLUDED_FOLDER ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_ExcludePackage , name ) ; if ( type == DialogPackageExplorerActionGroup . RUBY_SCRIPT ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_ExcludeFile , name ) ; if ( type == DialogPackageExplorerActionGroup . INCLUDED_FILE ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_ExcludeFile , name ) ; return NewWizardMessages . PackageExplorerActionGroup_FormText_Default_Exclude ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup ; public interface IPackageExplorerActionListener { public void handlePackageExplorerActionEvent ( PackageExplorerActionEvent event ) ; } package org . rubypeople . rdt . internal . corext . buildpath ; import java . lang . reflect . InvocationTargetException ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierOperation ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . IRemoveLinkedFolderQuery ; public class RemoveFromLoadpathOperation extends LoadpathModifierOperation { public RemoveFromLoadpathOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider ) { super ( listener , informationProvider , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_tooltip , ILoadpathInformationProvider . REMOVE_FROM_BP ) ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException { List result = null ; fException = null ; try { result = removeFromLoadpath ( fInformationProvider . getRemoveLinkedFolderQuery ( ) , getSelectedElements ( ) , fInformationProvider . getRubyProject ( ) , monitor ) ; } catch ( CoreException e ) { fException = e ; result = null ; } super . handleResult ( result , monitor ) ; } public boolean isValid ( List elements , int [ ] types ) throws RubyModelException { if ( elements . size ( ) == ) return false ; IRubyProject project = fInformationProvider . getRubyProject ( ) ; Iterator iterator = elements . iterator ( ) ; while ( iterator . hasNext ( ) ) { Object element = iterator . next ( ) ; if ( ! ( element instanceof ISourceFolderRoot || element instanceof IRubyProject || element instanceof LoadPathContainer ) ) return false ; if ( element instanceof IRubyProject ) { if ( ! isSourceFolder ( project ) ) return false ; } else if ( element instanceof ISourceFolderRoot ) { ILoadpathEntry entry = ( ( ISourceFolderRoot ) element ) . getRawLoadpathEntry ( ) ; if ( entry != null && entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) { return false ; } } } return true ; } public String getDescription ( int type ) { IRubyElement elem = ( IRubyElement ) getSelectedElements ( ) . get ( ) ; String name = escapeSpecialChars ( elem . getElementName ( ) ) ; if ( type == DialogPackageExplorerActionGroup . RUBY_PROJECT ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_ProjectFromBuildpath , name ) ; if ( type == DialogPackageExplorerActionGroup . SOURCE_FOLDER_ROOT || type == DialogPackageExplorerActionGroup . MODIFIED_FRAGMENT_ROOT ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_fromBuildpath , name ) ; return NewWizardMessages . PackageExplorerActionGroup_FormText_Default_FromBuildpath ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import java . net . URI ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . BuildPathBasePage ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . CPListElement ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . IRemoveLinkedFolderQuery ; public class LoadpathModifier { public static interface ILoadpathModifierListener { public void classpathEntryChanged ( List newEntries ) ; } private ILoadpathModifierListener fListener ; public LoadpathModifier ( ) { this ( null ) ; } protected LoadpathModifier ( ILoadpathModifierListener listener ) { fListener = listener ; } public static List removeFilters ( IPath path , IRubyProject project , List existingEntries ) { if ( path == null ) return Collections . EMPTY_LIST ; IPath projPath = project . getPath ( ) ; if ( projPath . isPrefixOf ( path ) ) { path = path . removeFirstSegments ( projPath . segmentCount ( ) ) . addTrailingSeparator ( ) ; } List result = new ArrayList ( ) ; for ( Iterator iter = existingEntries . iterator ( ) ; iter . hasNext ( ) ; ) { CPListElement element = ( CPListElement ) iter . next ( ) ; boolean hasChange = false ; IPath [ ] exlusions = ( IPath [ ] ) element . getAttribute ( CPListElement . EXCLUSION ) ; if ( exlusions != null ) { List exlusionList = new ArrayList ( exlusions . length ) ; for ( int i = ; i < exlusions . length ; i ++ ) { if ( ! exlusions [ i ] . equals ( path ) ) { exlusionList . add ( exlusions [ i ] ) ; } else { hasChange = true ; } } element . setAttribute ( CPListElement . EXCLUSION , exlusionList . toArray ( new IPath [ exlusionList . size ( ) ] ) ) ; } IPath [ ] inclusion = ( IPath [ ] ) element . getAttribute ( CPListElement . INCLUSION ) ; if ( inclusion != null ) { List inclusionList = new ArrayList ( inclusion . length ) ; for ( int i = ; i < inclusion . length ; i ++ ) { if ( ! inclusion [ i ] . equals ( path ) ) { inclusionList . add ( inclusion [ i ] ) ; } else { hasChange = true ; } } element . setAttribute ( CPListElement . INCLUSION , inclusionList . toArray ( new IPath [ inclusionList . size ( ) ] ) ) ; } if ( hasChange ) { result . add ( element ) ; } } return result ; } public static List getExistingEntries ( IRubyProject project ) throws RubyModelException { ILoadpathEntry [ ] classpathEntries = project . getRawLoadpath ( ) ; ArrayList newClassPath = new ArrayList ( ) ; for ( int i = ; i < classpathEntries . length ; i ++ ) { ILoadpathEntry curr = classpathEntries [ i ] ; newClassPath . add ( CPListElement . createFromExisting ( curr , project ) ) ; } return newClassPath ; } public static CPListElement getLoadpathEntry ( List elements , ISourceFolderRoot root ) throws RubyModelException { ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { CPListElement element = ( CPListElement ) elements . get ( i ) ; if ( element . getPath ( ) . equals ( root . getPath ( ) ) && element . getEntryKind ( ) == entry . getEntryKind ( ) ) return ( CPListElement ) elements . get ( i ) ; } CPListElement newElement = CPListElement . createFromExisting ( entry , root . getRubyProject ( ) ) ; elements . add ( newElement ) ; return newElement ; } public static ILoadpathEntry getLoadpathEntryFor ( IPath path , IRubyProject project , int entryKind ) throws RubyModelException { ILoadpathEntry [ ] entries = project . getRawLoadpath ( ) ; for ( int i = ; i < entries . length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry . getPath ( ) . equals ( path ) && equalEntryKind ( entry , entryKind ) ) return entry ; } return null ; } private static boolean equalEntryKind ( ILoadpathEntry entry , int kind ) { return entry . getEntryKind ( ) == kind ; } public static boolean filtersSet ( ISourceFolderRoot root ) throws RubyModelException { if ( root == null ) return false ; ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; IPath [ ] inclusions = entry . getInclusionPatterns ( ) ; IPath [ ] exclusions = entry . getExclusionPatterns ( ) ; if ( inclusions != null && inclusions . length > ) return true ; if ( exclusions != null && exclusions . length > ) return true ; return false ; } public static boolean isExcluded ( IResource resource , IRubyProject project ) throws RubyModelException { ISourceFolderRoot root = getFolderRoot ( resource , project , null ) ; if ( root == null ) return false ; String fragmentName = getName ( resource . getFullPath ( ) , root . getPath ( ) ) ; fragmentName = completeName ( fragmentName ) ; ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; return entry != null && contains ( new Path ( fragmentName ) , entry . getExclusionPatterns ( ) , null ) ; } private static boolean contains ( IPath path , IPath [ ] paths , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; if ( path == null ) return false ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_ComparePaths , paths . length ) ; if ( path . getFileExtension ( ) == null ) path = new Path ( completeName ( path . toString ( ) ) ) ; for ( int i = ; i < paths . length ; i ++ ) { if ( paths [ i ] . equals ( path ) ) return true ; monitor . worked ( ) ; } } finally { monitor . done ( ) ; } return false ; } private static String completeName ( String name ) { if ( ! RubyCore . isRubyLikeFileName ( name ) ) { name = name + "" ; name = name . replace ( '' , '' ) ; return name ; } return name ; } private static String getName ( IPath path , IPath rootPath ) { return path . removeFirstSegments ( rootPath . segmentCount ( ) ) . toString ( ) ; } public static ISourceFolderRoot getFolderRoot ( IResource resource , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; IRubyElement javaElem = null ; if ( resource . getFullPath ( ) . equals ( project . getPath ( ) ) ) return project . getSourceFolderRoot ( resource ) ; IContainer container = resource . getParent ( ) ; do { if ( container instanceof IFolder ) javaElem = RubyCore . create ( ( IFolder ) container ) ; if ( container . getFullPath ( ) . equals ( project . getPath ( ) ) ) { javaElem = project ; break ; } container = container . getParent ( ) ; if ( container == null ) return null ; } while ( javaElem == null || ! ( javaElem instanceof ISourceFolderRoot ) ) ; if ( javaElem instanceof IRubyProject ) javaElem = project . getSourceFolderRoot ( project . getResource ( ) ) ; return ( ISourceFolderRoot ) javaElem ; } protected static String escapeSpecialChars ( String value ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < value . length ( ) ; i ++ ) { char c = value . charAt ( i ) ; switch ( c ) { case '' : buf . append ( "" ) ; break ; case '' : buf . append ( "" ) ; break ; case '>' : buf . append ( "" ) ; break ; case '' : buf . append ( "" ) ; break ; case '' : buf . append ( "" ) ; break ; case : buf . append ( "" ) ; break ; default : buf . append ( c ) ; break ; } } return buf . toString ( ) ; } public static boolean isSourceFolder ( IRubyProject project ) throws RubyModelException { return LoadpathModifier . getLoadpathEntryFor ( project . getPath ( ) , project , ILoadpathEntry . CPE_SOURCE ) != null ; } protected List addToLoadpath ( List elements , IRubyProject project , IProgressMonitor monitor ) throws OperationCanceledException , CoreException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . LoadpathModifier_Monitor_AddToBuildpath , * elements . size ( ) + ) ; IWorkspaceRoot workspaceRoot = RubyPlugin . getWorkspace ( ) . getRoot ( ) ; if ( project . getProject ( ) . hasNature ( RubyCore . NATURE_ID ) ) { IPath projPath = project . getProject ( ) . getFullPath ( ) ; List existingEntries = getExistingEntries ( project ) ; List newEntries = new ArrayList ( ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { Object element = elements . get ( i ) ; CPListElement entry ; if ( element instanceof IResource ) entry = addToLoadpath ( ( IResource ) element , existingEntries , newEntries , project , monitor ) ; else entry = addToLoadpath ( ( IRubyElement ) element , existingEntries , newEntries , project , monitor ) ; newEntries . add ( entry ) ; } Set modifiedSourceEntries = new HashSet ( ) ; BuildPathBasePage . fixNestingConflicts ( ( CPListElement [ ] ) newEntries . toArray ( new CPListElement [ newEntries . size ( ) ] ) , ( CPListElement [ ] ) existingEntries . toArray ( new CPListElement [ existingEntries . size ( ) ] ) , modifiedSourceEntries ) ; setNewEntry ( existingEntries , newEntries , project , new SubProgressMonitor ( monitor , ) ) ; updateLoadpath ( existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; List result = new ArrayList ( ) ; for ( int i = ; i < newEntries . size ( ) ; i ++ ) { ILoadpathEntry entry = ( ( CPListElement ) newEntries . get ( i ) ) . getLoadpathEntry ( ) ; IRubyElement root ; if ( entry . getPath ( ) . equals ( project . getPath ( ) ) ) root = project ; else root = project . findSourceFolderRoot ( entry . getPath ( ) ) ; if ( root != null ) { result . add ( root ) ; } } return result ; } else { StatusInfo rootStatus = new StatusInfo ( ) ; rootStatus . setError ( NewWizardMessages . LoadpathModifier_Error_NoNatures ) ; throw new CoreException ( rootStatus ) ; } } finally { monitor . done ( ) ; } } private void updateLoadpath ( List newEntries , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { ILoadpathEntry [ ] entries = convert ( newEntries ) ; IRubyModelStatus status = RubyConventions . validateLoadpath ( project , entries , null ) ; if ( ! status . isOK ( ) ) throw new RubyModelException ( status ) ; project . setRawLoadpath ( entries , null , new SubProgressMonitor ( monitor , ) ) ; fireEvent ( newEntries ) ; } finally { monitor . done ( ) ; } } private static ILoadpathEntry [ ] convert ( List list ) { ILoadpathEntry [ ] entries = new ILoadpathEntry [ list . size ( ) ] ; for ( int i = ; i < list . size ( ) ; i ++ ) { CPListElement element = ( CPListElement ) list . get ( i ) ; entries [ i ] = element . getLoadpathEntry ( ) ; } return entries ; } private void fireEvent ( List newEntries ) { if ( fListener != null ) fListener . classpathEntryChanged ( newEntries ) ; } public static CPListElement addToLoadpath ( IResource resource , List existingEntries , List newEntries , IRubyProject project , IProgressMonitor monitor ) throws OperationCanceledException , CoreException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_AddToBuildpath , ) ; exclude ( resource . getFullPath ( ) , existingEntries , newEntries , project , new SubProgressMonitor ( monitor , ) ) ; CPListElement entry = new CPListElement ( project , ILoadpathEntry . CPE_SOURCE , resource . getFullPath ( ) , resource ) ; return entry ; } finally { monitor . done ( ) ; } } public static void exclude ( IPath path , List existingEntries , List newEntries , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_Excluding , ) ; CPListElement elem = null ; CPListElement existingElem = null ; int i = ; do { i ++ ; IPath rootPath = path . removeLastSegments ( i ) ; if ( rootPath . segmentCount ( ) == ) return ; elem = getListElement ( rootPath , newEntries ) ; existingElem = getListElement ( rootPath , existingEntries ) ; } while ( existingElem == null && elem == null ) ; if ( elem == null ) { elem = existingElem ; } exclude ( path . removeFirstSegments ( path . segmentCount ( ) - i ) . toString ( ) , null , elem , project , new SubProgressMonitor ( monitor , ) ) ; } finally { monitor . done ( ) ; } } private static CPListElement getListElement ( IPath path , List elements ) { for ( int i = ; i < elements . size ( ) ; i ++ ) { CPListElement element = ( CPListElement ) elements . get ( i ) ; if ( element . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE && element . getPath ( ) . equals ( path ) ) { return element ; } } return null ; } private static IPath [ ] remove ( IPath path , IPath [ ] paths , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_RemovePath , paths . length + ) ; if ( ! contains ( path , paths , new SubProgressMonitor ( monitor , ) ) ) return paths ; ArrayList newPaths = new ArrayList ( ) ; for ( int i = ; i < paths . length ; i ++ ) { monitor . worked ( ) ; if ( ! paths [ i ] . equals ( path ) ) newPaths . add ( paths [ i ] ) ; } return ( IPath [ ] ) newPaths . toArray ( new IPath [ newPaths . size ( ) ] ) ; } finally { monitor . done ( ) ; } } private static IResource exclude ( String name , IPath fullPath , CPListElement entry , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; IResource result ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_Excluding , ) ; IPath [ ] excludedPath = ( IPath [ ] ) entry . getAttribute ( CPListElement . EXCLUSION ) ; IPath [ ] newExcludedPath = new IPath [ excludedPath . length + ] ; name = completeName ( name ) ; IPath path = new Path ( name ) ; if ( ! contains ( path , excludedPath , new SubProgressMonitor ( monitor , ) ) ) { System . arraycopy ( excludedPath , , newExcludedPath , , excludedPath . length ) ; newExcludedPath [ excludedPath . length ] = path ; entry . setAttribute ( CPListElement . EXCLUSION , newExcludedPath ) ; entry . setAttribute ( CPListElement . INCLUSION , remove ( path , ( IPath [ ] ) entry . getAttribute ( CPListElement . INCLUSION ) , new SubProgressMonitor ( monitor , ) ) ) ; } result = fullPath == null ? null : getResource ( fullPath , project ) ; } finally { monitor . done ( ) ; } return result ; } private static IResource getResource ( IPath path , IRubyProject project ) { return project . getProject ( ) . getWorkspace ( ) . getRoot ( ) . findMember ( path ) ; } public static CPListElement addToLoadpath ( IRubyElement javaElement , List existingEntries , List newEntries , IRubyProject project , IProgressMonitor monitor ) throws OperationCanceledException , CoreException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_AddToBuildpath , ) ; CPListElement entry = new CPListElement ( project , ILoadpathEntry . CPE_SOURCE , javaElement . getPath ( ) , javaElement . getResource ( ) ) ; return entry ; } finally { monitor . done ( ) ; } } public static void setNewEntry ( List existingEntries , List newEntries , IRubyProject project , IProgressMonitor monitor ) throws CoreException { try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_SetNewEntry , existingEntries . size ( ) ) ; for ( int i = ; i < newEntries . size ( ) ; i ++ ) { CPListElement entry = ( CPListElement ) newEntries . get ( i ) ; validateAndAddEntry ( entry , existingEntries , project ) ; monitor . worked ( ) ; } } finally { monitor . done ( ) ; } } private static void validateAndAddEntry ( CPListElement entry , List existingEntries , IRubyProject project ) throws CoreException { IPath path = entry . getPath ( ) ; IPath projPath = project . getProject ( ) . getFullPath ( ) ; IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IStatus validate = workspaceRoot . getWorkspace ( ) . validatePath ( path . toString ( ) , IResource . FOLDER ) ; StatusInfo rootStatus = new StatusInfo ( ) ; rootStatus . setOK ( ) ; boolean isExternal = isExternalArchiveOrLibrary ( entry , project ) ; if ( ! isExternal && validate . matches ( IStatus . ERROR ) && ! project . getPath ( ) . equals ( path ) ) { rootStatus . setError ( Messages . format ( NewWizardMessages . NewSourceFolderWizardPage_error_InvalidRootName , validate . getMessage ( ) ) ) ; throw new CoreException ( rootStatus ) ; } else { if ( ! isExternal && ! project . getPath ( ) . equals ( path ) ) { IResource res = workspaceRoot . findMember ( path ) ; if ( res != null ) { if ( res . getType ( ) != IResource . FOLDER && res . getType ( ) != IResource . FILE ) { rootStatus . setError ( NewWizardMessages . NewSourceFolderWizardPage_error_NotAFolder ) ; throw new CoreException ( rootStatus ) ; } } else { URI projLocation = project . getProject ( ) . getLocationURI ( ) ; if ( projLocation != null ) { IFileStore store = EFS . getStore ( projLocation ) . getChild ( path ) ; if ( store . fetchInfo ( ) . exists ( ) ) { rootStatus . setError ( NewWizardMessages . NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase ) ; throw new CoreException ( rootStatus ) ; } } } } for ( int i = ; i < existingEntries . size ( ) ; i ++ ) { CPListElement curr = ( CPListElement ) existingEntries . get ( i ) ; if ( curr . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { if ( path . equals ( curr . getPath ( ) ) && ! project . getPath ( ) . equals ( path ) ) { rootStatus . setError ( NewWizardMessages . NewSourceFolderWizardPage_error_AlreadyExisting ) ; throw new CoreException ( rootStatus ) ; } } } if ( ! isExternal && ! entry . getPath ( ) . equals ( project . getPath ( ) ) ) exclude ( entry . getPath ( ) , existingEntries , new ArrayList ( ) , project , null ) ; insertAtEndOfCategory ( entry , existingEntries ) ; ILoadpathEntry [ ] entries = convert ( existingEntries ) ; IRubyModelStatus status = RubyConventions . validateLoadpath ( project , entries , null ) ; if ( ! status . isOK ( ) ) { rootStatus . setError ( status . getMessage ( ) ) ; throw new CoreException ( rootStatus ) ; } if ( isSourceFolder ( project ) || project . getPath ( ) . equals ( path ) ) { rootStatus . setWarning ( NewWizardMessages . NewSourceFolderWizardPage_warning_ReplaceSF ) ; return ; } rootStatus . setOK ( ) ; return ; } } private static boolean isExternalArchiveOrLibrary ( CPListElement entry , IRubyProject project ) { if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY || entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) { if ( entry . getResource ( ) instanceof IFolder ) { return false ; } return true ; } return false ; } private static void insertAtEndOfCategory ( CPListElement entry , List existingEntries ) { int length = existingEntries . size ( ) ; CPListElement [ ] elements = ( CPListElement [ ] ) existingEntries . toArray ( new CPListElement [ length ] ) ; int i = ; while ( i < length && elements [ i ] . getLoadpathEntry ( ) . getEntryKind ( ) != entry . getLoadpathEntry ( ) . getEntryKind ( ) ) { i ++ ; } if ( i < length ) { i ++ ; while ( i < length && elements [ i ] . getLoadpathEntry ( ) . getEntryKind ( ) == entry . getLoadpathEntry ( ) . getEntryKind ( ) ) { i ++ ; } existingEntries . add ( i , entry ) ; return ; } switch ( entry . getLoadpathEntry ( ) . getEntryKind ( ) ) { case ILoadpathEntry . CPE_SOURCE : existingEntries . add ( , entry ) ; break ; case ILoadpathEntry . CPE_CONTAINER : case ILoadpathEntry . CPE_LIBRARY : case ILoadpathEntry . CPE_PROJECT : case ILoadpathEntry . CPE_VARIABLE : default : existingEntries . add ( entry ) ; break ; } } protected List removeFromLoadpath ( IRemoveLinkedFolderQuery query , List elements , IRubyProject project , IProgressMonitor monitor ) throws CoreException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_RemoveFromBuildpath , elements . size ( ) + ) ; List existingEntries = getExistingEntries ( project ) ; List resultElements = new ArrayList ( ) ; boolean archiveRemoved = false ; for ( int i = ; i < elements . size ( ) ; i ++ ) { Object element = elements . get ( i ) ; Object res = null ; if ( element instanceof IRubyProject ) { res = removeFromLoadpath ( project , existingEntries , new SubProgressMonitor ( monitor , ) ) ; } else { if ( element instanceof ISourceFolderRoot ) { ISourceFolderRoot root = ( ISourceFolderRoot ) element ; final IResource resource = root . getCorrespondingResource ( ) ; if ( resource instanceof IFolder ) { final IFolder folder = ( IFolder ) resource ; if ( folder . isLinked ( ) ) { final int result = query . doQuery ( folder ) ; if ( result != IRemoveLinkedFolderQuery . REMOVE_CANCEL ) { if ( result == IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH ) { res = removeFromLoadpath ( root , existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; } else if ( result == IRemoveLinkedFolderQuery . REMOVE_BUILD_PATH_AND_FOLDER ) { res = removeFromLoadpath ( root , existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; folder . delete ( true , true , new SubProgressMonitor ( monitor , ) ) ; } } } else { res = removeFromLoadpath ( root , existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; } } else { res = removeFromLoadpath ( root , existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; } } else { archiveRemoved = true ; LoadPathContainer container = ( LoadPathContainer ) element ; existingEntries . remove ( CPListElement . createFromExisting ( container . getLoadpathEntry ( ) , project ) ) ; } } if ( res != null ) { resultElements . add ( res ) ; } } updateLoadpath ( existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; fireEvent ( existingEntries ) ; if ( archiveRemoved && resultElements . size ( ) == ) resultElements . add ( project ) ; return resultElements ; } finally { monitor . done ( ) ; } } public static IRubyProject removeFromLoadpath ( IRubyProject project , List existingEntries , IProgressMonitor monitor ) throws CoreException { CPListElement elem = getListElement ( project . getPath ( ) , existingEntries ) ; if ( elem != null ) { existingEntries . remove ( elem ) ; } return project ; } public static IResource removeFromLoadpath ( ISourceFolderRoot root , List existingEntries , IRubyProject project , IProgressMonitor monitor ) throws CoreException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_RemoveFromBuildpath , ) ; ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; CPListElement elem = CPListElement . createFromExisting ( entry , project ) ; existingEntries . remove ( elem ) ; removeFilters ( elem . getPath ( ) , project , existingEntries ) ; return elem . getResource ( ) ; } finally { monitor . done ( ) ; } } protected List exclude ( List javaElements , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_Excluding , javaElements . size ( ) + ) ; List existingEntries = getExistingEntries ( project ) ; List resources = new ArrayList ( ) ; for ( int i = ; i < javaElements . size ( ) ; i ++ ) { IRubyElement javaElement = ( IRubyElement ) javaElements . get ( i ) ; ISourceFolderRoot root = ( ISourceFolderRoot ) javaElement . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; CPListElement entry = getLoadpathEntry ( existingEntries , root ) ; IResource resource = exclude ( javaElement , entry , project , new SubProgressMonitor ( monitor , ) ) ; if ( resource != null ) { resources . add ( resource ) ; } } updateLoadpath ( existingEntries , project , new SubProgressMonitor ( monitor , ) ) ; return resources ; } finally { monitor . done ( ) ; } } public static IResource exclude ( IRubyElement javaElement , CPListElement entry , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { String name = getName ( javaElement . getPath ( ) , entry . getPath ( ) ) ; return exclude ( name , javaElement . getPath ( ) , entry , project , new SubProgressMonitor ( monitor , ) ) ; } finally { monitor . done ( ) ; } } protected List unExclude ( List elements , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_Including , * elements . size ( ) ) ; List entries = getExistingEntries ( project ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { IResource resource = ( IResource ) elements . get ( i ) ; ISourceFolderRoot root = getFolderRoot ( resource , project , new SubProgressMonitor ( monitor , ) ) ; if ( root != null ) { CPListElement entry = getLoadpathEntry ( entries , root ) ; unExclude ( resource , entry , project , new SubProgressMonitor ( monitor , ) ) ; } } updateLoadpath ( entries , project , new SubProgressMonitor ( monitor , ) ) ; List resultElements = getCorrespondingElements ( elements , project ) ; return resultElements ; } finally { monitor . done ( ) ; } } public static void unExclude ( IResource resource , CPListElement entry , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_RemoveExclusion , ) ; String name = getName ( resource . getFullPath ( ) , entry . getPath ( ) ) ; IPath [ ] excludedPath = ( IPath [ ] ) entry . getAttribute ( CPListElement . EXCLUSION ) ; IPath [ ] newExcludedPath = remove ( new Path ( completeName ( name ) ) , excludedPath , new SubProgressMonitor ( monitor , ) ) ; entry . setAttribute ( CPListElement . EXCLUSION , newExcludedPath ) ; } finally { monitor . done ( ) ; } } public static List getCorrespondingElements ( List entries , IRubyProject project ) { List result = new ArrayList ( ) ; for ( int i = ; i < entries . size ( ) ; i ++ ) { Object element = entries . get ( i ) ; IPath path ; if ( element instanceof IResource ) path = ( ( IResource ) element ) . getFullPath ( ) ; else path = ( ( IRubyElement ) element ) . getPath ( ) ; IResource resource = getResource ( path , project ) ; if ( resource != null ) { IRubyElement elem = RubyCore . create ( resource ) ; if ( elem != null && project . isOnLoadpath ( elem ) ) result . add ( elem ) ; else result . add ( resource ) ; } } return result ; } public static void commitLoadPath ( List newEntries , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { ILoadpathEntry [ ] entries = convert ( newEntries ) ; IRubyModelStatus status = RubyConventions . validateLoadpath ( project , entries , null ) ; if ( ! status . isOK ( ) ) throw new RubyModelException ( status ) ; project . setRawLoadpath ( entries , null , new SubProgressMonitor ( monitor , ) ) ; } finally { monitor . done ( ) ; } } public static ISourceFolder getFolder ( IResource resource ) { IRubyElement elem = RubyCore . create ( resource ) ; if ( elem instanceof ISourceFolder ) return ( ISourceFolder ) elem ; return null ; } public static boolean parentExcluded ( IResource resource , IRubyProject project ) throws RubyModelException { if ( resource . getFullPath ( ) . equals ( project . getPath ( ) ) ) return false ; ISourceFolderRoot root = getFolderRoot ( resource , project , null ) ; if ( root == null ) { return true ; } IPath path = resource . getFullPath ( ) . removeFirstSegments ( root . getPath ( ) . segmentCount ( ) ) ; ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; if ( entry == null ) return true ; while ( path . segmentCount ( ) > ) { if ( contains ( path , entry . getExclusionPatterns ( ) , null ) ) return true ; path = path . removeLastSegments ( ) ; } return false ; } public static boolean isIncluded ( IRubyElement selection , IRubyProject project , IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; try { monitor . beginTask ( NewWizardMessages . ClasspathModifier_Monitor_ContainsPath , ) ; ISourceFolderRoot root = ( ISourceFolderRoot ) selection . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; ILoadpathEntry entry = root . getRawLoadpathEntry ( ) ; if ( entry == null ) return false ; return contains ( selection . getPath ( ) . removeFirstSegments ( root . getPath ( ) . segmentCount ( ) ) , entry . getInclusionPatterns ( ) , new SubProgressMonitor ( monitor , ) ) ; } finally { monitor . done ( ) ; } } public static boolean isDefaultFolder ( ISourceFolder fragment ) { return fragment . getElementName ( ) . length ( ) == ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import java . lang . reflect . InvocationTargetException ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierOperation ; public class AddSelectedSourceFolderOperation extends LoadpathModifierOperation { public AddSelectedSourceFolderOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider ) { super ( listener , informationProvider , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_tooltip , ILoadpathInformationProvider . ADD_SEL_SF_TO_BP ) ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException { List result = null ; fException = null ; try { List elements = getSelectedElements ( ) ; IRubyProject project = fInformationProvider . getRubyProject ( ) ; result = addToLoadpath ( elements , project , monitor ) ; } catch ( CoreException e ) { fException = e ; result = null ; } super . handleResult ( result , monitor ) ; } public boolean isValid ( List elements , int [ ] types ) throws RubyModelException { if ( elements . size ( ) == ) return false ; for ( int i = ; i < elements . size ( ) ; i ++ ) { Object object = elements . get ( i ) ; switch ( types [ i ] ) { case DialogPackageExplorerActionGroup . RUBY_PROJECT : if ( isSourceFolder ( ( IRubyProject ) object ) ) return false ; break ; case DialogPackageExplorerActionGroup . SOURCE_FOLDER : break ; case DialogPackageExplorerActionGroup . INCLUDED_FOLDER : break ; case DialogPackageExplorerActionGroup . FOLDER : break ; case DialogPackageExplorerActionGroup . EXCLUDED_FOLDER : break ; default : return false ; } } return true ; } public String getDescription ( int type ) { Object obj = getSelectedElements ( ) . get ( ) ; if ( obj instanceof IRubyElement ) { String name = escapeSpecialChars ( ( ( IRubyElement ) obj ) . getElementName ( ) ) ; if ( type == DialogPackageExplorerActionGroup . RUBY_PROJECT ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_ProjectToBuildpath , name ) ; if ( type == DialogPackageExplorerActionGroup . SOURCE_FOLDER ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_PackageToBuildpath , name ) ; if ( type == DialogPackageExplorerActionGroup . MODIFIED_FRAGMENT_ROOT ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_PackageToBuildpath , name ) ; } else if ( obj instanceof IResource ) { String name = escapeSpecialChars ( ( ( IResource ) obj ) . getName ( ) ) ; if ( type == DialogPackageExplorerActionGroup . FOLDER ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_FolderToBuildpath , name ) ; if ( type == DialogPackageExplorerActionGroup . EXCLUDED_FOLDER ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_FolderToBuildpath , name ) ; } return NewWizardMessages . PackageExplorerActionGroup_FormText_Default_toBuildpath ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierAction ; public class PackageExplorerActionEvent { private String [ ] fEnabledActionsDescriptions ; private LoadpathModifierAction [ ] fEnabledActions ; public PackageExplorerActionEvent ( String [ ] enabledActionsDescriptions , LoadpathModifierAction [ ] enabledActions ) { fEnabledActionsDescriptions = enabledActionsDescriptions ; fEnabledActions = enabledActions ; } public LoadpathModifierAction [ ] getEnabledActions ( ) { return fEnabledActions ; } public String [ ] getEnabledActionsText ( ) { return fEnabledActionsDescriptions ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . IRemoveLinkedFolderQuery ; public interface ILoadpathInformationProvider { public static final int ADD_SEL_SF_TO_BP = ; public static final int REMOVE_FROM_BP = ; public static final int EXCLUDE = ; public static final int UNEXCLUDE = ; public static final int EDIT_FILTERS = ; public static final int CREATE_LINK = ; public static final int RESET_ALL = ; public static final int CREATE_OUTPUT = ; public static final int RESET = ; public static final int INCLUDE = ; public static final int UNINCLUDE = ; public static final int CREATE_FOLDER = ; public static final int ADD_JAR_TO_BP = ; public static final int ADD_LIB_TO_BP = ; public static final int ADD_SEL_LIB_TO_BP = ; public void handleResult ( List resultElements , CoreException exception , int operationType ) ; public IStructuredSelection getSelection ( ) ; public IRubyProject getRubyProject ( ) ; public void deleteCreatedResources ( ) ; public IRemoveLinkedFolderQuery getRemoveLinkedFolderQuery ( ) throws RubyModelException ; } package org . rubypeople . rdt . internal . corext . buildpath ; import java . lang . reflect . InvocationTargetException ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierOperation ; public class UnexcludeOperation extends LoadpathModifierOperation { public UnexcludeOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider ) { super ( listener , informationProvider , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Unexclude_tooltip , ILoadpathInformationProvider . UNEXCLUDE ) ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException { List result = null ; fException = null ; try { List resources = getSelectedElements ( ) ; IRubyProject project = fInformationProvider . getRubyProject ( ) ; result = unExclude ( resources , project , monitor ) ; } catch ( CoreException e ) { fException = e ; result = null ; } super . handleResult ( result , monitor ) ; } public boolean isValid ( List elements , int [ ] types ) throws RubyModelException { if ( elements . size ( ) == ) return false ; IRubyProject project = fInformationProvider . getRubyProject ( ) ; for ( int i = ; i < elements . size ( ) ; i ++ ) { Object element = elements . get ( i ) ; switch ( types [ i ] ) { case DialogPackageExplorerActionGroup . FOLDER : if ( ! isValidFolder ( ( IResource ) element , project ) ) return false ; break ; case DialogPackageExplorerActionGroup . EXCLUDED_FOLDER : if ( ! isValidExcludedFolder ( ( IResource ) element , project ) ) return false ; break ; case DialogPackageExplorerActionGroup . EXCLUDED_FILE : if ( ! isValidExcludedFile ( ( IFile ) element , project ) ) return false ; break ; default : return false ; } } return true ; } private boolean isValidFolder ( IResource resource , IRubyProject project ) throws RubyModelException { return LoadpathModifier . isExcluded ( resource , project ) ; } private boolean isValidExcludedFolder ( IResource resource , IRubyProject project ) throws RubyModelException { return LoadpathModifier . isExcluded ( resource , project ) ; } private boolean isValidExcludedFile ( IFile file , IRubyProject project ) throws RubyModelException { return LoadpathModifier . isExcluded ( file , project ) ; } public String getDescription ( int type ) { IResource resource = ( IResource ) getSelectedElements ( ) . get ( ) ; String name = escapeSpecialChars ( resource . getName ( ) ) ; if ( type == DialogPackageExplorerActionGroup . FOLDER ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_UnexcludeFolder , name ) ; if ( type == DialogPackageExplorerActionGroup . EXCLUDED_FILE ) return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_UnexcludeFile , name ) ; return Messages . format ( NewWizardMessages . PackageExplorerActionGroup_FormText_Default_Unexclude , name ) ; } } package org . rubypeople . rdt . internal . corext . buildpath ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . DialogPackageExplorerActionGroup ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierOperation ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . GenerateBuildPathActionGroup . EditFilterAction ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . newsourcepage . LoadpathModifierQueries . IInclusionExclusionQuery ; public class EditFiltersOperation extends LoadpathModifierOperation { private final ILoadpathInformationProvider fCPInformationProvider ; private final ILoadpathModifierListener fListener ; public EditFiltersOperation ( ILoadpathModifierListener listener , ILoadpathInformationProvider informationProvider ) { super ( listener , informationProvider , NewWizardMessages . NewSourceContainerWorkbookPage_ToolBar_Edit_tooltip , ILoadpathInformationProvider . EDIT_FILTERS ) ; fListener = listener ; fCPInformationProvider = informationProvider ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException { EditFilterAction action = new EditFilterAction ( ) ; IStructuredSelection selection = fCPInformationProvider . getSelection ( ) ; Object firstElement = selection . getFirstElement ( ) ; action . selectionChanged ( selection ) ; action . run ( ) ; List l = new ArrayList ( ) ; l . add ( firstElement ) ; if ( fListener != null ) { List entries = action . getCPListElements ( ) ; fListener . classpathEntryChanged ( entries ) ; } fCPInformationProvider . handleResult ( l , null , ILoadpathInformationProvider . EDIT_FILTERS ) ; } public boolean isValid ( List elements , int [ ] types ) throws RubyModelException { if ( elements . size ( ) != ) return false ; IRubyProject project = fInformationProvider . getRubyProject ( ) ; Object element = elements . get ( ) ; if ( element instanceof IRubyProject ) { if ( isSourceFolder ( project ) ) return true ; } else if ( element instanceof ISourceFolderRoot ) { return true ; } return false ; } public String getDescription ( int type ) { if ( type == DialogPackageExplorerActionGroup . RUBY_PROJECT ) return NewWizardMessages . PackageExplorerActionGroup_FormText_Edit ; if ( type == DialogPackageExplorerActionGroup . SOURCE_FOLDER_ROOT ) return NewWizardMessages . PackageExplorerActionGroup_FormText_Edit ; if ( type == DialogPackageExplorerActionGroup . MODIFIED_FRAGMENT_ROOT ) return NewWizardMessages . PackageExplorerActionGroup_FormText_Edit ; return NewWizardMessages . PackageExplorerActionGroup_FormText_Default_Edit ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . Map ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . VCallNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; class CalleeAnalyzerVisitor extends InOrderVisitor { private IMethod fMethod ; private CallSearchResultCollector fSearchResults ; private IProgressMonitor fProgressMonitor ; private int fMethodStartPosition ; private int fMethodEndPosition ; public CalleeAnalyzerVisitor ( IMethod method , IProgressMonitor progressMonitor ) { fSearchResults = new CallSearchResultCollector ( ) ; this . fMethod = method ; this . fProgressMonitor = progressMonitor ; try { ISourceRange sourceRange = method . getSourceRange ( ) ; this . fMethodStartPosition = sourceRange . getOffset ( ) ; this . fMethodEndPosition = fMethodStartPosition + sourceRange . getLength ( ) ; } catch ( RubyModelException jme ) { RubyPlugin . log ( jme ) ; } } private void addMethodCall ( ISourcePosition pos ) { int offset = pos . getStartOffset ( ) ; int endOffset = pos . getEndOffset ( ) ; int length = endOffset - offset ; try { IRubyElement [ ] elements = fMethod . getRubyScript ( ) . codeSelect ( offset , length ) ; if ( elements == null ) return ; for ( int i = ; i < elements . length ; i ++ ) { if ( elements [ i ] instanceof IMember ) { IMember member = ( IMember ) elements [ i ] ; fSearchResults . addMember ( fMethod , member , offset , endOffset , pos . getStartLine ( ) ) ; } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } public Map < String , MethodCall > getCallees ( ) { return fSearchResults . getCallers ( ) ; } @ Override public Object visitVCallNode ( VCallNode iVisited ) { if ( isNodeWithinMethod ( iVisited ) ) { addMethodCall ( iVisited . getPosition ( ) ) ; } return super . visitVCallNode ( iVisited ) ; } @ Override public Object visitFCallNode ( FCallNode iVisited ) { if ( isNodeWithinMethod ( iVisited ) ) { addMethodCall ( iVisited . getPosition ( ) ) ; } return super . visitFCallNode ( iVisited ) ; } @ Override public Object visitCallNode ( CallNode iVisited ) { if ( isNodeWithinMethod ( iVisited ) ) { if ( iVisited . getName ( ) . equals ( "" ) ) return super . visitCallNode ( iVisited ) ; String receiver = ASTUtil . stringRepresentation ( iVisited . getReceiverNode ( ) ) ; ISourcePosition original = iVisited . getPosition ( ) ; int start = original . getStartOffset ( ) + receiver . length ( ) + ; ISourcePosition pos = new IDESourcePosition ( original . getFile ( ) , original . getStartLine ( ) , original . getEndLine ( ) , start , original . getEndOffset ( ) ) ; addMethodCall ( pos ) ; } return super . visitCallNode ( iVisited ) ; } private boolean isNodeWithinMethod ( Node node ) { int nodeStartPosition = node . getPosition ( ) . getStartOffset ( ) ; int nodeEndPosition = node . getPosition ( ) . getEndOffset ( ) ; if ( nodeStartPosition < fMethodStartPosition ) { return false ; } if ( nodeEndPosition > fMethodEndPosition ) { return false ; } return true ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { progressMonitorWorked ( ) ; return super . visitDefnNode ( iVisited ) ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { progressMonitorWorked ( ) ; return super . visitDefsNode ( iVisited ) ; } @ Override public Object visitClassNode ( ClassNode iVisited ) { progressMonitorWorked ( ) ; return super . visitClassNode ( iVisited ) ; } @ Override public Object visitModuleNode ( ModuleNode iVisited ) { progressMonitorWorked ( ) ; return super . visitModuleNode ( iVisited ) ; } private void progressMonitorWorked ( int work ) { if ( fProgressMonitor != null ) { fProgressMonitor . worked ( work ) ; if ( fProgressMonitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } } } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . List ; import java . util . StringTokenizer ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . preference . IPreferenceStore ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . internal . ui . util . StringMatcher ; public class CallHierarchy { private static final String PREF_USE_IMPLEMENTORS = "" ; private static final String PREF_USE_FILTERS = "" ; private static final String PREF_FILTERS_LIST = "" ; private static final String DEFAULT_IGNORE_FILTERS = "" ; private static CallHierarchy fgInstance ; private IRubySearchScope fSearchScope ; private StringMatcher [ ] fFilters ; public static CallHierarchy getDefault ( ) { if ( fgInstance == null ) { fgInstance = new CallHierarchy ( ) ; } return fgInstance ; } public boolean isSearchUsingImplementorsEnabled ( ) { IPreferenceStore settings = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; return settings . getBoolean ( PREF_USE_IMPLEMENTORS ) ; } public void setSearchUsingImplementorsEnabled ( boolean enabled ) { IPreferenceStore settings = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; settings . setValue ( PREF_USE_IMPLEMENTORS , enabled ) ; } public Collection getImplementingMethods ( IMethod method ) { if ( isSearchUsingImplementorsEnabled ( ) ) { IRubyElement [ ] result = Implementors . getInstance ( ) . searchForImplementors ( new IRubyElement [ ] { method } , new NullProgressMonitor ( ) ) ; if ( ( result != null ) && ( result . length > ) ) { return Arrays . asList ( result ) ; } } return new ArrayList ( ) ; } public Collection getInterfaceMethods ( IMethod method ) { if ( isSearchUsingImplementorsEnabled ( ) ) { IRubyElement [ ] result = Implementors . getInstance ( ) . searchForInterfaces ( new IRubyElement [ ] { method } , new NullProgressMonitor ( ) ) ; if ( ( result != null ) && ( result . length > ) ) { return Arrays . asList ( result ) ; } } return new ArrayList ( ) ; } public MethodWrapper getCallerRoot ( IMethod method ) { return new CallerMethodWrapper ( null , new MethodCall ( method ) ) ; } public MethodWrapper getCalleeRoot ( IMethod method ) { return new CalleeMethodWrapper ( null , new MethodCall ( method ) ) ; } public static CallLocation getCallLocation ( Object element ) { CallLocation callLocation = null ; if ( element instanceof MethodWrapper ) { MethodWrapper methodWrapper = ( MethodWrapper ) element ; MethodCall methodCall = methodWrapper . getMethodCall ( ) ; if ( methodCall != null ) { callLocation = methodCall . getFirstCallLocation ( ) ; } } else if ( element instanceof CallLocation ) { callLocation = ( CallLocation ) element ; } return callLocation ; } public IRubySearchScope getSearchScope ( ) { if ( fSearchScope == null ) { fSearchScope = SearchEngine . createWorkspaceScope ( ) ; } return fSearchScope ; } public void setSearchScope ( IRubySearchScope searchScope ) { this . fSearchScope = searchScope ; } public boolean isIgnored ( String fullyQualifiedName ) { if ( ( getIgnoreFilters ( ) != null ) && ( getIgnoreFilters ( ) . length > ) ) { for ( int i = ; i < getIgnoreFilters ( ) . length ; i ++ ) { String fullyQualifiedName1 = fullyQualifiedName ; if ( getIgnoreFilters ( ) [ i ] . match ( fullyQualifiedName1 ) ) { return true ; } } } return false ; } public boolean isFilterEnabled ( ) { IPreferenceStore settings = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; return settings . getBoolean ( PREF_USE_FILTERS ) ; } public void setFilterEnabled ( boolean filterEnabled ) { IPreferenceStore settings = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; settings . setValue ( PREF_USE_FILTERS , filterEnabled ) ; } public String getFilters ( ) { IPreferenceStore settings = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; return settings . getString ( PREF_FILTERS_LIST ) ; } public void setFilters ( String filters ) { fFilters = null ; IPreferenceStore settings = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; settings . setValue ( PREF_FILTERS_LIST , filters ) ; } private StringMatcher [ ] getIgnoreFilters ( ) { if ( fFilters == null ) { String filterString = null ; if ( isFilterEnabled ( ) ) { filterString = getFilters ( ) ; if ( filterString == null ) { filterString = DEFAULT_IGNORE_FILTERS ; } } if ( filterString != null ) { fFilters = parseList ( filterString ) ; } else { fFilters = null ; } } return fFilters ; } private static StringMatcher [ ] parseList ( String listString ) { List list = new ArrayList ( ) ; StringTokenizer tokenizer = new StringTokenizer ( listString , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) { String textFilter = tokenizer . nextToken ( ) . trim ( ) ; list . add ( new StringMatcher ( textFilter , false , false ) ) ; } return ( StringMatcher [ ] ) list . toArray ( new StringMatcher [ list . size ( ) ] ) ; } static Node getRubyScriptNode ( IMember member , boolean resolveBindings ) { IRubyScript icu = member . getRubyScript ( ) ; if ( icu != null && icu . exists ( ) ) { return ASTProvider . getASTProvider ( ) . getAST ( icu , ASTProvider . WAIT_YES , null ) ; } return null ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; public abstract class CallHierarchyVisitor { public void preVisit ( MethodWrapper methodWrapper ) { } public void postVisit ( MethodWrapper methodWrapper ) { } public boolean visit ( MethodWrapper methodWrapper ) { return true ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import org . eclipse . osgi . util . NLS ; public final class CallHierarchyMessages extends NLS { private static final String BUNDLE_NAME = "" ; private CallHierarchyMessages ( ) { } public static String CallerMethodWrapper_taskname ; public static String CalleeMethodWrapper_taskname ; static { NLS . initializeMessages ( BUNDLE_NAME , CallHierarchyMessages . class ) ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . rubypeople . rdt . core . IMember ; public class MethodCall { private IMember fMember ; private List fCallLocations ; public MethodCall ( IMember enclosingElement ) { this . fMember = enclosingElement ; } public Collection getCallLocations ( ) { return fCallLocations ; } public CallLocation getFirstCallLocation ( ) { if ( ( fCallLocations != null ) && ! fCallLocations . isEmpty ( ) ) { return ( CallLocation ) fCallLocations . get ( ) ; } else { return null ; } } public boolean hasCallLocations ( ) { return fCallLocations != null && fCallLocations . size ( ) > ; } public Object getKey ( ) { return getMember ( ) . getHandleIdentifier ( ) ; } public IMember getMember ( ) { return fMember ; } public void addCallLocation ( CallLocation location ) { if ( fCallLocations == null ) { fCallLocations = new ArrayList ( ) ; } fCallLocations . add ( location ) ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . HashMap ; import java . util . Map ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; class CallSearchResultCollector { private Map < String , MethodCall > fCalledMembers ; public CallSearchResultCollector ( ) { this . fCalledMembers = createCalledMethodsData ( ) ; } public Map < String , MethodCall > getCallers ( ) { return fCalledMembers ; } protected void addMember ( IMember member , IMember calledMember , int start , int end ) { addMember ( member , calledMember , start , end , CallLocation . UNKNOWN_LINE_NUMBER ) ; } protected void addMember ( IMember member , IMember calledMember , int start , int end , int lineNumber ) { if ( ( member != null ) && ( calledMember != null ) ) { if ( ! isIgnored ( calledMember ) ) { MethodCall methodCall = ( MethodCall ) fCalledMembers . get ( calledMember . getHandleIdentifier ( ) ) ; if ( methodCall == null ) { methodCall = new MethodCall ( calledMember ) ; fCalledMembers . put ( calledMember . getHandleIdentifier ( ) , methodCall ) ; } methodCall . addCallLocation ( new CallLocation ( member , calledMember , start , end , lineNumber ) ) ; } } } protected Map < String , MethodCall > createCalledMethodsData ( ) { return new HashMap < String , MethodCall > ( ) ; } private boolean isIgnored ( IMember enclosingElement ) { IType type = getTypeOfElement ( enclosingElement ) ; String fullyQualifiedName = "" ; if ( type != null ) { fullyQualifiedName = type . getFullyQualifiedName ( ) ; } return CallHierarchy . getDefault ( ) . isIgnored ( fullyQualifiedName ) ; } private IType getTypeOfElement ( IMember element ) { if ( element . getElementType ( ) == IRubyElement . TYPE ) { return ( IType ) element ; } return element . getDeclaringType ( ) ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . PlatformObject ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . callhierarchy . MethodWrapperWorkbenchAdapter ; public abstract class MethodWrapper extends PlatformObject { private Map fElements = null ; private Map fMethodCache ; private MethodCall fMethodCall ; private MethodWrapper fParent ; private int fLevel ; public MethodWrapper ( MethodWrapper parent , MethodCall methodCall ) { Assert . isNotNull ( methodCall ) ; if ( parent == null ) { setMethodCache ( new HashMap ( ) ) ; fLevel = ; } else { setMethodCache ( parent . getMethodCache ( ) ) ; fLevel = parent . getLevel ( ) + ; } this . fMethodCall = methodCall ; this . fParent = parent ; } public Object getAdapter ( Class adapter ) { if ( adapter == IRubyElement . class ) { return getMember ( ) ; } else if ( adapter == IWorkbenchAdapter . class ) { return new MethodWrapperWorkbenchAdapter ( this ) ; } else { return null ; } } public MethodWrapper [ ] getCalls ( IProgressMonitor progressMonitor ) { if ( fElements == null ) { doFindChildren ( progressMonitor ) ; } MethodWrapper [ ] result = new MethodWrapper [ fElements . size ( ) ] ; int i = ; for ( Iterator iter = fElements . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { MethodCall methodCall = getMethodCallFromMap ( fElements , iter . next ( ) ) ; result [ i ++ ] = createMethodWrapper ( methodCall ) ; } return result ; } public int getLevel ( ) { return fLevel ; } public IMember getMember ( ) { return getMethodCall ( ) . getMember ( ) ; } public MethodCall getMethodCall ( ) { return fMethodCall ; } public String getName ( ) { if ( getMethodCall ( ) != null ) { return getMethodCall ( ) . getMember ( ) . getElementName ( ) ; } else { return "" ; } } public MethodWrapper getParent ( ) { return fParent ; } public boolean equals ( Object oth ) { if ( this == oth ) { return true ; } if ( oth == null ) { return false ; } if ( oth instanceof MethodWrapperWorkbenchAdapter ) { oth = ( ( MethodWrapperWorkbenchAdapter ) oth ) . getMethodWrapper ( ) ; } if ( oth . getClass ( ) != getClass ( ) ) { return false ; } MethodWrapper other = ( MethodWrapper ) oth ; if ( this . fParent == null ) { if ( other . fParent != null ) { return false ; } } else { if ( ! this . fParent . equals ( other . fParent ) ) { return false ; } } if ( this . getMethodCall ( ) == null ) { if ( other . getMethodCall ( ) != null ) { return false ; } } else { if ( ! this . getMethodCall ( ) . equals ( other . getMethodCall ( ) ) ) { return false ; } } return true ; } public int hashCode ( ) { final int PRIME = ; int result = ; if ( fParent != null ) { result = ( PRIME * result ) + fParent . hashCode ( ) ; } if ( getMethodCall ( ) != null ) { result = ( PRIME * result ) + getMethodCall ( ) . getMember ( ) . hashCode ( ) ; } return result ; } private void setMethodCache ( Map methodCache ) { fMethodCache = methodCache ; } protected abstract String getTaskName ( ) ; private void addCallToCache ( MethodCall methodCall ) { Map cachedCalls = lookupMethod ( this . getMethodCall ( ) ) ; cachedCalls . put ( methodCall . getKey ( ) , methodCall ) ; } protected abstract MethodWrapper createMethodWrapper ( MethodCall methodCall ) ; private void doFindChildren ( IProgressMonitor progressMonitor ) { Map existingResults = lookupMethod ( getMethodCall ( ) ) ; if ( existingResults != null ) { fElements = new HashMap ( ) ; fElements . putAll ( existingResults ) ; } else { initCalls ( ) ; if ( progressMonitor != null ) { progressMonitor . beginTask ( getTaskName ( ) , ) ; } try { performSearch ( progressMonitor ) ; } finally { if ( progressMonitor != null ) { progressMonitor . done ( ) ; } } } } public boolean isRecursive ( ) { MethodWrapper current = getParent ( ) ; while ( current != null ) { if ( getMember ( ) . getHandleIdentifier ( ) . equals ( current . getMember ( ) . getHandleIdentifier ( ) ) ) { return true ; } current = current . getParent ( ) ; } return false ; } protected abstract Map findChildren ( IProgressMonitor progressMonitor ) ; private Map getMethodCache ( ) { return fMethodCache ; } private void initCalls ( ) { this . fElements = new HashMap ( ) ; initCacheForMethod ( ) ; } private Map lookupMethod ( MethodCall methodCall ) { return ( Map ) getMethodCache ( ) . get ( methodCall . getKey ( ) ) ; } private void performSearch ( IProgressMonitor progressMonitor ) { fElements = findChildren ( progressMonitor ) ; for ( Iterator iter = fElements . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { checkCanceled ( progressMonitor ) ; MethodCall methodCall = getMethodCallFromMap ( fElements , iter . next ( ) ) ; addCallToCache ( methodCall ) ; } } private MethodCall getMethodCallFromMap ( Map < String , MethodCall > elements , Object key ) { return ( MethodCall ) elements . get ( key ) ; } private void initCacheForMethod ( ) { Map cachedCalls = new HashMap ( ) ; getMethodCache ( ) . put ( this . getMethodCall ( ) . getKey ( ) , cachedCalls ) ; } protected void checkCanceled ( IProgressMonitor progressMonitor ) { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } } public void accept ( CallHierarchyVisitor visitor , IProgressMonitor progressMonitor ) { if ( getParent ( ) != null && getParent ( ) . isRecursive ( ) ) { return ; } checkCanceled ( progressMonitor ) ; visitor . preVisit ( this ) ; if ( visitor . visit ( this ) ) { MethodWrapper [ ] methodWrappers = getCalls ( progressMonitor ) ; for ( int i = ; i < methodWrappers . length ; i ++ ) { methodWrappers [ i ] . accept ( visitor , progressMonitor ) ; } } visitor . postVisit ( this ) ; if ( progressMonitor != null ) { progressMonitor . worked ( ) ; } } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . Map ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchRequestor ; class MethodReferencesSearchRequestor extends SearchRequestor { private CallSearchResultCollector fSearchResults ; private boolean fRequireExactMatch = false ; MethodReferencesSearchRequestor ( ) { fSearchResults = new CallSearchResultCollector ( ) ; } public Map getCallers ( ) { return fSearchResults . getCallers ( ) ; } public void acceptSearchMatch ( SearchMatch match ) { if ( fRequireExactMatch && ( match . getAccuracy ( ) != SearchMatch . A_ACCURATE ) ) { return ; } if ( match . isInsideDocComment ( ) ) { return ; } if ( match . getElement ( ) != null && match . getElement ( ) instanceof IMember ) { IMember member = ( IMember ) match . getElement ( ) ; switch ( member . getElementType ( ) ) { case IRubyElement . METHOD : case IRubyElement . TYPE : case IRubyElement . FIELD : fSearchResults . addMember ( member , member , match . getOffset ( ) , match . getOffset ( ) + match . getLength ( ) ) ; break ; } } } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . Collection ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IType ; public interface IImplementorFinder { public abstract Collection findImplementingTypes ( IType type , IProgressMonitor progressMonitor ) ; public abstract Collection findInterfaces ( IType type , IProgressMonitor progressMonitor ) ; } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . Arrays ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . IProgressMonitor ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; class CalleeMethodWrapper extends MethodWrapper { private Comparator fMethodWrapperComparator = new MethodWrapperComparator ( ) ; private static class MethodWrapperComparator implements Comparator { public int compare ( Object o1 , Object o2 ) { MethodWrapper m1 = ( MethodWrapper ) o1 ; MethodWrapper m2 = ( MethodWrapper ) o2 ; CallLocation callLocation1 = m1 . getMethodCall ( ) . getFirstCallLocation ( ) ; CallLocation callLocation2 = m2 . getMethodCall ( ) . getFirstCallLocation ( ) ; if ( ( callLocation1 != null ) && ( callLocation2 != null ) ) { if ( callLocation1 . getStart ( ) == callLocation2 . getStart ( ) ) { return callLocation1 . getEnd ( ) - callLocation2 . getEnd ( ) ; } return callLocation1 . getStart ( ) - callLocation2 . getStart ( ) ; } return ; } } public CalleeMethodWrapper ( MethodWrapper parent , MethodCall methodCall ) { super ( parent , methodCall ) ; } public MethodWrapper [ ] getCalls ( IProgressMonitor progressMonitor ) { MethodWrapper [ ] result = super . getCalls ( progressMonitor ) ; Arrays . sort ( result , fMethodWrapperComparator ) ; return result ; } protected String getTaskName ( ) { return CallHierarchyMessages . CalleeMethodWrapper_taskname ; } protected MethodWrapper createMethodWrapper ( MethodCall methodCall ) { return new CalleeMethodWrapper ( this , methodCall ) ; } protected Map < String , MethodCall > findChildren ( IProgressMonitor progressMonitor ) { if ( getMember ( ) . exists ( ) && getMember ( ) . getElementType ( ) == IRubyElement . METHOD ) { Node cu = CallHierarchy . getRubyScriptNode ( getMember ( ) , true ) ; if ( progressMonitor != null ) { progressMonitor . worked ( ) ; } if ( cu != null ) { CalleeAnalyzerVisitor visitor = new CalleeAnalyzerVisitor ( ( IMethod ) getMember ( ) , progressMonitor ) ; cu . accept ( visitor ) ; return visitor . getCallees ( ) ; } } return new HashMap < String , MethodCall > ( ) ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class CallLocation implements IAdaptable { public static final int UNKNOWN_LINE_NUMBER = - ; private IMember fMember ; private IMember fCalledMember ; private int fStart ; private int fEnd ; private String fCallText ; private int fLineNumber ; public CallLocation ( IMember member , IMember calledMember , int start , int end , int lineNumber ) { this . fMember = member ; this . fCalledMember = calledMember ; this . fStart = start ; this . fEnd = end ; this . fLineNumber = lineNumber ; } public IMember getCalledMember ( ) { return fCalledMember ; } public int getEnd ( ) { return fEnd ; } public IMember getMember ( ) { return fMember ; } public int getStart ( ) { return fStart ; } public int getLineNumber ( ) { initCallTextAndLineNumber ( ) ; return fLineNumber ; } public String getCallText ( ) { initCallTextAndLineNumber ( ) ; return fCallText ; } private void initCallTextAndLineNumber ( ) { if ( fCallText != null ) return ; IBuffer buffer = getBufferForMember ( ) ; if ( buffer == null || buffer . getLength ( ) < fEnd ) { fCallText = "" ; fLineNumber = UNKNOWN_LINE_NUMBER ; return ; } fCallText = buffer . getText ( fStart , ( fEnd - fStart ) ) ; if ( fLineNumber == UNKNOWN_LINE_NUMBER ) { Document document = new Document ( buffer . getContents ( ) ) ; try { fLineNumber = document . getLineOfOffset ( fStart ) + ; } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; } } } private IBuffer getBufferForMember ( ) { IBuffer buffer = null ; try { IOpenable openable = fMember . getOpenable ( ) ; if ( openable != null && fMember . exists ( ) ) { buffer = openable . getBuffer ( ) ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return buffer ; } public String toString ( ) { return getCallText ( ) ; } public Object getAdapter ( Class adapter ) { if ( IRubyElement . class . isAssignableFrom ( adapter ) ) { return getMember ( ) ; } return null ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . ArrayList ; import java . util . Collection ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class Implementors { private static IImplementorFinder [ ] IMPLEMENTOR_FINDERS = new IImplementorFinder [ ] { new RubyImplementorFinder ( ) } ; private static Implementors fgInstance ; public static Implementors getInstance ( ) { if ( fgInstance == null ) { fgInstance = new Implementors ( ) ; } return fgInstance ; } public IRubyElement [ ] searchForImplementors ( IRubyElement [ ] elements , IProgressMonitor progressMonitor ) { if ( ( elements != null ) && ( elements . length > ) ) { IRubyElement element = elements [ ] ; if ( element instanceof IMember ) { IMember member = ( IMember ) element ; IType type = member . getDeclaringType ( ) ; if ( type . isModule ( ) ) { IType [ ] implementingTypes = findImplementingTypes ( type , progressMonitor ) ; if ( member . getElementType ( ) == IRubyElement . METHOD ) { return findMethods ( ( IMethod ) member , implementingTypes , progressMonitor ) ; } else { return implementingTypes ; } } } } return null ; } public IRubyElement [ ] searchForInterfaces ( IRubyElement [ ] elements , IProgressMonitor progressMonitor ) { if ( ( elements != null ) && ( elements . length > ) ) { IRubyElement element = elements [ ] ; if ( element instanceof IMember ) { IMember member = ( IMember ) element ; IType type = member . getDeclaringType ( ) ; IType [ ] implementingTypes = findInterfaces ( type , progressMonitor ) ; if ( ! progressMonitor . isCanceled ( ) ) { if ( member . getElementType ( ) == IRubyElement . METHOD ) { return findMethods ( ( IMethod ) member , implementingTypes , progressMonitor ) ; } else { return implementingTypes ; } } } } return null ; } private IImplementorFinder [ ] getImplementorFinders ( ) { return IMPLEMENTOR_FINDERS ; } private IType [ ] findImplementingTypes ( IType type , IProgressMonitor progressMonitor ) { Collection implementingTypes = new ArrayList ( ) ; IImplementorFinder [ ] finders = getImplementorFinders ( ) ; for ( int i = ; ( i < finders . length ) && ! progressMonitor . isCanceled ( ) ; i ++ ) { Collection types = finders [ i ] . findImplementingTypes ( type , new SubProgressMonitor ( progressMonitor , , SubProgressMonitor . SUPPRESS_SUBTASK_LABEL ) ) ; if ( types != null ) { implementingTypes . addAll ( types ) ; } } return ( IType [ ] ) implementingTypes . toArray ( new IType [ implementingTypes . size ( ) ] ) ; } private IType [ ] findInterfaces ( IType type , IProgressMonitor progressMonitor ) { Collection interfaces = new ArrayList ( ) ; IImplementorFinder [ ] finders = getImplementorFinders ( ) ; for ( int i = ; ( i < finders . length ) && ! progressMonitor . isCanceled ( ) ; i ++ ) { Collection types = finders [ i ] . findInterfaces ( type , new SubProgressMonitor ( progressMonitor , , SubProgressMonitor . SUPPRESS_SUBTASK_LABEL ) ) ; if ( types != null ) { interfaces . addAll ( types ) ; } } return ( IType [ ] ) interfaces . toArray ( new IType [ interfaces . size ( ) ] ) ; } private IRubyElement [ ] findMethods ( IMethod method , IType [ ] types , IProgressMonitor progressMonitor ) { Collection foundMethods = new ArrayList ( ) ; SubProgressMonitor subProgressMonitor = new SubProgressMonitor ( progressMonitor , , SubProgressMonitor . SUPPRESS_SUBTASK_LABEL ) ; subProgressMonitor . beginTask ( "" , types . length ) ; try { for ( int i = ; i < types . length ; i ++ ) { IType type = types [ i ] ; IMethod [ ] methods = type . findMethods ( method ) ; if ( methods != null ) { for ( int j = ; j < methods . length ; j ++ ) { foundMethods . add ( methods [ j ] ) ; } } subProgressMonitor . worked ( ) ; } } finally { subProgressMonitor . done ( ) ; } return ( IRubyElement [ ] ) foundMethods . toArray ( new IRubyElement [ foundMethods . size ( ) ] ) ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . Arrays ; import java . util . Collection ; import java . util . HashSet ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class RubyImplementorFinder implements IImplementorFinder { public Collection findImplementingTypes ( IType type , IProgressMonitor progressMonitor ) { ITypeHierarchy typeHierarchy ; try { typeHierarchy = type . newTypeHierarchy ( progressMonitor ) ; IType [ ] implementingTypes = typeHierarchy . getAllClasses ( ) ; HashSet result = new HashSet ( Arrays . asList ( implementingTypes ) ) ; return result ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return null ; } public Collection findInterfaces ( IType type , IProgressMonitor progressMonitor ) { ITypeHierarchy typeHierarchy ; try { typeHierarchy = type . newSupertypeHierarchy ( progressMonitor ) ; IType [ ] interfaces = typeHierarchy . getAllSuperModules ( type ) ; HashSet result = new HashSet ( Arrays . asList ( interfaces ) ) ; return result ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return null ; } } package org . rubypeople . rdt . internal . corext . callhierarchy ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . corext . util . SearchUtils ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; class CallerMethodWrapper extends MethodWrapper { public CallerMethodWrapper ( MethodWrapper parent , MethodCall methodCall ) { super ( parent , methodCall ) ; } protected IRubySearchScope getSearchScope ( ) { return CallHierarchy . getDefault ( ) . getSearchScope ( ) ; } protected String getTaskName ( ) { return CallHierarchyMessages . CallerMethodWrapper_taskname ; } protected MethodWrapper createMethodWrapper ( MethodCall methodCall ) { return new CallerMethodWrapper ( this , methodCall ) ; } protected Map findChildren ( IProgressMonitor progressMonitor ) { try { MethodReferencesSearchRequestor searchRequestor = new MethodReferencesSearchRequestor ( ) ; SearchEngine searchEngine = new SearchEngine ( ) ; IProgressMonitor monitor = new SubProgressMonitor ( progressMonitor , , SubProgressMonitor . SUPPRESS_SUBTASK_LABEL ) ; IRubySearchScope defaultSearchScope = getSearchScope ( ) ; boolean isWorkspaceScope = SearchEngine . createWorkspaceScope ( ) . equals ( defaultSearchScope ) ; for ( Iterator iter = getMembers ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { checkCanceled ( progressMonitor ) ; IMember member = ( IMember ) iter . next ( ) ; SearchPattern pattern = SearchPattern . createPattern ( member , IRubySearchConstants . REFERENCES , SearchUtils . GENERICS_AGNOSTIC_MATCH_RULE ) ; IRubySearchScope searchScope = isWorkspaceScope ? getAccurateSearchScope ( defaultSearchScope , member ) : defaultSearchScope ; searchEngine . search ( pattern , new SearchParticipant [ ] { SearchEngine . getDefaultSearchParticipant ( ) } , searchScope , searchRequestor , monitor ) ; } return searchRequestor . getCallers ( ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; return new HashMap ( ) ; } } private IRubySearchScope getAccurateSearchScope ( IRubySearchScope defaultSearchScope , IMember member ) throws RubyModelException { if ( ! ( member . isType ( IRubyElement . METHOD ) && ( ( ( IMethod ) member ) . isPrivate ( ) ) ) ) return defaultSearchScope ; if ( member . getRubyScript ( ) != null ) { return SearchEngine . createRubySearchScope ( new IRubyElement [ ] { member . getRubyScript ( ) } ) ; } else { return defaultSearchScope ; } } private Collection getMembers ( ) { Collection result = new ArrayList ( ) ; result . add ( getMember ( ) ) ; return result ; } } package org . rubypeople . rdt . internal . corext . util ; import java . util . Map ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . BadPositionCategoryException ; import org . eclipse . jface . text . DefaultPositionUpdater ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . Position ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . ToolFactory ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class CodeFormatterUtil { public static TextEdit format2 ( int kind , String string , int offset , int length , int indentationLevel , String lineSeparator , Map options ) { if ( offset < || length < || offset + length > string . length ( ) ) { throw new IllegalArgumentException ( "" + offset + "" + length + "" + string . length ( ) ) ; } return ToolFactory . createCodeFormatter ( options ) . format ( kind , string , offset , length , indentationLevel , lineSeparator ) ; } public static int getIndentWidth ( IRubyProject project ) { String key ; if ( DefaultCodeFormatterConstants . MIXED . equals ( getCoreOption ( project , DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ) ) ) key = DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE ; else key = DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ; return getCoreOption ( project , key , ) ; } public static int getTabWidth ( IRubyProject project ) { String key ; if ( RubyCore . SPACE . equals ( getCoreOption ( project , DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ) ) ) key = DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE ; else key = DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ; return getCoreOption ( project , key , ) ; } private static String getCoreOption ( IRubyProject project , String key ) { if ( project == null ) return RubyCore . getOption ( key ) ; return project . getOption ( key , true ) ; } private static int getCoreOption ( IRubyProject project , String key , int def ) { try { return Integer . parseInt ( getCoreOption ( project , key ) ) ; } catch ( NumberFormatException e ) { return def ; } } public static String createIndentString ( int indentationUnits , IRubyProject project ) { final String tabChar = getCoreOption ( project , DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ) ; final int tabs , spaces ; if ( RubyCore . SPACE . equals ( tabChar ) ) { tabs = ; spaces = indentationUnits * getIndentWidth ( project ) ; } else if ( RubyCore . TAB . equals ( tabChar ) ) { tabs = indentationUnits ; spaces = ; } else if ( DefaultCodeFormatterConstants . MIXED . equals ( tabChar ) ) { int tabWidth = getTabWidth ( project ) ; int spaceEquivalents = indentationUnits * getIndentWidth ( project ) ; if ( tabWidth > ) { tabs = spaceEquivalents / tabWidth ; spaces = spaceEquivalents % tabWidth ; } else { tabs = ; spaces = spaceEquivalents ; } } else { Assert . isTrue ( false ) ; return null ; } StringBuffer buffer = new StringBuffer ( tabs + spaces ) ; for ( int i = ; i < tabs ; i ++ ) buffer . append ( '' ) ; for ( int i = ; i < spaces ; i ++ ) buffer . append ( '' ) ; return buffer . toString ( ) ; } public static TextEdit format2 ( int kind , String string , int indentationLevel , String lineSeparator , Map options ) { return format2 ( kind , string , , string . length ( ) , indentationLevel , lineSeparator , options ) ; } public static String format ( int kind , String string , int offset , int length , int indentationLevel , int [ ] positions , String lineSeparator , Map options ) { TextEdit edit = format2 ( kind , string , offset , length , indentationLevel , lineSeparator , options ) ; if ( edit == null ) { return string . substring ( offset , offset + length ) ; } String formatted = getOldAPICompatibleResult ( string , edit , indentationLevel , positions , lineSeparator , options ) ; return formatted . substring ( offset , formatted . length ( ) - ( string . length ( ) - ( offset + length ) ) ) ; } private static String getOldAPICompatibleResult ( String string , TextEdit edit , int indentationLevel , int [ ] positions , String lineSeparator , Map options ) { Position [ ] p = null ; if ( positions != null ) { p = new Position [ positions . length ] ; for ( int i = ; i < positions . length ; i ++ ) { p [ i ] = new Position ( positions [ i ] , ) ; } } String res = evaluateFormatterEdit ( string , edit , p ) ; if ( positions != null ) { for ( int i = ; i < positions . length ; i ++ ) { Position curr = p [ i ] ; positions [ i ] = curr . getOffset ( ) ; } } return res ; } public static String evaluateFormatterEdit ( String string , TextEdit edit , Position [ ] positions ) { try { Document doc = createDocument ( string , positions ) ; edit . apply ( doc , ) ; if ( positions != null ) { for ( int i = ; i < positions . length ; i ++ ) { Assert . isTrue ( ! positions [ i ] . isDeleted , "" ) ; } } return doc . get ( ) ; } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; Assert . isTrue ( false , "" + e . getMessage ( ) ) ; } return null ; } private static Document createDocument ( String string , Position [ ] positions ) throws IllegalArgumentException { Document doc = new Document ( string ) ; try { if ( positions != null ) { final String POS_CATEGORY = "" ; doc . addPositionCategory ( POS_CATEGORY ) ; doc . addPositionUpdater ( new DefaultPositionUpdater ( POS_CATEGORY ) { protected boolean notDeleted ( ) { if ( fOffset < fPosition . offset && ( fPosition . offset + fPosition . length < fOffset + fLength ) ) { fPosition . offset = fOffset + fLength ; return false ; } return true ; } } ) ; for ( int i = ; i < positions . length ; i ++ ) { try { doc . addPosition ( POS_CATEGORY , positions [ i ] ) ; } catch ( BadLocationException e ) { throw new IllegalArgumentException ( "" + positions [ i ] . offset + "" + positions [ i ] . length + "" + string . length ( ) ) ; } } } } catch ( BadPositionCategoryException cannotHappen ) { } return doc ; } public static String format ( int kind , String string , int indentationLevel , int [ ] positions , String lineSeparator , IRubyProject project ) { Map options = project != null ? project . getOptions ( true ) : null ; return format ( kind , string , , string . length ( ) , indentationLevel , positions , lineSeparator , options ) ; } } package org . rubypeople . rdt . internal . corext . util ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . SearchPattern ; public class SearchUtils { public final static int GENERICS_AGNOSTIC_MATCH_RULE = SearchPattern . R_EXACT_MATCH | SearchPattern . R_CASE_SENSITIVE | SearchPattern . R_ERASURE_MATCH ; public static boolean isCamelCasePattern ( String pattern ) { return SearchPattern . validateMatchRule ( pattern , SearchPattern . R_CAMELCASE_MATCH ) == SearchPattern . R_CAMELCASE_MATCH ; } } package org . rubypeople . rdt . internal . corext . util ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . util . Collection ; import java . util . Hashtable ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . Map ; import java . util . Set ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . Transformer ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . TransformerFactoryConfigurationError ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . rubypeople . rdt . internal . corext . CorextMessages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIException ; import org . rubypeople . rdt . internal . ui . RubyUIStatus ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; public abstract class History { private static final String DEFAULT_ROOT_NODE_NAME = "" ; private static final String DEFAULT_INFO_NODE_NAME = "" ; private static final int MAX_HISTORY_SIZE = ; private static RubyUIException createException ( Throwable t , String message ) { return new RubyUIException ( RubyUIStatus . createError ( IStatus . ERROR , message , t ) ) ; } private final Map fHistory ; private final Hashtable fPositions ; private final String fFileName ; private final String fRootNodeName ; private final String fInfoNodeName ; public History ( String fileName , String rootNodeName , String infoNodeName ) { fHistory = new LinkedHashMap ( , , true ) { private static final long serialVersionUID = ; protected boolean removeEldestEntry ( Map . Entry eldest ) { return size ( ) > MAX_HISTORY_SIZE ; } } ; fFileName = fileName ; fRootNodeName = rootNodeName ; fInfoNodeName = infoNodeName ; fPositions = new Hashtable ( MAX_HISTORY_SIZE ) ; } public History ( String fileName ) { this ( fileName , DEFAULT_ROOT_NODE_NAME , DEFAULT_INFO_NODE_NAME ) ; } public synchronized void accessed ( Object object ) { fHistory . put ( getKey ( object ) , object ) ; rebuildPositions ( ) ; } public synchronized boolean contains ( Object object ) { return fHistory . containsKey ( getKey ( object ) ) ; } public synchronized boolean containsKey ( Object key ) { return fHistory . containsKey ( key ) ; } public synchronized boolean isEmpty ( ) { return fHistory . isEmpty ( ) ; } public synchronized Object remove ( Object object ) { Object removed = fHistory . remove ( getKey ( object ) ) ; rebuildPositions ( ) ; return removed ; } public synchronized Object removeKey ( Object key ) { Object removed = fHistory . remove ( key ) ; rebuildPositions ( ) ; return removed ; } public synchronized float getNormalizedPosition ( Object key ) { if ( ! containsKey ( key ) ) return ; int pos = ( ( Integer ) fPositions . get ( key ) ) . intValue ( ) + ; return ( float ) pos / ( float ) fHistory . size ( ) ; } public synchronized int getPosition ( Object key ) { if ( ! containsKey ( key ) ) return - ; return ( ( Integer ) fPositions . get ( key ) ) . intValue ( ) ; } public synchronized void load ( ) { IPath stateLocation = RubyPlugin . getDefault ( ) . getStateLocation ( ) . append ( fFileName ) ; File file = new File ( stateLocation . toOSString ( ) ) ; if ( file . exists ( ) ) { InputStreamReader reader = null ; try { reader = new InputStreamReader ( new FileInputStream ( file ) , "" ) ; load ( new InputSource ( reader ) ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } finally { try { if ( reader != null ) reader . close ( ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } } } } public synchronized void save ( ) { IPath stateLocation = RubyPlugin . getDefault ( ) . getStateLocation ( ) . append ( fFileName ) ; File file = new File ( stateLocation . toOSString ( ) ) ; OutputStream out = null ; try { out = new FileOutputStream ( file ) ; save ( out ) ; } catch ( IOException e ) { RubyPlugin . log ( e ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } catch ( TransformerFactoryConfigurationError e ) { RubyPlugin . log ( e ) ; } finally { try { if ( out != null ) { out . close ( ) ; } } catch ( IOException e ) { RubyPlugin . log ( e ) ; } } } protected Set getKeys ( ) { return fHistory . keySet ( ) ; } protected Collection getValues ( ) { return fHistory . values ( ) ; } protected abstract void setAttributes ( Object object , Element element ) ; protected abstract Object createFromElement ( Element element ) ; protected abstract Object getKey ( Object object ) ; private void rebuildPositions ( ) { fPositions . clear ( ) ; Collection values = fHistory . values ( ) ; int pos = ; for ( Iterator iter = values . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; fPositions . put ( getKey ( element ) , new Integer ( pos ) ) ; pos ++ ; } } private void load ( InputSource inputSource ) throws CoreException { Element root ; try { DocumentBuilder parser = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; root = parser . parse ( inputSource ) . getDocumentElement ( ) ; } catch ( SAXException e ) { throw createException ( e , Messages . format ( CorextMessages . History_error_read , fFileName ) ) ; } catch ( ParserConfigurationException e ) { throw createException ( e , Messages . format ( CorextMessages . History_error_read , fFileName ) ) ; } catch ( IOException e ) { throw createException ( e , Messages . format ( CorextMessages . History_error_read , fFileName ) ) ; } if ( root == null ) return ; if ( ! root . getNodeName ( ) . equalsIgnoreCase ( fRootNodeName ) ) { return ; } NodeList list = root . getChildNodes ( ) ; int length = list . getLength ( ) ; for ( int i = ; i < length ; ++ i ) { Node node = list . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element type = ( Element ) node ; if ( type . getNodeName ( ) . equalsIgnoreCase ( fInfoNodeName ) ) { Object object = createFromElement ( type ) ; fHistory . put ( getKey ( object ) , object ) ; } } } rebuildPositions ( ) ; } private void save ( OutputStream stream ) throws CoreException { try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document document = builder . newDocument ( ) ; Element rootElement = document . createElement ( fRootNodeName ) ; document . appendChild ( rootElement ) ; Iterator values = getValues ( ) . iterator ( ) ; while ( values . hasNext ( ) ) { Object object = values . next ( ) ; Element element = document . createElement ( fInfoNodeName ) ; setAttributes ( object , element ) ; rootElement . appendChild ( element ) ; } Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . METHOD , "" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , "" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "" ) ; DOMSource source = new DOMSource ( document ) ; StreamResult result = new StreamResult ( stream ) ; transformer . transform ( source , result ) ; } catch ( TransformerException e ) { throw createException ( e , Messages . format ( CorextMessages . History_error_serialize , fFileName ) ) ; } catch ( ParserConfigurationException e ) { throw createException ( e , Messages . format ( CorextMessages . History_error_serialize , fFileName ) ) ; } } } package org . rubypeople . rdt . internal . corext . util ; import java . text . MessageFormat ; public class Messages { public static String format ( String message , Object object ) { return MessageFormat . format ( message , new Object [ ] { object } ) ; } public static String format ( String message , Object [ ] objects ) { return MessageFormat . format ( message , objects ) ; } private Messages ( ) { } } package org . rubypeople . rdt . internal . corext . util ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . StringTokenizer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . corext . CorextMessages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . w3c . dom . Element ; public class OpenTypeHistory extends History { private static class TypeHistoryDeltaListener implements IElementChangedListener { public void elementChanged ( ElementChangedEvent event ) { if ( processDelta ( event . getDelta ( ) ) ) { OpenTypeHistory . getInstance ( ) . markAsInconsistent ( ) ; } } private boolean processDelta ( IRubyElementDelta delta ) { IRubyElement elem = delta . getElement ( ) ; boolean isChanged = delta . getKind ( ) == IRubyElementDelta . CHANGED ; boolean isRemoved = delta . getKind ( ) == IRubyElementDelta . REMOVED ; switch ( elem . getElementType ( ) ) { case IRubyElement . RUBY_PROJECT : if ( isRemoved || ( isChanged && ( delta . getFlags ( ) & IRubyElementDelta . F_CLOSED ) != ) ) { return true ; } return processChildrenDelta ( delta ) ; case IRubyElement . SOURCE_FOLDER_ROOT : if ( isRemoved || ( isChanged && ( ( delta . getFlags ( ) & IRubyElementDelta . F_ARCHIVE_CONTENT_CHANGED ) != || ( delta . getFlags ( ) & IRubyElementDelta . F_REMOVED_FROM_CLASSPATH ) != ) ) ) { return true ; } return processChildrenDelta ( delta ) ; case IRubyElement . TYPE : if ( isChanged && ( delta . getFlags ( ) & IRubyElementDelta . F_MODIFIERS ) != ) { return true ; } case IRubyElement . RUBY_MODEL : case IRubyElement . SOURCE_FOLDER : if ( isRemoved ) { return true ; } return processChildrenDelta ( delta ) ; case IRubyElement . SCRIPT : if ( ! RubyModelUtil . isPrimary ( ( IRubyScript ) elem ) ) { return false ; } if ( isRemoved || ( isChanged && isUnknownStructuralChange ( delta . getFlags ( ) ) ) ) { return true ; } return processChildrenDelta ( delta ) ; default : return false ; } } private boolean isUnknownStructuralChange ( int flags ) { if ( ( flags & IRubyElementDelta . F_CONTENT ) == ) return false ; return ( flags & IRubyElementDelta . F_FINE_GRAINED ) == ; } private boolean processChildrenDelta ( IRubyElementDelta delta ) { IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( processDelta ( children [ i ] ) ) { return true ; } } return false ; } } private static class UpdateJob extends Job { public static final String FAMILY = UpdateJob . class . getName ( ) ; public UpdateJob ( ) { super ( CorextMessages . TypeInfoHistory_consistency_check ) ; } protected IStatus run ( IProgressMonitor monitor ) { OpenTypeHistory history = OpenTypeHistory . getInstance ( ) ; history . internalCheckConsistency ( monitor ) ; return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } public boolean belongsTo ( Object family ) { return FAMILY . equals ( family ) ; } } private volatile boolean fNeedsConsistencyCheck ; private Map fTimestampMapping ; private final IElementChangedListener fDeltaListener ; private final UpdateJob fUpdateJob ; private final TypeInfoFactory fTypeInfoFactory ; private static final String FILENAME = "" ; private static final String NODE_ROOT = "" ; private static final String NODE_TYPE_INFO = "" ; private static final String NODE_NAME = "" ; private static final String NODE_PACKAGE = "" ; private static final String NODE_ENCLOSING_NAMES = "" ; private static final String NODE_PATH = "" ; private static final String NODE_MODIFIERS = "" ; private static final String NODE_TIMESTAMP = "" ; private static final char [ ] [ ] EMPTY_ENCLOSING_NAMES = new char [ ] [ ] ; private static OpenTypeHistory fgInstance ; public static synchronized OpenTypeHistory getInstance ( ) { if ( fgInstance == null ) fgInstance = new OpenTypeHistory ( ) ; return fgInstance ; } public static synchronized void shutdown ( ) { if ( fgInstance == null ) return ; fgInstance . doShutdown ( ) ; } private OpenTypeHistory ( ) { super ( FILENAME , NODE_ROOT , NODE_TYPE_INFO ) ; fTypeInfoFactory = new TypeInfoFactory ( ) ; fTimestampMapping = new HashMap ( ) ; fNeedsConsistencyCheck = true ; load ( ) ; fDeltaListener = new TypeHistoryDeltaListener ( ) ; RubyCore . addElementChangedListener ( fDeltaListener ) ; fUpdateJob = new UpdateJob ( ) ; fUpdateJob . setPriority ( Job . SHORT ) ; } public void markAsInconsistent ( ) { fNeedsConsistencyCheck = true ; fUpdateJob . cancel ( ) ; fUpdateJob . schedule ( ) ; } public boolean needConsistencyCheck ( ) { return fNeedsConsistencyCheck ; } public void checkConsistency ( IProgressMonitor monitor ) throws OperationCanceledException { if ( ! fNeedsConsistencyCheck ) return ; if ( fUpdateJob . getState ( ) == Job . RUNNING ) { try { Platform . getJobManager ( ) . join ( UpdateJob . FAMILY , monitor ) ; } catch ( OperationCanceledException e ) { } catch ( InterruptedException e ) { } } if ( ! fNeedsConsistencyCheck ) return ; internalCheckConsistency ( monitor ) ; } public synchronized boolean contains ( TypeInfo type ) { return super . contains ( type ) ; } public synchronized void accessed ( TypeInfo info ) { if ( ! fTimestampMapping . containsKey ( info ) ) { fTimestampMapping . put ( info , new Long ( info . getContainerTimestamp ( ) ) ) ; } super . accessed ( info ) ; } public synchronized TypeInfo remove ( TypeInfo info ) { fTimestampMapping . remove ( info ) ; return ( TypeInfo ) super . remove ( info ) ; } public synchronized TypeInfo [ ] getTypeInfos ( ) { Collection values = getValues ( ) ; int size = values . size ( ) ; TypeInfo [ ] result = new TypeInfo [ size ] ; int i = size - ; for ( Iterator iter = values . iterator ( ) ; iter . hasNext ( ) ; ) { result [ i ] = ( TypeInfo ) iter . next ( ) ; i -- ; } return result ; } public synchronized TypeInfo [ ] getFilteredTypeInfos ( TypeInfoFilter filter ) { Collection values = getValues ( ) ; List result = new ArrayList ( ) ; for ( Iterator iter = values . iterator ( ) ; iter . hasNext ( ) ; ) { TypeInfo type = ( TypeInfo ) iter . next ( ) ; if ( ( filter == null || filter . matchesHistoryElement ( type ) ) && ! TypeFilter . isFiltered ( type . getFullyQualifiedName ( ) ) ) result . add ( type ) ; } Collections . reverse ( result ) ; return ( TypeInfo [ ] ) result . toArray ( new TypeInfo [ result . size ( ) ] ) ; } protected Object getKey ( Object object ) { return object ; } private synchronized void internalCheckConsistency ( IProgressMonitor monitor ) throws OperationCanceledException { fNeedsConsistencyCheck = true ; IRubySearchScope scope = SearchEngine . createWorkspaceScope ( ) ; List typesToCheck = new ArrayList ( getKeys ( ) ) ; monitor . beginTask ( CorextMessages . TypeInfoHistory_consistency_check , typesToCheck . size ( ) ) ; monitor . setTaskName ( CorextMessages . TypeInfoHistory_consistency_check ) ; for ( Iterator iter = typesToCheck . iterator ( ) ; iter . hasNext ( ) ; ) { TypeInfo type = ( TypeInfo ) iter . next ( ) ; long currentTimestamp = type . getContainerTimestamp ( ) ; Long lastTested = ( Long ) fTimestampMapping . get ( type ) ; if ( lastTested != null && currentTimestamp != IResource . NULL_STAMP && currentTimestamp == lastTested . longValue ( ) && ! type . isContainerDirty ( ) ) continue ; try { IType jType = type . resolveType ( scope ) ; if ( jType == null || ! jType . exists ( ) ) { remove ( type ) ; } else { type . setIsModule ( jType . isModule ( ) ) ; fTimestampMapping . put ( type , new Long ( currentTimestamp ) ) ; } } catch ( RubyModelException e ) { remove ( type ) ; } if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; monitor . worked ( ) ; } monitor . done ( ) ; fNeedsConsistencyCheck = false ; } private void doShutdown ( ) { RubyCore . removeElementChangedListener ( fDeltaListener ) ; save ( ) ; } protected Object createFromElement ( Element type ) { String name = type . getAttribute ( NODE_NAME ) ; String pack = type . getAttribute ( NODE_PACKAGE ) ; char [ ] [ ] enclosingNames = getEnclosingNames ( type ) ; String path = type . getAttribute ( NODE_PATH ) ; boolean isModule = false ; try { isModule = Boolean . parseBoolean ( type . getAttribute ( NODE_MODIFIERS ) ) ; } catch ( NumberFormatException e ) { } TypeInfo info = fTypeInfoFactory . create ( pack . toCharArray ( ) , name . toCharArray ( ) , enclosingNames , isModule , path ) ; long timestamp = IResource . NULL_STAMP ; String timestampValue = type . getAttribute ( NODE_TIMESTAMP ) ; if ( timestampValue != null && timestampValue . length ( ) > ) { try { timestamp = Long . parseLong ( timestampValue ) ; } catch ( NumberFormatException e ) { } } if ( timestamp != IResource . NULL_STAMP ) { fTimestampMapping . put ( info , new Long ( timestamp ) ) ; } return info ; } protected void setAttributes ( Object object , Element typeElement ) { TypeInfo type = ( TypeInfo ) object ; typeElement . setAttribute ( NODE_NAME , type . getTypeName ( ) ) ; typeElement . setAttribute ( NODE_PACKAGE , type . getPackageName ( ) ) ; typeElement . setAttribute ( NODE_ENCLOSING_NAMES , type . getEnclosingName ( ) ) ; typeElement . setAttribute ( NODE_PATH , type . getPath ( ) ) ; typeElement . setAttribute ( NODE_MODIFIERS , Boolean . toString ( type . isModule ( ) ) ) ; Long timestamp = ( Long ) fTimestampMapping . get ( type ) ; if ( timestamp == null ) { typeElement . setAttribute ( NODE_TIMESTAMP , Long . toString ( IResource . NULL_STAMP ) ) ; } else { typeElement . setAttribute ( NODE_TIMESTAMP , timestamp . toString ( ) ) ; } } private char [ ] [ ] getEnclosingNames ( Element type ) { String enclosingNames = type . getAttribute ( NODE_ENCLOSING_NAMES ) ; if ( enclosingNames . length ( ) == ) return EMPTY_ENCLOSING_NAMES ; StringTokenizer tokenizer = new StringTokenizer ( enclosingNames , "" ) ; List names = new ArrayList ( ) ; while ( tokenizer . hasMoreTokens ( ) ) { String name = tokenizer . nextToken ( ) ; names . add ( name . toCharArray ( ) ) ; } return ( char [ ] [ ] ) names . toArray ( new char [ names . size ( ) ] [ ] ) ; } } package org . rubypeople . rdt . internal . corext . util ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . corext . util . TypeInfo . TypeInfoAdapter ; import org . rubypeople . rdt . internal . ui . util . StringMatcher ; import org . rubypeople . rdt . ui . dialogs . ITypeInfoFilterExtension ; public class TypeInfoFilter { private static class PatternMatcher { private String fPattern ; private int fMatchKind ; private StringMatcher fStringMatcher ; private static final char END_SYMBOL = '' ; private static final char ANY_STRING = '' ; private static final char BLANK = '' ; public PatternMatcher ( String pattern , boolean ignoreCase ) { this ( pattern , SearchPattern . R_EXACT_MATCH | SearchPattern . R_PREFIX_MATCH | SearchPattern . R_PATTERN_MATCH | SearchPattern . R_CAMELCASE_MATCH ) ; } public PatternMatcher ( String pattern , int allowedModes ) { initializePatternAndMatchKind ( pattern ) ; fMatchKind = fMatchKind & allowedModes ; if ( fMatchKind == SearchPattern . R_PATTERN_MATCH ) { fStringMatcher = new StringMatcher ( fPattern , true , false ) ; } } public String getPattern ( ) { return fPattern ; } public int getMatchKind ( ) { return fMatchKind ; } public boolean matches ( String text ) { switch ( fMatchKind ) { case SearchPattern . R_PATTERN_MATCH : return fStringMatcher . match ( text ) ; case SearchPattern . R_EXACT_MATCH : return fPattern . equalsIgnoreCase ( text ) ; case SearchPattern . R_CAMELCASE_MATCH : if ( SearchPattern . camelCaseMatch ( fPattern , text ) ) { return true ; } default : return Strings . startsWithIgnoreCase ( text , fPattern ) ; } } private void initializePatternAndMatchKind ( String pattern ) { int length = pattern . length ( ) ; if ( length == ) { fMatchKind = SearchPattern . R_EXACT_MATCH ; fPattern = pattern ; return ; } char last = pattern . charAt ( length - ) ; if ( pattern . indexOf ( '' ) != - || pattern . indexOf ( '' ) != - ) { fMatchKind = SearchPattern . R_PATTERN_MATCH ; switch ( last ) { case END_SYMBOL : fPattern = pattern . substring ( , length - ) ; break ; case BLANK : fPattern = pattern . trim ( ) ; break ; case ANY_STRING : fPattern = pattern ; break ; default : fPattern = pattern + ANY_STRING ; } return ; } if ( last == END_SYMBOL ) { fMatchKind = SearchPattern . R_EXACT_MATCH ; fPattern = pattern . substring ( , length - ) ; return ; } if ( last == BLANK ) { fMatchKind = SearchPattern . R_EXACT_MATCH ; fPattern = pattern . trim ( ) ; return ; } if ( SearchUtils . isCamelCasePattern ( pattern ) ) { fMatchKind = SearchPattern . R_CAMELCASE_MATCH ; fPattern = pattern ; return ; } fMatchKind = SearchPattern . R_PREFIX_MATCH ; fPattern = pattern ; } } private String fText ; private IRubySearchScope fSearchScope ; private boolean fIsWorkspaceScope ; private int fElementKind ; private ITypeInfoFilterExtension fFilterExtension ; private TypeInfoAdapter fAdapter = new TypeInfoAdapter ( ) ; private PatternMatcher fNamespaceMatcher ; private PatternMatcher fNameMatcher ; public TypeInfoFilter ( String text , IRubySearchScope scope , int elementKind , ITypeInfoFilterExtension extension ) { fText = text ; fSearchScope = scope ; fIsWorkspaceScope = fSearchScope . equals ( SearchEngine . createWorkspaceScope ( ) ) ; fElementKind = elementKind ; fFilterExtension = extension ; int index = text . lastIndexOf ( "" ) ; if ( index == - ) { fNameMatcher = new PatternMatcher ( text , true ) ; } else { fNamespaceMatcher = new PatternMatcher ( text . substring ( , index ) , true ) ; String name = text . substring ( index + ) ; if ( name . length ( ) == ) name = "" ; fNameMatcher = new PatternMatcher ( name , true ) ; } } public String getText ( ) { return fText ; } public boolean isSubFilter ( String text ) { if ( ! fText . startsWith ( text ) ) return false ; if ( text . endsWith ( "" ) && ! text . equals ( fText ) ) { return false ; } return fText . indexOf ( "" , text . length ( ) ) == - ; } public boolean isCamelCasePattern ( ) { return fNameMatcher . getMatchKind ( ) == SearchPattern . R_CAMELCASE_MATCH ; } public String getPackagePattern ( ) { if ( fNamespaceMatcher == null ) return null ; return fNamespaceMatcher . getPattern ( ) ; } public String getNamePattern ( ) { return fNameMatcher . getPattern ( ) ; } public int getSearchFlags ( ) { if ( fNamespaceMatcher != null ) { int matchKind = fNamespaceMatcher . getMatchKind ( ) ; int nameKind = fNameMatcher . getMatchKind ( ) ; if ( matchKind == SearchPattern . R_CAMELCASE_MATCH || nameKind == SearchPattern . R_CAMELCASE_MATCH ) return SearchPattern . R_CAMELCASE_MATCH ; if ( matchKind == SearchPattern . R_PATTERN_MATCH || nameKind == SearchPattern . R_PATTERN_MATCH ) return SearchPattern . R_PATTERN_MATCH ; if ( matchKind == SearchPattern . R_PREFIX_MATCH || nameKind == SearchPattern . R_PREFIX_MATCH ) return SearchPattern . R_PREFIX_MATCH ; } return fNameMatcher . getMatchKind ( ) ; } public boolean matchesRawNamePattern ( TypeInfo type ) { return Strings . startsWithIgnoreCase ( type . getTypeName ( ) , fNameMatcher . getPattern ( ) ) ; } public boolean matchesCachedResult ( TypeInfo type ) { if ( ! ( matchesNamespace ( type ) && matchesFilterExtension ( type ) ) ) return false ; return matchesName ( type ) ; } public boolean matchesHistoryElement ( TypeInfo type ) { if ( ! ( matchesNamespace ( type ) && matchesModifiers ( type ) && matchesScope ( type ) && matchesFilterExtension ( type ) ) ) return false ; return matchesName ( type ) ; } public boolean matchesFilterExtension ( TypeInfo type ) { if ( fFilterExtension == null ) return true ; fAdapter . setInfo ( type ) ; return fFilterExtension . select ( fAdapter ) ; } private boolean matchesName ( TypeInfo type ) { return fNameMatcher . matches ( type . getTypeName ( ) ) ; } private boolean matchesNamespace ( TypeInfo type ) { if ( fNamespaceMatcher == null ) return true ; return fNamespaceMatcher . matches ( type . getEnclosingName ( ) ) ; } private boolean matchesScope ( TypeInfo type ) { if ( fIsWorkspaceScope ) return true ; return type . isEnclosed ( fSearchScope ) ; } private boolean matchesModifiers ( TypeInfo type ) { if ( fElementKind == IRubySearchConstants . TYPE ) return true ; boolean isModule = type . isModule ( ) ; switch ( fElementKind ) { case IRubySearchConstants . CLASS : return ! isModule ; case IRubySearchConstants . MODULE : return isModule ; } return false ; } } package org . rubypeople . rdt . internal . corext . util ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . ui . dialogs . ITypeInfoRequestor ; public abstract class TypeInfo { public static class TypeInfoAdapter implements ITypeInfoRequestor { private TypeInfo fInfo ; public void setInfo ( TypeInfo info ) { fInfo = info ; } public boolean isModule ( ) { return fInfo . isModule ( ) ; } public String getTypeName ( ) { return fInfo . getTypeName ( ) ; } public String getPackageName ( ) { return fInfo . getPackageName ( ) ; } public String getEnclosingName ( ) { return fInfo . getEnclosingName ( ) ; } } final String fName ; final String fPackage ; final char [ ] [ ] fEnclosingNames ; private boolean fIsModule ; public static final int UNRESOLVABLE_TYPE_INFO = ; public static final int JAR_FILE_ENTRY_TYPE_INFO = ; public static final int IFILE_TYPE_INFO = ; static final char SEPARATOR = '' ; static final char EXTENSION_SEPARATOR = '' ; static final char PACKAGE_PART_SEPARATOR = '' ; static final String EMPTY_STRING = "" ; protected TypeInfo ( String pkg , String name , char [ ] [ ] enclosingTypes , boolean isModule ) { fPackage = pkg ; fName = name ; fIsModule = isModule ; fEnclosingNames = enclosingTypes ; } public int hashCode ( ) { return ( fPackage . hashCode ( ) << ) + fName . hashCode ( ) ; } public abstract int getElementType ( ) ; public abstract String getPath ( ) ; protected abstract IRubyElement getContainer ( IRubySearchScope scope ) throws RubyModelException ; public abstract IPath getPackageFragmentRootPath ( ) ; public abstract String getPackageFragmentRootName ( ) ; public String getTypeName ( ) { return fName ; } public String getPackageName ( ) { return fPackage ; } public boolean isModule ( ) { return fIsModule ; } public boolean isEnclosed ( IRubySearchScope scope ) { return scope . encloses ( getPath ( ) ) ; } public String getEnclosingName ( ) { if ( fEnclosingNames == null || fEnclosingNames . length == ) return EMPTY_STRING ; StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < fEnclosingNames . length ; i ++ ) { if ( i != ) { buf . append ( "" ) ; } buf . append ( fEnclosingNames [ i ] ) ; } return buf . toString ( ) ; } public boolean isInnerType ( ) { return fEnclosingNames != null && fEnclosingNames . length > ; } public String getTypeQualifiedName ( ) { if ( fEnclosingNames != null && fEnclosingNames . length > ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < fEnclosingNames . length ; i ++ ) { buf . append ( fEnclosingNames [ i ] ) ; buf . append ( "" ) ; } buf . append ( fName ) ; return buf . toString ( ) ; } return fName ; } public String getFullyQualifiedName ( ) { StringBuffer buf = new StringBuffer ( ) ; if ( fPackage . length ( ) > ) { buf . append ( fPackage ) ; buf . append ( '' ) ; } if ( fEnclosingNames != null ) { for ( int i = ; i < fEnclosingNames . length ; i ++ ) { buf . append ( fEnclosingNames [ i ] ) ; buf . append ( '' ) ; } } buf . append ( fName ) ; return buf . toString ( ) ; } public String getTypeContainerName ( ) { if ( fEnclosingNames != null && fEnclosingNames . length > ) { StringBuffer buf = new StringBuffer ( ) ; if ( fPackage . length ( ) > ) { buf . append ( fPackage ) ; } for ( int i = ; i < fEnclosingNames . length ; i ++ ) { if ( buf . length ( ) > ) { buf . append ( "" ) ; } buf . append ( fEnclosingNames [ i ] ) ; } return buf . toString ( ) ; } return fPackage ; } public IType resolveType ( IRubySearchScope scope ) throws RubyModelException { IRubyElement elem = getContainer ( scope ) ; if ( elem instanceof IRubyScript ) return RubyModelUtil . findTypeInRubyScript ( ( IRubyScript ) elem , getTypeQualifiedName ( ) ) ; return null ; } protected boolean doEquals ( TypeInfo other ) { return fName . equals ( other . fName ) && fPackage . equals ( other . fPackage ) && CharOperation . equals ( fEnclosingNames , other . fEnclosingNames ) ; } protected static boolean equals ( String s1 , String s2 ) { if ( s1 == null || s2 == null ) return s1 == s2 ; return s1 . equals ( s2 ) ; } public String toString ( ) { StringBuffer buf = new StringBuffer ( ) ; buf . append ( "" ) ; buf . append ( getPath ( ) ) ; buf . append ( "" ) ; buf . append ( fPackage ) ; buf . append ( "" ) ; buf . append ( getEnclosingName ( ) ) ; buf . append ( "" ) ; buf . append ( fName ) ; return buf . toString ( ) ; } public abstract long getContainerTimestamp ( ) ; public abstract boolean isContainerDirty ( ) ; public void setIsModule ( boolean b ) { fIsModule = b ; } } package org . rubypeople . rdt . internal . corext . util ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultLineTracker ; import org . eclipse . jface . text . ILineTracker ; import org . eclipse . jface . text . IRegion ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . formatter . IndentManipulation ; public class Strings { public static int computeIndentUnits ( String line , IRubyProject project ) { return computeIndentUnits ( line , CodeFormatterUtil . getTabWidth ( project ) , CodeFormatterUtil . getIndentWidth ( project ) ) ; } public static int computeIndentUnits ( String line , int tabWidth , int indentWidth ) { if ( indentWidth == ) return - ; int visualLength = measureIndentLength ( line , tabWidth ) ; return visualLength / indentWidth ; } public static int measureIndentLength ( CharSequence line , int tabSize ) { int length = ; int max = line . length ( ) ; for ( int i = ; i < max ; i ++ ) { char ch = line . charAt ( i ) ; if ( ch == '' ) { int reminder = length % tabSize ; length += tabSize - reminder ; } else if ( isIndentChar ( ch ) ) { length ++ ; } else { return length ; } } return length ; } public static boolean isIndentChar ( char ch ) { return Character . isWhitespace ( ch ) && ! isLineDelimiterChar ( ch ) ; } public static boolean isLineDelimiterChar ( char ch ) { return ch == '' || ch == '' ; } public static boolean containsOnlyWhitespaces ( String s ) { int size = s . length ( ) ; for ( int i = ; i < size ; i ++ ) { if ( ! Character . isWhitespace ( s . charAt ( i ) ) ) return false ; } return true ; } public static boolean equals ( String s , char [ ] c ) { if ( s . length ( ) != c . length ) return false ; for ( int i = c . length ; -- i >= ; ) if ( s . charAt ( i ) != c [ i ] ) return false ; return true ; } public static boolean startsWithIgnoreCase ( String text , String prefix ) { int textLength = text . length ( ) ; int prefixLength = prefix . length ( ) ; if ( textLength < prefixLength ) return false ; for ( int i = prefixLength - ; i >= ; i -- ) { if ( Character . toLowerCase ( prefix . charAt ( i ) ) != Character . toLowerCase ( text . charAt ( i ) ) ) return false ; } return true ; } public static boolean isLowerCase ( char ch ) { return Character . toLowerCase ( ch ) == ch ; } public static String removeMnemonicIndicator ( String string ) { int length = string . length ( ) ; StringBuffer result = new StringBuffer ( length ) ; char lastChar = '' ; for ( int i = ; i < length ; i ++ ) { char ch = string . charAt ( i ) ; if ( ch != '' || lastChar == '' ) { result . append ( ch ) ; } lastChar = ch ; } return result . toString ( ) ; } public static String [ ] convertIntoLines ( String input ) { try { ILineTracker tracker = new DefaultLineTracker ( ) ; tracker . set ( input ) ; int size = tracker . getNumberOfLines ( ) ; String result [ ] = new String [ size ] ; for ( int i = ; i < size ; i ++ ) { IRegion region = tracker . getLineInformation ( i ) ; int offset = region . getOffset ( ) ; result [ i ] = input . substring ( offset , offset + region . getLength ( ) ) ; } return result ; } catch ( BadLocationException e ) { return null ; } } public static void trimIndentation ( String [ ] lines , IRubyProject project ) { trimIndentation ( lines , CodeFormatterUtil . getTabWidth ( project ) , CodeFormatterUtil . getIndentWidth ( project ) , true ) ; } public static void trimIndentation ( String [ ] lines , int tabWidth , int indentWidth , boolean considerFirstLine ) { String [ ] toDo = new String [ lines . length ] ; int minIndent = Integer . MAX_VALUE ; for ( int i = considerFirstLine ? : ; i < lines . length ; i ++ ) { String line = lines [ i ] ; if ( containsOnlyWhitespaces ( line ) ) continue ; toDo [ i ] = line ; int indent = computeIndentUnits ( line , tabWidth , indentWidth ) ; if ( indent < minIndent ) { minIndent = indent ; } } if ( minIndent > ) { for ( int i = considerFirstLine ? : ; i < toDo . length ; i ++ ) { String s = toDo [ i ] ; if ( s != null ) lines [ i ] = trimIndent ( s , minIndent , tabWidth , indentWidth ) ; else { String line = lines [ i ] ; int indent = computeIndentUnits ( line , tabWidth , indentWidth ) ; if ( indent > minIndent ) lines [ i ] = trimIndent ( line , minIndent , tabWidth , indentWidth ) ; else lines [ i ] = trimLeadingTabsAndSpaces ( line ) ; } } } } public static String trimIndent ( String line , int indentsToRemove , int tabWidth , int indentWidth ) { return IndentManipulation . trimIndent ( line , indentsToRemove , tabWidth , indentWidth ) ; } public static String trimLeadingTabsAndSpaces ( String line ) { int size = line . length ( ) ; int start = size ; for ( int i = ; i < size ; i ++ ) { char c = line . charAt ( i ) ; if ( ! IndentManipulation . isIndentChar ( c ) ) { start = i ; break ; } } if ( start == ) return line ; else if ( start == size ) return "" ; else return line . substring ( start ) ; } public static String concatenate ( String [ ] lines , String delimiter ) { StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < lines . length ; i ++ ) { if ( i > ) buffer . append ( delimiter ) ; buffer . append ( lines [ i ] ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . corext . util ; import java . util . LinkedHashMap ; public class LRUMap extends LinkedHashMap { private static final long serialVersionUID = ; private final int fMaxSize ; public LRUMap ( int maxSize ) { super ( maxSize , , true ) ; fMaxSize = maxSize ; } protected boolean removeEldestEntry ( java . util . Map . Entry eldest ) { return size ( ) > fMaxSize ; } } package org . rubypeople . rdt . internal . corext . util ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . IRubySearchScope ; public class UnresolvableTypeInfo extends TypeInfo { private final String fPath ; public UnresolvableTypeInfo ( String pkg , String name , char [ ] [ ] enclosingTypes , boolean isModule , String path ) { super ( pkg , name , enclosingTypes , isModule ) ; fPath = path ; } public boolean equals ( Object obj ) { if ( ! UnresolvableTypeInfo . class . equals ( obj . getClass ( ) ) ) return false ; UnresolvableTypeInfo other = ( UnresolvableTypeInfo ) obj ; return doEquals ( other ) && fPath . equals ( other . fPath ) ; } public int getElementType ( ) { return TypeInfo . UNRESOLVABLE_TYPE_INFO ; } public String getPath ( ) { return fPath ; } public IPath getPackageFragmentRootPath ( ) { return new Path ( fPath ) ; } public String getPackageFragmentRootName ( ) { return fPath ; } protected IRubyElement getContainer ( IRubySearchScope scope ) { return null ; } public long getContainerTimestamp ( ) { return IResource . NULL_STAMP ; } public boolean isContainerDirty ( ) { return false ; } } package org . rubypeople . rdt . internal . corext . util ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . operation . ModalContext ; import org . eclipse . swt . custom . BusyIndicator ; public class BusyIndicatorRunnableContext implements IRunnableContext { private static class BusyRunnable implements Runnable { private static class ThreadContext extends Thread { IRunnableWithProgress fRunnable ; Throwable fThrowable ; public ThreadContext ( IRunnableWithProgress runnable ) { this ( runnable , "" ) ; } protected ThreadContext ( IRunnableWithProgress runnable , String name ) { super ( name ) ; fRunnable = runnable ; } public void run ( ) { try { fRunnable . run ( new NullProgressMonitor ( ) ) ; } catch ( InvocationTargetException e ) { fThrowable = e ; } catch ( InterruptedException e ) { fThrowable = e ; } catch ( ThreadDeath e ) { fThrowable = e ; throw e ; } catch ( RuntimeException e ) { fThrowable = e ; } catch ( Error e ) { fThrowable = e ; } } void sync ( ) { try { join ( ) ; } catch ( InterruptedException e ) { } } } public Throwable fThrowable ; private boolean fFork ; private IRunnableWithProgress fRunnable ; public BusyRunnable ( boolean fork , IRunnableWithProgress runnable ) { fFork = fork ; fRunnable = runnable ; } public void run ( ) { try { internalRun ( fFork , fRunnable ) ; } catch ( InvocationTargetException e ) { fThrowable = e ; } catch ( InterruptedException e ) { fThrowable = e ; } } private void internalRun ( boolean fork , final IRunnableWithProgress runnable ) throws InvocationTargetException , InterruptedException { Thread thread = Thread . currentThread ( ) ; if ( thread instanceof ThreadContext || ModalContext . isModalContextThread ( thread ) ) fork = false ; if ( fork ) { final ThreadContext t = new ThreadContext ( runnable ) ; t . start ( ) ; t . sync ( ) ; Throwable throwable = t . fThrowable ; if ( throwable != null ) { if ( throwable instanceof InvocationTargetException ) { throw ( InvocationTargetException ) throwable ; } else if ( throwable instanceof InterruptedException ) { throw ( InterruptedException ) throwable ; } else if ( throwable instanceof OperationCanceledException ) { throw new InterruptedException ( ) ; } else { throw new InvocationTargetException ( throwable ) ; } } } else { try { runnable . run ( new NullProgressMonitor ( ) ) ; } catch ( OperationCanceledException e ) { throw new InterruptedException ( ) ; } } } } public void run ( boolean fork , boolean cancelable , IRunnableWithProgress runnable ) throws InvocationTargetException , InterruptedException { BusyRunnable busyRunnable = new BusyRunnable ( fork , runnable ) ; BusyIndicator . showWhile ( null , busyRunnable ) ; Throwable throwable = busyRunnable . fThrowable ; if ( throwable instanceof InvocationTargetException ) { throw ( InvocationTargetException ) throwable ; } else if ( throwable instanceof InterruptedException ) { throw ( InterruptedException ) throwable ; } } } package org . rubypeople . rdt . internal . corext . util ; import java . net . URI ; import org . eclipse . core . filebuffers . FileBuffers ; import org . eclipse . core . filebuffers . ITextFileBuffer ; import org . eclipse . core . filebuffers . ITextFileBufferManager ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileInfo ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . search . IRubySearchScope ; public class IFileTypeInfo extends TypeInfo { private final String fProject ; private final String fFolder ; private final String fFile ; private final String fExtension ; public IFileTypeInfo ( String pkg , String name , char [ ] [ ] enclosingTypes , boolean isModule , String project , String sourceFolder , String file , String extension ) { super ( pkg , name , enclosingTypes , isModule ) ; fProject = project ; fFolder = sourceFolder ; fFile = file ; fExtension = extension ; } public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( ! IFileTypeInfo . class . equals ( obj . getClass ( ) ) ) return false ; IFileTypeInfo other = ( IFileTypeInfo ) obj ; return doEquals ( other ) && fProject . equals ( other . fProject ) && equals ( fFolder , other . fFolder ) && fFile . equals ( other . fFile ) && fExtension . equals ( other . fExtension ) ; } public int getElementType ( ) { return TypeInfo . IFILE_TYPE_INFO ; } protected IRubyElement getContainer ( IRubySearchScope scope ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IPath path = new Path ( getPath ( ) ) ; IResource resource = root . findMember ( path ) ; if ( resource != null ) { IRubyElement elem = RubyCore . create ( resource ) ; if ( elem != null && elem . exists ( ) ) { return elem ; } } return null ; } public IPath getPackageFragmentRootPath ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( TypeInfo . SEPARATOR ) ; buffer . append ( fProject ) ; if ( fFolder != null && fFolder . length ( ) > ) { buffer . append ( TypeInfo . SEPARATOR ) ; buffer . append ( fFolder ) ; } return new Path ( buffer . toString ( ) ) ; } public String getPackageFragmentRootName ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( fProject ) ; if ( fFolder != null && fFolder . length ( ) > ) { buffer . append ( TypeInfo . SEPARATOR ) ; buffer . append ( fFolder ) ; } return buffer . toString ( ) ; } public String getPath ( ) { StringBuffer result = new StringBuffer ( ) ; result . append ( TypeInfo . SEPARATOR ) ; result . append ( fProject ) ; result . append ( TypeInfo . SEPARATOR ) ; if ( fFolder != null && fFolder . length ( ) > ) { result . append ( fFolder ) ; result . append ( TypeInfo . SEPARATOR ) ; } if ( fPackage != null && fPackage . length ( ) > ) { result . append ( fPackage . replace ( TypeInfo . PACKAGE_PART_SEPARATOR , TypeInfo . SEPARATOR ) ) ; result . append ( TypeInfo . SEPARATOR ) ; } result . append ( fFile ) ; result . append ( '' ) ; result . append ( fExtension ) ; return result . toString ( ) ; } public String getProject ( ) { return fProject ; } public String getFolder ( ) { return fFolder ; } public String getFileName ( ) { return fFile ; } public String getExtension ( ) { return fExtension ; } public long getContainerTimestamp ( ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IPath path = new Path ( getPath ( ) ) ; IResource resource = root . findMember ( path ) ; if ( resource != null ) { URI location = resource . getLocationURI ( ) ; if ( location != null ) { try { IFileInfo info = EFS . getStore ( location ) . fetchInfo ( ) ; if ( info . exists ( ) ) { IRubyElement element = RubyCore . create ( resource ) ; if ( element != null && element . exists ( ) ) return info . getLastModified ( ) ; } } catch ( CoreException e ) { } } } return IResource . NULL_STAMP ; } public boolean isContainerDirty ( ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IPath path = new Path ( getPath ( ) ) ; IResource resource = root . findMember ( path ) ; ITextFileBufferManager manager = FileBuffers . getTextFileBufferManager ( ) ; ITextFileBuffer textFileBuffer = manager . getTextFileBuffer ( resource . getFullPath ( ) ) ; if ( textFileBuffer != null ) { return textFileBuffer . isDirty ( ) ; } return false ; } } package org . rubypeople . rdt . internal . corext . util ; import java . io . File ; import java . net . URI ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceStatus ; import org . eclipse . core . resources . ResourceAttributes ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . internal . corext . CorextMessages ; import org . rubypeople . rdt . internal . ui . IRubyStatusConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIStatus ; public class Resources { private Resources ( ) { } public static IStatus checkInSync ( IResource resource ) { return checkInSync ( new IResource [ ] { resource } ) ; } public static IStatus checkInSync ( IResource [ ] resources ) { IStatus result = null ; for ( int i = ; i < resources . length ; i ++ ) { IResource resource = resources [ i ] ; if ( ! resource . isSynchronized ( IResource . DEPTH_INFINITE ) ) { result = addOutOfSync ( result , resource ) ; } } if ( result != null ) return result ; return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } public static IStatus makeCommittable ( IResource resource , Object context ) { return makeCommittable ( new IResource [ ] { resource } , context ) ; } public static IStatus makeCommittable ( IResource [ ] resources , Object context ) { List readOnlyFiles = new ArrayList ( ) ; for ( int i = ; i < resources . length ; i ++ ) { IResource resource = resources [ i ] ; if ( resource . getType ( ) == IResource . FILE && isReadOnly ( resource ) ) readOnlyFiles . add ( resource ) ; } if ( readOnlyFiles . size ( ) == ) return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; Map oldTimeStamps = createModificationStampMap ( readOnlyFiles ) ; IStatus status = ResourcesPlugin . getWorkspace ( ) . validateEdit ( ( IFile [ ] ) readOnlyFiles . toArray ( new IFile [ readOnlyFiles . size ( ) ] ) , context ) ; if ( ! status . isOK ( ) ) return status ; IStatus modified = null ; Map newTimeStamps = createModificationStampMap ( readOnlyFiles ) ; for ( Iterator iter = oldTimeStamps . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { IFile file = ( IFile ) iter . next ( ) ; if ( ! oldTimeStamps . get ( file ) . equals ( newTimeStamps . get ( file ) ) ) modified = addModified ( modified , file ) ; } if ( modified != null ) return modified ; return new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , IStatus . OK , "" , null ) ; } private static Map createModificationStampMap ( List files ) { Map map = new HashMap ( ) ; for ( Iterator iter = files . iterator ( ) ; iter . hasNext ( ) ; ) { IFile file = ( IFile ) iter . next ( ) ; map . put ( file , new Long ( file . getModificationStamp ( ) ) ) ; } return map ; } private static IStatus addModified ( IStatus status , IFile file ) { IStatus entry = RubyUIStatus . createError ( IRubyStatusConstants . VALIDATE_EDIT_CHANGED_CONTENT , Messages . format ( CorextMessages . Resources_fileModified , file . getFullPath ( ) . toString ( ) ) , null ) ; if ( status == null ) { return entry ; } else if ( status . isMultiStatus ( ) ) { ( ( MultiStatus ) status ) . add ( entry ) ; return status ; } else { MultiStatus result = new MultiStatus ( RubyPlugin . getPluginId ( ) , IRubyStatusConstants . VALIDATE_EDIT_CHANGED_CONTENT , CorextMessages . Resources_modifiedResources , null ) ; result . add ( status ) ; result . add ( entry ) ; return result ; } } private static IStatus addOutOfSync ( IStatus status , IResource resource ) { IStatus entry = new Status ( IStatus . ERROR , ResourcesPlugin . PI_RESOURCES , IResourceStatus . OUT_OF_SYNC_LOCAL , Messages . format ( CorextMessages . Resources_outOfSync , resource . getFullPath ( ) . toString ( ) ) , null ) ; if ( status == null ) { return entry ; } else if ( status . isMultiStatus ( ) ) { ( ( MultiStatus ) status ) . add ( entry ) ; return status ; } else { MultiStatus result = new MultiStatus ( ResourcesPlugin . PI_RESOURCES , IResourceStatus . OUT_OF_SYNC_LOCAL , CorextMessages . Resources_outOfSyncResources , null ) ; result . add ( status ) ; result . add ( entry ) ; return result ; } } public static String [ ] getLocationOSStrings ( IResource [ ] resources ) { List result = new ArrayList ( resources . length ) ; for ( int i = ; i < resources . length ; i ++ ) { IPath location = resources [ i ] . getLocation ( ) ; if ( location != null ) result . add ( location . toOSString ( ) ) ; } return ( String [ ] ) result . toArray ( new String [ result . size ( ) ] ) ; } public static String getLocationString ( IResource resource ) { URI uri = resource . getLocationURI ( ) ; if ( uri == null ) return null ; return EFS . SCHEME_FILE . equalsIgnoreCase ( uri . getScheme ( ) ) ? new File ( uri ) . getAbsolutePath ( ) : uri . toString ( ) ; } public static boolean isReadOnly ( IResource resource ) { ResourceAttributes resourceAttributes = resource . getResourceAttributes ( ) ; if ( resourceAttributes == null ) return false ; return resourceAttributes . isReadOnly ( ) ; } static void setReadOnly ( IResource resource , boolean readOnly ) { ResourceAttributes resourceAttributes = resource . getResourceAttributes ( ) ; if ( resourceAttributes == null ) return ; resourceAttributes . setReadOnly ( readOnly ) ; try { resource . setResourceAttributes ( resourceAttributes ) ; } catch ( CoreException e ) { RubyPlugin . log ( e ) ; } } } package org . rubypeople . rdt . internal . corext . util ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . ITypeHierarchyChangedListener ; import org . rubypeople . rdt . core . RubyModelException ; public class SuperTypeHierarchyCache { private static class HierarchyCacheEntry implements ITypeHierarchyChangedListener { private ITypeHierarchy fTypeHierarchy ; private long fLastAccess ; public HierarchyCacheEntry ( ITypeHierarchy hierarchy ) { fTypeHierarchy = hierarchy ; fTypeHierarchy . addTypeHierarchyChangedListener ( this ) ; markAsAccessed ( ) ; } public void typeHierarchyChanged ( ITypeHierarchy typeHierarchy ) { removeHierarchyEntryFromCache ( this ) ; } public ITypeHierarchy getTypeHierarchy ( ) { return fTypeHierarchy ; } public void markAsAccessed ( ) { fLastAccess = System . currentTimeMillis ( ) ; } public long getLastAccess ( ) { return fLastAccess ; } public void dispose ( ) { fTypeHierarchy . removeTypeHierarchyChangedListener ( this ) ; fTypeHierarchy = null ; } public String toString ( ) { return "" + fTypeHierarchy . getType ( ) . getElementName ( ) ; } } private static final int CACHE_SIZE = ; private static ArrayList fgHierarchyCache = new ArrayList ( CACHE_SIZE ) ; private static Map fgMethodOverrideTesterCache = new LRUMap ( CACHE_SIZE ) ; private static int fgCacheHits = ; private static int fgCacheMisses = ; public static ITypeHierarchy getTypeHierarchy ( IType type ) throws RubyModelException { return getTypeHierarchy ( type , null ) ; } public static MethodOverrideTester getMethodOverrideTester ( IType type ) throws RubyModelException { MethodOverrideTester test = null ; synchronized ( fgMethodOverrideTesterCache ) { test = ( MethodOverrideTester ) fgMethodOverrideTesterCache . get ( type ) ; } if ( test == null ) { ITypeHierarchy hierarchy = getTypeHierarchy ( type ) ; synchronized ( fgMethodOverrideTesterCache ) { test = ( MethodOverrideTester ) fgMethodOverrideTesterCache . get ( type ) ; if ( test == null ) { test = new MethodOverrideTester ( type , hierarchy ) ; fgMethodOverrideTesterCache . put ( type , test ) ; } } } return test ; } private static void removeMethodOverrideTester ( ITypeHierarchy hierarchy ) { synchronized ( fgMethodOverrideTesterCache ) { for ( Iterator iter = fgMethodOverrideTesterCache . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { MethodOverrideTester curr = ( MethodOverrideTester ) iter . next ( ) ; if ( curr . getTypeHierarchy ( ) . equals ( hierarchy ) ) { iter . remove ( ) ; } } } } public static ITypeHierarchy getTypeHierarchy ( IType type , IProgressMonitor progressMonitor ) throws RubyModelException { ITypeHierarchy hierarchy = findTypeHierarchyInCache ( type ) ; if ( hierarchy == null ) { fgCacheMisses ++ ; hierarchy = type . newSupertypeHierarchy ( progressMonitor ) ; addTypeHierarchyToCache ( hierarchy ) ; } else { fgCacheHits ++ ; } return hierarchy ; } private static void addTypeHierarchyToCache ( ITypeHierarchy hierarchy ) { if ( hierarchy == null ) return ; synchronized ( fgHierarchyCache ) { int nEntries = fgHierarchyCache . size ( ) ; if ( nEntries >= CACHE_SIZE ) { HierarchyCacheEntry oldest = null ; ArrayList obsoleteHierarchies = new ArrayList ( CACHE_SIZE ) ; for ( int i = ; i < nEntries ; i ++ ) { HierarchyCacheEntry entry = ( HierarchyCacheEntry ) fgHierarchyCache . get ( i ) ; ITypeHierarchy curr = entry . getTypeHierarchy ( ) ; if ( ! curr . exists ( ) || hierarchy . contains ( curr . getType ( ) ) ) { obsoleteHierarchies . add ( entry ) ; } else { if ( oldest == null || entry . getLastAccess ( ) < oldest . getLastAccess ( ) ) { oldest = entry ; } } } if ( ! obsoleteHierarchies . isEmpty ( ) ) { for ( int i = ; i < obsoleteHierarchies . size ( ) ; i ++ ) { removeHierarchyEntryFromCache ( ( HierarchyCacheEntry ) obsoleteHierarchies . get ( i ) ) ; } } else if ( oldest != null ) { removeHierarchyEntryFromCache ( oldest ) ; } } HierarchyCacheEntry newEntry = new HierarchyCacheEntry ( hierarchy ) ; fgHierarchyCache . add ( newEntry ) ; } } public static boolean hasInCache ( IType type ) { return findTypeHierarchyInCache ( type ) != null ; } private static ITypeHierarchy findTypeHierarchyInCache ( IType type ) { synchronized ( fgHierarchyCache ) { for ( int i = fgHierarchyCache . size ( ) - ; i >= ; i -- ) { HierarchyCacheEntry curr = ( HierarchyCacheEntry ) fgHierarchyCache . get ( i ) ; ITypeHierarchy hierarchy = curr . getTypeHierarchy ( ) ; if ( ! hierarchy . exists ( ) ) { removeHierarchyEntryFromCache ( curr ) ; } else { if ( hierarchy . contains ( type ) ) { curr . markAsAccessed ( ) ; return hierarchy ; } } } } return null ; } private static void removeHierarchyEntryFromCache ( HierarchyCacheEntry entry ) { synchronized ( fgHierarchyCache ) { removeMethodOverrideTester ( entry . getTypeHierarchy ( ) ) ; entry . dispose ( ) ; fgHierarchyCache . remove ( entry ) ; } } public static int getCacheHits ( ) { return fgCacheHits ; } public static int getCacheMisses ( ) { return fgCacheMisses ; } } package org . rubypeople . rdt . internal . corext . util ; import java . util . HashMap ; import java . util . Map ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; public class MethodOverrideTester { private static class Substitutions { public static final Substitutions EMPTY_SUBST = new Substitutions ( ) ; private HashMap fMap ; public Substitutions ( ) { fMap = null ; } public void addSubstitution ( String typeVariable , String substitution , String erasure ) { if ( fMap == null ) { fMap = new HashMap ( ) ; } fMap . put ( typeVariable , new String [ ] { substitution , erasure } ) ; } private String [ ] getSubstArray ( String typeVariable ) { if ( fMap != null ) { return ( String [ ] ) fMap . get ( typeVariable ) ; } return null ; } public String getSubstitution ( String typeVariable ) { String [ ] subst = getSubstArray ( typeVariable ) ; if ( subst != null ) { return subst [ ] ; } return null ; } public String getErasure ( String typeVariable ) { String [ ] subst = getSubstArray ( typeVariable ) ; if ( subst != null ) { return subst [ ] ; } return null ; } } private final IType fFocusType ; private final ITypeHierarchy fHierarchy ; private Map fMethodSubstitutions ; private Map fTypeVariableSubstitutions ; public MethodOverrideTester ( IType focusType , ITypeHierarchy hierarchy ) { fFocusType = focusType ; fHierarchy = hierarchy ; fTypeVariableSubstitutions = null ; fMethodSubstitutions = null ; } public IType getFocusType ( ) { return fFocusType ; } public ITypeHierarchy getTypeHierarchy ( ) { return fHierarchy ; } public IMethod findDeclaringMethod ( IMethod overriding , boolean testVisibility ) throws RubyModelException { IMethod result = null ; IMethod overridden = findOverriddenMethod ( overriding , testVisibility ) ; while ( overridden != null ) { result = overridden ; overridden = findOverriddenMethod ( result , testVisibility ) ; } return result ; } public IMethod findOverriddenMethod ( IMethod overriding , boolean testVisibility ) throws RubyModelException { if ( overriding . getVisibility ( ) == IMethod . PRIVATE || overriding . isSingleton ( ) || overriding . isConstructor ( ) ) { return null ; } IType type = overriding . getDeclaringType ( ) ; IType superClass = fHierarchy . getSuperclass ( type ) ; if ( superClass != null ) { IMethod res = findOverriddenMethodInHierarchy ( superClass , overriding ) ; if ( res != null && res . getVisibility ( ) != IMethod . PRIVATE ) { if ( ! testVisibility || RubyModelUtil . isVisibleInHierarchy ( res , type . getSourceFolder ( ) ) ) { return res ; } } } if ( ! overriding . isConstructor ( ) ) { IType [ ] interfaces = fHierarchy . getSuperModules ( type ) ; for ( int i = ; i < interfaces . length ; i ++ ) { IMethod res = findOverriddenMethodInHierarchy ( interfaces [ i ] , overriding ) ; if ( res != null ) { return res ; } } } return null ; } public IMethod findOverriddenMethodInHierarchy ( IType type , IMethod overriding ) throws RubyModelException { IMethod method = findOverriddenMethodInType ( type , overriding ) ; if ( method != null ) { return method ; } IType superClass = fHierarchy . getSuperclass ( type ) ; if ( superClass != null ) { IMethod res = findOverriddenMethodInHierarchy ( superClass , overriding ) ; if ( res != null ) { return res ; } } if ( ! overriding . isConstructor ( ) ) { IType [ ] superInterfaces = fHierarchy . getSuperModules ( type ) ; for ( int i = ; i < superInterfaces . length ; i ++ ) { IMethod res = findOverriddenMethodInHierarchy ( superInterfaces [ i ] , overriding ) ; if ( res != null ) { return res ; } } } return method ; } public IMethod findOverriddenMethodInType ( IType overriddenType , IMethod overriding ) throws RubyModelException { IMethod [ ] overriddenMethods = overriddenType . getMethods ( ) ; for ( int i = ; i < overriddenMethods . length ; i ++ ) { if ( isSubsignature ( overriding , overriddenMethods [ i ] ) ) { return overriddenMethods [ i ] ; } } return null ; } public IMethod findOverridingMethodInType ( IType overridingType , IMethod overridden ) throws RubyModelException { IMethod [ ] overridingMethods = overridingType . getMethods ( ) ; for ( int i = ; i < overridingMethods . length ; i ++ ) { if ( isSubsignature ( overridingMethods [ i ] , overridden ) ) { return overridingMethods [ i ] ; } } return null ; } public boolean isSubsignature ( IMethod overriding , IMethod overridden ) throws RubyModelException { if ( ! overridden . getElementName ( ) . equals ( overriding . getElementName ( ) ) ) { return false ; } int nParameters = overridden . getNumberOfParameters ( ) ; if ( nParameters != overriding . getNumberOfParameters ( ) ) { return false ; } return nParameters == ; } } package org . rubypeople . rdt . internal . corext . util ; import java . io . File ; import java . net . URI ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileInfo ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; public class ExternalFileTypeInfo extends TypeInfo { private final String fPath ; public ExternalFileTypeInfo ( String pkg , String name , char [ ] [ ] enclosingTypes , boolean isModule , String path ) { super ( pkg , name , enclosingTypes , isModule ) ; fPath = path ; } public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( ! ExternalFileTypeInfo . class . equals ( obj . getClass ( ) ) ) return false ; ExternalFileTypeInfo other = ( ExternalFileTypeInfo ) obj ; return doEquals ( other ) && fPath . equals ( other . fPath ) ; } public int getElementType ( ) { return TypeInfo . JAR_FILE_ENTRY_TYPE_INFO ; } protected IRubyElement getContainer ( IRubySearchScope scope ) throws RubyModelException { IRubyModel jmodel = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; IPath [ ] enclosedPaths = scope . enclosingProjectsAndJars ( ) ; IPath filePath = new Path ( fPath ) ; for ( int i = ; i < enclosedPaths . length ; i ++ ) { IPath curr = enclosedPaths [ i ] ; if ( curr . segmentCount ( ) == ) { IRubyProject jproject = jmodel . getRubyProject ( curr . segment ( ) ) ; ISourceFolderRoot [ ] roots = jproject . getSourceFolderRoots ( ) ; for ( int j = ; j < roots . length ; j ++ ) { ISourceFolderRoot root = roots [ j ] ; if ( root . isExternal ( ) && root . getPath ( ) . isPrefixOf ( filePath ) ) { IPath relative = filePath . removeFirstSegments ( root . getPath ( ) . segmentCount ( ) ) ; return findElementInRoot ( root , relative ) ; } } } } List paths = Arrays . asList ( enclosedPaths ) ; IRubyProject [ ] projects = jmodel . getRubyProjects ( ) ; for ( int i = ; i < projects . length ; i ++ ) { IRubyProject jproject = projects [ i ] ; if ( ! paths . contains ( jproject . getPath ( ) ) ) { ISourceFolderRoot [ ] roots = jproject . getSourceFolderRoots ( ) ; for ( int j = ; j < roots . length ; j ++ ) { ISourceFolderRoot root = roots [ j ] ; if ( root . isExternal ( ) && root . getPath ( ) . isPrefixOf ( filePath ) ) { IPath relative = filePath . removeFirstSegments ( root . getPath ( ) . segmentCount ( ) ) ; return findElementInRoot ( root , relative ) ; } } } } return null ; } private IRubyElement findElementInRoot ( ISourceFolderRoot root , IPath relative ) { IRubyElement res ; ISourceFolder frag = root . getSourceFolder ( relative . removeLastSegments ( ) . segments ( ) ) ; String extension = getExtension ( ) ; String fullName = getFileName ( ) + '' + extension ; if ( RubyCore . isRubyLikeFileName ( fullName ) ) { res = frag . getRubyScript ( fullName ) ; } else { return null ; } if ( res . exists ( ) ) { return res ; } return null ; } private String getFileName ( ) { String name = new File ( fPath ) . getName ( ) ; return name . substring ( , name . lastIndexOf ( '' ) ) ; } private String getExtension ( ) { String name = new File ( fPath ) . getName ( ) ; return name . substring ( name . lastIndexOf ( '' ) + ) ; } public IPath getPackageFragmentRootPath ( ) { return new Path ( fPath ) ; } public String getPackageFragmentRootName ( ) { return fPath ; } public String getPath ( ) { return fPath ; } public long getContainerTimestamp ( ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IPath path = new Path ( fPath ) ; IResource resource = root . findMember ( path ) ; IFileInfo info = null ; IRubyElement element = null ; if ( resource != null && resource . exists ( ) ) { URI location = resource . getLocationURI ( ) ; if ( location != null ) { try { info = EFS . getStore ( location ) . fetchInfo ( ) ; if ( info . exists ( ) ) { element = RubyCore . create ( resource ) ; if ( element != null && ! element . exists ( ) ) element = null ; } } catch ( CoreException e ) { } } } else { info = EFS . getLocalFileSystem ( ) . getStore ( Path . fromOSString ( fPath ) ) . fetchInfo ( ) ; if ( info . exists ( ) ) { element = getPackageFragementRootForExternalJar ( ) ; } } if ( info != null && info . exists ( ) && element != null ) { return info . getLastModified ( ) ; } return IResource . NULL_STAMP ; } public boolean isContainerDirty ( ) { return false ; } private void getElementPath ( StringBuffer result ) { String pack = getPackageName ( ) ; if ( pack != null && pack . length ( ) > ) { result . append ( pack . replace ( TypeInfo . PACKAGE_PART_SEPARATOR , TypeInfo . SEPARATOR ) ) ; result . append ( TypeInfo . SEPARATOR ) ; } result . append ( getFileName ( ) ) ; result . append ( '' ) ; result . append ( getExtension ( ) ) ; } private ISourceFolderRoot getPackageFragementRootForExternalJar ( ) { try { IRubyModel jmodel = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; IRubyProject [ ] projects = jmodel . getRubyProjects ( ) ; for ( int i = ; i < projects . length ; i ++ ) { IRubyProject project = projects [ i ] ; ISourceFolderRoot root = project . getSourceFolderRoot ( fPath ) ; if ( project . isOnLoadpath ( root ) ) return root ; } } catch ( RubyModelException e ) { } return null ; } } package org . rubypeople . rdt . internal . corext . util ; import java . util . Arrays ; import java . util . Comparator ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; public class TypeInfoFactory { private String [ ] fProjects ; private TypeInfo fLast ; private char [ ] fBuffer ; private static final String RUBY = "" ; public TypeInfoFactory ( ) { super ( ) ; fProjects = getProjectList ( ) ; fLast = null ; fBuffer = new char [ ] ; } public TypeInfo create ( char [ ] packageName , char [ ] typeName , char [ ] [ ] enclosingName , boolean isModule , String path ) { path = new Path ( path ) . toPortableString ( ) ; String pn = getPackageName ( packageName ) ; String tn = new String ( typeName ) ; TypeInfo result = null ; String project = getProject ( path ) ; if ( project != null ) { result = createIFileTypeInfo ( pn , tn , enclosingName , isModule , path , getIFileTypeInfo ( fLast ) , project ) ; } else { result = createExternalFileTypeInfo ( pn , tn , enclosingName , isModule , path ) ; } if ( result == null ) { result = new UnresolvableTypeInfo ( pn , tn , enclosingName , isModule , path ) ; } else { fLast = result ; } return result ; } private TypeInfo createExternalFileTypeInfo ( String packageName , String typeName , char [ ] [ ] enclosingName , boolean isModule , String path ) { return new ExternalFileTypeInfo ( packageName , typeName , enclosingName , isModule , path ) ; } private static IFileTypeInfo getIFileTypeInfo ( TypeInfo info ) { if ( info == null || info . getElementType ( ) != TypeInfo . IFILE_TYPE_INFO ) return null ; return ( IFileTypeInfo ) info ; } private TypeInfo createIFileTypeInfo ( String packageName , String typeName , char [ ] [ ] enclosingName , boolean isModule , String path , IFileTypeInfo last , String project ) { String rest = path . substring ( project . length ( ) + ) ; int index = rest . lastIndexOf ( TypeInfo . SEPARATOR ) ; if ( index == - ) return null ; String middle = rest . substring ( , index ) ; rest = rest . substring ( index + ) ; index = rest . lastIndexOf ( TypeInfo . EXTENSION_SEPARATOR ) ; String file = null ; String extension = null ; if ( index != - ) { file = rest . substring ( , index ) ; extension = rest . substring ( index + ) ; } else { return null ; } String src = null ; int ml = middle . length ( ) ; int pl = packageName . length ( ) ; if ( ml > && ml - > pl ) { src = middle . substring ( , ml - pl - ( pl > ? : ) ) ; } if ( last != null ) { if ( src != null && src . equals ( last . getFolder ( ) ) ) src = last . getFolder ( ) ; } if ( typeName . equals ( file ) ) { file = typeName ; } else { file = createString ( file ) ; } if ( RUBY . equals ( extension ) ) extension = RUBY ; else extension = createString ( extension ) ; return new IFileTypeInfo ( packageName , typeName , enclosingName , isModule , project , src , file , extension ) ; } private String getPackageName ( char [ ] packageName ) { if ( fLast == null ) return new String ( packageName ) ; String lastPackageName = fLast . getPackageName ( ) ; if ( Strings . equals ( lastPackageName , packageName ) ) return lastPackageName ; return new String ( packageName ) ; } private String getProject ( String path ) { for ( int i = ; i < fProjects . length ; i ++ ) { String project = fProjects [ i ] ; if ( path . startsWith ( project , ) ) return project ; } return null ; } private String createString ( String s ) { if ( s == null ) return null ; int length = s . length ( ) ; if ( length > fBuffer . length ) fBuffer = new char [ length ] ; s . getChars ( , length , fBuffer , ) ; return new String ( fBuffer , , length ) ; } private static String [ ] getProjectList ( ) { IRubyModel model = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; String [ ] result ; try { IRubyProject [ ] projects = model . getRubyProjects ( ) ; result = new String [ projects . length ] ; for ( int i = ; i < projects . length ; i ++ ) { result [ i ] = projects [ i ] . getElementName ( ) ; } } catch ( RubyModelException e ) { result = new String [ ] ; } Arrays . sort ( result , new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { int l1 = ( ( String ) o1 ) . length ( ) ; int l2 = ( ( String ) o2 ) . length ( ) ; if ( l1 < l2 ) return ; if ( l2 < l1 ) return - ; return ; } public boolean equals ( Object obj ) { return super . equals ( obj ) ; } } ) ; return result ; } } package org . rubypeople . rdt . internal . corext . util ; import java . io . IOException ; import java . util . Collection ; import java . util . Collections ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . Region ; import org . jruby . Ruby ; import org . jruby . RubyString ; import org . jruby . ast . CommentNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . runtime . builtin . IRubyObject ; import org . jruby . util . KCode ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . ui . text . HTMLPrinter ; import org . rubypeople . rdt . ui . RubyElementLabels ; public class RDocUtil { private final static long LABEL_FLAGS = RubyElementLabels . ALL_FULLY_QUALIFIED | RubyElementLabels . M_PARAMETER_NAMES | RubyElementLabels . USE_RESOLVED ; private final static long LOCAL_VARIABLE_FLAGS = LABEL_FLAGS & ~ RubyElementLabels . F_FULLY_QUALIFIED | RubyElementLabels . F_POST_QUALIFIED ; private static Ruby fgRuby ; private static String fgRdocScriptPath ; private RDocUtil ( ) { } public static String getDocumentation ( IRubyElement element ) { if ( element instanceof IMember ) { return getContents ( ( IMember ) element ) ; } return "" ; } public static String getHTMLDocumentation ( IRubyElement element ) { return getHTMLDocumentation ( getDocumentation ( element ) ) ; } private static String getContents ( IMember member ) { String src = "" ; int elementOffset = - ; try { src = member . getRubyScript ( ) . getSource ( ) ; ISourceRange range = member . getSourceRange ( ) ; if ( range == null ) return null ; elementOffset = range . getOffset ( ) ; } catch ( RubyModelException e ) { return null ; } Collection < CommentNode > comments = getComments ( src ) ; if ( member . isType ( IRubyElement . TYPE ) || member . isType ( IRubyElement . METHOD ) ) { return getPrecedingComment ( comments , elementOffset , src ) ; } if ( member . isType ( IRubyElement . CLASS_VAR ) || member . isType ( IRubyElement . INSTANCE_VAR ) || member . isType ( IRubyElement . LOCAL_VARIABLE ) || member . isType ( IRubyElement . CONSTANT ) ) { String comment = getFollowingComment ( comments , elementOffset , src ) ; if ( comment != null ) return comment ; return getPrecedingComment ( comments , elementOffset , src ) ; } return getFollowingComment ( comments , elementOffset , src ) ; } private static String getPrecedingComment ( Collection < CommentNode > comments , int elementStart , String src ) { if ( comments == null || comments . isEmpty ( ) ) return null ; for ( CommentNode comment : comments ) { ISourcePosition pos = comment . getPosition ( ) ; if ( pos . getEndOffset ( ) > elementStart ) continue ; String between = src . substring ( pos . getEndOffset ( ) , elementStart ) ; if ( between . trim ( ) . length ( ) > ) continue ; String preceding = getPrecedingComment ( comments , pos . getStartOffset ( ) , src ) ; if ( preceding == null ) { preceding = removePrecedingHashes ( comment . getContent ( ) ) ; } else { preceding += "" + removePrecedingHashes ( comment . getContent ( ) ) ; } return preceding ; } return null ; } private static String getFollowingComment ( Collection < CommentNode > comments , int elementStart , String src ) { if ( comments == null || comments . isEmpty ( ) ) return null ; for ( CommentNode comment : comments ) { ISourcePosition pos = comment . getPosition ( ) ; if ( pos . getStartOffset ( ) < elementStart ) continue ; String between = src . substring ( elementStart , pos . getStartOffset ( ) ) ; if ( between . contains ( "" ) ) continue ; String com = comment . getContent ( ) ; if ( com != null && com . length ( ) > ) return removePrecedingHashes ( com ) ; } return null ; } private static String removePrecedingHashes ( String comment ) { return comment . trim ( ) . substring ( ) ; } public static String getHTMLDocumentation ( String docs ) { if ( docs == null ) return null ; try { docs = removeUnecessaryIndent ( docs ) ; String script = "" + "" + "" + "" ; String script2 = "" + "" + "" ; Ruby ruby = getJRubyInstance ( ) ; RubyString blah = RubyString . newUnicodeString ( ruby , docs ) ; ruby . setCurrentDirectory ( getRDocScriptPath ( ) ) ; ruby . setKCode ( KCode . UTF8 ) ; IRubyObject p = ruby . evalScriptlet ( script ) ; IRubyObject html = ruby . evalScriptlet ( script2 ) ; IRubyObject output = p . callMethod ( ruby . getCurrentContext ( ) , "" , new IRubyObject [ ] { blah , html } ) ; docs = output . asString ( ) . getUnicodeValue ( ) ; } catch ( Exception e ) { } return docs ; } private static String removeUnecessaryIndent ( String docs ) { int count = ; String [ ] lines = docs . split ( "" ) ; if ( lines == null || lines . length == ) return docs ; String tmp = lines [ ] ; if ( tmp != null && tmp . length ( ) > ) { while ( tmp . charAt ( ) == '' ) { count ++ ; if ( tmp . length ( ) == ) break ; tmp = tmp . substring ( ) ; } } StringBuffer modified = new StringBuffer ( ) ; for ( int i = ; i < lines . length ; i ++ ) { String line = lines [ i ] ; if ( line . length ( ) > count ) { if ( line . substring ( , count ) . trim ( ) . length ( ) == ) { line = line . substring ( count ) ; } } modified . append ( line ) ; modified . append ( "" ) ; } modified . deleteCharAt ( modified . length ( ) - ) ; return modified . toString ( ) ; } private static Ruby getJRubyInstance ( ) { if ( fgRuby == null ) fgRuby = Ruby . newInstance ( ) ; return fgRuby ; } private static String getRDocScriptPath ( ) throws IOException { if ( fgRdocScriptPath == null ) { RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( RubyCore . getPlugin ( ) , new Path ( "" ) . append ( "" ) ) ; fgRdocScriptPath = RubyCore . getPlugin ( ) . getStateLocation ( ) . append ( "" ) . toPortableString ( ) ; } return fgRdocScriptPath ; } public static IRegion getDocumentationRegion ( IMember member ) { if ( ! ( member . isType ( IRubyElement . TYPE ) || member . isType ( IRubyElement . METHOD ) ) ) return null ; String src = "" ; int elementOffset = - ; try { src = member . getRubyScript ( ) . getSource ( ) ; elementOffset = member . getSourceRange ( ) . getOffset ( ) ; } catch ( RubyModelException e ) { return null ; } Collection < CommentNode > comments = getComments ( src ) ; return getPrecedingCommentRegion ( comments , elementOffset , src ) ; } private static Collection < CommentNode > getComments ( String src ) { try { RubyParser parser = new RubyParser ( ) ; return parser . parse ( src ) . getCommentNodes ( ) ; } catch ( SyntaxException e ) { } catch ( Exception e ) { RubyCore . log ( e ) ; } return Collections . emptyList ( ) ; } private static IRegion getPrecedingCommentRegion ( Collection < CommentNode > comments , int elementStart , String src ) { if ( comments == null || comments . isEmpty ( ) ) return null ; for ( CommentNode comment : comments ) { ISourcePosition pos = comment . getPosition ( ) ; if ( pos . getEndOffset ( ) > elementStart ) continue ; String between = src . substring ( pos . getEndOffset ( ) , elementStart ) ; if ( between . trim ( ) . length ( ) > ) continue ; IRegion preceding = getPrecedingCommentRegion ( comments , pos . getStartOffset ( ) , src ) ; if ( preceding == null ) { preceding = new Region ( pos . getStartOffset ( ) , pos . getEndOffset ( ) - pos . getStartOffset ( ) ) ; } else { preceding = new Region ( preceding . getOffset ( ) , pos . getEndOffset ( ) - preceding . getOffset ( ) ) ; } return preceding ; } return null ; } public static String getHTMLDocumentation ( IRubyElement [ ] result ) { StringBuffer buffer = new StringBuffer ( ) ; int nResults = result . length ; if ( nResults == ) return null ; boolean hasContents = false ; if ( nResults > ) { for ( int i = ; i < result . length ; i ++ ) { HTMLPrinter . startBulletList ( buffer ) ; IRubyElement curr = result [ i ] ; if ( curr instanceof IMember || curr . getElementType ( ) == IRubyElement . LOCAL_VARIABLE ) { HTMLPrinter . addBullet ( buffer , getInfoText ( curr ) ) ; hasContents = true ; } HTMLPrinter . endBulletList ( buffer ) ; } } else { IRubyElement curr = result [ ] ; if ( curr instanceof IMember ) { IMember member = ( IMember ) curr ; String contents = RDocUtil . getHTMLDocumentation ( member ) ; if ( contents != null ) { HTMLPrinter . addSmallHeader ( buffer , getInfoText ( member ) ) ; HTMLPrinter . addParagraph ( buffer , contents ) ; } hasContents = true ; } else if ( curr != null && curr . getElementType ( ) == IRubyElement . LOCAL_VARIABLE ) { HTMLPrinter . addSmallHeader ( buffer , getInfoText ( curr ) ) ; hasContents = true ; } } if ( ! hasContents ) return null ; if ( buffer . length ( ) > ) { return buffer . toString ( ) ; } return null ; } private static String getInfoText ( IRubyElement member ) { long flags = member . getElementType ( ) == IRubyElement . LOCAL_VARIABLE ? LOCAL_VARIABLE_FLAGS : LABEL_FLAGS ; String label = RubyElementLabels . getElementLabel ( member , flags ) ; StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < label . length ( ) ; i ++ ) { char ch = label . charAt ( i ) ; if ( ch == '' ) { buf . append ( "" ) ; } else if ( ch == '>' ) { buf . append ( "" ) ; } else { buf . append ( ch ) ; } } return buf . toString ( ) ; } } package org . rubypeople . rdt . internal . corext . util ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public final class RubyModelUtil { public static final String DEFAULT_SCRIPT_SUFFIX = "" ; private static boolean PRIMARY_ONLY = false ; public static IRubyScript toOriginal ( IRubyScript cu ) { if ( PRIMARY_ONLY ) { testRubyScriptOwner ( "" , cu ) ; } if ( cu == null ) return cu ; return cu . getPrimary ( ) ; } private static void testRubyScriptOwner ( String methodName , IRubyScript cu ) { if ( cu == null ) { return ; } if ( ! isPrimary ( cu ) ) { RubyPlugin . logErrorMessage ( methodName + "" ) ; } } public static boolean isPrimary ( IRubyScript cu ) { return cu . getOwner ( ) == null ; } public static void reconcile ( IRubyScript unit ) throws RubyModelException { unit . reconcile ( false , null , null ) ; } public static IRubyElement toOriginal ( IRubyElement element ) { return element . getPrimaryElement ( ) ; } public static ISourceFolderRoot getSourceFolderRoot ( IRubyElement element ) { return ( ISourceFolderRoot ) element . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; } public static ISourceFolder getSourceFolder ( IRubyElement element ) { ISourceFolder srcFolder = ( ISourceFolder ) element . getAncestor ( IRubyElement . SOURCE_FOLDER ) ; if ( srcFolder == null ) { IRubyProject proj = element . getRubyProject ( ) ; ISourceFolderRoot root = proj . getSourceFolderRoot ( proj . getResource ( ) ) ; return root . getSourceFolder ( "" ) ; } return srcFolder ; } public static boolean isExcludedPath ( IPath resourcePath , IPath [ ] exclusionPatterns ) { char [ ] path = resourcePath . toString ( ) . toCharArray ( ) ; for ( int i = , length = exclusionPatterns . length ; i < length ; i ++ ) { char [ ] pattern = exclusionPatterns [ i ] . toString ( ) . toCharArray ( ) ; if ( CharOperation . pathMatch ( pattern , path , true , '' ) ) { return true ; } } return false ; } public static String concatenateName ( char [ ] name1 , char [ ] name2 ) { StringBuffer buf = new StringBuffer ( ) ; if ( name1 != null && name1 . length > ) { buf . append ( name1 ) ; } if ( name2 != null && name2 . length > ) { if ( buf . length ( ) > ) { buf . append ( "" ) ; } buf . append ( name2 ) ; } return buf . toString ( ) ; } public static String getFullyQualifiedName ( IType type ) { return type . getFullyQualifiedName ( ) ; } public static IType findTypeInRubyScript ( IRubyScript script , String typeQualifiedName ) throws RubyModelException { IType [ ] types = script . getAllTypes ( ) ; for ( int i = ; i < types . length ; i ++ ) { String currName = getTypeQualifiedName ( types [ i ] ) ; if ( typeQualifiedName . equals ( currName ) ) { return types [ i ] ; } } return null ; } public static String getTypeQualifiedName ( IType type ) { return type . getTypeQualifiedName ( "" ) ; } public static boolean isExceptionToBeLogged ( CoreException exception ) { if ( ! ( exception instanceof RubyModelException ) ) return true ; RubyModelException je = ( RubyModelException ) exception ; if ( ! je . isDoesNotExist ( ) ) return true ; IRubyElement [ ] elements = je . getRubyModelStatus ( ) . getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { IRubyElement element = elements [ i ] ; if ( element . getElementType ( ) == IRubyElement . SCRIPT ) continue ; IRubyScript unit = ( IRubyScript ) element . getAncestor ( IRubyElement . SCRIPT ) ; if ( unit == null ) return true ; if ( ! unit . isWorkingCopy ( ) ) return true ; } return false ; } public static boolean isSuperType ( ITypeHierarchy hierarchy , IType possibleSuperType , IType type ) { IType superClass = hierarchy . getSuperclass ( type ) ; if ( superClass != null && ( possibleSuperType . equals ( superClass ) || isSuperType ( hierarchy , possibleSuperType , superClass ) ) ) { return true ; } if ( Flags . isModule ( hierarchy . getCachedFlags ( possibleSuperType ) ) ) { IType [ ] superInterfaces = hierarchy . getSuperModules ( type ) ; for ( int i = ; i < superInterfaces . length ; i ++ ) { IType curr = superInterfaces [ i ] ; if ( possibleSuperType . equals ( curr ) || isSuperType ( hierarchy , possibleSuperType , curr ) ) { return true ; } } } return false ; } public static boolean isVisibleInHierarchy ( IMember member , ISourceFolder pack ) throws RubyModelException { if ( member . isType ( IRubyElement . GLOBAL ) ) return true ; if ( ! member . isType ( IRubyElement . METHOD ) ) return false ; IMethod method = ( IMethod ) member ; IType declaringType = member . getDeclaringType ( ) ; if ( method . getVisibility ( ) == IMethod . PUBLIC || method . getVisibility ( ) == IMethod . PROTECTED || ( declaringType != null && declaringType . isModule ( ) ) ) { return true ; } else if ( method . getVisibility ( ) == IMethod . PRIVATE ) { return false ; } ISourceFolder otherpack = ( ISourceFolder ) member . getAncestor ( IRubyElement . SOURCE_FOLDER ) ; return ( pack != null && pack . equals ( otherpack ) ) ; } public static IMethod findMethodInHierarchy ( ITypeHierarchy hierarchy , IType type , String name , String [ ] paramTypes , boolean isConstructor ) throws RubyModelException { IMethod method = findMethod ( name , paramTypes , isConstructor , type ) ; if ( method != null ) { return method ; } IType superClass = hierarchy . getSuperclass ( type ) ; if ( superClass != null ) { IMethod res = findMethodInHierarchy ( hierarchy , superClass , name , paramTypes , isConstructor ) ; if ( res != null ) { return res ; } } if ( ! isConstructor ) { IType [ ] superInterfaces = hierarchy . getSuperModules ( type ) ; for ( int i = ; i < superInterfaces . length ; i ++ ) { IMethod res = findMethodInHierarchy ( hierarchy , superInterfaces [ i ] , name , paramTypes , false ) ; if ( res != null ) { return res ; } } } return method ; } public static IMethod findMethod ( String name , String [ ] paramTypes , boolean isConstructor , IType type ) throws RubyModelException { IMethod [ ] methods = type . getMethods ( ) ; for ( int i = ; i < methods . length ; i ++ ) { if ( isSameMethodSignature ( name , paramTypes , isConstructor , methods [ i ] ) ) { return methods [ i ] ; } } return null ; } public static boolean isSameMethodSignature ( String name , String [ ] paramTypes , boolean isConstructor , IMethod curr ) throws RubyModelException { if ( isConstructor || name . equals ( curr . getElementName ( ) ) ) { if ( isConstructor == curr . isConstructor ( ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . internal . corext . util ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceVisitor ; import org . eclipse . core . resources . mapping . RemoteResourceMappingContext ; import org . eclipse . core . resources . mapping . ResourceMapping ; import org . eclipse . core . resources . mapping . ResourceMappingContext ; import org . eclipse . core . resources . mapping . ResourceTraversal ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . model . RubyModelProvider ; public abstract class RubyElementResourceMapping extends ResourceMapping { protected RubyElementResourceMapping ( ) { } public IRubyElement getRubyElement ( ) { Object o = getModelObject ( ) ; if ( o instanceof IRubyElement ) return ( IRubyElement ) o ; return null ; } public boolean equals ( Object obj ) { if ( ! ( obj instanceof RubyElementResourceMapping ) ) return false ; return getRubyElement ( ) . equals ( ( ( RubyElementResourceMapping ) obj ) . getRubyElement ( ) ) ; } public int hashCode ( ) { IRubyElement javaElement = getRubyElement ( ) ; if ( javaElement == null ) return super . hashCode ( ) ; return javaElement . hashCode ( ) ; } public String getModelProviderId ( ) { return RubyModelProvider . RUBY_MODEL_PROVIDER_ID ; } public boolean contains ( ResourceMapping mapping ) { if ( mapping instanceof RubyElementResourceMapping ) { RubyElementResourceMapping javaMapping = ( RubyElementResourceMapping ) mapping ; IRubyElement element = getRubyElement ( ) ; IRubyElement other = javaMapping . getRubyElement ( ) ; if ( other != null && element != null ) return element . getPath ( ) . isPrefixOf ( other . getPath ( ) ) ; } return false ; } private static final class RubyModelResourceMapping extends RubyElementResourceMapping { private final IRubyModel fRubyModel ; private RubyModelResourceMapping ( IRubyModel model ) { Assert . isNotNull ( model ) ; fRubyModel = model ; } public Object getModelObject ( ) { return fRubyModel ; } public IProject [ ] getProjects ( ) { IRubyProject [ ] projects = null ; try { projects = fRubyModel . getRubyProjects ( ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; return new IProject [ ] ; } IProject [ ] result = new IProject [ projects . length ] ; for ( int i = ; i < projects . length ; i ++ ) { result [ i ] = projects [ i ] . getProject ( ) ; } return result ; } public ResourceTraversal [ ] getTraversals ( ResourceMappingContext context , IProgressMonitor monitor ) throws CoreException { IRubyProject [ ] projects = fRubyModel . getRubyProjects ( ) ; ResourceTraversal [ ] result = new ResourceTraversal [ projects . length ] ; for ( int i = ; i < projects . length ; i ++ ) { result [ i ] = new ResourceTraversal ( new IResource [ ] { projects [ i ] . getProject ( ) } , IResource . DEPTH_INFINITE , ) ; } return result ; } } private static final class RubyProjectResourceMapping extends RubyElementResourceMapping { private final IRubyProject fProject ; private RubyProjectResourceMapping ( IRubyProject project ) { Assert . isNotNull ( project ) ; fProject = project ; } public Object getModelObject ( ) { return fProject ; } public IProject [ ] getProjects ( ) { return new IProject [ ] { fProject . getProject ( ) } ; } public ResourceTraversal [ ] getTraversals ( ResourceMappingContext context , IProgressMonitor monitor ) throws CoreException { return new ResourceTraversal [ ] { new ResourceTraversal ( new IResource [ ] { fProject . getProject ( ) } , IResource . DEPTH_INFINITE , ) } ; } } private static final class PackageFragementRootResourceMapping extends RubyElementResourceMapping { private final ISourceFolderRoot fRoot ; private PackageFragementRootResourceMapping ( ISourceFolderRoot root ) { Assert . isNotNull ( root ) ; fRoot = root ; } public Object getModelObject ( ) { return fRoot ; } public IProject [ ] getProjects ( ) { return new IProject [ ] { fRoot . getRubyProject ( ) . getProject ( ) } ; } public ResourceTraversal [ ] getTraversals ( ResourceMappingContext context , IProgressMonitor monitor ) throws CoreException { return new ResourceTraversal [ ] { new ResourceTraversal ( new IResource [ ] { fRoot . getResource ( ) } , IResource . DEPTH_INFINITE , ) } ; } } private static final class LocalPackageFragementTraversal extends ResourceTraversal { private final ISourceFolder fPack ; public LocalPackageFragementTraversal ( ISourceFolder pack ) throws CoreException { super ( new IResource [ ] { pack . getResource ( ) } , IResource . DEPTH_ONE , ) ; fPack = pack ; } public void accept ( IResourceVisitor visitor ) throws CoreException { IFile [ ] files = getPackageContent ( fPack ) ; final IResource resource = fPack . getResource ( ) ; if ( resource != null ) visitor . visit ( resource ) ; for ( int i = ; i < files . length ; i ++ ) { visitor . visit ( files [ i ] ) ; } } } private static final class SourceFolderResourceMapping extends RubyElementResourceMapping { private final ISourceFolder fPack ; private SourceFolderResourceMapping ( ISourceFolder pack ) { Assert . isNotNull ( pack ) ; fPack = pack ; } public Object getModelObject ( ) { return fPack ; } public IProject [ ] getProjects ( ) { return new IProject [ ] { fPack . getRubyProject ( ) . getProject ( ) } ; } public ResourceTraversal [ ] getTraversals ( ResourceMappingContext context , IProgressMonitor monitor ) throws CoreException { if ( context instanceof RemoteResourceMappingContext ) { return new ResourceTraversal [ ] { new ResourceTraversal ( new IResource [ ] { fPack . getResource ( ) } , IResource . DEPTH_ONE , ) } ; } else { return new ResourceTraversal [ ] { new LocalPackageFragementTraversal ( fPack ) } ; } } public void accept ( ResourceMappingContext context , IResourceVisitor visitor , IProgressMonitor monitor ) throws CoreException { if ( context instanceof RemoteResourceMappingContext ) { super . accept ( context , visitor , monitor ) ; } else { IFile [ ] files = getPackageContent ( fPack ) ; if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , files . length + ) ; final IResource resource = fPack . getResource ( ) ; if ( resource != null ) visitor . visit ( resource ) ; monitor . worked ( ) ; for ( int i = ; i < files . length ; i ++ ) { visitor . visit ( files [ i ] ) ; monitor . worked ( ) ; } } } } private static IFile [ ] getPackageContent ( ISourceFolder pack ) throws CoreException { List result = new ArrayList ( ) ; IContainer container = ( IContainer ) pack . getResource ( ) ; if ( container != null ) { IResource [ ] members = container . members ( ) ; for ( int m = ; m < members . length ; m ++ ) { IResource member = members [ m ] ; if ( member instanceof IFile ) { IFile file = ( IFile ) member ; if ( "" . equals ( file . getFileExtension ( ) ) && file . isDerived ( ) ) continue ; result . add ( member ) ; } } } return ( IFile [ ] ) result . toArray ( new IFile [ result . size ( ) ] ) ; } private static final class RubyScriptResourceMapping extends RubyElementResourceMapping { private final IRubyScript fUnit ; private RubyScriptResourceMapping ( IRubyScript unit ) { Assert . isNotNull ( unit ) ; fUnit = unit ; } public Object getModelObject ( ) { return fUnit ; } public IProject [ ] getProjects ( ) { return new IProject [ ] { fUnit . getRubyProject ( ) . getProject ( ) } ; } public ResourceTraversal [ ] getTraversals ( ResourceMappingContext context , IProgressMonitor monitor ) throws CoreException { return new ResourceTraversal [ ] { new ResourceTraversal ( new IResource [ ] { fUnit . getResource ( ) } , IResource . DEPTH_ONE , ) } ; } } public static ResourceMapping create ( IRubyElement element ) { switch ( element . getElementType ( ) ) { case IRubyElement . TYPE : return create ( ( IType ) element ) ; case IRubyElement . SCRIPT : return create ( ( IRubyScript ) element ) ; case IRubyElement . SOURCE_FOLDER : return create ( ( ISourceFolder ) element ) ; case IRubyElement . SOURCE_FOLDER_ROOT : return create ( ( ISourceFolderRoot ) element ) ; case IRubyElement . RUBY_PROJECT : return create ( ( IRubyProject ) element ) ; case IRubyElement . RUBY_MODEL : return create ( ( IRubyModel ) element ) ; default : return null ; } } public static ResourceMapping create ( final IRubyModel model ) { return new RubyModelResourceMapping ( model ) ; } public static ResourceMapping create ( final IRubyProject project ) { return new RubyProjectResourceMapping ( project ) ; } public static ResourceMapping create ( final ISourceFolderRoot root ) { if ( root . isExternal ( ) ) return null ; return new PackageFragementRootResourceMapping ( root ) ; } public static ResourceMapping create ( final ISourceFolder pack ) { ISourceFolderRoot root = ( ISourceFolderRoot ) pack . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; if ( ! root . isExternal ( ) ) { return new SourceFolderResourceMapping ( pack ) ; } return null ; } public static ResourceMapping create ( IRubyScript unit ) { if ( unit == null ) return null ; return new RubyScriptResourceMapping ( unit . getPrimary ( ) ) ; } public static ResourceMapping create ( IType type ) { IRubyElement parent = type . getParent ( ) ; if ( parent instanceof IRubyScript ) { return create ( ( IRubyScript ) parent ) ; } return null ; } } package org . rubypeople . rdt . internal . corext . util ; import java . util . StringTokenizer ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . StringMatcher ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class TypeFilter implements IPropertyChangeListener { public static TypeFilter getDefault ( ) { return RubyPlugin . getDefault ( ) . getTypeFilter ( ) ; } public static boolean isFiltered ( String fullTypeName ) { return getDefault ( ) . filter ( fullTypeName ) ; } public static boolean isFiltered ( char [ ] fullTypeName ) { return getDefault ( ) . filter ( new String ( fullTypeName ) ) ; } public static boolean isFiltered ( char [ ] packageName , char [ ] typeName ) { return getDefault ( ) . filter ( RubyModelUtil . concatenateName ( packageName , typeName ) ) ; } public static boolean isFiltered ( IType type ) { TypeFilter typeFilter = getDefault ( ) ; if ( typeFilter . hasFilters ( ) ) { return typeFilter . filter ( RubyModelUtil . getFullyQualifiedName ( type ) ) ; } return false ; } private StringMatcher [ ] fStringMatchers ; public TypeFilter ( ) { fStringMatchers = null ; PreferenceConstants . getPreferenceStore ( ) . addPropertyChangeListener ( this ) ; } private synchronized StringMatcher [ ] getStringMatchers ( ) { if ( fStringMatchers == null ) { String str = PreferenceConstants . getPreferenceStore ( ) . getString ( PreferenceConstants . TYPEFILTER_ENABLED ) ; StringTokenizer tok = new StringTokenizer ( str , "" ) ; int nTokens = tok . countTokens ( ) ; fStringMatchers = new StringMatcher [ nTokens ] ; for ( int i = ; i < nTokens ; i ++ ) { String curr = tok . nextToken ( ) ; if ( curr . length ( ) > ) { fStringMatchers [ i ] = new StringMatcher ( curr , false , false ) ; } } } return fStringMatchers ; } public void dispose ( ) { PreferenceConstants . getPreferenceStore ( ) . removePropertyChangeListener ( this ) ; fStringMatchers = null ; } public boolean hasFilters ( ) { return getStringMatchers ( ) . length > ; } public boolean filter ( String fullTypeName ) { StringMatcher [ ] matchers = getStringMatchers ( ) ; for ( int i = ; i < matchers . length ; i ++ ) { StringMatcher curr = matchers [ i ] ; if ( curr . match ( fullTypeName ) ) { return true ; } } return false ; } public synchronized void propertyChange ( PropertyChangeEvent event ) { if ( PreferenceConstants . TYPEFILTER_ENABLED . equals ( event . getProperty ( ) ) ) { fStringMatchers = null ; } } } package org . rubypeople . rdt . ui . dialogs ; public interface ITypeInfoRequestor { public boolean isModule ( ) ; public String getTypeName ( ) ; public String getPackageName ( ) ; public String getEnclosingName ( ) ; } package org . rubypeople . rdt . ui . dialogs ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . dialogs . ISelectionStatusValidator ; import org . rubypeople . rdt . core . IType ; public abstract class TypeSelectionExtension { private ITypeSelectionComponent fComponent ; public final void initialize ( ITypeSelectionComponent component ) { fComponent = component ; } public final ITypeSelectionComponent getTypeSelectionComponent ( ) { return fComponent ; } public Control createContentArea ( Composite parent ) { return null ; } public ITypeInfoFilterExtension getFilterExtension ( ) { return null ; } public ISelectionStatusValidator getSelectionValidator ( ) { return null ; } public ITypeInfoImageProvider getImageProvider ( ) { return null ; } } package org . rubypeople . rdt . ui . dialogs ; import org . eclipse . jface . resource . ImageDescriptor ; public interface ITypeInfoImageProvider { public ImageDescriptor getImageDescriptor ( ITypeInfoRequestor typeInfoRequestor ) ; } package org . rubypeople . rdt . ui . dialogs ; public interface ITypeInfoFilterExtension { public boolean select ( ITypeInfoRequestor typeInfoRequestor ) ; } package org . rubypeople . rdt . ui . dialogs ; public interface ITypeSelectionComponent { public void triggerSearch ( ) ; } package org . rubypeople . rdt . ui ; import org . eclipse . core . resources . IFile ; import org . eclipse . jface . operation . IRunnableContext ; import org . eclipse . jface . util . Assert ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . dialogs . SelectionDialog ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . SharedImages ; import org . rubypeople . rdt . internal . ui . dialogs . TypeSelectionDialog2 ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . ui . dialogs . TypeSelectionExtension ; public final class RubyUI { private RubyUI ( ) { } private static ISharedImages fgSharedImages = null ; public static final String ID_PLUGIN = "" ; public static final String ID_ACTION_SET = "" ; public static final String ID_RUBY_EDITOR = "" ; public static final String ID_EXTERNAL_EDITOR = "" ; public static String ID_PROJECTS_VIEW = "" ; public static String ID_TYPES_VIEW = "" ; public static String ID_MEMBERS_VIEW = "" ; public static final String ID_ELEMENT_CREATION_ACTION_SET = "" ; public static final String ID_PERSPECTIVE = "" ; public static final String ID_TYPE_HIERARCHY = "" ; public static final String ID_HIERARCHYPERSPECTIVE = "" ; public static final String ID_RUBY_EXPLORER = "" ; public static final String ID_RUBY_RESOURCE_VIEW = "" ; public static final String ID_RULER_CONTEXT_MENU = "" ; public static final String ID_EDITOR_CONTEXT_MENU = "" ; public static IRubyElement getEditorInputRubyElement ( IEditorInput editorInput ) { Assert . isNotNull ( editorInput ) ; IRubyElement re = getWorkingCopyManager ( ) . getWorkingCopy ( editorInput ) ; if ( re != null ) return re ; re = ( IRubyElement ) editorInput . getAdapter ( IRubyElement . class ) ; if ( re != null ) return re ; if ( editorInput instanceof IFileEditorInput ) { IFileEditorInput fileInput = ( IFileEditorInput ) editorInput ; IFile file = fileInput . getFile ( ) ; re = RubyCore . create ( file ) ; } return re ; } public static ISharedImages getSharedImages ( ) { if ( fgSharedImages == null ) fgSharedImages = new SharedImages ( ) ; return fgSharedImages ; } public static IWorkingCopyManager getWorkingCopyManager ( ) { return RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) ; } public static IDocumentProvider getDocumentProvider ( ) { return RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) ; } public static void revealInEditor ( IEditorPart part , IRubyElement element ) { EditorUtility . revealInEditor ( part , element ) ; } public static SelectionDialog createTypeDialog ( Shell parent , IRunnableContext context , IRubySearchScope scope , int elementKinds , boolean multipleSelection ) throws RubyModelException { return createTypeDialog ( parent , context , scope , elementKinds , multipleSelection , "" ) ; } public static SelectionDialog createTypeDialog ( Shell parent , IRunnableContext context , IRubySearchScope scope , int elementKinds , boolean multipleSelection , String filter ) throws RubyModelException { return createTypeDialog ( parent , context , scope , elementKinds , multipleSelection , filter , null ) ; } public static SelectionDialog createTypeDialog ( Shell parent , IRunnableContext context , IRubySearchScope scope , int elementKinds , boolean multipleSelection , String filter , TypeSelectionExtension extension ) throws RubyModelException { TypeSelectionDialog2 dialog = new TypeSelectionDialog2 ( parent , multipleSelection , context , scope , elementKinds , extension ) ; dialog . setMessage ( RubyUIMessages . RubyUI_defaultDialogMessage ) ; dialog . setFilter ( filter ) ; return dialog ; } public static IEditorPart openInEditor ( IRubyElement element ) throws RubyModelException , PartInitException { return EditorUtility . openInEditor ( element ) ; } } package org . rubypeople . rdt . ui ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . ui . IViewPart ; public interface IPackagesViewPart extends IViewPart { void selectAndReveal ( Object element ) ; TreeViewer getTreeViewer ( ) ; boolean isLinkingEnabled ( ) ; void setLinkingEnabled ( boolean enabled ) ; } package org . rubypeople . rdt . ui ; import java . util . Iterator ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceStatus ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . text . Position ; import org . eclipse . jface . text . source . Annotation ; import org . eclipse . jface . text . source . IAnnotationModel ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . IDecoration ; import org . eclipse . jface . viewers . ILabelDecorator ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ILightweightLabelDecorator ; import org . eclipse . jface . viewers . LabelProviderChangedEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . ui . part . FileEditorInput ; import org . eclipse . ui . texteditor . MarkerAnnotation ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . viewsupport . IProblemChangedListener ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; import org . rubypeople . rdt . ui . viewsupport . ImageImageDescriptor ; public class ProblemsLabelDecorator implements ILabelDecorator , ILightweightLabelDecorator { public static class ProblemsLabelChangedEvent extends LabelProviderChangedEvent { private static final long serialVersionUID = ; private boolean fMarkerChange ; public ProblemsLabelChangedEvent ( IBaseLabelProvider eventSource , IResource [ ] changedResource , boolean isMarkerChange ) { super ( eventSource , changedResource ) ; fMarkerChange = isMarkerChange ; } public boolean isMarkerChange ( ) { return fMarkerChange ; } } private static final int ERRORTICK_WARNING = RubyElementImageDescriptor . WARNING ; private static final int ERRORTICK_ERROR = RubyElementImageDescriptor . ERROR ; private ImageDescriptorRegistry fRegistry ; private boolean fUseNewRegistry = false ; private IProblemChangedListener fProblemChangedListener ; private ListenerList fListeners ; private ISourceRange fCachedRange ; public ProblemsLabelDecorator ( ) { this ( null ) ; fUseNewRegistry = true ; } public ProblemsLabelDecorator ( ImageDescriptorRegistry registry ) { fRegistry = registry ; fProblemChangedListener = null ; } private ImageDescriptorRegistry getRegistry ( ) { if ( fRegistry == null ) { fRegistry = fUseNewRegistry ? new ImageDescriptorRegistry ( ) : RubyPlugin . getImageDescriptorRegistry ( ) ; } return fRegistry ; } public String decorateText ( String text , Object element ) { return text ; } public Image decorateImage ( Image image , Object obj ) { int adornmentFlags = computeAdornmentFlags ( obj ) ; if ( adornmentFlags != ) { ImageDescriptor baseImage = new ImageImageDescriptor ( image ) ; Rectangle bounds = image . getBounds ( ) ; return getRegistry ( ) . get ( new RubyElementImageDescriptor ( baseImage , adornmentFlags , new Point ( bounds . width , bounds . height ) ) ) ; } return image ; } protected int computeAdornmentFlags ( Object obj ) { try { if ( obj instanceof IRubyElement ) { IRubyElement element = ( IRubyElement ) obj ; int type = element . getElementType ( ) ; switch ( type ) { case IRubyElement . RUBY_MODEL : case IRubyElement . RUBY_PROJECT : case IRubyElement . SOURCE_FOLDER_ROOT : return getErrorTicksFromMarkers ( element . getResource ( ) , IResource . DEPTH_INFINITE , null ) ; case IRubyElement . SOURCE_FOLDER : case IRubyElement . SCRIPT : return getErrorTicksFromMarkers ( element . getResource ( ) , IResource . DEPTH_ONE , null ) ; case IRubyElement . IMPORT_DECLARATION : case IRubyElement . IMPORT_CONTAINER : case IRubyElement . TYPE : case IRubyElement . METHOD : case IRubyElement . FIELD : case IRubyElement . LOCAL_VARIABLE : IRubyScript cu = ( IRubyScript ) element . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) { ISourceReference ref = ( type == IRubyElement . SCRIPT ) ? null : ( ISourceReference ) element ; IAnnotationModel model = isInRubyAnnotationModel ( cu ) ; int result = ; if ( model != null ) { result = getErrorTicksFromAnnotationModel ( model , ref ) ; } else { result = getErrorTicksFromMarkers ( cu . getResource ( ) , IResource . DEPTH_ONE , ref ) ; } fCachedRange = null ; return result ; } break ; default : } } else if ( obj instanceof IResource ) { return getErrorTicksFromMarkers ( ( IResource ) obj , IResource . DEPTH_INFINITE , null ) ; } } catch ( CoreException e ) { if ( e instanceof RubyModelException ) { if ( ( ( RubyModelException ) e ) . isDoesNotExist ( ) ) { return ; } } if ( e . getStatus ( ) . getCode ( ) == IResourceStatus . MARKER_NOT_FOUND ) { return ; } RubyPlugin . log ( e ) ; } return ; } private int getErrorTicksFromMarkers ( IResource res , int depth , ISourceReference sourceElement ) throws CoreException { if ( res == null || ! res . isAccessible ( ) ) { return ; } int info = ; IMarker [ ] markers = res . findMarkers ( IMarker . PROBLEM , true , depth ) ; if ( markers != null ) { for ( int i = ; i < markers . length && ( info != ERRORTICK_ERROR ) ; i ++ ) { IMarker curr = markers [ i ] ; if ( sourceElement == null || isMarkerInRange ( curr , sourceElement ) ) { int priority = curr . getAttribute ( IMarker . SEVERITY , - ) ; if ( priority == IMarker . SEVERITY_WARNING ) { info = ERRORTICK_WARNING ; } else if ( priority == IMarker . SEVERITY_ERROR ) { info = ERRORTICK_ERROR ; } } } } return info ; } private boolean isMarkerInRange ( IMarker marker , ISourceReference sourceElement ) throws CoreException { if ( marker . isSubtypeOf ( IMarker . TEXT ) ) { int pos = marker . getAttribute ( IMarker . CHAR_START , - ) ; return isInside ( pos , sourceElement ) ; } return false ; } private IAnnotationModel isInRubyAnnotationModel ( IRubyScript original ) { if ( original . isWorkingCopy ( ) ) { FileEditorInput editorInput = new FileEditorInput ( ( IFile ) original . getResource ( ) ) ; return RubyPlugin . getDefault ( ) . getRubyDocumentProvider ( ) . getAnnotationModel ( editorInput ) ; } return null ; } private int getErrorTicksFromAnnotationModel ( IAnnotationModel model , ISourceReference sourceElement ) throws CoreException { int info = ; Iterator iter = model . getAnnotationIterator ( ) ; while ( ( info != ERRORTICK_ERROR ) && iter . hasNext ( ) ) { Annotation annot = ( Annotation ) iter . next ( ) ; IMarker marker = isAnnotationInRange ( model , annot , sourceElement ) ; if ( marker != null ) { int priority = marker . getAttribute ( IMarker . SEVERITY , - ) ; if ( priority == IMarker . SEVERITY_WARNING ) { info = ERRORTICK_WARNING ; } else if ( priority == IMarker . SEVERITY_ERROR ) { info = ERRORTICK_ERROR ; } } } return info ; } private IMarker isAnnotationInRange ( IAnnotationModel model , Annotation annot , ISourceReference sourceElement ) throws CoreException { if ( annot instanceof MarkerAnnotation ) { if ( sourceElement == null || isInside ( model . getPosition ( annot ) , sourceElement ) ) { IMarker marker = ( ( MarkerAnnotation ) annot ) . getMarker ( ) ; if ( marker . exists ( ) && marker . isSubtypeOf ( IMarker . PROBLEM ) ) { return marker ; } } } return null ; } private boolean isInside ( Position pos , ISourceReference sourceElement ) throws CoreException { return pos != null && isInside ( pos . getOffset ( ) , sourceElement ) ; } protected boolean isInside ( int pos , ISourceReference sourceElement ) throws CoreException { if ( fCachedRange == null ) { fCachedRange = sourceElement . getSourceRange ( ) ; } ISourceRange range = fCachedRange ; if ( range != null ) { int rangeOffset = range . getOffset ( ) ; return ( rangeOffset <= pos && rangeOffset + range . getLength ( ) > pos ) ; } return false ; } public void dispose ( ) { if ( fProblemChangedListener != null ) { RubyPlugin . getDefault ( ) . getProblemMarkerManager ( ) . removeListener ( fProblemChangedListener ) ; fProblemChangedListener = null ; } if ( fRegistry != null && fUseNewRegistry ) { fRegistry . dispose ( ) ; } } public boolean isLabelProperty ( Object element , String property ) { return true ; } public void addListener ( ILabelProviderListener listener ) { if ( fListeners == null ) { fListeners = new ListenerList ( ) ; } fListeners . add ( listener ) ; if ( fProblemChangedListener == null ) { fProblemChangedListener = new IProblemChangedListener ( ) { public void problemsChanged ( IResource [ ] changedResources , boolean isMarkerChange ) { fireProblemsChanged ( changedResources , isMarkerChange ) ; } } ; RubyPlugin . getDefault ( ) . getProblemMarkerManager ( ) . addListener ( fProblemChangedListener ) ; } } public void removeListener ( ILabelProviderListener listener ) { if ( fListeners != null ) { fListeners . remove ( listener ) ; if ( fListeners . isEmpty ( ) && fProblemChangedListener != null ) { RubyPlugin . getDefault ( ) . getProblemMarkerManager ( ) . removeListener ( fProblemChangedListener ) ; fProblemChangedListener = null ; } } } private void fireProblemsChanged ( IResource [ ] changedResources , boolean isMarkerChange ) { if ( fListeners != null && ! fListeners . isEmpty ( ) ) { LabelProviderChangedEvent event = new ProblemsLabelChangedEvent ( this , changedResources , isMarkerChange ) ; Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { ( ( ILabelProviderListener ) listeners [ i ] ) . labelProviderChanged ( event ) ; } } } public void decorate ( Object element , IDecoration decoration ) { int adornmentFlags = computeAdornmentFlags ( element ) ; if ( adornmentFlags == ERRORTICK_ERROR ) { decoration . addOverlay ( RubyPluginImages . DESC_OVR_ERROR ) ; } else if ( adornmentFlags == ERRORTICK_WARNING ) { decoration . addOverlay ( RubyPluginImages . DESC_OVR_WARNING ) ; } } } package org . rubypeople . rdt . ui . wizards ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . dialogs . ElementTreeSelectionDialog ; import org . eclipse . ui . views . contentoutline . ContentOutline ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . viewsupport . IViewPartInputProvider ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . TypedElementSelectionValidator ; import org . rubypeople . rdt . internal . ui . wizards . TypedViewerFilter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; import org . rubypeople . rdt . ui . RubyElementSorter ; import org . rubypeople . rdt . ui . StandardRubyElementContentProvider ; public abstract class NewContainerWizardPage extends NewElementWizardPage { protected static final String CONTAINER = "" ; protected IStatus fContainerStatus ; private IWorkspaceRoot fWorkspaceRoot ; private StringButtonDialogField fContainerDialogField ; private ISourceFolder fCurrSourceFolder ; public NewContainerWizardPage ( String name ) { super ( name ) ; fWorkspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; ContainerFieldAdapter adapter = new ContainerFieldAdapter ( ) ; fContainerDialogField = new StringButtonDialogField ( adapter ) ; fContainerDialogField . setDialogFieldListener ( adapter ) ; fContainerDialogField . setLabelText ( getContainerLabel ( ) ) ; fContainerDialogField . setButtonLabel ( NewWizardMessages . NewContainerWizardPage_container_button ) ; fContainerStatus = new StatusInfo ( ) ; fCurrSourceFolder = null ; } protected IRubyElement getInitialRubyElement ( IStructuredSelection selection ) { IRubyElement jelem = null ; if ( selection != null && ! selection . isEmpty ( ) ) { Object selectedElement = selection . getFirstElement ( ) ; if ( selectedElement instanceof IAdaptable ) { IAdaptable adaptable = ( IAdaptable ) selectedElement ; jelem = ( IRubyElement ) adaptable . getAdapter ( IRubyElement . class ) ; if ( jelem == null ) { IResource resource = ( IResource ) adaptable . getAdapter ( IResource . class ) ; if ( resource != null && resource . getType ( ) != IResource . ROOT ) { while ( jelem == null && resource . getType ( ) != IResource . PROJECT ) { resource = resource . getParent ( ) ; jelem = ( IRubyElement ) resource . getAdapter ( IRubyElement . class ) ; } if ( jelem == null ) { jelem = RubyCore . create ( resource ) ; } } } } } if ( jelem == null ) { IWorkbenchPart part = RubyPlugin . getActivePage ( ) . getActivePart ( ) ; if ( part instanceof ContentOutline ) { part = RubyPlugin . getActivePage ( ) . getActiveEditor ( ) ; } if ( part instanceof IViewPartInputProvider ) { Object elem = ( ( IViewPartInputProvider ) part ) . getViewPartInput ( ) ; if ( elem instanceof IRubyElement ) { jelem = ( IRubyElement ) elem ; } } } if ( jelem == null || jelem . getElementType ( ) == IRubyElement . RUBY_MODEL ) { try { IRubyProject [ ] projects = RubyCore . create ( getWorkspaceRoot ( ) ) . getRubyProjects ( ) ; if ( projects . length == ) { jelem = projects [ ] ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } return jelem ; } protected IWorkspaceRoot getWorkspaceRoot ( ) { return fWorkspaceRoot ; } protected void createContainerControls ( Composite parent , int nColumns ) { fContainerDialogField . doFillIntoGrid ( parent , nColumns ) ; LayoutUtil . setWidthHint ( fContainerDialogField . getTextControl ( null ) , getMaxFieldWidth ( ) ) ; } protected int getMaxFieldWidth ( ) { return convertWidthInCharsToPixels ( ) ; } protected String getContainerLabel ( ) { return NewWizardMessages . NewContainerWizardPage_container_label ; } protected ITextSelection getCurrentTextSelection ( ) { IWorkbenchPart part = RubyPlugin . getActivePage ( ) . getActivePart ( ) ; if ( part instanceof IEditorPart ) { ISelectionProvider selectionProvider = part . getSite ( ) . getSelectionProvider ( ) ; if ( selectionProvider != null ) { ISelection selection = selectionProvider . getSelection ( ) ; if ( selection instanceof ITextSelection ) { return ( ITextSelection ) selection ; } } } return null ; } private void containerChangeControlPressed ( DialogField field ) { ISourceFolder root = chooseContainer ( ) ; if ( root != null ) { setSourceFolder ( root , true ) ; } } public String getProjectText ( ) { return fContainerDialogField . getText ( ) ; } public String getSourceFolderText ( ) { return fContainerDialogField . getText ( ) ; } protected IStatus containerChanged ( ) { StatusInfo status = new StatusInfo ( ) ; fCurrSourceFolder = null ; String str = getSourceFolderText ( ) ; if ( str . length ( ) == ) { status . setError ( NewWizardMessages . NewContainerWizardPage_error_EnterContainerName ) ; return status ; } IPath path = new Path ( str ) ; IResource res = fWorkspaceRoot . findMember ( path ) ; if ( res != null ) { int resType = res . getType ( ) ; if ( resType == IResource . PROJECT || resType == IResource . FOLDER ) { IProject proj = res . getProject ( ) ; if ( ! proj . isOpen ( ) ) { status . setError ( Messages . format ( NewWizardMessages . NewContainerWizardPage_error_ProjectClosed , proj . getFullPath ( ) . toString ( ) ) ) ; return status ; } IRubyProject rproject = RubyCore . create ( proj ) ; IRubyElement element = RubyCore . create ( res ) ; fCurrSourceFolder = RubyModelUtil . getSourceFolder ( element ) ; if ( res . exists ( ) ) { try { if ( ! proj . hasNature ( RubyCore . NATURE_ID ) ) { if ( resType == IResource . PROJECT ) { status . setError ( NewWizardMessages . NewContainerWizardPage_warning_NotARubyProject ) ; } else { status . setWarning ( NewWizardMessages . NewContainerWizardPage_warning_NotInARubyProject ) ; } return status ; } if ( ! rproject . isOnLoadpath ( fCurrSourceFolder ) ) { status . setWarning ( Messages . format ( NewWizardMessages . NewContainerWizardPage_warning_NotOnLoadPath , str ) ) ; } } catch ( CoreException e ) { status . setWarning ( NewWizardMessages . NewContainerWizardPage_warning_NotARubyProject ) ; } } return status ; } else { status . setError ( Messages . format ( NewWizardMessages . NewContainerWizardPage_error_NotAFolder , str ) ) ; return status ; } } else { status . setError ( Messages . format ( NewWizardMessages . NewContainerWizardPage_error_ContainerDoesNotExist , str ) ) ; return status ; } } public void setSourceFolder ( ISourceFolder root , boolean canBeModified ) { fCurrSourceFolder = root ; String str = ( root == null ) ? "" : root . getPath ( ) . makeRelative ( ) . toString ( ) ; fContainerDialogField . setText ( str ) ; fContainerDialogField . setEnabled ( canBeModified ) ; } protected void initContainerPage ( IRubyElement elem ) { ISourceFolder initRoot = null ; if ( elem != null && ! elem . isType ( IRubyElement . RUBY_MODEL ) ) { initRoot = RubyModelUtil . getSourceFolder ( elem ) ; try { if ( initRoot == null || ( ( ISourceFolderRoot ) initRoot . getParent ( ) ) . isExternal ( ) ) { IRubyProject rproject = elem . getRubyProject ( ) ; if ( rproject != null ) { initRoot = null ; if ( rproject . exists ( ) ) { ISourceFolderRoot [ ] roots = rproject . getSourceFolderRoots ( ) ; for ( int i = ; i < roots . length ; i ++ ) { if ( ! roots [ i ] . isExternal ( ) ) { initRoot = roots [ i ] . getSourceFolder ( "" ) ; break ; } } } if ( initRoot == null ) { initRoot = rproject . getSourceFolderRoot ( rproject . getResource ( ) ) . getSourceFolder ( "" ) ; } } } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } setSourceFolder ( initRoot , true ) ; } private void containerDialogFieldChanged ( DialogField field ) { if ( field == fContainerDialogField ) { fContainerStatus = containerChanged ( ) ; } handleFieldChanged ( CONTAINER ) ; } protected void handleFieldChanged ( String fieldName ) { } private class ContainerFieldAdapter implements IStringButtonAdapter , IDialogFieldListener { public void changeControlPressed ( DialogField field ) { containerChangeControlPressed ( field ) ; } public void dialogFieldChanged ( DialogField field ) { containerDialogFieldChanged ( field ) ; } } protected ISourceFolder chooseContainer ( ) { IRubyElement initElement = getSourceFolder ( ) ; Class [ ] acceptedClasses = new Class [ ] { IRubyProject . class , ISourceFolderRoot . class , ISourceFolder . class } ; TypedElementSelectionValidator validator = new TypedElementSelectionValidator ( acceptedClasses , false ) { public boolean isSelectedValid ( Object element ) { try { if ( element instanceof IRubyProject ) { IRubyProject jproject = ( IRubyProject ) element ; IPath path = jproject . getProject ( ) . getFullPath ( ) ; return ( jproject . findSourceFolderRoot ( path ) != null ) ; } else if ( element instanceof ISourceFolderRoot ) { return ( ! ( ( ISourceFolderRoot ) element ) . isExternal ( ) ) ; } return true ; } catch ( RubyModelException e ) { RubyPlugin . log ( e . getStatus ( ) ) ; } return false ; } } ; acceptedClasses = new Class [ ] { IRubyModel . class , ISourceFolderRoot . class , IRubyProject . class , ISourceFolder . class } ; ViewerFilter filter = new TypedViewerFilter ( acceptedClasses ) { public boolean select ( Viewer viewer , Object parent , Object element ) { if ( element instanceof ISourceFolderRoot ) { return ( ! ( ( ISourceFolderRoot ) element ) . isExternal ( ) ) ; } return super . select ( viewer , parent , element ) ; } } ; StandardRubyElementContentProvider provider = new StandardRubyElementContentProvider ( ) ; ILabelProvider labelProvider = new RubyElementLabelProvider ( RubyElementLabelProvider . SHOW_DEFAULT ) ; ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog ( getShell ( ) , labelProvider , provider ) ; dialog . setValidator ( validator ) ; dialog . setSorter ( new RubyElementSorter ( ) ) ; dialog . setTitle ( NewWizardMessages . NewContainerWizardPage_ChooseSourceContainerDialog_title ) ; dialog . setMessage ( NewWizardMessages . NewContainerWizardPage_ChooseSourceContainerDialog_description ) ; dialog . addFilter ( filter ) ; dialog . setInput ( RubyCore . create ( fWorkspaceRoot ) ) ; dialog . setInitialSelection ( initElement ) ; dialog . setHelpAvailable ( false ) ; if ( dialog . open ( ) == Window . OK ) { Object element = dialog . getFirstResult ( ) ; if ( element instanceof IRubyProject ) { IRubyProject jproject = ( IRubyProject ) element ; return jproject . getSourceFolderRoot ( jproject . getProject ( ) ) . getSourceFolder ( "" ) ; } else if ( element instanceof ISourceFolderRoot ) { return ( ( ISourceFolderRoot ) element ) . getSourceFolder ( "" ) ; } else if ( element instanceof ISourceFolder ) { return ( ISourceFolder ) element ; } return null ; } return null ; } public ISourceFolder getSourceFolder ( ) { return fCurrSourceFolder ; } } package org . rubypeople . rdt . ui . wizards ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . internal . corext . codemanipulation . StubUtility ; import org . rubypeople . rdt . internal . corext . util . CodeFormatterUtil ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . TextFieldNavigationHandler ; import org . rubypeople . rdt . internal . ui . dialogs . TypeSelectionDialog2 ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . SuperModuleSelectionDialog ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IListAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ListDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . Separator ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; public abstract class NewTypeWizardPage extends NewContainerWizardPage { private static class InterfaceWrapper { public String interfaceName ; public InterfaceWrapper ( String interfaceName ) { this . interfaceName = interfaceName ; } public int hashCode ( ) { return interfaceName . hashCode ( ) ; } public boolean equals ( Object obj ) { return obj != null && getClass ( ) . equals ( obj . getClass ( ) ) && ( ( InterfaceWrapper ) obj ) . interfaceName . equals ( interfaceName ) ; } } private static class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage ; public InterfacesListLabelProvider ( ) { fInterfaceImage = RubyPluginImages . get ( RubyPluginImages . IMG_OBJS_MODULE ) ; } public String getText ( Object element ) { return ( ( InterfaceWrapper ) element ) . interfaceName ; } public Image getImage ( Object element ) { return fInterfaceImage ; } } private final static String PAGE_NAME = "" ; protected final static String PACKAGE = PAGE_NAME + "" ; protected final static String ENCLOSING = PAGE_NAME + "" ; protected final static String ENCLOSINGSELECTION = ENCLOSING + "" ; protected final static String TYPENAME = PAGE_NAME + "" ; protected final static String SUPER = PAGE_NAME + "" ; protected final static String INTERFACES = PAGE_NAME + "" ; protected final static String METHODS = PAGE_NAME + "" ; private IType fCurrType ; private StringDialogField fTypeNameDialogField ; private StringButtonDialogField fSuperClassDialogField ; private ListDialogField fSuperModulesDialogField ; private IType fCreatedType ; protected IStatus fTypeNameStatus ; protected IStatus fSuperClassStatus ; protected IStatus fSuperModulesStatus ; private int fTypeKind ; public static final int CLASS_TYPE = ; public static final int INTERFACE_TYPE = ; public NewTypeWizardPage ( boolean isClass , String pageName ) { this ( isClass ? CLASS_TYPE : INTERFACE_TYPE , pageName ) ; } public NewTypeWizardPage ( int typeKind , String pageName ) { super ( pageName ) ; fTypeKind = typeKind ; fCreatedType = null ; TypeFieldsAdapter adapter = new TypeFieldsAdapter ( ) ; fTypeNameDialogField = new StringDialogField ( ) ; fTypeNameDialogField . setDialogFieldListener ( adapter ) ; fTypeNameDialogField . setLabelText ( getTypeNameLabel ( ) ) ; fSuperClassDialogField = new StringButtonDialogField ( adapter ) ; fSuperClassDialogField . setDialogFieldListener ( adapter ) ; fSuperClassDialogField . setLabelText ( getSuperClassLabel ( ) ) ; fSuperClassDialogField . setButtonLabel ( NewWizardMessages . NewTypeWizardPage_superclass_button ) ; String [ ] addButtons = new String [ ] { NewWizardMessages . NewTypeWizardPage_interfaces_add , null , NewWizardMessages . NewTypeWizardPage_interfaces_remove } ; fSuperModulesDialogField = new ListDialogField ( adapter , addButtons , new InterfacesListLabelProvider ( ) ) ; fSuperModulesDialogField . setDialogFieldListener ( adapter ) ; fSuperModulesDialogField . setTableColumns ( new ListDialogField . ColumnsDescription ( , false ) ) ; fSuperModulesDialogField . setLabelText ( getSuperModulesLabel ( ) ) ; fSuperModulesDialogField . setRemoveButtonIndex ( ) ; fTypeNameStatus = new StatusInfo ( ) ; fSuperClassStatus = new StatusInfo ( ) ; fSuperModulesStatus = new StatusInfo ( ) ; } protected String getSourceFolderLabel ( ) { return NewWizardMessages . NewTypeWizardPage_package_label ; } protected void createTypeNameControls ( Composite composite , int nColumns ) { fTypeNameDialogField . doFillIntoGrid ( composite , nColumns - ) ; DialogField . createEmptySpace ( composite ) ; Text text = fTypeNameDialogField . getTextControl ( null ) ; LayoutUtil . setWidthHint ( text , getMaxFieldWidth ( ) ) ; TextFieldNavigationHandler . install ( text ) ; } protected void setFocus ( ) { fTypeNameDialogField . setFocus ( ) ; } public void setTypeName ( String name , boolean canBeModified ) { fTypeNameDialogField . setText ( name ) ; fTypeNameDialogField . setEnabled ( canBeModified ) ; } protected void createSeparator ( Composite composite , int nColumns ) { ( new Separator ( SWT . SEPARATOR | SWT . HORIZONTAL ) ) . doFillIntoGrid ( composite , nColumns , convertHeightInCharsToPixels ( ) ) ; } protected String getSuperModulesLabel ( ) { if ( fTypeKind != INTERFACE_TYPE ) return NewWizardMessages . NewTypeWizardPage_interfaces_class_label ; return NewWizardMessages . NewTypeWizardPage_interfaces_ifc_label ; } protected String getTypeNameLabel ( ) { return NewWizardMessages . NewTypeWizardPage_typename_label ; } protected String getSuperClassLabel ( ) { return NewWizardMessages . NewTypeWizardPage_superclass_label ; } protected void createSuperClassControls ( Composite composite , int nColumns ) { fSuperClassDialogField . doFillIntoGrid ( composite , nColumns ) ; Text text = fSuperClassDialogField . getTextControl ( null ) ; LayoutUtil . setWidthHint ( text , getMaxFieldWidth ( ) ) ; } private class TypeFieldsAdapter implements IStringButtonAdapter , IDialogFieldListener , IListAdapter , SelectionListener { public void changeControlPressed ( DialogField field ) { typePageChangeControlPressed ( field ) ; } public void customButtonPressed ( ListDialogField field , int index ) { typePageCustomButtonPressed ( field , index ) ; } public void selectionChanged ( ListDialogField field ) { } public void dialogFieldChanged ( DialogField field ) { typePageDialogFieldChanged ( field ) ; } public void doubleClicked ( ListDialogField field ) { } public void widgetSelected ( SelectionEvent e ) { typePageLinkActivated ( e ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { typePageLinkActivated ( e ) ; } } private void typePageLinkActivated ( SelectionEvent e ) { ISourceFolder root = getSourceFolder ( ) ; if ( root != null ) { } else { String title = NewWizardMessages . NewTypeWizardPage_configure_templates_title ; String message = NewWizardMessages . NewTypeWizardPage_configure_templates_message ; MessageDialog . openInformation ( getShell ( ) , title , message ) ; } } private void typePageChangeControlPressed ( DialogField field ) { if ( field == fSuperClassDialogField ) { IType type = chooseSuperClass ( ) ; if ( type != null ) { fSuperClassDialogField . setText ( type . getElementName ( ) ) ; } } } private void typePageCustomButtonPressed ( DialogField field , int index ) { if ( field == fSuperModulesDialogField ) { chooseSuperModules ( ) ; List interfaces = fSuperModulesDialogField . getElements ( ) ; if ( ! interfaces . isEmpty ( ) ) { Object element = interfaces . get ( interfaces . size ( ) - ) ; fSuperModulesDialogField . editElement ( element ) ; } } } public void setSuperClass ( String name , boolean canBeModified ) { fSuperClassDialogField . setText ( name ) ; fSuperClassDialogField . setEnabled ( canBeModified ) ; } protected void createTypeMembers ( IType newType , IProgressMonitor monitor ) throws CoreException { } protected String getRubyScriptName ( String typeName ) { int index = typeName . lastIndexOf ( "" ) ; if ( index != - ) { typeName = typeName . substring ( index + ) ; } return Util . camelCaseToUnderscores ( typeName ) + RubyModelUtil . DEFAULT_SCRIPT_SUFFIX ; } public void createType ( IProgressMonitor monitor ) throws CoreException , InterruptedException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( NewWizardMessages . NewTypeWizardPage_operationdesc , ) ; ISourceFolder pack = getSourceFolder ( ) ; monitor . worked ( ) ; boolean needsSave ; IRubyScript connectedCU = null ; try { String typeName = getTypeName ( ) ; IType createdType ; int indent = ; String lineDelimiter = StubUtility . getLineDelimiterUsed ( pack . getRubyProject ( ) ) ; String cuName = getRubyScriptName ( typeName ) ; IRubyScript parentCU = pack . createRubyScript ( cuName , "" , false , new SubProgressMonitor ( monitor , ) ) ; needsSave = true ; parentCU . becomeWorkingCopy ( null , new SubProgressMonitor ( monitor , ) ) ; connectedCU = parentCU ; IBuffer buffer = parentCU . getBuffer ( ) ; String cuContent = constructSimpleTypeStub ( lineDelimiter ) ; buffer . setContents ( cuContent ) ; createdType = parentCU . getType ( typeName ) ; if ( monitor . isCanceled ( ) ) { throw new InterruptedException ( ) ; } IRubyScript cu = createdType . getRubyScript ( ) ; RubyModelUtil . reconcile ( cu ) ; if ( monitor . isCanceled ( ) ) { throw new InterruptedException ( ) ; } createTypeMembers ( createdType , new SubProgressMonitor ( monitor , ) ) ; RubyModelUtil . reconcile ( cu ) ; ISourceRange range = createdType . getSourceRange ( ) ; int length = range . getLength ( ) + ; if ( lineDelimiter . length ( ) > ) length ++ ; IBuffer buf = cu . getBuffer ( ) ; int offset = range . getOffset ( ) ; if ( offset < ) offset = ; if ( offset + length > buf . getLength ( ) ) { length = buf . getLength ( ) - offset ; } String originalContent = buf . getText ( range . getOffset ( ) , length ) ; String formattedContent = CodeFormatterUtil . format ( CodeFormatter . K_CLASS_BODY_DECLARATIONS , originalContent , indent , null , lineDelimiter , pack . getRubyProject ( ) ) ; buf . replace ( range . getOffset ( ) , length , formattedContent ) ; fCreatedType = createdType ; if ( needsSave ) { cu . commitWorkingCopy ( true , new SubProgressMonitor ( monitor , ) ) ; } else { monitor . worked ( ) ; } } finally { if ( connectedCU != null ) { connectedCU . discardWorkingCopy ( ) ; } monitor . done ( ) ; } } private String constructSimpleTypeStub ( String lineDelimiter ) { StringBuffer buf = new StringBuffer ( ) ; List < String > imports = addImports ( ) ; if ( imports != null ) { for ( String string : imports ) { buf . append ( "" ) ; buf . append ( string ) ; buf . append ( '' ) ; buf . append ( lineDelimiter ) ; } } buf . append ( "" ) ; buf . append ( getTypeName ( ) ) ; String superclass = getSuperClass ( ) ; if ( superclass != null && superclass . trim ( ) . length ( ) > && ! superclass . trim ( ) . equals ( "" ) ) { buf . append ( "" ) ; buf . append ( superclass . trim ( ) ) ; } buf . append ( lineDelimiter ) ; buf . append ( "" ) ; return buf . toString ( ) ; } protected List < String > addImports ( ) { return null ; } protected void chooseSuperModules ( ) { ISourceFolder root = getSourceFolder ( ) ; if ( root == null ) { return ; } IRubyProject project = root . getRubyProject ( ) ; SuperModuleSelectionDialog dialog = new SuperModuleSelectionDialog ( getShell ( ) , getWizard ( ) . getContainer ( ) , this , project ) ; dialog . setTitle ( getModuleDialogTitle ( ) ) ; dialog . setMessage ( NewWizardMessages . NewTypeWizardPage_InterfacesDialog_message ) ; dialog . open ( ) ; } public void setSuperModules ( List interfacesNames , boolean canBeModified ) { ArrayList interfaces = new ArrayList ( interfacesNames . size ( ) ) ; for ( Iterator iter = interfacesNames . iterator ( ) ; iter . hasNext ( ) ; ) { interfaces . add ( new InterfaceWrapper ( ( String ) iter . next ( ) ) ) ; } fSuperModulesDialogField . setElements ( interfaces ) ; fSuperModulesDialogField . setEnabled ( canBeModified ) ; } public List getSuperModules ( ) { List interfaces = fSuperModulesDialogField . getElements ( ) ; ArrayList result = new ArrayList ( interfaces . size ( ) ) ; for ( Iterator iter = interfaces . iterator ( ) ; iter . hasNext ( ) ; ) { InterfaceWrapper wrapper = ( InterfaceWrapper ) iter . next ( ) ; result . add ( wrapper . interfaceName ) ; } return result ; } public boolean addSuperModule ( String superInterface ) { return fSuperModulesDialogField . addElement ( new InterfaceWrapper ( superInterface ) ) ; } private String getModuleDialogTitle ( ) { if ( fTypeKind == INTERFACE_TYPE ) return NewWizardMessages . NewTypeWizardPage_InterfacesDialog_interface_title ; return NewWizardMessages . NewTypeWizardPage_InterfacesDialog_class_title ; } public IResource getModifiedResource ( ) { ISourceFolder pack = getSourceFolder ( ) ; if ( pack != null ) { String cuName = getRubyScriptName ( getTypeName ( ) ) ; return pack . getRubyScript ( cuName ) . getResource ( ) ; } return null ; } private void typePageDialogFieldChanged ( DialogField field ) { String fieldName = null ; if ( field == fTypeNameDialogField ) { fTypeNameStatus = typeNameChanged ( ) ; fieldName = TYPENAME ; } else if ( field == fSuperClassDialogField ) { fSuperClassStatus = superClassChanged ( ) ; fieldName = SUPER ; } else if ( field == fSuperModulesDialogField ) { fSuperModulesStatus = superInterfacesChanged ( ) ; fieldName = INTERFACES ; } else { fieldName = METHODS ; } handleFieldChanged ( fieldName ) ; } public String getSuperClass ( ) { return fSuperClassDialogField . getText ( ) ; } protected IStatus superClassChanged ( ) { StatusInfo status = new StatusInfo ( ) ; ISourceFolder root = getSourceFolder ( ) ; fSuperClassDialogField . enableButton ( root != null ) ; String sclassName = getSuperClass ( ) ; if ( sclassName . length ( ) == ) { return status ; } if ( root != null ) { } else { status . setError ( "" ) ; } return status ; } public String getTypeName ( ) { return fTypeNameDialogField . getText ( ) ; } private IStatus typeNameChanged ( ) { StatusInfo status = new StatusInfo ( ) ; fCurrType = null ; String typeName = getTypeName ( ) ; if ( typeName . length ( ) == ) { status . setError ( NewWizardMessages . NewTypeWizardPage_error_EnterTypeName ) ; return status ; } if ( ! isConstant ( typeName ) ) { status . setError ( "" ) ; return status ; } return status ; } protected void doStatusUpdate ( ) { IStatus [ ] status = new IStatus [ ] { fContainerStatus , fTypeNameStatus , fSuperClassStatus , fSuperModulesStatus } ; updateStatus ( status ) ; } protected void handleFieldChanged ( String fieldName ) { super . handleFieldChanged ( fieldName ) ; if ( fieldName == CONTAINER ) { fTypeNameStatus = typeNameChanged ( ) ; fSuperClassStatus = superClassChanged ( ) ; fSuperModulesStatus = superInterfacesChanged ( ) ; } doStatusUpdate ( ) ; } protected void initTypePage ( IRubyElement elem ) { String initSuperclass = "" ; ArrayList initSuperinterfaces = new ArrayList ( ) ; IRubyProject project = null ; ISourceFolder folder = getSourceFolder ( ) ; IType enclosingType = null ; if ( elem != null ) { project = elem . getRubyProject ( ) ; IType typeInCU = ( IType ) elem . getAncestor ( IRubyElement . TYPE ) ; if ( typeInCU != null ) { if ( typeInCU . getRubyScript ( ) != null ) { enclosingType = typeInCU ; } } else { IRubyScript cu = ( IRubyScript ) elem . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) { enclosingType = cu . findPrimaryType ( ) ; } } } String typeName = "" ; ITextSelection selection = getCurrentTextSelection ( ) ; if ( selection != null ) { String text = selection . getText ( ) ; if ( text != null && RubyConventions . validateRubyTypeName ( text ) . isOK ( ) ) { typeName = text ; } } if ( enclosingType != null ) { typeName = enclosingType . getElementName ( ) ; try { initSuperclass = enclosingType . getSuperclassName ( ) ; initSuperinterfaces . addAll ( Arrays . asList ( enclosingType . getIncludedModuleNames ( ) ) ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } setSourceFolder ( folder , true ) ; setTypeName ( typeName , true ) ; setSuperClass ( initSuperclass , true ) ; } private boolean isConstant ( String className ) { if ( className == null || className . length ( ) == ) return false ; int namespaceDelimeterIndex = className . indexOf ( "" ) ; if ( namespaceDelimeterIndex != - ) { return isConstant ( className . substring ( , namespaceDelimeterIndex ) ) && isConstant ( className . substring ( namespaceDelimeterIndex + ) ) ; } return className . matches ( "" ) ; } protected IStatus superInterfacesChanged ( ) { StatusInfo status = new StatusInfo ( ) ; ISourceFolder root = getSourceFolder ( ) ; fSuperModulesDialogField . enableButton ( , root != null ) ; if ( root != null ) { List elements = fSuperModulesDialogField . getElements ( ) ; int nElements = elements . size ( ) ; for ( int i = ; i < nElements ; i ++ ) { } } return status ; } protected IType chooseSuperClass ( ) { ISourceFolder root = getSourceFolder ( ) ; if ( root == null ) { return null ; } IRubyElement [ ] elements = new IRubyElement [ ] { root . getRubyProject ( ) } ; IRubySearchScope scope = SearchEngine . createRubySearchScope ( elements ) ; TypeSelectionDialog2 dialog = new TypeSelectionDialog2 ( getShell ( ) , false , getWizard ( ) . getContainer ( ) , scope , IRubySearchConstants . CLASS ) ; dialog . setTitle ( NewWizardMessages . NewTypeWizardPage_SuperClassDialog_title ) ; dialog . setMessage ( NewWizardMessages . NewTypeWizardPage_SuperClassDialog_message ) ; dialog . setFilter ( getSuperClass ( ) ) ; if ( dialog . open ( ) == Window . OK ) { return ( IType ) dialog . getFirstResult ( ) ; } return null ; } public IType getCreatedType ( ) { return fCreatedType ; } } package org . rubypeople . rdt . ui . wizards ; import java . util . ArrayList ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . model . WorkbenchContentProvider ; import org . eclipse . ui . model . WorkbenchLabelProvider ; import org . rubypeople . rdt . internal . ui . IUIConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . TypedViewerFilter ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . EditVariableEntryDialog ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . MultipleFolderSelectionDialog ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . NewVariableEntryDialog ; public final class BuildPathDialogAccess { private BuildPathDialogAccess ( ) { } public static IPath [ ] chooseSourceFolderEntries ( Shell shell , IPath initialSelection , IPath [ ] usedEntries ) { if ( usedEntries == null ) { throw new IllegalArgumentException ( ) ; } String title = NewWizardMessages . BuildPathDialogAccess_ExistingSourceFolderDialog_new_title ; String message = NewWizardMessages . BuildPathDialogAccess_ExistingSourceFolderDialog_new_description ; return internalChooseFolderEntry ( shell , initialSelection , usedEntries , title , message ) ; } private static IPath [ ] internalChooseFolderEntry ( Shell shell , IPath initialSelection , IPath [ ] usedEntries , String title , String message ) { Class [ ] acceptedClasses = new Class [ ] { IProject . class , IFolder . class } ; ArrayList usedContainers = new ArrayList ( usedEntries . length ) ; IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( int i = ; i < usedEntries . length ; i ++ ) { IResource resource = root . findMember ( usedEntries [ i ] ) ; if ( resource instanceof IContainer ) { usedContainers . add ( resource ) ; } } IResource focus = initialSelection != null ? root . findMember ( initialSelection ) : null ; Object [ ] used = usedContainers . toArray ( ) ; MultipleFolderSelectionDialog dialog = new MultipleFolderSelectionDialog ( shell , new WorkbenchLabelProvider ( ) , new WorkbenchContentProvider ( ) ) ; dialog . setExisting ( used ) ; dialog . setTitle ( title ) ; dialog . setMessage ( message ) ; dialog . setHelpAvailable ( false ) ; dialog . addFilter ( new TypedViewerFilter ( acceptedClasses , used ) ) ; dialog . setInput ( root ) ; dialog . setInitialFocus ( focus ) ; if ( dialog . open ( ) == Window . OK ) { Object [ ] elements = dialog . getResult ( ) ; IPath [ ] res = new IPath [ elements . length ] ; for ( int i = ; i < res . length ; i ++ ) { IResource elem = ( IResource ) elements [ i ] ; res [ i ] = elem . getFullPath ( ) ; } return res ; } return null ; } public static IPath [ ] chooseExternalFolderEntries ( Shell shell ) { String lastUsedPath = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . get ( IUIConstants . DIALOGSTORE_LASTEXTJAR ) ; if ( lastUsedPath == null ) { lastUsedPath = "" ; } DirectoryDialog dialog = new DirectoryDialog ( shell , SWT . MULTI ) ; dialog . setText ( NewWizardMessages . BuildPathDialogAccess_ExtJARArchiveDialog_new_title ) ; dialog . setFilterPath ( lastUsedPath ) ; String res = dialog . open ( ) ; if ( res == null ) { return null ; } String dirName = dialog . getText ( ) ; IPath filterPath = Path . fromOSString ( dialog . getFilterPath ( ) ) ; IPath [ ] elems = { filterPath } ; RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( IUIConstants . DIALOGSTORE_LASTEXTJAR , dialog . getFilterPath ( ) ) ; return elems ; } public static IPath configureExternalFolderEntry ( Shell shell , IPath initialEntry ) { if ( initialEntry == null ) { throw new IllegalArgumentException ( ) ; } String lastUsedPath = initialEntry . removeLastSegments ( ) . toOSString ( ) ; DirectoryDialog dialog = new DirectoryDialog ( shell , SWT . SINGLE ) ; dialog . setText ( NewWizardMessages . BuildPathDialogAccess_ExtJARArchiveDialog_edit_title ) ; dialog . setFilterPath ( lastUsedPath ) ; String res = dialog . open ( ) ; if ( res == null ) { return null ; } RubyPlugin . getDefault ( ) . getDialogSettings ( ) . put ( IUIConstants . DIALOGSTORE_LASTEXTJAR , dialog . getFilterPath ( ) ) ; return Path . fromOSString ( res ) . makeAbsolute ( ) ; } public static IPath [ ] chooseVariableEntries ( Shell shell , IPath [ ] existingPaths ) { if ( existingPaths == null ) { throw new IllegalArgumentException ( ) ; } NewVariableEntryDialog dialog = new NewVariableEntryDialog ( shell ) ; if ( dialog . open ( ) == Window . OK ) { return dialog . getResult ( ) ; } return null ; } public static IPath configureVariableEntry ( Shell shell , IPath initialEntryPath , IPath [ ] existingPaths ) { if ( existingPaths == null ) { throw new IllegalArgumentException ( ) ; } EditVariableEntryDialog dialog = new EditVariableEntryDialog ( shell , initialEntryPath , existingPaths ) ; if ( dialog . open ( ) == Window . OK ) { return dialog . getPath ( ) ; } return null ; } } package org . rubypeople . rdt . ui . wizards ; import java . lang . reflect . InvocationTargetException ; import java . net . URI ; import org . eclipse . core . filesystem . URIUtil ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . corext . util . BusyIndicatorRunnableContext ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . wizards . IStatusChangeListener ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . buildpaths . BuildPathsBlock ; public class RubyCapabilityConfigurationPage extends NewElementWizardPage { private static final String PAGE_NAME = "" ; private IRubyProject fRubyProject ; private BuildPathsBlock fBuildPathsBlock ; public RubyCapabilityConfigurationPage ( ) { super ( PAGE_NAME ) ; fRubyProject = null ; setTitle ( NewWizardMessages . RubyCapabilityConfigurationPage_title ) ; setDescription ( NewWizardMessages . RubyCapabilityConfigurationPage_description ) ; } private BuildPathsBlock getBuildPathsBlock ( ) { if ( fBuildPathsBlock == null ) { IStatusChangeListener listener = new IStatusChangeListener ( ) { public void statusChanged ( IStatus status ) { updateStatus ( status ) ; } } ; fBuildPathsBlock = new BuildPathsBlock ( new BusyIndicatorRunnableContext ( ) , listener , , useNewSourcePage ( ) , null ) ; } return fBuildPathsBlock ; } protected boolean useNewSourcePage ( ) { return false ; } public void init ( IRubyProject jproject , IPath defaultOutputLocation , ILoadpathEntry [ ] defaultEntries , boolean defaultsOverrideExistingClasspath ) { if ( ! defaultsOverrideExistingClasspath && jproject . exists ( ) && jproject . getProject ( ) . getFile ( "" ) . exists ( ) ) { defaultOutputLocation = null ; defaultEntries = null ; } getBuildPathsBlock ( ) . init ( jproject , defaultOutputLocation , defaultEntries ) ; fRubyProject = jproject ; } public void createControl ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; composite . setLayout ( new GridLayout ( , false ) ) ; Control control = getBuildPathsBlock ( ) . createControl ( composite ) ; control . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Dialog . applyDialogFont ( composite ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( composite , IRubyHelpContextIds . NEW_JAVAPROJECT_WIZARD_PAGE ) ; setControl ( composite ) ; } public ILoadpathEntry [ ] getRawClassPath ( ) { return getBuildPathsBlock ( ) . getRawClassPath ( ) ; } public IRubyProject getRubyProject ( ) { return fRubyProject ; } public IRunnableWithProgress getRunnable ( ) { if ( getRubyProject ( ) != null ) { return new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { try { configureRubyProject ( monitor ) ; } catch ( CoreException e ) { throw new InvocationTargetException ( e ) ; } } } ; } return null ; } public static void createProject ( IProject project , IPath locationPath , IProgressMonitor monitor ) throws CoreException { createProject ( project , locationPath != null ? URIUtil . toURI ( locationPath ) : null , monitor ) ; } public static void createProject ( IProject project , URI locationURI , IProgressMonitor monitor ) throws CoreException { BuildPathsBlock . createProject ( project , locationURI , monitor ) ; } public void configureRubyProject ( IProgressMonitor monitor ) throws CoreException , InterruptedException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } int nSteps = ; monitor . beginTask ( NewWizardMessages . RubyCapabilityConfigurationPage_op_desc_ruby , nSteps ) ; try { IProject project = getRubyProject ( ) . getProject ( ) ; BuildPathsBlock . addRubyNature ( project , new SubProgressMonitor ( monitor , ) ) ; getBuildPathsBlock ( ) . configureRubyProject ( new SubProgressMonitor ( monitor , ) ) ; } catch ( OperationCanceledException e ) { throw new InterruptedException ( ) ; } finally { monitor . done ( ) ; } } } package org . rubypeople . rdt . ui . wizards ; import org . eclipse . jface . wizard . IWizardPage ; import org . rubypeople . rdt . core . ILoadpathEntry ; public interface ILoadpathContainerPage extends IWizardPage { public boolean finish ( ) ; public ILoadpathEntry getSelection ( ) ; public void setSelection ( ILoadpathEntry containerEntry ) ; } package org . rubypeople . rdt . ui . wizards ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . SelectionButtonDialogFieldGroup ; public class NewClassWizardPage extends NewTypeWizardPage { private final static String PAGE_NAME = "" ; private final static String SETTINGS_CREATECONSTR = "" ; private SelectionButtonDialogFieldGroup fMethodStubsButtons ; public NewClassWizardPage ( ) { super ( true , PAGE_NAME ) ; setTitle ( NewWizardMessages . NewClassWizardPage_title ) ; setDescription ( NewWizardMessages . NewClassWizardPage_description ) ; String [ ] buttonNames3 = new String [ ] { NewWizardMessages . NewClassWizardPage_methods_constructors } ; fMethodStubsButtons = new SelectionButtonDialogFieldGroup ( SWT . CHECK , buttonNames3 , ) ; fMethodStubsButtons . setLabelText ( NewWizardMessages . NewClassWizardPage_methods_label ) ; } public void init ( IStructuredSelection selection ) { IRubyElement jelem = getInitialRubyElement ( selection ) ; initContainerPage ( jelem ) ; initTypePage ( jelem ) ; doStatusUpdate ( ) ; boolean createConstructors = false ; boolean createUnimplemented = true ; IDialogSettings dialogSettings = getDialogSettings ( ) ; if ( dialogSettings != null ) { IDialogSettings section = dialogSettings . getSection ( PAGE_NAME ) ; if ( section != null ) { createConstructors = section . getBoolean ( SETTINGS_CREATECONSTR ) ; } } setMethodStubSelection ( createConstructors , true ) ; } public void createControl ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; int nColumns = ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = nColumns ; composite . setLayout ( layout ) ; createContainerControls ( composite , nColumns ) ; createSeparator ( composite , nColumns ) ; createTypeNameControls ( composite , nColumns ) ; createSuperClassControls ( composite , nColumns ) ; createMethodStubSelectionControls ( composite , nColumns ) ; setControl ( composite ) ; Dialog . applyDialogFont ( composite ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( composite , IRubyHelpContextIds . NEW_CLASS_WIZARD_PAGE ) ; } public void setVisible ( boolean visible ) { super . setVisible ( visible ) ; if ( visible ) { setFocus ( ) ; } else { IDialogSettings dialogSettings = getDialogSettings ( ) ; if ( dialogSettings != null ) { IDialogSettings section = dialogSettings . getSection ( PAGE_NAME ) ; if ( section == null ) { section = dialogSettings . addNewSection ( PAGE_NAME ) ; } section . put ( SETTINGS_CREATECONSTR , isCreateConstructors ( ) ) ; } } } private void createMethodStubSelectionControls ( Composite composite , int nColumns ) { Control labelControl = fMethodStubsButtons . getLabelControl ( composite ) ; LayoutUtil . setHorizontalSpan ( labelControl , nColumns ) ; DialogField . createEmptySpace ( composite ) ; Control buttonGroup = fMethodStubsButtons . getSelectionButtonsGroup ( composite ) ; LayoutUtil . setHorizontalSpan ( buttonGroup , nColumns - ) ; } public boolean isCreateConstructors ( ) { return fMethodStubsButtons . isSelected ( ) ; } public void setMethodStubSelection ( boolean createConstructors , boolean canBeModified ) { fMethodStubsButtons . setSelection ( , createConstructors ) ; fMethodStubsButtons . setEnabled ( canBeModified ) ; } protected void createTypeMembers ( IType type , IProgressMonitor monitor ) throws CoreException { boolean doConstr = isCreateConstructors ( ) ; if ( doConstr ) { StringBuffer buf = new StringBuffer ( ) ; final String lineDelim = "" ; buf . append ( "" ) ; buf . append ( lineDelim ) ; buf . append ( "" ) ; buf . append ( lineDelim ) ; buf . append ( "" ) ; buf . append ( lineDelim ) ; type . createMethod ( buf . toString ( ) , null , false , null ) ; } if ( monitor != null ) { monitor . done ( ) ; } } } package org . rubypeople . rdt . ui . wizards ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . codemanipulation . StubUtility ; import org . rubypeople . rdt . internal . ui . dialogs . TextFieldNavigationHandler ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . LayoutUtil ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . Separator ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; public class NewFileWizardPage extends NewContainerWizardPage { private StringDialogField fScriptNameDialogField ; private IRubyScript fCreatedScript ; private final static String PAGE_NAME = "" ; public NewFileWizardPage ( ) { super ( PAGE_NAME ) ; setTitle ( NewWizardMessages . NewFileWizardPage_title ) ; setDescription ( NewWizardMessages . NewFileWizardPage_description ) ; fScriptNameDialogField = new StringDialogField ( ) ; fScriptNameDialogField . setLabelText ( getScriptNameLabel ( ) ) ; fScriptNameDialogField . setText ( getDefaultScriptName ( ) ) ; } private String getDefaultScriptName ( ) { return "" ; } protected String getScriptNameLabel ( ) { return NewWizardMessages . NewFileWizardPage_scriptname_label ; } public void createScript ( IProgressMonitor monitor ) throws RubyModelException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( NewWizardMessages . NewTypeWizardPage_operationdesc , ) ; ISourceFolder pack = getSourceFolder ( ) ; monitor . worked ( ) ; try { String lineDelimiter = StubUtility . getLineDelimiterUsed ( pack . getRubyProject ( ) ) ; String cuName = getRubyScriptName ( ) ; String contents = "" + lineDelimiter + "" + lineDelimiter + "" ; fCreatedScript = pack . createRubyScript ( cuName , contents , false , new SubProgressMonitor ( monitor , ) ) ; } finally { monitor . done ( ) ; } } public IResource getModifiedResource ( ) { ISourceFolder pack = getSourceFolder ( ) ; if ( pack != null ) { String cuName = getRubyScriptName ( ) ; return pack . getRubyScript ( cuName ) . getResource ( ) ; } return null ; } public String getRubyScriptName ( ) { return fScriptNameDialogField . getText ( ) ; } public IRubyElement getCreatedScript ( ) { return fCreatedScript ; } public void createControl ( Composite parent ) { initializeDialogUnits ( parent ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; composite . setFont ( parent . getFont ( ) ) ; int nColumns = ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = nColumns ; composite . setLayout ( layout ) ; createContainerControls ( composite , nColumns ) ; createSeparator ( composite , nColumns ) ; createScriptNameControls ( composite , nColumns ) ; setControl ( composite ) ; Dialog . applyDialogFont ( composite ) ; } protected void createScriptNameControls ( Composite composite , int nColumns ) { fScriptNameDialogField . doFillIntoGrid ( composite , nColumns - ) ; DialogField . createEmptySpace ( composite ) ; Text text = fScriptNameDialogField . getTextControl ( null ) ; LayoutUtil . setWidthHint ( text , getMaxFieldWidth ( ) ) ; TextFieldNavigationHandler . install ( text ) ; } protected void createSeparator ( Composite composite , int nColumns ) { ( new Separator ( SWT . SEPARATOR | SWT . HORIZONTAL ) ) . doFillIntoGrid ( composite , nColumns , convertHeightInCharsToPixels ( ) ) ; } public void init ( IStructuredSelection selection ) { IRubyElement jelem = getInitialRubyElement ( selection ) ; initContainerPage ( jelem ) ; } @ Override protected void handleFieldChanged ( String fieldName ) { super . handleFieldChanged ( fieldName ) ; updateStatus ( fContainerStatus ) ; } } package org . rubypeople . rdt . ui . wizards ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; public interface ILoadpathContainerPageExtension { public void initialize ( IRubyProject project , ILoadpathEntry [ ] currentEntries ) ; } package org . rubypeople . rdt . ui . wizards ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . wizard . WizardPage ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . dialogs . StatusUtil ; public abstract class NewElementWizardPage extends WizardPage { private IStatus fCurrStatus ; private boolean fPageVisible ; public NewElementWizardPage ( String name ) { super ( name ) ; fPageVisible = false ; fCurrStatus = new StatusInfo ( ) ; } public void setVisible ( boolean visible ) { super . setVisible ( visible ) ; fPageVisible = visible ; if ( visible && fCurrStatus . matches ( IStatus . ERROR ) ) { StatusInfo status = new StatusInfo ( ) ; status . setError ( "" ) ; fCurrStatus = status ; } updateStatus ( fCurrStatus ) ; } protected void updateStatus ( IStatus status ) { fCurrStatus = status ; setPageComplete ( ! status . matches ( IStatus . ERROR ) ) ; if ( fPageVisible ) { StatusUtil . applyToStatusLine ( this , status ) ; } } protected void updateStatus ( IStatus [ ] status ) { updateStatus ( StatusUtil . getMostSevere ( status ) ) ; } } package org . rubypeople . rdt . ui . wizards ; import org . rubypeople . rdt . core . ILoadpathEntry ; public interface ILoadpathContainerPageExtension2 { public ILoadpathEntry [ ] getNewContainers ( ) ; } package org . rubypeople . rdt . ui ; import org . eclipse . core . runtime . ListenerList ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . widgets . Display ; import org . osgi . service . prefs . BackingStoreException ; import org . eclipse . jface . preference . IPreferenceStore ; public class EclipsePreferencesAdapter implements IPreferenceStore { private class PreferenceChangeListener implements IEclipsePreferences . IPreferenceChangeListener { public void preferenceChange ( final IEclipsePreferences . PreferenceChangeEvent event ) { if ( Display . getCurrent ( ) == null ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { firePropertyChangeEvent ( event . getKey ( ) , event . getOldValue ( ) , event . getNewValue ( ) ) ; } } ) ; } else { firePropertyChangeEvent ( event . getKey ( ) , event . getOldValue ( ) , event . getNewValue ( ) ) ; } } } private ListenerList fListeners = new ListenerList ( ListenerList . IDENTITY ) ; private IEclipsePreferences . IPreferenceChangeListener fListener = new PreferenceChangeListener ( ) ; private final IScopeContext fContext ; private final String fQualifier ; public EclipsePreferencesAdapter ( IScopeContext context , String qualifier ) { fContext = context ; fQualifier = qualifier ; } private IEclipsePreferences getNode ( ) { return fContext . getNode ( fQualifier ) ; } public void addPropertyChangeListener ( IPropertyChangeListener listener ) { if ( fListeners . size ( ) == ) getNode ( ) . addPreferenceChangeListener ( fListener ) ; fListeners . add ( listener ) ; } public void removePropertyChangeListener ( IPropertyChangeListener listener ) { fListeners . remove ( listener ) ; if ( fListeners . size ( ) == ) { getNode ( ) . removePreferenceChangeListener ( fListener ) ; } } public boolean contains ( String name ) { return getNode ( ) . get ( name , null ) != null ; } public void firePropertyChangeEvent ( String name , Object oldValue , Object newValue ) { PropertyChangeEvent event = new PropertyChangeEvent ( this , name , oldValue , newValue ) ; Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) ( ( IPropertyChangeListener ) listeners [ i ] ) . propertyChange ( event ) ; } public boolean getBoolean ( String name ) { return getNode ( ) . getBoolean ( name , getDefaultBoolean ( name ) ) ; } public boolean getDefaultBoolean ( String name ) { return getDefaultNode ( ) . getBoolean ( name , BOOLEAN_DEFAULT_DEFAULT ) ; } private IEclipsePreferences getDefaultNode ( ) { return new DefaultScope ( ) . getNode ( fQualifier ) ; } public double getDefaultDouble ( String name ) { return getDefaultNode ( ) . getDouble ( name , DOUBLE_DEFAULT_DEFAULT ) ; } public float getDefaultFloat ( String name ) { return getDefaultNode ( ) . getFloat ( name , FLOAT_DEFAULT_DEFAULT ) ; } public int getDefaultInt ( String name ) { return getDefaultNode ( ) . getInt ( name , INT_DEFAULT_DEFAULT ) ; } public long getDefaultLong ( String name ) { return getDefaultNode ( ) . getLong ( name , LONG_DEFAULT_DEFAULT ) ; } public String getDefaultString ( String name ) { return getDefaultNode ( ) . get ( name , STRING_DEFAULT_DEFAULT ) ; } public double getDouble ( String name ) { return getNode ( ) . getDouble ( name , getDefaultDouble ( name ) ) ; } public float getFloat ( String name ) { return getNode ( ) . getFloat ( name , getDefaultFloat ( name ) ) ; } public int getInt ( String name ) { return getNode ( ) . getInt ( name , getDefaultInt ( name ) ) ; } public long getLong ( String name ) { return getNode ( ) . getLong ( name , getDefaultLong ( name ) ) ; } public String getString ( String name ) { return getNode ( ) . get ( name , getDefaultString ( name ) ) ; } public boolean isDefault ( String name ) { return false ; } public boolean needsSaving ( ) { try { return getNode ( ) . keys ( ) . length > ; } catch ( BackingStoreException e ) { } return true ; } public void putValue ( String name , String value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , double value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , float value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , int value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , long value ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , String defaultObject ) { throw new UnsupportedOperationException ( ) ; } public void setDefault ( String name , boolean value ) { throw new UnsupportedOperationException ( ) ; } public void setToDefault ( String name ) { getNode ( ) . remove ( name ) ; } public void setValue ( String name , double value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , float value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , int value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , long value ) { throw new UnsupportedOperationException ( ) ; } public void setValue ( String name , String value ) { getNode ( ) . put ( name , value ) ; } public void setValue ( String name , boolean value ) { getNode ( ) . putBoolean ( name , value ) ; } public void flush ( ) { try { getNode ( ) . flush ( ) ; } catch ( BackingStoreException e ) { e . printStackTrace ( ) ; } } } package org . rubypeople . rdt . ui ; import java . io . UnsupportedEncodingException ; import java . net . URLDecoder ; import java . net . URLEncoder ; import java . util . ArrayList ; import java . util . NoSuchElementException ; import java . util . StringTokenizer ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . ui . texteditor . AbstractTextEditor ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . preferences . PreferencesMessages ; import org . rubypeople . rdt . internal . ui . preferences . formatter . ProfileManager ; import org . rubypeople . rdt . internal . ui . text . IRubyColorConstants ; import org . rubypeople . rdt . internal . ui . text . ruby . ProposalSorterRegistry ; import org . rubypeople . rdt . internal . ui . text . spelling . SpellCheckEngine ; import org . rubypeople . rdt . internal . ui . text . spelling . engine . ISpellCheckPreferenceKeys ; import org . rubypeople . rdt . launching . RubyRuntime ; public class PreferenceConstants { private PreferenceConstants ( ) { } private static String fgDefaultEncoding = System . getProperty ( "" ) ; public static final String DEBUGGER_USE_RUBY_DEBUG = "" ; public static final String TEMPLATES_USE_CODEFORMATTER = "" ; private static final String LOADPATH_RUBYVMLIBRARY_INDEX = PreferenceConstants . NEWPROJECT_JRELIBRARY_INDEX ; private static final String LOADPATH_RUBYVMLIBRARY_LIST = PreferenceConstants . NEWPROJECT_JRELIBRARY_LIST ; public static final String NEWPROJECT_JRELIBRARY_LIST = "" ; public static final String NEWPROJECT_JRELIBRARY_INDEX = "" ; public static final String APPEARANCE_METHOD_PARAMETER_NAMES = "" ; public static final String EDITOR_FOLDING_ENABLED = "" ; public static final String EDITOR_FOLDING_PROVIDER = "" ; public static final String EDITOR_FOLDING_RDOC = "" ; public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS = "" ; public static final String EDITOR_FOLDING_INNERTYPES = "" ; public static final String EDITOR_FOLDING_METHODS = "" ; public static final String EDITOR_BG_SUFFIX = "" ; public static final String EDITOR_BG_ENABLED_SUFFIX = "" ; public static final String EDITOR_BOLD_SUFFIX = "" ; public static final String EDITOR_ITALIC_SUFFIX = "" ; public final static String EDITOR_CORRECTION_INDICATION = "" ; public static final String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE = "" ; public static final String EDITOR_SHOW_SEGMENTS = "" ; public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE = "" ; public final static String EDITOR_SUB_WORD_NAVIGATION = "" ; public static final String EDITOR_QUICKASSIST_LIGHTBULB = "" ; public static final String APPEARANCE_MEMBER_SORT_ORDER = "" ; public static final String APPEARANCE_VISIBILITY_SORT_ORDER = "" ; public static final String APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER = "" ; public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES = "" ; public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW = "" ; public final static String EDITOR_TEXT_FONT = "" ; public static final String FORMATTER_PROFILE = "" ; public static final String BROWSING_STACK_VERTICALLY = "" ; public static final String LINK_BROWSING_PROJECTS_TO_EDITOR = "" ; public static final String LINK_BROWSING_TYPES_TO_EDITOR = "" ; public static final String LINK_BROWSING_MEMBERS_TO_EDITOR = "" ; public static final String LINK_TYPEHIERARCHY_TO_EDITOR = "" ; public static final String EDITOR_STRIKETHROUGH_SUFFIX = "" ; public static final String EDITOR_UNDERLINE_SUFFIX = "" ; public final static String EDITOR_MATCHING_BRACKETS = "" ; public final static String EDITOR_MATCHING_BRACKETS_COLOR = "" ; public final static String HOVERS_ENABLED = "" ; public final static String CODEASSIST_AUTOACTIVATION = "" ; public final static String CODEASSIST_AUTOACTIVATION_DELAY = "" ; public final static String CODEASSIST_AUTOINSERT = "" ; public final static String CODEASSIST_INSERT_COMPLETION = "" ; public final static String CODEASSIST_FILL_ARGUMENT_NAMES = "" ; public final static String CODEASSIST_FILL_METHOD_BLOCK_ARGUMENTS = "" ; public final static String CODEASSIST_PROPOSALS_BACKGROUND = "" ; public final static String CODEASSIST_PROPOSALS_FOREGROUND = "" ; public final static String CODEASSIST_PARAMETERS_BACKGROUND = "" ; public final static String CODEASSIST_PARAMETERS_FOREGROUND = "" ; public final static String CODEASSIST_REPLACEMENT_BACKGROUND = "" ; public final static String CODEASSIST_REPLACEMENT_FOREGROUND = "" ; public final static String CODEASSIST_PREFIX_COMPLETION = "" ; public final static String EDITOR_CLOSE_STRINGS = "" ; public final static String EDITOR_CLOSE_BRACKETS = "" ; public final static String EDITOR_CLOSE_BRACES = "" ; public final static String EDITOR_END_STATEMENTS = "" ; public final static String EDITOR_SMART_HOME_END = AbstractTextEditor . PREFERENCE_NAVIGATION_SMART_HOME_END ; public static final String EDITOR_MARK_OCCURRENCES = "" ; public static final String EDITOR_STICKY_OCCURRENCES = "" ; public static final String EDITOR_MARK_TYPE_OCCURRENCES = "" ; public static final String EDITOR_MARK_METHOD_OCCURRENCES = "" ; public static final String EDITOR_MARK_FIELD_OCCURRENCES = "" ; public static final String EDITOR_MARK_CONSTANT_OCCURRENCES = "" ; public static final String EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES = "" ; public static final String EDITOR_MARK_METHOD_EXIT_POINTS = "" ; public static final String EDITOR_USER_KEYWORDS = "" ; public static final String SRCBIN_FOLDERS_IN_NEWPROJ = "" ; public static final String SRCBIN_SRCNAME = "" ; public static final String TYPEFILTER_ENABLED = "" ; public static final String SHOW_CU_CHILDREN = "" ; public static final String LINK_PACKAGES_TO_EDITOR = "" ; public static final String EDITOR_TEXT_HOVER_MODIFIERS = "" ; public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS = "" ; public static final String ID_BESTMATCH_HOVER = "" ; public static final String ID_SOURCE_HOVER = "" ; public static final String SEARCH_USE_REDUCED_MENU = "" ; public final static String SPELLING_IGNORE_DIGITS = ISpellCheckPreferenceKeys . SPELLING_IGNORE_DIGITS ; public final static String SPELLING_IGNORE_MIXED = ISpellCheckPreferenceKeys . SPELLING_IGNORE_MIXED ; public final static String SPELLING_IGNORE_SENTENCE = ISpellCheckPreferenceKeys . SPELLING_IGNORE_SENTENCE ; public final static String SPELLING_IGNORE_UPPER = ISpellCheckPreferenceKeys . SPELLING_IGNORE_UPPER ; public final static String SPELLING_IGNORE_URLS = ISpellCheckPreferenceKeys . SPELLING_IGNORE_URLS ; public final static String SPELLING_LOCALE = ISpellCheckPreferenceKeys . SPELLING_LOCALE ; public final static String SPELLING_PROPOSAL_THRESHOLD = ISpellCheckPreferenceKeys . SPELLING_PROPOSAL_THRESHOLD ; public final static String SPELLING_USER_DICTIONARY = ISpellCheckPreferenceKeys . SPELLING_USER_DICTIONARY ; public final static String SPELLING_ENABLE_CONTENTASSIST = ISpellCheckPreferenceKeys . SPELLING_ENABLE_CONTENTASSIST ; public static final String LINK_BROWSING_PACKAGES_TO_EDITOR = "" ; public static final String DOUBLE_CLICK = "" ; public static final String DOUBLE_CLICK_GOES_INTO = "" ; public static final String DOUBLE_CLICK_EXPANDS = "" ; public static final String CODEASSIST_EXCLUDED_CATEGORIES = "" ; public static final String CODEASSIST_CATEGORY_ORDER = "" ; public static final String CODEASSIST_SORTER = "" ; public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_RUBY = "" ; private static String getDefaultRubyVMLibraries ( ) { StringBuffer buf = new StringBuffer ( ) ; ILoadpathEntry cntentry = getRubyVMContainerEntry ( ) ; buf . append ( encodeRubyVMLibrary ( PreferencesMessages . NewRubyProjectPreferencePage_jre_container_description , new ILoadpathEntry [ ] { cntentry } ) ) ; buf . append ( '' ) ; ILoadpathEntry varentry = getRubyVMVariableEntry ( ) ; buf . append ( encodeRubyVMLibrary ( PreferencesMessages . NewRubyProjectPreferencePage_jre_variable_description , new ILoadpathEntry [ ] { varentry } ) ) ; buf . append ( '' ) ; return buf . toString ( ) ; } private static ILoadpathEntry getRubyVMVariableEntry ( ) { return RubyCore . newVariableEntry ( new Path ( RubyRuntime . RUBYLIB_VARIABLE ) ) ; } public static String encodeRubyVMLibrary ( String desc , ILoadpathEntry [ ] cpentries ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < cpentries . length ; i ++ ) { ILoadpathEntry entry = cpentries [ i ] ; buf . append ( encode ( desc ) ) ; buf . append ( '' ) ; buf . append ( entry . getEntryKind ( ) ) ; buf . append ( '' ) ; buf . append ( encodePath ( entry . getPath ( ) ) ) ; buf . append ( '' ) ; buf . append ( entry . isExported ( ) ) ; buf . append ( '' ) ; } return buf . toString ( ) ; } private static String encodePath ( IPath path ) { if ( path == null ) { return "" ; } else if ( path . isEmpty ( ) ) { return "" ; } else { return encode ( path . toPortableString ( ) ) ; } } private static String encode ( String str ) { try { return URLEncoder . encode ( str , fgDefaultEncoding ) ; } catch ( UnsupportedEncodingException e ) { RubyPlugin . log ( e ) ; } return "" ; } public static void initializeDefaultValues ( IPreferenceStore store ) { store . setDefault ( PreferenceConstants . EDITOR_SHOW_SEGMENTS , false ) ; store . setDefault ( LOADPATH_RUBYVMLIBRARY_LIST , getDefaultRubyVMLibraries ( ) ) ; store . setDefault ( LOADPATH_RUBYVMLIBRARY_INDEX , ) ; store . setDefault ( PreferenceConstants . DEBUGGER_USE_RUBY_DEBUG , false ) ; store . setDefault ( PreferenceConstants . LINK_PACKAGES_TO_EDITOR , false ) ; store . setDefault ( PreferenceConstants . LINK_TYPEHIERARCHY_TO_EDITOR , false ) ; store . setDefault ( PreferenceConstants . DOUBLE_CLICK , PreferenceConstants . DOUBLE_CLICK_EXPANDS ) ; store . setDefault ( PreferenceConstants . LINK_BROWSING_PACKAGES_TO_EDITOR , true ) ; store . setDefault ( PreferenceConstants . LINK_BROWSING_PROJECTS_TO_EDITOR , true ) ; store . setDefault ( PreferenceConstants . LINK_BROWSING_TYPES_TO_EDITOR , true ) ; store . setDefault ( PreferenceConstants . LINK_BROWSING_MEMBERS_TO_EDITOR , true ) ; store . setDefault ( PreferenceConstants . SEARCH_USE_REDUCED_MENU , false ) ; store . setDefault ( PreferenceConstants . APPEARANCE_MEMBER_SORT_ORDER , "" ) ; store . setDefault ( PreferenceConstants . APPEARANCE_VISIBILITY_SORT_ORDER , "" ) ; store . setDefault ( PreferenceConstants . APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER , false ) ; store . setDefault ( "" , true ) ; store . setDefault ( PreferenceConstants . APPEARANCE_COMPRESS_PACKAGE_NAMES , false ) ; store . setDefault ( PreferenceConstants . APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW , "" ) ; store . setDefault ( PreferenceConstants . BROWSING_STACK_VERTICALLY , false ) ; store . setDefault ( PreferenceConstants . SHOW_CU_CHILDREN , true ) ; store . setDefault ( PreferenceConstants . EDITOR_CORRECTION_INDICATION , true ) ; store . setDefault ( PreferenceConstants . TYPEFILTER_ENABLED , "" ) ; store . setDefault ( PreferenceConstants . EDITOR_FOLDING_ENABLED , true ) ; store . setDefault ( PreferenceConstants . EDITOR_FOLDING_PROVIDER , "" ) ; store . setDefault ( PreferenceConstants . EDITOR_FOLDING_RDOC , false ) ; store . setDefault ( PreferenceConstants . EDITOR_FOLDING_INNERTYPES , false ) ; store . setDefault ( PreferenceConstants . EDITOR_FOLDING_METHODS , false ) ; store . setDefault ( PreferenceConstants . SPELLING_LOCALE , SpellCheckEngine . getDefaultLocale ( ) . toString ( ) ) ; store . setDefault ( PreferenceConstants . SPELLING_IGNORE_DIGITS , true ) ; store . setDefault ( PreferenceConstants . SPELLING_IGNORE_MIXED , true ) ; store . setDefault ( PreferenceConstants . SPELLING_IGNORE_SENTENCE , true ) ; store . setDefault ( PreferenceConstants . SPELLING_IGNORE_UPPER , true ) ; store . setDefault ( PreferenceConstants . SPELLING_IGNORE_URLS , true ) ; store . setDefault ( PreferenceConstants . SPELLING_USER_DICTIONARY , "" ) ; store . setDefault ( PreferenceConstants . SPELLING_PROPOSAL_THRESHOLD , ) ; store . setDefault ( PreferenceConstants . SPELLING_ENABLE_CONTENTASSIST , false ) ; store . setDefault ( PreferenceConstants . EDITOR_MATCHING_BRACKETS , true ) ; PreferenceConverter . setDefault ( store , PreferenceConstants . EDITOR_MATCHING_BRACKETS_COLOR , new RGB ( , , ) ) ; store . setDefault ( PreferenceConstants . HOVERS_ENABLED , true ) ; store . setDefault ( PreferenceConstants . CODEASSIST_AUTOACTIVATION , false ) ; store . setDefault ( PreferenceConstants . CODEASSIST_AUTOACTIVATION_DELAY , ) ; store . setDefault ( PreferenceConstants . CODEASSIST_AUTOACTIVATION_TRIGGERS_RUBY , "" ) ; store . setDefault ( PreferenceConstants . CODEASSIST_AUTOINSERT , true ) ; PreferenceConverter . setDefault ( store , PreferenceConstants . CODEASSIST_PROPOSALS_BACKGROUND , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , PreferenceConstants . CODEASSIST_PROPOSALS_FOREGROUND , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , PreferenceConstants . CODEASSIST_PARAMETERS_BACKGROUND , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , PreferenceConstants . CODEASSIST_PARAMETERS_FOREGROUND , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , PreferenceConstants . CODEASSIST_REPLACEMENT_BACKGROUND , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , PreferenceConstants . CODEASSIST_REPLACEMENT_FOREGROUND , new RGB ( , , ) ) ; store . setDefault ( PreferenceConstants . CODEASSIST_INSERT_COMPLETION , true ) ; store . setDefault ( PreferenceConstants . CODEASSIST_FILL_ARGUMENT_NAMES , true ) ; store . setDefault ( PreferenceConstants . CODEASSIST_FILL_METHOD_BLOCK_ARGUMENTS , true ) ; store . setDefault ( PreferenceConstants . CODEASSIST_PREFIX_COMPLETION , false ) ; store . setDefault ( PreferenceConstants . CODEASSIST_EXCLUDED_CATEGORIES , "" ) ; store . setDefault ( PreferenceConstants . CODEASSIST_CATEGORY_ORDER , "" ) ; store . setDefault ( PreferenceConstants . CODEASSIST_SORTER , "" ) ; store . setDefault ( PreferenceConstants . EDITOR_USER_KEYWORDS , "" ) ; store . setDefault ( PreferenceConstants . EDITOR_SUB_WORD_NAVIGATION , true ) ; store . setDefault ( PreferenceConstants . EDITOR_CLOSE_STRINGS , true ) ; store . setDefault ( PreferenceConstants . EDITOR_CLOSE_BRACKETS , true ) ; store . setDefault ( PreferenceConstants . EDITOR_CLOSE_BRACES , true ) ; store . setDefault ( PreferenceConstants . EDITOR_END_STATEMENTS , true ) ; store . setDefault ( PreferenceConstants . FORMATTER_PROFILE , ProfileManager . DEFAULT_PROFILE ) ; store . setDefault ( PreferenceConstants . EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE , true ) ; store . setDefault ( PreferenceConstants . EDITOR_EVALUTE_TEMPORARY_PROBLEMS , true ) ; store . setDefault ( PreferenceConstants . EDITOR_SHOW_TEXT_HOVER_AFFORDANCE , true ) ; store . setDefault ( PreferenceConstants . EDITOR_MARK_OCCURRENCES , true ) ; store . setDefault ( PreferenceConstants . EDITOR_STICKY_OCCURRENCES , true ) ; store . setDefault ( PreferenceConstants . EDITOR_MARK_TYPE_OCCURRENCES , true ) ; store . setDefault ( PreferenceConstants . EDITOR_MARK_METHOD_OCCURRENCES , true ) ; store . setDefault ( PreferenceConstants . EDITOR_MARK_CONSTANT_OCCURRENCES , true ) ; store . setDefault ( PreferenceConstants . EDITOR_MARK_FIELD_OCCURRENCES , true ) ; store . setDefault ( PreferenceConstants . EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES , true ) ; store . setDefault ( PreferenceConstants . EDITOR_MARK_METHOD_EXIT_POINTS , true ) ; int sourceHoverModifier = SWT . MOD2 ; String sourceHoverModifierName = Action . findModifierString ( sourceHoverModifier ) ; store . setDefault ( PreferenceConstants . EDITOR_TEXT_HOVER_MODIFIERS , "" + sourceHoverModifierName ) ; store . setDefault ( PreferenceConstants . EDITOR_TEXT_HOVER_MODIFIER_MASKS , "" + sourceHoverModifier ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_DEFAULT , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_DEFAULT + PreferenceConstants . EDITOR_BOLD_SUFFIX , false ) ; store . setDefault ( IRubyColorConstants . RUBY_DEFAULT + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_KEYWORD , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_KEYWORD + PreferenceConstants . EDITOR_BOLD_SUFFIX , true ) ; store . setDefault ( IRubyColorConstants . RUBY_KEYWORD + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_ERROR , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_ERROR + PreferenceConstants . EDITOR_BOLD_SUFFIX , true ) ; store . setDefault ( IRubyColorConstants . RUBY_ERROR + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_ERROR + PreferenceConstants . EDITOR_BG_SUFFIX , new RGB ( , , ) ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_STRING , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_STRING + PreferenceConstants . EDITOR_BOLD_SUFFIX , false ) ; store . setDefault ( IRubyColorConstants . RUBY_STRING + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_REGEXP , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_REGEXP + PreferenceConstants . EDITOR_BOLD_SUFFIX , false ) ; store . setDefault ( IRubyColorConstants . RUBY_REGEXP + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_COMMAND , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_COMMAND + PreferenceConstants . EDITOR_BOLD_SUFFIX , false ) ; store . setDefault ( IRubyColorConstants . RUBY_COMMAND + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_FIXNUM , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_FIXNUM + PreferenceConstants . EDITOR_BOLD_SUFFIX , true ) ; store . setDefault ( IRubyColorConstants . RUBY_FIXNUM + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_CHARACTER , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_CHARACTER + PreferenceConstants . EDITOR_BOLD_SUFFIX , true ) ; store . setDefault ( IRubyColorConstants . RUBY_CHARACTER + PreferenceConstants . EDITOR_ITALIC_SUFFIX , true ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_SYMBOL , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_SYMBOL + PreferenceConstants . EDITOR_BOLD_SUFFIX , true ) ; store . setDefault ( IRubyColorConstants . RUBY_SYMBOL + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_INSTANCE_VARIABLE , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_INSTANCE_VARIABLE + PreferenceConstants . EDITOR_BOLD_SUFFIX , true ) ; store . setDefault ( IRubyColorConstants . RUBY_INSTANCE_VARIABLE + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_CLASS_VARIABLE , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_CLASS_VARIABLE + PreferenceConstants . EDITOR_BOLD_SUFFIX , true ) ; store . setDefault ( IRubyColorConstants . RUBY_CLASS_VARIABLE + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_GLOBAL , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_GLOBAL + PreferenceConstants . EDITOR_BOLD_SUFFIX , false ) ; store . setDefault ( IRubyColorConstants . RUBY_GLOBAL + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_MULTI_LINE_COMMENT , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_MULTI_LINE_COMMENT + PreferenceConstants . EDITOR_BOLD_SUFFIX , false ) ; store . setDefault ( IRubyColorConstants . RUBY_MULTI_LINE_COMMENT + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_SINGLE_LINE_COMMENT , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . RUBY_SINGLE_LINE_COMMENT + PreferenceConstants . EDITOR_BOLD_SUFFIX , false ) ; store . setDefault ( IRubyColorConstants . RUBY_SINGLE_LINE_COMMENT + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . TASK_TAG , new RGB ( , , ) ) ; store . setDefault ( IRubyColorConstants . TASK_TAG + PreferenceConstants . EDITOR_BOLD_SUFFIX , true ) ; store . setDefault ( IRubyColorConstants . TASK_TAG + PreferenceConstants . EDITOR_ITALIC_SUFFIX , false ) ; PreferenceConverter . setDefault ( store , IRubyColorConstants . RUBY_CONTENT_ASSISTANT_BACKGROUND , new RGB ( , , ) ) ; } public static IPreferenceStore getPreferenceStore ( ) { return RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; } public static ILoadpathEntry [ ] getDefaultRubyVMLibrary ( ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; String str = store . getString ( LOADPATH_RUBYVMLIBRARY_LIST ) ; int index = store . getInt ( LOADPATH_RUBYVMLIBRARY_INDEX ) ; StringTokenizer tok = new StringTokenizer ( str , "" ) ; while ( tok . hasMoreTokens ( ) && index > ) { tok . nextToken ( ) ; index -- ; } if ( tok . hasMoreTokens ( ) ) { ILoadpathEntry [ ] res = decodeRubyVMLibraryLoadpathEntries ( tok . nextToken ( ) ) ; if ( res . length > ) { return res ; } } return new ILoadpathEntry [ ] { getRubyVMContainerEntry ( ) } ; } private static ILoadpathEntry getRubyVMContainerEntry ( ) { return RubyCore . newContainerEntry ( new Path ( "" ) ) ; } public static ILoadpathEntry [ ] decodeRubyVMLibraryLoadpathEntries ( String encoded ) { StringTokenizer tok = new StringTokenizer ( encoded , "" ) ; ArrayList res = new ArrayList ( ) ; while ( tok . hasMoreTokens ( ) ) { try { tok . nextToken ( ) ; int kind = Integer . parseInt ( tok . nextToken ( ) ) ; IPath path = decodePath ( tok . nextToken ( ) ) ; boolean isExported = Boolean . valueOf ( tok . nextToken ( ) ) . booleanValue ( ) ; switch ( kind ) { case ILoadpathEntry . CPE_SOURCE : res . add ( RubyCore . newSourceEntry ( path ) ) ; break ; case ILoadpathEntry . CPE_LIBRARY : res . add ( RubyCore . newLibraryEntry ( path , isExported ) ) ; break ; case ILoadpathEntry . CPE_VARIABLE : res . add ( RubyCore . newVariableEntry ( path , isExported ) ) ; break ; case ILoadpathEntry . CPE_PROJECT : res . add ( RubyCore . newProjectEntry ( path , isExported ) ) ; break ; case ILoadpathEntry . CPE_CONTAINER : res . add ( RubyCore . newContainerEntry ( path , isExported ) ) ; break ; } } catch ( NumberFormatException e ) { String message = PreferencesMessages . NewRubyProjectPreferencePage_error_decode ; RubyPlugin . log ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . ERROR , message , e ) ) ; } catch ( NoSuchElementException e ) { String message = PreferencesMessages . NewRubyProjectPreferencePage_error_decode ; RubyPlugin . log ( new Status ( IStatus . ERROR , RubyUI . ID_PLUGIN , IStatus . ERROR , message , e ) ) ; } } return ( ILoadpathEntry [ ] ) res . toArray ( new ILoadpathEntry [ res . size ( ) ] ) ; } private static IPath decodePath ( String str ) { if ( "" . equals ( str ) ) { return null ; } else if ( "" . equals ( str ) ) { return Path . EMPTY ; } else { return Path . fromPortableString ( decode ( str ) ) ; } } private static String decode ( String str ) { try { return URLDecoder . decode ( str , fgDefaultEncoding ) ; } catch ( UnsupportedEncodingException e ) { RubyPlugin . log ( e ) ; } return "" ; } public static String getPreference ( String key , IRubyProject project ) { String val ; if ( project != null ) { val = new ProjectScope ( project . getProject ( ) ) . getNode ( RubyUI . ID_PLUGIN ) . get ( key , null ) ; if ( val != null ) { return val ; } } val = new InstanceScope ( ) . getNode ( RubyUI . ID_PLUGIN ) . get ( key , null ) ; if ( val != null ) { return val ; } return new DefaultScope ( ) . getNode ( RubyUI . ID_PLUGIN ) . get ( key , null ) ; } } package org . rubypeople . rdt . ui . text . hyperlinks ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . hyperlink . IHyperlink ; import org . eclipse . ui . IEditorInput ; import org . jruby . ast . Node ; public interface IHyperlinkProvider { public IHyperlink getHyperlink ( IEditorInput input , ITextViewer textViewer , Node node , IRegion region , boolean canShowMultipleHyperlinks ) ; } package org . rubypeople . rdt . ui . text . ansi ; import java . util . LinkedList ; import java . util . List ; public class ANSIParser { public final static byte ESC = ; private final static byte TEXT = ; private final static byte ANSI_ESC_START = ; private final static byte ANSI = ; public List < ANSIToken > parse ( String s ) { if ( s == null ) return null ; List < ANSIToken > tokens = new LinkedList < ANSIToken > ( ) ; ANSIToken t = new ANSIToken ( ) ; int state = TEXT ; char [ ] c = s . toCharArray ( ) ; StringBuffer ansiBuffer = new StringBuffer ( ) ; for ( int i = ; i < c . length ; i ++ ) { switch ( state ) { case TEXT : if ( c [ i ] == ESC ) state = ANSI_ESC_START ; else t . add ( c [ i ] ) ; break ; case ANSI_ESC_START : if ( c [ i ] == '' ) { state = ANSI ; tokens . add ( t ) ; t = new ANSIToken ( ) ; } else { state = TEXT ; } break ; case ANSI : if ( c [ i ] == '' ) state = TEXT ; if ( c [ i ] == '' || c [ i ] == '' ) { if ( ansiBuffer . length ( ) > ) { try { int value = Integer . parseInt ( ansiBuffer . toString ( ) ) ; t . addProperty ( value ) ; } catch ( NumberFormatException e ) { } } ansiBuffer = new StringBuffer ( ) ; } else { ansiBuffer . append ( c [ i ] ) ; } break ; } } tokens . add ( t ) ; return tokens ; } } package org . rubypeople . rdt . ui . text . ansi ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . RGB ; public class ANSIToken { final static byte BOLD = ; final static byte UNDERSCORE = ; final static byte BLACK = ; final static byte BLUE = ; public final static byte CYAN = ; final static byte GREEN = ; final static byte MAGENTA = ; public final static byte RED = ; public final static byte YELLOW = ; private final static int INITIAL_TOKEN_LENGTH = ; boolean bold = false ; boolean underscore = false ; int backgroundColor = ; int foregroundColor = ; char [ ] text = new char [ INITIAL_TOKEN_LENGTH ] ; int textPos = ; public void add ( char c ) { if ( textPos >= text . length ) { char [ ] tmp = new char [ text . length + INITIAL_TOKEN_LENGTH ] ; System . arraycopy ( text , , tmp , , text . length ) ; text = tmp ; } text [ textPos ++ ] = c ; } public void addProperty ( int ansiProp ) { if ( ansiProp <= ) setTextAttribute ( ansiProp ) ; else if ( ansiProp <= ) foregroundColor = ansiProp ; else if ( ansiProp <= ) backgroundColor = ansiProp ; } public boolean hasFontStyle ( ) { return ( bold || underscore ) ; } public int getFontStyle ( ) { if ( bold && underscore ) return ( SWT . BOLD + SWT . ITALIC ) ; if ( underscore ) return SWT . ITALIC ; if ( bold ) return SWT . BOLD ; return ; } public RGB getForegroundRGB ( ) { switch ( foregroundColor ) { case BLACK : return new RGB ( , , ) ; case RED : return new RGB ( , , ) ; case GREEN : return new RGB ( , , ) ; case YELLOW : return new RGB ( , , ) ; case BLUE : return new RGB ( , , ) ; case MAGENTA : return new RGB ( , , ) ; case CYAN : return new RGB ( , , ) ; default : return new RGB ( , , ) ; } } public String getAnsi ( ) { return "" + bold + "" + underscore + "" + foregroundColor + "" + backgroundColor + "" ; } public boolean hasForegroundColor ( ) { return foregroundColor > ; } public void setTextAttribute ( int attr ) { switch ( attr ) { case BOLD : bold = true ; break ; case UNDERSCORE : underscore = true ; break ; } } public String toString ( ) { StringBuffer sb = new StringBuffer ( ) ; for ( int i = ; i < textPos ; i ++ ) sb . append ( text [ i ] ) ; return sb . toString ( ) ; } } package org . rubypeople . rdt . ui . text ; import org . eclipse . swt . graphics . RGB ; public interface IColorManagerExtension { void bindColor ( String key , RGB rgb ) ; void unbindColor ( String key ) ; } package org . rubypeople . rdt . ui . text ; import java . util . ArrayList ; import java . util . List ; import java . util . StringTokenizer ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentExtension3 ; import org . eclipse . jface . text . IDocumentPartitioner ; import org . eclipse . jface . text . rules . FastPartitioner ; import org . eclipse . jface . text . rules . IPartitionTokenScanner ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditorPreferences ; import org . rubypeople . rdt . internal . ui . text . IRubyColorConstants ; import org . rubypeople . rdt . internal . ui . text . MergingPartitionScanner ; import org . rubypeople . rdt . internal . ui . text . RubyColorManager ; import org . rubypeople . rdt . internal . ui . text . RubyPartitionScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . AbstractRubyScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . AbstractRubyTokenScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyCommentScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyColoringTokenScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . SingleTokenRubyScanner ; public class RubyTextTools { private class PreferenceListener implements IPropertyChangeListener , Preferences . IPropertyChangeListener { public void propertyChange ( PropertyChangeEvent event ) { adaptToPreferenceChange ( event ) ; } public void propertyChange ( Preferences . PropertyChangeEvent event ) { adaptToPreferenceChange ( new PropertyChangeEvent ( event . getSource ( ) , event . getProperty ( ) , event . getOldValue ( ) , event . getNewValue ( ) ) ) ; } } protected static String [ ] keywords ; protected RubyColorManager fColorManager ; protected IPartitionTokenScanner partitionScanner ; protected AbstractRubyTokenScanner fCodeScanner ; protected AbstractRubyScanner fMultilineCommentScanner , fSinglelineCommentScanner , FStringScanner ; private IPreferenceStore fPreferenceStore ; private Preferences fCorePreferenceStore ; private PreferenceListener fPreferenceListener = new PreferenceListener ( ) ; public RubyTextTools ( IPreferenceStore store ) { this ( store , null , true ) ; } public RubyTextTools ( IPreferenceStore store , Preferences coreStore ) { this ( store , coreStore , true ) ; } public RubyTextTools ( IPreferenceStore store , Preferences coreStore , boolean autoDisposeOnDisplayDispose ) { super ( ) ; fColorManager = new RubyColorManager ( autoDisposeOnDisplayDispose ) ; partitionScanner = new MergingPartitionScanner ( ) ; fCodeScanner = new RubyColoringTokenScanner ( fColorManager , store ) ; fMultilineCommentScanner = new RubyCommentScanner ( fColorManager , store , coreStore , IRubyColorConstants . RUBY_MULTI_LINE_COMMENT ) ; fSinglelineCommentScanner = new RubyCommentScanner ( fColorManager , store , coreStore , IRubyColorConstants . RUBY_SINGLE_LINE_COMMENT ) ; FStringScanner = new SingleTokenRubyScanner ( fColorManager , store , IRubyColorConstants . RUBY_STRING ) ; fPreferenceStore = store ; fPreferenceStore . addPropertyChangeListener ( fPreferenceListener ) ; fCorePreferenceStore = coreStore ; if ( fCorePreferenceStore != null ) fCorePreferenceStore . addPropertyChangeListener ( fPreferenceListener ) ; } protected void adaptToPreferenceChange ( PropertyChangeEvent event ) { if ( fCodeScanner . affectsBehavior ( event ) ) fCodeScanner . adaptToPreferenceChange ( event ) ; if ( fMultilineCommentScanner . affectsBehavior ( event ) ) fMultilineCommentScanner . adaptToPreferenceChange ( event ) ; if ( fSinglelineCommentScanner . affectsBehavior ( event ) ) fSinglelineCommentScanner . adaptToPreferenceChange ( event ) ; if ( FStringScanner . affectsBehavior ( event ) ) FStringScanner . adaptToPreferenceChange ( event ) ; } public IDocumentPartitioner createDocumentPartitioner ( ) { return new FastPartitioner ( getPartitionScanner ( ) , RubyPartitionScanner . LEGAL_CONTENT_TYPES ) ; } protected IPartitionTokenScanner getPartitionScanner ( ) { return partitionScanner ; } public IPreferenceStore getPreferenceStore ( ) { return RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; } public static String [ ] getKeyWords ( ) { if ( keywords == null ) { String csvKeywords = RubyEditorPreferences . getString ( "" ) ; List keywordList = new ArrayList ( ) ; StringTokenizer tokenizer = new StringTokenizer ( csvKeywords , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) keywordList . add ( tokenizer . nextToken ( ) ) ; keywords = new String [ keywordList . size ( ) ] ; keywordList . toArray ( keywords ) ; } return keywords ; } public boolean affectsTextPresentation ( PropertyChangeEvent event ) { return fCodeScanner . affectsBehavior ( event ) || fMultilineCommentScanner . affectsBehavior ( event ) || fSinglelineCommentScanner . affectsBehavior ( event ) || FStringScanner . affectsBehavior ( event ) ; } public void setupRubyDocumentPartitioner ( IDocument document , String partitioning ) { IDocumentPartitioner partitioner = createDocumentPartitioner ( ) ; if ( document instanceof IDocumentExtension3 ) { IDocumentExtension3 extension3 = ( IDocumentExtension3 ) document ; extension3 . setDocumentPartitioner ( partitioning , partitioner ) ; } else { document . setDocumentPartitioner ( partitioner ) ; } partitioner . connect ( document ) ; } public void dispose ( ) { fCodeScanner = null ; fMultilineCommentScanner = null ; fSinglelineCommentScanner = null ; partitionScanner = null ; if ( fColorManager != null ) { fColorManager . dispose ( ) ; fColorManager = null ; } if ( fPreferenceStore != null ) { fPreferenceStore . removePropertyChangeListener ( fPreferenceListener ) ; fPreferenceStore = null ; if ( fCorePreferenceStore != null ) { fCorePreferenceStore . removePropertyChangeListener ( fPreferenceListener ) ; fCorePreferenceStore = null ; } fPreferenceListener = null ; } } public IColorManager getColorManager ( ) { return fColorManager ; } public Preferences getCorePreferenceStore ( ) { return fCorePreferenceStore ; } public void setupRubyDocumentPartitioner ( IDocument document ) { setupRubyDocumentPartitioner ( document , IDocumentExtension3 . DEFAULT_PARTITIONING ) ; } } package org . rubypeople . rdt . ui . text . ruby ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyScript ; public interface IQuickFixProcessor { boolean hasCorrections ( IRubyScript unit , int problemId ) ; IRubyCompletionProposal [ ] getCorrections ( IInvocationContext context , IProblemLocation [ ] locations ) throws CoreException ; } package org . rubypeople . rdt . ui . text . ruby ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . IContextInformation ; public interface IRubyCompletionProposalComputer { void sessionStarted ( ) ; List computeCompletionProposals ( ContentAssistInvocationContext context , IProgressMonitor monitor ) ; List computeContextInformation ( ContentAssistInvocationContext context , IProgressMonitor monitor ) ; String getErrorMessage ( ) ; void sessionEnded ( ) ; } package org . rubypeople . rdt . ui . text . ruby ; import org . eclipse . jface . text . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextViewer ; import org . rubypeople . rdt . core . RubyConventions ; public class ContentAssistInvocationContext { private final ITextViewer fViewer ; private final IDocument fDocument ; private final int fOffset ; private CharSequence fPrefix ; private String fStatementPrefix ; public ContentAssistInvocationContext ( ITextViewer viewer ) { this ( viewer , viewer . getSelectedRange ( ) . x ) ; } public ContentAssistInvocationContext ( ITextViewer viewer , int offset ) { Assert . isNotNull ( viewer ) ; fViewer = viewer ; fDocument = null ; fOffset = offset ; } protected ContentAssistInvocationContext ( ) { fDocument = null ; fViewer = null ; fOffset = - ; } public ContentAssistInvocationContext ( IDocument document , int offset ) { Assert . isNotNull ( document ) ; Assert . isTrue ( offset >= ) ; fViewer = null ; fDocument = document ; fOffset = offset ; } public final int getInvocationOffset ( ) { return fOffset ; } public final ITextViewer getViewer ( ) { return fViewer ; } public IDocument getDocument ( ) { if ( fDocument == null ) { if ( fViewer == null ) return null ; return fViewer . getDocument ( ) ; } return fDocument ; } public CharSequence computeIdentifierPrefix ( ) throws BadLocationException { if ( fPrefix == null ) { IDocument document = getDocument ( ) ; if ( document == null ) return null ; int end = getInvocationOffset ( ) ; int start = end ; while ( -- start >= ) { if ( ! RubyConventions . isRubyIdentifierPart ( document . getChar ( start ) ) ) break ; } start ++ ; fPrefix = document . get ( start , end - start ) ; } return fPrefix ; } public CharSequence computeStatementPrefix ( ) throws BadLocationException { if ( fStatementPrefix == null ) { IDocument document = getDocument ( ) ; if ( document == null ) return null ; int end = getInvocationOffset ( ) ; int start = end ; while ( -- start >= ) { char c = document . getChar ( start ) ; if ( c == '' || c == '' || c == '' ) break ; } start ++ ; fStatementPrefix = document . get ( start , end - start ) ; } return fStatementPrefix ; } public boolean equals ( Object obj ) { if ( obj == null ) return false ; if ( ! getClass ( ) . equals ( obj . getClass ( ) ) ) return false ; ContentAssistInvocationContext other = ( ContentAssistInvocationContext ) obj ; return ( fViewer == null && other . fViewer == null || fViewer . equals ( other . fViewer ) ) && fOffset == other . fOffset && ( fDocument == null && other . fDocument == null || fDocument . equals ( other . fDocument ) ) ; } public int hashCode ( ) { return << | ( fViewer == null ? : fViewer . hashCode ( ) << ) | fOffset ; } } package org . rubypeople . rdt . ui . text . ruby ; import java . util . Arrays ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyContentAssistInvocationContext ; public abstract class RubyCompletionProposalComputer implements IRubyCompletionProposalComputer { protected RubyContentAssistInvocationContext fContext ; public List computeCompletionProposals ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { if ( ! ( context instanceof RubyContentAssistInvocationContext ) ) return Collections . EMPTY_LIST ; fContext = ( RubyContentAssistInvocationContext ) context ; CompletionProposalCollector collector = createCollector ( fContext ) ; List < CompletionProposal > proposals = doComputeCompletionProposals ( fContext , monitor ) ; for ( CompletionProposal proposal : proposals ) { collector . accept ( proposal ) ; } fContext = null ; return Arrays . asList ( collector . getRubyCompletionProposals ( ) ) ; } protected abstract List < CompletionProposal > doComputeCompletionProposals ( RubyContentAssistInvocationContext context , IProgressMonitor monitor ) ; public List computeContextInformation ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { return Collections . EMPTY_LIST ; } public String getErrorMessage ( ) { return null ; } public void sessionEnded ( ) { } public void sessionStarted ( ) { } protected CompletionProposalCollector createCollector ( RubyContentAssistInvocationContext context ) { return new CompletionProposalCollector ( context ) ; } } package org . rubypeople . rdt . ui . text . ruby ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; public interface IRubyCompletionProposal extends ICompletionProposal { int getRelevance ( ) ; } package org . rubypeople . rdt . ui . text . ruby ; import java . util . Comparator ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; public abstract class AbstractProposalSorter implements Comparator { protected AbstractProposalSorter ( ) { } public void beginSorting ( ContentAssistInvocationContext context ) { } public abstract int compare ( ICompletionProposal p1 , ICompletionProposal p2 ) ; public void endSorting ( ) { } public final int compare ( Object o1 , Object o2 ) { ICompletionProposal p1 = ( ICompletionProposal ) o1 ; ICompletionProposal p2 = ( ICompletionProposal ) o2 ; return compare ( p1 , p2 ) ; } } package org . rubypeople . rdt . ui . text . ruby ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . core . CompletionRequestor ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . ruby . AbstractRubyCompletionProposal ; import org . rubypeople . rdt . internal . ui . text . ruby . CompletionProposalLabelProvider ; import org . rubypeople . rdt . internal . ui . text . ruby . FillArgsAndBlockProposal ; import org . rubypeople . rdt . internal . ui . text . ruby . FillMethodArgumentsProposal ; import org . rubypeople . rdt . internal . ui . text . ruby . ProposalInfo ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyCompletionProposal ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyContentAssistInvocationContext ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; public class CompletionProposalCollector extends CompletionRequestor { private static final boolean DEBUG = "" . equalsIgnoreCase ( Platform . getDebugOption ( "" ) ) ; private final CompletionProposalLabelProvider fLabelProvider = new CompletionProposalLabelProvider ( ) ; private final ImageDescriptorRegistry fRegistry = RubyPlugin . getImageDescriptorRegistry ( ) ; protected final static char [ ] VAR_TRIGGER = new char [ ] { '' , '' , '' , '' , '' } ; private final List fRubyProposals = new ArrayList ( ) ; private final List fKeywords = new ArrayList ( ) ; private final Set fSuggestedMethodNames = new HashSet ( ) ; private final IRubyScript fRubyScript ; private final IRubyProject fRubyProject ; private int fUserReplacementLength ; private IProblem fLastProblem ; private long fStartTime ; private long fUITime ; private RubyContentAssistInvocationContext context ; public CompletionProposalCollector ( RubyContentAssistInvocationContext context ) { this ( context . getProject ( ) , context . getRubyScript ( ) ) ; this . context = context ; } private CompletionProposalCollector ( IRubyProject project , IRubyScript cu ) { fRubyProject = project ; fRubyScript = cu ; fUserReplacementLength = - ; } public final IRubyCompletionProposal [ ] getRubyCompletionProposals ( ) { return ( IRubyCompletionProposal [ ] ) fRubyProposals . toArray ( new IRubyCompletionProposal [ fRubyProposals . size ( ) ] ) ; } public final IRubyCompletionProposal [ ] getKeywordCompletionProposals ( ) { return ( IRubyCompletionProposal [ ] ) fKeywords . toArray ( new RubyCompletionProposal [ fKeywords . size ( ) ] ) ; } @ Override public void accept ( CompletionProposal proposal ) { if ( proposal == null ) return ; long start = DEBUG ? System . currentTimeMillis ( ) : ; try { if ( isFiltered ( proposal ) ) return ; if ( proposal . getKind ( ) == CompletionProposal . POTENTIAL_METHOD_DECLARATION ) { } else { IRubyCompletionProposal rubyProposal = createRubyCompletionProposal ( proposal ) ; if ( rubyProposal != null ) { fRubyProposals . add ( rubyProposal ) ; if ( proposal . getKind ( ) == CompletionProposal . KEYWORD ) fKeywords . add ( rubyProposal ) ; } } } catch ( IllegalArgumentException e ) { RubyPlugin . log ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . OK , "" + String . valueOf ( proposal . getCompletion ( ) ) , e ) ) ; } if ( DEBUG ) fUITime += System . currentTimeMillis ( ) - start ; } protected int computeRelevance ( CompletionProposal proposal ) { final int baseRelevance = proposal . getRelevance ( ) * ; switch ( proposal . getKind ( ) ) { case CompletionProposal . KEYWORD : return baseRelevance + ; case CompletionProposal . TYPE_REF : return baseRelevance + ; case CompletionProposal . METHOD_REF : case CompletionProposal . METHOD_NAME_REFERENCE : case CompletionProposal . METHOD_DECLARATION : return baseRelevance + ; case CompletionProposal . POTENTIAL_METHOD_DECLARATION : return baseRelevance + ; case CompletionProposal . CONSTANT_REF : case CompletionProposal . CLASS_VARIABLE_REF : case CompletionProposal . INSTANCE_VARIABLE_REF : return baseRelevance + ; case CompletionProposal . LOCAL_VARIABLE_REF : case CompletionProposal . VARIABLE_DECLARATION : return baseRelevance + ; default : return baseRelevance ; } } protected boolean isFiltered ( CompletionProposal proposal ) { if ( isIgnored ( proposal . getKind ( ) ) ) return true ; return false ; } protected IRubyCompletionProposal createRubyCompletionProposal ( CompletionProposal proposal ) { switch ( proposal . getKind ( ) ) { case CompletionProposal . METHOD_REF : IRubyCompletionProposal proposal2 = createMethodReferenceProposal ( proposal ) ; if ( fSuggestedMethodNames . contains ( proposal2 . getDisplayString ( ) ) ) return null ; fSuggestedMethodNames . add ( proposal2 . getDisplayString ( ) ) ; return proposal2 ; } return createProposal ( proposal ) ; } private IRubyCompletionProposal createMethodReferenceProposal ( CompletionProposal methodProposal ) { boolean fillArgs = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . CODEASSIST_FILL_ARGUMENT_NAMES ) ; if ( fillArgs ) { boolean fillBlockArgs = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . CODEASSIST_FILL_METHOD_BLOCK_ARGUMENTS ) ; String completion = String . valueOf ( methodProposal . getCompletion ( ) ) ; if ( ( completion . length ( ) == ) || ( ( completion . length ( ) == ) && completion . charAt ( ) == '' ) || methodProposal . getParameterNames ( ) == null || methodProposal . getParameterNames ( ) . length == ) return createProposal ( methodProposal ) ; if ( fillBlockArgs ) return new FillArgsAndBlockProposal ( methodProposal , context ) ; else return new FillMethodArgumentsProposal ( methodProposal , context ) ; } else { return createProposal ( methodProposal ) ; } } protected final IRubyScript getRubyScript ( ) { return fRubyScript ; } protected final Image getImage ( ImageDescriptor descriptor ) { return ( descriptor == null ) ? null : fRegistry . get ( descriptor ) ; } private IRubyCompletionProposal createProposal ( CompletionProposal proposal ) { String completion = proposal . getCompletion ( ) ; int start = proposal . getReplaceStart ( ) ; int length = getLength ( proposal ) ; String label = fLabelProvider . createLabel ( proposal ) ; int relevance = computeRelevance ( proposal ) ; Image image = getImage ( fLabelProvider . createImageDescriptor ( proposal ) ) ; AbstractRubyCompletionProposal rubyProposal = new RubyCompletionProposal ( completion , start , length , image , label , relevance ) ; if ( proposal . getElement ( ) != null && proposal . getElement ( ) instanceof IMember ) { ProposalInfo info = new ProposalInfo ( ( IMember ) proposal . getElement ( ) ) ; rubyProposal . setProposalInfo ( info ) ; } return rubyProposal ; } protected final int getLength ( CompletionProposal proposal ) { int start = proposal . getReplaceStart ( ) ; int end = proposal . getReplaceEnd ( ) ; int length ; if ( fUserReplacementLength == - ) { length = end - start ; } else { length = fUserReplacementLength ; int behindCompletion = proposal . getCompletionLocation ( ) + ; if ( start < behindCompletion ) { length += behindCompletion - start ; } } return length ; } public void beginReporting ( ) { if ( DEBUG ) { fStartTime = System . currentTimeMillis ( ) ; fUITime = ; } fLastProblem = null ; fRubyProposals . clear ( ) ; fKeywords . clear ( ) ; fSuggestedMethodNames . clear ( ) ; } public void completionFailure ( IProblem problem ) { fLastProblem = problem ; } public void endReporting ( ) { if ( DEBUG ) { long total = System . currentTimeMillis ( ) - fStartTime ; System . err . println ( "" + ( total - fUITime ) ) ; System . err . println ( "" + fUITime ) ; } fSuggestedMethodNames . clear ( ) ; } public String getErrorMessage ( ) { if ( fLastProblem != null ) return fLastProblem . getMessage ( ) ; return "" ; } } package org . rubypeople . rdt . ui . text . ruby ; import java . util . Comparator ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . templates . TemplateProposal ; import org . rubypeople . rdt . internal . ui . text . ruby . AbstractRubyCompletionProposal ; public final class CompletionProposalComparator implements Comparator { private boolean fOrderAlphabetically ; public CompletionProposalComparator ( ) { fOrderAlphabetically = false ; } public void setOrderAlphabetically ( boolean orderAlphabetically ) { fOrderAlphabetically = orderAlphabetically ; } public int compare ( Object o1 , Object o2 ) { ICompletionProposal p1 = ( ICompletionProposal ) o1 ; ICompletionProposal p2 = ( ICompletionProposal ) o2 ; if ( ! fOrderAlphabetically ) { int r1 = getRelevance ( p1 ) ; int r2 = getRelevance ( p2 ) ; int relevanceDif = r2 - r1 ; if ( relevanceDif != ) { return relevanceDif ; } } return getSortKey ( p1 ) . compareToIgnoreCase ( getSortKey ( p2 ) ) ; } private String getSortKey ( ICompletionProposal p ) { if ( p instanceof AbstractRubyCompletionProposal ) return ( ( AbstractRubyCompletionProposal ) p ) . getSortString ( ) ; return p . getDisplayString ( ) ; } private int getRelevance ( ICompletionProposal obj ) { if ( obj instanceof IRubyCompletionProposal ) { IRubyCompletionProposal jcp = ( IRubyCompletionProposal ) obj ; return jcp . getRelevance ( ) ; } else if ( obj instanceof TemplateProposal ) { TemplateProposal tp = ( TemplateProposal ) obj ; return tp . getRelevance ( ) ; } return ; } } package org . rubypeople . rdt . ui . text . ruby . hover ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . ui . IEditorPart ; public interface IRubyEditorTextHover extends ITextHover { void setEditor ( IEditorPart editor ) ; } package org . rubypeople . rdt . ui . text . ruby ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; public interface IProblemLocation { int getOffset ( ) ; int getLength ( ) ; String getMarkerType ( ) ; int getProblemId ( ) ; String [ ] getProblemArguments ( ) ; boolean isError ( ) ; Node getCoveringNode ( RootNode astRoot ) ; Node getCoveredNode ( RootNode astRoot ) ; } package org . rubypeople . rdt . ui . text . ruby ; import org . eclipse . core . runtime . CoreException ; public interface IQuickAssistProcessor { boolean hasAssists ( IInvocationContext context ) throws CoreException ; IRubyCompletionProposal [ ] getAssists ( IInvocationContext context , IProblemLocation [ ] locations ) throws CoreException ; } package org . rubypeople . rdt . ui . text . ruby ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyScript ; public interface IInvocationContext { IRubyScript getRubyScript ( ) ; int getSelectionOffset ( ) ; int getSelectionLength ( ) ; RootNode getASTRoot ( ) ; Node getCoveringNode ( ) ; Node getCoveredNode ( ) ; } package org . rubypeople . rdt . ui . text . folding ; import org . eclipse . jface . text . source . projection . ProjectionViewer ; import org . eclipse . ui . texteditor . ITextEditor ; public interface IRubyFoldingStructureProvider { public abstract void install ( ITextEditor editor , ProjectionViewer viewer ) ; public abstract void uninstall ( ) ; public abstract void initialize ( ) ; } package org . rubypeople . rdt . ui . text . folding ; import org . rubypeople . rdt . core . IRubyElement ; public interface IRubyFoldingStructureProviderExtension { void collapseMembers ( ) ; void collapseComments ( ) ; void collapseElements ( IRubyElement [ ] elements ) ; void expandElements ( IRubyElement [ ] elements ) ; } package org . rubypeople . rdt . ui . text . folding ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; public interface IRubyFoldingPreferenceBlock { Control createControl ( Composite parent ) ; void initialize ( ) ; void performOk ( ) ; void performDefaults ( ) ; void dispose ( ) ; } package org . rubypeople . rdt . ui . text ; import org . eclipse . swt . graphics . Color ; import org . eclipse . jface . text . source . ISharedTextColors ; public interface IColorManager extends ISharedTextColors { Color getColor ( String key ) ; } package org . rubypeople . rdt . ui . text ; import java . util . Vector ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . AbstractInformationControlManager ; import org . eclipse . jface . text . DefaultInformationControl ; import org . eclipse . jface . text . IAutoEditStrategy ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IInformationControl ; import org . eclipse . jface . text . IInformationControlCreator ; import org . eclipse . jface . text . ITextDoubleClickStrategy ; import org . eclipse . jface . text . ITextHover ; import org . eclipse . jface . text . contentassist . ContentAssistant ; import org . eclipse . jface . text . contentassist . IContentAssistProcessor ; import org . eclipse . jface . text . contentassist . IContentAssistant ; import org . eclipse . jface . text . formatter . IContentFormatter ; import org . eclipse . jface . text . formatter . MultiPassContentFormatter ; import org . eclipse . jface . text . hyperlink . IHyperlinkDetector ; import org . eclipse . jface . text . information . IInformationPresenter ; import org . eclipse . jface . text . information . IInformationProvider ; import org . eclipse . jface . text . information . InformationPresenter ; import org . eclipse . jface . text . presentation . IPresentationReconciler ; import org . eclipse . jface . text . presentation . PresentationReconciler ; import org . eclipse . jface . text . quickassist . IQuickAssistAssistant ; import org . eclipse . jface . text . reconciler . IReconciler ; import org . eclipse . jface . text . rules . DefaultDamagerRepairer ; import org . eclipse . jface . text . rules . ITokenScanner ; import org . eclipse . jface . text . source . IAnnotationHover ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . editors . text . TextSourceViewerConfiguration ; import org . eclipse . ui . texteditor . AbstractDecoratedTextEditorPreferenceConstants ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . corext . util . CodeFormatterUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptDocumentProvider ; import org . rubypeople . rdt . internal . ui . text . ContentAssistPreference ; import org . rubypeople . rdt . internal . ui . text . HTMLTextPresenter ; import org . rubypeople . rdt . internal . ui . text . IRubyColorConstants ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . internal . ui . text . RubyAnnotationHover ; import org . rubypeople . rdt . internal . ui . text . RubyCompositeReconcilingStrategy ; import org . rubypeople . rdt . internal . ui . text . RubyDoubleClickSelector ; import org . rubypeople . rdt . internal . ui . text . RubyElementProvider ; import org . rubypeople . rdt . internal . ui . text . RubyOutlineInformationControl ; import org . rubypeople . rdt . internal . ui . text . RubyPartitionScanner ; import org . rubypeople . rdt . internal . ui . text . RubyPresentationReconciler ; import org . rubypeople . rdt . internal . ui . text . RubyReconciler ; import org . rubypeople . rdt . internal . ui . text . comment . CommentFormattingStrategy ; import org . rubypeople . rdt . internal . ui . text . comment . RubyCommentAutoIndentStrategy ; import org . rubypeople . rdt . internal . ui . text . correction . RubyCorrectionAssistant ; import org . rubypeople . rdt . internal . ui . text . hyperlinks . RubyHyperLinkDetector ; import org . rubypeople . rdt . internal . ui . text . ruby . AbstractRubyScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . AbstractRubyTokenScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyAutoIndentStrategy ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyColoringTokenScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyCommentScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyCompletionProcessor ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyFormattingStrategy ; import org . rubypeople . rdt . internal . ui . text . ruby . SingleTokenRubyScanner ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . RubyEditorTextHoverDescriptor ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . RubyEditorTextHoverProxy ; import org . rubypeople . rdt . internal . ui . text . ruby . hover . RubyInformationProvider ; import org . rubypeople . rdt . ui . actions . IRubyEditorActionDefinitionIds ; public class RubySourceViewerConfiguration extends TextSourceViewerConfiguration { protected RubyTextTools textTools ; protected ITextEditor fTextEditor ; private String fDocumentPartitioning ; private IColorManager fColorManager ; protected AbstractRubyTokenScanner fCodeScanner ; protected AbstractRubyScanner fMultilineCommentScanner , fSinglelineCommentScanner , fStringScanner , fRegexScanner , fCommandScanner ; private RubyDoubleClickSelector fRubyDoubleClickSelector ; public RubySourceViewerConfiguration ( IColorManager colorManager , IPreferenceStore preferenceStore , ITextEditor editor , String partitioning ) { super ( preferenceStore ) ; fColorManager = colorManager ; fTextEditor = editor ; fDocumentPartitioning = partitioning ; initializeScanners ( ) ; } public IContentFormatter getContentFormatter ( ISourceViewer sourceViewer ) { final MultiPassContentFormatter formatter = new MultiPassContentFormatter ( getConfiguredDocumentPartitioning ( sourceViewer ) , IDocument . DEFAULT_CONTENT_TYPE ) ; formatter . setMasterStrategy ( new RubyFormattingStrategy ( ) ) ; formatter . setSlaveStrategy ( new CommentFormattingStrategy ( ) , IRubyPartitions . RUBY_SINGLE_LINE_COMMENT ) ; formatter . setSlaveStrategy ( new CommentFormattingStrategy ( ) , IRubyPartitions . RUBY_MULTI_LINE_COMMENT ) ; return formatter ; } @ Override public IHyperlinkDetector [ ] getHyperlinkDetectors ( ISourceViewer sourceViewer ) { if ( ! fPreferenceStore . getBoolean ( AbstractDecoratedTextEditorPreferenceConstants . EDITOR_HYPERLINKS_ENABLED ) ) return null ; IHyperlinkDetector [ ] inheritedDetectors = super . getHyperlinkDetectors ( sourceViewer ) ; if ( fTextEditor == null ) return inheritedDetectors ; int inheritedDetectorsLength = inheritedDetectors != null ? inheritedDetectors . length : ; IHyperlinkDetector [ ] detectors = new IHyperlinkDetector [ inheritedDetectorsLength + ] ; detectors [ ] = new RubyHyperLinkDetector ( fTextEditor . getEditorInput ( ) ) ; for ( int i = ; i < inheritedDetectorsLength ; i ++ ) detectors [ i + ] = inheritedDetectors [ i ] ; return detectors ; } public boolean affectsTextPresentation ( PropertyChangeEvent event ) { return fCodeScanner . affectsBehavior ( event ) || fMultilineCommentScanner . affectsBehavior ( event ) || fSinglelineCommentScanner . affectsBehavior ( event ) || fStringScanner . affectsBehavior ( event ) || fRegexScanner . affectsBehavior ( event ) ; } public void handlePropertyChangeEvent ( PropertyChangeEvent event ) { Assert . isTrue ( isNewSetup ( ) ) ; if ( fCodeScanner . affectsBehavior ( event ) ) fCodeScanner . adaptToPreferenceChange ( event ) ; if ( fMultilineCommentScanner . affectsBehavior ( event ) ) fMultilineCommentScanner . adaptToPreferenceChange ( event ) ; if ( fSinglelineCommentScanner . affectsBehavior ( event ) ) fSinglelineCommentScanner . adaptToPreferenceChange ( event ) ; if ( fStringScanner . affectsBehavior ( event ) ) fStringScanner . adaptToPreferenceChange ( event ) ; if ( fRegexScanner . affectsBehavior ( event ) ) fRegexScanner . adaptToPreferenceChange ( event ) ; } private void initializeScanners ( ) { Assert . isTrue ( isNewSetup ( ) ) ; fCodeScanner = new RubyColoringTokenScanner ( getColorManager ( ) , fPreferenceStore ) ; fMultilineCommentScanner = new RubyCommentScanner ( getColorManager ( ) , fPreferenceStore , IRubyColorConstants . RUBY_MULTI_LINE_COMMENT ) ; fSinglelineCommentScanner = new RubyCommentScanner ( getColorManager ( ) , fPreferenceStore , IRubyColorConstants . RUBY_SINGLE_LINE_COMMENT ) ; fStringScanner = new SingleTokenRubyScanner ( getColorManager ( ) , fPreferenceStore , IRubyColorConstants . RUBY_STRING ) ; fRegexScanner = new SingleTokenRubyScanner ( getColorManager ( ) , fPreferenceStore , IRubyColorConstants . RUBY_REGEXP ) ; fCommandScanner = new SingleTokenRubyScanner ( getColorManager ( ) , fPreferenceStore , IRubyColorConstants . RUBY_COMMAND ) ; } private boolean isNewSetup ( ) { return textTools == null ; } protected IColorManager getColorManager ( ) { return fColorManager ; } public IPresentationReconciler getPresentationReconciler ( ISourceViewer sourceViewer ) { PresentationReconciler reconciler = new RubyPresentationReconciler ( ) ; reconciler . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( sourceViewer ) ) ; DefaultDamagerRepairer dr = new DefaultDamagerRepairer ( getCodeScanner ( ) ) ; reconciler . setDamager ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; reconciler . setRepairer ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; dr = new DefaultDamagerRepairer ( getMultilineCommentScanner ( ) ) ; reconciler . setDamager ( dr , RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT ) ; reconciler . setRepairer ( dr , RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT ) ; dr = new DefaultDamagerRepairer ( getSinglelineCommentScanner ( ) ) ; reconciler . setDamager ( dr , RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT ) ; reconciler . setRepairer ( dr , RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT ) ; dr = new DefaultDamagerRepairer ( getStringScanner ( ) ) ; reconciler . setDamager ( dr , RubyPartitionScanner . RUBY_STRING ) ; reconciler . setRepairer ( dr , RubyPartitionScanner . RUBY_STRING ) ; dr = new DefaultDamagerRepairer ( getRegexScanner ( ) ) ; reconciler . setDamager ( dr , RubyPartitionScanner . RUBY_REGULAR_EXPRESSION ) ; reconciler . setRepairer ( dr , RubyPartitionScanner . RUBY_REGULAR_EXPRESSION ) ; dr = new DefaultDamagerRepairer ( getCommandScanner ( ) ) ; reconciler . setDamager ( dr , RubyPartitionScanner . RUBY_COMMAND ) ; reconciler . setRepairer ( dr , RubyPartitionScanner . RUBY_COMMAND ) ; return reconciler ; } protected ITokenScanner getCodeScanner ( ) { return fCodeScanner ; } protected ITokenScanner getMultilineCommentScanner ( ) { return fMultilineCommentScanner ; } protected ITokenScanner getSinglelineCommentScanner ( ) { return fSinglelineCommentScanner ; } protected ITokenScanner getStringScanner ( ) { return fStringScanner ; } protected ITokenScanner getRegexScanner ( ) { return fRegexScanner ; } protected ITokenScanner getCommandScanner ( ) { return fCommandScanner ; } public String [ ] getConfiguredContentTypes ( ISourceViewer sourceViewer ) { return RubyPartitionScanner . LEGAL_CONTENT_TYPES ; } public String getConfiguredDocumentPartitioning ( ISourceViewer sourceViewer ) { if ( fDocumentPartitioning != null ) return fDocumentPartitioning ; return super . getConfiguredDocumentPartitioning ( sourceViewer ) ; } public IContentAssistant getContentAssistant ( ISourceViewer sourceViewer ) { if ( getEditor ( ) != null ) { ContentAssistant assistant = new ContentAssistant ( ) ; assistant . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( sourceViewer ) ) ; assistant . setRestoreCompletionProposalSize ( getSettings ( "" ) ) ; IContentAssistProcessor rubyProcessor = new RubyCompletionProcessor ( getEditor ( ) , assistant , IDocument . DEFAULT_CONTENT_TYPE ) ; assistant . setContentAssistProcessor ( rubyProcessor , IDocument . DEFAULT_CONTENT_TYPE ) ; ContentAssistPreference . configure ( assistant , fPreferenceStore ) ; assistant . setContextInformationPopupOrientation ( IContentAssistant . CONTEXT_INFO_ABOVE ) ; assistant . setInformationControlCreator ( getInformationControlCreator ( sourceViewer ) ) ; return assistant ; } return null ; } private IDialogSettings getSettings ( String sectionName ) { IDialogSettings settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . getSection ( sectionName ) ; if ( settings == null ) settings = RubyPlugin . getDefault ( ) . getDialogSettings ( ) . addNewSection ( sectionName ) ; return settings ; } public IAnnotationHover getAnnotationHover ( ISourceViewer sourceViewer ) { return new RubyAnnotationHover ( RubyAnnotationHover . VERTICAL_RULER_HOVER ) ; } public IAutoEditStrategy [ ] getAutoEditStrategies ( ISourceViewer sourceViewer , String contentType ) { String partitioning = getConfiguredDocumentPartitioning ( sourceViewer ) ; if ( IRubyPartitions . RUBY_SINGLE_LINE_COMMENT . equals ( contentType ) || IRubyPartitions . RUBY_MULTI_LINE_COMMENT . equals ( contentType ) ) { return new IAutoEditStrategy [ ] { new RubyCommentAutoIndentStrategy ( fTextEditor , partitioning , getProject ( ) ) } ; } else if ( IDocument . DEFAULT_CONTENT_TYPE . equals ( contentType ) ) { return new IAutoEditStrategy [ ] { new RubyAutoIndentStrategy ( partitioning , getProject ( ) ) } ; } else { return super . getAutoEditStrategies ( sourceViewer , contentType ) ; } } public IInformationControlCreator getInformationControlCreator ( ISourceViewer sourceViewer ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { return new DefaultInformationControl ( parent , SWT . NONE , new HTMLTextPresenter ( true ) ) ; } } ; } public IInformationPresenter getInformationPresenter ( ISourceViewer sourceViewer ) { InformationPresenter presenter = new InformationPresenter ( getInformationPresenterControlCreator ( sourceViewer ) ) ; presenter . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( sourceViewer ) ) ; IInformationProvider provider = new RubyInformationProvider ( getEditor ( ) ) ; String [ ] contentTypes = getConfiguredContentTypes ( sourceViewer ) ; for ( int i = ; i < contentTypes . length ; i ++ ) presenter . setInformationProvider ( provider , contentTypes [ i ] ) ; presenter . setSizeConstraints ( , , true , true ) ; return presenter ; } private IInformationControlCreator getInformationPresenterControlCreator ( ISourceViewer sourceViewer ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { int shellStyle = SWT . RESIZE | SWT . TOOL ; int style = SWT . V_SCROLL | SWT . H_SCROLL ; return new DefaultInformationControl ( parent , shellStyle , style , new HTMLTextPresenter ( false ) ) ; } } ; } protected ITextEditor getEditor ( ) { return fTextEditor ; } protected IPreferenceStore getPreferenceStore ( ) { return RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; } public String [ ] getDefaultPrefixes ( ISourceViewer sourceViewer , String contentType ) { return new String [ ] { "" , "" } ; } public IReconciler getReconciler ( ISourceViewer sourceViewer ) { final ITextEditor editor = getEditor ( ) ; if ( editor != null && editor . isEditable ( ) ) { RubyCompositeReconcilingStrategy strategy = new RubyCompositeReconcilingStrategy ( editor , getConfiguredDocumentPartitioning ( sourceViewer ) ) ; RubyReconciler reconciler = new RubyReconciler ( editor , strategy , false ) ; reconciler . setIsIncrementalReconciler ( false ) ; reconciler . setIsAllowedToModifyDocument ( false ) ; reconciler . setProgressMonitor ( new NullProgressMonitor ( ) ) ; reconciler . setDelay ( ) ; return reconciler ; } return null ; } private IRubyProject getProject ( ) { ITextEditor editor = getEditor ( ) ; if ( editor == null ) return null ; IRubyElement element = null ; IEditorInput input = editor . getEditorInput ( ) ; IDocumentProvider provider = editor . getDocumentProvider ( ) ; if ( provider instanceof IRubyScriptDocumentProvider ) { IRubyScriptDocumentProvider cudp = ( IRubyScriptDocumentProvider ) provider ; element = cudp . getWorkingCopy ( input ) ; } if ( element == null ) return null ; return element . getRubyProject ( ) ; } public String [ ] getIndentPrefixes ( ISourceViewer sourceViewer , String contentType ) { Vector vector = new Vector ( ) ; IRubyProject project = getProject ( ) ; final int tabWidth = CodeFormatterUtil . getTabWidth ( project ) ; final int indentWidth = CodeFormatterUtil . getIndentWidth ( project ) ; int spaceEquivalents = Math . min ( tabWidth , indentWidth ) ; boolean useSpaces ; if ( project == null ) useSpaces = RubyCore . SPACE . equals ( RubyCore . getOption ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ) ) || tabWidth > indentWidth ; else useSpaces = RubyCore . SPACE . equals ( project . getOption ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , true ) ) || tabWidth > indentWidth ; for ( int i = ; i <= spaceEquivalents ; i ++ ) { StringBuffer prefix = new StringBuffer ( ) ; if ( useSpaces ) { for ( int j = ; j + i < spaceEquivalents ; j ++ ) prefix . append ( '' ) ; if ( i != ) prefix . append ( '' ) ; } else { for ( int j = ; j < i ; j ++ ) prefix . append ( '' ) ; if ( i != spaceEquivalents ) prefix . append ( '' ) ; } vector . add ( prefix . toString ( ) ) ; } vector . add ( "" ) ; return ( String [ ] ) vector . toArray ( new String [ vector . size ( ) ] ) ; } public ITextDoubleClickStrategy getDoubleClickStrategy ( ISourceViewer sourceViewer , String contentType ) { if ( fRubyDoubleClickSelector == null ) { fRubyDoubleClickSelector = new RubyDoubleClickSelector ( ) ; } return fRubyDoubleClickSelector ; } public int getTabWidth ( ISourceViewer sourceViewer ) { return CodeFormatterUtil . getTabWidth ( getProject ( ) ) ; } @ Override public ITextHover getTextHover ( ISourceViewer sourceViewer , String contentType , int stateMask ) { RubyEditorTextHoverDescriptor [ ] hoverDescs = RubyPlugin . getDefault ( ) . getRubyEditorTextHoverDescriptors ( ) ; int i = ; while ( i < hoverDescs . length ) { if ( hoverDescs [ i ] . isEnabled ( ) && hoverDescs [ i ] . getStateMask ( ) == stateMask ) return new RubyEditorTextHoverProxy ( hoverDescs [ i ] , getEditor ( ) ) ; i ++ ; } return null ; } public int [ ] getConfiguredTextHoverStateMasks ( ISourceViewer sourceViewer , String contentType ) { RubyEditorTextHoverDescriptor [ ] hoverDescs = RubyPlugin . getDefault ( ) . getRubyEditorTextHoverDescriptors ( ) ; int stateMasks [ ] = new int [ hoverDescs . length ] ; int stateMasksLength = ; for ( int i = ; i < hoverDescs . length ; i ++ ) { if ( hoverDescs [ i ] . isEnabled ( ) ) { int j = ; int stateMask = hoverDescs [ i ] . getStateMask ( ) ; while ( j < stateMasksLength ) { if ( stateMasks [ j ] == stateMask ) break ; j ++ ; } if ( j == stateMasksLength ) stateMasks [ stateMasksLength ++ ] = stateMask ; } } if ( stateMasksLength == hoverDescs . length ) return stateMasks ; int [ ] shortenedStateMasks = new int [ stateMasksLength ] ; System . arraycopy ( stateMasks , , shortenedStateMasks , , stateMasksLength ) ; return shortenedStateMasks ; } @ Override public IQuickAssistAssistant getQuickAssistAssistant ( ISourceViewer sourceViewer ) { if ( getEditor ( ) != null ) return new RubyCorrectionAssistant ( getEditor ( ) ) ; return null ; } public IInformationPresenter getOutlinePresenter ( ISourceViewer sourceViewer , boolean doCodeResolve ) { InformationPresenter presenter ; if ( doCodeResolve ) presenter = new InformationPresenter ( getOutlinePresenterControlCreator ( sourceViewer , IRubyEditorActionDefinitionIds . OPEN_STRUCTURE ) ) ; else presenter = new InformationPresenter ( getOutlinePresenterControlCreator ( sourceViewer , IRubyEditorActionDefinitionIds . SHOW_OUTLINE ) ) ; presenter . setDocumentPartitioning ( getConfiguredDocumentPartitioning ( sourceViewer ) ) ; presenter . setAnchor ( AbstractInformationControlManager . ANCHOR_GLOBAL ) ; IInformationProvider provider = new RubyElementProvider ( getEditor ( ) , doCodeResolve ) ; presenter . setInformationProvider ( provider , IDocument . DEFAULT_CONTENT_TYPE ) ; presenter . setInformationProvider ( provider , IRubyPartitions . RUBY_MULTI_LINE_COMMENT ) ; presenter . setInformationProvider ( provider , IRubyPartitions . RUBY_SINGLE_LINE_COMMENT ) ; presenter . setInformationProvider ( provider , IRubyPartitions . RUBY_STRING ) ; presenter . setInformationProvider ( provider , IRubyPartitions . RUBY_REGULAR_EXPRESSION ) ; presenter . setInformationProvider ( provider , IRubyPartitions . RUBY_COMMAND ) ; presenter . setSizeConstraints ( , , true , false ) ; return presenter ; } private IInformationControlCreator getOutlinePresenterControlCreator ( ISourceViewer sourceViewer , final String commandId ) { return new IInformationControlCreator ( ) { public IInformationControl createInformationControl ( Shell parent ) { int shellStyle = SWT . RESIZE ; int treeStyle = SWT . V_SCROLL | SWT . H_SCROLL ; return new RubyOutlineInformationControl ( parent , shellStyle , treeStyle , commandId ) ; } } ; } } package org . rubypeople . rdt . ui . text . correction ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRewriteTarget ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . jface . text . link . LinkedModeModel ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . NullChange ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . correction . CorrectionCommandHandler ; import org . rubypeople . rdt . internal . ui . text . correction . CorrectionMessages ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class ChangeCorrectionProposal implements IRubyCompletionProposal , ICommandAccess { private Change fChange ; private String fName ; private int fRelevance ; private Image fImage ; private String fCommandId ; public ChangeCorrectionProposal ( String name , Change change , int relevance , Image image ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } fName = name ; fChange = change ; fRelevance = relevance ; fImage = image ; fCommandId = null ; } public void apply ( IDocument document ) { try { performChange ( RubyPlugin . getActivePage ( ) . getActiveEditor ( ) , document ) ; } catch ( CoreException e ) { ExceptionHandler . handle ( e , CorrectionMessages . ChangeCorrectionProposal_error_title , CorrectionMessages . ChangeCorrectionProposal_error_message ) ; } } protected void performChange ( IEditorPart activeEditor , IDocument document ) throws CoreException { Change change = null ; IRewriteTarget rewriteTarget = null ; try { change = getChange ( ) ; if ( change != null ) { if ( document != null ) { LinkedModeModel . closeAllModels ( document ) ; } if ( activeEditor != null ) { rewriteTarget = ( IRewriteTarget ) activeEditor . getAdapter ( IRewriteTarget . class ) ; if ( rewriteTarget != null ) { rewriteTarget . beginCompoundChange ( ) ; } } change . initializeValidationData ( new NullProgressMonitor ( ) ) ; RefactoringStatus valid = change . isValid ( new NullProgressMonitor ( ) ) ; if ( valid . hasFatalError ( ) ) { IStatus status = new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . ERROR , valid . getMessageMatchingSeverity ( RefactoringStatus . FATAL ) , null ) ; throw new CoreException ( status ) ; } else { change . perform ( new NullProgressMonitor ( ) ) ; } } } finally { if ( rewriteTarget != null ) { rewriteTarget . endCompoundChange ( ) ; } if ( change != null ) { change . dispose ( ) ; } } } public String getAdditionalProposalInfo ( ) { StringBuffer buf = new StringBuffer ( ) ; buf . append ( "" ) ; try { Change change = getChange ( ) ; if ( change != null ) { String name = change . getName ( ) ; if ( name . length ( ) == ) { return null ; } buf . append ( name ) ; } else { return null ; } } catch ( CoreException e ) { buf . append ( "" ) ; buf . append ( e . getLocalizedMessage ( ) ) ; buf . append ( "" ) ; } buf . append ( "" ) ; return buf . toString ( ) ; } public IContextInformation getContextInformation ( ) { return null ; } public String getDisplayString ( ) { String shortCutString = CorrectionCommandHandler . getShortCutString ( getCommandId ( ) ) ; if ( shortCutString != null ) { return Messages . format ( CorrectionMessages . ChangeCorrectionProposal_name_with_shortcut , new String [ ] { fName , shortCutString } ) ; } return fName ; } public Image getImage ( ) { return fImage ; } public Point getSelection ( IDocument document ) { return null ; } public void setImage ( Image image ) { fImage = image ; } public final Change getChange ( ) throws CoreException { if ( fChange == null ) { fChange = createChange ( ) ; } return fChange ; } protected Change createChange ( ) throws CoreException { return new NullChange ( ) ; } public void setDisplayName ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } fName = name ; } public int getRelevance ( ) { return fRelevance ; } public void setRelevance ( int relevance ) { fRelevance = relevance ; } public String getCommandId ( ) { return fCommandId ; } public void setCommandId ( String commandId ) { fCommandId = commandId ; } } package org . rubypeople . rdt . ui . text . correction ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyCompletionProposal ; public class CorrectionProposal extends RubyCompletionProposal { public CorrectionProposal ( String replacementString , int replacementOffset , int replacementLength , Image image , String displayString , int relevance ) { super ( replacementString , replacementOffset , replacementLength , image , displayString , relevance ) ; } @ Override protected boolean isValidPrefix ( String prefix ) { return true ; } @ Override public void apply ( ITextViewer viewer , char trigger , int stateMask , int offset ) { IDocument document = viewer . getDocument ( ) ; apply ( document , trigger , getReplacementOffset ( ) ) ; } } package org . rubypeople . rdt . ui . text . correction ; public interface ICommandAccess { String getCommandId ( ) ; } package org . rubypeople . rdt . ui . text ; import org . eclipse . jface . text . rules . ITokenScanner ; import org . eclipse . jface . util . PropertyChangeEvent ; public interface IAbstractManagedScanner extends ITokenScanner { public boolean affectsBehavior ( PropertyChangeEvent event ) ; public void adaptToPreferenceChange ( PropertyChangeEvent event ) ; } package org . rubypeople . rdt . ui ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; public class TableViewerSorter extends ViewerSorter { private int columnIndex = ; public TableViewerSorter ( int columnIndex ) { this . columnIndex = columnIndex ; } public int compare ( Viewer viewer , Object e1 , Object e2 ) { int order = ; if ( viewer instanceof TableViewer ) { TableViewer tv = ( TableViewer ) viewer ; Table table = tv . getTable ( ) ; table . setSortColumn ( table . getColumn ( columnIndex ) ) ; int idx1 = - , idx2 = - ; for ( int i = ; i < table . getItemCount ( ) ; i ++ ) { Object obj = tv . getElementAt ( i ) ; if ( obj . equals ( e1 ) ) { idx1 = i ; } else if ( obj . equals ( e2 ) ) { idx2 = i ; } if ( idx1 > && idx2 > ) { break ; } } if ( idx1 > - && idx2 > - ) { String str1 = table . getItems ( ) [ idx1 ] . getText ( this . columnIndex ) ; String str2 = table . getItems ( ) [ idx2 ] . getText ( this . columnIndex ) ; order = str1 . compareTo ( str2 ) ; try { Double d1 = Double . valueOf ( str1 ) ; Double d2 = Double . valueOf ( str2 ) ; order = d1 . compareTo ( d2 ) ; } catch ( NumberFormatException e ) { } if ( table . getSortDirection ( ) != SWT . UP ) { order *= - ; } } } return order ; } public static void bind ( final TableViewer tableViewer ) { final Table table = tableViewer . getTable ( ) ; for ( int i = ; i < table . getColumnCount ( ) ; i ++ ) { final int columnNum = i ; TableColumn column = table . getColumn ( i ) ; column . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( final SelectionEvent e ) { TableViewerSorter sorter = new TableViewerSorter ( columnNum ) ; if ( table . getSortDirection ( ) == SWT . UP ) { table . setSortDirection ( SWT . DOWN ) ; } else if ( table . getSortDirection ( ) == SWT . DOWN ) { table . setSortDirection ( SWT . UP ) ; } else { table . setSortDirection ( SWT . UP ) ; } tableViewer . setSorter ( sorter ) ; } } ) ; } } public static void bind ( final TableViewer tableViewer , int columnIndex ) { bind ( tableViewer ) ; TableViewerSorter sorter = new TableViewerSorter ( columnIndex ) ; tableViewer . setSorter ( sorter ) ; } } package org . rubypeople . rdt . ui . rubyeditor ; import org . eclipse . ui . views . contentoutline . IContentOutlinePage ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyAbstractEditor ; public interface ICustomRubyOutlinePage extends IContentOutlinePage { public boolean isEnabled ( IRubyElement inputElement ) ; public void init ( String outlinerContextMenuId , RubyAbstractEditor rubyAbstractEditor ) ; public void select ( ISourceReference reference ) ; public void setInput ( IRubyElement inputElement ) ; } package org . rubypeople . rdt . ui ; public interface IRubyConstants { public static final String EDITOR_ID = RubyUI . ID_RUBY_EDITOR ; public static final String EXTERNAL_FILES_EDITOR_ID = RubyUI . ID_EXTERNAL_EDITOR ; public static final String RI_VIEW_ID = "" ; public static final String ID_NEW_CLASS_WIZARD = "" ; } package org . rubypeople . rdt . ui ; import org . eclipse . ui . navigator . ICommonMenuConstants ; public interface IContextMenuConstants { public static final String TARGET_ID_HIERARCHY_VIEW = RubyUI . ID_TYPE_HIERARCHY + "" ; public static final String TARGET_ID_SUPERTYPES_VIEW = RubyUI . ID_TYPE_HIERARCHY + "" ; public static final String TARGET_ID_SUBTYPES_VIEW = RubyUI . ID_TYPE_HIERARCHY + "" ; public static final String TARGET_ID_MEMBERS_VIEW = RubyUI . ID_TYPE_HIERARCHY + "" ; public static final String GROUP_SHOW = ICommonMenuConstants . GROUP_SHOW ; public static final String GROUP_NEW = ICommonMenuConstants . GROUP_NEW ; public static final String GROUP_SEARCH = ICommonMenuConstants . GROUP_SEARCH ; public static final String GROUP_OPEN = ICommonMenuConstants . GROUP_OPEN ; public static final String GROUP_PROPERTIES = ICommonMenuConstants . GROUP_PROPERTIES ; public static final String GROUP_REORGANIZE = ICommonMenuConstants . GROUP_REORGANIZE ; public static final String GROUP_BUILD = ICommonMenuConstants . GROUP_BUILD ; public static final String GROUP_GOTO = ICommonMenuConstants . GROUP_GOTO ; } package org . rubypeople . rdt . ui . extensions ; import org . eclipse . jface . text . templates . persistence . TemplatePersistenceData ; public interface IRubyTemplateProvider { public TemplatePersistenceData [ ] getTemplateData ( ) ; } package org . rubypeople . rdt . ui ; public interface IWorkingCopyProvider { public boolean providesWorkingCopies ( ) ; } package org . rubypeople . rdt . ui . search ; import org . eclipse . search . ui . text . Match ; public interface ISearchRequestor { void reportMatch ( Match match ) ; } package org . rubypeople . rdt . ui . search ; import org . rubypeople . rdt . core . search . IRubySearchScope ; public abstract class QuerySpecification { private IRubySearchScope fScope ; private int fLimitTo ; private String fScopeDescription ; QuerySpecification ( int limitTo , IRubySearchScope scope , String scopeDescription ) { fScope = scope ; fLimitTo = limitTo ; fScopeDescription = scopeDescription ; } public IRubySearchScope getScope ( ) { return fScope ; } public String getScopeDescription ( ) { return fScopeDescription ; } public int getLimitTo ( ) { return fLimitTo ; } } package org . rubypeople . rdt . ui . search ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IQueryParticipant { void search ( ISearchRequestor requestor , QuerySpecification querySpecification , IProgressMonitor monitor ) throws CoreException ; int estimateTicks ( QuerySpecification specification ) ; IMatchPresentation getUIParticipant ( ) ; } package org . rubypeople . rdt . ui . search ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . IRubySearchScope ; public class ElementQuerySpecification extends QuerySpecification { private IRubyElement fElement ; public ElementQuerySpecification ( IRubyElement RubyElement , int limitTo , IRubySearchScope scope , String scopeDescription ) { super ( limitTo , scope , scopeDescription ) ; fElement = RubyElement ; } public IRubyElement getElement ( ) { return fElement ; } } package org . rubypeople . rdt . ui . search ; import org . jruby . Ruby ; import org . rubypeople . rdt . core . search . IRubySearchScope ; public class PatternQuerySpecification extends QuerySpecification { private String fPattern ; private int fSearchFor ; private boolean fCaseSensitive ; public PatternQuerySpecification ( String pattern , int searchFor , boolean caseSensitive , int limitTo , IRubySearchScope scope , String scopeDescription ) { super ( limitTo , scope , scopeDescription ) ; fPattern = pattern ; fSearchFor = searchFor ; fCaseSensitive = caseSensitive ; } public boolean isCaseSensitive ( ) { return fCaseSensitive ; } public String getPattern ( ) { return fPattern ; } public int getSearchFor ( ) { return fSearchFor ; } } package org . rubypeople . rdt . ui . search ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . search . ui . text . Match ; import org . eclipse . ui . PartInitException ; public interface IMatchPresentation { ILabelProvider createLabelProvider ( ) ; void showMatch ( Match match , int currentOffset , int currentLength , boolean activate ) throws PartInitException ; } package org . rubypeople . rdt . ui ; import java . text . Collator ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IStorage ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . viewers . ContentViewer ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerSorter ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . packageview . LoadPathContainer ; import org . rubypeople . rdt . internal . ui . preferences . MembersOrderPreferenceCache ; public class RubyElementSorter extends ViewerSorter { private static final int PROJECTS = ; private static final int SOURCEFOLDERROOTS = ; private static final int SOURCEFOLDER = ; private static final int RUBYSCRIPTS = ; private static final int RESOURCEFOLDERS = ; private static final int RESOURCES = ; private static final int STORAGE = ; private static final int IMPORT_CONTAINER = ; private static final int IMPORT_DECLARATION = ; private static final int MEMBERSOFFSET = ; private static final int RUBYELEMENTS = ; private static final int OTHERS = ; private MembersOrderPreferenceCache fMemberOrderCache ; private Collator fNewCollator ; public RubyElementSorter ( ) { super ( null ) ; fMemberOrderCache = RubyPlugin . getDefault ( ) . getMemberOrderPreferenceCache ( ) ; fNewCollator = null ; } public final Collator getCollator ( ) { if ( collator == null ) { collator = Collator . getInstance ( ) ; } return collator ; } public int category ( Object element ) { if ( element instanceof IRubyElement ) { IRubyElement je = ( IRubyElement ) element ; switch ( je . getElementType ( ) ) { case IRubyElement . METHOD : { IMethod method = ( IMethod ) je ; if ( method . isConstructor ( ) ) { return getMemberCategory ( MembersOrderPreferenceCache . CONSTRUCTORS_INDEX ) ; } if ( method . isSingleton ( ) ) return getMemberCategory ( MembersOrderPreferenceCache . STATIC_METHODS_INDEX ) ; else return getMemberCategory ( MembersOrderPreferenceCache . METHOD_INDEX ) ; } case IRubyElement . FIELD : case IRubyElement . CLASS_VAR : case IRubyElement . INSTANCE_VAR : case IRubyElement . CONSTANT : { return getMemberCategory ( MembersOrderPreferenceCache . FIELDS_INDEX ) ; } case IRubyElement . TYPE : return getMemberCategory ( MembersOrderPreferenceCache . TYPE_INDEX ) ; case IRubyElement . IMPORT_CONTAINER : return IMPORT_CONTAINER ; case IRubyElement . IMPORT_DECLARATION : return IMPORT_DECLARATION ; case IRubyElement . SOURCE_FOLDER : return SOURCEFOLDER ; case IRubyElement . SOURCE_FOLDER_ROOT : return SOURCEFOLDERROOTS ; case IRubyElement . RUBY_PROJECT : return PROJECTS ; case IRubyElement . SCRIPT : return RUBYSCRIPTS ; } return RUBYELEMENTS ; } else if ( element instanceof IFile ) { return RESOURCES ; } else if ( element instanceof IProject ) { return PROJECTS ; } else if ( element instanceof IContainer ) { return RESOURCEFOLDERS ; } else if ( element instanceof IStorage ) { return STORAGE ; } else if ( element instanceof LoadPathContainer ) { return SOURCEFOLDERROOTS ; } return OTHERS ; } private int getMemberCategory ( int kind ) { int offset = fMemberOrderCache . getCategoryIndex ( kind ) ; return offset + MEMBERSOFFSET ; } public int compare ( Viewer viewer , Object e1 , Object e2 ) { int cat1 = category ( e1 ) ; int cat2 = category ( e2 ) ; if ( needsLoadpathComparision ( e1 , cat1 , e2 , cat2 ) ) { ISourceFolderRoot root1 = getSourceFolderRoot ( e1 ) ; ISourceFolderRoot root2 = getSourceFolderRoot ( e2 ) ; if ( root1 == null ) { if ( root2 == null ) { return ; } else { return ; } } else if ( root2 == null ) { return - ; } if ( ! root1 . getPath ( ) . equals ( root2 . getPath ( ) ) ) { int p1 = getLoadPathIndex ( root1 ) ; int p2 = getLoadPathIndex ( root2 ) ; if ( p1 != p2 ) { return p1 - p2 ; } } } if ( cat1 != cat2 ) return cat1 - cat2 ; if ( cat1 == PROJECTS || cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == STORAGE || cat1 == OTHERS ) { String name1 = getNonRubyElementLabel ( viewer , e1 ) ; String name2 = getNonRubyElementLabel ( viewer , e2 ) ; if ( name1 != null && name2 != null ) { return getCollator ( ) . compare ( name1 , name2 ) ; } return ; } if ( e1 instanceof IMethod ) { if ( fMemberOrderCache . isSortByVisibility ( ) ) { try { int flags1 = ( ( IMethod ) e1 ) . getVisibility ( ) ; int flags2 = ( ( IMethod ) e2 ) . getVisibility ( ) ; int vis = fMemberOrderCache . getVisibilityIndex ( flags1 ) - fMemberOrderCache . getVisibilityIndex ( flags2 ) ; if ( vis != ) { return vis ; } } catch ( RubyModelException ignore ) { } } } if ( e1 instanceof IMember ) { } String name1 = getElementName ( e1 ) ; String name2 = getElementName ( e2 ) ; if ( e1 instanceof IType ) { if ( name1 . length ( ) == ) { if ( name2 . length ( ) == ) { try { return getCollator ( ) . compare ( ( ( IType ) e1 ) . getSuperclassName ( ) , ( ( IType ) e2 ) . getSuperclassName ( ) ) ; } catch ( RubyModelException e ) { return ; } } else { return ; } } else if ( name2 . length ( ) == ) { return - ; } } int cmp = getCollator ( ) . compare ( name1 , name2 ) ; if ( cmp != ) { return cmp ; } try { if ( e1 instanceof IMethod ) { String [ ] params1 = ( ( IMethod ) e1 ) . getParameterNames ( ) ; String [ ] params2 = ( ( IMethod ) e2 ) . getParameterNames ( ) ; int len = Math . min ( params1 . length , params2 . length ) ; for ( int i = ; i < len ; i ++ ) { cmp = getCollator ( ) . compare ( params1 [ i ] , params2 [ i ] ) ; if ( cmp != ) { return cmp ; } } return params1 . length - params2 . length ; } return ; } catch ( RubyModelException e ) { return ; } } protected String getElementName ( Object element ) { if ( element instanceof IRubyElement ) { return ( ( IRubyElement ) element ) . getElementName ( ) ; } else { return element . toString ( ) ; } } private String getNonRubyElementLabel ( Viewer viewer , Object element ) { if ( element instanceof IAdaptable ) { IWorkbenchAdapter adapter = ( IWorkbenchAdapter ) ( ( IAdaptable ) element ) . getAdapter ( IWorkbenchAdapter . class ) ; if ( adapter != null ) { return adapter . getLabel ( element ) ; } } if ( viewer instanceof ContentViewer ) { IBaseLabelProvider prov = ( ( ContentViewer ) viewer ) . getLabelProvider ( ) ; if ( prov instanceof ILabelProvider ) { return ( ( ILabelProvider ) prov ) . getText ( element ) ; } } return null ; } private boolean needsLoadpathComparision ( Object e1 , int cat1 , Object e2 , int cat2 ) { if ( ( cat1 == SOURCEFOLDERROOTS && cat2 == SOURCEFOLDERROOTS ) || ( cat1 == SOURCEFOLDER && ( ( ISourceFolder ) e1 ) . getParent ( ) . getResource ( ) instanceof IProject && cat2 == SOURCEFOLDERROOTS ) || ( cat1 == SOURCEFOLDERROOTS && cat2 == SOURCEFOLDER && ( ( ISourceFolder ) e2 ) . getParent ( ) . getResource ( ) instanceof IProject ) ) { IRubyProject p1 = getRubyProject ( e1 ) ; return p1 != null && p1 . equals ( getRubyProject ( e2 ) ) ; } return false ; } private IRubyProject getRubyProject ( Object element ) { if ( element instanceof IRubyElement ) { return ( ( IRubyElement ) element ) . getRubyProject ( ) ; } else if ( element instanceof LoadPathContainer ) { return ( ( LoadPathContainer ) element ) . getRubyProject ( ) ; } return null ; } private ISourceFolderRoot getSourceFolderRoot ( Object element ) { if ( element instanceof LoadPathContainer ) { LoadPathContainer cp = ( LoadPathContainer ) element ; Object [ ] roots = cp . getSourceFolderRoots ( ) ; if ( roots . length > ) return ( ISourceFolderRoot ) roots [ ] ; return null ; } return RubyModelUtil . getSourceFolderRoot ( ( IRubyElement ) element ) ; } private int getLoadPathIndex ( ISourceFolderRoot root ) { try { IPath rootPath = root . getPath ( ) ; ISourceFolderRoot [ ] roots = root . getRubyProject ( ) . getSourceFolderRoots ( ) ; for ( int i = ; i < roots . length ; i ++ ) { if ( roots [ i ] . getPath ( ) . equals ( rootPath ) ) { return i ; } } } catch ( RubyModelException e ) { } return Integer . MAX_VALUE ; } } package org . rubypeople . rdt . ui ; import java . io . File ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyBlock ; public class StandardRubyElementContentProvider implements ITreeContentProvider { protected static final Object [ ] NO_CHILDREN = new Object [ ] ; protected boolean fProvideMembers ; protected boolean fProvideWorkingCopy ; public StandardRubyElementContentProvider ( ) { this ( false ) ; } public StandardRubyElementContentProvider ( boolean provideMembers , boolean provideWorkingCopy ) { this ( provideMembers ) ; } public StandardRubyElementContentProvider ( boolean provideMembers ) { fProvideMembers = provideMembers ; fProvideWorkingCopy = provideMembers ; } public boolean getProvideMembers ( ) { return fProvideMembers ; } public void setProvideMembers ( boolean b ) { fProvideMembers = b ; } public boolean getProvideWorkingCopy ( ) { return fProvideWorkingCopy ; } public void setProvideWorkingCopy ( boolean b ) { fProvideWorkingCopy = b ; } public boolean providesWorkingCopies ( ) { return getProvideWorkingCopy ( ) ; } public Object [ ] getElements ( Object parent ) { return getChildren ( parent ) ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void dispose ( ) { } public Object [ ] getChildren ( Object element ) { if ( ! exists ( element ) ) return NO_CHILDREN ; try { if ( element instanceof IRubyModel ) return getRubyProjects ( ( IRubyModel ) element ) ; if ( element instanceof IRubyProject ) return getSourceFolderRoots ( ( IRubyProject ) element ) ; if ( element instanceof ISourceFolderRoot ) return getSourceFolders ( ( ISourceFolderRoot ) element ) ; if ( element instanceof ISourceFolder ) return getFoldersAndRubyScripts ( ( ISourceFolder ) element ) ; if ( element instanceof IFolder ) return getResources ( ( IFolder ) element ) ; if ( getProvideMembers ( ) && element instanceof ISourceReference && element instanceof IParent ) { return removeBlocks ( ( ( IParent ) element ) . getChildren ( ) ) ; } } catch ( RubyModelException e ) { return NO_CHILDREN ; } return NO_CHILDREN ; } protected Object [ ] removeBlocks ( Object [ ] members ) { ArrayList tempResult = new ArrayList ( members . length ) ; for ( int i = ; i < members . length ; i ++ ) if ( ! ( members [ i ] instanceof RubyBlock ) ) tempResult . add ( members [ i ] ) ; return tempResult . toArray ( ) ; } private Object [ ] getSourceFolders ( ISourceFolderRoot root ) throws RubyModelException { IRubyElement [ ] fragments = root . getChildren ( ) ; List < IRubyElement > list = new ArrayList < IRubyElement > ( ) ; for ( int i = ; i < fragments . length ; i ++ ) { if ( ! ( fragments [ i ] instanceof ISourceFolder ) ) continue ; ISourceFolder folder = ( ISourceFolder ) fragments [ i ] ; if ( folder . isDefaultPackage ( ) ) { list . addAll ( Arrays . asList ( folder . getRubyScripts ( ) ) ) ; continue ; } String name = folder . getElementName ( ) ; int index = name . indexOf ( File . separatorChar ) ; if ( index == - ) list . add ( folder ) ; } fragments = new IRubyElement [ list . size ( ) ] ; fragments = list . toArray ( fragments ) ; Object [ ] nonRubyResources = root . getNonRubyResources ( ) ; if ( nonRubyResources == null ) return fragments ; return concatenate ( fragments , nonRubyResources ) ; } private Object [ ] getSourceFolderRoots ( IRubyProject project ) throws RubyModelException { if ( ! project . getProject ( ) . isOpen ( ) ) return NO_CHILDREN ; ISourceFolderRoot [ ] roots = project . getSourceFolderRoots ( ) ; List list = new ArrayList ( roots . length ) ; for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; if ( isProjectSourceFolderRoot ( root ) ) { Object [ ] children = getChildren ( root ) ; for ( int k = ; k < children . length ; k ++ ) list . add ( children [ k ] ) ; } else if ( hasChildren ( root ) ) { list . add ( root ) ; } } return concatenate ( list . toArray ( ) , project . getNonRubyResources ( ) ) ; } protected boolean isProjectSourceFolderRoot ( ISourceFolderRoot root ) { IResource resource = root . getResource ( ) ; return ( resource instanceof IProject ) ; } private Object [ ] getFoldersAndRubyScripts ( ISourceFolder folder ) throws RubyModelException { ISourceFolderRoot root = ( ISourceFolderRoot ) folder . getParent ( ) ; IRubyElement [ ] children = root . getChildren ( ) ; List < IRubyElement > list = new ArrayList < IRubyElement > ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( children [ i ] . equals ( folder ) ) continue ; if ( ! children [ i ] . getElementName ( ) . startsWith ( folder . getElementName ( ) ) ) continue ; String name = children [ i ] . getElementName ( ) ; name = name . substring ( folder . getElementName ( ) . length ( ) + ) ; int index = name . indexOf ( File . separator ) ; if ( index != - ) continue ; list . add ( children [ i ] ) ; } IRubyElement [ ] folders = new IRubyElement [ list . size ( ) ] ; folders = list . toArray ( folders ) ; return concatenate ( folders , concatenate ( folder . getRubyScripts ( ) , folder . getNonRubyResources ( ) ) ) ; } public boolean hasChildren ( Object element ) { if ( getProvideMembers ( ) ) { if ( element instanceof IRubyScript ) { return true ; } } else { if ( element instanceof IRubyScript || element instanceof IFile ) return false ; } if ( element instanceof IRubyProject ) { IRubyProject jp = ( IRubyProject ) element ; if ( ! jp . getProject ( ) . isOpen ( ) ) { return false ; } } if ( element instanceof IParent ) { try { if ( ( ( IParent ) element ) . hasChildren ( ) ) return true ; } catch ( RubyModelException e ) { return true ; } } Object [ ] children = getChildren ( element ) ; return ( children != null ) && children . length > ; } public Object getParent ( Object element ) { if ( ! exists ( element ) ) return null ; return internalGetParent ( element ) ; } protected Object [ ] getRubyProjects ( IRubyModel jm ) throws RubyModelException { return jm . getRubyProjects ( ) ; } private Object [ ] getResources ( IFolder folder ) { try { IResource [ ] members = folder . members ( ) ; IRubyProject javaProject = RubyCore . create ( folder . getProject ( ) ) ; if ( javaProject == null || ! javaProject . exists ( ) ) return members ; boolean isFolderOnClasspath = true ; List nonRubyResources = new ArrayList ( ) ; for ( int i = ; i < members . length ; i ++ ) { IResource member = members [ i ] ; if ( isFolderOnClasspath ) { } } return nonRubyResources . toArray ( ) ; } catch ( CoreException e ) { return NO_CHILDREN ; } } protected boolean isClassPathChange ( IRubyElementDelta delta ) { return false ; } protected boolean exists ( Object element ) { if ( element == null ) { return false ; } if ( element instanceof IResource ) { return ( ( IResource ) element ) . exists ( ) ; } if ( element instanceof IRubyElement ) { return ( ( IRubyElement ) element ) . exists ( ) ; } return true ; } protected Object internalGetParent ( Object element ) { if ( element instanceof IResource ) { IResource parent = ( ( IResource ) element ) . getParent ( ) ; IRubyElement jParent = RubyCore . create ( parent ) ; if ( jParent != null && jParent . exists ( ) ) return jParent ; return parent ; } else if ( element instanceof IRubyElement ) { IRubyElement parent = ( ( IRubyElement ) element ) . getParent ( ) ; return parent ; } return null ; } protected static Object [ ] concatenate ( Object [ ] a1 , Object [ ] a2 ) { int a1Len = a1 . length ; int a2Len = a2 . length ; Object [ ] res = new Object [ a1Len + a2Len ] ; System . arraycopy ( a1 , , res , , a1Len ) ; System . arraycopy ( a2 , , res , a1Len , a2Len ) ; return res ; } protected Object skipProjectSourceFolderRoot ( ISourceFolderRoot root ) { if ( isProjectSourceFolderRoot ( root ) ) return root . getParent ( ) ; return root ; } protected boolean isSourceFolderEmpty ( IRubyElement element ) throws RubyModelException { if ( element instanceof ISourceFolder ) { ISourceFolder fragment = ( ISourceFolder ) element ; if ( fragment . exists ( ) && ! ( fragment . hasChildren ( ) || fragment . getNonRubyResources ( ) . length > ) && fragment . hasSubfolders ( ) ) return true ; } return false ; } } package org . rubypeople . rdt . ui ; import org . eclipse . jface . resource . ImageDescriptor ; public interface IHasImageDescriptor { ImageDescriptor getImageDescriptor ( ) ; } package org . rubypeople . rdt . ui ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . IDecoration ; import org . eclipse . jface . viewers . ILabelDecorator ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ILightweightLabelDecorator ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . MethodOverrideTester ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . corext . util . SuperTypeHierarchyCache ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; import org . rubypeople . rdt . ui . viewsupport . ImageImageDescriptor ; public class OverrideIndicatorLabelDecorator implements ILabelDecorator , ILightweightLabelDecorator { private ImageDescriptorRegistry fRegistry ; private boolean fUseNewRegistry = false ; public OverrideIndicatorLabelDecorator ( ) { this ( null ) ; fUseNewRegistry = true ; } public OverrideIndicatorLabelDecorator ( ImageDescriptorRegistry registry ) { fRegistry = registry ; } private ImageDescriptorRegistry getRegistry ( ) { if ( fRegistry == null ) { fRegistry = fUseNewRegistry ? new ImageDescriptorRegistry ( ) : RubyPlugin . getImageDescriptorRegistry ( ) ; } return fRegistry ; } public String decorateText ( String text , Object element ) { return text ; } public Image decorateImage ( Image image , Object element ) { int adornmentFlags = computeAdornmentFlags ( element ) ; if ( adornmentFlags != ) { ImageDescriptor baseImage = new ImageImageDescriptor ( image ) ; Rectangle bounds = image . getBounds ( ) ; return getRegistry ( ) . get ( new RubyElementImageDescriptor ( baseImage , adornmentFlags , new Point ( bounds . width , bounds . height ) ) ) ; } return image ; } public int computeAdornmentFlags ( Object element ) { if ( element instanceof IMethod ) { try { IMethod method = ( IMethod ) element ; if ( ! method . getRubyProject ( ) . isOnLoadpath ( method ) ) { return ; } if ( ! method . isConstructor ( ) && method . getVisibility ( ) != IMethod . PRIVATE && ! method . isSingleton ( ) ) { int res = getOverrideIndicators ( method ) ; return res ; } } catch ( RubyModelException e ) { if ( ! e . isDoesNotExist ( ) ) { RubyPlugin . log ( e ) ; } } } return ; } protected int getOverrideIndicators ( IMethod method ) throws RubyModelException { IType type = method . getDeclaringType ( ) ; if ( type == null ) { return ; } MethodOverrideTester methodOverrideTester = SuperTypeHierarchyCache . getMethodOverrideTester ( type ) ; IMethod defining = methodOverrideTester . findOverriddenMethod ( method , true ) ; if ( defining != null ) { return RubyElementImageDescriptor . OVERRIDES ; } return ; } protected int findInHierarchy ( IType type , ITypeHierarchy hierarchy , String name , String [ ] paramTypes ) throws RubyModelException { IType superClass = hierarchy . getSuperclass ( type ) ; if ( superClass != null ) { IMethod res = RubyModelUtil . findMethodInHierarchy ( hierarchy , superClass , name , paramTypes , false ) ; if ( res != null && res . getVisibility ( ) != IMethod . PRIVATE && RubyModelUtil . isVisibleInHierarchy ( res , type . getSourceFolder ( ) ) ) { return RubyElementImageDescriptor . OVERRIDES ; } } IType [ ] interfaces = hierarchy . getSuperModules ( type ) ; for ( int i = ; i < interfaces . length ; i ++ ) { IMethod res = RubyModelUtil . findMethodInHierarchy ( hierarchy , interfaces [ i ] , name , paramTypes , false ) ; if ( res != null ) { return RubyElementImageDescriptor . OVERRIDES ; } } return ; } public void addListener ( ILabelProviderListener listener ) { } public void dispose ( ) { if ( fRegistry != null && fUseNewRegistry ) { fRegistry . dispose ( ) ; } } public boolean isLabelProperty ( Object element , String property ) { return true ; } public void removeListener ( ILabelProviderListener listener ) { } public void decorate ( Object element , IDecoration decoration ) { int adornmentFlags = computeAdornmentFlags ( element ) ; if ( ( adornmentFlags & RubyElementImageDescriptor . IMPLEMENTS ) != ) { decoration . addOverlay ( RubyPluginImages . DESC_OVR_IMPLEMENTS ) ; } else if ( ( adornmentFlags & RubyElementImageDescriptor . OVERRIDES ) != ) { decoration . addOverlay ( RubyPluginImages . DESC_OVR_OVERRIDES ) ; } } } package org . rubypeople . rdt . ui ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . ui . IEditorInput ; import org . rubypeople . rdt . core . IRubyScript ; public interface IWorkingCopyManager { void connect ( IEditorInput input ) throws CoreException ; void disconnect ( IEditorInput input ) ; IRubyScript getWorkingCopy ( IEditorInput input ) ; void shutdown ( ) ; } package org . rubypeople . rdt . ui ; import java . io . File ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . ui . model . IWorkbenchAdapter ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; public class RubyElementLabels { public final static long M_PARAMETER_NAMES = << ; public final static long M_FULLY_QUALIFIED = << ; public final static long M_POST_QUALIFIED = << ; public final static long I_FULLY_QUALIFIED = << ; public final static long I_POST_QUALIFIED = << ; public final static long F_FULLY_QUALIFIED = << ; public final static long F_POST_QUALIFIED = << ; public final static long T_FILENAME_QUALIFIED = << ; public final static long T_NAME_FULLY_QUALIFIED = << ; public final static long T_POST_QUALIFIED = << ; public final static long D_QUALIFIED = << ; public final static long D_POST_QUALIFIED = << ; public final static long CF_QUALIFIED = << ; public final static long CF_POST_QUALIFIED = << ; public final static long CU_QUALIFIED = << ; public final static long CU_POST_QUALIFIED = << ; public final static long P_QUALIFIED = << ; public final static long P_POST_QUALIFIED = << ; public final static long P_COMPRESSED = << ; public final static long ROOT_VARIABLE = << ; public final static long ROOT_QUALIFIED = << ; public final static long ROOT_POST_QUALIFIED = << ; public final static long APPEND_ROOT_PATH = << ; public final static long PREPEND_ROOT_PATH = << ; public final static long REFERENCED_ROOT_POST_QUALIFIED = << ; public final static long USE_RESOLVED = << ; public final static long ALL_FULLY_QUALIFIED = new Long ( F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FILENAME_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED | P_QUALIFIED | ROOT_QUALIFIED ) . longValue ( ) ; public final static long ALL_POST_QUALIFIED = new Long ( F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED | P_POST_QUALIFIED | ROOT_POST_QUALIFIED ) . longValue ( ) ; public final static long ALL_DEFAULT = new Long ( M_PARAMETER_NAMES ) . longValue ( ) ; public final static long DEFAULT_QUALIFIED = new Long ( F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FILENAME_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED ) . longValue ( ) ; public final static long DEFAULT_POST_QUALIFIED = new Long ( F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED ) . longValue ( ) ; public final static long F_CATEGORY = << ; public final static long M_CATEGORY = << ; public final static long T_CATEGORY = << ; public final static long ALL_CATEGORY = new Long ( RubyElementLabels . F_CATEGORY | RubyElementLabels . M_CATEGORY | RubyElementLabels . T_CATEGORY ) . longValue ( ) ; public final static String CONCAT_STRING = RubyUIMessages . RubyElementLabels_concat_string ; public final static String COMMA_STRING = RubyUIMessages . RubyElementLabels_comma_string ; public final static String DECL_STRING = RubyUIMessages . RubyElementLabels_declseparator_string ; public final static String ELLIPSIS_STRING = "" ; private final static long QUALIFIER_FLAGS = P_COMPRESSED | USE_RESOLVED ; public final static String DEFAULT_PACKAGE = RubyUIMessages . RubyElementLabels_default_package ; private static String fgPkgNamePattern = "" ; private static String fgPkgNamePrefix ; private static String fgPkgNamePostfix ; private static int fgPkgNameChars ; private static int fgPkgNameLength = - ; private RubyElementLabels ( ) { } private static final boolean getFlag ( long flags , long flag ) { return ( flags & flag ) != ; } public static String getTextLabel ( Object obj , long flags ) { if ( obj instanceof IRubyElement ) { return getElementLabel ( ( IRubyElement ) obj , flags ) ; } else if ( obj instanceof IAdaptable ) { IWorkbenchAdapter wbadapter = ( IWorkbenchAdapter ) ( ( IAdaptable ) obj ) . getAdapter ( IWorkbenchAdapter . class ) ; if ( wbadapter != null ) { return wbadapter . getLabel ( obj ) ; } } return "" ; } public static String getElementLabel ( IRubyElement element , long flags ) { StringBuffer buf = new StringBuffer ( ) ; getElementLabel ( element , flags , buf ) ; return buf . toString ( ) ; } public static void getElementLabel ( IRubyElement element , long flags , StringBuffer buf ) { int type = element . getElementType ( ) ; switch ( type ) { case IRubyElement . METHOD : getMethodLabel ( ( IMethod ) element , flags , buf ) ; break ; case IRubyElement . FIELD : getFieldLabel ( ( IField ) element , flags , buf ) ; break ; case IRubyElement . LOCAL_VARIABLE : getLocalVariableLabel ( ( IField ) element , flags , buf ) ; break ; case IRubyElement . TYPE : getTypeLabel ( ( IType ) element , flags , buf ) ; break ; case IRubyElement . SCRIPT : getRubyScriptLabel ( ( IRubyScript ) element , flags , buf ) ; break ; case IRubyElement . IMPORT_CONTAINER : case IRubyElement . IMPORT_DECLARATION : getDeclarationLabel ( element , flags , buf ) ; break ; case IRubyElement . SOURCE_FOLDER : getSourceFolderLabel ( ( ISourceFolder ) element , flags , buf ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : getSourceFolderRootLabel ( ( ISourceFolderRoot ) element , flags , buf ) ; break ; case IRubyElement . RUBY_PROJECT : case IRubyElement . RUBY_MODEL : default : buf . append ( element . getElementName ( ) ) ; } } public static void getMethodLabel ( IMethod method , long flags , StringBuffer buf ) { try { if ( getFlag ( flags , M_FULLY_QUALIFIED ) ) { if ( method . getDeclaringType ( ) != null ) { getTypeLabel ( method . getDeclaringType ( ) , T_NAME_FULLY_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , buf ) ; buf . append ( '' ) ; } } buf . append ( method . getElementName ( ) ) ; buf . append ( '' ) ; if ( getFlag ( flags , M_PARAMETER_NAMES ) ) { String [ ] types = null ; int nParams = ; boolean renderVarargs = false ; String [ ] names = null ; if ( getFlag ( flags , M_PARAMETER_NAMES ) && method . exists ( ) ) { names = method . getParameterNames ( ) ; if ( types == null ) { nParams = names . length ; } else { if ( nParams != names . length ) { names = null ; } } } for ( int i = ; i < nParams ; i ++ ) { if ( i > ) { buf . append ( COMMA_STRING ) ; } if ( names != null ) { buf . append ( names [ i ] ) ; } } } buf . append ( '' ) ; if ( getFlag ( flags , M_POST_QUALIFIED ) ) { if ( method . getDeclaringType ( ) != null ) { buf . append ( CONCAT_STRING ) ; getTypeLabel ( method . getDeclaringType ( ) , T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , buf ) ; } } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } public static void getFieldLabel ( IField field , long flags , StringBuffer buf ) { if ( getFlag ( flags , F_FULLY_QUALIFIED ) ) { getTypeLabel ( field . getDeclaringType ( ) , T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , buf ) ; buf . append ( '' ) ; } buf . append ( field . getElementName ( ) ) ; if ( getFlag ( flags , F_POST_QUALIFIED ) ) { buf . append ( CONCAT_STRING ) ; getTypeLabel ( field . getDeclaringType ( ) , T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , buf ) ; } } public static void getLocalVariableLabel ( IField localVariable , long flags , StringBuffer buf ) { if ( getFlag ( flags , F_FULLY_QUALIFIED ) ) { getElementLabel ( localVariable . getParent ( ) , M_FULLY_QUALIFIED | T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , buf ) ; buf . append ( '' ) ; } buf . append ( localVariable . getElementName ( ) ) ; if ( getFlag ( flags , F_POST_QUALIFIED ) ) { buf . append ( CONCAT_STRING ) ; getElementLabel ( localVariable . getParent ( ) , M_FULLY_QUALIFIED | T_FILENAME_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , buf ) ; } } public static void getTypeLabel ( IType type , long flags , StringBuffer buf ) { if ( getFlag ( flags , T_FILENAME_QUALIFIED ) ) { ISourceFolder folder = type . getSourceFolder ( ) ; if ( ! folder . isDefaultPackage ( ) ) { getSourceFolderLabel ( folder , ( flags & QUALIFIER_FLAGS ) , buf ) ; buf . append ( '' ) ; } getRubyScriptLabel ( type . getRubyScript ( ) , ( flags & QUALIFIER_FLAGS ) , buf ) ; buf . append ( '' ) ; } if ( getFlag ( flags , T_FILENAME_QUALIFIED | T_NAME_FULLY_QUALIFIED ) ) { IType declaringType = type . getDeclaringType ( ) ; if ( declaringType != null ) { getTypeLabel ( declaringType , T_NAME_FULLY_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , buf ) ; buf . append ( "" ) ; } int parentType = type . getParent ( ) . getElementType ( ) ; if ( parentType == IRubyElement . METHOD || parentType == IRubyElement . FIELD ) { getElementLabel ( type . getParent ( ) , , buf ) ; buf . append ( '' ) ; } } String typeName = type . getElementName ( ) ; if ( typeName . length ( ) == ) { try { String supertypeName = type . getSuperclassName ( ) ; typeName = Messages . format ( RubyUIMessages . RubyElementLabels_anonym_type , supertypeName ) ; } catch ( RubyModelException e ) { typeName = RubyUIMessages . RubyElementLabels_anonym ; } } buf . append ( typeName ) ; if ( getFlag ( flags , T_POST_QUALIFIED ) ) { buf . append ( CONCAT_STRING ) ; IType declaringType = type . getDeclaringType ( ) ; if ( declaringType != null ) { getTypeLabel ( declaringType , T_NAME_FULLY_QUALIFIED | ( flags & QUALIFIER_FLAGS ) , buf ) ; int parentType = type . getParent ( ) . getElementType ( ) ; if ( parentType == IRubyElement . METHOD || parentType == IRubyElement . FIELD ) { buf . append ( '' ) ; getElementLabel ( type . getParent ( ) , , buf ) ; } buf . append ( CONCAT_STRING ) ; } ISourceFolder folder = type . getSourceFolder ( ) ; if ( ! folder . isDefaultPackage ( ) ) { getSourceFolderLabel ( folder , flags & QUALIFIER_FLAGS , buf ) ; buf . append ( '' ) ; } getRubyScriptLabel ( type . getRubyScript ( ) , ( flags & QUALIFIER_FLAGS ) , buf ) ; try { int offset = type . getNameRange ( ) . getOffset ( ) ; buf . append ( "" ) ; buf . append ( offset ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } } public static void getDeclarationLabel ( IRubyElement declaration , long flags , StringBuffer buf ) { if ( getFlag ( flags , D_QUALIFIED ) ) { IRubyElement openable = ( IRubyElement ) declaration . getOpenable ( ) ; if ( openable != null ) { buf . append ( getElementLabel ( openable , CF_QUALIFIED | CU_QUALIFIED | ( flags & QUALIFIER_FLAGS ) ) ) ; buf . append ( '' ) ; } } if ( declaration . getElementType ( ) == IRubyElement . IMPORT_CONTAINER ) { buf . append ( RubyUIMessages . RubyElementLabels_import_container ) ; } else { buf . append ( declaration . getElementName ( ) ) ; } if ( getFlag ( flags , D_POST_QUALIFIED ) ) { IRubyElement openable = ( IRubyElement ) declaration . getOpenable ( ) ; if ( openable != null ) { buf . append ( CONCAT_STRING ) ; buf . append ( getElementLabel ( openable , CF_QUALIFIED | CU_QUALIFIED | ( flags & QUALIFIER_FLAGS ) ) ) ; } } } public static void getRubyScriptLabel ( IRubyScript script , long flags , StringBuffer buf ) { if ( getFlag ( flags , CU_QUALIFIED ) ) { ISourceFolder pack = ( ISourceFolder ) script . getParent ( ) ; if ( ! pack . isDefaultPackage ( ) ) { getSourceFolderLabel ( pack , ( flags & QUALIFIER_FLAGS ) , buf ) ; buf . append ( '' ) ; } } buf . append ( script . getElementName ( ) ) ; if ( getFlag ( flags , CU_POST_QUALIFIED ) ) { buf . append ( CONCAT_STRING ) ; getSourceFolderLabel ( ( ISourceFolder ) script . getParent ( ) , flags & QUALIFIER_FLAGS , buf ) ; } } public static void getSourceFolderLabel ( ISourceFolder pack , long flags , StringBuffer buf ) { if ( getFlag ( flags , P_QUALIFIED ) ) { getSourceFolderRootLabel ( ( ISourceFolderRoot ) pack . getParent ( ) , ROOT_QUALIFIED , buf ) ; buf . append ( '' ) ; } refreshPackageNamePattern ( ) ; if ( pack . isDefaultPackage ( ) ) { buf . append ( DEFAULT_PACKAGE ) ; } else if ( getFlag ( flags , P_COMPRESSED ) && fgPkgNameLength >= ) { String name = pack . getElementName ( ) ; int start = ; int dot = name . indexOf ( '' , start ) ; while ( dot > ) { if ( dot - start > fgPkgNameLength - ) { buf . append ( fgPkgNamePrefix ) ; if ( fgPkgNameChars > ) buf . append ( name . substring ( start , Math . min ( start + fgPkgNameChars , dot ) ) ) ; buf . append ( fgPkgNamePostfix ) ; } else buf . append ( name . substring ( start , dot + ) ) ; start = dot + ; dot = name . indexOf ( '' , start ) ; } buf . append ( name . substring ( start ) ) ; } else { String name = pack . getElementName ( ) ; buf . append ( name . replace ( File . separatorChar , '' ) ) ; } if ( getFlag ( flags , P_POST_QUALIFIED ) ) { buf . append ( CONCAT_STRING ) ; getSourceFolderRootLabel ( ( ISourceFolderRoot ) pack . getParent ( ) , ROOT_QUALIFIED , buf ) ; } } private static void refreshPackageNamePattern ( ) { String pattern = getPkgNamePatternForPackagesView ( ) ; final String EMPTY_STRING = "" ; if ( pattern . equals ( fgPkgNamePattern ) ) return ; else if ( pattern . length ( ) == ) { fgPkgNamePattern = EMPTY_STRING ; fgPkgNameLength = - ; return ; } fgPkgNamePattern = pattern ; int i = ; fgPkgNameChars = ; fgPkgNamePrefix = EMPTY_STRING ; fgPkgNamePostfix = EMPTY_STRING ; while ( i < pattern . length ( ) ) { char ch = pattern . charAt ( i ) ; if ( Character . isDigit ( ch ) ) { fgPkgNameChars = ch - ; if ( i > ) fgPkgNamePrefix = pattern . substring ( , i ) ; if ( i >= ) fgPkgNamePostfix = pattern . substring ( i + ) ; fgPkgNameLength = fgPkgNamePrefix . length ( ) + fgPkgNameChars + fgPkgNamePostfix . length ( ) ; return ; } i ++ ; } fgPkgNamePrefix = pattern ; fgPkgNameLength = pattern . length ( ) ; } private static String getPkgNamePatternForPackagesView ( ) { IPreferenceStore store = PreferenceConstants . getPreferenceStore ( ) ; if ( ! store . getBoolean ( PreferenceConstants . APPEARANCE_COMPRESS_PACKAGE_NAMES ) ) return "" ; return store . getString ( PreferenceConstants . APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW ) ; } public static void getSourceFolderRootLabel ( ISourceFolderRoot root , long flags , StringBuffer buf ) { getFolderLabel ( root , flags , buf ) ; } private static void getFolderLabel ( ISourceFolderRoot root , long flags , StringBuffer buf ) { IResource resource = root . getResource ( ) ; boolean rootQualified = getFlag ( flags , ROOT_QUALIFIED ) ; boolean referencedQualified = getFlag ( flags , REFERENCED_ROOT_POST_QUALIFIED ) && isReferenced ( root ) ; if ( rootQualified ) { buf . append ( root . getPath ( ) . makeRelative ( ) . toString ( ) ) ; } else { if ( resource != null ) buf . append ( resource . getProjectRelativePath ( ) . toString ( ) ) ; else buf . append ( root . getElementName ( ) ) ; if ( referencedQualified ) { buf . append ( CONCAT_STRING ) ; buf . append ( resource . getProject ( ) . getName ( ) ) ; } else if ( getFlag ( flags , ROOT_POST_QUALIFIED ) ) { buf . append ( CONCAT_STRING ) ; buf . append ( root . getParent ( ) . getElementName ( ) ) ; } } } private static boolean isReferenced ( ISourceFolderRoot root ) { IResource resource = root . getResource ( ) ; if ( resource != null ) { IProject jarProject = resource . getProject ( ) ; IProject container = root . getRubyProject ( ) . getProject ( ) ; return ! container . equals ( jarProject ) ; } return false ; } } package org . rubypeople . rdt . ui ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . ViewPart ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class DeprecatedView extends ViewPart { @ Override public void createPartControl ( Composite parent ) { Composite container = new Composite ( parent , SWT . NULL ) ; container . setLayout ( new GridLayout ( ) ) ; GridData data = new GridData ( ) ; data . widthHint = ; container . setLayoutData ( data ) ; Label label = new Label ( container , SWT . NULL ) ; label . setText ( "" ) ; Button button = new Button ( container , SWT . NULL ) ; button . setText ( "" ) ; final IViewPart view = this ; button . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { try { IWorkbenchWindow dw = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; if ( dw == null ) return ; IWorkbenchPage page = dw . getActivePage ( ) ; if ( page == null ) return ; page . showView ( RubyUI . ID_RUBY_EXPLORER ) ; page . hideView ( view ) ; } catch ( PartInitException e1 ) { RubyPlugin . log ( e1 ) ; } } } ) ; } @ Override public void setFocus ( ) { } } package org . rubypeople . rdt . ui ; import org . eclipse . core . resources . IStorage ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . internal . ui . viewsupport . StorageLabelProvider ; public class RubyElementLabelProvider extends LabelProvider { public final static int SHOW_OVERLAY_ICONS = ; public final static int SHOW_ROOT = ; public final static int SHOW_SMALL_ICONS = ; public final static int SHOW_VARIABLE = ; public final static int SHOW_QUALIFIED = ; public final static int SHOW_POST_QUALIFIED = ; public final static int SHOW_BASICS = ; public final static int SHOW_DEFAULT = new Integer ( SHOW_OVERLAY_ICONS ) . intValue ( ) ; private RubyElementImageProvider fImageLabelProvider ; private StorageLabelProvider fStorageLabelProvider ; private int fFlags ; private int fImageFlags ; private long fTextFlags ; public RubyElementLabelProvider ( ) { this ( SHOW_DEFAULT ) ; } public RubyElementLabelProvider ( int flags ) { fImageLabelProvider = new RubyElementImageProvider ( ) ; fStorageLabelProvider = new StorageLabelProvider ( ) ; fFlags = flags ; updateImageProviderFlags ( ) ; updateTextProviderFlags ( ) ; } private boolean getFlag ( int flag ) { return ( fFlags & flag ) != ; } public void turnOn ( int flags ) { fFlags |= flags ; updateImageProviderFlags ( ) ; updateTextProviderFlags ( ) ; } public void turnOff ( int flags ) { fFlags &= ( ~ flags ) ; updateImageProviderFlags ( ) ; updateTextProviderFlags ( ) ; } private void updateImageProviderFlags ( ) { fImageFlags = ; if ( getFlag ( SHOW_OVERLAY_ICONS ) ) { fImageFlags |= RubyElementImageProvider . OVERLAY_ICONS ; } if ( getFlag ( SHOW_SMALL_ICONS ) ) { fImageFlags |= RubyElementImageProvider . SMALL_ICONS ; } } private void updateTextProviderFlags ( ) { fTextFlags = RubyElementLabels . M_PARAMETER_NAMES ; if ( getFlag ( SHOW_ROOT ) ) { fTextFlags |= RubyElementLabels . APPEND_ROOT_PATH ; } if ( getFlag ( SHOW_VARIABLE ) ) { fTextFlags |= RubyElementLabels . ROOT_VARIABLE ; } if ( getFlag ( SHOW_QUALIFIED ) ) { fTextFlags |= ( RubyElementLabels . F_FULLY_QUALIFIED | RubyElementLabels . M_FULLY_QUALIFIED | RubyElementLabels . I_FULLY_QUALIFIED | RubyElementLabels . T_FILENAME_QUALIFIED | RubyElementLabels . D_QUALIFIED | RubyElementLabels . CF_QUALIFIED | RubyElementLabels . CU_QUALIFIED ) ; } if ( getFlag ( SHOW_POST_QUALIFIED ) ) { fTextFlags |= ( RubyElementLabels . F_POST_QUALIFIED | RubyElementLabels . M_POST_QUALIFIED | RubyElementLabels . I_POST_QUALIFIED | RubyElementLabels . T_POST_QUALIFIED | RubyElementLabels . D_POST_QUALIFIED | RubyElementLabels . CF_POST_QUALIFIED | RubyElementLabels . CU_POST_QUALIFIED ) | RubyElementLabels . P_POST_QUALIFIED ; } } public Image getImage ( Object element ) { Image result = fImageLabelProvider . getImageLabel ( element , fImageFlags ) ; if ( result != null ) { return result ; } if ( element instanceof IStorage ) return fStorageLabelProvider . getImage ( element ) ; return result ; } public String getText ( Object element ) { String text = RubyElementLabels . getTextLabel ( element , fTextFlags ) ; if ( text . length ( ) > ) { return text ; } if ( element instanceof IStorage ) return fStorageLabelProvider . getText ( element ) ; return text ; } public void dispose ( ) { fStorageLabelProvider . dispose ( ) ; fImageLabelProvider . dispose ( ) ; } } package org . rubypeople . rdt . ui ; import org . eclipse . ui . IEditorInput ; import org . rubypeople . rdt . core . IRubyScript ; public interface IWorkingCopyManagerExtension { void setWorkingCopy ( IEditorInput input , IRubyScript workingCopy ) ; void removeWorkingCopy ( IEditorInput input ) ; } package org . rubypeople . rdt . ui ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public interface ISharedImages { public static final String IMG_OBJS_LIBRARY = RubyPluginImages . IMG_OBJS_LIBRARY ; public static final String IMG_OBJS_SOURCE_FOLDER_ROOT = RubyPluginImages . IMG_OBJS_SOURCE_FOLDER_ROOT ; public static final String IMG_OBJS_LOADPATH_VAR_ENTRY = RubyPluginImages . IMG_OBJS_ENV_VAR ; public static final String IMG_OBJS_EXTERNAL_ARCHIVE_WITH_SOURCE = RubyPluginImages . IMG_OBJS_EXTJAR_WSRC ; public static final String IMG_OBJS_CORRECTION_CHANGE = RubyPluginImages . IMG_OBJS_CORRECTION_CHANGE ; public static final String IMG_OBJS_CLASS = RubyPluginImages . IMG_OBJS_CLASS ; public static final String IMG_OBJS_SOURCE_FOLDER = RubyPluginImages . IMG_OBJS_SOURCE_FOLDER ; public static final String IMG_MISC_PUBLIC_METHOD = RubyPluginImages . IMG_MISC_PUBLIC ; Image getImage ( String key ) ; ImageDescriptor getImageDescriptor ( String key ) ; } package org . rubypeople . rdt . ui ; import org . eclipse . ui . IViewPart ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; public interface ITypeHierarchyViewPart extends IViewPart { public void setInput ( IType type ) ; public void setInputElement ( IRubyElement element ) ; public IType getInput ( ) ; public IRubyElement getInputElement ( ) ; } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchSite ; public abstract class SelectionDispatchAction extends Action implements ISelectionChangedListener { private IWorkbenchSite fSite ; private ISelectionProvider fSpecialSelectionProvider ; protected SelectionDispatchAction ( IWorkbenchSite site ) { Assert . isNotNull ( site ) ; fSite = site ; fSpecialSelectionProvider = null ; } protected SelectionDispatchAction ( IWorkbenchSite site , ISelectionProvider provider ) { this ( site ) ; setSpecialSelectionProvider ( provider ) ; } public IWorkbenchSite getSite ( ) { return fSite ; } public ISelection getSelection ( ) { if ( getSelectionProvider ( ) != null ) return getSelectionProvider ( ) . getSelection ( ) ; else return null ; } public Shell getShell ( ) { return fSite . getShell ( ) ; } public ISelectionProvider getSelectionProvider ( ) { if ( fSpecialSelectionProvider != null ) { return fSpecialSelectionProvider ; } return fSite . getSelectionProvider ( ) ; } public void setSpecialSelectionProvider ( ISelectionProvider provider ) { fSpecialSelectionProvider = provider ; } public void update ( ISelection selection ) { dispatchSelectionChanged ( selection ) ; } public void selectionChanged ( IStructuredSelection selection ) { selectionChanged ( ( ISelection ) selection ) ; } public void run ( IStructuredSelection selection ) { run ( ( ISelection ) selection ) ; } public void selectionChanged ( ITextSelection selection ) { selectionChanged ( ( ISelection ) selection ) ; } public void run ( ITextSelection selection ) { run ( ( ISelection ) selection ) ; } public void selectionChanged ( ISelection selection ) { setEnabled ( false ) ; } public void run ( ISelection selection ) { } public void run ( ) { dispatchRun ( getSelection ( ) ) ; } public void selectionChanged ( SelectionChangedEvent event ) { dispatchSelectionChanged ( event . getSelection ( ) ) ; } private void dispatchSelectionChanged ( ISelection selection ) { if ( selection instanceof IStructuredSelection ) { selectionChanged ( ( IStructuredSelection ) selection ) ; } else if ( selection instanceof ITextSelection ) { selectionChanged ( ( ITextSelection ) selection ) ; } else { selectionChanged ( selection ) ; } } private void dispatchRun ( ISelection selection ) { if ( selection instanceof IStructuredSelection ) { run ( ( IStructuredSelection ) selection ) ; } else if ( selection instanceof ITextSelection ) { run ( ( ITextSelection ) selection ) ; } else { run ( selection ) ; } } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . action . IStatusLineManager ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorSite ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . IPageSite ; import org . eclipse . ui . part . Page ; import org . eclipse . ui . texteditor . IEditorStatusLine ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . ActionUtil ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptEditorInput ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . OccurrencesFinder ; import org . rubypeople . rdt . internal . ui . search . FindOccurrencesEngine ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; public class FindOccurrencesInFileAction extends SelectionDispatchAction { private RubyEditor fEditor ; private IActionBars fActionBars ; public FindOccurrencesInFileAction ( IViewPart part ) { this ( part . getSite ( ) ) ; } public FindOccurrencesInFileAction ( Page page ) { this ( page . getSite ( ) ) ; } public FindOccurrencesInFileAction ( RubyEditor editor ) { this ( editor . getEditorSite ( ) ) ; fEditor = editor ; setEnabled ( getEditorInput ( editor ) != null ) ; } public FindOccurrencesInFileAction ( IWorkbenchSite site ) { super ( site ) ; if ( site instanceof IViewSite ) fActionBars = ( ( IViewSite ) site ) . getActionBars ( ) ; else if ( site instanceof IEditorSite ) fActionBars = ( ( IEditorSite ) site ) . getActionBars ( ) ; else if ( site instanceof IPageSite ) fActionBars = ( ( IPageSite ) site ) . getActionBars ( ) ; setText ( SearchMessages . Search_FindOccurrencesInFile_label ) ; setToolTipText ( SearchMessages . Search_FindOccurrencesInFile_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_OCCURRENCES_IN_FILE_ACTION ) ; } public void selectionChanged ( IStructuredSelection selection ) { setEnabled ( getMember ( selection ) != null ) ; } private IMember getMember ( IStructuredSelection selection ) { if ( selection . size ( ) != ) return null ; Object o = selection . getFirstElement ( ) ; if ( o instanceof IMember ) { IMember member = ( IMember ) o ; try { if ( member . getNameRange ( ) == null ) return null ; } catch ( RubyModelException ex ) { return null ; } return member ; } return null ; } public void run ( IStructuredSelection selection ) { IMember member = getMember ( selection ) ; if ( ! ActionUtil . isProcessable ( getShell ( ) , member ) ) return ; FindOccurrencesEngine engine = FindOccurrencesEngine . create ( member , new OccurrencesFinder ( ) ) ; try { ISourceRange range = member . getNameRange ( ) ; String result = engine . run ( range . getOffset ( ) , range . getLength ( ) ) ; if ( result != null ) showMessage ( getShell ( ) , fActionBars , result ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } private static void showMessage ( Shell shell , IActionBars actionBars , String msg ) { if ( actionBars != null ) { IStatusLineManager statusLine = actionBars . getStatusLineManager ( ) ; if ( statusLine != null ) statusLine . setMessage ( msg ) ; } shell . getDisplay ( ) . beep ( ) ; } public void selectionChanged ( ITextSelection selection ) { } public final void run ( ITextSelection ts ) { IRubyElement input = getEditorInput ( fEditor ) ; if ( ! ActionUtil . isProcessable ( getShell ( ) , input ) ) return ; FindOccurrencesEngine engine = FindOccurrencesEngine . create ( input , new OccurrencesFinder ( ) ) ; try { String result = engine . run ( ts . getOffset ( ) , ts . getLength ( ) ) ; if ( result != null ) showMessage ( getShell ( ) , fEditor , result ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } } private static IRubyElement getEditorInput ( RubyEditor editor ) { IEditorInput input = editor . getEditorInput ( ) ; if ( input instanceof IRubyScriptEditorInput ) return ( ( IRubyScriptEditorInput ) input ) . getRubyScript ( ) ; return RubyPlugin . getDefault ( ) . getWorkingCopyManager ( ) . getWorkingCopy ( input ) ; } private static void showMessage ( Shell shell , RubyEditor editor , String msg ) { IEditorStatusLine statusLine = ( IEditorStatusLine ) editor . getAdapter ( IEditorStatusLine . class ) ; if ( statusLine != null ) statusLine . setMessage ( true , msg , null ) ; shell . getDisplay ( ) . beep ( ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . RubyUIMessages ; import org . rubypeople . rdt . internal . ui . dialogs . OpenTypeSelectionDialog2 ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public class OpenTypeAction extends Action implements IWorkbenchWindowActionDelegate { public OpenTypeAction ( ) { super ( ) ; setText ( RubyUIMessages . OpenTypeAction_label ) ; setDescription ( RubyUIMessages . OpenTypeAction_description ) ; setToolTipText ( RubyUIMessages . OpenTypeAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_TOOL_OPENTYPE ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . OPEN_TYPE_ACTION ) ; } public void run ( ) { Shell parent = RubyPlugin . getActiveWorkbenchShell ( ) ; OpenTypeSelectionDialog2 dialog = new OpenTypeSelectionDialog2 ( parent , false , PlatformUI . getWorkbench ( ) . getProgressService ( ) , null , IRubySearchConstants . TYPE ) ; dialog . setTitle ( RubyUIMessages . OpenTypeAction_dialogTitle ) ; dialog . setMessage ( RubyUIMessages . OpenTypeAction_dialogMessage ) ; int result = dialog . open ( ) ; if ( result != IDialogConstants . OK_ID ) return ; Object [ ] types = dialog . getResult ( ) ; if ( types != null && types . length > ) { IType type = ( IType ) types [ ] ; try { IEditorPart part = EditorUtility . openInEditor ( type , true ) ; EditorUtility . revealInEditor ( part , type ) ; } catch ( CoreException x ) { String title = RubyUIMessages . OpenTypeAction_errorTitle ; String message = RubyUIMessages . OpenTypeAction_errorMessage ; ExceptionHandler . handle ( x , title , message ) ; } } } public void run ( IAction action ) { run ( ) ; } public void dispose ( ) { } public void init ( IWorkbenchWindow window ) { } public void selectionChanged ( IAction action , ISelection selection ) { } } package org . rubypeople . rdt . ui . actions ; import java . util . ArrayList ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . viewsupport . MemberFilter ; import org . rubypeople . rdt . internal . ui . viewsupport . MemberFilterAction ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class MemberFilterActionGroup extends ActionGroup { public static final int FILTER_NONPUBLIC = MemberFilter . FILTER_NONPUBLIC ; public static final int FILTER_STATIC = MemberFilter . FILTER_STATIC ; public static final int FILTER_FIELDS = MemberFilter . FILTER_FIELDS ; public static final int FILTER_LOCALTYPES = MemberFilter . FILTER_LOCALTYPES ; public static final int ALL_FILTERS = FILTER_NONPUBLIC | FILTER_FIELDS | FILTER_STATIC | FILTER_LOCALTYPES ; private static final String TAG_HIDEFIELDS = "" ; private static final String TAG_HIDESTATIC = "" ; private static final String TAG_HIDENONPUBLIC = "" ; private static final String TAG_HIDELOCALTYPES = "" ; private MemberFilterAction [ ] fFilterActions ; private MemberFilter fFilter ; private StructuredViewer fViewer ; private String fViewerId ; private boolean fInViewMenu ; public MemberFilterActionGroup ( StructuredViewer viewer , String viewerId ) { this ( viewer , viewerId , false ) ; } public MemberFilterActionGroup ( StructuredViewer viewer , String viewerId , boolean inViewMenu ) { this ( viewer , viewerId , inViewMenu , ALL_FILTERS ) ; } public MemberFilterActionGroup ( StructuredViewer viewer , String viewerId , boolean inViewMenu , int availableFilters ) { fViewer = viewer ; fViewerId = viewerId ; fInViewMenu = inViewMenu ; IPreferenceStore store = PreferenceConstants . getPreferenceStore ( ) ; fFilter = new MemberFilter ( ) ; String title , helpContext ; ArrayList actions = new ArrayList ( ) ; int filterProperty = FILTER_FIELDS ; if ( isSet ( filterProperty , availableFilters ) ) { boolean filterEnabled = store . getBoolean ( getPreferenceKey ( filterProperty ) ) ; if ( filterEnabled ) { fFilter . addFilter ( filterProperty ) ; } title = ActionMessages . MemberFilterActionGroup_hide_fields_label ; helpContext = IRubyHelpContextIds . FILTER_FIELDS_ACTION ; MemberFilterAction hideFields = new MemberFilterAction ( this , title , filterProperty , helpContext , filterEnabled ) ; hideFields . setDescription ( ActionMessages . MemberFilterActionGroup_hide_fields_description ) ; hideFields . setToolTipText ( ActionMessages . MemberFilterActionGroup_hide_fields_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( hideFields , "" ) ; actions . add ( hideFields ) ; } filterProperty = FILTER_STATIC ; if ( isSet ( filterProperty , availableFilters ) ) { boolean filterEnabled = store . getBoolean ( getPreferenceKey ( filterProperty ) ) ; if ( filterEnabled ) { fFilter . addFilter ( filterProperty ) ; } title = ActionMessages . MemberFilterActionGroup_hide_static_label ; helpContext = IRubyHelpContextIds . FILTER_STATIC_ACTION ; MemberFilterAction hideStatic = new MemberFilterAction ( this , title , FILTER_STATIC , helpContext , filterEnabled ) ; hideStatic . setDescription ( ActionMessages . MemberFilterActionGroup_hide_static_description ) ; hideStatic . setToolTipText ( ActionMessages . MemberFilterActionGroup_hide_static_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( hideStatic , "" ) ; actions . add ( hideStatic ) ; } filterProperty = FILTER_NONPUBLIC ; if ( isSet ( filterProperty , availableFilters ) ) { boolean filterEnabled = store . getBoolean ( getPreferenceKey ( filterProperty ) ) ; if ( filterEnabled ) { fFilter . addFilter ( filterProperty ) ; } title = ActionMessages . MemberFilterActionGroup_hide_nonpublic_label ; helpContext = IRubyHelpContextIds . FILTER_PUBLIC_ACTION ; MemberFilterAction hideNonPublic = new MemberFilterAction ( this , title , filterProperty , helpContext , filterEnabled ) ; hideNonPublic . setDescription ( ActionMessages . MemberFilterActionGroup_hide_nonpublic_description ) ; hideNonPublic . setToolTipText ( ActionMessages . MemberFilterActionGroup_hide_nonpublic_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( hideNonPublic , "" ) ; actions . add ( hideNonPublic ) ; } filterProperty = FILTER_LOCALTYPES ; if ( isSet ( filterProperty , availableFilters ) ) { boolean filterEnabled = store . getBoolean ( getPreferenceKey ( filterProperty ) ) ; if ( filterEnabled ) { fFilter . addFilter ( filterProperty ) ; } title = ActionMessages . MemberFilterActionGroup_hide_localtypes_label ; helpContext = IRubyHelpContextIds . FILTER_LOCALTYPES_ACTION ; MemberFilterAction hideLocalTypes = new MemberFilterAction ( this , title , filterProperty , helpContext , filterEnabled ) ; hideLocalTypes . setDescription ( ActionMessages . MemberFilterActionGroup_hide_localtypes_description ) ; hideLocalTypes . setToolTipText ( ActionMessages . MemberFilterActionGroup_hide_localtypes_tooltip ) ; RubyPluginImages . setLocalImageDescriptors ( hideLocalTypes , "" ) ; actions . add ( hideLocalTypes ) ; } fFilterActions = ( MemberFilterAction [ ] ) actions . toArray ( new MemberFilterAction [ actions . size ( ) ] ) ; fViewer . addFilter ( fFilter ) ; } private String getPreferenceKey ( int filterProperty ) { return "" + fViewerId + '' + String . valueOf ( filterProperty ) ; } public void setMemberFilter ( int filterProperty , boolean set ) { setMemberFilters ( new int [ ] { filterProperty } , new boolean [ ] { set } , true ) ; } private void setMemberFilters ( int [ ] propertyKeys , boolean [ ] propertyValues , boolean refresh ) { if ( propertyKeys . length == ) return ; Assert . isTrue ( propertyKeys . length == propertyValues . length ) ; for ( int i = ; i < propertyKeys . length ; i ++ ) { int filterProperty = propertyKeys [ i ] ; boolean set = propertyValues [ i ] ; IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; boolean found = false ; for ( int j = ; j < fFilterActions . length ; j ++ ) { int currProperty = fFilterActions [ j ] . getFilterProperty ( ) ; if ( currProperty == filterProperty ) { fFilterActions [ j ] . setChecked ( set ) ; found = true ; store . setValue ( getPreferenceKey ( filterProperty ) , set ) ; } } if ( found ) { if ( set ) { fFilter . addFilter ( filterProperty ) ; } else { fFilter . removeFilter ( filterProperty ) ; } } } if ( refresh ) { fViewer . getControl ( ) . setRedraw ( false ) ; BusyIndicator . showWhile ( fViewer . getControl ( ) . getDisplay ( ) , new Runnable ( ) { public void run ( ) { fViewer . refresh ( ) ; } } ) ; fViewer . getControl ( ) . setRedraw ( true ) ; } } private boolean isSet ( int flag , int set ) { return ( flag & set ) != ; } public boolean hasMemberFilter ( int filterProperty ) { return fFilter . hasFilter ( filterProperty ) ; } public void saveState ( IMemento memento ) { memento . putString ( TAG_HIDEFIELDS , String . valueOf ( hasMemberFilter ( FILTER_FIELDS ) ) ) ; memento . putString ( TAG_HIDESTATIC , String . valueOf ( hasMemberFilter ( FILTER_STATIC ) ) ) ; memento . putString ( TAG_HIDENONPUBLIC , String . valueOf ( hasMemberFilter ( FILTER_NONPUBLIC ) ) ) ; memento . putString ( TAG_HIDELOCALTYPES , String . valueOf ( hasMemberFilter ( FILTER_LOCALTYPES ) ) ) ; } public void restoreState ( IMemento memento ) { setMemberFilters ( new int [ ] { FILTER_FIELDS , FILTER_STATIC , FILTER_NONPUBLIC , FILTER_LOCALTYPES } , new boolean [ ] { Boolean . valueOf ( memento . getString ( TAG_HIDEFIELDS ) ) . booleanValue ( ) , Boolean . valueOf ( memento . getString ( TAG_HIDESTATIC ) ) . booleanValue ( ) , Boolean . valueOf ( memento . getString ( TAG_HIDENONPUBLIC ) ) . booleanValue ( ) , Boolean . valueOf ( memento . getString ( TAG_HIDELOCALTYPES ) ) . booleanValue ( ) } , false ) ; } public void fillActionBars ( IActionBars actionBars ) { contributeToToolBar ( actionBars . getToolBarManager ( ) ) ; } public void contributeToToolBar ( IToolBarManager tbm ) { if ( fInViewMenu ) return ; for ( int i = ; i < fFilterActions . length ; i ++ ) { tbm . add ( fFilterActions [ i ] ) ; } } public void contributeToViewMenu ( IMenuManager menu ) { if ( ! fInViewMenu ) return ; final String filters = "" ; if ( menu . find ( filters ) != null ) { for ( int i = ; i < fFilterActions . length ; i ++ ) { menu . prependToGroup ( filters , fFilterActions [ i ] ) ; } } else { for ( int i = ; i < fFilterActions . length ; i ++ ) { menu . add ( fFilterActions [ i ] ) ; } } } public void dispose ( ) { super . dispose ( ) ; } } package org . rubypeople . rdt . ui . actions ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . IRubyStatusConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . actions . ActionUtil ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . callhierarchy . CallHierarchyMessages ; import org . rubypeople . rdt . internal . ui . callhierarchy . CallHierarchyUI ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public class OpenCallHierarchyAction extends SelectionDispatchAction { private RubyEditor fEditor ; public OpenCallHierarchyAction ( IWorkbenchSite site ) { super ( site ) ; setText ( CallHierarchyMessages . OpenCallHierarchyAction_label ) ; setToolTipText ( CallHierarchyMessages . OpenCallHierarchyAction_tooltip ) ; setDescription ( CallHierarchyMessages . OpenCallHierarchyAction_description ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . CALL_HIERARCHY_OPEN_ACTION ) ; } public OpenCallHierarchyAction ( IWorkbenchSite site , ISelectionProvider provider ) { this ( site ) ; setSpecialSelectionProvider ( provider ) ; } public OpenCallHierarchyAction ( RubyEditor editor ) { this ( editor . getEditorSite ( ) ) ; fEditor = editor ; setEnabled ( SelectionConverter . canOperateOn ( fEditor ) ) ; } public void selectionChanged ( ITextSelection selection ) { } public void selectionChanged ( IStructuredSelection selection ) { setEnabled ( isEnabled ( selection ) ) ; } private boolean isEnabled ( IStructuredSelection selection ) { if ( selection . size ( ) != ) return false ; Object input = selection . getFirstElement ( ) ; if ( ! ( input instanceof IRubyElement ) ) return false ; switch ( ( ( IRubyElement ) input ) . getElementType ( ) ) { case IRubyElement . METHOD : return true ; default : return false ; } } public void run ( ITextSelection selection ) { IRubyElement input = SelectionConverter . getInput ( fEditor ) ; if ( ! ActionUtil . isProcessable ( getShell ( ) , input ) ) return ; try { IRubyElement [ ] elements = SelectionConverter . codeResolveOrInputForked ( fEditor ) ; if ( elements == null ) return ; List candidates = new ArrayList ( elements . length ) ; for ( int i = ; i < elements . length ; i ++ ) { IRubyElement [ ] resolvedElements = CallHierarchyUI . getCandidates ( elements [ i ] ) ; if ( resolvedElements != null ) candidates . addAll ( Arrays . asList ( resolvedElements ) ) ; } if ( candidates . isEmpty ( ) ) { IRubyElement enclosingMethod = getEnclosingMethod ( input , selection ) ; if ( enclosingMethod != null ) { candidates . add ( enclosingMethod ) ; } } run ( ( IRubyElement [ ] ) candidates . toArray ( new IRubyElement [ candidates . size ( ) ] ) ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , getShell ( ) , getErrorDialogTitle ( ) , ActionMessages . SelectionConverter_codeResolve_failed ) ; } catch ( InterruptedException e ) { } } private IRubyElement getEnclosingMethod ( IRubyElement input , ITextSelection selection ) { IRubyElement enclosingElement = null ; try { switch ( input . getElementType ( ) ) { case IRubyElement . SCRIPT : IRubyScript cu = ( IRubyScript ) input . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) { enclosingElement = cu . getElementAt ( selection . getOffset ( ) ) ; } break ; } if ( enclosingElement != null && enclosingElement . getElementType ( ) == IRubyElement . METHOD ) { return enclosingElement ; } } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return null ; } public void run ( IStructuredSelection selection ) { if ( selection . size ( ) != ) return ; Object input = selection . getFirstElement ( ) ; if ( ! ( input instanceof IRubyElement ) ) { IStatus status = createStatus ( CallHierarchyMessages . OpenCallHierarchyAction_messages_no_java_element ) ; openErrorDialog ( status ) ; return ; } IRubyElement element = ( IRubyElement ) input ; if ( ! ActionUtil . isProcessable ( getShell ( ) , element ) ) return ; List result = new ArrayList ( ) ; IStatus status = compileCandidates ( result , element ) ; if ( status . isOK ( ) ) { run ( ( IRubyElement [ ] ) result . toArray ( new IRubyElement [ result . size ( ) ] ) ) ; } else { openErrorDialog ( status ) ; } } private int openErrorDialog ( IStatus status ) { String message = CallHierarchyMessages . OpenCallHierarchyAction_messages_title ; String dialogTitle = getErrorDialogTitle ( ) ; return ErrorDialog . openError ( getShell ( ) , dialogTitle , message , status ) ; } private static String getErrorDialogTitle ( ) { return CallHierarchyMessages . OpenCallHierarchyAction_dialog_title ; } public void run ( IRubyElement [ ] elements ) { if ( elements . length == ) { getShell ( ) . getDisplay ( ) . beep ( ) ; return ; } CallHierarchyUI . open ( elements , getSite ( ) . getWorkbenchWindow ( ) ) ; } private static IStatus compileCandidates ( List result , IRubyElement elem ) { IStatus ok = new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , , "" , null ) ; switch ( elem . getElementType ( ) ) { case IRubyElement . METHOD : result . add ( elem ) ; return ok ; } return createStatus ( CallHierarchyMessages . OpenCallHierarchyAction_messages_no_valid_java_element ) ; } private static IStatus createStatus ( String message ) { return new Status ( IStatus . INFO , RubyPlugin . getPluginId ( ) , IRubyStatusConstants . INTERNAL_ERROR , message , null ) ; } } package org . rubypeople . rdt . ui . actions ; import java . util . ResourceBundle ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . texteditor . ITextEditor ; import org . eclipse . ui . texteditor . TextEditorAction ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; public class FormatAction extends TextEditorAction { public FormatAction ( ResourceBundle bundle , String prefix , ITextEditor editor ) { super ( bundle , prefix , editor ) ; } public void run ( ) { IDocument doc = this . getTextEditor ( ) . getDocumentProvider ( ) . getDocument ( this . getTextEditor ( ) . getEditorInput ( ) ) ; try { ISelection selection = this . getTextEditor ( ) . getSelectionProvider ( ) . getSelection ( ) ; if ( selection instanceof TextSelection ) { TextSelection textSelection = ( TextSelection ) selection ; String text = textSelection . getText ( ) ; if ( text == null || text . length ( ) == ) { String original = doc . get ( ) ; String allFormatted = RubyPlugin . getDefault ( ) . getCodeFormatter ( ) . formatString ( original ) ; if ( original . equals ( allFormatted ) ) return ; RubyEditor rubyEditor = ( RubyEditor ) this . getTextEditor ( ) ; RubyEditor . CaretPosition cursorPos = rubyEditor . getCaretPosition ( ) ; doc . set ( allFormatted ) ; rubyEditor . setCaretPosition ( cursorPos ) ; } else { int startPos = doc . getLineOffset ( textSelection . getStartLine ( ) ) ; int endLine = textSelection . getEndLine ( ) ; int endPos = doc . getLineOffset ( endLine ) + doc . getLineLength ( endLine ) ; String unformatted = doc . get ( startPos , endPos - startPos ) ; String formatted = RubyPlugin . getDefault ( ) . getCodeFormatter ( ) . formatString ( unformatted ) ; if ( ! formatted . equals ( unformatted ) ) { doc . replace ( startPos , endPos - startPos , formatted ) ; } } } } catch ( BadLocationException e ) { RubyPlugin . log ( e ) ; } super . run ( ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class FindReferencesAction extends FindAction { public FindReferencesAction ( IWorkbenchSite site ) { super ( site ) ; } public FindReferencesAction ( RubyEditor editor ) { super ( editor ) ; } Class [ ] getValidTypes ( ) { return new Class [ ] { IRubyScript . class , IType . class , IMethod . class , IField . class , IImportDeclaration . class , ISourceFolder . class } ; } void init ( ) { setText ( SearchMessages . Search_FindReferencesAction_label ) ; setToolTipText ( SearchMessages . Search_FindReferencesAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_REFERENCES_IN_WORKSPACE_ACTION ) ; } int getLimitTo ( ) { return IRubySearchConstants . REFERENCES ; } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; boolean isInsideJRE = factory . isInsideRubyVMLibraries ( element ) ; IRubySearchScope scope = factory . createWorkspaceScope ( isInsideJRE ) ; String description = factory . getWorkspaceScopeDescription ( isInsideJRE ) ; return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . action . GroupMarker ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . part . Page ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . ui . PreferenceConstants ; public class RubySearchActionGroup extends ActionGroup { private RubyEditor fEditor ; private ReferencesSearchGroup fReferencesGroup ; private ReadReferencesSearchGroup fReadAccessGroup ; private WriteReferencesSearchGroup fWriteAccessGroup ; private DeclarationsSearchGroup fDeclarationsGroup ; private OccurrencesSearchGroup fOccurrencesGroup ; public RubySearchActionGroup ( IViewPart part ) { this ( part . getViewSite ( ) ) ; } public RubySearchActionGroup ( Page page ) { this ( page . getSite ( ) ) ; } public RubySearchActionGroup ( RubyEditor editor ) { Assert . isNotNull ( editor ) ; fEditor = editor ; fReferencesGroup = new ReferencesSearchGroup ( fEditor ) ; fReadAccessGroup = new ReadReferencesSearchGroup ( fEditor ) ; fWriteAccessGroup = new WriteReferencesSearchGroup ( fEditor ) ; fDeclarationsGroup = new DeclarationsSearchGroup ( fEditor ) ; fOccurrencesGroup = new OccurrencesSearchGroup ( fEditor ) ; } private RubySearchActionGroup ( IWorkbenchSite site ) { fReferencesGroup = new ReferencesSearchGroup ( site ) ; fReadAccessGroup = new ReadReferencesSearchGroup ( site ) ; fWriteAccessGroup = new WriteReferencesSearchGroup ( site ) ; fDeclarationsGroup = new DeclarationsSearchGroup ( site ) ; fOccurrencesGroup = new OccurrencesSearchGroup ( site ) ; } public void setContext ( ActionContext context ) { fReferencesGroup . setContext ( context ) ; fDeclarationsGroup . setContext ( context ) ; fReadAccessGroup . setContext ( context ) ; fWriteAccessGroup . setContext ( context ) ; fOccurrencesGroup . setContext ( context ) ; } public void fillActionBars ( IActionBars actionBar ) { super . fillActionBars ( actionBar ) ; fReferencesGroup . fillActionBars ( actionBar ) ; fDeclarationsGroup . fillActionBars ( actionBar ) ; fReadAccessGroup . fillActionBars ( actionBar ) ; fWriteAccessGroup . fillActionBars ( actionBar ) ; fOccurrencesGroup . fillActionBars ( actionBar ) ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; if ( PreferenceConstants . getPreferenceStore ( ) . getBoolean ( PreferenceConstants . SEARCH_USE_REDUCED_MENU ) ) { fReferencesGroup . fillContextMenu ( menu ) ; fDeclarationsGroup . fillContextMenu ( menu ) ; if ( fEditor == null ) { fReadAccessGroup . fillContextMenu ( menu ) ; fWriteAccessGroup . fillContextMenu ( menu ) ; } } else { IMenuManager target = menu ; IMenuManager searchSubMenu = null ; if ( fEditor != null ) { String groupName = SearchMessages . group_search ; searchSubMenu = new MenuManager ( groupName , ITextEditorActionConstants . GROUP_FIND ) ; searchSubMenu . add ( new GroupMarker ( ITextEditorActionConstants . GROUP_FIND ) ) ; target = searchSubMenu ; } fReferencesGroup . fillContextMenu ( target ) ; fDeclarationsGroup . fillContextMenu ( target ) ; fReadAccessGroup . fillContextMenu ( target ) ; fWriteAccessGroup . fillContextMenu ( target ) ; if ( searchSubMenu != null ) { fOccurrencesGroup . fillContextMenu ( target ) ; searchSubMenu . add ( new Separator ( ) ) ; } if ( searchSubMenu != null && searchSubMenu . getItems ( ) . length > ) { menu . appendToGroup ( ITextEditorActionConstants . GROUP_FIND , searchSubMenu ) ; } } } public void dispose ( ) { fReferencesGroup . dispose ( ) ; fDeclarationsGroup . dispose ( ) ; fReadAccessGroup . dispose ( ) ; fWriteAccessGroup . dispose ( ) ; fOccurrencesGroup . dispose ( ) ; super . dispose ( ) ; } } package org . rubypeople . rdt . ui . actions ; import java . lang . reflect . InvocationTargetException ; import java . net . URI ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . corext . util . Resources ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . actions . WorkbenchRunnableAdapter ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public class RefreshAction extends SelectionDispatchAction { public RefreshAction ( IWorkbenchSite site ) { super ( site ) ; setText ( ActionMessages . RefreshAction_label ) ; setToolTipText ( ActionMessages . RefreshAction_toolTip ) ; RubyPluginImages . setLocalImageDescriptors ( this , "" ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . REFRESH_ACTION ) ; } public void selectionChanged ( IStructuredSelection selection ) { setEnabled ( checkEnabled ( selection ) ) ; } private boolean checkEnabled ( IStructuredSelection selection ) { if ( selection . isEmpty ( ) ) return true ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof IWorkingSet ) { } else if ( element instanceof IAdaptable ) { IResource resource = ( IResource ) ( ( IAdaptable ) element ) . getAdapter ( IResource . class ) ; if ( resource == null ) return false ; if ( resource . getType ( ) == IResource . PROJECT && ! ( ( IProject ) resource ) . isOpen ( ) ) return false ; } else { return false ; } } return true ; } public void run ( IStructuredSelection selection ) { final IResource [ ] resources = getResources ( selection ) ; IWorkspaceRunnable operation = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { monitor . beginTask ( ActionMessages . RefreshAction_progressMessage , resources . length * ) ; monitor . subTask ( "" ) ; List javaElements = new ArrayList ( ) ; for ( int r = ; r < resources . length ; r ++ ) { IResource resource = resources [ r ] ; if ( resource . getType ( ) == IResource . PROJECT ) { checkLocationDeleted ( ( IProject ) resource ) ; } else if ( resource . getType ( ) == IResource . ROOT ) { IProject [ ] projects = ( ( IWorkspaceRoot ) resource ) . getProjects ( ) ; for ( int p = ; p < projects . length ; p ++ ) { checkLocationDeleted ( projects [ p ] ) ; } } resource . refreshLocal ( IResource . DEPTH_INFINITE , new SubProgressMonitor ( monitor , ) ) ; IRubyElement jElement = RubyCore . create ( resource ) ; if ( jElement != null && jElement . exists ( ) ) javaElements . add ( jElement ) ; } IRubyModel model = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; model . refreshExternalArchives ( ( IRubyElement [ ] ) javaElements . toArray ( new IRubyElement [ javaElements . size ( ) ] ) , new SubProgressMonitor ( monitor , resources . length ) ) ; } } ; try { PlatformUI . getWorkbench ( ) . getProgressService ( ) . run ( true , true , new WorkbenchRunnableAdapter ( operation ) ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , getShell ( ) , ActionMessages . RefreshAction_error_title , ActionMessages . RefreshAction_error_message ) ; } catch ( InterruptedException e ) { } } private IResource [ ] getResources ( IStructuredSelection selection ) { if ( selection . isEmpty ( ) ) { return new IResource [ ] { ResourcesPlugin . getWorkspace ( ) . getRoot ( ) } ; } List result = new ArrayList ( selection . size ( ) ) ; getResources ( result , selection . toArray ( ) ) ; for ( Iterator iter = result . iterator ( ) ; iter . hasNext ( ) ; ) { IResource resource = ( IResource ) iter . next ( ) ; if ( isDescendent ( result , resource ) ) iter . remove ( ) ; } return ( IResource [ ] ) result . toArray ( new IResource [ result . size ( ) ] ) ; } private void getResources ( List result , Object [ ] elements ) { for ( int i = ; i < elements . length ; i ++ ) { Object element = elements [ i ] ; if ( element instanceof IWorkingSet ) { getResources ( result , ( ( IWorkingSet ) element ) . getElements ( ) ) ; } else if ( element instanceof IAdaptable ) { IResource resource = ( IResource ) ( ( IAdaptable ) element ) . getAdapter ( IResource . class ) ; if ( resource == null ) continue ; if ( resource . getType ( ) != IResource . PROJECT || ( resource . getType ( ) == IResource . PROJECT && ( ( IProject ) resource ) . isOpen ( ) ) ) { result . add ( resource ) ; } } } } private boolean isDescendent ( List candidates , IResource element ) { IResource parent = element . getParent ( ) ; while ( parent != null ) { if ( candidates . contains ( parent ) ) return true ; parent = parent . getParent ( ) ; } return false ; } private void checkLocationDeleted ( IProject project ) throws CoreException { if ( ! project . exists ( ) ) return ; URI location = project . getLocationURI ( ) ; if ( location == null ) return ; IFileStore store = EFS . getStore ( location ) ; if ( ! store . fetchInfo ( ) . exists ( ) ) { final String message = Messages . format ( ActionMessages . RefreshAction_locationDeleted_message , new Object [ ] { project . getName ( ) , Resources . getLocationString ( project ) } ) ; final boolean [ ] result = new boolean [ ] ; getShell ( ) . getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { result [ ] = MessageDialog . openQuestion ( getShell ( ) , ActionMessages . RefreshAction_locationDeleted_title , message ) ; } } ) ; if ( result [ ] ) { project . delete ( true , true , null ) ; } } } } package org . rubypeople . rdt . ui . actions ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . SortedSet ; import java . util . Stack ; import java . util . StringTokenizer ; import java . util . TreeSet ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . ContributionItem ; import org . eclipse . jface . action . GroupMarker ; import org . eclipse . jface . action . IContributionItem ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . IContentProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . actions . ActionGroup ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . filters . CustomFiltersDialog ; import org . rubypeople . rdt . internal . ui . filters . FilterDescriptor ; import org . rubypeople . rdt . internal . ui . filters . FilterMessages ; import org . rubypeople . rdt . internal . ui . filters . NamePatternFilter ; public class CustomFiltersActionGroup extends ActionGroup { class ShowFilterDialogAction extends Action { ShowFilterDialogAction ( ) { setText ( FilterMessages . OpenCustomFiltersDialogAction_text ) ; setImageDescriptor ( RubyPluginImages . DESC_ELCL_FILTER ) ; setDisabledImageDescriptor ( RubyPluginImages . DESC_DLCL_FILTER ) ; } public void run ( ) { openDialog ( ) ; } } class FilterActionMenuContributionItem extends ContributionItem { private int fItemNumber ; private boolean fState ; private String fFilterId ; private String fFilterName ; private CustomFiltersActionGroup fActionGroup ; public FilterActionMenuContributionItem ( CustomFiltersActionGroup actionGroup , String filterId , String filterName , boolean state , int itemNumber ) { super ( filterId ) ; Assert . isNotNull ( actionGroup ) ; Assert . isNotNull ( filterId ) ; Assert . isNotNull ( filterName ) ; fActionGroup = actionGroup ; fFilterId = filterId ; fFilterName = filterName ; fState = state ; fItemNumber = itemNumber ; } public void fill ( Menu menu , int index ) { MenuItem mi = new MenuItem ( menu , SWT . CHECK , index ) ; mi . setText ( "" + fItemNumber + "" + fFilterName ) ; mi . setSelection ( fState ) ; mi . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fState = ! fState ; fActionGroup . setFilter ( fFilterId , fState ) ; } } ) ; } public boolean isDynamic ( ) { return true ; } } private static final String TAG_CUSTOM_FILTERS = "" ; private static final String TAG_USER_DEFINED_PATTERNS_ENABLED = "" ; private static final String TAG_USER_DEFINED_PATTERNS = "" ; private static final String TAG_XML_DEFINED_FILTERS = "" ; private static final String TAG_LRU_FILTERS = "" ; private static final String TAG_CHILD = "" ; private static final String TAG_PATTERN = "" ; private static final String TAG_FILTER_ID = "" ; private static final String TAG_IS_ENABLED = "" ; private static final String SEPARATOR = "" ; private static final int MAX_FILTER_MENU_ENTRIES = ; private static final String RECENT_FILTERS_GROUP_NAME = "" ; private StructuredViewer fViewer ; private NamePatternFilter fPatternFilter ; private Map fInstalledBuiltInFilters ; private Map fEnabledFilterIds ; private boolean fUserDefinedPatternsEnabled ; private String [ ] fUserDefinedPatterns ; private FilterDescriptor [ ] fCachedFilterDescriptors ; private Stack fLRUFilterIdsStack ; private IMenuManager fMenuManager ; private IMenuListener fMenuListener ; private String [ ] fFilterIdsUsedInLastViewMenu ; private HashMap fFilterDescriptorMap ; private String fTargetId ; public CustomFiltersActionGroup ( IViewPart part , StructuredViewer viewer ) { this ( part . getViewSite ( ) . getId ( ) , viewer ) ; } public CustomFiltersActionGroup ( String ownerId , StructuredViewer viewer ) { Assert . isNotNull ( ownerId ) ; Assert . isNotNull ( viewer ) ; fTargetId = ownerId ; fViewer = viewer ; fLRUFilterIdsStack = new Stack ( ) ; initializeWithPluginContributions ( ) ; initializeWithViewDefaults ( ) ; installFilters ( ) ; } public void fillActionBars ( IActionBars actionBars ) { fillToolBar ( actionBars . getToolBarManager ( ) ) ; fillViewMenu ( actionBars . getMenuManager ( ) ) ; } public String [ ] internalGetEnabledFilterIds ( ) { Set enabledFilterIds = new HashSet ( fEnabledFilterIds . size ( ) ) ; Iterator iter = fEnabledFilterIds . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; String id = ( String ) entry . getKey ( ) ; boolean isEnabled = ( ( Boolean ) entry . getValue ( ) ) . booleanValue ( ) ; if ( isEnabled ) enabledFilterIds . add ( id ) ; } return ( String [ ] ) enabledFilterIds . toArray ( new String [ enabledFilterIds . size ( ) ] ) ; } public String [ ] removeFiltersFor ( Object parent , Object element , IContentProvider contentProvider ) { String [ ] enabledFilters = internalGetEnabledFilterIds ( ) ; Set newFilters = new HashSet ( ) ; for ( int i = ; i < enabledFilters . length ; i ++ ) { String filterName = enabledFilters [ i ] ; ViewerFilter filter = ( ViewerFilter ) fInstalledBuiltInFilters . get ( filterName ) ; if ( filter == null ) newFilters . add ( filterName ) ; else if ( isSelected ( parent , element , contentProvider , filter ) ) newFilters . add ( filterName ) ; } if ( newFilters . size ( ) == enabledFilters . length ) return new String [ ] ; return ( String [ ] ) newFilters . toArray ( new String [ newFilters . size ( ) ] ) ; } public void setFilters ( String [ ] newFilters ) { setEnabledFilterIds ( newFilters ) ; updateViewerFilters ( true ) ; } private boolean isSelected ( Object parent , Object element , IContentProvider contentProvider , ViewerFilter filter ) { if ( contentProvider instanceof ITreeContentProvider ) { ITreeContentProvider provider = ( ITreeContentProvider ) contentProvider ; while ( element != null && ! ( element instanceof IRubyModel ) ) { if ( ! filter . select ( fViewer , parent , element ) ) return false ; element = provider . getParent ( element ) ; } return true ; } return filter . select ( fViewer , parent , element ) ; } private void setFilter ( String filterId , boolean state ) { fLRUFilterIdsStack . remove ( filterId ) ; fLRUFilterIdsStack . add ( , filterId ) ; fEnabledFilterIds . put ( filterId , new Boolean ( state ) ) ; storeViewDefaults ( ) ; updateViewerFilters ( true ) ; } private void setEnabledFilterIds ( String [ ] enabledIds ) { Iterator iter = fEnabledFilterIds . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String id = ( String ) iter . next ( ) ; fEnabledFilterIds . put ( id , Boolean . FALSE ) ; } for ( int i = ; i < enabledIds . length ; i ++ ) fEnabledFilterIds . put ( enabledIds [ i ] , Boolean . TRUE ) ; } private void setUserDefinedPatterns ( String [ ] patterns ) { fUserDefinedPatterns = patterns ; cleanUpPatternDuplicates ( ) ; } private void setRecentlyChangedFilters ( Stack changeHistory ) { Stack oldestFirstStack = new Stack ( ) ; int length = Math . min ( changeHistory . size ( ) , MAX_FILTER_MENU_ENTRIES ) ; for ( int i = ; i < length ; i ++ ) oldestFirstStack . push ( ( ( FilterDescriptor ) changeHistory . pop ( ) ) . getId ( ) ) ; length = Math . min ( fLRUFilterIdsStack . size ( ) , MAX_FILTER_MENU_ENTRIES - oldestFirstStack . size ( ) ) ; int NEWEST = ; for ( int i = ; i < length ; i ++ ) { Object filter = fLRUFilterIdsStack . remove ( NEWEST ) ; if ( ! oldestFirstStack . contains ( filter ) ) oldestFirstStack . push ( filter ) ; } fLRUFilterIdsStack = oldestFirstStack ; } private boolean areUserDefinedPatternsEnabled ( ) { return fUserDefinedPatternsEnabled ; } private void setUserDefinedPatternsEnabled ( boolean state ) { fUserDefinedPatternsEnabled = state ; } private void fillToolBar ( IToolBarManager tooBar ) { } public void fillViewMenu ( IMenuManager viewMenu ) { viewMenu . add ( new Separator ( "" ) ) ; viewMenu . add ( new GroupMarker ( RECENT_FILTERS_GROUP_NAME ) ) ; viewMenu . add ( new ShowFilterDialogAction ( ) ) ; fMenuManager = viewMenu ; fMenuListener = new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager manager ) { removePreviousLRUFilterActions ( manager ) ; addLRUFilterActions ( manager ) ; } } ; fMenuManager . addMenuListener ( fMenuListener ) ; } private void removePreviousLRUFilterActions ( IMenuManager mm ) { if ( fFilterIdsUsedInLastViewMenu == null ) return ; for ( int i = ; i < fFilterIdsUsedInLastViewMenu . length ; i ++ ) mm . remove ( fFilterIdsUsedInLastViewMenu [ i ] ) ; } private void addLRUFilterActions ( IMenuManager mm ) { if ( fLRUFilterIdsStack . isEmpty ( ) ) { fFilterIdsUsedInLastViewMenu = null ; return ; } SortedSet sortedFilters = new TreeSet ( fLRUFilterIdsStack ) ; String [ ] recentlyChangedFilterIds = ( String [ ] ) sortedFilters . toArray ( new String [ sortedFilters . size ( ) ] ) ; fFilterIdsUsedInLastViewMenu = new String [ recentlyChangedFilterIds . length ] ; for ( int i = ; i < recentlyChangedFilterIds . length ; i ++ ) { String id = recentlyChangedFilterIds [ i ] ; fFilterIdsUsedInLastViewMenu [ i ] = id ; boolean state = fEnabledFilterIds . containsKey ( id ) && ( ( Boolean ) fEnabledFilterIds . get ( id ) ) . booleanValue ( ) ; FilterDescriptor filterDesc = ( FilterDescriptor ) fFilterDescriptorMap . get ( id ) ; if ( filterDesc != null ) { IContributionItem item = new FilterActionMenuContributionItem ( this , id , filterDesc . getName ( ) , state , i + ) ; mm . insertBefore ( RECENT_FILTERS_GROUP_NAME , item ) ; } } } public void dispose ( ) { if ( fMenuManager != null ) fMenuManager . removeMenuListener ( fMenuListener ) ; fCachedFilterDescriptors = null ; super . dispose ( ) ; } private void initializeWithPluginContributions ( ) { fUserDefinedPatterns = new String [ ] ; fUserDefinedPatternsEnabled = false ; FilterDescriptor [ ] filterDescs = getCachedFilterDescriptors ( ) ; fFilterDescriptorMap = new HashMap ( filterDescs . length ) ; fEnabledFilterIds = new HashMap ( filterDescs . length ) ; for ( int i = ; i < filterDescs . length ; i ++ ) { String id = filterDescs [ i ] . getId ( ) ; Boolean isEnabled = new Boolean ( filterDescs [ i ] . isEnabled ( ) ) ; if ( fEnabledFilterIds . containsKey ( id ) ) RubyPlugin . logErrorMessage ( "" ) ; fEnabledFilterIds . put ( id , isEnabled ) ; fFilterDescriptorMap . put ( id , filterDescs [ i ] ) ; } } private void installFilters ( ) { fInstalledBuiltInFilters = new HashMap ( fEnabledFilterIds . size ( ) ) ; fPatternFilter = new NamePatternFilter ( ) ; fPatternFilter . setPatterns ( getUserAndBuiltInPatterns ( ) ) ; fViewer . addFilter ( fPatternFilter ) ; updateBuiltInFilters ( ) ; } private void updateViewerFilters ( boolean refresh ) { String [ ] patterns = getUserAndBuiltInPatterns ( ) ; fPatternFilter . setPatterns ( patterns ) ; fViewer . getControl ( ) . setRedraw ( false ) ; updateBuiltInFilters ( ) ; if ( refresh ) fViewer . refresh ( ) ; fViewer . getControl ( ) . setRedraw ( true ) ; } private void updateBuiltInFilters ( ) { Set installedFilters = fInstalledBuiltInFilters . keySet ( ) ; Set filtersToAdd = new HashSet ( fEnabledFilterIds . size ( ) ) ; Set filtersToRemove = new HashSet ( fEnabledFilterIds . size ( ) ) ; Iterator iter = fEnabledFilterIds . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; String id = ( String ) entry . getKey ( ) ; boolean isEnabled = ( ( Boolean ) entry . getValue ( ) ) . booleanValue ( ) ; if ( isEnabled && ! installedFilters . contains ( id ) ) filtersToAdd . add ( id ) ; else if ( ! isEnabled && installedFilters . contains ( id ) ) filtersToRemove . add ( id ) ; } FilterDescriptor [ ] filterDescs = getCachedFilterDescriptors ( ) ; for ( int i = ; i < filterDescs . length ; i ++ ) { String id = filterDescs [ i ] . getId ( ) ; boolean isCustomFilter = filterDescs [ i ] . isCustomFilter ( ) ; if ( isCustomFilter ) { if ( filtersToAdd . contains ( id ) ) { ViewerFilter filter = filterDescs [ i ] . createViewerFilter ( ) ; if ( filter != null ) { fViewer . addFilter ( filter ) ; fInstalledBuiltInFilters . put ( id , filter ) ; } } if ( filtersToRemove . contains ( id ) ) { fViewer . removeFilter ( ( ViewerFilter ) fInstalledBuiltInFilters . get ( id ) ) ; fInstalledBuiltInFilters . remove ( id ) ; } } } } private String [ ] getUserAndBuiltInPatterns ( ) { List patterns = new ArrayList ( fUserDefinedPatterns . length ) ; if ( areUserDefinedPatternsEnabled ( ) ) patterns . addAll ( Arrays . asList ( fUserDefinedPatterns ) ) ; FilterDescriptor [ ] filterDescs = getCachedFilterDescriptors ( ) ; for ( int i = ; i < filterDescs . length ; i ++ ) { String id = filterDescs [ i ] . getId ( ) ; boolean isPatternFilter = filterDescs [ i ] . isPatternFilter ( ) ; Object isEnabled = fEnabledFilterIds . get ( id ) ; if ( isEnabled != null && isPatternFilter && ( ( Boolean ) isEnabled ) . booleanValue ( ) ) patterns . add ( filterDescs [ i ] . getPattern ( ) ) ; } return ( String [ ] ) patterns . toArray ( new String [ patterns . size ( ) ] ) ; } private void initializeWithViewDefaults ( ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; if ( ! store . contains ( getPreferenceKey ( "" ) ) ) return ; fUserDefinedPatternsEnabled = store . getBoolean ( getPreferenceKey ( TAG_USER_DEFINED_PATTERNS_ENABLED ) ) ; setUserDefinedPatterns ( CustomFiltersDialog . convertFromString ( store . getString ( getPreferenceKey ( TAG_USER_DEFINED_PATTERNS ) ) , SEPARATOR ) ) ; Iterator iter = fEnabledFilterIds . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String id = ( String ) iter . next ( ) ; Boolean isEnabled = new Boolean ( store . getBoolean ( id ) ) ; fEnabledFilterIds . put ( id , isEnabled ) ; } fLRUFilterIdsStack . clear ( ) ; String lruFilterIds = store . getString ( TAG_LRU_FILTERS ) ; StringTokenizer tokenizer = new StringTokenizer ( lruFilterIds , SEPARATOR ) ; while ( tokenizer . hasMoreTokens ( ) ) { String id = tokenizer . nextToken ( ) ; if ( fFilterDescriptorMap . containsKey ( id ) && ! fLRUFilterIdsStack . contains ( id ) ) fLRUFilterIdsStack . push ( id ) ; } } private void storeViewDefaults ( ) { IPreferenceStore store = RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ; store . setValue ( getPreferenceKey ( "" ) , "" ) ; store . setValue ( getPreferenceKey ( TAG_USER_DEFINED_PATTERNS_ENABLED ) , fUserDefinedPatternsEnabled ) ; store . setValue ( getPreferenceKey ( TAG_USER_DEFINED_PATTERNS ) , CustomFiltersDialog . convertToString ( fUserDefinedPatterns , SEPARATOR ) ) ; Iterator iter = fEnabledFilterIds . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; String id = ( String ) entry . getKey ( ) ; boolean isEnabled = ( ( Boolean ) entry . getValue ( ) ) . booleanValue ( ) ; store . setValue ( id , isEnabled ) ; } StringBuffer buf = new StringBuffer ( fLRUFilterIdsStack . size ( ) * ) ; iter = fLRUFilterIdsStack . iterator ( ) ; while ( iter . hasNext ( ) ) { buf . append ( ( String ) iter . next ( ) ) ; buf . append ( SEPARATOR ) ; } store . setValue ( TAG_LRU_FILTERS , buf . toString ( ) ) ; } private String getPreferenceKey ( String tag ) { return "" + fTargetId + '' + tag ; } public void saveState ( IMemento memento ) { IMemento customFilters = memento . createChild ( TAG_CUSTOM_FILTERS ) ; customFilters . putString ( TAG_USER_DEFINED_PATTERNS_ENABLED , new Boolean ( fUserDefinedPatternsEnabled ) . toString ( ) ) ; saveUserDefinedPatterns ( customFilters ) ; saveXmlDefinedFilters ( customFilters ) ; saveLRUFilters ( customFilters ) ; } private void saveXmlDefinedFilters ( IMemento memento ) { if ( fEnabledFilterIds != null && ! fEnabledFilterIds . isEmpty ( ) ) { IMemento xmlDefinedFilters = memento . createChild ( TAG_XML_DEFINED_FILTERS ) ; Iterator iter = fEnabledFilterIds . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; String id = ( String ) entry . getKey ( ) ; Boolean isEnabled = ( Boolean ) entry . getValue ( ) ; IMemento child = xmlDefinedFilters . createChild ( TAG_CHILD ) ; child . putString ( TAG_FILTER_ID , id ) ; child . putString ( TAG_IS_ENABLED , isEnabled . toString ( ) ) ; } } } private void saveLRUFilters ( IMemento memento ) { if ( fLRUFilterIdsStack != null && ! fLRUFilterIdsStack . isEmpty ( ) ) { IMemento lruFilters = memento . createChild ( TAG_LRU_FILTERS ) ; Iterator iter = fLRUFilterIdsStack . iterator ( ) ; while ( iter . hasNext ( ) ) { String id = ( String ) iter . next ( ) ; IMemento child = lruFilters . createChild ( TAG_CHILD ) ; child . putString ( TAG_FILTER_ID , id ) ; } } } private void saveUserDefinedPatterns ( IMemento memento ) { if ( fUserDefinedPatterns != null && fUserDefinedPatterns . length > ) { IMemento userDefinedPatterns = memento . createChild ( TAG_USER_DEFINED_PATTERNS ) ; for ( int i = ; i < fUserDefinedPatterns . length ; i ++ ) { IMemento child = userDefinedPatterns . createChild ( TAG_CHILD ) ; child . putString ( TAG_PATTERN , fUserDefinedPatterns [ i ] ) ; } } } public void restoreState ( IMemento memento ) { if ( memento == null ) return ; IMemento customFilters = memento . getChild ( TAG_CUSTOM_FILTERS ) ; if ( customFilters == null ) return ; String userDefinedPatternsEnabled = customFilters . getString ( TAG_USER_DEFINED_PATTERNS_ENABLED ) ; if ( userDefinedPatternsEnabled == null ) return ; fUserDefinedPatternsEnabled = Boolean . valueOf ( userDefinedPatternsEnabled ) . booleanValue ( ) ; restoreUserDefinedPatterns ( customFilters ) ; restoreXmlDefinedFilters ( customFilters ) ; restoreLRUFilters ( customFilters ) ; updateViewerFilters ( false ) ; } private void restoreUserDefinedPatterns ( IMemento memento ) { IMemento userDefinedPatterns = memento . getChild ( TAG_USER_DEFINED_PATTERNS ) ; if ( userDefinedPatterns != null ) { IMemento children [ ] = userDefinedPatterns . getChildren ( TAG_CHILD ) ; String [ ] patterns = new String [ children . length ] ; for ( int i = ; i < children . length ; i ++ ) patterns [ i ] = children [ i ] . getString ( TAG_PATTERN ) ; setUserDefinedPatterns ( patterns ) ; } else setUserDefinedPatterns ( new String [ ] ) ; } private void restoreXmlDefinedFilters ( IMemento memento ) { IMemento xmlDefinedFilters = memento . getChild ( TAG_XML_DEFINED_FILTERS ) ; if ( xmlDefinedFilters != null ) { IMemento [ ] children = xmlDefinedFilters . getChildren ( TAG_CHILD ) ; for ( int i = ; i < children . length ; i ++ ) { String id = children [ i ] . getString ( TAG_FILTER_ID ) ; Boolean isEnabled = new Boolean ( children [ i ] . getString ( TAG_IS_ENABLED ) ) ; fEnabledFilterIds . put ( id , isEnabled ) ; } } } private void restoreLRUFilters ( IMemento memento ) { IMemento lruFilters = memento . getChild ( TAG_LRU_FILTERS ) ; fLRUFilterIdsStack . clear ( ) ; if ( lruFilters != null ) { IMemento [ ] children = lruFilters . getChildren ( TAG_CHILD ) ; for ( int i = ; i < children . length ; i ++ ) { String id = children [ i ] . getString ( TAG_FILTER_ID ) ; if ( fFilterDescriptorMap . containsKey ( id ) && ! fLRUFilterIdsStack . contains ( id ) ) fLRUFilterIdsStack . push ( id ) ; } } } private void cleanUpPatternDuplicates ( ) { if ( ! areUserDefinedPatternsEnabled ( ) ) return ; List userDefinedPatterns = new ArrayList ( Arrays . asList ( fUserDefinedPatterns ) ) ; FilterDescriptor [ ] filters = getCachedFilterDescriptors ( ) ; for ( int i = ; i < filters . length ; i ++ ) { if ( filters [ i ] . isPatternFilter ( ) ) { String pattern = filters [ i ] . getPattern ( ) ; if ( userDefinedPatterns . contains ( pattern ) ) { fEnabledFilterIds . put ( filters [ i ] . getId ( ) , Boolean . TRUE ) ; boolean hasMore = true ; while ( hasMore ) hasMore = userDefinedPatterns . remove ( pattern ) ; } } } fUserDefinedPatterns = ( String [ ] ) userDefinedPatterns . toArray ( new String [ userDefinedPatterns . size ( ) ] ) ; setUserDefinedPatternsEnabled ( fUserDefinedPatternsEnabled && fUserDefinedPatterns . length > ) ; } private FilterDescriptor [ ] getCachedFilterDescriptors ( ) { if ( fCachedFilterDescriptors == null ) fCachedFilterDescriptors = FilterDescriptor . getFilterDescriptors ( fTargetId ) ; return fCachedFilterDescriptors ; } private void openDialog ( ) { CustomFiltersDialog dialog = new CustomFiltersDialog ( fViewer . getControl ( ) . getShell ( ) , fTargetId , areUserDefinedPatternsEnabled ( ) , fUserDefinedPatterns , internalGetEnabledFilterIds ( ) ) ; if ( dialog . open ( ) == Window . OK ) { setEnabledFilterIds ( dialog . getEnabledFilterIds ( ) ) ; setUserDefinedPatternsEnabled ( dialog . areUserDefinedPatternsEnabled ( ) ) ; setUserDefinedPatterns ( dialog . getUserDefinedPatterns ( ) ) ; setRecentlyChangedFilters ( dialog . getFilterDescriptorChangeHistory ( ) ) ; storeViewDefaults ( ) ; updateViewerFilters ( true ) ; } } } package org . rubypeople . rdt . ui . actions ; import java . lang . reflect . Constructor ; import java . util . Iterator ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . actions . CloseResourceAction ; import org . eclipse . ui . ide . IDEActionFactory ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . ui . IContextMenuConstants ; public class ProjectActionGroup extends ActionGroup { private IWorkbenchSite fSite ; private OpenProjectAction fOpenAction ; private CloseResourceAction fCloseAction ; private CloseResourceAction fCloseUnrelatedAction ; public ProjectActionGroup ( IViewPart part ) { fSite = part . getSite ( ) ; Shell shell = fSite . getShell ( ) ; ISelectionProvider provider = fSite . getSelectionProvider ( ) ; ISelection selection = provider . getSelection ( ) ; fCloseAction = new CloseResourceAction ( shell ) ; fCloseAction . setActionDefinitionId ( "" ) ; fCloseUnrelatedAction = createCloseUnrelatedAction ( shell ) ; fCloseUnrelatedAction . setActionDefinitionId ( "" ) ; fOpenAction = new OpenProjectAction ( fSite ) ; fOpenAction . setActionDefinitionId ( "" ) ; if ( selection instanceof IStructuredSelection ) { IStructuredSelection s = ( IStructuredSelection ) selection ; fOpenAction . selectionChanged ( s ) ; fCloseAction . selectionChanged ( s ) ; fCloseUnrelatedAction . selectionChanged ( s ) ; } provider . addSelectionChangedListener ( fOpenAction ) ; provider . addSelectionChangedListener ( fCloseAction ) ; provider . addSelectionChangedListener ( fCloseUnrelatedAction ) ; IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; workspace . addResourceChangeListener ( fOpenAction ) ; workspace . addResourceChangeListener ( fCloseAction ) ; workspace . addResourceChangeListener ( fCloseUnrelatedAction ) ; } protected CloseResourceAction createCloseUnrelatedAction ( Shell shell ) { Class clazz = getCloseUnrelatedProjectsActionClass ( ) ; if ( clazz == null ) return null ; try { Constructor cons = clazz . getDeclaredConstructor ( new Class [ ] { Shell . class } ) ; return ( CloseResourceAction ) cons . newInstance ( new Object [ ] { shell } ) ; } catch ( Exception e ) { RubyPlugin . log ( e ) ; } return null ; } private Class getCloseUnrelatedProjectsActionClass ( ) { try { return Class . forName ( "" ) ; } catch ( ClassNotFoundException e ) { try { return Class . forName ( "" ) ; } catch ( ClassNotFoundException e1 ) { RubyPlugin . log ( e1 ) ; } } return null ; } public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; actionBars . setGlobalActionHandler ( IDEActionFactory . CLOSE_PROJECT . getId ( ) , fCloseAction ) ; actionBars . setGlobalActionHandler ( IDEActionFactory . CLOSE_UNRELATED_PROJECTS . getId ( ) , fCloseUnrelatedAction ) ; actionBars . setGlobalActionHandler ( IDEActionFactory . OPEN_PROJECT . getId ( ) , fOpenAction ) ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; if ( fOpenAction . isEnabled ( ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_BUILD , fOpenAction ) ; if ( fCloseAction . isEnabled ( ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_BUILD , fCloseAction ) ; if ( fCloseUnrelatedAction . isEnabled ( ) && areOnlyProjectsSelected ( fCloseUnrelatedAction . getStructuredSelection ( ) ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_BUILD , fCloseUnrelatedAction ) ; } private boolean areOnlyProjectsSelected ( IStructuredSelection selection ) { if ( selection . isEmpty ( ) ) return false ; Iterator iter = selection . iterator ( ) ; while ( iter . hasNext ( ) ) { Object obj = iter . next ( ) ; if ( obj instanceof IAdaptable ) { if ( ( ( IAdaptable ) obj ) . getAdapter ( IProject . class ) == null ) return false ; } } return true ; } public void dispose ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; provider . removeSelectionChangedListener ( fOpenAction ) ; provider . removeSelectionChangedListener ( fCloseAction ) ; provider . removeSelectionChangedListener ( fCloseUnrelatedAction ) ; IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; workspace . removeResourceChangeListener ( fOpenAction ) ; workspace . removeResourceChangeListener ( fCloseAction ) ; workspace . removeResourceChangeListener ( fCloseUnrelatedAction ) ; super . dispose ( ) ; } } package org . rubypeople . rdt . ui . actions ; import java . util . Iterator ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; public class DeclarationsSearchGroup extends ActionGroup { private static final String MENU_TEXT = SearchMessages . group_declarations ; private IWorkbenchSite fSite ; private RubyEditor fEditor ; private IActionBars fActionBars ; private String fGroupId ; private FindDeclarationsAction fFindDeclarationsAction ; private FindDeclarationsInProjectAction fFindDeclarationsInProjectAction ; private FindDeclarationsInWorkingSetAction fFindDeclarationsInWorkingSetAction ; public DeclarationsSearchGroup ( IWorkbenchSite site ) { fSite = site ; fGroupId = IContextMenuConstants . GROUP_SEARCH ; fFindDeclarationsAction = new FindDeclarationsAction ( site ) ; fFindDeclarationsAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_DECLARATIONS_IN_WORKSPACE ) ; fFindDeclarationsInProjectAction = new FindDeclarationsInProjectAction ( site ) ; fFindDeclarationsInProjectAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_DECLARATIONS_IN_PROJECTS ) ; fFindDeclarationsInWorkingSetAction = new FindDeclarationsInWorkingSetAction ( site ) ; fFindDeclarationsInWorkingSetAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_DECLARATIONS_IN_WORKING_SET ) ; ISelectionProvider provider = fSite . getSelectionProvider ( ) ; ISelection selection = provider . getSelection ( ) ; registerAction ( fFindDeclarationsAction , provider , selection ) ; registerAction ( fFindDeclarationsInProjectAction , provider , selection ) ; registerAction ( fFindDeclarationsInWorkingSetAction , provider , selection ) ; } public DeclarationsSearchGroup ( RubyEditor editor ) { Assert . isNotNull ( editor ) ; fEditor = editor ; fSite = fEditor . getSite ( ) ; fGroupId = ITextEditorActionConstants . GROUP_FIND ; fFindDeclarationsAction = new FindDeclarationsAction ( fEditor ) ; fFindDeclarationsAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_DECLARATIONS_IN_WORKSPACE ) ; fEditor . setAction ( "" , fFindDeclarationsAction ) ; fFindDeclarationsInProjectAction = new FindDeclarationsInProjectAction ( fEditor ) ; fFindDeclarationsInProjectAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_DECLARATIONS_IN_PROJECTS ) ; fEditor . setAction ( "" , fFindDeclarationsInProjectAction ) ; fFindDeclarationsInWorkingSetAction = new FindDeclarationsInWorkingSetAction ( fEditor ) ; fFindDeclarationsInWorkingSetAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_DECLARATIONS_IN_WORKING_SET ) ; fEditor . setAction ( "" , fFindDeclarationsInWorkingSetAction ) ; } private void registerAction ( SelectionDispatchAction action , ISelectionProvider provider , ISelection selection ) { action . update ( selection ) ; provider . addSelectionChangedListener ( action ) ; } public void fillActionBars ( IActionBars actionBars ) { Assert . isNotNull ( actionBars ) ; super . fillActionBars ( actionBars ) ; fActionBars = actionBars ; updateGlobalActionHandlers ( ) ; } private void addAction ( IAction action , IMenuManager manager ) { if ( action . isEnabled ( ) ) { manager . add ( action ) ; } } private void addWorkingSetAction ( IWorkingSet [ ] workingSets , IMenuManager manager ) { FindAction action ; if ( fEditor != null ) action = new WorkingSetFindAction ( fEditor , new FindDeclarationsInWorkingSetAction ( fEditor , workingSets ) , SearchUtil . toString ( workingSets ) ) ; else action = new WorkingSetFindAction ( fSite , new FindDeclarationsInWorkingSetAction ( fSite , workingSets ) , SearchUtil . toString ( workingSets ) ) ; action . update ( getContext ( ) . getSelection ( ) ) ; addAction ( action , manager ) ; } public void fillContextMenu ( IMenuManager manager ) { IMenuManager javaSearchMM = new MenuManager ( MENU_TEXT , IContextMenuConstants . GROUP_SEARCH ) ; addAction ( fFindDeclarationsAction , javaSearchMM ) ; addAction ( fFindDeclarationsInProjectAction , javaSearchMM ) ; javaSearchMM . add ( new Separator ( ) ) ; Iterator iter = SearchUtil . getLRUWorkingSets ( ) . sortedIterator ( ) ; while ( iter . hasNext ( ) ) { addWorkingSetAction ( ( IWorkingSet [ ] ) iter . next ( ) , javaSearchMM ) ; } addAction ( fFindDeclarationsInWorkingSetAction , javaSearchMM ) ; if ( ! javaSearchMM . isEmpty ( ) ) manager . appendToGroup ( fGroupId , javaSearchMM ) ; } public void dispose ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; if ( provider != null ) { disposeAction ( fFindDeclarationsAction , provider ) ; disposeAction ( fFindDeclarationsInProjectAction , provider ) ; disposeAction ( fFindDeclarationsInWorkingSetAction , provider ) ; } fFindDeclarationsAction = null ; fFindDeclarationsInProjectAction = null ; fFindDeclarationsInWorkingSetAction = null ; updateGlobalActionHandlers ( ) ; super . dispose ( ) ; } private void updateGlobalActionHandlers ( ) { if ( fActionBars != null ) { fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_DECLARATIONS_IN_WORKSPACE , fFindDeclarationsAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_DECLARATIONS_IN_PROJECT , fFindDeclarationsInProjectAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_DECLARATIONS_IN_WORKING_SET , fFindDeclarationsInWorkingSetAction ) ; } } private void disposeAction ( ISelectionChangedListener action , ISelectionProvider provider ) { if ( action != null ) provider . removeSelectionChangedListener ( action ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; public class FindDeclarationsAction extends FindAction { public FindDeclarationsAction ( IWorkbenchSite site ) { super ( site ) ; } public FindDeclarationsAction ( RubyEditor editor ) { super ( editor ) ; } void init ( ) { setText ( SearchMessages . Search_FindDeclarationAction_label ) ; setToolTipText ( SearchMessages . Search_FindDeclarationAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_DECL ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_DECLARATIONS_IN_WORKSPACE_ACTION ) ; } Class [ ] getValidTypes ( ) { return new Class [ ] { IField . class , IMethod . class , IType . class , IRubyScript . class , IImportDeclaration . class , ISourceFolder . class } ; } int getLimitTo ( ) { return IRubySearchConstants . DECLARATIONS | IRubySearchConstants . IGNORE_DECLARING_TYPE ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; public class FindWriteReferencesInWorkingSetAction extends FindReferencesInWorkingSetAction { public FindWriteReferencesInWorkingSetAction ( IWorkbenchSite site ) { super ( site ) ; } public FindWriteReferencesInWorkingSetAction ( IWorkbenchSite site , IWorkingSet [ ] workingSets ) { super ( site , workingSets ) ; } public FindWriteReferencesInWorkingSetAction ( RubyEditor editor ) { super ( editor ) ; } public FindWriteReferencesInWorkingSetAction ( RubyEditor editor , IWorkingSet [ ] workingSets ) { super ( editor , workingSets ) ; } Class [ ] getValidTypes ( ) { return new Class [ ] { IField . class } ; } void init ( ) { setText ( SearchMessages . Search_FindWriteReferencesInWorkingSetAction_label ) ; setToolTipText ( SearchMessages . Search_FindWriteReferencesInWorkingSetAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION ) ; } int getLimitTo ( ) { return IRubySearchConstants . WRITE_ACCESSES ; } String getOperationUnavailableMessage ( ) { return SearchMessages . RubyElementAction_operationUnavailable_field ; } } package org . rubypeople . rdt . ui . actions ; public class RdtActionConstants { public static final String OPEN = "" ; public static final String OPEN_TYPE_HIERARCHY = "" ; public static final String OPEN_CALL_HIERARCHY = "" ; public static final String SHOW_RUBY_DOC = "" ; public static final String FIND_REFERENCES_IN_WORKSPACE = "" ; public static final String FIND_REFERENCES_IN_PROJECT = "" ; public static final String FIND_REFERENCES_IN_HIERARCHY = "" ; public static final String FIND_REFERENCES_IN_WORKING_SET = "" ; public static final String FIND_READ_ACCESS_IN_WORKSPACE = "" ; public static final String FIND_READ_ACCESS_IN_PROJECT = "" ; public static final String FIND_READ_ACCESS_IN_WORKING_SET = "" ; public static final String FIND_OCCURRENCES_IN_FILE = "" ; public static final String FIND_DECLARATIONS_IN_WORKSPACE = "" ; public static final String FIND_DECLARATIONS_IN_PROJECT = "" ; public static final String FIND_DECLARATIONS_IN_WORKING_SET = "" ; public static final String FIND_WRITE_ACCESS_IN_WORKSPACE = "" ; public static final String FIND_WRITE_ACCESS_IN_PROJECT = "" ; public static final String FIND_WRITE_ACCESS_IN_WORKING_SET = "" ; } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . packageview . PackageExplorerPart ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; public class ShowInRubyExplorerViewAction extends SelectionDispatchAction { private RubyEditor fEditor ; public ShowInRubyExplorerViewAction ( IWorkbenchSite site ) { super ( site ) ; setText ( ActionMessages . ShowInPackageViewAction_label ) ; setDescription ( ActionMessages . ShowInPackageViewAction_description ) ; setToolTipText ( ActionMessages . ShowInPackageViewAction_tooltip ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . SHOW_IN_PACKAGEVIEW_ACTION ) ; } public ShowInRubyExplorerViewAction ( RubyEditor editor ) { this ( editor . getEditorSite ( ) ) ; fEditor = editor ; setEnabled ( SelectionConverter . canOperateOn ( fEditor ) ) ; } public void selectionChanged ( ITextSelection selection ) { } public void selectionChanged ( IStructuredSelection selection ) { setEnabled ( checkEnabled ( selection ) ) ; } private boolean checkEnabled ( IStructuredSelection selection ) { if ( selection . size ( ) != ) return false ; return selection . getFirstElement ( ) instanceof IRubyElement ; } public void run ( ITextSelection selection ) { try { IRubyElement element = SelectionConverter . getElementAtOffset ( fEditor ) ; if ( element != null ) run ( element ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; String message = ActionMessages . ShowInPackageViewAction_error_message ; ErrorDialog . openError ( getShell ( ) , getDialogTitle ( ) , message , e . getStatus ( ) ) ; } } public void run ( IStructuredSelection selection ) { if ( ! checkEnabled ( selection ) ) return ; run ( ( IRubyElement ) selection . getFirstElement ( ) ) ; } private void run ( IRubyElement element ) { if ( element == null ) return ; IOpenable openable = element . getOpenable ( ) ; if ( openable instanceof IRubyElement ) element = ( IRubyElement ) openable ; PackageExplorerPart view = PackageExplorerPart . openInActivePerspective ( ) ; view . tryToReveal ( element ) ; } private static String getDialogTitle ( ) { return ActionMessages . ShowInPackageViewAction_dialog_title ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class FindReferencesInWorkingSetAction extends FindReferencesAction { private IWorkingSet [ ] fWorkingSets ; public FindReferencesInWorkingSetAction ( IWorkbenchSite site ) { this ( site , null ) ; } public FindReferencesInWorkingSetAction ( IWorkbenchSite site , IWorkingSet [ ] workingSets ) { super ( site ) ; fWorkingSets = workingSets ; } public FindReferencesInWorkingSetAction ( RubyEditor editor ) { this ( editor , null ) ; } public FindReferencesInWorkingSetAction ( RubyEditor editor , IWorkingSet [ ] workingSets ) { super ( editor ) ; fWorkingSets = workingSets ; } void init ( ) { setText ( SearchMessages . Search_FindReferencesInWorkingSetAction_label ) ; setToolTipText ( SearchMessages . Search_FindReferencesInWorkingSetAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_REFERENCES_IN_WORKING_SET_ACTION ) ; } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; IWorkingSet [ ] workingSets = fWorkingSets ; if ( fWorkingSets == null ) { workingSets = factory . queryWorkingSets ( ) ; if ( workingSets == null ) return null ; } SearchUtil . updateLRUWorkingSets ( workingSets ) ; IRubySearchScope scope = factory . createRubySearchScope ( workingSets , true ) ; String description = factory . getWorkingSetScopeDescription ( workingSets , true ) ; return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } } package org . rubypeople . rdt . ui . actions ; import java . lang . reflect . InvocationTargetException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . ElementListSelectionDialog ; import org . eclipse . ui . progress . IProgressService ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . ActionUtil ; import org . rubypeople . rdt . internal . ui . actions . OpenActionUtil ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchQuery ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public abstract class FindAction extends SelectionDispatchAction { private static final IRubyElement RETURN_WITHOUT_BEEP = RubyCore . create ( RubyPlugin . getWorkspace ( ) . getRoot ( ) ) ; private Class [ ] fValidTypes ; private RubyEditor fEditor ; FindAction ( IWorkbenchSite site ) { super ( site ) ; fValidTypes = getValidTypes ( ) ; init ( ) ; } FindAction ( RubyEditor editor ) { this ( editor . getEditorSite ( ) ) ; fEditor = editor ; setEnabled ( SelectionConverter . canOperateOn ( fEditor ) ) ; } abstract void init ( ) ; abstract Class [ ] getValidTypes ( ) ; private boolean canOperateOn ( IStructuredSelection sel ) { return sel != null && ! sel . isEmpty ( ) && canOperateOn ( getRubyElement ( sel , true ) ) ; } boolean canOperateOn ( IRubyElement element ) { if ( element == null || fValidTypes == null || fValidTypes . length == || ! ActionUtil . isOnBuildPath ( element ) ) return false ; for ( int i = ; i < fValidTypes . length ; i ++ ) { if ( fValidTypes [ i ] . isInstance ( element ) ) { if ( element . getElementType ( ) == IRubyElement . SOURCE_FOLDER ) return hasChildren ( ( ISourceFolder ) element ) ; else return true ; } } return false ; } private boolean hasChildren ( ISourceFolder packageFragment ) { try { return packageFragment . hasChildren ( ) ; } catch ( RubyModelException ex ) { return false ; } } private IRubyElement getTypeIfPossible ( IRubyElement o , boolean silent ) { switch ( o . getElementType ( ) ) { case IRubyElement . SCRIPT : if ( silent ) return o ; else return findType ( ( IRubyScript ) o , silent ) ; default : return o ; } } IRubyElement getRubyElement ( IStructuredSelection selection , boolean silent ) { if ( selection . size ( ) == ) { Object firstElement = selection . getFirstElement ( ) ; IRubyElement elem = null ; if ( firstElement instanceof IRubyElement ) elem = ( IRubyElement ) firstElement ; else if ( firstElement instanceof IAdaptable ) elem = ( IRubyElement ) ( ( IAdaptable ) firstElement ) . getAdapter ( IRubyElement . class ) ; if ( elem != null ) { return getTypeIfPossible ( elem , silent ) ; } } return null ; } private void showOperationUnavailableDialog ( ) { MessageDialog . openInformation ( getShell ( ) , SearchMessages . RubyElementAction_operationUnavailable_title , getOperationUnavailableMessage ( ) ) ; } String getOperationUnavailableMessage ( ) { return SearchMessages . RubyElementAction_operationUnavailable_generic ; } private IRubyElement findType ( IRubyScript cu , boolean silent ) { IType [ ] types = null ; try { types = cu . getAllTypes ( ) ; } catch ( RubyModelException ex ) { if ( RubyModelUtil . isExceptionToBeLogged ( ex ) ) ExceptionHandler . log ( ex , SearchMessages . RubyElementAction_error_open_message ) ; if ( silent ) return RETURN_WITHOUT_BEEP ; else return null ; } if ( types . length == || ( silent && types . length > ) ) return types [ ] ; if ( silent ) return RETURN_WITHOUT_BEEP ; if ( types . length == ) return null ; String title = SearchMessages . RubyElementAction_typeSelectionDialog_title ; String message = SearchMessages . RubyElementAction_typeSelectionDialog_message ; int flags = ( RubyElementLabelProvider . SHOW_DEFAULT ) ; ElementListSelectionDialog dialog = new ElementListSelectionDialog ( getShell ( ) , new RubyElementLabelProvider ( flags ) ) ; dialog . setTitle ( title ) ; dialog . setMessage ( message ) ; dialog . setElements ( types ) ; if ( dialog . open ( ) == Window . OK ) return ( IType ) dialog . getFirstResult ( ) ; else return RETURN_WITHOUT_BEEP ; } public void run ( IStructuredSelection selection ) { IRubyElement element = getRubyElement ( selection , false ) ; if ( element == null || ! element . exists ( ) ) { showOperationUnavailableDialog ( ) ; return ; } else if ( element == RETURN_WITHOUT_BEEP ) return ; run ( element ) ; } public void run ( ITextSelection selection ) { if ( ! ActionUtil . isProcessable ( getShell ( ) , fEditor ) ) return ; try { String title = SearchMessages . SearchElementSelectionDialog_title ; String message = SearchMessages . SearchElementSelectionDialog_message ; IRubyElement [ ] elements = SelectionConverter . codeResolveForked ( fEditor , true ) ; if ( elements . length > && canOperateOn ( elements [ ] ) ) { IRubyElement element = elements [ ] ; if ( elements . length > ) element = OpenActionUtil . selectRubyElement ( elements , getShell ( ) , title , message ) ; if ( element != null ) run ( element ) ; } else showOperationUnavailableDialog ( ) ; } catch ( InvocationTargetException ex ) { String title = SearchMessages . Search_Error_search_title ; String message = SearchMessages . Search_Error_codeResolve ; ExceptionHandler . handle ( ex , getShell ( ) , title , message ) ; } catch ( InterruptedException e ) { } } public void selectionChanged ( IStructuredSelection selection ) { setEnabled ( canOperateOn ( selection ) ) ; } public void selectionChanged ( ITextSelection selection ) { } public void run ( IRubyElement element ) { if ( ! ActionUtil . isProcessable ( getShell ( ) , element ) ) return ; try { performNewSearch ( element ) ; } catch ( RubyModelException ex ) { ExceptionHandler . handle ( ex , getShell ( ) , SearchMessages . Search_Error_search_notsuccessful_title , SearchMessages . Search_Error_search_notsuccessful_message ) ; } } private void performNewSearch ( IRubyElement element ) throws RubyModelException { RubySearchQuery query = new RubySearchQuery ( createQuery ( element ) ) ; if ( query . canRunInBackground ( ) ) { SearchUtil . runQueryInBackground ( query ) ; } else { IProgressService progressService = PlatformUI . getWorkbench ( ) . getProgressService ( ) ; IStatus status = SearchUtil . runQueryInForeground ( progressService , query ) ; if ( status . matches ( IStatus . ERROR | IStatus . INFO | IStatus . WARNING ) ) { ErrorDialog . openError ( getShell ( ) , SearchMessages . Search_Error_search_title , SearchMessages . Search_Error_search_message , status ) ; } } } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; IRubySearchScope scope = factory . createWorkspaceScope ( true ) ; String description = factory . getWorkspaceScopeDescription ( true ) ; return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } abstract int getLimitTo ( ) ; IType getType ( IRubyElement element ) { if ( element == null ) return null ; IType type = null ; if ( element . getElementType ( ) == IRubyElement . TYPE ) type = ( IType ) element ; else if ( element instanceof IMember ) type = ( ( IMember ) element ) . getDeclaringType ( ) ; return type ; } RubyEditor getEditor ( ) { return fEditor ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . core . resources . IncrementalProjectBuilder ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . actions . BuildAction ; import org . eclipse . ui . ide . IDEActionFactory ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . ui . IContextMenuConstants ; public class BuildActionGroup extends ActionGroup { private IWorkbenchSite fSite ; private BuildAction fBuildAction ; private RefreshAction fRefreshAction ; public BuildActionGroup ( IViewPart part ) { fSite = part . getSite ( ) ; Shell shell = fSite . getShell ( ) ; ISelectionProvider provider = fSite . getSelectionProvider ( ) ; fBuildAction = new BuildAction ( shell , IncrementalProjectBuilder . INCREMENTAL_BUILD ) ; fBuildAction . setText ( ActionMessages . BuildAction_label ) ; fBuildAction . setActionDefinitionId ( "" ) ; fRefreshAction = new RefreshAction ( fSite ) ; fRefreshAction . setActionDefinitionId ( "" ) ; provider . addSelectionChangedListener ( fBuildAction ) ; provider . addSelectionChangedListener ( fRefreshAction ) ; } public IAction getRefreshAction ( ) { return fRefreshAction ; } public void fillActionBars ( IActionBars actionBar ) { super . fillActionBars ( actionBar ) ; setGlobalActionHandlers ( actionBar ) ; } public void fillContextMenu ( IMenuManager menu ) { ISelection selection = getContext ( ) . getSelection ( ) ; if ( ! ResourcesPlugin . getWorkspace ( ) . isAutoBuilding ( ) && isBuildTarget ( selection ) ) { appendToGroup ( menu , fBuildAction ) ; } appendToGroup ( menu , fRefreshAction ) ; super . fillContextMenu ( menu ) ; } public void dispose ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; provider . removeSelectionChangedListener ( fBuildAction ) ; provider . removeSelectionChangedListener ( fRefreshAction ) ; super . dispose ( ) ; } private void setGlobalActionHandlers ( IActionBars actionBar ) { actionBar . setGlobalActionHandler ( IDEActionFactory . BUILD_PROJECT . getId ( ) , fBuildAction ) ; actionBar . setGlobalActionHandler ( ActionFactory . REFRESH . getId ( ) , fRefreshAction ) ; } private void appendToGroup ( IMenuManager menu , IAction action ) { if ( action . isEnabled ( ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_BUILD , action ) ; } private boolean isBuildTarget ( ISelection s ) { if ( ! ( s instanceof IStructuredSelection ) ) return false ; IStructuredSelection selection = ( IStructuredSelection ) s ; if ( selection . size ( ) != ) return false ; return selection . getFirstElement ( ) instanceof IRubyProject ; } } package org . rubypeople . rdt . ui . actions ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . IRubyStatusConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . actions . ActionUtil ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . util . OpenTypeHierarchyUtil ; public class OpenTypeHierarchyAction extends SelectionDispatchAction { private RubyEditor fEditor ; public OpenTypeHierarchyAction ( IWorkbenchSite site ) { super ( site ) ; setText ( ActionMessages . OpenTypeHierarchyAction_label ) ; setToolTipText ( ActionMessages . OpenTypeHierarchyAction_tooltip ) ; setDescription ( ActionMessages . OpenTypeHierarchyAction_description ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . OPEN_TYPE_HIERARCHY_ACTION ) ; } public OpenTypeHierarchyAction ( IWorkbenchSite site , ISelectionProvider provider ) { this ( site ) ; setSpecialSelectionProvider ( provider ) ; } public OpenTypeHierarchyAction ( RubyEditor editor ) { this ( editor . getEditorSite ( ) ) ; fEditor = editor ; setEnabled ( SelectionConverter . canOperateOn ( fEditor ) ) ; } public void selectionChanged ( ITextSelection selection ) { } public void selectionChanged ( IStructuredSelection selection ) { setEnabled ( isEnabled ( selection ) ) ; } private boolean isEnabled ( IStructuredSelection selection ) { if ( selection . size ( ) != ) return false ; Object input = selection . getFirstElement ( ) ; if ( ! ( input instanceof IRubyElement ) ) return false ; switch ( ( ( IRubyElement ) input ) . getElementType ( ) ) { case IRubyElement . METHOD : case IRubyElement . FIELD : case IRubyElement . TYPE : return true ; case IRubyElement . SOURCE_FOLDER_ROOT : case IRubyElement . RUBY_PROJECT : case IRubyElement . SOURCE_FOLDER : case IRubyElement . IMPORT_DECLARATION : case IRubyElement . SCRIPT : return true ; case IRubyElement . LOCAL_VARIABLE : default : return false ; } } public void run ( ITextSelection selection ) { IRubyElement input = SelectionConverter . getInput ( fEditor ) ; if ( ! ActionUtil . isProcessable ( getShell ( ) , input ) ) return ; try { IRubyElement [ ] elements = SelectionConverter . codeResolveOrInputForked ( fEditor ) ; if ( elements == null ) return ; List candidates = new ArrayList ( elements . length ) ; for ( int i = ; i < elements . length ; i ++ ) { IRubyElement [ ] resolvedElements = OpenTypeHierarchyUtil . getCandidates ( elements [ i ] ) ; if ( resolvedElements != null ) candidates . addAll ( Arrays . asList ( resolvedElements ) ) ; } run ( ( IRubyElement [ ] ) candidates . toArray ( new IRubyElement [ candidates . size ( ) ] ) ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , getShell ( ) , getDialogTitle ( ) , ActionMessages . SelectionConverter_codeResolve_failed ) ; } catch ( InterruptedException e ) { } } public void run ( IStructuredSelection selection ) { if ( selection . size ( ) != ) return ; Object input = selection . getFirstElement ( ) ; if ( ! ( input instanceof IRubyElement ) ) { IStatus status = createStatus ( ActionMessages . OpenTypeHierarchyAction_messages_no_ruby_element ) ; ErrorDialog . openError ( getShell ( ) , getDialogTitle ( ) , ActionMessages . OpenTypeHierarchyAction_messages_title , status ) ; return ; } IRubyElement element = ( IRubyElement ) input ; if ( ! ActionUtil . isProcessable ( getShell ( ) , element ) ) return ; List result = new ArrayList ( ) ; IStatus status = compileCandidates ( result , element ) ; if ( status . isOK ( ) ) { run ( ( IRubyElement [ ] ) result . toArray ( new IRubyElement [ result . size ( ) ] ) ) ; } else { ErrorDialog . openError ( getShell ( ) , getDialogTitle ( ) , ActionMessages . OpenTypeHierarchyAction_messages_title , status ) ; } } public void run ( IRubyElement [ ] elements ) { if ( elements . length == ) { getShell ( ) . getDisplay ( ) . beep ( ) ; return ; } OpenTypeHierarchyUtil . open ( elements , getSite ( ) . getWorkbenchWindow ( ) ) ; } private static String getDialogTitle ( ) { return ActionMessages . OpenTypeHierarchyAction_dialog_title ; } private static IStatus compileCandidates ( List result , IRubyElement elem ) { IStatus ok = new Status ( IStatus . OK , RubyPlugin . getPluginId ( ) , , "" , null ) ; try { switch ( elem . getElementType ( ) ) { case IRubyElement . METHOD : case IRubyElement . FIELD : case IRubyElement . TYPE : case IRubyElement . SOURCE_FOLDER_ROOT : case IRubyElement . RUBY_PROJECT : result . add ( elem ) ; return ok ; case IRubyElement . SOURCE_FOLDER : if ( ( ( ISourceFolder ) elem ) . containsRubyResources ( ) ) { result . add ( elem ) ; return ok ; } return createStatus ( ActionMessages . OpenTypeHierarchyAction_messages_no_ruby_resources ) ; case IRubyElement . IMPORT_DECLARATION : IImportDeclaration decl = ( IImportDeclaration ) elem ; elem = elem . getRubyProject ( ) . findType ( elem . getElementName ( ) ) ; if ( elem != null ) { result . add ( elem ) ; return ok ; } return createStatus ( ActionMessages . OpenTypeHierarchyAction_messages_unknown_import_decl ) ; case IRubyElement . SCRIPT : IRubyScript cu = ( IRubyScript ) elem ; IType [ ] types = cu . getTypes ( ) ; if ( types . length > ) { result . addAll ( Arrays . asList ( types ) ) ; return ok ; } return createStatus ( ActionMessages . OpenTypeHierarchyAction_messages_no_types ) ; } } catch ( RubyModelException e ) { return e . getStatus ( ) ; } return createStatus ( ActionMessages . OpenTypeHierarchyAction_messages_no_valid_ruby_element ) ; } private static IStatus createStatus ( String message ) { return new Status ( IStatus . INFO , RubyPlugin . getPluginId ( ) , IRubyStatusConstants . INTERNAL_ERROR , message , null ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . INewWizard ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . NewProjectAction ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . NewElementWizard ; import org . rubypeople . rdt . internal . ui . wizards . NewWizardMessages ; public abstract class AbstractOpenWizardAction extends Action { private Shell fShell ; private IStructuredSelection fSelection ; private IRubyElement fCreatedElement ; protected AbstractOpenWizardAction ( ) { fShell = null ; fSelection = null ; fCreatedElement = null ; } public void run ( ) { Shell shell = getShell ( ) ; if ( ! doCreateProjectFirstOnEmptyWorkspace ( shell ) ) { return ; } try { INewWizard wizard = createWizard ( ) ; wizard . init ( PlatformUI . getWorkbench ( ) , getSelection ( ) ) ; WizardDialog dialog = new WizardDialog ( shell , wizard ) ; if ( shell != null ) { PixelConverter converter = new PixelConverter ( shell ) ; dialog . setMinimumPageSize ( converter . convertWidthInCharsToPixels ( ) , converter . convertHeightInCharsToPixels ( ) ) ; } dialog . create ( ) ; int res = dialog . open ( ) ; if ( res == Window . OK && wizard instanceof NewElementWizard ) { fCreatedElement = ( ( NewElementWizard ) wizard ) . getCreatedElement ( ) ; } notifyResult ( res == Window . OK ) ; } catch ( CoreException e ) { String title = NewWizardMessages . AbstractOpenWizardAction_createerror_title ; String message = NewWizardMessages . AbstractOpenWizardAction_createerror_message ; ExceptionHandler . handle ( e , shell , title , message ) ; } } abstract protected INewWizard createWizard ( ) throws CoreException ; protected IStructuredSelection getSelection ( ) { if ( fSelection == null ) { return evaluateCurrentSelection ( ) ; } return fSelection ; } private IStructuredSelection evaluateCurrentSelection ( ) { IWorkbenchWindow window = RubyPlugin . getActiveWorkbenchWindow ( ) ; if ( window != null ) { ISelection selection = window . getSelectionService ( ) . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { return ( IStructuredSelection ) selection ; } } return StructuredSelection . EMPTY ; } public void setSelection ( IStructuredSelection selection ) { fSelection = selection ; } protected Shell getShell ( ) { if ( fShell == null ) { return RubyPlugin . getActiveWorkbenchShell ( ) ; } return fShell ; } public void setShell ( Shell shell ) { fShell = shell ; } protected boolean doCreateProjectFirstOnEmptyWorkspace ( Shell shell ) { IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; if ( workspaceRoot . getProjects ( ) . length == ) { String title = NewWizardMessages . AbstractOpenWizardAction_noproject_title ; String message = NewWizardMessages . AbstractOpenWizardAction_noproject_message ; if ( MessageDialog . openQuestion ( shell , title , message ) ) { new NewProjectAction ( ) . run ( ) ; return workspaceRoot . getProjects ( ) . length != ; } return false ; } return true ; } public IRubyElement getCreatedElement ( ) { return fCreatedElement ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . actions . ActionContext ; import org . eclipse . ui . actions . ActionGroup ; public class NavigateActionGroup extends ActionGroup { private OpenEditorActionGroup fOpenEditorActionGroup ; private OpenViewActionGroup fOpenViewActionGroup ; public NavigateActionGroup ( IViewPart part ) { fOpenEditorActionGroup = new OpenEditorActionGroup ( part ) ; fOpenViewActionGroup = new OpenViewActionGroup ( part ) ; } public IAction getOpenAction ( ) { return fOpenEditorActionGroup . getOpenAction ( ) ; } public void dispose ( ) { super . dispose ( ) ; fOpenEditorActionGroup . dispose ( ) ; fOpenViewActionGroup . dispose ( ) ; } public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; fOpenEditorActionGroup . fillActionBars ( actionBars ) ; fOpenViewActionGroup . fillActionBars ( actionBars ) ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; fOpenEditorActionGroup . fillContextMenu ( menu ) ; fOpenViewActionGroup . fillContextMenu ( menu ) ; } public void setContext ( ActionContext context ) { super . setContext ( context ) ; fOpenEditorActionGroup . setContext ( context ) ; fOpenViewActionGroup . setContext ( context ) ; } public void updateActionBars ( ) { super . updateActionBars ( ) ; fOpenEditorActionGroup . updateActionBars ( ) ; fOpenViewActionGroup . updateActionBars ( ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . util . Assert ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; public class WorkingSetFindAction extends FindAction { private FindAction fAction ; public WorkingSetFindAction ( IWorkbenchSite site , FindAction action , String workingSetName ) { super ( site ) ; init ( action , workingSetName ) ; } public WorkingSetFindAction ( RubyEditor editor , FindAction action , String workingSetName ) { super ( editor ) ; init ( action , workingSetName ) ; } Class [ ] getValidTypes ( ) { return null ; } void init ( ) { } private void init ( FindAction action , String workingSetName ) { Assert . isNotNull ( action ) ; fAction = action ; setText ( workingSetName ) ; setImageDescriptor ( action . getImageDescriptor ( ) ) ; setToolTipText ( action . getToolTipText ( ) ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . WORKING_SET_FIND_ACTION ) ; } public void run ( IRubyElement element ) { fAction . run ( element ) ; } boolean canOperateOn ( IRubyElement element ) { return fAction . canOperateOn ( element ) ; } int getLimitTo ( ) { return - ; } String getOperationUnavailableMessage ( ) { return fAction . getOperationUnavailableMessage ( ) ; } } package org . rubypeople . rdt . ui . actions ; import java . util . Map ; import org . eclipse . core . filebuffers . FileBuffers ; import org . eclipse . core . filebuffers . ITextFileBufferManager ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . formatter . Indents ; import org . rubypeople . rdt . internal . corext . util . RubyModelUtil ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public class SurroundWithBeginRescueAction extends SelectionDispatchAction { public static final String SURROUND_WTH_BEGIN_RESCUE = "" ; private RubyEditor fEditor ; public SurroundWithBeginRescueAction ( RubyEditor editor ) { super ( editor . getEditorSite ( ) ) ; setText ( ActionMessages . SurroundWithBeginRescueAction_label ) ; fEditor = editor ; setEnabled ( ( fEditor != null && SelectionConverter . getInputAsRubyScript ( fEditor ) != null ) ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . SURROUND_WITH_TRY_CATCH_ACTION ) ; } public void run ( ITextSelection selection ) { try { createChange ( selection , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { ExceptionHandler . handle ( e , getDialogTitle ( ) , ActionMessages . SurroundWithBeginRescueAction_error ) ; } } private static String getDialogTitle ( ) { return ActionMessages . SurroundWithBeginRescueAction_dialog_title ; } private IFile getFile ( ) { IRubyScript cu = getRubyScript ( ) ; return ( IFile ) RubyModelUtil . toOriginal ( cu ) . getResource ( ) ; } private IRubyScript getRubyScript ( ) { return SelectionConverter . getInputAsRubyScript ( fEditor ) ; } public void createChange ( ITextSelection selection , IProgressMonitor pm ) throws CoreException { final String NN = "" ; if ( pm == null ) pm = new NullProgressMonitor ( ) ; pm . beginTask ( NN , ) ; IPath path = getFile ( ) . getFullPath ( ) ; ITextFileBufferManager bufferManager = FileBuffers . getTextFileBufferManager ( ) ; try { bufferManager . connect ( path , new SubProgressMonitor ( pm , ) ) ; IDocument document = bufferManager . getTextFileBuffer ( path ) . getDocument ( ) ; String text = createBeginRescueBlock ( document , selection ) ; document . replace ( selection . getOffset ( ) , selection . getLength ( ) , text ) ; } catch ( BadLocationException e ) { throw new CoreException ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IStatus . ERROR , e . getMessage ( ) , e ) ) ; } finally { bufferManager . disconnect ( path , new SubProgressMonitor ( pm , ) ) ; pm . done ( ) ; } } private String createBeginRescueBlock ( IDocument document , ITextSelection selection ) throws BadLocationException , RubyModelException { String originalText = selection . getText ( ) ; String lineDelimiter = document . getLineDelimiter ( ) ; Map options = getRubyScript ( ) . getRubyProject ( ) . getOptions ( true ) ; int lineNumber = selection . getStartLine ( ) ; String line = document . get ( document . getLineOffset ( lineNumber ) , document . getLineLength ( lineNumber ) ) ; int indentationUnits = Indents . measureIndentUnits ( line , Indents . getTabWidth ( options ) , Indents . getIndentWidth ( options ) ) ; StringBuffer text = new StringBuffer ( ) ; text . append ( "" ) ; text . append ( lineDelimiter ) ; text . append ( Indents . createIndentString ( indentationUnits + , options ) ) ; text . append ( originalText ) ; text . append ( lineDelimiter ) ; text . append ( Indents . createIndentString ( indentationUnits , options ) ) ; text . append ( "" ) ; text . append ( lineDelimiter ) ; text . append ( Indents . createIndentString ( indentationUnits + , options ) ) ; text . append ( "" ) ; text . append ( lineDelimiter ) ; text . append ( Indents . createIndentString ( indentationUnits , options ) ) ; text . append ( "" ) ; text . append ( lineDelimiter ) ; text . append ( Indents . createIndentString ( indentationUnits , options ) ) ; return text . toString ( ) ; } public void selectionChanged ( ITextSelection selection ) { setEnabled ( selection . getLength ( ) > && ( fEditor != null && SelectionConverter . getInputAsRubyScript ( fEditor ) != null ) ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class FindDeclarationsInWorkingSetAction extends FindDeclarationsAction { private IWorkingSet [ ] fWorkingSet ; public FindDeclarationsInWorkingSetAction ( IWorkbenchSite site ) { this ( site , null ) ; } public FindDeclarationsInWorkingSetAction ( IWorkbenchSite site , IWorkingSet [ ] workingSets ) { super ( site ) ; fWorkingSet = workingSets ; } public FindDeclarationsInWorkingSetAction ( RubyEditor editor ) { this ( editor , null ) ; } public FindDeclarationsInWorkingSetAction ( RubyEditor editor , IWorkingSet [ ] workingSets ) { super ( editor ) ; fWorkingSet = workingSets ; } void init ( ) { setText ( SearchMessages . Search_FindDeclarationsInWorkingSetAction_label ) ; setToolTipText ( SearchMessages . Search_FindDeclarationsInWorkingSetAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_DECL ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_DECLARATIONS_IN_WORKING_SET_ACTION ) ; } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; IWorkingSet [ ] workingSets = fWorkingSet ; if ( fWorkingSet == null ) { workingSets = factory . queryWorkingSets ( ) ; if ( workingSets == null ) return null ; } SearchUtil . updateLRUWorkingSets ( workingSets ) ; IRubySearchScope scope = factory . createRubySearchScope ( workingSets , true ) ; String description = factory . getWorkingSetScopeDescription ( workingSets , true ) ; return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class FindReferencesInProjectAction extends FindReferencesAction { public FindReferencesInProjectAction ( IWorkbenchSite site ) { super ( site ) ; } public FindReferencesInProjectAction ( RubyEditor editor ) { super ( editor ) ; } Class [ ] getValidTypes ( ) { return new Class [ ] { IField . class , IMethod . class , IType . class , IRubyScript . class , IImportDeclaration . class , ISourceFolder . class } ; } void init ( ) { setText ( SearchMessages . Search_FindReferencesInProjectAction_label ) ; setToolTipText ( SearchMessages . Search_FindReferencesInProjectAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_REFERENCES_IN_PROJECT_ACTION ) ; } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; RubyEditor editor = getEditor ( ) ; IRubySearchScope scope ; String description ; boolean isInsideJRE = factory . isInsideRubyVMLibraries ( element ) ; if ( editor != null ) { scope = factory . createRubyProjectSearchScope ( editor . getEditorInput ( ) , isInsideJRE ) ; description = factory . getProjectScopeDescription ( editor . getEditorInput ( ) , isInsideJRE ) ; } else { scope = factory . createRubyProjectSearchScope ( element . getRubyProject ( ) , isInsideJRE ) ; description = factory . getProjectScopeDescription ( element . getRubyProject ( ) , isInsideJRE ) ; } return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } } package org . rubypeople . rdt . ui . actions ; import java . util . Iterator ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; public class WriteReferencesSearchGroup extends ActionGroup { private static final String MENU_TEXT = SearchMessages . group_writeReferences ; private IWorkbenchSite fSite ; private RubyEditor fEditor ; private IActionBars fActionBars ; private String fGroupId ; private FindWriteReferencesAction fFindWriteReferencesAction ; private FindWriteReferencesInProjectAction fFindWriteReferencesInProjectAction ; private FindWriteReferencesInWorkingSetAction fFindWriteReferencesInWorkingSetAction ; public WriteReferencesSearchGroup ( IWorkbenchSite site ) { fSite = site ; fGroupId = IContextMenuConstants . GROUP_SEARCH ; fFindWriteReferencesAction = new FindWriteReferencesAction ( site ) ; fFindWriteReferencesAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_WRITE_ACCESS_IN_WORKSPACE ) ; fFindWriteReferencesInProjectAction = new FindWriteReferencesInProjectAction ( site ) ; fFindWriteReferencesInProjectAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_WRITE_ACCESS_IN_PROJECT ) ; fFindWriteReferencesInWorkingSetAction = new FindWriteReferencesInWorkingSetAction ( site ) ; fFindWriteReferencesInWorkingSetAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_WRITE_ACCESS_IN_WORKING_SET ) ; ISelectionProvider provider = fSite . getSelectionProvider ( ) ; ISelection selection = provider . getSelection ( ) ; registerAction ( fFindWriteReferencesAction , provider , selection ) ; registerAction ( fFindWriteReferencesInProjectAction , provider , selection ) ; registerAction ( fFindWriteReferencesInWorkingSetAction , provider , selection ) ; } public WriteReferencesSearchGroup ( RubyEditor editor ) { fEditor = editor ; fSite = fEditor . getSite ( ) ; fGroupId = ITextEditorActionConstants . GROUP_FIND ; fFindWriteReferencesAction = new FindWriteReferencesAction ( fEditor ) ; fFindWriteReferencesAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_WRITE_ACCESS_IN_WORKSPACE ) ; fEditor . setAction ( "" , fFindWriteReferencesAction ) ; fFindWriteReferencesInProjectAction = new FindWriteReferencesInProjectAction ( fEditor ) ; fFindWriteReferencesInProjectAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_WRITE_ACCESS_IN_PROJECT ) ; fEditor . setAction ( "" , fFindWriteReferencesInProjectAction ) ; fFindWriteReferencesInWorkingSetAction = new FindWriteReferencesInWorkingSetAction ( fEditor ) ; fFindWriteReferencesInWorkingSetAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_WRITE_ACCESS_IN_WORKING_SET ) ; fEditor . setAction ( "" , fFindWriteReferencesInWorkingSetAction ) ; } private void registerAction ( SelectionDispatchAction action , ISelectionProvider provider , ISelection selection ) { action . update ( selection ) ; provider . addSelectionChangedListener ( action ) ; } private void addAction ( IAction action , IMenuManager manager ) { if ( action . isEnabled ( ) ) { manager . add ( action ) ; } } private void addWorkingSetAction ( IWorkingSet [ ] workingSets , IMenuManager manager ) { FindAction action ; if ( fEditor != null ) action = new WorkingSetFindAction ( fEditor , new FindWriteReferencesInWorkingSetAction ( fEditor , workingSets ) , SearchUtil . toString ( workingSets ) ) ; else action = new WorkingSetFindAction ( fSite , new FindWriteReferencesInWorkingSetAction ( fSite , workingSets ) , SearchUtil . toString ( workingSets ) ) ; action . update ( getContext ( ) . getSelection ( ) ) ; addAction ( action , manager ) ; } public void fillContextMenu ( IMenuManager manager ) { MenuManager javaSearchMM = new MenuManager ( MENU_TEXT , IContextMenuConstants . GROUP_SEARCH ) ; addAction ( fFindWriteReferencesAction , javaSearchMM ) ; addAction ( fFindWriteReferencesInProjectAction , javaSearchMM ) ; javaSearchMM . add ( new Separator ( ) ) ; Iterator iter = SearchUtil . getLRUWorkingSets ( ) . sortedIterator ( ) ; while ( iter . hasNext ( ) ) { addWorkingSetAction ( ( IWorkingSet [ ] ) iter . next ( ) , javaSearchMM ) ; } addAction ( fFindWriteReferencesInWorkingSetAction , javaSearchMM ) ; if ( ! javaSearchMM . isEmpty ( ) ) manager . appendToGroup ( fGroupId , javaSearchMM ) ; } public void fillActionBars ( IActionBars actionBars ) { Assert . isNotNull ( actionBars ) ; super . fillActionBars ( actionBars ) ; fActionBars = actionBars ; updateGlobalActionHandlers ( ) ; } public void dispose ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; if ( provider != null ) { disposeAction ( fFindWriteReferencesAction , provider ) ; disposeAction ( fFindWriteReferencesInProjectAction , provider ) ; disposeAction ( fFindWriteReferencesInWorkingSetAction , provider ) ; } fFindWriteReferencesAction = null ; fFindWriteReferencesInProjectAction = null ; fFindWriteReferencesInWorkingSetAction = null ; updateGlobalActionHandlers ( ) ; super . dispose ( ) ; } private void updateGlobalActionHandlers ( ) { if ( fActionBars != null ) { fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_WRITE_ACCESS_IN_WORKSPACE , fFindWriteReferencesAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_WRITE_ACCESS_IN_PROJECT , fFindWriteReferencesInProjectAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_WRITE_ACCESS_IN_WORKING_SET , fFindWriteReferencesInWorkingSetAction ) ; } } private void disposeAction ( ISelectionChangedListener action , ISelectionProvider provider ) { if ( action != null ) provider . removeSelectionChangedListener ( action ) ; } } package org . rubypeople . rdt . ui . actions ; import java . util . Iterator ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; public class ReferencesSearchGroup extends ActionGroup { private static final String MENU_TEXT = SearchMessages . group_references ; private IWorkbenchSite fSite ; private RubyEditor fEditor ; private IActionBars fActionBars ; private String fGroupId ; private FindReferencesAction fFindReferencesAction ; private FindReferencesInProjectAction fFindReferencesInProjectAction ; private FindReferencesInHierarchyAction fFindReferencesInHierarchyAction ; private FindReferencesInWorkingSetAction fFindReferencesInWorkingSetAction ; public ReferencesSearchGroup ( IWorkbenchSite site ) { fSite = site ; fGroupId = IContextMenuConstants . GROUP_SEARCH ; fFindReferencesAction = new FindReferencesAction ( site ) ; fFindReferencesAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_REFERENCES_IN_WORKSPACE ) ; fFindReferencesInProjectAction = new FindReferencesInProjectAction ( site ) ; fFindReferencesInProjectAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_REFERENCES_IN_PROJECT ) ; fFindReferencesInHierarchyAction = new FindReferencesInHierarchyAction ( site ) ; fFindReferencesInHierarchyAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_REFERENCES_IN_HIERARCHY ) ; fFindReferencesInWorkingSetAction = new FindReferencesInWorkingSetAction ( site ) ; fFindReferencesInWorkingSetAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_REFERENCES_IN_WORKING_SET ) ; ISelectionProvider provider = fSite . getSelectionProvider ( ) ; ISelection selection = provider . getSelection ( ) ; registerAction ( fFindReferencesAction , provider , selection ) ; registerAction ( fFindReferencesInProjectAction , provider , selection ) ; registerAction ( fFindReferencesInHierarchyAction , provider , selection ) ; registerAction ( fFindReferencesInWorkingSetAction , provider , selection ) ; } public ReferencesSearchGroup ( RubyEditor editor ) { Assert . isNotNull ( editor ) ; fEditor = editor ; fSite = fEditor . getSite ( ) ; fGroupId = ITextEditorActionConstants . GROUP_FIND ; fFindReferencesAction = new FindReferencesAction ( editor ) ; fFindReferencesAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_REFERENCES_IN_WORKSPACE ) ; fEditor . setAction ( "" , fFindReferencesAction ) ; fFindReferencesInProjectAction = new FindReferencesInProjectAction ( fEditor ) ; fFindReferencesInProjectAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_REFERENCES_IN_PROJECT ) ; fEditor . setAction ( "" , fFindReferencesInProjectAction ) ; fFindReferencesInHierarchyAction = new FindReferencesInHierarchyAction ( fEditor ) ; fFindReferencesInHierarchyAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_REFERENCES_IN_HIERARCHY ) ; fEditor . setAction ( "" , fFindReferencesInHierarchyAction ) ; fFindReferencesInWorkingSetAction = new FindReferencesInWorkingSetAction ( fEditor ) ; fFindReferencesInWorkingSetAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_REFERENCES_IN_WORKING_SET ) ; fEditor . setAction ( "" , fFindReferencesInWorkingSetAction ) ; } private void registerAction ( SelectionDispatchAction action , ISelectionProvider provider , ISelection selection ) { action . update ( selection ) ; provider . addSelectionChangedListener ( action ) ; } protected String getName ( ) { return MENU_TEXT ; } public void fillActionBars ( IActionBars actionBars ) { Assert . isNotNull ( actionBars ) ; super . fillActionBars ( actionBars ) ; fActionBars = actionBars ; updateGlobalActionHandlers ( ) ; } private void addAction ( IAction action , IMenuManager manager ) { if ( action . isEnabled ( ) ) { manager . add ( action ) ; } } private void addWorkingSetAction ( IWorkingSet [ ] workingSets , IMenuManager manager ) { FindAction action ; if ( fEditor != null ) action = new WorkingSetFindAction ( fEditor , new FindReferencesInWorkingSetAction ( fEditor , workingSets ) , SearchUtil . toString ( workingSets ) ) ; else action = new WorkingSetFindAction ( fSite , new FindReferencesInWorkingSetAction ( fSite , workingSets ) , SearchUtil . toString ( workingSets ) ) ; action . update ( getContext ( ) . getSelection ( ) ) ; addAction ( action , manager ) ; } public void fillContextMenu ( IMenuManager manager ) { MenuManager javaSearchMM = new MenuManager ( getName ( ) , IContextMenuConstants . GROUP_SEARCH ) ; addAction ( fFindReferencesAction , javaSearchMM ) ; addAction ( fFindReferencesInProjectAction , javaSearchMM ) ; addAction ( fFindReferencesInHierarchyAction , javaSearchMM ) ; javaSearchMM . add ( new Separator ( ) ) ; Iterator iter = SearchUtil . getLRUWorkingSets ( ) . sortedIterator ( ) ; while ( iter . hasNext ( ) ) { addWorkingSetAction ( ( IWorkingSet [ ] ) iter . next ( ) , javaSearchMM ) ; } addAction ( fFindReferencesInWorkingSetAction , javaSearchMM ) ; if ( ! javaSearchMM . isEmpty ( ) ) manager . appendToGroup ( fGroupId , javaSearchMM ) ; } public void dispose ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; if ( provider != null ) { disposeAction ( fFindReferencesAction , provider ) ; disposeAction ( fFindReferencesInProjectAction , provider ) ; disposeAction ( fFindReferencesInHierarchyAction , provider ) ; disposeAction ( fFindReferencesInWorkingSetAction , provider ) ; } fFindReferencesAction = null ; fFindReferencesInProjectAction = null ; fFindReferencesInHierarchyAction = null ; fFindReferencesInWorkingSetAction = null ; updateGlobalActionHandlers ( ) ; super . dispose ( ) ; } private void updateGlobalActionHandlers ( ) { if ( fActionBars != null ) { fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_REFERENCES_IN_WORKSPACE , fFindReferencesAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_REFERENCES_IN_PROJECT , fFindReferencesInProjectAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_REFERENCES_IN_HIERARCHY , fFindReferencesInHierarchyAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_REFERENCES_IN_WORKING_SET , fFindReferencesInWorkingSetAction ) ; } } private void disposeAction ( ISelectionChangedListener action , ISelectionProvider provider ) { if ( action != null ) provider . removeSelectionChangedListener ( action ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . keys . IBindingService ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; public class OccurrencesSearchGroup extends ActionGroup { private IWorkbenchSite fSite ; private RubyEditor fEditor ; private IActionBars fActionBars ; private String fGroupId ; private FindOccurrencesInFileAction fOccurrencesInFileAction ; public OccurrencesSearchGroup ( IWorkbenchSite site ) { fSite = site ; fGroupId = IContextMenuConstants . GROUP_SEARCH ; fOccurrencesInFileAction = new FindOccurrencesInFileAction ( site ) ; fOccurrencesInFileAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_OCCURRENCES_IN_FILE ) ; fOccurrencesInFileAction . setText ( SearchMessages . Search_FindOccurrencesInFile_shortLabel ) ; ISelectionProvider provider = fSite . getSelectionProvider ( ) ; ISelection selection = provider . getSelection ( ) ; registerAction ( fOccurrencesInFileAction , provider , selection ) ; } public OccurrencesSearchGroup ( RubyEditor editor ) { fEditor = editor ; fSite = fEditor . getSite ( ) ; fGroupId = ITextEditorActionConstants . GROUP_FIND ; fOccurrencesInFileAction = new FindOccurrencesInFileAction ( fEditor ) ; fOccurrencesInFileAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_OCCURRENCES_IN_FILE ) ; fOccurrencesInFileAction . setText ( SearchMessages . Search_FindOccurrencesInFile_shortLabel ) ; fEditor . setAction ( "" , fOccurrencesInFileAction ) ; } private void registerAction ( SelectionDispatchAction action , ISelectionProvider provider , ISelection selection ) { action . update ( selection ) ; provider . addSelectionChangedListener ( action ) ; } private IAction [ ] getActions ( ) { IAction [ ] actions = new IAction [ ] ; actions [ ] = fOccurrencesInFileAction ; return actions ; } public void fillContextMenu ( IMenuManager manager ) { String menuText = SearchMessages . group_occurrences ; String shortcut = getShortcutString ( ) ; if ( shortcut != null ) { String [ ] args = new String [ ] { menuText , shortcut } ; menuText = Messages . format ( ActionMessages . QuickMenuAction_menuTextWithShortcut , args ) ; } MenuManager javaSearchMM = new MenuManager ( menuText , IContextMenuConstants . GROUP_SEARCH ) ; IAction [ ] actions = getActions ( ) ; for ( int i = ; i < actions . length ; i ++ ) { IAction action = actions [ i ] ; if ( action . isEnabled ( ) ) javaSearchMM . add ( action ) ; } if ( ! javaSearchMM . isEmpty ( ) ) manager . appendToGroup ( fGroupId , javaSearchMM ) ; } private String getShortcutString ( ) { IBindingService bindingService = ( IBindingService ) PlatformUI . getWorkbench ( ) . getAdapter ( IBindingService . class ) ; if ( bindingService == null ) return null ; return bindingService . getBestActiveBindingFormattedFor ( IRubyEditorActionDefinitionIds . SEARCH_OCCURRENCES_IN_FILE_QUICK_MENU ) ; } public void fillActionBars ( IActionBars actionBars ) { Assert . isNotNull ( actionBars ) ; super . fillActionBars ( actionBars ) ; fActionBars = actionBars ; updateGlobalActionHandlers ( ) ; } public void dispose ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; if ( provider != null ) { disposeAction ( fOccurrencesInFileAction , provider ) ; } super . dispose ( ) ; fOccurrencesInFileAction = null ; updateGlobalActionHandlers ( ) ; } private void updateGlobalActionHandlers ( ) { if ( fActionBars != null ) { fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_OCCURRENCES_IN_FILE , fOccurrencesInFileAction ) ; } } private void disposeAction ( ISelectionChangedListener action , ISelectionProvider provider ) { if ( action != null ) provider . removeSelectionChangedListener ( action ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class FindReadReferencesInProjectAction extends FindReadReferencesAction { public FindReadReferencesInProjectAction ( IWorkbenchSite site ) { super ( site ) ; } public FindReadReferencesInProjectAction ( RubyEditor editor ) { super ( editor ) ; } void init ( ) { setText ( SearchMessages . Search_FindReadReferencesInProjectAction_label ) ; setToolTipText ( SearchMessages . Search_FindReadReferencesInProjectAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_READ_REFERENCES_IN_PROJECT_ACTION ) ; } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; RubyEditor editor = getEditor ( ) ; IRubySearchScope scope ; String description ; boolean isInsideJRE = factory . isInsideRubyVMLibraries ( element ) ; if ( editor != null ) { scope = factory . createRubyProjectSearchScope ( editor . getEditorInput ( ) , isInsideJRE ) ; description = factory . getProjectScopeDescription ( editor . getEditorInput ( ) , isInsideJRE ) ; } else { scope = factory . createRubyProjectSearchScope ( element . getRubyProject ( ) , isInsideJRE ) ; description = factory . getProjectScopeDescription ( element . getRubyProject ( ) , isInsideJRE ) ; } return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; public class FindWriteReferencesAction extends FindReferencesAction { public FindWriteReferencesAction ( IWorkbenchSite site ) { super ( site ) ; } public FindWriteReferencesAction ( RubyEditor editor ) { super ( editor ) ; } Class [ ] getValidTypes ( ) { return new Class [ ] { IField . class } ; } void init ( ) { setText ( SearchMessages . Search_FindWriteReferencesAction_label ) ; setToolTipText ( SearchMessages . Search_FindWriteReferencesAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION ) ; } int getLimitTo ( ) { return IRubySearchConstants . WRITE_ACCESSES ; } String getOperationUnavailableMessage ( ) { return SearchMessages . RubyElementAction_operationUnavailable_field ; } } package org . rubypeople . rdt . ui . actions ; public interface RubyActionIds { public static final String COMMENT = "" ; public static final String UNCOMMENT = "" ; public static final String TOGGLE_COMMENT = "" ; public static final String FORMAT = "" ; } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class FindDeclarationsInProjectAction extends FindDeclarationsAction { public FindDeclarationsInProjectAction ( IWorkbenchSite site ) { super ( site ) ; } public FindDeclarationsInProjectAction ( RubyEditor editor ) { super ( editor ) ; } void init ( ) { setText ( SearchMessages . Search_FindDeclarationsInProjectAction_label ) ; setToolTipText ( SearchMessages . Search_FindDeclarationsInProjectAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_DECL ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_DECLARATIONS_IN_PROJECT_ACTION ) ; } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; RubyEditor editor = getEditor ( ) ; IRubySearchScope scope ; String description ; boolean isInsideJRE = true ; if ( editor != null ) { scope = factory . createRubyProjectSearchScope ( editor . getEditorInput ( ) , isInsideJRE ) ; description = factory . getProjectScopeDescription ( editor . getEditorInput ( ) , isInsideJRE ) ; } else { scope = factory . createRubyProjectSearchScope ( element . getRubyProject ( ) , isInsideJRE ) ; description = factory . getProjectScopeDescription ( element . getRubyProject ( ) , isInsideJRE ) ; } return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; public interface IRubyEditorActionDefinitionIds extends ITextEditorActionDefinitionIds { public static final String COMMENT = "" ; public static final String CONTENT_ASSIST_PROPOSALS = "" ; public static final String UNCOMMENT = "" ; public static final String FORMAT = "" ; public static final String TOGGLE_COMMENT = "" ; public static final String SHOW_RDOC = "" ; public static final String SURROUND_WITH_BEGIN_RESCUE = "" ; public static final String GOTO_MATCHING_BRACKET = "" ; public static final String OPEN_EDITOR = "" ; public static final String FOLDING_COLLAPSE_MEMBERS = "" ; public static final String FOLDING_COLLAPSE_COMMENTS = "" ; public static final String SEARCH_REFERENCES_IN_WORKSPACE = "" ; public static final String SEARCH_REFERENCES_IN_PROJECT = "" ; public static final String SEARCH_REFERENCES_IN_HIERARCHY = "" ; public static final String SEARCH_REFERENCES_IN_WORKING_SET = "" ; public static final String SEARCH_READ_ACCESS_IN_WORKSPACE = "" ; public static final String SEARCH_READ_ACCESS_IN_PROJECT = "" ; public static final String SEARCH_READ_ACCESS_IN_WORKING_SET = "" ; public static final String SEARCH_OCCURRENCES_IN_FILE_QUICK_MENU = "" ; public static final String SEARCH_OCCURRENCES_IN_FILE = "" ; public static final String SEARCH_WRITE_ACCESS_IN_WORKSPACE = "" ; public static final String SEARCH_WRITE_ACCESS_IN_PROJECT = "" ; public static final String SEARCH_WRITE_ACCESS_IN_WORKING_SET = "" ; public static final String SEARCH_DECLARATIONS_IN_WORKSPACE = "" ; public static final String SEARCH_DECLARATIONS_IN_PROJECTS = "" ; public static final String SEARCH_DECLARATIONS_IN_WORKING_SET = "" ; public static final String SHOW_OUTLINE = "" ; public static final String OPEN_STRUCTURE = "" ; public static final String OPEN_HIERARCHY = "" ; public static final String OPEN_TYPE_HIERARCHY = "" ; public static final String OPEN_CALL_HIERARCHY = "" ; public static final String SHOW_IN_RUBY_RESOURCES_VIEW = "" ; } package org . rubypeople . rdt . ui . actions ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . SWTError ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . FileTransfer ; import org . eclipse . swt . dnd . TextTransfer ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . SelectionListenerAction ; import org . eclipse . ui . internal . views . navigator . ResourceNavigatorMessages ; import org . eclipse . ui . part . ResourceTransfer ; class CopyAction extends SelectionListenerAction { public static final String ID = PlatformUI . PLUGIN_ID + "" ; private Shell shell ; private Clipboard clipboard ; private PasteAction pasteAction ; public CopyAction ( Shell shell , Clipboard clipboard ) { super ( ResourceNavigatorMessages . CopyAction_title ) ; Assert . isNotNull ( shell ) ; Assert . isNotNull ( clipboard ) ; this . shell = shell ; this . clipboard = clipboard ; setToolTipText ( ResourceNavigatorMessages . CopyAction_toolTip ) ; setId ( CopyAction . ID ) ; } public CopyAction ( Shell shell , Clipboard clipboard , PasteAction pasteAction ) { this ( shell , clipboard ) ; this . pasteAction = pasteAction ; } public void run ( ) { List selectedResources = getSelectedResources ( ) ; IResource [ ] resources = ( IResource [ ] ) selectedResources . toArray ( new IResource [ selectedResources . size ( ) ] ) ; final int length = resources . length ; int actualLength = ; String [ ] fileNames = new String [ length ] ; StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < length ; i ++ ) { IPath location = resources [ i ] . getLocation ( ) ; if ( location != null ) { fileNames [ actualLength ++ ] = location . toOSString ( ) ; } if ( i > ) { buf . append ( "" ) ; } buf . append ( resources [ i ] . getName ( ) ) ; } if ( actualLength < length ) { String [ ] tempFileNames = fileNames ; fileNames = new String [ actualLength ] ; for ( int i = ; i < actualLength ; i ++ ) { fileNames [ i ] = tempFileNames [ i ] ; } } setClipboard ( resources , fileNames , buf . toString ( ) ) ; if ( pasteAction != null && pasteAction . getStructuredSelection ( ) != null ) { pasteAction . selectionChanged ( pasteAction . getStructuredSelection ( ) ) ; } } private void setClipboard ( IResource [ ] resources , String [ ] fileNames , String names ) { try { if ( fileNames . length > ) { clipboard . setContents ( new Object [ ] { resources , fileNames , names } , new Transfer [ ] { ResourceTransfer . getInstance ( ) , FileTransfer . getInstance ( ) , TextTransfer . getInstance ( ) } ) ; } else { clipboard . setContents ( new Object [ ] { resources , names } , new Transfer [ ] { ResourceTransfer . getInstance ( ) , TextTransfer . getInstance ( ) } ) ; } } catch ( SWTError e ) { if ( e . code != DND . ERROR_CANNOT_SET_CLIPBOARD ) { throw e ; } if ( MessageDialog . openQuestion ( shell , ResourceNavigatorMessages . CopyToClipboardProblemDialog_title , ResourceNavigatorMessages . CopyToClipboardProblemDialog_message ) ) { setClipboard ( resources , fileNames , names ) ; } } } protected boolean updateSelection ( IStructuredSelection selection ) { if ( ! super . updateSelection ( selection ) ) { return false ; } if ( getSelectedNonResources ( ) . size ( ) > ) { return false ; } List selectedResources = getSelectedResources ( ) ; if ( selectedResources . size ( ) == ) { return false ; } boolean projSelected = selectionIsOfType ( IResource . PROJECT ) ; boolean fileFoldersSelected = selectionIsOfType ( IResource . FILE | IResource . FOLDER ) ; if ( ! projSelected && ! fileFoldersSelected ) { return false ; } if ( projSelected && fileFoldersSelected ) { return false ; } IContainer firstParent = ( ( IResource ) selectedResources . get ( ) ) . getParent ( ) ; if ( firstParent == null ) { return false ; } Iterator resourcesEnum = selectedResources . iterator ( ) ; while ( resourcesEnum . hasNext ( ) ) { IResource currentResource = ( IResource ) resourcesEnum . next ( ) ; if ( ! currentResource . getParent ( ) . equals ( firstParent ) ) { return false ; } } return true ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class FindWriteReferencesInProjectAction extends FindWriteReferencesAction { public FindWriteReferencesInProjectAction ( IWorkbenchSite site ) { super ( site ) ; } public FindWriteReferencesInProjectAction ( RubyEditor editor ) { super ( editor ) ; } void init ( ) { setText ( SearchMessages . Search_FindWriteReferencesInProjectAction_label ) ; setToolTipText ( SearchMessages . Search_FindWriteReferencesInProjectAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_WRITE_REFERENCES_IN_PROJECT_ACTION ) ; } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; RubyEditor editor = getEditor ( ) ; IRubySearchScope scope ; String description ; boolean isInsideJRE = factory . isInsideRubyVMLibraries ( element ) ; if ( editor != null ) { scope = factory . createRubyProjectSearchScope ( editor . getEditorInput ( ) , isInsideJRE ) ; description = factory . getProjectScopeDescription ( editor . getEditorInput ( ) , isInsideJRE ) ; } else { scope = factory . createRubyProjectSearchScope ( element . getRubyProject ( ) , isInsideJRE ) ; description = factory . getProjectScopeDescription ( element . getRubyProject ( ) , isInsideJRE ) ; } return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } } package org . rubypeople . rdt . ui . actions ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . dnd . FileTransfer ; import org . eclipse . swt . dnd . TransferData ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . CopyFilesAndFoldersOperation ; import org . eclipse . ui . actions . CopyProjectOperation ; import org . eclipse . ui . actions . SelectionListenerAction ; import org . eclipse . ui . internal . views . navigator . ResourceNavigatorMessages ; import org . eclipse . ui . part . ResourceTransfer ; class PasteAction extends SelectionListenerAction { public static final String ID = PlatformUI . PLUGIN_ID + "" ; private Shell shell ; private Clipboard clipboard ; public PasteAction ( Shell shell , Clipboard clipboard ) { super ( ResourceNavigatorMessages . PasteAction_title ) ; Assert . isNotNull ( shell ) ; Assert . isNotNull ( clipboard ) ; this . shell = shell ; this . clipboard = clipboard ; setToolTipText ( ResourceNavigatorMessages . PasteAction_toolTip ) ; setId ( PasteAction . ID ) ; } private IResource getTarget ( ) { List selectedResources = getSelectedResources ( ) ; for ( int i = ; i < selectedResources . size ( ) ; i ++ ) { IResource resource = ( IResource ) selectedResources . get ( i ) ; if ( resource instanceof IProject && ! ( ( IProject ) resource ) . isOpen ( ) ) { return null ; } if ( resource . getType ( ) == IResource . FILE ) { resource = resource . getParent ( ) ; } if ( resource != null ) { return resource ; } } return null ; } private boolean isLinked ( IResource [ ] resources ) { for ( int i = ; i < resources . length ; i ++ ) { if ( resources [ i ] . isLinked ( ) ) { return true ; } } return false ; } public void run ( ) { ResourceTransfer resTransfer = ResourceTransfer . getInstance ( ) ; IResource [ ] resourceData = ( IResource [ ] ) clipboard . getContents ( resTransfer ) ; if ( resourceData != null && resourceData . length > ) { if ( resourceData [ ] . getType ( ) == IResource . PROJECT ) { for ( int i = ; i < resourceData . length ; i ++ ) { CopyProjectOperation operation = new CopyProjectOperation ( this . shell ) ; operation . copyProject ( ( IProject ) resourceData [ i ] ) ; } } else { IContainer container = getContainer ( ) ; CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation ( this . shell ) ; operation . copyResources ( resourceData , container ) ; } return ; } FileTransfer fileTransfer = FileTransfer . getInstance ( ) ; String [ ] fileData = ( String [ ] ) clipboard . getContents ( fileTransfer ) ; if ( fileData != null ) { IContainer container = getContainer ( ) ; CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation ( this . shell ) ; operation . copyFiles ( fileData , container ) ; } } private IContainer getContainer ( ) { List selection = getSelectedResources ( ) ; if ( selection . get ( ) instanceof IFile ) { return ( ( IFile ) selection . get ( ) ) . getParent ( ) ; } else { return ( IContainer ) selection . get ( ) ; } } protected boolean updateSelection ( IStructuredSelection selection ) { if ( ! super . updateSelection ( selection ) ) { return false ; } final IResource [ ] [ ] clipboardData = new IResource [ ] [ ] ; shell . getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { ResourceTransfer resTransfer = ResourceTransfer . getInstance ( ) ; clipboardData [ ] = ( IResource [ ] ) clipboard . getContents ( resTransfer ) ; } } ) ; IResource [ ] resourceData = clipboardData [ ] ; boolean isProjectRes = resourceData != null && resourceData . length > && resourceData [ ] . getType ( ) == IResource . PROJECT ; if ( isProjectRes ) { for ( int i = ; i < resourceData . length ; i ++ ) { if ( resourceData [ i ] . getType ( ) != IResource . PROJECT || ( ( IProject ) resourceData [ i ] ) . isOpen ( ) == false ) { return false ; } } return true ; } if ( getSelectedNonResources ( ) . size ( ) > ) { return false ; } IResource targetResource = getTarget ( ) ; if ( targetResource == null ) { return false ; } List selectedResources = getSelectedResources ( ) ; if ( selectedResources . size ( ) > ) { for ( int i = ; i < selectedResources . size ( ) ; i ++ ) { IResource resource = ( IResource ) selectedResources . get ( i ) ; if ( resource . getType ( ) != IResource . FILE ) { return false ; } if ( ! targetResource . equals ( resource . getParent ( ) ) ) { return false ; } } } if ( resourceData != null ) { if ( isLinked ( resourceData ) && targetResource . getType ( ) != IResource . PROJECT && targetResource . getType ( ) != IResource . FOLDER ) { return false ; } if ( targetResource . getType ( ) == IResource . FOLDER ) { for ( int i = ; i < resourceData . length ; i ++ ) { if ( targetResource . equals ( resourceData [ i ] ) ) { return false ; } } } return true ; } TransferData [ ] transfers = clipboard . getAvailableTypes ( ) ; FileTransfer fileTransfer = FileTransfer . getInstance ( ) ; for ( int i = ; i < transfers . length ; i ++ ) { if ( fileTransfer . isSupportedType ( transfers [ i ] ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . actions . DeleteResourceAction ; import org . eclipse . ui . actions . MoveResourceAction ; import org . eclipse . ui . actions . RenameResourceAction ; import org . eclipse . ui . actions . SelectionListenerAction ; import org . eclipse . ui . navigator . ICommonMenuConstants ; import org . eclipse . ui . part . Page ; import org . eclipse . ui . texteditor . IWorkbenchActionDefinitionIds ; import org . eclipse . ui . views . navigator . ResourceNavigatorRenameAction ; import org . rubypeople . rdt . ui . IPackagesViewPart ; public class CCPActionGroup extends ActionGroup { private IWorkbenchSite fSite ; private Clipboard fClipboard ; private SelectionListenerAction [ ] fActions ; private SelectionListenerAction fDeleteAction ; private SelectionListenerAction fCopyAction ; private RenameResourceAction fRenameAction ; private PasteAction fPasteAction ; private MoveResourceAction fMoveAction ; private TreeViewer fTreeViewer ; public CCPActionGroup ( IViewPart part ) { if ( part instanceof IPackagesViewPart ) { IPackagesViewPart pack = ( IPackagesViewPart ) part ; fTreeViewer = pack . getTreeViewer ( ) ; } init ( part . getSite ( ) ) ; } public CCPActionGroup ( Page page ) { this ( page . getSite ( ) ) ; } private CCPActionGroup ( IWorkbenchSite site ) { init ( site ) ; } private void init ( IWorkbenchSite site ) { fSite = site ; fClipboard = new Clipboard ( site . getShell ( ) . getDisplay ( ) ) ; fPasteAction = new PasteAction ( fSite . getShell ( ) , fClipboard ) ; fPasteAction . setActionDefinitionId ( IWorkbenchActionDefinitionIds . PASTE ) ; fCopyAction = new CopyAction ( fSite . getShell ( ) , fClipboard , fPasteAction ) ; fCopyAction . setActionDefinitionId ( IWorkbenchActionDefinitionIds . COPY ) ; fMoveAction = new MoveResourceAction ( fSite . getShell ( ) ) ; if ( fTreeViewer != null ) { fRenameAction = new ResourceNavigatorRenameAction ( fSite . getShell ( ) , fTreeViewer ) ; } else { fRenameAction = new RenameResourceAction ( fSite . getShell ( ) ) ; } fRenameAction . setActionDefinitionId ( IWorkbenchActionDefinitionIds . RENAME ) ; fDeleteAction = new DeleteResourceAction ( fSite . getShell ( ) ) ; fDeleteAction . setActionDefinitionId ( IWorkbenchActionDefinitionIds . DELETE ) ; fActions = new SelectionListenerAction [ ] { fCopyAction , fPasteAction , fDeleteAction , fRenameAction , fMoveAction } ; registerActionsAsSelectionChangeListeners ( ) ; } private void registerActionsAsSelectionChangeListeners ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; ISelection selection = provider . getSelection ( ) ; for ( int i = ; i < fActions . length ; i ++ ) { SelectionListenerAction action = fActions [ i ] ; provider . addSelectionChangedListener ( action ) ; } } private void deregisterActionsAsSelectionChangeListeners ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; for ( int i = ; i < fActions . length ; i ++ ) { provider . removeSelectionChangedListener ( fActions [ i ] ) ; } } public IAction getDeleteAction ( ) { return fDeleteAction ; } public void fillActionBars ( IActionBars actionBars ) { super . fillActionBars ( actionBars ) ; actionBars . setGlobalActionHandler ( ActionFactory . DELETE . getId ( ) , fDeleteAction ) ; actionBars . setGlobalActionHandler ( ActionFactory . COPY . getId ( ) , fCopyAction ) ; actionBars . setGlobalActionHandler ( ActionFactory . PASTE . getId ( ) , fPasteAction ) ; actionBars . setGlobalActionHandler ( ActionFactory . RENAME . getId ( ) , fRenameAction ) ; actionBars . setGlobalActionHandler ( ActionFactory . MOVE . getId ( ) , fMoveAction ) ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; for ( int i = ; i < fActions . length ; i ++ ) { SelectionListenerAction action = fActions [ i ] ; menu . appendToGroup ( ICommonMenuConstants . GROUP_EDIT , action ) ; } } public void dispose ( ) { super . dispose ( ) ; if ( fClipboard != null ) { fClipboard . dispose ( ) ; fClipboard = null ; } deregisterActionsAsSelectionChangeListeners ( ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; public class FindReadReferencesInWorkingSetAction extends FindReferencesInWorkingSetAction { public FindReadReferencesInWorkingSetAction ( IWorkbenchSite site ) { super ( site ) ; } public FindReadReferencesInWorkingSetAction ( IWorkbenchSite site , IWorkingSet [ ] workingSets ) { super ( site , workingSets ) ; } public FindReadReferencesInWorkingSetAction ( RubyEditor editor ) { super ( editor ) ; } public FindReadReferencesInWorkingSetAction ( RubyEditor editor , IWorkingSet [ ] workingSets ) { super ( editor , workingSets ) ; } Class [ ] getValidTypes ( ) { return new Class [ ] { IField . class } ; } void init ( ) { setText ( SearchMessages . Search_FindReadReferencesInWorkingSetAction_label ) ; setToolTipText ( SearchMessages . Search_FindReadReferencesInWorkingSetAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_READ_REFERENCES_IN_WORKING_SET_ACTION ) ; } int getLimitTo ( ) { return IRubySearchConstants . READ_ACCESSES ; } String getOperationUnavailableMessage ( ) { return SearchMessages . RubyElementAction_operationUnavailable_field ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; public class FindReadReferencesAction extends FindReferencesAction { public FindReadReferencesAction ( IWorkbenchSite site ) { super ( site ) ; } public FindReadReferencesAction ( RubyEditor editor ) { super ( editor ) ; } Class [ ] getValidTypes ( ) { return new Class [ ] { IField . class } ; } void init ( ) { setText ( SearchMessages . Search_FindReadReferencesAction_label ) ; setToolTipText ( SearchMessages . Search_FindReadReferencesAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_READ_REFERENCES_IN_WORKSPACE_ACTION ) ; } int getLimitTo ( ) { return IRubySearchConstants . READ_ACCESSES ; } String getOperationUnavailableMessage ( ) { return SearchMessages . RubyElementAction_operationUnavailable_field ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . actions . OpenWithMenu ; import org . eclipse . ui . texteditor . AbstractTextEditor ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; public class OpenEditorActionGroup extends ActionGroup { private IWorkbenchSite fSite ; private boolean fIsEditorOwner ; private OpenAction fOpen ; public OpenEditorActionGroup ( IViewPart part ) { fSite = part . getSite ( ) ; fOpen = new OpenAction ( fSite ) ; fOpen . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_EDITOR ) ; initialize ( fSite . getSelectionProvider ( ) ) ; } public OpenEditorActionGroup ( AbstractTextEditor editor ) { fIsEditorOwner = true ; fOpen = new OpenAction ( editor ) ; fOpen . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_EDITOR ) ; editor . setAction ( "" , fOpen ) ; fSite = editor . getEditorSite ( ) ; initialize ( fSite . getSelectionProvider ( ) ) ; } public IAction getOpenAction ( ) { return fOpen ; } private void initialize ( ISelectionProvider provider ) { ISelection selection = provider . getSelection ( ) ; fOpen . update ( selection ) ; if ( ! fIsEditorOwner ) { provider . addSelectionChangedListener ( fOpen ) ; } } public void fillActionBars ( IActionBars actionBar ) { super . fillActionBars ( actionBar ) ; setGlobalActionHandlers ( actionBar ) ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; appendToGroup ( menu , fOpen ) ; if ( ! fIsEditorOwner ) { addOpenWithMenu ( menu ) ; } } public void dispose ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; provider . removeSelectionChangedListener ( fOpen ) ; super . dispose ( ) ; } private void setGlobalActionHandlers ( IActionBars actionBars ) { actionBars . setGlobalActionHandler ( RdtActionConstants . OPEN , fOpen ) ; } private void appendToGroup ( IMenuManager menu , IAction action ) { if ( action . isEnabled ( ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_OPEN , action ) ; } private void addOpenWithMenu ( IMenuManager menu ) { ISelection selection = getContext ( ) . getSelection ( ) ; if ( selection . isEmpty ( ) || ! ( selection instanceof IStructuredSelection ) ) return ; IStructuredSelection ss = ( IStructuredSelection ) selection ; if ( ss . size ( ) != ) return ; Object o = ss . getFirstElement ( ) ; if ( ! ( o instanceof IAdaptable ) ) return ; IAdaptable element = ( IAdaptable ) o ; Object resource = element . getAdapter ( IResource . class ) ; if ( ! ( resource instanceof IFile ) ) return ; IMenuManager submenu = new MenuManager ( ActionMessages . OpenWithMenu_label ) ; submenu . add ( new OpenWithMenu ( fSite . getPage ( ) , ( IFile ) resource ) ) ; menu . appendToGroup ( IContextMenuConstants . GROUP_OPEN , submenu ) ; } } package org . rubypeople . rdt . ui . actions ; import java . lang . reflect . InvocationTargetException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . actions . OpenResourceAction ; import org . eclipse . ui . dialogs . ElementListSelectionDialog ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . actions . WorkbenchRunnableAdapter ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; public class OpenProjectAction extends SelectionDispatchAction implements IResourceChangeListener { private static final int EMPTY_SELECTION = ; private static final int ELEMENT_SELECTION = ; private int fMode ; private OpenResourceAction fWorkbenchAction ; public OpenProjectAction ( IWorkbenchSite site ) { super ( site ) ; fWorkbenchAction = new OpenResourceAction ( site . getShell ( ) ) ; setText ( fWorkbenchAction . getText ( ) ) ; setToolTipText ( fWorkbenchAction . getToolTipText ( ) ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . OPEN_PROJECT_ACTION ) ; } public void resourceChanged ( IResourceChangeEvent event ) { fWorkbenchAction . resourceChanged ( event ) ; switch ( fMode ) { case ELEMENT_SELECTION : setEnabled ( fWorkbenchAction . isEnabled ( ) ) ; break ; case EMPTY_SELECTION : internalResourceChanged ( event ) ; break ; } } private void internalResourceChanged ( IResourceChangeEvent event ) { IResourceDelta delta = event . getDelta ( ) ; if ( delta != null ) { IResourceDelta [ ] projDeltas = delta . getAffectedChildren ( IResourceDelta . CHANGED ) ; for ( int i = ; i < projDeltas . length ; ++ i ) { IResourceDelta projDelta = projDeltas [ i ] ; if ( ( projDelta . getFlags ( ) & IResourceDelta . OPEN ) != ) { setEnabled ( hasCloseProjects ( ) ) ; return ; } } } } public void selectionChanged ( ISelection selection ) { setEnabled ( hasCloseProjects ( ) ) ; fMode = EMPTY_SELECTION ; } public void run ( ISelection selection ) { internalRun ( ) ; } public void selectionChanged ( IStructuredSelection selection ) { if ( selection . isEmpty ( ) ) { setEnabled ( hasCloseProjects ( ) ) ; fMode = EMPTY_SELECTION ; return ; } fWorkbenchAction . selectionChanged ( selection ) ; setEnabled ( fWorkbenchAction . isEnabled ( ) ) ; fMode = ELEMENT_SELECTION ; } public void run ( IStructuredSelection selection ) { if ( selection . isEmpty ( ) ) { internalRun ( ) ; return ; } fWorkbenchAction . run ( ) ; } private void internalRun ( ) { ElementListSelectionDialog dialog = new ElementListSelectionDialog ( getShell ( ) , new RubyElementLabelProvider ( ) ) ; dialog . setTitle ( ActionMessages . OpenProjectAction_dialog_title ) ; dialog . setMessage ( ActionMessages . OpenProjectAction_dialog_message ) ; dialog . setElements ( getClosedProjects ( ) ) ; dialog . setMultipleSelection ( true ) ; int result = dialog . open ( ) ; if ( result != Window . OK ) return ; final Object [ ] projects = dialog . getResult ( ) ; IWorkspaceRunnable runnable = createRunnable ( projects ) ; try { PlatformUI . getWorkbench ( ) . getProgressService ( ) . run ( true , true , new WorkbenchRunnableAdapter ( runnable ) ) ; } catch ( InvocationTargetException e ) { ExceptionHandler . handle ( e , getShell ( ) , ActionMessages . OpenProjectAction_dialog_title , ActionMessages . OpenProjectAction_error_message ) ; } catch ( InterruptedException e ) { } } private IWorkspaceRunnable createRunnable ( final Object [ ] projects ) { return new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { monitor . beginTask ( "" , projects . length ) ; MultiStatus errorStatus = null ; for ( int i = ; i < projects . length ; i ++ ) { IProject project = ( IProject ) projects [ i ] ; try { project . open ( new SubProgressMonitor ( monitor , ) ) ; } catch ( CoreException e ) { if ( errorStatus == null ) errorStatus = new MultiStatus ( RubyPlugin . getPluginId ( ) , IStatus . ERROR , ActionMessages . OpenProjectAction_error_message , e ) ; errorStatus . merge ( e . getStatus ( ) ) ; } } monitor . done ( ) ; if ( errorStatus != null ) throw new CoreException ( errorStatus ) ; } } ; } private Object [ ] getClosedProjects ( ) { IProject [ ] projects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; List result = new ArrayList ( ) ; for ( int i = ; i < projects . length ; i ++ ) { IProject project = projects [ i ] ; if ( ! project . isOpen ( ) ) result . add ( project ) ; } return result . toArray ( ) ; } private boolean hasCloseProjects ( ) { IProject [ ] projects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; for ( int i = ; i < projects . length ; i ++ ) { if ( ! projects [ i ] . isOpen ( ) ) return true ; } return false ; } } package org . rubypeople . rdt . ui . actions ; import java . util . Iterator ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IStorage ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . util . OpenStrategy ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . texteditor . AbstractTextEditor ; import org . eclipse . ui . texteditor . IEditorStatusLine ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . IRubyStatusConstants ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . actions . ActionMessages ; import org . rubypeople . rdt . internal . ui . actions . ActionUtil ; import org . rubypeople . rdt . internal . ui . actions . OpenActionUtil ; import org . rubypeople . rdt . internal . ui . actions . SelectionConverter ; import org . rubypeople . rdt . internal . ui . util . ExceptionHandler ; public class OpenAction extends SelectionDispatchAction { private AbstractTextEditor fEditor ; public OpenAction ( IWorkbenchSite site ) { super ( site ) ; setText ( ActionMessages . OpenAction_label ) ; setToolTipText ( ActionMessages . OpenAction_tooltip ) ; setDescription ( ActionMessages . OpenAction_description ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . OPEN_ACTION ) ; } public OpenAction ( AbstractTextEditor editor ) { this ( editor . getEditorSite ( ) ) ; fEditor = editor ; setText ( ActionMessages . OpenAction_declaration_label ) ; setEnabled ( SelectionConverter . canOperateOn ( fEditor ) ) ; } public void selectionChanged ( ITextSelection selection ) { } public void selectionChanged ( IStructuredSelection selection ) { setEnabled ( checkEnabled ( selection ) ) ; } private boolean checkEnabled ( IStructuredSelection selection ) { if ( selection . isEmpty ( ) ) return false ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof ISourceReference ) continue ; if ( element instanceof IFile ) continue ; if ( element instanceof IStorage ) continue ; return false ; } return true ; } public void run ( ITextSelection selection ) { if ( ! ActionUtil . isProcessable ( getShell ( ) , fEditor ) ) return ; try { IRubyElement element = SelectionConverter . codeResolve ( fEditor , getShell ( ) , getDialogTitle ( ) , ActionMessages . OpenAction_select_element ) ; if ( element == null ) { IEditorStatusLine statusLine = ( IEditorStatusLine ) fEditor . getAdapter ( IEditorStatusLine . class ) ; if ( statusLine != null ) statusLine . setMessage ( true , ActionMessages . OpenAction_error_messageBadSelection , null ) ; getShell ( ) . getDisplay ( ) . beep ( ) ; return ; } IRubyElement input = SelectionConverter . getInput ( fEditor ) ; int type = element . getElementType ( ) ; if ( type == IRubyElement . RUBY_PROJECT ) element = input ; run ( new Object [ ] { element } ) ; } catch ( RubyModelException e ) { showError ( e ) ; } } public void run ( IStructuredSelection selection ) { if ( ! checkEnabled ( selection ) ) return ; run ( selection . toArray ( ) ) ; } public void run ( Object [ ] elements ) { if ( elements == null ) return ; for ( int i = ; i < elements . length ; i ++ ) { Object element = elements [ i ] ; try { element = getElementToOpen ( element ) ; boolean activateOnOpen = fEditor != null ? true : OpenStrategy . activateOnOpen ( ) ; OpenActionUtil . open ( element , activateOnOpen ) ; } catch ( RubyModelException e ) { RubyPlugin . log ( new Status ( IStatus . ERROR , RubyPlugin . getPluginId ( ) , IRubyStatusConstants . INTERNAL_ERROR , ActionMessages . OpenAction_error_message , e ) ) ; ErrorDialog . openError ( getShell ( ) , getDialogTitle ( ) , ActionMessages . OpenAction_error_messageProblems , e . getStatus ( ) ) ; } catch ( PartInitException x ) { String name = null ; if ( element instanceof IRubyElement ) { name = ( ( IRubyElement ) element ) . getElementName ( ) ; } else if ( element instanceof IStorage ) { name = ( ( IStorage ) element ) . getName ( ) ; } else if ( element instanceof IResource ) { name = ( ( IResource ) element ) . getName ( ) ; } if ( name != null ) { MessageDialog . openError ( getShell ( ) , ActionMessages . OpenAction_error_messageProblems , Messages . format ( ActionMessages . OpenAction_error_messageArgs , new String [ ] { name , x . getMessage ( ) } ) ) ; } } } } public Object getElementToOpen ( Object object ) throws RubyModelException { return object ; } private String getDialogTitle ( ) { return ActionMessages . OpenAction_error_title ; } private void showError ( CoreException e ) { ExceptionHandler . handle ( e , getShell ( ) , getDialogTitle ( ) , ActionMessages . OpenAction_error_message ) ; } } package org . rubypeople . rdt . ui . actions ; import java . util . Iterator ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . search . ui . IContextMenuConstants ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . IWorkingSet ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . internal . ui . search . SearchUtil ; public class ReadReferencesSearchGroup extends ActionGroup { private static final String MENU_TEXT = SearchMessages . group_readReferences ; private IWorkbenchSite fSite ; private RubyEditor fEditor ; private IActionBars fActionBars ; private String fGroupId ; private FindReadReferencesAction fFindReadReferencesAction ; private FindReadReferencesInProjectAction fFindReadReferencesInProjectAction ; private FindReadReferencesInWorkingSetAction fFindReadReferencesInWorkingSetAction ; public ReadReferencesSearchGroup ( IWorkbenchSite site ) { fSite = site ; fGroupId = IContextMenuConstants . GROUP_SEARCH ; fFindReadReferencesAction = new FindReadReferencesAction ( site ) ; fFindReadReferencesAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_READ_ACCESS_IN_WORKSPACE ) ; fFindReadReferencesInProjectAction = new FindReadReferencesInProjectAction ( site ) ; fFindReadReferencesInProjectAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_READ_ACCESS_IN_PROJECT ) ; fFindReadReferencesInWorkingSetAction = new FindReadReferencesInWorkingSetAction ( site ) ; fFindReadReferencesInWorkingSetAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_READ_ACCESS_IN_WORKING_SET ) ; ISelectionProvider provider = fSite . getSelectionProvider ( ) ; ISelection selection = provider . getSelection ( ) ; registerAction ( fFindReadReferencesAction , provider , selection ) ; registerAction ( fFindReadReferencesInProjectAction , provider , selection ) ; registerAction ( fFindReadReferencesInWorkingSetAction , provider , selection ) ; } public ReadReferencesSearchGroup ( RubyEditor editor ) { fEditor = editor ; fSite = fEditor . getSite ( ) ; fGroupId = ITextEditorActionConstants . GROUP_FIND ; fFindReadReferencesAction = new FindReadReferencesAction ( fEditor ) ; fFindReadReferencesAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_READ_ACCESS_IN_WORKSPACE ) ; fEditor . setAction ( "" , fFindReadReferencesAction ) ; fFindReadReferencesInProjectAction = new FindReadReferencesInProjectAction ( fEditor ) ; fFindReadReferencesInProjectAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_READ_ACCESS_IN_PROJECT ) ; fEditor . setAction ( "" , fFindReadReferencesInProjectAction ) ; fFindReadReferencesInWorkingSetAction = new FindReadReferencesInWorkingSetAction ( fEditor ) ; fFindReadReferencesInWorkingSetAction . setActionDefinitionId ( IRubyEditorActionDefinitionIds . SEARCH_READ_ACCESS_IN_WORKING_SET ) ; fEditor . setAction ( "" , fFindReadReferencesInWorkingSetAction ) ; } private void registerAction ( SelectionDispatchAction action , ISelectionProvider provider , ISelection selection ) { action . update ( selection ) ; provider . addSelectionChangedListener ( action ) ; } private void addAction ( IAction action , IMenuManager manager ) { if ( action . isEnabled ( ) ) { manager . add ( action ) ; } } private void addWorkingSetAction ( IWorkingSet [ ] workingSets , IMenuManager manager ) { FindAction action ; if ( fEditor != null ) action = new WorkingSetFindAction ( fEditor , new FindReadReferencesInWorkingSetAction ( fEditor , workingSets ) , SearchUtil . toString ( workingSets ) ) ; else action = new WorkingSetFindAction ( fSite , new FindReadReferencesInWorkingSetAction ( fSite , workingSets ) , SearchUtil . toString ( workingSets ) ) ; action . update ( getContext ( ) . getSelection ( ) ) ; addAction ( action , manager ) ; } public void fillContextMenu ( IMenuManager manager ) { MenuManager javaSearchMM = new MenuManager ( MENU_TEXT , IContextMenuConstants . GROUP_SEARCH ) ; addAction ( fFindReadReferencesAction , javaSearchMM ) ; addAction ( fFindReadReferencesInProjectAction , javaSearchMM ) ; javaSearchMM . add ( new Separator ( ) ) ; Iterator iter = SearchUtil . getLRUWorkingSets ( ) . sortedIterator ( ) ; while ( iter . hasNext ( ) ) { addWorkingSetAction ( ( IWorkingSet [ ] ) iter . next ( ) , javaSearchMM ) ; } addAction ( fFindReadReferencesInWorkingSetAction , javaSearchMM ) ; if ( ! javaSearchMM . isEmpty ( ) ) manager . appendToGroup ( fGroupId , javaSearchMM ) ; } public void fillActionBars ( IActionBars actionBars ) { Assert . isNotNull ( actionBars ) ; super . fillActionBars ( actionBars ) ; fActionBars = actionBars ; updateGlobalActionHandlers ( ) ; } public void dispose ( ) { ISelectionProvider provider = fSite . getSelectionProvider ( ) ; if ( provider != null ) { disposeAction ( fFindReadReferencesAction , provider ) ; disposeAction ( fFindReadReferencesInProjectAction , provider ) ; disposeAction ( fFindReadReferencesInWorkingSetAction , provider ) ; } fFindReadReferencesAction = null ; fFindReadReferencesInProjectAction = null ; fFindReadReferencesInWorkingSetAction = null ; updateGlobalActionHandlers ( ) ; super . dispose ( ) ; } private void updateGlobalActionHandlers ( ) { if ( fActionBars != null ) { fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_READ_ACCESS_IN_WORKSPACE , fFindReadReferencesAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_READ_ACCESS_IN_PROJECT , fFindReadReferencesInProjectAction ) ; fActionBars . setGlobalActionHandler ( RdtActionConstants . FIND_READ_ACCESS_IN_WORKING_SET , fFindReadReferencesInWorkingSetAction ) ; } } private void disposeAction ( ISelectionChangedListener action , ISelectionProvider provider ) { if ( action != null ) provider . removeSelectionChangedListener ( action ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . ILocalVariable ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . ui . IRubyHelpContextIds ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . internal . ui . search . RubySearchScopeFactory ; import org . rubypeople . rdt . internal . ui . search . SearchMessages ; import org . rubypeople . rdt . ui . search . ElementQuerySpecification ; import org . rubypeople . rdt . ui . search . QuerySpecification ; public class FindReferencesInHierarchyAction extends FindReferencesAction { public FindReferencesInHierarchyAction ( IWorkbenchSite site ) { super ( site ) ; } public FindReferencesInHierarchyAction ( RubyEditor editor ) { super ( editor ) ; } Class [ ] getValidTypes ( ) { return new Class [ ] { IRubyScript . class , IType . class , IMethod . class , IField . class , ILocalVariable . class } ; } void init ( ) { setText ( SearchMessages . Search_FindHierarchyReferencesAction_label ) ; setToolTipText ( SearchMessages . Search_FindHierarchyReferencesAction_tooltip ) ; setImageDescriptor ( RubyPluginImages . DESC_OBJS_SEARCH_REF ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( this , IRubyHelpContextIds . FIND_REFERENCES_IN_HIERARCHY_ACTION ) ; } QuerySpecification createQuery ( IRubyElement element ) throws RubyModelException { IType type = getType ( element ) ; if ( type == null ) { return super . createQuery ( element ) ; } RubySearchScopeFactory factory = RubySearchScopeFactory . getInstance ( ) ; IRubySearchScope scope = SearchEngine . createHierarchyScope ( type ) ; String description = factory . getHierarchyScopeDescription ( type ) ; return new ElementQuerySpecification ( element , getLimitTo ( ) , scope , description ) ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . texteditor . IUpdate ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; public class RubyActionGroup extends ActionGroup { public static final String MENU_ID = "" ; public static final String GROUP_GENERATE = "" ; public static final String GROUP_CODE = "" ; private static final String GROUP_COMMENT = "" ; public static final String GROUP_EDIT = "" ; private RubyEditor fEditor ; private String fGroupName ; public RubyActionGroup ( RubyEditor editor , String groupName ) { fEditor = editor ; fGroupName = groupName ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; String menuText = "" ; IMenuManager subMenu = new MenuManager ( menuText , MENU_ID ) ; int added = ; if ( isEditorOwner ( ) ) { added = fillEditorSubMenu ( subMenu ) ; } else { added = fillViewSubMenu ( subMenu ) ; } if ( added > ) menu . appendToGroup ( fGroupName , subMenu ) ; } private int fillEditorSubMenu ( IMenuManager source ) { int added = ; source . add ( new Separator ( GROUP_COMMENT ) ) ; added += addEditorAction ( source , "" ) ; added += addEditorAction ( source , "" ) ; added += addEditorAction ( source , "" ) ; source . add ( new Separator ( GROUP_EDIT ) ) ; added += addEditorAction ( source , "" ) ; added += addEditorAction ( source , "" ) ; added += addEditorAction ( source , "" ) ; source . add ( new Separator ( GROUP_GENERATE ) ) ; source . add ( new Separator ( GROUP_CODE ) ) ; return added ; } private int fillViewSubMenu ( IMenuManager source ) { int added = ; source . add ( new Separator ( GROUP_COMMENT ) ) ; source . add ( new Separator ( GROUP_EDIT ) ) ; source . add ( new Separator ( GROUP_GENERATE ) ) ; source . add ( new Separator ( GROUP_CODE ) ) ; return added ; } private int addAction ( IMenuManager menu , IAction action ) { if ( action != null && action . isEnabled ( ) ) { menu . add ( action ) ; return ; } return ; } private int addEditorAction ( IMenuManager menu , String actionID ) { if ( fEditor == null ) return ; IAction action = fEditor . getAction ( actionID ) ; if ( action == null ) return ; if ( action instanceof IUpdate ) ( ( IUpdate ) action ) . update ( ) ; if ( action . isEnabled ( ) ) { menu . add ( action ) ; return ; } return ; } private boolean isEditorOwner ( ) { return fEditor != null ; } } package org . rubypeople . rdt . ui . actions ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchSite ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . dialogs . PropertyDialogAction ; import org . eclipse . ui . part . Page ; import org . eclipse . ui . texteditor . IWorkbenchActionDefinitionIds ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . ui . IContextMenuConstants ; public class OpenViewActionGroup extends ActionGroup { private boolean fEditorIsOwner ; private boolean fIsTypeHiararchyViewerOwner ; private boolean fIsCallHiararchyViewerOwner ; private ISelectionProvider fSelectionProvider ; private OpenTypeHierarchyAction fOpenTypeHierarchy ; private OpenCallHierarchyAction fOpenCallHierarchy ; private PropertyDialogAction fOpenPropertiesDialog ; public OpenViewActionGroup ( Page page ) { createSiteActions ( page . getSite ( ) , null ) ; } public OpenViewActionGroup ( Page page , ISelectionProvider selectionProvider ) { createSiteActions ( page . getSite ( ) , selectionProvider ) ; } public OpenViewActionGroup ( IViewPart part ) { this ( part , null ) ; } public OpenViewActionGroup ( IViewPart part , ISelectionProvider selectionProvider ) { createSiteActions ( part . getSite ( ) , selectionProvider ) ; String partName = part . getClass ( ) . getName ( ) ; fIsTypeHiararchyViewerOwner = "" . equals ( partName ) ; fIsCallHiararchyViewerOwner = "" . equals ( partName ) ; } public OpenViewActionGroup ( IWorkbenchSite site , ISelectionProvider selectionProvider ) { createSiteActions ( site , selectionProvider ) ; } public OpenViewActionGroup ( RubyEditor part ) { fEditorIsOwner = true ; fOpenTypeHierarchy = new OpenTypeHierarchyAction ( part ) ; fOpenTypeHierarchy . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_TYPE_HIERARCHY ) ; part . setAction ( "" , fOpenTypeHierarchy ) ; fOpenCallHierarchy = new OpenCallHierarchyAction ( part ) ; fOpenCallHierarchy . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_CALL_HIERARCHY ) ; part . setAction ( "" , fOpenCallHierarchy ) ; initialize ( part . getEditorSite ( ) . getSelectionProvider ( ) ) ; } private void createSiteActions ( IWorkbenchSite site , ISelectionProvider specialProvider ) { fOpenTypeHierarchy = new OpenTypeHierarchyAction ( site ) ; fOpenTypeHierarchy . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_TYPE_HIERARCHY ) ; fOpenTypeHierarchy . setSpecialSelectionProvider ( specialProvider ) ; fOpenCallHierarchy = new OpenCallHierarchyAction ( site ) ; fOpenCallHierarchy . setActionDefinitionId ( IRubyEditorActionDefinitionIds . OPEN_CALL_HIERARCHY ) ; fOpenCallHierarchy . setSpecialSelectionProvider ( specialProvider ) ; ISelectionProvider provider = specialProvider != null ? specialProvider : site . getSelectionProvider ( ) ; if ( getShowProperties ( ) ) { fOpenPropertiesDialog = new PropertyDialogAction ( site , provider ) ; fOpenPropertiesDialog . setActionDefinitionId ( IWorkbenchActionDefinitionIds . PROPERTIES ) ; } initialize ( provider ) ; } private void initialize ( ISelectionProvider provider ) { fSelectionProvider = provider ; ISelection selection = provider . getSelection ( ) ; fOpenTypeHierarchy . update ( selection ) ; fOpenCallHierarchy . update ( selection ) ; if ( ! fEditorIsOwner ) { if ( getShowProperties ( ) ) { if ( selection instanceof IStructuredSelection ) { IStructuredSelection ss = ( IStructuredSelection ) selection ; fOpenPropertiesDialog . selectionChanged ( ss ) ; } else { fOpenPropertiesDialog . selectionChanged ( selection ) ; } } provider . addSelectionChangedListener ( fOpenTypeHierarchy ) ; provider . addSelectionChangedListener ( fOpenCallHierarchy ) ; } } public void fillActionBars ( IActionBars actionBar ) { super . fillActionBars ( actionBar ) ; setGlobalActionHandlers ( actionBar ) ; } public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; if ( ! fIsTypeHiararchyViewerOwner ) appendToGroup ( menu , fOpenTypeHierarchy ) ; if ( ! fIsCallHiararchyViewerOwner ) appendToGroup ( menu , fOpenCallHierarchy ) ; IStructuredSelection selection = getStructuredSelection ( ) ; if ( getShowProperties ( ) && fOpenPropertiesDialog != null && fOpenPropertiesDialog . isEnabled ( ) && selection != null && fOpenPropertiesDialog . isApplicableForSelection ( selection ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_PROPERTIES , fOpenPropertiesDialog ) ; } public void dispose ( ) { fSelectionProvider . removeSelectionChangedListener ( fOpenTypeHierarchy ) ; fSelectionProvider . removeSelectionChangedListener ( fOpenCallHierarchy ) ; super . dispose ( ) ; } private void setGlobalActionHandlers ( IActionBars actionBars ) { actionBars . setGlobalActionHandler ( RdtActionConstants . OPEN_TYPE_HIERARCHY , fOpenTypeHierarchy ) ; actionBars . setGlobalActionHandler ( RdtActionConstants . OPEN_CALL_HIERARCHY , fOpenCallHierarchy ) ; if ( ! fEditorIsOwner && getShowProperties ( ) ) actionBars . setGlobalActionHandler ( ActionFactory . PROPERTIES . getId ( ) , fOpenPropertiesDialog ) ; } private void appendToGroup ( IMenuManager menu , IAction action ) { if ( action . isEnabled ( ) ) menu . appendToGroup ( IContextMenuConstants . GROUP_OPEN , action ) ; } private IStructuredSelection getStructuredSelection ( ) { ISelection selection = getContext ( ) . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) return ( IStructuredSelection ) selection ; return null ; } protected boolean getShowProperties ( ) { return true ; } } package org . rubypeople . rdt . ui ; import org . eclipse . jface . resource . CompositeImageDescriptor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . util . Assert ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . Point ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; public class RubyElementImageDescriptor extends CompositeImageDescriptor { public final static int STATIC = ; public final static int WARNING = ; public final static int ERROR = ; public final static int OVERRIDES = ; public final static int IMPLEMENTS = ; public final static int CONSTRUCTOR = ; public final static int DEPRECATED = ; private ImageDescriptor fBaseImage ; private int fFlags ; private Point fSize ; public RubyElementImageDescriptor ( ImageDescriptor baseImage , int flags , Point size ) { fBaseImage = baseImage ; Assert . isNotNull ( fBaseImage ) ; fFlags = flags ; Assert . isTrue ( fFlags >= ) ; fSize = size ; Assert . isNotNull ( fSize ) ; } public void setAdornments ( int adornments ) { Assert . isTrue ( adornments >= ) ; fFlags = adornments ; } public int getAdronments ( ) { return fFlags ; } public void setImageSize ( Point size ) { Assert . isNotNull ( size ) ; Assert . isTrue ( size . x >= && size . y >= ) ; fSize = size ; } public Point getImageSize ( ) { return new Point ( fSize . x , fSize . y ) ; } protected Point getSize ( ) { return fSize ; } public boolean equals ( Object object ) { if ( object == null || ! RubyElementImageDescriptor . class . equals ( object . getClass ( ) ) ) return false ; RubyElementImageDescriptor other = ( RubyElementImageDescriptor ) object ; return ( fBaseImage . equals ( other . fBaseImage ) && fFlags == other . fFlags && fSize . equals ( other . fSize ) ) ; } public int hashCode ( ) { return fBaseImage . hashCode ( ) | fFlags | fSize . hashCode ( ) ; } protected void drawCompositeImage ( int width , int height ) { ImageData bg = getImageData ( fBaseImage ) ; if ( ( fFlags & DEPRECATED ) != ) { Point size = getSize ( ) ; ImageData data = getImageData ( RubyPluginImages . DESC_OVR_DEPRECATED ) ; drawImage ( data , , size . y - data . height ) ; } drawImage ( bg , , ) ; drawTopRight ( ) ; drawBottomRight ( ) ; drawBottomLeft ( ) ; } private ImageData getImageData ( ImageDescriptor descriptor ) { ImageData data = descriptor . getImageData ( ) ; if ( data == null ) { data = DEFAULT_IMAGE_DATA ; RubyPlugin . logErrorMessage ( "" + descriptor . toString ( ) ) ; } return data ; } private void drawTopRight ( ) { int x = getSize ( ) . x ; if ( ( fFlags & CONSTRUCTOR ) != ) { ImageData data = getImageData ( RubyPluginImages . DESC_OVR_CONSTRUCTOR ) ; x -= data . width ; drawImage ( data , x , ) ; } if ( ( fFlags & STATIC ) != ) { ImageData data = getImageData ( RubyPluginImages . DESC_OVR_STATIC ) ; x -= data . width ; drawImage ( data , x , ) ; } } private void drawBottomRight ( ) { Point size = getSize ( ) ; int x = size . x ; int flags = fFlags ; if ( ( flags & OVERRIDES ) != ) { ImageData data = getImageData ( RubyPluginImages . DESC_OVR_OVERRIDES ) ; x -= data . width ; drawImage ( data , x , size . y - data . height ) ; } if ( ( flags & IMPLEMENTS ) != ) { ImageData data = getImageData ( RubyPluginImages . DESC_OVR_IMPLEMENTS ) ; x -= data . width ; drawImage ( data , x , size . y - data . height ) ; } } private void drawBottomLeft ( ) { Point size = getSize ( ) ; int x = ; if ( ( fFlags & ERROR ) != ) { ImageData data = getImageData ( RubyPluginImages . DESC_OVR_ERROR ) ; drawImage ( data , x , size . y - data . height ) ; x += data . width ; } if ( ( fFlags & WARNING ) != ) { ImageData data = getImageData ( RubyPluginImages . DESC_OVR_WARNING ) ; drawImage ( data , x , size . y - data . height ) ; x += data . width ; } } } package org . rubypeople . rdt . ui . viewsupport ; import java . util . HashMap ; import java . util . Iterator ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . util . Assert ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; public class ImageDescriptorRegistry { private HashMap fRegistry = new HashMap ( ) ; private Display fDisplay ; public ImageDescriptorRegistry ( ) { this ( SWTUtil . getStandardDisplay ( ) ) ; } public ImageDescriptorRegistry ( Display display ) { fDisplay = display ; Assert . isNotNull ( fDisplay ) ; hookDisplay ( ) ; } public Image get ( ImageDescriptor descriptor ) { if ( descriptor == null ) descriptor = ImageDescriptor . getMissingImageDescriptor ( ) ; Image result = ( Image ) fRegistry . get ( descriptor ) ; if ( result != null ) return result ; Assert . isTrue ( fDisplay == SWTUtil . getStandardDisplay ( ) , "" ) ; result = descriptor . createImage ( ) ; if ( result != null ) fRegistry . put ( descriptor , result ) ; return result ; } public void dispose ( ) { for ( Iterator iter = fRegistry . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Image image = ( Image ) iter . next ( ) ; image . dispose ( ) ; } fRegistry . clear ( ) ; } private void hookDisplay ( ) { fDisplay . disposeExec ( new Runnable ( ) { public void run ( ) { dispose ( ) ; } } ) ; } } package org . rubypeople . rdt . ui . viewsupport ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . ImageData ; public class ImageImageDescriptor extends ImageDescriptor { private Image fImage ; public ImageImageDescriptor ( Image image ) { super ( ) ; fImage = image ; } public ImageData getImageData ( ) { return fImage . getImageData ( ) ; } public boolean equals ( Object obj ) { return ( obj != null ) && getClass ( ) . equals ( obj . getClass ( ) ) && fImage . equals ( ( ( ImageImageDescriptor ) obj ) . fImage ) ; } public int hashCode ( ) { return fImage . hashCode ( ) ; } } package org . rubypeople . rdt . internal . debug . core ; public class DebuggerNotFoundException extends RuntimeException { public DebuggerNotFoundException ( String message ) { super ( message ) ; } private static final long serialVersionUID = - ; public DebuggerNotFoundException ( ) { super ( "" ) ; } } package org . rubypeople . rdt . internal . debug . core . breakpoints ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . model . Breakpoint ; import org . rubypeople . rdt . debug . core . RdtDebugModel ; public abstract class RubyBreakpoint extends Breakpoint { protected static final String EXPIRED = "" ; protected static final String HIT_COUNT = "" ; protected static final String TYPE_NAME = "" ; protected static final String INSTALL_COUNT = "" ; protected String fInstalledTypeName = null ; protected void setTypeName ( String typeName ) throws CoreException { setAttribute ( TYPE_NAME , typeName ) ; } public String getTypeName ( ) throws CoreException { if ( fInstalledTypeName == null ) { return ensureMarker ( ) . getAttribute ( TYPE_NAME , null ) ; } return fInstalledTypeName ; } public String getModelIdentifier ( ) { return RdtDebugModel . getModelIdentifier ( ) ; } protected void register ( boolean register ) throws CoreException { DebugPlugin plugin = DebugPlugin . getDefault ( ) ; if ( plugin != null && register ) { plugin . getBreakpointManager ( ) . addBreakpoint ( this ) ; } else { setRegistered ( false ) ; } } public boolean isInstalled ( ) throws CoreException { return ensureMarker ( ) . getAttribute ( INSTALL_COUNT , ) > ; } } package org . rubypeople . rdt . internal . debug . core . breakpoints ; import java . util . Map ; import java . util . regex . Pattern ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . debug . core . IRubyMethodBreakpoint ; public class RubyMethodBreakpoint extends RubyLineBreakpoint implements IRubyMethodBreakpoint { private static final String RUBY_METHOD_BREAKPOINT = "" ; private static final String METHOD_NAME = "" ; private static final String ENTRY = "" ; private static final String EXIT = "" ; private String fMethodName = null ; private Pattern fPattern ; public RubyMethodBreakpoint ( ) { } public RubyMethodBreakpoint ( final IResource resource , final String typePattern , final String methodName , final boolean entry , final boolean exit , final int lineNumber , final int charStart , final int charEnd , final int hitCount , final boolean register , final Map attributes ) throws CoreException { IWorkspaceRunnable wr = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { setMarker ( resource . createMarker ( RUBY_METHOD_BREAKPOINT ) ) ; addLineBreakpointAttributes ( attributes , getModelIdentifier ( ) , true , lineNumber , charStart , charEnd ) ; addMethodNameAndSignature ( attributes , methodName , null ) ; addTypeNameAndHitCount ( attributes , typePattern , hitCount ) ; attributes . put ( ENTRY , Boolean . valueOf ( entry ) ) ; attributes . put ( EXIT , Boolean . valueOf ( exit ) ) ; ensureMarker ( ) . setAttributes ( attributes ) ; register ( register ) ; } } ; run ( getMarkerRule ( resource ) , wr ) ; String type = convertToRegularExpression ( typePattern ) ; fPattern = Pattern . compile ( type ) ; } private void addMethodNameAndSignature ( Map attributes , String methodName , String methodSignature ) { if ( methodName != null ) { attributes . put ( METHOD_NAME , methodName ) ; } fMethodName = methodName ; } public String getMethodName ( ) { return fMethodName ; } public void setMarker ( IMarker marker ) throws CoreException { super . setMarker ( marker ) ; fMethodName = marker . getAttribute ( METHOD_NAME , null ) ; String typePattern = marker . getAttribute ( TYPE_NAME , "" ) ; if ( typePattern != null ) { fPattern = Pattern . compile ( convertToRegularExpression ( typePattern ) ) ; } } private String convertToRegularExpression ( String stringMatcherPattern ) { String regex = stringMatcherPattern . replaceAll ( "" , "" ) ; regex = regex . replaceAll ( "" , "" ) ; regex = regex . replaceAll ( "" , "" ) ; return regex ; } } package org . rubypeople . rdt . internal . debug . core . breakpoints ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . debug . core . model . IBreakpoint ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; public class RubyExceptionBreakpoint extends RubyBreakpoint implements IRubyExceptionBreakpoint { private static final String RUBY_EXCEPTION_BREAKPOINT = "" ; public RubyExceptionBreakpoint ( final IResource resource , final String exception , final boolean add , final Map attributes ) throws CoreException { IWorkspaceRunnable wr = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { setMarker ( resource . createMarker ( RUBY_EXCEPTION_BREAKPOINT ) ) ; attributes . put ( IBreakpoint . ID , getModelIdentifier ( ) ) ; attributes . put ( TYPE_NAME , exception ) ; attributes . put ( ENABLED , Boolean . TRUE ) ; ensureMarker ( ) . setAttributes ( attributes ) ; register ( add ) ; } } ; run ( getMarkerRule ( resource ) , wr ) ; } } package org . rubypeople . rdt . internal . debug . core . breakpoints ; import java . util . Map ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . model . IBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyLineBreakpoint ; import org . rubypeople . rdt . debug . core . RdtDebugModel ; public class RubyLineBreakpoint extends RubyBreakpoint implements IRubyLineBreakpoint { public static final String RUBY_BREAKPOINT_MARKER = "" ; private static final String EXTERNAL_FILENAME = "" ; private int index = - ; public RubyLineBreakpoint ( ) { } public RubyLineBreakpoint ( IResource resource , String fileName , String typeName , int lineNumber , int charStart , int charEnd , int hitCount , boolean add , Map attributes ) throws DebugException { this ( resource , fileName , typeName , lineNumber , charStart , charEnd , hitCount , add , attributes , RUBY_BREAKPOINT_MARKER ) ; } protected RubyLineBreakpoint ( final IResource resource , final String fileName , final String typeName , final int lineNumber , final int charStart , final int charEnd , final int hitCount , final boolean add , final Map attributes , final String markerType ) throws DebugException { IWorkspaceRunnable wr = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { setMarker ( resource . createMarker ( RUBY_BREAKPOINT_MARKER ) ) ; if ( resource . equals ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ) { attributes . put ( EXTERNAL_FILENAME , fileName ) ; } addLineBreakpointAttributes ( attributes , getModelIdentifier ( ) , true , lineNumber , charStart , charEnd ) ; addTypeNameAndHitCount ( attributes , typeName , hitCount ) ; ensureMarker ( ) . setAttributes ( attributes ) ; register ( add ) ; } } ; run ( getMarkerRule ( resource ) , wr ) ; } public void addLineBreakpointAttributes ( Map < String , Object > attributes , String modelIdentifier , boolean enabled , int lineNumber , int charStart , int charEnd ) { attributes . put ( IBreakpoint . ID , modelIdentifier ) ; attributes . put ( IBreakpoint . ENABLED , Boolean . valueOf ( enabled ) ) ; attributes . put ( IMarker . LINE_NUMBER , new Integer ( lineNumber ) ) ; attributes . put ( IMarker . CHAR_START , new Integer ( charStart ) ) ; attributes . put ( IMarker . CHAR_END , new Integer ( charEnd ) ) ; } public void addTypeNameAndHitCount ( Map < String , Object > attributes , String typeName , int hitCount ) { attributes . put ( TYPE_NAME , typeName ) ; if ( hitCount > ) { attributes . put ( HIT_COUNT , new Integer ( hitCount ) ) ; attributes . put ( EXPIRED , Boolean . FALSE ) ; } } public String getFileName ( ) throws CoreException { IResource resource = ensureMarker ( ) . getResource ( ) ; if ( resource . equals ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ) { return ensureMarker ( ) . getAttribute ( EXTERNAL_FILENAME , "" ) ; } return resource . getName ( ) ; } public int getLineNumber ( ) throws CoreException { return ensureMarker ( ) . getAttribute ( IMarker . LINE_NUMBER , - ) ; } public int getCharStart ( ) throws CoreException { return ensureMarker ( ) . getAttribute ( IMarker . CHAR_START , - ) ; } public int getCharEnd ( ) throws CoreException { return ensureMarker ( ) . getAttribute ( IMarker . CHAR_END , - ) ; } public static String getMarkerType ( ) { return RUBY_BREAKPOINT_MARKER ; } public String getModelIdentifier ( ) { return RdtDebugModel . getModelIdentifier ( ) ; } public int getIndex ( ) { return index ; } public void setIndex ( int index ) { this . index = index ; } public String getCondition ( ) throws CoreException { return null ; } public boolean isConditionEnabled ( ) throws CoreException { return false ; } public boolean isConditionSuspendOnTrue ( ) throws CoreException { return false ; } public void setCondition ( String condition ) throws CoreException { } public void setConditionEnabled ( boolean enabled ) throws CoreException { } public void setConditionSuspendOnTrue ( boolean suspendOnTrue ) throws CoreException { } public boolean supportsCondition ( ) { return false ; } } package org . rubypeople . rdt . internal . debug . core ; import java . io . IOException ; import org . eclipse . core . resources . IMarkerDelta ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . model . IBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyLineBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyMethodBreakpoint ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . commands . AbstractDebuggerConnection ; import org . rubypeople . rdt . internal . debug . core . commands . BreakpointCommand ; import org . rubypeople . rdt . internal . debug . core . commands . ClassicDebuggerConnection ; import org . rubypeople . rdt . internal . debug . core . commands . GenericCommand ; import org . rubypeople . rdt . internal . debug . core . commands . RubyDebugConnection ; import org . rubypeople . rdt . internal . debug . core . model . IRubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyEvaluationResult ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . rubypeople . rdt . internal . debug . core . model . RubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyThread ; import org . rubypeople . rdt . internal . debug . core . model . RubyVariable ; import org . rubypeople . rdt . internal . debug . core . model . ThreadInfo ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . ErrorReader ; import org . rubypeople . rdt . internal . debug . core . parsing . FramesReader ; import org . rubypeople . rdt . internal . debug . core . parsing . LoadResultReader ; import org . rubypeople . rdt . internal . debug . core . parsing . SuspensionReader ; import org . rubypeople . rdt . internal . debug . core . parsing . ThreadInfoReader ; import org . rubypeople . rdt . internal . debug . core . parsing . VariableReader ; public class RubyDebuggerProxy { public final static String DEBUGGER_ACTIVE_KEY = "" ; private AbstractDebuggerConnection debuggerConnection ; private IRubyDebugTarget debugTarget ; private RubyLoop rubyLoop ; private ICommandFactory commandFactory ; private Thread threadUpdater ; private Thread errorReader ; private boolean isLoopFinished ; public RubyDebuggerProxy ( IRubyDebugTarget debugTarget , boolean isRubyDebug ) { this . debugTarget = debugTarget ; debugTarget . setRubyDebuggerProxy ( this ) ; commandFactory = isRubyDebug ? new RubyDebugCommandFactory ( ) : new ClassicDebuggerCommandFactory ( ) ; debuggerConnection = isRubyDebug ? new RubyDebugConnection ( debugTarget . getHost ( ) , debugTarget . getPort ( ) ) : new ClassicDebuggerConnection ( debugTarget . getPort ( ) ) ; } public boolean checkConnection ( ) { return debuggerConnection . isCommandPortConnected ( ) ; } public void start ( ) throws RubyProcessingException , IOException { isLoopFinished = false ; debuggerConnection . connect ( ) ; this . setBreakPoints ( ) ; this . startRubyLoop ( ) ; } public void stop ( ) throws IOException { if ( rubyLoop == null ) { return ; } rubyLoop . setShouldStop ( ) ; rubyLoop . interrupt ( ) ; closeConnection ( ) ; } protected void setBreakPoints ( ) throws IOException { IBreakpoint [ ] breakpoints = DebugPlugin . getDefault ( ) . getBreakpointManager ( ) . getBreakpoints ( IRubyDebugTarget . MODEL_IDENTIFIER ) ; for ( int i = ; i < breakpoints . length ; i ++ ) { this . addBreakpoint ( breakpoints [ i ] ) ; } } public void addBreakpoint ( IBreakpoint breakpoint ) { try { if ( breakpoint . isEnabled ( ) ) { if ( breakpoint instanceof IRubyExceptionBreakpoint ) { String command = commandFactory . createCatchOn ( ( IRubyExceptionBreakpoint ) breakpoint ) ; new BreakpointCommand ( command ) . execute ( debuggerConnection ) ; } else if ( breakpoint instanceof IRubyMethodBreakpoint ) { IRubyMethodBreakpoint rubymethodBreakpoint = ( IRubyMethodBreakpoint ) breakpoint ; String command = commandFactory . createAddMethodBreakpoint ( rubymethodBreakpoint . getFileName ( ) , rubymethodBreakpoint . getTypeName ( ) , rubymethodBreakpoint . getMethodName ( ) , rubymethodBreakpoint . getLineNumber ( ) ) ; int index = new BreakpointCommand ( command ) . executeWithResult ( debuggerConnection ) ; rubymethodBreakpoint . setIndex ( index ) ; } else if ( breakpoint instanceof IRubyLineBreakpoint ) { IRubyLineBreakpoint rubyLineBreakpoint = ( IRubyLineBreakpoint ) breakpoint ; String command = commandFactory . createAddBreakpoint ( rubyLineBreakpoint . getFileName ( ) , rubyLineBreakpoint . getLineNumber ( ) ) ; int index = new BreakpointCommand ( command ) . executeWithResult ( debuggerConnection ) ; rubyLineBreakpoint . setIndex ( index ) ; } } } catch ( IOException e ) { RdtDebugCorePlugin . log ( e ) ; } catch ( CoreException e ) { RdtDebugCorePlugin . log ( e ) ; } } public void removeBreakpoint ( IBreakpoint breakpoint ) { try { if ( breakpoint instanceof IRubyExceptionBreakpoint ) { String command = commandFactory . createCatchOff ( ( IRubyExceptionBreakpoint ) breakpoint ) ; if ( command != null ) new BreakpointCommand ( command ) . execute ( debuggerConnection ) ; } else if ( breakpoint instanceof IRubyLineBreakpoint ) { IRubyLineBreakpoint rubyLineBreakpoint = ( IRubyLineBreakpoint ) breakpoint ; if ( rubyLineBreakpoint . getIndex ( ) != - ) { String command = commandFactory . createRemoveBreakpoint ( rubyLineBreakpoint . getIndex ( ) ) ; int deletedIndex = new BreakpointCommand ( command ) . executeWithResult ( debuggerConnection ) ; rubyLineBreakpoint . setIndex ( - ) ; } } } catch ( IOException e ) { RdtDebugCorePlugin . log ( e ) ; } catch ( CoreException e ) { RdtDebugCorePlugin . log ( e ) ; } } public void updateBreakpoint ( IBreakpoint breakpoint , IMarkerDelta markerDelta ) { this . removeBreakpoint ( breakpoint ) ; this . addBreakpoint ( breakpoint ) ; } public void startRubyLoop ( ) throws DebuggerNotFoundException , IOException { debuggerConnection . start ( ) ; rubyLoop = new RubyLoop ( ) ; rubyLoop . start ( ) ; Runnable runnable = new Runnable ( ) { public void run ( ) { try { RdtDebugCorePlugin . debug ( "" ) ; while ( debuggerConnection . getCommandReadStrategy ( ) . isConnected ( ) ) { new ErrorReader ( debuggerConnection . getCommandReadStrategy ( ) ) . read ( ) ; } } catch ( Exception e ) { RdtDebugCorePlugin . log ( e ) ; } finally { RdtDebugCorePlugin . debug ( "" ) ; } } ; } ; errorReader = new Thread ( runnable , "" ) ; errorReader . start ( ) ; Runnable threadListener = new Runnable ( ) { public void run ( ) { try { RdtDebugCorePlugin . debug ( "" ) ; Thread . sleep ( ) ; GenericCommand cmd = null ; while ( cmd == null || ( cmd != null && cmd . getReadStrategy ( ) . isConnected ( ) ) ) { if ( ! getDebugTarget ( ) . isSuspended ( ) ) { String command = commandFactory . createReadThreads ( ) ; cmd = new GenericCommand ( command , true ) ; cmd . execute ( debuggerConnection ) ; ThreadInfo [ ] threadInfos = new ThreadInfoReader ( cmd . getReadStrategy ( ) ) . readThreads ( ) ; ( ( RubyDebugTarget ) getDebugTarget ( ) ) . updateThreads ( threadInfos ) ; } Thread . sleep ( ) ; } } catch ( Exception e ) { RdtDebugCorePlugin . log ( e ) ; } finally { RdtDebugCorePlugin . debug ( "" ) ; } } ; } ; threadUpdater = new Thread ( threadListener , "" ) ; threadUpdater . start ( ) ; } public void resume ( RubyThread thread ) { try { println ( commandFactory . createResume ( thread ) ) ; } catch ( IOException e ) { } } protected void println ( String s ) throws IOException { try { new GenericCommand ( s , false ) . execute ( debuggerConnection ) ; } catch ( IOException e ) { RdtDebugCorePlugin . debug ( "" , e ) ; throw e ; } } protected IRubyDebugTarget getDebugTarget ( ) { return debugTarget ; } public RubyVariable [ ] readVariables ( RubyStackFrame frame ) throws DebugException { try { this . println ( commandFactory . createReadLocalVariables ( frame ) ) ; return new VariableReader ( getMultiReaderStrategy ( ) ) . readVariables ( frame ) ; } catch ( Exception e ) { throw new DebugException ( new Status ( IStatus . ERROR , RdtDebugCorePlugin . getPluginIdentifier ( ) , - , e . getMessage ( ) , e ) ) ; } } public RubyVariable [ ] readInstanceVariables ( RubyVariable variable ) { try { this . println ( commandFactory . createReadInstanceVariable ( variable ) ) ; return new VariableReader ( getMultiReaderStrategy ( ) ) . readVariables ( variable ) ; } catch ( Exception ioex ) { ioex . printStackTrace ( ) ; throw new RuntimeException ( ioex . getMessage ( ) ) ; } } public RubyVariable readInspectExpression ( IRubyStackFrame frame , String expression ) throws RubyProcessingException { try { expression = expression . replaceAll ( "" , "" ) ; RubyEvaluationResult result = new RubyEvaluationResult ( expression , frame . getThread ( ) ) ; this . println ( commandFactory . createInspect ( frame , expression ) ) ; RubyVariable [ ] variables = new VariableReader ( getMultiReaderStrategy ( ) ) . readVariables ( frame ) ; if ( variables . length == ) { return null ; } else { result . setValue ( variables [ ] . getValue ( ) ) ; return variables [ ] ; } } catch ( IOException ioex ) { ioex . printStackTrace ( ) ; throw new RuntimeException ( ioex . getMessage ( ) ) ; } } public IEvaluationResult evaluate ( RubyStackFrame frame , String expression ) { expression = expression . replaceAll ( "" , "" ) ; expression = expression . replaceAll ( "" , "" ) ; expression = expression . trim ( ) ; RubyEvaluationResult result = new RubyEvaluationResult ( expression , frame . getThread ( ) ) ; try { this . println ( commandFactory . createInspect ( frame , expression ) ) ; RubyVariable [ ] variables = new VariableReader ( getMultiReaderStrategy ( ) ) . readVariables ( frame ) ; if ( variables . length > ) { result . setValue ( variables [ ] . getValue ( ) ) ; } } catch ( IOException ioex ) { DebugException ex = new DebugException ( new Status ( IStatus . ERROR , RdtDebugCorePlugin . PLUGIN_ID , DebugException . INTERNAL_ERROR , ioex . getMessage ( ) , ioex ) ) ; result . setException ( ex ) ; } catch ( RubyProcessingException e ) { DebugException ex = new DebugException ( new Status ( IStatus . ERROR , RdtDebugCorePlugin . PLUGIN_ID , DebugException . TARGET_REQUEST_FAILED , e . getMessage ( ) , e ) ) ; result . setException ( ex ) ; } return result ; } public void sendStepOverEnd ( RubyStackFrame stackFrame ) { try { this . println ( commandFactory . createStepOver ( stackFrame ) ) ; } catch ( Exception e ) { RdtDebugCorePlugin . log ( e ) ; } } public void sendStepReturnEnd ( RubyStackFrame stackFrame ) { try { this . println ( commandFactory . createStepReturn ( stackFrame ) ) ; } catch ( Exception e ) { RdtDebugCorePlugin . log ( e ) ; } } public void sendStepIntoEnd ( RubyStackFrame stackFrame ) { try { this . println ( commandFactory . createStepInto ( stackFrame ) ) ; } catch ( Exception e ) { RdtDebugCorePlugin . log ( e ) ; } } public void sendThreadStop ( RubyThread thread ) { try { String command = commandFactory . createThreadStop ( thread ) ; new GenericCommand ( command , true ) . execute ( debuggerConnection ) ; } catch ( Exception e ) { RdtDebugCorePlugin . log ( e ) ; } } public RubyStackFrame [ ] readFrames ( RubyThread thread ) { try { this . println ( commandFactory . createReadFrames ( thread ) ) ; return new FramesReader ( getMultiReaderStrategy ( ) ) . readFrames ( thread ) ; } catch ( IOException e ) { RdtDebugCorePlugin . log ( e ) ; return null ; } } public ThreadInfo [ ] readThreads ( ) { try { String command = commandFactory . createReadThreads ( ) ; new GenericCommand ( command , true ) . execute ( debuggerConnection ) ; return new ThreadInfoReader ( getMultiReaderStrategy ( ) ) . readThreads ( ) ; } catch ( Exception e ) { RdtDebugCorePlugin . log ( e ) ; return null ; } } public IStatus readLoadResult ( String filename ) { try { this . println ( commandFactory . createLoad ( filename ) ) ; return new LoadResultReader ( getMultiReaderStrategy ( ) ) . readLoadResult ( ) ; } catch ( Exception e ) { return new Status ( IStatus . ERROR , RdtDebugCorePlugin . getPluginIdentifier ( ) , - , e . getMessage ( ) , e ) ; } } public void closeConnection ( ) throws IOException { debuggerConnection . exit ( ) ; } private AbstractReadStrategy getMultiReaderStrategy ( ) { return debuggerConnection . getCommandReadStrategy ( ) ; } class RubyLoop extends Thread { public RubyLoop ( ) { this . setName ( "" ) ; } public void setShouldStop ( ) { } public void run ( ) { try { System . setProperty ( DEBUGGER_ACTIVE_KEY , "" ) ; RdtDebugCorePlugin . debug ( "" ) ; while ( true ) { final SuspensionPoint hit = new SuspensionReader ( getMultiReaderStrategy ( ) ) . readSuspension ( ) ; if ( hit == null ) { break ; } RdtDebugCorePlugin . debug ( hit ) ; new Thread ( ) { public void run ( ) { getDebugTarget ( ) . suspensionOccurred ( hit ) ; } } . start ( ) ; } } catch ( DebuggerNotFoundException ex ) { throw ex ; } catch ( Exception ex ) { RdtDebugCorePlugin . debug ( "" , ex ) ; } finally { System . setProperty ( DEBUGGER_ACTIVE_KEY , "" ) ; try { getDebugTarget ( ) . terminate ( ) ; closeConnection ( ) ; } catch ( Exception e ) { RdtDebugCorePlugin . log ( e ) ; } RdtDebugCorePlugin . debug ( "" ) ; } } } } package org . rubypeople . rdt . internal . debug . core . commands ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . EvalReader ; import org . rubypeople . rdt . internal . debug . core . parsing . XmlStreamReader ; public class EvalCommand extends AbstractCommand { public EvalCommand ( String command , boolean isControl ) { super ( command , isControl ) ; } @ Override protected XmlStreamReader createResultReader ( AbstractReadStrategy readStrategy ) { return new EvalReader ( readStrategy ) ; } public EvalReader getEvalReader ( ) { return ( EvalReader ) getResultReader ( ) ; } } package org . rubypeople . rdt . internal . debug . core . commands ; import java . io . IOException ; import org . rubypeople . rdt . internal . debug . core . DebuggerNotFoundException ; import org . rubypeople . rdt . internal . debug . core . SuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . SuspensionReader ; import org . rubypeople . rdt . internal . debug . core . parsing . XmlStreamReader ; import org . rubypeople . rdt . internal . debug . core . parsing . XmlStreamReaderException ; import org . xmlpull . v1 . XmlPullParserException ; public class StepCommand extends AbstractCommand { public StepCommand ( String command ) { super ( command , false ) ; } @ Override protected XmlStreamReader createResultReader ( AbstractReadStrategy readStrategy ) { return new SuspensionReader ( readStrategy ) ; } public SuspensionReader getSuspensionReader ( ) { return ( SuspensionReader ) getResultReader ( ) ; } public SuspensionPoint readSuspension ( AbstractDebuggerConnection debuggerConnection ) throws DebuggerNotFoundException , IOException , XmlPullParserException , XmlStreamReaderException { execute ( debuggerConnection ) ; return getSuspensionReader ( ) . readSuspension ( ) ; } } package org . rubypeople . rdt . internal . debug . core . commands ; import java . io . IOException ; import org . rubypeople . rdt . internal . debug . core . DebuggerNotFoundException ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . BreakpointModificationReader ; import org . rubypeople . rdt . internal . debug . core . parsing . XmlStreamReader ; public class BreakpointCommand extends AbstractCommand { public BreakpointCommand ( String command ) { super ( command , true ) ; } @ Override protected XmlStreamReader createResultReader ( AbstractReadStrategy readStrategy ) { return new BreakpointModificationReader ( readStrategy ) ; } public BreakpointModificationReader getBreakpointAddedReader ( ) { return ( BreakpointModificationReader ) getResultReader ( ) ; } public int executeWithResult ( AbstractDebuggerConnection connection ) throws DebuggerNotFoundException , IOException { execute ( connection ) ; return getBreakpointAddedReader ( ) . readBreakpointNo ( ) ; } } package org . rubypeople . rdt . internal . debug . core . commands ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . XmlStreamReader ; public class GenericCommand extends AbstractCommand { private AbstractReadStrategy readStrategy ; public GenericCommand ( String command , boolean isControl ) { super ( command , isControl ) ; } @ Override protected XmlStreamReader createResultReader ( AbstractReadStrategy readStrategy ) { this . readStrategy = readStrategy ; return null ; } public AbstractReadStrategy getReadStrategy ( ) { return readStrategy ; } } package org . rubypeople . rdt . internal . debug . core . commands ; import java . io . IOException ; import org . rubypeople . rdt . internal . debug . core . DebuggerNotFoundException ; import org . rubypeople . rdt . internal . debug . core . parsing . SuspensionReader ; public class ClassicDebuggerConnection extends AbstractDebuggerConnection { private boolean isStarted ; public ClassicDebuggerConnection ( int port ) { super ( port ) ; } @ Override public void connect ( ) throws DebuggerNotFoundException , IOException { createCommandConnection ( ) ; } @ Override public SuspensionReader start ( ) throws DebuggerNotFoundException , IOException { StepCommand stepCommand = new StepCommand ( "" ) ; stepCommand . execute ( this ) ; isStarted = true ; return stepCommand . getSuspensionReader ( ) ; } @ Override public boolean isStarted ( ) { return isStarted ; } } package org . rubypeople . rdt . internal . debug . core . commands ; import java . io . IOException ; import org . rubypeople . rdt . internal . debug . core . DebuggerNotFoundException ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . XmlStreamReader ; public abstract class AbstractCommand { private String command ; private boolean isControl ; private XmlStreamReader resultReader ; protected AbstractCommand ( String command , boolean isControl ) { this . command = command ; this . isControl = isControl ; } public void execute ( AbstractDebuggerConnection debuggerConnection ) throws DebuggerNotFoundException , IOException { AbstractReadStrategy readStrategy = debuggerConnection . sendCommand ( this ) ; resultReader = createResultReader ( readStrategy ) ; } protected abstract XmlStreamReader createResultReader ( AbstractReadStrategy readStrategy ) ; public XmlStreamReader getResultReader ( ) { if ( ! isExecuted ( ) ) { throw new IllegalStateException ( "" ) ; } return resultReader ; } public String getCommand ( ) { return command ; } public boolean isControl ( ) { return isControl ; } public boolean isExecuted ( ) { return resultReader != null ; } } package org . rubypeople . rdt . internal . debug . core . commands ; import java . io . IOException ; import java . io . PrintWriter ; import java . net . Socket ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . internal . debug . core . DebuggerNotFoundException ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . MultiReaderStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . SuspensionReader ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserException ; import org . xmlpull . v1 . XmlPullParserFactory ; public abstract class AbstractDebuggerConnection { private int commandPort ; private Socket commandSocket ; private PrintWriter writer ; private AbstractReadStrategy commandReadStrategy ; private String host ; public AbstractDebuggerConnection ( int port ) { this ( "" , port ) ; } public AbstractDebuggerConnection ( String host , int port ) { super ( ) ; this . host = host ; this . commandPort = port ; } public abstract void connect ( ) throws DebuggerNotFoundException , IOException ; public abstract SuspensionReader start ( ) throws DebuggerNotFoundException , IOException ; public abstract boolean isStarted ( ) ; protected AbstractReadStrategy sendCommand ( AbstractCommand command ) throws DebuggerNotFoundException , IOException { if ( ! isCommandPortConnected ( ) ) { throw new IllegalStateException ( command + "" ) ; } RdtDebugCorePlugin . debug ( "" + command . getCommand ( ) ) ; getWriter ( ) . println ( command . getCommand ( ) ) ; return getCommandReadStrategy ( ) ; } public AbstractReadStrategy getCommandReadStrategy ( ) { return commandReadStrategy ; } protected void createCommandConnection ( ) throws DebuggerNotFoundException , IOException { getSocket ( ) ; XmlPullParser xpp = createXpp ( commandSocket ) ; commandReadStrategy = new MultiReaderStrategy ( xpp ) ; } public boolean isCommandPortConnected ( ) { return commandSocket != null ; } protected Socket getSocket ( ) throws IOException , DebuggerNotFoundException { if ( commandSocket == null ) { commandSocket = acquireSocket ( host , commandPort ) ; if ( commandSocket == null ) { throw new DebuggerNotFoundException ( "" + commandPort ) ; } } return commandSocket ; } protected static Socket acquireSocket ( String host , int port ) throws IOException { Socket socket = null ; int tryCount = ; for ( int i = ; i < tryCount ; i ++ ) { try { socket = new Socket ( host , port ) ; break ; } catch ( IOException e ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e1 ) { } } } return socket ; } private PrintWriter getWriter ( ) throws IOException , DebuggerNotFoundException { if ( writer == null ) { writer = new PrintWriter ( commandSocket . getOutputStream ( ) , true ) ; } return writer ; } protected static XmlPullParser createXpp ( Socket socket ) { XmlPullParser xpp = null ; try { XmlPullParserFactory factory = XmlPullParserFactory . newInstance ( "" , null ) ; xpp = factory . newPullParser ( ) ; xpp . setInput ( socket . getInputStream ( ) , "" ) ; } catch ( XmlPullParserException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return xpp ; } public int getCommandPort ( ) { return commandPort ; } public void exit ( ) throws IOException { if ( commandSocket != null ) { commandSocket . close ( ) ; } } } package org . rubypeople . rdt . internal . debug . core . commands ; import java . io . IOException ; import org . rubypeople . rdt . internal . debug . core . DebuggerNotFoundException ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . SuspensionReader ; public class RubyDebugConnection extends AbstractDebuggerConnection { private boolean isStarted ; public RubyDebugConnection ( String host , int port ) { super ( host , port ) ; } @ Override public void connect ( ) throws DebuggerNotFoundException , IOException { createCommandConnection ( ) ; } @ Override public SuspensionReader start ( ) throws DebuggerNotFoundException , IOException { AbstractReadStrategy strategy = sendControlCommand ( new GenericCommand ( "" , true ) ) ; isStarted = true ; return new SuspensionReader ( strategy ) ; } private AbstractReadStrategy sendControlCommand ( AbstractCommand command ) throws IOException { return sendCommand ( command ) ; } @ Override public void exit ( ) throws IOException { GenericCommand command = new GenericCommand ( "" , true ) ; command . execute ( this ) ; } @ Override public boolean isStarted ( ) { return isStarted ; } } package org . rubypeople . rdt . internal . debug . core ; public class ExceptionSuspensionPoint extends SuspensionPoint { private String exceptionMessage ; private String exceptionType ; public boolean isBreakpoint ( ) { return false ; } public boolean isException ( ) { return true ; } public boolean isStep ( ) { return false ; } public String toString ( ) { return this . getExceptionType ( ) + "" + this . getExceptionMessage ( ) ; } public String getExceptionMessage ( ) { return exceptionMessage ; } public String getExceptionType ( ) { return exceptionType ; } public void setExceptionMessage ( String exceptionMessage ) { this . exceptionMessage = exceptionMessage ; } public void setExceptionType ( String exceptionType ) { this . exceptionType = exceptionType ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . rubypeople . rdt . internal . debug . core . model . ThreadInfo ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserException ; public class ThreadInfoReader extends XmlStreamReader { private List < ThreadInfo > threads = new ArrayList < ThreadInfo > ( ) ; public ThreadInfoReader ( XmlPullParser xpp ) { super ( xpp ) ; } public ThreadInfoReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } public ThreadInfo [ ] readThreads ( ) throws XmlPullParserException , IOException , XmlStreamReaderException { this . read ( ) ; return threads . toArray ( new ThreadInfo [ threads . size ( ) ] ) ; } protected boolean processStartElement ( XmlPullParser xpp ) { String name = xpp . getName ( ) ; if ( name . equals ( "" ) ) { return true ; } if ( name . equals ( "" ) ) { int id = Integer . parseInt ( xpp . getAttributeValue ( "" , "" ) ) ; String status = xpp . getAttributeValue ( "" , "" ) ; threads . add ( new ThreadInfo ( id , status ) ) ; return true ; } return false ; } protected boolean processEndElement ( XmlPullParser xpp ) { return xpp . getName ( ) . equals ( "" ) ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import java . io . IOException ; import java . net . SocketException ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserException ; public class MultiReaderStrategy extends AbstractReadStrategy { private Map < XmlStreamReader , Thread > threads ; private XmlStreamReader currentReader ; private boolean isConnected ; public MultiReaderStrategy ( XmlPullParser xpp ) { super ( xpp ) ; isConnected = true ; threads = new HashMap < XmlStreamReader , Thread > ( ) ; new Thread ( "" ) { public void run ( ) { try { readLoop ( ) ; } catch ( SocketException e ) { RdtDebugCorePlugin . debug ( "" ) ; } catch ( Exception e ) { RdtDebugCorePlugin . debug ( "" , e ) ; e . printStackTrace ( ) ; } finally { isConnected = false ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } releaseAllReaders ( ) ; } } } . start ( ) ; } protected void readLoop ( ) throws XmlPullParserException , IOException , XmlStreamReaderException { RdtDebugCorePlugin . debug ( "" ) ; int eventType = xpp . getEventType ( ) ; do { if ( eventType == XmlPullParser . START_TAG ) { this . dispatchStartTag ( ) ; } else if ( eventType == XmlPullParser . END_TAG && currentReader != null ) { if ( currentReader . processEndElement ( xpp ) ) { this . removeReader ( currentReader ) ; currentReader = null ; } } else if ( eventType == XmlPullParser . TEXT ) { if ( currentReader != null ) { currentReader . processContent ( xpp . getText ( ) ) ; } } eventType = xpp . next ( ) ; } while ( eventType != XmlPullParser . END_DOCUMENT ) ; RdtDebugCorePlugin . debug ( "" ) ; } protected void dispatchStartTag ( ) throws XmlPullParserException , IOException , XmlStreamReaderException { RdtDebugCorePlugin . debug ( "" + xpp . getName ( ) ) ; if ( currentReader != null ) { if ( currentReader . processStartElement ( xpp ) ) { return ; } else { RdtDebugCorePlugin . debug ( "" + xpp . getName ( ) ) ; currentReader = null ; } } int missed = ; RdtDebugCorePlugin . debug ( "" + xpp . getName ( ) ) ; do { findReaderForTag ( ) ; if ( currentReader == null ) { missed += ; RdtDebugCorePlugin . debug ( "" + xpp . getName ( ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } } while ( currentReader == null && missed < ) ; } private synchronized void findReaderForTag ( ) throws XmlStreamReaderException { for ( XmlStreamReader streamReader : threads . keySet ( ) ) { if ( streamReader . processStartElement ( xpp ) ) { currentReader = streamReader ; break ; } } } protected synchronized void releaseAllReaders ( ) { for ( Iterator < Map . Entry < XmlStreamReader , Thread > > iter = threads . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Thread thread = iter . next ( ) . getValue ( ) ; thread . interrupt ( ) ; iter . remove ( ) ; } } protected synchronized void removeReader ( XmlStreamReader streamReader ) { threads . get ( streamReader ) . interrupt ( ) ; threads . remove ( streamReader ) ; } protected synchronized void addReader ( XmlStreamReader streamReader ) { threads . put ( streamReader , Thread . currentThread ( ) ) ; } public void readElement ( XmlStreamReader streamReader ) throws IOException { readElement ( streamReader , Long . MAX_VALUE ) ; } public void readElement ( XmlStreamReader streamReader , long maxWaitTime ) throws IOException { if ( ! isConnected ) { throw new IOException ( "" ) ; } this . addReader ( streamReader ) ; try { RdtDebugCorePlugin . debug ( "" + Thread . currentThread ( ) ) ; Thread . sleep ( maxWaitTime ) ; streamReader . setWaitTimeExpired ( true ) ; } catch ( InterruptedException e ) { RdtDebugCorePlugin . debug ( "" + Thread . currentThread ( ) ) ; } } public boolean isConnected ( ) { return isConnected ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import java . io . IOException ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserException ; public abstract class XmlStreamReader { private AbstractReadStrategy readStrategy ; private boolean isWaitTimeExpired ; public XmlStreamReader ( XmlPullParser xpp ) { this ( new SingleReaderStrategy ( xpp ) ) ; } public XmlStreamReader ( AbstractReadStrategy readStrategy ) { this . readStrategy = readStrategy ; this . isWaitTimeExpired = false ; } public void read ( ) throws XmlPullParserException , IOException , XmlStreamReaderException { this . readStrategy . readElement ( this ) ; } public void read ( long maxWaitTime ) throws XmlPullParserException , IOException , XmlStreamReaderException { this . readStrategy . readElement ( this , maxWaitTime ) ; } protected abstract boolean processStartElement ( XmlPullParser xpp ) throws XmlStreamReaderException ; protected boolean processEndElement ( XmlPullParser xpp ) { String name = xpp . getName ( ) ; RdtDebugCorePlugin . debug ( "" + this . getClass ( ) . getName ( ) + "" + name ) ; return true ; } public void processContent ( String text ) { } public boolean isWaitTimeExpired ( ) { return isWaitTimeExpired ; } protected void setWaitTimeExpired ( boolean isWaitTimeExpired ) { this . isWaitTimeExpired = isWaitTimeExpired ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . xmlpull . v1 . XmlPullParser ; public class LoadResultReader extends XmlStreamReader { private LoadResult loadResult ; public LoadResultReader ( XmlPullParser xpp ) { super ( xpp ) ; } public LoadResultReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } public IStatus readLoadResult ( ) throws RubyProcessingException { this . loadResult = new LoadResult ( ) ; try { this . read ( ) ; } catch ( Exception ex ) { RdtDebugCorePlugin . log ( ex ) ; } int code = IStatus . ERROR ; if ( loadResult . isOk ( ) ) code = IStatus . OK ; StringBuilder builder = new StringBuilder ( ) ; if ( loadResult . exceptionType != null ) builder . append ( loadResult . exceptionType ) . append ( "" ) ; builder . append ( loadResult . exceptionMessage ) ; return new Status ( code , RdtDebugCorePlugin . PLUGIN_ID , - , builder . toString ( ) , null ) ; } protected boolean processStartElement ( XmlPullParser xpp ) { String name = xpp . getName ( ) ; if ( name . equals ( "" ) ) { this . loadResult . setFileName ( xpp . getAttributeValue ( "" , "" ) ) ; this . loadResult . setExceptionType ( xpp . getAttributeValue ( "" , "" ) ) ; this . loadResult . setExceptionMessage ( xpp . getAttributeValue ( "" , "" ) ) ; return true ; } return false ; } public class LoadResult { private String fileName ; private String exceptionMessage ; private String exceptionType ; public String getExceptionMessage ( ) { return exceptionMessage ; } public void setExceptionMessage ( String exceptionMessage ) { this . exceptionMessage = exceptionMessage ; } public String getExceptionType ( ) { return exceptionType ; } public void setExceptionType ( String exceptionType ) { this . exceptionType = exceptionType ; } public String getFileName ( ) { return fileName ; } public void setFileName ( String fileName ) { this . fileName = fileName ; } public boolean isOk ( ) { return exceptionType == null ; } } } package org . rubypeople . rdt . internal . debug . core . parsing ; import java . io . IOException ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserException ; public abstract class AbstractReadStrategy { protected XmlPullParser xpp ; public AbstractReadStrategy ( XmlPullParser xpp ) { this . xpp = xpp ; } public abstract void readElement ( XmlStreamReader streamReader ) throws XmlPullParserException , IOException , XmlStreamReaderException ; public abstract void readElement ( XmlStreamReader streamReader , long maxWaitTime ) throws XmlPullParserException , IOException , XmlStreamReaderException ; public abstract boolean isConnected ( ) ; } package org . rubypeople . rdt . internal . debug . core . parsing ; public class XmlStreamReaderException extends Exception { private static final long serialVersionUID = ; public XmlStreamReaderException ( ) { super ( ) ; } public XmlStreamReaderException ( String s ) { super ( s ) ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import java . io . IOException ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . internal . debug . core . BreakpointSuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . ExceptionSuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . StepSuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . SuspensionPoint ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserException ; public class SuspensionReader extends XmlStreamReader { private SuspensionPoint suspensionPoint ; public SuspensionReader ( XmlPullParser xpp ) { super ( xpp ) ; } public SuspensionReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } public SuspensionPoint readSuspension ( ) throws XmlPullParserException , IOException , XmlStreamReaderException { this . read ( ) ; return suspensionPoint ; } protected boolean processStartElement ( XmlPullParser xpp ) throws XmlStreamReaderException { String name = xpp . getName ( ) ; if ( name . equals ( "" ) ) { suspensionPoint = new BreakpointSuspensionPoint ( ) ; } else if ( name . equals ( "" ) ) { ExceptionSuspensionPoint exceptionPoint = new ExceptionSuspensionPoint ( ) ; exceptionPoint . setExceptionMessage ( xpp . getAttributeValue ( "" , "" ) ) ; exceptionPoint . setExceptionType ( xpp . getAttributeValue ( "" , "" ) ) ; suspensionPoint = exceptionPoint ; } else if ( name . equals ( "" ) ) { StepSuspensionPoint stepPoint = new StepSuspensionPoint ( ) ; String frameNoAttribute = xpp . getAttributeValue ( "" , "" ) ; try { stepPoint . setFramesNumber ( Integer . parseInt ( frameNoAttribute ) ) ; suspensionPoint = stepPoint ; } catch ( NumberFormatException nfe ) { String message = "" + frameNoAttribute + "" + xpp . getText ( ) ; RdtDebugCorePlugin . debug ( message ) ; return false ; } } else { return false ; } suspensionPoint . setLine ( xpp . getAttributeValue ( "" , "" ) ) ; suspensionPoint . setFile ( xpp . getAttributeValue ( "" , "" ) ) ; suspensionPoint . setThreadId ( Integer . parseInt ( xpp . getAttributeValue ( "" , "" ) ) ) ; return true ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . xmlpull . v1 . XmlPullParser ; public class BreakpointModificationReader extends XmlStreamReader { private String no ; public BreakpointModificationReader ( XmlPullParser xpp ) { super ( xpp ) ; } public BreakpointModificationReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } public int readBreakpointNo ( ) throws NumberFormatException { try { this . read ( ) ; } catch ( Exception ex ) { RdtDebugCorePlugin . log ( ex ) ; return - ; } return Integer . parseInt ( no ) ; } @ Override protected boolean processStartElement ( XmlPullParser xpp ) throws XmlStreamReaderException { boolean result = false ; if ( xpp . getName ( ) . equals ( "" ) ) { no = xpp . getAttributeValue ( "" , "" ) ; result = true ; } else if ( xpp . getName ( ) . equals ( "" ) ) { no = xpp . getAttributeValue ( "" , "" ) ; result = true ; } else if ( xpp . getName ( ) . equals ( "" ) ) { no = "" ; result = true ; } return result ; } @ Override public void processContent ( String text ) { } @ Override protected boolean processEndElement ( XmlPullParser xpp ) { return xpp . getName ( ) . equals ( "" ) || xpp . getName ( ) . equals ( "" ) || xpp . getName ( ) . equals ( "" ) ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . internal . debug . core . model . RubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyThread ; import org . xmlpull . v1 . XmlPullParser ; public class FramesReader extends XmlStreamReader { private RubyThread thread ; private List < RubyStackFrame > frames ; public FramesReader ( XmlPullParser xpp ) { super ( xpp ) ; } public FramesReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } public RubyStackFrame [ ] readFrames ( RubyThread thread ) { this . thread = thread ; this . frames = new ArrayList < RubyStackFrame > ( ) ; try { this . read ( ) ; } catch ( Exception ex ) { RdtDebugCorePlugin . log ( ex ) ; return new RubyStackFrame [ ] ; } Collections . sort ( frames , new Comparator < RubyStackFrame > ( ) { public int compare ( RubyStackFrame one , RubyStackFrame two ) { return Integer . valueOf ( one . getIndex ( ) ) . compareTo ( Integer . valueOf ( two . getIndex ( ) ) ) ; } } ) ; RubyStackFrame [ ] frameArray = new RubyStackFrame [ frames . size ( ) ] ; frames . toArray ( frameArray ) ; thread . setStackFrames ( frameArray ) ; return frameArray ; } protected boolean processStartElement ( XmlPullParser xpp ) { String name = xpp . getName ( ) ; if ( name . equals ( "" ) ) { return true ; } if ( name . equals ( "" ) ) { int line = Integer . parseInt ( xpp . getAttributeValue ( "" , "" ) ) ; int index = Integer . parseInt ( xpp . getAttributeValue ( "" , "" ) ) ; String file = xpp . getAttributeValue ( "" , "" ) ; this . frames . add ( new RubyStackFrame ( thread , file , line , index ) ) ; return true ; } return false ; } protected boolean processEndElement ( XmlPullParser xpp ) { return xpp . getName ( ) . equals ( "" ) ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . xmlpull . v1 . XmlPullParser ; public class ErrorReader extends XmlStreamReader { public ErrorReader ( XmlPullParser xpp ) { super ( xpp ) ; } public ErrorReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } @ Override protected boolean processStartElement ( XmlPullParser xpp ) throws XmlStreamReaderException { return xpp . getName ( ) . equals ( "" ) || xpp . getName ( ) . equals ( "" ) ; } @ Override public void processContent ( String text ) { RdtDebugCorePlugin . log ( text , null ) ; } @ Override protected boolean processEndElement ( XmlPullParser xpp ) { return xpp . getName ( ) . equals ( "" ) || xpp . getName ( ) . equals ( "" ) ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import java . io . IOException ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserException ; public class SingleReaderStrategy extends AbstractReadStrategy { public SingleReaderStrategy ( XmlPullParser xpp ) { super ( xpp ) ; } public void readElement ( XmlStreamReader streamReader ) throws XmlPullParserException , IOException , XmlStreamReaderException { int eventType = xpp . getEventType ( ) ; do { if ( eventType == XmlPullParser . START_DOCUMENT ) { RdtDebugCorePlugin . debug ( "" ) ; } else if ( eventType == XmlPullParser . END_DOCUMENT ) { RdtDebugCorePlugin . debug ( "" ) ; break ; } else if ( eventType == XmlPullParser . START_TAG ) { streamReader . processStartElement ( xpp ) ; } else if ( eventType == XmlPullParser . END_TAG ) { streamReader . processEndElement ( xpp ) ; if ( xpp . getDepth ( ) == ) { break ; } } else if ( eventType == XmlPullParser . TEXT ) { } eventType = xpp . next ( ) ; } while ( true ) ; } @ Override public void readElement ( XmlStreamReader streamReader , long maxWaitTime ) throws XmlPullParserException , IOException , XmlStreamReaderException { readElement ( streamReader ) ; } @ Override public boolean isConnected ( ) { return true ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . xmlpull . v1 . XmlPullParser ; public class EvalReader extends XmlStreamReader { private String exceptionType ; private String exceptionMessage ; private String name ; private String value ; public EvalReader ( XmlPullParser xpp ) { super ( xpp ) ; } public EvalReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } @ Override protected boolean processStartElement ( XmlPullParser xpp ) throws XmlStreamReaderException { boolean result = false ; if ( xpp . getName ( ) . equals ( "" ) ) { exceptionType = xpp . getAttributeValue ( "" , "" ) ; exceptionMessage = xpp . getAttributeValue ( "" , "" ) ; result = true ; } else if ( xpp . getName ( ) . equals ( "" ) ) { name = xpp . getAttributeValue ( "" , "" ) ; value = xpp . getAttributeValue ( "" , "" ) ; result = true ; } return result ; } public String readEvalResult ( ) throws RubyProcessingException { try { this . read ( ) ; } catch ( Exception ex ) { RdtDebugCorePlugin . log ( ex ) ; return null ; } if ( exceptionType != null ) { throw new RubyProcessingException ( exceptionType , exceptionMessage ) ; } return value ; } @ Override public void processContent ( String text ) { } @ Override protected boolean processEndElement ( XmlPullParser xpp ) { return xpp . getName ( ) . equals ( "" ) || xpp . getName ( ) . equals ( "" ) ; } } package org . rubypeople . rdt . internal . debug . core . parsing ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . debug . core . model . IVariable ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . rubypeople . rdt . internal . debug . core . model . RubyVariable ; import org . xmlpull . v1 . XmlPullParser ; public class VariableReader extends XmlStreamReader { private IRubyStackFrame stackFrame ; private IRubyVariable parent ; private List < IVariable > variables ; private String exceptionMessage ; private String exceptionType ; public VariableReader ( XmlPullParser xpp ) { super ( xpp ) ; } public VariableReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } public RubyVariable [ ] readVariables ( IRubyVariable variable ) throws RubyProcessingException { return readVariables ( variable . getStackFrame ( ) , variable ) ; } public RubyVariable [ ] readVariables ( IRubyStackFrame stackFrame ) throws RubyProcessingException { return readVariables ( stackFrame , null ) ; } public RubyVariable [ ] readVariables ( IRubyStackFrame stackFrame , IRubyVariable parent ) throws RubyProcessingException { this . stackFrame = stackFrame ; this . parent = parent ; this . variables = new ArrayList < IVariable > ( ) ; try { this . read ( ) ; } catch ( Exception ex ) { RdtDebugCorePlugin . log ( ex ) ; return new RubyVariable [ ] ; } if ( exceptionMessage != null ) { throw new RubyProcessingException ( exceptionType , exceptionMessage ) ; } else if ( isWaitTimeExpired ( ) ) { throw new RubyProcessingException ( "" ) ; } RubyVariable [ ] variablesArray = new RubyVariable [ variables . size ( ) ] ; variables . toArray ( variablesArray ) ; return variablesArray ; } protected boolean processStartElement ( XmlPullParser xpp ) { String name = xpp . getName ( ) ; if ( name . equals ( "" ) ) { return true ; } if ( name . equals ( "" ) ) { String varName = xpp . getAttributeValue ( "" , "" ) ; String varValue = xpp . getAttributeValue ( "" , "" ) ; String kind = xpp . getAttributeValue ( "" , "" ) ; RubyVariable newVariable ; if ( varValue == null ) { newVariable = new RubyVariable ( stackFrame , varName , kind ) ; } else { String typeName = xpp . getAttributeValue ( "" , "" ) ; boolean hasChildren = xpp . getAttributeValue ( "" , "" ) . equals ( "" ) ; String objectId = xpp . getAttributeValue ( "" , "" ) ; newVariable = new RubyVariable ( stackFrame , varName , kind , varValue , typeName , hasChildren , objectId ) ; } newVariable . setParent ( parent ) ; variables . add ( newVariable ) ; return true ; } if ( name . equals ( "" ) ) { exceptionMessage = xpp . getAttributeValue ( "" , "" ) ; exceptionType = xpp . getAttributeValue ( "" , "" ) ; return true ; } return false ; } protected boolean processEndElement ( XmlPullParser xpp ) { return ! xpp . getName ( ) . equals ( "" ) ; } } package org . rubypeople . rdt . internal . debug . core ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyThread ; import org . rubypeople . rdt . internal . debug . core . model . RubyVariable ; public class RubyDebugCommandFactory implements ICommandFactory { public String createReadFrames ( RubyThread thread ) { return "" ; } public String createReadLocalVariables ( RubyStackFrame frame ) { return "" + frame . getIndex ( ) + "" ; } public String createReadGlobalVariables ( ) { return "" ; } public String createReadInstanceVariable ( RubyVariable variable ) { StringBuilder command = new StringBuilder ( ) ; return command . append ( "" + variable . getObjectId ( ) ) . toString ( ) ; } public String createStepOver ( RubyStackFrame frame ) { return "" + frame . getIndex ( ) + "" ; } public String createForcedStepOver ( RubyStackFrame frame ) { return "" + frame . getIndex ( ) + "" ; } public String createStepReturn ( RubyStackFrame frame ) { return "" + frame . getIndex ( ) + "" ; } public String createStepInto ( RubyStackFrame frame ) { return "" + frame . getIndex ( ) + "" ; } public String createForcedStepInto ( RubyStackFrame frame ) { return "" + frame . getIndex ( ) + "" ; } public String createReadThreads ( ) { return "" ; } public String createLoad ( String filename ) { return "" + filename ; } public String createInspect ( IRubyStackFrame frame , String expression ) { return "" + frame . getIndex ( ) + "" + expression . replaceAll ( "" , "" ) ; } public String createResume ( RubyThread thread ) { return "" ; } public String createAddBreakpoint ( String file , int line ) { StringBuffer setBreakPointCommand = new StringBuffer ( ) ; setBreakPointCommand . append ( "" ) ; setBreakPointCommand . append ( file ) ; setBreakPointCommand . append ( "" ) ; setBreakPointCommand . append ( line ) ; return setBreakPointCommand . toString ( ) ; } public String createAddMethodBreakpoint ( String file , String type , String method , int line ) { StringBuffer setBreakPointCommand = new StringBuffer ( ) ; setBreakPointCommand . append ( "" ) ; setBreakPointCommand . append ( type ) ; setBreakPointCommand . append ( "" ) ; setBreakPointCommand . append ( method ) ; return setBreakPointCommand . toString ( ) ; } public String createRemoveBreakpoint ( int index ) { return "" + index ; } public String createCatchOff ( IRubyExceptionBreakpoint breakpoint ) throws CoreException { return "" + breakpoint . getTypeName ( ) + "" ; } public String createCatchOn ( IRubyExceptionBreakpoint breakpoint ) throws CoreException { return "" + breakpoint . getTypeName ( ) ; } public String createThreadStop ( RubyThread thread ) { return "" + thread . getId ( ) ; } public String createSetCondition ( int bpNum , String condition ) { return "" + bpNum + '' + condition ; } } package org . rubypeople . rdt . internal . debug . core ; public abstract class SuspensionPoint { private String file ; private String line ; private int threadId ; public SuspensionPoint ( ) { } public String getFile ( ) { return file ; } public String getLine ( ) { return line ; } public void setFile ( String file ) { this . file = file ; } public void setLine ( String line ) { this . line = line ; } public String getPosition ( ) { return this . getFile ( ) + "" + this . getLine ( ) ; } public abstract String toString ( ) ; public abstract boolean isException ( ) ; public abstract boolean isStep ( ) ; public abstract boolean isBreakpoint ( ) ; public int getThreadId ( ) { return threadId ; } public void setThreadId ( int threadId ) { this . threadId = threadId ; } } package org . rubypeople . rdt . internal . debug . core ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyThread ; import org . rubypeople . rdt . internal . debug . core . model . RubyVariable ; public interface ICommandFactory { public String createReadFrames ( RubyThread thread ) ; public String createReadLocalVariables ( RubyStackFrame frame ) ; public String createReadInstanceVariable ( RubyVariable variable ) ; public String createStepOver ( RubyStackFrame stackFrame ) ; public String createForcedStepOver ( RubyStackFrame stackFrame ) ; public String createStepReturn ( RubyStackFrame stackFrame ) ; public String createStepInto ( RubyStackFrame stackFrame ) ; public String createForcedStepInto ( RubyStackFrame stackFrame ) ; public String createReadThreads ( ) ; public String createThreadStop ( RubyThread thread ) ; public String createInspect ( IRubyStackFrame frame , String expression ) ; public String createResume ( RubyThread thread ) ; public String createAddBreakpoint ( String file , int line ) ; public String createRemoveBreakpoint ( int index ) ; public String createCatchOff ( IRubyExceptionBreakpoint rubyExceptionBreakpoint ) throws CoreException ; public String createCatchOn ( IRubyExceptionBreakpoint breakpoint ) throws CoreException ; public String createLoad ( String filename ) ; public String createAddMethodBreakpoint ( String fileName , String typeName , String methodName , int line ) ; } package org . rubypeople . rdt . internal . debug . core ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyThread ; import org . rubypeople . rdt . internal . debug . core . model . RubyVariable ; public class ClassicDebuggerCommandFactory implements ICommandFactory { public String createReadFrames ( RubyThread thread ) { return "" + thread . getId ( ) + "" ; } public String createReadLocalVariables ( RubyStackFrame frame ) { return "" + ( ( RubyThread ) frame . getThread ( ) ) . getId ( ) + "" + frame . getIndex ( ) + "" ; } public String createReadInstanceVariable ( RubyVariable variable ) { return "" + ( ( RubyThread ) variable . getStackFrame ( ) . getThread ( ) ) . getId ( ) + "" + variable . getStackFrame ( ) . getIndex ( ) + "" + variable . getObjectId ( ) ; } public String createStepOver ( RubyStackFrame stackFrame ) { return "" + ( ( RubyThread ) stackFrame . getThread ( ) ) . getId ( ) + "" ; } public String createForcedStepOver ( RubyStackFrame stackFrame ) { return createStepOver ( stackFrame ) ; } public String createStepReturn ( RubyStackFrame stackFrame ) { return "" + ( ( RubyThread ) stackFrame . getThread ( ) ) . getId ( ) + "" + ( stackFrame . getLineNumber ( ) + ) ; } public String createStepInto ( RubyStackFrame stackFrame ) { return "" + ( ( RubyThread ) stackFrame . getThread ( ) ) . getId ( ) + "" ; } public String createForcedStepInto ( RubyStackFrame stackFrame ) { return createStepInto ( stackFrame ) ; } public String createReadThreads ( ) { return "" ; } public String createLoad ( String filename ) { return "" + filename ; } public String createInspect ( IRubyStackFrame frame , String expression ) { return "" + ( ( RubyThread ) frame . getThread ( ) ) . getId ( ) + "" + frame . getIndex ( ) + "" + expression ; } public String createResume ( RubyThread thread ) { return "" + thread . getId ( ) + "" ; } public String createAddBreakpoint ( String file , int line ) { StringBuffer setBreakPointCommand = new StringBuffer ( ) ; setBreakPointCommand . append ( "" ) ; setBreakPointCommand . append ( file ) ; setBreakPointCommand . append ( "" ) ; setBreakPointCommand . append ( line ) ; return setBreakPointCommand . toString ( ) ; } public String createRemoveBreakpoint ( int index ) { return "" + index ; } public String createCatchOff ( IRubyExceptionBreakpoint breakpoint ) { return "" ; } public String createCatchOn ( IRubyExceptionBreakpoint breakpoint ) throws CoreException { return "" + breakpoint . getTypeName ( ) ; } public String createThreadStop ( RubyThread thread ) { return "" + thread . getId ( ) ; } public String createAddMethodBreakpoint ( String file , String typeName , String methodName , int line ) { StringBuffer setBreakPointCommand = new StringBuffer ( ) ; setBreakPointCommand . append ( "" ) ; setBreakPointCommand . append ( file ) ; setBreakPointCommand . append ( "" ) ; setBreakPointCommand . append ( line ) ; return setBreakPointCommand . toString ( ) ; } } package org . rubypeople . rdt . internal . debug . core ; public class BreakpointSuspensionPoint extends SuspensionPoint { public String toString ( ) { return "" + this . getPosition ( ) ; } public boolean isBreakpoint ( ) { return true ; } public boolean isException ( ) { return false ; } public boolean isStep ( ) { return false ; } } package org . rubypeople . rdt . internal . debug . core . model ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . debug . core . model . IDebugTarget ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . SuspensionPoint ; public interface IRubyDebugTarget extends IDebugTarget { public final static String MODEL_IDENTIFIER = "" ; public void suspensionOccurred ( SuspensionPoint suspensionPoint ) ; public void updateThreads ( ) ; public void setRubyDebuggerProxy ( RubyDebuggerProxy rubyDebuggerProxy ) ; public int getPort ( ) ; public String getHost ( ) ; public RubyDebuggerProxy getRubyDebuggerProxy ( ) ; public IStatus load ( String filename ) ; } package org . rubypeople . rdt . internal . debug . core . model ; import java . util . Vector ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugEvent ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . model . IBreakpoint ; import org . eclipse . debug . core . model . IDebugTarget ; import org . eclipse . debug . core . model . IStackFrame ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . model . IRubyThread ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . SuspensionPoint ; public class RubyThread extends RubyDebugElement implements IRubyThread { private RubyStackFrame [ ] frames ; private boolean isSuspended = false ; private boolean isTerminated = false ; private boolean isStepping = false ; private String name ; private String status ; private int id ; private ThreadJob fRunningAsyncJob ; private ThreadJob fAsyncJob ; public RubyThread ( IDebugTarget target , int id , String status ) { super ( target ) ; this . setId ( id ) ; this . status = status ; this . updateName ( ) ; } public IStackFrame [ ] getStackFrames ( ) { if ( frames == null ) { createStackFrames ( ) ; } return frames ; } private synchronized void createStackFrames ( ) { if ( isSuspended ( ) ) { getRubyDebuggerProxy ( ) . readFrames ( this ) ; } else { frames = new RubyStackFrame [ ] { } ; } } public int getStackFramesSize ( ) { return frames . length ; } public boolean hasStackFrames ( ) { return isSuspended ; } public int getPriority ( ) throws DebugException { return ; } public IStackFrame getTopStackFrame ( ) throws DebugException { IStackFrame [ ] frames = getStackFrames ( ) ; if ( frames == null || frames . length == ) return null ; return frames [ ] ; } public IBreakpoint [ ] getBreakpoints ( ) { return new IBreakpoint [ ] { DebugPlugin . getDefault ( ) . getBreakpointManager ( ) . getBreakpoints ( getModelIdentifier ( ) ) [ ] } ; } public boolean canResume ( ) { return isSuspended ; } public boolean canSuspend ( ) { return false ; } public boolean isSuspended ( ) { return isSuspended ; } protected void setSuspended ( boolean isSuspended ) { this . isSuspended = isSuspended ; } protected void resume ( boolean isStep ) { isStepping = isStep ; isSuspended = false ; this . updateName ( ) ; this . frames = new RubyStackFrame [ ] { } ; } public void resume ( ) throws DebugException { resume ( false ) ; ( ( RubyDebugTarget ) this . getDebugTarget ( ) ) . getRubyDebuggerProxy ( ) . resume ( this ) ; DebugEvent ev = new DebugEvent ( this , DebugEvent . RESUME , DebugEvent . CLIENT_REQUEST ) ; DebugPlugin . getDefault ( ) . fireDebugEventSet ( new DebugEvent [ ] { ev } ) ; } public void doSuspend ( SuspensionPoint suspensionPoint ) { int suspensionReason = ; if ( suspensionPoint . isStep ( ) ) { suspensionReason = DebugEvent . STEP_END ; } else { suspensionReason = DebugEvent . BREAKPOINT ; } frames = null ; isSuspended = true ; isStepping = false ; this . createName ( suspensionPoint ) ; DebugEvent ev = new DebugEvent ( this , DebugEvent . SUSPEND , suspensionReason ) ; DebugPlugin . getDefault ( ) . fireDebugEventSet ( new DebugEvent [ ] { ev } ) ; } public void suspend ( ) { frames = null ; isStepping = false ; isSuspended = true ; getRubyDebuggerProxy ( ) . sendThreadStop ( this ) ; } public boolean canStepInto ( ) { return isSuspended && this . hasStackFrames ( ) ; } public boolean canStepOver ( ) { return isSuspended && this . hasStackFrames ( ) ; } public boolean canStepReturn ( ) { return false ; } public boolean isStepping ( ) { return isStepping ; } public void stepInto ( ) throws DebugException { isStepping = true ; this . updateName ( ) ; if ( frames != null && frames . length > ) { frames [ ] . stepInto ( ) ; } } public void stepOver ( ) throws DebugException { if ( frames != null && frames . length > ) { frames [ ] . stepOver ( ) ; } } public void stepReturn ( ) throws DebugException { } public boolean canTerminate ( ) { return ! isTerminated ; } public boolean isTerminated ( ) { return isTerminated ; } public void terminate ( ) throws DebugException { this . getDebugTarget ( ) . terminate ( ) ; isTerminated = true ; this . frames = null ; } public RubyDebuggerProxy getRubyDebuggerProxy ( ) { return ( ( RubyDebugTarget ) this . getDebugTarget ( ) ) . getRubyDebuggerProxy ( ) ; } public void setStackFrames ( RubyStackFrame [ ] frames ) { this . frames = frames ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } protected void updateName ( ) { this . createName ( null ) ; } protected void createName ( SuspensionPoint suspensionPoint ) { this . name = "" + this . getId ( ) ; if ( suspensionPoint != null ) { this . name += "" + suspensionPoint + "" ; } else { this . name += "" + status + "" ; } } public int getId ( ) { return id ; } public void setId ( int id ) { this . id = id ; } public String getStatus ( ) { return status ; } public void setStatus ( String status ) { this . status = status ; } public void queueRunnable ( Runnable evaluation ) { if ( fAsyncJob == null ) { fAsyncJob = new ThreadJob ( this ) ; } fAsyncJob . addRunnable ( evaluation ) ; } static class ThreadJob extends Job { private Vector fRunnables ; private RubyThread fJDIThread ; public ThreadJob ( RubyThread thread ) { super ( "" ) ; fJDIThread = thread ; fRunnables = new Vector ( ) ; setSystem ( true ) ; } public void addRunnable ( Runnable runnable ) { synchronized ( fRunnables ) { fRunnables . add ( runnable ) ; } schedule ( ) ; } public boolean isEmpty ( ) { return fRunnables . isEmpty ( ) ; } public IStatus run ( IProgressMonitor monitor ) { fJDIThread . fRunningAsyncJob = this ; Object [ ] runnables ; synchronized ( fRunnables ) { runnables = fRunnables . toArray ( ) ; fRunnables . clear ( ) ; } MultiStatus failed = null ; monitor . beginTask ( this . getName ( ) , runnables . length ) ; int i = ; while ( i < runnables . length && ! fJDIThread . isTerminated ( ) && ! monitor . isCanceled ( ) ) { try { ( ( Runnable ) runnables [ i ] ) . run ( ) ; } catch ( Exception e ) { if ( failed == null ) { failed = new MultiStatus ( RdtDebugCorePlugin . getPluginIdentifier ( ) , RdtDebugCorePlugin . INTERNAL_ERROR , "" , null ) ; } failed . add ( new Status ( IStatus . ERROR , RdtDebugCorePlugin . getPluginIdentifier ( ) , RdtDebugCorePlugin . INTERNAL_ERROR , "" , e ) ) ; } i ++ ; monitor . worked ( ) ; } fJDIThread . fRunningAsyncJob = null ; monitor . done ( ) ; if ( failed == null ) { return Status . OK_STATUS ; } return failed ; } public boolean shouldRun ( ) { return ! fJDIThread . isTerminated ( ) && ! fRunnables . isEmpty ( ) ; } } } package org . rubypeople . rdt . internal . debug . core . model ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . model . IThread ; import org . eclipse . debug . core . model . IValue ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; public class RubyEvaluationResult implements IEvaluationResult { private String fSnippet ; private IThread fThread ; private IValue fValue ; private DebugException debugException ; public RubyEvaluationResult ( String expression , IThread thread ) { this . fSnippet = expression ; this . fThread = thread ; } public String [ ] getErrorMessages ( ) { return new String [ ] ; } public DebugException getException ( ) { return debugException ; } public void setException ( DebugException e ) { this . debugException = e ; } public String getSnippet ( ) { return fSnippet ; } public IThread getThread ( ) { return fThread ; } public IValue getValue ( ) { return fValue ; } public void setValue ( IValue value ) { this . fValue = value ; } public boolean hasErrors ( ) { return getErrorMessages ( ) . length > || getException ( ) != null ; } } package org . rubypeople . rdt . internal . debug . core . model ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . model . IVariable ; import org . rubypeople . rdt . debug . core . model . IRubyValue ; public class RubyValue extends RubyDebugElement implements IRubyValue { private String valueString ; private String referenceTypeName ; private boolean hasChildren ; private RubyVariable owner ; private RubyVariable [ ] variables ; public RubyValue ( RubyVariable owner ) { this ( owner , "" , null , false ) ; } public RubyValue ( RubyVariable owner , String valueString , String type , boolean hasChildren ) { super ( owner . getDebugTarget ( ) ) ; this . valueString = valueString ; if ( type != null && type . equals ( "" ) ) { this . valueString = '' + this . valueString + '' ; } else if ( this . valueString . startsWith ( "" ) ) { this . valueString = this . valueString . substring ( ) + "" ; } else if ( this . valueString . endsWith ( "" ) ) { int index = this . valueString . substring ( , this . valueString . length ( ) - ) . lastIndexOf ( "" ) ; this . valueString = this . valueString . substring ( , index ) . trim ( ) + "" + this . valueString . substring ( index + , this . valueString . length ( ) - ) . trim ( ) + "" ; } else if ( type != null && type . equals ( "" ) ) { this . valueString = '' + this . valueString ; } this . owner = owner ; this . hasChildren = hasChildren ; this . referenceTypeName = type ; } public String getReferenceTypeName ( ) { return this . referenceTypeName ; } public String getValueString ( ) { return valueString ; } public boolean isAllocated ( ) throws DebugException { return false ; } public IVariable [ ] getVariables ( ) throws DebugException { if ( ! hasChildren ) { return new RubyVariable [ ] ; } if ( variables == null ) { variables = ( ( RubyDebugTarget ) this . getDebugTarget ( ) ) . getRubyDebuggerProxy ( ) . readInstanceVariables ( owner ) ; } return variables ; } public boolean hasVariables ( ) throws DebugException { return hasChildren ; } public String toString ( ) { if ( this . getReferenceTypeName ( ) == null ) { return this . getValueString ( ) ; } return this . getValueString ( ) ; } public RubyVariable getOwner ( ) { return owner ; } } package org . rubypeople . rdt . internal . debug . core . model ; import org . eclipse . debug . core . DebugEvent ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . model . IRegisterGroup ; import org . eclipse . debug . core . model . IThread ; import org . eclipse . debug . core . model . IVariable ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; public class RubyStackFrame extends RubyDebugElement implements IRubyStackFrame { private RubyThread thread ; private String file ; private int lineNumber ; private int index ; private RubyVariable [ ] variables ; public RubyStackFrame ( RubyThread thread , String file , int line , int index ) { super ( thread . getDebugTarget ( ) ) ; this . lineNumber = line ; this . index = index ; this . file = file ; this . thread = thread ; } public IThread getThread ( ) { return thread ; } public void setThread ( RubyThread thread ) { this . thread = thread ; } public IVariable [ ] getVariables ( ) throws DebugException { if ( variables == null ) { variables = this . getRubyDebuggerProxy ( ) . readVariables ( this ) ; } return variables ; } public boolean hasVariables ( ) throws DebugException { return getVariables ( ) . length > ; } public int getLineNumber ( ) { return lineNumber ; } public int getCharStart ( ) throws DebugException { return - ; } public int getCharEnd ( ) throws DebugException { return - ; } public String getName ( ) { return file + "" + this . getLineNumber ( ) ; } public String getFileName ( ) { return file ; } public IRegisterGroup [ ] getRegisterGroups ( ) throws DebugException { return null ; } public boolean hasRegisterGroups ( ) throws DebugException { return false ; } public boolean canStepInto ( ) { return canResume ( ) ; } public boolean canStepOver ( ) { return canResume ( ) ; } public boolean canStepReturn ( ) { return canResume ( ) ; } public boolean isStepping ( ) { return false ; } public void stepInto ( ) throws DebugException { thread . resume ( true ) ; this . getRubyDebuggerProxy ( ) . sendStepIntoEnd ( RubyStackFrame . this ) ; DebugEvent ev = new DebugEvent ( this . getThread ( ) , DebugEvent . RESUME , DebugEvent . STEP_INTO ) ; DebugPlugin . getDefault ( ) . fireDebugEventSet ( new DebugEvent [ ] { ev } ) ; } public void stepOver ( ) throws DebugException { thread . resume ( true ) ; this . getRubyDebuggerProxy ( ) . sendStepOverEnd ( RubyStackFrame . this ) ; DebugEvent ev = new DebugEvent ( this . getThread ( ) , DebugEvent . RESUME , DebugEvent . STEP_OVER ) ; DebugPlugin . getDefault ( ) . fireDebugEventSet ( new DebugEvent [ ] { ev } ) ; } public void stepReturn ( ) throws DebugException { thread . resume ( true ) ; this . getRubyDebuggerProxy ( ) . sendStepReturnEnd ( RubyStackFrame . this ) ; DebugEvent ev = new DebugEvent ( this . getThread ( ) , DebugEvent . RESUME , DebugEvent . STEP_RETURN ) ; DebugPlugin . getDefault ( ) . fireDebugEventSet ( new DebugEvent [ ] { ev } ) ; } public boolean canResume ( ) { return this . getThread ( ) . canResume ( ) ; } public boolean canSuspend ( ) { return this . getThread ( ) . canSuspend ( ) ; } public boolean isSuspended ( ) { return this . getThread ( ) . isSuspended ( ) ; } public void resume ( ) throws DebugException { this . getThread ( ) . resume ( ) ; } public void suspend ( ) throws DebugException { } public boolean canTerminate ( ) { return this . getThread ( ) . canTerminate ( ) ; } public boolean isTerminated ( ) { return this . getThread ( ) . isTerminated ( ) ; } public void terminate ( ) throws DebugException { this . getThread ( ) . terminate ( ) ; } public int getIndex ( ) { return index ; } public RubyDebuggerProxy getRubyDebuggerProxy ( ) { return thread . getRubyDebuggerProxy ( ) ; } @ Override public String toString ( ) { return getName ( ) ; } public IEvaluationResult evaluate ( String expressionText ) { return getRubyDebuggerProxy ( ) . evaluate ( this , expressionText ) ; } } package org . rubypeople . rdt . internal . debug . core . model ; import org . rubypeople . rdt . internal . debug . core . breakpoints . RubyLineBreakpoint ; public class RubyWatchpoint extends RubyLineBreakpoint { } package org . rubypeople . rdt . internal . debug . core . model ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugEvent ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . model . IValue ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . debug . core . model . IRubyValue ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; public class RubyVariable extends RubyDebugElement implements IRubyVariable { private boolean isStatic ; private boolean isLocal ; private boolean isInstance ; private boolean isConstant ; private IRubyStackFrame stackFrame ; private String name ; private String objectId ; private IValue value ; private IRubyVariable parent ; private boolean valueHasChanged = false ; public RubyVariable ( IRubyStackFrame stackFrame , String name , String scope ) { super ( stackFrame . getDebugTarget ( ) ) ; this . initialize ( stackFrame , name , scope , null , new RubyValue ( this ) ) ; } public RubyVariable ( IRubyStackFrame stackFrame , String name , String scope , String value , String type , boolean hasChildren , String objectId ) { super ( stackFrame . getDebugTarget ( ) ) ; this . initialize ( stackFrame , name , scope , objectId , new RubyValue ( this , value , type , hasChildren ) ) ; } protected final void initialize ( IRubyStackFrame stackFrame , String name , String scope , String objectId , RubyValue value ) { this . stackFrame = stackFrame ; this . value = value ; this . name = name ; this . objectId = objectId ; this . isStatic = scope . equals ( "" ) ; this . isLocal = scope . equals ( "" ) ; this . isInstance = scope . equals ( "" ) ; this . isConstant = scope . equals ( "" ) ; } public IValue getValue ( ) { return value ; } public String getName ( ) { return name ; } public String getReferenceTypeName ( ) { return "" ; } public boolean hasValueChanged ( ) throws DebugException { return valueHasChanged ; } public void setValue ( String expression ) throws DebugException { try { String assignee = getName ( ) ; if ( isHashValue ( ) ) { assignee = parent . getName ( ) + "" + assignee + "" ; } else if ( isArrayValue ( ) ) { assignee = parent . getName ( ) + assignee ; } RubyVariable var = getRubyDebuggerProxy ( ) . readInspectExpression ( stackFrame , assignee + "" + expression ) ; this . value = var . getValue ( ) ; this . valueHasChanged = true ; fireChangeEvent ( DebugEvent . CONTENT ) ; } catch ( RubyProcessingException e ) { throw new DebugException ( new Status ( Status . ERROR , RdtDebugCorePlugin . PLUGIN_ID , - , e . getMessage ( ) , e ) ) ; } } public RubyDebuggerProxy getRubyDebuggerProxy ( ) { return ( ( RubyDebugTarget ) this . getDebugTarget ( ) ) . getRubyDebuggerProxy ( ) ; } public void setValue ( IValue value ) throws DebugException { if ( value instanceof RubyValue ) { RubyValue val = ( RubyValue ) value ; RubyVariable var = val . getOwner ( ) ; setValue ( var . getName ( ) ) ; } else { setValue ( value . getValueString ( ) ) ; } } public boolean supportsValueModification ( ) { return true ; } public boolean verifyValue ( String expression ) throws DebugException { try { RubyParser parser = new RubyParser ( ) ; parser . parse ( expression ) ; } catch ( SyntaxException e ) { return false ; } return true ; } public boolean verifyValue ( IValue value ) throws DebugException { return false ; } public String toString ( ) { if ( this . isHashValue ( ) ) { return this . getName ( ) + "" + this . getValue ( ) ; } return this . getName ( ) + "" + this . getValue ( ) ; } public IRubyStackFrame getStackFrame ( ) { return stackFrame ; } public IRubyVariable getParent ( ) { return parent ; } public void setParent ( IRubyVariable parent ) { this . parent = parent ; } public String getQualifiedName ( ) { if ( parent == null ) { return this . getName ( ) ; } if ( this . isHashValue ( ) ) { if ( ( ( RubyValue ) this . getValue ( ) ) . getReferenceTypeName ( ) . equals ( "" ) ) { return parent . getQualifiedName ( ) + "" + this . getName ( ) + "" ; } return "" + this . getObjectId ( ) + "" ; } if ( this . getName ( ) . startsWith ( "" ) ) { return parent . getQualifiedName ( ) + this . getName ( ) ; } return parent . getQualifiedName ( ) + "" + this . getName ( ) ; } public boolean isInstance ( ) { return isInstance ; } public boolean isLocal ( ) { return isLocal ; } public boolean isStatic ( ) { return isStatic ; } public boolean isConstant ( ) { return isConstant ; } public String getObjectId ( ) { return objectId ; } public boolean isHashValue ( ) { if ( parent == null ) return false ; try { String type = ( ( IRubyValue ) parent . getValue ( ) ) . getReferenceTypeName ( ) ; return type . equals ( "" ) || type . equals ( "" ) || type . equals ( "" ) ; } catch ( DebugException e ) { return false ; } } private boolean isArrayValue ( ) { if ( parent == null ) return false ; try { String type = ( ( IRubyValue ) parent . getValue ( ) ) . getReferenceTypeName ( ) ; return type . equals ( "" ) ; } catch ( DebugException e ) { return false ; } } } package org . rubypeople . rdt . internal . debug . core . model ; public class ThreadInfo { private int id ; private String status ; public ThreadInfo ( int id , String status ) { this . id = id ; this . status = status ; } public int getId ( ) { return id ; } public String getStatus ( ) { return status ; } } package org . rubypeople . rdt . internal . debug . core . model ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import java . util . TreeSet ; import org . eclipse . core . resources . IMarkerDelta ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugEvent ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . IBreakpointManager ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . IBreakpoint ; import org . eclipse . debug . core . model . IDebugTarget ; import org . eclipse . debug . core . model . IMemoryBlock ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . core . model . IThread ; import org . rubypeople . rdt . debug . core . IRubyLineBreakpoint ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . RdtDebugModel ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . SuspensionPoint ; public class RubyDebugTarget extends RubyDebugElement implements IRubyDebugTarget { public static int DEFAULT_PORT = ; private IProcess process ; private boolean isTerminated ; private ILaunch launch ; private RubyThread [ ] threads ; private RubyDebuggerProxy rubyDebuggerProxy ; private int port ; private File debugParameterFile ; private ArrayList < IBreakpoint > fBreakPoints ; private String host ; private RubyDebugTarget ( ILaunch launch , IProcess process , String host , int port ) { super ( null ) ; this . launch = launch ; this . host = host ; this . port = port ; this . process = process ; this . threads = new RubyThread [ ] ; this . fBreakPoints = new ArrayList < IBreakpoint > ( ) ; this . isTerminated = false ; if ( DebugPlugin . getDefault ( ) != null ) { initializeBreakpoints ( ) ; } addDebugParameter ( "" + port ) ; } public RubyDebugTarget ( ILaunch launch , String host , int port ) { this ( launch , null , host , port ) ; } public RubyDebugTarget ( ILaunch launch , int port ) { this ( launch , "" , port ) ; } public String getHost ( ) { return host ; } public void updateThreads ( ) { RdtDebugCorePlugin . debug ( "" ) ; ThreadInfo [ ] threadInfos = this . getRubyDebuggerProxy ( ) . readThreads ( ) ; updateThreads ( threadInfos ) ; } public synchronized void updateThreads ( ThreadInfo [ ] threadInfos ) { if ( isSuspended ( ) ) { return ; } DebugEvent [ ] events = updateThreadsInternal ( threadInfos ) ; DebugPlugin . getDefault ( ) . fireDebugEventSet ( events ) ; } public DebugEvent [ ] updateThreadsInternal ( ThreadInfo [ ] threadInfos ) { List < DebugEvent > events = new ArrayList < DebugEvent > ( ) ; RubyThread [ ] newThreads = new RubyThread [ threadInfos . length ] ; Set < Integer > newIds = new TreeSet < Integer > ( ) ; boolean changed = false ; int threadIndex = ; for ( int i = ; i < threadInfos . length ; i ++ ) { ThreadInfo currentThreadInfo = threadInfos [ i ] ; RubyThread existingThread = getThreadById ( currentThreadInfo . getId ( ) ) ; if ( existingThread == null ) { newThreads [ i ] = new RubyThread ( this , currentThreadInfo . getId ( ) , currentThreadInfo . getStatus ( ) ) ; DebugEvent ev = new DebugEvent ( newThreads [ i ] , DebugEvent . CREATE ) ; events . add ( ev ) ; } else { newThreads [ i ] = existingThread ; if ( ! existingThread . getStatus ( ) . equals ( currentThreadInfo . getStatus ( ) ) ) { existingThread . setStatus ( currentThreadInfo . getStatus ( ) ) ; existingThread . updateName ( ) ; DebugEvent ev = new DebugEvent ( newThreads [ i ] , DebugEvent . CHANGE ) ; events . add ( ev ) ; } } newIds . add ( newThreads [ i ] . getId ( ) ) ; } for ( int i = ; i < threads . length ; i ++ ) { if ( ! newIds . contains ( threads [ i ] . getId ( ) ) ) { DebugEvent ev = new DebugEvent ( threads [ i ] , DebugEvent . TERMINATE ) ; events . add ( ev ) ; } } threads = newThreads ; if ( changed ) { DebugEvent ev1 = new DebugEvent ( this , DebugEvent . CHANGE , DebugEvent . CONTENT ) ; events . add ( ev1 ) ; } return events . toArray ( new DebugEvent [ ] { } ) ; } protected RubyThread getThreadById ( int id ) { for ( int i = ; i < threads . length ; i ++ ) { if ( threads [ i ] . getId ( ) == id ) { return threads [ i ] ; } } return null ; } public void suspensionOccurred ( SuspensionPoint suspensionPoint ) { this . updateThreads ( ) ; RubyThread thread = this . getThreadById ( suspensionPoint . getThreadId ( ) ) ; if ( thread == null ) { RdtDebugCorePlugin . log ( IStatus . ERROR , "" + suspensionPoint . getThreadId ( ) + "" ) ; return ; } thread . doSuspend ( suspensionPoint ) ; } public IThread [ ] getThreads ( ) { return threads ; } public boolean hasThreads ( ) throws DebugException { return threads . length > ; } public String getName ( ) throws DebugException { return "" ; } public boolean supportsBreakpoint ( IBreakpoint arg0 ) { return false ; } public IDebugTarget getDebugTarget ( ) { return this ; } public ILaunch getLaunch ( ) { return launch ; } public boolean canTerminate ( ) { return ! isTerminated ; } public boolean isTerminated ( ) { return isTerminated ; } public synchronized void terminate ( ) throws DebugException { if ( isTerminated ) { return ; } IBreakpointManager manager = DebugPlugin . getDefault ( ) . getBreakpointManager ( ) ; manager . removeBreakpointListener ( this ) ; try { rubyDebuggerProxy . stop ( ) ; if ( getProcess ( ) != null ) { getProcess ( ) . terminate ( ) ; } this . threads = new RubyThread [ ] ; isTerminated = true ; } catch ( DebugException e ) { throw e ; } catch ( IOException e ) { throw new DebugException ( new Status ( IStatus . ERROR , RdtDebugCorePlugin . PLUGIN_ID , DebugException . INTERNAL_ERROR , "" , e ) ) ; } DebugPlugin . getDefault ( ) . fireDebugEventSet ( new DebugEvent [ ] { new DebugEvent ( this , DebugEvent . TERMINATE ) } ) ; if ( debugParameterFile . exists ( ) ) { boolean deleted = debugParameterFile . delete ( ) ; if ( ! deleted ) { RdtDebugCorePlugin . debug ( "" + debugParameterFile . toURI ( ) ) ; } } } public boolean canResume ( ) { return false ; } public boolean canSuspend ( ) { return false ; } public boolean isSuspended ( ) { boolean isSuspended = false ; for ( int i = ; i < getThreads ( ) . length ; i ++ ) { if ( getThreads ( ) [ i ] . isSuspended ( ) ) { isSuspended = true ; break ; } } return isSuspended ; } public void resume ( ) throws DebugException { } public void suspend ( ) throws DebugException { } public void breakpointAdded ( IBreakpoint breakpoint ) { if ( isTerminated ) { return ; } if ( ! getBreakpoints ( ) . contains ( breakpoint ) ) { if ( this . getRubyDebuggerProxy ( ) != null ) this . getRubyDebuggerProxy ( ) . addBreakpoint ( breakpoint ) ; getBreakpoints ( ) . add ( breakpoint ) ; } } private List < IBreakpoint > getBreakpoints ( ) { return fBreakPoints ; } public void breakpointRemoved ( IBreakpoint breakpoint , IMarkerDelta arg1 ) { if ( isTerminated ) { return ; } this . getRubyDebuggerProxy ( ) . removeBreakpoint ( breakpoint ) ; fBreakPoints . remove ( breakpoint ) ; } public void breakpointChanged ( IBreakpoint breakpoint , IMarkerDelta arg1 ) { if ( isTerminated ) { return ; } this . getRubyDebuggerProxy ( ) . updateBreakpoint ( breakpoint , arg1 ) ; } public boolean canDisconnect ( ) { return false ; } public void disconnect ( ) throws DebugException { } public boolean isDisconnected ( ) { return false ; } public boolean supportsStorageRetrieval ( ) { return false ; } public IMemoryBlock getMemoryBlock ( long arg0 , long arg1 ) throws DebugException { return null ; } public IProcess getProcess ( ) { return process ; } public void setProcess ( IProcess process ) { this . process = process ; } public RubyDebuggerProxy getRubyDebuggerProxy ( ) { return rubyDebuggerProxy ; } public void setRubyDebuggerProxy ( RubyDebuggerProxy rubyDebuggerProxy ) { this . rubyDebuggerProxy = rubyDebuggerProxy ; } public File getDebugParameterFile ( ) { if ( debugParameterFile == null ) { try { debugParameterFile = File . createTempFile ( "" , "" ) ; } catch ( IOException e ) { RdtDebugCorePlugin . log ( "" , e ) ; } } return debugParameterFile ; } public void reinstallBreakpointsIn ( List resources , List classNames ) { List breakpoints = getBreakpoints ( ) ; IBreakpoint [ ] copy = new IBreakpoint [ breakpoints . size ( ) ] ; breakpoints . toArray ( copy ) ; IBreakpoint breakpoint = null ; for ( int i = ; i < copy . length ; i ++ ) { breakpoint = copy [ i ] ; if ( breakpoint instanceof IRubyLineBreakpoint ) { breakpointRemoved ( breakpoint , null ) ; breakpointAdded ( breakpoint ) ; } } } protected void initializeBreakpoints ( ) { IBreakpointManager manager = DebugPlugin . getDefault ( ) . getBreakpointManager ( ) ; manager . addBreakpointListener ( this ) ; IBreakpoint [ ] bps = manager . getBreakpoints ( RdtDebugModel . getModelIdentifier ( ) ) ; for ( int i = ; i < bps . length ; i ++ ) { if ( bps [ i ] . getModelIdentifier ( ) . equals ( RdtDebugModel . getModelIdentifier ( ) ) ) { breakpointAdded ( bps [ i ] ) ; } } } private boolean addDebugParameter ( String line ) { PrintWriter writer = null ; try { writer = new PrintWriter ( new FileWriter ( getDebugParameterFile ( ) ) ) ; writer . println ( line ) ; writer . flush ( ) ; return true ; } catch ( IOException ex ) { RdtDebugCorePlugin . log ( ex ) ; return false ; } finally { writer . close ( ) ; } } public int getPort ( ) { return port ; } public boolean isUsingDefaultPort ( ) { return getPort ( ) == DEFAULT_PORT ; } public IStatus load ( String filename ) { return getRubyDebuggerProxy ( ) . readLoadResult ( filename ) ; } } package org . rubypeople . rdt . internal . debug . core . model ; import org . eclipse . core . runtime . PlatformObject ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . IDebugTarget ; import org . eclipse . debug . core . model . IExpression ; import org . eclipse . debug . core . model . IValue ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; public class RubyExpression extends PlatformObject implements IExpression { private IRubyVariable inspectionResult ; private String expression ; public RubyExpression ( String expression , IRubyVariable inspectionResult ) { this . inspectionResult = inspectionResult ; this . expression = expression ; } public String getExpressionText ( ) { return expression ; } public IValue getValue ( ) { try { return inspectionResult . getValue ( ) ; } catch ( DebugException e ) { RdtDebugCorePlugin . log ( e ) ; return null ; } } public IDebugTarget getDebugTarget ( ) { return inspectionResult . getDebugTarget ( ) ; } public void dispose ( ) { } public String getModelIdentifier ( ) { return this . getDebugTarget ( ) . getModelIdentifier ( ) ; } public ILaunch getLaunch ( ) { return this . getDebugTarget ( ) . getLaunch ( ) ; } } package org . rubypeople . rdt . internal . debug . core . model ; import org . eclipse . debug . core . model . DebugElement ; import org . eclipse . debug . core . model . IDebugTarget ; public class RubyDebugElement extends DebugElement { public RubyDebugElement ( IDebugTarget target ) { super ( target ) ; } public String getModelIdentifier ( ) { return IRubyDebugTarget . MODEL_IDENTIFIER ; } } package org . rubypeople . rdt . internal . debug . core . model ; public class RubyProcessingException extends Exception { private static final long serialVersionUID = - ; private String rubyExceptionType ; public RubyProcessingException ( String message ) { super ( message ) ; } public RubyProcessingException ( String type , String message ) { super ( message ) ; this . rubyExceptionType = type ; } public String getRubyExceptionType ( ) { return rubyExceptionType ; } } package org . rubypeople . rdt . internal . debug . core ; public class StepSuspensionPoint extends SuspensionPoint { private int framesNumber ; public boolean isBreakpoint ( ) { return false ; } public boolean isException ( ) { return false ; } public boolean isStep ( ) { return true ; } public String toString ( ) { return "" + this . getPosition ( ) ; } public int getFramesNumber ( ) { return framesNumber ; } public void setFramesNumber ( int framesNumber ) { this . framesNumber = framesNumber ; } } package org . rubypeople . rdt . debug . core . model ; import org . rubypeople . rdt . debug . core . IRubyBreakpoint ; public interface IRubyExceptionBreakpoint extends IRubyBreakpoint { } package org . rubypeople . rdt . debug . core . model ; import org . eclipse . debug . core . model . IVariable ; public interface IRubyVariable extends IVariable { boolean isHashValue ( ) ; boolean isConstant ( ) ; boolean isStatic ( ) ; String getQualifiedName ( ) ; IRubyVariable getParent ( ) ; String getObjectId ( ) ; IRubyStackFrame getStackFrame ( ) ; } package org . rubypeople . rdt . debug . core . model ; import org . eclipse . debug . core . model . IValue ; public interface IRubyValue extends IValue { IRubyVariable getOwner ( ) ; } package org . rubypeople . rdt . debug . core . model ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . model . IThread ; import org . eclipse . debug . core . model . IValue ; public interface IEvaluationResult { public IValue getValue ( ) ; public boolean hasErrors ( ) ; public String [ ] getErrorMessages ( ) ; public String getSnippet ( ) ; public DebugException getException ( ) ; public IThread getThread ( ) ; } package org . rubypeople . rdt . debug . core . model ; import org . eclipse . debug . core . model . IStackFrame ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; public interface IRubyStackFrame extends IStackFrame { String getFileName ( ) ; IEvaluationResult evaluate ( String expressionText ) ; RubyDebuggerProxy getRubyDebuggerProxy ( ) ; int getIndex ( ) ; } package org . rubypeople . rdt . debug . core . model ; import org . eclipse . debug . core . model . IThread ; public interface IRubyThread extends IThread { void queueRunnable ( Runnable runnable ) ; } package org . rubypeople . rdt . debug . core ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . model . ILineBreakpoint ; public interface IRubyLineBreakpoint extends IRubyBreakpoint , ILineBreakpoint { public boolean supportsCondition ( ) ; public String getCondition ( ) throws CoreException ; public void setCondition ( String condition ) throws CoreException ; public boolean isConditionEnabled ( ) throws CoreException ; public void setConditionEnabled ( boolean enabled ) throws CoreException ; public boolean isConditionSuspendOnTrue ( ) throws CoreException ; public void setConditionSuspendOnTrue ( boolean suspendOnTrue ) throws CoreException ; public String getFileName ( ) throws CoreException ; public void setIndex ( int index ) ; public int getIndex ( ) ; } package org . rubypeople . rdt . debug . core ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . model . IBreakpoint ; public interface IRubyBreakpoint extends IBreakpoint { public String getTypeName ( ) throws CoreException ; public boolean isInstalled ( ) throws CoreException ; } package org . rubypeople . rdt . debug . core ; import org . eclipse . core . runtime . CoreException ; public interface IRubyMethodBreakpoint extends IRubyLineBreakpoint { public String getMethodName ( ) throws CoreException ; public String getTypeName ( ) throws CoreException ; } package org . rubypeople . rdt . debug . core ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . core . runtime . Status ; import org . osgi . framework . BundleContext ; import org . rubypeople . rdt . core . RubyCore ; public class RdtDebugCorePlugin extends Plugin { public static final String PLUGIN_ID = "" ; public static final String MODEL_IDENTIFIER = "" ; public static final int INTERNAL_ERROR = ; private static boolean isRubyDebuggerVerbose = false ; protected static RdtDebugCorePlugin plugin ; public RdtDebugCorePlugin ( ) { super ( ) ; } public static Plugin getDefault ( ) { return plugin ; } public static IWorkspace getWorkspace ( ) { return RubyCore . getWorkspace ( ) ; } public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; String rubyDebuggerVerboseOption = Platform . getDebugOption ( RdtDebugCorePlugin . PLUGIN_ID + "" ) ; isRubyDebuggerVerbose = rubyDebuggerVerboseOption == null ? false : rubyDebuggerVerboseOption . equalsIgnoreCase ( "" ) ; } public static void log ( int severity , String message ) { Status status = new Status ( severity , PLUGIN_ID , IStatus . OK , message , null ) ; RdtDebugCorePlugin . log ( status ) ; } public static void log ( String message , Throwable e ) { log ( new Status ( IStatus . ERROR , PLUGIN_ID , IStatus . ERROR , message , e ) ) ; } public static void log ( IStatus status ) { if ( RdtDebugCorePlugin . getDefault ( ) != null ) { getDefault ( ) . getLog ( ) . log ( status ) ; } else { System . out . println ( "" ) ; System . out . println ( status . getMessage ( ) ) ; } } public static void log ( Throwable e ) { log ( new Status ( IStatus . ERROR , PLUGIN_ID , IStatus . ERROR , "" , e ) ) ; } public static void debug ( Object message ) { if ( RdtDebugCorePlugin . getDefault ( ) != null ) { if ( RdtDebugCorePlugin . getDefault ( ) . isDebugging ( ) ) { System . out . println ( message . toString ( ) ) ; } } else { System . out . println ( message . toString ( ) ) ; } } public static void debug ( String message , Throwable e ) { if ( RdtDebugCorePlugin . getDefault ( ) != null ) { if ( RdtDebugCorePlugin . getDefault ( ) . isDebugging ( ) ) { System . out . println ( message + "" + e . getMessage ( ) ) ; RdtDebugCorePlugin . log ( e ) ; } } else { System . out . println ( message ) ; e . printStackTrace ( ) ; } } public static boolean isRubyDebuggerVerbose ( ) { return isRubyDebuggerVerbose ; } public static String getPluginIdentifier ( ) { return PLUGIN_ID ; } } package org . rubypeople . rdt . debug . core ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . IBreakpointManager ; import org . eclipse . debug . core . model . IBreakpoint ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; import org . rubypeople . rdt . internal . debug . core . breakpoints . RubyExceptionBreakpoint ; import org . rubypeople . rdt . internal . debug . core . breakpoints . RubyLineBreakpoint ; import org . rubypeople . rdt . internal . debug . core . breakpoints . RubyMethodBreakpoint ; public class RdtDebugModel { public static IRubyExceptionBreakpoint createExceptionBreakpoint ( IResource resource , String exceptionName , boolean register , Map attributes ) throws CoreException { if ( attributes == null ) { attributes = new HashMap ( ) ; } return new RubyExceptionBreakpoint ( resource , exceptionName , register , attributes ) ; } public static IRubyLineBreakpoint createLineBreakpoint ( IResource resource , String fileName , String typeName , int lineNumber , boolean register , Map attributes ) throws CoreException { if ( attributes == null ) { attributes = new HashMap ( ) ; } return new RubyLineBreakpoint ( resource , fileName , typeName , lineNumber , - , - , , register , attributes ) ; } public static IRubyLineBreakpoint lineBreakpointExists ( IResource resource , String typeName , int lineNumber ) throws CoreException { if ( resource == null ) return null ; String modelId = getModelIdentifier ( ) ; String markerType = RubyLineBreakpoint . getMarkerType ( ) ; IBreakpointManager manager = DebugPlugin . getDefault ( ) . getBreakpointManager ( ) ; IBreakpoint [ ] breakpoints = manager . getBreakpoints ( modelId ) ; for ( int i = ; i < breakpoints . length ; i ++ ) { if ( ! ( breakpoints [ i ] instanceof IRubyLineBreakpoint ) ) { continue ; } IRubyLineBreakpoint breakpoint = ( IRubyLineBreakpoint ) breakpoints [ i ] ; if ( breakpoint == null ) continue ; IMarker marker = breakpoint . getMarker ( ) ; if ( marker != null && marker . exists ( ) && marker . getType ( ) . equals ( markerType ) ) { String breakpointTypeName = breakpoint . getTypeName ( ) ; if ( equals ( breakpointTypeName , typeName ) && breakpoint . getLineNumber ( ) == lineNumber && resource . equals ( marker . getResource ( ) ) ) { return breakpoint ; } } } return null ; } private static boolean equals ( String breakpointTypeName , String typeName ) { if ( breakpointTypeName == null ) return typeName == null ; return breakpointTypeName . equals ( typeName ) ; } public static String getModelIdentifier ( ) { return RdtDebugCorePlugin . MODEL_IDENTIFIER ; } public static IRubyMethodBreakpoint createMethodBreakpoint ( IResource resource , String typePattern , String methodName , boolean entry , boolean exit , int lineNumber , int charStart , int charEnd , int hitCount , boolean register , Map attributes ) throws CoreException { if ( attributes == null ) { attributes = new HashMap ( ) ; } return new RubyMethodBreakpoint ( resource , typePattern , methodName , entry , exit , lineNumber , charStart , charEnd , hitCount , register , attributes ) ; } } package org . rubypeople . rdt . internal . formatter ; import java . util . HashMap ; import java . util . Map ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; public class DefaultCodeFormatterOptions { private static final int DEFAULT_INDENT_SIZE = ; private static final int DEFAULT_TAB_SIZE = ; public static final int TAB = ; public static final int SPACE = ; public static final int MIXED = ; public int indentation_size ; public int tab_char ; public int tab_size ; public int comment_line_length ; public boolean indent_case_body = false ; public boolean indent_empty_lines = true ; public static DefaultCodeFormatterOptions getDefaultSettings ( ) { DefaultCodeFormatterOptions options = new DefaultCodeFormatterOptions ( ) ; options . setDefaultSettings ( ) ; return options ; } public static DefaultCodeFormatterOptions getEclipseDefaultSettings ( ) { DefaultCodeFormatterOptions options = new DefaultCodeFormatterOptions ( ) ; options . setEclipseDefaultSettings ( ) ; return options ; } public static DefaultCodeFormatterOptions getRubyConventionsSettings ( ) { DefaultCodeFormatterOptions options = new DefaultCodeFormatterOptions ( ) ; options . setRubyConventionsSettings ( ) ; return options ; } private DefaultCodeFormatterOptions ( ) { } public DefaultCodeFormatterOptions ( Map settings ) { setDefaultSettings ( ) ; if ( settings == null ) return ; set ( settings ) ; } public void setDefaultSettings ( ) { this . tab_char = TAB ; this . tab_size = DEFAULT_TAB_SIZE ; this . indentation_size = DEFAULT_INDENT_SIZE ; this . indent_case_body = true ; this . indent_empty_lines = true ; } public void setEclipseDefaultSettings ( ) { setRubyConventionsSettings ( ) ; } public void setRubyConventionsSettings ( ) { setDefaultSettings ( ) ; this . tab_char = SPACE ; this . tab_size = ; this . indentation_size = ; this . indent_case_body = true ; this . indent_empty_lines = true ; } public Map getMap ( ) { Map options = new HashMap ( ) ; options . put ( DefaultCodeFormatterConstants . FORMATTER_COMMENT_LINE_LENGTH , Integer . toString ( this . comment_line_length ) ) ; options . put ( DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE , Integer . toString ( this . indentation_size ) ) ; switch ( this . tab_char ) { case SPACE : options . put ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , RubyCore . SPACE ) ; break ; case TAB : options . put ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , RubyCore . TAB ) ; break ; case MIXED : options . put ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , DefaultCodeFormatterConstants . MIXED ) ; break ; } options . put ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE , Integer . toString ( this . tab_size ) ) ; options . put ( DefaultCodeFormatterConstants . FORMATTER_INDENT_CASE_BODY , Boolean . toString ( this . indent_case_body ) ) ; options . put ( DefaultCodeFormatterConstants . FORMATTER_INDENT_EMPTY_LINES , Boolean . toString ( this . indent_empty_lines ) ) ; return options ; } public void set ( Map settings ) { final Object indentCaseBodyOption = settings . get ( DefaultCodeFormatterConstants . FORMATTER_INDENT_CASE_BODY ) ; if ( indentCaseBodyOption != null ) { try { this . indent_case_body = Boolean . parseBoolean ( ( String ) indentCaseBodyOption ) ; } catch ( NumberFormatException e ) { this . indent_case_body = false ; } catch ( ClassCastException e ) { this . indent_case_body = false ; } } final Object indentEmptyLinesOption = settings . get ( DefaultCodeFormatterConstants . FORMATTER_INDENT_EMPTY_LINES ) ; if ( indentEmptyLinesOption != null ) { try { this . indent_empty_lines = Boolean . parseBoolean ( ( String ) indentEmptyLinesOption ) ; } catch ( NumberFormatException e ) { this . indent_empty_lines = true ; } catch ( ClassCastException e ) { this . indent_empty_lines = true ; } } final Object commentLineLengthOption = settings . get ( DefaultCodeFormatterConstants . FORMATTER_COMMENT_LINE_LENGTH ) ; if ( commentLineLengthOption != null ) { try { this . comment_line_length = Integer . parseInt ( ( String ) commentLineLengthOption ) ; } catch ( NumberFormatException e ) { this . comment_line_length = ; } catch ( ClassCastException e ) { this . comment_line_length = ; } } final Object indentationSizeOption = settings . get ( DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE ) ; if ( indentationSizeOption != null ) { try { this . indentation_size = Integer . parseInt ( ( String ) indentationSizeOption ) ; } catch ( NumberFormatException e ) { this . indentation_size = DEFAULT_INDENT_SIZE ; } catch ( ClassCastException e ) { this . indentation_size = DEFAULT_INDENT_SIZE ; } } final Object tabSizeOption = settings . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ) ; if ( tabSizeOption != null ) { try { this . tab_size = Integer . parseInt ( ( String ) tabSizeOption ) ; } catch ( NumberFormatException e ) { this . tab_size = DEFAULT_TAB_SIZE ; } catch ( ClassCastException e ) { this . tab_size = DEFAULT_TAB_SIZE ; } } final Object useTabOption = settings . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ) ; if ( useTabOption != null ) { if ( RubyCore . TAB . equals ( useTabOption ) ) { this . tab_char = TAB ; } else if ( RubyCore . SPACE . equals ( useTabOption ) ) { this . tab_char = SPACE ; } else { this . tab_char = MIXED ; } } } } package org . rubypeople . rdt . internal . formatter . rewriter ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import org . jruby . parser . StaticScope ; public class LocalVariables { private final HashMap < Integer , String > localVariablesMap = new HashMap < Integer , String > ( ) ; public void addLocalVariable ( int count , String name ) { localVariablesMap . put ( new Integer ( count ) , name ) ; } public void addLocalVariable ( StaticScope scope ) { for ( int i = ; i < scope . getVariables ( ) . length ; i ++ ) { addLocalVariable ( i , scope . getVariables ( ) [ i ] ) ; } } public Collection < String > getNames ( ) { return Collections . unmodifiableCollection ( localVariablesMap . values ( ) ) ; } } package org . rubypeople . rdt . internal . formatter . rewriter ; import java . util . Iterator ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; public class MultipleAssignmentReWriteVisitor extends ReWriteVisitor { public MultipleAssignmentReWriteVisitor ( ReWriterContext config ) { super ( config ) ; } protected void printAssignmentOperator ( ) { } protected boolean inMultipleAssignment ( ) { return true ; } public void visitAndPrintWithSeparator ( Iterator < Node > it ) { while ( it . hasNext ( ) ) { Node n = ( Node ) it . next ( ) ; if ( n instanceof ArgumentNode ) { config . getOutput ( ) . print ( ( ( ArgumentNode ) n ) . getName ( ) ) ; } else { visitNode ( n ) ; } if ( it . hasNext ( ) ) print ( "" ) ; } } } package org . rubypeople . rdt . internal . formatter . rewriter ; import org . jruby . ast . StrNode ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; public class HereDocReWriteVisitor extends ReWriteVisitor { public HereDocReWriteVisitor ( ReWriterContext config ) { super ( config ) ; } public Object visitStrNode ( StrNode iVisited ) { print ( iVisited . getValue ( ) . toString ( ) ) ; return null ; } } package org . rubypeople . rdt . internal . formatter . rewriter ; import java . util . Iterator ; import org . jruby . ast . BlockNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; public class ClassBodyWriter { private ReWriteVisitor visitor ; private Node bodyNode ; private ReWriterContext context ; public ClassBodyWriter ( ReWriteVisitor visitor , Node bodyNode ) { this . visitor = visitor ; this . bodyNode = bodyNode ; this . context = visitor . getConfig ( ) ; } public void write ( ) { if ( bodyNode instanceof BlockNode ) { context . getIndentor ( ) . indent ( ) ; writeContent ( ( BlockNode ) bodyNode ) ; context . getIndentor ( ) . outdent ( ) ; } else if ( bodyNode instanceof NewlineNode ) { visitor . visitNodeInIndentation ( bodyNode ) ; } else { visitor . visitNode ( bodyNode ) ; } } private void writeContent ( BlockNode node ) { for ( Iterator < Node > it = node . childNodes ( ) . iterator ( ) ; it . hasNext ( ) ; ) { visitor . visitNode ( it . next ( ) ) ; if ( it . hasNext ( ) ) { context . getOutput ( ) . print ( context . getFormatHelper ( ) . classBodyElementsSeparator ( ) ) ; } } } } package org . rubypeople . rdt . internal . formatter . rewriter ; import java . util . HashSet ; public abstract class Operators { private static HashSet < String > operatorSet = new HashSet < String > ( ) ; static { String [ ] operators = new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , ">" , "" , "" , "" } ; for ( int i = ; i < operators . length ; i ++ ) { operatorSet . add ( operators [ i ] ) ; } } public static boolean contain ( String name ) { return operatorSet . contains ( name ) ; } } package org . rubypeople . rdt . internal . formatter . rewriter ; import org . jruby . ast . NewlineNode ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; public class ShortIfNodeReWriteVisitor extends ReWriteVisitor { public ShortIfNodeReWriteVisitor ( ReWriterContext config ) { super ( config ) ; } protected void printNewlineAndIndentation ( ) { print ( "" ) ; } public Object visitNewlineNode ( NewlineNode iVisited ) { if ( config . getSource ( ) . charAt ( getEndOffset ( iVisited ) - ) == '' ) { print ( '' ) ; visitNode ( iVisited . getNextNode ( ) ) ; print ( '' ) ; } else { print ( "" ) ; visitNode ( iVisited . getNextNode ( ) ) ; } return null ; } } package org . rubypeople . rdt . internal . formatter . rewriter ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; public class IgnoreCommentsReWriteVisitor extends ReWriteVisitor { public IgnoreCommentsReWriteVisitor ( ReWriterContext config ) { super ( config ) ; } protected boolean printCommentsAfter ( Node iVisited ) { return false ; } } package org . rubypeople . rdt . internal . formatter . rewriter ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; public class DRegxReWriteVisitor extends ReWriteVisitor { public DRegxReWriteVisitor ( ReWriterContext config ) { super ( config ) ; } protected boolean inDRegxNode ( ) { return true ; } } package org . rubypeople . rdt . internal . formatter ; import java . util . Map ; import org . rubypeople . rdt . core . formatter . Indents ; public class IndentationState { private String lastIndentationBasedOnLevel = "" ; private int indentationLevel ; private int offset ; private int pos ; private int fixIndentation ; private String unformattedText ; public IndentationState ( String unformattedText , int offset , int initialIndentLevel ) { this . unformattedText = unformattedText ; this . offset = offset ; indentationLevel = initialIndentLevel ; pos = ; resetFixIndentation ( ) ; } public void decIndentationLevel ( ) { indentationLevel -= ; resetFixIndentation ( ) ; } public void incIndentationLevel ( ) { indentationLevel += ; resetFixIndentation ( ) ; } public void incPos ( int increment ) { pos += increment ; } public void resetFixIndentation ( ) { fixIndentation = - ; } public int getIndentation ( ) { return fixIndentation ; } public int getIndentationLevel ( ) { return indentationLevel ; } public int getOffset ( ) { return offset ; } public int getPos ( ) { return pos ; } public String getUnformattedText ( ) { return unformattedText ; } public void setFixIndentation ( int indentation ) { this . fixIndentation = indentation ; } public void setIndentationLevel ( int indentationLevel ) { this . indentationLevel = indentationLevel ; this . resetFixIndentation ( ) ; } public void setOffset ( int offset ) { this . offset = offset ; this . resetFixIndentation ( ) ; } public void setPos ( int pos ) { this . pos = pos ; } protected String getIndentationString ( Map options ) { StringBuffer sb = new StringBuffer ( ) ; if ( this . getIndentation ( ) != - ) { sb . append ( lastIndentationBasedOnLevel ) ; sb . append ( Indents . createFixIndentString ( this . getIndentation ( ) , options ) ) ; } else { lastIndentationBasedOnLevel = Indents . createIndentString ( this . getIndentationLevel ( ) , options ) ; sb . append ( lastIndentationBasedOnLevel ) ; } return sb . toString ( ) ; } } package org . rubypeople . rdt . internal . formatter ; public class NeutralMarker extends AbstractBlockMarker { public NeutralMarker ( String aKeyword , int aLine ) { super ( aKeyword , aLine ) ; } protected void indentAfterPrint ( IndentationState state ) { } protected void indentBeforePrint ( IndentationState state ) { state . resetFixIndentation ( ) ; } } package org . rubypeople . rdt . internal . formatter ; import java . util . Map ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import java . util . regex . PatternSyntaxException ; import org . eclipse . core . runtime . Platform ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . core . formatter . Indents ; public class OldCodeFormatter extends CodeFormatter { private final static String BLOCK_BEGIN_RE = "" ; private String BLOCK_MID_RE = "" ; private final static String BLOCK_END_RE = "" ; private final static String DELIMITER_RE = "" ; private final static String [ ] LITERAL_BEGIN_LITERALS = { "" , "" , "" , "" , "" , "" , "" } ; private final static String [ ] LITERAL_END_RES = { "" , "" , "" , "" , "" , "" , "" } ; private final int BLOCK_BEGIN_PAREN = ; private final int BLOCK_MID_PAREN = ; private final int BLOCK_END_PAREN = ; private final int LITERAL_BEGIN_PAREN = ; private static Pattern MODIFIER_RE ; private static Pattern OPERATOR_RE ; private static Pattern NON_BLOCK_DO_RE ; private static String LITERAL_BEGIN_RE ; private static Pattern [ ] LITERAL_END_RES_COMPILED ; static { LITERAL_END_RES_COMPILED = new Pattern [ LITERAL_END_RES . length ] ; for ( int i = ; i < LITERAL_END_RES . length ; i ++ ) { try { LITERAL_END_RES_COMPILED [ i ] = Pattern . compile ( LITERAL_END_RES [ i ] ) ; } catch ( PatternSyntaxException e ) { System . out . println ( e ) ; } } StringBuffer sb = new StringBuffer ( ) ; sb . append ( "" ) ; for ( int i = ; i < LITERAL_BEGIN_LITERALS . length ; i ++ ) { sb . append ( LITERAL_BEGIN_LITERALS [ i ] ) ; if ( i < LITERAL_BEGIN_LITERALS . length - ) { sb . append ( "" ) ; } } sb . append ( "" ) ; LITERAL_BEGIN_RE = sb . toString ( ) ; try { MODIFIER_RE = Pattern . compile ( "" ) ; OPERATOR_RE = Pattern . compile ( "" ) ; NON_BLOCK_DO_RE = Pattern . compile ( "" ) ; } catch ( PatternSyntaxException e ) { System . out . println ( e ) ; } } private DefaultCodeFormatterOptions preferences ; private Map options ; public OldCodeFormatter ( ) { this ( new DefaultCodeFormatterOptions ( DefaultCodeFormatterConstants . getRubyConventionsSettings ( ) ) , null ) ; } public OldCodeFormatter ( DefaultCodeFormatterOptions preferences ) { this ( preferences , null ) ; } public OldCodeFormatter ( DefaultCodeFormatterOptions defaultCodeFormatterOptions , Map options ) { if ( options != null ) { this . options = options ; this . preferences = new DefaultCodeFormatterOptions ( options ) ; } else { this . options = RubyCore . getOptions ( ) ; this . preferences = new DefaultCodeFormatterOptions ( DefaultCodeFormatterConstants . getRubyConventionsSettings ( ) ) ; } if ( defaultCodeFormatterOptions != null ) { this . preferences . set ( defaultCodeFormatterOptions . getMap ( ) ) ; } } public OldCodeFormatter ( Map options ) { this ( null , options ) ; } public synchronized String formatString ( String unformatted ) { AbstractBlockMarker firstAbstractBlockMarker = this . createBlockMarkerList ( unformatted ) ; if ( isDebug ( ) ) { firstAbstractBlockMarker . print ( ) ; } int initialIndentLevel = Indents . measureIndentUnits ( unformatted , preferences . tab_size , preferences . indentation_size ) ; try { return this . formatString ( unformatted , firstAbstractBlockMarker , initialIndentLevel ) ; } catch ( PatternSyntaxException ex ) { return unformatted ; } } private boolean isDebug ( ) { String codeFormatterOption = Platform . getDebugOption ( RubyCore . PLUGIN_ID + "" ) ; boolean isDebug = codeFormatterOption == null ? false : codeFormatterOption . equalsIgnoreCase ( "" ) ; return isDebug ; } protected String formatString ( String unformatted , AbstractBlockMarker abstractBlockMarker , int initialIndentLevel ) throws PatternSyntaxException { Pattern pat = Pattern . compile ( "" ) ; String [ ] lines = pat . split ( unformatted ) ; IndentationState state = null ; StringBuffer formatted = new StringBuffer ( ) ; Pattern whitespacePattern = Pattern . compile ( "" ) ; for ( int i = ; i < lines . length ; i ++ ) { Matcher whitespaceMatcher = whitespacePattern . matcher ( lines [ i ] ) ; whitespaceMatcher . find ( ) ; int leadingWhitespace = whitespaceMatcher . end ( ) ; if ( state == null ) { state = new IndentationState ( unformatted , leadingWhitespace , initialIndentLevel ) ; } state . incPos ( leadingWhitespace ) ; String strippedLine = new String ( lines [ i ] . substring ( leadingWhitespace ) ) ; AbstractBlockMarker newBlockMarker = this . findNextBlockMarker ( abstractBlockMarker , state . getPos ( ) , state ) ; if ( newBlockMarker != null ) { newBlockMarker . indentBeforePrint ( state ) ; newBlockMarker . appendIndentedLine ( formatted , state , lines [ i ] , strippedLine , options ) ; newBlockMarker . indentAfterPrint ( state ) ; abstractBlockMarker = newBlockMarker ; } else { abstractBlockMarker . appendIndentedLine ( formatted , state , lines [ i ] , strippedLine , options ) ; } if ( i != lines . length - ) { formatted . append ( "" ) ; } state . incPos ( strippedLine . length ( ) + ) ; } if ( unformatted . lastIndexOf ( "" ) == unformatted . length ( ) - ) { formatted . append ( "" ) ; } return formatted . toString ( ) ; } private AbstractBlockMarker findNextBlockMarker ( AbstractBlockMarker abstractBlockMarker , int pos , IndentationState state ) { AbstractBlockMarker startBlockMarker = abstractBlockMarker ; while ( abstractBlockMarker . getNext ( ) != null && abstractBlockMarker . getNext ( ) . getPos ( ) <= pos ) { if ( abstractBlockMarker != startBlockMarker ) { abstractBlockMarker . indentBeforePrint ( state ) ; abstractBlockMarker . indentAfterPrint ( state ) ; } abstractBlockMarker = abstractBlockMarker . getNext ( ) ; } return startBlockMarker == abstractBlockMarker ? null : abstractBlockMarker ; } protected AbstractBlockMarker createBlockMarkerList ( String unformatted ) { Pattern pat = null ; try { pat = Pattern . compile ( "" + BLOCK_BEGIN_RE + "" + DELIMITER_RE + "" + getBlockMiddleRegex ( ) + "" + DELIMITER_RE + "" + BLOCK_END_RE + "" + LITERAL_BEGIN_RE + "" + DELIMITER_RE ) ; } catch ( PatternSyntaxException e ) { System . out . println ( e ) ; } int pos = ; AbstractBlockMarker lastBlockMarker = new NeutralMarker ( "" , ) ; AbstractBlockMarker firstBlockMarker = lastBlockMarker ; Matcher re = pat . matcher ( unformatted ) ; while ( pos != - && re . find ( pos ) ) { AbstractBlockMarker newBlockMarker = null ; if ( re . group ( BLOCK_BEGIN_PAREN ) != null ) { pos = re . end ( BLOCK_BEGIN_PAREN ) ; String blockBeginStr = re . group ( BLOCK_BEGIN_PAREN ) ; if ( MODIFIER_RE . matcher ( blockBeginStr ) . matches ( ) && ! this . isRubyExprBegin ( unformatted , re . start ( BLOCK_BEGIN_PAREN ) , "" ) ) { continue ; } if ( blockBeginStr . equals ( "" ) && this . isNonBlockDo ( unformatted , re . start ( BLOCK_BEGIN_PAREN ) ) ) { continue ; } newBlockMarker = new BeginBlockMarker ( re . group ( BLOCK_BEGIN_PAREN ) , re . start ( BLOCK_BEGIN_PAREN ) ) ; } else if ( re . group ( BLOCK_MID_PAREN ) != null ) { pos = re . end ( BLOCK_MID_PAREN ) ; String blockMiddleStr = re . group ( BLOCK_MID_PAREN ) ; if ( MODIFIER_RE . matcher ( blockMiddleStr ) . matches ( ) && ! this . isRubyExprBegin ( unformatted , re . start ( BLOCK_MID_PAREN ) , "" ) ) { continue ; } newBlockMarker = new MidBlockMarker ( re . group ( BLOCK_MID_PAREN ) , re . start ( BLOCK_MID_PAREN ) ) ; } else if ( re . group ( BLOCK_END_PAREN ) != null ) { pos = re . end ( BLOCK_END_PAREN ) ; newBlockMarker = new EndBlockMarker ( re . group ( BLOCK_END_PAREN ) , re . start ( BLOCK_END_PAREN ) ) ; } else if ( re . group ( LITERAL_BEGIN_PAREN ) != null ) { pos = re . end ( LITERAL_BEGIN_PAREN ) ; String matchedLiteralBegin = re . group ( LITERAL_BEGIN_PAREN ) ; if ( matchedLiteralBegin . startsWith ( "" ) ) { int delimitChar = matchedLiteralBegin . charAt ( matchedLiteralBegin . length ( ) - ) ; boolean expand = matchedLiteralBegin . charAt ( ) != '' ; if ( delimitChar == '' ) { pos = this . forwardString ( unformatted , pos , '' , '' , expand ) ; } else if ( delimitChar == '' ) { pos = this . forwardString ( unformatted , pos , '' , '' , expand ) ; } else if ( delimitChar == '' ) { pos = this . forwardString ( unformatted , pos , '' , '' , expand ) ; } else if ( delimitChar == '' ) { pos = this . forwardString ( unformatted , pos , '' , '>' , expand ) ; } else { pos = unformatted . indexOf ( delimitChar , pos ) ; } } else if ( matchedLiteralBegin . startsWith ( "" ) ) { int posClosingSlash = this . forwardString ( unformatted , pos , '' , "" , true ) ; if ( posClosingSlash == pos ) { continue ; } int posNextLine = unformatted . indexOf ( "" , pos ) ; if ( posNextLine != - && posClosingSlash > posNextLine ) { continue ; } pos = posClosingSlash ; } else if ( matchedLiteralBegin . startsWith ( "" ) ) { if ( pos > && unformatted . charAt ( pos - ) == '' ) { continue ; } pos = this . forwardString ( unformatted , pos , '' , "" , true ) ; } else if ( matchedLiteralBegin . startsWith ( "" ) ) { int startId = ; int endId = matchedLiteralBegin . length ( ) ; boolean isMinus = ( matchedLiteralBegin . charAt ( startId ) == '' ) ; if ( isMinus ) { startId += ; } if ( startId < matchedLiteralBegin . length ( ) - && matchedLiteralBegin . charAt ( startId ) == '' ) { startId += ; endId -= ; } String reStr = ( isMinus ? "" : "" ) + matchedLiteralBegin . substring ( startId , endId ) ; try { Pattern idSearch = Pattern . compile ( reStr ) ; Matcher matcher = idSearch . matcher ( unformatted ) ; if ( matcher . find ( pos ) ) { pos = matcher . end ( ) ; } else { pos = - ; } } catch ( PatternSyntaxException e1 ) { continue ; } } else { for ( int i = ; i < LITERAL_BEGIN_LITERALS . length ; i ++ ) { if ( LITERAL_BEGIN_LITERALS [ i ] . equals ( matchedLiteralBegin ) ) { Pattern matchEnd = LITERAL_END_RES_COMPILED [ i ] ; pos = - ; Matcher tmpMatch = matchEnd . matcher ( unformatted ) ; if ( tmpMatch . find ( re . end ( LITERAL_BEGIN_PAREN ) - ) ) { pos = tmpMatch . end ( ) ; } break ; } } } newBlockMarker = new NoFormattingMarker ( matchedLiteralBegin , re . start ( LITERAL_BEGIN_PAREN ) ) ; if ( pos != - ) { lastBlockMarker . setNext ( newBlockMarker ) ; lastBlockMarker = newBlockMarker ; newBlockMarker = new NeutralMarker ( "" , pos ) ; } } else { String delimiter = re . group ( ) ; if ( delimiter . equals ( "" ) ) { pos = unformatted . indexOf ( "" , re . end ( ) ) ; continue ; } else if ( delimiter . equals ( "" ) ) { newBlockMarker = new BeginBlockMarker ( "" , re . start ( ) ) ; } else if ( delimiter . equals ( "" ) ) { newBlockMarker = new EndBlockMarker ( "" , re . start ( ) ) ; } else if ( delimiter . equals ( "" ) ) { newBlockMarker = new FixLengthMarker ( "" , re . start ( ) ) ; } else if ( delimiter . equals ( "" ) ) { newBlockMarker = new NeutralMarker ( "" , re . start ( ) ) ; } pos = re . end ( ) ; } if ( newBlockMarker == null ) { continue ; } if ( lastBlockMarker != null ) { lastBlockMarker . setNext ( newBlockMarker ) ; } lastBlockMarker = newBlockMarker ; } return firstBlockMarker ; } private String getBlockMiddleRegex ( ) { if ( this . preferences . indent_case_body ) { return BLOCK_MID_RE ; } StringBuffer buffer = new StringBuffer ( BLOCK_MID_RE ) ; buffer . insert ( , "" ) ; return buffer . toString ( ) ; } protected int forwardString ( String unformatted , int pos , char opening , char closing , boolean expand ) { return this . forwardString ( unformatted , pos , opening , "" + opening + "" + closing , expand ) ; } protected int forwardString ( String unformatted , int pos , char opening , String term , boolean expand ) { int n = ; try { Pattern pat = Pattern . compile ( expand ? "" + term + "" : "" + term + "" ) ; Matcher re = pat . matcher ( unformatted ) ; while ( re . find ( pos ) && n > ) { if ( re . group ( ) != null ) { pos = this . forwardString ( unformatted , re . end ( ) , '' , "" , expand ) ; } else { pos = re . end ( ) ; if ( pos > && unformatted . charAt ( pos - ) == '' && unformatted . charAt ( pos - ) != '' ) { continue ; } if ( re . group ( ) . charAt ( ) == opening ) { n += ; } else { n -= ; } } } } catch ( PatternSyntaxException e ) { e . printStackTrace ( ) ; } return pos ; } protected int skipCharsBackward ( String unformatted , int pos ) { do { if ( pos == ) { return ; } if ( unformatted . charAt ( pos - ) == '' ) { return pos ; } pos -= ; } while ( unformatted . charAt ( pos ) == '' || unformatted . charAt ( pos ) == '' ) ; return pos ; } protected int backToIndentation ( String unformatted , int pos ) { do { if ( pos == ) { return ; } if ( unformatted . charAt ( pos - ) == '' ) { break ; } pos -= ; } while ( true ) ; while ( unformatted . charAt ( pos ) == '' || unformatted . charAt ( pos ) == '' ) { pos += ; if ( pos == unformatted . length ( ) ) { break ; } } return pos ; } protected int posOfLineStart ( String unformatted , int pos ) { do { if ( pos == ) { return ; } if ( unformatted . charAt ( pos - ) == '' ) { break ; } pos -= ; } while ( true ) ; return pos ; } protected boolean matchREBackward ( String str , Pattern re ) { int pos = str . length ( ) - ; while ( pos >= ) { if ( str . charAt ( pos ) == '' ) { return false ; } if ( re . matcher ( str ) . find ( pos ) ) { return true ; } pos -= ; } return false ; } protected boolean isRubyExprBegin ( String unformatted , int pos , String option ) { int firstNonSpaceCharInLine = this . skipCharsBackward ( unformatted , pos ) ; if ( firstNonSpaceCharInLine == || unformatted . charAt ( firstNonSpaceCharInLine - ) == '' ) { return true ; } char c = unformatted . charAt ( firstNonSpaceCharInLine ) ; if ( c == '' ) { return true ; } String c_str = "" + c ; if ( OPERATOR_RE . matcher ( c_str ) . matches ( ) ) { return true ; } return false ; } protected boolean isNonBlockDo ( String unformatted , int pos ) { int lineStart = this . posOfLineStart ( unformatted , pos ) ; return this . matchREBackward ( new String ( unformatted . substring ( lineStart , pos ) ) , NON_BLOCK_DO_RE ) ; } public TextEdit format ( int kind , String source , int offset , int length , int indentationLevel , String lineSeparator ) { String newText = formatString ( new String ( source . substring ( offset , length ) ) , indentationLevel ) ; return new ReplaceEdit ( offset , length , newText ) ; } private String formatString ( String unformatted , int indentationLevel ) { AbstractBlockMarker firstAbstractBlockMarker = this . createBlockMarkerList ( unformatted ) ; if ( isDebug ( ) ) { firstAbstractBlockMarker . print ( ) ; } try { return this . formatString ( unformatted , firstAbstractBlockMarker , indentationLevel ) ; } catch ( PatternSyntaxException ex ) { return unformatted ; } } } package org . rubypeople . rdt . internal . formatter ; public class BeginBlockMarker extends AbstractBlockMarker { public BeginBlockMarker ( String aKeyword , int aLine ) { super ( aKeyword , aLine ) ; } protected void indentAfterPrint ( IndentationState state ) { if ( ! ( state . getPos ( ) > this . getPos ( ) ) ) { state . incIndentationLevel ( ) ; } } protected void indentBeforePrint ( IndentationState state ) { if ( state . getPos ( ) > this . getPos ( ) ) { state . incIndentationLevel ( ) ; } } } package org . rubypeople . rdt . internal . formatter ; public class FixLengthMarker extends AbstractBlockMarker { int posInLine = - ; public FixLengthMarker ( String aKeyword , int aPos ) { super ( aKeyword , aPos ) ; } protected int getPosInLine ( IndentationState state ) { if ( posInLine == - ) { posInLine = this . calculatePosInLine ( state ) ; } return posInLine ; } private int calculatePosInLine ( IndentationState state ) { int i = this . getPos ( ) ; while ( ! state . getUnformattedText ( ) . substring ( i , i + ) . equals ( "" ) ) { i -= ; if ( i == ) { break ; } } while ( state . getUnformattedText ( ) . charAt ( i + ) == '' || state . getUnformattedText ( ) . charAt ( i + ) == '' ) { i += ; } return this . getPos ( ) - i ; } protected void indentBeforePrint ( IndentationState state ) { state . setFixIndentation ( this . getPosInLine ( state ) ) ; } protected void indentAfterPrint ( IndentationState state ) { } } package org . rubypeople . rdt . internal . formatter ; import java . io . StringWriter ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . formatter . ReWriterContext ; import org . rubypeople . rdt . core . formatter . ReWriterFactory ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . parser . RubyParserWithComments ; public class ASTBasedCodeFormatter extends CodeFormatter { @ Override public TextEdit format ( int kind , String source , int offset , int length , int indentationLevel , String lineSeparator ) { StringWriter writer = new StringWriter ( ) ; EditableFormatHelper helper = new EditableFormatHelper ( ) ; helper . setLineDelimiter ( lineSeparator ) ; helper . setSpacesBeforeAndAfterAssignments ( true ) ; helper . setAlwaysParanthesizeMethodDefs ( true ) ; source = source . substring ( offset , length ) ; ReWriterContext context = new ReWriterContext ( writer , source , helper ) ; ReWriterFactory factory = new ReWriterFactory ( context ) ; ReWriteVisitor visitor = factory . createReWriteVisitor ( ) ; RubyParser parser = new RubyParserWithComments ( ) ; Node root = parser . parse ( source ) . getAST ( ) ; root . accept ( visitor ) ; writer . append ( lineSeparator ) ; String result = writer . getBuffer ( ) . toString ( ) ; return new ReplaceEdit ( offset , length , result ) ; } } package org . rubypeople . rdt . internal . formatter ; import java . util . Map ; public abstract class AbstractBlockMarker { protected int pos ; private AbstractBlockMarker next ; private String keyword ; protected AbstractBlockMarker ( String aKeyword , int aPos ) { this . keyword = aKeyword ; this . pos = aPos ; } protected abstract void indentBeforePrint ( IndentationState state ) ; protected abstract void indentAfterPrint ( IndentationState state ) ; public int getPos ( ) { return pos ; } public AbstractBlockMarker getNext ( ) { return next ; } public String getKeyword ( ) { return keyword ; } protected void setKeyword ( String keyword ) { this . keyword = keyword ; } public void setNext ( AbstractBlockMarker next ) { this . next = next ; } public void appendIndentedLine ( StringBuffer sb , IndentationState state , String originalLine , String strippedLine , Map options ) { sb . append ( state . getIndentationString ( options ) ) ; sb . append ( strippedLine ) ; } public void print ( ) { System . out . println ( "" + pos + "" + this . getClass ( ) . getName ( ) + "" + this . getKeyword ( ) ) ; if ( next != null ) { next . print ( ) ; } } } package org . rubypeople . rdt . internal . formatter ; public class MidBlockMarker extends AbstractBlockMarker { public MidBlockMarker ( String aKeyword , int aLine ) { super ( aKeyword , aLine ) ; } protected void indentAfterPrint ( IndentationState state ) { state . incIndentationLevel ( ) ; } protected void indentBeforePrint ( IndentationState state ) { state . decIndentationLevel ( ) ; } } package org . rubypeople . rdt . internal . formatter ; import java . util . Map ; public class NoFormattingMarker extends AbstractBlockMarker { public NoFormattingMarker ( String aKeyword , int aPos ) { super ( aKeyword , aPos ) ; } public boolean isFormatting ( ) { return false ; } protected void indentAfterPrint ( IndentationState state ) { } protected void indentBeforePrint ( IndentationState state ) { } public void appendIndentedLine ( StringBuffer sb , IndentationState state , String originalLine , String strippedLine , Map options ) { sb . append ( originalLine ) ; } } package org . rubypeople . rdt . internal . formatter ; import java . io . PrintWriter ; public class Indentor { private int indentation ; private int indentationSteps ; private char indentationChar ; public Indentor ( int indentationSteps , char indentationChar ) { this . indentationSteps = indentationSteps ; this . indentationChar = indentationChar ; } public void indent ( ) { indentation += indentationSteps ; } public void outdent ( ) { indentation -= indentationSteps ; } public void printIndentation ( PrintWriter out ) { for ( int i = ; i < indentation ; i ++ ) out . print ( indentationChar ) ; } public char getIndentationChar ( ) { return indentationChar ; } public void setIndentationChar ( char indentationChar ) { this . indentationChar = indentationChar ; } public int getIndentationSteps ( ) { return indentationSteps ; } public void setIndentationSteps ( int indentationSteps ) { this . indentationSteps = indentationSteps ; } } package org . rubypeople . rdt . internal . formatter ; public class EndBlockMarker extends AbstractBlockMarker { public EndBlockMarker ( String aKeyword , int aLine ) { super ( aKeyword , aLine ) ; } protected void indentAfterPrint ( IndentationState state ) { } protected void indentBeforePrint ( IndentationState state ) { state . decIndentationLevel ( ) ; } } package org . rubypeople . rdt . internal . compiler . util ; public final class SimpleSet implements Cloneable { public Object [ ] values ; public int elementSize ; public int threshold ; public SimpleSet ( ) { this ( ) ; } public SimpleSet ( int size ) { if ( size < ) size = ; this . elementSize = ; this . threshold = size + ; this . values = new Object [ * size + ] ; } public Object add ( Object object ) { int length = this . values . length ; int index = ( object . hashCode ( ) & ) % length ; Object current ; while ( ( current = this . values [ index ] ) != null ) { if ( current . equals ( object ) ) return this . values [ index ] = object ; if ( ++ index == length ) index = ; } this . values [ index ] = object ; if ( ++ this . elementSize > this . threshold ) rehash ( ) ; return object ; } public void asArray ( Object [ ] copy ) { if ( this . elementSize != copy . length ) throw new IllegalArgumentException ( ) ; int index = this . elementSize ; for ( int i = , l = this . values . length ; i < l && index > ; i ++ ) if ( this . values [ i ] != null ) copy [ -- index ] = this . values [ i ] ; } public void clear ( ) { for ( int i = this . values . length ; -- i >= ; ) this . values [ i ] = null ; this . elementSize = ; } public Object clone ( ) throws CloneNotSupportedException { SimpleSet result = ( SimpleSet ) super . clone ( ) ; result . elementSize = this . elementSize ; result . threshold = this . threshold ; int length = this . values . length ; result . values = new Object [ length ] ; System . arraycopy ( this . values , , result . values , , length ) ; return result ; } public boolean includes ( Object object ) { int length = values . length ; int index = ( object . hashCode ( ) & ) % length ; Object current ; while ( ( current = values [ index ] ) != null ) { if ( current . equals ( object ) ) return true ; if ( ++ index == length ) index = ; } return false ; } public Object remove ( Object object ) { int length = values . length ; int index = ( object . hashCode ( ) & ) % length ; Object current ; while ( ( current = values [ index ] ) != null ) { if ( current . equals ( object ) ) { elementSize -- ; Object oldValue = values [ index ] ; values [ index ] = null ; if ( values [ index + == length ? : index + ] != null ) rehash ( ) ; return oldValue ; } if ( ++ index == length ) index = ; } return null ; } private void rehash ( ) { SimpleSet newSet = new SimpleSet ( elementSize * ) ; Object current ; for ( int i = values . length ; -- i >= ; ) if ( ( current = values [ i ] ) != null ) newSet . add ( current ) ; this . values = newSet . values ; this . elementSize = newSet . elementSize ; this . threshold = newSet . threshold ; } public String toString ( ) { String s = "" ; Object object ; for ( int i = , l = values . length ; i < l ; i ++ ) if ( ( object = values [ i ] ) != null ) s += object . toString ( ) + "" ; return s ; } } package org . rubypeople . rdt . internal . compiler . util ; public final class HashtableOfLong { public long [ ] keyTable ; public Object [ ] valueTable ; public int elementSize ; int threshold ; public HashtableOfLong ( ) { this ( ) ; } public HashtableOfLong ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . keyTable = new long [ extraRoom ] ; this . valueTable = new Object [ extraRoom ] ; } public boolean containsKey ( long key ) { int length = keyTable . length , index = ( ( int ) ( key > > > ) ) % length ; long currentKey ; while ( ( currentKey = keyTable [ index ] ) != ) { if ( currentKey == key ) return true ; if ( ++ index == length ) { index = ; } } return false ; } public Object get ( long key ) { int length = keyTable . length , index = ( ( int ) ( key > > > ) ) % length ; long currentKey ; while ( ( currentKey = keyTable [ index ] ) != ) { if ( currentKey == key ) return valueTable [ index ] ; if ( ++ index == length ) { index = ; } } return null ; } public Object put ( long key , Object value ) { int length = keyTable . length , index = ( ( int ) ( key > > > ) ) % length ; long currentKey ; while ( ( currentKey = keyTable [ index ] ) != ) { if ( currentKey == key ) return valueTable [ index ] = value ; if ( ++ index == length ) { index = ; } } keyTable [ index ] = key ; valueTable [ index ] = value ; if ( ++ elementSize > threshold ) rehash ( ) ; return value ; } private void rehash ( ) { HashtableOfLong newHashtable = new HashtableOfLong ( elementSize * ) ; long currentKey ; for ( int i = keyTable . length ; -- i >= ; ) if ( ( currentKey = keyTable [ i ] ) != ) newHashtable . put ( currentKey , valueTable [ i ] ) ; this . keyTable = newHashtable . keyTable ; this . valueTable = newHashtable . valueTable ; this . threshold = newHashtable . threshold ; } public int size ( ) { return elementSize ; } public String toString ( ) { String s = "" ; Object object ; for ( int i = , length = valueTable . length ; i < length ; i ++ ) if ( ( object = valueTable [ i ] ) != null ) s += keyTable [ i ] + "" + object . toString ( ) + "" ; return s ; } } package org . rubypeople . rdt . internal . compiler . util ; public final class SimpleLookupTable implements Cloneable { public Object [ ] keyTable ; public Object [ ] valueTable ; public int elementSize ; public int threshold ; public SimpleLookupTable ( ) { this ( ) ; } public SimpleLookupTable ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . keyTable = new Object [ extraRoom ] ; this . valueTable = new Object [ extraRoom ] ; } public Object clone ( ) throws CloneNotSupportedException { SimpleLookupTable result = ( SimpleLookupTable ) super . clone ( ) ; result . elementSize = this . elementSize ; result . threshold = this . threshold ; int length = this . keyTable . length ; result . keyTable = new Object [ length ] ; System . arraycopy ( this . keyTable , , result . keyTable , , length ) ; length = this . valueTable . length ; result . valueTable = new Object [ length ] ; System . arraycopy ( this . valueTable , , result . valueTable , , length ) ; return result ; } public boolean containsKey ( Object key ) { int length = keyTable . length ; int index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) return true ; if ( ++ index == length ) index = ; } return false ; } public Object get ( Object key ) { int length = keyTable . length ; int index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) return valueTable [ index ] ; if ( ++ index == length ) index = ; } return null ; } public Object getKey ( Object key ) { int length = keyTable . length ; int index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) return currentKey ; if ( ++ index == length ) index = ; } return key ; } public Object keyForValue ( Object valueToMatch ) { if ( valueToMatch != null ) for ( int i = , l = keyTable . length ; i < l ; i ++ ) if ( keyTable [ i ] != null && valueToMatch . equals ( valueTable [ i ] ) ) return keyTable [ i ] ; return null ; } public Object put ( Object key , Object value ) { int length = keyTable . length ; int index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) return valueTable [ index ] = value ; if ( ++ index == length ) index = ; } keyTable [ index ] = key ; valueTable [ index ] = value ; if ( ++ elementSize > threshold ) rehash ( ) ; return value ; } public Object removeKey ( Object key ) { int length = keyTable . length ; int index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) { elementSize -- ; Object oldValue = valueTable [ index ] ; keyTable [ index ] = null ; valueTable [ index ] = null ; if ( keyTable [ index + == length ? : index + ] != null ) rehash ( ) ; return oldValue ; } if ( ++ index == length ) index = ; } return null ; } public void removeValue ( Object valueToRemove ) { boolean rehash = false ; for ( int i = , l = valueTable . length ; i < l ; i ++ ) { Object value = valueTable [ i ] ; if ( value != null && value . equals ( valueToRemove ) ) { elementSize -- ; keyTable [ i ] = null ; valueTable [ i ] = null ; if ( ! rehash && keyTable [ i + == l ? : i + ] != null ) rehash = true ; } } if ( rehash ) rehash ( ) ; } private void rehash ( ) { SimpleLookupTable newLookupTable = new SimpleLookupTable ( elementSize * ) ; Object currentKey ; for ( int i = keyTable . length ; -- i >= ; ) if ( ( currentKey = keyTable [ i ] ) != null ) newLookupTable . put ( currentKey , valueTable [ i ] ) ; this . keyTable = newLookupTable . keyTable ; this . valueTable = newLookupTable . valueTable ; this . elementSize = newLookupTable . elementSize ; this . threshold = newLookupTable . threshold ; } public String toString ( ) { String s = "" ; Object object ; for ( int i = , l = valueTable . length ; i < l ; i ++ ) if ( ( object = valueTable [ i ] ) != null ) s += keyTable [ i ] . toString ( ) + "" + object . toString ( ) + "" ; return s ; } } package org . rubypeople . rdt . internal . compiler . util ; public final class HashtableOfObjectToInt implements Cloneable { public Object [ ] keyTable ; public int [ ] valueTable ; public int elementSize ; int threshold ; public HashtableOfObjectToInt ( ) { this ( ) ; } public HashtableOfObjectToInt ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . keyTable = new Object [ extraRoom ] ; this . valueTable = new int [ extraRoom ] ; } public Object clone ( ) throws CloneNotSupportedException { HashtableOfObjectToInt result = ( HashtableOfObjectToInt ) super . clone ( ) ; result . elementSize = this . elementSize ; result . threshold = this . threshold ; int length = this . keyTable . length ; result . keyTable = new Object [ length ] ; System . arraycopy ( this . keyTable , , result . keyTable , , length ) ; length = this . valueTable . length ; result . valueTable = new int [ length ] ; System . arraycopy ( this . valueTable , , result . valueTable , , length ) ; return result ; } public boolean containsKey ( Object key ) { int length = this . keyTable . length , index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) return true ; if ( ++ index == length ) { index = ; } } return false ; } public int get ( Object key ) { int length = this . keyTable . length , index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) return this . valueTable [ index ] ; if ( ++ index == length ) { index = ; } } return - ; } public void keysToArray ( Object [ ] array ) { int index = ; for ( int i = , length = this . keyTable . length ; i < length ; i ++ ) { if ( this . keyTable [ i ] != null ) array [ index ++ ] = this . keyTable [ i ] ; } } public int put ( Object key , int value ) { int length = this . keyTable . length , index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) return this . valueTable [ index ] = value ; if ( ++ index == length ) { index = ; } } this . keyTable [ index ] = key ; this . valueTable [ index ] = value ; if ( ++ elementSize > threshold ) rehash ( ) ; return value ; } public int removeKey ( Object key ) { int length = this . keyTable . length , index = ( key . hashCode ( ) & ) % length ; Object currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . equals ( key ) ) { int value = this . valueTable [ index ] ; elementSize -- ; this . keyTable [ index ] = null ; rehash ( ) ; return value ; } if ( ++ index == length ) { index = ; } } return - ; } private void rehash ( ) { HashtableOfObjectToInt newHashtable = new HashtableOfObjectToInt ( elementSize * ) ; Object currentKey ; for ( int i = this . keyTable . length ; -- i >= ; ) if ( ( currentKey = this . keyTable [ i ] ) != null ) newHashtable . put ( currentKey , this . valueTable [ i ] ) ; this . keyTable = newHashtable . keyTable ; this . valueTable = newHashtable . valueTable ; this . threshold = newHashtable . threshold ; } public int size ( ) { return elementSize ; } public String toString ( ) { String s = "" ; Object key ; for ( int i = , length = this . keyTable . length ; i < length ; i ++ ) if ( ( key = this . keyTable [ i ] ) != null ) s += key + "" + this . valueTable [ i ] + "" ; return s ; } } package org . rubypeople . rdt . internal . compiler . util ; public final class ObjectVector { static int INITIAL_SIZE = ; public int size ; int maxSize ; Object [ ] elements ; public ObjectVector ( ) { this ( INITIAL_SIZE ) ; } public ObjectVector ( int initialSize ) { this . maxSize = initialSize > ? initialSize : INITIAL_SIZE ; this . size = ; this . elements = new Object [ this . maxSize ] ; } public void add ( Object newElement ) { if ( this . size == this . maxSize ) System . arraycopy ( this . elements , , ( this . elements = new Object [ this . maxSize *= ] ) , , this . size ) ; this . elements [ this . size ++ ] = newElement ; } public void addAll ( Object [ ] newElements ) { if ( this . size + newElements . length >= this . maxSize ) { maxSize = this . size + newElements . length ; System . arraycopy ( this . elements , , ( this . elements = new Object [ this . maxSize ] ) , , this . size ) ; } System . arraycopy ( newElements , , this . elements , size , newElements . length ) ; this . size += newElements . length ; } public void addAll ( ObjectVector newVector ) { if ( this . size + newVector . size >= this . maxSize ) { maxSize = this . size + newVector . size ; System . arraycopy ( this . elements , , ( this . elements = new Object [ this . maxSize ] ) , , this . size ) ; } System . arraycopy ( newVector . elements , , this . elements , size , newVector . size ) ; this . size += newVector . size ; } public boolean containsIdentical ( Object element ) { for ( int i = this . size ; -- i >= ; ) if ( element == this . elements [ i ] ) return true ; return false ; } public boolean contains ( Object element ) { for ( int i = this . size ; -- i >= ; ) if ( element . equals ( this . elements [ i ] ) ) return true ; return false ; } public void copyInto ( Object [ ] targetArray ) { this . copyInto ( targetArray , ) ; } public void copyInto ( Object [ ] targetArray , int index ) { System . arraycopy ( this . elements , , targetArray , index , this . size ) ; } public Object elementAt ( int index ) { return this . elements [ index ] ; } public Object find ( Object element ) { for ( int i = this . size ; -- i >= ; ) if ( element . equals ( this . elements [ i ] ) ) return element ; return null ; } public Object remove ( Object element ) { for ( int i = this . size ; -- i >= ; ) if ( element . equals ( this . elements [ i ] ) ) { System . arraycopy ( this . elements , i + , this . elements , i , -- this . size - i ) ; this . elements [ this . size ] = null ; return element ; } return null ; } public void removeAll ( ) { for ( int i = this . size ; -- i >= ; ) this . elements [ i ] = null ; this . size = ; } public int size ( ) { return this . size ; } public String toString ( ) { String s = "" ; for ( int i = ; i < this . size ; i ++ ) s += this . elements [ i ] . toString ( ) + "" ; return s ; } } package org . rubypeople . rdt . internal . compiler . util ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public final class HashtableOfIntValues implements Cloneable { public static final int NO_VALUE = Integer . MIN_VALUE ; public char [ ] keyTable [ ] ; public int valueTable [ ] ; public int elementSize ; int threshold ; public HashtableOfIntValues ( ) { this ( ) ; } public HashtableOfIntValues ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . keyTable = new char [ extraRoom ] [ ] ; this . valueTable = new int [ extraRoom ] ; } public Object clone ( ) throws CloneNotSupportedException { HashtableOfIntValues result = ( HashtableOfIntValues ) super . clone ( ) ; result . elementSize = this . elementSize ; result . threshold = this . threshold ; int length = this . keyTable . length ; result . keyTable = new char [ length ] [ ] ; System . arraycopy ( this . keyTable , , result . keyTable , , length ) ; length = this . valueTable . length ; result . valueTable = new int [ length ] ; System . arraycopy ( this . valueTable , , result . valueTable , , length ) ; return result ; } public boolean containsKey ( char [ ] key ) { int length = keyTable . length , index = CharOperation . hashCode ( key ) % length ; int keyLength = key . length ; char [ ] currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && CharOperation . equals ( currentKey , key ) ) return true ; if ( ++ index == length ) { index = ; } } return false ; } public int get ( char [ ] key ) { int length = keyTable . length , index = CharOperation . hashCode ( key ) % length ; int keyLength = key . length ; char [ ] currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && CharOperation . equals ( currentKey , key ) ) return valueTable [ index ] ; if ( ++ index == length ) { index = ; } } return NO_VALUE ; } public int put ( char [ ] key , int value ) { int length = keyTable . length , index = CharOperation . hashCode ( key ) % length ; int keyLength = key . length ; char [ ] currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && CharOperation . equals ( currentKey , key ) ) return valueTable [ index ] = value ; if ( ++ index == length ) { index = ; } } keyTable [ index ] = key ; valueTable [ index ] = value ; if ( ++ elementSize > threshold ) rehash ( ) ; return value ; } public int removeKey ( char [ ] key ) { int length = keyTable . length , index = CharOperation . hashCode ( key ) % length ; int keyLength = key . length ; char [ ] currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && CharOperation . equals ( currentKey , key ) ) { int value = valueTable [ index ] ; elementSize -- ; keyTable [ index ] = null ; valueTable [ index ] = NO_VALUE ; rehash ( ) ; return value ; } if ( ++ index == length ) { index = ; } } return NO_VALUE ; } private void rehash ( ) { HashtableOfIntValues newHashtable = new HashtableOfIntValues ( elementSize * ) ; char [ ] currentKey ; for ( int i = keyTable . length ; -- i >= ; ) if ( ( currentKey = keyTable [ i ] ) != null ) newHashtable . put ( currentKey , valueTable [ i ] ) ; this . keyTable = newHashtable . keyTable ; this . valueTable = newHashtable . valueTable ; this . threshold = newHashtable . threshold ; } public int size ( ) { return elementSize ; } public String toString ( ) { String s = "" ; char [ ] key ; for ( int i = , length = valueTable . length ; i < length ; i ++ ) if ( ( key = keyTable [ i ] ) != null ) s += new String ( key ) + "" + valueTable [ i ] + "" ; return s ; } } package org . rubypeople . rdt . internal . compiler . util ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public final class SimpleSetOfCharArray implements Cloneable { public char [ ] [ ] values ; public int elementSize ; public int threshold ; public SimpleSetOfCharArray ( ) { this ( ) ; } public SimpleSetOfCharArray ( int size ) { if ( size < ) size = ; this . elementSize = ; this . threshold = size + ; this . values = new char [ * size + ] [ ] ; } public Object add ( char [ ] object ) { int length = this . values . length ; int index = ( CharOperation . hashCode ( object ) & ) % length ; char [ ] current ; while ( ( current = this . values [ index ] ) != null ) { if ( CharOperation . equals ( current , object ) ) return this . values [ index ] = object ; if ( ++ index == length ) index = ; } this . values [ index ] = object ; if ( ++ this . elementSize > this . threshold ) rehash ( ) ; return object ; } public void asArray ( Object [ ] copy ) { if ( this . elementSize != copy . length ) throw new IllegalArgumentException ( ) ; int index = this . elementSize ; for ( int i = , l = this . values . length ; i < l && index > ; i ++ ) if ( this . values [ i ] != null ) copy [ -- index ] = this . values [ i ] ; } public void clear ( ) { for ( int i = this . values . length ; -- i >= ; ) this . values [ i ] = null ; this . elementSize = ; } public Object clone ( ) throws CloneNotSupportedException { SimpleSetOfCharArray result = ( SimpleSetOfCharArray ) super . clone ( ) ; result . elementSize = this . elementSize ; result . threshold = this . threshold ; int length = this . values . length ; result . values = new char [ length ] [ ] ; System . arraycopy ( this . values , , result . values , , length ) ; return result ; } public char [ ] get ( char [ ] object ) { int length = this . values . length ; int index = ( CharOperation . hashCode ( object ) & ) % length ; char [ ] current ; while ( ( current = this . values [ index ] ) != null ) { if ( CharOperation . equals ( current , object ) ) return current ; if ( ++ index == length ) index = ; } this . values [ index ] = object ; if ( ++ this . elementSize > this . threshold ) rehash ( ) ; return object ; } public boolean includes ( char [ ] object ) { int length = values . length ; int index = ( CharOperation . hashCode ( object ) & ) % length ; char [ ] current ; while ( ( current = values [ index ] ) != null ) { if ( CharOperation . equals ( current , object ) ) return true ; if ( ++ index == length ) index = ; } return false ; } public char [ ] remove ( char [ ] object ) { int length = values . length ; int index = ( CharOperation . hashCode ( object ) & ) % length ; char [ ] current ; while ( ( current = values [ index ] ) != null ) { if ( CharOperation . equals ( current , object ) ) { elementSize -- ; char [ ] oldValue = values [ index ] ; values [ index ] = null ; if ( values [ index + == length ? : index + ] != null ) rehash ( ) ; return oldValue ; } if ( ++ index == length ) index = ; } return null ; } private void rehash ( ) { SimpleSetOfCharArray newSet = new SimpleSetOfCharArray ( elementSize * ) ; char [ ] current ; for ( int i = values . length ; -- i >= ; ) if ( ( current = values [ i ] ) != null ) newSet . add ( current ) ; this . values = newSet . values ; this . elementSize = newSet . elementSize ; this . threshold = newSet . threshold ; } public String toString ( ) { String s = "" ; char [ ] object ; for ( int i = , l = values . length ; i < l ; i ++ ) if ( ( object = values [ i ] ) != null ) s += new String ( object ) + "" ; return s ; } } package org . rubypeople . rdt . internal . compiler . util ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public final class HashtableOfObject implements Cloneable { public char [ ] keyTable [ ] ; public Object valueTable [ ] ; public int elementSize ; int threshold ; public HashtableOfObject ( ) { this ( ) ; } public HashtableOfObject ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . keyTable = new char [ extraRoom ] [ ] ; this . valueTable = new Object [ extraRoom ] ; } public void clear ( ) { for ( int i = this . keyTable . length ; -- i >= ; ) { this . keyTable [ i ] = null ; this . valueTable [ i ] = null ; } this . elementSize = ; } public Object clone ( ) throws CloneNotSupportedException { HashtableOfObject result = ( HashtableOfObject ) super . clone ( ) ; result . elementSize = this . elementSize ; result . threshold = this . threshold ; int length = this . keyTable . length ; result . keyTable = new char [ length ] [ ] ; System . arraycopy ( this . keyTable , , result . keyTable , , length ) ; length = this . valueTable . length ; result . valueTable = new Object [ length ] ; System . arraycopy ( this . valueTable , , result . valueTable , , length ) ; return result ; } public boolean containsKey ( char [ ] key ) { int length = keyTable . length , index = CharOperation . hashCode ( key ) % length ; int keyLength = key . length ; char [ ] currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && CharOperation . equals ( currentKey , key ) ) return true ; if ( ++ index == length ) { index = ; } } return false ; } public Object get ( char [ ] key ) { int length = keyTable . length , index = CharOperation . hashCode ( key ) % length ; int keyLength = key . length ; char [ ] currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && CharOperation . equals ( currentKey , key ) ) return valueTable [ index ] ; if ( ++ index == length ) { index = ; } } return null ; } public Object put ( char [ ] key , Object value ) { int length = keyTable . length , index = CharOperation . hashCode ( key ) % length ; int keyLength = key . length ; char [ ] currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && CharOperation . equals ( currentKey , key ) ) return valueTable [ index ] = value ; if ( ++ index == length ) { index = ; } } keyTable [ index ] = key ; valueTable [ index ] = value ; if ( ++ elementSize > threshold ) rehash ( ) ; return value ; } public Object removeKey ( char [ ] key ) { int length = keyTable . length , index = CharOperation . hashCode ( key ) % length ; int keyLength = key . length ; char [ ] currentKey ; while ( ( currentKey = keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && CharOperation . equals ( currentKey , key ) ) { Object value = valueTable [ index ] ; elementSize -- ; keyTable [ index ] = null ; valueTable [ index ] = null ; rehash ( ) ; return value ; } if ( ++ index == length ) { index = ; } } return null ; } private void rehash ( ) { HashtableOfObject newHashtable = new HashtableOfObject ( elementSize * ) ; char [ ] currentKey ; for ( int i = keyTable . length ; -- i >= ; ) if ( ( currentKey = keyTable [ i ] ) != null ) newHashtable . put ( currentKey , valueTable [ i ] ) ; this . keyTable = newHashtable . keyTable ; this . valueTable = newHashtable . valueTable ; this . threshold = newHashtable . threshold ; } public int size ( ) { return elementSize ; } public String toString ( ) { String s = "" ; Object object ; for ( int i = , length = valueTable . length ; i < length ; i ++ ) if ( ( object = valueTable [ i ] ) != null ) s += new String ( keyTable [ i ] ) + "" + object . toString ( ) + "" ; return s ; } } package org . rubypeople . rdt . internal . compiler . parser ; public abstract class ScannerHelper { public final static int MAX_OBVIOUS = ; public final static int [ ] OBVIOUS_IDENT_CHAR_NATURES = new int [ MAX_OBVIOUS ] ; public final static int C_JLS_SPACE = ; public final static int C_SPECIAL = ; public final static int C_IDENT_START = ; public final static int C_UPPER_LETTER = ; public final static int C_LOWER_LETTER = ; public final static int C_IDENT_PART = ; public final static int C_DIGIT = ; public final static int C_SEPARATOR = ; public final static int C_SPACE = ; static { OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_IDENT_PART ; for ( int i = '' ; i <= '' ; i ++ ) OBVIOUS_IDENT_CHAR_NATURES [ i ] = C_DIGIT | C_IDENT_PART ; for ( int i = '' ; i <= '' ; i ++ ) OBVIOUS_IDENT_CHAR_NATURES [ i ] = C_LOWER_LETTER | C_IDENT_PART | C_IDENT_START ; for ( int i = '' ; i <= '' ; i ++ ) OBVIOUS_IDENT_CHAR_NATURES [ i ] = C_UPPER_LETTER | C_IDENT_PART | C_IDENT_START ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SPECIAL | C_IDENT_PART | C_IDENT_START ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SPECIAL | C_IDENT_PART | C_IDENT_START ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE | C_JLS_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE | C_JLS_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE | C_JLS_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE | C_JLS_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ ] = C_SPACE | C_JLS_SPACE ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '>' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; OBVIOUS_IDENT_CHAR_NATURES [ '' ] = C_SEPARATOR ; } public static char toLowerCase ( char c ) { if ( c < MAX_OBVIOUS ) { if ( ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ c ] & ScannerHelper . C_LOWER_LETTER ) != ) { return c ; } else if ( ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ c ] & ScannerHelper . C_UPPER_LETTER ) != ) { return ( char ) ( + c ) ; } } return Character . toLowerCase ( c ) ; } public static boolean isUpperCase ( char c ) { if ( c < MAX_OBVIOUS ) { return ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ c ] & ScannerHelper . C_UPPER_LETTER ) != ; } return Character . isUpperCase ( c ) ; } public static boolean isJavaIdentifierStart ( char c ) { if ( c < MAX_OBVIOUS ) { return ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ c ] & ScannerHelper . C_IDENT_START ) != ; } return Character . isJavaIdentifierStart ( c ) ; } public static boolean isWhitespace ( char c ) { if ( c < MAX_OBVIOUS ) { return ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ c ] & ScannerHelper . C_SPACE ) != ; } return Character . isWhitespace ( c ) ; } } package org . rubypeople . rdt . internal . compiler ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; public interface ISourceElementRequestor { public static class TypeInfo { public int declarationStart ; public boolean isModule = false ; public String name ; public int nameSourceStart ; public int nameSourceEnd ; public String superclass ; public String [ ] modules ; public boolean secondary ; } public static class MethodInfo { public boolean isConstructor = false ; public boolean isClassLevel = false ; public int visibility ; public int declarationStart ; public String name ; public int nameSourceStart ; public int nameSourceEnd ; public String [ ] parameterNames ; public String [ ] blockVars ; } public static class FieldInfo { public int declarationStart ; public String name ; public boolean isDynamic ; public int nameSourceStart ; public int nameSourceEnd ; } public void enterMethod ( MethodInfo method ) ; public void enterConstructor ( MethodInfo constructor ) ; public void enterField ( FieldInfo field ) ; public void enterType ( TypeInfo type ) ; public void enterScript ( ) ; public void exitMethod ( int endOffset ) ; public void exitConstructor ( int endOffset ) ; public void exitField ( int endOffset ) ; public void exitType ( int endOffset ) ; public void exitScript ( int endOffset ) ; public void acceptMethodReference ( String name , int argCount , int offset ) ; public void acceptConstructorReference ( String name , int argCount , int offset ) ; public void acceptFieldReference ( String name , int offset ) ; public void acceptTypeReference ( String name , int startOffset , int endOffset ) ; public void acceptImport ( String value , int startOffset , int endOffset ) ; public void acceptUnknownReference ( String name , int startOffset , int endOffset ) ; public void acceptProblem ( CategorizedProblem problem ) ; public void acceptMixin ( String string ) ; public void acceptModuleFunction ( String function ) ; public void acceptMethodVisibilityChange ( String methodName , int visibility ) ; public void acceptYield ( String name ) ; public void acceptBlock ( int startOffset , int endOffset ) ; } package org . rubypeople . rdt . internal . compiler ; import java . util . HashMap ; import java . util . Map ; import org . rubypeople . rdt . core . RubyCore ; public class CompilerOptions { public static final long EmptyStatement = ; public static final long ConstantReassignment = ; public static final long UnreachableCode = ; public static final long CoreClassMethodRedefinition = ; public static final long Ruby19WhenStatements = ; public static final long Ruby19HashCommaSyntax = ; public static final String ERROR = RubyCore . ERROR ; public static final String WARNING = RubyCore . WARNING ; public static final String IGNORE = RubyCore . IGNORE ; public long errorThreshold = ; public long warningThreshold = ConstantReassignment | UnreachableCode | Ruby19WhenStatements | Ruby19HashCommaSyntax ; public Map < String , String > getMap ( ) { Map < String , String > optionsMap = new HashMap < String , String > ( ) ; optionsMap . put ( RubyCore . COMPILER_PB_EMPTY_STATEMENT , getSeverityString ( EmptyStatement ) ) ; optionsMap . put ( RubyCore . COMPILER_PB_CONSTANT_REASSIGNMENT , getSeverityString ( ConstantReassignment ) ) ; optionsMap . put ( RubyCore . COMPILER_PB_UNREACHABLE_CODE , getSeverityString ( UnreachableCode ) ) ; optionsMap . put ( RubyCore . COMPILER_PB_REDEFINITION_CORE_CLASS_METHOD , getSeverityString ( CoreClassMethodRedefinition ) ) ; optionsMap . put ( RubyCore . COMPILER_PB_RUBY_19_WHEN_STATEMENTS , getSeverityString ( Ruby19WhenStatements ) ) ; optionsMap . put ( RubyCore . COMPILER_PB_RUBY_19_HASH_COMMA_SYTNAX , getSeverityString ( Ruby19HashCommaSyntax ) ) ; return optionsMap ; } public String getSeverityString ( long irritant ) { if ( ( this . warningThreshold & irritant ) != ) return WARNING ; if ( ( this . errorThreshold & irritant ) != ) return ERROR ; return IGNORE ; } public void set ( Map < String , String > optionsMap ) { String optionValue ; if ( ( optionValue = optionsMap . get ( RubyCore . COMPILER_PB_EMPTY_STATEMENT ) ) != null ) updateSeverity ( EmptyStatement , optionValue ) ; if ( ( optionValue = optionsMap . get ( RubyCore . COMPILER_PB_CONSTANT_REASSIGNMENT ) ) != null ) updateSeverity ( ConstantReassignment , optionValue ) ; if ( ( optionValue = optionsMap . get ( RubyCore . COMPILER_PB_UNREACHABLE_CODE ) ) != null ) updateSeverity ( UnreachableCode , optionValue ) ; if ( ( optionValue = optionsMap . get ( RubyCore . COMPILER_PB_REDEFINITION_CORE_CLASS_METHOD ) ) != null ) updateSeverity ( CoreClassMethodRedefinition , optionValue ) ; if ( ( optionValue = optionsMap . get ( RubyCore . COMPILER_PB_RUBY_19_WHEN_STATEMENTS ) ) != null ) updateSeverity ( Ruby19WhenStatements , optionValue ) ; if ( ( optionValue = optionsMap . get ( RubyCore . COMPILER_PB_RUBY_19_HASH_COMMA_SYTNAX ) ) != null ) updateSeverity ( Ruby19HashCommaSyntax , optionValue ) ; } void updateSeverity ( long irritant , String severityString ) { if ( ERROR . equals ( severityString ) ) { this . errorThreshold |= irritant ; this . warningThreshold &= ~ irritant ; } else if ( WARNING . equals ( severityString ) ) { this . errorThreshold &= ~ irritant ; this . warningThreshold |= irritant ; } else if ( IGNORE . equals ( severityString ) ) { this . errorThreshold &= ~ irritant ; this . warningThreshold &= ~ irritant ; } } } package org . rubypeople . rdt . internal . ti ; import java . util . LinkedList ; import java . util . List ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . jruby . common . NullWarnings ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . internal . core . parser . RdtWarnings ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . ti . util . FirstPrecursorNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; import org . rubypeople . rdt . internal . ti . util . ScopedNodeLocator ; public class DefaultReferenceFinder implements IReferenceFinder { private static final boolean VERBOSE = false ; public List < ISourcePosition > findReferences ( String source , int offset ) { List < ISourcePosition > references = new LinkedList < ISourcePosition > ( ) ; RubyParser parser = new RubyParser ( new NullWarnings ( ) ) ; Node root = parser . parse ( source ) . getAST ( ) ; Node orig = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( root , offset ) ; log ( "" + orig . getClass ( ) . getName ( ) ) ; if ( isLocalVarRef ( orig ) ) { pushLocalVarRefs ( root , orig , references ) ; } if ( isInstanceVarRef ( orig ) ) { pushInstVarRefs ( root , orig , references ) ; } if ( isGlobalVarRef ( orig ) ) { pushGlobalVarRefs ( root , orig , references ) ; } if ( orig instanceof ConstNode ) { pushConstRefs ( root , orig , references ) ; } return references ; } private ISourcePosition getPositionOfName ( Node node , Node scope ) { ISourcePosition pos = node . getPosition ( ) ; String name = null ; if ( isLocalVarRef ( node ) ) { name = getLocalVarRefName ( node , scope ) ; } if ( isInstanceVarRef ( node ) ) { name = getInstVarRefName ( node , scope ) ; } if ( isGlobalVarRef ( node ) ) { name = getGlobalVarRefName ( node ) ; } if ( node instanceof ConstNode ) { name = ( ( ConstNode ) node ) . getName ( ) ; } if ( name == null ) { System . err . println ( "" + node . toString ( ) + "" + scope . toString ( ) ) ; name = "" ; } return new IDESourcePosition ( pos . getFile ( ) , pos . getStartLine ( ) , pos . getEndLine ( ) , pos . getStartOffset ( ) , pos . getStartOffset ( ) + name . length ( ) ) ; } private String getLocalVarRefName ( Node node , Node scope ) { if ( node instanceof INameNode ) { return ( ( INameNode ) node ) . getName ( ) ; } return null ; } private String getClassNodeName ( ClassNode classNode ) { if ( classNode . getCPath ( ) instanceof Colon2Node ) { Colon2Node c2node = ( Colon2Node ) classNode . getCPath ( ) ; return c2node . getName ( ) ; } System . err . println ( "" + classNode . toString ( ) ) ; return null ; } private String getInstVarRefName ( Node node , Node scope ) { if ( node instanceof InstAsgnNode ) { return ( ( InstAsgnNode ) node ) . getName ( ) ; } if ( node instanceof ArgumentNode ) { return ( ( ArgumentNode ) node ) . getName ( ) ; } if ( node instanceof InstVarNode ) { return ( ( InstVarNode ) node ) . getName ( ) ; } if ( node instanceof DVarNode ) { return ( ( DVarNode ) node ) . getName ( ) ; } return null ; } private String getGlobalVarRefName ( Node node ) { if ( node instanceof GlobalVarNode ) { return ( ( GlobalVarNode ) node ) . getName ( ) ; } if ( node instanceof GlobalAsgnNode ) { return ( ( GlobalAsgnNode ) node ) . getName ( ) ; } return null ; } private boolean isLocalVarRef ( Node node ) { return ( ( node instanceof LocalAsgnNode ) || ( node instanceof ArgumentNode ) || ( node instanceof LocalVarNode ) ) ; } private boolean isInstanceVarRef ( Node node ) { return ( ( node instanceof InstAsgnNode ) || ( node instanceof InstVarNode ) ) ; } private boolean isGlobalVarRef ( Node node ) { return ( ( node instanceof GlobalAsgnNode ) || ( node instanceof GlobalVarNode ) ) ; } private void pushLocalVarRefs ( Node root , Node orig , List < ISourcePosition > references ) { log ( "" + orig . toString ( ) ) ; Node searchSpace = FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( root , orig . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( ( node instanceof DefnNode ) || ( node instanceof DefsNode ) ) ; } } ) ; if ( searchSpace == null ) { searchSpace = root ; } final Node finalSearchSpace = searchSpace ; final String origName = getLocalVarRefName ( orig , searchSpace ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { String name = getLocalVarRefName ( node , finalSearchSpace ) ; return ( name != null && name . equals ( origName ) ) ; } } ) ; for ( Node searchResult : searchResults ) { references . add ( getPositionOfName ( searchResult , searchSpace ) ) ; } } private void log ( String string ) { if ( VERBOSE ) System . out . println ( string ) ; } private void pushInstVarRefs ( Node root , Node orig , List < ISourcePosition > references ) { log ( "" + orig . toString ( ) ) ; Node searchSpace ; ClassNode enclosingClass = ( ClassNode ) FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( root , orig . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ClassNode ) ; } } ) ; if ( enclosingClass == null ) { searchSpace = root ; } else { final String className = getClassNodeName ( enclosingClass ) ; List < Node > classNodes = ScopedNodeLocator . Instance ( ) . findNodesInScope ( root , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( node instanceof ClassNode ) { return getClassNodeName ( ( ClassNode ) node ) . equals ( className ) ; } return false ; } } ) ; BlockNode blockNode = new BlockNode ( new IDESourcePosition ( ) ) ; for ( Node classNode : classNodes ) { blockNode . add ( classNode ) ; } searchSpace = blockNode ; } final Node finalSearchSpace = searchSpace ; final String origName = getInstVarRefName ( orig , searchSpace ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( isInstanceVarRef ( node ) ) { String name = getInstVarRefName ( node , finalSearchSpace ) ; return ( name != null && name . equals ( origName ) ) ; } return false ; } } ) ; for ( Node searchResult : searchResults ) { references . add ( getPositionOfName ( searchResult , searchSpace ) ) ; } } private void pushGlobalVarRefs ( Node root , Node orig , List < ISourcePosition > references ) { final Node searchSpace = root ; final String origName = getGlobalVarRefName ( orig ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( searchSpace , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return isGlobalVarRef ( node ) && getGlobalVarRefName ( node ) . equals ( origName ) ; } } ) ; for ( Node searchResult : searchResults ) { references . add ( getPositionOfName ( searchResult , searchSpace ) ) ; } } private void pushConstRefs ( Node root , Node orig , List < ISourcePosition > references ) { if ( ! ( orig instanceof ConstNode ) ) { return ; } final String matchName = ( ( ConstNode ) orig ) . getName ( ) ; List < Node > searchResults = ScopedNodeLocator . Instance ( ) . findNodesInScope ( root , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( node instanceof ConstNode ) { return ( ( ConstNode ) node ) . getName ( ) . equals ( matchName ) ; } return false ; } } ) ; for ( Node searchResult : searchResults ) { references . add ( getPositionOfName ( searchResult , root ) ) ; } } } package org . rubypeople . rdt . internal . ti ; public class ReferenceTypeGuess implements ITypeGuess { private Variable other ; public ReferenceTypeGuess ( Variable other ) { this . other = other ; } public int getConfidence ( ) { return ; } public String getType ( ) { return null ; } } package org . rubypeople . rdt . internal . ti ; import java . util . Collection ; public interface ITypeInferrer { public Collection < ITypeGuess > infer ( String source , int offset ) ; } package org . rubypeople . rdt . internal . ti . util ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . StrNode ; import org . jruby . ast . SymbolNode ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; public class AttributeLocator extends InOrderVisitor { private Set < String > attributes ; public Collection < String > findInstanceAttributesInScope ( Node rootNode ) { if ( rootNode == null ) return Collections . emptyList ( ) ; attributes = new HashSet < String > ( ) ; rootNode . accept ( this ) ; Collection < String > result = Collections . unmodifiableSet ( attributes ) ; attributes = null ; return result ; } @ Override public Object visitFCallNode ( FCallNode fCallNode ) { String attrPrefix = null ; if ( isInstanceAttributeDeclaration ( fCallNode . getName ( ) ) ) { attrPrefix = "" ; } else if ( isClassAttributeDeclaration ( fCallNode . getName ( ) ) ) { attrPrefix = "" ; } if ( attrPrefix == null ) return super . visitFCallNode ( fCallNode ) ; Node argsNode = fCallNode . getArgsNode ( ) ; if ( ! ( argsNode instanceof ArrayNode ) ) return super . visitFCallNode ( fCallNode ) ; ArrayNode arrayNode = ( ArrayNode ) argsNode ; for ( Node argNode : arrayNode . childNodes ( ) ) { if ( argNode instanceof SymbolNode ) { attributes . add ( attrPrefix + ( ( SymbolNode ) argNode ) . getName ( ) ) ; } else if ( argNode instanceof StrNode ) { attributes . add ( attrPrefix + ( ( StrNode ) argNode ) . getValue ( ) ) ; } } return super . visitFCallNode ( fCallNode ) ; } private boolean isInstanceAttributeDeclaration ( String methodName ) { return ( methodName . equals ( "" ) || methodName . equals ( "" ) || methodName . equals ( "" ) || methodName . equals ( "" ) ) ; } private boolean isClassAttributeDeclaration ( String methodName ) { return ( methodName . equals ( "" ) || methodName . equals ( "" ) || methodName . equals ( "" ) || methodName . equals ( "" ) ) ; } } package org . rubypeople . rdt . internal . ti . util ; import java . util . Iterator ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; public class OffsetNodeLocator extends NodeLocator { private OffsetNodeLocator ( ) { } private static OffsetNodeLocator staticInstance = new OffsetNodeLocator ( ) ; public static OffsetNodeLocator Instance ( ) { return staticInstance ; } private Node locatedNode ; private int offset ; public Node getNodeAtOffset ( Node rootNode , int offset ) { if ( rootNode == null ) { return null ; } locatedNode = null ; this . offset = offset ; rootNode . accept ( this ) ; locatedNode = refine ( locatedNode ) ; return locatedNode ; } private Node refine ( Node node ) { if ( node instanceof ArgsNode ) { ArgsNode argsNode = ( ArgsNode ) node ; if ( argsNode . getRequiredArgsCount ( ) > ) { for ( Iterator < Node > iter = argsNode . getPre ( ) . childNodes ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { ArgumentNode argNode = ( ArgumentNode ) iter . next ( ) ; if ( nodeDoesSpanOffset ( argNode , offset ) ) { return argNode ; } } } } return node ; } public Object handleNode ( Node iVisited ) { if ( ! ( iVisited instanceof NewlineNode ) && nodeDoesSpanOffset ( iVisited , offset ) ) { if ( locatedNode == null || ( nodeSpanLength ( iVisited ) <= nodeSpanLength ( locatedNode ) ) ) { if ( ! ( ( locatedNode instanceof Colon2Node ) && ( iVisited instanceof ConstNode ) ) ) { locatedNode = iVisited ; } if ( iVisited instanceof ArgsNode ) { ArgsNode args = ( ArgsNode ) iVisited ; handleNode ( args . getRestArgNode ( ) ) ; } } } return super . handleNode ( iVisited ) ; } } package org . rubypeople . rdt . internal . ti . util ; import org . jruby . ast . Node ; public class ClosestSpanningNodeLocator extends NodeLocator { private ClosestSpanningNodeLocator ( ) { } private static ClosestSpanningNodeLocator staticInstance = new ClosestSpanningNodeLocator ( ) ; public static ClosestSpanningNodeLocator Instance ( ) { return staticInstance ; } private int offset ; private INodeAcceptor acceptor ; private Node locatedNode ; public Node findClosestSpanner ( Node rootNode , int offset , INodeAcceptor acceptor ) { if ( rootNode == null ) return null ; locatedNode = null ; this . offset = offset ; this . acceptor = acceptor ; rootNode . accept ( this ) ; return locatedNode ; } public Object handleNode ( Node iVisited ) { boolean nodeSpansOffset = nodeSpansOffset ( iVisited , offset ) ; boolean nodeSpansMoreCloselyThanCurrent = ( locatedNode == null ) || ( calculateSpanLength ( iVisited ) <= calculateSpanLength ( locatedNode ) ) ; if ( nodeSpansOffset && nodeSpansMoreCloselyThanCurrent && acceptor . doesAccept ( iVisited ) ) { locatedNode = iVisited ; } return super . handleNode ( iVisited ) ; } public static boolean nodeSpansOffset ( Node node , int offset ) { return ( node . getPosition ( ) . getStartOffset ( ) <= offset ) && ( node . getPosition ( ) . getEndOffset ( ) > offset ) ; } private int calculateSpanLength ( Node node ) { if ( node == null ) { return ; } if ( node . getPosition ( ) == null ) { return ; } return node . getPosition ( ) . getEndOffset ( ) - node . getPosition ( ) . getStartOffset ( ) ; } } package org . rubypeople . rdt . internal . ti . util ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; public class ScopedNodeLocator extends NodeLocator { private ScopedNodeLocator ( ) { } private static ScopedNodeLocator staticInstance = new ScopedNodeLocator ( ) ; public static ScopedNodeLocator Instance ( ) { return staticInstance ; } private INodeAcceptor acceptor ; private List < Node > locatedNodes ; public List < Node > findNodesInScope ( Node rootNode , INodeAcceptor acceptor ) { if ( rootNode == null || acceptor == null ) return null ; locatedNodes = new LinkedList < Node > ( ) ; this . acceptor = acceptor ; rootNode . accept ( this ) ; return locatedNodes ; } public Object handleNode ( Node iVisited ) { if ( acceptor . doesAccept ( iVisited ) ) { locatedNodes . add ( iVisited ) ; } return super . handleNode ( iVisited ) ; } public Object visitArgsNode ( ArgsNode iVisited ) { if ( iVisited . getRequiredArgsCount ( ) > ) { for ( Iterator < Node > iter = iVisited . getPre ( ) . childNodes ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { ArgumentNode argNode = ( ArgumentNode ) iter . next ( ) ; if ( acceptor . doesAccept ( argNode ) ) { locatedNodes . add ( argNode ) ; } } } ArgumentNode argNode = iVisited . getRestArgNode ( ) ; if ( argNode != null ) { if ( acceptor . doesAccept ( argNode ) ) { ISourcePosition pos = argNode . getPosition ( ) ; pos . adjustStartOffset ( ) ; argNode . setPosition ( pos ) ; locatedNodes . add ( argNode ) ; } } return super . visitArgsNode ( iVisited ) ; } } package org . rubypeople . rdt . internal . ti . util ; import org . jruby . ast . Node ; public interface INodeAcceptor { public boolean doesAccept ( Node node ) ; } package org . rubypeople . rdt . internal . ti . util ; import java . util . Collection ; import java . util . LinkedList ; import java . util . List ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . internal . ti . ITypeGuess ; import org . rubypeople . rdt . internal . ti . ITypeInferrer ; import org . rubypeople . rdt . internal . ti . TypeInferenceHelper ; public class MethodInvocationLocator extends NodeLocator { private MethodInvocationLocator ( ) { } private static MethodInvocationLocator staticInstance = new MethodInvocationLocator ( ) ; public static MethodInvocationLocator Instance ( ) { return staticInstance ; } private TypeInferenceHelper helper = TypeInferenceHelper . Instance ( ) ; private String typeName ; private String methodName ; private List < Node > locatedNodes ; private ITypeInferrer inferrer ; private String source ; public List < Node > findMethodInvocations ( Node rootNode , String typeName , String methodName , ITypeInferrer inferrer ) { if ( rootNode == null ) { return null ; } this . locatedNodes = new LinkedList < Node > ( ) ; this . typeNameStack = new LinkedList < String > ( ) ; this . typeName = typeName ; this . methodName = methodName ; this . inferrer = inferrer ; typeNameStack . add ( "" ) ; rootNode . accept ( this ) ; return locatedNodes ; } public Object handleNode ( Node iVisited ) { if ( iVisited instanceof FCallNode ) { if ( ( ( FCallNode ) iVisited ) . getName ( ) . equals ( methodName ) ) { if ( peekType ( ) . equals ( typeName ) ) { locatedNodes . add ( iVisited ) ; } } } if ( iVisited instanceof CallNode ) { if ( helper . getCallNodeMethodName ( iVisited ) . equals ( methodName ) ) { Node receiverNode = ( ( CallNode ) iVisited ) . getReceiverNode ( ) ; Collection < ITypeGuess > receiverTypeInferences = inferrer . infer ( source , receiverNode . getPosition ( ) . getStartOffset ( ) ) ; for ( ITypeGuess inference : receiverTypeInferences ) { if ( inference . getType ( ) . equals ( typeName ) ) { locatedNodes . add ( iVisited ) ; break ; } } } } return super . handleNode ( iVisited ) ; } public Object visitClassNode ( ClassNode iVisited ) { pushType ( helper . getTypeNodeName ( iVisited ) ) ; super . visitClassNode ( iVisited ) ; popType ( ) ; return null ; } public Object visitModuleNode ( ModuleNode iVisited ) { pushType ( helper . getTypeNodeName ( iVisited ) ) ; super . visitModuleNode ( iVisited ) ; popType ( ) ; return null ; } } package org . rubypeople . rdt . internal . ti . util ; import org . jruby . ast . Node ; public class FirstPrecursorNodeLocator extends NodeLocator { private FirstPrecursorNodeLocator ( ) { } private static FirstPrecursorNodeLocator staticInstance = new FirstPrecursorNodeLocator ( ) ; public static FirstPrecursorNodeLocator Instance ( ) { return staticInstance ; } private int offset ; private INodeAcceptor acceptor ; private Node locatedNode ; public Node findFirstPrecursor ( Node rootNode , int offset , INodeAcceptor acceptor ) { locatedNode = null ; this . offset = offset ; this . acceptor = acceptor ; rootNode . accept ( this ) ; return locatedNode ; } public Object handleNode ( Node iVisited ) { if ( ( iVisited . getPosition ( ) . getEndOffset ( ) <= offset ) || ( iVisited . getPosition ( ) . getStartOffset ( ) <= offset ) ) { if ( acceptor . doesAccept ( iVisited ) ) { locatedNode = iVisited ; } } return super . handleNode ( iVisited ) ; } } package org . rubypeople . rdt . internal . ti . util ; import java . util . LinkedList ; import java . util . List ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . internal . ti . TypeInferenceHelper ; public class MethodDefinitionLocator extends NodeLocator { private MethodDefinitionLocator ( ) { } private static MethodDefinitionLocator staticInstance = new MethodDefinitionLocator ( ) ; public static MethodDefinitionLocator Instance ( ) { return staticInstance ; } private TypeInferenceHelper helper = TypeInferenceHelper . Instance ( ) ; private String typeName ; private String methodName ; private List < Node > locatedNodes ; public List < Node > findMethodDefinitions ( Node rootNode , String typeName , String methodName ) { if ( rootNode == null ) { return null ; } this . locatedNodes = new LinkedList < Node > ( ) ; this . typeNameStack = new LinkedList < String > ( ) ; this . typeName = typeName ; this . methodName = methodName ; typeNameStack . add ( "" ) ; rootNode . accept ( this ) ; return locatedNodes ; } public Object handleNode ( Node iVisited ) { if ( ( iVisited instanceof DefnNode ) || ( iVisited instanceof DefsNode ) ) { if ( peekType ( ) . equals ( typeName ) ) { String methodName = helper . getMethodDefinitionNodeName ( iVisited ) ; if ( methodName . equals ( this . methodName ) ) { locatedNodes . add ( iVisited ) ; } } } return super . handleNode ( iVisited ) ; } public Object visitClassNode ( ClassNode iVisited ) { pushType ( helper . getTypeNodeName ( iVisited ) ) ; super . visitClassNode ( iVisited ) ; popType ( ) ; return null ; } public Object visitModuleNode ( ModuleNode iVisited ) { pushType ( helper . getTypeNodeName ( iVisited ) ) ; super . visitModuleNode ( iVisited ) ; popType ( ) ; return null ; } } package org . rubypeople . rdt . internal . ti . util ; import java . util . List ; import org . jruby . ast . Node ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; public class NodeLocator extends InOrderVisitor { protected List < String > typeNameStack ; protected boolean nodeDoesSpanOffset ( Node node , int offset ) { if ( node == null ) return false ; if ( node . getPosition ( ) == null ) return false ; return ( node . getPosition ( ) . getStartOffset ( ) <= offset ) && ( node . getPosition ( ) . getEndOffset ( ) > offset ) ; } protected int nodeSpanLength ( Node node ) { if ( node == null || node . getPosition ( ) == null ) { return ; } else { return node . getPosition ( ) . getEndOffset ( ) - node . getPosition ( ) . getStartOffset ( ) ; } } protected void pushType ( String typeName ) { typeNameStack . add ( , typeName ) ; } protected void popType ( ) { if ( typeNameStack . isEmpty ( ) ) return ; typeNameStack . remove ( ) ; } protected String peekType ( ) { if ( typeNameStack . isEmpty ( ) ) return null ; return typeNameStack . get ( ) ; } } package org . rubypeople . rdt . internal . ti ; import java . util . Collections ; import java . util . LinkedList ; import java . util . List ; import org . jruby . ast . Node ; public class Scope extends LinkedList < Scope > { private static final long serialVersionUID = - ; private List < Variable > variables ; private List < Scope > childScopes ; private Scope parentScope ; private Node node ; public Scope ( Node node , Scope parentScope ) { super ( ) ; this . node = node ; this . parentScope = parentScope ; this . childScopes = new LinkedList < Scope > ( ) ; this . variables = new LinkedList < Variable > ( ) ; } public List < Variable > getVariables ( ) { return variables ; } public void setVariables ( List < Variable > variables ) { this . variables = variables ; } public Node getNode ( ) { return node ; } public void setNode ( Node node ) { this . node = node ; } public List < Scope > getChildScopes ( ) { return Collections . unmodifiableList ( childScopes ) ; } public void addChildScope ( Scope childScope ) { childScopes . add ( childScope ) ; } public Scope getParentScope ( ) { return parentScope ; } public Variable getLocalVariableByCount ( int count ) { for ( Variable var : variables ) { if ( var . getCount ( ) == count ) return var ; } return null ; } } package org . rubypeople . rdt . internal . ti ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . YieldNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . search . CollectingSearchRequestor ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . ti . data . LiteralNodeTypeNames ; import org . rubypeople . rdt . internal . ti . data . TypicalMethodReturnNames ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . FirstPrecursorNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; import org . rubypeople . rdt . internal . ti . util . ScopedNodeLocator ; public class DefaultTypeInferrer implements ITypeInferrer { private static final String CONSTRUCTOR_INVOKE_NAME = "" ; private RootNode rootNode ; private Set < Node > dontVisitNodes ; private HashSet < Node > fVisitedNodes ; private Map < String , RootNode > parsed ; public Collection < ITypeGuess > infer ( String source , int offset ) { dontVisitNodes = new HashSet < Node > ( ) ; fVisitedNodes = new HashSet < Node > ( ) ; parsed = new HashMap < String , RootNode > ( ) ; try { rootNode = parse ( source ) ; Node node = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( rootNode . getBodyNode ( ) , offset ) ; if ( node == null ) { return Collections . emptyList ( ) ; } return infer ( node ) ; } catch ( SyntaxException e ) { return Collections . emptyList ( ) ; } finally { parsed . clear ( ) ; dontVisitNodes . clear ( ) ; fVisitedNodes . clear ( ) ; } } private Set < ITypeGuess > infer ( Node node ) { if ( fVisitedNodes . contains ( node ) ) return new HashSet < ITypeGuess > ( ) ; fVisitedNodes . add ( node ) ; Set < ITypeGuess > guesses = new HashSet < ITypeGuess > ( ) ; tryLiteralNode ( node , guesses ) ; tryAsgnNode ( node , guesses ) ; tryDVarNode ( node , guesses ) ; tryLocalVarNode ( node , guesses ) ; tryInstVarNode ( node , guesses ) ; tryGlobalVarNode ( node , guesses ) ; tryMethodNode ( node , guesses ) ; tryIterNode ( node , guesses ) ; tryWellKnownMethodCalls ( node , guesses ) ; if ( node instanceof Colon2Node ) { Colon2Node colonNode = ( Colon2Node ) node ; String name = ASTUtil . getFullyQualifiedName ( colonNode ) ; guesses . add ( new BasicTypeGuess ( name , ) ) ; } if ( node instanceof ConstNode ) { ConstNode constNode = ( ConstNode ) node ; String name = constNode . getName ( ) ; if ( ! name . equals ( "" ) ) guesses . add ( new BasicTypeGuess ( constNode . getName ( ) , ) ) ; } if ( guesses . isEmpty ( ) ) { if ( node instanceof CallNode ) { CallNode call = ( CallNode ) node ; return infer ( call . getReceiverNode ( ) ) ; } } return guesses ; } private void tryDVarNode ( Node node , Set < ITypeGuess > guesses ) { if ( ! ( node instanceof DVarNode ) ) return ; Node iterNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( rootNode , node . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof IterNode ) ; } } ) ; Node methodCall = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( rootNode , iterNode . getPosition ( ) . getStartOffset ( ) - ) ; try { SearchEngine engine = new SearchEngine ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . METHOD , ASTUtil . getNameReflectively ( methodCall ) , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; SearchParticipant [ ] participants = new SearchParticipant [ ] { SearchEngine . getDefaultSearchParticipant ( ) } ; IRubySearchScope scope = SearchEngine . createWorkspaceScope ( ) ; CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; engine . search ( pattern , participants , scope , requestor , new NullProgressMonitor ( ) ) ; List < SearchMatch > matches = requestor . getResults ( ) ; for ( SearchMatch match : matches ) { IMethod method = ( IMethod ) match . getElement ( ) ; String src = method . getRubyScript ( ) . getSource ( ) ; Node otherRoot = parse ( src ) ; Node methodNodeThing = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( otherRoot , method . getSourceRange ( ) . getOffset ( ) ) ; List < Node > yields = ScopedNodeLocator . Instance ( ) . findNodesInScope ( methodNodeThing , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof YieldNode ; } } ) ; if ( yields == null ) continue ; for ( Node yield : yields ) { if ( yield instanceof YieldNode ) { YieldNode yieldNode = ( YieldNode ) yield ; Node argsNode = yieldNode . getArgsNode ( ) ; guesses . addAll ( infer ( src , argsNode . getPosition ( ) . getStartOffset ( ) ) ) ; } } } } catch ( CoreException e ) { RubyCore . log ( e ) ; } } private RootNode parse ( String src ) { if ( parsed . containsKey ( src ) ) { return parsed . get ( src ) ; } RubyParser parser = new RubyParser ( ) ; RootNode root = ( RootNode ) parser . parse ( src ) . getAST ( ) ; parsed . put ( src , root ) ; return root ; } private void tryIterNode ( Node node , Set < ITypeGuess > guesses ) { if ( ! ( node instanceof IterNode ) ) return ; tryEnclosingType ( node , guesses ) ; } private void tryEnclosingType ( Node node , Set < ITypeGuess > guesses ) { Node typeNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( rootNode , node . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ClassNode || node instanceof ModuleNode ) ; } } ) ; if ( typeNode == null ) { guesses . add ( new BasicTypeGuess ( "" , ) ) ; } else { guesses . add ( new BasicTypeGuess ( ASTUtil . getFullyQualifiedTypeName ( rootNode , typeNode ) , ) ) ; } } private void tryMethodNode ( Node node , Set < ITypeGuess > guesses ) { if ( ! ( node instanceof MethodDefNode ) ) return ; tryEnclosingType ( node , guesses ) ; } private void tryLiteralNode ( Node node , Collection < ITypeGuess > guesses ) { String concreteGuess = LiteralNodeTypeNames . get ( node . getClass ( ) . getSimpleName ( ) ) ; if ( concreteGuess != null ) { guesses . add ( new BasicTypeGuess ( concreteGuess , ) ) ; } } private void tryAsgnNode ( Node node , Collection < ITypeGuess > guesses ) { Node valueNode = null ; if ( node instanceof LocalAsgnNode ) { valueNode = ( ( LocalAsgnNode ) node ) . getValueNode ( ) ; } if ( node instanceof InstAsgnNode ) { valueNode = ( ( InstAsgnNode ) node ) . getValueNode ( ) ; } if ( node instanceof GlobalAsgnNode ) { valueNode = ( ( GlobalAsgnNode ) node ) . getValueNode ( ) ; } if ( valueNode != null ) { guesses . addAll ( infer ( valueNode ) ) ; } } private void tryInstVarNode ( Node node , Collection < ITypeGuess > guesses ) { if ( ! ( node instanceof InstVarNode ) ) return ; final InstVarNode instVarNode = ( InstVarNode ) node ; final Node assignmentNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( rootNode , instVarNode . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof InstAsgnNode ; } } ) ; if ( assignmentNode != null ) dontVisitNodes . add ( assignmentNode ) ; List < Node > assignments = new ArrayList < Node > ( ) ; assignments . addAll ( ScopedNodeLocator . Instance ( ) . findNodesInScope ( rootNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof InstAsgnNode ) && ( ( ( InstAsgnNode ) node ) . getName ( ) . equals ( instVarNode . getName ( ) ) ) && ! dontVisitNodes . contains ( node ) ; } } ) ) ; for ( Node assignNode : assignments ) { tryAsgnNode ( assignNode , guesses ) ; } } private void tryGlobalVarNode ( Node node , Collection < ITypeGuess > guesses ) { if ( ! ( node instanceof GlobalVarNode ) ) return ; final GlobalVarNode globalVarNode = ( GlobalVarNode ) node ; int nodeStart = node . getPosition ( ) . getStartOffset ( ) ; Node initialAssignmentNode = FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( rootNode , nodeStart , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { String name = null ; if ( node instanceof LocalAsgnNode ) name = ( ( LocalAsgnNode ) node ) . getName ( ) ; if ( node instanceof InstAsgnNode ) name = ( ( InstAsgnNode ) node ) . getName ( ) ; if ( node instanceof GlobalAsgnNode ) name = ( ( GlobalAsgnNode ) node ) . getName ( ) ; return ( name != null && name . equals ( globalVarNode . getName ( ) ) ) ; } } ) ; if ( initialAssignmentNode != null ) { tryAsgnNode ( initialAssignmentNode , guesses ) ; } } private void tryLocalVarNode ( Node node , Collection < ITypeGuess > guesses ) { if ( node instanceof VCallNode ) { return ; } if ( ! ( node instanceof LocalVarNode ) ) return ; LocalVarNode localVarNode = ( LocalVarNode ) node ; int nodeStart = node . getPosition ( ) . getStartOffset ( ) ; final String localVarName = TypeInferenceHelper . Instance ( ) . getVarName ( localVarNode ) ; Node initialAssignmentNode = FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( rootNode , nodeStart , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { String name = null ; if ( node instanceof LocalAsgnNode ) name = ( ( LocalAsgnNode ) node ) . getName ( ) ; if ( node instanceof InstAsgnNode ) name = ( ( InstAsgnNode ) node ) . getName ( ) ; if ( node instanceof GlobalAsgnNode ) name = ( ( GlobalAsgnNode ) node ) . getName ( ) ; return ( name != null && name . equals ( localVarName ) ) ; } } ) ; if ( initialAssignmentNode != null ) { tryAsgnNode ( initialAssignmentNode , guesses ) ; } ArgsNode argsNode = ( ArgsNode ) FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( rootNode , nodeStart , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( ( node instanceof ArgsNode ) && ( doesArgsNodeContainsVariable ( ( ArgsNode ) node , localVarName ) ) ) ; } } ) ; if ( argsNode != null ) { Node defNode = FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( rootNode , nodeStart , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { ArgsNode argsNode = null ; if ( node instanceof DefnNode ) argsNode = ( ( DefnNode ) node ) . getArgsNode ( ) ; if ( node instanceof DefsNode ) argsNode = ( ( DefsNode ) node ) . getArgsNode ( ) ; return ( ( argsNode != null ) && ( doesArgsNodeContainsVariable ( argsNode , localVarName ) ) ) ; } } ) ; if ( defNode != null ) { String methodName = null ; if ( defNode instanceof DefnNode ) methodName = ( ( DefnNode ) defNode ) . getName ( ) ; if ( defNode instanceof DefsNode ) methodName = ( ( DefsNode ) defNode ) . getName ( ) ; } } } private void tryWellKnownMethodCalls ( Node node , Collection < ITypeGuess > guesses ) { if ( ! ( node instanceof CallNode ) ) return ; CallNode callNode = ( CallNode ) node ; String method = callNode . getName ( ) ; if ( method . equals ( CONSTRUCTOR_INVOKE_NAME ) ) { String name = null ; if ( callNode . getReceiverNode ( ) instanceof ConstNode ) { name = ( ( ConstNode ) callNode . getReceiverNode ( ) ) . getName ( ) ; } else if ( callNode . getReceiverNode ( ) instanceof Colon2Node ) { name = ASTUtil . getFullyQualifiedName ( ( Colon2Node ) callNode . getReceiverNode ( ) ) ; } if ( name != null ) guesses . add ( new BasicTypeGuess ( name , ) ) ; } else { guesses . addAll ( TypicalMethodReturnNames . get ( method ) ) ; } } private boolean doesArgsNodeContainsVariable ( ArgsNode argsNode , String argName ) { if ( argsNode == null ) return false ; if ( argName == null ) return false ; return getArgumentIndex ( argsNode , argName ) >= ; } private int getArgumentIndex ( ArgsNode argsNode , String argName ) { int argNumber = ; ListNode args = argsNode . getArgs ( ) ; if ( args == null ) return - ; for ( Iterator iter = args . childNodes ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { ArgumentNode arg = ( ArgumentNode ) iter . next ( ) ; if ( arg . getName ( ) . equals ( argName ) ) { break ; } argNumber ++ ; } if ( argNumber == argsNode . getRequiredArgsCount ( ) ) { return - ; } return argNumber ; } } package org . rubypeople . rdt . internal . ti ; import org . jruby . ast . BlockNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . parser . StaticScope ; public class ScopingVisitor { protected Scope globalScope ; protected Scope currentScope ; public ScopingVisitor ( Node root ) { globalScope = new Scope ( root , null ) ; currentScope = globalScope ; if ( isScopingNode ( root ) ) { processNode ( root ) ; } else if ( root instanceof BlockNode ) { BlockNode blockRoot = ( BlockNode ) root ; for ( Object node : blockRoot . childNodes ( ) ) { if ( node instanceof NewlineNode ) { NewlineNode newlineNode = ( NewlineNode ) node ; processNode ( newlineNode . getNextNode ( ) ) ; } } } } private void processNode ( Node node ) { if ( node == null ) { return ; } if ( isScopingNode ( node ) ) { currentScope = new Scope ( node , currentScope ) ; visitScopingNode ( node ) ; for ( Object child : node . childNodes ( ) ) { processNode ( ( Node ) child ) ; } currentScope = currentScope . getParentScope ( ) ; } else { visitNode ( node ) ; } } protected void visitScopingNode ( Node node ) { StaticScope bodyNode = null ; if ( node instanceof ModuleNode ) bodyNode = ( ( ModuleNode ) node ) . getScope ( ) ; if ( node instanceof ClassNode ) bodyNode = ( ( ClassNode ) node ) . getScope ( ) ; if ( node instanceof DefnNode ) bodyNode = ( ( DefnNode ) node ) . getScope ( ) ; if ( node instanceof DefsNode ) bodyNode = ( ( DefsNode ) node ) . getScope ( ) ; if ( node instanceof IterNode ) bodyNode = ( ( IterNode ) node ) . getScope ( ) ; Variable . insertLocalsFromScopeNode ( bodyNode , currentScope ) ; } protected void visitNode ( Node node ) { System . out . print ( "" ) ; if ( node != null ) { String pos = "" ; String cls = "" ; if ( node . getPosition ( ) != null ) pos = Integer . toString ( node . getPosition ( ) . getStartLine ( ) ) ; if ( node . getClass ( ) != null ) cls = node . getClass ( ) . getName ( ) ; System . out . print ( "" + node . getClass ( ) . getSimpleName ( ) + "" + pos + "" + cls ) ; System . out . println ( "" + node . getPosition ( ) . getStartOffset ( ) + "" + node . getPosition ( ) . getEndOffset ( ) + "" ) ; } if ( node instanceof CallNode ) visitCallNode ( ( CallNode ) node ) ; if ( node instanceof LocalAsgnNode ) visitLocalAsgnNode ( ( LocalAsgnNode ) node ) ; } protected void visitCallNode ( CallNode node ) { } protected void visitLocalAsgnNode ( LocalAsgnNode node ) { } private boolean isScopingNode ( Node node ) { return ( node instanceof ModuleNode ) || ( node instanceof ClassNode ) || ( node instanceof DefnNode ) || ( node instanceof DefsNode ) || ( node instanceof IterNode ) ; } } package org . rubypeople . rdt . internal . ti . data ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import org . rubypeople . rdt . internal . ti . BasicTypeGuess ; import org . rubypeople . rdt . internal . ti . ITypeGuess ; public abstract class TypicalMethodReturnNames { public static Collection < ITypeGuess > get ( String method ) { if ( method . endsWith ( "" ) ) { return createSet ( "" , "" ) ; } Collection < ITypeGuess > result = TYPICAL_METHOD_RETURN_TYPE_NAMES . get ( method ) ; if ( result == null ) return Collections . emptySet ( ) ; return result ; } private static final Map < String , Collection < ITypeGuess > > TYPICAL_METHOD_RETURN_TYPE_NAMES = new HashMap < String , Collection < ITypeGuess > > ( ) ; static { TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" , "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" , "" , "" , "" , "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" , "" , "" , "" , "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; TYPICAL_METHOD_RETURN_TYPE_NAMES . put ( "" , createSet ( "" ) ) ; } private static Set < ITypeGuess > createSet ( String ... strings ) { int weight = / strings . length ; Set < ITypeGuess > set = new HashSet < ITypeGuess > ( ) ; for ( String string : strings ) { set . add ( new BasicTypeGuess ( string , weight ) ) ; } return set ; } } package org . rubypeople . rdt . internal . ti . data ; import java . util . HashMap ; import java . util . Map ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . BignumNode ; import org . jruby . ast . DRegexpNode ; import org . jruby . ast . DStrNode ; import org . jruby . ast . DSymbolNode ; import org . jruby . ast . DXStrNode ; import org . jruby . ast . FalseNode ; import org . jruby . ast . FixnumNode ; import org . jruby . ast . FloatNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . NilNode ; import org . jruby . ast . RegexpNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . TrueNode ; import org . jruby . ast . XStrNode ; import org . jruby . ast . ZArrayNode ; public abstract class LiteralNodeTypeNames { public static String get ( String nodeType ) { return CONST_NODE_TYPE_NAMES . get ( nodeType ) ; } private static final Map < String , String > CONST_NODE_TYPE_NAMES = new HashMap < String , String > ( ) ; static { CONST_NODE_TYPE_NAMES . put ( ArrayNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( BignumNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( DRegexpNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( DStrNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( DSymbolNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( DXStrNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( FalseNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( FixnumNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( FloatNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( HashNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( NilNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( NilImplicitNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( RegexpNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( StrNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( SymbolNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( TrueNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( XStrNode . class . getSimpleName ( ) , "" ) ; CONST_NODE_TYPE_NAMES . put ( ZArrayNode . class . getSimpleName ( ) , "" ) ; } } package org . rubypeople . rdt . internal . ti ; import java . util . Iterator ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . FCallNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . VCallNode ; import org . jruby . ast . types . INameNode ; public class TypeInferenceHelper { private TypeInferenceHelper ( ) { } private static TypeInferenceHelper staticInstance = new TypeInferenceHelper ( ) ; public static TypeInferenceHelper Instance ( ) { return staticInstance ; } public String getVarName ( Node node ) { if ( node instanceof INameNode ) { return ( ( INameNode ) node ) . getName ( ) ; } return null ; } public int getArgIndex ( ListNode listNode , String argName ) { int argNumber = ; for ( Iterator iter = listNode . childNodes ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { if ( ( ( ArgumentNode ) iter . next ( ) ) . getName ( ) . equals ( argName ) ) { return argNumber ; } argNumber ++ ; } return - ; } public String getTypeNodeName ( Node node ) { if ( node instanceof ClassNode ) { return ( ( Colon2Node ) ( ( ClassNode ) node ) . getCPath ( ) ) . getName ( ) ; } if ( node instanceof ModuleNode ) { return ( ( Colon2Node ) ( ( ModuleNode ) node ) . getCPath ( ) ) . getName ( ) ; } return null ; } public String getMethodDefinitionNodeName ( Node methodNode ) { if ( methodNode instanceof MethodDefNode ) return ( ( MethodDefNode ) methodNode ) . getName ( ) ; return null ; } public boolean isArgumentInMethod ( String varName , Node enclosingScopeNode ) { ListNode listNode = getArgsListNode ( enclosingScopeNode ) ; if ( listNode == null ) { return false ; } return ( getArgIndex ( listNode , varName ) >= ) ; } public ListNode getArgsListNode ( Node node ) { if ( node instanceof MethodDefNode ) { return ( ( ( MethodDefNode ) node ) . getArgsNode ( ) ) . getArgs ( ) ; } if ( node instanceof CallNode ) { return ( ( ArgsNode ) ( ( ( CallNode ) node ) . getArgsNode ( ) ) ) . getArgs ( ) ; } if ( node instanceof FCallNode ) { return ( ArrayNode ) ( ( ( FCallNode ) node ) . getArgsNode ( ) ) ; } return null ; } public String getCallNodeMethodName ( Node node ) { if ( node instanceof CallNode ) { return ( ( CallNode ) node ) . getName ( ) ; } if ( node instanceof FCallNode ) { return ( ( FCallNode ) node ) . getName ( ) ; } if ( node instanceof VCallNode ) { return ( ( VCallNode ) node ) . getName ( ) ; } return null ; } public Node findNthArgExprInSendExpr ( int n , Node sendExprNode ) { ListNode listNode = getArgsListNode ( sendExprNode ) ; if ( listNode == null ) { return null ; } return listNode . get ( n ) ; } } package org . rubypeople . rdt . internal . ti ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . ti . data . LiteralNodeTypeNames ; import org . rubypeople . rdt . internal . ti . data . TypicalMethodReturnNames ; public class TypeInferenceVisitor extends InOrderVisitor { private Scope globalScope ; private Scope currentScope ; public TypeInferenceVisitor ( Node rootNode ) { globalScope = new Scope ( rootNode , null ) ; currentScope = globalScope ; } public Object visitModuleNode ( ModuleNode iVisited ) { Scope newScope = pushScope ( iVisited ) ; Variable . insertLocalsFromScopeNode ( iVisited . getScope ( ) , newScope ) ; return super . visitModuleNode ( iVisited ) ; } public Object visitClassNode ( ClassNode iVisited ) { Scope newScope = pushScope ( iVisited ) ; Variable . insertLocalsFromScopeNode ( iVisited . getScope ( ) , newScope ) ; return super . visitClassNode ( iVisited ) ; } public Object visitDefnNode ( DefnNode iVisited ) { Scope newScope = pushScope ( iVisited ) ; Variable . insertLocalsFromScopeNode ( iVisited . getScope ( ) , newScope ) ; return super . visitDefnNode ( iVisited ) ; } public Object visitDefsNode ( DefsNode iVisited ) { Scope newScope = pushScope ( iVisited ) ; Variable . insertLocalsFromScopeNode ( iVisited . getScope ( ) , newScope ) ; return super . visitDefsNode ( iVisited ) ; } public Object visitIterNode ( IterNode iVisited ) { pushScope ( iVisited ) ; return super . visitIterNode ( iVisited ) ; } private Scope pushScope ( Node node ) { Scope newScope = new Scope ( node , currentScope ) ; currentScope = newScope ; return newScope ; } private void popScope ( ) { currentScope = currentScope . getParentScope ( ) ; } public Object visitCallNode ( CallNode iVisited ) { Variable var = getVariableByVarNode ( iVisited . getReceiverNode ( ) ) ; if ( var != null ) { } return super . visitCallNode ( iVisited ) ; } private Variable getVariableByVarNode ( Node node ) { if ( node instanceof LocalVarNode ) { LocalVarNode localVarNode = ( LocalVarNode ) node ; return currentScope . getLocalVariableByCount ( localVarNode . getIndex ( ) ) ; } return null ; } public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { Variable var = currentScope . getLocalVariableByCount ( iVisited . getIndex ( ) ) ; if ( var == null ) { if ( currentScope == globalScope ) { var = new Variable ( globalScope , iVisited . getName ( ) , iVisited . getIndex ( ) ) ; currentScope . getVariables ( ) . add ( var ) ; } } System . out . print ( "" + var . getName ( ) + "" ) ; Node valueNode = iVisited . getValueNode ( ) ; String concreteGuess = LiteralNodeTypeNames . get ( valueNode . getClass ( ) . getSimpleName ( ) ) ; if ( concreteGuess != null ) { var . getTypeGuesses ( ) . add ( new BasicTypeGuess ( concreteGuess , ) ) ; } else if ( valueNode instanceof CallNode ) { CallNode callValueNode = ( CallNode ) valueNode ; String method = callValueNode . getName ( ) ; if ( method . equals ( "" ) && callValueNode . getReceiverNode ( ) instanceof ConstNode ) { var . getTypeGuesses ( ) . add ( new BasicTypeGuess ( ( ( ConstNode ) callValueNode . getReceiverNode ( ) ) . getName ( ) , ) ) ; } else { var . getTypeGuesses ( ) . addAll ( TypicalMethodReturnNames . get ( method ) ) ; } } return super . visitLocalAsgnNode ( iVisited ) ; } } package org . rubypeople . rdt . internal . ti ; public interface ITypeGuess { public int getConfidence ( ) ; public String getType ( ) ; } package org . rubypeople . rdt . internal . ti ; public class BasicTypeGuess implements ITypeGuess { private String type ; private int confidence ; public int getConfidence ( ) { return confidence ; } public void setConfidence ( int confidence ) { this . confidence = confidence ; } public String getType ( ) { return type ; } public void setType ( String type ) { this . type = type ; } public BasicTypeGuess ( String type , int confidence ) { this . type = type ; this . confidence = confidence ; } public String toString ( ) { return "" + type + "" + confidence + "" ; } @ Override public int hashCode ( ) { return toString ( ) . hashCode ( ) ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof BasicTypeGuess ) { BasicTypeGuess other = ( BasicTypeGuess ) obj ; return toString ( ) . equals ( other . toString ( ) ) ; } return false ; } } package org . rubypeople . rdt . internal . ti ; import java . util . List ; import org . jruby . lexer . yacc . ISourcePosition ; public interface IReferenceFinder { public List < ISourcePosition > findReferences ( String source , int offset ) ; } package org . rubypeople . rdt . internal . ti ; import java . util . LinkedList ; import java . util . List ; import org . jruby . parser . StaticScope ; public class Variable { private List < ITypeGuess > typeGuesses ; private Scope scope ; private String name ; private int count ; public Variable ( Scope scope , String name , int count ) { super ( ) ; this . count = count ; this . scope = scope ; this . name = name ; this . typeGuesses = new LinkedList < ITypeGuess > ( ) ; } public int getCount ( ) { return count ; } public void setCount ( int count ) { this . count = count ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public Scope getScope ( ) { return scope ; } public void setScope ( Scope scope ) { this . scope = scope ; } public List < ITypeGuess > getTypeGuesses ( ) { return typeGuesses ; } public static void insertLocalsFromScopeNode ( StaticScope node , Scope scope ) { int count = ; for ( Object varName : node . getVariables ( ) ) { scope . getVariables ( ) . add ( new Variable ( scope , ( String ) varName , count ) ) ; count ++ ; } } public String toString ( ) { return "" + getScope ( ) . getNode ( ) . getClass ( ) . getName ( ) + "" + name + "" ; } } package org . rubypeople . rdt . internal . ti ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . concurrent . CopyOnWriteArrayList ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . ReturnNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . VCallNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . ReturnVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . ti . data . LiteralNodeTypeNames ; import org . rubypeople . rdt . internal . ti . data . TypicalMethodReturnNames ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ti . util . MethodDefinitionLocator ; import org . rubypeople . rdt . internal . ti . util . MethodInvocationLocator ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; import org . rubypeople . rdt . internal . ti . util . ScopedNodeLocator ; public class DataFlowTypeInferrer implements ITypeInferrer { private static final boolean VERBOSE = false ; private void sysout ( String string ) { if ( VERBOSE ) { System . out . println ( string ) ; } } private void prettyPrint ( Node node ) { sysout ( "" + "" + node . getClass ( ) . getSimpleName ( ) + "" + "" + node . getPosition ( ) . getStartOffset ( ) + "" + node . getPosition ( ) . getEndOffset ( ) + "" + source . substring ( node . getPosition ( ) . getStartOffset ( ) , node . getPosition ( ) . getEndOffset ( ) ) + "" + "" ) ; } TypeInferenceHelper helper ; private String source ; private Node rootNode ; private List < Node > inferNodeStack ; public List < ITypeGuess > infer ( String source , int offset ) { if ( source == null ) return Collections . emptyList ( ) ; this . rootNode = null ; try { this . rootNode = ( new RubyParser ( ) ) . parse ( source ) . getAST ( ) ; } catch ( SyntaxException se ) { return Collections . emptyList ( ) ; } catch ( Exception e ) { RubyCore . log ( e ) ; return Collections . emptyList ( ) ; } List < ITypeGuess > guesses = new LinkedList < ITypeGuess > ( ) ; this . helper = TypeInferenceHelper . Instance ( ) ; this . source = source ; this . inferNodeStack = new LinkedList < Node > ( ) ; Node node = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( rootNode , offset ) ; if ( node == null ) { return null ; } guesses = inferNodeType ( node ) ; guesses = redistributeGuessConfidences ( guesses ) ; guesses = combineSameGuesses ( guesses ) ; return guesses ; } private List < ITypeGuess > combineSameGuesses ( List < ITypeGuess > guesses ) { Map < String , Integer > combined = new HashMap < String , Integer > ( ) ; for ( ITypeGuess typeGuess : guesses ) { Integer percent = combined . get ( typeGuess . getType ( ) ) ; if ( percent == null ) { combined . put ( typeGuess . getType ( ) , typeGuess . getConfidence ( ) ) ; } else { combined . put ( typeGuess . getType ( ) , percent + typeGuess . getConfidence ( ) ) ; } } List < ITypeGuess > combinedGuesses = new ArrayList < ITypeGuess > ( combined . size ( ) ) ; for ( String type : combined . keySet ( ) ) { combinedGuesses . add ( new BasicTypeGuess ( type , combined . get ( type ) ) ) ; } return combinedGuesses ; } private List < ITypeGuess > redistributeGuessConfidences ( List < ITypeGuess > guesses ) { int sum = ; for ( ITypeGuess guess : guesses ) { if ( guess == null ) continue ; sum += guess . getConfidence ( ) ; } List < ITypeGuess > newGuesses = new ArrayList < ITypeGuess > ( guesses . size ( ) ) ; for ( ITypeGuess guess : guesses ) { if ( guess == null ) continue ; ITypeGuess newGuess = new BasicTypeGuess ( guess . getType ( ) , ( int ) ( ( ( double ) guess . getConfidence ( ) ) / ( ( double ) sum ) * ) ) ; newGuesses . add ( newGuess ) ; } return newGuesses ; } private List < ITypeGuess > inferNodeType ( Node node ) { if ( node == null ) { return Collections . emptyList ( ) ; } sysout ( "" + node . getClass ( ) . getSimpleName ( ) ) ; List < ITypeGuess > guesses = new ArrayList < ITypeGuess > ( ) ; if ( inferNodeStack . indexOf ( node ) != - ) { sysout ( "" ) ; prettyPrint ( node ) ; return guesses ; } inferNodeStack . add ( , node ) ; if ( isSelfReferenceNode ( node ) ) { ITypeGuess guess = getSelfReferenceNodeType ( node ) ; if ( guess != null ) guesses . add ( guess ) ; } if ( isAssignmentNode ( node ) ) { guesses . addAll ( inferNodeType ( getAssignmentNodeValueNode ( node ) ) ) ; } if ( isTypeDefinitionNode ( node ) ) { ITypeGuess guess = getTypeDefinitionNodeType ( node ) ; if ( guess != null ) guesses . add ( guess ) ; } if ( isConstantNode ( node ) ) { guesses . add ( getConstantNodeType ( node ) ) ; } if ( node instanceof LocalVarNode ) { guesses . addAll ( getLocalVarReferenceNodeTypes ( ( LocalVarNode ) node ) ) ; } if ( node instanceof DVarNode ) { guesses . addAll ( getDVarReferenceNodeTypes ( ( DVarNode ) node ) ) ; } if ( node instanceof InstVarNode ) { guesses . addAll ( getInstanceVarReferenceNodeTypes ( ( InstVarNode ) node ) ) ; } if ( node instanceof ClassVarNode ) { guesses . addAll ( getClassVarReferenceNodeTypes ( ( ClassVarNode ) node ) ) ; } if ( node instanceof GlobalVarNode ) { guesses . addAll ( getGlobalVarReferenceNodeTypes ( ( GlobalVarNode ) node ) ) ; } if ( isCallNode ( node ) ) { guesses . addAll ( getCallNodeTypes ( node ) ) ; } inferNodeStack . remove ( ) ; return guesses ; } private boolean isConstantNode ( Node node ) { return ( node instanceof Colon2Node ) || ( node instanceof ConstNode ) || ( null != LiteralNodeTypeNames . get ( node . getClass ( ) . getSimpleName ( ) ) ) ; } private ITypeGuess getConstantNodeType ( Node node ) { if ( node instanceof ConstNode ) { return new BasicTypeGuess ( ( ( ConstNode ) node ) . getName ( ) , ) ; } if ( node instanceof Colon2Node ) { String name = ASTUtil . getFullyQualifiedName ( ( Colon2Node ) node ) ; return new BasicTypeGuess ( name , ) ; } return new BasicTypeGuess ( LiteralNodeTypeNames . get ( node . getClass ( ) . getSimpleName ( ) ) , ) ; } private boolean isTypeDefinitionNode ( Node node ) { return ( node instanceof ClassNode ) || ( node instanceof ModuleNode ) ; } private ITypeGuess getTypeDefinitionNodeType ( Node node ) { String typeNodeName = helper . getTypeNodeName ( node ) ; if ( typeNodeName != null ) { return new BasicTypeGuess ( typeNodeName , ) ; } RubyCore . log ( "" + node ) ; return null ; } private boolean isSelfReferenceNode ( Node node ) { return ( node instanceof SelfNode ) ; } private ITypeGuess getSelfReferenceNodeType ( Node node ) { Node enclosingTypeNode = findEnclosingTypeNode ( node ) ; return getTypeDefinitionNodeType ( enclosingTypeNode ) ; } private List < Node > findAllSendersOfMethod ( String typeName , String methodName ) { return MethodInvocationLocator . Instance ( ) . findMethodInvocations ( rootNode , typeName , methodName , new DataFlowTypeInferrer ( ) ) ; } private List < Node > findAllMethodDefinitions ( String typeName , String methodName ) { return MethodDefinitionLocator . Instance ( ) . findMethodDefinitions ( rootNode , typeName , methodName ) ; } private List < Node > findRetvalExprs ( Node methodNode ) { ReturnVisitor visitor = new ReturnVisitor ( ) ; visitor . acceptNode ( methodNode ) ; List < Node > returnNodes = visitor . getReturnValues ( ) ; List < Node > retvalExprs = new ArrayList < Node > ( returnNodes . size ( ) ) ; for ( Node returnNode : returnNodes ) { if ( returnNode instanceof ReturnNode ) { retvalExprs . add ( ( ( ReturnNode ) returnNode ) . getValueNode ( ) ) ; } else { retvalExprs . add ( returnNode ) ; } } sysout ( "" + retvalExprs . size ( ) + "" + helper . getMethodDefinitionNodeName ( methodNode ) ) ; return retvalExprs ; } private Node findEnclosingMethodNode ( Node node ) { Node enclosingScopeNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( rootNode , node . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof DefnNode ) || ( node instanceof DefsNode ) ; } } ) ; if ( enclosingScopeNode == null ) { enclosingScopeNode = rootNode ; } return enclosingScopeNode ; } private Node findEnclosingTypeNode ( Node node ) { Node enclosingTypeNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( rootNode , node . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ClassNode ) || ( node instanceof ModuleNode ) ; } } ) ; if ( enclosingTypeNode == null ) { enclosingTypeNode = rootNode ; } return enclosingTypeNode ; } private List < ITypeGuess > getLocalVarReferenceNodeTypes ( LocalVarNode node ) { List < ITypeGuess > possibleTypes = new ArrayList < ITypeGuess > ( ) ; Node enclosingScopeNode = findEnclosingMethodNode ( node ) ; if ( enclosingScopeNode == rootNode ) { sysout ( "" ) ; enclosingScopeNode = findEnclosingTypeNode ( node ) ; } final String localVarName = helper . getVarName ( node ) ; CopyOnWriteArrayList < Node > localAssignsIntoNode = new CopyOnWriteArrayList < Node > ( ScopedNodeLocator . Instance ( ) . findNodesInScope ( enclosingScopeNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node acceptNode ) { if ( acceptNode instanceof LocalAsgnNode ) { return ( ( ( LocalAsgnNode ) acceptNode ) . getName ( ) . equals ( localVarName ) ) ; } return false ; } } ) ) ; if ( ( localAssignsIntoNode != null ) && ( localAssignsIntoNode . size ( ) > ) ) { for ( Node asgnNode : localAssignsIntoNode ) { possibleTypes . addAll ( inferNodeType ( ( ( AssignableNode ) asgnNode ) . getValueNode ( ) ) ) ; } return possibleTypes ; } if ( helper . isArgumentInMethod ( localVarName , enclosingScopeNode ) ) { Node enclosingMethodNode = enclosingScopeNode ; sysout ( "" ) ; Node enclosingTypeNode = findEnclosingTypeNode ( node ) ; String enclosingTypeName = "" ; if ( enclosingTypeNode != rootNode ) { enclosingTypeName = helper . getTypeNodeName ( enclosingTypeNode ) ; } String enclosingMethodName = helper . getMethodDefinitionNodeName ( enclosingMethodNode ) ; sysout ( "" + localVarName + "" + enclosingMethodName ) ; ListNode argsListNode = helper . getArgsListNode ( enclosingMethodNode ) ; int paramIndex = helper . getArgIndex ( argsListNode , localVarName ) ; List < Node > sendExprs = findAllSendersOfMethod ( enclosingTypeName , enclosingMethodName ) ; sysout ( "" + sendExprs . size ( ) + "" ) ; List < Node > argExprs = new ArrayList < Node > ( sendExprs . size ( ) ) ; for ( Node sendExpr : sendExprs ) { prettyPrint ( sendExpr ) ; argExprs . add ( helper . findNthArgExprInSendExpr ( paramIndex , sendExpr ) ) ; } sysout ( "" + argExprs . size ( ) ) ; for ( Node argExpr : argExprs ) { prettyPrint ( argExpr ) ; possibleTypes . addAll ( inferNodeType ( argExpr ) ) ; } return possibleTypes ; } sysout ( "" ) ; return possibleTypes ; } private List < ITypeGuess > getDVarReferenceNodeTypes ( DVarNode node ) { List < ITypeGuess > possibleTypes = new ArrayList < ITypeGuess > ( ) ; Node enclosingScopeNode = findEnclosingMethodNode ( node ) ; if ( enclosingScopeNode == rootNode ) { enclosingScopeNode = findEnclosingTypeNode ( node ) ; } final String varName = node . getName ( ) ; List < Node > dynAsgnNodes = ScopedNodeLocator . Instance ( ) . findNodesInScope ( enclosingScopeNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node acceptNode ) { if ( acceptNode instanceof DAsgnNode ) { return ( ( ( DAsgnNode ) acceptNode ) . getName ( ) . equals ( varName ) ) ; } return false ; } } ) ; if ( dynAsgnNodes != null ) { for ( Node dynAsgnNode : dynAsgnNodes ) { possibleTypes . addAll ( inferNodeType ( ( ( DAsgnNode ) dynAsgnNode ) . getValueNode ( ) ) ) ; } } return possibleTypes ; } private List < ITypeGuess > getInstanceVarReferenceNodeTypes ( InstVarNode node ) { List < ITypeGuess > possibleTypes = new ArrayList < ITypeGuess > ( ) ; Node enclosingTypeNode = findEnclosingTypeNode ( node ) ; final String instanceVarName = helper . getVarName ( node ) ; List < Node > instAsgnNodes = ScopedNodeLocator . Instance ( ) . findNodesInScope ( enclosingTypeNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node acceptNode ) { if ( acceptNode instanceof InstAsgnNode ) { return ( ( ( InstAsgnNode ) acceptNode ) . getName ( ) . equals ( instanceVarName ) ) ; } return false ; } } ) ; if ( instAsgnNodes != null ) { for ( Node instAsgnNode : instAsgnNodes ) { possibleTypes . addAll ( inferNodeType ( ( ( InstAsgnNode ) instAsgnNode ) . getValueNode ( ) ) ) ; } } return possibleTypes ; } private List < ITypeGuess > getClassVarReferenceNodeTypes ( ClassVarNode node ) { List < ITypeGuess > possibleTypes = new ArrayList < ITypeGuess > ( ) ; Node enclosingTypeNode = findEnclosingTypeNode ( node ) ; final String classVarName = helper . getVarName ( node ) ; prettyPrint ( enclosingTypeNode ) ; List < Node > classAsgnNodes = ScopedNodeLocator . Instance ( ) . findNodesInScope ( enclosingTypeNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node acceptNode ) { if ( acceptNode instanceof ClassVarAsgnNode ) { return ( ( ( ClassVarAsgnNode ) acceptNode ) . getName ( ) . equals ( classVarName ) ) ; } else if ( acceptNode instanceof ClassVarDeclNode ) { return ( ( ( ClassVarDeclNode ) acceptNode ) . getName ( ) . equals ( classVarName ) ) ; } return false ; } } ) ; if ( classAsgnNodes != null ) { sysout ( "" + classAsgnNodes . size ( ) ) ; for ( Node classAsgnNode : classAsgnNodes ) { if ( classAsgnNode instanceof ClassVarAsgnNode ) { possibleTypes . addAll ( inferNodeType ( ( ( ClassVarAsgnNode ) classAsgnNode ) . getValueNode ( ) ) ) ; } if ( classAsgnNode instanceof ClassVarDeclNode ) { possibleTypes . addAll ( inferNodeType ( ( ( ClassVarDeclNode ) classAsgnNode ) . getValueNode ( ) ) ) ; } } } return possibleTypes ; } private List < ITypeGuess > getGlobalVarReferenceNodeTypes ( GlobalVarNode node ) { List < ITypeGuess > possibleTypes = new ArrayList < ITypeGuess > ( ) ; final String globalVarName = helper . getVarName ( node ) ; List < Node > globalAsgnNodes = ScopedNodeLocator . Instance ( ) . findNodesInScope ( rootNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node acceptNode ) { if ( acceptNode instanceof GlobalAsgnNode ) { return ( ( ( GlobalAsgnNode ) acceptNode ) . getName ( ) . equals ( globalVarName ) ) ; } return false ; } } ) ; for ( Node globalAsgnNode : globalAsgnNodes ) { possibleTypes . addAll ( inferNodeType ( ( ( GlobalAsgnNode ) globalAsgnNode ) . getValueNode ( ) ) ) ; } return possibleTypes ; } private boolean isAssignmentNode ( Node node ) { return ( node instanceof LocalAsgnNode ) || ( node instanceof InstAsgnNode ) || ( node instanceof GlobalAsgnNode ) ; } private Node getAssignmentNodeValueNode ( Node node ) { if ( node instanceof InstAsgnNode ) { return ( ( InstAsgnNode ) node ) . getValueNode ( ) ; } if ( node instanceof LocalAsgnNode ) { return ( ( LocalAsgnNode ) node ) . getValueNode ( ) ; } if ( node instanceof GlobalAsgnNode ) { return ( ( GlobalAsgnNode ) node ) . getValueNode ( ) ; } return null ; } private boolean isCallNode ( Node node ) { return ( node instanceof CallNode ) || ( node instanceof FCallNode ) || ( node instanceof VCallNode ) ; } private List < ITypeGuess > getCallNodeTypes ( Node node ) { String methodName = helper . getCallNodeMethodName ( node ) ; if ( methodName . equals ( "" ) ) { return getInstantiationCallNodeTypes ( node ) ; } List < ITypeGuess > possibleTypes = new LinkedList < ITypeGuess > ( ) ; possibleTypes . addAll ( TypicalMethodReturnNames . get ( methodName ) ) ; List < String > receiverTypes = new ArrayList < String > ( ) ; if ( node instanceof CallNode ) { List < ITypeGuess > receiverTypeInferences = inferNodeType ( ( ( CallNode ) node ) . getReceiverNode ( ) ) ; if ( receiverTypeInferences != null && receiverTypeInferences . size ( ) > ) { for ( ITypeGuess typeGuess : receiverTypeInferences ) { if ( typeGuess == null ) continue ; receiverTypes . add ( typeGuess . getType ( ) ) ; } } } else if ( ( node instanceof FCallNode ) || ( node instanceof VCallNode ) ) { String receiverTypeName = helper . getTypeNodeName ( findEnclosingTypeNode ( node ) ) ; if ( receiverTypeName == null ) { receiverTypeName = "" ; } receiverTypes . add ( receiverTypeName ) ; } List < Node > defnNodes = new ArrayList < Node > ( ) ; for ( String receiverType : receiverTypes ) { List < Node > result = findAllMethodDefinitions ( receiverType , methodName ) ; defnNodes . addAll ( result ) ; sysout ( "" + receiverType ) ; sysout ( "" + result . size ( ) + "" ) ; } List < Node > retvalExprs = new LinkedList < Node > ( ) ; for ( Node defnNode : defnNodes ) { retvalExprs . addAll ( findRetvalExprs ( defnNode ) ) ; } for ( Node retvalExpr : retvalExprs ) { possibleTypes . addAll ( inferNodeType ( retvalExpr ) ) ; } return possibleTypes ; } private List < ITypeGuess > getInstantiationCallNodeTypes ( Node node ) { List < ITypeGuess > possibleTypes = new ArrayList < ITypeGuess > ( ) ; if ( node instanceof CallNode ) { Node receiverNode = ( ( CallNode ) node ) . getReceiverNode ( ) ; return inferNodeType ( receiverNode ) ; } if ( node instanceof FCallNode ) { Node enclosingTypeNode = findEnclosingTypeNode ( node ) ; possibleTypes . add ( getTypeDefinitionNodeType ( enclosingTypeNode ) ) ; } if ( node instanceof VCallNode ) { Node enclosingTypeNode = findEnclosingTypeNode ( node ) ; possibleTypes . add ( getTypeDefinitionNodeType ( enclosingTypeNode ) ) ; } return possibleTypes ; } } package org . rubypeople . rdt . internal . codeassist ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor . MethodInfo ; public class ASTSourceRequestor implements ISourceElementRequestor { private Map < TypeInfo , List < MethodInfo > > types = new HashMap < TypeInfo , List < MethodInfo > > ( ) ; private Map < TypeInfo , List < String > > mixins = new HashMap < TypeInfo , List < String > > ( ) ; private List < TypeInfo > typeStack = new ArrayList < TypeInfo > ( ) ; private Map < String , TypeInfo > fullTypeNames = new HashMap < String , TypeInfo > ( ) ; private TypeInfo topLevel ; private MethodInfo latestMethod ; public ASTSourceRequestor ( ) { topLevel = new TypeInfo ( ) ; topLevel . declarationStart = ; topLevel . isModule = false ; topLevel . name = "" ; topLevel . nameSourceStart = ; topLevel . nameSourceEnd = ; topLevel . secondary = false ; topLevel . superclass = null ; } public void acceptConstructorReference ( String name , int argCount , int offset ) { } public void acceptFieldReference ( String name , int offset ) { } public void acceptImport ( String value , int startOffset , int endOffset ) { } public void acceptMethodReference ( String name , int argCount , int offset ) { } public void acceptMethodVisibilityChange ( String methodName , int visibility ) { } public void acceptMixin ( String string ) { TypeInfo info = getCurrentType ( ) ; List < String > duh = mixins . get ( info ) ; if ( duh == null ) { duh = new ArrayList < String > ( ) ; } duh . add ( string ) ; mixins . put ( info , duh ) ; } public void acceptModuleFunction ( String function ) { } public void acceptProblem ( CategorizedProblem problem ) { } public void acceptTypeReference ( String name , int startOffset , int endOffset ) { } public void acceptUnknownReference ( String name , int startOffset , int endOffset ) { } public void enterConstructor ( MethodInfo constructor ) { } public void enterField ( FieldInfo field ) { } public void enterMethod ( MethodInfo method ) { TypeInfo info = getCurrentType ( ) ; List < MethodInfo > methods = types . get ( info ) ; if ( methods == null ) methods = new ArrayList < MethodInfo > ( ) ; methods . add ( method ) ; types . put ( info , methods ) ; latestMethod = method ; } public void acceptYield ( String name ) { latestMethod . blockVars = new String [ ] { name } ; } private TypeInfo getCurrentType ( ) { if ( typeStack . isEmpty ( ) ) return topLevel ; TypeInfo info = typeStack . get ( typeStack . size ( ) - ) ; return info ; } public void enterScript ( ) { } public void enterType ( TypeInfo type ) { types . put ( type , new ArrayList < MethodInfo > ( ) ) ; typeStack . add ( type ) ; mixins . put ( type , new ArrayList < String > ( ) ) ; String fullName = getNamespace ( ) + type . name ; fullTypeNames . put ( fullName , type ) ; } private String getNamespace ( ) { StringBuffer buffer = new StringBuffer ( ) ; List < TypeInfo > newTypeStack = new ArrayList < TypeInfo > ( typeStack ) ; newTypeStack . remove ( newTypeStack . size ( ) - ) ; for ( TypeInfo type : newTypeStack ) { buffer . append ( type . name ) ; buffer . append ( "" ) ; } return buffer . toString ( ) ; } public void exitConstructor ( int endOffset ) { } public void exitField ( int endOffset ) { } public void exitMethod ( int endOffset ) { } public void exitScript ( int endOffset ) { } public void exitType ( int endOffset ) { typeStack . remove ( typeStack . size ( ) - ) ; } public List < String > getMixins ( String name ) { for ( String fullName : fullTypeNames . keySet ( ) ) { if ( fullName . equals ( name ) ) { TypeInfo info = fullTypeNames . get ( fullName ) ; return mixins . get ( info ) ; } } return Collections . emptyList ( ) ; } public Map < IMethod , String > getMethods ( String mixin ) { Map < IMethod , String > duh = new HashMap < IMethod , String > ( ) ; for ( String fullName : fullTypeNames . keySet ( ) ) { if ( fullName . equals ( mixin ) ) { TypeInfo info = fullTypeNames . get ( fullName ) ; List < MethodInfo > methods = types . get ( info ) ; for ( MethodInfo methodInfo : methods ) { duh . put ( new MethodInfoMethod ( methodInfo ) , mixin ) ; } return duh ; } } return duh ; } private static class MethodInfoMethod implements IMethod { private MethodInfo info ; public MethodInfoMethod ( MethodInfo info ) { this . info = info ; } public int getNumberOfParameters ( ) throws RubyModelException { return info . parameterNames . length ; } public String [ ] getParameterNames ( ) throws RubyModelException { return info . parameterNames ; } public int getVisibility ( ) throws RubyModelException { return info . visibility ; } public boolean isConstructor ( ) { return info . isConstructor ; } public boolean isPrivate ( ) throws RubyModelException { return info . visibility == IMethod . PRIVATE ; } public boolean isProtected ( ) throws RubyModelException { return info . visibility == IMethod . PROTECTED ; } public boolean isPublic ( ) throws RubyModelException { return info . visibility == IMethod . PUBLIC ; } public boolean isSingleton ( ) { return info . isClassLevel ; } public boolean exists ( ) { return false ; } public IRubyElement getAncestor ( int ancestorType ) { return null ; } public IResource getCorrespondingResource ( ) throws RubyModelException { return null ; } public boolean isSimilar ( IMethod method ) { return false ; } public String getElementName ( ) { return info . name ; } public int getElementType ( ) { return IRubyElement . METHOD ; } public String getHandleIdentifier ( ) { return null ; } public IOpenable getOpenable ( ) { return null ; } public IRubyElement getParent ( ) { return null ; } public IPath getPath ( ) { return null ; } public IRubyElement getPrimaryElement ( ) { return null ; } public IResource getResource ( ) { return null ; } public IRubyModel getRubyModel ( ) { return null ; } public IRubyProject getRubyProject ( ) { return null ; } public IResource getUnderlyingResource ( ) throws RubyModelException { return null ; } public boolean isReadOnly ( ) { return false ; } public boolean isStructureKnown ( ) throws RubyModelException { return false ; } public boolean isType ( int type ) { return type == IRubyElement . METHOD ; } public Object getAdapter ( Class adapter ) { return null ; } public IType getDeclaringType ( ) { return null ; } public ISourceRange getNameRange ( ) throws RubyModelException { return null ; } public IRubyScript getRubyScript ( ) { return null ; } public IType getType ( String name , int occurrenceCount ) { return null ; } public String getSource ( ) throws RubyModelException { return null ; } public ISourceRange getSourceRange ( ) throws RubyModelException { return null ; } public IRubyElement [ ] getChildren ( ) throws RubyModelException { return null ; } public boolean hasChildren ( ) throws RubyModelException { return false ; } public String [ ] getBlockParameters ( ) throws RubyModelException { return info . blockVars ; } } public void acceptBlock ( int startOffset , int endOffset ) { } } package org . rubypeople . rdt . internal . codeassist ; import java . util . Comparator ; import org . rubypeople . rdt . core . CompletionProposal ; public class CompletionProposalComparator implements Comparator < CompletionProposal > { public int compare ( CompletionProposal o1 , CompletionProposal o2 ) { if ( o1 . getRelevance ( ) == o2 . getRelevance ( ) ) return o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; else return o2 . getRelevance ( ) - o1 . getRelevance ( ) ; } } package org . rubypeople . rdt . internal . codeassist ; import java . util . List ; import org . jruby . ast . ClassNode ; import org . jruby . ast . CommentNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . parser . RubyParserResult ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; public class CompletionContext { private IRubyScript script ; private int offset ; private boolean isMethodInvokation = false ; private String correctedSource ; private String partialPrefix ; private String fullPrefix ; private int replaceStart ; private boolean isAfterDoubleSemiColon = false ; private Node fRootNode ; private List < CommentNode > fCommentNodes ; private boolean inComment ; public CompletionContext ( IRubyScript script , int offset ) throws RubyModelException { this . script = script ; if ( offset < ) offset = ; this . offset = offset ; replaceStart = offset + ; try { run ( ) ; } catch ( RuntimeException e ) { RubyCore . log ( e ) ; } } private void run ( ) throws RubyModelException { StringBuffer source = new StringBuffer ( script . getSource ( ) ) ; if ( offset >= source . length ( ) ) { offset = source . length ( ) - ; replaceStart = offset + ; } StringBuffer tmpPrefix = new StringBuffer ( ) ; boolean setOffset = false ; for ( int i = offset ; i >= ; i -- ) { char curChar = source . charAt ( i ) ; if ( offset == i ) { switch ( curChar ) { case '' : if ( ( ( i - ) >= ) && ( source . charAt ( i - ) == '' ) ) { source . deleteCharAt ( i ) ; source . deleteCharAt ( i - ) ; tmpPrefix . append ( "" ) ; i -- ; } else source . deleteCharAt ( i ) ; break ; case '' : case '' : case '' : source . deleteCharAt ( i ) ; break ; case '' : if ( i > ) { char previous = source . charAt ( i - ) ; if ( previous == '' ) { isAfterDoubleSemiColon = true ; source . deleteCharAt ( i ) ; source . deleteCharAt ( i - ) ; tmpPrefix . insert ( , "" ) ; partialPrefix = "" ; i -- ; continue ; } } break ; } } if ( curChar == '' ) { isMethodInvokation = true ; if ( partialPrefix == null ) this . partialPrefix = tmpPrefix . toString ( ) ; if ( offset - == i ) { offset = i ; } else { offset = i - ; } setOffset = true ; } else if ( curChar == '' ) { if ( i > ) { char previous = source . charAt ( i - ) ; if ( previous == '' ) { isAfterDoubleSemiColon = true ; if ( partialPrefix == null ) partialPrefix = tmpPrefix . toString ( ) ; tmpPrefix . insert ( , "" ) ; i -- ; } } } if ( Character . isWhitespace ( curChar ) || curChar == '' || curChar == '' || curChar == '' || curChar == '' ) { if ( ! setOffset ) { offset = i + ; setOffset = true ; } break ; } tmpPrefix . insert ( , curChar ) ; } this . fullPrefix = tmpPrefix . toString ( ) ; if ( partialPrefix == null ) partialPrefix = fullPrefix ; if ( partialPrefix != null ) replaceStart -= partialPrefix . length ( ) ; this . correctedSource = source . toString ( ) ; Node selected = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( getRootNode ( ) , this . offset , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return true ; } } ) ; if ( selected == null ) { if ( fCommentNodes != null ) { for ( CommentNode comment : fCommentNodes ) { if ( ClosestSpanningNodeLocator . nodeSpansOffset ( comment , this . offset ) ) { inComment = true ; break ; } } } } } public boolean isExplicitMethodInvokation ( ) { return isMethodInvokation ; } public boolean isMethodInvokationOrLocal ( ) { return ! isExplicitMethodInvokation ( ) && ( emptyPrefix ( ) || ( getPartialPrefix ( ) . length ( ) > && Character . isLowerCase ( getPartialPrefix ( ) . charAt ( ) ) ) ) ; } public boolean isConstant ( ) { return getPartialPrefix ( ) != null && getPartialPrefix ( ) . length ( ) > && Character . isUpperCase ( getPartialPrefix ( ) . charAt ( ) ) ; } public int getReplaceStart ( ) { return replaceStart ; } public String getCorrectedSource ( ) { return correctedSource ; } public boolean isBroken ( ) { try { return ! getCorrectedSource ( ) . equals ( script . getSource ( ) ) ; } catch ( RubyModelException e ) { return true ; } } public boolean hasReceiver ( ) { return getFullPrefix ( ) . indexOf ( '' ) > ; } public String getSource ( ) { try { return getScript ( ) . getSource ( ) ; } catch ( RubyModelException e ) { return "" ; } } public String getFullPrefix ( ) { return fullPrefix ; } public String getPartialPrefix ( ) { return partialPrefix ; } public int getOffset ( ) { return offset ; } public IRubyScript getScript ( ) { return script ; } public boolean emptyPrefix ( ) { return getFullPrefix ( ) == null || getFullPrefix ( ) . length ( ) == ; } public boolean prefixStartsWith ( String name ) { return name != null && getPartialPrefix ( ) != null && name . startsWith ( getPartialPrefix ( ) ) ; } public boolean isGlobal ( ) { return ! emptyPrefix ( ) && ! isExplicitMethodInvokation ( ) && getPartialPrefix ( ) . startsWith ( "" ) ; } public boolean isDoubleSemiColon ( ) { return isAfterDoubleSemiColon && ! isMethodInvokation ; } public boolean fullPrefixIsConstant ( ) { if ( getFullPrefix ( ) == null || getFullPrefix ( ) . length ( ) == ) return false ; if ( getFullPrefix ( ) . endsWith ( "" ) || getFullPrefix ( ) . endsWith ( "" ) ) return false ; return Character . isUpperCase ( getFullPrefix ( ) . charAt ( ) ) ; } public boolean inTypeDefinition ( ) { if ( getRootNode ( ) == null ) return false ; Node spanner = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( getRootNode ( ) , getOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof MethodDefNode || node instanceof ClassNode || node instanceof ModuleNode ; } } ) ; return spanner instanceof ClassNode || spanner instanceof ModuleNode ; } Node getRootNode ( ) { if ( fRootNode != null ) return fRootNode ; RubyParser parser = new RubyParser ( ) ; if ( ! isBroken ( ) ) { try { RubyParserResult result = parser . parse ( getScript ( ) . getElementName ( ) , getSource ( ) ) ; fRootNode = result . getAST ( ) ; ( ( RubyScript ) getScript ( ) ) . lastGoodAST = fRootNode ; fCommentNodes = result . getCommentNodes ( ) ; } catch ( RuntimeException e ) { } } if ( fRootNode == null ) { try { RubyParserResult result = parser . parse ( getCorrectedSource ( ) ) ; fRootNode = result . getAST ( ) ; fCommentNodes = result . getCommentNodes ( ) ; } catch ( RuntimeException e ) { } } if ( fRootNode == null ) { fRootNode = ( ( RubyScript ) getScript ( ) ) . lastGoodAST ; } return fRootNode ; } public boolean inComment ( ) { return inComment ; } public boolean isInstanceOrClassVariable ( ) { return getPartialPrefix ( ) != null && getPartialPrefix ( ) . startsWith ( "" ) && getPartialPrefix ( ) . length ( ) == ; } public boolean isInstanceVariable ( ) { return getPartialPrefix ( ) != null && getPartialPrefix ( ) . startsWith ( "" ) && ! isClassVariable ( ) && getPartialPrefix ( ) . length ( ) > ; } public boolean isClassVariable ( ) { return getPartialPrefix ( ) != null && getPartialPrefix ( ) . startsWith ( "" ) ; } } package org . rubypeople . rdt . internal . codeassist ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . search . CollectingSearchRequestor ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . search . BasicSearchEngine ; public class RubyElementRequestor { private IRubyScript script ; public RubyElementRequestor ( IRubyScript script ) { this . script = script ; } public IType [ ] findType ( String fullyQualifiedName ) { List < IType > types = new ArrayList < IType > ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . TYPE , fullyQualifiedName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; SearchParticipant [ ] participants = new SearchParticipant [ ] { BasicSearchEngine . getDefaultSearchParticipant ( ) } ; IRubySearchScope scope = BasicSearchEngine . createRubySearchScope ( new IRubyElement [ ] { script . getRubyProject ( ) } ) ; CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; try { new BasicSearchEngine ( ) . search ( pattern , participants , scope , requestor , null ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } List < SearchMatch > matches = requestor . getResults ( ) ; for ( SearchMatch match : matches ) { IType type = ( IType ) match . getElement ( ) ; if ( type == null ) continue ; if ( ! type . getFullyQualifiedName ( ) . equals ( fullyQualifiedName ) ) continue ; types . add ( type ) ; } if ( types . isEmpty ( ) ) { for ( SearchMatch match : matches ) { IType type = ( IType ) match . getElement ( ) ; if ( type == null ) continue ; types . add ( type ) ; } } return types . toArray ( new IType [ types . size ( ) ] ) ; } } package org . rubypeople . rdt . internal . codeassist ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . jruby . ast . AliasNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . codeassist . CodeResolver ; import org . rubypeople . rdt . core . codeassist . ResolveContext ; import org . rubypeople . rdt . core . search . CollectingSearchRequestor ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . search . BasicSearchEngine ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . core . util . Util ; import org . rubypeople . rdt . internal . ti . ITypeGuess ; import org . rubypeople . rdt . internal . ti . ITypeInferrer ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . FirstPrecursorNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; public class RubyCodeResolver extends CodeResolver { private static final String OBJECT = "" ; private static final String NEW = "" ; private static final String DEFAULT_FILE_EXTENSION = "" ; private static final String LOAD = "" ; private static final String REQUIRE = "" ; private static final String INITIALIZE = "" ; private HashSet < IType > fVisitedTypes ; @ Override public void select ( ResolveContext context ) throws RubyModelException { Node selected = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( context . getAST ( ) , context . getStartOffset ( ) ) ; if ( selected instanceof StrNode ) { resolveString ( context , selected ) ; return ; } if ( selected instanceof AliasNode ) { resolveAlias ( context , selected ) ; return ; } if ( selected instanceof Colon2Node ) { resolveColon2Node ( context , selected ) ; return ; } if ( selected instanceof DVarNode ) { resolveDynamicVar ( context , selected ) ; return ; } if ( selected instanceof ConstNode ) { resolveConstant ( context , selected ) ; return ; } if ( isLocalVarRef ( selected ) ) { resolveLocalVar ( context , selected ) ; return ; } if ( isInstanceVarRef ( selected ) ) { resolveInstanceVar ( context , selected ) ; return ; } if ( isClassVarRef ( selected ) ) { resolveClassVarRef ( context , selected ) ; return ; } if ( isDeclaration ( selected ) ) { resolveDeclaration ( context ) ; return ; } if ( isMethodCall ( selected ) ) { resolveMethodCall ( context , selected ) ; return ; } } private boolean isDeclaration ( Node selected ) { return ( selected instanceof DefnNode ) || ( selected instanceof DefsNode ) || ( selected instanceof ConstDeclNode ) || ( selected instanceof ClassNode ) || ( selected instanceof ModuleNode ) || ( selected instanceof ClassVarDeclNode ) ; } protected void resolveString ( ResolveContext context , Node selected ) throws RubyModelException { StrNode string = ( StrNode ) selected ; FCallNode fcall = ( FCallNode ) ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( context . getAST ( ) , string . getPosition ( ) . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof FCallNode ; } } ) ; if ( fcall == null ) return ; IRubyScript script = context . getScript ( ) ; if ( fcall . getName ( ) . equals ( REQUIRE ) || fcall . getName ( ) . equals ( LOAD ) ) { String value = string . getValue ( ) . toString ( ) ; if ( ! value . endsWith ( DEFAULT_FILE_EXTENSION ) ) { value += DEFAULT_FILE_EXTENSION ; } ILoadpathEntry [ ] entries = script . getRubyProject ( ) . getResolvedLoadpath ( true ) ; for ( int i = ; i < entries . length ; i ++ ) { IPath path = entries [ i ] . getPath ( ) . append ( value ) ; if ( path . toFile ( ) . exists ( ) ) { IFile file = null ; if ( path . isAbsolute ( ) ) { file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFileForLocation ( path ) ; } else { file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( path ) ; } if ( file != null ) { putResolved ( context , new IRubyElement [ ] { RubyCore . create ( file ) } ) ; return ; } ISourceFolderRoot sfRoot = script . getRubyProject ( ) . getSourceFolderRoot ( entries [ i ] . getPath ( ) . toPortableString ( ) ) ; String [ ] parts = value . split ( "" ) ; String [ ] minusFileName ; if ( parts . length == ) { minusFileName = new String [ ] ; } else { minusFileName = new String [ parts . length - ] ; System . arraycopy ( parts , , minusFileName , , minusFileName . length ) ; } ISourceFolder folder = sfRoot . getSourceFolder ( minusFileName ) ; putResolved ( context , new IRubyElement [ ] { folder . getRubyScript ( path . lastSegment ( ) ) } ) ; return ; } } } } protected void putResolved ( ResolveContext context , IRubyElement [ ] resolved ) { if ( resolved != null && resolved . length > ) context . putResolved ( resolved ) ; } protected void resolveMethodCall ( ResolveContext context , Node selected ) throws RubyModelException { String methodName = getName ( selected ) ; if ( methodName . equals ( NEW ) ) methodName = INITIALIZE ; Set < IRubyElement > possible = new HashSet < IRubyElement > ( ) ; IType [ ] types = getReceiver ( context , selected ) ; for ( int i = ; i < types . length ; i ++ ) { IType type = types [ i ] ; if ( fVisitedTypes == null ) { fVisitedTypes = new HashSet < IType > ( ) ; } Collection < IMethod > methods = suggestMethods ( type ) ; fVisitedTypes . clear ( ) ; for ( IMethod method : methods ) { if ( method . getElementName ( ) . equals ( methodName ) ) possible . add ( method ) ; } } if ( possible . isEmpty ( ) ) { Set < String > uniqueTypeNames = uniqueTypeNames ( types ) ; if ( uniqueTypeNames . size ( ) == ) { if ( methodName . equals ( INITIALIZE ) ) { putResolved ( context , types ) ; return ; } else { try { List < SearchMatch > results = search ( IRubyElement . METHOD , uniqueTypeNames . iterator ( ) . next ( ) + "" + methodName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; for ( SearchMatch match : results ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; possible . add ( element ) ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } else { try { List < SearchMatch > results = search ( IRubyElement . METHOD , methodName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; for ( SearchMatch match : results ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; possible . add ( element ) ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } putResolved ( context , possible . toArray ( new IRubyElement [ possible . size ( ) ] ) ) ; } protected void resolveInstanceVar ( ResolveContext context , Node selected ) throws RubyModelException { List < IRubyElement > possible = getChildrenWithName ( context . getScript ( ) . getChildren ( ) , IRubyElement . INSTANCE_VAR , getName ( selected ) ) ; putResolved ( context , possible . toArray ( new IRubyElement [ possible . size ( ) ] ) ) ; } protected void resolveLocalVar ( ResolveContext context , Node selected ) throws RubyModelException { IRubyScript script = context . getScript ( ) ; IRubyElement spanner = script . getElementAt ( selected . getPosition ( ) . getStartOffset ( ) ) ; List < IRubyElement > possible = new ArrayList < IRubyElement > ( ) ; if ( spanner instanceof IParent ) { IParent parent = ( IParent ) spanner ; possible = getChildrenWithName ( parent . getChildren ( ) , IRubyElement . LOCAL_VARIABLE , getName ( selected ) ) ; } if ( possible . isEmpty ( ) ) { possible = getChildrenWithName ( script . getChildren ( ) , IRubyElement . LOCAL_VARIABLE , getName ( selected ) ) ; } putResolved ( context , possible . toArray ( new IRubyElement [ possible . size ( ) ] ) ) ; } protected void resolveConstant ( ResolveContext context , Node selected ) throws RubyModelException { ConstNode constNode = ( ConstNode ) selected ; String name = constNode . getName ( ) ; IRubyScript script = context . getScript ( ) ; try { IRubySearchScope scope = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { script } ) ; List < SearchMatch > matches = search ( scope , IRubyElement . CONSTANT , name , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; if ( matches . isEmpty ( ) ) { scope = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { script . getRubyProject ( ) } ) ; matches = search ( scope , IRubyElement . CONSTANT , name , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; } for ( SearchMatch match : matches ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; if ( element != null ) { putResolved ( context , new IRubyElement [ ] { element } ) ; return ; } } } catch ( CoreException e ) { RubyCore . log ( e ) ; } try { IRubySearchScope scope = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { script } ) ; List < SearchMatch > matches = search ( scope , IRubyElement . TYPE , name , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; for ( SearchMatch match : matches ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; if ( element != null ) { putResolved ( context , new IRubyElement [ ] { element } ) ; return ; } } } catch ( CoreException e ) { RubyCore . log ( e ) ; } RubyElementRequestor completer = new RubyElementRequestor ( script ) ; String fullyQualifiedName = getFullyQualifiedName ( context . getAST ( ) , constNode . getPosition ( ) . getStartOffset ( ) , name ) ; if ( fullyQualifiedName != null ) { IType [ ] types = completer . findType ( fullyQualifiedName ) ; if ( types != null && types . length > ) { putResolved ( context , types ) ; return ; } } putResolved ( context , completer . findType ( name ) ) ; } protected void resolveDynamicVar ( ResolveContext context , Node selected ) throws RubyModelException { final String name = ( ( DVarNode ) selected ) . getName ( ) ; Node assignment = FirstPrecursorNodeLocator . Instance ( ) . findFirstPrecursor ( context . getAST ( ) , context . getStartOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof DAsgnNode ) && ( ( DAsgnNode ) node ) . getName ( ) . equals ( name ) ; } } ) ; putResolved ( context , new IRubyElement [ ] { context . getScript ( ) . getElementAt ( assignment . getPosition ( ) . getStartOffset ( ) ) } ) ; } protected void resolveClassVarRef ( ResolveContext context , Node selected ) throws RubyModelException { List < IRubyElement > possible = getChildrenWithName ( context . getScript ( ) . getChildren ( ) , IRubyElement . CLASS_VAR , getName ( selected ) ) ; putResolved ( context , possible . toArray ( new IRubyElement [ possible . size ( ) ] ) ) ; } protected void resolveDeclaration ( ResolveContext context ) throws RubyModelException { IRubyElement element = ( ( RubyScript ) context . getScript ( ) ) . getElementAt ( context . getStartOffset ( ) ) ; if ( element != null ) putResolved ( context , new IRubyElement [ ] { element } ) ; } protected void resolveColon2Node ( ResolveContext context , Node selected ) { String simpleName = ( ( Colon2Node ) selected ) . getName ( ) ; String fullyQualifiedName = ASTUtil . getFullyQualifiedName ( ( Colon2Node ) selected ) ; IRubyScript script = context . getScript ( ) ; IRubyElement element = findChild ( simpleName , IRubyElement . TYPE , script ) ; if ( element != null && Util . parentsMatch ( ( IType ) element , fullyQualifiedName ) ) { putResolved ( context , new IRubyElement [ ] { element } ) ; return ; } RubyElementRequestor completer = new RubyElementRequestor ( script ) ; putResolved ( context , completer . findType ( fullyQualifiedName ) ) ; } protected void resolveAlias ( ResolveContext context , Node selected ) { AliasNode aliasNode = ( AliasNode ) selected ; int startOffset = aliasNode . getPosition ( ) . getStartOffset ( ) ; int diff = context . getStartOffset ( ) - startOffset ; if ( diff < ( + aliasNode . getNewName ( ) . length ( ) + ) ) return ; String methodName = aliasNode . getOldName ( ) ; List < IRubyElement > possible = new ArrayList < IRubyElement > ( ) ; try { List < SearchMatch > results = search ( IRubyElement . METHOD , methodName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; for ( SearchMatch match : results ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; possible . add ( element ) ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } putResolved ( context , possible . toArray ( new IRubyElement [ possible . size ( ) ] ) ) ; return ; } private Set < String > uniqueTypeNames ( IType [ ] types ) { Set < String > names = new HashSet < String > ( ) ; if ( types == null ) return names ; for ( IType type : types ) { names . add ( type . getFullyQualifiedName ( ) ) ; } return names ; } private String getFullyQualifiedName ( Node root , int offset , String name ) { String namespace = ASTUtil . getNamespace ( root , offset ) ; if ( namespace == null || namespace . trim ( ) . length ( ) == ) { return name ; } return namespace + "" + name ; } protected List < SearchMatch > search ( int type , String patternString , int limitTo , int matchRule ) throws CoreException { return search ( SearchEngine . createWorkspaceScope ( ) , type , patternString , limitTo , matchRule ) ; } protected List < SearchMatch > search ( IRubySearchScope scope , int type , String patternString , int limitTo , int matchRule ) throws CoreException { SearchEngine engine = new SearchEngine ( ) ; SearchPattern pattern = SearchPattern . createPattern ( type , patternString , limitTo , matchRule ) ; SearchParticipant [ ] participants = new SearchParticipant [ ] { SearchEngine . getDefaultSearchParticipant ( ) } ; CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; engine . search ( pattern , participants , scope , requestor , null ) ; return requestor . getResults ( ) ; } private IType [ ] getReceiver ( ResolveContext context , Node selected ) throws RubyModelException { List < IType > types = new ArrayList < IType > ( ) ; if ( ( selected instanceof FCallNode ) || ( selected instanceof VCallNode ) ) { types = resolveImplicitReceiver ( context , selected ) ; } else { int start = context . getStartOffset ( ) ; if ( selected instanceof CallNode ) { CallNode call = ( CallNode ) selected ; Node receiver = call . getReceiverNode ( ) ; start = receiver . getPosition ( ) . getStartOffset ( ) ; } IRubyScript script = context . getScript ( ) ; ITypeInferrer inferrer = RubyCore . getTypeInferrer ( ) ; Collection < ITypeGuess > guesses = new ArrayList < ITypeGuess > ( ) ; try { guesses = inferrer . infer ( script . getSource ( ) , start ) ; } catch ( RubyModelException e1 ) { RubyCore . log ( e1 ) ; } if ( guesses . isEmpty ( ) ) { String methodName = ASTUtil . getNameReflectively ( selected ) ; IRubySearchScope scope = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { script . getRubyProject ( ) } ) ; CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . METHOD , methodName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; SearchParticipant [ ] participants = { BasicSearchEngine . getDefaultSearchParticipant ( ) } ; try { new BasicSearchEngine ( ) . search ( pattern , participants , scope , requestor , null ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } List < SearchMatch > matches = requestor . getResults ( ) ; if ( matches == null || matches . isEmpty ( ) ) return new IType [ ] ; for ( SearchMatch match : matches ) { IMethod method = ( IMethod ) match . getElement ( ) ; types . add ( method . getDeclaringType ( ) ) ; } } else { RubyElementRequestor requestor = new RubyElementRequestor ( script ) ; for ( ITypeGuess guess : guesses ) { String name = guess . getType ( ) ; IType [ ] tmpTypes = requestor . findType ( name ) ; for ( int i = ; i < tmpTypes . length ; i ++ ) { types . add ( tmpTypes [ i ] ) ; } } } } return types . toArray ( new IType [ types . size ( ) ] ) ; } protected List < IType > resolveImplicitReceiver ( ResolveContext context , Node selected ) throws RubyModelException { IRubyScript script = context . getScript ( ) ; RootNode root = context . getAST ( ) ; int start = context . getStartOffset ( ) ; List < IType > types = new ArrayList < IType > ( ) ; Node receiver = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( root , start , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ClassNode || node instanceof ModuleNode ) ; } } ) ; IRubySearchScope scope = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { script } ) ; String typeName = ASTUtil . getNameReflectively ( receiver ) ; if ( typeName == null ) typeName = OBJECT ; try { List < SearchMatch > matches = search ( scope , IRubyElement . TYPE , typeName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; if ( matches == null || matches . isEmpty ( ) ) return Collections . emptyList ( ) ; for ( SearchMatch match : matches ) { types . add ( ( IType ) match . getElement ( ) ) ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } return types ; } private Collection < IMethod > suggestMethods ( IType type ) throws RubyModelException { if ( type == null ) return Collections . emptyList ( ) ; if ( fVisitedTypes == null ) fVisitedTypes = new HashSet < IType > ( ) ; List < IMethod > proposals = new ArrayList < IMethod > ( ) ; ITypeHierarchy hierarchy = type . newSupertypeHierarchy ( null ) ; IType [ ] all = new IType [ ] { type } ; if ( hierarchy != null ) { all = hierarchy . getAllSupertypes ( type ) ; } for ( int j = ; j < all . length ; j ++ ) { IType currentType = all [ j ] ; if ( fVisitedTypes . contains ( currentType ) ) continue ; fVisitedTypes . add ( currentType ) ; IMethod [ ] methods = currentType . getMethods ( ) ; if ( methods != null ) { for ( int k = ; k < methods . length ; k ++ ) { if ( methods [ k ] == null ) continue ; proposals . add ( methods [ k ] ) ; } } } fVisitedTypes . clear ( ) ; return proposals ; } private IRubyElement findChild ( String name , int type , IParent parent ) { try { IRubyElement [ ] children = parent . getChildren ( ) ; for ( int j = ; j < children . length ; j ++ ) { IRubyElement child = children [ j ] ; if ( child . getElementName ( ) . equals ( name ) && child . isType ( type ) ) return child ; if ( child instanceof IParent ) { IRubyElement found = findChild ( name , type , ( IParent ) child ) ; if ( found != null ) return found ; } } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } return null ; } private boolean isMethodCall ( Node selected ) { return ( selected instanceof VCallNode ) || ( selected instanceof FCallNode ) || ( selected instanceof CallNode ) ; } private List < IRubyElement > getChildrenWithName ( IRubyElement [ ] children , int type , String name ) throws RubyModelException { List < IRubyElement > possible = new ArrayList < IRubyElement > ( ) ; for ( int i = ; i < children . length ; i ++ ) { IRubyElement child = children [ i ] ; if ( child . getElementType ( ) == type ) { if ( child . getElementName ( ) . equals ( name ) ) possible . add ( child ) ; } if ( child instanceof IParent ) { possible . addAll ( getChildrenWithName ( ( ( IParent ) child ) . getChildren ( ) , type , name ) ) ; } } return possible ; } private String getName ( Node node ) { if ( node instanceof INameNode ) { return ( ( INameNode ) node ) . getName ( ) ; } if ( node instanceof ClassVarNode ) { return ( ( ClassVarNode ) node ) . getName ( ) ; } return "" ; } private boolean isInstanceVarRef ( Node node ) { return ( ( node instanceof InstAsgnNode ) || ( node instanceof InstVarNode ) ) ; } private boolean isClassVarRef ( Node node ) { return ( ( node instanceof ClassVarAsgnNode ) || ( node instanceof ClassVarNode ) ) ; } private boolean isLocalVarRef ( Node node ) { return ( ( node instanceof LocalAsgnNode ) || ( node instanceof ArgumentNode ) || ( node instanceof LocalVarNode ) ) ; } } package org . rubypeople . rdt . internal . codeassist ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionRegistry ; import org . eclipse . core . runtime . PerformanceStats ; import org . eclipse . core . runtime . Platform ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . codeassist . CodeResolver ; import org . rubypeople . rdt . core . codeassist . ResolveContext ; public class SelectionEngine { private static final String PERFORMANCE_EVENT = "" ; private static final boolean MEASURE_PERFORMANCE = PerformanceStats . isEnabled ( PERFORMANCE_EVENT ) ; private static final String EXTENSION_POINT = "" ; private ArrayList < CodeResolver > fResolvers ; public IRubyElement [ ] select ( IRubyScript script , int start , int end ) throws RubyModelException { ResolveContext context = new ResolveContext ( script , start , end ) ; List < CodeResolver > resolvers = getResolvers ( ) ; for ( CodeResolver resolver : resolvers ) { PerformanceStats stats = null ; if ( MEASURE_PERFORMANCE ) { stats = PerformanceStats . getStats ( PERFORMANCE_EVENT , resolver ) ; stats . startRun ( resolver . getClass ( ) . getName ( ) ) ; } resolver . select ( context ) ; if ( MEASURE_PERFORMANCE ) { stats . endRun ( ) ; } } if ( MEASURE_PERFORMANCE ) { PerformanceStats . printStats ( ) ; } return context . getResolved ( ) ; } private List < CodeResolver > getResolvers ( ) { if ( fResolvers == null ) { fResolvers = new ArrayList < CodeResolver > ( ) ; IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; List < IConfigurationElement > elements = new ArrayList < IConfigurationElement > ( Arrays . asList ( registry . getConfigurationElementsFor ( RubyCore . PLUGIN_ID , EXTENSION_POINT ) ) ) ; sortParticipants ( elements ) ; for ( IConfigurationElement configurationElement : elements ) { try { CodeResolver resolver = ( CodeResolver ) configurationElement . createExecutableExtension ( "" ) ; fResolvers . add ( resolver ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } return fResolvers ; } private void sortParticipants ( List < IConfigurationElement > group ) { Collections . sort ( group , new Comparator < IConfigurationElement > ( ) { public int compare ( IConfigurationElement a , IConfigurationElement b ) { if ( a == b ) return ; String id = a . getAttribute ( "" ) ; if ( id == null ) return - ; IConfigurationElement [ ] requiredElements = b . getChildren ( "" ) ; for ( int i = , length = requiredElements . length ; i < length ; i ++ ) { IConfigurationElement required = requiredElements [ i ] ; if ( id . equals ( required . getAttribute ( "" ) ) ) return ; } return - ; } } ) ; } } package org . rubypeople . rdt . internal . codeassist ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; 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 org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . YieldNode ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . parser . StaticScope ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . core . CompletionRequestor ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . CollectingSearchRequestor ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . LogicalType ; import org . rubypeople . rdt . internal . core . RubyConstant ; import org . rubypeople . rdt . internal . core . RubyElement ; import org . rubypeople . rdt . internal . core . RubyType ; import org . rubypeople . rdt . internal . core . SourceElementParser ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . search . BasicSearchEngine ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . core . util . Util ; import org . rubypeople . rdt . internal . ti . BasicTypeGuess ; import org . rubypeople . rdt . internal . ti . ITypeGuess ; import org . rubypeople . rdt . internal . ti . ITypeInferrer ; import org . rubypeople . rdt . internal . ti . util . AttributeLocator ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ti . util . ScopedNodeLocator ; public class CompletionEngine { private static final String OBJECT = "" ; private static final String CONSTRUCTOR_INVOKE_NAME = "" ; private static final String CONSTRUCTOR_DEFINITION_NAME = "" ; private CompletionRequestor fRequestor ; private CompletionContext fContext ; private Set < IType > fVisitedTypes ; private IType fOriginalType ; public CompletionEngine ( CompletionRequestor requestor ) { this . fRequestor = requestor ; } public void complete ( IRubyScript script , int offset ) throws RubyModelException { this . fRequestor . beginReporting ( ) ; fContext = new CompletionContext ( script , offset ) ; if ( fContext . inComment ( ) ) { this . fRequestor . endReporting ( ) ; fContext = null ; return ; } if ( fContext . emptyPrefix ( ) ) { suggestMethodsForEnclosingType ( script ) ; getDocumentsRubyElementsInScope ( ) ; suggestGlobals ( ) ; } else { if ( fContext . isDoubleSemiColon ( ) ) { String prefix = fContext . getFullPrefix ( ) ; String typeName = prefix . substring ( , prefix . lastIndexOf ( "" ) ) ; RubyElementRequestor requestor = new RubyElementRequestor ( script ) ; Map < String , CompletionProposal > proposals = new HashMap < String , CompletionProposal > ( ) ; if ( fContext . isBroken ( ) ) { Map < IMethod , String > astMethods = addASTProposals ( typeName ) ; for ( IMethod method : astMethods . keySet ( ) ) { if ( ! method . isSingleton ( ) ) continue ; CompletionProposal proposal = suggestMethod ( method , astMethods . get ( method ) , ) ; if ( proposal == null ) continue ; proposals . put ( proposal . getName ( ) , proposal ) ; } addASTTypeConstants ( typeName ) ; } IType [ ] types = requestor . findType ( typeName ) ; for ( int i = ; i < types . length ; i ++ ) { IType type = types [ i ] ; proposals . putAll ( suggestTypesConstants ( type ) ) ; proposals . putAll ( suggestNestedTypes ( type ) ) ; proposals . putAll ( suggestMethods ( , type , false ) ) ; } List < CompletionProposal > list = new ArrayList < CompletionProposal > ( proposals . values ( ) ) ; Collections . sort ( list , new CompletionProposalComparator ( ) ) ; for ( CompletionProposal proposal : list ) { if ( proposal . getCompletion ( ) . startsWith ( fContext . getPartialPrefix ( ) ) ) fRequestor . accept ( proposal ) ; } this . fRequestor . endReporting ( ) ; fContext = null ; return ; } if ( fContext . isConstant ( ) ) { suggestTypeNames ( ) ; suggestConstantNames ( ) ; return ; } if ( fContext . isGlobal ( ) ) { suggestGlobals ( ) ; return ; } if ( fContext . isInstanceVariable ( ) ) { suggestInstanceVariables ( ) ; return ; } if ( fContext . isClassVariable ( ) ) { suggestClassVariables ( ) ; return ; } if ( fContext . isInstanceOrClassVariable ( ) ) { suggestClassAndInstanceVariables ( ) ; return ; } if ( fContext . isExplicitMethodInvokation ( ) ) { ITypeInferrer inferrer = RubyCore . getTypeInferrer ( ) ; Collection < ITypeGuess > guesses = inferrer . infer ( fContext . getCorrectedSource ( ) , fContext . getOffset ( ) ) ; if ( guesses . isEmpty ( ) ) { guesses = new ArrayList < ITypeGuess > ( ) ; guesses . add ( new BasicTypeGuess ( OBJECT , ) ) ; } List < CompletionProposal > list = new ArrayList < CompletionProposal > ( ) ; RubyElementRequestor requestor = new RubyElementRequestor ( script ) ; for ( ITypeGuess guess : guesses ) { final String name = guess . getType ( ) ; if ( fContext . isBroken ( ) ) { Map < IMethod , String > astMethods = addASTProposals ( name ) ; for ( IMethod method : astMethods . keySet ( ) ) { CompletionProposal proposal = suggestMethod ( method , astMethods . get ( method ) , ) ; if ( proposal == null ) continue ; list . add ( proposal ) ; } } IType [ ] types = requestor . findType ( name ) ; if ( types == null || types . length == ) { types = requestor . findType ( OBJECT ) ; } Map < String , CompletionProposal > mapAll = new HashMap < String , CompletionProposal > ( ) ; if ( types != null && types . length > ) { LogicalType type = new LogicalType ( types ) ; mapAll . putAll ( suggestMethods ( guess . getConfidence ( ) , type , true ) ) ; } if ( ! mapAll . containsKey ( "" ) && fContext . fullPrefixIsConstant ( ) && "" . startsWith ( fContext . getPartialPrefix ( ) ) ) { CompletionProposal proposal = new CompletionProposal ( CompletionProposal . METHOD_REF , "" , ) ; proposal . setDeclaringType ( name ) ; proposal . setFlags ( Flags . AccPublic | Flags . AccStatic ) ; proposal . setReplaceRange ( fContext . getReplaceStart ( ) , fContext . getReplaceStart ( ) + ) ; proposal . setName ( "" ) ; mapAll . put ( "" , proposal ) ; } list . addAll ( mapAll . values ( ) ) ; } if ( guesses . size ( ) > || ( guesses . size ( ) == && guesses . iterator ( ) . next ( ) . getType ( ) . equals ( OBJECT ) ) ) { list . addAll ( suggestAllMethodsMatchingPrefix ( script ) ) ; } Collections . sort ( list , new CompletionProposalComparator ( ) ) ; for ( CompletionProposal proposal : list ) { fRequestor . accept ( proposal ) ; } } else { if ( fContext . isMethodInvokationOrLocal ( ) ) { suggestMethodsForEnclosingType ( script ) ; List < CompletionProposal > proposals = suggestAllMethodsMatchingPrefix ( script ) ; for ( CompletionProposal proposal : proposals ) { fRequestor . accept ( proposal ) ; } } getDocumentsRubyElementsInScope ( ) ; } } this . fRequestor . endReporting ( ) ; fContext = null ; } private void suggestClassAndInstanceVariables ( ) { addTypesVariables ( getEnclosingTypeNode ( ) ) ; } private void suggestInstanceVariables ( ) { addTypesVariables ( getEnclosingTypeNode ( ) ) ; } private void suggestClassVariables ( ) { addTypesVariables ( getEnclosingTypeNode ( ) ) ; } private Node getEnclosingTypeNode ( ) { return ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( getRootNode ( ) , fContext . getOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ClassNode || node instanceof ModuleNode ) ; } } ) ; } private void addASTTypeConstants ( String typeName ) { Collection < Node > typeNodes = getASTTypeNodesFromName ( typeName ) ; for ( Node typeNode : typeNodes ) { List < Node > constants = ScopedNodeLocator . Instance ( ) . findNodesInScope ( typeNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ConstDeclNode ) || ( node instanceof ClassNode ) || ( node instanceof ModuleNode ) ; } } ) ; Set < String > fields = new HashSet < String > ( ) ; if ( constants != null ) { for ( Node varNode : constants ) { if ( varNode . equals ( typeNode ) ) continue ; Node spanner = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( typeNode , varNode . getPosition ( ) . getStartOffset ( ) - , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof ClassNode || node instanceof ModuleNode ; } } ) ; if ( spanner == null || ! spanner . equals ( typeNode ) ) continue ; String name = ASTUtil . getNameReflectively ( varNode ) ; if ( ! fContext . prefixStartsWith ( name ) ) continue ; fields . add ( name ) ; } } for ( String field : fields ) { CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , CompletionProposal . CONSTANT_REF , field ) ; proposal . setDeclaringType ( typeName ) ; proposal . setName ( field ) ; fRequestor . accept ( proposal ) ; } } } private Map < IMethod , String > addASTProposals ( final String name ) { Map < IMethod , String > list = new HashMap < IMethod , String > ( ) ; Collection < Node > typeNodes = getASTTypeNodesFromName ( name ) ; for ( Node typeNode : typeNodes ) { Collection < IMethod > astMethodsInScope = addASTMethodsInScope ( typeNode , name ) ; for ( IMethod method : astMethodsInScope ) { list . put ( method , name ) ; } } ASTSourceRequestor srcRequestor = new ASTSourceRequestor ( ) ; SourceElementParser srcParser = new SourceElementParser ( srcRequestor ) ; srcParser . acceptNode ( getRootNode ( ) ) ; List < String > mixins = srcRequestor . getMixins ( name ) ; for ( String mixin : mixins ) { list . putAll ( srcRequestor . getMethods ( mixin ) ) ; } return list ; } private Collection < Node > getASTTypeNodesFromName ( final String name ) { final Node rootNode = getRootNode ( ) ; return ScopedNodeLocator . Instance ( ) . findNodesInScope ( rootNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( ! ( node instanceof ModuleNode ) && ! ( node instanceof ClassNode ) ) return false ; return ASTUtil . getFullyQualifiedTypeName ( rootNode , node ) . equals ( name ) ; } } ) ; } private Collection < IMethod > addASTMethodsInScope ( Node typeNode , String name ) { List < IMethod > list = new ArrayList < IMethod > ( ) ; if ( typeNode == null ) return list ; List < Node > methods = ScopedNodeLocator . Instance ( ) . findNodesInScope ( typeNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof DefnNode ) || ( node instanceof DefsNode ) ; } } ) ; for ( Node methodNode : methods ) { Node scoping = findNearestScope ( typeNode , methodNode . getPosition ( ) . getStartOffset ( ) - ) ; if ( scoping == null || ! scoping . equals ( typeNode ) ) continue ; MethodDefNode methodDef = ( MethodDefNode ) methodNode ; NodeMethod method = new NodeMethod ( methodDef , fContext . getScript ( ) ) ; list . add ( method ) ; } return list ; } private Map < String , CompletionProposal > suggestTypesConstants ( IType type ) throws RubyModelException { Map < String , CompletionProposal > proposals = new HashMap < String , CompletionProposal > ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . CONSTANT , "" , IRubySearchConstants . DECLARATIONS , SearchPattern . R_PATTERN_MATCH ) ; IRubySearchScope scope = BasicSearchEngine . createRubySearchScope ( new IRubyElement [ ] { type } ) ; List < SearchMatch > results = search ( pattern , scope ) ; for ( SearchMatch match : results ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; if ( element . getElementType ( ) != IRubyElement . CONSTANT ) continue ; CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , CompletionProposal . CONSTANT_REF , element . getElementName ( ) , element ) ; proposal . setType ( type . getFullyQualifiedName ( ) ) ; proposal . setName ( element . getElementName ( ) ) ; proposals . put ( element . getElementName ( ) , proposal ) ; } return proposals ; } private Map < String , CompletionProposal > suggestNestedTypes ( IType type ) throws RubyModelException { Map < String , CompletionProposal > proposals = new HashMap < String , CompletionProposal > ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . TYPE , "" , IRubySearchConstants . DECLARATIONS , SearchPattern . R_PATTERN_MATCH ) ; IRubySearchScope scope = BasicSearchEngine . createRubySearchScope ( new IRubyElement [ ] { type } ) ; List < SearchMatch > results = search ( pattern , scope ) ; for ( SearchMatch match : results ) { IType aType = ( IType ) match . getElement ( ) ; String fullname = aType . getFullyQualifiedName ( ) ; if ( fullname . equals ( type . getFullyQualifiedName ( ) ) ) continue ; if ( ! fullname . startsWith ( type . getFullyQualifiedName ( ) ) ) continue ; String [ ] parts = Util . getTypeNameParts ( fullname ) ; if ( parts . length != Util . getTypeNameParts ( type . getFullyQualifiedName ( ) ) . length + ) continue ; CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , CompletionProposal . TYPE_REF , aType . getElementName ( ) ) ; proposal . setType ( aType . getFullyQualifiedName ( ) ) ; proposal . setName ( aType . getElementName ( ) ) ; proposals . put ( aType . getElementName ( ) , proposal ) ; } return proposals ; } private List < CompletionProposal > suggestAllMethodsMatchingPrefix ( IRubyScript script ) { List < CompletionProposal > list = new ArrayList < CompletionProposal > ( ) ; if ( fContext . getPartialPrefix ( ) == null || fContext . getPartialPrefix ( ) . trim ( ) . length ( ) == ) return list ; IRubySearchScope scope = BasicSearchEngine . createRubySearchScope ( new IRubyElement [ ] { script . getRubyProject ( ) } ) ; SearchParticipant participant = BasicSearchEngine . getDefaultSearchParticipant ( ) ; CollectingSearchRequestor searchRequestor = new CollectingSearchRequestor ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . METHOD , fContext . getPartialPrefix ( ) , IRubySearchConstants . DECLARATIONS , SearchPattern . R_PREFIX_MATCH ) ; try { new BasicSearchEngine ( ) . search ( pattern , new SearchParticipant [ ] { participant } , scope , searchRequestor , null ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } List < SearchMatch > matches = searchRequestor . getResults ( ) ; for ( SearchMatch match : matches ) { IMethod element = ( IMethod ) match . getElement ( ) ; IType type = element . getDeclaringType ( ) ; String typeName = "" ; if ( type != null ) typeName = type . getElementName ( ) ; CompletionProposal proposal = suggestMethod ( element , typeName , ) ; if ( proposal != null ) { list . add ( proposal ) ; } } return list ; } private void suggestMethodsForEnclosingType ( IRubyScript script ) throws RubyModelException { Object thing = script . getElementAt ( fContext . getOffset ( ) ) ; IMember element = null ; if ( thing instanceof IMember ) { element = ( IMember ) thing ; } boolean includeInstance = ! fContext . inTypeDefinition ( ) ; IType [ ] types ; if ( element == null ) { RubyElementRequestor requestor = new RubyElementRequestor ( script ) ; IType [ ] tmpTypes = requestor . findType ( OBJECT ) ; List < IType > filtered = new ArrayList < IType > ( ) ; for ( int i = ; i < tmpTypes . length ; i ++ ) { if ( ! tmpTypes [ i ] . getFullyQualifiedName ( ) . equals ( OBJECT ) ) continue ; filtered . add ( tmpTypes [ i ] ) ; } types = filtered . toArray ( new IType [ filtered . size ( ) ] ) ; includeInstance = false ; } else if ( element instanceof IType ) { IType type = ( IType ) element ; RubyElementRequestor requestor = new RubyElementRequestor ( script ) ; types = requestor . findType ( type . getFullyQualifiedName ( ) ) ; } else { types = new IType [ ] { element . getDeclaringType ( ) } ; } if ( types == null || types . length < ) return ; Map < String , CompletionProposal > map = new HashMap < String , CompletionProposal > ( ) ; for ( int i = ; i < types . length ; i ++ ) { if ( types [ i ] == null ) continue ; map . putAll ( suggestMethods ( , types [ i ] , includeInstance ) ) ; } List < CompletionProposal > list = sort ( map ) ; for ( CompletionProposal proposal : list ) { fRequestor . accept ( proposal ) ; } } private Map < String , CompletionProposal > suggestMethods ( int confidence , IType type , boolean includeInstanceMethods ) throws RubyModelException { if ( fVisitedTypes == null ) fVisitedTypes = new HashSet < IType > ( ) ; fOriginalType = type ; Map < String , CompletionProposal > proposals = new HashMap < String , CompletionProposal > ( ) ; IType [ ] superTypes = getSuperTypes ( type ) ; for ( int j = ; j < superTypes . length ; j ++ ) { IType currentType = superTypes [ j ] ; if ( fVisitedTypes . contains ( currentType ) ) continue ; fVisitedTypes . add ( currentType ) ; IMethod [ ] methods = currentType . getMethods ( ) ; if ( methods == null ) continue ; for ( int k = ; k < methods . length ; k ++ ) { if ( methods [ k ] == null ) continue ; CompletionProposal proposal = suggestMethod ( methods [ k ] , currentType . getElementName ( ) , confidence ) ; if ( proposal != null && ! proposals . containsKey ( proposal . getName ( ) ) ) { proposals . put ( proposal . getName ( ) , proposal ) ; } } } fOriginalType = null ; fVisitedTypes . clear ( ) ; return proposals ; } private IType [ ] getSuperTypes ( IType type ) throws RubyModelException { ITypeHierarchy hierarchy = type . newSupertypeHierarchy ( new NullProgressMonitor ( ) ) ; if ( hierarchy == null ) return new IType [ ] { type } ; IType [ ] superTypes = hierarchy . getAllSupertypes ( type ) ; if ( superTypes == null || superTypes . length == ) return new IType [ ] { type } ; IType [ ] modules = hierarchy . getAllSuperModules ( type ) ; if ( modules == null || modules . length == ) { int length = superTypes . length ; IType [ ] all = new IType [ length + ] ; all [ ] = type ; System . arraycopy ( superTypes , , all , , length ) ; return all ; } int length = superTypes . length + modules . length ; IType [ ] all = new IType [ length + ] ; all [ ] = type ; System . arraycopy ( superTypes , , all , , superTypes . length ) ; System . arraycopy ( modules , , all , superTypes . length + , modules . length ) ; return all ; } private List < CompletionProposal > sort ( Map < String , CompletionProposal > proposals ) { List < CompletionProposal > list = new ArrayList < CompletionProposal > ( proposals . values ( ) ) ; Collections . sort ( list , new CompletionProposalComparator ( ) ) ; return list ; } private void suggestGlobals ( ) { SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . GLOBAL , "" , IRubySearchConstants . DECLARATIONS , SearchPattern . R_PATTERN_MATCH ) ; IRubySearchScope scope = BasicSearchEngine . createRubySearchScope ( new IRubyElement [ ] { fContext . getScript ( ) . getRubyProject ( ) } ) ; List < SearchMatch > results = search ( pattern , scope ) ; Set < String > names = new HashSet < String > ( ) ; for ( SearchMatch match : results ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; String name = element . getElementName ( ) ; if ( names . contains ( name ) ) continue ; names . add ( name ) ; CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , CompletionProposal . GLOBAL_REF , name , element ) ; proposal . setType ( name ) ; fRequestor . accept ( proposal ) ; } } private void suggestTypeNames ( ) { SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . TYPE , fContext . getPartialPrefix ( ) , IRubySearchConstants . DECLARATIONS , SearchPattern . R_CAMELCASE_MATCH ) ; List < SearchMatch > results = search ( pattern , BasicSearchEngine . createWorkspaceScope ( ) ) ; Set < String > names = new HashSet < String > ( ) ; for ( SearchMatch match : results ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; String name = element . getElementName ( ) ; if ( names . contains ( name ) ) continue ; names . add ( name ) ; CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , CompletionProposal . TYPE_REF , name , element ) ; proposal . setType ( name ) ; fRequestor . accept ( proposal ) ; } } private List < SearchMatch > search ( SearchPattern pattern , IRubySearchScope scope ) { BasicSearchEngine engine = new BasicSearchEngine ( ) ; SearchParticipant [ ] participants = new SearchParticipant [ ] { BasicSearchEngine . getDefaultSearchParticipant ( ) } ; CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; try { engine . search ( pattern , participants , scope , requestor , new NullProgressMonitor ( ) ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } return requestor . getResults ( ) ; } private CompletionProposal createProposal ( int replaceStart , int type , String name ) { return createProposal ( replaceStart , type , name , , null ) ; } private CompletionProposal createProposal ( int replaceStart , int type , String name , IRubyElement element ) { return createProposal ( replaceStart , type , name , , element ) ; } private CompletionProposal createProposal ( int replaceStart , int type , String name , int confidence , IRubyElement element ) { CompletionProposal proposal = new CompletionProposal ( type , name , confidence ) ; proposal . setReplaceRange ( replaceStart , replaceStart + name . length ( ) ) ; proposal . setElement ( element ) ; return proposal ; } private void suggestConstantNames ( ) { SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . CONSTANT , fContext . getPartialPrefix ( ) + "" , IRubySearchConstants . DECLARATIONS , SearchPattern . R_PATTERN_MATCH ) ; IRubySearchScope scope = BasicSearchEngine . createRubySearchScope ( new IRubyElement [ ] { fContext . getScript ( ) } ) ; List < SearchMatch > results = search ( pattern , scope ) ; for ( SearchMatch match : results ) { IRubyElement element = ( IRubyElement ) match . getElement ( ) ; String name = element . getElementName ( ) ; CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , CompletionProposal . CONSTANT_REF , name , element ) ; proposal . setType ( name ) ; fRequestor . accept ( proposal ) ; } if ( "" . startsWith ( fContext . getPartialPrefix ( ) ) ) { IRubyElement element = new RubyConstant ( null , "" ) ; CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , CompletionProposal . CONSTANT_REF , "" , element ) ; proposal . setType ( "" ) ; fRequestor . accept ( proposal ) ; } } private CompletionProposal suggestMethod ( IMethod method , String typeName , int confidence ) { try { int start = fContext . getReplaceStart ( ) ; String name = method . getElementName ( ) ; int flags = Flags . AccDefault ; if ( method . isSingleton ( ) ) { flags |= Flags . AccStatic ; if ( method . isConstructor ( ) ) name = CONSTRUCTOR_INVOKE_NAME ; else { if ( name . startsWith ( typeName ) ) { name = name . substring ( typeName . length ( ) + ) ; } } } else { if ( fContext . fullPrefixIsConstant ( ) ) return null ; } if ( ! fContext . prefixStartsWith ( name ) ) return null ; try { switch ( method . getVisibility ( ) ) { case IMethod . PRIVATE : flags |= Flags . AccPrivate ; if ( fOriginalType != null && ! fOriginalType . getElementName ( ) . equals ( typeName ) ) return null ; if ( fContext . hasReceiver ( ) ) return null ; break ; case IMethod . PUBLIC : flags |= Flags . AccPublic ; break ; case IMethod . PROTECTED : flags |= Flags . AccProtected ; break ; default : break ; } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; flags |= Flags . AccPublic ; } CompletionProposal proposal = createProposal ( start , CompletionProposal . METHOD_REF , name , confidence , method ) ; proposal . setReplaceRange ( start , start + name . length ( ) ) ; proposal . setFlags ( flags ) ; proposal . setName ( name ) ; IType declaringType = method . getDeclaringType ( ) ; String declaringName = typeName ; if ( declaringType != null ) declaringName = declaringType . getFullyQualifiedName ( ) ; proposal . setDeclaringType ( declaringName ) ; return proposal ; } catch ( RuntimeException e ) { RubyCore . log ( e ) ; return null ; } } private void getDocumentsRubyElementsInScope ( ) { Collection < String > variables = addVariablesinScope ( getScope ( findNearestScope ( getRootNode ( ) , fContext . getOffset ( ) ) ) ) ; for ( final String variable : variables ) { if ( variable . equals ( fContext . getPartialPrefix ( ) ) ) { if ( onlyLocalVarReferenceIsInvokation ( ) ) continue ; } CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , getCompletionProposalType ( variable ) , variable ) ; proposal . setName ( variable ) ; fRequestor . accept ( proposal ) ; } Collection < IMethod > methods = addASTMethodsInScope ( getEnclosingTypeOrRootNode ( ) , "" ) ; for ( IMethod method : methods ) { CompletionProposal proposal = suggestMethod ( method , "" , ) ; if ( proposal == null ) continue ; fRequestor . accept ( proposal ) ; } getMembersAvailableInsideType ( getEnclosingTypeNode ( ) ) ; } private boolean onlyLocalVarReferenceIsInvokation ( ) { List < Node > localVarNodes = ScopedNodeLocator . Instance ( ) . findNodesInScope ( getRootNode ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( ! ( node instanceof LocalVarNode || node instanceof LocalAsgnNode ) ) return false ; INameNode nameNode = ( INameNode ) node ; return nameNode . getName ( ) . equals ( fContext . getPartialPrefix ( ) ) ; } } ) ; return localVarNodes != null && localVarNodes . size ( ) == ; } private Node getEnclosingTypeOrRootNode ( ) { Node result = getEnclosingTypeNode ( ) ; if ( result != null ) return result ; return getRootNode ( ) ; } private Node getRootNode ( ) { try { return fContext . getRootNode ( ) ; } catch ( SyntaxException se ) { RubyCore . log ( se ) ; } return null ; } private Node findNearestScope ( Node scopeNode , int offset ) { if ( offset == - ) return scopeNode ; Node scope = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( scopeNode , offset , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof DefnNode || node instanceof DefsNode || node instanceof ClassNode || node instanceof ModuleNode || node instanceof RootNode || node instanceof IterNode ) ; } } ) ; if ( scope == null ) return scopeNode ; return scope ; } private Set < String > addVariablesinScope ( StaticScope scope ) { Set < String > matches = new HashSet < String > ( ) ; if ( scope == null ) return matches ; for ( String local : scope . getVariables ( ) ) { if ( ! fContext . prefixStartsWith ( local ) ) continue ; matches . add ( local ) ; } matches . addAll ( addVariablesinScope ( scope . getEnclosingScope ( ) ) ) ; return matches ; } private StaticScope getScope ( Node enclosingNode ) { if ( enclosingNode == null ) return ( ( RootNode ) getRootNode ( ) ) . getStaticScope ( ) ; if ( enclosingNode instanceof RootNode ) { RootNode root = ( RootNode ) enclosingNode ; return root . getStaticScope ( ) ; } try { Method getScopeMethod = enclosingNode . getClass ( ) . getMethod ( "" , new Class [ ] { } ) ; Object scope = getScopeMethod . invoke ( enclosingNode , new Object [ ] ) ; return ( StaticScope ) scope ; } catch ( Exception e ) { return null ; } } private void getMembersAvailableInsideType ( Node typeNode ) { if ( typeNode == null ) return ; String typeName = getTypeName ( typeNode ) ; if ( typeName == null ) return ; List < Node > superclassNodes = getSuperclassNodes ( typeNode ) ; for ( Node superclassNode : superclassNodes ) { getMembersAvailableInsideType ( superclassNode ) ; } List < String > mixinNames = getIncludedMixinNames ( typeName ) ; for ( String mixinName : mixinNames ) { List < Node > mixinDeclarations = getTypeDeclarationNodes ( mixinName ) ; for ( Node mixinDeclaration : mixinDeclarations ) { getMembersAvailableInsideType ( mixinDeclaration ) ; } } List < Node > methodDefinitions = ScopedNodeLocator . Instance ( ) . findNodesInScope ( typeNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof DefnNode ) || ( node instanceof DefsNode ) ; } } ) ; for ( Node methodDefinition : methodDefinitions ) { String name = null ; if ( methodDefinition instanceof DefnNode ) { name = ( ( DefnNode ) methodDefinition ) . getName ( ) ; } if ( methodDefinition instanceof DefsNode ) { name = ( ( DefsNode ) methodDefinition ) . getName ( ) ; } if ( ! fContext . prefixStartsWith ( name ) ) continue ; NodeMethod method = new NodeMethod ( ( MethodDefNode ) methodDefinition , fContext . getScript ( ) ) ; suggestMethod ( method , typeName , ) ; } addTypesVariables ( typeNode ) ; } private String getTypeName ( Node typeNode ) { String typeName = null ; if ( typeNode instanceof ClassNode ) { typeName = ( ( Colon2Node ) ( ( ClassNode ) typeNode ) . getCPath ( ) ) . getName ( ) ; } if ( typeNode instanceof ModuleNode ) { typeName = ( ( Colon2Node ) ( ( ModuleNode ) typeNode ) . getCPath ( ) ) . getName ( ) ; } return typeName ; } private void addTypesVariables ( Node typeNode ) { if ( typeNode == null ) return ; List < Node > instanceAndClassVars = ScopedNodeLocator . Instance ( ) . findNodesInScope ( typeNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ConstDeclNode || node instanceof InstVarNode || node instanceof InstAsgnNode || node instanceof ClassVarNode || node instanceof ClassVarDeclNode || node instanceof ClassVarAsgnNode ) ; } } ) ; Set < String > fields = new HashSet < String > ( ) ; if ( instanceAndClassVars != null ) { for ( Node varNode : instanceAndClassVars ) { String name = ASTUtil . getNameReflectively ( varNode ) ; if ( name . equals ( fContext . getPartialPrefix ( ) ) ) { if ( varNode . getPosition ( ) . getStartOffset ( ) <= fContext . getOffset ( ) && varNode . getPosition ( ) . getEndOffset ( ) >= fContext . getOffset ( ) ) { continue ; } } fields . add ( name ) ; } } fields . addAll ( new AttributeLocator ( ) . findInstanceAttributesInScope ( typeNode ) ) ; for ( String field : fields ) { if ( ! fContext . prefixStartsWith ( field ) ) continue ; CompletionProposal proposal = createProposal ( fContext . getReplaceStart ( ) , getCompletionProposalType ( field ) , field ) ; proposal . setName ( field ) ; fRequestor . accept ( proposal ) ; } } private int getCompletionProposalType ( String field ) { if ( field == null ) return CompletionProposal . CONSTANT_REF ; if ( field . startsWith ( "" ) ) return CompletionProposal . CLASS_VARIABLE_REF ; if ( field . startsWith ( "" ) ) return CompletionProposal . INSTANCE_VARIABLE_REF ; if ( field . startsWith ( "" ) ) return CompletionProposal . GLOBAL_REF ; if ( Character . isUpperCase ( field . charAt ( ) ) ) return CompletionProposal . CONSTANT_REF ; return CompletionProposal . LOCAL_VARIABLE_REF ; } private List < Node > getSuperclassNodes ( Node typeNode ) { if ( typeNode instanceof ClassNode ) { Node superNode = ( ( ClassNode ) typeNode ) . getSuperNode ( ) ; if ( superNode instanceof ConstNode ) { String superclassName = ( ( ConstNode ) superNode ) . getName ( ) ; return getTypeDeclarationNodes ( superclassName ) ; } } return new ArrayList < Node > ( ) ; } private List < Node > getTypeDeclarationNodes ( String typeName ) { RubyElementRequestor requestor = new RubyElementRequestor ( fContext . getScript ( ) ) ; IType [ ] types = requestor . findType ( typeName ) ; if ( types == null || types . length == ) return new ArrayList < Node > ( ) ; IType type = types [ ] ; try { if ( type instanceof RubyType ) { RubyType rubyType = ( RubyType ) type ; String source = rubyType . getSource ( ) ; if ( source == null ) return new ArrayList < Node > ( ) ; source = source . replace ( '' , '' ) ; Node rootNode = null ; try { rootNode = ( new RubyParser ( ) ) . parse ( type . getRubyScript ( ) . getElementName ( ) , source ) . getAST ( ) ; } catch ( Exception e ) { RubyCore . log ( e ) ; } if ( rootNode == null ) { return new ArrayList < Node > ( ) ; } return ScopedNodeLocator . Instance ( ) . findNodesInScope ( rootNode , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ( node instanceof ClassNode ) || ( node instanceof ModuleNode ) ; } } ) ; } } catch ( RubyModelException rme ) { rme . printStackTrace ( ) ; } return new ArrayList < Node > ( ) ; } private List < String > getIncludedMixinNames ( String typeName ) { IType rubyType = new RubyType ( ( RubyElement ) fContext . getScript ( ) , typeName ) ; try { String [ ] includedModuleNames = rubyType . getIncludedModuleNames ( ) ; if ( includedModuleNames != null ) { return Arrays . asList ( rubyType . getIncludedModuleNames ( ) ) ; } return new ArrayList < String > ( ) ; } catch ( RubyModelException e ) { return new ArrayList < String > ( ) ; } } private class NodeMethod implements IMethod { private MethodDefNode node ; private IRubyScript fScript ; public NodeMethod ( MethodDefNode methodDefinition , IRubyScript script ) { this . node = methodDefinition ; this . fScript = script ; } public String [ ] getParameterNames ( ) throws RubyModelException { return ASTUtil . getArgs ( node . getArgsNode ( ) , node . getScope ( ) ) ; } public int getNumberOfParameters ( ) throws RubyModelException { return getParameterNames ( ) . length ; } public int getVisibility ( ) throws RubyModelException { return IMethod . PUBLIC ; } public boolean isConstructor ( ) { return node . getName ( ) . equals ( CONSTRUCTOR_DEFINITION_NAME ) ; } public boolean isSingleton ( ) { return isConstructor ( ) || node instanceof DefsNode ; } public boolean isSimilar ( IMethod method ) { return false ; } public boolean exists ( ) { return false ; } public IRubyElement getAncestor ( int ancestorType ) { return null ; } public IResource getCorrespondingResource ( ) throws RubyModelException { return null ; } public String getElementName ( ) { return node . getName ( ) ; } public int getElementType ( ) { return IRubyElement . METHOD ; } public IOpenable getOpenable ( ) { return fScript ; } public IRubyElement getParent ( ) { return null ; } public IPath getPath ( ) { return null ; } public IRubyElement getPrimaryElement ( ) { return null ; } public IResource getResource ( ) { return null ; } public IRubyModel getRubyModel ( ) { return null ; } public IRubyProject getRubyProject ( ) { return null ; } public IResource getUnderlyingResource ( ) throws RubyModelException { return null ; } public boolean isReadOnly ( ) { return false ; } public boolean isStructureKnown ( ) throws RubyModelException { return false ; } public boolean isType ( int type ) { return type == IRubyElement . METHOD ; } public Object getAdapter ( Class adapter ) { return null ; } public IType getDeclaringType ( ) { return null ; } public ISourceRange getNameRange ( ) throws RubyModelException { return null ; } public IRubyScript getRubyScript ( ) { return fScript ; } public IType getType ( String name , int occurrenceCount ) { return null ; } public String getSource ( ) throws RubyModelException { return null ; } public ISourceRange getSourceRange ( ) throws RubyModelException { return null ; } public IRubyElement [ ] getChildren ( ) throws RubyModelException { return null ; } public boolean hasChildren ( ) throws RubyModelException { return false ; } public String getHandleIdentifier ( ) { return null ; } public boolean isPrivate ( ) throws RubyModelException { return false ; } public boolean isProtected ( ) throws RubyModelException { return false ; } public boolean isPublic ( ) throws RubyModelException { return false ; } public String [ ] getBlockParameters ( ) throws RubyModelException { final Set < String > vars = new HashSet < String > ( ) ; InOrderVisitor visitor = new InOrderVisitor ( ) { private String typeName ; @ Override public Object visitClassNode ( ClassNode iVisited ) { typeName = ASTUtil . getFullyQualifiedName ( iVisited . getCPath ( ) ) ; return super . visitClassNode ( iVisited ) ; } @ Override public Object visitModuleNode ( ModuleNode iVisited ) { typeName = ASTUtil . getFullyQualifiedName ( iVisited . getCPath ( ) ) ; return super . visitModuleNode ( iVisited ) ; } @ Override public Object visitYieldNode ( YieldNode iVisited ) { Node argsNode = iVisited . getArgsNode ( ) ; if ( argsNode instanceof LocalVarNode ) { vars . add ( ( ( LocalVarNode ) argsNode ) . getName ( ) ) ; } else if ( argsNode instanceof SelfNode ) { String name = null ; if ( typeName == null ) { name = "" ; } else { name = typeName . toLowerCase ( ) ; if ( name . indexOf ( "" ) > - ) { name = name . substring ( name . lastIndexOf ( "" ) + ) ; } } vars . add ( name ) ; } return super . visitYieldNode ( iVisited ) ; } } ; this . node . accept ( visitor ) ; return vars . toArray ( new String [ vars . size ( ) ] ) ; } } } package org . rubypeople . rdt . internal . core ; public class RubyFieldElementInfo extends MemberElementInfo { protected String fieldName ; protected String typeName ; public String getName ( ) { return this . fieldName ; } public String getTypeName ( ) { return this . typeName ; } protected void setTypeName ( String typeName ) { this . typeName = typeName ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class ERBScript extends RubyScript implements IRubyScript { public ERBScript ( SourceFolder parent , String name , WorkingCopyOwner owner ) { super ( parent , name , owner ) ; } @ Override public IRubyElement getElementAt ( int position ) throws RubyModelException { getElementInfo ( ) ; return super . getElementAt ( position ) ; } @ Override protected char [ ] getCharacters ( IProgressMonitor pm , RubyScriptElementInfo unitInfo ) throws RubyModelException { char [ ] cs = super . getCharacters ( pm , unitInfo ) ; return Util . replaceNonRubyCodeWithWhitespace ( new String ( cs ) ) ; } protected IStatus validateRubyScript ( IResource resource ) { ISourceFolderRoot root = getSourceFolderRoot ( ) ; if ( resource != null ) { char [ ] [ ] inclusionPatterns = ( ( SourceFolderRoot ) root ) . fullInclusionPatternChars ( ) ; char [ ] [ ] exclusionPatterns = ( ( SourceFolderRoot ) root ) . fullExclusionPatternChars ( ) ; if ( Util . isExcluded ( resource , inclusionPatterns , exclusionPatterns ) ) return new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_NOT_ON_CLASSPATH , this ) ; if ( ! resource . isAccessible ( ) ) return new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST , this ) ; } if ( name == null ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , Messages . bind ( Messages . convention_unit_nullName ) , null ) ; } if ( ! org . rubypeople . rdt . internal . core . util . Util . isERBLikeFileName ( name ) ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , Messages . bind ( Messages . convention_unit_notERBName ) , null ) ; } IStatus status = ResourcesPlugin . getWorkspace ( ) . validateName ( name , IResource . FILE ) ; if ( ! status . isOK ( ) ) { return status ; } return RubyModelStatus . VERIFIED_OK ; } @ Override public String getSource ( ) throws RubyModelException { String src = super . getSource ( ) ; return replaceNonRubyCodeWithWhitespace ( src ) ; } private String replaceNonRubyCodeWithWhitespace ( String source ) { return new String ( Util . replaceNonRubyCodeWithWhitespace ( source ) ) ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IResourceStatus ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . util . Messages ; public class RubyModelStatus extends Status implements IRubyModelStatus , IRubyModelStatusConstants , IResourceStatus { protected IRubyElement [ ] elements = new IRubyElement [ ] ; protected IPath path ; protected String string ; protected final static IStatus [ ] NO_CHILDREN = new IStatus [ ] { } ; protected IStatus [ ] children = NO_CHILDREN ; public static final IRubyModelStatus VERIFIED_OK = new RubyModelStatus ( OK , OK , Messages . bind ( Messages . status_OK ) ) ; public RubyModelStatus ( ) { super ( ERROR , RubyCore . PLUGIN_ID , , "" , null ) ; } public RubyModelStatus ( int code ) { super ( ERROR , RubyCore . PLUGIN_ID , code , "" , null ) ; this . elements = RubyElement . NO_ELEMENTS ; } public RubyModelStatus ( int code , IRubyElement [ ] elements ) { super ( ERROR , RubyCore . PLUGIN_ID , code , "" , null ) ; this . elements = elements ; this . path = null ; } public RubyModelStatus ( int code , String string ) { this ( ERROR , code , string ) ; } public RubyModelStatus ( int severity , int code , String string ) { super ( severity , RubyCore . PLUGIN_ID , code , "" , null ) ; this . elements = RubyElement . NO_ELEMENTS ; this . path = null ; this . string = string ; } public RubyModelStatus ( int code , Throwable throwable ) { super ( ERROR , RubyCore . PLUGIN_ID , code , "" , throwable ) ; this . elements = RubyElement . NO_ELEMENTS ; } public RubyModelStatus ( int code , IPath path ) { super ( ERROR , RubyCore . PLUGIN_ID , code , "" , null ) ; this . elements = RubyElement . NO_ELEMENTS ; this . path = path ; } public RubyModelStatus ( int code , IRubyElement element ) { this ( code , new IRubyElement [ ] { element } ) ; } public RubyModelStatus ( int code , IRubyElement element , String string ) { this ( code , new IRubyElement [ ] { element } ) ; this . string = string ; } public RubyModelStatus ( int code , IRubyElement element , IPath path ) { this ( code , new IRubyElement [ ] { element } ) ; this . path = path ; } public RubyModelStatus ( int code , IRubyElement element , IPath path , String string ) { this ( code , new IRubyElement [ ] { element } ) ; this . path = path ; this . string = string ; } public RubyModelStatus ( CoreException coreException ) { super ( ERROR , RubyCore . PLUGIN_ID , CORE_EXCEPTION , "" , coreException ) ; elements = RubyElement . NO_ELEMENTS ; } protected int getBits ( ) { int severity = << ( getCode ( ) % / ) ; int category = << ( ( getCode ( ) / ) + ) ; return severity | category ; } public IStatus [ ] getChildren ( ) { return children ; } public IRubyElement [ ] getElements ( ) { return elements ; } public String getMessage ( ) { Throwable exception = getException ( ) ; if ( exception == null ) { switch ( getCode ( ) ) { case CORE_EXCEPTION : return Messages . bind ( Messages . status_coreException ) ; case BUILDER_INITIALIZATION_ERROR : return Messages . bind ( Messages . build_initializationError ) ; case BUILDER_SERIALIZATION_ERROR : return Messages . bind ( Messages . build_serializationError ) ; case DEVICE_PATH : return Messages . bind ( Messages . status_cannotUseDeviceOnPath , getPath ( ) . toString ( ) ) ; case DOM_EXCEPTION : return Messages . bind ( Messages . status_JDOMError ) ; case ELEMENT_DOES_NOT_EXIST : return Messages . bind ( Messages . element_doesNotExist , ( ( RubyElement ) elements [ ] ) . toStringWithAncestors ( ) ) ; case ELEMENT_NOT_ON_CLASSPATH : return Messages . bind ( Messages . element_notOnClasspath , ( ( RubyElement ) elements [ ] ) . toStringWithAncestors ( ) ) ; case EVALUATION_ERROR : return Messages . bind ( Messages . status_evaluationError , string ) ; case INDEX_OUT_OF_BOUNDS : return Messages . bind ( Messages . status_indexOutOfBounds ) ; case INVALID_CONTENTS : return Messages . bind ( Messages . status_invalidContents ) ; case INVALID_DESTINATION : return Messages . bind ( Messages . status_invalidDestination , ( ( RubyElement ) elements [ ] ) . toStringWithAncestors ( ) ) ; case INVALID_ELEMENT_TYPES : StringBuffer buff = new StringBuffer ( Messages . bind ( Messages . operation_notSupported ) ) ; for ( int i = ; i < elements . length ; i ++ ) { if ( i > ) { buff . append ( "" ) ; } buff . append ( ( ( RubyElement ) elements [ i ] ) . toStringWithAncestors ( ) ) ; } return buff . toString ( ) ; case INVALID_NAME : return Messages . bind ( Messages . status_invalidName , string ) ; case INVALID_PACKAGE : return Messages . bind ( Messages . status_invalidPackage , string ) ; case INVALID_PATH : if ( string != null ) { return string ; } return Messages . bind ( Messages . status_invalidPath , getPath ( ) == null ? "" : getPath ( ) . toString ( ) ) ; case INVALID_PROJECT : return Messages . bind ( Messages . status_invalidProject , string ) ; case INVALID_RESOURCE : return Messages . bind ( Messages . status_invalidResource , string ) ; case INVALID_RESOURCE_TYPE : return Messages . bind ( Messages . status_invalidResourceType , string ) ; case INVALID_SIBLING : if ( string != null ) { return Messages . bind ( Messages . status_invalidSibling , string ) ; } return Messages . bind ( Messages . status_invalidSibling , ( ( RubyElement ) elements [ ] ) . toStringWithAncestors ( ) ) ; case IO_EXCEPTION : return Messages . bind ( Messages . status_IOException ) ; case NAME_COLLISION : if ( string != null ) { return string ; } return Messages . bind ( Messages . status_nameCollision , "" ) ; case NO_ELEMENTS_TO_PROCESS : return Messages . bind ( Messages . operation_needElements ) ; case NULL_NAME : return Messages . bind ( Messages . operation_needName ) ; case NULL_PATH : return Messages . bind ( Messages . operation_needPath ) ; case NULL_STRING : return Messages . bind ( Messages . operation_needString ) ; case PATH_OUTSIDE_PROJECT : return Messages . bind ( Messages . operation_pathOutsideProject , string , ( ( RubyElement ) elements [ ] ) . toStringWithAncestors ( ) ) ; case READ_ONLY : IRubyElement element = elements [ ] ; String name = element . getElementName ( ) ; return Messages . bind ( Messages . status_readOnly , name ) ; case RELATIVE_PATH : return Messages . bind ( Messages . operation_needAbsolutePath , getPath ( ) . toString ( ) ) ; case TARGET_EXCEPTION : return Messages . bind ( Messages . status_targetException ) ; case UPDATE_CONFLICT : return Messages . bind ( Messages . status_updateConflict ) ; case NO_LOCAL_CONTENTS : return Messages . bind ( Messages . status_noLocalContents , getPath ( ) . toString ( ) ) ; case CP_VARIABLE_PATH_UNBOUND : IRubyProject javaProject = ( IRubyProject ) elements [ ] ; return Messages . bind ( Messages . classpath_unboundVariablePath , path . makeRelative ( ) . toString ( ) , javaProject . getElementName ( ) ) ; case CLASSPATH_CYCLE : javaProject = ( IRubyProject ) elements [ ] ; return Messages . bind ( Messages . classpath_cycle , javaProject . getElementName ( ) ) ; case DISABLED_CP_EXCLUSION_PATTERNS : javaProject = ( IRubyProject ) elements [ ] ; String projectName = javaProject . getElementName ( ) ; IPath newPath = path ; if ( path . segment ( ) . toString ( ) . equals ( projectName ) ) { newPath = path . removeFirstSegments ( ) ; } return Messages . bind ( Messages . classpath_disabledInclusionExclusionPatterns , newPath . makeRelative ( ) . toString ( ) , projectName ) ; case DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS : javaProject = ( IRubyProject ) elements [ ] ; projectName = javaProject . getElementName ( ) ; newPath = path ; if ( path . segment ( ) . toString ( ) . equals ( projectName ) ) { newPath = path . removeFirstSegments ( ) ; } return Messages . bind ( Messages . classpath_disabledMultipleOutputLocations , newPath . makeRelative ( ) . toString ( ) , projectName ) ; case PROJECT_HAS_NO_RUBY_NATURE : javaProject = ( IRubyProject ) elements [ ] ; projectName = javaProject . getElementName ( ) ; return Messages . bind ( Messages . project_has_no_ruby_nature , projectName ) ; } if ( string != null ) { return string ; } return "" ; } String message = exception . getMessage ( ) ; if ( message != null ) { return message ; } return exception . toString ( ) ; } public IPath getPath ( ) { return path ; } public int getSeverity ( ) { if ( children == NO_CHILDREN ) return super . getSeverity ( ) ; int severity = - ; for ( int i = , max = children . length ; i < max ; i ++ ) { int childrenSeverity = children [ i ] . getSeverity ( ) ; if ( childrenSeverity > severity ) { severity = childrenSeverity ; } } return severity ; } public String getString ( ) { return string ; } public boolean isDoesNotExist ( ) { int code = getCode ( ) ; return code == ELEMENT_DOES_NOT_EXIST || code == ELEMENT_NOT_ON_CLASSPATH ; } public boolean isMultiStatus ( ) { return children != NO_CHILDREN ; } public boolean isOK ( ) { return getCode ( ) == OK ; } public boolean matches ( int mask ) { if ( ! isMultiStatus ( ) ) { return matches ( this , mask ) ; } for ( int i = , max = children . length ; i < max ; i ++ ) { if ( matches ( ( RubyModelStatus ) children [ i ] , mask ) ) return true ; } return false ; } protected boolean matches ( RubyModelStatus status , int mask ) { int severityMask = mask & ; int categoryMask = mask & ~ ; int bits = status . getBits ( ) ; return ( ( severityMask == ) || ( bits & severityMask ) != ) && ( ( categoryMask == ) || ( bits & categoryMask ) != ) ; } public static IRubyModelStatus newMultiStatus ( IRubyModelStatus [ ] children ) { RubyModelStatus jms = new RubyModelStatus ( ) ; jms . children = children ; return jms ; } public String toString ( ) { if ( this == VERIFIED_OK ) { return "" ; } StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( getMessage ( ) ) ; buffer . append ( "" ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . ISourceRange ; class SourceRefElementInfo extends RubyElementInfo { protected int fSourceRangeStart , fSourceRangeEnd ; public int getDeclarationSourceEnd ( ) { return fSourceRangeEnd ; } public int getDeclarationSourceStart ( ) { return fSourceRangeStart ; } protected ISourceRange getSourceRange ( ) { return new SourceRange ( fSourceRangeStart , fSourceRangeEnd - fSourceRangeStart + ) ; } protected void setSourceRangeEnd ( int end ) { fSourceRangeEnd = end ; } protected void setSourceRangeStart ( int start ) { fSourceRangeStart = start ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; public abstract class NamedMember extends Member { protected String name ; public NamedMember ( RubyElement parent , String name ) { super ( parent ) ; this . name = name ; } public String getElementName ( ) { return this . name ; } public String getTypeQualifiedName ( String enclosingTypeSeparator , boolean showParameters ) throws RubyModelException { NamedMember declaringType ; switch ( this . parent . getElementType ( ) ) { case IRubyElement . SCRIPT : return this . name ; case IRubyElement . TYPE : declaringType = ( NamedMember ) this . parent ; break ; case IRubyElement . FIELD : case IRubyElement . METHOD : declaringType = ( NamedMember ) ( ( IMember ) this . parent ) . getDeclaringType ( ) ; break ; default : return null ; } StringBuffer buffer = new StringBuffer ( declaringType . getTypeQualifiedName ( enclosingTypeSeparator , showParameters ) ) ; buffer . append ( enclosingTypeSeparator ) ; String simpleName = this . name . length ( ) == ? Integer . toString ( this . occurrenceCount ) : this . name ; buffer . append ( simpleName ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . formatter . DefaultCodeFormatterConstants ; import org . rubypeople . rdt . internal . compiler . CompilerOptions ; public class RubyCorePreferenceInitializer extends AbstractPreferenceInitializer { public void initializeDefaultPreferences ( ) { HashSet optionNames = RubyModelManager . getRubyModelManager ( ) . optionNames ; Map defaultOptionsMap = new CompilerOptions ( ) . getMap ( ) ; defaultOptionsMap . put ( RubyCore . COMPILER_TASK_TAGS , RubyCore . DEFAULT_TASK_TAGS ) ; defaultOptionsMap . put ( RubyCore . COMPILER_TASK_PRIORITIES , RubyCore . DEFAULT_TASK_PRIORITIES ) ; defaultOptionsMap . put ( RubyCore . COMPILER_TASK_CASE_SENSITIVE , RubyCore . ENABLED ) ; optionNames . add ( RubyCore . CORE_ENCODING ) ; Map codeFormatterOptionsMap = DefaultCodeFormatterConstants . getEclipseDefaultSettings ( ) ; for ( Iterator iter = codeFormatterOptionsMap . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; String optionName = ( String ) entry . getKey ( ) ; defaultOptionsMap . put ( optionName , entry . getValue ( ) ) ; optionNames . add ( optionName ) ; } IEclipsePreferences defaultPreferences = new DefaultScope ( ) . getNode ( RubyCore . PLUGIN_ID ) ; for ( Iterator iter = defaultOptionsMap . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; String optionName = ( String ) entry . getKey ( ) ; defaultPreferences . put ( optionName , ( String ) entry . getValue ( ) ) ; optionNames . add ( optionName ) ; } } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IRubyElement ; class RubyElementInfo { protected IRubyElement [ ] children ; protected boolean isStructureKnown = false ; static Object [ ] NO_NON_RUBY_RESOURCES = new Object [ ] { } ; protected RubyElementInfo ( ) { this . children = RubyElement . NO_ELEMENTS ; } public void addChild ( IRubyElement child ) { if ( this . children == RubyElement . NO_ELEMENTS ) { setChildren ( new IRubyElement [ ] { child } ) ; } else { if ( ! includesChild ( child ) ) { setChildren ( growAndAddToArray ( this . children , child ) ) ; } } } public Object clone ( ) { try { return super . clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new Error ( ) ; } } public IRubyElement [ ] getChildren ( ) { return this . children ; } protected IRubyElement [ ] growAndAddToArray ( IRubyElement [ ] array , IRubyElement addition ) { IRubyElement [ ] old = array ; array = new IRubyElement [ old . length + ] ; System . arraycopy ( old , , array , , old . length ) ; array [ old . length ] = addition ; return array ; } protected boolean includesChild ( IRubyElement child ) { for ( int i = ; i < this . children . length ; i ++ ) { if ( this . children [ i ] . equals ( child ) ) { return true ; } } return false ; } public boolean isStructureKnown ( ) { return this . isStructureKnown ; } protected IRubyElement [ ] removeAndShrinkArray ( IRubyElement [ ] array , IRubyElement deletion ) { IRubyElement [ ] old = array ; array = new IRubyElement [ old . length - ] ; int j = ; for ( int i = ; i < old . length ; i ++ ) { if ( ! old [ i ] . equals ( deletion ) ) { array [ j ] = old [ i ] ; } else { System . arraycopy ( old , i + , array , j , old . length - ( i + ) ) ; return array ; } j ++ ; } return array ; } public void removeChild ( IRubyElement child ) { if ( includesChild ( child ) ) { setChildren ( removeAndShrinkArray ( this . children , child ) ) ; } } public void setChildren ( IRubyElement [ ] children ) { this . children = children ; } public void setIsStructureKnown ( boolean newIsStructureKnown ) { this . isStructureKnown = newIsStructureKnown ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IType ; public final class TypeVector { static int INITIAL_SIZE = ; public int size ; int maxSize ; IType [ ] elements ; public final static IType [ ] NoElements = new IType [ ] ; public TypeVector ( ) { maxSize = INITIAL_SIZE ; size = ; elements = new IType [ maxSize ] ; } public TypeVector ( IType [ ] types ) { this . size = types . length ; this . maxSize = this . size + ; elements = new IType [ this . maxSize ] ; System . arraycopy ( types , , elements , , this . size ) ; } public TypeVector ( IType type ) { this . maxSize = INITIAL_SIZE ; this . size = ; elements = new IType [ this . maxSize ] ; elements [ ] = type ; } public void add ( IType newElement ) { if ( size == maxSize ) System . arraycopy ( elements , , ( elements = new IType [ maxSize *= ] ) , , size ) ; elements [ size ++ ] = newElement ; } public void addAll ( IType [ ] newElements ) { if ( size + newElements . length >= maxSize ) { maxSize = size + newElements . length ; System . arraycopy ( elements , , ( elements = new IType [ maxSize ] ) , , size ) ; } System . arraycopy ( newElements , , elements , size , newElements . length ) ; size += newElements . length ; } public boolean contains ( IType element ) { for ( int i = size ; -- i >= ; ) if ( element . equals ( elements [ i ] ) ) return true ; return false ; } public TypeVector copy ( ) { TypeVector clone = new TypeVector ( ) ; int length = this . elements . length ; System . arraycopy ( this . elements , , clone . elements = new IType [ length ] , , length ) ; clone . size = this . size ; clone . maxSize = this . maxSize ; return clone ; } public IType elementAt ( int index ) { return elements [ index ] ; } public IType [ ] elements ( ) { if ( this . size == ) return NoElements ; if ( this . size < this . maxSize ) { maxSize = size ; System . arraycopy ( this . elements , , ( this . elements = new IType [ maxSize ] ) , , size ) ; } return this . elements ; } public IType find ( IType element ) { for ( int i = size ; -- i >= ; ) if ( element == elements [ i ] ) return elements [ i ] ; return null ; } public IType remove ( IType element ) { for ( int i = size ; -- i >= ; ) if ( element == elements [ i ] ) { System . arraycopy ( elements , i + , elements , i , -- size - i ) ; elements [ size ] = null ; return element ; } return null ; } public void removeAll ( ) { for ( int i = size ; -- i >= ; ) elements [ i ] = null ; size = ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( "" ) ; for ( int i = ; i < size ; i ++ ) { buffer . append ( "" ) ; buffer . append ( elements [ i ] ) ; } buffer . append ( "" ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core ; import java . io . BufferedInputStream ; import java . io . BufferedOutputStream ; import java . io . DataInputStream ; import java . io . DataOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Hashtable ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . WeakHashMap ; import java . util . Map . Entry ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . ISaveContext ; import org . eclipse . core . resources . ISaveParticipant ; import org . eclipse . core . resources . ISavedState ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . PerformanceStats ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . core . runtime . SafeRunner ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . content . IContentTypeManager . ContentTypeChangeEvent ; import org . eclipse . core . runtime . content . IContentTypeManager . IContentTypeChangeListener ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IPreferencesService ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . osgi . service . prefs . BackingStoreException ; import org . rubypeople . rdt . core . ILoadpathAttribute ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IProblemRequestor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . compiler . CompilationParticipant ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . compiler . util . HashtableOfObjectToInt ; import org . rubypeople . rdt . internal . core . buffer . BufferManager ; import org . rubypeople . rdt . internal . core . builder . RubyBuilder ; import org . rubypeople . rdt . internal . core . hierarchy . TypeHierarchy ; import org . rubypeople . rdt . internal . core . parser . MarkerUtility ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . search . AbstractSearchScope ; import org . rubypeople . rdt . internal . core . search . RubyWorkspaceScope ; import org . rubypeople . rdt . internal . core . search . indexing . IndexManager ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; import org . rubypeople . rdt . internal . core . util . WeakHashSet ; public class RubyModelManager implements IContentTypeChangeListener , ISaveParticipant { private static final String BUFFER_MANAGER_DEBUG = RubyCore . PLUGIN_ID + "" ; private static final String TYPE_HIERARCHY_DEBUG = RubyCore . PLUGIN_ID + "" ; private static final String RUBYMODEL_DEBUG = RubyCore . PLUGIN_ID + "" ; private static final String DELTA_DEBUG = RubyCore . PLUGIN_ID + "" ; private static final String DELTA_DEBUG_VERBOSE = RubyCore . PLUGIN_ID + "" ; private static final String POST_ACTION_DEBUG = RubyCore . PLUGIN_ID + "" ; private static final String BUILDER_DEBUG = RubyCore . PLUGIN_ID + "" ; private static final String RUBY_PARSER_DEBUG_OPTION = RubyCore . PLUGIN_ID + "" ; private static final String MODEL_MANAGER_VERBOSE_OPTION = RubyCore . PLUGIN_ID + "" ; private static final String BUILDER_VERBOSE_OPTION = RubyCore . PLUGIN_ID + "" ; private static final String ENABLE_NEW_FORMATTER = RubyCore . PLUGIN_ID + "" ; public static final String DELTA_LISTENER_PERF = RubyCore . PLUGIN_ID + "" ; public static final String RECONCILE_PERF = RubyCore . PLUGIN_ID + "" ; private final static String INDEXED_SECONDARY_TYPES = "" ; public static final String CPVARIABLE_INITIALIZER_EXTPOINT_ID = "" ; public static final String CPCONTAINER_INITIALIZER_EXTPOINT_ID = "" ; public HashMap < String , IPath [ ] > variables = new HashMap < String , IPath [ ] > ( ) ; public HashSet < String > variablesWithInitializer = new HashSet < String > ( ) ; public HashMap < String , IPath [ ] > previousSessionVariables = new HashMap < String , IPath [ ] > ( ) ; private ThreadLocal < HashSet < String > > variableInitializationInProgress = new ThreadLocal < HashSet < String > > ( ) ; public HashMap < IRubyProject , Map < IPath , ILoadpathContainer > > containers = new HashMap < IRubyProject , Map < IPath , ILoadpathContainer > > ( ) ; public HashMap < IRubyProject , Map < IPath , ILoadpathContainer > > previousSessionContainers = new HashMap < IRubyProject , Map < IPath , ILoadpathContainer > > ( ) ; private ThreadLocal < Map < IRubyProject , HashSet < IPath > > > containerInitializationInProgress = new ThreadLocal < Map < IRubyProject , HashSet < IPath > > > ( ) ; public boolean batchContainerInitializations = false ; public HashMap < String , LoadpathContainerInitializer > containerInitializersCache = new HashMap < String , LoadpathContainerInitializer > ( ) ; private final static RubyModelManager MANAGER = new RubyModelManager ( ) ; public DeltaProcessingState deltaState = new DeltaProcessingState ( ) ; public IndexManager indexManager = null ; final RubyModel rubyModel = new RubyModel ( ) ; private ThreadLocal < HashMap > temporaryCache = new ThreadLocal < HashMap > ( ) ; protected HashSet < Openable > elementsOutOfSynchWithBuffers = new HashSet < Openable > ( ) ; private ThreadLocal < HashSet < IRubyProject > > classpathsBeingResolved = new ThreadLocal < HashSet < IRubyProject > > ( ) ; public RubyWorkspaceScope workspaceScope ; protected RubyModelCache cache = new RubyModelCache ( ) ; protected Map < IProject , PerProjectInfo > perProjectInfos = new HashMap < IProject , PerProjectInfo > ( ) ; protected Map < WorkingCopyOwner , Map < RubyScript , PerWorkingCopyInfo > > perWorkingCopyInfos = new HashMap < WorkingCopyOwner , Map < RubyScript , PerWorkingCopyInfo > > ( ) ; protected WeakHashMap < AbstractSearchScope , Object > searchScopes = new WeakHashMap < AbstractSearchScope , Object > ( ) ; public static boolean CP_RESOLVE_VERBOSE = false ; public static boolean ZIP_ACCESS_VERBOSE = false ; public static boolean VERBOSE = false ; HashSet < String > optionNames = new HashSet < String > ( ) ; Hashtable < String , String > optionsCache ; public final IEclipsePreferences [ ] preferencesLookup = new IEclipsePreferences [ ] ; private WeakHashSet stringSymbols = new WeakHashSet ( ) ; static final int PREF_INSTANCE = ; static final int PREF_DEFAULT = ; public static final IRubyScript [ ] NO_WORKING_COPY = new IRubyScript [ ] ; public final static String CP_VARIABLE_PREFERENCES_PREFIX = RubyCore . PLUGIN_ID + "" ; public final static String CP_CONTAINER_PREFERENCES_PREFIX = RubyCore . PLUGIN_ID + "" ; public final static IPath [ ] VARIABLE_INITIALIZATION_IN_PROGRESS = new Path [ ] { new Path ( "" ) } ; public final static ILoadpathContainer CONTAINER_INITIALIZATION_IN_PROGRESS = new ILoadpathContainer ( ) { public ILoadpathEntry [ ] getLoadpathEntries ( ) { return null ; } public String getDescription ( ) { return "" ; } public int getKind ( ) { return ; } public IPath getPath ( ) { return null ; } public String toString ( ) { return getDescription ( ) ; } } ; public final static String CP_ENTRY_IGNORE = "" ; public final static IPath [ ] CP_ENTRY_IGNORE_PATH = new Path [ ] { new Path ( CP_ENTRY_IGNORE ) } ; private static final int VARIABLES_AND_CONTAINERS_FILE_VERSION = ; public static boolean PERF_VARIABLE_INITIALIZER = false ; public static boolean PERF_CONTAINER_INITIALIZER = false ; private static final Object [ ] NO_PARTICIPANTS = new Object [ ] ; public static final String COMPILATION_PARTICIPANT_EXTPOINT_ID = "" ; public class CompilationParticipants { private Object [ ] registeredParticipants = null ; private HashSet < String > managedMarkerTypes ; public CompilationParticipant [ ] getCompilationParticipants ( IRubyProject project ) { final Object [ ] participants = getRegisteredParticipants ( ) ; if ( participants == NO_PARTICIPANTS ) return null ; int length = participants . length ; final List < CompilationParticipant > result = new ArrayList < CompilationParticipant > ( ) ; for ( int i = ; i < length ; i ++ ) { if ( participants [ i ] instanceof IConfigurationElement ) { final IConfigurationElement configElement = ( IConfigurationElement ) participants [ i ] ; SafeRunner . run ( new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { Util . log ( exception , "" ) ; } public void run ( ) throws Exception { Object executableExtension = configElement . createExecutableExtension ( "" ) ; CompilationParticipant participant = ( CompilationParticipant ) executableExtension ; result . add ( participant ) ; } } ) ; } else { CompilationParticipant participant = ( CompilationParticipant ) participants [ i ] ; result . add ( participant ) ; } } if ( result . isEmpty ( ) ) return null ; List < CompilationParticipant > finalResult = new ArrayList < CompilationParticipant > ( ) ; for ( CompilationParticipant participant : result ) { if ( participant != null && participant . isActive ( project ) ) finalResult . add ( participant ) ; } return finalResult . toArray ( new CompilationParticipant [ finalResult . size ( ) ] ) ; } public HashSet < String > managedMarkerTypes ( ) { if ( this . managedMarkerTypes == null ) { getRegisteredParticipants ( ) ; } return this . managedMarkerTypes ; } private synchronized Object [ ] getRegisteredParticipants ( ) { if ( this . registeredParticipants != null ) { return this . registeredParticipants ; } this . managedMarkerTypes = new HashSet < String > ( ) ; IExtensionPoint extension = Platform . getExtensionRegistry ( ) . getExtensionPoint ( RubyCore . PLUGIN_ID , COMPILATION_PARTICIPANT_EXTPOINT_ID ) ; if ( extension == null ) return this . registeredParticipants = NO_PARTICIPANTS ; final ArrayList < IConfigurationElement > modifyingEnv = new ArrayList < IConfigurationElement > ( ) ; final ArrayList < IConfigurationElement > creatingProblems = new ArrayList < IConfigurationElement > ( ) ; final ArrayList < IConfigurationElement > others = new ArrayList < IConfigurationElement > ( ) ; IExtension [ ] extensions = extension . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] configElements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < configElements . length ; j ++ ) { final IConfigurationElement configElement = configElements [ j ] ; String elementName = configElement . getName ( ) ; if ( ! ( "" . equals ( elementName ) ) ) { continue ; } if ( "" . equals ( configElement . getAttribute ( "" ) ) ) modifyingEnv . add ( configElement ) ; else if ( "" . equals ( configElement . getAttribute ( "" ) ) ) creatingProblems . add ( configElement ) ; else others . add ( configElement ) ; IConfigurationElement [ ] managedMarkers = configElement . getChildren ( "" ) ; for ( int k = , length = managedMarkers . length ; k < length ; k ++ ) { IConfigurationElement element = managedMarkers [ k ] ; String markerType = element . getAttribute ( "" ) ; if ( markerType != null ) this . managedMarkerTypes . add ( markerType ) ; } } } int size = modifyingEnv . size ( ) + creatingProblems . size ( ) + others . size ( ) ; if ( size == ) return this . registeredParticipants = NO_PARTICIPANTS ; IConfigurationElement [ ] configElements = new IConfigurationElement [ size ] ; int index = ; index = sortParticipants ( modifyingEnv , configElements , index ) ; index = sortParticipants ( creatingProblems , configElements , index ) ; index = sortParticipants ( others , configElements , index ) ; return this . registeredParticipants = configElements ; } private int sortParticipants ( ArrayList group , IConfigurationElement [ ] configElements , int index ) { int size = group . size ( ) ; if ( size == ) return index ; Object [ ] elements = group . toArray ( ) ; Util . sort ( elements , new Util . Comparer ( ) { public int compare ( Object a , Object b ) { if ( a == b ) return ; String id = ( ( IConfigurationElement ) a ) . getAttribute ( "" ) ; if ( id == null ) return - ; IConfigurationElement [ ] requiredElements = ( ( IConfigurationElement ) b ) . getChildren ( "" ) ; for ( int i = , length = requiredElements . length ; i < length ; i ++ ) { IConfigurationElement required = requiredElements [ i ] ; if ( id . equals ( required . getAttribute ( "" ) ) ) return ; } return - ; } } ) ; for ( int i = ; i < size ; i ++ ) configElements [ index + i ] = ( IConfigurationElement ) elements [ i ] ; return index + size ; } } public final CompilationParticipants compilationParticipants = new CompilationParticipants ( ) ; public static class EclipsePreferencesListener implements IEclipsePreferences . IPreferenceChangeListener { public void preferenceChange ( IEclipsePreferences . PreferenceChangeEvent event ) { } } private RubyModelManager ( ) { if ( Platform . isRunning ( ) ) this . indexManager = new IndexManager ( ) ; } public final static RubyModelManager getRubyModelManager ( ) { return MANAGER ; } public void initializePreferences ( ) { preferencesLookup [ PREF_INSTANCE ] = new InstanceScope ( ) . getNode ( RubyCore . PLUGIN_ID ) ; preferencesLookup [ PREF_DEFAULT ] = new DefaultScope ( ) . getNode ( RubyCore . PLUGIN_ID ) ; IEclipsePreferences . INodeChangeListener listener = new IEclipsePreferences . INodeChangeListener ( ) { public void added ( IEclipsePreferences . NodeChangeEvent event ) { } public void removed ( IEclipsePreferences . NodeChangeEvent event ) { if ( event . getChild ( ) == preferencesLookup [ PREF_INSTANCE ] ) { preferencesLookup [ PREF_INSTANCE ] = new InstanceScope ( ) . getNode ( RubyCore . PLUGIN_ID ) ; preferencesLookup [ PREF_INSTANCE ] . addPreferenceChangeListener ( new EclipsePreferencesListener ( ) ) ; } } } ; ( ( IEclipsePreferences ) preferencesLookup [ PREF_INSTANCE ] . parent ( ) ) . addNodeChangeListener ( listener ) ; preferencesLookup [ PREF_INSTANCE ] . addPreferenceChangeListener ( new EclipsePreferencesListener ( ) ) ; listener = new IEclipsePreferences . INodeChangeListener ( ) { public void added ( IEclipsePreferences . NodeChangeEvent event ) { } public void removed ( IEclipsePreferences . NodeChangeEvent event ) { if ( event . getChild ( ) == preferencesLookup [ PREF_DEFAULT ] ) { preferencesLookup [ PREF_DEFAULT ] = new DefaultScope ( ) . getNode ( RubyCore . PLUGIN_ID ) ; } } } ; ( ( IEclipsePreferences ) preferencesLookup [ PREF_DEFAULT ] . parent ( ) ) . addNodeChangeListener ( listener ) ; } public synchronized Object getInfo ( IRubyElement element ) { HashMap tempCache = this . temporaryCache . get ( ) ; if ( tempCache != null ) { Object result = tempCache . get ( element ) ; if ( result != null ) { return result ; } } return this . cache . getInfo ( element ) ; } public void rememberScope ( AbstractSearchScope scope ) { this . searchScopes . put ( scope , null ) ; } public synchronized Object removeInfoAndChildren ( RubyElement element ) throws RubyModelException { Object info = this . cache . peekAtInfo ( element ) ; if ( info != null ) { element . closing ( info ) ; if ( element instanceof IParent && info instanceof RubyElementInfo ) { IRubyElement [ ] children = ( ( RubyElementInfo ) info ) . getChildren ( ) ; for ( int i = , size = children . length ; i < size ; ++ i ) { RubyElement child = ( RubyElement ) children [ i ] ; child . close ( ) ; } } this . cache . removeInfo ( element ) ; return info ; } return null ; } protected synchronized Object peekAtInfo ( IRubyElement element ) { HashMap tempCache = this . temporaryCache . get ( ) ; if ( tempCache != null ) { Object result = tempCache . get ( element ) ; if ( result != null ) { return result ; } } return this . cache . peekAtInfo ( element ) ; } protected synchronized void putInfos ( IRubyElement openedElement , Map < IRubyElement , Object > newElements ) { Object existingInfo = this . cache . peekAtInfo ( openedElement ) ; if ( openedElement instanceof IParent && existingInfo instanceof RubyElementInfo ) { IRubyElement [ ] children = ( ( RubyElementInfo ) existingInfo ) . getChildren ( ) ; for ( int i = , size = children . length ; i < size ; ++ i ) { RubyElement child = ( RubyElement ) children [ i ] ; try { child . close ( ) ; } catch ( RubyModelException e ) { } } } Iterator < IRubyElement > iterator = newElements . keySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { IRubyElement element = iterator . next ( ) ; Object info = newElements . get ( element ) ; this . cache . putInfo ( element , info ) ; } } public HashMap getTemporaryCache ( ) { HashMap result = this . temporaryCache . get ( ) ; if ( result == null ) { result = new HashMap ( ) ; this . temporaryCache . set ( result ) ; } return result ; } public boolean hasTemporaryCache ( ) { return this . temporaryCache . get ( ) != null ; } public void resetProjectOptions ( RubyProject rubyProject ) { synchronized ( this . perProjectInfos ) { IProject project = rubyProject . getProject ( ) ; PerProjectInfo info = this . perProjectInfos . get ( project ) ; if ( info != null ) { info . options = null ; } } } public void resetProjectPreferences ( RubyProject rubyProject ) { synchronized ( this . perProjectInfos ) { IProject project = rubyProject . getProject ( ) ; PerProjectInfo info = this . perProjectInfos . get ( project ) ; if ( info != null ) { info . preferences = null ; } } } public void resetTemporaryCache ( ) { this . temporaryCache . set ( null ) ; } public final RubyModel getRubyModel ( ) { return this . rubyModel ; } public static class PerWorkingCopyInfo implements IProblemRequestor { int useCount = ; IRubyScript workingCopy ; private IProblemRequestor problemRequestor ; public PerWorkingCopyInfo ( IRubyScript workingCopy , IProblemRequestor problemRequestor ) { this . workingCopy = workingCopy ; this . problemRequestor = problemRequestor ; } public IRubyScript getWorkingCopy ( ) { return this . workingCopy ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( ( ( RubyElement ) this . workingCopy ) . toString ( ) ) ; buffer . append ( "" ) ; buffer . append ( this . useCount ) ; buffer . append ( "" ) ; buffer . append ( this . problemRequestor ) ; return buffer . toString ( ) ; } public void acceptProblem ( IProblem problem ) { try { IResource resource = workingCopy . getUnderlyingResource ( ) ; String markerType = IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER ; if ( problem . isTask ( ) ) { markerType = IRubyModelMarker . TASK_MARKER ; } if ( MarkerUtility . markerExists ( resource , problem . getID ( ) , problem . getSourceStart ( ) , problem . getSourceEnd ( ) , markerType ) ) return ; } catch ( RubyModelException e ) { } catch ( CoreException e ) { } if ( this . problemRequestor == null ) return ; this . problemRequestor . acceptProblem ( problem ) ; } public void beginReporting ( ) { if ( this . problemRequestor == null ) return ; this . problemRequestor . beginReporting ( ) ; } public void endReporting ( ) { if ( this . problemRequestor == null ) return ; this . problemRequestor . endReporting ( ) ; } public boolean isActive ( ) { return this . problemRequestor != null && this . problemRequestor . isActive ( ) ; } } public PerWorkingCopyInfo getPerWorkingCopyInfo ( RubyScript workingCopy , boolean create , boolean recordUsage , IProblemRequestor problemRequestor ) { synchronized ( this . perWorkingCopyInfos ) { WorkingCopyOwner owner = workingCopy . owner ; Map < RubyScript , PerWorkingCopyInfo > workingCopyToInfos = this . perWorkingCopyInfos . get ( owner ) ; if ( workingCopyToInfos == null && create ) { workingCopyToInfos = new HashMap < RubyScript , PerWorkingCopyInfo > ( ) ; this . perWorkingCopyInfos . put ( owner , workingCopyToInfos ) ; } PerWorkingCopyInfo info = workingCopyToInfos == null ? null : workingCopyToInfos . get ( workingCopy ) ; if ( info == null && create ) { info = new PerWorkingCopyInfo ( workingCopy , problemRequestor ) ; workingCopyToInfos . put ( workingCopy , info ) ; } if ( info != null && recordUsage ) info . useCount ++ ; return info ; } } public int discardPerWorkingCopyInfo ( RubyScript workingCopy ) throws RubyModelException { PerWorkingCopyInfo info = null ; synchronized ( this . perWorkingCopyInfos ) { WorkingCopyOwner owner = workingCopy . owner ; Map < RubyScript , PerWorkingCopyInfo > workingCopyToInfos = this . perWorkingCopyInfos . get ( owner ) ; if ( workingCopyToInfos == null ) return - ; info = workingCopyToInfos . get ( workingCopy ) ; if ( info == null ) return - ; if ( -- info . useCount == ) { workingCopyToInfos . remove ( workingCopy ) ; if ( workingCopyToInfos . isEmpty ( ) ) { this . perWorkingCopyInfos . remove ( owner ) ; } } } if ( info . useCount == ) { removeInfoAndChildren ( workingCopy ) ; workingCopy . closeBuffer ( ) ; } return info . useCount ; } protected HashSet < Openable > getElementsOutOfSynchWithBuffers ( ) { return this . elementsOutOfSynchWithBuffers ; } public PerProjectInfo getPerProjectInfo ( IProject project , boolean create ) { synchronized ( this . perProjectInfos ) { PerProjectInfo info = this . perProjectInfos . get ( project ) ; if ( info == null && create ) { info = new PerProjectInfo ( project ) ; this . perProjectInfos . put ( project , info ) ; } return info ; } } public void removePerProjectInfo ( RubyProject rubyProject ) { synchronized ( this . perProjectInfos ) { IProject project = rubyProject . getProject ( ) ; PerProjectInfo info = this . perProjectInfos . get ( project ) ; if ( info != null ) { this . perProjectInfos . remove ( project ) ; } } } public boolean isLoadpathBeingResolved ( IRubyProject project ) { return getLoadpathBeingResolved ( ) . contains ( project ) ; } private HashSet < IRubyProject > getLoadpathBeingResolved ( ) { HashSet < IRubyProject > result = this . classpathsBeingResolved . get ( ) ; if ( result == null ) { result = new HashSet < IRubyProject > ( ) ; this . classpathsBeingResolved . set ( result ) ; } return result ; } public static class PerProjectInfo { public IProject project ; public Object savedState ; public boolean triedRead ; public ILoadpathEntry [ ] rawLoadpath ; public ILoadpathEntry [ ] resolvedLoadpath ; public Map < IPath , ILoadpathEntry > resolvedPathToRawEntries ; public IPath outputLocation ; public Hashtable < String , HashMap < ? , IType > > secondaryTypes ; public IEclipsePreferences preferences ; public Hashtable < String , String > options ; public PerProjectInfo ( IProject project ) { this . triedRead = false ; this . savedState = null ; this . project = project ; } public synchronized void updateLoadpathInformation ( ILoadpathEntry [ ] newRawLoadpath ) { this . rawLoadpath = newRawLoadpath ; this . resolvedLoadpath = null ; this . resolvedPathToRawEntries = null ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( this . project . getFullPath ( ) ) ; buffer . append ( "" ) ; if ( this . rawLoadpath == null ) { buffer . append ( "" ) ; } else { for ( int i = , length = this . rawLoadpath . length ; i < length ; i ++ ) { buffer . append ( "" ) ; buffer . append ( this . rawLoadpath [ i ] ) ; buffer . append ( '' ) ; } } buffer . append ( "" ) ; ILoadpathEntry [ ] resolvedCP = this . resolvedLoadpath ; if ( resolvedCP == null ) { buffer . append ( "" ) ; } else { for ( int i = , length = resolvedCP . length ; i < length ; i ++ ) { buffer . append ( "" ) ; buffer . append ( resolvedCP [ i ] ) ; buffer . append ( '' ) ; } } buffer . append ( "" ) ; if ( this . outputLocation == null ) { buffer . append ( "" ) ; } else { buffer . append ( this . outputLocation ) ; } return buffer . toString ( ) ; } public void rememberExternalLibTimestamps ( ) { ILoadpathEntry [ ] classpath = this . resolvedLoadpath ; if ( classpath == null ) return ; Map < IPath , Long > externalTimeStamps = RubyModelManager . getRubyModelManager ( ) . deltaState . getExternalLibTimeStamps ( ) ; for ( int i = , length = classpath . length ; i < length ; i ++ ) { ILoadpathEntry entry = classpath [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY ) { IPath path = entry . getPath ( ) ; if ( externalTimeStamps . get ( path ) == null ) { Object target = RubyModel . getTarget ( path , true ) ; if ( target instanceof java . io . File ) { long timestamp = DeltaProcessor . getTimeStamp ( ( java . io . File ) target ) ; externalTimeStamps . put ( path , new Long ( timestamp ) ) ; } } } } } } public PerProjectInfo getPerProjectInfoCheckExistence ( IProject project ) throws RubyModelException { RubyModelManager . PerProjectInfo info = getPerProjectInfo ( project , false ) ; if ( info == null ) { if ( ! RubyProject . hasRubyNature ( project ) ) { throw ( ( RubyProject ) RubyCore . create ( project ) ) . newNotPresentException ( ) ; } info = getPerProjectInfo ( project , true ) ; } return info ; } public void setLoadpathBeingResolved ( IRubyProject project , boolean classpathIsResolved ) { if ( classpathIsResolved ) { getLoadpathBeingResolved ( ) . add ( project ) ; } else { getLoadpathBeingResolved ( ) . remove ( project ) ; } } public String getOption ( String optionName ) { if ( RubyCore . CORE_ENCODING . equals ( optionName ) ) { return RubyCore . getEncoding ( ) ; } String propertyName = optionName ; if ( this . optionNames . contains ( propertyName ) ) { IPreferencesService service = Platform . getPreferencesService ( ) ; String value = service . get ( optionName , null , this . preferencesLookup ) ; return value == null ? null : value . trim ( ) ; } return null ; } public Hashtable < String , String > getOptions ( ) { if ( this . optionsCache != null ) return new Hashtable < String , String > ( this . optionsCache ) ; Hashtable < String , String > options = new Hashtable < String , String > ( ) ; IPreferencesService service = Platform . getPreferencesService ( ) ; Iterator < String > iterator = optionNames . iterator ( ) ; while ( iterator . hasNext ( ) ) { String propertyName = iterator . next ( ) ; String propertyValue = service . get ( propertyName , null , this . preferencesLookup ) ; if ( propertyValue != null ) { options . put ( propertyName , propertyValue ) ; } } options . put ( RubyCore . CORE_ENCODING , RubyCore . getEncoding ( ) ) ; this . optionsCache = new Hashtable < String , String > ( options ) ; return options ; } public DeltaProcessor getDeltaProcessor ( ) { return this . deltaState . getDeltaProcessor ( ) ; } public void startup ( ) throws CoreException { try { configurePluginDebugOptions ( ) ; this . cache = new RubyModelCache ( ) ; RubyCore . getPlugin ( ) . getStateLocation ( ) ; initializePreferences ( ) ; Preferences . IPropertyChangeListener propertyListener = new Preferences . IPropertyChangeListener ( ) { public void propertyChange ( Preferences . PropertyChangeEvent event ) { RubyModelManager . this . optionsCache = null ; } } ; RubyCore . getPlugin ( ) . getPluginPreferences ( ) . addPropertyChangeListener ( propertyListener ) ; Platform . getContentTypeManager ( ) . addContentTypeChangeListener ( this ) ; Job job = new Job ( "" ) { protected IStatus run ( IProgressMonitor monitor ) { try { long start = - ; if ( VERBOSE ) start = System . currentTimeMillis ( ) ; loadVariablesAndContainers ( ) ; if ( VERBOSE ) traceVariableAndContainers ( "" , start ) ; } catch ( CoreException e ) { return e . getStatus ( ) ; } return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . setPriority ( Job . SHORT ) ; job . schedule ( ) ; final IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; workspace . addResourceChangeListener ( this . deltaState , IResourceChangeEvent . PRE_BUILD | IResourceChangeEvent . POST_BUILD | IResourceChangeEvent . POST_CHANGE | IResourceChangeEvent . PRE_DELETE | IResourceChangeEvent . PRE_CLOSE ) ; job = new Job ( "" ) { protected IStatus run ( IProgressMonitor monitor ) { startIndexing ( ) ; Job processSavedState = new Job ( Messages . savedState_jobName ) { protected IStatus run ( IProgressMonitor monitor ) { try { workspace . run ( new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor progress ) throws CoreException { ISavedState savedState = workspace . addSaveParticipant ( RubyCore . getRubyCore ( ) , RubyModelManager . this ) ; if ( savedState != null ) { RubyModelManager . this . deltaState . getDeltaProcessor ( ) . overridenEventType = IResourceChangeEvent . POST_CHANGE ; savedState . processResourceChangeEvents ( RubyModelManager . this . deltaState ) ; } } } , monitor ) ; } catch ( CoreException e ) { return e . getStatus ( ) ; } return Status . OK_STATUS ; } } ; processSavedState . setSystem ( true ) ; processSavedState . setPriority ( Job . SHORT ) ; processSavedState . schedule ( ) ; return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . setPriority ( Job . SHORT ) ; job . schedule ( ) ; } catch ( RuntimeException e ) { shutdown ( ) ; throw e ; } } private void startIndexing ( ) { getIndexManager ( ) . reset ( ) ; } public void loadVariablesAndContainers ( ) throws CoreException { loadVariablesAndContainers ( getDefaultPreferences ( ) ) ; loadVariablesAndContainers ( getInstancePreferences ( ) ) ; File file = getVariableAndContainersFile ( ) ; DataInputStream in = null ; try { in = new DataInputStream ( new BufferedInputStream ( new FileInputStream ( file ) ) ) ; switch ( in . readInt ( ) ) { case VARIABLES_AND_CONTAINERS_FILE_VERSION : new VariablesAndContainersLoadHelper ( in ) . load ( ) ; break ; } } catch ( IOException e ) { if ( file . exists ( ) ) Util . log ( e , "" ) ; } catch ( RuntimeException e ) { if ( file . exists ( ) ) Util . log ( e , "" ) ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( IOException e ) { } } } String [ ] registeredVariables = getRegisteredVariableNames ( ) ; for ( int i = ; i < registeredVariables . length ; i ++ ) { String varName = registeredVariables [ i ] ; this . variables . put ( varName , null ) ; } containersReset ( getRegisteredContainerIDs ( ) ) ; } public static void recreatePersistedContainer ( String propertyName , String containerString , boolean addToContainerValues ) { int containerPrefixLength = CP_CONTAINER_PREFERENCES_PREFIX . length ( ) ; int index = propertyName . indexOf ( '' , containerPrefixLength ) ; if ( containerString != null ) containerString = containerString . trim ( ) ; if ( index > ) { String projectName = propertyName . substring ( containerPrefixLength , index ) . trim ( ) ; IRubyProject project = getRubyModelManager ( ) . getRubyModel ( ) . getRubyProject ( projectName ) ; IPath containerPath = new Path ( propertyName . substring ( index + ) . trim ( ) ) ; recreatePersistedContainer ( project , containerPath , containerString , addToContainerValues ) ; } } private static void recreatePersistedContainer ( final IRubyProject project , final IPath containerPath , String containerString , boolean addToContainerValues ) { if ( ! project . getProject ( ) . isAccessible ( ) ) return ; if ( containerString == null ) { getRubyModelManager ( ) . containerPut ( project , containerPath , null ) ; } else { final ILoadpathEntry [ ] containerEntries = ( ( RubyProject ) project ) . decodeLoadpath ( containerString , false , false ) ; if ( containerEntries != null && containerEntries != RubyProject . INVALID_LOADPATH ) { ILoadpathContainer container = new ILoadpathContainer ( ) { public ILoadpathEntry [ ] getLoadpathEntries ( ) { return containerEntries ; } public String getDescription ( ) { return "" + containerPath + "" + project . getElementName ( ) + "" ; } public int getKind ( ) { return ; } public IPath getPath ( ) { return containerPath ; } public String toString ( ) { return getDescription ( ) ; } } ; if ( addToContainerValues ) { getRubyModelManager ( ) . containerPut ( project , containerPath , container ) ; } Map < IPath , ILoadpathContainer > projectContainers = getRubyModelManager ( ) . previousSessionContainers . get ( project ) ; if ( projectContainers == null ) { projectContainers = new HashMap < IPath , ILoadpathContainer > ( ) ; getRubyModelManager ( ) . previousSessionContainers . put ( project , projectContainers ) ; } projectContainers . put ( containerPath , container ) ; } } } private File getVariableAndContainersFile ( ) { return RubyCore . getPlugin ( ) . getStateLocation ( ) . append ( "" ) . toFile ( ) ; } private synchronized void containersReset ( String [ ] containerIDs ) { for ( int i = ; i < containerIDs . length ; i ++ ) { String containerID = containerIDs [ i ] ; Iterator < IRubyProject > projectIterator = this . containers . keySet ( ) . iterator ( ) ; while ( projectIterator . hasNext ( ) ) { IRubyProject project = projectIterator . next ( ) ; Map < IPath , ILoadpathContainer > projectContainers = this . containers . get ( project ) ; if ( projectContainers != null ) { Iterator < IPath > containerIterator = projectContainers . keySet ( ) . iterator ( ) ; while ( containerIterator . hasNext ( ) ) { IPath containerPath = containerIterator . next ( ) ; if ( containerPath . segment ( ) . equals ( containerID ) ) { projectContainers . put ( containerPath , null ) ; } } } } } } public static String [ ] getRegisteredVariableNames ( ) { Plugin jdtCorePlugin = RubyCore . getPlugin ( ) ; if ( jdtCorePlugin == null ) return null ; ArrayList < String > variableList = new ArrayList < String > ( ) ; IExtensionPoint extension = Platform . getExtensionRegistry ( ) . getExtensionPoint ( RubyCore . PLUGIN_ID , RubyModelManager . CPVARIABLE_INITIALIZER_EXTPOINT_ID ) ; if ( extension != null ) { IExtension [ ] extensions = extension . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] configElements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < configElements . length ; j ++ ) { String varAttribute = configElements [ j ] . getAttribute ( "" ) ; if ( varAttribute != null ) variableList . add ( varAttribute ) ; } } } String [ ] variableNames = new String [ variableList . size ( ) ] ; variableList . toArray ( variableNames ) ; return variableNames ; } private void loadVariablesAndContainers ( IEclipsePreferences preferences ) { try { String [ ] propertyNames = preferences . keys ( ) ; int variablePrefixLength = CP_VARIABLE_PREFERENCES_PREFIX . length ( ) ; for ( int i = ; i < propertyNames . length ; i ++ ) { String propertyName = propertyNames [ i ] ; if ( propertyName . startsWith ( CP_VARIABLE_PREFERENCES_PREFIX ) ) { String varName = propertyName . substring ( variablePrefixLength ) ; String propertyValue = preferences . get ( propertyName , null ) ; if ( propertyValue != null ) { String pathString = propertyValue . trim ( ) ; if ( CP_ENTRY_IGNORE . equals ( pathString ) ) { preferences . remove ( propertyName ) ; continue ; } String [ ] pathStrings = pathString . split ( "" ) ; IPath [ ] paths = new IPath [ pathStrings . length ] ; for ( int x = ; x < paths . length ; x ++ ) { paths [ x ] = new Path ( pathStrings [ x ] ) ; } this . variables . put ( varName , paths ) ; this . previousSessionVariables . put ( varName , paths ) ; } } else if ( propertyName . startsWith ( CP_CONTAINER_PREFERENCES_PREFIX ) ) { String propertyValue = preferences . get ( propertyName , null ) ; if ( propertyValue != null ) { preferences . remove ( propertyName ) ; recreatePersistedContainer ( propertyName , propertyValue , true ) ; } } } } catch ( BackingStoreException e1 ) { } } public IEclipsePreferences getDefaultPreferences ( ) { return preferencesLookup [ PREF_DEFAULT ] ; } public static String [ ] getRegisteredContainerIDs ( ) { Plugin jdtCorePlugin = RubyCore . getPlugin ( ) ; if ( jdtCorePlugin == null ) return null ; ArrayList < String > containerIDList = new ArrayList < String > ( ) ; IExtensionPoint extension = Platform . getExtensionRegistry ( ) . getExtensionPoint ( RubyCore . PLUGIN_ID , RubyModelManager . CPCONTAINER_INITIALIZER_EXTPOINT_ID ) ; if ( extension != null ) { IExtension [ ] extensions = extension . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] configElements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < configElements . length ; j ++ ) { String idAttribute = configElements [ j ] . getAttribute ( "" ) ; if ( idAttribute != null ) containerIDList . add ( idAttribute ) ; } } } String [ ] containerIDs = new String [ containerIDList . size ( ) ] ; containerIDList . toArray ( containerIDs ) ; return containerIDs ; } public void shutdown ( ) { RubyCore rubyCore = RubyCore . getRubyCore ( ) ; rubyCore . savePluginPreferences ( ) ; IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; workspace . removeResourceChangeListener ( this . deltaState ) ; workspace . removeSaveParticipant ( rubyCore ) ; if ( this . indexManager != null ) { this . indexManager . shutdown ( ) ; } try { Job . getJobManager ( ) . join ( RubyCore . PLUGIN_ID , null ) ; } catch ( InterruptedException e ) { } } public void saving ( ISaveContext context ) throws CoreException { saveVariablesAndContainers ( ) ; if ( context . getKind ( ) == ISaveContext . FULL_SAVE ) { context . needDelta ( ) ; IndexManager manager = this . indexManager ; if ( manager != null && this . workspaceScope != null ) { manager . cleanUpIndexes ( ) ; } } IProject savedProject = context . getProject ( ) ; if ( savedProject != null ) { if ( ! RubyProject . hasRubyNature ( savedProject ) ) return ; PerProjectInfo info = getPerProjectInfo ( savedProject , true ) ; saveState ( info , context ) ; info . rememberExternalLibTimestamps ( ) ; return ; } ArrayList < IStatus > vStats = null ; ArrayList < PerProjectInfo > values = null ; synchronized ( this . perProjectInfos ) { values = new ArrayList < PerProjectInfo > ( this . perProjectInfos . values ( ) ) ; } if ( values != null ) { Iterator < PerProjectInfo > iterator = values . iterator ( ) ; while ( iterator . hasNext ( ) ) { try { PerProjectInfo info = iterator . next ( ) ; saveState ( info , context ) ; info . rememberExternalLibTimestamps ( ) ; } catch ( CoreException e ) { if ( vStats == null ) vStats = new ArrayList < IStatus > ( ) ; vStats . add ( e . getStatus ( ) ) ; } } } if ( vStats != null ) { IStatus [ ] stats = new IStatus [ vStats . size ( ) ] ; vStats . toArray ( stats ) ; throw new CoreException ( new MultiStatus ( RubyCore . PLUGIN_ID , IStatus . ERROR , stats , Messages . build_cannotSaveStates , null ) ) ; } this . deltaState . saveExternalLibTimeStamps ( ) ; } private void saveVariablesAndContainers ( ) throws CoreException { File file = getVariableAndContainersFile ( ) ; DataOutputStream out = null ; try { out = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( file ) ) ) ; out . writeInt ( VARIABLES_AND_CONTAINERS_FILE_VERSION ) ; new VariablesAndContainersSaveHelper ( out ) . save ( ) ; } catch ( IOException e ) { IStatus status = new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , IStatus . ERROR , "" , e ) ; throw new CoreException ( status ) ; } finally { if ( out != null ) { try { out . close ( ) ; } catch ( IOException e ) { } } } } private void saveState ( PerProjectInfo info , ISaveContext context ) throws CoreException { if ( context . getKind ( ) == ISaveContext . SNAPSHOT ) return ; if ( info . triedRead ) saveBuiltState ( info ) ; } private void saveBuiltState ( PerProjectInfo info ) throws CoreException { if ( RubyBuilder . DEBUG ) System . out . println ( Messages . bind ( Messages . build_saveStateProgress , info . project . getName ( ) ) ) ; File file = getSerializationFile ( info . project ) ; if ( file == null ) return ; long t = System . currentTimeMillis ( ) ; try { DataOutputStream out = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( file ) ) ) ; try { out . writeUTF ( RubyCore . PLUGIN_ID ) ; out . writeUTF ( "" ) ; if ( info . savedState == null ) { out . writeBoolean ( false ) ; } else { out . writeBoolean ( true ) ; RubyBuilder . writeState ( info . savedState , out ) ; } } finally { out . close ( ) ; } } catch ( RuntimeException e ) { try { file . delete ( ) ; } catch ( SecurityException se ) { } throw new CoreException ( new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , Platform . PLUGIN_ERROR , Messages . bind ( Messages . build_cannotSaveState , info . project . getName ( ) ) , e ) ) ; } catch ( IOException e ) { try { file . delete ( ) ; } catch ( SecurityException se ) { } throw new CoreException ( new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , Platform . PLUGIN_ERROR , Messages . bind ( Messages . build_cannotSaveState , info . project . getName ( ) ) , e ) ) ; } if ( RubyBuilder . DEBUG ) { t = System . currentTimeMillis ( ) - t ; System . out . println ( Messages . bind ( Messages . build_saveStateComplete , String . valueOf ( t ) ) ) ; } } private File getSerializationFile ( IProject project ) { if ( ! project . exists ( ) ) return null ; IPath workingLocation = project . getWorkingLocation ( RubyCore . PLUGIN_ID ) ; return workingLocation . append ( "" ) . toFile ( ) ; } public void configurePluginDebugOptions ( ) { if ( RubyCore . getPlugin ( ) . isDebugging ( ) ) { String option = Platform . getDebugOption ( BUFFER_MANAGER_DEBUG ) ; if ( option != null ) BufferManager . VERBOSE = option . equalsIgnoreCase ( "" ) ; option = Platform . getDebugOption ( TYPE_HIERARCHY_DEBUG ) ; if ( option != null ) TypeHierarchy . DEBUG = option . equalsIgnoreCase ( "" ) ; option = Platform . getDebugOption ( BUILDER_DEBUG ) ; if ( option != null ) RubyBuilder . DEBUG = option . equalsIgnoreCase ( "" ) ; option = Platform . getDebugOption ( DELTA_DEBUG ) ; if ( option != null ) DeltaProcessor . DEBUG = option . equalsIgnoreCase ( "" ) ; option = Platform . getDebugOption ( DELTA_DEBUG_VERBOSE ) ; if ( option != null ) DeltaProcessor . VERBOSE = option . equalsIgnoreCase ( "" ) ; option = Platform . getDebugOption ( RUBYMODEL_DEBUG ) ; if ( option != null ) RubyModelManager . VERBOSE = option . equalsIgnoreCase ( "" ) ; option = Platform . getDebugOption ( POST_ACTION_DEBUG ) ; if ( option != null ) RubyModelOperation . POST_ACTION_VERBOSE = option . equalsIgnoreCase ( "" ) ; option = Platform . getDebugOption ( RUBY_PARSER_DEBUG_OPTION ) ; if ( option != null ) RubyParser . setDebugging ( option . equalsIgnoreCase ( "" ) ) ; option = Platform . getDebugOption ( MODEL_MANAGER_VERBOSE_OPTION ) ; if ( option != null ) RubyModelManager . VERBOSE = option . equalsIgnoreCase ( "" ) ; option = Platform . getDebugOption ( BUILDER_VERBOSE_OPTION ) ; if ( option != null ) RubyBuilder . setVerbose ( option . equalsIgnoreCase ( "" ) ) ; if ( PerformanceStats . ENABLED ) { DeltaProcessor . PERF = PerformanceStats . isEnabled ( DELTA_LISTENER_PERF ) ; ReconcileWorkingCopyOperation . PERF = PerformanceStats . isEnabled ( RECONCILE_PERF ) ; } } } public void contentTypeChanged ( ContentTypeChangeEvent event ) { Util . resetRubyLikeExtensions ( ) ; } public static IRubyElement create ( IResource resource , IRubyProject project ) { if ( resource == null ) { return null ; } int type = resource . getType ( ) ; switch ( type ) { case IResource . PROJECT : return RubyCore . create ( ( IProject ) resource ) ; case IResource . FILE : return create ( ( IFile ) resource , project ) ; case IResource . FOLDER : return create ( ( IFolder ) resource , project ) ; case IResource . ROOT : return RubyCore . create ( ( IWorkspaceRoot ) resource ) ; default : return null ; } } public static IRubyElement create ( IFolder folder , IRubyProject project ) { if ( folder == null ) { return null ; } IRubyElement element ; if ( project == null ) { project = RubyCore . create ( folder . getProject ( ) ) ; element = determineIfOnLoadpath ( folder , project ) ; if ( element == null ) { IRubyProject [ ] projects ; try { projects = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) . getRubyProjects ( ) ; } catch ( RubyModelException e ) { return null ; } for ( int i = , length = projects . length ; i < length ; i ++ ) { project = projects [ i ] ; element = determineIfOnLoadpath ( folder , project ) ; if ( element != null ) break ; } } } else { element = determineIfOnLoadpath ( folder , project ) ; } return element ; } private static IRubyElement determineIfOnLoadpath ( IResource resource , IRubyProject project ) { IPath resourcePath = resource . getFullPath ( ) ; IPath rootPath = project . getPath ( ) ; if ( rootPath . equals ( resourcePath ) ) { return project . getSourceFolderRoot ( resource ) ; } else if ( rootPath . isPrefixOf ( resourcePath ) ) { SourceFolderRoot root = ( SourceFolderRoot ) ( ( RubyProject ) project ) . getFolderSourceFolderRoot ( rootPath ) ; if ( root == null ) return null ; IPath pkgPath = resourcePath . removeFirstSegments ( rootPath . segmentCount ( ) ) ; if ( resource . getType ( ) == IResource . FILE ) { pkgPath = pkgPath . removeLastSegments ( ) ; } String [ ] pkgName = pkgPath . segments ( ) ; return root . getSourceFolder ( pkgName ) ; } return null ; } public static IRubyScript create ( IFile file , IRubyProject project ) { if ( file == null ) { return null ; } if ( project == null ) { project = RubyCore . create ( file . getProject ( ) ) ; } String name = file . getName ( ) ; if ( org . rubypeople . rdt . internal . core . util . Util . isRubyLikeFileName ( name ) || org . rubypeople . rdt . internal . core . util . Util . isERBLikeFileName ( name ) ) return createRubyScriptFrom ( file , project ) ; return null ; } public static IRubyScript createRubyScriptFrom ( IFile file , IRubyProject project ) { if ( file == null ) return null ; if ( project == null ) { project = RubyCore . create ( file . getProject ( ) ) ; } ISourceFolder pkg = ( ISourceFolder ) determineIfOnLoadpath ( file , project ) ; if ( pkg == null ) { ISourceFolderRoot root = project . getSourceFolderRoot ( file . getParent ( ) ) ; pkg = root . getSourceFolder ( ISourceFolder . DEFAULT_PACKAGE_NAME ) ; if ( VERBOSE ) { System . out . println ( "" + Thread . currentThread ( ) + "" + file . getFullPath ( ) ) ; } } return pkg . getRubyScript ( file . getName ( ) ) ; } public IRubyScript [ ] getWorkingCopies ( WorkingCopyOwner owner , boolean addPrimary ) { synchronized ( this . perWorkingCopyInfos ) { IRubyScript [ ] primaryWCs = addPrimary && owner != DefaultWorkingCopyOwner . PRIMARY ? getWorkingCopies ( DefaultWorkingCopyOwner . PRIMARY , false ) : null ; Map < RubyScript , PerWorkingCopyInfo > workingCopyToInfos = this . perWorkingCopyInfos . get ( owner ) ; if ( workingCopyToInfos == null ) return primaryWCs ; int primaryLength = primaryWCs == null ? : primaryWCs . length ; int size = workingCopyToInfos . size ( ) ; IRubyScript [ ] result = new IRubyScript [ primaryLength + size ] ; int index = ; if ( primaryWCs != null ) { for ( int i = ; i < primaryLength ; i ++ ) { IRubyScript primaryWorkingCopy = primaryWCs [ i ] ; IRubyScript workingCopy = new RubyScript ( ( SourceFolder ) primaryWorkingCopy . getParent ( ) , primaryWorkingCopy . getElementName ( ) , owner ) ; if ( ! workingCopyToInfos . containsKey ( workingCopy ) ) result [ index ++ ] = primaryWorkingCopy ; } if ( index != primaryLength ) System . arraycopy ( result , , result = new IRubyScript [ index + size ] , , index ) ; } Iterator < PerWorkingCopyInfo > iterator = workingCopyToInfos . values ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { result [ index ++ ] = iterator . next ( ) . getWorkingCopy ( ) ; } return result ; } } public synchronized String intern ( String s ) { return ( String ) this . stringSymbols . add ( new String ( s ) ) ; } public void doneSaving ( ISaveContext context ) { } public void prepareToSave ( ISaveContext context ) throws CoreException { } public void rollback ( ISaveContext context ) { } public synchronized IPath [ ] variableGet ( String variableName ) { HashSet < String > initializations = variableInitializationInProgress ( ) ; if ( initializations . contains ( variableName ) ) { return VARIABLE_INITIALIZATION_IN_PROGRESS ; } IPath [ ] variablePath = this . variables . get ( variableName ) ; if ( variablePath == null ) return null ; IPath [ ] copy = new IPath [ variablePath . length ] ; System . arraycopy ( variablePath , , copy , , variablePath . length ) ; return copy ; } private HashSet < String > variableInitializationInProgress ( ) { HashSet < String > initializations = this . variableInitializationInProgress . get ( ) ; if ( initializations == null ) { initializations = new HashSet < String > ( ) ; this . variableInitializationInProgress . set ( initializations ) ; } return initializations ; } public IPath [ ] getPreviousSessionVariable ( String variableName ) { IPath [ ] previousPath = ( IPath [ ] ) this . previousSessionVariables . get ( variableName ) ; if ( previousPath != null ) { if ( CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + variableName + '' + "" + previousPath ) ; new Exception ( "" ) . printStackTrace ( System . out ) ; } return previousPath ; } return null ; } public synchronized void variablePut ( String variableName , IPath [ ] variablePath ) { HashSet < String > initializations = variableInitializationInProgress ( ) ; if ( variablePath == VARIABLE_INITIALIZATION_IN_PROGRESS ) { initializations . add ( variableName ) ; return ; } else { initializations . remove ( variableName ) ; if ( variablePath == null ) { this . variables . put ( variableName , CP_ENTRY_IGNORE_PATH ) ; } else { this . variables . put ( variableName , variablePath ) ; } this . previousSessionVariables . remove ( variableName ) ; } } public ILoadpathContainer getLoadpathContainer ( IPath containerPath , IRubyProject project ) throws RubyModelException { ILoadpathContainer container = containerGet ( project , containerPath ) ; if ( container == null ) { if ( this . batchContainerInitializations ) { this . batchContainerInitializations = false ; return initializeAllContainers ( project , containerPath ) ; } return initializeContainer ( project , containerPath ) ; } return container ; } ILoadpathContainer initializeContainer ( IRubyProject project , IPath containerPath ) throws RubyModelException { ILoadpathContainer container = null ; final LoadpathContainerInitializer initializer = RubyCore . getLoadpathContainerInitializer ( containerPath . segment ( ) ) ; if ( initializer != null ) { if ( CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + project . getElementName ( ) + '' + "" + containerPath + '' + "" + initializer + '' + "" ) ; new Exception ( "" ) . printStackTrace ( System . out ) ; } containerPut ( project , containerPath , CONTAINER_INITIALIZATION_IN_PROGRESS ) ; boolean ok = false ; try { initializer . initialize ( containerPath , project ) ; container = containerGet ( project , containerPath ) ; if ( container == CONTAINER_INITIALIZATION_IN_PROGRESS ) return null ; ok = true ; } catch ( CoreException e ) { if ( e instanceof RubyModelException ) { throw ( RubyModelException ) e ; } else { throw new RubyModelException ( e ) ; } } catch ( RuntimeException e ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { e . printStackTrace ( ) ; } throw e ; } catch ( Error e ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { e . printStackTrace ( ) ; } throw e ; } finally { if ( ! ok ) { containerRemoveInitializationInProgress ( project , containerPath ) ; if ( CP_RESOLVE_VERBOSE ) { if ( container == CONTAINER_INITIALIZATION_IN_PROGRESS ) { Util . verbose ( "" + "" + project . getElementName ( ) + '' + "" + containerPath + '' + "" + initializer ) ; } else { Util . verbose ( "" + "" + project . getElementName ( ) + '' + "" + containerPath + '' + "" + initializer ) ; } } } } if ( CP_RESOLVE_VERBOSE ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( "" + project . getElementName ( ) + '' ) ; buffer . append ( "" + containerPath + '' ) ; if ( container != null ) { buffer . append ( "" + container . getDescription ( ) + "" ) ; ILoadpathEntry [ ] entries = container . getLoadpathEntries ( ) ; if ( entries != null ) { for ( int i = ; i < entries . length ; i ++ ) { buffer . append ( "" + entries [ i ] + '' ) ; } } buffer . append ( "" ) ; } else { buffer . append ( "" ) ; } Util . verbose ( buffer . toString ( ) ) ; } } else { if ( CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + project . getElementName ( ) + '' + "" + containerPath ) ; } } return container ; } private void containerRemoveInitializationInProgress ( IRubyProject project , IPath containerPath ) { HashSet < IPath > projectInitializations = containerInitializationInProgress ( project ) ; projectInitializations . remove ( containerPath ) ; if ( projectInitializations . size ( ) == ) { Map < IRubyProject , HashSet < IPath > > initializations = this . containerInitializationInProgress . get ( ) ; initializations . remove ( project ) ; } } public synchronized void containerPut ( IRubyProject project , IPath containerPath , ILoadpathContainer container ) { if ( container == CONTAINER_INITIALIZATION_IN_PROGRESS ) { HashSet < IPath > projectInitializations = containerInitializationInProgress ( project ) ; projectInitializations . add ( containerPath ) ; return ; } else { containerRemoveInitializationInProgress ( project , containerPath ) ; Map < IPath , ILoadpathContainer > projectContainers = this . containers . get ( project ) ; if ( projectContainers == null ) { projectContainers = new HashMap < IPath , ILoadpathContainer > ( ) ; this . containers . put ( project , projectContainers ) ; } if ( container == null ) { projectContainers . remove ( containerPath ) ; } else { projectContainers . put ( containerPath , container ) ; } Map < IPath , ILoadpathContainer > previousContainers = this . previousSessionContainers . get ( project ) ; if ( previousContainers != null ) { previousContainers . remove ( containerPath ) ; } } } private ILoadpathContainer initializeAllContainers ( IRubyProject javaProjectToInit , IPath containerToInit ) throws RubyModelException { if ( CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + javaProjectToInit . getElementName ( ) + '' + "" + containerToInit ) ; } final HashMap < IRubyProject , HashSet < IPath > > allContainerPaths = new HashMap < IRubyProject , HashSet < IPath > > ( ) ; IProject [ ] projects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; for ( int i = , length = projects . length ; i < length ; i ++ ) { IProject project = projects [ i ] ; if ( ! RubyProject . hasRubyNature ( project ) ) continue ; IRubyProject javaProject = new RubyProject ( project , getRubyModel ( ) ) ; HashSet < IPath > paths = null ; ILoadpathEntry [ ] rawClasspath = javaProject . getRawLoadpath ( ) ; for ( int j = , length2 = rawClasspath . length ; j < length2 ; j ++ ) { ILoadpathEntry entry = rawClasspath [ j ] ; IPath path = entry . getPath ( ) ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER && containerGet ( javaProject , path ) == null ) { if ( paths == null ) { paths = new HashSet < IPath > ( ) ; allContainerPaths . put ( javaProject , paths ) ; } paths . add ( path ) ; } } } HashSet < IPath > containerPaths = allContainerPaths . get ( javaProjectToInit ) ; if ( containerPaths == null ) { containerPaths = new HashSet < IPath > ( ) ; allContainerPaths . put ( javaProjectToInit , containerPaths ) ; } containerPaths . add ( containerToInit ) ; this . containerInitializationInProgress . set ( allContainerPaths ) ; boolean ok = false ; try { IWorkspaceRunnable runnable = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { Set < IRubyProject > keys = allContainerPaths . keySet ( ) ; int length = keys . size ( ) ; IRubyProject [ ] javaProjects = new IRubyProject [ length ] ; keys . toArray ( javaProjects ) ; for ( int i = ; i < length ; i ++ ) { IRubyProject javaProject = javaProjects [ i ] ; HashSet < IPath > pathSet = allContainerPaths . get ( javaProject ) ; if ( pathSet == null ) continue ; int length2 = pathSet . size ( ) ; IPath [ ] paths = new IPath [ length2 ] ; pathSet . toArray ( paths ) ; for ( int j = ; j < length2 ; j ++ ) { IPath path = paths [ j ] ; initializeContainer ( javaProject , path ) ; } } } } ; IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; if ( workspace . isTreeLocked ( ) ) runnable . run ( null ) ; else workspace . run ( runnable , null , IWorkspace . AVOID_UPDATE , null ) ; ok = true ; } catch ( CoreException e ) { Util . log ( e , "" ) ; } finally { if ( ! ok ) { this . containerInitializationInProgress . set ( null ) ; } } return containerGet ( javaProjectToInit , containerToInit ) ; } public synchronized ILoadpathContainer containerGet ( IRubyProject project , IPath containerPath ) { HashSet < IPath > projectInitializations = containerInitializationInProgress ( project ) ; if ( projectInitializations . contains ( containerPath ) ) { return CONTAINER_INITIALIZATION_IN_PROGRESS ; } Map < IPath , ILoadpathContainer > projectContainers = this . containers . get ( project ) ; if ( projectContainers == null ) { return null ; } ILoadpathContainer container = projectContainers . get ( containerPath ) ; return container ; } private HashSet < IPath > containerInitializationInProgress ( IRubyProject project ) { Map < IRubyProject , HashSet < IPath > > initializations = this . containerInitializationInProgress . get ( ) ; if ( initializations == null ) { initializations = new HashMap < IRubyProject , HashSet < IPath > > ( ) ; this . containerInitializationInProgress . set ( initializations ) ; } HashSet < IPath > projectInitializations = initializations . get ( project ) ; if ( projectInitializations == null ) { projectInitializations = new HashSet < IPath > ( ) ; initializations . put ( project , projectInitializations ) ; } return projectInitializations ; } public ILoadpathContainer getPreviousSessionContainer ( IPath containerPath , IRubyProject project ) { Map < IPath , ILoadpathContainer > previousContainerValues = this . previousSessionContainers . get ( project ) ; if ( previousContainerValues != null ) { ILoadpathContainer previousContainer = ( ILoadpathContainer ) previousContainerValues . get ( containerPath ) ; if ( previousContainer != null ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( "" + project . getElementName ( ) + '' ) ; buffer . append ( "" + containerPath + '' ) ; buffer . append ( "" ) ; buffer . append ( previousContainer . getDescription ( ) ) ; buffer . append ( "" ) ; ILoadpathEntry [ ] entries = previousContainer . getLoadpathEntries ( ) ; if ( entries != null ) { for ( int j = ; j < entries . length ; j ++ ) { buffer . append ( "" ) ; buffer . append ( entries [ j ] ) ; buffer . append ( '' ) ; } } buffer . append ( "" ) ; Util . verbose ( buffer . toString ( ) ) ; new Exception ( "" ) . printStackTrace ( System . out ) ; } return previousContainer ; } } return null ; } public void containerRemove ( IRubyProject project ) { Map < IRubyProject , HashSet < IPath > > initializations = this . containerInitializationInProgress . get ( ) ; if ( initializations != null ) { initializations . remove ( project ) ; } this . containers . remove ( project ) ; } public void setLastBuiltState ( IProject project , Object state ) { if ( RubyProject . hasRubyNature ( project ) ) { PerProjectInfo info = getPerProjectInfo ( project , true ) ; info . triedRead = true ; info . savedState = state ; } if ( state == null ) { try { File file = getSerializationFile ( project ) ; if ( file != null && file . exists ( ) ) file . delete ( ) ; } catch ( SecurityException se ) { } } } public boolean containerPutIfInitializingWithSameEntries ( IPath containerPath , IRubyProject [ ] projects , ILoadpathContainer [ ] respectiveContainers ) { int projectLength = projects . length ; if ( projectLength != ) return false ; final ILoadpathContainer container = respectiveContainers [ ] ; if ( container == null ) return false ; IRubyProject project = projects [ ] ; if ( ! containerInitializationInProgress ( project ) . contains ( containerPath ) ) return false ; ILoadpathContainer previousSessionContainer = getPreviousSessionContainer ( containerPath , project ) ; final ILoadpathEntry [ ] newEntries = container . getLoadpathEntries ( ) ; if ( previousSessionContainer == null ) if ( newEntries . length == ) { containerPut ( project , containerPath , container ) ; return true ; } else { return false ; } final ILoadpathEntry [ ] oldEntries = previousSessionContainer . getLoadpathEntries ( ) ; if ( oldEntries . length != newEntries . length ) return false ; for ( int i = , length = newEntries . length ; i < length ; i ++ ) { if ( ! newEntries [ i ] . equals ( oldEntries [ i ] ) ) { if ( CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + containerPath + '' + "" + org . rubypeople . rdt . core . util . Util . toString ( projects , new org . rubypeople . rdt . core . util . Util . Displayable ( ) { public String displayString ( Object o ) { return ( ( IRubyProject ) o ) . getElementName ( ) ; } } ) + "" + org . rubypeople . rdt . core . util . Util . toString ( respectiveContainers , new org . rubypeople . rdt . core . util . Util . Displayable ( ) { public String displayString ( Object o ) { StringBuffer buffer = new StringBuffer ( "" ) ; if ( o == null ) { buffer . append ( "" ) ; return buffer . toString ( ) ; } buffer . append ( container . getDescription ( ) ) ; buffer . append ( "" ) ; for ( int j = ; j < oldEntries . length ; j ++ ) { buffer . append ( "" ) ; buffer . append ( oldEntries [ j ] ) ; buffer . append ( '' ) ; } buffer . append ( "" ) ; return buffer . toString ( ) ; } } ) + "" + org . rubypeople . rdt . core . util . Util . toString ( respectiveContainers , new org . rubypeople . rdt . core . util . Util . Displayable ( ) { public String displayString ( Object o ) { StringBuffer buffer = new StringBuffer ( "" ) ; if ( o == null ) { buffer . append ( "" ) ; return buffer . toString ( ) ; } buffer . append ( container . getDescription ( ) ) ; buffer . append ( "" ) ; for ( int j = ; j < newEntries . length ; j ++ ) { buffer . append ( "" ) ; buffer . append ( newEntries [ j ] ) ; buffer . append ( '' ) ; } buffer . append ( "" ) ; return buffer . toString ( ) ; } } ) + "" ) ; } return false ; } } containerPut ( project , containerPath , container ) ; return true ; } public void updateVariableValues ( String [ ] variableNames , IPath [ ] [ ] variablePaths , boolean updatePreferences , IProgressMonitor monitor ) throws RubyModelException { if ( monitor != null && monitor . isCanceled ( ) ) return ; if ( CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + org . rubypeople . rdt . core . util . Util . toString ( variableNames ) + '' + "" + org . rubypeople . rdt . core . util . Util . toString ( variablePaths ) ) ; } if ( variablePutIfInitializingWithSameValue ( variableNames , variablePaths ) ) return ; int varLength = variableNames . length ; final HashMap < RubyProject , ILoadpathEntry [ ] > affectedProjectClasspaths = new HashMap < RubyProject , ILoadpathEntry [ ] > ( ) ; IRubyModel model = getRubyModel ( ) ; int discardCount = ; for ( int i = ; i < varLength ; i ++ ) { String variableName = variableNames [ i ] ; IPath [ ] oldPath = this . variableGet ( variableName ) ; if ( oldPath == VARIABLE_INITIALIZATION_IN_PROGRESS ) { oldPath = null ; } if ( oldPath != null && oldPath . equals ( variablePaths [ i ] ) ) { variableNames [ i ] = null ; discardCount ++ ; } } if ( discardCount > ) { if ( discardCount == varLength ) return ; int changedLength = varLength - discardCount ; String [ ] changedVariableNames = new String [ changedLength ] ; IPath [ ] [ ] changedVariablePaths = new IPath [ changedLength ] [ ] ; for ( int i = , index = ; i < varLength ; i ++ ) { if ( variableNames [ i ] != null ) { changedVariableNames [ index ] = variableNames [ i ] ; changedVariablePaths [ index ] = variablePaths [ i ] ; index ++ ; } } variableNames = changedVariableNames ; variablePaths = changedVariablePaths ; varLength = changedLength ; } if ( monitor != null && monitor . isCanceled ( ) ) return ; if ( model != null ) { IRubyProject [ ] projects = model . getRubyProjects ( ) ; nextProject : for ( int i = , projectLength = projects . length ; i < projectLength ; i ++ ) { RubyProject project = ( RubyProject ) projects [ i ] ; ILoadpathEntry [ ] classpath = project . getRawLoadpath ( ) ; for ( int j = , cpLength = classpath . length ; j < cpLength ; j ++ ) { ILoadpathEntry entry = classpath [ j ] ; for ( int k = ; k < varLength ; k ++ ) { String variableName = variableNames [ k ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_VARIABLE ) { if ( variableName . equals ( entry . getPath ( ) . segment ( ) ) ) { affectedProjectClasspaths . put ( project , project . getResolvedLoadpath ( true , false , false ) ) ; continue nextProject ; } } } } } } for ( int i = ; i < varLength ; i ++ ) { variablePut ( variableNames [ i ] , variablePaths [ i ] ) ; if ( updatePreferences ) variablePreferencesPut ( variableNames [ i ] , variablePaths [ i ] ) ; } final String [ ] dbgVariableNames = variableNames ; if ( ! affectedProjectClasspaths . isEmpty ( ) ) { try { final boolean canChangeResources = ! ResourcesPlugin . getWorkspace ( ) . isTreeLocked ( ) ; RubyCore . run ( new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor progressMonitor ) throws CoreException { Iterator < RubyProject > projectsToUpdate = affectedProjectClasspaths . keySet ( ) . iterator ( ) ; while ( projectsToUpdate . hasNext ( ) ) { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) return ; RubyProject affectedProject = projectsToUpdate . next ( ) ; if ( CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + affectedProject . getElementName ( ) + '' + "" + org . rubypeople . rdt . core . util . Util . toString ( dbgVariableNames ) ) ; } affectedProject . setRawLoadpath ( affectedProject . getRawLoadpath ( ) , SetLoadpathOperation . DO_NOT_SET_OUTPUT , null , canChangeResources , ( ILoadpathEntry [ ] ) affectedProjectClasspaths . get ( affectedProject ) , false , false ) ; } } } , null , monitor ) ; } catch ( CoreException e ) { if ( CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + org . rubypeople . rdt . core . util . Util . toString ( dbgVariableNames ) , System . err ) ; e . printStackTrace ( ) ; } if ( e instanceof RubyModelException ) { throw ( RubyModelException ) e ; } else { throw new RubyModelException ( e ) ; } } } } private void variablePreferencesPut ( String variableName , IPath [ ] variablePath ) { String variableKey = CP_VARIABLE_PREFERENCES_PREFIX + variableName ; if ( variablePath == null ) { this . variablesWithInitializer . remove ( variableName ) ; getInstancePreferences ( ) . remove ( variableKey ) ; } else { String string = "" ; for ( int i = ; i < variablePath . length ; i ++ ) { if ( i != ) string += "" ; string += variablePath [ i ] . toString ( ) ; } getInstancePreferences ( ) . put ( variableKey , string ) ; } try { getInstancePreferences ( ) . flush ( ) ; } catch ( BackingStoreException e ) { } } public IEclipsePreferences getInstancePreferences ( ) { return preferencesLookup [ PREF_INSTANCE ] ; } public boolean variablePutIfInitializingWithSameValue ( String [ ] variableNames , IPath [ ] [ ] variablePaths ) { if ( variableNames . length != ) return false ; String variableName = variableNames [ ] ; IPath [ ] oldPath = getPreviousSessionVariable ( variableName ) ; if ( oldPath == null ) return false ; IPath [ ] newPath = variablePaths [ ] ; if ( ! oldPath . equals ( newPath ) ) return false ; variablePut ( variableName , newPath ) ; return true ; } private final class VariablesAndContainersLoadHelper { private static final int ARRAY_INCREMENT = ; private ILoadpathEntry [ ] allLoadpathEntries ; private int allLoadpathEntryCount ; private final Map < String , IPath > allPaths ; private String [ ] allStrings ; private int allStringsCount ; private final DataInputStream in ; VariablesAndContainersLoadHelper ( DataInputStream in ) { super ( ) ; this . allLoadpathEntries = null ; this . allLoadpathEntryCount = ; this . allPaths = new HashMap < String , IPath > ( ) ; this . allStrings = null ; this . allStringsCount = ; this . in = in ; } void load ( ) throws IOException { loadProjects ( RubyModelManager . this . getRubyModel ( ) ) ; loadVariables ( ) ; } private boolean loadBoolean ( ) throws IOException { return this . in . readBoolean ( ) ; } private ILoadpathEntry [ ] loadLoadpathEntries ( ) throws IOException { int count = loadInt ( ) ; ILoadpathEntry [ ] entries = new ILoadpathEntry [ count ] ; for ( int i = ; i < count ; ++ i ) entries [ i ] = loadLoadpathEntry ( ) ; return entries ; } private ILoadpathEntry loadLoadpathEntry ( ) throws IOException { int id = loadInt ( ) ; if ( id < || id > this . allLoadpathEntryCount ) throw new IOException ( "" ) ; if ( id < this . allLoadpathEntryCount ) return this . allLoadpathEntries [ id ] ; int entryKind = loadInt ( ) ; IPath path = loadPath ( ) ; IPath [ ] inclusionPatterns = loadPaths ( ) ; IPath [ ] exclusionPatterns = loadPaths ( ) ; boolean isExported = loadBoolean ( ) ; ILoadpathAttribute [ ] extraAttributes = loadAttributes ( ) ; ILoadpathEntry entry = new LoadpathEntry ( entryKind , path , inclusionPatterns , exclusionPatterns , extraAttributes , isExported ) ; ILoadpathEntry [ ] array = this . allLoadpathEntries ; if ( array == null || id == array . length ) { array = new ILoadpathEntry [ id + ARRAY_INCREMENT ] ; if ( id != ) System . arraycopy ( this . allLoadpathEntries , , array , , id ) ; this . allLoadpathEntries = array ; } array [ id ] = entry ; this . allLoadpathEntryCount = id + ; return entry ; } private ILoadpathAttribute [ ] loadAttributes ( ) throws IOException { int count = loadInt ( ) ; if ( count == ) return LoadpathEntry . NO_EXTRA_ATTRIBUTES ; ILoadpathAttribute [ ] attributes = new ILoadpathAttribute [ count ] ; for ( int i = ; i < count ; ++ i ) attributes [ i ] = loadAttribute ( ) ; return attributes ; } private ILoadpathAttribute loadAttribute ( ) throws IOException { String name = loadString ( ) ; String value = loadString ( ) ; return new LoadpathAttribute ( name , value ) ; } private void loadContainers ( IRubyProject project ) throws IOException { boolean projectIsAccessible = project . getProject ( ) . isAccessible ( ) ; int count = loadInt ( ) ; for ( int i = ; i < count ; ++ i ) { IPath path = loadPath ( ) ; ILoadpathEntry [ ] entries = loadLoadpathEntries ( ) ; if ( ! projectIsAccessible ) continue ; ILoadpathContainer container = new PersistedLoadpathContainer ( project , path , entries ) ; RubyModelManager . this . containerPut ( project , path , container ) ; Map < IPath , ILoadpathContainer > oldContainers = RubyModelManager . this . previousSessionContainers . get ( project ) ; if ( oldContainers == null ) { oldContainers = new HashMap < IPath , ILoadpathContainer > ( ) ; RubyModelManager . this . previousSessionContainers . put ( project , oldContainers ) ; } oldContainers . put ( path , container ) ; } } private int loadInt ( ) throws IOException { return this . in . readInt ( ) ; } private IPath loadPath ( ) throws IOException { if ( loadBoolean ( ) ) return null ; String portableString = loadString ( ) ; IPath path = ( IPath ) this . allPaths . get ( portableString ) ; if ( path == null ) { path = Path . fromPortableString ( portableString ) ; this . allPaths . put ( portableString , path ) ; } return path ; } private IPath [ ] loadPaths ( ) throws IOException { int count = loadInt ( ) ; IPath [ ] pathArray = new IPath [ count ] ; for ( int i = ; i < count ; ++ i ) pathArray [ i ] = loadPath ( ) ; return pathArray ; } private void loadProjects ( IRubyModel model ) throws IOException { int count = loadInt ( ) ; for ( int i = ; i < count ; ++ i ) { String projectName = loadString ( ) ; loadContainers ( model . getRubyProject ( projectName ) ) ; } } private String loadString ( ) throws IOException { int id = loadInt ( ) ; if ( id < || id > this . allStringsCount ) throw new IOException ( "" ) ; if ( id < this . allStringsCount ) return this . allStrings [ id ] ; String string = this . in . readUTF ( ) ; String [ ] array = this . allStrings ; if ( array == null || id == array . length ) { array = new String [ id + ARRAY_INCREMENT ] ; if ( id != ) System . arraycopy ( this . allStrings , , array , , id ) ; this . allStrings = array ; } array [ id ] = string ; this . allStringsCount = id + ; return string ; } private void loadVariables ( ) throws IOException { int size = loadInt ( ) ; Map < String , IPath [ ] > loadedVars = new HashMap < String , IPath [ ] > ( size ) ; for ( int i = ; i < size ; ++ i ) { String varName = loadString ( ) ; IPath [ ] varPath = loadPaths ( ) ; if ( varPath != null ) loadedVars . put ( varName , varPath ) ; } RubyModelManager . this . previousSessionVariables . putAll ( loadedVars ) ; RubyModelManager . this . variables . putAll ( loadedVars ) ; } } private static final class PersistedLoadpathContainer implements ILoadpathContainer { private final IPath containerPath ; private final ILoadpathEntry [ ] entries ; private final IRubyProject project ; PersistedLoadpathContainer ( IRubyProject project , IPath containerPath , ILoadpathEntry [ ] entries ) { super ( ) ; this . containerPath = containerPath ; this . entries = entries ; this . project = project ; } public ILoadpathEntry [ ] getLoadpathEntries ( ) { return entries ; } public String getDescription ( ) { return "" + containerPath + "" + project . getElementName ( ) + "" ; } public int getKind ( ) { return ; } public IPath getPath ( ) { return containerPath ; } public String toString ( ) { return getDescription ( ) ; } } private final class VariablesAndContainersSaveHelper { private final HashtableOfObjectToInt loadpathEntryIds ; private final DataOutputStream out ; private final HashtableOfObjectToInt stringIds ; VariablesAndContainersSaveHelper ( DataOutputStream out ) { super ( ) ; this . loadpathEntryIds = new HashtableOfObjectToInt ( ) ; this . out = out ; this . stringIds = new HashtableOfObjectToInt ( ) ; } void save ( ) throws IOException , RubyModelException { saveProjects ( RubyModelManager . this . getRubyModel ( ) . getRubyProjects ( ) ) ; HashMap < String , IPath [ ] > varsToSave = null ; Iterator < Map . Entry < String , IPath [ ] > > iterator = RubyModelManager . this . variables . entrySet ( ) . iterator ( ) ; IEclipsePreferences defaultPreferences = getDefaultPreferences ( ) ; while ( iterator . hasNext ( ) ) { Map . Entry < String , IPath [ ] > entry = iterator . next ( ) ; String varName = entry . getKey ( ) ; if ( defaultPreferences . get ( CP_VARIABLE_PREFERENCES_PREFIX + varName , null ) != null || CP_ENTRY_IGNORE_PATH . equals ( entry . getValue ( ) ) ) { if ( varsToSave == null ) varsToSave = new HashMap < String , IPath [ ] > ( RubyModelManager . this . variables ) ; varsToSave . remove ( varName ) ; } } saveVariables ( varsToSave != null ? varsToSave : RubyModelManager . this . variables ) ; } private void saveLoadpathEntries ( ILoadpathEntry [ ] entries ) throws IOException { int count = entries == null ? : entries . length ; saveInt ( count ) ; for ( int i = ; i < count ; ++ i ) saveLoadpathEntry ( entries [ i ] ) ; } private void saveLoadpathEntry ( ILoadpathEntry entry ) throws IOException { if ( saveNewId ( entry , this . loadpathEntryIds ) ) { saveInt ( entry . getEntryKind ( ) ) ; savePath ( entry . getPath ( ) ) ; savePaths ( entry . getInclusionPatterns ( ) ) ; savePaths ( entry . getExclusionPatterns ( ) ) ; this . out . writeBoolean ( entry . isExported ( ) ) ; saveAttributes ( entry . getExtraAttributes ( ) ) ; } } private void saveAttribute ( ILoadpathAttribute attribute ) throws IOException { saveString ( attribute . getName ( ) ) ; saveString ( attribute . getValue ( ) ) ; } private void saveAttributes ( ILoadpathAttribute [ ] attributes ) throws IOException { int count = attributes == null ? : attributes . length ; saveInt ( count ) ; for ( int i = ; i < count ; ++ i ) saveAttribute ( attributes [ i ] ) ; } private void saveContainers ( IRubyProject project , Map < IPath , ILoadpathContainer > containerMap ) throws IOException { saveInt ( containerMap . size ( ) ) ; for ( Iterator < Map . Entry < IPath , ILoadpathContainer > > i = containerMap . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Entry < IPath , ILoadpathContainer > entry = i . next ( ) ; IPath path = entry . getKey ( ) ; ILoadpathContainer container = entry . getValue ( ) ; ILoadpathEntry [ ] cpEntries = null ; if ( container == null ) { container = RubyModelManager . this . getPreviousSessionContainer ( path , project ) ; } if ( container != null ) cpEntries = container . getLoadpathEntries ( ) ; savePath ( path ) ; saveLoadpathEntries ( cpEntries ) ; } } private void saveInt ( int value ) throws IOException { this . out . writeInt ( value ) ; } private boolean saveNewId ( Object key , HashtableOfObjectToInt map ) throws IOException { int id = map . get ( key ) ; if ( id == - ) { int newId = map . size ( ) ; map . put ( key , newId ) ; saveInt ( newId ) ; return true ; } else { saveInt ( id ) ; return false ; } } private void savePath ( IPath path ) throws IOException { if ( path == null ) { this . out . writeBoolean ( true ) ; } else { this . out . writeBoolean ( false ) ; saveString ( path . toPortableString ( ) ) ; } } private void savePaths ( IPath [ ] paths ) throws IOException { int count = paths == null ? : paths . length ; saveInt ( count ) ; for ( int i = ; i < count ; ++ i ) savePath ( paths [ i ] ) ; } private void saveProjects ( IRubyProject [ ] projects ) throws IOException , RubyModelException { int count = projects . length ; saveInt ( count ) ; for ( int i = ; i < count ; ++ i ) { IRubyProject project = projects [ i ] ; saveString ( project . getElementName ( ) ) ; Map < IPath , ILoadpathContainer > containerMap = RubyModelManager . this . containers . get ( project ) ; if ( containerMap == null ) { containerMap = Collections . emptyMap ( ) ; } else { containerMap = new HashMap < IPath , ILoadpathContainer > ( containerMap ) ; } saveContainers ( project , containerMap ) ; } } private void saveString ( String string ) throws IOException { if ( saveNewId ( string , this . stringIds ) ) this . out . writeUTF ( string ) ; } private void saveVariables ( Map < String , IPath [ ] > map ) throws IOException { saveInt ( map . size ( ) ) ; for ( String varName : map . keySet ( ) ) { IPath [ ] varPath = map . get ( varName ) ; saveString ( varName ) ; savePaths ( varPath ) ; } } } public IRubySearchScope getWorkspaceScope ( ) { if ( this . workspaceScope == null ) { this . workspaceScope = new RubyWorkspaceScope ( ) ; } return this . workspaceScope ; } public IndexManager getIndexManager ( ) { return indexManager ; } public void secondaryTypesRemoving ( IFile file , boolean cleanIndexCache ) { if ( VERBOSE ) { StringBuffer buffer = new StringBuffer ( "" ) ; buffer . append ( file . getName ( ) ) ; buffer . append ( '' ) ; Util . verbose ( buffer . toString ( ) ) ; } if ( file != null ) { PerProjectInfo projectInfo = getPerProjectInfo ( file . getProject ( ) , false ) ; if ( projectInfo != null && projectInfo . secondaryTypes != null ) { if ( VERBOSE ) { Util . verbose ( "" + file . getProject ( ) . getName ( ) ) ; } secondaryTypesRemoving ( projectInfo . secondaryTypes , file ) ; if ( ! cleanIndexCache ) return ; HashMap < IFile , IType > indexingCache = ( HashMap < IFile , IType > ) projectInfo . secondaryTypes . get ( INDEXED_SECONDARY_TYPES ) ; if ( indexingCache != null ) { Set < IFile > keys = indexingCache . keySet ( ) ; int filesSize = keys . size ( ) , filesCount = ; IFile [ ] removed = null ; Iterator < IFile > cachedFiles = keys . iterator ( ) ; while ( cachedFiles . hasNext ( ) ) { IFile cachedFile = cachedFiles . next ( ) ; if ( file . equals ( cachedFile ) ) { if ( removed == null ) removed = new IFile [ filesSize ] ; filesSize -- ; removed [ filesCount ++ ] = cachedFile ; } } if ( removed != null ) { for ( int i = ; i < filesCount ; i ++ ) { indexingCache . remove ( removed [ i ] ) ; } } } } } } private void secondaryTypesRemoving ( Hashtable < String , HashMap < ? , IType > > secondaryTypesMap , IFile file ) { if ( VERBOSE ) { StringBuffer buffer = new StringBuffer ( "" ) ; Iterator < String > keys = secondaryTypesMap . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { String qualifiedName = keys . next ( ) ; buffer . append ( qualifiedName + '' + secondaryTypesMap . get ( qualifiedName ) ) ; } buffer . append ( '' ) ; buffer . append ( file . getFullPath ( ) ) ; buffer . append ( '' ) ; Util . verbose ( buffer . toString ( ) ) ; } Set < String > packageKeys = secondaryTypesMap . keySet ( ) ; int packagesSize = packageKeys . size ( ) , removedPackagesCount = ; String [ ] removedPackages = null ; Iterator < String > packages = packageKeys . iterator ( ) ; while ( packages . hasNext ( ) ) { String packName = packages . next ( ) ; if ( packName != INDEXED_SECONDARY_TYPES ) { HashMap < String , IType > types = ( HashMap < String , IType > ) secondaryTypesMap . get ( packName ) ; Set < String > nameKeys = types . keySet ( ) ; int namesSize = nameKeys . size ( ) , removedNamesCount = ; String [ ] removedNames = null ; Iterator < String > names = nameKeys . iterator ( ) ; while ( names . hasNext ( ) ) { String typeName = names . next ( ) ; IType type = types . get ( typeName ) ; if ( file . equals ( type . getResource ( ) ) ) { if ( removedNames == null ) removedNames = new String [ namesSize ] ; namesSize -- ; removedNames [ removedNamesCount ++ ] = typeName ; } } if ( removedNames != null ) { for ( int i = ; i < removedNamesCount ; i ++ ) { types . remove ( removedNames [ i ] ) ; } } if ( types . size ( ) == ) { if ( removedPackages == null ) removedPackages = new String [ packagesSize ] ; packagesSize -- ; removedPackages [ removedPackagesCount ++ ] = packName ; } } } if ( removedPackages != null ) { for ( int i = ; i < removedPackagesCount ; i ++ ) { secondaryTypesMap . remove ( removedPackages [ i ] ) ; } } if ( VERBOSE ) { Util . verbose ( "" ) ; Iterator < String > keys = secondaryTypesMap . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { String qualifiedName = keys . next ( ) ; Util . verbose ( "" + qualifiedName + '' + secondaryTypesMap . get ( qualifiedName ) ) ; } } } private void traceVariableAndContainers ( String action , long start ) { Long delta = new Long ( System . currentTimeMillis ( ) - start ) ; Long length = new Long ( getVariableAndContainersFile ( ) . length ( ) ) ; String pattern = "" ; String message = MessageFormat . format ( pattern , new Object [ ] { action , length , delta } ) ; System . out . println ( message ) ; } public static boolean isVerbose ( ) { return VERBOSE ; } public synchronized String [ ] variableNames ( ) { int length = this . variables . size ( ) ; String [ ] result = new String [ length ] ; Iterator < String > vars = this . variables . keySet ( ) . iterator ( ) ; int index = ; while ( vars . hasNext ( ) ) { result [ index ++ ] = vars . next ( ) ; } return result ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IResourceStatus ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . RubyModelException ; public class BatchOperation extends RubyModelOperation { protected IWorkspaceRunnable runnable ; public BatchOperation ( IWorkspaceRunnable runnable ) { this . runnable = runnable ; } protected boolean canModifyRoots ( ) { return true ; } protected void executeOperation ( ) throws RubyModelException { try { this . runnable . run ( this . progressMonitor ) ; } catch ( CoreException ce ) { if ( ce instanceof RubyModelException ) { throw ( RubyModelException ) ce ; } else { if ( ce . getStatus ( ) . getCode ( ) == IResourceStatus . OPERATION_FAILED ) { Throwable e = ce . getStatus ( ) . getException ( ) ; if ( e instanceof RubyModelException ) { throw ( RubyModelException ) e ; } } throw new RubyModelException ( ce ) ; } } } protected IRubyModelStatus verify ( ) { return RubyModelStatus . VERIFIED_OK ; } } package org . rubypeople . rdt . internal . core . builder ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . core . parser . TaskTag ; public interface IMarkerManager { public void removeProblemsAndTasksFor ( IResource resource ) ; public void createSyntaxError ( IFile file , SyntaxException e ) ; public void createTasks ( IFile file , List < TaskTag > tasks ) throws CoreException ; public void addProblem ( IFile file , IProblem problem ) ; } package org . rubypeople . rdt . internal . core . builder ; import org . eclipse . core . resources . IFile ; import org . rubypeople . rdt . core . compiler . BuildContext ; import org . rubypeople . rdt . internal . core . util . Util ; public class ERBBuildContext extends BuildContext { private char [ ] fContents ; public ERBBuildContext ( IFile resource ) { super ( resource ) ; } public char [ ] getContents ( ) { if ( fContents == null ) { char [ ] contents = super . getContents ( ) ; fContents = Util . replaceNonRubyCodeWithWhitespace ( new String ( contents ) ) ; } return fContents ; } } package org . rubypeople . rdt . internal . core . builder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SubMonitor ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . BuildContext ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . CompilationParticipant ; import org . rubypeople . rdt . internal . core . RubyModelManager ; public abstract class AbstractRdtCompiler { protected final IProject project ; protected final IMarkerManager markerManager ; protected CompilationParticipant [ ] fParticipants ; private IRubyProject fRubyProject ; public AbstractRdtCompiler ( IProject project , IMarkerManager markerManager ) { this . project = project ; this . markerManager = markerManager ; this . fRubyProject = getRubyProject ( ) ; fParticipants = RubyModelManager . getRubyModelManager ( ) . compilationParticipants . getCompilationParticipants ( fRubyProject ) ; } protected abstract void removeMarkers ( IMarkerManager markerManager , IProgressMonitor monitor ) ; public void compile ( IProgressMonitor monitor ) throws CoreException { SubMonitor sub = SubMonitor . convert ( monitor , "" + project . getName ( ) + "" , ) ; notifyParticipants ( sub . newChild ( ) ) ; BuildContext [ ] files = getBuildContexts ( ) ; sub . worked ( ) ; int workUnitsPerTask = / ( fParticipants . length + ) ; if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; removeMarkers ( markerManager , sub . newChild ( workUnitsPerTask ) ) ; if ( sub . isCanceled ( ) ) throw new OperationCanceledException ( ) ; compileFiles ( files , sub . newChild ( workUnitsPerTask * fParticipants . length ) ) ; monitor . done ( ) ; } private void notifyParticipants ( IProgressMonitor monitor ) { SubMonitor sub = SubMonitor . convert ( monitor , "" , fParticipants . length ) ; for ( int i = ; i < fParticipants . length ; i ++ ) { fParticipants [ i ] . aboutToBuild ( fRubyProject ) ; sub . worked ( ) ; } sub . done ( ) ; } private void compileFiles ( BuildContext [ ] contexts , IProgressMonitor monitor ) throws CoreException { SubMonitor sub = SubMonitor . convert ( monitor , "" , fParticipants . length + contexts . length ) ; if ( fParticipants != null ) { for ( int i = ; i < fParticipants . length ; i ++ ) { if ( monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; try { long start = System . currentTimeMillis ( ) ; fParticipants [ i ] . buildStarting ( contexts , true , sub . newChild ( ) ) ; if ( RubyBuilder . DEBUG ) System . out . println ( fParticipants [ i ] . getClass ( ) . getSimpleName ( ) + "" + ( System . currentTimeMillis ( ) - start ) + "" ) ; } catch ( Exception e ) { RubyCore . log ( e ) ; } } } for ( int i = ; i < contexts . length ; i ++ ) { CategorizedProblem [ ] problems = contexts [ i ] . getProblems ( ) ; if ( problems == null || problems . length == ) { sub . worked ( ) ; continue ; } for ( int j = ; j < problems . length ; j ++ ) { markerManager . addProblem ( contexts [ i ] . getFile ( ) , problems [ j ] ) ; } sub . worked ( ) ; } sub . done ( ) ; } abstract protected BuildContext [ ] getBuildContexts ( ) throws CoreException ; private IRubyProject getRubyProject ( ) { return RubyCore . create ( project ) ; } public void cleanStarting ( ) { for ( int i = ; i < fParticipants . length ; i ++ ) { fParticipants [ i ] . cleanStarting ( fRubyProject ) ; } } } package org . rubypeople . rdt . internal . core . builder ; import java . util . Collection ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubMonitor ; import org . jruby . ast . CommentNode ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . compiler . BuildContext ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . CompilationParticipant ; import org . rubypeople . rdt . internal . core . parser . ASTTaskParser ; import org . rubypeople . rdt . internal . core . parser . TaskParser ; import org . rubypeople . rdt . internal . core . parser . TaskTag ; public class TaskCompiler extends CompilationParticipant { private TaskParser taskParser ; private ASTTaskParser astTaskParser ; @ Override public int aboutToBuild ( IRubyProject project ) { taskParser = new TaskParser ( project . getOptions ( true ) ) ; astTaskParser = new ASTTaskParser ( project . getOptions ( true ) ) ; return super . aboutToBuild ( project ) ; } @ Override public boolean isActive ( IRubyProject project ) { return true ; } @ Override public void buildStarting ( BuildContext [ ] files , boolean isBatch , IProgressMonitor monitor ) { SubMonitor sub = SubMonitor . convert ( monitor , files . length ) ; for ( BuildContext context : files ) { sub . subTask ( "" + context . getFile ( ) . getLocation ( ) . toPortableString ( ) ) ; Collection < CommentNode > comments = context . getComments ( ) ; if ( comments == null ) { List < TaskTag > tasks = taskParser . getTasks ( new String ( context . getContents ( ) ) ) ; context . recordNewProblems ( tasks . toArray ( new CategorizedProblem [ tasks . size ( ) ] ) ) ; } else { List < TaskTag > tasks = astTaskParser . getTasks ( comments ) ; context . recordNewProblems ( tasks . toArray ( new CategorizedProblem [ tasks . size ( ) ] ) ) ; } sub . worked ( ) ; } sub . done ( ) ; } } package org . rubypeople . rdt . internal . core . builder ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . core . parser . MarkerUtility ; import org . rubypeople . rdt . internal . core . parser . TaskTag ; class MarkerManager implements IMarkerManager { public void removeProblemsAndTasksFor ( IResource resource ) { RubyBuilder . removeProblemsAndTasksFor ( resource ) ; } public void createSyntaxError ( IFile file , SyntaxException e ) { MarkerUtility . createSyntaxError ( file , e ) ; } public void createTasks ( IFile file , List < TaskTag > tasks ) throws CoreException { MarkerUtility . createTasks ( file , tasks ) ; } public void addProblem ( IFile file , IProblem problem ) { MarkerUtility . createProblemMarker ( file , problem ) ; } } package org . rubypeople . rdt . internal . core . builder ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IResourceDeltaVisitor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . SubMonitor ; import org . rubypeople . rdt . core . compiler . BuildContext ; import org . rubypeople . rdt . internal . core . util . Util ; public class IncrementalRdtCompiler extends AbstractRdtCompiler { private List < BuildContext > contexts ; private List < IFile > filesToClear ; private final IResourceDelta rootDelta ; public IncrementalRdtCompiler ( IProject project , IResourceDelta delta , IMarkerManager markerManager ) { super ( project , markerManager ) ; this . rootDelta = delta ; } public IncrementalRdtCompiler ( IProject project , IResourceDelta delta ) { this ( project , delta , new MarkerManager ( ) ) ; } protected void removeMarkers ( IMarkerManager markerManager , IProgressMonitor monitor ) { SubMonitor sub = SubMonitor . convert ( monitor , "" , fParticipants . length ) ; for ( IFile file : filesToClear ) { markerManager . removeProblemsAndTasksFor ( file ) ; sub . worked ( ) ; } sub . done ( ) ; } private void analyzeFiles ( ) throws CoreException { filesToClear = new ArrayList < IFile > ( ) ; contexts = new ArrayList < BuildContext > ( ) ; rootDelta . accept ( new IResourceDeltaVisitor ( ) { public boolean visit ( IResourceDelta delta ) throws CoreException { IResource resource = delta . getResource ( ) ; if ( isRubyFile ( resource ) || isERBFile ( resource ) ) { if ( delta . getKind ( ) == IResourceDelta . REMOVED ) { filesToClear . add ( ( IFile ) resource ) ; } else if ( delta . getKind ( ) == IResourceDelta . ADDED || delta . getKind ( ) == IResourceDelta . CHANGED ) { filesToClear . add ( ( IFile ) resource ) ; if ( isERBFile ( resource ) ) { contexts . add ( new ERBBuildContext ( ( IFile ) resource ) ) ; } else { contexts . add ( new BuildContext ( ( IFile ) resource ) ) ; } } } if ( IResource . FOLDER == resource . getType ( ) ) { if ( resource . getProjectRelativePath ( ) . equals ( new Path ( "" ) ) ) { return false ; } } return true ; } private boolean isERBFile ( IResource resource ) { if ( ! ( resource instanceof IFile ) ) return false ; String name = resource . getName ( ) ; return BuildContextCollector . isERB ( name ) ; } private boolean isRubyFile ( IResource resource ) { return resource instanceof IFile && Util . isRubyLikeFileName ( resource . getName ( ) ) ; } } ) ; } protected BuildContext [ ] getBuildContexts ( ) throws CoreException { if ( contexts == null ) { analyzeFiles ( ) ; } return contexts . toArray ( new BuildContext [ contexts . size ( ) ] ) ; } } package org . rubypeople . rdt . internal . core . builder ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceProxy ; import org . eclipse . core . resources . IResourceProxyVisitor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . content . IContentDescription ; import org . eclipse . core . runtime . content . IContentType ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . BuildContext ; public class BuildContextCollector implements IResourceProxyVisitor { private static final String RUBY_SOURCE_CONTENT_TYPE_ID = "" ; private final List < BuildContext > contexts ; private HashSet < String > visitedLinks ; private IRubyProject rubyProject ; public BuildContextCollector ( IProject project ) { this . contexts = new ArrayList < BuildContext > ( ) ; this . visitedLinks = new HashSet < String > ( ) ; this . rubyProject = RubyCore . create ( project ) ; } public boolean visit ( IResourceProxy proxy ) throws CoreException { switch ( proxy . getType ( ) ) { case IResource . FILE : if ( org . rubypeople . rdt . internal . core . util . Util . isRubyLikeFileName ( proxy . getName ( ) ) ) { IFile file = getFile ( proxy ) ; contexts . add ( new BuildContext ( file ) ) ; return false ; } if ( isERB ( proxy . getName ( ) ) ) { IFile file = getFile ( proxy ) ; contexts . add ( new ERBBuildContext ( file ) ) ; return false ; } IFile file = getFile ( proxy ) ; if ( isRubySourceContentType ( file ) ) { contexts . add ( new BuildContext ( file ) ) ; return false ; } return false ; case IResource . FOLDER : if ( proxy != null && proxy . getName ( ) != null && ( proxy . getName ( ) . equals ( "" ) || proxy . getName ( ) . equals ( "" ) ) ) { return false ; } try { IResource resource = proxy . requestResource ( ) ; if ( resource . getProjectRelativePath ( ) . equals ( new Path ( "" ) ) ) { return false ; } IPath path = resource . getLocation ( ) ; if ( path == null ) { return false ; } String unique = path . toOSString ( ) ; if ( path . toFile ( ) != null ) { unique = path . toFile ( ) . getCanonicalPath ( ) ; } if ( visitedLinks . contains ( unique ) ) return false ; visitedLinks . add ( unique ) ; } catch ( IOException e ) { RubyCore . log ( e ) ; return false ; } } return true ; } private IFile getFile ( IResourceProxy proxy ) { return ( IFile ) proxy . requestResource ( ) ; } public static boolean isERB ( String name ) { return name . endsWith ( "" ) || name . endsWith ( "" ) ; } private boolean isRubySourceContentType ( IFile file ) throws CoreException { IContentDescription contentDescription = file . getContentDescription ( ) ; if ( contentDescription != null ) { IContentType type = contentDescription . getContentType ( ) ; if ( type != null ) if ( type . getId ( ) . equals ( RUBY_SOURCE_CONTENT_TYPE_ID ) ) return true ; } return false ; } public List < BuildContext > getContexts ( ) { return contexts ; } } package org . rubypeople . rdt . internal . core . builder ; import java . io . IOException ; import java . io . InputStream ; import java . io . Reader ; import org . rubypeople . rdt . core . RubyCore ; public class IoUtils { public static void closeQuietly ( Reader reader ) { try { reader . close ( ) ; } catch ( IOException e ) { RubyCore . log ( e ) ; } } public static void closeQuietly ( InputStream contents ) { try { if ( contents != null ) contents . close ( ) ; } catch ( IOException e ) { RubyCore . log ( e ) ; } } public static String readAll ( Reader reader ) throws IOException { StringBuffer result = new StringBuffer ( ) ; char [ ] buffer = new char [ ] ; while ( true ) { int bytesRead = reader . read ( buffer ) ; if ( bytesRead <= ) return result . toString ( ) ; result . append ( buffer , , bytesRead ) ; } } public static String readAllQuietly ( Reader reader ) { try { return readAll ( reader ) ; } catch ( IOException e ) { throw new RuntimeException ( ) ; } } } package org . rubypeople . rdt . internal . core . builder ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . core . parser . Error ; public class SyntaxExceptionHandler { public static CategorizedProblem handle ( SyntaxException e , String contents ) { String restOfSource = contents . substring ( e . getPosition ( ) . getStartOffset ( ) ) ; if ( restOfSource != null && e . getMessage ( ) . trim ( ) . endsWith ( "" ) && restOfSource . startsWith ( "" ) ) { int endIndex = restOfSource . indexOf ( "" ) ; if ( endIndex == - ) { endIndex = contents . length ( ) ; } else { endIndex += e . getPosition ( ) . getStartOffset ( ) + ; } ISourcePosition pos = new IDESourcePosition ( e . getPosition ( ) . getFile ( ) , e . getPosition ( ) . getStartLine ( ) , e . getPosition ( ) . getEndLine ( ) , e . getPosition ( ) . getStartOffset ( ) - , endIndex ) ; CategorizedProblem problem = new Error ( pos , "" , IProblem . MultineCommentNotAtFirstColumn ) ; return problem ; } else if ( e . getMessage ( ) . trim ( ) . endsWith ( "" ) ) { Pattern p = Pattern . compile ( "" ) ; Matcher m = p . matcher ( contents ) ; if ( m . find ( ) ) { int startLine = getLineOfOffset ( m . start ( ) , contents ) ; int endLine = getLineOfOffset ( m . end ( ) , contents ) ; ISourcePosition pos = new IDESourcePosition ( e . getPosition ( ) . getFile ( ) , startLine , endLine , m . start ( ) , m . end ( ) ) ; return new Error ( pos , "" , IProblem . Syntax ) ; } } return grabPrecedingPrefixForPosition ( e , contents ) ; } private static CategorizedProblem grabPrecedingPrefixForPosition ( SyntaxException e , String contents ) { int offset = e . getPosition ( ) . getStartOffset ( ) ; String prefix = getLeadingPrefix ( contents , offset ) ; ISourcePosition pos = new IDESourcePosition ( e . getPosition ( ) . getFile ( ) , e . getPosition ( ) . getStartLine ( ) , e . getPosition ( ) . getEndLine ( ) , offset - prefix . length ( ) - , offset - ) ; return new Error ( pos , e . getMessage ( ) , IProblem . Syntax ) ; } private static int getLineOfOffset ( int offset , String contents ) { String [ ] lines = contents . split ( "" ) ; final int lineDelimeterLength = getLineDelimeterLength ( contents ) ; int start = ; for ( int i = ; i < lines . length ; i ++ ) { int end = start + lines [ i ] . length ( ) ; if ( offset <= end ) return i + ; start = end + lineDelimeterLength ; } return ; } private static int getLineDelimeterLength ( String string ) { int index = string . indexOf ( '' ) ; if ( index == - ) return ; if ( index == ) return ; char c = string . charAt ( index - ) ; if ( c == '' ) return ; return ; } private static String getLeadingPrefix ( String contents , int offset ) { StringBuffer buffer = new StringBuffer ( ) ; for ( int i = offset - ; i >= ; i -- ) { char c = contents . charAt ( i ) ; if ( Character . isWhitespace ( c ) ) break ; buffer . insert ( , c ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core . builder ; import java . io . DataOutputStream ; import java . util . ArrayList ; import java . util . Date ; import java . util . Iterator ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . IncrementalProjectBuilder ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . LoadpathEntry ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; public class RubyBuilder extends IncrementalProjectBuilder { public static boolean DEBUG ; private IProject currentProject ; private RubyProject rubyProject ; private IWorkspaceRoot workspaceRoot ; protected IProject [ ] build ( int kind , Map args , IProgressMonitor monitor ) throws CoreException { this . currentProject = getProject ( ) ; if ( currentProject == null || ! currentProject . isAccessible ( ) ) return null ; AbstractRdtCompiler compiler = createCompiler ( kind ) ; long start = ; if ( DEBUG ) { RubyCore . trace ( "" + buildType ( kind ) + "" + buildDescription ( ) ) ; start = System . currentTimeMillis ( ) ; } compiler . compile ( monitor ) ; if ( DEBUG ) { RubyCore . trace ( "" + buildDescription ( ) ) ; long end = System . currentTimeMillis ( ) ; System . out . println ( currentProject . getName ( ) + "" + ( end - start ) + "" ) ; } return getRequiredProjects ( true ) ; } protected void clean ( IProgressMonitor monitor ) throws CoreException { this . currentProject = getProject ( ) ; if ( currentProject == null || ! currentProject . isAccessible ( ) ) return ; initializeBuilder ( ) ; AbstractRdtCompiler compiler = new CleanRdtCompiler ( currentProject ) ; compiler . cleanStarting ( ) ; RubyModelManager . getRubyModelManager ( ) . indexManager . indexAll ( currentProject ) ; super . clean ( monitor ) ; } private void initializeBuilder ( ) { this . rubyProject = ( RubyProject ) RubyCore . create ( currentProject ) ; this . workspaceRoot = currentProject . getWorkspace ( ) . getRoot ( ) ; } private IProject [ ] getRequiredProjects ( boolean includeBinaryPrerequisites ) { if ( rubyProject == null || workspaceRoot == null ) return new IProject [ ] ; ArrayList < IProject > projects = new ArrayList < IProject > ( ) ; try { ILoadpathEntry [ ] entries = rubyProject . getExpandedLoadpath ( true ) ; for ( int i = , l = entries . length ; i < l ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; IPath path = entry . getPath ( ) ; IProject p = null ; switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_PROJECT : p = workspaceRoot . getProject ( path . lastSegment ( ) ) ; if ( ( ( LoadpathEntry ) entry ) . isOptional ( ) && ! RubyProject . hasRubyNature ( p ) ) p = null ; break ; case ILoadpathEntry . CPE_LIBRARY : if ( includeBinaryPrerequisites && path . segmentCount ( ) > ) { IResource resource = workspaceRoot . findMember ( path . segment ( ) ) ; if ( resource instanceof IProject ) p = ( IProject ) resource ; } } if ( p != null && ! projects . contains ( p ) ) projects . add ( p ) ; } } catch ( RubyModelException e ) { return new IProject [ ] ; } IProject [ ] result = new IProject [ projects . size ( ) ] ; projects . toArray ( result ) ; return result ; } private AbstractRdtCompiler createCompiler ( int kind ) { if ( isPartialBuild ( kind ) ) return new IncrementalRdtCompiler ( currentProject , getDelta ( currentProject ) ) ; return new CleanRdtCompiler ( currentProject ) ; } private String buildType ( int kind ) { return isPartialBuild ( kind ) ? "" : "" ; } private String buildDescription ( ) { return currentProject . getName ( ) + "" + new Date ( System . currentTimeMillis ( ) ) ; } private boolean isPartialBuild ( int kind ) { return kind == INCREMENTAL_BUILD || kind == AUTO_BUILD ; } public static void setVerbose ( boolean verbose ) { RubyBuilder . DEBUG = verbose ; } public static void writeState ( Object savedState , DataOutputStream out ) { } public static void removeProblemsAndTasksFor ( IResource resource ) { try { if ( resource != null && resource . exists ( ) ) { resource . deleteMarkers ( IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER , false , IResource . DEPTH_INFINITE ) ; resource . deleteMarkers ( IRubyModelMarker . TASK_MARKER , false , IResource . DEPTH_INFINITE ) ; Set < String > markerTypes = RubyModelManager . getRubyModelManager ( ) . compilationParticipants . managedMarkerTypes ( ) ; if ( markerTypes . size ( ) == ) return ; Iterator < String > iterator = markerTypes . iterator ( ) ; while ( iterator . hasNext ( ) ) resource . deleteMarkers ( iterator . next ( ) , false , IResource . DEPTH_INFINITE ) ; } } catch ( CoreException e ) { } } public static void buildStarting ( ) { } public static void buildFinished ( ) { } } package org . rubypeople . rdt . internal . core . builder ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubMonitor ; import org . rubypeople . rdt . core . compiler . BuildContext ; public class CleanRdtCompiler extends AbstractRdtCompiler { private List < BuildContext > contexts ; public CleanRdtCompiler ( IProject project ) { this ( project , new MarkerManager ( ) ) ; } public CleanRdtCompiler ( IProject project , IMarkerManager markerManager ) { super ( project , markerManager ) ; } protected void removeMarkers ( IMarkerManager markerManager , IProgressMonitor monitor ) { SubMonitor sub = SubMonitor . convert ( monitor , "" , ) ; markerManager . removeProblemsAndTasksFor ( project ) ; sub . worked ( ) ; sub . done ( ) ; } private void analyzeFiles ( ) throws CoreException { BuildContextCollector collector = new BuildContextCollector ( project ) ; project . accept ( collector , IResource . NONE ) ; contexts = collector . getContexts ( ) ; } @ Override protected BuildContext [ ] getBuildContexts ( ) throws CoreException { if ( contexts == null ) { analyzeFiles ( ) ; } return contexts . toArray ( new BuildContext [ contexts . size ( ) ] ) ; } } package org . rubypeople . rdt . internal . core . builder ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . resources . IResourceDelta ; public class ResourceDeltaFormatter { public String format ( IResourceDelta delta ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( kindAsString ( delta . getKind ( ) ) ) ; buffer . append ( flagsAsString ( delta . getFlags ( ) ) ) ; buffer . append ( delta . getFullPath ( ) ) ; buffer . append ( "" ) ; IResourceDelta [ ] affectedChildren = delta . getAffectedChildren ( ) ; for ( int i = ; i < affectedChildren . length ; i ++ ) { IResourceDelta childDelta = affectedChildren [ i ] ; buffer . append ( format ( childDelta ) ) ; } return buffer . toString ( ) ; } private String flagsAsString ( int flags ) { StringBuffer buffer = new StringBuffer ( ) ; for ( Iterator iter = flagMap . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Integer flag = ( Integer ) iter . next ( ) ; if ( ( flags & flag . intValue ( ) ) != ) buffer . append ( flagMap . get ( flag ) + "" ) ; } return buffer . toString ( ) ; } private String kindAsString ( int kind ) { switch ( kind ) { case IResourceDelta . ADDED : return "" ; case IResourceDelta . REMOVED : return "" ; case IResourceDelta . CHANGED : return "" ; case IResourceDelta . ADDED_PHANTOM : return "" ; case IResourceDelta . REMOVED_PHANTOM : return "" ; } return String . valueOf ( kind ) ; } static Map flagMap = new HashMap ( ) ; static { putFlag ( IResourceDelta . CONTENT , "" ) ; putFlag ( IResourceDelta . ENCODING , "" ) ; putFlag ( IResourceDelta . DESCRIPTION , "" ) ; putFlag ( IResourceDelta . OPEN , "" ) ; putFlag ( IResourceDelta . TYPE , "" ) ; putFlag ( IResourceDelta . SYNC , "" ) ; putFlag ( IResourceDelta . MARKERS , "" ) ; putFlag ( IResourceDelta . MOVED_FROM , "" ) ; putFlag ( IResourceDelta . MOVED_TO , "" ) ; } private static void putFlag ( int flag , String description ) { flagMap . put ( new Integer ( flag ) , description ) ; } } package org . rubypeople . rdt . internal . core . builder ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IProblemRequestor ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . core . parser . TaskTag ; public class ProblemRequestorMarkerManager implements IProblemRequestor { private IMarkerManager markerManager ; private boolean active = false ; private IFile file ; public ProblemRequestorMarkerManager ( IFile file , IMarkerManager markerManager ) { this . markerManager = markerManager ; this . file = file ; } public void acceptProblem ( IProblem problem ) { if ( problem . isWarning ( ) || problem . isError ( ) ) { markerManager . addProblem ( file , problem ) ; return ; } if ( problem . isTask ( ) ) { List tasks = new ArrayList ( ) ; TaskTag task = ( TaskTag ) problem ; tasks . add ( task ) ; try { markerManager . createTasks ( file , tasks ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } return ; } } public void beginReporting ( ) { active = true ; } public void endReporting ( ) { active = false ; } public boolean isActive ( ) { return active ; } } package org . rubypeople . rdt . internal . core . builder ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubMonitor ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . compiler . BuildContext ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . CompilationParticipant ; import org . rubypeople . rdt . core . compiler . ReconcileContext ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . ConstantReassignmentVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . CoreClassReOpening ; import org . rubypeople . rdt . internal . core . parser . warnings . EmptyStatementVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . Ruby19HashCommaSyntax ; import org . rubypeople . rdt . internal . core . parser . warnings . Ruby19WhenStatements ; public class RubyCodeAnalyzer extends CompilationParticipant { private Map < String , Long > timings ; @ Override public boolean isActive ( IRubyProject project ) { return true ; } @ Override public void buildStarting ( BuildContext [ ] files , boolean isBatch , IProgressMonitor monitor ) { timings = new HashMap < String , Long > ( ) ; SubMonitor sub = SubMonitor . convert ( monitor , files . length ) ; for ( BuildContext context : files ) { sub . subTask ( "" + context . getFile ( ) . getLocation ( ) . toPortableString ( ) ) ; String contents = new String ( context . getContents ( ) ) ; IRubyScript script = RubyCore . create ( context . getFile ( ) ) ; long start = System . currentTimeMillis ( ) ; Node ast = context . getAST ( ) ; addTiming ( "" , System . currentTimeMillis ( ) - start ) ; List < CategorizedProblem > problems = parse ( script , contents , ast ) ; context . recordNewProblems ( problems . toArray ( new CategorizedProblem [ problems . size ( ) ] ) ) ; sub . worked ( ) ; } if ( RubyBuilder . DEBUG ) { for ( Map . Entry < String , Long > timing : timings . entrySet ( ) ) { System . out . println ( timing . getKey ( ) + "" + timing . getValue ( ) + "" ) ; } timings . clear ( ) ; } sub . done ( ) ; } private List < CategorizedProblem > parse ( IRubyScript script , String contents , Node ast ) { if ( ast == null ) return Collections . emptyList ( ) ; List < CategorizedProblem > problems = new ArrayList < CategorizedProblem > ( ) ; long lintVTime = System . currentTimeMillis ( ) ; List < RubyLintVisitor > visitors = getLintVisitors ( script , contents ) ; addTiming ( "" , System . currentTimeMillis ( ) - lintVTime ) ; for ( RubyLintVisitor rubyLintVisitor : visitors ) { long start = System . currentTimeMillis ( ) ; rubyLintVisitor . acceptNode ( ast ) ; if ( RubyBuilder . DEBUG ) { addTiming ( rubyLintVisitor . getClass ( ) . getSimpleName ( ) , System . currentTimeMillis ( ) - start ) ; } problems . addAll ( rubyLintVisitor . getProblems ( ) ) ; } return problems ; } private void addTiming ( String simpleName , long length ) { if ( timings == null ) timings = new HashMap < String , Long > ( ) ; Long existingValue = timings . get ( simpleName ) ; if ( existingValue == null ) existingValue = ; timings . put ( simpleName , existingValue + length ) ; } private List < RubyLintVisitor > getLintVisitors ( IRubyScript script , String contents ) { List < RubyLintVisitor > visitors = new ArrayList < RubyLintVisitor > ( ) ; visitors . add ( new EmptyStatementVisitor ( contents ) ) ; visitors . add ( new ConstantReassignmentVisitor ( contents ) ) ; if ( script != null ) { visitors . add ( new CoreClassReOpening ( script , contents ) ) ; } visitors . add ( new Ruby19WhenStatements ( contents ) ) ; visitors . add ( new Ruby19HashCommaSyntax ( contents ) ) ; List < RubyLintVisitor > filtered = new ArrayList < RubyLintVisitor > ( ) ; for ( RubyLintVisitor visitor : visitors ) { if ( visitor . isIgnored ( ) ) continue ; filtered . add ( visitor ) ; } return filtered ; } @ Override public void reconcile ( ReconcileContext context ) { try { List < CategorizedProblem > problems = parse ( context . getWorkingCopy ( ) , context . getWorkingCopy ( ) . getSource ( ) , context . getAST ( ) ) ; addProblems ( context , IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER , problems ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Util ; public class SourceFolderRootInfo extends OpenableElementInfo { protected Object [ ] fNonRubyResources ; public SourceFolderRootInfo ( ) { this . fNonRubyResources = null ; } Object [ ] getNonRubyResources ( IResource underlyingResource ) { if ( this . fNonRubyResources == null ) { try { this . fNonRubyResources = computeFolderNonRubyResources ( ( IContainer ) underlyingResource ) ; } catch ( RubyModelException e ) { this . fNonRubyResources = NO_NON_RUBY_RESOURCES ; } } return this . fNonRubyResources ; } void setNonRubyResources ( Object [ ] resources ) { this . fNonRubyResources = resources ; } static Object [ ] computeFolderNonRubyResources ( IContainer folder ) throws RubyModelException { Object [ ] nonRubyResources = new IResource [ ] ; int nonRubyResourcesCounter = ; try { IResource [ ] members = folder . members ( ) ; nextResource : for ( int i = , max = members . length ; i < max ; i ++ ) { IResource member = members [ i ] ; switch ( member . getType ( ) ) { case IResource . FILE : String fileName = member . getName ( ) ; if ( Util . isValidRubyScriptName ( fileName ) ) continue nextResource ; break ; case IResource . FOLDER : continue nextResource ; } if ( nonRubyResources . length == nonRubyResourcesCounter ) { System . arraycopy ( nonRubyResources , , ( nonRubyResources = new IResource [ nonRubyResourcesCounter * ] ) , , nonRubyResourcesCounter ) ; } nonRubyResources [ nonRubyResourcesCounter ++ ] = member ; } if ( nonRubyResources . length != nonRubyResourcesCounter ) { System . arraycopy ( nonRubyResources , , ( nonRubyResources = new IResource [ nonRubyResourcesCounter ] ) , , nonRubyResourcesCounter ) ; } return nonRubyResources ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } static Object [ ] computeFolderNonRubyResources ( RubyProject project , IContainer folder , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns ) throws RubyModelException { Object [ ] nonRubyResources = new IResource [ ] ; int nonRubyResourcesCounter = ; try { ILoadpathEntry [ ] classpath = project . getResolvedLoadpath ( true , false , false ) ; IResource [ ] members = new IResource [ ] ; if ( folder != null ) members = folder . members ( ) ; nextResource : for ( int i = , max = members . length ; i < max ; i ++ ) { IResource member = members [ i ] ; switch ( member . getType ( ) ) { case IResource . FILE : String fileName = member . getName ( ) ; if ( Util . isValidRubyOrERBScriptName ( fileName ) && ! Util . isExcluded ( member , inclusionPatterns , exclusionPatterns ) ) continue nextResource ; break ; case IResource . FOLDER : if ( Util . isValidSourceFolderName ( member . getName ( ) ) && ( ! Util . isExcluded ( member , inclusionPatterns , exclusionPatterns ) || isLoadpathEntry ( member . getFullPath ( ) , classpath ) ) ) continue nextResource ; break ; } if ( nonRubyResources . length == nonRubyResourcesCounter ) { System . arraycopy ( nonRubyResources , , ( nonRubyResources = new IResource [ nonRubyResourcesCounter * ] ) , , nonRubyResourcesCounter ) ; } nonRubyResources [ nonRubyResourcesCounter ++ ] = member ; } if ( nonRubyResources . length != nonRubyResourcesCounter ) { System . arraycopy ( nonRubyResources , , ( nonRubyResources = new IResource [ nonRubyResourcesCounter ] ) , , nonRubyResourcesCounter ) ; } return nonRubyResources ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } private static boolean isLoadpathEntry ( IPath path , ILoadpathEntry [ ] resolvedLoadpath ) { for ( int i = , length = resolvedLoadpath . length ; i < length ; i ++ ) { ILoadpathEntry entry = resolvedLoadpath [ i ] ; if ( entry . getPath ( ) . equals ( path ) ) { return true ; } } return false ; } synchronized Object [ ] getNonRubyResources ( IRubyProject project , IResource underlyingResource , SourceFolderRoot handle ) { Object [ ] nonRubyResources = this . fNonRubyResources ; if ( nonRubyResources == null ) { nonRubyResources = this . computeNonRubyResources ( project , underlyingResource , handle ) ; this . fNonRubyResources = nonRubyResources ; } return nonRubyResources ; } private Object [ ] computeNonRubyResources ( IRubyProject project , IResource underlyingResource , SourceFolderRoot handle ) { Object [ ] nonRubyResources = NO_NON_RUBY_RESOURCES ; try { if ( underlyingResource . getType ( ) == IResource . FOLDER || underlyingResource . getType ( ) == IResource . PROJECT ) { nonRubyResources = computeFolderNonRubyResources ( ( RubyProject ) project , ( IContainer ) underlyingResource , handle . fullInclusionPatternChars ( ) , handle . fullExclusionPatternChars ( ) ) ; } } catch ( RubyModelException e ) { } return nonRubyResources ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . jruby . ast . RootNode ; import org . jruby . common . IRubyWarnings ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . parser . RubyParserResult ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . internal . core . builder . SyntaxExceptionHandler ; import org . rubypeople . rdt . internal . core . parser . RdtWarnings ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; public class RubyScriptProblemFinder { public static RootNode process ( RubyScript script , char [ ] charContents , HashMap < String , CategorizedProblem [ ] > problems , IProgressMonitor pm ) { RdtWarnings warnings = new RdtWarnings ( script . getElementName ( ) ) ; String contents = new String ( charContents ) ; List < CategorizedProblem > generatedProblems = new ArrayList < CategorizedProblem > ( ) ; RubyParserResult parserResult = null ; try { parserResult = parse ( script , contents , warnings ) ; } catch ( SyntaxException e ) { generatedProblems . add ( SyntaxExceptionHandler . handle ( e , contents ) ) ; } generatedProblems . addAll ( warnings . getWarnings ( ) ) ; problems . put ( IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER , generatedProblems . toArray ( new CategorizedProblem [ generatedProblems . size ( ) ] ) ) ; if ( parserResult == null ) return null ; return ( RootNode ) parserResult . getAST ( ) ; } private static RubyParserResult parse ( RubyScript script , String contents , IRubyWarnings warnings ) { try { RubyParser parser = new RubyParser ( warnings ) ; return parser . parse ( ( IFile ) script . getUnderlyingResource ( ) , contents ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } return null ; } } package org . rubypeople . rdt . internal . core . buffer ; import java . util . Enumeration ; public class LRUCacheEnumerator implements Enumeration { protected LRUEnumeratorElement fElementQueue ; public static class LRUEnumeratorElement { public Object fValue ; public LRUEnumeratorElement fNext ; public LRUEnumeratorElement ( Object value ) { fValue = value ; } } public LRUCacheEnumerator ( LRUEnumeratorElement firstElement ) { fElementQueue = firstElement ; } public boolean hasMoreElements ( ) { return fElementQueue != null ; } public Object nextElement ( ) { Object temp = fElementQueue . fValue ; fElementQueue = fElementQueue . fNext ; return temp ; } } package org . rubypeople . rdt . internal . core . buffer ; import java . text . NumberFormat ; import java . util . Enumeration ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . core . Openable ; public class BufferManager { protected static BufferManager DEFAULT_BUFFER_MANAGER ; public static boolean VERBOSE ; protected OverflowingLRUCache openBuffers = new BufferCache ( ) ; public void addBuffer ( IBuffer buffer ) { if ( VERBOSE ) { String owner = ( ( Openable ) buffer . getOwner ( ) ) . toString ( ) ; System . out . println ( "" + owner ) ; } this . openBuffers . put ( buffer . getOwner ( ) , buffer ) ; if ( VERBOSE ) { System . out . println ( "" + NumberFormat . getInstance ( ) . format ( this . openBuffers . fillingRatio ( ) ) + "" ) ; } } public IBuffer createBuffer ( IOpenable owner ) { IRubyElement element = ( IRubyElement ) owner ; IResource resource = element . getResource ( ) ; return new Buffer ( resource instanceof IFile ? ( IFile ) resource : null , owner , element . isReadOnly ( ) ) ; } public IBuffer getBuffer ( IOpenable owner ) { return ( IBuffer ) this . openBuffers . get ( owner ) ; } public synchronized static BufferManager getDefaultBufferManager ( ) { if ( DEFAULT_BUFFER_MANAGER == null ) { DEFAULT_BUFFER_MANAGER = new BufferManager ( ) ; } return DEFAULT_BUFFER_MANAGER ; } public Enumeration getOpenBuffers ( ) { synchronized ( this . openBuffers ) { this . openBuffers . shrink ( ) ; return this . openBuffers . elements ( ) ; } } public void removeBuffer ( IBuffer buffer ) { this . openBuffers . remove ( buffer . getOwner ( ) ) ; } } package org . rubypeople . rdt . internal . core . buffer ; import java . util . Enumeration ; public interface ICacheEnumeration extends Enumeration { public Object getValue ( ) ; } package org . rubypeople . rdt . internal . core . buffer ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . internal . core . Openable ; public class BufferCache extends OverflowingLRUCache { public BufferCache ( int size ) { super ( size ) ; } public BufferCache ( int size , int overflow ) { super ( size , overflow ) ; } protected boolean close ( LRUCacheEntry entry ) { IBuffer buffer = ( IBuffer ) entry . _fValue ; if ( ! ( ( Openable ) buffer . getOwner ( ) ) . canBufferBeRemovedFromCache ( buffer ) ) { return false ; } buffer . close ( ) ; return true ; } protected LRUCache newInstance ( int size , int overflow ) { return new BufferCache ( size , overflow ) ; } } package org . rubypeople . rdt . internal . core . buffer ; import java . text . NumberFormat ; import java . util . Enumeration ; import java . util . Iterator ; public abstract class OverflowingLRUCache extends LRUCache { protected int fOverflow = ; protected boolean fTimestampsOn = true ; protected double fLoadFactor = ; public OverflowingLRUCache ( int size ) { this ( size , ) ; } public OverflowingLRUCache ( int size , int overflow ) { super ( size ) ; fOverflow = overflow ; } public Object clone ( ) { OverflowingLRUCache newCache = ( OverflowingLRUCache ) newInstance ( fSpaceLimit , fOverflow ) ; LRUCacheEntry qEntry ; qEntry = this . fEntryQueueTail ; while ( qEntry != null ) { newCache . privateAdd ( qEntry . _fKey , qEntry . _fValue , qEntry . _fSpace ) ; qEntry = qEntry . _fPrevious ; } return newCache ; } protected abstract boolean close ( LRUCacheEntry entry ) ; public Enumeration elements ( ) { if ( fEntryQueue == null ) return new LRUCacheEnumerator ( null ) ; LRUCacheEnumerator . LRUEnumeratorElement head = new LRUCacheEnumerator . LRUEnumeratorElement ( fEntryQueue . _fValue ) ; LRUCacheEntry currentEntry = fEntryQueue . _fNext ; LRUCacheEnumerator . LRUEnumeratorElement currentElement = head ; while ( currentEntry != null ) { currentElement . fNext = new LRUCacheEnumerator . LRUEnumeratorElement ( currentEntry . _fValue ) ; currentElement = currentElement . fNext ; currentEntry = currentEntry . _fNext ; } return new LRUCacheEnumerator ( head ) ; } public double fillingRatio ( ) { return ( fCurrentSpace + fOverflow ) * / fSpaceLimit ; } public java . util . Hashtable getEntryTable ( ) { return fEntryTable ; } public double getLoadFactor ( ) { return fLoadFactor ; } public int getOverflow ( ) { return fOverflow ; } protected boolean makeSpace ( int space ) { int limit = fSpaceLimit ; if ( fOverflow == ) { if ( fCurrentSpace + space <= limit ) { return true ; } } int spaceNeeded = ( int ) ( ( - fLoadFactor ) * fSpaceLimit ) ; spaceNeeded = ( spaceNeeded > space ) ? spaceNeeded : space ; LRUCacheEntry entry = fEntryQueueTail ; try { fTimestampsOn = false ; while ( fCurrentSpace + spaceNeeded > limit && entry != null ) { this . privateRemoveEntry ( entry , false , false ) ; entry = entry . _fPrevious ; } } finally { fTimestampsOn = true ; } if ( fCurrentSpace + space <= limit ) { fOverflow = ; return true ; } fOverflow = fCurrentSpace + space - limit ; return false ; } protected abstract LRUCache newInstance ( int size , int overflow ) ; public Object peek ( Object key ) { LRUCacheEntry entry = ( LRUCacheEntry ) fEntryTable . get ( key ) ; if ( entry == null ) { return null ; } return entry . _fValue ; } public void printStats ( ) { int forwardListLength = ; LRUCacheEntry entry = fEntryQueue ; while ( entry != null ) { forwardListLength ++ ; entry = entry . _fNext ; } System . out . println ( "" + forwardListLength ) ; int backwardListLength = ; entry = fEntryQueueTail ; while ( entry != null ) { backwardListLength ++ ; entry = entry . _fPrevious ; } System . out . println ( "" + backwardListLength ) ; Enumeration keys = fEntryTable . keys ( ) ; class Temp { public Class fClass ; public int fCount ; public Temp ( Class aClass ) { fClass = aClass ; fCount = ; } public String toString ( ) { return "" + fClass + "" + fCount + "" ; } } java . util . HashMap h = new java . util . HashMap ( ) ; while ( keys . hasMoreElements ( ) ) { entry = ( LRUCacheEntry ) fEntryTable . get ( keys . nextElement ( ) ) ; Class key = entry . _fValue . getClass ( ) ; Temp t = ( Temp ) h . get ( key ) ; if ( t == null ) { h . put ( key , new Temp ( key ) ) ; } else { t . fCount ++ ; } } for ( Iterator iter = h . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { System . out . println ( h . get ( iter . next ( ) ) ) ; } } protected void privateRemoveEntry ( LRUCacheEntry entry , boolean shuffle ) { privateRemoveEntry ( entry , shuffle , true ) ; } protected void privateRemoveEntry ( LRUCacheEntry entry , boolean shuffle , boolean external ) { if ( ! shuffle ) { if ( external ) { fEntryTable . remove ( entry . _fKey ) ; fCurrentSpace -= entry . _fSpace ; privateNotifyDeletionFromCache ( entry ) ; } else { if ( ! close ( entry ) ) return ; if ( fEntryTable . get ( entry . _fKey ) == null ) return ; fEntryTable . remove ( entry . _fKey ) ; fCurrentSpace -= entry . _fSpace ; privateNotifyDeletionFromCache ( entry ) ; } } LRUCacheEntry previous = entry . _fPrevious ; LRUCacheEntry next = entry . _fNext ; if ( previous == null ) { fEntryQueue = next ; } else { previous . _fNext = next ; } if ( next == null ) { fEntryQueueTail = previous ; } else { next . _fPrevious = previous ; } } public Object put ( Object key , Object value ) { if ( fOverflow > ) shrink ( ) ; int newSpace = spaceFor ( value ) ; LRUCacheEntry entry = ( LRUCacheEntry ) fEntryTable . get ( key ) ; if ( entry != null ) { int oldSpace = entry . _fSpace ; int newTotal = fCurrentSpace - oldSpace + newSpace ; if ( newTotal <= fSpaceLimit ) { updateTimestamp ( entry ) ; entry . _fValue = value ; entry . _fSpace = newSpace ; fCurrentSpace = newTotal ; fOverflow = ; return value ; } privateRemoveEntry ( entry , false , false ) ; } makeSpace ( newSpace ) ; privateAdd ( key , value , newSpace ) ; return value ; } public Object remove ( Object key ) { return removeKey ( key ) ; } public void setLoadFactor ( double newLoadFactor ) throws IllegalArgumentException { if ( newLoadFactor <= && newLoadFactor > ) fLoadFactor = newLoadFactor ; else throw new IllegalArgumentException ( "" ) ; } public void setSpaceLimit ( int limit ) { if ( limit < fSpaceLimit ) { makeSpace ( fSpaceLimit - limit ) ; } fSpaceLimit = limit ; } public boolean shrink ( ) { if ( fOverflow > ) return makeSpace ( ) ; return true ; } public String toString ( ) { return "" + NumberFormat . getInstance ( ) . format ( this . fillingRatio ( ) ) + "" + this . toStringContents ( ) ; } protected void updateTimestamp ( LRUCacheEntry entry ) { if ( fTimestampsOn ) { entry . _fTimestamp = fTimestampCounter ++ ; if ( fEntryQueue != entry ) { this . privateRemoveEntry ( entry , true ) ; this . privateAddEntry ( entry , true ) ; } } } } package org . rubypeople . rdt . internal . core . buffer ; public class ToStringSorter { Object [ ] sortedObjects ; String [ ] sortedStrings ; public boolean compare ( String stringOne , String stringTwo ) { return stringOne . compareTo ( stringTwo ) < ; } private void quickSort ( int left , int right ) { int originalLeft = left ; int originalRight = right ; int midIndex = ( left + right ) / ; String midToString = this . sortedStrings [ midIndex ] ; do { while ( compare ( this . sortedStrings [ left ] , midToString ) ) left ++ ; while ( compare ( midToString , this . sortedStrings [ right ] ) ) right -- ; if ( left <= right ) { Object tmp = this . sortedObjects [ left ] ; this . sortedObjects [ left ] = this . sortedObjects [ right ] ; this . sortedObjects [ right ] = tmp ; String tmpToString = this . sortedStrings [ left ] ; this . sortedStrings [ left ] = this . sortedStrings [ right ] ; this . sortedStrings [ right ] = tmpToString ; left ++ ; right -- ; } } while ( left <= right ) ; if ( originalLeft < right ) quickSort ( originalLeft , right ) ; if ( left < originalRight ) quickSort ( left , originalRight ) ; } public void sort ( Object [ ] unSortedObjects , String [ ] unsortedStrings ) { int size = unSortedObjects . length ; this . sortedObjects = new Object [ size ] ; this . sortedStrings = new String [ size ] ; System . arraycopy ( unSortedObjects , , this . sortedObjects , , size ) ; System . arraycopy ( unsortedStrings , , this . sortedStrings , , size ) ; if ( size > ) quickSort ( , size - ) ; } } package org . rubypeople . rdt . internal . core . buffer ; import java . text . NumberFormat ; import java . util . Enumeration ; import java . util . Hashtable ; import org . rubypeople . rdt . internal . core . RubyElement ; public class LRUCache implements Cloneable { protected static class LRUCacheEntry { public Object _fKey ; public Object _fValue ; public int _fTimestamp ; public int _fSpace ; public LRUCacheEntry _fPrevious ; public LRUCacheEntry _fNext ; public LRUCacheEntry ( Object key , Object value , int space ) { _fKey = key ; _fValue = value ; _fSpace = space ; } public String toString ( ) { return "" + _fKey + "" + _fValue + "" ; } } protected int fCurrentSpace ; protected int fSpaceLimit ; protected int fTimestampCounter ; protected Hashtable fEntryTable ; protected LRUCacheEntry fEntryQueue ; protected LRUCacheEntry fEntryQueueTail ; protected static final int DEFAULT_SPACELIMIT = ; public LRUCache ( ) { this ( DEFAULT_SPACELIMIT ) ; } public LRUCache ( int size ) { fTimestampCounter = fCurrentSpace = ; fEntryQueue = fEntryQueueTail = null ; fEntryTable = new Hashtable ( size ) ; fSpaceLimit = size ; } public Object clone ( ) { LRUCache newCache = newInstance ( fSpaceLimit ) ; LRUCacheEntry qEntry ; qEntry = this . fEntryQueueTail ; while ( qEntry != null ) { newCache . privateAdd ( qEntry . _fKey , qEntry . _fValue , qEntry . _fSpace ) ; qEntry = qEntry . _fPrevious ; } return newCache ; } public void flush ( ) { fCurrentSpace = ; LRUCacheEntry entry = fEntryQueueTail ; fEntryTable = new Hashtable ( ) ; fEntryQueue = fEntryQueueTail = null ; while ( entry != null ) { privateNotifyDeletionFromCache ( entry ) ; entry = entry . _fPrevious ; } } public void flush ( Object key ) { LRUCacheEntry entry ; entry = ( LRUCacheEntry ) fEntryTable . get ( key ) ; if ( entry == null ) return ; this . privateRemoveEntry ( entry , false ) ; } public Object get ( Object key ) { LRUCacheEntry entry = ( LRUCacheEntry ) fEntryTable . get ( key ) ; if ( entry == null ) { return null ; } this . updateTimestamp ( entry ) ; return entry . _fValue ; } public int getCurrentSpace ( ) { return fCurrentSpace ; } public int getSpaceLimit ( ) { return fSpaceLimit ; } public Enumeration keys ( ) { return fEntryTable . keys ( ) ; } public ICacheEnumeration keysAndValues ( ) { return new ICacheEnumeration ( ) { Enumeration fValues = fEntryTable . elements ( ) ; LRUCacheEntry fEntry ; public boolean hasMoreElements ( ) { return fValues . hasMoreElements ( ) ; } public Object nextElement ( ) { fEntry = ( LRUCacheEntry ) fValues . nextElement ( ) ; return fEntry . _fKey ; } public Object getValue ( ) { if ( fEntry == null ) { throw new java . util . NoSuchElementException ( ) ; } return fEntry . _fValue ; } } ; } protected boolean makeSpace ( int space ) { int limit ; limit = this . getSpaceLimit ( ) ; if ( fCurrentSpace + space <= limit ) { return true ; } if ( space > limit ) { return false ; } while ( fCurrentSpace + space > limit && fEntryQueueTail != null ) { this . privateRemoveEntry ( fEntryQueueTail , false ) ; } return true ; } protected LRUCache newInstance ( int size ) { return new LRUCache ( size ) ; } protected void privateAdd ( Object key , Object value , int space ) { LRUCacheEntry entry ; entry = new LRUCacheEntry ( key , value , space ) ; this . privateAddEntry ( entry , false ) ; } protected void privateAddEntry ( LRUCacheEntry entry , boolean shuffle ) { if ( ! shuffle ) { fEntryTable . put ( entry . _fKey , entry ) ; fCurrentSpace += entry . _fSpace ; } entry . _fTimestamp = fTimestampCounter ++ ; entry . _fNext = this . fEntryQueue ; entry . _fPrevious = null ; if ( fEntryQueue == null ) { fEntryQueueTail = entry ; } else { fEntryQueue . _fPrevious = entry ; } fEntryQueue = entry ; } protected void privateNotifyDeletionFromCache ( LRUCacheEntry entry ) { } protected void privateRemoveEntry ( LRUCacheEntry entry , boolean shuffle ) { LRUCacheEntry previous , next ; previous = entry . _fPrevious ; next = entry . _fNext ; if ( ! shuffle ) { fEntryTable . remove ( entry . _fKey ) ; fCurrentSpace -= entry . _fSpace ; privateNotifyDeletionFromCache ( entry ) ; } if ( previous == null ) { fEntryQueue = next ; } else { previous . _fNext = next ; } if ( next == null ) { fEntryQueueTail = previous ; } else { next . _fPrevious = previous ; } } public Object put ( Object key , Object value ) { int newSpace , oldSpace , newTotal ; LRUCacheEntry entry ; newSpace = spaceFor ( value ) ; entry = ( LRUCacheEntry ) fEntryTable . get ( key ) ; if ( entry != null ) { oldSpace = entry . _fSpace ; newTotal = getCurrentSpace ( ) - oldSpace + newSpace ; if ( newTotal <= getSpaceLimit ( ) ) { updateTimestamp ( entry ) ; entry . _fValue = value ; entry . _fSpace = newSpace ; this . fCurrentSpace = newTotal ; return value ; } privateRemoveEntry ( entry , false ) ; } if ( makeSpace ( newSpace ) ) { privateAdd ( key , value , newSpace ) ; } return value ; } public Object removeKey ( Object key ) { LRUCacheEntry entry = ( LRUCacheEntry ) fEntryTable . get ( key ) ; if ( entry == null ) { return null ; } Object value = entry . _fValue ; this . privateRemoveEntry ( entry , false ) ; return value ; } public void setSpaceLimit ( int limit ) { if ( limit < fSpaceLimit ) { makeSpace ( fSpaceLimit - limit ) ; } fSpaceLimit = limit ; } protected int spaceFor ( Object value ) { if ( value instanceof ILRUCacheable ) { return ( ( ILRUCacheable ) value ) . getCacheFootprint ( ) ; } return ; } public String toString ( ) { return "" + ( fCurrentSpace * / fSpaceLimit ) + "" + this . toStringContents ( ) ; } protected String toStringContents ( ) { StringBuffer result = new StringBuffer ( ) ; int length = fEntryTable . size ( ) ; Object [ ] unsortedKeys = new Object [ length ] ; String [ ] unsortedToStrings = new String [ length ] ; Enumeration e = this . keys ( ) ; for ( int i = ; i < length ; i ++ ) { Object key = e . nextElement ( ) ; unsortedKeys [ i ] = key ; unsortedToStrings [ i ] = ( key instanceof RubyElement ) ? ( ( RubyElement ) key ) . getElementName ( ) : key . toString ( ) ; } ToStringSorter sorter = new ToStringSorter ( ) ; sorter . sort ( unsortedKeys , unsortedToStrings ) ; for ( int i = ; i < length ; i ++ ) { String toString = sorter . sortedStrings [ i ] ; Object value = this . get ( sorter . sortedObjects [ i ] ) ; result . append ( toString ) ; result . append ( "" ) ; result . append ( value ) ; result . append ( "" ) ; } return result . toString ( ) ; } public String toStringFillingRation ( String cacheName ) { StringBuffer buffer = new StringBuffer ( cacheName ) ; buffer . append ( '' ) ; buffer . append ( getSpaceLimit ( ) ) ; buffer . append ( "" ) ; buffer . append ( NumberFormat . getInstance ( ) . format ( fillingRatio ( ) ) ) ; buffer . append ( "" ) ; return buffer . toString ( ) ; } public double fillingRatio ( ) { return ( fCurrentSpace ) * / fSpaceLimit ; } protected void updateTimestamp ( LRUCacheEntry entry ) { entry . _fTimestamp = fTimestampCounter ++ ; if ( fEntryQueue != entry ) { this . privateRemoveEntry ( entry , true ) ; this . privateAddEntry ( entry , true ) ; } return ; } } package org . rubypeople . rdt . internal . core . buffer ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . SafeRunner ; import org . rubypeople . rdt . core . BufferChangedEvent ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IBufferChangedListener ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyElement ; public class Buffer implements IBuffer { protected IFile file ; protected int flags ; protected char [ ] contents ; protected List < IBufferChangedListener > changeListeners ; protected IOpenable owner ; protected int gapStart = - ; protected int gapEnd = - ; protected Object lock = new Object ( ) ; protected static final int F_HAS_UNSAVED_CHANGES = ; protected static final int F_IS_READ_ONLY = ; protected static final int F_IS_CLOSED = ; protected Buffer ( IFile file , IOpenable owner , boolean readOnly ) { this . file = file ; this . owner = owner ; if ( file == null ) { setReadOnly ( readOnly ) ; } } public void addBufferChangedListener ( IBufferChangedListener listener ) { if ( this . changeListeners == null ) { this . changeListeners = new ArrayList < IBufferChangedListener > ( ) ; } if ( ! this . changeListeners . contains ( listener ) ) { this . changeListeners . add ( listener ) ; } } public void append ( char [ ] text ) { if ( ! isReadOnly ( ) ) { if ( text == null || text . length == ) { return ; } int length = getLength ( ) ; synchronized ( this . lock ) { if ( this . contents == null ) return ; moveAndResizeGap ( length , text . length ) ; System . arraycopy ( text , , this . contents , length , text . length ) ; this . gapStart += text . length ; this . flags |= F_HAS_UNSAVED_CHANGES ; } notifyChanged ( new BufferChangedEvent ( this , length , , new String ( text ) ) ) ; } } public void append ( String text ) { if ( text == null ) { return ; } this . append ( text . toCharArray ( ) ) ; } public void close ( ) { BufferChangedEvent event = null ; synchronized ( this . lock ) { if ( isClosed ( ) ) return ; event = new BufferChangedEvent ( this , , , null ) ; this . contents = null ; this . flags |= F_IS_CLOSED ; } notifyChanged ( event ) ; this . changeListeners = null ; } public char getChar ( int position ) { synchronized ( this . lock ) { if ( this . contents == null ) return Character . MIN_VALUE ; if ( position < this . gapStart ) { return this . contents [ position ] ; } int gapLength = this . gapEnd - this . gapStart ; return this . contents [ position + gapLength ] ; } } public char [ ] getCharacters ( ) { synchronized ( this . lock ) { if ( this . contents == null ) return null ; if ( this . gapStart < ) { return this . contents ; } int length = this . contents . length ; char [ ] newContents = new char [ length - this . gapEnd + this . gapStart ] ; System . arraycopy ( this . contents , , newContents , , this . gapStart ) ; System . arraycopy ( this . contents , this . gapEnd , newContents , this . gapStart , length - this . gapEnd ) ; return newContents ; } } public String getContents ( ) { char [ ] chars = this . getCharacters ( ) ; if ( chars == null ) return null ; return new String ( chars ) ; } public int getLength ( ) { synchronized ( this . lock ) { if ( this . contents == null ) return - ; int length = this . gapEnd - this . gapStart ; return ( this . contents . length - length ) ; } } public IOpenable getOwner ( ) { return this . owner ; } public String getText ( int offset , int length ) { synchronized ( this . lock ) { if ( this . contents == null ) return "" ; if ( offset + length < this . gapStart ) return new String ( this . contents , offset , length ) ; if ( this . gapStart < offset ) { int gapLength = this . gapEnd - this . gapStart ; return new String ( this . contents , offset + gapLength , length ) ; } StringBuffer buf = new StringBuffer ( ) ; buf . append ( this . contents , offset , this . gapStart - offset ) ; buf . append ( this . contents , this . gapEnd , offset + length - this . gapStart ) ; return buf . toString ( ) ; } } public IResource getUnderlyingResource ( ) { return this . file ; } public boolean hasUnsavedChanges ( ) { return ( this . flags & F_HAS_UNSAVED_CHANGES ) != ; } public boolean isClosed ( ) { return ( this . flags & F_IS_CLOSED ) != ; } public boolean isReadOnly ( ) { return ( this . flags & F_IS_READ_ONLY ) != ; } protected void moveAndResizeGap ( int position , int size ) { char [ ] content = null ; int oldSize = this . gapEnd - this . gapStart ; if ( size < ) { if ( oldSize > ) { content = new char [ this . contents . length - oldSize ] ; System . arraycopy ( this . contents , , content , , this . gapStart ) ; System . arraycopy ( this . contents , this . gapEnd , content , this . gapStart , content . length - this . gapStart ) ; this . contents = content ; } this . gapStart = this . gapEnd = position ; return ; } content = new char [ this . contents . length + ( size - oldSize ) ] ; int newGapStart = position ; int newGapEnd = newGapStart + size ; if ( oldSize == ) { System . arraycopy ( this . contents , , content , , newGapStart ) ; System . arraycopy ( this . contents , newGapStart , content , newGapEnd , content . length - newGapEnd ) ; } else if ( newGapStart < this . gapStart ) { int delta = this . gapStart - newGapStart ; System . arraycopy ( this . contents , , content , , newGapStart ) ; System . arraycopy ( this . contents , newGapStart , content , newGapEnd , delta ) ; System . arraycopy ( this . contents , this . gapEnd , content , newGapEnd + delta , this . contents . length - this . gapEnd ) ; } else { int delta = newGapStart - this . gapStart ; System . arraycopy ( this . contents , , content , , this . gapStart ) ; System . arraycopy ( this . contents , this . gapEnd , content , this . gapStart , delta ) ; System . arraycopy ( this . contents , this . gapEnd + delta , content , newGapEnd , content . length - newGapEnd ) ; } this . contents = content ; this . gapStart = newGapStart ; this . gapEnd = newGapEnd ; } protected void notifyChanged ( final BufferChangedEvent event ) { if ( this . changeListeners != null ) { for ( int i = , size = this . changeListeners . size ( ) ; i < size ; ++ i ) { final IBufferChangedListener listener = ( IBufferChangedListener ) this . changeListeners . get ( i ) ; SafeRunner . run ( new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { } public void run ( ) throws Exception { listener . bufferChanged ( event ) ; } } ) ; } } } public void removeBufferChangedListener ( IBufferChangedListener listener ) { if ( this . changeListeners != null ) { this . changeListeners . remove ( listener ) ; if ( this . changeListeners . size ( ) == ) { this . changeListeners = null ; } } } public void replace ( int position , int length , char [ ] text ) { if ( ! isReadOnly ( ) ) { int textLength = text == null ? : text . length ; synchronized ( this . lock ) { if ( this . contents == null ) return ; moveAndResizeGap ( position + length , textLength - length ) ; int min = Math . min ( textLength , length ) ; if ( min > ) { System . arraycopy ( text , , this . contents , position , min ) ; } if ( length > textLength ) { this . gapStart -= length - textLength ; } else if ( textLength > length ) { this . gapStart += textLength - length ; System . arraycopy ( text , , this . contents , position , textLength ) ; } this . flags |= F_HAS_UNSAVED_CHANGES ; } String string = null ; if ( textLength > ) { string = new String ( text ) ; } notifyChanged ( new BufferChangedEvent ( this , position , length , string ) ) ; } } public void replace ( int position , int length , String text ) { this . replace ( position , length , text == null ? null : text . toCharArray ( ) ) ; } public void save ( IProgressMonitor progress , boolean force ) throws RubyModelException { if ( isReadOnly ( ) || this . file == null ) { return ; } if ( ! hasUnsavedChanges ( ) ) return ; try { String encoding = null ; try { encoding = this . file . getCharset ( ) ; } catch ( CoreException ce ) { } String stringContents = this . getContents ( ) ; if ( stringContents == null ) return ; byte [ ] bytes = encoding == null ? stringContents . getBytes ( ) : stringContents . getBytes ( encoding ) ; ByteArrayInputStream stream = new ByteArrayInputStream ( bytes ) ; if ( this . file . exists ( ) ) { this . file . setContents ( stream , force ? IResource . FORCE | IResource . KEEP_HISTORY : IResource . KEEP_HISTORY , null ) ; } else { this . file . create ( stream , force , null ) ; } } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } this . flags &= ~ ( F_HAS_UNSAVED_CHANGES ) ; } public void setContents ( char [ ] newContents ) { if ( this . contents == null ) { synchronized ( this . lock ) { this . contents = newContents ; this . flags &= ~ ( F_HAS_UNSAVED_CHANGES ) ; } return ; } if ( ! isReadOnly ( ) ) { String string = null ; if ( newContents != null ) { string = new String ( newContents ) ; } synchronized ( this . lock ) { if ( this . contents == null ) return ; this . contents = newContents ; this . flags |= F_HAS_UNSAVED_CHANGES ; this . gapStart = - ; this . gapEnd = - ; } BufferChangedEvent event = new BufferChangedEvent ( this , , this . getLength ( ) , string ) ; notifyChanged ( event ) ; } } public void setContents ( String newContents ) { this . setContents ( newContents . toCharArray ( ) ) ; } protected void setReadOnly ( boolean readOnly ) { if ( readOnly ) { this . flags |= F_IS_READ_ONLY ; } else { this . flags &= ~ ( F_IS_READ_ONLY ) ; } } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" + ( ( RubyElement ) this . owner ) . toString ( ) ) ; buffer . append ( "" + this . hasUnsavedChanges ( ) ) ; buffer . append ( "" + this . isReadOnly ( ) ) ; buffer . append ( "" + this . isClosed ( ) ) ; buffer . append ( "" ) ; char [ ] charContents = this . getCharacters ( ) ; if ( charContents == null ) { buffer . append ( "" ) ; } else { int length = charContents . length ; for ( int i = ; i < length ; i ++ ) { char c = charContents [ i ] ; switch ( c ) { case '' : buffer . append ( "" ) ; break ; case '' : if ( i < length - && this . contents [ i + ] == '' ) { buffer . append ( "" ) ; i ++ ; } else { buffer . append ( "" ) ; } break ; default : buffer . append ( c ) ; break ; } } } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core . buffer ; public interface ILRUCacheable { public int getCacheFootprint ( ) ; } package org . rubypeople . rdt . internal . core ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . util . Properties ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . rubypeople . rdt . core . RubyCore ; public class SetExecutableBits extends Job { public SetExecutableBits ( ) { super ( "" ) ; setSystem ( true ) ; } @ Override protected IStatus run ( IProgressMonitor monitor ) { if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) return Status . OK_STATUS ; try { Properties props = new Properties ( ) ; InputStream inStream = FileLocator . openStream ( Platform . getBundle ( "" ) , new Path ( "" ) , false ) ; props . load ( inStream ) ; String raw = props . getProperty ( "" ) ; String [ ] paths = raw . split ( "" ) ; for ( int i = ; i < paths . length ; i ++ ) { URL bundleURL = FileLocator . find ( Platform . getBundle ( "" ) , new Path ( paths [ i ] ) , null ) ; if ( bundleURL == null ) continue ; URL fileURL = FileLocator . toFileURL ( bundleURL ) ; if ( fileURL == null ) continue ; setExecutableBit ( fileURL . getPath ( ) ) ; } } catch ( IOException e ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , , e . getMessage ( ) , e ) ; } return Status . OK_STATUS ; } private void setExecutableBit ( String filePath ) { if ( filePath == null ) return ; try { Process pr = Runtime . getRuntime ( ) . exec ( new String [ ] { "" , "" , filePath } ) ; Thread chmodOutput = new StreamConsumer ( pr . getInputStream ( ) ) ; chmodOutput . setName ( "" ) ; chmodOutput . start ( ) ; Thread chmodError = new StreamConsumer ( pr . getErrorStream ( ) ) ; chmodError . setName ( "" ) ; chmodError . start ( ) ; } catch ( IOException ioe ) { RubyCore . log ( ioe ) ; } } public static class StreamConsumer extends Thread { InputStream is ; byte [ ] buf ; public StreamConsumer ( InputStream inputStream ) { super ( ) ; this . setDaemon ( true ) ; this . is = inputStream ; buf = new byte [ ] ; } public void run ( ) { try { int n = ; while ( n >= ) n = is . read ( buf ) ; } catch ( IOException ioe ) { } } } } package org . rubypeople . rdt . internal . core ; import java . text . NumberFormat ; import java . util . HashMap ; import java . util . Map ; import org . rubypeople . rdt . core . IRubyElement ; public class RubyModelCache { public static final int CACHE_RATIO = ; protected RubyModelInfo modelInfo ; protected HashMap projectCache ; protected ElementCache folderCache ; protected ElementCache rootCache ; protected ElementCache openableCache ; protected Map childrenCache ; public static final int DEFAULT_PROJECT_SIZE = ; public static final int DEFAULT_ROOT_SIZE = ; public static final int DEFAULT_FOLDER_SIZE = ; public static final int DEFAULT_OPENABLE_SIZE = ; public static final int DEFAULT_CHILDREN_SIZE = * ; protected double memoryRatio = - ; public RubyModelCache ( ) { double ratio = getMemoryRatio ( ) ; this . rootCache = new ElementCache ( ( int ) ( DEFAULT_ROOT_SIZE * ratio ) ) ; this . projectCache = new HashMap ( DEFAULT_PROJECT_SIZE ) ; this . openableCache = new ElementCache ( ( int ) ( DEFAULT_OPENABLE_SIZE * ratio ) ) ; this . folderCache = new ElementCache ( ( int ) ( DEFAULT_FOLDER_SIZE * ratio ) ) ; this . childrenCache = new HashMap ( ( int ) ( DEFAULT_CHILDREN_SIZE * ratio ) ) ; } protected double getMemoryRatio ( ) { if ( this . memoryRatio == - ) { long maxMemory = Runtime . getRuntime ( ) . maxMemory ( ) ; this . memoryRatio = maxMemory == Long . MAX_VALUE ? : ( ( double ) maxMemory ) / ( * ) ; } return this . memoryRatio ; } public Object getInfo ( IRubyElement element ) { switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : return this . modelInfo ; case IRubyElement . RUBY_PROJECT : return this . projectCache . get ( element ) ; case IRubyElement . SOURCE_FOLDER_ROOT : return this . rootCache . get ( element ) ; case IRubyElement . SOURCE_FOLDER : return this . folderCache . get ( element ) ; case IRubyElement . SCRIPT : return this . openableCache . get ( element ) ; default : return this . childrenCache . get ( element ) ; } } protected Object peekAtInfo ( IRubyElement element ) { switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : return this . modelInfo ; case IRubyElement . RUBY_PROJECT : return this . projectCache . get ( element ) ; case IRubyElement . SOURCE_FOLDER_ROOT : return this . rootCache . peek ( element ) ; case IRubyElement . SOURCE_FOLDER : return this . folderCache . peek ( element ) ; case IRubyElement . SCRIPT : return this . openableCache . peek ( element ) ; default : return this . childrenCache . get ( element ) ; } } protected void putInfo ( IRubyElement element , Object info ) { switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : this . modelInfo = ( RubyModelInfo ) info ; break ; case IRubyElement . RUBY_PROJECT : this . projectCache . put ( element , info ) ; this . rootCache . ensureSpaceLimit ( ( ( RubyElementInfo ) info ) . children . length , element ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : this . rootCache . put ( element , info ) ; this . folderCache . ensureSpaceLimit ( ( ( RubyElementInfo ) info ) . children . length , element ) ; break ; case IRubyElement . SOURCE_FOLDER : this . folderCache . put ( element , info ) ; this . openableCache . ensureSpaceLimit ( ( ( RubyElementInfo ) info ) . children . length , element ) ; break ; case IRubyElement . SCRIPT : this . openableCache . put ( element , info ) ; break ; default : this . childrenCache . put ( element , info ) ; } } protected void removeInfo ( IRubyElement element ) { switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : this . modelInfo = null ; break ; case IRubyElement . RUBY_PROJECT : this . projectCache . remove ( element ) ; this . rootCache . resetSpaceLimit ( ( int ) ( DEFAULT_ROOT_SIZE * getMemoryRatio ( ) ) , element ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : this . rootCache . remove ( element ) ; this . folderCache . resetSpaceLimit ( ( int ) ( DEFAULT_FOLDER_SIZE * getMemoryRatio ( ) ) , element ) ; break ; case IRubyElement . SOURCE_FOLDER : this . folderCache . remove ( element ) ; this . openableCache . resetSpaceLimit ( ( int ) ( DEFAULT_OPENABLE_SIZE * getMemoryRatio ( ) ) , element ) ; break ; case IRubyElement . SCRIPT : this . openableCache . remove ( element ) ; break ; default : this . childrenCache . remove ( element ) ; } } public String toStringFillingRation ( String prefix ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( prefix ) ; buffer . append ( "" ) ; buffer . append ( this . projectCache . size ( ) ) ; buffer . append ( "" ) ; buffer . append ( prefix ) ; buffer . append ( this . rootCache . toStringFillingRation ( "" ) ) ; buffer . append ( '' ) ; buffer . append ( prefix ) ; buffer . append ( this . folderCache . toStringFillingRation ( "" ) ) ; buffer . append ( '' ) ; buffer . append ( prefix ) ; buffer . append ( "" ) ; buffer . append ( NumberFormat . getInstance ( ) . format ( this . openableCache . fillingRatio ( ) ) ) ; buffer . append ( "" ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor ; public class RubyScriptStructureBuilder implements ISourceElementRequestor { private InfoStack infoStack ; private HandleStack modelStack ; private RubyScriptElementInfo scriptInfo ; private IRubyScript script ; private Map < IRubyElement , RubyElementInfo > newElements ; private RubyElementInfo importContainerInfo ; public RubyScriptStructureBuilder ( IRubyScript script , RubyScriptElementInfo info , Map < IRubyElement , RubyElementInfo > newElements ) { this . script = script ; this . scriptInfo = info ; this . newElements = newElements ; infoStack = new InfoStack ( ) ; modelStack = new HandleStack ( ) ; modelStack . push ( script ) ; infoStack . push ( scriptInfo ) ; } private RubyElementInfo getCurrentTypeInfo ( ) { List < RubyElementInfo > extras = new ArrayList < RubyElementInfo > ( ) ; RubyElementInfo element = infoStack . peek ( ) ; while ( ! ( element instanceof RubyTypeElementInfo ) ) { extras . add ( infoStack . pop ( ) ) ; element = infoStack . peek ( ) ; if ( element == null ) break ; } Collections . reverse ( extras ) ; for ( Iterator < RubyElementInfo > iter = extras . iterator ( ) ; iter . hasNext ( ) ; ) { infoStack . push ( iter . next ( ) ) ; } if ( element == null ) return scriptInfo ; return element ; } private RubyType findChild ( RubyElement parent , int type , String name ) { try { if ( ! parent . exists ( ) ) return null ; List < IRubyElement > children = parent . getChildrenOfType ( type ) ; for ( IRubyElement element : children ) { if ( element . getElementName ( ) . equals ( name ) ) return ( RubyType ) element ; } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } return null ; } private RubyElement getCurrentType ( ) { List < IRubyElement > extras = new ArrayList < IRubyElement > ( ) ; IRubyElement element = modelStack . peek ( ) ; while ( ! element . isType ( IRubyElement . TYPE ) ) { extras . add ( modelStack . pop ( ) ) ; element = modelStack . peek ( ) ; if ( element == null ) break ; } Collections . reverse ( extras ) ; for ( Iterator < IRubyElement > iter = extras . iterator ( ) ; iter . hasNext ( ) ; ) { modelStack . push ( iter . next ( ) ) ; } if ( element == null ) return ( RubyScript ) script ; return ( RubyElement ) element ; } public void acceptConstructorReference ( String name , int argCount , int offset ) { } public void acceptFieldReference ( String name , int offset ) { } public void acceptImport ( String value , int startOffset , int endOffset ) { ImportContainer importContainer = ( ImportContainer ) script . getImportContainer ( ) ; if ( this . importContainerInfo == null ) { this . importContainerInfo = new RubyElementInfo ( ) ; scriptInfo . addChild ( importContainer ) ; this . newElements . put ( importContainer , this . importContainerInfo ) ; } RubyImport handle = new RubyImport ( importContainer , value ) ; ImportDeclarationElementInfo info = new ImportDeclarationElementInfo ( ) ; info . setNameSourceStart ( startOffset ) ; info . setNameSourceEnd ( endOffset ) ; info . setSourceRangeStart ( startOffset ) ; info . setSourceRangeEnd ( endOffset ) ; info . name = value ; this . importContainerInfo . addChild ( handle ) ; this . newElements . put ( handle , info ) ; } public void acceptMethodReference ( String name , int argCount , int offset ) { } public void acceptProblem ( CategorizedProblem problem ) { } public void acceptTypeReference ( String name , int startOffset , int endOffset ) { } public void acceptUnknownReference ( String name , int startOffset , int endOffset ) { } public void enterConstructor ( MethodInfo constructor ) { enterMethod ( constructor ) ; } public void enterField ( FieldInfo field ) { RubyField handle ; if ( field . name . startsWith ( "" ) ) { handle = new RubyClassVar ( getCurrentType ( ) , field . name ) ; } else if ( field . name . startsWith ( "" ) ) { handle = new RubyInstVar ( getCurrentType ( ) , field . name ) ; } else if ( field . name . startsWith ( "" ) ) { handle = new RubyGlobal ( script , field . name ) ; } else if ( Character . isUpperCase ( field . name . charAt ( ) ) ) { handle = new RubyConstant ( getCurrentType ( ) , field . name ) ; } else { int start = field . declarationStart - field . name . length ( ) + ; int end = start + field . name . length ( ) ; if ( field . isDynamic ) { handle = new RubyDynamicVar ( modelStack . peek ( ) , field . name , start , end ) ; } else { handle = new LocalVariable ( modelStack . peek ( ) , field . name , start , end ) ; } } modelStack . push ( handle ) ; RubyElementInfo parentInfo ; if ( handle instanceof LocalVariable || handle instanceof RubyDynamicVar ) { parentInfo = infoStack . peek ( ) ; } else if ( handle instanceof RubyGlobal ) { parentInfo = scriptInfo ; } else { parentInfo = getCurrentTypeInfo ( ) ; } parentInfo . addChild ( handle ) ; RubyFieldElementInfo info = new RubyFieldElementInfo ( ) ; info . setSourceRangeStart ( field . declarationStart ) ; info . setNameSourceStart ( field . nameSourceStart ) ; info . setNameSourceEnd ( field . nameSourceEnd ) ; infoStack . push ( info ) ; newElements . put ( handle , info ) ; } public void enterMethod ( MethodInfo methodInfo ) { RubyMethod method = new RubyMethod ( getCurrentType ( ) , methodInfo . name , methodInfo . parameterNames ) ; modelStack . push ( method ) ; infoStack . peek ( ) . addChild ( method ) ; RubyMethodElementInfo info = new RubyMethodElementInfo ( ) ; info . setArgumentNames ( methodInfo . parameterNames ) ; info . setVisibility ( methodInfo . visibility ) ; info . setNameSourceStart ( methodInfo . nameSourceStart ) ; info . setNameSourceEnd ( methodInfo . nameSourceEnd ) ; info . setSourceRangeStart ( methodInfo . declarationStart ) ; info . setIsSingleton ( methodInfo . isClassLevel ) ; infoStack . push ( info ) ; newElements . put ( method , info ) ; } public void acceptYield ( String name ) { ( ( RubyMethodElementInfo ) infoStack . peek ( ) ) . addBlockVar ( name ) ; } public void enterScript ( ) { } public void enterType ( TypeInfo type ) { RubyType handle ; if ( type . isModule ) { handle = new RubyModule ( modelStack . peek ( ) , type . name ) ; } else { handle = new RubyType ( modelStack . peek ( ) , type . name ) ; } RubyElement parent = modelStack . peek ( ) ; RubyType existing = findChild ( parent , IRubyElement . TYPE , type . name ) ; if ( existing != null ) { handle . occurrenceCount = existing . occurrenceCount + ; } modelStack . push ( handle ) ; infoStack . peek ( ) . addChild ( handle ) ; RubyTypeElementInfo info = new RubyTypeElementInfo ( ) ; info . setHandle ( handle ) ; info . setNameSourceStart ( type . nameSourceStart ) ; info . setNameSourceEnd ( type . nameSourceEnd ) ; info . setSourceRangeStart ( type . declarationStart ) ; info . setSuperclassName ( type . superclass ) ; info . setIncludedModuleNames ( type . modules ) ; infoStack . push ( info ) ; newElements . put ( handle , info ) ; } public void exitConstructor ( int endOffset ) { exitMethod ( endOffset ) ; } public void exitField ( int endOffset ) { RubyFieldElementInfo info = ( RubyFieldElementInfo ) infoStack . pop ( ) ; info . setSourceRangeEnd ( endOffset ) ; modelStack . pop ( ) ; } public void exitMethod ( int endOffset ) { RubyMethodElementInfo info = ( RubyMethodElementInfo ) infoStack . pop ( ) ; info . setSourceRangeEnd ( endOffset ) ; modelStack . pop ( ) ; } public void exitScript ( int endOffset ) { modelStack . pop ( ) ; infoStack . pop ( ) ; } public void exitType ( int endOffset ) { RubyTypeElementInfo info = ( RubyTypeElementInfo ) infoStack . pop ( ) ; info . setSourceRangeEnd ( endOffset ) ; modelStack . pop ( ) ; } public void acceptMixin ( String string ) { RubyElementInfo info = getCurrentTypeInfo ( ) ; if ( ! ( info instanceof RubyTypeElementInfo ) ) return ; RubyTypeElementInfo parentType = ( RubyTypeElementInfo ) info ; String [ ] importedModuleNames = parentType . getIncludedModuleNames ( ) ; List < String > mergedModuleNames = new LinkedList < String > ( ) ; if ( importedModuleNames != null ) { mergedModuleNames . addAll ( ( Arrays . asList ( importedModuleNames ) ) ) ; } mergedModuleNames . add ( string ) ; String [ ] newIncludedModuleNames = mergedModuleNames . toArray ( new String [ ] { } ) ; parentType . setIncludedModuleNames ( newIncludedModuleNames ) ; } public void acceptMethodVisibilityChange ( String methodName , int visibility ) { RubyElementInfo info = getCurrentTypeInfo ( ) ; if ( ! ( info instanceof RubyTypeElementInfo ) ) return ; RubyTypeElementInfo parentType = ( RubyTypeElementInfo ) info ; IMethod [ ] methods = parentType . getMethods ( ) ; for ( int i = ; i < methods . length ; i ++ ) { RubyMethod method = ( RubyMethod ) methods [ i ] ; if ( ! method . getElementName ( ) . equals ( methodName ) ) continue ; ; try { RubyMethodElementInfo methodInfo = ( RubyMethodElementInfo ) method . getElementInfo ( ) ; methodInfo . setVisibility ( visibility ) ; return ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } } public void acceptModuleFunction ( String methodName ) { RubyElementInfo info = getCurrentTypeInfo ( ) ; if ( ! ( info instanceof RubyTypeElementInfo ) ) return ; RubyTypeElementInfo parentType = ( RubyTypeElementInfo ) info ; IMethod [ ] methods = parentType . getMethods ( ) ; for ( int i = ; i < methods . length ; i ++ ) { RubyMethod method = ( RubyMethod ) methods [ i ] ; if ( ! method . getElementName ( ) . equals ( methodName ) ) continue ; try { RubyMethodElementInfo methodInfo = ( RubyMethodElementInfo ) method . getElementInfo ( ) ; methodInfo . setIsSingleton ( true ) ; return ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } } public void acceptBlock ( int startOffset , int endOffset ) { RubyBlock method = new RubyBlock ( modelStack . peek ( ) ) ; infoStack . peek ( ) . addChild ( method ) ; SourceRefElementInfo info = new SourceRefElementInfo ( ) ; info . setSourceRangeStart ( startOffset ) ; info . setSourceRangeEnd ( endOffset ) ; newElements . put ( method , info ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; public class ImportContainer extends SourceRefElement implements IImportContainer { protected ImportContainer ( RubyScript parent ) { super ( parent ) ; } public boolean equals ( Object o ) { if ( ! ( o instanceof ImportContainer ) ) return false ; return super . equals ( o ) ; } public String getElementName ( ) { return "" ; } public int getElementType ( ) { return IMPORT_CONTAINER ; } public IImportDeclaration getImport ( String importName ) { return new RubyImport ( this , importName ) ; } public IRubyElement getPrimaryElement ( boolean checkOwner ) { RubyScript cu = ( RubyScript ) this . parent ; if ( checkOwner && cu . isPrimary ( ) ) return this ; return cu . getImportContainer ( ) ; } public ISourceRange getSourceRange ( ) throws RubyModelException { IRubyElement [ ] imports = getChildren ( ) ; ISourceRange firstRange = ( ( ISourceReference ) imports [ ] ) . getSourceRange ( ) ; ISourceRange lastRange = ( ( ISourceReference ) imports [ imports . length - ] ) . getSourceRange ( ) ; SourceRange range = new SourceRange ( firstRange . getOffset ( ) , lastRange . getOffset ( ) + lastRange . getLength ( ) - firstRange . getOffset ( ) ) ; return range ; } public boolean hasChildren ( ) { return true ; } public String readableName ( ) { return null ; } protected void toString ( int tab , StringBuffer buffer ) { Object info = RubyModelManager . getRubyModelManager ( ) . peekAtInfo ( this ) ; if ( info == null || ! ( info instanceof RubyElementInfo ) ) return ; IRubyElement [ ] children = ( ( RubyElementInfo ) info ) . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( i > ) buffer . append ( "" ) ; ( ( RubyElement ) children [ i ] ) . toString ( tab , buffer ) ; } } protected void toStringInfo ( int tab , StringBuffer buffer , Object info ) { buffer . append ( this . tabString ( tab ) ) ; buffer . append ( "" ) ; if ( info == null ) { buffer . append ( "" ) ; } } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner workingCopyOwner ) { switch ( token . charAt ( ) ) { case JEM_COUNT : return getHandleUpdatingCountFromMemento ( memento , workingCopyOwner ) ; case JEM_IMPORTDECLARATION : if ( memento . hasMoreTokens ( ) ) { String importName = memento . nextToken ( ) ; RubyElement importDecl = ( RubyElement ) getImport ( importName ) ; return importDecl . getHandleFromMemento ( memento , workingCopyOwner ) ; } else { return this ; } } return null ; } protected char getHandleMementoDelimiter ( ) { return RubyElement . JEM_IMPORTDECLARATION ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . runtime . IProgressMonitor ; public class RubyDynamicVar extends LocalVariable { public RubyDynamicVar ( RubyElement parent , String name , int start , int end ) { super ( parent , name , start , end ) ; } public int getElementType ( ) { return RubyElement . DYNAMIC_VAR ; } protected void generateInfos ( IProgressMonitor pm ) { } } package org . rubypeople . rdt . internal . core . index ; import org . rubypeople . rdt . internal . compiler . util . HashtableOfObject ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class EntryResult { private char [ ] word ; private HashtableOfObject [ ] documentTables ; private SimpleSet documentNames ; public EntryResult ( char [ ] word , HashtableOfObject table ) { this . word = word ; if ( table != null ) this . documentTables = new HashtableOfObject [ ] { table } ; } public void addDocumentName ( String documentName ) { if ( this . documentNames == null ) this . documentNames = new SimpleSet ( ) ; this . documentNames . add ( documentName ) ; } public void addDocumentTable ( HashtableOfObject table ) { if ( this . documentTables != null ) { int length = this . documentTables . length ; System . arraycopy ( this . documentTables , , this . documentTables = new HashtableOfObject [ length + ] , , length ) ; this . documentTables [ length ] = table ; } else { this . documentTables = new HashtableOfObject [ ] { table } ; } } public char [ ] getWord ( ) { return this . word ; } public String [ ] getDocumentNames ( Index index ) throws java . io . IOException { if ( this . documentTables != null ) { int length = this . documentTables . length ; if ( length == && this . documentNames == null ) { Object offset = this . documentTables [ ] . get ( word ) ; int [ ] numbers = index . diskIndex . readDocumentNumbers ( offset ) ; String [ ] names = new String [ numbers . length ] ; for ( int i = , l = numbers . length ; i < l ; i ++ ) names [ i ] = index . diskIndex . readDocumentName ( numbers [ i ] ) ; return names ; } for ( int i = ; i < length ; i ++ ) { Object offset = this . documentTables [ i ] . get ( word ) ; int [ ] numbers = index . diskIndex . readDocumentNumbers ( offset ) ; for ( int j = , k = numbers . length ; j < k ; j ++ ) addDocumentName ( index . diskIndex . readDocumentName ( numbers [ j ] ) ) ; } } if ( this . documentNames == null ) return CharOperation . NO_STRINGS ; String [ ] names = new String [ this . documentNames . elementSize ] ; int count = ; Object [ ] values = this . documentNames . values ; for ( int i = , l = values . length ; i < l ; i ++ ) if ( values [ i ] != null ) names [ count ++ ] = ( String ) values [ i ] ; return names ; } public boolean isEmpty ( ) { return this . documentTables == null && this . documentNames == null ; } } package org . rubypeople . rdt . internal . core . index ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . HashtableOfObject ; import org . rubypeople . rdt . internal . compiler . util . SimpleLookupTable ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . core . util . SimpleWordSet ; public class MemoryIndex { public int NUM_CHANGES = ; SimpleLookupTable docsToReferences ; SimpleWordSet allWords ; String lastDocumentName ; HashtableOfObject lastReferenceTable ; MemoryIndex ( ) { this . docsToReferences = new SimpleLookupTable ( ) ; this . allWords = new SimpleWordSet ( ) ; } void addDocumentNames ( String substring , SimpleSet results ) { Object [ ] paths = this . docsToReferences . keyTable ; Object [ ] referenceTables = this . docsToReferences . valueTable ; if ( substring == null ) { for ( int i = , l = referenceTables . length ; i < l ; i ++ ) if ( referenceTables [ i ] != null ) results . add ( paths [ i ] ) ; } else { for ( int i = , l = referenceTables . length ; i < l ; i ++ ) if ( referenceTables [ i ] != null && ( ( String ) paths [ i ] ) . startsWith ( substring , ) ) results . add ( paths [ i ] ) ; } } void addIndexEntry ( char [ ] category , char [ ] key , String documentName ) { HashtableOfObject referenceTable ; if ( documentName . equals ( this . lastDocumentName ) ) referenceTable = this . lastReferenceTable ; else { referenceTable = ( HashtableOfObject ) this . docsToReferences . get ( documentName ) ; if ( referenceTable == null ) this . docsToReferences . put ( documentName , referenceTable = new HashtableOfObject ( ) ) ; this . lastDocumentName = documentName ; this . lastReferenceTable = referenceTable ; } SimpleWordSet existingWords = ( SimpleWordSet ) referenceTable . get ( category ) ; if ( existingWords == null ) referenceTable . put ( category , existingWords = new SimpleWordSet ( ) ) ; existingWords . add ( this . allWords . add ( key ) ) ; } HashtableOfObject addQueryResults ( char [ ] [ ] categories , char [ ] key , int matchRule , HashtableOfObject results ) { Object [ ] paths = this . docsToReferences . keyTable ; Object [ ] referenceTables = this . docsToReferences . valueTable ; if ( matchRule == ( SearchPattern . R_EXACT_MATCH | SearchPattern . R_CASE_SENSITIVE ) && key != null ) { nextPath : for ( int i = , l = referenceTables . length ; i < l ; i ++ ) { HashtableOfObject categoryToWords = ( HashtableOfObject ) referenceTables [ i ] ; if ( categoryToWords != null ) { for ( int j = , m = categories . length ; j < m ; j ++ ) { SimpleWordSet wordSet = ( SimpleWordSet ) categoryToWords . get ( categories [ j ] ) ; if ( wordSet != null && wordSet . includes ( key ) ) { if ( results == null ) results = new HashtableOfObject ( ) ; EntryResult result = ( EntryResult ) results . get ( key ) ; if ( result == null ) results . put ( key , result = new EntryResult ( key , null ) ) ; result . addDocumentName ( ( String ) paths [ i ] ) ; continue nextPath ; } } } } } else { for ( int i = , l = referenceTables . length ; i < l ; i ++ ) { HashtableOfObject categoryToWords = ( HashtableOfObject ) referenceTables [ i ] ; if ( categoryToWords != null ) { for ( int j = , m = categories . length ; j < m ; j ++ ) { SimpleWordSet wordSet = ( SimpleWordSet ) categoryToWords . get ( categories [ j ] ) ; if ( wordSet != null ) { char [ ] [ ] words = wordSet . words ; for ( int k = , n = words . length ; k < n ; k ++ ) { char [ ] word = words [ k ] ; if ( word != null && Index . isMatch ( key , word , matchRule ) ) { if ( results == null ) results = new HashtableOfObject ( ) ; EntryResult result = ( EntryResult ) results . get ( word ) ; if ( result == null ) results . put ( word , result = new EntryResult ( word , null ) ) ; result . addDocumentName ( ( String ) paths [ i ] ) ; } } } } } } } return results ; } boolean hasChanged ( ) { return this . docsToReferences . elementSize > ; } void remove ( String documentName ) { if ( documentName . equals ( this . lastDocumentName ) ) { this . lastDocumentName = null ; this . lastReferenceTable = null ; } this . docsToReferences . put ( documentName , null ) ; } boolean shouldMerge ( ) { return this . docsToReferences . elementSize >= NUM_CHANGES ; } } package org . rubypeople . rdt . internal . core . index ; import java . io . File ; import java . io . IOException ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . HashtableOfObject ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . core . search . indexing . ReadWriteMonitor ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class Index { public String containerPath ; public ReadWriteMonitor monitor ; static final char DEFAULT_SEPARATOR = '' ; public char separator = DEFAULT_SEPARATOR ; protected DiskIndex diskIndex ; protected MemoryIndex memoryIndex ; static final int MATCH_RULE_INDEX_MASK = SearchPattern . R_EXACT_MATCH | SearchPattern . R_PREFIX_MATCH | SearchPattern . R_PATTERN_MATCH | SearchPattern . R_REGEXP_MATCH | SearchPattern . R_CASE_SENSITIVE | SearchPattern . R_CAMELCASE_MATCH ; public static boolean isMatch ( char [ ] pattern , char [ ] word , int matchRule ) { if ( pattern == null ) return true ; int patternLength = pattern . length ; int wordLength = word . length ; if ( patternLength == ) return matchRule != SearchPattern . R_EXACT_MATCH ; if ( wordLength == ) return ( matchRule & SearchPattern . R_PATTERN_MATCH ) != && patternLength == && pattern [ ] == '' ; boolean isCamelCase = ( matchRule & SearchPattern . R_CAMELCASE_MATCH ) != ; if ( isCamelCase && pattern [ ] == word [ ] && CharOperation . camelCaseMatch ( pattern , word ) ) { return true ; } matchRule &= ~ SearchPattern . R_CAMELCASE_MATCH ; switch ( matchRule & MATCH_RULE_INDEX_MASK ) { case SearchPattern . R_EXACT_MATCH : if ( ! isCamelCase ) { return patternLength == wordLength && CharOperation . equals ( pattern , word , false ) ; } case SearchPattern . R_PREFIX_MATCH : return patternLength <= wordLength && CharOperation . prefixEquals ( pattern , word , false ) ; case SearchPattern . R_PATTERN_MATCH : return CharOperation . match ( pattern , word , false ) ; case SearchPattern . R_EXACT_MATCH | SearchPattern . R_CASE_SENSITIVE : if ( ! isCamelCase ) { return pattern [ ] == word [ ] && patternLength == wordLength && CharOperation . equals ( pattern , word ) ; } case SearchPattern . R_PREFIX_MATCH | SearchPattern . R_CASE_SENSITIVE : return pattern [ ] == word [ ] && patternLength <= wordLength && CharOperation . prefixEquals ( pattern , word ) ; case SearchPattern . R_PATTERN_MATCH | SearchPattern . R_CASE_SENSITIVE : return CharOperation . match ( pattern , word , true ) ; } return false ; } public Index ( String fileName , String containerPath , boolean reuseExistingFile ) throws IOException { this . containerPath = containerPath ; this . monitor = new ReadWriteMonitor ( ) ; this . memoryIndex = new MemoryIndex ( ) ; this . diskIndex = new DiskIndex ( fileName ) ; this . diskIndex . initialize ( reuseExistingFile ) ; if ( reuseExistingFile ) this . separator = this . diskIndex . separator ; } public void addIndexEntry ( char [ ] category , char [ ] key , String containerRelativePath ) { this . memoryIndex . addIndexEntry ( category , key , containerRelativePath ) ; } public String containerRelativePath ( String documentPath ) { int index = - ; if ( index == - ) { index = this . containerPath . length ( ) ; if ( documentPath . length ( ) <= index ) throw new IllegalArgumentException ( "" + documentPath + "" + this . containerPath ) ; } return documentPath . substring ( index + ) ; } public File getIndexFile ( ) { return this . diskIndex == null ? null : this . diskIndex . indexFile ; } public boolean hasChanged ( ) { return this . memoryIndex . hasChanged ( ) ; } public EntryResult [ ] query ( char [ ] [ ] categories , char [ ] key , int matchRule ) throws IOException { if ( this . memoryIndex . shouldMerge ( ) && monitor . exitReadEnterWrite ( ) ) { try { save ( ) ; } finally { monitor . exitWriteEnterRead ( ) ; } } HashtableOfObject results ; int rule = matchRule & MATCH_RULE_INDEX_MASK ; if ( this . memoryIndex . hasChanged ( ) ) { results = this . diskIndex . addQueryResults ( categories , key , rule , this . memoryIndex ) ; results = this . memoryIndex . addQueryResults ( categories , key , rule , results ) ; } else { results = this . diskIndex . addQueryResults ( categories , key , rule , null ) ; } if ( results == null ) return null ; EntryResult [ ] entryResults = new EntryResult [ results . elementSize ] ; int count = ; Object [ ] values = results . valueTable ; for ( int i = , l = values . length ; i < l ; i ++ ) { EntryResult result = ( EntryResult ) values [ i ] ; if ( result != null ) entryResults [ count ++ ] = result ; } return entryResults ; } public String [ ] queryDocumentNames ( String substring ) throws IOException { SimpleSet results ; if ( this . memoryIndex . hasChanged ( ) ) { results = this . diskIndex . addDocumentNames ( substring , this . memoryIndex ) ; this . memoryIndex . addDocumentNames ( substring , results ) ; } else { results = this . diskIndex . addDocumentNames ( substring , null ) ; } if ( results . elementSize == ) return null ; String [ ] documentNames = new String [ results . elementSize ] ; int count = ; Object [ ] paths = results . values ; for ( int i = , l = paths . length ; i < l ; i ++ ) if ( paths [ i ] != null ) documentNames [ count ++ ] = ( String ) paths [ i ] ; return documentNames ; } public void remove ( String containerRelativePath ) { this . memoryIndex . remove ( containerRelativePath ) ; } public void save ( ) throws IOException { if ( ! hasChanged ( ) ) return ; int numberOfChanges = this . memoryIndex . docsToReferences . elementSize ; this . diskIndex . separator = this . separator ; this . diskIndex = this . diskIndex . mergeWith ( this . memoryIndex ) ; this . memoryIndex = new MemoryIndex ( ) ; if ( numberOfChanges > ) System . gc ( ) ; } public void startQuery ( ) { if ( this . diskIndex != null ) this . diskIndex . startQuery ( ) ; } public void stopQuery ( ) { if ( this . diskIndex != null ) this . diskIndex . stopQuery ( ) ; } public String toString ( ) { return "" + this . containerPath ; } } package org . rubypeople . rdt . internal . core . index ; import java . io . EOFException ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . io . RandomAccessFile ; import java . io . UTFDataFormatException ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . HashtableOfIntValues ; import org . rubypeople . rdt . internal . compiler . util . HashtableOfObject ; import org . rubypeople . rdt . internal . compiler . util . SimpleLookupTable ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . compiler . util . SimpleSetOfCharArray ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . SimpleWordSet ; import org . rubypeople . rdt . internal . core . util . Util ; public class DiskIndex { File indexFile ; private int headerInfoOffset ; private int numberOfChunks ; private int sizeOfLastChunk ; private int [ ] chunkOffsets ; private int documentReferenceSize ; private int startOfCategoryTables ; private HashtableOfIntValues categoryOffsets , categoryEnds ; private int cacheUserCount ; private String [ ] [ ] cachedChunks ; private HashtableOfObject categoryTables ; private char [ ] cachedCategoryName ; private static final int DEFAULT_BUFFER_SIZE = ; private static int BUFFER_READ_SIZE = DEFAULT_BUFFER_SIZE ; private static final int BUFFER_WRITE_SIZE = DEFAULT_BUFFER_SIZE ; private byte [ ] streamBuffer ; private int bufferIndex , bufferEnd ; private int streamEnd ; char separator = Index . DEFAULT_SEPARATOR ; public static final String SIGNATURE = "" ; private static final char [ ] SIGNATURE_CHARS = SIGNATURE . toCharArray ( ) ; public static boolean DEBUG = false ; private static final int RE_INDEXED = - ; private static final int DELETED = - ; private static final int CHUNK_SIZE = ; private static final SimpleSetOfCharArray INTERNED_CATEGORY_NAMES = new SimpleSetOfCharArray ( ) ; static class IntList { int size ; int [ ] elements ; IntList ( int [ ] elements ) { this . elements = elements ; this . size = elements . length ; } void add ( int newElement ) { if ( this . size == this . elements . length ) { int newSize = this . size * ; if ( newSize < ) newSize = ; System . arraycopy ( this . elements , , this . elements = new int [ newSize ] , , this . size ) ; } this . elements [ this . size ++ ] = newElement ; } int [ ] asArray ( ) { int [ ] result = new int [ this . size ] ; System . arraycopy ( this . elements , , result , , this . size ) ; return result ; } } DiskIndex ( String fileName ) { if ( fileName == null ) throw new java . lang . IllegalArgumentException ( ) ; this . indexFile = new File ( fileName ) ; this . headerInfoOffset = - ; this . numberOfChunks = - ; this . sizeOfLastChunk = - ; this . chunkOffsets = null ; this . documentReferenceSize = - ; this . cacheUserCount = - ; this . cachedChunks = null ; this . categoryTables = null ; this . cachedCategoryName = null ; this . categoryOffsets = null ; this . categoryEnds = null ; } SimpleSet addDocumentNames ( String substring , MemoryIndex memoryIndex ) throws IOException { String [ ] docNames = readAllDocumentNames ( ) ; SimpleSet results = new SimpleSet ( docNames . length ) ; if ( substring == null ) { if ( memoryIndex == null ) { for ( int i = , l = docNames . length ; i < l ; i ++ ) results . add ( docNames [ i ] ) ; } else { SimpleLookupTable docsToRefs = memoryIndex . docsToReferences ; for ( int i = , l = docNames . length ; i < l ; i ++ ) { String docName = docNames [ i ] ; if ( ! docsToRefs . containsKey ( docName ) ) results . add ( docName ) ; } } } else { if ( memoryIndex == null ) { for ( int i = , l = docNames . length ; i < l ; i ++ ) if ( docNames [ i ] . startsWith ( substring , ) ) results . add ( docNames [ i ] ) ; } else { SimpleLookupTable docsToRefs = memoryIndex . docsToReferences ; for ( int i = , l = docNames . length ; i < l ; i ++ ) { String docName = docNames [ i ] ; if ( docName . startsWith ( substring , ) && ! docsToRefs . containsKey ( docName ) ) results . add ( docName ) ; } } } return results ; } private HashtableOfObject addQueryResult ( HashtableOfObject results , char [ ] word , HashtableOfObject wordsToDocNumbers , MemoryIndex memoryIndex ) throws IOException { if ( results == null ) results = new HashtableOfObject ( ) ; EntryResult result = ( EntryResult ) results . get ( word ) ; if ( memoryIndex == null ) { if ( result == null ) results . put ( word , new EntryResult ( word , wordsToDocNumbers ) ) ; else result . addDocumentTable ( wordsToDocNumbers ) ; } else { SimpleLookupTable docsToRefs = memoryIndex . docsToReferences ; if ( result == null ) result = new EntryResult ( word , null ) ; int [ ] docNumbers = readDocumentNumbers ( wordsToDocNumbers . get ( word ) ) ; for ( int i = , l = docNumbers . length ; i < l ; i ++ ) { String docName = readDocumentName ( docNumbers [ i ] ) ; if ( ! docsToRefs . containsKey ( docName ) ) result . addDocumentName ( docName ) ; } if ( ! result . isEmpty ( ) ) results . put ( word , result ) ; } return results ; } HashtableOfObject addQueryResults ( char [ ] [ ] categories , char [ ] key , int matchRule , MemoryIndex memoryIndex ) throws IOException { if ( this . categoryOffsets == null ) return null ; HashtableOfObject results = null ; if ( key == null ) { for ( int i = , l = categories . length ; i < l ; i ++ ) { HashtableOfObject wordsToDocNumbers = readCategoryTable ( categories [ i ] , true ) ; if ( wordsToDocNumbers != null ) { char [ ] [ ] words = wordsToDocNumbers . keyTable ; if ( results == null ) results = new HashtableOfObject ( wordsToDocNumbers . elementSize ) ; for ( int j = , m = words . length ; j < m ; j ++ ) if ( words [ j ] != null ) results = addQueryResult ( results , words [ j ] , wordsToDocNumbers , memoryIndex ) ; } } if ( results != null && this . cachedChunks == null ) cacheDocumentNames ( ) ; } else { switch ( matchRule ) { case SearchPattern . R_EXACT_MATCH | SearchPattern . R_CASE_SENSITIVE : for ( int i = , l = categories . length ; i < l ; i ++ ) { HashtableOfObject wordsToDocNumbers = readCategoryTable ( categories [ i ] , false ) ; if ( wordsToDocNumbers != null && wordsToDocNumbers . containsKey ( key ) ) results = addQueryResult ( results , key , wordsToDocNumbers , memoryIndex ) ; } break ; case SearchPattern . R_PREFIX_MATCH | SearchPattern . R_CASE_SENSITIVE : for ( int i = , l = categories . length ; i < l ; i ++ ) { HashtableOfObject wordsToDocNumbers = readCategoryTable ( categories [ i ] , false ) ; if ( wordsToDocNumbers != null ) { char [ ] [ ] words = wordsToDocNumbers . keyTable ; for ( int j = , m = words . length ; j < m ; j ++ ) { char [ ] word = words [ j ] ; if ( word != null && key [ ] == word [ ] && CharOperation . prefixEquals ( key , word ) ) results = addQueryResult ( results , word , wordsToDocNumbers , memoryIndex ) ; } } } break ; default : for ( int i = , l = categories . length ; i < l ; i ++ ) { HashtableOfObject wordsToDocNumbers = readCategoryTable ( categories [ i ] , false ) ; if ( wordsToDocNumbers != null ) { char [ ] [ ] words = wordsToDocNumbers . keyTable ; for ( int j = , m = words . length ; j < m ; j ++ ) { char [ ] word = words [ j ] ; if ( word != null && Index . isMatch ( key , word , matchRule ) ) results = addQueryResult ( results , word , wordsToDocNumbers , memoryIndex ) ; } } } } } if ( results == null ) return null ; return results ; } private void cacheDocumentNames ( ) throws IOException { this . cachedChunks = new String [ this . numberOfChunks ] [ ] ; FileInputStream stream = new FileInputStream ( this . indexFile ) ; try { if ( this . numberOfChunks > ) BUFFER_READ_SIZE <<= ; int offset = this . chunkOffsets [ ] ; stream . skip ( offset ) ; this . streamBuffer = new byte [ BUFFER_READ_SIZE ] ; this . bufferIndex = ; this . bufferEnd = stream . read ( this . streamBuffer , , this . streamBuffer . length ) ; for ( int i = ; i < this . numberOfChunks ; i ++ ) { int size = i == this . numberOfChunks - ? this . sizeOfLastChunk : CHUNK_SIZE ; readChunk ( this . cachedChunks [ i ] = new String [ size ] , stream , , size ) ; } } catch ( IOException e ) { this . cachedChunks = null ; throw e ; } finally { stream . close ( ) ; this . streamBuffer = null ; BUFFER_READ_SIZE = DEFAULT_BUFFER_SIZE ; } } private String [ ] computeDocumentNames ( String [ ] onDiskNames , int [ ] positions , SimpleLookupTable indexedDocuments , MemoryIndex memoryIndex ) { int onDiskLength = onDiskNames . length ; Object [ ] docNames = memoryIndex . docsToReferences . keyTable ; Object [ ] referenceTables = memoryIndex . docsToReferences . valueTable ; if ( onDiskLength == ) { for ( int i = , l = referenceTables . length ; i < l ; i ++ ) if ( referenceTables [ i ] != null ) indexedDocuments . put ( docNames [ i ] , null ) ; String [ ] newDocNames = new String [ indexedDocuments . elementSize ] ; int count = ; Object [ ] added = indexedDocuments . keyTable ; for ( int i = , l = added . length ; i < l ; i ++ ) if ( added [ i ] != null ) newDocNames [ count ++ ] = ( String ) added [ i ] ; Util . sort ( newDocNames ) ; for ( int i = , l = newDocNames . length ; i < l ; i ++ ) indexedDocuments . put ( newDocNames [ i ] , new Integer ( i ) ) ; return newDocNames ; } for ( int i = ; i < onDiskLength ; i ++ ) positions [ i ] = i ; int numDeletedDocNames = ; int numReindexedDocNames = ; nextPath : for ( int i = , l = docNames . length ; i < l ; i ++ ) { String docName = ( String ) docNames [ i ] ; if ( docName != null ) { for ( int j = ; j < onDiskLength ; j ++ ) { if ( docName . equals ( onDiskNames [ j ] ) ) { if ( referenceTables [ i ] == null ) { positions [ j ] = DELETED ; numDeletedDocNames ++ ; } else { positions [ j ] = RE_INDEXED ; numReindexedDocNames ++ ; } continue nextPath ; } } if ( referenceTables [ i ] != null ) indexedDocuments . put ( docName , null ) ; } } String [ ] newDocNames = onDiskNames ; if ( numDeletedDocNames > || indexedDocuments . elementSize > ) { newDocNames = new String [ onDiskLength + indexedDocuments . elementSize - numDeletedDocNames ] ; int count = ; for ( int i = ; i < onDiskLength ; i ++ ) if ( positions [ i ] >= RE_INDEXED ) newDocNames [ count ++ ] = onDiskNames [ i ] ; Object [ ] added = indexedDocuments . keyTable ; for ( int i = , l = added . length ; i < l ; i ++ ) if ( added [ i ] != null ) newDocNames [ count ++ ] = ( String ) added [ i ] ; Util . sort ( newDocNames ) ; for ( int i = , l = newDocNames . length ; i < l ; i ++ ) if ( indexedDocuments . containsKey ( newDocNames [ i ] ) ) indexedDocuments . put ( newDocNames [ i ] , new Integer ( i ) ) ; } int count = - ; for ( int i = ; i < onDiskLength ; ) { switch ( positions [ i ] ) { case DELETED : i ++ ; break ; case RE_INDEXED : String newName = newDocNames [ ++ count ] ; if ( newName . equals ( onDiskNames [ i ] ) ) { indexedDocuments . put ( newName , new Integer ( count ) ) ; i ++ ; } break ; default : if ( newDocNames [ ++ count ] . equals ( onDiskNames [ i ] ) ) positions [ i ++ ] = count ; } } return newDocNames ; } private void copyQueryResults ( HashtableOfObject categoryToWords , int newPosition ) { char [ ] [ ] categoryNames = categoryToWords . keyTable ; Object [ ] wordSets = categoryToWords . valueTable ; for ( int i = , l = categoryNames . length ; i < l ; i ++ ) { char [ ] categoryName = categoryNames [ i ] ; if ( categoryName != null ) { SimpleWordSet wordSet = ( SimpleWordSet ) wordSets [ i ] ; HashtableOfObject wordsToDocs = ( HashtableOfObject ) this . categoryTables . get ( categoryName ) ; if ( wordsToDocs == null ) this . categoryTables . put ( categoryName , wordsToDocs = new HashtableOfObject ( wordSet . elementSize ) ) ; char [ ] [ ] words = wordSet . words ; for ( int j = , m = words . length ; j < m ; j ++ ) { char [ ] word = words [ j ] ; if ( word != null ) { Object o = wordsToDocs . get ( word ) ; if ( o == null ) { wordsToDocs . put ( word , new int [ ] { newPosition } ) ; } else if ( o instanceof IntList ) { ( ( IntList ) o ) . add ( newPosition ) ; } else { IntList list = new IntList ( ( int [ ] ) o ) ; list . add ( newPosition ) ; wordsToDocs . put ( word , list ) ; } } } } } } void initialize ( boolean reuseExistingFile ) throws IOException { if ( this . indexFile . exists ( ) ) { if ( reuseExistingFile ) { FileInputStream stream = new FileInputStream ( this . indexFile ) ; this . streamBuffer = new byte [ BUFFER_READ_SIZE ] ; this . bufferIndex = ; this . bufferEnd = stream . read ( this . streamBuffer , , ) ; try { char [ ] signature = readStreamChars ( stream ) ; if ( ! CharOperation . equals ( signature , SIGNATURE_CHARS ) ) { throw new IOException ( Messages . exception_wrongFormat ) ; } this . headerInfoOffset = readStreamInt ( stream ) ; if ( this . headerInfoOffset > ) { stream . skip ( this . headerInfoOffset - this . bufferEnd ) ; this . bufferIndex = ; this . bufferEnd = stream . read ( this . streamBuffer , , this . streamBuffer . length ) ; readHeaderInfo ( stream ) ; } } finally { stream . close ( ) ; } return ; } if ( ! this . indexFile . delete ( ) ) { if ( DEBUG ) System . out . println ( "" + this . indexFile ) ; throw new IOException ( "" + this . indexFile ) ; } } if ( this . indexFile . createNewFile ( ) ) { FileOutputStream stream = new FileOutputStream ( this . indexFile , false ) ; try { this . streamBuffer = new byte [ BUFFER_READ_SIZE ] ; this . bufferIndex = ; writeStreamChars ( stream , SIGNATURE_CHARS ) ; writeStreamInt ( stream , - ) ; if ( this . bufferIndex > ) { stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } } finally { stream . close ( ) ; } } else { if ( DEBUG ) System . out . println ( "" + this . indexFile ) ; throw new IOException ( "" + this . indexFile ) ; } } private void initializeFrom ( DiskIndex diskIndex , File newIndexFile ) throws IOException { if ( newIndexFile . exists ( ) && ! newIndexFile . delete ( ) ) { if ( DEBUG ) System . out . println ( "" + this . indexFile ) ; } else if ( ! newIndexFile . createNewFile ( ) ) { if ( DEBUG ) System . out . println ( "" + this . indexFile ) ; throw new IOException ( "" + this . indexFile ) ; } int size = diskIndex . categoryOffsets == null ? : diskIndex . categoryOffsets . elementSize ; this . categoryOffsets = new HashtableOfIntValues ( size ) ; this . categoryEnds = new HashtableOfIntValues ( size ) ; this . categoryTables = new HashtableOfObject ( size ) ; this . separator = diskIndex . separator ; } private void mergeCategories ( DiskIndex onDisk , int [ ] positions , FileOutputStream stream ) throws IOException { char [ ] [ ] oldNames = onDisk . categoryOffsets . keyTable ; for ( int i = , l = oldNames . length ; i < l ; i ++ ) { char [ ] oldName = oldNames [ i ] ; if ( oldName != null && ! this . categoryTables . containsKey ( oldName ) ) this . categoryTables . put ( oldName , null ) ; } char [ ] [ ] categoryNames = this . categoryTables . keyTable ; for ( int i = , l = categoryNames . length ; i < l ; i ++ ) if ( categoryNames [ i ] != null ) mergeCategory ( categoryNames [ i ] , onDisk , positions , stream ) ; this . categoryTables = null ; } private void mergeCategory ( char [ ] categoryName , DiskIndex onDisk , int [ ] positions , FileOutputStream stream ) throws IOException { HashtableOfObject wordsToDocs = ( HashtableOfObject ) this . categoryTables . get ( categoryName ) ; if ( wordsToDocs == null ) wordsToDocs = new HashtableOfObject ( ) ; HashtableOfObject oldWordsToDocs = onDisk . readCategoryTable ( categoryName , true ) ; if ( oldWordsToDocs != null ) { char [ ] [ ] oldWords = oldWordsToDocs . keyTable ; Object [ ] oldArrayOffsets = oldWordsToDocs . valueTable ; nextWord : for ( int i = , l = oldWords . length ; i < l ; i ++ ) { char [ ] oldWord = oldWords [ i ] ; if ( oldWord != null ) { int [ ] oldDocNumbers = ( int [ ] ) oldArrayOffsets [ i ] ; int length = oldDocNumbers . length ; int [ ] mappedNumbers = new int [ length ] ; int count = ; for ( int j = ; j < length ; j ++ ) { int pos = positions [ oldDocNumbers [ j ] ] ; if ( pos > RE_INDEXED ) mappedNumbers [ count ++ ] = pos ; } if ( count < length ) { if ( count == ) continue nextWord ; System . arraycopy ( mappedNumbers , , mappedNumbers = new int [ count ] , , count ) ; } Object o = wordsToDocs . get ( oldWord ) ; if ( o == null ) { wordsToDocs . put ( oldWord , mappedNumbers ) ; } else { IntList list = null ; if ( o instanceof IntList ) { list = ( IntList ) o ; } else { list = new IntList ( ( int [ ] ) o ) ; wordsToDocs . put ( oldWord , list ) ; } for ( int j = ; j < count ; j ++ ) list . add ( mappedNumbers [ j ] ) ; } } } onDisk . categoryTables . put ( categoryName , null ) ; } writeCategoryTable ( categoryName , wordsToDocs , stream ) ; } DiskIndex mergeWith ( MemoryIndex memoryIndex ) throws IOException { String [ ] docNames = readAllDocumentNames ( ) ; int previousLength = docNames . length ; int [ ] positions = new int [ previousLength ] ; SimpleLookupTable indexedDocuments = new SimpleLookupTable ( ) ; docNames = computeDocumentNames ( docNames , positions , indexedDocuments , memoryIndex ) ; if ( docNames . length == ) { if ( previousLength == ) return this ; DiskIndex newDiskIndex = new DiskIndex ( this . indexFile . getPath ( ) ) ; newDiskIndex . initialize ( false ) ; return newDiskIndex ; } DiskIndex newDiskIndex = new DiskIndex ( this . indexFile . getPath ( ) + "" ) ; try { newDiskIndex . initializeFrom ( this , newDiskIndex . indexFile ) ; FileOutputStream stream = new FileOutputStream ( newDiskIndex . indexFile , false ) ; int offsetToHeader = - ; try { newDiskIndex . writeAllDocumentNames ( docNames , stream ) ; docNames = null ; if ( indexedDocuments . elementSize > ) { Object [ ] names = indexedDocuments . keyTable ; Object [ ] integerPositions = indexedDocuments . valueTable ; for ( int i = , l = names . length ; i < l ; i ++ ) if ( names [ i ] != null ) newDiskIndex . copyQueryResults ( ( HashtableOfObject ) memoryIndex . docsToReferences . get ( names [ i ] ) , ( ( Integer ) integerPositions [ i ] ) . intValue ( ) ) ; } indexedDocuments = null ; if ( previousLength == ) newDiskIndex . writeCategories ( stream ) ; else newDiskIndex . mergeCategories ( this , positions , stream ) ; offsetToHeader = newDiskIndex . streamEnd ; newDiskIndex . writeHeaderInfo ( stream ) ; positions = null ; } finally { stream . close ( ) ; this . streamBuffer = null ; } newDiskIndex . writeOffsetToHeader ( offsetToHeader ) ; if ( this . indexFile . exists ( ) && ! this . indexFile . delete ( ) ) { if ( DEBUG ) System . out . println ( "" + this . indexFile ) ; throw new IOException ( "" + this . indexFile ) ; } if ( ! newDiskIndex . indexFile . renameTo ( this . indexFile ) ) { if ( DEBUG ) System . out . println ( "" + this . indexFile ) ; throw new IOException ( "" + this . indexFile ) ; } } catch ( IOException e ) { if ( newDiskIndex . indexFile . exists ( ) && ! newDiskIndex . indexFile . delete ( ) ) if ( DEBUG ) System . out . println ( "" + newDiskIndex . indexFile ) ; throw e ; } newDiskIndex . indexFile = this . indexFile ; return newDiskIndex ; } private synchronized String [ ] readAllDocumentNames ( ) throws IOException { if ( this . numberOfChunks <= ) return CharOperation . NO_STRINGS ; FileInputStream stream = new FileInputStream ( this . indexFile ) ; try { int offset = this . chunkOffsets [ ] ; stream . skip ( offset ) ; this . streamBuffer = new byte [ BUFFER_READ_SIZE ] ; this . bufferIndex = ; this . bufferEnd = stream . read ( this . streamBuffer , , this . streamBuffer . length ) ; int lastIndex = this . numberOfChunks - ; String [ ] docNames = new String [ lastIndex * CHUNK_SIZE + sizeOfLastChunk ] ; for ( int i = ; i < this . numberOfChunks ; i ++ ) readChunk ( docNames , stream , i * CHUNK_SIZE , i < lastIndex ? CHUNK_SIZE : sizeOfLastChunk ) ; return docNames ; } finally { stream . close ( ) ; this . streamBuffer = null ; } } private synchronized HashtableOfObject readCategoryTable ( char [ ] categoryName , boolean readDocNumbers ) throws IOException { int offset = this . categoryOffsets . get ( categoryName ) ; if ( offset == HashtableOfIntValues . NO_VALUE ) { return null ; } if ( this . categoryTables == null ) { this . categoryTables = new HashtableOfObject ( ) ; } else { HashtableOfObject cachedTable = ( HashtableOfObject ) this . categoryTables . get ( categoryName ) ; if ( cachedTable != null ) { if ( readDocNumbers ) { Object [ ] arrayOffsets = cachedTable . valueTable ; for ( int i = , l = arrayOffsets . length ; i < l ; i ++ ) if ( arrayOffsets [ i ] instanceof Integer ) arrayOffsets [ i ] = readDocumentNumbers ( arrayOffsets [ i ] ) ; } return cachedTable ; } } FileInputStream stream = new FileInputStream ( this . indexFile ) ; HashtableOfObject categoryTable = null ; char [ ] [ ] matchingWords = null ; int count = ; int firstOffset = - ; this . streamBuffer = new byte [ BUFFER_READ_SIZE ] ; try { stream . skip ( offset ) ; this . bufferIndex = ; this . bufferEnd = stream . read ( this . streamBuffer , , this . streamBuffer . length ) ; int size = readStreamInt ( stream ) ; try { if ( size < ) { System . err . println ( "" ) ; System . err . println ( "" + this . indexFile ) ; System . err . println ( "" + offset ) ; System . err . println ( "" + size ) ; System . err . println ( "" ) ; } categoryTable = new HashtableOfObject ( size ) ; } catch ( OutOfMemoryError oom ) { oom . printStackTrace ( ) ; System . err . println ( "" ) ; System . err . println ( "" + this . indexFile ) ; System . err . println ( "" + offset ) ; System . err . println ( "" + size ) ; System . err . println ( "" ) ; throw oom ; } int largeArraySize = ; for ( int i = ; i < size ; i ++ ) { char [ ] word = readStreamChars ( stream ) ; int arrayOffset = readStreamInt ( stream ) ; if ( arrayOffset <= ) { categoryTable . put ( word , new int [ ] { - arrayOffset } ) ; } else if ( arrayOffset < largeArraySize ) { categoryTable . put ( word , readStreamDocumentArray ( stream , arrayOffset ) ) ; } else { arrayOffset = readStreamInt ( stream ) ; if ( readDocNumbers ) { if ( matchingWords == null ) matchingWords = new char [ size ] [ ] ; if ( count == ) firstOffset = arrayOffset ; matchingWords [ count ++ ] = word ; } categoryTable . put ( word , new Integer ( arrayOffset ) ) ; } } this . categoryTables . put ( INTERNED_CATEGORY_NAMES . get ( categoryName ) , categoryTable ) ; this . cachedCategoryName = categoryTable . elementSize < ? categoryName : null ; } catch ( IOException ioe ) { this . streamBuffer = null ; throw ioe ; } finally { stream . close ( ) ; } if ( matchingWords != null && count > ) { stream = new FileInputStream ( this . indexFile ) ; try { stream . skip ( firstOffset ) ; this . bufferIndex = ; this . bufferEnd = stream . read ( this . streamBuffer , , this . streamBuffer . length ) ; for ( int i = ; i < count ; i ++ ) { categoryTable . put ( matchingWords [ i ] , readStreamDocumentArray ( stream , readStreamInt ( stream ) ) ) ; } } catch ( IOException ioe ) { this . streamBuffer = null ; throw ioe ; } finally { stream . close ( ) ; } } this . streamBuffer = null ; return categoryTable ; } private void readChunk ( String [ ] docNames , FileInputStream stream , int index , int size ) throws IOException { String current = new String ( readStreamChars ( stream ) ) ; docNames [ index ++ ] = current ; for ( int i = ; i < size ; i ++ ) { if ( stream != null && this . bufferIndex + >= this . bufferEnd ) readStreamBuffer ( stream ) ; int start = streamBuffer [ this . bufferIndex ++ ] & ; int end = streamBuffer [ this . bufferIndex ++ ] & ; String next = new String ( readStreamChars ( stream ) ) ; if ( start > ) { if ( end > ) { int length = current . length ( ) ; next = current . substring ( , start ) + next + current . substring ( length - end , length ) ; } else { next = current . substring ( , start ) + next ; } } else if ( end > ) { int length = current . length ( ) ; next = next + current . substring ( length - end , length ) ; } docNames [ index ++ ] = next ; current = next ; } } synchronized String readDocumentName ( int docNumber ) throws IOException { if ( this . cachedChunks == null ) this . cachedChunks = new String [ this . numberOfChunks ] [ ] ; int chunkNumber = docNumber / CHUNK_SIZE ; String [ ] chunk = this . cachedChunks [ chunkNumber ] ; if ( chunk == null ) { boolean isLastChunk = chunkNumber == this . numberOfChunks - ; int start = this . chunkOffsets [ chunkNumber ] ; int numberOfBytes = ( isLastChunk ? this . startOfCategoryTables : this . chunkOffsets [ chunkNumber + ] ) - start ; if ( numberOfBytes < ) throw new IllegalArgumentException ( ) ; this . streamBuffer = new byte [ numberOfBytes ] ; this . bufferIndex = ; FileInputStream file = new FileInputStream ( this . indexFile ) ; try { file . skip ( start ) ; if ( file . read ( this . streamBuffer , , numberOfBytes ) != numberOfBytes ) throw new IOException ( ) ; } catch ( IOException ioe ) { this . streamBuffer = null ; throw ioe ; } finally { file . close ( ) ; } int numberOfNames = isLastChunk ? this . sizeOfLastChunk : CHUNK_SIZE ; chunk = new String [ numberOfNames ] ; try { readChunk ( chunk , null , , numberOfNames ) ; } catch ( IOException ioe ) { this . streamBuffer = null ; throw ioe ; } this . cachedChunks [ chunkNumber ] = chunk ; } this . streamBuffer = null ; return chunk [ docNumber - ( chunkNumber * CHUNK_SIZE ) ] ; } synchronized int [ ] readDocumentNumbers ( Object arrayOffset ) throws IOException { if ( arrayOffset instanceof int [ ] ) return ( int [ ] ) arrayOffset ; FileInputStream stream = new FileInputStream ( this . indexFile ) ; try { int offset = ( ( Integer ) arrayOffset ) . intValue ( ) ; stream . skip ( offset ) ; this . streamBuffer = new byte [ BUFFER_READ_SIZE ] ; this . bufferIndex = ; this . bufferEnd = stream . read ( this . streamBuffer , , this . streamBuffer . length ) ; return readStreamDocumentArray ( stream , readStreamInt ( stream ) ) ; } finally { stream . close ( ) ; this . streamBuffer = null ; } } private void readHeaderInfo ( FileInputStream stream ) throws IOException { this . numberOfChunks = readStreamInt ( stream ) ; this . sizeOfLastChunk = this . streamBuffer [ this . bufferIndex ++ ] & ; this . documentReferenceSize = this . streamBuffer [ this . bufferIndex ++ ] & ; this . separator = ( char ) ( this . streamBuffer [ this . bufferIndex ++ ] & ) ; this . chunkOffsets = new int [ this . numberOfChunks ] ; for ( int i = ; i < this . numberOfChunks ; i ++ ) this . chunkOffsets [ i ] = readStreamInt ( stream ) ; this . startOfCategoryTables = readStreamInt ( stream ) ; int size = readStreamInt ( stream ) ; this . categoryOffsets = new HashtableOfIntValues ( size ) ; this . categoryEnds = new HashtableOfIntValues ( size ) ; char [ ] previousCategory = null ; int offset = - ; for ( int i = ; i < size ; i ++ ) { char [ ] categoryName = INTERNED_CATEGORY_NAMES . get ( readStreamChars ( stream ) ) ; offset = readStreamInt ( stream ) ; this . categoryOffsets . put ( categoryName , offset ) ; if ( previousCategory != null ) { this . categoryEnds . put ( previousCategory , offset ) ; } previousCategory = categoryName ; } if ( previousCategory != null ) { this . categoryEnds . put ( previousCategory , this . headerInfoOffset ) ; } this . categoryTables = new HashtableOfObject ( ) ; } synchronized void startQuery ( ) { this . cacheUserCount ++ ; } synchronized void stopQuery ( ) { if ( -- this . cacheUserCount < ) { this . cacheUserCount = - ; this . cachedChunks = null ; if ( this . categoryTables != null ) { if ( this . cachedCategoryName == null ) { this . categoryTables = null ; } else if ( this . categoryTables . elementSize > ) { HashtableOfObject newTables = new HashtableOfObject ( ) ; newTables . put ( this . cachedCategoryName , this . categoryTables . get ( this . cachedCategoryName ) ) ; this . categoryTables = newTables ; } } } } private void readStreamBuffer ( FileInputStream stream ) throws IOException { if ( this . bufferEnd < this . streamBuffer . length ) return ; int bytesInBuffer = this . bufferEnd - this . bufferIndex ; if ( bytesInBuffer > ) System . arraycopy ( this . streamBuffer , this . bufferIndex , this . streamBuffer , , bytesInBuffer ) ; this . bufferEnd = bytesInBuffer + stream . read ( this . streamBuffer , bytesInBuffer , this . bufferIndex ) ; this . bufferIndex = ; } private char [ ] readStreamChars ( FileInputStream stream ) throws IOException { if ( stream != null && this . bufferIndex + >= this . bufferEnd ) readStreamBuffer ( stream ) ; int length = ( streamBuffer [ this . bufferIndex ++ ] & ) << ; length += this . streamBuffer [ this . bufferIndex ++ ] & ; char [ ] word = new char [ length ] ; int i = ; while ( i < length ) { int charsInBuffer = i + ( ( this . bufferEnd - this . bufferIndex ) / ) ; if ( charsInBuffer > length || this . bufferEnd != this . streamBuffer . length || stream == null ) charsInBuffer = length ; while ( i < charsInBuffer ) { byte b = this . streamBuffer [ this . bufferIndex ++ ] ; switch ( b & ) { case : case : case : case : case : case : case : case : word [ i ++ ] = ( char ) b ; break ; case : case : char next = ( char ) this . streamBuffer [ this . bufferIndex ++ ] ; if ( ( next & ) != ) { throw new UTFDataFormatException ( ) ; } char ch = ( char ) ( ( b & ) << ) ; ch |= next & ; word [ i ++ ] = ch ; break ; case : char first = ( char ) this . streamBuffer [ this . bufferIndex ++ ] ; char second = ( char ) this . streamBuffer [ this . bufferIndex ++ ] ; if ( ( first & second & ) != ) { throw new UTFDataFormatException ( ) ; } ch = ( char ) ( ( b & ) << ) ; ch |= ( ( first & ) << ) ; ch |= second & ; word [ i ++ ] = ch ; break ; default : throw new UTFDataFormatException ( ) ; } } if ( i < length && stream != null ) readStreamBuffer ( stream ) ; } return word ; } private int [ ] readStreamDocumentArray ( FileInputStream stream , int arraySize ) throws IOException { int [ ] indexes = new int [ arraySize ] ; if ( arraySize == ) return indexes ; int i = ; switch ( this . documentReferenceSize ) { case : while ( i < arraySize ) { int bytesInBuffer = i + this . bufferEnd - this . bufferIndex ; if ( bytesInBuffer > arraySize ) bytesInBuffer = arraySize ; while ( i < bytesInBuffer ) { indexes [ i ++ ] = this . streamBuffer [ this . bufferIndex ++ ] & ; } if ( i < arraySize && stream != null ) readStreamBuffer ( stream ) ; } break ; case : while ( i < arraySize ) { int shortsInBuffer = i + ( ( this . bufferEnd - this . bufferIndex ) / ) ; if ( shortsInBuffer > arraySize ) shortsInBuffer = arraySize ; while ( i < shortsInBuffer ) { int val = ( this . streamBuffer [ this . bufferIndex ++ ] & ) << ; indexes [ i ++ ] = val + ( this . streamBuffer [ this . bufferIndex ++ ] & ) ; } if ( i < arraySize && stream != null ) readStreamBuffer ( stream ) ; } break ; default : while ( i < arraySize ) { indexes [ i ++ ] = readStreamInt ( stream ) ; } break ; } return indexes ; } private int readStreamInt ( FileInputStream stream ) throws IOException { if ( this . bufferIndex + >= this . bufferEnd ) { readStreamBuffer ( stream ) ; } int val = ( streamBuffer [ this . bufferIndex ++ ] & ) << ; val += ( streamBuffer [ this . bufferIndex ++ ] & ) << ; val += ( streamBuffer [ this . bufferIndex ++ ] & ) << ; return val + ( streamBuffer [ this . bufferIndex ++ ] & ) ; } private void writeAllDocumentNames ( String [ ] sortedDocNames , FileOutputStream stream ) throws IOException { if ( sortedDocNames . length == ) throw new IllegalArgumentException ( ) ; this . streamBuffer = new byte [ BUFFER_WRITE_SIZE ] ; this . bufferIndex = ; this . streamEnd = ; writeStreamChars ( stream , SIGNATURE_CHARS ) ; this . headerInfoOffset = this . streamEnd ; writeStreamInt ( stream , - ) ; int size = sortedDocNames . length ; this . numberOfChunks = ( size / CHUNK_SIZE ) + ; this . sizeOfLastChunk = size % CHUNK_SIZE ; if ( this . sizeOfLastChunk == ) { this . numberOfChunks -- ; this . sizeOfLastChunk = CHUNK_SIZE ; } this . documentReferenceSize = size <= ? : ( size <= ? : ) ; this . chunkOffsets = new int [ this . numberOfChunks ] ; int lastIndex = this . numberOfChunks - ; for ( int i = ; i < this . numberOfChunks ; i ++ ) { this . chunkOffsets [ i ] = this . streamEnd ; int chunkSize = i == lastIndex ? this . sizeOfLastChunk : CHUNK_SIZE ; int chunkIndex = i * CHUNK_SIZE ; String current = sortedDocNames [ chunkIndex ] ; writeStreamChars ( stream , current . toCharArray ( ) ) ; for ( int j = ; j < chunkSize ; j ++ ) { String next = sortedDocNames [ chunkIndex + j ] ; int len1 = current . length ( ) ; int len2 = next . length ( ) ; int max = len1 < len2 ? len1 : len2 ; int start = ; while ( current . charAt ( start ) == next . charAt ( start ) ) { start ++ ; if ( max == start ) break ; } if ( start > ) start = ; int end = ; while ( current . charAt ( -- len1 ) == next . charAt ( -- len2 ) ) { end ++ ; if ( len2 == start ) break ; if ( len1 == ) break ; } if ( end > ) end = ; if ( ( this . bufferIndex + ) >= BUFFER_WRITE_SIZE ) { stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) start ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) end ; this . streamEnd += ; int last = next . length ( ) - end ; writeStreamChars ( stream , ( start < last ? CharOperation . subarray ( next . toCharArray ( ) , start , last ) : CharOperation . NO_CHAR ) ) ; current = next ; } } this . startOfCategoryTables = this . streamEnd + ; } private void writeCategories ( FileOutputStream stream ) throws IOException { char [ ] [ ] categoryNames = this . categoryTables . keyTable ; Object [ ] tables = this . categoryTables . valueTable ; for ( int i = , l = categoryNames . length ; i < l ; i ++ ) if ( categoryNames [ i ] != null ) writeCategoryTable ( categoryNames [ i ] , ( HashtableOfObject ) tables [ i ] , stream ) ; this . categoryTables = null ; } private void writeCategoryTable ( char [ ] categoryName , HashtableOfObject wordsToDocs , FileOutputStream stream ) throws IOException { int largeArraySize = ; Object [ ] values = wordsToDocs . valueTable ; for ( int i = , l = values . length ; i < l ; i ++ ) { Object o = values [ i ] ; if ( o != null ) { if ( o instanceof IntList ) o = values [ i ] = ( ( IntList ) values [ i ] ) . asArray ( ) ; int [ ] documentNumbers = ( int [ ] ) o ; if ( documentNumbers . length >= largeArraySize ) { values [ i ] = new Integer ( this . streamEnd ) ; writeDocumentNumbers ( documentNumbers , stream ) ; } } } this . categoryOffsets . put ( categoryName , this . streamEnd ) ; this . categoryTables . put ( categoryName , null ) ; writeStreamInt ( stream , wordsToDocs . elementSize ) ; char [ ] [ ] words = wordsToDocs . keyTable ; for ( int i = , l = words . length ; i < l ; i ++ ) { Object o = values [ i ] ; if ( o != null ) { writeStreamChars ( stream , words [ i ] ) ; if ( o instanceof int [ ] ) { int [ ] documentNumbers = ( int [ ] ) o ; if ( documentNumbers . length == ) writeStreamInt ( stream , - documentNumbers [ ] ) ; else writeDocumentNumbers ( documentNumbers , stream ) ; } else { writeStreamInt ( stream , largeArraySize ) ; writeStreamInt ( stream , ( ( Integer ) o ) . intValue ( ) ) ; } } } } private void writeDocumentNumbers ( int [ ] documentNumbers , FileOutputStream stream ) throws IOException { int length = documentNumbers . length ; writeStreamInt ( stream , length ) ; Util . sort ( documentNumbers ) ; int start = ; switch ( this . documentReferenceSize ) { case : while ( ( this . bufferIndex + length - start ) >= BUFFER_WRITE_SIZE ) { int bytesLeft = BUFFER_WRITE_SIZE - this . bufferIndex ; for ( int i = ; i < bytesLeft ; i ++ ) { this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) documentNumbers [ start ++ ] ; } stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } while ( start < length ) { this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) documentNumbers [ start ++ ] ; } this . streamEnd += length ; break ; case : while ( ( this . bufferIndex + ( ( length - start ) * ) ) >= BUFFER_WRITE_SIZE ) { int shortsLeft = ( BUFFER_WRITE_SIZE - this . bufferIndex ) / ; for ( int i = ; i < shortsLeft ; i ++ ) { this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) ( documentNumbers [ start ] > > ) ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) documentNumbers [ start ++ ] ; } stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } while ( start < length ) { this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) ( documentNumbers [ start ] > > ) ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) documentNumbers [ start ++ ] ; } this . streamEnd += length * ; break ; default : while ( start < length ) { writeStreamInt ( stream , documentNumbers [ start ++ ] ) ; } break ; } } private void writeHeaderInfo ( FileOutputStream stream ) throws IOException { writeStreamInt ( stream , this . numberOfChunks ) ; if ( ( this . bufferIndex + ) >= BUFFER_WRITE_SIZE ) { stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) this . sizeOfLastChunk ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) this . documentReferenceSize ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) this . separator ; this . streamEnd += ; for ( int i = ; i < this . numberOfChunks ; i ++ ) { writeStreamInt ( stream , this . chunkOffsets [ i ] ) ; } writeStreamInt ( stream , this . startOfCategoryTables ) ; writeStreamInt ( stream , this . categoryOffsets . elementSize ) ; char [ ] [ ] categoryNames = this . categoryOffsets . keyTable ; int [ ] offsets = this . categoryOffsets . valueTable ; for ( int i = , l = categoryNames . length ; i < l ; i ++ ) { if ( categoryNames [ i ] != null ) { writeStreamChars ( stream , categoryNames [ i ] ) ; writeStreamInt ( stream , offsets [ i ] ) ; } } if ( this . bufferIndex > ) { stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } } private void writeOffsetToHeader ( int offsetToHeader ) throws IOException { if ( offsetToHeader > ) { RandomAccessFile file = new RandomAccessFile ( this . indexFile , "" ) ; try { file . seek ( this . headerInfoOffset ) ; file . writeInt ( offsetToHeader ) ; this . headerInfoOffset = offsetToHeader ; } finally { file . close ( ) ; } } } private void writeStreamChars ( FileOutputStream stream , char [ ] array ) throws IOException { if ( ( this . bufferIndex + ) >= BUFFER_WRITE_SIZE ) { stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } int length = array . length ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) ( ( length > > > ) & ) ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) ( length & ) ; this . streamEnd += ; int totalBytesNeeded = length * ; if ( totalBytesNeeded <= BUFFER_WRITE_SIZE ) { if ( this . bufferIndex + totalBytesNeeded > BUFFER_WRITE_SIZE ) { stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } writeStreamChars ( stream , array , , length ) ; } else { int charsPerWrite = BUFFER_WRITE_SIZE / ; int start = ; while ( start < length ) { stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; int charsLeftToWrite = length - start ; int end = start + ( charsPerWrite < charsLeftToWrite ? charsPerWrite : charsLeftToWrite ) ; writeStreamChars ( stream , array , start , end ) ; start = end ; } } } private void writeStreamChars ( FileOutputStream stream , char [ ] array , int start , int end ) throws IOException { int oldIndex = this . bufferIndex ; while ( start < end ) { int ch = array [ start ++ ] ; if ( ( ch & ) == ch ) { this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) ch ; } else if ( ( ch & ) == ch ) { byte b = ( byte ) ( ch > > ) ; b &= ; b |= ; this . streamBuffer [ this . bufferIndex ++ ] = b ; b = ( byte ) ( ch & ) ; b |= ; this . streamBuffer [ this . bufferIndex ++ ] = b ; } else { byte b = ( byte ) ( ch > > ) ; b &= ; b |= ; this . streamBuffer [ this . bufferIndex ++ ] = b ; b = ( byte ) ( ch > > ) ; b &= ; b |= ; this . streamBuffer [ this . bufferIndex ++ ] = b ; b = ( byte ) ( ch & ) ; b |= ; this . streamBuffer [ this . bufferIndex ++ ] = b ; } } this . streamEnd += this . bufferIndex - oldIndex ; } private void writeStreamInt ( FileOutputStream stream , int val ) throws IOException { if ( ( this . bufferIndex + ) >= BUFFER_WRITE_SIZE ) { stream . write ( this . streamBuffer , , this . bufferIndex ) ; this . bufferIndex = ; } this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) ( val > > ) ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) ( val > > ) ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) ( val > > ) ; this . streamBuffer [ this . bufferIndex ++ ] = ( byte ) val ; this . streamEnd += ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IRubyElement ; public class RubyGlobal extends RubyField { public RubyGlobal ( IRubyElement parent , String name ) { super ( ( RubyElement ) parent , name ) ; } public int getElementType ( ) { return RubyElement . GLOBAL ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . text . edits . TextEdit ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . ASTRewrite ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . core . util . Messages ; public class CreateMethodOperation extends RubyModelOperation { protected static final int INSERT_LAST = ; protected static final int INSERT_AFTER = ; protected static final int INSERT_BEFORE = ; protected int insertionPolicy = INSERT_LAST ; protected IRubyElement anchorElement = null ; protected boolean creationOccurred = true ; private String source ; private Node cuAST ; private Node createdNode ; private String [ ] parameters ; public CreateMethodOperation ( IType parentElement , String source , boolean force ) { super ( null , new IRubyElement [ ] { parentElement } , force ) ; this . source = source ; } @ Override protected void executeOperation ( ) throws RubyModelException { try { beginTask ( getMainTaskName ( ) , getMainAmountOfWork ( ) ) ; RubyElementDelta delta = newRubyElementDelta ( ) ; IRubyScript unit = getRubyScript ( ) ; generateNewRubyScriptAST ( unit ) ; if ( this . creationOccurred ) { unit . save ( null , false ) ; boolean isWorkingCopy = unit . isWorkingCopy ( ) ; if ( ! isWorkingCopy ) this . setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; worked ( ) ; resultElements = generateResultHandles ( ) ; if ( ! isWorkingCopy && unit . getParent ( ) . exists ( ) ) { for ( int i = ; i < resultElements . length ; i ++ ) { delta . added ( resultElements [ i ] ) ; } addDelta ( delta ) ; } } } finally { done ( ) ; } } protected IType getType ( ) { return ( IType ) getParentElement ( ) ; } protected IRubyElement generateResultHandle ( ) { String [ ] types = convertASTMethodTypesToSignatures ( ) ; String name = getASTNodeName ( ) ; return getType ( ) . getMethod ( name , types ) ; } private String getASTNodeName ( ) { if ( this . createdNode instanceof DefsNode ) return ( ( DefsNode ) this . createdNode ) . getName ( ) ; return ( ( DefnNode ) this . createdNode ) . getName ( ) ; } protected String [ ] convertASTMethodTypesToSignatures ( ) { if ( this . parameters == null ) { if ( this . createdNode != null ) { DefnNode methodDeclaration = ( DefnNode ) this . createdNode ; this . parameters = ASTUtil . getArgs ( methodDeclaration . getArgsNode ( ) , methodDeclaration . getScope ( ) ) ; } } return this . parameters ; } protected IRubyElement [ ] generateResultHandles ( ) { return new IRubyElement [ ] { generateResultHandle ( ) } ; } protected IRubyScript getRubyScript ( ) { return getRubyScriptFor ( getParentElement ( ) ) ; } public String getMainTaskName ( ) { return Messages . operation_createMethodProgress ; } protected int getMainAmountOfWork ( ) { return ; } public void createBefore ( IRubyElement sibling ) { setRelativePosition ( sibling , INSERT_BEFORE ) ; } protected void setRelativePosition ( IRubyElement sibling , int policy ) throws IllegalArgumentException { if ( sibling == null ) { this . anchorElement = null ; this . insertionPolicy = INSERT_LAST ; } else { this . anchorElement = sibling ; this . insertionPolicy = policy ; } } protected void generateNewRubyScriptAST ( IRubyScript cu ) throws RubyModelException { this . cuAST = parse ( cu ) ; IDocument document = getDocument ( cu ) ; ASTRewrite rewriter = ASTRewrite . create ( this . cuAST , document ) ; Node child = generateElementAST ( document , cu ) ; if ( child != null ) { Node parent = ( ( RubyElement ) getParentElement ( ) ) . findNode ( this . cuAST ) ; if ( parent == null ) parent = this . cuAST ; insertASTNode ( rewriter , parent , child ) ; apply ( rewriter , document ) ; } worked ( ) ; } private void insertASTNode ( ASTRewrite rewriter , Node parent , Node child ) { switch ( this . insertionPolicy ) { case INSERT_BEFORE : Node element = ( ( RubyElement ) this . anchorElement ) . findNode ( this . cuAST ) ; rewriter . insertBefore ( source , child , element , null ) ; case INSERT_AFTER : element = ( ( RubyElement ) this . anchorElement ) . findNode ( this . cuAST ) ; rewriter . insertAfter ( source , child , element , null ) ; case INSERT_LAST : rewriter . insertLast ( source , child , null ) ; break ; } } private Node generateElementAST ( IDocument document , IRubyScript cu ) { RubyParser parser = new RubyParser ( ) ; Node root = parser . parse ( this . source ) . getAST ( ) ; this . createdNode = ( ( NewlineNode ) ( ( RootNode ) root ) . getBodyNode ( ) ) . getNextNode ( ) ; return this . createdNode ; } protected Node parse ( IRubyScript cu ) throws RubyModelException { cu . makeConsistent ( this . progressMonitor ) ; RubyParser parser = new RubyParser ( ) ; return parser . parse ( cu . getSource ( ) ) . getAST ( ) ; } protected void apply ( ASTRewrite rewriter , IDocument document ) throws RubyModelException { TextEdit edits = rewriter . rewriteAST ( document , null ) ; try { edits . apply ( document ) ; } catch ( BadLocationException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . INVALID_CONTENTS ) ; } } public IRubyModelStatus verify ( ) { if ( getParentElement ( ) == null ) { return new RubyModelStatus ( IRubyModelStatusConstants . NO_ELEMENTS_TO_PROCESS ) ; } if ( this . anchorElement != null ) { IRubyElement domPresentParent = this . anchorElement . getParent ( ) ; if ( ! domPresentParent . equals ( getParentElement ( ) ) ) { return new RubyModelStatus ( IRubyModelStatusConstants . INVALID_SIBLING , this . anchorElement ) ; } } return RubyModelStatus . VERIFIED_OK ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import org . eclipse . core . resources . IResourceDelta ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; public class RubyElementDelta extends SimpleDelta implements IRubyElementDelta { protected IRubyElementDelta [ ] affectedChildren = EMPTY_DELTA ; protected Node ast = null ; protected IRubyElement changedElement ; protected IResourceDelta [ ] resourceDeltas = null ; protected int resourceDeltasCounter ; protected IRubyElement movedFromHandle = null ; protected IRubyElement movedToHandle = null ; protected static IRubyElementDelta [ ] EMPTY_DELTA = new IRubyElementDelta [ ] { } ; public RubyElementDelta ( IRubyElement element ) { this . changedElement = element ; } protected void addAffectedChild ( RubyElementDelta child ) { switch ( this . kind ) { case ADDED : case REMOVED : return ; case CHANGED : this . changeFlags |= F_CHILDREN ; break ; default : this . kind = CHANGED ; this . changeFlags |= F_CHILDREN ; } if ( this . changedElement . getElementType ( ) >= IRubyElement . SCRIPT ) { this . fineGrained ( ) ; } if ( this . affectedChildren . length == ) { this . affectedChildren = new IRubyElementDelta [ ] { child } ; return ; } RubyElementDelta existingChild = null ; int existingChildIndex = - ; if ( this . affectedChildren != null ) { for ( int i = ; i < this . affectedChildren . length ; i ++ ) { if ( this . equalsAndSameParent ( this . affectedChildren [ i ] . getElement ( ) , child . getElement ( ) ) ) { existingChild = ( RubyElementDelta ) this . affectedChildren [ i ] ; existingChildIndex = i ; break ; } } } if ( existingChild == null ) { this . affectedChildren = growAndAddToArray ( this . affectedChildren , child ) ; } else { switch ( existingChild . getKind ( ) ) { case ADDED : switch ( child . getKind ( ) ) { case ADDED : case CHANGED : return ; case REMOVED : this . affectedChildren = this . removeAndShrinkArray ( this . affectedChildren , existingChildIndex ) ; return ; } break ; case REMOVED : switch ( child . getKind ( ) ) { case ADDED : child . kind = CHANGED ; this . affectedChildren [ existingChildIndex ] = child ; return ; case CHANGED : case REMOVED : return ; } break ; case CHANGED : switch ( child . getKind ( ) ) { case ADDED : case REMOVED : this . affectedChildren [ existingChildIndex ] = child ; return ; case CHANGED : IRubyElementDelta [ ] children = child . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { RubyElementDelta childsChild = ( RubyElementDelta ) children [ i ] ; existingChild . addAffectedChild ( childsChild ) ; } boolean childHadContentFlag = ( child . changeFlags & F_CONTENT ) != ; boolean existingChildHadChildrenFlag = ( existingChild . changeFlags & F_CHILDREN ) != ; existingChild . changeFlags |= child . changeFlags ; if ( childHadContentFlag && existingChildHadChildrenFlag ) { existingChild . changeFlags &= ~ F_CONTENT ; } IResourceDelta [ ] resDeltas = child . getResourceDeltas ( ) ; if ( resDeltas != null ) { existingChild . resourceDeltas = resDeltas ; existingChild . resourceDeltasCounter = child . resourceDeltasCounter ; } return ; } break ; default : int flags = existingChild . getFlags ( ) ; this . affectedChildren [ existingChildIndex ] = child ; child . changeFlags |= flags ; } } } public void added ( IRubyElement element ) { added ( element , ) ; } public void added ( IRubyElement element , int flags ) { RubyElementDelta addedDelta = new RubyElementDelta ( element ) ; addedDelta . added ( ) ; addedDelta . changeFlags |= flags ; insertDeltaTree ( element , addedDelta ) ; } protected void addResourceDelta ( IResourceDelta child ) { switch ( this . kind ) { case ADDED : case REMOVED : return ; case CHANGED : this . changeFlags |= F_CONTENT ; break ; default : this . kind = CHANGED ; this . changeFlags |= F_CONTENT ; } if ( resourceDeltas == null ) { resourceDeltas = new IResourceDelta [ ] ; resourceDeltas [ resourceDeltasCounter ++ ] = child ; return ; } if ( resourceDeltas . length == resourceDeltasCounter ) { System . arraycopy ( resourceDeltas , , ( resourceDeltas = new IResourceDelta [ resourceDeltasCounter * ] ) , , resourceDeltasCounter ) ; } resourceDeltas [ resourceDeltasCounter ++ ] = child ; } public RubyElementDelta changed ( IRubyElement element , int changeFlag ) { RubyElementDelta changedDelta = new RubyElementDelta ( element ) ; changedDelta . changed ( changeFlag ) ; insertDeltaTree ( element , changedDelta ) ; return changedDelta ; } public void changedAST ( Node changedAST ) { this . ast = changedAST ; changed ( F_AST_AFFECTED ) ; } public void contentChanged ( ) { this . changeFlags |= F_CONTENT ; } public void closed ( IRubyElement element ) { RubyElementDelta delta = new RubyElementDelta ( element ) ; delta . changed ( F_CLOSED ) ; insertDeltaTree ( element , delta ) ; } protected RubyElementDelta createDeltaTree ( IRubyElement element , RubyElementDelta delta ) { RubyElementDelta childDelta = delta ; ArrayList ancestors = getAncestors ( element ) ; if ( ancestors == null ) { if ( this . equalsAndSameParent ( delta . getElement ( ) , getElement ( ) ) ) { this . kind = delta . kind ; this . changeFlags = delta . changeFlags ; this . movedToHandle = delta . movedToHandle ; this . movedFromHandle = delta . movedFromHandle ; } } else { for ( int i = , size = ancestors . size ( ) ; i < size ; i ++ ) { IRubyElement ancestor = ( IRubyElement ) ancestors . get ( i ) ; RubyElementDelta ancestorDelta = new RubyElementDelta ( ancestor ) ; ancestorDelta . addAffectedChild ( childDelta ) ; childDelta = ancestorDelta ; } } return childDelta ; } protected boolean equalsAndSameParent ( IRubyElement e1 , IRubyElement e2 ) { IRubyElement parent1 ; return e1 . equals ( e2 ) && ( ( parent1 = e1 . getParent ( ) ) != null ) && parent1 . equals ( e2 . getParent ( ) ) ; } protected RubyElementDelta find ( IRubyElement e ) { if ( this . equalsAndSameParent ( this . changedElement , e ) ) { return this ; } else { for ( int i = ; i < this . affectedChildren . length ; i ++ ) { RubyElementDelta delta = ( ( RubyElementDelta ) this . affectedChildren [ i ] ) . find ( e ) ; if ( delta != null ) { return delta ; } } } return null ; } public void fineGrained ( ) { changed ( F_FINE_GRAINED ) ; } public IRubyElementDelta [ ] getAddedChildren ( ) { return getChildrenOfType ( ADDED ) ; } public IRubyElementDelta [ ] getAffectedChildren ( ) { return this . affectedChildren ; } private ArrayList getAncestors ( IRubyElement element ) { IRubyElement parent = element . getParent ( ) ; if ( parent == null ) { return null ; } ArrayList parents = new ArrayList ( ) ; while ( ! parent . equals ( this . changedElement ) ) { parents . add ( parent ) ; parent = parent . getParent ( ) ; if ( parent == null ) { return null ; } } parents . trimToSize ( ) ; return parents ; } public Node getRubyScriptAST ( ) { return this . ast ; } public IRubyElementDelta [ ] getChangedChildren ( ) { return getChildrenOfType ( CHANGED ) ; } protected IRubyElementDelta [ ] getChildrenOfType ( int type ) { int length = this . affectedChildren . length ; if ( length == ) { return new IRubyElementDelta [ ] { } ; } ArrayList children = new ArrayList ( length ) ; for ( int i = ; i < length ; i ++ ) { if ( this . affectedChildren [ i ] . getKind ( ) == type ) { children . add ( this . affectedChildren [ i ] ) ; } } IRubyElementDelta [ ] childrenOfType = new IRubyElementDelta [ children . size ( ) ] ; children . toArray ( childrenOfType ) ; return childrenOfType ; } protected RubyElementDelta getDeltaFor ( IRubyElement element ) { if ( this . equalsAndSameParent ( getElement ( ) , element ) ) return this ; if ( this . affectedChildren . length == ) return null ; int childrenCount = this . affectedChildren . length ; for ( int i = ; i < childrenCount ; i ++ ) { RubyElementDelta delta = ( RubyElementDelta ) this . affectedChildren [ i ] ; if ( this . equalsAndSameParent ( delta . getElement ( ) , element ) ) { return delta ; } else { delta = delta . getDeltaFor ( element ) ; if ( delta != null ) return delta ; } } return null ; } public IRubyElement getElement ( ) { return this . changedElement ; } public IRubyElement getMovedFromElement ( ) { return this . movedFromHandle ; } public IRubyElement getMovedToElement ( ) { return movedToHandle ; } public IRubyElementDelta [ ] getRemovedChildren ( ) { return getChildrenOfType ( REMOVED ) ; } public IResourceDelta [ ] getResourceDeltas ( ) { if ( resourceDeltas == null ) return null ; if ( resourceDeltas . length != resourceDeltasCounter ) { System . arraycopy ( resourceDeltas , , resourceDeltas = new IResourceDelta [ resourceDeltasCounter ] , , resourceDeltasCounter ) ; } return resourceDeltas ; } protected IRubyElementDelta [ ] growAndAddToArray ( IRubyElementDelta [ ] array , IRubyElementDelta addition ) { IRubyElementDelta [ ] old = array ; array = new IRubyElementDelta [ old . length + ] ; System . arraycopy ( old , , array , , old . length ) ; array [ old . length ] = addition ; return array ; } protected void insertDeltaTree ( IRubyElement element , RubyElementDelta delta ) { RubyElementDelta childDelta = createDeltaTree ( element , delta ) ; if ( ! this . equalsAndSameParent ( element , getElement ( ) ) ) { addAffectedChild ( childDelta ) ; } } public void movedFrom ( IRubyElement movedFromElement , IRubyElement movedToElement ) { RubyElementDelta removedDelta = new RubyElementDelta ( movedFromElement ) ; removedDelta . kind = REMOVED ; removedDelta . changeFlags |= F_MOVED_TO ; removedDelta . movedToHandle = movedToElement ; insertDeltaTree ( movedFromElement , removedDelta ) ; } public void movedTo ( IRubyElement movedToElement , IRubyElement movedFromElement ) { RubyElementDelta addedDelta = new RubyElementDelta ( movedToElement ) ; addedDelta . kind = ADDED ; addedDelta . changeFlags |= F_MOVED_FROM ; addedDelta . movedFromHandle = movedFromElement ; insertDeltaTree ( movedToElement , addedDelta ) ; } public void opened ( IRubyElement element ) { RubyElementDelta delta = new RubyElementDelta ( element ) ; delta . changed ( F_OPENED ) ; insertDeltaTree ( element , delta ) ; } protected void removeAffectedChild ( RubyElementDelta child ) { int index = - ; if ( this . affectedChildren != null ) { for ( int i = ; i < this . affectedChildren . length ; i ++ ) { if ( this . equalsAndSameParent ( this . affectedChildren [ i ] . getElement ( ) , child . getElement ( ) ) ) { index = i ; break ; } } } if ( index >= ) { this . affectedChildren = removeAndShrinkArray ( this . affectedChildren , index ) ; } } protected IRubyElementDelta [ ] removeAndShrinkArray ( IRubyElementDelta [ ] old , int index ) { IRubyElementDelta [ ] array = new IRubyElementDelta [ old . length - ] ; if ( index > ) System . arraycopy ( old , , array , , index ) ; int rest = old . length - index - ; if ( rest > ) System . arraycopy ( old , index + , array , index , rest ) ; return array ; } public void removed ( IRubyElement element ) { removed ( element , ) ; } public void removed ( IRubyElement element , int flags ) { RubyElementDelta removedDelta = new RubyElementDelta ( element ) ; insertDeltaTree ( element , removedDelta ) ; RubyElementDelta actualDelta = getDeltaFor ( element ) ; if ( actualDelta != null ) { actualDelta . removed ( ) ; actualDelta . changeFlags |= flags ; actualDelta . affectedChildren = EMPTY_DELTA ; } } public void sourceAttached ( IRubyElement element ) { RubyElementDelta attachedDelta = new RubyElementDelta ( element ) ; attachedDelta . changed ( F_SOURCEATTACHED ) ; insertDeltaTree ( element , attachedDelta ) ; } public void sourceDetached ( IRubyElement element ) { RubyElementDelta detachedDelta = new RubyElementDelta ( element ) ; detachedDelta . changed ( F_SOURCEDETACHED ) ; insertDeltaTree ( element , detachedDelta ) ; } public String toDebugString ( int depth ) { StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < depth ; i ++ ) { buffer . append ( '' ) ; } buffer . append ( ( ( RubyElement ) getElement ( ) ) . toDebugString ( ) ) ; toDebugString ( buffer ) ; IRubyElementDelta [ ] children = getAffectedChildren ( ) ; if ( children != null ) { for ( int i = ; i < children . length ; ++ i ) { buffer . append ( "" ) ; buffer . append ( ( ( RubyElementDelta ) children [ i ] ) . toDebugString ( depth + ) ) ; } } for ( int i = ; i < resourceDeltasCounter ; i ++ ) { buffer . append ( "" ) ; for ( int j = ; j < depth + ; j ++ ) { buffer . append ( '' ) ; } IResourceDelta resourceDelta = resourceDeltas [ i ] ; buffer . append ( resourceDelta . toString ( ) ) ; buffer . append ( "" ) ; switch ( resourceDelta . getKind ( ) ) { case IResourceDelta . ADDED : buffer . append ( '' ) ; break ; case IResourceDelta . REMOVED : buffer . append ( '' ) ; break ; case IResourceDelta . CHANGED : buffer . append ( '' ) ; break ; default : buffer . append ( '' ) ; break ; } buffer . append ( "" ) ; } return buffer . toString ( ) ; } protected boolean toDebugString ( StringBuffer buffer , int flags ) { boolean prev = super . toDebugString ( buffer , flags ) ; if ( ( flags & IRubyElementDelta . F_CHILDREN ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_CONTENT ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_MOVED_FROM ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" + ( ( RubyElement ) getMovedFromElement ( ) ) . toStringWithAncestors ( ) + "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_MOVED_TO ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" + ( ( RubyElement ) getMovedToElement ( ) ) . toStringWithAncestors ( ) + "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_ADDED_TO_CLASSPATH ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_REMOVED_FROM_CLASSPATH ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_REORDER ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_ARCHIVE_CONTENT_CHANGED ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_SOURCEATTACHED ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_SOURCEDETACHED ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_FINE_GRAINED ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_PRIMARY_WORKING_COPY ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_CLASSPATH_CHANGED ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_PRIMARY_RESOURCE ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_OPENED ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_CLOSED ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_AST_AFFECTED ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_CATEGORIES ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } return prev ; } public String toString ( ) { return toDebugString ( ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . ISourceRange ; public class SourceRange implements ISourceRange { private int offset , length ; public SourceRange ( int offset , int length ) { this . offset = offset ; this . length = length ; } public int getLength ( ) { return this . length ; } public int getOffset ( ) { return this . offset ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( this . offset ) ; buffer . append ( "" ) ; buffer . append ( this . length ) ; buffer . append ( "" ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . HashtableOfArrayToObject ; class RubyProjectElementInfo extends OpenableElementInfo { private Object [ ] nonRubyResources ; public ProjectCache projectCache ; static class ProjectCache { ProjectCache ( ISourceFolderRoot [ ] allPkgFragmentRootsCache , HashtableOfArrayToObject allPkgFragmentsCache , HashtableOfArrayToObject isPackageCache , Map rootToResolvedEntries ) { this . allPkgFragmentRootsCache = allPkgFragmentRootsCache ; this . allPkgFragmentsCache = allPkgFragmentsCache ; this . isPackageCache = isPackageCache ; this . rootToResolvedEntries = rootToResolvedEntries ; } public ISourceFolderRoot [ ] allPkgFragmentRootsCache ; public HashtableOfArrayToObject allPkgFragmentsCache ; public HashtableOfArrayToObject isPackageCache ; public Map rootToResolvedEntries ; } public RubyProjectElementInfo ( ) { this . nonRubyResources = null ; } private Object [ ] computeNonRubyResources ( RubyProject project ) { IPath projectPath = project . getProject ( ) . getFullPath ( ) ; boolean srcIsProject = false ; char [ ] [ ] inclusionPatterns = null ; char [ ] [ ] exclusionPatterns = null ; ILoadpathEntry [ ] classpath = null ; try { classpath = project . getResolvedLoadpath ( true , false , false ) ; for ( int i = ; i < classpath . length ; i ++ ) { ILoadpathEntry entry = classpath [ i ] ; if ( projectPath . equals ( entry . getPath ( ) ) ) { srcIsProject = true ; inclusionPatterns = ( ( LoadpathEntry ) entry ) . fullInclusionPatternChars ( ) ; exclusionPatterns = ( ( LoadpathEntry ) entry ) . fullExclusionPatternChars ( ) ; break ; } } } catch ( RubyModelException e ) { } Object [ ] resources = new IResource [ ] ; int resourcesCounter = ; try { IResource [ ] members = ( ( IContainer ) project . getResource ( ) ) . members ( ) ; for ( int i = , max = members . length ; i < max ; i ++ ) { IResource res = members [ i ] ; switch ( res . getType ( ) ) { case IResource . FILE : IPath resFullPath = res . getFullPath ( ) ; String resName = res . getName ( ) ; if ( srcIsProject && ! org . rubypeople . rdt . internal . core . util . Util . isExcluded ( res , inclusionPatterns , exclusionPatterns ) ) { break ; } if ( resources . length == resourcesCounter ) { System . arraycopy ( resources , , ( resources = new IResource [ resourcesCounter * ] ) , , resourcesCounter ) ; } resources [ resourcesCounter ++ ] = res ; break ; case IResource . FOLDER : resFullPath = res . getFullPath ( ) ; if ( ( srcIsProject && ! org . rubypeople . rdt . internal . core . util . Util . isExcluded ( res , inclusionPatterns , exclusionPatterns ) ) || this . isLoadpathEntryOrOutputLocation ( resFullPath , classpath ) ) { break ; } if ( resources . length == resourcesCounter ) { System . arraycopy ( resources , , ( resources = new IResource [ resourcesCounter * ] ) , , resourcesCounter ) ; } resources [ resourcesCounter ++ ] = res ; } } if ( resources . length != resourcesCounter ) { System . arraycopy ( resources , , ( resources = new IResource [ resourcesCounter ] ) , , resourcesCounter ) ; } } catch ( CoreException e ) { resources = NO_NON_RUBY_RESOURCES ; resourcesCounter = ; } return resources ; } Object [ ] getNonRubyResources ( RubyProject project ) { if ( this . nonRubyResources == null ) { this . nonRubyResources = computeNonRubyResources ( project ) ; } return this . nonRubyResources ; } private boolean isLoadpathEntryOrOutputLocation ( IPath path , ILoadpathEntry [ ] resolvedLoadpath ) { for ( int i = , length = resolvedLoadpath . length ; i < length ; i ++ ) { ILoadpathEntry entry = resolvedLoadpath [ i ] ; if ( entry . getPath ( ) . equals ( path ) ) { return true ; } } return false ; } void resetCaches ( ) { this . projectCache = null ; } void setNonRubyResources ( Object [ ] resources ) { this . nonRubyResources = resources ; } ProjectCache getProjectCache ( RubyProject project ) { ProjectCache cache = this . projectCache ; if ( cache == null ) { ISourceFolderRoot [ ] roots ; Map reverseMap = new HashMap ( ) ; try { roots = project . getAllSourceFolderRoots ( reverseMap ) ; } catch ( RubyModelException e ) { roots = new ISourceFolderRoot [ ] ; reverseMap . clear ( ) ; } HashtableOfArrayToObject fragmentsCache = new HashtableOfArrayToObject ( ) ; HashtableOfArrayToObject isPackageCache = new HashtableOfArrayToObject ( ) ; for ( int i = , length = roots . length ; i < length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; IRubyElement [ ] frags = null ; try { frags = root . getChildren ( ) ; } catch ( RubyModelException e ) { continue ; } for ( int j = , length2 = frags . length ; j < length2 ; j ++ ) { SourceFolder fragment = ( SourceFolder ) frags [ j ] ; String [ ] pkgName = fragment . names ; Object existing = fragmentsCache . get ( pkgName ) ; if ( existing == null ) { fragmentsCache . put ( pkgName , root ) ; addNames ( pkgName , isPackageCache ) ; } else { if ( existing instanceof SourceFolderRoot ) { fragmentsCache . put ( pkgName , new ISourceFolderRoot [ ] { ( SourceFolderRoot ) existing , root } ) ; } else { ISourceFolderRoot [ ] entry = ( ISourceFolderRoot [ ] ) existing ; ISourceFolderRoot [ ] copy = new ISourceFolderRoot [ entry . length + ] ; System . arraycopy ( entry , , copy , , entry . length ) ; copy [ entry . length ] = root ; fragmentsCache . put ( pkgName , copy ) ; } } } } cache = new ProjectCache ( roots , fragmentsCache , isPackageCache , reverseMap ) ; this . projectCache = cache ; } return cache ; } public static void addNames ( String [ ] name , HashtableOfArrayToObject set ) { set . put ( name , name ) ; int length = name . length ; for ( int i = length - ; i > ; i -- ) { String [ ] superName = new String [ i ] ; System . arraycopy ( name , , superName , , i ) ; set . put ( superName , superName ) ; } } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class RubyElementDeltaBuilder { IRubyElement rubyElement ; int maxDepth = Integer . MAX_VALUE ; Map infos ; Map oldPositions ; Map newPositions ; public RubyElementDelta delta ; ArrayList added ; ArrayList removed ; class ListItem { public IRubyElement previous ; public IRubyElement next ; public ListItem ( IRubyElement previous , IRubyElement next ) { this . previous = previous ; this . next = next ; } } public RubyElementDeltaBuilder ( IRubyElement rubyElement ) { this . rubyElement = rubyElement ; this . initialize ( ) ; this . recordElementInfo ( rubyElement , ( RubyModel ) this . rubyElement . getRubyModel ( ) , ) ; } public RubyElementDeltaBuilder ( IRubyElement rubyElement , int maxDepth ) { this . rubyElement = rubyElement ; this . maxDepth = maxDepth ; this . initialize ( ) ; this . recordElementInfo ( rubyElement , ( RubyModel ) this . rubyElement . getRubyModel ( ) , ) ; } private void added ( IRubyElement element ) { this . added . add ( element ) ; ListItem current = this . getNewPosition ( element ) ; ListItem previous = null , next = null ; if ( current . previous != null ) previous = this . getNewPosition ( current . previous ) ; if ( current . next != null ) next = this . getNewPosition ( current . next ) ; if ( previous != null ) previous . next = current . next ; if ( next != null ) next . previous = current . previous ; } public void buildDeltas ( ) { this . recordNewPositions ( this . rubyElement , ) ; this . findAdditions ( this . rubyElement , ) ; this . findDeletions ( ) ; this . findChangesInPositioning ( this . rubyElement , ) ; this . trimDelta ( this . delta ) ; if ( this . delta . getAffectedChildren ( ) . length == ) { this . delta . contentChanged ( ) ; } } private void findAdditions ( IRubyElement newElement , int depth ) { RubyElementInfo oldInfo = this . getElementInfo ( newElement ) ; if ( oldInfo == null && depth < this . maxDepth ) { this . delta . added ( newElement ) ; added ( newElement ) ; } else { this . removeElementInfo ( newElement ) ; } if ( depth >= this . maxDepth ) { this . delta . changed ( newElement , IRubyElementDelta . F_CONTENT ) ; return ; } RubyElementInfo newInfo = null ; try { newInfo = ( RubyElementInfo ) ( ( RubyElement ) newElement ) . getElementInfo ( ) ; } catch ( RubyModelException npe ) { return ; } this . findContentChange ( oldInfo , newInfo , newElement ) ; if ( oldInfo != null && newElement instanceof IParent ) { IRubyElement [ ] children = newInfo . getChildren ( ) ; if ( children != null ) { int length = children . length ; for ( int i = ; i < length ; i ++ ) { this . findAdditions ( children [ i ] , depth + ) ; } } } } private void findChangesInPositioning ( IRubyElement element , int depth ) { if ( depth >= this . maxDepth || this . added . contains ( element ) || this . removed . contains ( element ) ) return ; if ( ! isPositionedCorrectly ( element ) ) { this . delta . changed ( element , IRubyElementDelta . F_REORDER ) ; } if ( element instanceof IParent ) { RubyElementInfo info = null ; try { info = ( RubyElementInfo ) ( ( RubyElement ) element ) . getElementInfo ( ) ; } catch ( RubyModelException npe ) { return ; } IRubyElement [ ] children = info . getChildren ( ) ; if ( children != null ) { int length = children . length ; for ( int i = ; i < length ; i ++ ) { this . findChangesInPositioning ( children [ i ] , depth + ) ; } } } } private void findContentChange ( RubyElementInfo oldInfo , RubyElementInfo newInfo , IRubyElement newElement ) { if ( oldInfo instanceof MemberElementInfo && newInfo instanceof MemberElementInfo ) { if ( oldInfo instanceof RubyMethodElementInfo && newInfo instanceof RubyMethodElementInfo ) { RubyMethodElementInfo oldSourceMethodInfo = ( RubyMethodElementInfo ) oldInfo ; RubyMethodElementInfo newSourceMethodInfo = ( RubyMethodElementInfo ) newInfo ; if ( oldSourceMethodInfo . getVisibility ( ) != newSourceMethodInfo . getVisibility ( ) ) { this . delta . changed ( newElement , IRubyElementDelta . F_MODIFIERS ) ; } if ( ! CharOperation . equals ( oldSourceMethodInfo . getArgumentNames ( ) , newSourceMethodInfo . getArgumentNames ( ) ) ) { this . delta . changed ( newElement , IRubyElementDelta . F_CONTENT ) ; } } else if ( oldInfo instanceof RubyFieldElementInfo && newInfo instanceof RubyFieldElementInfo ) { if ( ( ( RubyFieldElementInfo ) oldInfo ) . getTypeName ( ) != null && ( ( RubyFieldElementInfo ) newInfo ) . getTypeName ( ) != null ) { if ( ! ( ( RubyFieldElementInfo ) oldInfo ) . getTypeName ( ) . equals ( ( ( RubyFieldElementInfo ) newInfo ) . getTypeName ( ) ) ) { this . delta . changed ( newElement , IRubyElementDelta . F_CONTENT ) ; } } } } if ( oldInfo instanceof RubyTypeElementInfo && newInfo instanceof RubyTypeElementInfo ) { RubyTypeElementInfo oldSourceTypeInfo = ( RubyTypeElementInfo ) oldInfo ; RubyTypeElementInfo newSourceTypeInfo = ( RubyTypeElementInfo ) newInfo ; if ( oldSourceTypeInfo . getSuperclassName ( ) != null && newSourceTypeInfo . getSuperclassName ( ) != null ) { if ( ! oldSourceTypeInfo . getSuperclassName ( ) . equals ( newSourceTypeInfo . getSuperclassName ( ) ) || ! CharOperation . equals ( oldSourceTypeInfo . getIncludedModuleNames ( ) , newSourceTypeInfo . getIncludedModuleNames ( ) ) ) { this . delta . changed ( newElement , IRubyElementDelta . F_SUPER_TYPES ) ; } } } } private void findDeletions ( ) { Iterator iter = this . infos . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { IRubyElement element = ( IRubyElement ) iter . next ( ) ; this . delta . removed ( element ) ; this . removed ( element ) ; } } private RubyElementInfo getElementInfo ( IRubyElement element ) { return ( RubyElementInfo ) this . infos . get ( element ) ; } private ListItem getNewPosition ( IRubyElement element ) { return ( ListItem ) this . newPositions . get ( element ) ; } private ListItem getOldPosition ( IRubyElement element ) { return ( ListItem ) this . oldPositions . get ( element ) ; } private void initialize ( ) { this . infos = new HashMap ( ) ; this . oldPositions = new HashMap ( ) ; this . newPositions = new HashMap ( ) ; this . putOldPosition ( this . rubyElement , new ListItem ( null , null ) ) ; this . putNewPosition ( this . rubyElement , new ListItem ( null , null ) ) ; this . delta = new RubyElementDelta ( rubyElement ) ; if ( rubyElement . getElementType ( ) >= IRubyElement . SCRIPT ) { this . delta . fineGrained ( ) ; } this . added = new ArrayList ( ) ; this . removed = new ArrayList ( ) ; } private void insertPositions ( IRubyElement [ ] elements , boolean isNew ) { int length = elements . length ; IRubyElement previous = null , current = null , next = ( length > ) ? elements [ ] : null ; for ( int i = ; i < length ; i ++ ) { previous = current ; current = next ; next = ( i + < length ) ? elements [ i + ] : null ; if ( isNew ) { this . putNewPosition ( current , new ListItem ( previous , next ) ) ; } else { this . putOldPosition ( current , new ListItem ( previous , next ) ) ; } } } private boolean isPositionedCorrectly ( IRubyElement element ) { ListItem oldListItem = this . getOldPosition ( element ) ; if ( oldListItem == null ) return false ; ListItem newListItem = this . getNewPosition ( element ) ; if ( newListItem == null ) return false ; IRubyElement oldPrevious = oldListItem . previous ; IRubyElement newPrevious = newListItem . previous ; if ( oldPrevious == null ) { return newPrevious == null ; } else { return oldPrevious . equals ( newPrevious ) ; } } private void putElementInfo ( IRubyElement element , RubyElementInfo info ) { this . infos . put ( element , info ) ; } private void putNewPosition ( IRubyElement element , ListItem position ) { this . newPositions . put ( element , position ) ; } private void putOldPosition ( IRubyElement element , ListItem position ) { this . oldPositions . put ( element , position ) ; } private void recordElementInfo ( IRubyElement element , RubyModel model , int depth ) { if ( depth >= this . maxDepth ) { return ; } RubyElementInfo info = ( RubyElementInfo ) RubyModelManager . getRubyModelManager ( ) . getInfo ( element ) ; if ( info == null ) return ; this . putElementInfo ( element , info ) ; if ( element instanceof IParent ) { IRubyElement [ ] children = info . getChildren ( ) ; if ( children != null ) { insertPositions ( children , false ) ; for ( int i = , length = children . length ; i < length ; i ++ ) recordElementInfo ( children [ i ] , model , depth + ) ; } } } private void recordNewPositions ( IRubyElement newElement , int depth ) { if ( depth < this . maxDepth && newElement instanceof IParent ) { RubyElementInfo info = null ; try { info = ( RubyElementInfo ) ( ( RubyElement ) newElement ) . getElementInfo ( ) ; } catch ( RubyModelException npe ) { return ; } IRubyElement [ ] children = info . getChildren ( ) ; if ( children != null ) { insertPositions ( children , true ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { recordNewPositions ( children [ i ] , depth + ) ; } } } } private void removed ( IRubyElement element ) { this . removed . add ( element ) ; ListItem current = this . getOldPosition ( element ) ; ListItem previous = null , next = null ; if ( current . previous != null ) previous = this . getOldPosition ( current . previous ) ; if ( current . next != null ) next = this . getOldPosition ( current . next ) ; if ( previous != null ) previous . next = current . next ; if ( next != null ) next . previous = current . previous ; } private void removeElementInfo ( IRubyElement element ) { this . infos . remove ( element ) ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( this . delta . toString ( ) ) ; return buffer . toString ( ) ; } private void trimDelta ( RubyElementDelta elementDelta ) { if ( elementDelta . getKind ( ) == IRubyElementDelta . REMOVED ) { IRubyElementDelta [ ] children = elementDelta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { elementDelta . removeAffectedChild ( ( RubyElementDelta ) children [ i ] ) ; } } else { IRubyElementDelta [ ] children = elementDelta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { trimDelta ( ( RubyElementDelta ) children [ i ] ) ; } } } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . RubyModelException ; public class SourceFolderInfo extends OpenableElementInfo { protected Object [ ] nonRubyResources ; public SourceFolderInfo ( ) { this . nonRubyResources = null ; } boolean containsRubyResources ( ) { return this . children . length != ; } Object [ ] getNonRubyResources ( IResource underlyingResource , SourceFolderRoot rootHandle ) { if ( this . nonRubyResources == null ) { try { this . nonRubyResources = SourceFolderRootInfo . computeFolderNonRubyResources ( ( RubyProject ) rootHandle . getRubyProject ( ) , ( IContainer ) underlyingResource , rootHandle . fullInclusionPatternChars ( ) , rootHandle . fullExclusionPatternChars ( ) ) ; } catch ( RubyModelException e ) { this . nonRubyResources = NO_NON_RUBY_RESOURCES ; } } return this . nonRubyResources ; } void setNonRubyResources ( Object [ ] resources ) { this . nonRubyResources = resources ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . HashMap ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . PlatformObject ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; import org . rubypeople . rdt . internal . core . util . Util ; public abstract class RubyElement extends PlatformObject implements IRubyElement { public static final char JEM_ESCAPE = '' ; public static final char JEM_RUBYPROJECT = '' ; public static final char JEM_SOURCEFOLDERROOT = '' ; public static final char JEM_SOURCE_FOLDER = '' ; public static final char JEM_FIELD = '' ; public static final char JEM_METHOD = '' ; public static final char JEM_RUBYSCRIPT = '' ; public static final char JEM_TYPE = '' ; public static final char JEM_IMPORTDECLARATION = '' ; public static final char JEM_COUNT = '' ; public static final char JEM_LOCALVARIABLE = '' ; public static final IRubyElement [ ] NO_ELEMENTS = new IRubyElement [ ] ; protected static final Object NO_INFO = new Object ( ) ; protected RubyElement parent ; public RubyElement ( RubyElement parent ) { this . parent = parent ; } public String getElementName ( ) { return "" ; } public boolean equals ( Object o ) { if ( this == o ) return true ; if ( this . parent == null ) return super . equals ( o ) ; RubyElement other = ( RubyElement ) o ; return getElementName ( ) . equals ( other . getElementName ( ) ) && this . parent . equals ( other . parent ) ; } public boolean exists ( ) { try { getElementInfo ( ) ; return true ; } catch ( RubyModelException e ) { } return false ; } public abstract int getElementType ( ) ; void setParent ( RubyElement parent ) { this . parent = parent ; } public IRubyElement getParent ( ) { return parent ; } public IRubyElement getPrimaryElement ( ) { return getPrimaryElement ( true ) ; } public IRubyElement getPrimaryElement ( boolean checkOwner ) { return this ; } protected IRubyElement getSourceElementAt ( int position ) throws RubyModelException { if ( this instanceof ISourceReference ) { IRubyElement [ ] children = getChildren ( ) ; for ( int i = children . length - ; i >= ; i -- ) { IRubyElement aChild = children [ i ] ; if ( aChild instanceof SourceRefElement ) { SourceRefElement child = ( SourceRefElement ) children [ i ] ; ISourceRange range = child . getSourceRange ( ) ; int start = range . getOffset ( ) ; int end = start + range . getLength ( ) ; if ( start <= position && position <= end ) { if ( child instanceof IField ) { int declarationStart = start ; SourceRefElement candidate = null ; do { range = ( ( IField ) child ) . getNameRange ( ) ; if ( position <= range . getOffset ( ) + range . getLength ( ) ) { candidate = child ; } else { return candidate == null ? child . getSourceElementAt ( position ) : candidate . getSourceElementAt ( position ) ; } child = -- i >= ? ( SourceRefElement ) children [ i ] : null ; } while ( child != null && child . getSourceRange ( ) . getOffset ( ) == declarationStart ) ; return candidate . getSourceElementAt ( position ) ; } else if ( child instanceof IParent ) { return child . getSourceElementAt ( position ) ; } else { return child ; } } } } } else { Assert . isTrue ( false ) ; } return this ; } public IRubyElement getAncestor ( int ancestorType ) { IRubyElement element = this ; while ( element != null ) { if ( element . getElementType ( ) == ancestorType ) return element ; element = element . getParent ( ) ; } return null ; } public IRubyElement [ ] getChildren ( ) throws RubyModelException { Object elementInfo = getElementInfo ( ) ; if ( elementInfo instanceof RubyElementInfo ) { return ( ( RubyElementInfo ) elementInfo ) . getChildren ( ) ; } return NO_ELEMENTS ; } public ArrayList < IRubyElement > getChildrenOfType ( int type ) throws RubyModelException { IRubyElement [ ] children = getChildren ( ) ; int size = children . length ; ArrayList < IRubyElement > list = new ArrayList < IRubyElement > ( size ) ; for ( int i = ; i < size ; ++ i ) { RubyElement elt = ( RubyElement ) children [ i ] ; if ( elt . getElementType ( ) == type ) { list . add ( elt ) ; } } return list ; } public boolean hasChildren ( ) throws RubyModelException { Object elementInfo = RubyModelManager . getRubyModelManager ( ) . getInfo ( this ) ; if ( elementInfo instanceof RubyElementInfo ) { return ( ( RubyElementInfo ) elementInfo ) . getChildren ( ) . length > ; } return true ; } public int hashCode ( ) { if ( this . parent == null ) return super . hashCode ( ) ; return Util . combineHashCodes ( getElementName ( ) . hashCode ( ) , this . parent . hashCode ( ) ) ; } public boolean isType ( int type ) { return type == getElementType ( ) ; } public IRubyScript getRubyScript ( ) { return null ; } public IRubyProject getRubyProject ( ) { IRubyElement current = this ; do { if ( current instanceof IRubyProject ) return ( IRubyProject ) current ; } while ( ( current = current . getParent ( ) ) != null ) ; return null ; } public boolean isReadOnly ( ) { return false ; } public IRubyModel getRubyModel ( ) { IRubyElement current = this ; do { if ( current instanceof IRubyModel ) return ( IRubyModel ) current ; } while ( ( current = current . getParent ( ) ) != null ) ; return null ; } public void close ( ) throws RubyModelException { RubyModelManager . getRubyModelManager ( ) . removeInfoAndChildren ( this ) ; } protected abstract void closing ( Object info ) throws RubyModelException ; public boolean isAncestorOf ( IRubyElement e ) { IRubyElement parentElement = e . getParent ( ) ; while ( parentElement != null && ! parentElement . equals ( this ) ) { parentElement = parentElement . getParent ( ) ; } return parentElement != null ; } protected Object openWhenClosed ( Object info , IProgressMonitor monitor ) throws RubyModelException { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; boolean hadTemporaryCache = manager . hasTemporaryCache ( ) ; try { HashMap newElements = manager . getTemporaryCache ( ) ; generateInfos ( info , newElements , monitor ) ; if ( info == null ) { info = newElements . get ( this ) ; } if ( info == null ) { Openable openable = ( Openable ) getOpenable ( ) ; if ( newElements . containsKey ( openable ) ) { openable . closeBuffer ( ) ; } throw newNotPresentException ( ) ; } if ( ! hadTemporaryCache ) { manager . putInfos ( this , newElements ) ; } } finally { if ( ! hadTemporaryCache ) { manager . resetTemporaryCache ( ) ; } } return info ; } public RubyModelException newNotPresentException ( ) { return new RubyModelException ( new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST , this ) ) ; } public RubyModelException newRubyModelException ( IStatus status ) { if ( status instanceof IRubyModelStatus ) return new RubyModelException ( ( IRubyModelStatus ) status ) ; return new RubyModelException ( new RubyModelStatus ( status . getSeverity ( ) , status . getCode ( ) , status . getMessage ( ) ) ) ; } abstract protected void generateInfos ( Object info , HashMap newElements , IProgressMonitor monitor ) throws RubyModelException ; public IOpenable getOpenable ( ) { return this . getOpenableParent ( ) ; } public IOpenable getOpenableParent ( ) { return ( IOpenable ) this . parent ; } public String readableName ( ) { return this . getElementName ( ) ; } public Object getElementInfo ( ) throws RubyModelException { return getElementInfo ( null ) ; } public Object getElementInfo ( IProgressMonitor monitor ) throws RubyModelException { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; Object info = manager . getInfo ( this ) ; if ( info != null ) return info ; return openWhenClosed ( createElementInfo ( ) , monitor ) ; } protected abstract Object createElementInfo ( ) ; protected String tabString ( int tab ) { StringBuffer buffer = new StringBuffer ( ) ; for ( int i = tab ; i > ; i -- ) buffer . append ( "" ) ; return buffer . toString ( ) ; } public String toDebugString ( ) { StringBuffer buffer = new StringBuffer ( ) ; this . toStringInfo ( , buffer , NO_INFO ) ; return buffer . toString ( ) ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; toString ( , buffer ) ; return buffer . toString ( ) ; } protected void toString ( int tab , StringBuffer buffer ) { Object info = this . toStringInfo ( tab , buffer ) ; if ( tab == ) { this . toStringAncestors ( buffer ) ; } this . toStringChildren ( tab , buffer , info ) ; } public String toStringWithAncestors ( boolean showResolvedInfo ) { StringBuffer buffer = new StringBuffer ( ) ; this . toStringInfo ( , buffer , NO_INFO , showResolvedInfo ) ; this . toStringAncestors ( buffer ) ; return buffer . toString ( ) ; } protected void toStringInfo ( int tab , StringBuffer buffer , Object info , boolean showResolvedInfo ) { buffer . append ( this . tabString ( tab ) ) ; toStringName ( buffer ) ; if ( info == null ) { buffer . append ( "" ) ; } } public String toStringWithAncestors ( ) { StringBuffer buffer = new StringBuffer ( ) ; this . toStringInfo ( , buffer , NO_INFO ) ; this . toStringAncestors ( buffer ) ; return buffer . toString ( ) ; } protected void toStringAncestors ( StringBuffer buffer ) { RubyElement parentElement = ( RubyElement ) this . getParent ( ) ; if ( parentElement != null && parentElement . getParent ( ) != null ) { buffer . append ( "" ) ; parentElement . toStringInfo ( , buffer , NO_INFO ) ; parentElement . toStringAncestors ( buffer ) ; buffer . append ( "" ) ; } } protected void toStringChildren ( int tab , StringBuffer buffer , Object info ) { if ( info == null || ! ( info instanceof RubyElementInfo ) ) return ; IRubyElement [ ] children = ( ( RubyElementInfo ) info ) . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { buffer . append ( "" ) ; ( ( RubyElement ) children [ i ] ) . toString ( tab + , buffer ) ; } } public Object toStringInfo ( int tab , StringBuffer buffer ) { Object info = RubyModelManager . getRubyModelManager ( ) . peekAtInfo ( this ) ; this . toStringInfo ( tab , buffer , info ) ; return info ; } protected void toStringInfo ( int tab , StringBuffer buffer , Object info ) { buffer . append ( this . tabString ( tab ) ) ; toStringName ( buffer ) ; if ( info == null ) { buffer . append ( "" ) ; } } protected void toStringName ( StringBuffer buffer ) { buffer . append ( getElementName ( ) ) ; } public Node findNode ( Node cuAST ) { return null ; } public abstract IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner owner ) ; public IRubyElement getHandleFromMemento ( MementoTokenizer memento , WorkingCopyOwner owner ) { if ( ! memento . hasMoreTokens ( ) ) return this ; String token = memento . nextToken ( ) ; return getHandleFromMemento ( token , memento , owner ) ; } public String getHandleIdentifier ( ) { return getHandleMemento ( ) ; } public String getHandleMemento ( ) { StringBuffer buff = new StringBuffer ( ) ; getHandleMemento ( buff ) ; return buff . toString ( ) ; } protected void getHandleMemento ( StringBuffer buff ) { ( ( RubyElement ) getParent ( ) ) . getHandleMemento ( buff ) ; buff . append ( getHandleMementoDelimiter ( ) ) ; escapeMementoName ( buff , getElementName ( ) ) ; } protected abstract char getHandleMementoDelimiter ( ) ; protected void escapeMementoName ( StringBuffer buffer , String mementoName ) { for ( int i = , length = mementoName . length ( ) ; i < length ; i ++ ) { char character = mementoName . charAt ( i ) ; switch ( character ) { case JEM_ESCAPE : case JEM_COUNT : case JEM_RUBYPROJECT : case JEM_SOURCEFOLDERROOT : case JEM_SOURCE_FOLDER : case JEM_FIELD : case JEM_METHOD : case JEM_RUBYSCRIPT : case JEM_TYPE : case JEM_IMPORTDECLARATION : case JEM_LOCALVARIABLE : buffer . append ( JEM_ESCAPE ) ; } buffer . append ( character ) ; } } public IRubyElement unresolved ( ) { return this ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; public class RubyType extends NamedMember implements IType { private static final String [ ] CORE_NAMES = new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; public RubyType ( RubyElement parent , String name ) { super ( parent , name ) ; } public String getSuperclassName ( ) throws RubyModelException { if ( isCoreClass ( ) && ! isCoreStub ( ) ) { IType type = getCoreClass ( getElementName ( ) ) ; if ( type != null ) return type . getSuperclassName ( ) ; } RubyTypeElementInfo info = ( RubyTypeElementInfo ) getElementInfo ( ) ; return info . getSuperclassName ( ) ; } private boolean isCoreStub ( ) throws RubyModelException { ISourceFolderRoot root = ( ISourceFolderRoot ) getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; return root . equals ( getCoreStubRoot ( ) ) ; } private IType getCoreClass ( String elementName ) throws RubyModelException { ISourceFolderRoot root = getCoreStubRoot ( ) ; if ( root == null ) return null ; ISourceFolder folder = root . getSourceFolder ( new String [ ] ) ; IRubyScript script = folder . getRubyScript ( elementName . toLowerCase ( ) + "" ) ; return script . getType ( elementName ) ; } private ISourceFolderRoot getCoreStubRoot ( ) throws RubyModelException { ISourceFolderRoot [ ] roots = getRubyProject ( ) . getSourceFolderRoots ( ) ; for ( int i = ; i < roots . length ; i ++ ) { IPath path = roots [ i ] . getPath ( ) ; String string = path . toPortableString ( ) ; if ( string . contains ( "" ) ) { return roots [ i ] ; } } return null ; } private boolean isCoreClass ( ) { String name = getElementName ( ) ; for ( int i = ; i < CORE_NAMES . length ; i ++ ) { if ( CORE_NAMES [ i ] . equals ( name ) ) return true ; } return false ; } public String [ ] getIncludedModuleNames ( ) throws RubyModelException { RubyTypeElementInfo info = ( RubyTypeElementInfo ) getElementInfo ( ) ; String [ ] modules = info . getIncludedModuleNames ( ) ; if ( ( modules == null || modules . length == ) && getFullyQualifiedName ( ) . equals ( "" ) ) { return new String [ ] { "" } ; } return modules ; } public boolean isMember ( ) { return getDeclaringType ( ) != null ; } public int getElementType ( ) { return IRubyElement . TYPE ; } public IField getField ( String fieldName ) { if ( fieldName . startsWith ( "" ) ) return new RubyClassVar ( this , fieldName ) ; if ( fieldName . startsWith ( "" ) ) return new RubyInstVar ( this , fieldName ) ; if ( fieldName . startsWith ( "" ) ) return new RubyGlobal ( this , fieldName ) ; if ( Character . isUpperCase ( fieldName . charAt ( ) ) ) return new RubyConstant ( this , fieldName ) ; Assert . isTrue ( false , "" ) ; return null ; } public IField [ ] getFields ( ) throws RubyModelException { ArrayList list = getChildrenOfType ( CONSTANT ) ; list . addAll ( getChildrenOfType ( INSTANCE_VAR ) ) ; list . addAll ( getChildrenOfType ( CLASS_VAR ) ) ; IField [ ] array = new IField [ list . size ( ) ] ; list . toArray ( array ) ; return array ; } public IMethod getMethod ( String name , String [ ] parameterNames ) { return new RubyMethod ( this , name , parameterNames ) ; } public IMethod [ ] getMethods ( ) throws RubyModelException { ArrayList list = getChildrenOfType ( METHOD ) ; IMethod [ ] array = new IMethod [ list . size ( ) ] ; list . toArray ( array ) ; return array ; } public IType getDeclaringType ( ) { IRubyElement parentElement = getParent ( ) ; while ( parentElement != null ) { if ( parentElement . getElementType ( ) == IRubyElement . TYPE ) { return ( IType ) parentElement ; } else if ( parentElement instanceof IMember ) { parentElement = parentElement . getParent ( ) ; } else { return null ; } } return null ; } public IRubyElement getPrimaryElement ( boolean checkOwner ) { if ( checkOwner ) { RubyScript cu = ( RubyScript ) getAncestor ( SCRIPT ) ; if ( cu . isPrimary ( ) ) return this ; } IRubyElement primaryParent = this . parent . getPrimaryElement ( false ) ; switch ( primaryParent . getElementType ( ) ) { case IRubyElement . SCRIPT : return ( ( IRubyScript ) primaryParent ) . getType ( this . name ) ; case IRubyElement . TYPE : return ( ( IType ) primaryParent ) . getType ( this . name ) ; case IRubyElement . INSTANCE_VAR : case IRubyElement . CLASS_VAR : case IRubyElement . BLOCK : case IRubyElement . LOCAL_VARIABLE : case IRubyElement . METHOD : return ( ( IMember ) primaryParent ) . getType ( this . name , this . occurrenceCount ) ; } return this ; } public IType getType ( String typeName ) { return new RubyType ( this , typeName ) ; } public boolean equals ( Object o ) { if ( ! ( o instanceof RubyType ) ) return false ; return super . equals ( o ) ; } public boolean isClass ( ) { return true ; } public boolean isModule ( ) { return false ; } public IMethod createMethod ( String contents , IRubyElement sibling , boolean force , IProgressMonitor monitor ) throws RubyModelException { CreateMethodOperation op = new CreateMethodOperation ( this , contents , force ) ; if ( sibling != null ) { op . createBefore ( sibling ) ; } op . runOperation ( monitor ) ; return ( IMethod ) op . getResultElements ( ) [ ] ; } public ISourceFolder getSourceFolder ( ) { IRubyElement parentElement = this . parent ; while ( parentElement != null ) { if ( parentElement . getElementType ( ) == IRubyElement . SOURCE_FOLDER ) { return ( ISourceFolder ) parentElement ; } else { parentElement = parentElement . getParent ( ) ; } } Assert . isTrue ( false ) ; return null ; } public String getFullyQualifiedName ( ) { IType declaring = getDeclaringType ( ) ; if ( declaring != null ) { return declaring . getFullyQualifiedName ( ) + "" + getElementName ( ) ; } return getElementName ( ) ; } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner workingCopyOwner ) { switch ( token . charAt ( ) ) { case JEM_COUNT : return getHandleUpdatingCountFromMemento ( memento , workingCopyOwner ) ; case JEM_FIELD : if ( ! memento . hasMoreTokens ( ) ) return this ; String fieldName = memento . nextToken ( ) ; RubyElement field = ( RubyElement ) getField ( fieldName ) ; return field . getHandleFromMemento ( memento , workingCopyOwner ) ; case JEM_METHOD : if ( ! memento . hasMoreTokens ( ) ) return this ; String selector = memento . nextToken ( ) ; ArrayList params = new ArrayList ( ) ; nextParam : while ( memento . hasMoreTokens ( ) ) { token = memento . nextToken ( ) ; switch ( token . charAt ( ) ) { case JEM_TYPE : break nextParam ; case JEM_METHOD : if ( ! memento . hasMoreTokens ( ) ) return this ; String param = memento . nextToken ( ) ; StringBuffer buffer = new StringBuffer ( ) ; params . add ( buffer . toString ( ) + param ) ; break ; default : break nextParam ; } } String [ ] parameters = new String [ params . size ( ) ] ; params . toArray ( parameters ) ; RubyElement method = ( RubyElement ) getMethod ( selector , parameters ) ; switch ( token . charAt ( ) ) { case JEM_TYPE : case JEM_LOCALVARIABLE : return method . getHandleFromMemento ( token , memento , workingCopyOwner ) ; default : return method ; } case JEM_TYPE : String typeName ; if ( memento . hasMoreTokens ( ) ) { typeName = memento . nextToken ( ) ; char firstChar = typeName . charAt ( ) ; if ( firstChar == JEM_FIELD || firstChar == JEM_METHOD || firstChar == JEM_TYPE || firstChar == JEM_COUNT ) { token = typeName ; typeName = "" ; } else { token = null ; } } else { typeName = "" ; token = null ; } RubyElement type = ( RubyElement ) getType ( typeName ) ; if ( token == null ) { return type . getHandleFromMemento ( memento , workingCopyOwner ) ; } else { return type . getHandleFromMemento ( token , memento , workingCopyOwner ) ; } } return null ; } public String getTypeQualifiedName ( String enclosingTypeSeparator ) { try { return getTypeQualifiedName ( enclosingTypeSeparator , false ) ; } catch ( RubyModelException e ) { return null ; } } public IType [ ] getTypes ( ) throws RubyModelException { ArrayList list = getChildrenOfType ( TYPE ) ; IType [ ] array = new IType [ list . size ( ) ] ; list . toArray ( array ) ; return array ; } public ITypeHierarchy newTypeHierarchy ( IProgressMonitor monitor ) throws RubyModelException { CreateTypeHierarchyOperation op = new CreateTypeHierarchyOperation ( this , null , SearchEngine . createWorkspaceScope ( ) , true ) ; op . runOperation ( monitor ) ; return op . getResult ( ) ; } public ITypeHierarchy newTypeHierarchy ( WorkingCopyOwner owner , IProgressMonitor monitor ) throws RubyModelException { IRubyScript [ ] workingCopies = RubyModelManager . getRubyModelManager ( ) . getWorkingCopies ( owner , true ) ; CreateTypeHierarchyOperation op = new CreateTypeHierarchyOperation ( this , workingCopies , SearchEngine . createWorkspaceScope ( ) , true ) ; op . runOperation ( monitor ) ; return op . getResult ( ) ; } public ITypeHierarchy newSupertypeHierarchy ( IProgressMonitor monitor ) throws RubyModelException { return this . newSupertypeHierarchy ( DefaultWorkingCopyOwner . PRIMARY , monitor ) ; } public ITypeHierarchy newSupertypeHierarchy ( WorkingCopyOwner owner , IProgressMonitor monitor ) throws RubyModelException { IRubyScript [ ] workingCopies = RubyModelManager . getRubyModelManager ( ) . getWorkingCopies ( owner , true ) ; CreateTypeHierarchyOperation op = new CreateTypeHierarchyOperation ( this , workingCopies , SearchEngine . createWorkspaceScope ( ) , false ) ; op . runOperation ( monitor ) ; return op . getResult ( ) ; } public IMethod [ ] findMethods ( IMethod method ) { List < IMethod > filtered = new ArrayList < IMethod > ( ) ; try { ArrayList < IRubyElement > list = getChildrenOfType ( METHOD ) ; for ( IRubyElement element : list ) { IMethod other = ( IMethod ) element ; if ( ! other . getElementName ( ) . equals ( method . getElementName ( ) ) ) continue ; filtered . add ( other ) ; } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } IMethod [ ] array = new IMethod [ filtered . size ( ) ] ; filtered . toArray ( array ) ; return array ; } } package org . rubypeople . rdt . internal . core ; public class RubyInstVar extends RubyField { public RubyInstVar ( RubyElement parent , String name ) { super ( parent , name ) ; } public int getElementType ( ) { return RubyElement . INSTANCE_VAR ; } } package org . rubypeople . rdt . internal . core ; import java . io . ByteArrayOutputStream ; import java . io . OutputStreamWriter ; import java . io . UnsupportedEncodingException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . AssertionFailedException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . ILoadpathAttribute ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . w3c . dom . DOMException ; import org . w3c . dom . Element ; import org . w3c . dom . NamedNodeMap ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . w3c . dom . Text ; public class LoadpathEntry implements ILoadpathEntry { public static final String TAG_LOADPATH = "" ; public static final String TAG_LOADPATHENTRY = "" ; public static final String TAG_KIND = "" ; public static final String TAG_PATH = "" ; public static final String TAG_EXPORTED = "" ; public static final String TAG_INCLUDING = "" ; public static final String TAG_EXCLUDING = "" ; public static final String TAG_ATTRIBUTES = "" ; public static final String TAG_ATTRIBUTE = "" ; public static final String TAG_ATTRIBUTE_NAME = "" ; public static final String TAG_ATTRIBUTE_VALUE = "" ; static class UnknownXmlElements { String [ ] attributes ; ArrayList children ; } private static final String TYPE_PROJECT = "" ; private String rootID ; private int entryKind ; private IPath path ; private IPath [ ] inclusionPatterns ; private char [ ] [ ] fullInclusionPatternChars ; private IPath [ ] exclusionPatterns ; private char [ ] [ ] fullExclusionPatternChars ; private final static char [ ] [ ] UNINIT_PATTERNS = new char [ ] [ ] { "" . toCharArray ( ) } ; public final static ILoadpathAttribute [ ] NO_EXTRA_ATTRIBUTES = { } ; public final static IPath [ ] INCLUDE_ALL = { } ; public final static IPath [ ] EXCLUDE_NONE = { } ; private IProject project ; private boolean isExported ; ILoadpathAttribute [ ] extraAttributes ; public LoadpathEntry ( int entryKind , IPath path , IPath [ ] inclusionPatterns , IPath [ ] exclusionPatterns , ILoadpathAttribute [ ] extraAttributes , boolean isExported ) { this . path = path ; this . entryKind = entryKind ; this . inclusionPatterns = inclusionPatterns ; this . exclusionPatterns = exclusionPatterns ; this . extraAttributes = extraAttributes ; if ( inclusionPatterns != INCLUDE_ALL && inclusionPatterns . length > ) { this . fullInclusionPatternChars = UNINIT_PATTERNS ; } if ( exclusionPatterns . length > ) { this . fullExclusionPatternChars = UNINIT_PATTERNS ; } this . isExported = isExported ; } public IPath getPath ( ) { return path ; } public int getEntryKind ( ) { return this . entryKind ; } static String kindToString ( int kind ) { switch ( kind ) { case ILoadpathEntry . CPE_PROJECT : return TYPE_PROJECT ; case ILoadpathEntry . CPE_SOURCE : return "" ; case ILoadpathEntry . CPE_LIBRARY : return "" ; case ILoadpathEntry . CPE_VARIABLE : return "" ; case ILoadpathEntry . CPE_CONTAINER : return "" ; default : return "" ; } } public String toXML ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( LoadpathEntry . kindToString ( entryKind ) + "" ) ; buffer . append ( "" + getPath ( ) + "" ) ; return buffer . toString ( ) ; } public String rootID ( ) { if ( this . rootID == null ) { switch ( this . entryKind ) { case ILoadpathEntry . CPE_LIBRARY : this . rootID = "" + this . path ; break ; case ILoadpathEntry . CPE_PROJECT : this . rootID = "" + this . path ; break ; case ILoadpathEntry . CPE_SOURCE : this . rootID = "" + this . path ; break ; case ILoadpathEntry . CPE_VARIABLE : this . rootID = "" + this . path ; break ; case ILoadpathEntry . CPE_CONTAINER : this . rootID = "" + this . path ; break ; default : this . rootID = "" ; break ; } } return this . rootID ; } public char [ ] [ ] fullExclusionPatternChars ( ) { if ( this . fullExclusionPatternChars == UNINIT_PATTERNS ) { int length = this . exclusionPatterns . length ; this . fullExclusionPatternChars = new char [ length ] [ ] ; IPath prefixPath = this . path . removeTrailingSeparator ( ) ; for ( int i = ; i < length ; i ++ ) { this . fullExclusionPatternChars [ i ] = prefixPath . append ( this . exclusionPatterns [ i ] ) . toString ( ) . toCharArray ( ) ; } } return this . fullExclusionPatternChars ; } public char [ ] [ ] fullInclusionPatternChars ( ) { if ( this . fullInclusionPatternChars == UNINIT_PATTERNS ) { int length = this . inclusionPatterns . length ; this . fullInclusionPatternChars = new char [ length ] [ ] ; IPath prefixPath = this . path . removeTrailingSeparator ( ) ; for ( int i = ; i < length ; i ++ ) { this . fullInclusionPatternChars [ i ] = prefixPath . append ( this . inclusionPatterns [ i ] ) . toString ( ) . toCharArray ( ) ; } } return this . fullInclusionPatternChars ; } public boolean isExported ( ) { return this . isExported ; } public IPath [ ] getExclusionPatterns ( ) { return exclusionPatterns ; } public IPath [ ] getInclusionPatterns ( ) { return inclusionPatterns ; } public LoadpathEntry combineWith ( LoadpathEntry referringEntry ) { if ( referringEntry == null ) return this ; if ( referringEntry . isExported ( ) ) { return new LoadpathEntry ( getEntryKind ( ) , getPath ( ) , this . inclusionPatterns , this . exclusionPatterns , this . extraAttributes , referringEntry . isExported ( ) || this . isExported ) ; } return this ; } public static ILoadpathEntry elementDecode ( Element element , IRubyProject project , Map unknownElements ) { IPath projectPath = project . getProject ( ) . getFullPath ( ) ; NamedNodeMap attributes = element . getAttributes ( ) ; NodeList children = element . getChildNodes ( ) ; boolean [ ] foundChildren = new boolean [ children . getLength ( ) ] ; String kindAttr = removeAttribute ( TAG_KIND , attributes ) ; String pathAttr = removeAttribute ( TAG_PATH , attributes ) ; IPath path = new Path ( pathAttr ) ; int kind = kindFromString ( kindAttr ) ; if ( kind != ILoadpathEntry . CPE_VARIABLE && kind != ILoadpathEntry . CPE_CONTAINER && ! path . isAbsolute ( ) ) { path = projectPath . append ( path ) ; } boolean isExported = removeAttribute ( TAG_EXPORTED , attributes ) . equals ( "" ) ; IPath [ ] inclusionPatterns = decodePatterns ( attributes , TAG_INCLUDING ) ; if ( inclusionPatterns == null ) inclusionPatterns = INCLUDE_ALL ; IPath [ ] exclusionPatterns = decodePatterns ( attributes , TAG_EXCLUDING ) ; if ( exclusionPatterns == null ) exclusionPatterns = EXCLUDE_NONE ; NodeList attributeList = getChildAttributes ( TAG_ATTRIBUTES , children , foundChildren ) ; ILoadpathAttribute [ ] extraAttributes = decodeExtraAttributes ( attributeList ) ; String [ ] unknownAttributes = null ; ArrayList unknownChildren = null ; if ( unknownElements != null ) { int unknownAttributeLength = attributes . getLength ( ) ; if ( unknownAttributeLength != ) { unknownAttributes = new String [ unknownAttributeLength * ] ; for ( int i = ; i < unknownAttributeLength ; i ++ ) { Node attribute = attributes . item ( i ) ; unknownAttributes [ i * ] = attribute . getNodeName ( ) ; unknownAttributes [ i * + ] = attribute . getNodeValue ( ) ; } } for ( int i = , length = foundChildren . length ; i < length ; i ++ ) { if ( ! foundChildren [ i ] ) { Node node = children . item ( i ) ; if ( node . getNodeType ( ) != Node . ELEMENT_NODE ) continue ; if ( unknownChildren == null ) unknownChildren = new ArrayList ( ) ; StringBuffer buffer = new StringBuffer ( ) ; decodeUnknownNode ( node , buffer , project ) ; unknownChildren . add ( buffer . toString ( ) ) ; } } } ILoadpathEntry entry = null ; switch ( kind ) { case ILoadpathEntry . CPE_PROJECT : entry = new LoadpathEntry ( ILoadpathEntry . CPE_PROJECT , path , LoadpathEntry . INCLUDE_ALL , LoadpathEntry . EXCLUDE_NONE , extraAttributes , isExported ) ; break ; case ILoadpathEntry . CPE_LIBRARY : entry = RubyCore . newLibraryEntry ( path , extraAttributes , isExported ) ; break ; case ILoadpathEntry . CPE_SOURCE : String projSegment = path . segment ( ) ; if ( projSegment != null && projSegment . equals ( project . getElementName ( ) ) ) { entry = RubyCore . newSourceEntry ( path , inclusionPatterns , exclusionPatterns , extraAttributes ) ; } else { if ( path . segmentCount ( ) == ) { entry = RubyCore . newProjectEntry ( path , extraAttributes , isExported ) ; } else { entry = RubyCore . newSourceEntry ( path , inclusionPatterns , exclusionPatterns , extraAttributes ) ; } } break ; case ILoadpathEntry . CPE_VARIABLE : entry = RubyCore . newVariableEntry ( path , extraAttributes , isExported ) ; break ; case ILoadpathEntry . CPE_CONTAINER : entry = RubyCore . newContainerEntry ( path , extraAttributes , isExported ) ; break ; default : throw new AssertionFailedException ( Messages . bind ( Messages . classpath_unknownKind , kindAttr ) ) ; } if ( unknownAttributes != null || unknownChildren != null ) { UnknownXmlElements unknownXmlElements = new UnknownXmlElements ( ) ; unknownXmlElements . attributes = unknownAttributes ; unknownXmlElements . children = unknownChildren ; unknownElements . put ( path , unknownXmlElements ) ; } return entry ; } public static NodeList getChildAttributes ( String childName , NodeList children , boolean [ ] foundChildren ) { for ( int i = , length = foundChildren . length ; i < length ; i ++ ) { Node node = children . item ( i ) ; if ( childName . equals ( node . getNodeName ( ) ) ) { foundChildren [ i ] = true ; return node . getChildNodes ( ) ; } } return null ; } static ILoadpathAttribute [ ] decodeExtraAttributes ( NodeList attributes ) { if ( attributes == null ) return NO_EXTRA_ATTRIBUTES ; int length = attributes . getLength ( ) ; if ( length == ) return NO_EXTRA_ATTRIBUTES ; ILoadpathAttribute [ ] result = new ILoadpathAttribute [ length ] ; int index = ; for ( int i = ; i < length ; ++ i ) { Node node = attributes . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element attribute = ( Element ) node ; String name = attribute . getAttribute ( TAG_ATTRIBUTE_NAME ) ; if ( name == null ) continue ; String value = attribute . getAttribute ( TAG_ATTRIBUTE_VALUE ) ; if ( value == null ) continue ; result [ index ++ ] = new LoadpathAttribute ( name , value ) ; } } if ( index != length ) System . arraycopy ( result , , result = new ILoadpathAttribute [ index ] , , index ) ; return result ; } private static void decodeUnknownNode ( Node node , StringBuffer buffer , IRubyProject project ) { ByteArrayOutputStream s = new ByteArrayOutputStream ( ) ; OutputStreamWriter writer ; try { writer = new OutputStreamWriter ( s , "" ) ; XMLWriter xmlWriter = new XMLWriter ( writer , project , false ) ; decodeUnknownNode ( node , xmlWriter , true ) ; xmlWriter . flush ( ) ; xmlWriter . close ( ) ; buffer . append ( s . toString ( "" ) ) ; } catch ( UnsupportedEncodingException e ) { } } private static void decodeUnknownNode ( Node node , XMLWriter xmlWriter , boolean insertNewLine ) { switch ( node . getNodeType ( ) ) { case Node . ELEMENT_NODE : NamedNodeMap attributes ; HashMap parameters = null ; if ( ( attributes = node . getAttributes ( ) ) != null ) { int length = attributes . getLength ( ) ; if ( length > ) { parameters = new HashMap ( ) ; for ( int i = ; i < length ; i ++ ) { Node attribute = attributes . item ( i ) ; parameters . put ( attribute . getNodeName ( ) , attribute . getNodeValue ( ) ) ; } } } NodeList children = node . getChildNodes ( ) ; int childrenLength = children . getLength ( ) ; String nodeName = node . getNodeName ( ) ; xmlWriter . printTag ( nodeName , parameters , false , false , childrenLength == ) ; if ( childrenLength > ) { for ( int i = ; i < childrenLength ; i ++ ) { decodeUnknownNode ( children . item ( i ) , xmlWriter , false ) ; } xmlWriter . endTag ( nodeName , false , insertNewLine ) ; } break ; case Node . TEXT_NODE : String data = ( ( Text ) node ) . getData ( ) ; xmlWriter . printString ( data , false , false ) ; break ; } } private static IPath [ ] decodePatterns ( NamedNodeMap nodeMap , String tag ) { String sequence = removeAttribute ( tag , nodeMap ) ; if ( ! sequence . equals ( "" ) ) { char [ ] [ ] patterns = CharOperation . splitOn ( '' , sequence . toCharArray ( ) ) ; int patternCount ; if ( ( patternCount = patterns . length ) > ) { IPath [ ] paths = new IPath [ patternCount ] ; int index = ; for ( int j = ; j < patternCount ; j ++ ) { char [ ] pattern = patterns [ j ] ; if ( pattern . length == ) continue ; paths [ index ++ ] = new Path ( new String ( pattern ) ) ; } if ( index < patternCount ) System . arraycopy ( paths , , paths = new IPath [ index ] , , index ) ; return paths ; } } return null ; } static int kindFromString ( String kindStr ) { if ( kindStr . equalsIgnoreCase ( "" ) ) return ILoadpathEntry . CPE_PROJECT ; if ( kindStr . equalsIgnoreCase ( "" ) ) return ILoadpathEntry . CPE_VARIABLE ; if ( kindStr . equalsIgnoreCase ( "" ) ) return ILoadpathEntry . CPE_CONTAINER ; if ( kindStr . equalsIgnoreCase ( "" ) ) return ILoadpathEntry . CPE_SOURCE ; if ( kindStr . equalsIgnoreCase ( "" ) ) return ILoadpathEntry . CPE_LIBRARY ; return - ; } private static String removeAttribute ( String nodeName , NamedNodeMap nodeMap ) { Node node = removeNode ( nodeName , nodeMap ) ; if ( node == null ) return "" ; return node . getNodeValue ( ) ; } private static Node removeNode ( String nodeName , NamedNodeMap nodeMap ) { try { return nodeMap . removeNamedItem ( nodeName ) ; } catch ( DOMException e ) { if ( e . code != DOMException . NOT_FOUND_ERR ) throw e ; return null ; } } public boolean isOptional ( ) { for ( int i = , length = this . extraAttributes . length ; i < length ; i ++ ) { ILoadpathAttribute attribute = this . extraAttributes [ i ] ; if ( ILoadpathAttribute . OPTIONAL . equals ( attribute . getName ( ) ) && "" . equals ( attribute . getValue ( ) ) ) return true ; } return false ; } public static IRubyModelStatus validateLoadpathEntry ( IRubyProject project , ILoadpathEntry rawEntry , boolean b , boolean c ) { return RubyModelStatus . VERIFIED_OK ; } public static IRubyModelStatus validateLoadpath ( IRubyProject project , ILoadpathEntry [ ] resolvedPath , IPath projectOutputLocation ) { return RubyModelStatus . VERIFIED_OK ; } public void elementEncode ( XMLWriter writer , IPath projectPath , boolean indent , boolean newLine , Map unknownElements ) { HashMap parameters = new HashMap ( ) ; parameters . put ( TAG_KIND , LoadpathEntry . kindToString ( this . entryKind ) ) ; IPath xmlPath = this . path ; if ( this . entryKind != ILoadpathEntry . CPE_VARIABLE && this . entryKind != ILoadpathEntry . CPE_CONTAINER ) { if ( xmlPath . isAbsolute ( ) ) { if ( projectPath != null && projectPath . isPrefixOf ( xmlPath ) ) { if ( xmlPath . segment ( ) . equals ( projectPath . segment ( ) ) ) { xmlPath = xmlPath . removeFirstSegments ( ) ; xmlPath = xmlPath . makeRelative ( ) ; } else { xmlPath = xmlPath . makeAbsolute ( ) ; } } } } parameters . put ( TAG_PATH , String . valueOf ( xmlPath ) ) ; if ( this . isExported ) { parameters . put ( TAG_EXPORTED , "" ) ; } encodePatterns ( this . inclusionPatterns , TAG_INCLUDING , parameters ) ; encodePatterns ( this . exclusionPatterns , TAG_EXCLUDING , parameters ) ; UnknownXmlElements unknownXmlElements = unknownElements == null ? null : ( UnknownXmlElements ) unknownElements . get ( this . path ) ; String [ ] unknownAttributes ; if ( unknownXmlElements != null && ( unknownAttributes = unknownXmlElements . attributes ) != null ) for ( int i = , length = unknownAttributes . length ; i < length ; i += ) { String tagName = unknownAttributes [ i ] ; String tagValue = unknownAttributes [ i + ] ; parameters . put ( tagName , tagValue ) ; } boolean hasExtraAttributes = this . extraAttributes . length != ; ArrayList unknownChildren = unknownXmlElements != null ? unknownXmlElements . children : null ; boolean hasUnknownChildren = unknownChildren != null ; writer . printTag ( TAG_LOADPATHENTRY , parameters , indent , newLine , ! hasUnknownChildren ) ; if ( hasExtraAttributes ) encodeExtraAttributes ( writer , indent , newLine ) ; if ( hasUnknownChildren ) { encodeUnknownChildren ( writer , indent , newLine , unknownChildren ) ; if ( hasExtraAttributes || hasUnknownChildren ) writer . endTag ( TAG_LOADPATHENTRY , indent , true ) ; } } void encodeExtraAttributes ( XMLWriter writer , boolean indent , boolean newLine ) { writer . startTag ( TAG_ATTRIBUTES , indent ) ; for ( int i = ; i < this . extraAttributes . length ; i ++ ) { ILoadpathAttribute attribute = this . extraAttributes [ i ] ; HashMap parameters = new HashMap ( ) ; parameters . put ( TAG_ATTRIBUTE_NAME , attribute . getName ( ) ) ; parameters . put ( TAG_ATTRIBUTE_VALUE , attribute . getValue ( ) ) ; writer . printTag ( TAG_ATTRIBUTE , parameters , indent , newLine , true ) ; } writer . endTag ( TAG_ATTRIBUTES , indent , true ) ; } private static void encodePatterns ( IPath [ ] patterns , String tag , Map parameters ) { if ( patterns != null && patterns . length > ) { StringBuffer rule = new StringBuffer ( ) ; for ( int i = , max = patterns . length ; i < max ; i ++ ) { if ( i > ) rule . append ( '' ) ; rule . append ( patterns [ i ] ) ; } parameters . put ( tag , String . valueOf ( rule ) ) ; } } private void encodeUnknownChildren ( XMLWriter writer , boolean indent , boolean newLine , ArrayList unknownChildren ) { for ( int i = , length = unknownChildren . size ( ) ; i < length ; i ++ ) { String child = ( String ) unknownChildren . get ( i ) ; writer . printString ( child , indent , false ) ; } } public ILoadpathAttribute [ ] getExtraAttributes ( ) { return extraAttributes ; } public boolean equals ( Object object ) { if ( this == object ) return true ; if ( object instanceof LoadpathEntry ) { LoadpathEntry otherEntry = ( LoadpathEntry ) object ; if ( this . entryKind != otherEntry . getEntryKind ( ) ) return false ; if ( this . isExported != otherEntry . isExported ( ) ) return false ; if ( ! this . path . equals ( otherEntry . getPath ( ) ) ) return false ; if ( ! equalPatterns ( this . inclusionPatterns , otherEntry . getInclusionPatterns ( ) ) ) return false ; if ( ! equalPatterns ( this . exclusionPatterns , otherEntry . getExclusionPatterns ( ) ) ) return false ; if ( ! equalAttributes ( this . extraAttributes , otherEntry . getExtraAttributes ( ) ) ) return false ; return true ; } else { return false ; } } private static boolean equalAttributes ( ILoadpathAttribute [ ] firstAttributes , ILoadpathAttribute [ ] secondAttributes ) { if ( firstAttributes != secondAttributes ) { if ( firstAttributes == null ) return false ; int length = firstAttributes . length ; if ( secondAttributes == null || secondAttributes . length != length ) return false ; for ( int i = ; i < length ; i ++ ) { if ( ! firstAttributes [ i ] . equals ( secondAttributes [ i ] ) ) return false ; } } return true ; } private static boolean equalPatterns ( IPath [ ] firstPatterns , IPath [ ] secondPatterns ) { if ( firstPatterns != secondPatterns ) { if ( firstPatterns == null ) return false ; int length = firstPatterns . length ; if ( secondPatterns == null || secondPatterns . length != length ) return false ; for ( int i = ; i < length ; i ++ ) { if ( ! firstPatterns [ i ] . toString ( ) . equals ( secondPatterns [ i ] . toString ( ) ) ) return false ; } } return true ; } public int hashCode ( ) { return this . path . hashCode ( ) ; } public String toString ( ) { return getPath ( ) . toPortableString ( ) ; } } package org . rubypeople . rdt . internal . core ; import java . util . Enumeration ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . rubypeople . rdt . core . BufferChangedEvent ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IBufferChangedListener ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . codeassist . SelectionEngine ; import org . rubypeople . rdt . internal . core . buffer . BufferManager ; import org . rubypeople . rdt . internal . core . util . Util ; public abstract class Openable extends RubyElement implements IOpenable , IBufferChangedListener { public Openable ( RubyElement parent ) { super ( parent ) ; } public SourceFolderRoot getSourceFolderRoot ( ) { return ( SourceFolderRoot ) getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; } public IResource getUnderlyingResource ( ) throws RubyModelException { IResource parentResource = this . parent . getUnderlyingResource ( ) ; if ( parentResource == null ) { return null ; } int type = parentResource . getType ( ) ; if ( type == IResource . FOLDER || type == IResource . PROJECT ) { IContainer folder = ( IContainer ) parentResource ; IResource resource = folder . findMember ( getElementName ( ) ) ; if ( resource == null ) { throw newNotPresentException ( ) ; } else { return resource ; } } else { return parentResource ; } } public void bufferChanged ( BufferChangedEvent event ) { if ( event . getBuffer ( ) . isClosed ( ) ) { RubyModelManager . getRubyModelManager ( ) . getElementsOutOfSynchWithBuffers ( ) . remove ( this ) ; getBufferManager ( ) . removeBuffer ( event . getBuffer ( ) ) ; } else { RubyModelManager . getRubyModelManager ( ) . getElementsOutOfSynchWithBuffers ( ) . add ( this ) ; } } public IBuffer getBuffer ( ) throws RubyModelException { if ( hasBuffer ( ) ) { Object info = getElementInfo ( ) ; IBuffer buffer = getBufferManager ( ) . getBuffer ( this ) ; if ( buffer == null ) { buffer = openBuffer ( null , info ) ; } return buffer ; } return null ; } protected IBuffer openBuffer ( IProgressMonitor pm , Object info ) throws RubyModelException { return null ; } public boolean canBufferBeRemovedFromCache ( IBuffer buffer ) { return ! buffer . hasUnsavedChanges ( ) ; } protected boolean hasBuffer ( ) { return false ; } public boolean isOpen ( ) { return RubyModelManager . getRubyModelManager ( ) . getInfo ( this ) != null ; } protected BufferManager getBufferManager ( ) { return BufferManager . getDefaultBufferManager ( ) ; } public IResource getCorrespondingResource ( ) throws RubyModelException { return getUnderlyingResource ( ) ; } public boolean canBeRemovedFromCache ( ) { try { return ! hasUnsavedChanges ( ) ; } catch ( RubyModelException e ) { return false ; } } public boolean isConsistent ( ) { return true ; } public boolean isStructureKnown ( ) throws RubyModelException { return ( ( OpenableElementInfo ) getElementInfo ( ) ) . isStructureKnown ( ) ; } public boolean hasUnsavedChanges ( ) throws RubyModelException { if ( isReadOnly ( ) || ! isOpen ( ) ) { return false ; } IBuffer buf = this . getBuffer ( ) ; if ( buf != null && buf . hasUnsavedChanges ( ) ) { return true ; } int elementType = getElementType ( ) ; if ( elementType == RUBY_PROJECT || elementType == RUBY_MODEL ) { Enumeration openBuffers = getBufferManager ( ) . getOpenBuffers ( ) ; while ( openBuffers . hasMoreElements ( ) ) { IBuffer buffer = ( IBuffer ) openBuffers . nextElement ( ) ; if ( buffer . hasUnsavedChanges ( ) ) { IRubyElement owner = ( IRubyElement ) buffer . getOwner ( ) ; if ( isAncestorOf ( owner ) ) { return true ; } } } } return false ; } protected void closing ( Object info ) { closeBuffer ( ) ; } public boolean exists ( ) { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; if ( manager . getInfo ( this ) != null ) return true ; if ( ! parentExists ( ) ) return false ; SourceFolderRoot root = getSourceFolderRoot ( ) ; if ( root != null && ( root == this || ! root . isExternal ( ) ) ) { return resourceExists ( ) ; } return super . exists ( ) ; } protected boolean parentExists ( ) { IRubyElement parentElement = getParent ( ) ; if ( parentElement == null ) return true ; return parentElement . exists ( ) ; } protected void closeBuffer ( ) { if ( ! hasBuffer ( ) ) return ; IBuffer buffer = getBufferManager ( ) . getBuffer ( this ) ; if ( buffer != null ) { buffer . close ( ) ; buffer . removeBufferChangedListener ( this ) ; } } protected void generateInfos ( Object info , HashMap newElements , IProgressMonitor monitor ) throws RubyModelException { if ( RubyModelManager . isVerbose ( ) ) { String element ; switch ( getElementType ( ) ) { case RUBY_PROJECT : element = "" ; break ; case SCRIPT : element = "" ; break ; default : element = "" ; } System . out . println ( Thread . currentThread ( ) + "" + element + "" + this . toString ( ) ) ; } openParent ( info , newElements , monitor ) ; if ( monitor != null && monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; newElements . put ( this , info ) ; try { OpenableElementInfo openableElementInfo = ( OpenableElementInfo ) info ; boolean isStructureKnown = buildStructure ( openableElementInfo , monitor , newElements , getResource ( ) ) ; openableElementInfo . setIsStructureKnown ( isStructureKnown ) ; } catch ( RubyModelException e ) { newElements . remove ( this ) ; throw e ; } RubyModelManager . getRubyModelManager ( ) . getElementsOutOfSynchWithBuffers ( ) . remove ( this ) ; if ( RubyModelManager . isVerbose ( ) ) { System . out . println ( RubyModelManager . getRubyModelManager ( ) . cache . toStringFillingRation ( "" ) ) ; } } protected abstract boolean buildStructure ( OpenableElementInfo info , IProgressMonitor pm , Map newElements , IResource underlyingResource ) throws RubyModelException ; protected void openParent ( Object info , HashMap newElements , IProgressMonitor pm ) throws RubyModelException { Openable openableParent = ( Openable ) getOpenableParent ( ) ; if ( openableParent != null && ! openableParent . isOpen ( ) ) { openableParent . generateInfos ( openableParent . createElementInfo ( ) , newElements , pm ) ; } } public void makeConsistent ( IProgressMonitor monitor ) throws RubyModelException { } public void save ( IProgressMonitor pm , boolean force ) throws RubyModelException { if ( isReadOnly ( ) ) { throw new RubyModelException ( new RubyModelStatus ( IRubyModelStatusConstants . READ_ONLY , this ) ) ; } IBuffer buf = getBuffer ( ) ; if ( buf != null ) { buf . save ( pm , force ) ; this . makeConsistent ( pm ) ; } } protected boolean resourceExists ( ) { return RubyModel . getTarget ( this . getPath ( ) . makeRelative ( ) , true ) != null ; } public void open ( IProgressMonitor pm ) throws RubyModelException { getElementInfo ( pm ) ; } protected IRubyElement [ ] codeSelect ( IRubyScript cu , int offset , int length , WorkingCopyOwner owner ) throws RubyModelException { IBuffer buffer = getBuffer ( ) ; if ( buffer == null ) { return new IRubyElement [ ] ; } int end = buffer . getLength ( ) ; if ( offset < || length < || offset + length > end ) { throw new RubyModelException ( new RubyModelStatus ( IRubyModelStatusConstants . INDEX_OUT_OF_BOUNDS ) ) ; } SelectionEngine engine = new SelectionEngine ( ) ; return engine . select ( cu , offset , offset + length - ) ; } public String findRecommendedLineSeparator ( ) throws RubyModelException { IBuffer buffer = getBuffer ( ) ; String source = buffer == null ? null : buffer . getContents ( ) ; return Util . getLineSeparator ( source , getRubyProject ( ) ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . ILoadpathAttribute ; import org . rubypeople . rdt . internal . core . util . Util ; public class LoadpathAttribute implements ILoadpathAttribute { private String name ; private String value ; public LoadpathAttribute ( String name , String value ) { this . name = name ; this . value = value ; } public boolean equals ( Object obj ) { if ( ! ( obj instanceof LoadpathAttribute ) ) return false ; LoadpathAttribute other = ( LoadpathAttribute ) obj ; return this . name . equals ( other . name ) && this . value . equals ( other . value ) ; } public String getName ( ) { return this . name ; } public String getValue ( ) { return this . value ; } public int hashCode ( ) { return Util . combineHashCodes ( this . name . hashCode ( ) , this . value . hashCode ( ) ) ; } public String toString ( ) { return this . name + "" + this . value ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . List ; import org . rubypeople . rdt . core . IRubyElement ; public class HandleStack { private List stack = new ArrayList ( ) ; public HandleStack ( ) { } public RubyElement pop ( ) { if ( stack . isEmpty ( ) ) return null ; return ( RubyElement ) stack . remove ( stack . size ( ) - ) ; } public void push ( IRubyElement element ) { stack . add ( element ) ; } public RubyElement peek ( ) { if ( stack . isEmpty ( ) ) return null ; return ( RubyElement ) stack . get ( stack . size ( ) - ) ; } } package org . rubypeople . rdt . internal . core ; import java . util . HashMap ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; public class ASTHolderCUInfo extends RubyScriptElementInfo { public HashMap < String , CategorizedProblem [ ] > problems ; public RootNode ast ; } package org . rubypeople . rdt . internal . core . util ; import java . io . CharArrayReader ; import java . io . IOException ; import org . jruby . CompatVersion ; import org . jruby . common . NullWarnings ; import org . jruby . lexer . yacc . LexerSource ; import org . jruby . lexer . yacc . RubyYaccLexer ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . lexer . yacc . RubyYaccLexer . LexState ; import org . jruby . parser . ParserConfiguration ; import org . jruby . parser . ParserSupport ; import org . jruby . parser . RubyParserResult ; import org . jruby . util . KCode ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . IScanner ; import org . rubypeople . rdt . core . compiler . InvalidInputException ; public class PublicScanner implements IScanner { private char [ ] source ; private RubyYaccLexer lexer ; private ParserSupport parserSupport ; private RubyParserResult result ; private LexerSource lexerSource ; private int fOffset ; private int fTokenLength ; public PublicScanner ( ) { lexer = new RubyYaccLexer ( ) ; parserSupport = new ParserSupport ( ) ; ParserConfiguration config = new ParserConfiguration ( KCode . NIL , , true , false , CompatVersion . RUBY1_8 ) ; parserSupport . setConfiguration ( config ) ; result = new RubyParserResult ( ) ; parserSupport . setResult ( result ) ; lexer . setParserSupport ( parserSupport ) ; lexer . setWarnings ( new NullWarnings ( ) ) ; lexer . setEncoding ( config . getKCode ( ) . getEncoding ( ) ) ; } public int getCurrentTokenEndPosition ( ) { return fOffset + fTokenLength ; } public int getCurrentTokenStartPosition ( ) { return fTokenLength ; } public int getNextToken ( ) throws InvalidInputException { fOffset = lexerSource . getOffset ( ) ; fTokenLength = ; int returnValue = ; boolean isEOF = false ; try { isEOF = ! lexer . advance ( ) ; if ( isEOF ) { returnValue = TokenNameEOF ; } else { fTokenLength = lexerSource . getOffset ( ) - fOffset ; returnValue = lexer . token ( ) ; } } catch ( SyntaxException se ) { if ( lexerSource . getOffset ( ) == || fOffset >= source . length ) return TokenNameEOF ; fTokenLength = lexerSource . getOffset ( ) - fOffset ; return ; } catch ( NumberFormatException nfe ) { fTokenLength = lexerSource . getOffset ( ) - fOffset ; return returnValue ; } catch ( IOException e ) { RubyCore . log ( e ) ; } return returnValue ; } public void setSource ( char [ ] source ) { this . source = source ; lexer . reset ( ) ; lexer . setState ( LexState . EXPR_BEG ) ; parserSupport . initTopLocalVariables ( ) ; ParserConfiguration config = new ParserConfiguration ( KCode . NIL , , true , false , CompatVersion . RUBY1_8 ) ; lexerSource = LexerSource . getSource ( "" , new CharArrayReader ( source ) , null , config ) ; lexer . setSource ( lexerSource ) ; } } package org . rubypeople . rdt . internal . core . util ; import org . rubypeople . rdt . internal . compiler . parser . ScannerHelper ; public class CharOperation { public static final char [ ] NO_CHAR = new char [ ] ; public static final String [ ] NO_STRINGS = new String [ ] ; public static final char [ ] [ ] NO_CHAR_CHAR = new char [ ] [ ] ; public static final int indexOf ( char toBeFound , char [ ] array , int start ) { for ( int i = start ; i < array . length ; i ++ ) if ( toBeFound == array [ i ] ) return i ; return - ; } public static final char [ ] replace ( char [ ] array , char [ ] toBeReplaced , char [ ] replacementChars ) { int max = array . length ; int replacedLength = toBeReplaced . length ; int replacementLength = replacementChars . length ; int [ ] starts = new int [ ] ; int occurrenceCount = ; if ( ! equals ( toBeReplaced , replacementChars ) ) { next : for ( int i = ; i < max ; i ++ ) { int j = ; while ( j < replacedLength ) { if ( i + j == max ) continue next ; if ( array [ i + j ] != toBeReplaced [ j ++ ] ) continue next ; } if ( occurrenceCount == starts . length ) { System . arraycopy ( starts , , starts = new int [ occurrenceCount * ] , , occurrenceCount ) ; } starts [ occurrenceCount ++ ] = i ; } } if ( occurrenceCount == ) return array ; char [ ] result = new char [ max + occurrenceCount * ( replacementLength - replacedLength ) ] ; int inStart = , outStart = ; for ( int i = ; i < occurrenceCount ; i ++ ) { int offset = starts [ i ] - inStart ; System . arraycopy ( array , inStart , result , outStart , offset ) ; inStart += offset ; outStart += offset ; System . arraycopy ( replacementChars , , result , outStart , replacementLength ) ; inStart += replacedLength ; outStart += replacementLength ; } System . arraycopy ( array , inStart , result , outStart , max - inStart ) ; return result ; } public static final boolean equals ( char [ ] first , char [ ] second ) { if ( first == second ) return true ; if ( first == null || second == null ) return false ; if ( first . length != second . length ) return false ; for ( int i = first . length ; -- i >= ; ) if ( first [ i ] != second [ i ] ) return false ; return true ; } public static final boolean pathMatch ( char [ ] pattern , char [ ] filepath , boolean isCaseSensitive , char pathSeparator ) { if ( filepath == null ) return false ; if ( pattern == null ) return true ; int pSegmentStart = pattern [ ] == pathSeparator ? : ; int pLength = pattern . length ; int pSegmentEnd = CharOperation . indexOf ( pathSeparator , pattern , pSegmentStart + ) ; if ( pSegmentEnd < ) pSegmentEnd = pLength ; boolean freeTrailingDoubleStar = pattern [ pLength - ] == pathSeparator ; int fSegmentStart , fLength = filepath . length ; if ( filepath [ ] != pathSeparator ) { fSegmentStart = ; } else { fSegmentStart = ; } if ( fSegmentStart != pSegmentStart ) { return false ; } int fSegmentEnd = CharOperation . indexOf ( pathSeparator , filepath , fSegmentStart + ) ; if ( fSegmentEnd < ) fSegmentEnd = fLength ; while ( pSegmentStart < pLength && ! ( pSegmentEnd == pLength && freeTrailingDoubleStar || ( pSegmentEnd == pSegmentStart + && pattern [ pSegmentStart ] == '' && pattern [ pSegmentStart + ] == '' ) ) ) { if ( fSegmentStart >= fLength ) return false ; if ( ! CharOperation . match ( pattern , pSegmentStart , pSegmentEnd , filepath , fSegmentStart , fSegmentEnd , isCaseSensitive ) ) { return false ; } pSegmentEnd = CharOperation . indexOf ( pathSeparator , pattern , pSegmentStart = pSegmentEnd + ) ; if ( pSegmentEnd < ) pSegmentEnd = pLength ; fSegmentEnd = CharOperation . indexOf ( pathSeparator , filepath , fSegmentStart = fSegmentEnd + ) ; if ( fSegmentEnd < ) fSegmentEnd = fLength ; } int pSegmentRestart ; if ( ( pSegmentStart >= pLength && freeTrailingDoubleStar ) || ( pSegmentEnd == pSegmentStart + && pattern [ pSegmentStart ] == '' && pattern [ pSegmentStart + ] == '' ) ) { pSegmentEnd = CharOperation . indexOf ( pathSeparator , pattern , pSegmentStart = pSegmentEnd + ) ; if ( pSegmentEnd < ) pSegmentEnd = pLength ; pSegmentRestart = pSegmentStart ; } else { if ( pSegmentStart >= pLength ) return fSegmentStart >= fLength ; pSegmentRestart = ; } int fSegmentRestart = fSegmentStart ; checkSegment : while ( fSegmentStart < fLength ) { if ( pSegmentStart >= pLength ) { if ( freeTrailingDoubleStar ) return true ; pSegmentEnd = CharOperation . indexOf ( pathSeparator , pattern , pSegmentStart = pSegmentRestart ) ; if ( pSegmentEnd < ) pSegmentEnd = pLength ; fSegmentRestart = CharOperation . indexOf ( pathSeparator , filepath , fSegmentRestart + ) ; if ( fSegmentRestart < ) { fSegmentRestart = fLength ; } else { fSegmentRestart ++ ; } fSegmentEnd = CharOperation . indexOf ( pathSeparator , filepath , fSegmentStart = fSegmentRestart ) ; if ( fSegmentEnd < ) fSegmentEnd = fLength ; continue checkSegment ; } if ( pSegmentEnd == pSegmentStart + && pattern [ pSegmentStart ] == '' && pattern [ pSegmentStart + ] == '' ) { pSegmentEnd = CharOperation . indexOf ( pathSeparator , pattern , pSegmentStart = pSegmentEnd + ) ; if ( pSegmentEnd < ) pSegmentEnd = pLength ; pSegmentRestart = pSegmentStart ; fSegmentRestart = fSegmentStart ; if ( pSegmentStart >= pLength ) return true ; continue checkSegment ; } if ( ! CharOperation . match ( pattern , pSegmentStart , pSegmentEnd , filepath , fSegmentStart , fSegmentEnd , isCaseSensitive ) ) { pSegmentEnd = CharOperation . indexOf ( pathSeparator , pattern , pSegmentStart = pSegmentRestart ) ; if ( pSegmentEnd < ) pSegmentEnd = pLength ; fSegmentRestart = CharOperation . indexOf ( pathSeparator , filepath , fSegmentRestart + ) ; if ( fSegmentRestart < ) { fSegmentRestart = fLength ; } else { fSegmentRestart ++ ; } fSegmentEnd = CharOperation . indexOf ( pathSeparator , filepath , fSegmentStart = fSegmentRestart ) ; if ( fSegmentEnd < ) fSegmentEnd = fLength ; continue checkSegment ; } pSegmentEnd = CharOperation . indexOf ( pathSeparator , pattern , pSegmentStart = pSegmentEnd + ) ; if ( pSegmentEnd < ) pSegmentEnd = pLength ; fSegmentEnd = CharOperation . indexOf ( pathSeparator , filepath , fSegmentStart = fSegmentEnd + ) ; if ( fSegmentEnd < ) fSegmentEnd = fLength ; } return ( pSegmentRestart >= pSegmentEnd ) || ( fSegmentStart >= fLength && pSegmentStart >= pLength ) || ( pSegmentStart == pLength - && pattern [ pSegmentStart ] == '' && pattern [ pSegmentStart + ] == '' ) || ( pSegmentStart == pLength && freeTrailingDoubleStar ) ; } public static final boolean match ( char [ ] pattern , int patternStart , int patternEnd , char [ ] name , int nameStart , int nameEnd , boolean isCaseSensitive ) { if ( name == null ) return false ; if ( pattern == null ) return true ; int iPattern = patternStart ; int iName = nameStart ; if ( patternEnd < ) patternEnd = pattern . length ; if ( nameEnd < ) nameEnd = name . length ; char patternChar = ; while ( ( iPattern < patternEnd ) && ( patternChar = pattern [ iPattern ] ) != '' ) { if ( iName == nameEnd ) return false ; if ( patternChar != ( isCaseSensitive ? name [ iName ] : Character . toLowerCase ( name [ iName ] ) ) && patternChar != '' ) { return false ; } iName ++ ; iPattern ++ ; } int segmentStart ; if ( patternChar == '' ) { segmentStart = ++ iPattern ; } else { segmentStart = ; } int prefixStart = iName ; checkSegment : while ( iName < nameEnd ) { if ( iPattern == patternEnd ) { iPattern = segmentStart ; iName = ++ prefixStart ; continue checkSegment ; } if ( ( patternChar = pattern [ iPattern ] ) == '' ) { segmentStart = ++ iPattern ; if ( segmentStart == patternEnd ) { return true ; } prefixStart = iName ; continue checkSegment ; } if ( ( isCaseSensitive ? name [ iName ] : Character . toLowerCase ( name [ iName ] ) ) != patternChar && patternChar != '' ) { iPattern = segmentStart ; iName = ++ prefixStart ; continue checkSegment ; } iName ++ ; iPattern ++ ; } return ( segmentStart == patternEnd ) || ( iName == nameEnd && iPattern == patternEnd ) || ( iPattern == patternEnd - && pattern [ iPattern ] == '' ) ; } public static final char [ ] subarray ( char [ ] array , int start , int end ) { if ( end == - ) end = array . length ; if ( start > end ) return null ; if ( start < ) return null ; if ( end > array . length ) return null ; char [ ] result = new char [ end - start ] ; System . arraycopy ( array , start , result , , end - start ) ; return result ; } public static final char [ ] concat ( char [ ] first , char [ ] second , char separator ) { if ( first == null ) return second ; if ( second == null ) return first ; int length1 = first . length ; if ( length1 == ) return second ; int length2 = second . length ; if ( length2 == ) return first ; char [ ] result = new char [ length1 + length2 + ] ; System . arraycopy ( first , , result , , length1 ) ; result [ length1 ] = separator ; System . arraycopy ( second , , result , length1 + , length2 ) ; return result ; } public static final int lastIndexOf ( char toBeFound , char [ ] array ) { for ( int i = array . length ; -- i >= ; ) if ( toBeFound == array [ i ] ) return i ; return - ; } public static final boolean equals ( char [ ] [ ] first , char [ ] [ ] second ) { if ( first == second ) return true ; if ( first == null || second == null ) return false ; if ( first . length != second . length ) return false ; for ( int i = first . length ; -- i >= ; ) if ( ! equals ( first [ i ] , second [ i ] ) ) return false ; return true ; } public static final boolean equals ( String [ ] first , String [ ] second ) { if ( first == second ) return true ; if ( first == null || second == null ) return false ; if ( first . length != second . length ) return false ; for ( int i = first . length ; -- i >= ; ) if ( ! first [ i ] . equals ( second [ i ] ) ) return false ; return true ; } public static final int hashCode ( char [ ] array ) { int length = array . length ; int hash = length == ? : array [ ] ; if ( length < ) { for ( int i = length ; -- i > ; ) hash = ( hash * ) + array [ i ] ; } else { for ( int i = length - , last = i > ? i - : ; i > last ; i -= ) hash = ( hash * ) + array [ i ] ; } return hash & ; } public static final char [ ] concatWith ( char [ ] [ ] array , char separator ) { int length = array == null ? : array . length ; if ( length == ) return CharOperation . NO_CHAR ; int size = length - ; int index = length ; while ( -- index >= ) { if ( array [ index ] . length == ) size -- ; else size += array [ index ] . length ; } if ( size <= ) return CharOperation . NO_CHAR ; char [ ] result = new char [ size ] ; index = length ; while ( -- index >= ) { length = array [ index ] . length ; if ( length > ) { System . arraycopy ( array [ index ] , , result , ( size -= length ) , length ) ; if ( -- size >= ) result [ size ] = separator ; } } return result ; } public static final char [ ] [ ] splitOn ( char divider , char [ ] array ) { int length = array == null ? : array . length ; if ( length == ) return NO_CHAR_CHAR ; int wordCount = ; for ( int i = ; i < length ; i ++ ) if ( array [ i ] == divider ) wordCount ++ ; char [ ] [ ] split = new char [ wordCount ] [ ] ; int last = , currentWord = ; for ( int i = ; i < length ; i ++ ) { if ( array [ i ] == divider ) { split [ currentWord ] = new char [ i - last ] ; System . arraycopy ( array , last , split [ currentWord ++ ] , , i - last ) ; last = i + ; } } split [ currentWord ] = new char [ length - last ] ; System . arraycopy ( array , last , split [ currentWord ] , , length - last ) ; return split ; } public static final boolean prefixEquals ( char [ ] prefix , char [ ] name ) { int max = prefix . length ; if ( name . length < max ) return false ; for ( int i = max ; -- i >= ; ) if ( prefix [ i ] != name [ i ] ) return false ; return true ; } public static final boolean camelCaseMatch ( char [ ] pattern , char [ ] name ) { if ( pattern == null ) return true ; if ( name == null ) return false ; return camelCaseMatch ( pattern , , pattern . length , name , , name . length ) ; } public static final boolean camelCaseMatch ( char [ ] pattern , int patternStart , int patternEnd , char [ ] name , int nameStart , int nameEnd ) { if ( name == null ) return false ; if ( pattern == null ) return true ; if ( patternEnd < ) patternEnd = pattern . length ; if ( nameEnd < ) nameEnd = name . length ; if ( patternEnd <= patternStart ) return nameEnd <= nameStart ; if ( nameEnd <= nameStart ) return false ; if ( name [ nameStart ] != pattern [ patternStart ] ) { return false ; } char patternChar , nameChar ; int iPattern = patternStart ; int iName = nameStart ; while ( true ) { iPattern ++ ; iName ++ ; if ( iPattern == patternEnd ) { return true ; } if ( iName == nameEnd ) { return false ; } if ( ( patternChar = pattern [ iPattern ] ) == name [ iName ] ) { continue ; } if ( patternChar < ScannerHelper . MAX_OBVIOUS ) { if ( ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ patternChar ] & ScannerHelper . C_UPPER_LETTER ) == ) { return false ; } } else if ( Character . isJavaIdentifierPart ( patternChar ) && ! Character . isUpperCase ( patternChar ) ) { return false ; } while ( true ) { if ( iName == nameEnd ) { return false ; } nameChar = name [ iName ] ; if ( nameChar < ScannerHelper . MAX_OBVIOUS ) { if ( ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ nameChar ] & ( ScannerHelper . C_LOWER_LETTER | ScannerHelper . C_SPECIAL | ScannerHelper . C_DIGIT ) ) != ) { iName ++ ; } else if ( patternChar != nameChar ) { return false ; } else { break ; } } else if ( Character . isJavaIdentifierPart ( nameChar ) && ! Character . isUpperCase ( nameChar ) ) { iName ++ ; } else if ( patternChar != nameChar ) { return false ; } else { break ; } } } } public static final boolean equals ( char [ ] first , char [ ] second , boolean isCaseSensitive ) { if ( isCaseSensitive ) { return equals ( first , second ) ; } if ( first == second ) return true ; if ( first == null || second == null ) return false ; if ( first . length != second . length ) return false ; for ( int i = first . length ; -- i >= ; ) if ( ScannerHelper . toLowerCase ( first [ i ] ) != ScannerHelper . toLowerCase ( second [ i ] ) ) return false ; return true ; } public static final boolean prefixEquals ( char [ ] prefix , char [ ] name , boolean isCaseSensitive ) { int max = prefix . length ; if ( name . length < max ) return false ; if ( isCaseSensitive ) { for ( int i = max ; -- i >= ; ) if ( prefix [ i ] != name [ i ] ) return false ; return true ; } for ( int i = max ; -- i >= ; ) if ( ScannerHelper . toLowerCase ( prefix [ i ] ) != ScannerHelper . toLowerCase ( name [ i ] ) ) return false ; return true ; } public static final boolean match ( char [ ] pattern , char [ ] name , boolean isCaseSensitive ) { if ( name == null ) return false ; if ( pattern == null ) return true ; return match ( pattern , , pattern . length , name , , name . length , isCaseSensitive ) ; } final static public char [ ] toLowerCase ( char [ ] chars ) { if ( chars == null ) return null ; int length = chars . length ; char [ ] lowerChars = null ; for ( int i = ; i < length ; i ++ ) { char c = chars [ i ] ; char lc = ScannerHelper . toLowerCase ( c ) ; if ( ( c != lc ) || ( lowerChars != null ) ) { if ( lowerChars == null ) { System . arraycopy ( chars , , lowerChars = new char [ length ] , , i ) ; } lowerChars [ i ] = lc ; } } return lowerChars == null ? chars : lowerChars ; } public static final char [ ] [ ] subarray ( char [ ] [ ] array , int start , int end ) { if ( end == - ) end = array . length ; if ( start > end ) return null ; if ( start < ) return null ; if ( end > array . length ) return null ; char [ ] [ ] result = new char [ end - start ] [ ] ; System . arraycopy ( array , start , result , , end - start ) ; return result ; } public static final char [ ] concat ( char [ ] first , char sep1 , char [ ] second , char sep2 , char [ ] third ) { if ( first == null ) return concat ( second , third , sep2 ) ; if ( second == null ) return concat ( first , third , sep1 ) ; if ( third == null ) return concat ( first , second , sep1 ) ; int length1 = first . length ; int length2 = second . length ; int length3 = third . length ; char [ ] result = new char [ length1 + length2 + length3 + ] ; System . arraycopy ( first , , result , , length1 ) ; result [ length1 ] = sep1 ; System . arraycopy ( second , , result , length1 + , length2 ) ; result [ length1 + length2 + ] = sep2 ; System . arraycopy ( third , , result , length1 + length2 + , length3 ) ; return result ; } public static final char [ ] append ( char [ ] array , char suffix ) { if ( array == null ) return new char [ ] { suffix } ; int length = array . length ; System . arraycopy ( array , , array = new char [ length + ] , , length ) ; array [ length ] = suffix ; return array ; } public static final boolean equals ( char [ ] [ ] first , char [ ] [ ] second , boolean isCaseSensitive ) { if ( isCaseSensitive ) { return equals ( first , second ) ; } if ( first == second ) return true ; if ( first == null || second == null ) return false ; if ( first . length != second . length ) return false ; for ( int i = first . length ; -- i >= ; ) if ( ! equals ( first [ i ] , second [ i ] , false ) ) return false ; return true ; } public static char [ ] [ ] splitOn ( String divider , char [ ] key , int start , int last ) { String newKey = new String ( key ) ; newKey = newKey . substring ( start , last ) ; String [ ] result = newKey . split ( divider ) ; char [ ] [ ] resultEnd = new char [ result . length ] [ ] ; for ( int i = ; i < resultEnd . length ; i ++ ) { resultEnd [ i ] = result [ i ] . toCharArray ( ) ; } return resultEnd ; } public static char [ ] [ ] splitOn ( String divider , char [ ] key ) { String newKey = new String ( key ) ; String [ ] result = newKey . split ( divider ) ; char [ ] [ ] resultEnd = new char [ result . length ] [ ] ; for ( int i = ; i < resultEnd . length ; i ++ ) { resultEnd [ i ] = result [ i ] . toCharArray ( ) ; } return resultEnd ; } public static int occurencesOf ( String toBeFound , char [ ] originalString ) { String newKey = new String ( originalString ) ; int count = ; int index = newKey . indexOf ( toBeFound ) ; while ( index > - ) { count ++ ; if ( newKey . length ( ) < index + toBeFound . length ( ) ) break ; newKey = newKey . substring ( index + toBeFound . length ( ) ) ; index = newKey . indexOf ( toBeFound ) ; } return count ; } public static int lastIndexOf ( String toBeFound , char [ ] typePart ) { if ( typePart == null || typePart . length == ) return - ; return new String ( typePart ) . lastIndexOf ( toBeFound ) ; } public static final char [ ] concat ( char [ ] first , char [ ] second ) { if ( first == null ) return second ; if ( second == null ) return first ; int length1 = first . length ; int length2 = second . length ; char [ ] result = new char [ length1 + length2 ] ; System . arraycopy ( first , , result , , length1 ) ; System . arraycopy ( second , , result , length1 , length2 ) ; return result ; } public static char [ ] lastSegment ( char [ ] typeName , String divider ) { if ( typeName == null ) return NO_CHAR ; char [ ] [ ] result = splitOn ( divider , typeName ) ; return result [ result . length - ] ; } public static final char [ ] [ ] arrayConcat ( char [ ] [ ] first , char [ ] [ ] second ) { if ( first == null ) return second ; if ( second == null ) return first ; int length1 = first . length ; int length2 = second . length ; char [ ] [ ] result = new char [ length1 + length2 ] [ ] ; System . arraycopy ( first , , result , , length1 ) ; System . arraycopy ( second , , result , length1 , length2 ) ; return result ; } public static final char [ ] [ ] arrayConcat ( char [ ] [ ] first , char [ ] second ) { if ( second == null ) return first ; if ( first == null ) return new char [ ] [ ] { second } ; int length = first . length ; char [ ] [ ] result = new char [ length + ] [ ] ; System . arraycopy ( first , , result , , length ) ; result [ length ] = second ; return result ; } public static char [ ] concatWith ( char [ ] [ ] enclosingTypeNames , String string ) { if ( enclosingTypeNames == null ) return NO_CHAR ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < enclosingTypeNames . length ; i ++ ) { char [ ] name = enclosingTypeNames [ i ] ; if ( i > ) buffer . append ( string ) ; buffer . append ( name ) ; } return buffer . toString ( ) . toCharArray ( ) ; } public static char [ ] concat ( char [ ] one , char [ ] two , String separator ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( one ) ; buffer . append ( separator ) ; buffer . append ( two ) ; return buffer . toString ( ) . toCharArray ( ) ; } } package org . rubypeople . rdt . internal . core . util ; import org . rubypeople . rdt . internal . core . RubyElement ; public class MementoTokenizer { private static final String COUNT = Character . toString ( RubyElement . JEM_COUNT ) ; private static final String JAVAPROJECT = Character . toString ( RubyElement . JEM_RUBYPROJECT ) ; private static final String PACKAGEFRAGMENTROOT = Character . toString ( RubyElement . JEM_SOURCEFOLDERROOT ) ; private static final String PACKAGEFRAGMENT = Character . toString ( RubyElement . JEM_SOURCE_FOLDER ) ; private static final String FIELD = Character . toString ( RubyElement . JEM_FIELD ) ; private static final String METHOD = Character . toString ( RubyElement . JEM_METHOD ) ; private static final String COMPILATIONUNIT = Character . toString ( RubyElement . JEM_RUBYSCRIPT ) ; private static final String TYPE = Character . toString ( RubyElement . JEM_TYPE ) ; private static final String IMPORTDECLARATION = Character . toString ( RubyElement . JEM_IMPORTDECLARATION ) ; private static final String LOCALVARIABLE = Character . toString ( RubyElement . JEM_LOCALVARIABLE ) ; private final char [ ] memento ; private final int length ; private int index = ; public MementoTokenizer ( String memento ) { this . memento = memento . toCharArray ( ) ; this . length = this . memento . length ; } public boolean hasMoreTokens ( ) { return this . index < this . length ; } public String nextToken ( ) { int start = this . index ; StringBuffer buffer = null ; switch ( this . memento [ this . index ++ ] ) { case RubyElement . JEM_ESCAPE : buffer = new StringBuffer ( ) ; buffer . append ( this . memento [ this . index ] ) ; start = ++ this . index ; break ; case RubyElement . JEM_COUNT : return COUNT ; case RubyElement . JEM_RUBYPROJECT : return JAVAPROJECT ; case RubyElement . JEM_SOURCEFOLDERROOT : return PACKAGEFRAGMENTROOT ; case RubyElement . JEM_SOURCE_FOLDER : return PACKAGEFRAGMENT ; case RubyElement . JEM_FIELD : return FIELD ; case RubyElement . JEM_METHOD : return METHOD ; case RubyElement . JEM_RUBYSCRIPT : return COMPILATIONUNIT ; case RubyElement . JEM_TYPE : return TYPE ; case RubyElement . JEM_IMPORTDECLARATION : return IMPORTDECLARATION ; case RubyElement . JEM_LOCALVARIABLE : return LOCALVARIABLE ; } loop : while ( this . index < this . length ) { switch ( this . memento [ this . index ] ) { case RubyElement . JEM_ESCAPE : if ( buffer == null ) buffer = new StringBuffer ( ) ; buffer . append ( this . memento , start , this . index - start ) ; start = ++ this . index ; break ; case RubyElement . JEM_COUNT : case RubyElement . JEM_RUBYPROJECT : case RubyElement . JEM_SOURCEFOLDERROOT : case RubyElement . JEM_SOURCE_FOLDER : case RubyElement . JEM_FIELD : case RubyElement . JEM_METHOD : case RubyElement . JEM_RUBYSCRIPT : case RubyElement . JEM_TYPE : case RubyElement . JEM_IMPORTDECLARATION : case RubyElement . JEM_LOCALVARIABLE : break loop ; } this . index ++ ; } if ( buffer != null ) { buffer . append ( this . memento , start , this . index - start ) ; return buffer . toString ( ) ; } else { return new String ( this . memento , start , this . index - start ) ; } } } package org . rubypeople . rdt . internal . core . util ; import java . util . HashSet ; import java . util . Set ; public class SetUtil { public static Set create ( Object obj1 , Object obj2 ) { HashSet Set = create ( obj1 ) ; Set . add ( obj2 ) ; return Set ; } public static HashSet create ( Object obj1 ) { HashSet Set = new HashSet ( ) ; Set . add ( obj1 ) ; return Set ; } public static Set create ( Object obj1 , Object obj2 , Object obj3 ) { Set Set = create ( obj1 , obj2 ) ; Set . add ( obj3 ) ; return Set ; } } package org . rubypeople . rdt . internal . core . util ; import java . util . Iterator ; import org . jruby . ast . AliasNode ; import org . jruby . ast . AndNode ; import org . jruby . ast . ArgsCatNode ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgsPushNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . AttrAssignNode ; import org . jruby . ast . BackRefNode ; import org . jruby . ast . BeginNode ; import org . jruby . ast . BignumNode ; import org . jruby . ast . BlockArgNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . BlockPassNode ; import org . jruby . ast . BreakNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . CaseNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . Colon3Node ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DRegexpNode ; import org . jruby . ast . DStrNode ; import org . jruby . ast . DSymbolNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DXStrNode ; import org . jruby . ast . DefinedNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . DotNode ; import org . jruby . ast . EnsureNode ; import org . jruby . ast . EvStrNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . FalseNode ; import org . jruby . ast . FixnumNode ; import org . jruby . ast . FlipNode ; import org . jruby . ast . FloatNode ; import org . jruby . ast . ForNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Match2Node ; import org . jruby . ast . Match3Node ; import org . jruby . ast . MatchNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . MultipleAsgn19Node ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . NextNode ; import org . jruby . ast . NilNode ; import org . jruby . ast . Node ; import org . jruby . ast . NotNode ; import org . jruby . ast . NthRefNode ; import org . jruby . ast . OpAsgnAndNode ; import org . jruby . ast . OpAsgnNode ; import org . jruby . ast . OpAsgnOrNode ; import org . jruby . ast . OpElementAsgnNode ; import org . jruby . ast . OrNode ; import org . jruby . ast . PostExeNode ; import org . jruby . ast . PreExeNode ; import org . jruby . ast . RedoNode ; import org . jruby . ast . RegexpNode ; import org . jruby . ast . RescueBodyNode ; import org . jruby . ast . RescueNode ; import org . jruby . ast . RestArgNode ; import org . jruby . ast . RetryNode ; import org . jruby . ast . ReturnNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . jruby . ast . SValueNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . SplatNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . SuperNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . ToAryNode ; import org . jruby . ast . TrueNode ; import org . jruby . ast . UndefNode ; import org . jruby . ast . UntilNode ; import org . jruby . ast . VAliasNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . WhenNode ; import org . jruby . ast . WhileNode ; import org . jruby . ast . XStrNode ; import org . jruby . ast . YieldNode ; import org . jruby . ast . ZArrayNode ; import org . jruby . ast . ZSuperNode ; import org . jruby . ast . visitor . NodeVisitor ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . SourceRefElement ; public class DOMFinder implements NodeVisitor { public Node foundNode = null ; private Node ast ; private SourceRefElement element ; private int rangeStart = - , rangeLength = ; public DOMFinder ( Node ast , SourceRefElement element ) { this . ast = ast ; this . element = element ; } public Object visitAliasNode ( AliasNode arg0 ) { return null ; } public Object visitAndNode ( AndNode iVisited ) { visitNode ( iVisited . getFirstNode ( ) ) ; visitNode ( iVisited . getSecondNode ( ) ) ; return null ; } public Object visitArgsCatNode ( ArgsCatNode iVisited ) { visitNode ( iVisited . getFirstNode ( ) ) ; visitNode ( iVisited . getSecondNode ( ) ) ; return null ; } public Object visitArgsNode ( ArgsNode iVisited ) { visitNode ( iVisited . getBlock ( ) ) ; if ( iVisited . getOptArgs ( ) != null ) { visitIter ( iVisited . getOptArgs ( ) . childNodes ( ) . iterator ( ) ) ; } return null ; } private Object visitIter ( Iterator < Node > iterator ) { while ( iterator . hasNext ( ) ) { visitNode ( iterator . next ( ) ) ; } return null ; } public Object visitArrayNode ( ArrayNode iVisited ) { visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public Object visitBackRefNode ( BackRefNode arg0 ) { return null ; } public Object visitBeginNode ( BeginNode iVisited ) { visitNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitBignumNode ( BignumNode arg0 ) { return null ; } public Object visitBlockArgNode ( BlockArgNode arg0 ) { return null ; } public Object visitBlockNode ( BlockNode iVisited ) { visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public Object visitBlockPassNode ( BlockPassNode iVisited ) { visitNode ( iVisited . getArgsNode ( ) ) ; visitNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitBreakNode ( BreakNode iVisited ) { visitNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitCallNode ( CallNode iVisited ) { visitNode ( iVisited . getReceiverNode ( ) ) ; visitNode ( iVisited . getArgsNode ( ) ) ; visitNode ( iVisited . getIterNode ( ) ) ; return null ; } public Object visitCaseNode ( CaseNode iVisited ) { visitNode ( iVisited . getCaseNode ( ) ) ; visitNode ( iVisited . getCases ( ) ) ; return null ; } public Object visitClassNode ( ClassNode node ) { String name = getFullyQualifiedName ( node . getCPath ( ) ) ; ISourcePosition pos = node . getPosition ( ) ; int nameStart = pos . getStartOffset ( ) + "" . length ( ) + ; if ( ! found ( node , nameStart , name . length ( ) ) ) { visitNode ( node . getSuperNode ( ) ) ; visitNode ( node . getBodyNode ( ) ) ; } return null ; } private Object visitNode ( Node iVisited ) { if ( iVisited != null ) iVisited . accept ( this ) ; return null ; } private boolean found ( Node node , int start , int length ) { if ( start == this . rangeStart && length == this . rangeLength ) { this . foundNode = node ; } return false ; } private String getFullyQualifiedName ( Node node ) { if ( node == null ) return "" ; if ( node instanceof ConstNode ) { ConstNode constNode = ( ConstNode ) node ; return constNode . getName ( ) ; } if ( node instanceof Colon2Node ) { Colon2Node colonNode = ( Colon2Node ) node ; String prefix = getFullyQualifiedName ( colonNode . getLeftNode ( ) ) ; if ( prefix . length ( ) > ) prefix = prefix + "" ; return prefix + colonNode . getName ( ) ; } return "" ; } public Object visitClassVarAsgnNode ( ClassVarAsgnNode arg0 ) { return null ; } public Object visitClassVarDeclNode ( ClassVarDeclNode arg0 ) { return null ; } public Object visitClassVarNode ( ClassVarNode arg0 ) { return null ; } public Object visitColon2Node ( Colon2Node arg0 ) { return null ; } public Object visitColon3Node ( Colon3Node arg0 ) { return null ; } public Object visitConstDeclNode ( ConstDeclNode arg0 ) { return null ; } public Object visitConstNode ( ConstNode arg0 ) { return null ; } public Object visitDAsgnNode ( DAsgnNode arg0 ) { return null ; } public Object visitDRegxNode ( DRegexpNode arg0 ) { return null ; } public Object visitDStrNode ( DStrNode arg0 ) { return null ; } public Object visitDSymbolNode ( DSymbolNode arg0 ) { return null ; } public Object visitDVarNode ( DVarNode arg0 ) { return null ; } public Object visitDXStrNode ( DXStrNode arg0 ) { return null ; } public Object visitDefinedNode ( DefinedNode arg0 ) { return null ; } public Object visitDefnNode ( DefnNode iVisited ) { String name = iVisited . getName ( ) ; ISourcePosition pos = iVisited . getPosition ( ) ; int nameStart = pos . getStartOffset ( ) + "" . length ( ) + ; if ( ! found ( iVisited , nameStart , name . length ( ) ) ) { visitNode ( iVisited . getArgsNode ( ) ) ; visitNode ( iVisited . getBodyNode ( ) ) ; } return null ; } public Object visitDefsNode ( DefsNode iVisited ) { String name ; String receiver = ASTUtil . stringRepresentation ( iVisited . getReceiverNode ( ) ) ; if ( receiver != null && receiver . trim ( ) . length ( ) > ) { name = receiver + "" + iVisited . getName ( ) ; } else { name = iVisited . getName ( ) ; } ISourcePosition pos = iVisited . getPosition ( ) ; int nameStart = pos . getStartOffset ( ) + "" . length ( ) + ; if ( ! found ( iVisited , nameStart , name . length ( ) ) ) { visitNode ( iVisited . getReceiverNode ( ) ) ; visitNode ( iVisited . getArgsNode ( ) ) ; visitNode ( iVisited . getBodyNode ( ) ) ; } return null ; } public Object visitDotNode ( DotNode arg0 ) { return null ; } public Object visitEnsureNode ( EnsureNode arg0 ) { return null ; } public Object visitEvStrNode ( EvStrNode arg0 ) { return null ; } public Object visitFCallNode ( FCallNode arg0 ) { return null ; } public Object visitFalseNode ( FalseNode arg0 ) { return null ; } public Object visitFixnumNode ( FixnumNode arg0 ) { return null ; } public Object visitFlipNode ( FlipNode arg0 ) { return null ; } public Object visitFloatNode ( FloatNode arg0 ) { return null ; } public Object visitForNode ( ForNode arg0 ) { return null ; } public Object visitGlobalAsgnNode ( GlobalAsgnNode arg0 ) { return null ; } public Object visitGlobalVarNode ( GlobalVarNode arg0 ) { return null ; } public Object visitHashNode ( HashNode arg0 ) { return null ; } public Object visitIfNode ( IfNode arg0 ) { return null ; } public Object visitInstAsgnNode ( InstAsgnNode arg0 ) { return null ; } public Object visitInstVarNode ( InstVarNode arg0 ) { return null ; } public Object visitIterNode ( IterNode arg0 ) { return null ; } public Object visitLocalAsgnNode ( LocalAsgnNode arg0 ) { return null ; } public Object visitLocalVarNode ( LocalVarNode arg0 ) { return null ; } public Object visitMatch2Node ( Match2Node arg0 ) { return null ; } public Object visitMatch3Node ( Match3Node arg0 ) { return null ; } public Object visitMatchNode ( MatchNode arg0 ) { return null ; } public Object visitModuleNode ( ModuleNode arg0 ) { return null ; } public Object visitMultipleAsgnNode ( MultipleAsgnNode arg0 ) { return null ; } public Object visitNewlineNode ( NewlineNode iVisited ) { visitNode ( iVisited . getNextNode ( ) ) ; return null ; } public Object visitNextNode ( NextNode iVisited ) { visitNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitNilNode ( NilNode arg0 ) { return null ; } public Object visitNotNode ( NotNode arg0 ) { return null ; } public Object visitNthRefNode ( NthRefNode arg0 ) { return null ; } public Object visitOpAsgnAndNode ( OpAsgnAndNode arg0 ) { return null ; } public Object visitOpAsgnNode ( OpAsgnNode arg0 ) { return null ; } public Object visitOpAsgnOrNode ( OpAsgnOrNode arg0 ) { return null ; } public Object visitOpElementAsgnNode ( OpElementAsgnNode arg0 ) { return null ; } public Object visitOrNode ( OrNode arg0 ) { return null ; } public Object visitPreExeNode ( PreExeNode iVisited ) { return null ; } public Object visitPostExeNode ( PostExeNode arg0 ) { return null ; } public Object visitRedoNode ( RedoNode arg0 ) { return null ; } public Object visitRegexpNode ( RegexpNode arg0 ) { return null ; } public Object visitRescueBodyNode ( RescueBodyNode arg0 ) { return null ; } public Object visitRescueNode ( RescueNode arg0 ) { return null ; } public Object visitRetryNode ( RetryNode arg0 ) { return null ; } public Object visitReturnNode ( ReturnNode arg0 ) { return null ; } public Object visitSClassNode ( SClassNode arg0 ) { return null ; } public Object visitSValueNode ( SValueNode arg0 ) { return null ; } public Object visitSelfNode ( SelfNode arg0 ) { return null ; } public Object visitSplatNode ( SplatNode arg0 ) { return null ; } public Object visitStrNode ( StrNode arg0 ) { return null ; } public Object visitSuperNode ( SuperNode arg0 ) { return null ; } public Object visitSymbolNode ( SymbolNode arg0 ) { return null ; } public Object visitToAryNode ( ToAryNode arg0 ) { return null ; } public Object visitTrueNode ( TrueNode arg0 ) { return null ; } public Object visitUndefNode ( UndefNode arg0 ) { return null ; } public Object visitUntilNode ( UntilNode arg0 ) { return null ; } public Object visitVAliasNode ( VAliasNode arg0 ) { return null ; } public Object visitVCallNode ( VCallNode arg0 ) { return null ; } public Object visitWhenNode ( WhenNode arg0 ) { return null ; } public Object visitWhileNode ( WhileNode arg0 ) { return null ; } public Object visitXStrNode ( XStrNode arg0 ) { return null ; } public Object visitYieldNode ( YieldNode arg0 ) { return null ; } public Object visitZArrayNode ( ZArrayNode arg0 ) { return null ; } public Object visitZSuperNode ( ZSuperNode node ) { return null ; } public Node search ( ) throws RubyModelException { ISourceRange range = null ; if ( this . element instanceof IMember ) range = ( ( IMember ) this . element ) . getNameRange ( ) ; else range = this . element . getSourceRange ( ) ; this . rangeStart = range . getOffset ( ) ; this . rangeLength = range . getLength ( ) ; this . ast . accept ( this ) ; return this . foundNode ; } public Object visitArgsPushNode ( ArgsPushNode node ) { return null ; } public Object visitAttrAssignNode ( AttrAssignNode iVisited ) { return null ; } public Object visitRootNode ( RootNode iVisited ) { visitNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitRestArgNode ( RestArgNode visited ) { return null ; } public Object visitMultipleAsgnNode ( MultipleAsgn19Node visited ) { return null ; } } package org . rubypeople . rdt . internal . core . util ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . AttrAssignNode ; import org . jruby . ast . BignumNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DStrNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . FalseNode ; import org . jruby . ast . FixnumNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . IArgumentNode ; import org . jruby . ast . IScopingNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . NilNode ; import org . jruby . ast . Node ; import org . jruby . ast . SClassNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . SplatNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . TrueNode ; import org . jruby . ast . ZArrayNode ; import org . jruby . ast . types . INameNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . parser . StaticScope ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; public abstract class ASTUtil { private static final boolean VERBOSE = false ; private static final String NAMESPACE_DELIMETER = "" ; private static final String OBJECT = "" ; private static final String EMPTY_STRING = "" ; public static String [ ] getArgs ( Node argsNode , StaticScope scope ) { if ( argsNode == null ) return new String [ ] ; ArgsNode args = ( ArgsNode ) argsNode ; boolean hasRest = false ; if ( args . getRestArg ( ) != - ) hasRest = true ; boolean hasBlock = false ; if ( args . getBlock ( ) != null ) hasBlock = true ; int optArgCount = ; if ( args . getOptArgs ( ) != null ) optArgCount = args . getOptArgs ( ) . size ( ) ; List < String > arguments = getArguments ( args . getPre ( ) ) ; if ( optArgCount > ) { arguments . addAll ( getArguments ( args . getOptArgs ( ) ) ) ; } if ( hasRest ) { String restName = "" ; if ( args . getRestArg ( ) != - ) { restName += scope . getVariables ( ) [ args . getRestArg ( ) ] ; } arguments . add ( restName ) ; } if ( hasBlock ) arguments . add ( "" + scope . getVariables ( ) [ args . getBlock ( ) . getCount ( ) ] ) ; return stringListToArray ( arguments ) ; } private static String [ ] stringListToArray ( List < String > list ) { String [ ] array = new String [ list . size ( ) ] ; for ( int i = ; i < list . size ( ) ; i ++ ) { array [ i ] = list . get ( i ) ; } return array ; } public static List < String > getArguments ( ListNode argList ) { if ( argList == null ) return new ArrayList < String > ( ) ; List < String > arguments = new ArrayList < String > ( ) ; for ( Node node : argList . childNodes ( ) ) { if ( node instanceof ArgumentNode ) { arguments . add ( ( ( ArgumentNode ) node ) . getName ( ) ) ; } else if ( node instanceof LocalAsgnNode ) { LocalAsgnNode local = ( LocalAsgnNode ) node ; String argString = local . getName ( ) ; argString += "" ; argString += stringRepresentation ( local . getValueNode ( ) ) ; arguments . add ( argString ) ; } else { System . err . println ( "" + node . getClass ( ) . getSimpleName ( ) ) ; } } return arguments ; } public static String stringRepresentation ( Node node ) { if ( node == null ) return "" ; if ( node instanceof HashNode ) return "" ; if ( node instanceof SelfNode ) return "" ; if ( node instanceof NilNode ) return "" ; if ( node instanceof TrueNode ) return "" ; if ( node instanceof FalseNode ) return "" ; if ( node instanceof SymbolNode ) return '' + ( ( SymbolNode ) node ) . getName ( ) ; if ( node instanceof INameNode ) return ( ( INameNode ) node ) . getName ( ) ; if ( node instanceof ZArrayNode ) return "" ; if ( node instanceof FixnumNode ) return "" + ( ( FixnumNode ) node ) . getValue ( ) ; if ( node instanceof DStrNode ) return stringRepresentation ( ( DStrNode ) node ) ; if ( node instanceof StrNode ) return '' + ( ( StrNode ) node ) . getValue ( ) . toString ( ) + '' ; log ( "" + node . getClass ( ) . getName ( ) ) ; return node . toString ( ) ; } private static void log ( String string ) { if ( VERBOSE ) System . out . println ( string ) ; } private static String stringRepresentation ( DStrNode node ) { List children = node . childNodes ( ) ; StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( Iterator iter = children . iterator ( ) ; iter . hasNext ( ) ; ) { Node child = ( Node ) iter . next ( ) ; buffer . append ( stringRepresentation ( child ) ) ; } buffer . append ( "" ) ; return buffer . toString ( ) ; } public static String getNameReflectively ( Node node ) { if ( node == null ) return "" ; if ( node instanceof ClassNode ) { ClassNode classNode = ( ClassNode ) node ; return getNameReflectively ( classNode . getCPath ( ) ) ; } if ( node instanceof ModuleNode ) { ModuleNode moduleNode = ( ModuleNode ) node ; return getNameReflectively ( moduleNode . getCPath ( ) ) ; } if ( node instanceof INameNode ) { return ( ( INameNode ) node ) . getName ( ) ; } try { Method getNameMethod = node . getClass ( ) . getMethod ( "" , new Class [ ] { } ) ; Object name = getNameMethod . invoke ( node , new Object [ ] ) ; return ( String ) name ; } catch ( Exception e ) { return null ; } } public static String getFullyQualifiedName ( Colon2Node node ) { StringBuffer name = new StringBuffer ( ) ; Node left = node . getLeftNode ( ) ; if ( left instanceof Colon2Node ) { name . append ( getFullyQualifiedName ( ( Colon2Node ) left ) ) ; } else if ( left instanceof ConstNode ) { name . append ( ( ( ConstNode ) left ) . getName ( ) ) ; } name . append ( NAMESPACE_DELIMETER ) ; name . append ( node . getName ( ) ) ; return name . toString ( ) ; } public static boolean isAssignment ( Node node ) { return ( node instanceof LocalAsgnNode ) || ( node instanceof ClassVarAsgnNode ) || ( node instanceof InstAsgnNode ) || ( node instanceof GlobalAsgnNode ) || ( node instanceof AttrAssignNode ) ; } public static boolean isTypeDefinition ( Node node ) { return node instanceof ClassNode || node instanceof ModuleNode || node instanceof SClassNode ; } public static boolean isMethodDefinition ( Node node ) { return node instanceof DefnNode || node instanceof DefsNode ; } public static boolean isMethodCall ( Node node ) { return node instanceof FCallNode || node instanceof CallNode ; } public static String getSource ( String contents , Node node ) { if ( node == null || contents == null ) return null ; ISourcePosition pos = node . getPosition ( ) ; if ( pos == null ) return null ; if ( pos . getStartOffset ( ) >= contents . length ( ) ) return null ; if ( pos . getEndOffset ( ) > contents . length ( ) ) return null ; return new String ( contents . substring ( pos . getStartOffset ( ) , pos . getEndOffset ( ) ) ) ; } public static boolean isVariable ( Node node ) { return ( node instanceof GlobalAsgnNode ) || ( node instanceof GlobalVarNode ) || ( node instanceof InstAsgnNode ) || ( node instanceof InstVarNode ) || ( node instanceof ConstDeclNode ) || ( node instanceof ConstNode ) || ( node instanceof ClassVarAsgnNode ) || ( node instanceof ClassVarDeclNode ) || ( node instanceof ClassVarNode ) ; } public static List < String > getArgumentsFromFunctionCall ( IArgumentNode iVisited ) { List < String > arguments = new ArrayList < String > ( ) ; List < Node > nodes = getArgumentNodesFromFunctionCall ( iVisited ) ; for ( Node node : nodes ) { if ( node instanceof DAsgnNode ) { DAsgnNode dasgn = ( DAsgnNode ) node ; arguments . add ( dasgn . getName ( ) ) ; } else { arguments . add ( stringRepresentation ( node ) ) ; } } return arguments ; } public static List < Node > getArgumentNodesFromFunctionCall ( IArgumentNode iVisited ) { List < Node > arguments = new ArrayList < Node > ( ) ; Node argsNode = iVisited . getArgsNode ( ) ; Iterator iter = null ; if ( argsNode instanceof SplatNode ) { SplatNode splat = ( SplatNode ) argsNode ; iter = splat . childNodes ( ) . iterator ( ) ; } else if ( argsNode instanceof ArrayNode ) { ArrayNode arrayNode = ( ArrayNode ) iVisited . getArgsNode ( ) ; iter = arrayNode . childNodes ( ) . iterator ( ) ; } else if ( argsNode == null ) { Node iterNode = null ; if ( iVisited instanceof FCallNode ) { FCallNode fcall = ( FCallNode ) iVisited ; iterNode = fcall . getIterNode ( ) ; } else if ( iVisited instanceof CallNode ) { CallNode call = ( CallNode ) iVisited ; iterNode = call . getIterNode ( ) ; } if ( iterNode == null ) return arguments ; if ( iterNode instanceof IterNode ) { IterNode yeah = ( IterNode ) iterNode ; Node varNode = yeah . getVarNode ( ) ; if ( varNode instanceof DAsgnNode ) { DAsgnNode dassgn = ( DAsgnNode ) varNode ; arguments . add ( dassgn ) ; } else if ( varNode instanceof MultipleAsgnNode ) { MultipleAsgnNode multi = ( MultipleAsgnNode ) varNode ; ListNode list = multi . getHeadNode ( ) ; if ( list != null ) iter = list . childNodes ( ) . iterator ( ) ; else { Node multiArgsNode = multi . getArgsNode ( ) ; if ( multiArgsNode instanceof DAsgnNode ) { DAsgnNode dassgn = ( DAsgnNode ) multiArgsNode ; arguments . add ( dassgn ) ; } } } } } if ( iter == null ) return arguments ; for ( ; iter . hasNext ( ) ; ) { Node argument = ( Node ) iter . next ( ) ; arguments . add ( argument ) ; } return arguments ; } public static String getSuperClassName ( Node superNode ) { if ( superNode == null ) return OBJECT ; return getFullyQualifiedName ( superNode ) ; } public static String getFullyQualifiedName ( Node node ) { if ( node == null ) return EMPTY_STRING ; if ( node instanceof ConstNode ) { ConstNode constNode = ( ConstNode ) node ; return constNode . getName ( ) ; } if ( node instanceof Colon2Node ) { Colon2Node colonNode = ( Colon2Node ) node ; String prefix = getFullyQualifiedName ( colonNode . getLeftNode ( ) ) ; if ( prefix . length ( ) > ) prefix = prefix + NAMESPACE_DELIMETER ; return prefix + colonNode . getName ( ) ; } return getNameReflectively ( node ) ; } public static String getFullyQualifiedTypeName ( Node rootNode , Node typeNode ) { String namespace = ASTUtil . getNamespace ( rootNode , typeNode . getPosition ( ) . getStartOffset ( ) ) ; if ( typeNode instanceof IScopingNode ) { String typeName = getNameReflectively ( typeNode ) ; if ( namespace . length ( ) == ) return typeName ; if ( ! namespace . equals ( typeName ) && ! namespace . endsWith ( NAMESPACE_DELIMETER + typeName ) ) { namespace += NAMESPACE_DELIMETER + typeName ; } } return namespace ; } public static String getNamespace ( Node root , int offset ) { List < Node > surrounding = new ArrayList < Node > ( ) ; Node typeNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( root , offset , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof ModuleNode || node instanceof ClassNode ; } } ) ; if ( typeNode == null ) return "" ; if ( offset < ( ( IScopingNode ) typeNode ) . getCPath ( ) . getPosition ( ) . getEndOffset ( ) ) { int newStartOffset = typeNode . getPosition ( ) . getStartOffset ( ) - ; if ( newStartOffset < ) newStartOffset = ; typeNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( root , newStartOffset , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof ModuleNode || node instanceof ClassNode ; } } ) ; } while ( typeNode != null ) { surrounding . add ( , typeNode ) ; typeNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( root , typeNode . getPosition ( ) . getStartOffset ( ) - , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof ModuleNode || node instanceof ClassNode ; } } ) ; } StringBuffer buffer = new StringBuffer ( ) ; boolean first = true ; for ( Node node : surrounding ) { if ( ! first ) { buffer . append ( NAMESPACE_DELIMETER ) ; } buffer . append ( getNameReflectively ( node ) ) ; if ( first ) { first = false ; } } return buffer . toString ( ) ; } public static String stringValue ( Node node ) { if ( node instanceof StrNode ) { return ( ( StrNode ) node ) . getValue ( ) . toString ( ) ; } if ( node instanceof SymbolNode ) { return ( ( SymbolNode ) node ) . getName ( ) ; } if ( node instanceof FixnumNode ) { return Long . toString ( ( ( FixnumNode ) node ) . getValue ( ) ) ; } if ( node instanceof BignumNode ) { return ( ( BignumNode ) node ) . getValue ( ) . toString ( ) ; } return null ; } } package org . rubypeople . rdt . internal . core . util ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . PrintStream ; import java . net . URI ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . filesystem . IFileStore ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . content . IContentType ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyElement ; public class Util { private static boolean ENABLE_RUBY_LIKE_EXTENSIONS = true ; private static char [ ] [ ] RUBY_LIKE_EXTENSIONS ; private static char [ ] [ ] RUBY_LIKE_FILENAMES ; private static final String NAMESPACE_DELIMETER = "" ; private Util ( ) { } public interface Comparer { int compare ( Object a , Object b ) ; } public static void sort ( Object [ ] objects , Comparer comparer ) { if ( objects . length > ) quickSort ( objects , , objects . length - , comparer ) ; } private static void quickSort ( Object [ ] sortedCollection , int left , int right , Comparer comparer ) { int original_left = left ; int original_right = right ; Object mid = sortedCollection [ ( left + right ) / ] ; do { while ( comparer . compare ( sortedCollection [ left ] , mid ) < ) { left ++ ; } while ( comparer . compare ( mid , sortedCollection [ right ] ) < ) { right -- ; } if ( left <= right ) { Object tmp = sortedCollection [ left ] ; sortedCollection [ left ] = sortedCollection [ right ] ; sortedCollection [ right ] = tmp ; left ++ ; right -- ; } } while ( left <= right ) ; if ( original_left < right ) { quickSort ( sortedCollection , original_left , right , comparer ) ; } if ( left < original_right ) { quickSort ( sortedCollection , left , original_right , comparer ) ; } } public final static boolean isExcluded ( IPath resourcePath , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns , boolean isFolderPath ) { if ( inclusionPatterns == null && exclusionPatterns == null ) return false ; return isExcluded ( resourcePath . toString ( ) . toCharArray ( ) , inclusionPatterns , exclusionPatterns , isFolderPath ) ; } public final static boolean isExcluded ( IResource resource , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns ) { IPath path = resource . getFullPath ( ) ; return isExcluded ( path , inclusionPatterns , exclusionPatterns , resource . getType ( ) == IResource . FOLDER ) ; } public final static boolean isExcluded ( char [ ] path , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns , boolean isFolderPath ) { if ( inclusionPatterns == null && exclusionPatterns == null ) return false ; inclusionCheck : if ( inclusionPatterns != null ) { for ( int i = , length = inclusionPatterns . length ; i < length ; i ++ ) { char [ ] pattern = inclusionPatterns [ i ] ; char [ ] folderPattern = pattern ; if ( isFolderPath ) { int lastSlash = CharOperation . lastIndexOf ( '' , pattern ) ; if ( lastSlash != - && lastSlash != pattern . length - ) { int star = CharOperation . indexOf ( '' , pattern , lastSlash ) ; if ( ( star == - || star >= pattern . length - || pattern [ star + ] != '' ) ) { folderPattern = CharOperation . subarray ( pattern , , lastSlash ) ; } } } if ( CharOperation . pathMatch ( folderPattern , path , true , '' ) ) { break inclusionCheck ; } } return true ; } if ( isFolderPath ) { path = CharOperation . concat ( path , new char [ ] { '' } , '' ) ; } exclusionCheck : if ( exclusionPatterns != null ) { for ( int i = , length = exclusionPatterns . length ; i < length ; i ++ ) { if ( CharOperation . pathMatch ( exclusionPatterns [ i ] , path , true , '' ) ) { return true ; } } } return false ; } public static void verbose ( String log ) { verbose ( log , System . out ) ; } public static synchronized void verbose ( String log , PrintStream printStream ) { int start = ; do { int end = log . indexOf ( '' , start ) ; printStream . print ( Thread . currentThread ( ) ) ; printStream . print ( "" ) ; printStream . print ( log . substring ( start , end == - ? log . length ( ) : end + ) ) ; start = end + ; } while ( start != ) ; printStream . println ( ) ; } public final static boolean isRubyLikeFileName ( String name ) { if ( name == null ) return false ; char [ ] [ ] rubyFileNames = getRubyLikeFilenames ( ) ; for ( int i = ; i < rubyFileNames . length ; i ++ ) { char [ ] filename = rubyFileNames [ i ] ; if ( name . equals ( new String ( filename ) ) ) return true ; } return indexOfRubyLikeExtension ( name ) != - ; } public final static boolean isRubyOrERBLikeFileName ( String name ) { return isRubyLikeFileName ( name ) || isERBLikeFileName ( name ) ; } public static boolean isValidRubyScriptName ( String name ) { return RubyConventions . validateRubyScriptName ( name ) . getSeverity ( ) != IStatus . ERROR ; } public static boolean equalArraysOrNull ( Object [ ] a , Object [ ] b ) { if ( a == b ) return true ; if ( a == null || b == null ) return false ; int len = a . length ; if ( len != b . length ) return false ; for ( int i = ; i < len ; ++ i ) { if ( a [ i ] == null ) { if ( b [ i ] != null ) return false ; } else { if ( ! a [ i ] . equals ( b [ i ] ) ) return false ; } } return true ; } public static void log ( Throwable e , String message ) { Throwable nestedException ; if ( e instanceof RubyModelException && ( nestedException = ( ( RubyModelException ) e ) . getException ( ) ) != null ) { e = nestedException ; } IStatus status = new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , IStatus . ERROR , message , e ) ; RubyCore . getPlugin ( ) . getLog ( ) . log ( status ) ; } public static int combineHashCodes ( int hashCode1 , int hashCode2 ) { return hashCode1 * + hashCode2 ; } public static final boolean isExcluded ( IRubyElement element ) { int elementType = element . getElementType ( ) ; switch ( elementType ) { case IRubyElement . RUBY_MODEL : case IRubyElement . RUBY_PROJECT : return false ; case IRubyElement . SCRIPT : IResource resource = element . getResource ( ) ; if ( resource == null ) return false ; return isExcluded ( element . getParent ( ) ) ; default : IRubyElement cu = element . getAncestor ( IRubyElement . SCRIPT ) ; return cu != null && isExcluded ( cu ) ; } } public static String getNameWithoutRubyLikeExtension ( String fileName ) { int index = indexOfRubyLikeExtension ( fileName ) ; if ( index == - ) return fileName ; return fileName . substring ( , index ) ; } public static int indexOfRubyLikeExtension ( String fileName ) { int fileNameLength = fileName . length ( ) ; char [ ] [ ] rubyLikeExtensions = getRubyLikeExtensions ( ) ; extensions : for ( int i = , length = rubyLikeExtensions . length ; i < length ; i ++ ) { char [ ] extension = rubyLikeExtensions [ i ] ; int extensionLength = extension . length ; int extensionStart = fileNameLength - extensionLength ; int dotIndex = extensionStart - ; if ( dotIndex < ) continue ; if ( fileName . charAt ( dotIndex ) != '' ) continue ; for ( int j = ; j < extensionLength ; j ++ ) { if ( fileName . charAt ( extensionStart + j ) != extension [ j ] ) continue extensions ; } return dotIndex ; } return - ; } public static char [ ] [ ] getRubyLikeExtensions ( ) { if ( RUBY_LIKE_EXTENSIONS == null ) { if ( ! ENABLE_RUBY_LIKE_EXTENSIONS ) RUBY_LIKE_EXTENSIONS = new char [ ] [ ] { "" . toCharArray ( ) , "" . toCharArray ( ) , "" . toCharArray ( ) , "" . toCharArray ( ) , "" . toCharArray ( ) } ; else { IContentType rubyContentType = Platform . getContentTypeManager ( ) . getContentType ( RubyCore . RUBY_SOURCE_CONTENT_TYPE ) ; String [ ] fileExtensions = rubyContentType == null ? null : rubyContentType . getFileSpecs ( IContentType . FILE_EXTENSION_SPEC ) ; int length = fileExtensions == null ? : fileExtensions . length ; char [ ] [ ] extensions = new char [ length ] [ ] ; SimpleWordSet knownExtensions = new SimpleWordSet ( length ) ; extensions [ ] = "" . toCharArray ( ) ; knownExtensions . add ( extensions [ ] ) ; int index = ; for ( int i = ; i < length ; i ++ ) { String fileExtension = fileExtensions [ i ] ; char [ ] extension = fileExtension . toCharArray ( ) ; if ( ! knownExtensions . includes ( extension ) ) { extensions [ index ++ ] = extension ; knownExtensions . add ( extension ) ; } } if ( index != length ) System . arraycopy ( extensions , , extensions = new char [ index ] [ ] , , index ) ; RUBY_LIKE_EXTENSIONS = extensions ; } } return RUBY_LIKE_EXTENSIONS ; } public static char [ ] [ ] getRubyLikeFilenames ( ) { if ( RUBY_LIKE_FILENAMES == null ) { IContentType rubyContentType = Platform . getContentTypeManager ( ) . getContentType ( RubyCore . RUBY_SOURCE_CONTENT_TYPE ) ; String [ ] filenames = rubyContentType == null ? null : rubyContentType . getFileSpecs ( IContentType . FILE_NAME_SPEC ) ; int length = filenames == null ? : filenames . length ; names = new char [ length ] [ ] ; SimpleWordSet knownExtensions = new SimpleWordSet ( length ) ; names [ ] = "" . toCharArray ( ) ; knownExtensions . add ( names [ ] ) ; int index = ; for ( int i = ; i < length ; i ++ ) { String fileExtension = filenames [ i ] ; char [ ] extension = fileExtension . toCharArray ( ) ; if ( ! knownExtensions . includes ( extension ) ) { names [ index ++ ] = extension ; knownExtensions . add ( extension ) ; } } if ( index != length ) System . arraycopy ( names , , names = new char [ index ] [ ] , , index ) ; RUBY_LIKE_FILENAMES = names ; } return RUBY_LIKE_FILENAMES ; } private static final int DEFAULT_READING_SIZE = ; private static char [ ] [ ] names ; private static final String ARGUMENTS_DELIMITER = "" ; private static final String EMPTY_ARGUMENT = "" ; public static char [ ] getResourceContentsAsCharArray ( IFile file ) throws RubyModelException { String encoding = null ; try { encoding = file . getCharset ( ) ; } catch ( CoreException ce ) { } return getResourceContentsAsCharArray ( file , encoding ) ; } public static char [ ] getResourceContentsAsCharArray ( IFile file , String encoding ) throws RubyModelException { InputStream stream = null ; try { stream = new BufferedInputStream ( file . getContents ( true ) ) ; } catch ( CoreException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST ) ; } try { return Util . getInputStreamAsCharArray ( stream , - , encoding ) ; } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } finally { try { stream . close ( ) ; } catch ( IOException e ) { } } } public static char [ ] getInputStreamAsCharArray ( InputStream stream , int length , String encoding ) throws IOException { InputStreamReader reader = null ; reader = encoding == null ? new InputStreamReader ( stream ) : new InputStreamReader ( stream , encoding ) ; char [ ] contents ; if ( length == - ) { contents = new char [ ] ; int contentsLength = ; int amountRead = - ; do { int amountRequested = Math . max ( stream . available ( ) , DEFAULT_READING_SIZE ) ; if ( contentsLength + amountRequested > contents . length ) { System . arraycopy ( contents , , contents = new char [ contentsLength + amountRequested ] , , contentsLength ) ; } amountRead = reader . read ( contents , contentsLength , amountRequested ) ; if ( amountRead > ) { contentsLength += amountRead ; } } while ( amountRead != - ) ; int start = ; if ( contentsLength > && "" . equals ( encoding ) ) { if ( contents [ ] == ) { contentsLength -- ; start = ; } } if ( contentsLength < contents . length ) { System . arraycopy ( contents , start , contents = new char [ contentsLength ] , , contentsLength ) ; } } else { contents = new char [ length ] ; int len = ; int readSize = ; while ( ( readSize != - ) && ( len != length ) ) { len += readSize ; readSize = reader . read ( contents , len , length - len ) ; } int start = ; if ( length > && "" . equals ( encoding ) ) { if ( contents [ ] == ) { len -- ; start = ; } } if ( len != length ) System . arraycopy ( contents , start , ( contents = new char [ len ] ) , , len ) ; } return contents ; } public static void resetRubyLikeExtensions ( ) { RUBY_LIKE_EXTENSIONS = null ; RUBY_LIKE_FILENAMES = null ; } public static final String [ ] arrayConcat ( String [ ] first , String second ) { if ( second == null ) return first ; if ( first == null ) return new String [ ] { second } ; int length = first . length ; if ( first . length == ) { return new String [ ] { second } ; } String [ ] result = new String [ length + ] ; System . arraycopy ( first , , result , , length ) ; result [ length ] = second ; return result ; } public static String [ ] getTrimmedSimpleNames ( String packageName ) { if ( packageName . length ( ) == ) return new String [ ] ; return packageName . split ( "" + File . separator ) ; } public static String concatWith ( String [ ] array , char separator ) { StringBuffer buffer = new StringBuffer ( ) ; for ( int i = , length = array . length ; i < length ; i ++ ) { buffer . append ( array [ i ] ) ; if ( i < length - ) buffer . append ( separator ) ; } return buffer . toString ( ) ; } public static boolean isValidSourceFolderName ( String name ) { return true ; } public static byte [ ] getResourceContentsAsByteArray ( IFile file ) throws RubyModelException { InputStream stream = null ; try { stream = file . getContents ( true ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } try { return org . rubypeople . rdt . core . util . Util . getInputStreamAsByteArray ( stream , - ) ; } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } finally { try { stream . close ( ) ; } catch ( IOException e ) { } } } public static File toLocalFile ( URI uri , IProgressMonitor monitor ) throws CoreException { IFileStore fileStore = EFS . getStore ( uri ) ; File localFile = fileStore . toLocalFile ( EFS . NONE , monitor ) ; if ( localFile == null ) localFile = fileStore . toLocalFile ( EFS . CACHE , monitor ) ; return localFile ; } public static String getProblemArgumentsForMarker ( String [ ] arguments ) { StringBuffer args = new StringBuffer ( ) ; args . append ( arguments . length ) ; args . append ( '' ) ; for ( int j = ; j < arguments . length ; j ++ ) { if ( j != ) args . append ( ARGUMENTS_DELIMITER ) ; if ( arguments [ j ] . length ( ) == ) { args . append ( EMPTY_ARGUMENT ) ; } else { args . append ( arguments [ j ] ) ; } } return args . toString ( ) ; } public static String getLineSeparator ( String text , IRubyProject project ) { String lineSeparator = null ; if ( text != null && text . length ( ) != ) { lineSeparator = findLineSeparator ( text . toCharArray ( ) ) ; if ( lineSeparator != null ) return lineSeparator ; } IScopeContext [ ] scopeContext ; if ( project != null ) { scopeContext = new IScopeContext [ ] { new ProjectScope ( project . getProject ( ) ) } ; lineSeparator = Platform . getPreferencesService ( ) . getString ( Platform . PI_RUNTIME , Platform . PREF_LINE_SEPARATOR , null , scopeContext ) ; if ( lineSeparator != null ) return lineSeparator ; } scopeContext = new IScopeContext [ ] { new InstanceScope ( ) } ; lineSeparator = Platform . getPreferencesService ( ) . getString ( Platform . PI_RUNTIME , Platform . PREF_LINE_SEPARATOR , null , scopeContext ) ; if ( lineSeparator != null ) return lineSeparator ; return org . rubypeople . rdt . core . util . Util . LINE_SEPARATOR ; } public static String findLineSeparator ( char [ ] text ) { int length = text . length ; if ( length > ) { char nextChar = text [ ] ; for ( int i = ; i < length ; i ++ ) { char currentChar = nextChar ; nextChar = i < length - ? text [ i + ] : '' ; switch ( currentChar ) { case '' : return "" ; case '' : return nextChar == '' ? "" : "" ; } } } return null ; } public static void sort ( String [ ] strings ) { if ( strings . length > ) quickSort ( strings , , strings . length - ) ; } private static void quickSort ( String [ ] sortedCollection , int left , int right ) { int original_left = left ; int original_right = right ; String mid = sortedCollection [ ( left + right ) / ] ; do { while ( sortedCollection [ left ] . compareTo ( mid ) < ) { left ++ ; } while ( mid . compareTo ( sortedCollection [ right ] ) < ) { right -- ; } if ( left <= right ) { String tmp = sortedCollection [ left ] ; sortedCollection [ left ] = sortedCollection [ right ] ; sortedCollection [ right ] = tmp ; left ++ ; right -- ; } } while ( left <= right ) ; if ( original_left < right ) { quickSort ( sortedCollection , original_left , right ) ; } if ( left < original_right ) { quickSort ( sortedCollection , left , original_right ) ; } } public static boolean equalArrays ( Object [ ] a , Object [ ] b , int len ) { if ( a == b ) return true ; if ( a . length < len || b . length < len ) return false ; for ( int i = ; i < len ; ++ i ) { if ( a [ i ] == null ) { if ( b [ i ] != null ) return false ; } else { if ( ! a [ i ] . equals ( b [ i ] ) ) return false ; } } return true ; } public static String getSimpleName ( String fullyQualifiedName ) { if ( fullyQualifiedName == null ) return null ; String [ ] names = getTypeNameParts ( fullyQualifiedName ) ; if ( names . length == ) return null ; return names [ names . length - ] ; } public static boolean parentsMatch ( IType type , String fullyQualifiedName ) { String [ ] names = getTypeNameParts ( fullyQualifiedName ) ; for ( int i = names . length - ; i >= ; i -- ) { IType parent = type . getDeclaringType ( ) ; if ( parent == null || ! names [ i ] . equals ( parent . getElementName ( ) ) ) { return false ; } type = parent ; } return true ; } public static String [ ] getTypeNameParts ( String fullyQualifiedName ) { if ( fullyQualifiedName == null ) return new String [ ] ; return fullyQualifiedName . split ( NAMESPACE_DELIMETER ) ; } public static void sort ( int [ ] list ) { if ( list . length > ) quickSort ( list , , list . length - ) ; } private static void quickSort ( int [ ] list , int left , int right ) { int original_left = left ; int original_right = right ; int mid = list [ ( left + right ) / ] ; do { while ( list [ left ] < mid ) { left ++ ; } while ( mid < list [ right ] ) { right -- ; } if ( left <= right ) { int tmp = list [ left ] ; list [ left ] = list [ right ] ; list [ right ] = tmp ; left ++ ; right -- ; } } while ( left <= right ) ; if ( original_left < right ) { quickSort ( list , original_left , right ) ; } if ( left < original_right ) { quickSort ( list , left , original_right ) ; } } public static String relativePath ( IPath fullPath , int skipSegmentCount ) { boolean hasTrailingSeparator = fullPath . hasTrailingSeparator ( ) ; String [ ] segments = fullPath . segments ( ) ; int length = ; int max = segments . length ; if ( max > skipSegmentCount ) { for ( int i1 = skipSegmentCount ; i1 < max ; i1 ++ ) { length += segments [ i1 ] . length ( ) ; } length += max - skipSegmentCount - ; } if ( hasTrailingSeparator ) length ++ ; char [ ] result = new char [ length ] ; int offset = ; int len = segments . length - ; if ( len >= skipSegmentCount ) { for ( int i = skipSegmentCount ; i < len ; i ++ ) { int size = segments [ i ] . length ( ) ; segments [ i ] . getChars ( , size , result , offset ) ; offset += size ; result [ offset ++ ] = '' ; } int size = segments [ len ] . length ( ) ; segments [ len ] . getChars ( , size , result , offset ) ; offset += size ; } if ( hasTrailingSeparator ) result [ offset ++ ] = '' ; return new String ( result ) ; } public static IRubyElement [ ] sortCopy ( IRubyElement [ ] elements ) { int len = elements . length ; IRubyElement [ ] copy = new IRubyElement [ len ] ; System . arraycopy ( elements , , copy , , len ) ; sort ( copy , new Comparer ( ) { public int compare ( Object a , Object b ) { return ( ( RubyElement ) a ) . toStringWithAncestors ( ) . compareTo ( ( ( RubyElement ) b ) . toStringWithAncestors ( ) ) ; } } ) ; return copy ; } public static String identifierToConstant ( String typeName ) { StringBuffer buffer = new StringBuffer ( ) ; boolean doNextAsUpper = true ; for ( int i = ; i < typeName . length ( ) ; i ++ ) { char c = typeName . charAt ( i ) ; if ( doNextAsUpper ) { buffer . append ( Character . toUpperCase ( c ) ) ; doNextAsUpper = false ; } else if ( c == '' ) { doNextAsUpper = true ; } else { buffer . append ( c ) ; } } return buffer . toString ( ) ; } public static void sortReverseOrder ( String [ ] strings ) { if ( strings . length > ) quickSortReverse ( strings , , strings . length - ) ; } private static void quickSortReverse ( String [ ] sortedCollection , int left , int right ) { int original_left = left ; int original_right = right ; String mid = sortedCollection [ ( left + right ) / ] ; do { while ( sortedCollection [ left ] . compareTo ( mid ) > ) { left ++ ; } while ( mid . compareTo ( sortedCollection [ right ] ) > ) { right -- ; } if ( left <= right ) { String tmp = sortedCollection [ left ] ; sortedCollection [ left ] = sortedCollection [ right ] ; sortedCollection [ right ] = tmp ; left ++ ; right -- ; } } while ( left <= right ) ; if ( original_left < right ) { quickSortReverse ( sortedCollection , original_left , right ) ; } if ( left < original_right ) { quickSortReverse ( sortedCollection , left , original_right ) ; } } public static final String concatWith ( String [ ] array , String name , char separator ) { if ( array == null || array . length == ) return name ; if ( name == null || name . length ( ) == ) return concatWith ( array , separator ) ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = , length = array . length ; i < length ; i ++ ) { buffer . append ( array [ i ] ) ; buffer . append ( separator ) ; } buffer . append ( name ) ; return buffer . toString ( ) ; } public static boolean ignore ( String message ) { return message . startsWith ( "" ) || message . startsWith ( "" ) ; } public static boolean isERBLikeFileName ( String name ) { return name . endsWith ( "" ) || name . endsWith ( "" ) ; } public static char [ ] replaceNonRubyCodeWithWhitespace ( String source ) { List < String > code = getRubyCodeChunks ( source ) ; if ( code == null || code . size ( ) == ) { return fillWithWhitespace ( source ) . toCharArray ( ) ; } StringBuilder buffer = new StringBuilder ( ) ; int endOfLastFragment = ; boolean dontIncludeSemicolon = false ; for ( String codeFragment : code ) { int beginningOfCurrentFragment = source . indexOf ( codeFragment , endOfLastFragment ) ; if ( codeFragment . startsWith ( "" ) ) { codeFragment = fillWithWhitespace ( codeFragment ) ; dontIncludeSemicolon = true ; } String portion = source . substring ( endOfLastFragment , beginningOfCurrentFragment ) ; for ( int j = ; j < portion . length ( ) ; j ++ ) { char chr = portion . charAt ( j ) ; if ( Character . isWhitespace ( chr ) ) { buffer . append ( chr ) ; } else { if ( j != && chr == '>' && portion . charAt ( j - ) == '' ) { if ( dontIncludeSemicolon ) { buffer . append ( '' ) ; dontIncludeSemicolon = false ; } else buffer . append ( '' ) ; } else { buffer . append ( '' ) ; } } } buffer . append ( codeFragment ) ; endOfLastFragment = beginningOfCurrentFragment + codeFragment . length ( ) ; } return buffer . toString ( ) . toCharArray ( ) ; } private static String fillWithWhitespace ( String source ) { StringBuilder buffer = new StringBuilder ( ) ; for ( int j = ; j < source . length ( ) ; j ++ ) { char chr = source . charAt ( j ) ; if ( Character . isWhitespace ( chr ) ) { buffer . append ( chr ) ; } else { buffer . append ( '' ) ; } } return buffer . toString ( ) ; } private static List < String > getRubyCodeChunks ( String stringContents ) { List < String > code = new ArrayList < String > ( ) ; String [ ] pieces = stringContents . split ( "" ) ; for ( int i = ; i < pieces . length ; i ++ ) { if ( ( i % ) == ) { code . add ( pieces [ i ] ) ; } } return code ; } public static boolean isValidRubyOrERBScriptName ( String name ) { if ( RubyConventions . validateRubyScriptName ( name ) . getSeverity ( ) != IStatus . ERROR ) return true ; return isERBLikeFileName ( name ) ; } } package org . rubypeople . rdt . internal . core . util ; public final class HashtableOfArrayToObject implements Cloneable { public Object [ ] [ ] keyTable ; public Object [ ] valueTable ; public int elementSize ; int threshold ; public HashtableOfArrayToObject ( ) { this ( ) ; } public HashtableOfArrayToObject ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . keyTable = new Object [ extraRoom ] [ ] ; this . valueTable = new Object [ extraRoom ] ; } public Object clone ( ) throws CloneNotSupportedException { HashtableOfArrayToObject result = ( HashtableOfArrayToObject ) super . clone ( ) ; result . elementSize = this . elementSize ; result . threshold = this . threshold ; int length = this . keyTable . length ; result . keyTable = new Object [ length ] [ ] ; System . arraycopy ( this . keyTable , , result . keyTable , , length ) ; length = this . valueTable . length ; result . valueTable = new Object [ length ] ; System . arraycopy ( this . valueTable , , result . valueTable , , length ) ; return result ; } public boolean containsKey ( Object [ ] key ) { int length = this . keyTable . length ; int index = hashCode ( key ) % length ; int keyLength = key . length ; Object [ ] currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && Util . equalArraysOrNull ( currentKey , key ) ) return true ; if ( ++ index == length ) { index = ; } } return false ; } public Object get ( Object [ ] key ) { int length = this . keyTable . length ; int index = hashCode ( key ) % length ; int keyLength = key . length ; Object [ ] currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && Util . equalArraysOrNull ( currentKey , key ) ) return this . valueTable [ index ] ; if ( ++ index == length ) { index = ; } } return null ; } public Object [ ] getKey ( Object [ ] key , int keyLength ) { int length = this . keyTable . length ; int index = hashCode ( key , keyLength ) % length ; Object [ ] currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && Util . equalArrays ( currentKey , key , keyLength ) ) return currentKey ; if ( ++ index == length ) { index = ; } } return null ; } private int hashCode ( Object [ ] element ) { return hashCode ( element , element . length ) ; } private int hashCode ( Object [ ] element , int length ) { int hash = ; for ( int i = length - ; i >= ; i -- ) hash = Util . combineHashCodes ( hash , element [ i ] . hashCode ( ) ) ; return hash & ; } public Object put ( Object [ ] key , Object value ) { int length = this . keyTable . length ; int index = hashCode ( key ) % length ; int keyLength = key . length ; Object [ ] currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && Util . equalArraysOrNull ( currentKey , key ) ) return this . valueTable [ index ] = value ; if ( ++ index == length ) { index = ; } } this . keyTable [ index ] = key ; this . valueTable [ index ] = value ; if ( ++ this . elementSize > threshold ) rehash ( ) ; return value ; } public Object removeKey ( Object [ ] key ) { int length = this . keyTable . length ; int index = hashCode ( key ) % length ; int keyLength = key . length ; Object [ ] currentKey ; while ( ( currentKey = this . keyTable [ index ] ) != null ) { if ( currentKey . length == keyLength && Util . equalArraysOrNull ( currentKey , key ) ) { Object value = this . valueTable [ index ] ; this . elementSize -- ; this . keyTable [ index ] = null ; this . valueTable [ index ] = null ; rehash ( ) ; return value ; } if ( ++ index == length ) { index = ; } } return null ; } private void rehash ( ) { HashtableOfArrayToObject newHashtable = new HashtableOfArrayToObject ( elementSize * ) ; Object [ ] currentKey ; for ( int i = this . keyTable . length ; -- i >= ; ) if ( ( currentKey = this . keyTable [ i ] ) != null ) newHashtable . put ( currentKey , this . valueTable [ i ] ) ; this . keyTable = newHashtable . keyTable ; this . valueTable = newHashtable . valueTable ; this . threshold = newHashtable . threshold ; } public int size ( ) { return elementSize ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; Object [ ] element ; for ( int i = , length = this . keyTable . length ; i < length ; i ++ ) if ( ( element = this . keyTable [ i ] ) != null ) { buffer . append ( '' ) ; for ( int j = , length2 = element . length ; j < length2 ; j ++ ) { buffer . append ( element [ j ] ) ; if ( j != length2 - ) buffer . append ( "" ) ; } buffer . append ( "" ) ; buffer . append ( this . valueTable [ i ] ) ; if ( i != length - ) buffer . append ( '' ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core . util ; public final class SimpleWordSet { public char [ ] [ ] words ; public int elementSize ; public int threshold ; public SimpleWordSet ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . words = new char [ extraRoom ] [ ] ; } public char [ ] add ( char [ ] word ) { int length = this . words . length ; int index = CharOperation . hashCode ( word ) % length ; char [ ] current ; while ( ( current = words [ index ] ) != null ) { if ( CharOperation . equals ( current , word ) ) return current ; if ( ++ index == length ) index = ; } words [ index ] = word ; if ( ++ elementSize > threshold ) rehash ( ) ; return word ; } public boolean includes ( char [ ] word ) { int length = this . words . length ; int index = CharOperation . hashCode ( word ) % length ; char [ ] current ; while ( ( current = words [ index ] ) != null ) { if ( CharOperation . equals ( current , word ) ) return true ; if ( ++ index == length ) index = ; } return false ; } private void rehash ( ) { SimpleWordSet newSet = new SimpleWordSet ( elementSize * ) ; char [ ] current ; for ( int i = words . length ; -- i >= ; ) if ( ( current = words [ i ] ) != null ) newSet . add ( current ) ; this . words = newSet . words ; this . elementSize = newSet . elementSize ; this . threshold = newSet . threshold ; } } package org . rubypeople . rdt . internal . core . util ; import java . lang . ref . ReferenceQueue ; import java . lang . ref . WeakReference ; public class WeakHashSet { public static class HashableWeakReference extends WeakReference { public int hashCode ; public HashableWeakReference ( Object referent , ReferenceQueue queue ) { super ( referent , queue ) ; this . hashCode = referent . hashCode ( ) ; } public boolean equals ( Object obj ) { if ( ! ( obj instanceof HashableWeakReference ) ) return false ; Object referent = get ( ) ; Object other = ( ( HashableWeakReference ) obj ) . get ( ) ; if ( referent == null ) return other == null ; return referent . equals ( other ) ; } public int hashCode ( ) { return this . hashCode ; } public String toString ( ) { Object referent = get ( ) ; if ( referent == null ) return "" + this . hashCode + "" ; return "" + this . hashCode + "" + referent . toString ( ) ; } } HashableWeakReference [ ] values ; public int elementSize ; int threshold ; ReferenceQueue referenceQueue = new ReferenceQueue ( ) ; public WeakHashSet ( ) { this ( ) ; } public WeakHashSet ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . values = new HashableWeakReference [ extraRoom ] ; } public Object add ( Object obj ) { cleanupGarbageCollectedValues ( ) ; int valuesLength = this . values . length , index = ( obj . hashCode ( ) & ) % valuesLength ; HashableWeakReference currentValue ; while ( ( currentValue = this . values [ index ] ) != null ) { Object referent ; if ( obj . equals ( referent = currentValue . get ( ) ) ) { return referent ; } if ( ++ index == valuesLength ) { index = ; } } this . values [ index ] = new HashableWeakReference ( obj , this . referenceQueue ) ; if ( ++ this . elementSize > this . threshold ) rehash ( ) ; return obj ; } private void addValue ( HashableWeakReference value ) { Object obj = value . get ( ) ; if ( obj == null ) return ; int valuesLength = this . values . length ; int index = ( value . hashCode & ) % valuesLength ; HashableWeakReference currentValue ; while ( ( currentValue = this . values [ index ] ) != null ) { if ( obj . equals ( currentValue . get ( ) ) ) { return ; } if ( ++ index == valuesLength ) { index = ; } } this . values [ index ] = value ; if ( ++ this . elementSize > this . threshold ) rehash ( ) ; } private void cleanupGarbageCollectedValues ( ) { HashableWeakReference toBeRemoved ; while ( ( toBeRemoved = ( HashableWeakReference ) this . referenceQueue . poll ( ) ) != null ) { int hashCode = toBeRemoved . hashCode ; int valuesLength = this . values . length ; int index = ( hashCode & ) % valuesLength ; HashableWeakReference currentValue ; while ( ( currentValue = this . values [ index ] ) != null ) { if ( currentValue == toBeRemoved ) { int sameHash = index ; int current ; while ( ( currentValue = this . values [ current = ( sameHash + ) % valuesLength ] ) != null && currentValue . hashCode == hashCode ) sameHash = current ; this . values [ index ] = this . values [ sameHash ] ; this . values [ sameHash ] = null ; this . elementSize -- ; break ; } if ( ++ index == valuesLength ) { index = ; } } } } public boolean contains ( Object obj ) { return get ( obj ) != null ; } public Object get ( Object obj ) { cleanupGarbageCollectedValues ( ) ; int valuesLength = this . values . length ; int index = ( obj . hashCode ( ) & ) % valuesLength ; HashableWeakReference currentValue ; while ( ( currentValue = this . values [ index ] ) != null ) { Object referent ; if ( obj . equals ( referent = currentValue . get ( ) ) ) { return referent ; } if ( ++ index == valuesLength ) { index = ; } } return null ; } private void rehash ( ) { WeakHashSet newHashSet = new WeakHashSet ( this . elementSize * ) ; newHashSet . referenceQueue = this . referenceQueue ; HashableWeakReference currentValue ; for ( int i = , length = this . values . length ; i < length ; i ++ ) if ( ( currentValue = this . values [ i ] ) != null ) newHashSet . addValue ( currentValue ) ; this . values = newHashSet . values ; this . threshold = newHashSet . threshold ; this . elementSize = newHashSet . elementSize ; } public Object remove ( Object obj ) { cleanupGarbageCollectedValues ( ) ; int valuesLength = this . values . length ; int index = ( obj . hashCode ( ) & ) % valuesLength ; HashableWeakReference currentValue ; while ( ( currentValue = this . values [ index ] ) != null ) { Object referent ; if ( obj . equals ( referent = currentValue . get ( ) ) ) { this . elementSize -- ; this . values [ index ] = null ; rehash ( ) ; return referent ; } if ( ++ index == valuesLength ) { index = ; } } return null ; } public int size ( ) { return this . elementSize ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( "" ) ; for ( int i = , length = this . values . length ; i < length ; i ++ ) { HashableWeakReference value = this . values [ i ] ; if ( value != null ) { Object ref = value . get ( ) ; if ( ref != null ) { buffer . append ( ref . toString ( ) ) ; buffer . append ( "" ) ; } } } buffer . append ( "" ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core . util ; import java . text . MessageFormat ; import org . eclipse . osgi . util . NLS ; public final class Messages extends NLS { private static final String BUNDLE_NAME = "" ; private Messages ( ) { } public static String element_doesNotExist ; public static String element_notOnClasspath ; public static String element_invalidClassFileName ; public static String element_reconciling ; public static String element_attachingSource ; public static String element_invalidResourceForProject ; public static String element_nullName ; public static String element_nullType ; public static String element_illegalParent ; public static String operation_needElements ; public static String operation_needName ; public static String operation_needPath ; public static String operation_needAbsolutePath ; public static String operation_needString ; public static String operation_notSupported ; public static String operation_cancelled ; public static String operation_nullContainer ; public static String operation_nullName ; public static String operation_copyElementProgress ; public static String operation_moveElementProgress ; public static String operation_renameElementProgress ; public static String operation_copyResourceProgress ; public static String operation_moveResourceProgress ; public static String operation_renameResourceProgress ; public static String operation_createUnitProgress ; public static String operation_createFieldProgress ; public static String operation_createImportsProgress ; public static String operation_createInitializerProgress ; public static String operation_createMethodProgress ; public static String operation_createPackageProgress ; public static String operation_createPackageFragmentProgress ; public static String operation_createTypeProgress ; public static String operation_deleteElementProgress ; public static String operation_deleteResourceProgress ; public static String operation_cannotRenameDefaultPackage ; public static String operation_pathOutsideProject ; public static String operation_sortelements ; public static String workingCopy_commit ; public static String build_cannotSaveState ; public static String build_cannotSaveStates ; public static String build_initializationError ; public static String build_serializationError ; public static String status_cannotUseDeviceOnPath ; public static String status_coreException ; public static String status_evaluationError ; public static String status_JDOMError ; public static String status_IOException ; public static String status_indexOutOfBounds ; public static String status_invalidContents ; public static String status_invalidDestination ; public static String status_invalidName ; public static String status_invalidPackage ; public static String status_invalidPath ; public static String status_invalidProject ; public static String status_invalidResource ; public static String status_invalidResourceType ; public static String status_invalidSibling ; public static String status_nameCollision ; public static String status_noLocalContents ; public static String status_OK ; public static String status_readOnly ; public static String status_targetException ; public static String status_updateConflict ; public static String classpath_buildPath ; public static String classpath_cannotNestEntryInEntry ; public static String classpath_cannotNestEntryInLibrary ; public static String classpath_cannotNestEntryInOutput ; public static String classpath_cannotNestOutputInEntry ; public static String classpath_cannotNestOutputInOutput ; public static String classpath_cannotReadClasspathFile ; public static String classpath_cannotReferToItself ; public static String classpath_cannotUseDistinctSourceFolderAsOutput ; public static String classpath_cannotUseLibraryAsOutput ; public static String classpath_closedProject ; public static String classpath_couldNotWriteClasspathFile ; public static String classpath_cycle ; public static String classpath_duplicateEntryPath ; public static String classpath_illegalContainerPath ; public static String classpath_illegalEntryInClasspathFile ; public static String classpath_illegalLibraryPath ; public static String classpath_illegalLibraryArchive ; public static String classpath_illegalExternalFolder ; public static String classpath_illegalProjectPath ; public static String classpath_illegalSourceFolderPath ; public static String classpath_illegalVariablePath ; public static String classpath_invalidClasspathInClasspathFile ; public static String classpath_invalidContainer ; public static String classpath_mustEndWithSlash ; public static String classpath_unboundContainerPath ; public static String classpath_unboundLibrary ; public static String classpath_unboundProject ; public static String classpath_settingOutputLocationProgress ; public static String classpath_settingProgress ; public static String classpath_unboundSourceAttachment ; public static String classpath_unboundSourceFolder ; public static String classpath_unboundVariablePath ; public static String classpath_unknownKind ; public static String classpath_xmlFormatError ; public static String classpath_disabledInclusionExclusionPatterns ; public static String classpath_disabledMultipleOutputLocations ; public static String classpath_incompatibleLibraryJDKLevel ; public static String classpath_duplicateEntryExtraAttribute ; public static String file_notFound ; public static String file_badFormat ; public static String path_nullPath ; public static String path_mustBeAbsolute ; public static String cache_invalidLoadFactor ; public static String savedState_jobName ; public static String javamodel_initialization ; public static String restrictedAccess_project ; public static String restrictedAccess_library ; public static String convention_unit_nullName ; public static String convention_unit_notRubyName ; public static String convention_unit_notERBName ; public static String convention_classFile_nullName ; public static String convention_classFile_notClassFileName ; public static String convention_illegalIdentifier ; public static String convention_import_nullImport ; public static String convention_import_unqualifiedImport ; public static String convention_type_nullName ; public static String convention_type_nameWithBlanks ; public static String convention_type_dollarName ; public static String convention_type_lowercaseName ; public static String convention_type_invalidName ; public static String convention_package_nullName ; public static String convention_package_emptyName ; public static String convention_package_dotName ; public static String convention_package_nameWithBlanks ; public static String convention_package_consecutiveDotsName ; public static String convention_package_uppercaseName ; public static String build_saveStateProgress ; public static String build_saveStateComplete ; public static String project_has_no_ruby_nature ; public static String manager_filesToIndex ; public static String manager_indexingInProgress ; public static String process_name ; public static String exception_wrongFormat ; public static String engine_searching_matching ; public static String engine_searching_indexing ; public static String engine_searching ; public static String hierarchy_creating ; public static String hierarchy_creatingOnType ; public static String hierarchy_nullRegion ; static { NLS . initializeMessages ( BUNDLE_NAME , Messages . class ) ; } public static String bind ( String message ) { return bind ( message , null ) ; } public static String bind ( String message , Object binding ) { return bind ( message , new Object [ ] { binding } ) ; } public static String bind ( String message , Object binding1 , Object binding2 ) { return bind ( message , new Object [ ] { binding1 , binding2 } ) ; } public static String bind ( String message , Object [ ] bindings ) { return format ( message , bindings ) ; } public static String format ( String message , Object [ ] objects ) { return MessageFormat . format ( message , objects ) ; } public static String format ( String message , String binding ) { return MessageFormat . format ( message , binding ) ; } } package org . rubypeople . rdt . internal . core . util ; import java . util . Map ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . TextEdit ; import org . eclipse . text . edits . TextEditGroup ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; public class ASTRewrite { private Node ast ; private TextEdit currentEdit ; private String lineDelim ; protected ASTRewrite ( Node ast , IDocument document ) { this . ast = ast ; TextEdit edit = new MultiTextEdit ( ) ; this . lineDelim = TextUtilities . getDefaultLineDelimiter ( document ) ; this . currentEdit = edit ; } public static ASTRewrite create ( Node ast , IDocument document ) { return new ASTRewrite ( ast , document ) ; } public TextEdit rewriteAST ( IDocument document , Map options ) { return currentEdit ; } final void doTextInsert ( int offset , String insertString ) { if ( insertString . length ( ) > ) { if ( ! insertString . startsWith ( getLineDelimiter ( ) ) ) { TextEdit edit = new InsertEdit ( offset , getLineDelimiter ( ) ) ; addEdit ( edit ) ; } TextEdit edit = new InsertEdit ( offset , insertString ) ; addEdit ( edit ) ; } } private String getLineDelimiter ( ) { return lineDelim ; } public void insertBefore ( String source , Node insert , Node element , TextEditGroup group ) { ISourcePosition pos = element . getPosition ( ) ; doTextInsert ( pos . getStartOffset ( ) , source ) ; } final void addEdit ( TextEdit edit ) { this . currentEdit . addChild ( edit ) ; } public void insertAfter ( String source , Node insert , Node element , TextEditGroup group ) { ISourcePosition pos = element . getPosition ( ) ; doTextInsert ( pos . getEndOffset ( ) + , source ) ; } public void insertLast ( String source , Node insert , TextEditGroup group ) { ISourcePosition pos = ast . getPosition ( ) ; doTextInsert ( pos . getEndOffset ( ) - "" . length ( ) , source ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . RubyModelException ; public class DiscardWorkingCopyOperation extends RubyModelOperation { public DiscardWorkingCopyOperation ( RubyScript workingCopy ) { super ( new IRubyElement [ ] { workingCopy } ) ; } protected void executeOperation ( ) throws RubyModelException { RubyScript workingCopy = getWorkingCopy ( ) ; int useCount = RubyModelManager . getRubyModelManager ( ) . discardPerWorkingCopyInfo ( workingCopy ) ; if ( useCount == ) { if ( ! workingCopy . isPrimary ( ) ) { RubyElementDelta delta = new RubyElementDelta ( this . getRubyModel ( ) ) ; delta . removed ( workingCopy ) ; addDelta ( delta ) ; removeReconcileDelta ( workingCopy ) ; } else { if ( workingCopy . getResource ( ) . isAccessible ( ) ) { RubyElementDelta delta = new RubyElementDelta ( this . getRubyModel ( ) ) ; delta . changed ( workingCopy , IRubyElementDelta . F_PRIMARY_WORKING_COPY ) ; addDelta ( delta ) ; } else { RubyElementDelta delta = new RubyElementDelta ( this . getRubyModel ( ) ) ; delta . removed ( workingCopy , IRubyElementDelta . F_PRIMARY_WORKING_COPY ) ; addDelta ( delta ) ; } } } } protected RubyScript getWorkingCopy ( ) { return ( RubyScript ) getElementToProcess ( ) ; } public boolean isReadOnly ( ) { return true ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import org . jruby . ast . AliasNode ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . AssignableNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DStrNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . SplatNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . YieldNode ; import org . jruby . runtime . Visibility ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor . FieldInfo ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor . MethodInfo ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor . TypeInfo ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; public class SourceElementParser extends InOrderVisitor { private static final String MODULE_FUNCTION = "" ; private static final String PROTECTED = "" ; private static final String PRIVATE = "" ; private static final String PUBLIC = "" ; private static final String INCLUDE = "" ; private static final String LOAD = "" ; private static final String REQUIRE = "" ; private static final String ALIAS = "" ; private static final String MODULE = "" ; private static final String CONSTRUCTOR_NAME = "" ; private static final String OBJECT = "" ; private List < Visibility > visibilities = new ArrayList < Visibility > ( ) ; private boolean inSingletonClass ; public ISourceElementRequestor requestor ; private boolean inModuleFunction ; private char [ ] source ; private String typeName ; public SourceElementParser ( ISourceElementRequestor requestor ) { super ( ) ; this . requestor = requestor ; } public Object visitClassNode ( ClassNode iVisited ) { pushVisibility ( Visibility . PUBLIC ) ; TypeInfo typeInfo = new TypeInfo ( ) ; typeInfo . name = ASTUtil . getFullyQualifiedName ( iVisited . getCPath ( ) ) ; typeInfo . declarationStart = iVisited . getPosition ( ) . getStartOffset ( ) ; typeInfo . nameSourceStart = iVisited . getCPath ( ) . getPosition ( ) . getStartOffset ( ) ; typeInfo . nameSourceEnd = iVisited . getCPath ( ) . getPosition ( ) . getEndOffset ( ) - ; if ( ! typeInfo . name . equals ( OBJECT ) ) { String superClass = ASTUtil . getSuperClassName ( iVisited . getSuperNode ( ) ) ; typeInfo . superclass = superClass ; } typeInfo . isModule = false ; typeInfo . modules = new String [ ] ; typeInfo . secondary = false ; typeName = typeInfo . name ; requestor . enterType ( typeInfo ) ; Object ins = super . visitClassNode ( iVisited ) ; popVisibility ( ) ; requestor . exitType ( iVisited . getPosition ( ) . getEndOffset ( ) - ) ; return ins ; } @ Override public Object visitConstNode ( ConstNode iVisited ) { requestor . acceptTypeReference ( iVisited . getName ( ) , iVisited . getPosition ( ) . getStartOffset ( ) , iVisited . getPosition ( ) . getEndOffset ( ) ) ; return super . visitConstNode ( iVisited ) ; } @ Override public Object visitModuleNode ( ModuleNode iVisited ) { pushVisibility ( Visibility . PUBLIC ) ; TypeInfo typeInfo = new TypeInfo ( ) ; typeInfo . name = ASTUtil . getFullyQualifiedName ( iVisited . getCPath ( ) ) ; typeInfo . declarationStart = iVisited . getPosition ( ) . getStartOffset ( ) ; typeInfo . nameSourceStart = iVisited . getCPath ( ) . getPosition ( ) . getStartOffset ( ) ; typeInfo . nameSourceEnd = iVisited . getCPath ( ) . getPosition ( ) . getEndOffset ( ) - ; typeInfo . superclass = MODULE ; typeInfo . isModule = true ; typeInfo . modules = new String [ ] ; typeInfo . secondary = false ; typeName = typeInfo . name ; requestor . enterType ( typeInfo ) ; Object ins = super . visitModuleNode ( iVisited ) ; popVisibility ( ) ; requestor . exitType ( iVisited . getPosition ( ) . getEndOffset ( ) - ) ; inModuleFunction = false ; return ins ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { Visibility visibility = getCurrentVisibility ( ) ; MethodInfo methodInfo = new MethodInfo ( ) ; methodInfo . declarationStart = iVisited . getPosition ( ) . getStartOffset ( ) ; methodInfo . name = iVisited . getName ( ) ; methodInfo . nameSourceStart = iVisited . getNameNode ( ) . getPosition ( ) . getStartOffset ( ) ; methodInfo . nameSourceEnd = iVisited . getNameNode ( ) . getPosition ( ) . getEndOffset ( ) - ; if ( methodInfo . name . equals ( CONSTRUCTOR_NAME ) ) { visibility = Visibility . PROTECTED ; methodInfo . isConstructor = true ; } else { methodInfo . isConstructor = false ; } methodInfo . isClassLevel = inSingletonClass || inModuleFunction ; methodInfo . visibility = convertVisibility ( visibility ) ; methodInfo . parameterNames = ASTUtil . getArgs ( iVisited . getArgsNode ( ) , iVisited . getScope ( ) ) ; if ( methodInfo . isConstructor ) { requestor . enterConstructor ( methodInfo ) ; } else { requestor . enterMethod ( methodInfo ) ; } Object ins = super . visitDefnNode ( iVisited ) ; int end = iVisited . getPosition ( ) . getEndOffset ( ) - ; if ( methodInfo . isConstructor ) { requestor . exitConstructor ( end ) ; } else { requestor . exitMethod ( end ) ; } return ins ; } @ Override public Object visitArgsNode ( ArgsNode iVisited ) { ListNode list = iVisited . getArgs ( ) ; if ( list != null ) { for ( int i = ; i < list . size ( ) ; i ++ ) { Node arg = list . get ( i ) ; FieldInfo field = new FieldInfo ( ) ; field . declarationStart = arg . getPosition ( ) . getStartOffset ( ) ; field . nameSourceStart = arg . getPosition ( ) . getStartOffset ( ) ; String name = ASTUtil . getNameReflectively ( arg ) ; field . nameSourceEnd = arg . getPosition ( ) . getStartOffset ( ) + name . length ( ) - ; field . name = name ; requestor . enterField ( field ) ; requestor . exitField ( arg . getPosition ( ) . getEndOffset ( ) - ) ; } } ArgumentNode arg = iVisited . getRestArgNode ( ) ; if ( arg != null ) { FieldInfo field = new FieldInfo ( ) ; field . declarationStart = arg . getPosition ( ) . getStartOffset ( ) + ; field . nameSourceStart = arg . getPosition ( ) . getStartOffset ( ) + ; String name = ASTUtil . getNameReflectively ( arg ) ; field . nameSourceEnd = arg . getPosition ( ) . getStartOffset ( ) + name . length ( ) ; field . name = name ; requestor . enterField ( field ) ; requestor . exitField ( arg . getPosition ( ) . getEndOffset ( ) ) ; } return super . visitArgsNode ( iVisited ) ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { MethodInfo methodInfo = new MethodInfo ( ) ; methodInfo . declarationStart = iVisited . getPosition ( ) . getStartOffset ( ) ; methodInfo . name = iVisited . getName ( ) ; methodInfo . nameSourceStart = iVisited . getNameNode ( ) . getPosition ( ) . getStartOffset ( ) ; methodInfo . nameSourceEnd = iVisited . getNameNode ( ) . getPosition ( ) . getEndOffset ( ) - ; methodInfo . isConstructor = false ; methodInfo . isClassLevel = true ; methodInfo . visibility = convertVisibility ( getCurrentVisibility ( ) ) ; methodInfo . parameterNames = ASTUtil . getArgs ( iVisited . getArgsNode ( ) , iVisited . getScope ( ) ) ; requestor . enterMethod ( methodInfo ) ; Object ins = super . visitDefsNode ( iVisited ) ; requestor . exitMethod ( iVisited . getPosition ( ) . getEndOffset ( ) - ) ; return ins ; } private int convertVisibility ( Visibility visibility ) { if ( visibility == Visibility . PUBLIC ) return IMethod . PUBLIC ; if ( visibility == Visibility . PROTECTED ) return IMethod . PROTECTED ; return IMethod . PRIVATE ; } @ Override public Object visitRootNode ( RootNode iVisited ) { requestor . enterScript ( ) ; pushVisibility ( Visibility . PUBLIC ) ; Object ins = super . visitRootNode ( iVisited ) ; popVisibility ( ) ; requestor . exitScript ( iVisited . getPosition ( ) . getEndOffset ( ) ) ; return ins ; } private void popVisibility ( ) { visibilities . remove ( visibilities . size ( ) - ) ; } @ Override public Object visitConstDeclNode ( ConstDeclNode iVisited ) { FieldInfo field = createFieldInfo ( iVisited ) ; field . name = iVisited . getName ( ) ; requestor . enterField ( field ) ; exitField ( iVisited ) ; return super . visitConstDeclNode ( iVisited ) ; } public Object visitClassVarAsgnNode ( ClassVarAsgnNode iVisited ) { FieldInfo field = createFieldInfo ( iVisited ) ; field . name = iVisited . getName ( ) ; requestor . enterField ( field ) ; exitField ( iVisited ) ; return super . visitClassVarAsgnNode ( iVisited ) ; } @ Override public Object visitClassVarDeclNode ( ClassVarDeclNode iVisited ) { FieldInfo field = createFieldInfo ( iVisited ) ; field . name = iVisited . getName ( ) ; requestor . enterField ( field ) ; exitField ( iVisited ) ; return super . visitClassVarDeclNode ( iVisited ) ; } @ Override public Object visitClassVarNode ( ClassVarNode iVisited ) { requestor . acceptFieldReference ( iVisited . getName ( ) , iVisited . getPosition ( ) . getStartOffset ( ) ) ; return super . visitClassVarNode ( iVisited ) ; } public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { FieldInfo field = createFieldInfo ( iVisited ) ; field . name = iVisited . getName ( ) ; requestor . enterField ( field ) ; exitField ( iVisited ) ; return super . visitLocalAsgnNode ( iVisited ) ; } @ Override public Object visitInstAsgnNode ( InstAsgnNode iVisited ) { FieldInfo field = createFieldInfo ( iVisited ) ; field . name = iVisited . getName ( ) ; requestor . enterField ( field ) ; exitField ( iVisited ) ; return super . visitInstAsgnNode ( iVisited ) ; } @ Override public Object visitInstVarNode ( InstVarNode iVisited ) { requestor . acceptFieldReference ( iVisited . getName ( ) , iVisited . getPosition ( ) . getStartOffset ( ) ) ; return super . visitInstVarNode ( iVisited ) ; } @ Override public Object visitGlobalAsgnNode ( GlobalAsgnNode iVisited ) { FieldInfo field = createFieldInfo ( iVisited ) ; field . name = iVisited . getName ( ) ; requestor . enterField ( field ) ; exitField ( iVisited ) ; return super . visitGlobalAsgnNode ( iVisited ) ; } @ Override public Object visitGlobalVarNode ( GlobalVarNode iVisited ) { requestor . acceptFieldReference ( iVisited . getName ( ) , iVisited . getPosition ( ) . getStartOffset ( ) ) ; return super . visitGlobalVarNode ( iVisited ) ; } private void exitField ( AssignableNode iVisited ) { requestor . exitField ( iVisited . getPosition ( ) . getEndOffset ( ) - ) ; } private FieldInfo createFieldInfo ( AssignableNode iVisited ) { FieldInfo field = new FieldInfo ( ) ; field . declarationStart = iVisited . getPosition ( ) . getStartOffset ( ) ; field . nameSourceStart = iVisited . getPosition ( ) . getStartOffset ( ) ; String name = ASTUtil . getNameReflectively ( iVisited ) ; field . nameSourceEnd = iVisited . getPosition ( ) . getStartOffset ( ) + name . length ( ) - ; return field ; } public Object visitIterNode ( IterNode iVisited ) { requestor . acceptBlock ( iVisited . getPosition ( ) . getStartOffset ( ) , iVisited . getPosition ( ) . getEndOffset ( ) - ) ; return super . visitIterNode ( iVisited ) ; } @ Override public Object visitDAsgnNode ( DAsgnNode iVisited ) { FieldInfo field = createFieldInfo ( iVisited ) ; field . name = iVisited . getName ( ) ; field . isDynamic = true ; requestor . enterField ( field ) ; exitField ( iVisited ) ; return super . visitDAsgnNode ( iVisited ) ; } @ Override public Object visitSClassNode ( SClassNode iVisited ) { Node receiver = iVisited . getReceiverNode ( ) ; if ( receiver instanceof SelfNode ) { inSingletonClass = true ; } pushVisibility ( Visibility . PUBLIC ) ; Object ins = super . visitSClassNode ( iVisited ) ; popVisibility ( ) ; if ( receiver instanceof SelfNode ) { inSingletonClass = false ; } return ins ; } public Object visitFCallNode ( FCallNode iVisited ) { String name = iVisited . getName ( ) ; List < String > arguments = getArgumentsFromFunctionCall ( iVisited ) ; if ( name . equals ( REQUIRE ) || name . equals ( LOAD ) ) { addImport ( iVisited ) ; } else if ( name . equals ( INCLUDE ) ) { includeModule ( iVisited ) ; } if ( name . equals ( PUBLIC ) ) { for ( String methodName : arguments ) { requestor . acceptMethodVisibilityChange ( methodName , convertVisibility ( Visibility . PUBLIC ) ) ; } } else if ( name . equals ( PRIVATE ) ) { for ( String methodName : arguments ) { requestor . acceptMethodVisibilityChange ( methodName , convertVisibility ( Visibility . PRIVATE ) ) ; } } else if ( name . equals ( PROTECTED ) ) { for ( String methodName : arguments ) { requestor . acceptMethodVisibilityChange ( methodName , convertVisibility ( Visibility . PROTECTED ) ) ; } } else if ( name . equals ( MODULE_FUNCTION ) ) { for ( String methodName : arguments ) { requestor . acceptModuleFunction ( methodName ) ; } } if ( name . equals ( "" ) ) { String newName = arguments . get ( ) . substring ( ) ; int nameStart = iVisited . getPosition ( ) . getStartOffset ( ) + "" . length ( ) ; addAliasMethod ( newName , iVisited . getPosition ( ) . getStartOffset ( ) , iVisited . getPosition ( ) . getEndOffset ( ) , nameStart ) ; } if ( name . equals ( "" ) ) { List < Node > nodes = ASTUtil . getArgumentNodesFromFunctionCall ( iVisited ) ; generateReadMethod ( arguments . get ( ) , nodes . get ( ) ) ; if ( arguments . size ( ) == && arguments . get ( ) . equals ( "" ) ) { Node node = nodes . get ( ) ; int start = node . getPosition ( ) . getEndOffset ( ) + ; generateWriteMethod ( arguments . get ( ) , start , start + arguments . get ( ) . length ( ) - ) ; } } if ( name . equals ( "" ) || name . equals ( "" ) ) { List < Node > nodes = ASTUtil . getArgumentNodesFromFunctionCall ( iVisited ) ; for ( int i = ; i < arguments . size ( ) ; i ++ ) { generateReadMethod ( arguments . get ( i ) , nodes . get ( i ) ) ; } } if ( name . equals ( "" ) || name . equals ( "" ) ) { List < Node > nodes = ASTUtil . getArgumentNodesFromFunctionCall ( iVisited ) ; for ( int i = ; i < arguments . size ( ) ; i ++ ) { generateWriteMethod ( arguments . get ( i ) , nodes . get ( i ) ) ; } } if ( name . equals ( "" ) || name . equals ( "" ) || name . equals ( "" ) || name . equals ( "" ) ) { List < Node > nodes = ASTUtil . getArgumentNodesFromFunctionCall ( iVisited ) ; for ( int i = ; i < arguments . size ( ) ; i ++ ) { FieldInfo field = new FieldInfo ( ) ; Node node = nodes . get ( i ) ; field . declarationStart = node . getPosition ( ) . getStartOffset ( ) + ; field . name = "" + arguments . get ( i ) ; field . nameSourceStart = node . getPosition ( ) . getStartOffset ( ) + ; field . nameSourceEnd = node . getPosition ( ) . getEndOffset ( ) - ; requestor . enterField ( field ) ; requestor . exitField ( node . getPosition ( ) . getEndOffset ( ) - ) ; } } requestor . acceptMethodReference ( name , arguments . size ( ) , iVisited . getPosition ( ) . getStartOffset ( ) ) ; return super . visitFCallNode ( iVisited ) ; } private void addAliasMethod ( String name , int start , int end , int nameStart ) { MethodInfo method = new MethodInfo ( ) ; Visibility visibility = getCurrentVisibility ( ) ; if ( name . equals ( CONSTRUCTOR_NAME ) ) { visibility = Visibility . PROTECTED ; method . isConstructor = true ; } else { method . isConstructor = false ; } method . declarationStart = start ; method . isClassLevel = inSingletonClass ; method . name = name ; method . visibility = convertVisibility ( visibility ) ; method . nameSourceStart = nameStart ; method . nameSourceEnd = nameStart + name . length ( ) - ; method . parameterNames = new String [ ] ; requestor . enterMethod ( method ) ; requestor . exitMethod ( end ) ; } private void generateWriteMethod ( String argument , Node node ) { generateWriteMethod ( argument , node . getPosition ( ) . getStartOffset ( ) , node . getPosition ( ) . getEndOffset ( ) - ) ; } private void generateWriteMethod ( String argument , int start , int end ) { if ( argument . startsWith ( "" ) ) { argument = argument . substring ( ) ; } MethodInfo info = new MethodInfo ( ) ; info . declarationStart = start ; info . isClassLevel = false ; info . isConstructor = false ; info . name = argument + "" ; info . nameSourceStart = start ; info . nameSourceEnd = end ; info . visibility = IMethod . PUBLIC ; info . parameterNames = new String [ ] { "" } ; requestor . enterMethod ( info ) ; requestor . exitMethod ( end ) ; } private void generateReadMethod ( String argument , Node node ) { if ( argument . startsWith ( "" ) ) { argument = argument . substring ( ) ; } MethodInfo info = new MethodInfo ( ) ; info . declarationStart = node . getPosition ( ) . getStartOffset ( ) ; info . isClassLevel = false ; info . isConstructor = false ; info . name = argument ; info . nameSourceStart = node . getPosition ( ) . getStartOffset ( ) ; info . nameSourceEnd = node . getPosition ( ) . getEndOffset ( ) - ; info . visibility = IMethod . PUBLIC ; info . parameterNames = new String [ ] ; requestor . enterMethod ( info ) ; requestor . exitMethod ( node . getPosition ( ) . getEndOffset ( ) - ) ; } private void addImport ( FCallNode iVisited ) { ArrayNode node = ( ArrayNode ) iVisited . getArgsNode ( ) ; String arg = getString ( node ) ; if ( arg != null ) { requestor . acceptImport ( arg , iVisited . getPosition ( ) . getStartOffset ( ) , iVisited . getPosition ( ) . getEndOffset ( ) ) ; } } private String getString ( ArrayNode node ) { Object tmp = node . childNodes ( ) . iterator ( ) . next ( ) ; if ( tmp instanceof DStrNode ) { DStrNode dstrNode = ( DStrNode ) tmp ; tmp = dstrNode . childNodes ( ) . iterator ( ) . next ( ) ; } if ( tmp instanceof StrNode ) { StrNode strNode = ( StrNode ) tmp ; return strNode . getValue ( ) . toString ( ) ; } return null ; } private void includeModule ( FCallNode iVisited ) { List < String > mixins = new LinkedList < String > ( ) ; Node argsNode = iVisited . getArgsNode ( ) ; Iterator iter = null ; if ( argsNode instanceof SplatNode ) { SplatNode splat = ( SplatNode ) argsNode ; iter = splat . childNodes ( ) . iterator ( ) ; } else if ( argsNode instanceof ArrayNode ) { ArrayNode arrayNode = ( ArrayNode ) iVisited . getArgsNode ( ) ; iter = arrayNode . childNodes ( ) . iterator ( ) ; } for ( ; iter . hasNext ( ) ; ) { Node mixinNameNode = ( Node ) iter . next ( ) ; if ( mixinNameNode instanceof StrNode ) { mixins . add ( ( ( StrNode ) mixinNameNode ) . getValue ( ) . toString ( ) ) ; } if ( mixinNameNode instanceof DStrNode ) { Node next = ( Node ) ( ( DStrNode ) mixinNameNode ) . childNodes ( ) . iterator ( ) . next ( ) ; if ( next instanceof StrNode ) { mixins . add ( ( ( StrNode ) next ) . getValue ( ) . toString ( ) ) ; } } if ( mixinNameNode instanceof ConstNode ) { mixins . add ( ( ( ConstNode ) mixinNameNode ) . getName ( ) ) ; } if ( mixinNameNode instanceof Colon2Node ) { mixins . add ( ASTUtil . getFullyQualifiedName ( ( Colon2Node ) mixinNameNode ) ) ; } } for ( String string : mixins ) { requestor . acceptMixin ( string ) ; } } public Object visitVCallNode ( VCallNode iVisited ) { String functionName = iVisited . getName ( ) ; if ( functionName . equals ( PUBLIC ) ) { setVisibility ( Visibility . PUBLIC ) ; } else if ( functionName . equals ( PRIVATE ) ) { setVisibility ( Visibility . PRIVATE ) ; } else if ( functionName . equals ( PROTECTED ) ) { setVisibility ( Visibility . PROTECTED ) ; } else if ( functionName . equals ( MODULE_FUNCTION ) ) { inModuleFunction = true ; } requestor . acceptMethodReference ( functionName , , iVisited . getPosition ( ) . getStartOffset ( ) ) ; return super . visitVCallNode ( iVisited ) ; } private void setVisibility ( Visibility visibility ) { popVisibility ( ) ; pushVisibility ( visibility ) ; } private void pushVisibility ( Visibility visibility ) { visibilities . add ( visibility ) ; } @ Override public Object visitCallNode ( CallNode iVisited ) { String name = iVisited . getName ( ) ; List < String > arguments = getArgumentsFromFunctionCall ( iVisited ) ; if ( name . equals ( PUBLIC ) ) { for ( String methodName : arguments ) { requestor . acceptMethodVisibilityChange ( methodName , convertVisibility ( Visibility . PUBLIC ) ) ; } } else if ( name . equals ( PRIVATE ) ) { for ( String methodName : arguments ) { requestor . acceptMethodVisibilityChange ( methodName , convertVisibility ( Visibility . PRIVATE ) ) ; } } else if ( name . equals ( PROTECTED ) ) { for ( String methodName : arguments ) { requestor . acceptMethodVisibilityChange ( methodName , convertVisibility ( Visibility . PROTECTED ) ) ; } } else if ( name . equals ( MODULE_FUNCTION ) ) { for ( String methodName : arguments ) { requestor . acceptModuleFunction ( methodName ) ; } } else if ( name . equals ( "" ) ) { Node receiver = iVisited . getReceiverNode ( ) ; if ( receiver instanceof ConstNode || receiver instanceof Colon2Node ) { String receiverName = null ; if ( receiver instanceof Colon2Node ) { receiverName = ASTUtil . getFullyQualifiedName ( ( Colon2Node ) receiver ) ; } else { receiverName = ASTUtil . getNameReflectively ( receiver ) ; } requestor . acceptMethodReference ( name , arguments . size ( ) , iVisited . getPosition ( ) . getStartOffset ( ) ) ; pushVisibility ( Visibility . PUBLIC ) ; TypeInfo typeInfo = new TypeInfo ( ) ; typeInfo . name = receiverName ; typeInfo . declarationStart = iVisited . getPosition ( ) . getStartOffset ( ) ; typeInfo . nameSourceStart = receiver . getPosition ( ) . getStartOffset ( ) ; typeInfo . nameSourceEnd = receiver . getPosition ( ) . getEndOffset ( ) - ; typeInfo . isModule = false ; typeInfo . modules = new String [ ] ; typeInfo . secondary = false ; requestor . enterType ( typeInfo ) ; Object ins = super . visitCallNode ( iVisited ) ; popVisibility ( ) ; requestor . exitType ( iVisited . getPosition ( ) . getEndOffset ( ) - ) ; return ins ; } } requestor . acceptMethodReference ( name , arguments . size ( ) , iVisited . getPosition ( ) . getStartOffset ( ) ) ; return super . visitCallNode ( iVisited ) ; } public Object visitAliasNode ( AliasNode iVisited ) { String name = iVisited . getNewName ( ) ; int nameStart = iVisited . getPosition ( ) . getStartOffset ( ) + ALIAS . length ( ) - ; addAliasMethod ( name , iVisited . getPosition ( ) . getStartOffset ( ) , iVisited . getPosition ( ) . getEndOffset ( ) , nameStart ) ; return super . visitAliasNode ( iVisited ) ; } private Visibility getCurrentVisibility ( ) { return visibilities . get ( visibilities . size ( ) - ) ; } public void parse ( char [ ] source , char [ ] name ) { RubyParser p = new RubyParser ( ) ; this . source = source ; if ( name == null ) name = new char [ ] ; Node ast = p . parse ( new String ( name ) , new String ( source ) ) . getAST ( ) ; acceptNode ( ast ) ; } @ Override public Object visitYieldNode ( YieldNode iVisited ) { Node argsNode = iVisited . getArgsNode ( ) ; if ( argsNode instanceof LocalVarNode ) { requestor . acceptYield ( ( ( LocalVarNode ) argsNode ) . getName ( ) ) ; } else if ( argsNode instanceof SelfNode ) { String name = null ; if ( typeName == null ) { name = "" ; } else { name = typeName . toLowerCase ( ) ; if ( name . indexOf ( "" ) > - ) { name = name . substring ( name . lastIndexOf ( "" ) + ) ; } } requestor . acceptYield ( name ) ; } return super . visitYieldNode ( iVisited ) ; } } package org . rubypeople . rdt . internal . core ; import java . util . HashSet ; import java . util . Iterator ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; public class ModelUpdater { HashSet projectsToUpdate = new HashSet ( ) ; protected void addToParentInfo ( Openable child ) { Openable parent = ( Openable ) child . getParent ( ) ; if ( parent != null && parent . isOpen ( ) ) { try { RubyElementInfo info = ( RubyElementInfo ) parent . getElementInfo ( ) ; info . addChild ( child ) ; } catch ( RubyModelException e ) { } } } protected static void close ( Openable element ) { try { element . close ( ) ; } catch ( RubyModelException e ) { } } protected void elementAdded ( Openable element ) { int elementType = element . getElementType ( ) ; if ( elementType == IRubyElement . RUBY_PROJECT ) { addToParentInfo ( element ) ; this . projectsToUpdate . add ( element ) ; } else { addToParentInfo ( element ) ; close ( element ) ; } switch ( elementType ) { case IRubyElement . SOURCE_FOLDER_ROOT : this . projectsToUpdate . add ( element . getRubyProject ( ) ) ; break ; case IRubyElement . SOURCE_FOLDER : RubyProject project = ( RubyProject ) element . getRubyProject ( ) ; project . resetCaches ( ) ; break ; } } protected void elementChanged ( Openable element ) { close ( element ) ; } protected void elementRemoved ( Openable element ) { if ( element . isOpen ( ) ) { close ( element ) ; } removeFromParentInfo ( element ) ; int elementType = element . getElementType ( ) ; switch ( elementType ) { case IRubyElement . RUBY_MODEL : break ; case IRubyElement . RUBY_PROJECT : RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; RubyProject javaProject = ( RubyProject ) element ; manager . removePerProjectInfo ( javaProject ) ; manager . containerRemove ( javaProject ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : this . projectsToUpdate . add ( element . getRubyProject ( ) ) ; break ; case IRubyElement . SOURCE_FOLDER : RubyProject project = ( RubyProject ) element . getRubyProject ( ) ; project . resetCaches ( ) ; break ; } } public void processRubyDelta ( IRubyElementDelta delta ) { try { this . traverseDelta ( delta , null , null ) ; Iterator iterator = this . projectsToUpdate . iterator ( ) ; while ( iterator . hasNext ( ) ) { RubyProject project = ( RubyProject ) iterator . next ( ) ; project . updateSourceFolderRoots ( ) ; } } finally { this . projectsToUpdate = new HashSet ( ) ; } } protected void removeFromParentInfo ( Openable child ) { Openable parent = ( Openable ) child . getParent ( ) ; if ( parent != null && parent . isOpen ( ) ) { try { RubyElementInfo info = ( RubyElementInfo ) parent . getElementInfo ( ) ; info . removeChild ( child ) ; } catch ( RubyModelException e ) { } } } protected void traverseDelta ( IRubyElementDelta delta , ISourceFolderRoot root , IRubyProject project ) { boolean processChildren = true ; Openable element = ( Openable ) delta . getElement ( ) ; switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_PROJECT : project = ( IRubyProject ) element ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : root = ( ISourceFolderRoot ) element ; break ; case IRubyElement . SCRIPT : RubyScript cu = ( RubyScript ) element ; if ( cu . isWorkingCopy ( ) && ! cu . isPrimary ( ) ) { return ; } } switch ( delta . getKind ( ) ) { case IRubyElementDelta . ADDED : elementAdded ( element ) ; break ; case IRubyElementDelta . REMOVED : elementRemoved ( element ) ; break ; case IRubyElementDelta . CHANGED : if ( ( delta . getFlags ( ) & IRubyElementDelta . F_CONTENT ) != ) { elementChanged ( element ) ; } break ; } if ( processChildren ) { IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { IRubyElementDelta childDelta = children [ i ] ; this . traverseDelta ( childDelta , root , project ) ; } } } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class CreateSourceFolderOperation extends RubyModelOperation { protected String [ ] pkgName ; public CreateSourceFolderOperation ( SourceFolderRoot root , String packageName , boolean force ) { super ( null , new IRubyElement [ ] { root } , force ) ; this . pkgName = packageName == null ? null : Util . getTrimmedSimpleNames ( packageName ) ; } protected void executeOperation ( ) throws RubyModelException { RubyElementDelta delta = null ; SourceFolderRoot root = ( SourceFolderRoot ) getParentElement ( ) ; beginTask ( Messages . operation_createPackageFragmentProgress , this . pkgName . length ) ; IContainer parentFolder = ( IContainer ) root . getResource ( ) ; String [ ] sideEffectPackageName = CharOperation . NO_STRINGS ; ArrayList results = new ArrayList ( this . pkgName . length ) ; int i ; for ( i = ; i < this . pkgName . length ; i ++ ) { String subFolderName = this . pkgName [ i ] ; sideEffectPackageName = Util . arrayConcat ( sideEffectPackageName , subFolderName ) ; IResource subFolder = parentFolder . findMember ( subFolderName ) ; if ( subFolder == null ) { createFolder ( parentFolder , subFolderName , force ) ; parentFolder = parentFolder . getFolder ( new Path ( subFolderName ) ) ; ISourceFolder addedFrag = root . getSourceFolder ( sideEffectPackageName ) ; if ( delta == null ) { delta = newRubyElementDelta ( ) ; } delta . added ( addedFrag ) ; results . add ( addedFrag ) ; } else { parentFolder = ( IContainer ) subFolder ; } worked ( ) ; } if ( results . size ( ) > ) { this . resultElements = new IRubyElement [ results . size ( ) ] ; results . toArray ( this . resultElements ) ; if ( delta != null ) { addDelta ( delta ) ; } } done ( ) ; } public IRubyModelStatus verify ( ) { if ( getParentElement ( ) == null ) { return new RubyModelStatus ( IRubyModelStatusConstants . NO_ELEMENTS_TO_PROCESS ) ; } String packageName = this . pkgName == null ? null : Util . concatWith ( this . pkgName , '' ) ; if ( this . pkgName == null ) { return new RubyModelStatus ( IRubyModelStatusConstants . INVALID_NAME , packageName ) ; } IRubyProject root = ( IRubyProject ) getParentElement ( ) ; if ( root . isReadOnly ( ) ) { return new RubyModelStatus ( IRubyModelStatusConstants . READ_ONLY , root ) ; } IContainer parentFolder = ( IContainer ) root . getResource ( ) ; int i ; for ( i = ; i < this . pkgName . length ; i ++ ) { IResource subFolder = parentFolder . findMember ( this . pkgName [ i ] ) ; if ( subFolder != null ) { if ( subFolder . getType ( ) != IResource . FOLDER ) { return new RubyModelStatus ( IRubyModelStatusConstants . NAME_COLLISION , Messages . bind ( Messages . status_nameCollision , subFolder . getFullPath ( ) . toString ( ) ) ) ; } parentFolder = ( IContainer ) subFolder ; } } return RubyModelStatus . VERIFIED_OK ; } } package org . rubypeople . rdt . internal . core ; import java . io . File ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Map ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; import org . rubypeople . rdt . internal . core . util . Messages ; public class RubyModel extends Openable implements IRubyModel { public static HashSet < File > existingExternalFiles = new HashSet < File > ( ) ; public static HashSet existingExternalConfirmedFolders = new HashSet ( ) ; protected RubyModel ( ) { super ( null ) ; } public static void flushExternalFileCache ( ) { existingExternalFiles = new HashSet < File > ( ) ; existingExternalConfirmedFolders = new HashSet ( ) ; } protected Object createElementInfo ( ) { return new RubyModelInfo ( ) ; } public boolean equals ( Object o ) { if ( ! ( o instanceof RubyModel ) ) return false ; return super . equals ( o ) ; } public Object [ ] getNonRubyResources ( ) throws RubyModelException { return ( ( RubyModelInfo ) getElementInfo ( ) ) . getNonRubyResources ( ) ; } public IRubyProject findRubyProject ( IProject project ) { try { IRubyProject [ ] projects = this . getRubyProjects ( ) ; for ( int i = , length = projects . length ; i < length ; i ++ ) { IRubyProject rubyProject = projects [ i ] ; if ( project . equals ( rubyProject . getProject ( ) ) ) { return rubyProject ; } } } catch ( RubyModelException e ) { } return null ; } public int getElementType ( ) { return IRubyElement . RUBY_MODEL ; } public IPath getPath ( ) { return Path . ROOT ; } public IResource getResource ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; } public IResource getUnderlyingResource ( ) { return null ; } public IWorkspace getWorkspace ( ) { return ResourcesPlugin . getWorkspace ( ) ; } public IRubyProject [ ] getRubyProjects ( ) throws RubyModelException { ArrayList list = getChildrenOfType ( RUBY_PROJECT ) ; IRubyProject [ ] array = new IRubyProject [ list . size ( ) ] ; list . toArray ( array ) ; return array ; } protected boolean buildStructure ( OpenableElementInfo info , IProgressMonitor pm , Map newElements , IResource underlyingResource ) { IProject [ ] projects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; for ( int i = , max = projects . length ; i < max ; i ++ ) { IProject project = projects [ i ] ; if ( RubyProject . hasRubyNature ( project ) ) { info . addChild ( getRubyProject ( project ) ) ; } } newElements . put ( this , info ) ; return true ; } public IRubyProject getRubyProject ( IResource resource ) { switch ( resource . getType ( ) ) { case IResource . FOLDER : return new RubyProject ( ( ( IFolder ) resource ) . getProject ( ) , this ) ; case IResource . FILE : return new RubyProject ( ( ( IFile ) resource ) . getProject ( ) , this ) ; case IResource . PROJECT : return new RubyProject ( ( IProject ) resource , this ) ; default : throw new IllegalArgumentException ( Messages . bind ( Messages . element_invalidResourceForProject ) ) ; } } public IRubyProject getRubyProject ( String projectName ) { return new RubyProject ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) , this ) ; } public static Object getTarget ( IPath path , boolean checkResourceExistence ) { Object target = getWorkspaceTarget ( path ) ; if ( target != null ) return target ; return getExternalTarget ( path , checkResourceExistence ) ; } public static IResource getWorkspaceTarget ( IPath path ) { if ( path == null || path . getDevice ( ) != null ) return null ; IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; if ( workspace == null ) return null ; return workspace . getRoot ( ) . findMember ( path ) ; } public static Object getExternalTarget ( IPath path , boolean checkResourceExistence ) { if ( path == null ) return null ; File externalFile = new File ( path . toOSString ( ) ) ; Object linkedFolder = getFolder ( externalFile ) ; if ( linkedFolder != null ) { if ( checkResourceExistence ) { if ( ! externalFile . exists ( ) ) { return null ; } } return linkedFolder ; } if ( ! checkResourceExistence ) { return externalFile ; } else if ( existingExternalFilesContains ( externalFile ) ) { return externalFile ; } else { if ( RubyModelManager . ZIP_ACCESS_VERBOSE ) { System . out . println ( "" + Thread . currentThread ( ) + "" + path . toString ( ) ) ; } if ( externalFile . isFile ( ) ) { existingExternalFilesAdd ( externalFile ) ; return externalFile ; } } return null ; } private synchronized static void existingExternalFilesAdd ( File externalFile ) { existingExternalFiles . add ( externalFile ) ; } private synchronized static boolean existingExternalFilesContains ( File externalFile ) { return existingExternalFiles . contains ( externalFile ) ; } public static boolean isFolder ( Object target ) { return getFolder ( target ) != null ; } public static synchronized File getFolder ( Object target ) { if ( existingExternalConfirmedFolders . contains ( target ) ) return ( File ) target ; if ( target instanceof File ) { File f = ( File ) target ; if ( f . isDirectory ( ) ) { existingExternalConfirmedFolders . add ( f ) ; return f ; } } return null ; } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner owner ) { switch ( token . charAt ( ) ) { case JEM_RUBYPROJECT : if ( ! memento . hasMoreTokens ( ) ) return this ; String projectName = memento . nextToken ( ) ; RubyElement project = ( RubyElement ) getRubyProject ( projectName ) ; return project . getHandleFromMemento ( memento , owner ) ; } return null ; } protected void getHandleMemento ( StringBuffer buff ) { buff . append ( getElementName ( ) ) ; } protected char getHandleMementoDelimiter ( ) { Assert . isTrue ( false , "" ) ; return ; } public boolean contains ( IResource resource ) { switch ( resource . getType ( ) ) { case IResource . ROOT : case IResource . PROJECT : return true ; } IRubyProject [ ] projects ; try { projects = this . getRubyProjects ( ) ; } catch ( RubyModelException e ) { return false ; } for ( int i = , length = projects . length ; i < length ; i ++ ) { RubyProject project = ( RubyProject ) projects [ i ] ; if ( ! project . contains ( resource ) ) { return false ; } } return true ; } public void refreshExternalArchives ( IRubyElement [ ] elementsScope , IProgressMonitor monitor ) throws RubyModelException { if ( elementsScope == null ) { elementsScope = new IRubyElement [ ] { this } ; } RubyModelManager . getRubyModelManager ( ) . getDeltaProcessor ( ) . checkExternalArchiveChanges ( elementsScope , monitor ) ; } } package org . rubypeople . rdt . internal . core ; public class RubyClassVar extends RubyField { public RubyClassVar ( RubyElement parent , String name ) { super ( parent , name ) ; } public int getElementType ( ) { return RubyElement . CLASS_VAR ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . ISourceImport ; public class ImportDeclarationElementInfo extends MemberElementInfo implements ISourceImport { String name ; public String getName ( ) { return this . name ; } } package org . rubypeople . rdt . internal . core ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import org . eclipse . core . resources . * ; import org . eclipse . core . runtime . * ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . rubypeople . rdt . core . * ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . eclipse . jface . text . IDocument ; public abstract class RubyModelOperation implements IWorkspaceRunnable , IProgressMonitor { protected interface IPostAction { String getID ( ) ; void run ( ) throws RubyModelException ; } protected static final int APPEND = ; protected static final int REMOVEALL_APPEND = ; protected static final int KEEP_EXISTING = ; protected static boolean POST_ACTION_VERBOSE ; protected IPostAction [ ] actions ; protected int actionsStart = ; protected int actionsEnd = - ; protected HashMap < Object , Object > attributes ; public static final String HAS_MODIFIED_RESOURCE_ATTR = "" ; public static final String TRUE = "" ; protected IRubyElement [ ] elementsToProcess ; protected IRubyElement [ ] parentElements ; protected static IRubyElement [ ] NO_ELEMENTS = new IRubyElement [ ] { } ; protected IRubyElement [ ] resultElements = NO_ELEMENTS ; protected IProgressMonitor progressMonitor = null ; protected boolean isNested = false ; protected boolean force = false ; protected static ThreadLocal < ArrayList < RubyModelOperation > > operationStacks = new ThreadLocal < ArrayList < RubyModelOperation > > ( ) ; protected RubyModelOperation ( ) { } protected RubyModelOperation ( IRubyElement [ ] elements ) { this . elementsToProcess = elements ; } protected RubyModelOperation ( IRubyElement [ ] elementsToProcess , IRubyElement [ ] parentElements ) { this . elementsToProcess = elementsToProcess ; this . parentElements = parentElements ; } protected RubyModelOperation ( IRubyElement [ ] elementsToProcess , IRubyElement [ ] parentElements , boolean force ) { this . elementsToProcess = elementsToProcess ; this . parentElements = parentElements ; this . force = force ; } protected RubyModelOperation ( IRubyElement [ ] elements , boolean force ) { this . elementsToProcess = elements ; this . force = force ; } protected RubyModelOperation ( IRubyElement element ) { this . elementsToProcess = new IRubyElement [ ] { element } ; } protected RubyModelOperation ( IRubyElement element , boolean force ) { this . elementsToProcess = new IRubyElement [ ] { element } ; this . force = force ; } protected void addAction ( IPostAction action ) { int length = this . actions . length ; if ( length == ++ this . actionsEnd ) { System . arraycopy ( this . actions , , this . actions = new IPostAction [ length * ] , , length ) ; } this . actions [ this . actionsEnd ] = action ; } protected void addDelta ( IRubyElementDelta delta ) { RubyModelManager . getRubyModelManager ( ) . getDeltaProcessor ( ) . registerRubyModelDelta ( delta ) ; } protected void addReconcileDelta ( IRubyScript workingCopy , IRubyElementDelta delta ) { HashMap < IRubyScript , IRubyElementDelta > reconcileDeltas = RubyModelManager . getRubyModelManager ( ) . getDeltaProcessor ( ) . reconcileDeltas ; RubyElementDelta previousDelta = ( RubyElementDelta ) reconcileDeltas . get ( workingCopy ) ; if ( previousDelta != null ) { IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { RubyElementDelta child = ( RubyElementDelta ) children [ i ] ; previousDelta . insertDeltaTree ( child . getElement ( ) , child ) ; } if ( ( delta . getFlags ( ) & IRubyElementDelta . F_AST_AFFECTED ) != ) { previousDelta . changedAST ( delta . getRubyScriptAST ( ) ) ; } } else { reconcileDeltas . put ( workingCopy , delta ) ; } } protected void removeReconcileDelta ( IRubyScript workingCopy ) { RubyModelManager . getRubyModelManager ( ) . getDeltaProcessor ( ) . reconcileDeltas . remove ( workingCopy ) ; } public void beginTask ( String name , int totalWork ) { if ( progressMonitor != null ) { progressMonitor . beginTask ( name , totalWork ) ; } } protected boolean canModifyRoots ( ) { return false ; } protected void checkCanceled ( ) { if ( isCanceled ( ) ) { throw new OperationCanceledException ( Messages . operation_cancelled ) ; } } protected IRubyModelStatus commonVerify ( ) { if ( elementsToProcess == null || elementsToProcess . length == ) { return new RubyModelStatus ( IRubyModelStatusConstants . NO_ELEMENTS_TO_PROCESS ) ; } for ( int i = ; i < elementsToProcess . length ; i ++ ) { if ( elementsToProcess [ i ] == null ) { return new RubyModelStatus ( IRubyModelStatusConstants . NO_ELEMENTS_TO_PROCESS ) ; } } return RubyModelStatus . VERIFIED_OK ; } protected void copyResources ( IResource [ ] resources , IPath destinationPath ) throws RubyModelException { IProgressMonitor subProgressMonitor = getSubProgressMonitor ( resources . length ) ; IWorkspace workspace = resources [ ] . getWorkspace ( ) ; try { workspace . copy ( resources , destinationPath , false , subProgressMonitor ) ; this . setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } protected void createFile ( IContainer folder , String name , InputStream contents , boolean forceFlag ) throws RubyModelException { IFile file = folder . getFile ( new Path ( name ) ) ; try { file . create ( contents , forceFlag ? IResource . FORCE | IResource . KEEP_HISTORY : IResource . KEEP_HISTORY , getSubProgressMonitor ( ) ) ; this . setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } protected void createFolder ( IContainer parentFolder , String name , boolean forceFlag ) throws RubyModelException { IFolder folder = parentFolder . getFolder ( new Path ( name ) ) ; try { folder . create ( forceFlag ? IResource . FORCE | IResource . KEEP_HISTORY : IResource . KEEP_HISTORY , true , getSubProgressMonitor ( ) ) ; this . setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } protected void deleteResource ( IResource resource , int flags ) throws RubyModelException { try { resource . delete ( flags , getSubProgressMonitor ( ) ) ; this . setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } protected void deleteResources ( IResource [ ] resources , boolean forceFlag ) throws RubyModelException { if ( resources == null || resources . length == ) return ; IProgressMonitor subProgressMonitor = getSubProgressMonitor ( resources . length ) ; IWorkspace workspace = resources [ ] . getWorkspace ( ) ; try { workspace . delete ( resources , forceFlag ? IResource . FORCE | IResource . KEEP_HISTORY : IResource . KEEP_HISTORY , subProgressMonitor ) ; this . setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } public void done ( ) { if ( progressMonitor != null ) { progressMonitor . done ( ) ; } } protected boolean equalsOneOf ( IPath path , IPath [ ] otherPaths ) { for ( int i = , length = otherPaths . length ; i < length ; i ++ ) { if ( path . equals ( otherPaths [ i ] ) ) { return true ; } } return false ; } public void executeNestedOperation ( RubyModelOperation operation , int subWorkAmount ) throws RubyModelException { IRubyModelStatus status = operation . verify ( ) ; if ( ! status . isOK ( ) ) { throw new RubyModelException ( status ) ; } IProgressMonitor subProgressMonitor = getSubProgressMonitor ( subWorkAmount ) ; try { operation . setNested ( true ) ; operation . run ( subProgressMonitor ) ; } catch ( CoreException ce ) { if ( ce instanceof RubyModelException ) { throw ( RubyModelException ) ce ; } if ( ce . getStatus ( ) . getCode ( ) == IResourceStatus . OPERATION_FAILED ) { Throwable e = ce . getStatus ( ) . getException ( ) ; if ( e instanceof RubyModelException ) { throw ( RubyModelException ) e ; } } throw new RubyModelException ( ce ) ; } } protected abstract void executeOperation ( ) throws RubyModelException ; protected Object getAttribute ( Object key ) { ArrayList stack = this . getCurrentOperationStack ( ) ; if ( stack . size ( ) == ) return null ; RubyModelOperation topLevelOp = ( RubyModelOperation ) stack . get ( ) ; if ( topLevelOp . attributes == null ) { return null ; } return topLevelOp . attributes . get ( key ) ; } protected IRubyScript getRubyScriptFor ( IRubyElement element ) { return ( ( RubyElement ) element ) . getRubyScript ( ) ; } protected ArrayList < RubyModelOperation > getCurrentOperationStack ( ) { ArrayList < RubyModelOperation > stack = operationStacks . get ( ) ; if ( stack == null ) { stack = new ArrayList < RubyModelOperation > ( ) ; operationStacks . set ( stack ) ; } return stack ; } protected IDocument getDocument ( IRubyScript cu ) throws RubyModelException { IBuffer buffer = cu . getBuffer ( ) ; if ( buffer instanceof IDocument ) return ( IDocument ) buffer ; return new DocumentAdapter ( buffer ) ; } protected IRubyElement [ ] getElementsToProcess ( ) { return elementsToProcess ; } protected IRubyElement getElementToProcess ( ) { if ( elementsToProcess == null || elementsToProcess . length == ) { return null ; } return elementsToProcess [ ] ; } public IRubyModel getRubyModel ( ) { if ( elementsToProcess == null || elementsToProcess . length == ) { return getParentElement ( ) . getRubyModel ( ) ; } return elementsToProcess [ ] . getRubyModel ( ) ; } protected IRubyElement getParentElement ( ) { if ( parentElements == null || parentElements . length == ) { return null ; } return parentElements [ ] ; } protected IRubyElement [ ] getParentElements ( ) { return parentElements ; } public IRubyElement [ ] getResultElements ( ) { return resultElements ; } protected ISchedulingRule getSchedulingRule ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; } protected IProgressMonitor getSubProgressMonitor ( int workAmount ) { IProgressMonitor sub = null ; if ( progressMonitor != null ) { sub = new SubProgressMonitor ( progressMonitor , workAmount , SubProgressMonitor . PREPEND_MAIN_LABEL_TO_SUBTASK ) ; } return sub ; } public boolean hasModifiedResource ( ) { return ! this . isReadOnly ( ) && this . getAttribute ( HAS_MODIFIED_RESOURCE_ATTR ) == TRUE ; } public void internalWorked ( double work ) { if ( progressMonitor != null ) { progressMonitor . internalWorked ( work ) ; } } public boolean isCanceled ( ) { if ( progressMonitor != null ) { return progressMonitor . isCanceled ( ) ; } return false ; } public boolean isReadOnly ( ) { return false ; } protected boolean isTopLevelOperation ( ) { ArrayList stack ; return ( stack = this . getCurrentOperationStack ( ) ) . size ( ) > && stack . get ( ) == this ; } protected int firstActionWithID ( String id , int start ) { for ( int i = start ; i <= this . actionsEnd ; i ++ ) { if ( this . actions [ i ] . getID ( ) . equals ( id ) ) { return i ; } } return - ; } protected void moveResources ( IResource [ ] resources , IPath destinationPath ) throws RubyModelException { IProgressMonitor subProgressMonitor = null ; if ( progressMonitor != null ) { subProgressMonitor = new SubProgressMonitor ( progressMonitor , resources . length , SubProgressMonitor . PREPEND_MAIN_LABEL_TO_SUBTASK ) ; } IWorkspace workspace = resources [ ] . getWorkspace ( ) ; try { workspace . move ( resources , destinationPath , false , subProgressMonitor ) ; this . setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } public RubyElementDelta newRubyElementDelta ( ) { return new RubyElementDelta ( getRubyModel ( ) ) ; } protected RubyModelOperation popOperation ( ) { ArrayList stack = getCurrentOperationStack ( ) ; int size = stack . size ( ) ; if ( size > ) { if ( size == ) { operationStacks . set ( null ) ; } return ( RubyModelOperation ) stack . remove ( size - ) ; } return null ; } protected void postAction ( IPostAction action , int insertionMode ) { if ( POST_ACTION_VERBOSE ) { System . out . print ( "" + Thread . currentThread ( ) + "" + action . getID ( ) ) ; switch ( insertionMode ) { case REMOVEALL_APPEND : System . out . println ( "" ) ; break ; case KEEP_EXISTING : System . out . println ( "" ) ; break ; case APPEND : System . out . println ( "" ) ; break ; } } RubyModelOperation topLevelOp = getCurrentOperationStack ( ) . get ( ) ; IPostAction [ ] postActions = topLevelOp . actions ; if ( postActions == null ) { topLevelOp . actions = postActions = new IPostAction [ ] ; postActions [ ] = action ; topLevelOp . actionsEnd = ; } else { String id = action . getID ( ) ; switch ( insertionMode ) { case REMOVEALL_APPEND : int index = this . actionsStart - ; while ( ( index = topLevelOp . firstActionWithID ( id , index + ) ) >= ) { System . arraycopy ( postActions , index + , postActions , index , topLevelOp . actionsEnd - index ) ; postActions [ topLevelOp . actionsEnd -- ] = null ; } topLevelOp . addAction ( action ) ; break ; case KEEP_EXISTING : if ( topLevelOp . firstActionWithID ( id , ) < ) { topLevelOp . addAction ( action ) ; } break ; case APPEND : topLevelOp . addAction ( action ) ; break ; } } } protected boolean prefixesOneOf ( IPath path , IPath [ ] otherPaths ) { for ( int i = , length = otherPaths . length ; i < length ; i ++ ) { if ( path . isPrefixOf ( otherPaths [ i ] ) ) { return true ; } } return false ; } protected void pushOperation ( RubyModelOperation operation ) { getCurrentOperationStack ( ) . add ( operation ) ; } protected void removeAllPostAction ( String actionID ) { if ( POST_ACTION_VERBOSE ) { System . out . println ( "" + Thread . currentThread ( ) + "" + actionID ) ; } RubyModelOperation topLevelOp = getCurrentOperationStack ( ) . get ( ) ; IPostAction [ ] postActions = topLevelOp . actions ; if ( postActions == null ) return ; int index = this . actionsStart - ; while ( ( index = topLevelOp . firstActionWithID ( actionID , index + ) ) >= ) { System . arraycopy ( postActions , index + , postActions , index , topLevelOp . actionsEnd - index ) ; postActions [ topLevelOp . actionsEnd -- ] = null ; } } public void run ( IProgressMonitor monitor ) throws CoreException { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; DeltaProcessor deltaProcessor = manager . getDeltaProcessor ( ) ; int previousDeltaCount = deltaProcessor . rubyModelDeltas . size ( ) ; try { progressMonitor = monitor ; pushOperation ( this ) ; try { if ( canModifyRoots ( ) ) { RubyModelManager . getRubyModelManager ( ) . deltaState . initializeRoots ( ) ; } executeOperation ( ) ; } finally { if ( this . isTopLevelOperation ( ) ) { this . runPostActions ( ) ; } } } finally { try { deltaProcessor = manager . getDeltaProcessor ( ) ; for ( int i = previousDeltaCount , size = deltaProcessor . rubyModelDeltas . size ( ) ; i < size ; i ++ ) { deltaProcessor . updateRubyModel ( deltaProcessor . rubyModelDeltas . get ( i ) ) ; } for ( int i = , length = this . resultElements . length ; i < length ; i ++ ) { IRubyElement element = this . resultElements [ i ] ; Openable openable = ( Openable ) element . getOpenable ( ) ; if ( ! ( openable instanceof RubyScript ) || ! ( ( RubyScript ) openable ) . isWorkingCopy ( ) ) { ( ( RubyElement ) openable . getParent ( ) ) . close ( ) ; } } if ( this . isTopLevelOperation ( ) ) { if ( ( deltaProcessor . rubyModelDeltas . size ( ) > previousDeltaCount || ! deltaProcessor . reconcileDeltas . isEmpty ( ) ) && ! this . hasModifiedResource ( ) ) { deltaProcessor . fire ( null , DeltaProcessor . DEFAULT_CHANGE_EVENT ) ; } } } finally { popOperation ( ) ; } } } public void runOperation ( IProgressMonitor monitor ) throws RubyModelException { IRubyModelStatus status = verify ( ) ; if ( ! status . isOK ( ) ) { throw new RubyModelException ( status ) ; } try { if ( isReadOnly ( ) ) { run ( monitor ) ; } else { ResourcesPlugin . getWorkspace ( ) . run ( this , getSchedulingRule ( ) , IWorkspace . AVOID_UPDATE , monitor ) ; } } catch ( CoreException ce ) { if ( ce instanceof RubyModelException ) { throw ( RubyModelException ) ce ; } if ( ce . getStatus ( ) . getCode ( ) == IResourceStatus . OPERATION_FAILED ) { Throwable e = ce . getStatus ( ) . getException ( ) ; if ( e instanceof RubyModelException ) { throw ( RubyModelException ) e ; } } throw new RubyModelException ( ce ) ; } } protected void runPostActions ( ) throws RubyModelException { while ( this . actionsStart <= this . actionsEnd ) { IPostAction postAction = this . actions [ this . actionsStart ++ ] ; if ( POST_ACTION_VERBOSE ) { System . out . println ( "" + Thread . currentThread ( ) + "" + postAction . getID ( ) ) ; } postAction . run ( ) ; } } protected void setAttribute ( Object key , Object attribute ) { RubyModelOperation topLevelOp = this . getCurrentOperationStack ( ) . get ( ) ; if ( topLevelOp . attributes == null ) { topLevelOp . attributes = new HashMap < Object , Object > ( ) ; } topLevelOp . attributes . put ( key , attribute ) ; } public void setCanceled ( boolean b ) { if ( progressMonitor != null ) { progressMonitor . setCanceled ( b ) ; } } protected void setNested ( boolean nested ) { isNested = nested ; } public void setTaskName ( String name ) { if ( progressMonitor != null ) { progressMonitor . setTaskName ( name ) ; } } public void subTask ( String name ) { if ( progressMonitor != null ) { progressMonitor . subTask ( name ) ; } } protected IRubyModelStatus verify ( ) { return commonVerify ( ) ; } public void worked ( int work ) { if ( progressMonitor != null ) { progressMonitor . worked ( work ) ; checkCanceled ( ) ; } } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Util ; public class RubyMethod extends NamedMember implements IMethod { private String [ ] parameterNames ; public RubyMethod ( RubyElement parent , String name , String [ ] parameterNames ) { super ( parent , name ) ; this . parameterNames = parameterNames ; } public int getElementType ( ) { return RubyElement . METHOD ; } protected void getHandleMemento ( StringBuffer buff ) { ( ( RubyElement ) getParent ( ) ) . getHandleMemento ( buff ) ; char delimiter = getHandleMementoDelimiter ( ) ; buff . append ( delimiter ) ; escapeMementoName ( buff , getElementName ( ) ) ; for ( int i = ; i < this . parameterNames . length ; i ++ ) { buff . append ( delimiter ) ; escapeMementoName ( buff , this . parameterNames [ i ] ) ; } if ( this . occurrenceCount > ) { buff . append ( JEM_COUNT ) ; buff . append ( this . occurrenceCount ) ; } } protected char getHandleMementoDelimiter ( ) { return RubyElement . JEM_METHOD ; } public IRubyElement getPrimaryElement ( boolean checkOwner ) { if ( checkOwner ) { RubyScript cu = ( RubyScript ) getAncestor ( SCRIPT ) ; if ( cu . isPrimary ( ) ) return this ; } IRubyElement primaryParent = this . parent . getPrimaryElement ( false ) ; return ( ( IType ) primaryParent ) . getMethod ( this . name , parameterNames ) ; } public boolean isConstructor ( ) { return getElementName ( ) . equals ( "" ) ; } public boolean equals ( Object o ) { if ( ! ( o instanceof RubyMethod ) ) return false ; return super . equals ( o ) ; } public int hashCode ( ) { int hash = super . hashCode ( ) ; for ( int i = , length = parameterNames . length ; i < length ; i ++ ) { hash = Util . combineHashCodes ( hash , parameterNames [ i ] . hashCode ( ) ) ; } return hash ; } public IType getDeclaringType ( ) { IRubyElement parent = getParent ( ) ; if ( parent instanceof IType ) return ( IType ) parent ; return null ; } public int getVisibility ( ) throws RubyModelException { if ( isConstructor ( ) ) return IMethod . PUBLIC ; RubyMethodElementInfo info = ( RubyMethodElementInfo ) getElementInfo ( ) ; return info . getVisibility ( ) ; } public String [ ] getParameterNames ( ) throws RubyModelException { return parameterNames ; } public int getNumberOfParameters ( ) throws RubyModelException { return getParameterNames ( ) . length ; } public boolean isSingleton ( ) { try { RubyMethodElementInfo info = ( RubyMethodElementInfo ) getElementInfo ( ) ; return info . isSingleton ( ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } return isConstructor ( ) ; } public static RubyMethod singleton ( RubyElement currentType , String name , String [ ] parameterNames2 ) { RubyMethod method = new RubyMethod ( currentType , name , parameterNames2 ) ; try { RubyMethodElementInfo info = ( RubyMethodElementInfo ) method . getElementInfo ( ) ; info . setIsSingleton ( true ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } return method ; } public boolean isPrivate ( ) throws RubyModelException { return getVisibility ( ) == PRIVATE ; } public boolean isPublic ( ) throws RubyModelException { return getVisibility ( ) == PUBLIC ; } public boolean isProtected ( ) throws RubyModelException { return getVisibility ( ) == PROTECTED ; } public String [ ] getBlockParameters ( ) throws RubyModelException { RubyMethodElementInfo info = ( RubyMethodElementInfo ) getElementInfo ( ) ; return info . getBlockVars ( ) ; } public boolean isSimilar ( IMethod method ) { if ( ! this . getElementName ( ) . equals ( method . getElementName ( ) ) ) return false ; try { return getNumberOfParameters ( ) == method . getNumberOfParameters ( ) ; } catch ( RubyModelException e ) { return true ; } } } package org . rubypeople . rdt . internal . core ; import java . util . HashMap ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . DOMFinder ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; public abstract class SourceRefElement extends RubyElement implements ISourceReference { public int occurrenceCount = ; public SourceRefElement ( RubyElement parent ) { super ( parent ) ; } public IRubyScript getRubyScript ( ) { return ( ( RubyElement ) getParent ( ) ) . getRubyScript ( ) ; } public Node findNode ( Node ast ) { DOMFinder finder = new DOMFinder ( ast , this ) ; try { return finder . search ( ) ; } catch ( RubyModelException e ) { return null ; } } public IOpenable getOpenableParent ( ) { IRubyElement current = getParent ( ) ; while ( current != null ) { if ( current instanceof IOpenable ) { return ( IOpenable ) current ; } current = current . getParent ( ) ; } return null ; } public IResource getCorrespondingResource ( ) throws RubyModelException { if ( ! exists ( ) ) throw newNotPresentException ( ) ; return null ; } public boolean isStructureKnown ( ) throws RubyModelException { return true ; } public String getSource ( ) throws RubyModelException { IOpenable openable = getOpenableParent ( ) ; IBuffer buffer = openable . getBuffer ( ) ; if ( buffer == null ) { return null ; } ISourceRange range = getSourceRange ( ) ; int offset = range . getOffset ( ) ; int length = range . getLength ( ) ; if ( offset == - || length == ) { return null ; } try { return buffer . getText ( offset , length ) ; } catch ( RuntimeException e ) { return null ; } } public ISourceRange getSourceRange ( ) throws RubyModelException { SourceRefElementInfo info = ( SourceRefElementInfo ) getElementInfo ( ) ; return info . getSourceRange ( ) ; } public IPath getPath ( ) { return this . getParent ( ) . getPath ( ) ; } public IResource getResource ( ) { return this . getParent ( ) . getResource ( ) ; } public IResource getUnderlyingResource ( ) throws RubyModelException { if ( ! exists ( ) ) throw newNotPresentException ( ) ; return getParent ( ) . getUnderlyingResource ( ) ; } protected void closing ( Object info ) throws RubyModelException { } protected void generateInfos ( Object info , HashMap newElements , IProgressMonitor pm ) throws RubyModelException { Openable openableParent = ( Openable ) getOpenableParent ( ) ; if ( openableParent == null ) return ; RubyElementInfo openableParentInfo = ( RubyElementInfo ) RubyModelManager . getRubyModelManager ( ) . getInfo ( openableParent ) ; if ( openableParentInfo == null ) { openableParent . generateInfos ( openableParent . createElementInfo ( ) , newElements , pm ) ; } } protected Object createElementInfo ( ) { return null ; } public boolean equals ( Object o ) { if ( ! ( o instanceof SourceRefElement ) ) return false ; return this . occurrenceCount == ( ( SourceRefElement ) o ) . occurrenceCount && super . equals ( o ) ; } public IRubyElement getHandleUpdatingCountFromMemento ( MementoTokenizer memento , WorkingCopyOwner owner ) { if ( ! memento . hasMoreTokens ( ) ) return this ; this . occurrenceCount = Integer . parseInt ( memento . nextToken ( ) ) ; if ( ! memento . hasMoreTokens ( ) ) return this ; String token = memento . nextToken ( ) ; return getHandleFromMemento ( token , memento , owner ) ; } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner workingCopyOwner ) { switch ( token . charAt ( ) ) { case JEM_COUNT : return getHandleUpdatingCountFromMemento ( memento , workingCopyOwner ) ; } return this ; } protected void getHandleMemento ( StringBuffer buff ) { super . getHandleMemento ( buff ) ; if ( this . occurrenceCount > ) { buff . append ( JEM_COUNT ) ; buff . append ( this . occurrenceCount ) ; } } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . buffer . LRUCache ; import org . rubypeople . rdt . internal . core . buffer . OverflowingLRUCache ; public class ElementCache extends OverflowingLRUCache { IRubyElement spaceLimitParent = null ; public ElementCache ( int size ) { super ( size ) ; } public ElementCache ( int size , int overflow ) { super ( size , overflow ) ; } protected void ensureSpaceLimit ( int childrenSize , IRubyElement parent ) { int spaceNeeded = + ( int ) ( ( + fLoadFactor ) * ( childrenSize + fOverflow ) ) ; if ( fSpaceLimit < spaceNeeded ) { shrink ( ) ; setSpaceLimit ( spaceNeeded ) ; this . spaceLimitParent = parent ; } } protected void resetSpaceLimit ( int defaultLimit , IRubyElement parent ) { if ( parent . equals ( this . spaceLimitParent ) ) { setSpaceLimit ( defaultLimit ) ; this . spaceLimitParent = null ; } } protected boolean close ( LRUCacheEntry entry ) { Openable element = ( Openable ) entry . _fKey ; try { if ( ! element . canBeRemovedFromCache ( ) ) { return false ; } element . close ( ) ; return true ; } catch ( RubyModelException npe ) { return false ; } } protected LRUCache newInstance ( int size , int overflow ) { return new ElementCache ( size , overflow ) ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ModuleNode ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; public class ConstantReassignmentVisitor extends RubyLintVisitor { private Set < String > assignedConstants ; private List < String > namespace ; public ConstantReassignmentVisitor ( String contents ) { super ( contents ) ; assignedConstants = new HashSet < String > ( ) ; namespace = new ArrayList < String > ( ) ; } @ Override protected String getOptionKey ( ) { return RubyCore . COMPILER_PB_CONSTANT_REASSIGNMENT ; } public Object visitConstDeclNode ( ConstDeclNode iVisited ) { String name ; if ( iVisited . getConstNode ( ) != null ) { name = ASTUtil . getFullyQualifiedName ( iVisited . getConstNode ( ) ) ; } else { name = getNamespace ( ) + iVisited . getName ( ) ; } if ( assignedConstants . contains ( name ) ) createProblem ( iVisited . getPosition ( ) , "" ) ; else assignedConstants . add ( name ) ; return super . visitConstDeclNode ( iVisited ) ; } @ Override public Object visitClassNode ( ClassNode visited ) { namespace . add ( ASTUtil . getFullyQualifiedName ( visited . getCPath ( ) ) ) ; Object ret = super . visitClassNode ( visited ) ; namespace . remove ( namespace . size ( ) - ) ; return ret ; } @ Override public Object visitModuleNode ( ModuleNode visited ) { namespace . add ( ASTUtil . getFullyQualifiedName ( visited . getCPath ( ) ) ) ; Object ret = super . visitModuleNode ( visited ) ; namespace . remove ( namespace . size ( ) - ) ; return ret ; } private String getNamespace ( ) { StringBuilder builder = new StringBuilder ( ) ; for ( String portion : namespace ) { builder . append ( portion ) . append ( "" ) ; } return builder . toString ( ) ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import java . util . List ; import org . jruby . ast . HashNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; public class Ruby19HashCommaSyntax extends RubyLintVisitor { public Ruby19HashCommaSyntax ( String contents ) { super ( contents ) ; } @ Override protected String getOptionKey ( ) { return RubyCore . COMPILER_PB_RUBY_19_HASH_COMMA_SYTNAX ; } @ Override protected String getSeverity ( ) { return super . getSeverity ( ) ; } @ Override public Object visitHashNode ( HashNode iVisited ) { ListNode list = iVisited . getListNode ( ) ; List < Node > children = list . childNodes ( ) ; for ( int i = ; i < children . size ( ) ; i += ) { if ( children . size ( ) <= ( i + ) ) break ; Node key = children . get ( i ) ; if ( key == null ) continue ; Node value = children . get ( i + ) ; if ( value == null ) continue ; ISourcePosition pos = key . getPosition ( ) ; String between = getSource ( pos . getEndOffset ( ) , value . getPosition ( ) . getStartOffset ( ) ) ; if ( between != null && between . trim ( ) . equals ( "" ) ) { int start = pos . getEndOffset ( ) + between . indexOf ( "" ) ; createProblem ( new IDESourcePosition ( "" , pos . getEndLine ( ) , pos . getEndLine ( ) , start , start + ) , "" ) ; } } return super . visitHashNode ( iVisited ) ; } @ Override protected int getProblemID ( ) { return IProblem . HashCommaSyntax ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . Node ; import org . jruby . ast . WhenNode ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; public class EmptyStatementVisitor extends RubyLintVisitor { public EmptyStatementVisitor ( String contents ) { super ( contents ) ; } @ Override protected String getOptionKey ( ) { return RubyCore . COMPILER_PB_EMPTY_STATEMENT ; } public Object visitIfNode ( IfNode iVisited ) { if ( iVisited . getThenBody ( ) == null && iVisited . getElseBody ( ) == null ) { createProblem ( iVisited . getPosition ( ) , "" ) ; return super . visitIfNode ( iVisited ) ; } String source = getSourceOfKeywordForIf ( iVisited ) ; Node body = null ; if ( source != null && source . trim ( ) . startsWith ( "" ) ) { body = iVisited . getElseBody ( ) ; } else if ( source != null && source . trim ( ) . startsWith ( "" ) ) { body = iVisited . getThenBody ( ) ; } if ( body == null ) { createProblem ( iVisited . getPosition ( ) , "" ) ; } return super . visitIfNode ( iVisited ) ; } private String getSourceOfKeywordForIf ( IfNode iVisited ) { Node conditionNode = iVisited . getCondition ( ) ; Node elseBody = iVisited . getElseBody ( ) ; if ( elseBody == null ) { Node thenBody = iVisited . getThenBody ( ) ; if ( thenBody == null ) return null ; if ( thenBody . getPosition ( ) . getEndOffset ( ) > conditionNode . getPosition ( ) . getStartOffset ( ) ) { return getSource ( iVisited . getPosition ( ) . getStartOffset ( ) , conditionNode . getPosition ( ) . getStartOffset ( ) ) ; } else { return getSource ( thenBody . getPosition ( ) . getEndOffset ( ) , conditionNode . getPosition ( ) . getStartOffset ( ) ) ; } } else { if ( elseBody . getPosition ( ) . getEndOffset ( ) > conditionNode . getPosition ( ) . getStartOffset ( ) ) { return getSource ( iVisited . getPosition ( ) . getStartOffset ( ) , conditionNode . getPosition ( ) . getStartOffset ( ) ) ; } else { return getSource ( elseBody . getPosition ( ) . getEndOffset ( ) , conditionNode . getPosition ( ) . getStartOffset ( ) ) ; } } } public Object visitDefnNode ( DefnNode iVisited ) { if ( iVisited . getBodyNode ( ) == null ) { createProblem ( iVisited . getPosition ( ) , "" ) ; } return super . visitDefnNode ( iVisited ) ; } public Object visitDefsNode ( DefsNode iVisited ) { if ( iVisited . getBodyNode ( ) == null ) { createProblem ( iVisited . getPosition ( ) , "" ) ; } return super . visitDefsNode ( iVisited ) ; } public Object visitWhenNode ( WhenNode iVisited ) { if ( iVisited . getBodyNode ( ) == null || iVisited . getBodyNode ( ) . equals ( NilImplicitNode . NIL ) ) { createProblem ( iVisited . getPosition ( ) , "" ) ; } return super . visitWhenNode ( iVisited ) ; } public Object visitIterNode ( IterNode iVisited ) { if ( iVisited . getBodyNode ( ) == null ) { createProblem ( iVisited . getPosition ( ) , "" ) ; } return super . visitIterNode ( iVisited ) ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . WhenNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; public class Ruby19WhenStatements extends RubyLintVisitor { public Ruby19WhenStatements ( String contents ) { super ( contents ) ; } @ Override protected String getOptionKey ( ) { return RubyCore . COMPILER_PB_RUBY_19_WHEN_STATEMENTS ; } @ Override public Object visitWhenNode ( WhenNode iVisited ) { if ( iVisited . getExpressionNodes ( ) == null ) return super . visitWhenNode ( iVisited ) ; if ( iVisited . getBodyNode ( ) == null ) return super . visitWhenNode ( iVisited ) ; if ( iVisited . getPosition ( ) == null ) return super . visitWhenNode ( iVisited ) ; int start = iVisited . getPosition ( ) . getStartOffset ( ) ; ISourcePosition pos = iVisited . getExpressionNodes ( ) . getPosition ( ) ; if ( pos == null ) return super . visitWhenNode ( iVisited ) ; if ( iVisited . getBodyNode ( ) . equals ( NilImplicitNode . NIL ) ) return super . visitWhenNode ( iVisited ) ; ISourcePosition bodyPosition = iVisited . getBodyNode ( ) . getPosition ( ) ; if ( bodyPosition == null ) return super . visitWhenNode ( iVisited ) ; String src = getSource ( iVisited ) ; src = src . substring ( pos . getEndOffset ( ) - start , bodyPosition . getStartOffset ( ) - start ) ; if ( src . trim ( ) . equals ( "" ) ) { int startOffset = pos . getEndOffset ( ) + src . indexOf ( "" ) ; int endOffset = startOffset + ; ISourcePosition position = new IDESourcePosition ( "" , pos . getEndLine ( ) , pos . getEndLine ( ) , startOffset , endOffset ) ; createProblem ( position , "" ) ; } return super . visitWhenNode ( iVisited ) ; } @ Override protected String getSeverity ( ) { return super . getSeverity ( ) ; } @ Override protected int getProblemID ( ) { return IProblem . ColonAfterWhenStatement ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . core . search . CollectingSearchRequestor ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; public class CoreClassReOpening extends RubyLintVisitor { private List < Node > typeStack ; private RootNode rootNode ; private IRubyScript script ; private static Set < String > coreTypes = new HashSet < String > ( ) ; static { coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; coreTypes . add ( "" ) ; } public CoreClassReOpening ( IRubyScript script , String contents ) { super ( contents ) ; this . script = script ; typeStack = new ArrayList < Node > ( ) ; } @ Override protected String getOptionKey ( ) { return RubyCore . COMPILER_PB_REDEFINITION_CORE_CLASS_METHOD ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { String typeName = getCurrentTypeName ( ) ; if ( isCoreClass ( typeName ) ) { String methodName = iVisited . getName ( ) ; if ( methodExistsOnType ( typeName , methodName ) ) createProblem ( iVisited . getPosition ( ) , "" ) ; } return super . visitDefnNode ( iVisited ) ; } protected boolean methodExistsOnType ( String typeName , String methodName ) { try { ISourceFolderRoot [ ] roots = script . getRubyProject ( ) . getAllSourceFolderRoots ( ) ; ISourceFolderRoot stubs = findCoreStubsRoot ( roots ) ; if ( stubs == null ) return false ; SearchParticipant [ ] participants = new SearchParticipant [ ] { SearchEngine . getDefaultSearchParticipant ( ) } ; SearchEngine engine = new SearchEngine ( ) ; IRubySearchScope scope = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { stubs } ) ; CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . METHOD , typeName + '' + methodName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; engine . search ( pattern , participants , scope , requestor , null ) ; List < SearchMatch > matches = requestor . getResults ( ) ; return matches != null && ! matches . isEmpty ( ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } return false ; } private ISourceFolderRoot findCoreStubsRoot ( ISourceFolderRoot [ ] roots ) { for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; IPath path = root . getPath ( ) ; if ( path . segmentCount ( ) < ) continue ; String segment = path . segment ( path . segmentCount ( ) - ) ; if ( segment . equals ( "" ) ) { return root ; } } return null ; } private boolean isCoreClass ( String typeName ) { return coreTypes . contains ( typeName ) ; } @ Override public Object visitRootNode ( RootNode iVisited ) { this . rootNode = iVisited ; return super . visitRootNode ( iVisited ) ; } private String getCurrentTypeName ( ) { Node typeNode = typeStack . get ( typeStack . size ( ) - ) ; return ASTUtil . getFullyQualifiedTypeName ( rootNode , typeNode ) ; } @ Override public Object visitClassNode ( ClassNode iVisited ) { push ( iVisited ) ; return super . visitClassNode ( iVisited ) ; } @ Override public void exitClassNode ( ClassNode iVisited ) { pop ( ) ; super . exitClassNode ( iVisited ) ; } @ Override public Object visitModuleNode ( ModuleNode iVisited ) { push ( iVisited ) ; return super . visitModuleNode ( iVisited ) ; } @ Override public void exitModuleNode ( ModuleNode iVisited ) { pop ( ) ; super . exitModuleNode ( iVisited ) ; } private void pop ( ) { typeStack . remove ( typeStack . size ( ) - ) ; } private void push ( Node visited ) { typeStack . add ( visited ) ; } } package org . rubypeople . rdt . internal . core . parser ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . jruby . common . IRubyWarnings ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . core . util . Util ; public class RdtWarnings implements IRubyWarnings { private List < CategorizedProblem > warnings ; private String fileName ; public RdtWarnings ( String fileName ) { this . fileName = fileName ; warnings = new ArrayList < CategorizedProblem > ( ) ; } public List < CategorizedProblem > getWarnings ( ) { return Collections . unmodifiableList ( warnings ) ; } public void warn ( ID id , ISourcePosition position , String message , Object ... data ) { if ( Util . ignore ( message ) ) { return ; } if ( message . equals ( "" ) ) { String value = RubyCore . getOption ( RubyCore . COMPILER_PB_UNREACHABLE_CODE ) ; if ( value == null || value . equals ( RubyCore . WARNING ) ) { warnings . add ( new Warning ( position , message ) ) ; } if ( value != null && value . equals ( RubyCore . ERROR ) ) { warnings . add ( new Error ( position , message ) ) ; } return ; } else if ( message . equals ( "" ) ) { ISourcePosition pos = new IDESourcePosition ( position . getFile ( ) , position . getStartLine ( ) , position . getEndLine ( ) , position . getStartOffset ( ) , position . getEndOffset ( ) - ) ; warnings . add ( new Warning ( pos , message , IProblem . ParenthesizeArguments ) ) ; return ; } warnings . add ( new Warning ( position , message ) ) ; } public void warn ( ID id , String fileName , int lineNumber , String message , Object ... data ) { warn ( id , new IDESourcePosition ( fileName , lineNumber , lineNumber ) , message , data ) ; } public boolean isVerbose ( ) { return true ; } public void warn ( ID id , String message , Object ... data ) { warn ( id , fileName , , message , data ) ; } public void warning ( ID id , String message , Object ... data ) { warning ( id , fileName , , message , data ) ; } public void warning ( ID id , ISourcePosition position , String message , Object ... data ) { warning ( id , position . getFile ( ) , position . getEndLine ( ) , message , data ) ; } public void warning ( ID id , String fileName , int lineNumber , String message , Object ... data ) { if ( isVerbose ( ) ) warn ( id , fileName , lineNumber , message , data ) ; } } package org . rubypeople . rdt . internal . core . parser ; import org . jruby . lexer . yacc . ISourcePosition ; public class Error extends DefaultProblem { public Error ( ISourcePosition position , String message ) { this ( position , message , - ) ; } public Error ( ISourcePosition position , String message , int problemID ) { super ( position , message , problemID ) ; } public boolean isError ( ) { return true ; } } package org . rubypeople . rdt . internal . core . parser ; import java . io . Reader ; import java . io . StringReader ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . jruby . CompatVersion ; import org . jruby . ast . Node ; import org . jruby . common . IRubyWarnings ; import org . jruby . common . NullWarnings ; import org . jruby . lexer . yacc . LexerSource ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . parser . DefaultRubyParser ; import org . jruby . parser . ParserConfiguration ; import org . jruby . parser . ParserSupport ; import org . jruby . parser . RubyParserPool ; import org . jruby . parser . RubyParserResult ; import org . jruby . util . KCode ; import org . rubypeople . rdt . internal . core . builder . IoUtils ; import org . rubypeople . rdt . internal . core . util . Util ; public class RubyParser { private final RubyParserPool pool ; private IRubyWarnings warnings ; private static boolean isDebug ; private static int count = ; public RubyParser ( ) { this ( new NullWarnings ( ) ) ; } public RubyParser ( IRubyWarnings warnings ) { this . warnings = warnings ; this . pool = RubyParserPool . getInstance ( ) ; } private RubyParserResult parse ( String fileName , Reader content ) { if ( fileName == null ) { fileName = "" ; } DefaultRubyParser parser = null ; try { ParserConfiguration config = getParserConfig ( ) ; parser = getDefaultRubyParser ( config ) ; parser . setWarnings ( warnings ) ; if ( isDebug ) System . out . println ( "" + count ++ + "" + fileName ) ; LexerSource lexerSource = LexerSource . getSource ( fileName , content , null , config ) ; RubyParserResult result = parser . parse ( config , lexerSource ) ; postProcessResult ( result ) ; return result ; } catch ( SyntaxException e ) { throw e ; } finally { IoUtils . closeQuietly ( content ) ; returnBorrowedParser ( parser ) ; } } protected void postProcessResult ( RubyParserResult result ) { } protected void returnBorrowedParser ( DefaultRubyParser parser ) { pool . returnParser ( parser ) ; } protected DefaultRubyParser getDefaultRubyParser ( ParserConfiguration config ) { ParserSupport support = new ParserSupport ( ) ; support . setConfiguration ( config ) ; return new DefaultRubyParser ( support ) ; } protected ParserConfiguration getParserConfig ( ) { return new ParserConfiguration ( KCode . NIL , , true , false , CompatVersion . RUBY1_8 ) ; } public static void setDebugging ( boolean b ) { isDebug = b ; } public static boolean isDebugging ( ) { return isDebug ; } public Node parse ( IFile file ) throws CoreException { return parse ( file . getName ( ) , new String ( Util . getResourceContentsAsCharArray ( file ) ) ) . getAST ( ) ; } public RubyParserResult parse ( String source ) { return parse ( ( String ) null , source ) ; } public RubyParserResult parse ( IFile file , String source ) { String name = "" ; if ( file != null ) name = file . getName ( ) ; return parse ( name , source ) ; } public RubyParserResult parse ( String fileName , String source ) { return parse ( fileName , source , false ) ; } public RubyParserResult parse ( String fileName , String source , boolean bypassCache ) { if ( source == null ) return new NullParserResult ( ) ; RubyParserResult ast = parse ( fileName , new StringReader ( source ) ) ; if ( ast == null ) ast = new NullParserResult ( ) ; return ast ; } } package org . rubypeople . rdt . internal . core . parser ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileReader ; import java . io . FileWriter ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . Reader ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import javax . xml . parsers . SAXParserFactory ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . xml . sax . InputSource ; import org . xml . sax . XMLReader ; public class MarkerUtility { private static Set < IgnoreMarker > toIgnore = new HashSet < IgnoreMarker > ( ) ; static { loadIgnoredMarkers ( ) ; } public static void createSyntaxError ( IResource underlyingResource , SyntaxException syntaxException ) { try { ISourcePosition pos = syntaxException . getPosition ( ) ; IMarker marker = underlyingResource . createMarker ( IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER ) ; Map < String , Comparable > map = new HashMap < String , Comparable > ( ) ; map . put ( IMarker . SEVERITY , new Integer ( IMarker . SEVERITY_ERROR ) ) ; map . put ( IMarker . MESSAGE , "" ) ; map . put ( IMarker . USER_EDITABLE , Boolean . FALSE ) ; map . put ( IMarker . LINE_NUMBER , new Integer ( pos . getStartLine ( ) ) ) ; map . put ( IMarker . CHAR_START , new Integer ( pos . getStartOffset ( ) ) ) ; map . put ( IMarker . CHAR_END , new Integer ( pos . getEndOffset ( ) ) ) ; map . put ( IRubyModelMarker . ID , IProblem . Syntax ) ; marker . setAttributes ( map ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } public static void removeMarkers ( IResource underlyingResource ) { try { underlyingResource . deleteMarkers ( IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER , true , IResource . DEPTH_INFINITE ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } public static void createProblemMarkers ( IResource resource , List < IProblem > problems ) { for ( Iterator iter = problems . iterator ( ) ; iter . hasNext ( ) ; ) { createProblemMarker ( resource , ( IProblem ) iter . next ( ) ) ; } } public static void createProblemMarker ( IResource underlyingResource , IProblem problem ) { if ( problem . isTask ( ) ) { try { createTask ( underlyingResource , ( TaskTag ) problem ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } return ; } try { if ( markerExists ( underlyingResource , problem . getID ( ) , problem . getSourceStart ( ) , problem . getSourceEnd ( ) , IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER ) ) return ; Map < String , Comparable > map = new HashMap < String , Comparable > ( ) ; int severity ; if ( problem . isWarning ( ) ) severity = IMarker . SEVERITY_WARNING ; else if ( problem . isError ( ) ) severity = IMarker . SEVERITY_ERROR ; else severity = IMarker . SEVERITY_INFO ; IMarker marker = underlyingResource . createMarker ( IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER ) ; map . put ( IMarker . SEVERITY , new Integer ( severity ) ) ; map . put ( IMarker . MESSAGE , problem . getMessage ( ) ) ; map . put ( IMarker . USER_EDITABLE , Boolean . FALSE ) ; map . put ( IMarker . LINE_NUMBER , new Integer ( problem . getSourceLineNumber ( ) ) ) ; map . put ( IMarker . CHAR_START , new Integer ( problem . getSourceStart ( ) ) ) ; map . put ( IMarker . CHAR_END , new Integer ( problem . getSourceEnd ( ) ) ) ; map . put ( IRubyModelMarker . ID , problem . getID ( ) ) ; marker . setAttributes ( map ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } public static void createTasks ( IResource underlyingResource , List < TaskTag > tasks ) throws CoreException { for ( Iterator iter = tasks . iterator ( ) ; iter . hasNext ( ) ; ) { createTask ( underlyingResource , ( TaskTag ) iter . next ( ) ) ; } } private static void createTask ( IResource resource , TaskTag task ) throws CoreException { int lineNumber = task . getSourceLineNumber ( ) ; if ( lineNumber <= ) lineNumber = ; if ( markerExists ( resource , task . getID ( ) , task . getSourceStart ( ) , task . getSourceEnd ( ) , IRubyModelMarker . TASK_MARKER ) ) return ; HashMap < String , Comparable > map = new HashMap < String , Comparable > ( ) ; map . put ( IMarker . PRIORITY , new Integer ( task . getPriority ( ) ) ) ; map . put ( IMarker . MESSAGE , task . getMessage ( ) ) ; map . put ( IMarker . LINE_NUMBER , new Integer ( lineNumber ) ) ; map . put ( IMarker . SEVERITY , new Integer ( IMarker . SEVERITY_INFO ) ) ; map . put ( IMarker . USER_EDITABLE , new Boolean ( false ) ) ; map . put ( IMarker . TRANSIENT , new Boolean ( false ) ) ; map . put ( IMarker . CHAR_START , new Integer ( task . getSourceStart ( ) ) ) ; map . put ( IMarker . CHAR_END , new Integer ( task . getSourceEnd ( ) ) ) ; map . put ( IRubyModelMarker . ID , task . getID ( ) ) ; IMarker marker = resource . createMarker ( IRubyModelMarker . TASK_MARKER ) ; marker . setAttributes ( map ) ; } public static boolean markerExists ( IResource resource , int id , int offset , int endOffset , String type ) throws CoreException { if ( ignoring ( resource , id , offset , endOffset ) ) return true ; IMarker tasks [ ] = resource . findMarkers ( type , true , IResource . DEPTH_ZERO ) ; for ( int i = ; i < tasks . length ; i ++ ) { if ( markerMatches ( id , offset , endOffset , tasks [ i ] ) ) return true ; } return false ; } public static boolean ignoring ( IResource resource , int id , int offset , int endOffset ) { for ( IgnoreMarker marker : toIgnore ) { if ( ! marker . getResource ( ) . equals ( resource ) ) continue ; if ( markerMatches ( id , offset , endOffset , marker ) ) return true ; } return false ; } private static boolean markerMatches ( int id , int offset , int endOffset , IgnoreMarker marker ) { if ( marker . getId ( ) != id ) return false ; if ( marker . getOffset ( ) != offset ) return false ; if ( marker . getEndOffset ( ) != endOffset ) return false ; return true ; } public static boolean markerMatches ( int id , int offset , int endOffset , IMarker marker ) throws CoreException { Integer markerId = ( Integer ) marker . getAttribute ( IRubyModelMarker . ID ) ; if ( markerId . intValue ( ) != id ) return false ; Integer start = ( Integer ) marker . getAttribute ( IMarker . CHAR_START ) ; if ( start != offset ) return false ; Integer end = ( Integer ) marker . getAttribute ( IMarker . CHAR_END ) ; if ( end != endOffset ) return false ; return true ; } public static void ignore ( IResource resource , int problemId , int offset , int length ) { ignore ( new IgnoreMarker ( resource , problemId , offset , offset + length ) ) ; } public static void ignore ( IMarker marker ) { try { ignore ( new IgnoreMarker ( marker ) ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } public synchronized static void ignore ( IgnoreMarker marker ) { if ( toIgnore . contains ( marker ) ) return ; toIgnore . add ( marker ) ; saveIgnoredMarkers ( ) ; } private static void saveIgnoredMarkers ( ) { PrintWriter out = null ; try { out = new PrintWriter ( new FileWriter ( getConfigFile ( ) ) ) ; writeXML ( out ) ; } catch ( FileNotFoundException e ) { RubyCore . log ( e ) ; } catch ( IOException e ) { RubyCore . log ( e ) ; } finally { if ( out != null ) out . close ( ) ; } } private static void loadIgnoredMarkers ( ) { Reader fileReader = null ; try { fileReader = new FileReader ( getConfigFile ( ) ) ; XMLReader reader = SAXParserFactory . newInstance ( ) . newSAXParser ( ) . getXMLReader ( ) ; IgnoreMarkersContentHandler handler = new IgnoreMarkersContentHandler ( ) ; reader . setContentHandler ( handler ) ; reader . parse ( new InputSource ( fileReader ) ) ; toIgnore . clear ( ) ; Collection < IgnoreMarker > markers = handler . getIgnoreMarkers ( ) ; for ( IgnoreMarker marker : markers ) { toIgnore . add ( marker ) ; } } catch ( FileNotFoundException e ) { } catch ( Exception e ) { RubyCore . log ( e ) ; } finally { try { if ( fileReader != null ) fileReader . close ( ) ; } catch ( IOException e ) { } } } private static File getConfigFile ( ) { IPath rubyCoreMetadataDir = RubyCore . getPlugin ( ) . getStateLocation ( ) ; return rubyCoreMetadataDir . append ( "" ) . toFile ( ) ; } private static void writeXML ( PrintWriter out ) { out . println ( "" ) ; out . println ( tag ( IgnoreMarkersContentHandler . ROOT ) ) ; Iterator i = toIgnore . iterator ( ) ; while ( i . hasNext ( ) ) { IgnoreMarker s = ( IgnoreMarker ) i . next ( ) ; out . println ( tag ( IgnoreMarkersContentHandler . WARNING ) ) ; out . println ( tag ( IgnoreMarkersContentHandler . RESOURCE , s . getResource ( ) . getLocation ( ) . toPortableString ( ) ) ) ; out . println ( tag ( IgnoreMarkersContentHandler . ID , s . getId ( ) ) ) ; out . println ( tag ( IgnoreMarkersContentHandler . OFFSET , s . getOffset ( ) ) ) ; out . println ( tag ( IgnoreMarkersContentHandler . END_OFFSET , s . getEndOffset ( ) ) ) ; out . println ( endTag ( IgnoreMarkersContentHandler . WARNING ) ) ; } out . println ( endTag ( IgnoreMarkersContentHandler . ROOT ) ) ; out . flush ( ) ; } private static String tag ( String tag ) { return "" + tag + ">" ; } private static String endTag ( String tag ) { return "" + tag + ">" ; } private static String tag ( String tag , String content ) { return tag ( tag ) + content + endTag ( tag ) ; } private static String tag ( String tag , int intValue ) { return tag ( tag , Integer . toString ( intValue ) ) ; } } package org . rubypeople . rdt . internal . core . parser ; import org . jruby . ast . Node ; public class NextNodeFinder extends InOrderVisitor { @ Override public Object acceptNode ( Node node ) { if ( node != null && ! node . isInvisible ( ) ) throw new NodeFoundException ( node ) ; return null ; } public Node nextNode ( Node current ) { try { current . accept ( this ) ; } catch ( NodeFoundException e ) { return e . getNode ( ) ; } return null ; } } package org . rubypeople . rdt . internal . core . parser ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyModelMarker ; class IgnoreMarker { private IResource resource ; private int id ; private int offset ; private int endOffset ; IgnoreMarker ( IMarker marker ) throws CoreException { this . id = ( ( Integer ) marker . getAttribute ( IRubyModelMarker . ID ) ) . intValue ( ) ; this . offset = ( ( Integer ) marker . getAttribute ( IMarker . CHAR_START ) ) . intValue ( ) ; this . endOffset = ( ( Integer ) marker . getAttribute ( IMarker . CHAR_END ) ) . intValue ( ) ; this . resource = marker . getResource ( ) ; } public int getEndOffset ( ) { return endOffset ; } public int getOffset ( ) { return offset ; } public int getId ( ) { return id ; } public IResource getResource ( ) { return resource ; } IgnoreMarker ( IResource resource , int id , int offset , int endOffset ) { this . resource = resource ; this . id = id ; this . offset = offset ; this . endOffset = endOffset ; } @ Override public boolean equals ( Object obj ) { if ( obj == null ) return false ; if ( obj instanceof IgnoreMarker ) { IgnoreMarker other = ( IgnoreMarker ) obj ; return other . getId ( ) == getId ( ) && other . getOffset ( ) == getOffset ( ) && other . getEndOffset ( ) == getEndOffset ( ) && other . getResource ( ) . equals ( getResource ( ) ) ; } return false ; } @ Override public String toString ( ) { return "" + getResource ( ) . getLocation ( ) . toPortableString ( ) + "" + getId ( ) + "" + getOffset ( ) + "" + getEndOffset ( ) ; } } package org . rubypeople . rdt . internal . core . parser ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; abstract class DefaultProblem extends CategorizedProblem { private ISourcePosition position ; private String message ; private int id ; private String [ ] arguments ; private static final String MARKER_TYPE_PROBLEM = "" ; private static final String MARKER_TYPE_TASK = "" ; public DefaultProblem ( ISourcePosition position , String message , int problemID ) { this ( position , message , problemID , null ) ; } public DefaultProblem ( ISourcePosition position , String message , int problemID , String [ ] args ) { this . position = position ; this . message = message ; this . id = problemID ; this . arguments = args ; } public String getMessage ( ) { return message ; } public char [ ] getOriginatingFileName ( ) { return position . getFile ( ) . toCharArray ( ) ; } public int getSourceEnd ( ) { return position . getEndOffset ( ) ; } public int getSourceLineNumber ( ) { return position . getStartLine ( ) ; } public int getSourceStart ( ) { return position . getStartOffset ( ) ; } public String toString ( ) { return position . toString ( ) + "" + message ; } public int getID ( ) { return this . id ; } @ Override public String getMarkerType ( ) { return isTask ( ) ? MARKER_TYPE_TASK : MARKER_TYPE_PROBLEM ; } public String [ ] getArguments ( ) { return arguments ; } } package org . rubypeople . rdt . internal . core . parser ; import java . util . Collections ; import java . util . List ; import org . jruby . ast . CommentNode ; import org . jruby . ast . Node ; import org . jruby . parser . RubyParserResult ; import org . jruby . runtime . DynamicScope ; public class NullParserResult extends RubyParserResult { @ Override public Node getAST ( ) { return null ; } @ Override public List < Node > getBeginNodes ( ) { return Collections . emptyList ( ) ; } @ Override public int getEndOffset ( ) { return ; } @ Override public DynamicScope getScope ( ) { return null ; } @ Override public List < CommentNode > getCommentNodes ( ) { return Collections . emptyList ( ) ; } } package org . rubypeople . rdt . internal . core . parser ; import java . util . Map ; import java . util . StringTokenizer ; import org . eclipse . core . resources . IMarker ; import org . rubypeople . rdt . core . RubyCore ; public class AbstractTaskParser { protected boolean fCaseSensitive = false ; protected String [ ] fTags ; protected int [ ] fPriorities ; public AbstractTaskParser ( Map < String , String > preferences ) { super ( ) ; String caseSensitive = getString ( preferences , RubyCore . COMPILER_TASK_CASE_SENSITIVE , RubyCore . ENABLED ) ; if ( caseSensitive . equals ( RubyCore . ENABLED ) ) fCaseSensitive = true ; String tags = getString ( preferences , RubyCore . COMPILER_TASK_TAGS , RubyCore . DEFAULT_TASK_TAGS ) ; String priorities = getString ( preferences , RubyCore . COMPILER_TASK_PRIORITIES , RubyCore . DEFAULT_TASK_PRIORITIES ) ; fTags = tokenize ( tags , "" ) ; fPriorities = convertPriorities ( tokenize ( priorities , "" ) ) ; } protected String getString ( Map < String , String > preferences , String key , String def ) { if ( preferences == null ) return def ; String answer = preferences . get ( key ) ; if ( answer == null ) return def ; return answer ; } protected int [ ] convertPriorities ( String [ ] stringPriorities ) { int priorities [ ] = new int [ stringPriorities . length ] ; for ( int i = ; i < stringPriorities . length ; i ++ ) { String priority = stringPriorities [ i ] ; if ( priority . equals ( RubyCore . COMPILER_TASK_PRIORITY_LOW ) ) { priorities [ i ] = IMarker . PRIORITY_LOW ; } else if ( priority . equals ( RubyCore . COMPILER_TASK_PRIORITY_HIGH ) ) { priorities [ i ] = IMarker . PRIORITY_HIGH ; } else { priorities [ i ] = IMarker . PRIORITY_NORMAL ; } } return priorities ; } protected String [ ] tokenize ( String tags , String delim ) { String [ ] tokens ; StringTokenizer tokenizer = new StringTokenizer ( tags , delim ) ; tokens = new String [ tokenizer . countTokens ( ) ] ; int i = ; while ( tokenizer . hasMoreTokens ( ) ) { tokens [ i ++ ] = tokenizer . nextToken ( ) ; } return tokens ; } } package org . rubypeople . rdt . internal . core . parser ; import org . jruby . ast . Node ; public class NodeFoundException extends RuntimeException { private static final long serialVersionUID = - ; private Node node ; public NodeFoundException ( Node node ) { super ( ) ; this . node = node ; } public Node getNode ( ) { return node ; } } package org . rubypeople . rdt . internal . core . parser ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; public class ClosestNodeLocator extends InOrderVisitor { private int startOffset ; private int endOffset ; private int smallestDiff = Integer . MAX_VALUE ; private Node locatedNode ; private INodeAcceptor acceptor ; public Object handleNode ( Node iVisited ) { ISourcePosition position = iVisited . getPosition ( ) ; int diff = Integer . MAX_VALUE ; if ( position . getEndOffset ( ) < startOffset ) { diff = Math . abs ( startOffset - position . getEndOffset ( ) ) ; } else if ( position . getStartOffset ( ) > endOffset ) { diff = Math . abs ( position . getStartOffset ( ) - endOffset ) ; } else { diff = Math . abs ( position . getStartOffset ( ) - startOffset ) ; diff = Math . min ( diff , Math . abs ( position . getEndOffset ( ) - endOffset ) ) ; } if ( diff <= smallestDiff && acceptor . doesAccept ( iVisited ) ) { locatedNode = iVisited ; smallestDiff = diff ; } return super . handleNode ( iVisited ) ; } public Node getClosestNodeAtOffset ( Node ast , int startOffset ) { return getClosestNodeAtOffset ( ast , startOffset , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ! ( node instanceof NewlineNode ) ; } } ) ; } public Node getClosestNodeAtOffset ( Node ast , int startOffset , INodeAcceptor nodeAcceptor ) { return getClosestNode ( ast , startOffset , startOffset , nodeAcceptor ) ; } public Node getClosestNode ( Node ast , ISourcePosition pos ) { return getClosestNode ( ast , pos , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ! ( node instanceof NewlineNode ) ; } } ) ; } public Node getClosestNode ( Node ast , ISourcePosition pos , INodeAcceptor nodeAcceptor ) { return getClosestNode ( ast , pos . getStartOffset ( ) , pos . getEndOffset ( ) , nodeAcceptor ) ; } private Node getClosestNode ( Node ast , int startOffset , int endOffset , INodeAcceptor nodeAcceptor ) { this . startOffset = startOffset ; this . endOffset = endOffset ; this . acceptor = nodeAcceptor ; ast . accept ( this ) ; this . acceptor = null ; return locatedNode ; } } package org . rubypeople . rdt . internal . core . parser ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import java . util . Map ; import org . jruby . ast . CommentNode ; public class ASTTaskParser extends AbstractTaskParser { public ASTTaskParser ( Map < String , String > preferences ) { super ( preferences ) ; } public List < TaskTag > getTasks ( Collection < CommentNode > comments ) { List < TaskTag > tasks = new ArrayList < TaskTag > ( ) ; for ( CommentNode commentNode : comments ) { String line = commentNode . getContent ( ) ; if ( ! fCaseSensitive ) line = line . toLowerCase ( ) ; for ( int i = ; i < fTags . length ; i ++ ) { String tag = fTags [ i ] ; int priority = fPriorities [ i ] ; if ( ! fCaseSensitive ) tag = tag . toLowerCase ( ) ; int index = line . indexOf ( tag ) ; if ( index != - ) { String message = line . substring ( index ) . trim ( ) ; TaskTag task = new TaskTag ( new String ( message ) , priority , commentNode . getPosition ( ) . getStartLine ( ) , commentNode . getPosition ( ) . getStartOffset ( ) , commentNode . getPosition ( ) . getEndOffset ( ) ) ; tasks . add ( task ) ; } } } return tasks ; } } package org . rubypeople . rdt . internal . core . parser ; import org . jruby . ast . Node ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; public class ParentLocator extends InOrderVisitor { private Node root ; private Node child ; private Node parent ; private boolean parentFound ; private INodeAcceptor acceptor ; public ParentLocator ( Node root , Node lastBeforeOnSameLine ) { this . root = root ; this . child = lastBeforeOnSameLine ; } @ Override protected Object handleNode ( Node visited ) { if ( parentFound ) return null ; if ( visited . equals ( child ) ) { parentFound = true ; throw new NodeFoundException ( parent ) ; } else { if ( acceptor . doesAccept ( visited ) ) parent = visited ; } return null ; } public Node findParent ( INodeAcceptor nodeAcceptor ) { this . acceptor = nodeAcceptor ; this . parent = null ; try { root . accept ( this ) ; } catch ( NodeFoundException e ) { return e . getNode ( ) ; } finally { this . acceptor = null ; } return null ; } } package org . rubypeople . rdt . internal . core . parser ; import org . jruby . lexer . yacc . ISourcePosition ; public class Warning extends DefaultProblem { public Warning ( ISourcePosition position , String message ) { this ( position , message , - ) ; } public Warning ( ISourcePosition position , String message , int problemID ) { super ( position , message , problemID ) ; } public boolean isWarning ( ) { return true ; } } package org . rubypeople . rdt . internal . core . parser ; import java . util . Iterator ; import java . util . List ; import org . jruby . ast . AliasNode ; import org . jruby . ast . AndNode ; import org . jruby . ast . ArgsCatNode ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgsPushNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . AttrAssignNode ; import org . jruby . ast . BackRefNode ; import org . jruby . ast . BeginNode ; import org . jruby . ast . BignumNode ; import org . jruby . ast . BlockArgNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . BlockPassNode ; import org . jruby . ast . BreakNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . CaseNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . Colon3Node ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DRegexpNode ; import org . jruby . ast . DStrNode ; import org . jruby . ast . DSymbolNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DXStrNode ; import org . jruby . ast . DefinedNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . DotNode ; import org . jruby . ast . EnsureNode ; import org . jruby . ast . EvStrNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . FalseNode ; import org . jruby . ast . FixnumNode ; import org . jruby . ast . FlipNode ; import org . jruby . ast . FloatNode ; import org . jruby . ast . ForNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . IArgumentNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Match2Node ; import org . jruby . ast . Match3Node ; import org . jruby . ast . MatchNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . NextNode ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . NilNode ; import org . jruby . ast . Node ; import org . jruby . ast . NotNode ; import org . jruby . ast . NthRefNode ; import org . jruby . ast . OpAsgnAndNode ; import org . jruby . ast . OpAsgnNode ; import org . jruby . ast . OpAsgnOrNode ; import org . jruby . ast . OpElementAsgnNode ; import org . jruby . ast . OrNode ; import org . jruby . ast . PostExeNode ; import org . jruby . ast . RedoNode ; import org . jruby . ast . RegexpNode ; import org . jruby . ast . RescueBodyNode ; import org . jruby . ast . RescueNode ; import org . jruby . ast . RetryNode ; import org . jruby . ast . ReturnNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . jruby . ast . SValueNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . SplatNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . SuperNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . ToAryNode ; import org . jruby . ast . TrueNode ; import org . jruby . ast . UndefNode ; import org . jruby . ast . UntilNode ; import org . jruby . ast . VAliasNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . WhenNode ; import org . jruby . ast . WhileNode ; import org . jruby . ast . XStrNode ; import org . jruby . ast . YieldNode ; import org . jruby . ast . ZArrayNode ; import org . jruby . ast . ZSuperNode ; import org . rubypeople . rdt . core . parser . AbstractVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; public class InOrderVisitor extends AbstractVisitor { public Object visitAliasNode ( AliasNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitAndNode ( AndNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getFirstNode ( ) ) ; acceptNode ( iVisited . getSecondNode ( ) ) ; return null ; } public Object visitArgsNode ( ArgsNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getBlock ( ) ) ; if ( iVisited . getOptArgs ( ) != null ) { visitIter ( iVisited . getOptArgs ( ) . childNodes ( ) . iterator ( ) ) ; } return null ; } public Object visitArgsCatNode ( ArgsCatNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getFirstNode ( ) ) ; acceptNode ( iVisited . getSecondNode ( ) ) ; return null ; } public Object visitArrayNode ( ArrayNode iVisited ) { handleNode ( iVisited ) ; visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } private Object visitIter ( Iterator < Node > iterator ) { while ( iterator . hasNext ( ) ) { acceptNode ( iterator . next ( ) ) ; } return null ; } public Object visitBackRefNode ( BackRefNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitBeginNode ( BeginNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitBignumNode ( BignumNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitBlockArgNode ( BlockArgNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitBlockNode ( BlockNode iVisited ) { handleNode ( iVisited ) ; visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public Object visitBlockPassNode ( BlockPassNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitBreakNode ( BreakNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitConstDeclNode ( ConstDeclNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitClassVarAsgnNode ( ClassVarAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitClassVarDeclNode ( ClassVarDeclNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitClassVarNode ( ClassVarNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitCallNode ( CallNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; acceptNode ( iVisited . getIterNode ( ) ) ; return null ; } public Object visitCaseNode ( CaseNode iVisited ) { handleNode ( iVisited ) ; visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public Object visitClassNode ( ClassNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getSuperNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitColon2Node ( Colon2Node iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getLeftNode ( ) ) ; return null ; } public Object visitColon3Node ( Colon3Node iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitConstNode ( ConstNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitDAsgnNode ( DAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitDRegxNode ( DRegexpNode iVisited ) { handleNode ( iVisited ) ; visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public Object visitDStrNode ( DStrNode iVisited ) { handleNode ( iVisited ) ; visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public Object visitDSymbolNode ( DSymbolNode iVisited ) { handleNode ( iVisited ) ; visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public Object visitDVarNode ( DVarNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitDXStrNode ( DXStrNode iVisited ) { handleNode ( iVisited ) ; visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public Object visitDefinedNode ( DefinedNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getExpressionNode ( ) ) ; return null ; } public Object visitDefnNode ( DefnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitDefsNode ( DefsNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitDotNode ( DotNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getBeginNode ( ) ) ; acceptNode ( iVisited . getEndNode ( ) ) ; return null ; } public Object visitEnsureNode ( EnsureNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getEnsureNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitEvStrNode ( EvStrNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getBody ( ) ) ; return null ; } public Object visitFCallNode ( FCallNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; acceptNode ( iVisited . getIterNode ( ) ) ; return null ; } public Object visitFalseNode ( FalseNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitFixnumNode ( FixnumNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitFlipNode ( FlipNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getBeginNode ( ) ) ; acceptNode ( iVisited . getEndNode ( ) ) ; return null ; } public Object visitFloatNode ( FloatNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitForNode ( ForNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getVarNode ( ) ) ; acceptNode ( iVisited . getIterNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitGlobalAsgnNode ( GlobalAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitGlobalVarNode ( GlobalVarNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitHashNode ( HashNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getListNode ( ) ) ; return null ; } public Object visitInstAsgnNode ( InstAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitInstVarNode ( InstVarNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitIfNode ( IfNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getCondition ( ) ) ; acceptNode ( iVisited . getThenBody ( ) ) ; acceptNode ( iVisited . getElseBody ( ) ) ; return null ; } public Object visitIterNode ( IterNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getVarNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitLocalVarNode ( LocalVarNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitMultipleAsgnNode ( MultipleAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getHeadNode ( ) ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitMatch2Node ( Match2Node iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitMatch3Node ( Match3Node iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitMatchNode ( MatchNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getRegexpNode ( ) ) ; return null ; } public Object visitModuleNode ( ModuleNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitNewlineNode ( NewlineNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getNextNode ( ) ) ; return null ; } public Object visitNextNode ( NextNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitNilNode ( NilNode iVisited ) { if ( ! ( iVisited instanceof NilImplicitNode ) ) { handleNode ( iVisited ) ; } return null ; } public Object visitNotNode ( NotNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getConditionNode ( ) ) ; return null ; } public Object visitNthRefNode ( NthRefNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitOpElementAsgnNode ( OpElementAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitOpAsgnNode ( OpAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitOpAsgnAndNode ( OpAsgnAndNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getFirstNode ( ) ) ; acceptNode ( iVisited . getSecondNode ( ) ) ; return null ; } public Object visitOpAsgnOrNode ( OpAsgnOrNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getFirstNode ( ) ) ; acceptNode ( iVisited . getSecondNode ( ) ) ; return null ; } public Object visitOrNode ( OrNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getFirstNode ( ) ) ; acceptNode ( iVisited . getSecondNode ( ) ) ; return null ; } public Object visitPostExeNode ( PostExeNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitRedoNode ( RedoNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitRegexpNode ( RegexpNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitRescueBodyNode ( RescueBodyNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getExceptionNodes ( ) ) ; acceptNode ( iVisited . getOptRescueNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitRescueNode ( RescueNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getRescueNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; acceptNode ( iVisited . getElseNode ( ) ) ; return null ; } public Object visitRetryNode ( RetryNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitReturnNode ( ReturnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitSClassNode ( SClassNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitSelfNode ( SelfNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitSplatNode ( SplatNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValue ( ) ) ; return null ; } public Object visitStrNode ( StrNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitSuperNode ( SuperNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; return null ; } public Object visitSValueNode ( SValueNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValue ( ) ) ; return null ; } public Object visitSymbolNode ( SymbolNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitToAryNode ( ToAryNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getValue ( ) ) ; return null ; } public Object visitTrueNode ( TrueNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitUndefNode ( UndefNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitUntilNode ( UntilNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getConditionNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitVAliasNode ( VAliasNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitVCallNode ( VCallNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitWhenNode ( WhenNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getExpressionNodes ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; acceptNode ( iVisited . getNextCase ( ) ) ; return null ; } public Object visitWhileNode ( WhileNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getConditionNode ( ) ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitXStrNode ( XStrNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitYieldNode ( YieldNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; return null ; } public Object visitZArrayNode ( ZArrayNode iVisited ) { handleNode ( iVisited ) ; return null ; } public Object visitZSuperNode ( ZSuperNode iVisited ) { handleNode ( iVisited ) ; return null ; } protected Object handleNode ( Node visited ) { return visitNode ( visited ) ; } public Object visitRootNode ( RootNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitArgsPushNode ( ArgsPushNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getFirstNode ( ) ) ; acceptNode ( iVisited . getSecondNode ( ) ) ; return null ; } public Object visitAttrAssignNode ( AttrAssignNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; acceptNode ( iVisited . getArgsNode ( ) ) ; return null ; } @ Override protected Object visitNode ( Node iVisited ) { return null ; } protected List < String > getArgumentsFromFunctionCall ( IArgumentNode iVisited ) { return ASTUtil . getArgumentsFromFunctionCall ( iVisited ) ; } } package org . rubypeople . rdt . internal . core . parser ; import java . util . List ; import org . jruby . ast . BlockNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . CommentNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . parser . RubyParserResult ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; public class RubyParserWithComments extends RubyParser { @ Override protected void postProcessResult ( RubyParserResult result ) { super . postProcessResult ( result ) ; associateCommentsWithNodes ( result . getAST ( ) , result . getCommentNodes ( ) ) ; } private void associateCommentsWithNodes ( Node ast , List < CommentNode > commentNodes ) { for ( CommentNode commentNode : commentNodes ) { final ISourcePosition pos = commentNode . getPosition ( ) ; Node closestOnSameLine = new ClosestNodeLocator ( ) . getClosestNode ( ast , pos , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( node instanceof NewlineNode || node instanceof RootNode ) return false ; return ( node . getPosition ( ) . getEndLine ( ) == pos . getStartLine ( ) ) || ( node . getPosition ( ) . getStartLine ( ) == pos . getStartLine ( ) ) ; } } ) ; if ( closestOnSameLine == null ) { Node next = new ClosestNodeLocator ( ) . getClosestNode ( ast , pos , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( node instanceof NewlineNode ) return false ; return node . getPosition ( ) . getStartOffset ( ) > pos . getStartOffset ( ) ; } } ) ; if ( next != null ) { Node surroundingScopeOfComment = getSurroundingScopeNode ( ast , pos ) ; Node surroundingScopeOfNext = getSurroundingScopeNode ( ast , next . getPosition ( ) ) ; if ( surroundingScopeOfComment . equals ( surroundingScopeOfNext ) ) { next . addComment ( commentNode ) ; } else { surroundingScopeOfComment . addComment ( commentNode ) ; } continue ; } else { Node surroundingScopeOfComment = getSurroundingScopeNode ( ast , pos ) ; surroundingScopeOfComment . addComment ( commentNode ) ; } } else { Node unwrapped = unwrap ( ast , closestOnSameLine , pos . getStartLine ( ) ) ; if ( unwrapped != null ) unwrapped . addComment ( commentNode ) ; } } } private Node getSurroundingScopeNode ( Node ast , final ISourcePosition pos ) { Node result = new ClosestNodeLocator ( ) . getClosestNode ( ast , pos , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { if ( ! ( node instanceof ClassNode || node instanceof ModuleNode || node instanceof DefnNode || node instanceof DefsNode || node instanceof IterNode || node instanceof RootNode ) ) return false ; return node . getPosition ( ) . getEndLine ( ) > pos . getEndLine ( ) && node . getPosition ( ) . getStartLine ( ) < pos . getStartLine ( ) ; } } ) ; if ( result == null ) return ast ; return result ; } private Node unwrap ( Node ast , Node closest , final int line ) { while ( true ) { Node last = closest ; closest = new ParentLocator ( ast , closest ) . findParent ( new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return ! ( node instanceof NewlineNode ) && ! ( node instanceof BlockNode ) && ! ( node instanceof RootNode ) && ( node . getPosition ( ) . getEndLine ( ) == line || node . getPosition ( ) . getStartLine ( ) == line ) ; } } ) ; if ( closest == null ) { return last ; } } } } package org . rubypeople . rdt . internal . core . parser ; import java . io . IOException ; import java . io . Reader ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . RubyCore ; public class TaskParser extends AbstractTaskParser { public TaskParser ( Map < String , String > preferences ) { super ( preferences ) ; } public List < TaskTag > getTasks ( Reader reader ) throws IOException { return getTasks ( loadFromReader ( reader ) ) ; } public List < TaskTag > getTasks ( String contents ) { List < TaskTag > tasks = new ArrayList < TaskTag > ( ) ; try { if ( fTags . length <= ) return Collections . emptyList ( ) ; int offset = ; int lineNum = ; String line = null ; while ( ( line = findNextLine ( contents , offset ) ) != null ) { tasks . addAll ( processLine ( line , offset , lineNum ) ) ; lineNum ++ ; offset += line . length ( ) ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } return tasks ; } private String findNextLine ( String contents , int offset ) { if ( offset >= contents . length ( ) ) return null ; int crPos = contents . indexOf ( '' , offset ) ; int nlPos = contents . indexOf ( '' , offset ) ; int eolPos = crPos ; if ( crPos == - ) eolPos = nlPos ; if ( nlPos == - && crPos == - ) return contents . substring ( offset ) ; if ( crPos + == nlPos && crPos >= ) { eolPos ++ ; } return contents . substring ( offset , eolPos + ) ; } private List < TaskTag > processLine ( String line , int offset , int lineNum ) throws CoreException { List < TaskTag > tasks = new ArrayList < TaskTag > ( ) ; if ( ! fCaseSensitive ) line = line . toLowerCase ( ) ; for ( int i = ; i < fTags . length ; i ++ ) { String tag = fTags [ i ] ; int priority = fPriorities [ i ] ; if ( ! fCaseSensitive ) tag = tag . toLowerCase ( ) ; if ( line . matches ( "" + tag + "" ) ) { int index = line . indexOf ( tag ) ; String message = line . substring ( index ) . trim ( ) ; tasks . add ( createTaskTag ( priority , new String ( message ) , lineNum + , offset + index , offset + index + message . length ( ) ) ) ; } } return tasks ; } private TaskTag createTaskTag ( int priority , String message , int lineNumber , int start , int end ) throws CoreException { return new TaskTag ( message , priority , lineNumber , start , end ) ; } private String loadFromReader ( Reader reader ) throws IOException { StringBuffer contents = new StringBuffer ( ) ; char [ ] buffer = new char [ ] ; while ( true ) { int bytesRead = reader . read ( buffer ) ; if ( bytesRead == - ) return contents . toString ( ) ; contents . append ( buffer , , bytesRead ) ; } } } package org . rubypeople . rdt . internal . core . parser ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . rubypeople . rdt . core . compiler . IProblem ; public class TaskTag extends DefaultProblem implements IProblem { private int priority ; public TaskTag ( String message , int priority , int lineNumber , int start , int end ) { super ( new IDESourcePosition ( "" , lineNumber , lineNumber , start , end ) , message , IProblem . Task ) ; this . priority = priority ; } public int getPriority ( ) { return priority ; } public boolean isTask ( ) { return true ; } } package org . rubypeople . rdt . internal . core . parser ; import java . util . ArrayList ; import java . util . Collection ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . xml . sax . Attributes ; import org . xml . sax . ContentHandler ; import org . xml . sax . Locator ; import org . xml . sax . SAXException ; public class IgnoreMarkersContentHandler implements ContentHandler { public static final String ID = "" ; public static final String OFFSET = "" ; public static final String END_OFFSET = "" ; public static final String RESOURCE = "" ; public static final String WARNING = "" ; public static final String ROOT = "" ; private StringBuffer data ; private Collection < IgnoreMarker > markers ; private int id ; private int offset ; private int endOffset ; private IResource resource ; public void endDocument ( ) throws SAXException { } public void startDocument ( ) throws SAXException { markers = new ArrayList < IgnoreMarker > ( ) ; } public void characters ( char [ ] ch , int start , int length ) throws SAXException { for ( int i = start ; i < start + length ; i ++ ) { data . append ( ch [ i ] ) ; } } public void ignorableWhitespace ( char [ ] ch , int start , int length ) throws SAXException { } public void endPrefixMapping ( String prefix ) throws SAXException { } public void skippedEntity ( String name ) throws SAXException { } public void setDocumentLocator ( Locator locator ) { } public void processingInstruction ( String target , String data ) throws SAXException { } public void startPrefixMapping ( String prefix , String uri ) throws SAXException { } public void endElement ( String namespaceURI , String localName , String qName ) throws SAXException { if ( qName . equals ( RESOURCE ) ) { IPath proj = Path . fromPortableString ( data . toString ( ) ) ; resource = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFileForLocation ( proj ) ; } else if ( qName . equals ( ID ) ) { id = Integer . parseInt ( data . toString ( ) ) ; } else if ( qName . equals ( OFFSET ) ) { offset = Integer . parseInt ( data . toString ( ) ) ; } else if ( qName . equals ( END_OFFSET ) ) { endOffset = Integer . parseInt ( data . toString ( ) ) ; } else if ( qName . equals ( WARNING ) ) { if ( resource != null ) markers . add ( new IgnoreMarker ( resource , id , offset , endOffset ) ) ; } } public void startElement ( String namespaceURI , String localName , String qName , Attributes atts ) throws SAXException { data = new StringBuffer ( ) ; } public Collection < IgnoreMarker > getIgnoreMarkers ( ) { return markers ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRegion ; import org . rubypeople . rdt . core . IRubyElement ; public class Region implements IRegion { protected ArrayList < IRubyElement > fRootElements ; public Region ( ) { fRootElements = new ArrayList < IRubyElement > ( ) ; } public void add ( IRubyElement element ) { if ( ! contains ( element ) ) { removeAllChildren ( element ) ; fRootElements . add ( element ) ; fRootElements . trimToSize ( ) ; } } public boolean contains ( IRubyElement element ) { int size = fRootElements . size ( ) ; ArrayList < IRubyElement > parents = getAncestors ( element ) ; for ( int i = ; i < size ; i ++ ) { IRubyElement aTop = fRootElements . get ( i ) ; if ( aTop . equals ( element ) ) { return true ; } for ( int j = , pSize = parents . size ( ) ; j < pSize ; j ++ ) { if ( aTop . equals ( parents . get ( j ) ) ) { return true ; } } } return false ; } private ArrayList < IRubyElement > getAncestors ( IRubyElement element ) { ArrayList < IRubyElement > parents = new ArrayList < IRubyElement > ( ) ; IRubyElement parent = element . getParent ( ) ; while ( parent != null ) { parents . add ( parent ) ; parent = parent . getParent ( ) ; } parents . trimToSize ( ) ; return parents ; } public IRubyElement [ ] getElements ( ) { int size = fRootElements . size ( ) ; IRubyElement [ ] roots = new IRubyElement [ size ] ; for ( int i = ; i < size ; i ++ ) { roots [ i ] = ( IRubyElement ) fRootElements . get ( i ) ; } return roots ; } public boolean remove ( IRubyElement element ) { removeAllChildren ( element ) ; return fRootElements . remove ( element ) ; } protected void removeAllChildren ( IRubyElement element ) { if ( element instanceof IParent ) { ArrayList < IRubyElement > newRootElements = new ArrayList < IRubyElement > ( ) ; for ( int i = , size = fRootElements . size ( ) ; i < size ; i ++ ) { IRubyElement currentRoot = fRootElements . get ( i ) ; IRubyElement parent = currentRoot . getParent ( ) ; boolean isChild = false ; while ( parent != null ) { if ( parent . equals ( element ) ) { isChild = true ; break ; } parent = parent . getParent ( ) ; } if ( ! isChild ) { newRootElements . add ( currentRoot ) ; } } fRootElements = newRootElements ; } } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; IRubyElement [ ] roots = getElements ( ) ; buffer . append ( '' ) ; for ( int i = ; i < roots . length ; i ++ ) { buffer . append ( roots [ i ] . getElementName ( ) ) ; if ( i < ( roots . length - ) ) { buffer . append ( "" ) ; } } buffer . append ( '' ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core ; public class ExternalSourceFolderRootInfo extends SourceFolderRootInfo { public Object [ ] getNonRubyResources ( ) { fNonRubyResources = NO_NON_RUBY_RESOURCES ; return fNonRubyResources ; } } package org . rubypeople . rdt . internal . core ; import java . util . HashMap ; import java . util . Iterator ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SafeRunner ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IProblemRequestor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . CompilationParticipant ; import org . rubypeople . rdt . core . compiler . ReconcileContext ; import org . rubypeople . rdt . internal . core . parser . MarkerUtility ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class ReconcileWorkingCopyOperation extends RubyModelOperation { public static boolean PERF = false ; boolean createAST ; boolean forceProblemDetection ; WorkingCopyOwner workingCopyOwner ; public RootNode ast ; public RubyElementDeltaBuilder deltaBuilder ; public HashMap problems ; public ReconcileWorkingCopyOperation ( IRubyElement workingCopy , boolean forceProblemDetection , WorkingCopyOwner workingCopyOwner ) { super ( new IRubyElement [ ] { workingCopy } ) ; this . forceProblemDetection = forceProblemDetection ; this . workingCopyOwner = workingCopyOwner ; } protected void executeOperation ( ) throws RubyModelException { if ( this . progressMonitor != null ) { if ( this . progressMonitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; this . progressMonitor . beginTask ( Messages . element_reconciling , ) ; } RubyScript workingCopy = getWorkingCopy ( ) ; boolean wasConsistent = workingCopy . isConsistent ( ) ; IProblemRequestor problemRequestor = workingCopy . getPerWorkingCopyInfo ( ) ; this . deltaBuilder = new RubyElementDeltaBuilder ( workingCopy ) ; makeConsistent ( workingCopy , problemRequestor ) ; notifyParticipants ( workingCopy ) ; if ( this . problems != null && ( this . forceProblemDetection || ! wasConsistent ) ) { try { problemRequestor . beginReporting ( ) ; for ( Iterator iteraror = this . problems . values ( ) . iterator ( ) ; iteraror . hasNext ( ) ; ) { CategorizedProblem [ ] categorizedProblems = ( CategorizedProblem [ ] ) iteraror . next ( ) ; if ( categorizedProblems == null ) continue ; for ( int i = , length = categorizedProblems . length ; i < length ; i ++ ) { CategorizedProblem problem = categorizedProblems [ i ] ; if ( RubyModelManager . VERBOSE ) { System . out . println ( "" + problem . getMessage ( ) ) ; } if ( this . progressMonitor != null && this . progressMonitor . isCanceled ( ) ) break ; if ( ! MarkerUtility . ignoring ( workingCopy . getResource ( ) , problem . getID ( ) , problem . getSourceStart ( ) , problem . getSourceEnd ( ) ) ) problemRequestor . acceptProblem ( problem ) ; } } } finally { problemRequestor . endReporting ( ) ; } } try { RubyElementDelta delta = this . deltaBuilder . delta ; if ( delta != null ) { addReconcileDelta ( workingCopy , delta ) ; } } finally { if ( this . progressMonitor != null ) this . progressMonitor . done ( ) ; } } public RootNode makeConsistent ( RubyScript workingCopy , IProblemRequestor problemRequestor ) throws RubyModelException { if ( ! workingCopy . isConsistent ( ) ) { if ( this . problems == null ) this . problems = new HashMap ( ) ; this . ast = workingCopy . makeConsistent ( true , this . problems , this . progressMonitor ) ; this . deltaBuilder . buildDeltas ( ) ; if ( this . ast != null && this . deltaBuilder . delta != null ) this . deltaBuilder . delta . changedAST ( this . ast ) ; return this . ast ; } if ( this . ast != null ) return this . ast ; if ( this . forceProblemDetection ) { if ( RubyProject . hasRubyNature ( workingCopy . getRubyProject ( ) . getProject ( ) ) ) { HashMap problemMap ; if ( this . problems == null ) { problemMap = new HashMap ( ) ; if ( this . forceProblemDetection ) this . problems = problemMap ; } else problemMap = this . problems ; char [ ] contents = workingCopy . getContents ( ) ; this . ast = RubyScriptProblemFinder . process ( workingCopy , contents , problemMap , this . progressMonitor ) ; if ( this . ast != null ) { this . deltaBuilder . delta = new RubyElementDelta ( workingCopy ) ; this . deltaBuilder . delta . changedAST ( this . ast ) ; } if ( this . progressMonitor != null ) this . progressMonitor . worked ( ) ; } return this . ast ; } return null ; } protected RubyScript getWorkingCopy ( ) { return ( RubyScript ) getElementToProcess ( ) ; } public boolean isReadOnly ( ) { return true ; } protected IRubyModelStatus verify ( ) { IRubyModelStatus status = super . verify ( ) ; if ( ! status . isOK ( ) ) { return status ; } RubyScript workingCopy = getWorkingCopy ( ) ; if ( ! workingCopy . isWorkingCopy ( ) ) { return new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST , workingCopy ) ; } return status ; } private void notifyParticipants ( final RubyScript workingCopy ) { IRubyProject rubyProject = getWorkingCopy ( ) . getRubyProject ( ) ; CompilationParticipant [ ] participants = RubyModelManager . getRubyModelManager ( ) . compilationParticipants . getCompilationParticipants ( rubyProject ) ; if ( participants == null ) return ; final ReconcileContext context = new ReconcileContext ( this , workingCopy ) ; for ( int i = , length = participants . length ; i < length ; i ++ ) { final CompilationParticipant participant = participants [ i ] ; SafeRunner . run ( new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { if ( exception instanceof Error ) { throw ( Error ) exception ; } else if ( exception instanceof OperationCanceledException ) throw ( OperationCanceledException ) exception ; else if ( exception instanceof UnsupportedOperationException ) { Util . log ( exception , "" ) ; } else Util . log ( exception , "" ) ; } public void run ( ) throws Exception { participant . reconcile ( context ) ; } } ) ; } } } package org . rubypeople . rdt . internal . core ; public class ExternalSourceFolderInfo extends SourceFolderInfo { Object [ ] getNonRubyResources ( ) { return this . nonRubyResources ; } } package org . rubypeople . rdt . internal . core ; public class OpenableElementInfo extends RubyElementInfo { } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; public abstract class Member extends SourceRefElement implements IMember { protected Member ( RubyElement parent ) { super ( parent ) ; } protected static boolean areSimilarMethods ( String name1 , String [ ] params1 , String name2 , String [ ] params2 , String [ ] simpleNames1 ) { if ( name1 . equals ( name2 ) ) { int params1Length = params1 . length ; if ( params1Length == params2 . length ) { return true ; } } return false ; } public IType getDeclaringType ( ) { RubyElement parentElement = ( RubyElement ) getParent ( ) ; if ( parentElement . getElementType ( ) == TYPE ) { return ( IType ) parentElement ; } return null ; } public Member getOuterMostLocalContext ( ) { IRubyElement current = this ; Member lastLocalContext = null ; parentLoop : while ( true ) { switch ( current . getElementType ( ) ) { case SCRIPT : break parentLoop ; case TYPE : break ; case CLASS_VAR : case INSTANCE_VAR : case METHOD : lastLocalContext = ( Member ) current ; break ; } current = current . getParent ( ) ; } return lastLocalContext ; } public ISourceRange getNameRange ( ) throws RubyModelException { MemberElementInfo info = ( MemberElementInfo ) getElementInfo ( ) ; return new SourceRange ( info . getNameSourceStart ( ) , info . getNameSourceEnd ( ) - info . getNameSourceStart ( ) + ) ; } public IType getType ( String typeName , int count ) { RubyType type = new RubyType ( this , typeName ) ; type . occurrenceCount = count ; return type ; } public String readableName ( ) { IRubyElement declaringType = getDeclaringType ( ) ; if ( declaringType != null ) { String declaringName = ( ( RubyElement ) getDeclaringType ( ) ) . readableName ( ) ; StringBuffer buffer = new StringBuffer ( declaringName ) ; buffer . append ( "" ) ; buffer . append ( this . getElementName ( ) ) ; return buffer . toString ( ) ; } return super . readableName ( ) ; } protected void updateNameRange ( int nameStart , int nameEnd ) { try { MemberElementInfo info = ( MemberElementInfo ) getElementInfo ( ) ; info . setNameSourceStart ( nameStart ) ; info . setNameSourceEnd ( nameEnd ) ; } catch ( RubyModelException npe ) { return ; } } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner workingCopyOwner ) { switch ( token . charAt ( ) ) { case JEM_COUNT : return getHandleUpdatingCountFromMemento ( memento , workingCopyOwner ) ; case JEM_TYPE : String typeName ; if ( memento . hasMoreTokens ( ) ) { typeName = memento . nextToken ( ) ; char firstChar = typeName . charAt ( ) ; if ( firstChar == JEM_FIELD || firstChar == JEM_METHOD || firstChar == JEM_TYPE || firstChar == JEM_COUNT ) { token = typeName ; typeName = "" ; } else { token = null ; } } else { typeName = "" ; token = null ; } RubyElement type = ( RubyElement ) getType ( typeName , ) ; if ( token == null ) { return type . getHandleFromMemento ( memento , workingCopyOwner ) ; } else { return type . getHandleFromMemento ( token , memento , workingCopyOwner ) ; } } return null ; } protected char getHandleMementoDelimiter ( ) { return RubyElement . JEM_TYPE ; } } package org . rubypeople . rdt . internal . core ; import java . util . HashSet ; import java . util . Set ; public class RubyMethodElementInfo extends MemberElementInfo { protected String selector ; protected int visibility ; private Set < String > blockVars = new HashSet < String > ( ) ; protected String [ ] argumentNames ; private boolean isSingleton ; public String [ ] getArgumentNames ( ) { return this . argumentNames ; } public String getSelector ( ) { return this . selector ; } public int getVisibility ( ) { return this . visibility ; } protected void setVisibility ( int visibility ) { this . visibility = visibility ; } public boolean isConstructor ( ) { return selector == "" ; } protected void setArgumentNames ( String [ ] names ) { this . argumentNames = names ; } protected void setIsSingleton ( boolean b ) { isSingleton = b ; } public boolean isSingleton ( ) { return isSingleton || isConstructor ( ) ; } public void addBlockVar ( String name ) { blockVars . add ( name ) ; } public String [ ] getBlockVars ( ) { return blockVars . toArray ( new String [ blockVars . size ( ) ] ) ; } } package org . rubypeople . rdt . internal . core ; import java . io . File ; import java . util . ArrayList ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Util ; public class ExternalSourceFolderRoot extends SourceFolderRoot implements ISourceFolderRoot { protected final IPath folderPath ; protected ExternalSourceFolderRoot ( IPath resource , RubyProject project ) { super ( null , project ) ; this . folderPath = resource ; } public String getElementName ( ) { return this . folderPath . toPortableString ( ) ; } public Object [ ] getNonRubyResources ( ) throws RubyModelException { return ( ( ExternalSourceFolder ) getSourceFolder ( CharOperation . NO_STRINGS ) ) . storedNonRubyResources ( ) ; } @ Override protected boolean computeChildren ( OpenableElementInfo info , Map newElements ) throws RubyModelException { try { Object target = RubyModel . getTarget ( this . folderPath , false ) ; if ( target instanceof File ) { ArrayList < ISourceFolder > vChildren = new ArrayList < ISourceFolder > ( ) ; computeFolderChildren ( ( File ) target , CharOperation . NO_STRINGS , vChildren ) ; IRubyElement [ ] children = new IRubyElement [ vChildren . size ( ) ] ; vChildren . toArray ( children ) ; info . setChildren ( children ) ; for ( int i = ; i < children . length ; i ++ ) { ExternalSourceFolder packFrag = ( ExternalSourceFolder ) children [ i ] ; ExternalSourceFolderInfo fragInfo = new ExternalSourceFolderInfo ( ) ; packFrag . computeChildren ( fragInfo ) ; newElements . put ( packFrag , fragInfo ) ; } } } catch ( RubyModelException e ) { info . setChildren ( new IRubyElement [ ] { } ) ; throw e ; } return true ; } protected void computeFolderChildren ( File folder , String [ ] pkgName , ArrayList < ISourceFolder > vChildren ) throws RubyModelException { ISourceFolder pkg = getSourceFolder ( pkgName ) ; vChildren . add ( pkg ) ; try { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; File [ ] members = folder . listFiles ( ) ; if ( members == null ) return ; for ( int i = , max = members . length ; i < max ; i ++ ) { File member = members [ i ] ; String memberName = member . getName ( ) ; if ( member . isDirectory ( ) ) { String [ ] newNames = Util . arrayConcat ( pkgName , manager . intern ( memberName ) ) ; computeFolderChildren ( member , newNames , vChildren ) ; } else if ( member . isFile ( ) ) { } } } catch ( IllegalArgumentException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } public SourceFolder getSourceFolder ( String [ ] pkgName ) { return new ExternalSourceFolder ( this , pkgName ) ; } @ Override public IPath getPath ( ) { return folderPath ; } @ Override public boolean isExternal ( ) { return true ; } public int hashCode ( ) { return this . folderPath . hashCode ( ) ; } @ Override public boolean isReadOnly ( ) { return true ; } public boolean equals ( Object o ) { if ( this == o ) return true ; if ( o instanceof ExternalSourceFolderRoot ) { ExternalSourceFolderRoot other = ( ExternalSourceFolderRoot ) o ; return this . folderPath . equals ( other . folderPath ) ; } return false ; } public IResource getUnderlyingResource ( ) throws RubyModelException { if ( isExternal ( ) ) { if ( ! exists ( ) ) throw newNotPresentException ( ) ; return null ; } return super . getUnderlyingResource ( ) ; } protected Object createElementInfo ( ) { return new ExternalSourceFolderRootInfo ( ) ; } public IResource getResource ( ) { if ( this . resource == null ) { this . resource = RubyModel . getTarget ( this . folderPath , false ) ; } if ( this . resource instanceof IResource ) { return super . getResource ( ) ; } return null ; } @ Override protected IStatus validateOnLoadpath ( ) { return Status . OK_STATUS ; } protected boolean resourceExists ( ) { if ( this . isExternal ( ) ) { return RubyModel . getTarget ( this . getPath ( ) , true ) != null ; } return super . resourceExists ( ) ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . Map ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; import org . rubypeople . rdt . internal . core . util . Util ; public class SourceFolderRoot extends Openable implements ISourceFolderRoot { protected Object resource ; protected SourceFolderRoot ( IResource resource , RubyProject project ) { super ( project ) ; this . resource = resource ; } public boolean hasChildren ( ) throws RubyModelException { return true ; } @ Override protected boolean buildStructure ( OpenableElementInfo info , IProgressMonitor pm , Map newElements , IResource underlyingResource ) throws RubyModelException { IStatus status = validateOnLoadpath ( ) ; if ( ! resourceExists ( ) ) throw newNotPresentException ( ) ; return computeChildren ( info , newElements ) ; } public boolean equals ( Object o ) { if ( this == o ) return true ; if ( ! ( o instanceof SourceFolderRoot ) ) return false ; SourceFolderRoot other = ( SourceFolderRoot ) o ; return this . resource . equals ( other . resource ) && this . parent . equals ( other . parent ) ; } protected IStatus validateOnLoadpath ( ) { IPath path = this . getPath ( ) ; try { RubyProject project = ( RubyProject ) getRubyProject ( ) ; ILoadpathEntry [ ] classpath = project . getResolvedLoadpath ( true , false , false ) ; for ( int i = , length = classpath . length ; i < length ; i ++ ) { ILoadpathEntry entry = classpath [ i ] ; if ( entry . getPath ( ) . equals ( path ) ) { return Status . OK_STATUS ; } } } catch ( RubyModelException e ) { return e . getRubyModelStatus ( ) ; } return new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_NOT_ON_CLASSPATH , this ) ; } public char [ ] [ ] fullExclusionPatternChars ( ) { try { LoadpathEntry entry = ( LoadpathEntry ) getRawLoadpathEntry ( ) ; if ( entry == null ) { return null ; } else { return entry . fullExclusionPatternChars ( ) ; } } catch ( RubyModelException e ) { return null ; } } public ILoadpathEntry getRawLoadpathEntry ( ) throws RubyModelException { ILoadpathEntry rawEntry = null ; RubyProject project = ( RubyProject ) this . getRubyProject ( ) ; project . getResolvedLoadpath ( true , false , false ) ; RubyModelManager . PerProjectInfo perProjectInfo = project . getPerProjectInfo ( ) ; if ( perProjectInfo != null && perProjectInfo . resolvedPathToRawEntries != null ) { rawEntry = ( ILoadpathEntry ) perProjectInfo . resolvedPathToRawEntries . get ( this . getPath ( ) ) ; } return rawEntry ; } public char [ ] [ ] fullInclusionPatternChars ( ) { try { LoadpathEntry entry = ( LoadpathEntry ) getRawLoadpathEntry ( ) ; if ( entry == null ) { return null ; } else { return entry . fullInclusionPatternChars ( ) ; } } catch ( RubyModelException e ) { return null ; } } protected boolean computeChildren ( OpenableElementInfo info , Map newElements ) throws RubyModelException { try { IResource underlyingResource = getResource ( ) ; if ( underlyingResource . getType ( ) == IResource . FOLDER || underlyingResource . getType ( ) == IResource . PROJECT ) { ArrayList vChildren = new ArrayList ( ) ; IContainer rootFolder = ( IContainer ) underlyingResource ; computeFolderChildren ( rootFolder , CharOperation . NO_STRINGS , vChildren ) ; IRubyElement [ ] children = new IRubyElement [ vChildren . size ( ) ] ; vChildren . toArray ( children ) ; info . setChildren ( children ) ; } } catch ( RubyModelException e ) { info . setChildren ( new IRubyElement [ ] { } ) ; throw e ; } return true ; } @ Override protected Object createElementInfo ( ) { return new SourceFolderRootInfo ( ) ; } @ Override public int getElementType ( ) { return IRubyElement . SOURCE_FOLDER_ROOT ; } public String getElementName ( ) { if ( this . resource instanceof IFolder ) return ( ( IFolder ) this . resource ) . getName ( ) ; return "" ; } public ISourceFolder createSourceFolder ( String names , boolean force , IProgressMonitor monitor ) throws RubyModelException { CreateSourceFolderOperation op = new CreateSourceFolderOperation ( this , names , force ) ; op . runOperation ( monitor ) ; return getSourceFolder ( op . pkgName ) ; } protected void computeFolderChildren ( IContainer folder , String [ ] pkgName , ArrayList vChildren ) throws RubyModelException { ISourceFolder pkg = getSourceFolder ( pkgName ) ; vChildren . add ( pkg ) ; try { RubyProject rubyProject = ( RubyProject ) getRubyProject ( ) ; RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; IResource [ ] members = folder . members ( ) ; for ( int i = , max = members . length ; i < max ; i ++ ) { IResource member = members [ i ] ; String memberName = member . getName ( ) ; switch ( member . getType ( ) ) { case IResource . FOLDER : if ( rubyProject . contains ( member ) ) { String [ ] newNames = Util . arrayConcat ( pkgName , manager . intern ( memberName ) ) ; computeFolderChildren ( ( IFolder ) member , newNames , vChildren ) ; } break ; case IResource . FILE : break ; } } } catch ( IllegalArgumentException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } public void delete ( int updateResourceFlags , int updateModelFlags , IProgressMonitor monitor ) throws RubyModelException { } public boolean exists ( ) { return super . exists ( ) ; } public SourceFolder getSourceFolder ( String [ ] names ) { return new SourceFolder ( this , names ) ; } public boolean isExternal ( ) { return false ; } public IPath getPath ( ) { return getResource ( ) . getFullPath ( ) ; } public IResource getResource ( ) { return ( IResource ) this . resource ; } public IResource getUnderlyingResource ( ) throws RubyModelException { if ( ! exists ( ) ) throw newNotPresentException ( ) ; return getResource ( ) ; } public boolean isArchive ( ) { return false ; } public Object [ ] getNonRubyResources ( ) throws RubyModelException { return ( ( SourceFolderRootInfo ) getElementInfo ( ) ) . getNonRubyResources ( getRubyProject ( ) , getResource ( ) , this ) ; } public ISourceFolder getSourceFolder ( String packName ) { String [ ] names = Util . getTrimmedSimpleNames ( packName ) ; return getSourceFolder ( names ) ; } protected char getHandleMementoDelimiter ( ) { return RubyElement . JEM_SOURCEFOLDERROOT ; } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner owner ) { switch ( token . charAt ( ) ) { case JEM_SOURCE_FOLDER : String pkgName ; if ( memento . hasMoreTokens ( ) ) { pkgName = memento . nextToken ( ) ; char firstChar = pkgName . charAt ( ) ; if ( firstChar == JEM_RUBYSCRIPT || firstChar == JEM_COUNT ) { token = pkgName ; pkgName = ISourceFolder . DEFAULT_PACKAGE_NAME ; } else { token = null ; } } else { pkgName = ISourceFolder . DEFAULT_PACKAGE_NAME ; token = null ; } RubyElement pkg = ( RubyElement ) getSourceFolder ( pkgName ) ; if ( token == null ) { return pkg . getHandleFromMemento ( memento , owner ) ; } else { return pkg . getHandleFromMemento ( token , memento , owner ) ; } } return null ; } protected void getHandleMemento ( StringBuffer buff ) { IPath path ; IResource underlyingResource = getResource ( ) ; if ( underlyingResource != null ) { if ( getResource ( ) . getProject ( ) . equals ( getRubyProject ( ) . getProject ( ) ) ) { path = underlyingResource . getProjectRelativePath ( ) ; } else { path = underlyingResource . getFullPath ( ) ; } } else { path = getPath ( ) ; } ( ( RubyElement ) getParent ( ) ) . getHandleMemento ( buff ) ; buff . append ( getHandleMementoDelimiter ( ) ) ; escapeMementoName ( buff , path . toString ( ) ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IRegion ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . core . hierarchy . RegionBasedTypeHierarchy ; import org . rubypeople . rdt . internal . core . hierarchy . TypeHierarchy ; public class CreateTypeHierarchyOperation extends RubyModelOperation { protected TypeHierarchy typeHierarchy ; public CreateTypeHierarchyOperation ( IRegion region , IRubyScript [ ] workingCopies , IType element , boolean computeSubtypes ) { super ( element ) ; this . typeHierarchy = new RegionBasedTypeHierarchy ( region , workingCopies , element , computeSubtypes ) ; } public CreateTypeHierarchyOperation ( IType element , IRubyScript [ ] workingCopies , IRubySearchScope scope , boolean computeSubtypes ) { super ( element ) ; IRubyScript [ ] copies ; if ( workingCopies != null ) { int length = workingCopies . length ; copies = new IRubyScript [ length ] ; System . arraycopy ( workingCopies , , copies , , length ) ; } else { copies = null ; } this . typeHierarchy = new TypeHierarchy ( element , copies , scope , computeSubtypes ) ; } public CreateTypeHierarchyOperation ( IType element , IRubyScript [ ] workingCopies , IRubyProject project , boolean computeSubtypes ) { super ( element ) ; IRubyScript [ ] copies ; if ( workingCopies != null ) { int length = workingCopies . length ; copies = new IRubyScript [ length ] ; System . arraycopy ( workingCopies , , copies , , length ) ; } else { copies = null ; } this . typeHierarchy = new TypeHierarchy ( element , copies , project , computeSubtypes ) ; } protected void executeOperation ( ) throws RubyModelException { try { this . typeHierarchy . refresh ( this ) ; } catch ( IllegalStateException e ) { this . typeHierarchy = null ; } } public ITypeHierarchy getResult ( ) { return this . typeHierarchy ; } public boolean isReadOnly ( ) { return true ; } public IRubyModelStatus verify ( ) { IRubyElement elementToProcess = getElementToProcess ( ) ; if ( elementToProcess == null && ! ( this . typeHierarchy instanceof RegionBasedTypeHierarchy ) ) { return new RubyModelStatus ( IRubyModelStatusConstants . NO_ELEMENTS_TO_PROCESS ) ; } if ( elementToProcess != null && ! elementToProcess . exists ( ) ) { return new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST , elementToProcess ) ; } IRubyProject project = this . typeHierarchy . rubyProject ( ) ; if ( project != null && ! project . exists ( ) ) { return new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST , project ) ; } return RubyModelStatus . VERIFIED_OK ; } } package org . rubypeople . rdt . internal . core ; import java . io . BufferedInputStream ; import java . io . BufferedOutputStream ; import java . io . DataInputStream ; import java . io . DataOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Hashtable ; import java . util . Iterator ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . SafeRunner ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . DeltaProcessor . RootInfo ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Util ; public class DeltaProcessingState implements IResourceChangeListener { public IElementChangedListener [ ] elementChangedListeners = new IElementChangedListener [ ] ; public int [ ] elementChangedListenerMasks = new int [ ] ; public int elementChangedListenerCount = ; public IResourceChangeListener [ ] preResourceChangeListeners = new IResourceChangeListener [ ] ; public int [ ] preResourceChangeEventMasks = new int [ ] ; public int preResourceChangeListenerCount = ; private ThreadLocal < DeltaProcessor > deltaProcessors = new ThreadLocal < DeltaProcessor > ( ) ; public HashMap < IPath , RootInfo > roots = new HashMap < IPath , RootInfo > ( ) ; public HashMap < IPath , ArrayList < RootInfo > > otherRoots = new HashMap < IPath , ArrayList < RootInfo > > ( ) ; public HashMap < IPath , RootInfo > oldRoots = new HashMap < IPath , RootInfo > ( ) ; public HashMap < IPath , ArrayList < RootInfo > > oldOtherRoots = new HashMap < IPath , ArrayList < RootInfo > > ( ) ; public boolean rootsAreStale = true ; private Set < Thread > initializingThreads = Collections . synchronizedSet ( new HashSet < Thread > ( ) ) ; public HashMap < IRubyProject , IRubyProject [ ] > projectDependencies = new HashMap < IRubyProject , IRubyProject [ ] > ( ) ; public Hashtable < IPath , Long > externalTimeStamps ; public HashMap < RubyProject , ProjectUpdateInfo > projectUpdates = new HashMap < RubyProject , ProjectUpdateInfo > ( ) ; private HashSet < String > rubyProjectNamesCache ; public void addElementChangedListener ( IElementChangedListener listener , int eventMask ) { for ( int i = ; i < this . elementChangedListenerCount ; i ++ ) { if ( this . elementChangedListeners [ i ] . equals ( listener ) ) { int cloneLength = this . elementChangedListenerMasks . length ; System . arraycopy ( this . elementChangedListenerMasks , , this . elementChangedListenerMasks = new int [ cloneLength ] , , cloneLength ) ; this . elementChangedListenerMasks [ i ] = eventMask ; return ; } } int length ; if ( ( length = this . elementChangedListeners . length ) == this . elementChangedListenerCount ) { System . arraycopy ( this . elementChangedListeners , , this . elementChangedListeners = new IElementChangedListener [ length * ] , , length ) ; System . arraycopy ( this . elementChangedListenerMasks , , this . elementChangedListenerMasks = new int [ length * ] , , length ) ; } this . elementChangedListeners [ this . elementChangedListenerCount ] = listener ; this . elementChangedListenerMasks [ this . elementChangedListenerCount ] = eventMask ; this . elementChangedListenerCount ++ ; } public void removeElementChangedListener ( IElementChangedListener listener ) { for ( int i = ; i < this . elementChangedListenerCount ; i ++ ) { if ( this . elementChangedListeners [ i ] . equals ( listener ) ) { int length = this . elementChangedListeners . length ; IElementChangedListener [ ] newListeners = new IElementChangedListener [ length ] ; System . arraycopy ( this . elementChangedListeners , , newListeners , , i ) ; int [ ] newMasks = new int [ length ] ; System . arraycopy ( this . elementChangedListenerMasks , , newMasks , , i ) ; int trailingLength = this . elementChangedListenerCount - i - ; if ( trailingLength > ) { System . arraycopy ( this . elementChangedListeners , i + , newListeners , i , trailingLength ) ; System . arraycopy ( this . elementChangedListenerMasks , i + , newMasks , i , trailingLength ) ; } this . elementChangedListeners = newListeners ; this . elementChangedListenerMasks = newMasks ; this . elementChangedListenerCount -- ; return ; } } } public DeltaProcessor getDeltaProcessor ( ) { DeltaProcessor deltaProcessor = ( DeltaProcessor ) this . deltaProcessors . get ( ) ; if ( deltaProcessor != null ) return deltaProcessor ; deltaProcessor = new DeltaProcessor ( this , RubyModelManager . getRubyModelManager ( ) ) ; this . deltaProcessors . set ( deltaProcessor ) ; return deltaProcessor ; } public void addPreResourceChangedListener ( IResourceChangeListener listener , int eventMask ) { for ( int i = ; i < this . preResourceChangeListenerCount ; i ++ ) { if ( this . preResourceChangeListeners [ i ] . equals ( listener ) ) { this . preResourceChangeEventMasks [ i ] |= eventMask ; return ; } } int length ; if ( ( length = this . preResourceChangeListeners . length ) == this . preResourceChangeListenerCount ) { System . arraycopy ( this . preResourceChangeListeners , , this . preResourceChangeListeners = new IResourceChangeListener [ length * ] , , length ) ; System . arraycopy ( this . preResourceChangeEventMasks , , this . preResourceChangeEventMasks = new int [ length * ] , , length ) ; } this . preResourceChangeListeners [ this . preResourceChangeListenerCount ] = listener ; this . preResourceChangeEventMasks [ this . preResourceChangeListenerCount ] = eventMask ; this . preResourceChangeListenerCount ++ ; } public void removePreResourceChangedListener ( IResourceChangeListener listener ) { for ( int i = ; i < this . preResourceChangeListenerCount ; i ++ ) { if ( this . preResourceChangeListeners [ i ] . equals ( listener ) ) { int length = this . preResourceChangeListeners . length ; IResourceChangeListener [ ] newListeners = new IResourceChangeListener [ length ] ; int [ ] newEventMasks = new int [ length ] ; System . arraycopy ( this . preResourceChangeListeners , , newListeners , , i ) ; System . arraycopy ( this . preResourceChangeEventMasks , , newEventMasks , , i ) ; int trailingLength = this . preResourceChangeListenerCount - i - ; if ( trailingLength > ) { System . arraycopy ( this . preResourceChangeListeners , i + , newListeners , i , trailingLength ) ; System . arraycopy ( this . preResourceChangeEventMasks , i + , newEventMasks , i , trailingLength ) ; } this . preResourceChangeListeners = newListeners ; this . preResourceChangeEventMasks = newEventMasks ; this . preResourceChangeListenerCount -- ; return ; } } } public void resourceChanged ( final IResourceChangeEvent event ) { for ( int i = ; i < this . preResourceChangeListenerCount ; i ++ ) { final IResourceChangeListener listener = this . preResourceChangeListeners [ i ] ; if ( ( this . preResourceChangeEventMasks [ i ] & event . getType ( ) ) != ) SafeRunner . run ( new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { Util . log ( exception , "" ) ; } public void run ( ) throws Exception { listener . resourceChanged ( event ) ; } } ) ; } try { getDeltaProcessor ( ) . resourceChanged ( event ) ; } finally { if ( event . getType ( ) == IResourceChangeEvent . POST_CHANGE ) { this . deltaProcessors . set ( null ) ; } } } public void initializeRoots ( ) { HashMap < IPath , RootInfo > newRoots = null ; HashMap < IPath , ArrayList < RootInfo > > newOtherRoots = null ; HashMap < IRubyProject , IRubyProject [ ] > newProjectDependencies = null ; if ( this . rootsAreStale ) { Thread currentThread = Thread . currentThread ( ) ; boolean addedCurrentThread = false ; try { if ( ! this . initializingThreads . add ( currentThread ) ) return ; addedCurrentThread = true ; RubyModelManager . getRubyModelManager ( ) . batchContainerInitializations = true ; newRoots = new HashMap < IPath , RootInfo > ( ) ; newOtherRoots = new HashMap < IPath , ArrayList < RootInfo > > ( ) ; newProjectDependencies = new HashMap < IRubyProject , IRubyProject [ ] > ( ) ; IRubyModel model = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; IRubyProject [ ] projects ; try { projects = model . getRubyProjects ( ) ; } catch ( RubyModelException e ) { return ; } for ( int i = , length = projects . length ; i < length ; i ++ ) { RubyProject project = ( RubyProject ) projects [ i ] ; ILoadpathEntry [ ] loadpath ; try { loadpath = project . getResolvedLoadpath ( true , false , false ) ; } catch ( RubyModelException e ) { continue ; } for ( int j = , loadpathLength = loadpath . length ; j < loadpathLength ; j ++ ) { ILoadpathEntry entry = loadpath [ j ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { IRubyProject key = model . getRubyProject ( entry . getPath ( ) . segment ( ) ) ; IRubyProject [ ] dependents = ( IRubyProject [ ] ) newProjectDependencies . get ( key ) ; if ( dependents == null ) { dependents = new IRubyProject [ ] { project } ; } else { int dependentsLength = dependents . length ; System . arraycopy ( dependents , , dependents = new IRubyProject [ dependentsLength + ] , , dependentsLength ) ; dependents [ dependentsLength ] = project ; } newProjectDependencies . put ( key , dependents ) ; continue ; } IPath path = entry . getPath ( ) ; if ( newRoots . get ( path ) == null ) { newRoots . put ( path , new DeltaProcessor . RootInfo ( project , path , ( ( LoadpathEntry ) entry ) . fullInclusionPatternChars ( ) , ( ( LoadpathEntry ) entry ) . fullExclusionPatternChars ( ) , entry . getEntryKind ( ) ) ) ; } else { ArrayList < RootInfo > rootList = newOtherRoots . get ( path ) ; if ( rootList == null ) { rootList = new ArrayList < RootInfo > ( ) ; newOtherRoots . put ( path , rootList ) ; } rootList . add ( new DeltaProcessor . RootInfo ( project , path , ( ( LoadpathEntry ) entry ) . fullInclusionPatternChars ( ) , ( ( LoadpathEntry ) entry ) . fullExclusionPatternChars ( ) , entry . getEntryKind ( ) ) ) ; } } } } finally { if ( addedCurrentThread ) { this . initializingThreads . remove ( currentThread ) ; } } } synchronized ( this ) { this . oldRoots = this . roots ; this . oldOtherRoots = this . otherRoots ; if ( this . rootsAreStale && newRoots != null ) { this . roots = newRoots ; this . otherRoots = newOtherRoots ; this . projectDependencies = newProjectDependencies ; this . rootsAreStale = false ; } } } public Hashtable < IPath , Long > getExternalLibTimeStamps ( ) { if ( this . externalTimeStamps == null ) { Hashtable < IPath , Long > timeStamps = new Hashtable < IPath , Long > ( ) ; File timestampsFile = getTimeStampsFile ( ) ; DataInputStream in = null ; try { in = new DataInputStream ( new BufferedInputStream ( new FileInputStream ( timestampsFile ) ) ) ; int size = in . readInt ( ) ; while ( size -- > ) { String key = in . readUTF ( ) ; long timestamp = in . readLong ( ) ; timeStamps . put ( Path . fromPortableString ( key ) , new Long ( timestamp ) ) ; } } catch ( IOException e ) { if ( timestampsFile . exists ( ) ) Util . log ( e , "" ) ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( IOException e ) { } } } this . externalTimeStamps = timeStamps ; } return this . externalTimeStamps ; } private File getTimeStampsFile ( ) { return RubyCore . getPlugin ( ) . getStateLocation ( ) . append ( "" ) . toFile ( ) ; } public void saveExternalLibTimeStamps ( ) throws CoreException { if ( this . externalTimeStamps == null ) return ; File timestamps = getTimeStampsFile ( ) ; DataOutputStream out = null ; try { out = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( timestamps ) ) ) ; out . writeInt ( this . externalTimeStamps . size ( ) ) ; for ( IPath key : this . externalTimeStamps . keySet ( ) ) { out . writeUTF ( key . toPortableString ( ) ) ; Long timestamp = this . externalTimeStamps . get ( key ) ; out . writeLong ( timestamp . longValue ( ) ) ; } } catch ( IOException e ) { IStatus status = new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , IStatus . ERROR , "" , e ) ; throw new CoreException ( status ) ; } finally { if ( out != null ) { try { out . close ( ) ; } catch ( IOException e ) { } } } } public IRubyProject findRubyProject ( String name ) { if ( getOldRubyProjecNames ( ) . contains ( name ) ) return RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) . getRubyProject ( name ) ; return null ; } public synchronized HashSet < String > getOldRubyProjecNames ( ) { if ( this . rubyProjectNamesCache == null ) { HashSet < String > result = new HashSet < String > ( ) ; IRubyProject [ ] projects ; try { projects = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) . getRubyProjects ( ) ; } catch ( RubyModelException e ) { return this . rubyProjectNamesCache ; } for ( IRubyProject project : projects ) { result . add ( project . getElementName ( ) ) ; } return this . rubyProjectNamesCache = result ; } return this . rubyProjectNamesCache ; } public synchronized void resetOldRubyProjectNames ( ) { this . rubyProjectNamesCache = null ; } public synchronized ProjectUpdateInfo [ ] removeAllProjectUpdates ( ) { int length = this . projectUpdates . size ( ) ; if ( length == ) return null ; ProjectUpdateInfo [ ] updates = new ProjectUpdateInfo [ length ] ; this . projectUpdates . values ( ) . toArray ( updates ) ; this . projectUpdates . clear ( ) ; return updates ; } public void updateProjectReferences ( RubyProject project , ILoadpathEntry [ ] oldResolvedPath , ILoadpathEntry [ ] newResolvedPath , ILoadpathEntry [ ] newRawPath , boolean canChangeResources ) throws RubyModelException { ProjectUpdateInfo info ; synchronized ( this ) { info = ( ProjectUpdateInfo ) ( canChangeResources ? this . projectUpdates . remove ( project ) : this . projectUpdates . get ( project ) ) ; if ( info == null ) { info = new ProjectUpdateInfo ( ) ; info . project = project ; info . oldResolvedPath = oldResolvedPath ; if ( ! canChangeResources ) { this . projectUpdates . put ( project , info ) ; } } info . newResolvedPath = newResolvedPath ; info . newRawPath = newRawPath ; } if ( canChangeResources ) { info . updateProjectReferencesIfNecessary ( ) ; } } public static class ProjectUpdateInfo { RubyProject project ; ILoadpathEntry [ ] oldResolvedPath ; ILoadpathEntry [ ] newResolvedPath ; ILoadpathEntry [ ] newRawPath ; @ SuppressWarnings ( "" ) public void updateProjectReferencesIfNecessary ( ) throws RubyModelException { String [ ] oldRequired = this . oldResolvedPath == null ? CharOperation . NO_STRINGS : this . project . projectPrerequisites ( this . oldResolvedPath ) ; if ( this . newResolvedPath == null ) { if ( this . newRawPath == null ) this . newRawPath = this . project . getRawLoadpath ( true , false ) ; this . newResolvedPath = this . project . getResolvedLoadpath ( this . newRawPath , null , true , true , null ) ; } String [ ] newRequired = this . project . projectPrerequisites ( this . newResolvedPath ) ; try { IProject projectResource = this . project . getProject ( ) ; IProjectDescription description = projectResource . getDescription ( ) ; IProject [ ] projectReferences = description . getDynamicReferences ( ) ; HashSet < String > oldReferences = new HashSet < String > ( projectReferences . length ) ; for ( int i = ; i < projectReferences . length ; i ++ ) { String projectName = projectReferences [ i ] . getName ( ) ; oldReferences . add ( projectName ) ; } HashSet < String > newReferences = ( HashSet < String > ) oldReferences . clone ( ) ; for ( int i = ; i < oldRequired . length ; i ++ ) { String projectName = oldRequired [ i ] ; newReferences . remove ( projectName ) ; } for ( int i = ; i < newRequired . length ; i ++ ) { String projectName = newRequired [ i ] ; newReferences . add ( projectName ) ; } Iterator iter ; int newSize = newReferences . size ( ) ; checkIdentity : { if ( oldReferences . size ( ) == newSize ) { iter = newReferences . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( ! oldReferences . contains ( iter . next ( ) ) ) { break checkIdentity ; } } return ; } } String [ ] requiredProjectNames = new String [ newSize ] ; int index = ; iter = newReferences . iterator ( ) ; while ( iter . hasNext ( ) ) { requiredProjectNames [ index ++ ] = ( String ) iter . next ( ) ; } Util . sort ( requiredProjectNames ) ; IProject [ ] requiredProjectArray = new IProject [ newSize ] ; IWorkspaceRoot wksRoot = projectResource . getWorkspace ( ) . getRoot ( ) ; for ( int i = ; i < newSize ; i ++ ) { requiredProjectArray [ i ] = wksRoot . getProject ( requiredProjectNames [ i ] ) ; } description . setDynamicReferences ( requiredProjectArray ) ; projectResource . setDescription ( description , null ) ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } } public synchronized void updateRoots ( IPath containerPath , IResourceDelta containerDelta , DeltaProcessor deltaProcessor ) { Map < IPath , RootInfo > updatedRoots ; Map < IPath , ArrayList < RootInfo > > otherUpdatedRoots ; if ( containerDelta . getKind ( ) == IResourceDelta . REMOVED ) { updatedRoots = this . oldRoots ; otherUpdatedRoots = this . oldOtherRoots ; } else { updatedRoots = this . roots ; otherUpdatedRoots = this . otherRoots ; } Iterator < IPath > iterator = updatedRoots . keySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { IPath path = ( IPath ) iterator . next ( ) ; if ( containerPath . isPrefixOf ( path ) && ! containerPath . equals ( path ) ) { IResourceDelta rootDelta = containerDelta . findMember ( path . removeFirstSegments ( ) ) ; if ( rootDelta == null ) continue ; DeltaProcessor . RootInfo rootInfo = ( DeltaProcessor . RootInfo ) updatedRoots . get ( path ) ; if ( ! rootInfo . project . getPath ( ) . isPrefixOf ( path ) ) { deltaProcessor . updateCurrentDeltaAndIndex ( rootDelta , IRubyElement . SOURCE_FOLDER_ROOT , rootInfo ) ; } ArrayList < RootInfo > rootList = otherUpdatedRoots . get ( path ) ; if ( rootList != null ) { Iterator < RootInfo > otherProjects = rootList . iterator ( ) ; while ( otherProjects . hasNext ( ) ) { rootInfo = ( DeltaProcessor . RootInfo ) otherProjects . next ( ) ; if ( ! rootInfo . project . getPath ( ) . isPrefixOf ( path ) ) { deltaProcessor . updateCurrentDeltaAndIndex ( rootDelta , IRubyElement . SOURCE_FOLDER_ROOT , rootInfo ) ; } } } } } } } package org . rubypeople . rdt . internal . core ; import java . io . ByteArrayInputStream ; import java . io . UnsupportedEncodingException ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class CommitWorkingCopyOperation extends RubyModelOperation { public CommitWorkingCopyOperation ( IRubyScript element , boolean force ) { super ( new IRubyElement [ ] { element } , force ) ; } protected void executeOperation ( ) throws RubyModelException { try { beginTask ( Messages . workingCopy_commit , ) ; RubyScript workingCopy = getRubyScript ( ) ; IFile resource = ( IFile ) workingCopy . getResource ( ) ; if ( resource == null ) { workingCopy . getBuffer ( ) . save ( this . progressMonitor , this . force ) ; return ; } IRubyScript primary = workingCopy . getPrimary ( ) ; boolean isPrimary = workingCopy . isPrimary ( ) ; RubyElementDeltaBuilder deltaBuilder = null ; boolean isIncluded = ! Util . isExcluded ( workingCopy ) ; if ( isPrimary || ( isIncluded && resource . isAccessible ( ) && Util . isValidRubyScriptName ( workingCopy . getElementName ( ) ) ) ) { if ( ! isPrimary && ! primary . isOpen ( ) ) { primary . open ( null ) ; } if ( isIncluded && ( ! isPrimary || ! workingCopy . isConsistent ( ) ) ) { deltaBuilder = new RubyElementDeltaBuilder ( primary ) ; } IBuffer primaryBuffer = primary . getBuffer ( ) ; if ( ! isPrimary ) { if ( primaryBuffer == null ) return ; char [ ] primaryContents = primaryBuffer . getCharacters ( ) ; boolean hasSaved = false ; try { IBuffer workingCopyBuffer = workingCopy . getBuffer ( ) ; if ( workingCopyBuffer == null ) return ; primaryBuffer . setContents ( workingCopyBuffer . getCharacters ( ) ) ; primaryBuffer . save ( this . progressMonitor , this . force ) ; primary . makeConsistent ( this ) ; hasSaved = true ; } finally { if ( ! hasSaved ) { primaryBuffer . setContents ( primaryContents ) ; } } } else { primaryBuffer . save ( this . progressMonitor , this . force ) ; primary . makeConsistent ( this ) ; } } else { String encoding = null ; try { encoding = resource . getCharset ( ) ; } catch ( CoreException ce ) { } String contents = workingCopy . getSource ( ) ; if ( contents == null ) return ; try { byte [ ] bytes = encoding == null ? contents . getBytes ( ) : contents . getBytes ( encoding ) ; ByteArrayInputStream stream = new ByteArrayInputStream ( bytes ) ; if ( resource . exists ( ) ) { resource . setContents ( stream , this . force ? IResource . FORCE | IResource . KEEP_HISTORY : IResource . KEEP_HISTORY , null ) ; } else { resource . create ( stream , this . force , this . progressMonitor ) ; } } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } catch ( UnsupportedEncodingException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } } setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; workingCopy . updateTimeStamp ( ( RubyScript ) primary ) ; workingCopy . makeConsistent ( this ) ; worked ( ) ; if ( deltaBuilder != null ) { deltaBuilder . buildDeltas ( ) ; if ( deltaBuilder . delta != null ) { addDelta ( deltaBuilder . delta ) ; } } worked ( ) ; } finally { done ( ) ; } } protected RubyScript getRubyScript ( ) { return ( RubyScript ) getElementToProcess ( ) ; } protected ISchedulingRule getSchedulingRule ( ) { IResource resource = getElementToProcess ( ) . getResource ( ) ; if ( resource == null ) return null ; IWorkspace workspace = resource . getWorkspace ( ) ; if ( resource . exists ( ) ) { return workspace . getRuleFactory ( ) . modifyRule ( resource ) ; } else { return workspace . getRuleFactory ( ) . createRule ( resource ) ; } } public IRubyModelStatus verify ( ) { RubyScript cu = getRubyScript ( ) ; if ( ! cu . isWorkingCopy ( ) ) { return new RubyModelStatus ( IRubyModelStatusConstants . INVALID_ELEMENT_TYPES , cu ) ; } if ( cu . hasResourceChanged ( ) && ! this . force ) { return new RubyModelStatus ( IRubyModelStatusConstants . UPDATE_CONFLICT ) ; } return RubyModelStatus . VERIFIED_OK ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; public class RubyModelInfo extends OpenableElementInfo { Object [ ] nonRubyResources ; private Object [ ] computeNonRubyResources ( ) { IProject [ ] projects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; int length = projects . length ; Object [ ] resources = null ; int index = ; for ( int i = ; i < length ; i ++ ) { IProject project = projects [ i ] ; if ( ! RubyProject . hasRubyNature ( project ) ) { if ( resources == null ) { resources = new Object [ length ] ; } resources [ index ++ ] = project ; } } if ( index == ) return NO_NON_RUBY_RESOURCES ; if ( index < length ) { System . arraycopy ( resources , , resources = new Object [ index ] , , index ) ; } return resources ; } Object [ ] getNonRubyResources ( ) { if ( this . nonRubyResources == null ) { this . nonRubyResources = computeNonRubyResources ( ) ; } return this . nonRubyResources ; } } package org . rubypeople . rdt . internal . core ; import java . io . BufferedInputStream ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStreamWriter ; import java . io . StringReader ; import java . io . UnsupportedEncodingException ; import java . net . URI ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Hashtable ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import org . eclipse . core . resources . ICommand ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IProjectNature ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ProjectScope ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . AssertionFailedException ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IScopeContext ; import org . osgi . service . prefs . BackingStoreException ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRegion ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . search . CollectingSearchRequestor ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . ObjectVector ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; public class RubyProject extends Openable implements IProjectNature , IRubyElement , IRubyProject { protected IProject project ; protected boolean scratched ; private static final String PREF_FILENAME = "" ; private static final ILoadpathEntry [ ] RESOLUTION_IN_PROGRESS = new ILoadpathEntry [ ] ; static final String LOADPATH_FILENAME = "" ; static final ILoadpathEntry [ ] INVALID_LOADPATH = new ILoadpathEntry [ ] ; protected static final boolean IS_CASE_SENSITIVE = ! new File ( "" ) . equals ( new File ( "" ) ) ; protected static final String [ ] NO_PREREQUISITES = new String [ ] ; public RubyProject ( ) { super ( null ) ; } public RubyProject ( IProject aProject , RubyElement parent ) { super ( parent ) ; setProject ( aProject ) ; } public void configure ( ) throws CoreException { addToBuildSpec ( RubyCore . BUILDER_ID ) ; } protected boolean addToBuildSpec ( String builderID ) throws CoreException { IProjectDescription description = this . project . getDescription ( ) ; int commandIndex = getRubyCommandIndex ( description . getBuildSpec ( ) ) ; if ( commandIndex == - ) { ICommand command = description . newCommand ( ) ; command . setBuilderName ( builderID ) ; setRubyCommand ( description , command ) ; return true ; } return false ; } private int getRubyCommandIndex ( ICommand [ ] buildSpec ) { for ( int i = ; i < buildSpec . length ; ++ i ) { if ( buildSpec [ i ] . getBuilderName ( ) . equals ( RubyCore . BUILDER_ID ) ) { return i ; } } return - ; } private void setRubyCommand ( IProjectDescription description , ICommand newCommand ) throws CoreException { ICommand [ ] oldBuildSpec = description . getBuildSpec ( ) ; int oldRubyCommandIndex = getRubyCommandIndex ( oldBuildSpec ) ; ICommand [ ] newCommands ; if ( oldRubyCommandIndex == - ) { newCommands = new ICommand [ oldBuildSpec . length + ] ; System . arraycopy ( oldBuildSpec , , newCommands , , oldBuildSpec . length ) ; newCommands [ ] = newCommand ; } else { oldBuildSpec [ oldRubyCommandIndex ] = newCommand ; newCommands = oldBuildSpec ; } description . setBuildSpec ( newCommands ) ; this . project . setDescription ( description , null ) ; } public void deconfigure ( ) throws CoreException { removeFromBuildSpec ( RubyCore . BUILDER_ID ) ; } protected void removeFromBuildSpec ( String builderID ) throws CoreException { IProjectDescription description = this . project . getDescription ( ) ; ICommand [ ] commands = description . getBuildSpec ( ) ; for ( int i = ; i < commands . length ; ++ i ) { if ( commands [ i ] . getBuilderName ( ) . equals ( builderID ) ) { ICommand [ ] newCommands = new ICommand [ commands . length - ] ; System . arraycopy ( commands , , newCommands , , i ) ; System . arraycopy ( commands , i + , newCommands , i , commands . length - i - ) ; description . setBuildSpec ( newCommands ) ; this . project . setDescription ( description , null ) ; return ; } } } public boolean equals ( Object o ) { if ( this == o ) return true ; if ( ! ( o instanceof RubyProject ) ) return false ; RubyProject other = ( RubyProject ) o ; return this . project . equals ( other . getProject ( ) ) ; } public int hashCode ( ) { if ( this . project == null ) { return super . hashCode ( ) * + ; } return this . project . hashCode ( ) * + ; } public boolean exists ( ) { return hasRubyNature ( this . project ) ; } public RubyModelManager . PerProjectInfo getPerProjectInfo ( ) throws RubyModelException { return RubyModelManager . getRubyModelManager ( ) . getPerProjectInfoCheckExistence ( this . project ) ; } private IPath getPluginWorkingLocation ( ) { return this . project . getWorkingLocation ( RubyCore . PLUGIN_ID ) ; } public IProject getProject ( ) { return project ; } public IPath getPath ( ) { return this . project . getFullPath ( ) ; } protected IProject getProject ( String name ) { return RubyCore . getWorkspace ( ) . getRoot ( ) . getProject ( name ) ; } public void setProject ( IProject aProject ) { project = aProject ; } public IResource getResource ( ) { return this . project ; } public String [ ] getRequiredProjectNames ( ) throws RubyModelException { return this . projectPrerequisites ( getResolvedLoadpath ( true , false , false ) ) ; } public String [ ] projectPrerequisites ( ILoadpathEntry [ ] entries ) throws RubyModelException { ArrayList prerequisites = new ArrayList ( ) ; entries = getResolvedLoadpath ( entries , null , true , false , null ) ; for ( int i = , length = entries . length ; i < length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { prerequisites . add ( entry . getPath ( ) . lastSegment ( ) ) ; } } int size = prerequisites . size ( ) ; if ( size == ) { return NO_PREREQUISITES ; } else { String [ ] result = new String [ size ] ; prerequisites . toArray ( result ) ; return result ; } } public IResource getUnderlyingResource ( ) throws RubyModelException { if ( ! exists ( ) ) throw newNotPresentException ( ) ; return this . project ; } public IEclipsePreferences getEclipsePreferences ( ) { if ( ! RubyProject . hasRubyNature ( this . project ) ) return null ; RubyModelManager . PerProjectInfo perProjectInfo = RubyModelManager . getRubyModelManager ( ) . getPerProjectInfo ( this . project , true ) ; if ( perProjectInfo . preferences != null ) return perProjectInfo . preferences ; IScopeContext context = new ProjectScope ( getProject ( ) ) ; final IEclipsePreferences eclipsePreferences = context . getNode ( RubyCore . PLUGIN_ID ) ; updatePreferences ( eclipsePreferences ) ; perProjectInfo . preferences = eclipsePreferences ; IEclipsePreferences . INodeChangeListener nodeListener = new IEclipsePreferences . INodeChangeListener ( ) { public void added ( IEclipsePreferences . NodeChangeEvent event ) { } public void removed ( IEclipsePreferences . NodeChangeEvent event ) { if ( event . getChild ( ) == eclipsePreferences ) { RubyModelManager . getRubyModelManager ( ) . resetProjectPreferences ( RubyProject . this ) ; } } } ; ( ( IEclipsePreferences ) eclipsePreferences . parent ( ) ) . addNodeChangeListener ( nodeListener ) ; IEclipsePreferences . IPreferenceChangeListener preferenceListener = new IEclipsePreferences . IPreferenceChangeListener ( ) { public void preferenceChange ( IEclipsePreferences . PreferenceChangeEvent event ) { RubyModelManager . getRubyModelManager ( ) . resetProjectOptions ( RubyProject . this ) ; } } ; eclipsePreferences . addPreferenceChangeListener ( preferenceListener ) ; return eclipsePreferences ; } public String getElementName ( ) { if ( project == null ) { return super . getElementName ( ) ; } return project . getName ( ) ; } public int getElementType ( ) { return IRubyElement . RUBY_PROJECT ; } public boolean hasChildren ( ) { return true ; } public IType findType ( String fullyQualifiedName ) { return findType ( fullyQualifiedName , null ) ; } public IType findType ( String fullyQualifiedName , IProgressMonitor monitor ) { try { SearchEngine engine = new SearchEngine ( ) ; SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . TYPE , fullyQualifiedName , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; SearchParticipant [ ] participants = new SearchParticipant [ ] { SearchEngine . getDefaultSearchParticipant ( ) } ; IRubySearchScope scope = SearchEngine . createWorkspaceScope ( ) ; CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; engine . search ( pattern , participants , scope , requestor , monitor ) ; List < SearchMatch > matches = requestor . getResults ( ) ; for ( SearchMatch match : matches ) { IType type = ( IType ) match . getElement ( ) ; if ( type . getFullyQualifiedName ( ) . equals ( fullyQualifiedName ) ) return type ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } return null ; } public static boolean hasRubyNature ( IProject project ) { try { return project . hasNature ( RubyCore . NATURE_ID ) ; } catch ( CoreException e ) { } return false ; } protected boolean buildStructure ( OpenableElementInfo info , IProgressMonitor pm , Map newElements , IResource underlyingResource ) throws RubyModelException { if ( ! hasRubyNature ( ( IProject ) underlyingResource ) ) { throw new RubyModelException ( new RubyModelStatus ( IRubyModelStatusConstants . PROJECT_HAS_NO_RUBY_NATURE , this ) ) ; } ILoadpathEntry [ ] resolvedClasspath = getResolvedLoadpath ( true , false , false ) ; info . setChildren ( computeSourceFolderRoots ( resolvedClasspath , false , null ) ) ; getPerProjectInfo ( ) . rememberExternalLibTimestamps ( ) ; return true ; } public ISourceFolderRoot [ ] computeSourceFolderRoots ( ILoadpathEntry [ ] resolvedClasspath , boolean retrieveExportedRoots , Map rootToResolvedEntries ) throws RubyModelException { ObjectVector accumulatedRoots = new ObjectVector ( ) ; computeSourceFolderRoots ( resolvedClasspath , accumulatedRoots , new HashSet ( ) , null , true , retrieveExportedRoots , rootToResolvedEntries ) ; ISourceFolderRoot [ ] rootArray = new ISourceFolderRoot [ accumulatedRoots . size ( ) ] ; accumulatedRoots . copyInto ( rootArray ) ; return rootArray ; } public void computeSourceFolderRoots ( ILoadpathEntry [ ] resolvedClasspath , ObjectVector accumulatedRoots , HashSet rootIDs , ILoadpathEntry referringEntry , boolean checkExistency , boolean retrieveExportedRoots , Map rootToResolvedEntries ) throws RubyModelException { if ( referringEntry == null ) { rootIDs . add ( rootID ( ) ) ; } for ( int i = , length = resolvedClasspath . length ; i < length ; i ++ ) { computeSourceFolderRoots ( resolvedClasspath [ i ] , accumulatedRoots , rootIDs , referringEntry , checkExistency , retrieveExportedRoots , rootToResolvedEntries ) ; } } public void computeSourceFolderRoots ( ILoadpathEntry resolvedEntry , ObjectVector accumulatedRoots , HashSet rootIDs , ILoadpathEntry referringEntry , boolean checkExistency , boolean retrieveExportedRoots , Map rootToResolvedEntries ) throws RubyModelException { String rootID = ( ( LoadpathEntry ) resolvedEntry ) . rootID ( ) ; if ( rootIDs . contains ( rootID ) ) return ; IPath projectPath = this . project . getFullPath ( ) ; IPath entryPath = resolvedEntry . getPath ( ) ; IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; ISourceFolderRoot root = null ; switch ( resolvedEntry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_SOURCE : if ( projectPath . isPrefixOf ( entryPath ) ) { if ( checkExistency ) { Object target = RubyModel . getTarget ( entryPath , checkExistency ) ; if ( target == null ) return ; if ( target instanceof IFolder || target instanceof IProject ) { root = getSourceFolderRoot ( ( IResource ) target ) ; } } else { root = getFolderSourceFolderRoot ( entryPath ) ; } } break ; case ILoadpathEntry . CPE_LIBRARY : if ( referringEntry != null && ! resolvedEntry . isExported ( ) ) return ; if ( checkExistency ) { Object target = RubyModel . getTarget ( entryPath , checkExistency ) ; if ( target == null ) return ; if ( target instanceof IResource ) { root = getSourceFolderRoot ( ( IResource ) target ) ; } else { if ( RubyModel . isFolder ( target ) ) { root = new ExternalSourceFolderRoot ( entryPath , this ) ; } } } else { root = getSourceFolderRoot ( entryPath ) ; } break ; case ILoadpathEntry . CPE_PROJECT : if ( ! retrieveExportedRoots ) return ; if ( referringEntry != null && ! resolvedEntry . isExported ( ) ) return ; IResource member = workspaceRoot . findMember ( entryPath ) ; if ( member != null && member . getType ( ) == IResource . PROJECT ) { IProject requiredProjectRsc = ( IProject ) member ; if ( RubyProject . hasRubyNature ( requiredProjectRsc ) ) { rootIDs . add ( rootID ) ; RubyProject requiredProject = ( RubyProject ) RubyCore . create ( requiredProjectRsc ) ; requiredProject . computeSourceFolderRoots ( requiredProject . getResolvedLoadpath ( true , false , false ) , accumulatedRoots , rootIDs , rootToResolvedEntries == null ? resolvedEntry : ( ( LoadpathEntry ) resolvedEntry ) . combineWith ( ( LoadpathEntry ) referringEntry ) , checkExistency , retrieveExportedRoots , rootToResolvedEntries ) ; } break ; } } if ( root != null ) { accumulatedRoots . add ( root ) ; rootIDs . add ( rootID ) ; if ( rootToResolvedEntries != null ) rootToResolvedEntries . put ( root , ( ( LoadpathEntry ) resolvedEntry ) . combineWith ( ( LoadpathEntry ) referringEntry ) ) ; } } public ISourceFolderRoot getSourceFolderRoot ( IPath path ) { if ( ! path . isAbsolute ( ) ) { path = getPath ( ) . append ( path ) ; } int segmentCount = path . segmentCount ( ) ; switch ( segmentCount ) { case : return null ; case : if ( path . equals ( getPath ( ) ) ) { return getSourceFolderRoot ( this . project ) ; } default : if ( segmentCount == ) { return getSourceFolderRoot ( this . project . getWorkspace ( ) . getRoot ( ) . getProject ( path . lastSegment ( ) ) ) ; } else { return getSourceFolderRoot ( this . project . getWorkspace ( ) . getRoot ( ) . getFolder ( path ) ) ; } } } public boolean contains ( IResource resource ) { return true ; } public String rootID ( ) { return "" + this . project . getFullPath ( ) ; } protected Object createElementInfo ( ) { return new RubyProjectElementInfo ( ) ; } public String getOption ( String optionName , boolean inheritRubyCoreOptions ) { String propertyName = optionName ; if ( RubyModelManager . getRubyModelManager ( ) . optionNames . contains ( propertyName ) ) { IEclipsePreferences projectPreferences = getEclipsePreferences ( ) ; String javaCoreDefault = inheritRubyCoreOptions ? RubyCore . getOption ( propertyName ) : null ; if ( projectPreferences == null ) return javaCoreDefault ; String value = projectPreferences . get ( propertyName , javaCoreDefault ) ; return value == null ? null : value . trim ( ) ; } return null ; } public Map getOptions ( boolean inheritRubyCoreOptions ) { Map < String , String > options = inheritRubyCoreOptions ? RubyCore . getOptions ( ) : new Hashtable < String , String > ( ) ; RubyModelManager . PerProjectInfo perProjectInfo = null ; Hashtable < String , String > projectOptions = null ; HashSet < String > optionNames = RubyModelManager . getRubyModelManager ( ) . optionNames ; try { perProjectInfo = getPerProjectInfo ( ) ; projectOptions = perProjectInfo . options ; if ( projectOptions == null ) { IEclipsePreferences projectPreferences = getEclipsePreferences ( ) ; if ( projectPreferences == null ) return options ; String [ ] propertyNames = projectPreferences . keys ( ) ; projectOptions = new Hashtable < String , String > ( propertyNames . length ) ; for ( int i = ; i < propertyNames . length ; i ++ ) { String propertyName = propertyNames [ i ] ; String value = projectPreferences . get ( propertyName , null ) ; if ( value != null && optionNames . contains ( propertyName ) ) { projectOptions . put ( propertyName , value . trim ( ) ) ; } } perProjectInfo . options = projectOptions ; } } catch ( RubyModelException jme ) { projectOptions = new Hashtable < String , String > ( ) ; } catch ( BackingStoreException e ) { projectOptions = new Hashtable < String , String > ( ) ; } if ( inheritRubyCoreOptions ) { Iterator < Map . Entry < String , String > > entries = projectOptions . entrySet ( ) . iterator ( ) ; while ( entries . hasNext ( ) ) { Map . Entry < String , String > entry = entries . next ( ) ; String propertyName = entry . getKey ( ) ; String propertyValue = entry . getValue ( ) ; if ( propertyValue != null && optionNames . contains ( propertyName ) ) { options . put ( propertyName , propertyValue . trim ( ) ) ; } } return options ; } return projectOptions ; } private void updatePreferences ( IEclipsePreferences preferences ) { Preferences oldPreferences = loadPreferences ( ) ; if ( oldPreferences != null ) { String [ ] propertyNames = oldPreferences . propertyNames ( ) ; for ( int i = ; i < propertyNames . length ; i ++ ) { String propertyName = propertyNames [ i ] ; String propertyValue = oldPreferences . getString ( propertyName ) ; if ( ! "" . equals ( propertyValue ) ) { preferences . put ( propertyName , propertyValue ) ; } } try { preferences . flush ( ) ; } catch ( BackingStoreException e ) { } } } private Preferences loadPreferences ( ) { Preferences preferences = new Preferences ( ) ; IPath projectMetaLocation = getPluginWorkingLocation ( ) ; if ( projectMetaLocation != null ) { File prefFile = projectMetaLocation . append ( PREF_FILENAME ) . toFile ( ) ; if ( prefFile . exists ( ) ) { InputStream in = null ; try { in = new BufferedInputStream ( new FileInputStream ( prefFile ) ) ; preferences . load ( in ) ; } catch ( IOException e ) { } finally { if ( in != null ) { try { in . close ( ) ; } catch ( IOException e ) { } } } prefFile . delete ( ) ; return preferences ; } } return null ; } public void resetCaches ( ) { RubyProjectElementInfo info = ( RubyProjectElementInfo ) RubyModelManager . getRubyModelManager ( ) . peekAtInfo ( this ) ; if ( info != null ) { info . resetCaches ( ) ; } } public Object [ ] getNonRubyResources ( ) throws RubyModelException { return ( ( RubyProjectElementInfo ) getElementInfo ( ) ) . getNonRubyResources ( this ) ; } public ISourceFolder [ ] getSourceFolders ( ) throws RubyModelException { ISourceFolderRoot [ ] roots = getSourceFolderRoots ( ) ; return getSourceFoldersInRoots ( roots ) ; } public ISourceFolder [ ] getSourceFoldersInRoots ( ISourceFolderRoot [ ] roots ) { ArrayList frags = new ArrayList ( ) ; for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; try { IRubyElement [ ] rootFragments = root . getChildren ( ) ; for ( int j = ; j < rootFragments . length ; j ++ ) { frags . add ( rootFragments [ j ] ) ; } } catch ( RubyModelException e ) { } } ISourceFolder [ ] fragments = new ISourceFolder [ frags . size ( ) ] ; frags . toArray ( fragments ) ; return fragments ; } public ILoadpathEntry [ ] getRawLoadpath ( boolean createMarkers , boolean logProblems ) throws RubyModelException { RubyModelManager . PerProjectInfo perProjectInfo = null ; ILoadpathEntry [ ] classpath ; if ( createMarkers ) { this . flushLoadpathProblemMarkers ( false , true ) ; classpath = this . readLoadpathFile ( createMarkers , logProblems ) ; } else { perProjectInfo = getPerProjectInfo ( ) ; classpath = perProjectInfo . rawLoadpath ; if ( classpath != null ) return classpath ; classpath = this . readLoadpathFile ( createMarkers , logProblems ) ; } if ( classpath == null ) { return defaultLoadpath ( ) ; } if ( ! createMarkers ) { perProjectInfo . rawLoadpath = classpath ; perProjectInfo . outputLocation = null ; } return classpath ; } protected ILoadpathEntry [ ] defaultLoadpath ( ) { return new ILoadpathEntry [ ] { RubyCore . newSourceEntry ( this . project . getFullPath ( ) ) } ; } public ILoadpathEntry [ ] readRawLoadpath ( ) { return this . readLoadpathFile ( false , false ) ; } protected ILoadpathEntry [ ] readLoadpathFile ( boolean createMarker , boolean logProblems ) { return readLoadpathFile ( createMarker , logProblems , null ) ; } protected ILoadpathEntry [ ] readLoadpathFile ( boolean createMarker , boolean logProblems , Map unknownElements ) { try { String xmlClasspath = getSharedProperty ( LOADPATH_FILENAME ) ; if ( xmlClasspath == null ) { if ( createMarker && this . project . isAccessible ( ) ) { this . createLoadpathProblemMarker ( new RubyModelStatus ( IRubyModelStatusConstants . INVALID_LOADPATH_FILE_FORMAT , Messages . bind ( Messages . classpath_cannotReadClasspathFile , this . getElementName ( ) ) ) ) ; } return null ; } return decodeLoadpath ( xmlClasspath , createMarker , logProblems , unknownElements ) ; } catch ( CoreException e ) { if ( createMarker && this . project . isAccessible ( ) ) { this . createLoadpathProblemMarker ( new RubyModelStatus ( IRubyModelStatusConstants . INVALID_LOADPATH_FILE_FORMAT , Messages . bind ( Messages . classpath_cannotReadClasspathFile , this . getElementName ( ) ) ) ) ; } if ( logProblems ) { Util . log ( e , "" + this . getPath ( ) + "" ) ; } } return null ; } protected ILoadpathEntry [ ] decodeLoadpath ( String xmlClasspath , boolean createMarker , boolean logProblems , Map unknownElements ) { ArrayList paths = new ArrayList ( ) ; try { if ( xmlClasspath == null ) return null ; StringReader reader = new StringReader ( xmlClasspath ) ; Element cpElement ; try { DocumentBuilder parser = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; cpElement = parser . parse ( new InputSource ( reader ) ) . getDocumentElement ( ) ; } catch ( SAXException e ) { throw new IOException ( Messages . file_badFormat ) ; } catch ( ParserConfigurationException e ) { throw new IOException ( Messages . file_badFormat ) ; } finally { reader . close ( ) ; } if ( ! cpElement . getNodeName ( ) . equalsIgnoreCase ( LoadpathEntry . TAG_LOADPATH ) ) { throw new IOException ( Messages . file_badFormat ) ; } NodeList list = cpElement . getElementsByTagName ( LoadpathEntry . TAG_LOADPATHENTRY ) ; int length = list . getLength ( ) ; for ( int i = ; i < length ; ++ i ) { Node node = list . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { ILoadpathEntry entry = LoadpathEntry . elementDecode ( ( Element ) node , this , unknownElements ) ; if ( entry != null ) { paths . add ( entry ) ; } } } } catch ( IOException e ) { if ( createMarker && this . project . isAccessible ( ) ) { this . createLoadpathProblemMarker ( new RubyModelStatus ( IRubyModelStatusConstants . INVALID_LOADPATH_FILE_FORMAT , Messages . bind ( Messages . classpath_xmlFormatError , new String [ ] { this . getElementName ( ) , e . getMessage ( ) } ) ) ) ; } if ( logProblems ) { Util . log ( e , "" + this . getPath ( ) + "" ) ; } return INVALID_LOADPATH ; } catch ( AssertionFailedException e ) { if ( createMarker && this . project . isAccessible ( ) ) { this . createLoadpathProblemMarker ( new RubyModelStatus ( IRubyModelStatusConstants . INVALID_LOADPATH_FILE_FORMAT , Messages . bind ( Messages . classpath_illegalEntryInClasspathFile , new String [ ] { this . getElementName ( ) , e . getMessage ( ) } ) ) ) ; } if ( logProblems ) { Util . log ( e , "" + this . getPath ( ) + "" ) ; } return INVALID_LOADPATH ; } int pathSize = paths . size ( ) ; ILoadpathEntry [ ] entries = new ILoadpathEntry [ pathSize ] ; paths . toArray ( entries ) ; return entries ; } public String getSharedProperty ( String key ) throws CoreException { String property = null ; IFile rscFile = this . project . getFile ( key ) ; if ( rscFile . exists ( ) ) { byte [ ] bytes = Util . getResourceContentsAsByteArray ( rscFile ) ; try { property = new String ( bytes , org . rubypeople . rdt . core . util . Util . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { Util . log ( e , "" ) ; property = new String ( bytes ) ; } } else { URI location = rscFile . getLocationURI ( ) ; if ( location != null ) { File file = Util . toLocalFile ( location , null ) ; if ( file != null && file . exists ( ) ) { byte [ ] bytes ; try { bytes = org . rubypeople . rdt . core . util . Util . getFileByteContent ( file ) ; } catch ( IOException e ) { return null ; } try { property = new String ( bytes , org . rubypeople . rdt . core . util . Util . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { Util . log ( e , "" ) ; property = new String ( bytes ) ; } } } } return property ; } public ILoadpathEntry [ ] getResolvedLoadpath ( boolean ignoreUnresolvedEntry , boolean generateMarkerOnError ) throws RubyModelException { return getResolvedLoadpath ( ignoreUnresolvedEntry , generateMarkerOnError , true ) ; } public ILoadpathEntry [ ] getResolvedLoadpath ( boolean ignoreUnresolvedEntry , boolean generateMarkerOnError , boolean returnResolutionInProgress ) throws RubyModelException { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; RubyModelManager . PerProjectInfo perProjectInfo = null ; if ( ignoreUnresolvedEntry && ! generateMarkerOnError ) { perProjectInfo = getPerProjectInfo ( ) ; if ( perProjectInfo != null ) { ILoadpathEntry [ ] infoPath = perProjectInfo . resolvedLoadpath ; if ( infoPath != null ) { return infoPath ; } else if ( returnResolutionInProgress && manager . isLoadpathBeingResolved ( this ) ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + getElementName ( ) + '' + "" ) ; new Exception ( "" ) . printStackTrace ( System . out ) ; } return RESOLUTION_IN_PROGRESS ; } } } Map < IPath , ILoadpathEntry > rawReverseMap = perProjectInfo == null ? null : new HashMap < IPath , ILoadpathEntry > ( ) ; ILoadpathEntry [ ] resolvedPath = null ; boolean nullOldResolvedCP = perProjectInfo != null && perProjectInfo . resolvedLoadpath == null ; try { if ( nullOldResolvedCP ) manager . setLoadpathBeingResolved ( this , true ) ; resolvedPath = getResolvedLoadpath ( getRawLoadpath ( generateMarkerOnError , ! generateMarkerOnError ) , null , ignoreUnresolvedEntry , generateMarkerOnError , rawReverseMap ) ; } finally { if ( nullOldResolvedCP ) perProjectInfo . resolvedLoadpath = null ; } if ( perProjectInfo != null ) { if ( perProjectInfo . rawLoadpath == null && generateMarkerOnError && RubyProject . hasRubyNature ( this . project ) ) { this . flushLoadpathProblemMarkers ( false , true ) ; this . createLoadpathProblemMarker ( new RubyModelStatus ( IRubyModelStatusConstants . INVALID_LOADPATH_FILE_FORMAT , Messages . bind ( Messages . classpath_cannotReadClasspathFile , this . getElementName ( ) ) ) ) ; } perProjectInfo . resolvedLoadpath = resolvedPath ; perProjectInfo . resolvedPathToRawEntries = rawReverseMap ; manager . setLoadpathBeingResolved ( this , false ) ; } return resolvedPath ; } public ILoadpathEntry [ ] getResolvedLoadpath ( ILoadpathEntry [ ] classpathEntries , IPath projectOutputLocation , boolean ignoreUnresolvedEntry , boolean generateMarkerOnError , Map < IPath , ILoadpathEntry > rawReverseMap ) throws RubyModelException { IRubyModelStatus status ; if ( generateMarkerOnError ) { flushLoadpathProblemMarkers ( false , false ) ; } int length = classpathEntries . length ; ArrayList < ILoadpathEntry > resolvedEntries = new ArrayList < ILoadpathEntry > ( ) ; for ( int i = ; i < length ; i ++ ) { ILoadpathEntry rawEntry = classpathEntries [ i ] ; IPath resolvedPath ; status = null ; if ( generateMarkerOnError || ! ignoreUnresolvedEntry ) { status = LoadpathEntry . validateLoadpathEntry ( this , rawEntry , false , false ) ; if ( generateMarkerOnError && ! status . isOK ( ) ) { if ( status . getCode ( ) == IRubyModelStatusConstants . INVALID_CLASSPATH && ( ( LoadpathEntry ) rawEntry ) . isOptional ( ) ) continue ; createLoadpathProblemMarker ( status ) ; } } switch ( rawEntry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_VARIABLE : ILoadpathEntry resolvedEntry = null ; try { resolvedEntry = RubyCore . getResolvedLoadpathEntry ( rawEntry ) ; } catch ( AssertionFailedException e ) { if ( ! ignoreUnresolvedEntry ) throw new RubyModelException ( status ) ; } if ( resolvedEntry == null ) { if ( ! ignoreUnresolvedEntry ) throw new RubyModelException ( status ) ; } else { if ( rawReverseMap != null ) { if ( rawReverseMap . get ( resolvedPath = resolvedEntry . getPath ( ) ) == null ) rawReverseMap . put ( resolvedPath , rawEntry ) ; } resolvedEntries . add ( resolvedEntry ) ; } break ; case ILoadpathEntry . CPE_CONTAINER : ILoadpathContainer container = RubyCore . getLoadpathContainer ( rawEntry . getPath ( ) , this ) ; if ( container == null ) { if ( ! ignoreUnresolvedEntry ) throw new RubyModelException ( status ) ; break ; } ILoadpathEntry [ ] containerEntries = container . getLoadpathEntries ( ) ; if ( containerEntries == null ) break ; for ( int j = , containerLength = containerEntries . length ; j < containerLength ; j ++ ) { LoadpathEntry cEntry = ( LoadpathEntry ) containerEntries [ j ] ; if ( generateMarkerOnError ) { IRubyModelStatus containerStatus = LoadpathEntry . validateLoadpathEntry ( this , cEntry , false , true ) ; if ( ! containerStatus . isOK ( ) ) createLoadpathProblemMarker ( containerStatus ) ; } cEntry = cEntry . combineWith ( ( LoadpathEntry ) rawEntry ) ; if ( rawReverseMap != null ) { if ( rawReverseMap . get ( resolvedPath = cEntry . getPath ( ) ) == null ) rawReverseMap . put ( resolvedPath , rawEntry ) ; } resolvedEntries . add ( cEntry ) ; } break ; default : if ( rawReverseMap != null ) { if ( rawReverseMap . get ( resolvedPath = rawEntry . getPath ( ) ) == null ) rawReverseMap . put ( resolvedPath , rawEntry ) ; } resolvedEntries . add ( rawEntry ) ; } } ILoadpathEntry [ ] resolvedPath = new ILoadpathEntry [ resolvedEntries . size ( ) ] ; resolvedEntries . toArray ( resolvedPath ) ; if ( generateMarkerOnError && projectOutputLocation != null ) { status = LoadpathEntry . validateLoadpath ( this , resolvedPath , projectOutputLocation ) ; if ( ! status . isOK ( ) ) createLoadpathProblemMarker ( status ) ; } return resolvedPath ; } public ISourceFolderRoot getFolderSourceFolderRoot ( IPath path ) { if ( path . segmentCount ( ) == ) { return getSourceFolderRoot ( this . project ) ; } return getSourceFolderRoot ( this . project . getWorkspace ( ) . getRoot ( ) . getFolder ( path ) ) ; } public ISourceFolderRoot getSourceFolderRoot ( IResource resource ) { switch ( resource . getType ( ) ) { case IResource . FILE : return null ; case IResource . FOLDER : return new SourceFolderRoot ( resource , this ) ; case IResource . PROJECT : return new SourceFolderRoot ( resource , this ) ; default : return null ; } } void createLoadpathProblemMarker ( IRubyModelStatus status ) { IMarker marker = null ; int severity ; String [ ] arguments = new String [ ] ; boolean isCycleProblem = false , isClasspathFileFormatProblem = false ; switch ( status . getCode ( ) ) { case IRubyModelStatusConstants . CLASSPATH_CYCLE : isCycleProblem = true ; if ( RubyCore . ERROR . equals ( getOption ( RubyCore . CORE_CIRCULAR_CLASSPATH , true ) ) ) { severity = IMarker . SEVERITY_ERROR ; } else { severity = IMarker . SEVERITY_WARNING ; } break ; case IRubyModelStatusConstants . INVALID_LOADPATH_FILE_FORMAT : isClasspathFileFormatProblem = true ; severity = IMarker . SEVERITY_ERROR ; break ; case IRubyModelStatusConstants . INCOMPATIBLE_JDK_LEVEL : String setting = getOption ( RubyCore . CORE_INCOMPATIBLE_JDK_LEVEL , true ) ; if ( RubyCore . ERROR . equals ( setting ) ) { severity = IMarker . SEVERITY_ERROR ; } else if ( RubyCore . WARNING . equals ( setting ) ) { severity = IMarker . SEVERITY_WARNING ; } else { return ; } break ; default : IPath path = status . getPath ( ) ; if ( path != null ) arguments = new String [ ] { path . toString ( ) } ; if ( RubyCore . ERROR . equals ( getOption ( RubyCore . CORE_INCOMPLETE_CLASSPATH , true ) ) ) { severity = IMarker . SEVERITY_ERROR ; } else { severity = IMarker . SEVERITY_WARNING ; } break ; } try { marker = this . project . createMarker ( IRubyModelMarker . BUILDPATH_PROBLEM_MARKER ) ; marker . setAttributes ( new String [ ] { IMarker . MESSAGE , IMarker . SEVERITY , IMarker . LOCATION , IRubyModelMarker . CYCLE_DETECTED , IRubyModelMarker . CLASSPATH_FILE_FORMAT , IRubyModelMarker . ID , IRubyModelMarker . ARGUMENTS , IRubyModelMarker . CATEGORY_ID , } , new Object [ ] { status . getMessage ( ) , new Integer ( severity ) , Messages . classpath_buildPath , isCycleProblem ? "" : "" , isClasspathFileFormatProblem ? "" : "" , Integer . valueOf ( status . getCode ( ) ) , Util . getProblemArgumentsForMarker ( arguments ) , new Integer ( CategorizedProblem . CAT_BUILDPATH ) } ) ; } catch ( CoreException e ) { if ( RubyModelManager . VERBOSE ) { e . printStackTrace ( ) ; } } } protected void flushLoadpathProblemMarkers ( boolean flushCycleMarkers , boolean flushClasspathFormatMarkers ) { try { if ( this . project . isAccessible ( ) ) { IMarker [ ] markers = this . project . findMarkers ( IRubyModelMarker . BUILDPATH_PROBLEM_MARKER , false , IResource . DEPTH_ZERO ) ; for ( int i = , length = markers . length ; i < length ; i ++ ) { IMarker marker = markers [ i ] ; if ( flushCycleMarkers && flushClasspathFormatMarkers ) { marker . delete ( ) ; } else { String cycleAttr = ( String ) marker . getAttribute ( IRubyModelMarker . CYCLE_DETECTED ) ; String classpathFileFormatAttr = ( String ) marker . getAttribute ( IRubyModelMarker . CLASSPATH_FILE_FORMAT ) ; if ( ( flushCycleMarkers == ( cycleAttr != null && cycleAttr . equals ( "" ) ) ) && ( flushClasspathFormatMarkers == ( classpathFileFormatAttr != null && classpathFileFormatAttr . equals ( "" ) ) ) ) { marker . delete ( ) ; } } } } } catch ( CoreException e ) { if ( RubyModelManager . VERBOSE ) { e . printStackTrace ( ) ; } } } public static IPath canonicalizedPath ( IPath externalPath ) { if ( externalPath == null ) return null ; if ( IS_CASE_SENSITIVE ) { return externalPath ; } IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; if ( workspace == null ) return externalPath ; if ( workspace . getRoot ( ) . findMember ( externalPath ) != null ) { return externalPath ; } IPath canonicalPath = null ; try { canonicalPath = new Path ( new File ( externalPath . toOSString ( ) ) . getCanonicalPath ( ) ) ; } catch ( IOException e ) { return externalPath ; } IPath result ; int canonicalLength = canonicalPath . segmentCount ( ) ; if ( canonicalLength == ) { return externalPath ; } else if ( externalPath . isAbsolute ( ) ) { result = canonicalPath ; } else { int externalLength = externalPath . segmentCount ( ) ; if ( canonicalLength >= externalLength ) { result = canonicalPath . removeFirstSegments ( canonicalLength - externalLength ) ; } else { return externalPath ; } } if ( externalPath . getDevice ( ) == null ) { result = result . setDevice ( null ) ; } return result ; } public ILoadpathEntry [ ] getRawLoadpath ( ) throws RubyModelException { return getRawLoadpath ( false , true ) ; } public ISourceFolderRoot [ ] getSourceFolderRoots ( ) throws RubyModelException { Object [ ] children ; int length ; ISourceFolderRoot [ ] roots ; System . arraycopy ( children = getChildren ( ) , , roots = new ISourceFolderRoot [ length = children . length ] , , length ) ; return roots ; } public boolean isOnLoadpath ( IRubyElement element ) { ILoadpathEntry [ ] rawClasspath ; try { rawClasspath = getRawLoadpath ( ) ; } catch ( RubyModelException e ) { return false ; } int elementType = element . getElementType ( ) ; boolean isPackageFragmentRoot = false ; boolean isFolderPath = false ; boolean isSource = false ; switch ( elementType ) { case IRubyElement . RUBY_MODEL : return false ; case IRubyElement . RUBY_PROJECT : break ; case IRubyElement . SOURCE_FOLDER_ROOT : isPackageFragmentRoot = true ; break ; case IRubyElement . SOURCE_FOLDER : isFolderPath = ! ( ( ISourceFolderRoot ) element . getParent ( ) ) . isArchive ( ) ; break ; case IRubyElement . SCRIPT : isSource = true ; break ; default : isSource = element . getAncestor ( IRubyElement . SCRIPT ) != null ; break ; } IPath elementPath = element . getPath ( ) ; int length = rawClasspath . length ; for ( int i = ; i < length ; i ++ ) { ILoadpathEntry entry = rawClasspath [ i ] ; switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_LIBRARY : case ILoadpathEntry . CPE_PROJECT : case ILoadpathEntry . CPE_SOURCE : if ( isOnLoadpathEntry ( elementPath , isFolderPath , isPackageFragmentRoot , entry ) ) return true ; break ; } } if ( isSource ) return false ; for ( int i = ; i < length ; i ++ ) { ILoadpathEntry rawEntry = rawClasspath [ i ] ; switch ( rawEntry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_CONTAINER : ILoadpathContainer container ; try { container = RubyCore . getLoadpathContainer ( rawEntry . getPath ( ) , this ) ; } catch ( RubyModelException e ) { break ; } if ( container == null ) break ; ILoadpathEntry [ ] containerEntries = container . getLoadpathEntries ( ) ; if ( containerEntries == null ) break ; for ( int j = , containerLength = containerEntries . length ; j < containerLength ; j ++ ) { ILoadpathEntry resolvedEntry = containerEntries [ j ] ; if ( isOnLoadpathEntry ( elementPath , isFolderPath , isPackageFragmentRoot , resolvedEntry ) ) return true ; } break ; case ILoadpathEntry . CPE_VARIABLE : ILoadpathEntry resolvedEntry = RubyCore . getResolvedLoadpathEntry ( rawEntry ) ; if ( resolvedEntry == null ) break ; if ( isOnLoadpathEntry ( elementPath , isFolderPath , isPackageFragmentRoot , resolvedEntry ) ) return true ; break ; } } return false ; } private boolean isOnLoadpathEntry ( IPath elementPath , boolean isFolderPath , boolean isPackageFragmentRoot , ILoadpathEntry entry ) { IPath entryPath = entry . getPath ( ) ; if ( isPackageFragmentRoot ) { if ( entryPath . equals ( elementPath ) ) return true ; } else { if ( entryPath . isPrefixOf ( elementPath ) && ! Util . isExcluded ( elementPath , ( ( LoadpathEntry ) entry ) . fullInclusionPatternChars ( ) , ( ( LoadpathEntry ) entry ) . fullExclusionPatternChars ( ) , isFolderPath ) ) return true ; } return false ; } public ILoadpathEntry [ ] getResolvedLoadpath ( boolean ignoreUnresolvedEntry ) throws RubyModelException { return getResolvedLoadpath ( ignoreUnresolvedEntry , false , true ) ; } public ISourceFolderRoot [ ] computeSourceFolderRoots ( ILoadpathEntry resolvedEntry ) { try { return computeSourceFolderRoots ( new ILoadpathEntry [ ] { resolvedEntry } , false , null ) ; } catch ( RubyModelException e ) { return new ISourceFolderRoot [ ] { } ; } } public ILoadpathEntry [ ] getExpandedLoadpath ( boolean ignoreUnresolvedVariable ) throws RubyModelException { return getExpandedLoadpath ( ignoreUnresolvedVariable , false , null , null ) ; } private ILoadpathEntry [ ] getExpandedLoadpath ( boolean ignoreUnresolvedVariable , boolean generateMarkerOnError , Map preferredClasspaths , Map preferredOutputs ) throws RubyModelException { ObjectVector accumulatedEntries = new ObjectVector ( ) ; computeExpandedLoadpath ( null , ignoreUnresolvedVariable , generateMarkerOnError , new HashSet ( ) , accumulatedEntries , preferredClasspaths , preferredOutputs ) ; ILoadpathEntry [ ] expandedPath = new ILoadpathEntry [ accumulatedEntries . size ( ) ] ; accumulatedEntries . copyInto ( expandedPath ) ; return expandedPath ; } private void computeExpandedLoadpath ( LoadpathEntry referringEntry , boolean ignoreUnresolvedVariable , boolean generateMarkerOnError , HashSet rootIDs , ObjectVector accumulatedEntries , Map preferredClasspaths , Map preferredOutputs ) throws RubyModelException { String projectRootId = this . rootID ( ) ; if ( rootIDs . contains ( projectRootId ) ) { return ; } rootIDs . add ( projectRootId ) ; ILoadpathEntry [ ] preferredClasspath = preferredClasspaths != null ? ( ILoadpathEntry [ ] ) preferredClasspaths . get ( this ) : null ; IPath preferredOutput = preferredOutputs != null ? ( IPath ) preferredOutputs . get ( this ) : null ; ILoadpathEntry [ ] immediateClasspath = preferredClasspath != null ? getResolvedLoadpath ( preferredClasspath , preferredOutput , ignoreUnresolvedVariable , generateMarkerOnError , null ) : getResolvedLoadpath ( ignoreUnresolvedVariable , generateMarkerOnError , false ) ; IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; boolean isInitialProject = referringEntry == null ; for ( int i = , length = immediateClasspath . length ; i < length ; i ++ ) { LoadpathEntry entry = ( LoadpathEntry ) immediateClasspath [ i ] ; if ( isInitialProject || entry . isExported ( ) ) { String rootID = entry . rootID ( ) ; if ( rootIDs . contains ( rootID ) ) { continue ; } LoadpathEntry combinedEntry = entry . combineWith ( referringEntry ) ; accumulatedEntries . add ( combinedEntry ) ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { IResource member = workspaceRoot . findMember ( entry . getPath ( ) ) ; if ( member != null && member . getType ( ) == IResource . PROJECT ) { IProject projRsc = ( IProject ) member ; if ( RubyProject . hasRubyNature ( projRsc ) ) { RubyProject javaProject = ( RubyProject ) RubyCore . create ( projRsc ) ; javaProject . computeExpandedLoadpath ( combinedEntry , ignoreUnresolvedVariable , false , rootIDs , accumulatedEntries , preferredClasspaths , preferredOutputs ) ; } } } else { rootIDs . add ( rootID ) ; } } } } public void updateSourceFolderRoots ( ) { if ( this . isOpen ( ) ) { try { RubyProjectElementInfo info = getRubyProjectElementInfo ( ) ; computeChildren ( info ) ; info . resetCaches ( ) ; } catch ( RubyModelException e ) { try { close ( ) ; } catch ( RubyModelException ex ) { } } } } protected RubyProjectElementInfo getRubyProjectElementInfo ( ) throws RubyModelException { return ( RubyProjectElementInfo ) getElementInfo ( ) ; } public void computeChildren ( RubyProjectElementInfo info ) throws RubyModelException { ILoadpathEntry [ ] classpath = getResolvedLoadpath ( true , false , false ) ; RubyProjectElementInfo . ProjectCache projectCache = info . projectCache ; if ( projectCache != null ) { ISourceFolderRoot [ ] newRoots = computeSourceFolderRoots ( classpath , true , null ) ; checkIdentical : { ISourceFolderRoot [ ] oldRoots = projectCache . allPkgFragmentRootsCache ; if ( oldRoots . length == newRoots . length ) { for ( int i = , length = oldRoots . length ; i < length ; i ++ ) { if ( ! oldRoots [ i ] . equals ( newRoots [ i ] ) ) { break checkIdentical ; } } return ; } } } info . setNonRubyResources ( null ) ; info . setChildren ( computeSourceFolderRoots ( classpath , false , null ) ) ; } public ISourceFolderRoot [ ] getAllSourceFolderRoots ( Map rootToResolvedEntries ) throws RubyModelException { return computeSourceFolderRoots ( getResolvedLoadpath ( true , false , false ) , true , rootToResolvedEntries ) ; } public boolean hasCycleMarker ( ) { return this . getCycleMarker ( ) != null ; } public IMarker getCycleMarker ( ) { try { if ( this . project . isAccessible ( ) ) { IMarker [ ] markers = this . project . findMarkers ( IRubyModelMarker . BUILDPATH_PROBLEM_MARKER , false , IResource . DEPTH_ZERO ) ; for ( int i = , length = markers . length ; i < length ; i ++ ) { IMarker marker = markers [ i ] ; String cycleAttr = ( String ) marker . getAttribute ( IRubyModelMarker . CYCLE_DETECTED ) ; if ( cycleAttr != null && cycleAttr . equals ( "" ) ) { return marker ; } } } } catch ( CoreException e ) { } return null ; } public boolean hasLoadpathCycle ( ILoadpathEntry [ ] preferredClasspath ) { HashSet cycleParticipants = new HashSet ( ) ; HashMap preferredClasspaths = new HashMap ( ) ; preferredClasspaths . put ( this , preferredClasspath ) ; updateCycleParticipants ( new ArrayList ( ) , cycleParticipants , ResourcesPlugin . getWorkspace ( ) . getRoot ( ) , new HashSet ( ) , preferredClasspaths ) ; return ! cycleParticipants . isEmpty ( ) ; } public void updateCycleParticipants ( ArrayList prereqChain , HashSet cycleParticipants , IWorkspaceRoot workspaceRoot , HashSet traversed , Map preferredClasspaths ) { IPath path = this . getPath ( ) ; prereqChain . add ( path ) ; traversed . add ( path ) ; try { ILoadpathEntry [ ] classpath = null ; if ( preferredClasspaths != null ) classpath = ( ILoadpathEntry [ ] ) preferredClasspaths . get ( this ) ; if ( classpath == null ) classpath = getResolvedLoadpath ( true , false , false ) ; for ( int i = , length = classpath . length ; i < length ; i ++ ) { ILoadpathEntry entry = classpath [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { IPath prereqProjectPath = entry . getPath ( ) ; int index = cycleParticipants . contains ( prereqProjectPath ) ? : prereqChain . indexOf ( prereqProjectPath ) ; if ( index >= ) { for ( int size = prereqChain . size ( ) ; index < size ; index ++ ) { cycleParticipants . add ( prereqChain . get ( index ) ) ; } } else { if ( ! traversed . contains ( prereqProjectPath ) ) { IResource member = workspaceRoot . findMember ( prereqProjectPath ) ; if ( member != null && member . getType ( ) == IResource . PROJECT ) { RubyProject javaProject = ( RubyProject ) RubyCore . create ( ( IProject ) member ) ; javaProject . updateCycleParticipants ( prereqChain , cycleParticipants , workspaceRoot , traversed , preferredClasspaths ) ; } } } } } } catch ( RubyModelException e ) { } prereqChain . remove ( path ) ; } public static void updateAllCycleMarkers ( Map preferredClasspaths ) throws RubyModelException { IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IProject [ ] rscProjects = workspaceRoot . getProjects ( ) ; int length = rscProjects . length ; RubyProject [ ] projects = new RubyProject [ length ] ; HashSet cycleParticipants = new HashSet ( ) ; HashSet traversed = new HashSet ( ) ; ArrayList prereqChain = new ArrayList ( ) ; for ( int i = ; i < length ; i ++ ) { if ( hasRubyNature ( rscProjects [ i ] ) ) { RubyProject project = ( projects [ i ] = ( RubyProject ) RubyCore . create ( rscProjects [ i ] ) ) ; if ( ! traversed . contains ( project . getPath ( ) ) ) { prereqChain . clear ( ) ; project . updateCycleParticipants ( prereqChain , cycleParticipants , workspaceRoot , traversed , preferredClasspaths ) ; } } } for ( int i = ; i < length ; i ++ ) { RubyProject project = projects [ i ] ; if ( project != null ) { if ( cycleParticipants . contains ( project . getPath ( ) ) ) { IMarker cycleMarker = project . getCycleMarker ( ) ; String circularCPOption = project . getOption ( RubyCore . CORE_CIRCULAR_CLASSPATH , true ) ; int circularCPSeverity = RubyCore . ERROR . equals ( circularCPOption ) ? IMarker . SEVERITY_ERROR : IMarker . SEVERITY_WARNING ; if ( cycleMarker != null ) { try { int existingSeverity = ( ( Integer ) cycleMarker . getAttribute ( IMarker . SEVERITY ) ) . intValue ( ) ; if ( existingSeverity != circularCPSeverity ) { cycleMarker . setAttribute ( IMarker . SEVERITY , circularCPSeverity ) ; } } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } else { project . createLoadpathProblemMarker ( new RubyModelStatus ( IRubyModelStatusConstants . CLASSPATH_CYCLE , project ) ) ; } } else { project . flushLoadpathProblemMarkers ( true , false ) ; } } } } public void setRawLoadpath ( ILoadpathEntry [ ] newEntries , IPath newOutputLocation , IProgressMonitor monitor , boolean canChangeResource , ILoadpathEntry [ ] oldResolvedPath , boolean needValidation , boolean needSave ) throws RubyModelException { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; try { ILoadpathEntry [ ] newRawPath = newEntries ; if ( newRawPath == null ) { newRawPath = defaultLoadpath ( ) ; } SetLoadpathOperation op = new SetLoadpathOperation ( this , oldResolvedPath , newRawPath , newOutputLocation , canChangeResource , needValidation , needSave ) ; op . runOperation ( monitor ) ; } catch ( RubyModelException e ) { manager . getDeltaProcessor ( ) . flush ( ) ; throw e ; } } public boolean saveLoadpath ( ILoadpathEntry [ ] newLoadpath , IPath newOutputLocation ) throws RubyModelException { if ( ! this . project . isAccessible ( ) ) return false ; Map unknownElements = new HashMap ( ) ; ILoadpathEntry [ ] fileEntries = readLoadpathFile ( false , false , unknownElements ) ; if ( fileEntries != null && isLoadpathEqualsTo ( newLoadpath , newOutputLocation , fileEntries ) ) { return false ; } try { setSharedProperty ( LOADPATH_FILENAME , encodeLoadpath ( newLoadpath , newOutputLocation , true , unknownElements ) ) ; return true ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } public void setSharedProperty ( String key , String value ) throws CoreException { IFile rscFile = this . project . getFile ( key ) ; byte [ ] bytes = null ; try { bytes = value . getBytes ( org . rubypeople . rdt . core . util . Util . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { Util . log ( e , "" ) ; bytes = value . getBytes ( ) ; } InputStream inputStream = new ByteArrayInputStream ( bytes ) ; if ( rscFile . exists ( ) ) { if ( rscFile . isReadOnly ( ) ) { ResourcesPlugin . getWorkspace ( ) . validateEdit ( new IFile [ ] { rscFile } , null ) ; } rscFile . setContents ( inputStream , IResource . FORCE , null ) ; } else { rscFile . create ( inputStream , IResource . FORCE , null ) ; } } public boolean isLoadpathEqualsTo ( ILoadpathEntry [ ] newClasspath , IPath newOutputLocation , ILoadpathEntry [ ] otherClasspathWithOutput ) { if ( otherClasspathWithOutput == null || otherClasspathWithOutput . length == ) return false ; int length = otherClasspathWithOutput . length ; if ( length != newClasspath . length + ) return false ; for ( int i = ; i < length - ; i ++ ) { if ( ! otherClasspathWithOutput [ i ] . equals ( newClasspath [ i ] ) ) return false ; } return true ; } protected String encodeLoadpath ( ILoadpathEntry [ ] classpath , IPath outputLocation , boolean indent , Map unknownElements ) throws RubyModelException { try { ByteArrayOutputStream s = new ByteArrayOutputStream ( ) ; OutputStreamWriter writer = new OutputStreamWriter ( s , "" ) ; XMLWriter xmlWriter = new XMLWriter ( writer , this , true ) ; xmlWriter . startTag ( LoadpathEntry . TAG_LOADPATH , indent ) ; for ( int i = ; i < classpath . length ; ++ i ) { ( ( LoadpathEntry ) classpath [ i ] ) . elementEncode ( xmlWriter , this . project . getFullPath ( ) , indent , true , unknownElements ) ; } xmlWriter . endTag ( LoadpathEntry . TAG_LOADPATH , indent , true ) ; writer . flush ( ) ; writer . close ( ) ; return s . toString ( "" ) ; } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } } public void setRawLoadpath ( ILoadpathEntry [ ] entries , boolean canModifyResources , IProgressMonitor monitor ) throws RubyModelException { setRawLoadpath ( entries , SetLoadpathOperation . DO_NOT_SET_OUTPUT , monitor , canModifyResources , getResolvedLoadpath ( true , false , false ) , true , canModifyResources ) ; } public void setRawLoadpath ( ILoadpathEntry [ ] entries , IProgressMonitor monitor ) throws RubyModelException { setRawLoadpath ( entries , SetLoadpathOperation . DO_NOT_SET_OUTPUT , monitor , true , getResolvedLoadpath ( true , false , false ) , true , true ) ; } public void setRawLoadpath ( ILoadpathEntry [ ] entries , IPath outputLocation , IProgressMonitor monitor ) throws RubyModelException { setRawLoadpath ( entries , outputLocation , monitor , true , getResolvedLoadpath ( true , false , false ) , true , true ) ; } public ISourceFolderRoot getSourceFolderRoot ( String string ) { return getPackageFragmentRoot0 ( RubyProject . canonicalizedPath ( new Path ( string ) ) ) ; } private ISourceFolderRoot getPackageFragmentRoot0 ( IPath path ) { return new ExternalSourceFolderRoot ( path , this ) ; } protected void forceLoadpathReload ( IProgressMonitor monitor ) throws RubyModelException { if ( monitor != null && monitor . isCanceled ( ) ) return ; boolean wasSuccessful = false ; try { ILoadpathEntry [ ] fileEntries = readLoadpathFile ( false , false ) ; if ( fileEntries == null ) { return ; } RubyModelManager . PerProjectInfo info = getPerProjectInfo ( ) ; if ( info . rawLoadpath != null ) { if ( isLoadpathEqualsTo ( info . rawLoadpath , info . outputLocation , fileEntries ) ) { wasSuccessful = true ; return ; } } ILoadpathEntry [ ] oldResolvedLoadpath = info . resolvedLoadpath ; setRawLoadpath ( fileEntries , SetLoadpathOperation . DO_NOT_SET_OUTPUT , monitor , ! ResourcesPlugin . getWorkspace ( ) . isTreeLocked ( ) , oldResolvedLoadpath != null ? oldResolvedLoadpath : getResolvedLoadpath ( true , false , false ) , true , false ) ; wasSuccessful = true ; } catch ( RuntimeException e ) { if ( this . project . isAccessible ( ) ) { Util . log ( e , "" + getPath ( ) ) ; } throw e ; } catch ( RubyModelException e ) { if ( ! ResourcesPlugin . getWorkspace ( ) . isTreeLocked ( ) ) { if ( this . project . isAccessible ( ) ) { if ( e . getRubyModelStatus ( ) . getException ( ) instanceof CoreException ) { createLoadpathProblemMarker ( new RubyModelStatus ( IRubyModelStatusConstants . INVALID_LOADPATH_FILE_FORMAT , Messages . bind ( Messages . classpath_couldNotWriteClasspathFile , new String [ ] { getElementName ( ) , e . getMessage ( ) } ) ) ) ; } else { createLoadpathProblemMarker ( new RubyModelStatus ( IRubyModelStatusConstants . INVALID_LOADPATH_FILE_FORMAT , Messages . bind ( Messages . classpath_invalidClasspathInClasspathFile , new String [ ] { getElementName ( ) , e . getMessage ( ) } ) ) ) ; } } } throw e ; } finally { if ( ! wasSuccessful ) { try { this . getPerProjectInfo ( ) . updateLoadpathInformation ( RubyProject . INVALID_LOADPATH ) ; updateSourceFolderRoots ( ) ; } catch ( RubyModelException e ) { } } } } public void updateLoadpathMarkers ( Map preferredClasspaths , Map preferredOutputs ) { this . flushLoadpathProblemMarkers ( false , true ) ; this . flushLoadpathProblemMarkers ( false , false ) ; ILoadpathEntry [ ] classpath = this . readLoadpathFile ( true , false ) ; if ( preferredClasspaths != null ) { preferredClasspaths . put ( this , classpath == null ? INVALID_LOADPATH : classpath ) ; } if ( preferredOutputs != null ) { preferredOutputs . put ( this , null ) ; } if ( classpath != null ) { for ( int i = ; i < classpath . length ; i ++ ) { IRubyModelStatus status = LoadpathEntry . validateLoadpathEntry ( this , classpath [ i ] , false , true ) ; if ( ! status . isOK ( ) ) { if ( status . getCode ( ) == IRubyModelStatusConstants . INVALID_CLASSPATH && ( ( LoadpathEntry ) classpath [ i ] ) . isOptional ( ) ) continue ; this . createLoadpathProblemMarker ( status ) ; } } IRubyModelStatus status = LoadpathEntry . validateLoadpath ( this , classpath , null ) ; if ( ! status . isOK ( ) ) this . createLoadpathProblemMarker ( status ) ; } } public ILoadpathEntry [ ] decodeLoadpath ( String xmlClasspath , boolean createMarker , boolean logProblems ) { return decodeLoadpath ( xmlClasspath , createMarker , logProblems , null ) ; } public ISourceFolderRoot findSourceFolderRoot ( IPath path ) throws RubyModelException { return findSourceFolderRoot0 ( RubyProject . canonicalizedPath ( path ) ) ; } public ISourceFolderRoot findSourceFolderRoot0 ( IPath path ) throws RubyModelException { ISourceFolderRoot [ ] allRoots = this . getAllSourceFolderRoots ( ) ; if ( ! path . isAbsolute ( ) ) { throw new IllegalArgumentException ( Messages . path_mustBeAbsolute ) ; } for ( int i = ; i < allRoots . length ; i ++ ) { ISourceFolderRoot classpathRoot = allRoots [ i ] ; if ( classpathRoot . getPath ( ) . equals ( path ) ) { return classpathRoot ; } } return null ; } public ISourceFolderRoot [ ] findSourceFolderRoots ( ILoadpathEntry entry ) { try { ILoadpathEntry [ ] classpath = this . getRawLoadpath ( ) ; for ( int i = , length = classpath . length ; i < length ; i ++ ) { if ( classpath [ i ] . equals ( entry ) ) { return computeSourceFolderRoots ( getResolvedLoadpath ( new ILoadpathEntry [ ] { entry } , null , true , false , null ) , false , null ) ; } } } catch ( RubyModelException e ) { } return new ISourceFolderRoot [ ] { } ; } public ISourceFolderRoot [ ] getAllSourceFolderRoots ( ) throws RubyModelException { return getAllSourceFolderRoots ( null ) ; } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner owner ) { switch ( token . charAt ( ) ) { case JEM_SOURCEFOLDERROOT : String rootPath = ISourceFolderRoot . DEFAULT_PACKAGEROOT_PATH ; token = null ; while ( memento . hasMoreTokens ( ) ) { token = memento . nextToken ( ) ; char firstChar = token . charAt ( ) ; if ( firstChar != JEM_SOURCE_FOLDER && firstChar != JEM_COUNT ) { rootPath += token ; } else { break ; } } IPath path = new Path ( rootPath ) ; RubyElement root ; if ( path . isAbsolute ( ) ) { root = ( RubyElement ) getPackageFragmentRoot0 ( path ) ; } else root = ( RubyElement ) getSourceFolderRoot ( path ) ; if ( token != null && token . charAt ( ) == JEM_SOURCE_FOLDER ) { return root . getHandleFromMemento ( token , memento , owner ) ; } else { return root . getHandleFromMemento ( memento , owner ) ; } } return null ; } protected char getHandleMementoDelimiter ( ) { return JEM_RUBYPROJECT ; } public ITypeHierarchy newTypeHierarchy ( IRegion region , IProgressMonitor monitor ) throws RubyModelException { return newTypeHierarchy ( region , DefaultWorkingCopyOwner . PRIMARY , monitor ) ; } public ITypeHierarchy newTypeHierarchy ( IRegion region , WorkingCopyOwner owner , IProgressMonitor monitor ) throws RubyModelException { if ( region == null ) { throw new IllegalArgumentException ( Messages . hierarchy_nullRegion ) ; } IRubyScript [ ] workingCopies = RubyModelManager . getRubyModelManager ( ) . getWorkingCopies ( owner , true ) ; CreateTypeHierarchyOperation op = new CreateTypeHierarchyOperation ( region , workingCopies , null , true ) ; op . runOperation ( monitor ) ; return op . getResult ( ) ; } public boolean isOnLoadpath ( IResource resource ) { IPath exactPath = resource . getFullPath ( ) ; IPath path = exactPath ; boolean isFolderPath = resource . getType ( ) == IResource . FOLDER ; ILoadpathEntry [ ] classpath ; try { classpath = this . getResolvedLoadpath ( true , false , false ) ; } catch ( RubyModelException e ) { return false ; } for ( int i = ; i < classpath . length ; i ++ ) { ILoadpathEntry entry = classpath [ i ] ; IPath entryPath = entry . getPath ( ) ; if ( entryPath . equals ( exactPath ) ) { return true ; } if ( entryPath . isPrefixOf ( path ) && ! Util . isExcluded ( path , ( ( LoadpathEntry ) entry ) . fullInclusionPatternChars ( ) , ( ( LoadpathEntry ) entry ) . fullExclusionPatternChars ( ) , isFolderPath ) ) { return true ; } } return false ; } } package org . rubypeople . rdt . internal . core . search . processing ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IJob { int ForceImmediate = ; int CancelIfNotReady = ; int WaitUntilReady = ; boolean FAILED = false ; boolean COMPLETE = true ; public boolean belongsTo ( String jobFamily ) ; public void cancel ( ) ; public void ensureReadyToRun ( ) ; public boolean execute ( IProgressMonitor progress ) ; } package org . rubypeople . rdt . internal . core . search . processing ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . Job ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public abstract class JobManager implements Runnable { protected IJob [ ] awaitingJobs = new IJob [ ] ; protected int jobStart = ; protected int jobEnd = - ; protected boolean executing = false ; protected Thread processingThread ; protected Job progressJob ; private int enableCount = ; public static boolean VERBOSE = false ; public boolean activated = false ; private int awaitingClients = ; public void activateProcessing ( ) { this . activated = true ; } public synchronized int awaitingJobsCount ( ) { return this . activated ? this . jobEnd - this . jobStart + : ; } public synchronized IJob currentJob ( ) { if ( this . enableCount > && this . jobStart <= this . jobEnd ) return this . awaitingJobs [ this . jobStart ] ; return null ; } public void disable ( ) { this . enableCount -- ; if ( VERBOSE ) Util . verbose ( "" ) ; } public void discardJobs ( String jobFamily ) { if ( VERBOSE ) Util . verbose ( "" + jobFamily ) ; try { IJob currentJob ; synchronized ( this ) { currentJob = this . currentJob ( ) ; disable ( ) ; } if ( currentJob != null && ( jobFamily == null || currentJob . belongsTo ( jobFamily ) ) ) { currentJob . cancel ( ) ; while ( this . processingThread != null && this . executing ) { try { if ( VERBOSE ) Util . verbose ( "" + currentJob ) ; Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } } int loc = - ; synchronized ( this ) { for ( int i = this . jobStart ; i <= this . jobEnd ; i ++ ) { currentJob = this . awaitingJobs [ i ] ; if ( currentJob != null ) { this . awaitingJobs [ i ] = null ; if ( ! ( jobFamily == null || currentJob . belongsTo ( jobFamily ) ) ) { this . awaitingJobs [ ++ loc ] = currentJob ; } else { if ( VERBOSE ) Util . verbose ( "" + currentJob ) ; currentJob . cancel ( ) ; } } } this . jobStart = ; this . jobEnd = loc ; } } finally { enable ( ) ; } if ( VERBOSE ) Util . verbose ( "" + jobFamily ) ; } public synchronized void enable ( ) { this . enableCount ++ ; if ( VERBOSE ) Util . verbose ( "" ) ; this . notifyAll ( ) ; } protected synchronized boolean isJobWaiting ( IJob request ) { for ( int i = this . jobEnd ; i > this . jobStart ; i -- ) if ( request . equals ( this . awaitingJobs [ i ] ) ) return true ; return false ; } protected synchronized void moveToNextJob ( ) { if ( this . jobStart <= this . jobEnd ) { this . awaitingJobs [ this . jobStart ++ ] = null ; if ( this . jobStart > this . jobEnd ) { this . jobStart = ; this . jobEnd = - ; } } } protected void notifyIdle ( long idlingTime ) { } public boolean performConcurrentJob ( IJob searchJob , int waitingPolicy , IProgressMonitor progress ) { if ( VERBOSE ) Util . verbose ( "" + searchJob ) ; searchJob . ensureReadyToRun ( ) ; int concurrentJobWork = ; if ( progress != null ) progress . beginTask ( "" , concurrentJobWork ) ; boolean status = IJob . FAILED ; if ( awaitingJobsCount ( ) > ) { switch ( waitingPolicy ) { case IJob . ForceImmediate : if ( VERBOSE ) Util . verbose ( "" + searchJob ) ; try { disable ( ) ; status = searchJob . execute ( progress == null ? null : new SubProgressMonitor ( progress , concurrentJobWork ) ) ; } finally { enable ( ) ; } if ( VERBOSE ) Util . verbose ( "" + searchJob ) ; return status ; case IJob . CancelIfNotReady : if ( VERBOSE ) Util . verbose ( "" + searchJob ) ; if ( VERBOSE ) Util . verbose ( "" + searchJob ) ; throw new OperationCanceledException ( ) ; case IJob . WaitUntilReady : int awaitingWork ; IJob previousJob = null ; IJob currentJob ; IProgressMonitor subProgress = null ; int totalWork = this . awaitingJobsCount ( ) ; if ( progress != null && totalWork > ) { subProgress = new SubProgressMonitor ( progress , concurrentJobWork / ) ; subProgress . beginTask ( "" , totalWork ) ; concurrentJobWork = concurrentJobWork / ; } Thread t = this . processingThread ; int originalPriority = t == null ? - : t . getPriority ( ) ; try { if ( t != null ) t . setPriority ( Thread . currentThread ( ) . getPriority ( ) ) ; synchronized ( this ) { this . awaitingClients ++ ; } while ( ( awaitingWork = awaitingJobsCount ( ) ) > ) { if ( subProgress != null && subProgress . isCanceled ( ) ) throw new OperationCanceledException ( ) ; currentJob = currentJob ( ) ; if ( currentJob != null && currentJob != previousJob ) { if ( VERBOSE ) Util . verbose ( "" + searchJob ) ; if ( subProgress != null ) { subProgress . subTask ( Messages . bind ( Messages . manager_filesToIndex , Integer . toString ( awaitingWork ) ) ) ; subProgress . worked ( ) ; } previousJob = currentJob ; } try { if ( VERBOSE ) Util . verbose ( "" + searchJob ) ; Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } } finally { synchronized ( this ) { this . awaitingClients -- ; } if ( t != null && originalPriority > - && t . isAlive ( ) ) t . setPriority ( originalPriority ) ; } if ( subProgress != null ) subProgress . done ( ) ; } } status = searchJob . execute ( progress == null ? null : new SubProgressMonitor ( progress , concurrentJobWork ) ) ; if ( progress != null ) progress . done ( ) ; if ( VERBOSE ) Util . verbose ( "" + searchJob ) ; return status ; } public abstract String processName ( ) ; public synchronized void request ( IJob job ) { job . ensureReadyToRun ( ) ; int size = this . awaitingJobs . length ; if ( ++ this . jobEnd == size ) { this . jobEnd -= this . jobStart ; System . arraycopy ( this . awaitingJobs , this . jobStart , this . awaitingJobs = new IJob [ size * ] , , this . jobEnd ) ; this . jobStart = ; } this . awaitingJobs [ this . jobEnd ] = job ; if ( VERBOSE ) { Util . verbose ( "" + job ) ; Util . verbose ( "" + awaitingJobsCount ( ) ) ; } notifyAll ( ) ; } public synchronized void reset ( ) { if ( VERBOSE ) Util . verbose ( "" ) ; if ( this . processingThread != null ) { discardJobs ( null ) ; } else { this . processingThread = new Thread ( this , this . processName ( ) ) ; this . processingThread . setDaemon ( true ) ; this . processingThread . setPriority ( Thread . NORM_PRIORITY - ) ; this . processingThread . start ( ) ; } } public void run ( ) { long idlingStart = - ; activateProcessing ( ) ; try { class ProgressJob extends Job { ProgressJob ( String name ) { super ( name ) ; } protected IStatus run ( IProgressMonitor monitor ) { int awaitingJobsCount ; while ( ! monitor . isCanceled ( ) && ( awaitingJobsCount = awaitingJobsCount ( ) ) > ) { monitor . subTask ( Messages . bind ( Messages . manager_filesToIndex , Integer . toString ( awaitingJobsCount ) ) ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } return Status . OK_STATUS ; } } this . progressJob = null ; while ( this . processingThread != null ) { try { IJob job ; synchronized ( this ) { if ( this . processingThread == null ) continue ; if ( ( job = currentJob ( ) ) == null ) { if ( this . progressJob != null ) { this . progressJob . cancel ( ) ; this . progressJob = null ; } if ( idlingStart < ) idlingStart = System . currentTimeMillis ( ) ; else notifyIdle ( System . currentTimeMillis ( ) - idlingStart ) ; this . wait ( ) ; } else { idlingStart = - ; } } if ( job == null ) { notifyIdle ( System . currentTimeMillis ( ) - idlingStart ) ; Thread . sleep ( ) ; continue ; } if ( VERBOSE ) { Util . verbose ( awaitingJobsCount ( ) + "" ) ; Util . verbose ( "" + job ) ; } try { this . executing = true ; if ( this . progressJob == null ) { this . progressJob = new ProgressJob ( Messages . manager_indexingInProgress ) ; this . progressJob . setPriority ( Job . LONG ) ; this . progressJob . setSystem ( true ) ; this . progressJob . schedule ( ) ; } job . execute ( null ) ; } finally { this . executing = false ; if ( VERBOSE ) Util . verbose ( "" + job ) ; moveToNextJob ( ) ; if ( this . awaitingClients == ) Thread . sleep ( ) ; } } catch ( InterruptedException e ) { } } } catch ( RuntimeException e ) { if ( this . processingThread != null ) { Util . log ( e , "" ) ; this . discardJobs ( null ) ; this . processingThread = null ; this . reset ( ) ; } throw e ; } catch ( Error e ) { if ( this . processingThread != null && ! ( e instanceof ThreadDeath ) ) { Util . log ( e , "" ) ; this . discardJobs ( null ) ; this . processingThread = null ; this . reset ( ) ; } throw e ; } } public void shutdown ( ) { if ( VERBOSE ) Util . verbose ( "" ) ; disable ( ) ; discardJobs ( null ) ; Thread thread = this . processingThread ; try { if ( thread != null ) { synchronized ( this ) { this . processingThread = null ; this . notifyAll ( ) ; } thread . join ( ) ; } Job job = this . progressJob ; if ( job != null ) { job . cancel ( ) ; job . join ( ) ; } } catch ( InterruptedException e ) { } } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) . append ( this . enableCount ) . append ( '' ) ; int numJobs = this . jobEnd - this . jobStart + ; buffer . append ( "" ) . append ( numJobs ) . append ( '' ) ; for ( int i = ; i < numJobs && i < ; i ++ ) { buffer . append ( i ) . append ( "" + i + "" ) . append ( this . awaitingJobs [ this . jobStart + i ] ) . append ( '' ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core . search ; import java . util . HashSet ; import java . util . Iterator ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; public class PathCollector extends IndexQueryRequestor { public HashSet paths = new HashSet ( ) ; public boolean acceptIndexMatch ( String documentPath , SearchPattern indexRecord , SearchParticipant participant ) { paths . add ( documentPath ) ; return true ; } public String [ ] getPaths ( ) { String [ ] result = new String [ this . paths . size ( ) ] ; int i = ; for ( Iterator iter = this . paths . iterator ( ) ; iter . hasNext ( ) ; ) { result [ i ++ ] = ( String ) iter . next ( ) ; } return result ; } } package org . rubypeople . rdt . internal . core . search ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyModel ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . util . Util ; public class RubyWorkspaceScope extends RubySearchScope { private IPath [ ] enclosingPaths = null ; public RubyWorkspaceScope ( ) { } public boolean encloses ( IRubyElement element ) { return true ; } public boolean encloses ( String resourcePathString ) { return true ; } public IPath [ ] enclosingProjectsAndJars ( ) { IPath [ ] result = this . enclosingPaths ; if ( result != null ) { return result ; } long start = BasicSearchEngine . VERBOSE ? System . currentTimeMillis ( ) : - ; try { IRubyProject [ ] projects = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) . getRubyProjects ( ) ; Set < IPath > paths = new HashSet < IPath > ( projects . length * ) ; for ( int i = , length = projects . length ; i < length ; i ++ ) { RubyProject rubyProject = ( RubyProject ) projects [ i ] ; IPath projectPath = rubyProject . getProject ( ) . getFullPath ( ) ; paths . add ( projectPath ) ; ILoadpathEntry [ ] entries = rubyProject . getResolvedLoadpath ( true ) ; for ( int j = , eLength = entries . length ; j < eLength ; j ++ ) { ILoadpathEntry entry = entries [ j ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY ) { IPath path = entry . getPath ( ) ; Object target = RubyModel . getTarget ( path , false ) ; if ( target instanceof IFolder ) path = ( ( IFolder ) target ) . getFullPath ( ) ; paths . add ( entry . getPath ( ) ) ; } } } result = new IPath [ paths . size ( ) ] ; paths . toArray ( result ) ; return this . enclosingPaths = result ; } catch ( RubyModelException e ) { Util . log ( e , "" ) ; return new IPath [ ] ; } finally { if ( BasicSearchEngine . VERBOSE ) { long time = System . currentTimeMillis ( ) - start ; int length = result == null ? : result . length ; Util . verbose ( "" + length + "" + time + "" ) ; } } } public boolean equals ( Object o ) { return o == this ; } public int hashCode ( ) { return RubyWorkspaceScope . class . hashCode ( ) ; } public void processDelta ( IRubyElementDelta delta , int eventType ) { if ( this . enclosingPaths == null ) return ; IRubyElement element = delta . getElement ( ) ; switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { IRubyElementDelta child = children [ i ] ; this . processDelta ( child , eventType ) ; } break ; case IRubyElement . RUBY_PROJECT : int kind = delta . getKind ( ) ; switch ( kind ) { case IRubyElementDelta . ADDED : case IRubyElementDelta . REMOVED : this . enclosingPaths = null ; break ; case IRubyElementDelta . CHANGED : int flags = delta . getFlags ( ) ; if ( ( flags & IRubyElementDelta . F_CLOSED ) != || ( flags & IRubyElementDelta . F_OPENED ) != ) { this . enclosingPaths = null ; } else { children = delta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { IRubyElementDelta child = children [ i ] ; this . processDelta ( child , eventType ) ; } } break ; } break ; case IRubyElement . SOURCE_FOLDER_ROOT : kind = delta . getKind ( ) ; switch ( kind ) { case IRubyElementDelta . ADDED : case IRubyElementDelta . REMOVED : this . enclosingPaths = null ; break ; case IRubyElementDelta . CHANGED : int flags = delta . getFlags ( ) ; if ( ( flags & IRubyElementDelta . F_ADDED_TO_CLASSPATH ) > || ( flags & IRubyElementDelta . F_REMOVED_FROM_CLASSPATH ) > ) { this . enclosingPaths = null ; } break ; } break ; } } public String toString ( ) { StringBuffer result = new StringBuffer ( "" ) ; IPath [ ] paths = enclosingProjectsAndJars ( ) ; int length = paths == null ? : paths . length ; if ( length == ) { result . append ( "" ) ; } else { result . append ( "" ) ; for ( int i = ; i < length ; i ++ ) { result . append ( "" ) ; result . append ( paths [ i ] ) ; } result . append ( "" ) ; } return result . toString ( ) ; } } package org . rubypeople . rdt . internal . core . search ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . core . index . Index ; public class SubTypeSearchJob extends PatternSearchJob { SimpleSet indexes = new SimpleSet ( ) ; public SubTypeSearchJob ( SearchPattern pattern , SearchParticipant participant , IRubySearchScope scope , IndexQueryRequestor requestor ) { super ( pattern , participant , scope , requestor ) ; } public void finished ( ) { Object [ ] values = this . indexes . values ; for ( int i = , l = values . length ; i < l ; i ++ ) if ( values [ i ] != null ) ( ( Index ) values [ i ] ) . stopQuery ( ) ; } public boolean search ( Index index , IProgressMonitor progressMonitor ) { if ( index == null ) return COMPLETE ; if ( ! indexes . includes ( index ) ) { indexes . add ( index ) ; index . startQuery ( ) ; } return super . search ( index , progressMonitor ) ; } } package org . rubypeople . rdt . internal . core . search ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchDocument ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . core . search . SearchRequestor ; import org . rubypeople . rdt . internal . core . search . indexing . SourceIndexer ; import org . rubypeople . rdt . internal . core . search . matching . MatchLocator ; import org . rubypeople . rdt . internal . core . util . Util ; public class RubySearchParticipant extends SearchParticipant { private IndexSelector indexSelector ; @ Override public SearchDocument getDocument ( String documentPath ) { if ( Util . isERBLikeFileName ( new Path ( documentPath ) . lastSegment ( ) ) ) { return new ERBSearchDocument ( documentPath , this ) ; } return new RubySearchDocument ( documentPath , this ) ; } @ Override public void indexDocument ( SearchDocument document , IPath indexLocation ) { document . removeAllIndexEntries ( ) ; String documentPath = document . getPath ( ) ; if ( org . rubypeople . rdt . internal . core . util . Util . isRubyOrERBLikeFileName ( documentPath ) ) { new SourceIndexer ( document ) . indexDocument ( ) ; } } public IPath [ ] selectIndexes ( SearchPattern pattern , IRubySearchScope scope ) { if ( this . indexSelector == null ) { this . indexSelector = new IndexSelector ( scope , pattern ) ; } return this . indexSelector . getIndexLocations ( ) ; } public void locateMatches ( SearchDocument [ ] indexMatches , SearchPattern pattern , IRubySearchScope scope , SearchRequestor requestor , IProgressMonitor monitor ) throws CoreException { MatchLocator matchLocator = new MatchLocator ( pattern , requestor , scope , monitor == null ? null : new SubProgressMonitor ( monitor , ) ) ; if ( monitor != null && monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; matchLocator . locateMatches ( indexMatches ) ; } } package org . rubypeople . rdt . internal . core . search ; import java . util . ArrayList ; import java . util . List ; import java . util . StringTokenizer ; import org . rubypeople . rdt . internal . core . util . Util ; public class MethodPatternParser { private String selector ; private String typeName ; List < String > params = new ArrayList < String > ( ) ; public char [ ] getSelector ( ) { if ( selector == null ) return null ; return selector . toCharArray ( ) ; } public void parse ( String string ) { if ( string == null ) return ; int index = string . indexOf ( "" ) ; if ( index == - ) { index = string . indexOf ( "" ) ; } if ( index != - ) { typeName = string . substring ( , index ) ; selector = string . substring ( index + ) ; } else { selector = string ; typeName = null ; } index = selector . indexOf ( '' ) ; if ( index != - ) { String raw = selector . substring ( index + , selector . length ( ) - ) ; selector = selector . substring ( , index ) ; StringTokenizer tokenizer = new StringTokenizer ( raw , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) { String param = tokenizer . nextToken ( ) ; params . add ( param ) ; } } } public char [ ] getTypeSimpleName ( ) { if ( typeName == null ) return null ; String name = Util . getSimpleName ( typeName ) ; if ( name == null ) return null ; return name . toCharArray ( ) ; } public char [ ] getQualifiedTypeName ( ) { if ( typeName == null ) return null ; return typeName . toCharArray ( ) ; } public char [ ] [ ] getParameterNames ( ) { if ( params . isEmpty ( ) ) return null ; char [ ] [ ] parameters = new char [ params . size ( ) ] [ ] ; int i = ; for ( String param : params ) { parameters [ i ++ ] = param . toCharArray ( ) ; } return parameters ; } } package org . rubypeople . rdt . internal . core . search ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . search . IRubySearchScope ; public abstract class AbstractSearchScope implements IRubySearchScope { public abstract void processDelta ( IRubyElementDelta delta , int eventType ) ; } package org . rubypeople . rdt . internal . core . search . matching ; import org . eclipse . core . resources . IResource ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . search . SearchDocument ; import org . rubypeople . rdt . internal . core . Openable ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Util ; public class PossibleMatch { public static final String NO_SOURCE_FILE_NAME = "" ; public IResource resource ; public Openable openable ; public MatchingNodeSet nodeSet ; public char [ ] [ ] compoundName ; Node parsedUnit ; public SearchDocument document ; private String sourceFileName ; private char [ ] source ; public PossibleMatch ( MatchLocator locator , IResource resource , Openable openable , SearchDocument document , boolean mustResolve ) { this . resource = resource ; this . openable = openable ; this . document = document ; this . nodeSet = new MatchingNodeSet ( mustResolve ) ; char [ ] qualifiedName = getQualifiedName ( ) ; if ( qualifiedName != null ) this . compoundName = CharOperation . splitOn ( '' , qualifiedName ) ; } public void cleanUp ( ) { this . source = null ; if ( this . parsedUnit != null ) { this . parsedUnit = null ; } this . nodeSet = null ; } public boolean equals ( Object obj ) { if ( this . compoundName == null ) return super . equals ( obj ) ; if ( ! ( obj instanceof PossibleMatch ) ) return false ; return CharOperation . equals ( this . compoundName , ( ( PossibleMatch ) obj ) . compoundName ) ; } public char [ ] getContents ( ) { if ( this . source != null ) return this . source ; return this . source = this . document . getCharContents ( ) ; } public char [ ] getFileName ( ) { return this . openable . getElementName ( ) . toCharArray ( ) ; } public char [ ] getMainTypeName ( ) { return this . compoundName [ this . compoundName . length - ] ; } public char [ ] [ ] getPackageName ( ) { int length = this . compoundName . length ; if ( length <= ) return CharOperation . NO_CHAR_CHAR ; return CharOperation . subarray ( this . compoundName , , length - ) ; } private char [ ] getQualifiedName ( ) { if ( this . openable instanceof RubyScript ) { String fileName = this . openable . getElementName ( ) ; char [ ] mainTypeName = Util . getNameWithoutRubyLikeExtension ( fileName ) . toCharArray ( ) ; RubyScript cu = ( RubyScript ) this . openable ; return cu . getType ( new String ( mainTypeName ) ) . getFullyQualifiedName ( ) . toCharArray ( ) ; } return null ; } private String getSourceFileName ( ) { if ( this . sourceFileName != null ) return this . sourceFileName ; this . sourceFileName = NO_SOURCE_FILE_NAME ; return this . sourceFileName ; } public int hashCode ( ) { if ( this . compoundName == null ) return super . hashCode ( ) ; int hashCode = ; for ( int i = , length = this . compoundName . length ; i < length ; i ++ ) hashCode += CharOperation . hashCode ( this . compoundName [ i ] ) ; return hashCode ; } public String toString ( ) { return this . openable == null ? "" : this . openable . toString ( ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import java . io . IOException ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . index . EntryResult ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class ConstructorPattern extends RubySearchPattern implements IIndexConstants { protected boolean findDeclarations ; protected boolean findReferences ; public char [ ] declaringQualification ; public char [ ] declaringSimpleName ; public char [ ] [ ] parameterNames ; public int parameterCount ; public boolean varargs = false ; boolean constructorParameters = false ; protected static char [ ] [ ] REF_CATEGORIES = { CONSTRUCTOR_REF } ; protected static char [ ] [ ] REF_AND_DECL_CATEGORIES = { CONSTRUCTOR_REF , CONSTRUCTOR_DECL } ; protected static char [ ] [ ] DECL_CATEGORIES = { CONSTRUCTOR_DECL } ; public static char [ ] createIndexKey ( char [ ] typeName , int argCount ) { char [ ] countChars = argCount < ? COUNTS [ argCount ] : ( "" + String . valueOf ( argCount ) ) . toCharArray ( ) ; return CharOperation . concat ( typeName , countChars ) ; } ConstructorPattern ( int matchRule ) { super ( CONSTRUCTOR_PATTERN , matchRule ) ; } public ConstructorPattern ( boolean findDeclarations , boolean findReferences , char [ ] declaringSimpleName , char [ ] declaringQualification , char [ ] [ ] parameterNames , int matchRule ) { this ( matchRule ) ; this . findDeclarations = findDeclarations ; this . findReferences = findReferences ; this . declaringQualification = isCaseSensitive ( ) ? declaringQualification : CharOperation . toLowerCase ( declaringQualification ) ; this . declaringSimpleName = ( isCaseSensitive ( ) || isCamelCase ( ) ) ? declaringSimpleName : CharOperation . toLowerCase ( declaringSimpleName ) ; if ( parameterNames != null ) { this . parameterCount = parameterNames . length ; int offset = ; this . parameterNames = new char [ this . parameterCount ] [ ] ; for ( int i = ; i < this . parameterCount ; i ++ ) { this . parameterNames [ i ] = isCaseSensitive ( ) ? parameterNames [ i + offset ] : CharOperation . toLowerCase ( parameterNames [ i + offset ] ) ; } } else { this . parameterCount = - ; } ( ( InternalSearchPattern ) this ) . mustResolve = mustResolve ( ) ; } public ConstructorPattern ( boolean findDeclarations , boolean findReferences , char [ ] declaringSimpleName , char [ ] declaringQualification , char [ ] [ ] parameterNames , IMethod method , int matchRule ) { this ( findDeclarations , findReferences , declaringSimpleName , declaringQualification , parameterNames , matchRule ) ; this . varargs = true ; } public void decodeIndexKey ( char [ ] key ) { int last = key . length - ; this . parameterCount = ; this . declaringSimpleName = null ; int power = ; for ( int i = last ; i >= ; i -- ) { if ( key [ i ] == SEPARATOR ) { System . arraycopy ( key , , this . declaringSimpleName = new char [ i ] , , i ) ; break ; } if ( i == last ) { this . parameterCount = key [ i ] - '' ; } else { power *= ; this . parameterCount += power * ( key [ i ] - '' ) ; } } } public SearchPattern getBlankPattern ( ) { return new ConstructorPattern ( R_EXACT_MATCH | R_CASE_SENSITIVE ) ; } public char [ ] [ ] getIndexCategories ( ) { if ( this . findReferences ) return this . findDeclarations ? REF_AND_DECL_CATEGORIES : REF_CATEGORIES ; if ( this . findDeclarations ) return DECL_CATEGORIES ; return CharOperation . NO_CHAR_CHAR ; } boolean hasConstructorParameters ( ) { return constructorParameters ; } public boolean matchesDecodedKey ( SearchPattern decodedPattern ) { ConstructorPattern pattern = ( ConstructorPattern ) decodedPattern ; return ( this . parameterCount == pattern . parameterCount || this . parameterCount == - || this . varargs ) && matchesName ( this . declaringSimpleName , pattern . declaringSimpleName ) ; } protected boolean mustResolve ( ) { if ( this . declaringQualification != null ) return true ; return this . findReferences ; } EntryResult [ ] queryIn ( Index index ) throws IOException { char [ ] key = this . declaringSimpleName ; int matchRule = getMatchRule ( ) ; switch ( getMatchMode ( ) ) { case R_EXACT_MATCH : if ( this . isCamelCase ) break ; if ( this . declaringSimpleName != null && this . parameterCount >= && ! this . varargs ) key = createIndexKey ( this . declaringSimpleName , this . parameterCount ) ; else { matchRule &= ~ R_EXACT_MATCH ; matchRule |= R_PREFIX_MATCH ; } break ; case R_PREFIX_MATCH : break ; case R_PATTERN_MATCH : if ( this . parameterCount >= && ! this . varargs ) key = createIndexKey ( this . declaringSimpleName == null ? ONE_STAR : this . declaringSimpleName , this . parameterCount ) ; else if ( this . declaringSimpleName != null && this . declaringSimpleName [ this . declaringSimpleName . length - ] != '' ) key = CharOperation . concat ( this . declaringSimpleName , ONE_STAR , SEPARATOR ) ; break ; case R_REGEXP_MATCH : break ; } return index . query ( getIndexCategories ( ) , key , matchRule ) ; } protected StringBuffer print ( StringBuffer output ) { if ( this . findDeclarations ) { output . append ( this . findReferences ? "" : "" ) ; } else { output . append ( "" ) ; } if ( declaringQualification != null ) output . append ( declaringQualification ) . append ( '' ) ; if ( declaringSimpleName != null ) output . append ( declaringSimpleName ) ; else if ( declaringQualification != null ) output . append ( "" ) ; output . append ( '' ) ; if ( parameterNames == null ) { output . append ( "" ) ; } else { for ( int i = , max = parameterNames . length ; i < max ; i ++ ) { if ( i > ) output . append ( "" ) ; if ( parameterNames [ i ] == null ) output . append ( '' ) ; else output . append ( parameterNames [ i ] ) ; } } output . append ( '' ) ; return super . print ( output ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . internal . core . LocalVariable ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . IndexQueryRequestor ; import org . rubypeople . rdt . internal . core . search . RubySearchScope ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . Util ; public class LocalVariablePattern extends VariablePattern implements IIndexConstants { LocalVariable localVariable ; public LocalVariablePattern ( boolean findDeclarations , boolean readAccess , boolean writeAccess , LocalVariable localVariable , int matchRule ) { super ( LOCAL_VAR_PATTERN , findDeclarations , readAccess , writeAccess , localVariable . getElementName ( ) . toCharArray ( ) , matchRule ) ; this . localVariable = localVariable ; } public void findIndexMatches ( Index index , IndexQueryRequestor requestor , SearchParticipant participant , IRubySearchScope scope , IProgressMonitor progressMonitor ) { ISourceFolderRoot root = ( ISourceFolderRoot ) this . localVariable . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; String documentPath ; String relativePath ; IPath path = this . localVariable . getPath ( ) ; documentPath = path . toString ( ) ; relativePath = Util . relativePath ( path , ) ; if ( scope instanceof RubySearchScope ) { RubySearchScope javaSearchScope = ( RubySearchScope ) scope ; if ( ! requestor . acceptIndexMatch ( documentPath , this , participant ) ) throw new OperationCanceledException ( ) ; } else if ( scope . encloses ( documentPath ) ) { if ( ! requestor . acceptIndexMatch ( documentPath , this , participant ) ) throw new OperationCanceledException ( ) ; } } protected StringBuffer print ( StringBuffer output ) { if ( this . findDeclarations ) { output . append ( this . findReferences ? "" : "" ) ; } else { output . append ( "" ) ; } output . append ( this . localVariable . toStringWithAncestors ( ) ) ; return super . print ( output ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class FieldPattern extends VariablePattern implements IIndexConstants { protected char [ ] declaringQualification ; protected char [ ] declaringSimpleName ; protected static char [ ] [ ] REF_CATEGORIES = { REF } ; protected static char [ ] [ ] REF_AND_DECL_CATEGORIES = { REF , FIELD_DECL } ; protected static char [ ] [ ] DECL_CATEGORIES = { FIELD_DECL } ; public static char [ ] createIndexKey ( char [ ] fieldName ) { return fieldName ; } public FieldPattern ( boolean findDeclarations , boolean readAccess , boolean writeAccess , char [ ] name , char [ ] declaringQualification , char [ ] declaringSimpleName , int matchRule ) { super ( FIELD_PATTERN , findDeclarations , readAccess , writeAccess , name , matchRule ) ; this . declaringQualification = isCaseSensitive ( ) ? declaringQualification : CharOperation . toLowerCase ( declaringQualification ) ; this . declaringSimpleName = isCaseSensitive ( ) ? declaringSimpleName : CharOperation . toLowerCase ( declaringSimpleName ) ; ( ( InternalSearchPattern ) this ) . mustResolve = mustResolve ( ) ; } public void decodeIndexKey ( char [ ] key ) { this . name = key ; } public SearchPattern getBlankPattern ( ) { return new FieldPattern ( false , false , false , null , null , null , R_EXACT_MATCH | R_CASE_SENSITIVE ) ; } public char [ ] getIndexKey ( ) { return this . name ; } public char [ ] [ ] getIndexCategories ( ) { if ( this . findReferences ) return this . findDeclarations || this . writeAccess ? REF_AND_DECL_CATEGORIES : REF_CATEGORIES ; if ( this . findDeclarations ) return DECL_CATEGORIES ; return CharOperation . NO_CHAR_CHAR ; } public boolean matchesDecodedKey ( SearchPattern decodedPattern ) { return true ; } protected boolean mustResolve ( ) { if ( this . declaringSimpleName != null || this . declaringQualification != null ) return true ; return super . mustResolve ( ) ; } protected StringBuffer print ( StringBuffer output ) { if ( this . findDeclarations ) { output . append ( this . findReferences ? "" : "" ) ; } else { output . append ( "" ) ; } if ( declaringQualification != null ) output . append ( declaringQualification ) . append ( '' ) ; if ( declaringSimpleName != null ) output . append ( declaringSimpleName ) . append ( '' ) ; else if ( declaringQualification != null ) output . append ( "" ) ; if ( name == null ) { output . append ( "" ) ; } else { output . append ( name ) ; } return super . print ( output ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . jruby . ast . CallNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . IArgumentNode ; import org . jruby . ast . Node ; import org . jruby . ast . VCallNode ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; public class MethodLocator extends PatternLocator { private MethodPattern pattern ; public MethodLocator ( MethodPattern pattern ) { super ( pattern ) ; this . pattern = pattern ; } @ Override public void reportMatches ( RubyScript script , MatchLocator locator ) { if ( ! this . pattern . findReferences ) { reportMatches ( ( IParent ) script , locator ) ; } else { reportASTMatches ( script , locator ) ; } } private void reportASTMatches ( final RubyScript script , final MatchLocator locator ) { try { Node ast = script . lastGoodAST ; if ( ast == null ) { ast = new RubyParser ( ) . parse ( script . getElementName ( ) , script . getSource ( ) ) . getAST ( ) ; } final boolean findDeclarations = this . pattern . findDeclarations ; new InOrderVisitor ( ) { @ Override public Object visitVCallNode ( VCallNode iVisited ) { match ( iVisited , ) ; return super . visitVCallNode ( iVisited ) ; } @ Override public Object visitFCallNode ( FCallNode iVisited ) { match ( iVisited , getArgumentsFromFunctionCall ( iVisited ) . size ( ) ) ; return super . visitFCallNode ( iVisited ) ; } @ Override public Object visitCallNode ( CallNode iVisited ) { match ( iVisited , getArgumentsFromFunctionCall ( iVisited ) . size ( ) ) ; return super . visitCallNode ( iVisited ) ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { if ( findDeclarations ) matchDeclaration ( iVisited , iVisited . getArgsNode ( ) . getRequiredArgsCount ( ) ) ; return super . visitDefnNode ( iVisited ) ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { if ( findDeclarations ) matchDeclaration ( iVisited , iVisited . getArgsNode ( ) . getRequiredArgsCount ( ) ) ; return super . visitDefsNode ( iVisited ) ; } private void match ( Node iVisited , int arity ) { String name = ( ( INameNode ) iVisited ) . getName ( ) ; int accuracy = getAccuracy ( name , arity ) ; if ( accuracy != IMPOSSIBLE_MATCH ) { try { IRubyElement element = script . getElementAt ( iVisited . getPosition ( ) . getStartOffset ( ) ) ; if ( element == null ) element = script ; if ( locator . encloses ( element ) ) { IRubyElement binding = resolve ( element , iVisited ) ; int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int length = iVisited . getPosition ( ) . getEndOffset ( ) - start ; boolean isConstructor = false ; if ( name . equals ( "" ) ) { isConstructor = true ; } List < String > args = new ArrayList < String > ( ) ; if ( iVisited instanceof IArgumentNode ) { args = getArgumentsFromFunctionCall ( ( IArgumentNode ) iVisited ) ; } locator . report ( locator . newMethodReferenceMatch ( element , binding , args , accuracy , start , length , isConstructor , iVisited ) ) ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } private IRubyElement resolve ( IRubyElement element , Node visited ) { return element ; } private void matchDeclaration ( Node iVisited , int arity ) { String name = ( ( INameNode ) iVisited ) . getName ( ) ; int accuracy = getAccuracy ( name , arity ) ; if ( accuracy != IMPOSSIBLE_MATCH ) { try { IRubyElement element = script . getElementAt ( iVisited . getPosition ( ) . getStartOffset ( ) ) ; if ( element == null ) element = script ; if ( locator . encloses ( element ) ) { int start = iVisited . getPosition ( ) . getStartOffset ( ) ; int length = iVisited . getPosition ( ) . getEndOffset ( ) - start ; locator . report ( locator . newDeclarationMatch ( element , accuracy , start , length ) ) ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } } . acceptNode ( ast ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } private void reportMatches ( IParent parent , MatchLocator locator ) { try { IRubyElement [ ] children = parent . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { IRubyElement child = children [ i ] ; if ( child . isType ( IRubyElement . METHOD ) && locator . encloses ( child ) ) { IMethod method = ( IMethod ) child ; int accuracy = getAccuracy ( method ) ; if ( accuracy != IMPOSSIBLE_MATCH ) { IMember member = ( IMember ) child ; ISourceRange range = member . getSourceRange ( ) ; try { locator . report ( locator . newDeclarationMatch ( child , accuracy , range . getOffset ( ) , range . getLength ( ) ) ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } if ( child instanceof IParent ) { IParent parentTwo = ( IParent ) child ; reportMatches ( parentTwo , locator ) ; } } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } private int getAccuracy ( IMethod method ) throws RubyModelException { int accuracy = getAccuracy ( method . getElementName ( ) , method . getParameterNames ( ) . length ) ; if ( accuracy == IMPOSSIBLE_MATCH ) return accuracy ; IType type = method . getDeclaringType ( ) ; char [ ] declaringTypeName = new char [ ] ; if ( type != null ) { declaringTypeName = type . getElementName ( ) . toCharArray ( ) ; } if ( pattern . declaringSimpleName != null && ! matchesName ( pattern . declaringSimpleName , declaringTypeName ) ) return IMPOSSIBLE_MATCH ; return ACCURATE_MATCH ; } private int getAccuracy ( String name , int arity ) { if ( ! matchesName ( this . pattern . selector , name . toCharArray ( ) ) ) return IMPOSSIBLE_MATCH ; if ( this . pattern . parameterNames != null ) { int length = this . pattern . parameterNames . length ; if ( length != arity ) return IMPOSSIBLE_MATCH ; } return ACCURATE_MATCH ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class TypeReferencePattern extends AndPattern implements IIndexConstants { protected char [ ] qualification ; protected char [ ] simpleName ; protected char [ ] currentCategory ; public int segmentsSize ; protected char [ ] [ ] segments ; protected int currentSegment ; protected static char [ ] [ ] CATEGORIES = { REF } ; public TypeReferencePattern ( char [ ] qualification , char [ ] simpleName , int matchRule ) { this ( matchRule ) ; if ( qualification != null && qualification . length == ) { this . qualification = null ; } else { this . qualification = isCaseSensitive ( ) ? qualification : CharOperation . toLowerCase ( qualification ) ; } this . simpleName = ( isCaseSensitive ( ) || isCamelCase ( ) ) ? simpleName : CharOperation . toLowerCase ( simpleName ) ; if ( simpleName == null ) this . segments = this . qualification == null ? ONE_STAR_CHAR : CharOperation . splitOn ( "" , this . qualification ) ; else this . segments = null ; if ( this . segments == null ) if ( this . qualification == null ) this . segmentsSize = ; else this . segmentsSize = CharOperation . occurencesOf ( "" , this . qualification ) + ; else this . segmentsSize = this . segments . length ; ( ( InternalSearchPattern ) this ) . mustResolve = true ; } TypeReferencePattern ( int matchRule ) { super ( TYPE_REF_PATTERN , matchRule ) ; } public void decodeIndexKey ( char [ ] key ) { this . simpleName = key ; } public SearchPattern getBlankPattern ( ) { return new TypeReferencePattern ( R_EXACT_MATCH | R_CASE_SENSITIVE ) ; } public char [ ] getIndexKey ( ) { if ( this . simpleName != null ) return this . simpleName ; if ( this . currentSegment >= ) return this . segments [ this . currentSegment ] ; return null ; } public char [ ] [ ] getIndexCategories ( ) { return CATEGORIES ; } protected boolean hasNextQuery ( ) { if ( this . segments == null ) return false ; return -- this . currentSegment >= ( this . segments . length >= ? : ) ; } public boolean matchesDecodedKey ( SearchPattern decodedPattern ) { return true ; } protected void resetQuery ( ) { if ( this . segments != null ) this . currentSegment = this . segments . length - ; } protected StringBuffer print ( StringBuffer output ) { output . append ( "" ) ; if ( qualification != null ) output . append ( qualification ) ; else output . append ( "" ) ; output . append ( "" ) ; if ( simpleName != null ) output . append ( simpleName ) ; else output . append ( "" ) ; output . append ( ">" ) ; return super . print ( output ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyScript ; public class LocalVariableLocator extends VariableLocator { public LocalVariableLocator ( LocalVariablePattern pattern ) { super ( pattern ) ; } @ Override public void reportMatches ( RubyScript script , MatchLocator locator ) { reportMatches ( ( IParent ) script , locator ) ; } private void reportMatches ( IParent parent , MatchLocator locator ) { try { IRubyElement [ ] children = parent . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { IRubyElement child = children [ i ] ; if ( child . isType ( IRubyElement . LOCAL_VARIABLE ) ) { int accuracy = getAccuracy ( ( IField ) child ) ; if ( accuracy != IMPOSSIBLE_MATCH ) { IMember member = ( IMember ) child ; ISourceRange range = member . getSourceRange ( ) ; try { locator . report ( locator . newDeclarationMatch ( child , accuracy , range . getOffset ( ) , range . getLength ( ) ) ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } if ( child instanceof IParent ) { IParent parentTwo = ( IParent ) child ; reportMatches ( parentTwo , locator ) ; } } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } } package org . rubypeople . rdt . internal . core . search . matching ; import java . io . IOException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . IndexQueryRequestor ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; public class OrPattern extends SearchPattern implements IIndexConstants { protected SearchPattern [ ] patterns ; int matchCompatibility ; public OrPattern ( SearchPattern leftPattern , SearchPattern rightPattern ) { super ( Math . max ( leftPattern . getMatchRule ( ) , rightPattern . getMatchRule ( ) ) ) ; ( ( InternalSearchPattern ) this ) . kind = OR_PATTERN ; ( ( InternalSearchPattern ) this ) . mustResolve = ( ( InternalSearchPattern ) leftPattern ) . mustResolve || ( ( InternalSearchPattern ) rightPattern ) . mustResolve ; SearchPattern [ ] leftPatterns = leftPattern instanceof OrPattern ? ( ( OrPattern ) leftPattern ) . patterns : null ; SearchPattern [ ] rightPatterns = rightPattern instanceof OrPattern ? ( ( OrPattern ) rightPattern ) . patterns : null ; int leftSize = leftPatterns == null ? : leftPatterns . length ; int rightSize = rightPatterns == null ? : rightPatterns . length ; this . patterns = new SearchPattern [ leftSize + rightSize ] ; if ( leftPatterns == null ) this . patterns [ ] = leftPattern ; else System . arraycopy ( leftPatterns , , this . patterns , , leftSize ) ; if ( rightPatterns == null ) this . patterns [ leftSize ] = rightPattern ; else System . arraycopy ( rightPatterns , , this . patterns , leftSize , rightSize ) ; matchCompatibility = ; for ( int i = , length = this . patterns . length ; i < length ; i ++ ) { matchCompatibility |= ( ( RubySearchPattern ) this . patterns [ i ] ) . matchCompatibility ; } } void findIndexMatches ( Index index , IndexQueryRequestor requestor , SearchParticipant participant , IRubySearchScope scope , IProgressMonitor progressMonitor ) throws IOException { try { index . startQuery ( ) ; for ( int i = , length = this . patterns . length ; i < length ; i ++ ) ( ( InternalSearchPattern ) this . patterns [ i ] ) . findIndexMatches ( index , requestor , participant , scope , progressMonitor ) ; } finally { index . stopQuery ( ) ; } } public SearchPattern getBlankPattern ( ) { return null ; } boolean isErasureMatch ( ) { return ( this . matchCompatibility & R_ERASURE_MATCH ) != ; } boolean isPolymorphicSearch ( ) { for ( int i = , length = this . patterns . length ; i < length ; i ++ ) if ( ( ( InternalSearchPattern ) this . patterns [ i ] ) . isPolymorphicSearch ( ) ) return true ; return false ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( this . patterns [ ] . toString ( ) ) ; for ( int i = , length = this . patterns . length ; i < length ; i ++ ) { buffer . append ( "" ) ; buffer . append ( this . patterns [ i ] . toString ( ) ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import java . io . IOException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . core . index . EntryResult ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . IndexQueryRequestor ; public abstract class AndPattern extends RubySearchPattern { public AndPattern ( int patternKind , int matchRule ) { super ( patternKind , matchRule ) ; } public void findIndexMatches ( Index index , IndexQueryRequestor requestor , SearchParticipant participant , IRubySearchScope scope , IProgressMonitor progressMonitor ) throws IOException { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; this . resetQuery ( ) ; SimpleSet intersectedNames = null ; try { index . startQuery ( ) ; do { SearchPattern pattern = ( ( InternalSearchPattern ) this ) . currentPattern ( ) ; EntryResult [ ] entries = ( ( InternalSearchPattern ) pattern ) . queryIn ( index ) ; if ( entries == null ) return ; SearchPattern decodedResult = pattern . getBlankPattern ( ) ; SimpleSet newIntersectedNames = new SimpleSet ( ) ; for ( int i = , l = entries . length ; i < l ; i ++ ) { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; EntryResult entry = entries [ i ] ; decodedResult . decodeIndexKey ( entry . getWord ( ) ) ; if ( pattern . matchesDecodedKey ( decodedResult ) ) { String [ ] names = entry . getDocumentNames ( index ) ; if ( intersectedNames != null ) { for ( int j = , n = names . length ; j < n ; j ++ ) if ( intersectedNames . includes ( names [ j ] ) ) newIntersectedNames . add ( names [ j ] ) ; } else { for ( int j = , n = names . length ; j < n ; j ++ ) newIntersectedNames . add ( names [ j ] ) ; } } } if ( newIntersectedNames . elementSize == ) return ; intersectedNames = newIntersectedNames ; } while ( this . hasNextQuery ( ) ) ; } finally { index . stopQuery ( ) ; } String containerPath = index . containerPath ; Object [ ] names = intersectedNames . values ; for ( int i = , l = names . length ; i < l ; i ++ ) if ( names [ i ] != null ) ( ( InternalSearchPattern ) this ) . acceptMatch ( ( String ) names [ i ] , containerPath , null , requestor , participant , scope ) ; } protected abstract boolean hasNextQuery ( ) ; protected abstract void resetQuery ( ) ; } package org . rubypeople . rdt . internal . core . search . matching ; import java . io . IOException ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . index . EntryResult ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class TypeDeclarationPattern extends RubySearchPattern implements IIndexConstants { public char [ ] simpleName ; public char [ ] pkg ; public char [ ] [ ] enclosingTypeNames ; public char typeSuffix ; public int modifiers ; public boolean secondary = false ; protected static char [ ] [ ] CATEGORIES = { TYPE_DECL } ; static PackageNameSet internedPackageNames = new PackageNameSet ( ) ; static class PackageNameSet { public char [ ] [ ] names ; public int elementSize ; public int threshold ; PackageNameSet ( int size ) { this . elementSize = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . names = new char [ extraRoom ] [ ] ; } char [ ] add ( char [ ] name ) { int length = names . length ; int index = CharOperation . hashCode ( name ) % length ; char [ ] current ; while ( ( current = names [ index ] ) != null ) { if ( CharOperation . equals ( current , name ) ) return current ; if ( ++ index == length ) index = ; } names [ index ] = name ; if ( ++ elementSize > threshold ) rehash ( ) ; return name ; } void rehash ( ) { PackageNameSet newSet = new PackageNameSet ( elementSize * ) ; char [ ] current ; for ( int i = names . length ; -- i >= ; ) if ( ( current = names [ i ] ) != null ) newSet . add ( current ) ; this . names = newSet . names ; this . elementSize = newSet . elementSize ; this . threshold = newSet . threshold ; } } public static char [ ] createIndexKey ( int modifiers , char [ ] typeName , char [ ] packageName , char [ ] [ ] enclosingTypeNames , boolean secondary ) { int typeNameLength = typeName == null ? : typeName . length ; int packageLength = packageName == null ? : packageName . length ; int enclosingNamesLength = ; if ( enclosingTypeNames != null ) { for ( int i = , length = enclosingTypeNames . length ; i < length ; ) { enclosingNamesLength += enclosingTypeNames [ i ] . length ; if ( ++ i < length ) enclosingNamesLength += ; } } int resultLength = typeNameLength + packageLength + enclosingNamesLength + ; if ( secondary ) resultLength += ; char [ ] result = new char [ resultLength ] ; int pos = ; if ( typeNameLength > ) { System . arraycopy ( typeName , , result , pos , typeNameLength ) ; pos += typeNameLength ; } result [ pos ++ ] = SEPARATOR ; if ( packageLength > ) { System . arraycopy ( packageName , , result , pos , packageLength ) ; pos += packageLength ; } result [ pos ++ ] = SEPARATOR ; if ( enclosingTypeNames != null && enclosingNamesLength > ) { for ( int i = , length = enclosingTypeNames . length ; i < length ; ) { char [ ] enclosingName = enclosingTypeNames [ i ] ; int itsLength = enclosingName . length ; System . arraycopy ( enclosingName , , result , pos , itsLength ) ; pos += itsLength ; if ( ++ i < length ) { result [ pos ++ ] = '' ; result [ pos ++ ] = '' ; } } } result [ pos ++ ] = SEPARATOR ; result [ pos ++ ] = ( char ) modifiers ; result [ pos ] = ( char ) ( modifiers > > ) ; if ( secondary ) { result [ ++ pos ] = SEPARATOR ; result [ ++ pos ] = '' ; } return result ; } public TypeDeclarationPattern ( char [ ] pkg , char [ ] [ ] enclosingTypeNames , char [ ] simpleName , char typeSuffix , int matchRule ) { this ( matchRule ) ; this . pkg = isCaseSensitive ( ) ? pkg : CharOperation . toLowerCase ( pkg ) ; if ( isCaseSensitive ( ) || isCamelCase ( ) || enclosingTypeNames == null ) { this . enclosingTypeNames = enclosingTypeNames ; } else { int length = enclosingTypeNames . length ; this . enclosingTypeNames = new char [ length ] [ ] ; for ( int i = ; i < length ; i ++ ) this . enclosingTypeNames [ i ] = CharOperation . toLowerCase ( enclosingTypeNames [ i ] ) ; } this . simpleName = ( isCaseSensitive ( ) || isCamelCase ( ) ) ? simpleName : CharOperation . toLowerCase ( simpleName ) ; this . typeSuffix = typeSuffix ; ( ( InternalSearchPattern ) this ) . mustResolve = ( this . pkg != null && this . enclosingTypeNames != null ) || typeSuffix != TYPE_SUFFIX ; } TypeDeclarationPattern ( int matchRule ) { super ( TYPE_DECL_PATTERN , matchRule ) ; } public void decodeIndexKey ( char [ ] key ) { int slash = CharOperation . indexOf ( SEPARATOR , key , ) ; this . simpleName = CharOperation . subarray ( key , , slash ) ; int start = ++ slash ; if ( key [ start ] == SEPARATOR ) { this . pkg = CharOperation . NO_CHAR ; } else { slash = CharOperation . indexOf ( SEPARATOR , key , start ) ; this . pkg = internedPackageNames . add ( CharOperation . subarray ( key , start , slash ) ) ; } int last = key . length - ; this . secondary = key [ last ] == '' ; if ( this . secondary ) { last -= ; } this . modifiers = key [ last - ] + ( key [ last ] << ) ; decodeModifiers ( ) ; start = slash + ; last -= ; if ( start == last ) { this . enclosingTypeNames = CharOperation . NO_CHAR_CHAR ; } else { if ( last == ( start + ) && key [ start ] == ZERO_CHAR ) { this . enclosingTypeNames = ONE_ZERO_CHAR ; } else { this . enclosingTypeNames = CharOperation . splitOn ( "" , key , start , last ) ; } } } protected void decodeModifiers ( ) { switch ( this . modifiers & ( Flags . AccModule ) ) { case Flags . AccModule : this . typeSuffix = MODULE_SUFFIX ; break ; default : this . typeSuffix = CLASS_SUFFIX ; break ; } } public SearchPattern getBlankPattern ( ) { return new TypeDeclarationPattern ( R_EXACT_MATCH | R_CASE_SENSITIVE ) ; } public char [ ] [ ] getIndexCategories ( ) { return CATEGORIES ; } public boolean matchesDecodedKey ( SearchPattern decodedPattern ) { TypeDeclarationPattern pattern = ( TypeDeclarationPattern ) decodedPattern ; switch ( this . typeSuffix ) { case CLASS_SUFFIX : switch ( pattern . typeSuffix ) { case CLASS_SUFFIX : case TYPE_SUFFIX : break ; default : return false ; } break ; case MODULE_SUFFIX : switch ( pattern . typeSuffix ) { case MODULE_SUFFIX : case TYPE_SUFFIX : break ; default : return false ; } break ; } if ( ! matchesName ( this . simpleName , pattern . simpleName ) ) return false ; if ( CharOperation . equals ( this . simpleName , "" . toCharArray ( ) ) ) { System . out . println ( "" ) ; } if ( this . pkg != null && ! CharOperation . equals ( this . pkg , pattern . pkg , isCaseSensitive ( ) ) ) return false ; if ( this . enclosingTypeNames != null ) { if ( this . enclosingTypeNames . length == ) return pattern . enclosingTypeNames . length == ; if ( this . enclosingTypeNames . length == && pattern . enclosingTypeNames . length == ) return matchesName ( this . enclosingTypeNames [ ] , pattern . enclosingTypeNames [ ] ) ; if ( pattern . enclosingTypeNames == ONE_ZERO_CHAR ) return true ; return matchesName ( this . enclosingTypeNames , pattern . enclosingTypeNames ) ; } return true ; } private boolean matchesName ( char [ ] [ ] name , char [ ] [ ] pattern ) { if ( name . length != pattern . length ) return false ; for ( int i = ; i < name . length ; i ++ ) { if ( ! matchesName ( name [ i ] , pattern [ i ] ) ) return false ; } return true ; } EntryResult [ ] queryIn ( Index index ) throws IOException { char [ ] key = this . simpleName ; int matchRule = getMatchRule ( ) ; switch ( getMatchMode ( ) ) { case R_PREFIX_MATCH : break ; case R_EXACT_MATCH : if ( this . isCamelCase ) break ; matchRule &= ~ R_EXACT_MATCH ; if ( this . simpleName != null ) { matchRule |= R_PREFIX_MATCH ; key = this . pkg == null ? CharOperation . append ( this . simpleName , SEPARATOR ) : CharOperation . concat ( this . simpleName , SEPARATOR , this . pkg , SEPARATOR , CharOperation . NO_CHAR ) ; break ; } matchRule |= R_PATTERN_MATCH ; case R_PATTERN_MATCH : if ( this . pkg == null ) { if ( this . simpleName == null ) { switch ( this . typeSuffix ) { case CLASS_SUFFIX : case MODULE_SUFFIX : case TYPE_SUFFIX : break ; } } else if ( this . simpleName [ this . simpleName . length - ] != '' ) { key = CharOperation . concat ( this . simpleName , ONE_STAR , SEPARATOR ) ; } break ; } key = CharOperation . concat ( this . simpleName == null ? ONE_STAR : this . simpleName , SEPARATOR , this . pkg , SEPARATOR , ONE_STAR ) ; break ; case R_REGEXP_MATCH : break ; } return index . query ( getIndexCategories ( ) , key , matchRule ) ; } protected StringBuffer print ( StringBuffer output ) { switch ( this . typeSuffix ) { case CLASS_SUFFIX : output . append ( "" ) ; break ; case MODULE_SUFFIX : output . append ( "" ) ; break ; default : output . append ( "" ) ; break ; } if ( pkg != null ) output . append ( pkg ) ; else output . append ( "" ) ; output . append ( "" ) ; if ( enclosingTypeNames != null ) { for ( int i = ; i < enclosingTypeNames . length ; i ++ ) { output . append ( enclosingTypeNames [ i ] ) ; if ( i < enclosingTypeNames . length - ) output . append ( '' ) ; } } else { output . append ( "" ) ; } output . append ( "" ) ; if ( simpleName != null ) output . append ( simpleName ) ; else output . append ( "" ) ; output . append ( ">" ) ; return super . print ( output ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import java . util . ArrayList ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . HashtableOfLong ; import org . rubypeople . rdt . internal . compiler . util . SimpleLookupTable ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . core . util . Util ; public class MatchingNodeSet { SimpleLookupTable matchingNodes = new SimpleLookupTable ( ) ; private HashtableOfLong matchingNodesKeys = new HashtableOfLong ( ) ; static Integer EXACT_MATCH = new Integer ( SearchMatch . A_ACCURATE ) ; static Integer POTENTIAL_MATCH = new Integer ( SearchMatch . A_INACCURATE ) ; static Integer ERASURE_MATCH = new Integer ( SearchPattern . R_ERASURE_MATCH ) ; public boolean mustResolve ; SimpleSet possibleMatchingNodesSet = new SimpleSet ( ) ; private HashtableOfLong possibleMatchingNodesKeys = new HashtableOfLong ( ) ; public MatchingNodeSet ( boolean mustResolvePattern ) { super ( ) ; mustResolve = mustResolvePattern ; } public int addMatch ( Node node , int matchLevel ) { int maskedLevel = matchLevel & PatternLocator . MATCH_LEVEL_MASK ; switch ( maskedLevel ) { case PatternLocator . INACCURATE_MATCH : if ( matchLevel != maskedLevel ) { addTrustedMatch ( node , new Integer ( SearchMatch . A_INACCURATE + ( matchLevel & PatternLocator . FLAVORS_MASK ) ) ) ; } else { addTrustedMatch ( node , POTENTIAL_MATCH ) ; } break ; case PatternLocator . POSSIBLE_MATCH : addPossibleMatch ( node ) ; break ; case PatternLocator . ERASURE_MATCH : if ( matchLevel != maskedLevel ) { addTrustedMatch ( node , new Integer ( SearchPattern . R_ERASURE_MATCH + ( matchLevel & PatternLocator . FLAVORS_MASK ) ) ) ; } else { addTrustedMatch ( node , ERASURE_MATCH ) ; } break ; case PatternLocator . ACCURATE_MATCH : if ( matchLevel != maskedLevel ) { addTrustedMatch ( node , new Integer ( SearchMatch . A_ACCURATE + ( matchLevel & PatternLocator . FLAVORS_MASK ) ) ) ; } else { addTrustedMatch ( node , EXACT_MATCH ) ; } break ; } return matchLevel ; } public void addPossibleMatch ( Node node ) { long key = ( ( ( long ) node . getPosition ( ) . getStartOffset ( ) ) << ) + node . getPosition ( ) . getEndOffset ( ) ; Node existing = ( Node ) this . possibleMatchingNodesKeys . get ( key ) ; if ( existing != null && existing . getClass ( ) . equals ( node . getClass ( ) ) ) this . possibleMatchingNodesSet . remove ( existing ) ; this . possibleMatchingNodesSet . add ( node ) ; this . possibleMatchingNodesKeys . put ( key , node ) ; } public void addTrustedMatch ( Node node , boolean isExact ) { addTrustedMatch ( node , isExact ? EXACT_MATCH : POTENTIAL_MATCH ) ; } void addTrustedMatch ( Node node , Integer level ) { long key = ( ( ( long ) node . getPosition ( ) . getStartOffset ( ) ) << ) + node . getPosition ( ) . getEndOffset ( ) ; Node existing = ( Node ) this . matchingNodesKeys . get ( key ) ; if ( existing != null && existing . getClass ( ) . equals ( node . getClass ( ) ) ) this . matchingNodes . removeKey ( existing ) ; this . matchingNodes . put ( node , level ) ; this . matchingNodesKeys . put ( key , node ) ; } protected boolean hasPossibleNodes ( int start , int end ) { Object [ ] nodes = this . possibleMatchingNodesSet . values ; for ( int i = , l = nodes . length ; i < l ; i ++ ) { Node node = ( Node ) nodes [ i ] ; if ( node != null && start <= node . getPosition ( ) . getStartOffset ( ) && node . getPosition ( ) . getEndOffset ( ) <= end ) return true ; } nodes = this . matchingNodes . keyTable ; for ( int i = , l = nodes . length ; i < l ; i ++ ) { Node node = ( Node ) nodes [ i ] ; if ( node != null && start <= node . getPosition ( ) . getStartOffset ( ) && node . getPosition ( ) . getEndOffset ( ) <= end ) return true ; } return false ; } protected Node [ ] matchingNodes ( int start , int end ) { ArrayList nodes = null ; Object [ ] keyTable = this . matchingNodes . keyTable ; for ( int i = , l = keyTable . length ; i < l ; i ++ ) { Node node = ( Node ) keyTable [ i ] ; if ( node != null && start <= node . getPosition ( ) . getStartOffset ( ) && node . getPosition ( ) . getEndOffset ( ) <= end ) { if ( nodes == null ) nodes = new ArrayList ( ) ; nodes . add ( node ) ; } } if ( nodes == null ) return null ; Node [ ] result = new Node [ nodes . size ( ) ] ; nodes . toArray ( result ) ; Util . Comparer comparer = new Util . Comparer ( ) { public int compare ( Object o1 , Object o2 ) { return ( ( Node ) o1 ) . getPosition ( ) . getStartOffset ( ) - ( ( Node ) o2 ) . getPosition ( ) . getStartOffset ( ) ; } } ; Util . sort ( result , comparer ) ; return result ; } public Object removePossibleMatch ( Node node ) { long key = ( ( ( long ) node . getPosition ( ) . getStartOffset ( ) ) << ) + node . getPosition ( ) . getEndOffset ( ) ; Node existing = ( Node ) this . possibleMatchingNodesKeys . get ( key ) ; if ( existing == null ) return null ; this . possibleMatchingNodesKeys . put ( key , null ) ; return this . possibleMatchingNodesSet . remove ( node ) ; } public Object removeTrustedMatch ( Node node ) { long key = ( ( ( long ) node . getPosition ( ) . getStartOffset ( ) ) << ) + node . getPosition ( ) . getEndOffset ( ) ; Node existing = ( Node ) this . matchingNodesKeys . get ( key ) ; if ( existing == null ) return null ; this . matchingNodesKeys . put ( key , null ) ; return this . matchingNodes . removeKey ( node ) ; } public String toString ( ) { StringBuffer result = new StringBuffer ( ) ; result . append ( "" ) ; Object [ ] keyTable = this . matchingNodes . keyTable ; Object [ ] valueTable = this . matchingNodes . valueTable ; for ( int i = , l = keyTable . length ; i < l ; i ++ ) { Node node = ( Node ) keyTable [ i ] ; if ( node == null ) continue ; result . append ( "" ) ; switch ( ( ( Integer ) valueTable [ i ] ) . intValue ( ) ) { case SearchMatch . A_ACCURATE : result . append ( "" ) ; break ; case SearchMatch . A_INACCURATE : result . append ( "" ) ; break ; case SearchPattern . R_ERASURE_MATCH : result . append ( "" ) ; break ; } result . append ( node . toString ( ) ) ; } result . append ( "" ) ; Object [ ] nodes = this . possibleMatchingNodesSet . values ; for ( int i = , l = nodes . length ; i < l ; i ++ ) { Node node = ( Node ) nodes [ i ] ; if ( node == null ) continue ; result . append ( "" ) ; result . append ( node . toString ( ) ) ; } return result . toString ( ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . rubypeople . rdt . core . IField ; public class VariableLocator extends PatternLocator { protected VariablePattern pattern ; public VariableLocator ( VariablePattern pattern ) { super ( pattern ) ; this . pattern = pattern ; } protected int getAccuracy ( IField field ) { if ( ! this . pattern . findDeclarations ) return IMPOSSIBLE_MATCH ; if ( ! matchesName ( this . pattern . name , field . getElementName ( ) . toCharArray ( ) ) ) return IMPOSSIBLE_MATCH ; return ACCURATE_MATCH ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . internal . compiler . util . ObjectVector ; import org . rubypeople . rdt . internal . compiler . util . SimpleLookupTable ; public class PossibleMatchSet { private SimpleLookupTable rootsToPossibleMatches = new SimpleLookupTable ( ) ; private int elementCount = ; public void add ( PossibleMatch possibleMatch ) { IPath path = possibleMatch . openable . getSourceFolderRoot ( ) . getPath ( ) ; ObjectVector possibleMatches = ( ObjectVector ) this . rootsToPossibleMatches . get ( path ) ; if ( possibleMatches != null ) { if ( possibleMatches . contains ( possibleMatch ) ) return ; } else { this . rootsToPossibleMatches . put ( path , possibleMatches = new ObjectVector ( ) ) ; } possibleMatches . add ( possibleMatch ) ; this . elementCount ++ ; } public PossibleMatch [ ] getPossibleMatches ( ISourceFolderRoot [ ] roots ) { PossibleMatch [ ] result = new PossibleMatch [ this . elementCount ] ; int index = ; for ( int i = , length = roots . length ; i < length ; i ++ ) { ObjectVector possibleMatches = ( ObjectVector ) this . rootsToPossibleMatches . get ( roots [ i ] . getPath ( ) ) ; if ( possibleMatches != null ) { possibleMatches . copyInto ( result , index ) ; index += possibleMatches . size ( ) ; } } if ( index < this . elementCount ) System . arraycopy ( result , , result = new PossibleMatch [ index ] , , index ) ; return result ; } public void reset ( ) { this . rootsToPossibleMatches = new SimpleLookupTable ( ) ; this . elementCount = ; } } package org . rubypeople . rdt . internal . core . search . matching ; import java . io . IOException ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . index . EntryResult ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class MethodPattern extends RubySearchPattern implements IIndexConstants { protected boolean findDeclarations ; protected boolean findReferences ; public char [ ] selector ; public char [ ] declaringQualification ; public char [ ] declaringSimpleName ; public char [ ] [ ] parameterNames ; public int parameterCount ; public boolean varargs = false ; protected IType declaringType ; char [ ] [ ] methodArguments ; protected static char [ ] [ ] REF_CATEGORIES = { METHOD_REF } ; protected static char [ ] [ ] REF_AND_DECL_CATEGORIES = { METHOD_REF , METHOD_DECL } ; protected static char [ ] [ ] DECL_CATEGORIES = { METHOD_DECL } ; public static char [ ] createIndexKey ( char [ ] selector , int argCount ) { char [ ] countChars = argCount < ? COUNTS [ argCount ] : ( "" + String . valueOf ( argCount ) ) . toCharArray ( ) ; return CharOperation . concat ( selector , countChars ) ; } MethodPattern ( int matchRule ) { super ( METHOD_PATTERN , matchRule ) ; } public MethodPattern ( boolean findDeclarations , boolean findReferences , char [ ] selector , char [ ] declaringQualification , char [ ] declaringSimpleName , char [ ] [ ] parameterNames , IType declaringType , int matchRule ) { this ( matchRule ) ; this . findDeclarations = findDeclarations ; this . findReferences = findReferences ; this . selector = ( isCaseSensitive ( ) || isCamelCase ( ) ) ? selector : CharOperation . toLowerCase ( selector ) ; this . declaringQualification = isCaseSensitive ( ) ? declaringQualification : CharOperation . toLowerCase ( declaringQualification ) ; this . declaringSimpleName = isCaseSensitive ( ) ? declaringSimpleName : CharOperation . toLowerCase ( declaringSimpleName ) ; if ( parameterNames != null ) { this . parameterCount = parameterNames . length ; this . parameterNames = new char [ this . parameterCount ] [ ] ; for ( int i = ; i < this . parameterCount ; i ++ ) { this . parameterNames [ i ] = isCaseSensitive ( ) ? parameterNames [ i ] : CharOperation . toLowerCase ( parameterNames [ i ] ) ; } } else { this . parameterCount = - ; } this . declaringType = declaringType ; ( ( InternalSearchPattern ) this ) . mustResolve = mustResolve ( ) ; } public MethodPattern ( boolean findDeclarations , boolean findReferences , char [ ] selector , char [ ] declaringQualification , char [ ] declaringSimpleName , char [ ] [ ] parameterNames , IMethod method , int matchRule ) { this ( findDeclarations , findReferences , selector , declaringQualification , declaringSimpleName , parameterNames , method . getDeclaringType ( ) , matchRule ) ; this . varargs = true ; } public MethodPattern ( boolean findDeclarations , boolean findReferences , char [ ] selector , char [ ] declaringQualification , char [ ] declaringSimpleName , char [ ] [ ] parameterSimpleNames , int matchRule ) { this ( findDeclarations , findReferences , selector , declaringQualification , declaringSimpleName , parameterSimpleNames , ( IType ) null , matchRule ) ; } public void decodeIndexKey ( char [ ] key ) { int last = key . length - ; this . parameterCount = ; this . selector = null ; int power = ; for ( int i = last ; i >= ; i -- ) { if ( key [ i ] == SEPARATOR ) { System . arraycopy ( key , , this . selector = new char [ i ] , , i ) ; break ; } if ( i == last ) { this . parameterCount = key [ i ] - '' ; } else { power *= ; this . parameterCount += power * ( key [ i ] - '' ) ; } } } public SearchPattern getBlankPattern ( ) { return new MethodPattern ( R_EXACT_MATCH | R_CASE_SENSITIVE ) ; } public char [ ] [ ] getIndexCategories ( ) { if ( this . findReferences ) return this . findDeclarations ? REF_AND_DECL_CATEGORIES : REF_CATEGORIES ; if ( this . findDeclarations ) return DECL_CATEGORIES ; return CharOperation . NO_CHAR_CHAR ; } boolean hasMethodArguments ( ) { return methodArguments != null && methodArguments . length > ; } boolean isPolymorphicSearch ( ) { return this . findReferences ; } public boolean matchesDecodedKey ( SearchPattern decodedPattern ) { MethodPattern pattern = ( MethodPattern ) decodedPattern ; return ( this . parameterCount == pattern . parameterCount || this . parameterCount == - || this . varargs ) && matchesName ( this . selector , pattern . selector ) ; } protected boolean mustResolve ( ) { if ( declaringSimpleName != null || declaringQualification != null ) return true ; return false ; } EntryResult [ ] queryIn ( Index index ) throws IOException { char [ ] key = this . selector ; int matchRule = getMatchRule ( ) ; switch ( getMatchMode ( ) ) { case R_EXACT_MATCH : if ( this . isCamelCase ) break ; if ( this . selector != null && this . parameterCount >= && ! this . varargs ) key = createIndexKey ( this . selector , this . parameterCount ) ; else { matchRule &= ~ R_EXACT_MATCH ; matchRule |= R_PREFIX_MATCH ; } break ; case R_PREFIX_MATCH : break ; case R_PATTERN_MATCH : if ( this . parameterCount >= && ! this . varargs ) key = createIndexKey ( this . selector == null ? ONE_STAR : this . selector , this . parameterCount ) ; else if ( this . selector != null && this . selector [ this . selector . length - ] != '' ) key = CharOperation . concat ( this . selector , ONE_STAR , SEPARATOR ) ; break ; case R_REGEXP_MATCH : break ; } return index . query ( getIndexCategories ( ) , key , matchRule ) ; } protected StringBuffer print ( StringBuffer output ) { if ( this . findDeclarations ) { output . append ( this . findReferences ? "" : "" ) ; } else { output . append ( "" ) ; } if ( declaringQualification != null ) output . append ( declaringQualification ) . append ( '' ) ; if ( declaringSimpleName != null ) output . append ( declaringSimpleName ) . append ( '' ) ; else if ( declaringQualification != null ) output . append ( "" ) ; if ( selector != null ) output . append ( selector ) ; else output . append ( "" ) ; output . append ( '' ) ; if ( parameterNames == null ) { output . append ( "" ) ; } else { for ( int i = , max = parameterNames . length ; i < max ; i ++ ) { if ( i > ) output . append ( "" ) ; if ( parameterNames [ i ] == null ) output . append ( '' ) ; else output . append ( parameterNames [ i ] ) ; } } output . append ( '' ) ; return super . print ( output ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import java . io . IOException ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . index . EntryResult ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class SuperTypeReferencePattern extends RubySearchPattern implements IIndexConstants { public char [ ] superQualification ; public char [ ] superSimpleName ; public char superClassOrInterface ; public char typeSuffix ; public char [ ] pkgName ; public char [ ] simpleName ; public char [ ] enclosingTypeName ; public char classOrInterface ; public int modifiers ; protected int superRefKind ; public static final int ALL_SUPER_TYPES = ; public static final int ONLY_SUPER_INTERFACES = ; public static final int ONLY_SUPER_CLASSES = ; protected static char [ ] [ ] CATEGORIES = { SUPER_REF } ; public static char [ ] createIndexKey ( int modifiers , char [ ] packageName , char [ ] typeName , char [ ] [ ] enclosingTypeNames , char classOrInterface , char [ ] superTypeName , char superClassOrInterface ) { if ( superTypeName == null ) superTypeName = OBJECT ; char [ ] superSimpleName = CharOperation . lastSegment ( superTypeName , "" ) ; char [ ] superQualification = null ; if ( ! CharOperation . equals ( superSimpleName , superTypeName ) ) { int length = superTypeName . length - superSimpleName . length - ; superQualification = new char [ length - ] ; System . arraycopy ( superTypeName , , superQualification , , length - ) ; } char [ ] superTypeSourceName = CharOperation . lastSegment ( superSimpleName , "" ) ; if ( ! CharOperation . equals ( superSimpleName , superTypeSourceName ) ) { int start = superQualification == null ? : superQualification . length + ; int prefixLength = superSimpleName . length - superTypeSourceName . length ; char [ ] mangledQualification = new char [ start + prefixLength ] ; if ( superQualification != null ) { System . arraycopy ( superQualification , , mangledQualification , , start - ) ; mangledQualification [ start - ] = '' ; } System . arraycopy ( superSimpleName , , mangledQualification , start , prefixLength ) ; superQualification = mangledQualification ; superSimpleName = superTypeSourceName ; } char [ ] simpleName = CharOperation . lastSegment ( typeName , "" ) ; char [ ] enclosingTypeName = CharOperation . concatWith ( enclosingTypeNames , "" ) ; if ( superQualification != null && CharOperation . equals ( superQualification , packageName ) ) packageName = ONE_ZERO ; int superLength = superSimpleName == null ? : superSimpleName . length ; int superQLength = superQualification == null ? : superQualification . length ; int simpleLength = simpleName == null ? : simpleName . length ; int enclosingLength = enclosingTypeName == null ? : enclosingTypeName . length ; int packageLength = packageName == null ? : packageName . length ; char [ ] result = new char [ superLength + superQLength + simpleLength + enclosingLength + packageLength + ] ; int pos = ; if ( superLength > ) { System . arraycopy ( superSimpleName , , result , pos , superLength ) ; pos += superLength ; } result [ pos ++ ] = SEPARATOR ; if ( superQLength > ) { System . arraycopy ( superQualification , , result , pos , superQLength ) ; pos += superQLength ; } result [ pos ++ ] = SEPARATOR ; if ( simpleLength > ) { System . arraycopy ( simpleName , , result , pos , simpleLength ) ; pos += simpleLength ; } result [ pos ++ ] = SEPARATOR ; if ( enclosingLength > ) { System . arraycopy ( enclosingTypeName , , result , pos , enclosingLength ) ; pos += enclosingLength ; } result [ pos ++ ] = SEPARATOR ; if ( packageLength > ) { System . arraycopy ( packageName , , result , pos , packageLength ) ; pos += packageLength ; } result [ pos ++ ] = SEPARATOR ; result [ pos ++ ] = superClassOrInterface ; result [ pos ++ ] = classOrInterface ; result [ pos ] = ( char ) modifiers ; return result ; } public SuperTypeReferencePattern ( char [ ] superQualification , char [ ] superSimpleName , int superRefKind , int matchRule ) { this ( matchRule ) ; this . superQualification = isCaseSensitive ( ) ? superQualification : CharOperation . toLowerCase ( superQualification ) ; this . superSimpleName = ( isCaseSensitive ( ) || isCamelCase ( ) ) ? superSimpleName : CharOperation . toLowerCase ( superSimpleName ) ; ( ( InternalSearchPattern ) this ) . mustResolve = superQualification != null ; this . superRefKind = superRefKind ; } public SuperTypeReferencePattern ( char [ ] superQualification , char [ ] superSimpleName , int superRefKind , char typeSuffix , int matchRule ) { this ( superQualification , superSimpleName , superRefKind , matchRule ) ; this . typeSuffix = typeSuffix ; ( ( InternalSearchPattern ) this ) . mustResolve = superQualification != null || typeSuffix != IIndexConstants . TYPE_SUFFIX ; } SuperTypeReferencePattern ( int matchRule ) { super ( SUPER_REF_PATTERN , matchRule ) ; } public void decodeIndexKey ( char [ ] key ) { int slash = CharOperation . indexOf ( SEPARATOR , key , ) ; this . superSimpleName = CharOperation . subarray ( key , , slash ) ; int start = slash + ; slash = CharOperation . indexOf ( SEPARATOR , key , start ) ; this . superQualification = slash == start ? null : CharOperation . subarray ( key , start , slash ) ; slash = CharOperation . indexOf ( SEPARATOR , key , start = slash + ) ; this . simpleName = CharOperation . subarray ( key , start , slash ) ; start = ++ slash ; if ( key [ start ] == SEPARATOR ) { this . enclosingTypeName = null ; } else { slash = CharOperation . indexOf ( SEPARATOR , key , start ) ; if ( slash == ( start + ) && key [ start ] == ZERO_CHAR ) { this . enclosingTypeName = ONE_ZERO ; } else { char [ ] names = CharOperation . subarray ( key , start , slash ) ; this . enclosingTypeName = names ; } } start = ++ slash ; if ( key [ start ] == SEPARATOR ) { this . pkgName = null ; } else { slash = CharOperation . indexOf ( SEPARATOR , key , start ) ; if ( slash == ( start + ) && key [ start ] == ZERO_CHAR ) { this . pkgName = this . superQualification ; } else { char [ ] names = CharOperation . subarray ( key , start , slash ) ; this . pkgName = names ; } } this . superClassOrInterface = key [ slash + ] ; this . classOrInterface = key [ slash + ] ; this . modifiers = key [ slash + ] ; } public SearchPattern getBlankPattern ( ) { return new SuperTypeReferencePattern ( R_EXACT_MATCH | R_CASE_SENSITIVE ) ; } public char [ ] [ ] getIndexCategories ( ) { return CATEGORIES ; } public boolean matchesDecodedKey ( SearchPattern decodedPattern ) { SuperTypeReferencePattern pattern = ( SuperTypeReferencePattern ) decodedPattern ; if ( this . superRefKind == ONLY_SUPER_CLASSES && pattern . enclosingTypeName != IIndexConstants . ONE_ZERO ) if ( pattern . superClassOrInterface == IIndexConstants . MODULE_SUFFIX ) return false ; if ( pattern . superQualification != null ) if ( ! matchesName ( this . superQualification , pattern . superQualification ) ) return false ; return matchesName ( this . superSimpleName , pattern . superSimpleName ) ; } EntryResult [ ] queryIn ( Index index ) throws IOException { char [ ] key = this . superSimpleName ; int matchRule = getMatchRule ( ) ; switch ( getMatchMode ( ) ) { case R_EXACT_MATCH : if ( this . isCamelCase ) break ; matchRule &= ~ R_EXACT_MATCH ; matchRule |= R_PREFIX_MATCH ; if ( this . superSimpleName != null ) key = CharOperation . append ( this . superSimpleName , SEPARATOR ) ; break ; case R_PREFIX_MATCH : break ; case R_PATTERN_MATCH : break ; case R_REGEXP_MATCH : break ; } return index . query ( getIndexCategories ( ) , key , matchRule ) ; } protected StringBuffer print ( StringBuffer output ) { switch ( this . superRefKind ) { case ALL_SUPER_TYPES : output . append ( "" ) ; break ; case ONLY_SUPER_INTERFACES : output . append ( "" ) ; break ; case ONLY_SUPER_CLASSES : output . append ( "" ) ; break ; } if ( superSimpleName != null ) output . append ( superSimpleName ) ; else output . append ( "" ) ; output . append ( ">" ) ; return super . print ( output ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import java . io . File ; import java . io . IOException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . index . EntryResult ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . IndexQueryRequestor ; import org . rubypeople . rdt . internal . core . search . RubySearchScope ; public abstract class InternalSearchPattern { IRubyElement focus ; int kind ; boolean mustResolve = true ; void acceptMatch ( String relativePath , String containerPath , SearchPattern pattern , IndexQueryRequestor requestor , SearchParticipant participant , IRubySearchScope scope ) { if ( scope instanceof RubySearchScope ) { String documentPath = documentPath ( containerPath , relativePath ) ; if ( ! requestor . acceptIndexMatch ( documentPath , pattern , participant ) ) throw new OperationCanceledException ( ) ; } else { String documentPath = documentPath ( containerPath , relativePath ) ; if ( scope . encloses ( documentPath ) ) if ( ! requestor . acceptIndexMatch ( documentPath , pattern , participant ) ) throw new OperationCanceledException ( ) ; } } SearchPattern currentPattern ( ) { return ( SearchPattern ) this ; } String documentPath ( String containerPath , String relativePath ) { String separator = "" ; StringBuffer buffer = new StringBuffer ( containerPath . length ( ) + separator . length ( ) + relativePath . length ( ) ) ; buffer . append ( containerPath ) ; buffer . append ( separator ) ; buffer . append ( relativePath ) ; return buffer . toString ( ) ; } void findIndexMatches ( Index index , IndexQueryRequestor requestor , SearchParticipant participant , IRubySearchScope scope , IProgressMonitor monitor ) throws IOException { if ( monitor != null && monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; try { index . startQuery ( ) ; SearchPattern pattern = currentPattern ( ) ; EntryResult [ ] entries = ( ( InternalSearchPattern ) pattern ) . queryIn ( index ) ; if ( entries == null ) return ; SearchPattern decodedResult = pattern . getBlankPattern ( ) ; String containerPath = index . containerPath ; for ( int i = , l = entries . length ; i < l ; i ++ ) { if ( monitor != null && monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; EntryResult entry = entries [ i ] ; decodedResult . decodeIndexKey ( entry . getWord ( ) ) ; if ( pattern . matchesDecodedKey ( decodedResult ) ) { String [ ] names = entry . getDocumentNames ( index ) ; for ( int j = , n = names . length ; j < n ; j ++ ) acceptMatch ( names [ j ] , containerPath , decodedResult , requestor , participant , scope ) ; } } } finally { index . stopQuery ( ) ; } } boolean isPolymorphicSearch ( ) { return false ; } EntryResult [ ] queryIn ( Index index ) throws IOException { SearchPattern pattern = ( SearchPattern ) this ; return index . query ( pattern . getIndexCategories ( ) , pattern . getIndexKey ( ) , pattern . getMatchRule ( ) ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class QualifiedTypeDeclarationPattern extends TypeDeclarationPattern implements IIndexConstants { public char [ ] qualification ; public int packageIndex ; public QualifiedTypeDeclarationPattern ( char [ ] qualification , char [ ] simpleName , char typeSuffix , int matchRule ) { this ( matchRule ) ; this . qualification = isCaseSensitive ( ) ? qualification : CharOperation . toLowerCase ( qualification ) ; this . simpleName = ( isCaseSensitive ( ) || isCamelCase ( ) ) ? simpleName : CharOperation . toLowerCase ( simpleName ) ; this . typeSuffix = typeSuffix ; ( ( InternalSearchPattern ) this ) . mustResolve = this . qualification != null || typeSuffix != TYPE_SUFFIX ; } QualifiedTypeDeclarationPattern ( int matchRule ) { super ( matchRule ) ; } public void decodeIndexKey ( char [ ] key ) { int slash = CharOperation . indexOf ( SEPARATOR , key , ) ; this . simpleName = CharOperation . subarray ( key , , slash ) ; int start = slash + ; slash = CharOperation . indexOf ( SEPARATOR , key , start ) ; int secondSlash = CharOperation . indexOf ( SEPARATOR , key , slash + ) ; this . packageIndex = - ; if ( start + == secondSlash ) { this . qualification = CharOperation . NO_CHAR ; } else if ( slash + == secondSlash ) { this . qualification = CharOperation . subarray ( key , start , slash ) ; } else if ( slash == start ) { this . qualification = CharOperation . subarray ( key , slash + , secondSlash ) ; this . packageIndex = ; } else { this . qualification = CharOperation . subarray ( key , start , secondSlash ) ; this . packageIndex = slash - start ; this . qualification [ this . packageIndex ] = '' ; } int last = key . length - ; this . secondary = key [ last ] == '' ; if ( this . secondary ) { last -= ; } this . modifiers = key [ last - ] + ( key [ last ] << ) ; decodeModifiers ( ) ; } public SearchPattern getBlankPattern ( ) { return new QualifiedTypeDeclarationPattern ( R_EXACT_MATCH | R_CASE_SENSITIVE ) ; } public char [ ] getPackageName ( ) { if ( this . packageIndex == - ) return this . qualification ; return internedPackageNames . add ( CharOperation . subarray ( this . qualification , , this . packageIndex ) ) ; } public char [ ] [ ] getEnclosingTypeNames ( ) { if ( this . packageIndex == - ) return CharOperation . NO_CHAR_CHAR ; if ( this . packageIndex == ) return CharOperation . splitOn ( "" , this . qualification ) ; char [ ] names = CharOperation . subarray ( this . qualification , this . packageIndex + , this . qualification . length ) ; return CharOperation . splitOn ( "" , names ) ; } public boolean matchesDecodedKey ( SearchPattern decodedPattern ) { QualifiedTypeDeclarationPattern pattern = ( QualifiedTypeDeclarationPattern ) decodedPattern ; switch ( this . typeSuffix ) { case CLASS_SUFFIX : switch ( pattern . typeSuffix ) { case CLASS_SUFFIX : case TYPE_SUFFIX : break ; default : return false ; } break ; case MODULE_SUFFIX : switch ( pattern . typeSuffix ) { case MODULE_SUFFIX : case TYPE_SUFFIX : break ; default : return false ; } break ; } return matchesName ( this . simpleName , pattern . simpleName ) && matchesName ( this . qualification , pattern . qualification ) ; } protected StringBuffer print ( StringBuffer output ) { switch ( this . typeSuffix ) { case CLASS_SUFFIX : output . append ( "" ) ; break ; case MODULE_SUFFIX : output . append ( "" ) ; break ; default : output . append ( "" ) ; break ; } if ( this . qualification != null ) output . append ( this . qualification ) ; else output . append ( "" ) ; output . append ( "" ) ; if ( simpleName != null ) output . append ( simpleName ) ; else output . append ( "" ) ; output . append ( "" ) ; return super . print ( output ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public abstract class VariablePattern extends RubySearchPattern { protected boolean findDeclarations ; protected boolean findReferences ; protected boolean readAccess ; protected boolean writeAccess ; protected char [ ] name ; public VariablePattern ( int patternKind , boolean findDeclarations , boolean readAccess , boolean writeAccess , char [ ] name , int matchRule ) { super ( patternKind , matchRule ) ; this . findDeclarations = findDeclarations ; this . readAccess = readAccess ; this . writeAccess = writeAccess ; this . findReferences = readAccess || writeAccess ; this . name = ( isCaseSensitive ( ) || isCamelCase ( ) ) ? name : CharOperation . toLowerCase ( name ) ; } protected boolean mustResolve ( ) { return this . findReferences ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . RubyScript ; public class OrLocator extends PatternLocator { protected PatternLocator [ ] patternLocators ; public OrLocator ( OrPattern pattern ) { super ( pattern ) ; SearchPattern [ ] patterns = pattern . patterns ; int length = patterns . length ; this . patternLocators = new PatternLocator [ length ] ; for ( int i = ; i < length ; i ++ ) this . patternLocators [ i ] = PatternLocator . patternLocator ( patterns [ i ] ) ; } @ Override public void reportMatches ( RubyScript script , MatchLocator locator ) { for ( int i = , length = this . patternLocators . length ; i < length ; i ++ ) { PatternLocator patternLocator = this . patternLocators [ i ] ; patternLocator . reportMatches ( script , locator ) ; } } } package org . rubypeople . rdt . internal . core . search . matching ; import org . eclipse . core . runtime . CoreException ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; public class FieldLocator extends PatternLocator { private FieldPattern pattern ; public FieldLocator ( FieldPattern pattern ) { super ( pattern ) ; this . pattern = pattern ; } @ Override public void reportMatches ( final RubyScript script , final MatchLocator locator ) { if ( ! this . pattern . findReferences ) { reportMatches ( ( IParent ) script , locator ) ; } else { reportASTMatches ( script , locator ) ; } } private void reportASTMatches ( final RubyScript script , final MatchLocator locator ) { try { Node ast = script . lastGoodAST ; if ( ast == null ) { ast = new RubyParser ( ) . parse ( script . getElementName ( ) , script . getSource ( ) ) . getAST ( ) ; } final boolean findDeclarations = this . pattern . findDeclarations ; new InOrderVisitor ( ) { @ Override public Object visitInstVarNode ( InstVarNode iVisited ) { match ( iVisited ) ; return super . visitInstVarNode ( iVisited ) ; } @ Override public Object visitGlobalVarNode ( GlobalVarNode iVisited ) { match ( iVisited ) ; return super . visitGlobalVarNode ( iVisited ) ; } @ Override public Object visitConstDeclNode ( ConstDeclNode iVisited ) { if ( findDeclarations ) match ( iVisited ) ; return super . visitConstDeclNode ( iVisited ) ; } @ Override public Object visitGlobalAsgnNode ( GlobalAsgnNode iVisited ) { match ( iVisited ) ; return super . visitGlobalAsgnNode ( iVisited ) ; } @ Override public Object visitClassVarNode ( ClassVarNode iVisited ) { match ( iVisited ) ; return super . visitClassVarNode ( iVisited ) ; } @ Override public Object visitClassVarAsgnNode ( ClassVarAsgnNode iVisited ) { match ( iVisited ) ; return super . visitClassVarAsgnNode ( iVisited ) ; } @ Override public Object visitInstAsgnNode ( InstAsgnNode iVisited ) { match ( iVisited ) ; return super . visitInstAsgnNode ( iVisited ) ; } private void match ( Node iVisited ) { int accuracy = getAccuracy ( ( ( INameNode ) iVisited ) . getName ( ) ) ; if ( accuracy != IMPOSSIBLE_MATCH ) { try { IRubyElement element = script . getElementAt ( iVisited . getPosition ( ) . getStartOffset ( ) ) ; if ( element == null ) element = script ; if ( locator . encloses ( element ) ) { IRubyElement binding = resolve ( element , ( ( INameNode ) iVisited ) . getName ( ) ) ; locator . report ( locator . newFieldReferenceMatch ( element , binding , accuracy , iVisited . getPosition ( ) . getStartOffset ( ) , iVisited . getPosition ( ) . getEndOffset ( ) - iVisited . getPosition ( ) . getStartOffset ( ) , iVisited ) ) ; } } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } private IRubyElement resolve ( IRubyElement element , String name ) { if ( element instanceof IMember ) { IMember member = ( IMember ) element ; IType type = member . getDeclaringType ( ) ; return type . getField ( name ) ; } return null ; } } . acceptNode ( ast ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } private void reportMatches ( IParent parent , MatchLocator locator ) { try { IRubyElement [ ] children = parent . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { IRubyElement child = children [ i ] ; if ( ( child . isType ( IRubyElement . FIELD ) || child . isType ( IRubyElement . GLOBAL ) || child . isType ( IRubyElement . CONSTANT ) || child . isType ( IRubyElement . CLASS_VAR ) || child . isType ( IRubyElement . INSTANCE_VAR ) ) && ( locator . encloses ( child ) ) ) { int accuracy = getAccuracy ( child . getElementName ( ) ) ; if ( accuracy != IMPOSSIBLE_MATCH ) { IMember member = ( IMember ) child ; ISourceRange range = member . getSourceRange ( ) ; try { locator . report ( locator . newDeclarationMatch ( child , accuracy , range . getOffset ( ) , range . getLength ( ) ) ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } if ( child instanceof IParent ) { IParent parentTwo = ( IParent ) child ; reportMatches ( parentTwo , locator ) ; } } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } private int getAccuracy ( String name ) { if ( this . pattern . findReferences ) if ( matchesName ( this . pattern . name , name . toCharArray ( ) ) ) return ACCURATE_MATCH ; if ( this . pattern . findDeclarations ) { if ( matchesName ( this . pattern . name , name . toCharArray ( ) ) ) return ACCURATE_MATCH ; } return IMPOSSIBLE_MATCH ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; public class RubySearchPattern extends SearchPattern implements IIndexConstants { boolean isCaseSensitive ; boolean isCamelCase ; int matchMode ; int matchCompatibility ; public static final int MATCH_MODE_MASK = R_EXACT_MATCH | R_PREFIX_MATCH | R_PATTERN_MATCH | R_REGEXP_MATCH ; public static final int MATCH_COMPATIBILITY_MASK = R_ERASURE_MATCH | R_EQUIVALENT_MATCH | R_FULL_MATCH ; protected RubySearchPattern ( int patternKind , int matchRule ) { super ( matchRule ) ; ( ( InternalSearchPattern ) this ) . kind = patternKind ; int rule = getMatchRule ( ) ; this . isCaseSensitive = ( rule & R_CASE_SENSITIVE ) != ; this . isCamelCase = ( rule & R_CAMELCASE_MATCH ) != ; this . matchCompatibility = rule & MATCH_COMPATIBILITY_MASK ; this . matchMode = rule & MATCH_MODE_MASK ; } public SearchPattern getBlankPattern ( ) { return null ; } int getMatchMode ( ) { return this . matchMode ; } boolean isCamelCase ( ) { return this . isCamelCase ; } boolean isCaseSensitive ( ) { return this . isCaseSensitive ; } protected StringBuffer print ( StringBuffer output ) { output . append ( "" ) ; if ( this . isCamelCase ) { output . append ( "" ) ; } switch ( getMatchMode ( ) ) { case R_EXACT_MATCH : output . append ( "" ) ; break ; case R_PREFIX_MATCH : output . append ( "" ) ; break ; case R_PATTERN_MATCH : output . append ( "" ) ; break ; case R_REGEXP_MATCH : output . append ( "" ) ; break ; } if ( isCaseSensitive ( ) ) output . append ( "" ) ; else output . append ( "" ) ; if ( ( this . matchCompatibility & R_ERASURE_MATCH ) != ) { output . append ( "" ) ; } if ( ( this . matchCompatibility & R_EQUIVALENT_MATCH ) != ) { output . append ( "" ) ; } return output ; } } package org . rubypeople . rdt . internal . core . search . matching ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . FieldDeclarationMatch ; import org . rubypeople . rdt . core . search . FieldReferenceMatch ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . MethodDeclarationMatch ; import org . rubypeople . rdt . core . search . MethodReferenceMatch ; import org . rubypeople . rdt . core . search . SearchDocument ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . core . search . SearchRequestor ; import org . rubypeople . rdt . core . search . TypeDeclarationMatch ; import org . rubypeople . rdt . core . search . TypeReferenceMatch ; import org . rubypeople . rdt . internal . compiler . util . SimpleLookupTable ; import org . rubypeople . rdt . internal . core . ExternalSourceFolderRoot ; import org . rubypeople . rdt . internal . core . Openable ; import org . rubypeople . rdt . internal . core . RubyElement ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . BasicSearchEngine ; import org . rubypeople . rdt . internal . core . search . HandleFactory ; import org . rubypeople . rdt . internal . core . search . IndexQueryRequestor ; import org . rubypeople . rdt . internal . core . search . IndexSelector ; import org . rubypeople . rdt . internal . core . search . RubySearchDocument ; import org . rubypeople . rdt . internal . core . util . Util ; public class MatchLocator { public static final int MAX_AT_ONCE ; static { long maxMemory = Runtime . getRuntime ( ) . maxMemory ( ) ; int ratio = ( int ) Math . round ( ( ( double ) maxMemory ) / ( * ) ) ; switch ( ratio ) { case : case : MAX_AT_ONCE = ; break ; case : MAX_AT_ONCE = ; break ; case : MAX_AT_ONCE = ; break ; default : MAX_AT_ONCE = ; break ; } } public SearchPattern pattern ; public PatternLocator patternLocator ; public int matchContainer ; public SearchRequestor requestor ; public IRubySearchScope scope ; public IProgressMonitor progressMonitor ; public IRubyScript [ ] workingCopies ; public HandleFactory handleFactory ; SimpleLookupTable bindings ; int progressStep ; int progressWorked ; private PossibleMatch currentPossibleMatch ; public MatchLocator ( SearchPattern pattern , SearchRequestor requestor , IRubySearchScope scope , IProgressMonitor progressMonitor ) { this . pattern = pattern ; this . patternLocator = PatternLocator . patternLocator ( this . pattern ) ; this . matchContainer = this . patternLocator . matchContainer ( ) ; this . requestor = requestor ; this . scope = scope ; this . progressMonitor = progressMonitor ; } public static void findIndexMatches ( InternalSearchPattern pattern , Index index , IndexQueryRequestor requestor , SearchParticipant participant , IRubySearchScope scope , IProgressMonitor monitor ) throws IOException { pattern . findIndexMatches ( index , requestor , participant , scope , monitor ) ; } public static IRubyElement getProjectOrJar ( IRubyElement element ) { while ( ! ( element instanceof IRubyProject ) ) { element = element . getParent ( ) ; } return element ; } public static IRubyElement projectOrJarFocus ( InternalSearchPattern pattern ) { return pattern == null || pattern . focus == null ? null : getProjectOrJar ( pattern . focus ) ; } public static SearchDocument [ ] addWorkingCopies ( InternalSearchPattern pattern , SearchDocument [ ] indexMatches , IRubyScript [ ] copies , SearchParticipant participant ) { HashMap workingCopyDocuments = workingCopiesThatCanSeeFocus ( copies , pattern . focus , pattern . isPolymorphicSearch ( ) , participant ) ; SearchDocument [ ] matches = null ; int length = indexMatches . length ; for ( int i = ; i < length ; i ++ ) { SearchDocument searchDocument = indexMatches [ i ] ; if ( searchDocument . getParticipant ( ) == participant ) { SearchDocument workingCopyDocument = ( SearchDocument ) workingCopyDocuments . remove ( searchDocument . getPath ( ) ) ; if ( workingCopyDocument != null ) { if ( matches == null ) { System . arraycopy ( indexMatches , , matches = new SearchDocument [ length ] , , length ) ; } matches [ i ] = workingCopyDocument ; } } } if ( matches == null ) { matches = indexMatches ; } int remainingWorkingCopiesSize = workingCopyDocuments . size ( ) ; if ( remainingWorkingCopiesSize != ) { System . arraycopy ( matches , , matches = new SearchDocument [ length + remainingWorkingCopiesSize ] , , length ) ; Iterator iterator = workingCopyDocuments . values ( ) . iterator ( ) ; int index = length ; while ( iterator . hasNext ( ) ) { matches [ index ++ ] = ( SearchDocument ) iterator . next ( ) ; } } return matches ; } public static void setFocus ( InternalSearchPattern pattern , IRubyElement focus ) { pattern . focus = focus ; } private static HashMap workingCopiesThatCanSeeFocus ( IRubyScript [ ] copies , IRubyElement focus , boolean isPolymorphicSearch , SearchParticipant participant ) { if ( copies == null ) return new HashMap ( ) ; if ( focus != null ) { while ( ! ( focus instanceof IRubyProject ) && ! ( focus instanceof ExternalSourceFolderRoot ) ) { focus = focus . getParent ( ) ; } } HashMap result = new HashMap ( ) ; for ( int i = , length = copies . length ; i < length ; i ++ ) { IRubyScript workingCopy = copies [ i ] ; IPath projectOrJar = MatchLocator . getProjectOrJar ( workingCopy ) . getPath ( ) ; if ( focus == null || IndexSelector . canSeeFocus ( focus , isPolymorphicSearch , projectOrJar ) ) { result . put ( workingCopy . getPath ( ) . toString ( ) , new WorkingCopyDocument ( workingCopy , participant ) ) ; } } return result ; } public static class WorkingCopyDocument extends RubySearchDocument { public IRubyScript workingCopy ; WorkingCopyDocument ( IRubyScript workingCopy , SearchParticipant participant ) { super ( workingCopy . getPath ( ) . toString ( ) , participant ) ; this . charContents = ( ( RubyScript ) workingCopy ) . getContents ( ) ; this . workingCopy = workingCopy ; } public String toString ( ) { return "" + getPath ( ) ; } } public void locateMatches ( SearchDocument [ ] searchDocuments ) throws CoreException { int docsLength = searchDocuments . length ; if ( BasicSearchEngine . VERBOSE ) { System . out . println ( "" ) ; for ( int i = ; i < docsLength ; i ++ ) System . out . println ( "" + searchDocuments [ i ] ) ; System . out . println ( "" ) ; } int n = docsLength < ? Math . min ( Math . max ( docsLength / + , ) , ) : * ( docsLength / ) ; this . progressStep = docsLength < n ? : docsLength / n ; this . progressWorked = ; ArrayList copies = new ArrayList ( ) ; for ( int i = ; i < docsLength ; i ++ ) { SearchDocument document = searchDocuments [ i ] ; if ( document instanceof WorkingCopyDocument ) { copies . add ( ( ( WorkingCopyDocument ) document ) . workingCopy ) ; } } int copiesLength = copies . size ( ) ; this . workingCopies = new IRubyScript [ copiesLength ] ; copies . toArray ( this . workingCopies ) ; RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; this . bindings = new SimpleLookupTable ( ) ; try { if ( this . handleFactory == null ) this . handleFactory = new HandleFactory ( ) ; if ( this . progressMonitor != null ) { this . progressMonitor . beginTask ( "" , searchDocuments . length ) ; } RubyProject previousJavaProject = null ; PossibleMatchSet matchSet = new PossibleMatchSet ( ) ; Util . sort ( searchDocuments , new Util . Comparer ( ) { public int compare ( Object a , Object b ) { return ( ( SearchDocument ) a ) . getPath ( ) . compareTo ( ( ( SearchDocument ) b ) . getPath ( ) ) ; } } ) ; int displayed = ; String previousPath = null ; for ( int i = ; i < docsLength ; i ++ ) { if ( this . progressMonitor != null && this . progressMonitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } SearchDocument searchDocument = searchDocuments [ i ] ; searchDocuments [ i ] = null ; String pathString = searchDocument . getPath ( ) ; if ( i > && pathString . equals ( previousPath ) ) { if ( this . progressMonitor != null ) { this . progressWorked ++ ; if ( ( this . progressWorked % this . progressStep ) == ) this . progressMonitor . worked ( this . progressStep ) ; } displayed ++ ; continue ; } previousPath = pathString ; Openable openable ; IRubyScript workingCopy = null ; if ( searchDocument instanceof WorkingCopyDocument ) { workingCopy = ( ( WorkingCopyDocument ) searchDocument ) . workingCopy ; openable = ( Openable ) workingCopy ; } else { openable = this . handleFactory . createOpenable ( pathString ) ; } if ( openable == null ) { if ( this . progressMonitor != null ) { this . progressWorked ++ ; if ( ( this . progressWorked % this . progressStep ) == ) this . progressMonitor . worked ( this . progressStep ) ; } displayed ++ ; continue ; } IResource resource = null ; RubyProject javaProject = ( RubyProject ) openable . getRubyProject ( ) ; resource = workingCopy != null ? workingCopy . getResource ( ) : openable . getResource ( ) ; if ( resource == null ) resource = javaProject . getProject ( ) ; if ( ! javaProject . equals ( previousJavaProject ) ) { if ( previousJavaProject != null ) { try { locateMatches ( previousJavaProject , matchSet , i - displayed ) ; displayed = i ; } catch ( RubyModelException e ) { } matchSet . reset ( ) ; } previousJavaProject = javaProject ; } matchSet . add ( new PossibleMatch ( this , resource , openable , searchDocument , ( ( InternalSearchPattern ) this . pattern ) . mustResolve ) ) ; } if ( previousJavaProject != null ) { try { locateMatches ( previousJavaProject , matchSet , docsLength - displayed ) ; } catch ( RubyModelException e ) { } } } finally { if ( this . progressMonitor != null ) this . progressMonitor . done ( ) ; this . bindings = null ; } } protected boolean encloses ( IRubyElement element ) { return element != null && this . scope . encloses ( element ) ; } protected void report ( SearchMatch match ) throws CoreException { long start = - ; if ( BasicSearchEngine . VERBOSE ) { start = System . currentTimeMillis ( ) ; System . out . println ( "" ) ; System . out . println ( "" + match . getResource ( ) ) ; System . out . println ( "" + match . getOffset ( ) + "" + match . getLength ( ) + "" ) ; try { RubyElement javaElement = ( RubyElement ) match . getElement ( ) ; System . out . println ( "" + javaElement . toStringWithAncestors ( ) ) ; if ( ! javaElement . exists ( ) ) { System . out . println ( "" ) ; } } catch ( Exception e ) { } System . out . println ( match . getAccuracy ( ) == SearchMatch . A_ACCURATE ? "" : "" ) ; System . out . print ( "" ) ; if ( match . isExact ( ) ) { System . out . print ( "" ) ; } else if ( match . isEquivalent ( ) ) { System . out . print ( "" ) ; } else if ( match . isErasure ( ) ) { System . out . print ( "" ) ; } else { System . out . print ( "" ) ; } System . out . println ( "" + match . isRaw ( ) ) ; } this . requestor . acceptSearchMatch ( match ) ; } protected void locateMatches ( RubyProject javaProject , PossibleMatchSet matchSet , int expected ) throws CoreException { PossibleMatch [ ] possibleMatches = matchSet . getPossibleMatches ( javaProject . getSourceFolderRoots ( ) ) ; int length = possibleMatches . length ; if ( this . progressMonitor != null && expected > length ) { this . progressWorked += expected - length ; this . progressMonitor . worked ( expected - length ) ; } for ( int index = ; index < length ; ) { int max = Math . min ( MAX_AT_ONCE , length - index ) ; locateMatches ( javaProject , possibleMatches , index , max ) ; index += max ; } this . patternLocator . clear ( ) ; } protected void locateMatches ( RubyProject rubyProject , PossibleMatch [ ] possibleMatches , int start , int length ) throws CoreException { for ( int i = start , maxUnits = start + length ; i < maxUnits ; i ++ ) { PossibleMatch possibleMatch = possibleMatches [ i ] ; process ( possibleMatch ) ; possibleMatch . cleanUp ( ) ; } } protected void process ( PossibleMatch possibleMatch ) { this . currentPossibleMatch = possibleMatch ; RubyScript script = ( RubyScript ) possibleMatch . openable ; this . patternLocator . reportMatches ( script , this ) ; this . currentPossibleMatch = null ; } public SearchMatch newDeclarationMatch ( IRubyElement element , int accuracy , int offset , int length , SearchParticipant participant , IResource resource ) { switch ( element . getElementType ( ) ) { case IRubyElement . TYPE : return new TypeDeclarationMatch ( element , accuracy , offset , length , participant , resource ) ; case IRubyElement . FIELD : case IRubyElement . INSTANCE_VAR : case IRubyElement . CLASS_VAR : case IRubyElement . GLOBAL : case IRubyElement . CONSTANT : return new FieldDeclarationMatch ( element , accuracy , offset , length , participant , resource ) ; case IRubyElement . METHOD : return new MethodDeclarationMatch ( element , accuracy , offset , length , participant , resource ) ; default : return null ; } } public SearchMatch newDeclarationMatch ( IRubyElement element , int accuracy , int offset , int length ) { SearchParticipant participant = getParticipant ( ) ; IResource resource = this . currentPossibleMatch . resource ; return newDeclarationMatch ( element , accuracy , offset , length , participant , resource ) ; } public SearchParticipant getParticipant ( ) { return this . currentPossibleMatch . document . getParticipant ( ) ; } public TypeReferenceMatch newTypeReferenceMatch ( IRubyElement enclosingElement , int accuracy , int offset , int length ) { SearchParticipant participant = getParticipant ( ) ; IResource resource = this . currentPossibleMatch . resource ; return new TypeReferenceMatch ( enclosingElement , accuracy , offset , length , participant , resource ) ; } public SearchMatch newFieldReferenceMatch ( IRubyElement enclosingElement , IRubyElement binding , int accuracy , int offset , int length , Node reference ) { boolean isReadAccess = false ; boolean isWriteAccess = false ; if ( ( reference instanceof GlobalAsgnNode ) || ( reference instanceof ClassVarAsgnNode ) || ( reference instanceof InstAsgnNode ) ) { isWriteAccess = true ; } else { isReadAccess = true ; } SearchParticipant participant = getParticipant ( ) ; IResource resource = this . currentPossibleMatch . resource ; return new FieldReferenceMatch ( enclosingElement , binding , accuracy , offset , length , isReadAccess , isWriteAccess , false , participant , resource ) ; } public SearchMatch newMethodReferenceMatch ( IRubyElement enclosingElement , IRubyElement binding , List < String > arguments , int accuracy , int offset , int length , boolean isConstructor , Node reference ) { SearchParticipant participant = getParticipant ( ) ; IResource resource = this . currentPossibleMatch . resource ; return new MethodReferenceMatch ( enclosingElement , binding , arguments , accuracy , offset , length , isConstructor , false , participant , resource ) ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . eclipse . core . runtime . CoreException ; import org . jruby . ast . ConstNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class TypeReferenceLocator extends PatternLocator { private TypeReferencePattern pattern ; public TypeReferenceLocator ( TypeReferencePattern pattern ) { super ( pattern ) ; this . pattern = pattern ; } @ Override public void reportMatches ( RubyScript script , MatchLocator locator ) { Node ast = script . lastGoodAST ; if ( ast == null ) { try { ast = new RubyParser ( ) . parse ( script . getSource ( ) ) . getAST ( ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } InOrderVisitor visitor = new TypeRefASTVisitor ( script , pattern , locator ) ; visitor . acceptNode ( ast ) ; } private class TypeRefASTVisitor extends InOrderVisitor { private TypeReferencePattern pattern ; private MatchLocator locator ; private RubyScript script ; public TypeRefASTVisitor ( RubyScript script , TypeReferencePattern pattern , MatchLocator locator ) { this . script = script ; this . pattern = pattern ; this . locator = locator ; } private int resolveLevel ( char [ ] sourceName ) { char [ ] qualifiedPattern = getQualifiedPattern ( pattern . simpleName , pattern . qualification ) ; if ( sourceName == null ) return IMPOSSIBLE_MATCH ; if ( ( pattern . matchMode & SearchPattern . R_PREFIX_MATCH ) != ) { if ( CharOperation . prefixEquals ( qualifiedPattern , sourceName , pattern . isCaseSensitive ) ) { return ACCURATE_MATCH ; } } if ( pattern . isCamelCase ) { if ( ! pattern . isCaseSensitive || ( qualifiedPattern . length > && sourceName . length > && qualifiedPattern [ ] == sourceName [ ] ) ) { if ( CharOperation . camelCaseMatch ( qualifiedPattern , sourceName ) ) { return ACCURATE_MATCH ; } } if ( pattern . matchMode == SearchPattern . R_EXACT_MATCH ) { boolean matchPattern = CharOperation . prefixEquals ( qualifiedPattern , sourceName , pattern . isCaseSensitive ) ; return matchPattern ? ACCURATE_MATCH : IMPOSSIBLE_MATCH ; } } boolean matchPattern = CharOperation . match ( qualifiedPattern , sourceName , pattern . isCaseSensitive ) ; return matchPattern ? ACCURATE_MATCH : IMPOSSIBLE_MATCH ; } protected char [ ] getQualifiedPattern ( char [ ] simpleNamePattern , char [ ] qualificationPattern ) { if ( simpleNamePattern == null ) { if ( qualificationPattern == null ) return null ; return CharOperation . concat ( qualificationPattern , ONE_STAR , "" ) ; } else if ( qualificationPattern == null ) { return simpleNamePattern ; } else { return CharOperation . concat ( qualificationPattern , simpleNamePattern , "" ) ; } } @ Override public Object visitConstNode ( ConstNode iVisited ) { String constantName = iVisited . getName ( ) ; int accuracy = resolveLevel ( constantName . toCharArray ( ) ) ; if ( accuracy != IMPOSSIBLE_MATCH ) { try { IRubyElement enclosingElement = script . getElementAt ( iVisited . getPosition ( ) . getStartOffset ( ) ) ; locator . report ( locator . newTypeReferenceMatch ( enclosingElement , accuracy , iVisited . getPosition ( ) . getStartOffset ( ) , iVisited . getPosition ( ) . getEndOffset ( ) - iVisited . getPosition ( ) . getStartOffset ( ) ) ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } return super . visitConstNode ( iVisited ) ; } } } package org . rubypeople . rdt . internal . core . search . matching ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . util . Util ; public class TypeDeclarationLocator extends PatternLocator { private TypeDeclarationPattern pattern ; public TypeDeclarationLocator ( TypeDeclarationPattern pattern ) { super ( pattern ) ; this . pattern = pattern ; } @ Override public void reportMatches ( RubyScript script , MatchLocator locator ) { reportMatches ( ( IParent ) script , locator ) ; } private void reportMatches ( IParent parent , MatchLocator locator ) { try { IRubyElement [ ] children = parent . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { IRubyElement child = children [ i ] ; if ( child . isType ( IRubyElement . TYPE ) && locator . encloses ( child ) ) { int accuracy = getAccuracy ( ( IType ) child ) ; if ( accuracy != IMPOSSIBLE_MATCH ) { IMember member = ( IMember ) child ; ISourceRange range = member . getSourceRange ( ) ; try { locator . report ( locator . newDeclarationMatch ( child , accuracy , range . getOffset ( ) , range . getLength ( ) ) ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } } if ( child instanceof IParent ) { IParent parentTwo = ( IParent ) child ; reportMatches ( parentTwo , locator ) ; } } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } private int getAccuracy ( IType type ) { String simpleName = Util . getSimpleName ( type . getElementName ( ) ) ; if ( this . pattern . simpleName != null && ! matchesName ( this . pattern . simpleName , simpleName . toCharArray ( ) ) ) return IMPOSSIBLE_MATCH ; switch ( this . pattern . typeSuffix ) { case CLASS_SUFFIX : if ( ! type . isClass ( ) ) return IMPOSSIBLE_MATCH ; break ; case MODULE_SUFFIX : if ( ! type . isModule ( ) ) return IMPOSSIBLE_MATCH ; break ; } return ACCURATE_MATCH ; } } package org . rubypeople . rdt . internal . core . search . matching ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class PatternLocator implements IIndexConstants { protected int matchMode ; protected boolean isCaseSensitive ; protected boolean isCamelCase ; protected boolean isEquivalentMatch ; protected boolean isErasureMatch ; protected boolean mustResolve ; protected boolean mayBeGeneric ; public static final int IMPOSSIBLE_MATCH = ; public static final int INACCURATE_MATCH = ; public static final int POSSIBLE_MATCH = ; public static final int ACCURATE_MATCH = ; public static final int ERASURE_MATCH = ; public static final int EXACT_FLAVOR = ; public static final int PREFIX_FLAVOR = ; public static final int PATTERN_FLAVOR = ; public static final int REGEXP_FLAVOR = ; public static final int CAMELCASE_FLAVOR = ; public static final int SUPER_INVOCATION_FLAVOR = ; public static final int SUB_INVOCATION_FLAVOR = ; public static final int OVERRIDDEN_METHOD_FLAVOR = ; public static final int MATCH_LEVEL_MASK = ; public static final int FLAVORS_MASK = ~ MATCH_LEVEL_MASK ; public static final int COMPILATION_UNIT_CONTAINER = ; public static final int CLASS_CONTAINER = ; public static final int METHOD_CONTAINER = ; public static final int FIELD_CONTAINER = ; public static final int ALL_CONTAINER = COMPILATION_UNIT_CONTAINER | CLASS_CONTAINER | METHOD_CONTAINER | FIELD_CONTAINER ; public PatternLocator ( SearchPattern pattern ) { int matchRule = pattern . getMatchRule ( ) ; this . isCaseSensitive = ( matchRule & SearchPattern . R_CASE_SENSITIVE ) != ; this . isCamelCase = ( matchRule & SearchPattern . R_CAMELCASE_MATCH ) != ; this . isErasureMatch = ( matchRule & SearchPattern . R_ERASURE_MATCH ) != ; this . isEquivalentMatch = ( matchRule & SearchPattern . R_EQUIVALENT_MATCH ) != ; this . matchMode = matchRule & RubySearchPattern . MATCH_MODE_MASK ; this . mustResolve = ( ( InternalSearchPattern ) pattern ) . mustResolve ; } protected int matchContainer ( ) { return ALL_CONTAINER ; } public static PatternLocator patternLocator ( SearchPattern pattern ) { switch ( ( ( InternalSearchPattern ) pattern ) . kind ) { case IIndexConstants . TYPE_REF_PATTERN : return new TypeReferenceLocator ( ( TypeReferencePattern ) pattern ) ; case IIndexConstants . TYPE_DECL_PATTERN : return new TypeDeclarationLocator ( ( TypeDeclarationPattern ) pattern ) ; case IIndexConstants . FIELD_PATTERN : return new FieldLocator ( ( FieldPattern ) pattern ) ; case IIndexConstants . METHOD_PATTERN : return new MethodLocator ( ( MethodPattern ) pattern ) ; case IIndexConstants . OR_PATTERN : return new OrLocator ( ( OrPattern ) pattern ) ; case IIndexConstants . LOCAL_VAR_PATTERN : return new LocalVariableLocator ( ( LocalVariablePattern ) pattern ) ; } return null ; } protected void clear ( ) { } public void reportMatches ( RubyScript script , MatchLocator locator ) { } protected boolean matchesName ( char [ ] pattern , char [ ] name ) { if ( pattern == null ) return true ; if ( name == null ) return false ; return matchNameValue ( pattern , name ) != IMPOSSIBLE_MATCH ; } protected int matchNameValue ( char [ ] pattern , char [ ] name ) { if ( pattern == null ) return ACCURATE_MATCH ; if ( name == null ) return IMPOSSIBLE_MATCH ; if ( name . length == ) { if ( pattern . length == ) { return ACCURATE_MATCH ; } return IMPOSSIBLE_MATCH ; } else if ( pattern . length == ) { return IMPOSSIBLE_MATCH ; } boolean matchFirstChar = ! this . isCaseSensitive || pattern [ ] == name [ ] ; boolean sameLength = pattern . length == name . length ; boolean canBePrefix = name . length >= pattern . length ; if ( this . isCamelCase && matchFirstChar && CharOperation . camelCaseMatch ( pattern , name ) ) { return POSSIBLE_MATCH ; } switch ( this . matchMode ) { case SearchPattern . R_EXACT_MATCH : if ( ! this . isCamelCase ) { if ( sameLength && matchFirstChar && CharOperation . equals ( pattern , name , this . isCaseSensitive ) ) { return POSSIBLE_MATCH | EXACT_FLAVOR ; } break ; } case SearchPattern . R_PREFIX_MATCH : if ( canBePrefix && matchFirstChar && CharOperation . prefixEquals ( pattern , name , this . isCaseSensitive ) ) { return POSSIBLE_MATCH ; } break ; case SearchPattern . R_PATTERN_MATCH : if ( ! this . isCaseSensitive ) { pattern = CharOperation . toLowerCase ( pattern ) ; } if ( CharOperation . match ( pattern , name , this . isCaseSensitive ) ) { return POSSIBLE_MATCH ; } break ; case SearchPattern . R_REGEXP_MATCH : break ; } return IMPOSSIBLE_MATCH ; } } package org . rubypeople . rdt . internal . core . search ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . core . ExternalSourceFolderRoot ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . search . indexing . IndexManager ; import org . rubypeople . rdt . internal . core . search . matching . MatchLocator ; import org . rubypeople . rdt . internal . core . search . matching . MethodPattern ; public class IndexSelector { IRubySearchScope searchScope ; SearchPattern pattern ; IPath [ ] indexLocations ; public IndexSelector ( IRubySearchScope searchScope , SearchPattern pattern ) { this . searchScope = searchScope ; this . pattern = pattern ; } public static boolean canSeeFocus ( IRubyElement focus , boolean isPolymorphicSearch , IPath projectOrJarPath ) { try { ILoadpathEntry [ ] focusEntries = null ; if ( isPolymorphicSearch ) { RubyProject focusProject = ( RubyProject ) focus ; focusEntries = focusProject . getExpandedLoadpath ( true ) ; } IRubyModel model = focus . getRubyModel ( ) ; IRubyProject project = getRubyProject ( projectOrJarPath , model ) ; if ( project != null ) return canSeeFocus ( focus , ( RubyProject ) project , focusEntries ) ; IRubyProject [ ] allProjects = model . getRubyProjects ( ) ; for ( int i = , length = allProjects . length ; i < length ; i ++ ) { RubyProject otherProject = ( RubyProject ) allProjects [ i ] ; ILoadpathEntry [ ] entries = otherProject . getResolvedLoadpath ( true ) ; for ( int j = , length2 = entries . length ; j < length2 ; j ++ ) { ILoadpathEntry entry = entries [ j ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY && entry . getPath ( ) . equals ( projectOrJarPath ) ) if ( canSeeFocus ( focus , otherProject , focusEntries ) ) return true ; } } return false ; } catch ( RubyModelException e ) { return false ; } } public static boolean canSeeFocus ( IRubyElement focus , RubyProject javaProject , ILoadpathEntry [ ] focusEntriesForPolymorphicSearch ) { try { if ( focus . equals ( javaProject ) ) return true ; if ( focusEntriesForPolymorphicSearch != null ) { IPath projectPath = javaProject . getProject ( ) . getFullPath ( ) ; for ( int i = , length = focusEntriesForPolymorphicSearch . length ; i < length ; i ++ ) { ILoadpathEntry entry = focusEntriesForPolymorphicSearch [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT && entry . getPath ( ) . equals ( projectPath ) ) return true ; } } if ( focus instanceof ExternalSourceFolderRoot ) { IPath focusPath = focus . getPath ( ) ; ILoadpathEntry [ ] entries = javaProject . getExpandedLoadpath ( true ) ; for ( int i = , length = entries . length ; i < length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY && entry . getPath ( ) . equals ( focusPath ) ) return true ; } return false ; } IPath focusPath = ( ( RubyProject ) focus ) . getProject ( ) . getFullPath ( ) ; ILoadpathEntry [ ] entries = javaProject . getExpandedLoadpath ( true ) ; for ( int i = , length = entries . length ; i < length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT && entry . getPath ( ) . equals ( focusPath ) ) return true ; } return false ; } catch ( RubyModelException e ) { return false ; } } private void initializeIndexLocations ( ) { IPath [ ] projectsAndJars = this . searchScope . enclosingProjectsAndJars ( ) ; IndexManager manager = RubyModelManager . getRubyModelManager ( ) . getIndexManager ( ) ; SimpleSet locations = new SimpleSet ( ) ; IRubyElement focus = MatchLocator . projectOrJarFocus ( this . pattern ) ; if ( focus == null ) { for ( int i = ; i < projectsAndJars . length ; i ++ ) locations . add ( manager . computeIndexLocation ( projectsAndJars [ i ] ) ) ; } else { try { int length = projectsAndJars . length ; RubyProject [ ] projectsCanSeeFocus = new RubyProject [ length ] ; SimpleSet visitedProjects = new SimpleSet ( length ) ; int projectIndex = ; SimpleSet jarsToCheck = new SimpleSet ( length ) ; ILoadpathEntry [ ] focusEntries = null ; if ( this . pattern instanceof MethodPattern ) { RubyProject focusProject = ( RubyProject ) focus ; focusEntries = focusProject . getExpandedLoadpath ( true ) ; } IRubyModel model = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; for ( int i = ; i < length ; i ++ ) { IPath path = projectsAndJars [ i ] ; RubyProject project = ( RubyProject ) getRubyProject ( path , model ) ; if ( project != null ) { visitedProjects . add ( project ) ; if ( canSeeFocus ( focus , project , focusEntries ) ) { locations . add ( manager . computeIndexLocation ( path ) ) ; projectsCanSeeFocus [ projectIndex ++ ] = project ; } } else { jarsToCheck . add ( path ) ; } } for ( int i = ; i < projectIndex && jarsToCheck . elementSize > ; i ++ ) { ILoadpathEntry [ ] entries = projectsCanSeeFocus [ i ] . getResolvedLoadpath ( true ) ; for ( int j = entries . length ; -- j >= ; ) { ILoadpathEntry entry = entries [ j ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY ) { IPath path = entry . getPath ( ) ; if ( jarsToCheck . includes ( path ) ) { locations . add ( manager . computeIndexLocation ( entry . getPath ( ) ) ) ; jarsToCheck . remove ( path ) ; } } } } if ( jarsToCheck . elementSize > ) { IRubyProject [ ] allProjects = model . getRubyProjects ( ) ; for ( int i = , l = allProjects . length ; i < l && jarsToCheck . elementSize > ; i ++ ) { RubyProject project = ( RubyProject ) allProjects [ i ] ; if ( ! visitedProjects . includes ( project ) ) { ILoadpathEntry [ ] entries = project . getResolvedLoadpath ( true ) ; for ( int j = entries . length ; -- j >= ; ) { ILoadpathEntry entry = entries [ j ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY ) { IPath path = entry . getPath ( ) ; if ( jarsToCheck . includes ( path ) ) { locations . add ( manager . computeIndexLocation ( entry . getPath ( ) ) ) ; jarsToCheck . remove ( path ) ; } } } } } } } catch ( RubyModelException e ) { } } this . indexLocations = new IPath [ locations . elementSize ] ; Object [ ] values = locations . values ; int count = ; for ( int i = values . length ; -- i >= ; ) if ( values [ i ] != null ) this . indexLocations [ count ++ ] = ( IPath ) values [ i ] ; } public IPath [ ] getIndexLocations ( ) { if ( this . indexLocations == null ) { this . initializeIndexLocations ( ) ; } return this . indexLocations ; } private static IRubyProject getRubyProject ( IPath path , IRubyModel model ) { IRubyProject project = model . getRubyProject ( path . lastSegment ( ) ) ; if ( project . exists ( ) ) { return project ; } return null ; } } package org . rubypeople . rdt . internal . core . search ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . core . RubyElement ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . hierarchy . TypeHierarchy ; public class HierarchyScope implements IRubySearchScope { public IType focusType ; private String focusPath ; private WorkingCopyOwner owner ; private ITypeHierarchy hierarchy ; private IType [ ] types ; private HashSet resourcePaths ; private IPath [ ] enclosingProjectsAndJars ; protected IResource [ ] elements ; protected int elementCount ; public boolean needsRefresh ; public void add ( IResource element ) { if ( this . elementCount == this . elements . length ) { System . arraycopy ( this . elements , , this . elements = new IResource [ this . elementCount * ] , , this . elementCount ) ; } elements [ elementCount ++ ] = element ; } public HierarchyScope ( IType type , WorkingCopyOwner owner ) throws RubyModelException { this . focusType = type ; this . owner = owner ; this . enclosingProjectsAndJars = this . computeProjectsAndJars ( type ) ; ISourceFolderRoot root = ( ISourceFolderRoot ) type . getSourceFolder ( ) . getParent ( ) ; this . focusPath = type . getPath ( ) . toString ( ) ; this . needsRefresh = true ; } private void buildResourceVector ( ) { HashMap resources = new HashMap ( ) ; HashMap paths = new HashMap ( ) ; this . types = this . hierarchy . getAllTypes ( ) ; IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; for ( int i = ; i < this . types . length ; i ++ ) { IType type = this . types [ i ] ; IResource resource = type . getResource ( ) ; if ( resource != null && resources . get ( resource ) == null ) { resources . put ( resource , resource ) ; add ( resource ) ; } ISourceFolderRoot root = ( ISourceFolderRoot ) type . getSourceFolder ( ) . getParent ( ) ; paths . put ( type . getRubyProject ( ) . getProject ( ) . getFullPath ( ) , type ) ; } this . enclosingProjectsAndJars = new IPath [ paths . size ( ) ] ; int i = ; for ( Iterator iter = paths . keySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { this . enclosingProjectsAndJars [ i ++ ] = ( IPath ) iter . next ( ) ; } } private IPath [ ] computeProjectsAndJars ( IType type ) throws RubyModelException { HashSet set = new HashSet ( ) ; ISourceFolderRoot root = ( ISourceFolderRoot ) type . getSourceFolder ( ) . getParent ( ) ; if ( root . isArchive ( ) ) { set . add ( root . getPath ( ) ) ; IPath rootPath = root . getPath ( ) ; IRubyModel model = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; IRubyProject [ ] projects = model . getRubyProjects ( ) ; HashSet visited = new HashSet ( ) ; for ( int i = ; i < projects . length ; i ++ ) { RubyProject project = ( RubyProject ) projects [ i ] ; ILoadpathEntry [ ] classpath = project . getResolvedLoadpath ( true , false , false ) ; for ( int j = ; j < classpath . length ; j ++ ) { if ( rootPath . equals ( classpath [ j ] . getPath ( ) ) ) { ISourceFolderRoot [ ] roots = project . getAllSourceFolderRoots ( ) ; set . add ( project . getPath ( ) ) ; this . computeDependents ( project , set , visited ) ; break ; } } } } else { IRubyProject project = ( IRubyProject ) root . getParent ( ) ; ISourceFolderRoot [ ] roots = project . getAllSourceFolderRoots ( ) ; for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot pkgFragmentRoot = roots [ i ] ; set . add ( pkgFragmentRoot . getParent ( ) . getPath ( ) ) ; } this . computeDependents ( project , set , new HashSet ( ) ) ; } IPath [ ] result = new IPath [ set . size ( ) ] ; set . toArray ( result ) ; return result ; } private void computeDependents ( IRubyProject project , HashSet set , HashSet visited ) { if ( visited . contains ( project ) ) return ; visited . add ( project ) ; IProject [ ] dependents = project . getProject ( ) . getReferencingProjects ( ) ; for ( int i = ; i < dependents . length ; i ++ ) { try { IRubyProject dependent = RubyCore . create ( dependents [ i ] ) ; ISourceFolderRoot [ ] roots = dependent . getSourceFolderRoots ( ) ; set . add ( dependent . getPath ( ) ) ; for ( int j = ; j < roots . length ; j ++ ) { ISourceFolderRoot pkgFragmentRoot = roots [ j ] ; if ( pkgFragmentRoot . isArchive ( ) ) { set . add ( pkgFragmentRoot . getPath ( ) ) ; } } this . computeDependents ( dependent , set , visited ) ; } catch ( RubyModelException e ) { } } } public boolean encloses ( String resourcePath ) { if ( this . hierarchy == null ) { if ( resourcePath . equals ( this . focusPath ) ) { return true ; } else { if ( this . needsRefresh ) { try { this . initialize ( ) ; } catch ( RubyModelException e ) { return false ; } } else { return true ; } } } if ( this . needsRefresh ) { try { this . refresh ( ) ; } catch ( RubyModelException e ) { return false ; } } for ( int i = ; i < this . elementCount ; i ++ ) { if ( resourcePath . startsWith ( this . elements [ i ] . getFullPath ( ) . toString ( ) ) ) { return true ; } } return false ; } public boolean encloses ( IRubyElement element ) { if ( this . hierarchy == null ) { if ( this . focusType . equals ( element . getAncestor ( IRubyElement . TYPE ) ) ) { return true ; } else { if ( this . needsRefresh ) { try { this . initialize ( ) ; } catch ( RubyModelException e ) { return false ; } } else { return true ; } } } if ( this . needsRefresh ) { try { this . refresh ( ) ; } catch ( RubyModelException e ) { return false ; } } IType type = null ; if ( element instanceof IType ) { type = ( IType ) element ; } else if ( element instanceof IMember ) { type = ( ( IMember ) element ) . getDeclaringType ( ) ; } if ( type != null ) { if ( this . hierarchy . contains ( type ) ) { return true ; } else { IType original ; if ( ( original = ( IType ) type . getPrimaryElement ( ) ) != null ) { return this . hierarchy . contains ( original ) ; } } } return false ; } public IPath [ ] enclosingProjectsAndJars ( ) { if ( this . needsRefresh ) { try { this . refresh ( ) ; } catch ( RubyModelException e ) { return new IPath [ ] ; } } return this . enclosingProjectsAndJars ; } protected void initialize ( ) throws RubyModelException { this . resourcePaths = new HashSet ( ) ; this . elements = new IResource [ ] ; this . elementCount = ; this . needsRefresh = false ; if ( this . hierarchy == null ) { this . hierarchy = this . focusType . newTypeHierarchy ( this . owner , null ) ; } else { this . hierarchy . refresh ( null ) ; } this . buildResourceVector ( ) ; } public void processDelta ( IRubyElementDelta delta ) { if ( this . needsRefresh ) return ; this . needsRefresh = this . hierarchy == null ? false : ( ( TypeHierarchy ) this . hierarchy ) . isAffected ( delta ) ; } protected void refresh ( ) throws RubyModelException { if ( this . hierarchy != null ) { this . initialize ( ) ; } } public String toString ( ) { return "" + ( ( RubyElement ) this . focusType ) . toStringWithAncestors ( ) ; } } package org . rubypeople . rdt . internal . core . search ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . core . LoadpathEntry ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . SourceFolder ; import org . rubypeople . rdt . internal . core . util . Util ; public class RubySearchScope extends AbstractSearchScope implements IRubySearchScope { private List < IRubyElement > elements ; private ArrayList < String > projectPaths = new ArrayList < String > ( ) ; private int [ ] projectIndexes ; private String [ ] containerPaths ; private String [ ] relativePaths ; private boolean [ ] isPkgPath ; private int pathsCount ; private int threshold ; private IPath [ ] enclosingProjectsAndJars ; public RubySearchScope ( ) { this ( ) ; } private RubySearchScope ( int size ) { initialize ( size ) ; } protected void initialize ( int size ) { this . pathsCount = ; this . threshold = size ; int extraRoom = ( int ) ( size * ) ; if ( this . threshold == extraRoom ) extraRoom ++ ; this . relativePaths = new String [ extraRoom ] ; this . containerPaths = new String [ extraRoom ] ; this . projectPaths = new ArrayList < String > ( ) ; this . projectIndexes = new int [ extraRoom ] ; this . isPkgPath = new boolean [ extraRoom ] ; this . enclosingProjectsAndJars = new IPath [ ] ; } public boolean encloses ( String resourcePathString ) { int index1 = indexOf ( resourcePathString ) ; if ( index1 >= ) return true ; for ( int i = ; i < this . containerPaths . length ; i ++ ) { String containerPath = this . containerPaths [ i ] ; if ( containerPath == null ) continue ; if ( resourcePathString . startsWith ( containerPath ) ) return true ; } return false ; } private int indexOf ( String fullPath ) { for ( int i = , length = this . relativePaths . length ; i < length ; i ++ ) { String currentRelativePath = this . relativePaths [ i ] ; if ( currentRelativePath == null ) continue ; String currentContainerPath = this . containerPaths [ i ] ; String currentFullPath = currentRelativePath . length ( ) == ? currentContainerPath : ( currentContainerPath + '' + currentRelativePath ) ; if ( encloses ( currentFullPath , fullPath , i ) ) return i ; } return - ; } private boolean encloses ( String enclosingPath , String path , int index ) { path = normalize ( path ) ; int pathLength = path . length ( ) ; int enclosingLength = enclosingPath . length ( ) ; if ( pathLength < enclosingLength ) { return false ; } if ( enclosingLength == ) { return true ; } if ( pathLength == enclosingLength ) { return path . equals ( enclosingPath ) ; } if ( ! this . isPkgPath [ index ] ) { return path . startsWith ( enclosingPath ) && path . charAt ( enclosingLength ) == '' ; } else { if ( path . startsWith ( enclosingPath ) && ( ( enclosingPath . length ( ) == path . lastIndexOf ( '' ) ) || ( enclosingPath . length ( ) == path . length ( ) ) ) ) { return true ; } } return false ; } private void add ( String projectPath , String relativePath , String containerPath , boolean isPackage ) { containerPath = normalize ( containerPath ) ; relativePath = normalize ( relativePath ) ; int length = this . containerPaths . length , index = ( containerPath . hashCode ( ) & ) % length ; String currentRelativePath , currentContainerPath ; while ( ( currentRelativePath = this . relativePaths [ index ] ) != null && ( currentContainerPath = this . containerPaths [ index ] ) != null ) { if ( currentRelativePath . equals ( relativePath ) && currentContainerPath . equals ( containerPath ) ) return ; if ( ++ index == length ) { index = ; } } int idx = this . projectPaths . indexOf ( projectPath ) ; if ( idx == - ) { this . projectPaths . add ( projectPath ) ; idx = this . projectPaths . indexOf ( projectPath ) ; } this . projectIndexes [ index ] = idx ; this . relativePaths [ index ] = relativePath ; this . containerPaths [ index ] = containerPath ; this . isPkgPath [ index ] = isPackage ; if ( ++ this . pathsCount > this . threshold ) rehash ( ) ; } void add ( RubyProject rubyProject , IPath pathToAdd , int includeMask , HashSet visitedProjects , ILoadpathEntry referringEntry ) throws RubyModelException { IProject project = rubyProject . getProject ( ) ; if ( ! project . isAccessible ( ) || ! visitedProjects . add ( project ) ) return ; IPath projectPath = project . getFullPath ( ) ; String projectPathString = projectPath . toString ( ) ; this . addEnclosingProjectOrJar ( projectPath ) ; ILoadpathEntry [ ] entries = rubyProject . getResolvedLoadpath ( true ) ; IRubyModel model = rubyProject . getRubyModel ( ) ; RubyModelManager . PerProjectInfo perProjectInfo = rubyProject . getPerProjectInfo ( ) ; for ( int i = , length = entries . length ; i < length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; LoadpathEntry cpEntry = ( LoadpathEntry ) entry ; if ( referringEntry != null ) { if ( ! entry . isExported ( ) && entry . getEntryKind ( ) != ILoadpathEntry . CPE_SOURCE ) continue ; cpEntry = cpEntry . combineWith ( ( LoadpathEntry ) referringEntry ) ; } switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_LIBRARY : ILoadpathEntry rawEntry = null ; Map resolvedPathToRawEntries = perProjectInfo . resolvedPathToRawEntries ; if ( resolvedPathToRawEntries != null ) { rawEntry = ( ILoadpathEntry ) resolvedPathToRawEntries . get ( entry . getPath ( ) ) ; } if ( rawEntry == null ) break ; switch ( rawEntry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_LIBRARY : case ILoadpathEntry . CPE_VARIABLE : if ( ( includeMask & APPLICATION_LIBRARIES ) != ) { IPath path = entry . getPath ( ) ; if ( pathToAdd == null || pathToAdd . equals ( path ) ) { String pathToString = path . getDevice ( ) == null ? path . toString ( ) : path . toOSString ( ) ; add ( projectPath . toString ( ) , "" , pathToString , false ) ; addEnclosingProjectOrJar ( path ) ; } } break ; case ILoadpathEntry . CPE_CONTAINER : ILoadpathContainer container = RubyCore . getLoadpathContainer ( rawEntry . getPath ( ) , rubyProject ) ; if ( container == null ) break ; if ( ( container . getKind ( ) == ILoadpathContainer . K_APPLICATION && ( includeMask & APPLICATION_LIBRARIES ) != ) || ( includeMask & SYSTEM_LIBRARIES ) != ) { IPath path = entry . getPath ( ) ; if ( pathToAdd == null || pathToAdd . equals ( path ) ) { String pathToString = path . getDevice ( ) == null ? path . toString ( ) : path . toOSString ( ) ; add ( projectPath . toString ( ) , "" , pathToString , false ) ; addEnclosingProjectOrJar ( path ) ; } } break ; } break ; case ILoadpathEntry . CPE_PROJECT : if ( ( includeMask & REFERENCED_PROJECTS ) != ) { IPath path = entry . getPath ( ) ; if ( pathToAdd == null || pathToAdd . equals ( path ) ) { add ( ( RubyProject ) model . getRubyProject ( entry . getPath ( ) . lastSegment ( ) ) , null , includeMask , visitedProjects , cpEntry ) ; } } break ; case ILoadpathEntry . CPE_SOURCE : if ( ( includeMask & SOURCES ) != ) { IPath path = entry . getPath ( ) ; if ( pathToAdd == null || pathToAdd . equals ( path ) ) { add ( projectPath . toString ( ) , Util . relativePath ( path , ) , projectPathString , false ) ; } } break ; } } } private void addEnclosingProjectOrJar ( IPath path ) { int length = this . enclosingProjectsAndJars . length ; for ( int i = ; i < length ; i ++ ) { if ( this . enclosingProjectsAndJars [ i ] . equals ( path ) ) return ; } System . arraycopy ( this . enclosingProjectsAndJars , , this . enclosingProjectsAndJars = new IPath [ length + ] , , length ) ; this . enclosingProjectsAndJars [ length ] = path ; } private String normalize ( String path ) { int pathLength = path . length ( ) ; int index = pathLength - ; while ( index >= && path . charAt ( index ) == '' ) index -- ; if ( index != pathLength - ) return path . substring ( , index + ) ; return path ; } private void rehash ( ) { RubySearchScope newScope = new RubySearchScope ( this . pathsCount * ) ; newScope . projectPaths . ensureCapacity ( this . projectPaths . size ( ) ) ; String currentPath ; for ( int i = this . relativePaths . length ; -- i >= ; ) if ( ( currentPath = this . relativePaths [ i ] ) != null ) { int idx = this . projectIndexes [ i ] ; if ( this . projectPaths . size ( ) <= idx ) { newScope . add ( currentPath , this . containerPaths [ i ] , this . isPkgPath [ i ] ) ; } else { String projectPath = idx == - ? null : ( String ) this . projectPaths . get ( idx ) ; newScope . add ( projectPath , currentPath , this . containerPaths [ i ] , this . isPkgPath [ i ] ) ; } } this . relativePaths = newScope . relativePaths ; this . containerPaths = newScope . containerPaths ; this . projectPaths = newScope . projectPaths ; this . projectIndexes = newScope . projectIndexes ; this . isPkgPath = newScope . isPkgPath ; this . threshold = newScope . threshold ; } public IPath [ ] enclosingProjectsAndJars ( ) { return this . enclosingProjectsAndJars ; } public void add ( RubyProject project , int includeMask , HashSet visitedProject ) throws RubyModelException { add ( project , null , includeMask , visitedProject , null ) ; } public void add ( IRubyElement element ) throws RubyModelException { IPath containerPath = null ; String containerPathToString = null ; int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES ; switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : break ; case IRubyElement . RUBY_PROJECT : add ( ( RubyProject ) element , null , includeMask , new HashSet ( ) , null ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : ISourceFolderRoot root = ( ISourceFolderRoot ) element ; containerPath = root . getPath ( ) ; containerPathToString = containerPath . getDevice ( ) == null ? containerPath . toString ( ) : containerPath . toOSString ( ) ; IResource rootResource = root . getResource ( ) ; if ( rootResource != null && rootResource . isAccessible ( ) ) { String relativePath = Util . relativePath ( rootResource . getFullPath ( ) , containerPath . segmentCount ( ) ) ; add ( relativePath , containerPathToString , false ) ; } else { add ( "" , containerPathToString , false ) ; } break ; case IRubyElement . SOURCE_FOLDER : root = ( ISourceFolderRoot ) element . getParent ( ) ; if ( root . isExternal ( ) ) { String relativePath = Util . concatWith ( ( ( SourceFolder ) element ) . names , '' ) ; containerPath = root . getPath ( ) ; containerPathToString = containerPath . getDevice ( ) == null ? containerPath . toString ( ) : containerPath . toOSString ( ) ; add ( relativePath , containerPathToString , true ) ; } else { IResource resource = element . getResource ( ) ; if ( resource != null ) { if ( resource . isAccessible ( ) ) { containerPath = root . getParent ( ) . getPath ( ) ; } else { containerPath = resource . getParent ( ) . getFullPath ( ) ; } containerPathToString = containerPath . getDevice ( ) == null ? containerPath . toString ( ) : containerPath . toOSString ( ) ; String relativePath = Util . relativePath ( resource . getFullPath ( ) , containerPath . segmentCount ( ) ) ; add ( relativePath , containerPathToString , true ) ; } } break ; default : if ( element instanceof IMember ) { if ( this . elements == null ) { this . elements = new ArrayList < IRubyElement > ( ) ; } this . elements . add ( element ) ; } root = ( ISourceFolderRoot ) element . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; containerPath = root . getPath ( ) ; String relativePath = Util . relativePath ( getPath ( element , true ) , ) ; containerPathToString = containerPath . getDevice ( ) == null ? containerPath . toString ( ) : containerPath . toOSString ( ) ; add ( relativePath , containerPathToString , false ) ; } if ( containerPath != null ) addEnclosingProjectOrJar ( containerPath ) ; } private void add ( String relativePath , String containerPath , boolean isPackage ) { containerPath = normalize ( containerPath ) ; relativePath = normalize ( relativePath ) ; int length = this . containerPaths . length , index = ( containerPath . hashCode ( ) & ) % length ; String currentRelativePath , currentContainerPath ; while ( ( currentRelativePath = this . relativePaths [ index ] ) != null && ( currentContainerPath = this . containerPaths [ index ] ) != null ) { if ( currentRelativePath . equals ( relativePath ) && currentContainerPath . equals ( containerPath ) ) return ; if ( ++ index == length ) { index = ; } } this . relativePaths [ index ] = relativePath ; this . containerPaths [ index ] = containerPath ; this . isPkgPath [ index ] = isPackage ; if ( ++ this . pathsCount > this . threshold ) rehash ( ) ; } private IPath getPath ( IRubyElement element , boolean relativeToRoot ) { switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : return Path . EMPTY ; case IRubyElement . RUBY_PROJECT : return element . getPath ( ) ; case IRubyElement . SOURCE_FOLDER_ROOT : if ( relativeToRoot ) return Path . EMPTY ; return element . getPath ( ) ; case IRubyElement . SOURCE_FOLDER : String relativePath = Util . concatWith ( ( ( SourceFolder ) element ) . names , '' ) ; return getPath ( element . getParent ( ) , relativeToRoot ) . append ( new Path ( relativePath ) ) ; case IRubyElement . SCRIPT : return getPath ( element . getParent ( ) , relativeToRoot ) . append ( new Path ( element . getElementName ( ) ) ) ; default : return getPath ( element . getParent ( ) , relativeToRoot ) ; } } public boolean encloses ( IRubyElement element ) { if ( this . elements != null ) { for ( int i = , length = this . elements . size ( ) ; i < length ; i ++ ) { IRubyElement scopeElement = this . elements . get ( i ) ; if ( element instanceof IField ) { if ( element . isType ( IRubyElement . GLOBAL ) ) { scopeElement = scopeElement . getAncestor ( IRubyElement . SCRIPT ) ; } else { scopeElement = scopeElement . getAncestor ( IRubyElement . TYPE ) ; } } IRubyElement searchedElement = element ; while ( searchedElement != null ) { if ( searchedElement . equals ( scopeElement ) ) return true ; searchedElement = searchedElement . getParent ( ) ; } } return false ; } ISourceFolderRoot root = ( ISourceFolderRoot ) element . getAncestor ( IRubyElement . SOURCE_FOLDER_ROOT ) ; if ( root != null && root . isExternal ( ) ) { IPath rootPath = root . getPath ( ) ; String rootPathToString = rootPath . getDevice ( ) == null ? rootPath . toString ( ) : rootPath . toOSString ( ) ; IPath relativePath = getPath ( element , true ) ; return indexOf ( rootPathToString , relativePath . toString ( ) ) >= ; } String fullResourcePathString = getPath ( element , false ) . toString ( ) ; return indexOf ( fullResourcePathString ) >= ; } private int indexOf ( String containerPath , String relativePath ) { int length = this . containerPaths . length , index = ( containerPath . hashCode ( ) & ) % length ; String currentContainerPath ; while ( ( currentContainerPath = this . containerPaths [ index ] ) != null ) { if ( currentContainerPath . equals ( containerPath ) ) { String currentRelativePath = this . relativePaths [ index ] ; if ( encloses ( currentRelativePath , relativePath , index ) ) return index ; } if ( ++ index == length ) { index = ; } } return - ; } public void processDelta ( IRubyElementDelta delta , int eventType ) { switch ( delta . getKind ( ) ) { case IRubyElementDelta . CHANGED : IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { IRubyElementDelta child = children [ i ] ; this . processDelta ( child , eventType ) ; } break ; case IRubyElementDelta . REMOVED : IRubyElement element = delta . getElement ( ) ; if ( this . encloses ( element ) ) { if ( this . elements != null ) { this . elements . remove ( element ) ; } IPath path = null ; switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_PROJECT : path = ( ( IRubyProject ) element ) . getProject ( ) . getFullPath ( ) ; case IRubyElement . SOURCE_FOLDER_ROOT : if ( path == null ) { path = ( ( ISourceFolderRoot ) element ) . getPath ( ) ; } int toRemove = - ; for ( int i = ; i < this . pathsCount ; i ++ ) { if ( this . relativePaths [ i ] . equals ( path ) ) { toRemove = i ; break ; } } if ( toRemove != - ) { this . relativePaths [ toRemove ] = null ; rehash ( ) ; } } } break ; } } } package org . rubypeople . rdt . internal . core . search ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . SearchDocument ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . Util ; public class RubySearchDocument extends SearchDocument { private IFile file ; protected char [ ] charContents ; public RubySearchDocument ( String documentPath , SearchParticipant participant ) { super ( documentPath , participant ) ; } public RubySearchDocument ( String documentPath , char [ ] contents , SearchParticipant participant ) { this ( documentPath , participant ) ; this . charContents = contents ; } @ Override public char [ ] getCharContents ( ) { if ( this . charContents != null ) return this . charContents ; try { return Util . getResourceContentsAsCharArray ( getFile ( ) ) ; } catch ( RubyModelException e ) { if ( BasicSearchEngine . VERBOSE || JobManager . VERBOSE ) { e . printStackTrace ( ) ; } return null ; } } private IFile getFile ( ) { if ( this . file == null ) this . file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( new Path ( getPath ( ) ) ) ; return this . file ; } } package org . rubypeople . rdt . internal . core . search ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchDocument ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . core . search . SearchRequestor ; import org . rubypeople . rdt . core . search . TypeNameRequestor ; import org . rubypeople . rdt . internal . core . DefaultWorkingCopyOwner ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . search . indexing . IndexManager ; import org . rubypeople . rdt . internal . core . search . matching . MatchLocator ; import org . rubypeople . rdt . internal . core . search . matching . RubySearchPattern ; import org . rubypeople . rdt . internal . core . search . matching . TypeDeclarationPattern ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class BasicSearchEngine { public static final int CLASS_DECL = ; public static final int MODULE_DECL = ; public static final boolean VERBOSE = false ; private IRubyScript [ ] workingCopies ; private WorkingCopyOwner workingCopyOwner ; public BasicSearchEngine ( ) { } public BasicSearchEngine ( WorkingCopyOwner workingCopyOwner ) { this . workingCopyOwner = workingCopyOwner ; } public void search ( SearchPattern pattern , SearchParticipant [ ] participants , IRubySearchScope scope , SearchRequestor requestor , IProgressMonitor monitor ) throws CoreException { if ( VERBOSE ) { Util . verbose ( "" ) ; } findMatches ( pattern , participants , scope , requestor , monitor ) ; } public static IRubySearchScope createRubySearchScope ( IRubyElement [ ] elements ) { return createRubySearchScope ( elements , true ) ; } public static IRubySearchScope createRubySearchScope ( IRubyElement [ ] elements , boolean includeReferencedProjects ) { int includeMask = IRubySearchScope . SOURCES | IRubySearchScope . APPLICATION_LIBRARIES | IRubySearchScope . SYSTEM_LIBRARIES ; if ( includeReferencedProjects ) { includeMask |= IRubySearchScope . REFERENCED_PROJECTS ; } return createRubySearchScope ( elements , includeMask ) ; } public static IRubySearchScope createRubySearchScope ( IRubyElement [ ] elements , int includeMask ) { RubySearchScope scope = new RubySearchScope ( ) ; HashSet visitedProjects = new HashSet ( ) ; for ( int i = , length = elements . length ; i < length ; i ++ ) { IRubyElement element = elements [ i ] ; if ( element != null ) { try { if ( element instanceof RubyProject ) { scope . add ( ( RubyProject ) element , includeMask , visitedProjects ) ; } else { scope . add ( element ) ; } } catch ( RubyModelException e ) { } } } return scope ; } void findMatches ( SearchPattern pattern , SearchParticipant [ ] participants , IRubySearchScope scope , SearchRequestor requestor , IProgressMonitor monitor ) throws CoreException { if ( monitor != null && monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; try { if ( monitor != null ) monitor . beginTask ( Messages . engine_searching , ) ; if ( VERBOSE ) { Util . verbose ( "" + pattern . toString ( ) ) ; Util . verbose ( scope . toString ( ) ) ; } if ( participants == null ) { if ( VERBOSE ) Util . verbose ( "" ) ; return ; } IndexManager indexManager = RubyModelManager . getRubyModelManager ( ) . getIndexManager ( ) ; requestor . beginReporting ( ) ; for ( int i = , l = participants . length ; i < l ; i ++ ) { if ( monitor != null && monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; SearchParticipant participant = participants [ i ] ; SubProgressMonitor subMonitor = monitor == null ? null : new SubProgressMonitor ( monitor , ) ; if ( subMonitor != null ) subMonitor . beginTask ( "" , ) ; try { if ( subMonitor != null ) subMonitor . subTask ( Messages . bind ( Messages . engine_searching_indexing , new String [ ] { participant . getDescription ( ) } ) ) ; participant . beginSearching ( ) ; requestor . enterParticipant ( participant ) ; PathCollector pathCollector = new PathCollector ( ) ; indexManager . performConcurrentJob ( new PatternSearchJob ( pattern , participant , scope , pathCollector ) , IRubySearchConstants . WAIT_UNTIL_READY_TO_SEARCH , subMonitor ) ; if ( monitor != null && monitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; if ( subMonitor != null ) subMonitor . subTask ( Messages . bind ( Messages . engine_searching_matching , new String [ ] { participant . getDescription ( ) } ) ) ; String [ ] indexMatchPaths = pathCollector . getPaths ( ) ; if ( indexMatchPaths != null ) { pathCollector = null ; int indexMatchLength = indexMatchPaths . length ; SearchDocument [ ] indexMatches = new SearchDocument [ indexMatchLength ] ; for ( int j = ; j < indexMatchLength ; j ++ ) { indexMatches [ j ] = participant . getDocument ( indexMatchPaths [ j ] ) ; } SearchDocument [ ] matches = MatchLocator . addWorkingCopies ( pattern , indexMatches , getWorkingCopies ( ) , participant ) ; participant . locateMatches ( matches , pattern , scope , requestor , subMonitor ) ; } } finally { requestor . exitParticipant ( participant ) ; participant . doneSearching ( ) ; } } } finally { requestor . endReporting ( ) ; if ( monitor != null ) monitor . done ( ) ; } } private IRubyScript [ ] getWorkingCopies ( ) { IRubyScript [ ] copies ; if ( this . workingCopies != null ) { if ( this . workingCopyOwner == null ) { copies = RubyModelManager . getRubyModelManager ( ) . getWorkingCopies ( DefaultWorkingCopyOwner . PRIMARY , false ) ; if ( copies == null ) { copies = this . workingCopies ; } else { HashMap pathToCUs = new HashMap ( ) ; for ( int i = , length = copies . length ; i < length ; i ++ ) { IRubyScript unit = copies [ i ] ; pathToCUs . put ( unit . getPath ( ) , unit ) ; } for ( int i = , length = this . workingCopies . length ; i < length ; i ++ ) { IRubyScript unit = this . workingCopies [ i ] ; pathToCUs . put ( unit . getPath ( ) , unit ) ; } int length = pathToCUs . size ( ) ; copies = new IRubyScript [ length ] ; pathToCUs . values ( ) . toArray ( copies ) ; } } else { copies = this . workingCopies ; } } else if ( this . workingCopyOwner != null ) { copies = RubyModelManager . getRubyModelManager ( ) . getWorkingCopies ( this . workingCopyOwner , true ) ; } else { copies = RubyModelManager . getRubyModelManager ( ) . getWorkingCopies ( DefaultWorkingCopyOwner . PRIMARY , false ) ; } if ( copies == null ) return null ; IRubyScript [ ] result = null ; int length = copies . length ; int index = ; for ( int i = ; i < length ; i ++ ) { RubyScript copy = ( RubyScript ) copies [ i ] ; try { if ( ! copy . isPrimary ( ) || copy . hasUnsavedChanges ( ) || copy . hasResourceChanged ( ) ) { if ( result == null ) { result = new IRubyScript [ length ] ; } result [ index ++ ] = copy ; } } catch ( RubyModelException e ) { } } if ( index != length && result != null ) { System . arraycopy ( result , , result = new IRubyScript [ index ] , , index ) ; } return result ; } public static SearchParticipant getDefaultSearchParticipant ( ) { return new RubySearchParticipant ( ) ; } public static IRubySearchScope createWorkspaceScope ( ) { return RubyModelManager . getRubyModelManager ( ) . getWorkspaceScope ( ) ; } public static Collection < IType > findType ( String simpleTypeName ) { SearchPattern pattern = SearchPattern . createPattern ( IRubyElement . TYPE , "" + simpleTypeName + "" , IRubySearchConstants . DECLARATIONS , SearchPattern . R_PATTERN_MATCH ) ; SearchParticipant [ ] participants = new SearchParticipant [ ] { getDefaultSearchParticipant ( ) } ; IRubySearchScope scope = createWorkspaceScope ( ) ; TypeRequestor requestor = new TypeRequestor ( ) ; try { new BasicSearchEngine ( ) . search ( pattern , participants , scope , requestor , null ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } List < IType > types = new ArrayList < IType > ( ) ; List < IType > matches = requestor . getTypes ( ) ; for ( IType type : matches ) { if ( Util . getSimpleName ( type . getElementName ( ) ) . equals ( simpleTypeName ) ) types . add ( type ) ; } return types ; } private static class TypeRequestor extends SearchRequestor { private List < IType > types = new ArrayList < IType > ( ) ; @ Override public void acceptSearchMatch ( SearchMatch match ) throws CoreException { Object element = match . getElement ( ) ; types . add ( ( IType ) element ) ; } public List < IType > getTypes ( ) { return types ; } } public void searchAllTypeNames ( final char [ ] namespace , final char [ ] typeName , final int matchRule , int searchFor , IRubySearchScope scope , final TypeNameRequestor nameRequestor , int waitingPolicy , IProgressMonitor progressMonitor ) throws RubyModelException { if ( VERBOSE ) { Util . verbose ( "" ) ; Util . verbose ( "" + ( namespace == null ? "" : new String ( namespace ) ) ) ; Util . verbose ( "" + ( typeName == null ? "" : new String ( typeName ) ) ) ; Util . verbose ( "" + getMatchRuleString ( matchRule ) ) ; Util . verbose ( "" + searchFor ) ; Util . verbose ( "" + scope ) ; } if ( namespace == null || namespace . length == ) { if ( typeName != null && typeName . length == ) { if ( VERBOSE ) { Util . verbose ( "" ) ; } return ; } } IndexManager indexManager = RubyModelManager . getRubyModelManager ( ) . getIndexManager ( ) ; final char typeSuffix ; switch ( searchFor ) { case IRubySearchConstants . CLASS : typeSuffix = IIndexConstants . CLASS_SUFFIX ; break ; case IRubySearchConstants . MODULE : typeSuffix = IIndexConstants . MODULE_SUFFIX ; break ; default : typeSuffix = IIndexConstants . TYPE_SUFFIX ; break ; } final TypeDeclarationPattern pattern = new TypeDeclarationPattern ( null , getEnclosingTypeNames ( namespace ) , typeName , typeSuffix , matchRule ) ; final HashSet < String > workingCopyPaths = new HashSet < String > ( ) ; String workingCopyPath = null ; IRubyScript [ ] copies = getWorkingCopies ( ) ; final int copiesLength = copies == null ? : copies . length ; if ( copies != null ) { if ( copiesLength == ) { workingCopyPath = copies [ ] . getPath ( ) . toString ( ) ; } else { for ( int i = ; i < copiesLength ; i ++ ) { IRubyScript workingCopy = copies [ i ] ; workingCopyPaths . add ( workingCopy . getPath ( ) . toString ( ) ) ; } } } final String singleWkcpPath = workingCopyPath ; IndexQueryRequestor searchRequestor = new IndexQueryRequestor ( ) { public boolean acceptIndexMatch ( String documentPath , SearchPattern indexRecord , SearchParticipant participant ) { TypeDeclarationPattern record = ( TypeDeclarationPattern ) indexRecord ; if ( record . enclosingTypeNames == IIndexConstants . ONE_ZERO_CHAR ) { return true ; } switch ( copiesLength ) { case : break ; case : if ( singleWkcpPath . equals ( documentPath ) ) { return true ; } break ; default : if ( workingCopyPaths . contains ( documentPath ) ) { return true ; } break ; } if ( match ( record . typeSuffix , record . modifiers ) ) { nameRequestor . acceptType ( record . typeSuffix == IIndexConstants . MODULE_SUFFIX , record . pkg , record . simpleName , record . enclosingTypeNames , documentPath ) ; } return true ; } } ; try { if ( progressMonitor != null ) { progressMonitor . beginTask ( Messages . engine_searching , ) ; } indexManager . performConcurrentJob ( new PatternSearchJob ( pattern , getDefaultSearchParticipant ( ) , scope , searchRequestor ) , waitingPolicy , progressMonitor == null ? null : new SubProgressMonitor ( progressMonitor , ) ) ; if ( copies != null ) { for ( int i = ; i < copiesLength ; i ++ ) { IRubyScript workingCopy = copies [ i ] ; if ( ! scope . encloses ( workingCopy ) ) continue ; final String path = workingCopy . getPath ( ) . toString ( ) ; if ( workingCopy . isConsistent ( ) ) { char [ ] packageDeclaration = CharOperation . NO_CHAR ; IType [ ] allTypes = workingCopy . getAllTypes ( ) ; for ( int j = , allTypesLength = allTypes . length ; j < allTypesLength ; j ++ ) { IType type = allTypes [ j ] ; IRubyElement parent = type . getParent ( ) ; char [ ] [ ] enclosingTypeNames ; if ( parent instanceof IType ) { char [ ] parentQualifiedName = ( ( IType ) parent ) . getTypeQualifiedName ( "" ) . toCharArray ( ) ; enclosingTypeNames = CharOperation . splitOn ( "" , parentQualifiedName ) ; } else { enclosingTypeNames = CharOperation . NO_CHAR_CHAR ; } char [ ] simpleName = type . getElementName ( ) . toCharArray ( ) ; int kind ; if ( type . isClass ( ) ) { kind = CLASS_DECL ; } else { kind = MODULE_DECL ; } if ( match ( typeSuffix , namespace , typeName , matchRule , kind , squish ( enclosingTypeNames ) , simpleName ) ) { nameRequestor . acceptType ( type . isModule ( ) , packageDeclaration , simpleName , enclosingTypeNames , path ) ; } } } else { } } } } finally { if ( progressMonitor != null ) { progressMonitor . done ( ) ; } } } private char [ ] squish ( char [ ] [ ] enclosingTypeNames ) { StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < enclosingTypeNames . length ; i ++ ) { if ( i != ) buffer . append ( "" ) ; buffer . append ( enclosingTypeNames [ i ] ) ; } return buffer . toString ( ) . toCharArray ( ) ; } private char [ ] [ ] getEnclosingTypeNames ( char [ ] packageName ) { if ( packageName == null || packageName . length == ) return null ; String raw = new String ( packageName ) ; String [ ] parts = Util . getTypeNameParts ( raw ) ; char [ ] [ ] enclosing = new char [ parts . length ] [ ] ; for ( int i = ; i < parts . length ; i ++ ) { enclosing [ i ] = parts [ i ] . toCharArray ( ) ; } return enclosing ; } boolean match ( char patternTypeSuffix , int modifiers ) { switch ( patternTypeSuffix ) { case IIndexConstants . CLASS_SUFFIX : return ( modifiers & ( Flags . AccModule ) ) == ; case IIndexConstants . TYPE_SUFFIX : return true ; case IIndexConstants . MODULE_SUFFIX : return ( modifiers & Flags . AccModule ) != ; } return true ; } boolean match ( char patternTypeSuffix , char [ ] patternPkg , char [ ] patternTypeName , int matchRule , int typeKind , char [ ] pkg , char [ ] typeName ) { switch ( patternTypeSuffix ) { case IIndexConstants . CLASS_SUFFIX : if ( typeKind != CLASS_DECL ) return false ; break ; case IIndexConstants . TYPE_SUFFIX : if ( typeKind != CLASS_DECL && typeKind != MODULE_DECL ) return false ; break ; case IIndexConstants . MODULE_SUFFIX : if ( typeKind != MODULE_DECL ) return false ; break ; } if ( patternPkg != null ) { if ( ! doMatch ( patternPkg , pkg , matchRule ) ) return false ; } if ( patternTypeName != null ) { if ( ! doMatch ( patternTypeName , typeName , matchRule ) ) return false ; } return true ; } private boolean isCaseSensitive ( int matchRule ) { return ( matchRule & SearchPattern . R_CASE_SENSITIVE ) != ; } private boolean doMatch ( char [ ] patternTypeName , char [ ] typeName , int matchRule ) { boolean isCaseSensitive = isCaseSensitive ( matchRule ) ; boolean isCamelCase = ( matchRule & SearchPattern . R_CAMELCASE_MATCH ) != ; int matchMode = matchRule & RubySearchPattern . MATCH_MODE_MASK ; if ( ! isCaseSensitive && ! isCamelCase ) { patternTypeName = CharOperation . toLowerCase ( patternTypeName ) ; } boolean matchFirstChar = ! isCaseSensitive || patternTypeName [ ] == typeName [ ] ; if ( isCamelCase && matchFirstChar && CharOperation . camelCaseMatch ( patternTypeName , typeName ) ) { return true ; } switch ( matchMode ) { case SearchPattern . R_EXACT_MATCH : if ( ! isCamelCase ) { return matchFirstChar && CharOperation . equals ( patternTypeName , typeName , isCaseSensitive ) ; } case SearchPattern . R_PREFIX_MATCH : return matchFirstChar && CharOperation . prefixEquals ( patternTypeName , typeName , isCaseSensitive ) ; case SearchPattern . R_PATTERN_MATCH : return CharOperation . match ( patternTypeName , typeName , isCaseSensitive ) ; case SearchPattern . R_REGEXP_MATCH : return true ; } return true ; } public static String getMatchRuleString ( final int matchRule ) { if ( matchRule == ) { return "" ; } StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i <= ; i ++ ) { int bit = matchRule & ( << ( i - ) ) ; if ( bit != && buffer . length ( ) > ) buffer . append ( "" ) ; switch ( bit ) { case SearchPattern . R_PREFIX_MATCH : buffer . append ( "" ) ; break ; case SearchPattern . R_CASE_SENSITIVE : buffer . append ( "" ) ; break ; case SearchPattern . R_EQUIVALENT_MATCH : buffer . append ( "" ) ; break ; case SearchPattern . R_ERASURE_MATCH : buffer . append ( "" ) ; break ; case SearchPattern . R_FULL_MATCH : buffer . append ( "" ) ; break ; case SearchPattern . R_PATTERN_MATCH : buffer . append ( "" ) ; break ; case SearchPattern . R_REGEXP_MATCH : buffer . append ( "" ) ; break ; case SearchPattern . R_CAMELCASE_MATCH : buffer . append ( "" ) ; break ; } } return buffer . toString ( ) ; } public static IRubySearchScope createHierarchyScope ( IType type ) throws RubyModelException { return createHierarchyScope ( type , DefaultWorkingCopyOwner . PRIMARY ) ; } public static IRubySearchScope createHierarchyScope ( IType type , WorkingCopyOwner owner ) throws RubyModelException { return new HierarchyScope ( type , owner ) ; } } package org . rubypeople . rdt . internal . core . search ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . Openable ; import org . rubypeople . rdt . internal . core . RubyModel ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . SourceFolderRoot ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . HashtableOfArrayToObject ; import org . rubypeople . rdt . internal . core . util . Util ; public class HandleFactory { private String lastSrcFolderRootPath ; private ISourceFolderRoot lastSrcFolderRoot ; private HashtableOfArrayToObject folderHandles ; private RubyModel rubyModel ; public HandleFactory ( ) { this . rubyModel = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; } private ISourceFolderRoot getSourceFolderRoot ( String pathString ) { IPath path = new Path ( pathString ) ; IProject [ ] projects = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; for ( int i = , max = projects . length ; i < max ; i ++ ) { try { IProject project = projects [ i ] ; if ( ! project . isAccessible ( ) || ! project . hasNature ( RubyCore . NATURE_ID ) ) continue ; IRubyProject rubyProject = this . rubyModel . getRubyProject ( project ) ; ISourceFolderRoot [ ] roots = rubyProject . getSourceFolderRoots ( ) ; for ( int j = , rootCount = roots . length ; j < rootCount ; j ++ ) { SourceFolderRoot root = ( SourceFolderRoot ) roots [ j ] ; if ( root . getPath ( ) . isPrefixOf ( path ) && ! Util . isExcluded ( path , root . fullInclusionPatternChars ( ) , root . fullExclusionPatternChars ( ) , false ) ) { return root ; } } } catch ( CoreException e ) { } } return null ; } public Openable createOpenable ( String resourcePath ) { int rootPathLength = - ; if ( this . lastSrcFolderRootPath == null || ! ( resourcePath . startsWith ( this . lastSrcFolderRootPath ) && ( rootPathLength = this . lastSrcFolderRootPath . length ( ) ) > && resourcePath . charAt ( rootPathLength ) == '' ) ) { ISourceFolderRoot root = this . getSourceFolderRoot ( resourcePath ) ; if ( root == null ) return null ; this . lastSrcFolderRoot = root ; this . lastSrcFolderRootPath = this . lastSrcFolderRoot . getPath ( ) . toString ( ) ; this . folderHandles = new HashtableOfArrayToObject ( ) ; } resourcePath = resourcePath . substring ( this . lastSrcFolderRootPath . length ( ) + ) ; String [ ] simpleNames = new Path ( resourcePath ) . segments ( ) ; String [ ] pkgName ; int length = simpleNames . length - ; if ( length > ) { pkgName = new String [ length ] ; System . arraycopy ( simpleNames , , pkgName , , length ) ; } else { pkgName = CharOperation . NO_STRINGS ; } ISourceFolder pkgFragment = ( ISourceFolder ) this . folderHandles . get ( pkgName ) ; if ( pkgFragment == null ) { pkgFragment = ( ( SourceFolderRoot ) this . lastSrcFolderRoot ) . getSourceFolder ( pkgName ) ; this . folderHandles . put ( pkgName , pkgFragment ) ; } String simpleName = simpleNames [ length ] ; if ( org . rubypeople . rdt . internal . core . util . Util . isRubyOrERBLikeFileName ( simpleName ) ) { IRubyScript unit = pkgFragment . getRubyScript ( simpleName ) ; return ( Openable ) unit ; } return null ; } } package org . rubypeople . rdt . internal . core . search ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; public abstract class IndexQueryRequestor { public abstract boolean acceptIndexMatch ( String documentPath , SearchPattern indexRecord , SearchParticipant participant ) ; } package org . rubypeople . rdt . internal . core . search ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . internal . core . util . Util ; public class ERBSearchDocument extends RubySearchDocument { private char [ ] fContents ; public ERBSearchDocument ( String absolutePath , char [ ] contents , SearchParticipant participant ) { super ( absolutePath , contents , participant ) ; } public ERBSearchDocument ( String documentPath , SearchParticipant participant ) { super ( documentPath , participant ) ; } @ Override public char [ ] getCharContents ( ) { if ( fContents == null ) { char [ ] contents = super . getCharContents ( ) ; fContents = Util . replaceNonRubyCodeWithWhitespace ( new String ( contents ) ) ; } return fContents ; } } package org . rubypeople . rdt . internal . core . search ; import java . io . IOException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . indexing . IndexManager ; import org . rubypeople . rdt . internal . core . search . indexing . ReadWriteMonitor ; import org . rubypeople . rdt . internal . core . search . matching . MatchLocator ; import org . rubypeople . rdt . internal . core . search . processing . IJob ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . Util ; public class PatternSearchJob implements IJob { protected SearchPattern pattern ; protected IRubySearchScope scope ; protected SearchParticipant participant ; protected IndexQueryRequestor requestor ; protected boolean areIndexesReady ; protected long executionTime = ; public PatternSearchJob ( SearchPattern pattern , SearchParticipant participant , IRubySearchScope scope , IndexQueryRequestor requestor ) { this . pattern = pattern ; this . participant = participant ; this . scope = scope ; this . requestor = requestor ; } public boolean belongsTo ( String jobFamily ) { return true ; } public void cancel ( ) { } public void ensureReadyToRun ( ) { if ( ! this . areIndexesReady ) getIndexes ( null ) ; } public boolean execute ( IProgressMonitor progressMonitor ) { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; boolean isComplete = COMPLETE ; executionTime = ; Index [ ] indexes = getIndexes ( progressMonitor ) ; try { int max = indexes . length ; if ( progressMonitor != null ) progressMonitor . beginTask ( "" , max ) ; for ( int i = ; i < max ; i ++ ) { isComplete &= search ( indexes [ i ] , progressMonitor ) ; if ( progressMonitor != null ) { if ( progressMonitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; progressMonitor . worked ( ) ; } } if ( JobManager . VERBOSE ) Util . verbose ( "" + executionTime + "" + this ) ; return isComplete ; } finally { if ( progressMonitor != null ) progressMonitor . done ( ) ; } } public Index [ ] getIndexes ( IProgressMonitor progressMonitor ) { IPath [ ] indexLocations = this . participant . selectIndexes ( this . pattern , this . scope ) ; int length = indexLocations . length ; Index [ ] indexes = new Index [ length ] ; int count = ; IndexManager indexManager = RubyModelManager . getRubyModelManager ( ) . getIndexManager ( ) ; for ( int i = ; i < length ; i ++ ) { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; IPath indexLocation = indexLocations [ i ] ; Index index = indexManager . getIndex ( indexLocation ) ; if ( index == null ) { IPath containerPath = ( IPath ) indexManager . indexLocations . keyForValue ( indexLocation ) ; if ( containerPath != null ) index = indexManager . getIndex ( containerPath , indexLocation , true , false ) ; } if ( index != null ) indexes [ count ++ ] = index ; } if ( count == length ) this . areIndexesReady = true ; else System . arraycopy ( indexes , , indexes = new Index [ count ] , , count ) ; return indexes ; } public boolean search ( Index index , IProgressMonitor progressMonitor ) { if ( index == null ) return COMPLETE ; if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) throw new OperationCanceledException ( ) ; ReadWriteMonitor monitor = index . monitor ; if ( monitor == null ) return COMPLETE ; try { monitor . enterRead ( ) ; long start = System . currentTimeMillis ( ) ; MatchLocator . findIndexMatches ( this . pattern , index , requestor , this . participant , this . scope , progressMonitor ) ; executionTime += System . currentTimeMillis ( ) - start ; return COMPLETE ; } catch ( IOException e ) { if ( e instanceof java . io . EOFException ) e . printStackTrace ( ) ; return FAILED ; } finally { monitor . exitRead ( ) ; } } public String toString ( ) { return "" + pattern . toString ( ) ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import org . rubypeople . rdt . internal . core . SourceElementParser ; import org . rubypeople . rdt . internal . core . index . Index ; public class InternalSearchDocument { protected Index index ; private String containerRelativePath ; public SourceElementParser parser ; public void addIndexEntry ( char [ ] category , char [ ] key ) { if ( this . index != null ) { index . addIndexEntry ( category , key , getContainerRelativePath ( ) ) ; } } private String getContainerRelativePath ( ) { if ( this . containerRelativePath == null ) this . containerRelativePath = this . index . containerRelativePath ( getPath ( ) ) ; return this . containerRelativePath ; } public void removeAllIndexEntries ( ) { if ( this . index != null ) index . remove ( getContainerRelativePath ( ) ) ; } public String getPath ( ) { return null ; } } package org . rubypeople . rdt . internal . core . search . indexing ; public interface IIndexConstants { char [ ] REF = "" . toCharArray ( ) ; char [ ] METHOD_REF = "" . toCharArray ( ) ; char [ ] CONSTRUCTOR_REF = "" . toCharArray ( ) ; char [ ] SUPER_REF = "" . toCharArray ( ) ; char [ ] TYPE_DECL = "" . toCharArray ( ) ; char [ ] METHOD_DECL = "" . toCharArray ( ) ; char [ ] CONSTRUCTOR_DECL = "" . toCharArray ( ) ; char [ ] FIELD_DECL = "" . toCharArray ( ) ; char [ ] OBJECT = "" . toCharArray ( ) ; char [ ] [ ] COUNTS = new char [ ] [ ] { new char [ ] { '' , '' } , new char [ ] { '' , '' } , new char [ ] { '' , '' } , new char [ ] { '' , '' } , new char [ ] { '' , '' } , new char [ ] { '' , '' } , new char [ ] { '' , '' } , new char [ ] { '' , '' } , new char [ ] { '' , '' } , new char [ ] { '' , '' } } ; char CLASS_SUFFIX = '' ; char MODULE_SUFFIX = '' ; char TYPE_SUFFIX = ; char SEPARATOR = '' ; char SECONDARY_SUFFIX = '' ; char [ ] ONE_STAR = new char [ ] { '' } ; char [ ] [ ] ONE_STAR_CHAR = new char [ ] [ ] { ONE_STAR } ; char ZERO_CHAR = '' ; char [ ] ONE_ZERO = new char [ ] { ZERO_CHAR } ; char [ ] [ ] ONE_ZERO_CHAR = new char [ ] [ ] { ONE_ZERO } ; int SCRIPT_REF_PATTERN = ; int TYPE_REF_PATTERN = ; int TYPE_DECL_PATTERN = ; int SUPER_REF_PATTERN = ; int CONSTRUCTOR_PATTERN = ; int FIELD_PATTERN = ; int METHOD_PATTERN = ; int OR_PATTERN = ; int LOCAL_VAR_PATTERN = ; } package org . rubypeople . rdt . internal . core . search . indexing ; import java . io . IOException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . Util ; public class SaveIndex extends IndexRequest { public SaveIndex ( IPath containerPath , IndexManager manager ) { super ( containerPath , manager ) ; } public boolean execute ( IProgressMonitor progressMonitor ) { if ( this . isCancelled || progressMonitor != null && progressMonitor . isCanceled ( ) ) return true ; Index index = this . manager . getIndex ( this . containerPath , true , false ) ; if ( index == null ) return true ; ReadWriteMonitor monitor = index . monitor ; if ( monitor == null ) return true ; try { monitor . enterWrite ( ) ; this . manager . saveIndex ( index ) ; } catch ( IOException e ) { if ( JobManager . VERBOSE ) { Util . verbose ( "" + this . containerPath + "" , System . err ) ; e . printStackTrace ( ) ; } return false ; } finally { monitor . exitWrite ( ) ; } return true ; } public String toString ( ) { return "" + this . containerPath ; } } package org . rubypeople . rdt . internal . core . search . indexing ; public class ReadWriteMonitor { private int status = ; public synchronized void enterRead ( ) { while ( status < ) { try { wait ( ) ; } catch ( InterruptedException e ) { } } status ++ ; } public synchronized void enterWrite ( ) { while ( status != ) { try { wait ( ) ; } catch ( InterruptedException e ) { } } status -- ; } public synchronized void exitRead ( ) { if ( -- status == ) notifyAll ( ) ; } public synchronized void exitWrite ( ) { if ( ++ status == ) notifyAll ( ) ; } public synchronized boolean exitReadEnterWrite ( ) { if ( status != ) return false ; status = - ; return true ; } public synchronized void exitWriteEnterRead ( ) { this . exitWrite ( ) ; this . enterRead ( ) ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; if ( status == ) { buffer . append ( "" ) ; } else if ( status < ) { buffer . append ( "" ) ; } else if ( status > ) { buffer . append ( "" ) ; } buffer . append ( "" ) ; buffer . append ( this . status ) ; buffer . append ( "" ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . search . SearchDocument ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . SourceElementParser ; import org . rubypeople . rdt . internal . core . search . matching . ConstructorPattern ; import org . rubypeople . rdt . internal . core . search . matching . FieldPattern ; import org . rubypeople . rdt . internal . core . search . matching . MethodPattern ; import org . rubypeople . rdt . internal . core . search . matching . SuperTypeReferencePattern ; import org . rubypeople . rdt . internal . core . search . matching . TypeDeclarationPattern ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class SourceIndexer implements IIndexConstants { private SearchDocument document ; public SourceIndexer ( SearchDocument document ) { this . document = document ; } public void indexDocument ( ) { SourceIndexerRequestor requestor = new SourceIndexerRequestor ( this ) ; String documentPath = this . document . getPath ( ) ; SourceElementParser parser = ( ( InternalSearchDocument ) this . document ) . parser ; if ( parser == null ) { IPath path = new Path ( documentPath ) ; IProject project = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( path . segment ( ) ) ; parser = RubyModelManager . getRubyModelManager ( ) . getIndexManager ( ) . getSourceElementParser ( RubyCore . create ( project ) , requestor ) ; } else { parser . requestor = requestor ; } char [ ] source = null ; char [ ] name = null ; try { source = document . getCharContents ( ) ; name = documentPath . toCharArray ( ) ; } catch ( Exception e ) { } if ( source == null || name == null ) return ; try { parser . parse ( source , name ) ; } catch ( Exception e ) { if ( JobManager . VERBOSE ) { e . printStackTrace ( ) ; } } } public void addClassDeclaration ( int modifiers , char [ ] packageName , char [ ] name , char [ ] [ ] enclosingTypeNames , char [ ] superclass , char [ ] [ ] superinterfaces , boolean secondary ) { char [ ] indexKey = TypeDeclarationPattern . createIndexKey ( modifiers , name , packageName , enclosingTypeNames , secondary ) ; addIndexEntry ( TYPE_DECL , indexKey ) ; if ( superclass != null && ! superclass . equals ( "" ) ) { addTypeReference ( superclass ) ; } addIndexEntry ( SUPER_REF , SuperTypeReferencePattern . createIndexKey ( modifiers , packageName , name , enclosingTypeNames , CLASS_SUFFIX , superclass , CLASS_SUFFIX ) ) ; if ( superinterfaces != null ) { for ( int i = , max = superinterfaces . length ; i < max ; i ++ ) { char [ ] superinterface = superinterfaces [ i ] ; addTypeReference ( superinterface ) ; addIncludedModuleReference ( modifiers , packageName , name , enclosingTypeNames , superinterface ) ; } } } public void addIncludedModuleReference ( int modifiers , char [ ] packageName , char [ ] name , char [ ] [ ] enclosingTypeNames , char [ ] superinterface ) { addIndexEntry ( SUPER_REF , SuperTypeReferencePattern . createIndexKey ( modifiers , packageName , name , enclosingTypeNames , CLASS_SUFFIX , superinterface , MODULE_SUFFIX ) ) ; } public void addFieldDeclaration ( char [ ] typeName , char [ ] fieldName ) { addIndexEntry ( FIELD_DECL , FieldPattern . createIndexKey ( fieldName ) ) ; if ( typeName != null ) addTypeReference ( typeName ) ; } public void addFieldReference ( char [ ] fieldName ) { addNameReference ( fieldName ) ; } public void addMethodDeclaration ( char [ ] methodName , int arity ) { addIndexEntry ( METHOD_DECL , MethodPattern . createIndexKey ( methodName , arity ) ) ; } public void addMethodReference ( char [ ] methodName , int argCount ) { addIndexEntry ( METHOD_REF , MethodPattern . createIndexKey ( methodName , argCount ) ) ; } public void addNameReference ( char [ ] name ) { addIndexEntry ( REF , name ) ; } public void addTypeReference ( char [ ] typeName ) { addNameReference ( CharOperation . lastSegment ( typeName , "" ) ) ; } protected void addIndexEntry ( char [ ] category , char [ ] key ) { this . document . addIndexEntry ( category , key ) ; } public void addConstructorDeclaration ( char [ ] typeName , int argCount ) { addIndexEntry ( CONSTRUCTOR_DECL , ConstructorPattern . createIndexKey ( CharOperation . lastSegment ( typeName , "" ) , argCount ) ) ; } public void addConstructorReference ( char [ ] typeName , int argCount ) { char [ ] simpleTypeName = CharOperation . lastSegment ( typeName , "" ) ; addTypeReference ( simpleTypeName ) ; addIndexEntry ( CONSTRUCTOR_REF , ConstructorPattern . createIndexKey ( simpleTypeName , argCount ) ) ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Map ; import java . util . zip . CRC32 ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchDocument ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor ; import org . rubypeople . rdt . internal . compiler . util . SimpleLookupTable ; import org . rubypeople . rdt . internal . compiler . util . SimpleSet ; import org . rubypeople . rdt . internal . core . RubyModel ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . SourceElementParser ; import org . rubypeople . rdt . internal . core . index . DiskIndex ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . BasicSearchEngine ; import org . rubypeople . rdt . internal . core . search . PatternSearchJob ; import org . rubypeople . rdt . internal . core . search . processing . IJob ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class IndexManager extends JobManager { public SimpleLookupTable indexLocations = new SimpleLookupTable ( ) ; private Map < IPath , Index > indexes = new HashMap < IPath , Index > ( ) ; private boolean needToSave = false ; private static final CRC32 checksumCalculator = new CRC32 ( ) ; private IPath rubyPluginLocation = null ; private SimpleLookupTable indexStates = null ; private File savedIndexNamesFile = new File ( getSavedIndexesDirectory ( ) , "" ) ; public static Integer SAVED_STATE = new Integer ( ) ; public static Integer UPDATING_STATE = new Integer ( ) ; public static Integer UNKNOWN_STATE = new Integer ( ) ; public static Integer REBUILDING_STATE = new Integer ( ) ; private IPath getRubyPluginWorkingLocation ( ) { if ( this . rubyPluginLocation != null ) return this . rubyPluginLocation ; IPath stateLocation = RubyCore . getPlugin ( ) . getStateLocation ( ) ; return this . rubyPluginLocation = stateLocation ; } private File getSavedIndexesDirectory ( ) { return new File ( getRubyPluginWorkingLocation ( ) . toOSString ( ) ) ; } public synchronized void jobWasCancelled ( IPath containerPath ) { IPath indexLocation = computeIndexLocation ( containerPath ) ; Index index = getIndex ( indexLocation ) ; if ( index != null ) { index . monitor = null ; this . indexes . remove ( indexLocation ) ; } updateIndexState ( indexLocation , UNKNOWN_STATE ) ; } public IPath computeIndexLocation ( IPath containerPath ) { IPath indexLocation = ( IPath ) this . indexLocations . get ( containerPath ) ; if ( indexLocation == null ) { String pathString = containerPath . toOSString ( ) ; checksumCalculator . reset ( ) ; checksumCalculator . update ( pathString . getBytes ( ) ) ; String fileName = Long . toString ( checksumCalculator . getValue ( ) ) + "" ; if ( VERBOSE ) Util . verbose ( "" + pathString + "" + fileName ) ; indexLocation = ( IPath ) getIndexStates ( ) . getKey ( getRubyPluginWorkingLocation ( ) . append ( fileName ) ) ; this . indexLocations . put ( containerPath , indexLocation ) ; } return indexLocation ; } public synchronized Index getIndex ( IPath indexLocation ) { return ( Index ) this . indexes . get ( indexLocation ) ; } private SimpleLookupTable getIndexStates ( ) { if ( this . indexStates != null ) return this . indexStates ; this . indexStates = new SimpleLookupTable ( ) ; IPath indexesDirectoryPath = getRubyPluginWorkingLocation ( ) ; char [ ] [ ] savedNames = readIndexState ( indexesDirectoryPath . toOSString ( ) ) ; if ( savedNames != null ) { for ( int i = , l = savedNames . length ; i < l ; i ++ ) { char [ ] savedName = savedNames [ i ] ; if ( savedName . length > ) { IPath indexLocation = indexesDirectoryPath . append ( new String ( savedName ) ) ; if ( VERBOSE ) Util . verbose ( "" + indexLocation ) ; this . indexStates . put ( indexLocation , SAVED_STATE ) ; } } } else { deleteIndexFiles ( ) ; } return this . indexStates ; } public void deleteIndexFiles ( ) { this . savedIndexNamesFile . delete ( ) ; deleteIndexFiles ( null ) ; } private void deleteIndexFiles ( SimpleSet pathsToKeep ) { File [ ] indexesFiles = getSavedIndexesDirectory ( ) . listFiles ( ) ; if ( indexesFiles == null ) return ; for ( int i = , l = indexesFiles . length ; i < l ; i ++ ) { String fileName = indexesFiles [ i ] . getAbsolutePath ( ) ; if ( pathsToKeep != null && pathsToKeep . includes ( fileName ) ) continue ; String suffix = "" ; if ( fileName . regionMatches ( true , fileName . length ( ) - suffix . length ( ) , suffix , , suffix . length ( ) ) ) { if ( VERBOSE ) Util . verbose ( "" + indexesFiles [ i ] ) ; indexesFiles [ i ] . delete ( ) ; } } } private synchronized void updateIndexState ( IPath indexLocation , Integer indexState ) { if ( indexLocation . isEmpty ( ) ) throw new IllegalArgumentException ( ) ; getIndexStates ( ) ; if ( indexState != null ) { if ( indexState . equals ( indexStates . get ( indexLocation ) ) ) return ; indexStates . put ( indexLocation , indexState ) ; } else { if ( ! indexStates . containsKey ( indexLocation ) ) return ; indexStates . removeKey ( indexLocation ) ; } writeSavedIndexNamesFile ( ) ; if ( VERBOSE ) { String state = "" ; if ( indexState == SAVED_STATE ) state = "" ; else if ( indexState == UPDATING_STATE ) state = "" ; else if ( indexState == UNKNOWN_STATE ) state = "" ; else if ( indexState == REBUILDING_STATE ) state = "" ; Util . verbose ( "" + state + "" + indexLocation ) ; } } private void writeSavedIndexNamesFile ( ) { BufferedWriter writer = null ; try { writer = new BufferedWriter ( new FileWriter ( savedIndexNamesFile ) ) ; writer . write ( DiskIndex . SIGNATURE ) ; writer . write ( '' ) ; writer . write ( getRubyPluginWorkingLocation ( ) . toOSString ( ) ) ; writer . write ( '' ) ; Object [ ] keys = indexStates . keyTable ; Object [ ] states = indexStates . valueTable ; for ( int i = , l = states . length ; i < l ; i ++ ) { IPath key = ( IPath ) keys [ i ] ; if ( key != null && ! key . isEmpty ( ) && states [ i ] == SAVED_STATE ) { writer . write ( key . lastSegment ( ) ) ; writer . write ( '' ) ; } } } catch ( IOException ignored ) { if ( VERBOSE ) Util . verbose ( "" , System . err ) ; } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( IOException e ) { } } } } private char [ ] [ ] readIndexState ( String dirOSString ) { try { char [ ] savedIndexNames = org . rubypeople . rdt . core . util . Util . getFileCharContent ( savedIndexNamesFile , null ) ; if ( savedIndexNames . length > ) { char [ ] [ ] names = CharOperation . splitOn ( '' , savedIndexNames ) ; if ( names . length > ) { String savedSignature = DiskIndex . SIGNATURE + "" + dirOSString ; if ( savedSignature . equals ( new String ( names [ ] ) ) ) return names ; } } } catch ( IOException ignored ) { if ( VERBOSE ) Util . verbose ( "" ) ; } return null ; } @ Override public String processName ( ) { return Messages . process_name ; } public synchronized void aboutToUpdateIndex ( IPath containerPath , Integer newIndexState ) { IPath indexLocation = computeIndexLocation ( containerPath ) ; Object state = getIndexStates ( ) . get ( indexLocation ) ; Integer currentIndexState = state == null ? UNKNOWN_STATE : ( Integer ) state ; if ( currentIndexState . equals ( REBUILDING_STATE ) ) return ; int compare = newIndexState . compareTo ( currentIndexState ) ; if ( compare > ) { updateIndexState ( indexLocation , newIndexState ) ; } else if ( compare < && this . indexes . get ( indexLocation ) == null ) { rebuildIndex ( indexLocation , containerPath ) ; } } private void rebuildIndex ( IPath indexLocation , IPath containerPath ) { Object target = RubyModel . getTarget ( containerPath , true ) ; if ( target == null ) return ; if ( VERBOSE ) Util . verbose ( "" + indexLocation + "" + containerPath ) ; updateIndexState ( indexLocation , REBUILDING_STATE ) ; IndexRequest request = null ; if ( target instanceof IProject ) { IProject p = ( IProject ) target ; if ( RubyProject . hasRubyNature ( p ) ) request = new IndexAllProject ( p , this ) ; } else if ( target instanceof File ) { request = new AddExternalFolderToIndex ( containerPath , this ) ; } if ( request != null ) request ( request ) ; } public void saveIndex ( Index index ) throws IOException { if ( index . hasChanged ( ) ) { if ( VERBOSE ) Util . verbose ( "" + index . getIndexFile ( ) ) ; index . save ( ) ; } synchronized ( this ) { IPath containerPath = new Path ( index . containerPath ) ; if ( this . jobEnd > this . jobStart ) { for ( int i = this . jobEnd ; i > this . jobStart ; i -- ) { IJob job = this . awaitingJobs [ i ] ; if ( job instanceof IndexRequest ) if ( ( ( IndexRequest ) job ) . containerPath . equals ( containerPath ) ) return ; } } IPath indexLocation = computeIndexLocation ( containerPath ) ; updateIndexState ( indexLocation , SAVED_STATE ) ; } } public synchronized Index getIndexForUpdate ( IPath containerPath , boolean reuseExistingFile , boolean createIfMissing ) { IPath indexLocation = computeIndexLocation ( containerPath ) ; if ( getIndexStates ( ) . get ( indexLocation ) == REBUILDING_STATE ) return getIndex ( containerPath , indexLocation , reuseExistingFile , createIfMissing ) ; return null ; } public synchronized Index getIndex ( IPath containerPath , IPath indexLocation , boolean reuseExistingFile , boolean createIfMissing ) { Index index = getIndex ( indexLocation ) ; if ( index == null ) { Object state = getIndexStates ( ) . get ( indexLocation ) ; Integer currentIndexState = state == null ? UNKNOWN_STATE : ( Integer ) state ; if ( currentIndexState == UNKNOWN_STATE ) { rebuildIndex ( indexLocation , containerPath ) ; return null ; } String containerPathString = containerPath . getDevice ( ) == null ? containerPath . toString ( ) : containerPath . toOSString ( ) ; String indexLocationString = indexLocation . toOSString ( ) ; if ( reuseExistingFile ) { File indexFile = new File ( indexLocationString ) ; if ( indexFile . exists ( ) ) { try { index = new Index ( indexLocationString , containerPathString , true ) ; this . indexes . put ( indexLocation , index ) ; return index ; } catch ( IOException e ) { if ( currentIndexState != REBUILDING_STATE ) { if ( VERBOSE ) Util . verbose ( "" + indexLocationString + "" + containerPathString ) ; rebuildIndex ( indexLocation , containerPath ) ; return null ; } } } if ( currentIndexState == SAVED_STATE ) { rebuildIndex ( indexLocation , containerPath ) ; return null ; } } if ( createIfMissing ) { try { if ( VERBOSE ) Util . verbose ( "" + indexLocationString + "" + containerPathString ) ; index = new Index ( indexLocationString , containerPathString , false ) ; this . indexes . put ( indexLocation , index ) ; return index ; } catch ( IOException e ) { if ( VERBOSE ) Util . verbose ( "" + indexLocationString + "" + containerPathString ) ; return null ; } } } return index ; } public synchronized void removeIndex ( IPath containerPath ) { if ( VERBOSE ) Util . verbose ( "" + containerPath ) ; IPath indexLocation = computeIndexLocation ( containerPath ) ; Index index = getIndex ( indexLocation ) ; File indexFile = null ; if ( index != null ) { index . monitor = null ; indexFile = index . getIndexFile ( ) ; } if ( indexFile == null ) indexFile = new File ( indexLocation . toOSString ( ) ) ; if ( indexFile . exists ( ) ) indexFile . delete ( ) ; this . indexes . remove ( indexLocation ) ; updateIndexState ( indexLocation , null ) ; } public void remove ( String containerRelativePath , IPath indexedContainer ) { request ( new RemoveFromIndex ( containerRelativePath , indexedContainer , this ) ) ; } public synchronized Index getIndex ( IPath containerPath , boolean reuseExistingFile , boolean createIfMissing ) { IPath indexLocation = computeIndexLocation ( containerPath ) ; return getIndex ( containerPath , indexLocation , reuseExistingFile , createIfMissing ) ; } public void addSource ( IFile resource , IPath containerPath , SourceElementParser parser ) { if ( RubyCore . getPlugin ( ) == null ) return ; SearchParticipant participant = BasicSearchEngine . getDefaultSearchParticipant ( ) ; SearchDocument document = participant . getDocument ( resource . getFullPath ( ) . toString ( ) ) ; ( ( InternalSearchDocument ) document ) . parser = parser ; IPath indexLocation = computeIndexLocation ( containerPath ) ; scheduleDocumentIndexing ( document , containerPath , indexLocation , participant ) ; } public void scheduleDocumentIndexing ( final SearchDocument searchDocument , IPath container , final IPath indexLocation , final SearchParticipant searchParticipant ) { request ( new IndexRequest ( container , this ) { public boolean execute ( IProgressMonitor progressMonitor ) { if ( this . isCancelled || progressMonitor != null && progressMonitor . isCanceled ( ) ) return true ; Index index = getIndex ( this . containerPath , indexLocation , true , true ) ; if ( index == null ) return true ; ReadWriteMonitor monitor = index . monitor ; if ( monitor == null ) return true ; try { monitor . enterWrite ( ) ; indexDocument ( searchDocument , searchParticipant , index , indexLocation ) ; } finally { monitor . exitWrite ( ) ; } return true ; } public String toString ( ) { return "" + searchDocument . getPath ( ) ; } } ) ; } public void indexDocument ( SearchDocument searchDocument , SearchParticipant searchParticipant , Index index , IPath indexLocation ) { try { ( ( InternalSearchDocument ) searchDocument ) . index = index ; searchParticipant . indexDocument ( searchDocument , indexLocation ) ; } finally { ( ( InternalSearchDocument ) searchDocument ) . index = null ; } } public void cleanUpIndexes ( ) { SimpleSet knownPaths = new SimpleSet ( ) ; IRubySearchScope scope = BasicSearchEngine . createWorkspaceScope ( ) ; PatternSearchJob job = new PatternSearchJob ( null , BasicSearchEngine . getDefaultSearchParticipant ( ) , scope , null ) ; Index [ ] selectedIndexes = job . getIndexes ( null ) ; for ( int i = , l = selectedIndexes . length ; i < l ; i ++ ) { String path = selectedIndexes [ i ] . getIndexFile ( ) . getAbsolutePath ( ) ; knownPaths . add ( path ) ; } if ( this . indexStates != null ) { Object [ ] keys = this . indexStates . keyTable ; IPath [ ] locations = new IPath [ this . indexStates . elementSize ] ; int count = ; for ( int i = , l = keys . length ; i < l ; i ++ ) { IPath key = ( IPath ) keys [ i ] ; if ( key != null && ! knownPaths . includes ( key . toOSString ( ) ) ) locations [ count ++ ] = key ; } if ( count > ) removeIndexesState ( locations ) ; } deleteIndexFiles ( knownPaths ) ; } private synchronized void removeIndexesState ( IPath [ ] locations ) { getIndexStates ( ) ; int length = locations . length ; boolean changed = false ; for ( int i = ; i < length ; i ++ ) { if ( locations [ i ] == null ) continue ; if ( ( indexStates . removeKey ( locations [ i ] ) != null ) ) { changed = true ; if ( VERBOSE ) { Util . verbose ( "" + locations [ i ] ) ; } } } if ( ! changed ) return ; writeSavedIndexNamesFile ( ) ; } public SourceElementParser getSourceElementParser ( IRubyProject project , ISourceElementRequestor requestor ) { return new SourceElementParser ( requestor ) ; } public void indexLibrary ( IPath path , IProject project ) { if ( RubyCore . getPlugin ( ) == null ) return ; Object target = RubyModel . getTarget ( path , true ) ; IndexRequest request = null ; if ( target instanceof java . io . File ) { if ( ( ( java . io . File ) target ) . isDirectory ( ) ) { request = new AddExternalFolderToIndex ( path , this ) ; } else { return ; } } else { return ; } if ( ! isJobWaiting ( request ) ) this . request ( request ) ; } public void indexAll ( IProject project ) { if ( RubyCore . getPlugin ( ) == null ) return ; try { RubyModel model = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; RubyProject javaProject = ( RubyProject ) model . getRubyProject ( project ) ; ILoadpathEntry [ ] entries = javaProject . getResolvedLoadpath ( true , false , false ) ; for ( int i = ; i < entries . length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY ) this . indexLibrary ( entry . getPath ( ) , project ) ; } } catch ( RubyModelException e ) { } IndexRequest request = new IndexAllProject ( project , this ) ; if ( ! isJobWaiting ( request ) ) this . request ( request ) ; } public synchronized void removeIndexFamily ( IPath path ) { ArrayList < IPath > toRemove = null ; Object [ ] containerPaths = this . indexLocations . keyTable ; for ( int i = , length = containerPaths . length ; i < length ; i ++ ) { IPath containerPath = ( IPath ) containerPaths [ i ] ; if ( containerPath == null ) continue ; if ( path . isPrefixOf ( containerPath ) ) { if ( toRemove == null ) toRemove = new ArrayList < IPath > ( ) ; toRemove . add ( containerPath ) ; } } if ( toRemove != null ) for ( int i = , length = toRemove . size ( ) ; i < length ; i ++ ) this . removeIndex ( ( IPath ) toRemove . get ( i ) ) ; } public synchronized Index recreateIndex ( IPath containerPath ) { String containerPathString = containerPath . getDevice ( ) == null ? containerPath . toString ( ) : containerPath . toOSString ( ) ; try { IPath indexLocation = computeIndexLocation ( containerPath ) ; Index index = ( Index ) this . indexes . get ( indexLocation ) ; ReadWriteMonitor monitor = index == null ? null : index . monitor ; if ( VERBOSE ) Util . verbose ( "" + indexLocation + "" + containerPathString ) ; index = new Index ( indexLocation . toString ( ) , containerPathString , false ) ; this . indexes . put ( indexLocation , index ) ; index . monitor = monitor ; return index ; } catch ( IOException e ) { if ( VERBOSE ) { Util . verbose ( "" + containerPathString ) ; e . printStackTrace ( ) ; } return null ; } } public void removeSourceFolderFromIndex ( RubyProject javaProject , IPath sourceFolder , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns ) { IProject project = javaProject . getProject ( ) ; if ( this . jobEnd > this . jobStart ) { IndexRequest request = new IndexAllProject ( project , this ) ; if ( isJobWaiting ( request ) ) return ; } this . request ( new RemoveFolderFromIndex ( sourceFolder , inclusionPatterns , exclusionPatterns , project , this ) ) ; } public void indexSourceFolder ( RubyProject javaProject , IPath sourceFolder , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns ) { IProject project = javaProject . getProject ( ) ; if ( this . jobEnd > this . jobStart ) { IndexRequest request = new IndexAllProject ( project , this ) ; if ( isJobWaiting ( request ) ) return ; } this . request ( new AddFolderToIndex ( sourceFolder , project , inclusionPatterns , exclusionPatterns , this ) ) ; } @ Override public synchronized void reset ( ) { super . reset ( ) ; if ( this . indexes != null ) { this . indexes = new HashMap ( ) ; this . indexStates = null ; } this . indexLocations = new SimpleLookupTable ( ) ; this . rubyPluginLocation = null ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import java . io . IOException ; import java . net . URI ; import org . eclipse . core . filesystem . EFS ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceProxy ; import org . eclipse . core . resources . IResourceProxyVisitor ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . compiler . util . SimpleLookupTable ; import org . rubypeople . rdt . internal . core . LoadpathEntry ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . SourceElementParser ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . Util ; public class IndexAllProject extends IndexRequest { IProject project ; public IndexAllProject ( IProject project , IndexManager manager ) { super ( project . getFullPath ( ) , manager ) ; this . project = project ; } public boolean equals ( Object o ) { if ( o instanceof IndexAllProject ) return this . project . equals ( ( ( IndexAllProject ) o ) . project ) ; return false ; } public boolean execute ( IProgressMonitor progressMonitor ) { if ( this . isCancelled || progressMonitor != null && progressMonitor . isCanceled ( ) ) return true ; if ( ! project . isAccessible ( ) ) return true ; ReadWriteMonitor monitor = null ; try { RubyProject rubyProject = ( RubyProject ) RubyCore . create ( this . project ) ; ILoadpathEntry [ ] entries = rubyProject . getRawLoadpath ( ) ; int length = entries . length ; ILoadpathEntry [ ] sourceEntries = new ILoadpathEntry [ length ] ; int sourceEntriesNumber = ; for ( int i = ; i < length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) sourceEntries [ sourceEntriesNumber ++ ] = entry ; } if ( sourceEntriesNumber == ) { IPath projectPath = rubyProject . getPath ( ) ; for ( int i = ; i < length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY && entry . getPath ( ) . equals ( projectPath ) ) { this . manager . indexLibrary ( projectPath , this . project ) ; return true ; } } Index index = this . manager . getIndexForUpdate ( this . containerPath , true , true ) ; if ( index != null ) this . manager . saveIndex ( index ) ; return true ; } if ( sourceEntriesNumber != length ) System . arraycopy ( sourceEntries , , sourceEntries = new ILoadpathEntry [ sourceEntriesNumber ] , , sourceEntriesNumber ) ; Index index = this . manager . getIndexForUpdate ( this . containerPath , true , true ) ; if ( index == null ) return true ; monitor = index . monitor ; if ( monitor == null ) return true ; monitor . enterRead ( ) ; String [ ] paths = index . queryDocumentNames ( "" ) ; int max = paths == null ? : paths . length ; final SimpleLookupTable indexedFileNames = new SimpleLookupTable ( max == ? : max + ) ; final String OK = "" ; final String DELETED = "" ; if ( paths != null ) { for ( int i = ; i < max ; i ++ ) indexedFileNames . put ( paths [ i ] , DELETED ) ; } final long indexLastModified = max == ? : index . getIndexFile ( ) . lastModified ( ) ; IWorkspaceRoot root = this . project . getWorkspace ( ) . getRoot ( ) ; for ( int i = ; i < sourceEntriesNumber ; i ++ ) { if ( this . isCancelled ) return false ; ILoadpathEntry entry = sourceEntries [ i ] ; IResource sourceFolder = root . findMember ( entry . getPath ( ) ) ; if ( sourceFolder != null ) { final char [ ] [ ] inclusionPatterns = ( ( LoadpathEntry ) entry ) . fullInclusionPatternChars ( ) ; final char [ ] [ ] exclusionPatterns = ( ( LoadpathEntry ) entry ) . fullExclusionPatternChars ( ) ; if ( max == ) { sourceFolder . accept ( new IResourceProxyVisitor ( ) { public boolean visit ( IResourceProxy proxy ) { if ( isCancelled ) return false ; switch ( proxy . getType ( ) ) { case IResource . FILE : if ( org . rubypeople . rdt . internal . core . util . Util . isRubyOrERBLikeFileName ( proxy . getName ( ) ) ) { IFile file = ( IFile ) proxy . requestResource ( ) ; if ( exclusionPatterns != null || inclusionPatterns != null ) if ( Util . isExcluded ( file , inclusionPatterns , exclusionPatterns ) ) return false ; indexedFileNames . put ( Util . relativePath ( file . getFullPath ( ) , ) , file ) ; } return false ; case IResource . FOLDER : if ( exclusionPatterns != null && inclusionPatterns == null ) { if ( Util . isExcluded ( proxy . requestFullPath ( ) , inclusionPatterns , exclusionPatterns , true ) ) return false ; } } return true ; } } , IResource . NONE ) ; } else { sourceFolder . accept ( new IResourceProxyVisitor ( ) { public boolean visit ( IResourceProxy proxy ) throws CoreException { if ( isCancelled ) return false ; switch ( proxy . getType ( ) ) { case IResource . FILE : if ( org . rubypeople . rdt . internal . core . util . Util . isRubyOrERBLikeFileName ( proxy . getName ( ) ) ) { IFile file = ( IFile ) proxy . requestResource ( ) ; URI location = file . getLocationURI ( ) ; if ( location == null ) return false ; if ( exclusionPatterns != null || inclusionPatterns != null ) if ( Util . isExcluded ( file , inclusionPatterns , exclusionPatterns ) ) return false ; String relativePathString = Util . relativePath ( file . getFullPath ( ) , ) ; indexedFileNames . put ( relativePathString , indexedFileNames . get ( relativePathString ) == null || indexLastModified < EFS . getStore ( location ) . fetchInfo ( ) . getLastModified ( ) ? ( Object ) file : ( Object ) OK ) ; } return false ; case IResource . FOLDER : if ( exclusionPatterns != null || inclusionPatterns != null ) if ( Util . isExcluded ( proxy . requestResource ( ) , inclusionPatterns , exclusionPatterns ) ) return false ; } return true ; } } , IResource . NONE ) ; } } } SourceElementParser parser = this . manager . getSourceElementParser ( rubyProject , null ) ; Object [ ] names = indexedFileNames . keyTable ; Object [ ] values = indexedFileNames . valueTable ; for ( int i = , namesLength = names . length ; i < namesLength ; i ++ ) { String name = ( String ) names [ i ] ; if ( name != null ) { if ( this . isCancelled ) return false ; Object value = values [ i ] ; if ( value != OK ) { if ( value == DELETED ) this . manager . remove ( name , this . containerPath ) ; else this . manager . addSource ( ( IFile ) value , this . containerPath , parser ) ; } } } this . manager . request ( new SaveIndex ( this . containerPath , this . manager ) ) ; } catch ( CoreException e ) { if ( JobManager . VERBOSE ) { Util . verbose ( "" + this . project + "" , System . err ) ; e . printStackTrace ( ) ; } this . manager . removeIndex ( this . containerPath ) ; return false ; } catch ( IOException e ) { if ( JobManager . VERBOSE ) { Util . verbose ( "" + this . project + "" , System . err ) ; e . printStackTrace ( ) ; } this . manager . removeIndex ( this . containerPath ) ; return false ; } finally { if ( monitor != null ) monitor . exitRead ( ) ; } return true ; } public int hashCode ( ) { return this . project . hashCode ( ) ; } protected Integer updatedIndexState ( ) { return IndexManager . REBUILDING_STATE ; } public String toString ( ) { return "" + this . project . getFullPath ( ) ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import java . io . IOException ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . Util ; class RemoveFolderFromIndex extends IndexRequest { IPath folderPath ; char [ ] [ ] inclusionPatterns ; char [ ] [ ] exclusionPatterns ; IProject project ; public RemoveFolderFromIndex ( IPath folderPath , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns , IProject project , IndexManager manager ) { super ( project . getFullPath ( ) , manager ) ; this . folderPath = folderPath ; this . inclusionPatterns = inclusionPatterns ; this . exclusionPatterns = exclusionPatterns ; this . project = project ; } public boolean execute ( IProgressMonitor progressMonitor ) { if ( this . isCancelled || progressMonitor != null && progressMonitor . isCanceled ( ) ) return true ; Index index = this . manager . getIndex ( this . containerPath , true , false ) ; if ( index == null ) return true ; ReadWriteMonitor monitor = index . monitor ; if ( monitor == null ) return true ; try { monitor . enterRead ( ) ; String containerRelativePath = Util . relativePath ( this . folderPath , this . containerPath . segmentCount ( ) ) ; String [ ] paths = index . queryDocumentNames ( containerRelativePath ) ; if ( paths != null ) { if ( this . exclusionPatterns == null && this . inclusionPatterns == null ) { for ( int i = , max = paths . length ; i < max ; i ++ ) { manager . remove ( paths [ i ] , this . containerPath ) ; } } else { for ( int i = , max = paths . length ; i < max ; i ++ ) { String documentPath = this . containerPath . toString ( ) + '' + paths [ i ] ; if ( ! Util . isExcluded ( new Path ( documentPath ) , this . inclusionPatterns , this . exclusionPatterns , false ) ) manager . remove ( paths [ i ] , this . containerPath ) ; } } } } catch ( IOException e ) { if ( JobManager . VERBOSE ) { Util . verbose ( "" + this . folderPath + "" , System . err ) ; e . printStackTrace ( ) ; } return false ; } finally { monitor . exitRead ( ) ; } return true ; } public String toString ( ) { return "" + this . folderPath + "" + this . containerPath ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import java . util . Stack ; import org . rubypeople . rdt . core . Flags ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor ; import org . rubypeople . rdt . internal . core . util . Util ; public class SourceIndexerRequestor implements ISourceElementRequestor { private SourceIndexer indexer ; private Stack < TypeInfo > typeStack ; public SourceIndexerRequestor ( SourceIndexer sourceIndexer ) { this . indexer = sourceIndexer ; typeStack = new Stack < TypeInfo > ( ) ; } public void acceptConstructorReference ( String name , int argCount , int offset ) { indexer . addConstructorReference ( name . toCharArray ( ) , argCount ) ; } public void acceptFieldReference ( String name , int offset ) { indexer . addFieldReference ( name . toCharArray ( ) ) ; } public void acceptImport ( String value , int startOffset , int endOffset ) { } public void acceptMethodReference ( String name , int argCount , int offset ) { indexer . addMethodReference ( name . toCharArray ( ) , argCount ) ; } public void acceptMixin ( String moduleName ) { indexer . addTypeReference ( moduleName . toCharArray ( ) ) ; TypeInfo info = typeStack . peek ( ) ; char [ ] simpleName = getSimpleName ( info . name ) ; char [ ] [ ] enclosingTypes = getEnclosingTypeNames ( info . name ) ; indexer . addIncludedModuleReference ( info . isModule ? Flags . AccModule : , new char [ ] , simpleName , enclosingTypes , moduleName . toCharArray ( ) ) ; } public void acceptProblem ( CategorizedProblem problem ) { } public void acceptTypeReference ( String name , int startOffset , int endOffset ) { indexer . addTypeReference ( name . toCharArray ( ) ) ; } public void acceptUnknownReference ( String name , int startOffset , int endOffset ) { } public void enterConstructor ( MethodInfo constructor ) { indexer . addConstructorDeclaration ( constructor . name . toCharArray ( ) , constructor . parameterNames . length ) ; } public void enterField ( FieldInfo field ) { indexer . addFieldDeclaration ( null , field . name . toCharArray ( ) ) ; } public void enterMethod ( MethodInfo method ) { indexer . addMethodDeclaration ( method . name . toCharArray ( ) , method . parameterNames . length ) ; } public void enterScript ( ) { } public void enterType ( TypeInfo type ) { String [ ] modules = type . modules ; char [ ] [ ] mod = new char [ modules . length ] [ ] ; for ( int i = ; i < modules . length ; i ++ ) { mod [ i ] = modules [ i ] . toCharArray ( ) ; } char [ ] packName = new char [ ] ; char [ ] superclass = new char [ ] ; if ( type . superclass != null ) { superclass = type . superclass . toCharArray ( ) ; } char [ ] simpleName = getSimpleName ( type . name ) ; char [ ] [ ] enclosingTypes = getEnclosingTypeNames ( type . name ) ; indexer . addClassDeclaration ( type . isModule ? Flags . AccModule : , packName , simpleName , enclosingTypes , superclass , mod , type . secondary ) ; typeStack . push ( type ) ; } private char [ ] getSimpleName ( String name ) { return Util . getSimpleName ( name ) . toCharArray ( ) ; } private char [ ] [ ] getEnclosingTypeNames ( String typeName ) { String [ ] parts = typeName . split ( "" ) ; char [ ] [ ] names = new char [ typeStack . size ( ) + parts . length - ] [ ] ; int i = ; for ( TypeInfo info : typeStack ) { names [ i ++ ] = info . name . toCharArray ( ) ; } for ( int j = ; j < parts . length - ; j ++ ) { names [ i ++ ] = parts [ j ] . toCharArray ( ) ; } return names ; } public void exitConstructor ( int endOffset ) { } public void exitField ( int endOffset ) { } public void exitMethod ( int endOffset ) { } public void exitScript ( int endOffset ) { typeStack . clear ( ) ; } public void exitType ( int endOffset ) { typeStack . pop ( ) ; } public void acceptMethodVisibilityChange ( String methodName , int visibility ) { } public void acceptModuleFunction ( String function ) { } public void acceptYield ( String name ) { } public void acceptBlock ( int startOffset , int endOffset ) { } } package org . rubypeople . rdt . internal . core . search . indexing ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . internal . compiler . util . SimpleLookupTable ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . BasicSearchEngine ; import org . rubypeople . rdt . internal . core . search . ERBSearchDocument ; import org . rubypeople . rdt . internal . core . search . RubySearchDocument ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . Util ; public class AddExternalFolderToIndex extends IndexRequest { public AddExternalFolderToIndex ( IPath containerPath , IndexManager manager ) { super ( containerPath , manager ) ; } public boolean execute ( IProgressMonitor progressMonitor ) { if ( this . isCancelled || progressMonitor != null && progressMonitor . isCanceled ( ) ) return true ; try { Index index = this . manager . getIndexForUpdate ( this . containerPath , false , false ) ; if ( index != null ) { if ( JobManager . VERBOSE ) org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + this . containerPath ) ; return true ; } index = this . manager . getIndexForUpdate ( this . containerPath , true , true ) ; if ( index == null ) { if ( JobManager . VERBOSE ) org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + this . containerPath ) ; return true ; } ReadWriteMonitor monitor = index . monitor ; if ( monitor == null ) { if ( JobManager . VERBOSE ) org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + this . containerPath + "" ) ; return true ; } File file = null ; try { monitor . enterWrite ( ) ; if ( RubyModelManager . ZIP_ACCESS_VERBOSE ) System . out . println ( "" + Thread . currentThread ( ) + "" + this . containerPath ) ; file = this . containerPath . toFile ( ) ; if ( this . isCancelled ) { if ( JobManager . VERBOSE ) org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + file . getName ( ) + "" ) ; return false ; } if ( JobManager . VERBOSE ) org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + file . getName ( ) ) ; long initialTime = System . currentTimeMillis ( ) ; String [ ] paths = index . queryDocumentNames ( "" ) ; if ( paths != null ) { int max = paths . length ; String EXISTS = "" ; String DELETED = "" ; SimpleLookupTable indexedFileNames = new SimpleLookupTable ( max == ? : max + ) ; for ( int i = ; i < max ; i ++ ) indexedFileNames . put ( paths [ i ] , DELETED ) ; addDirectorysChildren ( file , EXISTS , indexedFileNames ) ; boolean needToReindex = indexedFileNames . elementSize != max ; if ( ! needToReindex ) { Object [ ] valueTable = indexedFileNames . valueTable ; for ( int i = , l = valueTable . length ; i < l ; i ++ ) { if ( valueTable [ i ] == DELETED ) { needToReindex = true ; break ; } } if ( ! needToReindex ) { if ( JobManager . VERBOSE ) org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + file . getName ( ) + "" + ( System . currentTimeMillis ( ) - initialTime ) + "" ) ; this . manager . saveIndex ( index ) ; return true ; } } } SearchParticipant participant = BasicSearchEngine . getDefaultSearchParticipant ( ) ; index = manager . recreateIndex ( this . containerPath ) ; if ( index == null ) { manager . removeIndex ( this . containerPath ) ; return false ; } if ( ! indexFiles ( index , file , participant ) ) return false ; this . manager . saveIndex ( index ) ; if ( JobManager . VERBOSE ) org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + file . getName ( ) + "" + ( System . currentTimeMillis ( ) - initialTime ) + "" ) ; } finally { monitor . exitWrite ( ) ; } } catch ( IOException e ) { if ( JobManager . VERBOSE ) { org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + this . containerPath + "" ) ; e . printStackTrace ( ) ; } manager . removeIndex ( this . containerPath ) ; return false ; } return true ; } private boolean indexFiles ( Index index , File file , SearchParticipant participant ) throws FileNotFoundException , IOException { File [ ] children = file . listFiles ( ) ; if ( children == null ) return true ; for ( int i = ; i < children . length ; i ++ ) { if ( this . isCancelled ) { if ( JobManager . VERBOSE ) org . rubypeople . rdt . internal . core . util . Util . verbose ( "" + file . getName ( ) + "" ) ; return false ; } String name = children [ i ] . getName ( ) ; if ( children [ i ] . isFile ( ) && Util . isRubyOrERBLikeFileName ( name ) ) { InputStream stream = new FileInputStream ( children [ i ] ) ; char [ ] contents = Util . getInputStreamAsCharArray ( stream , - , null ) ; RubySearchDocument entryDocument ; if ( Util . isERBLikeFileName ( name ) ) { entryDocument = new ERBSearchDocument ( children [ i ] . getAbsolutePath ( ) , contents , participant ) ; } else { entryDocument = new RubySearchDocument ( children [ i ] . getAbsolutePath ( ) , contents , participant ) ; } this . manager . indexDocument ( entryDocument , participant , index , this . containerPath ) ; } if ( ! indexFiles ( index , children [ i ] , participant ) ) return false ; } return true ; } private void addDirectorysChildren ( File file , String EXISTS , SimpleLookupTable indexedFileNames ) { File [ ] children = file . listFiles ( ) ; if ( children == null ) return ; for ( int i = ; i < children . length ; i ++ ) { String name = children [ i ] . getName ( ) ; if ( Util . isRubyOrERBLikeFileName ( name ) ) { indexedFileNames . put ( name , EXISTS ) ; } addDirectorysChildren ( children [ i ] , EXISTS , indexedFileNames ) ; } } protected Integer updatedIndexState ( ) { return IndexManager . REBUILDING_STATE ; } public String toString ( ) { return "" + this . containerPath . toString ( ) ; } public boolean equals ( Object o ) { if ( o instanceof AddExternalFolderToIndex ) { if ( this . containerPath != null ) return this . containerPath . equals ( ( ( AddExternalFolderToIndex ) o ) . containerPath ) ; } return false ; } public int hashCode ( ) { if ( this . containerPath != null ) return this . containerPath . hashCode ( ) ; return - ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . internal . core . index . Index ; class RemoveFromIndex extends IndexRequest { String resourceName ; public RemoveFromIndex ( String resourceName , IPath containerPath , IndexManager manager ) { super ( containerPath , manager ) ; this . resourceName = resourceName ; } public boolean execute ( IProgressMonitor progressMonitor ) { if ( this . isCancelled || progressMonitor != null && progressMonitor . isCanceled ( ) ) return true ; Index index = this . manager . getIndex ( this . containerPath , true , false ) ; if ( index == null ) return true ; ReadWriteMonitor monitor = index . monitor ; if ( monitor == null ) return true ; try { monitor . enterWrite ( ) ; index . remove ( resourceName ) ; } finally { monitor . exitWrite ( ) ; } return true ; } public String toString ( ) { return "" + this . resourceName + "" + this . containerPath ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceProxy ; import org . eclipse . core . resources . IResourceProxyVisitor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . SourceElementParser ; import org . rubypeople . rdt . internal . core . index . Index ; import org . rubypeople . rdt . internal . core . search . processing . JobManager ; import org . rubypeople . rdt . internal . core . util . Util ; class AddFolderToIndex extends IndexRequest { IPath folderPath ; IProject project ; char [ ] [ ] inclusionPatterns ; char [ ] [ ] exclusionPatterns ; public AddFolderToIndex ( IPath folderPath , IProject project , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns , IndexManager manager ) { super ( project . getFullPath ( ) , manager ) ; this . folderPath = folderPath ; this . project = project ; this . inclusionPatterns = inclusionPatterns ; this . exclusionPatterns = exclusionPatterns ; } public boolean execute ( IProgressMonitor progressMonitor ) { if ( this . isCancelled || progressMonitor != null && progressMonitor . isCanceled ( ) ) return true ; if ( ! project . isAccessible ( ) ) return true ; IResource folder = this . project . getParent ( ) . findMember ( this . folderPath ) ; if ( folder == null || folder . getType ( ) == IResource . FILE ) return true ; Index index = this . manager . getIndex ( this . containerPath , true , true ) ; if ( index == null ) return true ; ReadWriteMonitor monitor = index . monitor ; if ( monitor == null ) return true ; try { monitor . enterRead ( ) ; final IPath container = this . containerPath ; final IndexManager indexManager = this . manager ; final SourceElementParser parser = indexManager . getSourceElementParser ( RubyCore . create ( this . project ) , null ) ; if ( this . exclusionPatterns == null && this . inclusionPatterns == null ) { folder . accept ( new IResourceProxyVisitor ( ) { public boolean visit ( IResourceProxy proxy ) { if ( proxy . getType ( ) == IResource . FILE ) { if ( org . rubypeople . rdt . internal . core . util . Util . isRubyOrERBLikeFileName ( proxy . getName ( ) ) ) indexManager . addSource ( ( IFile ) proxy . requestResource ( ) , container , parser ) ; return false ; } return true ; } } , IResource . NONE ) ; } else { folder . accept ( new IResourceProxyVisitor ( ) { public boolean visit ( IResourceProxy proxy ) { switch ( proxy . getType ( ) ) { case IResource . FILE : if ( org . rubypeople . rdt . internal . core . util . Util . isRubyOrERBLikeFileName ( proxy . getName ( ) ) ) { IResource resource = proxy . requestResource ( ) ; if ( ! Util . isExcluded ( resource , inclusionPatterns , exclusionPatterns ) ) indexManager . addSource ( ( IFile ) resource , container , parser ) ; } return false ; case IResource . FOLDER : if ( exclusionPatterns != null && inclusionPatterns == null ) { if ( Util . isExcluded ( proxy . requestFullPath ( ) , inclusionPatterns , exclusionPatterns , true ) ) return false ; } } return true ; } } , IResource . NONE ) ; } } catch ( CoreException e ) { if ( JobManager . VERBOSE ) { Util . verbose ( "" + this . folderPath + "" , System . err ) ; e . printStackTrace ( ) ; } return false ; } finally { monitor . exitRead ( ) ; } return true ; } public String toString ( ) { return "" + this . folderPath + "" + this . containerPath ; } } package org . rubypeople . rdt . internal . core . search . indexing ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . internal . core . search . processing . IJob ; public abstract class IndexRequest implements IJob { protected boolean isCancelled = false ; protected IPath containerPath ; protected IndexManager manager ; public IndexRequest ( IPath containerPath , IndexManager manager ) { this . containerPath = containerPath ; this . manager = manager ; } public boolean belongsTo ( String projectNameOrJarPath ) { return projectNameOrJarPath . equals ( this . containerPath . segment ( ) ) || projectNameOrJarPath . equals ( this . containerPath . toString ( ) ) ; } public void cancel ( ) { this . manager . jobWasCancelled ( this . containerPath ) ; this . isCancelled = true ; } public void ensureReadyToRun ( ) { this . manager . aboutToUpdateIndex ( this . containerPath , updatedIndexState ( ) ) ; } protected Integer updatedIndexState ( ) { return IndexManager . UPDATING_STATE ; } } package org . rubypeople . rdt . internal . core ; public class RubyModule extends RubyType { public RubyModule ( RubyElement parent , String name ) { super ( parent , name ) ; } public boolean isClass ( ) { return false ; } public boolean isModule ( ) { return true ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . compiler . util . ObjectVector ; import org . rubypeople . rdt . internal . core . search . indexing . IndexManager ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class SetLoadpathOperation extends RubyModelOperation { ILoadpathEntry [ ] oldResolvedPath , newResolvedPath ; ILoadpathEntry [ ] newRawPath ; boolean canChangeResources ; boolean loadpathWasSaved ; boolean needCycleCheck ; boolean needValidation ; boolean needSave ; IPath newOutputLocation ; RubyProject project ; boolean identicalRoots ; public static final ILoadpathEntry [ ] DO_NOT_SET_ENTRIES = new ILoadpathEntry [ ] ; public static final ILoadpathEntry [ ] DO_NOT_UPDATE_PROJECT_REFS = new ILoadpathEntry [ ] ; public static final IPath DO_NOT_SET_OUTPUT = new Path ( "" ) ; public SetLoadpathOperation ( RubyProject project , ILoadpathEntry [ ] oldResolvedPath , ILoadpathEntry [ ] newRawPath , IPath newOutputLocation , boolean canChangeResource , boolean needValidation , boolean needSave ) { super ( new IRubyElement [ ] { project } ) ; this . oldResolvedPath = oldResolvedPath ; this . newRawPath = newRawPath ; this . newOutputLocation = newOutputLocation ; this . canChangeResources = canChangeResource ; this . needValidation = needValidation ; this . needSave = needSave ; this . project = project ; } protected void addLoadpathDeltas ( ISourceFolderRoot [ ] roots , int flag , RubyElementDelta delta ) { for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; delta . changed ( root , flag ) ; if ( ( flag & IRubyElementDelta . F_REMOVED_FROM_CLASSPATH ) != || ( flag & IRubyElementDelta . F_SOURCEATTACHED ) != || ( flag & IRubyElementDelta . F_SOURCEDETACHED ) != ) { try { root . close ( ) ; } catch ( RubyModelException e ) { } } } } protected boolean canModifyRoots ( ) { return true ; } protected int classpathContains ( ILoadpathEntry [ ] list , ILoadpathEntry entry ) { IPath [ ] exclusionPatterns = entry . getExclusionPatterns ( ) ; IPath [ ] inclusionPatterns = entry . getInclusionPatterns ( ) ; nextEntry : for ( int i = ; i < list . length ; i ++ ) { ILoadpathEntry other = list [ i ] ; if ( other . getEntryKind ( ) == entry . getEntryKind ( ) && other . isExported ( ) == entry . isExported ( ) && other . getPath ( ) . equals ( entry . getPath ( ) ) ) { IPath [ ] otherIncludes = other . getInclusionPatterns ( ) ; if ( inclusionPatterns != otherIncludes ) { if ( inclusionPatterns == null ) continue ; int includeLength = inclusionPatterns . length ; if ( otherIncludes == null || otherIncludes . length != includeLength ) continue ; for ( int j = ; j < includeLength ; j ++ ) { if ( ! inclusionPatterns [ j ] . toString ( ) . equals ( otherIncludes [ j ] . toString ( ) ) ) continue nextEntry ; } } IPath [ ] otherExcludes = other . getExclusionPatterns ( ) ; if ( exclusionPatterns != otherExcludes ) { if ( exclusionPatterns == null ) continue ; int excludeLength = exclusionPatterns . length ; if ( otherExcludes == null || otherExcludes . length != excludeLength ) continue ; for ( int j = ; j < excludeLength ; j ++ ) { if ( ! exclusionPatterns [ j ] . toString ( ) . equals ( otherExcludes [ j ] . toString ( ) ) ) continue nextEntry ; } } return i ; } } return - ; } protected void collectAllSubfolders ( IFolder folder , ArrayList collection ) throws RubyModelException { try { IResource [ ] members = folder . members ( ) ; for ( int i = , max = members . length ; i < max ; i ++ ) { IResource r = members [ i ] ; if ( r . getType ( ) == IResource . FOLDER ) { collection . add ( r ) ; collectAllSubfolders ( ( IFolder ) r , collection ) ; } } } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } } protected ArrayList determineAffectedPackageFragments ( IPath location ) throws RubyModelException { ArrayList fragments = new ArrayList ( ) ; IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; IResource resource = null ; if ( location != null ) { resource = workspace . getRoot ( ) . findMember ( location ) ; } if ( resource != null && resource . getType ( ) == IResource . FOLDER ) { IFolder folder = ( IFolder ) resource ; ILoadpathEntry [ ] classpath = project . getExpandedLoadpath ( true ) ; for ( int i = ; i < classpath . length ; i ++ ) { ILoadpathEntry entry = classpath [ i ] ; IPath path = classpath [ i ] . getPath ( ) ; if ( entry . getEntryKind ( ) != ILoadpathEntry . CPE_PROJECT && path . isPrefixOf ( location ) && ! path . equals ( location ) ) { ISourceFolderRoot [ ] roots = project . computeSourceFolderRoots ( classpath [ i ] ) ; SourceFolderRoot root = ( SourceFolderRoot ) roots [ ] ; ArrayList folders = new ArrayList ( ) ; folders . add ( folder ) ; collectAllSubfolders ( folder , folders ) ; Iterator elements = folders . iterator ( ) ; int segments = path . segmentCount ( ) ; while ( elements . hasNext ( ) ) { IFolder f = ( IFolder ) elements . next ( ) ; IPath relativePath = f . getFullPath ( ) . removeFirstSegments ( segments ) ; String [ ] pkgName = relativePath . segments ( ) ; ISourceFolder pkg = root . getSourceFolder ( pkgName ) ; fragments . add ( pkg ) ; } } } } return fragments ; } protected void executeOperation ( ) throws RubyModelException { updateProjectReferencesIfNecessary ( ) ; saveLoadpathIfNecessary ( ) ; RubyModelException originalException = null ; try { if ( this . newRawPath == DO_NOT_UPDATE_PROJECT_REFS ) this . newRawPath = project . getRawLoadpath ( ) ; if ( this . newRawPath != DO_NOT_SET_ENTRIES ) { updateLoadpath ( ) ; project . updateSourceFolderRoots ( ) ; RubyModelManager . getRubyModelManager ( ) . getDeltaProcessor ( ) . addForRefresh ( project ) ; } } catch ( RubyModelException e ) { originalException = e ; throw e ; } finally { if ( ! this . identicalRoots && this . canChangeResources ) { try { this . project . getProject ( ) . touch ( this . progressMonitor ) ; } catch ( CoreException e ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + this . project . getElementName ( ) , System . err ) ; e . printStackTrace ( ) ; } } } } done ( ) ; } protected void generateLoadpathChangeDeltas ( ) { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; if ( manager . deltaState . findRubyProject ( this . project . getElementName ( ) ) == null ) return ; boolean needToUpdateDependents = false ; RubyElementDelta delta = new RubyElementDelta ( getRubyModel ( ) ) ; boolean hasDelta = false ; if ( this . loadpathWasSaved ) { delta . changed ( this . project , IRubyElementDelta . F_CLASSPATH_CHANGED ) ; hasDelta = true ; } int oldLength = oldResolvedPath . length ; int newLength = newResolvedPath . length ; final IndexManager indexManager = manager . getIndexManager ( ) ; Map oldRoots = null ; ISourceFolderRoot [ ] roots = null ; if ( project . isOpen ( ) ) { try { roots = project . getSourceFolderRoots ( ) ; } catch ( RubyModelException e ) { } } else { Map allRemovedRoots ; if ( ( allRemovedRoots = manager . getDeltaProcessor ( ) . removedRoots ) != null ) { roots = ( ISourceFolderRoot [ ] ) allRemovedRoots . get ( project ) ; } } if ( roots != null ) { oldRoots = new HashMap ( ) ; for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; oldRoots . put ( root . getPath ( ) , root ) ; } } for ( int i = ; i < oldLength ; i ++ ) { int index = classpathContains ( newResolvedPath , oldResolvedPath [ i ] ) ; if ( index == - ) { if ( oldResolvedPath [ i ] . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { needToUpdateDependents = true ; this . needCycleCheck = true ; continue ; } ISourceFolderRoot [ ] pkgFragmentRoots = null ; if ( oldRoots != null ) { ISourceFolderRoot oldRoot = ( ISourceFolderRoot ) oldRoots . get ( oldResolvedPath [ i ] . getPath ( ) ) ; if ( oldRoot != null ) { pkgFragmentRoots = new ISourceFolderRoot [ ] { oldRoot } ; } } if ( pkgFragmentRoots == null ) { try { ObjectVector accumulatedRoots = new ObjectVector ( ) ; HashSet rootIDs = new HashSet ( ) ; rootIDs . add ( project . rootID ( ) ) ; project . computeSourceFolderRoots ( oldResolvedPath [ i ] , accumulatedRoots , rootIDs , null , false , false , null ) ; pkgFragmentRoots = new ISourceFolderRoot [ accumulatedRoots . size ( ) ] ; accumulatedRoots . copyInto ( pkgFragmentRoots ) ; } catch ( RubyModelException e ) { pkgFragmentRoots = new ISourceFolderRoot [ ] { } ; } } addLoadpathDeltas ( pkgFragmentRoots , IRubyElementDelta . F_REMOVED_FROM_CLASSPATH , delta ) ; int changeKind = oldResolvedPath [ i ] . getEntryKind ( ) ; needToUpdateDependents |= ( changeKind == ILoadpathEntry . CPE_SOURCE ) || oldResolvedPath [ i ] . isExported ( ) ; if ( indexManager != null ) { ILoadpathEntry oldEntry = oldResolvedPath [ i ] ; final IPath path = oldEntry . getPath ( ) ; switch ( changeKind ) { case ILoadpathEntry . CPE_SOURCE : final char [ ] [ ] inclusionPatterns = ( ( LoadpathEntry ) oldEntry ) . fullInclusionPatternChars ( ) ; final char [ ] [ ] exclusionPatterns = ( ( LoadpathEntry ) oldEntry ) . fullExclusionPatternChars ( ) ; postAction ( new IPostAction ( ) { public String getID ( ) { return path . toString ( ) ; } public void run ( ) { indexManager . removeSourceFolderFromIndex ( project , path , inclusionPatterns , exclusionPatterns ) ; } } , REMOVEALL_APPEND ) ; break ; case ILoadpathEntry . CPE_LIBRARY : final DeltaProcessingState deltaState = manager . deltaState ; postAction ( new IPostAction ( ) { public String getID ( ) { return path . toString ( ) ; } public void run ( ) { if ( deltaState . otherRoots . get ( path ) == null ) { indexManager . discardJobs ( path . toString ( ) ) ; indexManager . removeIndex ( path ) ; } } } , REMOVEALL_APPEND ) ; break ; } } hasDelta = true ; } else { if ( oldResolvedPath [ i ] . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { LoadpathEntry oldEntry = ( LoadpathEntry ) oldResolvedPath [ i ] ; LoadpathEntry newEntry = ( LoadpathEntry ) newResolvedPath [ index ] ; this . needCycleCheck |= ( oldEntry . isExported ( ) != newEntry . isExported ( ) ) ; continue ; } needToUpdateDependents |= ( oldResolvedPath [ i ] . isExported ( ) != newResolvedPath [ index ] . isExported ( ) ) ; if ( index != i ) { addLoadpathDeltas ( project . computeSourceFolderRoots ( oldResolvedPath [ i ] ) , IRubyElementDelta . F_REORDER , delta ) ; int changeKind = oldResolvedPath [ i ] . getEntryKind ( ) ; needToUpdateDependents |= ( changeKind == ILoadpathEntry . CPE_SOURCE ) ; hasDelta = true ; } } } for ( int i = ; i < newLength ; i ++ ) { int index = classpathContains ( oldResolvedPath , newResolvedPath [ i ] ) ; if ( index == - ) { if ( newResolvedPath [ i ] . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { needToUpdateDependents = true ; this . needCycleCheck = true ; continue ; } addLoadpathDeltas ( project . computeSourceFolderRoots ( newResolvedPath [ i ] ) , IRubyElementDelta . F_ADDED_TO_CLASSPATH , delta ) ; int changeKind = newResolvedPath [ i ] . getEntryKind ( ) ; if ( indexManager != null ) { switch ( changeKind ) { case ILoadpathEntry . CPE_LIBRARY : boolean pathHasChanged = true ; final IPath newPath = newResolvedPath [ i ] . getPath ( ) ; for ( int j = ; j < oldLength ; j ++ ) { ILoadpathEntry oldEntry = oldResolvedPath [ j ] ; if ( oldEntry . getPath ( ) . equals ( newPath ) ) { pathHasChanged = false ; break ; } } if ( pathHasChanged ) { postAction ( new IPostAction ( ) { public String getID ( ) { return newPath . toString ( ) ; } public void run ( ) { indexManager . indexLibrary ( newPath , project . getProject ( ) ) ; } } , REMOVEALL_APPEND ) ; } break ; case ILoadpathEntry . CPE_SOURCE : ILoadpathEntry entry = newResolvedPath [ i ] ; final IPath path = entry . getPath ( ) ; final char [ ] [ ] inclusionPatterns = ( ( LoadpathEntry ) entry ) . fullInclusionPatternChars ( ) ; final char [ ] [ ] exclusionPatterns = ( ( LoadpathEntry ) entry ) . fullExclusionPatternChars ( ) ; postAction ( new IPostAction ( ) { public String getID ( ) { return path . toString ( ) ; } public void run ( ) { indexManager . indexSourceFolder ( project , path , inclusionPatterns , exclusionPatterns ) ; } } , APPEND ) ; break ; } } needToUpdateDependents |= ( changeKind == ILoadpathEntry . CPE_SOURCE ) || newResolvedPath [ i ] . isExported ( ) ; hasDelta = true ; } } if ( hasDelta ) { this . addDelta ( delta ) ; } else { this . identicalRoots = true ; } if ( needToUpdateDependents ) { updateAffectedProjects ( project . getProject ( ) . getFullPath ( ) ) ; } } protected ISchedulingRule getSchedulingRule ( ) { return null ; } public boolean isReadOnly ( ) { return ! this . canChangeResources ; } protected void saveLoadpathIfNecessary ( ) throws RubyModelException { if ( ! this . canChangeResources || ! this . needSave ) return ; ILoadpathEntry [ ] loadpathForSave ; if ( this . newRawPath == DO_NOT_SET_ENTRIES || this . newRawPath == DO_NOT_UPDATE_PROJECT_REFS ) { loadpathForSave = project . getRawLoadpath ( ) ; } else { loadpathForSave = this . newRawPath ; } if ( project . saveLoadpath ( loadpathForSave , null ) ) { this . loadpathWasSaved = true ; this . setAttribute ( HAS_MODIFIED_RESOURCE_ATTR , TRUE ) ; } } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( "" ) ; if ( this . newRawPath == DO_NOT_SET_ENTRIES ) { buffer . append ( "" ) ; } else { buffer . append ( "" ) ; for ( int i = ; i < this . newRawPath . length ; i ++ ) { if ( i > ) buffer . append ( "" ) ; ILoadpathEntry element = this . newRawPath [ i ] ; buffer . append ( "" ) . append ( element . toString ( ) ) ; } } buffer . append ( "" ) ; if ( this . newOutputLocation == DO_NOT_SET_OUTPUT ) { buffer . append ( "" ) ; } else { buffer . append ( this . newOutputLocation . toString ( ) ) ; } return buffer . toString ( ) ; } private void updateLoadpath ( ) throws RubyModelException { beginTask ( Messages . bind ( Messages . classpath_settingProgress , project . getElementName ( ) ) , ) ; project . getPerProjectInfo ( ) . updateLoadpathInformation ( this . newRawPath ) ; if ( this . newResolvedPath == null ) { this . newResolvedPath = project . getResolvedLoadpath ( true , this . canChangeResources , false ) ; } if ( this . oldResolvedPath != null ) { generateLoadpathChangeDeltas ( ) ; } else { this . needCycleCheck = true ; updateAffectedProjects ( project . getProject ( ) . getFullPath ( ) ) ; } updateCycleMarkersIfNecessary ( ) ; } protected void updateAffectedProjects ( IPath prerequisiteProjectPath ) { final String updateLoadpath = "" ; removeAllPostAction ( updateLoadpath + prerequisiteProjectPath . toString ( ) ) ; try { IRubyModel model = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; IRubyProject initialProject = this . project ; IRubyProject [ ] projects = model . getRubyProjects ( ) ; for ( int i = , projectCount = projects . length ; i < projectCount ; i ++ ) { try { final RubyProject affectedProject = ( RubyProject ) projects [ i ] ; if ( affectedProject . equals ( initialProject ) ) continue ; if ( ! affectedProject . isOpen ( ) ) continue ; ILoadpathEntry [ ] classpath = affectedProject . getExpandedLoadpath ( true ) ; for ( int j = , entryCount = classpath . length ; j < entryCount ; j ++ ) { ILoadpathEntry entry = classpath [ j ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT && entry . getPath ( ) . equals ( prerequisiteProjectPath ) ) { postAction ( new IPostAction ( ) { public String getID ( ) { return updateLoadpath + affectedProject . getPath ( ) . toString ( ) ; } public void run ( ) throws RubyModelException { affectedProject . setRawLoadpath ( DO_NOT_UPDATE_PROJECT_REFS , SetLoadpathOperation . DO_NOT_SET_OUTPUT , SetLoadpathOperation . this . progressMonitor , SetLoadpathOperation . this . canChangeResources , affectedProject . getResolvedLoadpath ( true , false , false ) , false , false ) ; } } , REMOVEALL_APPEND ) ; break ; } } } catch ( RubyModelException e ) { } } } catch ( RubyModelException e ) { } } protected void updateCycleMarkersIfNecessary ( ) { if ( ! this . needCycleCheck ) return ; if ( ! this . canChangeResources ) return ; if ( ! project . hasCycleMarker ( ) && ! project . hasLoadpathCycle ( newResolvedPath ) ) { return ; } postAction ( new IPostAction ( ) { public String getID ( ) { return "" ; } public void run ( ) throws RubyModelException { RubyProject . updateAllCycleMarkers ( null ) ; } } , REMOVEALL_APPEND ) ; } protected void updateProjectReferencesIfNecessary ( ) throws RubyModelException { if ( this . newRawPath == DO_NOT_SET_ENTRIES || this . newRawPath == DO_NOT_UPDATE_PROJECT_REFS ) return ; RubyModelManager . getRubyModelManager ( ) . deltaState . updateProjectReferences ( project , oldResolvedPath , newResolvedPath , newRawPath , canChangeResources ) ; } public IRubyModelStatus verify ( ) { IRubyModelStatus status = super . verify ( ) ; if ( ! status . isOK ( ) ) { return status ; } if ( needValidation ) { ILoadpathEntry [ ] entries = this . newRawPath ; if ( entries == DO_NOT_SET_ENTRIES ) { try { entries = project . getRawLoadpath ( ) ; } catch ( RubyModelException e ) { return e . getRubyModelStatus ( ) ; } } return LoadpathEntry . validateLoadpath ( project , entries , null ) ; } return RubyModelStatus . VERIFIED_OK ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IRubyElement ; public class RubyBlock extends SourceRefElement { public RubyBlock ( RubyElement parent ) { super ( parent ) ; } public int getElementType ( ) { return IRubyElement . BLOCK ; } @ Override protected char getHandleMementoDelimiter ( ) { return JEM_FIELD ; } } package org . rubypeople . rdt . internal . core ; import java . io . File ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . LocalFileStorage ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class ExternalSourceFolder extends SourceFolder { public ExternalSourceFolder ( SourceFolderRoot parent , String [ ] names ) { super ( parent , names ) ; } protected void generateInfos ( Object info , HashMap newElements , IProgressMonitor pm ) throws RubyModelException { Openable openableParent = ( Openable ) this . parent ; if ( ! openableParent . isOpen ( ) ) { openableParent . generateInfos ( openableParent . createElementInfo ( ) , newElements , pm ) ; } } public boolean isReadOnly ( ) { return true ; } protected Object [ ] storedNonRubyResources ( ) throws RubyModelException { return ( ( ExternalSourceFolderInfo ) getElementInfo ( ) ) . getNonRubyResources ( ) ; } protected boolean computeChildren ( OpenableElementInfo info ) { ArrayList < IRubyElement > vChildren = new ArrayList < IRubyElement > ( ) ; File file = getPath ( ) . toFile ( ) ; File [ ] members = file . listFiles ( ) ; List < LocalFileStorage > files = new ArrayList < LocalFileStorage > ( ) ; for ( int i = , max = members . length ; i < max ; i ++ ) { File child = members [ i ] ; if ( ! child . isDirectory ( ) ) { IRubyElement childElement ; if ( Util . isValidRubyScriptName ( child . getName ( ) ) ) { childElement = new ExternalRubyScript ( this , child . getName ( ) , DefaultWorkingCopyOwner . PRIMARY ) ; vChildren . add ( childElement ) ; } else { files . add ( new LocalFileStorage ( child ) ) ; } } } if ( info instanceof SourceFolderInfo ) { SourceFolderInfo duh = ( SourceFolderInfo ) info ; duh . setNonRubyResources ( files . toArray ( new Object [ files . size ( ) ] ) ) ; } IRubyElement [ ] children = new IRubyElement [ vChildren . size ( ) ] ; vChildren . toArray ( children ) ; info . setChildren ( children ) ; return true ; } public IRubyScript getRubyScript ( String name ) { if ( ! org . rubypeople . rdt . internal . core . util . Util . isRubyLikeFileName ( name ) ) { throw new IllegalArgumentException ( Messages . convention_unit_notRubyName ) ; } return new ExternalRubyScript ( this , name , DefaultWorkingCopyOwner . PRIMARY ) ; } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner owner ) { switch ( token . charAt ( ) ) { case JEM_RUBYSCRIPT : if ( ! memento . hasMoreTokens ( ) ) return this ; String classFileName = memento . nextToken ( ) ; RubyElement classFile = new ExternalRubyScript ( this , classFileName , owner ) ; return classFile . getHandleFromMemento ( memento , owner ) ; } return null ; } public Object [ ] getNonRubyResources ( ) throws RubyModelException { if ( this . isDefaultPackage ( ) ) { return RubyElementInfo . NO_NON_RUBY_RESOURCES ; } else { return this . storedNonRubyResources ( ) ; } } } package org . rubypeople . rdt . internal . core . pmd ; import java . io . File ; import java . io . FileReader ; import java . io . LineNumberReader ; import java . io . Reader ; import java . io . StringReader ; import java . lang . ref . SoftReference ; import java . util . ArrayList ; import java . util . List ; public class SourceCode { public static abstract class CodeLoader { private SoftReference code ; public List getCode ( ) { List c = null ; if ( code != null ) { c = ( List ) code . get ( ) ; } if ( c != null ) { return c ; } this . code = new SoftReference ( load ( ) ) ; return ( List ) code . get ( ) ; } public abstract String getFileName ( ) ; protected abstract Reader getReader ( ) throws Exception ; protected List load ( ) { LineNumberReader lnr = null ; try { lnr = new LineNumberReader ( getReader ( ) ) ; List lines = new ArrayList ( ) ; String currentLine ; while ( ( currentLine = lnr . readLine ( ) ) != null ) { lines . add ( currentLine ) ; } return lines ; } catch ( Exception e ) { throw new RuntimeException ( "" + getFileName ( ) + "" + e . getMessage ( ) ) ; } finally { try { if ( lnr != null ) lnr . close ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "" + getFileName ( ) + "" + e . getMessage ( ) ) ; } } } } public static class FileCodeLoader extends CodeLoader { private File file ; public FileCodeLoader ( File file ) { this . file = file ; } public Reader getReader ( ) throws Exception { return new FileReader ( file ) ; } public String getFileName ( ) { return this . file . getAbsolutePath ( ) ; } } public static class StringCodeLoader extends CodeLoader { public static final String DEFAULT_NAME = "" ; private String source_code ; private String name ; public StringCodeLoader ( String code ) { this ( code , DEFAULT_NAME ) ; } public StringCodeLoader ( String code , String name ) { this . source_code = code ; this . name = name ; } public Reader getReader ( ) { return new StringReader ( source_code ) ; } public String getFileName ( ) { return name ; } } private CodeLoader cl ; public SourceCode ( CodeLoader cl ) { this . cl = cl ; } public List getCode ( ) { return cl . getCode ( ) ; } public StringBuffer getCodeBuffer ( ) { StringBuffer sb = new StringBuffer ( ) ; List lines = cl . getCode ( ) ; for ( int i = ; i < lines . size ( ) ; i ++ ) { sb . append ( ( String ) lines . get ( i ) ) ; sb . append ( PMD . EOL ) ; } return sb ; } public String getSlice ( int startLine , int endLine ) { StringBuffer sb = new StringBuffer ( ) ; List lines = cl . getCode ( ) ; for ( int i = startLine - ; i < endLine && i < lines . size ( ) ; i ++ ) { if ( sb . length ( ) != ) { sb . append ( PMD . EOL ) ; } sb . append ( ( String ) lines . get ( i ) ) ; } return sb . toString ( ) ; } public String getFileName ( ) { return cl . getFileName ( ) ; } } package org . rubypeople . rdt . internal . core . pmd ; import java . util . Comparator ; import java . util . Iterator ; import java . util . Set ; import java . util . TreeSet ; public class Match implements Comparable { private int tokenCount ; private int lineCount ; private Set < TokenEntry > markSet = new TreeSet < TokenEntry > ( ) ; private TokenEntry [ ] marks = new TokenEntry [ ] ; private String code ; private MatchCode mc ; private String label ; public static final Comparator MatchesComparator = new Comparator ( ) { public int compare ( Object a , Object b ) { Match ma = ( Match ) a ; Match mb = ( Match ) b ; return mb . getMarkCount ( ) - ma . getMarkCount ( ) ; } } ; public static final Comparator LinesComparator = new Comparator ( ) { public int compare ( Object a , Object b ) { Match ma = ( Match ) a ; Match mb = ( Match ) b ; return mb . getLineCount ( ) - ma . getLineCount ( ) ; } } ; public static final Comparator LabelComparator = new Comparator ( ) { public int compare ( Object a , Object b ) { Match ma = ( Match ) a ; Match mb = ( Match ) b ; if ( ma . getLabel ( ) == null ) return ; if ( mb . getLabel ( ) == null ) return - ; return mb . getLabel ( ) . compareTo ( ma . getLabel ( ) ) ; } } ; public static final Comparator LengthComparator = new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { Match m1 = ( Match ) o1 ; Match m2 = ( Match ) o2 ; return m2 . getLineCount ( ) - m1 . getLineCount ( ) ; } } ; public static class MatchCode { private int first ; private int second ; public MatchCode ( ) { } public MatchCode ( TokenEntry m1 , TokenEntry m2 ) { first = m1 . getIndex ( ) ; second = m2 . getIndex ( ) ; } public int hashCode ( ) { return first + * second ; } public boolean equals ( Object other ) { MatchCode mc = ( MatchCode ) other ; return mc . first == first && mc . second == second ; } public void setFirst ( int first ) { this . first = first ; } public void setSecond ( int second ) { this . second = second ; } } public Match ( int tokenCount , TokenEntry first , TokenEntry second ) { markSet . add ( first ) ; markSet . add ( second ) ; marks [ ] = first ; marks [ ] = second ; this . tokenCount = tokenCount ; } public int getMarkCount ( ) { return markSet . size ( ) ; } public void setLineCount ( int lineCount ) { this . lineCount = lineCount ; } public int getLineCount ( ) { return this . lineCount ; } public int getTokenCount ( ) { return this . tokenCount ; } public String getSourceCodeSlice ( ) { return this . code ; } public void setSourceCodeSlice ( String code ) { this . code = code ; } public Iterator < TokenEntry > iterator ( ) { return markSet . iterator ( ) ; } public int compareTo ( Object o ) { Match other = ( Match ) o ; int diff = other . getTokenCount ( ) - getTokenCount ( ) ; if ( diff != ) { return diff ; } return other . getFirstMark ( ) . getIndex ( ) - getFirstMark ( ) . getIndex ( ) ; } public TokenEntry getFirstMark ( ) { return marks [ ] ; } public TokenEntry getSecondMark ( ) { return marks [ ] ; } public String toString ( ) { return "" + PMD . EOL + "" + tokenCount + PMD . EOL + "" + markSet . size ( ) ; } public Set < TokenEntry > getMarkSet ( ) { return markSet ; } public MatchCode getMatchCode ( ) { if ( mc == null ) { mc = new MatchCode ( marks [ ] , marks [ ] ) ; } return mc ; } public int getEndIndex ( ) { return marks [ ] . getIndex ( ) + getTokenCount ( ) - ; } public void setMarkSet ( Set < TokenEntry > markSet ) { this . markSet = markSet ; } public void setLabel ( String aLabel ) { label = aLabel ; } public String getLabel ( ) { return label ; } } package org . rubypeople . rdt . internal . core . pmd ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; public class MatchAlgorithm { private final static int MOD = ; private int lastHash ; private int lastMod = ; private List < Match > matches ; private Map source ; private Tokens tokens ; private List code ; private CPDListener cpdListener ; private int min ; public MatchAlgorithm ( Map sourceCode , Tokens tokens , int min ) { this ( sourceCode , tokens , min , new CPDNullListener ( ) ) ; } public MatchAlgorithm ( Map sourceCode , Tokens tokens , int min , CPDListener listener ) { this . source = sourceCode ; this . tokens = tokens ; this . code = tokens . getTokens ( ) ; this . min = min ; this . cpdListener = listener ; for ( int i = ; i < min ; i ++ ) { lastMod *= MOD ; } } public void setListener ( CPDListener listener ) { this . cpdListener = listener ; } public Iterator < Match > matches ( ) { return matches . iterator ( ) ; } public TokenEntry tokenAt ( int offset , TokenEntry m ) { return ( TokenEntry ) code . get ( offset + m . getIndex ( ) ) ; } public int getMinimumTileSize ( ) { return this . min ; } public void findMatches ( ) { cpdListener . phaseUpdate ( CPDListener . HASH ) ; Map markGroups = hash ( ) ; cpdListener . phaseUpdate ( CPDListener . MATCH ) ; MatchCollector matchCollector = new MatchCollector ( this ) ; for ( Iterator i = markGroups . values ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Object o = i . next ( ) ; if ( o instanceof List ) { Collections . reverse ( ( List ) o ) ; matchCollector . collect ( ( List ) o ) ; } i . remove ( ) ; } cpdListener . phaseUpdate ( CPDListener . GROUPING ) ; matches = matchCollector . getMatches ( ) ; matchCollector = null ; for ( Iterator < Match > i = matches . iterator ( ) ; i . hasNext ( ) ; ) { Match match = i . next ( ) ; for ( Iterator < TokenEntry > occurrences = match . iterator ( ) ; occurrences . hasNext ( ) ; ) { TokenEntry mark = occurrences . next ( ) ; match . setLineCount ( tokens . getLineCount ( mark , match ) ) ; if ( ! occurrences . hasNext ( ) ) { int start = mark . getBeginLine ( ) ; int end = start + match . getLineCount ( ) - ; SourceCode sourceCode = ( SourceCode ) source . get ( mark . getTokenSrcID ( ) ) ; match . setSourceCodeSlice ( sourceCode . getSlice ( start , end ) ) ; } } } cpdListener . phaseUpdate ( CPDListener . DONE ) ; } private Map hash ( ) { Map markGroups = new HashMap ( tokens . size ( ) ) ; for ( int i = code . size ( ) - ; i >= ; i -- ) { TokenEntry token = ( TokenEntry ) code . get ( i ) ; if ( token != TokenEntry . EOF ) { int last = tokenAt ( min , token ) . getIdentifier ( ) ; lastHash = MOD * lastHash + token . getIdentifier ( ) - lastMod * last ; token . setHashCode ( lastHash ) ; Object o = markGroups . get ( token ) ; if ( o == null ) { markGroups . put ( token , token ) ; } else if ( o instanceof TokenEntry ) { List l = new ArrayList ( ) ; l . add ( o ) ; l . add ( token ) ; markGroups . put ( token , l ) ; } else { List l = ( List ) o ; l . add ( token ) ; } } else { lastHash = ; for ( int end = Math . max ( , i - min + ) ; i > end ; i -- ) { token = ( TokenEntry ) code . get ( i - ) ; lastHash = MOD * lastHash + token . getIdentifier ( ) ; if ( token == TokenEntry . EOF ) { break ; } } } } return markGroups ; } } package org . rubypeople . rdt . internal . core . pmd ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; public class Tokens { private List tokens = new ArrayList ( ) ; public void add ( TokenEntry tokenEntry ) { this . tokens . add ( tokenEntry ) ; } public Iterator iterator ( ) { return tokens . iterator ( ) ; } private TokenEntry get ( int index ) { return ( TokenEntry ) tokens . get ( index ) ; } public int size ( ) { return tokens . size ( ) ; } public int getLineCount ( TokenEntry mark , Match match ) { TokenEntry endTok = get ( mark . getIndex ( ) + match . getTokenCount ( ) - ) ; if ( endTok == TokenEntry . EOF ) { endTok = get ( mark . getIndex ( ) + match . getTokenCount ( ) - ) ; } return endTok . getBeginLine ( ) - mark . getBeginLine ( ) + ; } public List getTokens ( ) { return tokens ; } } package org . rubypeople . rdt . internal . core . pmd ; import java . util . HashMap ; import java . util . Map ; public class TokenEntry implements Comparable { public static final TokenEntry EOF = new TokenEntry ( ) ; private String tokenSrcID ; private int beginLine ; private int index ; private int identifier ; private int hashCode ; private int startOffset ; private int endOffset ; private final static Map Tokens = new HashMap ( ) ; private static int TokenCount = ; private TokenEntry ( ) { this . identifier = ; this . tokenSrcID = "" ; } public TokenEntry ( String image , String tokenSrcID , int beginLine , int startOffset , int endOffset ) { Integer i = ( Integer ) Tokens . get ( image ) ; if ( i == null ) { i = new Integer ( Tokens . size ( ) + ) ; Tokens . put ( image , i ) ; } this . identifier = i . intValue ( ) ; this . tokenSrcID = tokenSrcID ; this . beginLine = beginLine ; this . startOffset = startOffset ; this . endOffset = endOffset ; this . index = TokenCount ++ ; } public static TokenEntry getEOF ( ) { TokenCount ++ ; return EOF ; } public static void clearImages ( ) { Tokens . clear ( ) ; TokenCount = ; } public int getStartOffset ( ) { return startOffset ; } public int getEndOffset ( ) { return endOffset ; } public String getTokenSrcID ( ) { return tokenSrcID ; } public int getBeginLine ( ) { return beginLine ; } public int getIdentifier ( ) { return this . identifier ; } public int getIndex ( ) { return this . index ; } public int hashCode ( ) { return hashCode ; } public void setHashCode ( int hashCode ) { this . hashCode = hashCode ; } public boolean equals ( Object o ) { if ( ! ( o instanceof TokenEntry ) ) { return false ; } TokenEntry other = ( TokenEntry ) o ; return other . hashCode == hashCode ; } public int compareTo ( Object o ) { TokenEntry other = ( TokenEntry ) o ; return getIndex ( ) - other . getIndex ( ) ; } } package org . rubypeople . rdt . internal . core . pmd ; import java . io . File ; public interface CPDListener { public static final int INIT = ; public static final int HASH = ; public static final int MATCH = ; public static final int GROUPING = ; public static final int DONE = ; void addedFile ( int fileCount , File file ) ; void phaseUpdate ( int phase ) ; } package org . rubypeople . rdt . internal . core . pmd ; import java . io . File ; public class CPDNullListener implements CPDListener { public void addedFile ( int fileCount , File file ) { } public void phaseUpdate ( int phase ) { } } package org . rubypeople . rdt . internal . core . pmd ; import java . io . File ; import java . io . FilenameFilter ; import org . rubypeople . rdt . internal . core . util . Util ; public class RubyLanguage implements Language { public static class RubyFileOrDirectoryFilter implements FilenameFilter { public boolean accept ( File dir , String filename ) { return Util . isValidRubyScriptName ( filename ) || ( new File ( dir . getAbsolutePath ( ) + fileSeparator + filename ) . isDirectory ( ) ) ; } } public Tokenizer getTokenizer ( ) { return new RubyTokenizer ( ) ; } public FilenameFilter getFileFilter ( ) { return new RubyFileOrDirectoryFilter ( ) ; } } package org . rubypeople . rdt . internal . core . pmd ; import java . io . File ; import java . io . FilenameFilter ; import java . util . ArrayList ; import java . util . List ; public class FileFinder { private FilenameFilter filter ; private static final String FILE_SEP = System . getProperty ( "" ) ; public List findFilesFrom ( String dir , FilenameFilter filter , boolean recurse ) { this . filter = filter ; List files = new ArrayList ( ) ; scanDirectory ( new File ( dir ) , files , recurse ) ; return files ; } private void scanDirectory ( File dir , List list , boolean recurse ) { String [ ] candidates = dir . list ( filter ) ; if ( candidates == null ) { return ; } for ( int i = ; i < candidates . length ; i ++ ) { File tmp = new File ( dir + FILE_SEP + candidates [ i ] ) ; if ( tmp . isDirectory ( ) ) { if ( recurse ) { scanDirectory ( tmp , list , true ) ; } } else { list . add ( new File ( dir + FILE_SEP + candidates [ i ] ) ) ; } } } } package org . rubypeople . rdt . internal . core . pmd ; import java . io . File ; import java . io . IOException ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IFile ; public class CPD { private Map < String , SourceCode > source = new HashMap < String , SourceCode > ( ) ; private int minimumTileSize ; private Language language = new RubyLanguage ( ) ; private MatchAlgorithm matchAlgorithm ; private Tokens tokens = new Tokens ( ) ; private CPDListener listener = new CPDNullListener ( ) ; private Set < String > current = new HashSet < String > ( ) ; private CPD ( int minimumTileSize ) { this . minimumTileSize = minimumTileSize ; } public static Iterator < Match > findMatches ( List < IFile > files ) throws IOException { int minimumTokens = ; CPD cpd = new CPD ( minimumTokens ) ; cpd . add ( files ) ; cpd . go ( ) ; return cpd . getMatches ( ) ; } private void go ( ) { TokenEntry . clearImages ( ) ; matchAlgorithm = new MatchAlgorithm ( source , tokens , minimumTileSize , listener ) ; matchAlgorithm . findMatches ( ) ; } private Iterator < Match > getMatches ( ) { return matchAlgorithm . matches ( ) ; } private void add ( List < IFile > files ) throws IOException { for ( IFile file : files ) { add ( files . size ( ) , file ) ; } } private void add ( int fileCount , IFile file ) throws IOException { File realFile = file . getLocation ( ) . toFile ( ) ; String signature = realFile . getName ( ) + '' + realFile . length ( ) ; if ( current . contains ( signature ) ) { return ; } current . add ( signature ) ; if ( ! realFile . getCanonicalPath ( ) . equals ( realFile . getAbsolutePath ( ) ) ) { return ; } listener . addedFile ( fileCount , realFile ) ; SourceCode sourceCode = new SourceCode ( new SourceCode . FileCodeLoader ( realFile ) ) ; language . getTokenizer ( ) . tokenize ( sourceCode , tokens ) ; source . put ( sourceCode . getFileName ( ) , sourceCode ) ; } } package org . rubypeople . rdt . internal . core . pmd ; import java . io . FilenameFilter ; public interface Language { String fileSeparator = System . getProperty ( "" ) ; public Tokenizer getTokenizer ( ) ; public FilenameFilter getFileFilter ( ) ; } package org . rubypeople . rdt . internal . core . pmd ; import java . io . IOException ; public interface Tokenizer { void tokenize ( SourceCode tokens , Tokens tokenEntries ) throws IOException ; } package org . rubypeople . rdt . internal . core . pmd ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; public class MatchCollector { private MatchAlgorithm ma ; private Map < Match . MatchCode , Match > startMap = new HashMap < Match . MatchCode , Match > ( ) ; private Map fileMap = new HashMap ( ) ; public MatchCollector ( MatchAlgorithm ma ) { this . ma = ma ; } public void collect ( List marks ) { for ( int i = ; i < marks . size ( ) - ; i ++ ) { TokenEntry mark1 = ( TokenEntry ) marks . get ( i ) ; for ( int j = i + ; j < marks . size ( ) ; j ++ ) { TokenEntry mark2 = ( TokenEntry ) marks . get ( j ) ; int diff = mark1 . getIndex ( ) - mark2 . getIndex ( ) ; if ( - diff < ma . getMinimumTileSize ( ) ) { continue ; } if ( hasPreviousDupe ( mark1 , mark2 ) ) { continue ; } int dupes = countDuplicateTokens ( mark1 , mark2 ) ; if ( dupes < ma . getMinimumTileSize ( ) ) { continue ; } if ( diff + dupes >= ) { continue ; } determineMatch ( mark1 , mark2 , dupes ) ; } } } public List < Match > getMatches ( ) { List < Match > matchList = new ArrayList < Match > ( startMap . values ( ) ) ; Collections . sort ( matchList ) ; Set < Match . MatchCode > matchSet = new HashSet < Match . MatchCode > ( ) ; Match . MatchCode matchCode = new Match . MatchCode ( ) ; for ( int i = matchList . size ( ) ; i > ; i -- ) { Match match1 = matchList . get ( i - ) ; TokenEntry mark1 = match1 . getMarkSet ( ) . iterator ( ) . next ( ) ; matchSet . clear ( ) ; matchSet . add ( match1 . getMatchCode ( ) ) ; for ( int j = i - ; j > ; j -- ) { Match match2 = matchList . get ( j - ) ; if ( match1 . getTokenCount ( ) != match2 . getTokenCount ( ) ) { break ; } TokenEntry mark2 = null ; for ( Iterator iter = match2 . getMarkSet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { mark2 = ( TokenEntry ) iter . next ( ) ; if ( mark2 != mark1 ) { break ; } } int dupes = countDuplicateTokens ( mark1 , mark2 ) ; if ( dupes < match1 . getTokenCount ( ) ) { break ; } matchSet . add ( match2 . getMatchCode ( ) ) ; match1 . getMarkSet ( ) . addAll ( match2 . getMarkSet ( ) ) ; matchList . remove ( i - ) ; i -- ; } if ( matchSet . size ( ) == ) { continue ; } Set pruned = match1 . getMarkSet ( ) ; boolean done = false ; ArrayList a1 = new ArrayList ( match1 . getMarkSet ( ) ) ; Collections . sort ( a1 ) ; for ( int outer = ; outer < a1 . size ( ) - && ! done ; outer ++ ) { TokenEntry cmark1 = ( TokenEntry ) a1 . get ( outer ) ; for ( int inner = outer + ; inner < a1 . size ( ) && ! done ; inner ++ ) { TokenEntry cmark2 = ( TokenEntry ) a1 . get ( inner ) ; matchCode . setFirst ( cmark1 . getIndex ( ) ) ; matchCode . setSecond ( cmark2 . getIndex ( ) ) ; if ( ! matchSet . contains ( matchCode ) ) { if ( pruned . size ( ) > ) { pruned . remove ( cmark2 ) ; } if ( pruned . size ( ) == ) { done = true ; } } } } } return matchList ; } private void determineMatch ( TokenEntry mark1 , TokenEntry mark2 , int dupes ) { Match match = new Match ( dupes , mark1 , mark2 ) ; String fileKey = mark1 . getTokenSrcID ( ) + mark2 . getTokenSrcID ( ) ; List pairMatches = ( ArrayList ) fileMap . get ( fileKey ) ; if ( pairMatches == null ) { pairMatches = new ArrayList ( ) ; fileMap . put ( fileKey , pairMatches ) ; } boolean add = true ; for ( int i = ; i < pairMatches . size ( ) ; i ++ ) { Match other = ( Match ) pairMatches . get ( i ) ; if ( other . getFirstMark ( ) . getIndex ( ) + other . getTokenCount ( ) - mark1 . getIndex ( ) > ) { boolean ordered = other . getSecondMark ( ) . getIndex ( ) - mark2 . getIndex ( ) < ; if ( ( ordered && ( other . getEndIndex ( ) - mark2 . getIndex ( ) > ) ) || ( ! ordered && ( match . getEndIndex ( ) - other . getSecondMark ( ) . getIndex ( ) ) > ) ) { if ( other . getTokenCount ( ) >= match . getTokenCount ( ) ) { add = false ; break ; } else { pairMatches . remove ( i ) ; startMap . remove ( other . getMatchCode ( ) ) ; } } } } if ( add ) { pairMatches . add ( match ) ; startMap . put ( match . getMatchCode ( ) , match ) ; } } private boolean hasPreviousDupe ( TokenEntry mark1 , TokenEntry mark2 ) { if ( mark1 . getIndex ( ) == ) { return false ; } return ! matchEnded ( ma . tokenAt ( - , mark1 ) , ma . tokenAt ( - , mark2 ) ) ; } private int countDuplicateTokens ( TokenEntry mark1 , TokenEntry mark2 ) { int index = ; while ( ! matchEnded ( ma . tokenAt ( index , mark1 ) , ma . tokenAt ( index , mark2 ) ) ) { index ++ ; } return index ; } private boolean matchEnded ( TokenEntry token1 , TokenEntry token2 ) { return token1 . getIdentifier ( ) != token2 . getIdentifier ( ) || token1 == TokenEntry . EOF || token2 == TokenEntry . EOF ; } } package org . rubypeople . rdt . internal . core . pmd ; public interface PMD { public static final String EOL = System . getProperty ( "" , "" ) ; } package org . rubypeople . rdt . internal . core . pmd ; import java . util . List ; public class RubyTokenizer implements Tokenizer { private boolean downcaseString = true ; public void tokenize ( SourceCode tokens , Tokens tokenEntries ) { List code = tokens . getCode ( ) ; int curLineOffset = ; for ( int i = ; i < code . size ( ) ; i ++ ) { String currentLine = ( String ) code . get ( i ) ; int loc = ; int startOffset = ; while ( loc < currentLine . length ( ) ) { StringBuffer token = new StringBuffer ( ) ; startOffset = curLineOffset + loc ; loc = getTokenFromLine ( currentLine , token , loc ) ; if ( token . length ( ) > && ! isIgnorableString ( token . toString ( ) ) ) { if ( downcaseString ) { token = new StringBuffer ( token . toString ( ) . toLowerCase ( ) ) ; } tokenEntries . add ( new TokenEntry ( token . toString ( ) , tokens . getFileName ( ) , i + , startOffset , startOffset + token . length ( ) ) ) ; } } curLineOffset += currentLine . length ( ) ; } tokenEntries . add ( TokenEntry . getEOF ( ) ) ; } private int getTokenFromLine ( String line , StringBuffer token , int loc ) { for ( int j = loc ; j < line . length ( ) ; j ++ ) { char tok = line . charAt ( j ) ; if ( ! Character . isWhitespace ( tok ) && ! ignoreCharacter ( tok ) ) { if ( isComment ( tok ) ) { if ( token . length ( ) > ) { return j ; } else { return getCommentToken ( line , token , loc ) ; } } else if ( isString ( tok ) ) { if ( token . length ( ) > ) { return j ; } else { return parseString ( line , token , j , tok ) ; } } else { token . append ( tok ) ; } } else { if ( token . length ( ) > ) { return j ; } } loc = j ; } return loc + ; } private int parseString ( String line , StringBuffer token , int loc , char stringType ) { boolean escaped = false ; boolean done = false ; char tok = '' ; while ( ( loc < line . length ( ) ) && ! done ) { tok = line . charAt ( loc ) ; if ( escaped && tok == stringType ) { escaped = false ; } else if ( tok == stringType && ( token . length ( ) > ) ) { done = true ; } else if ( tok == '' ) { escaped = true ; } else { escaped = false ; } token . append ( tok ) ; loc ++ ; } return loc + ; } private boolean ignoreCharacter ( char tok ) { boolean result = false ; switch ( tok ) { case '' : case '' : case '' : case '' : case '' : case '' : result = true ; break ; default : result = false ; } return result ; } private boolean isString ( char tok ) { boolean result = false ; switch ( tok ) { case '' : case '' : result = true ; break ; default : result = false ; } return result ; } private boolean isComment ( char tok ) { return tok == '' ; } private int getCommentToken ( String line , StringBuffer token , int loc ) { while ( loc < line . length ( ) ) { token . append ( line . charAt ( loc ) ) ; loc ++ ; } return loc ; } private boolean isIgnorableString ( String token ) { return "" . equals ( token ) || "" . equals ( token ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . WorkingCopyOwner ; public class DefaultWorkingCopyOwner extends WorkingCopyOwner { public WorkingCopyOwner primaryBufferProvider ; public static final DefaultWorkingCopyOwner PRIMARY = new DefaultWorkingCopyOwner ( ) ; private DefaultWorkingCopyOwner ( ) { } public IBuffer createBuffer ( IRubyScript workingCopy ) { if ( this . primaryBufferProvider != null ) return this . primaryBufferProvider . createBuffer ( workingCopy ) ; return super . createBuffer ( workingCopy ) ; } public String toString ( ) { return "" ; } } package org . rubypeople . rdt . internal . core ; public abstract class MemberElementInfo extends SourceRefElementInfo { protected int nameStart = - ; protected int nameEnd = - ; public int getNameSourceEnd ( ) { return this . nameEnd ; } public int getNameSourceStart ( ) { return this . nameStart ; } protected void setNameSourceEnd ( int end ) { this . nameEnd = end ; } protected void setNameSourceStart ( int start ) { this . nameStart = start ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; public abstract class RubyField extends NamedMember implements IField { public RubyField ( RubyElement parent , String name ) { super ( parent , name ) ; } public boolean equals ( Object o ) { if ( ! ( o instanceof RubyField ) ) return false ; return super . equals ( o ) ; } public IRubyElement getPrimaryElement ( boolean checkOwner ) { if ( checkOwner ) { RubyScript cu = ( RubyScript ) getAncestor ( SCRIPT ) ; if ( cu . isPrimary ( ) ) return this ; } IRubyElement primaryParent = this . parent . getPrimaryElement ( false ) ; return ( ( IType ) primaryParent ) . getField ( this . name ) ; } public int getElementType ( ) { return IRubyElement . FIELD ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ISourceImport ; import org . rubypeople . rdt . core . RubyModelException ; public class RubyTypeElementInfo extends MemberElementInfo { protected static final ImportDeclarationElementInfo [ ] NO_IMPORTS = new ImportDeclarationElementInfo [ ] ; protected static final RubyField [ ] NO_FIELDS = new RubyField [ ] ; protected static final RubyMethod [ ] NO_METHODS = new RubyMethod [ ] ; protected static final RubyType [ ] NO_TYPES = new RubyType [ ] ; protected String superclassName ; protected String [ ] includedModuleNames ; protected String sourceFileName ; protected String namespaceName ; private ISourceImport [ ] imports ; protected IType handle = null ; public IType getEnclosingType ( ) { IRubyElement parent = this . handle . getParent ( ) ; if ( parent != null && parent . getElementType ( ) == IRubyElement . TYPE ) { try { return ( IType ) ( ( RubyElement ) parent ) . getElementInfo ( ) ; } catch ( RubyModelException e ) { return null ; } } return null ; } public IField [ ] getFields ( ) { RubyField [ ] fieldHandles = getFieldHandles ( ) ; int length = fieldHandles . length ; IField [ ] fields = new IField [ length ] ; for ( int i = ; i < length ; i ++ ) { try { IField field = ( IField ) fieldHandles [ i ] . getElementInfo ( ) ; fields [ i ] = field ; } catch ( RubyModelException e ) { } } return fields ; } public RubyField [ ] getFieldHandles ( ) { int length = this . children . length ; if ( length == ) return NO_FIELDS ; RubyField [ ] fields = new RubyField [ length ] ; int fieldIndex = ; for ( int i = ; i < length ; i ++ ) { IRubyElement child = this . children [ i ] ; if ( child instanceof RubyField ) fields [ fieldIndex ++ ] = ( RubyField ) child ; } if ( fieldIndex == ) return NO_FIELDS ; if ( fieldIndex < length ) System . arraycopy ( fields , , fields = new RubyField [ fieldIndex ] , , fieldIndex ) ; return fields ; } public String getFileName ( ) { return this . sourceFileName ; } public IType getHandle ( ) { return this . handle ; } public ISourceImport [ ] getImports ( ) { if ( this . imports == null ) { try { IImportDeclaration [ ] importDeclarations = this . handle . getRubyScript ( ) . getImports ( ) ; int length = importDeclarations . length ; if ( length == ) { this . imports = NO_IMPORTS ; } else { ISourceImport [ ] sourceImports = new ImportDeclarationElementInfo [ length ] ; for ( int i = ; i < length ; i ++ ) { sourceImports [ i ] = ( ImportDeclarationElementInfo ) ( ( RubyImport ) importDeclarations [ i ] ) . getElementInfo ( ) ; } this . imports = sourceImports ; } } catch ( RubyModelException e ) { this . imports = NO_IMPORTS ; } } return this . imports ; } public String [ ] getIncludedModuleNames ( ) { if ( this . handle . getElementName ( ) . length ( ) == ) { return null ; } return this . includedModuleNames ; } public IType [ ] getMemberTypes ( ) { RubyType [ ] memberTypeHandles = getMemberTypeHandles ( ) ; int length = memberTypeHandles . length ; IType [ ] memberTypes = new IType [ length ] ; for ( int i = ; i < length ; i ++ ) { try { IType type = ( IType ) memberTypeHandles [ i ] . getElementInfo ( ) ; memberTypes [ i ] = type ; } catch ( RubyModelException e ) { } } return memberTypes ; } public RubyType [ ] getMemberTypeHandles ( ) { int length = this . children . length ; if ( length == ) return NO_TYPES ; RubyType [ ] memberTypes = new RubyType [ length ] ; int typeIndex = ; for ( int i = ; i < length ; i ++ ) { IRubyElement child = this . children [ i ] ; if ( child instanceof RubyType ) memberTypes [ typeIndex ++ ] = ( RubyType ) child ; } if ( typeIndex == ) return NO_TYPES ; if ( typeIndex < length ) System . arraycopy ( memberTypes , , memberTypes = new RubyType [ typeIndex ] , , typeIndex ) ; return memberTypes ; } public IMethod [ ] getMethods ( ) { return getMethodHandles ( ) ; } public RubyMethod [ ] getMethodHandles ( ) { int length = this . children . length ; if ( length == ) return NO_METHODS ; RubyMethod [ ] methods = new RubyMethod [ length ] ; int methodIndex = ; for ( int i = ; i < length ; i ++ ) { IRubyElement child = this . children [ i ] ; if ( child instanceof RubyMethod ) methods [ methodIndex ++ ] = ( RubyMethod ) child ; } if ( methodIndex == ) return NO_METHODS ; if ( methodIndex < length ) System . arraycopy ( methods , , methods = new RubyMethod [ methodIndex ] , , methodIndex ) ; return methods ; } public char [ ] getName ( ) { return this . handle . getElementName ( ) . toCharArray ( ) ; } public String getNamespace ( ) { return this . namespaceName ; } public String getSuperclassName ( ) { if ( this . handle . getElementName ( ) . length ( ) == ) { String [ ] interfaceNames = this . includedModuleNames ; if ( interfaceNames != null && interfaceNames . length > ) { return interfaceNames [ ] ; } } return this . superclassName ; } protected void setHandle ( IType handle ) { this . handle = handle ; } protected void setNamespaceName ( String name ) { this . namespaceName = name ; } protected void setSourceFileName ( String name ) { this . sourceFileName = name ; } protected void setSuperclassName ( String superclassName ) { this . superclassName = superclassName ; } protected void setIncludedModuleNames ( String [ ] includedModuleNames ) { this . includedModuleNames = includedModuleNames ; } public String toString ( ) { return "" + this . handle . toString ( ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IProblemRequestor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . RubyModelException ; public class BecomeWorkingCopyOperation extends RubyModelOperation { private IProblemRequestor problemRequestor ; public BecomeWorkingCopyOperation ( RubyScript workingCopy , IProblemRequestor problemRequestor ) { super ( new IRubyElement [ ] { workingCopy } ) ; this . problemRequestor = problemRequestor ; } protected void executeOperation ( ) throws RubyModelException { RubyScript workingCopy = getWorkingCopy ( ) ; RubyModelManager . getRubyModelManager ( ) . getPerWorkingCopyInfo ( workingCopy , true , true , this . problemRequestor ) ; workingCopy . openWhenClosed ( workingCopy . createElementInfo ( ) , this . progressMonitor ) ; if ( ! workingCopy . isPrimary ( ) ) { RubyElementDelta delta = new RubyElementDelta ( getRubyModel ( ) ) ; delta . added ( workingCopy ) ; addDelta ( delta ) ; } else { if ( workingCopy . getResource ( ) . isAccessible ( ) ) { RubyElementDelta delta = new RubyElementDelta ( getRubyModel ( ) ) ; delta . changed ( workingCopy , IRubyElementDelta . F_PRIMARY_WORKING_COPY ) ; addDelta ( delta ) ; } else { RubyElementDelta delta = new RubyElementDelta ( this . getRubyModel ( ) ) ; delta . added ( workingCopy , IRubyElementDelta . F_PRIMARY_WORKING_COPY ) ; addDelta ( delta ) ; } } this . resultElements = new IRubyElement [ ] { workingCopy } ; } protected RubyScript getWorkingCopy ( ) { return ( RubyScript ) getElementToProcess ( ) ; } public boolean isReadOnly ( ) { return true ; } } package org . rubypeople . rdt . internal . core ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . io . InputStream ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModelStatus ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class CreateRubyScriptOperation extends RubyModelOperation { protected String fName ; protected String fSource = null ; public CreateRubyScriptOperation ( ISourceFolder parentElement , String name , String source , boolean force ) { super ( null , new IRubyElement [ ] { parentElement } , force ) ; fName = name ; fSource = source ; } protected void executeOperation ( ) throws RubyModelException { try { beginTask ( Messages . operation_createUnitProgress , ) ; RubyElementDelta delta = newRubyElementDelta ( ) ; IRubyScript unit = getRubyScript ( ) ; ISourceFolder pkg = ( ISourceFolder ) getParentElement ( ) ; IContainer folder = ( IContainer ) pkg . getResource ( ) ; worked ( ) ; IFile compilationUnitFile = folder . getFile ( new Path ( fName ) ) ; if ( compilationUnitFile . exists ( ) ) { if ( force ) { IBuffer buffer = unit . getBuffer ( ) ; if ( buffer == null ) return ; buffer . setContents ( fSource ) ; unit . save ( new NullProgressMonitor ( ) , false ) ; resultElements = new IRubyElement [ ] { unit } ; if ( ! Util . isExcluded ( unit ) && unit . getParent ( ) . exists ( ) ) { for ( int i = ; i < resultElements . length ; i ++ ) { delta . changed ( resultElements [ i ] , IRubyElementDelta . F_CONTENT ) ; } addDelta ( delta ) ; } } else { throw new RubyModelException ( new RubyModelStatus ( IRubyModelStatusConstants . NAME_COLLISION , Messages . bind ( Messages . status_nameCollision , compilationUnitFile . getFullPath ( ) . toString ( ) ) ) ) ; } } else { try { String encoding = null ; try { encoding = folder . getDefaultCharset ( ) ; } catch ( CoreException ce ) { } InputStream stream = new ByteArrayInputStream ( encoding == null ? fSource . getBytes ( ) : fSource . getBytes ( encoding ) ) ; createFile ( folder , unit . getElementName ( ) , stream , force ) ; resultElements = new IRubyElement [ ] { unit } ; if ( ! Util . isExcluded ( unit ) && unit . getParent ( ) . exists ( ) ) { for ( int i = ; i < resultElements . length ; i ++ ) { delta . added ( resultElements [ i ] ) ; } addDelta ( delta ) ; } } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } } worked ( ) ; } finally { done ( ) ; } } protected IRubyScript getRubyScript ( ) { return ( ( ISourceFolder ) getParentElement ( ) ) . getRubyScript ( fName ) ; } protected ISchedulingRule getSchedulingRule ( ) { IResource resource = getRubyScript ( ) . getResource ( ) ; IWorkspace workspace = resource . getWorkspace ( ) ; if ( resource . exists ( ) ) { return workspace . getRuleFactory ( ) . modifyRule ( resource ) ; } else { return workspace . getRuleFactory ( ) . createRule ( resource ) ; } } public IRubyModelStatus verify ( ) { if ( getParentElement ( ) == null ) { return new RubyModelStatus ( IRubyModelStatusConstants . NO_ELEMENTS_TO_PROCESS ) ; } if ( ! org . rubypeople . rdt . internal . core . util . Util . isERBLikeFileName ( fName ) ) { if ( RubyConventions . validateRubyScriptName ( fName ) . getSeverity ( ) == IStatus . ERROR ) { return new RubyModelStatus ( IRubyModelStatusConstants . INVALID_NAME , fName ) ; } } if ( fSource == null ) { return new RubyModelStatus ( IRubyModelStatusConstants . INVALID_CONTENTS ) ; } return RubyModelStatus . VERIFIED_OK ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . List ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; public class LogicalType extends RubyType implements IType { private IType [ ] types ; public LogicalType ( IType [ ] types ) { super ( ( RubyElement ) types [ ] . getParent ( ) , types [ ] . getElementName ( ) ) ; this . types = types ; } @ Override public IRubyElement [ ] getChildren ( ) throws RubyModelException { List < IRubyElement > children = new ArrayList < IRubyElement > ( ) ; for ( int i = ; i < types . length ; i ++ ) { IRubyElement [ ] subchildren = types [ i ] . getChildren ( ) ; for ( int j = ; j < subchildren . length ; j ++ ) { if ( subchildren [ j ] != null ) children . add ( subchildren [ j ] ) ; } } return ( IRubyElement [ ] ) children . toArray ( new IRubyElement [ children . size ( ) ] ) ; } @ Override public boolean hasChildren ( ) throws RubyModelException { for ( int i = ; i < types . length ; i ++ ) { if ( types [ i ] . hasChildren ( ) ) return true ; } return false ; } @ Override public boolean isModule ( ) { return types [ ] . isModule ( ) ; } public IType [ ] getOriginalTypes ( ) { return types ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . CompletionRequestor ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . ICodeAssist ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IProblemRequestor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . internal . codeassist . CompletionEngine ; import org . rubypeople . rdt . internal . compiler . ISourceElementRequestor ; import org . rubypeople . rdt . internal . core . buffer . BufferManager ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; import org . rubypeople . rdt . internal . core . util . Util ; public class RubyScript extends Openable implements IRubyScript { public WorkingCopyOwner owner ; protected String name ; public Node lastGoodAST ; public RubyScript ( SourceFolder parent , String name , WorkingCopyOwner owner ) { super ( parent ) ; this . name = name ; this . owner = owner ; } protected Object createElementInfo ( ) { return new RubyScriptElementInfo ( ) ; } protected boolean buildStructure ( OpenableElementInfo info , final IProgressMonitor pm , Map newElements , IResource underlyingResource ) throws RubyModelException { if ( ! isWorkingCopy ( ) ) { IStatus status = validateRubyScript ( underlyingResource ) ; if ( ! status . isOK ( ) ) throw newRubyModelException ( status ) ; } if ( ! isPrimary ( ) && getPerWorkingCopyInfo ( ) == null ) { throw newNotPresentException ( ) ; } RubyScriptElementInfo unitInfo = ( RubyScriptElementInfo ) info ; final char [ ] contents = getCharacters ( pm , unitInfo ) ; RubyModelManager . PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo ( ) ; IRubyProject project = getRubyProject ( ) ; boolean createAST ; HashMap < String , CategorizedProblem [ ] > problems ; if ( info instanceof ASTHolderCUInfo ) { ASTHolderCUInfo astHolder = ( ASTHolderCUInfo ) info ; createAST = true ; problems = astHolder . problems ; } else { createAST = false ; problems = null ; } boolean computeProblems = RubyProject . hasRubyNature ( project . getProject ( ) ) && perWorkingCopyInfo != null && perWorkingCopyInfo . isActive ( ) ; Node ast = null ; try { ISourceElementRequestor requestor = new RubyScriptStructureBuilder ( this , unitInfo , newElements ) ; SourceElementParser sp = new SourceElementParser ( requestor ) { @ Override public Object visitRootNode ( RootNode iVisited ) { lastGoodAST = iVisited ; return super . visitRootNode ( iVisited ) ; } } ; sp . parse ( contents , getElementName ( ) . toCharArray ( ) ) ; ast = lastGoodAST ; unitInfo . setIsStructureKnown ( true ) ; } catch ( SyntaxException e ) { unitInfo . setIsStructureKnown ( false ) ; unitInfo . setSyntaxException ( e ) ; } catch ( Exception e ) { RubyCore . log ( e ) ; } if ( underlyingResource == null ) { underlyingResource = getResource ( ) ; } unitInfo . timestamp = ( ( IFile ) underlyingResource ) . getModificationStamp ( ) ; if ( computeProblems ) { if ( problems == null ) { problems = new HashMap < String , CategorizedProblem [ ] > ( ) ; RubyScriptProblemFinder . process ( this , contents , problems , pm ) ; try { perWorkingCopyInfo . beginReporting ( ) ; for ( Iterator < CategorizedProblem [ ] > iteraror = problems . values ( ) . iterator ( ) ; iteraror . hasNext ( ) ; ) { CategorizedProblem [ ] categorizedProblems = iteraror . next ( ) ; if ( categorizedProblems == null ) continue ; for ( int i = , length = categorizedProblems . length ; i < length ; i ++ ) { perWorkingCopyInfo . acceptProblem ( categorizedProblems [ i ] ) ; } } } finally { perWorkingCopyInfo . endReporting ( ) ; } } else { RubyScriptProblemFinder . process ( this , contents , problems , pm ) ; } perWorkingCopyInfo . endReporting ( ) ; } if ( createAST ) { ( ( ASTHolderCUInfo ) info ) . ast = ( RootNode ) ast ; } return unitInfo . isStructureKnown ( ) ; } protected char [ ] getCharacters ( final IProgressMonitor pm , RubyScriptElementInfo unitInfo ) throws RubyModelException { IBuffer buffer = getBufferManager ( ) . getBuffer ( this ) ; if ( buffer == null ) { buffer = openBuffer ( pm , unitInfo ) ; } final char [ ] contents = buffer == null ? null : buffer . getCharacters ( ) ; return contents ; } protected void updateTimeStamp ( RubyScript original ) throws RubyModelException { long timeStamp = ( ( IFile ) original . getResource ( ) ) . getModificationStamp ( ) ; if ( timeStamp == IResource . NULL_STAMP ) { throw new RubyModelException ( new RubyModelStatus ( IRubyModelStatusConstants . INVALID_RESOURCE ) ) ; } ( ( RubyScriptElementInfo ) getElementInfo ( ) ) . timestamp = timeStamp ; } protected IStatus validateRubyScript ( IResource resource ) { ISourceFolderRoot root = getSourceFolderRoot ( ) ; if ( resource != null ) { char [ ] [ ] inclusionPatterns = ( ( SourceFolderRoot ) root ) . fullInclusionPatternChars ( ) ; char [ ] [ ] exclusionPatterns = ( ( SourceFolderRoot ) root ) . fullExclusionPatternChars ( ) ; if ( Util . isExcluded ( resource , inclusionPatterns , exclusionPatterns ) ) return new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_NOT_ON_CLASSPATH , this ) ; if ( ! resource . isAccessible ( ) ) return new RubyModelStatus ( IRubyModelStatusConstants . ELEMENT_DOES_NOT_EXIST , this ) ; } return RubyConventions . validateRubyScriptName ( getElementName ( ) ) ; } public IRubyElement getElementAt ( int position ) throws RubyModelException { IRubyElement e = getSourceElementAt ( position ) ; if ( e == this ) { return null ; } return e ; } public String getElementName ( ) { return this . name ; } public IResource getUnderlyingResource ( ) throws RubyModelException { if ( isWorkingCopy ( ) && ! isPrimary ( ) ) return null ; return super . getUnderlyingResource ( ) ; } public IResource getResource ( ) { SourceFolderRoot root = getSourceFolderRoot ( ) ; if ( root == null ) return null ; if ( root . isArchive ( ) ) { return root . getResource ( ) ; } else { return ( ( IContainer ) getParent ( ) . getResource ( ) ) . getFile ( new Path ( getElementName ( ) ) ) ; } } public void close ( ) throws RubyModelException { if ( getPerWorkingCopyInfo ( ) != null ) return ; super . close ( ) ; } protected void closing ( Object info ) { if ( getPerWorkingCopyInfo ( ) == null ) { super . closing ( info ) ; } } public WorkingCopyOwner getOwner ( ) { return isPrimary ( ) || ! isWorkingCopy ( ) ? null : this . owner ; } public IPath getPath ( ) { return getResource ( ) . getFullPath ( ) ; } public IRubyScript getPrimary ( ) { return ( IRubyScript ) getPrimaryElement ( true ) ; } public IRubyElement getPrimaryElement ( boolean checkOwner ) { if ( checkOwner && isPrimary ( ) ) return this ; return new RubyScript ( ( SourceFolder ) getParent ( ) , getElementName ( ) , DefaultWorkingCopyOwner . PRIMARY ) ; } public int getElementType ( ) { return RubyElement . SCRIPT ; } public void reconcile ( ) throws RubyModelException { reconcile ( false , null , null ) ; } public RootNode reconcile ( boolean forceProblemDetection , WorkingCopyOwner workingCopyOwner , IProgressMonitor monitor ) throws RubyModelException { if ( ! isWorkingCopy ( ) ) return null ; if ( workingCopyOwner == null ) workingCopyOwner = DefaultWorkingCopyOwner . PRIMARY ; ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation ( this , forceProblemDetection , workingCopyOwner ) ; op . runOperation ( monitor ) ; return op . ast ; } public IRubyScript getRubyScript ( ) { return this ; } public char [ ] getContents ( ) { try { IBuffer buffer = this . getBuffer ( ) ; return buffer == null ? null : buffer . getCharacters ( ) ; } catch ( RubyModelException e ) { return new char [ ] ; } } public ISourceRange getSourceRange ( ) throws RubyModelException { return ( ( RubyScriptElementInfo ) getElementInfo ( ) ) . getSourceRange ( ) ; } public IType getType ( String typeName ) { return new RubyType ( this , typeName ) ; } public String getSource ( ) throws RubyModelException { IBuffer buffer = getBuffer ( ) ; if ( buffer == null ) return "" ; return buffer . getContents ( ) ; } protected IBuffer openBuffer ( IProgressMonitor pm , Object info ) throws RubyModelException { boolean isWorkingCopy = isWorkingCopy ( ) ; IBuffer buffer = isWorkingCopy ? this . owner . createBuffer ( this ) : BufferManager . getDefaultBufferManager ( ) . createBuffer ( this ) ; if ( buffer == null ) return null ; if ( buffer . getCharacters ( ) == null ) { if ( isWorkingCopy ) { IRubyScript original ; if ( ! isPrimary ( ) && ( original = new RubyScript ( ( SourceFolder ) getParent ( ) , getElementName ( ) , DefaultWorkingCopyOwner . PRIMARY ) ) . isOpen ( ) ) { buffer . setContents ( original . getSource ( ) ) ; } else { IFile file = ( IFile ) getResource ( ) ; if ( file == null || ! file . exists ( ) ) { buffer . setContents ( new char [ ] ) ; } else { buffer . setContents ( Util . getResourceContentsAsCharArray ( file ) ) ; } } } else { IFile file = ( IFile ) this . getResource ( ) ; if ( file == null || ! file . exists ( ) ) throw newNotPresentException ( ) ; buffer . setContents ( Util . getResourceContentsAsCharArray ( file ) ) ; } } BufferManager bufManager = getBufferManager ( ) ; bufManager . addBuffer ( buffer ) ; buffer . addBufferChangedListener ( this ) ; return buffer ; } public boolean isPrimary ( ) { return this . owner == DefaultWorkingCopyOwner . PRIMARY ; } public boolean isWorkingCopy ( ) { return ! isPrimary ( ) || getPerWorkingCopyInfo ( ) != null ; } public RubyModelManager . PerWorkingCopyInfo getPerWorkingCopyInfo ( ) { return RubyModelManager . getRubyModelManager ( ) . getPerWorkingCopyInfo ( this , false , false , null ) ; } public IRubyScript getWorkingCopy ( IProgressMonitor monitor ) throws RubyModelException { return getWorkingCopy ( new WorkingCopyOwner ( ) { } , null , monitor ) ; } public IRubyScript getWorkingCopy ( WorkingCopyOwner workingCopyOwner , IProblemRequestor problemRequestor , IProgressMonitor monitor ) throws RubyModelException { if ( ! isPrimary ( ) ) return this ; RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; RubyScript workingCopy = new RubyScript ( ( SourceFolder ) getParent ( ) , getElementName ( ) , workingCopyOwner ) ; RubyModelManager . PerWorkingCopyInfo perWorkingCopyInfo = manager . getPerWorkingCopyInfo ( workingCopy , false , true , null ) ; if ( perWorkingCopyInfo != null ) { return perWorkingCopyInfo . getWorkingCopy ( ) ; } BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation ( workingCopy , problemRequestor ) ; op . runOperation ( monitor ) ; return workingCopy ; } public void becomeWorkingCopy ( IProblemRequestor requestor , IProgressMonitor monitor ) throws RubyModelException { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; RubyModelManager . PerWorkingCopyInfo perWorkingCopyInfo = manager . getPerWorkingCopyInfo ( this , false , true , null ) ; if ( perWorkingCopyInfo == null ) { close ( ) ; BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation ( this , requestor ) ; operation . runOperation ( monitor ) ; } } public void commitWorkingCopy ( boolean force , IProgressMonitor monitor ) throws RubyModelException { CommitWorkingCopyOperation op = new CommitWorkingCopyOperation ( this , force ) ; op . runOperation ( monitor ) ; } public boolean equals ( Object obj ) { if ( ! ( obj instanceof RubyScript ) ) return false ; RubyScript other = ( RubyScript ) obj ; return this . owner . equals ( other . owner ) && super . equals ( obj ) ; } public boolean exists ( ) { if ( getPerWorkingCopyInfo ( ) != null ) return true ; return isPrimary ( ) ; } public boolean canBeRemovedFromCache ( ) { if ( getPerWorkingCopyInfo ( ) != null ) return false ; return super . canBeRemovedFromCache ( ) ; } public boolean canBufferBeRemovedFromCache ( IBuffer buffer ) { if ( getPerWorkingCopyInfo ( ) != null ) return false ; return super . canBufferBeRemovedFromCache ( buffer ) ; } protected boolean hasBuffer ( ) { return true ; } public boolean hasResourceChanged ( ) { if ( ! isWorkingCopy ( ) ) return false ; Object info = RubyModelManager . getRubyModelManager ( ) . getInfo ( this ) ; if ( info == null ) return false ; return ( ( RubyScriptElementInfo ) info ) . timestamp != getResource ( ) . getModificationStamp ( ) ; } public boolean isConsistent ( ) { return ! RubyModelManager . getRubyModelManager ( ) . getElementsOutOfSynchWithBuffers ( ) . contains ( this ) ; } public void makeConsistent ( IProgressMonitor monitor ) throws RubyModelException { makeConsistent ( false , null , monitor ) ; } public RootNode makeConsistent ( boolean createAST , HashMap < String , CategorizedProblem [ ] > problems , IProgressMonitor monitor ) throws RubyModelException { if ( isConsistent ( ) ) return null ; if ( createAST ) { ASTHolderCUInfo info = new ASTHolderCUInfo ( ) ; info . problems = problems ; openWhenClosed ( info , monitor ) ; RootNode result = info . ast ; info . ast = null ; return result ; } openWhenClosed ( createElementInfo ( ) , monitor ) ; return null ; } public void discardWorkingCopy ( ) throws RubyModelException { DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation ( this ) ; op . runOperation ( null ) ; } public void save ( IProgressMonitor pm , boolean force ) throws RubyModelException { if ( isWorkingCopy ( ) ) { reconcile ( ) ; } else { super . save ( pm , force ) ; } } public IImportDeclaration [ ] getImports ( ) throws RubyModelException { IImportContainer container = getImportContainer ( ) ; if ( container . exists ( ) ) { IRubyElement [ ] elements = container . getChildren ( ) ; IImportDeclaration [ ] imprts = new IImportDeclaration [ elements . length ] ; System . arraycopy ( elements , , imprts , , elements . length ) ; return imprts ; } else if ( ! exists ( ) ) { throw newNotPresentException ( ) ; } else { return new IImportDeclaration [ ] ; } } public IImportDeclaration getImport ( String importName ) { return new RubyImport ( ( ImportContainer ) getImportContainer ( ) , importName ) ; } public IImportContainer getImportContainer ( ) { return new ImportContainer ( this ) ; } public IType [ ] getTypes ( ) throws RubyModelException { ArrayList < IRubyElement > list = getChildrenOfType ( TYPE ) ; IType [ ] array = new IType [ list . size ( ) ] ; list . toArray ( array ) ; return array ; } public IType findPrimaryType ( ) { String typeName = Util . getNameWithoutRubyLikeExtension ( getElementName ( ) ) ; typeName = Util . identifierToConstant ( typeName ) ; IType primaryType = getType ( typeName ) ; if ( primaryType . exists ( ) ) { return primaryType ; } try { IType [ ] types = getTypes ( ) ; if ( types != null && types . length > ) { return types [ ] ; } } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } return null ; } public IRubyElement [ ] codeSelect ( int offset , int length ) throws RubyModelException { return codeSelect ( offset , length , DefaultWorkingCopyOwner . PRIMARY ) ; } public IRubyElement [ ] codeSelect ( int offset , int length , WorkingCopyOwner workingCopyOwner ) throws RubyModelException { return super . codeSelect ( this , offset , length , workingCopyOwner ) ; } public void codeComplete ( int offset , CompletionRequestor requestor ) throws RubyModelException { CompletionEngine engine = new CompletionEngine ( requestor ) ; engine . complete ( this , offset ) ; } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner workingCopyOwner ) { switch ( token . charAt ( ) ) { case JEM_IMPORTDECLARATION : RubyElement container = ( RubyElement ) getImportContainer ( ) ; return container . getHandleFromMemento ( token , memento , workingCopyOwner ) ; case JEM_TYPE : if ( ! memento . hasMoreTokens ( ) ) return this ; String typeName = memento . nextToken ( ) ; RubyElement type = ( RubyElement ) getType ( typeName ) ; return type . getHandleFromMemento ( memento , workingCopyOwner ) ; } return null ; } protected char getHandleMementoDelimiter ( ) { return RubyElement . JEM_RUBYSCRIPT ; } public IType [ ] getAllTypes ( ) throws RubyModelException { IType [ ] types = getTypes ( ) ; int i ; ArrayList < IType > allTypes = new ArrayList < IType > ( types . length ) ; ArrayList < IType > typesToTraverse = new ArrayList < IType > ( types . length ) ; for ( i = ; i < types . length ; i ++ ) { typesToTraverse . add ( types [ i ] ) ; } while ( ! typesToTraverse . isEmpty ( ) ) { IType type = typesToTraverse . get ( ) ; typesToTraverse . remove ( type ) ; allTypes . add ( type ) ; types = type . getTypes ( ) ; for ( i = ; i < types . length ; i ++ ) { typesToTraverse . add ( types [ i ] ) ; } } IType [ ] arrayOfAllTypes = new IType [ allTypes . size ( ) ] ; allTypes . toArray ( arrayOfAllTypes ) ; return arrayOfAllTypes ; } } package org . rubypeople . rdt . internal . core ; import java . io . File ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IResourceDeltaVisitor ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . PerformanceStats ; import org . eclipse . core . runtime . SafeRunner ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . builder . RubyBuilder ; import org . rubypeople . rdt . internal . core . hierarchy . TypeHierarchy ; import org . rubypeople . rdt . internal . core . search . AbstractSearchScope ; import org . rubypeople . rdt . internal . core . search . RubyWorkspaceScope ; import org . rubypeople . rdt . internal . core . search . indexing . IndexManager ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Util ; public class DeltaProcessor { static class RootInfo { char [ ] [ ] inclusionPatterns ; char [ ] [ ] exclusionPatterns ; RubyProject project ; IPath rootPath ; int entryKind ; ISourceFolderRoot root ; RootInfo ( RubyProject project , IPath rootPath , char [ ] [ ] inclusionPatterns , char [ ] [ ] exclusionPatterns , int entryKind ) { this . project = project ; this . rootPath = rootPath ; this . inclusionPatterns = inclusionPatterns ; this . exclusionPatterns = exclusionPatterns ; this . entryKind = entryKind ; } ISourceFolderRoot getSourceFolderRoot ( IResource resource ) { if ( this . root == null ) { if ( resource != null ) { this . root = this . project . getSourceFolderRoot ( resource ) ; } else { Object target = RubyModel . getTarget ( this . rootPath , false ) ; if ( target instanceof IResource ) { this . root = this . project . getSourceFolderRoot ( ( IResource ) target ) ; } else { this . root = this . project . getSourceFolderRoot ( this . rootPath . toOSString ( ) ) ; } } } return this . root ; } boolean isRootOfProject ( IPath path ) { return this . rootPath . equals ( path ) && this . project . getProject ( ) . getFullPath ( ) . isPrefixOf ( path ) ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( "" ) ; if ( this . project == null ) { buffer . append ( "" ) ; } else { buffer . append ( this . project . getElementName ( ) ) ; } buffer . append ( "" ) ; if ( this . rootPath == null ) { buffer . append ( "" ) ; } else { buffer . append ( this . rootPath . toString ( ) ) ; } buffer . append ( "" ) ; if ( this . inclusionPatterns == null ) { buffer . append ( "" ) ; } else { for ( int i = , length = this . inclusionPatterns . length ; i < length ; i ++ ) { buffer . append ( new String ( this . inclusionPatterns [ i ] ) ) ; if ( i < length - ) { buffer . append ( "" ) ; } } } buffer . append ( "" ) ; if ( this . exclusionPatterns == null ) { buffer . append ( "" ) ; } else { for ( int i = , length = this . exclusionPatterns . length ; i < length ; i ++ ) { buffer . append ( new String ( this . exclusionPatterns [ i ] ) ) ; if ( i < length - ) { buffer . append ( "" ) ; } } } return buffer . toString ( ) ; } } private final static String EXTERNAL_JAR_ADDED = "" ; private final static String EXTERNAL_JAR_CHANGED = "" ; private final static String EXTERNAL_JAR_REMOVED = "" ; private final static String EXTERNAL_JAR_UNCHANGED = "" ; private final static String INTERNAL_JAR_IGNORE = "" ; public static final int DEFAULT_CHANGE_EVENT = ; private final static int NON_RUBY_RESOURCE = - ; public static boolean DEBUG ; public static boolean VERBOSE = false ; public static boolean PERF = false ; private final ModelUpdater modelUpdater = new ModelUpdater ( ) ; private HashSet < IRubyProject > projectCachesToReset = new HashSet < IRubyProject > ( ) ; public Map < IRubyProject , ISourceFolderRoot [ ] > removedRoots ; private HashSet < IRubyElement > refreshedElements ; private DeltaProcessingState state ; private RubyModelManager manager ; private boolean isFiring = true ; public ArrayList < IRubyElementDelta > rubyModelDeltas = new ArrayList < IRubyElementDelta > ( ) ; public HashMap < IRubyScript , IRubyElementDelta > reconcileDeltas = new HashMap < IRubyScript , IRubyElementDelta > ( ) ; private Openable currentElement ; private HashSet < IRubyProject > rootsToRefresh = new HashSet < IRubyProject > ( ) ; private RubyElementDelta currentDelta ; public int overridenEventType = - ; private SourceElementParser sourceElementParserCache ; public DeltaProcessor ( DeltaProcessingState state , RubyModelManager manager ) { this . state = state ; this . manager = manager ; } public void registerRubyModelDelta ( IRubyElementDelta delta ) { this . rubyModelDeltas . add ( delta ) ; } public void updateRubyModel ( IRubyElementDelta customDelta ) { if ( customDelta == null ) { for ( int i = , length = this . rubyModelDeltas . size ( ) ; i < length ; i ++ ) { IRubyElementDelta delta = this . rubyModelDeltas . get ( i ) ; this . modelUpdater . processRubyDelta ( delta ) ; } } else { this . modelUpdater . processRubyDelta ( customDelta ) ; } } public void fire ( IRubyElementDelta customDelta , int eventType ) { if ( ! this . isFiring ) return ; if ( DEBUG ) { System . out . println ( "" ) ; } IRubyElementDelta deltaToNotify ; if ( customDelta == null ) { deltaToNotify = this . mergeDeltas ( this . rubyModelDeltas ) ; } else { deltaToNotify = customDelta ; } if ( deltaToNotify != null ) { Iterator < AbstractSearchScope > scopes = this . manager . searchScopes . keySet ( ) . iterator ( ) ; while ( scopes . hasNext ( ) ) { AbstractSearchScope scope = scopes . next ( ) ; scope . processDelta ( deltaToNotify , eventType ) ; } RubyWorkspaceScope workspaceScope = this . manager . workspaceScope ; if ( workspaceScope != null ) workspaceScope . processDelta ( deltaToNotify , eventType ) ; } IElementChangedListener [ ] listeners = this . state . elementChangedListeners ; int [ ] listenerMask = this . state . elementChangedListenerMasks ; int listenerCount = this . state . elementChangedListenerCount ; switch ( eventType ) { case DEFAULT_CHANGE_EVENT : firePostChangeDelta ( deltaToNotify , listeners , listenerMask , listenerCount ) ; fireReconcileDelta ( listeners , listenerMask , listenerCount ) ; break ; case ElementChangedEvent . POST_CHANGE : firePostChangeDelta ( deltaToNotify , listeners , listenerMask , listenerCount ) ; fireReconcileDelta ( listeners , listenerMask , listenerCount ) ; break ; } } private IRubyElementDelta mergeDeltas ( Collection deltas ) { if ( deltas . size ( ) == ) return null ; if ( deltas . size ( ) == ) return ( IRubyElementDelta ) deltas . iterator ( ) . next ( ) ; if ( VERBOSE ) { System . out . println ( "" + deltas . size ( ) + "" + Thread . currentThread ( ) + "" ) ; } Iterator iterator = deltas . iterator ( ) ; RubyElementDelta rootDelta = new RubyElementDelta ( this . manager . rubyModel ) ; boolean insertedTree = false ; while ( iterator . hasNext ( ) ) { RubyElementDelta delta = ( RubyElementDelta ) iterator . next ( ) ; if ( VERBOSE ) { System . out . println ( delta . toString ( ) ) ; } IRubyElement element = delta . getElement ( ) ; if ( this . manager . rubyModel . equals ( element ) ) { IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int j = ; j < children . length ; j ++ ) { RubyElementDelta projectDelta = ( RubyElementDelta ) children [ j ] ; rootDelta . insertDeltaTree ( projectDelta . getElement ( ) , projectDelta ) ; insertedTree = true ; } IResourceDelta [ ] resourceDeltas = delta . getResourceDeltas ( ) ; if ( resourceDeltas != null ) { for ( int i = , length = resourceDeltas . length ; i < length ; i ++ ) { rootDelta . addResourceDelta ( resourceDeltas [ i ] ) ; insertedTree = true ; } } } else { rootDelta . insertDeltaTree ( element , delta ) ; insertedTree = true ; } } if ( insertedTree ) return rootDelta ; return null ; } private void firePostChangeDelta ( IRubyElementDelta deltaToNotify , IElementChangedListener [ ] listeners , int [ ] listenerMask , int listenerCount ) { if ( DEBUG ) { System . out . println ( "" + Thread . currentThread ( ) + "" ) ; System . out . println ( deltaToNotify == null ? "" : deltaToNotify . toString ( ) ) ; } if ( deltaToNotify != null ) { this . flush ( ) ; notifyListeners ( deltaToNotify , ElementChangedEvent . POST_CHANGE , listeners , listenerMask , listenerCount ) ; } } private void fireReconcileDelta ( IElementChangedListener [ ] listeners , int [ ] listenerMask , int listenerCount ) { IRubyElementDelta deltaToNotify = mergeDeltas ( this . reconcileDeltas . values ( ) ) ; if ( DEBUG ) { System . out . println ( "" + Thread . currentThread ( ) + "" ) ; System . out . println ( deltaToNotify == null ? "" : deltaToNotify . toString ( ) ) ; } if ( deltaToNotify != null ) { this . reconcileDeltas = new HashMap < IRubyScript , IRubyElementDelta > ( ) ; notifyListeners ( deltaToNotify , ElementChangedEvent . POST_RECONCILE , listeners , listenerMask , listenerCount ) ; } } public void flush ( ) { this . rubyModelDeltas = new ArrayList < IRubyElementDelta > ( ) ; } private void notifyListeners ( IRubyElementDelta deltaToNotify , int eventType , IElementChangedListener [ ] listeners , int [ ] listenerMask , int listenerCount ) { final ElementChangedEvent extraEvent = new ElementChangedEvent ( deltaToNotify , eventType ) ; for ( int i = ; i < listenerCount ; i ++ ) { if ( ( listenerMask [ i ] & eventType ) != ) { final IElementChangedListener listener = listeners [ i ] ; long start = - ; if ( VERBOSE ) { System . out . print ( "" + ( i + ) + "" + listener . toString ( ) ) ; start = System . currentTimeMillis ( ) ; } SafeRunner . run ( new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { Util . log ( exception , "" ) ; } public void run ( ) throws Exception { PerformanceStats stats = null ; if ( PERF ) { stats = PerformanceStats . getStats ( RubyModelManager . DELTA_LISTENER_PERF , listener ) ; stats . startRun ( ) ; } listener . elementChanged ( extraEvent ) ; if ( PERF ) { stats . endRun ( ) ; } } } ) ; if ( VERBOSE ) { System . out . println ( "" + ( System . currentTimeMillis ( ) - start ) + "" ) ; } } } } public void resourceChanged ( IResourceChangeEvent event ) { if ( event . getSource ( ) instanceof IWorkspace ) { int eventType = this . overridenEventType == - ? event . getType ( ) : this . overridenEventType ; IResource resource = event . getResource ( ) ; IResourceDelta delta = event . getDelta ( ) ; switch ( eventType ) { case IResourceChangeEvent . PRE_DELETE : try { if ( resource . getType ( ) == IResource . PROJECT && ( ( IProject ) resource ) . hasNature ( RubyCore . NATURE_ID ) ) { deleting ( ( IProject ) resource ) ; } } catch ( CoreException e ) { } return ; case IResourceChangeEvent . POST_CHANGE : if ( isAffectedBy ( delta ) ) { try { try { stopDeltas ( ) ; checkProjectsBeingAddedOrRemoved ( delta ) ; if ( this . refreshedElements != null ) { createExternalArchiveDelta ( null ) ; } IRubyElementDelta translatedDelta = processResourceDelta ( delta ) ; if ( translatedDelta != null ) { registerRubyModelDelta ( translatedDelta ) ; } } finally { startDeltas ( ) ; } IElementChangedListener [ ] listeners ; int listenerCount ; synchronized ( this . state ) { listeners = this . state . elementChangedListeners ; listenerCount = this . state . elementChangedListenerCount ; } notifyTypeHierarchies ( listeners , listenerCount ) ; fire ( null , ElementChangedEvent . POST_CHANGE ) ; } finally { this . state . resetOldRubyProjectNames ( ) ; this . removedRoots = null ; } } return ; case IResourceChangeEvent . PRE_BUILD : DeltaProcessingState . ProjectUpdateInfo [ ] updates = this . state . removeAllProjectUpdates ( ) ; if ( updates != null ) { for ( int i = , length = updates . length ; i < length ; i ++ ) { try { updates [ i ] . updateProjectReferencesIfNecessary ( ) ; } catch ( RubyModelException e ) { } } } if ( isAffectedBy ( delta ) ) { updateLoadpathMarkers ( delta , updates ) ; RubyBuilder . buildStarting ( ) ; } return ; case IResourceChangeEvent . POST_BUILD : RubyBuilder . buildFinished ( ) ; return ; } } } private void notifyTypeHierarchies ( IElementChangedListener [ ] listeners , int listenerCount ) { for ( int i = ; i < listenerCount ; i ++ ) { final IElementChangedListener listener = listeners [ i ] ; if ( ! ( listener instanceof TypeHierarchy ) ) continue ; SafeRunner . run ( new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { Util . log ( exception , "" ) ; } public void run ( ) throws Exception { TypeHierarchy typeHierarchy = ( TypeHierarchy ) listener ; if ( typeHierarchy . hasFineGrainChanges ( ) ) { typeHierarchy . needsRefresh = true ; typeHierarchy . fireChange ( ) ; } } } ) ; } } private void updateLoadpathMarkers ( IResourceDelta delta , DeltaProcessingState . ProjectUpdateInfo [ ] updates ) { Map < RubyProject , ILoadpathEntry [ ] > preferredClasspaths = new HashMap < RubyProject , ILoadpathEntry [ ] > ( ) ; Map preferredOutputs = new HashMap ( ) ; HashSet < IPath > affectedProjects = new HashSet < IPath > ( ) ; RubyModel . flushExternalFileCache ( ) ; updateLoadpathMarkers ( delta , affectedProjects , preferredClasspaths , preferredOutputs ) ; if ( ! affectedProjects . isEmpty ( ) ) { IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IProject [ ] projects = workspaceRoot . getProjects ( ) ; int length = projects . length ; for ( int i = ; i < length ; i ++ ) { IProject project = projects [ i ] ; RubyProject rubyProject = ( RubyProject ) RubyCore . create ( project ) ; if ( preferredClasspaths . get ( rubyProject ) == null ) { try { IPath projectPath = project . getFullPath ( ) ; ILoadpathEntry [ ] classpath = rubyProject . getResolvedLoadpath ( true , false , false ) ; for ( int j = , cpLength = classpath . length ; j < cpLength ; j ++ ) { ILoadpathEntry entry = classpath [ j ] ; switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_PROJECT : if ( affectedProjects . contains ( entry . getPath ( ) ) ) { rubyProject . updateLoadpathMarkers ( null , null ) ; } break ; case ILoadpathEntry . CPE_LIBRARY : IPath entryPath = entry . getPath ( ) ; IPath libProjectPath = entryPath . removeLastSegments ( entryPath . segmentCount ( ) - ) ; if ( ! libProjectPath . equals ( projectPath ) && affectedProjects . contains ( libProjectPath ) ) { rubyProject . updateLoadpathMarkers ( null , null ) ; } break ; } } } catch ( RubyModelException e ) { } } } } if ( ! affectedProjects . isEmpty ( ) || updates != null ) { if ( updates != null ) { for ( int i = , length = updates . length ; i < length ; i ++ ) { DeltaProcessingState . ProjectUpdateInfo info = updates [ i ] ; if ( ! preferredClasspaths . containsKey ( info . project ) ) preferredClasspaths . put ( info . project , info . newResolvedPath ) ; } } try { RubyProject . updateAllCycleMarkers ( preferredClasspaths ) ; } catch ( RubyModelException e ) { } } } private void updateLoadpathMarkers ( IResourceDelta delta , HashSet < IPath > affectedProjects , Map preferredClasspaths , Map preferredOutputs ) { IResource resource = delta . getResource ( ) ; boolean processChildren = false ; switch ( resource . getType ( ) ) { case IResource . ROOT : if ( delta . getKind ( ) == IResourceDelta . CHANGED ) { processChildren = true ; } break ; case IResource . PROJECT : IProject project = ( IProject ) resource ; int kind = delta . getKind ( ) ; boolean isRubyProject = RubyProject . hasRubyNature ( project ) ; switch ( kind ) { case IResourceDelta . ADDED : processChildren = isRubyProject ; affectedProjects . add ( project . getFullPath ( ) ) ; break ; case IResourceDelta . CHANGED : processChildren = isRubyProject ; if ( ( delta . getFlags ( ) & IResourceDelta . OPEN ) != ) { affectedProjects . add ( project . getFullPath ( ) ) ; if ( isRubyProject ) { RubyProject rubyProject = ( RubyProject ) RubyCore . create ( project ) ; rubyProject . updateLoadpathMarkers ( preferredClasspaths , preferredOutputs ) ; } } else if ( ( delta . getFlags ( ) & IResourceDelta . DESCRIPTION ) != ) { boolean wasRubyProject = this . state . findRubyProject ( project . getName ( ) ) != null ; if ( wasRubyProject && ! isRubyProject ) { affectedProjects . add ( project . getFullPath ( ) ) ; RubyProject javaProject = ( RubyProject ) RubyCore . create ( project ) ; javaProject . flushLoadpathProblemMarkers ( true , true ) ; RubyBuilder . removeProblemsAndTasksFor ( project ) ; } } else if ( isRubyProject ) { try { RubyProject javaProject = ( RubyProject ) RubyCore . create ( project ) ; javaProject . getResolvedLoadpath ( true , true , false ) ; } catch ( RubyModelException e ) { } } break ; case IResourceDelta . REMOVED : affectedProjects . add ( project . getFullPath ( ) ) ; break ; } break ; case IResource . FILE : IFile file = ( IFile ) resource ; if ( file . getName ( ) . equals ( RubyProject . LOADPATH_FILENAME ) ) { affectedProjects . add ( file . getProject ( ) . getFullPath ( ) ) ; RubyProject rubyProject = ( RubyProject ) RubyCore . create ( file . getProject ( ) ) ; rubyProject . updateLoadpathMarkers ( preferredClasspaths , preferredOutputs ) ; break ; } break ; } if ( processChildren ) { IResourceDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { updateLoadpathMarkers ( children [ i ] , affectedProjects , preferredClasspaths , preferredOutputs ) ; } } } private IRubyElementDelta processResourceDelta ( IResourceDelta changes ) { try { IRubyModel model = this . manager . getRubyModel ( ) ; if ( ! model . isOpen ( ) ) { try { model . open ( null ) ; } catch ( RubyModelException e ) { if ( VERBOSE ) { e . printStackTrace ( ) ; } return null ; } } this . state . initializeRoots ( ) ; this . currentElement = null ; IResourceDelta [ ] deltas = changes . getAffectedChildren ( ) ; for ( int i = ; i < deltas . length ; i ++ ) { IResourceDelta delta = deltas [ i ] ; IResource res = delta . getResource ( ) ; RootInfo rootInfo = null ; int elementType ; IProject proj = ( IProject ) res ; boolean wasRubyProject = this . state . findRubyProject ( proj . getName ( ) ) != null ; boolean isRubyProject = RubyProject . hasRubyNature ( proj ) ; if ( ! wasRubyProject && ! isRubyProject ) { elementType = NON_RUBY_RESOURCE ; } else { rootInfo = this . enclosingRootInfo ( res . getFullPath ( ) , delta . getKind ( ) ) ; if ( rootInfo != null && rootInfo . isRootOfProject ( res . getFullPath ( ) ) ) { elementType = IRubyElement . SOURCE_FOLDER_ROOT ; } else { elementType = IRubyElement . RUBY_PROJECT ; } } this . traverseDelta ( delta , elementType , rootInfo ) ; if ( elementType == NON_RUBY_RESOURCE || ( wasRubyProject != isRubyProject && ( delta . getKind ( ) ) == IResourceDelta . CHANGED ) ) { try { nonRubyResourcesChanged ( ( RubyModel ) model , delta ) ; } catch ( RubyModelException e ) { } } } resetProjectCaches ( ) ; return this . currentDelta ; } finally { this . currentDelta = null ; this . rootsToRefresh . clear ( ) ; this . projectCachesToReset . clear ( ) ; } } private RootInfo enclosingRootInfo ( IPath path , int kind ) { while ( path != null && path . segmentCount ( ) > ) { RootInfo rootInfo = this . rootInfo ( path , kind ) ; if ( rootInfo != null ) return rootInfo ; path = path . removeLastSegments ( ) ; } return null ; } private RootInfo rootInfo ( IPath path , int kind ) { if ( kind == IResourceDelta . REMOVED ) { return ( RootInfo ) this . state . oldRoots . get ( path ) ; } return ( RootInfo ) this . state . roots . get ( path ) ; } private void refreshSourceFolderRoots ( ) { Iterator iterator = this . rootsToRefresh . iterator ( ) ; while ( iterator . hasNext ( ) ) { RubyProject project = ( RubyProject ) iterator . next ( ) ; project . updateSourceFolderRoots ( ) ; } } private RubyElementDelta currentDelta ( ) { if ( this . currentDelta == null ) { this . currentDelta = new RubyElementDelta ( this . manager . getRubyModel ( ) ) ; } return this . currentDelta ; } private void resetProjectCaches ( ) { Iterator iterator = this . projectCachesToReset . iterator ( ) ; HashMap projectDepencies = this . state . projectDependencies ; HashSet < IRubyProject > affectedDependents = new HashSet < IRubyProject > ( ) ; while ( iterator . hasNext ( ) ) { RubyProject project = ( RubyProject ) iterator . next ( ) ; project . resetCaches ( ) ; addDependentProjects ( project , projectDepencies , affectedDependents ) ; } iterator = affectedDependents . iterator ( ) ; while ( iterator . hasNext ( ) ) { RubyProject project = ( RubyProject ) iterator . next ( ) ; project . resetCaches ( ) ; } } private void addDependentProjects ( IRubyProject project , HashMap projectDependencies , HashSet < IRubyProject > result ) { IRubyProject [ ] dependents = ( IRubyProject [ ] ) projectDependencies . get ( project ) ; if ( dependents == null ) return ; for ( int i = , length = dependents . length ; i < length ; i ++ ) { IRubyProject dependent = dependents [ i ] ; if ( result . contains ( dependent ) ) continue ; result . add ( dependent ) ; addDependentProjects ( dependent , projectDependencies , result ) ; } } private void nonRubyResourcesChanged ( Openable element , IResourceDelta delta ) throws RubyModelException { if ( element . isOpen ( ) ) { RubyElementInfo info = ( RubyElementInfo ) element . getElementInfo ( ) ; switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : ( ( RubyModelInfo ) info ) . nonRubyResources = null ; currentDelta ( ) . addResourceDelta ( delta ) ; return ; case IRubyElement . RUBY_PROJECT : ( ( RubyProjectElementInfo ) info ) . setNonRubyResources ( null ) ; RubyProject project = ( RubyProject ) element ; SourceFolderRoot projectRoot = ( SourceFolderRoot ) project . getSourceFolderRoot ( project . getProject ( ) ) ; if ( projectRoot . isOpen ( ) ) { ( ( SourceFolderRootInfo ) projectRoot . getElementInfo ( ) ) . setNonRubyResources ( null ) ; } break ; case IRubyElement . SOURCE_FOLDER : ( ( SourceFolderInfo ) info ) . setNonRubyResources ( null ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : ( ( SourceFolderRootInfo ) info ) . setNonRubyResources ( null ) ; } } RubyElementDelta current = currentDelta ( ) ; RubyElementDelta elementDelta = current . find ( element ) ; if ( elementDelta == null ) { elementDelta = current . changed ( element , IRubyElementDelta . F_CONTENT ) ; } elementDelta . addResourceDelta ( delta ) ; } private void stopDeltas ( ) { this . isFiring = false ; } private void startDeltas ( ) { this . isFiring = true ; } private void deleting ( IProject project ) { try { RubyProject rubyProject = ( RubyProject ) RubyCore . create ( project ) ; if ( this . removedRoots == null ) { this . removedRoots = new HashMap < IRubyProject , ISourceFolderRoot [ ] > ( ) ; } if ( rubyProject . isOpen ( ) ) { this . removedRoots . put ( rubyProject , rubyProject . getSourceFolderRoots ( ) ) ; } else { this . removedRoots . put ( rubyProject , rubyProject . computeSourceFolderRoots ( rubyProject . getResolvedLoadpath ( true , false , false ) , false , null ) ) ; } rubyProject . close ( ) ; this . state . getOldRubyProjecNames ( ) ; this . removeFromParentInfo ( rubyProject ) ; this . manager . resetProjectPreferences ( rubyProject ) ; } catch ( RubyModelException e ) { } } private void removeFromParentInfo ( Openable child ) { Openable parent = ( Openable ) child . getParent ( ) ; if ( parent != null && parent . isOpen ( ) ) { try { RubyElementInfo info = ( RubyElementInfo ) parent . getElementInfo ( ) ; info . removeChild ( child ) ; } catch ( RubyModelException e ) { } } } private boolean isAffectedBy ( IResourceDelta rootDelta ) { if ( rootDelta != null ) { class FoundRelevantDeltaException extends RuntimeException { private static final long serialVersionUID = ; } try { rootDelta . accept ( new IResourceDeltaVisitor ( ) { public boolean visit ( IResourceDelta delta ) { switch ( delta . getKind ( ) ) { case IResourceDelta . ADDED : case IResourceDelta . REMOVED : throw new FoundRelevantDeltaException ( ) ; case IResourceDelta . CHANGED : if ( delta . getAffectedChildren ( ) . length == && ( delta . getFlags ( ) & ~ ( IResourceDelta . SYNC | IResourceDelta . MARKERS ) ) != ) { throw new FoundRelevantDeltaException ( ) ; } } return true ; } } ) ; } catch ( FoundRelevantDeltaException e ) { return true ; } catch ( CoreException e ) { } } return false ; } private void checkProjectsBeingAddedOrRemoved ( IResourceDelta delta ) { IResource resource = delta . getResource ( ) ; boolean processChildren = false ; switch ( resource . getType ( ) ) { case IResource . ROOT : this . state . getOldRubyProjecNames ( ) ; processChildren = true ; break ; case IResource . PROJECT : IProject project = ( IProject ) resource ; RubyProject rubyProject = ( RubyProject ) RubyCore . create ( project ) ; switch ( delta . getKind ( ) ) { case IResourceDelta . ADDED : this . manager . batchContainerInitializations = true ; this . addToRootsToRefreshWithDependents ( rubyProject ) ; if ( RubyProject . hasRubyNature ( project ) ) { this . addToParentInfo ( rubyProject ) ; try { this . state . updateProjectReferences ( rubyProject , null , null , null , false ) ; } catch ( RubyModelException e1 ) { } } this . state . rootsAreStale = true ; break ; case IResourceDelta . CHANGED : if ( ( delta . getFlags ( ) & IResourceDelta . OPEN ) != ) { this . manager . batchContainerInitializations = true ; this . addToRootsToRefreshWithDependents ( rubyProject ) ; if ( project . isOpen ( ) ) { if ( RubyProject . hasRubyNature ( project ) ) { this . addToParentInfo ( rubyProject ) ; } } else { try { rubyProject . close ( ) ; } catch ( RubyModelException e ) { } this . removeFromParentInfo ( rubyProject ) ; this . manager . removePerProjectInfo ( rubyProject ) ; this . manager . containerRemove ( rubyProject ) ; } this . state . rootsAreStale = true ; } else if ( ( delta . getFlags ( ) & IResourceDelta . DESCRIPTION ) != ) { boolean wasJavaProject = this . state . findRubyProject ( project . getName ( ) ) != null ; boolean isJavaProject = RubyProject . hasRubyNature ( project ) ; if ( wasJavaProject != isJavaProject ) { this . manager . batchContainerInitializations = true ; this . addToRootsToRefreshWithDependents ( rubyProject ) ; if ( isJavaProject ) { this . addToParentInfo ( rubyProject ) ; } else { this . manager . removePerProjectInfo ( ( RubyProject ) RubyCore . create ( project ) ) ; this . manager . containerRemove ( rubyProject ) ; try { rubyProject . close ( ) ; } catch ( RubyModelException e ) { } this . removeFromParentInfo ( rubyProject ) ; } this . state . rootsAreStale = true ; } else { if ( isJavaProject ) { this . addToParentInfo ( rubyProject ) ; processChildren = true ; } } } else { if ( RubyProject . hasRubyNature ( project ) ) { this . addToParentInfo ( rubyProject ) ; processChildren = true ; } } break ; case IResourceDelta . REMOVED : this . manager . batchContainerInitializations = true ; this . manager . removePerProjectInfo ( rubyProject ) ; this . manager . containerRemove ( rubyProject ) ; this . state . rootsAreStale = true ; break ; } addForRefresh ( rubyProject ) ; break ; case IResource . FILE : IFile file = ( IFile ) resource ; if ( file . getName ( ) . equals ( RubyProject . LOADPATH_FILENAME ) ) { this . manager . batchContainerInitializations = true ; reconcileLoadpathFileUpdate ( delta , ( RubyProject ) RubyCore . create ( file . getProject ( ) ) ) ; this . state . rootsAreStale = true ; } break ; } if ( processChildren ) { IResourceDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { checkProjectsBeingAddedOrRemoved ( children [ i ] ) ; } } } private void addToRootsToRefreshWithDependents ( IRubyProject rubyProject ) { this . rootsToRefresh . add ( rubyProject ) ; this . addDependentProjects ( rubyProject , this . state . projectDependencies , this . rootsToRefresh ) ; } public void addForRefresh ( IRubyElement element ) { if ( this . refreshedElements == null ) { this . refreshedElements = new HashSet < IRubyElement > ( ) ; } this . refreshedElements . add ( element ) ; } private void addToParentInfo ( Openable child ) { Openable parent = ( Openable ) child . getParent ( ) ; if ( parent != null && parent . isOpen ( ) ) { try { RubyElementInfo info = ( RubyElementInfo ) parent . getElementInfo ( ) ; info . addChild ( child ) ; } catch ( RubyModelException e ) { } } } private void traverseDelta ( IResourceDelta delta , int elementType , RootInfo rootInfo ) { IResource res = delta . getResource ( ) ; if ( this . currentElement == null && rootInfo != null ) { this . currentElement = rootInfo . project ; } boolean processChildren = true ; if ( res instanceof IProject ) { processChildren = updateCurrentDeltaAndIndex ( delta , elementType == IRubyElement . SOURCE_FOLDER_ROOT ? IRubyElement . RUBY_PROJECT : elementType , rootInfo ) ; } else if ( rootInfo != null ) { processChildren = this . updateCurrentDeltaAndIndex ( delta , elementType , rootInfo ) ; } else { processChildren = true ; } if ( processChildren ) { IResourceDelta [ ] children = delta . getAffectedChildren ( ) ; boolean oneChildOnLoadpath = false ; int length = children . length ; IResourceDelta [ ] orphanChildren = null ; Openable parent = null ; boolean isValidParent = true ; for ( int i = ; i < length ; i ++ ) { IResourceDelta child = children [ i ] ; IResource childRes = child . getResource ( ) ; IPath childPath = childRes . getFullPath ( ) ; int childKind = child . getKind ( ) ; RootInfo childRootInfo = this . rootInfo ( childPath , childKind ) ; if ( childRootInfo != null && ! childRootInfo . isRootOfProject ( childPath ) ) { childRootInfo = null ; } int childType = this . elementType ( childRes , childKind , elementType , rootInfo == null ? childRootInfo : rootInfo ) ; boolean isResFilteredFromOutput = false ; boolean isNestedRoot = rootInfo != null && childRootInfo != null ; if ( ! isResFilteredFromOutput && ! isNestedRoot ) { this . traverseDelta ( child , childType , rootInfo == null ? childRootInfo : rootInfo ) ; if ( childType == NON_RUBY_RESOURCE ) { if ( rootInfo != null ) { if ( ! isValidParent ) continue ; if ( parent == null ) { if ( this . currentElement == null || ! rootInfo . project . equals ( this . currentElement . getRubyProject ( ) ) ) { this . currentElement = rootInfo . project ; } if ( elementType == IRubyElement . RUBY_PROJECT || ( elementType == IRubyElement . SOURCE_FOLDER_ROOT && res instanceof IProject ) ) { parent = rootInfo . project ; } else { parent = this . createElement ( res , elementType , rootInfo ) ; } if ( parent == null ) { isValidParent = false ; continue ; } } try { nonRubyResourcesChanged ( parent , child ) ; } catch ( RubyModelException e ) { } } else { if ( orphanChildren == null ) orphanChildren = new IResourceDelta [ length ] ; orphanChildren [ i ] = child ; } } else { oneChildOnLoadpath = true ; } } else { oneChildOnLoadpath = true ; } if ( isNestedRoot || ( childRootInfo == null && ( childRootInfo = this . rootInfo ( childPath , childKind ) ) != null ) ) { this . traverseDelta ( child , IRubyElement . SOURCE_FOLDER_ROOT , childRootInfo ) ; } ArrayList < RootInfo > rootList ; if ( ( rootList = this . otherRootsInfo ( childPath , childKind ) ) != null ) { Iterator < RootInfo > iterator = rootList . iterator ( ) ; while ( iterator . hasNext ( ) ) { childRootInfo = iterator . next ( ) ; this . traverseDelta ( child , IRubyElement . SOURCE_FOLDER_ROOT , childRootInfo ) ; } } } if ( orphanChildren != null && ( oneChildOnLoadpath || res instanceof IProject ) ) { IProject rscProject = res . getProject ( ) ; RubyProject adoptiveProject = ( RubyProject ) RubyCore . create ( rscProject ) ; if ( adoptiveProject != null && RubyProject . hasRubyNature ( rscProject ) ) { for ( int i = ; i < length ; i ++ ) { if ( orphanChildren [ i ] != null ) { try { nonRubyResourcesChanged ( adoptiveProject , orphanChildren [ i ] ) ; } catch ( RubyModelException e ) { } } } } } } } private ArrayList < RootInfo > otherRootsInfo ( IPath path , int kind ) { if ( kind == IResourceDelta . REMOVED ) { return this . state . oldOtherRoots . get ( path ) ; } return this . state . otherRoots . get ( path ) ; } private void close ( Openable element ) { try { element . close ( ) ; } catch ( RubyModelException e ) { } } private Openable createElement ( IResource resource , int elementType , RootInfo rootInfo ) { if ( resource == null ) return null ; IPath path = resource . getFullPath ( ) ; IRubyElement element = null ; switch ( elementType ) { case IRubyElement . RUBY_PROJECT : if ( resource instanceof IProject ) { this . popUntilPrefixOf ( path ) ; if ( this . currentElement != null && this . currentElement . getElementType ( ) == IRubyElement . RUBY_PROJECT && ( ( IRubyProject ) this . currentElement ) . getProject ( ) . equals ( resource ) ) { return this . currentElement ; } if ( rootInfo != null && rootInfo . project . getProject ( ) . equals ( resource ) ) { element = rootInfo . project ; break ; } IProject proj = ( IProject ) resource ; if ( RubyProject . hasRubyNature ( proj ) ) { element = RubyCore . create ( proj ) ; } else { element = this . manager . getRubyModel ( ) . findRubyProject ( proj ) ; } } break ; case IRubyElement . SOURCE_FOLDER_ROOT : element = rootInfo == null ? RubyCore . create ( resource ) : rootInfo . getSourceFolderRoot ( resource ) ; break ; case IRubyElement . SOURCE_FOLDER : if ( rootInfo != null ) { if ( rootInfo . project . contains ( resource ) ) { SourceFolderRoot root = ( SourceFolderRoot ) rootInfo . getSourceFolderRoot ( null ) ; IPath pkgPath = path . removeFirstSegments ( rootInfo . rootPath . segmentCount ( ) ) ; String [ ] pkgName = pkgPath . segments ( ) ; element = root . getSourceFolder ( pkgName ) ; } } else { this . popUntilPrefixOf ( path ) ; if ( this . currentElement == null ) { element = RubyCore . create ( resource ) ; } else { SourceFolderRoot root = this . currentElement . getSourceFolderRoot ( ) ; if ( root == null ) { element = RubyCore . create ( resource ) ; } else if ( ( ( RubyProject ) root . getRubyProject ( ) ) . contains ( resource ) ) { IPath pkgPath = path . removeFirstSegments ( root . getPath ( ) . segmentCount ( ) ) ; String [ ] pkgName = pkgPath . segments ( ) ; element = root . getSourceFolder ( pkgName ) ; } } } break ; case IRubyElement . SCRIPT : this . popUntilPrefixOf ( path ) ; element = RubyCore . create ( resource ) ; break ; } if ( element == null ) return null ; this . currentElement = ( Openable ) element ; return this . currentElement ; } private void popUntilPrefixOf ( IPath path ) { while ( this . currentElement != null ) { IPath currentElementPath = null ; IResource currentElementResource = this . currentElement . getResource ( ) ; if ( currentElementResource != null ) { currentElementPath = currentElementResource . getFullPath ( ) ; } if ( currentElementPath != null ) { if ( currentElementPath . isPrefixOf ( path ) ) { return ; } } this . currentElement = ( Openable ) this . currentElement . getParent ( ) ; } } private void elementAdded ( Openable element , IResourceDelta delta , RootInfo rootInfo ) { int elementType = element . getElementType ( ) ; if ( elementType == IRubyElement . RUBY_PROJECT ) { if ( delta != null && RubyProject . hasRubyNature ( ( IProject ) delta . getResource ( ) ) ) { addToParentInfo ( element ) ; if ( ( delta . getFlags ( ) & IResourceDelta . MOVED_FROM ) != ) { Openable movedFromElement = ( Openable ) element . getRubyModel ( ) . getRubyProject ( delta . getMovedFromPath ( ) . lastSegment ( ) ) ; currentDelta ( ) . movedTo ( element , movedFromElement ) ; } else { currentDelta ( ) . added ( element ) ; } this . state . updateRoots ( element . getPath ( ) , delta , this ) ; this . rootsToRefresh . add ( ( IRubyProject ) element ) ; this . projectCachesToReset . add ( ( IRubyProject ) element ) ; } } else { if ( delta == null || ( delta . getFlags ( ) & IResourceDelta . MOVED_FROM ) == ) { if ( isPrimaryWorkingCopy ( element , elementType ) ) { currentDelta ( ) . changed ( element , IRubyElementDelta . F_PRIMARY_RESOURCE ) ; } else { addToParentInfo ( element ) ; close ( element ) ; currentDelta ( ) . added ( element ) ; } } else { addToParentInfo ( element ) ; close ( element ) ; IPath movedFromPath = delta . getMovedFromPath ( ) ; IResource res = delta . getResource ( ) ; IResource movedFromRes ; if ( res instanceof IFile ) { movedFromRes = res . getWorkspace ( ) . getRoot ( ) . getFile ( movedFromPath ) ; } else { movedFromRes = res . getWorkspace ( ) . getRoot ( ) . getFolder ( movedFromPath ) ; } RootInfo movedFromInfo = this . enclosingRootInfo ( movedFromPath , IResourceDelta . REMOVED ) ; int movedFromType = this . elementType ( movedFromRes , IResourceDelta . REMOVED , element . getParent ( ) . getElementType ( ) , movedFromInfo ) ; this . currentElement = null ; Openable movedFromElement = elementType != IRubyElement . RUBY_PROJECT && movedFromType == IRubyElement . RUBY_PROJECT ? null : this . createElement ( movedFromRes , movedFromType , rootInfo ) ; if ( movedFromElement == null ) { currentDelta ( ) . added ( element ) ; } else { currentDelta ( ) . movedTo ( element , movedFromElement ) ; } } switch ( elementType ) { case IRubyElement . SOURCE_FOLDER_ROOT : RubyProject project = ( RubyProject ) element . getRubyProject ( ) ; this . rootsToRefresh . add ( project ) ; this . projectCachesToReset . add ( project ) ; break ; case IRubyElement . SOURCE_FOLDER : project = ( RubyProject ) element . getRubyProject ( ) ; this . projectCachesToReset . add ( project ) ; break ; } } } private boolean isPrimaryWorkingCopy ( IRubyElement element , int elementType ) { if ( elementType == IRubyElement . SCRIPT ) { RubyScript cu = ( RubyScript ) element ; return cu . isPrimary ( ) && cu . isWorkingCopy ( ) ; } return false ; } private void elementRemoved ( Openable element , IResourceDelta delta , RootInfo rootInfo ) { int elementType = element . getElementType ( ) ; if ( delta == null || ( delta . getFlags ( ) & IResourceDelta . MOVED_TO ) == ) { if ( isPrimaryWorkingCopy ( element , elementType ) ) { currentDelta ( ) . changed ( element , IRubyElementDelta . F_PRIMARY_RESOURCE ) ; } else { close ( element ) ; removeFromParentInfo ( element ) ; currentDelta ( ) . removed ( element ) ; } } else { close ( element ) ; removeFromParentInfo ( element ) ; IPath movedToPath = delta . getMovedToPath ( ) ; IResource res = delta . getResource ( ) ; IResource movedToRes ; switch ( res . getType ( ) ) { case IResource . PROJECT : movedToRes = res . getWorkspace ( ) . getRoot ( ) . getProject ( movedToPath . lastSegment ( ) ) ; break ; case IResource . FOLDER : movedToRes = res . getWorkspace ( ) . getRoot ( ) . getFolder ( movedToPath ) ; break ; case IResource . FILE : movedToRes = res . getWorkspace ( ) . getRoot ( ) . getFile ( movedToPath ) ; break ; default : return ; } RootInfo movedToInfo = this . enclosingRootInfo ( movedToPath , IResourceDelta . ADDED ) ; int movedToType = this . elementType ( movedToRes , IResourceDelta . ADDED , element . getParent ( ) . getElementType ( ) , movedToInfo ) ; this . currentElement = null ; Openable movedToElement = elementType != IRubyElement . RUBY_PROJECT && movedToType == IRubyElement . RUBY_PROJECT ? null : this . createElement ( movedToRes , movedToType , rootInfo ) ; if ( movedToElement == null ) { currentDelta ( ) . removed ( element ) ; } else { currentDelta ( ) . movedFrom ( element , movedToElement ) ; } } switch ( elementType ) { case IRubyElement . RUBY_MODEL : break ; case IRubyElement . RUBY_PROJECT : this . state . updateRoots ( element . getPath ( ) , delta , this ) ; this . rootsToRefresh . add ( ( IRubyProject ) element ) ; this . projectCachesToReset . add ( ( IRubyProject ) element ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : RubyProject project = ( RubyProject ) element . getRubyProject ( ) ; this . rootsToRefresh . add ( project ) ; this . projectCachesToReset . add ( project ) ; break ; case IRubyElement . SOURCE_FOLDER : project = ( RubyProject ) element . getRubyProject ( ) ; this . projectCachesToReset . add ( project ) ; break ; } } private void contentChanged ( Openable element ) { boolean isPrimary = false ; boolean isPrimaryWorkingCopy = false ; if ( element . getElementType ( ) == IRubyElement . SCRIPT ) { RubyScript cu = ( RubyScript ) element ; isPrimary = cu . isPrimary ( ) ; isPrimaryWorkingCopy = isPrimary && cu . isWorkingCopy ( ) ; } if ( isPrimaryWorkingCopy ) { currentDelta ( ) . changed ( element , IRubyElementDelta . F_PRIMARY_RESOURCE ) ; } else { close ( element ) ; int flags = IRubyElementDelta . F_CONTENT ; if ( isPrimary ) { flags |= IRubyElementDelta . F_PRIMARY_RESOURCE ; } currentDelta ( ) . changed ( element , flags ) ; } } private int elementType ( IResource res , int kind , int parentType , RootInfo rootInfo ) { switch ( parentType ) { case IRubyElement . RUBY_MODEL : return IRubyElement . RUBY_PROJECT ; case NON_RUBY_RESOURCE : case IRubyElement . RUBY_PROJECT : if ( rootInfo == null ) { rootInfo = this . enclosingRootInfo ( res . getFullPath ( ) , kind ) ; } if ( rootInfo != null && rootInfo . isRootOfProject ( res . getFullPath ( ) ) ) { return IRubyElement . SOURCE_FOLDER_ROOT ; } case IRubyElement . SOURCE_FOLDER_ROOT : case IRubyElement . SOURCE_FOLDER : if ( rootInfo == null ) { rootInfo = this . enclosingRootInfo ( res . getFullPath ( ) , kind ) ; } if ( rootInfo == null ) { return NON_RUBY_RESOURCE ; } if ( Util . isExcluded ( res , rootInfo . inclusionPatterns , rootInfo . exclusionPatterns ) ) { return NON_RUBY_RESOURCE ; } if ( res . getType ( ) == IResource . FOLDER ) { if ( parentType == NON_RUBY_RESOURCE && ! Util . isExcluded ( res . getParent ( ) , rootInfo . inclusionPatterns , rootInfo . exclusionPatterns ) ) return NON_RUBY_RESOURCE ; return IRubyElement . SOURCE_FOLDER ; } String fileName = res . getName ( ) ; if ( Util . isValidRubyOrERBScriptName ( fileName ) ) { return IRubyElement . SCRIPT ; } else if ( this . rootInfo ( res . getFullPath ( ) , kind ) != null ) { return IRubyElement . SOURCE_FOLDER_ROOT ; } else { return NON_RUBY_RESOURCE ; } default : return NON_RUBY_RESOURCE ; } } public static long getTimeStamp ( File file ) { return file . lastModified ( ) + file . length ( ) ; } private void reconcileLoadpathFileUpdate ( IResourceDelta delta , RubyProject project ) { switch ( delta . getKind ( ) ) { case IResourceDelta . REMOVED : try { RubyModelManager . PerProjectInfo info = project . getPerProjectInfo ( ) ; if ( info . rawLoadpath != null ) { project . saveLoadpath ( info . rawLoadpath , info . outputLocation ) ; } } catch ( RubyModelException e ) { if ( project . getProject ( ) . isAccessible ( ) ) { Util . log ( e , "" + project . getPath ( ) ) ; } } break ; case IResourceDelta . CHANGED : int flags = delta . getFlags ( ) ; if ( ( flags & IResourceDelta . CONTENT ) == && ( flags & IResourceDelta . ENCODING ) == && ( flags & IResourceDelta . MOVED_FROM ) == ) { break ; } case IResourceDelta . ADDED : try { project . forceLoadpathReload ( null ) ; } catch ( RuntimeException e ) { if ( VERBOSE ) { e . printStackTrace ( ) ; } } catch ( RubyModelException e ) { if ( VERBOSE ) { e . printStackTrace ( ) ; } } } } private void updateIndex ( Openable element , IResourceDelta delta ) { IndexManager indexManager = this . manager . getIndexManager ( ) ; if ( indexManager == null ) return ; switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_PROJECT : switch ( delta . getKind ( ) ) { case IResourceDelta . ADDED : indexManager . indexAll ( element . getRubyProject ( ) . getProject ( ) ) ; break ; case IResourceDelta . REMOVED : indexManager . removeIndexFamily ( element . getRubyProject ( ) . getProject ( ) . getFullPath ( ) ) ; break ; } break ; case IRubyElement . SOURCE_FOLDER_ROOT : if ( element instanceof ExternalSourceFolderRoot ) { ExternalSourceFolderRoot root = ( ExternalSourceFolderRoot ) element ; IPath jarPath = root . getPath ( ) ; switch ( delta . getKind ( ) ) { case IResourceDelta . ADDED : indexManager . indexLibrary ( jarPath , root . getRubyProject ( ) . getProject ( ) ) ; break ; case IResourceDelta . CHANGED : indexManager . removeIndex ( jarPath ) ; indexManager . indexLibrary ( jarPath , root . getRubyProject ( ) . getProject ( ) ) ; break ; case IResourceDelta . REMOVED : indexManager . discardJobs ( jarPath . toString ( ) ) ; indexManager . removeIndex ( jarPath ) ; break ; } break ; } int kind = delta . getKind ( ) ; if ( kind == IResourceDelta . ADDED || kind == IResourceDelta . REMOVED ) { SourceFolderRoot root = ( SourceFolderRoot ) element ; this . updateRootIndex ( root , CharOperation . NO_STRINGS , delta ) ; break ; } case IRubyElement . SOURCE_FOLDER : switch ( delta . getKind ( ) ) { case IResourceDelta . ADDED : case IResourceDelta . REMOVED : ISourceFolder pkg = null ; if ( element instanceof ISourceFolderRoot ) { SourceFolderRoot root = ( SourceFolderRoot ) element ; pkg = root . getSourceFolder ( CharOperation . NO_STRINGS ) ; } else { pkg = ( ISourceFolder ) element ; } RootInfo rootInfo = rootInfo ( pkg . getParent ( ) . getPath ( ) , delta . getKind ( ) ) ; boolean isSource = rootInfo == null || rootInfo . entryKind == ILoadpathEntry . CPE_SOURCE ; IResourceDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { IResourceDelta child = children [ i ] ; IResource resource = child . getResource ( ) ; if ( resource instanceof IFile ) { String name = resource . getName ( ) ; if ( isSource ) { if ( org . rubypeople . rdt . internal . core . util . Util . isRubyOrERBLikeFileName ( name ) ) { Openable cu = ( Openable ) pkg . getRubyScript ( name ) ; this . updateIndex ( cu , child ) ; } } } } break ; } break ; case IRubyElement . SCRIPT : IFile file = ( IFile ) delta . getResource ( ) ; switch ( delta . getKind ( ) ) { case IResourceDelta . CHANGED : int flags = delta . getFlags ( ) ; if ( ( flags & IResourceDelta . CONTENT ) == && ( flags & IResourceDelta . ENCODING ) == ) break ; case IResourceDelta . ADDED : indexManager . addSource ( file , file . getProject ( ) . getFullPath ( ) , getSourceElementParser ( element ) ) ; this . manager . secondaryTypesRemoving ( file , false ) ; break ; case IResourceDelta . REMOVED : indexManager . remove ( Util . relativePath ( file . getFullPath ( ) , ) , file . getProject ( ) . getFullPath ( ) ) ; this . manager . secondaryTypesRemoving ( file , true ) ; break ; } } } private SourceElementParser getSourceElementParser ( Openable element ) { if ( this . sourceElementParserCache == null ) this . sourceElementParserCache = this . manager . getIndexManager ( ) . getSourceElementParser ( element . getRubyProject ( ) , null ) ; return this . sourceElementParserCache ; } private void updateRootIndex ( SourceFolderRoot root , String [ ] pkgName , IResourceDelta delta ) { Openable pkg = root . getSourceFolder ( pkgName ) ; this . updateIndex ( pkg , delta ) ; IResourceDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { IResourceDelta child = children [ i ] ; IResource resource = child . getResource ( ) ; if ( resource instanceof IFolder ) { String [ ] subpkgName = Util . arrayConcat ( pkgName , resource . getName ( ) ) ; this . updateRootIndex ( root , subpkgName , child ) ; } } } public boolean updateCurrentDeltaAndIndex ( IResourceDelta delta , int elementType , RootInfo rootInfo ) { Openable element ; switch ( delta . getKind ( ) ) { case IResourceDelta . ADDED : IResource deltaRes = delta . getResource ( ) ; element = createElement ( deltaRes , elementType , rootInfo ) ; if ( element == null ) { this . state . updateRoots ( deltaRes . getFullPath ( ) , delta , this ) ; return rootInfo != null && rootInfo . inclusionPatterns != null ; } updateIndex ( element , delta ) ; elementAdded ( element , delta , rootInfo ) ; return elementType == IRubyElement . SOURCE_FOLDER ; case IResourceDelta . REMOVED : deltaRes = delta . getResource ( ) ; element = createElement ( deltaRes , elementType , rootInfo ) ; if ( element == null ) { this . state . updateRoots ( deltaRes . getFullPath ( ) , delta , this ) ; return rootInfo != null && rootInfo . inclusionPatterns != null ; } updateIndex ( element , delta ) ; elementRemoved ( element , delta , rootInfo ) ; if ( deltaRes . getType ( ) == IResource . PROJECT ) { if ( RubyBuilder . DEBUG ) System . out . println ( "" + deltaRes ) ; this . manager . setLastBuiltState ( ( IProject ) deltaRes , null ) ; this . manager . previousSessionContainers . remove ( element ) ; } return elementType == IRubyElement . SOURCE_FOLDER ; case IResourceDelta . CHANGED : int flags = delta . getFlags ( ) ; if ( ( flags & IResourceDelta . CONTENT ) != || ( flags & IResourceDelta . ENCODING ) != ) { element = createElement ( delta . getResource ( ) , elementType , rootInfo ) ; if ( element == null ) return false ; updateIndex ( element , delta ) ; contentChanged ( element ) ; } else if ( elementType == IRubyElement . RUBY_PROJECT ) { if ( ( flags & IResourceDelta . OPEN ) != ) { IProject res = ( IProject ) delta . getResource ( ) ; element = createElement ( res , elementType , rootInfo ) ; if ( element == null ) { this . state . updateRoots ( res . getFullPath ( ) , delta , this ) ; return false ; } if ( res . isOpen ( ) ) { if ( RubyProject . hasRubyNature ( res ) ) { addToParentInfo ( element ) ; currentDelta ( ) . opened ( element ) ; this . state . updateRoots ( element . getPath ( ) , delta , this ) ; this . rootsToRefresh . add ( ( IRubyProject ) element ) ; this . projectCachesToReset . add ( ( IRubyProject ) element ) ; this . manager . getIndexManager ( ) . indexAll ( res ) ; } } else { boolean wasJavaProject = this . state . findRubyProject ( res . getName ( ) ) != null ; if ( wasJavaProject ) { close ( element ) ; removeFromParentInfo ( element ) ; currentDelta ( ) . closed ( element ) ; this . manager . getIndexManager ( ) . discardJobs ( element . getElementName ( ) ) ; this . manager . getIndexManager ( ) . removeIndexFamily ( res . getFullPath ( ) ) ; } } return false ; } if ( ( flags & IResourceDelta . DESCRIPTION ) != ) { IProject res = ( IProject ) delta . getResource ( ) ; boolean wasJavaProject = this . state . findRubyProject ( res . getName ( ) ) != null ; boolean isJavaProject = RubyProject . hasRubyNature ( res ) ; if ( wasJavaProject != isJavaProject ) { element = this . createElement ( res , elementType , rootInfo ) ; if ( element == null ) return false ; if ( isJavaProject ) { elementAdded ( element , delta , rootInfo ) ; this . manager . getIndexManager ( ) . indexAll ( res ) ; } else { elementRemoved ( element , delta , rootInfo ) ; this . manager . getIndexManager ( ) . discardJobs ( element . getElementName ( ) ) ; this . manager . getIndexManager ( ) . removeIndexFamily ( res . getFullPath ( ) ) ; if ( RubyBuilder . DEBUG ) System . out . println ( "" + res ) ; this . manager . setLastBuiltState ( res , null ) ; } return false ; } } } return true ; } return true ; } public void checkExternalArchiveChanges ( IRubyElement [ ] elementsToRefresh , IProgressMonitor monitor ) throws RubyModelException { try { for ( int i = , length = elementsToRefresh . length ; i < length ; i ++ ) { this . addForRefresh ( elementsToRefresh [ i ] ) ; } boolean hasDelta = this . createExternalArchiveDelta ( monitor ) ; if ( monitor != null && monitor . isCanceled ( ) ) return ; if ( hasDelta ) { RubyModel . flushExternalFileCache ( ) ; IRubyElementDelta [ ] projectDeltas = this . currentDelta . getAffectedChildren ( ) ; final int length = projectDeltas . length ; for ( int i = ; i < length ; i ++ ) { IRubyElementDelta delta = projectDeltas [ i ] ; RubyProject rubyProject = ( RubyProject ) delta . getElement ( ) ; rubyProject . getResolvedLoadpath ( true , true , false ) ; } if ( this . currentDelta != null ) { this . fire ( this . currentDelta , DEFAULT_CHANGE_EVENT ) ; } } } finally { this . currentDelta = null ; if ( monitor != null ) monitor . done ( ) ; } } private boolean createExternalArchiveDelta ( IProgressMonitor monitor ) { if ( this . refreshedElements == null ) return false ; HashMap < IPath , String > externalArchivesStatus = new HashMap < IPath , String > ( ) ; boolean hasDelta = false ; HashSet < IPath > archivePathsToRefresh = new HashSet < IPath > ( ) ; Iterator < IRubyElement > iterator = this . refreshedElements . iterator ( ) ; this . refreshedElements = null ; while ( iterator . hasNext ( ) ) { IRubyElement element = ( IRubyElement ) iterator . next ( ) ; switch ( element . getElementType ( ) ) { case IRubyElement . SOURCE_FOLDER_ROOT : archivePathsToRefresh . add ( element . getPath ( ) ) ; break ; case IRubyElement . RUBY_PROJECT : RubyProject javaProject = ( RubyProject ) element ; if ( ! RubyProject . hasRubyNature ( javaProject . getProject ( ) ) ) { break ; } ILoadpathEntry [ ] classpath ; try { classpath = javaProject . getResolvedLoadpath ( true , false , false ) ; for ( int j = , cpLength = classpath . length ; j < cpLength ; j ++ ) { if ( classpath [ j ] . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY ) { archivePathsToRefresh . add ( classpath [ j ] . getPath ( ) ) ; } } } catch ( RubyModelException e ) { } break ; case IRubyElement . RUBY_MODEL : Iterator < String > projectNames = this . state . getOldRubyProjecNames ( ) . iterator ( ) ; while ( projectNames . hasNext ( ) ) { String projectName = projectNames . next ( ) ; IProject project = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; if ( ! RubyProject . hasRubyNature ( project ) ) { continue ; } javaProject = ( RubyProject ) RubyCore . create ( project ) ; try { classpath = javaProject . getResolvedLoadpath ( true , false , false ) ; } catch ( RubyModelException e2 ) { continue ; } for ( int k = , cpLength = classpath . length ; k < cpLength ; k ++ ) { if ( classpath [ k ] . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY ) { archivePathsToRefresh . add ( classpath [ k ] . getPath ( ) ) ; } } } break ; } } Iterator < String > projectNames = this . state . getOldRubyProjecNames ( ) . iterator ( ) ; IWorkspaceRoot wksRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; while ( projectNames . hasNext ( ) ) { if ( monitor != null && monitor . isCanceled ( ) ) break ; String projectName = projectNames . next ( ) ; IProject project = wksRoot . getProject ( projectName ) ; if ( ! RubyProject . hasRubyNature ( project ) ) { continue ; } RubyProject javaProject = ( RubyProject ) RubyCore . create ( project ) ; ILoadpathEntry [ ] entries ; try { entries = javaProject . getResolvedLoadpath ( true , false , false ) ; } catch ( RubyModelException e1 ) { continue ; } for ( int j = ; j < entries . length ; j ++ ) { if ( entries [ j ] . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY ) { IPath entryPath = entries [ j ] . getPath ( ) ; if ( ! archivePathsToRefresh . contains ( entryPath ) ) continue ; String status = ( String ) externalArchivesStatus . get ( entryPath ) ; if ( status == null ) { Object targetLibrary = RubyModel . getTarget ( entryPath , true ) ; if ( targetLibrary == null ) { if ( this . state . getExternalLibTimeStamps ( ) . remove ( entryPath ) != null ) { externalArchivesStatus . put ( entryPath , EXTERNAL_JAR_REMOVED ) ; this . manager . indexManager . removeIndex ( entryPath ) ; } } else if ( targetLibrary instanceof File ) { File externalFile = ( File ) targetLibrary ; Long oldTimestamp = ( Long ) this . state . getExternalLibTimeStamps ( ) . get ( entryPath ) ; long newTimeStamp = getTimeStamp ( externalFile ) ; if ( oldTimestamp != null ) { if ( newTimeStamp == ) { externalArchivesStatus . put ( entryPath , EXTERNAL_JAR_REMOVED ) ; this . state . getExternalLibTimeStamps ( ) . remove ( entryPath ) ; this . manager . indexManager . removeIndex ( entryPath ) ; } else if ( oldTimestamp . longValue ( ) != newTimeStamp ) { externalArchivesStatus . put ( entryPath , EXTERNAL_JAR_CHANGED ) ; this . state . getExternalLibTimeStamps ( ) . put ( entryPath , new Long ( newTimeStamp ) ) ; this . manager . indexManager . removeIndex ( entryPath ) ; this . manager . indexManager . indexLibrary ( entryPath , project . getProject ( ) ) ; } else { externalArchivesStatus . put ( entryPath , EXTERNAL_JAR_UNCHANGED ) ; } } else { if ( newTimeStamp == ) { externalArchivesStatus . put ( entryPath , EXTERNAL_JAR_UNCHANGED ) ; } else { externalArchivesStatus . put ( entryPath , EXTERNAL_JAR_ADDED ) ; this . state . getExternalLibTimeStamps ( ) . put ( entryPath , new Long ( newTimeStamp ) ) ; this . manager . indexManager . indexLibrary ( entryPath , project . getProject ( ) ) ; } } } else { externalArchivesStatus . put ( entryPath , INTERNAL_JAR_IGNORE ) ; } } status = ( String ) externalArchivesStatus . get ( entryPath ) ; if ( status != null ) { if ( status == EXTERNAL_JAR_ADDED ) { SourceFolderRoot root = ( SourceFolderRoot ) javaProject . getSourceFolderRoot ( entryPath . toString ( ) ) ; if ( VERBOSE ) { System . out . println ( "" + root . getElementName ( ) ) ; } elementAdded ( root , null , null ) ; hasDelta = true ; } else if ( status == EXTERNAL_JAR_CHANGED ) { SourceFolderRoot root = ( SourceFolderRoot ) javaProject . getSourceFolderRoot ( entryPath . toString ( ) ) ; if ( VERBOSE ) { System . out . println ( "" + root . getElementName ( ) ) ; } contentChanged ( root ) ; hasDelta = true ; } else if ( status == EXTERNAL_JAR_REMOVED ) { SourceFolderRoot root = ( SourceFolderRoot ) javaProject . getSourceFolderRoot ( entryPath . toString ( ) ) ; if ( VERBOSE ) { System . out . println ( "" + root . getElementName ( ) ) ; } elementRemoved ( root , null , null ) ; hasDelta = true ; } } } } } return hasDelta ; } } package org . rubypeople . rdt . internal . core ; public interface IPathRequestor { void acceptPath ( String path , boolean containsLocalTypes ) ; } package org . rubypeople . rdt . internal . core ; import java . util . HashMap ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . ISourceRange ; public class RubyScriptElementInfo extends OpenableElementInfo { protected int sourceLength ; protected long timestamp ; public HashMap annotationPositions ; protected SyntaxException syntaxException = null ; public void addAnnotationPositions ( IRubyElement handle , long [ ] positions ) { if ( positions == null ) return ; if ( this . annotationPositions == null ) this . annotationPositions = new HashMap ( ) ; this . annotationPositions . put ( handle , positions ) ; } public int getSourceLength ( ) { return this . sourceLength ; } protected ISourceRange getSourceRange ( ) { return new SourceRange ( , this . sourceLength ) ; } protected boolean isOpen ( ) { return true ; } public void setSourceLength ( int newSourceLength ) { this . sourceLength = newSourceLength ; } public SyntaxException getSyntaxException ( ) { return syntaxException ; } public void setSyntaxException ( SyntaxException syntaxException ) { this . syntaxException = syntaxException ; } } package org . rubypeople . rdt . internal . core ; import java . util . HashMap ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . ILocalVariable ; import org . rubypeople . rdt . internal . core . util . Util ; public class LocalVariable extends RubyField implements ILocalVariable { private int start ; private int end ; public LocalVariable ( RubyElement parent , String name , int start , int end ) { super ( parent , name ) ; } public int getElementType ( ) { return RubyElement . LOCAL_VARIABLE ; } protected Object createElementInfo ( ) { return null ; } public IResource getCorrespondingResource ( ) { return null ; } public int hashCode ( ) { return Util . combineHashCodes ( this . parent . hashCode ( ) , this . start ) ; } public boolean equals ( Object o ) { if ( ! ( o instanceof LocalVariable ) ) return false ; LocalVariable other = ( LocalVariable ) o ; return this . start == other . start && this . end == other . end && super . equals ( o ) ; } protected void generateInfos ( Object info , HashMap newElements , IProgressMonitor pm ) { } } package org . rubypeople . rdt . internal . core ; import java . io . CharArrayReader ; import java . io . File ; import java . io . IOException ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . internal . core . buffer . BufferManager ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; public class ExternalRubyScript extends RubyScript { public ExternalRubyScript ( ExternalSourceFolder parent , String name , WorkingCopyOwner owner ) { super ( parent , name , owner ) ; } @ Override protected boolean buildStructure ( OpenableElementInfo info , IProgressMonitor pm , Map newElements , IResource underlyingResource ) throws RubyModelException { RubyScriptElementInfo unitInfo = ( RubyScriptElementInfo ) info ; IBuffer buffer = getBufferManager ( ) . getBuffer ( this ) ; if ( buffer == null ) { buffer = openBuffer ( pm , unitInfo ) ; } final char [ ] contents = buffer == null ? null : buffer . getCharacters ( ) ; try { RubyScriptStructureBuilder visitor = new RubyScriptStructureBuilder ( this , unitInfo , newElements ) ; SourceElementParser sp = new SourceElementParser ( visitor ) ; sp . parse ( contents , null ) ; unitInfo . setIsStructureKnown ( true ) ; } catch ( SyntaxException e ) { unitInfo . setIsStructureKnown ( false ) ; unitInfo . setSyntaxException ( e ) ; } catch ( Exception e ) { RubyCore . log ( e ) ; } return unitInfo . isStructureKnown ( ) ; } @ Override public boolean exists ( ) { return getFile ( ) . exists ( ) ; } protected IBuffer openBuffer ( IProgressMonitor pm , Object info ) throws RubyModelException { char [ ] contents = findSource ( ) ; if ( contents != null ) { IBuffer buffer = getBufferManager ( ) . createBuffer ( this ) ; if ( buffer == null ) return null ; BufferManager bufManager = getBufferManager ( ) ; bufManager . addBuffer ( buffer ) ; if ( buffer . getCharacters ( ) == null ) { buffer . setContents ( contents ) ; } buffer . addBufferChangedListener ( this ) ; return buffer ; } return null ; } public File getFile ( ) { ExternalSourceFolder parent = ( ExternalSourceFolder ) getParent ( ) ; IPath parentPath = parent . getPath ( ) ; return parentPath . append ( name ) . toFile ( ) ; } private char [ ] findSource ( ) { String source = null ; try { source = getSource ( ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } if ( source == null ) return new char [ ] ; return source . toCharArray ( ) ; } @ Override public IResource getResource ( ) { return null ; } @ Override public IPath getPath ( ) { return getParent ( ) . getPath ( ) . append ( getElementName ( ) ) ; } @ Override public String getSource ( ) throws RubyModelException { File file = getFile ( ) ; if ( ! file . exists ( ) ) return null ; byte [ ] bytes ; try { bytes = Util . getFileByteContent ( file ) ; } catch ( IOException e ) { RubyCore . log ( e ) ; return null ; } return new String ( bytes ) ; } } package org . rubypeople . rdt . internal . core ; public class RubyConstant extends RubyField { public RubyConstant ( RubyElement parent , String name ) { super ( parent , name ) ; } public int getElementType ( ) { return CONSTANT ; } } package org . rubypeople . rdt . internal . core ; import java . io . File ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Map ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class SourceFolder extends Openable implements ISourceFolder { public String [ ] names ; public SourceFolder ( SourceFolderRoot parent , String [ ] names ) { super ( parent ) ; this . names = names ; } public boolean hasChildren ( ) throws RubyModelException { return getChildren ( ) . length > ; } @ Override protected boolean buildStructure ( OpenableElementInfo info , IProgressMonitor pm , Map newElements , IResource underlyingResource ) throws RubyModelException { if ( ! underlyingResource . isAccessible ( ) ) throw newNotPresentException ( ) ; if ( Util . isExcluded ( this ) ) throw newNotPresentException ( ) ; HashSet vChildren = new HashSet ( ) ; try { SourceFolderRoot root = getSourceFolderRoot ( ) ; char [ ] [ ] inclusionPatterns = root . fullInclusionPatternChars ( ) ; char [ ] [ ] exclusionPatterns = root . fullExclusionPatternChars ( ) ; IResource [ ] members = ( ( IContainer ) underlyingResource ) . members ( ) ; for ( int i = , max = members . length ; i < max ; i ++ ) { IResource child = members [ i ] ; if ( child . getType ( ) != IResource . FOLDER && ! Util . isExcluded ( child , inclusionPatterns , exclusionPatterns ) ) { IRubyElement childElement ; if ( Util . isValidRubyScriptName ( child . getName ( ) ) ) { childElement = new RubyScript ( this , child . getName ( ) , DefaultWorkingCopyOwner . PRIMARY ) ; vChildren . add ( childElement ) ; } else if ( Util . isERBLikeFileName ( child . getName ( ) ) ) { childElement = new ERBScript ( this , child . getName ( ) , DefaultWorkingCopyOwner . PRIMARY ) ; vChildren . add ( childElement ) ; } } } } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } IRubyScript [ ] primaryCompilationUnits = getRubyScripts ( DefaultWorkingCopyOwner . PRIMARY ) ; for ( int i = , length = primaryCompilationUnits . length ; i < length ; i ++ ) { IRubyScript primary = primaryCompilationUnits [ i ] ; vChildren . add ( primary ) ; } IRubyElement [ ] children = new IRubyElement [ vChildren . size ( ) ] ; vChildren . toArray ( children ) ; info . setChildren ( children ) ; return true ; } @ Override protected Object createElementInfo ( ) { return new SourceFolderInfo ( ) ; } @ Override public int getElementType ( ) { return IRubyElement . SOURCE_FOLDER ; } @ Override public String getElementName ( ) { if ( names . length == ) return "" ; return Util . concatWith ( this . names , File . separatorChar ) ; } public boolean containsRubyResources ( ) throws RubyModelException { return ( ( SourceFolderInfo ) getElementInfo ( ) ) . containsRubyResources ( ) ; } public IRubyScript createRubyScript ( String name , String contents , boolean force , IProgressMonitor monitor ) throws RubyModelException { CreateRubyScriptOperation op = new CreateRubyScriptOperation ( this , name , contents , force ) ; op . runOperation ( monitor ) ; return new RubyScript ( this , name , DefaultWorkingCopyOwner . PRIMARY ) ; } public Object [ ] getNonRubyResources ( ) throws RubyModelException { if ( this . isDefaultPackage ( ) ) { return RubyElementInfo . NO_NON_RUBY_RESOURCES ; } else { return ( ( SourceFolderInfo ) getElementInfo ( ) ) . getNonRubyResources ( getResource ( ) , getSourceFolderRoot ( ) ) ; } } public boolean isDefaultPackage ( ) { return this . names . length == ; } public IRubyScript [ ] getRubyScripts ( ) throws RubyModelException { ArrayList < IRubyElement > list = getChildrenOfType ( SCRIPT ) ; IRubyScript [ ] array = new IRubyScript [ list . size ( ) ] ; list . toArray ( array ) ; return array ; } public IRubyScript [ ] getRubyScripts ( WorkingCopyOwner owner ) throws RubyModelException { IRubyScript [ ] workingCopies = RubyModelManager . getRubyModelManager ( ) . getWorkingCopies ( owner , false ) ; if ( workingCopies == null ) return RubyModelManager . NO_WORKING_COPY ; int length = workingCopies . length ; IRubyScript [ ] result = new IRubyScript [ length ] ; int index = ; for ( int i = ; i < length ; i ++ ) { IRubyScript wc = workingCopies [ i ] ; if ( equals ( wc . getParent ( ) ) && ! Util . isExcluded ( wc ) ) { result [ index ++ ] = wc ; } } if ( index != length ) { System . arraycopy ( result , , result = new IRubyScript [ index ] , , index ) ; } return result ; } public IPath getPath ( ) { SourceFolderRoot root = this . getSourceFolderRoot ( ) ; IPath path = root . getPath ( ) ; for ( int i = , length = this . names . length ; i < length ; i ++ ) { String name = this . names [ i ] ; path = path . append ( name ) ; } return path ; } public boolean equals ( Object o ) { if ( this == o ) return true ; if ( ! ( o instanceof SourceFolder ) ) return false ; SourceFolder other = ( SourceFolder ) o ; return Util . equalArraysOrNull ( this . names , other . names ) && this . parent . equals ( other . parent ) ; } public boolean exists ( ) { return super . exists ( ) && ! Util . isExcluded ( this ) ; } public IResource getResource ( ) { SourceFolderRoot root = this . getSourceFolderRoot ( ) ; if ( root . isExternal ( ) ) { return root . getResource ( ) ; } int length = this . names . length ; if ( length == ) { return root . getResource ( ) ; } IPath path = new Path ( this . names [ ] ) ; for ( int i = ; i < length ; i ++ ) path = path . append ( this . names [ i ] ) ; return ( ( IContainer ) root . getResource ( ) ) . getFolder ( path ) ; } public IResource getUnderlyingResource ( ) throws RubyModelException { IResource rootResource = this . parent . getUnderlyingResource ( ) ; if ( rootResource == null ) { return null ; } if ( rootResource . getType ( ) == IResource . FOLDER || rootResource . getType ( ) == IResource . PROJECT ) { IContainer folder = ( IContainer ) rootResource ; String [ ] segs = this . names ; for ( int i = ; i < segs . length ; ++ i ) { IResource child = folder . findMember ( segs [ i ] ) ; if ( child == null || child . getType ( ) != IResource . FOLDER ) { throw newNotPresentException ( ) ; } folder = ( IFolder ) child ; } return folder ; } else { return rootResource ; } } public IRubyScript getRubyScript ( String name ) { if ( org . rubypeople . rdt . internal . core . util . Util . isERBLikeFileName ( name ) ) { return new ERBScript ( this , name , DefaultWorkingCopyOwner . PRIMARY ) ; } if ( ! org . rubypeople . rdt . internal . core . util . Util . isRubyLikeFileName ( name ) ) { throw new IllegalArgumentException ( Messages . convention_unit_notRubyName ) ; } return new RubyScript ( this , name , DefaultWorkingCopyOwner . PRIMARY ) ; } public IRubyElement getHandleFromMemento ( String token , MementoTokenizer memento , WorkingCopyOwner owner ) { switch ( token . charAt ( ) ) { case JEM_RUBYSCRIPT : if ( ! memento . hasMoreTokens ( ) ) return this ; String cuName = memento . nextToken ( ) ; RubyElement cu = new RubyScript ( this , cuName , owner ) ; return cu . getHandleFromMemento ( memento , owner ) ; } return null ; } protected char getHandleMementoDelimiter ( ) { return RubyElement . JEM_SOURCE_FOLDER ; } public boolean hasSubfolders ( ) throws RubyModelException { IRubyElement [ ] packages = ( ( ISourceFolderRoot ) getParent ( ) ) . getChildren ( ) ; int namesLength = this . names . length ; nextPackage : for ( int i = , length = packages . length ; i < length ; i ++ ) { String [ ] otherNames = ( ( SourceFolder ) packages [ i ] ) . names ; if ( otherNames . length <= namesLength ) continue nextPackage ; for ( int j = ; j < namesLength ; j ++ ) if ( ! this . names [ j ] . equals ( otherNames [ j ] ) ) continue nextPackage ; return true ; } return false ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . rubypeople . rdt . core . IBuffer ; public class DocumentAdapter extends Document { private IBuffer buffer ; public DocumentAdapter ( IBuffer buffer ) { super ( buffer . getContents ( ) ) ; this . buffer = buffer ; } public void set ( String text ) { super . set ( text ) ; this . buffer . setContents ( text ) ; } public void replace ( int offset , int length , String text ) throws BadLocationException { super . replace ( offset , length , text ) ; this . buffer . replace ( offset , length , text ) ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . runtime . Assert ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; public class RubyImport extends NamedMember implements IImportDeclaration { public RubyImport ( RubyElement parent , String name ) { super ( parent , name ) ; } public boolean equals ( Object o ) { if ( ! ( o instanceof RubyImport ) ) return false ; return super . equals ( o ) ; } public int getElementType ( ) { return IRubyElement . IMPORT_DECLARATION ; } protected void getHandleMemento ( StringBuffer buff ) { ( ( RubyElement ) getParent ( ) ) . getHandleMemento ( buff ) ; escapeMementoName ( buff , getElementName ( ) ) ; if ( this . occurrenceCount > ) { buff . append ( JEM_COUNT ) ; buff . append ( this . occurrenceCount ) ; } } protected char getHandleMementoDelimiter ( ) { Assert . isTrue ( false , "" ) ; return ; } @ Override public String getTypeQualifiedName ( String enclosingTypeSeparator , boolean showParameters ) throws RubyModelException { return getElementName ( ) ; } } package org . rubypeople . rdt . internal . core ; import org . rubypeople . rdt . core . IRubyElementDelta ; public class SimpleDelta { protected int kind = ; protected int changeFlags = ; public void added ( ) { this . kind = IRubyElementDelta . ADDED ; } public void changed ( int flags ) { this . kind = IRubyElementDelta . CHANGED ; this . changeFlags |= flags ; } public int getFlags ( ) { return this . changeFlags ; } public int getKind ( ) { return this . kind ; } public void modifiers ( ) { changed ( IRubyElementDelta . F_MODIFIERS ) ; } public void removed ( ) { this . kind = IRubyElementDelta . REMOVED ; this . changeFlags = ; } public void superTypes ( ) { changed ( IRubyElementDelta . F_SUPER_TYPES ) ; } protected void toDebugString ( StringBuffer buffer ) { buffer . append ( "" ) ; switch ( getKind ( ) ) { case IRubyElementDelta . ADDED : buffer . append ( '' ) ; break ; case IRubyElementDelta . REMOVED : buffer . append ( '' ) ; break ; case IRubyElementDelta . CHANGED : buffer . append ( '' ) ; break ; default : buffer . append ( '' ) ; break ; } buffer . append ( "" ) ; toDebugString ( buffer , getFlags ( ) ) ; buffer . append ( "" ) ; } protected boolean toDebugString ( StringBuffer buffer , int flags ) { boolean prev = false ; if ( ( flags & IRubyElementDelta . F_MODIFIERS ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } if ( ( flags & IRubyElementDelta . F_SUPER_TYPES ) != ) { if ( prev ) buffer . append ( "" ) ; buffer . append ( "" ) ; prev = true ; } return prev ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; toDebugString ( buffer ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core ; import java . io . PrintWriter ; import java . io . Writer ; import java . util . HashMap ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . core . util . Util ; class XMLWriter extends PrintWriter { private static final String XML_VERSION = "" ; private static void appendEscapedChar ( StringBuffer buffer , char c ) { String replacement = getReplacement ( c ) ; if ( replacement != null ) { buffer . append ( '' ) ; buffer . append ( replacement ) ; buffer . append ( '' ) ; } else { buffer . append ( c ) ; } } private static String getEscaped ( String s ) { StringBuffer result = new StringBuffer ( s . length ( ) + ) ; for ( int i = ; i < s . length ( ) ; ++ i ) appendEscapedChar ( result , s . charAt ( i ) ) ; return result . toString ( ) ; } private static String getReplacement ( char c ) { switch ( c ) { case '' : return "" ; case '>' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; } return null ; } private int tab ; private String lineSeparator ; public XMLWriter ( Writer writer , IRubyProject project , boolean printXmlVersion ) { super ( writer ) ; this . tab = ; this . lineSeparator = Util . getLineSeparator ( ( String ) null , project ) ; if ( printXmlVersion ) { print ( XML_VERSION ) ; print ( this . lineSeparator ) ; } } public void endTag ( String name , boolean insertTab , boolean insertNewLine ) { this . tab -- ; printTag ( '' + name , null , insertTab , insertNewLine , false ) ; } private void printTabulation ( ) { for ( int i = ; i < tab ; i ++ ) super . print ( '' ) ; } public void printTag ( String name , HashMap parameters , boolean insertTab , boolean insertNewLine , boolean closeTag ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( "" ) ; sb . append ( name ) ; if ( parameters != null ) { int length = parameters . size ( ) ; String [ ] keys = new String [ length ] ; parameters . keySet ( ) . toArray ( keys ) ; Util . sort ( keys ) ; for ( int i = ; i < length ; i ++ ) { sb . append ( "" ) ; sb . append ( keys [ i ] ) ; sb . append ( "" ) ; sb . append ( getEscaped ( String . valueOf ( parameters . get ( keys [ i ] ) ) ) ) ; sb . append ( "" ) ; } } if ( closeTag ) { sb . append ( "" ) ; } else { sb . append ( ">" ) ; } printString ( sb . toString ( ) , insertTab , insertNewLine ) ; if ( parameters != null && ! closeTag ) this . tab ++ ; } public void printString ( String string , boolean insertTab , boolean insertNewLine ) { if ( insertTab ) { printTabulation ( ) ; } print ( string ) ; if ( insertNewLine ) { print ( this . lineSeparator ) ; } } public void startTag ( String name , boolean insertTab ) { printTag ( name , null , insertTab , true , false ) ; this . tab ++ ; } } package org . rubypeople . rdt . internal . core . hierarchy ; import java . util . ArrayList ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRegion ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . internal . core . Openable ; import org . rubypeople . rdt . internal . core . Region ; import org . rubypeople . rdt . internal . core . RubyElement ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . TypeVector ; public class RegionBasedTypeHierarchy extends TypeHierarchy { protected IRegion region ; public RegionBasedTypeHierarchy ( IRegion region , IRubyScript [ ] workingCopies , IType type , boolean computeSubtypes ) { super ( type , workingCopies , ( IRubySearchScope ) null , computeSubtypes ) ; Region newRegion = new Region ( ) { public void add ( IRubyElement element ) { if ( ! contains ( element ) ) { removeAllChildren ( element ) ; fRootElements . add ( element ) ; if ( element . getElementType ( ) == IRubyElement . RUBY_PROJECT ) { try { ISourceFolderRoot [ ] roots = ( ( IRubyProject ) element ) . getSourceFolderRoots ( ) ; for ( int i = , length = roots . length ; i < length ; i ++ ) { if ( roots [ i ] . isArchive ( ) && ! fRootElements . contains ( roots [ i ] ) ) fRootElements . add ( roots [ i ] ) ; } } catch ( RubyModelException e ) { } } fRootElements . trimToSize ( ) ; } } } ; IRubyElement [ ] elements = region . getElements ( ) ; for ( int i = , length = elements . length ; i < length ; i ++ ) { newRegion . add ( elements [ i ] ) ; } this . region = newRegion ; if ( elements . length > ) this . project = elements [ ] . getRubyProject ( ) ; } protected void initializeRegions ( ) { super . initializeRegions ( ) ; IRubyElement [ ] roots = this . region . getElements ( ) ; for ( int i = ; i < roots . length ; i ++ ) { IRubyElement root = roots [ i ] ; if ( root instanceof IOpenable ) { this . files . put ( ( IOpenable ) root , new ArrayList < IType > ( ) ) ; } else { Openable o = ( Openable ) ( ( RubyElement ) root ) . getOpenableParent ( ) ; if ( o != null ) { this . files . put ( o , new ArrayList < IType > ( ) ) ; } } checkCanceled ( ) ; } } protected void compute ( ) throws RubyModelException , CoreException { HierarchyBuilder builder = new RegionBasedHierarchyBuilder ( this ) ; builder . build ( this . computeSubtypes ) ; } protected boolean isAffectedByOpenable ( IRubyElementDelta delta , IRubyElement element ) { if ( element instanceof RubyScript && ( ( RubyScript ) element ) . isWorkingCopy ( ) ) { return super . isAffectedByOpenable ( delta , element ) ; } if ( this . focusType == null ) { return this . region . contains ( element ) ; } else { return super . isAffectedByOpenable ( delta , element ) ; } } public IRubyProject rubyProject ( ) { return this . project ; } public void pruneDeadBranches ( ) { pruneDeadBranches ( getRootClasses ( ) ) ; pruneDeadBranches ( getRootModules ( ) ) ; } private boolean pruneDeadBranches ( IType type ) { TypeVector subtypes = ( TypeVector ) this . typeToSubtypes . get ( type ) ; if ( subtypes == null ) return true ; pruneDeadBranches ( subtypes . copy ( ) . elements ( ) ) ; subtypes = ( TypeVector ) this . typeToSubtypes . get ( type ) ; return ( subtypes == null || subtypes . size == ) ; } private void pruneDeadBranches ( IType [ ] types ) { for ( int i = , length = types . length ; i < length ; i ++ ) { IType type = types [ i ] ; if ( pruneDeadBranches ( type ) && ! this . region . contains ( type ) ) { removeType ( type ) ; } } } protected void removeType ( IType type ) { IType [ ] subtypes = this . getSubtypes ( type ) ; this . typeToSubtypes . remove ( type ) ; if ( subtypes != null ) { for ( int i = ; i < subtypes . length ; i ++ ) { this . removeType ( subtypes [ i ] ) ; } } IType superclass = ( IType ) this . classToSuperclass . remove ( type ) ; if ( superclass != null ) { TypeVector types = ( TypeVector ) this . typeToSubtypes . get ( superclass ) ; if ( types != null ) types . remove ( type ) ; } IType [ ] superinterfaces = ( IType [ ] ) this . typeToSuperModules . remove ( type ) ; if ( superinterfaces != null ) { for ( int i = , length = superinterfaces . length ; i < length ; i ++ ) { IType superinterface = superinterfaces [ i ] ; TypeVector types = ( TypeVector ) this . typeToSubtypes . get ( superinterface ) ; if ( types != null ) types . remove ( type ) ; } } this . modules . remove ( type ) ; } } package org . rubypeople . rdt . internal . core . hierarchy ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Hashtable ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SafeRunner ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModelStatusConstants ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . ITypeHierarchyChangedListener ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . core . Openable ; import org . rubypeople . rdt . internal . core . Region ; import org . rubypeople . rdt . internal . core . RubyElement ; import org . rubypeople . rdt . internal . core . RubyModelStatus ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . SourceFolder ; import org . rubypeople . rdt . internal . core . TypeVector ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; public class TypeHierarchy implements ITypeHierarchy , IElementChangedListener { public static boolean DEBUG = false ; static final byte VERSION = ; static final byte SEPARATOR1 = '' ; static final byte SEPARATOR2 = '' ; static final byte SEPARATOR3 = '>' ; static final byte SEPARATOR4 = '' ; static final byte COMPUTE_SUBTYPES = ; static final byte CLASS = ; static final byte INTERFACE = ; static final byte COMPUTED_FOR = ; static final byte ROOT = ; static final byte [ ] NO_FLAGS = new byte [ ] { } ; static final int SIZE = ; protected IRubyProject project ; protected IType focusType ; protected IRubyScript [ ] workingCopies ; protected Map < IType , IType > classToSuperclass ; protected Map < IType , IType [ ] > typeToSuperModules ; protected Map < IType , TypeVector > typeToSubtypes ; protected Map < IType , Integer > typeFlags ; protected TypeVector rootClasses = new TypeVector ( ) ; protected ArrayList < IType > modules = new ArrayList < IType > ( ) ; public ArrayList < String > missingTypes = new ArrayList < String > ( ) ; protected static final IType [ ] NO_TYPE = new IType [ ] ; protected IProgressMonitor progressMonitor = null ; protected ArrayList < ITypeHierarchyChangedListener > changeListeners = null ; public Map < IOpenable , ArrayList < IType > > files = null ; protected Region packageRegion = null ; protected Region projectRegion = null ; protected boolean computeSubtypes ; IRubySearchScope scope ; public boolean needsRefresh = true ; protected ChangeCollector changeCollector ; public TypeHierarchy ( ) { } public TypeHierarchy ( IType type , IRubyScript [ ] workingCopies , IRubyProject project , boolean computeSubtypes ) { this ( type , workingCopies , SearchEngine . createRubySearchScope ( new IRubyElement [ ] { project } ) , computeSubtypes ) ; this . project = project ; } public TypeHierarchy ( IType type , IRubyScript [ ] workingCopies , IRubySearchScope scope , boolean computeSubtypes ) { this . focusType = type == null ? null : ( IType ) ( ( RubyElement ) type ) . unresolved ( ) ; this . workingCopies = workingCopies ; this . computeSubtypes = computeSubtypes ; this . scope = scope ; } protected void initializeRegions ( ) { IType [ ] allTypes = getAllTypes ( ) ; for ( int i = ; i < allTypes . length ; i ++ ) { IType type = allTypes [ i ] ; Openable o = ( Openable ) ( ( RubyElement ) type ) . getOpenableParent ( ) ; if ( o != null ) { ArrayList < IType > types = ( ArrayList < IType > ) this . files . get ( o ) ; if ( types == null ) { types = new ArrayList < IType > ( ) ; this . files . put ( o , types ) ; } types . add ( type ) ; } ISourceFolder pkg = type . getSourceFolder ( ) ; this . packageRegion . add ( pkg ) ; IRubyProject declaringProject = type . getRubyProject ( ) ; if ( declaringProject != null ) { this . projectRegion . add ( declaringProject ) ; } checkCanceled ( ) ; } } private void addAllCheckingDuplicates ( ArrayList < IType > list , IType [ ] collection ) { for ( int i = ; i < collection . length ; i ++ ) { IType element = collection [ i ] ; if ( ! list . contains ( element ) ) { list . add ( element ) ; } } } protected void addModule ( IType type ) { this . modules . add ( type ) ; } protected void addRootClass ( IType type ) { if ( this . rootClasses . contains ( type ) ) return ; this . rootClasses . add ( type ) ; } protected void addSubtype ( IType type , IType subtype ) { TypeVector subtypes = this . typeToSubtypes . get ( type ) ; if ( subtypes == null ) { subtypes = new TypeVector ( ) ; this . typeToSubtypes . put ( type , subtypes ) ; } if ( ! subtypes . contains ( subtype ) ) { subtypes . add ( subtype ) ; } } public synchronized void addTypeHierarchyChangedListener ( ITypeHierarchyChangedListener listener ) { ArrayList < ITypeHierarchyChangedListener > listeners = this . changeListeners ; if ( listeners == null ) { this . changeListeners = listeners = new ArrayList < ITypeHierarchyChangedListener > ( ) ; } if ( listeners . size ( ) == ) { RubyCore . addElementChangedListener ( this ) ; } if ( listeners . indexOf ( listener ) == - ) { listeners . add ( listener ) ; } } private static Integer bytesToFlags ( byte [ ] bytes ) { if ( bytes != null && bytes . length > ) { return new Integer ( new String ( bytes ) ) ; } else { return null ; } } public void cacheFlags ( IType type , int flags ) { this . typeFlags . put ( type , new Integer ( flags ) ) ; } protected void cacheSuperclass ( IType type , IType superclass ) { if ( superclass != null ) { this . classToSuperclass . put ( type , superclass ) ; addSubtype ( superclass , type ) ; } } protected void cacheSuperModules ( IType type , IType [ ] supermodules ) { this . typeToSuperModules . put ( type , supermodules ) ; for ( int i = ; i < supermodules . length ; i ++ ) { IType supermodule = supermodules [ i ] ; if ( supermodule != null ) { addModule ( supermodule ) ; addSubtype ( supermodule , type ) ; } } } protected void checkCanceled ( ) { if ( this . progressMonitor != null && this . progressMonitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } } protected void compute ( ) throws RubyModelException , CoreException { if ( this . focusType != null ) { HierarchyBuilder builder = new IndexBasedHierarchyBuilder ( this , this . scope ) ; builder . build ( this . computeSubtypes ) ; } } public boolean contains ( IType type ) { if ( this . classToSuperclass . get ( type ) != null ) { return true ; } if ( this . rootClasses . contains ( type ) ) return true ; if ( this . modules . contains ( type ) ) return true ; return false ; } public void elementChanged ( ElementChangedEvent event ) { if ( this . needsRefresh ) return ; if ( isAffected ( event . getDelta ( ) ) ) { this . needsRefresh = true ; fireChange ( ) ; } } public boolean exists ( ) { if ( ! this . needsRefresh ) return true ; return ( this . focusType == null || this . focusType . exists ( ) ) && this . rubyProject ( ) . exists ( ) ; } @ SuppressWarnings ( "" ) public void fireChange ( ) { ArrayList < ITypeHierarchyChangedListener > listeners = this . changeListeners ; if ( listeners == null ) { return ; } if ( DEBUG ) { System . out . println ( "" + Thread . currentThread ( ) + "" ) ; if ( this . focusType != null ) { System . out . println ( "" + ( ( RubyElement ) this . focusType ) . toStringWithAncestors ( ) ) ; } } listeners = ( ArrayList < ITypeHierarchyChangedListener > ) listeners . clone ( ) ; for ( int i = ; i < listeners . size ( ) ; i ++ ) { final ITypeHierarchyChangedListener listener = listeners . get ( i ) ; SafeRunner . run ( new ISafeRunnable ( ) { public void handleException ( Throwable exception ) { Util . log ( exception , "" ) ; } public void run ( ) throws Exception { listener . typeHierarchyChanged ( TypeHierarchy . this ) ; } } ) ; } } private static byte [ ] flagsToBytes ( Integer flags ) { if ( flags != null ) { return flags . toString ( ) . getBytes ( ) ; } else { return NO_FLAGS ; } } public IType [ ] getAllClasses ( ) { TypeVector classes = this . rootClasses . copy ( ) ; for ( IType type : this . classToSuperclass . keySet ( ) ) { classes . add ( type ) ; } return classes . elements ( ) ; } public IType [ ] getAllModules ( ) { IType [ ] collection = new IType [ this . modules . size ( ) ] ; this . modules . toArray ( collection ) ; return collection ; } public IType [ ] getAllSubtypes ( IType type ) { return getAllSubtypesForType ( type ) ; } private IType [ ] getAllSubtypesForType ( IType type ) { ArrayList < IType > subTypes = new ArrayList < IType > ( ) ; getAllSubtypesForType0 ( type , subTypes ) ; IType [ ] subClasses = new IType [ subTypes . size ( ) ] ; subTypes . toArray ( subClasses ) ; return subClasses ; } private void getAllSubtypesForType0 ( IType type , ArrayList < IType > subs ) { IType [ ] subTypes = getSubtypesForType ( type ) ; if ( subTypes . length != ) { for ( IType subType : subTypes ) { subs . add ( subType ) ; getAllSubtypesForType0 ( subType , subs ) ; } } } public IType [ ] getAllSuperclasses ( IType type ) { IType superclass = getSuperclass ( type ) ; TypeVector supers = new TypeVector ( ) ; while ( superclass != null ) { supers . add ( superclass ) ; superclass = getSuperclass ( superclass ) ; } return supers . elements ( ) ; } public IType [ ] getAllSuperModules ( IType type ) { ArrayList < IType > supers = new ArrayList < IType > ( ) ; if ( this . typeToSuperModules . get ( type ) == null ) { return NO_TYPE ; } getAllSuperModules0 ( type , supers ) ; IType [ ] supermodules = new IType [ supers . size ( ) ] ; supers . toArray ( supermodules ) ; return supermodules ; } private void getAllSuperModules0 ( IType type , ArrayList < IType > supers ) { IType [ ] superinterfaces = this . typeToSuperModules . get ( type ) ; if ( superinterfaces != null && superinterfaces . length != ) { addAllCheckingDuplicates ( supers , superinterfaces ) ; for ( int i = ; i < superinterfaces . length ; i ++ ) { getAllSuperModules0 ( superinterfaces [ i ] , supers ) ; } } IType superclass = this . classToSuperclass . get ( type ) ; if ( superclass != null ) { getAllSuperModules0 ( superclass , supers ) ; } } public IType [ ] getAllSupertypes ( IType type ) { ArrayList < IType > supers = new ArrayList < IType > ( ) ; if ( this . typeToSuperModules . get ( type ) == null ) { return NO_TYPE ; } getAllSupertypes0 ( type , supers ) ; IType [ ] supertypes = new IType [ supers . size ( ) ] ; supers . toArray ( supertypes ) ; return supertypes ; } private void getAllSupertypes0 ( IType type , ArrayList < IType > supers ) { IType [ ] superinterfaces = this . typeToSuperModules . get ( type ) ; if ( superinterfaces != null && superinterfaces . length != ) { addAllCheckingDuplicates ( supers , superinterfaces ) ; for ( int i = ; i < superinterfaces . length ; i ++ ) { getAllSuperModules0 ( superinterfaces [ i ] , supers ) ; } } IType superclass = this . classToSuperclass . get ( type ) ; if ( superclass != null ) { supers . add ( superclass ) ; getAllSupertypes0 ( superclass , supers ) ; } } public IType [ ] getAllTypes ( ) { IType [ ] classes = getAllClasses ( ) ; int classesLength = classes . length ; IType [ ] allInterfaces = getAllModules ( ) ; int interfacesLength = allInterfaces . length ; IType [ ] all = new IType [ classesLength + interfacesLength ] ; System . arraycopy ( classes , , all , , classesLength ) ; System . arraycopy ( allInterfaces , , all , classesLength , interfacesLength ) ; return all ; } public int getCachedFlags ( IType type ) { Integer flagObject = ( Integer ) this . typeFlags . get ( type ) ; if ( flagObject != null ) { return flagObject . intValue ( ) ; } return - ; } public IType [ ] getExtendingModules ( IType type ) { if ( ! this . isModule ( type ) ) return NO_TYPE ; return getExtendingModules0 ( type ) ; } private IType [ ] getExtendingModules0 ( IType extendedInterface ) { ArrayList < IType > interfaceList = new ArrayList < IType > ( ) ; for ( IType type : this . typeToSuperModules . keySet ( ) ) { if ( ! this . isModule ( type ) ) { continue ; } IType [ ] superInterfaces = this . typeToSuperModules . get ( type ) ; if ( superInterfaces != null ) { for ( IType superInterface : superInterfaces ) { if ( superInterface . equals ( extendedInterface ) ) { interfaceList . add ( type ) ; } } } } IType [ ] extendingInterfaces = new IType [ interfaceList . size ( ) ] ; interfaceList . toArray ( extendingInterfaces ) ; return extendingInterfaces ; } public IType [ ] getIncludingClasses ( IType type ) { if ( ! this . isModule ( type ) ) { return NO_TYPE ; } return getIncludingClasses0 ( type ) ; } private IType [ ] getIncludingClasses0 ( IType interfce ) { ArrayList < IType > iMenters = new ArrayList < IType > ( ) ; for ( IType type : this . typeToSuperModules . keySet ( ) ) { if ( this . isModule ( type ) ) { continue ; } IType [ ] types = this . typeToSuperModules . get ( type ) ; for ( IType iFace : types ) { if ( iFace . equals ( interfce ) ) { iMenters . add ( type ) ; } } } IType [ ] implementers = new IType [ iMenters . size ( ) ] ; iMenters . toArray ( implementers ) ; return implementers ; } public IType [ ] getRootClasses ( ) { return this . rootClasses . elements ( ) ; } public IType [ ] getRootModules ( ) { IType [ ] allInterfaces = getAllModules ( ) ; IType [ ] roots = new IType [ allInterfaces . length ] ; int rootNumber = ; for ( int i = ; i < allInterfaces . length ; i ++ ) { IType [ ] superInterfaces = getSuperModules ( allInterfaces [ i ] ) ; if ( superInterfaces == null || superInterfaces . length == ) { roots [ rootNumber ++ ] = allInterfaces [ i ] ; } } IType [ ] result = new IType [ rootNumber ] ; if ( result . length > ) { System . arraycopy ( roots , , result , , rootNumber ) ; } return result ; } public IType [ ] getSubclasses ( IType type ) { if ( this . isModule ( type ) ) { return NO_TYPE ; } TypeVector vector = ( TypeVector ) this . typeToSubtypes . get ( type ) ; if ( vector == null ) return NO_TYPE ; else return vector . elements ( ) ; } public IType [ ] getSubtypes ( IType type ) { return getSubtypesForType ( type ) ; } private IType [ ] getSubtypesForType ( IType type ) { TypeVector vector = ( TypeVector ) this . typeToSubtypes . get ( type ) ; if ( vector == null ) return NO_TYPE ; else return vector . elements ( ) ; } public IType getSuperclass ( IType type ) { if ( this . isModule ( type ) ) { return null ; } return ( IType ) this . classToSuperclass . get ( type ) ; } public IType [ ] getSuperModules ( IType type ) { IType [ ] types = ( IType [ ] ) this . typeToSuperModules . get ( type ) ; if ( types == null ) { return NO_TYPE ; } return types ; } public IType [ ] getSupertypes ( IType type ) { IType superclass = getSuperclass ( type ) ; if ( superclass == null ) { return getSuperModules ( type ) ; } else { TypeVector superTypes = new TypeVector ( getSuperModules ( type ) ) ; superTypes . add ( superclass ) ; return superTypes . elements ( ) ; } } public IType getType ( ) { return this . focusType ; } protected IType [ ] growAndAddToArray ( IType [ ] array , IType [ ] additions ) { if ( array == null || array . length == ) { return additions ; } IType [ ] old = array ; array = new IType [ old . length + additions . length ] ; System . arraycopy ( old , , array , , old . length ) ; System . arraycopy ( additions , , array , old . length , additions . length ) ; return array ; } protected IType [ ] growAndAddToArray ( IType [ ] array , IType addition ) { if ( array == null || array . length == ) { return new IType [ ] { addition } ; } IType [ ] old = array ; array = new IType [ old . length + ] ; System . arraycopy ( old , , array , , old . length ) ; array [ old . length ] = addition ; return array ; } public boolean hasFineGrainChanges ( ) { ChangeCollector collector = this . changeCollector ; return collector != null && collector . needsRefresh ( ) ; } private boolean hasSubtypeNamed ( String simpleName ) { if ( this . focusType != null && this . focusType . getElementName ( ) . equals ( simpleName ) ) { return true ; } IType [ ] types = this . focusType == null ? getAllTypes ( ) : getAllSubtypes ( this . focusType ) ; for ( int i = , length = types . length ; i < length ; i ++ ) { if ( types [ i ] . getElementName ( ) . equals ( simpleName ) ) { return true ; } } return false ; } private boolean hasTypeNamed ( String simpleName ) { IType [ ] types = this . getAllTypes ( ) ; for ( int i = , length = types . length ; i < length ; i ++ ) { if ( types [ i ] . getElementName ( ) . equals ( simpleName ) ) { return true ; } } return false ; } boolean includesTypeOrSupertype ( IType type ) { try { if ( hasTypeNamed ( type . getElementName ( ) ) ) return true ; String superclassName = type . getSuperclassName ( ) ; if ( superclassName != null ) { int lastSeparator = superclassName . lastIndexOf ( '' ) ; String simpleName = superclassName . substring ( lastSeparator + ) ; if ( hasTypeNamed ( simpleName ) ) return true ; } String [ ] superinterfaceNames = type . getIncludedModuleNames ( ) ; if ( superinterfaceNames != null ) { for ( int i = , length = superinterfaceNames . length ; i < length ; i ++ ) { String superinterfaceName = superinterfaceNames [ i ] ; int lastSeparator = superinterfaceName . lastIndexOf ( '' ) ; String simpleName = superinterfaceName . substring ( lastSeparator + ) ; if ( hasTypeNamed ( simpleName ) ) return true ; } } } catch ( RubyModelException e ) { } return false ; } protected void initialize ( int size ) { if ( size < ) { size = ; } int smallSize = ( size / ) ; this . classToSuperclass = new HashMap < IType , IType > ( size ) ; this . modules = new ArrayList < IType > ( smallSize ) ; this . missingTypes = new ArrayList < String > ( smallSize ) ; this . rootClasses = new TypeVector ( ) ; this . typeToSubtypes = new HashMap < IType , TypeVector > ( smallSize ) ; this . typeToSuperModules = new HashMap < IType , IType [ ] > ( smallSize ) ; this . typeFlags = new HashMap < IType , Integer > ( smallSize ) ; this . projectRegion = new Region ( ) ; this . packageRegion = new Region ( ) ; this . files = new HashMap < IOpenable , ArrayList < IType > > ( ) ; } public synchronized boolean isAffected ( IRubyElementDelta delta ) { IRubyElement element = delta . getElement ( ) ; switch ( element . getElementType ( ) ) { case IRubyElement . RUBY_MODEL : return isAffectedByRubyModel ( delta , element ) ; case IRubyElement . RUBY_PROJECT : return isAffectedByRubyProject ( delta , element ) ; case IRubyElement . SOURCE_FOLDER_ROOT : return isAffectedBySourceFolderRoot ( delta , element ) ; case IRubyElement . SOURCE_FOLDER : return isAffectedBySourceFolder ( delta , ( SourceFolder ) element ) ; case IRubyElement . SCRIPT : return isAffectedByOpenable ( delta , element ) ; } return false ; } private boolean isAffectedByChildren ( IRubyElementDelta delta ) { if ( ( delta . getFlags ( ) & IRubyElementDelta . F_CHILDREN ) > ) { IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( isAffected ( children [ i ] ) ) { return true ; } } } return false ; } private boolean isAffectedByRubyModel ( IRubyElementDelta delta , IRubyElement element ) { switch ( delta . getKind ( ) ) { case IRubyElementDelta . ADDED : case IRubyElementDelta . REMOVED : return element . equals ( this . rubyProject ( ) . getRubyModel ( ) ) ; case IRubyElementDelta . CHANGED : return isAffectedByChildren ( delta ) ; } return false ; } private boolean isAffectedByRubyProject ( IRubyElementDelta delta , IRubyElement element ) { int kind = delta . getKind ( ) ; int flags = delta . getFlags ( ) ; if ( ( flags & IRubyElementDelta . F_OPENED ) != ) { kind = IRubyElementDelta . ADDED ; } if ( ( flags & IRubyElementDelta . F_CLOSED ) != ) { kind = IRubyElementDelta . REMOVED ; } switch ( kind ) { case IRubyElementDelta . ADDED : try { ILoadpathEntry [ ] classpath = ( ( RubyProject ) this . rubyProject ( ) ) . getExpandedLoadpath ( true ) ; for ( int i = ; i < classpath . length ; i ++ ) { if ( classpath [ i ] . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT && classpath [ i ] . getPath ( ) . equals ( element . getPath ( ) ) ) { return true ; } } if ( this . focusType != null ) { classpath = ( ( RubyProject ) element ) . getExpandedLoadpath ( true ) ; IPath hierarchyProject = rubyProject ( ) . getPath ( ) ; for ( int i = ; i < classpath . length ; i ++ ) { if ( classpath [ i ] . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT && classpath [ i ] . getPath ( ) . equals ( hierarchyProject ) ) { return true ; } } } return false ; } catch ( RubyModelException e ) { return false ; } case IRubyElementDelta . REMOVED : IRubyElement [ ] pkgs = this . packageRegion . getElements ( ) ; for ( int i = ; i < pkgs . length ; i ++ ) { IRubyProject javaProject = pkgs [ i ] . getRubyProject ( ) ; if ( javaProject != null && javaProject . equals ( element ) ) { return true ; } } return false ; case IRubyElementDelta . CHANGED : return isAffectedByChildren ( delta ) ; } return false ; } private boolean isAffectedBySourceFolder ( IRubyElementDelta delta , SourceFolder element ) { switch ( delta . getKind ( ) ) { case IRubyElementDelta . ADDED : return this . projectRegion . contains ( element ) ; case IRubyElementDelta . REMOVED : return packageRegionContainsSameSourceFolder ( element ) ; case IRubyElementDelta . CHANGED : return isAffectedByChildren ( delta ) ; } return false ; } private boolean isAffectedBySourceFolderRoot ( IRubyElementDelta delta , IRubyElement element ) { switch ( delta . getKind ( ) ) { case IRubyElementDelta . ADDED : return this . projectRegion . contains ( element ) ; case IRubyElementDelta . REMOVED : case IRubyElementDelta . CHANGED : int flags = delta . getFlags ( ) ; if ( ( flags & IRubyElementDelta . F_ADDED_TO_CLASSPATH ) > ) { if ( this . projectRegion != null ) { ISourceFolderRoot root = ( ISourceFolderRoot ) element ; IPath rootPath = root . getPath ( ) ; IRubyElement [ ] elements = this . projectRegion . getElements ( ) ; for ( int i = ; i < elements . length ; i ++ ) { RubyProject javaProject = ( RubyProject ) elements [ i ] ; try { ILoadpathEntry [ ] classpath = javaProject . getResolvedLoadpath ( true , false , false ) ; for ( int j = ; j < classpath . length ; j ++ ) { ILoadpathEntry entry = classpath [ j ] ; if ( entry . getPath ( ) . equals ( rootPath ) ) { return true ; } } } catch ( RubyModelException e ) { } } } } if ( ( flags & IRubyElementDelta . F_REMOVED_FROM_CLASSPATH ) > || ( flags & IRubyElementDelta . F_CONTENT ) > ) { IRubyElement [ ] pkgs = this . packageRegion . getElements ( ) ; for ( int i = ; i < pkgs . length ; i ++ ) { if ( pkgs [ i ] . getParent ( ) . equals ( element ) ) { return true ; } } return false ; } } return isAffectedByChildren ( delta ) ; } protected boolean isAffectedByOpenable ( IRubyElementDelta delta , IRubyElement element ) { if ( element instanceof RubyScript ) { RubyScript cu = ( RubyScript ) element ; ChangeCollector collector = this . changeCollector ; if ( collector == null ) { collector = new ChangeCollector ( this ) ; } try { collector . addChange ( cu , delta ) ; } catch ( RubyModelException e ) { if ( DEBUG ) e . printStackTrace ( ) ; } if ( cu . isWorkingCopy ( ) ) { this . changeCollector = collector ; return false ; } else { return collector . needsRefresh ( ) ; } } return false ; } private boolean isModule ( IType type ) { return type . isModule ( ) ; } public IRubyProject rubyProject ( ) { return this . focusType . getRubyProject ( ) ; } protected static byte [ ] readUntil ( InputStream input , byte separator ) throws RubyModelException , IOException { return readUntil ( input , separator , ) ; } protected static byte [ ] readUntil ( InputStream input , byte separator , int offset ) throws IOException , RubyModelException { int length = ; byte [ ] bytes = new byte [ SIZE ] ; byte b ; while ( ( b = ( byte ) input . read ( ) ) != separator && b != - ) { if ( bytes . length == length ) { System . arraycopy ( bytes , , bytes = new byte [ length * ] , , length ) ; } bytes [ length ++ ] = b ; } if ( b == - ) { throw new RubyModelException ( new RubyModelStatus ( IStatus . ERROR ) ) ; } System . arraycopy ( bytes , , bytes = new byte [ length + offset ] , offset , length ) ; return bytes ; } public static ITypeHierarchy load ( IType type , InputStream input , WorkingCopyOwner owner ) throws RubyModelException { try { TypeHierarchy typeHierarchy = new TypeHierarchy ( ) ; typeHierarchy . initialize ( ) ; IType [ ] types = new IType [ SIZE ] ; int typeCount = ; byte version = ( byte ) input . read ( ) ; if ( version != VERSION ) { throw new RubyModelException ( new RubyModelStatus ( IStatus . ERROR ) ) ; } byte generalInfo = ( byte ) input . read ( ) ; if ( ( generalInfo & COMPUTE_SUBTYPES ) != ) { typeHierarchy . computeSubtypes = true ; } byte b ; byte [ ] bytes ; bytes = readUntil ( input , SEPARATOR1 ) ; if ( bytes . length > ) { typeHierarchy . project = ( IRubyProject ) RubyCore . create ( new String ( bytes ) ) ; typeHierarchy . scope = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { typeHierarchy . project } ) ; } else { typeHierarchy . project = null ; typeHierarchy . scope = SearchEngine . createWorkspaceScope ( ) ; } { bytes = readUntil ( input , SEPARATOR1 ) ; byte [ ] missing ; int j = ; int length = bytes . length ; for ( int i = ; i < length ; i ++ ) { b = bytes [ i ] ; if ( b == SEPARATOR2 ) { missing = new byte [ i - j ] ; System . arraycopy ( bytes , j , missing , , i - j ) ; typeHierarchy . missingTypes . add ( new String ( missing ) ) ; j = i + ; } } System . arraycopy ( bytes , j , missing = new byte [ length - j ] , , length - j ) ; typeHierarchy . missingTypes . add ( new String ( missing ) ) ; } while ( ( b = ( byte ) input . read ( ) ) != SEPARATOR1 && b != - ) { bytes = readUntil ( input , SEPARATOR4 , ) ; bytes [ ] = b ; IType element = ( IType ) RubyCore . create ( new String ( bytes ) , owner ) ; if ( types . length == typeCount ) { System . arraycopy ( types , , types = new IType [ typeCount * ] , , typeCount ) ; } types [ typeCount ++ ] = element ; bytes = readUntil ( input , SEPARATOR4 ) ; Integer flags = bytesToFlags ( bytes ) ; if ( flags != null ) { typeHierarchy . cacheFlags ( element , flags . intValue ( ) ) ; } byte info = ( byte ) input . read ( ) ; if ( ( info & INTERFACE ) != ) { typeHierarchy . addModule ( element ) ; } if ( ( info & COMPUTED_FOR ) != ) { if ( ! element . equals ( type ) ) { throw new RubyModelException ( new RubyModelStatus ( IStatus . ERROR ) ) ; } typeHierarchy . focusType = element ; } if ( ( info & ROOT ) != ) { typeHierarchy . addRootClass ( element ) ; } } while ( ( b = ( byte ) input . read ( ) ) != SEPARATOR1 && b != - ) { bytes = readUntil ( input , SEPARATOR3 , ) ; bytes [ ] = b ; int subClass = new Integer ( new String ( bytes ) ) . intValue ( ) ; bytes = readUntil ( input , SEPARATOR1 ) ; int superClass = new Integer ( new String ( bytes ) ) . intValue ( ) ; typeHierarchy . cacheSuperclass ( types [ subClass ] , types [ superClass ] ) ; } while ( ( b = ( byte ) input . read ( ) ) != SEPARATOR1 && b != - ) { bytes = readUntil ( input , SEPARATOR3 , ) ; bytes [ ] = b ; int subClass = new Integer ( new String ( bytes ) ) . intValue ( ) ; bytes = readUntil ( input , SEPARATOR1 ) ; IType [ ] superInterfaces = new IType [ ( bytes . length / ) + ] ; int interfaceCount = ; int j = ; byte [ ] b2 ; for ( int i = ; i < bytes . length ; i ++ ) { if ( bytes [ i ] == SEPARATOR2 ) { b2 = new byte [ i - j ] ; System . arraycopy ( bytes , j , b2 , , i - j ) ; j = i + ; superInterfaces [ interfaceCount ++ ] = types [ new Integer ( new String ( b2 ) ) . intValue ( ) ] ; } } b2 = new byte [ bytes . length - j ] ; System . arraycopy ( bytes , j , b2 , , bytes . length - j ) ; superInterfaces [ interfaceCount ++ ] = types [ new Integer ( new String ( b2 ) ) . intValue ( ) ] ; System . arraycopy ( superInterfaces , , superInterfaces = new IType [ interfaceCount ] , , interfaceCount ) ; typeHierarchy . cacheSuperModules ( types [ subClass ] , superInterfaces ) ; } if ( b == - ) { throw new RubyModelException ( new RubyModelStatus ( IStatus . ERROR ) ) ; } return typeHierarchy ; } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } } protected boolean packageRegionContainsSameSourceFolder ( SourceFolder element ) { IRubyElement [ ] pkgs = this . packageRegion . getElements ( ) ; for ( int i = ; i < pkgs . length ; i ++ ) { SourceFolder pkg = ( SourceFolder ) pkgs [ i ] ; if ( Util . equalArraysOrNull ( pkg . names , element . names ) ) return true ; } return false ; } public synchronized void refresh ( IProgressMonitor monitor ) throws RubyModelException { try { this . progressMonitor = monitor ; if ( monitor != null ) { if ( this . focusType != null ) { monitor . beginTask ( Messages . bind ( Messages . hierarchy_creatingOnType , this . focusType . getFullyQualifiedName ( ) ) , ) ; } else { monitor . beginTask ( Messages . hierarchy_creating , ) ; } } long start = - ; if ( DEBUG ) { start = System . currentTimeMillis ( ) ; if ( this . computeSubtypes ) { System . out . println ( "" + Thread . currentThread ( ) + "" ) ; } else { System . out . println ( "" + Thread . currentThread ( ) + "" ) ; } if ( this . focusType != null ) { System . out . println ( "" + ( ( RubyElement ) this . focusType ) . toStringWithAncestors ( ) ) ; } } compute ( ) ; initializeRegions ( ) ; this . needsRefresh = false ; this . changeCollector = null ; if ( DEBUG ) { if ( this . computeSubtypes ) { System . out . println ( "" + ( System . currentTimeMillis ( ) - start ) + "" ) ; } else { System . out . println ( "" + ( System . currentTimeMillis ( ) - start ) + "" ) ; } System . out . println ( this . toString ( ) ) ; } } catch ( RubyModelException e ) { throw e ; } catch ( CoreException e ) { throw new RubyModelException ( e ) ; } finally { if ( monitor != null ) { monitor . done ( ) ; } this . progressMonitor = null ; } } public synchronized void removeTypeHierarchyChangedListener ( ITypeHierarchyChangedListener listener ) { ArrayList < ITypeHierarchyChangedListener > listeners = this . changeListeners ; if ( listeners == null ) { return ; } listeners . remove ( listener ) ; if ( listeners . isEmpty ( ) ) { RubyCore . removeElementChangedListener ( this ) ; } } public void store ( OutputStream output , IProgressMonitor monitor ) throws RubyModelException { try { Hashtable < IType , Integer > hashtable = new Hashtable < IType , Integer > ( ) ; Hashtable < Integer , IType > hashtable2 = new Hashtable < Integer , IType > ( ) ; int count = ; if ( this . focusType != null ) { Integer index = new Integer ( count ++ ) ; hashtable . put ( this . focusType , index ) ; hashtable2 . put ( index , this . focusType ) ; } IType [ ] types = ( IType [ ] ) this . classToSuperclass . keySet ( ) . toArray ( ) ; for ( IType t : types ) { if ( hashtable . get ( t ) == null ) { Integer index = new Integer ( count ++ ) ; hashtable . put ( t , index ) ; hashtable2 . put ( index , t ) ; } IType superClass = this . classToSuperclass . get ( t ) ; if ( superClass != null && hashtable . get ( superClass ) == null ) { Integer index = new Integer ( count ++ ) ; hashtable . put ( superClass , index ) ; hashtable2 . put ( index , superClass ) ; } } types = ( IType [ ] ) this . typeToSuperModules . keySet ( ) . toArray ( ) ; for ( IType t : types ) { if ( hashtable . get ( t ) == null ) { Integer index = new Integer ( count ++ ) ; hashtable . put ( t , index ) ; hashtable2 . put ( index , t ) ; } IType [ ] sp = this . typeToSuperModules . get ( t ) ; if ( sp != null ) { for ( IType superInterface : sp ) { if ( superInterface != null && hashtable . get ( superInterface ) == null ) { Integer index = new Integer ( count ++ ) ; hashtable . put ( superInterface , index ) ; hashtable2 . put ( index , superInterface ) ; } } } } output . write ( VERSION ) ; byte generalInfo = ; if ( this . computeSubtypes ) { generalInfo |= COMPUTE_SUBTYPES ; } output . write ( generalInfo ) ; if ( this . project != null ) { output . write ( this . project . getHandleIdentifier ( ) . getBytes ( ) ) ; } output . write ( SEPARATOR1 ) ; for ( int i = ; i < this . missingTypes . size ( ) ; i ++ ) { if ( i != ) { output . write ( SEPARATOR2 ) ; } output . write ( ( ( String ) this . missingTypes . get ( i ) ) . getBytes ( ) ) ; } output . write ( SEPARATOR1 ) ; for ( int i = ; i < count ; i ++ ) { IType t = hashtable2 . get ( new Integer ( i ) ) ; output . write ( t . getHandleIdentifier ( ) . getBytes ( ) ) ; output . write ( SEPARATOR4 ) ; output . write ( flagsToBytes ( this . typeFlags . get ( t ) ) ) ; output . write ( SEPARATOR4 ) ; byte info = CLASS ; if ( this . focusType != null && this . focusType . equals ( t ) ) { info |= COMPUTED_FOR ; } if ( this . modules . contains ( t ) ) { info |= INTERFACE ; } if ( this . rootClasses . contains ( t ) ) { info |= ROOT ; } output . write ( info ) ; } output . write ( SEPARATOR1 ) ; types = ( IType [ ] ) this . classToSuperclass . keySet ( ) . toArray ( ) ; for ( int i = ; i < types . length ; i ++ ) { IRubyElement key = types [ i ] ; IRubyElement value = this . classToSuperclass . get ( key ) ; output . write ( ( hashtable . get ( key ) ) . toString ( ) . getBytes ( ) ) ; output . write ( '>' ) ; output . write ( ( hashtable . get ( value ) ) . toString ( ) . getBytes ( ) ) ; output . write ( SEPARATOR1 ) ; } output . write ( SEPARATOR1 ) ; types = ( IType [ ] ) this . typeToSuperModules . keySet ( ) . toArray ( ) ; for ( int i = ; i < types . length ; i ++ ) { IRubyElement key = types [ i ] ; IRubyElement [ ] values = this . typeToSuperModules . get ( key ) ; if ( values . length > ) { output . write ( ( hashtable . get ( key ) ) . toString ( ) . getBytes ( ) ) ; output . write ( SEPARATOR3 ) ; for ( int j = ; j < values . length ; j ++ ) { IRubyElement value = values [ j ] ; if ( j != ) output . write ( SEPARATOR2 ) ; output . write ( ( hashtable . get ( value ) ) . toString ( ) . getBytes ( ) ) ; } output . write ( SEPARATOR1 ) ; } } output . write ( SEPARATOR1 ) ; } catch ( IOException e ) { throw new RubyModelException ( e , IRubyModelStatusConstants . IO_EXCEPTION ) ; } } boolean subtypesIncludeSupertypeOf ( IType type ) { String superclassName = null ; try { superclassName = type . getSuperclassName ( ) ; } catch ( RubyModelException e ) { if ( DEBUG ) { e . printStackTrace ( ) ; } return false ; } if ( superclassName == null ) { superclassName = "" ; } int dot = - ; String simpleSuper = ( dot = superclassName . lastIndexOf ( '' ) ) > - ? superclassName . substring ( dot + ) : superclassName ; if ( hasSubtypeNamed ( simpleSuper ) ) { return true ; } String [ ] interfaceNames = null ; try { interfaceNames = type . getIncludedModuleNames ( ) ; } catch ( RubyModelException e ) { if ( DEBUG ) e . printStackTrace ( ) ; return false ; } for ( int i = , length = interfaceNames . length ; i < length ; i ++ ) { dot = - ; String interfaceName = interfaceNames [ i ] ; String simpleInterface = ( dot = interfaceName . lastIndexOf ( '' ) ) > - ? interfaceName . substring ( dot ) : interfaceName ; if ( hasSubtypeNamed ( simpleInterface ) ) { return true ; } } return false ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( this . focusType == null ? "" : ( ( RubyElement ) this . focusType ) . toStringWithAncestors ( false ) ) ; buffer . append ( "" ) ; if ( exists ( ) ) { if ( this . focusType != null ) { buffer . append ( "" ) ; toString ( buffer , this . focusType , , true ) ; buffer . append ( "" ) ; toString ( buffer , this . focusType , , false ) ; } else { buffer . append ( "" ) ; IRubyElement [ ] roots = Util . sortCopy ( getRootClasses ( ) ) ; for ( int i = ; i < roots . length ; i ++ ) { toString ( buffer , ( IType ) roots [ i ] , , false ) ; } } if ( this . rootClasses . size > ) { buffer . append ( "" ) ; IRubyElement [ ] roots = Util . sortCopy ( getRootClasses ( ) ) ; for ( int i = , length = roots . length ; i < length ; i ++ ) { toString ( buffer , ( IType ) roots [ i ] , , false ) ; } } else if ( this . rootClasses . size == ) { buffer . append ( "" ) ; } } else { buffer . append ( "" ) ; } return buffer . toString ( ) ; } private void toString ( StringBuffer buffer , IType type , int indent , boolean ascendant ) { IType [ ] types = ascendant ? getSupertypes ( type ) : getSubtypes ( type ) ; IRubyElement [ ] sortedTypes = Util . sortCopy ( types ) ; for ( int i = ; i < sortedTypes . length ; i ++ ) { for ( int j = ; j < indent ; j ++ ) { buffer . append ( "" ) ; } RubyElement element = ( RubyElement ) sortedTypes [ i ] ; buffer . append ( element . toStringWithAncestors ( false ) ) ; buffer . append ( '' ) ; toString ( buffer , types [ i ] , indent + , ascendant ) ; } } boolean hasSupertype ( String simpleName ) { for ( IType superType : this . classToSuperclass . values ( ) ) { if ( superType . getElementName ( ) . equals ( simpleName ) ) { return true ; } } return false ; } protected void worked ( int work ) { if ( this . progressMonitor != null ) { this . progressMonitor . worked ( work ) ; checkCanceled ( ) ; } } } package org . rubypeople . rdt . internal . core . hierarchy ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyElement ; import org . rubypeople . rdt . internal . core . SimpleDelta ; public class ChangeCollector { private Map < IRubyElement , SimpleDelta > changes = new HashMap < IRubyElement , SimpleDelta > ( ) ; private TypeHierarchy hierarchy ; public ChangeCollector ( TypeHierarchy hierarchy ) { this . hierarchy = hierarchy ; } private void addAffectedChildren ( IRubyElementDelta delta ) throws RubyModelException { IRubyElementDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { IRubyElementDelta child = children [ i ] ; IRubyElement childElement = child . getElement ( ) ; switch ( childElement . getElementType ( ) ) { case IRubyElement . IMPORT_CONTAINER : addChange ( ( IImportContainer ) childElement , child ) ; break ; case IRubyElement . IMPORT_DECLARATION : addChange ( ( IImportDeclaration ) childElement , child ) ; break ; case IRubyElement . TYPE : addChange ( ( IType ) childElement , child ) ; break ; case IRubyElement . FIELD : case IRubyElement . METHOD : addChange ( ( IMember ) childElement , child ) ; break ; } } } public void addChange ( IRubyScript cu , IRubyElementDelta newDelta ) throws RubyModelException { int newKind = newDelta . getKind ( ) ; switch ( newKind ) { case IRubyElementDelta . ADDED : ArrayList < IType > allTypes = new ArrayList < IType > ( ) ; getAllTypesFromElement ( cu , allTypes ) ; for ( int i = , length = allTypes . size ( ) ; i < length ; i ++ ) { IType type = allTypes . get ( i ) ; addTypeAddition ( type , ( SimpleDelta ) this . changes . get ( type ) ) ; } break ; case IRubyElementDelta . REMOVED : allTypes = new ArrayList < IType > ( ) ; getAllTypesFromHierarchy ( ( RubyElement ) cu , allTypes ) ; for ( int i = , length = allTypes . size ( ) ; i < length ; i ++ ) { IType type = allTypes . get ( i ) ; addTypeRemoval ( type , ( SimpleDelta ) this . changes . get ( type ) ) ; } break ; case IRubyElementDelta . CHANGED : addAffectedChildren ( newDelta ) ; break ; } } private void addChange ( IImportContainer importContainer , IRubyElementDelta newDelta ) throws RubyModelException { int newKind = newDelta . getKind ( ) ; if ( newKind == IRubyElementDelta . CHANGED ) { addAffectedChildren ( newDelta ) ; return ; } SimpleDelta existingDelta = ( SimpleDelta ) this . changes . get ( importContainer ) ; if ( existingDelta != null ) { switch ( newKind ) { case IRubyElementDelta . ADDED : if ( existingDelta . getKind ( ) == IRubyElementDelta . REMOVED ) { this . changes . remove ( importContainer ) ; } break ; case IRubyElementDelta . REMOVED : if ( existingDelta . getKind ( ) == IRubyElementDelta . ADDED ) { this . changes . remove ( importContainer ) ; } break ; } } else { SimpleDelta delta = new SimpleDelta ( ) ; switch ( newKind ) { case IRubyElementDelta . ADDED : delta . added ( ) ; break ; case IRubyElementDelta . REMOVED : delta . removed ( ) ; break ; } this . changes . put ( importContainer , delta ) ; } } private void addChange ( IImportDeclaration importDecl , IRubyElementDelta newDelta ) { SimpleDelta existingDelta = ( SimpleDelta ) this . changes . get ( importDecl ) ; int newKind = newDelta . getKind ( ) ; if ( existingDelta != null ) { switch ( newKind ) { case IRubyElementDelta . ADDED : if ( existingDelta . getKind ( ) == IRubyElementDelta . REMOVED ) { this . changes . remove ( importDecl ) ; } break ; case IRubyElementDelta . REMOVED : if ( existingDelta . getKind ( ) == IRubyElementDelta . ADDED ) { this . changes . remove ( importDecl ) ; } break ; } } else { SimpleDelta delta = new SimpleDelta ( ) ; switch ( newKind ) { case IRubyElementDelta . ADDED : delta . added ( ) ; break ; case IRubyElementDelta . REMOVED : delta . removed ( ) ; break ; } this . changes . put ( importDecl , delta ) ; } } private void addChange ( IMember member , IRubyElementDelta newDelta ) throws RubyModelException { int newKind = newDelta . getKind ( ) ; switch ( newKind ) { case IRubyElementDelta . ADDED : ArrayList < IType > allTypes = new ArrayList < IType > ( ) ; getAllTypesFromElement ( member , allTypes ) ; for ( int i = , length = allTypes . size ( ) ; i < length ; i ++ ) { IType innerType = allTypes . get ( i ) ; addTypeAddition ( innerType , ( SimpleDelta ) this . changes . get ( innerType ) ) ; } break ; case IRubyElementDelta . REMOVED : allTypes = new ArrayList < IType > ( ) ; getAllTypesFromHierarchy ( ( RubyElement ) member , allTypes ) ; for ( int i = , length = allTypes . size ( ) ; i < length ; i ++ ) { IType type = allTypes . get ( i ) ; addTypeRemoval ( type , ( SimpleDelta ) this . changes . get ( type ) ) ; } break ; case IRubyElementDelta . CHANGED : addAffectedChildren ( newDelta ) ; break ; } } private void addChange ( IType type , IRubyElementDelta newDelta ) throws RubyModelException { int newKind = newDelta . getKind ( ) ; SimpleDelta existingDelta = ( SimpleDelta ) this . changes . get ( type ) ; switch ( newKind ) { case IRubyElementDelta . ADDED : addTypeAddition ( type , existingDelta ) ; ArrayList < IType > allTypes = new ArrayList < IType > ( ) ; getAllTypesFromElement ( type , allTypes ) ; for ( int i = , length = allTypes . size ( ) ; i < length ; i ++ ) { IType innerType = allTypes . get ( i ) ; addTypeAddition ( innerType , ( SimpleDelta ) this . changes . get ( innerType ) ) ; } break ; case IRubyElementDelta . REMOVED : addTypeRemoval ( type , existingDelta ) ; allTypes = new ArrayList < IType > ( ) ; getAllTypesFromHierarchy ( ( RubyElement ) type , allTypes ) ; for ( int i = , length = allTypes . size ( ) ; i < length ; i ++ ) { IType innerType = allTypes . get ( i ) ; addTypeRemoval ( innerType , ( SimpleDelta ) this . changes . get ( innerType ) ) ; } break ; case IRubyElementDelta . CHANGED : addTypeChange ( type , newDelta . getFlags ( ) , existingDelta ) ; addAffectedChildren ( newDelta ) ; break ; } } private void addTypeAddition ( IType type , SimpleDelta existingDelta ) throws RubyModelException { if ( existingDelta != null ) { switch ( existingDelta . getKind ( ) ) { case IRubyElementDelta . REMOVED : boolean hasChange = false ; if ( hasSuperTypeChange ( type ) ) { existingDelta . superTypes ( ) ; hasChange = true ; } if ( ! hasChange ) { this . changes . remove ( type ) ; } break ; } } else { String typeName = type . getElementName ( ) ; if ( this . hierarchy . hasSupertype ( typeName ) || this . hierarchy . subtypesIncludeSupertypeOf ( type ) || this . hierarchy . missingTypes . contains ( typeName ) ) { SimpleDelta delta = new SimpleDelta ( ) ; delta . added ( ) ; this . changes . put ( type , delta ) ; } } } private void addTypeChange ( IType type , int newFlags , SimpleDelta existingDelta ) throws RubyModelException { if ( existingDelta != null ) { switch ( existingDelta . getKind ( ) ) { case IRubyElementDelta . CHANGED : int existingFlags = existingDelta . getFlags ( ) ; boolean hasChange = false ; if ( ( existingFlags & IRubyElementDelta . F_SUPER_TYPES ) != && hasSuperTypeChange ( type ) ) { existingDelta . superTypes ( ) ; hasChange = true ; } if ( ! hasChange ) { this . changes . remove ( type ) ; } break ; } } else { SimpleDelta typeDelta = null ; if ( ( newFlags & IRubyElementDelta . F_SUPER_TYPES ) != && this . hierarchy . includesTypeOrSupertype ( type ) ) { typeDelta = new SimpleDelta ( ) ; typeDelta . superTypes ( ) ; } if ( ( newFlags & IRubyElementDelta . F_MODIFIERS ) != && ( this . hierarchy . hasSupertype ( type . getElementName ( ) ) || type . equals ( this . hierarchy . focusType ) ) ) { if ( typeDelta == null ) { typeDelta = new SimpleDelta ( ) ; } typeDelta . modifiers ( ) ; } if ( typeDelta != null ) { this . changes . put ( type , typeDelta ) ; } } } private void addTypeRemoval ( IType type , SimpleDelta existingDelta ) { if ( existingDelta != null ) { switch ( existingDelta . getKind ( ) ) { case IRubyElementDelta . ADDED : this . changes . remove ( type ) ; break ; case IRubyElementDelta . CHANGED : existingDelta . removed ( ) ; break ; } } else { if ( this . hierarchy . contains ( type ) ) { SimpleDelta typeDelta = new SimpleDelta ( ) ; typeDelta . removed ( ) ; this . changes . put ( type , typeDelta ) ; } } } private void getAllTypesFromElement ( IRubyElement element , ArrayList < IType > allTypes ) throws RubyModelException { switch ( element . getElementType ( ) ) { case IRubyElement . SCRIPT : IType [ ] types = ( ( IRubyScript ) element ) . getTypes ( ) ; for ( int i = , length = types . length ; i < length ; i ++ ) { IType type = types [ i ] ; allTypes . add ( type ) ; getAllTypesFromElement ( type , allTypes ) ; } break ; case IRubyElement . TYPE : types = ( ( IType ) element ) . getTypes ( ) ; for ( int i = , length = types . length ; i < length ; i ++ ) { IType type = types [ i ] ; allTypes . add ( type ) ; getAllTypesFromElement ( type , allTypes ) ; } break ; case IRubyElement . FIELD : case IRubyElement . METHOD : IRubyElement [ ] children = ( ( IMember ) element ) . getChildren ( ) ; for ( int i = , length = children . length ; i < length ; i ++ ) { if ( children [ i ] instanceof IType ) { IType type = ( IType ) children [ i ] ; allTypes . add ( type ) ; getAllTypesFromElement ( type , allTypes ) ; } } break ; } } private void getAllTypesFromHierarchy ( RubyElement element , ArrayList < IType > allTypes ) { switch ( element . getElementType ( ) ) { case IRubyElement . SCRIPT : ArrayList < IType > types = this . hierarchy . files . get ( element ) ; if ( types != null ) { allTypes . addAll ( types ) ; } break ; case IRubyElement . TYPE : case IRubyElement . FIELD : case IRubyElement . METHOD : types = this . hierarchy . files . get ( ( ( IMember ) element ) . getRubyScript ( ) ) ; if ( types != null ) { for ( int i = , length = types . size ( ) ; i < length ; i ++ ) { IType type = types . get ( i ) ; if ( element . isAncestorOf ( type ) ) { allTypes . add ( type ) ; } } } break ; } } private boolean hasSuperTypeChange ( IType type ) throws RubyModelException { IType superclass = this . hierarchy . getSuperclass ( type ) ; String existingSuperclassName = superclass == null ? null : superclass . getElementName ( ) ; String newSuperclassName = type . getSuperclassName ( ) ; if ( existingSuperclassName != null && ! existingSuperclassName . equals ( newSuperclassName ) ) { return true ; } IType [ ] existingSuperInterfaces = this . hierarchy . getSuperModules ( type ) ; String [ ] newSuperInterfaces = type . getIncludedModuleNames ( ) ; if ( existingSuperInterfaces . length != newSuperInterfaces . length ) { return true ; } for ( int i = , length = newSuperInterfaces . length ; i < length ; i ++ ) { String superInterfaceName = newSuperInterfaces [ i ] ; if ( ! superInterfaceName . equals ( newSuperInterfaces [ i ] ) ) { return true ; } } return false ; } public boolean needsRefresh ( ) { return changes . size ( ) != ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; Iterator < Map . Entry < IRubyElement , SimpleDelta > > iterator = this . changes . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Map . Entry < IRubyElement , SimpleDelta > entry = ( Map . Entry < IRubyElement , SimpleDelta > ) iterator . next ( ) ; buffer . append ( ( ( RubyElement ) entry . getKey ( ) ) . toDebugString ( ) ) ; buffer . append ( entry . getValue ( ) ) ; if ( iterator . hasNext ( ) ) { buffer . append ( '' ) ; } } return buffer . toString ( ) ; } } package org . rubypeople . rdt . internal . core . hierarchy ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyElement ; import org . rubypeople . rdt . internal . core . RubyProject ; public abstract class HierarchyBuilder { protected TypeHierarchy hierarchy ; protected Map infoToHandle ; protected String focusQualifiedName ; protected HierarchyResolver hierarchyResolver ; public HierarchyBuilder ( TypeHierarchy hierarchy ) throws RubyModelException { this . hierarchy = hierarchy ; RubyProject project = ( RubyProject ) hierarchy . rubyProject ( ) ; IType focusType = hierarchy . getType ( ) ; org . rubypeople . rdt . core . IRubyScript unitToLookInside = focusType == null ? null : focusType . getRubyScript ( ) ; org . rubypeople . rdt . core . IRubyScript [ ] workingCopies = this . hierarchy . workingCopies ; org . rubypeople . rdt . core . IRubyScript [ ] unitsToLookInside ; if ( unitToLookInside != null ) { int wcLength = workingCopies == null ? : workingCopies . length ; if ( wcLength == ) { unitsToLookInside = new org . rubypeople . rdt . core . IRubyScript [ ] { unitToLookInside } ; } else { unitsToLookInside = new org . rubypeople . rdt . core . IRubyScript [ wcLength + ] ; unitsToLookInside [ ] = unitToLookInside ; System . arraycopy ( workingCopies , , unitsToLookInside , , wcLength ) ; } } else { unitsToLookInside = workingCopies ; } if ( project != null ) { this . hierarchyResolver = new HierarchyResolver ( project . getOptions ( true ) , this ) ; } this . infoToHandle = new HashMap ( ) ; this . focusQualifiedName = focusType == null ? null : focusType . getFullyQualifiedName ( ) ; } public abstract void build ( boolean computeSubtypes ) throws RubyModelException , CoreException ; public void connect ( IType typeHandle , IType superclassHandle , IType [ ] superinterfaceHandles ) { if ( typeHandle == null ) return ; if ( TypeHierarchy . DEBUG ) { System . out . println ( "" + ( ( RubyElement ) typeHandle ) . toStringWithAncestors ( ) ) ; System . out . println ( "" + ( superclassHandle == null ? "" : ( ( RubyElement ) superclassHandle ) . toStringWithAncestors ( ) ) ) ; System . out . print ( "" ) ; if ( superinterfaceHandles == null || superinterfaceHandles . length == ) { System . out . println ( "" ) ; } else { System . out . println ( ) ; for ( int i = , length = superinterfaceHandles . length ; i < length ; i ++ ) { if ( superinterfaceHandles [ i ] == null ) continue ; System . out . println ( "" + ( ( RubyElement ) superinterfaceHandles [ i ] ) . toStringWithAncestors ( ) ) ; } } } if ( typeHandle . isModule ( ) ) { this . hierarchy . addModule ( typeHandle ) ; } else { if ( superclassHandle == null ) { this . hierarchy . addRootClass ( typeHandle ) ; } else { this . hierarchy . cacheSuperclass ( typeHandle , superclassHandle ) ; } } if ( superinterfaceHandles == null ) { superinterfaceHandles = TypeHierarchy . NO_TYPE ; } this . hierarchy . cacheSuperModules ( typeHandle , superinterfaceHandles ) ; this . hierarchy . cacheFlags ( typeHandle , ) ; } protected IType getType ( ) { return this . hierarchy . getType ( ) ; } protected void buildSupertypes ( ) { IType focusType = this . getType ( ) ; if ( focusType == null ) return ; this . hierarchyResolver . resolve ( focusType ) ; if ( ! this . hierarchy . contains ( focusType ) ) { this . hierarchy . addRootClass ( focusType ) ; } } protected void worked ( IProgressMonitor monitor , int work ) { if ( monitor != null ) { if ( monitor . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } else { monitor . worked ( work ) ; } } } } package org . rubypeople . rdt . internal . core . hierarchy ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyProject ; public class RegionBasedHierarchyBuilder extends HierarchyBuilder { public RegionBasedHierarchyBuilder ( TypeHierarchy hierarchy ) throws RubyModelException { super ( hierarchy ) ; } public void build ( boolean computeSubtypes ) { try { if ( this . hierarchy . focusType == null || computeSubtypes ) { IProgressMonitor typeInRegionMonitor = this . hierarchy . progressMonitor == null ? null : new SubProgressMonitor ( this . hierarchy . progressMonitor , ) ; HashMap < IRubyProject , ArrayList < IOpenable > > allOpenablesInRegion = determineOpenablesInRegion ( typeInRegionMonitor ) ; this . hierarchy . initialize ( allOpenablesInRegion . size ( ) ) ; IProgressMonitor buildMonitor = this . hierarchy . progressMonitor == null ? null : new SubProgressMonitor ( this . hierarchy . progressMonitor , ) ; createTypeHierarchyBasedOnRegion ( allOpenablesInRegion , buildMonitor ) ; ( ( RegionBasedTypeHierarchy ) this . hierarchy ) . pruneDeadBranches ( ) ; } else { this . hierarchy . initialize ( ) ; this . buildSupertypes ( ) ; } } finally { } } private void createTypeHierarchyBasedOnRegion ( HashMap < IRubyProject , ArrayList < IOpenable > > allOpenablesInRegion , IProgressMonitor monitor ) { int size = allOpenablesInRegion . size ( ) ; if ( size == ) { if ( monitor != null ) monitor . done ( ) ; return ; } this . infoToHandle = new HashMap ( size ) ; Iterator < IRubyProject > rubyProjects = allOpenablesInRegion . keySet ( ) . iterator ( ) ; while ( rubyProjects . hasNext ( ) ) { IRubyProject project = rubyProjects . next ( ) ; ArrayList < IOpenable > allOpenables = allOpenablesInRegion . get ( project ) ; IOpenable [ ] openables = new IOpenable [ allOpenables . size ( ) ] ; allOpenables . toArray ( openables ) ; try { if ( monitor != null ) monitor . beginTask ( "" , size * ) ; this . hierarchyResolver . resolve ( openables , null , monitor ) ; } finally { if ( monitor != null ) monitor . done ( ) ; } } } private HashMap < IRubyProject , ArrayList < IOpenable > > determineOpenablesInRegion ( IProgressMonitor monitor ) { try { HashMap < IRubyProject , ArrayList < IOpenable > > allOpenables = new HashMap < IRubyProject , ArrayList < IOpenable > > ( ) ; IRubyElement [ ] roots = ( ( RegionBasedTypeHierarchy ) this . hierarchy ) . region . getElements ( ) ; int length = roots . length ; if ( monitor != null ) monitor . beginTask ( "" , length ) ; for ( int i = ; i < length ; i ++ ) { IRubyElement root = roots [ i ] ; IRubyProject javaProject = root . getRubyProject ( ) ; ArrayList < IOpenable > openables = allOpenables . get ( javaProject ) ; if ( openables == null ) { openables = new ArrayList < IOpenable > ( ) ; allOpenables . put ( javaProject , openables ) ; } switch ( root . getElementType ( ) ) { case IRubyElement . RUBY_PROJECT : injectAllOpenablesForRubyProject ( ( IRubyProject ) root , openables ) ; break ; case IRubyElement . SOURCE_FOLDER_ROOT : injectAllOpenablesForSourceFolderRoot ( ( ISourceFolderRoot ) root , openables ) ; break ; case IRubyElement . SOURCE_FOLDER : injectAllOpenablesForSourceFolder ( ( ISourceFolder ) root , openables ) ; break ; case IRubyElement . SCRIPT : openables . add ( ( IRubyScript ) root ) ; break ; case IRubyElement . TYPE : IType type = ( IType ) root ; openables . add ( type . getRubyScript ( ) ) ; break ; default : break ; } worked ( monitor , ) ; } return allOpenables ; } finally { if ( monitor != null ) monitor . done ( ) ; } } private void injectAllOpenablesForRubyProject ( IRubyProject project , ArrayList < IOpenable > openables ) { try { ISourceFolderRoot [ ] devPathRoots = ( ( RubyProject ) project ) . getSourceFolderRoots ( ) ; if ( devPathRoots == null ) { return ; } for ( int j = ; j < devPathRoots . length ; j ++ ) { ISourceFolderRoot root = devPathRoots [ j ] ; injectAllOpenablesForSourceFolderRoot ( root , openables ) ; } } catch ( RubyModelException e ) { } } private void injectAllOpenablesForSourceFolder ( ISourceFolder packFrag , ArrayList < IOpenable > openables ) { try { IRubyScript [ ] cus = packFrag . getRubyScripts ( ) ; for ( int i = , length = cus . length ; i < length ; i ++ ) { openables . add ( cus [ i ] ) ; } } catch ( RubyModelException e ) { } } private void injectAllOpenablesForSourceFolderRoot ( ISourceFolderRoot root , ArrayList < IOpenable > openables ) { try { IRubyElement [ ] packFrags = root . getChildren ( ) ; for ( int k = ; k < packFrags . length ; k ++ ) { ISourceFolder packFrag = ( ISourceFolder ) packFrags [ k ] ; injectAllOpenablesForSourceFolder ( packFrag , openables ) ; } } catch ( RubyModelException e ) { return ; } } } package org . rubypeople . rdt . internal . core . hierarchy ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . compiler . util . HashtableOfObject ; import org . rubypeople . rdt . internal . core . IPathRequestor ; import org . rubypeople . rdt . internal . core . Member ; import org . rubypeople . rdt . internal . core . Openable ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . search . HandleFactory ; import org . rubypeople . rdt . internal . core . search . IndexQueryRequestor ; import org . rubypeople . rdt . internal . core . search . RubySearchParticipant ; import org . rubypeople . rdt . internal . core . search . SubTypeSearchJob ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . search . indexing . IndexManager ; import org . rubypeople . rdt . internal . core . search . matching . MatchLocator ; import org . rubypeople . rdt . internal . core . search . matching . SuperTypeReferencePattern ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public class IndexBasedHierarchyBuilder extends HierarchyBuilder { public static final int MAXTICKS = ; private IRubySearchScope scope ; public IndexBasedHierarchyBuilder ( TypeHierarchy hierarchy , IRubySearchScope scope ) throws RubyModelException { super ( hierarchy ) ; this . scope = scope ; } @ Override public void build ( boolean computeSubtypes ) throws RubyModelException , CoreException { if ( computeSubtypes ) { IType focusType = getType ( ) ; boolean focusIsObject = focusType . getElementName ( ) . equals ( new String ( IIndexConstants . OBJECT ) ) ; int amountOfWorkForSubtypes = focusIsObject ? : ; IProgressMonitor possibleSubtypesMonitor = this . hierarchy . progressMonitor == null ? null : new SubProgressMonitor ( this . hierarchy . progressMonitor , amountOfWorkForSubtypes ) ; HashSet < String > localTypes = new HashSet < String > ( ) ; String [ ] allPossibleSubtypes ; if ( ( ( Member ) focusType ) . getOuterMostLocalContext ( ) == null ) { allPossibleSubtypes = this . determinePossibleSubTypes ( localTypes , possibleSubtypesMonitor ) ; } else { allPossibleSubtypes = new String [ ] ; } if ( allPossibleSubtypes != null ) { IProgressMonitor buildMonitor = this . hierarchy . progressMonitor == null ? null : new SubProgressMonitor ( this . hierarchy . progressMonitor , - amountOfWorkForSubtypes ) ; this . hierarchy . initialize ( allPossibleSubtypes . length ) ; buildFromPotentialSubtypes ( allPossibleSubtypes , localTypes , buildMonitor ) ; } } else { this . hierarchy . initialize ( ) ; this . buildSupertypes ( ) ; } } private void buildFromPotentialSubtypes ( String [ ] allPotentialSubTypes , HashSet < String > localTypes , IProgressMonitor monitor ) { IType focusType = this . getType ( ) ; HashMap < String , IRubyScript > wcPaths = new HashMap < String , IRubyScript > ( ) ; int wcLength ; org . rubypeople . rdt . core . IRubyScript [ ] workingCopies = this . hierarchy . workingCopies ; if ( workingCopies != null && ( wcLength = workingCopies . length ) > ) { String [ ] newPaths = new String [ wcLength ] ; for ( int i = ; i < wcLength ; i ++ ) { org . rubypeople . rdt . core . IRubyScript workingCopy = workingCopies [ i ] ; String path = workingCopy . getPath ( ) . toString ( ) ; wcPaths . put ( path , workingCopy ) ; newPaths [ i ] = path ; } int potentialSubtypesLength = allPotentialSubTypes . length ; System . arraycopy ( allPotentialSubTypes , , allPotentialSubTypes = new String [ potentialSubtypesLength + wcLength ] , , potentialSubtypesLength ) ; System . arraycopy ( newPaths , , allPotentialSubTypes , potentialSubtypesLength , wcLength ) ; } int length = allPotentialSubTypes . length ; Openable focusCU = ( Openable ) focusType . getRubyScript ( ) ; String focusPath = null ; if ( focusCU != null ) { focusPath = focusCU . getPath ( ) . toString ( ) ; if ( length > ) { System . arraycopy ( allPotentialSubTypes , , allPotentialSubTypes = new String [ length + ] , , length ) ; allPotentialSubTypes [ length ] = focusPath ; } else { allPotentialSubTypes = new String [ ] { focusPath } ; } length ++ ; } org . rubypeople . rdt . internal . core . util . Util . sortReverseOrder ( allPotentialSubTypes ) ; ArrayList < IOpenable > potentialSubtypes = new ArrayList < IOpenable > ( ) ; try { HandleFactory factory = new HandleFactory ( ) ; IRubyProject currentProject = null ; if ( monitor != null ) monitor . beginTask ( "" , length * ) ; for ( int i = ; i < length ; i ++ ) { try { String resourcePath = allPotentialSubTypes [ i ] ; if ( i > && resourcePath . equals ( allPotentialSubTypes [ i - ] ) ) continue ; Openable handle ; org . rubypeople . rdt . core . IRubyScript workingCopy = ( org . rubypeople . rdt . core . IRubyScript ) wcPaths . get ( resourcePath ) ; if ( workingCopy != null ) { handle = ( Openable ) workingCopy ; } else { handle = resourcePath . equals ( focusPath ) ? focusCU : factory . createOpenable ( resourcePath ) ; if ( handle == null ) continue ; } IRubyProject project = handle . getRubyProject ( ) ; if ( currentProject == null ) { currentProject = project ; potentialSubtypes = new ArrayList < IOpenable > ( ) ; } else if ( ! currentProject . equals ( project ) ) { this . buildForProject ( ( RubyProject ) currentProject , potentialSubtypes , workingCopies , localTypes , monitor ) ; currentProject = project ; potentialSubtypes = new ArrayList < IOpenable > ( ) ; } potentialSubtypes . add ( handle ) ; } catch ( RubyModelException e ) { continue ; } } try { if ( currentProject == null ) { currentProject = focusType . getRubyProject ( ) ; potentialSubtypes . add ( focusType . getRubyScript ( ) ) ; } this . buildForProject ( ( RubyProject ) currentProject , potentialSubtypes , workingCopies , localTypes , monitor ) ; } catch ( RubyModelException e ) { } if ( ! this . hierarchy . contains ( focusType ) ) { try { currentProject = focusType . getRubyProject ( ) ; potentialSubtypes = new ArrayList < IOpenable > ( ) ; potentialSubtypes . add ( focusType . getRubyScript ( ) ) ; this . buildForProject ( ( RubyProject ) currentProject , potentialSubtypes , workingCopies , localTypes , monitor ) ; } catch ( RubyModelException e ) { } } if ( ! this . hierarchy . contains ( focusType ) ) { this . hierarchy . addRootClass ( focusType ) ; } } finally { if ( monitor != null ) monitor . done ( ) ; } } private void buildForProject ( RubyProject project , ArrayList < IOpenable > potentialSubtypes , org . rubypeople . rdt . core . IRubyScript [ ] workingCopies , HashSet < String > localTypes , IProgressMonitor monitor ) throws RubyModelException { int openablesLength = potentialSubtypes . size ( ) ; Openable [ ] openables = new Openable [ openablesLength ] ; potentialSubtypes . toArray ( openables ) ; if ( openablesLength > ) { IType focusType = this . getType ( ) ; boolean inProjectOfFocusType = focusType != null && focusType . getRubyProject ( ) . equals ( project ) ; org . rubypeople . rdt . core . IRubyScript [ ] unitsToLookInside = null ; if ( inProjectOfFocusType ) { org . rubypeople . rdt . core . IRubyScript unitToLookInside = focusType . getRubyScript ( ) ; if ( unitToLookInside != null ) { int wcLength = workingCopies == null ? : workingCopies . length ; if ( wcLength == ) { unitsToLookInside = new org . rubypeople . rdt . core . IRubyScript [ ] { unitToLookInside } ; } else { unitsToLookInside = new org . rubypeople . rdt . core . IRubyScript [ wcLength + ] ; unitsToLookInside [ ] = unitToLookInside ; System . arraycopy ( workingCopies , , unitsToLookInside , , wcLength ) ; } } else { unitsToLookInside = workingCopies ; } } if ( focusType != null ) { Member declaringMember = ( ( Member ) focusType ) . getOuterMostLocalContext ( ) ; if ( declaringMember == null ) { if ( ! inProjectOfFocusType ) { } } else { IRubyScript openable = declaringMember . getRubyScript ( ) ; localTypes = new HashSet < String > ( ) ; localTypes . add ( openable . getPath ( ) . toString ( ) ) ; this . hierarchyResolver . resolve ( new IOpenable [ ] { openable } , localTypes , monitor ) ; return ; } } this . hierarchyResolver . resolve ( openables , localTypes , monitor ) ; } } private String [ ] determinePossibleSubTypes ( final HashSet < String > localTypes , IProgressMonitor monitor ) { class PathCollector implements IPathRequestor { HashSet < String > paths = new HashSet < String > ( ) ; public void acceptPath ( String path , boolean containsLocalTypes ) { this . paths . add ( path ) ; if ( containsLocalTypes ) { localTypes . add ( path ) ; } } } PathCollector collector = new PathCollector ( ) ; try { if ( monitor != null ) monitor . beginTask ( "" , MAXTICKS ) ; searchAllPossibleSubTypes ( this . getType ( ) , this . scope , collector , IRubySearchConstants . WAIT_UNTIL_READY_TO_SEARCH , monitor ) ; } finally { if ( monitor != null ) monitor . done ( ) ; } HashSet < String > paths = collector . paths ; int length = paths . size ( ) ; String [ ] result = new String [ length ] ; int count = ; for ( Iterator < String > iter = paths . iterator ( ) ; iter . hasNext ( ) ; ) { result [ count ++ ] = iter . next ( ) ; } return result ; } static class Queue { public char [ ] [ ] names = new char [ ] [ ] ; public int start = ; public int end = - ; public void add ( char [ ] name ) { if ( ++ this . end == this . names . length ) { this . end -= this . start ; System . arraycopy ( this . names , this . start , this . names = new char [ this . end * ] [ ] , , this . end ) ; this . start = ; } this . names [ this . end ] = name ; } public char [ ] retrieve ( ) { if ( this . start > this . end ) return null ; char [ ] name = this . names [ this . start ++ ] ; if ( this . start > this . end ) { this . start = ; this . end = - ; } return name ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( "" ) ; for ( int i = this . start ; i <= this . end ; i ++ ) { buffer . append ( this . names [ i ] ) . append ( '' ) ; } return buffer . toString ( ) ; } } private static void searchAllPossibleSubTypes ( IType type , IRubySearchScope scope , final IPathRequestor pathRequestor , int waitingPolicy , IProgressMonitor progressMonitor ) { final Queue queue = new Queue ( ) ; final HashtableOfObject foundSuperNames = new HashtableOfObject ( ) ; IndexManager indexManager = RubyModelManager . getRubyModelManager ( ) . getIndexManager ( ) ; IndexQueryRequestor searchRequestor = new IndexQueryRequestor ( ) { public boolean acceptIndexMatch ( String documentPath , SearchPattern indexRecord , SearchParticipant participant ) { SuperTypeReferencePattern record = ( SuperTypeReferencePattern ) indexRecord ; boolean isLocalOrAnonymous = record . enclosingTypeName == IIndexConstants . ONE_ZERO ; pathRequestor . acceptPath ( documentPath , isLocalOrAnonymous ) ; char [ ] typeName = record . simpleName ; if ( ! isLocalOrAnonymous && ! foundSuperNames . containsKey ( typeName ) ) { foundSuperNames . put ( typeName , typeName ) ; queue . add ( typeName ) ; } return true ; } } ; int superRefKind ; superRefKind = type . isClass ( ) ? SuperTypeReferencePattern . ONLY_SUPER_CLASSES : SuperTypeReferencePattern . ALL_SUPER_TYPES ; SuperTypeReferencePattern pattern = new SuperTypeReferencePattern ( null , null , superRefKind , SearchPattern . R_EXACT_MATCH | SearchPattern . R_CASE_SENSITIVE ) ; MatchLocator . setFocus ( pattern , type ) ; SubTypeSearchJob job = new SubTypeSearchJob ( pattern , new RubySearchParticipant ( ) , scope , searchRequestor ) ; int ticks = ; queue . add ( type . getElementName ( ) . toCharArray ( ) ) ; try { while ( queue . start <= queue . end ) { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) return ; char [ ] currentTypeName = queue . retrieve ( ) ; if ( CharOperation . equals ( currentTypeName , IIndexConstants . OBJECT ) ) currentTypeName = null ; String simple = null ; if ( currentTypeName == null ) { simple = "" ; } else { simple = new String ( currentTypeName ) ; } int index = simple . lastIndexOf ( "" ) ; if ( index != - ) { simple = simple . substring ( index + ) ; } pattern . superSimpleName = simple . toCharArray ( ) ; indexManager . performConcurrentJob ( job , waitingPolicy , null ) ; if ( progressMonitor != null && ++ ticks <= MAXTICKS ) progressMonitor . worked ( ) ; if ( currentTypeName == null ) break ; } } finally { job . finished ( ) ; } } } package org . rubypeople . rdt . internal . core . hierarchy ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . rubypeople . rdt . core . IOpenable ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . codeassist . RubyElementRequestor ; import org . rubypeople . rdt . internal . core . LogicalType ; public class HierarchyResolver { private static final int RECURSE_DEPTH_BAILOUT = ; private boolean superTypesOnly ; private HierarchyBuilder builder ; private HashSet < String > visitedTypes ; public HierarchyResolver ( Map options , HierarchyBuilder builder ) { this . builder = builder ; } public void resolve ( IOpenable [ ] openables , HashSet < String > localTypes , IProgressMonitor monitor ) { try { int openablesLength = openables . length ; IType focus = this . builder . getType ( ) ; for ( int i = ; i < openablesLength ; i ++ ) { IOpenable openable = openables [ i ] ; if ( openable instanceof org . rubypeople . rdt . core . IRubyScript ) { org . rubypeople . rdt . core . IRubyScript cu = ( org . rubypeople . rdt . core . IRubyScript ) openable ; IType [ ] types = cu . getAllTypes ( ) ; for ( int j = ; j < types . length ; j ++ ) { IType type = types [ j ] ; if ( focusIsInHierarchy ( focus , type , ) ) { try { this . visitedTypes = new HashSet < String > ( ) ; reportHierarchy ( type ) ; visitedTypes . clear ( ) ; } catch ( RubyModelException e ) { } } } } } } catch ( ClassCastException e ) { } catch ( RubyModelException e ) { } finally { reset ( ) ; } } private boolean focusIsInHierarchy ( IType focus , IType type , int currentDepth ) throws RubyModelException { if ( currentDepth > RECURSE_DEPTH_BAILOUT ) { RubyCore . log ( IStatus . ERROR , "" + currentDepth + "" + type . getFullyQualifiedName ( ) , new IllegalStateException ( ) . fillInStackTrace ( ) ) ; return false ; } if ( focus == null || type == null ) return false ; if ( type . getFullyQualifiedName ( ) . equals ( focus . getFullyQualifiedName ( ) ) ) return true ; return focusIsInHierarchy ( focus , findSuperClass ( type ) , ++ currentDepth ) ; } private void reportHierarchy ( IType type ) throws RubyModelException { visitedTypes . add ( type . getFullyQualifiedName ( ) ) ; IType superclass ; if ( type . isModule ( ) ) { superclass = null ; } else { superclass = findSuperClass ( type ) ; } IType [ ] superinterfaces = findSuperInterfaces ( type ) ; this . builder . connect ( type , superclass , superinterfaces ) ; if ( type . isClass ( ) && superclass != null ) { if ( visitedTypes . contains ( superclass . getFullyQualifiedName ( ) ) ) { throw new IllegalStateException ( "" + type . getFullyQualifiedName ( ) + "" + superclass . getFullyQualifiedName ( ) ) ; } reportHierarchy ( superclass ) ; } } private IType [ ] findSuperInterfaces ( IType type ) throws RubyModelException { String [ ] names = type . getIncludedModuleNames ( ) ; List < IType > types = new ArrayList < IType > ( ) ; for ( int i = ; i < names . length ; i ++ ) { IType logical = getLogicalType ( type , names [ i ] ) ; if ( logical == null ) { String namespace = type . getFullyQualifiedName ( ) . substring ( , type . getFullyQualifiedName ( ) . length ( ) - type . getElementName ( ) . length ( ) ) ; logical = getLogicalType ( type , namespace + names [ i ] ) ; if ( logical == null ) continue ; } types . add ( logical ) ; } return ( IType [ ] ) types . toArray ( new IType [ types . size ( ) ] ) ; } private IType findSuperClass ( IType type ) throws RubyModelException { String name = type . getSuperclassName ( ) ; if ( name == null ) return null ; return getLogicalType ( type , name ) ; } private IType getLogicalType ( IType type , String name ) { RubyElementRequestor requestor = new RubyElementRequestor ( type . getRubyScript ( ) ) ; IType [ ] types = requestor . findType ( name ) ; if ( types == null || types . length == ) return null ; return new LogicalType ( types ) ; } private void reset ( ) { this . superTypesOnly = false ; } public void resolve ( IType type ) { org . rubypeople . rdt . core . IRubyScript cu = type . getRubyScript ( ) ; HashSet < String > localTypes = new HashSet < String > ( ) ; localTypes . add ( cu . getPath ( ) . toString ( ) ) ; this . superTypesOnly = true ; resolve ( new IOpenable [ ] { cu } , localTypes , null ) ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . List ; public class InfoStack { private List stack = new ArrayList ( ) ; public InfoStack ( ) { } public RubyElementInfo pop ( ) { if ( stack . isEmpty ( ) ) return null ; return ( RubyElementInfo ) stack . remove ( stack . size ( ) - ) ; } public void push ( RubyElementInfo element ) { stack . add ( element ) ; } public RubyElementInfo peek ( ) { if ( stack . isEmpty ( ) ) return null ; return ( RubyElementInfo ) stack . get ( stack . size ( ) - ) ; } } package org . rubypeople . rdt . core ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IRubyModel extends IParent , IRubyElement , IOpenable { IRubyProject getRubyProject ( String name ) ; IRubyProject [ ] getRubyProjects ( ) throws RubyModelException ; Object [ ] getNonRubyResources ( ) throws RubyModelException ; IWorkspace getWorkspace ( ) ; boolean contains ( IResource resource ) ; void refreshExternalArchives ( IRubyElement [ ] elements , IProgressMonitor monitor ) throws RubyModelException ; } package org . rubypeople . rdt . core ; public interface IField extends IMember { } package org . rubypeople . rdt . core ; public interface ICodeAssist { public IRubyElement [ ] codeSelect ( int offset , int length ) throws RubyModelException ; public IRubyElement [ ] codeSelect ( int offset , int length , WorkingCopyOwner workingCopyOwner ) throws RubyModelException ; void codeComplete ( int offset , CompletionRequestor requestor ) throws RubyModelException ; } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; public abstract class LoadpathContainerInitializer { public LoadpathContainerInitializer ( ) { } public abstract void initialize ( IPath containerPath , IRubyProject project ) throws CoreException ; public boolean canUpdateLoadpathContainer ( IPath containerPath , IRubyProject project ) { return false ; } public void requestLoadpathContainerUpdate ( IPath containerPath , IRubyProject project , ILoadpathContainer containerSuggestion ) throws CoreException { } public String getDescription ( IPath containerPath , IRubyProject project ) { return containerPath . makeRelative ( ) . toString ( ) ; } public Object getComparisonID ( IPath containerPath , IRubyProject project ) { if ( containerPath == null ) { return null ; } else { return containerPath . segment ( ) ; } } } package org . rubypeople . rdt . core ; public interface IImportContainer extends IRubyElement , IParent , ISourceReference { IImportDeclaration getImport ( String name ) ; } package org . rubypeople . rdt . core ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import org . eclipse . core . resources . IStorage ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . PlatformObject ; import org . eclipse . core . runtime . Status ; public class LocalFileStorage extends PlatformObject implements IStorage { private File fFile ; public LocalFileStorage ( File file ) { setFile ( file ) ; } public InputStream getContents ( ) throws CoreException { try { return new FileInputStream ( getFile ( ) ) ; } catch ( IOException e ) { throw new CoreException ( new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , "" , e ) ) ; } } public IPath getFullPath ( ) { try { return new Path ( getFile ( ) . getCanonicalPath ( ) ) ; } catch ( IOException e ) { RubyCore . log ( e ) ; return null ; } } public String getName ( ) { return getFile ( ) . getName ( ) ; } public boolean isReadOnly ( ) { return true ; } private void setFile ( File file ) { fFile = file ; } public File getFile ( ) { return fFile ; } public boolean equals ( Object object ) { return object instanceof LocalFileStorage && getFile ( ) . equals ( ( ( LocalFileStorage ) object ) . getFile ( ) ) ; } public int hashCode ( ) { return getFile ( ) . hashCode ( ) ; } } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . IPath ; public interface ILoadpathContainer { int K_APPLICATION = ; int K_SYSTEM = ; int K_DEFAULT_SYSTEM = ; ILoadpathEntry [ ] getLoadpathEntries ( ) ; String getDescription ( ) ; int getKind ( ) ; IPath getPath ( ) ; } package org . rubypeople . rdt . core . formatter ; import java . util . Map ; import org . eclipse . jface . text . Assert ; import org . rubypeople . rdt . core . RubyCore ; public class Indents { private Indents ( ) { } public static int getTabWidth ( Map options ) { if ( options == null ) { throw new IllegalArgumentException ( ) ; } return getIntValue ( options , DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE , ) ; } public static int getIndentWidth ( Map options ) { if ( options == null ) { throw new IllegalArgumentException ( ) ; } int tabWidth = getTabWidth ( options ) ; boolean isMixedMode = DefaultCodeFormatterConstants . MIXED . equals ( options . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ) ) ; if ( isMixedMode ) { return getIntValue ( options , DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE , tabWidth ) ; } return tabWidth ; } private static int getIntValue ( Map options , String key , int def ) { try { return Integer . parseInt ( ( String ) options . get ( key ) ) ; } catch ( NumberFormatException e ) { return def ; } } public static int measureIndentUnits ( CharSequence line , int tabWidth , int indentWidth ) { if ( indentWidth <= || tabWidth < || line == null ) { throw new IllegalArgumentException ( ) ; } int visualLength = measureIndentInSpaces ( line , tabWidth ) ; return visualLength / indentWidth ; } public static String createIndentString ( int indentationUnits , Map options ) { if ( indentationUnits < ) { return "" ; } if ( options == null || indentationUnits < ) { throw new IllegalArgumentException ( ) ; } String tabChar = getStringValue ( options , DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , RubyCore . TAB ) ; final int tabs , spaces ; if ( RubyCore . SPACE . equals ( tabChar ) ) { tabs = ; spaces = indentationUnits * getIndentWidth ( options ) ; } else if ( RubyCore . TAB . equals ( tabChar ) ) { tabs = indentationUnits ; spaces = ; } else if ( DefaultCodeFormatterConstants . MIXED . equals ( tabChar ) ) { int tabWidth = getTabWidth ( options ) ; int spaceEquivalents = indentationUnits * getIndentWidth ( options ) ; if ( tabWidth > ) { tabs = spaceEquivalents / tabWidth ; spaces = spaceEquivalents % tabWidth ; } else { tabs = ; spaces = spaceEquivalents ; } } else { Assert . isTrue ( false ) ; return null ; } StringBuffer buffer = new StringBuffer ( tabs + spaces ) ; for ( int i = ; i < tabs ; i ++ ) buffer . append ( '' ) ; for ( int i = ; i < spaces ; i ++ ) buffer . append ( '' ) ; return buffer . toString ( ) ; } public static String createFixIndentString ( int fixIndentation , Map options ) { if ( options == null || fixIndentation < ) { throw new IllegalArgumentException ( ) ; } String tabChar = getStringValue ( options , DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR , RubyCore . TAB ) ; final int tabs , spaces ; if ( RubyCore . SPACE . equals ( tabChar ) ) { tabs = ; spaces = fixIndentation ; } else if ( RubyCore . TAB . equals ( tabChar ) ) { int tabWidth = getTabWidth ( options ) ; tabs = fixIndentation / tabWidth ; spaces = ; } else if ( DefaultCodeFormatterConstants . MIXED . equals ( tabChar ) ) { int tabWidth = getTabWidth ( options ) ; if ( tabWidth > ) { tabs = fixIndentation / tabWidth ; spaces = fixIndentation % tabWidth ; } else { tabs = ; spaces = fixIndentation ; } } else { Assert . isTrue ( false ) ; return null ; } StringBuffer buffer = new StringBuffer ( tabs + spaces ) ; for ( int i = ; i < tabs ; i ++ ) buffer . append ( '' ) ; for ( int i = ; i < spaces ; i ++ ) buffer . append ( '' ) ; return buffer . toString ( ) ; } private static String getStringValue ( Map options , String key , String def ) { Object value = options . get ( key ) ; if ( value instanceof String ) return ( String ) value ; return def ; } public static int measureIndentInSpaces ( CharSequence line , int tabWidth ) { if ( tabWidth < || line == null ) { throw new IllegalArgumentException ( ) ; } int length = ; int max = line . length ( ) ; for ( int i = ; i < max ; i ++ ) { char ch = line . charAt ( i ) ; if ( ch == '' ) { int reminder = length % tabWidth ; length += tabWidth - reminder ; } else if ( isIndentChar ( ch ) ) { length ++ ; } else { return length ; } } return length ; } public static String extractIndentString ( String line , int tabWidth , int indentWidth ) { if ( tabWidth < || indentWidth <= || line == null ) { throw new IllegalArgumentException ( ) ; } int size = line . length ( ) ; int end = ; int spaceEquivs = ; int characters = ; for ( int i = ; i < size ; i ++ ) { char c = line . charAt ( i ) ; if ( c == '' ) { int remainder = spaceEquivs % tabWidth ; spaceEquivs += tabWidth - remainder ; characters ++ ; } else if ( isIndentChar ( c ) ) { spaceEquivs ++ ; characters ++ ; } else { break ; } if ( spaceEquivs >= indentWidth ) { end += characters ; characters = ; spaceEquivs = spaceEquivs % indentWidth ; } } if ( end == ) return "" ; else if ( end == size ) return line ; else return line . substring ( , end ) ; } public static boolean isIndentChar ( char ch ) { return Character . isWhitespace ( ch ) && ! isLineDelimiterChar ( ch ) ; } public static boolean isLineDelimiterChar ( char ch ) { return ch == '' || ch == '' ; } public static String extractIndentString ( String line , Map options ) { return extractIndentString ( line , getTabWidth ( options ) , getIndentWidth ( options ) ) ; } } package org . rubypeople . rdt . core . formatter ; import org . eclipse . text . edits . TextEdit ; public abstract class CodeFormatter { public static final int K_UNKNOWN = ; public static final int K_EXPRESSION = ; public static final int K_STATEMENTS = ; public static final int K_CLASS_BODY_DECLARATIONS = ; public static final int K_RUBY_SCRIPT = ; public static final int K_SINGLE_LINE_COMMENT = ; public static final int K_MULTI_LINE_COMMENT = ; public static final int K_RUBY_DOC = ; public abstract TextEdit format ( int kind , String source , int offset , int length , int indentationLevel , String lineSeparator ) ; } package org . rubypeople . rdt . core . formatter ; import org . rubypeople . rdt . internal . formatter . rewriter . DRegxReWriteVisitor ; import org . rubypeople . rdt . internal . formatter . rewriter . HereDocReWriteVisitor ; import org . rubypeople . rdt . internal . formatter . rewriter . IgnoreCommentsReWriteVisitor ; import org . rubypeople . rdt . internal . formatter . rewriter . MultipleAssignmentReWriteVisitor ; import org . rubypeople . rdt . internal . formatter . rewriter . ShortIfNodeReWriteVisitor ; public class ReWriterFactory { private ReWriterContext config ; public ReWriterFactory ( ReWriterContext config ) { this . config = config ; } public ReWriteVisitor createShortIfNodeReWriteVisitor ( ) { return new ShortIfNodeReWriteVisitor ( config ) ; } public ReWriteVisitor createMultipleAssignmentReWriteVisitor ( ) { return new MultipleAssignmentReWriteVisitor ( config ) ; } public ReWriteVisitor createDRegxReWriteVisitor ( ) { return new DRegxReWriteVisitor ( config ) ; } public ReWriteVisitor createHereDocReWriteVisitor ( ) { return new HereDocReWriteVisitor ( config ) ; } public ReWriteVisitor createIgnoreCommentsReWriteVisitor ( ) { return new IgnoreCommentsReWriteVisitor ( config ) ; } public ReWriteVisitor createReWriteVisitor ( ) { return new ReWriteVisitor ( config ) ; } } package org . rubypeople . rdt . core . formatter ; import java . util . HashMap ; import java . util . Map ; import org . rubypeople . rdt . internal . formatter . Indentor ; public class EditableFormatHelper implements FormatHelper { private static final String DEFAULT_LINE_DELIMITER = "" ; private String lineDelimiter ; private boolean spaceAfterCommaInListings ; private boolean spacesBeforeAndAfterAssignments ; private boolean alwaysParanthesizeMethodCalls ; private boolean spacesAroundHashAssignment ; private boolean spacesBeforeAndAfterHashContent ; private boolean spaceBeforeIterVars ; private boolean spaceAfterIterVars ; private boolean newlineBetweenClassBodyElements ; private boolean alwaysParanthesizeMethodDefs ; private boolean spaceBeforeIterBrackets ; private boolean spaceBeforeClosingIterBrackets ; private boolean insertDoAfterWhileExpression ; private boolean collpaseOperatorSelfAssignments ; private Indentor indentor = new Indentor ( , '' ) ; public EditableFormatHelper ( ) { this ( DEFAULT_LINE_DELIMITER ) ; } public EditableFormatHelper ( String lineDelimiter ) { this ( new HashMap < String , Object > ( ) ) ; if ( lineDelimiter != null ) this . lineDelimiter = lineDelimiter ; } public EditableFormatHelper ( Map < String , Object > options ) { spaceAfterCommaInListings = getBoolean ( options , EditableFormatHelper . SPACE_AFTER_COMMA_IN_LISTS , true ) ; alwaysParanthesizeMethodCalls = getBoolean ( options , EditableFormatHelper . ALWAYS_SURROUND_METHOD_CALLS_IN_PARENS , false ) ; alwaysParanthesizeMethodDefs = getBoolean ( options , EditableFormatHelper . ALWAYS_SURROUND_METHOD_ARGUMENTS_IN_PARENS , false ) ; spacesAroundHashAssignment = getBoolean ( options , EditableFormatHelper . SPACES_AROUND_HASH_ASSIGNMENT , true ) ; spacesBeforeAndAfterHashContent = getBoolean ( options , EditableFormatHelper . SPACES_BEFORE_AND_AFTER_HASH_CONTENT , false ) ; spacesBeforeAndAfterAssignments = getBoolean ( options , EditableFormatHelper . SPACE_BEFORE_AND_AFTER_ASSIGNMENTS , true ) ; spaceBeforeIterBrackets = getBoolean ( options , EditableFormatHelper . SPACE_BEFORE_BLOCK_BRACKETS , true ) ; spaceAfterIterVars = getBoolean ( options , EditableFormatHelper . SPACE_AFTER_ITER_VARS , true ) ; spaceBeforeIterVars = getBoolean ( options , EditableFormatHelper . SPACES_BEFORE_ITER_VARS , true ) ; spaceBeforeClosingIterBrackets = getBoolean ( options , EditableFormatHelper . SPACE_BEFORE_CLOSING_BLOCK_BRACKET , true ) ; insertDoAfterWhileExpression = getBoolean ( options , EditableFormatHelper . INSERT_DO_AFTER_WHILE_EXPRESSION , false ) ; newlineBetweenClassBodyElements = getBoolean ( options , EditableFormatHelper . NEWLINE_BETWEEN_CLASS_BODY_ELEMENTS , false ) ; collpaseOperatorSelfAssignments = getBoolean ( options , EditableFormatHelper . COLLAPSE_OPERATOR_SELF_ASSIGNMENTS , true ) ; lineDelimiter = DEFAULT_LINE_DELIMITER ; } private boolean getBoolean ( Map < String , Object > options , String key , boolean defaultValue ) { Object value = options . get ( key ) ; if ( value == null ) return defaultValue ; if ( value instanceof Boolean ) return ( Boolean ) value ; if ( value instanceof String ) { String str = ( String ) value ; if ( str . trim ( ) . toLowerCase ( ) . equals ( Boolean . TRUE . toString ( ) . toLowerCase ( ) ) ) return true ; if ( str . trim ( ) . toLowerCase ( ) . equals ( Boolean . FALSE . toString ( ) . toLowerCase ( ) ) ) return false ; } return defaultValue ; } public Indentor getIndentor ( ) { return indentor ; } public void setTabInsteadOfSpaces ( boolean tabInsteadOfSpaces ) { if ( tabInsteadOfSpaces ) { indentor . setIndentationChar ( '' ) ; } else { indentor . setIndentationChar ( '' ) ; } } public void setIndentationSteps ( int indentationSteps ) { indentor . setIndentationSteps ( indentationSteps ) ; } public void setLineDelimiter ( String lineDelimiter ) { if ( lineDelimiter != null ) this . lineDelimiter = lineDelimiter ; } public String beforeAssignment ( ) { return spacesBeforeAndAfterAssignments ? "" : "" ; } public String afterAssignment ( ) { return spacesBeforeAndAfterAssignments ? "" : "" ; } public String matchOperator ( ) { return spacesBeforeAndAfterAssignments ? "" : "" ; } public String beforeCallArguments ( ) { return alwaysParanthesizeMethodCalls ? "" : "" ; } public String afterCallArguments ( ) { return alwaysParanthesizeMethodCalls ? "" : "" ; } public String beforeHashContent ( ) { return spacesBeforeAndAfterHashContent ? "" : "" ; } public String afterHashContent ( ) { return spacesBeforeAndAfterHashContent ? "" : "" ; } public String beforeIterVars ( ) { return spaceBeforeIterVars ? "" : "" ; } public String afterIterVars ( ) { return spaceAfterIterVars ? "" : "" ; } public String beforeMethodArguments ( ) { return alwaysParanthesizeMethodDefs ? "" : "" ; } public String afterMethodArguments ( ) { return alwaysParanthesizeMethodDefs ? "" : "" ; } public String beforeIterBrackets ( ) { return spaceBeforeIterBrackets ? "" : "" ; } public String beforeClosingIterBrackets ( ) { return spaceBeforeClosingIterBrackets ? "" : "" ; } public String classBodyElementsSeparator ( ) { return newlineBetweenClassBodyElements ? getLineDelimiter ( ) : "" ; } public String getListSeparator ( ) { return spaceAfterCommaInListings ? "" : "" ; } public String hashAssignment ( ) { return spacesAroundHashAssignment ? "" : "" ; } public void setAlwaysParanthesizeMethodCalls ( boolean alwaysParanthesizeMethodCalls ) { this . alwaysParanthesizeMethodCalls = alwaysParanthesizeMethodCalls ; } public void setAlwaysParanthesizeMethodDefs ( boolean alwaysParanthesizeMethodDefs ) { this . alwaysParanthesizeMethodDefs = alwaysParanthesizeMethodDefs ; } public void setNewlineBetweenClassBodyElements ( boolean newlineBetweenClassBodyElements ) { this . newlineBetweenClassBodyElements = newlineBetweenClassBodyElements ; } public void setSpaceAfterCommaInListings ( boolean spaceAfterCommaInListings ) { this . spaceAfterCommaInListings = spaceAfterCommaInListings ; } public void setSpaceAfterIterVars ( boolean spaceAfterIterVars ) { this . spaceAfterIterVars = spaceAfterIterVars ; } public void setSpaceBeforeClosingIterBrackets ( boolean spaceBeforeClosingIterBrackets ) { this . spaceBeforeClosingIterBrackets = spaceBeforeClosingIterBrackets ; } public void setSpaceBeforeIterBrackets ( boolean spaceBeforeIterBrackets ) { this . spaceBeforeIterBrackets = spaceBeforeIterBrackets ; } public void setSpaceBeforeIterVars ( boolean spaceBeforeIterVars ) { this . spaceBeforeIterVars = spaceBeforeIterVars ; } public void setSpacesAroundHashAssignment ( boolean spacesAroundHashAssignment ) { this . spacesAroundHashAssignment = spacesAroundHashAssignment ; } public void setSpacesBeforeAndAfterAssignments ( boolean spacesBeforeAndAfterAssignments ) { this . spacesBeforeAndAfterAssignments = spacesBeforeAndAfterAssignments ; } public void setSpacesBeforeAndAfterHashContent ( boolean spacesBeforeAndAfterHashContent ) { this . spacesBeforeAndAfterHashContent = spacesBeforeAndAfterHashContent ; } public String getLineDelimiter ( ) { return lineDelimiter ; } public boolean insertDoAfterWhileExpression ( ) { return insertDoAfterWhileExpression ; } public boolean collapseOperatorSelfAssignments ( ) { return collpaseOperatorSelfAssignments ; } } package org . rubypeople . rdt . core . formatter ; import java . io . OutputStream ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . io . Writer ; import java . math . BigInteger ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . jruby . ast . * ; import org . jruby . ast . types . INameNode ; import org . jruby . ast . visitor . NodeVisitor ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . parser . StaticScope ; import org . rubypeople . rdt . internal . formatter . rewriter . ClassBodyWriter ; import org . rubypeople . rdt . internal . formatter . rewriter . Operators ; public class ReWriteVisitor implements NodeVisitor { protected final ReWriterContext config ; protected final ReWriterFactory factory ; public ReWriteVisitor ( Writer out , String source ) { this ( new ReWriterContext ( new PrintWriter ( out ) , source , new EditableFormatHelper ( ) ) ) ; } public ReWriteVisitor ( OutputStream out , String source ) { this ( new ReWriterContext ( new PrintWriter ( out , true ) , source , new EditableFormatHelper ( ) ) ) ; } public ReWriteVisitor ( ReWriterContext config ) { this . config = config ; factory = new ReWriterFactory ( config ) ; } public void flushStream ( ) { config . getOutput ( ) . flush ( ) ; } protected void print ( String s ) { config . getOutput ( ) . print ( s ) ; } protected void print ( char c ) { config . getOutput ( ) . print ( c ) ; } protected void print ( BigInteger i ) { config . getOutput ( ) . print ( i ) ; } protected void print ( int i ) { config . getOutput ( ) . print ( i ) ; } protected void print ( long l ) { config . getOutput ( ) . print ( l ) ; } protected void print ( double d ) { config . getOutput ( ) . print ( d ) ; } private void enterCall ( ) { config . getCallDepth ( ) . enterCall ( ) ; } private void leaveCall ( ) { config . getCallDepth ( ) . leaveCall ( ) ; } private boolean inCall ( ) { return config . getCallDepth ( ) . inCall ( ) ; } protected void printNewlineAndIndentation ( ) { print ( config . getFormatHelper ( ) . getLineDelimiter ( ) ) ; config . getIndentor ( ) . printIndentation ( config . getOutput ( ) ) ; } private static boolean isReceiverACallNode ( CallNode n ) { return ( n . getReceiverNode ( ) instanceof CallNode || n . getReceiverNode ( ) instanceof FCallNode ) ; } private void printCommentsBefore ( Node iVisited ) { for ( CommentNode n : iVisited . getComments ( ) ) { if ( getStartLine ( n ) < getStartLine ( iVisited ) ) { visitNode ( n ) ; printComment ( n . getContent ( ) ) ; printNewlineAndIndentation ( ) ; } } } private void printComment ( String content ) { if ( content == null ) return ; if ( content . trim ( ) . endsWith ( "" ) && content . startsWith ( "" ) ) { print ( '' ) ; } print ( content ) ; } protected boolean printCommentsAfter ( Node iVisited ) { boolean hasComment = false ; for ( CommentNode n : iVisited . getComments ( ) ) { if ( getStartLine ( n ) >= getEndLine ( iVisited ) ) { print ( '' ) ; visitNode ( n ) ; print ( n . getContent ( ) ) ; hasComment = true ; } } return hasComment ; } public void visitNode ( Node iVisited ) { if ( iVisited == null || iVisited . isInvisible ( ) ) return ; printCommentsBefore ( iVisited ) ; if ( iVisited instanceof ArgumentNode ) { print ( ( ( ArgumentNode ) iVisited ) . getName ( ) ) ; } else { iVisited . accept ( this ) ; } printCommentsAfter ( iVisited ) ; config . setLastPosition ( iVisited . getPosition ( ) ) ; } public void visitIter ( Iterator < ? extends Node > iterator ) { while ( iterator . hasNext ( ) ) { visitNode ( iterator . next ( ) ) ; } } private void visitIterAndSkipFirst ( Iterator < ? extends Node > iterator ) { iterator . next ( ) ; visitIter ( iterator ) ; } private static boolean isStartOnNewLine ( Node first , Node second ) { if ( first == null || second == null ) return false ; return ( getStartLine ( first ) < getStartLine ( second ) ) ; } private boolean needsParentheses ( Node n ) { return ( n != null && ( n . childNodes ( ) . size ( ) > || inCall ( ) || firstChild ( n ) instanceof HashNode ) || firstChild ( n ) instanceof NewlineNode || firstChild ( n ) instanceof IfNode ) ; } private void printCallArguments ( Node argsNode , Node iterNode ) { if ( argsNode != null && argsNode . childNodes ( ) . size ( ) < && iterNode == null ) return ; if ( argsNode != null && argsNode . childNodes ( ) . size ( ) == && firstChild ( argsNode ) instanceof HashNode && iterNode == null ) { HashNode hashNode = ( HashNode ) firstChild ( argsNode ) ; if ( hashNode . getListNode ( ) . childNodes ( ) . size ( ) < ) { print ( "" ) ; } else { print ( '' ) ; printHashNodeContent ( hashNode ) ; } return ; } boolean paranthesesPrinted = needsParentheses ( argsNode ) || ( argsNode == null && iterNode != null && iterNode instanceof BlockPassNode ) || ( argsNode != null && argsNode . childNodes ( ) . size ( ) > && iterNode != null ) ; if ( paranthesesPrinted ) { print ( '' ) ; } else if ( argsNode != null ) { print ( config . getFormatHelper ( ) . beforeCallArguments ( ) ) ; } if ( firstChild ( argsNode ) instanceof NewlineNode ) { config . setSkipNextNewline ( true ) ; } enterCall ( ) ; if ( argsNode instanceof SplatNode ) { visitNode ( argsNode ) ; } else if ( argsNode != null ) { visitAndPrintWithSeparator ( argsNode . childNodes ( ) . iterator ( ) ) ; } if ( iterNode instanceof BlockPassNode ) { if ( argsNode != null ) print ( config . getFormatHelper ( ) . getListSeparator ( ) ) ; print ( '' ) ; visitNode ( ( ( BlockPassNode ) iterNode ) . getBodyNode ( ) ) ; } if ( paranthesesPrinted ) { print ( '' ) ; } else { print ( config . getFormatHelper ( ) . afterCallArguments ( ) ) ; } leaveCall ( ) ; } public void visitAndPrintWithSeparator ( Iterator < Node > it ) { while ( it . hasNext ( ) ) { Node n = it . next ( ) ; factory . createIgnoreCommentsReWriteVisitor ( ) . visitNode ( n ) ; if ( it . hasNext ( ) ) print ( config . getFormatHelper ( ) . getListSeparator ( ) ) ; if ( n . hasComments ( ) ) { factory . createReWriteVisitor ( ) . visitIter ( n . getComments ( ) . iterator ( ) ) ; printNewlineAndIndentation ( ) ; } } } public Object visitAliasNode ( AliasNode iVisited ) { print ( "" ) ; print ( iVisited . getNewName ( ) ) ; print ( '' ) ; print ( iVisited . getOldName ( ) ) ; printCommentsAtEnd ( iVisited ) ; return null ; } private boolean sourceRangeContains ( ISourcePosition pos , String searched ) { return pos . getStartOffset ( ) < config . getSource ( ) . length ( ) && pos . getEndOffset ( ) < config . getSource ( ) . length ( ) + && config . getSource ( ) . substring ( pos . getStartOffset ( ) , pos . getEndOffset ( ) ) . indexOf ( searched ) > - ; } public Object visitAndNode ( AndNode iVisited ) { enterCall ( ) ; visitNode ( iVisited . getFirstNode ( ) ) ; if ( sourceRangeContains ( iVisited . getPosition ( ) , "" ) ) { print ( "" ) ; } else { print ( "" ) ; } visitNode ( iVisited . getSecondNode ( ) ) ; leaveCall ( ) ; return null ; } private ArrayList < Node > collectAllArguments ( ArgsNode iVisited ) { ArrayList < Node > arguments = new ArrayList < Node > ( ) ; if ( iVisited . getPre ( ) != null ) arguments . addAll ( iVisited . getPre ( ) . childNodes ( ) ) ; if ( iVisited . getOptArgs ( ) != null ) arguments . addAll ( iVisited . getOptArgs ( ) . childNodes ( ) ) ; if ( iVisited . getRestArgNode ( ) != null ) { arguments . add ( new ConstNode ( iVisited . getRestArgNode ( ) . getPosition ( ) , '' + iVisited . getRestArgNode ( ) . getName ( ) ) ) ; } if ( iVisited . getPost ( ) != null ) arguments . addAll ( iVisited . getPost ( ) . childNodes ( ) ) ; if ( iVisited . getBlock ( ) != null ) arguments . add ( iVisited . getBlock ( ) ) ; return arguments ; } private boolean hasNodeCommentsAtEnd ( Node n ) { for ( Node comment : n . getComments ( ) ) { if ( getStartLine ( comment ) == getStartLine ( n ) ) return true ; } return false ; } private void printCommentsInArgs ( Node n , boolean hasNext ) { if ( hasNodeCommentsAtEnd ( n ) && hasNext ) print ( "" ) ; if ( printCommentsAfter ( n ) && hasNext ) { printNewlineAndIndentation ( ) ; } else if ( hasNext ) { print ( config . getFormatHelper ( ) . getListSeparator ( ) ) ; } } public Object visitArgsNode ( ArgsNode iVisited ) { for ( Iterator < Node > it = collectAllArguments ( iVisited ) . iterator ( ) ; it . hasNext ( ) ; ) { Node n = it . next ( ) ; if ( n instanceof ArgumentNode ) { print ( ( ( ArgumentNode ) n ) . getName ( ) ) ; printCommentsInArgs ( n , it . hasNext ( ) ) ; } else { visitNode ( n ) ; if ( it . hasNext ( ) ) print ( config . getFormatHelper ( ) . getListSeparator ( ) ) ; } if ( ! it . hasNext ( ) ) print ( config . getFormatHelper ( ) . afterMethodArguments ( ) ) ; } return null ; } public Object visitArgsCatNode ( ArgsCatNode iVisited ) { print ( "" ) ; visitAndPrintWithSeparator ( iVisited . getFirstNode ( ) . childNodes ( ) . iterator ( ) ) ; print ( config . getFormatHelper ( ) . getListSeparator ( ) ) ; print ( "" ) ; visitNode ( iVisited . getSecondNode ( ) ) ; print ( "" ) ; return null ; } public Object visitArrayNode ( ArrayNode iVisited ) { print ( '' ) ; enterCall ( ) ; visitAndPrintWithSeparator ( iVisited . childNodes ( ) . iterator ( ) ) ; leaveCall ( ) ; print ( '' ) ; return null ; } public Object visitBackRefNode ( BackRefNode iVisited ) { print ( '' ) ; print ( iVisited . getType ( ) ) ; return null ; } public Object visitBeginNode ( BeginNode iVisited ) { print ( "" ) ; if ( getStartLine ( iVisited ) == getEndLine ( iVisited . getBodyNode ( ) ) ) { config . setSkipNextNewline ( true ) ; print ( "" ) ; visitNode ( iVisited . getBodyNode ( ) ) ; print ( "" ) ; } else { visitNodeInIndentation ( iVisited . getBodyNode ( ) ) ; printNewlineAndIndentation ( ) ; } print ( "" ) ; return null ; } public Object visitBignumNode ( BignumNode iVisited ) { print ( iVisited . getValue ( ) ) ; return null ; } public Object visitBlockArgNode ( BlockArgNode iVisited ) { print ( '' ) ; print ( iVisited . getName ( ) ) ; return null ; } public Object visitBlockNode ( BlockNode iVisited ) { visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; return null ; } public static int getLocalVarIndex ( Node n ) { return n instanceof LocalVarNode ? ( ( LocalVarNode ) n ) . getIndex ( ) : - ; } public Object visitBlockPassNode ( BlockPassNode iVisited ) { visitNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitBreakNode ( BreakNode iVisited ) { print ( "" ) ; return null ; } public Object visitConstDeclNode ( ConstDeclNode iVisited ) { printAsgnNode ( iVisited ) ; return null ; } public Object visitClassVarAsgnNode ( ClassVarAsgnNode iVisited ) { printAsgnNode ( iVisited ) ; return null ; } public Object visitClassVarDeclNode ( ClassVarDeclNode iVisited ) { printAsgnNode ( iVisited ) ; return null ; } public Object visitClassVarNode ( ClassVarNode iVisited ) { print ( iVisited . getName ( ) ) ; return null ; } private boolean isNumericNode ( Node n ) { return ( n != null && ( n instanceof FixnumNode || n instanceof BignumNode ) ) ; } private boolean isNameAnOperator ( String name ) { return Operators . contain ( name ) ; } private boolean printSpaceInsteadOfDot ( CallNode n ) { return ( isNameAnOperator ( n . getName ( ) ) && ! ( n . getArgsNode ( ) . childNodes ( ) . size ( ) > ) ) ; } protected void printAssignmentOperator ( ) { print ( config . getFormatHelper ( ) . beforeAssignment ( ) ) ; print ( "" ) ; print ( config . getFormatHelper ( ) . afterAssignment ( ) ) ; } private Object printIndexAssignment ( AttrAssignNode iVisited ) { enterCall ( ) ; visitNode ( iVisited . getReceiverNode ( ) ) ; leaveCall ( ) ; print ( '' ) ; visitNode ( firstChild ( iVisited . getArgsNode ( ) ) ) ; print ( "" ) ; printAssignmentOperator ( ) ; if ( iVisited . getArgsNode ( ) . childNodes ( ) . size ( ) > ) visitNode ( ( Node ) iVisited . getArgsNode ( ) . childNodes ( ) . get ( ) ) ; return null ; } private Object printIndexAccess ( CallNode visited ) { enterCall ( ) ; visitNode ( visited . getReceiverNode ( ) ) ; leaveCall ( ) ; print ( '' ) ; if ( visited . getArgsNode ( ) != null ) { visitAndPrintWithSeparator ( visited . getArgsNode ( ) . childNodes ( ) . iterator ( ) ) ; } print ( "" ) ; return null ; } private Object printNegativNumericNode ( CallNode visited ) { print ( '' ) ; visitNode ( visited . getReceiverNode ( ) ) ; return null ; } private boolean isNegativeNumericNode ( CallNode visited ) { return isNumericNode ( visited . getReceiverNode ( ) ) && visited . getName ( ) . equals ( "" ) ; } private void printCallReceiverNode ( CallNode iVisited ) { if ( iVisited . getReceiverNode ( ) instanceof HashNode ) print ( '' ) ; if ( isReceiverACallNode ( iVisited ) && ! printSpaceInsteadOfDot ( iVisited ) ) { enterCall ( ) ; visitNewlineInParentheses ( iVisited . getReceiverNode ( ) ) ; leaveCall ( ) ; } else { visitNewlineInParentheses ( iVisited . getReceiverNode ( ) ) ; } if ( iVisited . getReceiverNode ( ) instanceof HashNode ) print ( '' ) ; } protected boolean inMultipleAssignment ( ) { return false ; } public Object visitCallNode ( CallNode iVisited ) { if ( isNegativeNumericNode ( iVisited ) ) return printNegativNumericNode ( iVisited ) ; if ( iVisited . getName ( ) . equals ( "" ) ) return printIndexAccess ( iVisited ) ; printCallReceiverNode ( iVisited ) ; print ( printSpaceInsteadOfDot ( iVisited ) ? '' : '' ) ; if ( inMultipleAssignment ( ) && iVisited . getName ( ) . endsWith ( "" ) ) { print ( iVisited . getName ( ) . substring ( , iVisited . getName ( ) . length ( ) - ) ) ; } else { print ( iVisited . getName ( ) ) ; } if ( isNameAnOperator ( iVisited . getName ( ) ) ) { if ( firstChild ( iVisited . getArgsNode ( ) ) instanceof NewlineNode ) print ( '' ) ; config . getCallDepth ( ) . disableCallDepth ( ) ; } printCallArguments ( iVisited . getArgsNode ( ) , iVisited . getIterNode ( ) ) ; if ( isNameAnOperator ( iVisited . getName ( ) ) ) config . getCallDepth ( ) . enableCallDepth ( ) ; if ( ! ( iVisited . getIterNode ( ) instanceof BlockPassNode ) ) visitNode ( iVisited . getIterNode ( ) ) ; return null ; } public Object visitCaseNode ( CaseNode iVisited ) { print ( "" ) ; visitNode ( iVisited . getCaseNode ( ) ) ; visitNode ( iVisited . getCases ( ) . get ( ) ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; return null ; } private boolean printCommentsIn ( Node iVisited ) { boolean hadComment = false ; for ( CommentNode n : iVisited . getComments ( ) ) { if ( getStartLine ( n ) > getStartLine ( iVisited ) && getEndLine ( n ) < getEndLine ( iVisited ) ) { hadComment = true ; visitNode ( n ) ; printComment ( n . getContent ( ) ) ; printNewlineAndIndentation ( ) ; } } return hadComment ; } public Object visitClassNode ( ClassNode iVisited ) { print ( "" ) ; visitNode ( iVisited . getCPath ( ) ) ; if ( iVisited . getSuperNode ( ) != null ) { print ( "" ) ; visitNode ( iVisited . getSuperNode ( ) ) ; } new ClassBodyWriter ( this , iVisited . getBodyNode ( ) ) . write ( ) ; printNewlineAndIndentation ( ) ; printCommentsIn ( iVisited ) ; print ( "" ) ; return null ; } public Object visitColon2Node ( Colon2Node iVisited ) { if ( iVisited . getLeftNode ( ) != null ) { visitNode ( iVisited . getLeftNode ( ) ) ; print ( "" ) ; } print ( iVisited . getName ( ) ) ; return null ; } public Object visitColon3Node ( Colon3Node iVisited ) { if ( ! ( iVisited instanceof Colon2ImplicitNode ) ) { print ( "" ) ; } print ( iVisited . getName ( ) ) ; return null ; } public Object visitConstNode ( ConstNode iVisited ) { print ( iVisited . getName ( ) ) ; return null ; } public Object visitDAsgnNode ( DAsgnNode iVisited ) { printAsgnNode ( iVisited ) ; return null ; } public Object visitDRegxNode ( DRegexpNode iVisited ) { config . getPrintQuotesInString ( ) . set ( false ) ; print ( getFirstRegexpEnclosure ( iVisited ) ) ; factory . createDRegxReWriteVisitor ( ) . visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; print ( getSecondRegexpEnclosure ( iVisited ) ) ; printRegexpOptions ( iVisited . getOptions ( ) ) ; config . getPrintQuotesInString ( ) . revert ( ) ; return null ; } public Object visitDStrNode ( DStrNode iVisited ) { if ( firstChild ( iVisited ) instanceof StrNode ) { StrNode str = ( StrNode ) firstChild ( iVisited ) ; String realSource = getStringSource ( str ) ; if ( realSource != null && realSource . startsWith ( "" ) ) { print ( realSource . trim ( ) ) ; return null ; } } if ( config . getPrintQuotesInString ( ) . isTrue ( ) ) print ( getSeparatorForStr ( iVisited ) ) ; config . getPrintQuotesInString ( ) . set ( false ) ; leaveCall ( ) ; for ( Node child : iVisited . childNodes ( ) ) { visitNode ( child ) ; } enterCall ( ) ; config . getPrintQuotesInString ( ) . revert ( ) ; if ( config . getPrintQuotesInString ( ) . isTrue ( ) ) print ( getSeparatorForStr ( iVisited ) ) ; return null ; } public Object visitDSymbolNode ( DSymbolNode iVisited ) { print ( '' ) ; if ( config . getPrintQuotesInString ( ) . isTrue ( ) ) print ( getSeparatorForSym ( iVisited ) ) ; config . getPrintQuotesInString ( ) . set ( false ) ; leaveCall ( ) ; for ( Node child : iVisited . childNodes ( ) ) { visitNode ( child ) ; } enterCall ( ) ; config . getPrintQuotesInString ( ) . revert ( ) ; if ( config . getPrintQuotesInString ( ) . isTrue ( ) ) print ( getSeparatorForSym ( iVisited ) ) ; return null ; } public Object visitDVarNode ( DVarNode iVisited ) { print ( iVisited . getName ( ) ) ; return null ; } public Object visitDXStrNode ( DXStrNode iVisited ) { config . getPrintQuotesInString ( ) . set ( false ) ; print ( "" ) ; visitIter ( iVisited . childNodes ( ) . iterator ( ) ) ; print ( '' ) ; config . getPrintQuotesInString ( ) . revert ( ) ; return null ; } public Object visitDefinedNode ( DefinedNode iVisited ) { print ( "" ) ; enterCall ( ) ; visitNode ( iVisited . getExpressionNode ( ) ) ; leaveCall ( ) ; return null ; } private boolean hasArguments ( Node n ) { if ( n instanceof ArgsNode ) { ArgsNode args = ( ArgsNode ) n ; return ( args . getPre ( ) != null || args . getOptArgs ( ) != null || args . getBlock ( ) != null || args . getRestArgNode ( ) != null ) ; } else if ( n instanceof ArrayNode && n . childNodes ( ) . isEmpty ( ) ) { return false ; } return true ; } protected void printCommentsAtEnd ( Node n ) { for ( CommentNode comment : n . getComments ( ) ) { if ( getStartLine ( n ) == getStartLine ( comment ) ) { print ( '' ) ; visitNode ( comment ) ; print ( comment . getContent ( ) ) ; } } } private void printDefNode ( Node parent , String name , Node args , StaticScope scope , Node bodyNode ) { print ( name ) ; config . getLocalVariables ( ) . addLocalVariable ( scope ) ; if ( hasArguments ( args ) ) { print ( config . getFormatHelper ( ) . beforeMethodArguments ( ) ) ; visitNode ( args ) ; } printCommentsAtEnd ( parent ) ; visitNode ( bodyNode ) ; config . getIndentor ( ) . outdent ( ) ; printNewlineAndIndentation ( ) ; printCommentsIn ( parent ) ; print ( "" ) ; } public Object visitDefnNode ( DefnNode iVisited ) { config . getIndentor ( ) . indent ( ) ; print ( "" ) ; printDefNode ( iVisited , iVisited . getName ( ) , iVisited . getArgsNode ( ) , iVisited . getScope ( ) , iVisited . getBodyNode ( ) ) ; return null ; } public Object visitDefsNode ( DefsNode iVisited ) { config . getIndentor ( ) . indent ( ) ; print ( "" ) ; visitNode ( iVisited . getReceiverNode ( ) ) ; print ( '' ) ; printDefNode ( iVisited , iVisited . getName ( ) , iVisited . getArgsNode ( ) , iVisited . getScope ( ) , iVisited . getBodyNode ( ) ) ; return null ; } public Object visitDotNode ( DotNode iVisited ) { enterCall ( ) ; visitNode ( iVisited . getBeginNode ( ) ) ; print ( "" ) ; if ( iVisited . isExclusive ( ) ) print ( '' ) ; visitNode ( iVisited . getEndNode ( ) ) ; leaveCall ( ) ; return null ; } public Object visitEnsureNode ( EnsureNode iVisited ) { visitNode ( iVisited . getBodyNode ( ) ) ; config . getIndentor ( ) . outdent ( ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; visitNodeInIndentation ( iVisited . getEnsureNode ( ) ) ; config . getIndentor ( ) . indent ( ) ; return null ; } public Object visitEvStrNode ( EvStrNode iVisited ) { print ( '' ) ; if ( ! ( iVisited . getBody ( ) instanceof NthRefNode ) ) print ( '' ) ; config . getPrintQuotesInString ( ) . set ( true ) ; visitNode ( unwrapNewlineNode ( iVisited . getBody ( ) ) ) ; config . getPrintQuotesInString ( ) . revert ( ) ; if ( ! ( iVisited . getBody ( ) instanceof NthRefNode ) ) print ( '' ) ; return null ; } private Node unwrapNewlineNode ( Node node ) { return node instanceof NewlineNode ? ( ( NewlineNode ) node ) . getNextNode ( ) : node ; } public Object visitFCallNode ( FCallNode iVisited ) { print ( iVisited . getName ( ) ) ; if ( iVisited . getIterNode ( ) != null ) config . getCallDepth ( ) . enterCall ( ) ; if ( ( iVisited . getArgsNode ( ) == null || iVisited . getArgsNode ( ) . childNodes ( ) . isEmpty ( ) ) && matchingLocalVar ( iVisited . getName ( ) ) ) { print ( "" ) ; } printCallArguments ( iVisited . getArgsNode ( ) , iVisited . getIterNode ( ) ) ; if ( iVisited . getIterNode ( ) != null ) config . getCallDepth ( ) . leaveCall ( ) ; if ( ! ( iVisited . getIterNode ( ) instanceof BlockPassNode ) ) visitNode ( iVisited . getIterNode ( ) ) ; return null ; } private boolean matchingLocalVar ( String name ) { for ( String varName : config . getLocalVariables ( ) . getNames ( ) ) { if ( varName . equals ( name ) ) return true ; } return false ; } public Object visitFalseNode ( FalseNode iVisited ) { print ( "" ) ; return null ; } public Object visitFixnumNode ( FixnumNode iVisited ) { print ( iVisited . getValue ( ) ) ; return null ; } public Object visitFlipNode ( FlipNode iVisited ) { enterCall ( ) ; visitNode ( iVisited . getBeginNode ( ) ) ; print ( "" ) ; if ( iVisited . isExclusive ( ) ) print ( '' ) ; print ( '' ) ; visitNode ( iVisited . getEndNode ( ) ) ; leaveCall ( ) ; return null ; } public Object visitFloatNode ( FloatNode iVisited ) { print ( iVisited . getValue ( ) ) ; return null ; } public Object visitForNode ( ForNode iVisited ) { print ( "" ) ; visitNode ( iVisited . getVarNode ( ) ) ; print ( "" ) ; visitNode ( iVisited . getIterNode ( ) ) ; visitNodeInIndentation ( iVisited . getBodyNode ( ) ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; return null ; } public Object visitGlobalAsgnNode ( GlobalAsgnNode iVisited ) { printAsgnNode ( iVisited ) ; return null ; } public Object visitGlobalVarNode ( GlobalVarNode iVisited ) { print ( iVisited . getName ( ) ) ; return null ; } private void printHashNodeContent ( HashNode iVisited ) { print ( config . getFormatHelper ( ) . beforeHashContent ( ) ) ; if ( iVisited . getListNode ( ) != null ) { for ( Iterator < Node > it = iVisited . getListNode ( ) . childNodes ( ) . iterator ( ) ; it . hasNext ( ) ; ) { visitNode ( it . next ( ) ) ; print ( config . getFormatHelper ( ) . hashAssignment ( ) ) ; visitNode ( it . next ( ) ) ; if ( it . hasNext ( ) ) print ( config . getFormatHelper ( ) . getListSeparator ( ) ) ; } } print ( config . getFormatHelper ( ) . afterHashContent ( ) ) ; } public Object visitHashNode ( HashNode iVisited ) { print ( '' ) ; printHashNodeContent ( iVisited ) ; print ( '' ) ; return null ; } private void printAsgnNode ( AssignableNode n ) { String name = ( ( INameNode ) n ) . getName ( ) ; print ( name ) ; if ( n . getValueNode ( ) == null || n . getValueNode ( ) . isInvisible ( ) ) return ; if ( config . getFormatHelper ( ) . collapseOperatorSelfAssignments ( ) ) { if ( n . getValueNode ( ) instanceof CallNode ) { CallNode call = ( CallNode ) n . getValueNode ( ) ; if ( call . getName ( ) . equals ( "" ) || call . getName ( ) . equals ( "" ) || call . getName ( ) . equals ( "" ) ) { if ( call . getReceiverNode ( ) instanceof INameNode ) { INameNode recvr = ( INameNode ) call . getReceiverNode ( ) ; if ( recvr . getName ( ) . equals ( name ) ) { print ( config . getFormatHelper ( ) . beforeAssignment ( ) ) ; print ( call . getName ( ) ) ; print ( "" ) ; printCallArguments ( call . getArgsNode ( ) , call . getIterNode ( ) ) ; return ; } } } } } printAssignmentOperator ( ) ; visitNewlineInParentheses ( n . getValueNode ( ) ) ; } public Object visitInstAsgnNode ( InstAsgnNode iVisited ) { printAsgnNode ( iVisited ) ; return null ; } public Object visitInstVarNode ( InstVarNode iVisited ) { print ( iVisited . getName ( ) ) ; return null ; } private Node printElsIfNodes ( Node iVisited ) { if ( iVisited != null && iVisited instanceof IfNode ) { IfNode n = ( IfNode ) iVisited ; printNewlineAndIndentation ( ) ; print ( "" ) ; visitNode ( n . getCondition ( ) ) ; visitNodeInIndentation ( n . getThenBody ( ) ) ; return printElsIfNodes ( n . getElseBody ( ) ) ; } return iVisited != null ? iVisited : null ; } private Object printShortIfStatement ( IfNode n ) { if ( n . getThenBody ( ) == null ) { visitNode ( n . getElseBody ( ) ) ; print ( "" ) ; visitNode ( n . getCondition ( ) ) ; } else { enterCall ( ) ; factory . createShortIfNodeReWriteVisitor ( ) . visitNode ( n . getCondition ( ) ) ; print ( "" ) ; factory . createShortIfNodeReWriteVisitor ( ) . visitNode ( n . getThenBody ( ) ) ; print ( "" ) ; factory . createShortIfNodeReWriteVisitor ( ) . visitNewlineInParentheses ( n . getElseBody ( ) ) ; leaveCall ( ) ; } return null ; } private boolean isAssignment ( Node n ) { return ( n instanceof DAsgnNode || n instanceof GlobalAsgnNode || n instanceof InstAsgnNode || n instanceof LocalAsgnNode || n instanceof ClassVarAsgnNode ) ; } private boolean sourceSubStringEquals ( int offset , int length , String str ) { return config . getSource ( ) . length ( ) >= offset + length && config . getSource ( ) . substring ( offset , offset + length ) . equals ( str ) ; } private boolean isShortIfStatement ( IfNode iVisited ) { return ( isOnSingleLine ( iVisited . getCondition ( ) , iVisited . getElseBody ( ) ) && ! ( iVisited . getElseBody ( ) instanceof IfNode ) && ! sourceSubStringEquals ( getStartOffset ( iVisited ) , , "" ) ) ; } public Object visitIfNode ( IfNode iVisited ) { if ( isShortIfStatement ( iVisited ) ) return printShortIfStatement ( iVisited ) ; if ( isIfModifier ( iVisited ) ) return printIfModifier ( iVisited ) ; print ( "" ) ; if ( isAssignment ( iVisited . getCondition ( ) ) ) enterCall ( ) ; visitNewlineInParentheses ( iVisited . getCondition ( ) ) ; if ( isAssignment ( iVisited . getCondition ( ) ) ) leaveCall ( ) ; config . getIndentor ( ) . indent ( ) ; if ( ! isStartOnNewLine ( iVisited . getCondition ( ) , iVisited . getThenBody ( ) ) && iVisited . getThenBody ( ) != null ) { printNewlineAndIndentation ( ) ; config . setSkipNextNewline ( true ) ; } visitNode ( iVisited . getThenBody ( ) ) ; config . getIndentor ( ) . outdent ( ) ; Node elseNode = printElsIfNodes ( iVisited . getElseBody ( ) ) ; if ( elseNode != null ) { printNewlineAndIndentation ( ) ; print ( "" ) ; config . getIndentor ( ) . indent ( ) ; visitNode ( elseNode ) ; config . getIndentor ( ) . outdent ( ) ; } printNewlineAndIndentation ( ) ; print ( "" ) ; return null ; } private Object printIfModifier ( IfNode iVisited ) { visitNode ( iVisited . getThenBody ( ) ) ; print ( "" ) ; if ( isAssignment ( iVisited . getCondition ( ) ) ) enterCall ( ) ; visitNewlineInParentheses ( iVisited . getCondition ( ) ) ; if ( isAssignment ( iVisited . getCondition ( ) ) ) leaveCall ( ) ; return null ; } private boolean isIfModifier ( IfNode visited ) { Node then = visited . getThenBody ( ) ; if ( then == null ) return false ; Node condition = visited . getCondition ( ) ; if ( condition . getPosition ( ) . getStartOffset ( ) > then . getPosition ( ) . getEndOffset ( ) ) return true ; return false ; } private boolean isOnSingleLine ( Node n ) { return isOnSingleLine ( n , n ) ; } private boolean isOnSingleLine ( Node n1 , Node n2 ) { if ( n1 == null || n2 == null ) return false ; return ( getStartLine ( n1 ) == getEndLine ( n2 ) ) ; } private boolean printIterVarNode ( IterNode n ) { if ( n . getVarNode ( ) == null ) return false ; print ( '' ) ; visitNode ( n . getVarNode ( ) ) ; print ( '' ) ; return true ; } public Object visitIterNode ( IterNode iVisited ) { if ( isOnSingleLine ( iVisited ) ) { print ( config . getFormatHelper ( ) . beforeIterBrackets ( ) ) ; print ( "" ) ; print ( config . getFormatHelper ( ) . beforeIterVars ( ) ) ; if ( printIterVarNode ( iVisited ) ) print ( config . getFormatHelper ( ) . afterIterVars ( ) ) ; config . setSkipNextNewline ( true ) ; visitNode ( iVisited . getBodyNode ( ) ) ; print ( config . getFormatHelper ( ) . beforeClosingIterBrackets ( ) ) ; print ( '' ) ; } else { print ( "" ) ; printIterVarNode ( iVisited ) ; visitNodeInIndentation ( iVisited . getBodyNode ( ) ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; } return null ; } public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { config . getLocalVariables ( ) . addLocalVariable ( iVisited . getIndex ( ) , iVisited . getName ( ) ) ; printAsgnNode ( iVisited ) ; return null ; } public Object visitLocalVarNode ( LocalVarNode iVisited ) { print ( iVisited . getName ( ) ) ; return null ; } public Object visitMultipleAsgnNode ( MultipleAsgnNode iVisited ) { if ( iVisited . getHeadNode ( ) != null ) { factory . createMultipleAssignmentReWriteVisitor ( ) . visitAndPrintWithSeparator ( iVisited . getHeadNode ( ) . childNodes ( ) . iterator ( ) ) ; } if ( iVisited . getValueNode ( ) == null || iVisited . getValueNode ( ) . isInvisible ( ) ) { visitNode ( iVisited . getArgsNode ( ) ) ; return null ; } print ( config . getFormatHelper ( ) . beforeAssignment ( ) ) ; print ( "" ) ; print ( config . getFormatHelper ( ) . afterAssignment ( ) ) ; enterCall ( ) ; if ( iVisited . getValueNode ( ) instanceof ArrayNode ) { visitAndPrintWithSeparator ( iVisited . getValueNode ( ) . childNodes ( ) . iterator ( ) ) ; } else { visitNode ( iVisited . getValueNode ( ) ) ; } leaveCall ( ) ; return null ; } public Object visitMultipleAsgnNode ( MultipleAsgn19Node iVisited ) { if ( iVisited . getPre ( ) != null ) { factory . createMultipleAssignmentReWriteVisitor ( ) . visitAndPrintWithSeparator ( iVisited . getPre ( ) . childNodes ( ) . iterator ( ) ) ; } if ( iVisited . getValueNode ( ) == null || iVisited . getValueNode ( ) . isInvisible ( ) ) { visitNode ( iVisited . getRest ( ) ) ; return null ; } print ( config . getFormatHelper ( ) . beforeAssignment ( ) ) ; print ( "" ) ; print ( config . getFormatHelper ( ) . afterAssignment ( ) ) ; enterCall ( ) ; if ( iVisited . getValueNode ( ) instanceof ArrayNode ) { visitAndPrintWithSeparator ( iVisited . getValueNode ( ) . childNodes ( ) . iterator ( ) ) ; } else { visitNode ( iVisited . getValueNode ( ) ) ; } leaveCall ( ) ; return null ; } public Object visitMatch2Node ( Match2Node iVisited ) { visitNode ( iVisited . getReceiverNode ( ) ) ; print ( config . getFormatHelper ( ) . matchOperator ( ) ) ; enterCall ( ) ; visitNode ( iVisited . getValueNode ( ) ) ; leaveCall ( ) ; return null ; } public Object visitMatch3Node ( Match3Node iVisited ) { visitNode ( iVisited . getValueNode ( ) ) ; print ( config . getFormatHelper ( ) . matchOperator ( ) ) ; visitNode ( iVisited . getReceiverNode ( ) ) ; return null ; } public Object visitMatchNode ( MatchNode iVisited ) { visitNode ( iVisited . getRegexpNode ( ) ) ; return null ; } public Object visitModuleNode ( ModuleNode iVisited ) { print ( "" ) ; config . getIndentor ( ) . indent ( ) ; visitNode ( iVisited . getCPath ( ) ) ; visitNode ( iVisited . getBodyNode ( ) ) ; config . getIndentor ( ) . outdent ( ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; return null ; } public Object visitNewlineNode ( NewlineNode iVisited ) { if ( config . isSkipNextNewline ( ) ) { config . setSkipNextNewline ( false ) ; } else { printNewlineAndIndentation ( ) ; } visitNode ( iVisited . getNextNode ( ) ) ; return null ; } public Object visitNextNode ( NextNode iVisited ) { print ( "" ) ; return null ; } public Object visitNilNode ( NilNode iVisited ) { print ( "" ) ; return null ; } public Object visitNotNode ( NotNode iVisited ) { if ( iVisited . getConditionNode ( ) instanceof CallNode ) { CallNode call = ( CallNode ) iVisited . getConditionNode ( ) ; String name = call . getName ( ) ; if ( name . equals ( "" ) ) { printCallReceiverNode ( call ) ; print ( "" ) ; if ( firstChild ( call . getArgsNode ( ) ) instanceof NewlineNode ) print ( '' ) ; config . getCallDepth ( ) . disableCallDepth ( ) ; printCallArguments ( call . getArgsNode ( ) , call . getIterNode ( ) ) ; config . getCallDepth ( ) . enableCallDepth ( ) ; return null ; } enterCall ( ) ; } print ( sourceRangeContains ( iVisited . getPosition ( ) , "" ) ? "" : "" ) ; visitNewlineInParentheses ( iVisited . getConditionNode ( ) ) ; if ( iVisited . getConditionNode ( ) instanceof CallNode ) leaveCall ( ) ; return null ; } public Object visitNthRefNode ( NthRefNode iVisited ) { print ( '' ) ; print ( iVisited . getMatchNumber ( ) ) ; return null ; } private boolean isSimpleNode ( Node n ) { return ( n instanceof LocalVarNode || n instanceof AssignableNode || n instanceof InstVarNode || n instanceof ClassVarNode || n instanceof GlobalVarNode || n instanceof ConstDeclNode || n instanceof VCallNode || isNumericNode ( n ) ) ; } public Object visitOpElementAsgnNode ( OpElementAsgnNode iVisited ) { if ( ! isSimpleNode ( iVisited . getReceiverNode ( ) ) ) { visitNewlineInParentheses ( iVisited . getReceiverNode ( ) ) ; } else { visitNode ( iVisited . getReceiverNode ( ) ) ; } visitNode ( iVisited . getArgsNode ( ) ) ; print ( '' ) ; print ( iVisited . getOperatorName ( ) ) ; print ( "" ) ; print ( config . getFormatHelper ( ) . afterAssignment ( ) ) ; visitNode ( iVisited . getValueNode ( ) ) ; return null ; } public Object visitOpAsgnNode ( OpAsgnNode iVisited ) { visitNode ( iVisited . getReceiverNode ( ) ) ; print ( '' ) ; print ( iVisited . getVariableName ( ) ) ; print ( '' ) ; print ( iVisited . getOperatorName ( ) ) ; print ( "" ) ; print ( config . getFormatHelper ( ) . afterAssignment ( ) ) ; visitNode ( iVisited . getValueNode ( ) ) ; return null ; } private void printOpAsgnNode ( Node n , String operator ) { enterCall ( ) ; print ( ( ( INameNode ) n ) . getName ( ) ) ; print ( config . getFormatHelper ( ) . beforeAssignment ( ) ) ; print ( operator ) ; print ( config . getFormatHelper ( ) . afterAssignment ( ) ) ; visitNode ( ( ( AssignableNode ) n ) . getValueNode ( ) ) ; leaveCall ( ) ; } public Object visitOpAsgnAndNode ( OpAsgnAndNode iVisited ) { printOpAsgnNode ( iVisited . getSecondNode ( ) , "" ) ; return null ; } public Object visitOpAsgnOrNode ( OpAsgnOrNode iVisited ) { printOpAsgnNode ( iVisited . getSecondNode ( ) , "" ) ; return null ; } public Object visitOrNode ( OrNode iVisited ) { enterCall ( ) ; visitNode ( iVisited . getFirstNode ( ) ) ; leaveCall ( ) ; print ( sourceRangeContains ( iVisited . getPosition ( ) , "" ) ? "" : "" ) ; enterCall ( ) ; visitNewlineInParentheses ( iVisited . getSecondNode ( ) ) ; leaveCall ( ) ; return null ; } public Object visitPostExeNode ( PostExeNode iVisited ) { return null ; } public Object visitPreExeNode ( PreExeNode iVisited ) { return null ; } public Object visitRedoNode ( RedoNode iVisited ) { print ( "" ) ; return null ; } private String getFirstRegexpEnclosure ( Node n ) { return isSpecialRegexNotation ( n ) ? "" : "" ; } private String getSecondRegexpEnclosure ( Node n ) { return isSpecialRegexNotation ( n ) ? "" : "" ; } private boolean isSpecialRegexNotation ( Node n ) { return getStartOffset ( n ) >= && ! ( config . getSource ( ) . length ( ) < getStartOffset ( n ) ) && config . getSource ( ) . charAt ( getStartOffset ( n ) - ) == '' ; } private void printRegexpOptions ( int option ) { if ( ( option & ) == ) print ( '' ) ; if ( ( option & ) == ) print ( '' ) ; if ( ( option & ) == ) print ( '' ) ; } public Object visitRegexpNode ( RegexpNode iVisited ) { print ( getFirstRegexpEnclosure ( iVisited ) ) ; print ( iVisited . getValue ( ) . toString ( ) ) ; print ( getSecondRegexpEnclosure ( iVisited ) ) ; printRegexpOptions ( iVisited . getOptions ( ) ) ; return null ; } public static Node firstChild ( Node n ) { if ( n == null || n . childNodes ( ) . size ( ) <= ) return null ; return ( Node ) n . childNodes ( ) . get ( ) ; } public Object visitRescueBodyNode ( RescueBodyNode iVisited ) { if ( ! iVisited . getBodyNode ( ) . isInvisible ( ) && config . getLastPosition ( ) . getStartLine ( ) == getEndLine ( iVisited . getBodyNode ( ) ) ) { print ( "" ) ; } else { print ( "" ) ; } if ( iVisited . getExceptionNodes ( ) != null ) { printExceptionNode ( iVisited ) ; } else { visitNodeInIndentation ( iVisited . getBodyNode ( ) ) ; } if ( iVisited . getOptRescueNode ( ) != null ) printNewlineAndIndentation ( ) ; visitNode ( iVisited . getOptRescueNode ( ) ) ; return null ; } private void printExceptionNode ( RescueBodyNode n ) { if ( n . getExceptionNodes ( ) == null ) return ; print ( '' ) ; visitNode ( firstChild ( n . getExceptionNodes ( ) ) ) ; Node firstBodyNode = n . getBodyNode ( ) ; if ( n . getBodyNode ( ) instanceof BlockNode ) firstBodyNode = firstChild ( n . getBodyNode ( ) ) ; if ( firstBodyNode instanceof AssignableNode ) { print ( config . getFormatHelper ( ) . beforeAssignment ( ) ) ; print ( "" ) ; print ( config . getFormatHelper ( ) . afterAssignment ( ) ) ; print ( ( ( INameNode ) firstBodyNode ) . getName ( ) ) ; if ( firstBodyNode instanceof LocalAsgnNode ) config . getLocalVariables ( ) . addLocalVariable ( ( ( LocalAsgnNode ) firstBodyNode ) . getIndex ( ) , ( ( LocalAsgnNode ) firstBodyNode ) . getName ( ) ) ; config . getIndentor ( ) . indent ( ) ; visitIterAndSkipFirst ( n . getBodyNode ( ) . childNodes ( ) . iterator ( ) ) ; config . getIndentor ( ) . outdent ( ) ; } else { visitNodeInIndentation ( n . getBodyNode ( ) ) ; } } public Object visitRescueNode ( RescueNode iVisited ) { visitNode ( iVisited . getBodyNode ( ) ) ; config . getIndentor ( ) . outdent ( ) ; if ( iVisited . getRescueNode ( ) . getBodyNode ( ) . isInvisible ( ) ) { printNewlineAndIndentation ( ) ; print ( "" ) ; printExceptionNode ( iVisited . getRescueNode ( ) ) ; } else { if ( getStartLine ( iVisited ) != getEndLine ( iVisited . getRescueNode ( ) . getBodyNode ( ) ) ) printNewlineAndIndentation ( ) ; visitNode ( iVisited . getRescueNode ( ) ) ; } if ( iVisited . getElseNode ( ) != null ) { printNewlineAndIndentation ( ) ; print ( "" ) ; visitNodeInIndentation ( iVisited . getElseNode ( ) ) ; } config . getIndentor ( ) . indent ( ) ; return null ; } public Object visitRetryNode ( RetryNode iVisited ) { print ( "" ) ; return null ; } public static Node unwrapSingleArrayNode ( Node n ) { if ( ! ( n instanceof ArrayNode ) ) return n ; if ( ( ( ArrayNode ) n ) . childNodes ( ) . size ( ) > ) return n ; return firstChild ( ( ArrayNode ) n ) ; } public Object visitReturnNode ( ReturnNode iVisited ) { print ( "" ) ; enterCall ( ) ; if ( ! iVisited . getValueNode ( ) . isInvisible ( ) ) { print ( '' ) ; visitNode ( unwrapSingleArrayNode ( iVisited . getValueNode ( ) ) ) ; } leaveCall ( ) ; return null ; } public Object visitSClassNode ( SClassNode iVisited ) { print ( "" ) ; config . getIndentor ( ) . indent ( ) ; visitNode ( iVisited . getReceiverNode ( ) ) ; visitNode ( iVisited . getBodyNode ( ) ) ; config . getIndentor ( ) . outdent ( ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; return null ; } public Object visitSelfNode ( SelfNode iVisited ) { print ( "" ) ; return null ; } public Object visitSplatNode ( SplatNode iVisited ) { print ( "" ) ; visitNode ( iVisited . getValue ( ) ) ; return null ; } protected char getSeparatorForSym ( Node n ) { if ( config . getSource ( ) . length ( ) >= ( getStartOffset ( n ) + ) && config . getSource ( ) . charAt ( getStartOffset ( n ) + ) == '' ) { return '' ; } return '' ; } protected char getSeparatorForStr ( Node n ) { if ( config . getSource ( ) . length ( ) >= getStartOffset ( n ) && config . getSource ( ) . charAt ( getStartOffset ( n ) ) == '' ) { return '' ; } return '' ; } protected boolean inDRegxNode ( ) { return false ; } public Object visitStrNode ( StrNode iVisited ) { String realSource = getStringSource ( iVisited ) ; if ( realSource != null && realSource . startsWith ( "" ) ) { print ( realSource . trim ( ) ) ; return null ; } if ( realSource == null ) realSource = iVisited . getValue ( ) . toString ( ) ; String opening = "" + getSeparatorForStr ( iVisited ) ; String closing = opening ; if ( realSource != null && realSource . startsWith ( "" ) ) { int index = realSource . indexOf ( iVisited . getValue ( ) . toString ( ) ) ; opening = realSource . substring ( , index ) ; closing = realSource . substring ( index + iVisited . getValue ( ) . toString ( ) . length ( ) ) . trim ( ) ; } if ( realSource . equals ( "" ) ) { if ( config . getPrintQuotesInString ( ) . isTrue ( ) ) print ( "" ) ; return null ; } if ( config . getPrintQuotesInString ( ) . isTrue ( ) ) { print ( opening ) ; } if ( inDRegxNode ( ) ) { print ( iVisited . getValue ( ) . toString ( ) ) ; } else { Matcher matcher = Pattern . compile ( "" ) . matcher ( iVisited . getValue ( ) . toString ( ) ) ; if ( matcher . find ( ) ) { String unescChar = unescapeChar ( matcher . group ( ) . charAt ( ) ) ; print ( matcher . replaceAll ( "" + unescChar ) ) ; } else { print ( iVisited . getValue ( ) . toString ( ) ) ; } } if ( config . getPrintQuotesInString ( ) . isTrue ( ) ) { print ( closing ) ; } return null ; } private String getStringSource ( StrNode n ) { String src = config . getSource ( ) ; if ( src == null || src . length ( ) == ) return null ; int start = Math . max ( , n . getPosition ( ) . getStartOffset ( ) ) ; int end = Math . min ( src . length ( ) , n . getPosition ( ) . getEndOffset ( ) + ) ; String realValue = src . substring ( start , end ) ; return realValue ; } public static String unescapeChar ( char escapedChar ) { switch ( escapedChar ) { case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; default : return null ; } } private boolean needsSuperNodeParentheses ( SuperNode n ) { return n . getArgsNode ( ) . childNodes ( ) . isEmpty ( ) && config . getSource ( ) . charAt ( getEndOffset ( n ) ) == '' ; } public Object visitSuperNode ( SuperNode iVisited ) { print ( "" ) ; if ( needsSuperNodeParentheses ( iVisited ) ) print ( '' ) ; printCallArguments ( iVisited . getArgsNode ( ) , iVisited . getIterNode ( ) ) ; if ( needsSuperNodeParentheses ( iVisited ) ) print ( '' ) ; return null ; } public Object visitSValueNode ( SValueNode iVisited ) { visitNode ( iVisited . getValue ( ) ) ; return null ; } public Object visitSymbolNode ( SymbolNode iVisited ) { print ( '' ) ; print ( iVisited . getName ( ) ) ; return null ; } public Object visitToAryNode ( ToAryNode iVisited ) { visitNode ( iVisited . getValue ( ) ) ; return null ; } public Object visitTrueNode ( TrueNode iVisited ) { print ( "" ) ; return null ; } public Object visitUndefNode ( UndefNode iVisited ) { print ( "" ) ; print ( iVisited . getName ( ) ) ; return null ; } public Object visitUntilNode ( UntilNode iVisited ) { if ( isUntilModifier ( iVisited ) ) return printUntilModifier ( iVisited ) ; print ( "" ) ; visitNode ( iVisited . getConditionNode ( ) ) ; visitNodeInIndentation ( iVisited . getBodyNode ( ) ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; return null ; } private Object printUntilModifier ( UntilNode iVisited ) { visitNode ( iVisited . getBodyNode ( ) ) ; print ( "" ) ; visitNode ( iVisited . getConditionNode ( ) ) ; return null ; } private boolean isUntilModifier ( UntilNode visited ) { Node condition = visited . getConditionNode ( ) ; Node body = visited . getBodyNode ( ) ; return ( body . getPosition ( ) . getEndOffset ( ) < condition . getPosition ( ) . getStartOffset ( ) ) ; } public Object visitVAliasNode ( VAliasNode iVisited ) { print ( "" ) ; print ( iVisited . getNewName ( ) ) ; print ( '' ) ; print ( iVisited . getOldName ( ) ) ; return null ; } public Object visitVCallNode ( VCallNode iVisited ) { print ( iVisited . getName ( ) ) ; return null ; } public void visitNodeInIndentation ( Node n ) { config . getIndentor ( ) . indent ( ) ; visitNode ( n ) ; config . getIndentor ( ) . outdent ( ) ; } public Object visitWhenNode ( WhenNode iVisited ) { printNewlineAndIndentation ( ) ; print ( "" ) ; enterCall ( ) ; Node expression = iVisited . getExpressionNodes ( ) ; if ( expression instanceof ListNode ) { visitAndPrintWithSeparator ( expression . childNodes ( ) . iterator ( ) ) ; } else { visitNode ( expression ) ; } leaveCall ( ) ; visitNodeInIndentation ( iVisited . getBodyNode ( ) ) ; if ( ( iVisited . getNextCase ( ) instanceof WhenNode || iVisited . getNextCase ( ) == null ) ) { visitNode ( iVisited . getNextCase ( ) ) ; } else { printNewlineAndIndentation ( ) ; print ( "" ) ; visitNodeInIndentation ( iVisited . getNextCase ( ) ) ; } return null ; } protected void visitNewlineInParentheses ( Node n ) { if ( n instanceof NewlineNode ) { if ( ( ( NewlineNode ) n ) . getNextNode ( ) instanceof SplatNode ) { print ( '' ) ; visitNode ( ( ( NewlineNode ) n ) . getNextNode ( ) ) ; print ( '' ) ; } else { print ( '' ) ; visitNode ( ( ( NewlineNode ) n ) . getNextNode ( ) ) ; print ( '' ) ; } } else { visitNode ( n ) ; } } private void printWhileStatement ( WhileNode iVisited ) { if ( isWhileModifier ( iVisited ) ) { printWhileModifier ( iVisited ) ; return ; } print ( "" ) ; if ( isAssignment ( iVisited . getConditionNode ( ) ) ) enterCall ( ) ; visitNewlineInParentheses ( iVisited . getConditionNode ( ) ) ; if ( isAssignment ( iVisited . getConditionNode ( ) ) ) leaveCall ( ) ; if ( config . getFormatHelper ( ) . insertDoAfterWhileExpression ( ) ) print ( "" ) ; visitNodeInIndentation ( iVisited . getBodyNode ( ) ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; } private void printWhileModifier ( WhileNode visited ) { visitNode ( visited . getBodyNode ( ) ) ; print ( "" ) ; if ( isAssignment ( visited . getConditionNode ( ) ) ) enterCall ( ) ; visitNewlineInParentheses ( visited . getConditionNode ( ) ) ; if ( isAssignment ( visited . getConditionNode ( ) ) ) leaveCall ( ) ; } private boolean isWhileModifier ( WhileNode visited ) { Node condition = visited . getConditionNode ( ) ; Node body = visited . getBodyNode ( ) ; return ( body . getPosition ( ) . getEndOffset ( ) < condition . getPosition ( ) . getStartOffset ( ) ) ; } private void printDoWhileStatement ( WhileNode iVisited ) { print ( "" ) ; visitNodeInIndentation ( iVisited . getBodyNode ( ) ) ; printNewlineAndIndentation ( ) ; print ( "" ) ; visitNode ( iVisited . getConditionNode ( ) ) ; } public Object visitWhileNode ( WhileNode iVisited ) { if ( iVisited . evaluateAtStart ( ) ) { printWhileStatement ( iVisited ) ; } else { printDoWhileStatement ( iVisited ) ; } return null ; } public Object visitXStrNode ( XStrNode iVisited ) { print ( '' ) ; print ( iVisited . getValue ( ) . toString ( ) ) ; print ( '' ) ; return null ; } public Object visitYieldNode ( YieldNode iVisited ) { print ( "" ) ; if ( iVisited . getArgsNode ( ) != null ) { print ( needsParentheses ( iVisited . getArgsNode ( ) ) ? '' : '' ) ; enterCall ( ) ; if ( iVisited . getArgsNode ( ) instanceof ArrayNode ) { visitAndPrintWithSeparator ( iVisited . getArgsNode ( ) . childNodes ( ) . iterator ( ) ) ; } else { visitNode ( iVisited . getArgsNode ( ) ) ; } leaveCall ( ) ; if ( needsParentheses ( iVisited . getArgsNode ( ) ) ) print ( '' ) ; } return null ; } public Object visitZArrayNode ( ZArrayNode iVisited ) { print ( "" ) ; return null ; } public Object visitZSuperNode ( ZSuperNode iVisited ) { print ( "" ) ; return null ; } private static int getStartLine ( Node n ) { return n . getPosition ( ) . getStartLine ( ) ; } private static int getStartOffset ( Node n ) { return n . getPosition ( ) . getStartOffset ( ) ; } private static int getEndLine ( Node n ) { return n . getPosition ( ) . getEndLine ( ) ; } protected static int getEndOffset ( Node n ) { return n . getPosition ( ) . getEndOffset ( ) ; } public ReWriterContext getConfig ( ) { return config ; } public static String createCodeFromNode ( Node node , String document ) { return createCodeFromNode ( node , document , new EditableFormatHelper ( ) ) ; } public static String createCodeFromNode ( Node node , String document , FormatHelper helper ) { StringWriter writer = new StringWriter ( ) ; ReWriterContext ctx = new ReWriterContext ( writer , document , helper ) ; ReWriteVisitor rewriter = new ReWriteVisitor ( ctx ) ; rewriter . visitNode ( node ) ; return writer . toString ( ) ; } public Object visitArgsPushNode ( ArgsPushNode node ) { assert false : "" ; return null ; } public Object visitAttrAssignNode ( AttrAssignNode iVisited ) { if ( iVisited . getName ( ) . equals ( "" ) ) return printIndexAssignment ( iVisited ) ; if ( iVisited . getName ( ) . endsWith ( "" ) ) { visitNode ( iVisited . getReceiverNode ( ) ) ; print ( '' ) ; printNameWithoutEqualSign ( iVisited ) ; printAssignmentOperator ( ) ; if ( iVisited . getArgsNode ( ) != null ) { visitAndPrintWithSeparator ( iVisited . getArgsNode ( ) . childNodes ( ) . iterator ( ) ) ; } } else { assert false : "" ; } return null ; } private void printNameWithoutEqualSign ( INameNode iVisited ) { print ( iVisited . getName ( ) . substring ( , iVisited . getName ( ) . length ( ) - ) ) ; } public Object visitRootNode ( RootNode iVisited ) { config . getLocalVariables ( ) . addLocalVariable ( iVisited . getStaticScope ( ) ) ; visitNode ( iVisited . getBodyNode ( ) ) ; return null ; } public Object visitRestArgNode ( RestArgNode iVisited ) { print ( "" + iVisited . getName ( ) ) ; return null ; } } package org . rubypeople . rdt . core . formatter ; import java . util . Map ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . formatter . DefaultCodeFormatterOptions ; public class DefaultCodeFormatterConstants { public static final String MIXED = "" ; public static final String FORMATTER_INDENTATION_SIZE = RubyCore . PLUGIN_ID + "" ; public static final String FORMATTER_TAB_CHAR = RubyCore . PLUGIN_ID + "" ; public static final String FORMATTER_TAB_SIZE = RubyCore . PLUGIN_ID + "" ; public static final String FALSE = "" ; public static final String TRUE = "" ; public static final String FORMATTER_LINE_SPLIT = RubyCore . PLUGIN_ID + "" ; public static final String FORMATTER_INDENT_EMPTY_LINES = RubyCore . PLUGIN_ID + "" ; public static final String FORMATTER_INDENT_CASE_BODY = RubyCore . PLUGIN_ID + "" ; public static final String FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS = RubyCore . PLUGIN_ID + "" ; public final static String FORMATTER_COMMENT_FORMAT = RubyCore . PLUGIN_ID + "" ; public final static String FORMATTER_COMMENT_FORMAT_HEADER = RubyCore . PLUGIN_ID + "" ; public final static String FORMATTER_COMMENT_LINE_LENGTH = RubyCore . PLUGIN_ID + "" ; public final static String FORMATTER_COMMENT_CLEAR_BLANK_LINES = RubyCore . PLUGIN_ID + "" ; public static Map getEclipseDefaultSettings ( ) { return DefaultCodeFormatterOptions . getEclipseDefaultSettings ( ) . getMap ( ) ; } public static Map getRubyConventionsSettings ( ) { return DefaultCodeFormatterOptions . getRubyConventionsSettings ( ) . getMap ( ) ; } } package org . rubypeople . rdt . core . formatter ; import java . io . PrintWriter ; import java . io . StringWriter ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . formatter . rewriter . BooleanStateStack ; import org . rubypeople . rdt . core . formatter . rewriter . CallDepth ; import org . rubypeople . rdt . internal . formatter . Indentor ; import org . rubypeople . rdt . internal . formatter . rewriter . LocalVariables ; public class ReWriterContext { private final String source ; private final CallDepth callDepth = new CallDepth ( ) ; private final LocalVariables localVariables = new LocalVariables ( ) ; private final BooleanStateStack printQuotesInString = new BooleanStateStack ( true , true ) ; private boolean skipNextNewline = true ; private PrintWriter output ; private FormatHelper formatHelper ; private ISourcePosition lastPosition ; public LocalVariables getLocalVariables ( ) { return localVariables ; } public ReWriterContext ( PrintWriter output , String source , FormatHelper formatHelper ) { super ( ) ; this . output = output ; this . source = source ; this . formatHelper = formatHelper ; } public ReWriterContext ( StringWriter output , String source , FormatHelper formatHelper ) { this ( new PrintWriter ( output ) , source , formatHelper ) ; } public CallDepth getCallDepth ( ) { return callDepth ; } public String getSource ( ) { return source ; } public Indentor getIndentor ( ) { return formatHelper . getIndentor ( ) ; } public ISourcePosition getLastPosition ( ) { return lastPosition ; } public void setLastPosition ( ISourcePosition lastPosition ) { this . lastPosition = lastPosition ; } public BooleanStateStack getPrintQuotesInString ( ) { return printQuotesInString ; } public boolean isSkipNextNewline ( ) { return skipNextNewline ; } public void setSkipNextNewline ( boolean skipNextNewline ) { this . skipNextNewline = skipNextNewline ; } public PrintWriter getOutput ( ) { return output ; } public void setOutput ( PrintWriter output ) { this . output = output ; } public FormatHelper getFormatHelper ( ) { return formatHelper ; } } package org . rubypeople . rdt . core . formatter ; import org . rubypeople . rdt . internal . formatter . Indentor ; public interface FormatHelper { public static final String SPACE_AFTER_COMMA_IN_LISTS = "" ; public static final String SPACE_BEFORE_AND_AFTER_ASSIGNMENTS = "" ; public static final String ALWAYS_SURROUND_METHOD_CALLS_IN_PARENS = "" ; public static final String SPACES_AROUND_HASH_ASSIGNMENT = "" ; public static final String SPACES_BEFORE_AND_AFTER_HASH_CONTENT = "" ; public static final String SPACES_BEFORE_ITER_VARS = "" ; public static final String SPACE_AFTER_ITER_VARS = "" ; public static final String NEWLINE_BETWEEN_CLASS_BODY_ELEMENTS = "" ; public static final String ALWAYS_SURROUND_METHOD_ARGUMENTS_IN_PARENS = "" ; public static final String SPACE_BEFORE_BLOCK_BRACKETS = "" ; public static final String SPACE_BEFORE_CLOSING_BLOCK_BRACKET = "" ; public static final String INSERT_DO_AFTER_WHILE_EXPRESSION = "" ; public static final String COLLAPSE_OPERATOR_SELF_ASSIGNMENTS = "" ; public abstract Indentor getIndentor ( ) ; public abstract String getListSeparator ( ) ; public abstract String beforeCallArguments ( ) ; public abstract String afterCallArguments ( ) ; public abstract String beforeMethodArguments ( ) ; public abstract String afterMethodArguments ( ) ; public abstract String hashAssignment ( ) ; public abstract String beforeHashContent ( ) ; public abstract String afterHashContent ( ) ; public abstract String matchOperator ( ) ; public abstract String beforeAssignment ( ) ; public abstract String beforeIterBrackets ( ) ; public abstract String afterAssignment ( ) ; public abstract String beforeIterVars ( ) ; public abstract String afterIterVars ( ) ; public abstract String beforeClosingIterBrackets ( ) ; public abstract String classBodyElementsSeparator ( ) ; public abstract String getLineDelimiter ( ) ; public abstract boolean insertDoAfterWhileExpression ( ) ; public abstract boolean collapseOperatorSelfAssignments ( ) ; } package org . rubypeople . rdt . core . formatter . rewriter ; import java . util . EmptyStackException ; import java . util . Stack ; public class BooleanStateStack { private final Stack < Boolean > states = new Stack < Boolean > ( ) ; private final boolean defaultValue ; public BooleanStateStack ( boolean b , boolean defaultValue ) { set ( b ) ; this . defaultValue = defaultValue ; } public void set ( boolean b ) { states . push ( Boolean . valueOf ( b ) ) ; } public void revert ( ) { states . pop ( ) ; } public boolean isTrue ( ) { try { return ( ( Boolean ) states . peek ( ) ) . booleanValue ( ) ; } catch ( EmptyStackException e ) { return defaultValue ; } } } package org . rubypeople . rdt . core . formatter . rewriter ; public class CallDepth { private int nestedCallDepth ; private int savedNestedCallDepth ; public void enterCall ( ) { nestedCallDepth ++ ; } public void leaveCall ( ) { nestedCallDepth -- ; if ( nestedCallDepth < ) nestedCallDepth = ; } public boolean inCall ( ) { return nestedCallDepth > ; } public void disableCallDepth ( ) { savedNestedCallDepth = nestedCallDepth ; nestedCallDepth = ; } public void enableCallDepth ( ) { nestedCallDepth = savedNestedCallDepth ; } } package org . rubypeople . rdt . core . formatter ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Map ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DefaultLineTracker ; import org . eclipse . jface . text . ILineTracker ; import org . eclipse . jface . text . IRegion ; import org . eclipse . text . edits . ReplaceEdit ; import org . rubypeople . rdt . internal . compiler . parser . ScannerHelper ; public final class IndentManipulation { public static final String EMPTY_STRING = "" ; private IndentManipulation ( ) { } public static boolean isIndentChar ( char ch ) { return ScannerHelper . isWhitespace ( ch ) && ! isLineDelimiterChar ( ch ) ; } public static boolean isLineDelimiterChar ( char ch ) { return ch == '' || ch == '' ; } public static int measureIndentUnits ( CharSequence line , int tabWidth , int indentWidth ) { if ( indentWidth <= || tabWidth < || line == null ) { throw new IllegalArgumentException ( ) ; } int visualLength = measureIndentInSpaces ( line , tabWidth ) ; return visualLength / indentWidth ; } public static int measureIndentInSpaces ( CharSequence line , int tabWidth ) { if ( tabWidth < || line == null ) { throw new IllegalArgumentException ( ) ; } int length = ; int max = line . length ( ) ; for ( int i = ; i < max ; i ++ ) { char ch = line . charAt ( i ) ; if ( ch == '' ) { int reminder = length % tabWidth ; length += tabWidth - reminder ; } else if ( isIndentChar ( ch ) ) { length ++ ; } else { return length ; } } return length ; } public static String extractIndentString ( String line , int tabWidth , int indentWidth ) { if ( tabWidth < || indentWidth <= || line == null ) { throw new IllegalArgumentException ( ) ; } int size = line . length ( ) ; int end = ; int spaceEquivs = ; int characters = ; for ( int i = ; i < size ; i ++ ) { char c = line . charAt ( i ) ; if ( c == '' ) { int remainder = spaceEquivs % tabWidth ; spaceEquivs += tabWidth - remainder ; characters ++ ; } else if ( isIndentChar ( c ) ) { spaceEquivs ++ ; characters ++ ; } else { break ; } if ( spaceEquivs >= indentWidth ) { end += characters ; characters = ; spaceEquivs = spaceEquivs % indentWidth ; } } if ( end == ) { return EMPTY_STRING ; } else if ( end == size ) { return line ; } else { return line . substring ( , end ) ; } } public static String trimIndent ( String line , int indentUnitsToRemove , int tabWidth , int indentWidth ) { if ( tabWidth < || indentWidth <= || line == null ) { throw new IllegalArgumentException ( ) ; } if ( indentUnitsToRemove <= ) return line ; final int spaceEquivalentsToRemove = indentUnitsToRemove * indentWidth ; int start = ; int spaceEquivalents = ; int size = line . length ( ) ; String prefix = null ; for ( int i = ; i < size ; i ++ ) { char c = line . charAt ( i ) ; if ( c == '' ) { int remainder = spaceEquivalents % tabWidth ; spaceEquivalents += tabWidth - remainder ; } else if ( isIndentChar ( c ) ) { spaceEquivalents ++ ; } else { start = i ; break ; } if ( spaceEquivalents == spaceEquivalentsToRemove ) { start = i + ; break ; } if ( spaceEquivalents > spaceEquivalentsToRemove ) { start = i + ; char [ ] missing = new char [ spaceEquivalents - spaceEquivalentsToRemove ] ; Arrays . fill ( missing , '' ) ; prefix = new String ( missing ) ; break ; } } String trimmed ; if ( start == size ) trimmed = EMPTY_STRING ; else trimmed = line . substring ( start ) ; if ( prefix == null ) return trimmed ; return prefix + trimmed ; } public static String changeIndent ( String code , int indentUnitsToRemove , int tabWidth , int indentWidth , String newIndentString , String lineDelim ) { if ( tabWidth < || indentWidth <= || code == null || indentUnitsToRemove < || newIndentString == null || lineDelim == null ) { throw new IllegalArgumentException ( ) ; } try { ILineTracker tracker = new DefaultLineTracker ( ) ; tracker . set ( code ) ; int nLines = tracker . getNumberOfLines ( ) ; if ( nLines == ) { return code ; } StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < nLines ; i ++ ) { IRegion region = tracker . getLineInformation ( i ) ; int start = region . getOffset ( ) ; int end = start + region . getLength ( ) ; String line = code . substring ( start , end ) ; if ( i == ) { buf . append ( line ) ; } else { buf . append ( lineDelim ) ; buf . append ( newIndentString ) ; buf . append ( trimIndent ( line , indentUnitsToRemove , tabWidth , indentWidth ) ) ; } } return buf . toString ( ) ; } catch ( BadLocationException e ) { return code ; } } public static ReplaceEdit [ ] getChangeIndentEdits ( String source , int indentUnitsToRemove , int tabWidth , int indentWidth , String newIndentString ) { if ( tabWidth < || indentWidth <= || source == null || indentUnitsToRemove < || newIndentString == null ) { throw new IllegalArgumentException ( ) ; } ArrayList result = new ArrayList ( ) ; try { ILineTracker tracker = new DefaultLineTracker ( ) ; tracker . set ( source ) ; int nLines = tracker . getNumberOfLines ( ) ; if ( nLines == ) return ( ReplaceEdit [ ] ) result . toArray ( new ReplaceEdit [ result . size ( ) ] ) ; for ( int i = ; i < nLines ; i ++ ) { IRegion region = tracker . getLineInformation ( i ) ; int offset = region . getOffset ( ) ; String line = source . substring ( offset , offset + region . getLength ( ) ) ; int length = indexOfIndent ( line , indentUnitsToRemove , tabWidth , indentWidth ) ; if ( length >= ) { result . add ( new ReplaceEdit ( offset , length , newIndentString ) ) ; } else { length = measureIndentUnits ( line , tabWidth , indentWidth ) ; result . add ( new ReplaceEdit ( offset , length , "" ) ) ; } } } catch ( BadLocationException cannotHappen ) { } return ( ReplaceEdit [ ] ) result . toArray ( new ReplaceEdit [ result . size ( ) ] ) ; } private static int indexOfIndent ( CharSequence line , int numberOfIndentUnits , int tabWidth , int indentWidth ) { int spaceEquivalents = numberOfIndentUnits * indentWidth ; int size = line . length ( ) ; int result = - ; int blanks = ; for ( int i = ; i < size && blanks < spaceEquivalents ; i ++ ) { char c = line . charAt ( i ) ; if ( c == '' ) { int remainder = blanks % tabWidth ; blanks += tabWidth - remainder ; } else if ( isIndentChar ( c ) ) { blanks ++ ; } else { break ; } result = i ; } if ( blanks < spaceEquivalents ) return - ; return result + ; } public static int getTabWidth ( Map options ) { if ( options == null ) { throw new IllegalArgumentException ( ) ; } return getIntValue ( options , DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE , ) ; } public static int getIndentWidth ( Map options ) { if ( options == null ) { throw new IllegalArgumentException ( ) ; } int tabWidth = getTabWidth ( options ) ; boolean isMixedMode = DefaultCodeFormatterConstants . MIXED . equals ( options . get ( DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ) ) ; if ( isMixedMode ) { return getIntValue ( options , DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE , tabWidth ) ; } return tabWidth ; } private static int getIntValue ( Map options , String key , int def ) { try { return Integer . parseInt ( ( String ) options . get ( key ) ) ; } catch ( NumberFormatException e ) { return def ; } } } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . IPath ; public interface ILoadpathEntry { int CPE_LIBRARY = ; int CPE_PROJECT = ; int CPE_SOURCE = ; int CPE_VARIABLE = ; int CPE_CONTAINER = ; int getEntryKind ( ) ; IPath [ ] getExclusionPatterns ( ) ; IPath [ ] getInclusionPatterns ( ) ; IPath getPath ( ) ; boolean isExported ( ) ; ILoadpathAttribute [ ] getExtraAttributes ( ) ; } package org . rubypeople . rdt . core ; public interface IRubyInformation { public String getDocs ( String token ) ; } package org . rubypeople . rdt . core ; public interface ILoadpathAttribute { String OPTIONAL = "" ; String getName ( ) ; String getValue ( ) ; } package org . rubypeople . rdt . core ; public interface IParent { IRubyElement [ ] getChildren ( ) throws RubyModelException ; boolean hasChildren ( ) throws RubyModelException ; } package org . rubypeople . rdt . core ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IPath ; public interface IRubyElement extends IAdaptable { public static final int RUBY_MODEL = ; public static final int RUBY_PROJECT = ; public static final int SOURCE_FOLDER_ROOT = ; public static final int SOURCE_FOLDER = ; public static final int SCRIPT = ; public static final int TYPE = ; public static final int METHOD = ; public static final int GLOBAL = ; public static final int IMPORT_DECLARATION = ; public static final int CONSTANT = ; public static final int CLASS_VAR = ; public static final int INSTANCE_VAR = ; public static final int LOCAL_VARIABLE = ; public static final int BLOCK = ; public static final int DYNAMIC_VAR = ; public static final int FIELD = ; public static final int IMPORT_CONTAINER = ; IRubyElement getAncestor ( int ancestorType ) ; boolean exists ( ) ; String getElementName ( ) ; IResource getCorrespondingResource ( ) throws RubyModelException ; IResource getUnderlyingResource ( ) throws RubyModelException ; IOpenable getOpenable ( ) ; IRubyElement getParent ( ) ; boolean isType ( int type ) ; IPath getPath ( ) ; int getElementType ( ) ; public IRubyProject getRubyProject ( ) ; IRubyModel getRubyModel ( ) ; boolean isReadOnly ( ) ; IRubyElement getPrimaryElement ( ) ; IResource getResource ( ) ; boolean isStructureKnown ( ) throws RubyModelException ; public String getHandleIdentifier ( ) ; } package org . rubypeople . rdt . core . compiler ; import java . util . Collection ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . jruby . ast . CommentNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . SyntaxException ; import org . jruby . parser . RubyParserResult ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . builder . SyntaxExceptionHandler ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . Util ; public class BuildContext extends CompilationParticipantResult { private RubyParserResult ast ; private boolean alreadyFailed ; public BuildContext ( IFile resource ) { super ( resource ) ; } public char [ ] getContents ( ) { try { return Util . getResourceContentsAsCharArray ( this . resource ) ; } catch ( CoreException e ) { throw new RuntimeException ( "" + this . resource ) ; } } public IFile getFile ( ) { return this . resource ; } public boolean hasAnnotations ( ) { return this . hasAnnotations ; } public void recordNewProblems ( CategorizedProblem [ ] newProblems ) { int length2 = newProblems . length ; if ( length2 == ) return ; int length1 = this . problems == null ? : this . problems . length ; CategorizedProblem [ ] merged = new CategorizedProblem [ length1 + length2 ] ; if ( length1 > ) System . arraycopy ( this . problems , , merged , , length1 ) ; System . arraycopy ( newProblems , , merged , length1 , length2 ) ; this . problems = merged ; } public Node getAST ( ) { if ( ast == null ) { lazilyParse ( ) ; } if ( ast == null ) return null ; return ast . getAST ( ) ; } private void lazilyParse ( ) { if ( alreadyFailed ) return ; String contents = new String ( getContents ( ) ) ; try { IRubyScript script = RubyCore . create ( getFile ( ) ) ; ast = new RubyParser ( ) . parse ( script . getPath ( ) . toPortableString ( ) , contents ) ; } catch ( SyntaxException se ) { recordNewProblems ( new CategorizedProblem [ ] { SyntaxExceptionHandler . handle ( se , contents ) } ) ; alreadyFailed = true ; } catch ( Exception e ) { alreadyFailed = true ; } } public Collection < CommentNode > getComments ( ) { if ( ast == null ) { lazilyParse ( ) ; } if ( ast == null ) return null ; return ast . getCommentNodes ( ) ; } } package org . rubypeople . rdt . core . compiler ; public interface IProblem { int Uncategorized = ; int TypeRelated = ; int FieldRelated = ; int MethodRelated = ; int ConstructorRelated = ; int ImportRelated = ; int Internal = ; int Syntax = ; int IgnoreCategoriesMask = ; int UndocumentedEmptyBlock = Internal + ; int UnusedPrivateField = Internal + FieldRelated + ; int LocalVariableIsNeverUsed = Internal + ; int ArgumentIsNeverUsed = Internal + ; int UnusedPrivateMethod = Internal + MethodRelated + ; int Task = Internal + ; int MultineCommentNotAtFirstColumn = Syntax + ; int ParenthesizeArguments = Syntax + ; int HashCommaSyntax = Syntax + ; int ColonAfterWhenStatement = Syntax + ; int getID ( ) ; String [ ] getArguments ( ) ; String getMessage ( ) ; char [ ] getOriginatingFileName ( ) ; int getSourceEnd ( ) ; int getSourceLineNumber ( ) ; int getSourceStart ( ) ; boolean isError ( ) ; boolean isWarning ( ) ; boolean isTask ( ) ; } package org . rubypeople . rdt . core . compiler ; public class InvalidInputException extends Exception { private static final long serialVersionUID = ; public InvalidInputException ( ) { super ( ) ; } public InvalidInputException ( String message ) { super ( message ) ; } } package org . rubypeople . rdt . core . compiler ; import org . eclipse . core . resources . IFile ; public class CompilationParticipantResult { protected IFile resource ; protected boolean hasAnnotations ; protected IFile [ ] addedFiles ; protected IFile [ ] deletedFiles ; protected CategorizedProblem [ ] problems ; protected String [ ] dependencies ; protected CompilationParticipantResult ( IFile resource ) { this . resource = resource ; this . hasAnnotations = false ; this . addedFiles = null ; this . deletedFiles = null ; this . problems = null ; this . dependencies = null ; } void reset ( boolean detectedAnnotations ) { this . hasAnnotations = detectedAnnotations ; this . addedFiles = null ; this . deletedFiles = null ; this . problems = null ; this . dependencies = null ; } public String toString ( ) { return this . resource . toString ( ) ; } public CategorizedProblem [ ] getProblems ( ) { return problems ; } } package org . rubypeople . rdt . core . compiler ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyProject ; public abstract class CompilationParticipant { public static int READY_FOR_BUILD = ; public static int NEEDS_FULL_BUILD = ; public int aboutToBuild ( IRubyProject project ) { return READY_FOR_BUILD ; } public void buildStarting ( BuildContext [ ] files , boolean isBatch , IProgressMonitor monitor ) { } public void cleanStarting ( IRubyProject project ) { } public boolean isActive ( IRubyProject project ) { return false ; } public boolean isAnnotationProcessor ( ) { return false ; } public void processAnnotations ( BuildContext [ ] files , IProgressMonitor monitor ) { } public void reconcile ( ReconcileContext context ) { } protected void addProblems ( ReconcileContext context , String type , List < CategorizedProblem > problems ) { if ( problems == null || problems . size ( ) == ) return ; CategorizedProblem [ ] oldProblems = context . getProblems ( type ) ; if ( oldProblems == null || oldProblems . length == ) { context . putProblems ( type , problems . toArray ( new CategorizedProblem [ problems . size ( ) ] ) ) ; return ; } CategorizedProblem [ ] combined = new CategorizedProblem [ problems . size ( ) + oldProblems . length ] ; for ( int i = ; i < oldProblems . length ; i ++ ) { combined [ i ] = oldProblems [ i ] ; } int j = oldProblems . length ; for ( CategorizedProblem problem : problems ) { combined [ j ++ ] = problem ; } context . putProblems ( type , combined ) ; } } package org . rubypeople . rdt . core . compiler ; import java . util . HashMap ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . ReconcileWorkingCopyOperation ; import org . rubypeople . rdt . internal . core . RubyScript ; public class ReconcileContext { private ReconcileWorkingCopyOperation operation ; private RubyScript workingCopy ; public ReconcileContext ( ReconcileWorkingCopyOperation operation , RubyScript workingCopy ) { this . operation = operation ; this . workingCopy = workingCopy ; } public RootNode getAST ( ) throws RubyModelException { return this . operation . makeConsistent ( this . workingCopy , null ) ; } public IRubyElementDelta getDelta ( ) { return this . operation . deltaBuilder . delta ; } public CategorizedProblem [ ] getProblems ( String markerType ) { if ( this . operation . problems == null ) return null ; return ( CategorizedProblem [ ] ) this . operation . problems . get ( markerType ) ; } public IRubyScript getWorkingCopy ( ) { return this . workingCopy ; } public void resetAST ( ) { this . operation . ast = null ; putProblems ( IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER , null ) ; putProblems ( IRubyModelMarker . TASK_MARKER , null ) ; } public void putProblems ( String markerType , CategorizedProblem [ ] problems ) { if ( this . operation . problems == null ) this . operation . problems = new HashMap ( ) ; this . operation . problems . put ( markerType , problems ) ; } } package org . rubypeople . rdt . core . compiler ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public abstract class CategorizedProblem implements IProblem { public static final int CAT_UNSPECIFIED = ; public static final int CAT_BUILDPATH = ; public static final int CAT_SYNTAX = ; public static final int CAT_IMPORT = ; public static final int CAT_TYPE = ; public static final int CAT_MEMBER = ; public static final int CAT_INTERNAL = ; public static final int CAT_JAVADOC = ; public static final int CAT_CODE_STYLE = ; public static final int CAT_POTENTIAL_PROGRAMMING_PROBLEM = ; public static final int CAT_NAME_SHADOWING_CONFLICT = ; public static final int CAT_DEPRECATION = ; public static final int CAT_UNNECESSARY_CODE = ; public static final int CAT_UNCHECKED_RAW = ; public static final int CAT_NLS = ; public static final int CAT_RESTRICTION = ; public abstract String getMarkerType ( ) ; public String [ ] getExtraMarkerAttributeNames ( ) { return CharOperation . NO_STRINGS ; } public Object [ ] getExtraMarkerAttributeValues ( ) { return new Object [ ] { } ; } public boolean isTask ( ) { return false ; } public boolean isError ( ) { return false ; } public boolean isWarning ( ) { return false ; } } package org . rubypeople . rdt . core . compiler ; public interface IScanner { int TokenNameEOF = - ; int getCurrentTokenStartPosition ( ) ; int getCurrentTokenEndPosition ( ) ; int getNextToken ( ) throws InvalidInputException ; void setSource ( char [ ] source ) ; } package org . rubypeople . rdt . core ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IRubyProject extends IRubyElement , IParent , IOpenable { public abstract IProject getProject ( ) ; public String [ ] getRequiredProjectNames ( ) throws RubyModelException ; public ILoadpathEntry [ ] readRawLoadpath ( ) ; IType findType ( String fullyQualifiedName ) throws RubyModelException ; String getOption ( String optionName , boolean inheritRubyCoreOptions ) ; Map getOptions ( boolean inheritRubyCoreOptions ) ; ISourceFolderRoot [ ] getAllSourceFolderRoots ( ) throws RubyModelException ; public abstract Object [ ] getNonRubyResources ( ) throws RubyModelException ; public abstract ISourceFolder [ ] getSourceFolders ( ) throws RubyModelException ; public abstract ISourceFolderRoot getSourceFolderRoot ( IResource resource ) ; public abstract ILoadpathEntry [ ] getRawLoadpath ( ) throws RubyModelException ; public abstract ISourceFolderRoot [ ] getSourceFolderRoots ( ) throws RubyModelException ; public abstract boolean isOnLoadpath ( IRubyElement element ) ; ILoadpathEntry [ ] getResolvedLoadpath ( boolean ignoreUnresolvedEntry ) throws RubyModelException ; public void setRawLoadpath ( ILoadpathEntry [ ] newEntries , IPath newOutputLocation , IProgressMonitor monitor , boolean canChangeResource , ILoadpathEntry [ ] oldResolvedPath , boolean needValidation , boolean needSave ) throws RubyModelException ; void setRawLoadpath ( ILoadpathEntry [ ] entries , boolean canModifyResources , IProgressMonitor monitor ) throws RubyModelException ; void setRawLoadpath ( ILoadpathEntry [ ] entries , IProgressMonitor monitor ) throws RubyModelException ; void setRawLoadpath ( ILoadpathEntry [ ] entries , IPath outputLocation , IProgressMonitor monitor ) throws RubyModelException ; public abstract ISourceFolderRoot getSourceFolderRoot ( String rootPath ) ; public abstract ISourceFolderRoot findSourceFolderRoot ( IPath path ) throws RubyModelException ; ISourceFolderRoot [ ] findSourceFolderRoots ( ILoadpathEntry entry ) ; IType findType ( String fullyQualifiedName , IProgressMonitor progressMonitor ) throws RubyModelException ; ITypeHierarchy newTypeHierarchy ( IRegion region , IProgressMonitor monitor ) throws RubyModelException ; boolean isOnLoadpath ( IResource resource ) ; } package org . rubypeople . rdt . core ; public interface ISourceReference { ISourceRange getSourceRange ( ) throws RubyModelException ; String getSource ( ) throws RubyModelException ; } package org . rubypeople . rdt . core ; public class Flags { public static final int AccPublic = ; public static final int AccPrivate = ; public static final int AccProtected = ; public static final int AccStatic = ; public static final int AccDefault = ; public static final int AccModule = ; public static boolean isPrivate ( int flags ) { return ( flags & AccPrivate ) != ; } public static boolean isProtected ( int flags ) { return ( flags & AccProtected ) != ; } public static boolean isPublic ( int flags ) { return ( flags & AccPublic ) != ; } public static boolean isStatic ( int flags ) { return ( flags & AccStatic ) != ; } public static boolean isModule ( int flags ) { return ( flags & AccModule ) != ; } } package org . rubypeople . rdt . core ; import org . rubypeople . rdt . core . compiler . IProblem ; public interface IProblemRequestor { void acceptProblem ( IProblem problem ) ; void beginReporting ( ) ; void endReporting ( ) ; boolean isActive ( ) ; } package org . rubypeople . rdt . core ; public interface ITypeHierarchyChangedListener { void typeHierarchyChanged ( ITypeHierarchy typeHierarchy ) ; } package org . rubypeople . rdt . core ; public interface ISourceRange { int getOffset ( ) ; int getLength ( ) ; } package org . rubypeople . rdt . core ; public class CompletionProposal { public static final int GLOBAL_REF = ; public static final int CONSTANT_REF = ; public static final int KEYWORD = ; public static final int INSTANCE_VARIABLE_REF = ; public static final int LOCAL_VARIABLE_REF = ; public static final int METHOD_REF = ; public static final int METHOD_DECLARATION = ; public static final int CLASS_VARIABLE_REF = ; public static final int TYPE_REF = ; public static final int VARIABLE_DECLARATION = ; public static final int POTENTIAL_METHOD_DECLARATION = ; public static final int METHOD_NAME_REFERENCE = ; protected static final int FIRST_KIND = GLOBAL_REF ; protected static final int LAST_KIND = METHOD_NAME_REFERENCE ; private int completionKind ; private int completionLocation ; private int tokenStart = ; private int tokenEnd = ; private String completion = "" ; private int replaceStart = ; private int replaceEnd = ; private int relevance = ; private String [ ] parameterNames = null ; private boolean parameterNamesComputed = false ; private String name = null ; private int flags ; private String type ; private String declaringType ; private IRubyElement element ; private boolean blockNamesComputed ; private String [ ] blockNames ; public CompletionProposal ( int kind , String completion , int relevance ) { this . completionKind = kind ; this . completion = completion ; this . relevance = relevance ; } public int getKind ( ) { return completionKind ; } public String getCompletion ( ) { return completion ; } public int getReplaceStart ( ) { return replaceStart ; } public int getReplaceEnd ( ) { return replaceEnd ; } public int getCompletionLocation ( ) { return completionLocation ; } public int getRelevance ( ) { return relevance ; } public String getName ( ) { return name ; } public int getFlags ( ) { return this . flags ; } public void setFlags ( int flags ) { this . flags = flags ; } public void setReplaceRange ( int startIndex , int endIndex ) { if ( startIndex < || endIndex < startIndex ) { throw new IllegalArgumentException ( ) ; } this . replaceStart = startIndex ; this . replaceEnd = endIndex ; } public String [ ] getParameterNames ( ) { if ( ! parameterNamesComputed ) { if ( getElement ( ) != null && getElement ( ) . isType ( IRubyElement . METHOD ) ) { IMethod method = ( IMethod ) getElement ( ) ; try { parameterNames = method . getParameterNames ( ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } parameterNamesComputed = true ; } return parameterNames ; } public String getType ( ) { if ( type != null ) return type ; return "" ; } public String getDeclaringType ( ) { if ( declaringType != null ) return declaringType ; return "" ; } public void setType ( String name ) { this . type = name ; } public void setDeclaringType ( String elementName ) { this . declaringType = elementName ; } public void setName ( String newName ) { this . name = newName ; } public void setElement ( IRubyElement element ) { this . element = element ; } public IRubyElement getElement ( ) { return element ; } public String [ ] getBlockVars ( ) { if ( ! blockNamesComputed ) { if ( getElement ( ) . isType ( IRubyElement . METHOD ) ) { IMethod method = ( IMethod ) getElement ( ) ; try { blockNames = method . getBlockParameters ( ) ; } catch ( RubyModelException e ) { RubyCore . log ( e ) ; } } blockNamesComputed = true ; } return blockNames ; } @ Override public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( name ) ; if ( element != null ) { buffer . append ( "" ) ; buffer . append ( element . toString ( ) ) ; buffer . append ( "" ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . core ; import org . rubypeople . rdt . internal . core . DefaultWorkingCopyOwner ; import org . rubypeople . rdt . internal . core . buffer . BufferManager ; public abstract class WorkingCopyOwner { public static void setPrimaryBufferProvider ( WorkingCopyOwner primaryBufferProvider ) { DefaultWorkingCopyOwner . PRIMARY . primaryBufferProvider = primaryBufferProvider ; } public IBuffer createBuffer ( IRubyScript workingCopy ) { return BufferManager . getDefaultBufferManager ( ) . createBuffer ( workingCopy ) ; } } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IOpenable { public void close ( ) throws RubyModelException ; public IBuffer getBuffer ( ) throws RubyModelException ; boolean hasUnsavedChanges ( ) throws RubyModelException ; boolean isConsistent ( ) throws RubyModelException ; boolean isOpen ( ) ; void makeConsistent ( IProgressMonitor progress ) throws RubyModelException ; public void open ( IProgressMonitor progress ) throws RubyModelException ; public void save ( IProgressMonitor progress , boolean force ) throws RubyModelException ; public String findRecommendedLineSeparator ( ) throws RubyModelException ; } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ISourceFolder extends IRubyElement , IParent , IOpenable { public static final String DEFAULT_PACKAGE_NAME = "" ; boolean containsRubyResources ( ) throws RubyModelException ; IRubyScript createRubyScript ( String name , String contents , boolean force , IProgressMonitor monitor ) throws RubyModelException ; IRubyScript [ ] getRubyScripts ( ) throws RubyModelException ; IRubyScript [ ] getRubyScripts ( WorkingCopyOwner owner ) throws RubyModelException ; String getElementName ( ) ; Object [ ] getNonRubyResources ( ) throws RubyModelException ; IRubyScript getRubyScript ( String name ) ; boolean isDefaultPackage ( ) ; boolean hasSubfolders ( ) throws RubyModelException ; } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IType extends IRubyElement , IMember { public IMethod getMethod ( String name , String [ ] parameterNames ) ; IMethod [ ] getMethods ( ) throws RubyModelException ; boolean isClass ( ) ; String getFullyQualifiedName ( ) ; boolean isModule ( ) ; IType getType ( String name ) ; public IField getField ( String string ) ; IField [ ] getFields ( ) throws RubyModelException ; String getSuperclassName ( ) throws RubyModelException ; String [ ] getIncludedModuleNames ( ) throws RubyModelException ; public boolean isMember ( ) throws RubyModelException ; public IMethod createMethod ( String contents , IRubyElement sibling , boolean force , IProgressMonitor progress ) throws RubyModelException ; public ISourceFolder getSourceFolder ( ) ; public String getTypeQualifiedName ( String string ) ; IType [ ] getTypes ( ) throws RubyModelException ; ITypeHierarchy newSupertypeHierarchy ( IProgressMonitor monitor ) throws RubyModelException ; ITypeHierarchy newTypeHierarchy ( IProgressMonitor monitor ) throws RubyModelException ; ITypeHierarchy newTypeHierarchy ( WorkingCopyOwner owner , IProgressMonitor monitor ) throws RubyModelException ; public IMethod [ ] findMethods ( IMethod method ) ; } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; public interface IRubyModelStatus extends IStatus { IRubyElement [ ] getElements ( ) ; IPath getPath ( ) ; String getString ( ) ; boolean isDoesNotExist ( ) ; } package org . rubypeople . rdt . core ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . internal . core . LoadpathEntry ; import org . rubypeople . rdt . internal . core . RubyModelStatus ; import org . rubypeople . rdt . internal . core . util . Messages ; public class RubyConventions { public static IStatus validateRubyScriptName ( String name ) { if ( name == null ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , Messages . bind ( Messages . convention_unit_nullName ) , null ) ; } if ( ! org . rubypeople . rdt . internal . core . util . Util . isRubyLikeFileName ( name ) ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , Messages . bind ( Messages . convention_unit_notRubyName ) , null ) ; } IStatus status = ResourcesPlugin . getWorkspace ( ) . validateName ( name , IResource . FILE ) ; if ( ! status . isOK ( ) ) { return status ; } return RubyModelStatus . VERIFIED_OK ; } public static IStatus validateIdentifier ( String id ) { return RubyModelStatus . VERIFIED_OK ; } public static IStatus validateRubyTypeName ( String typeName ) { if ( typeName == null ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , Messages . convention_type_nullName , null ) ; } if ( typeName . length ( ) == ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , Messages . bind ( Messages . convention_type_invalidName , typeName ) , null ) ; } if ( ! isConstant ( typeName ) ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , "" , null ) ; } return RubyModelStatus . VERIFIED_OK ; } public static IStatus validateConstant ( String constantName ) { if ( constantName == null ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , Messages . convention_type_nullName , null ) ; } if ( constantName . length ( ) == ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , Messages . bind ( Messages . convention_type_invalidName , constantName ) , null ) ; } if ( ! isConstant ( constantName ) ) { return new Status ( IStatus . ERROR , RubyCore . PLUGIN_ID , - , "" , null ) ; } return RubyModelStatus . VERIFIED_OK ; } private static boolean isConstant ( String className ) { if ( className == null || className . length ( ) == ) return false ; if ( ! Character . isLowerCase ( className . charAt ( ) ) && ! Character . isLetter ( className . charAt ( ) ) ) return false ; int namespaceDelimeterIndex = className . indexOf ( "" ) ; if ( namespaceDelimeterIndex != - ) { return isConstant ( className . substring ( , namespaceDelimeterIndex ) ) && isConstant ( className . substring ( namespaceDelimeterIndex + ) ) ; } for ( int i = ; i < className . length ( ) ; i ++ ) { char c = className . charAt ( i ) ; if ( ! Character . isLetterOrDigit ( c ) && c != '' ) return false ; } return true ; } public static IStatus validateSourceFolderName ( String packName ) { return RubyModelStatus . VERIFIED_OK ; } public static IRubyModelStatus validateLoadpath ( IRubyProject rubyProject , ILoadpathEntry [ ] rawCLoadpath , IPath projectOutputLocation ) { return LoadpathEntry . validateLoadpath ( rubyProject , rawCLoadpath , projectOutputLocation ) ; } public static IStatus validateMethodName ( String methodName ) { return validateIdentifier ( methodName ) ; } public static boolean isRubyIdentifierPart ( char c ) { return isStrictRubyIdentifierPart ( c ) || c == '' || c == '' || c == '' || c == '' || c == '' ; } private static boolean isStrictRubyIdentifierPart ( char c ) { return Character . isLetterOrDigit ( c ) || c == '' ; } } package org . rubypeople . rdt . core ; import java . util . Map ; import org . rubypeople . rdt . core . compiler . IScanner ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . rubypeople . rdt . internal . core . util . PublicScanner ; import org . rubypeople . rdt . internal . formatter . OldCodeFormatter ; public class ToolFactory { public static CodeFormatter createCodeFormatter ( Map options ) { if ( options == null ) options = RubyCore . getOptions ( ) ; return new OldCodeFormatter ( options ) ; } public static IScanner createScanner ( boolean b , boolean c , boolean d , boolean e ) { return new PublicScanner ( ) ; } } package org . rubypeople . rdt . core ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . URL ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Hashtable ; import java . util . List ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IResourceProxy ; import org . eclipse . core . resources . IResourceProxyVisitor ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . osgi . framework . Bundle ; import org . osgi . framework . BundleContext ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . core . search . TypeNameRequestor ; import org . rubypeople . rdt . internal . core . BatchOperation ; import org . rubypeople . rdt . internal . core . DefaultWorkingCopyOwner ; import org . rubypeople . rdt . internal . core . LoadpathAttribute ; import org . rubypeople . rdt . internal . core . LoadpathEntry ; import org . rubypeople . rdt . internal . core . Region ; import org . rubypeople . rdt . internal . core . RubyCorePreferenceInitializer ; import org . rubypeople . rdt . internal . core . RubyModel ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . SetExecutableBits ; import org . rubypeople . rdt . internal . core . SetLoadpathOperation ; import org . rubypeople . rdt . internal . core . util . MementoTokenizer ; import org . rubypeople . rdt . internal . core . util . Messages ; import org . rubypeople . rdt . internal . core . util . Util ; import org . rubypeople . rdt . internal . ti . DataFlowTypeInferrer ; import org . rubypeople . rdt . internal . ti . ITypeInferrer ; public class RubyCore extends Plugin { private static RubyCore RUBY_CORE_PLUGIN = null ; public final static String PLUGIN_ID = "" ; public final static String NATURE_ID = PLUGIN_ID + "" ; public static final IEclipsePreferences [ ] preferencesLookup = new IEclipsePreferences [ ] ; static final int PREF_INSTANCE = ; static final int PREF_DEFAULT = ; public static final String DEFAULT_TASK_TAGS = "" ; public static final String BUILDER_ID = PLUGIN_ID + "" ; public static final String DEFAULT_TASK_PRIORITIES = "" ; public static final String COMPILER_TASK_PRIORITIES = PLUGIN_ID + "" ; public static final String COMPILER_TASK_PRIORITY_HIGH = "" ; public static final String COMPILER_TASK_PRIORITY_LOW = "" ; public static final String COMPILER_TASK_PRIORITY_NORMAL = "" ; public static final String COMPILER_TASK_TAGS = PLUGIN_ID + "" ; public static final String COMPILER_TASK_CASE_SENSITIVE = PLUGIN_ID + "" ; public static final String ENABLED = "" ; public static final String DISABLED = "" ; public static final String ERROR = "" ; public static final String WARNING = "" ; public static final String IGNORE = "" ; public static final String TAB = "" ; public static final String SPACE = "" ; public static final String CORE_ENCODING = PLUGIN_ID + "" ; public static final String INSERT = "" ; public static final String DO_NOT_INSERT = "" ; public static final String RUBY_SOURCE_CONTENT_TYPE = RubyCore . PLUGIN_ID + "" ; public static final String COMPILER_PB_EMPTY_STATEMENT = PLUGIN_ID + "" ; public static final String COMPILER_PB_CONSTANT_REASSIGNMENT = PLUGIN_ID + "" ; public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID + "" ; public static final String COMPILER_PB_REDEFINITION_CORE_CLASS_METHOD = PLUGIN_ID + "" ; public static final String COMPILER_PB_RUBY_19_WHEN_STATEMENTS = PLUGIN_ID + "" ; public static final String COMPILER_PB_RUBY_19_HASH_COMMA_SYTNAX = PLUGIN_ID + "" ; public static final String CODEASSIST_CAMEL_CASE_MATCH = PLUGIN_ID + "" ; public static final String CORE_INCOMPLETE_CLASSPATH = PLUGIN_ID + "" ; public static final String CORE_INCOMPATIBLE_JDK_LEVEL = PLUGIN_ID + "" ; public static final String CORE_CIRCULAR_CLASSPATH = PLUGIN_ID + "" ; public static final String USER_LIBRARY_CONTAINER_ID = "" ; private static final boolean VERBOSE = false ; private RubyProjectListener fProjectListener ; public RubyCore ( ) { super ( ) ; } public static RubyCore getPlugin ( ) { return RUBY_CORE_PLUGIN ; } public static IWorkspace getWorkspace ( ) { return ResourcesPlugin . getWorkspace ( ) ; } public void start ( BundleContext context ) throws Exception { RUBY_CORE_PLUGIN = this ; super . start ( context ) ; fProjectListener = new RubyProjectListener ( ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( fProjectListener , IResourceChangeEvent . POST_CHANGE ) ; RubyModelManager . getRubyModelManager ( ) . startup ( ) ; new SetExecutableBits ( ) . schedule ( ) ; } public void stop ( BundleContext context ) throws Exception { try { ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( fProjectListener ) ; RubyModelManager . getRubyModelManager ( ) . shutdown ( ) ; } finally { super . stop ( context ) ; } } public static void trace ( String message ) { if ( getPlugin ( ) . isDebugging ( ) ) System . out . println ( message ) ; } public static void log ( Exception e ) { String msg = e . getMessage ( ) ; if ( msg == null ) msg = "" ; log ( Status . ERROR , msg , e ) ; } public static void log ( String string ) { log ( IStatus . INFO , string ) ; } public static void log ( int severity , String string ) { log ( severity , string , null ) ; } public static void log ( int severity , String string , Throwable e ) { getPlugin ( ) . getLog ( ) . log ( new Status ( severity , PLUGIN_ID , IStatus . OK , string , e ) ) ; if ( severity == Status . ERROR ) { } if ( VERBOSE ) { System . out . println ( string ) ; if ( e != null ) e . printStackTrace ( ) ; } } public static String getOSDirectory ( Plugin plugin ) { final Bundle bundle = plugin . getBundle ( ) ; String location = bundle . getLocation ( ) ; int prefixLength = location . indexOf ( '' ) ; if ( prefixLength == - ) { throw new RuntimeException ( "" + location ) ; } String pluginDir = location . substring ( prefixLength + ) ; File pluginDirFile = new File ( pluginDir ) ; if ( ! pluginDirFile . exists ( ) ) { String installArea = System . getProperty ( "" ) ; if ( installArea . startsWith ( "" ) ) { installArea = installArea . substring ( "" . length ( ) ) ; } File installFile = new File ( new Path ( installArea ) . toOSString ( ) ) ; pluginDirFile = new File ( installFile , pluginDir ) ; if ( ! pluginDirFile . exists ( ) ) throw new RuntimeException ( "" + pluginDirFile + "" + plugin . getClass ( ) ) ; } return pluginDirFile . getAbsolutePath ( ) + "" ; } public static IProject [ ] getRubyProjects ( ) { List < IProject > rubyProjectsList = new ArrayList < IProject > ( ) ; IProject [ ] workspaceProjects = RubyCore . getWorkspace ( ) . getRoot ( ) . getProjects ( ) ; for ( int i = ; i < workspaceProjects . length ; i ++ ) { IProject iProject = workspaceProjects [ i ] ; if ( isRubyProject ( iProject ) ) rubyProjectsList . add ( iProject ) ; } IProject [ ] rubyProjects = new IProject [ rubyProjectsList . size ( ) ] ; return rubyProjectsList . toArray ( rubyProjects ) ; } public static boolean isRubyProject ( IProject aProject ) { try { return aProject . hasNature ( RubyCore . NATURE_ID ) ; } catch ( CoreException e ) { } return false ; } public static IRubyScript create ( IFile file ) { return RubyModelManager . create ( file , null ) ; } public static IRubyProject create ( IProject project ) { if ( project == null ) { return null ; } RubyModel rubyModel = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; return rubyModel . getRubyProject ( project ) ; } public static void addRubyNature ( IProject project , IProgressMonitor monitor ) throws CoreException { if ( ! project . hasNature ( RubyCore . NATURE_ID ) ) { IProjectDescription description = project . getDescription ( ) ; String [ ] prevNatures = description . getNatureIds ( ) ; String [ ] newNatures = new String [ prevNatures . length + ] ; System . arraycopy ( prevNatures , , newNatures , , prevNatures . length ) ; newNatures [ prevNatures . length ] = RubyCore . NATURE_ID ; description . setNatureIds ( newNatures ) ; project . setDescription ( description , monitor ) ; } } public static IRubyElement create ( IResource resource ) { return RubyModelManager . create ( resource , null ) ; } public static IRubyModel create ( IWorkspaceRoot root ) { if ( root == null ) { return null ; } return RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; } public static void run ( IWorkspaceRunnable action , ISchedulingRule rule , IProgressMonitor monitor ) throws CoreException { IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; if ( workspace . isTreeLocked ( ) ) { new BatchOperation ( action ) . run ( monitor ) ; } else { workspace . run ( new BatchOperation ( action ) , rule , IWorkspace . AVOID_UPDATE , monitor ) ; } } public static String getOption ( String optionName ) { return RubyModelManager . getRubyModelManager ( ) . getOption ( optionName ) ; } public static String getEncoding ( ) { IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; if ( workspace != null ) { try { return workspace . getRoot ( ) . getDefaultCharset ( ) ; } catch ( CoreException e ) { } } return ResourcesPlugin . getEncoding ( ) ; } public static ITypeInferrer getTypeInferrer ( ) { return new DataFlowTypeInferrer ( ) ; } public static Hashtable < String , String > getOptions ( ) { return RubyModelManager . getRubyModelManager ( ) . getOptions ( ) ; } public static void addElementChangedListener ( IElementChangedListener listener ) { addElementChangedListener ( listener , ElementChangedEvent . POST_CHANGE | ElementChangedEvent . POST_RECONCILE ) ; } public static void addElementChangedListener ( IElementChangedListener listener , int eventMask ) { RubyModelManager . getRubyModelManager ( ) . deltaState . addElementChangedListener ( listener , eventMask ) ; } public static void removeElementChangedListener ( IElementChangedListener listener ) { RubyModelManager . getRubyModelManager ( ) . deltaState . removeElementChangedListener ( listener ) ; } public static RubyCore getRubyCore ( ) { return getPlugin ( ) ; } public static boolean isRubyLikeFileName ( String name ) { return Util . isRubyLikeFileName ( name ) ; } public static ILoadpathEntry newSourceEntry ( IPath path ) { return newSourceEntry ( path , LoadpathEntry . INCLUDE_ALL , LoadpathEntry . EXCLUDE_NONE , LoadpathEntry . NO_EXTRA_ATTRIBUTES ) ; } public static ILoadpathEntry newSourceEntry ( IPath path , IPath [ ] inclusionPatterns , IPath [ ] exclusionPatterns , ILoadpathAttribute [ ] extraAttributes ) { if ( path == null ) Assert . isTrue ( false , "" ) ; if ( ! path . isAbsolute ( ) ) Assert . isTrue ( false , "" ) ; if ( exclusionPatterns == null ) Assert . isTrue ( false , "" ) ; if ( inclusionPatterns == null ) Assert . isTrue ( false , "" ) ; return new LoadpathEntry ( ILoadpathEntry . CPE_SOURCE , path , inclusionPatterns , exclusionPatterns , extraAttributes , false ) ; } public static ILoadpathEntry newLibraryEntry ( IPath path , ILoadpathAttribute [ ] extraAttributes , boolean isExported ) { if ( path == null ) Assert . isTrue ( false , "" ) ; if ( ! path . isAbsolute ( ) ) Assert . isTrue ( false , "" ) ; return new LoadpathEntry ( ILoadpathEntry . CPE_LIBRARY , RubyProject . canonicalizedPath ( path ) , LoadpathEntry . INCLUDE_ALL , LoadpathEntry . EXCLUDE_NONE , extraAttributes , isExported ) ; } public static ILoadpathEntry newProjectEntry ( IPath path , ILoadpathAttribute [ ] extraAttributes , boolean isExported ) { if ( ! path . isAbsolute ( ) ) Assert . isTrue ( false , "" ) ; return new LoadpathEntry ( ILoadpathEntry . CPE_PROJECT , path , LoadpathEntry . INCLUDE_ALL , LoadpathEntry . EXCLUDE_NONE , extraAttributes , isExported ) ; } public static ILoadpathEntry newVariableEntry ( IPath variablePath , ILoadpathAttribute [ ] extraAttributes , boolean isExported ) { if ( variablePath == null ) Assert . isTrue ( false , "" ) ; if ( variablePath . segmentCount ( ) < ) { Assert . isTrue ( false , "" + variablePath . makeRelative ( ) . toString ( ) + "" ) ; } return new LoadpathEntry ( ILoadpathEntry . CPE_VARIABLE , variablePath , LoadpathEntry . INCLUDE_ALL , LoadpathEntry . EXCLUDE_NONE , extraAttributes , isExported ) ; } public static ILoadpathEntry newContainerEntry ( IPath containerPath , ILoadpathAttribute [ ] extraAttributes , boolean isExported ) { if ( containerPath == null ) { Assert . isTrue ( false , "" ) ; } else if ( containerPath . segmentCount ( ) < ) { Assert . isTrue ( false , "" + containerPath . makeRelative ( ) . toString ( ) + "" ) ; } return new LoadpathEntry ( ILoadpathEntry . CPE_CONTAINER , containerPath , LoadpathEntry . INCLUDE_ALL , LoadpathEntry . EXCLUDE_NONE , extraAttributes , isExported ) ; } public static ILoadpathEntry getResolvedLoadpathEntry ( ILoadpathEntry entry ) { if ( entry . getEntryKind ( ) != ILoadpathEntry . CPE_VARIABLE ) return entry ; IPath resolvedPath = RubyCore . getResolvedVariablePath ( entry . getPath ( ) ) ; if ( resolvedPath == null ) return null ; Object target = RubyModel . getTarget ( resolvedPath , false ) ; if ( target == null ) return null ; if ( target instanceof IResource ) { IResource resolvedResource = ( IResource ) target ; if ( resolvedResource != null ) { switch ( resolvedResource . getType ( ) ) { case IResource . PROJECT : return RubyCore . newProjectEntry ( resolvedPath , entry . getExtraAttributes ( ) , entry . isExported ( ) ) ; case IResource . FOLDER : return RubyCore . newLibraryEntry ( resolvedPath , entry . getExtraAttributes ( ) , entry . isExported ( ) ) ; } } } if ( target instanceof File ) { File externalFile = RubyModel . getFolder ( target ) ; if ( externalFile != null ) { return RubyCore . newLibraryEntry ( resolvedPath , entry . getExtraAttributes ( ) , entry . isExported ( ) ) ; } else { if ( resolvedPath . isAbsolute ( ) ) { return RubyCore . newLibraryEntry ( resolvedPath , entry . getExtraAttributes ( ) , entry . isExported ( ) ) ; } } } return null ; } public static IPath getResolvedVariablePath ( IPath variablePath ) { if ( variablePath == null ) return null ; int count = variablePath . segmentCount ( ) ; if ( count == ) return null ; String variableName = variablePath . segment ( ) ; IPath [ ] resolvedPaths = RubyCore . getLoadpathVariable ( variableName ) ; if ( resolvedPaths == null ) { return null ; } if ( count > ) { for ( int i = ; i < resolvedPaths . length ; i ++ ) { resolvedPaths [ i ] = resolvedPaths [ i ] . append ( variablePath . removeFirstSegments ( ) ) ; } } IPath resolvedPath = null ; Object target = null ; for ( int i = ; i < resolvedPaths . length ; i ++ ) { target = RubyModel . getTarget ( resolvedPaths [ i ] , false ) ; if ( target instanceof File ) { File targetFile = ( File ) target ; if ( ! targetFile . exists ( ) ) { target = null ; } } if ( target != null ) { resolvedPath = resolvedPaths [ i ] ; break ; } } if ( target == null ) { return null ; } return resolvedPath ; } public static IPath [ ] getLoadpathVariable ( final String variableName ) { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; IPath [ ] variablePath = manager . variableGet ( variableName ) ; if ( variablePath == RubyModelManager . VARIABLE_INITIALIZATION_IN_PROGRESS ) { return manager . getPreviousSessionVariable ( variableName ) ; } if ( variablePath != null ) { if ( variablePath == RubyModelManager . CP_ENTRY_IGNORE_PATH ) return null ; return variablePath ; } final LoadpathVariableInitializer initializer = RubyCore . getLoadpathVariableInitializer ( variableName ) ; if ( initializer != null ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + variableName + '' + "" + initializer + '' + "" ) ; new Exception ( "" ) . printStackTrace ( System . out ) ; } manager . variablePut ( variableName , RubyModelManager . VARIABLE_INITIALIZATION_IN_PROGRESS ) ; boolean ok = false ; try { initializer . initialize ( variableName ) ; variablePath = manager . variableGet ( variableName ) ; if ( variablePath == RubyModelManager . VARIABLE_INITIALIZATION_IN_PROGRESS ) return null ; if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + variableName + '' + "" + variablePath ) ; } manager . variablesWithInitializer . add ( variableName ) ; ok = true ; } catch ( RuntimeException e ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { e . printStackTrace ( ) ; } throw e ; } catch ( Error e ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { e . printStackTrace ( ) ; } throw e ; } finally { if ( ! ok ) RubyModelManager . getRubyModelManager ( ) . variablePut ( variableName , null ) ; } } else { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + variableName ) ; } } return variablePath ; } public static LoadpathVariableInitializer getLoadpathVariableInitializer ( String variable ) { Plugin jdtCorePlugin = RubyCore . getPlugin ( ) ; if ( jdtCorePlugin == null ) return null ; IExtensionPoint extension = Platform . getExtensionRegistry ( ) . getExtensionPoint ( RubyCore . PLUGIN_ID , RubyModelManager . CPVARIABLE_INITIALIZER_EXTPOINT_ID ) ; if ( extension != null ) { IExtension [ ] extensions = extension . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] configElements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < configElements . length ; j ++ ) { try { String varAttribute = configElements [ j ] . getAttribute ( "" ) ; if ( variable . equals ( varAttribute ) ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + variable + '' + "" + configElements [ j ] . getAttribute ( "" ) ) ; } Object execExt = configElements [ j ] . createExecutableExtension ( "" ) ; if ( execExt instanceof LoadpathVariableInitializer ) { return ( LoadpathVariableInitializer ) execExt ; } } } catch ( CoreException e ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + variable + '' + "" + configElements [ j ] . getAttribute ( "" ) , System . err ) ; e . printStackTrace ( ) ; } } } } } return null ; } public static ILoadpathContainer getLoadpathContainer ( IPath containerPath , IRubyProject project ) throws RubyModelException { RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; ILoadpathContainer container = manager . getLoadpathContainer ( containerPath , project ) ; if ( container == RubyModelManager . CONTAINER_INITIALIZATION_IN_PROGRESS ) { return manager . getPreviousSessionContainer ( containerPath , project ) ; } return container ; } public static LoadpathContainerInitializer getLoadpathContainerInitializer ( String containerID ) { HashMap < String , LoadpathContainerInitializer > containerInitializersCache = RubyModelManager . getRubyModelManager ( ) . containerInitializersCache ; LoadpathContainerInitializer initializer = ( LoadpathContainerInitializer ) containerInitializersCache . get ( containerID ) ; if ( initializer == null ) { initializer = computeLoadpathContainerInitializer ( containerID ) ; if ( initializer == null ) return null ; containerInitializersCache . put ( containerID , initializer ) ; } return initializer ; } private static LoadpathContainerInitializer computeLoadpathContainerInitializer ( String containerID ) { Plugin jdtCorePlugin = RubyCore . getPlugin ( ) ; if ( jdtCorePlugin == null ) return null ; IExtensionPoint extension = Platform . getExtensionRegistry ( ) . getExtensionPoint ( RubyCore . PLUGIN_ID , RubyModelManager . CPCONTAINER_INITIALIZER_EXTPOINT_ID ) ; if ( extension != null ) { IExtension [ ] extensions = extension . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] configElements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < configElements . length ; j ++ ) { String initializerID = configElements [ j ] . getAttribute ( "" ) ; if ( initializerID != null && initializerID . equals ( containerID ) ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + containerID + '' + "" + configElements [ j ] . getAttribute ( "" ) ) ; } try { Object execExt = configElements [ j ] . createExecutableExtension ( "" ) ; if ( execExt instanceof LoadpathContainerInitializer ) { return ( LoadpathContainerInitializer ) execExt ; } } catch ( CoreException e ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + containerID + '' + "" + configElements [ j ] . getAttribute ( "" ) , System . err ) ; e . printStackTrace ( ) ; } } } } } } return null ; } public static void setLoadpathContainer ( final IPath containerPath , IRubyProject [ ] affectedProjects , ILoadpathContainer [ ] respectiveContainers , IProgressMonitor monitor ) throws RubyModelException { if ( affectedProjects . length != respectiveContainers . length ) Assert . isTrue ( false , "" ) ; if ( monitor != null && monitor . isCanceled ( ) ) return ; if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + containerPath + '' + "" + org . rubypeople . rdt . core . util . Util . toString ( affectedProjects , new org . rubypeople . rdt . core . util . Util . Displayable ( ) { public String displayString ( Object o ) { return ( ( IRubyProject ) o ) . getElementName ( ) ; } } ) + "" + org . rubypeople . rdt . core . util . Util . toString ( respectiveContainers , new org . rubypeople . rdt . core . util . Util . Displayable ( ) { public String displayString ( Object o ) { StringBuffer buffer = new StringBuffer ( "" ) ; if ( o == null ) { buffer . append ( "" ) ; return buffer . toString ( ) ; } ILoadpathContainer container = ( ILoadpathContainer ) o ; buffer . append ( container . getDescription ( ) ) ; buffer . append ( "" ) ; ILoadpathEntry [ ] entries = container . getLoadpathEntries ( ) ; if ( entries != null ) { for ( int i = ; i < entries . length ; i ++ ) { buffer . append ( "" ) ; buffer . append ( entries [ i ] ) ; buffer . append ( '' ) ; } } buffer . append ( "" ) ; return buffer . toString ( ) ; } } ) + "" ) ; new Exception ( "" ) . printStackTrace ( System . out ) ; } RubyModelManager manager = RubyModelManager . getRubyModelManager ( ) ; if ( manager . containerPutIfInitializingWithSameEntries ( containerPath , affectedProjects , respectiveContainers ) ) return ; final int projectLength = affectedProjects . length ; final IRubyProject [ ] modifiedProjects ; System . arraycopy ( affectedProjects , , modifiedProjects = new IRubyProject [ projectLength ] , , projectLength ) ; final ILoadpathEntry [ ] [ ] oldResolvedPaths = new ILoadpathEntry [ projectLength ] [ ] ; int remaining = ; for ( int i = ; i < projectLength ; i ++ ) { if ( monitor != null && monitor . isCanceled ( ) ) return ; RubyProject affectedProject = ( RubyProject ) affectedProjects [ i ] ; ILoadpathContainer newContainer = respectiveContainers [ i ] ; if ( newContainer == null ) newContainer = RubyModelManager . CONTAINER_INITIALIZATION_IN_PROGRESS ; boolean found = false ; if ( RubyProject . hasRubyNature ( affectedProject . getProject ( ) ) ) { ILoadpathEntry [ ] rawClasspath = affectedProject . getRawLoadpath ( ) ; for ( int j = , cpLength = rawClasspath . length ; j < cpLength ; j ++ ) { ILoadpathEntry entry = rawClasspath [ j ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER && entry . getPath ( ) . equals ( containerPath ) ) { found = true ; break ; } } } if ( ! found ) { modifiedProjects [ i ] = null ; manager . containerPut ( affectedProject , containerPath , newContainer ) ; continue ; } ILoadpathContainer oldContainer = manager . containerGet ( affectedProject , containerPath ) ; if ( oldContainer == RubyModelManager . CONTAINER_INITIALIZATION_IN_PROGRESS ) { oldContainer = null ; } if ( oldContainer != null && oldContainer . equals ( respectiveContainers [ i ] ) ) { modifiedProjects [ i ] = null ; continue ; } remaining ++ ; oldResolvedPaths [ i ] = affectedProject . getResolvedLoadpath ( true , false , false ) ; manager . containerPut ( affectedProject , containerPath , newContainer ) ; } if ( remaining == ) return ; try { final boolean canChangeResources = ! ResourcesPlugin . getWorkspace ( ) . isTreeLocked ( ) ; RubyCore . run ( new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor progressMonitor ) throws CoreException { for ( int i = ; i < projectLength ; i ++ ) { if ( progressMonitor != null && progressMonitor . isCanceled ( ) ) return ; RubyProject affectedProject = ( RubyProject ) modifiedProjects [ i ] ; if ( affectedProject == null ) continue ; if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + affectedProject . getElementName ( ) + '' + "" + containerPath ) ; } affectedProject . setRawLoadpath ( affectedProject . getRawLoadpath ( ) , SetLoadpathOperation . DO_NOT_SET_OUTPUT , progressMonitor , canChangeResources , oldResolvedPaths [ i ] , false , false ) ; } } } , null , monitor ) ; } catch ( CoreException e ) { if ( RubyModelManager . CP_RESOLVE_VERBOSE ) { Util . verbose ( "" + "" + containerPath , System . err ) ; e . printStackTrace ( ) ; } if ( e instanceof RubyModelException ) { throw ( RubyModelException ) e ; } else { throw new RubyModelException ( e ) ; } } finally { for ( int i = ; i < projectLength ; i ++ ) { if ( respectiveContainers [ i ] == null ) { manager . containerPut ( affectedProjects [ i ] , containerPath , null ) ; } } } } public static void setLoadpathVariable ( String variableName , IPath [ ] path , IProgressMonitor monitor ) throws RubyModelException { if ( path == null ) Assert . isTrue ( false , "" ) ; setLoadpathVariables ( new String [ ] { variableName } , new IPath [ ] [ ] { path } , monitor ) ; } public static void setLoadpathVariables ( String [ ] variableNames , IPath [ ] [ ] paths , IProgressMonitor monitor ) throws RubyModelException { if ( variableNames . length != paths . length ) Assert . isTrue ( false , "" ) ; RubyModelManager . getRubyModelManager ( ) . updateVariableValues ( variableNames , paths , true , monitor ) ; } public static ILoadpathEntry newProjectEntry ( IPath fullPath ) { return newProjectEntry ( fullPath , LoadpathEntry . NO_EXTRA_ATTRIBUTES , false ) ; } public static ILoadpathEntry newVariableEntry ( IPath path ) { return newVariableEntry ( path , LoadpathEntry . NO_EXTRA_ATTRIBUTES , false ) ; } public static ILoadpathEntry newContainerEntry ( IPath path ) { return newContainerEntry ( path , LoadpathEntry . NO_EXTRA_ATTRIBUTES , false ) ; } public static ILoadpathEntry newLibraryEntry ( IPath p ) { return newLibraryEntry ( p , LoadpathEntry . NO_EXTRA_ATTRIBUTES , false ) ; } public static ILoadpathAttribute newLoadpathAttribute ( String name , String value ) { return new LoadpathAttribute ( name , value ) ; } public static ILoadpathEntry newLibraryEntry ( IPath path , boolean isExported ) { return newLibraryEntry ( path , LoadpathEntry . NO_EXTRA_ATTRIBUTES , isExported ) ; } public static ILoadpathEntry newVariableEntry ( IPath path , boolean isExported ) { return newVariableEntry ( path , LoadpathEntry . NO_EXTRA_ATTRIBUTES , isExported ) ; } public static ILoadpathEntry newProjectEntry ( IPath path , boolean isExported ) { return newProjectEntry ( path , LoadpathEntry . NO_EXTRA_ATTRIBUTES , isExported ) ; } public static ILoadpathEntry newContainerEntry ( IPath path , boolean isExported ) { return newContainerEntry ( path , LoadpathEntry . NO_EXTRA_ATTRIBUTES , isExported ) ; } public static IRubyElement create ( String handleIdentifier ) { return create ( handleIdentifier , DefaultWorkingCopyOwner . PRIMARY ) ; } public static IRubyElement create ( String handleIdentifier , WorkingCopyOwner owner ) { if ( handleIdentifier == null ) { return null ; } MementoTokenizer memento = new MementoTokenizer ( handleIdentifier ) ; RubyModel model = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; return model . getHandleFromMemento ( memento , owner ) ; } public static ILoadpathEntry newSourceEntry ( IPath path , IPath [ ] exclusionPatterns ) { return newSourceEntry ( path , LoadpathEntry . INCLUDE_ALL , exclusionPatterns , LoadpathEntry . NO_EXTRA_ATTRIBUTES ) ; } public static IRubyScript createRubyScriptFrom ( IFile file ) { return RubyModelManager . createRubyScriptFrom ( file , null ) ; } private static class RubyProjectListener implements IResourceChangeListener { public void resourceChanged ( IResourceChangeEvent event ) { if ( event == null ) return ; IResourceDelta delta = event . getDelta ( ) ; checkDelta ( delta ) ; } private void checkDelta ( IResourceDelta delta ) { if ( delta == null ) return ; IResource resource = delta . getResource ( ) ; if ( resource instanceof IProject ) { final IProject project = ( IProject ) resource ; if ( ! RubyProject . hasRubyNature ( project ) ) { IResourceProxyVisitor visitor = new IResourceProxyVisitor ( ) { private boolean added = false ; public boolean visit ( IResourceProxy proxy ) throws CoreException { if ( proxy . getType ( ) == IResource . FILE ) { if ( RubyCore . isRubyLikeFileName ( proxy . getName ( ) ) ) { Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { try { RubyCore . addRubyNature ( project , monitor ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } return Status . OK_STATUS ; } } ; job . schedule ( ) ; added = true ; } } return ! added ; } } ; try { project . accept ( visitor , IResource . NONE ) ; } catch ( CoreException e ) { RubyCore . log ( e ) ; } } IResourceDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { checkDelta ( children [ i ] ) ; } } } } public static IRegion newRegion ( ) { return new Region ( ) ; } public static String [ ] getLoadpathVariableNames ( ) { return RubyModelManager . getRubyModelManager ( ) . variableNames ( ) ; } public static void initializeAfterLoad ( IProgressMonitor monitor ) throws CoreException { try { if ( monitor != null ) monitor . beginTask ( Messages . javamodel_initialization , ) ; SearchEngine engine = new SearchEngine ( ) ; IRubySearchScope scope = SearchEngine . createWorkspaceScope ( ) ; try { engine . searchAllTypeNames ( null , "" . toCharArray ( ) , SearchPattern . R_PATTERN_MATCH | SearchPattern . R_CASE_SENSITIVE , IRubySearchConstants . CLASS , scope , new TypeNameRequestor ( ) { public void acceptType ( boolean isModule , char [ ] packageName , char [ ] simpleTypeName , char [ ] [ ] enclosingTypeNames , String path ) { } } , IRubySearchConstants . CANCEL_IF_NOT_READY_TO_SEARCH , monitor == null ? null : new SubProgressMonitor ( monitor , ) ) ; } catch ( RubyModelException e ) { } catch ( OperationCanceledException e ) { if ( monitor != null && monitor . isCanceled ( ) ) throw e ; } final RubyModel model = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) ; try { model . refreshExternalArchives ( null , monitor == null ? null : new SubProgressMonitor ( monitor , ) ) ; } catch ( RubyModelException e ) { } } finally { if ( monitor != null ) monitor . done ( ) ; } } public static IPath checkSystemPath ( String exe ) { String systemPath = System . getenv ( "" ) ; if ( systemPath == null ) return null ; String [ ] paths = systemPath . split ( File . pathSeparator ) ; return checkDirs ( exe , paths ) ; } public static IPath checkCommonBinLocations ( String exe ) { if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) return null ; String [ ] paths = new String [ ] { "" , "" , "" , "" , "" , "" } ; return checkDirs ( exe , paths ) ; } private static IPath checkDirs ( String exe , String [ ] paths ) { for ( int i = ; i < paths . length ; i ++ ) { IPath path = new Path ( paths [ i ] ) . append ( exe ) ; if ( path . toFile ( ) . exists ( ) ) return path ; } return null ; } public static File copyToStateLocation ( Plugin plugin , IPath fileName ) { return copyToStateLocation ( plugin , fileName , false ) ; } public static File copyToStateLocation ( Plugin plugin , IPath fileName , boolean force ) { IPath path = plugin . getStateLocation ( ) . append ( fileName ) ; if ( ! force && path . toFile ( ) . exists ( ) ) return path . toFile ( ) ; InputStream stream = null ; OutputStream out = null ; try { URL url = getFileURL ( plugin , fileName ) ; stream = url . openStream ( ) ; if ( ! path . toFile ( ) . getParentFile ( ) . exists ( ) && ! path . toFile ( ) . getParentFile ( ) . mkdirs ( ) ) { return null ; } path . toFile ( ) . createNewFile ( ) ; byte [ ] bytes = org . rubypeople . rdt . core . util . Util . getInputStreamAsByteArray ( stream , - ) ; out = new FileOutputStream ( path . toFile ( ) ) ; out . write ( bytes ) ; } catch ( IOException e ) { RubyCore . log ( e ) ; } finally { try { if ( stream != null ) stream . close ( ) ; } catch ( IOException e ) { } try { if ( out != null ) out . close ( ) ; } catch ( IOException e ) { } } return path . toFile ( ) ; } private static URL getFileURL ( Plugin plugin , IPath fileName ) { URL url = FileLocator . find ( plugin . getBundle ( ) , fileName , null ) ; if ( url == null ) throw new RuntimeException ( "" + fileName + "" + fileName . toPortableString ( ) ) ; return url ; } } package org . rubypeople . rdt . core ; public abstract class LoadpathVariableInitializer { public LoadpathVariableInitializer ( ) { } public abstract void initialize ( String variable ) ; } package org . rubypeople . rdt . core ; import org . rubypeople . rdt . core . compiler . IProblem ; public abstract class CompletionRequestor { private int ignoreSet = ; public CompletionRequestor ( ) { } public final boolean isIgnored ( int completionProposalKind ) { if ( completionProposalKind < CompletionProposal . FIRST_KIND || completionProposalKind > CompletionProposal . LAST_KIND ) { throw new IllegalArgumentException ( "" + completionProposalKind ) ; } return != ( this . ignoreSet & ( << completionProposalKind ) ) ; } public final void setIgnored ( int completionProposalKind , boolean ignore ) { if ( completionProposalKind < CompletionProposal . FIRST_KIND || completionProposalKind > CompletionProposal . LAST_KIND ) { throw new IllegalArgumentException ( "" + completionProposalKind ) ; } if ( ignore ) { this . ignoreSet |= ( << completionProposalKind ) ; } else { this . ignoreSet &= ~ ( << completionProposalKind ) ; } } public void beginReporting ( ) { } public void endReporting ( ) { } public void completionFailure ( IProblem problem ) { } public abstract void accept ( CompletionProposal proposal ) ; } package org . rubypeople . rdt . core ; public interface IMethod extends IRubyElement , IMember { public static final int PUBLIC = Flags . AccPublic ; public static final int PROTECTED = Flags . AccProtected ; public static final int PRIVATE = Flags . AccPrivate ; public int getVisibility ( ) throws RubyModelException ; public boolean isConstructor ( ) ; public String [ ] getParameterNames ( ) throws RubyModelException ; public boolean isSingleton ( ) ; public int getNumberOfParameters ( ) throws RubyModelException ; public boolean isPrivate ( ) throws RubyModelException ; public boolean isPublic ( ) throws RubyModelException ; public boolean isProtected ( ) throws RubyModelException ; public String [ ] getBlockParameters ( ) throws RubyModelException ; public boolean isSimilar ( IMethod method ) ; } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . IProgressMonitor ; import org . jruby . ast . RootNode ; public interface IRubyScript extends IRubyElement , ISourceReference , IParent , IOpenable , ICodeAssist { void reconcile ( ) throws RubyModelException ; RootNode reconcile ( boolean forceProblemDetection , WorkingCopyOwner owner , IProgressMonitor monitor ) throws RubyModelException ; IType getType ( String name ) ; IRubyScript getPrimary ( ) ; boolean isWorkingCopy ( ) ; IRubyScript getWorkingCopy ( IProgressMonitor monitor ) throws RubyModelException ; IRubyScript getWorkingCopy ( WorkingCopyOwner owner , IProblemRequestor requestor , IProgressMonitor monitor ) throws RubyModelException ; public boolean hasResourceChanged ( ) ; void becomeWorkingCopy ( IProblemRequestor requestor , IProgressMonitor monitor ) throws RubyModelException ; void commitWorkingCopy ( boolean force , IProgressMonitor monitor ) throws RubyModelException ; void discardWorkingCopy ( ) throws RubyModelException ; IImportDeclaration getImport ( String name ) ; IImportContainer getImportContainer ( ) ; IImportDeclaration [ ] getImports ( ) throws RubyModelException ; WorkingCopyOwner getOwner ( ) ; IType [ ] getTypes ( ) throws RubyModelException ; IRubyElement getElementAt ( int position ) throws RubyModelException ; IType findPrimaryType ( ) ; IType [ ] getAllTypes ( ) throws RubyModelException ; } package org . rubypeople . rdt . core ; public interface IImportDeclaration extends IRubyElement , ISourceReference { String getElementName ( ) ; } package org . rubypeople . rdt . core ; import java . io . PrintStream ; import java . io . PrintWriter ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . rubypeople . rdt . internal . core . RubyModelStatus ; public class RubyModelException extends CoreException { private static final long serialVersionUID = - ; CoreException nestedCoreException ; public RubyModelException ( Throwable e , int code ) { this ( new RubyModelStatus ( code , e ) ) ; } public RubyModelException ( CoreException exception ) { super ( exception . getStatus ( ) ) ; this . nestedCoreException = exception ; } public RubyModelException ( IRubyModelStatus status ) { super ( status ) ; } public Throwable getException ( ) { if ( this . nestedCoreException == null ) { return getStatus ( ) . getException ( ) ; } return this . nestedCoreException ; } public IRubyModelStatus getRubyModelStatus ( ) { IStatus status = this . getStatus ( ) ; if ( status instanceof IRubyModelStatus ) { return ( IRubyModelStatus ) status ; } return new RubyModelStatus ( this . nestedCoreException ) ; } public boolean isDoesNotExist ( ) { IRubyModelStatus javaModelStatus = getRubyModelStatus ( ) ; return javaModelStatus != null && javaModelStatus . isDoesNotExist ( ) ; } public void printStackTrace ( PrintStream output ) { synchronized ( output ) { super . printStackTrace ( output ) ; Throwable throwable = getException ( ) ; if ( throwable != null ) { output . print ( "" ) ; throwable . printStackTrace ( output ) ; } } } public void printStackTrace ( PrintWriter output ) { synchronized ( output ) { super . printStackTrace ( output ) ; Throwable throwable = getException ( ) ; if ( throwable != null ) { output . print ( "" ) ; throwable . printStackTrace ( output ) ; } } } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; if ( getException ( ) != null ) { if ( getException ( ) instanceof CoreException ) { CoreException c = ( CoreException ) getException ( ) ; buffer . append ( "" ) ; buffer . append ( c . getStatus ( ) . getCode ( ) ) ; buffer . append ( "" ) ; buffer . append ( c . getStatus ( ) . getMessage ( ) ) ; } else { buffer . append ( getException ( ) . toString ( ) ) ; } } else { buffer . append ( getStatus ( ) . toString ( ) ) ; } return buffer . toString ( ) ; } } package org . rubypeople . rdt . core . util ; import java . io . File ; import java . io . FileInputStream ; import java . io . FilenameFilter ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . UnsupportedEncodingException ; import java . util . regex . Pattern ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public abstract class Util { private static final String [ ] KEYWORDS = new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private static final String [ ] OPERATORS = new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , ">" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; public interface Displayable { public String displayString ( Object o ) ; } private static final int DEFAULT_READING_SIZE = ; public final static String UTF_8 = "" ; public static String LINE_SEPARATOR = System . getProperty ( "" ) ; public static byte [ ] getFileByteContent ( File file ) throws IOException { InputStream stream = null ; try { stream = new FileInputStream ( file ) ; return getInputStreamAsByteArray ( stream , ( int ) file . length ( ) ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { } } } } public static String toString ( Object [ ] objects , Displayable renderer ) { if ( objects == null ) return "" ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < objects . length ; i ++ ) { if ( i > ) buffer . append ( "" ) ; buffer . append ( renderer . displayString ( objects [ i ] ) ) ; } return buffer . toString ( ) ; } public static byte [ ] getInputStreamAsByteArray ( InputStream stream , int length ) throws IOException { byte [ ] contents ; if ( length == - ) { contents = new byte [ ] ; int contentsLength = ; int amountRead = - ; do { int amountRequested = Math . max ( stream . available ( ) , DEFAULT_READING_SIZE ) ; if ( contentsLength + amountRequested > contents . length ) { System . arraycopy ( contents , , contents = new byte [ contentsLength + amountRequested ] , , contentsLength ) ; } amountRead = stream . read ( contents , contentsLength , amountRequested ) ; if ( amountRead > ) { contentsLength += amountRead ; } } while ( amountRead != - ) ; if ( contentsLength < contents . length ) { System . arraycopy ( contents , , contents = new byte [ contentsLength ] , , contentsLength ) ; } } else { contents = new byte [ length ] ; int len = ; int readSize = ; while ( ( readSize != - ) && ( len != length ) ) { len += readSize ; readSize = stream . read ( contents , len , length - len ) ; } } return contents ; } public static String toString ( Object [ ] objects ) { return toString ( objects , new Displayable ( ) { public String displayString ( Object o ) { if ( o == null ) return "" ; return o . toString ( ) ; } } ) ; } public static char [ ] getFileCharContent ( File file , String encoding ) throws IOException { InputStream stream = null ; try { stream = new FileInputStream ( file ) ; return getInputStreamAsCharArray ( stream , ( int ) file . length ( ) , encoding ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { } } } } public static char [ ] getInputStreamAsCharArray ( InputStream stream , int length , String encoding ) throws IOException { InputStreamReader reader = null ; try { reader = encoding == null ? new InputStreamReader ( stream ) : new InputStreamReader ( stream , encoding ) ; } catch ( UnsupportedEncodingException e ) { reader = new InputStreamReader ( stream ) ; } char [ ] contents ; int totalRead = ; if ( length == - ) { contents = CharOperation . NO_CHAR ; } else { contents = new char [ length ] ; } while ( true ) { int amountRequested ; if ( totalRead < length ) { amountRequested = length - totalRead ; } else { int current = reader . read ( ) ; if ( current < ) break ; amountRequested = Math . max ( stream . available ( ) , DEFAULT_READING_SIZE ) ; if ( totalRead + + amountRequested > contents . length ) System . arraycopy ( contents , , contents = new char [ totalRead + + amountRequested ] , , totalRead ) ; contents [ totalRead ++ ] = ( char ) current ; } int amountRead = reader . read ( contents , totalRead , amountRequested ) ; if ( amountRead < ) break ; totalRead += amountRead ; } int start = ; if ( totalRead > && UTF_8 . equals ( encoding ) ) { if ( contents [ ] == ) { totalRead -- ; start = ; } } if ( totalRead < contents . length ) System . arraycopy ( contents , start , contents = new char [ totalRead ] , , totalRead ) ; return contents ; } public static String camelCaseToUnderscores ( String name ) { if ( name == null ) return null ; if ( name . length ( ) == ) return "" ; StringBuffer newName = new StringBuffer ( ) ; boolean lastWasUpper = false ; for ( int i = ; i < name . length ( ) ; i ++ ) { char c = name . charAt ( i ) ; newName . append ( Character . toLowerCase ( c ) ) ; if ( lastWasUpper && Character . isLowerCase ( c ) ) { if ( newName . length ( ) > ) newName . insert ( newName . length ( ) - , "" ) ; lastWasUpper = false ; } if ( Character . isUpperCase ( c ) ) { lastWasUpper = true ; } } return newName . toString ( ) ; } public static String underscoresToCamelCase ( String name ) { if ( name == null ) return null ; if ( name . length ( ) == ) return "" ; StringBuffer newName = new StringBuffer ( ) ; boolean lastWasUnderScore = false ; for ( int i = ; i < name . length ( ) ; i ++ ) { char c = name . charAt ( i ) ; if ( lastWasUnderScore || i == ) { newName . append ( Character . toUpperCase ( c ) ) ; lastWasUnderScore = false ; } else if ( c == '' ) { lastWasUnderScore = true ; } else { newName . append ( c ) ; } } return newName . toString ( ) ; } public static boolean isOperator ( String word ) { return contains ( word , OPERATORS ) ; } public static boolean isKeyword ( String word ) { return contains ( word , KEYWORDS ) ; } private static boolean contains ( String word , String [ ] array ) { for ( int i = ; i < array . length ; i ++ ) { if ( array [ i ] . equals ( word ) ) return true ; } return false ; } public static File findFileWithOptionalSuffix ( String basePath ) { File file = new File ( basePath ) ; if ( file != null && file . exists ( ) && file . isFile ( ) ) return file ; File parentDir = file . getParentFile ( ) ; if ( parentDir == null || ! parentDir . exists ( ) ) return null ; IPath path = new Path ( basePath ) ; final String extension = getExtension ( path ) ; final String filenameWithoutExtension = path . removeFileExtension ( ) . lastSegment ( ) ; File [ ] children = parentDir . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { String tmpExtension = getExtension ( new Path ( name ) ) ; return name . startsWith ( filenameWithoutExtension ) && ( ( extension == null && tmpExtension == null ) || ( tmpExtension != null && extension != null && tmpExtension . equals ( extension ) ) ) ; } } ) ; if ( children == null || children . length == ) return null ; String [ ] commonSuffixes = new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" } ; for ( File child : children ) { for ( String suffix : commonSuffixes ) { IPath childPath = new Path ( child . getName ( ) ) ; String childExtension = getExtension ( childPath ) ; String baseName = childPath . lastSegment ( ) ; if ( childExtension != null ) baseName = baseName . substring ( , baseName . length ( ) - childExtension . length ( ) ) ; if ( baseName . endsWith ( suffix ) ) return child ; } } return children [ ] ; } private static String getExtension ( IPath path ) { String extension = path . getFileExtension ( ) ; if ( extension == null ) return null ; if ( Pattern . matches ( "" , extension ) ) return null ; return extension ; } } package org . rubypeople . rdt . core ; import java . util . EventObject ; public class BufferChangedEvent extends EventObject { private int length ; private int offset ; private String text ; private static final long serialVersionUID = ; public BufferChangedEvent ( IBuffer buffer , int offset , int length , String text ) { super ( buffer ) ; this . offset = offset ; this . length = length ; this . text = text ; } public IBuffer getBuffer ( ) { return ( IBuffer ) this . source ; } public int getLength ( ) { return this . length ; } public int getOffset ( ) { return this . offset ; } public String getText ( ) { return this . text ; } } package org . rubypeople . rdt . core ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . IProgressMonitor ; public interface IBuffer { public void addBufferChangedListener ( IBufferChangedListener listener ) ; public void append ( char [ ] text ) ; public void append ( String text ) ; public void close ( ) ; public char getChar ( int position ) ; public char [ ] getCharacters ( ) ; public String getContents ( ) ; public int getLength ( ) ; public IOpenable getOwner ( ) ; public String getText ( int offset , int length ) ; public IResource getUnderlyingResource ( ) ; public boolean hasUnsavedChanges ( ) ; public boolean isClosed ( ) ; public boolean isReadOnly ( ) ; public void removeBufferChangedListener ( IBufferChangedListener listener ) ; public void replace ( int position , int length , char [ ] text ) ; public void replace ( int position , int length , String text ) ; public void save ( IProgressMonitor progress , boolean force ) throws RubyModelException ; public void setContents ( char [ ] contents ) ; public void setContents ( String contents ) ; } package org . rubypeople . rdt . core ; public interface IRubyModelMarker { public static final String RUBY_MODEL_PROBLEM_MARKER = RubyCore . PLUGIN_ID + "" ; public static final String TRANSIENT_PROBLEM = RubyCore . PLUGIN_ID + "" ; public static final String TASK_MARKER = RubyCore . PLUGIN_ID + "" ; public static final String ARGUMENTS = "" ; public static final String ID = "" ; String CLASSPATH_FILE_FORMAT = "" ; String CYCLE_DETECTED = "" ; String BUILDPATH_PROBLEM_MARKER = RubyCore . PLUGIN_ID + "" ; String CATEGORY_ID = "" ; } package org . rubypeople . rdt . core ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ISourceFolderRoot extends IParent , IRubyElement , IOpenable { String DEFAULT_PACKAGEROOT_PATH = "" ; boolean isExternal ( ) ; ISourceFolder getSourceFolder ( String names [ ] ) ; ISourceFolder createSourceFolder ( String name , boolean force , IProgressMonitor monitor ) throws RubyModelException ; void delete ( int updateResourceFlags , int updateModelFlags , IProgressMonitor monitor ) throws RubyModelException ; boolean isArchive ( ) ; Object [ ] getNonRubyResources ( ) throws RubyModelException ; ISourceFolder getSourceFolder ( String packName ) ; ILoadpathEntry getRawLoadpathEntry ( ) throws RubyModelException ; } package org . rubypeople . rdt . core ; public interface IBufferChangedListener { public void bufferChanged ( BufferChangedEvent event ) ; } package org . rubypeople . rdt . core ; public interface IMember extends IRubyElement , ISourceReference , IParent { IRubyScript getRubyScript ( ) ; IType getType ( String name , int occurrenceCount ) ; IType getDeclaringType ( ) ; ISourceRange getNameRange ( ) throws RubyModelException ; } package org . rubypeople . rdt . core ; public interface ISourceImport { int getDeclarationSourceEnd ( ) ; int getDeclarationSourceStart ( ) ; String getName ( ) ; } package org . rubypeople . rdt . core . parser . warnings ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . RescueBodyNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . jruby . ast . WhenNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . internal . core . parser . Error ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . parser . Warning ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; public abstract class RubyLintVisitor extends InOrderVisitor { private String contents ; protected Map < String , String > fOptions ; private List < CategorizedProblem > problems ; public RubyLintVisitor ( String contents ) { this ( RubyCore . getOptions ( ) , contents ) ; } public RubyLintVisitor ( Map < String , String > options , String contents ) { this . problems = new ArrayList < CategorizedProblem > ( ) ; this . contents = contents ; this . fOptions = options ; } protected String getSource ( Node node ) { return ASTUtil . getSource ( contents , node ) ; } protected String getSource ( int start , int end ) { if ( start > end ) { int temp = end ; end = start ; start = temp ; } if ( contents . length ( ) < end ) end = contents . length ( ) ; if ( start < ) start = ; return new String ( contents . substring ( start , end ) ) ; } public List < CategorizedProblem > getProblems ( ) { return problems ; } public boolean isIgnored ( ) { String value = getSeverity ( ) ; if ( value != null && value . equals ( RubyCore . IGNORE ) ) return true ; return false ; } protected void createProblem ( ISourcePosition position , String message ) { String value = getSeverity ( ) ; if ( value != null && value . equals ( RubyCore . IGNORE ) ) return ; CategorizedProblem problem ; if ( value != null && value . equals ( RubyCore . ERROR ) ) problem = new Error ( position , message , getProblemID ( ) ) ; else problem = new Warning ( position , message , getProblemID ( ) ) ; problems . add ( problem ) ; } protected String getSeverity ( ) { return ( String ) fOptions . get ( getOptionKey ( ) ) ; } @ Override protected Object visitNode ( Node iVisited ) { return null ; } abstract protected String getOptionKey ( ) ; public void exitClassNode ( ClassNode iVisited ) { } public void exitDefnNode ( DefnNode iVisited ) { } public void exitIfNode ( IfNode iVisited ) { } public void exitBlockNode ( BlockNode iVisited ) { } public void exitDefsNode ( DefsNode iVisited ) { } public void exitModuleNode ( ModuleNode iVisited ) { } public void exitWhenNode ( WhenNode iVisited ) { } public void exitSClassNode ( SClassNode iVisited ) { } public void exitArgsNode ( ArgsNode iVisited ) { } public void exitRescueBodyNode ( RescueBodyNode iVisited ) { } public void exitHashNode ( HashNode iVisited ) { } public void exitRootNode ( RootNode iVisited ) { } protected int getProblemID ( ) { return IProblem . Uncategorized ; } @ Override public Object visitArgsNode ( ArgsNode iVisited ) { Object ins = super . visitArgsNode ( iVisited ) ; exitArgsNode ( iVisited ) ; return ins ; } @ Override public Object visitBlockNode ( BlockNode iVisited ) { Object ins = super . visitBlockNode ( iVisited ) ; exitBlockNode ( iVisited ) ; return ins ; } @ Override public Object visitClassNode ( ClassNode iVisited ) { Object ins = super . visitClassNode ( iVisited ) ; exitClassNode ( iVisited ) ; return ins ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { Object ins = super . visitDefnNode ( iVisited ) ; exitDefnNode ( iVisited ) ; return ins ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { Object ins = super . visitDefsNode ( iVisited ) ; exitDefsNode ( iVisited ) ; return ins ; } @ Override public Object visitHashNode ( HashNode iVisited ) { Object ins = super . visitHashNode ( iVisited ) ; exitHashNode ( iVisited ) ; return ins ; } @ Override public Object visitIfNode ( IfNode iVisited ) { Object ins = super . visitIfNode ( iVisited ) ; exitIfNode ( iVisited ) ; return ins ; } @ Override public Object visitModuleNode ( ModuleNode iVisited ) { Object ins = super . visitModuleNode ( iVisited ) ; exitModuleNode ( iVisited ) ; return ins ; } @ Override public Object visitRescueBodyNode ( RescueBodyNode iVisited ) { Object ins = super . visitRescueBodyNode ( iVisited ) ; exitRescueBodyNode ( iVisited ) ; return ins ; } @ Override public Object visitRootNode ( RootNode iVisited ) { problems . clear ( ) ; Object ret = super . visitRootNode ( iVisited ) ; exitRootNode ( iVisited ) ; return ret ; } @ Override public Object visitSClassNode ( SClassNode iVisited ) { Object ins = super . visitSClassNode ( iVisited ) ; exitSClassNode ( iVisited ) ; return ins ; } @ Override public Object visitWhenNode ( WhenNode iVisited ) { Object ins = super . visitWhenNode ( iVisited ) ; exitWhenNode ( iVisited ) ; return ins ; } } package org . rubypeople . rdt . core . parser ; import org . jruby . ast . AliasNode ; import org . jruby . ast . AndNode ; import org . jruby . ast . ArgsCatNode ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgsPushNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . AttrAssignNode ; import org . jruby . ast . BackRefNode ; import org . jruby . ast . BeginNode ; import org . jruby . ast . BignumNode ; import org . jruby . ast . BlockArgNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . BlockPassNode ; import org . jruby . ast . BreakNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . CaseNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . Colon3Node ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DRegexpNode ; import org . jruby . ast . DStrNode ; import org . jruby . ast . DSymbolNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DXStrNode ; import org . jruby . ast . DefinedNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . DotNode ; import org . jruby . ast . EnsureNode ; import org . jruby . ast . EvStrNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . FalseNode ; import org . jruby . ast . FixnumNode ; import org . jruby . ast . FlipNode ; import org . jruby . ast . FloatNode ; import org . jruby . ast . ForNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . GlobalVarNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Match2Node ; import org . jruby . ast . Match3Node ; import org . jruby . ast . MatchNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . MultipleAsgn19Node ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . NextNode ; import org . jruby . ast . NilNode ; import org . jruby . ast . Node ; import org . jruby . ast . NotNode ; import org . jruby . ast . NthRefNode ; import org . jruby . ast . OpAsgnAndNode ; import org . jruby . ast . OpAsgnNode ; import org . jruby . ast . OpAsgnOrNode ; import org . jruby . ast . OpElementAsgnNode ; import org . jruby . ast . OrNode ; import org . jruby . ast . PostExeNode ; import org . jruby . ast . PreExeNode ; import org . jruby . ast . RedoNode ; import org . jruby . ast . RegexpNode ; import org . jruby . ast . RescueBodyNode ; import org . jruby . ast . RescueNode ; import org . jruby . ast . RestArgNode ; import org . jruby . ast . RetryNode ; import org . jruby . ast . ReturnNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . jruby . ast . SValueNode ; import org . jruby . ast . SelfNode ; import org . jruby . ast . SplatNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . SuperNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . ToAryNode ; import org . jruby . ast . TrueNode ; import org . jruby . ast . UndefNode ; import org . jruby . ast . UntilNode ; import org . jruby . ast . VAliasNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . WhenNode ; import org . jruby . ast . WhileNode ; import org . jruby . ast . XStrNode ; import org . jruby . ast . YieldNode ; import org . jruby . ast . ZArrayNode ; import org . jruby . ast . ZSuperNode ; import org . jruby . ast . visitor . NodeVisitor ; public abstract class AbstractVisitor implements NodeVisitor { protected abstract Object visitNode ( Node visited ) ; public Object visitNullNode ( ) { return visitNode ( null ) ; } public Object acceptNode ( Node node ) { if ( node == null ) { return visitNullNode ( ) ; } else { return node . accept ( this ) ; } } public Object visitAliasNode ( AliasNode visited ) { return visitNode ( visited ) ; } public Object visitAndNode ( AndNode visited ) { return visitNode ( visited ) ; } public Object visitArgsCatNode ( ArgsCatNode visited ) { return visitNode ( visited ) ; } public Object visitArgsNode ( ArgsNode visited ) { return visitNode ( visited ) ; } public Object visitArgsPushNode ( ArgsPushNode visited ) { return visitNode ( visited ) ; } public Object visitArrayNode ( ArrayNode visited ) { return visitNode ( visited ) ; } public Object visitAttrAssignNode ( AttrAssignNode visited ) { return visitNode ( visited ) ; } public Object visitBackRefNode ( BackRefNode visited ) { return visitNode ( visited ) ; } public Object visitBeginNode ( BeginNode visited ) { return visitNode ( visited ) ; } public Object visitBignumNode ( BignumNode visited ) { return visitNode ( visited ) ; } public Object visitBlockArgNode ( BlockArgNode visited ) { return visitNode ( visited ) ; } public Object visitBlockNode ( BlockNode visited ) { return visitNode ( visited ) ; } public Object visitBlockPassNode ( BlockPassNode visited ) { return visitNode ( visited ) ; } public Object visitBreakNode ( BreakNode visited ) { return visitNode ( visited ) ; } public Object visitCallNode ( CallNode visited ) { return visitNode ( visited ) ; } public Object visitCaseNode ( CaseNode visited ) { return visitNode ( visited ) ; } public Object visitClassNode ( ClassNode visited ) { return visitNode ( visited ) ; } public Object visitClassVarAsgnNode ( ClassVarAsgnNode visited ) { return visitNode ( visited ) ; } public Object visitClassVarDeclNode ( ClassVarDeclNode visited ) { return visitNode ( visited ) ; } public Object visitClassVarNode ( ClassVarNode visited ) { return visitNode ( visited ) ; } public Object visitColon2Node ( Colon2Node visited ) { return visitNode ( visited ) ; } public Object visitColon3Node ( Colon3Node visited ) { return visitNode ( visited ) ; } public Object visitConstDeclNode ( ConstDeclNode visited ) { return visitNode ( visited ) ; } public Object visitConstNode ( ConstNode visited ) { return visitNode ( visited ) ; } public Object visitDAsgnNode ( DAsgnNode visited ) { return visitNode ( visited ) ; } public Object visitDRegxNode ( DRegexpNode visited ) { return visitNode ( visited ) ; } public Object visitDStrNode ( DStrNode visited ) { return visitNode ( visited ) ; } public Object visitDSymbolNode ( DSymbolNode visited ) { return visitNode ( visited ) ; } public Object visitDVarNode ( DVarNode visited ) { return visitNode ( visited ) ; } public Object visitDXStrNode ( DXStrNode visited ) { return visitNode ( visited ) ; } public Object visitDefinedNode ( DefinedNode visited ) { return visitNode ( visited ) ; } public Object visitDefnNode ( DefnNode visited ) { return visitNode ( visited ) ; } public Object visitDefsNode ( DefsNode visited ) { return visitNode ( visited ) ; } public Object visitDotNode ( DotNode visited ) { return visitNode ( visited ) ; } public Object visitEnsureNode ( EnsureNode visited ) { return visitNode ( visited ) ; } public Object visitEvStrNode ( EvStrNode visited ) { return visitNode ( visited ) ; } public Object visitFCallNode ( FCallNode visited ) { return visitNode ( visited ) ; } public Object visitFalseNode ( FalseNode visited ) { return visitNode ( visited ) ; } public Object visitFixnumNode ( FixnumNode visited ) { return visitNode ( visited ) ; } public Object visitFlipNode ( FlipNode visited ) { return visitNode ( visited ) ; } public Object visitFloatNode ( FloatNode visited ) { return visitNode ( visited ) ; } public Object visitForNode ( ForNode visited ) { return visitNode ( visited ) ; } public Object visitGlobalAsgnNode ( GlobalAsgnNode visited ) { return visitNode ( visited ) ; } public Object visitGlobalVarNode ( GlobalVarNode visited ) { return visitNode ( visited ) ; } public Object visitHashNode ( HashNode visited ) { return visitNode ( visited ) ; } public Object visitIfNode ( IfNode visited ) { return visitNode ( visited ) ; } public Object visitInstAsgnNode ( InstAsgnNode visited ) { return visitNode ( visited ) ; } public Object visitInstVarNode ( InstVarNode visited ) { return visitNode ( visited ) ; } public Object visitIterNode ( IterNode visited ) { return visitNode ( visited ) ; } public Object visitLocalAsgnNode ( LocalAsgnNode visited ) { return visitNode ( visited ) ; } public Object visitLocalVarNode ( LocalVarNode visited ) { return visitNode ( visited ) ; } public Object visitMatch2Node ( Match2Node visited ) { return visitNode ( visited ) ; } public Object visitMatch3Node ( Match3Node visited ) { return visitNode ( visited ) ; } public Object visitMatchNode ( MatchNode visited ) { return visitNode ( visited ) ; } public Object visitModuleNode ( ModuleNode visited ) { return visitNode ( visited ) ; } public Object visitMultipleAsgnNode ( MultipleAsgnNode visited ) { return visitNode ( visited ) ; } public Object visitMultipleAsgnNode ( MultipleAsgn19Node visited ) { return visitNode ( visited ) ; } public Object visitNewlineNode ( NewlineNode visited ) { return visitNode ( visited ) ; } public Object visitNextNode ( NextNode visited ) { return visitNode ( visited ) ; } public Object visitNilNode ( NilNode visited ) { return visitNode ( visited ) ; } public Object visitNotNode ( NotNode visited ) { return visitNode ( visited ) ; } public Object visitNthRefNode ( NthRefNode visited ) { return visitNode ( visited ) ; } public Object visitOpAsgnAndNode ( OpAsgnAndNode visited ) { return visitNode ( visited ) ; } public Object visitOpAsgnNode ( OpAsgnNode visited ) { return visitNode ( visited ) ; } public Object visitOpAsgnOrNode ( OpAsgnOrNode visited ) { return visitNode ( visited ) ; } public Object visitOpElementAsgnNode ( OpElementAsgnNode visited ) { return visitNode ( visited ) ; } public Object visitOrNode ( OrNode visited ) { return visitNode ( visited ) ; } public Object visitPostExeNode ( PostExeNode visited ) { return visitNode ( visited ) ; } public Object visitPreExeNode ( PreExeNode visited ) { return visitNode ( visited ) ; } public Object visitRedoNode ( RedoNode visited ) { return visitNode ( visited ) ; } public Object visitRegexpNode ( RegexpNode visited ) { return visitNode ( visited ) ; } public Object visitRescueBodyNode ( RescueBodyNode visited ) { return visitNode ( visited ) ; } public Object visitRescueNode ( RescueNode visited ) { return visitNode ( visited ) ; } public Object visitRestArgNode ( RestArgNode visited ) { return visitNode ( visited ) ; } public Object visitRetryNode ( RetryNode visited ) { return visitNode ( visited ) ; } public Object visitReturnNode ( ReturnNode visited ) { return visitNode ( visited ) ; } public Object visitRootNode ( RootNode visited ) { return visitNode ( visited ) ; } public Object visitSClassNode ( SClassNode visited ) { return visitNode ( visited ) ; } public Object visitSValueNode ( SValueNode visited ) { return visitNode ( visited ) ; } public Object visitSelfNode ( SelfNode visited ) { return visitNode ( visited ) ; } public Object visitSplatNode ( SplatNode visited ) { return visitNode ( visited ) ; } public Object visitStrNode ( StrNode visited ) { return visitNode ( visited ) ; } public Object visitSuperNode ( SuperNode visited ) { return visitNode ( visited ) ; } public Object visitSymbolNode ( SymbolNode visited ) { return visitNode ( visited ) ; } public Object visitToAryNode ( ToAryNode visited ) { return visitNode ( visited ) ; } public Object visitTrueNode ( TrueNode visited ) { return visitNode ( visited ) ; } public Object visitUndefNode ( UndefNode visited ) { return visitNode ( visited ) ; } public Object visitUntilNode ( UntilNode visited ) { return visitNode ( visited ) ; } public Object visitVAliasNode ( VAliasNode visited ) { return visitNode ( visited ) ; } public Object visitVCallNode ( VCallNode visited ) { return visitNode ( visited ) ; } public Object visitWhenNode ( WhenNode visited ) { return visitNode ( visited ) ; } public Object visitWhileNode ( WhileNode visited ) { return visitNode ( visited ) ; } public Object visitXStrNode ( XStrNode visited ) { return visitNode ( visited ) ; } public Object visitYieldNode ( YieldNode visited ) { return visitNode ( visited ) ; } public Object visitZArrayNode ( ZArrayNode visited ) { return visitNode ( visited ) ; } public Object visitZSuperNode ( ZSuperNode visited ) { return visitNode ( visited ) ; } } package org . rubypeople . rdt . core . parser ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . jruby . ast . BlockNode ; import org . jruby . ast . CaseNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . OpAsgnAndNode ; import org . jruby . ast . OpAsgnNode ; import org . jruby . ast . OpAsgnOrNode ; import org . jruby . ast . OpElementAsgnNode ; import org . jruby . ast . ReturnNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . WhenNode ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; public class ReturnVisitor extends InOrderVisitor { private boolean implicit = false ; private Set < ReturnVisitor > branches = new HashSet < ReturnVisitor > ( ) ; private List < Node > values = new ArrayList < Node > ( ) ; private Node lastNode ; @ Override protected Object visitNode ( Node iVisited ) { if ( iVisited != null && ! structuralNode ( iVisited ) && ! branchingNode ( iVisited ) && ! ( iVisited instanceof ReturnNode ) ) { implicit = true ; lastNode = iVisited ; } return super . visitNode ( iVisited ) ; } @ Override public Object visitOpAsgnAndNode ( OpAsgnAndNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getFirstNode ( ) ) ; return null ; } @ Override public Object visitOpAsgnNode ( OpAsgnNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getReceiverNode ( ) ) ; return null ; } @ Override public Object visitOpAsgnOrNode ( OpAsgnOrNode iVisited ) { handleNode ( iVisited ) ; acceptNode ( iVisited . getFirstNode ( ) ) ; return null ; } private boolean structuralNode ( Node visited ) { return ( visited instanceof RootNode ) || ( visited instanceof NewlineNode ) ; } private boolean branchingNode ( Node visited ) { return ( visited instanceof IfNode ) || ( visited instanceof CaseNode ) ; } @ Override public Object visitReturnNode ( ReturnNode iVisited ) { implicit = false ; lastNode = null ; values . add ( iVisited ) ; return null ; } @ Override public Object visitCaseNode ( CaseNode iVisited ) { ListNode node = iVisited . getCases ( ) ; List < Node > caseChildren = node . childNodes ( ) ; WhenNode whenNode = ( WhenNode ) caseChildren . get ( ) ; while ( whenNode != null ) { ReturnVisitor visitor = new ReturnVisitor ( ) ; whenNode . getBodyNode ( ) . accept ( visitor ) ; branches . add ( visitor ) ; Node nextCase = whenNode . getNextCase ( ) ; if ( nextCase instanceof BlockNode ) { ReturnVisitor visitor2 = new ReturnVisitor ( ) ; nextCase . accept ( visitor2 ) ; branches . add ( visitor ) ; whenNode = null ; break ; } if ( nextCase instanceof NewlineNode ) { NewlineNode newline = ( NewlineNode ) nextCase ; nextCase = newline . getNextNode ( ) ; } if ( nextCase instanceof WhenNode ) { whenNode = ( WhenNode ) whenNode . getNextCase ( ) ; } else { whenNode = null ; } } return null ; } @ Override public Object visitIfNode ( IfNode iVisited ) { if ( iVisited . getThenBody ( ) != null ) { ReturnVisitor visitor = new ReturnVisitor ( ) ; iVisited . getThenBody ( ) . accept ( visitor ) ; branches . add ( visitor ) ; } if ( iVisited . getElseBody ( ) != null ) { ReturnVisitor visitor = new ReturnVisitor ( ) ; iVisited . getElseBody ( ) . accept ( visitor ) ; branches . add ( visitor ) ; } else { implicit = true ; } return null ; } public boolean alwaysExplicit ( ) { for ( ReturnVisitor visitor : branches ) { if ( ! visitor . alwaysExplicit ( ) ) return false ; } return ! implicit ; } public List < Node > getReturnValues ( ) { if ( lastNode != null ) { values . add ( lastNode ) ; } for ( ReturnVisitor visitor : branches ) { values . addAll ( visitor . getReturnValues ( ) ) ; } return values ; } } package org . rubypeople . rdt . core ; public interface IElementChangedListener { public void elementChanged ( ElementChangedEvent event ) ; } package org . rubypeople . rdt . core ; public interface IRegion { void add ( IRubyElement element ) ; boolean contains ( IRubyElement element ) ; IRubyElement [ ] getElements ( ) ; boolean remove ( IRubyElement element ) ; } package org . rubypeople . rdt . core ; import java . io . IOException ; import java . net . InetSocketAddress ; import java . net . ServerSocket ; public class SocketUtil { public static int findFreePort ( ) { ServerSocket socket = null ; try { socket = new ServerSocket ( ) ; return socket . getLocalPort ( ) ; } catch ( IOException e ) { } finally { if ( socket != null ) { try { socket . close ( ) ; } catch ( IOException e ) { } } } return - ; } public static boolean portFree ( int port ) { return portFree ( "" , port ) ; } public static boolean portFree ( String host , int port ) { ServerSocket socket = null ; try { socket = new ServerSocket ( ) ; socket . setReuseAddress ( true ) ; socket . bind ( new InetSocketAddress ( host , port ) ) ; } catch ( Exception e ) { return false ; } finally { try { if ( socket != null ) socket . close ( ) ; } catch ( IOException e ) { } } return true ; } } package org . rubypeople . rdt . core ; public interface IRubyModelStatusConstants { public static final int INVALID_CP_CONTAINER_ENTRY = ; public static final int CP_CONTAINER_PATH_UNBOUND = ; public static final int INVALID_CLASSPATH = ; public static final int CP_VARIABLE_PATH_UNBOUND = ; public static final int CORE_EXCEPTION = ; public static final int INVALID_ELEMENT_TYPES = ; public static final int NO_ELEMENTS_TO_PROCESS = ; public static final int ELEMENT_DOES_NOT_EXIST = ; public static final int NULL_PATH = ; public static final int PATH_OUTSIDE_PROJECT = ; public static final int RELATIVE_PATH = ; public static final int DEVICE_PATH = ; public static final int NULL_STRING = ; public static final int READ_ONLY = ; public static final int NAME_COLLISION = ; public static final int INVALID_DESTINATION = ; public static final int INVALID_PATH = ; public static final int INDEX_OUT_OF_BOUNDS = ; public static final int UPDATE_CONFLICT = ; public static final int NULL_NAME = ; public static final int INVALID_NAME = ; public static final int INVALID_CONTENTS = ; public static final int IO_EXCEPTION = ; public static final int DOM_EXCEPTION = ; public static final int TARGET_EXCEPTION = ; public static final int BUILDER_INITIALIZATION_ERROR = ; public static final int BUILDER_SERIALIZATION_ERROR = ; public static final int EVALUATION_ERROR = ; public static final int INVALID_SIBLING = ; public static final int INVALID_RESOURCE = ; public static final int INVALID_RESOURCE_TYPE = ; public static final int INVALID_PROJECT = ; public static final int INVALID_PACKAGE = ; public static final int NO_LOCAL_CONTENTS = ; public static final int INVALID_LOADPATH_FILE_FORMAT = ; public static final int CLASSPATH_CYCLE = ; public static final int DISABLED_CP_EXCLUSION_PATTERNS = ; public static final int DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS = ; public static final int INCOMPATIBLE_JDK_LEVEL = ; public static final int COMPILER_FAILURE = ; public static final int ELEMENT_NOT_ON_CLASSPATH = ; public static final int PROJECT_HAS_NO_RUBY_NATURE = ; } package org . rubypeople . rdt . core ; public interface ILocalVariable extends IRubyElement , ISourceReference { String getElementName ( ) ; ISourceRange getNameRange ( ) throws RubyModelException ; } package org . rubypeople . rdt . core . codeassist ; import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . ExternalRubyScript ; import org . rubypeople . rdt . internal . core . RubyScript ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; public class ResolveContext { private IRubyScript script ; private int start ; private int end ; private RootNode root ; private Node selected ; private IRubyElement [ ] resolved = new IRubyElement [ ] ; public ResolveContext ( IRubyScript script , int start , int end ) { this . script = script ; this . start = start ; this . end = end ; } public RootNode getAST ( ) throws RubyModelException { if ( root == null ) { try { RubyParser parser = new RubyParser ( ) ; root = ( RootNode ) parser . parse ( ( IFile ) script . getResource ( ) , script . getSource ( ) ) . getAST ( ) ; } catch ( SyntaxException e ) { root = ( RootNode ) ( ( RubyScript ) script ) . lastGoodAST ; } } return root ; } public Node getSelectedNode ( ) throws RubyModelException { if ( selected == null ) { selected = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( getAST ( ) , start ) ; } return selected ; } public IRubyScript getScript ( ) { return script ; } public int getStartOffset ( ) { return start ; } public int getEndOffset ( ) { return end ; } public IRubyElement [ ] getResolved ( ) { return prioritize ( resolved ) ; } private IRubyElement [ ] prioritize ( IRubyElement [ ] resolved ) { List < IRubyElement > prioritized = Arrays . asList ( resolved ) ; Collections . sort ( prioritized , new Comparator < IRubyElement > ( ) { public int compare ( IRubyElement o1 , IRubyElement o2 ) { IRubyScript o1Script = ( IRubyScript ) o1 . getAncestor ( IRubyElement . SCRIPT ) ; if ( o1Script != null && o1Script . getPath ( ) . equals ( script . getPath ( ) ) ) { IRubyScript o2Script = ( IRubyScript ) o2 . getAncestor ( IRubyElement . SCRIPT ) ; if ( o2Script != null && o2Script . getPath ( ) . equals ( script . getPath ( ) ) ) { return ; } return - ; } else { IRubyScript o2Script = ( IRubyScript ) o2 . getAncestor ( IRubyElement . SCRIPT ) ; if ( o2Script != null && o2Script . getPath ( ) . equals ( script . getPath ( ) ) ) { return ; } IRubyProject o1Project = o1 . getRubyProject ( ) ; if ( o1Project != null && o1Project . equals ( script . getRubyProject ( ) ) ) { IRubyProject o2Project = o2 . getRubyProject ( ) ; if ( o2Project != null && o2Project . equals ( script . getRubyProject ( ) ) ) { return ; } return - ; } else { IRubyProject o2Project = o2 . getRubyProject ( ) ; if ( o2Project != null && o2Project . equals ( script . getRubyProject ( ) ) ) { return ; } if ( o1Script != null && o1Script instanceof ExternalRubyScript ) { if ( o2Script != null && o2Script instanceof ExternalRubyScript ) { return ; } return - ; } else if ( o2Script != null && o2Script instanceof ExternalRubyScript ) { return ; } return ; } } } } ) ; return prioritized . toArray ( new IRubyElement [ prioritized . size ( ) ] ) ; } public void putResolved ( IRubyElement [ ] resolved ) { this . resolved = resolved ; } } package org . rubypeople . rdt . core . codeassist ; import org . rubypeople . rdt . core . RubyModelException ; public abstract class CodeResolver { public abstract void select ( ResolveContext context ) throws RubyModelException ; } package org . rubypeople . rdt . core ; import java . io . OutputStream ; import org . eclipse . core . runtime . IProgressMonitor ; public interface ITypeHierarchy { void addTypeHierarchyChangedListener ( ITypeHierarchyChangedListener listener ) ; boolean contains ( IType type ) ; boolean exists ( ) ; IType [ ] getAllClasses ( ) ; IType [ ] getAllModules ( ) ; IType [ ] getAllSubtypes ( IType type ) ; IType [ ] getAllSuperclasses ( IType type ) ; IType [ ] getAllSuperModules ( IType type ) ; IType [ ] getAllSupertypes ( IType type ) ; IType [ ] getAllTypes ( ) ; int getCachedFlags ( IType type ) ; IType [ ] getExtendingModules ( IType type ) ; IType [ ] getIncludingClasses ( IType type ) ; IType [ ] getRootClasses ( ) ; IType [ ] getRootModules ( ) ; IType [ ] getSubclasses ( IType type ) ; IType [ ] getSubtypes ( IType type ) ; IType getSuperclass ( IType type ) ; IType [ ] getSuperModules ( IType type ) ; IType [ ] getSupertypes ( IType type ) ; IType getType ( ) ; void refresh ( IProgressMonitor monitor ) throws RubyModelException ; void removeTypeHierarchyChangedListener ( ITypeHierarchyChangedListener listener ) ; void store ( OutputStream outputStream , IProgressMonitor monitor ) throws RubyModelException ; } package org . rubypeople . rdt . core ; import org . eclipse . core . resources . IResourceDelta ; import org . jruby . ast . Node ; public interface IRubyElementDelta { public int ADDED = ; public int REMOVED = ; public int CHANGED = ; public int F_CONTENT = ; public int F_MODIFIERS = ; public int F_CHILDREN = ; public int F_MOVED_FROM = ; public int F_MOVED_TO = ; public int F_ADDED_TO_CLASSPATH = ; public int F_REMOVED_FROM_CLASSPATH = ; public int F_CLASSPATH_REORDER = ; public int F_REORDER = ; public int F_OPENED = ; public int F_CLOSED = ; public int F_SUPER_TYPES = ; public int F_SOURCEATTACHED = ; public int F_SOURCEDETACHED = ; public int F_FINE_GRAINED = ; public int F_ARCHIVE_CONTENT_CHANGED = ; public int F_PRIMARY_WORKING_COPY = ; public int F_CLASSPATH_CHANGED = ; public int F_PRIMARY_RESOURCE = ; public int F_AST_AFFECTED = ; public int F_CATEGORIES = ; public IRubyElementDelta [ ] getAddedChildren ( ) ; public IRubyElementDelta [ ] getAffectedChildren ( ) ; public Node getRubyScriptAST ( ) ; public IRubyElementDelta [ ] getChangedChildren ( ) ; public IRubyElement getElement ( ) ; public int getFlags ( ) ; public int getKind ( ) ; public IRubyElement getMovedFromElement ( ) ; public IRubyElement getMovedToElement ( ) ; public IRubyElementDelta [ ] getRemovedChildren ( ) ; public IResourceDelta [ ] getResourceDeltas ( ) ; } package org . rubypeople . rdt . core . search ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . IRubyElement ; public interface IRubySearchScope { int SOURCES = ; int APPLICATION_LIBRARIES = ; int SYSTEM_LIBRARIES = ; int REFERENCED_PROJECTS = ; IPath [ ] enclosingProjectsAndJars ( ) ; public boolean encloses ( String resourcePath ) ; boolean encloses ( IRubyElement element ) ; } package org . rubypeople . rdt . core . search ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . WorkingCopyOwner ; import org . rubypeople . rdt . internal . core . search . BasicSearchEngine ; public class SearchEngine { private BasicSearchEngine basicEngine ; public SearchEngine ( ) { this . basicEngine = new BasicSearchEngine ( ) ; } public SearchEngine ( WorkingCopyOwner workingCopyOwner ) { this . basicEngine = new BasicSearchEngine ( workingCopyOwner ) ; } public static IRubySearchScope createWorkspaceScope ( ) { return BasicSearchEngine . createWorkspaceScope ( ) ; } public void searchAllTypeNames ( final char [ ] namespace , final char [ ] typeName , final int matchRule , int searchFor , IRubySearchScope scope , final TypeNameRequestor nameRequestor , int waitingPolicy , IProgressMonitor progressMonitor ) throws RubyModelException { this . basicEngine . searchAllTypeNames ( namespace , typeName , matchRule , searchFor , scope , nameRequestor , waitingPolicy , progressMonitor ) ; } public static IRubySearchScope createRubySearchScope ( IRubyElement [ ] elements ) { return BasicSearchEngine . createRubySearchScope ( elements ) ; } public static IRubySearchScope createRubySearchScope ( IRubyElement [ ] elements , int includeMask ) { return BasicSearchEngine . createRubySearchScope ( elements , includeMask ) ; } public static SearchParticipant getDefaultSearchParticipant ( ) { return BasicSearchEngine . getDefaultSearchParticipant ( ) ; } public void search ( SearchPattern pattern , SearchParticipant [ ] participants , IRubySearchScope scope , SearchRequestor requestor , IProgressMonitor monitor ) throws CoreException { this . basicEngine . search ( pattern , participants , scope , requestor , monitor ) ; } public static IRubySearchScope createHierarchyScope ( IType type ) throws RubyModelException { return BasicSearchEngine . createHierarchyScope ( type ) ; } } package org . rubypeople . rdt . core . search ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyElement ; public class FieldReferenceMatch extends SearchMatch { private boolean isReadAccess ; private boolean isWriteAccess ; private IRubyElement binding ; public FieldReferenceMatch ( IRubyElement enclosingElement , IRubyElement binding , int accuracy , int offset , int length , boolean isReadAccess , boolean isWriteAccess , boolean insideDocComment , SearchParticipant participant , IResource resource ) { super ( enclosingElement , accuracy , offset , length , participant , resource ) ; this . binding = binding ; this . isReadAccess = isReadAccess ; this . isWriteAccess = isWriteAccess ; setInsideDocComment ( insideDocComment ) ; } public final boolean isReadAccess ( ) { return this . isReadAccess ; } public final boolean isWriteAccess ( ) { return this . isWriteAccess ; } public IRubyElement getBinding ( ) { return this . binding ; } } package org . rubypeople . rdt . core . search ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyElement ; public class TypeReferenceMatch extends SearchMatch { private IRubyElement localElement ; private IRubyElement [ ] otherElements ; public TypeReferenceMatch ( IRubyElement enclosingElement , int accuracy , int offset , int length , SearchParticipant participant , IResource resource ) { super ( enclosingElement , accuracy , offset , length , participant , resource ) ; setInsideDocComment ( false ) ; } public final IRubyElement getLocalElement ( ) { return this . localElement ; } public final IRubyElement [ ] getOtherElements ( ) { return this . otherElements ; } public final void setLocalElement ( IRubyElement localElement ) { this . localElement = localElement ; } public final void setOtherElements ( IRubyElement [ ] otherElements ) { this . otherElements = otherElements ; } } package org . rubypeople . rdt . core . search ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . Openable ; import org . rubypeople . rdt . internal . core . index . EntryResult ; import org . rubypeople . rdt . internal . core . search . HandleFactory ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . search . indexing . InternalSearchDocument ; public abstract class SearchDocument extends InternalSearchDocument { private static HandleFactory factory = new HandleFactory ( ) ; private IRubyScript script ; private String documentPath ; private SearchParticipant participant ; public SearchDocument ( String documentPath , SearchParticipant participant ) { this . documentPath = documentPath ; this . participant = participant ; } public void addIndexEntry ( char [ ] category , char [ ] key ) { super . addIndexEntry ( category , key ) ; } public void removeAllIndexEntries ( ) { super . removeAllIndexEntries ( ) ; } public Set < String > getElementNamesOfType ( int type ) { Set < String > names = new HashSet < String > ( ) ; try { EntryResult [ ] results = index . query ( new char [ ] [ ] { getCategory ( type ) } , new char [ ] { '' } , SearchPattern . R_PATTERN_MATCH ) ; for ( int i = ; i < results . length ; i ++ ) { String name = new String ( results [ i ] . getWord ( ) ) ; names . add ( name ) ; } } catch ( IOException e ) { RubyCore . log ( e ) ; } return names ; } public List < IRubyElement > getElementsOfType ( int type ) { IRubyScript script = getScript ( ) ; return getChildrenOfType ( script , type ) ; } private IRubyScript getScript ( ) { if ( this . script == null ) { Openable openable = factory . createOpenable ( documentPath ) ; this . script = ( IRubyScript ) openable ; } return this . script ; } public final String getPath ( ) { return this . documentPath ; } private List < IRubyElement > getChildrenOfType ( IParent parent , int type ) { List < IRubyElement > elements = new ArrayList < IRubyElement > ( ) ; if ( parent == null ) return elements ; try { IRubyElement [ ] children = parent . getChildren ( ) ; if ( children == null ) return elements ; for ( int i = ; i < children . length ; i ++ ) { if ( children [ i ] . isType ( type ) ) elements . add ( children [ i ] ) ; if ( children [ i ] instanceof IParent ) { IParent childParent = ( IParent ) children [ i ] ; elements . addAll ( getChildrenOfType ( childParent , type ) ) ; } } } catch ( RubyModelException e ) { } return elements ; } public void removeElement ( IRubyElement element ) { } public void addElement ( IRubyElement element ) { addIndexEntry ( getCategory ( element ) , element . getElementName ( ) . toCharArray ( ) ) ; } private char [ ] getCategory ( IRubyElement element ) { return getCategory ( element . getElementType ( ) ) ; } private char [ ] getCategory ( int elementType ) { switch ( elementType ) { case IRubyElement . TYPE : return IIndexConstants . TYPE_DECL ; case IRubyElement . METHOD : return IIndexConstants . METHOD_DECL ; case IRubyElement . CONSTANT : case IRubyElement . GLOBAL : case IRubyElement . CLASS_VAR : case IRubyElement . INSTANCE_VAR : case IRubyElement . LOCAL_VARIABLE : return IIndexConstants . FIELD_DECL ; default : return new char [ ] ; } } public IType findType ( String name ) { return ( IType ) findElement ( IRubyElement . TYPE , name ) ; } private IRubyElement findElement ( int type , String name ) { IRubyScript script = getScript ( ) ; List < IRubyElement > children = getChildrenOfType ( script , type ) ; for ( IRubyElement element : children ) { if ( element . getElementName ( ) . equals ( name ) ) return element ; } return null ; } public abstract char [ ] getCharContents ( ) ; public final SearchParticipant getParticipant ( ) { return this . participant ; } } package org . rubypeople . rdt . core . search ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; public class CollectingSearchRequestor extends SearchRequestor { private ArrayList < SearchMatch > fFound ; public CollectingSearchRequestor ( ) { fFound = new ArrayList < SearchMatch > ( ) ; } public void acceptSearchMatch ( SearchMatch match ) throws CoreException { fFound . add ( match ) ; } public List < SearchMatch > getResults ( ) { return fFound ; } } package org . rubypeople . rdt . core . search ; import org . eclipse . core . runtime . CoreException ; public abstract class SearchRequestor { public abstract void acceptSearchMatch ( SearchMatch match ) throws CoreException ; public void beginReporting ( ) { } public void endReporting ( ) { } public void enterParticipant ( SearchParticipant participant ) { } public void exitParticipant ( SearchParticipant participant ) { } } package org . rubypeople . rdt . core . search ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyElement ; public class TypeDeclarationMatch extends SearchMatch { public TypeDeclarationMatch ( IRubyElement element , int accuracy , int offset , int length , SearchParticipant participant , IResource resource ) { super ( element , accuracy , offset , length , participant , resource ) ; } } package org . rubypeople . rdt . core . search ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyElement ; public class FieldDeclarationMatch extends SearchMatch { public FieldDeclarationMatch ( IRubyElement element , int accuracy , int offset , int length , SearchParticipant participant , IResource resource ) { super ( element , accuracy , offset , length , participant , resource ) ; } } package org . rubypeople . rdt . core . search ; import org . rubypeople . rdt . internal . core . search . processing . IJob ; public interface IRubySearchConstants { int DECLARATIONS = ; int REFERENCES = ; int ALL_OCCURRENCES = ; int READ_ACCESSES = ; int WRITE_ACCESSES = ; int IGNORE_DECLARING_TYPE = ; int TYPE = ; int METHOD = ; int CONSTRUCTOR = ; int FIELD = ; int CLASS = ; int MODULE = ; int FORCE_IMMEDIATE_SEARCH = IJob . ForceImmediate ; int CANCEL_IF_NOT_READY_TO_SEARCH = IJob . CancelIfNotReady ; int WAIT_UNTIL_READY_TO_SEARCH = IJob . WaitUntilReady ; } package org . rubypeople . rdt . core . search ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyElement ; public class MethodDeclarationMatch extends SearchMatch { public MethodDeclarationMatch ( IRubyElement element , int accuracy , int offset , int length , SearchParticipant participant , IResource resource ) { super ( element , accuracy , offset , length , participant , resource ) ; } } package org . rubypeople . rdt . core . search ; import org . rubypeople . rdt . core . IField ; import org . rubypeople . rdt . core . IImportDeclaration ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . compiler . parser . ScannerHelper ; import org . rubypeople . rdt . internal . core . LocalVariable ; import org . rubypeople . rdt . internal . core . search . MethodPatternParser ; import org . rubypeople . rdt . internal . core . search . indexing . IIndexConstants ; import org . rubypeople . rdt . internal . core . search . matching . ConstructorPattern ; import org . rubypeople . rdt . internal . core . search . matching . FieldPattern ; import org . rubypeople . rdt . internal . core . search . matching . InternalSearchPattern ; import org . rubypeople . rdt . internal . core . search . matching . LocalVariablePattern ; import org . rubypeople . rdt . internal . core . search . matching . MatchLocator ; import org . rubypeople . rdt . internal . core . search . matching . MethodPattern ; import org . rubypeople . rdt . internal . core . search . matching . OrPattern ; import org . rubypeople . rdt . internal . core . search . matching . QualifiedTypeDeclarationPattern ; import org . rubypeople . rdt . internal . core . search . matching . TypeDeclarationPattern ; import org . rubypeople . rdt . internal . core . search . matching . TypeReferencePattern ; import org . rubypeople . rdt . internal . core . util . CharOperation ; public abstract class SearchPattern extends InternalSearchPattern { public static final int R_EXACT_MATCH = ; public static final int R_PREFIX_MATCH = ; public static final int R_PATTERN_MATCH = ; public static final int R_REGEXP_MATCH = ; public static final int R_CASE_SENSITIVE = ; public static final int R_ERASURE_MATCH = ; public static final int R_EQUIVALENT_MATCH = ; public static final int R_FULL_MATCH = ; public static final int R_CAMELCASE_MATCH = ; private static final int MODE_MASK = R_EXACT_MATCH | R_PREFIX_MATCH | R_PATTERN_MATCH | R_REGEXP_MATCH ; private int matchRule ; public SearchPattern ( int matchRule ) { this . matchRule = matchRule ; if ( ( matchRule & ( R_EQUIVALENT_MATCH | R_ERASURE_MATCH ) ) == ) { this . matchRule |= R_FULL_MATCH ; } } public abstract SearchPattern getBlankPattern ( ) ; public void decodeIndexKey ( char [ ] key ) { } public char [ ] getIndexKey ( ) { return null ; } public char [ ] [ ] getIndexCategories ( ) { return CharOperation . NO_CHAR_CHAR ; } public final int getMatchRule ( ) { return this . matchRule ; } public boolean matchesDecodedKey ( SearchPattern decodedPattern ) { return true ; } public static SearchPattern createPattern ( int elementType , String stringPattern , int limitTo , int matchRule ) { switch ( elementType ) { case IRubyElement . TYPE : return createTypePattern ( stringPattern , limitTo , matchRule , IIndexConstants . TYPE_SUFFIX ) ; case IRubyElement . METHOD : return createMethodOrConstructorPattern ( stringPattern , limitTo , matchRule , false ) ; case IRubyElement . FIELD : case IRubyElement . CONSTANT : case IRubyElement . GLOBAL : case IRubyElement . CLASS_VAR : case IRubyElement . INSTANCE_VAR : return createFieldPattern ( stringPattern , limitTo , matchRule ) ; default : break ; } return null ; } private static SearchPattern createFieldPattern ( String patternString , int limitTo , int matchRule ) { String fieldName = patternString ; if ( fieldName == null ) return null ; char [ ] fieldNameChars = fieldName . toCharArray ( ) ; if ( fieldNameChars . length == && fieldNameChars [ ] == '' ) fieldNameChars = null ; char [ ] declaringTypeQualification = null , declaringTypeSimpleName = null ; char [ ] typeQualification = null , typeSimpleName = null ; boolean findDeclarations = false ; boolean readAccess = false ; boolean writeAccess = false ; switch ( limitTo ) { case IRubySearchConstants . DECLARATIONS : findDeclarations = true ; break ; case IRubySearchConstants . REFERENCES : readAccess = true ; writeAccess = true ; break ; case IRubySearchConstants . READ_ACCESSES : readAccess = true ; break ; case IRubySearchConstants . WRITE_ACCESSES : writeAccess = true ; break ; case IRubySearchConstants . ALL_OCCURRENCES : findDeclarations = true ; readAccess = true ; writeAccess = true ; break ; } return new FieldPattern ( findDeclarations , readAccess , writeAccess , fieldNameChars , declaringTypeQualification , declaringTypeSimpleName , matchRule ) ; } public boolean matchesName ( char [ ] pattern , char [ ] name ) { if ( pattern == null ) return true ; if ( name != null ) { boolean isCaseSensitive = ( this . matchRule & R_CASE_SENSITIVE ) != ; boolean isCamelCase = ( this . matchRule & R_CAMELCASE_MATCH ) != ; int matchMode = this . matchRule & MODE_MASK ; boolean sameLength = pattern . length == name . length ; boolean canBePrefix = name . length >= pattern . length ; boolean matchFirstChar = ! isCaseSensitive || pattern . length == || ( name . length > && pattern [ ] == name [ ] ) ; if ( isCamelCase && matchFirstChar && CharOperation . camelCaseMatch ( pattern , name ) ) { return true ; } switch ( matchMode ) { case R_EXACT_MATCH : case R_FULL_MATCH : if ( ! isCamelCase ) { if ( sameLength && matchFirstChar ) { return CharOperation . equals ( pattern , name , isCaseSensitive ) ; } break ; } case R_PREFIX_MATCH : if ( canBePrefix && matchFirstChar ) { return CharOperation . prefixEquals ( pattern , name , isCaseSensitive ) ; } break ; case R_PATTERN_MATCH : if ( ! isCaseSensitive ) pattern = CharOperation . toLowerCase ( pattern ) ; return CharOperation . match ( pattern , name , isCaseSensitive ) ; case R_REGEXP_MATCH : return true ; } } return false ; } private static SearchPattern createTypePattern ( String patternString , int limitTo , int matchRule , char indexSuffix ) { char [ ] typePart = null ; if ( patternString != null ) typePart = patternString . toCharArray ( ) ; char [ ] typeChars = null ; char [ ] qualificationChars = null ; int lastDotPosition = CharOperation . lastIndexOf ( "" , typePart ) ; if ( lastDotPosition >= ) { qualificationChars = CharOperation . subarray ( typePart , , lastDotPosition ) ; if ( qualificationChars . length == && qualificationChars [ ] == '' ) qualificationChars = null ; typeChars = CharOperation . subarray ( typePart , lastDotPosition + , typePart . length ) ; } else { typeChars = typePart ; } if ( typeChars != null && typeChars . length == && typeChars [ ] == '' ) { typeChars = null ; } switch ( limitTo ) { case IRubySearchConstants . DECLARATIONS : if ( qualificationChars == null ) return new TypeDeclarationPattern ( null , null , typeChars , indexSuffix , matchRule ) ; return new QualifiedTypeDeclarationPattern ( qualificationChars , typeChars , indexSuffix , matchRule ) ; case IRubySearchConstants . REFERENCES : return new TypeReferencePattern ( qualificationChars , typeChars , matchRule ) ; case IRubySearchConstants . ALL_OCCURRENCES : return new OrPattern ( new QualifiedTypeDeclarationPattern ( qualificationChars , typeChars , indexSuffix , matchRule ) , new TypeReferencePattern ( qualificationChars , typeChars , matchRule ) ) ; } return null ; } private static SearchPattern createMethodOrConstructorPattern ( String patternString , int limitTo , int matchRule , boolean isConstructor ) { MethodPatternParser parser = new MethodPatternParser ( ) ; parser . parse ( patternString ) ; char [ ] selectorChars = parser . getSelector ( ) ; char [ ] [ ] parameterNames = parser . getParameterNames ( ) ; char [ ] declaringTypeSimpleName = parser . getTypeSimpleName ( ) ; char [ ] declaringTypeQualification = parser . getQualifiedTypeName ( ) ; boolean findDeclarations = true ; boolean findReferences = true ; switch ( limitTo ) { case IRubySearchConstants . DECLARATIONS : findReferences = false ; break ; case IRubySearchConstants . REFERENCES : findDeclarations = false ; break ; case IRubySearchConstants . ALL_OCCURRENCES : break ; } if ( isConstructor ) { return new ConstructorPattern ( findDeclarations , findReferences , declaringTypeSimpleName , declaringTypeQualification , parameterNames , matchRule ) ; } else { return new MethodPattern ( findDeclarations , findReferences , selectorChars , declaringTypeQualification , declaringTypeSimpleName , parameterNames , matchRule ) ; } } public static final boolean camelCaseMatch ( String pattern , String name ) { if ( pattern == null ) return true ; if ( name == null ) return false ; return camelCaseMatch ( pattern , , pattern . length ( ) , name , , name . length ( ) ) ; } public static final boolean camelCaseMatch ( String pattern , int patternStart , int patternEnd , String name , int nameStart , int nameEnd ) { if ( name == null ) return false ; if ( pattern == null ) return true ; if ( patternEnd < ) patternEnd = pattern . length ( ) ; if ( nameEnd < ) nameEnd = name . length ( ) ; if ( patternEnd <= patternStart ) return nameEnd <= nameStart ; if ( nameEnd <= nameStart ) return false ; if ( name . charAt ( nameStart ) != pattern . charAt ( patternStart ) ) { return false ; } char patternChar , nameChar ; int iPattern = patternStart ; int iName = nameStart ; while ( true ) { iPattern ++ ; iName ++ ; if ( iPattern == patternEnd ) { return true ; } if ( iName == nameEnd ) { return false ; } if ( ( patternChar = pattern . charAt ( iPattern ) ) == name . charAt ( iName ) ) { continue ; } if ( patternChar < ScannerHelper . MAX_OBVIOUS ) { if ( ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ patternChar ] & ScannerHelper . C_UPPER_LETTER ) == ) { return false ; } } else if ( Character . isJavaIdentifierPart ( patternChar ) && ! Character . isUpperCase ( patternChar ) ) { return false ; } while ( true ) { if ( iName == nameEnd ) { return false ; } nameChar = name . charAt ( iName ) ; if ( nameChar < ScannerHelper . MAX_OBVIOUS ) { if ( ( ScannerHelper . OBVIOUS_IDENT_CHAR_NATURES [ nameChar ] & ( ScannerHelper . C_LOWER_LETTER | ScannerHelper . C_SPECIAL | ScannerHelper . C_DIGIT ) ) != ) { iName ++ ; } else if ( patternChar != nameChar ) { return false ; } else { break ; } } else if ( Character . isJavaIdentifierPart ( nameChar ) && ! Character . isUpperCase ( nameChar ) ) { iName ++ ; } else if ( patternChar != nameChar ) { return false ; } else { break ; } } } } public static int validateMatchRule ( String stringPattern , int matchRule ) { if ( ( matchRule & R_REGEXP_MATCH ) != ) { if ( ( matchRule & R_PATTERN_MATCH ) != || ( matchRule & R_PREFIX_MATCH ) != || ( matchRule & R_CAMELCASE_MATCH ) != ) { return - ; } } int starIndex = stringPattern . indexOf ( '' ) ; int questionIndex = stringPattern . indexOf ( '' ) ; if ( starIndex < && questionIndex < ) { matchRule &= ~ R_PATTERN_MATCH ; } else { matchRule |= R_PATTERN_MATCH ; } if ( ( matchRule & R_PATTERN_MATCH ) != ) { matchRule &= ~ R_CAMELCASE_MATCH ; matchRule &= ~ R_PREFIX_MATCH ; } if ( ( matchRule & R_CAMELCASE_MATCH ) != ) { int length = stringPattern . length ( ) ; boolean validCamelCase = true ; boolean uppercase = false ; for ( int i = ; i < length && validCamelCase ; i ++ ) { char ch = stringPattern . charAt ( i ) ; validCamelCase = ScannerHelper . isJavaIdentifierStart ( ch ) ; if ( ! uppercase ) uppercase = ScannerHelper . isUpperCase ( ch ) ; } validCamelCase = validCamelCase && uppercase ; if ( validCamelCase ) { if ( ( matchRule & R_PREFIX_MATCH ) != ) { if ( ( matchRule & R_CASE_SENSITIVE ) != ) { matchRule &= ~ R_PREFIX_MATCH ; matchRule &= ~ R_CASE_SENSITIVE ; } } } else { matchRule &= ~ R_CAMELCASE_MATCH ; if ( ( matchRule & R_PREFIX_MATCH ) == ) { matchRule |= R_PREFIX_MATCH ; matchRule |= R_CASE_SENSITIVE ; } } } return matchRule ; } public static SearchPattern createPattern ( String stringPattern , int searchFor , int limitTo , int matchRule ) { if ( stringPattern == null || stringPattern . length ( ) == ) return null ; if ( ( matchRule = validateMatchRule ( stringPattern , matchRule ) ) == - ) { return null ; } switch ( searchFor ) { case IRubySearchConstants . CLASS : return createTypePattern ( stringPattern , limitTo , matchRule , IIndexConstants . CLASS_SUFFIX ) ; case IRubySearchConstants . MODULE : return createTypePattern ( stringPattern , limitTo , matchRule , IIndexConstants . MODULE_SUFFIX ) ; case IRubySearchConstants . TYPE : return createTypePattern ( stringPattern , limitTo , matchRule , IIndexConstants . TYPE_SUFFIX ) ; case IRubySearchConstants . METHOD : return createMethodOrConstructorPattern ( stringPattern , limitTo , matchRule , false ) ; case IRubySearchConstants . CONSTRUCTOR : return createMethodOrConstructorPattern ( stringPattern , limitTo , matchRule , true ) ; case IRubySearchConstants . FIELD : return createFieldPattern ( stringPattern , limitTo , matchRule ) ; } return null ; } public static SearchPattern createPattern ( IRubyElement element , int limitTo , int matchRule ) { SearchPattern searchPattern = null ; int lastDot ; boolean ignoreDeclaringType = true ; int maskedLimitTo = limitTo ; if ( maskedLimitTo == IRubySearchConstants . DECLARATIONS || maskedLimitTo == IRubySearchConstants . ALL_OCCURRENCES ) { ignoreDeclaringType = ( limitTo & IRubySearchConstants . IGNORE_DECLARING_TYPE ) != ; } char [ ] declaringSimpleName = null ; char [ ] declaringQualification = null ; switch ( element . getElementType ( ) ) { case IRubyElement . FIELD : case IRubyElement . INSTANCE_VAR : case IRubyElement . CONSTANT : case IRubyElement . CLASS_VAR : IField field = ( IField ) element ; if ( ! ignoreDeclaringType ) { IType declaringClass = field . getDeclaringType ( ) ; declaringSimpleName = declaringClass . getElementName ( ) . toCharArray ( ) ; declaringQualification = declaringClass . getSourceFolder ( ) . getElementName ( ) . toCharArray ( ) ; char [ ] [ ] enclosingNames = enclosingTypeNames ( declaringClass ) ; if ( enclosingNames . length > ) { declaringQualification = CharOperation . concat ( declaringQualification , CharOperation . concatWith ( enclosingNames , '' ) , '' ) ; } } char [ ] name = field . getElementName ( ) . toCharArray ( ) ; boolean findDeclarations = false ; boolean readAccess = false ; boolean writeAccess = false ; switch ( maskedLimitTo ) { case IRubySearchConstants . DECLARATIONS : findDeclarations = true ; break ; case IRubySearchConstants . REFERENCES : readAccess = true ; writeAccess = true ; break ; case IRubySearchConstants . READ_ACCESSES : readAccess = true ; break ; case IRubySearchConstants . WRITE_ACCESSES : writeAccess = true ; break ; case IRubySearchConstants . ALL_OCCURRENCES : findDeclarations = true ; readAccess = true ; writeAccess = true ; break ; } searchPattern = new FieldPattern ( findDeclarations , readAccess , writeAccess , name , declaringQualification , declaringSimpleName , matchRule ) ; break ; case IRubyElement . IMPORT_DECLARATION : String elementName = element . getElementName ( ) ; lastDot = elementName . lastIndexOf ( '' ) ; if ( lastDot == - ) return null ; IImportDeclaration importDecl = ( IImportDeclaration ) element ; searchPattern = createTypePattern ( elementName . substring ( lastDot + ) . toCharArray ( ) , elementName . substring ( , lastDot ) . toCharArray ( ) , null , null , null , maskedLimitTo , matchRule ) ; break ; case IRubyElement . LOCAL_VARIABLE : LocalVariable localVar = ( LocalVariable ) element ; boolean findVarDeclarations = false ; boolean findVarReadAccess = false ; boolean findVarWriteAccess = false ; switch ( maskedLimitTo ) { case IRubySearchConstants . DECLARATIONS : findVarDeclarations = true ; break ; case IRubySearchConstants . REFERENCES : findVarReadAccess = true ; findVarWriteAccess = true ; break ; case IRubySearchConstants . READ_ACCESSES : findVarReadAccess = true ; break ; case IRubySearchConstants . WRITE_ACCESSES : findVarWriteAccess = true ; break ; case IRubySearchConstants . ALL_OCCURRENCES : findVarDeclarations = true ; findVarReadAccess = true ; findVarWriteAccess = true ; break ; } searchPattern = new LocalVariablePattern ( findVarDeclarations , findVarReadAccess , findVarWriteAccess , localVar , matchRule ) ; break ; case IRubyElement . METHOD : IMethod method = ( IMethod ) element ; boolean isConstructor = method . isConstructor ( ) ; IType declaringClass = method . getDeclaringType ( ) ; if ( ignoreDeclaringType ) { if ( isConstructor ) declaringSimpleName = declaringClass . getElementName ( ) . toCharArray ( ) ; } else { declaringSimpleName = declaringClass . getElementName ( ) . toCharArray ( ) ; declaringQualification = declaringClass . getSourceFolder ( ) . getElementName ( ) . toCharArray ( ) ; char [ ] [ ] enclosingNames = enclosingTypeNames ( declaringClass ) ; if ( enclosingNames . length > ) { declaringQualification = CharOperation . concat ( declaringQualification , CharOperation . concatWith ( enclosingNames , '' ) , '' ) ; } } char [ ] selector = method . getElementName ( ) . toCharArray ( ) ; String [ ] parameterNames ; try { parameterNames = method . getParameterNames ( ) ; } catch ( RubyModelException e ) { return null ; } int paramCount = parameterNames . length ; char [ ] [ ] parameterSimpleNames = new char [ paramCount ] [ ] ; for ( int i = ; i < paramCount ; i ++ ) { parameterSimpleNames [ i ] = parameterNames [ i ] . toCharArray ( ) ; } boolean findMethodDeclarations = true ; boolean findMethodReferences = true ; switch ( maskedLimitTo ) { case IRubySearchConstants . DECLARATIONS : findMethodReferences = false ; break ; case IRubySearchConstants . REFERENCES : findMethodDeclarations = false ; break ; case IRubySearchConstants . ALL_OCCURRENCES : break ; } if ( isConstructor ) { searchPattern = new ConstructorPattern ( findMethodDeclarations , findMethodReferences , declaringSimpleName , declaringQualification , parameterSimpleNames , method , matchRule ) ; } else { searchPattern = new MethodPattern ( findMethodDeclarations , findMethodReferences , selector , declaringQualification , declaringSimpleName , parameterSimpleNames , method , matchRule ) ; } break ; case IRubyElement . TYPE : IType type = ( IType ) element ; searchPattern = createTypePattern ( type . getElementName ( ) . toCharArray ( ) , type . getSourceFolder ( ) . getElementName ( ) . toCharArray ( ) , ignoreDeclaringType ? null : enclosingTypeNames ( type ) , null , type , maskedLimitTo , matchRule ) ; break ; } if ( searchPattern != null ) MatchLocator . setFocus ( searchPattern , element ) ; return searchPattern ; } private static SearchPattern createTypePattern ( char [ ] simpleName , char [ ] packageName , char [ ] [ ] enclosingTypeNames , String typeSignature , IType type , int limitTo , int matchRule ) { switch ( limitTo ) { case IRubySearchConstants . DECLARATIONS : return new TypeDeclarationPattern ( packageName , enclosingTypeNames , simpleName , IIndexConstants . TYPE_SUFFIX , matchRule ) ; case IRubySearchConstants . REFERENCES : return new TypeReferencePattern ( CharOperation . concatWith ( enclosingTypeNames , "" ) , simpleName , matchRule ) ; case IRubySearchConstants . ALL_OCCURRENCES : return new OrPattern ( new TypeDeclarationPattern ( packageName , enclosingTypeNames , simpleName , IIndexConstants . TYPE_SUFFIX , matchRule ) , new TypeReferencePattern ( CharOperation . concatWith ( enclosingTypeNames , "" ) , simpleName , matchRule ) ) ; } return null ; } private static char [ ] [ ] enclosingTypeNames ( IType type ) { IRubyElement parent = type . getParent ( ) ; switch ( parent . getElementType ( ) ) { case IRubyElement . SCRIPT : return CharOperation . NO_CHAR_CHAR ; case IRubyElement . FIELD : case IRubyElement . METHOD : IType declaringClass = ( ( IMember ) parent ) . getDeclaringType ( ) ; return CharOperation . arrayConcat ( enclosingTypeNames ( declaringClass ) , new char [ ] [ ] { declaringClass . getElementName ( ) . toCharArray ( ) , IIndexConstants . ONE_STAR } ) ; case IRubyElement . TYPE : return CharOperation . arrayConcat ( enclosingTypeNames ( ( IType ) parent ) , parent . getElementName ( ) . toCharArray ( ) ) ; default : return null ; } } } package org . rubypeople . rdt . core . search ; import java . util . List ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyElement ; public class MethodReferenceMatch extends SearchMatch { private boolean constructor ; private IRubyElement binding ; private List < String > arguments ; public MethodReferenceMatch ( IRubyElement enclosingElement , int accuracy , int offset , int length , boolean insideDocComment , SearchParticipant participant , IResource resource ) { super ( enclosingElement , accuracy , offset , length , participant , resource ) ; setInsideDocComment ( insideDocComment ) ; } public MethodReferenceMatch ( IRubyElement enclosingElement , IRubyElement binding , List < String > args , int accuracy , int offset , int length , boolean constructor , boolean insideDocComment , SearchParticipant participant , IResource resource ) { this ( enclosingElement , accuracy , offset , length , insideDocComment , participant , resource ) ; this . arguments = args ; this . constructor = constructor ; this . binding = binding ; } public final boolean isConstructor ( ) { return this . constructor ; } public IRubyElement getBinding ( ) { return this . binding ; } public List < String > getArguments ( ) { return this . arguments ; } } package org . rubypeople . rdt . core . search ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; public abstract class SearchParticipant { public abstract void indexDocument ( SearchDocument document , IPath indexLocation ) ; public abstract SearchDocument getDocument ( String documentPath ) ; public abstract IPath [ ] selectIndexes ( SearchPattern pattern , IRubySearchScope scope ) ; public abstract void locateMatches ( SearchDocument [ ] documents , SearchPattern pattern , IRubySearchScope scope , SearchRequestor requestor , IProgressMonitor monitor ) throws CoreException ; public void beginSearching ( ) { } public void doneSearching ( ) { } public String getDescription ( ) { return "" ; } } package org . rubypeople . rdt . core . search ; public abstract class TypeNameRequestor { public void acceptType ( boolean isModule , char [ ] packageName , char [ ] simpleTypeName , char [ ] [ ] enclosingTypeNames , String path ) { } } package org . rubypeople . rdt . core . search ; import org . eclipse . core . resources . IResource ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . core . RubyElement ; public class SearchMatch { public static final int A_ACCURATE = ; public static final int A_INACCURATE = ; private Object element ; private int length ; private int offset ; private int accuracy ; private SearchParticipant participant ; private IResource resource ; private boolean insideDocComment = false ; private final static int ALL_GENERIC_FLAVORS = SearchPattern . R_FULL_MATCH | SearchPattern . R_EQUIVALENT_MATCH | SearchPattern . R_ERASURE_MATCH ; private int rule = ALL_GENERIC_FLAVORS ; private boolean raw = false ; private boolean implicit = false ; public SearchMatch ( IRubyElement element , int accuracy , int offset , int length , SearchParticipant participant , IResource resource ) { this . element = element ; this . offset = offset ; this . length = length ; this . accuracy = accuracy & A_INACCURATE ; if ( accuracy > A_INACCURATE ) { int genericFlavors = accuracy & ALL_GENERIC_FLAVORS ; if ( genericFlavors > ) { this . rule &= ~ ALL_GENERIC_FLAVORS ; } this . rule |= accuracy & ~ A_INACCURATE ; } this . participant = participant ; this . resource = resource ; } public final int getAccuracy ( ) { return this . accuracy ; } public final Object getElement ( ) { return this . element ; } public final int getLength ( ) { return this . length ; } public final int getOffset ( ) { return this . offset ; } public final SearchParticipant getParticipant ( ) { return this . participant ; } public final IResource getResource ( ) { return this . resource ; } public final int getRule ( ) { return this . rule ; } public final boolean isEquivalent ( ) { return isErasure ( ) && ( this . rule & SearchPattern . R_EQUIVALENT_MATCH ) != ; } public final boolean isErasure ( ) { return ( this . rule & SearchPattern . R_ERASURE_MATCH ) != ; } public final boolean isExact ( ) { return isEquivalent ( ) && ( this . rule & SearchPattern . R_FULL_MATCH ) != ; } public final boolean isImplicit ( ) { return this . implicit ; } public final boolean isRaw ( ) { return this . raw ; } public final boolean isInsideDocComment ( ) { return this . insideDocComment ; } public final void setAccuracy ( int accuracy ) { this . accuracy = accuracy ; } public final void setElement ( Object element ) { this . element = element ; } public final void setInsideDocComment ( boolean insideDoc ) { this . insideDocComment = insideDoc ; } public final void setImplicit ( boolean implicit ) { this . implicit = implicit ; } public final void setLength ( int length ) { this . length = length ; } public final void setOffset ( int offset ) { this . offset = offset ; } public final void setParticipant ( SearchParticipant participant ) { this . participant = participant ; } public final void setResource ( IResource resource ) { this . resource = resource ; } public final void setRule ( int rule ) { this . rule = rule ; } public final void setRaw ( boolean raw ) { this . raw = raw ; } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( "" ) ; buffer . append ( this . accuracy == A_ACCURATE ? "" : "" ) ; buffer . append ( "" ) ; if ( ( this . rule & SearchPattern . R_FULL_MATCH ) != ) { buffer . append ( "" ) ; } else if ( ( this . rule & SearchPattern . R_EQUIVALENT_MATCH ) != ) { buffer . append ( "" ) ; } else if ( ( this . rule & SearchPattern . R_ERASURE_MATCH ) != ) { buffer . append ( "" ) ; } buffer . append ( "" ) ; buffer . append ( this . raw ) ; buffer . append ( "" ) ; buffer . append ( this . offset ) ; buffer . append ( "" ) ; buffer . append ( this . length ) ; if ( this . element != null ) { buffer . append ( "" ) ; buffer . append ( ( ( RubyElement ) getElement ( ) ) . toStringWithAncestors ( ) ) ; } buffer . append ( "" ) ; return buffer . toString ( ) ; } } package org . rubypeople . rdt . core ; import java . util . EventObject ; public class ElementChangedEvent extends EventObject { public static final int POST_CHANGE = ; public static final int PRE_AUTO_BUILD = ; public static final int POST_RECONCILE = ; private static final long serialVersionUID = - ; private int type ; public ElementChangedEvent ( IRubyElementDelta delta , int type ) { super ( delta ) ; this . type = type ; } public IRubyElementDelta getDelta ( ) { return ( IRubyElementDelta ) this . source ; } public int getType ( ) { return this . type ; } } package org . rubypeople . rdt . astviewer ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static Activator plugin ; public Activator ( ) { super ( ) ; } public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static Activator getDefault ( ) { return plugin ; } public static ImageDescriptor getImageDescriptor ( String path ) { return imageDescriptorFromPlugin ( PLUGIN_ID , path ) ; } } package org . rubypeople . rdt . astviewer . preferences ; public class PreferenceConstants { public static final String P_SHOW_NEWLINE = "" ; } package org . rubypeople . rdt . astviewer . preferences ; import org . eclipse . jface . preference . * ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . IWorkbench ; import org . rubypeople . rdt . astviewer . Activator ; public class AstViewerPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public AstViewerPreferencePage ( ) { super ( GRID ) ; setPreferenceStore ( Activator . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( "" ) ; } public void createFieldEditors ( ) { addField ( new BooleanFieldEditor ( PreferenceConstants . P_SHOW_NEWLINE , "" , getFieldEditorParent ( ) ) ) ; } public void init ( @ SuppressWarnings ( "" ) IWorkbench workbench ) { } } package org . rubypeople . rdt . astviewer . preferences ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . jface . preference . IPreferenceStore ; import org . rubypeople . rdt . astviewer . Activator ; public class PreferenceInitializer extends AbstractPreferenceInitializer { public void initializeDefaultPreferences ( ) { IPreferenceStore store = Activator . getDefault ( ) . getPreferenceStore ( ) ; store . setDefault ( PreferenceConstants . P_SHOW_NEWLINE , true ) ; } } package org . rubypeople . rdt . astviewer . views ; import java . util . ArrayList ; import java . util . Iterator ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; public class AstUtility { public static ArrayList < Node > findAllNodes ( Node rootNode ) { ArrayList < Node > nodes = new ArrayList < Node > ( ) ; if ( rootNode == null ) return nodes ; nodes . add ( rootNode ) ; for ( Object o : rootNode . childNodes ( ) ) { nodes . addAll ( findAllNodes ( ( Node ) o ) ) ; } return nodes ; } public static String nodeList ( ArrayList < Node > nodes ) { StringBuilder str = new StringBuilder ( ) ; for ( Node node : nodes ) { String name = node . getClass ( ) . getName ( ) ; str . append ( name . substring ( name . lastIndexOf ( "" ) + , name . length ( ) ) ) ; str . append ( "" ) ; } str . deleteCharAt ( str . length ( ) - ) ; str . deleteCharAt ( str . length ( ) - ) ; return str . toString ( ) ; } public static String formatedPosition ( Node n ) { if ( n == null || n . getPosition ( ) == null ) return "" ; StringBuilder posString = new StringBuilder ( ) ; posString . append ( "" ) ; posString . append ( n . getPosition ( ) . getStartLine ( ) ) ; posString . append ( "" ) ; posString . append ( n . getPosition ( ) . getEndLine ( ) ) ; posString . append ( "" ) ; posString . append ( n . getPosition ( ) . getStartOffset ( ) ) ; posString . append ( "" ) ; posString . append ( n . getPosition ( ) . getEndOffset ( ) ) ; posString . append ( "" ) ; return posString . toString ( ) ; } public static String nodeListJRubyFormat ( ArrayList < Node > nodes ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "" ) ; Iterator nodeIter = nodes . iterator ( ) ; while ( nodeIter . hasNext ( ) ) { Node node = ( Node ) nodeIter . next ( ) ; if ( node instanceof NewlineNode || node instanceof RootNode ) { builder . append ( "" ) ; continue ; } builder . append ( "" ) ; builder . append ( node . getClass ( ) . getSimpleName ( ) ) ; builder . append ( "" ) ; builder . append ( node . getPosition ( ) . getStartLine ( ) ) ; builder . append ( "" ) ; builder . append ( node . getPosition ( ) . getEndLine ( ) ) ; builder . append ( "" ) ; builder . append ( node . getPosition ( ) . getStartOffset ( ) ) ; builder . append ( "" ) ; builder . append ( node . getPosition ( ) . getEndOffset ( ) ) ; builder . append ( "" ) ; if ( nodeIter . hasNext ( ) ) { builder . append ( "" ) ; } } builder . append ( "" ) ; return builder . toString ( ) ; } } package org . rubypeople . rdt . astviewer . views ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . console . ConsolePlugin ; import org . eclipse . ui . console . IConsole ; import org . eclipse . ui . console . IConsoleConstants ; import org . eclipse . ui . console . IConsoleManager ; import org . eclipse . ui . console . IConsoleView ; import org . eclipse . ui . console . MessageConsole ; import org . eclipse . ui . console . MessageConsoleStream ; public class AstViewConsole { private static final String name = "" ; private static MessageConsole findConsole ( String name ) { ConsolePlugin plugin = ConsolePlugin . getDefault ( ) ; IConsoleManager conMan = plugin . getConsoleManager ( ) ; IConsole [ ] existing = conMan . getConsoles ( ) ; for ( int i = ; i < existing . length ; i ++ ) if ( name . equals ( existing [ i ] . getName ( ) ) ) return ( MessageConsole ) existing [ i ] ; MessageConsole myConsole = new MessageConsole ( name , null ) ; conMan . addConsoles ( new IConsole [ ] { myConsole } ) ; return myConsole ; } public static void print ( String text ) { revealConsole ( ) ; MessageConsole myConsole = findConsole ( name ) ; MessageConsoleStream out = myConsole . newMessageStream ( ) ; out . println ( text ) ; } private static void revealConsole ( ) { IConsole myConsole = findConsole ( name ) ; IWorkbenchPage page = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) ; String id = IConsoleConstants . ID_CONSOLE_VIEW ; IConsoleView view ; try { view = ( IConsoleView ) page . showView ( id ) ; view . display ( myConsole ) ; } catch ( PartInitException e ) { return ; } } } package org . rubypeople . rdt . astviewer . views ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . TreeItem ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . dialogs . FilteredTree ; import org . eclipse . ui . dialogs . PatternFilter ; import org . eclipse . ui . part . DrillDownAdapter ; import org . eclipse . ui . part . ViewPart ; import org . jruby . ast . Node ; import org . rubypeople . rdt . astviewer . Activator ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; public class AstView extends ViewPart { private TreeViewer viewer ; private DrillDownAdapter drillDownAdapter ; private Action refreshAction ; private Action dumpToConsoleAction ; private Action dumpJRubyTestFormatAction ; private Action doubleClickAction ; private Action clickAction ; private ViewContentProvider viewContentProvider ; private SashForm sashForm ; private SourceViewer detailsViewer ; public void createPartControl ( Composite parent ) { sashForm = new SashForm ( parent , SWT . NONE ) ; sashForm . setOrientation ( SWT . VERTICAL ) ; PatternFilter patternFilter = new PatternFilter ( ) ; final FilteredTree filter = new FilteredTree ( sashForm , SWT . MULTI | SWT . H_SCROLL | SWT . V_SCROLL , patternFilter ) ; viewer = filter . getViewer ( ) ; drillDownAdapter = new DrillDownAdapter ( viewer ) ; viewContentProvider = new ViewContentProvider ( getViewSite ( ) ) ; viewer . setContentProvider ( viewContentProvider ) ; viewer . setLabelProvider ( new ViewLabelProvider ( ) ) ; viewer . setInput ( getViewSite ( ) ) ; makeActions ( ) ; hookContextMenu ( ) ; hookClickAction ( ) ; hookDoubleClickAction ( ) ; contributeToActionBars ( ) ; viewer . setAutoExpandLevel ( TreeViewer . ALL_LEVELS ) ; detailsViewer = new SourceViewer ( sashForm , null , SWT . V_SCROLL | SWT . H_SCROLL ) ; detailsViewer . setEditable ( false ) ; detailsViewer . setDocument ( new Document ( ) ) ; Control control = detailsViewer . getControl ( ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; control . setLayoutData ( gd ) ; sashForm . setWeights ( new int [ ] { , } ) ; } private void hookContextMenu ( ) { MenuManager menuMgr = new MenuManager ( "" ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager manager ) { AstView . this . fillContextMenu ( manager ) ; } } ) ; Menu menu = menuMgr . createContextMenu ( viewer . getControl ( ) ) ; viewer . getControl ( ) . setMenu ( menu ) ; getSite ( ) . registerContextMenu ( menuMgr , viewer ) ; } private void contributeToActionBars ( ) { IActionBars bars = getViewSite ( ) . getActionBars ( ) ; fillLocalPullDown ( bars . getMenuManager ( ) ) ; fillLocalToolBar ( bars . getToolBarManager ( ) ) ; } private void fillLocalPullDown ( IMenuManager manager ) { manager . add ( refreshAction ) ; manager . add ( dumpToConsoleAction ) ; manager . add ( dumpJRubyTestFormatAction ) ; } private void fillContextMenu ( IMenuManager manager ) { manager . add ( refreshAction ) ; manager . add ( dumpToConsoleAction ) ; drillDownAdapter . addNavigationActions ( manager ) ; manager . add ( new Separator ( IWorkbenchActionConstants . MB_ADDITIONS ) ) ; } private void fillLocalToolBar ( IToolBarManager manager ) { manager . add ( refreshAction ) ; manager . add ( dumpToConsoleAction ) ; manager . add ( dumpJRubyTestFormatAction ) ; drillDownAdapter . addNavigationActions ( manager ) ; } private void makeActions ( ) { makeRefreshAction ( ) ; makeDumpAction ( ) ; makeDumpJRubyFormatAction ( ) ; } private void makeDumpJRubyFormatAction ( ) { dumpJRubyTestFormatAction = new Action ( ) { public void run ( ) { AstViewConsole . print ( AstUtility . nodeListJRubyFormat ( AstUtility . findAllNodes ( getRootNode ( ) ) ) ) ; AstViewConsole . print ( "" ) ; AstViewConsole . print ( textEditorContentToString ( ) . toString ( ) . trim ( ) ) ; AstViewConsole . print ( "" ) ; } private StringBuilder textEditorContentToString ( ) { IEditorInput editorInput = getEditor ( ) . getEditorInput ( ) ; IFile aFile = null ; if ( editorInput instanceof IFileEditorInput ) { aFile = ( ( IFileEditorInput ) editorInput ) . getFile ( ) ; } BufferedReader br = null ; StringBuilder sb = new StringBuilder ( ) ; try { br = new BufferedReader ( new InputStreamReader ( aFile . getContents ( ) ) ) ; String line = null ; while ( ( line = br . readLine ( ) ) != null ) { sb . append ( line + "" ) ; } br . close ( ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return sb ; } } ; dumpJRubyTestFormatAction . setText ( "" ) ; dumpJRubyTestFormatAction . setToolTipText ( "" ) ; dumpJRubyTestFormatAction . setImageDescriptor ( Activator . getImageDescriptor ( "" ) ) ; } private void makeDumpAction ( ) { dumpToConsoleAction = new Action ( ) { public void run ( ) { AstViewConsole . print ( AstUtility . nodeList ( AstUtility . findAllNodes ( getSelectedNode ( ) ) ) ) ; } } ; dumpToConsoleAction . setText ( "" ) ; dumpToConsoleAction . setToolTipText ( "" ) ; dumpToConsoleAction . setImageDescriptor ( Activator . getImageDescriptor ( "" ) ) ; } private void makeRefreshAction ( ) { refreshAction = new Action ( ) { public void run ( ) { viewContentProvider . forceUpdateContent ( ) ; viewer . setInput ( getViewSite ( ) ) ; viewer . setAutoExpandLevel ( TreeViewer . ALL_LEVELS ) ; } } ; refreshAction . setText ( "" ) ; refreshAction . setToolTipText ( "" ) ; refreshAction . setImageDescriptor ( Activator . getImageDescriptor ( "" ) ) ; } private void setSelection ( RubyEditor editor , Node n ) { if ( n == null || n . getPosition ( ) == null ) return ; editor . selectAndReveal ( n . getPosition ( ) . getStartOffset ( ) , n . getPosition ( ) . getEndOffset ( ) - n . getPosition ( ) . getStartOffset ( ) ) ; } private void hookClickAction ( ) { clickAction = new Action ( ) { public void run ( ) { detailsViewer . getDocument ( ) . set ( AstUtility . formatedPosition ( getSelectedNode ( ) ) ) ; } } ; viewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( @ SuppressWarnings ( "" ) SelectionChangedEvent event ) { clickAction . run ( ) ; } } ) ; } private Node getSelectedNode ( ) { TreeItem [ ] selection = viewer . getTree ( ) . getSelection ( ) ; if ( selection . length <= ) return null ; return ( ( TreeObject ) selection [ ] . getData ( ) ) . getNode ( ) ; } private Node getRootNode ( ) { TreeItem root = viewer . getTree ( ) . getItem ( ) ; return ( ( TreeObject ) root . getData ( ) ) . getNode ( ) ; } private RubyEditor getEditor ( ) { return ( RubyEditor ) PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . getActiveEditor ( ) ; } private void hookDoubleClickAction ( ) { doubleClickAction = new Action ( ) { public void run ( ) { setSelection ( getEditor ( ) , getSelectedNode ( ) ) ; } } ; viewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( @ SuppressWarnings ( "" ) DoubleClickEvent event ) { doubleClickAction . run ( ) ; } } ) ; } public void setFocus ( ) { viewer . getControl ( ) . setFocus ( ) ; } } package org . rubypeople . rdt . astviewer . views ; import org . eclipse . core . runtime . IAdaptable ; import org . jruby . ast . Node ; class TreeObject implements IAdaptable { private Node node ; private TreeParent parent ; public Node getNode ( ) { return node ; } public TreeObject ( Node n ) { this . node = n ; } public String getName ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( node . getClass ( ) . toString ( ) ) ; return builder . toString ( ) ; } public void setParent ( TreeParent parent ) { this . parent = parent ; } public TreeParent getParent ( ) { return parent ; } public String toString ( ) { return getName ( ) ; } public Object getAdapter ( @ SuppressWarnings ( "" ) Class key ) { return null ; } } package org . rubypeople . rdt . astviewer . views ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . eclipse . ui . ISharedImages ; import org . eclipse . ui . PlatformUI ; class ViewLabelProvider extends LabelProvider { public String getText ( Object obj ) { String text = obj . toString ( ) . substring ( obj . toString ( ) . lastIndexOf ( '' ) + ) ; if ( text . endsWith ( "" ) ) text = text . substring ( , text . length ( ) - "" . length ( ) ) ; return text ; } public Image getImage ( Object obj ) { String imageKey = ISharedImages . IMG_OBJ_ELEMENT ; if ( obj instanceof TreeParent ) imageKey = ISharedImages . IMG_OBJ_FOLDER ; return PlatformUI . getWorkbench ( ) . getSharedImages ( ) . getImage ( imageKey ) ; } } package org . rubypeople . rdt . astviewer . views ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . IStorageEditorInput ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PlatformUI ; import org . jruby . ast . CommentNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . common . NullWarnings ; import org . jruby . parser . DefaultRubyParser ; import org . jruby . parser . RubyParserPool ; import org . rubypeople . rdt . astviewer . Activator ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . Util ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; class ViewContentProvider implements IStructuredContentProvider , ITreeContentProvider { private TreeParent invisibleRoot ; private IViewSite viewSite ; private RubyEditor editor ; private DefaultRubyParser parser ; private boolean showNewline ; public ViewContentProvider ( IViewSite viewSite ) { this . viewSite = viewSite ; parser = RubyParserPool . getInstance ( ) . borrowParser ( ) ; parser . setWarnings ( new NullWarnings ( ) ) ; } public void inputChanged ( @ SuppressWarnings ( "" ) Viewer v , @ SuppressWarnings ( "" ) Object oldInput , @ SuppressWarnings ( "" ) Object newInput ) { } public void dispose ( ) { RubyParserPool . getInstance ( ) . returnParser ( parser ) ; } protected IFile getFile ( ) { IEditorInput input = editor . getEditorInput ( ) ; if ( input instanceof IFileEditorInput ) { return ( ( IFileEditorInput ) input ) . getFile ( ) ; } return null ; } public Object [ ] getElements ( Object parent ) { if ( parent . equals ( viewSite ) ) { if ( invisibleRoot == null ) initialize ( ) ; return getChildren ( invisibleRoot ) ; } return getChildren ( parent ) ; } public Object getParent ( Object child ) { if ( child instanceof TreeObject ) { return ( ( TreeObject ) child ) . getParent ( ) ; } return null ; } public Object [ ] getChildren ( Object parent ) { if ( parent instanceof TreeParent ) { return ( ( TreeParent ) parent ) . getChildren ( ) ; } return new Object [ ] ; } public boolean hasChildren ( Object parent ) { if ( parent instanceof TreeParent ) return ( ( TreeParent ) parent ) . hasChildren ( ) ; return false ; } public Node getRootNode ( ) { try { return new RubyParser ( ) . parse ( getName ( ) , new String ( Util . getInputStreamAsCharArray ( getContents ( ) , - , null ) ) ) . getAST ( ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return null ; } private String getName ( ) throws CoreException { IFile file = getFile ( ) ; if ( file != null ) return file . getName ( ) ; IEditorInput input = editor . getEditorInput ( ) ; if ( input instanceof IStorageEditorInput ) { IStorageEditorInput storageInput = ( IStorageEditorInput ) input ; return storageInput . getStorage ( ) . getName ( ) ; } return "" ; } private InputStream getContents ( ) throws CoreException { IFile file = getFile ( ) ; if ( file != null ) return file . getContents ( ) ; IEditorInput input = editor . getEditorInput ( ) ; if ( input instanceof IStorageEditorInput ) { IStorageEditorInput storageInput = ( IStorageEditorInput ) input ; return storageInput . getStorage ( ) . getContents ( ) ; } return null ; } private void initialize ( ) { updateContent ( ) ; } private void buildTree ( TreeParent parent , Node n ) { if ( n == null || n . isInvisible ( ) ) return ; if ( ! showNewline && n instanceof NewlineNode ) n = ( ( NewlineNode ) n ) . getNextNode ( ) ; List < Node > children = new ArrayList < Node > ( n . childNodes ( ) ) ; children . addAll ( n . getComments ( ) ) ; if ( ( n instanceof CommentNode ) || ( children . size ( ) <= ) ) { parent . addChild ( new TreeObject ( n ) ) ; } else { TreeParent newParent = new TreeParent ( n ) ; parent . addChild ( newParent ) ; for ( Node childNode : children ) { if ( childNode . isInvisible ( ) ) continue ; buildTree ( newParent , childNode ) ; } } } private IWorkbenchPage getActiveWorkbenchPage ( ) { return PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) ; } private boolean editorChanged ( ) { if ( getActiveWorkbenchPage ( ) == null || ! ( getActiveWorkbenchPage ( ) . getActiveEditor ( ) instanceof RubyEditor ) ) return false ; return getEditor ( ) != ( RubyEditor ) getActiveWorkbenchPage ( ) . getActiveEditor ( ) ; } public boolean forceUpdateContent ( ) { if ( getActiveWorkbenchPage ( ) == null ) return false ; setEditor ( ( RubyEditor ) getActiveWorkbenchPage ( ) . getActiveEditor ( ) ) ; invisibleRoot = new TreeParent ( null ) ; showNewline = Activator . getDefault ( ) . getPreferenceStore ( ) . getBoolean ( "" ) ; buildTree ( invisibleRoot , getRootNode ( ) ) ; return true ; } public boolean updateContent ( ) { if ( editorChanged ( ) ) return forceUpdateContent ( ) ; else return false ; } private void setEditor ( RubyEditor editor ) { this . editor = editor ; } private RubyEditor getEditor ( ) { return editor ; } } package org . rubypeople . rdt . astviewer . views ; import java . util . ArrayList ; import org . jruby . ast . Node ; class TreeParent extends TreeObject { private ArrayList < TreeObject > children ; public TreeParent ( Node n ) { super ( n ) ; children = new ArrayList < TreeObject > ( ) ; } public void addChild ( TreeObject child ) { children . add ( child ) ; child . setParent ( this ) ; } public void removeChild ( TreeObject child ) { children . remove ( child ) ; child . setParent ( null ) ; } public TreeObject [ ] getChildren ( ) { return children . toArray ( new TreeObject [ children . size ( ) ] ) ; } public boolean hasChildren ( ) { return children . size ( ) > ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . StringReader ; import java . io . StringWriter ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . ToolBarManager ; import org . eclipse . jface . util . Assert ; import org . eclipse . jface . util . IOpenEventListener ; import org . eclipse . jface . util . OpenStrategy ; import org . eclipse . swt . SWT ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; import org . eclipse . swt . widgets . ToolBar ; import org . rubypeople . rdt . internal . ui . util . StackTraceLine ; public class FailureTrace implements IMenuListener { static final String FRAME_PREFIX = "" ; private final Image fStackIcon = TestUnitView . createImage ( "" ) ; private final Image fExceptionIcon = TestUnitView . createImage ( "" ) ; private Table fTable ; private String fInputTrace ; private final Clipboard fClipboard ; private TestRunInfo fFailure ; private CompareResultsAction fCompareAction ; private TestUnitView fTestRunner ; public FailureTrace ( Composite parent , Clipboard clipboard , TestUnitView testRunner , ToolBar toolBar ) { Assert . isNotNull ( clipboard ) ; ToolBarManager failureToolBarmanager = new ToolBarManager ( toolBar ) ; failureToolBarmanager . add ( new EnableStackFilterAction ( this ) ) ; fCompareAction = new CompareResultsAction ( this ) ; fCompareAction . setEnabled ( false ) ; failureToolBarmanager . add ( fCompareAction ) ; failureToolBarmanager . update ( true ) ; fTestRunner = testRunner ; fTable = new Table ( parent , SWT . SINGLE | SWT . V_SCROLL | SWT . H_SCROLL ) ; fClipboard = clipboard ; OpenStrategy handler = new OpenStrategy ( fTable ) ; handler . addOpenListener ( new IOpenEventListener ( ) { public void handleOpen ( SelectionEvent e ) { if ( fTable . getSelectionIndex ( ) == && fFailure . isComparisonFailure ( ) ) { ( new CompareResultsAction ( FailureTrace . this ) ) . run ( ) ; } if ( fTable . getSelection ( ) . length != ) { Action a = createOpenEditorAction ( getSelectedText ( ) ) ; if ( a != null ) a . run ( ) ; } } } ) ; initMenu ( ) ; parent . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { disposeIcons ( ) ; } } ) ; } private void initMenu ( ) { MenuManager menuMgr = new MenuManager ( ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( this ) ; Menu menu = menuMgr . createContextMenu ( fTable ) ; fTable . setMenu ( menu ) ; } public void menuAboutToShow ( IMenuManager manager ) { if ( fTable . getSelectionCount ( ) > ) { Action a = createOpenEditorAction ( getSelectedText ( ) ) ; if ( a != null ) manager . add ( a ) ; manager . add ( new CopyTraceAction ( FailureTrace . this , fClipboard ) ) ; } if ( fFailure != null && fFailure . isComparisonFailure ( ) ) manager . add ( new CompareResultsAction ( FailureTrace . this ) ) ; } public String getTrace ( ) { return fInputTrace ; } private String getSelectedText ( ) { return fTable . getSelection ( ) [ ] . getText ( ) ; } private Action createOpenEditorAction ( String traceLine ) { StackTraceLine stack = new StackTraceLine ( traceLine , fTestRunner . getLaunchedProject ( ) ) ; return new OpenEditorAtLineAction ( fTestRunner , stack . getFilename ( ) , stack . getLineNumber ( ) ) ; } private void disposeIcons ( ) { if ( fExceptionIcon != null && ! fExceptionIcon . isDisposed ( ) ) fExceptionIcon . dispose ( ) ; if ( fStackIcon != null && ! fStackIcon . isDisposed ( ) ) fStackIcon . dispose ( ) ; } public Composite getComposite ( ) { return fTable ; } public void refresh ( ) { updateTable ( fInputTrace ) ; } public void showFailure ( TestRunInfo failure ) { fFailure = failure ; String trace = "" ; updateEnablement ( failure ) ; if ( failure != null ) trace = failure . getTrace ( ) ; if ( fInputTrace == trace ) return ; fInputTrace = trace ; updateTable ( trace ) ; } public void updateEnablement ( TestRunInfo failure ) { fCompareAction . setEnabled ( failure != null && failure . isComparisonFailure ( ) ) ; } private void updateTable ( String trace ) { if ( trace == null || trace . trim ( ) . equals ( "" ) ) { clear ( ) ; return ; } trace = trace . trim ( ) ; fTable . setRedraw ( false ) ; fTable . removeAll ( ) ; fillTable ( filterStack ( trace , getFilterPatterns ( ) ) ) ; fTable . setRedraw ( true ) ; } private String [ ] getFilterPatterns ( ) { if ( TestUnitPreferencePage . getFilterStack ( ) ) return TestUnitPreferencePage . getFilterPatterns ( ) ; return new String [ ] ; } private void fillTable ( String trace ) { StringReader stringReader = new StringReader ( trace ) ; BufferedReader bufferedReader = new BufferedReader ( stringReader ) ; String line ; try { line = bufferedReader . readLine ( ) ; if ( line == null ) return ; TableItem tableItem = new TableItem ( fTable , SWT . NONE ) ; String itemLabel = line . replace ( '' , '' ) ; tableItem . setText ( itemLabel ) ; tableItem . setImage ( fExceptionIcon ) ; while ( ( line = bufferedReader . readLine ( ) ) != null ) { itemLabel = line . replace ( '' , '' ) ; tableItem = new TableItem ( fTable , SWT . NONE ) ; if ( ( itemLabel . indexOf ( "" ) >= ) ) { tableItem . setImage ( fStackIcon ) ; } tableItem . setText ( itemLabel ) ; } } catch ( IOException e ) { TableItem tableItem = new TableItem ( fTable , SWT . NONE ) ; tableItem . setText ( trace ) ; } } public void setInformation ( String text ) { clear ( ) ; TableItem tableItem = new TableItem ( fTable , SWT . NONE ) ; tableItem . setText ( text ) ; } public void clear ( ) { fTable . removeAll ( ) ; fInputTrace = null ; } private String filterStack ( String stackTrace , String [ ] filterPatterns ) { if ( filterPatterns . length == || stackTrace == null ) return stackTrace ; StringWriter stringWriter = new StringWriter ( ) ; PrintWriter printWriter = new PrintWriter ( stringWriter ) ; StringReader stringReader = new StringReader ( stackTrace ) ; BufferedReader bufferedReader = new BufferedReader ( stringReader ) ; String line ; String [ ] patterns = filterPatterns ; try { while ( ( line = bufferedReader . readLine ( ) ) != null ) { if ( ! filterLine ( patterns , line ) ) printWriter . println ( line ) ; } } catch ( IOException e ) { return stackTrace ; } return stringWriter . toString ( ) ; } private boolean filterLine ( String [ ] patterns , String line ) { if ( line == null || line . trim ( ) . length ( ) == ) return false ; if ( Character . isDigit ( line . trim ( ) . charAt ( ) ) ) return false ; String pattern ; int len ; for ( int i = ( patterns . length - ) ; i >= ; -- i ) { pattern = patterns [ i ] ; len = pattern . length ( ) - ; if ( pattern . charAt ( len ) == '' ) { pattern = pattern . substring ( , len ) ; } else if ( Character . isUpperCase ( pattern . charAt ( ) ) ) { pattern = FailureTrace . FRAME_PREFIX + pattern + '' ; } else { final int lastDotIndex = pattern . lastIndexOf ( '' ) ; if ( ( lastDotIndex != - ) && ( lastDotIndex != len ) && Character . isUpperCase ( pattern . charAt ( lastDotIndex + ) ) ) pattern += '' ; } if ( line . indexOf ( pattern ) > ) return true ; } return false ; } public TestRunInfo getFailedTest ( ) { return fFailure ; } public Shell getShell ( ) { return fTable . getShell ( ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import java . util . StringTokenizer ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ColumnWeightData ; import org . eclipse . jface . viewers . ContentViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . TableEditor ; import org . eclipse . swt . events . FocusAdapter ; import org . eclipse . swt . events . FocusEvent ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . swt . widgets . TableItem ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . eclipse . ui . model . WorkbenchViewerSorter ; import org . rubypeople . rdt . internal . testunit . util . LayoutUtil ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; import org . rubypeople . rdt . internal . ui . util . TableLayoutComposite ; import org . rubypeople . rdt . ui . ISharedImages ; import org . rubypeople . rdt . ui . RubyUI ; public class TestUnitPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String DEFAULT_NEW_FILTER_TEXT = "" ; private static final Image IMG_CUNIT = RubyUI . getSharedImages ( ) . getImage ( ISharedImages . IMG_OBJS_CLASS ) ; private static final Image IMG_PKG = RubyUI . getSharedImages ( ) . getImage ( ISharedImages . IMG_OBJS_SOURCE_FOLDER ) ; private Label fFilterViewerLabel ; private CheckboxTableViewer fFilterViewer ; private Table fFilterTable ; private Button fRemoveFilterButton ; private Button fAddFilterButton ; private Button fEnableAllButton ; private Button fDisableAllButton ; private Text fEditorText ; private String fInvalidEditorText = null ; private TableEditor fTableEditor ; private TableItem fNewTableItem ; private Filter fNewStackFilter ; private StackFilterContentProvider fStackFilterContentProvider ; private static class Filter { private String fName ; private boolean fChecked ; public Filter ( String name , boolean checked ) { setName ( name ) ; setChecked ( checked ) ; } public String getName ( ) { return fName ; } public void setName ( String name ) { fName = name ; } public boolean isChecked ( ) { return fChecked ; } public void setChecked ( boolean checked ) { fChecked = checked ; } public boolean equals ( Object o ) { if ( ! ( o instanceof Filter ) ) return false ; Filter other = ( Filter ) o ; return ( getName ( ) . equals ( other . getName ( ) ) ) ; } public int hashCode ( ) { return fName . hashCode ( ) ; } } private static class FilterViewerSorter extends WorkbenchViewerSorter { public int compare ( Viewer viewer , Object e1 , Object e2 ) { ILabelProvider lprov = ( ILabelProvider ) ( ( ContentViewer ) viewer ) . getLabelProvider ( ) ; String name1 = lprov . getText ( e1 ) ; String name2 = lprov . getText ( e2 ) ; if ( name1 == null ) name1 = "" ; if ( name2 == null ) name2 = "" ; if ( name1 . length ( ) > && name2 . length ( ) > ) { char char1 = name1 . charAt ( name1 . length ( ) - ) ; char char2 = name2 . charAt ( name2 . length ( ) - ) ; if ( char1 == '' && char1 != char2 ) return - ; if ( char2 == '' && char2 != char1 ) return ; } return name1 . compareTo ( name2 ) ; } } private static class FilterLabelProvider extends LabelProvider implements ITableLabelProvider { public String getColumnText ( Object object , int column ) { return ( column == ) ? ( ( Filter ) object ) . getName ( ) : "" ; } public String getText ( Object element ) { return ( ( Filter ) element ) . getName ( ) ; } public Image getColumnImage ( Object object , int column ) { String name = ( ( Filter ) object ) . getName ( ) ; if ( name . endsWith ( "" ) || name . equals ( TestUnitMessages . TestUnitMainTab_label_defaultpackage ) ) { return IMG_PKG ; } else if ( "" . equals ( name ) ) { return null ; } else if ( ( Character . isUpperCase ( name . charAt ( ) ) ) && ( name . indexOf ( '' ) < ) ) { return IMG_CUNIT ; } else { final int lastDotIndex = name . lastIndexOf ( '' ) ; if ( ( - != lastDotIndex ) && ( ( name . length ( ) - ) != lastDotIndex ) && Character . isUpperCase ( name . charAt ( lastDotIndex + ) ) ) return IMG_CUNIT ; } return null ; } } private class StackFilterContentProvider implements IStructuredContentProvider { private List fFilters ; public StackFilterContentProvider ( ) { List active = createActiveStackFiltersList ( ) ; List inactive = createInactiveStackFiltersList ( ) ; populateFilters ( active , inactive ) ; } public void setDefaults ( ) { fFilterViewer . remove ( fFilters . toArray ( ) ) ; List active = TestUnitPreferencesConstants . createDefaultStackFiltersList ( ) ; List inactive = new ArrayList ( ) ; populateFilters ( active , inactive ) ; } protected void populateFilters ( List activeList , List inactiveList ) { fFilters = new ArrayList ( activeList . size ( ) + inactiveList . size ( ) ) ; populateList ( activeList , true ) ; if ( inactiveList . size ( ) != ) populateList ( inactiveList , false ) ; } protected void populateList ( List list , boolean checked ) { Iterator iterator = list . iterator ( ) ; while ( iterator . hasNext ( ) ) { String name = ( String ) iterator . next ( ) ; addFilter ( name , checked ) ; } } public Filter addFilter ( String name , boolean checked ) { Filter filter = new Filter ( name , checked ) ; if ( ! fFilters . contains ( filter ) ) { fFilters . add ( filter ) ; fFilterViewer . add ( filter ) ; fFilterViewer . setChecked ( filter , checked ) ; } updateActions ( ) ; return filter ; } public void saveFilters ( ) { List active = new ArrayList ( fFilters . size ( ) ) ; List inactive = new ArrayList ( fFilters . size ( ) ) ; Iterator iterator = fFilters . iterator ( ) ; while ( iterator . hasNext ( ) ) { Filter filter = ( Filter ) iterator . next ( ) ; String name = filter . getName ( ) ; if ( filter . isChecked ( ) ) active . add ( name ) ; else inactive . add ( name ) ; } String pref = TestUnitPreferencesConstants . serializeList ( ( String [ ] ) active . toArray ( new String [ active . size ( ) ] ) ) ; getPreferenceStore ( ) . setValue ( TestUnitPreferencesConstants . PREF_ACTIVE_FILTERS_LIST , pref ) ; pref = TestUnitPreferencesConstants . serializeList ( ( String [ ] ) inactive . toArray ( new String [ inactive . size ( ) ] ) ) ; getPreferenceStore ( ) . setValue ( TestUnitPreferencesConstants . PREF_INACTIVE_FILTERS_LIST , pref ) ; } public void removeFilters ( Object [ ] filters ) { for ( int i = ( filters . length - ) ; i >= ; -- i ) { Filter filter = ( Filter ) filters [ i ] ; fFilters . remove ( filter ) ; } fFilterViewer . remove ( filters ) ; updateActions ( ) ; } public void toggleFilter ( Filter filter ) { boolean newState = ! filter . isChecked ( ) ; filter . setChecked ( newState ) ; fFilterViewer . setChecked ( filter , newState ) ; } public Object [ ] getElements ( Object inputElement ) { return fFilters . toArray ( ) ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public void dispose ( ) { } } public TestUnitPreferencePage ( ) { super ( ) ; setDescription ( TestUnitMessages . TestUnitPreferencePage_description ) ; setPreferenceStore ( TestunitPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; } protected Control createContents ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginHeight = ; layout . marginWidth = ; composite . setLayout ( layout ) ; GridData data = new GridData ( ) ; data . verticalAlignment = GridData . FILL ; data . horizontalAlignment = GridData . FILL ; composite . setLayoutData ( data ) ; createStackFilterPreferences ( composite ) ; Dialog . applyDialogFont ( composite ) ; return composite ; } private void createStackFilterPreferences ( Composite composite ) { fFilterViewerLabel = new Label ( composite , SWT . SINGLE | SWT . LEFT ) ; fFilterViewerLabel . setText ( TestUnitMessages . TestUnitPreferencePage_filter_label ) ; Composite container = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginHeight = ; layout . marginWidth = ; container . setLayout ( layout ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; container . setLayoutData ( gd ) ; createFilterTable ( container ) ; createStepFilterButtons ( container ) ; } private void createFilterTable ( Composite container ) { TableLayoutComposite layouter = new TableLayoutComposite ( container , SWT . NONE ) ; layouter . addColumnData ( new ColumnWeightData ( ) ) ; layouter . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; fFilterTable = new Table ( layouter , SWT . CHECK | SWT . BORDER | SWT . MULTI | SWT . FULL_SELECTION ) ; new TableColumn ( fFilterTable , SWT . NONE ) ; fFilterViewer = new CheckboxTableViewer ( fFilterTable ) ; fTableEditor = new TableEditor ( fFilterTable ) ; fFilterViewer . setLabelProvider ( new FilterLabelProvider ( ) ) ; fFilterViewer . setSorter ( new FilterViewerSorter ( ) ) ; fStackFilterContentProvider = new StackFilterContentProvider ( ) ; fFilterViewer . setContentProvider ( fStackFilterContentProvider ) ; fFilterViewer . setInput ( this ) ; fFilterViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { Filter filter = ( Filter ) event . getElement ( ) ; fStackFilterContentProvider . toggleFilter ( filter ) ; } } ) ; fFilterViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { ISelection selection = event . getSelection ( ) ; fRemoveFilterButton . setEnabled ( ! selection . isEmpty ( ) ) ; } } ) ; } private void createStepFilterButtons ( Composite container ) { Composite buttonContainer = new Composite ( container , SWT . NONE ) ; GridData gd = new GridData ( GridData . FILL_VERTICAL ) ; buttonContainer . setLayoutData ( gd ) ; GridLayout buttonLayout = new GridLayout ( ) ; buttonLayout . numColumns = ; buttonLayout . marginHeight = ; buttonLayout . marginWidth = ; buttonContainer . setLayout ( buttonLayout ) ; fAddFilterButton = new Button ( buttonContainer , SWT . PUSH ) ; fAddFilterButton . setText ( TestUnitMessages . TestUnitPreferencePage_addfilterbutton_label ) ; fAddFilterButton . setToolTipText ( TestUnitMessages . TestUnitPreferencePage_addfilterbutton_tooltip ) ; gd = new GridData ( GridData . FILL_HORIZONTAL | GridData . VERTICAL_ALIGN_BEGINNING ) ; fAddFilterButton . setLayoutData ( gd ) ; LayoutUtil . setButtonDimensionHint ( fAddFilterButton ) ; fAddFilterButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { editFilter ( ) ; } } ) ; fRemoveFilterButton = new Button ( buttonContainer , SWT . PUSH ) ; fRemoveFilterButton . setText ( TestUnitMessages . TestUnitPreferencePage_removefilterbutton_label ) ; fRemoveFilterButton . setToolTipText ( TestUnitMessages . TestUnitPreferencePage_removefilterbutton_tooltip ) ; gd = getButtonGridData ( fRemoveFilterButton ) ; fRemoveFilterButton . setLayoutData ( gd ) ; SWTUtil . setButtonDimensionHint ( fRemoveFilterButton ) ; fRemoveFilterButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { removeFilters ( ) ; } } ) ; fRemoveFilterButton . setEnabled ( false ) ; fEnableAllButton = new Button ( buttonContainer , SWT . PUSH ) ; fEnableAllButton . setText ( TestUnitMessages . TestUnitPreferencePage_enableallbutton_label ) ; fEnableAllButton . setToolTipText ( TestUnitMessages . TestUnitPreferencePage_enableallbutton_tooltip ) ; gd = getButtonGridData ( fEnableAllButton ) ; fEnableAllButton . setLayoutData ( gd ) ; SWTUtil . setButtonDimensionHint ( fEnableAllButton ) ; fEnableAllButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { checkAllFilters ( true ) ; } } ) ; fDisableAllButton = new Button ( buttonContainer , SWT . PUSH ) ; fDisableAllButton . setText ( TestUnitMessages . TestUnitPreferencePage_disableallbutton_label ) ; fDisableAllButton . setToolTipText ( TestUnitMessages . TestUnitPreferencePage_disableallbutton_tooltip ) ; gd = getButtonGridData ( fDisableAllButton ) ; fDisableAllButton . setLayoutData ( gd ) ; SWTUtil . setButtonDimensionHint ( fDisableAllButton ) ; fDisableAllButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { checkAllFilters ( false ) ; } } ) ; } private GridData getButtonGridData ( Button button ) { GridData gd = new GridData ( GridData . FILL_HORIZONTAL | GridData . VERTICAL_ALIGN_BEGINNING ) ; int widthHint = convertHorizontalDLUsToPixels ( IDialogConstants . BUTTON_WIDTH ) ; gd . widthHint = Math . max ( widthHint , button . computeSize ( SWT . DEFAULT , SWT . DEFAULT , true ) . x ) ; return gd ; } public void init ( IWorkbench workbench ) { } private void editFilter ( ) { if ( fEditorText != null ) validateChangeAndCleanup ( ) ; fNewStackFilter = fStackFilterContentProvider . addFilter ( DEFAULT_NEW_FILTER_TEXT , true ) ; fNewTableItem = fFilterTable . getItem ( ) ; int textStyles = SWT . SINGLE | SWT . LEFT ; if ( ! SWT . getPlatform ( ) . equals ( "" ) ) textStyles |= SWT . BORDER ; fEditorText = new Text ( fFilterTable , textStyles ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; fEditorText . setLayoutData ( gd ) ; fTableEditor . horizontalAlignment = SWT . LEFT ; fTableEditor . grabHorizontal = true ; fTableEditor . setEditor ( fEditorText , fNewTableItem , ) ; fEditorText . setText ( fNewStackFilter . getName ( ) ) ; fEditorText . selectAll ( ) ; setEditorListeners ( fEditorText ) ; fEditorText . setFocus ( ) ; } private void setEditorListeners ( Text text ) { text . addKeyListener ( new KeyAdapter ( ) { public void keyReleased ( KeyEvent event ) { if ( event . character == SWT . CR ) { if ( fInvalidEditorText != null ) { fEditorText . setText ( fInvalidEditorText ) ; fInvalidEditorText = null ; } else validateChangeAndCleanup ( ) ; } else if ( event . character == SWT . ESC ) { removeNewFilter ( ) ; cleanupEditor ( ) ; } } } ) ; text . addFocusListener ( new FocusAdapter ( ) { public void focusLost ( FocusEvent event ) { if ( fInvalidEditorText != null ) { fEditorText . setText ( fInvalidEditorText ) ; fInvalidEditorText = null ; } else validateChangeAndCleanup ( ) ; } } ) ; text . addListener ( SWT . Traverse , new Listener ( ) { public void handleEvent ( Event event ) { event . doit = false ; } } ) ; } private void validateChangeAndCleanup ( ) { String trimmedValue = fEditorText . getText ( ) . trim ( ) ; if ( trimmedValue . length ( ) < ) removeNewFilter ( ) ; else if ( ! validateEditorInput ( trimmedValue ) ) { fInvalidEditorText = trimmedValue ; fEditorText . setText ( TestUnitMessages . TestUnitPreferencePage_invalidstepfilterreturnescape ) ; getShell ( ) . getDisplay ( ) . beep ( ) ; return ; } else { Object [ ] filters = fStackFilterContentProvider . getElements ( null ) ; for ( int i = ; i < filters . length ; i ++ ) { Filter filter = ( Filter ) filters [ i ] ; if ( filter . getName ( ) . equals ( trimmedValue ) ) { removeNewFilter ( ) ; cleanupEditor ( ) ; return ; } } fNewTableItem . setText ( trimmedValue ) ; fNewStackFilter . setName ( trimmedValue ) ; fFilterViewer . refresh ( ) ; } cleanupEditor ( ) ; } private void cleanupEditor ( ) { if ( fEditorText == null ) return ; fNewStackFilter = null ; fNewTableItem = null ; fTableEditor . setEditor ( null , null , ) ; fEditorText . dispose ( ) ; fEditorText = null ; } private void removeNewFilter ( ) { fStackFilterContentProvider . removeFilters ( new Object [ ] { fNewStackFilter } ) ; } private boolean validateEditorInput ( String trimmedValue ) { char firstChar = trimmedValue . charAt ( ) ; if ( ( ! ( Character . isJavaIdentifierStart ( firstChar ) ) || ( firstChar == '' ) ) ) return false ; int length = trimmedValue . length ( ) ; for ( int i = ; i < length ; i ++ ) { char c = trimmedValue . charAt ( i ) ; if ( ! Character . isJavaIdentifierPart ( c ) ) { if ( c == '' && i != ( length - ) ) continue ; if ( c == '' && i == ( length - ) ) continue ; return false ; } } return true ; } private void removeFilters ( ) { IStructuredSelection selection = ( IStructuredSelection ) fFilterViewer . getSelection ( ) ; fStackFilterContentProvider . removeFilters ( selection . toArray ( ) ) ; } private void checkAllFilters ( boolean check ) { Object [ ] filters = fStackFilterContentProvider . getElements ( null ) ; for ( int i = ( filters . length - ) ; i >= ; -- i ) ( ( Filter ) filters [ i ] ) . setChecked ( check ) ; fFilterViewer . setAllChecked ( check ) ; } public boolean performOk ( ) { fStackFilterContentProvider . saveFilters ( ) ; return true ; } protected void performDefaults ( ) { setDefaultValues ( ) ; super . performDefaults ( ) ; } private void setDefaultValues ( ) { fStackFilterContentProvider . setDefaults ( ) ; } protected List < String > createActiveStackFiltersList ( ) { return Arrays . asList ( getFilterPatterns ( ) ) ; } protected List < String > createInactiveStackFiltersList ( ) { String [ ] strings = TestUnitPreferencesConstants . parseList ( getPreferenceStore ( ) . getString ( TestUnitPreferencesConstants . PREF_INACTIVE_FILTERS_LIST ) ) ; return Arrays . asList ( strings ) ; } protected void updateActions ( ) { if ( fEnableAllButton == null ) return ; boolean enabled = fFilterViewer . getTable ( ) . getItemCount ( ) > ; fEnableAllButton . setEnabled ( enabled ) ; fDisableAllButton . setEnabled ( enabled ) ; } public static String [ ] getFilterPatterns ( ) { IPreferenceStore store = TestunitPlugin . getDefault ( ) . getPreferenceStore ( ) ; return TestUnitPreferencesConstants . parseList ( store . getString ( TestUnitPreferencesConstants . PREF_ACTIVE_FILTERS_LIST ) ) ; } public static boolean getFilterStack ( ) { IPreferenceStore store = TestunitPlugin . getDefault ( ) . getPreferenceStore ( ) ; return store . getBoolean ( TestUnitPreferencesConstants . DO_FILTER_STACK ) ; } public static void setFilterStack ( boolean filter ) { IPreferenceStore store = TestunitPlugin . getDefault ( ) . getPreferenceStore ( ) ; store . setValue ( TestUnitPreferencesConstants . DO_FILTER_STACK , filter ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Layout ; public class TabFolderLayout extends Layout { protected Point computeSize ( Composite composite , int wHint , int hHint , boolean flushCache ) { if ( wHint != SWT . DEFAULT && hHint != SWT . DEFAULT ) return new Point ( wHint , hHint ) ; Control [ ] children = composite . getChildren ( ) ; int count = children . length ; int maxWidth = , maxHeight = ; for ( int i = ; i < count ; i ++ ) { Control child = children [ i ] ; Point pt = child . computeSize ( SWT . DEFAULT , SWT . DEFAULT , flushCache ) ; maxWidth = Math . max ( maxWidth , pt . x ) ; maxHeight = Math . max ( maxHeight , pt . y ) ; } if ( wHint != SWT . DEFAULT ) maxWidth = wHint ; if ( hHint != SWT . DEFAULT ) maxHeight = hHint ; return new Point ( maxWidth , maxHeight ) ; } protected void layout ( Composite composite , boolean flushCache ) { Rectangle rect = composite . getClientArea ( ) ; Control [ ] children = composite . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { children [ i ] . setBounds ( rect ) ; } } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . swt . graphics . Image ; public class ProgressImages { private static final int PROGRESS_STEPS = ; private static final String BASE = "" ; private static final String FAILURE = "" ; private static final String OK = "" ; private Image [ ] fOKImages = new Image [ PROGRESS_STEPS ] ; private Image [ ] fFailureImages = new Image [ PROGRESS_STEPS ] ; private void load ( ) { if ( isLoaded ( ) ) return ; for ( int i = ; i < PROGRESS_STEPS ; i ++ ) { String okname = BASE + OK + Integer . toString ( i + ) + "" ; fOKImages [ i ] = createImage ( okname ) ; String failurename = BASE + FAILURE + Integer . toString ( i + ) + "" ; fFailureImages [ i ] = createImage ( failurename ) ; } } private Image createImage ( String name ) { return TestunitPlugin . getImageDescriptor ( name ) . createImage ( ) ; } public void dispose ( ) { if ( ! isLoaded ( ) ) return ; for ( int i = ; i < PROGRESS_STEPS ; i ++ ) { fOKImages [ i ] . dispose ( ) ; fOKImages [ i ] = null ; fFailureImages [ i ] . dispose ( ) ; fFailureImages [ i ] = null ; } } public Image getImage ( int current , int total , int errors , int failures ) { if ( ! isLoaded ( ) ) load ( ) ; if ( total == ) return fOKImages [ ] ; int index = ( ( current * PROGRESS_STEPS ) / total ) - ; index = Math . min ( Math . max ( , index ) , PROGRESS_STEPS - ) ; if ( errors + failures == ) return fOKImages [ index ] ; return fFailureImages [ index ] ; } private boolean isLoaded ( ) { return fOKImages [ ] != null ; } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . ISourceLocator ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorDescriptor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . internal . debug . ui . RubySourceLocator ; import org . rubypeople . rdt . internal . debug . ui . RubySourceLocator . SourceElement ; public class OpenEditorAtLineAction extends Action { private int fLineNumber ; private String fileName ; private TestUnitView fTestRunner ; public OpenEditorAtLineAction ( TestUnitView testRunner , String fileName , int line ) { super ( TestUnitMessages . OpenEditorAction_action_label ) ; fLineNumber = line ; fTestRunner = testRunner ; IRubyProject project = testRunner . getLaunchedProject ( ) ; if ( project != null ) { this . fileName = fileName . replace ( "" , project . getProject ( ) . getLocation ( ) . toPortableString ( ) ) ; } else { this . fileName = fileName ; } } public void run ( ) { try { IEditorInput input = getInput ( ) ; if ( input == null ) { if ( TestunitPlugin . getDefault ( ) . isDebugging ( ) ) { System . out . println ( "" + fileName ) ; } return ; } IEditorPart editorPart = getEditorPart ( input ) ; setEditorToLine ( editorPart , input ) ; } catch ( CoreException e ) { TestunitPlugin . log ( new Status ( IStatus . ERROR , TestunitPlugin . PLUGIN_ID , , "" + fileName , e ) ) ; } } private IEditorPart getEditorPart ( IEditorInput input ) throws PartInitException { ISourceLocator sourceLocator = getSourceLocator ( ) ; if ( ! ( sourceLocator instanceof RubySourceLocator ) ) { return null ; } RubySourceLocator rubySourceLocator = ( RubySourceLocator ) sourceLocator ; SourceElement sourceElement = ( SourceElement ) rubySourceLocator . getSourceElement ( fileName ) ; IEditorDescriptor descriptor = IDE . getEditorDescriptor ( sourceElement . getFilename ( ) ) ; return IDE . openEditor ( PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) , input , descriptor . getId ( ) ) ; } private void setEditorToLine ( IEditorPart pEditorPart , IEditorInput pInput ) throws CoreException { if ( ! ( pEditorPart instanceof ITextEditor ) ) { return ; } if ( fLineNumber > ) { fLineNumber -- ; } if ( fLineNumber == ) { return ; } ITextEditor textEditor = ( ITextEditor ) pEditorPart ; IDocumentProvider provider = textEditor . getDocumentProvider ( ) ; provider . connect ( pInput ) ; IDocument document = provider . getDocument ( pInput ) ; try { IRegion line = document . getLineInformation ( fLineNumber ) ; textEditor . selectAndReveal ( line . getOffset ( ) , line . getLength ( ) ) ; } catch ( BadLocationException e ) { if ( TestunitPlugin . getDefault ( ) . isDebugging ( ) ) { System . out . println ( "" + fLineNumber ) ; } } provider . disconnect ( pInput ) ; } protected void reveal ( ITextEditor textEditor ) { if ( fLineNumber >= ) { try { IDocument document = textEditor . getDocumentProvider ( ) . getDocument ( textEditor . getEditorInput ( ) ) ; textEditor . selectAndReveal ( document . getLineOffset ( fLineNumber - ) , document . getLineLength ( fLineNumber - ) ) ; } catch ( BadLocationException x ) { } } } public boolean isEnabled ( ) { return getInput ( ) != null ; } private IEditorInput getInput ( ) { ISourceLocator sourceLocator = getSourceLocator ( ) ; if ( ! ( sourceLocator instanceof RubySourceLocator ) ) { return null ; } RubySourceLocator rubySourceLocator = ( RubySourceLocator ) sourceLocator ; Object sourceElement = rubySourceLocator . getSourceElement ( fileName ) ; IEditorInput input = rubySourceLocator . getEditorInput ( sourceElement ) ; return input ; } private ISourceLocator getSourceLocator ( ) { ILaunch launch = fTestRunner . getLastLaunch ( ) ; if ( launch == null ) { return null ; } return launch . getSourceLocator ( ) ; } protected Shell getShell ( ) { return fTestRunner . getSite ( ) . getShell ( ) ; } protected IRubyProject getLaunchedProject ( ) { return fTestRunner . getLaunchedProject ( ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . StringReader ; import java . io . StringWriter ; import org . eclipse . swt . SWTError ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . dnd . DND ; import org . eclipse . swt . dnd . TextTransfer ; import org . eclipse . swt . dnd . Transfer ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . util . Assert ; public class CopyTraceAction extends Action { private FailureTrace fView ; private final Clipboard fClipboard ; public CopyTraceAction ( FailureTrace view , Clipboard clipboard ) { super ( TestUnitMessages . CopyTrace_action_label ) ; Assert . isNotNull ( clipboard ) ; fView = view ; fClipboard = clipboard ; } public void run ( ) { String trace = fView . getTrace ( ) ; if ( trace == null ) trace = "" ; TextTransfer plainTextTransfer = TextTransfer . getInstance ( ) ; try { fClipboard . setContents ( new String [ ] { convertLineTerminators ( trace ) } , new Transfer [ ] { plainTextTransfer } ) ; } catch ( SWTError e ) { if ( e . code != DND . ERROR_CANNOT_SET_CLIPBOARD ) throw e ; if ( MessageDialog . openQuestion ( fView . getComposite ( ) . getShell ( ) , TestUnitMessages . CopyTraceAction_problem , TestUnitMessages . CopyTraceAction_clipboard_busy ) ) run ( ) ; } } private String convertLineTerminators ( String in ) { StringWriter stringWriter = new StringWriter ( ) ; PrintWriter printWriter = new PrintWriter ( stringWriter ) ; StringReader stringReader = new StringReader ( in ) ; BufferedReader bufferedReader = new BufferedReader ( stringReader ) ; String line ; try { while ( ( line = bufferedReader . readLine ( ) ) != null ) { printWriter . println ( line ) ; } } catch ( IOException e ) { return in ; } return stringWriter . toString ( ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; public class CounterPanel extends Composite { protected Label fNumberOfErrors ; protected Label fNumberOfFailures ; protected Label fNumberOfRuns ; protected int fTotal ; private final Image fErrorIcon = TestUnitView . createImage ( "" ) ; private final Image fFailureIcon = TestUnitView . createImage ( "" ) ; public CounterPanel ( Composite parent ) { super ( parent , SWT . WRAP ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . numColumns = ; gridLayout . makeColumnsEqualWidth = false ; gridLayout . marginWidth = ; setLayout ( gridLayout ) ; fNumberOfRuns = createLabel ( TestUnitMessages . CounterPanel_label_runs , null , "" ) ; fNumberOfErrors = createLabel ( TestUnitMessages . CounterPanel_label_errors , fErrorIcon , "" ) ; fNumberOfFailures = createLabel ( TestUnitMessages . CounterPanel_label_failures , fFailureIcon , "" ) ; addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { disposeIcons ( ) ; } } ) ; } private void disposeIcons ( ) { fErrorIcon . dispose ( ) ; fFailureIcon . dispose ( ) ; } private Label createLabel ( String name , Image image , String init ) { Label label = new Label ( this , SWT . NONE ) ; if ( image != null ) { image . setBackground ( label . getBackground ( ) ) ; label . setImage ( image ) ; } label . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ) ; label = new Label ( this , SWT . NONE ) ; label . setText ( name ) ; label . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ) ; label . setFont ( JFaceResources . getBannerFont ( ) ) ; Label value = new Label ( this , SWT . READ_ONLY ) ; value . setText ( init ) ; value . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL | GridData . HORIZONTAL_ALIGN_BEGINNING ) ) ; return value ; } public void reset ( ) { setErrorValue ( ) ; setFailureValue ( ) ; setRunValue ( ) ; fTotal = ; } public void setTotal ( int value ) { fTotal = value ; } public int getTotal ( ) { return fTotal ; } public void setRunValue ( int value ) { String runString = TestUnitMessages . getFormattedString ( TestUnitMessages . CounterPanel_runcount , new String [ ] { Integer . toString ( value ) , Integer . toString ( fTotal ) } ) ; fNumberOfRuns . setText ( runString ) ; fNumberOfRuns . redraw ( ) ; redraw ( ) ; } public void setErrorValue ( int value ) { fNumberOfErrors . setText ( Integer . toString ( value ) ) ; redraw ( ) ; } public void setFailureValue ( int value ) { fNumberOfFailures . setText ( Integer . toString ( value ) ) ; redraw ( ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . jface . action . Action ; public class CompareResultsAction extends Action { private final FailureTrace fView ; public CompareResultsAction ( FailureTrace view ) { super ( TestUnitMessages . CompareResultsAction_label ) ; this . fView = view ; setDescription ( TestUnitMessages . CompareResultsAction_description ) ; setToolTipText ( TestUnitMessages . CompareResultsAction_tooltip ) ; setDisabledImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setHoverImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; } public void run ( ) { CompareResultDialog dialog = new CompareResultDialog ( fView . getShell ( ) , fView . getFailedTest ( ) ) ; dialog . create ( ) ; dialog . open ( ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . rubyeditor . EditorUtility ; public abstract class OpenEditorAction extends Action { protected String fClassName ; protected TestUnitView fTestRunner ; private final boolean fActivate ; protected OpenEditorAction ( TestUnitView testRunner , String testClassName ) { this ( testRunner , testClassName , true ) ; } public OpenEditorAction ( TestUnitView testRunner , String className , boolean activate ) { super ( TestUnitMessages . OpenEditorAction_action_label ) ; fClassName = className ; fTestRunner = testRunner ; fActivate = activate ; } public void run ( ) { ITextEditor textEditor = null ; try { IRubyElement element = findElement ( getLaunchedProject ( ) , fClassName ) ; if ( element == null ) { MessageDialog . openError ( getShell ( ) , TestUnitMessages . OpenEditorAction_error_cannotopen_title , TestUnitMessages . OpenEditorAction_error_cannotopen_message ) ; return ; } textEditor = ( ITextEditor ) EditorUtility . openInEditor ( element , fActivate ) ; } catch ( CoreException e ) { ErrorDialog . openError ( getShell ( ) , TestUnitMessages . OpenEditorAction_error_dialog_title , TestUnitMessages . OpenEditorAction_error_dialog_message , e . getStatus ( ) ) ; return ; } if ( textEditor == null ) { fTestRunner . setInfoMessage ( TestUnitMessages . OpenEditorAction_message_cannotopen ) ; return ; } reveal ( textEditor ) ; } protected Shell getShell ( ) { return fTestRunner . getSite ( ) . getShell ( ) ; } protected IRubyProject getLaunchedProject ( ) { return fTestRunner . getLaunchedProject ( ) ; } protected String getClassName ( ) { return fClassName ; } protected abstract IRubyElement findElement ( IRubyProject project , String className ) throws CoreException ; protected abstract void reveal ( ITextEditor editor ) ; protected IType findType ( IRubyProject project , String className ) throws RubyModelException { return internalFindType ( project , className , new HashSet < IRubyProject > ( ) ) ; } private IType internalFindType ( IRubyProject project , String className , Set < IRubyProject > visitedProjects ) throws RubyModelException { if ( visitedProjects . contains ( project ) ) return null ; IStatus status = RubyConventions . validateRubyTypeName ( className ) ; if ( ! status . isOK ( ) ) return null ; IType type = project . findType ( className , ( IProgressMonitor ) null ) ; if ( type != null ) return type ; visitedProjects . add ( project ) ; IRubyModel javaModel = project . getRubyModel ( ) ; String [ ] requiredProjectNames = project . getRequiredProjectNames ( ) ; for ( int i = ; i < requiredProjectNames . length ; i ++ ) { IRubyProject requiredProject = javaModel . getRubyProject ( requiredProjectNames [ i ] ) ; if ( requiredProject . exists ( ) ) { type = internalFindType ( requiredProject , className , visitedProjects ) ; if ( type != null ) return type ; } } return null ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . io . ByteArrayInputStream ; import java . io . InputStream ; import java . io . UnsupportedEncodingException ; import org . eclipse . compare . CompareConfiguration ; import org . eclipse . compare . CompareViewerPane ; import org . eclipse . compare . IEncodedStreamContentAccessor ; import org . eclipse . compare . ITypedElement ; import org . eclipse . compare . contentmergeviewer . TextMergeViewer ; import org . eclipse . compare . structuremergeviewer . DiffNode ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . TrayDialog ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . text . TextAttribute ; import org . eclipse . jface . text . TextPresentation ; import org . eclipse . jface . text . TextViewer ; import org . eclipse . jface . text . presentation . IPresentationDamager ; import org . eclipse . jface . text . presentation . IPresentationReconciler ; import org . eclipse . jface . text . presentation . IPresentationRepairer ; import org . eclipse . jface . text . presentation . PresentationReconciler ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StyleRange ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; public class CompareResultDialog extends TrayDialog { private static class CompareResultMergeViewer extends TextMergeViewer { private CompareResultMergeViewer ( Composite parent , int style , CompareConfiguration configuration ) { super ( parent , style , configuration ) ; } protected void createControls ( Composite composite ) { super . createControls ( composite ) ; } protected void configureTextViewer ( TextViewer textViewer ) { if ( textViewer instanceof SourceViewer ) { ( ( SourceViewer ) textViewer ) . configure ( new CompareResultViewerConfiguration ( ) ) ; } } } public static class CompareResultViewerConfiguration extends SourceViewerConfiguration { public static class SimpleDamagerRepairer implements IPresentationDamager , IPresentationRepairer { private IDocument fDocument ; public void setDocument ( IDocument document ) { fDocument = document ; } public IRegion getDamageRegion ( ITypedRegion partition , DocumentEvent event , boolean changed ) { return new Region ( , fDocument . getLength ( ) ) ; } public void createPresentation ( TextPresentation presentation , ITypedRegion damage ) { int suffix = CompareResultDialog . fgThis . fSuffix ; int prefix = CompareResultDialog . fgThis . fPrefix ; TextAttribute attr = new TextAttribute ( Display . getDefault ( ) . getSystemColor ( SWT . COLOR_RED ) , null , SWT . BOLD ) ; presentation . addStyleRange ( new StyleRange ( prefix , fDocument . getLength ( ) - suffix - prefix , attr . getForeground ( ) , attr . getBackground ( ) , attr . getStyle ( ) ) ) ; } } public IPresentationReconciler getPresentationReconciler ( ISourceViewer sourceViewer ) { PresentationReconciler reconciler = new PresentationReconciler ( ) ; SimpleDamagerRepairer dr = new SimpleDamagerRepairer ( ) ; reconciler . setDamager ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; reconciler . setRepairer ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; return reconciler ; } } private static class CompareElement implements ITypedElement , IEncodedStreamContentAccessor { private String fContent ; public CompareElement ( String content ) { fContent = content ; } public String getName ( ) { return "" ; } public Image getImage ( ) { return null ; } public String getType ( ) { return "" ; } public InputStream getContents ( ) { try { return new ByteArrayInputStream ( fContent . getBytes ( "" ) ) ; } catch ( UnsupportedEncodingException e ) { return new ByteArrayInputStream ( fContent . getBytes ( ) ) ; } } public String getCharset ( ) throws CoreException { return "" ; } } private TextMergeViewer fViewer ; private String fExpected ; private String fActual ; private String fTestName ; private static CompareResultDialog fgThis ; private int fPrefix ; private int fSuffix ; public CompareResultDialog ( Shell parentShell , TestRunInfo element ) { super ( parentShell ) ; fgThis = this ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE | SWT . MAX ) ; fTestName = element . getTestName ( ) ; fExpected = element . getExpected ( ) ; fActual = element . getActual ( ) ; computePrefixSuffix ( ) ; } private void computePrefixSuffix ( ) { int end = Math . min ( fExpected . length ( ) , fActual . length ( ) ) ; int i = ; for ( ; i < end ; i ++ ) if ( fExpected . charAt ( i ) != fActual . charAt ( i ) ) break ; fPrefix = i ; int j = fExpected . length ( ) - ; int k = fActual . length ( ) - ; int l = ; for ( ; k >= fPrefix && j >= fPrefix ; k -- , j -- ) { if ( fExpected . charAt ( j ) != fActual . charAt ( k ) ) break ; l ++ ; } fSuffix = l ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; newShell . setText ( TestUnitMessages . CompareResultDialog_title ) ; } protected void createButtonsForButtonBar ( Composite parent ) { createButton ( parent , IDialogConstants . OK_ID , TestUnitMessages . CompareResultDialog_labelOK , true ) ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; CompareViewerPane pane = new CompareViewerPane ( composite , SWT . BORDER | SWT . FLAT ) ; pane . setText ( fTestName ) ; GridData data = new GridData ( GridData . FILL_HORIZONTAL | GridData . FILL_VERTICAL ) ; data . widthHint = convertWidthInCharsToPixels ( ) ; data . heightHint = convertHeightInCharsToPixels ( ) ; pane . setLayoutData ( data ) ; Control previewer = createPreviewer ( pane ) ; pane . setContent ( previewer ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; previewer . setLayoutData ( gd ) ; applyDialogFont ( parent ) ; return composite ; } private Control createPreviewer ( Composite parent ) { final CompareConfiguration compareConfiguration = new CompareConfiguration ( ) ; compareConfiguration . setLeftLabel ( TestUnitMessages . CompareResultDialog_expectedLabel ) ; compareConfiguration . setLeftEditable ( false ) ; compareConfiguration . setRightLabel ( TestUnitMessages . CompareResultDialog_actualLabel ) ; compareConfiguration . setRightEditable ( false ) ; compareConfiguration . setProperty ( CompareConfiguration . IGNORE_WHITESPACE , Boolean . FALSE ) ; fViewer = new CompareResultMergeViewer ( parent , SWT . NONE , compareConfiguration ) ; fViewer . setInput ( new DiffNode ( new CompareElement ( fExpected ) , new CompareElement ( fActual ) ) ) ; Control control = fViewer . getControl ( ) ; control . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { if ( compareConfiguration != null ) compareConfiguration . dispose ( ) ; } } ) ; return control ; } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . util . Messages ; public class OpenTestAction extends OpenEditorAction { private String fMethodName ; private ISourceRange fRange ; public OpenTestAction ( TestUnitView testRunner , String className , String method ) { this ( testRunner , className , method , true ) ; } public OpenTestAction ( TestUnitView testRunner , String className ) { this ( testRunner , className , null ) ; } public OpenTestAction ( TestUnitView testRunner , String className , String method , boolean activate ) { super ( testRunner , className , activate ) ; fMethodName = method ; } protected IRubyElement findElement ( IRubyProject project , String className ) throws RubyModelException { IType type = findType ( project , className ) ; if ( type == null ) return null ; if ( fMethodName == null ) return type ; IMethod method = findMethod ( type ) ; if ( method == null ) { ITypeHierarchy typeHierarchy = type . newSupertypeHierarchy ( null ) ; IType [ ] types = typeHierarchy . getAllSuperclasses ( type ) ; for ( int i = ; i < types . length ; i ++ ) { method = findMethod ( types [ i ] ) ; if ( method != null ) break ; } } if ( method == null ) { String title = TestUnitMessages . OpenTestAction_error_title ; String message = Messages . format ( TestUnitMessages . OpenTestAction_error_methodNoFound , fMethodName ) ; MessageDialog . openInformation ( getShell ( ) , title , message ) ; return type ; } fRange = method . getNameRange ( ) ; return method ; } IMethod findMethod ( IType type ) { IStatus status = RubyConventions . validateMethodName ( fMethodName ) ; if ( ! status . isOK ( ) ) return null ; IMethod method = type . getMethod ( fMethodName , new String [ ] ) ; if ( method != null && method . exists ( ) ) return method ; return null ; } protected void reveal ( ITextEditor textEditor ) { if ( fRange != null ) textEditor . selectAndReveal ( fRange . getOffset ( ) , fRange . getLength ( ) ) ; } public boolean isEnabled ( ) { try { return findType ( getLaunchedProject ( ) , getClassName ( ) ) != null ; } catch ( RubyModelException e ) { } return false ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . util . List ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . InstanceScope ; public class TestUnitPreferenceInitializer extends AbstractPreferenceInitializer { private static final String BAD_FILTER = "" ; private static final String GOOD_FILTER = "" ; public void initializeDefaultPreferences ( ) { IEclipsePreferences prefs = new DefaultScope ( ) . getNode ( TestunitPlugin . PLUGIN_ID ) ; prefs . putBoolean ( TestUnitPreferencesConstants . DO_FILTER_STACK , true ) ; prefs . putBoolean ( TestUnitPreferencesConstants . SHOW_ON_ERROR_ONLY , false ) ; List < String > defaults = TestUnitPreferencesConstants . createDefaultStackFiltersList ( ) ; String [ ] filters = ( String [ ] ) defaults . toArray ( new String [ defaults . size ( ) ] ) ; String active = TestUnitPreferencesConstants . serializeList ( filters ) ; prefs . put ( TestUnitPreferencesConstants . PREF_ACTIVE_FILTERS_LIST , active ) ; prefs . put ( TestUnitPreferencesConstants . PREF_INACTIVE_FILTERS_LIST , "" ) ; IEclipsePreferences instance = new InstanceScope ( ) . getNode ( TestunitPlugin . PLUGIN_ID ) ; String activeFilters = instance . get ( TestUnitPreferencesConstants . PREF_ACTIVE_FILTERS_LIST , "" ) ; String [ ] activeFiltersAry = TestUnitPreferencesConstants . parseList ( activeFilters ) ; boolean found = false ; for ( int i = ; i < activeFiltersAry . length ; i ++ ) { String activeFilter = activeFiltersAry [ i ] ; if ( activeFilter . equals ( BAD_FILTER ) ) { activeFilter = GOOD_FILTER ; found = true ; break ; } } if ( found ) { instance . put ( TestUnitPreferencesConstants . PREF_ACTIVE_FILTERS_LIST , TestUnitPreferencesConstants . serializeList ( activeFiltersAry ) ) ; } } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . swt . custom . CTabFolder ; import org . eclipse . swt . dnd . Clipboard ; public abstract class TestRunTab { public abstract void createTabControl ( CTabFolder tabFolder , Clipboard clipboard , TestUnitView runner ) ; public abstract String getSelectedTestId ( ) ; public void activate ( ) { } public void setFocus ( ) { } public void aboutToStart ( ) { } public void aboutToEnd ( ) { } public abstract String getName ( ) ; public void setSelectedTest ( String testId ) { } public void startTest ( String testId ) { } public void endTest ( String testId ) { } public void testStatusChanged ( TestRunInfo newInfo ) { } public void newTreeEntry ( String treeEntry ) { } public void selectNext ( ) { } public void selectPrevious ( ) { } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . jface . action . Action ; public class ScrollLockAction extends Action { private TestUnitView fRunnerViewPart ; public ScrollLockAction ( TestUnitView viewer ) { super ( TestUnitMessages . ScrollLockAction_action_label ) ; fRunnerViewPart = viewer ; setToolTipText ( TestUnitMessages . ScrollLockAction_action_tooltip ) ; setDisabledImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setHoverImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setChecked ( false ) ; } public void run ( ) { fRunnerViewPart . setAutoScroll ( ! isChecked ( ) ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . text . MessageFormat ; import org . eclipse . osgi . util . NLS ; public class TestUnitMessages { private static final String BUNDLE_NAME = "" ; private TestUnitMessages ( ) { } public static String LaunchConfigurationTab_RubyEntryPoint_allTestCases ; public static String LaunchConfigurationTab_RubyEntryPoint_classSelectorMessage ; public static String LaunchConfigurationTab_RubyEntryPoint_classLabel ; public static String CompareResultsAction_label ; public static String CompareResultsAction_description ; public static String CompareResultsAction_tooltip ; public static String CopyTrace_action_label ; public static String CopyTraceAction_problem ; public static String CopyTraceAction_clipboard_busy ; public static String CounterPanel_label_runs ; public static String CounterPanel_label_errors ; public static String CounterPanel_label_failures ; public static String FailureRunView_tab_tooltip ; public static String FailureRunView_tab_title ; public static String OpenEditor_action_label ; public static String OpenEditorAction_action_label ; public static String RerunAction_label_debug ; public static String RerunAction_label_run ; public static String TestRunnerViewPart_label_failure ; public static String TestRunnerViewPart_error_cannotrerun ; public static String TestRunnerViewPart_cannotrerun_title ; public static String TestRunnerViewPart_cannotrerurn_message ; public static String TestRunnerViewPart_message_launching ; public static String TestRunnerViewPart_message_stopped ; public static String TestRunnerViewPart_message_terminated ; public static String TestRunnerViewPart_jobName ; public static String TestRunnerViewPart_terminate_title ; public static String TestRunnerViewPart_terminate_message ; public static String TestRunnerViewPart_rerunaction_label ; public static String TestRunnerViewPart_rerunaction_tooltip ; public static String LaunchTestAction_message_selectConfiguration ; public static String LaunchTestAction_message_selectDebugConfiguration ; public static String LaunchTestAction_message_selectRunConfiguration ; public static String Dialog_launchWithoutSelectedInterpreter_title ; public static String Dialog_launchWithoutSelectedInterpreter ; public static String LaunchConfigurationTab_RubyEntryPoint_allTestMethods ; public static String LaunchConfigurationTab_RubyEntryPoint_methodLabel ; public static String JUnitMainTab_tab_label ; public static String ExpandAllAction_text ; public static String ExpandAllAction_tooltip ; public static String HierarchyRunView_tab_tooltip ; public static String HierarchyRunView_tab_title ; public static String ScrollLockAction_action_label ; public static String ScrollLockAction_action_tooltip ; public static String RubyClassSelector_Title ; public static String CounterPanel_runcount ; public static String FailureRunView_labelfmt ; public static String TestRunnerViewPart_message_error ; public static String TestRunnerViewPart_message_failure ; public static String TestRunnerViewPart_message_success ; public static String TestRunnerViewPart_message_finish ; public static String TestRunnerViewPart_message_started ; public static String TestRunnerViewPart_configName ; public static String CompareResultDialog_expectedLabel ; public static String CompareResultDialog_actualLabel ; public static String CompareResultDialog_labelOK ; public static String CompareResultDialog_title ; public static String TestRunnerViewPart_toggle_horizontal_label ; public static String TestRunnerViewPart_toggle_vertical_label ; public static String TestRunnerViewPart_toggle_automatic_label ; public static String TestRunnerViewPart_layout_menu ; public static String OpenEditorAction_error_cannotopen_title ; public static String OpenEditorAction_error_cannotopen_message ; public static String OpenEditorAction_error_dialog_title ; public static String OpenEditorAction_error_dialog_message ; public static String OpenEditorAction_message_cannotopen ; public static String OpenTestAction_error_title ; public static String OpenTestAction_error_methodNoFound ; public static String TestUnitBaseLaunchConfiguration_error_invalidproject ; public static String JUnitBaseLaunchConfiguration_dialog_title ; public static String EnableStackFilterAction_action_tooltip ; public static String EnableStackFilterAction_action_description ; public static String EnableStackFilterAction_action_label ; public static String TestUnitMainTab_label_defaultpackage ; public static String TestUnitPreferencePage_invalidstepfilterreturnescape ; public static String TestUnitPreferencePage_disableallbutton_tooltip ; public static String TestUnitPreferencePage_disableallbutton_label ; public static String TestUnitPreferencePage_enableallbutton_tooltip ; public static String TestUnitPreferencePage_enableallbutton_label ; public static String TestUnitPreferencePage_removefilterbutton_tooltip ; public static String TestUnitPreferencePage_removefilterbutton_label ; public static String TestUnitPreferencePage_addfilterbutton_tooltip ; public static String TestUnitPreferencePage_addfilterbutton_label ; public static String TestUnitPreferencePage_filter_label ; public static String TestUnitPreferencePage_description ; public static String TestRunnerViewPart_activate_on_failure_only ; static { NLS . initializeMessages ( BUNDLE_NAME , TestUnitMessages . class ) ; } public static String getFormattedString ( String key , Object arg ) { return MessageFormat . format ( key , new Object [ ] { arg } ) ; } public static String getFormattedString ( String key , Object [ ] args ) { return MessageFormat . format ( key , args ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . net . MalformedURLException ; import java . text . NumberFormat ; import java . util . ArrayList ; import java . util . Enumeration ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import java . util . Vector ; import org . eclipse . core . commands . AbstractHandler ; import org . eclipse . core . commands . ExecutionEvent ; import org . eclipse . core . commands . ExecutionException ; import org . eclipse . core . commands . IHandler ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . ui . DebugUITools ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IStatusLineManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CLabel ; import org . eclipse . swt . custom . CTabFolder ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . custom . ViewForm ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . events . ControlListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . ToolBar ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IEditorActionBarContributor ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IPartListener2 ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . handlers . IHandlerActivation ; import org . eclipse . ui . handlers . IHandlerService ; import org . eclipse . ui . keys . IBindingService ; import org . eclipse . ui . part . EditorActionBarContributor ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . core . ElementChangedEvent ; import org . rubypeople . rdt . core . IElementChangedListener ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyElementDelta ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . testunit . ITestRunListener ; import org . rubypeople . rdt . testunit . launcher . TestUnitLaunchConfigurationDelegate ; public class TestUnitView extends ViewPart implements ITestRunListener3 { public static final String NAME = "" ; private static final String RERUN_LAST_COMMAND = "" ; static final int REFRESH_INTERVAL = ; public static final String ID_EXTENSION_POINT_TESTRUN_TABS = TestunitPlugin . PLUGIN_ID + "" + "" ; static enum VIEW_ORIENTATION { VERTICAL , HORIZONTAL , AUTOMATIC } ; private VIEW_ORIENTATION fOrientation = VIEW_ORIENTATION . AUTOMATIC ; private VIEW_ORIENTATION fCurrentOrientation ; private ToggleOrientationAction [ ] fToggleOrientationActions ; final Image fStackViewIcon = TestUnitView . createImage ( "" ) ; final Image fTestRunOKIcon = TestUnitView . createImage ( "" ) ; final Image fTestRunFailIcon = TestUnitView . createImage ( "" ) ; final Image fTestRunOKDirtyIcon = TestUnitView . createImage ( "" ) ; final Image fTestRunFailDirtyIcon = TestUnitView . createImage ( "" ) ; private TestRunTab fActiveRunTab ; protected Vector < TestRunTab > fTestRunTabs = new Vector < TestRunTab > ( ) ; private Map < String , TestRunInfo > fTestInfos = new HashMap < String , TestRunInfo > ( ) ; private boolean fIsDisposed = false ; private RemoteTestRunnerClient fTestRunnerClient ; private String fLaunchMode ; private ILaunch fLastLaunch ; private Action fRerunLastTestAction ; protected volatile int fExecutedTests ; protected volatile int fErrorCount ; protected volatile int fFailureCount ; protected volatile int fTestCount ; private List < TestRunInfo > fFailures = new ArrayList < TestRunInfo > ( ) ; protected boolean fShowOnErrorOnly = false ; private CounterPanel fCounterPanel ; private TestUnitProgressBar fProgressBar ; protected ProgressImages fProgressImages ; protected Image fViewImage ; private Composite fCounterComposite ; private Composite fParent ; private SashForm fSashForm ; private CTabFolder fTabFolder ; private FailureTrace fFailureTrace ; private Clipboard fClipboard ; protected volatile String fStatus ; Image fOriginalViewImage ; IElementChangedListener fDirtyListener ; private UpdateUIJob fUpdateJob ; private boolean fAutoScroll = true ; private ScrollLockAction fScrollLockAction ; private IRubyProject fTestProject ; private IMenuListener fViewMenuListener ; private ActivateOnErrorAction fActivateOnErrorAction ; private boolean fIsRunning = false ; private boolean fIsStopped = false ; private int fStartedCount = ; private IPartListener2 fPartListener = new IPartListener2 ( ) { public void partActivated ( IWorkbenchPartReference ref ) { } public void partBroughtToTop ( IWorkbenchPartReference ref ) { } public void partInputChanged ( IWorkbenchPartReference ref ) { } public void partClosed ( IWorkbenchPartReference ref ) { } public void partDeactivated ( IWorkbenchPartReference ref ) { } public void partOpened ( IWorkbenchPartReference ref ) { } public void partVisible ( IWorkbenchPartReference ref ) { if ( getSite ( ) . getId ( ) . equals ( ref . getId ( ) ) ) { fPartIsVisible = true ; } } public void partHidden ( IWorkbenchPartReference ref ) { if ( getSite ( ) . getId ( ) . equals ( ref . getId ( ) ) ) { fPartIsVisible = false ; } } } ; protected boolean fPartIsVisible = false ; private IHandlerActivation fRerunLastActivation ; public TestUnitView ( ) { } public static Image createImage ( String path ) { try { ImageDescriptor id = ImageDescriptor . createFromURL ( TestunitPlugin . makeIconFileURL ( path ) ) ; return id . createImage ( ) ; } catch ( MalformedURLException e ) { } return null ; } public void createPartControl ( Composite parent ) { fParent = parent ; addResizeListener ( parent ) ; fClipboard = new Clipboard ( parent . getDisplay ( ) ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . marginWidth = ; gridLayout . marginHeight = ; parent . setLayout ( gridLayout ) ; configureToolBar ( ) ; fCounterComposite = createProgressCountPanel ( parent ) ; fCounterComposite . setLayoutData ( new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL ) ) ; SashForm sashForm = createSashForm ( parent ) ; sashForm . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; fOriginalViewImage = getTitleImage ( ) ; fProgressImages = new ProgressImages ( ) ; getViewSite ( ) . getPage ( ) . addPartListener ( fPartListener ) ; } private class ToggleOrientationAction extends Action { private final VIEW_ORIENTATION fActionOrientation ; public ToggleOrientationAction ( TestUnitView v , VIEW_ORIENTATION orientation ) { super ( "" , AS_RADIO_BUTTON ) ; if ( orientation == VIEW_ORIENTATION . HORIZONTAL ) { setText ( TestUnitMessages . TestRunnerViewPart_toggle_horizontal_label ) ; setImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; } else if ( orientation == VIEW_ORIENTATION . VERTICAL ) { setText ( TestUnitMessages . TestRunnerViewPart_toggle_vertical_label ) ; setImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; } else if ( orientation == VIEW_ORIENTATION . AUTOMATIC ) { setText ( TestUnitMessages . TestRunnerViewPart_toggle_automatic_label ) ; setImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; } fActionOrientation = orientation ; } public VIEW_ORIENTATION getOrientation ( ) { return fActionOrientation ; } public void run ( ) { if ( isChecked ( ) ) { fOrientation = fActionOrientation ; computeOrientation ( ) ; } } } private void configureToolBar ( ) { IActionBars actionBars = getViewSite ( ) . getActionBars ( ) ; IToolBarManager toolBar = actionBars . getToolBarManager ( ) ; IMenuManager viewMenu = actionBars . getMenuManager ( ) ; fRerunLastTestAction = new RerunLastAction ( ) ; IHandlerService handlerService = ( IHandlerService ) getSite ( ) . getWorkbenchWindow ( ) . getService ( IHandlerService . class ) ; IHandler handler = new AbstractHandler ( ) { public Object execute ( ExecutionEvent event ) throws ExecutionException { fRerunLastTestAction . run ( ) ; return null ; } public boolean isEnabled ( ) { return fRerunLastTestAction . isEnabled ( ) ; } } ; fRerunLastActivation = handlerService . activateHandler ( RERUN_LAST_COMMAND , handler ) ; fScrollLockAction = new ScrollLockAction ( this ) ; toolBar . add ( new Separator ( ) ) ; toolBar . add ( fRerunLastTestAction ) ; toolBar . add ( fScrollLockAction ) ; fToggleOrientationActions = new ToggleOrientationAction [ ] { new ToggleOrientationAction ( this , VIEW_ORIENTATION . VERTICAL ) , new ToggleOrientationAction ( this , VIEW_ORIENTATION . HORIZONTAL ) , new ToggleOrientationAction ( this , VIEW_ORIENTATION . AUTOMATIC ) } ; MenuManager layoutSubMenu = new MenuManager ( TestUnitMessages . TestRunnerViewPart_layout_menu ) ; for ( int i = ; i < fToggleOrientationActions . length ; ++ i ) { layoutSubMenu . add ( fToggleOrientationActions [ i ] ) ; } viewMenu . add ( layoutSubMenu ) ; viewMenu . add ( new Separator ( ) ) ; fScrollLockAction . setChecked ( ! fAutoScroll ) ; fActivateOnErrorAction = new ActivateOnErrorAction ( ) ; viewMenu . add ( fActivateOnErrorAction ) ; fViewMenuListener = new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager manager ) { fActivateOnErrorAction . update ( ) ; } } ; viewMenu . addMenuListener ( fViewMenuListener ) ; actionBars . updateActionBars ( ) ; } private SashForm createSashForm ( Composite parent ) { fSashForm = new SashForm ( parent , SWT . VERTICAL ) ; ViewForm top = new ViewForm ( fSashForm , SWT . NONE ) ; fTabFolder = createTestRunTabs ( top ) ; fTabFolder . setLayoutData ( new TabFolderLayout ( ) ) ; top . setContent ( fTabFolder ) ; ViewForm bottom = new ViewForm ( fSashForm , SWT . NONE ) ; CLabel label = new CLabel ( bottom , SWT . NONE ) ; label . setText ( TestUnitMessages . TestRunnerViewPart_label_failure ) ; label . setImage ( fStackViewIcon ) ; bottom . setTopLeft ( label ) ; ToolBar failureToolBar = new ToolBar ( bottom , SWT . FLAT | SWT . WRAP ) ; bottom . setTopCenter ( failureToolBar ) ; fFailureTrace = new FailureTrace ( bottom , fClipboard , this , failureToolBar ) ; bottom . setContent ( fFailureTrace . getComposite ( ) ) ; fSashForm . setWeights ( new int [ ] { , } ) ; return fSashForm ; } protected CTabFolder createTestRunTabs ( Composite parent ) { CTabFolder tabFolder = new CTabFolder ( parent , SWT . TOP ) ; tabFolder . setLayoutData ( new GridData ( GridData . FILL_BOTH | GridData . GRAB_VERTICAL ) ) ; loadTestRunTabs ( tabFolder ) ; tabFolder . setSelection ( ) ; fActiveRunTab = fTestRunTabs . firstElement ( ) ; tabFolder . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent event ) { testTabChanged ( event ) ; } } ) ; return tabFolder ; } private void testTabChanged ( SelectionEvent event ) { for ( Enumeration e = fTestRunTabs . elements ( ) ; e . hasMoreElements ( ) ; ) { TestRunTab v = ( TestRunTab ) e . nextElement ( ) ; if ( ( ( CTabFolder ) event . widget ) . getSelection ( ) . getText ( ) == v . getName ( ) ) { v . setSelectedTest ( fActiveRunTab . getSelectedTestId ( ) ) ; fActiveRunTab = v ; fActiveRunTab . activate ( ) ; } } } private void loadTestRunTabs ( CTabFolder tabFolder ) { IExtensionPoint extensionPoint = Platform . getExtensionRegistry ( ) . getExtensionPoint ( ID_EXTENSION_POINT_TESTRUN_TABS ) ; if ( extensionPoint == null ) { return ; } IConfigurationElement [ ] configs = extensionPoint . getConfigurationElements ( ) ; MultiStatus status = new MultiStatus ( TestunitPlugin . PLUGIN_ID , IStatus . OK , "" , null ) ; for ( int i = ; i < configs . length ; i ++ ) { try { TestRunTab testRunTab = ( TestRunTab ) configs [ i ] . createExecutableExtension ( "" ) ; testRunTab . createTabControl ( tabFolder , fClipboard , this ) ; fTestRunTabs . addElement ( testRunTab ) ; } catch ( CoreException e ) { status . add ( e . getStatus ( ) ) ; } } if ( ! status . isOK ( ) ) { TestunitPlugin . log ( status ) ; } } protected Composite createProgressCountPanel ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; composite . setLayout ( layout ) ; setCounterColumns ( layout ) ; fCounterPanel = new CounterPanel ( composite ) ; fCounterPanel . setLayoutData ( new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL ) ) ; fProgressBar = new TestUnitProgressBar ( composite ) ; fProgressBar . setLayoutData ( new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL ) ) ; return composite ; } private void setCounterColumns ( GridLayout layout ) { if ( fCurrentOrientation == VIEW_ORIENTATION . HORIZONTAL ) layout . numColumns = ; else layout . numColumns = ; } public void setFocus ( ) { if ( fActiveRunTab != null ) fActiveRunTab . setFocus ( ) ; } public void showTest ( TestRunInfo test ) { fActiveRunTab . setSelectedTest ( test . getTestId ( ) ) ; handleTestSelected ( test . getTestId ( ) ) ; } public void handleTestSelected ( String testId ) { TestRunInfo testInfo = getTestInfo ( testId ) ; if ( testInfo == null ) { showFailure ( null ) ; } else { showFailure ( testInfo ) ; } } public TestRunInfo getTestInfo ( String testId ) { if ( testId == null ) return null ; return fTestInfos . get ( testId ) ; } private void showFailure ( final TestRunInfo failure ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( ! isDisposed ( ) ) fFailureTrace . showFailure ( failure ) ; } } ) ; } private void postSyncRunnable ( Runnable r ) { if ( ! isDisposed ( ) ) getDisplay ( ) . syncExec ( r ) ; } private boolean isDisposed ( ) { return fIsDisposed || fCounterPanel . isDisposed ( ) ; } private Display getDisplay ( ) { return getViewSite ( ) . getShell ( ) . getDisplay ( ) ; } public synchronized void dispose ( ) { fIsDisposed = true ; stopTest ( ) ; IHandlerService handlerService = ( IHandlerService ) getSite ( ) . getWorkbenchWindow ( ) . getService ( IHandlerService . class ) ; handlerService . deactivateHandler ( fRerunLastActivation ) ; if ( fProgressImages != null ) fProgressImages . dispose ( ) ; fTestRunOKIcon . dispose ( ) ; fTestRunFailIcon . dispose ( ) ; fStackViewIcon . dispose ( ) ; fTestRunOKDirtyIcon . dispose ( ) ; fTestRunFailDirtyIcon . dispose ( ) ; getViewSite ( ) . getPage ( ) . removePartListener ( fPartListener ) ; if ( fClipboard != null ) fClipboard . dispose ( ) ; } public void rerunTest ( String testId , String className , String testName , String launchMode ) { DebugUITools . saveAndBuildBeforeLaunch ( ) ; if ( lastLaunchIsKeptAlive ( ) ) fTestRunnerClient . rerunTest ( testId , className , testName ) ; else if ( fLastLaunch != null ) { ILaunchConfiguration launchConfiguration = fLastLaunch . getLaunchConfiguration ( ) ; if ( launchConfiguration != null ) { try { String name = className ; if ( testName != null ) name += "" + testName ; String configName = TestUnitMessages . getFormattedString ( TestUnitMessages . TestRunnerViewPart_configName , name ) ; ILaunchConfigurationWorkingCopy tmp = launchConfiguration . copy ( configName ) ; tmp . setAttribute ( TestUnitLaunchConfigurationDelegate . TESTTYPE_ATTR , className ) ; if ( testName != null ) { tmp . setAttribute ( TestUnitLaunchConfigurationDelegate . TESTNAME_ATTR , testName ) ; } tmp . launch ( launchMode , null ) ; return ; } catch ( CoreException e ) { ErrorDialog . openError ( getSite ( ) . getShell ( ) , TestUnitMessages . TestRunnerViewPart_error_cannotrerun , e . getMessage ( ) , e . getStatus ( ) ) ; } } MessageDialog . openInformation ( getSite ( ) . getShell ( ) , TestUnitMessages . TestRunnerViewPart_cannotrerun_title , TestUnitMessages . TestRunnerViewPart_cannotrerurn_message ) ; } } public boolean lastLaunchIsKeptAlive ( ) { return fTestRunnerClient != null && fTestRunnerClient . isRunning ( ) && ILaunchManager . DEBUG_MODE . equals ( fLaunchMode ) ; } public void startTestRunListening ( int port , IType type , ILaunch launch , Set < ITestRunListener > testRunListeners ) { if ( type != null ) fTestProject = type . getRubyProject ( ) ; else { try { String projectName = launch . getLaunchConfiguration ( ) . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , ( String ) null ) ; fTestProject = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) . getRubyProject ( projectName ) ; } catch ( CoreException e ) { TestunitPlugin . log ( e ) ; } } fLaunchMode = launch . getLaunchMode ( ) ; aboutToLaunch ( ) ; if ( fTestRunnerClient != null ) { stopTest ( ) ; } fTestRunnerClient = new RemoteTestRunnerClient ( ) ; ITestRunListener [ ] listenerArray = new ITestRunListener [ testRunListeners . size ( ) + ] ; listenerArray [ ] = this ; Iterator < ITestRunListener > iter = testRunListeners . iterator ( ) ; for ( int i = ; i < testRunListeners . size ( ) ; i ++ ) { listenerArray [ i + ] = iter . next ( ) ; } fTestRunnerClient . startListening ( listenerArray , port ) ; fLastLaunch = launch ; setViewPartTitle ( type ) ; if ( type instanceof IType ) setTitleToolTip ( ( ( IType ) type ) . getFullyQualifiedName ( ) ) ; else if ( type != null ) setTitleToolTip ( type . getElementName ( ) ) ; } protected void aboutToLaunch ( ) { String msg = TestUnitMessages . TestRunnerViewPart_message_launching ; showInformation ( msg ) ; setInfoMessage ( msg ) ; fViewImage = fOriginalViewImage ; firePropertyChange ( IWorkbenchPart . PROP_TITLE ) ; } protected void showInformation ( final String info ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( ! isDisposed ( ) ) fFailureTrace . setInformation ( info ) ; } } ) ; } protected void setInfoMessage ( final String message ) { fStatus = message ; } public void stopTest ( ) { if ( fTestRunnerClient != null ) fTestRunnerClient . stopTest ( ) ; stopUpdateJob ( ) ; } private void stopUpdateJob ( ) { if ( fUpdateJob != null ) { fUpdateJob . stop ( ) ; fUpdateJob = null ; } } public void setAutoScroll ( boolean scroll ) { fAutoScroll = scroll ; } public boolean isAutoScroll ( ) { return fAutoScroll ; } public boolean isCreated ( ) { return fCounterPanel != null ; } public void reset ( ) { reset ( ) ; setViewPartTitle ( null ) ; clearStatus ( ) ; resetViewIcon ( ) ; } private void clearStatus ( ) { getStatusLine ( ) . setMessage ( null ) ; getStatusLine ( ) . setErrorMessage ( null ) ; } private IStatusLineManager getStatusLine ( ) { IViewSite site = getViewSite ( ) ; IWorkbenchPage page = site . getPage ( ) ; IWorkbenchPart activePart = page . getActivePart ( ) ; if ( activePart instanceof IViewPart ) { IViewPart activeViewPart = ( IViewPart ) activePart ; IViewSite activeViewSite = activeViewPart . getViewSite ( ) ; return activeViewSite . getActionBars ( ) . getStatusLineManager ( ) ; } if ( activePart instanceof IEditorPart ) { IEditorPart activeEditorPart = ( IEditorPart ) activePart ; IEditorActionBarContributor contributor = activeEditorPart . getEditorSite ( ) . getActionBarContributor ( ) ; if ( contributor instanceof EditorActionBarContributor ) return ( ( EditorActionBarContributor ) contributor ) . getActionBars ( ) . getStatusLineManager ( ) ; } return getViewSite ( ) . getActionBars ( ) . getStatusLineManager ( ) ; } private void resetViewIcon ( ) { fViewImage = fOriginalViewImage ; firePropertyChange ( IWorkbenchPart . PROP_TITLE ) ; } private void setViewPartTitle ( IRubyElement type ) { String title ; if ( type == null ) title = "" ; else { if ( type instanceof IType ) { title = ( ( IType ) type ) . getFullyQualifiedName ( ) ; } else title = type . getElementName ( ) ; } setContentDescription ( title ) ; } private void reset ( final int testCount ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( isDisposed ( ) ) return ; fCounterPanel . reset ( ) ; fFailureTrace . clear ( ) ; fProgressBar . reset ( ) ; clearStatus ( ) ; start ( testCount ) ; } } ) ; fExecutedTests = ; fFailureCount = ; fErrorCount = ; fTestCount = testCount ; fIsRunning = false ; fIsStopped = false ; fStartedCount = ; aboutToStart ( ) ; fTestInfos . clear ( ) ; fFailures = new ArrayList < TestRunInfo > ( ) ; } protected void start ( final int total ) { resetProgressBar ( total ) ; fCounterPanel . setTotal ( total ) ; fCounterPanel . setRunValue ( ) ; } private void resetProgressBar ( final int total ) { fProgressBar . reset ( ) ; fProgressBar . setMaximum ( total ) ; } private void aboutToStart ( ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( ! isDisposed ( ) ) { for ( Enumeration e = fTestRunTabs . elements ( ) ; e . hasMoreElements ( ) ; ) { TestRunTab v = ( TestRunTab ) e . nextElement ( ) ; v . aboutToStart ( ) ; } } } } ) ; } public void testEnded ( String testId , String testName ) { postEndTest ( testId , testName ) ; fExecutedTests ++ ; } public void testFailed ( int status , String testId , String testName , String trace ) { testFailed ( status , testId , testName , trace , null , null ) ; } public void testFailed ( int status , String testId , String testName , String trace , String expected , String actual ) { TestRunInfo testInfo = getTestInfo ( testId ) ; if ( testInfo == null ) { testInfo = new TestRunInfo ( testId , testName ) ; fTestInfos . put ( testName , testInfo ) ; } testInfo . setTrace ( trace ) ; testInfo . setStatus ( status ) ; if ( expected != null ) { testInfo . setExpected ( expected . substring ( , expected . length ( ) - ) ) ; } if ( actual != null ) testInfo . setActual ( actual . substring ( , actual . length ( ) - ) ) ; if ( status == ITestRunListener . STATUS_ERROR ) fErrorCount ++ ; else fFailureCount ++ ; fFailures . add ( testInfo ) ; if ( fShowOnErrorOnly && ( fErrorCount + fFailureCount == ) ) postShowTestResultsView ( ) ; } protected void postShowTestResultsView ( ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( isDisposed ( ) ) return ; showTestResultsView ( ) ; } } ) ; } public void showTestResultsView ( ) { IWorkbenchWindow window = getSite ( ) . getWorkbenchWindow ( ) ; IWorkbenchPage page = window . getActivePage ( ) ; TestUnitView testRunner = null ; if ( page != null ) { try { testRunner = ( TestUnitView ) page . findView ( TestUnitView . NAME ) ; if ( testRunner == null ) { IWorkbenchPart activePart = page . getActivePart ( ) ; testRunner = ( TestUnitView ) page . showView ( TestUnitView . NAME ) ; page . activate ( activePart ) ; } else { page . bringToTop ( testRunner ) ; } } catch ( PartInitException pie ) { TestunitPlugin . log ( pie ) ; } } } public void testReran ( String testId , String className , String testName , int status , String trace ) { if ( status == ITestRunListener . STATUS_ERROR ) { String msg = TestUnitMessages . getFormattedString ( TestUnitMessages . TestRunnerViewPart_message_error , new String [ ] { testName , className } ) ; postError ( msg ) ; } else if ( status == ITestRunListener . STATUS_FAILURE ) { String msg = TestUnitMessages . getFormattedString ( TestUnitMessages . TestRunnerViewPart_message_failure , new String [ ] { testName , className } ) ; postError ( msg ) ; } else { String msg = TestUnitMessages . getFormattedString ( TestUnitMessages . TestRunnerViewPart_message_success , new String [ ] { testName , className } ) ; setInfoMessage ( msg ) ; } TestRunInfo info = getTestInfo ( testId ) ; updateTest ( info , status ) ; if ( info . getTrace ( ) == null || ! info . getTrace ( ) . equals ( trace ) ) { info . setTrace ( trace ) ; showFailure ( info ) ; } } protected void postError ( final String message ) { fStatus = message ; } private void updateTest ( TestRunInfo info , final int status ) { if ( status == info . getStatus ( ) ) return ; if ( info . getStatus ( ) == ITestRunListener . STATUS_OK ) { if ( status == ITestRunListener . STATUS_FAILURE ) fFailureCount ++ ; else if ( status == ITestRunListener . STATUS_ERROR ) fErrorCount ++ ; } else if ( info . getStatus ( ) == ITestRunListener . STATUS_ERROR ) { if ( status == ITestRunListener . STATUS_OK ) fErrorCount -- ; else if ( status == ITestRunListener . STATUS_FAILURE ) { fErrorCount -- ; fFailureCount ++ ; } } else if ( info . getStatus ( ) == ITestRunListener . STATUS_FAILURE ) { if ( status == ITestRunListener . STATUS_OK ) fFailureCount -- ; else if ( status == ITestRunListener . STATUS_ERROR ) { fFailureCount -- ; fErrorCount ++ ; } } info . setStatus ( status ) ; final TestRunInfo finalInfo = info ; postSyncRunnable ( new Runnable ( ) { public void run ( ) { for ( Enumeration e = fTestRunTabs . elements ( ) ; e . hasMoreElements ( ) ; ) { TestRunTab v = ( TestRunTab ) e . nextElement ( ) ; v . testStatusChanged ( finalInfo ) ; } } } ) ; } public void testReran ( String testId , String className , String testName , int statusCode , String trace , String expectedResult , String actualResult ) { testReran ( testId , className , testName , statusCode , trace ) ; TestRunInfo info = getTestInfo ( testId ) ; info . setActual ( actualResult ) ; info . setExpected ( expectedResult ) ; fFailureTrace . updateEnablement ( info ) ; } private void postEndTest ( final String testId , final String testName ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( isDisposed ( ) ) return ; handleEndTest ( ) ; for ( Enumeration e = fTestRunTabs . elements ( ) ; e . hasMoreElements ( ) ; ) { TestRunTab v = ( TestRunTab ) e . nextElement ( ) ; v . endTest ( testId ) ; } if ( fFailureCount + fErrorCount > ) { } } } ) ; } private void handleEndTest ( ) { fProgressBar . step ( fFailureCount + fErrorCount ) ; if ( fShowOnErrorOnly ) { Image progress = fProgressImages . getImage ( fExecutedTests , fTestCount , fErrorCount , fFailureCount ) ; if ( progress != fViewImage ) { fViewImage = progress ; firePropertyChange ( IWorkbenchPart . PROP_TITLE ) ; } } } public void setShowOnErrorOnly ( boolean showOnErrorOnly ) { this . fShowOnErrorOnly = showOnErrorOnly ; } public boolean getShowOnErrorOnly ( ) { return this . fShowOnErrorOnly ; } public void testStarted ( String testId , String testName ) { postStartTest ( testId , testName ) ; if ( ! fShowOnErrorOnly && fExecutedTests == ) postShowTestResultsView ( ) ; TestRunInfo testInfo = getTestInfo ( testId ) ; if ( testInfo == null ) { testInfo = new TestRunInfo ( testId , testName ) ; fTestInfos . put ( testId , testInfo ) ; } String className = testInfo . getClassName ( ) ; String method = testInfo . getTestMethodName ( ) ; String status = TestUnitMessages . getFormattedString ( TestUnitMessages . TestRunnerViewPart_message_started , new String [ ] { className , method } ) ; setInfoMessage ( status ) ; fStartedCount ++ ; } private void postStartTest ( final String testId , final String testName ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( isDisposed ( ) ) return ; for ( Enumeration e = fTestRunTabs . elements ( ) ; e . hasMoreElements ( ) ; ) { TestRunTab v = ( TestRunTab ) e . nextElement ( ) ; v . startTest ( testId ) ; } } } ) ; } public void testRunStopped ( final long elapsedTime ) { setInfoMessage ( TestUnitMessages . TestRunnerViewPart_message_stopped ) ; handleStopped ( ) ; fIsRunning = false ; fIsStopped = true ; } private void handleStopped ( ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( isDisposed ( ) ) return ; resetViewIcon ( ) ; fProgressBar . stopped ( ) ; } } ) ; stopUpdateJob ( ) ; } public void testRunEnded ( long elapsedTime ) { fExecutedTests -- ; fIsRunning = false ; String [ ] keys = { elapsedTimeAsString ( elapsedTime ) } ; String msg = TestUnitMessages . getFormattedString ( TestUnitMessages . TestRunnerViewPart_message_finish , keys ) ; if ( hasErrorsOrFailures ( ) ) postError ( msg ) ; else setInfoMessage ( msg ) ; postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( isDisposed ( ) ) return ; if ( fFailures . size ( ) > ) { selectFirstFailure ( ) ; } updateViewIcon ( ) ; if ( fDirtyListener == null ) { fDirtyListener = new DirtyListener ( ) ; RubyCore . addElementChangedListener ( fDirtyListener ) ; } for ( Enumeration e = fTestRunTabs . elements ( ) ; e . hasMoreElements ( ) ; ) { TestRunTab v = ( TestRunTab ) e . nextElement ( ) ; v . aboutToEnd ( ) ; } } } ) ; stopUpdateJob ( ) ; } private String elapsedTimeAsString ( long runTime ) { return NumberFormat . getInstance ( ) . format ( ( double ) runTime / ) ; } private boolean hasErrorsOrFailures ( ) { return fErrorCount + fFailureCount > ; } protected void selectFirstFailure ( ) { TestRunInfo firstFailure = fFailures . get ( ) ; if ( firstFailure != null && fAutoScroll ) { fActiveRunTab . setSelectedTest ( firstFailure . getTestId ( ) ) ; handleTestSelected ( firstFailure . getTestId ( ) ) ; } } public void testRunTerminated ( ) { String msg = TestUnitMessages . TestRunnerViewPart_message_terminated ; showMessage ( msg ) ; handleStopped ( ) ; fIsRunning = false ; fIsStopped = true ; } private void showMessage ( String msg ) { postError ( msg ) ; } public void testRunStarted ( final int testCount ) { reset ( testCount ) ; fExecutedTests ++ ; stopUpdateJob ( ) ; fUpdateJob = new UpdateUIJob ( TestUnitMessages . TestRunnerViewPart_jobName ) ; fUpdateJob . schedule ( REFRESH_INTERVAL ) ; fIsRunning = true ; } private void refreshCounters ( ) { fCounterPanel . setErrorValue ( fErrorCount ) ; fCounterPanel . setFailureValue ( fFailureCount ) ; fCounterPanel . setRunValue ( fExecutedTests ) ; fProgressBar . refresh ( fErrorCount + fFailureCount > ) ; } protected void doShowStatus ( ) { setContentDescription ( fStatus ) ; } public void testTreeEntry ( final String treeEntry ) { postSyncRunnable ( new Runnable ( ) { public void run ( ) { if ( isDisposed ( ) ) return ; for ( Enumeration e = fTestRunTabs . elements ( ) ; e . hasMoreElements ( ) ; ) { TestRunTab v = ( TestRunTab ) e . nextElement ( ) ; v . newTreeEntry ( treeEntry ) ; } } } ) ; } public void rerunTestRun ( ) { if ( lastLaunchIsKeptAlive ( ) ) { if ( MessageDialog . openQuestion ( getSite ( ) . getShell ( ) , TestUnitMessages . TestRunnerViewPart_terminate_title , TestUnitMessages . TestRunnerViewPart_terminate_message ) ) { if ( fTestRunnerClient != null ) fTestRunnerClient . stopTest ( ) ; } } if ( fLastLaunch != null && fLastLaunch . getLaunchConfiguration ( ) != null ) { DebugUITools . launch ( fLastLaunch . getLaunchConfiguration ( ) , fLastLaunch . getLaunchMode ( ) ) ; } } private void addResizeListener ( Composite parent ) { parent . addControlListener ( new ControlListener ( ) { public void controlMoved ( ControlEvent e ) { } public void controlResized ( ControlEvent e ) { computeOrientation ( ) ; } } ) ; } void computeOrientation ( ) { if ( fOrientation != VIEW_ORIENTATION . AUTOMATIC ) { fCurrentOrientation = fOrientation ; setOrientation ( fCurrentOrientation ) ; } else { Point size = fParent . getSize ( ) ; if ( size . x != && size . y != ) { if ( size . x > size . y ) setOrientation ( VIEW_ORIENTATION . HORIZONTAL ) ; else setOrientation ( VIEW_ORIENTATION . VERTICAL ) ; } } } private void setOrientation ( VIEW_ORIENTATION orientation ) { if ( ( fSashForm == null ) || fSashForm . isDisposed ( ) ) return ; boolean horizontal = orientation == VIEW_ORIENTATION . HORIZONTAL ; fSashForm . setOrientation ( horizontal ? SWT . HORIZONTAL : SWT . VERTICAL ) ; for ( int i = ; i < fToggleOrientationActions . length ; ++ i ) fToggleOrientationActions [ i ] . setChecked ( fOrientation == fToggleOrientationActions [ i ] . getOrientation ( ) ) ; fCurrentOrientation = orientation ; GridLayout layout = ( GridLayout ) fCounterComposite . getLayout ( ) ; setCounterColumns ( layout ) ; fParent . layout ( ) ; } public IRubyProject getLaunchedProject ( ) { return fTestProject ; } public ILaunch getLastLaunch ( ) { return fLastLaunch ; } private void processChangesInUI ( ) { if ( fSashForm . isDisposed ( ) ) return ; doShowStatus ( ) ; refreshCounters ( ) ; if ( ! fPartIsVisible ) updateViewTitleProgress ( ) ; else { updateViewIcon ( ) ; } } private void updateViewIcon ( ) { if ( fIsStopped || fIsRunning || fStartedCount == ) fViewImage = fOriginalViewImage ; else if ( hasErrorsOrFailures ( ) ) fViewImage = fTestRunFailIcon ; else fViewImage = fTestRunOKIcon ; firePropertyChange ( IWorkbenchPart . PROP_TITLE ) ; } public Image getTitleImage ( ) { if ( fOriginalViewImage == null ) fOriginalViewImage = super . getTitleImage ( ) ; if ( fViewImage == null ) return super . getTitleImage ( ) ; return fViewImage ; } private void updateViewTitleProgress ( ) { if ( fIsRunning ) { Image progress = fProgressImages . getImage ( fStartedCount , fTestCount , fErrorCount , fFailureCount ) ; if ( progress != fViewImage ) { fViewImage = progress ; firePropertyChange ( IWorkbenchPart . PROP_TITLE ) ; } } else { updateViewIcon ( ) ; } } void codeHasChanged ( ) { if ( fDirtyListener != null ) { RubyCore . removeElementChangedListener ( fDirtyListener ) ; fDirtyListener = null ; } if ( fViewImage == fTestRunOKIcon ) fViewImage = fTestRunOKDirtyIcon ; else if ( fViewImage == fTestRunFailIcon ) fViewImage = fTestRunFailDirtyIcon ; Runnable r = new Runnable ( ) { public void run ( ) { if ( isDisposed ( ) ) return ; firePropertyChange ( IWorkbenchPart . PROP_TITLE ) ; } } ; if ( ! isDisposed ( ) ) getDisplay ( ) . asyncExec ( r ) ; } class UpdateUIJob extends UIJob { private boolean fRunning = true ; public UpdateUIJob ( String name ) { super ( name ) ; setSystem ( true ) ; } public IStatus runInUIThread ( IProgressMonitor monitor ) { if ( ! isDisposed ( ) ) { processChangesInUI ( ) ; } schedule ( REFRESH_INTERVAL ) ; return Status . OK_STATUS ; } public void stop ( ) { fRunning = false ; } public boolean shouldSchedule ( ) { return fRunning ; } } private class RerunLastAction extends Action { public RerunLastAction ( ) { setText ( TestUnitMessages . TestRunnerViewPart_rerunaction_label ) ; setToolTipText ( TestUnitMessages . TestRunnerViewPart_rerunaction_tooltip ) ; setDisabledImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setHoverImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setActionDefinitionId ( RERUN_LAST_COMMAND ) ; } public void run ( ) { rerunTestRun ( ) ; } } private class ActivateOnErrorAction extends Action { public ActivateOnErrorAction ( ) { super ( TestUnitMessages . TestRunnerViewPart_activate_on_failure_only , IAction . AS_CHECK_BOX ) ; update ( ) ; } public void update ( ) { setChecked ( getShowOnErrorOnly ( ) ) ; } public void run ( ) { boolean checked = isChecked ( ) ; fShowOnErrorOnly = checked ; IPreferenceStore store = TestunitPlugin . getDefault ( ) . getPreferenceStore ( ) ; store . setValue ( TestUnitPreferencesConstants . SHOW_ON_ERROR_ONLY , checked ) ; } } private class DirtyListener implements IElementChangedListener { public void elementChanged ( ElementChangedEvent event ) { processDelta ( event . getDelta ( ) ) ; } private boolean processDelta ( IRubyElementDelta delta ) { int kind = delta . getKind ( ) ; int details = delta . getFlags ( ) ; int type = delta . getElement ( ) . getElementType ( ) ; switch ( type ) { case IRubyElement . RUBY_MODEL : case IRubyElement . RUBY_PROJECT : case IRubyElement . SOURCE_FOLDER_ROOT : case IRubyElement . SOURCE_FOLDER : if ( kind != IRubyElementDelta . CHANGED || details != IRubyElementDelta . F_CHILDREN ) { codeHasChanged ( ) ; return false ; } break ; case IRubyElement . SCRIPT : if ( ( details & IRubyElementDelta . F_PRIMARY_WORKING_COPY ) != ) return true ; codeHasChanged ( ) ; return false ; default : codeHasChanged ( ) ; return false ; } IRubyElementDelta [ ] affectedChildren = delta . getAffectedChildren ( ) ; if ( affectedChildren == null ) return true ; for ( int i = ; i < affectedChildren . length ; i ++ ) { if ( ! processDelta ( affectedChildren [ i ] ) ) return false ; } return true ; } } } package org . rubypeople . rdt . internal . testunit . ui ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . io . UnsupportedEncodingException ; import java . net . ServerSocket ; import java . net . Socket ; import java . net . SocketException ; import org . eclipse . core . runtime . ISafeRunnable ; import org . eclipse . core . runtime . SafeRunner ; import org . rubypeople . rdt . internal . testunit . runner . MessageIds ; import org . rubypeople . rdt . testunit . ITestRunListener ; public class RemoteTestRunnerClient { public abstract class ListenerSafeRunnable implements ISafeRunnable { public void handleException ( Throwable exception ) { TestunitPlugin . log ( exception ) ; } } abstract class ProcessingState { abstract ProcessingState readMessage ( String message ) ; } class DefaultProcessingState extends ProcessingState { ProcessingState readMessage ( String message ) { if ( message . startsWith ( MessageIds . TRACE_START ) ) { fFailedTrace = "" ; return fTraceState ; } if ( message . startsWith ( MessageIds . EXPECTED_START ) ) { fExpectedResult = null ; return fExpectedState ; } if ( message . startsWith ( MessageIds . ACTUAL_START ) ) { fActualResult = null ; return fActualState ; } if ( message . startsWith ( MessageIds . RTRACE_START ) ) { fFailedRerunTrace = "" ; return fRerunState ; } String arg = message . substring ( MessageIds . MSG_HEADER_LENGTH ) ; if ( message . startsWith ( MessageIds . TEST_RUN_START ) ) { int count = ; int v = arg . indexOf ( '' ) ; if ( v == - ) { fVersion = "" ; count = Integer . parseInt ( arg ) ; } else { fVersion = arg . substring ( v + ) ; String sc = arg . substring ( , v ) ; count = Integer . parseInt ( sc ) ; } notifyTestRunStarted ( count ) ; return this ; } if ( message . startsWith ( MessageIds . TEST_START ) ) { notifyTestStarted ( arg ) ; return this ; } if ( message . startsWith ( MessageIds . TEST_END ) ) { notifyTestEnded ( arg ) ; return this ; } if ( message . startsWith ( MessageIds . TEST_ERROR ) ) { extractFailure ( arg , ITestRunListener . STATUS_ERROR ) ; return this ; } if ( message . startsWith ( MessageIds . TEST_FAILED ) ) { extractFailure ( arg , ITestRunListener . STATUS_FAILURE ) ; return this ; } if ( message . startsWith ( MessageIds . TEST_RUN_END ) ) { long elapsedTime = Long . parseLong ( arg ) ; testRunEnded ( elapsedTime ) ; return this ; } if ( message . startsWith ( MessageIds . TEST_STOPPED ) ) { long elapsedTime = Long . parseLong ( arg ) ; notifyTestRunStopped ( elapsedTime ) ; shutDown ( ) ; return this ; } if ( message . startsWith ( MessageIds . TEST_TREE ) ) { notifyTestTreeEntry ( arg ) ; return this ; } if ( message . startsWith ( MessageIds . TEST_RERAN ) ) { if ( hasTestId ( ) ) scanReranMessage ( arg ) ; else scanOldReranMessage ( arg ) ; return this ; } return this ; } } class TraceProcessingState extends ProcessingState { ProcessingState readMessage ( String message ) { if ( message . startsWith ( MessageIds . TRACE_END ) ) { notifyTestFailed ( ) ; fFailedTrace = "" ; fExpectedResult = null ; fActualResult = null ; return fDefaultState ; } fFailedTrace += message + '' ; return this ; } } class ExpectedProcessingState extends ProcessingState { ProcessingState readMessage ( String message ) { if ( message . startsWith ( MessageIds . EXPECTED_END ) ) return fDefaultState ; if ( fExpectedResult == null ) fExpectedResult = message + '' ; else fExpectedResult += message + '' ; return this ; } } class ActualProcessingState extends ProcessingState { ProcessingState readMessage ( String message ) { if ( message . startsWith ( MessageIds . ACTUAL_END ) ) return fDefaultState ; if ( fActualResult == null ) fActualResult = message + '' ; else fActualResult += message + '' ; return this ; } } class RerunTraceProcessingState extends ProcessingState { ProcessingState readMessage ( String message ) { if ( message . startsWith ( MessageIds . RTRACE_END ) ) return fDefaultState ; fFailedRerunTrace += message + '' ; return this ; } } ProcessingState fDefaultState = new DefaultProcessingState ( ) ; ProcessingState fTraceState = new TraceProcessingState ( ) ; ProcessingState fExpectedState = new ExpectedProcessingState ( ) ; ProcessingState fActualState = new ActualProcessingState ( ) ; ProcessingState fRerunState = new RerunTraceProcessingState ( ) ; ProcessingState fCurrentState = fDefaultState ; private ITestRunListener [ ] fListeners ; private ServerSocket fServerSocket ; private Socket fSocket ; private int fPort = - ; private PrintWriter fWriter ; private BufferedReader fBufferedReader ; private String fVersion ; private String fFailedTest ; private String fFailedTestId ; private String fFailedTrace ; private String fExpectedResult ; private String fActualResult ; private String fFailedRerunTrace ; private int fFailureKind ; private boolean fDebug = false ; private class ServerConnection extends Thread { int fServerPort ; public ServerConnection ( int port ) { super ( "" ) ; fServerPort = port ; } public void run ( ) { try { if ( fDebug ) System . out . println ( "" + fServerPort ) ; fServerSocket = new ServerSocket ( fServerPort ) ; fSocket = fServerSocket . accept ( ) ; try { fBufferedReader = new BufferedReader ( new InputStreamReader ( fSocket . getInputStream ( ) , "" ) ) ; } catch ( UnsupportedEncodingException e ) { fBufferedReader = new BufferedReader ( new InputStreamReader ( fSocket . getInputStream ( ) ) ) ; } try { fWriter = new PrintWriter ( new OutputStreamWriter ( fSocket . getOutputStream ( ) , "" ) , true ) ; } catch ( UnsupportedEncodingException e1 ) { fWriter = new PrintWriter ( new OutputStreamWriter ( fSocket . getOutputStream ( ) ) , true ) ; } String message ; while ( fBufferedReader != null && ( message = readMessage ( fBufferedReader ) ) != null ) receiveMessage ( message ) ; } catch ( SocketException e ) { notifyTestRunTerminated ( ) ; } catch ( IOException e ) { System . out . println ( e ) ; } shutDown ( ) ; } } public synchronized void startListening ( ITestRunListener [ ] listeners , int port ) { fListeners = listeners ; fPort = port ; ServerConnection connection = new ServerConnection ( port ) ; connection . start ( ) ; } public synchronized void stopTest ( ) { if ( isRunning ( ) ) { fWriter . println ( MessageIds . TEST_STOP ) ; fWriter . flush ( ) ; } } private synchronized void shutDown ( ) { if ( fDebug ) System . out . println ( "" + fPort ) ; if ( fWriter != null ) { fWriter . close ( ) ; fWriter = null ; } try { if ( fBufferedReader != null ) { fBufferedReader . close ( ) ; fBufferedReader = null ; } } catch ( IOException e ) { } try { if ( fSocket != null ) { fSocket . close ( ) ; fSocket = null ; } } catch ( IOException e ) { } try { if ( fServerSocket != null ) { fServerSocket . close ( ) ; fServerSocket = null ; } } catch ( IOException e ) { } } public boolean isRunning ( ) { return fSocket != null ; } private String readMessage ( BufferedReader in ) throws IOException { return in . readLine ( ) ; } private void receiveMessage ( String message ) { fCurrentState = fCurrentState . readMessage ( message ) ; } private void scanOldReranMessage ( String arg ) { int c = arg . indexOf ( "" ) ; int t = arg . indexOf ( "" , c + ) ; String className = arg . substring ( , c ) ; String testName = arg . substring ( c + , t ) ; String status = arg . substring ( t + ) ; int statusCode = ITestRunListener . STATUS_OK ; if ( status . equals ( "" ) ) statusCode = ITestRunListener . STATUS_FAILURE ; else if ( status . equals ( "" ) ) statusCode = ITestRunListener . STATUS_ERROR ; String trace = "" ; if ( statusCode != ITestRunListener . STATUS_OK ) trace = fFailedRerunTrace ; notifyTestReran ( className + testName , className , testName , statusCode , trace ) ; } private void scanReranMessage ( String arg ) { int i = arg . indexOf ( '' ) ; int c = arg . indexOf ( '' , i + ) ; int t = arg . indexOf ( '' , c + ) ; String testId = arg . substring ( , i ) ; String className = arg . substring ( i + , c ) ; String testName = arg . substring ( c + , t ) ; String status = arg . substring ( t + ) ; int statusCode = ITestRunListener . STATUS_OK ; if ( status . equals ( "" ) ) statusCode = ITestRunListener . STATUS_FAILURE ; else if ( status . equals ( "" ) ) statusCode = ITestRunListener . STATUS_ERROR ; String trace = "" ; if ( statusCode != ITestRunListener . STATUS_OK ) trace = fFailedRerunTrace ; notifyTestReran ( testId , className , testName , statusCode , trace ) ; } private void extractFailure ( String arg , int status ) { String s [ ] = extractTestId ( arg ) ; fFailedTestId = s [ ] ; fFailedTest = s [ ] ; fFailureKind = status ; } String [ ] extractTestId ( String arg ) { String [ ] result = new String [ ] ; if ( ! hasTestId ( ) ) { result [ ] = arg ; result [ ] = arg ; return result ; } int i = arg . indexOf ( '' ) ; result [ ] = arg . substring ( , i ) ; result [ ] = arg . substring ( i + , arg . length ( ) ) ; return result ; } private boolean hasTestId ( ) { if ( fVersion == null ) return true ; return fVersion . equals ( "" ) ; } private void notifyTestReran ( final String testId , final String className , final String testName , final int statusCode , final String trace ) { for ( int i = ; i < fListeners . length ; i ++ ) { final ITestRunListener listener = fListeners [ i ] ; SafeRunner . run ( new ListenerSafeRunnable ( ) { public void run ( ) { if ( listener instanceof ITestRunListener3 ) ( ( ITestRunListener3 ) listener ) . testReran ( testId , className , testName , statusCode , trace , fExpectedResult , fActualResult ) ; else listener . testReran ( testId , className , testName , statusCode , trace ) ; } } ) ; } } private void notifyTestTreeEntry ( final String treeEntry ) { for ( int i = ; i < fListeners . length ; i ++ ) { if ( fListeners [ i ] instanceof ITestRunListener2 ) { ITestRunListener2 listener = ( ITestRunListener2 ) fListeners [ i ] ; if ( ! hasTestId ( ) ) listener . testTreeEntry ( fakeTestId ( treeEntry ) ) ; else listener . testTreeEntry ( treeEntry ) ; } } } private String fakeTestId ( String treeEntry ) { int index0 = treeEntry . indexOf ( '' ) ; String testName = treeEntry . substring ( , index0 ) . trim ( ) ; return testName + "" + treeEntry ; } private void notifyTestRunStopped ( final long elapsedTime ) { for ( int i = ; i < fListeners . length ; i ++ ) { final ITestRunListener listener = fListeners [ i ] ; SafeRunner . run ( new ListenerSafeRunnable ( ) { public void run ( ) { listener . testRunStopped ( elapsedTime ) ; } } ) ; } } private void testRunEnded ( final long elapsedTime ) { for ( int i = ; i < fListeners . length ; i ++ ) { final ITestRunListener listener = fListeners [ i ] ; SafeRunner . run ( new ListenerSafeRunnable ( ) { public void run ( ) { listener . testRunEnded ( elapsedTime ) ; } } ) ; } } private void notifyTestEnded ( final String test ) { for ( int i = ; i < fListeners . length ; i ++ ) { final ITestRunListener listener = fListeners [ i ] ; SafeRunner . run ( new ListenerSafeRunnable ( ) { public void run ( ) { String s [ ] = extractTestId ( test ) ; listener . testEnded ( s [ ] , s [ ] ) ; } } ) ; } } private void notifyTestStarted ( final String test ) { for ( int i = ; i < fListeners . length ; i ++ ) { final ITestRunListener listener = fListeners [ i ] ; SafeRunner . run ( new ListenerSafeRunnable ( ) { public void run ( ) { String s [ ] = extractTestId ( test ) ; listener . testStarted ( s [ ] , s [ ] ) ; } } ) ; } } private void notifyTestRunStarted ( final int count ) { for ( int i = ; i < fListeners . length ; i ++ ) { final ITestRunListener listener = fListeners [ i ] ; SafeRunner . run ( new ListenerSafeRunnable ( ) { public void run ( ) { listener . testRunStarted ( count ) ; } } ) ; } } private void notifyTestFailed ( ) { for ( int i = ; i < fListeners . length ; i ++ ) { final ITestRunListener listener = fListeners [ i ] ; SafeRunner . run ( new ListenerSafeRunnable ( ) { public void run ( ) { if ( listener instanceof ITestRunListener3 ) ( ( ITestRunListener3 ) listener ) . testFailed ( fFailureKind , fFailedTestId , fFailedTest , fFailedTrace , fExpectedResult , fActualResult ) ; else listener . testFailed ( fFailureKind , fFailedTestId , fFailedTest , fFailedTrace ) ; } } ) ; } } private void notifyTestRunTerminated ( ) { for ( int i = ; i < fListeners . length ; i ++ ) { final ITestRunListener listener = fListeners [ i ] ; SafeRunner . run ( new ListenerSafeRunnable ( ) { public void run ( ) { listener . testRunTerminated ( ) ; } } ) ; } } public void rerunTest ( String testId , String className , String testName ) { if ( isRunning ( ) ) { fWriter . println ( MessageIds . TEST_RERUN + testId + "" + className + "" + testName ) ; fWriter . flush ( ) ; } } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ControlAdapter ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . PaintEvent ; import org . eclipse . swt . events . PaintListener ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . widgets . Canvas ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; public class TestUnitProgressBar extends Canvas { private static final int DEFAULT_WIDTH = ; private static final int DEFAULT_HEIGHT = ; private int fCurrentTickCount = ; private int fMaxTickCount = ; private int fColorBarWidth = ; private Color fOKColor ; private Color fFailureColor ; private Color fStoppedColor ; private boolean fError ; private boolean fStopped = false ; public TestUnitProgressBar ( Composite parent ) { super ( parent , SWT . NONE ) ; addControlListener ( new ControlAdapter ( ) { public void controlResized ( ControlEvent e ) { fColorBarWidth = scale ( fCurrentTickCount ) ; redraw ( ) ; } } ) ; addPaintListener ( new PaintListener ( ) { public void paintControl ( PaintEvent e ) { paint ( e ) ; } } ) ; addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { fFailureColor . dispose ( ) ; fOKColor . dispose ( ) ; fStoppedColor . dispose ( ) ; } } ) ; Display display = parent . getDisplay ( ) ; fFailureColor = new Color ( display , , , ) ; fOKColor = new Color ( display , , , ) ; fStoppedColor = new Color ( display , , , ) ; } public void setMaximum ( int max ) { fMaxTickCount = max ; } public void reset ( ) { fError = false ; fStopped = false ; fCurrentTickCount = ; fColorBarWidth = ; fMaxTickCount = ; redraw ( ) ; } private void paintStep ( int startX , int endX ) { GC gc = new GC ( this ) ; setStatusColor ( gc ) ; Rectangle rect = getClientArea ( ) ; startX = Math . max ( , startX ) ; gc . fillRectangle ( startX , , endX - startX , rect . height - ) ; gc . dispose ( ) ; } private void setStatusColor ( GC gc ) { if ( fStopped ) gc . setBackground ( fStoppedColor ) ; else if ( fError ) gc . setBackground ( fFailureColor ) ; else if ( fStopped ) gc . setBackground ( fStoppedColor ) ; else gc . setBackground ( fOKColor ) ; } public void stopped ( ) { fStopped = true ; redraw ( ) ; } private int scale ( int value ) { if ( fMaxTickCount > ) { Rectangle r = getClientArea ( ) ; if ( r . width != ) return Math . max ( , value * ( r . width - ) / fMaxTickCount ) ; } return value ; } private void drawBevelRect ( GC gc , int x , int y , int w , int h , Color topleft , Color bottomright ) { gc . setForeground ( topleft ) ; gc . drawLine ( x , y , x + w - , y ) ; gc . drawLine ( x , y , x , y + h - ) ; gc . setForeground ( bottomright ) ; gc . drawLine ( x + w , y , x + w , y + h ) ; gc . drawLine ( x , y + h , x + w , y + h ) ; } private void paint ( PaintEvent event ) { GC gc = event . gc ; Display disp = getDisplay ( ) ; Rectangle rect = getClientArea ( ) ; gc . fillRectangle ( rect ) ; drawBevelRect ( gc , rect . x , rect . y , rect . width - , rect . height - , disp . getSystemColor ( SWT . COLOR_WIDGET_NORMAL_SHADOW ) , disp . getSystemColor ( SWT . COLOR_WIDGET_HIGHLIGHT_SHADOW ) ) ; setStatusColor ( gc ) ; fColorBarWidth = Math . min ( rect . width - , fColorBarWidth ) ; gc . fillRectangle ( , , fColorBarWidth , rect . height - ) ; } public Point computeSize ( int wHint , int hHint , boolean changed ) { checkWidget ( ) ; Point size = new Point ( DEFAULT_WIDTH , DEFAULT_HEIGHT ) ; if ( wHint != SWT . DEFAULT ) size . x = wHint ; if ( hHint != SWT . DEFAULT ) size . y = hHint ; return size ; } public void step ( int failures ) { fCurrentTickCount ++ ; int x = fColorBarWidth ; fColorBarWidth = scale ( fCurrentTickCount ) ; if ( ! fError && failures > ) { fError = true ; x = ; } if ( fCurrentTickCount == fMaxTickCount ) fColorBarWidth = getClientArea ( ) . width - ; paintStep ( x , fColorBarWidth ) ; } public void refresh ( boolean hasErrors ) { fError = hasErrors ; redraw ( ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; public class TestRunInfo extends Object { private String fTestId ; private String fTestName ; private String fTrace ; private String fExpected ; private String fActual ; private int fStatus ; public TestRunInfo ( String testId , String testName ) { fTestName = testName ; fTestId = testId ; } public int hashCode ( ) { return getTestId ( ) . hashCode ( ) ; } public boolean equals ( Object obj ) { return getTestId ( ) . equals ( obj ) ; } public String getTestId ( ) { return fTestId ; } public String getTestName ( ) { return fTestName ; } public String getClassName ( ) { return extractClassName ( getTestName ( ) ) ; } public String getTestMethodName ( ) { int index = fTestName . indexOf ( '' ) ; if ( index > ) return fTestName . substring ( , index ) ; index = fTestName . indexOf ( '' ) ; if ( index > ) return fTestName . substring ( , index ) ; return fTestName ; } private String extractClassName ( String testNameString ) { if ( testNameString == null ) return null ; int index = testNameString . indexOf ( '' ) ; if ( index < ) return testNameString ; testNameString = testNameString . substring ( index + ) ; return testNameString . substring ( , testNameString . indexOf ( '' ) ) ; } public void setTrace ( String trace ) { fTrace = trace ; } public String getTrace ( ) { return fTrace ; } public void setStatus ( int status ) { fStatus = status ; } public int getStatus ( ) { return fStatus ; } public String getActual ( ) { return fActual ; } public void setActual ( String actual ) { fActual = actual ; } public String getExpected ( ) { return fExpected ; } public void setExpected ( String expected ) { fExpected = expected ; } public boolean isComparisonFailure ( ) { return fExpected != null && fActual != null ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . StringReader ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CTabFolder ; import org . eclipse . swt . custom . CTabItem ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . MouseAdapter ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableItem ; import org . rubypeople . rdt . testunit . ITestRunListener ; public class FailureTab extends TestRunTab implements IMenuListener { private Table fTable ; private TestUnitView fRunnerViewPart ; private boolean fMoveSelection = false ; private final Image fErrorIcon = TestUnitView . createImage ( "" ) ; private final Image fFailureIcon = TestUnitView . createImage ( "" ) ; private final Image fFailureTabIcon = TestUnitView . createImage ( "" ) ; public FailureTab ( ) { } public void createTabControl ( CTabFolder tabFolder , Clipboard clipboard , TestUnitView runner ) { fRunnerViewPart = runner ; CTabItem failureTab = new CTabItem ( tabFolder , SWT . NONE ) ; failureTab . setText ( getName ( ) ) ; failureTab . setImage ( fFailureTabIcon ) ; Composite composite = new Composite ( tabFolder , SWT . NONE ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . marginHeight = ; gridLayout . marginWidth = ; composite . setLayout ( gridLayout ) ; GridData gridData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . VERTICAL_ALIGN_FILL | GridData . GRAB_HORIZONTAL | GridData . GRAB_VERTICAL ) ; composite . setLayoutData ( gridData ) ; fTable = new Table ( composite , SWT . NONE ) ; gridLayout = new GridLayout ( ) ; gridLayout . marginHeight = ; gridLayout . marginWidth = ; fTable . setLayout ( gridLayout ) ; gridData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL | GridData . VERTICAL_ALIGN_FILL | GridData . GRAB_HORIZONTAL | GridData . GRAB_VERTICAL ) ; fTable . setLayoutData ( gridData ) ; failureTab . setControl ( composite ) ; failureTab . setToolTipText ( TestUnitMessages . FailureRunView_tab_tooltip ) ; initMenu ( ) ; addListeners ( ) ; } private void disposeIcons ( ) { fErrorIcon . dispose ( ) ; fFailureIcon . dispose ( ) ; fFailureTabIcon . dispose ( ) ; } private void initMenu ( ) { MenuManager menuMgr = new MenuManager ( ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( this ) ; Menu menu = menuMgr . createContextMenu ( fTable ) ; fTable . setMenu ( menu ) ; } public String getName ( ) { return TestUnitMessages . FailureRunView_tab_title ; } public String getSelectedTestId ( ) { int index = fTable . getSelectionIndex ( ) ; if ( index == - ) return null ; return getTestInfo ( fTable . getItem ( index ) ) . getTestId ( ) ; } public String getAllFailedTestNames ( ) { StringBuffer trace = new StringBuffer ( ) ; String lineDelim = System . getProperty ( "" , "" ) ; for ( int i = ; i < fTable . getItemCount ( ) ; i ++ ) { TestRunInfo testInfo = getTestInfo ( fTable . getItem ( i ) ) ; trace . append ( testInfo . getTestName ( ) ) . append ( lineDelim ) ; String failureTrace = testInfo . getTrace ( ) ; if ( failureTrace != null ) { StringReader stringReader = new StringReader ( failureTrace ) ; BufferedReader bufferedReader = new BufferedReader ( stringReader ) ; String line ; try { while ( ( line = bufferedReader . readLine ( ) ) != null ) trace . append ( line + lineDelim ) ; } catch ( IOException e ) { trace . append ( lineDelim ) ; } } } return trace . toString ( ) ; } private String getClassName ( ) { TableItem item = getSelectedItem ( ) ; TestRunInfo info = getTestInfo ( item ) ; return info . getClassName ( ) ; } private String getMethodName ( ) { TableItem item = getSelectedItem ( ) ; TestRunInfo info = getTestInfo ( item ) ; return info . getTestMethodName ( ) ; } public void menuAboutToShow ( IMenuManager manager ) { if ( fTable . getSelectionCount ( ) > ) { String className = getClassName ( ) ; String methodName = getMethodName ( ) ; if ( className != null ) { manager . add ( new OpenTestAction ( fRunnerViewPart , className , methodName , true ) ) ; manager . add ( new Separator ( ) ) ; manager . add ( new RerunAction ( fRunnerViewPart , getSelectedTestId ( ) , className , methodName , ILaunchManager . RUN_MODE ) ) ; manager . add ( new RerunAction ( fRunnerViewPart , getSelectedTestId ( ) , className , methodName , ILaunchManager . DEBUG_MODE ) ) ; manager . add ( new Separator ( ) ) ; } } } private TableItem getSelectedItem ( ) { int index = fTable . getSelectionIndex ( ) ; if ( index == - ) return null ; return fTable . getItem ( index ) ; } public void setSelectedTest ( String testId ) { TableItem [ ] items = fTable . getItems ( ) ; for ( int i = ; i < items . length ; i ++ ) { TableItem tableItem = items [ i ] ; TestRunInfo info = getTestInfo ( tableItem ) ; if ( info . getTestId ( ) . equals ( testId ) ) { fTable . setSelection ( new TableItem [ ] { tableItem } ) ; fTable . showItem ( tableItem ) ; return ; } } } private TestRunInfo getTestInfo ( TableItem item ) { return ( TestRunInfo ) item . getData ( ) ; } public void setFocus ( ) { fTable . setFocus ( ) ; } public void endTest ( String testId ) { TestRunInfo testInfo = fRunnerViewPart . getTestInfo ( testId ) ; if ( testInfo == null || testInfo . getStatus ( ) == ITestRunListener . STATUS_OK ) return ; TableItem tableItem = new TableItem ( fTable , SWT . NONE ) ; updateTableItem ( testInfo , tableItem ) ; fTable . showItem ( tableItem ) ; } private void updateTableItem ( TestRunInfo testInfo , TableItem tableItem ) { String label = TestUnitMessages . getFormattedString ( TestUnitMessages . FailureRunView_labelfmt , new String [ ] { testInfo . getTestMethodName ( ) , testInfo . getClassName ( ) } ) ; tableItem . setText ( label ) ; if ( testInfo . getStatus ( ) == ITestRunListener . STATUS_FAILURE ) tableItem . setImage ( fFailureIcon ) ; else tableItem . setImage ( fErrorIcon ) ; tableItem . setData ( testInfo ) ; } private TableItem findItem ( String testId ) { TableItem [ ] items = fTable . getItems ( ) ; for ( int i = ; i < items . length ; i ++ ) { TestRunInfo info = getTestInfo ( items [ i ] ) ; if ( info . getTestId ( ) . equals ( testId ) ) return items [ i ] ; } return null ; } public void activate ( ) { fMoveSelection = false ; testSelected ( ) ; } public void aboutToStart ( ) { fMoveSelection = false ; fTable . removeAll ( ) ; } private void testSelected ( ) { fRunnerViewPart . handleTestSelected ( getSelectedTestId ( ) ) ; } private void addListeners ( ) { fTable . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { activate ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { activate ( ) ; } } ) ; fTable . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { disposeIcons ( ) ; } } ) ; fTable . addMouseListener ( new MouseAdapter ( ) { public void mouseDoubleClick ( MouseEvent e ) { handleDoubleClick ( e ) ; } public void mouseDown ( MouseEvent e ) { activate ( ) ; } public void mouseUp ( MouseEvent e ) { activate ( ) ; } } ) ; } void handleDoubleClick ( MouseEvent e ) { if ( fTable . getSelectionCount ( ) > ) new OpenTestAction ( fRunnerViewPart , getClassName ( ) , getMethodName ( ) , true ) . run ( ) ; } public void testStatusChanged ( TestRunInfo info ) { TableItem item = findItem ( info . getTestId ( ) ) ; if ( item != null ) { if ( info . getStatus ( ) == ITestRunListener . STATUS_OK ) { item . dispose ( ) ; return ; } updateTableItem ( info , item ) ; } if ( item == null && info . getStatus ( ) != ITestRunListener . STATUS_OK ) { item = new TableItem ( fTable , SWT . NONE ) ; updateTableItem ( info , item ) ; } if ( item != null ) fTable . showItem ( item ) ; } public void selectNext ( ) { if ( fTable . getItemCount ( ) == ) return ; int index = fTable . getSelectionIndex ( ) ; if ( index == - ) index = ; if ( fMoveSelection ) index = Math . min ( fTable . getItemCount ( ) - , index + ) ; else fMoveSelection = true ; selectTest ( index ) ; } public void selectPrevious ( ) { if ( fTable . getItemCount ( ) == ) return ; int index = fTable . getSelectionIndex ( ) ; if ( index == - ) index = fTable . getItemCount ( ) - ; if ( fMoveSelection ) index = Math . max ( , index - ) ; else fMoveSelection = true ; selectTest ( index ) ; } private void selectTest ( int index ) { TableItem item = fTable . getItem ( index ) ; TestRunInfo info = getTestInfo ( item ) ; fRunnerViewPart . showTest ( info ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . ListIterator ; import java . util . Map ; import java . util . Vector ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . CTabFolder ; import org . eclipse . swt . custom . CTabItem ; import org . eclipse . swt . dnd . Clipboard ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . MouseAdapter ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Tree ; import org . eclipse . swt . widgets . TreeItem ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . testunit . ITestRunListener ; public class TestHierarchyTab extends TestRunTab implements IMenuListener { private Tree fTree ; private TreeItem fCachedParent ; private TreeItem [ ] fCachedItems ; private TreeItem fLastParent ; private List < TreeItem > fExecutionPath ; private boolean fMoveSelection = false ; private static class SuiteInfo { public int fTestCount ; public TreeItem fTreeItem ; public SuiteInfo ( TreeItem treeItem , int testCount ) { fTreeItem = treeItem ; fTestCount = testCount ; } } private Vector < SuiteInfo > fSuiteInfos = new Vector < SuiteInfo > ( ) ; private Map < String , TreeItem > fTreeItemMap = new HashMap < String , TreeItem > ( ) ; private TestUnitView fTestRunnerPart ; private final Image fOkIcon = TestUnitView . createImage ( "" ) ; private final Image fErrorIcon = TestUnitView . createImage ( "" ) ; private final Image fFailureIcon = TestUnitView . createImage ( "" ) ; private final Image fHierarchyIcon = TestUnitView . createImage ( "" ) ; private final Image fSuiteIcon = TestUnitView . createImage ( "" ) ; private final Image fSuiteErrorIcon = TestUnitView . createImage ( "" ) ; private final Image fSuiteFailIcon = TestUnitView . createImage ( "" ) ; private final Image fTestIcon = TestUnitView . createImage ( "" ) ; private final Image fTestRunningIcon = TestUnitView . createImage ( "" ) ; private final Image fSuiteRunningIcon = TestUnitView . createImage ( "" ) ; private class ExpandAllAction extends Action { public ExpandAllAction ( ) { setText ( TestUnitMessages . ExpandAllAction_text ) ; setToolTipText ( TestUnitMessages . ExpandAllAction_tooltip ) ; } public void run ( ) { expandAll ( ) ; } } public TestHierarchyTab ( ) { } public void createTabControl ( CTabFolder tabFolder , Clipboard clipboard , TestUnitView runner ) { fTestRunnerPart = runner ; CTabItem hierarchyTab = new CTabItem ( tabFolder , SWT . NONE ) ; hierarchyTab . setText ( getName ( ) ) ; hierarchyTab . setImage ( fHierarchyIcon ) ; Composite testTreePanel = new Composite ( tabFolder , SWT . NONE ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . marginHeight = ; gridLayout . marginWidth = ; testTreePanel . setLayout ( gridLayout ) ; GridData gridData = new GridData ( GridData . GRAB_HORIZONTAL | GridData . GRAB_VERTICAL ) ; testTreePanel . setLayoutData ( gridData ) ; hierarchyTab . setControl ( testTreePanel ) ; hierarchyTab . setToolTipText ( TestUnitMessages . HierarchyRunView_tab_tooltip ) ; fTree = new Tree ( testTreePanel , SWT . V_SCROLL | SWT . SINGLE ) ; gridData = new GridData ( GridData . FILL_BOTH | GridData . GRAB_HORIZONTAL | GridData . GRAB_VERTICAL ) ; fTree . setLayoutData ( gridData ) ; initMenu ( ) ; addListeners ( ) ; } void disposeIcons ( ) { fErrorIcon . dispose ( ) ; fFailureIcon . dispose ( ) ; fOkIcon . dispose ( ) ; fHierarchyIcon . dispose ( ) ; fTestIcon . dispose ( ) ; fTestRunningIcon . dispose ( ) ; fSuiteRunningIcon . dispose ( ) ; fSuiteIcon . dispose ( ) ; fSuiteErrorIcon . dispose ( ) ; fSuiteFailIcon . dispose ( ) ; } private void initMenu ( ) { MenuManager menuMgr = new MenuManager ( ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( this ) ; Menu menu = menuMgr . createContextMenu ( fTree ) ; fTree . setMenu ( menu ) ; } private String getTestMethod ( ) { return getTestInfo ( ) . getTestMethodName ( ) ; } private TestRunInfo getTestInfo ( ) { TreeItem [ ] treeItems = fTree . getSelection ( ) ; if ( treeItems . length == ) return null ; return ( ( TestRunInfo ) treeItems [ ] . getData ( ) ) ; } private boolean isSuiteSelected ( ) { TreeItem [ ] treeItems = fTree . getSelection ( ) ; if ( treeItems . length != ) return false ; return treeItems [ ] . getItemCount ( ) > ; } private String getClassName ( ) { return getTestInfo ( ) . getClassName ( ) ; } public String getSelectedTestId ( ) { TestRunInfo testInfo = getTestInfo ( ) ; if ( testInfo == null ) return null ; return testInfo . getTestId ( ) ; } public String getName ( ) { return TestUnitMessages . HierarchyRunView_tab_title ; } public void setSelectedTest ( String testId ) { TreeItem treeItem = findTreeItem ( testId ) ; if ( treeItem != null ) fTree . setSelection ( new TreeItem [ ] { treeItem } ) ; } public void startTest ( String testId ) { TreeItem treeItem = findTreeItem ( testId ) ; if ( treeItem == null ) return ; TreeItem parent = treeItem . getParentItem ( ) ; if ( fLastParent != parent ) { updatePath ( parent ) ; fLastParent = parent ; } setCurrentItem ( treeItem ) ; } private void updatePath ( TreeItem parent ) { List < TreeItem > newPath = new ArrayList < TreeItem > ( ) ; while ( parent != null ) { newPath . add ( parent ) ; parent = parent . getParentItem ( ) ; } Collections . reverse ( newPath ) ; ListIterator < TreeItem > old = fExecutionPath . listIterator ( ) ; ListIterator < TreeItem > np = newPath . listIterator ( ) ; int c = ; while ( old . hasNext ( ) && np . hasNext ( ) ) { if ( old . next ( ) != np . next ( ) ) break ; c ++ ; } for ( ListIterator < TreeItem > iter = fExecutionPath . listIterator ( c ) ; iter . hasNext ( ) ; ) refreshItem ( iter . next ( ) , false ) ; for ( ListIterator < TreeItem > iter = newPath . listIterator ( c ) ; iter . hasNext ( ) ; ) refreshItem ( iter . next ( ) , true ) ; fExecutionPath = newPath ; } private void refreshItem ( TreeItem item , boolean onPath ) { if ( onPath ) item . setImage ( fSuiteRunningIcon ) ; else { TestRunInfo info = getTestRunInfo ( item ) ; switch ( info . getStatus ( ) ) { case ITestRunListener . STATUS_ERROR : item . setImage ( fSuiteErrorIcon ) ; break ; case ITestRunListener . STATUS_FAILURE : item . setImage ( fSuiteFailIcon ) ; break ; default : item . setImage ( fSuiteIcon ) ; } } } private void setCurrentItem ( TreeItem treeItem ) { treeItem . setImage ( fTestRunningIcon ) ; TreeItem parent = treeItem . getParentItem ( ) ; if ( fTestRunnerPart . isAutoScroll ( ) ) { fTree . showItem ( treeItem ) ; while ( parent != null ) { if ( parent . getExpanded ( ) ) break ; parent . setExpanded ( true ) ; parent = parent . getParentItem ( ) ; } } } public void endTest ( String testId ) { TreeItem treeItem = findTreeItem ( testId ) ; if ( treeItem == null ) return ; TestRunInfo testInfo = fTestRunnerPart . getTestInfo ( testId ) ; if ( testInfo == null ) return ; updateItem ( treeItem , testInfo ) ; if ( fTestRunnerPart . isAutoScroll ( ) ) { fTree . showItem ( treeItem ) ; cacheItems ( treeItem ) ; collapsePassedTests ( treeItem ) ; } } private void cacheItems ( TreeItem treeItem ) { TreeItem parent = treeItem . getParentItem ( ) ; if ( parent == fCachedParent ) return ; fCachedItems = parent . getItems ( ) ; fCachedParent = parent ; } private void collapsePassedTests ( TreeItem treeItem ) { TreeItem parent = treeItem . getParentItem ( ) ; if ( parent != null ) { TreeItem [ ] items = null ; if ( parent == fCachedParent ) items = fCachedItems ; else items = parent . getItems ( ) ; if ( isLast ( treeItem , items ) ) { boolean ok = true ; for ( int i = ; i < items . length ; i ++ ) { if ( isFailure ( items [ i ] ) ) { ok = false ; break ; } } if ( ok ) { parent . setExpanded ( false ) ; collapsePassedTests ( parent ) ; } } } } private boolean isLast ( TreeItem treeItem , TreeItem [ ] items ) { return items [ items . length - ] == treeItem ; } private void updateItem ( TreeItem treeItem , TestRunInfo testInfo ) { treeItem . setData ( testInfo ) ; if ( testInfo . getStatus ( ) == ITestRunListener . STATUS_OK ) { treeItem . setImage ( fOkIcon ) ; return ; } if ( testInfo . getStatus ( ) == ITestRunListener . STATUS_FAILURE ) treeItem . setImage ( fFailureIcon ) ; else if ( testInfo . getStatus ( ) == ITestRunListener . STATUS_ERROR ) treeItem . setImage ( fErrorIcon ) ; propagateStatus ( treeItem , testInfo . getStatus ( ) ) ; } private void propagateStatus ( TreeItem item , int status ) { TreeItem parent = item . getParentItem ( ) ; TestRunInfo testRunInfo = getTestRunInfo ( item ) ; if ( parent == null ) return ; TestRunInfo parentInfo = getTestRunInfo ( parent ) ; int parentStatus = parentInfo . getStatus ( ) ; if ( status == ITestRunListener . STATUS_FAILURE ) { if ( parentStatus == ITestRunListener . STATUS_ERROR || parentStatus == ITestRunListener . STATUS_FAILURE ) return ; parentInfo . setStatus ( ITestRunListener . STATUS_FAILURE ) ; testRunInfo . setStatus ( ITestRunListener . STATUS_FAILURE ) ; } else { if ( parentStatus == ITestRunListener . STATUS_ERROR ) return ; parentInfo . setStatus ( ITestRunListener . STATUS_ERROR ) ; testRunInfo . setStatus ( ITestRunListener . STATUS_ERROR ) ; } propagateStatus ( parent , status ) ; } private TestRunInfo getTestRunInfo ( TreeItem item ) { return ( TestRunInfo ) item . getData ( ) ; } public void activate ( ) { fMoveSelection = false ; testSelected ( ) ; } public void setFocus ( ) { fTree . setFocus ( ) ; } public void aboutToStart ( ) { fTree . removeAll ( ) ; fSuiteInfos . removeAllElements ( ) ; fTreeItemMap = new HashMap < String , TreeItem > ( ) ; fCachedParent = null ; fCachedItems = null ; fMoveSelection = false ; fExecutionPath = new ArrayList < TreeItem > ( ) ; } private void testSelected ( ) { fTestRunnerPart . handleTestSelected ( getSelectedTestId ( ) ) ; } private void addListeners ( ) { fTree . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { activate ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { activate ( ) ; } } ) ; fTree . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { disposeIcons ( ) ; } } ) ; fTree . addMouseListener ( new MouseAdapter ( ) { public void mouseDoubleClick ( MouseEvent e ) { handleDoubleClick ( e ) ; } } ) ; } void handleDoubleClick ( MouseEvent e ) { TestRunInfo testInfo = getTestInfo ( ) ; if ( testInfo == null ) return ; IAction action = null ; if ( isSuiteSelected ( ) ) action = new OpenTestAction ( fTestRunnerPart , getClassName ( ) ) ; else action = new OpenTestAction ( fTestRunnerPart , getClassName ( ) , getTestMethod ( ) ) ; if ( action != null && action . isEnabled ( ) ) action . run ( ) ; } public void menuAboutToShow ( IMenuManager manager ) { if ( fTree . getSelectionCount ( ) > ) { if ( isSuiteSelected ( ) ) { manager . add ( new OpenTestAction ( fTestRunnerPart , getClassName ( ) ) ) ; manager . add ( new Separator ( ) ) ; if ( testClassExists ( getClassName ( ) ) && ! fTestRunnerPart . lastLaunchIsKeptAlive ( ) ) { manager . add ( new RerunAction ( fTestRunnerPart , getSelectedTestId ( ) , getClassName ( ) , null , ILaunchManager . RUN_MODE ) ) ; manager . add ( new RerunAction ( fTestRunnerPart , getSelectedTestId ( ) , getClassName ( ) , null , ILaunchManager . DEBUG_MODE ) ) ; } } else { manager . add ( new OpenTestAction ( fTestRunnerPart , getClassName ( ) , getTestMethod ( ) , true ) ) ; manager . add ( new Separator ( ) ) ; manager . add ( new RerunAction ( fTestRunnerPart , getSelectedTestId ( ) , getClassName ( ) , getTestMethod ( ) , ILaunchManager . RUN_MODE ) ) ; manager . add ( new RerunAction ( fTestRunnerPart , getSelectedTestId ( ) , getClassName ( ) , getTestMethod ( ) , ILaunchManager . DEBUG_MODE ) ) ; } manager . add ( new Separator ( ) ) ; manager . add ( new ExpandAllAction ( ) ) ; } } private boolean testClassExists ( String className ) { IStatus status = RubyConventions . validateRubyTypeName ( className ) ; return status . isOK ( ) ; } public void newTreeEntry ( String treeEntry ) { String [ ] parts = treeEntry . split ( "" ) ; String testId = parts [ ] ; String testName = parts [ ] ; Boolean isSuite = false ; int testCount = ; try { isSuite = Boolean . parseBoolean ( parts [ ] ) ; testCount = Integer . parseInt ( parts [ ] ) ; } catch ( NumberFormatException e ) { TestunitPlugin . log ( "" + treeEntry ) ; TestunitPlugin . log ( e ) ; } TestRunInfo testInfo = new TestRunInfo ( testId , testName ) ; TreeItem treeItem ; while ( ( fSuiteInfos . size ( ) > ) && ( ( fSuiteInfos . lastElement ( ) ) . fTestCount == ) ) { fSuiteInfos . removeElementAt ( fSuiteInfos . size ( ) - ) ; } if ( fSuiteInfos . size ( ) == ) { treeItem = new TreeItem ( fTree , SWT . NONE ) ; treeItem . setImage ( fSuiteIcon ) ; fSuiteInfos . addElement ( new SuiteInfo ( treeItem , testCount ) ) ; } else if ( isSuite ) { treeItem = new TreeItem ( ( fSuiteInfos . lastElement ( ) ) . fTreeItem , SWT . NONE ) ; treeItem . setImage ( fSuiteIcon ) ; ( fSuiteInfos . lastElement ( ) ) . fTestCount -= ; fSuiteInfos . addElement ( new SuiteInfo ( treeItem , testCount ) ) ; } else { treeItem = new TreeItem ( ( fSuiteInfos . lastElement ( ) ) . fTreeItem , SWT . NONE ) ; treeItem . setImage ( fTestIcon ) ; ( fSuiteInfos . lastElement ( ) ) . fTestCount -= ; mapTest ( testInfo , treeItem ) ; } treeItem . setText ( testInfo . getTestMethodName ( ) ) ; treeItem . setData ( testInfo ) ; } private void mapTest ( TestRunInfo info , TreeItem item ) { fTreeItemMap . put ( info . getTestId ( ) , item ) ; } private TreeItem findTreeItem ( String testId ) { Object o = fTreeItemMap . get ( testId ) ; if ( o instanceof TreeItem ) return ( TreeItem ) o ; return null ; } public void testStatusChanged ( TestRunInfo newInfo ) { Object o = fTreeItemMap . get ( newInfo . getTestId ( ) ) ; if ( o instanceof TreeItem ) { updateItem ( ( TreeItem ) o , newInfo ) ; return ; } } public void selectNext ( ) { TreeItem selection = getInitialSearchSelection ( ) ; if ( ! moveSelection ( selection ) ) return ; TreeItem failure = findFailure ( selection , true , ! isLeafFailure ( selection ) ) ; if ( failure != null ) selectTest ( failure ) ; } public void selectPrevious ( ) { TreeItem selection = getInitialSearchSelection ( ) ; if ( ! moveSelection ( selection ) ) return ; TreeItem failure = findFailure ( selection , false , ! isLeafFailure ( selection ) ) ; if ( failure != null ) selectTest ( failure ) ; } private boolean moveSelection ( TreeItem selection ) { if ( ! fMoveSelection ) { fMoveSelection = true ; if ( isLeafFailure ( selection ) ) { selectTest ( selection ) ; return false ; } } return true ; } private TreeItem getInitialSearchSelection ( ) { TreeItem [ ] treeItems = fTree . getSelection ( ) ; TreeItem selection = null ; if ( treeItems . length == ) selection = fTree . getItems ( ) [ ] ; else selection = treeItems [ ] ; return selection ; } private boolean isFailure ( TreeItem selection ) { return ! ( getTestRunInfo ( selection ) . getStatus ( ) == ITestRunListener . STATUS_OK ) ; } private boolean isLeafFailure ( TreeItem selection ) { boolean isLeaf = selection . getItemCount ( ) == ; return isLeaf && isFailure ( selection ) ; } private void selectTest ( TreeItem selection ) { fTestRunnerPart . showTest ( getTestRunInfo ( selection ) ) ; } private TreeItem findFailure ( TreeItem start , boolean next , boolean includeNode ) { TreeItem [ ] sib = findSiblings ( start , next , includeNode ) ; if ( next ) { for ( int i = ; i < sib . length ; i ++ ) { TreeItem failure = findFailureInTree ( sib [ i ] ) ; if ( failure != null ) return failure ; } } else { for ( int i = sib . length - ; i >= ; i -- ) { TreeItem failure = findFailureInTree ( sib [ i ] ) ; if ( failure != null ) return failure ; } } TreeItem parent = start . getParentItem ( ) ; if ( parent == null ) return null ; return findFailure ( parent , next , false ) ; } private TreeItem [ ] findSiblings ( TreeItem item , boolean next , boolean includeNode ) { TreeItem parent = item . getParentItem ( ) ; TreeItem [ ] children = null ; if ( parent == null ) children = item . getParent ( ) . getItems ( ) ; else children = parent . getItems ( ) ; for ( int i = ; i < children . length ; i ++ ) { TreeItem item2 = children [ i ] ; if ( item2 == item ) { TreeItem [ ] result = null ; if ( next ) { if ( ! includeNode ) { result = new TreeItem [ children . length - i - ] ; System . arraycopy ( children , i + , result , , children . length - i - ) ; } else { result = new TreeItem [ children . length - i ] ; System . arraycopy ( children , i , result , , children . length - i ) ; } } else { if ( ! includeNode ) { result = new TreeItem [ i ] ; System . arraycopy ( children , , result , , i ) ; } else { result = new TreeItem [ i + ] ; System . arraycopy ( children , , result , , i + ) ; } } return result ; } } return new TreeItem [ ] ; } private TreeItem findFailureInTree ( TreeItem item ) { if ( item . getItemCount ( ) == ) { if ( isFailure ( item ) ) return item ; } TreeItem [ ] children = item . getItems ( ) ; for ( int i = ; i < children . length ; i ++ ) { TreeItem item2 = findFailureInTree ( children [ i ] ) ; if ( item2 != null ) return item2 ; } return null ; } protected void expandAll ( ) { TreeItem [ ] treeItems = fTree . getSelection ( ) ; fTree . setRedraw ( false ) ; for ( int i = ; i < treeItems . length ; i ++ ) { expandAll ( treeItems [ i ] ) ; } fTree . setRedraw ( true ) ; } private void expandAll ( TreeItem item ) { item . setExpanded ( true ) ; TreeItem [ ] items = item . getItems ( ) ; for ( int i = ; i < items . length ; i ++ ) { expandAll ( items [ i ] ) ; } } public void aboutToEnd ( ) { for ( int i = ; i < fExecutionPath . size ( ) ; i ++ ) { refreshItem ( fExecutionPath . get ( i ) , false ) ; } } } package org . rubypeople . rdt . internal . testunit . ui ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . StringTokenizer ; public class TestUnitPreferencesConstants { public final static String DO_FILTER_STACK = TestunitPlugin . PLUGIN_ID + "" ; public final static String SHOW_ON_ERROR_ONLY = TestunitPlugin . PLUGIN_ID + "" ; public static final String PREF_ACTIVE_FILTERS_LIST = TestunitPlugin . PLUGIN_ID + "" ; public static final String PREF_INACTIVE_FILTERS_LIST = TestunitPlugin . PLUGIN_ID + "" ; private static String [ ] fgDefaultFilterPatterns = new String [ ] { "" , "" , "" , } ; private TestUnitPreferencesConstants ( ) { } public static List < String > createDefaultStackFiltersList ( ) { return Arrays . asList ( fgDefaultFilterPatterns ) ; } public static String serializeList ( String [ ] list ) { if ( list == null ) return "" ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < list . length ; i ++ ) { if ( i > ) buffer . append ( '' ) ; buffer . append ( list [ i ] ) ; } return buffer . toString ( ) ; } public static String [ ] parseList ( String listString ) { List < String > list = new ArrayList < String > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( listString , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) list . add ( tokenizer . nextToken ( ) ) ; return list . toArray ( new String [ list . size ( ) ] ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . jface . action . Action ; public class RerunAction extends Action { private String fTestId ; private String fClassName ; private String fTestName ; private TestUnitView fTestRunner ; private String fLaunchMode ; public RerunAction ( TestUnitView runner , String testId , String className , String testName , String launchMode ) { super ( ) ; if ( launchMode . equals ( ILaunchManager . RUN_MODE ) ) setText ( TestUnitMessages . RerunAction_label_run ) ; else if ( launchMode . equals ( ILaunchManager . DEBUG_MODE ) ) setText ( TestUnitMessages . RerunAction_label_debug ) ; fTestRunner = runner ; fTestId = testId ; fClassName = className ; fTestName = testName ; fLaunchMode = launchMode ; } public void run ( ) { fTestRunner . rerunTest ( fTestId , fClassName , fTestName , fLaunchMode ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import org . eclipse . jface . action . Action ; public class EnableStackFilterAction extends Action { private FailureTrace fView ; public EnableStackFilterAction ( FailureTrace view ) { super ( TestUnitMessages . EnableStackFilterAction_action_label ) ; setDescription ( TestUnitMessages . EnableStackFilterAction_action_description ) ; setToolTipText ( TestUnitMessages . EnableStackFilterAction_action_tooltip ) ; setDisabledImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setHoverImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; setImageDescriptor ( TestunitPlugin . getImageDescriptor ( "" ) ) ; fView = view ; setChecked ( TestUnitPreferencePage . getFilterStack ( ) ) ; } public void run ( ) { TestUnitPreferencePage . setFilterStack ( isChecked ( ) ) ; fView . refresh ( ) ; } } package org . rubypeople . rdt . internal . testunit . ui ; import java . net . MalformedURLException ; import java . net . URL ; import java . util . AbstractSet ; import java . util . HashSet ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; import java . util . Set ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchListener ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . testunit . ITestRunListener ; import org . rubypeople . rdt . testunit . launcher . TestUnitLaunchConfigurationDelegate ; public class TestunitPlugin extends AbstractUIPlugin implements ILaunchListener { public static final String PLUGIN_ID = "" ; public static final String TESTUNIT_PORT_ATTR = "" ; private static TestunitPlugin plugin ; private ResourceBundle resourceBundle ; private AbstractSet < ILaunch > fTrackedLaunches = new HashSet < ILaunch > ( ) ; private Set < ITestRunListener > fTestRunListeners = new HashSet < ITestRunListener > ( ) ; private static URL fgIconBaseURL ; public TestunitPlugin ( ) { super ( ) ; String pathSuffix = "" ; try { fgIconBaseURL = new URL ( Platform . getBundle ( PLUGIN_ID ) . getEntry ( "" ) , pathSuffix ) ; } catch ( MalformedURLException e ) { } try { resourceBundle = ResourceBundle . getBundle ( "" ) ; } catch ( MissingResourceException x ) { resourceBundle = null ; } } public static URL makeIconFileURL ( String name ) throws MalformedURLException { if ( TestunitPlugin . fgIconBaseURL == null ) throw new MalformedURLException ( ) ; return new URL ( TestunitPlugin . fgIconBaseURL , name ) ; } public static ImageDescriptor getImageDescriptor ( String relativePath ) { try { return ImageDescriptor . createFromURL ( makeIconFileURL ( relativePath ) ) ; } catch ( MalformedURLException e ) { return ImageDescriptor . getMissingImageDescriptor ( ) ; } } public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; ILaunchManager launchManager = DebugPlugin . getDefault ( ) . getLaunchManager ( ) ; launchManager . addLaunchListener ( this ) ; } public void stop ( BundleContext context ) throws Exception { super . stop ( context ) ; } public static TestunitPlugin getDefault ( ) { return plugin ; } public static String getResourceString ( String key ) { ResourceBundle bundle = TestunitPlugin . getDefault ( ) . getResourceBundle ( ) ; try { return ( bundle != null ) ? bundle . getString ( key ) : key ; } catch ( MissingResourceException e ) { return key ; } } public ResourceBundle getResourceBundle ( ) { return resourceBundle ; } public static String getPluginId ( ) { return PLUGIN_ID ; } public static void log ( Throwable e ) { log ( new Status ( IStatus . ERROR , getPluginId ( ) , IStatus . ERROR , "" , e ) ) ; } public static void log ( IStatus status ) { getDefault ( ) . getLog ( ) . log ( status ) ; } public static Shell getActiveWorkbenchShell ( ) { IWorkbenchWindow workBenchWindow = getActiveWorkbenchWindow ( ) ; if ( workBenchWindow == null ) return null ; return workBenchWindow . getShell ( ) ; } public static IWorkbenchWindow getActiveWorkbenchWindow ( ) { if ( plugin == null ) return null ; IWorkbench workBench = plugin . getWorkbench ( ) ; if ( workBench == null ) return null ; return workBench . getActiveWorkbenchWindow ( ) ; } public static IWorkspace getWorkspace ( ) { return RubyCore . getWorkspace ( ) ; } public static Display getDisplay ( ) { Display display = Display . getCurrent ( ) ; if ( display == null ) { display = Display . getDefault ( ) ; } return display ; } public static IWorkbenchPage getActivePage ( ) { IWorkbenchWindow activeWorkbenchWindow = getActiveWorkbenchWindow ( ) ; if ( activeWorkbenchWindow == null ) return null ; return activeWorkbenchWindow . getActivePage ( ) ; } public void connectTestRunner ( ILaunch launch , IType finalType , int port ) { TestUnitView testRunnerViewPart = showTestUnitViewInActivePage ( findTestUnitViewInActivePage ( ) ) ; if ( testRunnerViewPart != null ) testRunnerViewPart . startTestRunListening ( port , finalType , launch , fTestRunListeners ) ; } public void addTestRunListener ( ITestRunListener listener ) { fTestRunListeners . add ( listener ) ; } public void removeTestRunListener ( ITestRunListener listener ) { fTestRunListeners . remove ( listener ) ; } private TestUnitView showTestUnitViewInActivePage ( TestUnitView testRunner ) { IWorkbenchPart activePart = null ; IWorkbenchPage page = null ; try { if ( testRunner != null && testRunner . isCreated ( ) ) return testRunner ; page = getActivePage ( ) ; if ( page == null ) return null ; activePart = page . getActivePart ( ) ; return ( TestUnitView ) page . showView ( TestUnitView . NAME ) ; } catch ( PartInitException pie ) { log ( pie ) ; return null ; } finally { if ( page != null && activePart != null ) page . activate ( activePart ) ; } } public TestUnitView findTestUnitViewInActivePage ( ) { IWorkbenchPage page = getActivePage ( ) ; if ( page == null ) return null ; return ( TestUnitView ) page . findView ( TestUnitView . NAME ) ; } public static void log ( String string ) { log ( new Throwable ( string ) ) ; } public void launchRemoved ( final ILaunch launch ) { if ( ! fTrackedLaunches . remove ( launch ) ) return ; getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { TestUnitView testRunnerViewPart = findTestRunnerViewPartInActivePage ( ) ; if ( testRunnerViewPart != null && testRunnerViewPart . isCreated ( ) && launch . equals ( testRunnerViewPart . getLastLaunch ( ) ) ) testRunnerViewPart . reset ( ) ; } } ) ; } private TestUnitView findTestRunnerViewPartInActivePage ( ) { IWorkbenchPage page = getActivePage ( ) ; if ( page == null ) return null ; return ( TestUnitView ) page . findView ( TestUnitView . NAME ) ; } public void launchChanged ( final ILaunch launch ) { if ( ! fTrackedLaunches . contains ( launch ) ) return ; ILaunchConfiguration config = launch . getLaunchConfiguration ( ) ; IType launchedType = null ; if ( config != null ) { String typeStr = launch . getAttribute ( TestUnitLaunchConfigurationDelegate . TESTTYPE_ATTR ) ; if ( typeStr != null && typeStr . trim ( ) . length ( ) > ) { IRubyElement element = RubyCore . create ( typeStr ) ; if ( element instanceof IType ) launchedType = ( IType ) element ; } } fTrackedLaunches . remove ( launch ) ; final IType finalType = launchedType ; final int finalPort = Integer . parseInt ( launch . getAttribute ( TESTUNIT_PORT_ATTR ) ) ; getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { connectTestRunner ( launch , finalType , finalPort ) ; } } ) ; } public void launchAdded ( ILaunch launch ) { try { if ( launch == null || launch . getLaunchConfiguration ( ) == null || launch . getLaunchConfiguration ( ) . getType ( ) == null ) return ; if ( launch . getLaunchConfiguration ( ) . getType ( ) . getDelegate ( launch . getLaunchMode ( ) ) . getClass ( ) != TestUnitLaunchConfigurationDelegate . class ) { return ; } fTrackedLaunches . add ( launch ) ; } catch ( Exception ex ) { log ( ex ) ; } } } package org . rubypeople . rdt . internal . testunit . ui ; public interface ITestRunListener3 extends ITestRunListener2 { public void testFailed ( int status , String testId , String testName , String trace , String expected , String actual ) ; public void testReran ( String testId , String className , String testName , int statusCode , String trace , String expectedResult , String actualResult ) ; } package org . rubypeople . rdt . internal . testunit . ui ; import org . rubypeople . rdt . testunit . ITestRunListener ; public interface ITestRunListener2 extends ITestRunListener { public void testTreeEntry ( String description ) ; } package org . rubypeople . rdt . internal . testunit . wizards ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . wizards . NewElementWizard ; import org . rubypeople . rdt . testunit . wizards . RubyNewTestCaseWizardPage ; import org . rubypeople . rdt . testunit . wizards . RubyNewTestCaseWizardPageTwo ; public class NewTestCaseCreationWizard extends NewElementWizard { private RubyNewTestCaseWizardPage fPage1 ; private RubyNewTestCaseWizardPageTwo fPage2 ; public NewTestCaseCreationWizard ( ) { setDefaultPageImageDescriptor ( RubyPluginImages . DESC_WIZBAN_NEWCLASS ) ; setDialogSettings ( RubyPlugin . getDefault ( ) . getDialogSettings ( ) ) ; setWindowTitle ( WizardMessages . Wizard_title_new_testcase ) ; } public void addPages ( ) { super . addPages ( ) ; fPage2 = new RubyNewTestCaseWizardPageTwo ( ) ; fPage1 = new RubyNewTestCaseWizardPage ( fPage2 ) ; addPage ( fPage1 ) ; fPage1 . init ( getSelection ( ) ) ; addPage ( fPage2 ) ; } protected void finishPage ( IProgressMonitor monitor ) throws InterruptedException , CoreException { fPage1 . createType ( monitor ) ; } public boolean performFinish ( ) { boolean res = super . performFinish ( ) ; if ( res ) { IResource resource = fPage1 . getModifiedResource ( ) ; if ( resource != null ) { selectAndReveal ( resource ) ; openResource ( ( IFile ) resource ) ; } } return res ; } public IRubyElement getCreatedElement ( ) { return fPage1 . getCreatedType ( ) ; } } package org . rubypeople . rdt . internal . testunit . wizards ; import org . eclipse . osgi . util . NLS ; public class WizardMessages extends NLS { private static final String BUNDLE_NAME = "" ; public static String NewTestCaseWizardPage_title ; public static String NewTestCaseWizardPage_description ; public static String Wizard_title_new_testcase ; public static String NewTestCaseWizardPage_method_Stub_label ; public static String NewTestCaseWizardPage_methodStub_setUp ; public static String NewTestCaseWizardPage_methodStub_tearDown ; public static String NewTestCaseWizardPage_methodStub_constructor ; public static String NewTestCaseWizardPage_class_to_test_label ; public static String NewTestCaseWizardPage_class_to_test_browse ; public static String NewTestCaseWizardPage_class_to_test_dialog_title ; public static String NewTestCaseWizardPage_class_to_test_dialog_message ; public static String NewTestCaseWizardPage_error_class_to_test_not_valid ; public static String NewTestCaseWizardPage_error_class_to_test_not_exist ; public static String NewTestCaseWizardPage_warning_class_to_test_is_interface ; public static String NewTestCaseWizardPageTwo_title ; public static String NewTestCaseWizardPageTwo_description ; public static String NewTestCaseWizardPageTwo_create_final_method_stubs_text ; public static String NewTestCaseWizardPageTwo_create_tasks_text ; public static String NewTestCaseWizardPageTwo_methods_tree_label ; public static String NewTestCaseWizardPageTwo_selectAll ; public static String NewTestCaseWizardPageTwo_deselectAll ; public static String NewTestCaseWizardPageTwo_selected_methods_label_one ; public static String NewTestCaseWizardPageTwo_selected_methods_label_many ; public static String NewTestCaseWizardPageOne_not_yet_implemented_string ; private WizardMessages ( ) { } static { NLS . initializeMessages ( BUNDLE_NAME , WizardMessages . class ) ; } } package org . rubypeople . rdt . internal . testunit . wizards ; import org . eclipse . core . runtime . Assert ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . testunit . util . LayoutUtil ; public class MethodStubsSelectionButtonGroup { private Label fLabel ; protected String fLabelText ; private SelectionButtonGroupListener fGroupListener ; private boolean fEnabled ; private Composite fButtonComposite ; private Button [ ] fButtons ; private String [ ] fButtonNames ; private boolean [ ] fButtonsSelected ; private boolean [ ] fButtonsEnabled ; private int fGroupBorderStyle ; private int fGroupNumberOfColumns ; private int fButtonsStyle ; public interface SelectionButtonGroupListener { void groupChanged ( MethodStubsSelectionButtonGroup field ) ; } public MethodStubsSelectionButtonGroup ( int buttonsStyle , String [ ] buttonNames , int nColumns ) { this ( buttonsStyle , buttonNames , nColumns , SWT . NONE ) ; } public MethodStubsSelectionButtonGroup ( int buttonsStyle , String [ ] buttonNames , int nColumns , int borderStyle ) { fEnabled = true ; fLabel = null ; fLabelText = "" ; Assert . isTrue ( buttonsStyle == SWT . RADIO || buttonsStyle == SWT . CHECK || buttonsStyle == SWT . TOGGLE ) ; fButtonNames = buttonNames ; int nButtons = buttonNames . length ; fButtonsSelected = new boolean [ nButtons ] ; fButtonsEnabled = new boolean [ nButtons ] ; for ( int i = ; i < nButtons ; i ++ ) { fButtonsSelected [ i ] = false ; fButtonsEnabled [ i ] = true ; } if ( buttonsStyle == SWT . RADIO ) { fButtonsSelected [ ] = true ; } fGroupBorderStyle = borderStyle ; fGroupNumberOfColumns = ( nColumns <= ) ? nButtons : nColumns ; fButtonsStyle = buttonsStyle ; } public Control [ ] doFillIntoGrid ( Composite parent , int nColumns ) { assertEnoughColumns ( nColumns ) ; if ( fGroupBorderStyle == SWT . NONE ) { Label label = getLabelControl ( parent ) ; label . setLayoutData ( gridDataForLabel ( ) ) ; Composite buttonsgroup = getSelectionButtonsGroup ( parent ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = nColumns - ; buttonsgroup . setLayoutData ( gd ) ; return new Control [ ] { label , buttonsgroup } ; } Composite buttonsgroup = getSelectionButtonsGroup ( parent ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = nColumns ; buttonsgroup . setLayoutData ( gd ) ; return new Control [ ] { buttonsgroup } ; } public int getNumberOfControls ( ) { return ( fGroupBorderStyle == SWT . NONE ) ? : ; } private Button createSelectionButton ( int index , Composite group , SelectionListener listener ) { Button button = new Button ( group , fButtonsStyle | SWT . LEFT ) ; button . setFont ( group . getFont ( ) ) ; button . setText ( fButtonNames [ index ] ) ; button . setEnabled ( isEnabled ( ) && isEnabled ( index ) ) ; button . setSelection ( isSelected ( index ) ) ; button . addSelectionListener ( listener ) ; return button ; } public Composite getSelectionButtonsGroup ( Composite parent ) { if ( fButtonComposite == null ) { assertCompositeNotNull ( parent ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = fGroupNumberOfColumns ; if ( fGroupBorderStyle != SWT . NONE ) { Group group = new Group ( parent , fGroupBorderStyle ) ; if ( fLabelText != null && fLabelText . length ( ) > ) { group . setText ( fLabelText ) ; } fButtonComposite = group ; } else { fButtonComposite = new Composite ( parent , SWT . NULL ) ; layout . marginHeight = ; layout . marginWidth = ; } fButtonComposite . setLayout ( layout ) ; SelectionListener listener = new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { doWidgetSelected ( e ) ; } public void widgetSelected ( SelectionEvent e ) { doWidgetSelected ( e ) ; } } ; int nButtons = fButtonNames . length ; fButtons = new Button [ nButtons ] ; for ( int i = ; i < nButtons ; i ++ ) { fButtons [ i ] = createSelectionButton ( i , fButtonComposite , listener ) ; } int nRows = nButtons / fGroupNumberOfColumns ; int nFillElements = nRows * fGroupNumberOfColumns - nButtons ; for ( int i = ; i < nFillElements ; i ++ ) { createEmptySpace ( fButtonComposite ) ; } setSelectionGroupListener ( new SelectionButtonGroupListener ( ) { public void groupChanged ( MethodStubsSelectionButtonGroup field ) { field . setEnabled ( , isEnabled ( ) && field . isSelected ( ) ) ; } } ) ; } return fButtonComposite ; } public Button getSelectionButton ( int index ) { if ( index >= && index < fButtons . length ) { return fButtons [ index ] ; } return null ; } private void doWidgetSelected ( SelectionEvent e ) { Button button = ( Button ) e . widget ; for ( int i = ; i < fButtons . length ; i ++ ) { if ( fButtons [ i ] == button ) { fButtonsSelected [ i ] = button . getSelection ( ) ; dialogFieldChanged ( ) ; return ; } } } public boolean isSelected ( int index ) { if ( index >= && index < fButtonsSelected . length ) { return fButtonsSelected [ index ] && fButtonsEnabled [ index ] ; } return false ; } public void setSelection ( int index , boolean selected ) { if ( index >= && index < fButtonsSelected . length ) { if ( fButtonsSelected [ index ] != selected ) { fButtonsSelected [ index ] = selected ; if ( fButtons != null ) { Button button = fButtons [ index ] ; if ( isOkToUse ( button ) && button . isEnabled ( ) ) { button . setSelection ( selected ) ; } } } } } public boolean isEnabled ( int index ) { if ( index >= && index < fButtonsEnabled . length ) { return fButtonsEnabled [ index ] ; } return false ; } public void setEnabled ( int index , boolean enabled ) { if ( index >= && index < fButtonsEnabled . length ) { if ( fButtonsEnabled [ index ] != enabled ) { fButtonsEnabled [ index ] = enabled ; if ( fButtons != null ) { Button button = fButtons [ index ] ; if ( isOkToUse ( button ) ) { button . setEnabled ( enabled ) ; if ( ! enabled ) { button . setSelection ( false ) ; } else { button . setSelection ( fButtonsSelected [ index ] ) ; } } } } } } protected void updateEnableState ( ) { if ( fLabel != null ) { fLabel . setEnabled ( fEnabled ) ; } if ( fButtons != null ) { boolean enabled = isEnabled ( ) ; for ( int i = ; i < fButtons . length ; i ++ ) { Button button = fButtons [ i ] ; if ( isOkToUse ( button ) ) { button . setEnabled ( enabled && fButtonsEnabled [ i ] ) ; } } } } public void setLabelText ( String labeltext ) { fLabelText = labeltext ; } public final void setSelectionGroupListener ( SelectionButtonGroupListener listener ) { fGroupListener = listener ; } public void dialogFieldChanged ( ) { if ( fGroupListener != null ) { fGroupListener . groupChanged ( this ) ; } } public boolean setFocus ( ) { return false ; } public void postSetFocusOnDialogField ( Display display ) { if ( display != null ) { display . asyncExec ( new Runnable ( ) { public void run ( ) { setFocus ( ) ; } } ) ; } } protected static GridData gridDataForLabel ( int span ) { GridData gd = new GridData ( ) ; gd . horizontalSpan = span ; return gd ; } public Label getLabelControl ( Composite parent ) { if ( fLabel == null ) { assertCompositeNotNull ( parent ) ; fLabel = new Label ( parent , SWT . LEFT | SWT . WRAP ) ; fLabel . setFont ( parent . getFont ( ) ) ; fLabel . setEnabled ( fEnabled ) ; if ( fLabelText != null && ! "" . equals ( fLabelText ) ) { fLabel . setText ( fLabelText ) ; } else { fLabel . setText ( "" ) ; fLabel . setVisible ( false ) ; } } return fLabel ; } public static Control createEmptySpace ( Composite parent ) { return createEmptySpace ( parent , ) ; } public static Control createEmptySpace ( Composite parent , int span ) { return LayoutUtil . createEmptySpace ( parent , span ) ; } protected final boolean isOkToUse ( Control control ) { return ( control != null ) && ! ( control . isDisposed ( ) ) ; } public final void setEnabled ( boolean enabled ) { if ( enabled != fEnabled ) { fEnabled = enabled ; updateEnableState ( ) ; } } public final boolean isEnabled ( ) { return fEnabled ; } protected final void assertCompositeNotNull ( Composite comp ) { Assert . isNotNull ( comp , "" ) ; } protected final void assertEnoughColumns ( int nColumns ) { Assert . isTrue ( nColumns >= getNumberOfControls ( ) , "" ) ; } } package org . rubypeople . rdt . internal . testunit . launcher ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . ui . AbstractLaunchConfigurationTabGroup ; import org . eclipse . debug . ui . CommonTab ; import org . eclipse . debug . ui . EnvironmentTab ; import org . eclipse . debug . ui . ILaunchConfigurationDialog ; import org . eclipse . debug . ui . ILaunchConfigurationTab ; import org . eclipse . debug . ui . ILaunchConfigurationTabGroup ; import org . rubypeople . rdt . internal . debug . ui . launcher . RubyEnvironmentTab ; import org . rubypeople . rdt . testunit . launcher . TestUnitMainTab ; public class TestUnitTabGroup extends AbstractLaunchConfigurationTabGroup { public void createTabs ( ILaunchConfigurationDialog dialog , String mode ) { ILaunchConfigurationTab [ ] tabs = new ILaunchConfigurationTab [ ] { new TestUnitMainTab ( ) , new RubyEnvironmentTab ( ) , new EnvironmentTab ( ) , new CommonTab ( ) } ; setTabs ( tabs ) ; } public void setDefaults ( ILaunchConfigurationWorkingCopy config ) { super . setDefaults ( config ) ; } } package org . rubypeople . rdt . internal . testunit . util ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . IStatus ; import org . rubypeople . rdt . internal . testunit . ui . TestunitPlugin ; public class TestUnitStatus implements IStatus { private String fStatusMessage ; private int fSeverity ; public TestUnitStatus ( ) { this ( OK , null ) ; } public TestUnitStatus ( int severity , String message ) { fStatusMessage = message ; fSeverity = severity ; } public static IStatus createError ( String message ) { return new TestUnitStatus ( IStatus . ERROR , message ) ; } public static IStatus createWarning ( String message ) { return new TestUnitStatus ( IStatus . WARNING , message ) ; } public static IStatus createInfo ( String message ) { return new TestUnitStatus ( IStatus . INFO , message ) ; } public boolean isOK ( ) { return fSeverity == IStatus . OK ; } public boolean isWarning ( ) { return fSeverity == IStatus . WARNING ; } public boolean isInfo ( ) { return fSeverity == IStatus . INFO ; } public boolean isError ( ) { return fSeverity == IStatus . ERROR ; } public String getMessage ( ) { return fStatusMessage ; } public void setError ( String errorMessage ) { Assert . isNotNull ( errorMessage ) ; fStatusMessage = errorMessage ; fSeverity = IStatus . ERROR ; } public void setWarning ( String warningMessage ) { Assert . isNotNull ( warningMessage ) ; fStatusMessage = warningMessage ; fSeverity = IStatus . WARNING ; } public void setInfo ( String infoMessage ) { Assert . isNotNull ( infoMessage ) ; fStatusMessage = infoMessage ; fSeverity = IStatus . INFO ; } public void setOK ( ) { fStatusMessage = null ; fSeverity = IStatus . OK ; } public boolean matches ( int severityMask ) { return ( fSeverity & severityMask ) != ; } public boolean isMultiStatus ( ) { return false ; } public int getSeverity ( ) { return fSeverity ; } public String getPlugin ( ) { return TestunitPlugin . PLUGIN_ID ; } public Throwable getException ( ) { return null ; } public int getCode ( ) { return fSeverity ; } public IStatus [ ] getChildren ( ) { return new IStatus [ ] ; } } package org . rubypeople . rdt . internal . testunit . util ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . internal . testunit . wizards . MethodStubsSelectionButtonGroup ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; public class LayoutUtil { public static int getNumberOfColumns ( MethodStubsSelectionButtonGroup [ ] editors ) { int columnCount = ; for ( int i = ; i < editors . length ; i ++ ) { columnCount = Math . max ( editors [ i ] . getNumberOfControls ( ) , columnCount ) ; } return columnCount ; } public static void doDefaultLayout ( Composite parent , MethodStubsSelectionButtonGroup [ ] editors , boolean labelOnTop ) { doDefaultLayout ( parent , editors , labelOnTop , , , , ) ; } public static void doDefaultLayout ( Composite parent , MethodStubsSelectionButtonGroup [ ] editors , boolean labelOnTop , int minWidth , int minHeight ) { doDefaultLayout ( parent , editors , labelOnTop , minWidth , minHeight , , ) ; } public static void doDefaultLayout ( Composite parent , MethodStubsSelectionButtonGroup [ ] editors , boolean labelOnTop , int minWidth , int minHeight , int marginWidth , int marginHeight ) { int nCulumns = getNumberOfColumns ( editors ) ; Control [ ] [ ] controls = new Control [ editors . length ] [ ] ; for ( int i = ; i < editors . length ; i ++ ) { controls [ i ] = editors [ i ] . doFillIntoGrid ( parent , nCulumns ) ; } if ( labelOnTop ) { nCulumns -- ; modifyLabelSpans ( controls , nCulumns ) ; } GridLayout layout = new GridLayout ( ) ; if ( marginWidth != SWT . DEFAULT ) { layout . marginWidth = marginWidth ; } if ( marginHeight != SWT . DEFAULT ) { layout . marginHeight = marginHeight ; } layout . numColumns = nCulumns ; parent . setLayout ( layout ) ; } private static void modifyLabelSpans ( Control [ ] [ ] controls , int nCulumns ) { for ( int i = ; i < controls . length ; i ++ ) { setHorizontalSpan ( controls [ i ] [ ] , nCulumns ) ; } } public static void setHorizontalSpan ( Control control , int span ) { Object ld = control . getLayoutData ( ) ; if ( ld instanceof GridData ) { ( ( GridData ) ld ) . horizontalSpan = span ; } else if ( span != ) { GridData gd = new GridData ( ) ; gd . horizontalSpan = span ; control . setLayoutData ( gd ) ; } } public static void setWidthHint ( Control control , int widthHint ) { Object ld = control . getLayoutData ( ) ; if ( ld instanceof GridData ) { ( ( GridData ) ld ) . widthHint = widthHint ; } } public static void setHorizontalIndent ( Control control , int horizontalIndent ) { Object ld = control . getLayoutData ( ) ; if ( ld instanceof GridData ) { ( ( GridData ) ld ) . horizontalIndent = horizontalIndent ; } } public static Control createEmptySpace ( Composite parent , int span ) { Label label = new Label ( parent , SWT . LEFT ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . BEGINNING ; gd . grabExcessHorizontalSpace = false ; gd . horizontalSpan = span ; gd . horizontalIndent = ; gd . widthHint = ; gd . heightHint = ; label . setLayoutData ( gd ) ; return label ; } public static int getButtonWidthHint ( Button button ) { button . setFont ( JFaceResources . getDialogFont ( ) ) ; PixelConverter converter = new PixelConverter ( button ) ; int widthHint = converter . convertHorizontalDLUsToPixels ( IDialogConstants . BUTTON_WIDTH ) ; return Math . max ( widthHint , button . computeSize ( SWT . DEFAULT , SWT . DEFAULT , true ) . x ) ; } public static void setButtonDimensionHint ( Button button ) { Assert . isNotNull ( button ) ; Object gd = button . getLayoutData ( ) ; if ( gd instanceof GridData ) { ( ( GridData ) gd ) . widthHint = getButtonWidthHint ( button ) ; ( ( GridData ) gd ) . horizontalAlignment = GridData . FILL ; } } } package org . rubypeople . rdt . internal . testunit . runner ; public class MessageIds { public static final int MSG_HEADER_LENGTH = ; public static final String TRACE_START = "" ; public static final String TRACE_END = "" ; public static final String EXPECTED_START = "" ; public static final String EXPECTED_END = "" ; public static final String ACTUAL_START = "" ; public static final String ACTUAL_END = "" ; public static final String RTRACE_START = "" ; public static final String RTRACE_END = "" ; public static final String TEST_RUN_START = "" ; public static final String TEST_START = "" ; public static final String TEST_END = "" ; public static final String TEST_ERROR = "" ; public static final String TEST_FAILED = "" ; public static final String TEST_RUN_END = "" ; public static final String TEST_STOPPED = "" ; public static final String TEST_RERAN = "" ; public static final String TEST_TREE = "" ; public static final String TEST_STOP = "" ; public static final String TEST_RERUN = "" ; } package org . rubypeople . rdt . testunit . launcher ; import java . io . IOException ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . SocketUtil ; import org . rubypeople . rdt . internal . testunit . ui . TestUnitMessages ; import org . rubypeople . rdt . internal . testunit . ui . TestunitPlugin ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . RubyLaunchDelegate ; public class TestUnitLaunchConfigurationDelegate extends RubyLaunchDelegate { public static final String TESTTYPE_ATTR = TestunitPlugin . PLUGIN_ID + "" ; public static final String TESTNAME_ATTR = TestunitPlugin . PLUGIN_ID + "" ; public static final String LAUNCH_CONTAINER_ATTR = TestunitPlugin . PLUGIN_ID + "" ; public static final String ID_TESTUNIT_APPLICATION = "" ; private static final String TEST_RUNNER_FILE = "" ; private static final int TEST_RUNNER_VERSION = ; private int port = - ; @ Override public void launch ( ILaunchConfiguration configuration , String mode , ILaunch launch , IProgressMonitor monitor ) throws CoreException { IType [ ] testTypes = findTestTypes ( configuration , monitor ) ; getTestRunnerPath ( ) ; launch . setAttribute ( TestunitPlugin . TESTUNIT_PORT_ATTR , Integer . toString ( getPort ( ) ) ) ; if ( testTypes != null && testTypes . length > && testTypes [ ] != null ) launch . setAttribute ( TESTTYPE_ATTR , testTypes [ ] . getHandleIdentifier ( ) ) ; super . launch ( configuration , mode , launch , monitor ) ; } protected IType [ ] findTestTypes ( ILaunchConfiguration configuration , IProgressMonitor pm ) throws CoreException { IRubyProject javaProject = getRubyProject ( configuration ) ; if ( ( javaProject == null ) || ! javaProject . exists ( ) ) { informAndAbort ( TestUnitMessages . TestUnitBaseLaunchConfiguration_error_invalidproject , null , IRubyLaunchConfigurationConstants . ERR_NOT_A_RUBY_PROJECT ) ; } String containerHandle = configuration . getAttribute ( LAUNCH_CONTAINER_ATTR , "" ) ; if ( containerHandle . length ( ) > ) { IRubyElement element = RubyCore . create ( containerHandle ) ; if ( element != null ) { if ( element . isType ( IRubyElement . TYPE ) ) { return new IType [ ] { ( IType ) element } ; } IRubyScript script = ( IRubyScript ) element ; if ( script != null ) { IType type = script . findPrimaryType ( ) ; if ( type != null ) return new IType [ ] { type } ; } } } String testTypeName = configuration . getAttribute ( TESTTYPE_ATTR , ( String ) null ) ; if ( testTypeName != null && testTypeName . length ( ) > ) { return new IType [ ] { javaProject . findType ( testTypeName , pm ) } ; } return new IType [ ] ; } protected void informAndAbort ( String message , Throwable exception , int code ) throws CoreException { IStatus status = new Status ( IStatus . INFO , TestunitPlugin . PLUGIN_ID , code , message , exception ) ; if ( showStatusMessage ( status ) ) throw new CoreException ( status ) ; abort ( message , exception , code ) ; } private boolean showStatusMessage ( final IStatus status ) { final boolean [ ] success = new boolean [ ] { false } ; getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { Shell shell = TestunitPlugin . getActiveWorkbenchShell ( ) ; if ( shell == null ) shell = getDisplay ( ) . getActiveShell ( ) ; if ( shell != null ) { MessageDialog . openInformation ( shell , TestUnitMessages . JUnitBaseLaunchConfiguration_dialog_title , status . getMessage ( ) ) ; success [ ] = true ; } } } ) ; return success [ ] ; } private Display getDisplay ( ) { Display display ; display = Display . getCurrent ( ) ; if ( display == null ) display = Display . getDefault ( ) ; return display ; } public static String getTestRunnerPath ( ) { IPath stateLocation = TestunitPlugin . getDefault ( ) . getStateLocation ( ) ; IPath versionFile = stateLocation . append ( "" ) . append ( "" + TEST_RUNNER_VERSION ) ; boolean force = ! versionFile . toFile ( ) . exists ( ) ; RubyCore . copyToStateLocation ( TestunitPlugin . getDefault ( ) , new Path ( "" ) . append ( TEST_RUNNER_FILE ) , force ) ; RubyCore . copyToStateLocation ( TestunitPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) , force ) ; try { versionFile . toFile ( ) . createNewFile ( ) ; } catch ( IOException e ) { } IPath path = TestunitPlugin . getDefault ( ) . getStateLocation ( ) . append ( new Path ( "" ) . append ( TEST_RUNNER_FILE ) ) ; if ( ! path . toFile ( ) . exists ( ) ) throw new RuntimeException ( "" + TEST_RUNNER_FILE + "" + path ) ; return path . toPortableString ( ) ; } private int getPort ( ) { if ( port == - ) { port = SocketUtil . findFreePort ( ) ; } return port ; } @ Override public String getProgramArguments ( ILaunchConfiguration configuration ) throws CoreException { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( getLaunchContainerPath ( configuration ) ) ; buffer . append ( '' ) ; buffer . append ( Integer . toString ( getPort ( ) ) ) ; buffer . append ( '' ) ; buffer . append ( Boolean . toString ( false ) ) ; buffer . append ( '' ) ; buffer . append ( configuration . getAttribute ( TestUnitLaunchConfigurationDelegate . TESTTYPE_ATTR , "" ) ) ; buffer . append ( '' ) ; buffer . append ( configuration . getAttribute ( TestUnitLaunchConfigurationDelegate . TESTNAME_ATTR , "" ) ) ; return buffer . toString ( ) ; } private String getLaunchContainerPath ( ILaunchConfiguration configuration ) throws CoreException { String container = configuration . getAttribute ( TestUnitLaunchConfigurationDelegate . LAUNCH_CONTAINER_ATTR , "" ) ; IRubyElement element = ( IRubyElement ) RubyCore . create ( container ) ; if ( element != null ) container = element . getResource ( ) . getProjectRelativePath ( ) . toOSString ( ) ; if ( ! container . startsWith ( "" ) && container . indexOf ( '' ) != - ) { container = '' + container + '' ; } return container ; } } package org . rubypeople . rdt . testunit . launcher ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . ui . ILaunchConfigurationTab ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . launcher . RubyEntryPointTab ; import org . rubypeople . rdt . internal . testunit . ui . TestUnitMessages ; import org . rubypeople . rdt . internal . testunit . ui . TestunitPlugin ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class TestUnitMainTab extends RubyEntryPointTab implements ILaunchConfigurationTab { private RubyClassSelector classSelector ; private Label classLabel ; private Button allClassesCheckBox ; private Button allMethodsCheckBox ; private Label testLabel ; private Text testMethodEditBox ; public TestUnitMainTab ( ) { super ( ) ; } public void createControl ( Composite parent ) { super . createControl ( parent ) ; allClassesCheckBox = new Button ( composite , SWT . CHECK ) ; allClassesCheckBox . setText ( TestUnitMessages . LaunchConfigurationTab_RubyEntryPoint_allTestCases ) ; allClassesCheckBox . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { updateLaunchConfigurationDialog ( ) ; setControlState ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; classLabel = new Label ( composite , SWT . NONE ) ; classLabel . setText ( TestUnitMessages . LaunchConfigurationTab_RubyEntryPoint_classLabel ) ; classSelector = new RubyClassSelector ( composite , fileSelector , projectSelector ) ; classSelector . setBrowseDialogMessage ( TestUnitMessages . LaunchConfigurationTab_RubyEntryPoint_classSelectorMessage ) ; classSelector . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; classSelector . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent evt ) { updateLaunchConfigurationDialog ( ) ; } } ) ; allMethodsCheckBox = new Button ( composite , SWT . CHECK ) ; allMethodsCheckBox . setText ( TestUnitMessages . LaunchConfigurationTab_RubyEntryPoint_allTestMethods ) ; allMethodsCheckBox . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { updateLaunchConfigurationDialog ( ) ; setControlState ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; testLabel = new Label ( composite , SWT . NONE ) ; testLabel . setText ( TestUnitMessages . LaunchConfigurationTab_RubyEntryPoint_methodLabel ) ; testMethodEditBox = new Text ( composite , SWT . BORDER | SWT . BORDER ) ; testMethodEditBox . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; testMethodEditBox . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { updateLaunchConfigurationDialog ( ) ; } } ) ; setControlState ( ) ; } private void setControlState ( ) { boolean allClassesChecked = allClassesCheckBox . getSelection ( ) ; boolean allMethodsChecked = allMethodsCheckBox . getSelection ( ) ; classLabel . setEnabled ( ! allClassesChecked ) ; classSelector . setEnabled ( ! allClassesChecked ) ; allMethodsCheckBox . setEnabled ( ! allClassesChecked ) ; testLabel . setEnabled ( ! ( allClassesChecked || allMethodsChecked ) ) ; testMethodEditBox . setEnabled ( ! ( allClassesChecked || allMethodsChecked ) ) ; } public void setDefaults ( ILaunchConfigurationWorkingCopy configuration ) { super . setDefaults ( configuration ) ; configuration . setAttribute ( TestUnitLaunchConfigurationDelegate . TESTTYPE_ATTR , "" ) ; configuration . setAttribute ( TestUnitLaunchConfigurationDelegate . TESTNAME_ATTR , "" ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , TestUnitLaunchConfigurationDelegate . getTestRunnerPath ( ) ) ; configuration . setAttribute ( ILaunchConfiguration . ATTR_SOURCE_LOCATOR_ID , RdtDebugUiConstants . RUBY_SOURCE_LOCATOR ) ; } @ Override protected String handleFileName ( String filename ) { if ( filename == null || filename . trim ( ) . length ( ) == ) return "" ; IRubyElement element = RubyCore . create ( filename ) ; if ( element == null ) return "" ; IPath path = element . getPath ( ) ; if ( path . segment ( ) . equals ( getProject ( ) . getName ( ) ) ) return path . removeFirstSegments ( ) . toPortableString ( ) ; return path . toPortableString ( ) ; } protected String modifyFileToLaunch ( String path ) { if ( path == null || path . trim ( ) . length ( ) == ) return "" ; IRubyProject rubyproj = RubyCore . create ( getProject ( ) ) ; IPath projPath = rubyproj . getPath ( ) ; IPath duh = Path . fromOSString ( path ) ; if ( projPath . isPrefixOf ( duh ) ) { duh = duh . removeFirstSegments ( projPath . segmentCount ( ) ) ; } IFile file = getProject ( ) . getFile ( duh ) ; IRubyElement element = RubyCore . create ( file ) ; return element . getHandleIdentifier ( ) ; } public void initializeFrom ( ILaunchConfiguration configuration ) { super . initializeFrom ( configuration ) ; try { String testClass = configuration . getAttribute ( TestUnitLaunchConfigurationDelegate . TESTTYPE_ATTR , "" ) ; classSelector . setSelectionText ( testClass ) ; if ( testClass . length ( ) == ) { allClassesCheckBox . setSelection ( true ) ; } else { String testMethod = configuration . getAttribute ( TestUnitLaunchConfigurationDelegate . TESTNAME_ATTR , "" ) ; testMethodEditBox . setText ( testMethod ) ; if ( testMethod . length ( ) == ) allMethodsCheckBox . setSelection ( true ) ; } setControlState ( ) ; } catch ( CoreException e ) { TestunitPlugin . log ( e ) ; } } public void performApply ( ILaunchConfigurationWorkingCopy configuration ) { super . performApply ( configuration ) ; String testMethod = testMethodEditBox . getText ( ) ; if ( allMethodsCheckBox . getSelection ( ) ) testMethod = "" ; String testCaseClass = classSelector . getValidatedSelectionText ( ) ; if ( allClassesCheckBox . getSelection ( ) ) { testCaseClass = "" ; testMethod = "" ; } configuration . setAttribute ( TestUnitLaunchConfigurationDelegate . TESTNAME_ATTR , testMethod ) ; configuration . setAttribute ( TestUnitLaunchConfigurationDelegate . TESTTYPE_ATTR , testCaseClass ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , TestUnitLaunchConfigurationDelegate . getTestRunnerPath ( ) ) ; } @ Override protected String getFileToLaunchAttribute ( ) { return TestUnitLaunchConfigurationDelegate . LAUNCH_CONTAINER_ATTR ; } public String getName ( ) { return TestUnitMessages . JUnitMainTab_tab_label ; } } package org . rubypeople . rdt . testunit . launcher ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . RubyElementVisitor ; public class TestSearchEngine { public static IType [ ] findTests ( final IFile file ) { IRubyScript script = RubyCore . create ( file ) ; try { script . reconcile ( ) ; IRubyElement [ ] children = script . getChildren ( ) ; List < IType > types = new ArrayList < IType > ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( children [ i ] . isType ( IRubyElement . TYPE ) ) types . add ( ( IType ) children [ i ] ) ; } IType [ ] array = new IType [ types . size ( ) ] ; System . arraycopy ( types . toArray ( ) , , array , , types . size ( ) ) ; return array ; } catch ( RubyModelException e ) { RubyPlugin . log ( e ) ; } return new IType [ ] ; } public static IType [ ] findTests ( IProject rubyProject ) { if ( rubyProject == null ) { return new IType [ ] ; } try { List < IType > tests = new ArrayList < IType > ( ) ; RubyElementVisitor visitor = new RubyElementVisitor ( ) ; rubyProject . accept ( visitor ) ; Object [ ] rubyFiles = visitor . getCollectedRubyFiles ( ) ; for ( int i = ; i < rubyFiles . length ; i ++ ) { IFile rubyFile = ( IFile ) rubyFiles [ i ] ; IType [ ] elements = TestSearchEngine . findTests ( rubyFile ) ; for ( int j = ; j < elements . length ; j ++ ) { tests . add ( elements [ j ] ) ; } } Object [ ] listArray = tests . toArray ( ) ; IType [ ] array = new IType [ tests . size ( ) ] ; System . arraycopy ( listArray , , array , , listArray . length ) ; return array ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } return new IType [ ] ; } } package org . rubypeople . rdt . testunit . launcher ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . ui . DebugUITools ; import org . eclipse . debug . ui . IDebugModelPresentation ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . dialogs . ElementListSelectionDialog ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . launcher . RubyApplicationShortcut ; import org . rubypeople . rdt . internal . testunit . ui . TestUnitMessages ; import org . rubypeople . rdt . internal . testunit . ui . TestunitPlugin ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . RubyRuntime ; public class TestUnitLaunchShortcut extends RubyApplicationShortcut { protected void doLaunch ( IRubyElement rubyElement , String mode ) throws CoreException { String container = getContainer ( rubyElement ) ; ILaunchConfiguration config = findOrCreateLaunchConfiguration ( rubyElement , mode , container , "" , "" ) ; if ( config != null ) { DebugUITools . launch ( config , mode ) ; } } protected ILaunchConfiguration findOrCreateLaunchConfiguration ( IRubyElement rubyElement , String mode , String container , String testClass , String testName ) throws CoreException { IFile rubyFile = ( IFile ) rubyElement . getUnderlyingResource ( ) ; ILaunchConfigurationType configType = getRubyLaunchConfigType ( ) ; List < ILaunchConfiguration > candidateConfigs = null ; ILaunchConfiguration [ ] configs = getLaunchManager ( ) . getLaunchConfigurations ( configType ) ; candidateConfigs = new ArrayList < ILaunchConfiguration > ( configs . length ) ; for ( int i = ; i < configs . length ; i ++ ) { ILaunchConfiguration config = configs [ i ] ; if ( ( config . getAttribute ( TestUnitLaunchConfigurationDelegate . LAUNCH_CONTAINER_ATTR , "" ) . equals ( container ) ) && ( config . getAttribute ( TestUnitLaunchConfigurationDelegate . TESTTYPE_ATTR , "" ) . equals ( "" ) ) && ( config . getAttribute ( TestUnitLaunchConfigurationDelegate . TESTNAME_ATTR , "" ) . equals ( testName ) ) && ( config . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , "" ) . equals ( rubyFile . getProject ( ) . getName ( ) ) ) ) { candidateConfigs . add ( config ) ; } } switch ( candidateConfigs . size ( ) ) { case : return createConfiguration ( rubyFile , container , testName ) ; case : return candidateConfigs . get ( ) ; default : ILaunchConfiguration config = chooseConfiguration ( candidateConfigs , mode ) ; if ( config != null ) { return config ; } return null ; } } protected ILaunchConfiguration chooseConfiguration ( List configList , String mode ) { IDebugModelPresentation labelProvider = DebugUITools . newDebugModelPresentation ( ) ; ElementListSelectionDialog dialog = new ElementListSelectionDialog ( getShell ( ) , labelProvider ) ; dialog . setElements ( configList . toArray ( ) ) ; dialog . setTitle ( TestUnitMessages . LaunchTestAction_message_selectConfiguration ) ; if ( mode . equals ( ILaunchManager . DEBUG_MODE ) ) { dialog . setMessage ( TestUnitMessages . LaunchTestAction_message_selectDebugConfiguration ) ; } else { dialog . setMessage ( TestUnitMessages . LaunchTestAction_message_selectRunConfiguration ) ; } dialog . setMultipleSelection ( false ) ; int result = dialog . open ( ) ; labelProvider . dispose ( ) ; if ( result == Window . OK ) { return ( ILaunchConfiguration ) dialog . getFirstResult ( ) ; } return null ; } protected Shell getShell ( ) { return TestunitPlugin . getActiveWorkbenchShell ( ) ; } private String getContainer ( IRubyElement rubyElement ) { return rubyElement . getHandleIdentifier ( ) ; } protected ILaunchConfiguration createConfiguration ( IFile rubyFile , String container , String testName ) { return createConfiguration ( rubyFile . getLocation ( ) . toOSString ( ) , container , rubyFile . getProject ( ) , testName ) ; } protected ILaunchConfiguration createConfiguration ( String rubyFile , String container , IProject project , String testName ) { if ( RubyRuntime . getDefaultVMInstall ( ) == null ) { showNoInterpreterDialog ( ) ; return null ; } String [ ] commonLoadPathFolders = new String [ ] { "" , "" } ; List < String > loadpath = new ArrayList < String > ( ) ; try { for ( int i = ; i < commonLoadPathFolders . length ; i ++ ) { if ( project . getFolder ( commonLoadPathFolders [ i ] ) . exists ( ) ) { IRuntimeLoadpathEntry entry = RubyRuntime . newArchiveRuntimeLoadpathEntry ( project . getLocation ( ) . append ( commonLoadPathFolders [ i ] ) ) ; loadpath . add ( entry . getMemento ( ) ) ; } } } catch ( CoreException e ) { log ( e ) ; } ILaunchConfiguration config = null ; try { ILaunchConfigurationType configType = getRubyLaunchConfigType ( ) ; ILaunchConfigurationWorkingCopy wc = configType . newInstance ( null , RubyRuntime . generateUniqueLaunchConfigurationNameFrom ( rubyFile ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , project . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , TestUnitLaunchConfigurationDelegate . getTestRunnerPath ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , TestUnitLaunchShortcut . getDefaultWorkingDirectory ( project ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , RubyRuntime . getDefaultVMInstall ( ) . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE , RubyRuntime . getDefaultVMInstall ( ) . getVMInstallType ( ) . getId ( ) ) ; wc . setAttribute ( TestUnitLaunchConfigurationDelegate . LAUNCH_CONTAINER_ATTR , container ) ; wc . setAttribute ( TestUnitLaunchConfigurationDelegate . TESTNAME_ATTR , testName ) ; wc . setAttribute ( TestUnitLaunchConfigurationDelegate . TESTTYPE_ATTR , "" ) ; if ( loadpath != null && ! loadpath . isEmpty ( ) ) { wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_DEFAULT_LOADPATH , false ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_LOADPATH , loadpath ) ; } wc . setAttribute ( ILaunchConfiguration . ATTR_SOURCE_LOCATOR_ID , RdtDebugUiConstants . RUBY_SOURCE_LOCATOR ) ; config = wc . doSave ( ) ; } catch ( CoreException ce ) { log ( ce ) ; } return config ; } protected ILaunchConfigurationType getRubyLaunchConfigType ( ) { return getLaunchManager ( ) . getLaunchConfigurationType ( TestUnitLaunchConfigurationDelegate . ID_TESTUNIT_APPLICATION ) ; } protected ILaunchManager getLaunchManager ( ) { return DebugPlugin . getDefault ( ) . getLaunchManager ( ) ; } protected void log ( String message ) { TestunitPlugin . log ( new Status ( Status . INFO , TestunitPlugin . PLUGIN_ID , Status . INFO , message , null ) ) ; } protected void log ( Throwable t ) { TestunitPlugin . log ( t ) ; } protected void showNoInterpreterDialog ( ) { MessageDialog . openInformation ( TestunitPlugin . getActiveWorkbenchShell ( ) , TestUnitMessages . Dialog_launchWithoutSelectedInterpreter_title , TestUnitMessages . Dialog_launchWithoutSelectedInterpreter ) ; } protected static String getDefaultWorkingDirectory ( IProject project ) { if ( project != null && project . exists ( ) ) { return project . getLocation ( ) . toOSString ( ) ; } return TestunitPlugin . getWorkspace ( ) . getRoot ( ) . getLocation ( ) . toOSString ( ) ; } } package org . rubypeople . rdt . testunit . launcher ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . dialogs . ElementListSelectionDialog ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . testunit . ui . TestUnitMessages ; import org . rubypeople . rdt . internal . ui . util . FileSelector ; import org . rubypeople . rdt . internal . ui . util . RubyProjectSelector ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; public class RubyClassSelector { protected final static String EMPTY_STRING = "" ; private Composite composite ; private Button browseButton ; private Text textField ; protected String browseDialogMessage = EMPTY_STRING ; protected String browseDialogTitle = EMPTY_STRING ; protected String validatedSelectionText = EMPTY_STRING ; private FileSelector fileSelector ; private RubyProjectSelector projectSelector ; public RubyClassSelector ( Composite parent , FileSelector fileSelector , RubyProjectSelector projectSelector ) { this . fileSelector = fileSelector ; this . projectSelector = projectSelector ; composite = new Composite ( parent , SWT . NONE ) ; GridLayout compositeLayout = new GridLayout ( ) ; compositeLayout . marginWidth = ; compositeLayout . marginHeight = ; compositeLayout . numColumns = ; composite . setLayout ( compositeLayout ) ; textField = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; textField . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; textField . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { validatedSelectionText = validateResourceSelection ( ) ; } } ) ; browseButton = new Button ( composite , SWT . PUSH ) ; browseButton . setText ( "" ) ; browseButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { handleBrowseSelected ( ) ; } } ) ; browseDialogTitle = TestUnitMessages . RubyClassSelector_Title ; } protected void handleBrowseSelected ( ) { IType [ ] types = getTypesInSelectedFile ( ) ; if ( types == null ) types = getTypesInSelectedProject ( ) ; if ( types == null ) types = getAllTypes ( ) ; ElementListSelectionDialog dialog = new ElementListSelectionDialog ( getShell ( ) , new RubyElementLabelProvider ( ) ) ; dialog . setElements ( types ) ; dialog . setTitle ( browseDialogTitle ) ; dialog . setMessage ( browseDialogMessage ) ; dialog . setMultipleSelection ( false ) ; if ( dialog . open ( ) == Window . OK ) { textField . setText ( ( ( IRubyElement ) dialog . getFirstResult ( ) ) . getElementName ( ) ) ; } } private IType [ ] getTypesInSelectedProject ( ) { IProject rubyProject = projectSelector . getSelection ( ) ; if ( rubyProject == null ) return null ; return TestSearchEngine . findTests ( rubyProject ) ; } private IType [ ] getTypesInSelectedFile ( ) { String relativeFilePath = fileSelector . getValidatedSelectionText ( ) ; if ( relativeFilePath == null || relativeFilePath . trim ( ) . length ( ) == ) return null ; IProject rubyProject = projectSelector . getSelection ( ) ; if ( rubyProject == null ) return null ; IFile file = rubyProject . getFile ( relativeFilePath ) ; return TestSearchEngine . findTests ( file ) ; } private IType [ ] getAllTypes ( ) { List < IType > typeList = new ArrayList < IType > ( ) ; IProject [ ] projects = RubyCore . getRubyProjects ( ) ; for ( int i = ; i < projects . length ; i ++ ) { IType [ ] types = TestSearchEngine . findTests ( projects [ i ] ) ; typeList . addAll ( Arrays . asList ( types ) ) ; } IType [ ] allTypes = new IType [ typeList . size ( ) ] ; System . arraycopy ( typeList . toArray ( ) , , allTypes , , allTypes . length ) ; return allTypes ; } protected String validateResourceSelection ( ) { String selection = textField . getText ( ) ; return selection == null ? EMPTY_STRING : selection ; } protected Shell getShell ( ) { return composite . getShell ( ) ; } public void setLayoutData ( Object layoutData ) { composite . setLayoutData ( layoutData ) ; } public void addModifyListener ( ModifyListener aListener ) { textField . addModifyListener ( aListener ) ; } public void setBrowseDialogMessage ( String aMessage ) { browseDialogMessage = aMessage ; } public void setBrowseDialogTitle ( String aTitle ) { browseDialogTitle = aTitle ; } public void setEnabled ( boolean enabled ) { composite . setEnabled ( enabled ) ; textField . setEnabled ( enabled ) ; browseButton . setEnabled ( enabled ) ; } public String getSelectionText ( ) { return textField . getText ( ) ; } public String getValidatedSelectionText ( ) { return validatedSelectionText ; } public void setSelectionText ( String newText ) { textField . setText ( newText ) ; } } package org . rubypeople . rdt . testunit ; public interface ITestRunListener { public static final int STATUS_OK = ; public static final int STATUS_ERROR = ; public static final int STATUS_FAILURE = ; public void testRunStarted ( int testCount ) ; public void testRunEnded ( long elapsedTime ) ; public void testRunStopped ( long elapsedTime ) ; public void testStarted ( String testId , String testName ) ; public void testEnded ( String testId , String testName ) ; public void testFailed ( int status , String testId , String testName , String trace ) ; public void testRunTerminated ( ) ; public void testReran ( String testId , String testClass , String testName , int status , String trace ) ; } package org . rubypeople . rdt . testunit . wizards ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Vector ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . jface . wizard . WizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Widget ; import org . eclipse . ui . dialogs . ContainerCheckedTreeViewer ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . testunit . ui . TestunitPlugin ; import org . rubypeople . rdt . internal . testunit . util . LayoutUtil ; import org . rubypeople . rdt . internal . testunit . wizards . WizardMessages ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; public class RubyNewTestCaseWizardPageTwo extends WizardPage { private final static String PAGE_NAME = "" ; private final static String STORE_USE_TASKMARKER = PAGE_NAME + "" ; private IType fClassToTest ; private Button fCreateTasksButton ; private ContainerCheckedTreeViewer fMethodsTree ; private Button fSelectAllButton ; private Button fDeselectAllButton ; private Label fSelectedMethodsLabel ; private Object [ ] fCheckedObjects ; private boolean fCreateTasks ; public RubyNewTestCaseWizardPageTwo ( ) { super ( PAGE_NAME ) ; setTitle ( WizardMessages . NewTestCaseWizardPageTwo_title ) ; setDescription ( WizardMessages . NewTestCaseWizardPageTwo_description ) ; } public void createControl ( Composite parent ) { Composite container = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; container . setLayout ( layout ) ; createMethodsTreeControls ( container ) ; createSpacer ( container ) ; createButtonChoices ( container ) ; setControl ( container ) ; restoreWidgetValues ( ) ; Dialog . applyDialogFont ( container ) ; } private void createButtonChoices ( Composite container ) { GridLayout layout ; GridData gd ; Composite prefixContainer = new Composite ( container , SWT . NONE ) ; gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . horizontalSpan = ; prefixContainer . setLayoutData ( gd ) ; layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginWidth = ; layout . marginHeight = ; prefixContainer . setLayout ( layout ) ; SelectionListener listener = new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { doCheckBoxSelected ( e . widget ) ; } } ; fCreateTasksButton = createCheckBox ( prefixContainer , WizardMessages . NewTestCaseWizardPageTwo_create_tasks_text , listener ) ; } private Button createCheckBox ( Composite parent , String name , SelectionListener listener ) { Button button = new Button ( parent , SWT . CHECK | SWT . LEFT ) ; button . setText ( name ) ; button . setEnabled ( true ) ; button . setSelection ( true ) ; button . addSelectionListener ( listener ) ; GridData gd = new GridData ( GridData . FILL , GridData . CENTER , false , false ) ; button . setLayoutData ( gd ) ; return button ; } private void doCheckBoxSelected ( Widget widget ) { if ( widget == fCreateTasksButton ) { fCreateTasks = fCreateTasksButton . getSelection ( ) ; } saveWidgetValues ( ) ; } private void createMethodsTreeControls ( Composite container ) { Label label = new Label ( container , SWT . LEFT | SWT . WRAP ) ; label . setFont ( container . getFont ( ) ) ; label . setText ( WizardMessages . NewTestCaseWizardPageTwo_methods_tree_label ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = ; label . setLayoutData ( gd ) ; fMethodsTree = new ContainerCheckedTreeViewer ( container , SWT . BORDER ) ; gd = new GridData ( GridData . FILL_BOTH | GridData . GRAB_HORIZONTAL | GridData . GRAB_VERTICAL ) ; gd . heightHint = ; fMethodsTree . getTree ( ) . setLayoutData ( gd ) ; fMethodsTree . setLabelProvider ( new RubyElementLabelProvider ( ) ) ; fMethodsTree . setAutoExpandLevel ( ) ; fMethodsTree . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { doCheckedStateChanged ( ) ; } } ) ; fMethodsTree . addFilter ( new ViewerFilter ( ) { public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( element instanceof IMethod ) { IMethod method = ( IMethod ) element ; return ! method . getElementName ( ) . equals ( "" ) ; } return true ; } } ) ; Composite buttonContainer = new Composite ( container , SWT . NONE ) ; gd = new GridData ( GridData . FILL_VERTICAL ) ; buttonContainer . setLayoutData ( gd ) ; GridLayout buttonLayout = new GridLayout ( ) ; buttonLayout . marginWidth = ; buttonLayout . marginHeight = ; buttonContainer . setLayout ( buttonLayout ) ; fSelectAllButton = new Button ( buttonContainer , SWT . PUSH ) ; fSelectAllButton . setText ( WizardMessages . NewTestCaseWizardPageTwo_selectAll ) ; gd = new GridData ( GridData . FILL_HORIZONTAL | GridData . VERTICAL_ALIGN_BEGINNING ) ; fSelectAllButton . setLayoutData ( gd ) ; fSelectAllButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fMethodsTree . setCheckedElements ( ( Object [ ] ) fMethodsTree . getInput ( ) ) ; doCheckedStateChanged ( ) ; } } ) ; LayoutUtil . setButtonDimensionHint ( fSelectAllButton ) ; fDeselectAllButton = new Button ( buttonContainer , SWT . PUSH ) ; fDeselectAllButton . setText ( WizardMessages . NewTestCaseWizardPageTwo_deselectAll ) ; gd = new GridData ( GridData . FILL_HORIZONTAL | GridData . VERTICAL_ALIGN_BEGINNING ) ; fDeselectAllButton . setLayoutData ( gd ) ; fDeselectAllButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { fMethodsTree . setCheckedElements ( new Object [ ] ) ; doCheckedStateChanged ( ) ; } } ) ; LayoutUtil . setButtonDimensionHint ( fDeselectAllButton ) ; fSelectedMethodsLabel = new Label ( container , SWT . LEFT ) ; fSelectedMethodsLabel . setFont ( container . getFont ( ) ) ; doCheckedStateChanged ( ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = ; fSelectedMethodsLabel . setLayoutData ( gd ) ; Label emptyLabel = new Label ( container , SWT . LEFT ) ; gd = new GridData ( ) ; gd . horizontalSpan = ; emptyLabel . setLayoutData ( gd ) ; } private void createSpacer ( Composite container ) { Label spacer = new Label ( container , SWT . NONE ) ; GridData data = new GridData ( ) ; data . horizontalSpan = ; data . horizontalAlignment = GridData . FILL ; data . verticalAlignment = GridData . BEGINNING ; data . heightHint = ; spacer . setLayoutData ( data ) ; } public void setClassUnderTest ( IType classUnderTest ) { fClassToTest = classUnderTest ; } public void setVisible ( boolean visible ) { super . setVisible ( visible ) ; if ( visible ) { if ( fClassToTest == null ) { return ; } ArrayList types = null ; try { ITypeHierarchy hierarchy = fClassToTest . newSupertypeHierarchy ( null ) ; IType [ ] superTypes ; if ( fClassToTest . isClass ( ) ) superTypes = hierarchy . getAllSuperclasses ( fClassToTest ) ; else if ( fClassToTest . isModule ( ) ) superTypes = hierarchy . getAllSuperModules ( fClassToTest ) ; else superTypes = new IType [ ] ; types = new ArrayList ( superTypes . length + ) ; types . add ( fClassToTest ) ; types . addAll ( Arrays . asList ( superTypes ) ) ; } catch ( RubyModelException e ) { TestunitPlugin . log ( e ) ; } if ( types == null ) types = new ArrayList ( ) ; fMethodsTree . setContentProvider ( new MethodsTreeContentProvider ( types . toArray ( ) ) ) ; fMethodsTree . setInput ( types . toArray ( ) ) ; fMethodsTree . setSelection ( new StructuredSelection ( fClassToTest ) , true ) ; doCheckedStateChanged ( ) ; fMethodsTree . getControl ( ) . setFocus ( ) ; } } public IMethod [ ] getCheckedMethods ( ) { int methodCount = ; for ( int i = ; i < fCheckedObjects . length ; i ++ ) { if ( fCheckedObjects [ i ] instanceof IMethod ) methodCount ++ ; } IMethod [ ] checkedMethods = new IMethod [ methodCount ] ; int j = ; for ( int i = ; i < fCheckedObjects . length ; i ++ ) { if ( fCheckedObjects [ i ] instanceof IMethod ) { checkedMethods [ j ] = ( IMethod ) fCheckedObjects [ i ] ; j ++ ; } } return checkedMethods ; } private static class MethodsTreeContentProvider implements ITreeContentProvider { private Object [ ] fTypes ; private IMethod [ ] fMethods ; private final Object [ ] fEmpty = new Object [ ] ; public MethodsTreeContentProvider ( Object [ ] types ) { fTypes = types ; Vector methods = new Vector ( ) ; for ( int i = types . length - ; i > - ; i -- ) { Object object = types [ i ] ; if ( object instanceof IType ) { IType type = ( IType ) object ; try { IMethod [ ] currMethods = type . getMethods ( ) ; for_currMethods : for ( int j = ; j < currMethods . length ; j ++ ) { IMethod currMethod = currMethods [ j ] ; if ( currMethod . isPublic ( ) ) { for ( int k = ; k < methods . size ( ) ; k ++ ) { IMethod m = ( ( IMethod ) methods . get ( k ) ) ; if ( m . getElementName ( ) . equals ( currMethod . getElementName ( ) ) ) { methods . set ( k , currMethod ) ; continue for_currMethods ; } } methods . add ( currMethod ) ; } } } catch ( RubyModelException e ) { TestunitPlugin . log ( e ) ; } } } fMethods = new IMethod [ methods . size ( ) ] ; methods . copyInto ( fMethods ) ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof IType ) { IType parentType = ( IType ) parentElement ; ArrayList result = new ArrayList ( fMethods . length ) ; for ( int i = ; i < fMethods . length ; i ++ ) { if ( fMethods [ i ] . getDeclaringType ( ) . equals ( parentType ) ) { result . add ( fMethods [ i ] ) ; } } return result . toArray ( ) ; } return fEmpty ; } public Object getParent ( Object element ) { if ( element instanceof IMethod ) return ( ( IMethod ) element ) . getDeclaringType ( ) ; return null ; } public boolean hasChildren ( Object element ) { return getChildren ( element ) . length > ; } public Object [ ] getElements ( Object inputElement ) { return fTypes ; } public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public IMethod [ ] getAllMethods ( ) { return fMethods ; } } public boolean isCreateTasks ( ) { return fCreateTasks ; } private void doCheckedStateChanged ( ) { Object [ ] checked = fMethodsTree . getCheckedElements ( ) ; fCheckedObjects = checked ; int checkedMethodCount = ; for ( int i = ; i < checked . length ; i ++ ) { if ( checked [ i ] instanceof IMethod ) checkedMethodCount ++ ; } String label = "" ; if ( checkedMethodCount == ) label = Messages . format ( WizardMessages . NewTestCaseWizardPageTwo_selected_methods_label_one , new Integer ( checkedMethodCount ) ) ; else label = Messages . format ( WizardMessages . NewTestCaseWizardPageTwo_selected_methods_label_many , new Integer ( checkedMethodCount ) ) ; fSelectedMethodsLabel . setText ( label ) ; } public IMethod [ ] getAllMethods ( ) { return ( ( MethodsTreeContentProvider ) fMethodsTree . getContentProvider ( ) ) . getAllMethods ( ) ; } private void restoreWidgetValues ( ) { IDialogSettings settings = getDialogSettings ( ) ; if ( settings != null ) { fCreateTasks = settings . getBoolean ( STORE_USE_TASKMARKER ) ; fCreateTasksButton . setSelection ( fCreateTasks ) ; } } private void saveWidgetValues ( ) { IDialogSettings settings = getDialogSettings ( ) ; if ( settings != null ) { settings . put ( STORE_USE_TASKMARKER , fCreateTasks ) ; } } } package org . rubypeople . rdt . testunit . wizards ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogPage ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyConventions ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . internal . corext . codemanipulation . StubUtility ; import org . rubypeople . rdt . internal . corext . util . Messages ; import org . rubypeople . rdt . internal . testunit . util . LayoutUtil ; import org . rubypeople . rdt . internal . testunit . util . TestUnitStatus ; import org . rubypeople . rdt . internal . testunit . wizards . MethodStubsSelectionButtonGroup ; import org . rubypeople . rdt . internal . testunit . wizards . WizardMessages ; import org . rubypeople . rdt . internal . ui . dialogs . TypeSelectionDialog2 ; import org . rubypeople . rdt . ui . wizards . NewTypeWizardPage ; public class RubyNewTestCaseWizardPage extends NewTypeWizardPage { private final static String PAGE_NAME = "" ; public final static String CLASS_UNDER_TEST = PAGE_NAME + "" ; private final static String TEST_SUFFIX = "" ; private final static String PREFIX = "" ; private final static String STORE_SETUP = PAGE_NAME + "" ; private final static String STORE_TEARDOWN = PAGE_NAME + "" ; private final static String STORE_CONSTRUCTOR = PAGE_NAME + "" ; private final static int IDX_SETUP = ; private final static int IDX_TEARDOWN = ; private final static int IDX_CONSTRUCTOR = ; private String fClassUnderTestText ; private MethodStubsSelectionButtonGroup fMethodStubsButtons ; private Text fClassUnderTestControl ; private Button fClassUnderTestButton ; private IStatus fClassUnderTestStatus ; private IType fClassUnderTest ; private RubyNewTestCaseWizardPageTwo fPage2 ; public RubyNewTestCaseWizardPage ( RubyNewTestCaseWizardPageTwo page2 ) { super ( true , PAGE_NAME ) ; fPage2 = page2 ; setTitle ( WizardMessages . NewTestCaseWizardPage_title ) ; setDescription ( WizardMessages . NewTestCaseWizardPage_description ) ; String [ ] buttonNames = new String [ ] { WizardMessages . NewTestCaseWizardPage_methodStub_setUp , WizardMessages . NewTestCaseWizardPage_methodStub_tearDown , WizardMessages . NewTestCaseWizardPage_methodStub_constructor } ; fMethodStubsButtons = new MethodStubsSelectionButtonGroup ( SWT . CHECK , buttonNames , ) ; fMethodStubsButtons . setLabelText ( WizardMessages . NewTestCaseWizardPage_method_Stub_label ) ; fClassUnderTestStatus = new TestUnitStatus ( ) ; fClassUnderTestText = "" ; } public void createControl ( Composite parent ) { Composite container = new Composite ( parent , SWT . NONE ) ; int nColumns = ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = nColumns ; container . setLayout ( layout ) ; createContainerControls ( container , nColumns ) ; createSeparator ( container , nColumns ) ; createTypeNameControls ( container , nColumns ) ; createSuperClassControls ( container , nColumns ) ; createMethodStubSelectionControls ( container , nColumns ) ; createSeparator ( container , nColumns ) ; createClassUnderTestControls ( container , nColumns ) ; setControl ( container ) ; setSuperClass ( "" , true ) ; String classUnderTest = getClassUnderTestText ( ) ; if ( classUnderTest . length ( ) > ) { setTypeName ( classUnderTest + TEST_SUFFIX , true ) ; } Dialog . applyDialogFont ( container ) ; setFocus ( ) ; } protected void createTypeMembers ( IType type , IProgressMonitor monitor ) throws CoreException { String lineDelimiter = getLineDelimiter ( ) ; if ( fMethodStubsButtons . isSelected ( IDX_CONSTRUCTOR ) ) { createConstructor ( type , lineDelimiter ) ; } if ( fMethodStubsButtons . isSelected ( IDX_SETUP ) ) { createSetUp ( type , lineDelimiter ) ; } if ( fMethodStubsButtons . isSelected ( IDX_TEARDOWN ) ) { createTearDown ( type , lineDelimiter ) ; } if ( fClassUnderTest != null ) { createTestMethodStubs ( type ) ; } } @ Override protected List < String > addImports ( ) { List < String > imports = new ArrayList < String > ( ) ; imports . add ( "" ) ; return imports ; } private void createConstructor ( IType type , String lineDelimiter ) throws CoreException { StringBuffer content = new StringBuffer ( ) ; content . append ( "" ) . append ( lineDelimiter ) ; content . append ( "" ) . append ( lineDelimiter ) ; content . append ( "" ) . append ( lineDelimiter ) ; type . createMethod ( content . toString ( ) , null , true , null ) ; } private void createSetUp ( IType type , String lineDelimiter ) throws CoreException { StringBuffer content = new StringBuffer ( ) ; content . append ( "" ) . append ( lineDelimiter ) ; content . append ( "" ) . append ( lineDelimiter ) ; content . append ( "" ) . append ( lineDelimiter ) ; type . createMethod ( content . toString ( ) , null , true , null ) ; } private void createTearDown ( IType type , String lineDelimiter ) throws CoreException { StringBuffer content = new StringBuffer ( ) ; content . append ( "" ) . append ( lineDelimiter ) ; content . append ( "" ) . append ( lineDelimiter ) ; content . append ( "" ) . append ( lineDelimiter ) ; type . createMethod ( content . toString ( ) , null , true , null ) ; } private void createTestMethodStubs ( IType type ) throws CoreException { IMethod [ ] methods = fPage2 . getCheckedMethods ( ) ; if ( methods . length == ) return ; IMethod [ ] allMethodsArray = fPage2 . getAllMethods ( ) ; List allMethods = new ArrayList ( ) ; allMethods . addAll ( Arrays . asList ( allMethodsArray ) ) ; List names = new ArrayList ( ) ; for ( int i = ; i < methods . length ; i ++ ) { IMethod method = methods [ i ] ; String elementName = method . getElementName ( ) ; StringBuffer name = new StringBuffer ( PREFIX ) . append ( "" ) . append ( elementName ) ; StringBuffer buffer = new StringBuffer ( ) ; String testName = name . toString ( ) ; if ( names . contains ( testName ) ) { int suffix = ; while ( names . contains ( testName + Integer . toString ( suffix ) ) ) suffix ++ ; name . append ( Integer . toString ( suffix ) ) ; } testName = name . toString ( ) ; names . add ( testName ) ; buffer . append ( "" ) ; buffer . append ( testName ) . append ( getLineDelimiter ( ) ) ; appendTestMethodBody ( buffer , testName , method , type . getRubyScript ( ) ) ; buffer . append ( "" ) . append ( getLineDelimiter ( ) ) ; type . createMethod ( buffer . toString ( ) , null , false , null ) ; } } private void appendTestMethodBody ( StringBuffer buffer , String name , IMethod method , IRubyScript targetCu ) throws CoreException { final String delimiter = getLineDelimiter ( ) ; String todoTask = "" ; if ( fPage2 . isCreateTasks ( ) ) { String todoTaskTag = "" ; if ( todoTaskTag != null ) { todoTask = "" + todoTaskTag ; } } String message = WizardMessages . NewTestCaseWizardPageOne_not_yet_implemented_string ; buffer . append ( Messages . format ( "" , message ) ) . append ( todoTask ) . append ( delimiter ) ; } private String getLineDelimiter ( ) throws RubyModelException { IType classToTest = getClassUnderTest ( ) ; if ( classToTest == null && getSourceFolder ( ) != null && getSourceFolder ( ) . exists ( ) ) { return StubUtility . getLineDelimiterUsed ( getSourceFolder ( ) ) ; } if ( classToTest != null && classToTest . exists ( ) && classToTest . getRubyScript ( ) != null ) return classToTest . getRubyScript ( ) . findRecommendedLineSeparator ( ) ; return "" ; } protected void createMethodStubSelectionControls ( Composite composite , int nColumns ) { LayoutUtil . setHorizontalSpan ( fMethodStubsButtons . getLabelControl ( composite ) , nColumns ) ; LayoutUtil . createEmptySpace ( composite , ) ; LayoutUtil . setHorizontalSpan ( fMethodStubsButtons . getSelectionButtonsGroup ( composite ) , nColumns - ) ; } protected void createClassUnderTestControls ( Composite composite , int nColumns ) { Label classUnderTestLabel = new Label ( composite , SWT . LEFT | SWT . WRAP ) ; classUnderTestLabel . setFont ( composite . getFont ( ) ) ; classUnderTestLabel . setText ( WizardMessages . NewTestCaseWizardPage_class_to_test_label ) ; classUnderTestLabel . setLayoutData ( new GridData ( ) ) ; fClassUnderTestControl = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; fClassUnderTestControl . setEnabled ( true ) ; fClassUnderTestControl . setFont ( composite . getFont ( ) ) ; fClassUnderTestControl . setText ( fClassUnderTestText ) ; fClassUnderTestControl . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { internalSetClassUnderText ( ( ( Text ) e . widget ) . getText ( ) ) ; } } ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = true ; gd . horizontalSpan = nColumns - ; fClassUnderTestControl . setLayoutData ( gd ) ; fClassUnderTestButton = new Button ( composite , SWT . PUSH ) ; fClassUnderTestButton . setText ( WizardMessages . NewTestCaseWizardPage_class_to_test_browse ) ; fClassUnderTestButton . setEnabled ( true ) ; fClassUnderTestButton . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { classToTestButtonPressed ( ) ; } public void widgetSelected ( SelectionEvent e ) { classToTestButtonPressed ( ) ; } } ) ; gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . grabExcessHorizontalSpace = false ; gd . horizontalSpan = ; gd . widthHint = LayoutUtil . getButtonWidthHint ( fClassUnderTestButton ) ; fClassUnderTestButton . setLayoutData ( gd ) ; } private IType chooseClassToTestType ( ) { ISourceFolder root = getSourceFolder ( ) ; if ( root == null ) { return null ; } IRubyElement [ ] elements = new IRubyElement [ ] { root . getRubyProject ( ) } ; IRubySearchScope scope = SearchEngine . createRubySearchScope ( elements ) ; TypeSelectionDialog2 dialog = new TypeSelectionDialog2 ( getShell ( ) , false , getWizard ( ) . getContainer ( ) , scope , IRubySearchConstants . CLASS ) ; dialog . setTitle ( WizardMessages . NewTestCaseWizardPage_class_to_test_dialog_title ) ; dialog . setMessage ( WizardMessages . NewTestCaseWizardPage_class_to_test_dialog_message ) ; if ( dialog . open ( ) == Window . OK ) { return ( IType ) dialog . getFirstResult ( ) ; } return null ; } private void classToTestButtonPressed ( ) { IType type = chooseClassToTestType ( ) ; if ( type != null ) { setClassUnderTest ( type . getElementName ( ) ) ; } } public void setClassUnderTest ( String name ) { if ( fClassUnderTestControl != null && ! fClassUnderTestControl . isDisposed ( ) ) { fClassUnderTestControl . setText ( name ) ; } internalSetClassUnderText ( name ) ; } private void internalSetClassUnderText ( String name ) { fClassUnderTestText = name ; fClassUnderTestStatus = classUnderTestChanged ( ) ; handleFieldChanged ( CLASS_UNDER_TEST ) ; } protected IStatus classUnderTestChanged ( ) { TestUnitStatus status = new TestUnitStatus ( ) ; fClassUnderTest = null ; ISourceFolder root = getSourceFolder ( ) ; if ( root == null ) { return status ; } String classToTestName = getClassUnderTestText ( ) ; if ( classToTestName . length ( ) == ) { return status ; } String classUnderTest = getClassUnderTestText ( ) ; if ( classUnderTest . length ( ) > ) { setTypeName ( classUnderTest + TEST_SUFFIX , true ) ; } IStatus val = RubyConventions . validateRubyTypeName ( classToTestName ) ; if ( val . getSeverity ( ) == IStatus . ERROR ) { status . setError ( WizardMessages . NewTestCaseWizardPage_error_class_to_test_not_valid ) ; return status ; } try { IType type = resolveClassNameToType ( root . getRubyProject ( ) , classToTestName ) ; if ( type == null ) { status . setError ( WizardMessages . NewTestCaseWizardPage_error_class_to_test_not_exist ) ; return status ; } if ( type . isModule ( ) ) { status . setWarning ( Messages . format ( WizardMessages . NewTestCaseWizardPage_warning_class_to_test_is_interface , classToTestName ) ) ; } fClassUnderTest = type ; fPage2 . setClassUnderTest ( fClassUnderTest ) ; } catch ( RubyModelException e ) { status . setError ( WizardMessages . NewTestCaseWizardPage_error_class_to_test_not_valid ) ; } return status ; } public IType getClassUnderTest ( ) { return fClassUnderTest ; } private IType resolveClassNameToType ( IRubyProject rproject , String classToTestName ) throws RubyModelException { if ( ! rproject . exists ( ) ) { return null ; } IType type = rproject . findType ( classToTestName ) ; return type ; } public String getClassUnderTestText ( ) { return fClassUnderTestText ; } public void init ( IStructuredSelection selection ) { IRubyElement element = getInitialRubyElement ( selection ) ; initContainerPage ( element ) ; initTypePage ( element ) ; if ( element != null ) { IType classToTest = null ; IType typeInCompUnit = ( IType ) element . getAncestor ( IRubyElement . TYPE ) ; if ( typeInCompUnit != null ) { if ( typeInCompUnit . getRubyScript ( ) != null ) { classToTest = typeInCompUnit ; } } else { IRubyScript cu = ( IRubyScript ) element . getAncestor ( IRubyElement . SCRIPT ) ; if ( cu != null ) classToTest = cu . findPrimaryType ( ) ; } if ( classToTest != null ) { setClassUnderTest ( classToTest . getFullyQualifiedName ( ) ) ; } } restoreWidgetValues ( ) ; updateStatus ( getStatusList ( ) ) ; } protected IStatus [ ] getStatusList ( ) { return new IStatus [ ] { fContainerStatus , fTypeNameStatus , fClassUnderTestStatus , fSuperClassStatus } ; } private void restoreWidgetValues ( ) { IDialogSettings settings = getDialogSettings ( ) ; if ( settings != null ) { fMethodStubsButtons . setSelection ( IDX_SETUP , settings . getBoolean ( STORE_SETUP ) ) ; fMethodStubsButtons . setSelection ( IDX_TEARDOWN , settings . getBoolean ( STORE_TEARDOWN ) ) ; fMethodStubsButtons . setSelection ( IDX_CONSTRUCTOR , settings . getBoolean ( STORE_CONSTRUCTOR ) ) ; } else { fMethodStubsButtons . setSelection ( IDX_SETUP , false ) ; fMethodStubsButtons . setSelection ( IDX_TEARDOWN , false ) ; fMethodStubsButtons . setSelection ( IDX_CONSTRUCTOR , false ) ; } } } package org . rubypeople . rdt . testunit ; public interface ITestUnitConstants { public static final String ID_NEW_TESTCASE_WIZARD = "" ; } package org . rubypeople . rdt . internal . debug . ui ; import java . io . File ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . model . IPersistableSourceLocator ; import org . eclipse . debug . core . model . IStackFrame ; import org . eclipse . debug . ui . ISourcePresentation ; import org . eclipse . ui . IEditorDescriptor ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . part . FileEditorInput ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . internal . ui . rubyeditor . ExternalRubyFileEditorInput ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . ui . RubyUI ; public class RubySourceLocator implements IPersistableSourceLocator , ISourcePresentation { private String absoluteWorkingDirectory ; private String projectName ; public RubySourceLocator ( ) { } public String getAbsoluteWorkingDirectory ( ) { return absoluteWorkingDirectory ; } public String getMemento ( ) throws CoreException { return null ; } public void initializeFromMemento ( String memento ) throws CoreException { } public void initializeDefaults ( ILaunchConfiguration configuration ) throws CoreException { this . absoluteWorkingDirectory = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , "" ) ; this . projectName = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , "" ) ; } public Object getSourceElement ( IStackFrame stackFrame ) { return this . getSourceElement ( ( ( IRubyStackFrame ) stackFrame ) . getFileName ( ) ) ; } public Object getSourceElement ( String pFilename ) { return new SourceElement ( pFilename , this ) ; } public String getEditorId ( IEditorInput input , Object element ) { SourceElement sourceElement = ( SourceElement ) element ; try { IEditorDescriptor desc = IDE . getEditorDescriptor ( sourceElement . getFilename ( ) ) ; return desc . getId ( ) ; } catch ( PartInitException e ) { } return sourceElement . isExternal ( ) ? RubyUI . ID_EXTERNAL_EDITOR : RubyUI . ID_RUBY_EDITOR ; } public IEditorInput getEditorInput ( Object element ) { SourceElement sourceElement = ( SourceElement ) element ; if ( ! sourceElement . isExternal ( ) ) { return new FileEditorInput ( sourceElement . getWorkspaceFile ( ) ) ; } File filesystemFile = new File ( sourceElement . getFilename ( ) ) ; if ( filesystemFile . exists ( ) ) { return new ExternalRubyFileEditorInput ( filesystemFile ) ; } RdtDebugCorePlugin . log ( IStatus . INFO , RdtDebugUiMessages . getFormattedString ( RdtDebugUiMessages . RdtDebugUiPlugin_couldNotOpenFile , sourceElement . getFilename ( ) ) ) ; return null ; } public class SourceElement { private String filename ; private IFile workspaceFile ; private RubySourceLocator sourceLocator ; public SourceElement ( String aFilename , RubySourceLocator pSourceLocator ) { filename = aFilename ; this . sourceLocator = pSourceLocator ; init ( ) ; } private void init ( ) { setFileName ( ) ; grabWorkspaceFile ( ) ; } private void setFileName ( ) { if ( filename == null ) return ; if ( filename . startsWith ( "" ) ) { filename = filename . substring ( ) ; } if ( sourceLocator . getAbsoluteWorkingDirectory ( ) != null && sourceLocator . getAbsoluteWorkingDirectory ( ) . trim ( ) . length ( ) > ) { String relativeToWorkingDir = sourceLocator . getAbsoluteWorkingDirectory ( ) + "" + filename ; File file = new File ( relativeToWorkingDir ) ; if ( file . exists ( ) && ! file . isDirectory ( ) ) { filename = relativeToWorkingDir ; return ; } } if ( projectName != null && projectName . trim ( ) . length ( ) > ) { IProject project = getProject ( ) ; String relativeToProject = project . getLocation ( ) . toOSString ( ) + filename . substring ( ) ; File file = new File ( relativeToProject ) ; if ( file . exists ( ) && ! file . isDirectory ( ) ) { filename = relativeToProject ; return ; } } } private IProject getProject ( ) { if ( projectName == null ) return null ; return RdtDebugCorePlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; } private void grabWorkspaceFile ( ) { if ( filename == null ) return ; workspaceFile = RdtDebugCorePlugin . getWorkspace ( ) . getRoot ( ) . getFileForLocation ( new Path ( filename ) ) ; if ( workspaceFile != null && workspaceFile . exists ( ) ) return ; try { workspaceFile = RdtDebugCorePlugin . getWorkspace ( ) . getRoot ( ) . getFile ( new Path ( filename ) ) ; if ( workspaceFile != null && workspaceFile . exists ( ) ) return ; } catch ( RuntimeException e ) { workspaceFile = null ; } if ( getProject ( ) != null ) { workspaceFile = getProject ( ) . getFile ( new Path ( filename ) ) ; } } public boolean isExternal ( ) { return workspaceFile == null || ! workspaceFile . exists ( ) ; } public IFile getWorkspaceFile ( ) { return workspaceFile ; } public String getFilename ( ) { return filename ; } } } package org . rubypeople . rdt . internal . debug . ui . evaluation ; import java . io . IOException ; import java . io . StringReader ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . core . runtime . Preferences . PropertyChangeEvent ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public class EvaluationExpressionModel implements Preferences . IPropertyChangeListener { public void propertyChange ( PropertyChangeEvent event ) { this . loadExpressions ( ) ; } private EvaluationExpression [ ] evaluationExpressions ; public EvaluationExpression [ ] getEvaluationExpressions ( ) { if ( evaluationExpressions == null ) { getPreferences ( ) . addPropertyChangeListener ( this ) ; this . loadExpressions ( ) ; } return evaluationExpressions ; } private void loadExpressions ( ) { String expressionsXml = this . getPreferences ( ) . getString ( RdtDebugUiConstants . EVALUATION_EXPRESSIONS_PREFERENCE ) ; try { evaluationExpressions = new EvaluationExpressionReaderWriter ( ) . read ( new StringReader ( expressionsXml ) , null ) ; } catch ( IOException e ) { evaluationExpressions = new EvaluationExpression [ ] ; RdtDebugUiPlugin . log ( e ) ; } } private Preferences getPreferences ( ) { return RdtDebugUiPlugin . getDefault ( ) . getPluginPreferences ( ) ; } } package org . rubypeople . rdt . internal . debug . ui . evaluation ; public class EvaluationExpression { private final String VARIABLE_TOKEN = "" ; private String name ; private String description ; private String expression ; private boolean enabled ; public EvaluationExpression ( String name , String description , String expression , boolean enabled ) { this . name = name ; this . description = description ; this . expression = expression ; this . enabled = enabled ; } public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this . description = description ; } public String getExpression ( ) { return expression ; } public void setExpression ( String expression ) { this . expression = expression ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String substitute ( String value ) { return this . expression . replaceAll ( VARIABLE_TOKEN , value ) ; } public boolean isEnabled ( ) { return enabled ; } public void setEnabled ( boolean enabled ) { this . enabled = enabled ; } public boolean hasVariable ( ) { return this . expression . indexOf ( VARIABLE_TOKEN ) != - ; } public Object clone ( ) throws CloneNotSupportedException { return new EvaluationExpression ( this . getName ( ) , this . getDescription ( ) , this . getExpression ( ) , this . enabled ) ; } } package org . rubypeople . rdt . internal . debug . ui . evaluation ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . Reader ; import java . io . Writer ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; import java . util . Set ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . Transformer ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; import org . eclipse . jface . text . Assert ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . w3c . dom . Attr ; import org . w3c . dom . Document ; import org . w3c . dom . NamedNodeMap ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . w3c . dom . Text ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; public class EvaluationExpressionReaderWriter { private static final String TEMPLATE_ROOT = "" ; private static final String TEMPLATE_ELEMENT = "" ; private static final String NAME_ATTRIBUTE = "" ; private static final String DESCRIPTION_ATTRIBUTE = "" ; private static final String ENABLED_ATTRIBUTE = "" ; public EvaluationExpressionReaderWriter ( ) { } public EvaluationExpression [ ] read ( Reader reader ) throws IOException { return read ( reader , null ) ; } public EvaluationExpression [ ] read ( Reader reader , ResourceBundle bundle ) throws IOException { return read ( new InputSource ( reader ) , bundle ) ; } public EvaluationExpression [ ] read ( InputStream stream , ResourceBundle bundle ) throws IOException { return read ( new InputSource ( stream ) , bundle ) ; } private EvaluationExpression [ ] read ( InputSource source , ResourceBundle bundle ) throws IOException { try { Collection expressions = new ArrayList ( ) ; Set ids = new HashSet ( ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder parser = factory . newDocumentBuilder ( ) ; Document document = parser . parse ( source ) ; NodeList elements = document . getElementsByTagName ( TEMPLATE_ELEMENT ) ; int count = elements . getLength ( ) ; for ( int i = ; i != count ; i ++ ) { Node node = elements . item ( i ) ; NamedNodeMap attributes = node . getAttributes ( ) ; if ( attributes == null ) continue ; String name = getStringValue ( attributes , NAME_ATTRIBUTE ) ; name = translateString ( name , bundle ) ; String description = getStringValue ( attributes , DESCRIPTION_ATTRIBUTE , "" ) ; description = translateString ( description , bundle ) ; String enabled = getStringValue ( attributes , ENABLED_ATTRIBUTE , "" ) ; StringBuffer buffer = new StringBuffer ( ) ; NodeList children = node . getChildNodes ( ) ; for ( int j = ; j != children . getLength ( ) ; j ++ ) { String value = children . item ( j ) . getNodeValue ( ) ; if ( value != null ) buffer . append ( value ) ; } expressions . add ( new EvaluationExpression ( name , description , buffer . toString ( ) , new Boolean ( enabled ) ) ) ; } return ( EvaluationExpression [ ] ) expressions . toArray ( new EvaluationExpression [ expressions . size ( ) ] ) ; } catch ( ParserConfigurationException e ) { Assert . isTrue ( false ) ; } catch ( SAXException e ) { Throwable t = e . getCause ( ) ; if ( t instanceof IOException ) throw ( IOException ) t ; else throw new IOException ( t . getMessage ( ) ) ; } return null ; } public void save ( EvaluationExpression [ ] templates , OutputStream stream ) throws IOException { save ( templates , new StreamResult ( stream ) ) ; } public void save ( EvaluationExpression [ ] templates , Writer writer ) throws IOException { save ( templates , new StreamResult ( writer ) ) ; } private void save ( EvaluationExpression [ ] templates , StreamResult result ) throws IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document document = builder . newDocument ( ) ; Node root = document . createElement ( TEMPLATE_ROOT ) ; document . appendChild ( root ) ; for ( int i = ; i < templates . length ; i ++ ) { EvaluationExpression evaluationExpression = templates [ i ] ; Node node = document . createElement ( TEMPLATE_ELEMENT ) ; root . appendChild ( node ) ; NamedNodeMap attributes = node . getAttributes ( ) ; Attr name = document . createAttribute ( NAME_ATTRIBUTE ) ; name . setValue ( evaluationExpression . getName ( ) ) ; attributes . setNamedItem ( name ) ; Attr description = document . createAttribute ( DESCRIPTION_ATTRIBUTE ) ; description . setValue ( evaluationExpression . getDescription ( ) ) ; attributes . setNamedItem ( description ) ; Attr enabled = document . createAttribute ( ENABLED_ATTRIBUTE ) ; enabled . setValue ( String . valueOf ( evaluationExpression . isEnabled ( ) ) ) ; attributes . setNamedItem ( enabled ) ; Text pattern = document . createTextNode ( evaluationExpression . getExpression ( ) ) ; node . appendChild ( pattern ) ; } Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . METHOD , "" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , "" ) ; DOMSource source = new DOMSource ( document ) ; transformer . transform ( source , result ) ; } catch ( ParserConfigurationException e ) { Assert . isTrue ( false ) ; } catch ( TransformerException e ) { if ( e . getException ( ) instanceof IOException ) throw ( IOException ) e . getException ( ) ; Assert . isTrue ( false ) ; } } private String getStringValue ( NamedNodeMap attributes , String name ) throws SAXException { return getStringValue ( attributes , name , null ) ; } private String getStringValue ( NamedNodeMap attributes , String name , String defaultValue ) { Node node = attributes . getNamedItem ( name ) ; return node == null ? defaultValue : node . getNodeValue ( ) ; } private String translateString ( String str , ResourceBundle bundle ) { if ( bundle == null ) return str ; int idx = str . indexOf ( '' ) ; if ( idx == - ) { return str ; } StringBuffer buf = new StringBuffer ( ) ; int k = ; while ( idx != - ) { buf . append ( str . substring ( k , idx ) ) ; for ( k = idx + ; k < str . length ( ) && ! Character . isWhitespace ( str . charAt ( k ) ) ; k ++ ) { } String key = str . substring ( idx + , k ) ; buf . append ( getBundleString ( key , bundle ) ) ; idx = str . indexOf ( '' , k ) ; } buf . append ( str . substring ( k ) ) ; return buf . toString ( ) ; } private String getBundleString ( String key , ResourceBundle bundle ) { if ( bundle != null ) { try { return bundle . getString ( key ) ; } catch ( MissingResourceException e ) { return '' + key + '' ; } } else return RdtDebugUiMessages . getString ( key ) ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . core . runtime . IAdapterFactory ; import org . eclipse . debug . ui . actions . IToggleBreakpointsTarget ; public class RetargettableActionAdapterFactory implements IAdapterFactory { public Object getAdapter ( Object adaptableObject , Class adapterType ) { if ( adapterType == IToggleBreakpointsTarget . class ) { return new ToggleBreakpointAdapter ( ) ; } return null ; } public Class [ ] getAdapterList ( ) { return new Class [ ] { IToggleBreakpointsTarget . class } ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . jface . viewers . Viewer ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; public class ShowStaticVariablesAction extends VariableFilterAction { protected String getPreferenceKey ( ) { return RdtDebugUiConstants . SHOW_STATIC_VARIABLES_PREFERENCE ; } public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( element instanceof IRubyVariable ) { IRubyVariable variable = ( IRubyVariable ) element ; if ( ! getValue ( ) ) { return ! variable . isStatic ( ) ; } } return true ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . IBreakpointManager ; import org . eclipse . debug . core . model . IBreakpoint ; import org . eclipse . debug . ui . actions . IToggleBreakpointsTargetExtension ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . jruby . ast . RootNode ; import org . jruby . parser . RubyParserResult ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . debug . core . IRubyBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyLineBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyMethodBreakpoint ; import org . rubypeople . rdt . debug . core . RdtDebugModel ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . debug . ui . BreakpointUtils ; import org . rubypeople . rdt . internal . debug . ui . DebugWorkingCopyManager ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . IRubyScriptEditorInput ; import org . rubypeople . rdt . ui . IWorkingCopyManager ; import org . rubypeople . rdt . ui . RubyUI ; public class ToggleBreakpointAdapter implements IToggleBreakpointsTargetExtension { public boolean canToggleBreakpoints ( IWorkbenchPart part , ISelection selection ) { if ( isRemote ( part , selection ) ) { return false ; } return canToggleLineBreakpoints ( part , selection ) ; } public void toggleBreakpoints ( IWorkbenchPart part , ISelection selection ) throws CoreException { ISelection sel = translateToMembers ( part , selection ) ; if ( sel instanceof IStructuredSelection ) { IMember member = ( IMember ) ( ( IStructuredSelection ) sel ) . getFirstElement ( ) ; int mtype = member . getElementType ( ) ; if ( mtype == IRubyElement . FIELD || mtype == IRubyElement . METHOD ) { if ( selection instanceof ITextSelection ) { ITextSelection ts = ( ITextSelection ) selection ; IType declaringType = member . getDeclaringType ( ) ; IResource resource = BreakpointUtils . getBreakpointResource ( declaringType ) ; IRubyLineBreakpoint breakpoint = RdtDebugModel . lineBreakpointExists ( resource , null , ts . getStartLine ( ) ) ; if ( breakpoint != null ) { breakpoint . delete ( ) ; return ; } RootNode unit = parseRubyScript ( getTextEditor ( part ) ) ; ValidBreakpointLocationLocator loc = new ValidBreakpointLocationLocator ( unit , ts . getStartLine ( ) , true ) ; unit . accept ( loc ) ; if ( loc . getLocationType ( ) == ValidBreakpointLocationLocator . LOCATION_METHOD ) { toggleMethodBreakpoints ( part , sel ) ; } else if ( loc . getLocationType ( ) == ValidBreakpointLocationLocator . LOCATION_FIELD ) { toggleWatchpoints ( part , ts ) ; } else if ( loc . getLocationType ( ) == ValidBreakpointLocationLocator . LOCATION_LINE ) { toggleLineBreakpoints ( part , ts ) ; } else { toggleLineBreakpoints ( part , selection , true ) ; } } } else { toggleLineBreakpoints ( part , selection , true ) ; } } else { toggleLineBreakpoints ( part , selection , true ) ; } } private RootNode parseRubyScript ( ITextEditor textEditor ) throws RubyModelException { IRubyScript script = getTypeRoot ( textEditor . getEditorInput ( ) ) ; RubyParserResult result = new RubyParser ( ) . parse ( script . getElementName ( ) , script . getSource ( ) ) ; return ( RootNode ) result . getAST ( ) ; } public boolean canToggleLineBreakpoints ( IWorkbenchPart part , ISelection selection ) { if ( isRemote ( part , selection ) ) { return false ; } return selection instanceof ITextSelection ; } public boolean canToggleMethodBreakpoints ( IWorkbenchPart part , ISelection selection ) { if ( isRemote ( part , selection ) ) { return false ; } if ( selection instanceof IStructuredSelection ) { IStructuredSelection ss = ( IStructuredSelection ) selection ; return getMethods ( ss ) . length > ; } return ( selection instanceof ITextSelection ) && isMethod ( ( ITextSelection ) selection , part ) ; } public boolean canToggleWatchpoints ( IWorkbenchPart part , ISelection selection ) { return false ; } public void toggleLineBreakpoints ( IWorkbenchPart part , ISelection selection ) throws CoreException { toggleLineBreakpoints ( part , selection , false ) ; } public void toggleLineBreakpoints ( final IWorkbenchPart part , final ISelection selection , final boolean bestMatch ) { Job job = new Job ( "" ) { protected IStatus run ( IProgressMonitor monitor ) { ITextEditor editor = getTextEditor ( part ) ; if ( editor != null && selection instanceof ITextSelection ) { if ( monitor . isCanceled ( ) ) { return Status . CANCEL_STATUS ; } try { ISelection sel = selection ; if ( ! ( selection instanceof IStructuredSelection ) ) { sel = translateToMembers ( part , selection ) ; } String tname = null ; IRubyElement element = null ; if ( sel instanceof IStructuredSelection ) { IMember member = ( IMember ) ( ( IStructuredSelection ) sel ) . getFirstElement ( ) ; IType type = null ; if ( member . getElementType ( ) == IRubyElement . TYPE ) { type = ( IType ) member ; } else { type = member . getDeclaringType ( ) ; } tname = createQualifiedTypeName ( type ) ; element = type ; } if ( tname == null ) tname = "" ; if ( element == null ) element = getTypeRoot ( editor . getEditorInput ( ) ) ; IResource resource = BreakpointUtils . getBreakpointResource ( element ) ; int lnumber = ( ( ITextSelection ) selection ) . getStartLine ( ) ; IRubyLineBreakpoint existingBreakpoint = RdtDebugModel . lineBreakpointExists ( resource , tname , lnumber + ) ; if ( existingBreakpoint != null ) { DebugPlugin . getDefault ( ) . getBreakpointManager ( ) . removeBreakpoint ( existingBreakpoint , true ) ; return Status . OK_STATUS ; } Map attributes = new HashMap ( ) ; IDocumentProvider documentProvider = editor . getDocumentProvider ( ) ; if ( documentProvider == null ) { return Status . CANCEL_STATUS ; } IDocument document = documentProvider . getDocument ( editor . getEditorInput ( ) ) ; try { IRegion line = document . getLineInformation ( lnumber - ) ; int start = line . getOffset ( ) ; int end = start + line . getLength ( ) - ; BreakpointUtils . addRubyBreakpointAttributesWithMemberDetails ( attributes , element , start , end ) ; } catch ( BadLocationException ble ) { RdtDebugUiPlugin . log ( ble ) ; } RdtDebugModel . createLineBreakpoint ( resource , getFileName ( editor . getEditorInput ( ) ) , tname , lnumber + , true , attributes ) ; } catch ( CoreException x ) { System . out . println ( x . getMessage ( ) ) ; } } return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . schedule ( ) ; } private String getFileName ( IEditorInput editorInput ) { if ( editorInput instanceof IRubyScriptEditorInput ) return ( ( IRubyScriptEditorInput ) editorInput ) . getRubyScript ( ) . getPath ( ) . makeAbsolute ( ) . toOSString ( ) ; return null ; } public void toggleMethodBreakpoints ( final IWorkbenchPart part , final ISelection finalSelection ) throws CoreException { Job job = new Job ( "" ) { protected IStatus run ( IProgressMonitor monitor ) { if ( monitor . isCanceled ( ) ) { return Status . CANCEL_STATUS ; } try { ISelection selection = finalSelection ; if ( ! ( selection instanceof IStructuredSelection ) ) { selection = translateToMembers ( part , selection ) ; } if ( selection instanceof IStructuredSelection ) { IMethod [ ] members = getMethods ( ( IStructuredSelection ) selection ) ; if ( members . length == ) { return Status . OK_STATUS ; } IRubyBreakpoint breakpoint = null ; ISourceRange range = null ; Map attributes = null ; IType type = null ; String mname = null ; for ( int i = , length = members . length ; i < length ; i ++ ) { breakpoint = getMethodBreakpoint ( members [ i ] ) ; if ( breakpoint == null ) { int start = - ; int end = - ; range = members [ i ] . getNameRange ( ) ; if ( range != null ) { start = range . getOffset ( ) ; end = start + range . getLength ( ) ; } attributes = new HashMap ( ) ; BreakpointUtils . addRubyBreakpointAttributes ( attributes , members [ i ] ) ; type = members [ i ] . getDeclaringType ( ) ; mname = members [ i ] . getElementName ( ) ; if ( members [ i ] . isConstructor ( ) ) { mname = "" ; } RdtDebugModel . createMethodBreakpoint ( BreakpointUtils . getBreakpointResource ( members [ i ] ) , createQualifiedTypeName ( type ) , mname , true , false , - , start , end , , true , attributes ) ; } else { DebugPlugin . getDefault ( ) . getBreakpointManager ( ) . removeBreakpoint ( breakpoint , true ) ; } } } else { return Status . OK_STATUS ; } } catch ( CoreException e ) { return e . getStatus ( ) ; } return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . schedule ( ) ; } protected String createQualifiedTypeName ( IType type ) { if ( type == null ) return null ; return type . getFullyQualifiedName ( ) ; } protected IRubyBreakpoint getMethodBreakpoint ( IMember element ) { IBreakpointManager breakpointManager = DebugPlugin . getDefault ( ) . getBreakpointManager ( ) ; IBreakpoint [ ] breakpoints = breakpointManager . getBreakpoints ( RdtDebugModel . getModelIdentifier ( ) ) ; if ( element instanceof IMethod ) { IMethod method = ( IMethod ) element ; for ( int i = ; i < breakpoints . length ; i ++ ) { IBreakpoint breakpoint = breakpoints [ i ] ; if ( breakpoint instanceof IRubyMethodBreakpoint ) { IRubyMethodBreakpoint methodBreakpoint = ( IRubyMethodBreakpoint ) breakpoint ; IMember container = null ; try { container = BreakpointUtils . getMember ( methodBreakpoint ) ; } catch ( CoreException e ) { RdtDebugUiPlugin . log ( e ) ; return null ; } if ( container == null ) { try { if ( method . getDeclaringType ( ) . getFullyQualifiedName ( ) . equals ( methodBreakpoint . getTypeName ( ) ) && method . getElementName ( ) . equals ( methodBreakpoint . getMethodName ( ) ) ) { return methodBreakpoint ; } } catch ( CoreException e ) { RdtDebugUiPlugin . log ( e ) ; } } else { if ( container instanceof IMethod ) { if ( method . getDeclaringType ( ) . getFullyQualifiedName ( ) . equals ( container . getDeclaringType ( ) . getFullyQualifiedName ( ) ) ) { if ( method . isSimilar ( ( IMethod ) container ) ) { return methodBreakpoint ; } } } } } } } return null ; } public void toggleWatchpoints ( IWorkbenchPart part , ISelection selection ) throws CoreException { } protected boolean isRemote ( IWorkbenchPart part , ISelection selection ) { if ( selection instanceof IStructuredSelection ) { IStructuredSelection ss = ( IStructuredSelection ) selection ; Object element = ss . getFirstElement ( ) ; if ( element instanceof IMember ) { IMember member = ( IMember ) element ; return ! member . getRubyProject ( ) . getProject ( ) . exists ( ) ; } } ITextEditor editor = getTextEditor ( part ) ; if ( editor != null ) { IEditorInput input = editor . getEditorInput ( ) ; Object adapter = Platform . getAdapterManager ( ) . getAdapter ( input , "" ) ; return adapter != null ; } return false ; } protected ITextEditor getTextEditor ( IWorkbenchPart part ) { if ( part instanceof ITextEditor ) { return ( ITextEditor ) part ; } return ( ITextEditor ) part . getAdapter ( ITextEditor . class ) ; } protected IMethod [ ] getMethods ( IStructuredSelection selection ) { if ( selection . isEmpty ( ) ) { return new IMethod [ ] ; } List < IMethod > methods = new ArrayList < IMethod > ( selection . size ( ) ) ; Iterator iterator = selection . iterator ( ) ; while ( iterator . hasNext ( ) ) { Object thing = iterator . next ( ) ; if ( thing instanceof IMethod ) { methods . add ( ( IMethod ) thing ) ; } } return ( IMethod [ ] ) methods . toArray ( new IMethod [ methods . size ( ) ] ) ; } private boolean isMethod ( ITextSelection selection , IWorkbenchPart part ) { ITextEditor editor = getTextEditor ( part ) ; if ( editor != null ) { IRubyElement element = getRubyElement ( editor . getEditorInput ( ) ) ; if ( element != null ) { try { if ( element instanceof IRubyScript ) { element = ( ( IRubyScript ) element ) . getElementAt ( selection . getOffset ( ) ) ; } return element != null && element . getElementType ( ) == IRubyElement . METHOD ; } catch ( RubyModelException e ) { return false ; } } } return false ; } private IRubyElement getRubyElement ( IEditorInput input ) { IRubyElement re = RubyUI . getEditorInputRubyElement ( input ) ; if ( re != null ) { return re ; } return DebugWorkingCopyManager . getWorkingCopy ( input , false ) ; } protected ISelection translateToMembers ( IWorkbenchPart part , ISelection selection ) throws CoreException { ITextEditor textEditor = getTextEditor ( part ) ; if ( textEditor != null && selection instanceof ITextSelection ) { ITextSelection textSelection = ( ITextSelection ) selection ; IEditorInput editorInput = textEditor . getEditorInput ( ) ; IDocumentProvider documentProvider = textEditor . getDocumentProvider ( ) ; if ( documentProvider == null ) { throw new CoreException ( Status . CANCEL_STATUS ) ; } IDocument document = documentProvider . getDocument ( editorInput ) ; int offset = textSelection . getOffset ( ) ; if ( document != null ) { try { IRegion region = document . getLineInformationOfOffset ( offset ) ; int end = region . getOffset ( ) + region . getLength ( ) ; while ( Character . isWhitespace ( document . getChar ( offset ) ) && offset < end ) { offset ++ ; } } catch ( BadLocationException e ) { } } IMember m = null ; IRubyScript root = getTypeRoot ( editorInput ) ; if ( root != null ) { synchronized ( root ) { root . reconcile ( false , null , null ) ; } IRubyElement e = root . getElementAt ( offset ) ; if ( e instanceof IMember ) { m = ( IMember ) e ; } } if ( m != null ) { return new StructuredSelection ( m ) ; } } return selection ; } private IRubyScript getTypeRoot ( IEditorInput input ) { IWorkingCopyManager manager = RubyUI . getWorkingCopyManager ( ) ; IRubyScript root = manager . getWorkingCopy ( input ) ; if ( root == null ) { root = DebugWorkingCopyManager . getWorkingCopy ( input , false ) ; } return root ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IViewActionDelegate ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; import org . rubypeople . rdt . internal . debug . core . model . RubyExpression ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; public class InspectHashKeyAction extends AbstractInspectAction implements IViewActionDelegate { public void run ( IAction arg0 ) { if ( ! ( this . selection instanceof StructuredSelection ) ) { return ; } Object selectedObject = ( ( StructuredSelection ) this . selection ) . getFirstElement ( ) ; if ( selectedObject == null ) { return ; } if ( ! ( selectedObject instanceof IRubyVariable ) ) { return ; } final IRubyVariable var = ( ( IRubyVariable ) selectedObject ) ; Display . getCurrent ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { String hashId = var . getParent ( ) . getObjectId ( ) ; String valueId = var . getObjectId ( ) ; String expression = "" + hashId + "" + valueId + "" ; try { IRubyVariable rubyVariable = var . getStackFrame ( ) . getRubyDebuggerProxy ( ) . readInspectExpression ( var . getStackFrame ( ) , expression ) ; showExpressionView ( ) ; DebugPlugin . getDefault ( ) . getExpressionManager ( ) . addExpression ( new RubyExpression ( "" , rubyVariable ) ) ; } catch ( RubyProcessingException e ) { MessageDialog . openInformation ( page . getActivePart ( ) . getSite ( ) . getShell ( ) , e . getRubyExceptionType ( ) , "" + expression + "" + e . getMessage ( ) ) ; } } } ) ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . debug . ui . IDebugView ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . StructuredViewer ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . viewers . ViewerFilter ; import org . eclipse . swt . widgets . Event ; import org . eclipse . ui . IActionDelegate2 ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . texteditor . IUpdate ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public abstract class VariableFilterAction extends ViewerFilter implements IViewActionDelegate , IActionDelegate2 , IUpdate { private boolean fValue ; private IViewPart fView ; private IAction fAction ; public VariableFilterAction ( ) { super ( ) ; } public void init ( IViewPart view ) { fView = view ; setValue ( getPreferenceValue ( view ) ) ; fAction . setChecked ( getValue ( ) ) ; run ( fAction ) ; IDebugView debugView = ( IDebugView ) view . getAdapter ( IDebugView . class ) ; if ( debugView != null ) { debugView . add ( this ) ; } } public void init ( IAction action ) { fAction = action ; } public void dispose ( ) { } public void runWithEvent ( IAction action , Event event ) { run ( action ) ; } public void run ( IAction action ) { setValue ( action . isChecked ( ) ) ; StructuredViewer viewer = getStructuredViewer ( ) ; ViewerFilter [ ] filters = viewer . getFilters ( ) ; ViewerFilter filter = null ; for ( int i = ; i < filters . length ; i ++ ) { if ( filters [ i ] == this ) { filter = filters [ i ] ; break ; } } if ( filter == null ) { viewer . addFilter ( this ) ; } viewer . refresh ( ) ; IPreferenceStore store = getPreferenceStore ( ) ; String key = getView ( ) . getSite ( ) . getId ( ) + "" + getPreferenceKey ( ) ; store . setValue ( key , getValue ( ) ) ; RdtDebugUiPlugin . getDefault ( ) . savePluginPreferences ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { } protected IPreferenceStore getPreferenceStore ( ) { return RdtDebugUiPlugin . getDefault ( ) . getPreferenceStore ( ) ; } protected boolean getPreferenceValue ( IViewPart part ) { String baseKey = getPreferenceKey ( ) ; String viewKey = part . getSite ( ) . getId ( ) ; String compositeKey = viewKey + "" + baseKey ; IPreferenceStore store = getPreferenceStore ( ) ; boolean value = false ; if ( store . contains ( compositeKey ) ) { value = store . getBoolean ( compositeKey ) ; } else { value = store . getBoolean ( baseKey ) ; } return value ; } protected abstract String getPreferenceKey ( ) ; protected void setValue ( boolean value ) { fValue = value ; } protected boolean getValue ( ) { return fValue ; } protected IViewPart getView ( ) { return fView ; } protected StructuredViewer getStructuredViewer ( ) { IDebugView view = ( IDebugView ) getView ( ) . getAdapter ( IDebugView . class ) ; if ( view != null ) { Viewer viewer = view . getViewer ( ) ; if ( viewer instanceof StructuredViewer ) { return ( StructuredViewer ) viewer ; } } return null ; } public void update ( ) { fAction . setChecked ( getValue ( ) ) ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . internal . debug . ui . evaluation . EvaluationExpression ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class ExpressionInspectAction extends Action { private EvaluationExpression expression ; private ISelection selection ; public ExpressionInspectAction ( EvaluationExpression expression , ISelection selection ) { this . expression = expression ; this . setText ( expression . getName ( ) ) ; this . selection = selection ; } public void run ( ) { if ( ! ( selection instanceof TextSelection ) ) { return ; } String replacementValue = ( ( TextSelection ) selection ) . getText ( ) ; if ( replacementValue == null || replacementValue . length ( ) == ) { replacementValue = "" ; } final String evaluationText = expression . substitute ( replacementValue ) ; ITextSelection textSelection = new ITextSelection ( ) { public int getOffset ( ) { return ; } public int getLength ( ) { return ; } public int getStartLine ( ) { return ; } public int getEndLine ( ) { return ; } public String getText ( ) { return evaluationText ; } public boolean isEmpty ( ) { return false ; } } ; InspectAction inspectAction = new InspectAction ( ) ; inspectAction . selectionChanged ( null , textSelection ) ; inspectAction . setActiveEditor ( this , ( IEditorPart ) RubyPlugin . getActivePage ( ) . getActivePart ( ) ) ; inspectAction . run ( this ) ; super . run ( ) ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . jface . viewers . Viewer ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; public class ShowConstantsAction extends VariableFilterAction { protected String getPreferenceKey ( ) { return RdtDebugUiConstants . SHOW_CONSTANTS_PREFERENCE ; } public boolean select ( Viewer viewer , Object parentElement , Object element ) { if ( element instanceof IRubyVariable ) { IRubyVariable variable = ( IRubyVariable ) element ; if ( ! getValue ( ) ) { return ! variable . isConstant ( ) ; } } return true ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . model . IValue ; import org . eclipse . debug . core . model . IVariable ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; import org . rubypeople . rdt . debug . core . model . IRubyValue ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . debug . ui . display . IDataDisplay ; public class ExecuteAction extends EvaluateAction { protected void displayResult ( final IEvaluationResult result ) { if ( result . hasErrors ( ) ) { final Display display = RdtDebugUiPlugin . getStandardDisplay ( ) ; display . asyncExec ( new Runnable ( ) { public void run ( ) { if ( display . isDisposed ( ) ) { return ; } reportErrors ( result ) ; evaluationCleanup ( ) ; } } ) ; } else { final Display display = RdtDebugUiPlugin . getStandardDisplay ( ) ; display . asyncExec ( new Runnable ( ) { public void run ( ) { if ( display . isDisposed ( ) ) { return ; } IValue value = result . getValue ( ) ; IDataDisplay dataDisplay = getDirectDataDisplay ( ) ; if ( dataDisplay != null ) { try { dataDisplay . displayExpressionValue ( valueToCode ( value ) ) ; } catch ( DebugException e ) { RdtDebugUiPlugin . log ( e ) ; } } evaluationCleanup ( ) ; } } ) ; } } public static String valueToCode ( IValue value ) throws DebugException { String string = value . getValueString ( ) ; if ( value instanceof IRubyValue ) { IRubyValue rubyValue = ( IRubyValue ) value ; if ( value . getReferenceTypeName ( ) . equals ( "" ) ) { StringBuffer buffer = new StringBuffer ( "" ) ; IVariable [ ] vars = rubyValue . getVariables ( ) ; for ( int i = ; i < vars . length ; i ++ ) { buffer . append ( vars [ i ] . getValue ( ) . getValueString ( ) ) ; if ( i < vars . length - ) buffer . append ( "" ) ; } buffer . append ( "" ) ; string = buffer . toString ( ) ; } else if ( value . getReferenceTypeName ( ) . equals ( "" ) ) { StringBuffer buffer = new StringBuffer ( "" ) ; IVariable [ ] vars = rubyValue . getVariables ( ) ; for ( int i = ; i < vars . length ; i ++ ) { buffer . append ( vars [ i ] ) ; if ( i < vars . length - ) buffer . append ( "" ) ; } buffer . append ( "" ) ; string = buffer . toString ( ) ; } } return "" + string ; } protected IDataDisplay getDataDisplay ( ) { return super . getDirectDataDisplay ( ) ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . IJobChangeEvent ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . core . runtime . jobs . JobChangeAdapter ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . debug . ui . IDebugView ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IEditorActionDelegate ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; import org . rubypeople . rdt . internal . debug . core . model . RubyExpression ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; public class InspectAction extends AbstractInspectAction implements IViewActionDelegate , IEditorActionDelegate { private IRubyVariable inspectResult ; protected IRubyStackFrame getRubyStackFrame ( ) { IViewPart part = page . findView ( IDebugUIConstants . ID_DEBUG_VIEW ) ; if ( part == null ) { return null ; } IDebugView launchView = ( IDebugView ) part ; StructuredSelection selected = ( StructuredSelection ) launchView . getViewer ( ) . getSelection ( ) ; if ( selected . isEmpty ( ) ) { return null ; } if ( ! ( selected . getFirstElement ( ) instanceof IRubyStackFrame ) ) { return null ; } return ( IRubyStackFrame ) selected . getFirstElement ( ) ; } public void run ( IAction action ) { final IRubyStackFrame stackFrame = this . getRubyStackFrame ( ) ; if ( stackFrame == null ) { MessageDialog . openInformation ( page . getActivePart ( ) . getSite ( ) . getShell ( ) , "" , "" ) ; return ; } if ( ! ( selection instanceof ITextSelection ) ) { return ; } final String selectedText = ( ( ITextSelection ) selection ) . getText ( ) . replace ( '' , '' ) . replace ( '' , '' ) ; String jobName = "" + ( selectedText . length ( ) < ? selectedText : selectedText . substring ( , ) + "" ) ; Job job = new Job ( jobName ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { monitor . beginTask ( "" , IProgressMonitor . UNKNOWN ) ; IStatus result = null ; try { inspectResult = stackFrame . getRubyDebuggerProxy ( ) . readInspectExpression ( stackFrame , selectedText ) ; result = Status . OK_STATUS ; } catch ( RubyProcessingException e ) { String message = e . getRubyExceptionType ( ) + "" + selectedText + "" + e . getMessage ( ) ; result = new Status ( IStatus . ERROR , RdtDebugCorePlugin . PLUGIN_ID , IStatus . ERROR , message , e ) ; } return result ; } } ; job . addJobChangeListener ( new JobChangeAdapter ( ) { public void done ( final IJobChangeEvent event ) { Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { if ( event . getResult ( ) . isOK ( ) ) { showExpressionView ( ) ; DebugPlugin . getDefault ( ) . getExpressionManager ( ) . addExpression ( new RubyExpression ( selectedText , inspectResult ) ) ; } } } ) ; } } ) ; job . setPriority ( Job . SHORT ) ; job . schedule ( ) ; } public void setActiveEditor ( IAction action , IEditorPart targetEditor ) { if ( targetEditor == null || targetEditor . getEditorSite ( ) == null ) { this . page = null ; } else { this . page = targetEditor . getEditorSite ( ) . getPage ( ) ; } } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . osgi . util . NLS ; public class ActionMessages extends NLS { private static final String BUNDLE_NAME = "" ; public static String Evaluate_error_message_direct_exception ; public static String Evaluate_error_message_exception_pattern ; public static String Evaluate_error_message_src_context ; public static String Evaluate_error_message_stack_frame_context ; public static String Evaluate_error_message_wrapped_exception ; public static String Evaluate_error_problem_append_pattern ; public static String Evaluate_error_title_eval_problems ; public static String EvaluateAction_Cannot_open_Display_view ; public static String EvaluateAction__evaluation_failed__1 ; public static String EvaluateAction__evaluation_failed__Reason ; public static String EvaluateAction_Thread_not_suspended___unable_to_perform_evaluation__1 ; public static String EvaluateAction_Cannot_perform_nested_evaluations__1 ; static { NLS . initializeMessages ( BUNDLE_NAME , ActionMessages . class ) ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . PartInitException ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public class AbstractInspectAction { protected IWorkbenchPage page ; public void init ( IViewPart view ) { page = view . getSite ( ) . getPage ( ) ; } protected void showExpressionView ( ) { IViewPart part = page . findView ( IDebugUIConstants . ID_EXPRESSION_VIEW ) ; if ( part == null ) { try { page . showView ( IDebugUIConstants . ID_EXPRESSION_VIEW ) ; } catch ( PartInitException e ) { RdtDebugUiPlugin . log ( e ) ; } } else { page . bringToTop ( part ) ; } } protected ISelection selection ; public void selectionChanged ( IAction action , ISelection selection ) { this . selection = selection ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import org . jruby . ast . DefnNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; public class ValidBreakpointLocationLocator extends InOrderVisitor { public static final int LOCATION_NOT_FOUND = ; public static final int LOCATION_LINE = ; public static final int LOCATION_METHOD = ; public static final int LOCATION_FIELD = ; private RootNode fCompilationUnit ; private int fLineNumber ; private boolean fBestMatch ; private int fLocationType ; private boolean fLocationFound ; private int fLineLocation ; public ValidBreakpointLocationLocator ( RootNode compilationUnit , int lineNumber , boolean bestMatch ) { fCompilationUnit = compilationUnit ; fLineNumber = lineNumber ; fBestMatch = bestMatch ; fLocationFound = false ; } public int getLocationType ( ) { return fLocationType ; } @ Override public Object visitDefnNode ( DefnNode node ) { if ( visit ( node , false ) ) { if ( fBestMatch ) { int nameStartLine = node . getNameNode ( ) . getPosition ( ) . getStartLine ( ) ; if ( nameStartLine == fLineNumber ) { fLocationType = LOCATION_METHOD ; fLocationFound = true ; return false ; } } super . visitDefnNode ( node ) ; } return false ; } private boolean visit ( Node node , boolean isCode ) { if ( fLocationFound ) { return false ; } int startPosition = node . getPosition ( ) . getStartOffset ( ) ; int endLine = node . getPosition ( ) . getEndLine ( ) ; if ( endLine < fLineNumber ) { return false ; } int startLine = node . getPosition ( ) . getStartLine ( ) ; if ( isCode && ( fLineNumber <= startLine ) ) { fLineLocation = startLine ; fLocationFound = true ; fLocationType = LOCATION_LINE ; return false ; } return true ; } } package org . rubypeople . rdt . internal . debug . ui . actions ; import java . lang . reflect . InvocationTargetException ; import java . text . MessageFormat ; import java . util . Iterator ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . ISourceLocator ; import org . eclipse . debug . core . model . IStackFrame ; import org . eclipse . debug . core . model . IThread ; import org . eclipse . debug . core . model . IValue ; import org . eclipse . debug . ui . DebugUITools ; import org . eclipse . debug . ui . IDebugModelPresentation ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . debug . ui . IDebugView ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . Region ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . graphics . GC ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IEditorActionDelegate ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IPartListener ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . debug . core . model . IRubyValue ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . debug . ui . display . IDataDisplay ; import org . rubypeople . rdt . internal . debug . ui . display . RubyInspectExpression ; import org . rubypeople . rdt . internal . ui . text . RubyWordFinder ; public abstract class EvaluateAction implements IWorkbenchWindowActionDelegate , IObjectActionDelegate , IEditorActionDelegate , IPartListener , IViewActionDelegate { private IAction fAction ; private IWorkbenchPart fTargetPart ; private IWorkbenchWindow fWindow ; private Object fSelection ; private IRegion fRegion ; private boolean fEvaluating ; private IWorkbenchPart fNewTargetPart = null ; private IDebugModelPresentation fPresentation ; public EvaluateAction ( ) { super ( ) ; } protected IRubyValue getObjectContext ( ) { IWorkbenchPage page = RdtDebugUiPlugin . getActivePage ( ) ; if ( page == null ) return null ; IWorkbenchPart activePart = page . getActivePart ( ) ; if ( activePart == null ) return null ; IDebugView a = ( IDebugView ) activePart . getAdapter ( IDebugView . class ) ; if ( a == null || a . getViewer ( ) == null ) return null ; ISelection s = a . getViewer ( ) . getSelection ( ) ; if ( ! ( s instanceof IStructuredSelection ) ) return null ; IStructuredSelection structuredSelection = ( IStructuredSelection ) s ; if ( structuredSelection . size ( ) != ) return null ; Object selection = structuredSelection . getFirstElement ( ) ; if ( selection instanceof IRubyVariable ) { IRubyVariable var = ( IRubyVariable ) selection ; try { if ( ! var . getName ( ) . equals ( "" ) ) { IValue value = var . getValue ( ) ; if ( value instanceof IRubyValue ) { return ( IRubyValue ) value ; } } } catch ( DebugException e ) { RdtDebugUiPlugin . log ( e ) ; } } else if ( selection instanceof RubyInspectExpression ) { IValue value = ( ( RubyInspectExpression ) selection ) . getValue ( ) ; if ( value instanceof IRubyValue ) { return ( IRubyValue ) value ; } } return null ; } protected IRubyStackFrame getStackFrameContext ( ) { try { IWorkbenchPart part = getTargetPart ( ) ; if ( part == null ) { return RdtDebugUiPlugin . getEvaluationContextManager ( ) . getEvaluationContext ( getWindow ( ) ) ; } return RdtDebugUiPlugin . getEvaluationContextManager ( ) . getEvaluationContext ( part ) ; } catch ( Throwable e ) { RdtDebugUiPlugin . log ( e ) ; return null ; } } public void evaluationComplete ( final IEvaluationResult result ) { if ( RdtDebugUiPlugin . getDefault ( ) == null ) { return ; } final IValue value = result . getValue ( ) ; if ( result . hasErrors ( ) || value != null ) { final Display display = RdtDebugUiPlugin . getStandardDisplay ( ) ; if ( display . isDisposed ( ) ) { return ; } displayResult ( result ) ; } } protected void evaluationCleanup ( ) { setEvaluating ( false ) ; setTargetPart ( fNewTargetPart ) ; } abstract protected void displayResult ( IEvaluationResult result ) ; protected void run ( ) { final IRubyValue object = getObjectContext ( ) ; final IRubyStackFrame stackFrame = getStackFrameContext ( ) ; if ( stackFrame == null ) { reportError ( ActionMessages . Evaluate_error_message_stack_frame_context ) ; return ; } IThread thread = ( IThread ) stackFrame . getThread ( ) ; setNewTargetPart ( getTargetPart ( ) ) ; IRunnableWithProgress runnable = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { if ( stackFrame . isSuspended ( ) ) { Object selection = getSelectedObject ( ) ; if ( ! ( selection instanceof String ) ) { return ; } String expression = ( String ) selection ; setEvaluating ( true ) ; IEvaluationResult result = stackFrame . evaluate ( expression ) ; evaluationComplete ( result ) ; return ; } throw new InvocationTargetException ( null , ActionMessages . EvaluateAction_Thread_not_suspended___unable_to_perform_evaluation__1 ) ; } } ; IWorkbench workbench = RdtDebugUiPlugin . getDefault ( ) . getWorkbench ( ) ; try { workbench . getProgressService ( ) . busyCursorWhile ( runnable ) ; } catch ( InvocationTargetException e ) { evaluationCleanup ( ) ; String message = e . getMessage ( ) ; if ( message == null ) { message = e . getClass ( ) . getName ( ) ; if ( e . getCause ( ) != null ) { message = e . getCause ( ) . getClass ( ) . getName ( ) ; if ( e . getCause ( ) . getMessage ( ) != null ) { message = e . getCause ( ) . getMessage ( ) ; } } } reportError ( message ) ; } catch ( InterruptedException e ) { } } protected void update ( ) { IAction action = getAction ( ) ; if ( action != null ) { resolveSelectedObject ( ) ; } } protected void resolveSelectedObject ( ) { Object selectedObject = null ; fRegion = null ; ISelection selection = getTargetSelection ( ) ; if ( selection instanceof ITextSelection ) { ITextSelection ts = ( ITextSelection ) selection ; String text = ts . getText ( ) ; if ( textHasContent ( text ) ) { selectedObject = text ; fRegion = new Region ( ts . getOffset ( ) , ts . getLength ( ) ) ; } else if ( getTargetPart ( ) instanceof IEditorPart ) { IEditorPart editor = ( IEditorPart ) getTargetPart ( ) ; if ( editor instanceof ITextEditor ) { selectedObject = resolveSelectedObjectUsingToken ( selectedObject , ts , editor ) ; } } } else if ( selection instanceof IStructuredSelection ) { if ( ! selection . isEmpty ( ) ) { if ( getTargetPart ( ) . getSite ( ) . getId ( ) . equals ( IDebugUIConstants . ID_DEBUG_VIEW ) ) { IEditorPart editor = getTargetPart ( ) . getSite ( ) . getPage ( ) . getActiveEditor ( ) ; setTargetPart ( editor ) ; selection = getTargetSelection ( ) ; if ( selection instanceof ITextSelection ) { ITextSelection ts = ( ITextSelection ) selection ; String text = ts . getText ( ) ; if ( textHasContent ( text ) ) { selectedObject = text ; } else if ( editor instanceof ITextEditor ) { selectedObject = resolveSelectedObjectUsingToken ( selectedObject , ts , editor ) ; } } } else { IStructuredSelection ss = ( IStructuredSelection ) selection ; Iterator elements = ss . iterator ( ) ; while ( elements . hasNext ( ) ) { if ( ! ( elements . next ( ) instanceof IRubyVariable ) ) { setSelectedObject ( null ) ; return ; } } selectedObject = ss ; } } } setSelectedObject ( selectedObject ) ; } private Object resolveSelectedObjectUsingToken ( Object selectedObject , ITextSelection ts , IEditorPart editor ) { ITextEditor textEditor = ( ITextEditor ) editor ; IDocument doc = textEditor . getDocumentProvider ( ) . getDocument ( editor . getEditorInput ( ) ) ; fRegion = RubyWordFinder . findWord ( doc , ts . getOffset ( ) ) ; if ( fRegion != null ) { try { selectedObject = doc . get ( fRegion . getOffset ( ) , fRegion . getLength ( ) ) ; } catch ( BadLocationException e ) { } } return selectedObject ; } protected ISelection getTargetSelection ( ) { IWorkbenchPart part = getTargetPart ( ) ; if ( part != null ) { ISelectionProvider provider = part . getSite ( ) . getSelectionProvider ( ) ; if ( provider != null ) { return provider . getSelection ( ) ; } } return null ; } protected boolean compareToEditorInput ( IStackFrame stackFrame ) { ILaunch launch = stackFrame . getLaunch ( ) ; if ( launch == null ) { return false ; } ISourceLocator locator = launch . getSourceLocator ( ) ; if ( locator == null ) { return false ; } Object sourceElement = locator . getSourceElement ( stackFrame ) ; if ( sourceElement == null ) { return false ; } IEditorInput sfEditorInput = getDebugModelPresentation ( ) . getEditorInput ( sourceElement ) ; if ( getTargetPart ( ) instanceof IEditorPart ) { return ( ( IEditorPart ) getTargetPart ( ) ) . getEditorInput ( ) . equals ( sfEditorInput ) ; } return false ; } protected Shell getShell ( ) { if ( getTargetPart ( ) != null ) { return getTargetPart ( ) . getSite ( ) . getShell ( ) ; } return RdtDebugUiPlugin . getActiveWorkbenchShell ( ) ; } protected IDataDisplay getDataDisplay ( ) { IDataDisplay display = getDirectDataDisplay ( ) ; if ( display != null ) { return display ; } IWorkbenchPage page = RdtDebugUiPlugin . getActivePage ( ) ; if ( page != null ) { IWorkbenchPart activePart = page . getActivePart ( ) ; if ( activePart != null ) { IViewPart view = page . findView ( RdtDebugUiConstants . ID_DISPLAY_VIEW ) ; if ( view == null ) { try { view = page . showView ( RdtDebugUiConstants . ID_DISPLAY_VIEW ) ; } catch ( PartInitException e ) { RdtDebugUiPlugin . errorDialog ( ActionMessages . EvaluateAction_Cannot_open_Display_view , e ) ; } finally { page . activate ( activePart ) ; } } if ( view != null ) { page . bringToTop ( view ) ; return ( IDataDisplay ) view . getAdapter ( IDataDisplay . class ) ; } } } return null ; } protected IDataDisplay getDirectDataDisplay ( ) { IWorkbenchPart part = getTargetPart ( ) ; if ( part != null ) { IDataDisplay display = ( IDataDisplay ) part . getAdapter ( IDataDisplay . class ) ; if ( display != null ) { IWorkbenchPage page = RdtDebugUiPlugin . getActivePage ( ) ; if ( page != null ) { IWorkbenchPart activePart = page . getActivePart ( ) ; if ( activePart != null ) { if ( activePart != part ) { page . activate ( part ) ; } } } return display ; } } IWorkbenchPage page = RdtDebugUiPlugin . getActivePage ( ) ; if ( page != null ) { IWorkbenchPart activePart = page . getActivePart ( ) ; if ( activePart != null ) { IDataDisplay display = ( IDataDisplay ) activePart . getAdapter ( IDataDisplay . class ) ; if ( display != null ) { return display ; } } } return null ; } protected boolean textHasContent ( String text ) { if ( text != null ) { int length = text . length ( ) ; if ( length > ) { for ( int i = ; i < length ; i ++ ) { if ( Character . isLetterOrDigit ( text . charAt ( i ) ) ) { return true ; } } } } return false ; } protected void reportErrors ( IEvaluationResult result ) { String message = getErrorMessage ( result ) ; reportError ( message ) ; } protected void reportError ( String message ) { IDataDisplay dataDisplay = getDirectDataDisplay ( ) ; if ( dataDisplay != null ) { if ( message . length ( ) != ) { dataDisplay . displayExpressionValue ( MessageFormat . format ( ActionMessages . EvaluateAction__evaluation_failed__Reason , new String [ ] { format ( message ) } ) ) ; } else { dataDisplay . displayExpressionValue ( ActionMessages . EvaluateAction__evaluation_failed__1 ) ; } } else { Status status = new Status ( IStatus . ERROR , RdtDebugUiPlugin . getUniqueIdentifier ( ) , IStatus . ERROR , message , null ) ; ErrorDialog . openError ( getShell ( ) , ActionMessages . Evaluate_error_title_eval_problems , null , status ) ; } } private String format ( String message ) { StringBuffer result = new StringBuffer ( ) ; int index = , pos ; while ( ( pos = message . indexOf ( '' , index ) ) != - ) { result . append ( "" ) . append ( message . substring ( index , index = pos + ) ) ; } if ( index < message . length ( ) ) { result . append ( "" ) . append ( message . substring ( index ) ) ; } return result . toString ( ) ; } public static String getExceptionMessage ( Throwable exception ) { if ( exception instanceof CoreException ) { CoreException ce = ( CoreException ) exception ; Throwable throwable = ce . getStatus ( ) . getException ( ) ; if ( throwable instanceof CoreException ) { return getExceptionMessage ( throwable ) ; } return ce . getStatus ( ) . getMessage ( ) ; } String message = MessageFormat . format ( ActionMessages . Evaluate_error_message_direct_exception , new Object [ ] { exception . getClass ( ) } ) ; if ( exception . getMessage ( ) != null ) { message = MessageFormat . format ( ActionMessages . Evaluate_error_message_exception_pattern , new Object [ ] { message , exception . getMessage ( ) } ) ; } return message ; } protected String getErrorMessage ( IEvaluationResult result ) { String [ ] errors = result . getErrorMessages ( ) ; if ( errors . length == ) { return getExceptionMessage ( result . getException ( ) ) ; } return getErrorMessage ( errors ) ; } protected String getErrorMessage ( String [ ] errors ) { String message = "" ; for ( int i = ; i < errors . length ; i ++ ) { String msg = errors [ i ] ; if ( i == ) { message = msg ; } else { message = MessageFormat . format ( ActionMessages . Evaluate_error_problem_append_pattern , new Object [ ] { message , msg } ) ; } } return message ; } public void run ( IAction action ) { update ( ) ; run ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { setAction ( action ) ; } public void dispose ( ) { disposeDebugModelPresentation ( ) ; IWorkbenchWindow win = getWindow ( ) ; if ( win != null ) { win . getPartService ( ) . removePartListener ( this ) ; } } public void init ( IWorkbenchWindow window ) { setWindow ( window ) ; IWorkbenchPage page = window . getActivePage ( ) ; if ( page != null ) { setTargetPart ( page . getActivePart ( ) ) ; } window . getPartService ( ) . addPartListener ( this ) ; update ( ) ; } protected IAction getAction ( ) { return fAction ; } protected void setAction ( IAction action ) { fAction = action ; } protected IDebugModelPresentation getDebugModelPresentation ( ) { if ( fPresentation == null ) { fPresentation = DebugUITools . newDebugModelPresentation ( RdtDebugCorePlugin . getPluginIdentifier ( ) ) ; } return fPresentation ; } protected void disposeDebugModelPresentation ( ) { if ( fPresentation != null ) { fPresentation . dispose ( ) ; } } public void setActiveEditor ( IAction action , IEditorPart targetEditor ) { setAction ( action ) ; setTargetPart ( targetEditor ) ; } public void partActivated ( IWorkbenchPart part ) { setTargetPart ( part ) ; } public void partBroughtToTop ( IWorkbenchPart part ) { } public void partClosed ( IWorkbenchPart part ) { if ( part == getTargetPart ( ) ) { setTargetPart ( null ) ; } if ( part == getNewTargetPart ( ) ) { setNewTargetPart ( null ) ; } } public void partDeactivated ( IWorkbenchPart part ) { } public void partOpened ( IWorkbenchPart part ) { } public void init ( IViewPart view ) { setTargetPart ( view ) ; } protected IWorkbenchPart getTargetPart ( ) { return fTargetPart ; } protected void setTargetPart ( IWorkbenchPart part ) { if ( isEvaluating ( ) ) { setNewTargetPart ( part ) ; } else { fTargetPart = part ; } } protected IWorkbenchWindow getWindow ( ) { return fWindow ; } protected void setWindow ( IWorkbenchWindow window ) { fWindow = window ; } public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { setAction ( action ) ; setTargetPart ( targetPart ) ; update ( ) ; } protected Object getSelectedObject ( ) { return fSelection ; } protected void setSelectedObject ( Object selection ) { fSelection = selection ; } protected IWorkbenchPart getNewTargetPart ( ) { return fNewTargetPart ; } protected void setNewTargetPart ( IWorkbenchPart newTargetPart ) { fNewTargetPart = newTargetPart ; } protected boolean isEvaluating ( ) { return fEvaluating ; } protected void setEvaluating ( boolean evaluating ) { fEvaluating = evaluating ; } protected IRegion getRegion ( ) { return fRegion ; } public static Point getPopupAnchor ( ITextViewer viewer ) { StyledText textWidget = viewer . getTextWidget ( ) ; Point docRange = textWidget . getSelectionRange ( ) ; int midOffset = docRange . x + ( docRange . y / ) ; Point point = textWidget . getLocationAtOffset ( midOffset ) ; point = textWidget . toDisplay ( point ) ; GC gc = new GC ( textWidget ) ; gc . setFont ( textWidget . getFont ( ) ) ; int height = gc . getFontMetrics ( ) . getHeight ( ) ; gc . dispose ( ) ; point . y += height ; return point ; } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . QualifiedName ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . IWorkbenchPropertyPage ; import org . eclipse . ui . dialogs . PropertyPage ; public class RubyExecutionArgumentsPage extends PropertyPage implements IWorkbenchPropertyPage { protected Text interpreterArgumentsText , programArgumentsText ; public RubyExecutionArgumentsPage ( ) { } protected Control createContents ( Composite parent ) { noDefaultAndApplyButton ( ) ; Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_interpreter_args_box_title ) ; new Label ( composite , SWT . NONE ) . setText ( "" ) ; interpreterArgumentsText = new Text ( composite , SWT . BORDER ) ; GridData interpreterArgumentsData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; interpreterArgumentsData . horizontalSpan = ; interpreterArgumentsText . setLayoutData ( interpreterArgumentsData ) ; interpreterArgumentsText . setText ( getArgument ( "" ) ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_program_args_box_title ) ; programArgumentsText = new Text ( composite , SWT . BORDER ) ; GridData programArgumentsData = new GridData ( GridData . HORIZONTAL_ALIGN_FILL ) ; programArgumentsData . horizontalSpan = ; programArgumentsText . setLayoutData ( programArgumentsData ) ; programArgumentsText . setText ( getArgument ( "" ) ) ; return composite ; } protected String getArgument ( String name ) { String argumentValue = null ; try { argumentValue = ( ( IFile ) getElement ( ) ) . getPersistentProperty ( new QualifiedName ( "" , name ) ) ; } catch ( CoreException e ) { } return argumentValue != null ? argumentValue : "" ; } public boolean performOk ( ) { IFile rubyFile = ( IFile ) getElement ( ) ; try { rubyFile . setPersistentProperty ( new QualifiedName ( "" , "" ) , interpreterArgumentsText . getText ( ) ) ; rubyFile . setPersistentProperty ( new QualifiedName ( "" , "" ) , programArgumentsText . getText ( ) ) ; } catch ( CoreException e ) { RdtDebugUiPlugin . log ( e ) ; return false ; } return true ; } } package org . rubypeople . rdt . internal . debug . ui ; import java . io . File ; import java . util . Hashtable ; import java . util . Map ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . model . IBreakpoint ; import org . eclipse . debug . core . model . IValue ; import org . eclipse . debug . internal . ui . DebugUIPlugin ; import org . eclipse . debug . ui . DebugUITools ; import org . eclipse . debug . ui . IDebugModelPresentation ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . debug . ui . IValueDetailListener ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IFileEditorInput ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . ide . IDE ; import org . eclipse . ui . part . FileEditorInput ; import org . rubypeople . rdt . debug . core . IRubyBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyLineBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyMethodBreakpoint ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . debug . core . model . IRubyThread ; import org . rubypeople . rdt . debug . core . model . IRubyValue ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; import org . rubypeople . rdt . internal . ui . rubyeditor . ExternalRubyFileEditorInput ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; public class DebugModelPresentation extends LabelProvider implements IDebugModelPresentation { private static Map < ImageDescriptor , Image > imageCache = new Hashtable < ImageDescriptor , Image > ( ) ; private static ImageDescriptorRegistry fgDebugImageRegistry ; private Boolean isShowTypes ; public String getText ( Object item ) { if ( item instanceof IRubyMethodBreakpoint ) { IRubyMethodBreakpoint breakpoint = ( IRubyMethodBreakpoint ) item ; try { return breakpoint . getTypeName ( ) + "" + breakpoint . getMethodName ( ) ; } catch ( CoreException e ) { DebugUIPlugin . log ( e ) ; return "" ; } } if ( item instanceof IRubyLineBreakpoint ) { IRubyLineBreakpoint breakpoint = ( IRubyLineBreakpoint ) item ; try { return breakpoint . getFileName ( ) + "" + breakpoint . getLineNumber ( ) ; } catch ( CoreException e ) { DebugUIPlugin . log ( e ) ; return "" ; } } if ( item instanceof IRubyExceptionBreakpoint ) { IRubyExceptionBreakpoint exceptionBreakpoint = ( IRubyExceptionBreakpoint ) item ; try { String exceptionType = exceptionBreakpoint . getTypeName ( ) ; if ( exceptionType == null || exceptionType . length ( ) == ) { return "" ; } else { return "" + exceptionType ; } } catch ( CoreException e ) { RdtDebugUiPlugin . log ( e ) ; return "" ; } } if ( item instanceof IRubyVariable ) { IRubyVariable variable = ( IRubyVariable ) item ; try { if ( isShowTypes == Boolean . TRUE ) { return ( ( IRubyValue ) variable . getValue ( ) ) . getReferenceTypeName ( ) + "" + variable . toString ( ) ; } } catch ( DebugException e ) { RdtDebugUiPlugin . log ( e ) ; } return variable . toString ( ) ; } return DebugUIPlugin . getDefaultLabelProvider ( ) . getText ( item ) ; } protected IBreakpoint getBreakpoint ( IMarker marker ) { return DebugPlugin . getDefault ( ) . getBreakpointManager ( ) . getBreakpoint ( marker ) ; } public void computeDetail ( IValue value , IValueDetailListener listener ) { String string = "" ; try { IRubyStackFrame frame = RdtDebugUiPlugin . getEvaluationContextManager ( ) . getEvaluationContext ( ( IWorkbenchWindow ) null ) ; IRubyValue rubyValue = ( IRubyValue ) value ; IRubyVariable var = rubyValue . getOwner ( ) ; String snippet = var . getName ( ) + "" ; IEvaluationResult result = frame . evaluate ( snippet ) ; try { if ( result != null && result . getValue ( ) != null ) string = result . getValue ( ) . getValueString ( ) ; if ( string != null && string . startsWith ( "" ) && string . endsWith ( "" ) ) { string = string . substring ( , string . length ( ) - ) ; } } catch ( DebugException e ) { } } catch ( Throwable t ) { } listener . detailComputed ( value , string ) ; } public void setAttribute ( String attribute , Object value ) { if ( attribute . equals ( IDebugModelPresentation . DISPLAY_VARIABLE_TYPE_NAMES ) ) { this . isShowTypes = ( Boolean ) value ; } } public String getEditorId ( IEditorInput input , Object element ) { if ( input instanceof ExternalRubyFileEditorInput ) { return RubyUI . ID_EXTERNAL_EDITOR ; } else if ( input instanceof IFileEditorInput ) { IFileEditorInput fileInput = ( IFileEditorInput ) input ; return IDE . getDefaultEditor ( fileInput . getFile ( ) ) . getId ( ) ; } return null ; } public IEditorInput getEditorInput ( Object element ) { if ( element instanceof IRubyLineBreakpoint ) { IRubyLineBreakpoint bp = ( IRubyLineBreakpoint ) element ; IResource resource = bp . getMarker ( ) . getResource ( ) ; if ( resource . equals ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ) { try { String filename = bp . getFileName ( ) ; if ( filename == null ) return null ; return new ExternalRubyFileEditorInput ( new File ( filename ) ) ; } catch ( CoreException e ) { RdtDebugUiPlugin . log ( e ) ; } } else { if ( resource instanceof IFile ) return new FileEditorInput ( ( IFile ) resource ) ; } } return null ; } private Image getImage ( ImageDescriptor imageDescriptor ) { Image image = ( Image ) imageCache . get ( imageDescriptor ) ; if ( image == null ) { image = imageDescriptor . createImage ( ) ; imageCache . put ( imageDescriptor , image ) ; } return image ; } public Image getImage ( Object item ) { try { ImageDescriptor descriptor ; if ( item instanceof IMarker ) { IBreakpoint bp = getBreakpoint ( ( IMarker ) item ) ; if ( bp != null && bp instanceof IRubyBreakpoint ) { return getBreakpointImage ( ( IRubyBreakpoint ) bp ) ; } } if ( item instanceof IRubyBreakpoint ) { return getBreakpointImage ( ( IRubyBreakpoint ) item ) ; } else if ( item instanceof IRubyThread ) { IRubyThread thread = ( IRubyThread ) item ; if ( thread . isSuspended ( ) ) { descriptor = DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_OBJS_THREAD_SUSPENDED ) ; } else if ( thread . isTerminated ( ) ) { descriptor = DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_OBJS_THREAD_TERMINATED ) ; } else { descriptor = DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_OBJS_THREAD_RUNNING ) ; } } else { descriptor = DebugUITools . getDefaultImageDescriptor ( item ) ; } return getImage ( descriptor ) ; } catch ( Exception e ) { } return null ; } protected Image getBreakpointImage ( IRubyBreakpoint breakpoint ) throws CoreException { if ( breakpoint instanceof IRubyExceptionBreakpoint ) { return getExceptionBreakpointImage ( ( IRubyExceptionBreakpoint ) breakpoint ) ; } return getRubyBreakpointImage ( breakpoint ) ; } protected Image getExceptionBreakpointImage ( IRubyExceptionBreakpoint exception ) throws CoreException { int flags = computeBreakpointAdornmentFlags ( exception ) ; RubyDebugImageDescriptor descriptor = null ; if ( ( flags & RubyDebugImageDescriptor . ENABLED ) == ) { descriptor = new RubyDebugImageDescriptor ( getImageDescriptor ( RubyDebugImages . IMG_OBJS_EXCEPTION_DISABLED ) , flags ) ; } else { descriptor = new RubyDebugImageDescriptor ( getImageDescriptor ( RubyDebugImages . IMG_OBJS_ERROR ) , flags ) ; } return getDebugImageRegistry ( ) . get ( descriptor ) ; } protected Image getRubyBreakpointImage ( IRubyBreakpoint breakpoint ) throws CoreException { if ( breakpoint instanceof IRubyMethodBreakpoint ) { IRubyMethodBreakpoint mBreakpoint = ( IRubyMethodBreakpoint ) breakpoint ; return getRubyMethodBreakpointImage ( mBreakpoint ) ; } else { int flags = computeBreakpointAdornmentFlags ( breakpoint ) ; RubyDebugImageDescriptor descriptor = null ; if ( breakpoint . isEnabled ( ) ) { descriptor = new RubyDebugImageDescriptor ( DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_OBJS_BREAKPOINT ) , flags ) ; } else { descriptor = new RubyDebugImageDescriptor ( DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_OBJS_BREAKPOINT_DISABLED ) , flags ) ; } return getDebugImageRegistry ( ) . get ( descriptor ) ; } } protected Image getRubyMethodBreakpointImage ( IRubyMethodBreakpoint mBreakpoint ) throws CoreException { int flags = computeBreakpointAdornmentFlags ( mBreakpoint ) ; RubyDebugImageDescriptor descriptor = null ; if ( mBreakpoint . isEnabled ( ) ) { descriptor = new RubyDebugImageDescriptor ( DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_OBJS_BREAKPOINT ) , flags ) ; } else { descriptor = new RubyDebugImageDescriptor ( DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_OBJS_BREAKPOINT_DISABLED ) , flags ) ; } return getDebugImageRegistry ( ) . get ( descriptor ) ; } protected static ImageDescriptorRegistry getDebugImageRegistry ( ) { if ( fgDebugImageRegistry == null ) { fgDebugImageRegistry = RdtDebugUiPlugin . getImageDescriptorRegistry ( ) ; } return fgDebugImageRegistry ; } private int computeBreakpointAdornmentFlags ( IRubyBreakpoint breakpoint ) { int flags = ; try { if ( breakpoint . isEnabled ( ) ) { flags |= RubyDebugImageDescriptor . ENABLED ; } if ( breakpoint . isInstalled ( ) ) { flags |= RubyDebugImageDescriptor . INSTALLED ; } if ( breakpoint instanceof IRubyLineBreakpoint ) { if ( ( ( IRubyLineBreakpoint ) breakpoint ) . isConditionEnabled ( ) ) { flags |= RubyDebugImageDescriptor . CONDITIONAL ; } if ( breakpoint instanceof IRubyMethodBreakpoint ) { IRubyMethodBreakpoint mBreakpoint = ( IRubyMethodBreakpoint ) breakpoint ; flags |= RubyDebugImageDescriptor . ENTRY ; } } else if ( breakpoint instanceof IRubyExceptionBreakpoint ) { IRubyExceptionBreakpoint eBreakpoint = ( IRubyExceptionBreakpoint ) breakpoint ; flags |= RubyDebugImageDescriptor . UNCAUGHT ; } } catch ( CoreException e ) { } return flags ; } private ImageDescriptor getImageDescriptor ( String key ) { return RubyDebugImages . getImageDescriptor ( key ) ; } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . jface . resource . CompositeImageDescriptor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . Point ; public class RDTImageDescriptor extends CompositeImageDescriptor { public final static int IS_OUT_OF_SYNCH = ; private Point fSize ; private ImageDescriptor fBaseImage ; private int fFlags ; public RDTImageDescriptor ( ImageDescriptor baseImage , int flags ) { setBaseImage ( baseImage ) ; setFlags ( flags ) ; } @ Override protected void drawCompositeImage ( int width , int height ) { ImageData bg = getBaseImage ( ) . getImageData ( ) ; if ( bg == null ) { bg = DEFAULT_IMAGE_DATA ; } drawImage ( bg , , ) ; drawOverlays ( ) ; } @ Override protected Point getSize ( ) { if ( fSize == null ) { ImageData data = getBaseImage ( ) . getImageData ( ) ; setSize ( new Point ( data . width , data . height ) ) ; } return fSize ; } protected void setSize ( Point size ) { fSize = size ; } protected ImageDescriptor getBaseImage ( ) { return fBaseImage ; } protected void setBaseImage ( ImageDescriptor baseImage ) { fBaseImage = baseImage ; } protected int getFlags ( ) { return fFlags ; } protected void setFlags ( int flags ) { fFlags = flags ; } protected void drawOverlays ( ) { int flags = getFlags ( ) ; int x = ; int y = ; ImageData data = null ; if ( ( flags & IS_OUT_OF_SYNCH ) != ) { x = getSize ( ) . x ; y = ; data = getImageData ( RubyDebugImages . IMG_OVR_OUT_OF_SYNCH ) ; x -= data . width ; drawImage ( data , x , y ) ; } } private ImageData getImageData ( String imageDescriptorKey ) { return RubyDebugImages . getImageDescriptor ( imageDescriptorKey ) . getImageData ( ) ; } } package org . rubypeople . rdt . internal . debug . ui ; import java . text . MessageFormat ; import java . util . MissingResourceException ; import java . util . ResourceBundle ; import org . eclipse . osgi . util . NLS ; public class RdtDebugUiMessages { private static final String BUNDLE_NAME = RdtDebugUiMessages . class . getName ( ) ; private RdtDebugUiMessages ( ) { } public static String LaunchConfigurationTab_RubyArguments_working_dir_error_message ; public static String LaunchConfigurationTab_RubyEntryPoint_invalidProjectSelectionMessage ; public static String LaunchConfigurationTab_RubyEntryPoint_invalidFileSelectionMessage ; public static String LaunchConfigurationTab_RubyEnvironment_interpreter_not_selected_error_message ; public static String RdtDebugUiPlugin_internalErrorOccurred ; public static String LaunchConfigurationTab_RubyArguments_interpreter_args_box_title ; public static String LaunchConfigurationTab_RubyArguments_program_args_box_title ; public static String ModifyCatchpointDialog_title ; public static String ModifyCatchpointDialog_message ; public static String Dialog_launchErrorTitle ; public static String Dialog_launchErrorMessage ; public static String LaunchConfigurationShortcut_Ruby_multipleConfigurationsError ; public static String Dialog_launchWithoutSelectedInterpreter_title ; public static String Dialog_launchWithoutSelectedInterpreter ; public static String LaunchConfigurationTab_RubyArguments_working_dir ; public static String LaunchConfigurationTab_RubyArguments_working_dir_browser_message ; public static String LaunchConfigurationTab_RubyArguments_working_dir_use_default_message ; public static String LaunchConfigurationTab_RubyArguments_name ; public static String LaunchConfigurationTab_RubyEntryPoint_projectLabel ; public static String LaunchConfigurationTab_RubyEntryPoint_projectSelectorMessage ; public static String LaunchConfigurationTab_RubyEntryPoint_fileLabel ; public static String LaunchConfigurationTab_RubyEntryPoint_fileSelectorMessage ; public static String LaunchConfigurationTab_RubyEntryPoint_name ; public static String LaunchConfigurationTab_RubyEnvironment_loadPathTab_label ; public static String LaunchConfigurationTab_RubyEnvironment_loadPathDefaultButton_label ; public static String LaunchConfigurationTab_RubyEnvironment_interpreterAddButton_label ; public static String LaunchConfigurationTab_RubyEnvironment_interpreterTab_label ; public static String LaunchConfigurationTab_RubyEnvironment_name ; public static String EditEvaluationExpression_name_label ; public static String EditEvaluationExpression_description_label ; public static String EditEvaluationExpression_expression_label ; public static String EvaluationExpressionsPreferencePage_description ; public static String EvaluationExpressionsPreferencePage_column_name ; public static String EvaluationExpressionsPreferencePage_column_description ; public static String EvaluationExpressionsPreferencePage_new ; public static String EvaluationExpressionsPreferencePage_edit ; public static String EvaluationExpressionsPreferencePage_remove ; public static String EvaluationExpressionsPreferencePage_import ; public static String EvaluationExpressionsPreferencePage_export ; public static String EditEvaluationExpressionDialog_add ; public static String EditEvaluationExpressionDialog_edit ; public static String EvaluationExpressionsPreferencePage_import_title ; public static String EvaluationExpressionsPreferencePage_importexport_extension ; public static String EvaluationExpressionsPreferencePage_export_title ; public static String EvaluationExpressionsPreferencePage_export_filename ; public static String EvaluationExpressionsPreferencePage_export_error_title ; public static String EvaluationExpressionsPreferencePage_export_error_hidden ; public static String EvaluationExpressionsPreferencePage_export_error_canNotWrite ; public static String EvaluationExpressionsPreferencePage_export_exists_title ; public static String EvaluationExpressionsPreferencePage_export_exists_message ; public static String EvaluationExpressionsPreferencePage_title ; public static String RubyInterpreterPreferencePage_addButton_label ; public static String RubyInterpreterPreferencePage_editButton_label ; public static String RubyInterpreterPreferencePage_removeButton_label ; public static String RubyInterpreterPreferencePage_rubyInterpreterTable_interpreterName ; public static String RubyInterpreterPreferencePage_rubyInterpreterTable_interpreterPath ; public static String RdtDebugUiPlugin_couldNotOpenFile ; public static String RubyInterpreterPreferencePage_rubyInterpreterTable_interpreterType ; public static String ToolChainNotFound_title ; public static String ToolChainNotFound_msg ; public static String ToolChainNotFound_msg_osx ; static { NLS . initializeMessages ( BUNDLE_NAME , RdtDebugUiMessages . class ) ; } public static String getFormattedString ( String key , Object arg ) { return MessageFormat . format ( key , new Object [ ] { arg } ) ; } private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle . getBundle ( BUNDLE_NAME ) ; public static String getString ( String key ) { try { return RESOURCE_BUNDLE . getString ( key ) ; } catch ( MissingResourceException e ) { return '' + key + '' ; } } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . internal . ui . DebugUIPlugin ; import org . eclipse . jface . dialogs . MessageDialog ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . internal . debug . core . model . IRubyDebugTarget ; public class CodeReloadJob extends Job { private String filename ; private IRubyDebugTarget debugTarget ; public CodeReloadJob ( IRubyDebugTarget debugTarget , String filename ) { super ( "" + filename ) ; this . filename = filename ; this . debugTarget = debugTarget ; } public IStatus run ( IProgressMonitor monitor ) { if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; final IStatus status = debugTarget . load ( filename ) ; if ( status == null ) return new Status ( Status . WARNING , RdtDebugCorePlugin . getPluginIdentifier ( ) , - , "" + filename , null ) ; if ( ! status . isOK ( ) ) { DebugUIPlugin . getStandardDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { MessageDialog . openInformation ( DebugUIPlugin . getStandardDisplay ( ) . getActiveShell ( ) , "" + filename , status . getMessage ( ) ) ; } } ) ; } return status ; } } package org . rubypeople . rdt . internal . debug . ui ; import java . net . URL ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . resource . ImageRegistry ; import org . osgi . framework . Bundle ; public class RubyDebugImages { private static String ICONS_PATH = "" ; private static ImageRegistry fgImageRegistry ; public static final String IMG_OBJS_EXCEPTION = "" ; public static final String IMG_OBJS_EXCEPTION_DISABLED = "" ; public static final String IMG_OBJS_ERROR = "" ; public static final String IMG_OVR_BREAKPOINT_INSTALLED = "" ; public static final String IMG_OVR_BREAKPOINT_INSTALLED_DISABLED = "" ; public static final String IMG_OVR_METHOD_BREAKPOINT_ENTRY = "" ; public static final String IMG_OVR_METHOD_BREAKPOINT_ENTRY_DISABLED = "" ; public static final String IMG_OVR_METHOD_BREAKPOINT_EXIT = "" ; public static final String IMG_OVR_METHOD_BREAKPOINT_EXIT_DISABLED = "" ; public static final String IMG_OVR_CONDITIONAL_BREAKPOINT = "" ; public static final String IMG_OVR_CONDITIONAL_BREAKPOINT_DISABLED = "" ; public static final String IMG_OVR_SCOPED_BREAKPOINT = "" ; public static final String IMG_OVR_SCOPED_BREAKPOINT_DISABLED = "" ; public static final String IMG_OVR_UNCAUGHT_BREAKPOINT = "" ; public static final String IMG_OVR_UNCAUGHT_BREAKPOINT_DISABLED = "" ; public static final String IMG_OVR_CAUGHT_BREAKPOINT = "" ; public static final String IMG_OVR_CAUGHT_BREAKPOINT_DISABLED = "" ; public static final String IMG_OVR_OWNED = "" ; public static final String IMG_OVR_OWNS_MONITOR = "" ; public static final String IMG_OVR_IN_CONTENTION = "" ; public static final String IMG_OVR_IN_CONTENTION_FOR_MONITOR = "" ; public static final String IMG_OVR_IN_DEADLOCK = "" ; public static final String IMG_OVR_OUT_OF_SYNCH = "" ; public static final String IMG_OVR_MAY_BE_OUT_OF_SYNCH = "" ; public static final String IMG_OVR_SYNCHRONIZED = "" ; private static final String T_OBJ = ICONS_PATH + "" ; private static final String T_OVR = ICONS_PATH + "" ; public static ImageDescriptor getImageDescriptor ( String key ) { return getImageRegistry ( ) . getDescriptor ( key ) ; } static ImageRegistry getImageRegistry ( ) { if ( fgImageRegistry == null ) { initializeImageRegistry ( ) ; } return fgImageRegistry ; } private static void initializeImageRegistry ( ) { fgImageRegistry = new ImageRegistry ( RdtDebugUiPlugin . getStandardDisplay ( ) ) ; declareImages ( ) ; } private static void declareImages ( ) { declareRegistryImage ( IMG_OBJS_EXCEPTION , T_OBJ + "" ) ; declareRegistryImage ( IMG_OBJS_EXCEPTION_DISABLED , T_OBJ + "" ) ; declareRegistryImage ( IMG_OVR_BREAKPOINT_INSTALLED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_BREAKPOINT_INSTALLED_DISABLED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_METHOD_BREAKPOINT_ENTRY , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_METHOD_BREAKPOINT_ENTRY_DISABLED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_METHOD_BREAKPOINT_EXIT , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_METHOD_BREAKPOINT_EXIT_DISABLED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_CONDITIONAL_BREAKPOINT , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_CONDITIONAL_BREAKPOINT_DISABLED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_SCOPED_BREAKPOINT , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_SCOPED_BREAKPOINT_DISABLED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_UNCAUGHT_BREAKPOINT , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_UNCAUGHT_BREAKPOINT_DISABLED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_CAUGHT_BREAKPOINT , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_CAUGHT_BREAKPOINT_DISABLED , T_OVR + "" ) ; declareRegistryImage ( IMG_OBJS_ERROR , T_OBJ + "" ) ; declareRegistryImage ( IMG_OVR_OUT_OF_SYNCH , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_MAY_BE_OUT_OF_SYNCH , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_SYNCHRONIZED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_OWNED , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_OWNS_MONITOR , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_IN_CONTENTION , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_IN_CONTENTION_FOR_MONITOR , T_OVR + "" ) ; declareRegistryImage ( IMG_OVR_IN_DEADLOCK , T_OVR + "" ) ; } private final static void declareRegistryImage ( String key , String path ) { ImageDescriptor desc = ImageDescriptor . getMissingImageDescriptor ( ) ; Bundle bundle = Platform . getBundle ( RdtDebugUiPlugin . getUniqueIdentifier ( ) ) ; URL url = null ; if ( bundle != null ) { url = FileLocator . find ( bundle , new Path ( path ) , null ) ; desc = ImageDescriptor . createFromURL ( url ) ; } fgImageRegistry . put ( key , desc ) ; } } package org . rubypeople . rdt . internal . debug . ui . rubyvms ; import java . io . File ; import java . io . IOException ; import java . text . MessageFormat ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . internal . ui . dialogs . StatusDialog ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . ComboDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . DialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IDialogFieldListener ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . IStringButtonAdapter ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringButtonDialogField ; import org . rubypeople . rdt . internal . ui . wizards . dialogfields . StringDialogField ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . VMStandin ; public class AddVMDialog extends StatusDialog { protected IStatus [ ] allStatus = new IStatus [ ] ; protected IVMInstall fEditedVM ; private StringButtonDialogField fRubyVMRoot ; private StringDialogField fVMName ; private StringDialogField fVMArgs ; private IVMInstallType fSelectedVMType ; private IVMInstallType [ ] fVMTypes ; private ComboDialogField fVMTypeCombo ; private VMLibraryBlock fLibraryBlock ; private IStatus [ ] fStati ; private int fPrevIndex = - ; private IAddVMDialogRequestor fRequestor ; public AddVMDialog ( IAddVMDialogRequestor requestor , Shell shell , IVMInstallType [ ] vmInstallTypes , IVMInstall editedVM ) { super ( shell ) ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; fRequestor = requestor ; fStati = new IStatus [ ] ; for ( int i = ; i < fStati . length ; i ++ ) { fStati [ i ] = new StatusInfo ( ) ; } fVMTypes = vmInstallTypes ; fSelectedVMType = editedVM != null ? editedVM . getVMInstallType ( ) : vmInstallTypes [ ] ; fEditedVM = editedVM ; } protected void setSystemLibraryStatus ( IStatus status ) { fStati [ ] = status ; } protected IStatus validateInterpreterLocationText ( ) { String locationName = fRubyVMRoot . getText ( ) ; IStatus s = null ; File file = null ; if ( locationName . length ( ) == ) { s = new StatusInfo ( IStatus . INFO , RubyVMMessages . addVMDialog_enterLocation ) ; } else { file = new File ( locationName ) ; if ( ! file . exists ( ) ) { s = new StatusInfo ( IStatus . ERROR , RubyVMMessages . addVMDialog_locationNotExists ) ; } else { final IStatus [ ] temp = new IStatus [ ] ; final File tempFile = file ; Runnable r = new Runnable ( ) { public void run ( ) { temp [ ] = getVMType ( ) . validateInstallLocation ( tempFile ) ; } } ; BusyIndicator . showWhile ( getShell ( ) . getDisplay ( ) , r ) ; s = temp [ ] ; } } if ( s . isOK ( ) ) { if ( file . getName ( ) . equals ( "" ) ) { file = file . getParentFile ( ) ; } fLibraryBlock . setHomeDirectory ( file ) ; String name = fVMName . getText ( ) ; if ( name == null || name . trim ( ) . length ( ) == ) { try { String genName = null ; IPath path = new Path ( file . getCanonicalPath ( ) ) ; int segs = path . segmentCount ( ) ; if ( segs == ) { genName = path . segment ( ) ; } else if ( segs >= ) { genName = path . lastSegment ( ) ; } if ( genName != null ) { fVMName . setText ( genName ) ; } } catch ( IOException e ) { } } } else { fLibraryBlock . setHomeDirectory ( null ) ; } fLibraryBlock . restoreDefaultLibraries ( ) ; return s ; } private IVMInstallType getVMType ( ) { return fSelectedVMType ; } protected void setButtonLayoutData ( Button button ) { super . setButtonLayoutData ( button ) ; } protected void browseForInstallLocation ( ) { DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) ) ; dialog . setFilterPath ( fRubyVMRoot . getText ( ) ) ; dialog . setMessage ( RubyVMMessages . addVMDialog_pickJRERootDialog_message ) ; String newPath = dialog . open ( ) ; if ( newPath != null ) { fRubyVMRoot . setText ( newPath ) ; } } protected void okPressed ( ) { doOkPressed ( ) ; super . okPressed ( ) ; } private void doOkPressed ( ) { if ( fEditedVM == null ) { IVMInstall vm = new VMStandin ( fSelectedVMType , createUniqueId ( fSelectedVMType ) ) ; setFieldValuesToVM ( vm ) ; fRequestor . vmAdded ( vm ) ; } else { setFieldValuesToVM ( fEditedVM ) ; } } public void create ( ) { super . create ( ) ; fVMName . setFocus ( ) ; selectVMType ( ) ; } private String createUniqueId ( IVMInstallType vmType ) { String id = null ; do { id = String . valueOf ( System . currentTimeMillis ( ) ) ; } while ( vmType . findVMInstall ( id ) != null ) ; return id ; } private void selectVMType ( ) { for ( int i = ; i < fVMTypes . length ; i ++ ) { if ( fSelectedVMType == fVMTypes [ i ] ) { fVMTypeCombo . selectItem ( i ) ; return ; } } } private void updateVMType ( ) { int selIndex = fVMTypeCombo . getSelectionIndex ( ) ; if ( selIndex == fPrevIndex ) { return ; } fPrevIndex = selIndex ; if ( selIndex >= && selIndex < fVMTypes . length ) { fSelectedVMType = fVMTypes [ selIndex ] ; } setRubyVMLocationStatus ( validateInterpreterLocationText ( ) ) ; fLibraryBlock . initializeFrom ( fEditedVM , fSelectedVMType ) ; updateStatusLine ( ) ; } private void setRubyVMLocationStatus ( IStatus status ) { fStati [ ] = status ; } protected void updateStatusLine ( ) { IStatus max = null ; for ( int i = ; i < fStati . length ; i ++ ) { IStatus curr = fStati [ i ] ; if ( curr . matches ( IStatus . ERROR ) ) { updateStatus ( curr ) ; return ; } if ( max == null || curr . getSeverity ( ) > max . getSeverity ( ) ) { max = curr ; } } updateStatus ( max ) ; } protected Control createDialogArea ( Composite ancestor ) { createDialogFields ( ) ; Composite parent = ( Composite ) super . createDialogArea ( ancestor ) ; ( ( GridLayout ) parent . getLayout ( ) ) . numColumns = ; fVMTypeCombo . doFillIntoGrid ( parent , ) ; ( ( GridData ) fVMTypeCombo . getComboControl ( null ) . getLayoutData ( ) ) . widthHint = convertWidthInCharsToPixels ( ) ; Label l = new Label ( parent , SWT . NONE ) ; l . setText ( RubyVMMessages . enterRubyInstallLocation ) ; GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = ; l . setLayoutData ( gd ) ; fRubyVMRoot . doFillIntoGrid ( parent , ) ; fVMName . doFillIntoGrid ( parent , ) ; fVMArgs . doFillIntoGrid ( parent , ) ; ( ( GridData ) fVMArgs . getTextControl ( null ) . getLayoutData ( ) ) . widthHint = convertWidthInCharsToPixels ( ) ; l = new Label ( parent , SWT . NONE ) ; l . setText ( RubyVMMessages . AddVMDialog_JRE_system_libraries__1 ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; gd . horizontalSpan = ; l . setLayoutData ( gd ) ; fLibraryBlock = new VMLibraryBlock ( this ) ; Control block = fLibraryBlock . createControl ( parent ) ; gd = new GridData ( GridData . FILL_BOTH ) ; gd . horizontalSpan = ; block . setLayoutData ( gd ) ; Text t = fRubyVMRoot . getTextControl ( parent ) ; gd = ( GridData ) t . getLayoutData ( ) ; gd . grabExcessHorizontalSpace = true ; gd . widthHint = convertWidthInCharsToPixels ( ) ; initializeFields ( ) ; createFieldListeners ( ) ; applyDialogFont ( parent ) ; return parent ; } private void initializeFields ( ) { fVMTypeCombo . setItems ( getVMTypeNames ( ) ) ; if ( fEditedVM == null ) { fVMName . setText ( "" ) ; fRubyVMRoot . setText ( "" ) ; fLibraryBlock . initializeFrom ( null , fSelectedVMType ) ; fVMArgs . setText ( "" ) ; } else { fVMTypeCombo . setEnabled ( false ) ; fVMName . setText ( fEditedVM . getName ( ) ) ; fRubyVMRoot . setText ( fEditedVM . getInstallLocation ( ) . getAbsolutePath ( ) ) ; fLibraryBlock . initializeFrom ( fEditedVM , fSelectedVMType ) ; String vmArgs = fEditedVM . getVMArgs ( ) ; if ( vmArgs != null ) { fVMArgs . setText ( vmArgs ) ; } } setVMNameStatus ( validateVMName ( ) ) ; updateStatusLine ( ) ; } private void setVMNameStatus ( IStatus status ) { fStati [ ] = status ; } protected void createFieldListeners ( ) { fVMTypeCombo . setDialogFieldListener ( new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { updateVMType ( ) ; } } ) ; fVMName . setDialogFieldListener ( new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { setVMNameStatus ( validateVMName ( ) ) ; updateStatusLine ( ) ; } } ) ; fRubyVMRoot . setDialogFieldListener ( new IDialogFieldListener ( ) { public void dialogFieldChanged ( DialogField field ) { setRubyVMLocationStatus ( validateInterpreterLocationText ( ) ) ; updateStatusLine ( ) ; } } ) ; } private IStatus validateVMName ( ) { StatusInfo status = new StatusInfo ( ) ; String name = fVMName . getText ( ) ; if ( name == null || name . trim ( ) . length ( ) == ) { status . setInfo ( RubyVMMessages . addVMDialog_enterName ) ; } else { if ( fRequestor . isDuplicateName ( name ) && ( fEditedVM == null || ! name . equals ( fEditedVM . getName ( ) ) ) ) { status . setError ( RubyVMMessages . addVMDialog_duplicateName ) ; } else { IStatus s = ResourcesPlugin . getWorkspace ( ) . validateName ( name , IResource . FILE ) ; if ( ! s . isOK ( ) ) { status . setError ( MessageFormat . format ( RubyVMMessages . AddVMDialog_JRE_name_must_be_a_valid_file_name___0__1 , s . getMessage ( ) ) ) ; } } } return status ; } protected void createDialogFields ( ) { fVMTypeCombo = new ComboDialogField ( SWT . READ_ONLY ) ; fVMTypeCombo . setLabelText ( RubyVMMessages . addVMDialog_jreType ) ; fVMTypeCombo . setItems ( getVMTypeNames ( ) ) ; fVMName = new StringDialogField ( ) ; fVMName . setLabelText ( RubyVMMessages . addVMDialog_jreName ) ; fRubyVMRoot = new StringButtonDialogField ( new IStringButtonAdapter ( ) { public void changeControlPressed ( DialogField field ) { browseForInstallLocation ( ) ; } } ) ; fRubyVMRoot . setLabelText ( RubyVMMessages . addVMDialog_jreHome ) ; fRubyVMRoot . setButtonLabel ( RubyVMMessages . addVMDialog_browse1 ) ; fVMArgs = new StringDialogField ( ) ; fVMArgs . setLabelText ( RubyVMMessages . AddVMDialog_23 ) ; } private String [ ] getVMTypeNames ( ) { String [ ] names = new String [ fVMTypes . length ] ; for ( int i = ; i < fVMTypes . length ; i ++ ) { names [ i ] = fVMTypes [ i ] . getName ( ) ; } return names ; } protected void setFieldValuesToVM ( IVMInstall vm ) { File dir = new File ( fRubyVMRoot . getText ( ) ) ; if ( dir . getName ( ) . equals ( "" ) ) { dir = dir . getParentFile ( ) ; } try { vm . setInstallLocation ( dir . getCanonicalFile ( ) ) ; } catch ( IOException e ) { vm . setInstallLocation ( dir . getAbsoluteFile ( ) ) ; } vm . setName ( fVMName . getText ( ) ) ; String argString = fVMArgs . getText ( ) . trim ( ) ; if ( argString != null && argString . length ( ) > ) { vm . setVMArgs ( argString ) ; } else { vm . setVMArgs ( null ) ; } fLibraryBlock . performApply ( vm ) ; } } package org . rubypeople . rdt . internal . debug . ui . rubyvms ; import java . io . IOException ; import java . lang . reflect . InvocationTargetException ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . TransformerException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . launching . VMDefinitionsContainer ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RubyVMsUpdater { private VMDefinitionsContainer fOriginalVMs ; public RubyVMsUpdater ( ) { fOriginalVMs = new VMDefinitionsContainer ( ) ; IVMInstall def = RubyRuntime . getDefaultVMInstall ( ) ; if ( def != null ) { fOriginalVMs . setDefaultVMInstallCompositeID ( RubyRuntime . getCompositeIdFromVM ( def ) ) ; } IVMInstallType [ ] types = RubyRuntime . getVMInstallTypes ( ) ; for ( int i = ; i < types . length ; i ++ ) { IVMInstall [ ] vms = types [ i ] . getVMInstalls ( ) ; for ( int j = ; j < vms . length ; j ++ ) { fOriginalVMs . addVM ( vms [ j ] ) ; } } } public boolean updateRubyVMSettings ( IVMInstall [ ] rubyVMs , IVMInstall defaultRubyVM ) { VMDefinitionsContainer vmContainer = new VMDefinitionsContainer ( ) ; String defaultVMId = RubyRuntime . getCompositeIdFromVM ( defaultRubyVM ) ; vmContainer . setDefaultVMInstallCompositeID ( defaultVMId ) ; for ( int i = ; i < rubyVMs . length ; i ++ ) { vmContainer . addVM ( rubyVMs [ i ] ) ; } saveVMDefinitions ( vmContainer ) ; return true ; } private void saveVMDefinitions ( final VMDefinitionsContainer container ) { IRunnableWithProgress runnable = new IRunnableWithProgress ( ) { public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { try { monitor . beginTask ( RubyVMMessages . JREsUpdater_0 , ) ; String vmDefXML = container . getAsXML ( ) ; monitor . worked ( ) ; RubyRuntime . getPreferences ( ) . setValue ( RubyRuntime . PREF_VM_XML , vmDefXML ) ; monitor . worked ( ) ; RubyRuntime . savePreferences ( ) ; monitor . worked ( ) ; } catch ( IOException ioe ) { RdtDebugUiPlugin . log ( ioe ) ; } catch ( ParserConfigurationException e ) { RdtDebugUiPlugin . log ( e ) ; } catch ( TransformerException e ) { RdtDebugUiPlugin . log ( e ) ; } finally { monitor . done ( ) ; } } } ; try { RdtDebugUiPlugin . getDefault ( ) . getWorkbench ( ) . getProgressService ( ) . busyCursorWhile ( runnable ) ; } catch ( InvocationTargetException e ) { RdtDebugUiPlugin . log ( e ) ; } catch ( InterruptedException e ) { RdtDebugUiPlugin . log ( e ) ; } } } package org . rubypeople . rdt . internal . debug . ui . rubyvms ; import java . text . MessageFormat ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public final class LibraryStandin { private IPath fSystemLibrary ; public LibraryStandin ( IPath path ) { fSystemLibrary = path ; } public IPath getSystemLibraryPath ( ) { return fSystemLibrary ; } public boolean equals ( Object obj ) { if ( obj instanceof LibraryStandin ) { LibraryStandin lib = ( LibraryStandin ) obj ; return getSystemLibraryPath ( ) . equals ( lib . getSystemLibraryPath ( ) ) ; } return false ; } public int hashCode ( ) { return getSystemLibraryPath ( ) . hashCode ( ) ; } protected boolean equals ( IPath path1 , IPath path2 ) { return equalsOrNull ( path1 , path2 ) ; } private boolean equalsOrNull ( Object o1 , Object o2 ) { if ( o1 == null ) { return o2 == null ; } if ( o2 == null ) { return false ; } return o1 . equals ( o2 ) ; } IPath toLibraryLocation ( ) { return getSystemLibraryPath ( ) ; } IStatus validate ( ) { if ( ! getSystemLibraryPath ( ) . toFile ( ) . exists ( ) ) { return new Status ( IStatus . ERROR , RdtDebugUiPlugin . getUniqueIdentifier ( ) , RdtDebugUiConstants . INTERNAL_ERROR , MessageFormat . format ( RubyVMMessages . LibraryStandin_0 , getSystemLibraryPath ( ) . toOSString ( ) ) , null ) ; } return Status . OK_STATUS ; } } package org . rubypeople . rdt . internal . debug . ui . rubyvms ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . Viewer ; public class LibraryContentProvider implements ITreeContentProvider { private Viewer fViewer ; private HashMap fChildren = new HashMap ( ) ; private LibraryStandin [ ] fLibraries = new LibraryStandin [ ] ; public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { fViewer = viewer ; } public Object [ ] getElements ( Object inputElement ) { return fLibraries ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof LibraryStandin ) { LibraryStandin standin = ( LibraryStandin ) parentElement ; Object [ ] children = ( Object [ ] ) fChildren . get ( standin ) ; return children ; } return null ; } public Object getParent ( Object element ) { return null ; } public boolean hasChildren ( Object element ) { return false ; } public void setLibraries ( IPath [ ] libs ) { fLibraries = new LibraryStandin [ libs . length ] ; for ( int i = ; i < libs . length ; i ++ ) { fLibraries [ i ] = new LibraryStandin ( libs [ i ] ) ; } fViewer . refresh ( ) ; } public IPath [ ] getLibraries ( ) { IPath [ ] locations = new IPath [ fLibraries . length ] ; for ( int i = ; i < locations . length ; i ++ ) { locations [ i ] = fLibraries [ i ] . toLibraryLocation ( ) ; } return locations ; } private Set getSelectedLibraries ( IStructuredSelection selection ) { Set libraries = new HashSet ( ) ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; if ( element instanceof LibraryStandin ) { libraries . add ( element ) ; } } return libraries ; } public void up ( IStructuredSelection selection ) { Set libraries = getSelectedLibraries ( selection ) ; for ( int i = ; i < fLibraries . length - ; i ++ ) { if ( libraries . contains ( fLibraries [ i + ] ) ) { LibraryStandin temp = fLibraries [ i ] ; fLibraries [ i ] = fLibraries [ i + ] ; fLibraries [ i + ] = temp ; } } fViewer . refresh ( ) ; fViewer . setSelection ( selection ) ; } public void down ( IStructuredSelection selection ) { Set libraries = getSelectedLibraries ( selection ) ; for ( int i = fLibraries . length - ; i > ; i -- ) { if ( libraries . contains ( fLibraries [ i - ] ) ) { LibraryStandin temp = fLibraries [ i ] ; fLibraries [ i ] = fLibraries [ i - ] ; fLibraries [ i - ] = temp ; } } fViewer . refresh ( ) ; fViewer . setSelection ( selection ) ; } public void remove ( IStructuredSelection selection ) { List newLibraries = new ArrayList ( ) ; for ( int i = ; i < fLibraries . length ; i ++ ) { newLibraries . add ( fLibraries [ i ] ) ; } Iterator iterator = selection . iterator ( ) ; while ( iterator . hasNext ( ) ) { Object element = iterator . next ( ) ; if ( element instanceof LibraryStandin ) { newLibraries . remove ( element ) ; } } fLibraries = ( LibraryStandin [ ] ) newLibraries . toArray ( new LibraryStandin [ newLibraries . size ( ) ] ) ; fViewer . refresh ( ) ; } public void add ( IPath [ ] libs , IStructuredSelection selection ) { List newLibraries = new ArrayList ( fLibraries . length + libs . length ) ; for ( int i = ; i < fLibraries . length ; i ++ ) { newLibraries . add ( fLibraries [ i ] ) ; } List toAdd = new ArrayList ( libs . length ) ; for ( int i = ; i < libs . length ; i ++ ) { toAdd . add ( new LibraryStandin ( libs [ i ] ) ) ; } if ( selection . isEmpty ( ) ) { newLibraries . addAll ( toAdd ) ; } else { Object element = selection . getFirstElement ( ) ; LibraryStandin firstLib = ( LibraryStandin ) element ; int index = newLibraries . indexOf ( firstLib ) ; newLibraries . addAll ( index , toAdd ) ; } fLibraries = ( LibraryStandin [ ] ) newLibraries . toArray ( new LibraryStandin [ newLibraries . size ( ) ] ) ; fViewer . refresh ( ) ; fViewer . setSelection ( new StructuredSelection ( libs ) , true ) ; } LibraryStandin [ ] getStandins ( ) { return fLibraries ; } } package org . rubypeople . rdt . internal . debug . ui . rubyvms ; import org . eclipse . osgi . util . NLS ; public class RubyVMMessages extends NLS { private static final String BUNDLE_NAME = "" ; public static String addVMDialog_enterLocation ; public static String addVMDialog_locationNotExists ; public static String AddVMDialog_JRE_system_libraries__1 ; public static String addVMDialog_jreType ; public static String addVMDialog_jreName ; public static String addVMDialog_jreHome ; public static String addVMDialog_browse1 ; public static String AddVMDialog_23 ; public static String addVMDialog_enterName ; public static String addVMDialog_duplicateName ; public static String AddVMDialog_JRE_name_must_be_a_valid_file_name___0__1 ; public static String InstalledJREsBlock_7 ; public static String InstalledJREsBlock_8 ; public static String JREsUpdater_0 ; public static String addVMDialog_pickJRERootDialog_message ; public static String VMLibraryBlock_7 ; public static String VMLibraryBlock_6 ; public static String VMLibraryBlock_4 ; public static String VMLibraryBlock_5 ; public static String VMLibraryBlock_9 ; public static String VMLibraryBlock_Libraries_cannot_be_empty__1 ; public static String VMLibraryBlock_10 ; public static String LibraryStandin_0 ; public static String InstalledJREsBlock_15 ; public static String JREsPreferencePage_2 ; public static String JREsPreferencePage_1 ; public static String enterRubyInstallLocation ; static { NLS . initializeMessages ( BUNDLE_NAME , RubyVMMessages . class ) ; } } package org . rubypeople . rdt . internal . debug . ui . rubyvms ; import org . rubypeople . rdt . launching . IVMInstall ; public interface IAddVMDialogRequestor { public boolean isDuplicateName ( String name ) ; public void vmAdded ( IVMInstall vm ) ; } package org . rubypeople . rdt . internal . debug . ui . rubyvms ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . internal . debug . ui . RDTImageDescriptor ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . ui . ISharedImages ; import org . rubypeople . rdt . ui . RubyUI ; public class LibraryLabelProvider extends LabelProvider { public Image getImage ( Object element ) { if ( element instanceof LibraryStandin ) { LibraryStandin library = ( LibraryStandin ) element ; String key = ISharedImages . IMG_OBJS_LIBRARY ; IStatus status = library . validate ( ) ; if ( ! status . isOK ( ) ) { ImageDescriptor base = RubyUI . getSharedImages ( ) . getImageDescriptor ( key ) ; RDTImageDescriptor descriptor = new RDTImageDescriptor ( base , RDTImageDescriptor . IS_OUT_OF_SYNCH ) ; return RdtDebugUiPlugin . getImageDescriptorRegistry ( ) . get ( descriptor ) ; } return RubyUI . getSharedImages ( ) . getImage ( key ) ; } return null ; } public String getText ( Object element ) { if ( element instanceof LibraryStandin ) { return ( ( LibraryStandin ) element ) . getSystemLibraryPath ( ) . toOSString ( ) ; } return null ; } } package org . rubypeople . rdt . internal . debug . ui . rubyvms ; import java . io . File ; import java . util . Iterator ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Status ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TreeViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; public class VMLibraryBlock implements SelectionListener , ISelectionChangedListener { protected static final String LAST_PATH_SETTING = "" ; protected static final String DIALOG_SETTINGS_PREFIX = "" ; protected boolean fInCallback = false ; protected IVMInstall fVmInstall ; protected IVMInstallType fVmInstallType ; protected File fHome ; protected LibraryContentProvider fLibraryContentProvider ; protected AddVMDialog fDialog = null ; protected TreeViewer fLibraryViewer ; private Button fUpButton ; private Button fDownButton ; private Button fRemoveButton ; private Button fAddButton ; protected Button fDefaultButton ; public VMLibraryBlock ( AddVMDialog dialog ) { fDialog = dialog ; } public Control createControl ( Composite parent ) { Font font = parent . getFont ( ) ; Composite comp = new Composite ( parent , SWT . NONE ) ; GridLayout topLayout = new GridLayout ( ) ; topLayout . numColumns = ; topLayout . marginHeight = ; topLayout . marginWidth = ; comp . setLayout ( topLayout ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; comp . setLayoutData ( gd ) ; fLibraryViewer = new TreeViewer ( comp ) ; gd = new GridData ( GridData . FILL_BOTH ) ; gd . heightHint = ; fLibraryViewer . getControl ( ) . setLayoutData ( gd ) ; fLibraryContentProvider = new LibraryContentProvider ( ) ; fLibraryViewer . setContentProvider ( fLibraryContentProvider ) ; fLibraryViewer . setLabelProvider ( new LibraryLabelProvider ( ) ) ; fLibraryViewer . setInput ( this ) ; fLibraryViewer . addSelectionChangedListener ( this ) ; Composite pathButtonComp = new Composite ( comp , SWT . NONE ) ; GridLayout pathButtonLayout = new GridLayout ( ) ; pathButtonLayout . marginHeight = ; pathButtonLayout . marginWidth = ; pathButtonComp . setLayout ( pathButtonLayout ) ; gd = new GridData ( GridData . VERTICAL_ALIGN_BEGINNING | GridData . HORIZONTAL_ALIGN_FILL ) ; pathButtonComp . setLayoutData ( gd ) ; pathButtonComp . setFont ( font ) ; fAddButton = createPushButton ( pathButtonComp , RubyVMMessages . VMLibraryBlock_7 ) ; fAddButton . addSelectionListener ( this ) ; fRemoveButton = createPushButton ( pathButtonComp , RubyVMMessages . VMLibraryBlock_6 ) ; fRemoveButton . addSelectionListener ( this ) ; fUpButton = createPushButton ( pathButtonComp , RubyVMMessages . VMLibraryBlock_4 ) ; fUpButton . addSelectionListener ( this ) ; fDownButton = createPushButton ( pathButtonComp , RubyVMMessages . VMLibraryBlock_5 ) ; fDownButton . addSelectionListener ( this ) ; fDefaultButton = createPushButton ( pathButtonComp , RubyVMMessages . VMLibraryBlock_9 ) ; fDefaultButton . addSelectionListener ( this ) ; return comp ; } public void restoreDefaultLibraries ( ) { IPath [ ] libs = null ; File installLocation = getHomeDirectory ( ) ; if ( installLocation == null ) { libs = new IPath [ ] ; } else { libs = getVMInstallType ( ) . getDefaultLibraryLocations ( installLocation ) ; } fLibraryContentProvider . setLibraries ( libs ) ; update ( ) ; } protected Button createPushButton ( Composite parent , String label ) { Button button = new Button ( parent , SWT . PUSH ) ; button . setFont ( parent . getFont ( ) ) ; button . setText ( label ) ; fDialog . setButtonLayoutData ( button ) ; return button ; } protected void createVerticalSpacer ( Composite comp , int colSpan ) { Label label = new Label ( comp , SWT . NONE ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = colSpan ; label . setLayoutData ( gd ) ; } public void initializeFrom ( IVMInstall vm , IVMInstallType type ) { fVmInstall = vm ; fVmInstallType = type ; if ( vm != null ) { setHomeDirectory ( vm . getInstallLocation ( ) ) ; fLibraryContentProvider . setLibraries ( RubyRuntime . getLibraryLocations ( getVMInstall ( ) ) ) ; } update ( ) ; } public void setHomeDirectory ( File file ) { fHome = file ; } protected File getHomeDirectory ( ) { return fHome ; } public void update ( ) { updateButtons ( ) ; IStatus status = Status . OK_STATUS ; if ( fLibraryContentProvider . getLibraries ( ) . length == ) { status = new Status ( IStatus . ERROR , RdtDebugUiPlugin . getUniqueIdentifier ( ) , RdtDebugUiConstants . INTERNAL_ERROR , RubyVMMessages . VMLibraryBlock_Libraries_cannot_be_empty__1 , null ) ; } LibraryStandin [ ] standins = fLibraryContentProvider . getStandins ( ) ; for ( int i = ; i < standins . length ; i ++ ) { IStatus st = standins [ i ] . validate ( ) ; if ( ! st . isOK ( ) ) { status = st ; break ; } } fDialog . setSystemLibraryStatus ( status ) ; fDialog . updateStatusLine ( ) ; } public void performApply ( IVMInstall vm ) { if ( isDefaultLocations ( ) ) { vm . setLibraryLocations ( null ) ; } else { IPath [ ] libs = fLibraryContentProvider . getLibraries ( ) ; vm . setLibraryLocations ( libs ) ; } } protected boolean isDefaultLocations ( ) { IPath [ ] libraryLocations = fLibraryContentProvider . getLibraries ( ) ; IVMInstall install = getVMInstall ( ) ; if ( install == null || libraryLocations == null ) { return true ; } File installLocation = install . getInstallLocation ( ) ; if ( installLocation != null ) { IPath [ ] def = getVMInstallType ( ) . getDefaultLibraryLocations ( installLocation ) ; if ( def . length == libraryLocations . length ) { for ( int i = ; i < def . length ; i ++ ) { if ( ! def [ i ] . equals ( libraryLocations [ i ] ) ) { return false ; } } return true ; } } return false ; } protected IVMInstall getVMInstall ( ) { return fVmInstall ; } protected IVMInstallType getVMInstallType ( ) { return fVmInstallType ; } public void widgetSelected ( SelectionEvent e ) { Object source = e . getSource ( ) ; if ( source == fUpButton ) { fLibraryContentProvider . up ( ( IStructuredSelection ) fLibraryViewer . getSelection ( ) ) ; } else if ( source == fDownButton ) { fLibraryContentProvider . down ( ( IStructuredSelection ) fLibraryViewer . getSelection ( ) ) ; } else if ( source == fRemoveButton ) { fLibraryContentProvider . remove ( ( IStructuredSelection ) fLibraryViewer . getSelection ( ) ) ; } else if ( source == fAddButton ) { add ( ( IStructuredSelection ) fLibraryViewer . getSelection ( ) ) ; } else if ( source == fDefaultButton ) { restoreDefaultLibraries ( ) ; } update ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } private void add ( IStructuredSelection selection ) { IDialogSettings dialogSettings = RdtDebugUiPlugin . getDefault ( ) . getDialogSettings ( ) ; String lastUsedPath = dialogSettings . get ( LAST_PATH_SETTING ) ; if ( lastUsedPath == null ) { lastUsedPath = "" ; } DirectoryDialog dialog = new DirectoryDialog ( fLibraryViewer . getControl ( ) . getShell ( ) , SWT . MULTI ) ; dialog . setMessage ( RubyVMMessages . VMLibraryBlock_10 ) ; dialog . setFilterPath ( lastUsedPath ) ; String res = dialog . open ( ) ; if ( res == null ) { return ; } dialogSettings . put ( LAST_PATH_SETTING , res ) ; fLibraryContentProvider . add ( new IPath [ ] { Path . fromOSString ( res ) } , selection ) ; } public void selectionChanged ( SelectionChangedEvent event ) { updateButtons ( ) ; } private void updateButtons ( ) { IStructuredSelection selection = ( IStructuredSelection ) fLibraryViewer . getSelection ( ) ; fRemoveButton . setEnabled ( ! selection . isEmpty ( ) ) ; boolean enableUp = true , enableDown = true , allRoots = true ; Object [ ] libraries = fLibraryContentProvider . getElements ( null ) ; if ( selection . isEmpty ( ) || libraries . length == ) { enableUp = false ; enableDown = false ; } else { Object first = libraries [ ] ; Object last = libraries [ libraries . length - ] ; for ( Iterator iter = selection . iterator ( ) ; iter . hasNext ( ) ; ) { Object element = iter . next ( ) ; Object lib = element ; if ( lib == first ) { enableUp = false ; } if ( lib == last ) { enableDown = false ; } } } fUpButton . setEnabled ( enableUp ) ; fDownButton . setEnabled ( enableDown ) ; } } package org . rubypeople . rdt . internal . debug . ui ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . osgi . service . prefs . Preferences ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; public class DebugUiPreferenceInitializer extends AbstractPreferenceInitializer { public DebugUiPreferenceInitializer ( ) { super ( ) ; } public void initializeDefaultPreferences ( ) { Preferences node = new DefaultScope ( ) . getNode ( RdtDebugUiPlugin . PLUGIN_ID ) ; node . put ( RdtDebugUiConstants . PREFERENCE_KEYWORDS , getDefaultKeywords ( ) ) ; try { BufferedReader reader = new BufferedReader ( new InputStreamReader ( RdtDebugUiPlugin . getDefault ( ) . getBundle ( ) . getEntry ( "" ) . openStream ( ) ) ) ; StringBuffer fileContent = new StringBuffer ( ) ; while ( reader . ready ( ) ) { fileContent . append ( reader . readLine ( ) ) ; } node . put ( RdtDebugUiConstants . EVALUATION_EXPRESSIONS_PREFERENCE , fileContent . toString ( ) ) ; } catch ( IOException e ) { RdtDebugUiPlugin . log ( e ) ; } } private String getDefaultKeywords ( ) { return "" ; } } package org . rubypeople . rdt . internal . debug . ui . breakpoints ; import org . eclipse . osgi . util . NLS ; public class BreakpointMessages extends NLS { private static final String BUNDLE_NAME = BreakpointMessages . class . getName ( ) ; public static String AddExceptionAction_0 ; public static String AddExceptionAction_1 ; public static String AddExceptionAction_error ; static { NLS . initializeMessages ( BUNDLE_NAME , BreakpointMessages . class ) ; } } package org . rubypeople . rdt . internal . debug . ui . breakpoints ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . model . IBreakpoint ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . eclipse . ui . dialogs . SelectionDialog ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . debug . core . IRubyBreakpoint ; import org . rubypeople . rdt . debug . core . RdtDebugModel ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; import org . rubypeople . rdt . internal . debug . ui . BreakpointUtils ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . ui . RubyUI ; public class AddExceptionAction implements IViewActionDelegate , IWorkbenchWindowActionDelegate { public static final String DIALOG_SETTINGS = "" ; private IWorkbenchWindow fWorkbenchWindow = null ; public void run ( IAction action ) { Shell shell = RdtDebugUiPlugin . getActiveWorkbenchShell ( ) ; AddExceptionDialogExtension ext = new AddExceptionDialogExtension ( ) ; try { SelectionDialog dialog = RubyUI . createTypeDialog ( shell , fWorkbenchWindow , SearchEngine . createWorkspaceScope ( ) , IRubySearchConstants . CLASS , true , "" , ext ) ; dialog . setTitle ( BreakpointMessages . AddExceptionAction_0 ) ; dialog . setMessage ( BreakpointMessages . AddExceptionAction_1 ) ; if ( dialog . open ( ) == IDialogConstants . OK_ID ) { Object [ ] results = dialog . getResult ( ) ; for ( int i = ; i < results . length ; i ++ ) { createBreakpoint ( ( IType ) results [ i ] ) ; } } } catch ( CoreException e ) { RdtDebugUiPlugin . errorDialog ( BreakpointMessages . AddExceptionAction_error , e . getStatus ( ) ) ; } } private void createBreakpoint ( final IType type ) throws CoreException { final IResource resource = BreakpointUtils . getBreakpointResource ( type ) ; final Map map = new HashMap ( ) ; BreakpointUtils . addRubyBreakpointAttributes ( map , type ) ; IBreakpoint [ ] breakpoints = DebugPlugin . getDefault ( ) . getBreakpointManager ( ) . getBreakpoints ( RdtDebugModel . getModelIdentifier ( ) ) ; boolean exists = false ; for ( int j = ; j < breakpoints . length ; j ++ ) { IRubyBreakpoint breakpoint = ( IRubyBreakpoint ) breakpoints [ j ] ; if ( breakpoint instanceof IRubyExceptionBreakpoint ) { if ( breakpoint . getTypeName ( ) . equals ( type . getFullyQualifiedName ( ) ) ) { exists = true ; break ; } } } if ( ! exists ) { new Job ( BreakpointMessages . AddExceptionAction_0 ) { protected IStatus run ( IProgressMonitor monitor ) { try { RdtDebugModel . createExceptionBreakpoint ( resource , type . getFullyQualifiedName ( ) , true , map ) ; return Status . OK_STATUS ; } catch ( CoreException e ) { return e . getStatus ( ) ; } } } . schedule ( ) ; } } public void init ( IViewPart view ) { } public void selectionChanged ( IAction action , ISelection selection ) { } public void dispose ( ) { fWorkbenchWindow = null ; } public void init ( IWorkbenchWindow window ) { fWorkbenchWindow = window ; } } package org . rubypeople . rdt . internal . debug . ui . breakpoints ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . ui . dialogs . ISelectionStatusValidator ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . ITypeHierarchy ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . ui . dialogs . StatusInfo ; import org . rubypeople . rdt . ui . dialogs . TypeSelectionExtension ; public class AddExceptionDialogExtension extends TypeSelectionExtension { public AddExceptionDialogExtension ( ) { super ( ) ; } public ISelectionStatusValidator getSelectionValidator ( ) { ISelectionStatusValidator validator = new ISelectionStatusValidator ( ) { public IStatus validate ( Object [ ] selection ) { IType type = null ; for ( int i = ; i < selection . length ; i ++ ) { type = ( IType ) selection [ i ] ; if ( ! isException ( type ) ) { return new StatusInfo ( IStatus . ERROR , "" ) ; } } return new StatusInfo ( IStatus . OK , "" ) ; } } ; return validator ; } protected boolean isException ( IType type ) { if ( type != null ) { try { ITypeHierarchy hierarchy = type . newSupertypeHierarchy ( new NullProgressMonitor ( ) ) ; IType curr = type ; while ( curr != null ) { if ( "" . equals ( curr . getFullyQualifiedName ( ) ) ) { return true ; } curr = hierarchy . getSuperclass ( curr ) ; } } catch ( RubyModelException e ) { RdtDebugUiPlugin . log ( e ) ; } } return false ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . ui . DebugUITools ; import org . eclipse . debug . ui . ILaunchShortcut ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . debug . ui . InstallDeveloperToolsDialog ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . ContributedGemRegistry ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . Version ; public class RubyApplicationShortcut implements ILaunchShortcut { private static final String RUBY_PROFILING_GEM_NAME = "" ; private static final String RUBY_DEBUG_IDE_GEM_NAME = "" ; private static final String MINIMUM_RUBY_DEBUG_IDE_VERSION = "" ; public void launch ( ISelection selection , String mode ) { Object firstSelection = null ; if ( selection instanceof IStructuredSelection ) { firstSelection = ( ( IStructuredSelection ) selection ) . getFirstElement ( ) ; } if ( firstSelection == null ) { log ( "" ) ; return ; } IRubyElement rubyElement = null ; if ( firstSelection instanceof IAdaptable ) { rubyElement = ( IRubyElement ) ( ( IAdaptable ) firstSelection ) . getAdapter ( IRubyElement . class ) ; } if ( rubyElement == null ) { log ( "" ) ; return ; } doLaunchWithErrorHandling ( rubyElement , mode ) ; } private void doLaunchWithErrorHandling ( IRubyElement rubyElement , String mode ) { if ( shouldInstallGemsFirst ( mode ) ) return ; try { doLaunch ( rubyElement , mode ) ; } catch ( CoreException e ) { log ( e ) ; IStatus status = e . getStatus ( ) ; String title = RdtDebugUiMessages . Dialog_launchErrorTitle ; String message = RdtDebugUiMessages . Dialog_launchErrorMessage ; if ( status != null ) { ErrorDialog . openError ( RdtDebugUiPlugin . getActiveWorkbenchWindow ( ) . getShell ( ) , title , message , status ) ; } } } private static boolean shouldInstallGemsFirst ( String mode ) { if ( mode . equals ( ILaunchManager . RUN_MODE ) ) return false ; if ( mode . equals ( ILaunchManager . DEBUG_MODE ) ) { if ( ! AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . gemInstalled ( RUBY_DEBUG_IDE_GEM_NAME ) ) { installNecessaryDebuggingGems ( ) ; return true ; } else if ( updatingRubyDebugIDEGem ( ) ) { return true ; } } else if ( mode . equals ( ILaunchManager . PROFILE_MODE ) ) { if ( RubyRuntime . currentVMIsJRuby ( ) ) { MessageDialog . openError ( Display . getDefault ( ) . getActiveShell ( ) , "" , "" ) ; return true ; } if ( ! AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . gemInstalled ( RUBY_PROFILING_GEM_NAME ) ) { installNecessaryProfilingGems ( ) ; return true ; } } return false ; } private static boolean updatingRubyDebugIDEGem ( ) { List < Version > versions = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . getVersions ( RUBY_DEBUG_IDE_GEM_NAME ) ; for ( Version version : versions ) { if ( version . isGreaterThanOrEqualTo ( MINIMUM_RUBY_DEBUG_IDE_VERSION ) ) return false ; } if ( ! MessageDialog . openQuestion ( Display . getDefault ( ) . getActiveShell ( ) , "" , "" + MINIMUM_RUBY_DEBUG_IDE_VERSION + "" ) ) return true ; Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { return AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . update ( new Gem ( RUBY_DEBUG_IDE_GEM_NAME , Gem . ANY_VERSION , null ) , monitor ) ; } } ; job . setUser ( true ) ; job . schedule ( ) ; return true ; } private static void installNecessaryProfilingGems ( ) { if ( ! MessageDialog . openQuestion ( Display . getDefault ( ) . getActiveShell ( ) , "" , "" ) ) return ; if ( InstallDeveloperToolsDialog . shouldShow ( ) ) { InstallDeveloperToolsDialog dialog = new InstallDeveloperToolsDialog ( Display . getDefault ( ) . getActiveShell ( ) ) ; dialog . open ( ) ; return ; } List < Gem > finalGems = new ArrayList < Gem > ( ) ; Gem gem = ContributedGemRegistry . getGem ( RUBY_PROFILING_GEM_NAME ) ; if ( gem != null ) finalGems . add ( gem ) ; Job job = new InstallGemsJob ( finalGems ) ; job . setSystem ( true ) ; job . schedule ( ) ; } private static void installNecessaryDebuggingGems ( ) { if ( ! MessageDialog . openQuestion ( Display . getDefault ( ) . getActiveShell ( ) , "" , "" ) ) return ; if ( InstallDeveloperToolsDialog . shouldShow ( ) ) { InstallDeveloperToolsDialog dialog = new InstallDeveloperToolsDialog ( Display . getDefault ( ) . getActiveShell ( ) ) ; dialog . open ( ) ; return ; } List < Gem > finalGems = new ArrayList < Gem > ( ) ; Gem gem = ContributedGemRegistry . getGem ( "" ) ; if ( gem != null ) finalGems . add ( gem ) ; gem = ContributedGemRegistry . getGem ( RUBY_DEBUG_IDE_GEM_NAME ) ; if ( gem != null ) finalGems . add ( gem ) ; Job job = new InstallGemsJob ( finalGems ) ; job . setSystem ( true ) ; job . schedule ( ) ; } protected void doLaunch ( IRubyElement rubyElement , String mode ) throws CoreException { ILaunchConfiguration config = findOrCreateLaunchConfiguration ( rubyElement , mode ) ; if ( config != null ) { DebugUITools . launch ( config , mode ) ; } } public void launch ( IEditorPart editor , String mode ) { IEditorInput input = editor . getEditorInput ( ) ; if ( input == null ) { log ( "" + editor . getTitle ( ) ) ; return ; } IRubyElement rubyElement = ( IRubyElement ) input . getAdapter ( IRubyElement . class ) ; if ( rubyElement == null ) { log ( "" ) ; return ; } doLaunchWithErrorHandling ( rubyElement , mode ) ; } protected ILaunchConfiguration findOrCreateLaunchConfiguration ( IRubyElement rubyElement , String mode ) throws CoreException { IFile rubyFile = ( IFile ) rubyElement . getUnderlyingResource ( ) ; ILaunchConfigurationType configType = getRubyLaunchConfigType ( ) ; List candidateConfigs = null ; ILaunchConfiguration [ ] configs = getLaunchManager ( ) . getLaunchConfigurations ( configType ) ; candidateConfigs = new ArrayList ( configs . length ) ; for ( int i = ; i < configs . length ; i ++ ) { ILaunchConfiguration config = configs [ i ] ; boolean projectsEqual = config . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , "" ) . equals ( rubyFile . getProject ( ) . getName ( ) ) ; if ( projectsEqual ) { boolean projectRelativeFileNamesEqual = config . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , "" ) . equals ( rubyFile . getProjectRelativePath ( ) . toString ( ) ) ; if ( projectRelativeFileNamesEqual ) { candidateConfigs . add ( config ) ; } } } switch ( candidateConfigs . size ( ) ) { case : return createConfiguration ( rubyFile ) ; case : return ( ILaunchConfiguration ) candidateConfigs . get ( ) ; default : Status status = new Status ( Status . WARNING , RdtDebugUiPlugin . PLUGIN_ID , , RdtDebugUiMessages . LaunchConfigurationShortcut_Ruby_multipleConfigurationsError , null ) ; throw new CoreException ( status ) ; } } protected ILaunchConfiguration createConfiguration ( IFile rubyFile ) { if ( RubyRuntime . getDefaultVMInstall ( ) == null ) { this . showNoInterpreterDialog ( ) ; return null ; } ILaunchConfiguration config = null ; try { ILaunchConfigurationType configType = getRubyLaunchConfigType ( ) ; ILaunchConfigurationWorkingCopy wc = configType . newInstance ( null , getLaunchManager ( ) . generateUniqueLaunchConfigurationNameFrom ( rubyFile . getName ( ) ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , rubyFile . getProject ( ) . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , rubyFile . getProjectRelativePath ( ) . toString ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , RubyApplicationShortcut . getDefaultWorkingDirectory ( rubyFile . getProject ( ) ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , RubyRuntime . getDefaultVMInstall ( ) . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE , RubyRuntime . getDefaultVMInstall ( ) . getVMInstallType ( ) . getId ( ) ) ; wc . setAttribute ( ILaunchConfiguration . ATTR_SOURCE_LOCATOR_ID , RdtDebugUiConstants . RUBY_SOURCE_LOCATOR ) ; config = wc . doSave ( ) ; } catch ( CoreException ce ) { log ( ce ) ; } return config ; } protected ILaunchConfigurationType getRubyLaunchConfigType ( ) { return getLaunchManager ( ) . getLaunchConfigurationType ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ; } protected ILaunchManager getLaunchManager ( ) { return DebugPlugin . getDefault ( ) . getLaunchManager ( ) ; } protected void log ( String message ) { RdtDebugUiPlugin . log ( new Status ( Status . INFO , RdtDebugUiPlugin . PLUGIN_ID , Status . INFO , message , null ) ) ; } protected void log ( Throwable t ) { RdtDebugUiPlugin . log ( t ) ; } protected void showNoInterpreterDialog ( ) { MessageDialog . openInformation ( RubyPlugin . getActiveWorkbenchShell ( ) , RdtDebugUiMessages . Dialog_launchWithoutSelectedInterpreter_title , RdtDebugUiMessages . Dialog_launchWithoutSelectedInterpreter ) ; } protected static String getDefaultWorkingDirectory ( IProject project ) { if ( project != null && project . exists ( ) ) { return project . getLocation ( ) . toOSString ( ) ; } return RdtDebugUiPlugin . getWorkspace ( ) . getRoot ( ) . getLocation ( ) . toOSString ( ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . ui . AbstractLaunchConfigurationTab ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . debug . ui . RdtDebugUiImages ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . launching . RubyLaunchConfigurationAttribute ; import org . rubypeople . rdt . internal . ui . util . DirectorySelector ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class RubyArgumentsTab extends AbstractLaunchConfigurationTab { protected Text interpreterArgsText , programArgsText ; protected DirectorySelector workingDirectorySelector ; protected Button useDefaultWorkingDirectoryButton ; public RubyArgumentsTab ( ) { super ( ) ; } public void createControl ( Composite parent ) { Composite composite = createPageRoot ( parent ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_working_dir ) ; workingDirectorySelector = new DirectorySelector ( composite ) ; workingDirectorySelector . setBrowseDialogMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_working_dir_browser_message ) ; workingDirectorySelector . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; workingDirectorySelector . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { updateLaunchConfigurationDialog ( ) ; } } ) ; Composite defaultWorkingDirectoryComposite = new Composite ( composite , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; defaultWorkingDirectoryComposite . setLayout ( layout ) ; useDefaultWorkingDirectoryButton = new Button ( defaultWorkingDirectoryComposite , SWT . CHECK ) ; useDefaultWorkingDirectoryButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { setUseDefaultWorkingDirectory ( ( ( Button ) e . getSource ( ) ) . getSelection ( ) ) ; } } ) ; new Label ( defaultWorkingDirectoryComposite , SWT . NONE ) . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_working_dir_use_default_message ) ; defaultWorkingDirectoryComposite . pack ( ) ; Label verticalSpacer = new Label ( composite , SWT . NONE ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_interpreter_args_box_title ) ; interpreterArgsText = new Text ( composite , SWT . MULTI | SWT . V_SCROLL | SWT . BORDER ) ; interpreterArgsText . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; interpreterArgsText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent evt ) { updateLaunchConfigurationDialog ( ) ; } } ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_program_args_box_title ) ; programArgsText = new Text ( composite , SWT . MULTI | SWT . V_SCROLL | SWT . BORDER ) ; programArgsText . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; programArgsText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent evt ) { updateLaunchConfigurationDialog ( ) ; } } ) ; } protected void setUseDefaultWorkingDirectory ( boolean useDefault ) { if ( useDefaultWorkingDirectoryButton . getSelection ( ) != useDefault ) useDefaultWorkingDirectoryButton . setSelection ( useDefault ) ; if ( useDefault ) { workingDirectorySelector . setSelectionText ( ( String ) "" ) ; } workingDirectorySelector . setEnabled ( ! useDefault ) ; } public void setDefaults ( ILaunchConfigurationWorkingCopy configuration ) { configuration . setAttribute ( RubyLaunchConfigurationAttribute . USE_DEFAULT_WORKING_DIRECTORY , true ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , ( String ) null ) ; configuration . setAttribute ( ILaunchConfiguration . ATTR_SOURCE_LOCATOR_ID , RdtDebugUiConstants . RUBY_SOURCE_LOCATOR ) ; } public void initializeFrom ( ILaunchConfiguration configuration ) { String workingDirectory = "" , interpreterArgs = "" , programArgs = "" ; boolean useDefaultWorkDir = true ; try { workingDirectory = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , "" ) ; interpreterArgs = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_ARGUMENTS , "" ) ; programArgs = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROGRAM_ARGUMENTS , "" ) ; useDefaultWorkDir = configuration . getAttribute ( RubyLaunchConfigurationAttribute . USE_DEFAULT_WORKING_DIRECTORY , true ) ; } catch ( CoreException e ) { log ( e ) ; } workingDirectorySelector . setSelectionText ( workingDirectory ) ; interpreterArgsText . setText ( interpreterArgs ) ; programArgsText . setText ( programArgs ) ; setUseDefaultWorkingDirectory ( useDefaultWorkDir ) ; } public void performApply ( ILaunchConfigurationWorkingCopy configuration ) { configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , workingDirectorySelector . getValidatedSelectionText ( ) ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_ARGUMENTS , interpreterArgsText . getText ( ) ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROGRAM_ARGUMENTS , programArgsText . getText ( ) ) ; configuration . setAttribute ( RubyLaunchConfigurationAttribute . USE_DEFAULT_WORKING_DIRECTORY , useDefaultWorkingDirectoryButton . getSelection ( ) ) ; } protected Composite createPageRoot ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout compositeLayout = new GridLayout ( ) ; compositeLayout . marginWidth = ; compositeLayout . numColumns = ; composite . setLayout ( compositeLayout ) ; setControl ( composite ) ; return composite ; } public String getName ( ) { return RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_name ; } public boolean isValid ( ILaunchConfiguration launchConfig ) { try { String workingDirectory = launchConfig . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , "" ) ; if ( ! useDefaultWorkingDirectoryButton ( ) && workingDirectory . length ( ) == ) { setErrorMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_working_dir_error_message ) ; return false ; } } catch ( CoreException e ) { log ( e ) ; } setErrorMessage ( null ) ; return true ; } private boolean useDefaultWorkingDirectoryButton ( ) { if ( useDefaultWorkingDirectoryButton == null ) return false ; return useDefaultWorkingDirectoryButton . getSelection ( ) ; } protected void log ( Throwable t ) { RdtDebugUiPlugin . log ( t ) ; } public Image getImage ( ) { return RdtDebugUiImages . get ( RdtDebugUiImages . IMG_EVIEW_ARGUMENTS_TAB ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . QualifiedName ; public class ExecutionArguments { protected static final QualifiedName EXECUTION_ARGUMENTS_PROPERTY = new QualifiedName ( "" , "" ) ; protected static final String ARGUMENT_SEPARATOR = "" ; protected String interpreterArguments , rubyFileArguments ; public static ExecutionArguments getExecutionArguments ( IFile rubyScriptFile ) { try { String executionArgumentsPersistableFormat = rubyScriptFile . getPersistentProperty ( EXECUTION_ARGUMENTS_PROPERTY ) ; ExecutionArguments executionArguments = new ExecutionArguments ( ) ; if ( executionArgumentsPersistableFormat != null ) { int argBreakIndex = executionArgumentsPersistableFormat . indexOf ( ARGUMENT_SEPARATOR ) ; executionArguments . setInterpreterArguments ( executionArgumentsPersistableFormat . substring ( , argBreakIndex ) ) ; executionArguments . setRubyFileArguments ( executionArgumentsPersistableFormat . substring ( argBreakIndex + ARGUMENT_SEPARATOR . length ( ) ) ) ; } return executionArguments ; } catch ( CoreException e ) { } return null ; } public static void setExecutionArguments ( IFile rubyScriptFile , ExecutionArguments arguments ) { try { rubyScriptFile . setPersistentProperty ( EXECUTION_ARGUMENTS_PROPERTY , arguments . toPersistableFormat ( ) ) ; } catch ( CoreException e ) { } } public void setInterpreterArguments ( String theArguments ) { interpreterArguments = theArguments ; } public void setRubyFileArguments ( String theArguments ) { rubyFileArguments = theArguments ; } public String toPersistableFormat ( ) { return interpreterArguments + ARGUMENT_SEPARATOR + rubyFileArguments ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IPath ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . RubyRuntime ; public class LoadPathContentProvider implements IStructuredContentProvider { public void dispose ( ) { } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } public Object [ ] getElements ( Object inputElement ) { if ( ! ( inputElement instanceof ILoadpathEntry [ ] ) ) return null ; List < Object > children = new ArrayList < Object > ( ) ; IVMInstall vm = RubyRuntime . getDefaultVMInstall ( ) ; IPath [ ] libraryLocations = vm . getLibraryLocations ( ) ; ILoadpathEntry [ ] entries = ( ILoadpathEntry [ ] ) inputElement ; for ( ILoadpathEntry loadpathEntry : entries ) { if ( loadpathEntry . getEntryKind ( ) == ILoadpathEntry . CPE_LIBRARY && contains ( libraryLocations , loadpathEntry . getPath ( ) ) ) { continue ; } children . add ( loadpathEntry ) ; } return ( Object [ ] ) children . toArray ( new Object [ children . size ( ) ] ) ; } private boolean contains ( IPath [ ] libraryLocations , IPath path ) { for ( IPath libraryPath : libraryLocations ) { if ( libraryPath . equals ( path ) ) return true ; } return false ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import java . io . File ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . ui . AbstractLaunchConfigurationTab ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . util . ProjectFileSelector ; import org . rubypeople . rdt . internal . ui . util . RubyProjectSelector ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class RubyEntryPointTab extends AbstractLaunchConfigurationTab { protected String originalFileName , originalProjectName ; protected RubyProjectSelector projectSelector ; protected ProjectFileSelector fileSelector ; protected Composite composite ; public RubyEntryPointTab ( ) { super ( ) ; } public void createControl ( Composite parent ) { composite = createPageRoot ( parent ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_projectLabel ) ; projectSelector = new RubyProjectSelector ( composite ) ; projectSelector . setBrowseDialogMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_projectSelectorMessage ) ; projectSelector . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; projectSelector . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent evt ) { updateLaunchConfigurationDialog ( ) ; } } ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_fileLabel ) ; fileSelector = new ProjectFileSelector ( composite , projectSelector ) ; fileSelector . setBrowseDialogMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_fileSelectorMessage ) ; fileSelector . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; fileSelector . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent evt ) { updateLaunchConfigurationDialog ( ) ; } } ) ; } public void setDefaults ( ILaunchConfigurationWorkingCopy configuration ) { IResource selectedResource = RubyPlugin . getDefault ( ) . getSelectedResource ( ) ; if ( ! RubyPlugin . getDefault ( ) . isRubyFile ( selectedResource ) ) { return ; } IProject project = selectedResource . getProject ( ) ; if ( project == null || ! RubyCore . isRubyProject ( project ) ) { return ; } configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , project . getName ( ) ) ; configuration . setAttribute ( getFileToLaunchAttribute ( ) , modifyFileToLaunch ( selectedResource . getProjectRelativePath ( ) . toString ( ) ) ) ; } public void initializeFrom ( ILaunchConfiguration configuration ) { try { originalProjectName = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , "" ) ; } catch ( CoreException e ) { log ( e ) ; } projectSelector . setSelectionText ( originalProjectName ) ; try { originalFileName = handleFileName ( configuration . getAttribute ( getFileToLaunchAttribute ( ) , "" ) ) ; } catch ( CoreException e ) { log ( e ) ; } if ( originalFileName . length ( ) != ) { fileSelector . setSelectionText ( new Path ( originalFileName ) . toOSString ( ) ) ; } } protected String handleFileName ( String filename ) { return filename ; } public void performApply ( ILaunchConfigurationWorkingCopy configuration ) { configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , projectSelector . getSelectionText ( ) ) ; String text = fileSelector . getSelectionText ( ) ; String workingDirectory = null ; try { workingDirectory = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , ( String ) null ) ; } catch ( CoreException e ) { RdtDebugUiPlugin . log ( e ) ; } if ( fileExists ( text , workingDirectory ) ) { configuration . setAttribute ( getFileToLaunchAttribute ( ) , modifyFileToLaunch ( text ) ) ; } else { configuration . setAttribute ( getFileToLaunchAttribute ( ) , modifyFileToLaunch ( "" ) ) ; } } protected String modifyFileToLaunch ( String text ) { return text ; } protected Composite createPageRoot ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . marginWidth = ; composite . setLayout ( layout ) ; setControl ( composite ) ; return composite ; } public String getName ( ) { return RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_name ; } public boolean isValid ( ILaunchConfiguration launchConfig ) { try { if ( ! super . isValid ( launchConfig ) ) return false ; String projectName = launchConfig . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , "" ) ; if ( projectName . length ( ) == ) { setErrorMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidProjectSelectionMessage ) ; return false ; } IProject project = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; if ( project == null ) { setErrorMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidProjectSelectionMessage ) ; return false ; } if ( ! project . exists ( ) ) { setErrorMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidProjectSelectionMessage ) ; return false ; } String fileName = handleFileName ( launchConfig . getAttribute ( getFileToLaunchAttribute ( ) , "" ) ) ; if ( fileName . length ( ) == ) { setErrorMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidFileSelectionMessage ) ; return false ; } String workingDirectory = null ; try { workingDirectory = launchConfig . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , ( String ) null ) ; } catch ( CoreException e ) { RdtDebugUiPlugin . log ( e ) ; } if ( ! fileExists ( fileName , workingDirectory ) ) { setErrorMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidFileSelectionMessage ) ; return false ; } setErrorMessage ( null ) ; return true ; } catch ( CoreException e ) { setErrorMessage ( e . getMessage ( ) ) ; RdtDebugUiPlugin . log ( e ) ; } return false ; } protected String getFileToLaunchAttribute ( ) { return IRubyLaunchConfigurationConstants . ATTR_FILE_NAME ; } private boolean fileExists ( String text , String workingDirectory ) { File test = new File ( text ) ; if ( test . exists ( ) ) return true ; if ( workingDirectory != null && ! workingDirectory . trim ( ) . equals ( "" ) ) { if ( new File ( workingDirectory + text ) . exists ( ) ) return true ; } IProject project = getProject ( ) ; if ( project == null || project . getLocation ( ) == null ) return false ; IPath path = project . getLocation ( ) . append ( text ) ; if ( path == null || path . toFile ( ) == null ) return false ; return path . toFile ( ) . exists ( ) ; } protected IProject getProject ( ) { String projectName = projectSelector . getSelectionText ( ) ; if ( projectName == null || projectName . trim ( ) . length ( ) == ) { return null ; } return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; } protected void log ( Throwable t ) { RdtDebugUiPlugin . log ( t ) ; } public boolean canSave ( ) { return getErrorMessage ( ) == null ; } public Image getImage ( ) { return RubyPluginImages . get ( RubyPluginImages . IMG_CTOOLS_RUBY_PAGE ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . debug . ui . AbstractLaunchConfigurationTabGroup ; import org . eclipse . debug . ui . CommonTab ; import org . eclipse . debug . ui . EnvironmentTab ; import org . eclipse . debug . ui . ILaunchConfigurationDialog ; import org . eclipse . debug . ui . ILaunchConfigurationTab ; public class RubyApplicationTabGroup extends AbstractLaunchConfigurationTabGroup { public RubyApplicationTabGroup ( ) { super ( ) ; } public void createTabs ( ILaunchConfigurationDialog dialog , String mode ) { ILaunchConfigurationTab [ ] tabs = new ILaunchConfigurationTab [ ] { new RubyEntryPointTab ( ) , new RubyArgumentsTab ( ) , new RubyEnvironmentTab ( ) , new EnvironmentTab ( ) , new CommonTab ( ) } ; setTabs ( tabs ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . debug . ui . AbstractLaunchConfigurationTabGroup ; import org . eclipse . debug . ui . CommonTab ; import org . eclipse . debug . ui . ILaunchConfigurationDialog ; import org . eclipse . debug . ui . ILaunchConfigurationTab ; import org . eclipse . debug . ui . sourcelookup . SourceLookupTab ; import org . rubypeople . rdt . debug . ui . launchConfigurations . RubyConnectTab ; public class RemoteRubyApplicationTabGroup extends AbstractLaunchConfigurationTabGroup { public void createTabs ( ILaunchConfigurationDialog dialog , String mode ) { ILaunchConfigurationTab [ ] tabs = new ILaunchConfigurationTab [ ] { new RubyConnectTab ( ) , new SourceLookupTab ( ) , new CommonTab ( ) , } ; setTabs ( tabs ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . ui . AbstractLaunchConfigurationTab ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ListViewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . DirectoryDialog ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . TabFolder ; import org . eclipse . swt . widgets . TabItem ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . core . RubyModelManager ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . debug . ui . rubyvms . AddVMDialog ; import org . rubypeople . rdt . internal . debug . ui . rubyvms . IAddVMDialogRequestor ; import org . rubypeople . rdt . internal . debug . ui . rubyvms . RubyVMMessages ; import org . rubypeople . rdt . internal . launching . RubyLaunchConfigurationAttribute ; import org . rubypeople . rdt . internal . launching . RuntimeLoadpathEntry ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; public class RubyEnvironmentTab extends AbstractLaunchConfigurationTab implements SelectionListener { protected ListViewer loadPathListViewer ; protected List < IVMInstall > installedInterpretersWorkingCopy ; protected Combo interpreterCombo ; protected Button loadPathDefaultButton ; private Button fAddButton ; private Button fRemoveButton ; private Button fUpButton ; private Button fDownButton ; public RubyEnvironmentTab ( ) { super ( ) ; } public void createControl ( Composite parent ) { Composite composite = createPageRoot ( parent ) ; TabFolder tabFolder = new TabFolder ( composite , SWT . NONE ) ; GridData gridData = new GridData ( GridData . FILL_BOTH ) ; tabFolder . setLayoutData ( gridData ) ; addLoadPathTab ( tabFolder ) ; addInterpreterTab ( tabFolder ) ; } protected void addLoadPathTab ( TabFolder tabFolder ) { Composite comp = new Composite ( tabFolder , SWT . NONE ) ; GridLayout topLayout = new GridLayout ( ) ; topLayout . numColumns = ; topLayout . marginHeight = ; topLayout . marginWidth = ; comp . setLayout ( topLayout ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; comp . setLayoutData ( gd ) ; loadPathListViewer = new ListViewer ( comp , SWT . BORDER | SWT . MULTI | SWT . V_SCROLL | SWT . H_SCROLL ) ; loadPathListViewer . setContentProvider ( new LoadPathContentProvider ( ) ) ; loadPathListViewer . setLabelProvider ( new LoadPathEntryLabelProvider ( ) ) ; loadPathListViewer . getList ( ) . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; Composite pathButtonComp = new Composite ( comp , SWT . NONE ) ; GridLayout pathButtonLayout = new GridLayout ( ) ; pathButtonLayout . marginHeight = ; pathButtonLayout . marginWidth = ; pathButtonComp . setLayout ( pathButtonLayout ) ; gd = new GridData ( GridData . VERTICAL_ALIGN_BEGINNING | GridData . HORIZONTAL_ALIGN_FILL ) ; pathButtonComp . setLayoutData ( gd ) ; fAddButton = createPushButton ( pathButtonComp , "" ) ; fAddButton . addSelectionListener ( this ) ; fRemoveButton = createPushButton ( pathButtonComp , "" ) ; fRemoveButton . addSelectionListener ( this ) ; fUpButton = createPushButton ( pathButtonComp , RubyVMMessages . VMLibraryBlock_4 ) ; fUpButton . addSelectionListener ( this ) ; fDownButton = createPushButton ( pathButtonComp , RubyVMMessages . VMLibraryBlock_5 ) ; fDownButton . addSelectionListener ( this ) ; loadPathDefaultButton = new Button ( comp , SWT . CHECK ) ; loadPathDefaultButton . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEnvironment_loadPathDefaultButton_label ) ; loadPathDefaultButton . setLayoutData ( new GridData ( GridData . HORIZONTAL_ALIGN_BEGINNING ) ) ; loadPathDefaultButton . addSelectionListener ( getLoadPathDefaultButtonSelectionListener ( ) ) ; loadPathDefaultButton . setEnabled ( true ) ; TabItem loadPathTab = new TabItem ( tabFolder , SWT . NONE , ) ; loadPathTab . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEnvironment_loadPathTab_label ) ; loadPathTab . setControl ( comp ) ; loadPathTab . setData ( loadPathListViewer ) ; } protected Button createPushButton ( Composite parent , String label ) { Button button = new Button ( parent , SWT . PUSH ) ; button . setFont ( parent . getFont ( ) ) ; button . setText ( label ) ; return button ; } protected SelectionListener getLoadPathSelectionListener ( ) { return new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { System . out . println ( "" + e . getSource ( ) ) ; } } ; } protected SelectionListener getLoadPathDefaultButtonSelectionListener ( ) { return new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { setUseLoadPathDefaults ( ( ( Button ) e . getSource ( ) ) . getSelection ( ) ) ; } } ; } protected void addInterpreterTab ( TabFolder tabFolder ) { Composite interpreterComposite = new Composite ( tabFolder , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginHeight = ; layout . marginWidth = ; interpreterComposite . setLayout ( layout ) ; interpreterComposite . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; createVerticalSpacer ( interpreterComposite , ) ; interpreterCombo = new Combo ( interpreterComposite , SWT . READ_ONLY ) ; interpreterCombo . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; initializeInterpreterCombo ( interpreterCombo ) ; interpreterCombo . addModifyListener ( getInterpreterComboModifyListener ( ) ) ; Button interpreterAddButton = new Button ( interpreterComposite , SWT . PUSH ) ; interpreterAddButton . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEnvironment_interpreterAddButton_label ) ; interpreterAddButton . addSelectionListener ( new AddInterpreterSelectionAdapter ( interpreterCombo , getShell ( ) ) ) ; TabItem interpreterTab = new TabItem ( tabFolder , SWT . NONE ) ; interpreterTab . setText ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEnvironment_interpreterTab_label ) ; interpreterTab . setControl ( interpreterComposite ) ; } private static class AddInterpreterSelectionAdapter extends SelectionAdapter implements IAddVMDialogRequestor { private Combo fCombo ; private Shell fShell ; public AddInterpreterSelectionAdapter ( Combo combo , Shell shell ) { fCombo = combo ; fShell = shell ; } public void widgetSelected ( SelectionEvent evt ) { AddVMDialog dialog = new AddVMDialog ( this , fShell , RubyRuntime . getVMInstallTypes ( ) , null ) ; dialog . setTitle ( RubyVMMessages . InstalledJREsBlock_7 ) ; if ( dialog . open ( ) != Window . OK ) { return ; } } public boolean isDuplicateName ( String name ) { return false ; } public void vmAdded ( IVMInstall vm ) { if ( vm instanceof VMStandin ) { VMStandin standin = ( VMStandin ) vm ; standin . convertToRealVM ( ) ; } fCombo . add ( vm . getName ( ) ) ; fCombo . select ( fCombo . indexOf ( vm . getName ( ) ) ) ; } } protected ModifyListener getInterpreterComboModifyListener ( ) { return new ModifyListener ( ) { public void modifyText ( ModifyEvent evt ) { updateLaunchConfigurationDialog ( ) ; } } ; } protected void createVerticalSpacer ( Composite comp , int colSpan ) { Label label = new Label ( comp , SWT . NONE ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = colSpan ; label . setLayoutData ( gd ) ; } public void setDefaults ( ILaunchConfigurationWorkingCopy configuration ) { IVMInstall defaultInterpreter = RubyRuntime . getDefaultVMInstall ( ) ; if ( defaultInterpreter != null ) { configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , defaultInterpreter . getName ( ) ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE , defaultInterpreter . getVMInstallType ( ) . getId ( ) ) ; } } public void initializeFrom ( ILaunchConfiguration configuration ) { initializeLoadPath ( configuration ) ; initializeInterpreterSelection ( configuration ) ; } protected void initializeLoadPath ( ILaunchConfiguration configuration ) { boolean useDefaultLoadPath = true ; try { useDefaultLoadPath = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_DEFAULT_LOADPATH , true ) ; setUseLoadPathDefaults ( useDefaultLoadPath ) ; if ( useDefaultLoadPath ) { String projectName = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , "" ) ; if ( projectName . length ( ) != ) { IRubyProject project = RubyModelManager . getRubyModelManager ( ) . getRubyModel ( ) . getRubyProject ( projectName ) ; if ( project != null ) { ILoadpathEntry [ ] entries = project . getRawLoadpath ( ) ; entries = filterStandard ( entries ) ; loadPathListViewer . setInput ( entries ) ; } } } else { List < String > entries = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_LOADPATH , Collections . EMPTY_LIST ) ; ILoadpathEntry [ ] rtes = new ILoadpathEntry [ entries . size ( ) ] ; int i = ; for ( String entry : entries ) { rtes [ i ] = RubyRuntime . newRuntimeLoadpathEntry ( entry ) . getLoadpathEntry ( ) ; i ++ ; } loadPathListViewer . setInput ( rtes ) ; } } catch ( CoreException e ) { log ( e ) ; } } private ILoadpathEntry [ ] filterStandard ( ILoadpathEntry [ ] entries ) { List < ILoadpathEntry > copy = new ArrayList < ILoadpathEntry > ( ) ; for ( ILoadpathEntry loadpathEntry : entries ) { if ( ( loadpathEntry . getEntryKind ( ) == ILoadpathEntry . CPE_VARIABLE ) || ( loadpathEntry . getEntryKind ( ) == ILoadpathEntry . CPE_CONTAINER ) ) continue ; copy . add ( loadpathEntry ) ; } return copy . toArray ( new ILoadpathEntry [ copy . size ( ) ] ) ; } protected void setUseLoadPathDefaults ( boolean useDefaults ) { loadPathListViewer . getList ( ) . setEnabled ( ! useDefaults ) ; fAddButton . setEnabled ( ! useDefaults ) ; fRemoveButton . setEnabled ( ! useDefaults ) ; fUpButton . setEnabled ( ! useDefaults ) ; fDownButton . setEnabled ( ! useDefaults ) ; loadPathDefaultButton . setSelection ( useDefaults ) ; setDirty ( true ) ; updateLaunchConfigurationDialog ( ) ; } protected void initializeInterpreterSelection ( ILaunchConfiguration configuration ) { String interpreterName = null ; try { interpreterName = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , ( String ) null ) ; } catch ( CoreException e ) { log ( e ) ; } if ( interpreterName != null && ! interpreterName . equals ( "" ) ) interpreterCombo . select ( interpreterCombo . indexOf ( interpreterName ) ) ; } protected void initializeInterpreterCombo ( Combo interpreterCombo ) { installedInterpretersWorkingCopy = new ArrayList < IVMInstall > ( ) ; List < IVMInstall > standins = new ArrayList < IVMInstall > ( ) ; IVMInstallType [ ] types = RubyRuntime . getVMInstallTypes ( ) ; for ( int i = ; i < types . length ; i ++ ) { IVMInstallType type = types [ i ] ; IVMInstall [ ] installs = type . getVMInstalls ( ) ; for ( int j = ; j < installs . length ; j ++ ) { IVMInstall install = installs [ j ] ; standins . add ( new VMStandin ( install ) ) ; } } installedInterpretersWorkingCopy . addAll ( standins ) ; String [ ] interpreterNames = new String [ installedInterpretersWorkingCopy . size ( ) ] ; for ( int interpreterIndex = ; interpreterIndex < installedInterpretersWorkingCopy . size ( ) ; interpreterIndex ++ ) { IVMInstall interpreter = ( IVMInstall ) installedInterpretersWorkingCopy . get ( interpreterIndex ) ; interpreterNames [ interpreterIndex ] = interpreter . getName ( ) ; } interpreterCombo . setItems ( interpreterNames ) ; IVMInstall selectedInterpreter = RubyRuntime . getDefaultVMInstall ( ) ; if ( selectedInterpreter != null ) interpreterCombo . select ( interpreterCombo . indexOf ( selectedInterpreter . getName ( ) ) ) ; } public void performApply ( ILaunchConfigurationWorkingCopy configuration ) { int selectionIndex = interpreterCombo . getSelectionIndex ( ) ; if ( selectionIndex >= ) { IVMInstall vm = installedInterpretersWorkingCopy . get ( selectionIndex ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , vm . getName ( ) ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE , vm . getVMInstallType ( ) . getId ( ) ) ; } setAttribute ( IRubyLaunchConfigurationConstants . ATTR_DEFAULT_LOADPATH , configuration , loadPathDefaultButton . getSelection ( ) , true ) ; if ( ! loadPathDefaultButton . getSelection ( ) ) { ILoadpathEntry [ ] loadPathEntries = ( ILoadpathEntry [ ] ) loadPathListViewer . getInput ( ) ; List < String > loadPathStrings = new ArrayList < String > ( ) ; for ( int i = ; i < loadPathEntries . length ; i ++ ) { try { ILoadpathEntry entry = loadPathEntries [ i ] ; if ( entry . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { if ( entry . getPath ( ) . equals ( new Path ( "" + configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , "" ) ) ) ) { continue ; } } IRuntimeLoadpathEntry runtime = new RuntimeLoadpathEntry ( entry ) ; loadPathStrings . add ( runtime . getMemento ( ) ) ; } catch ( CoreException e ) { log ( e ) ; } } configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_LOADPATH , loadPathStrings ) ; } } protected Composite createPageRoot ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; createVerticalSpacer ( composite , ) ; setControl ( composite ) ; return composite ; } public String getName ( ) { return RdtDebugUiMessages . LaunchConfigurationTab_RubyEnvironment_name ; } public boolean isValid ( ILaunchConfiguration launchConfig ) { try { String selectedInterpreter = launchConfig . getAttribute ( RubyLaunchConfigurationAttribute . SELECTED_INTERPRETER , "" ) ; if ( selectedInterpreter . length ( ) == ) { setErrorMessage ( RdtDebugUiMessages . LaunchConfigurationTab_RubyEnvironment_interpreter_not_selected_error_message ) ; return false ; } } catch ( CoreException e ) { log ( e ) ; } setErrorMessage ( null ) ; return true ; } protected void log ( Throwable t ) { RdtDebugUiPlugin . log ( t ) ; } public Image getImage ( ) { return RubyPluginImages . get ( RubyPluginImages . IMG_CTOOLS_RUBY ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { if ( e . getSource ( ) . equals ( fAddButton ) ) { DirectoryDialog dialog = new DirectoryDialog ( getShell ( ) ) ; String result = dialog . open ( ) ; if ( result != null ) { ILoadpathEntry [ ] loadPathEntries = ( ILoadpathEntry [ ] ) loadPathListViewer . getInput ( ) ; ILoadpathEntry [ ] copy = new ILoadpathEntry [ loadPathEntries . length + ] ; System . arraycopy ( loadPathEntries , , copy , , loadPathEntries . length ) ; copy [ loadPathEntries . length ] = RubyCore . newLibraryEntry ( new Path ( result ) ) ; loadPathListViewer . setInput ( copy ) ; } } else if ( e . getSource ( ) . equals ( fRemoveButton ) ) { ISelection selection = loadPathListViewer . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { IStructuredSelection structured = ( IStructuredSelection ) selection ; ILoadpathEntry firstElement = ( ILoadpathEntry ) structured . getFirstElement ( ) ; ILoadpathEntry [ ] loadPathEntries = ( ILoadpathEntry [ ] ) loadPathListViewer . getInput ( ) ; ILoadpathEntry [ ] copy = new ILoadpathEntry [ loadPathEntries . length - ] ; int i = ; for ( ILoadpathEntry entry : loadPathEntries ) { if ( entry . equals ( firstElement ) ) continue ; copy [ i ++ ] = entry ; } loadPathListViewer . setInput ( copy ) ; } } } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public class LoadPathEntryLabelProvider implements ILabelProvider { public Image getImage ( Object element ) { return null ; } public String getText ( Object element ) { if ( element != null && element instanceof ILoadpathEntry ) { ILoadpathEntry entry = ( ILoadpathEntry ) element ; return entry . getPath ( ) . toOSString ( ) ; } RdtDebugUiPlugin . log ( new RuntimeException ( "" ) ) ; return null ; } public void addListener ( ILabelProviderListener listener ) { } public void dispose ( ) { } public boolean isLabelProperty ( Object element , String property ) { return false ; } public void removeListener ( ILabelProviderListener listener ) { } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . osgi . util . NLS ; public class LauncherMessages extends NLS { private static final String BUNDLE_NAME = "" ; public static String AbstractRubyMainTab_0 ; public static String AbstractRubyMainTab_1 ; public static String AbstractRubyMainTab_4 ; public static String AbstractRubyMainTab_3 ; public static String RubyConnectTab_Connect_ion_Type__7 ; public static String RubyConnectTab_Connection_Properties_1 ; public static String RubyConnectTab_Unable_to_display_connection_arguments__2 ; public static String RubyConnectTab_Project_does_not_exist_14 ; public static String RubyConnectTab__is_invalid__5 ; public static String RubyConnectTab_Conn_ect_20 ; static { NLS . initializeMessages ( BUNDLE_NAME , LauncherMessages . class ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import java . lang . reflect . InvocationTargetException ; import java . util . Collection ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubMonitor ; import org . eclipse . jface . dialogs . MessageDialogWithToggle ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . jface . operation . IRunnableWithProgress ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . ContributedGemRegistry ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . IGemManager ; public class InstallGemsJob extends UIJob { Collection < Gem > finalGems ; public InstallGemsJob ( Collection < Gem > finalGems ) { super ( "" ) ; this . finalGems = finalGems ; } public IStatus runInUIThread ( IProgressMonitor monitor ) { if ( ! getGemManager ( ) . isRubyGemsInstalled ( ) ) { IPreferenceStore store = RdtDebugUiPlugin . getDefault ( ) . getPreferenceStore ( ) ; String key = "" ; if ( ! store . getString ( key ) . equals ( MessageDialogWithToggle . ALWAYS ) ) { MessageDialogWithToggle . openWarning ( Display . getDefault ( ) . getActiveShell ( ) , "" , "" , "" , false , store , key ) ; } return Status . OK_STATUS ; } try { ProgressMonitorDialog progressDialog = new ProgressMonitorDialog ( Display . getDefault ( ) . getActiveShell ( ) ) ; progressDialog . run ( true , true , new InstallGemsRunnableWithProgress ( finalGems ) ) ; } catch ( InvocationTargetException e ) { AptanaRDTPlugin . log ( e ) ; } catch ( InterruptedException e ) { AptanaRDTPlugin . log ( e ) ; } return Status . OK_STATUS ; } private class InstallGemsRunnableWithProgress implements IRunnableWithProgress { private Collection < Gem > finalGems ; public InstallGemsRunnableWithProgress ( Collection < Gem > finalGems ) { this . finalGems = finalGems ; } public void run ( IProgressMonitor monitor ) throws InvocationTargetException , InterruptedException { SubMonitor progress = SubMonitor . convert ( monitor , ) ; progress . setTaskName ( "" ) ; if ( progress . isCanceled ( ) ) return ; List < Gem > sorted = ContributedGemRegistry . sortByDependency ( finalGems ) ; progress . worked ( ) ; if ( progress . isCanceled ( ) ) return ; if ( ! sorted . isEmpty ( ) ) { int step = ( int ) Math . floor ( / ( double ) sorted . size ( ) ) ; for ( Gem gem : sorted ) { if ( progress . isCanceled ( ) ) return ; getGemManager ( ) . installGem ( gem , progress . newChild ( step ) ) ; if ( gem . isLocal ( ) ) { gem . delete ( ) ; } } } progress . done ( ) ; } } protected IGemManager getGemManager ( ) { return AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . jface . viewers . ILabelProvider ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . dialogs . ElementListSelectionDialog ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . debug . ui . launchConfigurations . RubyLaunchTab ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . launching . RubyMigrationDelegate ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . ui . RubyElementLabelProvider ; public abstract class AbstractRubyMainTab extends RubyLaunchTab { private class WidgetListener implements ModifyListener , SelectionListener { public void modifyText ( ModifyEvent e ) { updateLaunchConfigurationDialog ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { Object source = e . getSource ( ) ; if ( source == fProjButton ) { handleProjectButtonSelected ( ) ; } else { updateLaunchConfigurationDialog ( ) ; } } } protected static final String EMPTY_STRING = "" ; protected Text fProjText ; private Button fProjButton ; private WidgetListener fListener = new WidgetListener ( ) ; private IRubyProject chooseRubyProject ( ) { ILabelProvider labelProvider = new RubyElementLabelProvider ( RubyElementLabelProvider . SHOW_DEFAULT ) ; ElementListSelectionDialog dialog = new ElementListSelectionDialog ( getShell ( ) , labelProvider ) ; dialog . setTitle ( LauncherMessages . AbstractRubyMainTab_4 ) ; dialog . setMessage ( LauncherMessages . AbstractRubyMainTab_3 ) ; try { dialog . setElements ( RubyCore . create ( getWorkspaceRoot ( ) ) . getRubyProjects ( ) ) ; } catch ( RubyModelException jme ) { RdtDebugUiPlugin . log ( jme ) ; } IRubyProject javaProject = getRubyProject ( ) ; if ( javaProject != null ) { dialog . setInitialSelections ( new Object [ ] { javaProject } ) ; } if ( dialog . open ( ) == Window . OK ) { return ( IRubyProject ) dialog . getFirstResult ( ) ; } return null ; } protected void createProjectEditor ( Composite parent ) { Font font = parent . getFont ( ) ; Group group = new Group ( parent , SWT . NONE ) ; group . setText ( LauncherMessages . AbstractRubyMainTab_0 ) ; GridData gd = new GridData ( GridData . FILL_HORIZONTAL ) ; group . setLayoutData ( gd ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; group . setLayout ( layout ) ; group . setFont ( font ) ; fProjText = new Text ( group , SWT . SINGLE | SWT . BORDER ) ; gd = new GridData ( GridData . FILL_HORIZONTAL ) ; fProjText . setLayoutData ( gd ) ; fProjText . setFont ( font ) ; fProjText . addModifyListener ( fListener ) ; fProjButton = createPushButton ( group , LauncherMessages . AbstractRubyMainTab_1 , null ) ; fProjButton . addSelectionListener ( fListener ) ; } protected WidgetListener getDefaultListener ( ) { return fListener ; } private IRubyModel getRubyModel ( ) { return RubyCore . create ( getWorkspaceRoot ( ) ) ; } protected IRubyProject getRubyProject ( ) { String projectName = fProjText . getText ( ) . trim ( ) ; if ( projectName . length ( ) < ) { return null ; } return getRubyModel ( ) . getRubyProject ( projectName ) ; } protected IWorkspaceRoot getWorkspaceRoot ( ) { return ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; } protected void handleProjectButtonSelected ( ) { IRubyProject project = chooseRubyProject ( ) ; if ( project == null ) { return ; } String projectName = project . getElementName ( ) ; fProjText . setText ( projectName ) ; } public void initializeFrom ( ILaunchConfiguration config ) { updateProjectFromConfig ( config ) ; super . initializeFrom ( config ) ; } private void updateProjectFromConfig ( ILaunchConfiguration config ) { String projectName = EMPTY_STRING ; try { projectName = config . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , EMPTY_STRING ) ; } catch ( CoreException ce ) { setErrorMessage ( ce . getStatus ( ) . getMessage ( ) ) ; } fProjText . setText ( projectName ) ; } protected void mapResources ( ILaunchConfigurationWorkingCopy config ) { try { IRubyProject rubyProject = getRubyProject ( ) ; if ( rubyProject != null && rubyProject . exists ( ) && rubyProject . isOpen ( ) ) { RubyMigrationDelegate . updateResourceMapping ( config ) ; } } catch ( CoreException ce ) { setErrorMessage ( ce . getStatus ( ) . getMessage ( ) ) ; } } } package org . rubypeople . rdt . internal . debug . ui . display ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . ResourceBundle ; import org . eclipse . core . commands . operations . IUndoContext ; import org . eclipse . debug . ui . DebugUITools ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . IToolBarManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentListener ; import org . eclipse . jface . text . IFindReplaceTarget ; import org . eclipse . jface . text . ITextInputListener ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . IUndoManager ; import org . eclipse . jface . text . IUndoManagerExtension ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IMemento ; import org . eclipse . ui . IPerspectiveDescriptor ; import org . eclipse . ui . IPerspectiveListener2 ; import org . eclipse . ui . IViewReference ; import org . eclipse . ui . IViewSite ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPartReference ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . XMLMemento ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . commands . AbstractHandler ; import org . eclipse . ui . commands . ExecutionException ; import org . eclipse . ui . commands . HandlerSubmission ; import org . eclipse . ui . commands . IHandler ; import org . eclipse . ui . commands . IWorkbenchCommandSupport ; import org . eclipse . ui . commands . Priority ; import org . eclipse . ui . console . actions . ClearOutputAction ; import org . eclipse . ui . operations . OperationHistoryActionHandler ; import org . eclipse . ui . operations . RedoActionHandler ; import org . eclipse . ui . operations . UndoActionHandler ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . texteditor . FindReplaceAction ; import org . eclipse . ui . texteditor . IAbstractTextEditorHelpContextIds ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . eclipse . ui . texteditor . ITextEditorActionDefinitionIds ; import org . eclipse . ui . texteditor . IUpdate ; import org . eclipse . ui . texteditor . IWorkbenchActionDefinitionIds ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . debug . ui . RubyDebugSourceViewer ; import org . rubypeople . rdt . internal . debug . ui . actions . ExecuteAction ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; import org . rubypeople . rdt . ui . text . RubyTextTools ; public class DisplayView extends ViewPart implements ITextInputListener , IPerspectiveListener2 { class DataDisplay implements IDataDisplay { public void clear ( ) { IDocument document = fSourceViewer . getDocument ( ) ; if ( document != null ) { document . set ( "" ) ; } } public void displayExpression ( String expression ) { IDocument document = fSourceViewer . getDocument ( ) ; int offset = document . getLength ( ) ; try { if ( offset != document . getLineInformationOfOffset ( offset ) . getOffset ( ) ) { expression = System . getProperty ( "" ) + expression . trim ( ) ; } fSourceViewer . getDocument ( ) . replace ( offset , , expression ) ; fSourceViewer . setSelectedRange ( offset + expression . length ( ) , ) ; fSourceViewer . revealRange ( offset , expression . length ( ) ) ; } catch ( BadLocationException ble ) { RdtDebugUiPlugin . log ( ble ) ; } } public void displayExpressionValue ( String value ) { value = System . getProperty ( "" ) + '' + value ; ITextSelection selection = ( ITextSelection ) fSourceViewer . getSelection ( ) ; int offset = selection . getOffset ( ) + selection . getLength ( ) ; int length = value . length ( ) ; try { fSourceViewer . getDocument ( ) . replace ( offset , , value ) ; } catch ( BadLocationException ble ) { RdtDebugUiPlugin . log ( ble ) ; } fSourceViewer . setSelectedRange ( offset + length , ) ; fSourceViewer . revealRange ( offset , length ) ; } } protected IDataDisplay fDataDisplay = new DataDisplay ( ) ; protected IDocumentListener fDocumentListener = null ; protected RubyDebugSourceViewer fSourceViewer ; protected IAction fClearDisplayAction ; protected DisplayViewAction fContentAssistAction ; protected Map < String , IAction > fGlobalActions = new HashMap < String , IAction > ( ) ; protected List < String > fSelectionActions = new ArrayList < String > ( ) ; protected String fRestoredContents = null ; private static IMemento fgMemento ; private HandlerSubmission fSubmission ; public void createPartControl ( Composite parent ) { int styles = SWT . V_SCROLL | SWT . H_SCROLL | SWT . MULTI | SWT . FULL_SELECTION ; fSourceViewer = new RubyDebugSourceViewer ( parent , null , styles ) ; fSourceViewer . configure ( new DisplayViewerConfiguration ( ) ) ; fSourceViewer . getSelectionProvider ( ) . addSelectionChangedListener ( getSelectionChangedListener ( ) ) ; IDocument doc = getRestoredDocument ( ) ; fSourceViewer . setDocument ( doc ) ; fSourceViewer . addTextInputListener ( this ) ; doc . addDocumentListener ( new IDocumentListener ( ) { public void documentChanged ( DocumentEvent event ) { if ( event == null ) return ; String text = event . getText ( ) ; if ( text == null ) return ; String newline = System . getProperty ( "" ) ; if ( text . equals ( newline ) ) { IDocument doc = event . getDocument ( ) ; try { String prefix = doc . get ( , event . getOffset ( ) ) ; int index = prefix . lastIndexOf ( newline ) ; String line = null ; if ( index == - ) { line = prefix ; } else { line = prefix . substring ( index ) ; } IRubyStackFrame frame = RdtDebugUiPlugin . getEvaluationContextManager ( ) . getEvaluationContext ( getSite ( ) . getWorkbenchWindow ( ) ) ; if ( frame == null ) return ; if ( frame . isSuspended ( ) ) { IEvaluationResult result = frame . evaluate ( line ) ; if ( result == null ) return ; IDataDisplay display = ( IDataDisplay ) getAdapter ( IDataDisplay . class ) ; if ( display == null ) return ; String toDisplay = ExecuteAction . valueToCode ( result . getValue ( ) ) ; display . displayExpressionValue ( toDisplay ) ; } } catch ( Throwable e ) { RdtDebugUiPlugin . log ( e ) ; } } } public void documentAboutToBeChanged ( DocumentEvent event ) { } } ) ; fRestoredContents = null ; createActions ( ) ; createUndoRedoActions ( ) ; initializeToolBar ( ) ; MenuManager menuMgr = new MenuManager ( "" ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager mgr ) { fillContextMenu ( mgr ) ; } } ) ; Menu menu = menuMgr . createContextMenu ( fSourceViewer . getTextWidget ( ) ) ; fSourceViewer . getTextWidget ( ) . setMenu ( menu ) ; getSite ( ) . registerContextMenu ( menuMgr , fSourceViewer . getSelectionProvider ( ) ) ; getSite ( ) . setSelectionProvider ( fSourceViewer . getSelectionProvider ( ) ) ; getSite ( ) . getWorkbenchWindow ( ) . addPerspectiveListener ( this ) ; } protected IDocument getRestoredDocument ( ) { IDocument doc = null ; if ( fRestoredContents != null ) { doc = new Document ( fRestoredContents ) ; } else { doc = new Document ( ) ; } RubyTextTools tools = RdtDebugUiPlugin . getDefault ( ) . getRubyTextTools ( ) ; tools . setupRubyDocumentPartitioner ( doc , IRubyPartitions . RUBY_PARTITIONING ) ; fDocumentListener = new IDocumentListener ( ) { public void documentAboutToBeChanged ( DocumentEvent event ) { } public void documentChanged ( DocumentEvent event ) { updateAction ( ActionFactory . FIND . getId ( ) ) ; } } ; doc . addDocumentListener ( fDocumentListener ) ; return doc ; } public void setFocus ( ) { if ( fSourceViewer != null ) { fSourceViewer . getControl ( ) . setFocus ( ) ; } } protected void createActions ( ) { fClearDisplayAction = new ClearOutputAction ( fSourceViewer ) ; IAction action = new DisplayViewAction ( this , ITextOperationTarget . CUT ) ; action . setText ( DisplayMessages . DisplayView_Cut_label ) ; action . setToolTipText ( DisplayMessages . DisplayView_Cut_tooltip ) ; action . setDescription ( DisplayMessages . DisplayView_Cut_description ) ; setGlobalAction ( ActionFactory . CUT . getId ( ) , action ) ; action = new DisplayViewAction ( this , ITextOperationTarget . COPY ) ; action . setText ( DisplayMessages . DisplayView_Copy_label ) ; action . setToolTipText ( DisplayMessages . DisplayView_Copy_tooltip ) ; action . setDescription ( DisplayMessages . DisplayView_Copy_description ) ; setGlobalAction ( ActionFactory . COPY . getId ( ) , action ) ; action = new DisplayViewAction ( this , ITextOperationTarget . PASTE ) ; action . setText ( DisplayMessages . DisplayView_Paste_label ) ; action . setToolTipText ( DisplayMessages . DisplayView_Paste_tooltip ) ; action . setDescription ( DisplayMessages . DisplayView_Paste_Description ) ; setGlobalAction ( ActionFactory . PASTE . getId ( ) , action ) ; action = new DisplayViewAction ( this , ITextOperationTarget . SELECT_ALL ) ; action . setText ( DisplayMessages . DisplayView_SelectAll_label ) ; action . setToolTipText ( DisplayMessages . DisplayView_SelectAll_tooltip ) ; action . setDescription ( DisplayMessages . DisplayView_SelectAll_description ) ; setGlobalAction ( ActionFactory . SELECT_ALL . getId ( ) , action ) ; ResourceBundle bundle = ResourceBundle . getBundle ( "" ) ; FindReplaceAction findReplaceAction = new FindReplaceAction ( bundle , "" , this ) ; findReplaceAction . setActionDefinitionId ( IWorkbenchActionDefinitionIds . FIND_REPLACE ) ; setGlobalAction ( ActionFactory . FIND . getId ( ) , findReplaceAction ) ; fSelectionActions . add ( ActionFactory . CUT . getId ( ) ) ; fSelectionActions . add ( ActionFactory . COPY . getId ( ) ) ; fSelectionActions . add ( ActionFactory . PASTE . getId ( ) ) ; fContentAssistAction = new DisplayViewAction ( this , ISourceViewer . CONTENTASSIST_PROPOSALS ) ; fContentAssistAction . setActionDefinitionId ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS ) ; fContentAssistAction . setText ( DisplayMessages . DisplayView_Co_ntent_Assist_Ctrl_Space_1 ) ; fContentAssistAction . setDescription ( DisplayMessages . DisplayView_Content_Assist_2 ) ; fContentAssistAction . setToolTipText ( DisplayMessages . DisplayView_Content_Assist_2 ) ; fContentAssistAction . setImageDescriptor ( DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_ELCL_CONTENT_ASSIST ) ) ; fContentAssistAction . setHoverImageDescriptor ( DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_LCL_CONTENT_ASSIST ) ) ; fContentAssistAction . setDisabledImageDescriptor ( DebugUITools . getImageDescriptor ( IDebugUIConstants . IMG_DLCL_CONTENT_ASSIST ) ) ; getViewSite ( ) . getActionBars ( ) . updateActionBars ( ) ; IHandler handler = new AbstractHandler ( ) { public Object execute ( Map parameterValuesByName ) throws ExecutionException { fContentAssistAction . run ( ) ; return null ; } } ; IWorkbench workbench = PlatformUI . getWorkbench ( ) ; IWorkbenchCommandSupport commandSupport = workbench . getCommandSupport ( ) ; fSubmission = new HandlerSubmission ( null , null , getSite ( ) , ITextEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS , handler , Priority . MEDIUM ) ; commandSupport . addHandlerSubmission ( fSubmission ) ; } protected void createUndoRedoActions ( ) { IUndoContext undoContext = getUndoContext ( ) ; if ( undoContext != null ) { OperationHistoryActionHandler undoAction = new UndoActionHandler ( getSite ( ) , undoContext ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( undoAction , IAbstractTextEditorHelpContextIds . UNDO_ACTION ) ; undoAction . setActionDefinitionId ( IWorkbenchActionDefinitionIds . UNDO ) ; setGlobalAction ( ITextEditorActionConstants . UNDO , undoAction ) ; OperationHistoryActionHandler redoAction = new RedoActionHandler ( getSite ( ) , undoContext ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( redoAction , IAbstractTextEditorHelpContextIds . REDO_ACTION ) ; redoAction . setActionDefinitionId ( IWorkbenchActionDefinitionIds . REDO ) ; setGlobalAction ( ITextEditorActionConstants . REDO , redoAction ) ; } } private IUndoContext getUndoContext ( ) { IUndoManager undoManager = fSourceViewer . getUndoManager ( ) ; if ( undoManager instanceof IUndoManagerExtension ) return ( ( IUndoManagerExtension ) undoManager ) . getUndoContext ( ) ; return null ; } protected void setGlobalAction ( String actionID , IAction action ) { IActionBars actionBars = getViewSite ( ) . getActionBars ( ) ; fGlobalActions . put ( actionID , action ) ; actionBars . setGlobalActionHandler ( actionID , action ) ; } private void initializeToolBar ( ) { IToolBarManager tbm = getViewSite ( ) . getActionBars ( ) . getToolBarManager ( ) ; tbm . add ( new Separator ( RdtDebugUiConstants . EVALUATION_GROUP ) ) ; tbm . add ( fClearDisplayAction ) ; getViewSite ( ) . getActionBars ( ) . updateActionBars ( ) ; } protected void fillContextMenu ( IMenuManager menu ) { if ( fSourceViewer . getDocument ( ) == null ) { return ; } menu . add ( new Separator ( RdtDebugUiConstants . EVALUATION_GROUP ) ) ; menu . add ( new Separator ( ) ) ; menu . add ( fGlobalActions . get ( ActionFactory . CUT . getId ( ) ) ) ; menu . add ( fGlobalActions . get ( ActionFactory . COPY . getId ( ) ) ) ; menu . add ( fGlobalActions . get ( ActionFactory . PASTE . getId ( ) ) ) ; menu . add ( fGlobalActions . get ( ActionFactory . SELECT_ALL . getId ( ) ) ) ; menu . add ( new Separator ( ) ) ; menu . add ( fGlobalActions . get ( ActionFactory . FIND . getId ( ) ) ) ; menu . add ( fClearDisplayAction ) ; menu . add ( new Separator ( IWorkbenchActionConstants . MB_ADDITIONS ) ) ; } public Object getAdapter ( Class required ) { if ( ITextOperationTarget . class . equals ( required ) ) { return fSourceViewer . getTextOperationTarget ( ) ; } if ( IFindReplaceTarget . class . equals ( required ) ) { return fSourceViewer . getFindReplaceTarget ( ) ; } if ( IDataDisplay . class . equals ( required ) ) { return fDataDisplay ; } if ( ITextViewer . class . equals ( required ) ) { return fSourceViewer ; } return super . getAdapter ( required ) ; } protected void updateActions ( ) { Iterator < String > iterator = fSelectionActions . iterator ( ) ; while ( iterator . hasNext ( ) ) { IAction action = fGlobalActions . get ( iterator . next ( ) ) ; if ( action instanceof IUpdate ) { ( ( IUpdate ) action ) . update ( ) ; } } } public void saveState ( IMemento memento ) { if ( fSourceViewer != null ) { String contents = getContents ( ) ; if ( contents != null ) { memento . putTextData ( contents ) ; } } else if ( fRestoredContents != null ) { memento . putTextData ( fRestoredContents ) ; } } public void init ( IViewSite site , IMemento memento ) throws PartInitException { init ( site ) ; if ( fgMemento != null ) { memento = fgMemento ; } if ( memento != null ) { fRestoredContents = memento . getTextData ( ) ; } } private String getContents ( ) { if ( fSourceViewer != null ) { IDocument doc = fSourceViewer . getDocument ( ) ; if ( doc != null ) { String contents = doc . get ( ) . trim ( ) ; if ( contents . length ( ) > ) { return contents ; } } } return null ; } protected final ISelectionChangedListener getSelectionChangedListener ( ) { return new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { updateSelectionDependentActions ( ) ; } } ; } protected void updateSelectionDependentActions ( ) { Iterator < String > iterator = fSelectionActions . iterator ( ) ; while ( iterator . hasNext ( ) ) updateAction ( iterator . next ( ) ) ; } protected void updateAction ( String actionId ) { IAction action = fGlobalActions . get ( actionId ) ; if ( action instanceof IUpdate ) { ( ( IUpdate ) action ) . update ( ) ; } } public void inputDocumentAboutToBeChanged ( IDocument oldInput , IDocument newInput ) { } public void inputDocumentChanged ( IDocument oldInput , IDocument newInput ) { oldInput . removeDocumentListener ( fDocumentListener ) ; } public void dispose ( ) { getSite ( ) . getWorkbenchWindow ( ) . removePerspectiveListener ( this ) ; if ( fSourceViewer != null ) { fSourceViewer . dispose ( ) ; fSourceViewer = null ; } IWorkbench workbench = PlatformUI . getWorkbench ( ) ; IWorkbenchCommandSupport commandSupport = workbench . getCommandSupport ( ) ; commandSupport . removeHandlerSubmission ( fSubmission ) ; super . dispose ( ) ; } public void perspectiveChanged ( IWorkbenchPage page , IPerspectiveDescriptor perspective , IWorkbenchPartReference partRef , String changeId ) { if ( partRef instanceof IViewReference && changeId . equals ( IWorkbenchPage . CHANGE_VIEW_HIDE ) ) { String id = ( ( IViewReference ) partRef ) . getId ( ) ; if ( id . equals ( getViewSite ( ) . getId ( ) ) ) { String contents = getContents ( ) ; if ( contents != null ) { fgMemento = XMLMemento . createWriteRoot ( "" ) ; fgMemento . putTextData ( contents ) ; } } } } public void perspectiveActivated ( IWorkbenchPage page , IPerspectiveDescriptor perspective ) { } public void perspectiveChanged ( IWorkbenchPage page , IPerspectiveDescriptor perspective , String changeId ) { } } package org . rubypeople . rdt . internal . debug . ui . display ; public interface IDataDisplay { public void clear ( ) ; public void displayExpression ( String expression ) ; public void displayExpressionValue ( String value ) ; } package org . rubypeople . rdt . internal . debug . ui . display ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . text . ITextOperationTarget ; import org . eclipse . ui . texteditor . IUpdate ; public class DisplayViewAction extends Action implements IUpdate { private int fOperationCode = - ; private ITextOperationTarget fOperationTarget ; private IAdaptable fTargetProvider ; public DisplayViewAction ( ITextOperationTarget target , int operationCode ) { super ( ) ; fOperationTarget = target ; fOperationCode = operationCode ; update ( ) ; } public DisplayViewAction ( IAdaptable targetProvider , int operationCode ) { super ( ) ; fTargetProvider = targetProvider ; fOperationCode = operationCode ; update ( ) ; } public void run ( ) { if ( fOperationCode != - && fOperationTarget != null ) fOperationTarget . doOperation ( fOperationCode ) ; } public void update ( ) { if ( fOperationTarget == null && fTargetProvider != null && fOperationCode != - ) { fOperationTarget = ( ITextOperationTarget ) fTargetProvider . getAdapter ( ITextOperationTarget . class ) ; } boolean isEnabled = ( fOperationTarget != null && fOperationTarget . canDoOperation ( fOperationCode ) ) ; setEnabled ( isEnabled ) ; } } package org . rubypeople . rdt . internal . debug . ui . display ; import org . eclipse . core . runtime . PlatformObject ; import org . eclipse . debug . core . DebugEvent ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . IDebugEventSetListener ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . IDebugElement ; import org . eclipse . debug . core . model . IDebugTarget ; import org . eclipse . debug . core . model . IErrorReportingExpression ; import org . eclipse . debug . core . model . IExpression ; import org . eclipse . debug . core . model . IValue ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; public class RubyInspectExpression extends PlatformObject implements IErrorReportingExpression , IDebugEventSetListener { private IValue fValue ; private String fExpression ; private IEvaluationResult fResult ; public RubyInspectExpression ( String expression , IValue value ) { fValue = value ; fExpression = expression ; DebugPlugin . getDefault ( ) . addDebugEventListener ( this ) ; } public RubyInspectExpression ( IEvaluationResult result ) { this ( result . getSnippet ( ) , result . getValue ( ) ) ; fResult = result ; } public String getExpressionText ( ) { return fExpression ; } public IValue getValue ( ) { return fValue ; } public IDebugTarget getDebugTarget ( ) { IValue value = getValue ( ) ; if ( value != null ) { return getValue ( ) . getDebugTarget ( ) ; } if ( fResult != null ) { return fResult . getThread ( ) . getDebugTarget ( ) ; } return null ; } public String getModelIdentifier ( ) { return getDebugTarget ( ) . getModelIdentifier ( ) ; } public ILaunch getLaunch ( ) { return getDebugTarget ( ) . getLaunch ( ) ; } public void handleDebugEvents ( DebugEvent [ ] events ) { for ( int i = ; i < events . length ; i ++ ) { DebugEvent event = events [ i ] ; switch ( event . getKind ( ) ) { case DebugEvent . TERMINATE : if ( event . getSource ( ) . equals ( getDebugTarget ( ) ) ) { DebugPlugin . getDefault ( ) . getExpressionManager ( ) . removeExpression ( this ) ; } break ; case DebugEvent . SUSPEND : if ( event . getDetail ( ) != DebugEvent . EVALUATION_IMPLICIT ) { if ( event . getSource ( ) instanceof IDebugElement ) { IDebugElement source = ( IDebugElement ) event . getSource ( ) ; if ( source . getDebugTarget ( ) . equals ( getDebugTarget ( ) ) ) { DebugPlugin . getDefault ( ) . fireDebugEventSet ( new DebugEvent [ ] { new DebugEvent ( this , DebugEvent . CHANGE , DebugEvent . CONTENT ) } ) ; } } } break ; } } } public void dispose ( ) { DebugPlugin . getDefault ( ) . removeDebugEventListener ( this ) ; } public boolean hasErrors ( ) { return fResult != null && fResult . hasErrors ( ) ; } public String [ ] getErrorMessages ( ) { return getErrorMessages ( fResult ) ; } public static String [ ] getErrorMessages ( IEvaluationResult result ) { if ( result == null ) { return new String [ ] ; } String messages [ ] = result . getErrorMessages ( ) ; if ( messages . length > ) { return messages ; } DebugException exception = result . getException ( ) ; if ( exception != null ) { return new String [ ] { exception . getMessage ( ) } ; } return new String [ ] ; } } package org . rubypeople . rdt . internal . debug . ui . display ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextDoubleClickStrategy ; import org . eclipse . jface . text . ITextViewer ; import org . eclipse . jface . text . contentassist . ContentAssistant ; import org . eclipse . jface . text . contentassist . IContentAssistProcessor ; import org . eclipse . jface . text . contentassist . IContentAssistant ; import org . eclipse . jface . text . source . ISourceViewer ; import org . eclipse . ui . editors . text . EditorsUI ; import org . eclipse . ui . texteditor . ChainedPreferenceStore ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . RubySourceViewerConfiguration ; public class DisplayViewerConfiguration extends RubySourceViewerConfiguration { public DisplayViewerConfiguration ( ) { super ( RdtDebugUiPlugin . getDefault ( ) . getRubyTextTools ( ) . getColorManager ( ) , new ChainedPreferenceStore ( new IPreferenceStore [ ] { PreferenceConstants . getPreferenceStore ( ) , EditorsUI . getPreferenceStore ( ) } ) , null , null ) ; } public IPreferenceStore getTextPreferenceStore ( ) { return fPreferenceStore ; } public IContentAssistProcessor getContentAssistantProcessor ( ) { return null ; } public IContentAssistant getContentAssistant ( ISourceViewer sourceViewer ) { ContentAssistant assistant = new ContentAssistant ( ) ; assistant . setContentAssistProcessor ( getContentAssistantProcessor ( ) , IDocument . DEFAULT_CONTENT_TYPE ) ; assistant . setContextInformationPopupOrientation ( IContentAssistant . CONTEXT_INFO_ABOVE ) ; assistant . setInformationControlCreator ( getInformationControlCreator ( sourceViewer ) ) ; return assistant ; } public ITextDoubleClickStrategy getDoubleClickStrategy ( ISourceViewer sourceViewer , String contentType ) { ITextDoubleClickStrategy clickStrat = new ITextDoubleClickStrategy ( ) { public void doubleClicked ( ITextViewer viewer ) { try { IDocument doc = viewer . getDocument ( ) ; int caretOffset = viewer . getSelectedRange ( ) . x ; int lineNum = doc . getLineOfOffset ( caretOffset ) ; int start = doc . getLineOffset ( lineNum ) ; int length = doc . getLineLength ( lineNum ) ; viewer . setSelectedRange ( start , length ) ; } catch ( BadLocationException e ) { RdtDebugUiPlugin . log ( e ) ; } } } ; return clickStrat ; } } package org . rubypeople . rdt . internal . debug . ui . display ; import org . eclipse . osgi . util . NLS ; public class DisplayMessages extends NLS { private static final String BUNDLE_NAME = "" ; public static String ClearDisplay_description ; public static String ClearDisplay_label ; public static String ClearDisplay_tooltip ; public static String DisplayView_Co_ntent_Assist_Ctrl_Space_1 ; public static String DisplayView_Content_Assist_2 ; public static String DisplayView_Copy_description ; public static String DisplayCompletionProcessor_0 ; public static String DisplayCompletionProcessor_1 ; public static String DisplayView_Copy_label ; public static String DisplayView_Copy_tooltip ; public static String DisplayView_Cut_description ; public static String DisplayView_Cut_label ; public static String DisplayView_Cut_tooltip ; public static String DisplayView_Paste_Description ; public static String DisplayView_Paste_label ; public static String DisplayView_Paste_tooltip ; public static String DisplayView_SelectAll_description ; public static String DisplayView_SelectAll_label ; public static String DisplayView_SelectAll_tooltip ; public static String find_replace_action_label ; public static String find_replace_action_tooltip ; public static String find_replace_action_image ; public static String find_replace_action_description ; public static String JavaInspectExpression_0 ; static { NLS . initializeMessages ( BUNDLE_NAME , DisplayMessages . class ) ; } } package org . rubypeople . rdt . internal . debug . ui . display ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . ITextViewer ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public class DataDisplay implements IDataDisplay { private ITextViewer fTextViewer ; public DataDisplay ( ITextViewer viewer ) { setTextViewer ( viewer ) ; } public void clear ( ) { IDocument document = getTextViewer ( ) . getDocument ( ) ; if ( document != null ) { document . set ( "" ) ; } } public void displayExpression ( String expression ) { IDocument document = fTextViewer . getDocument ( ) ; int offset = document . getLength ( ) ; try { if ( offset != document . getLineInformationOfOffset ( offset ) . getOffset ( ) ) { expression = System . getProperty ( "" ) + expression . trim ( ) ; } document . replace ( offset , , expression ) ; fTextViewer . setSelectedRange ( offset + expression . length ( ) , ) ; fTextViewer . revealRange ( offset , expression . length ( ) ) ; } catch ( BadLocationException ble ) { RdtDebugUiPlugin . log ( ble ) ; } } public void displayExpressionValue ( String value ) { value = System . getProperty ( "" ) + '' + value ; ITextSelection selection = ( ITextSelection ) fTextViewer . getSelectionProvider ( ) . getSelection ( ) ; int offset = selection . getOffset ( ) + selection . getLength ( ) ; int length = value . length ( ) ; try { fTextViewer . getDocument ( ) . replace ( offset , , value ) ; } catch ( BadLocationException ble ) { RdtDebugUiPlugin . log ( ble ) ; } fTextViewer . setSelectedRange ( offset + length , ) ; fTextViewer . revealRange ( offset , length ) ; } private void setTextViewer ( ITextViewer viewer ) { fTextViewer = viewer ; } protected ITextViewer getTextViewer ( ) { return fTextViewer ; } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IPartListener ; import org . eclipse . ui . IPropertyListener ; import org . eclipse . ui . IWindowListener ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . internal . debug . core . model . IRubyDebugTarget ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class CodeReloader implements IPartListener , IPropertyListener , IWindowListener { public void windowActivated ( IWorkbenchWindow window ) { } public void windowClosed ( IWorkbenchWindow window ) { window . getPartService ( ) . removePartListener ( this ) ; } public void windowDeactivated ( IWorkbenchWindow window ) { } public void windowOpened ( IWorkbenchWindow window ) { window . getPartService ( ) . addPartListener ( this ) ; } public void partActivated ( IWorkbenchPart part ) { } public void partBroughtToTop ( IWorkbenchPart part ) { } public void partClosed ( IWorkbenchPart part ) { if ( part instanceof RubyEditor ) { part . removePropertyListener ( this ) ; } } public void partOpened ( IWorkbenchPart part ) { this . addAsListener ( part ) ; } public void partDeactivated ( IWorkbenchPart part ) { } public void propertyChanged ( Object source , int propId ) { if ( ! ( source instanceof IEditorPart ) ) { return ; } if ( propId != IEditorPart . PROP_DIRTY ) { return ; } RubyEditor editor = ( RubyEditor ) source ; if ( editor . isDirty ( ) ) { return ; } ILaunch [ ] launches = DebugPlugin . getDefault ( ) . getLaunchManager ( ) . getLaunches ( ) ; for ( int i = ; i < launches . length ; i ++ ) { try { ILaunch launch = launches [ i ] ; if ( ! launch . getLaunchMode ( ) . equals ( ILaunchManager . DEBUG_MODE ) ) { continue ; } if ( ! launch . getLaunchConfiguration ( ) . getType ( ) . getIdentifier ( ) . equals ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ) { continue ; } final IRubyDebugTarget target = ( IRubyDebugTarget ) launch . getDebugTarget ( ) ; if ( target . isTerminated ( ) || target . isDisconnected ( ) ) { continue ; } final IResource resource = ( IResource ) editor . getEditorInput ( ) . getAdapter ( IResource . class ) ; if ( resource == null ) { continue ; } CodeReloadJob job = new CodeReloadJob ( target , resource . getLocation ( ) . toOSString ( ) ) ; job . schedule ( ) ; } catch ( CoreException e ) { RdtDebugUiPlugin . log ( new Status ( IStatus . ERROR , RdtDebugUiPlugin . PLUGIN_ID , , "" , e ) ) ; } } } public void addAsListener ( IWorkbenchPart part ) { if ( part == null || ! ( part instanceof RubyEditor ) ) { return ; } part . addPropertyListener ( this ) ; } public CodeReloader ( ) { final CodeReloader self = this ; UIJob job = new UIJob ( "" ) { @ Override public IStatus runInUIThread ( IProgressMonitor monitor ) { RdtDebugUiPlugin . getDefault ( ) . getWorkbench ( ) . addWindowListener ( self ) ; IWorkbenchWindow [ ] windows = RdtDebugUiPlugin . getDefault ( ) . getWorkbench ( ) . getWorkbenchWindows ( ) ; for ( int i = ; i < windows . length ; i ++ ) { IWorkbenchWindow window = windows [ i ] ; window . getPartService ( ) . addPartListener ( self ) ; } IWorkbenchWindow activeWindow = RdtDebugUiPlugin . getDefault ( ) . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; if ( activeWindow == null ) { return Status . OK_STATUS ; } IWorkbenchPage page = activeWindow . getActivePage ( ) ; if ( page == null ) { return Status . OK_STATUS ; } addAsListener ( page . getActivePart ( ) ) ; return Status . OK_STATUS ; } } ; job . setPriority ( Job . LONG ) ; job . schedule ( ) ; } } package org . rubypeople . rdt . internal . debug . ui ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . debug . internal . ui . contexts . DebugContextManager ; import org . eclipse . debug . ui . contexts . DebugContextEvent ; import org . eclipse . debug . ui . contexts . IDebugContextListener ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IWindowListener ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . debug . core . model . IRubyThread ; import org . rubypeople . rdt . debug . ui . IEvaluationContextManager ; public class EvaluationContextManager implements IDebugContextListener , IWindowListener , IEvaluationContextManager { private static EvaluationContextManager fgManager ; private static final String DEBUGGER_ACTIVE = RdtDebugUiPlugin . getUniqueIdentifier ( ) + "" ; private static final String INSTANCE_OF_IRUBY_STACK_FRAME = RdtDebugUiPlugin . getUniqueIdentifier ( ) + "" ; private Map < IWorkbenchPage , IRubyStackFrame > fContextsByPage = null ; private IWorkbenchWindow fActiveWindow ; public EvaluationContextManager ( ) { DebugContextManager . getDefault ( ) . addDebugContextListener ( this ) ; fgManager = this ; } public IRubyStackFrame getEvaluationContext ( IWorkbenchPart part ) { IWorkbenchPage page = part . getSite ( ) . getPage ( ) ; IRubyStackFrame frame = getContext ( page ) ; if ( frame == null ) { return getEvaluationContext ( page . getWorkbenchWindow ( ) ) ; } return frame ; } public IRubyStackFrame getEvaluationContext ( IWorkbenchWindow window ) { List < IWorkbenchWindow > alreadyVisited = new ArrayList < IWorkbenchWindow > ( ) ; if ( window == null ) { window = fgManager . fActiveWindow ; } return getEvaluationContext ( window , alreadyVisited ) ; } private static IRubyStackFrame getEvaluationContext ( IWorkbenchWindow window , List < IWorkbenchWindow > alreadyVisited ) { IWorkbenchPage activePage = window . getActivePage ( ) ; IRubyStackFrame frame = null ; if ( activePage != null ) { frame = getContext ( activePage ) ; } if ( frame == null ) { IWorkbenchPage [ ] pages = window . getPages ( ) ; for ( int i = ; i < pages . length ; i ++ ) { if ( activePage != pages [ i ] ) { frame = getContext ( pages [ i ] ) ; if ( frame != null ) { return frame ; } } } alreadyVisited . add ( window ) ; IWorkbenchWindow [ ] windows = PlatformUI . getWorkbench ( ) . getWorkbenchWindows ( ) ; for ( int i = ; i < windows . length ; i ++ ) { if ( ! alreadyVisited . contains ( windows [ i ] ) ) { frame = getEvaluationContext ( windows [ i ] , alreadyVisited ) ; if ( frame != null ) { return frame ; } } } return null ; } return frame ; } private static IRubyStackFrame getContext ( IWorkbenchPage page ) { if ( fgManager != null ) { if ( fgManager . fContextsByPage != null ) { return fgManager . fContextsByPage . get ( page ) ; } } return null ; } public void contextActivated ( ISelection selection , IWorkbenchPart part ) { if ( part != null ) { IWorkbenchPage page = part . getSite ( ) . getPage ( ) ; if ( selection instanceof IStructuredSelection ) { IStructuredSelection ss = ( IStructuredSelection ) selection ; if ( ss . size ( ) == ) { Object element = ss . getFirstElement ( ) ; if ( element instanceof IAdaptable ) { IRubyStackFrame frame = ( IRubyStackFrame ) ( ( IAdaptable ) element ) . getAdapter ( IRubyStackFrame . class ) ; boolean instOf = element instanceof IRubyStackFrame || element instanceof IRubyThread ; if ( frame != null ) { setContext ( page , frame , instOf ) ; return ; } } } } removeContext ( page ) ; } } public void contextChanged ( ISelection selection , IWorkbenchPart part ) { } private void setContext ( IWorkbenchPage page , IRubyStackFrame frame , boolean instOf ) { if ( fContextsByPage == null ) { fContextsByPage = new HashMap < IWorkbenchPage , IRubyStackFrame > ( ) ; } fContextsByPage . put ( page , frame ) ; System . setProperty ( DEBUGGER_ACTIVE , "" ) ; if ( instOf ) { System . setProperty ( INSTANCE_OF_IRUBY_STACK_FRAME , "" ) ; } else { System . setProperty ( INSTANCE_OF_IRUBY_STACK_FRAME , "" ) ; } } private void removeContext ( IWorkbenchPage page ) { if ( fContextsByPage != null ) { fContextsByPage . remove ( page ) ; if ( fContextsByPage . isEmpty ( ) ) { System . setProperty ( DEBUGGER_ACTIVE , "" ) ; System . setProperty ( INSTANCE_OF_IRUBY_STACK_FRAME , "" ) ; } } } public void startup ( ) { Runnable r = new Runnable ( ) { public void run ( ) { IWorkbench workbench = PlatformUI . getWorkbench ( ) ; IWorkbenchWindow [ ] windows = workbench . getWorkbenchWindows ( ) ; for ( int i = ; i < windows . length ; i ++ ) { fgManager . windowOpened ( windows [ i ] ) ; } workbench . addWindowListener ( fgManager ) ; fgManager . fActiveWindow = workbench . getActiveWorkbenchWindow ( ) ; } } ; RdtDebugUiPlugin . getStandardDisplay ( ) . asyncExec ( r ) ; } public static IEvaluationContextManager instance ( ) { if ( fgManager == null ) { fgManager = new EvaluationContextManager ( ) ; } return fgManager ; } public void windowActivated ( IWorkbenchWindow window ) { fActiveWindow = window ; } public void windowClosed ( IWorkbenchWindow window ) { } public void windowDeactivated ( IWorkbenchWindow window ) { } public void windowOpened ( IWorkbenchWindow window ) { } public void debugContextChanged ( DebugContextEvent event ) { if ( ( event . getFlags ( ) & DebugContextEvent . ACTIVATED ) > ) { contextActivated ( event . getContext ( ) , event . getDebugContextProvider ( ) . getPart ( ) ) ; } } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . jface . resource . CompositeImageDescriptor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . Point ; public class RubyDebugImageDescriptor extends CompositeImageDescriptor { public final static int IS_OUT_OF_SYNCH = ; public final static int MAY_BE_OUT_OF_SYNCH = ; public final static int INSTALLED = ; public final static int ENTRY = ; public final static int EXIT = ; public final static int ENABLED = ; public final static int CONDITIONAL = ; public final static int CAUGHT = ; public final static int UNCAUGHT = ; public final static int SCOPED = ; public final static int OWNS_MONITOR = ; public final static int OWNED_MONITOR = ; public final static int CONTENTED_MONITOR = ; public final static int IN_CONTENTION_FOR_MONITOR = ; public final static int IN_DEADLOCK = ; public final static int SYNCHRONIZED = ; private ImageDescriptor fBaseImage ; private int fFlags ; private Point fSize ; public RubyDebugImageDescriptor ( ImageDescriptor baseImage , int flags ) { setBaseImage ( baseImage ) ; setFlags ( flags ) ; } protected Point getSize ( ) { if ( fSize == null ) { ImageData data = getBaseImage ( ) . getImageData ( ) ; setSize ( new Point ( data . width , data . height ) ) ; } return fSize ; } public boolean equals ( Object object ) { if ( ! ( object instanceof RubyDebugImageDescriptor ) ) { return false ; } RubyDebugImageDescriptor other = ( RubyDebugImageDescriptor ) object ; return ( getBaseImage ( ) . equals ( other . getBaseImage ( ) ) && getFlags ( ) == other . getFlags ( ) ) ; } public int hashCode ( ) { return getBaseImage ( ) . hashCode ( ) | getFlags ( ) ; } protected void drawCompositeImage ( int width , int height ) { ImageData bg = getBaseImage ( ) . getImageData ( ) ; if ( bg == null ) { bg = DEFAULT_IMAGE_DATA ; } drawImage ( bg , , ) ; drawOverlays ( ) ; } private ImageData getImageData ( String imageDescriptorKey ) { return RubyDebugImages . getImageDescriptor ( imageDescriptorKey ) . getImageData ( ) ; } protected void drawOverlays ( ) { int flags = getFlags ( ) ; int x = ; int y = ; ImageData data = null ; if ( ( flags & IS_OUT_OF_SYNCH ) != ) { x = getSize ( ) . x ; y = ; data = getImageData ( RubyDebugImages . IMG_OVR_OUT_OF_SYNCH ) ; x -= data . width ; drawImage ( data , x , y ) ; } else if ( ( flags & MAY_BE_OUT_OF_SYNCH ) != ) { x = getSize ( ) . x ; y = ; data = getImageData ( RubyDebugImages . IMG_OVR_MAY_BE_OUT_OF_SYNCH ) ; x -= data . width ; drawImage ( data , x , y ) ; } else if ( ( flags & SYNCHRONIZED ) != ) { x = getSize ( ) . x ; y = ; data = getImageData ( RubyDebugImages . IMG_OVR_SYNCHRONIZED ) ; x -= data . width ; drawImage ( data , x , y ) ; } else { if ( ( flags & IN_DEADLOCK ) != ) { x = ; y = ; data = getImageData ( RubyDebugImages . IMG_OVR_IN_DEADLOCK ) ; drawImage ( data , x , y ) ; } if ( ( flags & OWNED_MONITOR ) != ) { x = getSize ( ) . x ; y = getSize ( ) . y ; data = getImageData ( RubyDebugImages . IMG_OVR_OWNED ) ; x -= data . width ; y -= data . height ; drawImage ( data , x , y ) ; } else if ( ( flags & CONTENTED_MONITOR ) != ) { x = getSize ( ) . x ; y = getSize ( ) . y ; data = getImageData ( RubyDebugImages . IMG_OVR_IN_CONTENTION ) ; x -= data . width ; y -= data . height ; drawImage ( data , x , y ) ; } else if ( ( flags & OWNS_MONITOR ) != ) { x = getSize ( ) . x ; y = ; data = getImageData ( RubyDebugImages . IMG_OVR_OWNS_MONITOR ) ; x -= data . width ; drawImage ( data , x , y ) ; } else if ( ( flags & IN_CONTENTION_FOR_MONITOR ) != ) { x = getSize ( ) . x ; y = ; data = getImageData ( RubyDebugImages . IMG_OVR_IN_CONTENTION_FOR_MONITOR ) ; x -= data . width ; drawImage ( data , x , y ) ; } else { drawBreakpointOverlays ( ) ; } } } protected void drawBreakpointOverlays ( ) { int flags = getFlags ( ) ; int x = ; int y = ; ImageData data = null ; if ( ( flags & INSTALLED ) != ) { x = ; y = getSize ( ) . y ; if ( ( flags & ENABLED ) != ) { data = getImageData ( RubyDebugImages . IMG_OVR_BREAKPOINT_INSTALLED ) ; } else { data = getImageData ( RubyDebugImages . IMG_OVR_BREAKPOINT_INSTALLED_DISABLED ) ; } y -= data . height ; drawImage ( data , x , y ) ; } if ( ( flags & CAUGHT ) != ) { if ( ( flags & ENABLED ) != ) { data = getImageData ( RubyDebugImages . IMG_OVR_CAUGHT_BREAKPOINT ) ; } else { data = getImageData ( RubyDebugImages . IMG_OVR_CAUGHT_BREAKPOINT_DISABLED ) ; } x = ; y = ; drawImage ( data , x , y ) ; } if ( ( flags & UNCAUGHT ) != ) { if ( ( flags & ENABLED ) != ) { data = getImageData ( RubyDebugImages . IMG_OVR_UNCAUGHT_BREAKPOINT ) ; } else { data = getImageData ( RubyDebugImages . IMG_OVR_UNCAUGHT_BREAKPOINT_DISABLED ) ; } x = data . width ; y = data . height ; drawImage ( data , x , y ) ; } if ( ( flags & SCOPED ) != ) { if ( ( flags & ENABLED ) != ) { data = getImageData ( RubyDebugImages . IMG_OVR_SCOPED_BREAKPOINT ) ; } else { data = getImageData ( RubyDebugImages . IMG_OVR_SCOPED_BREAKPOINT_DISABLED ) ; } x = ; y = getSize ( ) . y ; y -= data . height ; drawImage ( data , x , y ) ; } if ( ( flags & CONDITIONAL ) != ) { if ( ( flags & ENABLED ) != ) { data = getImageData ( RubyDebugImages . IMG_OVR_CONDITIONAL_BREAKPOINT ) ; } else { data = getImageData ( RubyDebugImages . IMG_OVR_CONDITIONAL_BREAKPOINT_DISABLED ) ; } x = ; y = ; drawImage ( data , x , y ) ; } if ( ( flags & ENTRY ) != ) { x = getSize ( ) . x ; y = ; if ( ( flags & ENABLED ) != ) { data = getImageData ( RubyDebugImages . IMG_OVR_METHOD_BREAKPOINT_ENTRY ) ; } else { data = getImageData ( RubyDebugImages . IMG_OVR_METHOD_BREAKPOINT_ENTRY_DISABLED ) ; } x -= data . width ; x = x - ; drawImage ( data , x , y ) ; } if ( ( flags & EXIT ) != ) { x = getSize ( ) . x ; y = getSize ( ) . y ; if ( ( flags & ENABLED ) != ) { data = getImageData ( RubyDebugImages . IMG_OVR_METHOD_BREAKPOINT_EXIT ) ; } else { data = getImageData ( RubyDebugImages . IMG_OVR_METHOD_BREAKPOINT_EXIT_DISABLED ) ; } x -= data . width ; x = x - ; y -= data . height ; drawImage ( data , x , y ) ; } } protected ImageDescriptor getBaseImage ( ) { return fBaseImage ; } protected void setBaseImage ( ImageDescriptor baseImage ) { fBaseImage = baseImage ; } protected int getFlags ( ) { return fFlags ; } protected void setFlags ( int flags ) { fFlags = flags ; } protected void setSize ( Point size ) { fSize = size ; } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . ui . IEditorInput ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . internal . ui . rubyeditor . WorkingCopyManager ; import org . rubypeople . rdt . ui . RubyUI ; public class DebugWorkingCopyManager { public static IRubyScript getWorkingCopy ( IEditorInput input , boolean primaryOnly ) { return ( ( WorkingCopyManager ) RubyUI . getWorkingCopyManager ( ) ) . getWorkingCopy ( input , primaryOnly ) ; } } package org . rubypeople . rdt . internal . debug . ui . console ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . ISourceLocator ; import org . eclipse . debug . ui . console . IConsole ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . console . IHyperlink ; import org . eclipse . ui . texteditor . IDocumentProvider ; import org . eclipse . ui . texteditor . ITextEditor ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . debug . ui . RubySourceLocator ; import org . rubypeople . rdt . internal . ui . util . StackTraceLine ; public class RubyStackTraceHyperlink implements IHyperlink { private IConsole fConsole ; private StackTraceLine fTraceLine ; public RubyStackTraceHyperlink ( IConsole console , StackTraceLine line ) { fConsole = console ; fTraceLine = line ; } public void linkEntered ( ) { } public void linkExited ( ) { } private void setEditorToLine ( IEditorPart pEditorPart , IEditorInput pInput ) throws CoreException { if ( ! ( pEditorPart instanceof ITextEditor ) ) { return ; } int lineNumber = this . getLineNumber ( ) ; if ( lineNumber > ) { lineNumber -- ; } if ( lineNumber == ) { return ; } ITextEditor textEditor = ( ITextEditor ) pEditorPart ; IDocumentProvider provider = textEditor . getDocumentProvider ( ) ; provider . connect ( pInput ) ; IDocument document = provider . getDocument ( pInput ) ; try { IRegion line = document . getLineInformation ( lineNumber ) ; textEditor . selectAndReveal ( line . getOffset ( ) , line . getLength ( ) ) ; } catch ( BadLocationException e ) { if ( RdtDebugUiPlugin . getDefault ( ) . isDebugging ( ) ) { System . out . println ( "" + lineNumber ) ; } } provider . disconnect ( pInput ) ; } public void linkActivated ( ) { RubySourceLocator rubySourceLocator = null ; ILaunch launch = getConsole ( ) . getProcess ( ) . getLaunch ( ) ; if ( launch == null ) { return ; } ISourceLocator sourceLocator = launch . getSourceLocator ( ) ; if ( ! ( sourceLocator instanceof RubySourceLocator ) ) { return ; } rubySourceLocator = ( RubySourceLocator ) sourceLocator ; String filename = this . getFilename ( ) ; try { Object sourceElement = rubySourceLocator . getSourceElement ( filename ) ; IEditorInput input = rubySourceLocator . getEditorInput ( sourceElement ) ; if ( input == null ) { if ( RdtDebugUiPlugin . getDefault ( ) . isDebugging ( ) ) { System . out . println ( "" + filename ) ; } return ; } IEditorPart editorPart = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . openEditor ( input , rubySourceLocator . getEditorId ( input , sourceElement ) ) ; this . setEditorToLine ( editorPart , input ) ; } catch ( CoreException e ) { RdtDebugUiPlugin . log ( new Status ( IStatus . ERROR , RdtDebugUiPlugin . PLUGIN_ID , , "" + filename , e ) ) ; } } public int getLineNumber ( ) { return fTraceLine . getLineNumber ( ) ; } public String getFilename ( ) { return fTraceLine . getFilename ( ) ; } protected IConsole getConsole ( ) { return fConsole ; } protected String getLinkText ( ) throws BadLocationException { IRegion region = getConsole ( ) . getRegion ( this ) ; return getConsole ( ) . getDocument ( ) . get ( region . getOffset ( ) , region . getLength ( ) ) ; } } package org . rubypeople . rdt . internal . debug . ui . console ; import java . net . MalformedURLException ; import java . net . URL ; import java . util . StringTokenizer ; import org . eclipse . debug . ui . console . IConsole ; import org . eclipse . debug . ui . console . IConsoleLineTracker ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IRegion ; import org . eclipse . swt . program . Program ; import org . eclipse . ui . console . IHyperlink ; public class URLConsoleLineTracker implements IConsoleLineTracker { private IConsole fConsole ; public void dispose ( ) { fConsole = null ; } public void init ( IConsole console ) { this . fConsole = console ; } public void lineAppended ( IRegion line ) { String text ; try { text = getText ( line ) ; } catch ( BadLocationException e1 ) { return ; } int index = text . indexOf ( "" ) ; if ( index == - ) return ; int start = index ; while ( true ) { char c = text . charAt ( start ) ; if ( c == '' ) { start ++ ; break ; } if ( start == ) break ; start -- ; } StringTokenizer tokenizer = new StringTokenizer ( text . substring ( index ) , "" ) ; if ( ! tokenizer . hasMoreTokens ( ) ) return ; String url = text . substring ( start , index ) + tokenizer . nextToken ( ) ; url = url . trim ( ) ; try { new URL ( url ) ; } catch ( MalformedURLException e ) { return ; } int offset = line . getOffset ( ) + start ; int length = url . length ( ) ; IHyperlink link = new URLHyperlink ( url ) ; fConsole . addLink ( link , offset , length ) ; } protected String getText ( IRegion line ) throws BadLocationException { return fConsole . getDocument ( ) . get ( line . getOffset ( ) , line . getLength ( ) ) ; } private static class URLHyperlink implements IHyperlink { private String fURLString ; public URLHyperlink ( String url ) { this . fURLString = url ; } public void linkExited ( ) { } public void linkEntered ( ) { } public void linkActivated ( ) { Program . launch ( fURLString ) ; } } } package org . rubypeople . rdt . internal . debug . ui . console ; import java . io . File ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . ui . console . IConsole ; import org . eclipse . debug . ui . console . IConsoleLineTracker ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IRegion ; import org . eclipse . ui . console . IHyperlink ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . StackTraceLine ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class RubyConsoleTracker implements IConsoleLineTracker { public interface FileExistanceChecker { boolean fileExists ( String filename ) ; } public static class StandardFileExistanceChecker implements FileExistanceChecker { public boolean fileExists ( String filename ) { File file = new File ( filename ) ; if ( file . exists ( ) ) return true ; IPath path = new Path ( filename ) ; if ( ! path . isValidPath ( filename ) ) { return false ; } try { IFile iFile = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( path ) ; if ( iFile != null ) return iFile . exists ( ) ; } catch ( IllegalArgumentException e ) { return false ; } return false ; } } private final FileExistanceChecker existanceChecker ; public RubyConsoleTracker ( ) { this ( new StandardFileExistanceChecker ( ) ) ; } public RubyConsoleTracker ( FileExistanceChecker existance ) { this . existanceChecker = existance ; } protected IConsole fConsole ; private ILaunch fLastLaunch ; private IProject fProject ; public void init ( IConsole pConsole ) { fConsole = pConsole ; } public void lineAppended ( IRegion line ) { try { int prefix = ; String text = getText ( line ) ; while ( StackTraceLine . isTraceLine ( text ) ) { StackTraceLine stackTraceLine = new StackTraceLine ( text , getProject ( ) ) ; if ( ! existanceChecker . fileExists ( stackTraceLine . getFilename ( ) ) ) return ; IHyperlink link = new RubyStackTraceHyperlink ( fConsole , stackTraceLine ) ; fConsole . addLink ( link , line . getOffset ( ) + prefix + stackTraceLine . offset ( ) , stackTraceLine . length ( ) ) ; prefix = stackTraceLine . offset ( ) + stackTraceLine . length ( ) ; int substring = stackTraceLine . offset ( ) + stackTraceLine . length ( ) ; if ( text . length ( ) < substring - ) { text = "" ; } else { text = text . substring ( substring ) ; if ( text . startsWith ( "" ) ) { text = text . substring ( ) ; prefix += ; } } } } catch ( BadLocationException e ) { } } protected IProject getProject ( ) { if ( fLastLaunch == null || ( fConsole . getProcess ( ) != null && ! fLastLaunch . equals ( fConsole . getProcess ( ) . getLaunch ( ) ) ) ) { if ( fConsole . getProcess ( ) == null ) return null ; fLastLaunch = fConsole . getProcess ( ) . getLaunch ( ) ; String projectName = null ; try { if ( fConsole . getProcess ( ) != null && fConsole . getProcess ( ) . getLaunch ( ) != null && fConsole . getProcess ( ) . getLaunch ( ) . getLaunchConfiguration ( ) != null ) projectName = fConsole . getProcess ( ) . getLaunch ( ) . getLaunchConfiguration ( ) . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , ( String ) null ) ; } catch ( Exception e ) { RubyPlugin . log ( e ) ; } if ( projectName == null ) return null ; fProject = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; } return fProject ; } protected String getText ( IRegion line ) throws BadLocationException { return fConsole . getDocument ( ) . get ( line . getOffset ( ) , line . getLength ( ) ) ; } public void dispose ( ) { fConsole = null ; } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . core . runtime . IAdapterFactory ; import org . eclipse . ui . IActionFilter ; import org . rubypeople . rdt . debug . core . model . IRubyVariable ; class ActionFilterAdapterFactory implements IAdapterFactory , IActionFilter { public Object getAdapter ( Object obj , Class adapterType ) { if ( adapterType . isInstance ( obj ) ) { return obj ; } if ( adapterType != IActionFilter . class ) { return null ; } if ( obj instanceof IRubyVariable ) { return this ; } return null ; } public Class [ ] getAdapterList ( ) { return new Class [ ] { IActionFilter . class } ; } public boolean testAttribute ( Object rubyVariable , String name , String value ) { if ( name . equals ( "" ) ) { return ( ( IRubyVariable ) rubyVariable ) . isHashValue ( ) ; } return false ; } } package org . rubypeople . rdt . internal . debug . ui . preferences ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public class RubyKeywordsPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { public RubyKeywordsPreferencePage ( ) { } public void init ( IWorkbench workbench ) { } protected Control createContents ( Composite parent ) { Composite composite = new Composite ( parent , SWT . H_SCROLL | SWT . V_SCROLL ) ; GridLayout layout = new GridLayout ( ) ; composite . setLayout ( layout ) ; Text keywordText = new Text ( composite , SWT . NONE ) ; keywordText . setText ( getOriginalText ( ) ) ; keywordText . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; keywordText . setEditable ( false ) ; return composite ; } protected String getOriginalText ( ) { IPreferenceStore prefs = RdtDebugUiPlugin . getDefault ( ) . getPreferenceStore ( ) ; return prefs . getDefaultString ( RdtDebugUiConstants . PREFERENCE_KEYWORDS ) ; } } package org . rubypeople . rdt . internal . debug . ui . preferences ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . evaluation . EvaluationExpression ; import org . rubypeople . rdt . internal . ui . dialogs . StatusDialog ; public class EditEvaluationExpressionDialog extends StatusDialog { protected EvaluationExpression evaluationExpression ; protected Text txtName ; protected Text txtDescription ; protected Text txtExpression ; public EditEvaluationExpressionDialog ( Shell parentShell , String aDialogTitle , EvaluationExpression expr ) { super ( parentShell ) ; setTitle ( aDialogTitle ) ; evaluationExpression = expr ; } protected void okPressed ( ) { evaluationExpression . setName ( txtName . getText ( ) ) ; evaluationExpression . setDescription ( txtDescription . getText ( ) ) ; evaluationExpression . setExpression ( txtExpression . getText ( ) ) ; super . okPressed ( ) ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; composite . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . EditEvaluationExpression_name_label ) ; txtName = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; txtName . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; txtName . setText ( evaluationExpression . getName ( ) ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . EditEvaluationExpression_description_label ) ; txtDescription = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; txtDescription . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; txtDescription . setText ( evaluationExpression . getDescription ( ) ) ; new Label ( composite , SWT . NONE ) . setText ( RdtDebugUiMessages . EditEvaluationExpression_expression_label ) ; txtExpression = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; txtExpression . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; txtExpression . setText ( evaluationExpression . getExpression ( ) ) ; return composite ; } } package org . rubypeople . rdt . internal . debug . ui . preferences ; import java . io . BufferedInputStream ; import java . io . BufferedOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . StringWriter ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Iterator ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . text . templates . persistence . TemplateReaderWriter ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . TableLayout ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ControlAdapter ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . debug . ui . evaluation . EvaluationExpression ; import org . rubypeople . rdt . internal . debug . ui . evaluation . EvaluationExpressionReaderWriter ; import org . rubypeople . rdt . internal . ui . util . SWTUtil ; public class EvaluationExpressionsPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private class EvaluationExpressionLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage ( Object element , int columnIndex ) { return null ; } public String getColumnText ( Object element , int columnIndex ) { EvaluationExpression exp = ( EvaluationExpression ) element ; switch ( columnIndex ) { case : return exp . getName ( ) ; case : return exp . getDescription ( ) ; default : return "" ; } } } private class EvaluationExpressionContentProvider implements IStructuredContentProvider { private EditableExpressionModel model ; public Object [ ] getElements ( Object input ) { return model . getExpressionsAsArray ( ) ; } public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { model = ( EditableExpressionModel ) newInput ; } public void dispose ( ) { model = null ; } } private class EditableExpressionModel { private ArrayList expressions ; public EditableExpressionModel ( ) { this . load ( ) ; } public Collection getExpressions ( ) { return expressions ; } public Object [ ] getExpressionsAsArray ( ) { return expressions . toArray ( new EvaluationExpression [ expressions . size ( ) ] ) ; } public void addExpression ( EvaluationExpression expr ) { this . expressions . add ( expr ) ; } public void replaceExpression ( EvaluationExpression old , EvaluationExpression updated ) { int index = this . expressions . indexOf ( old ) ; if ( index >= ) { this . expressions . set ( index , updated ) ; } } public void removeExpression ( EvaluationExpression expr ) { this . expressions . remove ( expr ) ; } public void save ( ) { StringWriter xmlWriter = new StringWriter ( ) ; try { new EvaluationExpressionReaderWriter ( ) . save ( ( EvaluationExpression [ ] ) this . getExpressionsAsArray ( ) , xmlWriter ) ; RdtDebugUiPlugin . getDefault ( ) . getPluginPreferences ( ) . setValue ( RdtDebugUiConstants . EVALUATION_EXPRESSIONS_PREFERENCE , xmlWriter . toString ( ) ) ; } catch ( IOException e ) { RdtDebugUiPlugin . log ( e ) ; } } public void load ( ) { EvaluationExpression [ ] exprs = RdtDebugUiPlugin . getDefault ( ) . getEvaluationExpressionModel ( ) . getEvaluationExpressions ( ) ; expressions = new ArrayList ( exprs . length ) ; for ( int i = ; i < exprs . length ; i ++ ) { EvaluationExpression expression = exprs [ i ] ; expressions . add ( expression ) ; } } public void importExpressions ( InputStream in ) throws IOException , FileNotFoundException { EvaluationExpression [ ] importedExprs = new EvaluationExpressionReaderWriter ( ) . read ( in , null ) ; for ( int i = ; i < importedExprs . length ; i ++ ) { expressions . add ( importedExprs [ i ] ) ; } } public void exportExpressions ( EvaluationExpression [ ] expressions , OutputStream out ) throws IOException { new EvaluationExpressionReaderWriter ( ) . save ( expressions , out ) ; } } private CheckboxTableViewer fTableViewer ; private Button fAddButton ; private Button fEditButton ; private Button fImportButton ; private Button fExportButton ; private Button fRemoveButton ; private EditableExpressionModel fModel ; public EvaluationExpressionsPreferencePage ( ) { super ( ) ; fModel = new EditableExpressionModel ( ) ; setDescription ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_description ) ; } public void init ( IWorkbench workbench ) { } protected Control createContents ( Composite ancestor ) { Composite parent = new Composite ( ancestor , SWT . NONE ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; layout . marginHeight = ; layout . marginWidth = ; parent . setLayout ( layout ) ; Composite innerParent = new Composite ( parent , SWT . NONE ) ; GridLayout innerLayout = new GridLayout ( ) ; innerLayout . numColumns = ; innerLayout . marginHeight = ; innerLayout . marginWidth = ; innerParent . setLayout ( innerLayout ) ; GridData gd = new GridData ( GridData . FILL_BOTH ) ; gd . horizontalSpan = ; innerParent . setLayoutData ( gd ) ; Table table = new Table ( innerParent , SWT . CHECK | SWT . BORDER | SWT . MULTI | SWT . FULL_SELECTION ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . widthHint = convertWidthInCharsToPixels ( ) ; data . heightHint = convertHeightInCharsToPixels ( ) ; table . setLayoutData ( data ) ; table . setHeaderVisible ( true ) ; table . setLinesVisible ( true ) ; TableLayout tableLayout = new TableLayout ( ) ; table . setLayout ( tableLayout ) ; TableColumn column1 = new TableColumn ( table , SWT . NONE ) ; column1 . setText ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_column_name ) ; TableColumn column2 = new TableColumn ( table , SWT . NONE ) ; column2 . setText ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_column_description ) ; fTableViewer = new CheckboxTableViewer ( table ) ; fTableViewer . setLabelProvider ( new EvaluationExpressionLabelProvider ( ) ) ; fTableViewer . setContentProvider ( new EvaluationExpressionContentProvider ( ) ) ; fTableViewer . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent e ) { edit ( ) ; } } ) ; fTableViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent e ) { selectionChanged1 ( ) ; } } ) ; fTableViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { ( ( EvaluationExpression ) event . getElement ( ) ) . setEnabled ( event . getChecked ( ) ) ; } } ) ; Composite buttons = new Composite ( innerParent , SWT . NONE ) ; buttons . setLayoutData ( new GridData ( GridData . VERTICAL_ALIGN_BEGINNING ) ) ; layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; buttons . setLayout ( layout ) ; fAddButton = new Button ( buttons , SWT . PUSH ) ; fAddButton . setText ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_new ) ; fAddButton . setLayoutData ( getButtonGridData ( fAddButton ) ) ; fAddButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { add ( ) ; } } ) ; fEditButton = new Button ( buttons , SWT . PUSH ) ; fEditButton . setText ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_edit ) ; fEditButton . setLayoutData ( getButtonGridData ( fEditButton ) ) ; fEditButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { edit ( ) ; } } ) ; fRemoveButton = new Button ( buttons , SWT . PUSH ) ; fRemoveButton . setText ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_remove ) ; fRemoveButton . setLayoutData ( getButtonGridData ( fRemoveButton ) ) ; fRemoveButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { remove ( ) ; } } ) ; createSeparator ( buttons ) ; fImportButton = new Button ( buttons , SWT . PUSH ) ; fImportButton . setText ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_import ) ; fImportButton . setLayoutData ( getButtonGridData ( fImportButton ) ) ; fImportButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { importFile ( ) ; } } ) ; fExportButton = new Button ( buttons , SWT . PUSH ) ; fExportButton . setText ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export ) ; fExportButton . setLayoutData ( getButtonGridData ( fExportButton ) ) ; fExportButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event e ) { exportFile ( ) ; } } ) ; fTableViewer . setInput ( fModel ) ; setEnabledExpresions ( fTableViewer ) ; updateButtons ( ) ; configureTableResizing ( innerParent , buttons , table , column1 , column2 ) ; Dialog . applyDialogFont ( parent ) ; return parent ; } private void setEnabledExpresions ( CheckboxTableViewer viewer ) { for ( Object o : fModel . getExpressionsAsArray ( ) ) { EvaluationExpression expr = ( EvaluationExpression ) o ; viewer . setChecked ( o , expr . isEnabled ( ) ) ; } } private Label createSeparator ( Composite parent ) { Label separator = new Label ( parent , SWT . NONE ) ; separator . setVisible ( false ) ; GridData gd = new GridData ( ) ; gd . horizontalAlignment = GridData . FILL ; gd . verticalAlignment = GridData . BEGINNING ; gd . heightHint = ; separator . setLayoutData ( gd ) ; return separator ; } private static void configureTableResizing ( final Composite parent , final Composite buttons , final Table table , final TableColumn column1 , final TableColumn column2 ) { parent . addControlListener ( new ControlAdapter ( ) { public void controlResized ( ControlEvent e ) { Rectangle area = parent . getClientArea ( ) ; Point preferredSize = table . computeSize ( SWT . DEFAULT , SWT . DEFAULT ) ; int width = area . width - * table . getBorderWidth ( ) ; if ( preferredSize . y > area . height ) { Point vBarSize = table . getVerticalBar ( ) . getSize ( ) ; width -= vBarSize . x ; } width -= buttons . getSize ( ) . x ; Point oldSize = table . getSize ( ) ; if ( oldSize . x > width ) { column1 . setWidth ( width / ) ; column2 . setWidth ( width - column1 . getWidth ( ) ) ; table . setSize ( width , area . height ) ; } else { table . setSize ( width , area . height ) ; column1 . setWidth ( width / ) ; column2 . setWidth ( width - column1 . getWidth ( ) ) ; } } } ) ; } private static GridData getButtonGridData ( Button button ) { GridData data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . widthHint = SWTUtil . getButtonWidthHint ( button ) ; data . heightHint = SWTUtil . getButtonHeightHint ( button ) ; return data ; } private void selectionChanged1 ( ) { updateButtons ( ) ; } protected void updateButtons ( ) { IStructuredSelection selection = ( IStructuredSelection ) fTableViewer . getSelection ( ) ; int selectionCount = selection . size ( ) ; int itemCount = fTableViewer . getTable ( ) . getItemCount ( ) ; fEditButton . setEnabled ( selectionCount == ) ; fExportButton . setEnabled ( selectionCount > ) ; fRemoveButton . setEnabled ( selectionCount > && selectionCount <= itemCount ) ; } private void add ( ) { EvaluationExpression evalExpression = new EvaluationExpression ( "" , "" , "" , false ) ; String title = RdtDebugUiMessages . EditEvaluationExpressionDialog_add ; Dialog dialog = new EditEvaluationExpressionDialog ( getShell ( ) , title , evalExpression ) ; if ( dialog . open ( ) == Window . OK ) { fModel . addExpression ( evalExpression ) ; fTableViewer . refresh ( ) ; fTableViewer . setSelection ( new StructuredSelection ( evalExpression ) ) ; } } private void edit ( ) { IStructuredSelection selection = ( IStructuredSelection ) fTableViewer . getSelection ( ) ; Object [ ] objects = selection . toArray ( ) ; if ( ( objects == null ) || ( objects . length != ) ) return ; EvaluationExpression data = ( EvaluationExpression ) selection . getFirstElement ( ) ; edit ( data ) ; } private void edit ( EvaluationExpression evalExpression ) { String title = RdtDebugUiMessages . EditEvaluationExpressionDialog_edit ; Dialog dialog = new EditEvaluationExpressionDialog ( getShell ( ) , title , evalExpression ) ; if ( dialog . open ( ) == Window . OK ) { fTableViewer . refresh ( ) ; } } private void importFile ( ) { FileDialog dialog = new FileDialog ( getShell ( ) ) ; dialog . setText ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_import_title ) ; dialog . setFilterExtensions ( new String [ ] { RdtDebugUiMessages . EvaluationExpressionsPreferencePage_importexport_extension } ) ; String path = dialog . open ( ) ; if ( path == null ) return ; TemplateReaderWriter reader = new TemplateReaderWriter ( ) ; File file = new File ( path ) ; if ( file . exists ( ) ) { try { InputStream input = new BufferedInputStream ( new FileInputStream ( file ) ) ; fModel . importExpressions ( input ) ; } catch ( Exception e ) { RdtDebugUiPlugin . log ( e ) ; } } fTableViewer . refresh ( ) ; } private void exportFile ( ) { IStructuredSelection selection = ( IStructuredSelection ) fTableViewer . getSelection ( ) ; Object [ ] expressions = selection . toArray ( ) ; EvaluationExpression [ ] datas = new EvaluationExpression [ expressions . length ] ; for ( int i = ; i != expressions . length ; i ++ ) datas [ i ] = ( EvaluationExpression ) expressions [ i ] ; export ( datas ) ; } private void export ( EvaluationExpression [ ] expressions ) { FileDialog dialog = new FileDialog ( getShell ( ) , SWT . SAVE ) ; dialog . setText ( RdtDebugUiMessages . getFormattedString ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export_title , new Integer ( expressions . length ) ) ) ; dialog . setFilterExtensions ( new String [ ] { RdtDebugUiMessages . EvaluationExpressionsPreferencePage_importexport_extension } ) ; dialog . setFileName ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export_filename ) ; String path = dialog . open ( ) ; if ( path == null ) return ; File file = new File ( path ) ; if ( file . isHidden ( ) ) { String title = RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export_error_title ; String message = RdtDebugUiMessages . getFormattedString ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export_error_hidden , file . getAbsolutePath ( ) ) ; MessageDialog . openError ( getShell ( ) , title , message ) ; return ; } if ( file . exists ( ) && ! file . canWrite ( ) ) { String title = RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export_error_title ; String message = RdtDebugUiMessages . getFormattedString ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export_error_canNotWrite , file . getAbsolutePath ( ) ) ; MessageDialog . openError ( getShell ( ) , title , message ) ; return ; } if ( ! file . exists ( ) || confirmOverwrite ( file ) ) { try { OutputStream output = new BufferedOutputStream ( new FileOutputStream ( file ) ) ; fModel . exportExpressions ( expressions , output ) ; } catch ( Exception e ) { } } } private boolean confirmOverwrite ( File file ) { return MessageDialog . openQuestion ( getShell ( ) , RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export_exists_title , RdtDebugUiMessages . getFormattedString ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_export_exists_message , file . getAbsolutePath ( ) ) ) ; } private void remove ( ) { IStructuredSelection selection = ( IStructuredSelection ) fTableViewer . getSelection ( ) ; Iterator elements = selection . iterator ( ) ; while ( elements . hasNext ( ) ) { fModel . removeExpression ( ( EvaluationExpression ) elements . next ( ) ) ; } fTableViewer . refresh ( ) ; } public void setVisible ( boolean visible ) { super . setVisible ( visible ) ; if ( visible ) setTitle ( RdtDebugUiMessages . EvaluationExpressionsPreferencePage_title ) ; } protected void performDefaults ( ) { RdtDebugUiPlugin . getDefault ( ) . getPluginPreferences ( ) . setToDefault ( RdtDebugUiConstants . EVALUATION_EXPRESSIONS_PREFERENCE ) ; fModel . load ( ) ; fTableViewer . refresh ( ) ; } public boolean performOk ( ) { fModel . save ( ) ; return super . performOk ( ) ; } public boolean performCancel ( ) { fModel . load ( ) ; return super . performCancel ( ) ; } protected CheckboxTableViewer getTableViewer ( ) { return fTableViewer ; } } package org . rubypeople . rdt . internal . debug . ui . preferences ; import java . io . File ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; public class RubyInterpreterLabelProvider implements ITableLabelProvider { public RubyInterpreterLabelProvider ( ) { super ( ) ; } public Image getColumnImage ( Object element , int columnIndex ) { return null ; } public String getColumnText ( Object element , int columnIndex ) { IVMInstall interpreter = ( IVMInstall ) element ; switch ( columnIndex ) { case : return interpreter . getName ( ) ; case : File installLocation = interpreter . getInstallLocation ( ) ; return installLocation != null ? installLocation . getAbsolutePath ( ) : "" ; case : IVMInstallType installType = interpreter . getVMInstallType ( ) ; return installType != null ? installType . getName ( ) : "" ; default : return "" ; } } public void addListener ( ILabelProviderListener listener ) { } public void dispose ( ) { } public boolean isLabelProperty ( Object element , String property ) { return false ; } public void removeListener ( ILabelProviderListener listener ) { } } package org . rubypeople . rdt . internal . debug . ui . preferences ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . preference . PreferencePage ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . DoubleClickEvent ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . IDoubleClickListener ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . BusyIndicator ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . rubyvms . AddVMDialog ; import org . rubypeople . rdt . internal . debug . ui . rubyvms . IAddVMDialogRequestor ; import org . rubypeople . rdt . internal . debug . ui . rubyvms . RubyVMMessages ; import org . rubypeople . rdt . internal . debug . ui . rubyvms . RubyVMsUpdater ; import org . rubypeople . rdt . internal . ui . util . CollectionContentProvider ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; public class RubyInterpreterPreferencePage extends PreferencePage implements IWorkbenchPreferencePage , IAddVMDialogRequestor { private List < IVMInstall > fVMs = new ArrayList < IVMInstall > ( ) ; protected CheckboxTableViewer fVMList ; protected Button addButton , editButton , removeButton ; public RubyInterpreterPreferencePage ( ) { super ( ) ; setTitle ( RubyVMMessages . JREsPreferencePage_1 ) ; setDescription ( RubyVMMessages . JREsPreferencePage_2 ) ; } public void init ( IWorkbench workbench ) { } protected Control createContents ( Composite parent ) { noDefaultAndApplyButton ( ) ; Composite composite = createPageRoot ( parent ) ; Label tableLabel = new Label ( composite , SWT . NONE ) ; tableLabel . setText ( RubyVMMessages . InstalledJREsBlock_15 ) ; GridData data = new GridData ( ) ; data . horizontalSpan = ; tableLabel . setLayoutData ( data ) ; Font font = parent . getFont ( ) ; composite . setFont ( font ) ; tableLabel . setFont ( font ) ; Table table = createInstalledInterpretersTable ( composite ) ; createInstalledInterpretersTableViewer ( table ) ; createButtonGroup ( composite ) ; fillWithWorkspaceRubyVMs ( ) ; IVMInstall selectedInterpreter = RubyRuntime . getDefaultVMInstall ( ) ; if ( selectedInterpreter != null ) fVMList . setChecked ( selectedInterpreter , true ) ; enableButtons ( ) ; return composite ; } private void fillWithWorkspaceRubyVMs ( ) { List < VMStandin > standins = new ArrayList < VMStandin > ( ) ; IVMInstallType [ ] types = RubyRuntime . getVMInstallTypes ( ) ; for ( int i = ; i < types . length ; i ++ ) { IVMInstallType type = types [ i ] ; IVMInstall [ ] installs = type . getVMInstalls ( ) ; for ( int j = ; j < installs . length ; j ++ ) { IVMInstall install = installs [ j ] ; standins . add ( new VMStandin ( install ) ) ; } } setJREs ( ( IVMInstall [ ] ) standins . toArray ( new IVMInstall [ standins . size ( ) ] ) ) ; } protected void setJREs ( IVMInstall [ ] vms ) { fVMs . clear ( ) ; for ( int i = ; i < vms . length ; i ++ ) { fVMs . add ( vms [ i ] ) ; } fVMList . setInput ( fVMs ) ; fVMList . refresh ( ) ; } protected void createButtonGroup ( Composite composite ) { Composite buttons = new Composite ( composite , SWT . NULL ) ; buttons . setLayoutData ( new GridData ( GridData . VERTICAL_ALIGN_BEGINNING ) ) ; GridLayout layout = new GridLayout ( ) ; layout . marginHeight = ; layout . marginWidth = ; buttons . setLayout ( layout ) ; addButton = new Button ( buttons , SWT . PUSH ) ; addButton . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; addButton . setText ( RdtDebugUiMessages . RubyInterpreterPreferencePage_addButton_label ) ; addButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event evt ) { addInterpreter ( ) ; } } ) ; editButton = new Button ( buttons , SWT . PUSH ) ; editButton . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; editButton . setText ( RdtDebugUiMessages . RubyInterpreterPreferencePage_editButton_label ) ; editButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event evt ) { editInterpreter ( ) ; } } ) ; removeButton = new Button ( buttons , SWT . PUSH ) ; removeButton . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; removeButton . setText ( RdtDebugUiMessages . RubyInterpreterPreferencePage_removeButton_label ) ; removeButton . addListener ( SWT . Selection , new Listener ( ) { public void handleEvent ( Event evt ) { removeInterpreter ( ) ; } } ) ; } protected void createInstalledInterpretersTableViewer ( Table table ) { fVMList = new CheckboxTableViewer ( table ) ; fVMList . setLabelProvider ( new RubyInterpreterLabelProvider ( ) ) ; fVMList . setContentProvider ( new CollectionContentProvider ( ) ) ; fVMList . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent evt ) { enableButtons ( ) ; } } ) ; fVMList . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { updateSelectedInterpreter ( event . getElement ( ) ) ; } } ) ; fVMList . addDoubleClickListener ( new IDoubleClickListener ( ) { public void doubleClick ( DoubleClickEvent e ) { editInterpreter ( ) ; } } ) ; } protected Table createInstalledInterpretersTable ( Composite composite ) { Table table = new Table ( composite , SWT . CHECK | SWT . BORDER | SWT . FULL_SELECTION ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; table . setLayoutData ( data ) ; table . setHeaderVisible ( true ) ; table . setLinesVisible ( false ) ; TableColumn column = new TableColumn ( table , SWT . NULL ) ; column . setText ( RdtDebugUiMessages . RubyInterpreterPreferencePage_rubyInterpreterTable_interpreterName ) ; column . setWidth ( ) ; column = new TableColumn ( table , SWT . NULL ) ; column . setText ( RdtDebugUiMessages . RubyInterpreterPreferencePage_rubyInterpreterTable_interpreterPath ) ; column . setWidth ( ) ; column = new TableColumn ( table , SWT . NULL ) ; column . setText ( RdtDebugUiMessages . RubyInterpreterPreferencePage_rubyInterpreterTable_interpreterType ) ; column . setWidth ( ) ; return table ; } protected Composite createPageRoot ( Composite parent ) { Composite composite = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; composite . setLayout ( layout ) ; return composite ; } protected void addInterpreter ( ) { AddVMDialog dialog = new AddVMDialog ( this , getShell ( ) , RubyRuntime . getVMInstallTypes ( ) , null ) ; dialog . setTitle ( RubyVMMessages . InstalledJREsBlock_7 ) ; if ( dialog . open ( ) != Window . OK ) { return ; } } protected void removeInterpreter ( ) { fVMs . remove ( getSelectedInterpreter ( ) ) ; fVMList . refresh ( ) ; } protected void enableButtons ( ) { if ( getSelectedInterpreter ( ) != null ) { editButton . setEnabled ( true ) ; removeButton . setEnabled ( true ) ; } else { editButton . setEnabled ( false ) ; removeButton . setEnabled ( false ) ; } } protected void updateSelectedInterpreter ( Object interpreter ) { Object [ ] checkedElements = fVMList . getCheckedElements ( ) ; for ( int i = ; i < checkedElements . length ; i ++ ) { fVMList . setChecked ( checkedElements [ i ] , false ) ; } fVMList . setChecked ( interpreter , true ) ; } protected void editInterpreter ( ) { IStructuredSelection selection = ( IStructuredSelection ) fVMList . getSelection ( ) ; IVMInstall vm = ( IVMInstall ) selection . getFirstElement ( ) ; if ( vm == null ) { return ; } AddVMDialog dialog = new AddVMDialog ( this , getShell ( ) , RubyRuntime . getVMInstallTypes ( ) , vm ) ; dialog . setTitle ( RubyVMMessages . InstalledJREsBlock_8 ) ; if ( dialog . open ( ) != Window . OK ) { return ; } fVMList . refresh ( vm ) ; } protected IVMInstall getSelectedInterpreter ( ) { IStructuredSelection selection = ( IStructuredSelection ) fVMList . getSelection ( ) ; return ( IVMInstall ) selection . getFirstElement ( ) ; } public boolean performOk ( ) { final boolean [ ] canceled = new boolean [ ] { false } ; BusyIndicator . showWhile ( null , new Runnable ( ) { public void run ( ) { IVMInstall defaultVM = getCheckedRubyVM ( ) ; IVMInstall [ ] vms = getRubyVMs ( ) ; RubyVMsUpdater updater = new RubyVMsUpdater ( ) ; if ( ! updater . updateRubyVMSettings ( vms , defaultVM ) ) { canceled [ ] = true ; } } } ) ; if ( canceled [ ] ) { return false ; } return super . performOk ( ) ; } public IVMInstall getCheckedRubyVM ( ) { Object [ ] objects = fVMList . getCheckedElements ( ) ; if ( objects . length == ) { return null ; } return ( IVMInstall ) objects [ ] ; } public IVMInstall [ ] getRubyVMs ( ) { return ( IVMInstall [ ] ) fVMs . toArray ( new IVMInstall [ fVMs . size ( ) ] ) ; } public boolean isDuplicateName ( String name ) { for ( int i = ; i < fVMs . size ( ) ; i ++ ) { IVMInstall vm = ( IVMInstall ) fVMs . get ( i ) ; if ( vm . getName ( ) . equals ( name ) ) { return true ; } } return false ; } public void vmAdded ( IVMInstall vm ) { fVMs . add ( vm ) ; fVMList . refresh ( ) ; } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . ui . actions . ActionGroup ; import org . eclipse . ui . texteditor . ITextEditorActionConstants ; import org . rubypeople . rdt . internal . debug . ui . actions . ExpressionInspectAction ; import org . rubypeople . rdt . internal . debug . ui . evaluation . EvaluationExpression ; public class RubyEditorPopupMenuExtension extends ActionGroup { public void fillContextMenu ( IMenuManager menu ) { super . fillContextMenu ( menu ) ; MenuManager subMenu = new MenuManager ( "" , "" ) ; EvaluationExpression [ ] expressions = RdtDebugUiPlugin . getDefault ( ) . getEvaluationExpressionModel ( ) . getEvaluationExpressions ( ) ; for ( int i = ; i < expressions . length ; i ++ ) { ExpressionInspectAction action = new ExpressionInspectAction ( expressions [ i ] , this . getContext ( ) . getSelection ( ) ) ; subMenu . add ( action ) ; } if ( ! subMenu . isEmpty ( ) ) { menu . appendToGroup ( ITextEditorActionConstants . GROUP_REST , subMenu ) ; } } } package org . rubypeople . rdt . internal . debug . ui ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceConverter ; import org . eclipse . jface . resource . JFaceResources ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITypedRegion ; import org . eclipse . jface . text . contentassist . IContentAssistant ; import org . eclipse . jface . text . source . IVerticalRuler ; import org . eclipse . jface . text . source . SourceViewer ; import org . eclipse . jface . text . source . SourceViewerConfiguration ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . custom . BidiSegmentEvent ; import org . eclipse . swt . custom . BidiSegmentListener ; import org . eclipse . swt . custom . StyledText ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . texteditor . AbstractTextEditor ; import org . rubypeople . rdt . internal . debug . ui . display . DisplayViewerConfiguration ; import org . rubypeople . rdt . internal . ui . text . IRubyPartitions ; public class RubyDebugSourceViewer extends SourceViewer implements IPropertyChangeListener { private Font fFont ; private Color fBackgroundColor ; private Color fForegroundColor ; private IPreferenceStore fStore ; private DisplayViewerConfiguration fConfiguration ; public RubyDebugSourceViewer ( Composite parent , IVerticalRuler ruler , int styles ) { super ( parent , ruler , styles ) ; StyledText text = this . getTextWidget ( ) ; text . addBidiSegmentListener ( new BidiSegmentListener ( ) { public void lineGetSegments ( BidiSegmentEvent event ) { try { event . segments = getBidiLineSegments ( event . lineOffset ) ; } catch ( BadLocationException x ) { } } } ) ; } private void updateViewerFont ( ) { IPreferenceStore store = getPreferenceStore ( ) ; if ( store != null ) { FontData data = null ; if ( store . contains ( JFaceResources . TEXT_FONT ) && ! store . isDefault ( JFaceResources . TEXT_FONT ) ) { data = PreferenceConverter . getFontData ( store , JFaceResources . TEXT_FONT ) ; } else { data = PreferenceConverter . getDefaultFontData ( store , JFaceResources . TEXT_FONT ) ; } if ( data != null ) { Font font = new Font ( getTextWidget ( ) . getDisplay ( ) , data ) ; applyFont ( font ) ; if ( getFont ( ) != null ) { getFont ( ) . dispose ( ) ; } setFont ( font ) ; return ; } } applyFont ( JFaceResources . getTextFont ( ) ) ; } private void setFont ( Font font ) { fFont = font ; } private Font getFont ( ) { return fFont ; } private void applyFont ( Font font ) { IDocument doc = getDocument ( ) ; if ( doc != null && doc . getLength ( ) > ) { Point selection = getSelectedRange ( ) ; int topIndex = getTopIndex ( ) ; StyledText styledText = getTextWidget ( ) ; styledText . setRedraw ( false ) ; styledText . setFont ( font ) ; setSelectedRange ( selection . x , selection . y ) ; setTopIndex ( topIndex ) ; styledText . setRedraw ( true ) ; } else { getTextWidget ( ) . setFont ( font ) ; } } public void updateViewerColors ( ) { IPreferenceStore store = getPreferenceStore ( ) ; if ( store != null ) { StyledText styledText = getTextWidget ( ) ; Color color = store . getBoolean ( AbstractTextEditor . PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT ) ? null : createColor ( store , AbstractTextEditor . PREFERENCE_COLOR_FOREGROUND , styledText . getDisplay ( ) ) ; styledText . setForeground ( color ) ; if ( getForegroundColor ( ) != null ) { getForegroundColor ( ) . dispose ( ) ; } setForegroundColor ( color ) ; color = store . getBoolean ( AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT ) ? null : createColor ( store , AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND , styledText . getDisplay ( ) ) ; styledText . setBackground ( color ) ; if ( getBackgroundColor ( ) != null ) { getBackgroundColor ( ) . dispose ( ) ; } setBackgroundColor ( color ) ; } } private Color createColor ( IPreferenceStore store , String key , Display display ) { RGB rgb = null ; if ( store . contains ( key ) ) { if ( store . isDefault ( key ) ) { rgb = PreferenceConverter . getDefaultColor ( store , key ) ; } else { rgb = PreferenceConverter . getColor ( store , key ) ; } if ( rgb != null ) { return new Color ( display , rgb ) ; } } return null ; } protected Color getBackgroundColor ( ) { return fBackgroundColor ; } protected void setBackgroundColor ( Color backgroundColor ) { fBackgroundColor = backgroundColor ; } protected Color getForegroundColor ( ) { return fForegroundColor ; } protected void setForegroundColor ( Color foregroundColor ) { fForegroundColor = foregroundColor ; } public void propertyChange ( PropertyChangeEvent event ) { IContentAssistant assistant = getContentAssistant ( ) ; String property = event . getProperty ( ) ; if ( JFaceResources . TEXT_FONT . equals ( property ) ) { updateViewerFont ( ) ; } if ( AbstractTextEditor . PREFERENCE_COLOR_FOREGROUND . equals ( property ) || AbstractTextEditor . PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT . equals ( property ) || AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND . equals ( property ) || AbstractTextEditor . PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT . equals ( property ) ) { updateViewerColors ( ) ; } if ( fConfiguration != null ) { if ( fConfiguration . affectsTextPresentation ( event ) ) { fConfiguration . handlePropertyChangeEvent ( event ) ; invalidateTextPresentation ( ) ; } } } public IContentAssistant getContentAssistant ( ) { return fContentAssistant ; } protected int [ ] getBidiLineSegments ( int lineOffset ) throws BadLocationException { IDocument document = getDocument ( ) ; if ( document == null ) { return null ; } IRegion line = document . getLineInformationOfOffset ( lineOffset ) ; ITypedRegion [ ] linePartitioning = document . computePartitioning ( lineOffset , line . getLength ( ) ) ; List segmentation = new ArrayList ( ) ; for ( int i = ; i < linePartitioning . length ; i ++ ) { if ( IRubyPartitions . RUBY_STRING . equals ( linePartitioning [ i ] . getType ( ) ) ) segmentation . add ( linePartitioning [ i ] ) ; } if ( segmentation . size ( ) == ) return null ; int size = segmentation . size ( ) ; int [ ] segments = new int [ size * + ] ; int j = ; for ( int i = ; i < size ; i ++ ) { ITypedRegion segment = ( ITypedRegion ) segmentation . get ( i ) ; if ( i == ) segments [ j ++ ] = ; int offset = segment . getOffset ( ) - lineOffset ; if ( offset > segments [ j - ] ) segments [ j ++ ] = offset ; if ( offset + segment . getLength ( ) >= line . getLength ( ) ) break ; segments [ j ++ ] = offset + segment . getLength ( ) ; } if ( j < segments . length ) { int [ ] result = new int [ j ] ; System . arraycopy ( segments , , result , , j ) ; segments = result ; } return segments ; } public void dispose ( ) { if ( getFont ( ) != null ) { getFont ( ) . dispose ( ) ; setFont ( null ) ; } if ( getBackgroundColor ( ) != null ) { getBackgroundColor ( ) . dispose ( ) ; setBackgroundColor ( null ) ; } if ( getForegroundColor ( ) != null ) { getForegroundColor ( ) . dispose ( ) ; setForegroundColor ( null ) ; } if ( fStore != null ) { fStore . removePropertyChangeListener ( this ) ; fStore = null ; } } public void configure ( SourceViewerConfiguration configuration ) { super . configure ( configuration ) ; if ( fStore != null ) { fStore . removePropertyChangeListener ( this ) ; fStore = null ; } if ( configuration instanceof DisplayViewerConfiguration ) { fConfiguration = ( DisplayViewerConfiguration ) configuration ; fStore = fConfiguration . getTextPreferenceStore ( ) ; fStore . addPropertyChangeListener ( this ) ; } updateViewerFont ( ) ; updateViewerColors ( ) ; } private IPreferenceStore getPreferenceStore ( ) { return fStore ; } } package org . rubypeople . rdt . internal . debug . ui ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . model . IDebugElement ; import org . eclipse . debug . core . model . IStackFrame ; import org . eclipse . debug . core . model . IThread ; import org . eclipse . debug . core . model . IValue ; import org . eclipse . debug . core . model . IWatchExpressionDelegate ; import org . eclipse . debug . core . model . IWatchExpressionListener ; import org . eclipse . debug . core . model . IWatchExpressionResult ; import org . rubypeople . rdt . debug . core . model . IEvaluationResult ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; import org . rubypeople . rdt . debug . core . model . IRubyThread ; public class RubyWatchExpressionDelegate implements IWatchExpressionDelegate { private IWatchExpressionListener fListener ; private String fExpressionText ; public void evaluateExpression ( String expression , IDebugElement context , IWatchExpressionListener listener ) { fExpressionText = expression ; fListener = listener ; IStackFrame frame = null ; if ( context instanceof IStackFrame ) { frame = ( IStackFrame ) context ; } else if ( context instanceof IThread ) { try { frame = ( ( IThread ) context ) . getTopStackFrame ( ) ; } catch ( DebugException e ) { } } if ( frame == null ) { fListener . watchEvaluationFinished ( null ) ; } else { final IRubyStackFrame rubyStackFrame = ( IRubyStackFrame ) ( ( IAdaptable ) frame ) . getAdapter ( IRubyStackFrame . class ) ; if ( rubyStackFrame != null ) { doEvaluation ( rubyStackFrame ) ; } else { fListener . watchEvaluationFinished ( null ) ; } } } private void doEvaluation ( IRubyStackFrame rubyStackFrame ) { IRubyThread thread = ( IRubyThread ) rubyStackFrame . getThread ( ) ; if ( preEvaluationCheck ( thread ) ) { thread . queueRunnable ( new EvaluationRunnable ( rubyStackFrame ) ) ; } else { fListener . watchEvaluationFinished ( null ) ; } } private boolean preEvaluationCheck ( IRubyThread javaThread ) { if ( javaThread == null ) { return false ; } return true ; } private final class EvaluationRunnable implements Runnable { private final IRubyStackFrame fStackFrame ; private EvaluationRunnable ( IRubyStackFrame frame ) { fStackFrame = frame ; } public void run ( ) { IEvaluationResult result = fStackFrame . evaluate ( fExpressionText ) ; IWatchExpressionResult watchResult = new EvaluationWatchExpressionResult ( result ) ; fListener . watchEvaluationFinished ( watchResult ) ; } } private class EvaluationWatchExpressionResult implements IWatchExpressionResult { private IEvaluationResult result ; EvaluationWatchExpressionResult ( IEvaluationResult result ) { this . result = result ; } public String [ ] getErrorMessages ( ) { return result . getErrorMessages ( ) ; } public DebugException getException ( ) { return result . getException ( ) ; } public String getExpressionText ( ) { return result . getSnippet ( ) ; } public IValue getValue ( ) { return result . getValue ( ) ; } public boolean hasErrors ( ) { return result . hasErrors ( ) ; } } } package org . rubypeople . rdt . internal . debug . ui ; import java . util . Hashtable ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtension ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . dialogs . ErrorDialog ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchPage ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . debug . ui . IEvaluationContextManager ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . core . model . RubyVariable ; import org . rubypeople . rdt . internal . debug . ui . evaluation . EvaluationExpressionModel ; import org . rubypeople . rdt . ui . PreferenceConstants ; import org . rubypeople . rdt . ui . text . RubyTextTools ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; public class RdtDebugUiPlugin extends AbstractUIPlugin implements RdtDebugUiConstants { public static final String PLUGIN_ID = "" ; protected static RdtDebugUiPlugin plugin ; private EvaluationExpressionModel evaluationExpressionModel ; private ImageDescriptorRegistry fImageDescriptorRegistry ; private RubyTextTools fTextTools ; private static Hashtable < String , Image > images = new Hashtable < String , Image > ( ) ; private static IEvaluationContextManager manager ; public RdtDebugUiPlugin ( ) { super ( ) ; } public static IWorkbenchWindow getActiveWorkbenchWindow ( ) { return getDefault ( ) . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; } public static IWorkbenchPage getActivePage ( ) { IWorkbenchWindow w = getActiveWorkbenchWindow ( ) ; if ( w != null ) { return w . getActivePage ( ) ; } return null ; } public static RdtDebugUiPlugin getDefault ( ) { return plugin ; } public static IWorkspace getWorkspace ( ) { return RubyCore . getWorkspace ( ) ; } public static void log ( IStatus status ) { getDefault ( ) . getLog ( ) . log ( status ) ; } public static void log ( Throwable e ) { log ( new Status ( IStatus . ERROR , PLUGIN_ID , IStatus . ERROR , RdtDebugUiMessages . RdtDebugUiPlugin_internalErrorOccurred , e ) ) ; } public static ImageDescriptor getImageDescriptor ( String path ) { return AbstractUIPlugin . imageDescriptorFromPlugin ( PLUGIN_ID , path ) ; } public static Image getImage ( String path ) { if ( images . get ( path ) == null ) { ImageDescriptor id = getImageDescriptor ( path ) ; if ( id == null ) { return null ; } Image i = id . createImage ( ) ; images . put ( path , i ) ; return i ; } else { return ( Image ) images . get ( path ) ; } } public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { try { Platform . getAdapterManager ( ) . registerAdapters ( new ActionFilterAdapterFactory ( ) , RubyVariable . class ) ; new CodeReloader ( ) ; } catch ( Throwable e ) { log ( e ) ; } return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . schedule ( ) ; job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { try { IEvaluationContextManager manager = getEvaluationContextManager ( ) ; if ( manager != null ) manager . startup ( ) ; } catch ( Throwable e ) { log ( e ) ; } return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . schedule ( ) ; } public static IEvaluationContextManager getEvaluationContextManager ( ) { if ( manager == null ) { IExtensionPoint extension = Platform . getExtensionRegistry ( ) . getExtensionPoint ( PLUGIN_ID , "" ) ; if ( extension == null ) return EvaluationContextManager . instance ( ) ; IExtension [ ] extensions = extension . getExtensions ( ) ; for ( int i = ; i < extensions . length ; i ++ ) { IConfigurationElement [ ] configElements = extensions [ i ] . getConfigurationElements ( ) ; for ( int j = ; j < configElements . length ; j ++ ) { final IConfigurationElement configElement = configElements [ j ] ; String elementName = configElement . getName ( ) ; if ( ! ( "" . equals ( elementName ) ) ) { continue ; } try { manager = ( IEvaluationContextManager ) configElement . createExecutableExtension ( "" ) ; if ( manager != null ) { return manager ; } } catch ( Exception e ) { log ( e ) ; } } } } return manager ; } public void stop ( BundleContext context ) throws Exception { try { if ( fImageDescriptorRegistry != null ) { fImageDescriptorRegistry . dispose ( ) ; } } finally { super . stop ( context ) ; } } public EvaluationExpressionModel getEvaluationExpressionModel ( ) { if ( evaluationExpressionModel == null ) { evaluationExpressionModel = new EvaluationExpressionModel ( ) ; } return evaluationExpressionModel ; } public static String getUniqueIdentifier ( ) { return PLUGIN_ID ; } public static Display getStandardDisplay ( ) { Display display ; display = Display . getCurrent ( ) ; if ( display == null ) display = Display . getDefault ( ) ; return display ; } public static ImageDescriptorRegistry getImageDescriptorRegistry ( ) { if ( getDefault ( ) . fImageDescriptorRegistry == null ) { getDefault ( ) . fImageDescriptorRegistry = new ImageDescriptorRegistry ( ) ; } return getDefault ( ) . fImageDescriptorRegistry ; } public RubyTextTools getRubyTextTools ( ) { if ( fTextTools == null ) { fTextTools = new RubyTextTools ( PreferenceConstants . getPreferenceStore ( ) ) ; } return fTextTools ; } public static Shell getActiveWorkbenchShell ( ) { IWorkbenchWindow window = getActiveWorkbenchWindow ( ) ; if ( window != null ) { return window . getShell ( ) ; } return null ; } public static void errorDialog ( String message , IStatus status ) { log ( status ) ; Shell shell = getActiveWorkbenchShell ( ) ; if ( shell != null ) { ErrorDialog . openError ( shell , "" , message , status ) ; } } public static void errorDialog ( String message , Throwable t ) { log ( t ) ; Shell shell = getActiveWorkbenchShell ( ) ; if ( shell != null ) { IStatus status = new Status ( IStatus . ERROR , getUniqueIdentifier ( ) , RdtDebugUiConstants . INTERNAL_ERROR , "" , t ) ; ErrorDialog . openError ( shell , "" , message , status ) ; } } public static void statusDialog ( String title , IStatus status ) { Shell shell = getActiveWorkbenchShell ( ) ; if ( shell != null ) { switch ( status . getSeverity ( ) ) { case IStatus . ERROR : ErrorDialog . openError ( shell , title , null , status ) ; break ; case IStatus . WARNING : MessageDialog . openWarning ( shell , title , status . getMessage ( ) ) ; break ; case IStatus . INFO : MessageDialog . openInformation ( shell , title , status . getMessage ( ) ) ; break ; } } } } package org . rubypeople . rdt . internal . debug . ui ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . debug . core . IRubyBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyLineBreakpoint ; import org . rubypeople . rdt . debug . core . IRubyMethodBreakpoint ; public class BreakpointUtils { private static final String HANDLE_ID = RdtDebugUiPlugin . getUniqueIdentifier ( ) + "" ; private static final String RUN_TO_LINE = RdtDebugUiPlugin . getUniqueIdentifier ( ) + "" ; private static final String MEMBER_START = RdtDebugUiPlugin . getUniqueIdentifier ( ) + "" ; private static final String MEMBER_END = RdtDebugUiPlugin . getUniqueIdentifier ( ) + "" ; public static void addRubyBreakpointAttributes ( Map attributes , IRubyElement element ) { String handleId = element . getHandleIdentifier ( ) ; attributes . put ( HANDLE_ID , handleId ) ; } public static void addRubyBreakpointAttributesWithMemberDetails ( Map attributes , IRubyElement element , int memberStart , int memberEnd ) { addRubyBreakpointAttributes ( attributes , element ) ; attributes . put ( MEMBER_START , new Integer ( memberStart ) ) ; attributes . put ( MEMBER_END , new Integer ( memberEnd ) ) ; } public static IResource getBreakpointResource ( IRubyElement member ) { if ( member instanceof IMember ) { IRubyScript script = ( ( IMember ) member ) . getRubyScript ( ) ; if ( script != null && script . isWorkingCopy ( ) ) { member = ( IMember ) member . getPrimaryElement ( ) ; } } IResource res = member . getResource ( ) ; if ( res == null ) { res = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; } else if ( ! res . getProject ( ) . exists ( ) ) { res = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; } return res ; } public static IMember getMember ( IRubyLineBreakpoint breakpoint ) throws CoreException { if ( breakpoint instanceof IRubyMethodBreakpoint ) { return getMethod ( ( IRubyMethodBreakpoint ) breakpoint ) ; } int start = breakpoint . getCharStart ( ) ; int end = breakpoint . getCharEnd ( ) ; IType type = getType ( breakpoint ) ; if ( start == - && end == - ) { start = breakpoint . getMarker ( ) . getAttribute ( MEMBER_START , - ) ; end = breakpoint . getMarker ( ) . getAttribute ( MEMBER_END , - ) ; } IMember member = null ; if ( ( type != null && type . exists ( ) ) && ( end >= start ) && ( start >= ) ) { member = binSearch ( type , start , end ) ; } if ( member == null ) { member = type ; } return member ; } public static IMethod getMethod ( IRubyMethodBreakpoint breakpoint ) { String handle = breakpoint . getMarker ( ) . getAttribute ( HANDLE_ID , null ) ; if ( handle != null ) { IRubyElement je = RubyCore . create ( handle ) ; if ( je != null ) { if ( je instanceof IMethod ) { return ( IMethod ) je ; } } } return null ; } public static IType getType ( IRubyBreakpoint breakpoint ) { String handle = breakpoint . getMarker ( ) . getAttribute ( HANDLE_ID , null ) ; if ( handle != null ) { IRubyElement je = RubyCore . create ( handle ) ; if ( je != null ) { if ( je instanceof IType ) { return ( IType ) je ; } if ( je instanceof IMember ) { return ( ( IMember ) je ) . getDeclaringType ( ) ; } } } return null ; } protected static IMember binSearch ( IType type , int start , int end ) throws RubyModelException { IRubyElement je = getElementAt ( type , start ) ; if ( je != null && ! je . equals ( type ) ) { return asMember ( je ) ; } if ( end > start ) { je = getElementAt ( type , end ) ; if ( je != null && ! je . equals ( type ) ) { return asMember ( je ) ; } int mid = ( ( end - start ) / ) + start ; if ( mid > start ) { je = binSearch ( type , start + , mid ) ; if ( je == null ) { je = binSearch ( type , mid + , end - ) ; } return asMember ( je ) ; } } return null ; } private static IMember asMember ( IRubyElement element ) { if ( element instanceof IMember ) { return ( IMember ) element ; } return null ; } protected static IRubyElement getElementAt ( IType type , int pos ) throws RubyModelException { return type . getRubyScript ( ) . getElementAt ( pos ) ; } } package org . rubypeople . rdt . debug . ui ; import java . net . MalformedURLException ; import java . net . URL ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . resource . ImageRegistry ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public class RdtDebugUiImages { protected static final String NAME_PREFIX = "" ; protected static final int NAME_PREFIX_LENGTH = NAME_PREFIX . length ( ) ; protected static URL iconBaseURL ; static { iconBaseURL = RdtDebugUiPlugin . getDefault ( ) . getBundle ( ) . getEntry ( "" ) ; } protected static final ImageRegistry IMAGE_REGISTRY = new ImageRegistry ( ) ; protected static final String CTOOL_PREFIX = "" ; protected static final String EVIEW_PREFIX = "" ; public static final String IMG_EVIEW_ARGUMENTS_TAB = NAME_PREFIX + "" ; public static final ImageDescriptor DESC_EVIEW_ARGUMENTS_TAB = createManaged ( EVIEW_PREFIX , IMG_EVIEW_ARGUMENTS_TAB ) ; public static Image get ( String key ) { return IMAGE_REGISTRY . get ( key ) ; } public static void setToolImageDescriptors ( IAction action , String iconName ) { setImageDescriptors ( action , "" , iconName ) ; } public static void setLocalImageDescriptors ( IAction action , String iconName ) { setImageDescriptors ( action , "" , iconName ) ; } public static ImageRegistry getImageRegistry ( ) { return IMAGE_REGISTRY ; } protected static void setImageDescriptors ( IAction action , String type , String relPath ) { try { ImageDescriptor id = ImageDescriptor . createFromURL ( makeIconFileURL ( "" + type , relPath ) ) ; if ( id != null ) action . setDisabledImageDescriptor ( id ) ; } catch ( MalformedURLException e ) { } try { ImageDescriptor id = ImageDescriptor . createFromURL ( makeIconFileURL ( "" + type , relPath ) ) ; if ( id != null ) action . setHoverImageDescriptor ( id ) ; } catch ( MalformedURLException e ) { } action . setImageDescriptor ( create ( "" + type , relPath ) ) ; } protected static ImageDescriptor createManaged ( String prefix , String name ) { try { ImageDescriptor result = ImageDescriptor . createFromURL ( makeIconFileURL ( prefix , name . substring ( NAME_PREFIX_LENGTH ) ) ) ; IMAGE_REGISTRY . put ( name , result ) ; return result ; } catch ( MalformedURLException e ) { return ImageDescriptor . getMissingImageDescriptor ( ) ; } } protected static ImageDescriptor create ( String prefix , String name ) { try { return ImageDescriptor . createFromURL ( makeIconFileURL ( prefix , name ) ) ; } catch ( MalformedURLException e ) { return ImageDescriptor . getMissingImageDescriptor ( ) ; } } protected static URL makeIconFileURL ( String prefix , String name ) throws MalformedURLException { if ( iconBaseURL == null ) throw new MalformedURLException ( ) ; StringBuffer buffer = new StringBuffer ( prefix ) ; buffer . append ( '' ) ; buffer . append ( name ) ; return new URL ( iconBaseURL , buffer . toString ( ) ) ; } } package org . rubypeople . rdt . debug . ui ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Group ; public class SWTFactory { public static Group createGroup ( Composite parent , String text , int columns , int hspan , int fill ) { Group g = new Group ( parent , SWT . NONE ) ; g . setLayout ( new GridLayout ( columns , false ) ) ; g . setText ( text ) ; g . setFont ( parent . getFont ( ) ) ; GridData gd = new GridData ( fill ) ; gd . horizontalSpan = hspan ; g . setLayoutData ( gd ) ; return g ; } public static Combo createCombo ( Composite parent , int style , int hspan , int fill , String [ ] items ) { Combo c = new Combo ( parent , style ) ; c . setFont ( parent . getFont ( ) ) ; GridData gd = new GridData ( fill ) ; gd . horizontalSpan = hspan ; c . setLayoutData ( gd ) ; if ( items != null ) { c . setItems ( items ) ; } c . select ( ) ; return c ; } public static Composite createComposite ( Composite parent , Font font , int columns , int hspan , int fill ) { Composite g = new Composite ( parent , SWT . NONE ) ; g . setLayout ( new GridLayout ( columns , false ) ) ; g . setFont ( font ) ; GridData gd = new GridData ( fill ) ; gd . horizontalSpan = hspan ; g . setLayoutData ( gd ) ; return g ; } } package org . rubypeople . rdt . debug . ui ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . IWorkbenchWindow ; import org . rubypeople . rdt . debug . core . model . IRubyStackFrame ; public interface IEvaluationContextManager { public IRubyStackFrame getEvaluationContext ( IWorkbenchPart part ) ; public IRubyStackFrame getEvaluationContext ( IWorkbenchWindow window ) ; public void startup ( ) ; } package org . rubypeople . rdt . debug . ui ; import java . io . File ; import java . net . MalformedURLException ; import java . net . URL ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Link ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . browser . IWorkbenchBrowserSupport ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . RubyRuntime ; public class InstallDeveloperToolsDialog extends Dialog { public InstallDeveloperToolsDialog ( Shell parentShell ) { super ( parentShell ) ; setShellStyle ( getDefaultOrientation ( ) | SWT . RESIZE | SWT . APPLICATION_MODAL | SWT . DIALOG_TRIM ) ; } protected void configureShell ( Shell newShell ) { super . configureShell ( newShell ) ; newShell . setText ( RdtDebugUiMessages . ToolChainNotFound_title ) ; } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; Composite control = new Composite ( composite , SWT . NULL ) ; GridLayout layout = new GridLayout ( , false ) ; control . setLayout ( layout ) ; control . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; if ( Platform . getOS ( ) . equals ( Platform . OS_MACOSX ) ) { createMacDialog ( control ) ; } else { createLinuxDialog ( control ) ; } GridData data = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; control . setLayoutData ( data ) ; return composite ; } private void createLinuxDialog ( Composite parent ) { Label label = new Label ( parent , SWT . LEFT | SWT . WRAP ) ; label . setText ( RdtDebugUiMessages . ToolChainNotFound_msg ) ; GridData data = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; data . widthHint = ; label . setLayoutData ( data ) ; } private void createMacDialog ( Composite parent ) { FontData [ ] fds = parent . getFont ( ) . getFontData ( ) ; for ( FontData fd : fds ) { fd . setHeight ( fd . getHeight ( ) + ) ; fd . setStyle ( SWT . BOLD ) ; } final Font font = new Font ( parent . getDisplay ( ) , fds ) ; fds = parent . getFont ( ) . getFontData ( ) ; for ( FontData fd : fds ) { fd . setHeight ( fd . getHeight ( ) + ) ; fd . setStyle ( SWT . BOLD ) ; } final Font font2 = new Font ( parent . getDisplay ( ) , fds ) ; Composite top = new Composite ( parent , SWT . NONE ) ; top . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { if ( font != null && ! font . isDisposed ( ) ) { font . dispose ( ) ; } if ( font2 != null && ! font2 . isDisposed ( ) ) { font2 . dispose ( ) ; } } } ) ; GridLayout tLayout = new GridLayout ( , false ) ; tLayout . marginHeight = ; tLayout . marginWidth = ; tLayout . marginBottom = ; top . setLayout ( tLayout ) ; top . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; GridData iconData = new GridData ( SWT . FILL , SWT . TOP , true , false ) ; iconData . verticalIndent = ; Label icon = new Label ( top , SWT . LEFT ) ; icon . setImage ( RdtDebugUiPlugin . getImage ( "" ) ) ; icon . setLayoutData ( iconData ) ; Composite rightTop = new Composite ( top , SWT . NONE ) ; GridLayout rtLayout = new GridLayout ( , false ) ; rtLayout . marginHeight = ; rtLayout . marginWidth = ; rightTop . setLayout ( rtLayout ) ; Label title = new Label ( rightTop , SWT . LEFT ) ; title . setFont ( font ) ; title . setText ( "" ) ; title . setLayoutData ( new GridData ( SWT . FILL , SWT . TOP , true , false ) ) ; Label line1 = new Label ( rightTop , SWT . LEFT ) ; line1 . setText ( "" ) ; Label line2 = new Label ( rightTop , SWT . LEFT ) ; line2 . setText ( "" ) ; Label installDiskLabel = new Label ( parent , SWT . LEFT ) ; installDiskLabel . setImage ( RdtDebugUiPlugin . getImage ( "" ) ) ; installDiskLabel . setLayoutData ( new GridData ( SWT . CENTER , SWT . END , true , false ) ) ; GridData oData = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; oData . horizontalIndent = ; Label optionA = new Label ( parent , SWT . LEFT ) ; optionA . setLayoutData ( oData ) ; optionA . setFont ( font2 ) ; optionA . setText ( "" ) ; GridData iData = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; iData . horizontalIndent = ; Label instructionA = new Label ( parent , SWT . LEFT ) ; instructionA . setLayoutData ( iData ) ; instructionA . setText ( "" ) ; Label optionB = new Label ( parent , SWT . LEFT ) ; GridData oData2 = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; oData2 . horizontalIndent = ; oData2 . verticalIndent = ; optionB . setFont ( font2 ) ; optionB . setLayoutData ( oData2 ) ; optionB . setText ( "" ) ; Link instructionsB = new Link ( parent , SWT . LEFT ) ; instructionsB . setText ( "" ) ; instructionsB . setLayoutData ( iData ) ; instructionsB . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { try { IWorkbenchBrowserSupport support = PlatformUI . getWorkbench ( ) . getBrowserSupport ( ) ; if ( support != null ) { support . createBrowser ( null ) . openURL ( new URL ( "" ) ) ; } } catch ( PartInitException e1 ) { RdtDebugUiPlugin . log ( e1 ) ; } catch ( MalformedURLException e1 ) { RdtDebugUiPlugin . log ( e1 ) ; } } } ) ; } protected void createButtonsForButtonBar ( Composite parent ) { createButton ( parent , IDialogConstants . OK_ID , IDialogConstants . OK_LABEL , true ) ; } private static boolean osAndVMNeedCompiling ( ) { if ( RubyRuntime . currentVMIsCygwin ( ) ) return true ; if ( RubyRuntime . currentVMIsJRuby ( ) ) return false ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) return false ; return true ; } private static boolean hasMake ( ) { if ( RubyRuntime . currentVMIsCygwin ( ) ) { IVMInstall install = RubyRuntime . getDefaultVMInstall ( ) ; File location = install . getInstallLocation ( ) ; String [ ] binDirs = new String [ ] { "" , "" , "" } ; for ( int i = ; i < binDirs . length ; i ++ ) { File exe = new File ( location . getAbsolutePath ( ) + File . separator + binDirs [ i ] + File . separator + "" ) ; if ( exe . exists ( ) && exe . isFile ( ) ) { return true ; } } } IPath path = RubyCore . checkSystemPath ( "" ) ; if ( path != null && path . toFile ( ) . exists ( ) ) { return true ; } path = RubyCore . checkCommonBinLocations ( "" ) ; if ( path != null && path . toFile ( ) . exists ( ) ) { return true ; } return false ; } public static boolean shouldShow ( ) { return osAndVMNeedCompiling ( ) && ! hasMake ( ) ; } } package org . rubypeople . rdt . debug . ui . launchConfigurations ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . ui . AbstractLaunchConfigurationTab ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . IWorkbenchPage ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public abstract class RubyLaunchTab extends AbstractLaunchConfigurationTab { private ILaunchConfiguration fLaunchConfig ; protected IRubyElement getContext ( ) { IWorkbenchPage page = RdtDebugUiPlugin . getActivePage ( ) ; if ( page != null ) { ISelection selection = page . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { IStructuredSelection ss = ( IStructuredSelection ) selection ; if ( ! ss . isEmpty ( ) ) { Object obj = ss . getFirstElement ( ) ; if ( obj instanceof IRubyElement ) { return ( IRubyElement ) obj ; } if ( obj instanceof IResource ) { IRubyElement je = RubyCore . create ( ( IResource ) obj ) ; if ( je == null ) { IProject pro = ( ( IResource ) obj ) . getProject ( ) ; je = RubyCore . create ( pro ) ; } if ( je != null ) { return je ; } } } } IEditorPart part = page . getActiveEditor ( ) ; if ( part != null ) { IEditorInput input = part . getEditorInput ( ) ; return ( IRubyElement ) input . getAdapter ( IRubyElement . class ) ; } } return null ; } protected ILaunchConfiguration getCurrentLaunchConfiguration ( ) { return fLaunchConfig ; } private void setCurrentLaunchConfiguration ( ILaunchConfiguration config ) { fLaunchConfig = config ; } protected void initializeRubyProject ( IRubyElement javaElement , ILaunchConfigurationWorkingCopy config ) { IRubyProject javaProject = javaElement . getRubyProject ( ) ; String name = null ; if ( javaProject != null && javaProject . exists ( ) ) { name = javaProject . getElementName ( ) ; } config . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , name ) ; } public void initializeFrom ( ILaunchConfiguration config ) { setCurrentLaunchConfiguration ( config ) ; } } package org . rubypeople . rdt . debug . ui . launchConfigurations ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . ui . DebugUITools ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . jface . preference . FieldEditor ; import org . eclipse . jface . preference . IntegerFieldEditor ; import org . eclipse . jface . preference . PreferenceStore ; import org . eclipse . jface . preference . StringFieldEditor ; import org . eclipse . jface . util . IPropertyChangeListener ; import org . eclipse . jface . util . PropertyChangeEvent ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Group ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . debug . ui . SWTFactory ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . debug . ui . launcher . AbstractRubyMainTab ; import org . rubypeople . rdt . internal . debug . ui . launcher . LauncherMessages ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMConnector ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RubyConnectTab extends AbstractRubyMainTab implements IPropertyChangeListener { private Map < String , Object > fArgumentMap ; private Map < String , FieldEditor > fFieldEditorMap = new HashMap < String , FieldEditor > ( ) ; private Composite fArgumentComposite ; private Combo fConnectorCombo ; private IVMConnector fConnector ; private IVMConnector [ ] fConnectors = RubyRuntime . getVMConnectors ( ) ; public void createControl ( Composite parent ) { Font font = parent . getFont ( ) ; Composite comp = SWTFactory . createComposite ( parent , font , , , GridData . FILL_BOTH ) ; GridLayout layout = new GridLayout ( ) ; layout . verticalSpacing = ; comp . setLayout ( layout ) ; createProjectEditor ( comp ) ; createVerticalSpacer ( comp , ) ; Group group = SWTFactory . createGroup ( comp , LauncherMessages . RubyConnectTab_Connect_ion_Type__7 , , , GridData . FILL_HORIZONTAL ) ; String [ ] names = new String [ fConnectors . length ] ; for ( int i = ; i < fConnectors . length ; i ++ ) { names [ i ] = fConnectors [ i ] . getName ( ) ; } fConnectorCombo = SWTFactory . createCombo ( group , SWT . READ_ONLY , , GridData . FILL_HORIZONTAL , names ) ; fConnectorCombo . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { handleConnectorComboModified ( ) ; } } ) ; createVerticalSpacer ( comp , ) ; group = SWTFactory . createGroup ( comp , LauncherMessages . RubyConnectTab_Connection_Properties_1 , , , GridData . FILL_HORIZONTAL ) ; Composite cgroup = SWTFactory . createComposite ( group , font , , , GridData . FILL_HORIZONTAL ) ; fArgumentComposite = cgroup ; createVerticalSpacer ( comp , ) ; setControl ( comp ) ; } private void handleConnectorComboModified ( ) { int index = fConnectorCombo . getSelectionIndex ( ) ; if ( ( index < ) || ( index >= fConnectors . length ) ) { return ; } IVMConnector vm = fConnectors [ index ] ; if ( vm . equals ( fConnector ) ) { return ; } fConnector = vm ; try { fArgumentMap = vm . getDefaultArguments ( ) ; } catch ( CoreException e ) { RdtDebugUiPlugin . statusDialog ( LauncherMessages . RubyConnectTab_Unable_to_display_connection_arguments__2 , e . getStatus ( ) ) ; return ; } Control [ ] children = fArgumentComposite . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { children [ i ] . dispose ( ) ; } fFieldEditorMap . clear ( ) ; PreferenceStore store = new PreferenceStore ( ) ; Iterator < String > keys = vm . getArgumentOrder ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; Object arg = fArgumentMap . get ( key ) ; FieldEditor field = null ; if ( arg instanceof Integer ) { store . setDefault ( key , ( ( Integer ) arg ) . intValue ( ) ) ; field = new IntegerFieldEditor ( key , key , fArgumentComposite ) ; } else if ( arg instanceof String ) { store . setDefault ( key , ( String ) arg ) ; field = new StringFieldEditor ( key , key , fArgumentComposite ) ; } if ( field != null ) { field . setPreferenceStore ( store ) ; field . loadDefault ( ) ; field . setPropertyChangeListener ( this ) ; fFieldEditorMap . put ( key , field ) ; } } fArgumentComposite . getParent ( ) . getParent ( ) . layout ( ) ; fArgumentComposite . layout ( true ) ; updateLaunchConfigurationDialog ( ) ; } public void initializeFrom ( ILaunchConfiguration config ) { super . initializeFrom ( config ) ; updateConnectionFromConfig ( config ) ; } private void updateConnectionFromConfig ( ILaunchConfiguration config ) { String id = null ; try { id = config . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_CONNECTOR , RubyRuntime . getDefaultVMConnector ( ) . getIdentifier ( ) ) ; fConnectorCombo . setText ( RubyRuntime . getVMConnector ( id ) . getName ( ) ) ; handleConnectorComboModified ( ) ; Map < String , Object > attrMap = config . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_CONNECT_MAP , ( Map ) null ) ; if ( attrMap == null ) { return ; } Iterator < String > keys = attrMap . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; Object arg = fArgumentMap . get ( key ) ; FieldEditor editor = ( FieldEditor ) fFieldEditorMap . get ( key ) ; if ( arg != null && editor != null ) { String value = ( String ) attrMap . get ( key ) ; if ( arg instanceof String ) { editor . getPreferenceStore ( ) . setValue ( key , value ) ; } else if ( arg instanceof Integer ) { editor . getPreferenceStore ( ) . setValue ( key , new Integer ( value ) . intValue ( ) ) ; } editor . load ( ) ; } } } catch ( CoreException ce ) { RdtDebugUiPlugin . log ( ce ) ; } } public void performApply ( ILaunchConfigurationWorkingCopy config ) { config . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , fProjText . getText ( ) . trim ( ) ) ; config . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_CONNECTOR , getSelectedConnector ( ) . getIdentifier ( ) ) ; mapResources ( config ) ; Map < String , Object > attrMap = new HashMap < String , Object > ( fFieldEditorMap . size ( ) ) ; Iterator < String > keys = fFieldEditorMap . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; FieldEditor editor = ( FieldEditor ) fFieldEditorMap . get ( key ) ; if ( ! editor . isValid ( ) ) { return ; } Object arg = ( Object ) fArgumentMap . get ( key ) ; editor . store ( ) ; if ( arg instanceof String ) { attrMap . put ( key , editor . getPreferenceStore ( ) . getString ( key ) ) ; } else if ( arg instanceof Integer ) { attrMap . put ( key , new Integer ( editor . getPreferenceStore ( ) . getInt ( key ) ) . toString ( ) ) ; } } config . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_CONNECT_MAP , attrMap ) ; } private void initializeDefaults ( IRubyElement javaElement , ILaunchConfigurationWorkingCopy config ) { initializeRubyProject ( javaElement , config ) ; initializeName ( javaElement , config ) ; initializeHardCodedDefaults ( config ) ; } public void setDefaults ( ILaunchConfigurationWorkingCopy config ) { IRubyElement javaElement = getContext ( ) ; if ( javaElement == null ) { initializeHardCodedDefaults ( config ) ; } else { initializeDefaults ( javaElement , config ) ; } } private void initializeName ( IRubyElement javaElement , ILaunchConfigurationWorkingCopy config ) { String name = EMPTY_STRING ; try { IResource resource = javaElement . getUnderlyingResource ( ) ; if ( resource != null ) { name = resource . getName ( ) ; int index = name . lastIndexOf ( '' ) ; if ( index > ) { name = name . substring ( , index ) ; } } else { name = javaElement . getElementName ( ) ; } name = getLaunchConfigurationDialog ( ) . generateName ( name ) ; } catch ( RubyModelException jme ) { RdtDebugUiPlugin . log ( jme ) ; } config . rename ( name ) ; } private void initializeHardCodedDefaults ( ILaunchConfigurationWorkingCopy config ) { config . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_CONNECTOR , RubyRuntime . getDefaultVMConnector ( ) . getIdentifier ( ) ) ; } public boolean isValid ( ILaunchConfiguration config ) { setErrorMessage ( null ) ; setMessage ( null ) ; String name = fProjText . getText ( ) . trim ( ) ; if ( name . length ( ) > ) { if ( ! ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( name ) . exists ( ) ) { setErrorMessage ( LauncherMessages . RubyConnectTab_Project_does_not_exist_14 ) ; return false ; } } Iterator < String > keys = fFieldEditorMap . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; Object arg = ( Object ) fArgumentMap . get ( key ) ; FieldEditor editor = ( FieldEditor ) fFieldEditorMap . get ( key ) ; if ( editor instanceof StringFieldEditor ) { String value = ( ( StringFieldEditor ) editor ) . getStringValue ( ) ; } } return true ; } public String getName ( ) { return LauncherMessages . RubyConnectTab_Conn_ect_20 ; } public Image getImage ( ) { return DebugUITools . getImage ( IDebugUIConstants . IMG_LCL_DISCONNECT ) ; } public String getId ( ) { return "" ; } private IVMConnector getSelectedConnector ( ) { return fConnector ; } public void propertyChange ( PropertyChangeEvent event ) { updateLaunchConfigurationDialog ( ) ; } } package org . rubypeople . rdt . debug . ui ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; public interface RdtDebugUiConstants { public static final String PREFERENCE_KEYWORDS = RdtDebugUiPlugin . PLUGIN_ID + "" ; public static final String SHOW_STATIC_VARIABLES_PREFERENCE = RdtDebugUiPlugin . PLUGIN_ID + "" ; public static final String SHOW_CONSTANTS_PREFERENCE = RdtDebugUiPlugin . PLUGIN_ID + "" ; public static final String EVALUATION_EXPRESSIONS_PREFERENCE = RdtDebugUiPlugin . PLUGIN_ID + "" ; public static final int INTERNAL_ERROR = ; public static final String EVALUATION_GROUP = "" ; public static final String ID_DISPLAY_VIEW = RdtDebugUiPlugin . PLUGIN_ID + "" ; public static final String RUBY_SOURCE_LOCATOR = "" ; } package org . xmlpull . v1 ; public class XmlPullParserException extends Exception { private static final long serialVersionUID = ; protected Throwable detail ; protected int row = - ; protected int column = - ; public XmlPullParserException ( String s ) { super ( s ) ; } public XmlPullParserException ( String msg , XmlPullParser parser , Throwable chain ) { super ( ( msg == null ? "" : msg + "" ) + ( parser == null ? "" : "" + parser . getPositionDescription ( ) + "" ) + ( chain == null ? "" : "" + chain ) ) ; if ( parser != null ) { this . row = parser . getLineNumber ( ) ; this . column = parser . getColumnNumber ( ) ; } this . detail = chain ; } public Throwable getDetail ( ) { return detail ; } public int getLineNumber ( ) { return row ; } public int getColumnNumber ( ) { return column ; } public void printStackTrace ( ) { if ( detail == null ) { super . printStackTrace ( ) ; } else { synchronized ( System . err ) { System . err . println ( super . getMessage ( ) + "" ) ; detail . printStackTrace ( ) ; } } } } package org . xmlpull . v1 ; import java . io . InputStream ; import java . util . Enumeration ; import java . util . Hashtable ; import java . util . Vector ; public class XmlPullParserFactory { public static final String PROPERTY_NAME = "" ; private static final String RESOURCE_NAME = "" + PROPERTY_NAME ; protected Vector parserClasses ; protected String classNamesLocation ; protected Vector serializerClasses ; protected Hashtable features = new Hashtable ( ) ; protected XmlPullParserFactory ( ) { } public void setFeature ( String name , boolean state ) throws XmlPullParserException { features . put ( name , new Boolean ( state ) ) ; } public boolean getFeature ( String name ) { Boolean value = ( Boolean ) features . get ( name ) ; return value != null ? value . booleanValue ( ) : false ; } public void setNamespaceAware ( boolean awareness ) { features . put ( XmlPullParser . FEATURE_PROCESS_NAMESPACES , new Boolean ( awareness ) ) ; } public boolean isNamespaceAware ( ) { return getFeature ( XmlPullParser . FEATURE_PROCESS_NAMESPACES ) ; } public void setValidating ( boolean validating ) { features . put ( XmlPullParser . FEATURE_VALIDATION , new Boolean ( validating ) ) ; } public boolean isValidating ( ) { return getFeature ( XmlPullParser . FEATURE_VALIDATION ) ; } public XmlPullParser newPullParser ( ) throws XmlPullParserException { if ( parserClasses == null ) throw new XmlPullParserException ( "" + classNamesLocation ) ; if ( parserClasses . size ( ) == ) throw new XmlPullParserException ( "" + classNamesLocation ) ; StringBuffer issues = new StringBuffer ( ) ; for ( int i = ; i < parserClasses . size ( ) ; i ++ ) { Class ppClass = ( Class ) parserClasses . elementAt ( i ) ; try { XmlPullParser pp = ( XmlPullParser ) ppClass . newInstance ( ) ; for ( Enumeration e = features . keys ( ) ; e . hasMoreElements ( ) ; ) { String key = ( String ) e . nextElement ( ) ; Boolean value = ( Boolean ) features . get ( key ) ; if ( value != null && value . booleanValue ( ) ) { pp . setFeature ( key , true ) ; } } return pp ; } catch ( Exception ex ) { issues . append ( ppClass . getName ( ) + "" + ex . toString ( ) + "" ) ; } } throw new XmlPullParserException ( "" + issues ) ; } public XmlSerializer newSerializer ( ) throws XmlPullParserException { if ( serializerClasses == null ) { throw new XmlPullParserException ( "" + classNamesLocation ) ; } if ( serializerClasses . size ( ) == ) { throw new XmlPullParserException ( "" + classNamesLocation ) ; } StringBuffer issues = new StringBuffer ( ) ; for ( int i = ; i < serializerClasses . size ( ) ; i ++ ) { Class ppClass = ( Class ) serializerClasses . elementAt ( i ) ; try { XmlSerializer ser = ( XmlSerializer ) ppClass . newInstance ( ) ; return ser ; } catch ( Exception ex ) { issues . append ( ppClass . getName ( ) + "" + ex . toString ( ) + "" ) ; } } throw new XmlPullParserException ( "" + issues ) ; } public static XmlPullParserFactory newInstance ( ) throws XmlPullParserException { return newInstance ( null , null ) ; } public static XmlPullParserFactory newInstance ( String classNames , Class context ) throws XmlPullParserException { if ( context == null ) context = "" . getClass ( ) ; String classNamesLocation = null ; if ( classNames == null || classNames . length ( ) == || "" . equals ( classNames ) ) { try { InputStream is = context . getResourceAsStream ( RESOURCE_NAME ) ; if ( is == null ) throw new XmlPullParserException ( "" + RESOURCE_NAME ) ; StringBuffer sb = new StringBuffer ( ) ; while ( true ) { int ch = is . read ( ) ; if ( ch < ) break ; else if ( ch > '' ) sb . append ( ( char ) ch ) ; } is . close ( ) ; classNames = sb . toString ( ) ; } catch ( Exception e ) { throw new XmlPullParserException ( null , null , e ) ; } classNamesLocation = "" + RESOURCE_NAME + "" + classNames + "" ; } else { classNamesLocation = "" + classNames + "" ; } XmlPullParserFactory factory = null ; Vector parserClasses = new Vector ( ) ; Vector serializerClasses = new Vector ( ) ; int pos = ; while ( pos < classNames . length ( ) ) { int cut = classNames . indexOf ( '' , pos ) ; if ( cut == - ) cut = classNames . length ( ) ; String name = classNames . substring ( pos , cut ) ; Class candidate = null ; Object instance = null ; try { candidate = Class . forName ( name ) ; instance = candidate . newInstance ( ) ; } catch ( Exception e ) { } if ( candidate != null ) { boolean recognized = false ; if ( XmlPullParser . class . isAssignableFrom ( candidate ) ) { parserClasses . addElement ( candidate ) ; recognized = true ; } if ( XmlSerializer . class . isAssignableFrom ( candidate ) ) { serializerClasses . addElement ( candidate ) ; recognized = true ; } if ( XmlPullParserFactory . class . isAssignableFrom ( candidate ) ) { if ( factory == null ) { factory = ( XmlPullParserFactory ) instance ; } recognized = true ; } if ( ! recognized ) { throw new XmlPullParserException ( "" + name ) ; } } pos = cut + ; } if ( factory == null ) { factory = new XmlPullParserFactory ( ) ; } factory . parserClasses = parserClasses ; factory . serializerClasses = serializerClasses ; factory . classNamesLocation = classNamesLocation ; return factory ; } } package org . xmlpull . v1 ; import java . io . IOException ; import java . io . OutputStream ; import java . io . Writer ; public interface XmlSerializer { public void setFeature ( String name , boolean state ) throws IllegalArgumentException , IllegalStateException ; public boolean getFeature ( String name ) ; public void setProperty ( String name , Object value ) throws IllegalArgumentException , IllegalStateException ; public Object getProperty ( String name ) ; public void setOutput ( OutputStream os , String encoding ) throws IOException , IllegalArgumentException , IllegalStateException ; public void setOutput ( Writer writer ) throws IOException , IllegalArgumentException , IllegalStateException ; public void startDocument ( String encoding , Boolean standalone ) throws IOException , IllegalArgumentException , IllegalStateException ; public void endDocument ( ) throws IOException , IllegalArgumentException , IllegalStateException ; public void setPrefix ( String prefix , String namespace ) throws IOException , IllegalArgumentException , IllegalStateException ; public String getPrefix ( String namespace , boolean generatePrefix ) throws IllegalArgumentException ; public XmlSerializer startTag ( String namespace , String name ) throws IOException , IllegalArgumentException , IllegalStateException ; public XmlSerializer attribute ( String namespace , String name , String value ) throws IOException , IllegalArgumentException , IllegalStateException ; public XmlSerializer endTag ( String namespace , String name ) throws IOException , IllegalArgumentException , IllegalStateException ; public XmlSerializer text ( String text ) throws IOException , IllegalArgumentException , IllegalStateException ; public XmlSerializer text ( char [ ] buf , int start , int len ) throws IOException , IllegalArgumentException , IllegalStateException ; public void cdsect ( String text ) throws IOException , IllegalArgumentException , IllegalStateException ; public void entityRef ( String text ) throws IOException , IllegalArgumentException , IllegalStateException ; public void processingInstruction ( String text ) throws IOException , IllegalArgumentException , IllegalStateException ; public void comment ( String text ) throws IOException , IllegalArgumentException , IllegalStateException ; public void docdecl ( String text ) throws IOException , IllegalArgumentException , IllegalStateException ; public void ignorableWhitespace ( String text ) throws IOException , IllegalArgumentException , IllegalStateException ; public void flush ( ) throws IOException ; } package org . xmlpull . v1 ; import java . io . InputStream ; import java . io . IOException ; import java . io . Reader ; public interface XmlPullParser { public static final String NO_NAMESPACE = "" ; public final static int START_DOCUMENT = ; public final static int END_DOCUMENT = ; public final static int START_TAG = ; public final static int END_TAG = ; public final static int TEXT = ; public final static int CDSECT = ; public final static int ENTITY_REF = ; public static final int IGNORABLE_WHITESPACE = ; public static final int PROCESSING_INSTRUCTION = ; public static final int COMMENT = ; public static final int DOCDECL = ; public static final String [ ] TYPES = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; public static final String FEATURE_PROCESS_NAMESPACES = "" ; public static final String FEATURE_REPORT_NAMESPACE_ATTRIBUTES = "" ; public static final String FEATURE_PROCESS_DOCDECL = "" ; public static final String FEATURE_VALIDATION = "" ; public void setFeature ( String name , boolean state ) throws XmlPullParserException ; public boolean getFeature ( String name ) ; public void setProperty ( String name , Object value ) throws XmlPullParserException ; public Object getProperty ( String name ) ; public void setInput ( Reader in ) throws XmlPullParserException ; public void setInput ( InputStream inputStream , String inputEncoding ) throws XmlPullParserException ; public String getInputEncoding ( ) ; public void defineEntityReplacementText ( String entityName , String replacementText ) throws XmlPullParserException ; public int getNamespaceCount ( int depth ) throws XmlPullParserException ; public String getNamespacePrefix ( int pos ) throws XmlPullParserException ; public String getNamespaceUri ( int pos ) throws XmlPullParserException ; public String getNamespace ( String prefix ) ; public int getDepth ( ) ; public String getPositionDescription ( ) ; public int getLineNumber ( ) ; public int getColumnNumber ( ) ; public boolean isWhitespace ( ) throws XmlPullParserException ; public String getText ( ) ; public char [ ] getTextCharacters ( int [ ] holderForStartAndLength ) ; public String getNamespace ( ) ; public String getName ( ) ; public String getPrefix ( ) ; public boolean isEmptyElementTag ( ) throws XmlPullParserException ; public int getAttributeCount ( ) ; public String getAttributeNamespace ( int index ) ; public String getAttributeName ( int index ) ; public String getAttributePrefix ( int index ) ; public String getAttributeType ( int index ) ; public boolean isAttributeDefault ( int index ) ; public String getAttributeValue ( int index ) ; public String getAttributeValue ( String namespace , String name ) ; public int getEventType ( ) throws XmlPullParserException ; public int next ( ) throws XmlPullParserException , IOException ; public int nextToken ( ) throws XmlPullParserException , IOException ; public void require ( int type , String namespace , String name ) throws XmlPullParserException , IOException ; public String nextText ( ) throws XmlPullParserException , IOException ; public int nextTag ( ) throws XmlPullParserException , IOException ; } package org . kxml2 . kdom ; import java . util . * ; import java . io . * ; import org . xmlpull . v1 . * ; public class Node { public static final int DOCUMENT = ; public static final int ELEMENT = ; public static final int TEXT = ; public static final int CDSECT = ; public static final int ENTITY_REF = ; public static final int IGNORABLE_WHITESPACE = ; public static final int PROCESSING_INSTRUCTION = ; public static final int COMMENT = ; public static final int DOCDECL = ; protected Vector children ; protected StringBuffer types ; public void addChild ( int index , int type , Object child ) { if ( child == null ) throw new NullPointerException ( ) ; if ( children == null ) { children = new Vector ( ) ; types = new StringBuffer ( ) ; } if ( type == ELEMENT ) { if ( ! ( child instanceof Element ) ) throw new RuntimeException ( "" ) ; ( ( Element ) child ) . setParent ( this ) ; } else if ( ! ( child instanceof String ) ) throw new RuntimeException ( "" ) ; children . insertElementAt ( child , index ) ; types . insert ( index , ( char ) type ) ; } public void addChild ( int type , Object child ) { addChild ( getChildCount ( ) , type , child ) ; } public Element createElement ( String namespace , String name ) { Element e = new Element ( ) ; e . namespace = namespace == null ? "" : namespace ; e . name = name ; return e ; } public Object getChild ( int index ) { return children . elementAt ( index ) ; } public int getChildCount ( ) { return children == null ? : children . size ( ) ; } public Element getElement ( int index ) { Object child = getChild ( index ) ; return ( child instanceof Element ) ? ( Element ) child : null ; } public Element getElement ( String namespace , String name ) { int i = indexOf ( namespace , name , ) ; int j = indexOf ( namespace , name , i + ) ; if ( i == - || j != - ) throw new RuntimeException ( "" + namespace + "" + name + ( i == - ? "" : "" ) + this ) ; return getElement ( i ) ; } public String getText ( int index ) { return ( isText ( index ) ) ? ( String ) getChild ( index ) : null ; } public int getType ( int index ) { return types . charAt ( index ) ; } public int indexOf ( String namespace , String name , int startIndex ) { int len = getChildCount ( ) ; for ( int i = startIndex ; i < len ; i ++ ) { Element child = getElement ( i ) ; if ( child != null && name . equals ( child . getName ( ) ) && ( namespace == null || namespace . equals ( child . getNamespace ( ) ) ) ) return i ; } return - ; } public boolean isText ( int i ) { int t = getType ( i ) ; return t == TEXT || t == IGNORABLE_WHITESPACE || t == CDSECT ; } public void parse ( XmlPullParser parser ) throws IOException , XmlPullParserException { boolean leave = false ; do { int type = parser . getEventType ( ) ; switch ( type ) { case XmlPullParser . START_TAG : { Element child = createElement ( parser . getNamespace ( ) , parser . getName ( ) ) ; addChild ( ELEMENT , child ) ; child . parse ( parser ) ; break ; } case XmlPullParser . END_DOCUMENT : case XmlPullParser . END_TAG : leave = true ; break ; default : if ( parser . getText ( ) == null ) addChild ( ENTITY_REF , parser . getName ( ) ) ; else addChild ( type == XmlPullParser . ENTITY_REF ? TEXT : type , parser . getText ( ) ) ; parser . nextToken ( ) ; } } while ( ! leave ) ; } public void removeChild ( int idx ) { children . removeElementAt ( idx ) ; int n = types . length ( ) - ; for ( int i = idx ; i < n ; i ++ ) types . setCharAt ( i , types . charAt ( i + ) ) ; types . setLength ( n ) ; } public void write ( XmlSerializer writer ) throws IOException { writeChildren ( writer ) ; writer . flush ( ) ; } public void writeChildren ( XmlSerializer writer ) throws IOException { if ( children == null ) return ; int len = children . size ( ) ; for ( int i = ; i < len ; i ++ ) { int type = getType ( i ) ; Object child = children . elementAt ( i ) ; switch ( type ) { case ELEMENT : ( ( Element ) child ) . write ( writer ) ; break ; case TEXT : writer . text ( ( String ) child ) ; break ; case IGNORABLE_WHITESPACE : writer . ignorableWhitespace ( ( String ) child ) ; break ; case CDSECT : writer . cdsect ( ( String ) child ) ; break ; case COMMENT : writer . comment ( ( String ) child ) ; break ; case ENTITY_REF : writer . entityRef ( ( String ) child ) ; break ; case PROCESSING_INSTRUCTION : writer . processingInstruction ( ( String ) child ) ; break ; case DOCDECL : writer . docdecl ( ( String ) child ) ; break ; default : throw new RuntimeException ( "" + type ) ; } } } } package org . kxml2 . kdom ; import java . io . * ; import org . xmlpull . v1 . * ; public class Document extends Node { protected int rootIndex = - ; String encoding ; Boolean standalone ; public String getEncoding ( ) { return encoding ; } public void setEncoding ( String enc ) { this . encoding = enc ; } public void setStandalone ( Boolean standalone ) { this . standalone = standalone ; } public Boolean getStandalone ( ) { return standalone ; } public String getName ( ) { return "" ; } public void addChild ( int index , int type , Object child ) { if ( type == ELEMENT ) { if ( rootIndex != - ) throw new RuntimeException ( "" ) ; rootIndex = index ; } else if ( rootIndex >= index ) rootIndex ++ ; super . addChild ( index , type , child ) ; } public void parse ( XmlPullParser parser ) throws IOException , XmlPullParserException { parser . require ( XmlPullParser . START_DOCUMENT , null , null ) ; parser . nextToken ( ) ; encoding = parser . getInputEncoding ( ) ; standalone = ( Boolean ) parser . getProperty ( "" ) ; super . parse ( parser ) ; if ( parser . getEventType ( ) != XmlPullParser . END_DOCUMENT ) throw new RuntimeException ( "" ) ; } public void removeChild ( int index ) { if ( index == rootIndex ) rootIndex = - ; else if ( index < rootIndex ) rootIndex -- ; super . removeChild ( index ) ; } public Element getRootElement ( ) { if ( rootIndex == - ) throw new RuntimeException ( "" ) ; return ( Element ) getChild ( rootIndex ) ; } public void write ( XmlSerializer writer ) throws IOException { writer . startDocument ( encoding , standalone ) ; writeChildren ( writer ) ; writer . endDocument ( ) ; } } package org . kxml2 . kdom ; import java . io . * ; import java . util . * ; import org . xmlpull . v1 . * ; public class Element extends Node { protected String namespace ; protected String name ; protected Vector attributes ; protected Node parent ; protected Vector prefixes ; public Element ( ) { } public void init ( ) { } public void clear ( ) { attributes = null ; children = new Vector ( ) ; } public Element createElement ( String namespace , String name ) { return ( this . parent == null ) ? super . createElement ( namespace , name ) : this . parent . createElement ( namespace , name ) ; } public int getAttributeCount ( ) { return attributes == null ? : attributes . size ( ) ; } public String getAttributeNamespace ( int index ) { return ( ( String [ ] ) attributes . elementAt ( index ) ) [ ] ; } public String getAttributeName ( int index ) { return ( ( String [ ] ) attributes . elementAt ( index ) ) [ ] ; } public String getAttributeValue ( int index ) { return ( ( String [ ] ) attributes . elementAt ( index ) ) [ ] ; } public String getAttributeValue ( String namespace , String name ) { for ( int i = ; i < getAttributeCount ( ) ; i ++ ) { if ( name . equals ( getAttributeName ( i ) ) && ( namespace == null || namespace . equals ( getAttributeNamespace ( i ) ) ) ) { return getAttributeValue ( i ) ; } } return null ; } public Node getRoot ( ) { Element current = this ; while ( current . parent != null ) { if ( ! ( current . parent instanceof Element ) ) return current . parent ; current = ( Element ) current . parent ; } return current ; } public String getName ( ) { return name ; } public String getNamespace ( ) { return namespace ; } public String getNamespaceUri ( String prefix ) { int cnt = getNamespaceCount ( ) ; for ( int i = ; i < cnt ; i ++ ) { if ( prefix == getNamespacePrefix ( i ) || ( prefix != null && prefix . equals ( getNamespacePrefix ( i ) ) ) ) return getNamespaceUri ( i ) ; } return parent instanceof Element ? ( ( Element ) parent ) . getNamespaceUri ( prefix ) : null ; } public int getNamespaceCount ( ) { return ( prefixes == null ? : prefixes . size ( ) ) ; } public String getNamespacePrefix ( int i ) { return ( ( String [ ] ) prefixes . elementAt ( i ) ) [ ] ; } public String getNamespaceUri ( int i ) { return ( ( String [ ] ) prefixes . elementAt ( i ) ) [ ] ; } public Node getParent ( ) { return parent ; } public void parse ( XmlPullParser parser ) throws IOException , XmlPullParserException { for ( int i = parser . getNamespaceCount ( parser . getDepth ( ) - ) ; i < parser . getNamespaceCount ( parser . getDepth ( ) ) ; i ++ ) { setPrefix ( parser . getNamespacePrefix ( i ) , parser . getNamespaceUri ( i ) ) ; } for ( int i = ; i < parser . getAttributeCount ( ) ; i ++ ) setAttribute ( parser . getAttributeNamespace ( i ) , parser . getAttributeName ( i ) , parser . getAttributeValue ( i ) ) ; init ( ) ; if ( parser . isEmptyElementTag ( ) ) parser . nextToken ( ) ; else { parser . nextToken ( ) ; super . parse ( parser ) ; if ( getChildCount ( ) == ) addChild ( IGNORABLE_WHITESPACE , "" ) ; } parser . require ( XmlPullParser . END_TAG , getNamespace ( ) , getName ( ) ) ; parser . nextToken ( ) ; } public void setAttribute ( String namespace , String name , String value ) { if ( attributes == null ) attributes = new Vector ( ) ; if ( namespace == null ) namespace = "" ; for ( int i = attributes . size ( ) - ; i >= ; i -- ) { String [ ] attribut = ( String [ ] ) attributes . elementAt ( i ) ; if ( attribut [ ] . equals ( namespace ) && attribut [ ] . equals ( name ) ) { if ( value == null ) { attributes . removeElementAt ( i ) ; } else { attribut [ ] = value ; } return ; } } attributes . addElement ( new String [ ] { namespace , name , value } ) ; } public void setPrefix ( String prefix , String namespace ) { if ( prefixes == null ) prefixes = new Vector ( ) ; prefixes . addElement ( new String [ ] { prefix , namespace } ) ; } public void setName ( String name ) { this . name = name ; } public void setNamespace ( String namespace ) { if ( namespace == null ) throw new NullPointerException ( "" ) ; this . namespace = namespace ; } protected void setParent ( Node parent ) { this . parent = parent ; } public void write ( XmlSerializer writer ) throws IOException { if ( prefixes != null ) { for ( int i = ; i < prefixes . size ( ) ; i ++ ) { writer . setPrefix ( getNamespacePrefix ( i ) , getNamespaceUri ( i ) ) ; } } writer . startTag ( getNamespace ( ) , getName ( ) ) ; int len = getAttributeCount ( ) ; for ( int i = ; i < len ; i ++ ) { writer . attribute ( getAttributeNamespace ( i ) , getAttributeName ( i ) , getAttributeValue ( i ) ) ; } writeChildren ( writer ) ; writer . endTag ( getNamespace ( ) , getName ( ) ) ; } } package org . kxml2 . wap ; import java . io . * ; import java . util . * ; import org . xmlpull . v1 . * ; public class WbxmlSerializer implements XmlSerializer { Hashtable stringTable = new Hashtable ( ) ; OutputStream out ; ByteArrayOutputStream buf = new ByteArrayOutputStream ( ) ; ByteArrayOutputStream stringTableBuf = new ByteArrayOutputStream ( ) ; String pending ; int depth ; String name ; String namespace ; Vector attributes = new Vector ( ) ; Hashtable attrStartTable = new Hashtable ( ) ; Hashtable attrValueTable = new Hashtable ( ) ; Hashtable tagTable = new Hashtable ( ) ; public XmlSerializer attribute ( String namespace , String name , String value ) { attributes . addElement ( name ) ; attributes . addElement ( value ) ; return this ; } public void cdsect ( String cdsect ) throws IOException { text ( cdsect ) ; } public void comment ( String comment ) { } public void docdecl ( String docdecl ) { throw new RuntimeException ( "" ) ; } public void entityRef ( String er ) { throw new RuntimeException ( "" ) ; } public int getDepth ( ) { return depth ; } public boolean getFeature ( String name ) { return false ; } public String getNamespace ( ) { throw new RuntimeException ( "" ) ; } public String getName ( ) { throw new RuntimeException ( "" ) ; } public String getPrefix ( String nsp , boolean create ) { throw new RuntimeException ( "" ) ; } public Object getProperty ( String name ) { return null ; } public void ignorableWhitespace ( String sp ) { } public void endDocument ( ) throws IOException { writeInt ( out , stringTableBuf . size ( ) ) ; out . write ( stringTableBuf . toByteArray ( ) ) ; out . write ( buf . toByteArray ( ) ) ; out . flush ( ) ; } public void flush ( ) { } public void checkPending ( boolean degenerated ) throws IOException { if ( pending == null ) return ; int len = attributes . size ( ) ; Integer idx = ( Integer ) tagTable . get ( pending ) ; if ( idx == null ) { buf . write ( len == ? ( degenerated ? Wbxml . LITERAL : Wbxml . LITERAL_C ) : ( degenerated ? Wbxml . LITERAL_A : Wbxml . LITERAL_AC ) ) ; writeStrT ( pending ) ; } else { buf . write ( len == ? ( degenerated ? idx . intValue ( ) : idx . intValue ( ) | ) : ( degenerated ? idx . intValue ( ) | : idx . intValue ( ) | ) ) ; } for ( int i = ; i < len ; ) { idx = ( Integer ) attrStartTable . get ( attributes . elementAt ( i ) ) ; if ( idx == null ) { buf . write ( Wbxml . LITERAL ) ; writeStrT ( ( String ) attributes . elementAt ( i ) ) ; } else { buf . write ( idx . intValue ( ) ) ; } idx = ( Integer ) attrValueTable . get ( attributes . elementAt ( ++ i ) ) ; if ( idx == null ) { buf . write ( Wbxml . STR_I ) ; writeStrI ( buf , ( String ) attributes . elementAt ( i ) ) ; } else { buf . write ( idx . intValue ( ) ) ; } ++ i ; } if ( len > ) buf . write ( Wbxml . END ) ; pending = null ; attributes . removeAllElements ( ) ; } public void processingInstruction ( String pi ) { throw new RuntimeException ( "" ) ; } public void setFeature ( String name , boolean value ) { throw new IllegalArgumentException ( "" + name ) ; } public void setOutput ( Writer writer ) { throw new RuntimeException ( "" ) ; } public void setOutput ( OutputStream out , String encoding ) throws IOException { if ( encoding != null ) throw new IllegalArgumentException ( "" ) ; this . out = out ; buf = new ByteArrayOutputStream ( ) ; stringTableBuf = new ByteArrayOutputStream ( ) ; } public void setPrefix ( String prefix , String nsp ) { throw new RuntimeException ( "" ) ; } public void setProperty ( String property , Object value ) { throw new IllegalArgumentException ( "" + property ) ; } public void startDocument ( String s , Boolean b ) throws IOException { out . write ( ) ; out . write ( ) ; out . write ( ) ; } public XmlSerializer startTag ( String namespace , String name ) throws IOException { if ( namespace != null && ! "" . equals ( namespace ) ) throw new RuntimeException ( "" ) ; checkPending ( false ) ; pending = name ; depth ++ ; return this ; } public XmlSerializer text ( char [ ] chars , int start , int len ) throws IOException { checkPending ( false ) ; buf . write ( Wbxml . STR_I ) ; writeStrI ( buf , new String ( chars , start , len ) ) ; return this ; } public XmlSerializer text ( String text ) throws IOException { checkPending ( false ) ; buf . write ( Wbxml . STR_I ) ; writeStrI ( buf , text ) ; return this ; } public XmlSerializer endTag ( String namespace , String name ) throws IOException { if ( pending != null ) checkPending ( true ) ; else buf . write ( Wbxml . END ) ; depth -- ; return this ; } public void writeLegacy ( int type , String data ) { } static void writeInt ( OutputStream out , int i ) throws IOException { byte [ ] buf = new byte [ ] ; int idx = ; do { buf [ idx ++ ] = ( byte ) ( i & ) ; i = i > > ; } while ( i != ) ; while ( idx > ) { out . write ( buf [ -- idx ] | ) ; } out . write ( buf [ ] ) ; } static void writeStrI ( OutputStream out , String s ) throws IOException { for ( int i = ; i < s . length ( ) ; i ++ ) { out . write ( ( byte ) s . charAt ( i ) ) ; } out . write ( ) ; } void writeStrT ( String s ) throws IOException { Integer idx = ( Integer ) stringTable . get ( s ) ; if ( idx == null ) { idx = new Integer ( stringTableBuf . size ( ) ) ; stringTable . put ( s , idx ) ; writeStrI ( stringTableBuf , s ) ; stringTableBuf . flush ( ) ; } writeInt ( buf , idx . intValue ( ) ) ; } public void setTagTable ( int page , String [ ] tagTable ) { for ( int i = ; i < tagTable . length ; i ++ ) { if ( tagTable [ i ] != null ) { Integer idx = new Integer ( i + ) ; this . tagTable . put ( tagTable [ i ] , idx ) ; } } if ( page != ) throw new RuntimeException ( "" ) ; } public void setAttrStartTable ( int page , String [ ] attrStartTable ) { for ( int i = ; i < attrStartTable . length ; i ++ ) { if ( attrStartTable [ i ] != null ) { Integer idx = new Integer ( i + ) ; this . attrStartTable . put ( attrStartTable [ i ] , idx ) ; } } if ( page != ) throw new RuntimeException ( "" ) ; } public void setAttrValueTable ( int page , String [ ] attrValueTable ) { for ( int i = ; i < attrValueTable . length ; i ++ ) { if ( attrValueTable [ i ] != null ) { Integer idx = new Integer ( i + ) ; this . attrValueTable . put ( attrValueTable [ i ] , idx ) ; } } if ( page != ) throw new RuntimeException ( "" ) ; } } package org . kxml2 . wap ; public interface Wbxml { static public final int SWITCH_PAGE = ; static public final int END = ; static public final int ENTITY = ; static public final int STR_I = ; static public final int LITERAL = ; static public final int EXT_I_0 = ; static public final int EXT_I_1 = ; static public final int EXT_I_2 = ; static public final int PI = ; static public final int LITERAL_C = ; static public final int EXT_T_0 = ; static public final int EXT_T_1 = ; static public final int EXT_T_2 = ; static public final int STR_T = ; static public final int LITERAL_A = ; static public final int EXT_0 = ; static public final int EXT_1 = ; static public final int EXT_2 = ; static public final int OPAQUE = ; static public final int LITERAL_AC = ; } package org . kxml2 . wap ; import java . io . * ; import org . xmlpull . v1 . * ; public class WbxmlParser implements XmlPullParser { public static final int WAP_EXTENSION = ; static final private String UNEXPECTED_EOF = "" ; static final private String ILLEGAL_TYPE = "" ; private InputStream in ; private String [ ] attrStartTable ; private String [ ] attrValueTable ; private String [ ] tagTable ; private String stringTable ; private boolean processNsp ; private int depth ; private String [ ] elementStack = new String [ ] ; private String [ ] nspStack = new String [ ] ; private int [ ] nspCounts = new int [ ] ; private int attributeCount ; private String [ ] attributes = new String [ ] ; private int nextId = - ; int version ; int publicIdentifierId ; int charSet ; private String prefix ; private String namespace ; private String name ; private String text ; private Object wapExtensionData ; private int wapExtensionCode ; private int type ; private boolean degenerated ; private boolean isWhitespace ; public boolean getFeature ( String feature ) { if ( XmlPullParser . FEATURE_PROCESS_NAMESPACES . equals ( feature ) ) return processNsp ; else return false ; } public String getInputEncoding ( ) { return null ; } public void defineEntityReplacementText ( String entity , String value ) throws XmlPullParserException { } public Object getProperty ( String property ) { return null ; } public int getNamespaceCount ( int depth ) { if ( depth > this . depth ) throw new IndexOutOfBoundsException ( ) ; return nspCounts [ depth ] ; } public String getNamespacePrefix ( int pos ) { return nspStack [ pos << ] ; } public String getNamespaceUri ( int pos ) { return nspStack [ ( pos << ) + ] ; } public String getNamespace ( String prefix ) { if ( "" . equals ( prefix ) ) return "" ; if ( "" . equals ( prefix ) ) return "" ; for ( int i = ( getNamespaceCount ( depth ) << ) - ; i >= ; i -= ) { if ( prefix == null ) { if ( nspStack [ i ] == null ) return nspStack [ i + ] ; } else if ( prefix . equals ( nspStack [ i ] ) ) return nspStack [ i + ] ; } return null ; } public int getDepth ( ) { return depth ; } public String getPositionDescription ( ) { StringBuffer buf = new StringBuffer ( type < TYPES . length ? TYPES [ type ] : "" ) ; buf . append ( '' ) ; if ( type == START_TAG || type == END_TAG ) { if ( degenerated ) buf . append ( "" ) ; buf . append ( '' ) ; if ( type == END_TAG ) buf . append ( '' ) ; if ( prefix != null ) buf . append ( "" + namespace + "" + prefix + "" ) ; buf . append ( name ) ; int cnt = attributeCount << ; for ( int i = ; i < cnt ; i += ) { buf . append ( '' ) ; if ( attributes [ i + ] != null ) buf . append ( "" + attributes [ i ] + "" + attributes [ i + ] + "" ) ; buf . append ( attributes [ i + ] + "" + attributes [ i + ] + "" ) ; } buf . append ( '>' ) ; } else if ( type == IGNORABLE_WHITESPACE ) ; else if ( type != TEXT ) buf . append ( getText ( ) ) ; else if ( isWhitespace ) buf . append ( "" ) ; else { String text = getText ( ) ; if ( text . length ( ) > ) text = text . substring ( , ) + "" ; buf . append ( text ) ; } return buf . toString ( ) ; } public int getLineNumber ( ) { return - ; } public int getColumnNumber ( ) { return - ; } public boolean isWhitespace ( ) throws XmlPullParserException { if ( type != TEXT && type != IGNORABLE_WHITESPACE && type != CDSECT ) exception ( ILLEGAL_TYPE ) ; return isWhitespace ; } public String getText ( ) { return text ; } public char [ ] getTextCharacters ( int [ ] poslen ) { if ( type >= TEXT ) { poslen [ ] = ; poslen [ ] = text . length ( ) ; char [ ] buf = new char [ text . length ( ) ] ; text . getChars ( , text . length ( ) , buf , ) ; return buf ; } poslen [ ] = - ; poslen [ ] = - ; return null ; } public String getNamespace ( ) { return namespace ; } public String getName ( ) { return name ; } public String getPrefix ( ) { return prefix ; } public boolean isEmptyElementTag ( ) throws XmlPullParserException { if ( type != START_TAG ) exception ( ILLEGAL_TYPE ) ; return degenerated ; } public int getAttributeCount ( ) { return attributeCount ; } public String getAttributeType ( int index ) { return "" ; } public boolean isAttributeDefault ( int index ) { return false ; } public String getAttributeNamespace ( int index ) { if ( index >= attributeCount ) throw new IndexOutOfBoundsException ( ) ; return attributes [ index << ] ; } public String getAttributeName ( int index ) { if ( index >= attributeCount ) throw new IndexOutOfBoundsException ( ) ; return attributes [ ( index << ) + ] ; } public String getAttributePrefix ( int index ) { if ( index >= attributeCount ) throw new IndexOutOfBoundsException ( ) ; return attributes [ ( index << ) + ] ; } public String getAttributeValue ( int index ) { if ( index >= attributeCount ) throw new IndexOutOfBoundsException ( ) ; return attributes [ ( index << ) + ] ; } public String getAttributeValue ( String namespace , String name ) { for ( int i = ( attributeCount << ) - ; i >= ; i -= ) { if ( attributes [ i + ] . equals ( name ) && ( namespace == null || attributes [ i ] . equals ( namespace ) ) ) return attributes [ i + ] ; } return null ; } public int getEventType ( ) throws XmlPullParserException { return type ; } public int next ( ) throws XmlPullParserException , IOException { isWhitespace = true ; int minType = ; while ( true ) { String save = text ; nextImpl ( ) ; if ( type < minType ) minType = type ; if ( minType > CDSECT ) continue ; if ( minType >= TEXT ) { if ( save != null ) text = text != null ? save : save + text ; switch ( peekId ( ) ) { case Wbxml . ENTITY : case Wbxml . STR_I : case Wbxml . LITERAL : case Wbxml . LITERAL_C : case Wbxml . LITERAL_A : case Wbxml . LITERAL_AC : continue ; } } break ; } type = minType ; if ( type > TEXT ) type = TEXT ; return type ; } public int nextToken ( ) throws XmlPullParserException , IOException { isWhitespace = true ; nextImpl ( ) ; return type ; } public int nextTag ( ) throws XmlPullParserException , IOException { next ( ) ; if ( type == TEXT && isWhitespace ) next ( ) ; if ( type != END_TAG && type != START_TAG ) exception ( "" ) ; return type ; } public String nextText ( ) throws XmlPullParserException , IOException { if ( type != START_TAG ) exception ( "" ) ; next ( ) ; String result ; if ( type == TEXT ) { result = getText ( ) ; next ( ) ; } else result = "" ; if ( type != END_TAG ) exception ( "" ) ; return result ; } public void require ( int type , String namespace , String name ) throws XmlPullParserException , IOException { if ( type != this . type || ( namespace != null && ! namespace . equals ( getNamespace ( ) ) ) || ( name != null && ! name . equals ( getName ( ) ) ) ) exception ( "" + TYPES [ type ] + "" + namespace + "" + name ) ; } public void setInput ( Reader reader ) throws XmlPullParserException { exception ( "" ) ; } public void setInput ( InputStream in , String enc ) throws XmlPullParserException { this . in = in ; try { version = readByte ( ) ; publicIdentifierId = readInt ( ) ; if ( publicIdentifierId == ) readInt ( ) ; charSet = readInt ( ) ; int strTabSize = readInt ( ) ; StringBuffer buf = new StringBuffer ( strTabSize ) ; for ( int i = ; i < strTabSize ; i ++ ) buf . append ( ( char ) readByte ( ) ) ; stringTable = buf . toString ( ) ; } catch ( IOException e ) { exception ( "" ) ; } } public void setFeature ( String feature , boolean value ) throws XmlPullParserException { if ( XmlPullParser . FEATURE_PROCESS_NAMESPACES . equals ( feature ) ) processNsp = value ; else exception ( "" + feature ) ; } public void setProperty ( String property , Object value ) throws XmlPullParserException { throw new XmlPullParserException ( "" + property ) ; } private final boolean adjustNsp ( ) throws XmlPullParserException { boolean any = false ; for ( int i = ; i < attributeCount << ; i += ) { String attrName = attributes [ i + ] ; int cut = attrName . indexOf ( '' ) ; String prefix ; if ( cut != - ) { prefix = attrName . substring ( , cut ) ; attrName = attrName . substring ( cut + ) ; } else if ( attrName . equals ( "" ) ) { prefix = attrName ; attrName = null ; } else continue ; if ( ! prefix . equals ( "" ) ) { any = true ; } else { int j = ( nspCounts [ depth ] ++ ) << ; nspStack = ensureCapacity ( nspStack , j + ) ; nspStack [ j ] = attrName ; nspStack [ j + ] = attributes [ i + ] ; if ( attrName != null && attributes [ i + ] . equals ( "" ) ) exception ( "" ) ; System . arraycopy ( attributes , i + , attributes , i , ( ( -- attributeCount ) << ) - i ) ; i -= ; } } if ( any ) { for ( int i = ( attributeCount << ) - ; i >= ; i -= ) { String attrName = attributes [ i + ] ; int cut = attrName . indexOf ( '' ) ; if ( cut == ) throw new RuntimeException ( "" + attrName + "" + this ) ; else if ( cut != - ) { String attrPrefix = attrName . substring ( , cut ) ; attrName = attrName . substring ( cut + ) ; String attrNs = getNamespace ( attrPrefix ) ; if ( attrNs == null ) throw new RuntimeException ( "" + attrPrefix + "" + this ) ; attributes [ i ] = attrNs ; attributes [ i + ] = attrPrefix ; attributes [ i + ] = attrName ; for ( int j = ( attributeCount << ) - ; j > i ; j -= ) if ( attrName . equals ( attributes [ j + ] ) && attrNs . equals ( attributes [ j ] ) ) exception ( "" + attrNs + "" + attrName ) ; } } } int cut = name . indexOf ( '' ) ; if ( cut == ) exception ( "" + name ) ; else if ( cut != - ) { prefix = name . substring ( , cut ) ; name = name . substring ( cut + ) ; } this . namespace = getNamespace ( prefix ) ; if ( this . namespace == null ) { if ( prefix != null ) exception ( "" + prefix ) ; this . namespace = NO_NAMESPACE ; } return any ; } private final void exception ( String desc ) throws XmlPullParserException { throw new XmlPullParserException ( desc , this , null ) ; } private final void nextImpl ( ) throws IOException , XmlPullParserException { String s ; if ( type == END_TAG ) { depth -- ; } if ( degenerated ) { type = XmlPullParser . END_TAG ; return ; } text = null ; prefix = null ; name = null ; int id = peekId ( ) ; nextId = - ; switch ( id ) { case - : type = XmlPullParser . END_DOCUMENT ; break ; case Wbxml . SWITCH_PAGE : if ( readByte ( ) != ) throw new IOException ( "" ) ; break ; case Wbxml . END : { int sp = ( depth - ) << ; type = END_TAG ; namespace = elementStack [ sp ] ; prefix = elementStack [ sp + ] ; name = elementStack [ sp + ] ; } break ; case Wbxml . ENTITY : { type = ENTITY_REF ; char c = ( char ) readInt ( ) ; text = "" + c ; name = "" + ( ( int ) c ) ; } break ; case Wbxml . STR_I : type = TEXT ; text = readStrI ( ) ; break ; case Wbxml . EXT_I_0 : case Wbxml . EXT_I_1 : case Wbxml . EXT_I_2 : case Wbxml . EXT_T_0 : case Wbxml . EXT_T_1 : case Wbxml . EXT_T_2 : case Wbxml . EXT_0 : case Wbxml . EXT_1 : case Wbxml . EXT_2 : case Wbxml . OPAQUE : parseWapExtension ( id ) ; break ; case Wbxml . PI : throw new RuntimeException ( "" ) ; case Wbxml . STR_T : { type = TEXT ; int pos = readInt ( ) ; int end = stringTable . indexOf ( '' , pos ) ; text = stringTable . substring ( pos , end ) ; } break ; default : parseElement ( id ) ; } } public void parseWapExtension ( int id ) throws IOException , XmlPullParserException { type = WAP_EXTENSION ; wapExtensionCode = id ; switch ( id ) { case Wbxml . EXT_I_0 : case Wbxml . EXT_I_1 : case Wbxml . EXT_I_2 : wapExtensionData = readStrI ( ) ; break ; case Wbxml . EXT_T_0 : case Wbxml . EXT_T_1 : case Wbxml . EXT_T_2 : wapExtensionData = new Integer ( readInt ( ) ) ; break ; case Wbxml . EXT_0 : case Wbxml . EXT_1 : case Wbxml . EXT_2 : break ; case Wbxml . OPAQUE : { int len = readInt ( ) ; byte [ ] buf = new byte [ len ] ; for ( int i = ; i < len ; i ++ ) buf [ i ] = ( byte ) readByte ( ) ; wapExtensionData = buf ; } } throw new IOException ( "" ) ; } public void readAttr ( ) throws IOException { int id = readByte ( ) ; int i = ; while ( id != ) { String name = resolveId ( attrStartTable , id ) ; StringBuffer value ; int cut = name . indexOf ( '' ) ; if ( cut == - ) value = new StringBuffer ( ) ; else { value = new StringBuffer ( name . substring ( cut + ) ) ; name = name . substring ( , cut ) ; } id = readByte ( ) ; while ( id > || id == Wbxml . ENTITY || id == Wbxml . STR_I || id == Wbxml . STR_T || ( id >= Wbxml . EXT_I_0 && id <= Wbxml . EXT_I_2 ) || ( id >= Wbxml . EXT_T_0 && id <= Wbxml . EXT_T_2 ) ) { switch ( id ) { case Wbxml . ENTITY : value . append ( ( char ) readInt ( ) ) ; break ; case Wbxml . STR_I : value . append ( readStrI ( ) ) ; break ; case Wbxml . EXT_I_0 : case Wbxml . EXT_I_1 : case Wbxml . EXT_I_2 : case Wbxml . EXT_T_0 : case Wbxml . EXT_T_1 : case Wbxml . EXT_T_2 : case Wbxml . EXT_0 : case Wbxml . EXT_1 : case Wbxml . EXT_2 : case Wbxml . OPAQUE : throw new RuntimeException ( "" ) ; case Wbxml . STR_T : value . append ( readStrT ( ) ) ; break ; default : value . append ( resolveId ( attrValueTable , id ) ) ; } id = readByte ( ) ; } attributes = ensureCapacity ( attributes , i + ) ; attributes [ i ++ ] = "" ; attributes [ i ++ ] = null ; attributes [ i ++ ] = name ; attributes [ i ++ ] = value . toString ( ) ; } } private int peekId ( ) throws IOException { if ( nextId == - ) { nextId = in . read ( ) ; } return nextId ; } String resolveId ( String [ ] tab , int id ) throws IOException { int idx = ( id & ) - ; if ( idx == - ) return readStrT ( ) ; if ( idx < || tab == null || idx >= tab . length || tab [ idx ] == null ) throw new IOException ( "" + id + "" ) ; return tab [ idx ] ; } void parseElement ( int id ) throws IOException , XmlPullParserException { name = resolveId ( tagTable , id & ) ; if ( ( id & ) != ) { readAttr ( ) ; } degenerated = ( id & ) == ; int sp = depth ++ << ; elementStack = ensureCapacity ( elementStack , sp + ) ; elementStack [ sp + ] = name ; for ( int i = attributeCount - ; i > ; i -- ) { for ( int j = ; j < i ; j ++ ) { if ( getAttributeName ( i ) . equals ( getAttributeName ( j ) ) ) exception ( "" + getAttributeName ( i ) ) ; } } if ( processNsp ) adjustNsp ( ) ; else namespace = "" ; elementStack [ sp ] = namespace ; elementStack [ sp + ] = prefix ; elementStack [ sp + ] = name ; } private final String [ ] ensureCapacity ( String [ ] arr , int required ) { if ( arr . length >= required ) return arr ; String [ ] bigger = new String [ required + ] ; System . arraycopy ( arr , , bigger , , arr . length ) ; return bigger ; } int readByte ( ) throws IOException { int i = in . read ( ) ; if ( i == - ) throw new IOException ( "" ) ; return i ; } int readInt ( ) throws IOException { int result = ; int i ; do { i = readByte ( ) ; result = ( result << ) | ( i & ) ; } while ( ( i & ) != ) ; return result ; } String readStrI ( ) throws IOException { StringBuffer buf = new StringBuffer ( ) ; boolean wsp = true ; while ( true ) { int i = in . read ( ) ; if ( i == - ) throw new IOException ( "" ) ; if ( i == ) break ; if ( i > ) wsp = false ; buf . append ( ( char ) i ) ; } isWhitespace = wsp ; return buf . toString ( ) ; } String readStrT ( ) throws IOException { int pos = readInt ( ) ; int end = stringTable . indexOf ( '' , pos ) ; return stringTable . substring ( pos , end ) ; } public void setTagTable ( int page , String [ ] tagTable ) { this . tagTable = tagTable ; if ( page != ) throw new RuntimeException ( "" ) ; } public void setAttrStartTable ( int page , String [ ] attrStartTable ) { this . attrStartTable = attrStartTable ; if ( page != ) throw new RuntimeException ( "" ) ; } public void setAttrValueTable ( int page , String [ ] attrStartTable ) { this . attrValueTable = attrStartTable ; if ( page != ) throw new RuntimeException ( "" ) ; } } package org . kxml2 . io ; import java . io . * ; import java . util . * ; import org . xmlpull . v1 . * ; public class KXmlParser implements XmlPullParser { static final private String UNEXPECTED_EOF = "" ; static final private String ILLEGAL_TYPE = "" ; static final private int LEGACY = ; static final private int XML_DECL = ; private String version ; private Boolean standalone ; private boolean processNsp ; private boolean relaxed ; private Hashtable entityMap ; private int depth ; private String [ ] elementStack = new String [ ] ; private String [ ] nspStack = new String [ ] ; private int [ ] nspCounts = new int [ ] ; private Reader reader ; private String encoding ; private char [ ] srcBuf ; private int srcPos ; private int srcCount ; private int line ; private int column ; private char [ ] txtBuf = new char [ ] ; private int txtPos ; private int type ; private boolean isWhitespace ; private String namespace ; private String prefix ; private String name ; private boolean degenerated ; private int attributeCount ; private String [ ] attributes = new String [ ] ; private int [ ] peek = new int [ ] ; private int peekCount ; private boolean wasCR ; private boolean unresolved ; private boolean token ; public KXmlParser ( ) { srcBuf = new char [ Runtime . getRuntime ( ) . freeMemory ( ) >= ? : ] ; } private final boolean isProp ( String n1 , boolean prop , String n2 ) { if ( ! n1 . startsWith ( "" ) ) return false ; if ( prop ) return n1 . substring ( ) . equals ( n2 ) ; else return n1 . substring ( ) . equals ( n2 ) ; } private final boolean adjustNsp ( ) throws XmlPullParserException { boolean any = false ; for ( int i = ; i < attributeCount << ; i += ) { String attrName = attributes [ i + ] ; int cut = attrName . indexOf ( '' ) ; String prefix ; if ( cut != - ) { prefix = attrName . substring ( , cut ) ; attrName = attrName . substring ( cut + ) ; } else if ( attrName . equals ( "" ) ) { prefix = attrName ; attrName = null ; } else continue ; if ( ! prefix . equals ( "" ) ) { any = true ; } else { int j = ( nspCounts [ depth ] ++ ) << ; nspStack = ensureCapacity ( nspStack , j + ) ; nspStack [ j ] = attrName ; nspStack [ j + ] = attributes [ i + ] ; if ( attrName != null && attributes [ i + ] . equals ( "" ) ) exception ( "" ) ; System . arraycopy ( attributes , i + , attributes , i , ( ( -- attributeCount ) << ) - i ) ; i -= ; } } if ( any ) { for ( int i = ( attributeCount << ) - ; i >= ; i -= ) { String attrName = attributes [ i + ] ; int cut = attrName . indexOf ( '' ) ; if ( cut == && ! relaxed ) throw new RuntimeException ( "" + attrName + "" + this ) ; else if ( cut != - ) { String attrPrefix = attrName . substring ( , cut ) ; attrName = attrName . substring ( cut + ) ; String attrNs = getNamespace ( attrPrefix ) ; if ( attrNs == null && ! relaxed ) throw new RuntimeException ( "" + attrPrefix + "" + this ) ; attributes [ i ] = attrNs ; attributes [ i + ] = attrPrefix ; attributes [ i + ] = attrName ; if ( ! relaxed ) { for ( int j = ( attributeCount << ) - ; j > i ; j -= ) if ( attrName . equals ( attributes [ j + ] ) && attrNs . equals ( attributes [ j ] ) ) exception ( "" + attrNs + "" + attrName ) ; } } } } int cut = name . indexOf ( '' ) ; if ( cut == && ! relaxed ) exception ( "" + name ) ; else if ( cut != - ) { prefix = name . substring ( , cut ) ; name = name . substring ( cut + ) ; } this . namespace = getNamespace ( prefix ) ; if ( this . namespace == null ) { if ( prefix != null && ! relaxed ) exception ( "" + prefix ) ; this . namespace = NO_NAMESPACE ; } return any ; } private final String [ ] ensureCapacity ( String [ ] arr , int required ) { if ( arr . length >= required ) return arr ; String [ ] bigger = new String [ required + ] ; System . arraycopy ( arr , , bigger , , arr . length ) ; return bigger ; } private final void exception ( String desc ) throws XmlPullParserException { throw new XmlPullParserException ( desc , this , null ) ; } private final void nextImpl ( ) throws IOException , XmlPullParserException { if ( reader == null ) exception ( "" ) ; if ( type == END_TAG ) depth -- ; while ( true ) { attributeCount = - ; if ( degenerated ) { degenerated = false ; type = END_TAG ; return ; } prefix = null ; name = null ; namespace = null ; type = peekType ( ) ; switch ( type ) { case ENTITY_REF : pushEntity ( ) ; return ; case START_TAG : parseStartTag ( false ) ; return ; case END_TAG : parseEndTag ( ) ; return ; case END_DOCUMENT : return ; case TEXT : pushText ( '' , ! token ) ; if ( depth == ) { if ( isWhitespace ) type = IGNORABLE_WHITESPACE ; } return ; default : type = parseLegacy ( token ) ; if ( type != XML_DECL ) return ; } } } private final int parseLegacy ( boolean push ) throws IOException , XmlPullParserException { String req = "" ; int term ; int result ; int prev = ; read ( ) ; int c = read ( ) ; if ( c == '' ) { if ( ( peek ( ) == '' || peek ( ) == '' ) && ( peek ( ) == '' || peek ( ) == '' ) ) { if ( push ) { push ( peek ( ) ) ; push ( peek ( ) ) ; } read ( ) ; read ( ) ; if ( ( peek ( ) == '' || peek ( ) == '' ) && peek ( ) <= '' ) { if ( line != || column > ) exception ( "" ) ; parseStartTag ( true ) ; if ( attributeCount < || ! "" . equals ( attributes [ ] ) ) exception ( "" ) ; version = attributes [ ] ; int pos = ; if ( pos < attributeCount && "" . equals ( attributes [ + ] ) ) { encoding = attributes [ + ] ; pos ++ ; } if ( pos < attributeCount && "" . equals ( attributes [ * pos + ] ) ) { String st = attributes [ + * pos ] ; if ( "" . equals ( st ) ) standalone = new Boolean ( true ) ; else if ( "" . equals ( st ) ) standalone = new Boolean ( false ) ; else exception ( "" + st ) ; pos ++ ; } if ( pos != attributeCount ) exception ( "" ) ; isWhitespace = true ; txtPos = ; return XML_DECL ; } } term = '' ; result = PROCESSING_INSTRUCTION ; } else if ( c == '' ) { if ( peek ( ) == '' ) { result = COMMENT ; req = "" ; term = '' ; } else if ( peek ( ) == '' ) { result = CDSECT ; req = "" ; term = '' ; push = true ; } else { result = DOCDECL ; req = "" ; term = - ; } } else { exception ( "" + c ) ; return - ; } for ( int i = ; i < req . length ( ) ; i ++ ) read ( req . charAt ( i ) ) ; if ( result == DOCDECL ) parseDoctype ( push ) ; else { while ( true ) { c = read ( ) ; if ( c == - ) exception ( UNEXPECTED_EOF ) ; if ( push ) push ( c ) ; if ( ( term == '' || c == term ) && peek ( ) == term && peek ( ) == '>' ) break ; prev = c ; } if ( term == '' && prev == '' && ! relaxed ) throw new XmlPullParserException ( "" ) ; read ( ) ; read ( ) ; if ( push && term != '' ) txtPos -- ; } return result ; } private final void parseDoctype ( boolean push ) throws IOException , XmlPullParserException { int nesting = ; boolean quoted = false ; while ( true ) { int i = read ( ) ; switch ( i ) { case - : exception ( UNEXPECTED_EOF ) ; case '' : quoted = ! quoted ; break ; case '' : if ( ! quoted ) nesting ++ ; break ; case '>' : if ( ! quoted ) { if ( ( -- nesting ) == ) return ; } break ; } if ( push ) push ( i ) ; } } private final void parseEndTag ( ) throws IOException , XmlPullParserException { read ( ) ; read ( ) ; name = readName ( ) ; skip ( ) ; read ( '>' ) ; int sp = ( depth - ) << ; if ( ! relaxed ) { if ( depth == ) exception ( "" ) ; if ( ! name . equals ( elementStack [ sp + ] ) ) exception ( "" + elementStack [ sp + ] ) ; } else if ( depth == || ! name . toLowerCase ( ) . equals ( elementStack [ sp + ] . toLowerCase ( ) ) ) return ; namespace = elementStack [ sp ] ; prefix = elementStack [ sp + ] ; name = elementStack [ sp + ] ; } private final int peekType ( ) throws IOException { switch ( peek ( ) ) { case - : return END_DOCUMENT ; case '' : return ENTITY_REF ; case '' : switch ( peek ( ) ) { case '' : return END_TAG ; case '' : case '' : return LEGACY ; default : return START_TAG ; } default : return TEXT ; } } private final String get ( int pos ) { return new String ( txtBuf , pos , txtPos - pos ) ; } private final void push ( int c ) { isWhitespace &= c <= '' ; if ( txtPos == txtBuf . length ) { char [ ] bigger = new char [ txtPos * / + ] ; System . arraycopy ( txtBuf , , bigger , , txtPos ) ; txtBuf = bigger ; } txtBuf [ txtPos ++ ] = ( char ) c ; } private final void parseStartTag ( boolean xmldecl ) throws IOException , XmlPullParserException { if ( ! xmldecl ) read ( ) ; name = readName ( ) ; attributeCount = ; while ( true ) { skip ( ) ; int c = peek ( ) ; if ( xmldecl ) { if ( c == '' ) { read ( ) ; read ( '>' ) ; return ; } } else { if ( c == '' ) { degenerated = true ; read ( ) ; skip ( ) ; read ( '>' ) ; break ; } if ( c == '>' && ! xmldecl ) { read ( ) ; break ; } } if ( c == - ) exception ( UNEXPECTED_EOF ) ; String attrName = readName ( ) ; if ( attrName . length ( ) == ) exception ( "" ) ; skip ( ) ; read ( '' ) ; skip ( ) ; int delimiter = read ( ) ; if ( delimiter != '' && delimiter != '' ) { if ( ! relaxed ) exception ( "" + name + "" + ( char ) delimiter ) ; delimiter = '' ; } int i = ( attributeCount ++ ) << ; attributes = ensureCapacity ( attributes , i + ) ; attributes [ i ++ ] = "" ; attributes [ i ++ ] = null ; attributes [ i ++ ] = attrName ; int p = txtPos ; pushText ( delimiter , true ) ; attributes [ i ] = get ( p ) ; txtPos = p ; if ( delimiter != '' ) read ( ) ; } int sp = depth ++ << ; elementStack = ensureCapacity ( elementStack , sp + ) ; elementStack [ sp + ] = name ; if ( depth >= nspCounts . length ) { int [ ] bigger = new int [ depth + ] ; System . arraycopy ( nspCounts , , bigger , , nspCounts . length ) ; nspCounts = bigger ; } nspCounts [ depth ] = nspCounts [ depth - ] ; for ( int i = attributeCount - ; i > ; i -- ) { for ( int j = ; j < i ; j ++ ) { if ( getAttributeName ( i ) . equals ( getAttributeName ( j ) ) ) exception ( "" + getAttributeName ( i ) ) ; } } if ( processNsp ) adjustNsp ( ) ; else namespace = "" ; elementStack [ sp ] = namespace ; elementStack [ sp + ] = prefix ; elementStack [ sp + ] = name ; } private final void pushEntity ( ) throws IOException , XmlPullParserException { read ( ) ; int pos = txtPos ; while ( true ) { int c = read ( ) ; if ( c == '' ) break ; if ( relaxed && ( c == '' || c == '' || c <= '' ) ) { if ( c != - ) push ( c ) ; return ; } if ( c == - ) exception ( UNEXPECTED_EOF ) ; push ( c ) ; } String code = get ( pos ) ; txtPos = pos ; if ( token && type == ENTITY_REF ) name = code ; if ( code . charAt ( ) == '' ) { int c = ( code . charAt ( ) == '' ? Integer . parseInt ( code . substring ( ) , ) : Integer . parseInt ( code . substring ( ) ) ) ; push ( c ) ; return ; } String result = ( String ) entityMap . get ( code ) ; unresolved = result == null ; if ( unresolved ) { if ( ! token ) exception ( "" + code + "" ) ; } else { for ( int i = ; i < result . length ( ) ; i ++ ) push ( result . charAt ( i ) ) ; } } private final void pushText ( int delimiter , boolean resolveEntities ) throws IOException , XmlPullParserException { int next = peek ( ) ; while ( next != - && next != delimiter ) { if ( delimiter == '' ) if ( next <= '' || next == '>' ) break ; if ( next == '' ) { if ( ! resolveEntities ) break ; pushEntity ( ) ; } else if ( next == '' && type == START_TAG ) { read ( ) ; push ( '' ) ; } else push ( read ( ) ) ; next = peek ( ) ; } } private final void read ( char c ) throws IOException , XmlPullParserException { int a = read ( ) ; if ( a != c ) exception ( "" + c + "" + ( ( char ) a ) + "" ) ; } private final int read ( ) throws IOException { int result ; if ( peekCount == ) result = peek ( ) ; else { result = peek [ ] ; peek [ ] = peek [ ] ; } peekCount -- ; column ++ ; if ( result == '' ) { line ++ ; column = ; } return result ; } private final int peek ( int pos ) throws IOException { while ( pos >= peekCount ) { int nw ; if ( srcBuf . length <= ) nw = reader . read ( ) ; else if ( srcPos < srcCount ) nw = srcBuf [ srcPos ++ ] ; else { srcCount = reader . read ( srcBuf , , srcBuf . length ) ; if ( srcCount <= ) nw = - ; else nw = srcBuf [ ] ; srcPos = ; } if ( nw == '' ) { wasCR = true ; peek [ peekCount ++ ] = '' ; } else { if ( nw == '' ) { if ( ! wasCR ) peek [ peekCount ++ ] = '' ; } else peek [ peekCount ++ ] = nw ; wasCR = false ; } } return peek [ pos ] ; } private final String readName ( ) throws IOException , XmlPullParserException { int pos = txtPos ; int c = peek ( ) ; if ( ( c < '' || c > '' ) && ( c < '' || c > '' ) && c != '' && c != '' && c < ) exception ( "" ) ; do { push ( read ( ) ) ; c = peek ( ) ; } while ( ( c >= '' && c <= '' ) || ( c >= '' && c <= '' ) || ( c >= '' && c <= '' ) || c == '' || c == '' || c == '' || c == '' || c >= ) ; String result = get ( pos ) ; txtPos = pos ; return result ; } private final void skip ( ) throws IOException { while ( true ) { int c = peek ( ) ; if ( c > '' || c == - ) break ; read ( ) ; } } public void setInput ( Reader reader ) throws XmlPullParserException { this . reader = reader ; line = ; column = ; type = START_DOCUMENT ; name = null ; namespace = null ; degenerated = false ; attributeCount = - ; encoding = null ; version = null ; standalone = null ; if ( reader == null ) return ; srcPos = ; srcCount = ; peekCount = ; depth = ; entityMap = new Hashtable ( ) ; entityMap . put ( "" , "" ) ; entityMap . put ( "" , "" ) ; entityMap . put ( "" , ">" ) ; entityMap . put ( "" , "" ) ; entityMap . put ( "" , "" ) ; } public void setInput ( InputStream is , String _enc ) throws XmlPullParserException { srcPos = ; srcCount = ; String enc = _enc ; if ( is == null ) throw new IllegalArgumentException ( ) ; try { if ( enc == null ) { int chk = ; while ( srcCount < ) { int i = is . read ( ) ; if ( i == - ) break ; chk = ( chk << ) | i ; srcBuf [ srcCount ++ ] = ( char ) i ; } if ( srcCount == ) { switch ( chk ) { case : enc = "" ; srcCount = ; break ; case : enc = "" ; srcCount = ; break ; case : enc = "" ; srcBuf [ ] = '' ; srcCount = ; break ; case : enc = "" ; srcBuf [ ] = '' ; srcCount = ; break ; case : enc = "" ; srcBuf [ ] = '' ; srcBuf [ ] = '' ; srcCount = ; break ; case : enc = "" ; srcBuf [ ] = '' ; srcBuf [ ] = '' ; srcCount = ; break ; case : while ( true ) { int i = is . read ( ) ; if ( i == - ) break ; srcBuf [ srcCount ++ ] = ( char ) i ; if ( i == '>' ) { String s = new String ( srcBuf , , srcCount ) ; int i0 = s . indexOf ( "" ) ; if ( i0 != - ) { while ( s . charAt ( i0 ) != '' && s . charAt ( i0 ) != '' ) i0 ++ ; char deli = s . charAt ( i0 ++ ) ; int i1 = s . indexOf ( deli , i0 ) ; enc = s . substring ( i0 , i1 ) ; } break ; } } default : if ( ( chk & ) == ) { enc = "" ; srcBuf [ ] = ( char ) ( ( srcBuf [ ] << ) | srcBuf [ ] ) ; srcCount = ; } else if ( ( chk & ) == ) { enc = "" ; srcBuf [ ] = ( char ) ( ( srcBuf [ ] << ) | srcBuf [ ] ) ; srcCount = ; } else if ( ( chk & ) == ) { enc = "" ; srcBuf [ ] = srcBuf [ ] ; srcCount = ; } } } } if ( enc == null ) enc = "" ; int sc = srcCount ; setInput ( new InputStreamReader ( is , enc ) ) ; encoding = _enc ; srcCount = sc ; } catch ( Exception e ) { throw new XmlPullParserException ( "" + e . toString ( ) , this , e ) ; } } public boolean getFeature ( String feature ) { if ( XmlPullParser . FEATURE_PROCESS_NAMESPACES . equals ( feature ) ) return processNsp ; else if ( isProp ( feature , false , "" ) ) return relaxed ; else return false ; } public String getInputEncoding ( ) { return encoding ; } public void defineEntityReplacementText ( String entity , String value ) throws XmlPullParserException { if ( entityMap == null ) throw new RuntimeException ( "" ) ; entityMap . put ( entity , value ) ; } public Object getProperty ( String property ) { if ( isProp ( property , true , "" ) ) return version ; if ( isProp ( property , true , "" ) ) return standalone ; return null ; } public int getNamespaceCount ( int depth ) { if ( depth > this . depth ) throw new IndexOutOfBoundsException ( ) ; return nspCounts [ depth ] ; } public String getNamespacePrefix ( int pos ) { return nspStack [ pos << ] ; } public String getNamespaceUri ( int pos ) { return nspStack [ ( pos << ) + ] ; } public String getNamespace ( String prefix ) { if ( "" . equals ( prefix ) ) return "" ; if ( "" . equals ( prefix ) ) return "" ; for ( int i = ( getNamespaceCount ( depth ) << ) - ; i >= ; i -= ) { if ( prefix == null ) { if ( nspStack [ i ] == null ) return nspStack [ i + ] ; } else if ( prefix . equals ( nspStack [ i ] ) ) return nspStack [ i + ] ; } return null ; } public int getDepth ( ) { return depth ; } public String getPositionDescription ( ) { StringBuffer buf = new StringBuffer ( type < TYPES . length ? TYPES [ type ] : "" ) ; buf . append ( '' ) ; if ( type == START_TAG || type == END_TAG ) { if ( degenerated ) buf . append ( "" ) ; buf . append ( '' ) ; if ( type == END_TAG ) buf . append ( '' ) ; if ( prefix != null ) buf . append ( "" + namespace + "" + prefix + "" ) ; buf . append ( name ) ; int cnt = attributeCount << ; for ( int i = ; i < cnt ; i += ) { buf . append ( '' ) ; if ( attributes [ i + ] != null ) buf . append ( "" + attributes [ i ] + "" + attributes [ i + ] + "" ) ; buf . append ( attributes [ i + ] + "" + attributes [ i + ] + "" ) ; } buf . append ( '>' ) ; } else if ( type == IGNORABLE_WHITESPACE ) ; else if ( type != TEXT ) buf . append ( getText ( ) ) ; else if ( isWhitespace ) buf . append ( "" ) ; else { String text = getText ( ) ; if ( text . length ( ) > ) text = text . substring ( , ) + "" ; buf . append ( text ) ; } buf . append ( "" + line + "" + column ) ; return buf . toString ( ) ; } public int getLineNumber ( ) { return line ; } public int getColumnNumber ( ) { return column ; } public boolean isWhitespace ( ) throws XmlPullParserException { if ( type != TEXT && type != IGNORABLE_WHITESPACE && type != CDSECT ) exception ( ILLEGAL_TYPE ) ; return isWhitespace ; } public String getText ( ) { return type < TEXT || ( type == ENTITY_REF && unresolved ) ? null : get ( ) ; } public char [ ] getTextCharacters ( int [ ] poslen ) { if ( type >= TEXT ) { if ( type == ENTITY_REF ) { poslen [ ] = ; poslen [ ] = name . length ( ) ; return name . toCharArray ( ) ; } poslen [ ] = ; poslen [ ] = txtPos ; return txtBuf ; } poslen [ ] = - ; poslen [ ] = - ; return null ; } public String getNamespace ( ) { return namespace ; } public String getName ( ) { return name ; } public String getPrefix ( ) { return prefix ; } public boolean isEmptyElementTag ( ) throws XmlPullParserException { if ( type != START_TAG ) exception ( ILLEGAL_TYPE ) ; return degenerated ; } public int getAttributeCount ( ) { return attributeCount ; } public String getAttributeType ( int index ) { return "" ; } public boolean isAttributeDefault ( int index ) { return false ; } public String getAttributeNamespace ( int index ) { if ( index >= attributeCount ) throw new IndexOutOfBoundsException ( ) ; return attributes [ index << ] ; } public String getAttributeName ( int index ) { if ( index >= attributeCount ) throw new IndexOutOfBoundsException ( ) ; return attributes [ ( index << ) + ] ; } public String getAttributePrefix ( int index ) { if ( index >= attributeCount ) throw new IndexOutOfBoundsException ( ) ; return attributes [ ( index << ) + ] ; } public String getAttributeValue ( int index ) { if ( index >= attributeCount ) throw new IndexOutOfBoundsException ( ) ; return attributes [ ( index << ) + ] ; } public String getAttributeValue ( String namespace , String name ) { for ( int i = ( attributeCount << ) - ; i >= ; i -= ) { if ( attributes [ i + ] . equals ( name ) && ( namespace == null || attributes [ i ] . equals ( namespace ) ) ) return attributes [ i + ] ; } return null ; } public int getEventType ( ) throws XmlPullParserException { return type ; } public int next ( ) throws XmlPullParserException , IOException { txtPos = ; isWhitespace = true ; int minType = ; token = false ; do { nextImpl ( ) ; if ( type < minType ) minType = type ; } while ( minType > CDSECT || ( minType >= TEXT && peekType ( ) >= TEXT ) ) ; type = minType ; if ( type > TEXT ) type = TEXT ; return type ; } public int nextToken ( ) throws XmlPullParserException , IOException { isWhitespace = true ; txtPos = ; token = true ; nextImpl ( ) ; return type ; } public int nextTag ( ) throws XmlPullParserException , IOException { next ( ) ; if ( type == TEXT && isWhitespace ) next ( ) ; if ( type != END_TAG && type != START_TAG ) exception ( "" ) ; return type ; } public void require ( int type , String namespace , String name ) throws XmlPullParserException , IOException { if ( type != this . type || ( namespace != null && ! namespace . equals ( getNamespace ( ) ) ) || ( name != null && ! name . equals ( getName ( ) ) ) ) exception ( "" + TYPES [ type ] + "" + namespace + "" + name ) ; } public String nextText ( ) throws XmlPullParserException , IOException { if ( type != START_TAG ) exception ( "" ) ; next ( ) ; String result ; if ( type == TEXT ) { result = getText ( ) ; next ( ) ; } else result = "" ; if ( type != END_TAG ) exception ( "" ) ; return result ; } public void setFeature ( String feature , boolean value ) throws XmlPullParserException { if ( XmlPullParser . FEATURE_PROCESS_NAMESPACES . equals ( feature ) ) processNsp = value ; else if ( isProp ( feature , false , "" ) ) relaxed = value ; else exception ( "" + feature ) ; } public void setProperty ( String property , Object value ) throws XmlPullParserException { throw new XmlPullParserException ( "" + property ) ; } } package org . kxml2 . io ; import java . io . * ; import org . xmlpull . v1 . * ; public class KXmlSerializer implements XmlSerializer { private Writer writer ; private boolean pending ; private int auto ; private int depth ; private String [ ] elementStack = new String [ ] ; private int [ ] nspCounts = new int [ ] ; private String [ ] nspStack = new String [ ] ; private boolean [ ] indent = new boolean [ ] ; private boolean unicode ; private String encoding ; private final void check ( boolean close ) throws IOException { if ( ! pending ) return ; depth ++ ; pending = false ; if ( indent . length <= depth ) { boolean [ ] hlp = new boolean [ depth + ] ; System . arraycopy ( indent , , hlp , , depth ) ; indent = hlp ; } indent [ depth ] = indent [ depth - ] ; for ( int i = nspCounts [ depth - ] ; i < nspCounts [ depth ] ; i ++ ) { writer . write ( '' ) ; writer . write ( "" ) ; if ( ! "" . equals ( nspStack [ i * ] ) ) { writer . write ( '' ) ; writer . write ( nspStack [ i * ] ) ; } else if ( getNamespace ( ) . equals ( "" ) ) throw new IllegalStateException ( "" ) ; writer . write ( "" ) ; writeEscaped ( nspStack [ i * + ] , '' ) ; writer . write ( '' ) ; } if ( nspCounts . length <= depth + ) { int [ ] hlp = new int [ depth + ] ; System . arraycopy ( nspCounts , , hlp , , depth + ) ; nspCounts = hlp ; } nspCounts [ depth + ] = nspCounts [ depth ] ; writer . write ( close ? "" : ">" ) ; } private final void writeEscaped ( String s , int quot ) throws IOException { for ( int i = ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; switch ( c ) { case '' : writer . write ( "" ) ; break ; case '>' : writer . write ( "" ) ; break ; case '' : writer . write ( "" ) ; break ; case '' : case '' : if ( c == quot ) { writer . write ( c == '' ? "" : "" ) ; break ; } default : if ( c < || unicode ) writer . write ( c ) ; else writer . write ( "" + ( ( int ) c ) + "" ) ; } } } public void docdecl ( String dd ) throws IOException { writer . write ( "" ) ; writer . write ( dd ) ; writer . write ( ">" ) ; } public void endDocument ( ) throws IOException { while ( depth > ) { endTag ( elementStack [ depth * - ] , elementStack [ depth * - ] ) ; } flush ( ) ; } public void entityRef ( String name ) throws IOException { check ( false ) ; writer . write ( '' ) ; writer . write ( name ) ; writer . write ( '' ) ; } public boolean getFeature ( String name ) { return ( "" . equals ( name ) ) ? indent [ depth ] : false ; } public String getPrefix ( String namespace , boolean create ) { try { return getPrefix ( namespace , false , create ) ; } catch ( IOException e ) { throw new RuntimeException ( e . toString ( ) ) ; } } private final String getPrefix ( String namespace , boolean includeDefault , boolean create ) throws IOException { for ( int i = nspCounts [ depth + ] * - ; i >= ; i -= ) { if ( nspStack [ i + ] . equals ( namespace ) && ( includeDefault || ! nspStack [ i ] . equals ( "" ) ) ) { String cand = nspStack [ i ] ; for ( int j = i + ; j < nspCounts [ depth + ] * ; j ++ ) { if ( nspStack [ j ] . equals ( cand ) ) { cand = null ; break ; } } if ( cand != null ) return cand ; } } if ( ! create ) return null ; String prefix ; if ( "" . equals ( namespace ) ) prefix = "" ; else { do { prefix = "" + ( auto ++ ) ; for ( int i = nspCounts [ depth + ] * - ; i >= ; i -= ) { if ( prefix . equals ( nspStack [ i ] ) ) { prefix = null ; break ; } } } while ( prefix == null ) ; } boolean p = pending ; pending = false ; setPrefix ( prefix , namespace ) ; pending = p ; return prefix ; } public Object getProperty ( String name ) { throw new RuntimeException ( "" ) ; } public void ignorableWhitespace ( String s ) throws IOException { text ( s ) ; } public void setFeature ( String name , boolean value ) { if ( "" . equals ( name ) ) { indent [ depth ] = value ; } else throw new RuntimeException ( "" ) ; } public void setProperty ( String name , Object value ) { throw new RuntimeException ( "" + value ) ; } public void setPrefix ( String prefix , String namespace ) throws IOException { check ( false ) ; if ( prefix == null ) prefix = "" ; if ( namespace == null ) namespace = "" ; String defined = getPrefix ( namespace , true , false ) ; if ( prefix . equals ( defined ) ) return ; int pos = ( nspCounts [ depth + ] ++ ) << ; if ( nspStack . length < pos + ) { String [ ] hlp = new String [ nspStack . length + ] ; System . arraycopy ( nspStack , , hlp , , pos ) ; nspStack = hlp ; } nspStack [ pos ++ ] = prefix ; nspStack [ pos ] = namespace ; } public void setOutput ( Writer writer ) { this . writer = writer ; nspCounts [ ] = ; nspCounts [ ] = ; nspStack [ ] = "" ; nspStack [ ] = "" ; nspStack [ ] = "" ; nspStack [ ] = "" ; pending = false ; auto = ; depth = ; unicode = false ; } public void setOutput ( OutputStream os , String encoding ) throws IOException { if ( os == null ) throw new IllegalArgumentException ( ) ; setOutput ( encoding == null ? new OutputStreamWriter ( os ) : new OutputStreamWriter ( os , encoding ) ) ; this . encoding = encoding ; if ( encoding != null && encoding . toLowerCase ( ) . startsWith ( "" ) ) unicode = true ; } public void startDocument ( String encoding , Boolean standalone ) throws IOException { writer . write ( "" ) ; if ( encoding != null ) { this . encoding = encoding ; if ( encoding . toLowerCase ( ) . startsWith ( "" ) ) unicode = true ; } if ( this . encoding != null ) { writer . write ( "" ) ; writer . write ( this . encoding ) ; writer . write ( "" ) ; } if ( standalone != null ) { writer . write ( "" ) ; writer . write ( standalone . booleanValue ( ) ? "" : "" ) ; writer . write ( "" ) ; } writer . write ( "" ) ; } public XmlSerializer startTag ( String namespace , String name ) throws IOException { check ( false ) ; if ( indent [ depth ] ) { writer . write ( "" ) ; for ( int i = ; i < depth ; i ++ ) writer . write ( '' ) ; } int esp = depth * ; if ( elementStack . length < esp + ) { String [ ] hlp = new String [ elementStack . length + ] ; System . arraycopy ( elementStack , , hlp , , esp ) ; elementStack = hlp ; } String prefix = namespace == null ? "" : getPrefix ( namespace , true , true ) ; if ( "" . equals ( namespace ) ) { for ( int i = nspCounts [ depth ] ; i < nspCounts [ depth + ] ; i ++ ) { if ( "" . equals ( nspStack [ i * ] ) ) { throw new IllegalStateException ( "" ) ; } } } elementStack [ esp ++ ] = namespace ; elementStack [ esp ++ ] = prefix ; elementStack [ esp ] = name ; writer . write ( '' ) ; if ( ! "" . equals ( prefix ) ) { writer . write ( prefix ) ; writer . write ( '' ) ; } writer . write ( name ) ; pending = true ; return this ; } public XmlSerializer attribute ( String namespace , String name , String value ) throws IOException { if ( ! pending ) throw new IllegalStateException ( "" ) ; if ( namespace == null ) namespace = "" ; String prefix = "" . equals ( namespace ) ? "" : getPrefix ( namespace , false , true ) ; writer . write ( '' ) ; if ( ! "" . equals ( prefix ) ) { writer . write ( prefix ) ; writer . write ( '' ) ; } writer . write ( name ) ; writer . write ( '' ) ; char q = value . indexOf ( '' ) == - ? '' : '' ; writer . write ( q ) ; writeEscaped ( value , q ) ; writer . write ( q ) ; return this ; } public void flush ( ) throws IOException { check ( false ) ; writer . flush ( ) ; } public XmlSerializer endTag ( String namespace , String name ) throws IOException { if ( ! pending ) depth -- ; if ( ( namespace == null && elementStack [ depth * ] != null ) || ( namespace != null && ! namespace . equals ( elementStack [ depth * ] ) ) || ! elementStack [ depth * + ] . equals ( name ) ) throw new IllegalArgumentException ( "" ) ; if ( pending ) { check ( true ) ; depth -- ; } else { if ( indent [ depth + ] ) { writer . write ( "" ) ; for ( int i = ; i < depth ; i ++ ) writer . write ( '' ) ; } writer . write ( "" ) ; String prefix = elementStack [ depth * + ] ; if ( ! "" . equals ( prefix ) ) { writer . write ( prefix ) ; writer . write ( '' ) ; } writer . write ( name ) ; writer . write ( '>' ) ; } nspCounts [ depth + ] = nspCounts [ depth ] ; return this ; } public String getNamespace ( ) { return getDepth ( ) == ? null : elementStack [ getDepth ( ) * - ] ; } public String getName ( ) { return getDepth ( ) == ? null : elementStack [ getDepth ( ) * - ] ; } public int getDepth ( ) { return pending ? depth + : depth ; } public XmlSerializer text ( String text ) throws IOException { check ( false ) ; indent [ depth ] = false ; writeEscaped ( text , - ) ; return this ; } public XmlSerializer text ( char [ ] text , int start , int len ) throws IOException { text ( new String ( text , start , len ) ) ; return this ; } public void cdsect ( String data ) throws IOException { check ( false ) ; writer . write ( "" ) ; writer . write ( data ) ; writer . write ( "" ) ; } public void comment ( String comment ) throws IOException { check ( false ) ; writer . write ( "" ) ; writer . write ( comment ) ; writer . write ( "" ) ; } public void processingInstruction ( String pi ) throws IOException { check ( false ) ; writer . write ( "" ) ; writer . write ( pi ) ; writer . write ( "" ) ; } } import java . io . * ; import java . util . Vector ; import org . kxml2 . io . * ; import org . xmlpull . v1 . * ; import javax . microedition . midlet . * ; import javax . microedition . lcdui . * ; import javax . microedition . io . * ; public class Newsreader extends MIDlet implements CommandListener { static final String URL = "" ; static final String TITLE = "" ; Vector descriptions = new Vector ( ) ; List newsList = new List ( TITLE , Choice . IMPLICIT ) ; TextBox textBox = new TextBox ( "" , "" , , TextField . ANY ) ; Display display ; Command backCmd = new Command ( "" , Command . BACK , ) ; class ReadThread extends Thread { public void run ( ) { try { HttpConnection httpConnection = ( HttpConnection ) Connector . open ( URL ) ; KXmlParser parser = new KXmlParser ( ) ; parser . setInput ( new InputStreamReader ( httpConnection . openInputStream ( ) ) ) ; parser . nextTag ( ) ; parser . require ( parser . START_TAG , null , "" ) ; while ( parser . nextTag ( ) != parser . END_TAG ) readStory ( parser ) ; parser . require ( parser . END_TAG , null , "" ) ; parser . next ( ) ; parser . require ( parser . END_DOCUMENT , null , null ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; descriptions . addElement ( e . toString ( ) ) ; newsList . append ( "" , null ) ; } } void readStory ( KXmlParser parser ) throws IOException , XmlPullParserException { parser . require ( parser . START_TAG , null , "" ) ; String title = null ; String description = null ; while ( parser . nextTag ( ) != parser . END_TAG ) { parser . require ( parser . START_TAG , null , null ) ; String name = parser . getName ( ) ; String text = parser . nextText ( ) ; System . out . println ( "" + name + ">" + text ) ; if ( name . equals ( "" ) ) title = text ; else if ( name . equals ( "" ) ) description = text ; parser . require ( parser . END_TAG , null , name ) ; } parser . require ( parser . END_TAG , null , "" ) ; if ( title != null ) { descriptions . addElement ( "" + description ) ; newsList . append ( title , null ) ; } } } public void startApp ( ) { display = Display . getDisplay ( this ) ; display . setCurrent ( newsList ) ; newsList . setCommandListener ( this ) ; textBox . setCommandListener ( this ) ; textBox . addCommand ( backCmd ) ; new ReadThread ( ) . start ( ) ; } public void pauseApp ( ) { } public void commandAction ( Command c , Displayable d ) { if ( c == List . SELECT_COMMAND ) { String text = ( String ) descriptions . elementAt ( newsList . getSelectedIndex ( ) ) ; if ( textBox . getMaxSize ( ) < text . length ( ) ) textBox . setMaxSize ( text . length ( ) ) ; textBox . setString ( text ) ; display . setCurrent ( textBox ) ; } else if ( c == backCmd ) display . setCurrent ( newsList ) ; } public void destroyApp ( boolean really ) { } } import java . io . * ; import org . xmlpull . v1 . * ; import org . kxml2 . kdom . * ; import org . kxml2 . io . * ; public class KDomRoundtrip { public static void main ( String [ ] args ) throws IOException , XmlPullParserException { if ( args . length == ) throw new RuntimeException ( "" ) ; for ( int i = ; i < args . length ; i ++ ) { System . out . println ( "" + args [ i ] ) ; KXmlParser parser = new KXmlParser ( ) ; parser . setInput ( new FileReader ( args [ i ] ) ) ; parser . setFeature ( XmlPullParser . FEATURE_PROCESS_NAMESPACES , true ) ; Document doc = new Document ( ) ; doc . parse ( parser ) ; KXmlSerializer serializer = new KXmlSerializer ( ) ; serializer . setOutput ( System . out , null ) ; doc . write ( serializer ) ; serializer . flush ( ) ; } } } import java . io . * ; import org . kxml2 . io . * ; import org . xmlpull . v1 . * ; public class EventList { public static void main ( String [ ] args ) throws IOException , XmlPullParserException { for ( int i = ; i < ; i ++ ) { XmlPullParser xr = new KXmlParser ( ) ; xr . setInput ( new FileReader ( args [ ] ) ) ; System . out . println ( "" ) ; System . out . println ( "" + ( i == ? "" : "" ) + "" ) ; System . out . println ( "" ) ; do { if ( i == ) xr . nextToken ( ) ; else xr . next ( ) ; System . out . println ( xr . getPositionDescription ( ) ) ; } while ( xr . getEventType ( ) != XmlPullParser . END_DOCUMENT ) ; } } } import java . io . * ; import org . kxml2 . io . * ; import org . xmlpull . v1 . * ; public class Roundtrip { XmlPullParser parser ; XmlSerializer serializer ; public Roundtrip ( XmlPullParser parser , XmlSerializer serializer ) { this . parser = parser ; this . serializer = serializer ; } public void writeStartTag ( ) throws XmlPullParserException , IOException { if ( ! parser . getFeature ( parser . FEATURE_REPORT_NAMESPACE_ATTRIBUTES ) ) { for ( int i = parser . getNamespaceCount ( parser . getDepth ( ) - ) ; i < parser . getNamespaceCount ( parser . getDepth ( ) ) - ; i ++ ) { serializer . setPrefix ( parser . getNamespacePrefix ( i ) , parser . getNamespaceUri ( i ) ) ; } } serializer . startTag ( parser . getNamespace ( ) , parser . getName ( ) ) ; for ( int i = ; i < parser . getAttributeCount ( ) ; i ++ ) { serializer . attribute ( parser . getAttributeNamespace ( i ) , parser . getAttributeName ( i ) , parser . getAttributeValue ( i ) ) ; } } public void writeToken ( ) throws XmlPullParserException , IOException { switch ( parser . getEventType ( ) ) { case XmlPullParser . START_DOCUMENT : break ; case XmlPullParser . END_DOCUMENT : serializer . endDocument ( ) ; break ; case XmlPullParser . START_TAG : writeStartTag ( ) ; break ; case XmlPullParser . END_TAG : serializer . endTag ( parser . getNamespace ( ) , parser . getName ( ) ) ; break ; case XmlPullParser . IGNORABLE_WHITESPACE : serializer . ignorableWhitespace ( parser . getText ( ) ) ; break ; case XmlPullParser . TEXT : serializer . text ( parser . getText ( ) ) ; break ; case XmlPullParser . ENTITY_REF : serializer . entityRef ( parser . getName ( ) ) ; break ; case XmlPullParser . CDSECT : serializer . cdsect ( parser . getText ( ) ) ; break ; case XmlPullParser . PROCESSING_INSTRUCTION : serializer . processingInstruction ( parser . getText ( ) ) ; break ; case XmlPullParser . COMMENT : serializer . comment ( parser . getText ( ) ) ; break ; case XmlPullParser . DOCDECL : serializer . docdecl ( parser . getText ( ) ) ; break ; default : throw new RuntimeException ( "" + parser . getEventType ( ) ) ; } } public void roundTrip ( ) throws XmlPullParserException , IOException { while ( parser . getEventType ( ) != parser . END_DOCUMENT ) { writeToken ( ) ; parser . nextToken ( ) ; } writeToken ( ) ; } public static void main ( String [ ] args ) throws Exception { if ( args . length == ) throw new RuntimeException ( "" ) ; for ( int i = ; i < args . length ; i ++ ) { System . out . println ( "" + args [ i ] ) ; XmlPullParser pp = new KXmlParser ( ) ; pp . setFeature ( XmlPullParser . FEATURE_PROCESS_NAMESPACES , true ) ; XmlSerializer serializer = new KXmlSerializer ( ) ; pp . setInput ( new FileReader ( args [ i ] ) ) ; serializer . setOutput ( System . out , null ) ; ( new Roundtrip ( pp , serializer ) ) . roundTrip ( ) ; serializer . flush ( ) ; } } } package org . kobjects . xmlrpc ; import java . util . * ; import java . io . * ; import org . xmlpull . v1 . * ; public class XmlRpcParser { XmlPullParser parser ; public XmlRpcParser ( XmlPullParser parser ) { this . parser = parser ; } public Vector parseResponse ( ) throws XmlPullParserException , IOException { Vector result = new Vector ( ) ; parser . nextTag ( ) ; parser . require ( parser . START_TAG , "" , "" ) ; parser . nextTag ( ) ; parser . require ( parser . START_TAG , "" , "" ) ; while ( parser . nextTag ( ) == parser . START_TAG ) { parser . require ( parser . START_TAG , "" , "" ) ; parser . nextTag ( ) ; result . addElement ( parseValue ( ) ) ; parser . nextTag ( ) ; parser . require ( parser . END_TAG , "" , "" ) ; } parser . require ( parser . END_TAG , "" , "" ) ; parser . nextTag ( ) ; parser . require ( parser . END_TAG , "" , "" ) ; parser . next ( ) ; parser . require ( parser . END_DOCUMENT , null , null ) ; return result ; } Object parseValue ( ) throws IOException , XmlPullParserException { parser . require ( parser . START_TAG , "" , "" ) ; parser . next ( ) ; Object result ; if ( parser . getEventType ( ) == parser . END_TAG ) result = "" ; else if ( parser . getEventType ( ) == parser . TEXT ) { result = parser . getText ( ) ; parser . nextTag ( ) ; } else { parser . require ( parser . START_TAG , "" , null ) ; String name = parser . getName ( ) ; if ( name . equals ( "" ) ) result = new Double ( parser . nextText ( ) ) ; else if ( name . equals ( "" ) || name . equals ( "" ) ) result = new Integer ( parser . nextText ( ) ) ; else if ( name . equals ( "" ) ) result = parseArray ( ) ; else if ( name . equals ( "" ) ) result = parser . nextText ( ) ; else if ( name . equals ( "" ) ) result = parseStruct ( ) ; else throw new RuntimeException ( "" + name ) ; parser . require ( parser . END_TAG , "" , name ) ; parser . nextTag ( ) ; } parser . require ( parser . END_TAG , "" , "" ) ; return result ; } Vector parseArray ( ) throws IOException , XmlPullParserException { Vector v = new Vector ( ) ; parser . require ( parser . START_TAG , "" , "" ) ; while ( parser . nextTag ( ) == parser . START_TAG ) v . addElement ( parseValue ( ) ) ; parser . require ( parser . END_TAG , "" , "" ) ; return v ; } Hashtable parseStruct ( ) throws IOException , XmlPullParserException { Hashtable struct = new Hashtable ( ) ; parser . require ( parser . START_TAG , "" , "" ) ; while ( parser . nextTag ( ) == parser . START_TAG ) { parser . require ( parser . START_TAG , "" , "" ) ; parser . nextTag ( ) ; parser . require ( parser . START_TAG , "" , "" ) ; String name = parser . nextText ( ) ; parser . require ( parser . END_TAG , "" , "" ) ; parser . nextTag ( ) ; struct . put ( name , parseValue ( ) ) ; parser . nextTag ( ) ; parser . require ( parser . END_TAG , "" , "" ) ; } parser . require ( parser . END_TAG , "" , "" ) ; return struct ; } public static void main ( String [ ] argv ) throws IOException , XmlPullParserException { String test = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; System . out . println ( "" + test ) ; XmlPullParser xp = new org . kxml2 . io . KXmlParser ( ) ; xp . setInput ( new java . io . StringReader ( test ) ) ; System . out . println ( "" + new XmlRpcParser ( xp ) . parseResponse ( ) ) ; } } import org . xmlpull . v1 . * ; import java . util . * ; import java . io . * ; import java . net . * ; public class Weblogs { static List listChannels ( ) throws IOException , XmlPullParserException { return listChannels ( "" ) ; } static List listChannels ( String uri ) throws IOException , XmlPullParserException { Vector result = new Vector ( ) ; InputStream is = new URL ( uri ) . openStream ( ) ; XmlPullParser parser = XmlPullParserFactory . newInstance ( ) . newPullParser ( ) ; parser . setInput ( is , null ) ; parser . nextTag ( ) ; parser . require ( parser . START_TAG , "" , "" ) ; while ( parser . nextTag ( ) == parser . START_TAG ) { String url = readSingle ( parser ) ; if ( url != null ) result . addElement ( url ) ; } parser . require ( parser . END_TAG , "" , "" ) ; parser . next ( ) ; parser . require ( parser . END_DOCUMENT , null , null ) ; is . close ( ) ; parser . setInput ( null ) ; return result ; } public static String readSingle ( XmlPullParser parser ) throws IOException , XmlPullParserException { String url = null ; parser . require ( parser . START_TAG , "" , "" ) ; while ( parser . nextTag ( ) == parser . START_TAG ) { String name = parser . getName ( ) ; String content = parser . nextText ( ) ; if ( name . equals ( "" ) ) url = content ; parser . require ( parser . END_TAG , "" , name ) ; } parser . require ( parser . END_TAG , "" , "" ) ; return url ; } public static void main ( String [ ] args ) throws IOException , XmlPullParserException { List urls = args . length > ? listChannels ( args [ ] ) : listChannels ( ) ; for ( Iterator i = urls . iterator ( ) ; i . hasNext ( ) ; ) System . out . println ( i . next ( ) ) ; } } import java . io . * ; import org . xmlpull . v1 . * ; import org . kxml2 . io . * ; class Node { private String text ; private Node yes ; private Node no ; Node ( String answer ) { this . text = answer ; } Node ( String question , Node yes , Node no ) { this . text = question ; this . yes = yes ; this . no = no ; } void run ( ) throws IOException { if ( yes == null ) System . out . println ( "" + text ) ; else { System . out . println ( text + "" ) ; while ( true ) { int i = System . in . read ( ) ; if ( i == '' || i == '' ) { yes . run ( ) ; break ; } else if ( i == '' || i == '' ) { no . run ( ) ; break ; } } } } } public class YesNoGame { public static Node parseAnswer ( XmlPullParser p ) throws IOException , XmlPullParserException { p . require ( p . START_TAG , "" , "" ) ; Node result = new Node ( p . nextText ( ) ) ; p . require ( p . END_TAG , "" , "" ) ; return result ; } public static Node parseQuestion ( XmlPullParser p ) throws IOException , XmlPullParserException { p . require ( p . START_TAG , "" , "" ) ; String text = p . getAttributeValue ( "" , "" ) ; Node yes = parseNode ( p ) ; Node no = parseNode ( p ) ; p . nextTag ( ) ; p . require ( p . END_TAG , "" , "" ) ; return new Node ( text , yes , no ) ; } public static Node parseNode ( XmlPullParser p ) throws IOException , XmlPullParserException { p . nextTag ( ) ; p . require ( p . START_TAG , "" , null ) ; if ( p . getName ( ) . equals ( "" ) ) return parseQuestion ( p ) ; else return parseAnswer ( p ) ; } public static void main ( String [ ] args ) throws IOException , XmlPullParserException { String sample = "" + "" + "" + "" + "" + "" + "" ; XmlPullParser p = new KXmlParser ( ) ; p . setInput ( new StringReader ( sample ) ) ; Node game = parseNode ( p ) ; game . run ( ) ; } } package org . rubypeople . rdt . internal . launching ; public class IllegalCommandException extends Exception { private static final long serialVersionUID = - ; public IllegalCommandException ( String arg0 ) { super ( arg0 ) ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . text . DateFormat ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . IProcess ; import org . osgi . framework . Version ; import org . rubypeople . rdt . launching . AbstractVMRunner ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . VMRunnerConfiguration ; public class StandardVMRunner extends AbstractVMRunner { private static final String SUDO_PROMPT = "" ; public static final String STREAM_FLUSH_SCRIPT = "" ; private static final String LOADPATH_SWITCH = "" ; protected static final String END_OF_OPTIONS_DELIMITER = "" ; protected boolean isVMArgs = true ; protected String renderDebugTarget ( String classToRun , int host ) { String format = LaunchingMessages . StandardVMRunner__0__at_localhost__1__1 ; return MessageFormat . format ( format , classToRun , String . valueOf ( host ) ) ; } public static String renderProcessLabel ( String [ ] commandLine ) { String format = LaunchingMessages . StandardVMRunner__0____1___2 ; String timestamp = DateFormat . getDateTimeInstance ( DateFormat . MEDIUM , DateFormat . MEDIUM ) . format ( new Date ( System . currentTimeMillis ( ) ) ) ; return MessageFormat . format ( format , commandLine [ ] , timestamp ) ; } protected static String renderCommandLine ( String [ ] commandLine ) { if ( commandLine == null || commandLine . length < ) return "" ; StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < commandLine . length ; i ++ ) { if ( commandLine [ i ] == null ) continue ; buf . append ( '' ) ; char [ ] characters = commandLine [ i ] . toCharArray ( ) ; StringBuffer command = new StringBuffer ( ) ; boolean containsSpace = false ; for ( int j = ; j < characters . length ; j ++ ) { char character = characters [ j ] ; if ( character == '' ) { command . append ( '' ) ; } else if ( character == '' ) { containsSpace = true ; } command . append ( character ) ; } if ( containsSpace ) { buf . append ( '' ) ; buf . append ( command . toString ( ) ) ; buf . append ( '' ) ; } else { buf . append ( command . toString ( ) ) ; } } return buf . toString ( ) ; } protected void addArguments ( String [ ] args , List < String > v ) { if ( args == null ) { return ; } for ( int i = ; i < args . length ; i ++ ) { v . add ( args [ i ] ) ; } } protected File getWorkingDir ( VMRunnerConfiguration config ) throws CoreException { String path = config . getWorkingDirectory ( ) ; if ( path == null ) { return null ; } File dir = new File ( path ) ; if ( ! dir . isDirectory ( ) ) { abort ( MessageFormat . format ( LaunchingMessages . StandardVMRunner_Specified_working_directory_does_not_exist_or_is_not_a_directory___0__3 , path ) , null , IRubyLaunchConfigurationConstants . ERR_WORKING_DIRECTORY_DOES_NOT_EXIST ) ; } return dir ; } protected String getPluginIdentifier ( ) { return LaunchingPlugin . getUniqueIdentifier ( ) ; } protected List < String > constructProgramString ( VMRunnerConfiguration config , IProgressMonitor monitor ) throws CoreException { List < String > string = new ArrayList < String > ( ) ; if ( ! Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) && config . isSudo ( ) ) { forceBackgroundSudoCommand ( config , monitor ) ; string . add ( "" ) ; } String command = getCommand ( config ) ; if ( command == null ) { File exe = fVMInstance . getVMInstallType ( ) . findExecutable ( fVMInstance . getInstallLocation ( ) ) ; if ( exe == null ) { abort ( MessageFormat . format ( LaunchingMessages . StandardVMRunner_Unable_to_locate_executable_for__0__1 , fVMInstance . getName ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR ) ; } string . add ( exe . getAbsolutePath ( ) ) ; return string ; } String installLocation = fVMInstance . getInstallLocation ( ) . getAbsolutePath ( ) + File . separatorChar ; File originalExe = new File ( installLocation + "" + File . separatorChar + command ) ; File exe = originalExe ; if ( fileExists ( exe ) ) { string . add ( exe . getAbsolutePath ( ) ) ; return string ; } exe = new File ( exe . getAbsolutePath ( ) + "" ) ; if ( fileExists ( exe ) ) { string . add ( exe . getAbsolutePath ( ) ) ; return string ; } String version = fVMInstance . getRubyVersion ( ) ; Version versionObj = new Version ( version ) ; exe = new File ( originalExe . getAbsolutePath ( ) + versionObj . getMajor ( ) + "" + versionObj . getMinor ( ) ) ; if ( fileExists ( exe ) ) { string . add ( exe . getAbsolutePath ( ) ) ; return string ; } exe = new File ( exe . getAbsolutePath ( ) + "" ) ; if ( fileExists ( exe ) ) { string . add ( exe . getAbsolutePath ( ) ) ; return string ; } abort ( MessageFormat . format ( LaunchingMessages . StandardVMRunner_Specified_executable__0__does_not_exist_for__1__4 , command , fVMInstance . getName ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR ) ; return null ; } protected void forceBackgroundSudoCommand ( VMRunnerConfiguration config , IProgressMonitor monitor ) throws CoreException { final Process p = exec ( new String [ ] { "" , "" , "" , SUDO_PROMPT , "" , "" } , null ) ; final InputStream errorStream = p . getErrorStream ( ) ; final String sudoMsg = config . getSudoMessage ( ) ; final boolean [ ] doneWaiting = new boolean [ ] ; doneWaiting [ ] = false ; final int [ ] exitValue = new int [ ] ; exitValue [ ] = ; Job processWaiter = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { try { exitValue [ ] = p . waitFor ( ) ; } catch ( InterruptedException e ) { LaunchingPlugin . log ( e ) ; } doneWaiting [ ] = true ; return Status . OK_STATUS ; } } ; processWaiter . setSystem ( true ) ; processWaiter . schedule ( ) ; Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { StringBuffer buffer = new StringBuffer ( ) ; String lineDelimeter = "" ; while ( true ) { try { int value = errorStream . read ( ) ; if ( value == - ) break ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; buffer . append ( ( char ) value ) ; if ( buffer . toString ( ) . contains ( SUDO_PROMPT ) ) { buffer . delete ( , buffer . length ( ) ) ; String pw = Sudo . getPassword ( sudoMsg ) ; p . getOutputStream ( ) . write ( ( pw + lineDelimeter ) . getBytes ( ) ) ; p . getOutputStream ( ) . flush ( ) ; } } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } } return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . schedule ( ) ; while ( true ) { if ( monitor != null && monitor . isCanceled ( ) ) return ; Thread . yield ( ) ; if ( doneWaiting [ ] ) break ; } if ( exitValue [ ] != ) { job . cancel ( ) ; IStatus status = new Status ( IStatus . ERROR , LaunchingPlugin . PLUGIN_ID , - , "" , null ) ; throw new CoreException ( status ) ; } } protected String getCommand ( VMRunnerConfiguration config ) { String command = null ; Map map = config . getVMSpecificAttributesMap ( ) ; if ( map != null ) { command = ( String ) map . get ( IRubyLaunchConfigurationConstants . ATTR_RUBY_COMMAND ) ; } return command ; } protected boolean fileExists ( File file ) { return file . exists ( ) && file . isFile ( ) ; } protected List < String > convertLoadPath ( VMRunnerConfiguration config , String [ ] lp ) { String working = null ; try { File workingDir = getWorkingDir ( config ) ; if ( workingDir != null ) working = workingDir . getAbsolutePath ( ) ; } catch ( CoreException e ) { } List < String > strings = new ArrayList < String > ( ) ; for ( int i = ; i < lp . length ; i ++ ) { String path = lp [ i ] ; if ( working != null && working . equals ( path ) ) continue ; strings . add ( LOADPATH_SWITCH ) ; strings . add ( path ) ; } return strings ; } public void run ( VMRunnerConfiguration config , ILaunch launch , IProgressMonitor monitor ) throws CoreException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } IProgressMonitor subMonitor = new SubProgressMonitor ( monitor , ) ; subMonitor . beginTask ( LaunchingMessages . StandardVMRunner_Launching_VM____1 , ) ; subMonitor . subTask ( LaunchingMessages . StandardVMRunner_Constructing_command_line____2 ) ; List < String > arguments = constructProgramString ( config , monitor ) ; String [ ] allVMArgs = combineVmArgs ( config , fVMInstance ) ; addArguments ( allVMArgs , arguments ) ; String [ ] lp = config . getLoadPath ( ) ; if ( lp . length > ) { arguments . addAll ( convertLoadPath ( config , lp ) ) ; } addStreamSync ( arguments ) ; arguments . add ( END_OF_OPTIONS_DELIMITER ) ; arguments . add ( getFileToLaunch ( config ) ) ; addArguments ( config . getProgramArguments ( ) , arguments ) ; String [ ] cmdLine = new String [ arguments . size ( ) ] ; arguments . toArray ( cmdLine ) ; String [ ] envp = getEnvironment ( config ) ; subMonitor . worked ( ) ; if ( monitor . isCanceled ( ) ) { return ; } subMonitor . subTask ( LaunchingMessages . StandardVMRunner_Starting_virtual_machine____3 ) ; Process p = null ; File workingDir = getWorkingDir ( config ) ; if ( envp != null && envp . length > ) { p = exec ( cmdLine , workingDir , envp ) ; } else { p = exec ( cmdLine , workingDir ) ; } if ( p == null ) { return ; } if ( monitor . isCanceled ( ) ) { p . destroy ( ) ; return ; } IProcess process = newProcess ( launch , p , renderProcessLabel ( cmdLine ) , getDefaultProcessMap ( ) ) ; process . setAttribute ( IProcess . ATTR_CMDLINE , renderCommandLine ( cmdLine ) ) ; process . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , launch . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME ) ) ; process . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_REQUIRES_REFRESH , launch . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_REQUIRES_REFRESH ) ) ; subMonitor . worked ( ) ; subMonitor . done ( ) ; } protected String getFileToLaunch ( VMRunnerConfiguration config ) { String file = config . getFileToLaunch ( ) ; if ( fVMInstance . getPlatform ( ) . equals ( IVMInstall . CYWGIN_PLATFORM ) ) { file = file . replace ( '' , '' ) ; } return file ; } protected String [ ] getEnvironment ( VMRunnerConfiguration config ) { String [ ] envp = config . getEnvironment ( ) ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) { return envp ; } List < String > newEnv = new ArrayList < String > ( ) ; Map < String , String > environment = System . getenv ( ) ; for ( String key : environment . keySet ( ) ) { String value = environment . get ( key ) ; if ( key . equalsIgnoreCase ( "" ) ) { File exe = fVMInstance . getVMInstallType ( ) . findExecutable ( fVMInstance . getInstallLocation ( ) ) ; value = exe . getParent ( ) + "" + value ; } newEnv . add ( key + "" + value ) ; } int length = ( envp == null ) ? : envp . length ; for ( int i = ; i < length ; i ++ ) { newEnv . add ( envp [ i ] ) ; } return newEnv . toArray ( new String [ newEnv . size ( ) ] ) ; } protected void addStreamSync ( List < String > arguments ) { File sync = LaunchingPlugin . getFileInPlugin ( new Path ( "" ) . append ( "" ) . append ( STREAM_FLUSH_SCRIPT ) ) ; arguments . add ( LOADPATH_SWITCH ) ; arguments . add ( sync . getParent ( ) ) ; arguments . add ( "" + STREAM_FLUSH_SCRIPT ) ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceDescription ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . rubypeople . rdt . core . LoadpathVariableInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RubyLoadpathVariablesInitializer extends LoadpathVariableInitializer implements IVMInstallChangedListener { private IProgressMonitor fMonitor ; private String fVariable ; public RubyLoadpathVariablesInitializer ( ) { RubyRuntime . addVMInstallChangedListener ( this ) ; } public void initialize ( String variable ) { this . fVariable = variable ; IVMInstall vmInstall = RubyRuntime . getDefaultVMInstall ( ) ; if ( vmInstall != null ) { IPath [ ] systemLib = RubyRuntime . getLibraryLocations ( vmInstall ) ; if ( systemLib != null ) { IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; IWorkspaceDescription wsDescription = workspace . getDescription ( ) ; boolean wasAutobuild = wsDescription . isAutoBuilding ( ) ; try { setAutobuild ( workspace , false ) ; setRubyVMVariable ( systemLib , variable ) ; } catch ( CoreException ce ) { LaunchingPlugin . log ( ce ) ; return ; } finally { try { setAutobuild ( workspace , wasAutobuild ) ; } catch ( CoreException ce ) { LaunchingPlugin . log ( ce ) ; } } } } } private void setRubyVMVariable ( IPath [ ] newPath , String var ) throws CoreException { RubyCore . setLoadpathVariable ( var , newPath , getMonitor ( ) ) ; } private boolean setAutobuild ( IWorkspace ws , boolean newState ) throws CoreException { IWorkspaceDescription wsDescription = ws . getDescription ( ) ; boolean oldState = wsDescription . isAutoBuilding ( ) ; if ( oldState != newState ) { wsDescription . setAutoBuilding ( newState ) ; ws . setDescription ( wsDescription ) ; } return oldState ; } protected IProgressMonitor getMonitor ( ) { if ( fMonitor == null ) { return new NullProgressMonitor ( ) ; } return fMonitor ; } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { initialize ( fVariable ) ; } public void vmAdded ( IVMInstall newVm ) { } public void vmChanged ( PropertyChangeEvent event ) { } public void vmRemoved ( IVMInstall removedVm ) { } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . osgi . service . environment . Constants ; import org . rubypeople . rdt . launching . AbstractVMInstallType ; import org . rubypeople . rdt . launching . IVMInstall ; public class RubiniusVMType extends AbstractVMInstallType { private static Map < String , LibraryInfo > fgFailedInstallPath = new HashMap < String , LibraryInfo > ( ) ; private static final char fgSeparator = File . separatorChar ; private static final String [ ] fgCandidateRubyFiles = { "" , "" } ; private static final String [ ] fgCandidateRubyLocations = { "" , "" + fgSeparator , "" + fgSeparator } ; @ Override protected IVMInstall doCreateVMInstall ( String id ) { return new RubiniusVM ( this , id ) ; } public File detectInstallLocation ( ) { File rubyExecutable = null ; if ( Platform . getOS ( ) . equals ( Constants . OS_WIN32 ) ) { String winPath = System . getenv ( "" ) ; String [ ] paths = winPath . split ( "" ) ; for ( int i = ; i < paths . length ; i ++ ) { String possibleExecutablePath = paths [ i ] + File . separator + "" ; File possible = new File ( possibleExecutablePath ) ; if ( possible . exists ( ) ) { rubyExecutable = possible ; break ; } } } else { String [ ] cmdLine = new String [ ] { "" , "" } ; rubyExecutable = parseRubyExecutableLocation ( executeAndRead ( cmdLine ) ) ; if ( rubyExecutable == null || rubyExecutable . getAbsolutePath ( ) . startsWith ( "" ) ) { File rubyHome = tryLocation ( new File ( "" ) ) ; if ( rubyHome != null ) return rubyHome ; rubyHome = tryLocation ( new File ( "" ) ) ; if ( rubyHome != null ) return rubyHome ; } } return tryLocation ( rubyExecutable ) ; } private File tryLocation ( File rubyExecutable ) { if ( rubyExecutable == null ) { return null ; } File bin = rubyExecutable . getParentFile ( ) ; if ( ! bin . exists ( ) ) return null ; File rubyHome = bin . getParentFile ( ) ; if ( ! rubyHome . exists ( ) ) return null ; if ( ! canDetectDefaultSystemLibraries ( rubyHome , rubyExecutable ) ) { return null ; } return rubyHome ; } public IPath [ ] getDefaultLibraryLocations ( File installLocation ) { File rubyExecutable = findRubyExecutable ( installLocation ) ; LibraryInfo info ; if ( rubyExecutable == null ) { info = getDefaultLibraryInfo ( installLocation ) ; } else { info = getLibraryInfo ( installLocation , rubyExecutable ) ; } String [ ] loadpath = info . getBootpath ( ) ; IPath [ ] paths = new IPath [ loadpath . length ] ; for ( int i = ; i < loadpath . length ; i ++ ) { paths [ i ] = new Path ( loadpath [ i ] ) ; } return paths ; } public String getName ( ) { return "" ; } public IStatus validateInstallLocation ( File rubyHome ) { IStatus status = null ; File rubyExecutable = findRubyExecutable ( rubyHome ) ; if ( rubyExecutable == null ) { status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_Not_a_JDK_Root__Java_executable_was_not_found_1 , null ) ; } else { if ( canDetectDefaultSystemLibraries ( rubyHome , rubyExecutable ) ) { status = new Status ( IStatus . OK , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_ok_2 , null ) ; } else { status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_Not_a_JDK_root__System_library_was_not_found__1 , null ) ; } } return status ; } public static File findRubyExecutable ( File vmInstallLocation ) { for ( int i = ; i < fgCandidateRubyFiles . length ; i ++ ) { for ( int j = ; j < fgCandidateRubyLocations . length ; j ++ ) { File rubyFile = new File ( vmInstallLocation , fgCandidateRubyLocations [ j ] + fgCandidateRubyFiles [ i ] ) ; if ( rubyFile . isFile ( ) ) { return rubyFile ; } } } return null ; } protected boolean canDetectDefaultSystemLibraries ( File rubyHome , File rubyExecutable ) { IPath [ ] locations = getDefaultLibraryLocations ( rubyHome ) ; return locations . length > ; } protected LibraryInfo getDefaultLibraryInfo ( File installLocation ) { IPath [ ] dflts = getDefaultSystemLibrary ( installLocation ) ; String [ ] strings = new String [ dflts . length ] ; for ( int i = ; i < dflts . length ; i ++ ) { strings [ i ] = dflts [ i ] . toOSString ( ) ; } return new LibraryInfo ( "" , strings ) ; } protected IPath [ ] getDefaultSystemLibrary ( File rubyHome ) { File exe = findRubyExecutable ( rubyHome ) ; if ( exe != null && exe . getAbsolutePath ( ) . endsWith ( "" + File . separator + "" ) ) { return new IPath [ ] { new Path ( rubyHome . getAbsolutePath ( ) + fgSeparator + "" ) } ; } return new IPath [ ] { new Path ( rubyHome . getAbsolutePath ( ) + fgSeparator + "" + fgSeparator + "" + fgSeparator + "" ) } ; } protected synchronized LibraryInfo getLibraryInfo ( File rubyHome , File rubyExecutable ) { String installPath = rubyHome . getAbsolutePath ( ) ; LibraryInfo info = LaunchingPlugin . getLibraryInfo ( this , installPath ) ; if ( info == null ) { info = fgFailedInstallPath . get ( installPath ) ; if ( info == null ) { info = generateLibraryInfo ( rubyHome , rubyExecutable ) ; if ( info == null ) { info = getDefaultLibraryInfo ( rubyHome ) ; fgFailedInstallPath . put ( installPath , info ) ; } else { LaunchingPlugin . setLibraryInfo ( this , installPath , info ) ; } } } return info ; } protected File getLibraryInfoGeneratorPath ( ) { return LaunchingPlugin . getFileInPlugin ( new Path ( "" ) . append ( "" ) . append ( "" ) ) ; } public File findExecutable ( File installLocation ) { return findRubyExecutable ( installLocation ) ; } public String getVMPlatform ( File installLocation , File executable ) { return "" ; } } package org . rubypeople . rdt . internal . launching ; public class ListenerList { private int fSize ; private Object [ ] fListeners = null ; private static final Object [ ] EmptyArray = new Object [ ] ; public ListenerList ( int capacity ) { if ( capacity < ) { throw new IllegalArgumentException ( ) ; } fListeners = new Object [ capacity ] ; fSize = ; } public synchronized void add ( Object listener ) { if ( listener == null ) { throw new IllegalArgumentException ( ) ; } for ( int i = ; i < fSize ; ++ i ) { if ( fListeners [ i ] == listener ) { return ; } } if ( fSize == fListeners . length ) { Object [ ] temp = new Object [ ( fSize * ) + ] ; System . arraycopy ( fListeners , , temp , , fSize ) ; fListeners = temp ; } fListeners [ fSize ++ ] = listener ; } public synchronized Object [ ] getListeners ( ) { if ( fSize == ) { return EmptyArray ; } Object [ ] result = new Object [ fSize ] ; System . arraycopy ( fListeners , , result , , fSize ) ; return result ; } public synchronized void remove ( Object listener ) { if ( listener == null ) { throw new IllegalArgumentException ( ) ; } for ( int i = ; i < fSize ; ++ i ) { if ( fListeners [ i ] == listener ) { if ( -- fSize == ) { fListeners = new Object [ ] ; } else { if ( i < fSize ) { fListeners [ i ] = fListeners [ fSize ] ; } fListeners [ fSize ] = null ; } return ; } } } public synchronized void removeAll ( ) { fListeners = new Object [ ] ; fSize = ; } public int size ( ) { return fSize ; } } package org . rubypeople . rdt . internal . launching ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public interface RubyLaunchConfigurationAttribute { static final String SELECTED_INTERPRETER = IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME ; static final String USE_DEFAULT_LOAD_PATH = IRubyLaunchConfigurationConstants . ATTR_DEFAULT_LOADPATH ; static final String USE_DEFAULT_WORKING_DIRECTORY = LaunchingPlugin . PLUGIN_ID + "" ; } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . IProcess ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . SocketUtil ; import org . rubypeople . rdt . debug . core . RdtDebugCorePlugin ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMRunner ; import org . rubypeople . rdt . launching . VMRunnerConfiguration ; public class StandardVMDebugger extends StandardVMRunner implements IVMRunner { public void run ( VMRunnerConfiguration config , ILaunch launch , IProgressMonitor monitor ) throws CoreException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } IProgressMonitor subMonitor = new SubProgressMonitor ( monitor , ) ; subMonitor . beginTask ( LaunchingMessages . StandardVMDebugger_Launching_VM____1 , ) ; subMonitor . subTask ( LaunchingMessages . StandardVMDebugger_Finding_free_socket____2 ) ; int port = SocketUtil . findFreePort ( ) ; if ( port == - ) { abort ( LaunchingMessages . StandardVMDebugger_Could_not_find_a_free_socket_for_the_debugger_1 , null , IRubyLaunchConfigurationConstants . ERR_NO_SOCKET_AVAILABLE ) ; } subMonitor . worked ( ) ; if ( monitor . isCanceled ( ) ) { return ; } subMonitor . subTask ( LaunchingMessages . StandardVMDebugger_Constructing_command_line____3 ) ; RubyDebugTarget debugTarget = new RubyDebugTarget ( launch , port ) ; List < String > arguments = constructProgramString ( config , monitor ) ; String [ ] allVMArgs = combineVmArgs ( config , fVMInstance ) ; addArguments ( allVMArgs , arguments ) ; String [ ] cp = config . getLoadPath ( ) ; if ( cp . length > ) { arguments . addAll ( convertLoadPath ( config , cp ) ) ; } addStreamSync ( arguments ) ; arguments . addAll ( debugSpecificVMArgs ( debugTarget ) ) ; arguments . add ( StandardVMRunner . END_OF_OPTIONS_DELIMITER ) ; arguments . addAll ( debugArgs ( debugTarget ) ) ; arguments . add ( getFileToLaunch ( config ) ) ; addArguments ( config . getProgramArguments ( ) , arguments ) ; String [ ] cmdLine = new String [ arguments . size ( ) ] ; arguments . toArray ( cmdLine ) ; String [ ] envp = getEnvironment ( config ) ; if ( monitor . isCanceled ( ) ) { return ; } subMonitor . worked ( ) ; subMonitor . subTask ( LaunchingMessages . StandardVMDebugger_Starting_virtual_machine____4 ) ; Process p = null ; if ( monitor . isCanceled ( ) ) { return ; } File workingDir = getWorkingDir ( config ) ; p = exec ( cmdLine , workingDir , envp ) ; if ( p == null ) { return ; } if ( monitor . isCanceled ( ) ) { p . destroy ( ) ; return ; } IProcess process = newProcess ( launch , p , renderProcessLabel ( cmdLine ) , getDefaultProcessMap ( ) ) ; String commandLine = renderCommandLine ( cmdLine ) ; LaunchingPlugin . debug ( "" + commandLine ) ; process . setAttribute ( IProcess . ATTR_CMDLINE , commandLine ) ; subMonitor . worked ( ) ; subMonitor . subTask ( LaunchingMessages . StandardVMDebugger_Establishing_debug_connection____5 ) ; debugTarget . setProcess ( process ) ; RubyDebuggerProxy proxy = getDebugProxy ( debugTarget ) ; try { proxy . start ( ) ; launch . addDebugTarget ( debugTarget ) ; } catch ( IOException iox ) { LaunchingPlugin . log ( new Status ( IStatus . ERROR , LaunchingPlugin . PLUGIN_ID , IStatus . ERROR , LaunchingMessages . RdtLaunchingPlugin_processTerminatedBecauseNoDebuggerConnection , null ) ) ; debugTarget . terminate ( ) ; } catch ( RubyProcessingException e ) { abort ( LaunchingMessages . StandardVMDebugger_Couldn__t_connect_to_VM_5 , e , IRubyLaunchConfigurationConstants . ERR_CONNECTION_FAILED ) ; debugTarget . terminate ( ) ; } } protected Collection < String > debugArgs ( RubyDebugTarget debugTarget ) throws CoreException { return new ArrayList < String > ( ) ; } protected RubyDebuggerProxy getDebugProxy ( RubyDebugTarget debugTarget ) { return new RubyDebuggerProxy ( debugTarget , false ) ; } protected List < String > debugSpecificVMArgs ( RubyDebugTarget debugTarget ) { List < String > arguments = new ArrayList < String > ( ) ; arguments . add ( "" ) ; arguments . add ( new Path ( getDirectoryOfRubyDebuggerFile ( ) ) . toOSString ( ) ) ; if ( ! debugTarget . isUsingDefaultPort ( ) ) { arguments . add ( "" + debugTarget . getDebugParameterFile ( ) . getAbsolutePath ( ) ) ; } if ( RdtDebugCorePlugin . isRubyDebuggerVerbose ( ) || isDebuggerVerbose ( ) ) { arguments . add ( "" ) ; } else { arguments . add ( "" ) ; } return arguments ; } protected static boolean isDebuggerVerbose ( ) { return LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) . getBoolean ( PreferenceConstants . VERBOSE_DEBUGGER ) ; } public static String getDirectoryOfRubyDebuggerFile ( ) { RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) ) ; RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) ) ; File debugFile = RubyCore . copyToStateLocation ( LaunchingPlugin . getDefault ( ) , new Path ( "" ) . append ( "" ) ) ; if ( debugFile == null ) return "" ; return debugFile . getParent ( ) ; } } package org . rubypeople . rdt . internal . launching ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . FactoryConfigurationError ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . Transformer ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . Preferences . IPropertyChangeListener ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugEvent ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . IDebugEventSetListener ; import org . eclipse . debug . core . model . IProcess ; import org . osgi . framework . BundleContext ; import org . osgi . util . tracker . ServiceTracker ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyInformation ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry2 ; import org . rubypeople . rdt . launching . IVMConnector ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; import org . xml . sax . helpers . DefaultHandler ; public class LaunchingPlugin extends Plugin implements IVMInstallChangedListener , IPropertyChangeListener , IDebugEventSetListener { public static final String PLUGIN_ID = "" ; public static final String USING_INCLUDED_JRUBY = PLUGIN_ID + "" ; private HashMap < String , IConfigurationElement > fClasspathEntryExtensions = null ; public static final String ID_EXTENSION_POINT_RUNTIME_CLASSPATH_ENTRIES = "" ; public static final String ID_EXTENSION_POINT_VM_CONNECTORS = "" ; private static Map < String , LibraryInfo > fgLibraryInfoMap = null ; private boolean fBatchingChanges = false ; private boolean fIgnoreVMDefPropertyChangeEvents = false ; private String fOldVMPrefString = EMPTY_STRING ; protected static LaunchingPlugin plugin ; private static DocumentBuilder fgXMLParser ; private ServiceTracker fRITracker ; private LaunchCleaner fLaunchCleaner ; private HashMap < String , IVMConnector > fVMConnectors ; private static final String EMPTY_STRING = "" ; public static String osDependentPath ( String aPath ) { if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) { if ( aPath . startsWith ( File . separator ) ) { aPath = aPath . substring ( ) ; } } return aPath ; } public LaunchingPlugin ( ) { super ( ) ; } public static LaunchingPlugin getDefault ( ) { return plugin ; } public static IWorkspace getWorkspace ( ) { return RubyCore . getWorkspace ( ) ; } public static void log ( IStatus status ) { getDefault ( ) . getLog ( ) . log ( status ) ; } public static void log ( Throwable e ) { log ( new Status ( IStatus . ERROR , PLUGIN_ID , IStatus . ERROR , LaunchingMessages . RdtLaunchingPlugin_internalErrorOccurred , e ) ) ; } public static void debug ( String message ) { if ( getDefault ( ) . isDebugging ( ) ) { System . out . println ( message ) ; } } @ Override public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; fRITracker = new ServiceTracker ( context , IRubyInformation . class . getName ( ) , null ) ; fRITracker . open ( ) ; getPluginPreferences ( ) . addPropertyChangeListener ( this ) ; RubyRuntime . addVMInstallChangedListener ( this ) ; DebugPlugin . getDefault ( ) . addDebugEventListener ( this ) ; fLaunchCleaner = new LaunchCleaner ( ) ; ResourcesPlugin . getWorkspace ( ) . addResourceChangeListener ( fLaunchCleaner ) ; } @ Override public void stop ( BundleContext context ) throws Exception { try { fRITracker . close ( ) ; ResourcesPlugin . getWorkspace ( ) . removeResourceChangeListener ( fLaunchCleaner ) ; DebugPlugin . getDefault ( ) . removeDebugEventListener ( this ) ; getPluginPreferences ( ) . removePropertyChangeListener ( this ) ; RubyRuntime . removeVMInstallChangedListener ( this ) ; RubyRuntime . saveVMConfiguration ( ) ; savePluginPreferences ( ) ; fgXMLParser = null ; } finally { super . stop ( context ) ; } } public static String getUniqueIdentifier ( ) { return PLUGIN_ID ; } public void propertyChange ( org . eclipse . core . runtime . Preferences . PropertyChangeEvent event ) { String property = event . getProperty ( ) ; if ( property . equals ( RubyRuntime . PREF_VM_XML ) ) { if ( ! isIgnoreVMDefPropertyChangeEvents ( ) ) { processVMPrefsChanged ( ( String ) event . getOldValue ( ) , ( String ) event . getNewValue ( ) ) ; } } } public void setIgnoreVMDefPropertyChangeEvents ( boolean ignore ) { fIgnoreVMDefPropertyChangeEvents = ignore ; } public boolean isIgnoreVMDefPropertyChangeEvents ( ) { return fIgnoreVMDefPropertyChangeEvents ; } protected void processVMPrefsChanged ( String oldValue , String newValue ) { fBatchingChanges = true ; VMChanges vmChanges = null ; try { String oldPrefString ; String newPrefString ; if ( newValue == null || newValue . equals ( EMPTY_STRING ) ) { fOldVMPrefString = oldValue ; return ; } else if ( oldValue == null || oldValue . equals ( EMPTY_STRING ) ) { oldPrefString = fOldVMPrefString ; newPrefString = newValue ; } else { oldPrefString = oldValue ; newPrefString = newValue ; } vmChanges = new VMChanges ( ) ; RubyRuntime . addVMInstallChangedListener ( vmChanges ) ; VMDefinitionsContainer oldResults = getVMDefinitions ( oldPrefString ) ; VMDefinitionsContainer newResults = getVMDefinitions ( newPrefString ) ; List < IVMInstall > deleted = oldResults . getVMList ( ) ; List < IVMInstall > current = newResults . getValidVMList ( ) ; deleted . removeAll ( current ) ; Iterator deletedIterator = deleted . iterator ( ) ; while ( deletedIterator . hasNext ( ) ) { VMStandin deletedVMStandin = ( VMStandin ) deletedIterator . next ( ) ; deletedVMStandin . getVMInstallType ( ) . disposeVMInstall ( deletedVMStandin . getId ( ) ) ; } Iterator iter = current . iterator ( ) ; while ( iter . hasNext ( ) ) { VMStandin standin = ( VMStandin ) iter . next ( ) ; standin . convertToRealVM ( ) ; } String newDefaultId = newResults . getDefaultVMInstallCompositeID ( ) ; if ( newDefaultId != null ) { IVMInstall newDefaultVM = RubyRuntime . getVMFromCompositeId ( newDefaultId ) ; if ( newDefaultVM != null ) { try { RubyRuntime . setDefaultVMInstall ( newDefaultVM , null , false ) ; } catch ( CoreException ce ) { log ( ce ) ; } } } } finally { fBatchingChanges = false ; if ( vmChanges != null ) { RubyRuntime . removeVMInstallChangedListener ( vmChanges ) ; try { vmChanges . process ( ) ; } catch ( CoreException e ) { log ( e ) ; } } } } private VMDefinitionsContainer getVMDefinitions ( String xml ) { if ( xml . length ( ) > ) { try { ByteArrayInputStream stream = new ByteArrayInputStream ( xml . getBytes ( "" ) ) ; return VMDefinitionsContainer . parseXMLIntoContainer ( stream ) ; } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } } return new VMDefinitionsContainer ( ) ; } public static Document getDocument ( ) throws ParserConfigurationException { DocumentBuilderFactory dfactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder docBuilder = dfactory . newDocumentBuilder ( ) ; Document doc = docBuilder . newDocument ( ) ; return doc ; } public static String serializeDocument ( Document doc ) throws IOException , TransformerException { ByteArrayOutputStream s = new ByteArrayOutputStream ( ) ; TransformerFactory factory = TransformerFactory . newInstance ( ) ; Transformer transformer = factory . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . METHOD , "" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "" ) ; DOMSource source = new DOMSource ( doc ) ; StreamResult outputTarget = new StreamResult ( s ) ; transformer . transform ( source , outputTarget ) ; return s . toString ( "" ) ; } public static void log ( String message ) { log ( new Status ( IStatus . ERROR , getUniqueIdentifier ( ) , IStatus . ERROR , message , null ) ) ; } public static DocumentBuilder getParser ( ) throws CoreException { if ( fgXMLParser == null ) { try { fgXMLParser = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; fgXMLParser . setErrorHandler ( new DefaultHandler ( ) ) ; } catch ( ParserConfigurationException e ) { abort ( LaunchingMessages . LaunchingPlugin_33 , e ) ; } catch ( FactoryConfigurationError e ) { abort ( LaunchingMessages . LaunchingPlugin_34 , e ) ; } } return fgXMLParser ; } protected static void abort ( String message , Throwable exception ) throws CoreException { IStatus status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , , message , exception ) ; throw new CoreException ( status ) ; } public static void setLibraryInfo ( IVMInstallType type , String installPath , LibraryInfo info ) { if ( fgLibraryInfoMap == null ) { restoreLibraryInfo ( ) ; } if ( info == null ) { fgLibraryInfoMap . remove ( buildLibraryInfoKey ( type , installPath ) ) ; } else { fgLibraryInfoMap . put ( buildLibraryInfoKey ( type , installPath ) , info ) ; } saveLibraryInfo ( ) ; } private static void saveLibraryInfo ( ) { FileOutputStream stream = null ; try { String xml = getLibraryInfoAsXML ( ) ; IPath libPath = getDefault ( ) . getStateLocation ( ) ; libPath = libPath . append ( "" ) ; File file = libPath . toFile ( ) ; if ( ! file . exists ( ) ) { file . createNewFile ( ) ; } stream = new FileOutputStream ( file ) ; stream . write ( xml . getBytes ( "" ) ) ; } catch ( IOException e ) { log ( e ) ; } catch ( ParserConfigurationException e ) { log ( e ) ; } catch ( TransformerException e ) { log ( e ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e1 ) { } } } } private static String getLibraryInfoAsXML ( ) throws ParserConfigurationException , IOException , TransformerException { Document doc = getDocument ( ) ; Element config = doc . createElement ( "" ) ; doc . appendChild ( config ) ; Iterator locations = fgLibraryInfoMap . keySet ( ) . iterator ( ) ; while ( locations . hasNext ( ) ) { String raw = ( String ) locations . next ( ) ; int index = raw . indexOf ( "" ) ; String home = raw . substring ( index + ) ; String vmTypeId = "" ; if ( index != - ) { vmTypeId = raw . substring ( , index ) ; } LibraryInfo info = fgLibraryInfoMap . get ( raw ) ; Element locationElemnet = infoAsElement ( doc , info ) ; locationElemnet . setAttribute ( "" , home ) ; locationElemnet . setAttribute ( "" , vmTypeId ) ; config . appendChild ( locationElemnet ) ; } return LaunchingPlugin . serializeDocument ( doc ) ; } private static Element infoAsElement ( Document doc , LibraryInfo info ) { Element libraryElement = doc . createElement ( "" ) ; libraryElement . setAttribute ( "" , info . getVersion ( ) ) ; appendPathElements ( doc , "" , libraryElement , info . getBootpath ( ) ) ; return libraryElement ; } private static void appendPathElements ( Document doc , String elementType , Element libraryElement , String [ ] paths ) { if ( paths . length > ) { Element child = doc . createElement ( elementType ) ; libraryElement . appendChild ( child ) ; for ( int i = ; i < paths . length ; i ++ ) { String path = paths [ i ] ; Element entry = doc . createElement ( "" ) ; child . appendChild ( entry ) ; entry . setAttribute ( "" , path ) ; } } } public static LibraryInfo getLibraryInfo ( IVMInstallType type , String vmInstallPath ) { if ( fgLibraryInfoMap == null ) { restoreLibraryInfo ( ) ; } return fgLibraryInfoMap . get ( buildLibraryInfoKey ( type , vmInstallPath ) ) ; } private static String buildLibraryInfoKey ( IVMInstallType type , String vmInstallPath ) { return buildLibraryInfoKey ( type . getId ( ) , vmInstallPath ) ; } private static String buildLibraryInfoKey ( String vmTypeId , String vmInstallPath ) { return vmTypeId + "" + vmInstallPath ; } private static void restoreLibraryInfo ( ) { fgLibraryInfoMap = new HashMap < String , LibraryInfo > ( ) ; IPath libPath = getDefault ( ) . getStateLocation ( ) ; libPath = libPath . append ( "" ) ; File file = libPath . toFile ( ) ; if ( file . exists ( ) ) { try { InputStream stream = new FileInputStream ( file ) ; DocumentBuilder parser = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; parser . setErrorHandler ( new DefaultHandler ( ) ) ; Element root = parser . parse ( new InputSource ( stream ) ) . getDocumentElement ( ) ; if ( ! root . getNodeName ( ) . equals ( "" ) ) { return ; } NodeList list = root . getChildNodes ( ) ; int length = list . getLength ( ) ; for ( int i = ; i < length ; ++ i ) { Node node = list . item ( i ) ; short type = node . getNodeType ( ) ; if ( type == Node . ELEMENT_NODE ) { Element element = ( Element ) node ; String nodeName = element . getNodeName ( ) ; if ( nodeName . equalsIgnoreCase ( "" ) ) { String version = element . getAttribute ( "" ) ; String location = element . getAttribute ( "" ) ; String vmTypeId = element . getAttribute ( "" ) ; String [ ] bootpath = getPathsFromXML ( element , "" ) ; if ( location != null ) { LibraryInfo info = new LibraryInfo ( version , bootpath ) ; fgLibraryInfoMap . put ( buildLibraryInfoKey ( vmTypeId , location ) , info ) ; } } } } } catch ( IOException e ) { log ( e ) ; } catch ( ParserConfigurationException e ) { log ( e ) ; } catch ( SAXException e ) { log ( e ) ; } } } private static String [ ] getPathsFromXML ( Element lib , String pathType ) { List < String > paths = new ArrayList < String > ( ) ; NodeList list = lib . getChildNodes ( ) ; int length = list . getLength ( ) ; for ( int i = ; i < length ; ++ i ) { Node node = list . item ( i ) ; short type = node . getNodeType ( ) ; if ( type == Node . ELEMENT_NODE ) { Element element = ( Element ) node ; String nodeName = element . getNodeName ( ) ; if ( nodeName . equalsIgnoreCase ( pathType ) ) { NodeList entries = element . getChildNodes ( ) ; int numEntries = entries . getLength ( ) ; for ( int j = ; j < numEntries ; j ++ ) { Node n = entries . item ( j ) ; short t = n . getNodeType ( ) ; if ( t == Node . ELEMENT_NODE ) { Element entryElement = ( Element ) n ; String name = entryElement . getNodeName ( ) ; if ( name . equals ( "" ) ) { String path = entryElement . getAttribute ( "" ) ; if ( path != null && path . length ( ) > ) { paths . add ( path ) ; } } } } } } } return paths . toArray ( new String [ paths . size ( ) ] ) ; } public IRuntimeLoadpathEntry2 newRuntimeLoadpathEntry ( String id ) throws CoreException { if ( fClasspathEntryExtensions == null ) { initializeRuntimeLoadpathExtensions ( ) ; } IConfigurationElement config = fClasspathEntryExtensions . get ( id ) ; if ( config == null ) { abort ( MessageFormat . format ( LaunchingMessages . LaunchingPlugin_32 , id ) , null ) ; } return ( IRuntimeLoadpathEntry2 ) config . createExecutableExtension ( "" ) ; } private void initializeRuntimeLoadpathExtensions ( ) { IExtensionPoint extensionPoint = Platform . getExtensionRegistry ( ) . getExtensionPoint ( LaunchingPlugin . PLUGIN_ID , ID_EXTENSION_POINT_RUNTIME_CLASSPATH_ENTRIES ) ; IConfigurationElement [ ] configs = extensionPoint . getConfigurationElements ( ) ; fClasspathEntryExtensions = new HashMap < String , IConfigurationElement > ( configs . length ) ; for ( int i = ; i < configs . length ; i ++ ) { fClasspathEntryExtensions . put ( configs [ i ] . getAttribute ( "" ) , configs [ i ] ) ; } } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { if ( ! fBatchingChanges ) { try { VMChanges changes = new VMChanges ( ) ; changes . defaultVMInstallChanged ( previous , current ) ; changes . process ( ) ; } catch ( CoreException e ) { log ( e ) ; } } } public void vmAdded ( IVMInstall newVm ) { } public void vmChanged ( PropertyChangeEvent event ) { if ( ! fBatchingChanges ) { try { VMChanges changes = new VMChanges ( ) ; changes . vmChanged ( event ) ; changes . process ( ) ; } catch ( CoreException e ) { log ( e ) ; } } } public void vmRemoved ( IVMInstall vm ) { removeCoreStubs ( vm ) ; if ( ! fBatchingChanges ) { try { VMChanges changes = new VMChanges ( ) ; changes . vmRemoved ( vm ) ; changes . process ( ) ; } catch ( CoreException e ) { log ( e ) ; } } } private void removeCoreStubs ( IVMInstall vm ) { IPath coreStubPath = getStateLocation ( ) . append ( vm . getId ( ) ) ; deleteRecursively ( coreStubPath . toFile ( ) ) ; } private void deleteRecursively ( File file ) { if ( file . isDirectory ( ) ) { File [ ] children = file . listFiles ( ) ; for ( int i = ; i < children . length ; i ++ ) { deleteRecursively ( children [ i ] ) ; } } if ( ! file . delete ( ) ) file . deleteOnExit ( ) ; } class VMChanges implements IVMInstallChangedListener { private boolean fDefaultChanged = false ; private HashMap < IPath , IPath > fRenamedContainerIds = new HashMap < IPath , IPath > ( ) ; private IPath getContainerId ( IVMInstall vm ) { if ( vm != null ) { String name = vm . getName ( ) ; if ( name != null ) { IPath path = new Path ( RubyRuntime . RUBY_CONTAINER ) ; path = path . append ( new Path ( vm . getVMInstallType ( ) . getId ( ) ) ) ; path = path . append ( new Path ( name ) ) ; return path ; } } return null ; } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { fDefaultChanged = true ; } public void vmAdded ( IVMInstall vm ) { } public void vmChanged ( org . rubypeople . rdt . launching . PropertyChangeEvent event ) { String property = event . getProperty ( ) ; IVMInstall vm = ( IVMInstall ) event . getSource ( ) ; if ( property . equals ( IVMInstallChangedListener . PROPERTY_NAME ) ) { IPath newId = getContainerId ( vm ) ; IPath oldId = new Path ( RubyRuntime . RUBY_CONTAINER ) ; oldId = oldId . append ( vm . getVMInstallType ( ) . getId ( ) ) ; String oldName = ( String ) event . getOldValue ( ) ; if ( oldName != null ) { oldId = oldId . append ( oldName ) ; fRenamedContainerIds . put ( oldId , newId ) ; } } } public void vmRemoved ( IVMInstall vm ) { } public void process ( ) throws CoreException { RubyVMUpdateJob job = new RubyVMUpdateJob ( this ) ; job . schedule ( ) ; } protected void doit ( IProgressMonitor monitor ) throws CoreException { IWorkspaceRunnable runnable = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor1 ) throws CoreException { IRubyProject [ ] projects = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) . getRubyProjects ( ) ; monitor1 . beginTask ( LaunchingMessages . LaunchingPlugin_0 , projects . length + ) ; rebind ( monitor1 , projects ) ; monitor1 . done ( ) ; } } ; RubyCore . run ( runnable , null , monitor ) ; } private void rebind ( IProgressMonitor monitor , IRubyProject [ ] projects ) throws CoreException { if ( fDefaultChanged ) { RubyLoadpathVariablesInitializer initializer = new RubyLoadpathVariablesInitializer ( ) ; initializer . initialize ( RubyRuntime . RUBYLIB_VARIABLE ) ; } monitor . worked ( ) ; for ( int i = ; i < projects . length ; i ++ ) { IRubyProject project = projects [ i ] ; ILoadpathEntry [ ] entries = project . getRawLoadpath ( ) ; boolean replace = false ; for ( int j = ; j < entries . length ; j ++ ) { ILoadpathEntry entry = entries [ j ] ; switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_CONTAINER : IPath reference = entry . getPath ( ) ; IPath newBinding = null ; String firstSegment = reference . segment ( ) ; if ( RubyRuntime . RUBY_CONTAINER . equals ( firstSegment ) ) { if ( reference . segmentCount ( ) > ) { IPath renamed = fRenamedContainerIds . get ( reference ) ; if ( renamed != null ) { newBinding = renamed ; } } RubyContainerInitializer initializer = new RubyContainerInitializer ( ) ; if ( newBinding == null ) { initializer . initialize ( reference , project ) ; } else { ILoadpathEntry newEntry = RubyCore . newContainerEntry ( newBinding , entry . isExported ( ) ) ; entries [ j ] = newEntry ; replace = true ; } } break ; default : break ; } } if ( replace ) { project . setRawLoadpath ( entries , null ) ; } monitor . worked ( ) ; } } } class RubyVMUpdateJob extends Job { private VMChanges fChanges ; public RubyVMUpdateJob ( VMChanges changes ) { super ( LaunchingMessages . LaunchingPlugin_1 ) ; fChanges = changes ; setSystem ( true ) ; } protected IStatus run ( IProgressMonitor monitor ) { try { fChanges . doit ( monitor ) ; } catch ( CoreException e ) { return e . getStatus ( ) ; } return Status . OK_STATUS ; } } public static File getFileInPlugin ( IPath path ) { return RubyCore . copyToStateLocation ( getDefault ( ) , path ) ; } public static void info ( String string ) { log ( new Status ( IStatus . INFO , PLUGIN_ID , - , string , null ) ) ; } public void handleDebugEvents ( DebugEvent [ ] events ) { for ( int i = ; i < events . length ; i ++ ) { int kind = events [ i ] . getKind ( ) ; Object source = events [ i ] . getSource ( ) ; if ( ( kind == DebugEvent . TERMINATE ) && ( source instanceof IProcess ) ) { IProcess iProc = ( IProcess ) source ; String refresh = iProc . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_REQUIRES_REFRESH ) ; if ( ( refresh != null ) && refresh . equals ( "" ) ) { String projName = iProc . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME ) ; IProject proj = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projName ) ; try { proj . refreshLocal ( IResource . DEPTH_INFINITE , null ) ; } catch ( CoreException e ) { log ( e ) ; } } } } } public static IRubyInformation getRubyInformation ( ) { return ( IRubyInformation ) getDefault ( ) . fRITracker . getService ( ) ; } public IVMConnector getVMConnector ( String id ) { if ( fVMConnectors == null ) { initializeVMConnectors ( ) ; } return ( IVMConnector ) fVMConnectors . get ( id ) ; } public IVMConnector [ ] getVMConnectors ( ) { if ( fVMConnectors == null ) { initializeVMConnectors ( ) ; } return ( IVMConnector [ ] ) fVMConnectors . values ( ) . toArray ( new IVMConnector [ fVMConnectors . size ( ) ] ) ; } private void initializeVMConnectors ( ) { IExtensionPoint extensionPoint = Platform . getExtensionRegistry ( ) . getExtensionPoint ( PLUGIN_ID , ID_EXTENSION_POINT_VM_CONNECTORS ) ; IConfigurationElement [ ] configs = extensionPoint . getConfigurationElements ( ) ; MultiStatus status = new MultiStatus ( getUniqueIdentifier ( ) , IStatus . OK , "" , null ) ; fVMConnectors = new HashMap < String , IVMConnector > ( configs . length ) ; for ( int i = ; i < configs . length ; i ++ ) { try { IVMConnector vmConnector = ( IVMConnector ) configs [ i ] . createExecutableExtension ( "" ) ; fVMConnectors . put ( vmConnector . getIdentifier ( ) , vmConnector ) ; } catch ( CoreException e ) { status . add ( e . getStatus ( ) ) ; } } if ( ! status . isOK ( ) ) { LaunchingPlugin . log ( status ) ; } } public static void logInfo ( String msg ) { LaunchingPlugin . log ( new Status ( IStatus . INFO , LaunchingPlugin . PLUGIN_ID , - , msg , null ) ) ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . PlatformObject ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugPlugin ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry2 ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; public abstract class AbstractRuntimeLoadpathEntry extends PlatformObject implements IRuntimeLoadpathEntry2 { private IPath sourceAttachmentPath = null ; private IPath rootSourcePath = null ; private int classpathProperty = IRuntimeLoadpathEntry . USER_CLASSES ; private IRubyProject fRubyProject ; public boolean isComposite ( ) { return false ; } public IRuntimeLoadpathEntry [ ] getRuntimeLoadpathEntries ( ) throws CoreException { return new IRuntimeLoadpathEntry [ ] ; } protected void abort ( String message , Throwable exception ) throws CoreException { IStatus status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR , message , exception ) ; throw new CoreException ( status ) ; } public String getMemento ( ) throws CoreException { Document doc = DebugPlugin . newDocument ( ) ; Element root = doc . createElement ( "" ) ; doc . appendChild ( root ) ; root . setAttribute ( "" , getTypeId ( ) ) ; Element memento = doc . createElement ( "" ) ; root . appendChild ( memento ) ; buildMemento ( doc , memento ) ; return DebugPlugin . serializeDocument ( doc ) ; } protected abstract void buildMemento ( Document document , Element memento ) throws CoreException ; public IPath getPath ( ) { return null ; } public IResource getResource ( ) { return null ; } public IPath getSourceAttachmentPath ( ) { return sourceAttachmentPath ; } public void setSourceAttachmentPath ( IPath path ) { sourceAttachmentPath = path ; } public IPath getSourceAttachmentRootPath ( ) { return rootSourcePath ; } public void setSourceAttachmentRootPath ( IPath path ) { rootSourcePath = path ; } public int getLoadpathProperty ( ) { return classpathProperty ; } public void setLoadpathProperty ( int property ) { classpathProperty = property ; } public String getLocation ( ) { return null ; } public String getSourceAttachmentLocation ( ) { return null ; } public String getSourceAttachmentRootLocation ( ) { return null ; } public String getVariableName ( ) { return null ; } public ILoadpathEntry getLoadpathEntry ( ) { return null ; } public IRubyProject getRubyProject ( ) { return fRubyProject ; } protected void setRubyProject ( IRubyProject javaProject ) { fRubyProject = javaProject ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntryResolver ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntryResolver2 ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RubyVMRuntimeLoadpathEntryResolver implements IRuntimeLoadpathEntryResolver2 { public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , ILaunchConfiguration configuration ) throws CoreException { IVMInstall rubyVM = null ; if ( entry . getType ( ) == IRuntimeLoadpathEntry . CONTAINER && entry . getPath ( ) . segmentCount ( ) > ) { rubyVM = RubyContainerInitializer . resolveInterpreter ( entry . getPath ( ) ) ; } else { rubyVM = RubyRuntime . computeVMInstall ( configuration ) ; } if ( rubyVM == null ) { return new IRuntimeLoadpathEntry [ ] ; } return resolveLibraryLocations ( rubyVM , entry . getLoadpathProperty ( ) ) ; } public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , IRubyProject project ) throws CoreException { IVMInstall rubyVM = null ; if ( entry . getType ( ) == IRuntimeLoadpathEntry . CONTAINER && entry . getPath ( ) . segmentCount ( ) > ) { rubyVM = RubyContainerInitializer . resolveInterpreter ( entry . getPath ( ) ) ; } else { rubyVM = RubyRuntime . getVMInstall ( project ) ; } if ( rubyVM == null ) { return new IRuntimeLoadpathEntry [ ] ; } return resolveLibraryLocations ( rubyVM , entry . getLoadpathProperty ( ) ) ; } protected IRuntimeLoadpathEntry [ ] resolveLibraryLocations ( IVMInstall vm , int kind ) { IPath [ ] libs = vm . getLibraryLocations ( ) ; IPath [ ] defaultLibs = vm . getVMInstallType ( ) . getDefaultLibraryLocations ( vm . getInstallLocation ( ) ) ; boolean overrideRubydoc = false ; if ( libs == null ) { libs = defaultLibs ; overrideRubydoc = true ; } else if ( ! isSameArchives ( libs , defaultLibs ) ) { kind = IRuntimeLoadpathEntry . BOOTSTRAP_CLASSES ; } if ( kind == IRuntimeLoadpathEntry . BOOTSTRAP_CLASSES ) { File vmInstallLocation = vm . getInstallLocation ( ) ; if ( vmInstallLocation != null ) { LibraryInfo libraryInfo = LaunchingPlugin . getLibraryInfo ( vm . getVMInstallType ( ) , vmInstallLocation . getAbsolutePath ( ) ) ; if ( libraryInfo != null ) { List < IRuntimeLoadpathEntry > resolvedEntries = new ArrayList < IRuntimeLoadpathEntry > ( libs . length ) ; for ( int i = ; i < libs . length ; i ++ ) { IPath location = libs [ i ] ; IPath libraryPath = location ; String dir = libraryPath . toFile ( ) . getParent ( ) ; resolvedEntries . add ( resolveLibraryLocation ( vm , location , kind , overrideRubydoc ) ) ; } return resolvedEntries . toArray ( new IRuntimeLoadpathEntry [ resolvedEntries . size ( ) ] ) ; } } } List < IRuntimeLoadpathEntry > resolvedEntries = new ArrayList < IRuntimeLoadpathEntry > ( libs . length ) ; for ( int i = ; i < libs . length ; i ++ ) { IPath systemLibraryPath = libs [ i ] ; if ( systemLibraryPath . toFile ( ) . exists ( ) ) { resolvedEntries . add ( resolveLibraryLocation ( vm , libs [ i ] , kind , overrideRubydoc ) ) ; } } return resolvedEntries . toArray ( new IRuntimeLoadpathEntry [ resolvedEntries . size ( ) ] ) ; } public static boolean isSameArchives ( IPath [ ] libs , IPath [ ] defaultLibs ) { if ( libs . length != defaultLibs . length ) { return false ; } for ( int i = ; i < defaultLibs . length ; i ++ ) { IPath def = defaultLibs [ i ] ; IPath lib = libs [ i ] ; if ( ! def . equals ( lib ) ) { return false ; } } return true ; } public IVMInstall resolveVMInstall ( ILoadpathEntry entry ) { switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_VARIABLE : if ( entry . getPath ( ) . segment ( ) . equals ( RubyRuntime . RUBYLIB_VARIABLE ) ) { return RubyRuntime . getDefaultVMInstall ( ) ; } break ; case ILoadpathEntry . CPE_CONTAINER : if ( entry . getPath ( ) . segment ( ) . equals ( RubyRuntime . RUBY_CONTAINER ) ) { return RubyContainerInitializer . resolveInterpreter ( entry . getPath ( ) ) ; } break ; default : break ; } return null ; } public boolean isVMInstallReference ( ILoadpathEntry entry ) { switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_VARIABLE : if ( entry . getPath ( ) . segment ( ) . equals ( RubyRuntime . RUBYLIB_VARIABLE ) ) { return true ; } break ; case ILoadpathEntry . CPE_CONTAINER : if ( entry . getPath ( ) . segment ( ) . equals ( RubyRuntime . RUBY_CONTAINER ) ) { return true ; } break ; default : break ; } return false ; } private IRuntimeLoadpathEntry resolveLibraryLocation ( IVMInstall vm , IPath location , int kind , boolean overrideRubyDoc ) { IPath libraryPath = location ; ILoadpathEntry cpe = RubyCore . newLibraryEntry ( libraryPath , false ) ; IRuntimeLoadpathEntry resolved = new RuntimeLoadpathEntry ( cpe ) ; resolved . setLoadpathProperty ( kind ) ; return resolved ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . expressions . PropertyTester ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IAdaptable ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . rubypeople . rdt . core . IMember ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . IType ; import org . rubypeople . rdt . core . RubyModelException ; public class RubyLaunchableTester extends PropertyTester { private static final String PROPERTY_HAS_METHOD = "" ; private static final String PROPERTY_EXTENDS_CLASS = "" ; private static final String PROPERTY_IS_CONTAINER = "" ; private static final String PROPERTY_PROJECT_NATURE = "" ; public boolean test ( Object receiver , String property , Object [ ] args , Object expectedValue ) { if ( PROPERTY_IS_CONTAINER . equals ( property ) ) { if ( receiver instanceof IAdaptable ) { IResource resource = ( IResource ) ( ( IAdaptable ) receiver ) . getAdapter ( IResource . class ) ; if ( resource != null ) { return resource instanceof IContainer ; } } return false ; } if ( PROPERTY_PROJECT_NATURE . equals ( property ) ) { if ( receiver instanceof IAdaptable ) { IResource resource = ( IResource ) ( ( IAdaptable ) receiver ) . getAdapter ( IResource . class ) ; if ( resource != null ) { return hasProjectNature ( resource , ( String ) args [ ] ) ; } } } IRubyElement element = null ; if ( receiver instanceof IAdaptable ) { element = ( IRubyElement ) ( ( IAdaptable ) receiver ) . getAdapter ( IRubyElement . class ) ; if ( element != null ) { if ( ! element . exists ( ) ) { return false ; } } } if ( PROPERTY_HAS_METHOD . equals ( property ) ) { return hasMethod ( element , args ) ; } if ( PROPERTY_EXTENDS_CLASS . equals ( property ) ) { return hasSuperclass ( element , ( String ) args [ ] ) ; } if ( PROPERTY_PROJECT_NATURE . equals ( property ) ) { return hasProjectNature ( element , ( String ) args [ ] ) ; } return false ; } private boolean hasProjectNature ( IResource resource , String ntype ) { try { if ( resource != null ) { IProject proj = resource . getProject ( ) ; return proj . isAccessible ( ) && proj . hasNature ( ntype ) ; } } catch ( CoreException e ) { } return false ; } private boolean hasMethod ( IRubyElement element , Object [ ] args ) { try { if ( args . length > ) { IType type = getType ( element ) ; if ( type != null && type . exists ( ) ) { String name = ( String ) args [ ] ; String signature = ( String ) args [ ] ; String [ ] parms = signature . split ( "" ) ; IMethod candidate = type . getMethod ( name , parms ) ; if ( candidate . exists ( ) ) { if ( args . length > ) { String modifierText = ( String ) args [ ] ; String [ ] modifiers = modifierText . split ( "" ) ; for ( int j = ; j < modifiers . length ; j ++ ) { String modifier = modifiers [ j ] ; if ( modifier . equals ( "" ) && ! candidate . isPublic ( ) ) return false ; else if ( modifier . equals ( "" ) && ! candidate . isPrivate ( ) ) return false ; else if ( modifier . equals ( "" ) && ! candidate . isProtected ( ) ) return false ; else if ( modifier . equals ( "" ) && ! candidate . isSingleton ( ) ) return false ; } return true ; } } } } } catch ( RubyModelException e ) { } return false ; } private boolean hasSuperclass ( IRubyElement element , String qname ) { try { IType type = getType ( element ) ; if ( type != null ) { IType [ ] stypes = type . newSupertypeHierarchy ( new NullProgressMonitor ( ) ) . getAllSuperclasses ( type ) ; for ( int i = ; i < stypes . length ; i ++ ) { if ( stypes [ i ] . getFullyQualifiedName ( ) . equals ( qname ) || stypes [ i ] . getElementName ( ) . equals ( qname ) ) { return true ; } } } } catch ( RubyModelException e ) { } return false ; } private boolean hasProjectNature ( IRubyElement element , String ntype ) { if ( element != null ) { IResource resource = element . getResource ( ) ; if ( resource == null ) { resource = element . getRubyProject ( ) . getProject ( ) ; } if ( resource != null ) { return hasProjectNature ( resource , ntype ) ; } } return false ; } private IType getType ( IRubyElement element ) throws RubyModelException { IType type = null ; if ( element instanceof IRubyScript ) { type = ( ( IRubyScript ) element ) . findPrimaryType ( ) ; } else if ( element instanceof IType ) { type = ( IType ) element ; } else if ( element instanceof IMember ) { type = ( ( IMember ) element ) . getDeclaringType ( ) ; } return type ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . variables . VariablesPlugin ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntryResolver ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . RubyRuntime ; public class VariableLoadpathResolver implements IRuntimeLoadpathEntryResolver { public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , ILaunchConfiguration configuration ) throws CoreException { return resolveRuntimeLoadpathEntry ( entry ) ; } public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , IRubyProject project ) throws CoreException { return resolveRuntimeLoadpathEntry ( entry ) ; } private IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry ) throws CoreException { String variableString = ( ( VariableLoadpathEntry ) entry ) . getVariableString ( ) ; String strpath = VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) . performStringSubstitution ( variableString ) ; IPath path = new Path ( strpath ) . makeAbsolute ( ) ; IRuntimeLoadpathEntry archiveEntry = RubyRuntime . newArchiveRuntimeLoadpathEntry ( path ) ; return new IRuntimeLoadpathEntry [ ] { archiveEntry } ; } public IVMInstall resolveVMInstall ( ILoadpathEntry entry ) throws CoreException { return null ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . runtime . Platform ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IInputValidator ; import org . eclipse . jface . resource . StringConverter ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Text ; public class PasswordDialog extends Dialog { private String title ; private String message ; private String value = "" ; private IInputValidator validator ; private Button okButton ; private Text text ; private Text errorMessageText ; private String errorMessage ; public PasswordDialog ( Shell parentShell , String dialogTitle , String dialogMessage , String initialValue , IInputValidator validator ) { super ( parentShell ) ; setShellStyle ( getShellStyle ( ) | SWT . ON_TOP ) ; this . title = dialogTitle ; message = dialogMessage ; if ( initialValue == null ) { value = "" ; } else { value = initialValue ; } this . validator = validator ; } protected void buttonPressed ( int buttonId ) { if ( buttonId == IDialogConstants . OK_ID ) { value = text . getText ( ) ; } else { value = null ; } super . buttonPressed ( buttonId ) ; } protected void configureShell ( Shell shell ) { super . configureShell ( shell ) ; if ( title != null ) { shell . setText ( title ) ; } } protected void createButtonsForButtonBar ( Composite parent ) { okButton = createButton ( parent , IDialogConstants . OK_ID , IDialogConstants . OK_LABEL , true ) ; createButton ( parent , IDialogConstants . CANCEL_ID , IDialogConstants . CANCEL_LABEL , false ) ; text . setFocus ( ) ; if ( value != null ) { text . setText ( value ) ; text . selectAll ( ) ; } } protected Control createDialogArea ( Composite parent ) { Composite composite = ( Composite ) super . createDialogArea ( parent ) ; if ( message != null ) { Label label = new Label ( composite , SWT . WRAP ) ; label . setText ( message ) ; GridData data = new GridData ( GridData . GRAB_HORIZONTAL | GridData . GRAB_VERTICAL | GridData . HORIZONTAL_ALIGN_FILL | GridData . VERTICAL_ALIGN_CENTER ) ; data . widthHint = convertHorizontalDLUsToPixels ( IDialogConstants . MINIMUM_MESSAGE_AREA_WIDTH ) ; label . setLayoutData ( data ) ; label . setFont ( parent . getFont ( ) ) ; } text = new Text ( composite , SWT . SINGLE | SWT . BORDER ) ; text . setLayoutData ( new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL ) ) ; text . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { validateInput ( ) ; } } ) ; char cbit = '' ; if ( Platform . OS_MACOSX . equals ( Platform . getOS ( ) ) ) { cbit = ( char ) ( ( '' << ) + '' ) ; } text . setEchoChar ( cbit ) ; errorMessageText = new Text ( composite , SWT . READ_ONLY | SWT . WRAP ) ; errorMessageText . setLayoutData ( new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL ) ) ; errorMessageText . setBackground ( errorMessageText . getDisplay ( ) . getSystemColor ( SWT . COLOR_WIDGET_BACKGROUND ) ) ; setErrorMessage ( errorMessage ) ; applyDialogFont ( composite ) ; return composite ; } protected Label getErrorMessageLabel ( ) { return null ; } protected Button getOkButton ( ) { return okButton ; } protected Text getText ( ) { return text ; } protected IInputValidator getValidator ( ) { return validator ; } public String getValue ( ) { return value ; } protected void validateInput ( ) { String errorMessage = null ; if ( validator != null ) { errorMessage = validator . isValid ( text . getText ( ) ) ; } setErrorMessage ( errorMessage ) ; } public void setErrorMessage ( String errorMessage ) { this . errorMessage = errorMessage ; if ( errorMessageText != null && ! errorMessageText . isDisposed ( ) ) { errorMessageText . setText ( errorMessage == null ? "" : errorMessage ) ; boolean hasError = errorMessage != null && ( StringConverter . removeWhiteSpaces ( errorMessage ) ) . length ( ) > ; errorMessageText . setEnabled ( hasError ) ; errorMessageText . setVisible ( hasError ) ; errorMessageText . getParent ( ) . update ( ) ; Control button = getButton ( IDialogConstants . OK_ID ) ; if ( button != null ) { button . setEnabled ( errorMessage == null ) ; } } } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; public class VariableLoadpathEntry extends AbstractRuntimeLoadpathEntry { public static final String TYPE_ID = "" ; private String variableString ; public VariableLoadpathEntry ( ) { } public VariableLoadpathEntry ( String variableString ) { this . variableString = variableString ; } protected void buildMemento ( Document document , Element memento ) throws CoreException { memento . setAttribute ( "" , variableString ) ; } public void initializeFrom ( Element memento ) throws CoreException { variableString = memento . getAttribute ( "" ) ; } public String getTypeId ( ) { return TYPE_ID ; } public IRuntimeLoadpathEntry [ ] getRuntimeLoadpathEntries ( ILaunchConfiguration configuration ) throws CoreException { return new IRuntimeLoadpathEntry [ ] ; } public String getName ( ) { return variableString ; } public int getType ( ) { return OTHER ; } public String getVariableString ( ) { return variableString ; } public void setVariableString ( String variableString ) { this . variableString = variableString ; } public int hashCode ( ) { if ( variableString != null ) return variableString . hashCode ( ) ; return ; } public boolean equals ( Object obj ) { if ( obj instanceof VariableLoadpathEntry ) { VariableLoadpathEntry other = ( VariableLoadpathEntry ) obj ; if ( variableString != null ) { return variableString . equals ( other . variableString ) ; } } return false ; } } package org . rubypeople . rdt . internal . launching ; import java . util . ArrayList ; import java . util . List ; public class CompositeId { private String [ ] fParts ; public CompositeId ( String [ ] parts ) { fParts = parts ; } public static CompositeId fromString ( String idString ) { List < String > parts = new ArrayList < String > ( ) ; int commaIndex = idString . indexOf ( '' ) ; while ( commaIndex > ) { int length = Integer . valueOf ( idString . substring ( , commaIndex ) ) . intValue ( ) ; String part = idString . substring ( commaIndex + , commaIndex + + length ) ; parts . add ( part ) ; idString = idString . substring ( commaIndex + + length ) ; commaIndex = idString . indexOf ( '' ) ; } String [ ] result = ( String [ ] ) parts . toArray ( new String [ parts . size ( ) ] ) ; return new CompositeId ( result ) ; } public String toString ( ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < fParts . length ; i ++ ) { buf . append ( fParts [ i ] . length ( ) ) ; buf . append ( '' ) ; buf . append ( fParts [ i ] ) ; } return buf . toString ( ) ; } public String get ( int index ) { return fParts [ index ] ; } public int getPartCount ( ) { return fParts . length ; } } package org . rubypeople . rdt . internal . launching ; import java . util . ArrayList ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationMigrationDelegate ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class RubyMigrationDelegate implements ILaunchConfigurationMigrationDelegate { protected static final String EMPTY_STRING = "" ; public RubyMigrationDelegate ( ) { } protected IProject [ ] getProjectsForCandidate ( ILaunchConfiguration candidate ) throws CoreException { String pname = candidate . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , EMPTY_STRING ) ; return new IProject [ ] { ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( pname ) } ; } public boolean isCandidate ( ILaunchConfiguration candidate ) throws CoreException { if ( candidate . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , EMPTY_STRING ) . equals ( EMPTY_STRING ) ) { return false ; } IResource [ ] mappedResources = candidate . getMappedResources ( ) ; if ( mappedResources != null && mappedResources . length > ) { return false ; } return true ; } public void migrate ( ILaunchConfiguration candidate ) throws CoreException { IProject [ ] projects = getProjectsForCandidate ( candidate ) ; ArrayList mappings = new ArrayList ( ) ; for ( int i = ; i < projects . length ; i ++ ) { if ( ! mappings . contains ( projects [ i ] ) ) { mappings . add ( projects [ i ] ) ; } } ILaunchConfigurationWorkingCopy wc = candidate . getWorkingCopy ( ) ; wc . setMappedResources ( ( IResource [ ] ) mappings . toArray ( new IResource [ mappings . size ( ) ] ) ) ; wc . doSave ( ) ; } public static void updateResourceMapping ( ILaunchConfigurationWorkingCopy wc ) throws CoreException { IResource resource = getResource ( wc ) ; IResource [ ] resources = null ; if ( resource != null ) { resources = new IResource [ ] { resource } ; } wc . setMappedResources ( resources ) ; } public static IResource getResource ( ILaunchConfiguration candidate ) throws CoreException { IResource resource = null ; String pname = candidate . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , EMPTY_STRING ) ; if ( ! EMPTY_STRING . equals ( pname ) ) { IProject project = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( pname ) ; String tname = candidate . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , EMPTY_STRING ) ; if ( ! EMPTY_STRING . equals ( tname ) ) { if ( project != null && project . exists ( ) && project . isOpen ( ) ) { resource = project . getFile ( tname ) ; } } else { return project ; } if ( resource == null ) { resource = project ; } } return resource ; } } package org . rubypeople . rdt . internal . launching ; public class PreferenceConstants { public final static String USE_RUBY_DEBUG = "" ; public final static String VERBOSE_DEBUGGER = "" ; } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . IOException ; import java . net . URL ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . osgi . service . environment . Constants ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . launching . AbstractVMInstallType ; import org . rubypeople . rdt . launching . IVMInstall ; public class JRubyVMType extends AbstractVMInstallType { private static Map < String , LibraryInfo > fgFailedInstallPath = new HashMap < String , LibraryInfo > ( ) ; private static final char fgSeparator = File . separatorChar ; private static final String [ ] fgCandidateRubyFiles = { "" , "" , "" , "" } ; private static final String [ ] fgCandidateRubyLocations = { "" , "" + fgSeparator } ; @ Override protected IVMInstall doCreateVMInstall ( String id ) { return new JRubyVM ( this , id ) ; } public File detectInstallLocation ( ) { File rubyExecutable = null ; if ( Platform . getOS ( ) . equals ( Constants . OS_WIN32 ) ) { String winPath = System . getenv ( "" ) ; String [ ] paths = winPath . split ( "" ) ; for ( int i = ; i < paths . length ; i ++ ) { String possibleExecutablePath = paths [ i ] + File . separator + "" ; File possible = new File ( possibleExecutablePath ) ; if ( possible . exists ( ) ) { rubyExecutable = possible ; break ; } } } else { String [ ] cmdLine = new String [ ] { "" , "" } ; rubyExecutable = parseRubyExecutableLocation ( executeAndRead ( cmdLine ) ) ; } File location = tryLocation ( rubyExecutable ) ; if ( location != null ) return location ; return tryIncludedJRuby ( ) ; } private File tryIncludedJRuby ( ) { try { Bundle bundle = Platform . getBundle ( "" ) ; URL url = FileLocator . find ( bundle , new Path ( "" ) , null ) ; url = FileLocator . toFileURL ( url ) ; String fileName = url . getFile ( ) ; String executable = fileName + "" + File . separator + "" ; if ( Platform . getOS ( ) . equals ( Constants . OS_WIN32 ) ) { executable += "" ; } return tryLocation ( new File ( executable ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return null ; } private File tryLocation ( File rubyExecutable ) { if ( rubyExecutable == null ) { return null ; } File bin = rubyExecutable . getParentFile ( ) ; if ( ! bin . exists ( ) ) return null ; File rubyHome = bin . getParentFile ( ) ; if ( ! rubyHome . exists ( ) ) return null ; if ( ! canDetectDefaultSystemLibraries ( rubyHome , rubyExecutable ) ) { return null ; } return rubyHome ; } public IPath [ ] getDefaultLibraryLocations ( File installLocation ) { File rubyExecutable = findRubyExecutable ( installLocation ) ; LibraryInfo info ; if ( rubyExecutable == null ) { info = getDefaultLibraryInfo ( installLocation ) ; } else { info = getLibraryInfo ( installLocation , rubyExecutable ) ; } String [ ] loadpath = info . getBootpath ( ) ; IPath [ ] paths = new IPath [ loadpath . length ] ; for ( int i = ; i < loadpath . length ; i ++ ) { paths [ i ] = new Path ( loadpath [ i ] ) ; } return paths ; } public String getName ( ) { return "" ; } public IStatus validateInstallLocation ( File rubyHome ) { IStatus status = null ; File rubyExecutable = findRubyExecutable ( rubyHome ) ; if ( rubyExecutable == null ) { status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_Not_a_JDK_Root__Java_executable_was_not_found_1 , null ) ; } else { if ( canDetectDefaultSystemLibraries ( rubyHome , rubyExecutable ) ) { status = new Status ( IStatus . OK , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_ok_2 , null ) ; } else { status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_Not_a_JDK_root__System_library_was_not_found__1 , null ) ; } } return status ; } public static File findRubyExecutable ( File vmInstallLocation ) { for ( int i = ; i < fgCandidateRubyFiles . length ; i ++ ) { for ( int j = ; j < fgCandidateRubyLocations . length ; j ++ ) { File rubyFile = new File ( vmInstallLocation , fgCandidateRubyLocations [ j ] + fgCandidateRubyFiles [ i ] ) ; if ( rubyFile . isFile ( ) && isPlatformProper ( rubyFile ) ) { return rubyFile ; } } } return null ; } private static boolean isPlatformProper ( File rubyFile ) { if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) { return rubyFile . getName ( ) . endsWith ( "" ) ; } else { return ! rubyFile . getName ( ) . endsWith ( "" ) ; } } protected boolean canDetectDefaultSystemLibraries ( File rubyHome , File rubyExecutable ) { IPath [ ] locations = getDefaultLibraryLocations ( rubyHome ) ; return locations . length > ; } protected LibraryInfo getDefaultLibraryInfo ( File installLocation ) { IPath [ ] dflts = getDefaultSystemLibrary ( installLocation ) ; String [ ] strings = new String [ dflts . length ] ; for ( int i = ; i < dflts . length ; i ++ ) { strings [ i ] = dflts [ i ] . toOSString ( ) ; } return new LibraryInfo ( "" , strings ) ; } protected IPath [ ] getDefaultSystemLibrary ( File rubyHome ) { String stdPath = rubyHome . getAbsolutePath ( ) + fgSeparator + "" + fgSeparator + "" + fgSeparator + "" ; String sitePath = rubyHome . getAbsolutePath ( ) + fgSeparator + "" + fgSeparator + "" + fgSeparator + "" + fgSeparator + "" ; IPath [ ] paths = new IPath [ ] ; paths [ ] = new Path ( sitePath ) ; paths [ ] = new Path ( stdPath ) ; return paths ; } protected synchronized LibraryInfo getLibraryInfo ( File rubyHome , File rubyExecutable ) { String installPath = rubyHome . getAbsolutePath ( ) ; LibraryInfo info = LaunchingPlugin . getLibraryInfo ( this , installPath ) ; if ( info == null ) { info = fgFailedInstallPath . get ( installPath ) ; if ( info == null ) { info = generateLibraryInfo ( rubyHome , rubyExecutable ) ; if ( info == null ) { info = getDefaultLibraryInfo ( rubyHome ) ; fgFailedInstallPath . put ( installPath , info ) ; } else { LaunchingPlugin . setLibraryInfo ( this , installPath , info ) ; } } } return info ; } public File findExecutable ( File installLocation ) { return findRubyExecutable ( installLocation ) ; } public String getVMPlatform ( File installLocation , File executable ) { return "" ; } } package org . rubypeople . rdt . internal . launching ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . TransformerException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; import org . xml . sax . helpers . DefaultHandler ; public class VMDefinitionsContainer { private Map < IVMInstallType , List < IVMInstall > > fVMTypeToVMMap ; private List < IVMInstall > fVMList ; private List < IVMInstall > fInvalidVMList ; private String fDefaultVMInstallCompositeID ; public VMDefinitionsContainer ( ) { fVMTypeToVMMap = new HashMap < IVMInstallType , List < IVMInstall > > ( ) ; fInvalidVMList = new ArrayList < IVMInstall > ( ) ; fVMList = new ArrayList < IVMInstall > ( ) ; } public void addVM ( IVMInstall vm ) { if ( ! fVMList . contains ( vm ) ) { IVMInstallType vmInstallType = vm . getVMInstallType ( ) ; List < IVMInstall > vmList = fVMTypeToVMMap . get ( vmInstallType ) ; if ( vmList == null ) { vmList = new ArrayList < IVMInstall > ( ) ; fVMTypeToVMMap . put ( vmInstallType , vmList ) ; } vmList . add ( vm ) ; File installLocation = vm . getInstallLocation ( ) ; if ( installLocation == null || ! vmInstallType . validateInstallLocation ( installLocation ) . isOK ( ) ) { fInvalidVMList . add ( vm ) ; } fVMList . add ( vm ) ; } } public void addVMList ( List vmList ) { Iterator iterator = vmList . iterator ( ) ; while ( iterator . hasNext ( ) ) { IVMInstall vm = ( IVMInstall ) iterator . next ( ) ; addVM ( vm ) ; } } public Map getVMTypeToVMMap ( ) { return fVMTypeToVMMap ; } public List < IVMInstall > getVMList ( ) { return fVMList ; } public List < IVMInstall > getValidVMList ( ) { List < IVMInstall > vms = getVMList ( ) ; List < IVMInstall > resultList = new ArrayList < IVMInstall > ( vms . size ( ) ) ; resultList . addAll ( vms ) ; resultList . removeAll ( fInvalidVMList ) ; return resultList ; } public String getDefaultVMInstallCompositeID ( ) { return fDefaultVMInstallCompositeID ; } public void setDefaultVMInstallCompositeID ( String id ) { fDefaultVMInstallCompositeID = id ; } public String getAsXML ( ) throws ParserConfigurationException , IOException , TransformerException { Document doc = LaunchingPlugin . getDocument ( ) ; Element config = doc . createElement ( "" ) ; doc . appendChild ( config ) ; if ( getDefaultVMInstallCompositeID ( ) != null ) { config . setAttribute ( "" , getDefaultVMInstallCompositeID ( ) ) ; } Set vmInstallTypeSet = getVMTypeToVMMap ( ) . keySet ( ) ; Iterator keyIterator = vmInstallTypeSet . iterator ( ) ; while ( keyIterator . hasNext ( ) ) { IVMInstallType vmInstallType = ( IVMInstallType ) keyIterator . next ( ) ; Element vmTypeElement = vmTypeAsElement ( doc , vmInstallType ) ; config . appendChild ( vmTypeElement ) ; } return LaunchingPlugin . serializeDocument ( doc ) ; } private Element vmTypeAsElement ( Document doc , IVMInstallType vmType ) { Element element = doc . createElement ( "" ) ; element . setAttribute ( "" , vmType . getId ( ) ) ; List vmList = ( List ) getVMTypeToVMMap ( ) . get ( vmType ) ; Iterator vmIterator = vmList . iterator ( ) ; while ( vmIterator . hasNext ( ) ) { IVMInstall vm = ( IVMInstall ) vmIterator . next ( ) ; Element vmElement = vmAsElement ( doc , vm ) ; element . appendChild ( vmElement ) ; } return element ; } private Element vmAsElement ( Document doc , IVMInstall vm ) { Element element = doc . createElement ( "" ) ; element . setAttribute ( "" , vm . getId ( ) ) ; element . setAttribute ( "" , vm . getName ( ) ) ; String installPath = "" ; File installLocation = vm . getInstallLocation ( ) ; if ( installLocation != null ) { installPath = installLocation . getAbsolutePath ( ) ; } element . setAttribute ( "" , installPath ) ; IPath [ ] libraryLocations = vm . getLibraryLocations ( ) ; if ( libraryLocations != null ) { Element libLocationElement = libraryLocationsAsElement ( doc , libraryLocations ) ; element . appendChild ( libLocationElement ) ; } String vmArgs = vm . getVMArgs ( ) ; if ( vmArgs != null && vmArgs . length ( ) > ) { element . setAttribute ( "" , vmArgs ) ; } return element ; } private static Element libraryLocationsAsElement ( Document doc , IPath [ ] locations ) { Element root = doc . createElement ( "" ) ; for ( int i = ; i < locations . length ; i ++ ) { Element element = doc . createElement ( "" ) ; element . setAttribute ( "" , locations [ i ] . toString ( ) ) ; root . appendChild ( element ) ; } return root ; } public static VMDefinitionsContainer parseXMLIntoContainer ( InputStream inputStream ) throws IOException { VMDefinitionsContainer container = new VMDefinitionsContainer ( ) ; parseXMLIntoContainer ( inputStream , container ) ; return container ; } public static void parseXMLIntoContainer ( InputStream inputStream , VMDefinitionsContainer container ) throws IOException { InputStream stream = new BufferedInputStream ( inputStream ) ; Element config = null ; try { DocumentBuilder parser = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; parser . setErrorHandler ( new DefaultHandler ( ) ) ; config = parser . parse ( new InputSource ( stream ) ) . getDocumentElement ( ) ; } catch ( SAXException e ) { throw new IOException ( LaunchingMessages . RubyRuntime_badFormat ) ; } catch ( ParserConfigurationException e ) { stream . close ( ) ; throw new IOException ( LaunchingMessages . RubyRuntime_badFormat ) ; } finally { stream . close ( ) ; } String nodeName = config . getNodeName ( ) ; if ( nodeName . equalsIgnoreCase ( "" ) ) { importLegacyInterpreters ( config , container ) ; return ; } else if ( ! config . getNodeName ( ) . equalsIgnoreCase ( "" ) ) { throw new IOException ( LaunchingMessages . RubyRuntime_badFormat ) ; } container . setDefaultVMInstallCompositeID ( config . getAttribute ( "" ) ) ; NodeList list = config . getChildNodes ( ) ; int length = list . getLength ( ) ; for ( int i = ; i < length ; ++ i ) { Node node = list . item ( i ) ; short type = node . getNodeType ( ) ; if ( type == Node . ELEMENT_NODE ) { Element vmTypeElement = ( Element ) node ; if ( vmTypeElement . getNodeName ( ) . equalsIgnoreCase ( "" ) ) { populateVMTypes ( vmTypeElement , container ) ; } } } } private static void populateVMTypes ( Element vmTypeElement , VMDefinitionsContainer container ) { String id = vmTypeElement . getAttribute ( "" ) ; IVMInstallType vmType = RubyRuntime . getVMInstallType ( id ) ; if ( vmType != null ) { NodeList vmNodeList = vmTypeElement . getChildNodes ( ) ; for ( int i = ; i < vmNodeList . getLength ( ) ; ++ i ) { Node vmNode = vmNodeList . item ( i ) ; short type = vmNode . getNodeType ( ) ; if ( type == Node . ELEMENT_NODE ) { Element vmElement = ( Element ) vmNode ; if ( vmElement . getNodeName ( ) . equalsIgnoreCase ( "" ) ) { populateVMForType ( vmType , vmElement , container ) ; } } } } else { LaunchingPlugin . log ( LaunchingMessages . RubyRuntime_VM_type_element_with_unknown_id_1 ) ; } } private static void populateVMForType ( IVMInstallType vmType , Element vmElement , VMDefinitionsContainer container ) { String id = vmElement . getAttribute ( "" ) ; if ( id != null ) { String installPath = vmElement . getAttribute ( "" ) ; if ( installPath == null ) { return ; } VMStandin vmStandin = new VMStandin ( vmType , id ) ; vmStandin . setName ( vmElement . getAttribute ( "" ) ) ; File installLocation = new File ( installPath ) ; vmStandin . setInstallLocation ( installLocation ) ; container . addVM ( vmStandin ) ; NodeList list = vmElement . getChildNodes ( ) ; int length = list . getLength ( ) ; for ( int i = ; i < length ; ++ i ) { Node node = list . item ( i ) ; short type = node . getNodeType ( ) ; if ( type == Node . ELEMENT_NODE ) { Element subElement = ( Element ) node ; String subElementName = subElement . getNodeName ( ) ; if ( subElementName . equals ( "" ) ) { IPath loc = getLibraryLocation ( subElement ) ; vmStandin . setLibraryLocations ( new IPath [ ] { loc } ) ; break ; } else if ( subElementName . equals ( "" ) ) { setLibraryLocations ( vmStandin , subElement ) ; break ; } } } String vmArgs = vmElement . getAttribute ( "" ) ; if ( vmArgs != null && vmArgs . length ( ) > ) { vmStandin . setVMArgs ( vmArgs ) ; } } else { LaunchingPlugin . log ( LaunchingMessages . RubyRuntime_VM_element_specified_with_no_id_attribute_2 ) ; } } private static IPath getLibraryLocation ( Element libLocationElement ) { String src = libLocationElement . getAttribute ( "" ) ; return new Path ( src ) ; } private static void setLibraryLocations ( IVMInstall vm , Element libLocationsElement ) { NodeList list = libLocationsElement . getChildNodes ( ) ; int length = list . getLength ( ) ; List < IPath > locations = new ArrayList < IPath > ( length ) ; for ( int i = ; i < length ; ++ i ) { Node node = list . item ( i ) ; short type = node . getNodeType ( ) ; if ( type == Node . ELEMENT_NODE ) { Element libraryLocationElement = ( Element ) node ; if ( libraryLocationElement . getNodeName ( ) . equals ( "" ) ) { locations . add ( getLibraryLocation ( libraryLocationElement ) ) ; } } } vm . setLibraryLocations ( locations . toArray ( new IPath [ locations . size ( ) ] ) ) ; } private static void importLegacyInterpreters ( Element config , VMDefinitionsContainer container ) { IVMInstallType vmType = RubyRuntime . getVMInstallType ( "" ) ; NodeList list = config . getChildNodes ( ) ; int length = list . getLength ( ) ; for ( int i = ; i < length ; ++ i ) { Node node = list . item ( i ) ; short type = node . getNodeType ( ) ; if ( type == Node . ELEMENT_NODE ) { Element vmElement = ( Element ) node ; if ( vmElement . getNodeName ( ) . equalsIgnoreCase ( "" ) ) { legacyPopulateVMForType ( vmType , vmElement , container ) ; } } } } private static void legacyPopulateVMForType ( IVMInstallType vmType , Element vmElement , VMDefinitionsContainer container ) { String id = vmElement . getAttribute ( "" ) ; if ( id != null ) { String installPath = vmElement . getAttribute ( "" ) ; if ( installPath == null ) { return ; } VMStandin vmStandin = new VMStandin ( vmType , id ) ; vmStandin . setName ( id ) ; File installLocation = new File ( installPath ) ; if ( installLocation . isFile ( ) ) { installLocation = installLocation . getParentFile ( ) ; if ( installLocation != null && installLocation . getParentFile ( ) != null ) { installLocation = installLocation . getParentFile ( ) ; } } if ( installLocation == null ) return ; vmStandin . setInstallLocation ( installLocation ) ; container . addVM ( vmStandin ) ; } else { LaunchingPlugin . log ( LaunchingMessages . RubyRuntime_VM_element_specified_with_no_id_attribute_2 ) ; } } public void removeVM ( IVMInstall vm ) { fVMList . remove ( vm ) ; fInvalidVMList . remove ( vm ) ; List list = fVMTypeToVMMap . get ( vm . getVMInstallType ( ) ) ; if ( list != null ) { list . remove ( vm ) ; } } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . FilenameFilter ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . IStatusHandler ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMRunner ; import org . rubypeople . rdt . launching . VMRunnerConfiguration ; public class JRubyVMRunner extends StandardVMRunner implements IVMRunner { private static final String GEM_MEMORY_HACK = "" ; @ Override protected String [ ] combineVmArgs ( VMRunnerConfiguration configuration , IVMInstall vmInstall ) { String [ ] result = tryGemMemoryHack ( configuration , super . combineVmArgs ( configuration , vmInstall ) ) ; result = tryRailsRubyPlatformHack ( configuration , result ) ; return result ; } private String [ ] tryRailsRubyPlatformHack ( VMRunnerConfiguration configuration , String [ ] old ) { if ( ! isWindows ( ) ) return old ; String file = configuration . getFileToLaunch ( ) ; if ( file . endsWith ( "" ) ) { if ( old . length == ) { return new String [ ] { "" , "" , "" , "" } ; } String newArray [ ] = new String [ old . length + ] ; System . arraycopy ( old , , newArray , , old . length ) ; newArray [ old . length - ] = "" ; newArray [ old . length - ] = "" ; newArray [ old . length ] = "" ; newArray [ old . length + ] = "" ; return newArray ; } if ( ! ( file . endsWith ( "" ) || file . endsWith ( "" ) || file . endsWith ( "" ) || file . endsWith ( "" ) || file . endsWith ( "" ) ) ) return old ; String newArray [ ] = new String [ old . length + ] ; System . arraycopy ( old , , newArray , , old . length ) ; newArray [ old . length ] = "" ; newArray [ old . length + ] = "" ; newArray [ old . length + ] = "" ; newArray [ old . length + ] = "" ; return newArray ; } private String [ ] tryGemMemoryHack ( VMRunnerConfiguration configuration , String [ ] old ) { if ( isWindows ( ) ) return old ; String file = configuration . getFileToLaunch ( ) ; if ( ! file . endsWith ( "" ) ) return old ; String newArray [ ] = new String [ old . length + ] ; System . arraycopy ( old , , newArray , , old . length ) ; newArray [ ] = GEM_MEMORY_HACK ; return newArray ; } @ Override protected String getCommand ( VMRunnerConfiguration config ) { String command = super . getCommand ( config ) ; if ( command == null ) return null ; if ( command . equals ( "" ) || command . equals ( "" ) || command . equals ( "" ) ) return "" + command ; return command ; } protected List < String > constructProgramString ( VMRunnerConfiguration config , IProgressMonitor monitor ) throws CoreException { if ( ! isWindows ( ) ) { String installLocation = fVMInstance . getInstallLocation ( ) . getAbsolutePath ( ) ; File exe = new File ( installLocation + File . separatorChar + "" + File . separatorChar + "" ) ; if ( fileExists ( exe ) ) { try { Process p = setExecutableBit ( exe . getAbsolutePath ( ) ) ; p . waitFor ( ) ; } catch ( InterruptedException e ) { LaunchingPlugin . log ( e ) ; } } try { String link = installLocation + File . separator + "" + File . separator + "" ; File linkFile = new File ( link ) ; if ( ! linkFile . exists ( ) ) { Bundle bundle = Platform . getBundle ( "" ) ; if ( bundle != null ) { URL url = FileLocator . find ( bundle , new Path ( "" ) , null ) ; url = FileLocator . toFileURL ( url ) ; String path = url . getFile ( ) ; File file = new File ( path ) ; Process p = createSymbolicLink ( file . getAbsolutePath ( ) , link ) ; p . waitFor ( ) ; } } } catch ( Exception e ) { LaunchingPlugin . log ( e ) ; } return super . constructProgramString ( config , monitor ) ; } List < String > string = new ArrayList < String > ( ) ; string . add ( "" ) ; String installLocation = fVMInstance . getInstallLocation ( ) . getAbsolutePath ( ) ; File exe = new File ( installLocation + File . separatorChar + "" + File . separatorChar + "" ) ; if ( fileExists ( exe ) ) { File lib = new File ( fVMInstance . getInstallLocation ( ) , "" ) ; String [ ] jars = lib . list ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( "" ) ; } } ) ; String jarString = "" ; for ( int i = ; i < jars . length ; i ++ ) { if ( i != ) jarString += File . pathSeparator ; jarString += lib . getAbsolutePath ( ) + File . separator + jars [ i ] ; } try { Bundle bundle = Platform . getBundle ( "" ) ; if ( bundle != null ) { URL url = FileLocator . find ( bundle , new Path ( "" ) , null ) ; url = FileLocator . toFileURL ( url ) ; String path = url . getFile ( ) ; File file = new File ( path . substring ( ) ) ; jarString += File . pathSeparator + file . getAbsolutePath ( ) ; } } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } string . add ( "" ) ; if ( config . getFileToLaunch ( ) . endsWith ( "" ) ) { string . add ( "" ) ; } else { string . add ( "" ) ; } string . add ( "" ) ; string . add ( "" ) ; string . add ( "" + jarString + "" ) ; string . add ( "" + installLocation + "" ) ; string . add ( "" + installLocation + "" ) ; string . add ( "" + lib . getAbsolutePath ( ) + "" ) ; if ( isWindows ( ) ) string . add ( "" ) ; else string . add ( "" ) ; string . add ( "" + exe . getName ( ) + "" ) ; string . add ( "" ) ; return string ; } abort ( MessageFormat . format ( LaunchingMessages . StandardVMRunner_Specified_executable__0__does_not_exist_for__1__4 , "" , fVMInstance . getName ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR ) ; return null ; } private boolean isWindows ( ) { return Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ; } @ Override protected String [ ] getEnvironment ( VMRunnerConfiguration config ) { String [ ] env = super . getEnvironment ( config ) ; if ( env == null ) env = new String [ ] ; int itemsToAdd = ; if ( isWindows ( ) ) itemsToAdd ++ ; String [ ] special = new String [ env . length + itemsToAdd ] ; System . arraycopy ( env , , special , , env . length ) ; special [ env . length + ] = "" ; special [ env . length + ] = "" + fVMInstance . getInstallLocation ( ) . getAbsolutePath ( ) ; special [ env . length + ] = "" + fVMInstance . getInstallLocation ( ) . getAbsolutePath ( ) ; special [ env . length + ] = "" + System . getProperty ( "" ) ; String root = System . getenv ( "" ) ; if ( root == null || root . trim ( ) . length ( ) == ) { root = "" ; } if ( isWindows ( ) ) special [ env . length + ] = "" + root ; return special ; } @ Override protected void addStreamSync ( List < String > arguments ) { } protected Process exec ( String [ ] cmdLine , File workingDirectory , String [ ] envp ) throws CoreException { String cmd = getCmdLineAsString ( cmdLine ) ; LaunchingPlugin . info ( "" + cmd ) ; Process p = null ; try { if ( isWindows ( ) ) { if ( workingDirectory == null ) { p = Runtime . getRuntime ( ) . exec ( cmd , envp ) ; } else { p = Runtime . getRuntime ( ) . exec ( cmd , envp , workingDirectory ) ; } } else { if ( workingDirectory == null ) { p = Runtime . getRuntime ( ) . exec ( cmdLine , envp ) ; } else { p = Runtime . getRuntime ( ) . exec ( cmdLine , envp , workingDirectory ) ; } } } catch ( IOException e ) { Status status = new Status ( IStatus . ERROR , DebugPlugin . getUniqueIdentifier ( ) , DebugPlugin . INTERNAL_ERROR , LaunchingMessages . DebugPlugin_Exception_occurred_executing_command_line__1 , e ) ; throw new CoreException ( status ) ; } catch ( NoSuchMethodError e ) { IStatus status = new Status ( IStatus . ERROR , DebugPlugin . getUniqueIdentifier ( ) , DebugPlugin . ERR_WORKING_DIRECTORY_NOT_SUPPORTED , LaunchingMessages . DebugPlugin_Eclipse_runtime_does_not_support_working_directory_2 , e ) ; IStatusHandler handler = DebugPlugin . getDefault ( ) . getStatusHandler ( status ) ; if ( handler != null ) { Object result = handler . handleStatus ( status , null ) ; if ( result instanceof Boolean && ( ( Boolean ) result ) . booleanValue ( ) ) { p = exec ( cmdLine , null ) ; } } } return p ; } private Process setExecutableBit ( String filePath ) { LaunchingPlugin . log ( "" + filePath ) ; if ( filePath == null ) return null ; try { Process pr = Runtime . getRuntime ( ) . exec ( new String [ ] { "" , "" , filePath } ) ; Thread chmodOutput = new StreamConsumer ( pr . getInputStream ( ) ) ; chmodOutput . setName ( "" ) ; chmodOutput . start ( ) ; Thread chmodError = new StreamConsumer ( pr . getErrorStream ( ) ) ; chmodError . setName ( "" ) ; chmodError . start ( ) ; return pr ; } catch ( IOException ioe ) { LaunchingPlugin . log ( ioe ) ; } return null ; } private Process createSymbolicLink ( String target , String linkLocation ) { LaunchingPlugin . log ( "" + linkLocation + "" + target ) ; if ( target == null || linkLocation == null ) return null ; try { Process pr = Runtime . getRuntime ( ) . exec ( new String [ ] { "" , "" , target , linkLocation } ) ; Thread chmodOutput = new StreamConsumer ( pr . getInputStream ( ) ) ; chmodOutput . setName ( "" ) ; chmodOutput . start ( ) ; Thread chmodError = new StreamConsumer ( pr . getErrorStream ( ) ) ; chmodError . setName ( "" ) ; chmodError . start ( ) ; return pr ; } catch ( IOException ioe ) { LaunchingPlugin . log ( ioe ) ; } return null ; } public static class StreamConsumer extends Thread { InputStream is ; byte [ ] buf ; public StreamConsumer ( InputStream inputStream ) { super ( ) ; this . setDaemon ( true ) ; this . is = inputStream ; buf = new byte [ ] ; } public void run ( ) { try { int n = ; while ( n >= ) n = is . read ( buf ) ; } catch ( IOException ioe ) { } } } } package org . rubypeople . rdt . internal . launching ; import java . io . IOException ; import java . text . MessageFormat ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . TransformerException ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; public class RuntimeLoadpathEntry implements IRuntimeLoadpathEntry { private int fType = - ; private int fLoadpathProperty = - ; private ILoadpathEntry fLoadpathEntry = null ; private ILoadpathEntry fResolvedEntry = null ; private IRubyProject fRubyProject = null ; private IPath fInvalidPath ; public RuntimeLoadpathEntry ( ILoadpathEntry entry ) { switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_PROJECT : setType ( PROJECT ) ; break ; case ILoadpathEntry . CPE_LIBRARY : setType ( ARCHIVE ) ; break ; case ILoadpathEntry . CPE_VARIABLE : setType ( VARIABLE ) ; break ; case ILoadpathEntry . CPE_SOURCE : setType ( ARCHIVE ) ; break ; default : throw new IllegalArgumentException ( MessageFormat . format ( LaunchingMessages . RuntimeLoadpathEntry_Illegal_classpath_entry__0__1 , entry . toString ( ) ) ) ; } setLoadpathEntry ( entry ) ; initializeLoadpathProperty ( ) ; } public RuntimeLoadpathEntry ( ILoadpathEntry entry , int classpathProperty ) { switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_CONTAINER : setType ( CONTAINER ) ; break ; default : throw new IllegalArgumentException ( MessageFormat . format ( LaunchingMessages . RuntimeLoadpathEntry_Illegal_classpath_entry__0__1 , entry . toString ( ) ) ) ; } setLoadpathEntry ( entry ) ; setLoadpathProperty ( classpathProperty ) ; } public RuntimeLoadpathEntry ( Element root ) throws CoreException { try { setType ( Integer . parseInt ( root . getAttribute ( "" ) ) ) ; } catch ( NumberFormatException e ) { abort ( LaunchingMessages . RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry_type_2 , e ) ; } try { setLoadpathProperty ( Integer . parseInt ( root . getAttribute ( "" ) ) ) ; } catch ( NumberFormatException e ) { abort ( LaunchingMessages . RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry_location_3 , e ) ; } IPath sourcePath = null ; IPath rootPath = null ; String path = root . getAttribute ( "" ) ; if ( path != null && path . length ( ) > ) { sourcePath = new Path ( path ) ; } path = root . getAttribute ( "" ) ; if ( path != null && path . length ( ) > ) { rootPath = new Path ( path ) ; } switch ( getType ( ) ) { case PROJECT : String name = root . getAttribute ( "" ) ; if ( isEmpty ( name ) ) { abort ( LaunchingMessages . RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry___missing_project_name_4 , null ) ; } else { IProject proj = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( name ) ; setLoadpathEntry ( RubyCore . newProjectEntry ( proj . getFullPath ( ) ) ) ; } break ; case ARCHIVE : path = root . getAttribute ( "" ) ; if ( isEmpty ( path ) ) { path = root . getAttribute ( "" ) ; if ( isEmpty ( path ) ) { abort ( LaunchingMessages . RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry___missing_archive_path_5 , null ) ; } else { setLoadpathEntry ( createLibraryEntry ( sourcePath , rootPath , path ) ) ; } } else { setLoadpathEntry ( createLibraryEntry ( sourcePath , rootPath , path ) ) ; } break ; case VARIABLE : String var = root . getAttribute ( "" ) ; if ( isEmpty ( var ) ) { abort ( LaunchingMessages . RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry___missing_variable_name_6 , null ) ; } else { setLoadpathEntry ( RubyCore . newVariableEntry ( new Path ( var ) ) ) ; } break ; case CONTAINER : var = root . getAttribute ( "" ) ; if ( isEmpty ( var ) ) { abort ( LaunchingMessages . RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry___missing_variable_name_6 , null ) ; } else { setLoadpathEntry ( RubyCore . newContainerEntry ( new Path ( var ) ) ) ; } break ; } String name = root . getAttribute ( "" ) ; if ( isEmpty ( name ) ) { fRubyProject = null ; } else { IProject project2 = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( name ) ; fRubyProject = RubyCore . create ( project2 ) ; } } private ILoadpathEntry createLibraryEntry ( IPath sourcePath , IPath rootPath , String path ) { Path p = new Path ( path ) ; if ( ! p . isAbsolute ( ) ) { fInvalidPath = p ; return null ; } return RubyCore . newLibraryEntry ( p ) ; } protected void abort ( String message , Throwable e ) throws CoreException { IStatus s = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR , message , e ) ; throw new CoreException ( s ) ; } public int getType ( ) { return fType ; } private void setType ( int type ) { fType = type ; } private void setLoadpathEntry ( ILoadpathEntry entry ) { fLoadpathEntry = entry ; fResolvedEntry = null ; } public ILoadpathEntry getLoadpathEntry ( ) { return fLoadpathEntry ; } public String getMemento ( ) throws CoreException { Document doc ; try { doc = LaunchingPlugin . getDocument ( ) ; } catch ( ParserConfigurationException e ) { IStatus status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR , LaunchingMessages . RuntimeLoadpathEntry_An_exception_occurred_generating_runtime_classpath_memento_8 , e ) ; throw new CoreException ( status ) ; } Element node = doc . createElement ( "" ) ; doc . appendChild ( node ) ; node . setAttribute ( "" , ( new Integer ( getType ( ) ) ) . toString ( ) ) ; node . setAttribute ( "" , ( new Integer ( getLoadpathProperty ( ) ) ) . toString ( ) ) ; switch ( getType ( ) ) { case PROJECT : node . setAttribute ( "" , getPath ( ) . lastSegment ( ) ) ; break ; case ARCHIVE : IResource res = getResource ( ) ; if ( res == null ) { node . setAttribute ( "" , getPath ( ) . toString ( ) ) ; } else { node . setAttribute ( "" , res . getFullPath ( ) . toString ( ) ) ; } break ; case VARIABLE : case CONTAINER : node . setAttribute ( "" , getPath ( ) . toString ( ) ) ; break ; } if ( getRubyProject ( ) != null ) { node . setAttribute ( "" , getRubyProject ( ) . getElementName ( ) ) ; } try { return LaunchingPlugin . serializeDocument ( doc ) ; } catch ( IOException e ) { IStatus status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR , LaunchingMessages . RuntimeLoadpathEntry_An_exception_occurred_generating_runtime_classpath_memento_8 , e ) ; throw new CoreException ( status ) ; } catch ( TransformerException e ) { IStatus status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR , LaunchingMessages . RuntimeLoadpathEntry_An_exception_occurred_generating_runtime_classpath_memento_8 , e ) ; throw new CoreException ( status ) ; } } public IPath getPath ( ) { ILoadpathEntry entry = getLoadpathEntry ( ) ; return entry != null ? entry . getPath ( ) : fInvalidPath ; } public IResource getResource ( ) { switch ( getType ( ) ) { case CONTAINER : case VARIABLE : return null ; default : return getResource ( getPath ( ) ) ; } } protected IResource getResource ( IPath path ) { if ( path != null ) { IWorkspaceRoot root = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; if ( path . getDevice ( ) == null ) { return root . findMember ( path ) ; } IFile [ ] files = root . findFilesForLocation ( path ) ; if ( files . length > ) { return files [ ] ; } IContainer [ ] containers = root . findContainersForLocation ( path ) ; if ( containers . length > ) { return containers [ ] ; } } return null ; } private void initializeLoadpathProperty ( ) { switch ( getType ( ) ) { case VARIABLE : if ( getVariableName ( ) . equals ( RubyRuntime . RUBYLIB_VARIABLE ) || getVariableName ( ) . equals ( "" ) ) { setLoadpathProperty ( STANDARD_CLASSES ) ; } else { setLoadpathProperty ( USER_CLASSES ) ; } break ; case PROJECT : setLoadpathProperty ( USER_CLASSES ) ; break ; case ARCHIVE : if ( isGem ( ) ) { setLoadpathProperty ( STANDARD_CLASSES ) ; } else { setLoadpathProperty ( USER_CLASSES ) ; } break ; default : break ; } } private boolean isGem ( ) { String [ ] segments = fLoadpathEntry . getPath ( ) . segments ( ) ; if ( segments == null ) return false ; for ( int i = ; i < segments . length ; i ++ ) { if ( segments [ i ] . equals ( "" ) ) return true ; } return false ; } public void setLoadpathProperty ( int location ) { fLoadpathProperty = location ; } public int getLoadpathProperty ( ) { return fLoadpathProperty ; } public String getLocation ( ) { IPath path = null ; switch ( getType ( ) ) { case PROJECT : IRubyProject pro = ( IRubyProject ) RubyCore . create ( getResource ( ) ) ; if ( pro != null ) { path = pro . getPath ( ) ; } break ; case ARCHIVE : path = getPath ( ) ; break ; case VARIABLE : ILoadpathEntry resolved = getResolvedLoadpathEntry ( ) ; if ( resolved != null ) { path = resolved . getPath ( ) ; } break ; case CONTAINER : break ; } return resolveToOSPath ( path ) ; } protected String resolveToOSPath ( IPath path ) { if ( path != null ) { IResource res = null ; if ( path . getDevice ( ) == null ) { res = getResource ( path ) ; } if ( res == null ) { return path . toOSString ( ) ; } IPath location = res . getLocation ( ) ; if ( location != null ) { return location . toOSString ( ) ; } } return null ; } public String getVariableName ( ) { if ( getType ( ) == IRuntimeLoadpathEntry . VARIABLE || getType ( ) == IRuntimeLoadpathEntry . CONTAINER ) { return getPath ( ) . segment ( ) ; } return null ; } public boolean equals ( Object obj ) { if ( obj instanceof IRuntimeLoadpathEntry ) { IRuntimeLoadpathEntry r = ( IRuntimeLoadpathEntry ) obj ; if ( getType ( ) == r . getType ( ) && getLoadpathProperty ( ) == r . getLoadpathProperty ( ) ) { if ( getType ( ) == IRuntimeLoadpathEntry . CONTAINER ) { String id = getPath ( ) . segment ( ) ; LoadpathContainerInitializer initializer = RubyCore . getLoadpathContainerInitializer ( id ) ; IRubyProject javaProject1 = getRubyProject ( ) ; IRubyProject javaProject2 = r . getRubyProject ( ) ; if ( initializer == null || javaProject1 == null || javaProject2 == null ) { return getPath ( ) . equals ( r . getPath ( ) ) ; } Object comparisonID1 = initializer . getComparisonID ( getPath ( ) , javaProject1 ) ; Object comparisonID2 = initializer . getComparisonID ( r . getPath ( ) , javaProject2 ) ; return comparisonID1 . equals ( comparisonID2 ) ; } else { return getPath ( ) != null && getPath ( ) . equals ( r . getPath ( ) ) ; } } } return false ; } protected boolean equal ( Object one , Object two ) { if ( one == null ) { return two == null ; } return one . equals ( two ) ; } public int hashCode ( ) { if ( getType ( ) == CONTAINER ) { return getPath ( ) . segment ( ) . hashCode ( ) + getType ( ) ; } return getPath ( ) . hashCode ( ) + getType ( ) ; } protected void updateLoadpathEntry ( IPath path , IPath sourcePath , IPath rootPath ) { ILoadpathEntry entry = null ; ILoadpathEntry original = getLoadpathEntry ( ) ; switch ( getType ( ) ) { case ARCHIVE : entry = RubyCore . newLibraryEntry ( path , original . isExported ( ) ) ; break ; case VARIABLE : entry = RubyCore . newVariableEntry ( path ) ; break ; default : return ; } setLoadpathEntry ( entry ) ; } protected ILoadpathEntry getResolvedLoadpathEntry ( ) { if ( fResolvedEntry == null ) { fResolvedEntry = RubyCore . getResolvedLoadpathEntry ( getLoadpathEntry ( ) ) ; } return fResolvedEntry ; } protected boolean isEmpty ( String string ) { return string == null || string . length ( ) == ; } public String toString ( ) { if ( fLoadpathEntry != null ) { return fLoadpathEntry . toString ( ) ; } return super . toString ( ) ; } public IRubyProject getRubyProject ( ) { return fRubyProject ; } public void setRubyProject ( IRubyProject project ) { fRubyProject = project ; } } package org . rubypeople . rdt . internal . launching ; import java . text . MessageFormat ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . model . IDebugTarget ; import org . rubypeople . rdt . launching . AbstractRubyLaunchConfigurationDelegate ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMConnector ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RemoteRubyLaunchConfigurationDelegate extends AbstractRubyLaunchConfigurationDelegate { public void launch ( ILaunchConfiguration configuration , String mode , ILaunch launch , IProgressMonitor monitor ) throws CoreException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( MessageFormat . format ( LaunchingMessages . RubyRemoteApplicationLaunchConfigurationDelegate_Attaching_to__0_____1 , new String [ ] { configuration . getName ( ) } ) , ) ; if ( monitor . isCanceled ( ) ) { return ; } try { monitor . subTask ( LaunchingMessages . RubyRemoteApplicationLaunchConfigurationDelegate_Verifying_launch_attributes____1 ) ; String connectorId = getVMConnectorId ( configuration ) ; IVMConnector connector = null ; if ( connectorId == null ) { connector = RubyRuntime . getDefaultVMConnector ( ) ; } else { connector = RubyRuntime . getVMConnector ( connectorId ) ; } if ( connector == null ) { abort ( LaunchingMessages . RubyRemoteApplicationLaunchConfigurationDelegate_Connector_not_specified_2 , null , IRubyLaunchConfigurationConstants . ERR_CONNECTOR_NOT_AVAILABLE ) ; } Map argMap = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_CONNECT_MAP , ( Map ) null ) ; if ( monitor . isCanceled ( ) ) { return ; } monitor . worked ( ) ; monitor . subTask ( LaunchingMessages . RubyRemoteApplicationLaunchConfigurationDelegate_Creating_source_locator____2 ) ; setDefaultSourceLocator ( launch , configuration ) ; monitor . worked ( ) ; connector . connect ( argMap , monitor , launch ) ; if ( monitor . isCanceled ( ) ) { IDebugTarget [ ] debugTargets = launch . getDebugTargets ( ) ; for ( int i = ; i < debugTargets . length ; i ++ ) { IDebugTarget target = debugTargets [ i ] ; if ( target . canDisconnect ( ) ) { target . disconnect ( ) ; } } return ; } } finally { monitor . done ( ) ; } } } package org . rubypeople . rdt . internal . launching ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . launching . IRuntimeContainerComparator ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; public class DefaultProjectLoadpathEntry extends AbstractRuntimeLoadpathEntry { public static final String TYPE_ID = "" ; private boolean fExportedEntriesOnly = false ; public DefaultProjectLoadpathEntry ( ) { } public DefaultProjectLoadpathEntry ( IRubyProject project ) { setRubyProject ( project ) ; } protected void buildMemento ( Document document , Element memento ) throws CoreException { memento . setAttribute ( "" , getRubyProject ( ) . getElementName ( ) ) ; memento . setAttribute ( "" , Boolean . toString ( fExportedEntriesOnly ) ) ; } public void initializeFrom ( Element memento ) throws CoreException { String name = memento . getAttribute ( "" ) ; if ( name == null ) { abort ( LaunchingMessages . DefaultProjectLoadpathEntry_3 , null ) ; } IRubyProject project = RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( name ) ) ; setRubyProject ( project ) ; name = memento . getAttribute ( "" ) ; if ( name == null ) { fExportedEntriesOnly = false ; } else { fExportedEntriesOnly = Boolean . valueOf ( name ) . booleanValue ( ) ; } } public String getTypeId ( ) { return TYPE_ID ; } public int getType ( ) { return OTHER ; } protected IProject getProject ( ) { return getRubyProject ( ) . getProject ( ) ; } public String getLocation ( ) { return getProject ( ) . getLocation ( ) . toOSString ( ) ; } public IPath getPath ( ) { return getProject ( ) . getFullPath ( ) ; } public IResource getResource ( ) { return getProject ( ) ; } public IRuntimeLoadpathEntry [ ] getRuntimeLoadpathEntries ( ILaunchConfiguration configuration ) throws CoreException { ILoadpathEntry entry = RubyCore . newProjectEntry ( getRubyProject ( ) . getProject ( ) . getFullPath ( ) ) ; List classpathEntries = new ArrayList ( ) ; List < ILoadpathEntry > expanding = new ArrayList < ILoadpathEntry > ( ) ; expandProject ( entry , classpathEntries , expanding ) ; IRuntimeLoadpathEntry [ ] runtimeEntries = new IRuntimeLoadpathEntry [ classpathEntries . size ( ) ] ; for ( int i = ; i < runtimeEntries . length ; i ++ ) { Object e = classpathEntries . get ( i ) ; if ( e instanceof ILoadpathEntry ) { ILoadpathEntry cpe = ( ILoadpathEntry ) e ; runtimeEntries [ i ] = new RuntimeLoadpathEntry ( cpe ) ; } else { runtimeEntries [ i ] = ( IRuntimeLoadpathEntry ) e ; } } List < IRuntimeLoadpathEntry > ordered = new ArrayList < IRuntimeLoadpathEntry > ( runtimeEntries . length ) ; for ( int i = ; i < runtimeEntries . length ; i ++ ) { if ( runtimeEntries [ i ] . getLoadpathProperty ( ) == IRuntimeLoadpathEntry . USER_CLASSES ) { ordered . add ( runtimeEntries [ i ] ) ; } } return ordered . toArray ( new IRuntimeLoadpathEntry [ ordered . size ( ) ] ) ; } private void expandProject ( ILoadpathEntry projectEntry , List expandedPath , List < ILoadpathEntry > expanding ) throws CoreException { expanding . add ( projectEntry ) ; IPath projectPath = projectEntry . getPath ( ) ; IResource res = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( projectPath . lastSegment ( ) ) ; if ( res == null ) { expandedPath . add ( projectEntry ) ; return ; } IRubyProject project = ( IRubyProject ) RubyCore . create ( res ) ; if ( project == null || ! project . getProject ( ) . isOpen ( ) || ! project . exists ( ) ) { expandedPath . add ( projectEntry ) ; return ; } ILoadpathEntry [ ] buildPath = project . getRawLoadpath ( ) ; List unexpandedPath = new ArrayList ( buildPath . length ) ; boolean projectAdded = false ; for ( int i = ; i < buildPath . length ; i ++ ) { ILoadpathEntry classpathEntry = buildPath [ i ] ; if ( classpathEntry . getEntryKind ( ) == ILoadpathEntry . CPE_SOURCE ) { if ( ! projectAdded && classpathEntry . getPath ( ) . equals ( projectEntry . getPath ( ) ) ) { projectAdded = true ; unexpandedPath . add ( projectEntry ) ; continue ; } } if ( classpathEntry . isExported ( ) ) { unexpandedPath . add ( classpathEntry ) ; } else if ( ! isExportedEntriesOnly ( ) || project . equals ( getRubyProject ( ) ) ) { unexpandedPath . add ( classpathEntry ) ; } } Iterator iter = unexpandedPath . iterator ( ) ; while ( iter . hasNext ( ) ) { ILoadpathEntry entry = ( ILoadpathEntry ) iter . next ( ) ; if ( entry == projectEntry ) { expandedPath . add ( entry ) ; } else { switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_PROJECT : if ( ! expanding . contains ( entry ) ) { expandProject ( entry , expandedPath , expanding ) ; } break ; case ILoadpathEntry . CPE_CONTAINER : ILoadpathContainer container = RubyCore . getLoadpathContainer ( entry . getPath ( ) , project ) ; int property = - ; if ( container != null ) { switch ( container . getKind ( ) ) { case ILoadpathContainer . K_APPLICATION : property = IRuntimeLoadpathEntry . USER_CLASSES ; break ; case ILoadpathContainer . K_DEFAULT_SYSTEM : property = IRuntimeLoadpathEntry . STANDARD_CLASSES ; break ; case ILoadpathContainer . K_SYSTEM : property = IRuntimeLoadpathEntry . BOOTSTRAP_CLASSES ; break ; } IRuntimeLoadpathEntry r = RubyRuntime . newRuntimeContainerLoadpathEntry ( entry . getPath ( ) , property , project ) ; boolean duplicate = false ; LoadpathContainerInitializer initializer = RubyCore . getLoadpathContainerInitializer ( r . getPath ( ) . segment ( ) ) ; for ( int i = ; i < expandedPath . size ( ) ; i ++ ) { Object o = expandedPath . get ( i ) ; if ( o instanceof IRuntimeLoadpathEntry ) { IRuntimeLoadpathEntry re = ( IRuntimeLoadpathEntry ) o ; if ( re . getType ( ) == IRuntimeLoadpathEntry . CONTAINER ) { if ( container instanceof IRuntimeContainerComparator ) { duplicate = ( ( IRuntimeContainerComparator ) container ) . isDuplicate ( re . getPath ( ) ) ; } else { LoadpathContainerInitializer initializer2 = RubyCore . getLoadpathContainerInitializer ( re . getPath ( ) . segment ( ) ) ; Object id1 = null ; Object id2 = null ; if ( initializer == null ) { id1 = r . getPath ( ) . segment ( ) ; } else { id1 = initializer . getComparisonID ( r . getPath ( ) , project ) ; } if ( initializer2 == null ) { id2 = re . getPath ( ) . segment ( ) ; } else { IRubyProject context = re . getRubyProject ( ) ; if ( context == null ) { context = project ; } id2 = initializer2 . getComparisonID ( re . getPath ( ) , context ) ; } if ( id1 == null ) { duplicate = id2 == null ; } else { duplicate = id1 . equals ( id2 ) ; } } if ( duplicate ) { break ; } } } } if ( ! duplicate ) { expandedPath . add ( r ) ; } } break ; case ILoadpathEntry . CPE_VARIABLE : if ( entry . getPath ( ) . segment ( ) . equals ( RubyRuntime . RUBYLIB_VARIABLE ) ) { IRuntimeLoadpathEntry r = RubyRuntime . newVariableRuntimeLoadpathEntry ( entry . getPath ( ) ) ; r . setLoadpathProperty ( IRuntimeLoadpathEntry . STANDARD_CLASSES ) ; if ( ! expandedPath . contains ( r ) ) { expandedPath . add ( r ) ; } break ; } default : if ( ! expandedPath . contains ( entry ) ) { expandedPath . add ( entry ) ; } break ; } } } return ; } public boolean isComposite ( ) { return true ; } public String getName ( ) { if ( isExportedEntriesOnly ( ) ) { return MessageFormat . format ( LaunchingMessages . DefaultProjectLoadpathEntry_2 , getRubyProject ( ) . getElementName ( ) ) ; } return MessageFormat . format ( LaunchingMessages . DefaultProjectLoadpathEntry_4 , getRubyProject ( ) . getElementName ( ) ) ; } public boolean equals ( Object obj ) { if ( obj instanceof DefaultProjectLoadpathEntry ) { DefaultProjectLoadpathEntry entry = ( DefaultProjectLoadpathEntry ) obj ; return entry . getRubyProject ( ) . equals ( getRubyProject ( ) ) && entry . isExportedEntriesOnly ( ) == isExportedEntriesOnly ( ) ; } return false ; } public int hashCode ( ) { return getRubyProject ( ) . hashCode ( ) ; } public void setExportedEntriesOnly ( boolean exportedOnly ) { fExportedEntriesOnly = exportedOnly ; } public boolean isExportedEntriesOnly ( ) { return fExportedEntriesOnly ; } } package org . rubypeople . rdt . internal . launching ; public class LibraryInfo { private String fVersion ; private String [ ] fBootpath ; public LibraryInfo ( String version , String [ ] bootpath ) { fVersion = version ; fBootpath = bootpath ; } public String getVersion ( ) { return fVersion ; } public String [ ] getBootpath ( ) { return fBootpath ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . IVMRunner ; public class JRubyVM extends StandardVM { public JRubyVM ( IVMInstallType type , String id ) { super ( type , id ) ; } @ Override public IVMRunner getVMRunner ( String mode ) { IVMRunner runner = null ; if ( ILaunchManager . RUN_MODE . equals ( mode ) ) { runner = new JRubyVMRunner ( ) ; } else if ( ILaunchManager . DEBUG_MODE . equals ( mode ) ) { runner = new JRubyDebugVMDebugger ( ) ; } else if ( ILaunchManager . PROFILE_MODE . equals ( mode ) ) { MessageDialog . openError ( Display . getDefault ( ) . getActiveShell ( ) , "" , "" ) ; return null ; } if ( runner != null ) runner . setVMInstall ( this ) ; return runner ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . IProcess ; import org . rubypeople . rdt . core . SocketUtil ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMRunner ; import org . rubypeople . rdt . launching . VMRunnerConfiguration ; public class JRubyDebugVMDebugger extends JRubyVMRunner implements IVMRunner { private static final String PORT_SWITCH = "" ; private static final String VERBOSE_FLAG = "" ; private static final String RDEBUG_EXECUTABLE = "" ; public void run ( VMRunnerConfiguration config , ILaunch launch , IProgressMonitor monitor ) throws CoreException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } IProgressMonitor subMonitor = new SubProgressMonitor ( monitor , ) ; subMonitor . beginTask ( LaunchingMessages . StandardVMDebugger_Launching_VM____1 , ) ; subMonitor . subTask ( LaunchingMessages . StandardVMDebugger_Finding_free_socket____2 ) ; int port = SocketUtil . findFreePort ( ) ; if ( port == - ) { abort ( LaunchingMessages . StandardVMDebugger_Could_not_find_a_free_socket_for_the_debugger_1 , null , IRubyLaunchConfigurationConstants . ERR_NO_SOCKET_AVAILABLE ) ; } subMonitor . worked ( ) ; if ( monitor . isCanceled ( ) ) { return ; } subMonitor . subTask ( LaunchingMessages . StandardVMDebugger_Constructing_command_line____3 ) ; RubyDebugTarget debugTarget = new RubyDebugTarget ( launch , port ) ; List < String > arguments = constructProgramString ( config , monitor ) ; arguments . addAll ( debugSpecificVMArgs ( debugTarget ) ) ; String [ ] allVMArgs = combineVmArgs ( config , fVMInstance ) ; addArguments ( allVMArgs , arguments ) ; String [ ] cp = config . getLoadPath ( ) ; if ( cp . length > ) { arguments . addAll ( convertLoadPath ( config , cp ) ) ; } arguments . addAll ( debugArgs ( debugTarget ) ) ; arguments . add ( StandardVMRunner . END_OF_OPTIONS_DELIMITER ) ; arguments . add ( getFileToLaunch ( config ) ) ; addArguments ( config . getProgramArguments ( ) , arguments ) ; String [ ] cmdLine = new String [ arguments . size ( ) ] ; arguments . toArray ( cmdLine ) ; String [ ] envp = getEnvironment ( config ) ; if ( monitor . isCanceled ( ) ) { return ; } subMonitor . worked ( ) ; subMonitor . subTask ( LaunchingMessages . StandardVMDebugger_Starting_virtual_machine____4 ) ; Process p = null ; if ( monitor . isCanceled ( ) ) { return ; } File workingDir = getWorkingDir ( config ) ; p = exec ( cmdLine , workingDir , envp ) ; if ( p == null ) { return ; } if ( monitor . isCanceled ( ) ) { p . destroy ( ) ; return ; } IProcess process = newProcess ( launch , p , renderProcessLabel ( cmdLine ) , getDefaultProcessMap ( ) ) ; String commandLine = renderCommandLine ( cmdLine ) ; LaunchingPlugin . debug ( "" + commandLine ) ; process . setAttribute ( IProcess . ATTR_CMDLINE , commandLine ) ; subMonitor . worked ( ) ; subMonitor . subTask ( LaunchingMessages . StandardVMDebugger_Establishing_debug_connection____5 ) ; debugTarget . setProcess ( process ) ; RubyDebuggerProxy proxy = getDebugProxy ( debugTarget ) ; try { proxy . start ( ) ; launch . addDebugTarget ( debugTarget ) ; } catch ( IOException iox ) { LaunchingPlugin . log ( new Status ( IStatus . ERROR , LaunchingPlugin . PLUGIN_ID , IStatus . ERROR , LaunchingMessages . RdtLaunchingPlugin_processTerminatedBecauseNoDebuggerConnection , null ) ) ; debugTarget . terminate ( ) ; } catch ( RubyProcessingException e ) { abort ( LaunchingMessages . StandardVMDebugger_Couldn__t_connect_to_VM_5 , e , IRubyLaunchConfigurationConstants . ERR_CONNECTION_FAILED ) ; debugTarget . terminate ( ) ; } } protected List < String > debugSpecificVMArgs ( RubyDebugTarget debugTarget ) { List < String > arguments = new ArrayList < String > ( ) ; arguments . add ( "" ) ; return arguments ; } protected List < String > debugArgs ( RubyDebugTarget debugTarget ) { List < String > arguments = new ArrayList < String > ( ) ; String rdebug = RDebugVMDebugger . findRDebugExecutable ( fVMInstance . getInstallLocation ( ) ) ; arguments . add ( rdebug ) ; arguments . add ( PORT_SWITCH ) ; arguments . add ( Integer . toString ( debugTarget . getPort ( ) ) ) ; if ( isDebuggerVerbose ( ) ) { arguments . add ( VERBOSE_FLAG ) ; } return arguments ; } protected static boolean isDebuggerVerbose ( ) { return LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) . getBoolean ( PreferenceConstants . VERBOSE_DEBUGGER ) ; } protected RubyDebuggerProxy getDebugProxy ( RubyDebugTarget debugTarget ) { return new RubyDebuggerProxy ( debugTarget , true ) ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . LoadpathContainerInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RubyContainerInitializer extends LoadpathContainerInitializer { @ Override public void initialize ( IPath containerPath , IRubyProject project ) throws CoreException { int size = containerPath . segmentCount ( ) ; if ( size > ) { if ( containerPath . segment ( ) . equals ( RubyRuntime . RUBY_CONTAINER ) ) { IVMInstall vm = resolveInterpreter ( containerPath ) ; RubyVMContainer container = null ; if ( vm != null ) { container = new RubyVMContainer ( vm , containerPath ) ; } RubyCore . setLoadpathContainer ( containerPath , new IRubyProject [ ] { project } , new ILoadpathContainer [ ] { container } , null ) ; } } } public static IVMInstall resolveInterpreter ( IPath containerPath ) { IVMInstall vm = null ; if ( containerPath . segmentCount ( ) > ) { String vmTypeId = getInterpreterTypeId ( containerPath ) ; String vmName = getInterpreterName ( containerPath ) ; IVMInstallType vmType = RubyRuntime . getVMInstallType ( vmTypeId ) ; if ( vmType != null ) { vm = vmType . findVMInstallByName ( vmName ) ; } } else { vm = RubyRuntime . getDefaultVMInstall ( ) ; } return vm ; } public static String getInterpreterTypeId ( IPath path ) { return path . segment ( ) ; } public static String getInterpreterName ( IPath path ) { return path . segment ( ) ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . rubypeople . rdt . core . IRubyInformation ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . launching . RubyRuntime ; class CoreStubDocInsertingJob extends Job { public CoreStubDocInsertingJob ( ) { super ( "" ) ; } protected IStatus run ( IProgressMonitor monitor ) { File file = getCoreStubsDir ( ) ; if ( file == null ) return Status . CANCEL_STATUS ; File [ ] scripts = file . listFiles ( ) ; for ( int x = ; x < scripts . length ; x ++ ) { insertDocs ( scripts [ x ] ) ; } return Status . OK_STATUS ; } private void insertDocs ( File file ) { try { char [ ] contents = Util . getFileCharContent ( file , null ) ; String raw = new String ( contents ) ; StringBuffer modified = new StringBuffer ( raw ) ; Pattern p = Pattern . compile ( "" ) ; Matcher m = p . matcher ( raw ) ; while ( m . find ( ) ) { String className = m . group ( ) ; if ( Character . isLowerCase ( className . charAt ( ) ) ) continue ; String originalName = file . getName ( ) . substring ( , file . getName ( ) . length ( ) - ) ; if ( ! className . toLowerCase ( ) . equals ( originalName ) ) continue ; int offset = m . start ( ) ; String before = raw . substring ( , offset ) . trim ( ) ; if ( before . endsWith ( "" ) ) continue ; String docs = getRI ( className ) ; modified . insert ( offset , "" + docs + "" ) ; } if ( modified . length ( ) != raw . length ( ) ) write ( file , modified ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } private void write ( File file , StringBuffer modified ) { FileWriter writer = null ; try { writer = new FileWriter ( file ) ; writer . write ( modified . toString ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { try { if ( writer != null ) writer . close ( ) ; } catch ( IOException e ) { } } } private String getRI ( String type ) { String riResult = getRubyInformation ( ) . getDocs ( type ) ; if ( riResult . trim ( ) . equals ( "" ) ) return null ; return riResult ; } private IRubyInformation getRubyInformation ( ) { return LaunchingPlugin . getRubyInformation ( ) ; } private File getCoreStubsDir ( ) { IPath [ ] paths = RubyCore . getLoadpathVariable ( RubyRuntime . RUBYLIB_VARIABLE ) ; for ( int i = ; i < paths . length ; i ++ ) { IPath path = paths [ i ] ; if ( path . toPortableString ( ) . contains ( "" ) ) { return path . toFile ( ) ; } } return null ; } } package org . rubypeople . rdt . internal . launching ; import org . rubypeople . rdt . launching . AbstractVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . IVMRunner ; public class RubiniusVM extends AbstractVMInstall { public RubiniusVM ( IVMInstallType type , String id ) { super ( type , id ) ; } @ Override public IVMRunner getVMRunner ( String mode ) { IVMRunner runner = new RubiniusVMRunner ( ) ; runner . setVMInstall ( this ) ; return runner ; } public String getPlatform ( ) { return "" ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . IRuntimeLoadpathProvider ; public class RuntimeLoadpathProvider implements IRuntimeLoadpathProvider { private IConfigurationElement fConfigurationElement ; private IRuntimeLoadpathProvider fDelegate ; public RuntimeLoadpathProvider ( IConfigurationElement element ) { fConfigurationElement = element ; } protected IRuntimeLoadpathProvider getProvider ( ) throws CoreException { if ( fDelegate == null ) { fDelegate = ( IRuntimeLoadpathProvider ) fConfigurationElement . createExecutableExtension ( "" ) ; } return fDelegate ; } public String getIdentifier ( ) { return fConfigurationElement . getAttribute ( "" ) ; } public IRuntimeLoadpathEntry [ ] computeUnresolvedLoadpath ( ILaunchConfiguration configuration ) throws CoreException { return getProvider ( ) . computeUnresolvedLoadpath ( configuration ) ; } public IRuntimeLoadpathEntry [ ] resolveLoadpath ( IRuntimeLoadpathEntry [ ] entries , ILaunchConfiguration configuration ) throws CoreException { return getProvider ( ) . resolveLoadpath ( entries , configuration ) ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . osgi . util . NLS ; public class LaunchingMessages { private static final String BUNDLE_NAME = LaunchingMessages . class . getName ( ) ; public static String RdtLaunchingPlugin_processTerminatedBecauseNoDebuggerConnection ; public static String RdtLaunchingPlugin_internalErrorOccurred ; public static String RdtLaunchingPlugin_noInterpreterSelected ; public static String RdtLaunchingPlugin_interpreterNotFound ; public static String RdtLaunchingPlugin_noInterpreterSelectedTitle ; public static String RubyRuntime_badFormat ; public static String RubyRuntime_VM_type_element_with_unknown_id_1 ; public static String RubyRuntime_VM_element_specified_with_no_id_attribute_2 ; public static String RubyRuntime_exceptionOccurred ; public static String vmInstall_assert_typeNotNull ; public static String vmInstall_assert_idNotNull ; public static String AbstractInterpreterInstall_0 ; public static String AbstractInterpreterInstall_1 ; public static String AbstractInterpreterInstall_3 ; public static String AbstractInterpreterInstall_4 ; public static String LaunchingPlugin_33 ; public static String LaunchingPlugin_34 ; public static String RubyRuntime_exceptionsOccurred ; public static String vmInstallType_duplicateVM ; public static String StandardVMType_Standard_VM_3 ; public static String StandardVMType_Not_a_JDK_Root__Java_executable_was_not_found_1 ; public static String StandardVMType_ok_2 ; public static String StandardVMType_Not_a_JDK_root__System_library_was_not_found__1 ; public static String AbstractVMRunner_0 ; public static String vmRunnerConfig_assert_classNotNull ; public static String vmRunnerConfig_assert_classPathNotNull ; public static String vmRunnerConfig_assert_vmArgsNotNull ; public static String vmRunnerConfig_assert_programArgsNotNull ; public static String StandardVMRunner__0__at_localhost__1__1 ; public static String StandardVMRunner__0____1___2 ; public static String StandardVMRunner_Specified_working_directory_does_not_exist_or_is_not_a_directory___0__3 ; public static String StandardVMRunner_Unable_to_locate_executable_for__0__1 ; public static String StandardVMRunner_Specified_executable__0__does_not_exist_for__1__4 ; public static String StandardVMRunner_Launching_VM____1 ; public static String StandardVMRunner_Constructing_command_line____2 ; public static String StandardVMRunner_Starting_virtual_machine____3 ; public static String JavaLocalApplicationLaunchConfigurationDelegate_Creating_source_locator____2 ; public static String JavaLocalApplicationLaunchConfigurationDelegate_Verifying_launch_attributes____1 ; public static String AbstractJavaLaunchConfigurationDelegate_The_specified_JRE_installation_does_not_exist_4 ; public static String AbstractJavaLaunchConfigurationDelegate_JRE_home_directory_not_specified_for__0__5 ; public static String AbstractJavaLaunchConfigurationDelegate_JRE_home_directory_for__0__does_not_exist___1__6 ; public static String JavaLocalApplicationLaunchConfigurationDelegate_0 ; public static String JavaRuntime_Specified_VM_install_type_does_not_exist___0__2 ; public static String JavaRuntime_Specified_VM_install_not_found__type__0___name__1__2 ; public static String JavaRuntime_VM_not_fully_specified_in_launch_configuration__0____missing_VM_name__Reverting_to_default_VM__1 ; public static String JavaRuntime_28 ; public static String JavaRuntime_Launch_configuration__0__references_non_existing_project__1___1 ; public static String AbstractJavaLaunchConfigurationDelegate_Working_directory_does_not_exist___0__12 ; public static String AbstractJavaLaunchConfigurationDelegate_Main_type_not_specified_11 ; public static String RuntimeLoadpathEntry_Illegal_classpath_entry__0__1 ; public static String RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry_type_2 ; public static String RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry_location_3 ; public static String RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry___missing_project_name_4 ; public static String RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry___missing_archive_path_5 ; public static String RuntimeLoadpathEntry_Unable_to_recover_runtime_class_path_entry___missing_variable_name_6 ; public static String RuntimeLoadpathEntry_An_exception_occurred_generating_runtime_classpath_memento_8 ; public static String DefaultProjectLoadpathEntry_4 ; public static String DefaultProjectLoadpathEntry_2 ; public static String DefaultProjectLoadpathEntry_3 ; public static String JavaRuntime_26 ; public static String JavaRuntime_31 ; public static String JavaRuntime_32 ; public static String LaunchingPlugin_32 ; public static String JavaRuntime_Classpath_references_non_existant_archive___0__4 ; public static String JavaRuntime_Classpath_references_non_existant_project___0__3 ; public static String JavaRuntime_Could_not_resolve_classpath_container___0__1 ; public static String StandardVMDebugger_Launching_VM____1 ; public static String StandardVMDebugger_Finding_free_socket____2 ; public static String StandardVMDebugger_Could_not_find_a_free_socket_for_the_debugger_1 ; public static String StandardVMDebugger_Constructing_command_line____3 ; public static String StandardVMDebugger_Starting_virtual_machine____4 ; public static String StandardVMDebugger_Establishing_debug_connection____5 ; public static String StandardVMDebugger_Couldn__t_connect_to_VM_4 ; public static String StandardVMDebugger_Couldn__t_connect_to_VM_5 ; public static String LaunchingPlugin_0 ; public static String LaunchingPlugin_1 ; public static String DebugPlugin_Exception_occurred_executing_command_line__1 ; public static String DebugPlugin_Eclipse_runtime_does_not_support_working_directory_2 ; public static String RubyRemoteApplicationLaunchConfigurationDelegate_Attaching_to__0_____1 ; public static String RubyRemoteApplicationLaunchConfigurationDelegate_Creating_source_locator____2 ; public static String RubyRemoteApplicationLaunchConfigurationDelegate_Connector_not_specified_2 ; public static String RubyRemoteApplicationLaunchConfigurationDelegate_Verifying_launch_attributes____1 ; public static String SocketAttachConnector_Connecting____1 ; public static String SocketAttachConnector_Configuring_connection____1 ; public static String SocketAttachConnector_Establishing_connection____2 ; public static String SocketAttachConnector_Failed_to_connect_to_remote_VM_1 ; public static String SocketAttachConnector_Hostname_unspecified_for_remote_connection__4 ; public static String SocketAttachConnector_Standard__Socket_Attach__4 ; public static String SocketAttachConnector_Port_unspecified_for_remote_connection__2 ; private LaunchingMessages ( ) { } static { NLS . initializeMessages ( BUNDLE_NAME , LaunchingMessages . class ) ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . VMRunnerConfiguration ; public class RubiniusVMRunner extends StandardVMRunner { @ Override protected void addStreamSync ( List < String > arguments ) { } @ Override protected List < String > constructProgramString ( VMRunnerConfiguration config , IProgressMonitor monitor ) throws CoreException { List < String > string = new ArrayList < String > ( ) ; if ( ! Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) && config . isSudo ( ) ) { forceBackgroundSudoCommand ( config , monitor ) ; string . add ( "" ) ; } String command = null ; Map map = config . getVMSpecificAttributesMap ( ) ; if ( map != null ) { command = ( String ) map . get ( IRubyLaunchConfigurationConstants . ATTR_RUBY_COMMAND ) ; } if ( command == null ) { File exe = fVMInstance . getVMInstallType ( ) . findExecutable ( fVMInstance . getInstallLocation ( ) ) ; if ( exe == null ) { abort ( MessageFormat . format ( LaunchingMessages . StandardVMRunner_Unable_to_locate_executable_for__0__1 , fVMInstance . getName ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR ) ; } string . add ( exe . getAbsolutePath ( ) ) ; return string ; } String installLocation = fVMInstance . getInstallLocation ( ) . getAbsolutePath ( ) + File . separatorChar ; File exe = new File ( installLocation + "" + File . separatorChar + command ) ; if ( fileExists ( exe ) ) { string . add ( exe . getAbsolutePath ( ) ) ; return string ; } exe = new File ( exe . getAbsolutePath ( ) + "" ) ; if ( fileExists ( exe ) ) { string . add ( exe . getAbsolutePath ( ) ) ; return string ; } String path = installLocation + "" + File . separatorChar + "" + command ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) { exe = new File ( path + "" ) ; if ( fileExists ( exe ) ) { string . add ( exe . getAbsolutePath ( ) ) ; return string ; } } else { exe = new File ( path ) ; if ( fileExists ( exe ) ) { string . add ( exe . getAbsolutePath ( ) ) ; return string ; } } abort ( MessageFormat . format ( LaunchingMessages . StandardVMRunner_Specified_executable__0__does_not_exist_for__1__4 , command , fVMInstance . getName ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR ) ; return null ; } @ Override protected String [ ] getEnvironment ( VMRunnerConfiguration config ) { return config . getEnvironment ( ) ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . core . Launch ; import org . eclipse . debug . core . model . IProcess ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . launching . AbstractVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . IVMRunner ; public class StandardVM extends AbstractVMInstall { private static final String FINISHED_MARKER = "" ; private static final int FIVE_MINUTES = * * ; private static final String VERSION_TXT = "" ; private static final int CORE_STUBS_VERSION = ; private Job coreStubJob ; public StandardVM ( IVMInstallType type , String id ) { super ( type , id ) ; } @ Override public IVMRunner getVMRunner ( String mode ) { if ( ILaunchManager . RUN_MODE . equals ( mode ) ) { IVMRunner runner = new StandardVMRunner ( ) ; runner . setVMInstall ( this ) ; return runner ; } else if ( ILaunchManager . DEBUG_MODE . equals ( mode ) ) { IVMRunner runner = null ; if ( useRDebug ( ) ) { runner = new RDebugVMDebugger ( ) ; } else { runner = new StandardVMDebugger ( ) ; } runner . setVMInstall ( this ) ; return runner ; } else if ( ILaunchManager . PROFILE_MODE . equals ( mode ) ) { return getVMRunner ( this , mode ) ; } return null ; } protected boolean useRDebug ( ) { return LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) . getBoolean ( PreferenceConstants . USE_RUBY_DEBUG ) ; } public String getRubyVersion ( ) { IVMInstallType installType = getVMInstallType ( ) ; File installLocation = getInstallLocation ( ) ; if ( installLocation != null ) { File executable = installType . findExecutable ( installLocation ) ; if ( executable != null ) { String vmVersion = installType . getVMVersion ( installLocation , executable ) ; StringBuffer version = new StringBuffer ( ) ; for ( int i = ; i < vmVersion . length ( ) ; i ++ ) { char ch = vmVersion . charAt ( i ) ; if ( Character . isDigit ( ch ) || ch == '' ) { version . append ( ch ) ; } else { break ; } } if ( version . length ( ) > ) { return version . toString ( ) ; } } } return null ; } public String getPlatform ( ) { IVMInstallType installType = getVMInstallType ( ) ; File installLocation = getInstallLocation ( ) ; if ( installLocation != null ) { File executable = installType . findExecutable ( installLocation ) ; if ( executable != null ) { String platform = installType . getVMPlatform ( installLocation , executable ) ; if ( platform != null ) return platform ; } } return "" ; } @ Override public IPath [ ] getLibraryLocations ( ) { IPath [ ] paths = super . getLibraryLocations ( ) ; if ( paths != null ) { generateCoreStubs ( getVMInstallType ( ) . findExecutable ( getInstallLocation ( ) ) ) ; return paths ; } return getDefaultLibraryLocations ( ) ; } private IPath [ ] getDefaultLibraryLocations ( ) { IPath [ ] dflts = getVMInstallType ( ) . getDefaultLibraryLocations ( getInstallLocation ( ) ) ; IPath coreStubsPath = generateCoreStubs ( getVMInstallType ( ) . findExecutable ( getInstallLocation ( ) ) ) ; if ( coreStubsPath == null ) { return dflts ; } IPath [ ] paths = new IPath [ dflts . length + ] ; for ( int i = ; i < dflts . length ; i ++ ) { paths [ i ] = dflts [ i ] ; } paths [ dflts . length ] = coreStubsPath ; return paths ; } private IPath generateCoreStubs ( final File rubyExecutable ) { if ( rubyExecutable == null ) return null ; final File coreStubber = LaunchingPlugin . getFileInPlugin ( new Path ( "" ) . append ( "" ) . append ( "" ) ) ; if ( coreStubber == null || ! coreStubber . exists ( ) ) { LaunchingPlugin . log ( "" ) ; return null ; } final IPath stubFolder = LaunchingPlugin . getDefault ( ) . getStateLocation ( ) . append ( getId ( ) ) . append ( "" ) ; if ( stubFolder . toFile ( ) . exists ( ) && stubFolder . append ( FINISHED_MARKER ) . toFile ( ) . exists ( ) ) { int version = getCoreStubsVersion ( stubFolder ) ; if ( version == CORE_STUBS_VERSION ) { return stubFolder ; } delete ( stubFolder . toFile ( ) ) ; writeNewVersion ( stubFolder ) ; } stubFolder . toFile ( ) . mkdirs ( ) ; if ( coreStubJob != null ) { IStatus result = coreStubJob . getResult ( ) ; if ( result == null ) { return stubFolder ; } coreStubJob . cancel ( ) ; } coreStubJob = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { String rubyExecutablePath = rubyExecutable . getAbsolutePath ( ) ; rubyExecutablePath = rubyExecutablePath . replace ( "" , "" ) ; String [ ] cmdLine = new String [ ] { rubyExecutablePath , coreStubber . getAbsolutePath ( ) , stubFolder . toOSString ( ) } ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; Process p = null ; try { p = Runtime . getRuntime ( ) . exec ( cmdLine ) ; IProcess process = DebugPlugin . newProcess ( new Launch ( null , ILaunchManager . RUN_MODE , null ) , p , "" ) ; long start = System . currentTimeMillis ( ) ; while ( ! process . isTerminated ( ) ) { Thread . yield ( ) ; if ( monitor . isCanceled ( ) || ( System . currentTimeMillis ( ) > ( start + ( FIVE_MINUTES ) ) ) ) { p . destroy ( ) ; return Status . CANCEL_STATUS ; } } int exitValue = p . exitValue ( ) ; if ( exitValue == ) { stubFolder . append ( FINISHED_MARKER ) . toFile ( ) . createNewFile ( ) ; } } catch ( IOException ioe ) { LaunchingPlugin . log ( ioe ) ; } finally { if ( p != null ) { p . destroy ( ) ; } } return Status . OK_STATUS ; } } ; coreStubJob . schedule ( ) ; return stubFolder ; } private void writeNewVersion ( IPath stubFolder ) { stubFolder . toFile ( ) . mkdirs ( ) ; File versionFile = stubFolder . append ( VERSION_TXT ) . toFile ( ) ; FileWriter writer = null ; try { versionFile . createNewFile ( ) ; writer = new FileWriter ( versionFile ) ; writer . write ( Integer . toString ( CORE_STUBS_VERSION ) ) ; } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } finally { try { if ( writer != null ) writer . close ( ) ; } catch ( IOException e ) { } } } private void delete ( File file ) { if ( file . isDirectory ( ) ) { File [ ] children = file . listFiles ( ) ; for ( int i = ; i < children . length ; i ++ ) { delete ( children [ i ] ) ; } } file . delete ( ) ; file . deleteOnExit ( ) ; } private int getCoreStubsVersion ( IPath stubFolder ) { try { File versionFile = stubFolder . append ( VERSION_TXT ) . toFile ( ) ; if ( ! versionFile . exists ( ) ) { return ; } String raw = new String ( Util . getFileCharContent ( versionFile , null ) ) ; return Integer . parseInt ( raw ) ; } catch ( NumberFormatException e ) { LaunchingPlugin . log ( e ) ; } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } return CORE_STUBS_VERSION ; } } package org . rubypeople . rdt . internal . launching ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry2 ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntryResolver ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . RubyRuntime ; public class DefaultEntryResolver implements IRuntimeLoadpathEntryResolver { public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , ILaunchConfiguration configuration ) throws CoreException { IRuntimeLoadpathEntry2 entry2 = ( IRuntimeLoadpathEntry2 ) entry ; IRuntimeLoadpathEntry [ ] entries = entry2 . getRuntimeLoadpathEntries ( configuration ) ; List < IRuntimeLoadpathEntry > resolved = new ArrayList < IRuntimeLoadpathEntry > ( ) ; for ( int i = ; i < entries . length ; i ++ ) { IRuntimeLoadpathEntry [ ] temp = RubyRuntime . resolveRuntimeLoadpathEntry ( entries [ i ] , configuration ) ; for ( int j = ; j < temp . length ; j ++ ) { resolved . add ( temp [ j ] ) ; } } return resolved . toArray ( new IRuntimeLoadpathEntry [ resolved . size ( ) ] ) ; } public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , IRubyProject project ) throws CoreException { IRuntimeLoadpathEntry2 entry2 = ( IRuntimeLoadpathEntry2 ) entry ; IRuntimeLoadpathEntry [ ] entries = entry2 . getRuntimeLoadpathEntries ( null ) ; List < IRuntimeLoadpathEntry > resolved = new ArrayList < IRuntimeLoadpathEntry > ( ) ; for ( int i = ; i < entries . length ; i ++ ) { IRuntimeLoadpathEntry [ ] temp = RubyRuntime . resolveRuntimeLoadpathEntry ( entries [ i ] , project ) ; for ( int j = ; j < temp . length ; j ++ ) { resolved . add ( temp [ j ] ) ; } } return resolved . toArray ( new IRuntimeLoadpathEntry [ resolved . size ( ) ] ) ; } public IVMInstall resolveVMInstall ( ILoadpathEntry entry ) throws CoreException { return null ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . osgi . service . environment . Constants ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . launching . AbstractVMInstallType ; import org . rubypeople . rdt . launching . IVMInstall ; public class StandardVMType extends AbstractVMInstallType { private static final String DEFAULT_MAJOR_MINOR_VERSION = "" ; private static final String DEFAULT_VERSION = "" ; private static final String USR = "" ; private static final String USR_BIN_RUBY = USR + "" ; private static final String USR_LOCAL_BIN_RUBY = "" ; private static final String OPT_LOCAL_BIN_RUBY = "" ; private static final String MAC_OSX_LEOPARD_RUBY_PATH = "" ; private static Map < String , LibraryInfo > fgFailedInstallPath = new HashMap < String , LibraryInfo > ( ) ; private static final char fgSeparator = File . separatorChar ; private static final String [ ] fgCandidateRubyFiles = { "" , "" , "" , "" } ; private static final String [ ] fgCandidateRubyLocations = { "" , "" + fgSeparator } ; @ Override protected IVMInstall doCreateVMInstall ( String id ) { return new StandardVM ( this , id ) ; } public IPath [ ] getDefaultLibraryLocations ( File installLocation ) { File rubyExecutable = findRubyExecutable ( installLocation ) ; LibraryInfo info ; if ( rubyExecutable == null ) { LaunchingPlugin . logInfo ( "" + installLocation ) ; info = getDefaultLibraryInfo ( installLocation ) ; } else { info = getLibraryInfo ( installLocation , rubyExecutable ) ; } String [ ] loadpath = info . getBootpath ( ) ; IPath [ ] paths = new IPath [ loadpath . length ] ; for ( int i = ; i < loadpath . length ; i ++ ) { paths [ i ] = new Path ( loadpath [ i ] ) ; } return paths ; } public String getName ( ) { return LaunchingMessages . StandardVMType_Standard_VM_3 ; } public IStatus validateInstallLocation ( File rubyHome ) { IStatus status = null ; File rubyExecutable = findRubyExecutable ( rubyHome ) ; if ( rubyExecutable == null ) { status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_Not_a_JDK_Root__Java_executable_was_not_found_1 , null ) ; } else { if ( canDetectDefaultSystemLibraries ( rubyHome , rubyExecutable ) ) { status = new Status ( IStatus . OK , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_ok_2 , null ) ; } else { status = new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , , LaunchingMessages . StandardVMType_Not_a_JDK_root__System_library_was_not_found__1 , null ) ; } } return status ; } public static File findRubyExecutable ( File vmInstallLocation ) { for ( int i = ; i < fgCandidateRubyFiles . length ; i ++ ) { for ( int j = ; j < fgCandidateRubyLocations . length ; j ++ ) { File rubyFile = new File ( vmInstallLocation , fgCandidateRubyLocations [ j ] + fgCandidateRubyFiles [ i ] ) ; rubyFile = Util . findFileWithOptionalSuffix ( rubyFile . getAbsolutePath ( ) ) ; if ( rubyFile != null && rubyFile . isFile ( ) ) { return rubyFile ; } } } return null ; } protected boolean canDetectDefaultSystemLibraries ( File rubyHome , File rubyExecutable ) { File foundExecutable = findRubyExecutable ( rubyHome ) ; if ( foundExecutable == null || ! foundExecutable . exists ( ) ) return false ; IPath [ ] locations = getDefaultLibraryLocations ( rubyHome ) ; return locations != null && locations . length > ; } protected synchronized LibraryInfo getLibraryInfo ( File rubyHome , File rubyExecutable ) { String installPath = rubyHome . getAbsolutePath ( ) ; LibraryInfo info = LaunchingPlugin . getLibraryInfo ( this , installPath ) ; if ( info == null ) { info = fgFailedInstallPath . get ( installPath ) ; if ( info == null ) { info = generateLibraryInfo ( rubyHome , rubyExecutable ) ; if ( info == null ) { info = getDefaultLibraryInfo ( rubyHome ) ; fgFailedInstallPath . put ( installPath , info ) ; } else { LaunchingPlugin . setLibraryInfo ( this , installPath , info ) ; } } } return info ; } protected LibraryInfo getDefaultLibraryInfo ( File installLocation ) { IPath [ ] dflts = getDefaultSystemLibrary ( installLocation ) ; String [ ] strings = new String [ dflts . length ] ; for ( int i = ; i < dflts . length ; i ++ ) { strings [ i ] = dflts [ i ] . toOSString ( ) ; } return new LibraryInfo ( DEFAULT_VERSION , strings ) ; } protected IPath [ ] getDefaultSystemLibrary ( File rubyHome ) { String stdPath = rubyHome . getAbsolutePath ( ) + fgSeparator + "" + fgSeparator + "" + fgSeparator + DEFAULT_MAJOR_MINOR_VERSION ; String sitePath = rubyHome . getAbsolutePath ( ) + fgSeparator + "" + fgSeparator + "" + fgSeparator + "" + fgSeparator + DEFAULT_MAJOR_MINOR_VERSION ; IPath [ ] paths = new IPath [ ] ; paths [ ] = new Path ( sitePath ) ; paths [ ] = new Path ( stdPath ) ; return paths ; } public File detectInstallLocation ( ) { if ( Platform . getOS ( ) . equals ( Constants . OS_WIN32 ) ) { return tryLocation ( detectInstallOnWindows ( ) ) ; } File rubyExecutable = null ; if ( Platform . getOS ( ) . equals ( Constants . OS_MACOSX ) ) { File rubyHome = tryLocation ( new File ( MAC_OSX_LEOPARD_RUBY_PATH ) ) ; if ( rubyHome != null ) return rubyHome ; } File tentativeRubyHome = null ; try { rubyExecutable = parseRubyExecutableLocation ( executeAndRead ( new String [ ] { "" , "" } ) ) ; tentativeRubyHome = tryLocation ( rubyExecutable ) ; } catch ( Exception e ) { LaunchingPlugin . log ( e ) ; } if ( tentativeRubyHome == null || tentativeRubyHome . getAbsolutePath ( ) . equals ( USR ) ) { File rubyHome = tryLocation ( new File ( USR_LOCAL_BIN_RUBY ) ) ; if ( rubyHome != null ) return rubyHome ; rubyHome = tryLocation ( new File ( OPT_LOCAL_BIN_RUBY ) ) ; if ( rubyHome != null ) return rubyHome ; } if ( tentativeRubyHome != null ) return tentativeRubyHome ; return tryLocation ( new File ( USR_BIN_RUBY ) ) ; } private File detectInstallOnWindows ( ) { String winPath = System . getenv ( "" ) ; String [ ] paths = winPath . split ( "" ) ; for ( int i = ; i < paths . length ; i ++ ) { String possibleExecutablePath = paths [ i ] + File . separator + "" ; File possible = new File ( possibleExecutablePath ) ; if ( possible . exists ( ) ) { return possible ; } } return new File ( "" + File . separator + "" + File . separator + "" + File . separator + "" ) ; } private File tryLocation ( File rubyExecutable ) { if ( rubyExecutable == null ) return null ; File bin = rubyExecutable . getParentFile ( ) ; if ( ! bin . exists ( ) ) return null ; File rubyHome = bin . getParentFile ( ) ; if ( ! rubyHome . exists ( ) ) return null ; if ( ! canDetectDefaultSystemLibraries ( rubyHome , rubyExecutable ) ) { LaunchingPlugin . logInfo ( "" + rubyHome . getAbsolutePath ( ) ) ; return null ; } return rubyHome ; } public File findExecutable ( File installLocation ) { return findRubyExecutable ( installLocation ) ; } public String getVMPlatform ( File rubyHome , File rubyExecutable ) { String rubyExecutablePath = rubyExecutable . getAbsolutePath ( ) ; String [ ] cmdLine = new String [ ] { rubyExecutablePath , "" } ; String platform = parsePlatform ( executeAndRead ( cmdLine ) ) ; if ( platform == null ) { LaunchingPlugin . log ( MessageFormat . format ( "" , rubyHome . getAbsolutePath ( ) ) ) ; } return platform ; } private String parsePlatform ( List < String > lines ) { if ( lines == null || lines . size ( ) == ) return null ; String firstLine = lines . remove ( ) ; Pattern pat = Pattern . compile ( "" ) ; Matcher m = pat . matcher ( firstLine ) ; if ( m . find ( ) ) { return m . group ( ) ; } return null ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntry ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntryResolver ; import org . rubypeople . rdt . launching . IRuntimeLoadpathEntryResolver2 ; import org . rubypeople . rdt . launching . IVMInstall ; public class RuntimeLoadpathEntryResolver implements IRuntimeLoadpathEntryResolver2 { private IConfigurationElement fConfigurationElement ; private IRuntimeLoadpathEntryResolver fDelegate ; public RuntimeLoadpathEntryResolver ( IConfigurationElement element ) { fConfigurationElement = element ; } public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , ILaunchConfiguration configuration ) throws CoreException { return getResolver ( ) . resolveRuntimeLoadpathEntry ( entry , configuration ) ; } protected IRuntimeLoadpathEntryResolver getResolver ( ) throws CoreException { if ( fDelegate == null ) { fDelegate = ( IRuntimeLoadpathEntryResolver ) fConfigurationElement . createExecutableExtension ( "" ) ; } return fDelegate ; } public String getVariableName ( ) { return fConfigurationElement . getAttribute ( "" ) ; } public String getContainerId ( ) { return fConfigurationElement . getAttribute ( "" ) ; } public String getRuntimeLoadpathEntryId ( ) { return fConfigurationElement . getAttribute ( "" ) ; } public IVMInstall resolveVMInstall ( ILoadpathEntry entry ) throws CoreException { return getResolver ( ) . resolveVMInstall ( entry ) ; } public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , IRubyProject project ) throws CoreException { return getResolver ( ) . resolveRuntimeLoadpathEntry ( entry , project ) ; } public boolean isVMInstallReference ( ILoadpathEntry entry ) { try { IRuntimeLoadpathEntryResolver resolver = getResolver ( ) ; if ( resolver instanceof IRuntimeLoadpathEntryResolver2 ) { IRuntimeLoadpathEntryResolver2 resolver2 = ( IRuntimeLoadpathEntryResolver2 ) resolver ; return resolver2 . isVMInstallReference ( entry ) ; } else { return resolver . resolveVMInstall ( entry ) != null ; } } catch ( CoreException e ) { return false ; } } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . swt . widgets . Display ; abstract class Sudo { synchronized static final String getPassword ( final String msg ) { final String [ ] password = new String [ ] ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { PasswordDialog dialog = new PasswordDialog ( null , "" , msg , null , null ) ; if ( dialog . open ( ) == Dialog . OK ) { password [ ] = dialog . getValue ( ) ; } } } ) ; return password [ ] ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMRunnerConfiguration ; public class RDebugVMDebugger extends StandardVMDebugger { private static final String PORT_SWITCH = "" ; private static final String VERBOSE_FLAG = "" ; private static final String RDEBUG_EXECUTABLE = "" ; @ Override protected List < String > constructProgramString ( VMRunnerConfiguration config , IProgressMonitor monitor ) throws CoreException { String [ ] args = config . getProgramArguments ( ) ; List < String > argList = new ArrayList < String > ( ) ; argList . add ( StandardVMDebugger . END_OF_OPTIONS_DELIMITER ) ; for ( int i = ; i < args . length ; i ++ ) { argList . add ( args [ i ] ) ; } config . setProgramArguments ( argList . toArray ( new String [ argList . size ( ) ] ) ) ; return super . constructProgramString ( config , monitor ) ; } @ Override protected List < String > debugSpecificVMArgs ( RubyDebugTarget debugTarget ) { return new ArrayList < String > ( ) ; } protected List < String > debugArgs ( RubyDebugTarget debugTarget ) throws CoreException { List < String > arguments = new ArrayList < String > ( ) ; String rdebug = findRDebugExecutable ( fVMInstance . getInstallLocation ( ) ) ; if ( rdebug == null || rdebug . trim ( ) . length ( ) == ) { abort ( "" + RDEBUG_EXECUTABLE + "" , null , - ) ; } if ( fVMInstance . getPlatform ( ) . equals ( IVMInstall . CYWGIN_PLATFORM ) ) { rdebug = rdebug . replace ( '' , '' ) ; } arguments . add ( rdebug ) ; arguments . add ( PORT_SWITCH ) ; arguments . add ( Integer . toString ( debugTarget . getPort ( ) ) ) ; if ( isDebuggerVerbose ( ) ) { arguments . add ( VERBOSE_FLAG ) ; } return arguments ; } protected RubyDebuggerProxy getDebugProxy ( RubyDebugTarget debugTarget ) { return new RubyDebuggerProxy ( debugTarget , true ) ; } private static IPath tryToGetRDebugExecutablePath ( File vmInstallLocation ) { IPath path = RubyRuntime . checkAnyInterpreterBin ( RDEBUG_EXECUTABLE , vmInstallLocation ) ; if ( path == null ) { path = RubyRuntime . checkInterpreterBin ( RDEBUG_EXECUTABLE ) ; } return path ; } public static String findRDebugExecutable ( File vmInstallLocation ) { IPath path = tryToGetRDebugExecutablePath ( vmInstallLocation ) ; if ( path != null && path . toFile ( ) . exists ( ) ) return path . toOSString ( ) ; IPath [ ] gemsPaths = RubyCore . getLoadpathVariable ( "" ) ; if ( gemsPaths != null ) { for ( int i = ; i < gemsPaths . length ; i ++ ) { if ( gemsPaths [ i ] == null ) continue ; path = gemsPaths [ i ] . removeLastSegments ( ) . append ( "" ) . append ( RDEBUG_EXECUTABLE ) ; if ( path != null && path . toFile ( ) . exists ( ) ) return path . toOSString ( ) ; } } path = RubyCore . checkSystemPath ( RDEBUG_EXECUTABLE ) ; if ( path != null && path . toFile ( ) . exists ( ) ) return path . toOSString ( ) ; path = RubyCore . checkCommonBinLocations ( RDEBUG_EXECUTABLE ) ; if ( path != null && path . toFile ( ) . exists ( ) ) return path . toOSString ( ) ; return null ; } } package org . rubypeople . rdt . internal . launching ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; public class VMListener implements IVMInstallChangedListener { private boolean fChanged = false ; public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { fChanged = true ; } public void vmAdded ( IVMInstall vm ) { fChanged = true ; } public void vmChanged ( PropertyChangeEvent event ) { fChanged = true ; } public void vmRemoved ( IVMInstall vm ) { fChanged = true ; } public boolean isChanged ( ) { return fChanged ; } } package org . rubypeople . rdt . internal . launching ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . debug . core . ILaunch ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMConnector ; public class SocketAttachConnector implements IVMConnector { public String getIdentifier ( ) { return IRubyLaunchConfigurationConstants . ID_SOCKET_ATTACH_VM_CONNECTOR ; } public String getName ( ) { return LaunchingMessages . SocketAttachConnector_Standard__Socket_Attach__4 ; } protected static void abort ( String message , Throwable exception , int code ) throws CoreException { throw new CoreException ( new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , code , message , exception ) ) ; } public void connect ( Map < String , Object > arguments , IProgressMonitor monitor , ILaunch launch ) throws CoreException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } IProgressMonitor subMonitor = new SubProgressMonitor ( monitor , ) ; subMonitor . beginTask ( LaunchingMessages . SocketAttachConnector_Connecting____1 , ) ; subMonitor . subTask ( LaunchingMessages . SocketAttachConnector_Configuring_connection____1 ) ; String portNumberString = ( String ) arguments . get ( "" ) ; if ( portNumberString == null ) { abort ( LaunchingMessages . SocketAttachConnector_Port_unspecified_for_remote_connection__2 , null , IRubyLaunchConfigurationConstants . ERR_UNSPECIFIED_PORT ) ; } int port = Integer . parseInt ( portNumberString ) ; String host = ( String ) arguments . get ( "" ) ; if ( host == null ) { abort ( LaunchingMessages . SocketAttachConnector_Hostname_unspecified_for_remote_connection__4 , null , IRubyLaunchConfigurationConstants . ERR_UNSPECIFIED_HOSTNAME ) ; } subMonitor . worked ( ) ; subMonitor . subTask ( LaunchingMessages . SocketAttachConnector_Establishing_connection____2 ) ; try { RubyDebugTarget debugTarget = new RubyDebugTarget ( launch , host , port ) ; RubyDebuggerProxy proxy = new RubyDebuggerProxy ( debugTarget , true ) ; proxy . start ( ) ; launch . addDebugTarget ( debugTarget ) ; subMonitor . worked ( ) ; subMonitor . done ( ) ; } catch ( IOException e ) { abort ( LaunchingMessages . SocketAttachConnector_Failed_to_connect_to_remote_VM_1 , e , IRubyLaunchConfigurationConstants . ERR_REMOTE_VM_CONNECTION_FAILED ) ; } catch ( RubyProcessingException e ) { abort ( LaunchingMessages . SocketAttachConnector_Failed_to_connect_to_remote_VM_1 , e , IRubyLaunchConfigurationConstants . ERR_REMOTE_VM_CONNECTION_FAILED ) ; } } public Map < String , Object > getDefaultArguments ( ) throws CoreException { Map < String , Object > args = new HashMap < String , Object > ( ) ; args . put ( "" , "" ) ; args . put ( "" , ) ; return args ; } public List < String > getArgumentOrder ( ) { List < String > list = new ArrayList < String > ( ) ; list . add ( "" ) ; list . add ( "" ) ; return list ; } } package org . rubypeople . rdt . internal . launching ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; public class RubyVMContainer implements ILoadpathContainer { private static Map fgLoadpathEntries ; private IVMInstall fInterpreter ; private IPath fPath ; public RubyVMContainer ( IVMInstall interpreter , IPath path ) { fInterpreter = interpreter ; fPath = path ; } public String getDescription ( ) { return "" ; } public ILoadpathEntry [ ] getLoadpathEntries ( ) { return getLoadpathEntries ( fInterpreter ) ; } private static ILoadpathEntry [ ] getLoadpathEntries ( IVMInstall vm ) { if ( fgLoadpathEntries == null ) { fgLoadpathEntries = new HashMap ( ) ; IVMInstallChangedListener listener = new IVMInstallChangedListener ( ) { public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { } public void vmChanged ( PropertyChangeEvent event ) { if ( event . getSource ( ) != null ) { fgLoadpathEntries . remove ( event . getSource ( ) ) ; } } public void vmAdded ( IVMInstall newVm ) { } public void vmRemoved ( IVMInstall removedVm ) { fgLoadpathEntries . remove ( removedVm ) ; } } ; RubyRuntime . addVMInstallChangedListener ( listener ) ; } ILoadpathEntry [ ] entries = ( ILoadpathEntry [ ] ) fgLoadpathEntries . get ( vm ) ; if ( entries == null ) { entries = computeLoadpathEntries ( vm ) ; fgLoadpathEntries . put ( vm , entries ) ; } return entries ; } private static ILoadpathEntry [ ] computeLoadpathEntries ( IVMInstall vm ) { IPath [ ] libs = vm . getLibraryLocations ( ) ; if ( libs == null ) { libs = RubyRuntime . getLibraryLocations ( vm ) ; } List entries = new ArrayList ( libs . length ) ; for ( int i = ; i < libs . length ; i ++ ) { entries . add ( RubyCore . newLibraryEntry ( libs [ i ] , false ) ) ; } return ( ILoadpathEntry [ ] ) entries . toArray ( new ILoadpathEntry [ entries . size ( ) ] ) ; } public int getKind ( ) { return ILoadpathContainer . K_DEFAULT_SYSTEM ; } public IPath getPath ( ) { return fPath ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceChangeListener ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class LaunchCleaner implements IResourceChangeListener { public void resourceChanged ( IResourceChangeEvent event ) { if ( event == null ) return ; IResourceDelta delta = event . getDelta ( ) ; checkDelta ( delta ) ; } private void checkDelta ( IResourceDelta delta ) { if ( delta == null ) return ; IResource resource = delta . getResource ( ) ; if ( ! ( resource instanceof IWorkspaceRoot ) && ! ( resource instanceof IProject ) ) return ; if ( resource instanceof IProject ) { if ( IResourceDelta . REMOVED != delta . getKind ( ) ) return ; IPath path = delta . getFullPath ( ) ; String name = path . lastSegment ( ) ; projectRemoved ( name ) ; } IResourceDelta [ ] children = delta . getAffectedChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { checkDelta ( children [ i ] ) ; } } private void projectRemoved ( String name ) { try { ILaunchConfigurationType type = DebugPlugin . getDefault ( ) . getLaunchManager ( ) . getLaunchConfigurationType ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ; ILaunchConfiguration [ ] configs = DebugPlugin . getDefault ( ) . getLaunchManager ( ) . getLaunchConfigurations ( type ) ; for ( int i = ; i < configs . length ; i ++ ) { String projectName = configs [ i ] . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , ( String ) null ) ; if ( projectName != null && projectName . equals ( name ) ) { configs [ i ] . delete ( ) ; } } } catch ( CoreException e ) { e . printStackTrace ( ) ; } } } package org . rubypeople . rdt . launching ; import java . io . ByteArrayInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . StringReader ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . TransformerException ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Preferences ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . variables . VariablesPlugin ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . core . IStreamListener ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . core . model . IStreamMonitor ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . rubypeople . rdt . core . ILoadpathContainer ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyModel ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . internal . launching . CompositeId ; import org . rubypeople . rdt . internal . launching . DefaultEntryResolver ; import org . rubypeople . rdt . internal . launching . DefaultProjectLoadpathEntry ; import org . rubypeople . rdt . internal . launching . LaunchingMessages ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import org . rubypeople . rdt . internal . launching . ListenerList ; import org . rubypeople . rdt . internal . launching . RuntimeLoadpathEntry ; import org . rubypeople . rdt . internal . launching . RuntimeLoadpathEntryResolver ; import org . rubypeople . rdt . internal . launching . RuntimeLoadpathProvider ; import org . rubypeople . rdt . internal . launching . SocketAttachConnector ; import org . rubypeople . rdt . internal . launching . VMDefinitionsContainer ; import org . rubypeople . rdt . internal . launching . VMListener ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; public class RubyRuntime { private static final String STD_RUBY_VMTYPE = "" ; private static final String JRUBY_VMTYPE = "" ; public static final String RUBY_CONTAINER = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String PREF_VM_XML = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String EXTENSION_POINT_VM_INSTALLS = "" ; public static final String RUBYLIB_VARIABLE = "" ; public static final String EXTENSION_POINT_RUNTIME_CLASSPATH_ENTRY_RESOLVERS = "" ; public static final String EXTENSION_POINT_RUNTIME_CLASSPATH_PROVIDERS = "" ; private static IVMInstallType [ ] fgVMTypes = null ; private static RubyRuntime runtime ; private static Object fgVMLock = new Object ( ) ; private static boolean fgInitializingVMs ; private static String fgDefaultVMId ; private static ListenerList fgVMListeners = new ListenerList ( ) ; private static ThreadLocal < List < IRubyProject > > fgProjects = new ThreadLocal < List < IRubyProject > > ( ) ; private static ThreadLocal < Integer > fgEntryCount = new ThreadLocal < Integer > ( ) ; private static IRuntimeLoadpathProvider fgDefaultLoadpathProvider = new StandardLoadpathProvider ( ) ; private static Map < String , RuntimeLoadpathProvider > fgPathProviders = null ; private static Set < String > fgContributedVMs = new HashSet < String > ( ) ; private static Map < String , RuntimeLoadpathEntryResolver > fgVariableResolvers = null ; private static Map < String , RuntimeLoadpathEntryResolver > fgContainerResolvers = null ; private static Map < String , RuntimeLoadpathEntryResolver > fgRuntimeLoadpathEntryResolvers = null ; private static String fgDefaultVMConnectorId ; protected RubyRuntime ( ) { super ( ) ; } public static RubyRuntime getDefault ( ) { if ( runtime == null ) { runtime = new RubyRuntime ( ) ; } return runtime ; } public static void removeVMInstallChangedListener ( IVMInstallChangedListener listener ) { fgVMListeners . remove ( listener ) ; } public static IVMInstall getDefaultVMInstall ( ) { IVMInstall install = getVMFromCompositeId ( getDefaultVMId ( ) ) ; if ( install != null && install . getInstallLocation ( ) . exists ( ) ) { return install ; } if ( install != null ) { install . getVMInstallType ( ) . disposeVMInstall ( install . getId ( ) ) ; } synchronized ( fgVMLock ) { fgDefaultVMId = null ; fgVMTypes = null ; initializeVMs ( ) ; } return getVMFromCompositeId ( getDefaultVMId ( ) ) ; } public static IVMInstall getVMFromCompositeId ( String idString ) { if ( idString == null || idString . length ( ) == ) { return null ; } CompositeId id = CompositeId . fromString ( idString ) ; if ( id . getPartCount ( ) == ) { IVMInstallType vmType = getVMInstallType ( id . get ( ) ) ; if ( vmType != null ) { return vmType . findVMInstall ( id . get ( ) ) ; } } return null ; } private static String getDefaultVMId ( ) { initializeVMs ( ) ; return fgDefaultVMId ; } public static void saveVMConfiguration ( ) throws CoreException { if ( fgVMTypes == null ) { return ; } try { String xml = getVMsAsXML ( ) ; getPreferences ( ) . setValue ( PREF_VM_XML , xml ) ; savePreferences ( ) ; } catch ( IOException e ) { throw new CoreException ( new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , IStatus . ERROR , LaunchingMessages . RubyRuntime_exceptionsOccurred , e ) ) ; } catch ( ParserConfigurationException e ) { throw new CoreException ( new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , IStatus . ERROR , LaunchingMessages . RubyRuntime_exceptionsOccurred , e ) ) ; } catch ( TransformerException e ) { throw new CoreException ( new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , IStatus . ERROR , LaunchingMessages . RubyRuntime_exceptionsOccurred , e ) ) ; } } private static String getVMsAsXML ( ) throws IOException , ParserConfigurationException , TransformerException { VMDefinitionsContainer container = new VMDefinitionsContainer ( ) ; container . setDefaultVMInstallCompositeID ( getDefaultVMId ( ) ) ; IVMInstallType [ ] vmTypes = getVMInstallTypes ( ) ; for ( int i = ; i < vmTypes . length ; ++ i ) { IVMInstall [ ] vms = vmTypes [ i ] . getVMInstalls ( ) ; for ( int j = ; j < vms . length ; j ++ ) { IVMInstall install = vms [ j ] ; container . addVM ( install ) ; } } return container . getAsXML ( ) ; } public static void savePreferences ( ) { LaunchingPlugin . getDefault ( ) . savePluginPreferences ( ) ; } public static void addVMInstallChangedListener ( IVMInstallChangedListener listener ) { fgVMListeners . add ( listener ) ; } private static void notifyDefaultVMChanged ( IVMInstall previous , IVMInstall current ) { Object [ ] listeners = fgVMListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { IVMInstallChangedListener listener = ( IVMInstallChangedListener ) listeners [ i ] ; listener . defaultVMInstallChanged ( previous , current ) ; } } public static IVMInstallType getVMInstallType ( String id ) { IVMInstallType [ ] vmTypes = getVMInstallTypes ( ) ; for ( int i = ; i < vmTypes . length ; i ++ ) { if ( vmTypes [ i ] . getId ( ) . equals ( id ) ) { return vmTypes [ i ] ; } } return null ; } public static IVMInstallType [ ] getVMInstallTypes ( ) { initializeVMs ( ) ; return fgVMTypes ; } private static void initializeVMs ( ) { VMDefinitionsContainer vmDefs = null ; boolean setPref = false ; synchronized ( fgVMLock ) { if ( fgVMTypes == null ) { try { fgInitializingVMs = true ; initializeVMTypeExtensions ( ) ; try { vmDefs = new VMDefinitionsContainer ( ) ; setPref = addPersistedVMs ( vmDefs ) ; if ( vmDefs . getValidVMList ( ) . isEmpty ( ) ) { VMListener listener = new VMListener ( ) ; addVMInstallChangedListener ( listener ) ; setPref = true ; VMStandin [ ] runtime = detectDefaultVMs ( ) ; removeVMInstallChangedListener ( listener ) ; if ( ! listener . isChanged ( ) ) { if ( runtime != null && runtime . length > ) { for ( int i = ; i < runtime . length ; i ++ ) { vmDefs . addVM ( runtime [ i ] ) ; } VMStandin defaultVM = chooseDefault ( runtime ) ; vmDefs . setDefaultVMInstallCompositeID ( getCompositeIdFromVM ( defaultVM ) ) ; } } else { addPersistedVMs ( vmDefs ) ; vmDefs . setDefaultVMInstallCompositeID ( fgDefaultVMId ) ; } } else { if ( noJRubyVM ( vmDefs ) ) { IVMInstallType type = getVMInstallType ( JRUBY_VMTYPE ) ; VMStandin vm = detectDefaultVM ( type ) ; if ( vm != null ) vmDefs . addVM ( vm ) ; } if ( noStdRubyVM ( vmDefs ) ) { IVMInstallType type = getVMInstallType ( STD_RUBY_VMTYPE ) ; VMStandin vm = detectDefaultVM ( type ) ; if ( vm != null ) { vmDefs . addVM ( vm ) ; } } } addVMExtensions ( vmDefs ) ; String defId = vmDefs . getDefaultVMInstallCompositeID ( ) ; boolean validDef = false ; if ( defId != null ) { Iterator iterator = vmDefs . getValidVMList ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { IVMInstall vm = ( IVMInstall ) iterator . next ( ) ; if ( getCompositeIdFromVM ( vm ) . equals ( defId ) ) { validDef = true ; break ; } } } if ( ! validDef ) { setPref = true ; List list = vmDefs . getValidVMList ( ) ; if ( ! list . isEmpty ( ) ) { IVMInstall vm = ( IVMInstall ) list . get ( ) ; vmDefs . setDefaultVMInstallCompositeID ( getCompositeIdFromVM ( vm ) ) ; } } fgDefaultVMId = vmDefs . getDefaultVMInstallCompositeID ( ) ; List vmList = vmDefs . getValidVMList ( ) ; Iterator vmListIterator = vmList . iterator ( ) ; while ( vmListIterator . hasNext ( ) ) { VMStandin vmStandin = ( VMStandin ) vmListIterator . next ( ) ; vmStandin . convertToRealVM ( ) ; } } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } } finally { fgInitializingVMs = false ; } } } if ( vmDefs != null ) { IVMInstallType [ ] installTypes = getVMInstallTypes ( ) ; for ( int i = ; i < installTypes . length ; i ++ ) { IVMInstallType type = installTypes [ i ] ; IVMInstall [ ] installs = type . getVMInstalls ( ) ; for ( int j = ; j < installs . length ; j ++ ) { fireVMAdded ( installs [ j ] ) ; } } if ( setPref ) { try { String xml = vmDefs . getAsXML ( ) ; LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) . setValue ( PREF_VM_XML , xml ) ; } catch ( ParserConfigurationException e ) { LaunchingPlugin . log ( e ) ; } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } catch ( TransformerException e ) { LaunchingPlugin . log ( e ) ; } } } } private static boolean noJRubyVM ( VMDefinitionsContainer vmDefs ) { return ! hasVMOfType ( vmDefs , JRUBY_VMTYPE ) ; } private static boolean noStdRubyVM ( VMDefinitionsContainer vmDefs ) { return ! hasVMOfType ( vmDefs , STD_RUBY_VMTYPE ) ; } private static boolean hasVMOfType ( VMDefinitionsContainer vmDefs , String vmTypeId ) { List < IVMInstall > vms = vmDefs . getValidVMList ( ) ; for ( IVMInstall install : vms ) { if ( install . getVMInstallType ( ) == null || install . getVMInstallType ( ) . getId ( ) == null ) continue ; if ( install . getVMInstallType ( ) . getId ( ) . equals ( vmTypeId ) ) return true ; } return false ; } private static VMStandin chooseDefault ( VMStandin [ ] runtime ) { for ( int i = ; i < runtime . length ; i ++ ) { if ( runtime [ i ] . getVMInstallType ( ) . getId ( ) . equals ( STD_RUBY_VMTYPE ) ) { return runtime [ i ] ; } } return runtime [ ] ; } private static VMStandin [ ] detectDefaultVMs ( ) { List < VMStandin > detected = new ArrayList < VMStandin > ( ) ; IVMInstallType [ ] vmTypes = getVMInstallTypes ( ) ; for ( int i = ; i < vmTypes . length ; i ++ ) { VMStandin standin = detectDefaultVM ( vmTypes [ i ] ) ; if ( standin != null ) detected . add ( standin ) ; } return detected . toArray ( new VMStandin [ detected . size ( ) ] ) ; } private static VMStandin detectDefaultVM ( IVMInstallType vmType ) { if ( vmType == null ) return null ; File detectedLocation = vmType . detectInstallLocation ( ) ; if ( detectedLocation != null ) { long unique = System . currentTimeMillis ( ) ; while ( vmType . findVMInstall ( String . valueOf ( unique ) ) != null ) { unique ++ ; } String vmID = String . valueOf ( unique ) ; VMStandin detectedVMStandin = new VMStandin ( vmType , vmID ) ; detectedVMStandin . setInstallLocation ( detectedLocation ) ; detectedVMStandin . setName ( generateDetectedVMName ( detectedVMStandin ) ) ; return detectedVMStandin ; } return null ; } private static String generateDetectedVMName ( IVMInstall vm ) { return vm . getInstallLocation ( ) . getName ( ) ; } private static void initializeVMTypeExtensions ( ) { IExtensionPoint extensionPoint = Platform . getExtensionRegistry ( ) . getExtensionPoint ( LaunchingPlugin . PLUGIN_ID , "" ) ; IConfigurationElement [ ] configs = extensionPoint . getConfigurationElements ( ) ; MultiStatus status = new MultiStatus ( LaunchingPlugin . getUniqueIdentifier ( ) , IStatus . OK , LaunchingMessages . RubyRuntime_exceptionOccurred , null ) ; fgVMTypes = new IVMInstallType [ configs . length ] ; for ( int i = ; i < configs . length ; i ++ ) { try { IVMInstallType vmType = ( IVMInstallType ) configs [ i ] . createExecutableExtension ( "" ) ; fgVMTypes [ i ] = vmType ; } catch ( CoreException e ) { status . add ( e . getStatus ( ) ) ; } } if ( ! status . isOK ( ) ) { LaunchingPlugin . log ( status ) ; List < IVMInstallType > temp = new ArrayList < IVMInstallType > ( fgVMTypes . length ) ; for ( int i = ; i < fgVMTypes . length ; i ++ ) { if ( fgVMTypes [ i ] != null ) { temp . add ( fgVMTypes [ i ] ) ; } fgVMTypes = new IVMInstallType [ temp . size ( ) ] ; fgVMTypes = temp . toArray ( fgVMTypes ) ; } } } private static boolean addPersistedVMs ( VMDefinitionsContainer vmDefs ) throws IOException { String vmXMLString = getPreferences ( ) . getString ( PREF_VM_XML ) ; if ( vmXMLString . length ( ) > ) { try { ByteArrayInputStream inputStream = new ByteArrayInputStream ( vmXMLString . getBytes ( ) ) ; VMDefinitionsContainer . parseXMLIntoContainer ( inputStream , vmDefs ) ; return false ; } catch ( IOException ioe ) { LaunchingPlugin . log ( ioe ) ; } } else { IPath stateLocation = LaunchingPlugin . getDefault ( ) . getStateLocation ( ) ; IPath stateFile = stateLocation . append ( "" ) ; File file = new File ( stateFile . toOSString ( ) ) ; if ( file . exists ( ) ) { FileInputStream fileInputStream = new FileInputStream ( file ) ; VMDefinitionsContainer . parseXMLIntoContainer ( fileInputStream , vmDefs ) ; } } return true ; } public static Preferences getPreferences ( ) { return LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) ; } public static String getCompositeIdFromVM ( IVMInstall vm ) { if ( vm == null ) { return null ; } IVMInstallType vmType = vm . getVMInstallType ( ) ; String typeID = vmType . getId ( ) ; CompositeId id = new CompositeId ( new String [ ] { typeID , vm . getId ( ) } ) ; return id . toString ( ) ; } private static void addVMExtensions ( VMDefinitionsContainer vmDefs ) { IExtensionPoint extensionPoint = Platform . getExtensionRegistry ( ) . getExtensionPoint ( LaunchingPlugin . PLUGIN_ID , RubyRuntime . EXTENSION_POINT_VM_INSTALLS ) ; IConfigurationElement [ ] configs = extensionPoint . getConfigurationElements ( ) ; for ( int i = ; i < configs . length ; i ++ ) { IConfigurationElement element = configs [ i ] ; try { if ( "" . equals ( element . getName ( ) ) ) { String vmType = element . getAttribute ( "" ) ; if ( vmType == null ) { abort ( MessageFormat . format ( "" , ( Object [ ] ) new String [ ] { element . getContributor ( ) . getName ( ) } ) , null ) ; } String id = element . getAttribute ( "" ) ; if ( id == null ) { abort ( MessageFormat . format ( "" , ( Object [ ] ) new String [ ] { element . getContributor ( ) . getName ( ) } ) , null ) ; } IVMInstallType installType = getVMInstallType ( vmType ) ; if ( installType == null ) { abort ( MessageFormat . format ( "" , ( Object [ ] ) new String [ ] { id , element . getContributor ( ) . getName ( ) , vmType } ) , null ) ; } IVMInstall install = installType . findVMInstall ( id ) ; if ( install == null ) { String name = element . getAttribute ( "" ) ; if ( name == null ) { abort ( MessageFormat . format ( "" , ( Object [ ] ) new String [ ] { id , element . getContributor ( ) . getName ( ) } ) , null ) ; } String home = element . getAttribute ( "" ) ; if ( home == null ) { abort ( MessageFormat . format ( "" , ( Object [ ] ) new String [ ] { id , element . getContributor ( ) . getName ( ) } ) , null ) ; } String vmArgs = element . getAttribute ( "" ) ; VMStandin standin = new VMStandin ( installType , id ) ; standin . setName ( name ) ; home = substitute ( home ) ; File homeDir = new File ( home ) ; if ( homeDir . exists ( ) ) { try { home = homeDir . getCanonicalPath ( ) ; homeDir = new File ( home ) ; } catch ( IOException e ) { } } IStatus status = installType . validateInstallLocation ( homeDir ) ; if ( ! status . isOK ( ) ) { abort ( MessageFormat . format ( "" , ( Object [ ] ) new String [ ] { home , id , element . getContributor ( ) . getName ( ) , status . getMessage ( ) } ) , null ) ; } standin . setInstallLocation ( homeDir ) ; if ( vmArgs != null ) { standin . setVMArgs ( vmArgs ) ; } IConfigurationElement [ ] libraries = element . getChildren ( "" ) ; IPath [ ] locations = null ; if ( libraries . length > ) { locations = new IPath [ libraries . length ] ; for ( int j = ; j < libraries . length ; j ++ ) { IConfigurationElement library = libraries [ j ] ; String libPathStr = library . getAttribute ( "" ) ; if ( libPathStr == null ) { abort ( MessageFormat . format ( "" , ( Object [ ] ) new String [ ] { id , element . getContributor ( ) . getName ( ) } ) , null ) ; } IPath homePath = new Path ( home ) ; IPath libPath = homePath . append ( substitute ( libPathStr ) ) ; locations [ j ] = libPath ; } } standin . setLibraryLocations ( locations ) ; vmDefs . addVM ( standin ) ; } fgContributedVMs . add ( id ) ; } else { abort ( MessageFormat . format ( "" , ( Object [ ] ) new String [ ] { element . getName ( ) , element . getContributor ( ) . getName ( ) } ) , null ) ; } } catch ( CoreException e ) { LaunchingPlugin . log ( e ) ; } } } private static String substitute ( String expression ) throws CoreException { return VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) . performStringSubstitution ( expression ) ; } private static void abort ( String message , Throwable exception ) throws CoreException { abort ( message , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR , exception ) ; } private static void abort ( String message , int code , Throwable exception ) throws CoreException { throw new CoreException ( new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , code , message , exception ) ) ; } static void fireVMAdded ( IVMInstall vm ) { if ( ! fgInitializingVMs ) { Object [ ] listeners = fgVMListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { IVMInstallChangedListener listener = ( IVMInstallChangedListener ) listeners [ i ] ; listener . vmAdded ( vm ) ; } } } public static void fireVMChanged ( PropertyChangeEvent event ) { Object [ ] listeners = fgVMListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { IVMInstallChangedListener listener = ( IVMInstallChangedListener ) listeners [ i ] ; listener . vmChanged ( event ) ; } } public static void fireVMRemoved ( IVMInstall vm ) { Object [ ] listeners = fgVMListeners . getListeners ( ) ; for ( int i = ; i < listeners . length ; i ++ ) { IVMInstallChangedListener listener = ( IVMInstallChangedListener ) listeners [ i ] ; listener . vmRemoved ( vm ) ; } } public static IPath [ ] getLibraryLocations ( IVMInstall vm ) { IPath [ ] locations = vm . getLibraryLocations ( ) ; if ( locations != null ) return locations ; IPath [ ] dflts = vm . getVMInstallType ( ) . getDefaultLibraryLocations ( vm . getInstallLocation ( ) ) ; IPath [ ] libraryPaths = new IPath [ dflts . length ] ; for ( int i = ; i < dflts . length ; i ++ ) { libraryPaths [ i ] = dflts [ i ] ; if ( ! libraryPaths [ i ] . toFile ( ) . isDirectory ( ) ) { libraryPaths [ i ] = Path . EMPTY ; } } return libraryPaths ; } public static IVMInstall computeVMInstall ( ILaunchConfiguration configuration ) throws CoreException { String rubyVmAttr = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_RUBY_CONTAINER_PATH , ( String ) null ) ; if ( rubyVmAttr == null ) { String type = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE , ( String ) null ) ; if ( type == null ) { IRubyProject proj = getRubyProject ( configuration ) ; if ( proj != null ) { IVMInstall vm = getVMInstall ( proj ) ; if ( vm != null ) { return vm ; } } } else { String name = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , ( String ) null ) ; return resolveVM ( type , name , configuration ) ; } } else { IPath rubyVmPath = Path . fromPortableString ( rubyVmAttr ) ; ILoadpathEntry entry = RubyCore . newContainerEntry ( rubyVmPath ) ; IRuntimeLoadpathEntryResolver2 resolver = getVariableResolver ( rubyVmPath . segment ( ) ) ; if ( resolver != null ) { return resolver . resolveVMInstall ( entry ) ; } resolver = getContainerResolver ( rubyVmPath . segment ( ) ) ; if ( resolver != null ) { return resolver . resolveVMInstall ( entry ) ; } } return getDefaultVMInstall ( ) ; } private static IVMInstall resolveVM ( String type , String name , ILaunchConfiguration configuration ) throws CoreException { IVMInstallType vt = getVMInstallType ( type ) ; if ( vt == null ) { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_Specified_VM_install_type_does_not_exist___0__2 , type ) , null ) ; } IVMInstall vm = null ; if ( name == null ) { IStatus status = new Status ( IStatus . WARNING , LaunchingPlugin . getUniqueIdentifier ( ) , IRubyLaunchConfigurationConstants . ERR_UNSPECIFIED_VM_INSTALL , MessageFormat . format ( LaunchingMessages . JavaRuntime_VM_not_fully_specified_in_launch_configuration__0____missing_VM_name__Reverting_to_default_VM__1 , configuration . getName ( ) ) , null ) ; LaunchingPlugin . log ( status ) ; return getDefaultVMInstall ( ) ; } vm = vt . findVMInstallByName ( name ) ; if ( vm == null ) { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_Specified_VM_install_not_found__type__0___name__1__2 , vt . getName ( ) , name ) , null ) ; } else { return vm ; } return null ; } private static IRuntimeLoadpathEntryResolver2 getVariableResolver ( String variableName ) { return ( IRuntimeLoadpathEntryResolver2 ) getVariableResolvers ( ) . get ( variableName ) ; } private static IRuntimeLoadpathEntryResolver2 getContainerResolver ( String containerId ) { return ( IRuntimeLoadpathEntryResolver2 ) getContainerResolvers ( ) . get ( containerId ) ; } private static Map getVariableResolvers ( ) { if ( fgVariableResolvers == null ) { initializeResolvers ( ) ; } return fgVariableResolvers ; } private static Map getContainerResolvers ( ) { if ( fgContainerResolvers == null ) { initializeResolvers ( ) ; } return fgContainerResolvers ; } private static void initializeResolvers ( ) { IExtensionPoint point = Platform . getExtensionRegistry ( ) . getExtensionPoint ( LaunchingPlugin . PLUGIN_ID , EXTENSION_POINT_RUNTIME_CLASSPATH_ENTRY_RESOLVERS ) ; IConfigurationElement [ ] extensions = point . getConfigurationElements ( ) ; fgVariableResolvers = new HashMap < String , RuntimeLoadpathEntryResolver > ( extensions . length ) ; fgContainerResolvers = new HashMap < String , RuntimeLoadpathEntryResolver > ( extensions . length ) ; fgRuntimeLoadpathEntryResolvers = new HashMap < String , RuntimeLoadpathEntryResolver > ( extensions . length ) ; for ( int i = ; i < extensions . length ; i ++ ) { RuntimeLoadpathEntryResolver res = new RuntimeLoadpathEntryResolver ( extensions [ i ] ) ; String variable = res . getVariableName ( ) ; String container = res . getContainerId ( ) ; String entryId = res . getRuntimeLoadpathEntryId ( ) ; if ( variable != null ) { fgVariableResolvers . put ( variable , res ) ; } if ( container != null ) { fgContainerResolvers . put ( container , res ) ; } if ( entryId != null ) { fgRuntimeLoadpathEntryResolvers . put ( entryId , res ) ; } } } public static IVMInstall getVMInstall ( IRubyProject project ) throws CoreException { IVMInstall vm = null ; ILoadpathEntry [ ] loadpath = project . getRawLoadpath ( ) ; IRuntimeLoadpathEntryResolver resolver = null ; for ( int i = ; i < loadpath . length ; i ++ ) { ILoadpathEntry entry = loadpath [ i ] ; switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_VARIABLE : resolver = getVariableResolver ( entry . getPath ( ) . segment ( ) ) ; if ( resolver != null ) { vm = resolver . resolveVMInstall ( entry ) ; } break ; case ILoadpathEntry . CPE_CONTAINER : resolver = getContainerResolver ( entry . getPath ( ) . segment ( ) ) ; if ( resolver != null ) { vm = resolver . resolveVMInstall ( entry ) ; } break ; } if ( vm != null ) { return vm ; } } return null ; } public static IRubyProject getRubyProject ( ILaunchConfiguration configuration ) throws CoreException { String projectName = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , ( String ) null ) ; if ( ( projectName == null ) || ( projectName . trim ( ) . length ( ) < ) ) { return null ; } IRubyProject javaProject = getRubyModel ( ) . getRubyProject ( projectName ) ; if ( javaProject != null && javaProject . getProject ( ) . exists ( ) && ! javaProject . getProject ( ) . isOpen ( ) ) { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_28 , configuration . getName ( ) , projectName ) , IRubyLaunchConfigurationConstants . ERR_PROJECT_CLOSED , null ) ; } if ( ( javaProject == null ) || ! javaProject . exists ( ) ) { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_Launch_configuration__0__references_non_existing_project__1___1 , configuration . getName ( ) , projectName ) , IRubyLaunchConfigurationConstants . ERR_NOT_A_RUBY_PROJECT , null ) ; } return javaProject ; } private static IRubyModel getRubyModel ( ) { return RubyCore . create ( ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ) ; } public static IRuntimeLoadpathEntry newArchiveRuntimeLoadpathEntry ( IPath path ) { ILoadpathEntry cpe = RubyCore . newLibraryEntry ( path ) ; return newRuntimeLoadpathEntry ( cpe ) ; } private static IRuntimeLoadpathEntry newRuntimeLoadpathEntry ( ILoadpathEntry entry ) { return new RuntimeLoadpathEntry ( entry ) ; } public static IRuntimeLoadpathEntry newRuntimeContainerLoadpathEntry ( IPath path , int loadpathProperty , IRubyProject project ) throws CoreException { ILoadpathEntry cpe = RubyCore . newContainerEntry ( path ) ; RuntimeLoadpathEntry entry = new RuntimeLoadpathEntry ( cpe , loadpathProperty ) ; entry . setRubyProject ( project ) ; return entry ; } public static IRuntimeLoadpathEntry newVariableRuntimeLoadpathEntry ( IPath path ) { ILoadpathEntry cpe = RubyCore . newVariableEntry ( path ) ; return newRuntimeLoadpathEntry ( cpe ) ; } public static IRuntimeLoadpathEntry [ ] computeUnresolvedRuntimeLoadpath ( ILaunchConfiguration configuration ) throws CoreException { return getLoadpathProvider ( configuration ) . computeUnresolvedLoadpath ( configuration ) ; } public static IRuntimeLoadpathProvider getLoadpathProvider ( ILaunchConfiguration configuration ) throws CoreException { String providerId = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_LOADPATH_PROVIDER , ( String ) null ) ; IRuntimeLoadpathProvider provider = null ; if ( providerId == null ) { provider = fgDefaultLoadpathProvider ; } else { provider = ( IRuntimeLoadpathProvider ) getLoadpathProviders ( ) . get ( providerId ) ; if ( provider == null ) { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_26 , providerId ) , null ) ; } } return provider ; } private static Map getLoadpathProviders ( ) { if ( fgPathProviders == null ) { initializeProviders ( ) ; } return fgPathProviders ; } private static void initializeProviders ( ) { IExtensionPoint point = Platform . getExtensionRegistry ( ) . getExtensionPoint ( LaunchingPlugin . PLUGIN_ID , EXTENSION_POINT_RUNTIME_CLASSPATH_PROVIDERS ) ; IConfigurationElement [ ] extensions = point . getConfigurationElements ( ) ; fgPathProviders = new HashMap < String , RuntimeLoadpathProvider > ( extensions . length ) ; for ( int i = ; i < extensions . length ; i ++ ) { RuntimeLoadpathProvider res = new RuntimeLoadpathProvider ( extensions [ i ] ) ; fgPathProviders . put ( res . getIdentifier ( ) , res ) ; } } public static IRuntimeLoadpathEntry newRuntimeLoadpathEntry ( String memento ) throws CoreException { try { Element root = null ; DocumentBuilder parser = LaunchingPlugin . getParser ( ) ; StringReader reader = new StringReader ( memento ) ; InputSource source = new InputSource ( reader ) ; root = parser . parse ( source ) . getDocumentElement ( ) ; String id = root . getAttribute ( "" ) ; if ( id == null || id . length ( ) == ) { return new RuntimeLoadpathEntry ( root ) ; } IRuntimeLoadpathEntry2 entry = LaunchingPlugin . getDefault ( ) . newRuntimeLoadpathEntry ( id ) ; NodeList list = root . getChildNodes ( ) ; for ( int i = ; i < list . getLength ( ) ; i ++ ) { Node node = list . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element element = ( Element ) node ; if ( "" . equals ( element . getNodeName ( ) ) ) { entry . initializeFrom ( element ) ; } } } return entry ; } catch ( SAXException e ) { abort ( LaunchingMessages . JavaRuntime_31 , e ) ; } catch ( IOException e ) { abort ( LaunchingMessages . JavaRuntime_32 , e ) ; } return null ; } public static IRuntimeLoadpathEntry computeRubyVMEntry ( ILaunchConfiguration configuration ) throws CoreException { String rubyVmAttr = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_RUBY_CONTAINER_PATH , ( String ) null ) ; IPath containerPath = null ; if ( rubyVmAttr == null ) { String type = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE , ( String ) null ) ; if ( type == null ) { IRubyProject proj = getRubyProject ( configuration ) ; if ( proj == null ) { containerPath = newDefaultRubyVMContainerPath ( ) ; } else { return computeRubyVMEntry ( proj ) ; } } else { String name = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , ( String ) null ) ; if ( name != null ) { containerPath = newDefaultRubyVMContainerPath ( ) . append ( type ) . append ( name ) ; } } } else { containerPath = Path . fromPortableString ( rubyVmAttr ) ; } if ( containerPath != null ) { return newRuntimeContainerLoadpathEntry ( containerPath , IRuntimeLoadpathEntry . STANDARD_CLASSES ) ; } return null ; } public static IRuntimeLoadpathEntry computeRubyVMEntry ( IRubyProject project ) throws CoreException { ILoadpathEntry [ ] rawClasspath = project . getRawLoadpath ( ) ; IRuntimeLoadpathEntryResolver2 resolver = null ; for ( int i = ; i < rawClasspath . length ; i ++ ) { ILoadpathEntry entry = rawClasspath [ i ] ; switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_VARIABLE : resolver = getVariableResolver ( entry . getPath ( ) . segment ( ) ) ; if ( resolver != null ) { if ( resolver . isVMInstallReference ( entry ) ) { return newRuntimeLoadpathEntry ( entry ) ; } } break ; case ILoadpathEntry . CPE_CONTAINER : resolver = getContainerResolver ( entry . getPath ( ) . segment ( ) ) ; if ( resolver != null ) { if ( resolver . isVMInstallReference ( entry ) ) { ILoadpathContainer container = RubyCore . getLoadpathContainer ( entry . getPath ( ) , project ) ; if ( container != null ) { switch ( container . getKind ( ) ) { case ILoadpathContainer . K_APPLICATION : break ; case ILoadpathContainer . K_DEFAULT_SYSTEM : return newRuntimeContainerLoadpathEntry ( entry . getPath ( ) , IRuntimeLoadpathEntry . STANDARD_CLASSES ) ; case ILoadpathContainer . K_SYSTEM : return newRuntimeContainerLoadpathEntry ( entry . getPath ( ) , IRuntimeLoadpathEntry . BOOTSTRAP_CLASSES ) ; } } } } break ; } } return null ; } public static IPath newDefaultRubyVMContainerPath ( ) { return new Path ( RUBY_CONTAINER ) ; } public static IRuntimeLoadpathEntry newRuntimeContainerLoadpathEntry ( IPath path , int loadpathProperty ) throws CoreException { return newRuntimeContainerLoadpathEntry ( path , loadpathProperty , null ) ; } public static IRuntimeLoadpathEntry [ ] computeUnresolvedRuntimeLoadpath ( IRubyProject project ) throws CoreException { ILoadpathEntry [ ] entries = project . getRawLoadpath ( ) ; List < IRuntimeLoadpathEntry > loadpathEntries = new ArrayList < IRuntimeLoadpathEntry > ( ) ; for ( int i = ; i < entries . length ; i ++ ) { ILoadpathEntry entry = entries [ i ] ; switch ( entry . getEntryKind ( ) ) { case ILoadpathEntry . CPE_CONTAINER : ILoadpathContainer container = RubyCore . getLoadpathContainer ( entry . getPath ( ) , project ) ; if ( container != null ) { switch ( container . getKind ( ) ) { case ILoadpathContainer . K_APPLICATION : break ; case ILoadpathContainer . K_DEFAULT_SYSTEM : loadpathEntries . add ( newRuntimeContainerLoadpathEntry ( container . getPath ( ) , IRuntimeLoadpathEntry . STANDARD_CLASSES , project ) ) ; break ; case ILoadpathContainer . K_SYSTEM : loadpathEntries . add ( newRuntimeContainerLoadpathEntry ( container . getPath ( ) , IRuntimeLoadpathEntry . BOOTSTRAP_CLASSES , project ) ) ; break ; } } break ; case ILoadpathEntry . CPE_VARIABLE : if ( RUBYLIB_VARIABLE . equals ( entry . getPath ( ) . segment ( ) ) ) { IRuntimeLoadpathEntry jre = newVariableRuntimeLoadpathEntry ( entry . getPath ( ) ) ; jre . setLoadpathProperty ( IRuntimeLoadpathEntry . STANDARD_CLASSES ) ; loadpathEntries . add ( jre ) ; } break ; default : break ; } } loadpathEntries . add ( newDefaultProjectLoadpathEntry ( project ) ) ; return loadpathEntries . toArray ( new IRuntimeLoadpathEntry [ loadpathEntries . size ( ) ] ) ; } public static IRuntimeLoadpathEntry newDefaultProjectLoadpathEntry ( IRubyProject project ) { return new DefaultProjectLoadpathEntry ( project ) ; } public static IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , ILaunchConfiguration configuration ) throws CoreException { switch ( entry . getType ( ) ) { case IRuntimeLoadpathEntry . PROJECT : IResource resource = entry . getResource ( ) ; if ( resource instanceof IProject ) { IProject p = ( IProject ) resource ; IRubyProject project = RubyCore . create ( p ) ; if ( project == null || ! p . isOpen ( ) || ! project . exists ( ) ) { return new IRuntimeLoadpathEntry [ ] ; } } else { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_Classpath_references_non_existant_project___0__3 , entry . getPath ( ) . lastSegment ( ) ) , null ) ; } break ; case IRuntimeLoadpathEntry . VARIABLE : IRuntimeLoadpathEntryResolver resolver = getVariableResolver ( entry . getVariableName ( ) ) ; if ( resolver == null ) { IRuntimeLoadpathEntry [ ] resolved = resolveVariableEntry ( entry , null , configuration ) ; if ( resolved != null ) { return resolved ; } break ; } return resolver . resolveRuntimeLoadpathEntry ( entry , configuration ) ; case IRuntimeLoadpathEntry . CONTAINER : resolver = getContainerResolver ( entry . getVariableName ( ) ) ; if ( resolver == null ) { return computeDefaultContainerEntries ( entry , configuration ) ; } return resolver . resolveRuntimeLoadpathEntry ( entry , configuration ) ; case IRuntimeLoadpathEntry . ARCHIVE : String location = entry . getLocation ( ) ; if ( location == null ) { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_Classpath_references_non_existant_archive___0__4 , entry . getPath ( ) . toString ( ) ) , null ) ; } File file = new File ( location ) ; if ( ! file . exists ( ) ) { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_Classpath_references_non_existant_archive___0__4 , entry . getPath ( ) . toString ( ) ) , null ) ; } break ; case IRuntimeLoadpathEntry . OTHER : resolver = getContributedResolver ( ( ( IRuntimeLoadpathEntry2 ) entry ) . getTypeId ( ) ) ; return resolver . resolveRuntimeLoadpathEntry ( entry , configuration ) ; default : break ; } return new IRuntimeLoadpathEntry [ ] { entry } ; } private static IRuntimeLoadpathEntry [ ] computeDefaultContainerEntries ( IRuntimeLoadpathEntry entry , ILaunchConfiguration config ) throws CoreException { IRubyProject project = entry . getRubyProject ( ) ; if ( project == null ) { project = getRubyProject ( config ) ; } return computeDefaultContainerEntries ( entry , project ) ; } private static IRuntimeLoadpathEntry [ ] computeDefaultContainerEntries ( IRuntimeLoadpathEntry entry , IRubyProject project ) throws CoreException { if ( project == null || entry == null ) { return new IRuntimeLoadpathEntry [ ] ; } ILoadpathContainer container = RubyCore . getLoadpathContainer ( entry . getPath ( ) , project ) ; if ( container == null ) { abort ( MessageFormat . format ( LaunchingMessages . JavaRuntime_Could_not_resolve_classpath_container___0__1 , entry . getPath ( ) . toString ( ) ) , null ) ; return null ; } ILoadpathEntry [ ] cpes = container . getLoadpathEntries ( ) ; int property = - ; switch ( container . getKind ( ) ) { case ILoadpathContainer . K_APPLICATION : property = IRuntimeLoadpathEntry . USER_CLASSES ; break ; case ILoadpathContainer . K_DEFAULT_SYSTEM : property = IRuntimeLoadpathEntry . STANDARD_CLASSES ; break ; case ILoadpathContainer . K_SYSTEM : property = IRuntimeLoadpathEntry . BOOTSTRAP_CLASSES ; break ; } List < IRuntimeLoadpathEntry > resolved = new ArrayList < IRuntimeLoadpathEntry > ( cpes . length ) ; List < IRubyProject > projects = fgProjects . get ( ) ; Integer count = fgEntryCount . get ( ) ; if ( projects == null ) { projects = new ArrayList < IRubyProject > ( ) ; fgProjects . set ( projects ) ; count = Integer . valueOf ( ) ; } int intCount = count . intValue ( ) ; intCount ++ ; fgEntryCount . set ( Integer . valueOf ( intCount ) ) ; try { for ( int i = ; i < cpes . length ; i ++ ) { ILoadpathEntry cpe = cpes [ i ] ; if ( cpe . getEntryKind ( ) == ILoadpathEntry . CPE_PROJECT ) { IProject p = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( cpe . getPath ( ) . segment ( ) ) ; IRubyProject rp = RubyCore . create ( p ) ; if ( ! projects . contains ( rp ) ) { projects . add ( rp ) ; IRuntimeLoadpathEntry loadpath = newDefaultProjectLoadpathEntry ( rp ) ; IRuntimeLoadpathEntry [ ] entries = resolveRuntimeLoadpathEntry ( loadpath , rp ) ; for ( int j = ; j < entries . length ; j ++ ) { IRuntimeLoadpathEntry e = entries [ j ] ; if ( ! resolved . contains ( e ) ) { resolved . add ( entries [ j ] ) ; } } } } else { IRuntimeLoadpathEntry e = newRuntimeLoadpathEntry ( cpe ) ; if ( ! resolved . contains ( e ) ) { resolved . add ( e ) ; } } } } finally { intCount -- ; if ( intCount == ) { fgProjects . set ( null ) ; fgEntryCount . set ( null ) ; } else { fgEntryCount . set ( new Integer ( intCount ) ) ; } } IRuntimeLoadpathEntry [ ] result = new IRuntimeLoadpathEntry [ resolved . size ( ) ] ; for ( int i = ; i < result . length ; i ++ ) { result [ i ] = resolved . get ( i ) ; result [ i ] . setLoadpathProperty ( property ) ; } return result ; } private static IRuntimeLoadpathEntry [ ] resolveVariableEntry ( IRuntimeLoadpathEntry entry , IRubyProject project , ILaunchConfiguration configuration ) throws CoreException { IPath archPath = RubyCore . getResolvedVariablePath ( entry . getPath ( ) ) ; if ( archPath != null ) { if ( entry . getPath ( ) . segmentCount ( ) > ) { archPath = archPath . append ( entry . getPath ( ) . removeFirstSegments ( ) ) ; } if ( archPath != null && ! archPath . isEmpty ( ) ) { ILoadpathEntry archEntry = RubyCore . newLibraryEntry ( archPath , entry . getLoadpathEntry ( ) . isExported ( ) ) ; IRuntimeLoadpathEntry runtimeArchEntry = newRuntimeLoadpathEntry ( archEntry ) ; runtimeArchEntry . setLoadpathProperty ( entry . getLoadpathProperty ( ) ) ; if ( configuration == null ) { return resolveRuntimeLoadpathEntry ( runtimeArchEntry , project ) ; } return resolveRuntimeLoadpathEntry ( runtimeArchEntry , configuration ) ; } } return null ; } public static IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , IRubyProject project ) throws CoreException { switch ( entry . getType ( ) ) { case IRuntimeLoadpathEntry . PROJECT : IResource resource = entry . getResource ( ) ; if ( resource instanceof IProject ) { IProject p = ( IProject ) resource ; IRubyProject jp = RubyCore . create ( p ) ; if ( ! ( jp != null && p . isOpen ( ) && jp . exists ( ) ) ) { return new IRuntimeLoadpathEntry [ ] ; } } break ; case IRuntimeLoadpathEntry . VARIABLE : IRuntimeLoadpathEntryResolver resolver = getVariableResolver ( entry . getVariableName ( ) ) ; if ( resolver == null ) { IRuntimeLoadpathEntry [ ] resolved = resolveVariableEntry ( entry , project , null ) ; if ( resolved != null ) { return resolved ; } break ; } return resolver . resolveRuntimeLoadpathEntry ( entry , project ) ; case IRuntimeLoadpathEntry . CONTAINER : resolver = getContainerResolver ( entry . getVariableName ( ) ) ; if ( resolver == null ) { return computeDefaultContainerEntries ( entry , project ) ; } return resolver . resolveRuntimeLoadpathEntry ( entry , project ) ; case IRuntimeLoadpathEntry . OTHER : resolver = getContributedResolver ( ( ( IRuntimeLoadpathEntry2 ) entry ) . getTypeId ( ) ) ; return resolver . resolveRuntimeLoadpathEntry ( entry , project ) ; default : break ; } return new IRuntimeLoadpathEntry [ ] { entry } ; } private static IRuntimeLoadpathEntryResolver getContributedResolver ( String typeId ) { IRuntimeLoadpathEntryResolver resolver = ( IRuntimeLoadpathEntryResolver ) getEntryResolvers ( ) . get ( typeId ) ; if ( resolver == null ) { return new DefaultEntryResolver ( ) ; } return resolver ; } private static Map getEntryResolvers ( ) { if ( fgRuntimeLoadpathEntryResolvers == null ) { initializeResolvers ( ) ; } return fgRuntimeLoadpathEntryResolvers ; } public static IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpath ( IRuntimeLoadpathEntry [ ] entries , ILaunchConfiguration configuration ) throws CoreException { return getLoadpathProvider ( configuration ) . resolveLoadpath ( entries , configuration ) ; } public static void setDefaultVMInstall ( IVMInstall vm , IProgressMonitor monitor , boolean savePreference ) throws CoreException { IVMInstall previous = null ; if ( fgDefaultVMId != null ) { previous = getVMFromCompositeId ( fgDefaultVMId ) ; } fgDefaultVMId = getCompositeIdFromVM ( vm ) ; if ( savePreference ) { saveVMConfiguration ( ) ; } IVMInstall current = null ; if ( fgDefaultVMId != null ) { current = getVMFromCompositeId ( fgDefaultVMId ) ; } if ( previous != current ) { notifyDefaultVMChanged ( previous , current ) ; } } public static File getRI ( ) { return getBinExecutable ( "" ) ; } public static File getRDoc ( ) { return getBinExecutable ( "" ) ; } private static File getBinExecutable ( String command ) { IVMInstall vm = RubyRuntime . getDefaultVMInstall ( ) ; if ( vm == null ) return null ; File installLocation = vm . getInstallLocation ( ) ; String path = installLocation . getAbsolutePath ( ) ; if ( ! installLocation . getName ( ) . equals ( "" ) ) { path += File . separator + "" ; } path += File . separator + command ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) { path += "" ; File file = new File ( path ) ; if ( file . exists ( ) ) return file ; path = path . substring ( , path . length ( ) - ) + "" ; } File file = new File ( path ) ; if ( file . exists ( ) ) return file ; String version = vm . getRubyVersion ( ) ; if ( version == null || version . length ( ) < ) return file ; version = version . substring ( , ) ; path = installLocation . getAbsolutePath ( ) ; if ( ! installLocation . getName ( ) . equals ( "" ) ) { path += File . separator + "" ; } path = File . separator + command + version ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) { path += "" ; } return new File ( path ) ; } public static File getIRB ( ) { return getBinExecutable ( "" ) ; } private static ILaunchManager getLaunchManager ( ) { return DebugPlugin . getDefault ( ) . getLaunchManager ( ) ; } public static ILaunchConfigurationWorkingCopy createBasicLaunch ( String file , String args , IProject project ) throws CoreException { return createBasicLaunch ( file , args , project , project . getLocation ( ) . toOSString ( ) ) ; } public static ILaunchConfigurationWorkingCopy createBasicLaunch ( String file , String args , IProject project , String workingDirectory ) throws CoreException { ILaunchConfigurationType configType = getLaunchManager ( ) . getLaunchConfigurationType ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ; ILaunchConfigurationWorkingCopy wc = configType . newInstance ( null , generateUniqueLaunchConfigurationNameFrom ( file ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , file ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROGRAM_ARGUMENTS , args ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , workingDirectory ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_REQUIRES_REFRESH , true ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , project . getName ( ) ) ; wc . setAttribute ( DebugPlugin . ATTR_CONSOLE_ENCODING , "" ) ; return wc ; } public static boolean currentVMIsJRuby ( ) { if ( RubyRuntime . getDefaultVMInstall ( ) == null ) return false ; if ( RubyRuntime . getDefaultVMInstall ( ) . getVMInstallType ( ) == null ) return false ; if ( RubyRuntime . getDefaultVMInstall ( ) . getVMInstallType ( ) . getId ( ) == null ) return false ; return RubyRuntime . getDefaultVMInstall ( ) . getVMInstallType ( ) . getId ( ) . equals ( RubyRuntime . JRUBY_VMTYPE ) ; } public static IPath checkInterpreterBin ( String exe ) { IVMInstall vm = getDefaultVMInstall ( ) ; if ( vm == null ) return null ; File installLocation = vm . getInstallLocation ( ) ; if ( installLocation == null ) return null ; return checkAnyInterpreterBin ( exe , installLocation ) ; } public static IPath checkAnyInterpreterBin ( String exe , File installLocation ) { IPath path = new Path ( installLocation . getAbsolutePath ( ) ) ; if ( ! installLocation . getName ( ) . equals ( "" ) ) { path = path . append ( "" ) ; } path = path . append ( exe ) ; if ( path . toFile ( ) . exists ( ) ) return path ; return null ; } public static boolean currentVMIsCygwin ( ) { if ( RubyRuntime . getDefaultVMInstall ( ) == null ) return false ; if ( RubyRuntime . getDefaultVMInstall ( ) . getPlatform ( ) == null ) return false ; return RubyRuntime . getDefaultVMInstall ( ) . getPlatform ( ) . equals ( IVMInstall . CYWGIN_PLATFORM ) ; } public static String launchInBackgroundAndRead ( final ILaunchConfiguration config , final File file ) { try { ILaunchConfigurationWorkingCopy wc = config . getWorkingCopy ( ) ; wc . setAttribute ( IDebugUIConstants . ATTR_LAUNCH_IN_BACKGROUND , true ) ; wc . setAttribute ( IDebugUIConstants . ATTR_CAPTURE_IN_CONSOLE , false ) ; wc . setAttribute ( IDebugUIConstants . ATTR_CAPTURE_IN_FILE , file . getAbsolutePath ( ) ) ; wc . setAttribute ( IDebugUIConstants . ATTR_PRIVATE , true ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FORCE_NO_CONSOLE , true ) ; ILaunchConfiguration config2 = wc . doSave ( ) ; ILaunch launch = config2 . launch ( ILaunchManager . RUN_MODE , new NullProgressMonitor ( ) ) ; IProcess iproc = launch . getProcesses ( ) [ ] ; IStreamMonitor stdOut = iproc . getStreamsProxy ( ) . getOutputStreamMonitor ( ) ; StreamListener listener = new StreamListener ( ) ; stdOut . addListener ( listener ) ; while ( ! launch . isTerminated ( ) ) { Thread . yield ( ) ; } return readFile ( file ) ; } catch ( Exception e ) { LaunchingPlugin . log ( e ) ; } return null ; } private static String readFile ( File file ) { try { return new String ( Util . getFileCharContent ( file , null ) ) ; } catch ( FileNotFoundException e ) { LaunchingPlugin . log ( e ) ; } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } return null ; } private static class StreamListener implements IStreamListener { private StringBuffer buf ; public StreamListener ( ) { buf = new StringBuffer ( ) ; } public void streamAppended ( final String text , IStreamMonitor monitor ) { buf . append ( text ) ; } public String getContents ( ) { return buf . toString ( ) ; } } public static IVMConnector getVMConnector ( String id ) { return LaunchingPlugin . getDefault ( ) . getVMConnector ( id ) ; } public static IVMConnector [ ] getVMConnectors ( ) { return LaunchingPlugin . getDefault ( ) . getVMConnectors ( ) ; } public static IVMConnector getDefaultVMConnector ( ) { String id = getDefaultVMConnectorId ( ) ; IVMConnector connector = null ; if ( id != null ) { connector = getVMConnector ( id ) ; } if ( connector == null ) { connector = new SocketAttachConnector ( ) ; } return connector ; } private static String getDefaultVMConnectorId ( ) { initializeVMs ( ) ; return fgDefaultVMConnectorId ; } public static String generateUniqueLaunchConfigurationNameFrom ( String fullFileName ) { fullFileName = fullFileName . replace ( '' , '' ) ; fullFileName = fullFileName . replace ( '' , '' ) ; fullFileName = fullFileName . replace ( '' , '' ) ; return getLaunchManager ( ) . generateUniqueLaunchConfigurationNameFrom ( fullFileName ) ; } } package org . rubypeople . rdt . launching ; import java . util . Map ; import org . rubypeople . rdt . internal . launching . LaunchingMessages ; public class VMRunnerConfiguration { private String fFileToLaunch ; private String [ ] fVMArgs ; private String [ ] fProgramArgs ; private String [ ] fEnvironment ; private String [ ] fLoadPath ; private String fWorkingDirectory ; private Map fVMSpecificAttributesMap ; private boolean fResume = true ; private boolean fIsSudo ; private String fSudoMessage ; private static final String [ ] fgEmpty = new String [ ] ; public VMRunnerConfiguration ( String fileToLaunch , String [ ] loadPath ) { if ( fileToLaunch == null ) { throw new IllegalArgumentException ( LaunchingMessages . vmRunnerConfig_assert_classNotNull ) ; } if ( loadPath == null ) { throw new IllegalArgumentException ( LaunchingMessages . vmRunnerConfig_assert_classPathNotNull ) ; } fFileToLaunch = fileToLaunch ; fLoadPath = loadPath ; } public void setVMSpecificAttributesMap ( Map map ) { fVMSpecificAttributesMap = map ; } public void setVMArguments ( String [ ] args ) { if ( args == null ) { throw new IllegalArgumentException ( LaunchingMessages . vmRunnerConfig_assert_vmArgsNotNull ) ; } fVMArgs = args ; } public void setProgramArguments ( String [ ] args ) { if ( args == null ) { throw new IllegalArgumentException ( LaunchingMessages . vmRunnerConfig_assert_programArgsNotNull ) ; } fProgramArgs = args ; } public void setEnvironment ( String [ ] environment ) { fEnvironment = environment ; } public Map getVMSpecificAttributesMap ( ) { return fVMSpecificAttributesMap ; } public String getFileToLaunch ( ) { return fFileToLaunch ; } public String [ ] getLoadPath ( ) { return fLoadPath ; } public String [ ] getVMArguments ( ) { if ( fVMArgs == null ) { return fgEmpty ; } return fVMArgs ; } public String [ ] getProgramArguments ( ) { if ( fProgramArgs == null ) { return fgEmpty ; } return fProgramArgs ; } public String [ ] getEnvironment ( ) { return fEnvironment ; } public void setWorkingDirectory ( String path ) { fWorkingDirectory = path ; } public String getWorkingDirectory ( ) { return fWorkingDirectory ; } public void setResumeOnStartup ( boolean resume ) { fResume = resume ; } public boolean isResumeOnStartup ( ) { return fResume ; } public void setIsSudo ( boolean isSudo ) { fIsSudo = isSudo ; } public boolean isSudo ( ) { return fIsSudo ; } public void setSudoMessage ( String message ) { fSudoMessage = message ; } public String getSudoMessage ( ) { if ( fSudoMessage == null ) return "" ; return fSudoMessage ; } } package org . rubypeople . rdt . launching ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; public interface IRubyLaunchConfigurationConstants { public static final String ID_RUBY_APPLICATION = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ID_SOCKET_ATTACH_VM_CONNECTOR = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final int ERR_UNSPECIFIED_FILE_NAME = ; public static final int ERR_UNSPECIFIED_VM_INSTALL = ; public static final int ERR_VM_INSTALL_DOES_NOT_EXIST = ; public static final int ERR_VM_RUNNER_DOES_NOT_EXIST = ; public static final int ERR_NOT_A_RUBY_PROJECT = ; public static final int ERR_WORKING_DIRECTORY_DOES_NOT_EXIST = ; public static final int ERR_UNSPECIFIED_HOSTNAME = ; public static final int ERR_UNSPECIFIED_PORT = ; public static final int ERR_REMOTE_VM_CONNECTION_FAILED = ; public static final int ERR_NO_SOCKET_AVAILABLE = ; public static final int ERR_CONNECTOR_NOT_AVAILABLE = ; public static final int ERR_CONNECTION_FAILED = ; public static final int ERR_PROJECT_CLOSED = ; public static final int ERR_INTERNAL_ERROR = ; public static final String ID_RUBY_PROCESS_TYPE = "" ; public static final String ATTR_RUBY_COMMAND = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_PROJECT_NAME = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_VM_CONNECTOR = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_RUBY_CONTAINER_PATH = RubyRuntime . RUBY_CONTAINER ; public static final String ATTR_VM_INSTALL_NAME = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_VM_INSTALL_TYPE = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_PROGRAM_ARGUMENTS = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_VM_ARGUMENTS = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_WORKING_DIRECTORY = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_VM_INSTALL_TYPE_SPECIFIC_ATTRS_MAP = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_FILE_NAME = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_LOADPATH_PROVIDER = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_DEFAULT_LOADPATH = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_LOADPATH = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_IS_SUDO = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_REQUIRES_REFRESH = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_FORCE_NO_CONSOLE = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_USE_TERMINAL = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_TERMINAL_COMMAND = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_SUDO_MESSAGE = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ATTR_CONNECT_MAP = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String ID_STANDARD_VM_TYPE = "" ; } package org . rubypeople . rdt . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . debug . core . ILaunch ; public interface IVMRunner { public void run ( VMRunnerConfiguration configuration , ILaunch launch , IProgressMonitor monitor ) throws CoreException ; public void setVMInstall ( IVMInstall vm ) ; } package org . rubypeople . rdt . launching ; import java . util . EventObject ; public class PropertyChangeEvent extends EventObject { private static final long serialVersionUID = ; private String propertyName ; private Object oldValue ; private Object newValue ; public PropertyChangeEvent ( Object source , String property , Object oldValue , Object newValue ) { super ( source ) ; if ( property == null ) { throw new IllegalArgumentException ( ) ; } this . propertyName = property ; this . oldValue = oldValue ; this . newValue = newValue ; } public String getProperty ( ) { return propertyName ; } public Object getNewValue ( ) { return newValue ; } public Object getOldValue ( ) { return oldValue ; } } package org . rubypeople . rdt . launching ; import org . eclipse . core . runtime . IPath ; public interface IRuntimeContainerComparator { public boolean isDuplicate ( IPath containerPath ) ; } package org . rubypeople . rdt . launching ; import java . io . File ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . rubypeople . rdt . internal . launching . LaunchingMessages ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; public abstract class AbstractVMInstall implements IVMInstall { private IVMInstallType fType ; private String fId ; private String fName ; private File fInstallLocation ; protected IPath [ ] fSystemLibraryDescriptions ; private String fVMArgs ; private static final String PREF_VM_INSTALL_SYSTEM_PROPERTY = "" ; protected boolean fNotify = true ; private HashMap < String , IVMRunner > fgVMRunners ; public AbstractVMInstall ( IVMInstallType type , String id ) { if ( type == null ) throw new IllegalArgumentException ( LaunchingMessages . vmInstall_assert_typeNotNull ) ; if ( id == null ) throw new IllegalArgumentException ( LaunchingMessages . vmInstall_assert_idNotNull ) ; fType = type ; fId = id ; } public String getId ( ) { return fId ; } public String getName ( ) { return fName ; } public void setName ( String name ) { if ( ! name . equals ( fName ) ) { PropertyChangeEvent event = new PropertyChangeEvent ( this , IVMInstallChangedListener . PROPERTY_NAME , fName , name ) ; fName = name ; if ( fNotify ) { RubyRuntime . fireVMChanged ( event ) ; } } } public File getInstallLocation ( ) { return fInstallLocation ; } public void setInstallLocation ( File installLocation ) { if ( ! installLocation . equals ( fInstallLocation ) ) { PropertyChangeEvent event = new PropertyChangeEvent ( this , IVMInstallChangedListener . PROPERTY_INSTALL_LOCATION , fInstallLocation , installLocation ) ; fInstallLocation = installLocation ; if ( fNotify ) { RubyRuntime . fireVMChanged ( event ) ; } } } public IVMInstallType getVMInstallType ( ) { return fType ; } public IVMRunner getVMRunner ( String mode ) { return null ; } public IPath [ ] getLibraryLocations ( ) { return fSystemLibraryDescriptions ; } public void setLibraryLocations ( IPath [ ] locations ) { if ( locations == fSystemLibraryDescriptions ) { return ; } IPath [ ] newLocations = locations ; if ( newLocations == null ) { newLocations = getVMInstallType ( ) . getDefaultLibraryLocations ( getInstallLocation ( ) ) ; } IPath [ ] prevLocations = fSystemLibraryDescriptions ; if ( prevLocations == null ) { prevLocations = getVMInstallType ( ) . getDefaultLibraryLocations ( getInstallLocation ( ) ) ; } if ( newLocations . length == prevLocations . length ) { int i = ; boolean equal = true ; while ( i < newLocations . length && equal ) { equal = newLocations [ i ] . equals ( prevLocations [ i ] ) ; i ++ ; } if ( equal ) { return ; } } PropertyChangeEvent event = new PropertyChangeEvent ( this , IVMInstallChangedListener . PROPERTY_LIBRARY_LOCATIONS , prevLocations , newLocations ) ; fSystemLibraryDescriptions = locations ; if ( fNotify ) { RubyRuntime . fireVMChanged ( event ) ; } } protected void setNotify ( boolean notify ) { fNotify = notify ; } public boolean equals ( Object object ) { if ( object instanceof IVMInstall ) { IVMInstall vm = ( IVMInstall ) object ; return getVMInstallType ( ) . equals ( vm . getVMInstallType ( ) ) && getId ( ) . equals ( vm . getId ( ) ) ; } return false ; } public int hashCode ( ) { return getVMInstallType ( ) . hashCode ( ) + getId ( ) . hashCode ( ) ; } public String [ ] getVMArguments ( ) { String args = getVMArgs ( ) ; if ( args == null ) { return null ; } ExecutionArguments ex = new ExecutionArguments ( args , "" ) ; return ex . getVMArgumentsArray ( ) ; } public void setVMArguments ( String [ ] vmArgs ) { if ( vmArgs == null ) { setVMArgs ( null ) ; } else { StringBuffer buf = new StringBuffer ( ) ; for ( int i = ; i < vmArgs . length ; i ++ ) { String string = vmArgs [ i ] ; buf . append ( string ) ; buf . append ( "" ) ; } setVMArgs ( buf . toString ( ) . trim ( ) ) ; } } public String getVMArgs ( ) { return fVMArgs ; } public void setVMArgs ( String vmArgs ) { if ( fVMArgs == null ) { if ( vmArgs == null ) { return ; } } else if ( fVMArgs . equals ( vmArgs ) ) { return ; } PropertyChangeEvent event = new PropertyChangeEvent ( this , IVMInstallChangedListener . PROPERTY_VM_ARGUMENTS , fVMArgs , vmArgs ) ; fVMArgs = vmArgs ; if ( fNotify ) { RubyRuntime . fireVMChanged ( event ) ; } } public String getRubyVersion ( ) { return null ; } private String getSystemPropertyKey ( String property ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( PREF_VM_INSTALL_SYSTEM_PROPERTY ) ; buffer . append ( "" ) ; buffer . append ( getVMInstallType ( ) . getId ( ) ) ; buffer . append ( "" ) ; buffer . append ( getId ( ) ) ; buffer . append ( "" ) ; buffer . append ( property ) ; return buffer . toString ( ) ; } protected void abort ( String message , Throwable exception , int code ) throws CoreException { throw new CoreException ( new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , code , message , exception ) ) ; } protected IVMRunner getVMRunner ( IVMInstall vm , String mode ) { Map < String , IVMRunner > runners = getVMRunners ( ) ; IVMRunner runner = runners . get ( mode ) ; if ( runner == null ) return null ; runner . setVMInstall ( vm ) ; return runner ; } private Map < String , IVMRunner > getVMRunners ( ) { if ( fgVMRunners == null ) { IExtensionPoint extensionPoint = Platform . getExtensionRegistry ( ) . getExtensionPoint ( LaunchingPlugin . PLUGIN_ID , "" ) ; IConfigurationElement [ ] configs = extensionPoint . getConfigurationElements ( ) ; fgVMRunners = new HashMap < String , IVMRunner > ( ) ; for ( int i = ; i < configs . length ; i ++ ) { try { String vmType = configs [ i ] . getAttribute ( "" ) ; if ( vmType . equals ( fType . getId ( ) ) ) { String mode = configs [ i ] . getAttribute ( "" ) ; IVMRunner runner = ( IVMRunner ) configs [ i ] . createExecutableExtension ( "" ) ; fgVMRunners . put ( mode , runner ) ; } } catch ( CoreException e ) { LaunchingPlugin . log ( e ) ; } } } return fgVMRunners ; } } package org . rubypeople . rdt . launching ; import java . io . File ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . variables . VariablesPlugin ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . model . LaunchConfigurationDelegate ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . launching . LaunchingMessages ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; public abstract class AbstractRubyLaunchConfigurationDelegate extends LaunchConfigurationDelegate { protected void abort ( String message , Throwable exception , int code ) throws CoreException { throw new CoreException ( new Status ( IStatus . ERROR , LaunchingPlugin . getUniqueIdentifier ( ) , code , message , exception ) ) ; } public String getVMArguments ( ILaunchConfiguration configuration ) throws CoreException { String arguments = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_ARGUMENTS , "" ) ; String args = VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) . performStringSubstitution ( arguments ) ; return args ; } public String getProgramArguments ( ILaunchConfiguration configuration ) throws CoreException { String arguments = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROGRAM_ARGUMENTS , "" ) ; return VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) . performStringSubstitution ( arguments ) ; } public String [ ] getEnvironment ( ILaunchConfiguration configuration ) throws CoreException { return DebugPlugin . getDefault ( ) . getLaunchManager ( ) . getEnvironment ( configuration ) ; } public File verifyWorkingDirectory ( ILaunchConfiguration configuration ) throws CoreException { IPath path = getWorkingDirectoryPath ( configuration ) ; if ( path == null ) { File dir = getDefaultWorkingDirectory ( configuration ) ; if ( dir != null ) { if ( ! dir . isDirectory ( ) ) { abort ( MessageFormat . format ( LaunchingMessages . AbstractJavaLaunchConfigurationDelegate_Working_directory_does_not_exist___0__12 , dir . toString ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_WORKING_DIRECTORY_DOES_NOT_EXIST ) ; } return dir ; } } else { if ( path . isAbsolute ( ) ) { File dir = new File ( path . toOSString ( ) ) ; if ( dir . isDirectory ( ) ) { return dir ; } IResource res = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( path ) ; if ( res instanceof IContainer && res . exists ( ) ) { return res . getLocation ( ) . toFile ( ) ; } abort ( MessageFormat . format ( LaunchingMessages . AbstractJavaLaunchConfigurationDelegate_Working_directory_does_not_exist___0__12 , path . toString ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_WORKING_DIRECTORY_DOES_NOT_EXIST ) ; } else { IResource res = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . findMember ( path ) ; if ( res instanceof IContainer && res . exists ( ) ) { return res . getLocation ( ) . toFile ( ) ; } abort ( MessageFormat . format ( LaunchingMessages . AbstractJavaLaunchConfigurationDelegate_Working_directory_does_not_exist___0__12 , path . toString ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_WORKING_DIRECTORY_DOES_NOT_EXIST ) ; } } return null ; } public IPath getWorkingDirectoryPath ( ILaunchConfiguration configuration ) throws CoreException { String path = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , ( String ) null ) ; if ( path != null && path . length ( ) > ) { path = VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) . performStringSubstitution ( path ) ; return new Path ( path ) ; } return null ; } protected File getDefaultWorkingDirectory ( ILaunchConfiguration configuration ) throws CoreException { IRubyProject rp = getRubyProject ( configuration ) ; if ( rp != null ) { IProject p = rp . getProject ( ) ; return p . getLocation ( ) . toFile ( ) ; } return null ; } public IRubyProject getRubyProject ( ILaunchConfiguration configuration ) throws CoreException { String projectName = getRubyProjectName ( configuration ) ; if ( projectName != null ) { projectName = projectName . trim ( ) ; if ( projectName . length ( ) > ) { IProject project = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; IRubyProject rubyProject = RubyCore . create ( project ) ; if ( rubyProject != null && rubyProject . exists ( ) ) { return rubyProject ; } } } return null ; } public String getRubyProjectName ( ILaunchConfiguration configuration ) throws CoreException { return configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , ( String ) null ) ; } public Map getVMSpecificAttributesMap ( ILaunchConfiguration configuration ) throws CoreException { Map map = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE_SPECIFIC_ATTRS_MAP , ( Map ) null ) ; return map ; } public IVMRunner getVMRunner ( ILaunchConfiguration configuration , String mode ) throws CoreException { IVMInstall vm = verifyVMInstall ( configuration ) ; IVMRunner runner = vm . getVMRunner ( mode ) ; if ( runner == null ) { abort ( MessageFormat . format ( LaunchingMessages . JavaLocalApplicationLaunchConfigurationDelegate_0 , vm . getName ( ) , mode ) , null , IRubyLaunchConfigurationConstants . ERR_VM_RUNNER_DOES_NOT_EXIST ) ; } return runner ; } public IVMInstall verifyVMInstall ( ILaunchConfiguration configuration ) throws CoreException { IVMInstall vm = getVMInstall ( configuration ) ; if ( vm == null ) { abort ( LaunchingMessages . AbstractJavaLaunchConfigurationDelegate_The_specified_JRE_installation_does_not_exist_4 , null , IRubyLaunchConfigurationConstants . ERR_VM_INSTALL_DOES_NOT_EXIST ) ; } File location = vm . getInstallLocation ( ) ; if ( location == null ) { abort ( MessageFormat . format ( LaunchingMessages . AbstractJavaLaunchConfigurationDelegate_JRE_home_directory_not_specified_for__0__5 , vm . getName ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_VM_INSTALL_DOES_NOT_EXIST ) ; } if ( ! location . exists ( ) ) { abort ( MessageFormat . format ( LaunchingMessages . AbstractJavaLaunchConfigurationDelegate_JRE_home_directory_for__0__does_not_exist___1__6 , vm . getName ( ) , location . getAbsolutePath ( ) ) , null , IRubyLaunchConfigurationConstants . ERR_VM_INSTALL_DOES_NOT_EXIST ) ; } return vm ; } public IVMInstall getVMInstall ( ILaunchConfiguration configuration ) throws CoreException { return RubyRuntime . computeVMInstall ( configuration ) ; } public String verifyFileToLaunch ( ILaunchConfiguration configuration ) throws CoreException { String name = getFileToLaunch ( configuration ) ; if ( name == null ) { abort ( LaunchingMessages . AbstractJavaLaunchConfigurationDelegate_Main_type_not_specified_11 , null , IRubyLaunchConfigurationConstants . ERR_UNSPECIFIED_FILE_NAME ) ; } File file = new File ( name ) ; if ( file . exists ( ) && ! file . isDirectory ( ) ) { return name ; } IPath workingDir = getWorkingDirectoryPath ( configuration ) ; if ( workingDir != null ) { IPath fileToLaunch = workingDir . append ( name ) ; file = fileToLaunch . toFile ( ) ; if ( file . exists ( ) && ! file . isDirectory ( ) ) return name ; } IRubyProject project = getRubyProject ( configuration ) ; if ( project != null ) { IPath fileToLaunch = project . getProject ( ) . getLocation ( ) . append ( name ) ; file = fileToLaunch . toFile ( ) ; if ( file . exists ( ) && ! file . isDirectory ( ) ) return fileToLaunch . toOSString ( ) ; } abort ( "" + name + "" , null , IRubyLaunchConfigurationConstants . ERR_UNSPECIFIED_FILE_NAME ) ; return null ; } public String getFileToLaunch ( ILaunchConfiguration configuration ) throws CoreException { String mainType = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , ( String ) null ) ; if ( mainType == null ) { return null ; } return VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) . performStringSubstitution ( mainType ) ; } protected void setDefaultSourceLocator ( ILaunch launch , ILaunchConfiguration configuration ) { } public String [ ] getLoadpath ( ILaunchConfiguration configuration ) throws CoreException { IRuntimeLoadpathEntry [ ] entries = RubyRuntime . computeUnresolvedRuntimeLoadpath ( configuration ) ; entries = RubyRuntime . resolveRuntimeLoadpath ( entries , configuration ) ; List < String > userEntries = new ArrayList < String > ( entries . length ) ; for ( int i = ; i < entries . length ; i ++ ) { if ( entries [ i ] . getLoadpathProperty ( ) == IRuntimeLoadpathEntry . USER_CLASSES ) { String location = entries [ i ] . getLocation ( ) ; if ( location != null ) { userEntries . add ( location ) ; } } } return userEntries . toArray ( new String [ userEntries . size ( ) ] ) ; } public boolean getIsSudo ( ILaunchConfiguration configuration ) throws CoreException { return configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_IS_SUDO , false ) ; } public String getSudoMessage ( ILaunchConfiguration configuration ) throws CoreException { return configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_SUDO_MESSAGE , ( String ) null ) ; } public String getVMConnectorId ( ILaunchConfiguration configuration ) throws CoreException { return configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_CONNECTOR , ( String ) null ) ; } } package org . rubypeople . rdt . launching ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . debug . core . DebugPlugin ; public class ExecutionArguments { private String fVMArgs ; private String fProgramArgs ; public ExecutionArguments ( String vmArgs , String programArgs ) { if ( vmArgs == null || programArgs == null ) throw new IllegalArgumentException ( ) ; fVMArgs = vmArgs ; fProgramArgs = programArgs ; } public String getVMArguments ( ) { return fVMArgs ; } public String getProgramArguments ( ) { return fProgramArgs ; } public String [ ] getVMArgumentsArray ( ) { String [ ] raw = DebugPlugin . parseArguments ( fVMArgs ) ; List < String > modified = new ArrayList < String > ( ) ; for ( int i = ; i < raw . length ; i ++ ) { String arg = raw [ i ] ; if ( ( arg . equals ( "" ) || arg . equals ( "" ) || arg . equals ( "" ) ) && ( raw . length > ( i + ) ) ) { modified . add ( arg + "" + raw [ i + ] ) ; i ++ ; } else { modified . add ( arg ) ; } } return modified . toArray ( new String [ modified . size ( ) ] ) ; } public String [ ] getProgramArgumentsArray ( ) { return DebugPlugin . parseArguments ( fProgramArgs ) ; } } package org . rubypeople . rdt . launching ; import java . io . File ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . IProcess ; import org . rubypeople . rdt . internal . launching . LaunchingMessages ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; public abstract class AbstractVMRunner implements IVMRunner { protected IVMInstall fVMInstance ; protected void abort ( String message , Throwable exception , int code ) throws CoreException { throw new CoreException ( new Status ( IStatus . ERROR , getPluginIdentifier ( ) , code , message , exception ) ) ; } protected abstract String getPluginIdentifier ( ) ; public void setVMInstall ( IVMInstall vm ) { fVMInstance = vm ; } protected Process exec ( String [ ] cmdLine , File workingDirectory ) throws CoreException { if ( cmdLine == null ) { abort ( "" , null , - ) ; } List < String > newCmdLine = new ArrayList < String > ( ) ; for ( String string : cmdLine ) { if ( string == null ) { LaunchingPlugin . log ( new Throwable ( "" + cmdLine ) ) ; } else { newCmdLine . add ( string ) ; } } cmdLine = newCmdLine . toArray ( new String [ newCmdLine . size ( ) ] ) ; LaunchingPlugin . info ( getDebugLogStatement ( cmdLine , workingDirectory ) ) ; return DebugPlugin . exec ( cmdLine , workingDirectory ) ; } private String getDebugLogStatement ( String [ ] cmdLine , File workingDirectory ) { StringBuilder builder = new StringBuilder ( "" ) ; builder . append ( getCmdLineAsString ( cmdLine ) ) ; if ( workingDirectory != null ) builder . append ( "" ) . append ( workingDirectory ) ; return builder . toString ( ) ; } protected Process exec ( String [ ] cmdLine , File workingDirectory , String [ ] envp ) throws CoreException { if ( cmdLine == null ) { abort ( "" , null , - ) ; } List < String > newCmdLine = new ArrayList < String > ( ) ; for ( String string : cmdLine ) { if ( string == null ) { LaunchingPlugin . log ( new Throwable ( "" + cmdLine ) ) ; } else { newCmdLine . add ( string ) ; } } cmdLine = newCmdLine . toArray ( new String [ newCmdLine . size ( ) ] ) ; if ( envp == null ) return exec ( cmdLine , workingDirectory ) ; LaunchingPlugin . info ( getDebugLogStatement ( cmdLine , workingDirectory ) ) ; return DebugPlugin . exec ( cmdLine , workingDirectory , envp ) ; } protected String getCmdLineAsString ( String [ ] cmdLine ) { if ( cmdLine == null ) { return "" ; } StringBuffer buff = new StringBuffer ( ) ; for ( int i = , numStrings = cmdLine . length ; i < numStrings ; i ++ ) { String value = cmdLine [ i ] ; if ( value == null ) continue ; if ( value . indexOf ( '' ) != - && ! value . startsWith ( "" ) ) { if ( ! value . startsWith ( "" ) ) { value = "" + value ; } if ( ! value . endsWith ( "" ) ) { value = value + "" ; } } buff . append ( value ) ; buff . append ( '' ) ; } return buff . toString ( ) . trim ( ) ; } protected Map < String , String > getDefaultProcessMap ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( IProcess . ATTR_PROCESS_TYPE , IRubyLaunchConfigurationConstants . ID_RUBY_PROCESS_TYPE ) ; return map ; } protected IProcess newProcess ( ILaunch launch , Process p , String label , Map < String , String > attributes ) throws CoreException { IProcess process = DebugPlugin . newProcess ( launch , p , label , attributes ) ; if ( process == null ) { p . destroy ( ) ; abort ( LaunchingMessages . AbstractVMRunner_0 , null , IRubyLaunchConfigurationConstants . ERR_INTERNAL_ERROR ) ; } return process ; } protected String [ ] combineVmArgs ( VMRunnerConfiguration configuration , IVMInstall vmInstall ) { String [ ] launchVMArgs = configuration . getVMArguments ( ) ; String [ ] vmVMArgs = vmInstall . getVMArguments ( ) ; if ( vmVMArgs == null || vmVMArgs . length == ) { return launchVMArgs ; } String [ ] allVMArgs = new String [ launchVMArgs . length + vmVMArgs . length ] ; System . arraycopy ( launchVMArgs , , allVMArgs , , launchVMArgs . length ) ; System . arraycopy ( vmVMArgs , , allVMArgs , launchVMArgs . length , vmVMArgs . length ) ; return allVMArgs ; } } package org . rubypeople . rdt . launching ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . core . IRubyProject ; public class StandardLoadpathProvider implements IRuntimeLoadpathProvider { public IRuntimeLoadpathEntry [ ] computeUnresolvedLoadpath ( ILaunchConfiguration configuration ) throws CoreException { boolean useDefault = configuration . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_DEFAULT_LOADPATH , true ) ; if ( useDefault ) { IRubyProject proj = RubyRuntime . getRubyProject ( configuration ) ; IRuntimeLoadpathEntry jreEntry = RubyRuntime . computeRubyVMEntry ( configuration ) ; if ( proj == null ) { if ( jreEntry == null ) { return new IRuntimeLoadpathEntry [ ] ; } return new IRuntimeLoadpathEntry [ ] { jreEntry } ; } IRuntimeLoadpathEntry [ ] entries = RubyRuntime . computeUnresolvedRuntimeLoadpath ( proj ) ; IRuntimeLoadpathEntry projEntry = RubyRuntime . computeRubyVMEntry ( proj ) ; if ( jreEntry != null && projEntry != null ) { if ( ! jreEntry . equals ( projEntry ) ) { for ( int i = ; i < entries . length ; i ++ ) { IRuntimeLoadpathEntry entry = entries [ i ] ; if ( entry . equals ( projEntry ) ) { entries [ i ] = jreEntry ; return entries ; } } } } return entries ; } return recoverRuntimePath ( configuration , IRubyLaunchConfigurationConstants . ATTR_LOADPATH ) ; } public IRuntimeLoadpathEntry [ ] resolveLoadpath ( IRuntimeLoadpathEntry [ ] entries , ILaunchConfiguration configuration ) throws CoreException { List all = new ArrayList ( entries . length ) ; for ( int i = ; i < entries . length ; i ++ ) { IRuntimeLoadpathEntry [ ] resolved = RubyRuntime . resolveRuntimeLoadpathEntry ( entries [ i ] , configuration ) ; for ( int j = ; j < resolved . length ; j ++ ) { all . add ( resolved [ j ] ) ; } } return ( IRuntimeLoadpathEntry [ ] ) all . toArray ( new IRuntimeLoadpathEntry [ all . size ( ) ] ) ; } protected IRuntimeLoadpathEntry [ ] recoverRuntimePath ( ILaunchConfiguration configuration , String attribute ) throws CoreException { List < String > entries = configuration . getAttribute ( attribute , Collections . EMPTY_LIST ) ; IRuntimeLoadpathEntry [ ] rtes = new IRuntimeLoadpathEntry [ entries . size ( ) ] ; int i = ; for ( String entry : entries ) { rtes [ i ] = RubyRuntime . newRuntimeLoadpathEntry ( entry ) ; i ++ ; } return rtes ; } } package org . rubypeople . rdt . launching ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; public interface IRuntimeLoadpathEntry { public static final int PROJECT = ; public static final int ARCHIVE = ; public static final int VARIABLE = ; public static final int CONTAINER = ; public static final int OTHER = ; public static final int STANDARD_CLASSES = ; public static final int BOOTSTRAP_CLASSES = ; public static final int USER_CLASSES = ; public int getType ( ) ; public String getMemento ( ) throws CoreException ; public IPath getPath ( ) ; public IResource getResource ( ) ; public int getLoadpathProperty ( ) ; public void setLoadpathProperty ( int location ) ; public String getLocation ( ) ; public String getVariableName ( ) ; public ILoadpathEntry getLoadpathEntry ( ) ; public IRubyProject getRubyProject ( ) ; } package org . rubypeople . rdt . launching ; import java . io . File ; import org . eclipse . core . runtime . IPath ; public interface IVMInstall { public static final String CYWGIN_PLATFORM = "" ; public static final String MSWIN32_PLATFORM = "" ; public File getInstallLocation ( ) ; public void setInstallLocation ( File validInstallLocation ) ; public String getName ( ) ; public void setName ( String newName ) ; public IPath [ ] getLibraryLocations ( ) ; public String getId ( ) ; public IVMInstallType getVMInstallType ( ) ; public void setLibraryLocations ( IPath [ ] paths ) ; public String [ ] getVMArguments ( ) ; public String getVMArgs ( ) ; public void setVMArgs ( String vmArgs ) ; public IVMRunner getVMRunner ( String mode ) ; public String getRubyVersion ( ) ; public String getPlatform ( ) ; } package org . rubypeople . rdt . launching ; import java . io . File ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; public interface IVMInstallType { IVMInstall findVMInstallByName ( String vmName ) ; String getId ( ) ; IVMInstall [ ] getVMInstalls ( ) ; IStatus validateInstallLocation ( File installLocation ) ; IVMInstall findVMInstall ( String id ) ; IPath [ ] getDefaultLibraryLocations ( File installLocation ) ; String getName ( ) ; void disposeVMInstall ( String id ) ; IVMInstall createVMInstall ( String id ) ; public File detectInstallLocation ( ) ; File findExecutable ( File installLocation ) ; String getVMVersion ( File installLocation , File executable ) ; String getVMPlatform ( File installLocation , File executable ) ; } package org . rubypeople . rdt . launching ; import org . rubypeople . rdt . core . ILoadpathEntry ; public interface IRuntimeLoadpathEntryResolver2 extends IRuntimeLoadpathEntryResolver { public boolean isVMInstallReference ( ILoadpathEntry entry ) ; } package org . rubypeople . rdt . launching ; import java . io . File ; import java . text . MessageFormat ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . internal . launching . LaunchingMessages ; public class RubyLaunchDelegate extends AbstractRubyLaunchConfigurationDelegate { public void launch ( ILaunchConfiguration configuration , String mode , ILaunch launch , IProgressMonitor monitor ) throws CoreException { if ( monitor == null ) { monitor = new NullProgressMonitor ( ) ; } monitor . beginTask ( MessageFormat . format ( "" , configuration . getName ( ) ) , ) ; if ( monitor . isCanceled ( ) ) { return ; } monitor . subTask ( LaunchingMessages . JavaLocalApplicationLaunchConfigurationDelegate_Verifying_launch_attributes____1 ) ; String mainTypeName = verifyFileToLaunch ( configuration ) ; IVMRunner runner = getVMRunner ( configuration , mode ) ; File workingDir = verifyWorkingDirectory ( configuration ) ; String workingDirName = null ; if ( workingDir != null ) { workingDirName = workingDir . getAbsolutePath ( ) ; } String [ ] envp = getEnvironment ( configuration ) ; String pgmArgs = getProgramArguments ( configuration ) ; String vmArgs = getVMArguments ( configuration ) ; ExecutionArguments execArgs = new ExecutionArguments ( vmArgs , pgmArgs ) ; Map vmAttributesMap = getVMSpecificAttributesMap ( configuration ) ; String [ ] loadpath = getLoadpath ( configuration ) ; boolean isSudo = getIsSudo ( configuration ) ; String sudoMessage = getSudoMessage ( configuration ) ; VMRunnerConfiguration runConfig = new VMRunnerConfiguration ( mainTypeName , loadpath ) ; runConfig . setProgramArguments ( execArgs . getProgramArgumentsArray ( ) ) ; runConfig . setEnvironment ( envp ) ; runConfig . setVMArguments ( execArgs . getVMArgumentsArray ( ) ) ; runConfig . setWorkingDirectory ( workingDirName ) ; runConfig . setVMSpecificAttributesMap ( vmAttributesMap ) ; runConfig . setIsSudo ( isSudo ) ; runConfig . setSudoMessage ( sudoMessage ) ; if ( monitor . isCanceled ( ) ) { return ; } monitor . worked ( ) ; monitor . subTask ( LaunchingMessages . JavaLocalApplicationLaunchConfigurationDelegate_Creating_source_locator____2 ) ; setDefaultSourceLocator ( launch , configuration ) ; Map configAttributes = configuration . getAttributes ( ) ; for ( Object key : configAttributes . keySet ( ) ) { Object value = configAttributes . get ( key ) ; launch . setAttribute ( ( String ) key , value . toString ( ) ) ; } monitor . worked ( ) ; runner . run ( runConfig , launch , monitor ) ; if ( monitor . isCanceled ( ) ) { return ; } monitor . done ( ) ; } } package org . rubypeople . rdt . launching ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; public interface IVMInstallChangedListener { public static final String PROPERTY_NAME = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String PROPERTY_INSTALL_LOCATION = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String PROPERTY_LIBRARY_LOCATIONS = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public static final String PROPERTY_VM_ARGUMENTS = LaunchingPlugin . getUniqueIdentifier ( ) + "" ; public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) ; public void vmChanged ( PropertyChangeEvent event ) ; public void vmAdded ( IVMInstall newVm ) ; public void vmRemoved ( IVMInstall removedVm ) ; } package org . rubypeople . rdt . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; public interface IRuntimeLoadpathEntryResolver { public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , ILaunchConfiguration configuration ) throws CoreException ; public IRuntimeLoadpathEntry [ ] resolveRuntimeLoadpathEntry ( IRuntimeLoadpathEntry entry , IRubyProject project ) throws CoreException ; public IVMInstall resolveVMInstall ( ILoadpathEntry entry ) throws CoreException ; } package org . rubypeople . rdt . launching ; import java . io . File ; import java . util . List ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . internal . launching . IllegalCommandException ; public class VMStandin extends AbstractVMInstall { private String fRubyVersion = null ; private String fPlatform ; public VMStandin ( IVMInstallType type , String id ) { super ( type , id ) ; setNotify ( false ) ; } public VMStandin ( IVMInstall sourceVM , String id ) { super ( sourceVM . getVMInstallType ( ) , id ) ; setNotify ( false ) ; init ( sourceVM ) ; } public VMStandin ( IVMInstall realVM ) { this ( realVM . getVMInstallType ( ) , realVM . getId ( ) ) ; init ( realVM ) ; } private void init ( IVMInstall realVM ) { setName ( realVM . getName ( ) ) ; setInstallLocation ( realVM . getInstallLocation ( ) ) ; setLibraryLocations ( realVM . getLibraryLocations ( ) ) ; setVMArgs ( realVM . getVMArgs ( ) ) ; fRubyVersion = realVM . getRubyVersion ( ) ; fPlatform = realVM . getPlatform ( ) ; } public IVMInstall convertToRealVM ( ) { IVMInstallType vmType = getVMInstallType ( ) ; IVMInstall realVM = vmType . findVMInstall ( getId ( ) ) ; boolean notify = true ; if ( realVM == null ) { realVM = vmType . createVMInstall ( getId ( ) ) ; notify = false ; } if ( realVM instanceof AbstractVMInstall ) { ( ( AbstractVMInstall ) realVM ) . setNotify ( notify ) ; } realVM . setName ( getName ( ) ) ; realVM . setInstallLocation ( getInstallLocation ( ) ) ; realVM . setLibraryLocations ( getLibraryLocations ( ) ) ; realVM . setVMArgs ( getVMArgs ( ) ) ; if ( realVM instanceof AbstractVMInstall ) { ( ( AbstractVMInstall ) realVM ) . setNotify ( true ) ; } if ( ! notify ) { RubyRuntime . fireVMAdded ( realVM ) ; } return realVM ; } public String getRubyVersion ( ) { return fRubyVersion ; } public String getPlatform ( ) { return fPlatform ; } public Process exec ( List commandLine , File workingDirectory ) throws CoreException { return null ; } public String getCommand ( ) throws IllegalCommandException { return null ; } } package org . rubypeople . rdt . launching ; import org . eclipse . core . resources . IProject ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . debug . ui . console . IConsole ; public interface ITerminal extends IConsole , org . eclipse . ui . console . IConsole { public void attach ( IProcess process ) ; public void activate ( ) ; public void write ( String streamIdentifier , String text ) ; public void setProject ( IProject project ) ; } package org . rubypeople . rdt . launching ; import java . io . BufferedReader ; import java . io . File ; import java . io . IOException ; import java . io . StringReader ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExecutableExtension ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . core . Launch ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . core . model . IStreamsProxy ; import org . rubypeople . rdt . internal . launching . LaunchingMessages ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import org . rubypeople . rdt . internal . launching . LibraryInfo ; public abstract class AbstractVMInstallType implements IVMInstallType , IExecutableExtension { private List < IVMInstall > fVMs ; private String fId ; protected AbstractVMInstallType ( ) { fVMs = new ArrayList < IVMInstall > ( ) ; } public IVMInstall [ ] getVMInstalls ( ) { IVMInstall [ ] vms = new IVMInstall [ fVMs . size ( ) ] ; return ( IVMInstall [ ] ) fVMs . toArray ( vms ) ; } public void disposeVMInstall ( String id ) { for ( int i = ; i < fVMs . size ( ) ; i ++ ) { IVMInstall vm = ( IVMInstall ) fVMs . get ( i ) ; if ( vm . getId ( ) . equals ( id ) ) { fVMs . remove ( i ) ; RubyRuntime . fireVMRemoved ( vm ) ; return ; } } } public IVMInstall findVMInstall ( String id ) { for ( int i = ; i < fVMs . size ( ) ; i ++ ) { IVMInstall vm = ( IVMInstall ) fVMs . get ( i ) ; if ( vm . getId ( ) . equals ( id ) ) { return vm ; } } return null ; } public IVMInstall createVMInstall ( String id ) throws IllegalArgumentException { if ( findVMInstall ( id ) != null ) { String format = LaunchingMessages . vmInstallType_duplicateVM ; throw new IllegalArgumentException ( MessageFormat . format ( format , id ) ) ; } IVMInstall vm = doCreateVMInstall ( id ) ; fVMs . add ( vm ) ; return vm ; } protected abstract IVMInstall doCreateVMInstall ( String id ) ; public void setInitializationData ( IConfigurationElement config , String propertyName , Object data ) { fId = config . getAttribute ( "" ) ; } public String getId ( ) { return fId ; } public IVMInstall findVMInstallByName ( String name ) { for ( int i = ; i < fVMs . size ( ) ; i ++ ) { IVMInstall vm = ( IVMInstall ) fVMs . get ( i ) ; if ( vm . getName ( ) . equals ( name ) ) { return vm ; } } return null ; } protected LibraryInfo parseLibraryInfo ( IProcess process ) { IStreamsProxy streamsProxy = process . getStreamsProxy ( ) ; if ( streamsProxy == null ) return null ; String text = streamsProxy . getOutputStreamMonitor ( ) . getContents ( ) ; BufferedReader reader = new BufferedReader ( new StringReader ( text ) ) ; List < String > lines = new ArrayList < String > ( ) ; try { String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { lines . add ( line ) ; } } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } if ( lines . size ( ) > ) { String version = lines . remove ( ) ; removeNotExistingLibs ( lines ) ; if ( lines . size ( ) > ) { String [ ] loadpath = lines . toArray ( new String [ lines . size ( ) ] ) ; return new LibraryInfo ( version , loadpath ) ; } } return null ; } protected LibraryInfo generateLibraryInfo ( File rubyHome , File rubyExecutable ) { LibraryInfo info = null ; File file = getLibraryInfoGeneratorPath ( ) ; if ( file . exists ( ) ) { String rubyExecutablePath = rubyExecutable . getAbsolutePath ( ) ; String [ ] cmdLine = new String [ ] { rubyExecutablePath , file . getAbsolutePath ( ) } ; Process p = null ; try { p = Runtime . getRuntime ( ) . exec ( cmdLine ) ; IProcess process = DebugPlugin . newProcess ( new Launch ( null , ILaunchManager . RUN_MODE , null ) , p , "" ) ; for ( int i = ; i < ; i ++ ) { if ( process . isTerminated ( ) ) { break ; } try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } info = parseLibraryInfo ( process ) ; } catch ( IOException ioe ) { LaunchingPlugin . log ( ioe ) ; } finally { if ( p != null ) { p . destroy ( ) ; } } } if ( info == null ) { LaunchingPlugin . log ( MessageFormat . format ( "" , rubyHome . getAbsolutePath ( ) ) ) ; } return info ; } protected File getLibraryInfoGeneratorPath ( ) { return LaunchingPlugin . getFileInPlugin ( new Path ( "" ) . append ( "" ) . append ( "" ) ) ; } private void removeNotExistingLibs ( List < String > libraries ) { List < String > toRemove = new ArrayList < String > ( ) ; for ( String path : libraries ) { File file = new File ( path ) ; if ( ! file . exists ( ) ) toRemove . add ( path ) ; } libraries . removeAll ( toRemove ) ; } private List < String > readOutput ( IProcess process ) { IStreamsProxy streamsProxy = process . getStreamsProxy ( ) ; if ( streamsProxy == null ) return Collections . emptyList ( ) ; String text = streamsProxy . getOutputStreamMonitor ( ) . getContents ( ) ; BufferedReader reader = new BufferedReader ( new StringReader ( text ) ) ; List < String > lines = new ArrayList < String > ( ) ; try { String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { lines . add ( line ) ; } } catch ( IOException e ) { LaunchingPlugin . log ( e ) ; } return lines ; } protected List < String > executeAndRead ( String [ ] cmdLine ) { Process p = null ; try { p = Runtime . getRuntime ( ) . exec ( cmdLine ) ; IProcess process = DebugPlugin . newProcess ( new Launch ( null , ILaunchManager . RUN_MODE , null ) , p , "" ) ; for ( int i = ; i < ; i ++ ) { if ( process . isTerminated ( ) ) { break ; } try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } return readOutput ( process ) ; } catch ( IOException ioe ) { LaunchingPlugin . log ( ioe ) ; } finally { if ( p != null ) { p . destroy ( ) ; } } return null ; } protected File parseRubyExecutableLocation ( List < String > lines ) { if ( lines == null || lines . isEmpty ( ) ) { return null ; } String location = lines . remove ( ) ; File executable = new File ( location ) ; if ( executable . isFile ( ) && executable . exists ( ) ) return executable ; return null ; } protected abstract LibraryInfo getLibraryInfo ( File rubyHome , File rubyExecutable ) ; public String getVMVersion ( File installLocation , File executable ) { LibraryInfo info = getLibraryInfo ( installLocation , executable ) ; return info . getVersion ( ) ; } } package org . rubypeople . rdt . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; public interface IRuntimeLoadpathProvider { public IRuntimeLoadpathEntry [ ] computeUnresolvedLoadpath ( ILaunchConfiguration configuration ) throws CoreException ; public IRuntimeLoadpathEntry [ ] resolveLoadpath ( IRuntimeLoadpathEntry [ ] entries , ILaunchConfiguration configuration ) throws CoreException ; } package org . rubypeople . rdt . launching ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . w3c . dom . Element ; public interface IRuntimeLoadpathEntry2 extends IRuntimeLoadpathEntry { public void initializeFrom ( Element memento ) throws CoreException ; public String getTypeId ( ) ; public boolean isComposite ( ) ; public IRuntimeLoadpathEntry [ ] getRuntimeLoadpathEntries ( ILaunchConfiguration configuration ) throws CoreException ; public String getName ( ) ; } package org . rubypeople . rdt . launching ; import java . util . List ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . debug . core . ILaunch ; public interface IVMConnector { public void connect ( Map < String , Object > arguments , IProgressMonitor monitor , ILaunch launch ) throws CoreException ; public String getName ( ) ; public String getIdentifier ( ) ; public Map < String , Object > getDefaultArguments ( ) throws CoreException ; public List < String > getArgumentOrder ( ) ; } package org . rubypeople . rdt . internal . cheatsheets ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class RdtPlugin extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; protected static RdtPlugin plugin ; public RdtPlugin ( ) { plugin = this ; } public static RdtPlugin getDefault ( ) { return plugin ; } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } } package org . rubypeople . rdt . internal . cheatsheets . webservice ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . window . Window ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IActionDelegate ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . cheatsheets . ICheatSheetAction ; import org . eclipse . ui . cheatsheets . ICheatSheetManager ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . util . PixelConverter ; import org . rubypeople . rdt . internal . ui . wizards . RubyProjectWizard ; import org . rubypeople . rdt . internal . ui . wizards . RubyProjectWizardFirstPage ; public class OpenNewRubyProjectWizardAction extends Action implements ICheatSheetAction { public OpenNewRubyProjectWizardAction ( ) { super ( "" ) ; } public void run ( ) { run ( new String [ ] { } , null ) ; } public void run ( String [ ] params , ICheatSheetManager manager ) { RubyProjectWizard wizard = new RubyProjectWizard ( ) ; Shell shell = RubyPlugin . getActiveWorkbenchShell ( ) ; wizard . init ( PlatformUI . getWorkbench ( ) , new StructuredSelection ( ) ) ; WizardDialog dialog = new WizardDialog ( shell , wizard ) ; if ( shell != null ) { PixelConverter converter = new PixelConverter ( shell ) ; dialog . setMinimumPageSize ( converter . convertWidthInCharsToPixels ( ) , converter . convertHeightInCharsToPixels ( ) ) ; } dialog . create ( ) ; if ( params . length > ) { ( ( RubyProjectWizardFirstPage ) wizard . getPages ( ) [ ] ) . setName ( params [ ] ) ; } int res = dialog . open ( ) ; notifyResult ( res == Window . OK ) ; } } package org . rubypeople . rdt . internal . cheatsheets . webservice ; import org . eclipse . core . resources . IProject ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . wizard . WizardDialog ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . cheatsheets . ICheatSheetAction ; import org . eclipse . ui . cheatsheets . ICheatSheetManager ; import org . eclipse . ui . wizards . newresource . BasicNewFileResourceWizard ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class CreateWsdlFileAction extends Action implements ICheatSheetAction { public void run ( String [ ] params , ICheatSheetManager manager ) { BasicNewFileResourceWizard wizard = new BasicNewFileResourceWizard ( ) ; String projectName = params . length > ? params [ ] : "" ; IProject project = RubyPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( projectName ) ; if ( project == null ) { return ; } wizard . init ( PlatformUI . getWorkbench ( ) , new StructuredSelection ( project ) ) ; WizardDialog dialog = new WizardDialog ( RubyPlugin . getActiveWorkbenchShell ( ) , wizard ) ; dialog . create ( ) ; dialog . getShell ( ) . setText ( wizard . getWindowTitle ( ) ) ; int result = dialog . open ( ) ; notifyResult ( result == WizardDialog . OK ) ; } } package org . rubypeople . rdt . internal . cheatsheets . webservice ; import java . lang . reflect . Method ; import org . eclipse . debug . internal . ui . DebugUIPlugin ; import org . eclipse . debug . internal . ui . launchConfigurations . LaunchConfigurationManager ; import org . eclipse . debug . internal . ui . launchConfigurations . LaunchConfigurationsDialog ; import org . eclipse . debug . internal . ui . launchConfigurations . LaunchGroupExtension ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . cheatsheets . ICheatSheetAction ; import org . eclipse . ui . cheatsheets . ICheatSheetManager ; public class OpenRunConfigurationAction extends Action implements ICheatSheetAction { public void run ( String [ ] params , ICheatSheetManager manager ) { LaunchConfigurationManager launchManager = DebugUIPlugin . getDefault ( ) . getLaunchConfigurationManager ( ) ; LaunchGroupExtension group = null ; try { Method method = LaunchConfigurationManager . class . getMethod ( "" , new Class [ ] { String . class } ) ; group = ( LaunchGroupExtension ) method . invoke ( launchManager , new Object [ ] { IDebugUIConstants . ID_RUN_LAUNCH_GROUP } ) ; } catch ( Exception e ) { } if ( group == null ) { group = launchManager . getDefaultLaunchGroup ( IDebugUIConstants . ID_RUN_LAUNCH_GROUP ) ; } LaunchConfigurationsDialog dialog = new LaunchConfigurationsDialog ( DebugUIPlugin . getShell ( ) , group ) ; dialog . setOpenMode ( LaunchConfigurationsDialog . LAUNCH_CONFIGURATION_DIALOG_OPEN_ON_LAST_LAUNCHED ) ; dialog . open ( ) ; } } package org . rubypeople . rdt . internal . cheatsheets . webservice ; import java . io . File ; import java . io . FileInputStream ; import java . io . InputStream ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . Path ; import org . eclipse . jface . action . Action ; import org . eclipse . ui . cheatsheets . ICheatSheetAction ; import org . eclipse . ui . cheatsheets . ICheatSheetManager ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . cheatsheets . RdtPlugin ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; public class CopyContentAction extends Action implements ICheatSheetAction { public void run ( String [ ] params , ICheatSheetManager manager ) { File sourceFile = new File ( RubyCore . getOSDirectory ( RdtPlugin . getDefault ( ) ) + params [ ] ) ; if ( ! sourceFile . exists ( ) ) { this . notifyResult ( false ) ; return ; } IFile dest = RubyPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( new Path ( params [ ] ) ) ; if ( dest == null || ! dest . exists ( ) ) { this . notifyResult ( false ) ; return ; } try { InputStream inputStream = new FileInputStream ( sourceFile ) ; dest . setContents ( inputStream , true , true , null ) ; this . notifyResult ( true ) ; } catch ( Exception e ) { this . notifyResult ( false ) ; } } } package org . epic . regexp . views ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . part . * ; import org . eclipse . swt . graphics . Image ; import org . eclipse . jface . action . * ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . * ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . graphics . * ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . custom . * ; import org . eclipse . swt . events . FocusListener ; import org . eclipse . swt . events . FocusEvent ; import org . epic . regexp . RegExpPlugin ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . util . * ; import gnu . regexp . RE ; import gnu . regexp . REMatch ; import gnu . regexp . REException ; public class RegExpView extends ViewPart { class focusListener implements FocusListener { public void focusGained ( FocusEvent e ) { activeInput = e . getSource ( ) ; } public void focusLost ( FocusEvent e ) { } } ; class DebugInfo { private RE re ; private List subexpressions = new ArrayList ( ) ; private List bracketsInRegexp = new ArrayList ( ) ; private List allMatches = new ArrayList ( ) ; private String input ; private String regexp ; private String matchString ; private boolean matchesInitialized = false ; private int matchingBracketsCount = ; int eflags = ; public DebugInfo ( ) { } public void setInput ( String input ) { this . input = input ; } public void setRegexp ( String regexp ) { this . regexp = regexp ; } public void setMatchString ( String match ) { this . matchString = match ; } public String getInput ( ) { return input ; } public String getRegExp ( ) { return regexp ; } public String getMatchString ( ) { return matchString ; } public void addBracketPosition ( int start , int end ) { bracketsInRegexp . add ( new SubexpressionPos ( start , end ) ) ; } public void addSubexpressionPosition ( int start , int end ) { subexpressions . add ( new SubexpressionPos ( start , end ) ) ; } public SubexpressionPos getSubexpressionPosition ( int index ) { return ( SubexpressionPos ) subexpressions . get ( index ) ; } public int getSubexpressionCount ( ) { return subexpressions . size ( ) ; } public REMatch [ ] getMatches ( int index ) { int checkEflags = ; if ( ignoreCaseCheckBox . getSelection ( ) ) { checkEflags |= RE . REG_ICASE ; } if ( multilineCheckBox . getSelection ( ) ) { checkEflags |= RE . REG_MULTILINE ; } if ( ! matchesInitialized || eflags != checkEflags ) { eflags = checkEflags ; initMatches ( ) ; } return ( REMatch [ ] ) allMatches . toArray ( new REMatch [ ] ) ; } public int geMatchingBracketsCount ( ) { return matchingBracketsCount ; } public void initMatches ( ) { String reg = null ; boolean found = false ; RE re = null ; this . allMatches . clear ( ) ; try { for ( int i = bracketsInRegexp . size ( ) - ; i >= ; i -- ) { SubexpressionPos pos = ( SubexpressionPos ) bracketsInRegexp . get ( i ) ; reg = regexp . substring ( , pos . getEnd ( ) + ) ; re = new RE ( reg , eflags ) ; if ( re . getAllMatches ( matchString ) . length > ) { matchingBracketsCount = i + ; found = true ; break ; } } if ( re != null && found ) { REMatch [ ] matches = re . getAllMatches ( matchString ) ; for ( int j = ; j < matches . length ; j ++ ) { this . allMatches . add ( matches [ j ] ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } this . matchesInitialized = true ; } } ; class SubexpressionPos { int start ; int end ; public SubexpressionPos ( int start , int end ) { this . start = start ; this . end = end ; } private int getStart ( ) { return start ; } private int getEnd ( ) { return end ; } } ; private Composite panel ; private List colorTable = new ArrayList ( ) ; private Action validateAction , cutAction , copyAction , pasteAction ; private Action stopDebugAction , forwardDebugAction , backDebugAction ; private StyledText regExpText ; private StyledText matchText ; private Label resultImageLabel ; private Button ignoreCaseCheckBox , multilineCheckBox ; private Object activeInput = null ; private DebugInfo debugInfo = null ; private int debugPosition = ; private static final String SHORTCUTS_RESOURCE_BUNDLE = "" ; public RegExpView ( ) { } public void createPartControl ( Composite parent ) { makeActions ( ) ; contributeToActionBars ( ) ; panel = new Composite ( parent , SWT . NULL ) ; buildColorTable ( ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; panel . setLayout ( layout ) ; GridData data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . grabExcessHorizontalSpace = true ; panel . setLayoutData ( data ) ; data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . horizontalSpan = ; Label regExpLabel = new Label ( panel , SWT . NONE ) ; regExpLabel . setText ( "" ) ; regExpLabel . setLayoutData ( data ) ; data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . horizontalSpan = ; resultImageLabel = new Label ( panel , SWT . NONE ) ; resultUnknown ( ) ; resultImageLabel . setLayoutData ( data ) ; data = new GridData ( ) ; data . horizontalSpan = ; ignoreCaseCheckBox = new Button ( panel , SWT . CHECK ) ; ignoreCaseCheckBox . setText ( "" ) ; ignoreCaseCheckBox . setLayoutData ( data ) ; data = new GridData ( ) ; data . horizontalSpan = ; multilineCheckBox = new Button ( panel , SWT . CHECK ) ; multilineCheckBox . setText ( "" ) ; multilineCheckBox . setLayoutData ( data ) ; data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . horizontalSpan = ; regExpText = new StyledText ( panel , SWT . BORDER ) ; regExpText . setLayoutData ( data ) ; regExpText . addFocusListener ( new focusListener ( ) ) ; data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . horizontalSpan = ; Label matchTextLabel = new Label ( panel , SWT . NONE ) ; matchTextLabel . setText ( "" ) ; matchTextLabel . setLayoutData ( data ) ; data = new GridData ( GridData . FILL_HORIZONTAL | GridData . FILL_VERTICAL ) ; data . horizontalSpan = ; matchText = new StyledText ( panel , SWT . BORDER | SWT . H_SCROLL | SWT . V_SCROLL ) ; matchText . setLayoutData ( data ) ; matchText . addFocusListener ( new focusListener ( ) ) ; IActionBars bars = getViewSite ( ) . getActionBars ( ) ; bars . setGlobalActionHandler ( ActionFactory . CUT . getId ( ) , cutAction ) ; bars . setGlobalActionHandler ( ActionFactory . COPY . getId ( ) , copyAction ) ; bars . setGlobalActionHandler ( ActionFactory . PASTE . getId ( ) , pasteAction ) ; hookContextMenu ( ) ; } private void resultUnknown ( ) { setResultLabelImage ( RegExpImages . RESULT_GRAY , "" ) ; } private void hookContextMenu ( ) { MenuManager menuMgr = new MenuManager ( "" ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager manager ) { fillContextMenu ( manager ) ; } } ) ; Menu menuRegExp = menuMgr . createContextMenu ( regExpText ) ; regExpText . setMenu ( menuRegExp ) ; Menu menuMatch = menuMgr . createContextMenu ( matchText ) ; matchText . setMenu ( menuMatch ) ; } private void fillContextMenu ( IMenuManager manager ) { manager . add ( cutAction ) ; manager . add ( copyAction ) ; manager . add ( pasteAction ) ; createShortcutsMenu ( manager ) ; manager . add ( new Separator ( "" ) ) ; } private void buildColorTable ( ) { Display display = panel . getDisplay ( ) ; colorTable . add ( display . getSystemColor ( SWT . COLOR_BLUE ) ) ; colorTable . add ( display . getSystemColor ( SWT . COLOR_BLACK ) ) ; colorTable . add ( display . getSystemColor ( SWT . COLOR_RED ) ) ; colorTable . add ( display . getSystemColor ( SWT . COLOR_DARK_GRAY ) ) ; colorTable . add ( display . getSystemColor ( SWT . COLOR_DARK_GREEN ) ) ; colorTable . add ( new Color ( display , , , ) ) ; colorTable . add ( display . getSystemColor ( SWT . COLOR_DARK_MAGENTA ) ) ; colorTable . add ( new Color ( display , , , ) ) ; colorTable . add ( new Color ( display , , , ) ) ; colorTable . add ( new Color ( display , , , ) ) ; } private void createShortcutsMenu ( IMenuManager mgr ) { IMenuManager submenu = new MenuManager ( "" ) ; mgr . add ( submenu ) ; Action shortcut ; try { File shortcutsFile = new File ( RegExpPlugin . getPlugInDir ( ) + File . separator + "" ) ; FileInputStream fin = new FileInputStream ( shortcutsFile ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( fin ) ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { StringTokenizer st = new StringTokenizer ( line , "" ) ; if ( st . countTokens ( ) == ) { final String shortc = st . nextToken ( ) ; String descr = st . nextToken ( ) ; shortcut = new Action ( ) { public void run ( ) { insertShortcut ( shortc ) ; } } ; shortcut . setText ( shortc + "" + descr ) ; submenu . add ( shortcut ) ; mgr . update ( true ) ; } else if ( st . countTokens ( ) == ) { String token = st . nextToken ( ) ; if ( token . equals ( "" ) ) { submenu . add ( new Separator ( ) ) ; } } } } catch ( IOException e ) { e . printStackTrace ( ) ; } } private void contributeToActionBars ( ) { IActionBars bars = getViewSite ( ) . getActionBars ( ) ; fillLocalToolBar ( bars . getToolBarManager ( ) ) ; } private void fillLocalToolBar ( IToolBarManager manager ) { manager . add ( stopDebugAction ) ; manager . add ( backDebugAction ) ; manager . add ( forwardDebugAction ) ; manager . add ( new Separator ( ) ) ; manager . add ( validateAction ) ; } private void makeActions ( ) { stopDebugAction = new Action ( ) { public void run ( ) { resetDebug ( ) ; } } ; stopDebugAction . setText ( "" ) ; stopDebugAction . setToolTipText ( "" ) ; stopDebugAction . setImageDescriptor ( RegExpImages . ICON_DEBUG_STOP ) ; backDebugAction = new Action ( ) { public void run ( ) { backDebug ( ) ; } } ; backDebugAction . setText ( "" ) ; backDebugAction . setToolTipText ( "" ) ; backDebugAction . setImageDescriptor ( RegExpImages . ICON_DEBUG_BACK ) ; forwardDebugAction = new Action ( ) { public void run ( ) { forwardDebug ( ) ; } } ; forwardDebugAction . setText ( "" ) ; forwardDebugAction . setToolTipText ( "" ) ; forwardDebugAction . setImageDescriptor ( RegExpImages . ICON_DEBUG_FORWARD ) ; validateAction = new Action ( ) { public void run ( ) { validateRegExp ( ) ; } } ; validateAction . setText ( "" ) ; validateAction . setToolTipText ( "" ) ; validateAction . setImageDescriptor ( RegExpImages . ICON_RUN ) ; cutAction = new Action ( "" , RegExpImages . EDIT_CUT ) { public void run ( ) { ( ( StyledText ) activeInput ) . cut ( ) ; } } ; copyAction = new Action ( "" , RegExpImages . EDIT_COPY ) { public void run ( ) { ( ( StyledText ) activeInput ) . copy ( ) ; } } ; pasteAction = new Action ( "" , RegExpImages . EDIT_PASTE ) { public void run ( ) { ( ( StyledText ) activeInput ) . paste ( ) ; } } ; } private void insertShortcut ( String text ) { int selCount = regExpText . getSelectionCount ( ) ; int pos = regExpText . getCaretOffset ( ) ; regExpText . insert ( text ) ; if ( selCount == ) { regExpText . setCaretOffset ( pos + text . length ( ) ) ; } } public void validateRegExp ( ) { boolean result = false ; int eflags = ; regExpText . setStyleRange ( null ) ; debugPosition = ; if ( ignoreCaseCheckBox . getSelection ( ) ) { eflags |= RE . REG_ICASE ; } if ( multilineCheckBox . getSelection ( ) ) { eflags |= RE . REG_MULTILINE ; } try { RE re = new RE ( regExpText . getText ( ) , eflags ) ; REMatch [ ] matches = re . getAllMatches ( matchText . getText ( ) ) ; String matchesString = "" ; result = matches . length > ? true : false ; matchText . setStyleRange ( null ) ; for ( int i = ; i < matches . length ; i ++ ) { int color = ; for ( int j = ; j <= re . getNumSubs ( ) ; j ++ ) { StyleRange styleRange = new StyleRange ( ) ; styleRange . start = matches [ i ] . getStartIndex ( j ) ; styleRange . length = matches [ i ] . getEndIndex ( j ) - matches [ i ] . getStartIndex ( j ) ; Display display = panel . getDisplay ( ) ; styleRange . foreground = display . getSystemColor ( SWT . COLOR_WHITE ) ; styleRange . background = ( Color ) colorTable . get ( color ) ; matchText . setStyleRange ( styleRange ) ; matchText . setTopIndex ( styleRange . start ) ; matchText . setCaretOffset ( styleRange . start ) ; int offsetFromLine = styleRange . start - matchText . getOffsetAtLine ( matchText . getLineAtOffset ( styleRange . start ) ) ; matchText . setHorizontalIndex ( offsetFromLine ) ; matchText . redraw ( ) ; if ( ++ color > colorTable . size ( ) ) { color = ; } } } } catch ( REException e ) { e . printStackTrace ( ) ; } if ( result ) { resultMatches ( ) ; } else { resultDoesNotMatch ( ) ; } } private void resultDoesNotMatch ( ) { setResultLabelImage ( RegExpImages . RESULT_RED , "" ) ; } private void resultMatches ( ) { setResultLabelImage ( RegExpImages . RESULT_GREEN , "" ) ; } public void setResultLabelImage ( ImageDescriptor descr , String tooltip ) { Image labelImage = new Image ( resultImageLabel . getDisplay ( ) , descr . getImageData ( ) ) ; labelImage . setBackground ( panel . getBackground ( ) ) ; resultImageLabel . setImage ( labelImage ) ; resultImageLabel . setToolTipText ( tooltip ) ; } public void setFocus ( ) { } private void buildDebugRegExp ( String input , String match ) { String convInput ; String result = "" ; RE re = null ; boolean inBracket = false ; boolean escape = false ; String character ; int start = , end = ; int bracketStart = ; debugInfo = new DebugInfo ( ) ; debugInfo . setInput ( input ) ; debugInfo . setMatchString ( match ) ; try { re = new RE ( "" ) ; convInput = re . substitute ( input , "" ) ; if ( convInput . indexOf ( '' ) == - ) { for ( int i = ; i < input . length ( ) ; i ++ ) { character = input . substring ( i , i + ) ; if ( ! inBracket ) { re = new RE ( "" ) ; if ( re . isMatch ( character ) ) { bracketStart = result . length ( ) ; result += "" + character ; inBracket = true ; start = i ; } else { if ( ! escape ) { bracketStart = result . length ( ) ; result += "" ; start = i ; } else { escape = false ; } result += character ; if ( character . equals ( "" ) ) { escape = true ; continue ; } if ( ( i + ) < input . length ( ) ) { String nextChar = input . substring ( i + , i + ) ; re = new RE ( "" ) ; if ( re . isMatch ( nextChar ) ) { result += nextChar ; i ++ ; } } if ( ( i + ) < input . length ( ) ) { String nextChar = input . substring ( i + , i + ) ; re = new RE ( "" ) ; if ( re . isMatch ( nextChar ) ) { result += nextChar ; i ++ ; } } result += "" ; debugInfo . addSubexpressionPosition ( start , i + ) ; debugInfo . addBracketPosition ( bracketStart , result . length ( ) - ) ; } } else { re = new RE ( "" ) ; if ( re . isMatch ( character ) ) { if ( ( i + ) < input . length ( ) ) { String nextChar = input . substring ( i + , i + ) ; if ( nextChar . equals ( "" ) ) { result += character + nextChar ; i ++ ; continue ; } re = new RE ( "" ) ; if ( re . isMatch ( nextChar ) ) { result += character + nextChar ; i ++ ; if ( ( i + ) < input . length ( ) ) { nextChar = input . substring ( i + , i + ) ; re = new RE ( "" ) ; if ( re . isMatch ( nextChar ) ) { result += nextChar ; i ++ ; } } result += "" ; debugInfo . addSubexpressionPosition ( start , i + ) ; debugInfo . addBracketPosition ( bracketStart , result . length ( ) - ) ; inBracket = false ; } else { result += character + "" ; debugInfo . addSubexpressionPosition ( start , i + ) ; debugInfo . addBracketPosition ( bracketStart , result . length ( ) - ) ; inBracket = false ; } } else { result += character + "" ; debugInfo . addSubexpressionPosition ( start , i + ) ; debugInfo . addBracketPosition ( bracketStart , result . length ( ) - ) ; inBracket = false ; } } else { result += character ; } } } } else { result = input ; re = new RE ( "" ) ; REMatch [ ] matches = re . getAllMatches ( convInput ) ; for ( int i = ; i < matches . length ; i ++ ) { for ( int j = ; j <= re . getNumSubs ( ) ; j ++ ) { start = matches [ i ] . getStartIndex ( j ) ; end = matches [ i ] . getEndIndex ( j ) ; debugInfo . addSubexpressionPosition ( start , end ) ; debugInfo . addBracketPosition ( start , end ) ; } } } } catch ( Exception e ) { result = null ; e . printStackTrace ( ) ; } debugInfo . setRegexp ( result ) ; } private void resetDebug ( ) { debugPosition = ; regExpText . setStyleRange ( null ) ; matchText . setStyleRange ( null ) ; resultUnknown ( ) ; } private void backDebug ( ) { showDebugResult ( debugPosition - ) ; } private void forwardDebug ( ) { showDebugResult ( debugPosition + ) ; } private void showDebugResult ( int position ) { if ( debugInfo == null ) { buildDebugRegExp ( regExpText . getText ( ) , matchText . getText ( ) ) ; position = ; } else if ( ! debugInfo . getInput ( ) . equals ( regExpText . getText ( ) ) || ! debugInfo . getMatchString ( ) . equals ( matchText . getText ( ) ) ) { buildDebugRegExp ( regExpText . getText ( ) , matchText . getText ( ) ) ; position = ; } if ( position > debugInfo . getSubexpressionCount ( ) || position < ) { return ; } REMatch [ ] matches = debugInfo . getMatches ( position - ) ; debugPosition = position ; StyleRange styleRangeRegExp = new StyleRange ( ) ; Display display = panel . getDisplay ( ) ; styleRangeRegExp . background = display . getSystemColor ( SWT . COLOR_BLUE ) ; styleRangeRegExp . foreground = display . getSystemColor ( SWT . COLOR_WHITE ) ; SubexpressionPos pos = debugInfo . getSubexpressionPosition ( position - ) ; regExpText . setStyleRange ( null ) ; styleRangeRegExp . start = pos . getStart ( ) ; styleRangeRegExp . length = pos . getEnd ( ) - pos . getStart ( ) ; regExpText . setStyleRange ( styleRangeRegExp ) ; regExpText . setTopIndex ( styleRangeRegExp . start ) ; regExpText . setCaretOffset ( styleRangeRegExp . start ) ; int offsetFromLine = styleRangeRegExp . start - regExpText . getOffsetAtLine ( regExpText . getLineAtOffset ( styleRangeRegExp . start ) ) ; regExpText . setHorizontalIndex ( offsetFromLine ) ; regExpText . redraw ( ) ; matchText . setStyleRange ( null ) ; if ( position <= debugInfo . geMatchingBracketsCount ( ) ) { resultMatches ( ) ; for ( int i = ; i < matches . length ; i ++ ) { StyleRange styleRangeMatch = new StyleRange ( ) ; styleRangeMatch . background = display . getSystemColor ( SWT . COLOR_BLUE ) ; styleRangeMatch . foreground = display . getSystemColor ( SWT . COLOR_WHITE ) ; styleRangeMatch . start = matches [ i ] . getStartIndex ( position ) ; styleRangeMatch . length = matches [ i ] . getEndIndex ( position ) - matches [ i ] . getStartIndex ( position ) ; matchText . setStyleRange ( styleRangeMatch ) ; matchText . setTopIndex ( styleRangeMatch . start ) ; matchText . setCaretOffset ( styleRangeMatch . start ) ; offsetFromLine = styleRangeMatch . start - matchText . getOffsetAtLine ( matchText . getLineAtOffset ( styleRangeMatch . start ) ) ; matchText . setHorizontalIndex ( offsetFromLine ) ; matchText . redraw ( ) ; } } else { resultDoesNotMatch ( ) ; } } public void setRegExpText ( String regexp ) { regExpText . setText ( regexp ) ; } public void setMatchText ( String text ) { matchText . setText ( text ) ; } public void setIgnoreCaseCheckbox ( boolean state ) { ignoreCaseCheckBox . setSelection ( state ) ; } public void setMultilineCheckbox ( boolean state ) { multilineCheckBox . setSelection ( state ) ; } } package org . epic . regexp . views ; import org . eclipse . jface . resource . ImageDescriptor ; import org . epic . regexp . RegExpPlugin ; import java . net . MalformedURLException ; import java . net . URL ; public class RegExpImages { static final URL BASE_URL = RegExpPlugin . getDefault ( ) . getBundle ( ) . getEntry ( "" ) ; static final String iconPath = "" ; public static final ImageDescriptor ICON_VIEW = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor ICON_RUN = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor RESULT_GRAY = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor RESULT_GREEN = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor RESULT_RED = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor EDIT_CUT = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor EDIT_COPY = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor EDIT_PASTE = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor ICON_DEBUG_STOP = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor ICON_DEBUG_BACK = createImageDescriptor ( iconPath + "" ) ; public static final ImageDescriptor ICON_DEBUG_FORWARD = createImageDescriptor ( iconPath + "" ) ; private static ImageDescriptor createImageDescriptor ( String path ) { try { URL url = new URL ( BASE_URL , path ) ; return ImageDescriptor . createFromURL ( url ) ; } catch ( MalformedURLException e ) { } return ImageDescriptor . getMissingImageDescriptor ( ) ; } } package org . epic . regexp ; import org . eclipse . ui . plugin . * ; import org . eclipse . core . runtime . * ; import org . eclipse . core . resources . * ; import java . io . IOException ; import java . net . URL ; import java . util . * ; public class RegExpPlugin extends AbstractUIPlugin { private static RegExpPlugin plugin ; private ResourceBundle resourceBundle ; public RegExpPlugin ( ) { super ( ) ; plugin = this ; try { resourceBundle = ResourceBundle . getBundle ( "" ) ; } catch ( MissingResourceException x ) { resourceBundle = null ; } } public static RegExpPlugin getDefault ( ) { return plugin ; } public static IWorkspace getWorkspace ( ) { return ResourcesPlugin . getWorkspace ( ) ; } public static String getResourceString ( String key ) { ResourceBundle bundle = RegExpPlugin . getDefault ( ) . getResourceBundle ( ) ; try { return bundle . getString ( key ) ; } catch ( MissingResourceException e ) { return key ; } } public ResourceBundle getResourceBundle ( ) { return resourceBundle ; } static public String getPlugInDir ( ) { URL installURL = getDefault ( ) . getBundle ( ) . getEntry ( "" ) ; try { installURL = FileLocator . resolve ( installURL ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return installURL . toExternalForm ( ) ; } } package com . aptana . rdt . internal . core . builder ; import java . util . Collection ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubMonitor ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . SyntaxException ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . compiler . BuildContext ; import org . rubypeople . rdt . core . compiler . CompilationParticipant ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . Gem ; public class GemLoadpathAdder extends CompilationParticipant { private IRubyProject project ; @ Override public int aboutToBuild ( IRubyProject project ) { this . project = project ; return super . aboutToBuild ( project ) ; } @ Override public void buildStarting ( BuildContext [ ] files , boolean isBatch , IProgressMonitor monitor ) { SubMonitor sub = SubMonitor . convert ( monitor , ) ; Collection < String > gems = getReferencedGems ( files , sub . newChild ( ) ) ; addReferencedGemsToLoadpath ( gems , sub . newChild ( ) ) ; sub . done ( ) ; } private void addReferencedGemsToLoadpath ( Collection < String > gems , IProgressMonitor monitor ) { SubMonitor sub = SubMonitor . convert ( monitor , gems . size ( ) ) ; for ( String gemName : gems ) { if ( gemName . equals ( "" ) ) continue ; try { AptanaRDTPlugin . addGemLoadPath ( project , new Gem ( gemName , "" , "" ) , sub . newChild ( ) ) ; } catch ( RubyModelException e ) { AptanaRDTPlugin . log ( e ) ; } } sub . done ( ) ; } private Collection < String > getReferencedGems ( BuildContext [ ] files , IProgressMonitor monitor ) { SubMonitor sub = SubMonitor . convert ( monitor , files . length ) ; RubyParser parser = new RubyParser ( ) ; Collection < String > gems = new HashSet < String > ( ) ; for ( BuildContext context : files ) { sub . subTask ( "" + context . getFile ( ) . getLocation ( ) . toPortableString ( ) ) ; gems . addAll ( getGemNames ( parser , context ) ) ; sub . worked ( ) ; } sub . done ( ) ; return gems ; } private Collection < String > getGemNames ( RubyParser parser , BuildContext context ) { try { Node root = context . getAST ( ) ; if ( root == null ) return Collections . emptyList ( ) ; GemVisitor visitor = new GemVisitor ( ) ; root . accept ( visitor ) ; return visitor . getGems ( ) ; } catch ( SyntaxException e ) { } catch ( Exception e ) { RubyCore . log ( e ) ; } return Collections . emptyList ( ) ; } @ Override public boolean isActive ( IRubyProject project ) { return true ; } private static class GemVisitor extends InOrderVisitor { private Set < String > gems ; public GemVisitor ( ) { gems = new HashSet < String > ( ) ; } @ Override public Object visitFCallNode ( FCallNode iVisited ) { String name = iVisited . getName ( ) ; if ( name . equals ( "" ) || name . equals ( "" ) ) { List < String > args = ASTUtil . getArgumentsFromFunctionCall ( iVisited ) ; if ( args != null && ! args . isEmpty ( ) ) { String gemName = args . get ( ) ; if ( gemName . startsWith ( "" ) || gemName . startsWith ( "" ) ) { gemName = new String ( gemName . substring ( , gemName . length ( ) - ) ) ; } gems . add ( gemName ) ; } } return super . visitFCallNode ( iVisited ) ; } public Collection < String > getGems ( ) { return gems ; } } } package com . aptana . rdt . internal . core ; import java . util . Iterator ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . internal . parser . warnings . LintOptions ; public class AptanaRDTPreferenceInitializer extends AbstractPreferenceInitializer { public void initializeDefaultPreferences ( ) { Set < String > optionNames = AptanaRDTPlugin . getDefault ( ) . optionNames ; Map < String , String > defaultOptionsMap = new LintOptions ( ) . getMap ( ) ; IEclipsePreferences defaultPreferences = new DefaultScope ( ) . getNode ( AptanaRDTPlugin . PLUGIN_ID ) ; for ( Iterator < Map . Entry < String , String > > iter = defaultOptionsMap . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Map . Entry < String , String > entry = ( Map . Entry < String , String > ) iter . next ( ) ; String optionName = ( String ) entry . getKey ( ) ; defaultPreferences . put ( optionName , ( String ) entry . getValue ( ) ) ; optionNames . add ( optionName ) ; } AptanaRDTPlugin . getDefault ( ) . optionsCache = null ; defaultPreferences . putBoolean ( AptanaRDTPlugin . DUPLICATE_CODE_CHECK_ENABLED , true ) ; defaultPreferences . putInt ( AptanaRDTPlugin . DUPLICATE_CODE_MASS_THRESHOLD , ) ; } } package com . aptana . rdt . internal . core . gems ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . Gem ; public class LegacyGemParser implements IGemParser { private String lineDelimeter ; protected boolean strict ; LegacyGemParser ( ) { this ( System . getProperty ( "" ) , false ) ; } public LegacyGemParser ( String lineDelimeter ) { this ( lineDelimeter , false ) ; } LegacyGemParser ( boolean strict ) { this ( System . getProperty ( "" ) , strict ) ; } LegacyGemParser ( String lineDelimeter , boolean strict ) { this . lineDelimeter = lineDelimeter ; this . strict = strict ; } public Set < Gem > parse ( String string ) throws GemParseException { if ( string == null || string . trim ( ) . length ( ) == ) return new HashSet < Gem > ( ) ; String [ ] raw = string . split ( lineDelimeter ) ; if ( raw . length == ) { raw = string . split ( "" ) ; } if ( raw . length == ) { raw = string . split ( "" ) ; } List < String > lines = new ArrayList < String > ( Arrays . asList ( raw ) ) ; if ( lines . size ( ) < ) { return new HashSet < Gem > ( ) ; } if ( lines . get ( ) . startsWith ( "" ) ) { lines . remove ( ) ; for ( int i = ; i < lines . size ( ) ; i ++ ) { String line = lines . remove ( ) ; if ( line . trim ( ) . equals ( "" ) ) { break ; } } } else { String line = null ; while ( true ) { if ( lines . isEmpty ( ) ) break ; line = lines . get ( ) ; if ( line . trim ( ) . length ( ) == || line . trim ( ) . equals ( "" ) || line . trim ( ) . equals ( "" ) ) { lines . remove ( ) ; } else { break ; } } } return parseOutGems ( trimTrailingCRs ( lines ) ) ; } private List < String > trimTrailingCRs ( List < String > lines ) { List < String > trimmed = new ArrayList < String > ( ) ; for ( String line : lines ) { if ( line . endsWith ( "" ) ) line = line . substring ( , line . length ( ) - ) ; trimmed . add ( line ) ; } return trimmed ; } protected Set < Gem > parseOutGems ( List < String > lines ) throws GemParseException { Set < Gem > gems = new HashSet < Gem > ( ) ; if ( lines == null || lines . isEmpty ( ) ) return gems ; String line = lines . get ( ) ; if ( line . startsWith ( "" ) ) return gems ; for ( int i = ; i < lines . size ( ) ; ) { String nameAndVersion = lines . get ( i ) ; String description = "" ; if ( ( i + ) < lines . size ( ) ) { description = lines . get ( i + ) ; } int j = ; while ( true ) { if ( ( i + j ) >= lines . size ( ) ) break ; String nextLine = lines . get ( i + j ) ; if ( nextLine . trim ( ) . length ( ) == ) break ; description += "" + nextLine . trim ( ) ; j ++ ; } int openParen = nameAndVersion . indexOf ( '' ) ; if ( openParen == - ) { if ( strict ) { throw new GemParseException ( "" + lines ) ; } else { AptanaRDTPlugin . log ( "" + lines ) ; return gems ; } } int closeParen = nameAndVersion . indexOf ( '' ) ; String name = nameAndVersion . substring ( , openParen ) ; String version = nameAndVersion . substring ( openParen + , closeParen ) ; if ( version . indexOf ( "" ) != - ) { String [ ] versions = version . split ( "" ) ; for ( int y = ; y < versions . length ; y ++ ) gems . add ( new Gem ( name . trim ( ) , versions [ y ] , description . trim ( ) ) ) ; } else { gems . add ( new Gem ( name . trim ( ) , version , description . trim ( ) ) ) ; } i += ( j + ) ; } return gems ; } } package com . aptana . rdt . internal . core . gems ; import java . io . * ; import java . util . HashMap ; import java . util . Iterator ; public class XMLWriter extends PrintWriter { protected int tab ; protected static final String XML_VERSION = "" ; public XMLWriter ( OutputStream output ) throws UnsupportedEncodingException { super ( new OutputStreamWriter ( output , "" ) ) ; tab = ; println ( XML_VERSION ) ; } public void endTag ( String name ) { tab -- ; printTag ( '' + name , null ) ; } public void printSimpleTag ( String name , Object value ) { if ( value != null ) { printTag ( name , null , true , false ) ; print ( getEscaped ( String . valueOf ( value ) ) ) ; printTag ( '' + name , null , false , true ) ; } } public void printTabulation ( ) { for ( int i = ; i < tab ; i ++ ) super . print ( '' ) ; } public void printTag ( String name , HashMap < String , Object > parameters ) { printTag ( name , parameters , true , true ) ; } public void printTag ( String name , HashMap < String , Object > parameters , boolean shouldTab , boolean newLine ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( "" ) ; sb . append ( name ) ; if ( parameters != null ) for ( Iterator < String > it = parameters . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { sb . append ( "" ) ; String key = it . next ( ) ; sb . append ( key ) ; sb . append ( "" ) ; sb . append ( getEscaped ( String . valueOf ( parameters . get ( key ) ) ) ) ; sb . append ( "" ) ; } sb . append ( ">" ) ; if ( shouldTab ) printTabulation ( ) ; if ( newLine ) println ( sb . toString ( ) ) ; else print ( sb . toString ( ) ) ; } public void startTag ( String name , HashMap < String , Object > parameters ) { startTag ( name , parameters , true ) ; } public void startTag ( String name , HashMap < String , Object > parameters , boolean newLine ) { printTag ( name , parameters , true , newLine ) ; tab ++ ; } private static void appendEscapedChar ( StringBuffer buffer , char c ) { String replacement = getReplacement ( c ) ; if ( replacement != null ) { buffer . append ( '' ) ; buffer . append ( replacement ) ; buffer . append ( '' ) ; } else { buffer . append ( c ) ; } } public static String getEscaped ( String s ) { StringBuffer result = new StringBuffer ( s . length ( ) + ) ; for ( int i = ; i < s . length ( ) ; ++ i ) appendEscapedChar ( result , s . charAt ( i ) ) ; return result . toString ( ) ; } private static String getReplacement ( char c ) { switch ( c ) { case '' : return "" ; case '>' : return "" ; case '' : return "" ; case '' : return "" ; case '' : return "" ; } return null ; } } package com . aptana . rdt . internal . core . gems ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . FileReader ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collection ; 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 . SortedSet ; import java . util . TreeSet ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import javax . xml . parsers . FactoryConfigurationError ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . parsers . SAXParserFactory ; import org . eclipse . core . net . proxy . IProxyData ; import org . eclipse . core . net . proxy . IProxyService ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubMonitor ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . ui . IDebugUIConstants ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . xml . sax . InputSource ; import org . xml . sax . SAXException ; import org . xml . sax . XMLReader ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . AbstractGemManager ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . GemListener ; import com . aptana . rdt . core . gems . GemRequirement ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . core . gems . LogicalGem ; import com . aptana . rdt . core . gems . Version ; import com . aptana . rdt . core . preferences . IPreferenceConstants ; public class GemManager extends AbstractGemManager implements IGemManager , IVMInstallChangedListener { private static final String DETAIL_SWITCH = "" ; private static final String SOURCE_SWITCH = "" ; private static final String INCLUDE_DEPENDENCIES_SWITCH = "" ; private static final String LOCAL_SWITCH = "" ; private static final String VERSION_SWITCH = "" ; private static final String REMOTE_SWITCH = "" ; private static final String LIST_COMMAND = "" ; private static final String INSTALL_COMMAND = "" ; private static final String UNINSTALL_COMMAND = "" ; private static final String UPDATE_COMMAND = "" ; private static final String CLEANUP_COMMAND = "" ; private static final String EXECUTABLE = "" ; private static final String LOCAL_GEMS_CACHE_FILE = "" ; private static final String RUBYGEMS_UPDATE_GEM_NAME = "" ; private static final String UPDATE_RUBYGEMS_COMMAND = "" ; private static GemManager fgInstance ; private Set < Gem > gems ; private Set < String > urls ; private List < IPath > fGemInstallPaths ; private Map < String , Set < Gem > > fRemoteGems = new HashMap < String , Set < Gem > > ( ) ; protected boolean isInitialized ; private Version fVersion ; private static int seed = ; protected GemManager ( ) { super ( ) ; urls = new HashSet < String > ( ) ; gems = new HashSet < Gem > ( ) ; } public boolean isInitialized ( ) { return isInitialized ; } protected Set < Gem > loadLocalCache ( File file ) { FileReader fileReader = null ; try { fileReader = new FileReader ( file ) ; XMLReader reader = SAXParserFactory . newInstance ( ) . newSAXParser ( ) . getXMLReader ( ) ; GemManagerContentHandler handler = new GemManagerContentHandler ( ) ; reader . setContentHandler ( handler ) ; reader . parse ( new InputSource ( fileReader ) ) ; return handler . getGems ( ) ; } catch ( FileNotFoundException e ) { } catch ( SAXException e ) { AptanaRDTPlugin . log ( e ) ; } catch ( ParserConfigurationException e ) { AptanaRDTPlugin . log ( e ) ; } catch ( FactoryConfigurationError e ) { AptanaRDTPlugin . log ( e ) ; } catch ( IOException e ) { AptanaRDTPlugin . log ( e ) ; } finally { try { if ( fileReader != null ) fileReader . close ( ) ; } catch ( IOException e ) { } } return new HashSet < Gem > ( ) ; } protected void storeGemCache ( Set < Gem > gems , File file ) { XMLWriter out = null ; try { out = new XMLWriter ( new FileOutputStream ( file ) ) ; writeXML ( gems , out ) ; } catch ( FileNotFoundException e ) { AptanaRDTPlugin . log ( e ) ; } catch ( IOException e ) { AptanaRDTPlugin . log ( e ) ; } finally { if ( out != null ) out . close ( ) ; } } protected File getConfigFile ( String fileName ) { return AptanaRDTPlugin . getDefault ( ) . getStateLocation ( ) . append ( fileName ) . toFile ( ) ; } private void writeXML ( Set < Gem > gems , XMLWriter out ) { out . startTag ( "" , null ) ; for ( Gem gem : gems ) { out . startTag ( "" , null ) ; out . printSimpleTag ( "" , gem . getName ( ) ) ; out . printSimpleTag ( "" , gem . getVersion ( ) ) ; out . printSimpleTag ( "" , gem . getDescription ( ) ) ; out . printSimpleTag ( "" , gem . getPlatform ( ) ) ; out . endTag ( "" ) ; } out . endTag ( "" ) ; out . flush ( ) ; } protected Set < Gem > loadRemoteGems ( String gemIndexUrl , IProgressMonitor monitor ) { if ( ! isRubyGemsInstalled ( ) ) return new HashSet < Gem > ( ) ; IGemParser parser ; String command = LIST_COMMAND + "" + DETAIL_SWITCH + "" + REMOTE_SWITCH + "" + SOURCE_SWITCH + "" + gemIndexUrl ; String output = launchInBackgroundAndRead ( command , getStateFile ( "" ) ) ; if ( output != null && output . contains ( "" ) ) { command = LIST_COMMAND + "" + REMOTE_SWITCH + "" + SOURCE_SWITCH + "" + gemIndexUrl ; output = launchInBackgroundAndRead ( command , getStateFile ( "" ) ) ; parser = getGemParser ( false ) ; } else { parser = getGemParser ( true ) ; } try { return parser . parse ( output ) ; } catch ( GemParseException e ) { return Collections . emptySet ( ) ; } } protected IGemParser getGemParser ( ) { return getGemParser ( true ) ; } protected IGemParser getGemParser ( boolean detailed ) { if ( detailed ) return new HybridGemParser ( getVersion ( ) ) ; return new ShortListingGemParser ( ) ; } private Set < Gem > loadLocalGems ( IProgressMonitor monitor ) { if ( ! isRubyGemsInstalled ( ) ) return new HashSet < Gem > ( ) ; IGemParser parser = getGemParser ( ) ; String output = getLocalGemsListing ( ) ; try { return parser . parse ( output ) ; } catch ( GemParseException e ) { return Collections . emptySet ( ) ; } } private String launchInBackgroundAndRead ( final ILaunchConfiguration config , final File file ) { return RubyRuntime . launchInBackgroundAndRead ( config , file ) ; } private String launchInBackgroundAndRead ( String command , File file ) { return launchInBackgroundAndRead ( createGemLaunchConfiguration ( command , false ) , file ) ; } public Version getVersion ( ) { if ( fVersion != null ) return fVersion ; int tries = ; while ( fVersion == null && tries < ) { String version = launchInBackgroundAndRead ( "" , getStateFile ( "" ) ) ; try { if ( version != null && version . trim ( ) . length ( ) > ) fVersion = new Version ( version . trim ( ) ) ; } catch ( RuntimeException e ) { AptanaRDTPlugin . log ( e ) ; fVersion = null ; } tries ++ ; } return fVersion ; } private String getLocalGemsListing ( ) { String command = "" ; if ( getVersion ( ) != null && getVersion ( ) . isLessThanOrEqualTo ( "" ) ) { command = LIST_COMMAND + "" + LOCAL_SWITCH ; } return launchInBackgroundAndRead ( command , getGemListingFile ( ) ) ; } private File getGemListingFile ( ) { return getStateFile ( "" ) ; } public IStatus update ( final Gem gem , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; if ( ! isRubyGemsInstalled ( ) ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . PLUGIN_ID , - , "" , null ) ; try { String command = UPDATE_COMMAND + "" + gem . getName ( ) ; command = addProxy ( IGemManager . DEFAULT_GEM_HOST , command ) ; ILaunchConfiguration config = createGemLaunchConfiguration ( command , true ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; final ILaunch launch = config . launch ( ILaunchManager . RUN_MODE , monitor ) ; while ( ! launch . isTerminated ( ) ) { if ( monitor . isCanceled ( ) ) { try { launch . terminate ( ) ; } catch ( DebugException e ) { } return Status . CANCEL_STATUS ; } Thread . yield ( ) ; } refresh ( monitor ) ; for ( GemListener listener : new ArrayList < GemListener > ( listeners ) ) { listener . gemUpdated ( gem ) ; } return Status . OK_STATUS ; } catch ( CoreException e ) { return e . getStatus ( ) ; } } private ILaunchConfigurationType getRubyApplicationConfigType ( ) { return getLaunchManager ( ) . getLaunchConfigurationType ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ; } private ILaunchManager getLaunchManager ( ) { return DebugPlugin . getDefault ( ) . getLaunchManager ( ) ; } private ILaunchConfiguration createGemLaunchConfiguration ( String arguments , boolean isSudo ) { String gemPath = getGemScriptPath ( ) ; ILaunchConfiguration config = null ; try { ILaunchConfigurationType configType = getRubyApplicationConfigType ( ) ; ILaunchConfigurationWorkingCopy wc = configType . newInstance ( null , getUniqueName ( "" ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , gemPath ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_NAME , RubyRuntime . getDefaultVMInstall ( ) . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE , RubyRuntime . getDefaultVMInstall ( ) . getVMInstallType ( ) . getId ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROGRAM_ARGUMENTS , arguments ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_ARGUMENTS , "" ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_IS_SUDO , isSudo ) ; if ( isSudo ) { wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_TERMINAL_COMMAND , "" + arguments ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_USE_TERMINAL , "" ) ; } Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( IRubyLaunchConfigurationConstants . ATTR_RUBY_COMMAND , EXECUTABLE ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE_SPECIFIC_ATTRS_MAP , map ) ; wc . setAttribute ( IDebugUIConstants . ATTR_PRIVATE , true ) ; wc . setAttribute ( IDebugUIConstants . ATTR_LAUNCH_IN_BACKGROUND , false ) ; config = wc . doSave ( ) ; } catch ( CoreException ce ) { AptanaRDTPlugin . log ( ce ) ; } return config ; } private synchronized String getUniqueName ( String name ) { return RubyRuntime . generateUniqueLaunchConfigurationNameFrom ( name ) + seed ++ ; } public ILaunchConfiguration run ( String args ) throws CoreException { boolean useSudo = false ; if ( ( args . contains ( "" ) || args . contains ( "" ) || args . contains ( "" ) || args . contains ( "" ) ) && ! args . contains ( "" ) ) { useSudo = true ; } return createGemLaunchConfiguration ( args , useSudo ) ; } private static String getGemScriptPath ( ) { String path = Platform . getPreferencesService ( ) . getString ( AptanaRDTPlugin . PLUGIN_ID , IPreferenceConstants . GEM_SCRIPT_PATH , "" , null ) ; if ( path != null && path . trim ( ) . length ( ) > ) return path ; IVMInstall vm = RubyRuntime . getDefaultVMInstall ( ) ; if ( vm == null ) return null ; path = vm . getInstallLocation ( ) . getAbsolutePath ( ) + File . separator + "" + File . separator + "" ; File gemScript = Util . findFileWithOptionalSuffix ( path ) ; if ( gemScript == null ) return null ; return gemScript . getAbsolutePath ( ) ; } public boolean isRubyGemsInstalled ( ) { String path = getGemScriptPath ( ) ; if ( path == null ) return false ; File file = new File ( path ) ; return file . exists ( ) ; } public IStatus installGem ( final Gem gem , IProgressMonitor monitor ) { return installGem ( gem , true , monitor ) ; } public IStatus installGem ( final Gem gem , boolean includeDependencies , IProgressMonitor monitor ) { if ( gem . isLocal ( ) ) { return doLocalInstallGem ( gem , monitor ) ; } return installGem ( gem , DEFAULT_GEM_HOST , includeDependencies , monitor ) ; } public IStatus removeGem ( final Gem gem , IProgressMonitor monitor ) { if ( ! isRubyGemsInstalled ( ) ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . PLUGIN_ID , - , "" , null ) ; try { String command = UNINSTALL_COMMAND + "" + gem . getName ( ) ; if ( gem . getVersion ( ) != null && gem . getVersion ( ) . trim ( ) . length ( ) > ) { command += "" + VERSION_SWITCH + "" + gem . getVersion ( ) ; } ILaunchConfiguration config = createGemLaunchConfiguration ( command , true ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; final ILaunch launch = config . launch ( ILaunchManager . RUN_MODE , monitor ) ; while ( ! launch . isTerminated ( ) ) { if ( monitor . isCanceled ( ) ) { launch . terminate ( ) ; return Status . CANCEL_STATUS ; } Thread . yield ( ) ; } refresh ( monitor ) ; for ( GemListener listener : new ArrayList < GemListener > ( listeners ) ) { listener . gemRemoved ( gem ) ; } return Status . OK_STATUS ; } catch ( CoreException e ) { return e . getStatus ( ) ; } } public Set < Gem > getGems ( ) { return Collections . unmodifiableSortedSet ( new TreeSet < Gem > ( gems ) ) ; } public static GemManager getInstance ( ) { if ( fgInstance == null ) fgInstance = new GemManager ( ) ; return fgInstance ; } public IStatus refresh ( IProgressMonitor monitor ) { SubMonitor progress = SubMonitor . convert ( monitor , ) ; Set < Gem > newGems = loadLocalGems ( progress . newChild ( ) ) ; gems = newGems ; storeGemCache ( gems , getConfigFile ( LOCAL_GEMS_CACHE_FILE ) ) ; progress . worked ( ) ; Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { for ( GemListener listener : new ArrayList < GemListener > ( listeners ) ) { listener . gemsRefreshed ( ) ; } return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . schedule ( ) ; progress . done ( ) ; return Status . OK_STATUS ; } public Set < Gem > getRemoteGems ( ) { return getRemoteGems ( DEFAULT_GEM_HOST , new NullProgressMonitor ( ) ) ; } public Set < Gem > getRemoteGems ( String sourceURL , IProgressMonitor monitor ) { Set < Gem > remoteGems = new HashSet < Gem > ( ) ; if ( fRemoteGems . containsKey ( sourceURL ) ) { remoteGems = fRemoteGems . get ( sourceURL ) ; } else { remoteGems = makeLogical ( loadRemoteGems ( sourceURL , monitor ) ) ; if ( ! remoteGems . isEmpty ( ) ) { addSourceURL ( sourceURL ) ; fRemoteGems . put ( sourceURL , remoteGems ) ; } } return Collections . unmodifiableSortedSet ( new TreeSet < Gem > ( remoteGems ) ) ; } protected void addSourceURL ( String sourceURL ) { if ( urls . contains ( sourceURL ) ) return ; launchInBackgroundAndRead ( "" + sourceURL , getConfigFile ( "" ) ) ; urls . add ( sourceURL ) ; } public Set < String > getSourceURLs ( ) { return Collections . unmodifiableSet ( new TreeSet < String > ( urls ) ) ; } public boolean gemInstalled ( String gemName ) { Set < Gem > gems = getGems ( ) ; for ( Gem gem : gems ) { if ( gem . getName ( ) . equalsIgnoreCase ( gemName ) ) return true ; } return false ; } public synchronized List < IPath > getGemInstallPaths ( ) { if ( fGemInstallPaths == null ) { if ( ! isRubyGemsInstalled ( ) ) return null ; ILaunchConfiguration config = createGemLaunchConfiguration ( "" , false ) ; if ( config == null ) return null ; try { ILaunchConfigurationWorkingCopy wc = config . getWorkingCopy ( ) ; if ( wc == null ) return null ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_ARGUMENTS , "" ) ; config = wc . doSave ( ) ; } catch ( CoreException e ) { AptanaRDTPlugin . log ( e ) ; } try { String output = launchInBackgroundAndRead ( config , getGemInstallPathFile ( ) ) ; fGemInstallPaths = parseInstallPaths ( output ) ; } catch ( IllegalArgumentException e ) { fGemInstallPaths = null ; return null ; } } return fGemInstallPaths ; } private List < IPath > parseInstallPaths ( String output ) { try { if ( output == null || output . trim ( ) . length ( ) == ) throw new IllegalArgumentException ( "" ) ; output = output . trim ( ) ; if ( ! output . startsWith ( "" ) || ! output . endsWith ( "" ) ) throw new IllegalArgumentException ( "" + output ) ; output = new String ( output . substring ( , output . length ( ) - ) ) ; String [ ] paths = output . split ( "" ) ; if ( paths == null || paths . length < ) return null ; List < IPath > installPaths = new ArrayList < IPath > ( ) ; for ( int i = ; i < paths . length ; i ++ ) { String path = paths [ i ] . trim ( ) ; path = new String ( path . substring ( , path . length ( ) - ) ) ; installPaths . add ( new Path ( path . trim ( ) ) ) ; } return installPaths ; } catch ( Exception e ) { AptanaRDTPlugin . log ( e ) ; } return null ; } private File getGemInstallPathFile ( ) { return getStateFile ( "" ) ; } private File getStateFile ( String name ) { String currentVMId = RubyRuntime . getDefaultVMInstall ( ) . getId ( ) ; File file = AptanaRDTPlugin . getDefault ( ) . getStateLocation ( ) . append ( "" ) . append ( currentVMId ) . append ( name ) . toFile ( ) ; try { file . getParentFile ( ) . mkdirs ( ) ; file . createNewFile ( ) ; } catch ( IOException e ) { } return file ; } public IPath getGemPath ( String gemName ) { List < IPath > paths = getGemInstallPaths ( ) ; if ( paths == null ) return null ; List < IPath > matches = new ArrayList < IPath > ( ) ; for ( IPath path : paths ) { path = path . append ( "" ) ; File gemFolder = path . toFile ( ) ; File [ ] gems = gemFolder . listFiles ( ) ; if ( gems == null ) continue ; for ( int i = ; i < gems . length ; i ++ ) { File gem = gems [ i ] ; String name = gem . getName ( ) ; if ( name . startsWith ( gemName ) ) matches . add ( new Path ( gem . getAbsolutePath ( ) ) ) ; } } if ( matches . isEmpty ( ) ) return null ; if ( matches . size ( ) == ) return matches . get ( ) . append ( "" ) ; List < Version > versions = new ArrayList < Version > ( ) ; for ( IPath match : matches ) { String name = match . lastSegment ( ) ; String [ ] parts = name . split ( "" ) ; for ( int i = parts . length - ; i >= ; i -- ) { String version = parts [ i ] ; try { Version duh = new Version ( version ) ; versions . add ( duh ) ; break ; } catch ( IllegalArgumentException e ) { } } } Collections . sort ( versions ) ; Version latest = versions . get ( versions . size ( ) - ) ; for ( IPath match : matches ) { String name = match . lastSegment ( ) ; String [ ] parts = name . split ( "" ) ; String version = null ; for ( int i = parts . length - ; i >= ; i -- ) { version = parts [ i ] ; try { Version duh = new Version ( version ) ; versions . add ( duh ) ; break ; } catch ( IllegalArgumentException e ) { } } if ( version != null && version . equals ( latest . toString ( ) ) ) return match . append ( "" ) ; } return null ; } public IPath getGemPath ( String gemName , String version ) { return getGemPath ( gemName + "" + version ) ; } public IStatus updateAll ( IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; if ( ! isRubyGemsInstalled ( ) ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . PLUGIN_ID , "" , null ) ; IStatus result = updateSystem ( monitor ) ; if ( result != null && ! result . isOK ( ) ) { return result ; } try { ILaunchConfiguration config = createGemLaunchConfiguration ( addProxy ( IGemManager . DEFAULT_GEM_HOST , UPDATE_COMMAND + "" + INCLUDE_DEPENDENCIES_SWITCH ) , true ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; final ILaunch launch = config . launch ( ILaunchManager . RUN_MODE , monitor ) ; while ( ! launch . isTerminated ( ) ) { if ( monitor . isCanceled ( ) ) { launch . terminate ( ) ; return Status . CANCEL_STATUS ; } Thread . yield ( ) ; } refresh ( monitor ) ; return Status . OK_STATUS ; } catch ( CoreException e ) { return e . getStatus ( ) ; } } public void initialize ( ) { RubyRuntime . addVMInstallChangedListener ( this ) ; scheduleLoadingSources ( ) ; scheduleLoadingLocalGems ( ) ; } private void scheduleLoadingSources ( ) { Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { urls = loadSourceURLs ( ) ; return Status . OK_STATUS ; } } ; job . setPriority ( Job . LONG ) ; job . setSystem ( true ) ; job . schedule ( ) ; } protected Set < String > loadSourceURLs ( ) { Set < String > sources = new HashSet < String > ( ) ; String output = launchInBackgroundAndRead ( "" , getConfigFile ( "" ) ) ; if ( output == null ) return sources ; String [ ] lines = output . split ( "" ) ; if ( lines == null ) return sources ; for ( int i = ; i < lines . length ; i ++ ) { sources . add ( lines [ i ] . trim ( ) ) ; } return sources ; } private void scheduleLoadingLocalGems ( ) { Job job = new Job ( GemsMessages . GemManager_loading_local_gems ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { try { gems = loadLocalCache ( getConfigFile ( LOCAL_GEMS_CACHE_FILE ) ) ; for ( GemListener listener : new ArrayList < GemListener > ( listeners ) ) { listener . gemsRefreshed ( ) ; } gems = loadLocalGems ( monitor ) ; int tries = ; while ( gems . isEmpty ( ) && tries < ) { tries ++ ; gems = loadLocalGems ( monitor ) ; } storeGemCache ( gems , getConfigFile ( LOCAL_GEMS_CACHE_FILE ) ) ; isInitialized = true ; for ( GemListener listener : new ArrayList < GemListener > ( listeners ) ) { listener . managerInitialized ( ) ; } for ( GemListener listener : new ArrayList < GemListener > ( listeners ) ) { listener . gemsRefreshed ( ) ; } } catch ( Exception e ) { AptanaRDTPlugin . log ( e ) ; return Status . CANCEL_STATUS ; } return Status . OK_STATUS ; } } ; job . setPriority ( Job . LONG ) ; job . setSystem ( true ) ; job . schedule ( ) ; } protected Set < Gem > makeLogical ( Set < Gem > remoteGems ) { SortedSet < Gem > sorted = new TreeSet < Gem > ( remoteGems ) ; SortedSet < Gem > logical = new TreeSet < Gem > ( ) ; String name = null ; Collection < Gem > temp = new HashSet < Gem > ( ) ; for ( Gem gem : sorted ) { if ( name != null && ! gem . getName ( ) . equals ( name ) ) { logical . add ( LogicalGem . create ( temp ) ) ; temp . clear ( ) ; } name = gem . getName ( ) ; temp . add ( gem ) ; } if ( name != null && ! temp . isEmpty ( ) ) { logical . add ( LogicalGem . create ( temp ) ) ; temp . clear ( ) ; } return Collections . unmodifiableSortedSet ( logical ) ; } public IStatus cleanup ( IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; if ( ! isRubyGemsInstalled ( ) ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . PLUGIN_ID , "" , null ) ; try { String command = CLEANUP_COMMAND ; ILaunchConfiguration config = createGemLaunchConfiguration ( command , true ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; final ILaunch launch = config . launch ( ILaunchManager . RUN_MODE , monitor ) ; while ( ! launch . isTerminated ( ) ) { if ( monitor . isCanceled ( ) ) { launch . terminate ( ) ; return Status . CANCEL_STATUS ; } Thread . yield ( ) ; } refresh ( monitor ) ; return Status . OK_STATUS ; } catch ( CoreException e ) { return e . getStatus ( ) ; } } public IStatus installGem ( Gem gem , String sourceURL , IProgressMonitor monitor ) { return installGem ( gem , sourceURL , true , new NullProgressMonitor ( ) ) ; } private IStatus doInstallGem ( final Gem gem , String command , IProgressMonitor monitor ) { SubMonitor progress = SubMonitor . convert ( monitor , ) ; if ( ! isRubyGemsInstalled ( ) ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . PLUGIN_ID , - , "" , null ) ; try { ILaunchConfiguration config = createGemLaunchConfiguration ( command , true ) ; final ILaunch launch = config . launch ( ILaunchManager . RUN_MODE , null ) ; progress . worked ( ) ; while ( ! launch . isTerminated ( ) ) { if ( progress . isCanceled ( ) ) { try { launch . terminate ( ) ; } catch ( DebugException e ) { } return Status . CANCEL_STATUS ; } Thread . yield ( ) ; } progress . worked ( ) ; refresh ( progress . newChild ( ) ) ; for ( GemListener listener : listeners ) { listener . gemAdded ( gem ) ; } progress . worked ( ) ; return Status . OK_STATUS ; } catch ( CoreException e ) { return e . getStatus ( ) ; } finally { progress . done ( ) ; } } private IStatus doLocalInstallGem ( final Gem gem , IProgressMonitor monitor ) { SubMonitor progress = SubMonitor . convert ( monitor , ) ; progress . setTaskName ( "" + gem . getName ( ) ) ; if ( ! isRubyGemsInstalled ( ) ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . PLUGIN_ID , - , "" , null ) ; try { String command = INSTALL_COMMAND + "" + new File ( gem . getAbsolutePath ( ) ) . getName ( ) + "" ; ILaunchConfiguration config = createGemLaunchConfiguration ( command , true ) ; ILaunchConfigurationWorkingCopy wc = config . getWorkingCopy ( ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , new File ( gem . getAbsolutePath ( ) ) . getParent ( ) ) ; config = wc . doSave ( ) ; final ILaunch launch = config . launch ( ILaunchManager . RUN_MODE , null ) ; while ( ! launch . isTerminated ( ) ) { if ( monitor . isCanceled ( ) ) { try { launch . terminate ( ) ; } catch ( DebugException e ) { } return Status . CANCEL_STATUS ; } Thread . yield ( ) ; } progress . worked ( ) ; refresh ( progress . newChild ( ) ) ; for ( GemListener listener : new ArrayList < GemListener > ( listeners ) ) { listener . gemAdded ( gem ) ; } progress . worked ( ) ; return Status . OK_STATUS ; } catch ( CoreException e ) { return e . getStatus ( ) ; } finally { progress . done ( ) ; } } private IStatus installGem ( final Gem gem , String sourceURL , boolean includeDependencies , IProgressMonitor monitor ) { SubMonitor progress = SubMonitor . convert ( monitor , ) ; if ( ! gem . isInstallable ( ) ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . getPluginId ( ) , "" + gem . getName ( ) ) ; if ( gem . getName ( ) == null || gem . getName ( ) . trim ( ) . length ( ) == ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . getPluginId ( ) , "" ) ; if ( progress . isCanceled ( ) ) return Status . CANCEL_STATUS ; String command = INSTALL_COMMAND + "" + gem . getName ( ) ; if ( gem . getVersion ( ) != null && gem . getVersion ( ) . trim ( ) . length ( ) > ) { command += "" + VERSION_SWITCH + "" + gem . getVersion ( ) ; } if ( getVersion ( ) == null || getVersion ( ) . isGreaterThanOrEqualTo ( "" ) ) { if ( ! includeDependencies ) { command += "" ; } } else { if ( includeDependencies ) { command += "" + INCLUDE_DEPENDENCIES_SWITCH ; } } if ( sourceURL != null && ! sourceURL . equals ( DEFAULT_GEM_HOST ) ) { command += "" + SOURCE_SWITCH + "" + sourceURL ; } command = addProxy ( sourceURL , command ) ; progress . worked ( ) ; return doInstallGem ( gem , command , progress . newChild ( ) ) ; } private String addProxy ( String host , String command ) { IProxyService service = getProxyService ( ) ; if ( service == null || ! service . isProxiesEnabled ( ) ) return command ; IProxyData proxyData = service . getProxyDataForHost ( host , IProxyData . HTTP_PROXY_TYPE ) ; if ( proxyData == null ) return command ; StringBuilder proxyLine = new StringBuilder ( "" ) ; if ( proxyData . isRequiresAuthentication ( ) ) { proxyLine . append ( proxyData . getUserId ( ) ) ; proxyLine . append ( "" ) ; proxyLine . append ( proxyData . getPassword ( ) ) ; proxyLine . append ( "" ) ; } proxyLine . append ( proxyData . getHost ( ) ) ; proxyLine . append ( "" ) ; proxyLine . append ( proxyData . getPort ( ) ) ; return command + proxyLine ; } private IProxyService getProxyService ( ) { return AptanaRDTPlugin . getDefault ( ) . getProxyService ( ) ; } public Set < GemRequirement > getDependencies ( Gem gem ) { if ( ! isRubyGemsInstalled ( ) ) return Collections . emptySet ( ) ; String command = "" + gem . getName ( ) + "" + gem . getVersion ( ) ; File file = getStateFile ( "" + gem . getName ( ) + "" + gem . getVersion ( ) + "" ) ; String output = launchInBackgroundAndRead ( command , file ) ; Set < GemRequirement > requirements = parseDependencies ( output ) ; if ( requirements . isEmpty ( ) && gem . getName ( ) . equals ( "" ) ) { AptanaRDTPlugin . log ( "" ) ; } return requirements ; } private Set < GemRequirement > parseDependencies ( String output ) { if ( output == null ) return Collections . emptySet ( ) ; Set < GemRequirement > dependencies = new HashSet < GemRequirement > ( ) ; Pattern pat = Pattern . compile ( "" ) ; String [ ] lines = output . split ( "" ) ; for ( int i = ; i < lines . length ; i ++ ) { String line = lines [ i ] ; Matcher matcher = pat . matcher ( line ) ; if ( ! matcher . find ( ) ) continue ; String name = matcher . group ( ) ; String version = matcher . group ( ) ; dependencies . add ( new GemRequirement ( name , version ) ) ; } return dependencies ; } public Gem findGem ( GemRequirement dependency ) { for ( Gem gem : gems ) { if ( gem instanceof LogicalGem ) { LogicalGem logical = ( LogicalGem ) gem ; Collection < Gem > logicalsGems = logical . getGems ( ) ; for ( Gem gem2 : logicalsGems ) { if ( gem2 . meetsRequirements ( dependency ) ) return gem2 ; } } if ( gem . meetsRequirements ( dependency ) ) return gem ; } return null ; } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { fVersion = null ; fGemInstallPaths = null ; Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { return refresh ( monitor ) ; } } ; job . schedule ( ) ; } public void vmAdded ( IVMInstall newVm ) { } public void vmChanged ( PropertyChangeEvent event ) { } public void vmRemoved ( IVMInstall removedVm ) { } public List < Version > getVersions ( String gemName ) { List < Version > versions = new ArrayList < Version > ( ) ; for ( Gem gem : gems ) { if ( gem . getName ( ) . equals ( gemName ) ) { versions . add ( gem . getVersionObject ( ) ) ; } } return versions ; } public String getName ( ) { return "" ; } public IStatus updateSystem ( IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; monitor . beginTask ( "" , ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; IStatus status = null ; if ( getVersion ( ) != null && getVersion ( ) . isLessThan ( "" ) ) { status = updateRubygems ( monitor , "" ) ; if ( status != null && ! status . isOK ( ) ) return status ; } return updateRubygems ( monitor , Gem . ANY_VERSION ) ; } private IStatus updateRubygems ( IProgressMonitor monitor , String version ) { IProgressMonitor subMonitor = new SubProgressMonitor ( monitor , ) ; IStatus status = installGem ( new Gem ( RUBYGEMS_UPDATE_GEM_NAME , version , null ) , subMonitor ) ; subMonitor . done ( ) ; if ( ! status . isOK ( ) ) return status ; try { ILaunchConfiguration config = createGemLaunchConfiguration ( "" , true ) ; ILaunchConfigurationWorkingCopy wc = config . getWorkingCopy ( ) ; String fileName = getFileIfExists ( UPDATE_RUBYGEMS_COMMAND ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , fileName ) ; config = wc . doSave ( ) ; ILaunch launch = config . launch ( ILaunchManager . RUN_MODE , monitor ) ; while ( ! launch . isTerminated ( ) ) { if ( monitor . isCanceled ( ) ) { launch . terminate ( ) ; return Status . CANCEL_STATUS ; } Thread . yield ( ) ; } monitor . done ( ) ; if ( launch . getProcesses ( ) != null && launch . getProcesses ( ) [ ] != null && launch . getProcesses ( ) [ ] . getExitValue ( ) != ) return new Status ( IStatus . ERROR , AptanaRDTPlugin . PLUGIN_ID , - , "" , null ) ; fVersion = null ; } catch ( CoreException e ) { return e . getStatus ( ) ; } return Status . OK_STATUS ; } private String getFileIfExists ( String command ) { IPath path = RubyRuntime . checkInterpreterBin ( command ) ; if ( path != null && path . toFile ( ) . exists ( ) ) { return path . toOSString ( ) ; } path = RubyCore . checkSystemPath ( command ) ; if ( path != null && path . toFile ( ) . exists ( ) ) return path . toOSString ( ) ; return null ; } } package com . aptana . rdt . internal . core . gems ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import org . xml . sax . Attributes ; import org . xml . sax . ContentHandler ; import org . xml . sax . Locator ; import org . xml . sax . SAXException ; import com . aptana . rdt . core . gems . Gem ; public class GemManagerContentHandler implements ContentHandler { private HashSet < Gem > gems ; private String name ; private String version ; private String description ; private StringBuffer data = new StringBuffer ( ) ; private String platform ; public void characters ( char [ ] ch , int start , int length ) throws SAXException { for ( int i = start ; i < start + length ; i ++ ) { data . append ( ch [ i ] ) ; } } public void endDocument ( ) throws SAXException { } public void endElement ( String namespaceURI , String localName , String qName ) throws SAXException { if ( qName . equals ( "" ) ) { name = data . toString ( ) ; } else if ( qName . equals ( "" ) ) { version = data . toString ( ) ; } else if ( qName . equals ( "" ) ) { description = data . toString ( ) ; } else if ( qName . equals ( "" ) ) { platform = data . toString ( ) ; } else if ( qName . equals ( "" ) ) { if ( version . indexOf ( "" ) != - ) { String [ ] versions = version . split ( "" ) ; for ( int i = ; i < versions . length ; i ++ ) { gems . add ( new Gem ( name , versions [ i ] , description , platform ) ) ; } } else { gems . add ( new Gem ( name , version , description , platform ) ) ; } } data . delete ( , data . length ( ) ) ; } public void endPrefixMapping ( String arg0 ) throws SAXException { } public void ignorableWhitespace ( char [ ] arg0 , int arg1 , int arg2 ) throws SAXException { } public void processingInstruction ( String arg0 , String arg1 ) throws SAXException { } public void setDocumentLocator ( Locator arg0 ) { } public void skippedEntity ( String arg0 ) throws SAXException { } public void startDocument ( ) throws SAXException { gems = new HashSet < Gem > ( ) ; } public void startElement ( String namespaceURI , String localName , String qName , Attributes atts ) throws SAXException { } public void startPrefixMapping ( String arg0 , String arg1 ) throws SAXException { } public Set < Gem > getGems ( ) { return Collections . unmodifiableSet ( gems ) ; } } package com . aptana . rdt . internal . core . gems ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . AptanaRDTPlugin ; public class RubyGemsInitializer extends Job implements IVMInstallChangedListener { private boolean initialized ; public RubyGemsInitializer ( ) { super ( "" ) ; } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { if ( current == null ) return ; if ( ! initialized ) { initialize ( ) ; } } public void vmAdded ( IVMInstall newVm ) { } public void vmChanged ( PropertyChangeEvent event ) { } public void vmRemoved ( IVMInstall removedVm ) { } @ Override protected IStatus run ( IProgressMonitor monitor ) { monitor . beginTask ( "" , ) ; if ( rubyInstalled ( ) ) { Bundle bundle = Platform . getBundle ( "" ) ; while ( bundle . getState ( ) != Bundle . ACTIVE ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { } } initialize ( ) ; } RubyRuntime . addVMInstallChangedListener ( this ) ; monitor . done ( ) ; return Status . OK_STATUS ; } private void initialize ( ) { AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . initialize ( ) ; initialized = true ; try { Platform . getBundle ( "" ) . loadClass ( "" ) ; } catch ( Exception e ) { } } private boolean rubyInstalled ( ) { return RubyRuntime . getDefaultVMInstall ( ) != null ; } } package com . aptana . rdt . internal . core . gems ; import java . util . Set ; import com . aptana . rdt . core . gems . Gem ; public interface IGemParser { public Set < Gem > parse ( String string ) throws GemParseException ; } package com . aptana . rdt . internal . core . gems ; import java . util . HashSet ; import java . util . Set ; import org . xml . sax . Attributes ; import org . xml . sax . ContentHandler ; import org . xml . sax . Locator ; import org . xml . sax . SAXException ; public class SourceURLContentHandler implements ContentHandler { private HashSet < String > urls ; private StringBuffer data ; public void characters ( char [ ] ch , int start , int length ) throws SAXException { for ( int i = start ; i < start + length ; i ++ ) { data . append ( ch [ i ] ) ; } } public void endDocument ( ) throws SAXException { } public void endElement ( String namespaceURI , String localName , String qName ) throws SAXException { if ( qName . equals ( "" ) ) { urls . add ( data . toString ( ) ) ; } } public void endPrefixMapping ( String arg0 ) throws SAXException { } public void ignorableWhitespace ( char [ ] arg0 , int arg1 , int arg2 ) throws SAXException { } public void processingInstruction ( String arg0 , String arg1 ) throws SAXException { } public void setDocumentLocator ( Locator arg0 ) { } public void skippedEntity ( String arg0 ) throws SAXException { } public void startDocument ( ) throws SAXException { urls = new HashSet < String > ( ) ; } public void startElement ( String namespaceURI , String localName , String qName , Attributes atts ) throws SAXException { data = new StringBuffer ( ) ; } public void startPrefixMapping ( String arg0 , String arg1 ) throws SAXException { } public Set < String > getURLs ( ) { return urls ; } } package com . aptana . rdt . internal . core . gems ; public class GemParseException extends Exception { private static final long serialVersionUID = ; public GemParseException ( String string ) { super ( string ) ; } } package com . aptana . rdt . internal . core . gems ; import org . eclipse . osgi . util . NLS ; public class GemsMessages extends NLS { private static final String BUNDLE_NAME = GemsMessages . class . getName ( ) ; public static String GemManager_loading_local_gems ; public static String GemManager_loading_remote_gems ; static { NLS . initializeMessages ( BUNDLE_NAME , GemsMessages . class ) ; } } package com . aptana . rdt . internal . core . gems ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . StringTokenizer ; import com . aptana . rdt . core . gems . Gem ; public class ShortListingGemParser extends LegacyGemParser { @ Override protected Set < Gem > parseOutGems ( List < String > lines ) throws GemParseException { Set < Gem > gems = new HashSet < Gem > ( ) ; for ( String line : lines ) { int openParen = line . indexOf ( "" ) ; String name = line . substring ( , openParen ) . trim ( ) ; int closeParen = line . indexOf ( "" , openParen ) ; String versions = line . substring ( openParen + , closeParen ) ; StringTokenizer tokenizer = new StringTokenizer ( versions , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) { String version = tokenizer . nextToken ( ) ; gems . add ( new Gem ( name , version . trim ( ) , null ) ) ; } } return gems ; } } package com . aptana . rdt . internal . core . gems ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import com . aptana . rdt . core . gems . Gem ; public class GemOnePointTwoParser extends LegacyGemParser { private static final Pattern NAME_AND_VERSION_PATTERN = Pattern . compile ( "" ) ; public GemOnePointTwoParser ( String string ) { super ( string ) ; } public GemOnePointTwoParser ( boolean strict ) { super ( strict ) ; } protected Set < Gem > parseOutGems ( List < String > lines ) throws GemParseException { Set < Gem > gems = new HashSet < Gem > ( ) ; if ( lines == null || lines . isEmpty ( ) ) return gems ; if ( lines . get ( ) . startsWith ( "" ) ) return gems ; String nameAndVersion = null ; String description = null ; while ( true ) { while ( true ) { if ( lines . isEmpty ( ) ) break ; String nextLine = lines . remove ( ) ; if ( nameAndVersion == null ) { nameAndVersion = nextLine ; continue ; } if ( nextLine . trim ( ) . length ( ) == ) { if ( description == null ) { description = nextLine ; continue ; } } if ( description != null ) { Matcher m = NAME_AND_VERSION_PATTERN . matcher ( nextLine ) ; if ( m . find ( ) ) { lines . add ( , nextLine ) ; break ; } description += "" + nextLine . trim ( ) ; } } if ( description == null || description . length ( ) == ) { if ( strict ) { throw new GemParseException ( "" ) ; } else { return gems ; } } int openParen = nameAndVersion . indexOf ( '' ) ; int closeParen = nameAndVersion . indexOf ( '' ) ; String name = nameAndVersion . substring ( , openParen ) ; String version = nameAndVersion . substring ( openParen + , closeParen ) ; if ( version . indexOf ( "" ) != - ) { String [ ] versions = version . split ( "" ) ; for ( int y = ; y < versions . length ; y ++ ) gems . add ( new Gem ( name . trim ( ) , versions [ y ] , description . trim ( ) ) ) ; } else { gems . add ( new Gem ( name . trim ( ) , version , description . trim ( ) ) ) ; } nameAndVersion = null ; description = null ; if ( lines . isEmpty ( ) ) break ; } return gems ; } } package com . aptana . rdt . internal . core . gems ; import java . util . Collections ; import java . util . Set ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . Version ; public class HybridGemParser implements IGemParser { private IGemParser [ ] parsers ; public HybridGemParser ( Version version ) { if ( version != null && version . isLessThan ( "" ) ) { parsers = new IGemParser [ ] { new LegacyGemParser ( true ) , new GemOnePointTwoParser ( true ) } ; } else { parsers = new IGemParser [ ] { new GemOnePointTwoParser ( true ) , new LegacyGemParser ( true ) } ; } } public Set < Gem > parse ( String string ) { for ( int i = ; i < parsers . length ; i ++ ) { try { Set < Gem > gems = parsers [ i ] . parse ( string ) ; if ( gems != null && ! gems . isEmpty ( ) ) return gems ; } catch ( GemParseException e ) { AptanaRDTPlugin . log ( e ) ; } } return Collections . emptySet ( ) ; } } package com . aptana . rdt . internal . launching ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceDescription ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . rubypeople . rdt . core . LoadpathVariableInitializer ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . launching . IGemRuntime ; public class GemLoadpathVariablesInitializer extends LoadpathVariableInitializer implements IVMInstallChangedListener { private static final String LEOPARD_GEM_PATH_1 = "" ; private static final String LEOPARD_GEM_PATH_2 = "" ; private IProgressMonitor fMonitor ; public GemLoadpathVariablesInitializer ( ) { RubyRuntime . addVMInstallChangedListener ( this ) ; } @ Override public void initialize ( final String variable ) { if ( ! variable . equals ( IGemRuntime . GEMLIB_VARIABLE ) ) return ; IVMInstall vmInstall = RubyRuntime . getDefaultVMInstall ( ) ; if ( vmInstall == null ) return ; setQuickNDirtyPaths ( variable , vmInstall ) ; Job realJob = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { IGemManager gemManager = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) ; List < IPath > gemPaths = null ; int tries = ; while ( tries > ) { gemPaths = gemManager . getGemInstallPaths ( ) ; if ( gemPaths != null ) break ; tries -- ; } if ( gemPaths == null ) { gemPaths = loadCachedValue ( ) ; } else { saveValue ( gemPaths ) ; } if ( gemPaths == null ) { return new Status ( Status . ERROR , AptanaRDTPlugin . PLUGIN_ID , - , "" , null ) ; } IPath [ ] paths = new IPath [ gemPaths . size ( ) ] ; int i = ; for ( IPath path : gemPaths ) { paths [ i ++ ] = path . append ( "" ) ; } if ( RubyRuntime . currentVMIsCygwin ( ) ) { File home = RubyRuntime . getDefaultVMInstall ( ) . getInstallLocation ( ) ; for ( int x = ; x < paths . length ; x ++ ) { String portablePath = paths [ x ] . toOSString ( ) ; if ( portablePath . startsWith ( "" ) ) { portablePath = portablePath . substring ( ) ; } String cygwinConverted = home . getAbsolutePath ( ) + portablePath ; IPath path = new Path ( cygwinConverted ) ; paths [ x ] = path ; } } setVariable ( variable , paths ) ; return Status . OK_STATUS ; } private void saveValue ( List < IPath > gemPaths ) { File file = getCacheFile ( ) ; FileWriter writer = null ; try { if ( ! file . exists ( ) ) file . createNewFile ( ) ; writer = new FileWriter ( file ) ; for ( IPath gemPath : gemPaths ) { writer . write ( gemPath . toPortableString ( ) + "" ) ; } } catch ( IOException e ) { AptanaRDTPlugin . log ( e ) ; } finally { try { if ( writer != null ) writer . close ( ) ; } catch ( IOException e ) { } } } private File getCacheFile ( ) { IPath path = AptanaRDTPlugin . getDefault ( ) . getStateLocation ( ) . append ( RubyRuntime . getDefaultVMInstall ( ) . getId ( ) + "" ) ; return path . toFile ( ) ; } private List < IPath > loadCachedValue ( ) { List < IPath > paths = new ArrayList < IPath > ( ) ; try { String contents = new String ( Util . getFileCharContent ( getCacheFile ( ) , null ) ) ; String [ ] rawPaths = contents . split ( "" ) ; for ( int i = ; i < rawPaths . length ; i ++ ) { paths . add ( Path . fromPortableString ( rawPaths [ i ] ) ) ; } } catch ( IOException e ) { AptanaRDTPlugin . log ( e ) ; } return paths ; } } ; realJob . setSystem ( true ) ; realJob . setPriority ( Job . LONG ) ; realJob . schedule ( ) ; } private void setQuickNDirtyPaths ( final String variable , IVMInstall vmInstall ) { if ( Platform . getOS ( ) . equals ( Platform . OS_MACOSX ) && ! RubyRuntime . currentVMIsJRuby ( ) ) { File dir = new File ( LEOPARD_GEM_PATH_2 ) ; if ( dir . exists ( ) ) { setVariable ( variable , new IPath [ ] { new Path ( LEOPARD_GEM_PATH_1 ) , new Path ( LEOPARD_GEM_PATH_2 ) } ) ; return ; } } IPath quickNDirty = new Path ( vmInstall . getInstallLocation ( ) . getAbsolutePath ( ) ) . append ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) . append ( "" ) ; setVariable ( variable , new IPath [ ] { quickNDirty } ) ; } private void setVariable ( String variable , IPath newPath [ ] ) { IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; IWorkspaceDescription wsDescription = workspace . getDescription ( ) ; boolean wasAutobuild = wsDescription . isAutoBuilding ( ) ; try { setAutobuild ( workspace , false ) ; setRubyVMVariable ( newPath , variable ) ; } catch ( CoreException ce ) { LaunchingPlugin . log ( ce ) ; return ; } finally { try { setAutobuild ( workspace , wasAutobuild ) ; } catch ( CoreException ce ) { LaunchingPlugin . log ( ce ) ; } } } private void setRubyVMVariable ( IPath [ ] newPath , String var ) throws CoreException { RubyCore . setLoadpathVariable ( var , newPath , getMonitor ( ) ) ; } private boolean setAutobuild ( IWorkspace ws , boolean newState ) throws CoreException { IWorkspaceDescription wsDescription = ws . getDescription ( ) ; boolean oldState = wsDescription . isAutoBuilding ( ) ; if ( oldState != newState ) { wsDescription . setAutoBuilding ( newState ) ; ws . setDescription ( wsDescription ) ; } return oldState ; } protected IProgressMonitor getMonitor ( ) { if ( fMonitor == null ) { return new NullProgressMonitor ( ) ; } return fMonitor ; } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { initialize ( IGemRuntime . GEMLIB_VARIABLE ) ; } public void vmAdded ( IVMInstall newVm ) { } public void vmChanged ( PropertyChangeEvent event ) { } public void vmRemoved ( IVMInstall removedVm ) { } } package com . aptana . rdt . internal . parser . warnings ; import org . jruby . ast . ConstDeclNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class ConstantNamingConvention extends RubyLintVisitor { public ConstantNamingConvention ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_CONSTANT_NAMING_CONVENTION ; } @ Override public Object visitConstDeclNode ( ConstDeclNode iVisited ) { String name = iVisited . getName ( ) ; if ( ! name . toUpperCase ( ) . equals ( name ) ) { ISourcePosition pos = iVisited . getPosition ( ) ; IDESourcePosition duh = new IDESourcePosition ( pos . getFile ( ) , pos . getStartLine ( ) , pos . getEndLine ( ) , pos . getStartOffset ( ) , pos . getStartOffset ( ) + name . length ( ) ) ; createProblem ( duh , "" + name ) ; } return super . visitConstDeclNode ( iVisited ) ; } @ Override protected int getProblemID ( ) { return IProblem . ConstantNamingConvention ; } } package com . aptana . rdt . internal . parser . warnings ; import org . jruby . ast . FCallNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class RequireGemChecker extends RubyLintVisitor { private static final String REQUIRE_GEM = "" ; private static final String MSG = "" ; public RequireGemChecker ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_DEPRECATED_REQUIRE_GEM ; } @ Override public Object visitFCallNode ( FCallNode iVisited ) { if ( iVisited . getName ( ) . equals ( REQUIRE_GEM ) ) createProblem ( iVisited . getPosition ( ) , MSG ) ; return super . visitFCallNode ( iVisited ) ; } @ Override protected int getProblemID ( ) { return IProblem . DeprecatedRequireGem ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . List ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . LocalAsgnNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class LocalVariablePossibleAttributeAccess extends RubyLintVisitor { private List < LocalAsgnNode > locals = new ArrayList < LocalAsgnNode > ( ) ; private List < String > attributes = new ArrayList < String > ( ) ; private boolean insideMethodSignature ; public LocalVariablePossibleAttributeAccess ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_LOCAL_VARIABLE_POSSIBLE_ATTRIBUTE_ACCESS ; } @ Override public Object visitClassNode ( ClassNode iVisited ) { locals . clear ( ) ; attributes . clear ( ) ; return super . visitClassNode ( iVisited ) ; } @ Override public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { if ( ! insideMethodSignature ) locals . add ( iVisited ) ; return super . visitLocalAsgnNode ( iVisited ) ; } @ Override public Object visitArgsNode ( ArgsNode iVisited ) { insideMethodSignature = true ; return super . visitArgsNode ( iVisited ) ; } @ Override public void exitArgsNode ( ArgsNode iVisited ) { super . exitArgsNode ( iVisited ) ; insideMethodSignature = false ; } @ Override public Object visitFCallNode ( FCallNode iVisited ) { String name = iVisited . getName ( ) ; if ( name . equals ( "" ) || name . equals ( "" ) || name . equals ( "" ) ) { List < String > args = filterColonsFromSymbols ( ASTUtil . getArgumentsFromFunctionCall ( iVisited ) ) ; if ( name . equals ( "" ) ) { if ( args . size ( ) < ) { return super . visitFCallNode ( iVisited ) ; } if ( ! args . get ( ) . equals ( "" ) ) return super . visitFCallNode ( iVisited ) ; attributes . add ( args . get ( ) ) ; return super . visitFCallNode ( iVisited ) ; } attributes . addAll ( args ) ; } return super . visitFCallNode ( iVisited ) ; } private List < String > filterColonsFromSymbols ( List < String > args ) { if ( args == null ) return null ; List < String > newArgs = new ArrayList < String > ( ) ; for ( String string : args ) { if ( string . startsWith ( "" ) ) { string = string . substring ( ) ; } newArgs . add ( string ) ; } return newArgs ; } @ Override public void exitClassNode ( ClassNode iVisited ) { for ( LocalAsgnNode local : locals ) { if ( attributes . contains ( local . getName ( ) ) ) { createProblem ( local . getPosition ( ) , "" ) ; } } super . exitClassNode ( iVisited ) ; } @ Override protected int getProblemID ( ) { return IProblem . LocalVariablePossibleAttributeAccess ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . List ; import org . jruby . ast . IterNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . MultipleAsgnNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class DynamicVariableAliasesLocal extends RubyLintVisitor { public DynamicVariableAliasesLocal ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_DYNAMIC_VARIABLE_ALIASES_LOCAL ; } @ Override public Object visitIterNode ( IterNode iVisited ) { checkNode ( iVisited . getVarNode ( ) ) ; return super . visitIterNode ( iVisited ) ; } @ Override protected int getProblemID ( ) { return IProblem . DynamicVariableAliasesLocal ; } private void checkNode ( Node varNode ) { if ( varNode == null ) return ; if ( varNode instanceof ListNode ) { checkListNode ( ( ListNode ) varNode ) ; } else if ( varNode instanceof MultipleAsgnNode ) { MultipleAsgnNode multi = ( MultipleAsgnNode ) varNode ; checkList ( multi . childNodes ( ) ) ; } else if ( varNode instanceof LocalAsgnNode ) { createProblem ( varNode . getPosition ( ) , "" ) ; } } private void checkListNode ( ListNode node ) { checkList ( node . childNodes ( ) ) ; } private void checkList ( List < Node > list ) { for ( Node childNode : list ) { checkNode ( childNode ) ; } } } package com . aptana . rdt . internal . parser . warnings ; import java . util . Map ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class TooManyLinesVisitor extends RubyLintVisitor { public static final int DEFAULT_MAX_LINES = ; private int maxLines ; public TooManyLinesVisitor ( String contents ) { this ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } public TooManyLinesVisitor ( Map < String , String > options , String contents ) { super ( options , contents ) ; maxLines = getInt ( AptanaRDTPlugin . COMPILER_PB_MAX_LINES , DEFAULT_MAX_LINES ) ; } private int getInt ( String key , int defaultValue ) { try { return Integer . parseInt ( ( String ) fOptions . get ( key ) ) ; } catch ( NumberFormatException e ) { return defaultValue ; } } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_LINES ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { ISourcePosition pos = iVisited . getPosition ( ) ; int lines = ( pos . getEndLine ( ) - pos . getStartLine ( ) ) - ; if ( lines > maxLines ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" + lines ) ; } return super . visitDefsNode ( iVisited ) ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { ISourcePosition pos = iVisited . getPosition ( ) ; int lines = ( pos . getEndLine ( ) - pos . getStartLine ( ) ) - ; if ( lines > maxLines ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" + lines ) ; } return super . visitDefnNode ( iVisited ) ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . List ; import java . util . Map ; import org . jruby . ast . CaseNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . Node ; import org . jruby . ast . WhenNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class TooManyBranchesVisitor extends RubyLintVisitor { private int maxBranches ; private int branchCount ; public TooManyBranchesVisitor ( String contents ) { this ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } public TooManyBranchesVisitor ( Map < String , String > options , String contents ) { super ( options , contents ) ; maxBranches = getInt ( AptanaRDTPlugin . COMPILER_PB_MAX_BRANCHES , ) ; branchCount = ; } private int getInt ( String key , int defaultValue ) { try { return Integer . parseInt ( ( String ) fOptions . get ( key ) ) ; } catch ( NumberFormatException e ) { return defaultValue ; } } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_BRANCHES ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { branchCount = ; return super . visitDefsNode ( iVisited ) ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { branchCount = ; return super . visitDefnNode ( iVisited ) ; } @ Override public Object visitIfNode ( IfNode iVisited ) { if ( iVisited . getThenBody ( ) != null ) { branchCount ++ ; } if ( iVisited . getElseBody ( ) != null ) { branchCount ++ ; } return super . visitIfNode ( iVisited ) ; } @ Override public Object visitCaseNode ( CaseNode iVisited ) { List < Node > list = iVisited . getCases ( ) . childNodes ( ) ; WhenNode when = ( WhenNode ) list . get ( ) ; while ( when != null ) { branchCount ++ ; Node thing = when . getNextCase ( ) ; if ( thing instanceof WhenNode ) { when = ( WhenNode ) when . getNextCase ( ) ; } else { when = null ; } } return super . visitCaseNode ( iVisited ) ; } public void exitDefnNode ( DefnNode iVisited ) { if ( branchCount > maxBranches ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" + branchCount ) ; } branchCount = ; } @ Override public void exitDefsNode ( DefsNode iVisited ) { if ( branchCount > maxBranches ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" + branchCount ) ; } branchCount = ; super . exitDefsNode ( iVisited ) ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . jruby . ast . CaseNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . ReturnNode ; import org . jruby . ast . RootNode ; import org . jruby . ast . WhenNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class UnecessaryElseVisitor extends RubyLintVisitor { public UnecessaryElseVisitor ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_UNNECESSARY_ELSE ; } @ Override public Object visitIfNode ( IfNode iVisited ) { String src = getSource ( iVisited ) ; Node elseBody ; Node thenBody ; if ( src . startsWith ( "" ) ) { elseBody = iVisited . getThenBody ( ) ; thenBody = iVisited . getElseBody ( ) ; } else { elseBody = iVisited . getElseBody ( ) ; thenBody = iVisited . getThenBody ( ) ; } boolean isUnlessModifier = ( iVisited . getThenBody ( ) == null ) ; if ( elseBody != null && ! isUnlessModifier ) { if ( alwaysExplicitReturn ( thenBody ) ) { createProblem ( elseBody . getPosition ( ) , "" ) ; } } return super . visitIfNode ( iVisited ) ; } private boolean alwaysExplicitReturn ( Node body ) { if ( body == null ) return false ; ReturnVisitor visitor = new ReturnVisitor ( ) ; body . accept ( visitor ) ; return visitor . alwaysExplicit ( ) ; } private class ReturnVisitor extends InOrderVisitor { private boolean implicit = false ; private Set < ReturnVisitor > branches = new HashSet < ReturnVisitor > ( ) ; @ Override protected Object visitNode ( Node iVisited ) { if ( iVisited != null && ! structuralNode ( iVisited ) && ! branchingNode ( iVisited ) && ! ( iVisited instanceof ReturnNode ) ) { implicit = true ; } return super . visitNode ( iVisited ) ; } private boolean structuralNode ( Node visited ) { return ( visited instanceof RootNode ) || ( visited instanceof NewlineNode ) ; } private boolean branchingNode ( Node visited ) { return ( visited instanceof IfNode ) || ( visited instanceof CaseNode ) ; } @ Override public Object visitReturnNode ( ReturnNode iVisited ) { implicit = false ; return null ; } @ Override public Object visitCaseNode ( CaseNode iVisited ) { List < Node > list = iVisited . getCases ( ) . childNodes ( ) ; WhenNode whenNode = ( WhenNode ) list . get ( ) ; while ( whenNode != null ) { ReturnVisitor visitor = new ReturnVisitor ( ) ; whenNode . getBodyNode ( ) . accept ( visitor ) ; branches . add ( visitor ) ; whenNode = ( WhenNode ) whenNode . getNextCase ( ) ; } return null ; } @ Override public Object visitIfNode ( IfNode iVisited ) { if ( iVisited . getThenBody ( ) != null ) { ReturnVisitor visitor = new ReturnVisitor ( ) ; iVisited . getThenBody ( ) . accept ( visitor ) ; branches . add ( visitor ) ; } if ( iVisited . getElseBody ( ) != null ) { ReturnVisitor visitor = new ReturnVisitor ( ) ; iVisited . getElseBody ( ) . accept ( visitor ) ; branches . add ( visitor ) ; } else { implicit = true ; } return null ; } public boolean alwaysExplicit ( ) { for ( ReturnVisitor visitor : branches ) { if ( ! visitor . alwaysExplicit ( ) ) return false ; } return ! implicit ; } } } package com . aptana . rdt . internal . parser . warnings ; import java . util . HashSet ; import java . util . Set ; import org . jruby . ast . HashNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; public class DuplicateHashKeyVisitor extends RubyLintVisitor { public DuplicateHashKeyVisitor ( String code ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , code ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_DUPLICATE_HASH_KEY ; } @ Override public Object visitHashNode ( HashNode visited ) { ListNode list = visited . getListNode ( ) ; Set < String > keys = new HashSet < String > ( ) ; for ( int i = ; i < list . size ( ) ; i ++ ) { if ( i % != ) continue ; Node node = list . get ( i ) ; String name = ASTUtil . stringValue ( node ) ; if ( name == null ) continue ; if ( keys . contains ( name ) ) { createProblem ( node . getPosition ( ) , "" + name + "" ) ; } keys . add ( name ) ; } return super . visitHashNode ( visited ) ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . SubMonitor ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyModelMarker ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . compiler . BuildContext ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . CompilationParticipant ; import org . rubypeople . rdt . core . compiler . ReconcileContext ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class RubyRedLint extends CompilationParticipant { @ Override public void reconcile ( ReconcileContext context ) { try { List < CategorizedProblem > problems = handleFile ( context . getWorkingCopy ( ) . getElementName ( ) , context . getWorkingCopy ( ) . getSource ( ) , context . getAST ( ) ) ; addProblems ( context , IRubyModelMarker . RUBY_MODEL_PROBLEM_MARKER , problems ) ; } catch ( RubyModelException e ) { AptanaRDTPlugin . log ( e ) ; } } private List < CategorizedProblem > handleFile ( String name , String contents , Node ast ) { if ( ast == null ) return Collections . emptyList ( ) ; List < RubyLintVisitor > visitors = createLintVisitors ( contents ) ; List < CategorizedProblem > problems = new ArrayList < CategorizedProblem > ( ) ; for ( RubyLintVisitor visitor : visitors ) { ast . accept ( visitor ) ; problems . addAll ( visitor . getProblems ( ) ) ; } return problems ; } @ Override public void buildStarting ( BuildContext [ ] files , boolean isBatch , IProgressMonitor monitor ) { SubMonitor sub = SubMonitor . convert ( monitor , files . length ) ; for ( BuildContext context : files ) { sub . subTask ( "" + context . getFile ( ) . getLocation ( ) . toPortableString ( ) ) ; String contents = new String ( context . getContents ( ) ) ; List < CategorizedProblem > problems = handleFile ( context . getFile ( ) . getName ( ) , contents , context . getAST ( ) ) ; context . recordNewProblems ( problems . toArray ( new CategorizedProblem [ problems . size ( ) ] ) ) ; sub . worked ( ) ; } sub . done ( ) ; } @ Override public boolean isActive ( IRubyProject project ) { return true ; } private List < RubyLintVisitor > createLintVisitors ( String contents ) { List < RubyLintVisitor > visitors = new ArrayList < RubyLintVisitor > ( ) ; visitors . add ( new AccidentalBooleanAssignmentVisitor ( contents ) ) ; visitors . add ( new UnusedPrivateMethodVisitor ( contents ) ) ; visitors . add ( new MisspelledConstructorVisitor ( contents ) ) ; visitors . add ( new LocalsMaskingMethodsVisitor ( contents ) ) ; visitors . add ( new UnusedParameterVisitor ( contents ) ) ; visitors . add ( new UnecessaryElseVisitor ( contents ) ) ; visitors . add ( new TooManyLocalsVisitor ( contents ) ) ; visitors . add ( new TooManyLinesVisitor ( contents ) ) ; visitors . add ( new TooManyBranchesVisitor ( contents ) ) ; visitors . add ( new TooManyArgumentsVisitor ( contents ) ) ; visitors . add ( new TooManyReturnsVisitor ( contents ) ) ; visitors . add ( new SimilarVariableNameVisitor ( contents ) ) ; visitors . add ( new SubclassCallsSuper ( contents ) ) ; visitors . add ( new ComparableInclusionVisitor ( contents ) ) ; visitors . add ( new EnumerableInclusionVisitor ( contents ) ) ; visitors . add ( new AndOrUsedOnRighthandAssignment ( contents ) ) ; visitors . add ( new ConstantNamingConvention ( contents ) ) ; visitors . add ( new MethodMissingWithoutRespondTo ( contents ) ) ; visitors . add ( new DynamicVariableAliasesLocal ( contents ) ) ; visitors . add ( new LocalVariablePossibleAttributeAccess ( contents ) ) ; visitors . add ( new LocalAndMethodNamingConvention ( contents ) ) ; visitors . add ( new UnusedLocalVariable ( contents ) ) ; visitors . add ( new RequireGemChecker ( contents ) ) ; visitors . add ( new RetryOutsideRescueBodyChecker ( contents ) ) ; visitors . add ( new DuplicateHashKeyVisitor ( contents ) ) ; visitors . add ( new ControlCouple ( contents ) ) ; visitors . add ( new FeatureEnvy ( contents ) ) ; List < RubyLintVisitor > filtered = new ArrayList < RubyLintVisitor > ( ) ; for ( RubyLintVisitor visitor : visitors ) { if ( visitor . isIgnored ( ) ) continue ; filtered . add ( visitor ) ; } return filtered ; } } package com . aptana . rdt . internal . parser . warnings ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class EnumerableInclusionVisitor extends RubyLintVisitor { private static final String INCLUDE = "" ; private static final String ENUMERABLE_METHOD = "" ; private static final String ENUMERABLE = "" ; private boolean includedEnumerable = false ; private boolean definedEnumerableMethod ; private ISourcePosition pos ; public EnumerableInclusionVisitor ( String code ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , code ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_ENUMERABLE_MISSING_METHOD ; } @ Override public Object visitFCallNode ( FCallNode iVisited ) { if ( includedEnumerable ) return null ; String callName = iVisited . getName ( ) ; if ( ! callName . equals ( INCLUDE ) ) return null ; Node args = iVisited . getArgsNode ( ) ; if ( args instanceof ArrayNode ) { ArrayNode array = ( ArrayNode ) args ; for ( Object arg : array . childNodes ( ) ) { if ( ! ( arg instanceof ConstNode ) ) continue ; ConstNode constNode = ( ConstNode ) arg ; if ( ! ( constNode . getName ( ) . equals ( ENUMERABLE ) ) ) continue ; pos = constNode . getPosition ( ) ; includedEnumerable = true ; return null ; } } return null ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { String methodName = iVisited . getName ( ) ; if ( methodName . equals ( ENUMERABLE_METHOD ) ) { definedEnumerableMethod = true ; } return super . visitDefnNode ( iVisited ) ; } @ Override public void exitClassNode ( ClassNode iVisited ) { if ( includedEnumerable && ! definedEnumerableMethod ) { createProblem ( pos , "" ) ; } includedEnumerable = false ; pos = null ; definedEnumerableMethod = false ; } @ Override protected int getProblemID ( ) { return IProblem . EnumerableInclusionMissingEachMethod ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . regex . Pattern ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class UncommunicativeName extends RubyLintVisitor { private static List < Pattern > reject = new ArrayList < Pattern > ( ) ; private static List < String > accept = new ArrayList < String > ( ) ; static { reject . add ( Pattern . compile ( "" ) ) ; accept . add ( "" ) ; } private List < Node > scopes ; private Map < Node , Map < String , Node > > scopedVariables ; public UncommunicativeName ( String src ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , src ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_UNCOMMUNICATIVE_NAME ; } @ Override protected int getProblemID ( ) { return IProblem . UncommunicativeName ; } @ Override public Object visitRootNode ( RootNode visited ) { scopes = new ArrayList < Node > ( ) ; scopedVariables = new HashMap < Node , Map < String , Node > > ( ) ; pushScope ( visited ) ; return super . visitRootNode ( visited ) ; } @ Override public void exitRootNode ( RootNode visited ) { popScope ( ) ; scopes = null ; scopedVariables = null ; super . exitRootNode ( visited ) ; } private void popScope ( ) { Node scopingNode = scopes . remove ( ) ; Map < String , Node > varsInScope = scopedVariables . get ( scopingNode ) ; for ( Map . Entry < String , Node > entry : varsInScope . entrySet ( ) ) { considerVariable ( entry . getKey ( ) , entry . getValue ( ) ) ; } } private void pushScope ( Node visited ) { scopes . add ( visited ) ; scopedVariables . put ( visited , new HashMap < String , Node > ( ) ) ; } @ Override public Object visitModuleNode ( ModuleNode visited ) { considerName ( visited ) ; pushScope ( visited ) ; return super . visitModuleNode ( visited ) ; } @ Override public Object visitClassNode ( ClassNode visited ) { considerName ( visited ) ; pushScope ( visited ) ; return super . visitClassNode ( visited ) ; } @ Override public Object visitDefnNode ( DefnNode visited ) { considerName ( visited ) ; return super . visitDefnNode ( visited ) ; } @ Override public Object visitDefsNode ( DefsNode visited ) { considerName ( visited ) ; return super . visitDefsNode ( visited ) ; } private void considerName ( Node node ) { String fullName = fullyQualifiedName ( node ) ; if ( accept . contains ( fullName ) ) return ; String shortName = ASTUtil . getNameReflectively ( node ) ; if ( isBadName ( shortName ) ) { createProblem ( node . getPosition ( ) , "" + fullName ) ; } } private String fullyQualifiedName ( Node node ) { if ( node instanceof MethodDefNode ) return ( ( MethodDefNode ) node ) . getName ( ) ; return ASTUtil . getFullyQualifiedTypeName ( getRootNode ( ) , node ) ; } private Node getRootNode ( ) { if ( scopes == null || scopes . isEmpty ( ) ) return null ; return scopes . get ( ) ; } private boolean isBadName ( String var ) { if ( var . equals ( "" ) || accept . contains ( var ) ) return false ; for ( Pattern p : reject ) { if ( p . matcher ( var ) . find ( ) ) return true ; } return false ; } @ Override public Object visitLocalAsgnNode ( LocalAsgnNode visited ) { addVariable ( visited . getName ( ) , visited ) ; return super . visitLocalAsgnNode ( visited ) ; } @ Override public Object visitConstDeclNode ( ConstDeclNode visited ) { addVariable ( visited . getName ( ) , visited ) ; return super . visitConstDeclNode ( visited ) ; } @ Override public Object visitClassVarDeclNode ( ClassVarDeclNode visited ) { addVariable ( visited . getName ( ) , visited ) ; return super . visitClassVarDeclNode ( visited ) ; } @ Override public Object visitClassVarAsgnNode ( ClassVarAsgnNode visited ) { addVariable ( visited . getName ( ) , visited ) ; return super . visitClassVarAsgnNode ( visited ) ; } private void addVariable ( String name , Node visited ) { Node enclosingScope = null ; if ( visited instanceof ClassVarNode || visited instanceof ClassVarDeclNode || visited instanceof ClassVarAsgnNode || visited instanceof InstVarNode || visited instanceof InstAsgnNode || visited instanceof ConstDeclNode ) { for ( int i = scopes . size ( ) - ; i >= ; i -- ) { enclosingScope = scopes . get ( i ) ; if ( enclosingScope instanceof ClassNode || enclosingScope instanceof RootNode || enclosingScope instanceof ModuleNode ) break ; } } else { enclosingScope = scopes . get ( scopes . size ( ) - ) ; } Map < String , Node > vars = scopedVariables . get ( enclosingScope ) ; if ( vars == null ) { vars = new HashMap < String , Node > ( ) ; scopedVariables . put ( enclosingScope , vars ) ; } if ( vars . containsKey ( name ) ) return ; vars . put ( name , visited ) ; } @ Override public Object visitInstAsgnNode ( InstAsgnNode visited ) { addVariable ( visited . getName ( ) , visited ) ; return super . visitInstAsgnNode ( visited ) ; } @ Override public Object visitDVarNode ( DVarNode visited ) { considerVariable ( visited . getName ( ) , visited ) ; return super . visitDVarNode ( visited ) ; } private void considerVariable ( String name , Node node ) { name = effectiveName ( name ) ; if ( isBadName ( name ) ) { createProblem ( node . getPosition ( ) , "" + name ) ; } } @ Override public void exitClassNode ( ClassNode visited ) { popScope ( ) ; super . exitClassNode ( visited ) ; } private String effectiveName ( String name ) { if ( name . startsWith ( "" ) ) return name . substring ( ) ; if ( name . startsWith ( "" ) ) return name . substring ( ) ; return name ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class LocalsMaskingMethodsVisitor extends RubyLintVisitor { private Map < Node , Collection < LocalAsgnNode > > locals ; private HashSet < String > methods ; private List < Node > scopes ; public LocalsMaskingMethodsVisitor ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; init ( ) ; } private void init ( ) { locals = new HashMap < Node , Collection < LocalAsgnNode > > ( ) ; methods = new HashSet < String > ( ) ; scopes = new ArrayList < Node > ( ) ; } @ Override public Object visitRootNode ( RootNode visited ) { init ( ) ; enterScope ( visited ) ; Object ret = super . visitRootNode ( visited ) ; exitScope ( ) ; return ret ; } private void enterScope ( Node scopingNode ) { scopes . add ( scopingNode ) ; } private void exitScope ( ) { scopes . remove ( scopes . size ( ) - ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_LOCAL_MASKS_METHOD ; } @ Override protected int getProblemID ( ) { return IProblem . LocalMaskingMethod ; } public Object visitClassNode ( ClassNode iVisited ) { methods . clear ( ) ; locals . clear ( ) ; enterScope ( iVisited ) ; Object ret = super . visitClassNode ( iVisited ) ; findMaskingLocals ( ) ; exitScope ( ) ; return ret ; } @ Override public Object visitFCallNode ( FCallNode iVisited ) { String name = iVisited . getName ( ) ; if ( name . equals ( "" ) || name . equals ( "" ) ) { List < String > args = ASTUtil . getArgumentsFromFunctionCall ( iVisited ) ; if ( name . equals ( "" ) ) { methods . add ( args . get ( ) ) ; } else methods . addAll ( convertSymbolsToStrings ( args ) ) ; } return super . visitFCallNode ( iVisited ) ; } private Collection < ? extends String > convertSymbolsToStrings ( List < String > args ) { Collection < String > converted = new ArrayList < String > ( ) ; for ( String arg : args ) { if ( arg . startsWith ( "" ) ) { converted . add ( arg . substring ( ) ) ; } else { converted . add ( arg ) ; } } return converted ; } public Object visitDefnNode ( DefnNode iVisited ) { methods . add ( iVisited . getName ( ) ) ; enterScope ( iVisited ) ; Object ret = super . visitDefnNode ( iVisited ) ; exitScope ( ) ; return ret ; } public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { Collection < LocalAsgnNode > alreadyMarked = locals . get ( currentScope ( ) ) ; if ( alreadyMarked == null ) alreadyMarked = new ArrayList < LocalAsgnNode > ( ) ; for ( LocalAsgnNode localAsgnNode : alreadyMarked ) { if ( localAsgnNode . getName ( ) . equals ( iVisited . getName ( ) ) ) return super . visitLocalAsgnNode ( iVisited ) ; } alreadyMarked . add ( iVisited ) ; locals . put ( currentScope ( ) , alreadyMarked ) ; return super . visitLocalAsgnNode ( iVisited ) ; } private Node currentScope ( ) { return scopes . get ( scopes . size ( ) - ) ; } private void findMaskingLocals ( ) { for ( Collection < LocalAsgnNode > localAsgnNodes : locals . values ( ) ) { for ( LocalAsgnNode local : localAsgnNodes ) { if ( methods . contains ( local . getName ( ) ) ) { createProblem ( local . getPosition ( ) , "" ) ; } } } } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; public class UnusedParameterVisitor extends RubyLintVisitor { private Map < String , Node > declared ; private boolean inArgsNode = false ; public UnusedParameterVisitor ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; declared = new HashMap < String , Node > ( ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_UNUSED_PARAMETER ; } public Object visitDefnNode ( DefnNode iVisited ) { List < Node > args = getArgs ( iVisited . getArgsNode ( ) ) ; for ( Node arg : args ) { declared . put ( ASTUtil . getNameReflectively ( arg ) , arg ) ; } return null ; } @ Override public Object visitArgsNode ( ArgsNode visited ) { inArgsNode = true ; return super . visitArgsNode ( visited ) ; } @ Override public void exitArgsNode ( ArgsNode visited ) { inArgsNode = false ; super . exitArgsNode ( visited ) ; } @ Override public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { if ( inArgsNode ) { declared . put ( iVisited . getName ( ) , iVisited ) ; } return super . visitLocalAsgnNode ( iVisited ) ; } public void exitDefnNode ( DefnNode iVisited ) { for ( Node unused : declared . values ( ) ) { String name = ASTUtil . getNameReflectively ( unused ) ; ISourcePosition original = unused . getPosition ( ) ; ISourcePosition pos = new IDESourcePosition ( original . getFile ( ) , original . getStartLine ( ) , original . getEndLine ( ) , original . getStartOffset ( ) , original . getStartOffset ( ) + name . length ( ) ) ; createProblem ( pos , "" + name ) ; } declared . clear ( ) ; } private void usedParameter ( String name ) { declared . remove ( name ) ; } private List < Node > getArgs ( ArgsNode argsNode ) { List < Node > arguments = new ArrayList < Node > ( ) ; if ( argsNode == null ) return arguments ; ArgsNode args = ( ArgsNode ) argsNode ; ListNode argList = args . getPre ( ) ; if ( argList == null ) return arguments ; for ( Iterator < Node > iter = argList . childNodes ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Node node = iter . next ( ) ; arguments . add ( node ) ; } return arguments ; } public Object visitLocalVarNode ( LocalVarNode iVisited ) { usedParameter ( iVisited . getName ( ) ) ; return super . visitLocalVarNode ( iVisited ) ; } @ Override protected int getProblemID ( ) { return IProblem . ArgumentIsNeverUsed ; } } package com . aptana . rdt . internal . parser . warnings ; import org . jruby . ast . RescueBodyNode ; import org . jruby . ast . RetryNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class RetryOutsideRescueBodyChecker extends RubyLintVisitor { boolean insideRescue = false ; public RetryOutsideRescueBodyChecker ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override public Object visitRetryNode ( RetryNode iVisited ) { if ( ! insideRescue ) { createProblem ( iVisited . getPosition ( ) , "" ) ; } return super . visitRetryNode ( iVisited ) ; } @ Override public Object visitRescueBodyNode ( RescueBodyNode iVisited ) { insideRescue = true ; return super . visitRescueBodyNode ( iVisited ) ; } @ Override public void exitRescueBodyNode ( RescueBodyNode iVisited ) { insideRescue = false ; super . exitRescueBodyNode ( iVisited ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_RETRY_OUTSIDE_RESCUE ; } @ Override protected int getProblemID ( ) { return IProblem . RetryOutsideRescueBody ; } } package com . aptana . rdt . internal . parser . warnings ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class ComparableInclusionVisitor extends RubyLintVisitor { private static final String INCLUDE = "" ; private static final String COMPARABLE_METHOD = "" ; private static final String COMPARABLE = "" ; private boolean includedComparable = false ; private boolean definedComparableMethod ; private ISourcePosition pos ; public ComparableInclusionVisitor ( String code ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , code ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_COMPARABLE_MISSING_METHOD ; } @ Override public Object visitFCallNode ( FCallNode iVisited ) { if ( includedComparable ) return null ; String callName = iVisited . getName ( ) ; if ( ! callName . equals ( INCLUDE ) ) return null ; Node args = iVisited . getArgsNode ( ) ; if ( args instanceof ArrayNode ) { ArrayNode array = ( ArrayNode ) args ; for ( Object arg : array . childNodes ( ) ) { if ( ! ( arg instanceof ConstNode ) ) continue ; ConstNode constNode = ( ConstNode ) arg ; if ( ! ( constNode . getName ( ) . equals ( COMPARABLE ) ) ) continue ; pos = constNode . getPosition ( ) ; includedComparable = true ; return null ; } } return null ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { String methodName = iVisited . getName ( ) ; if ( methodName . equals ( COMPARABLE_METHOD ) ) { definedComparableMethod = true ; } return super . visitDefnNode ( iVisited ) ; } @ Override public void exitClassNode ( ClassNode iVisited ) { if ( includedComparable && ! definedComparableMethod ) { createProblem ( pos , "" ) ; } includedComparable = false ; pos = null ; definedComparableMethod = false ; } @ Override protected int getProblemID ( ) { return IProblem . ComparableInclusionMissingCompareMethod ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . Map ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; public class TooManyArgumentsVisitor extends RubyLintVisitor { public static final int DEFAULT_MAX_ARGS = ; private int maxArgLength ; public TooManyArgumentsVisitor ( String contents ) { this ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } public TooManyArgumentsVisitor ( Map < String , String > options , String contents ) { super ( options , contents ) ; maxArgLength = getInt ( AptanaRDTPlugin . COMPILER_PB_MAX_ARGUMENTS , DEFAULT_MAX_ARGS ) ; } private int getInt ( String key , int defaultValue ) { try { return Integer . parseInt ( ( String ) fOptions . get ( key ) ) ; } catch ( NumberFormatException e ) { return defaultValue ; } } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_ARGUMENTS ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { String [ ] args = ASTUtil . getArgs ( iVisited . getArgsNode ( ) , iVisited . getScope ( ) ) ; if ( args != null && args . length > maxArgLength ) { createProblem ( iVisited . getArgsNode ( ) . getPosition ( ) , "" + args . length ) ; } return super . visitDefsNode ( iVisited ) ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { String [ ] args = ASTUtil . getArgs ( iVisited . getArgsNode ( ) , iVisited . getScope ( ) ) ; if ( args != null && args . length > maxArgLength ) { createProblem ( iVisited . getArgsNode ( ) . getPosition ( ) , "" + args . length ) ; } return super . visitDefnNode ( iVisited ) ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ClassVarDeclNode ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . MethodDefNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . SClassNode ; import org . jruby . ast . VCallNode ; import org . jruby . ast . types . INameNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class SimilarVariableNameVisitor extends RubyLintVisitor { private Map < Node , Map < String , Node > > scopesToVars ; private List < Node > scopes ; public SimilarVariableNameVisitor ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; scopes = new ArrayList < Node > ( ) ; scopesToVars = new HashMap < Node , Map < String , Node > > ( ) ; } protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_SIMILAR_VARIABLE_NAMES ; } public Object visitDefnNode ( DefnNode iVisited ) { enterMethod ( iVisited ) ; return super . visitDefnNode ( iVisited ) ; } public Object visitDefsNode ( DefsNode iVisited ) { enterMethod ( iVisited ) ; return super . visitDefsNode ( iVisited ) ; } private void enterMethod ( MethodDefNode node ) { enterScope ( node ) ; } public Object visitClassNode ( ClassNode visited ) { enterScope ( visited ) ; return super . visitClassNode ( visited ) ; } public Object visitArgsNode ( ArgsNode iVisited ) { ListNode list = iVisited . getPre ( ) ; if ( list != null && list . childNodes ( ) != null ) { for ( Object arg : list . childNodes ( ) ) { Node argNode = ( Node ) arg ; addVar ( ( INameNode ) argNode ) ; } } list = iVisited . getOptArgs ( ) ; if ( list != null && list . childNodes ( ) != null ) { for ( Object arg : list . childNodes ( ) ) { Node argNode = ( Node ) arg ; addVar ( ( INameNode ) argNode ) ; } } return super . visitArgsNode ( iVisited ) ; } public void exitDefnNode ( DefnNode iVisited ) { exitMethod ( ) ; super . exitDefnNode ( iVisited ) ; } public Object visitBlockNode ( BlockNode iVisited ) { enterScope ( iVisited ) ; return super . visitBlockNode ( iVisited ) ; } private void enterScope ( Node node ) { scopes . add ( node ) ; scopesToVars . put ( node , new HashMap < String , Node > ( ) ) ; } public void exitBlockNode ( BlockNode iVisited ) { exitScope ( ) ; super . exitBlockNode ( iVisited ) ; } private void exitClass ( ) { exitScope ( true ) ; } private void exitScope ( ) { exitScope ( false ) ; } private void exitScope ( boolean exitingClass ) { Map < String , Node > vars = getAllVarsInScope ( ) ; pop ( ) ; List < String > names = new ArrayList < String > ( vars . keySet ( ) ) ; while ( ! names . isEmpty ( ) ) { String name = names . remove ( ) ; boolean isInstanceVar = isInstanceVar ( name ) ; boolean isClassVar = isClassVar ( name ) ; if ( ! exitingClass && ( isClassVar || isInstanceVar ) ) { continue ; } for ( String string : names ) { String modName = name ; if ( isInstanceVar ) { if ( ! isInstanceVar ( string ) ) continue ; modName = name . substring ( ) ; string = string . substring ( ) ; } else if ( isClassVar ) { if ( ! isClassVar ( string ) ) continue ; modName = name . substring ( ) ; string = string . substring ( ) ; } else { if ( isInstanceVar ( string ) || isClassVar ( string ) ) continue ; } if ( isPlural ( modName , string ) || isPlural ( string , modName ) ) { continue ; } if ( damerauLevenshteinDistance ( modName , string ) <= levenshteinThreshold ( modName ) ) { createProblem ( vars . get ( name ) . getPosition ( ) , "" ) ; } } } } private Map < String , Node > getAllVarsInScope ( ) { Map < String , Node > all = new HashMap < String , Node > ( ) ; for ( Node scopeNode : scopes ) { all . putAll ( scopesToVars . get ( scopeNode ) ) ; } return all ; } private void pop ( ) { Node scopeNode = scopes . remove ( scopes . size ( ) - ) ; scopesToVars . remove ( scopeNode ) ; } private boolean isPlural ( String singular , String plural ) { return ( singular . length ( ) == plural . length ( ) - ) && ( singular . equals ( plural . substring ( , plural . length ( ) - ) ) ) && plural . charAt ( plural . length ( ) - ) == '' ; } private boolean isInstanceVar ( String name ) { return ! isClassVar ( name ) && name . startsWith ( "" ) ; } private boolean isClassVar ( String name ) { return name . startsWith ( "" ) ; } private int levenshteinThreshold ( String name ) { int length = name . length ( ) ; if ( length < ) return ; return ( int ) Math . ceil ( length / ) ; } private int damerauLevenshteinDistance ( String s , String t ) { if ( s == null || t == null ) { throw new IllegalArgumentException ( "" ) ; } int m = s . length ( ) ; int n = t . length ( ) ; if ( n == ) { return m ; } else if ( m == ) { return n ; } int [ ] [ ] d = new int [ m + ] [ n + ] ; for ( int i = ; i <= m ; i ++ ) d [ i ] [ ] = i ; for ( int j = ; j <= n ; j ++ ) d [ ] [ j ] = j ; for ( int i = ; i <= m ; i ++ ) { for ( int j = ; j <= n ; j ++ ) { int cost ; if ( s . charAt ( i - ) == t . charAt ( j - ) ) { cost = ; } else { cost = ; } d [ i ] [ j ] = minimum ( d [ i - ] [ j ] + , d [ i ] [ j - ] + , d [ i - ] [ j - ] + cost ) ; if ( i > && j > && s . charAt ( i - ) == t . charAt ( j - ) && s . charAt ( i - ) == t . charAt ( j - ) ) { d [ i ] [ j ] = Math . min ( d [ i ] [ j ] , d [ i - ] [ j - ] + cost ) ; } } } return d [ m ] [ n ] ; } private int minimum ( int i , int j , int k ) { return Math . min ( Math . min ( i , j ) , k ) ; } public Object visitVCallNode ( VCallNode iVisited ) { addVar ( iVisited ) ; return super . visitVCallNode ( iVisited ) ; } public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { addVar ( iVisited ) ; return super . visitLocalAsgnNode ( iVisited ) ; } public Object visitLocalVarNode ( LocalVarNode iVisited ) { addVar ( iVisited ) ; return super . visitLocalVarNode ( iVisited ) ; } private void addToClass ( INameNode iVisited ) { int i = ; Node scopeNode = null ; while ( true ) { scopeNode = scopes . get ( scopes . size ( ) - i ) ; if ( scopeNode instanceof ClassNode || scopeNode instanceof SClassNode || scopeNode instanceof RootNode ) { addToScope ( iVisited , scopeNode ) ; break ; } i ++ ; if ( i > scopes . size ( ) ) break ; } } private void addVar ( INameNode iVisited ) { Node scopeNode = scopes . get ( scopes . size ( ) - ) ; addToScope ( iVisited , scopeNode ) ; } private void addToScope ( INameNode iVisited , Node scopeNode ) { Map < String , Node > vars = scopesToVars . get ( scopeNode ) ; if ( vars == null ) { vars = new HashMap < String , Node > ( ) ; } vars . put ( iVisited . getName ( ) , ( Node ) iVisited ) ; } public Object visitRootNode ( RootNode visited ) { enterScope ( visited ) ; return super . visitRootNode ( visited ) ; } public void exitClassNode ( ClassNode iVisited ) { exitClass ( ) ; } public void exitDefsNode ( DefsNode iVisited ) { exitMethod ( ) ; super . exitDefsNode ( iVisited ) ; } private void exitMethod ( ) { exitScope ( ) ; } public Object visitInstAsgnNode ( InstAsgnNode iVisited ) { addToClass ( iVisited ) ; return super . visitInstAsgnNode ( iVisited ) ; } public Object visitInstVarNode ( InstVarNode iVisited ) { addToClass ( iVisited ) ; return super . visitInstVarNode ( iVisited ) ; } public Object visitClassVarAsgnNode ( ClassVarAsgnNode iVisited ) { addToClass ( iVisited ) ; return super . visitClassVarAsgnNode ( iVisited ) ; } public Object visitClassVarNode ( ClassVarNode iVisited ) { addToClass ( iVisited ) ; return super . visitClassVarNode ( iVisited ) ; } public Object visitClassVarDeclNode ( ClassVarDeclNode iVisited ) { addToClass ( iVisited ) ; return super . visitClassVarDeclNode ( iVisited ) ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . jruby . ast . CallNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . SelfNode ; import org . jruby . ast . VCallNode ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class FeatureEnvy extends RubyLintVisitor { private static final int DEFAULT_MIN_REFERENCES_FOR_REPORT = ; private static final String SELF = "" ; private HashMap < String , List < ISourcePosition > > references = new HashMap < String , List < ISourcePosition > > ( ) ; private boolean recordReferences = false ; private int minReferences ; public FeatureEnvy ( String src ) { this ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , src ) ; } public FeatureEnvy ( Map < String , String > options , String src ) { super ( options , src ) ; minReferences = getInt ( AptanaRDTPlugin . COMPILER_PB_MIN_REFERENCES_FOR_ENVY , DEFAULT_MIN_REFERENCES_FOR_REPORT ) ; } private int getInt ( String key , int defaultValue ) { try { return Integer . parseInt ( ( String ) fOptions . get ( key ) ) ; } catch ( NumberFormatException e ) { return defaultValue ; } } @ Override protected int getProblemID ( ) { return IProblem . FeatureEnvy ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_FEATURE_ENVY ; } @ Override public Object visitDefnNode ( DefnNode visited ) { enterMethod ( ) ; return super . visitDefnNode ( visited ) ; } private void enterMethod ( ) { recordReferences = true ; } @ Override public Object visitDefsNode ( DefsNode visited ) { enterMethod ( ) ; return super . visitDefsNode ( visited ) ; } @ Override public void exitDefnNode ( DefnNode visited ) { exitMethod ( ) ; super . exitDefnNode ( visited ) ; } @ Override public void exitDefsNode ( DefsNode visited ) { exitMethod ( ) ; super . exitDefsNode ( visited ) ; } private void exitMethod ( ) { List < ISourcePosition > enviousReferences = getEnviousReferences ( ) ; for ( ISourcePosition pos : enviousReferences ) { createProblem ( pos , "" ) ; } recordReferences = false ; references . clear ( ) ; } private List < ISourcePosition > getEnviousReferences ( ) { if ( references . isEmpty ( ) ) return Collections . emptyList ( ) ; if ( references . size ( ) == && references . containsKey ( SELF ) ) return Collections . emptyList ( ) ; Collection < List < ISourcePosition > > listOfPositions = references . values ( ) ; int max = Math . max ( , minReferences ) ; for ( List < ISourcePosition > list : listOfPositions ) { if ( list . size ( ) > max ) max = list . size ( ) ; } List < ISourcePosition > envious = new ArrayList < ISourcePosition > ( ) ; for ( Map . Entry < String , List < ISourcePosition > > entry : references . entrySet ( ) ) { if ( entry . getValue ( ) . size ( ) == max ) { if ( entry . getKey ( ) . equals ( SELF ) ) { envious . clear ( ) ; break ; } else { envious . add ( entry . getValue ( ) . get ( ) ) ; } } } return envious ; } @ Override public Object visitCallNode ( CallNode visited ) { if ( ! visited . getName ( ) . equals ( "" ) ) { Node receiver = visited . getReceiverNode ( ) ; if ( receiver instanceof SelfNode ) { recordReference ( SELF , receiver . getPosition ( ) ) ; } else if ( receiver instanceof DVarNode ) { return super . visitCallNode ( visited ) ; } else { String expr = ASTUtil . getNameReflectively ( receiver ) ; if ( expr == null ) expr = ASTUtil . stringRepresentation ( receiver ) ; recordReference ( expr , receiver . getPosition ( ) ) ; } } return super . visitCallNode ( visited ) ; } @ Override public Object visitFCallNode ( FCallNode visited ) { recordReference ( SELF , visited . getPosition ( ) ) ; return super . visitFCallNode ( visited ) ; } @ Override public Object visitVCallNode ( VCallNode visited ) { recordReference ( SELF , visited . getPosition ( ) ) ; return super . visitVCallNode ( visited ) ; } private void recordReference ( String name , ISourcePosition pos ) { if ( ! recordReferences ) return ; List < ISourcePosition > value = references . get ( name ) ; if ( value == null ) value = new ArrayList < ISourcePosition > ( ) ; value . add ( pos ) ; references . put ( name , value ) ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . HashMap ; import java . util . Map ; import org . rubypeople . rdt . core . RubyCore ; import com . aptana . rdt . AptanaRDTPlugin ; public class LintOptions { public static final long UnusedPrivateMember = ; public static final long UnusedArgument = ; public static final long UnnecessaryElse = ; public static final long SimilarVariableNames = ; public static final long MisspelledConstructor = ; public static final long PossibleAccidentalBooleanAssignment = ; public static final long LocalVariableMasksMethod = ; public static final long MaxLocals = ; public static final long MaxReturns = ; public static final long MaxLines = ; public static final long MaxBranches = ; public static final long MaxArguments = ; public static final long UnreachableCode = ; public static final long ComparableMissingMethod = ; public static final long EnumerableMissingMethod = ; public static final long SubclassDoesntCallSuper = ; public static final long AssignmentPrecedence = ; public static final long MethodMissingWithoutRespondTo = ; public static final long ConstantNamingConvention = ; public static final long DynamicVariableAliasesLocal = ; public static final long LocalVariablePossibleAttributeAccess = ; public static final long LocalMethodNamingConvention = ; public static final long UnusedLocalVariable = ; public static final long DeprecatedRequireGem = ; public static final long RetryOutsideRescueBody = ; public static final long DuplicateHashKey = ; public static final long ControlCouple = ; public static final long FeatureEnvy = ; public static final long UncommunicativeName = ; public static final String ERROR = RubyCore . ERROR ; public static final String WARNING = RubyCore . WARNING ; public static final String IGNORE = RubyCore . IGNORE ; public static final String ENABLED = RubyCore . ENABLED ; public static final String DISABLED = RubyCore . DISABLED ; public long errorThreshold = ; public long warningThreshold = UnusedPrivateMember | MisspelledConstructor | PossibleAccidentalBooleanAssignment | LocalVariableMasksMethod | UnreachableCode | AssignmentPrecedence | SubclassDoesntCallSuper | MethodMissingWithoutRespondTo | DynamicVariableAliasesLocal | LocalVariablePossibleAttributeAccess | UnusedLocalVariable | DeprecatedRequireGem | RetryOutsideRescueBody | DuplicateHashKey | FeatureEnvy | UncommunicativeName ; public int maxLocals = ; public int maxLines = ; public int maxBranches = ; public int maxReturns = ; public int maxArguments = ; public int minReferencesForEnvy = ; public Map < String , String > getMap ( ) { Map < String , String > optionsMap = new HashMap < String , String > ( ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_UNCOMMUNICATIVE_NAME , getSeverityString ( UncommunicativeName ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_CONTROL_COUPLE , getSeverityString ( ControlCouple ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_FEATURE_ENVY , getSeverityString ( FeatureEnvy ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_DUPLICATE_HASH_KEY , getSeverityString ( DuplicateHashKey ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_DEPRECATED_REQUIRE_GEM , getSeverityString ( DeprecatedRequireGem ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_RETRY_OUTSIDE_RESCUE , getSeverityString ( RetryOutsideRescueBody ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_UNUSED_PRIVATE_MEMBER , getSeverityString ( UnusedPrivateMember ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_UNUSED_LOCAL_VARIABLE , getSeverityString ( UnusedLocalVariable ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_SUBCLASS_DOESNT_CALL_SUPER , getSeverityString ( SubclassDoesntCallSuper ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_ASSIGNMENT_PRECEDENCE , getSeverityString ( AssignmentPrecedence ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_UNUSED_PARAMETER , getSeverityString ( UnusedArgument ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_UNNECESSARY_ELSE , getSeverityString ( UnnecessaryElse ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_MISSPELLED_CONSTRUCTOR , getSeverityString ( MisspelledConstructor ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT , getSeverityString ( PossibleAccidentalBooleanAssignment ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_LOCAL_MASKS_METHOD , getSeverityString ( LocalVariableMasksMethod ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_ARGUMENTS , getSeverityString ( MaxArguments ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_BRANCHES , getSeverityString ( MaxBranches ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_LINES , getSeverityString ( MaxLines ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_LOCALS , getSeverityString ( MaxLocals ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_RETURNS , getSeverityString ( MaxReturns ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_SIMILAR_VARIABLE_NAMES , getSeverityString ( SimilarVariableNames ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_UNREACHABLE_CODE , getSeverityString ( UnreachableCode ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_COMPARABLE_MISSING_METHOD , getSeverityString ( ComparableMissingMethod ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_ENUMERABLE_MISSING_METHOD , getSeverityString ( EnumerableMissingMethod ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_CONSTANT_NAMING_CONVENTION , getSeverityString ( ConstantNamingConvention ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_METHOD_MISSING_NO_RESPOND_TO , getSeverityString ( MethodMissingWithoutRespondTo ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_DYNAMIC_VARIABLE_ALIASES_LOCAL , getSeverityString ( DynamicVariableAliasesLocal ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_LOCAL_VARIABLE_POSSIBLE_ATTRIBUTE_ACCESS , getSeverityString ( LocalVariablePossibleAttributeAccess ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_LOCAL_METHOD_NAMING_CONVENTION , getSeverityString ( LocalMethodNamingConvention ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_MAX_ARGUMENTS , String . valueOf ( maxArguments ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_MAX_LINES , String . valueOf ( maxLines ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_MAX_LOCALS , String . valueOf ( maxLocals ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_MAX_RETURNS , String . valueOf ( maxReturns ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_MAX_BRANCHES , String . valueOf ( maxBranches ) ) ; optionsMap . put ( AptanaRDTPlugin . COMPILER_PB_MIN_REFERENCES_FOR_ENVY , String . valueOf ( minReferencesForEnvy ) ) ; return optionsMap ; } public String getSeverityString ( long irritant ) { if ( ( this . warningThreshold & irritant ) != ) return WARNING ; if ( ( this . errorThreshold & irritant ) != ) return ERROR ; return IGNORE ; } public void set ( Map < String , Object > optionsMap ) { Object optionValue ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_UNCOMMUNICATIVE_NAME ) ) != null ) updateSeverity ( UncommunicativeName , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_CONTROL_COUPLE ) ) != null ) updateSeverity ( ControlCouple , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_FEATURE_ENVY ) ) != null ) updateSeverity ( FeatureEnvy , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_DUPLICATE_HASH_KEY ) ) != null ) updateSeverity ( DuplicateHashKey , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_DEPRECATED_REQUIRE_GEM ) ) != null ) updateSeverity ( DeprecatedRequireGem , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_RETRY_OUTSIDE_RESCUE ) ) != null ) updateSeverity ( RetryOutsideRescueBody , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_UNUSED_PRIVATE_MEMBER ) ) != null ) updateSeverity ( UnusedPrivateMember , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_UNUSED_LOCAL_VARIABLE ) ) != null ) updateSeverity ( UnusedLocalVariable , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_UNUSED_PARAMETER ) ) != null ) updateSeverity ( UnusedArgument , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_UNNECESSARY_ELSE ) ) != null ) updateSeverity ( UnnecessaryElse , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_MISSPELLED_CONSTRUCTOR ) ) != null ) updateSeverity ( MisspelledConstructor , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT ) ) != null ) updateSeverity ( PossibleAccidentalBooleanAssignment , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_LOCAL_MASKS_METHOD ) ) != null ) updateSeverity ( LocalVariableMasksMethod , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_ARGUMENTS ) ) != null ) updateSeverity ( MaxArguments , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_BRANCHES ) ) != null ) updateSeverity ( MaxBranches , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_LINES ) ) != null ) updateSeverity ( MaxLines , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_LOCALS ) ) != null ) updateSeverity ( MaxLocals , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_RETURNS ) ) != null ) updateSeverity ( MaxReturns , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_SIMILAR_VARIABLE_NAMES ) ) != null ) updateSeverity ( SimilarVariableNames , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_UNREACHABLE_CODE ) ) != null ) updateSeverity ( UnreachableCode , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_COMPARABLE_MISSING_METHOD ) ) != null ) updateSeverity ( ComparableMissingMethod , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_ENUMERABLE_MISSING_METHOD ) ) != null ) updateSeverity ( EnumerableMissingMethod , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_SUBCLASS_DOESNT_CALL_SUPER ) ) != null ) updateSeverity ( SubclassDoesntCallSuper , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_ASSIGNMENT_PRECEDENCE ) ) != null ) updateSeverity ( AssignmentPrecedence , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_CONSTANT_NAMING_CONVENTION ) ) != null ) updateSeverity ( ConstantNamingConvention , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_METHOD_MISSING_NO_RESPOND_TO ) ) != null ) updateSeverity ( MethodMissingWithoutRespondTo , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_DYNAMIC_VARIABLE_ALIASES_LOCAL ) ) != null ) updateSeverity ( DynamicVariableAliasesLocal , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_LOCAL_VARIABLE_POSSIBLE_ATTRIBUTE_ACCESS ) ) != null ) updateSeverity ( LocalVariablePossibleAttributeAccess , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_LOCAL_METHOD_NAMING_CONVENTION ) ) != null ) updateSeverity ( LocalMethodNamingConvention , optionValue ) ; if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_MAX_LOCALS ) ) != null ) { this . maxLocals = parseInt ( optionValue , maxLocals ) ; } if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_MAX_LINES ) ) != null ) { this . maxLines = parseInt ( optionValue , maxLines ) ; } if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_MAX_BRANCHES ) ) != null ) { this . maxBranches = parseInt ( optionValue , maxBranches ) ; } if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_MAX_ARGUMENTS ) ) != null ) { this . maxArguments = parseInt ( optionValue , maxArguments ) ; } if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_MAX_RETURNS ) ) != null ) { this . maxReturns = parseInt ( optionValue , maxReturns ) ; } if ( ( optionValue = optionsMap . get ( AptanaRDTPlugin . COMPILER_PB_MIN_REFERENCES_FOR_ENVY ) ) != null ) { this . minReferencesForEnvy = parseInt ( optionValue , minReferencesForEnvy ) ; } } private int parseInt ( Object optionValue , int defaultValue ) { if ( ! ( optionValue instanceof String ) ) return defaultValue ; String stringValue = ( String ) optionValue ; try { int val = Integer . parseInt ( stringValue ) ; if ( val >= ) return val ; } catch ( NumberFormatException e ) { } return defaultValue ; } void updateSeverity ( long irritant , Object severityString ) { if ( ERROR . equals ( severityString ) ) { this . errorThreshold |= irritant ; this . warningThreshold &= ~ irritant ; } else if ( WARNING . equals ( severityString ) ) { this . errorThreshold &= ~ irritant ; this . warningThreshold |= irritant ; } else if ( IGNORE . equals ( severityString ) ) { this . errorThreshold &= ~ irritant ; this . warningThreshold &= ~ irritant ; } } } package com . aptana . rdt . internal . parser . warnings ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . jruby . ast . CallNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . Node ; import org . jruby . ast . SelfNode ; import org . jruby . ast . SymbolNode ; import org . jruby . ast . VCallNode ; import org . jruby . runtime . Visibility ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; public class UnusedPrivateMethodVisitor extends RubyLintVisitor { private Map < String , Node > privateMethods = new HashMap < String , Node > ( ) ; private Set < String > usedMethods = new HashSet < String > ( ) ; private Visibility visibility ; public UnusedPrivateMethodVisitor ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; visibility = Visibility . PUBLIC ; } public Object visitFCallNode ( FCallNode iVisited ) { usedMethods . add ( iVisited . getName ( ) ) ; List < Node > args = ASTUtil . getArgumentNodesFromFunctionCall ( iVisited ) ; for ( Node node : args ) { if ( node instanceof SymbolNode ) { usedMethods . add ( ( ( SymbolNode ) node ) . getName ( ) ) ; } } return null ; } public Object visitCallNode ( CallNode iVisited ) { Node receiver = iVisited . getReceiverNode ( ) ; if ( receiver instanceof SelfNode ) usedMethods . add ( iVisited . getName ( ) ) ; return null ; } public Object visitVCallNode ( VCallNode iVisited ) { usedMethods . add ( iVisited . getName ( ) ) ; if ( iVisited . getName ( ) . equals ( "" ) ) { visibility = Visibility . PRIVATE ; } else if ( iVisited . getName ( ) . equals ( "" ) ) { visibility = Visibility . PROTECTED ; } else if ( iVisited . getName ( ) . equals ( "" ) ) { visibility = Visibility . PUBLIC ; } return null ; } public Object visitClassNode ( ClassNode iVisited ) { privateMethods . clear ( ) ; usedMethods . clear ( ) ; visibility = Visibility . PUBLIC ; return null ; } public void exitClassNode ( ClassNode iVisited ) { for ( String name : usedMethods ) { if ( privateMethods . containsKey ( name ) ) { privateMethods . remove ( name ) ; } } for ( Node method : privateMethods . values ( ) ) { createProblem ( method . getPosition ( ) , "" + ASTUtil . getNameReflectively ( method ) ) ; } } public Object visitDefnNode ( DefnNode iVisited ) { if ( visibility . isPrivate ( ) ) { privateMethods . put ( iVisited . getName ( ) , iVisited ) ; } return null ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_UNUSED_PRIVATE_MEMBER ; } @ Override protected int getProblemID ( ) { return IProblem . UnusedPrivateMethod ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . List ; import org . jruby . ast . DefnNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . NilImplicitNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class ControlCouple extends RubyLintVisitor { private Node condition ; private List < String > args ; private boolean problem ; public ControlCouple ( String src ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , src ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_CONTROL_COUPLE ; } @ Override protected int getProblemID ( ) { return IProblem . ControlCouple ; } @ Override public Object visitIfNode ( IfNode visited ) { Node elseBody = visited . getElseBody ( ) ; if ( elseBody != null && ! elseBody . equals ( NilImplicitNode . NIL ) ) condition = visited . getCondition ( ) ; return super . visitIfNode ( visited ) ; } @ Override public Object visitDefnNode ( DefnNode visited ) { args = ASTUtil . getArguments ( visited . getArgsNode ( ) . getPre ( ) ) ; return super . visitDefnNode ( visited ) ; } @ Override public void exitDefnNode ( DefnNode visited ) { args = null ; if ( problem ) { createProblem ( visited . getPosition ( ) , "" ) ; } problem = false ; super . exitDefnNode ( visited ) ; } @ Override public Object visitLocalVarNode ( LocalVarNode visited ) { if ( args != null && visited . equals ( condition ) ) { String name = visited . getName ( ) ; if ( args . contains ( name ) ) { problem = true ; } } return super . visitLocalVarNode ( visited ) ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . compiler . BuildContext ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . compiler . CompilationParticipant ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . parser . Warning ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class FlayClone extends CompilationParticipant { private static final int DEFAULT_THRESHOLD = ; private int massThreshold = DEFAULT_THRESHOLD ; private HashMap < Integer , Set < Node > > hashes ; private boolean doFuzzy ; private int total = ; private HashMap < Integer , Boolean > identical ; private HashMap < Integer , Integer > masses ; @ Override public void buildStarting ( BuildContext [ ] files , boolean isBatch , IProgressMonitor monitor ) { if ( ! isBatch ) return ; if ( files == null || files . length == ) return ; hashes = new HashMap < Integer , Set < Node > > ( ) ; identical = new HashMap < Integer , Boolean > ( ) ; masses = new HashMap < Integer , Integer > ( ) ; massThreshold = getMassThreshold ( ) ; for ( BuildContext buildContext : files ) { if ( buildContext == null || buildContext . getAST ( ) == null ) continue ; buildContext . getAST ( ) . accept ( new Visitor ( ) ) ; } if ( doFuzzy ) { processFuzzySimilarities ( ) ; } analyze ( files ) ; } private int getMassThreshold ( ) { return Platform . getPreferencesService ( ) . getInt ( AptanaRDTPlugin . PLUGIN_ID , AptanaRDTPlugin . DUPLICATE_CODE_MASS_THRESHOLD , DEFAULT_THRESHOLD , null ) ; } private void analyze ( BuildContext [ ] files ) { prune ( ) ; for ( Map . Entry < Integer , Set < Node > > entry : hashes . entrySet ( ) ) { Integer hash = entry . getKey ( ) ; Collection < Node > nodes = entry . getValue ( ) ; Node first = nodes . iterator ( ) . next ( ) ; boolean isIdentical = true ; for ( Node node : nodes ) { if ( ! equals ( node , first ) ) { isIdentical = false ; break ; } } identical . put ( hash , isIdentical ) ; int mass = mass ( first ) * nodes . size ( ) ; if ( isIdentical ) mass *= nodes . size ( ) ; masses . put ( hash , mass ) ; total += masses . get ( hash ) ; } Map < BuildContext , List < CategorizedProblem > > contextsToProblems = new HashMap < BuildContext , List < CategorizedProblem > > ( ) ; for ( Map . Entry < Integer , Integer > entry : masses . entrySet ( ) ) { if ( entry . getValue ( ) <= massThreshold ) continue ; Set < Node > nodes = hashes . get ( entry . getKey ( ) ) ; for ( Node node : nodes ) { CategorizedProblem problem = new Warning ( node . getPosition ( ) , "" + otherNodesPositions ( node , nodes ) , IProblem . DuplicateCodeStructure ) ; BuildContext context = findContext ( files , node ) ; if ( context == null ) continue ; List < CategorizedProblem > problems = contextsToProblems . get ( context ) ; if ( problems == null ) problems = new ArrayList < CategorizedProblem > ( ) ; problems . add ( problem ) ; contextsToProblems . put ( context , problems ) ; } } for ( Map . Entry < BuildContext , List < CategorizedProblem > > entry : contextsToProblems . entrySet ( ) ) { entry . getKey ( ) . recordNewProblems ( entry . getValue ( ) . toArray ( new CategorizedProblem [ ] ) ) ; } } private String otherNodesPositions ( Node node , Collection < Node > nodes ) { StringBuilder builder = new StringBuilder ( ) ; for ( Node node2 : nodes ) { if ( node2 . getPosition ( ) . equals ( node . getPosition ( ) ) ) continue ; builder . append ( node2 . getPosition ( ) . toString ( ) ) . append ( "" ) ; } if ( builder . length ( ) > ) { builder . delete ( builder . length ( ) - , builder . length ( ) ) ; } else { System . out . println ( "" ) ; } return builder . toString ( ) ; } private BuildContext findContext ( BuildContext [ ] files , Node node ) { String fileName = node . getPosition ( ) . getFile ( ) ; for ( BuildContext buildContext : files ) { IPath path = buildContext . getFile ( ) . getFullPath ( ) ; if ( path . toPortableString ( ) . equals ( fileName ) ) return buildContext ; } return null ; } private boolean equals ( Node node , Node first ) { return generateSexp ( node ) . equals ( generateSexp ( first ) ) ; } private void prune ( ) { List < Integer > toRemove = new ArrayList < Integer > ( ) ; for ( Map . Entry < Integer , Set < Node > > entry : hashes . entrySet ( ) ) { if ( entry . getValue ( ) . size ( ) == ) toRemove . add ( entry . getKey ( ) ) ; } for ( Integer integer : toRemove ) { hashes . remove ( integer ) ; } toRemove . clear ( ) ; Map < Integer , Set < Node > > hashesCopy = new HashMap < Integer , Set < Node > > ( hashes ) ; for ( Map . Entry < Integer , Set < Node > > entry : hashesCopy . entrySet ( ) ) { if ( toRemove . contains ( entry . getKey ( ) ) ) continue ; for ( Node node : entry . getValue ( ) ) { for ( Integer h : allSubHashes ( node ) ) { toRemove . add ( h ) ; hashes . remove ( h ) ; } } } } private Collection < Integer > allSubHashes ( final Node node ) { final Set < Integer > subHashes = new HashSet < Integer > ( ) ; InOrderVisitor visitor = new InOrderVisitor ( ) { @ Override protected Object handleNode ( Node visited ) { if ( ! visited . equals ( node ) ) subHashes . add ( fuzzyHash ( visited ) ) ; return super . handleNode ( visited ) ; } } ; node . accept ( visitor ) ; return subHashes ; } private void processFuzzySimilarities ( ) { } private int mass ( Node node ) { final int [ ] size = new int [ ] { } ; node . accept ( new InOrderVisitor ( ) { @ Override protected Object handleNode ( Node visited ) { if ( visited != null ) size [ ] += ; return super . handleNode ( visited ) ; } } ) ; return size [ ] ; } private int fuzzyHash ( Node node ) { return generateSexp ( node ) . hashCode ( ) ; } private String generateSexp ( Node node ) { final StringBuilder builder = new StringBuilder ( ) ; node . accept ( new InOrderVisitor ( ) { @ Override public Object acceptNode ( Node node ) { builder . append ( "" ) ; if ( node != null ) { builder . append ( node . getClass ( ) . getSimpleName ( ) ) ; } Object ret = super . acceptNode ( node ) ; builder . append ( "" ) ; return ret ; } } ) ; return builder . toString ( ) ; } @ Override public boolean isActive ( IRubyProject project ) { return Platform . getPreferencesService ( ) . getBoolean ( AptanaRDTPlugin . PLUGIN_ID , AptanaRDTPlugin . DUPLICATE_CODE_CHECK_ENABLED , true , null ) ; } private class Visitor extends InOrderVisitor { @ Override protected Object handleNode ( Node visited ) { if ( mass ( visited ) >= massThreshold ) { Integer hash = fuzzyHash ( visited ) ; Set < Node > nodes = hashes . get ( hash ) ; if ( nodes == null ) nodes = new HashSet < Node > ( ) ; for ( Node node : nodes ) { if ( node . getPosition ( ) . equals ( visited . getPosition ( ) ) ) { return super . handleNode ( visited ) ; } } nodes . add ( visited ) ; hashes . put ( hash , nodes ) ; } return super . handleNode ( visited ) ; } } } package com . aptana . rdt . internal . parser . warnings ; import java . util . Map ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . ReturnNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class TooManyReturnsVisitor extends RubyLintVisitor { public static final int DEFAULT_MAX_RETURNS = ; private int maxReturns ; private int returnCount ; public TooManyReturnsVisitor ( String contents ) { this ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } public TooManyReturnsVisitor ( Map < String , String > options , String contents ) { super ( options , contents ) ; maxReturns = getInt ( AptanaRDTPlugin . COMPILER_PB_MAX_RETURNS , DEFAULT_MAX_RETURNS ) ; returnCount = ; } private int getInt ( String key , int defaultValue ) { try { return Integer . parseInt ( ( String ) fOptions . get ( key ) ) ; } catch ( NumberFormatException e ) { return defaultValue ; } } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_RETURNS ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { returnCount = ; return super . visitDefsNode ( iVisited ) ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { returnCount = ; return super . visitDefnNode ( iVisited ) ; } public void exitDefnNode ( DefnNode iVisited ) { if ( returnCount > maxReturns ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" + returnCount ) ; } returnCount = ; } @ Override public void exitDefsNode ( DefsNode iVisited ) { if ( returnCount > maxReturns ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" + returnCount ) ; } returnCount = ; super . exitDefsNode ( iVisited ) ; } @ Override public Object visitReturnNode ( ReturnNode iVisited ) { returnCount ++ ; return super . visitReturnNode ( iVisited ) ; } } package com . aptana . rdt . internal . parser . warnings ; import org . jruby . ast . DefnNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class MisspelledConstructorVisitor extends RubyLintVisitor { public static final int PROBLEM_ID = ; public MisspelledConstructorVisitor ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } public Object visitDefnNode ( DefnNode iVisited ) { String methodName = iVisited . getName ( ) ; if ( methodName . equals ( "" ) || methodName . equals ( "" ) || methodName . equals ( "" ) ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" ) ; } return null ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_MISSPELLED_CONSTRUCTOR ; } @ Override protected int getProblemID ( ) { return PROBLEM_ID ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . HashMap ; import java . util . Map ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class MethodMissingWithoutRespondTo extends RubyLintVisitor { private static final String RESPOND_TO = "" ; private static final String METHOD_MISSING = "" ; private Map < String , DefnNode > methods = new HashMap < String , DefnNode > ( ) ; public MethodMissingWithoutRespondTo ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_METHOD_MISSING_NO_RESPOND_TO ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { methods . put ( iVisited . getName ( ) , iVisited ) ; return super . visitDefnNode ( iVisited ) ; } @ Override public void exitClassNode ( ClassNode iVisited ) { if ( methods . containsKey ( METHOD_MISSING ) && ! methods . containsKey ( RESPOND_TO ) ) { createProblem ( methods . get ( METHOD_MISSING ) . getNameNode ( ) . getPosition ( ) , "" ) ; } methods . clear ( ) ; super . exitClassNode ( iVisited ) ; } @ Override protected int getProblemID ( ) { return IProblem . MethodMissingWithoutRespondTo ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class UnusedLocalVariable extends RubyLintVisitor { private List < LocalAsgnNode > locals ; private Set < String > refs ; private boolean inArgsNode = false ; public UnusedLocalVariable ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; locals = new ArrayList < LocalAsgnNode > ( ) ; refs = new HashSet < String > ( ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_UNUSED_LOCAL_VARIABLE ; } @ Override protected int getProblemID ( ) { return IProblem . UnusedPrivateMethod ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { clear ( ) ; return super . visitDefnNode ( iVisited ) ; } @ Override public Object visitArgsNode ( ArgsNode visited ) { inArgsNode = true ; return super . visitArgsNode ( visited ) ; } @ Override public void exitArgsNode ( ArgsNode visited ) { inArgsNode = false ; super . exitArgsNode ( visited ) ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { clear ( ) ; return super . visitDefsNode ( iVisited ) ; } @ Override public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { if ( ! inArgsNode ) { locals . add ( iVisited ) ; } return super . visitLocalAsgnNode ( iVisited ) ; } @ Override public Object visitLocalVarNode ( LocalVarNode iVisited ) { refs . add ( iVisited . getName ( ) ) ; return super . visitLocalVarNode ( iVisited ) ; } @ Override public void exitDefnNode ( DefnNode iVisited ) { checkLocals ( ) ; clear ( ) ; super . exitDefnNode ( iVisited ) ; } @ Override public void exitDefsNode ( DefsNode iVisited ) { checkLocals ( ) ; clear ( ) ; super . exitDefsNode ( iVisited ) ; } private void clear ( ) { locals . clear ( ) ; refs . clear ( ) ; } private void checkLocals ( ) { for ( LocalAsgnNode local : locals ) { if ( ! refs . contains ( local . getName ( ) ) ) { createProblem ( local . getPosition ( ) , "" + local . getName ( ) ) ; } } } } package com . aptana . rdt . internal . parser . warnings ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class TooManyLocalsVisitor extends RubyLintVisitor { public static final int DEFAULT_MAX_LOCALS = ; private int maxLocals ; private Set < String > locals ; public TooManyLocalsVisitor ( String contents ) { this ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } public TooManyLocalsVisitor ( Map < String , String > options , String contents ) { super ( options , contents ) ; maxLocals = getInt ( AptanaRDTPlugin . COMPILER_PB_MAX_LOCALS , DEFAULT_MAX_LOCALS ) ; } private int getInt ( String key , int defaultValue ) { try { return Integer . parseInt ( ( String ) fOptions . get ( key ) ) ; } catch ( NumberFormatException e ) { return defaultValue ; } } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_CODE_COMPLEXITY_LOCALS ; } @ Override public Object visitRootNode ( RootNode iVisited ) { locals = new HashSet < String > ( ) ; Object ins = super . visitRootNode ( iVisited ) ; locals . clear ( ) ; return ins ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { locals = new HashSet < String > ( ) ; return super . visitDefsNode ( iVisited ) ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { locals = new HashSet < String > ( ) ; return super . visitDefnNode ( iVisited ) ; } @ Override public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { locals . add ( iVisited . getName ( ) ) ; return super . visitLocalAsgnNode ( iVisited ) ; } public void exitDefnNode ( DefnNode iVisited ) { if ( locals . size ( ) > maxLocals ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" + locals . size ( ) ) ; } locals . clear ( ) ; } @ Override public void exitDefsNode ( DefsNode iVisited ) { if ( locals . size ( ) > maxLocals ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" + locals . size ( ) ) ; } locals . clear ( ) ; super . exitDefsNode ( iVisited ) ; } } package com . aptana . rdt . internal . parser . warnings ; import org . jruby . ast . AndNode ; import org . jruby . ast . Node ; import org . jruby . ast . OrNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import com . aptana . rdt . AptanaRDTPlugin ; public class AndOrUsedOnRighthandAssignment extends RubyLintVisitor { public AndOrUsedOnRighthandAssignment ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_ASSIGNMENT_PRECEDENCE ; } @ Override public Object visitOrNode ( OrNode iVisited ) { Node leftHand = iVisited . getFirstNode ( ) ; if ( isAssignment ( leftHand ) ) { createProblem ( iVisited . getPosition ( ) , createMessage ( iVisited ) ) ; } return super . visitOrNode ( iVisited ) ; } @ Override public Object visitAndNode ( AndNode iVisited ) { Node leftHand = iVisited . getFirstNode ( ) ; if ( isAssignment ( leftHand ) ) { createProblem ( iVisited . getPosition ( ) , createMessage ( iVisited ) ) ; } return super . visitAndNode ( iVisited ) ; } private String createMessage ( Node iVisited ) { String type ; Node leftHand ; Node rightHand ; if ( iVisited instanceof AndNode ) { type = "" ; leftHand = ( ( AndNode ) iVisited ) . getFirstNode ( ) ; rightHand = ( ( AndNode ) iVisited ) . getSecondNode ( ) ; } else { type = "" ; leftHand = ( ( OrNode ) iVisited ) . getFirstNode ( ) ; rightHand = ( ( OrNode ) iVisited ) . getSecondNode ( ) ; } StringBuffer message = new StringBuffer ( ) ; message . append ( "" ) ; message . append ( type ) ; message . append ( "" ) ; message . append ( getSource ( leftHand ) ) ; message . append ( "" ) ; message . append ( type ) ; message . append ( "" ) ; message . append ( getSource ( rightHand ) ) ; message . append ( "" ) ; return message . toString ( ) ; } private boolean isAssignment ( Node node ) { return ASTUtil . isAssignment ( node ) ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . HashSet ; import java . util . Set ; import org . jruby . ast . ClassVarAsgnNode ; import org . jruby . ast . ConstDeclNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . GlobalAsgnNode ; import org . jruby . ast . IfNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . ListNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . Node ; import org . jruby . ast . WhenNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class AccidentalBooleanAssignmentVisitor extends RubyLintVisitor { private Set < String > locals = new HashSet < String > ( ) ; public AccidentalBooleanAssignmentVisitor ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT ; } @ Override public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { locals . add ( iVisited . getName ( ) ) ; return super . visitLocalAsgnNode ( iVisited ) ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { locals . clear ( ) ; return super . visitDefnNode ( iVisited ) ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { locals . clear ( ) ; return super . visitDefsNode ( iVisited ) ; } public Object visitIfNode ( IfNode iVisited ) { Node condition = iVisited . getCondition ( ) ; checkCondition ( condition ) ; return super . visitIfNode ( iVisited ) ; } private void checkCondition ( Node condition ) { if ( containsAssignment ( condition ) ) { if ( condition instanceof LocalAsgnNode ) { LocalAsgnNode assign = ( LocalAsgnNode ) condition ; if ( ! locals . contains ( assign . getName ( ) ) ) return ; } ISourcePosition original = condition . getPosition ( ) ; IDESourcePosition position = new IDESourcePosition ( original . getFile ( ) , original . getStartLine ( ) , original . getEndLine ( ) , original . getStartOffset ( ) , original . getEndOffset ( ) - ) ; createProblem ( position , "" ) ; } } private boolean containsAssignment ( Node condition ) { return condition instanceof LocalAsgnNode || condition instanceof GlobalAsgnNode || condition instanceof InstAsgnNode || condition instanceof ClassVarAsgnNode || condition instanceof ConstDeclNode ; } @ Override public Object visitWhenNode ( WhenNode visited ) { Node expressions = visited . getExpressionNodes ( ) ; if ( expressions instanceof ListNode ) { ListNode list = ( ListNode ) expressions ; for ( Node expression : list . childNodes ( ) ) { checkCondition ( expression ) ; } } else { checkCondition ( expressions ) ; } return super . visitWhenNode ( visited ) ; } @ Override protected int getProblemID ( ) { return IProblem . PossibleAccidentalBooleanAssignment ; } } package com . aptana . rdt . internal . parser . warnings ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . LocalAsgnNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . IProblem ; public class LocalAndMethodNamingConvention extends RubyLintVisitor { public LocalAndMethodNamingConvention ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_LOCAL_METHOD_NAMING_CONVENTION ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { String name = iVisited . getName ( ) ; if ( ! name . toLowerCase ( ) . equals ( name ) ) { createProblem ( iVisited . getPosition ( ) , "" + name ) ; } return super . visitDefnNode ( iVisited ) ; } @ Override public Object visitLocalAsgnNode ( LocalAsgnNode iVisited ) { String name = iVisited . getName ( ) ; if ( ! name . toLowerCase ( ) . equals ( name ) ) { createProblem ( iVisited . getPosition ( ) , "" + name ) ; } return super . visitLocalAsgnNode ( iVisited ) ; } @ Override public Object visitDefsNode ( DefsNode iVisited ) { String name = iVisited . getName ( ) ; if ( ! name . toLowerCase ( ) . equals ( name ) ) { createProblem ( iVisited . getPosition ( ) , "" + name ) ; } return super . visitDefsNode ( iVisited ) ; } @ Override protected int getProblemID ( ) { return IProblem . LocalAndMethodNamingConvention ; } } package com . aptana . rdt . internal . parser . warnings ; import java . util . ArrayList ; import java . util . List ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . Node ; import org . jruby . ast . SuperNode ; import org . jruby . ast . ZSuperNode ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; public class SubclassCallsSuper extends RubyLintVisitor { private boolean inConstructor ; private boolean calledSuper ; private List < Boolean > subclassStack = new ArrayList < Boolean > ( ) ; public SubclassCallsSuper ( String contents ) { super ( AptanaRDTPlugin . getDefault ( ) . getOptions ( ) , contents ) ; subclassStack . add ( Boolean . FALSE ) ; } @ Override protected String getOptionKey ( ) { return AptanaRDTPlugin . COMPILER_PB_SUBCLASS_DOESNT_CALL_SUPER ; } @ Override public Object visitClassNode ( ClassNode iVisited ) { Node superNode = iVisited . getSuperNode ( ) ; if ( superNode != null ) { subclassStack . add ( Boolean . TRUE ) ; } else { subclassStack . add ( Boolean . FALSE ) ; } return super . visitClassNode ( iVisited ) ; } @ Override public void exitClassNode ( ClassNode iVisited ) { subclassStack . remove ( subclassStack . size ( ) - ) ; super . exitClassNode ( iVisited ) ; } @ Override public Object visitDefnNode ( DefnNode iVisited ) { if ( ! isSubClass ( ) ) return null ; if ( ! iVisited . getName ( ) . equals ( "" ) ) return null ; inConstructor = true ; calledSuper = false ; return super . visitDefnNode ( iVisited ) ; } private boolean isSubClass ( ) { return subclassStack . get ( subclassStack . size ( ) - ) ; } @ Override public Object visitSuperNode ( SuperNode iVisited ) { if ( inConstructor ) calledSuper = true ; return super . visitSuperNode ( iVisited ) ; } @ Override public Object visitZSuperNode ( ZSuperNode iVisited ) { if ( inConstructor ) calledSuper = true ; return super . visitZSuperNode ( iVisited ) ; } @ Override public void exitDefnNode ( DefnNode iVisited ) { if ( ! isSubClass ( ) ) return ; if ( ! iVisited . getName ( ) . equals ( "" ) ) return ; if ( ! calledSuper ) { createProblem ( iVisited . getNameNode ( ) . getPosition ( ) , "" ) ; } inConstructor = false ; super . exitDefnNode ( iVisited ) ; } } package com . aptana . rdt . launching ; public interface IGemRuntime { public static final String GEMLIB_VARIABLE = "" ; } package com . aptana . rdt ; public interface IProblem { public static final int MisspelledConstructor = ; public static final int ConstantNamingConvention = ; public static final int MethodMissingWithoutRespondTo = ; public static final int LocalAndMethodNamingConvention = ; public static final int ComparableInclusionMissingCompareMethod = ; public static final int EnumerableInclusionMissingEachMethod = ; public static final int LocalVariablePossibleAttributeAccess = ; public static final int PossibleAccidentalBooleanAssignment = ; public static final int DeprecatedRequireGem = ; public static final int RetryOutsideRescueBody = ; public static final int DynamicVariableAliasesLocal = ; public static final int DuplicateHashKey = ; public static final int ControlCouple = ; public static final int FeatureEnvy = ; public static final int UncommunicativeName = ; public static final int LocalMaskingMethod = ; public static final int DuplicateCodeStructure = ; } package com . aptana . rdt ; import java . io . File ; import java . io . IOException ; import java . net . URL ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Hashtable ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . eclipse . core . net . proxy . IProxyService ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . core . runtime . preferences . DefaultScope ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IPreferencesService ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . osgi . framework . BundleContext ; import org . osgi . util . tracker . ServiceTracker ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyModelManager . EclipsePreferencesListener ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . GemListener ; import com . aptana . rdt . core . gems . GemRequirement ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . internal . core . gems . GemManager ; import com . aptana . rdt . internal . core . gems . RubyGemsInitializer ; import com . aptana . rdt . launching . IGemRuntime ; public class AptanaRDTPlugin extends Plugin { private static final String BIN = "" ; public static final String PLUGIN_ID = "" ; public Set < String > optionNames = new HashSet < String > ( ) ; public Hashtable < String , String > optionsCache ; public final IEclipsePreferences [ ] preferencesLookup = new IEclipsePreferences [ ] ; private ServiceTracker gemManagersTracker ; private ServiceTracker proxyTracker ; static final int PREF_INSTANCE = ; static final int PREF_DEFAULT = ; public static final String COMPILER_PB_UNUSED_PARAMETER = PLUGIN_ID + "" ; public static final String COMPILER_PB_UNUSED_PRIVATE_MEMBER = PLUGIN_ID + "" ; public static final String COMPILER_PB_UNNECESSARY_ELSE = PLUGIN_ID + "" ; public static final String COMPILER_PB_LOCAL_MASKS_METHOD = PLUGIN_ID + "" ; public static final String COMPILER_PB_MISSPELLED_CONSTRUCTOR = PLUGIN_ID + "" ; public static final String COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT = PLUGIN_ID + "" ; public static final String COMPILER_PB_CODE_COMPLEXITY_BRANCHES = PLUGIN_ID + "" ; public static final String COMPILER_PB_CODE_COMPLEXITY_LINES = PLUGIN_ID + "" ; public static final String COMPILER_PB_CODE_COMPLEXITY_RETURNS = PLUGIN_ID + "" ; public static final String COMPILER_PB_CODE_COMPLEXITY_LOCALS = PLUGIN_ID + "" ; public static final String COMPILER_PB_CODE_COMPLEXITY_ARGUMENTS = PLUGIN_ID + "" ; public static final String COMPILER_PB_MAX_LOCALS = PLUGIN_ID + "" ; public static final String COMPILER_PB_MAX_RETURNS = PLUGIN_ID + "" ; public static final String COMPILER_PB_MAX_BRANCHES = PLUGIN_ID + "" ; public static final String COMPILER_PB_MAX_LINES = PLUGIN_ID + "" ; public static final String COMPILER_PB_MAX_ARGUMENTS = PLUGIN_ID + "" ; public static final String COMPILER_PB_SIMILAR_VARIABLE_NAMES = PLUGIN_ID + "" ; public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID + "" ; public static final String COMPILER_PB_COMPARABLE_MISSING_METHOD = PLUGIN_ID + "" ; public static final String COMPILER_PB_ENUMERABLE_MISSING_METHOD = PLUGIN_ID + "" ; public static final String COMPILER_PB_SUBCLASS_DOESNT_CALL_SUPER = PLUGIN_ID + "" ; public static final String COMPILER_PB_ASSIGNMENT_PRECEDENCE = PLUGIN_ID + "" ; public static final String COMPILER_PB_CONSTANT_NAMING_CONVENTION = PLUGIN_ID + "" ; public static final String COMPILER_PB_METHOD_MISSING_NO_RESPOND_TO = PLUGIN_ID + "" ; public static final String COMPILER_PB_DYNAMIC_VARIABLE_ALIASES_LOCAL = PLUGIN_ID + "" ; public static final String COMPILER_PB_LOCAL_VARIABLE_POSSIBLE_ATTRIBUTE_ACCESS = PLUGIN_ID + "" ; public static final String COMPILER_PB_LOCAL_METHOD_NAMING_CONVENTION = PLUGIN_ID + "" ; public static final String COMPILER_PB_UNUSED_LOCAL_VARIABLE = PLUGIN_ID + "" ; public static final String COMPILER_PB_DEPRECATED_REQUIRE_GEM = PLUGIN_ID + "" ; public static final String COMPILER_PB_RETRY_OUTSIDE_RESCUE = PLUGIN_ID + "" ; public static final String COMPILER_PB_DUPLICATE_HASH_KEY = PLUGIN_ID + "" ; public static final String COMPILER_PB_CONTROL_COUPLE = PLUGIN_ID + "" ; public static final String COMPILER_PB_FEATURE_ENVY = PLUGIN_ID + "" ; public static final String COMPILER_PB_MIN_REFERENCES_FOR_ENVY = PLUGIN_ID + "" ; public static final String COMPILER_PB_UNCOMMUNICATIVE_NAME = PLUGIN_ID + "" ; public static final String EXTENSION_POINT_GEMS = "" ; public static final String DUPLICATE_CODE_CHECK_ENABLED = PLUGIN_ID + "" ; public static final String DUPLICATE_CODE_MASS_THRESHOLD = PLUGIN_ID + "" ; private static AptanaRDTPlugin plugin ; public AptanaRDTPlugin ( ) { super ( ) ; } private static class RubyDebugGemListener extends Job { private GemListener listener ; public RubyDebugGemListener ( GemListener listener ) { super ( "" ) ; this . listener = listener ; } @ Override protected IStatus run ( IProgressMonitor monitor ) { GemManager . getInstance ( ) . removeGemListener ( listener ) ; return Status . OK_STATUS ; } } public void start ( final BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; initializePreferences ( ) ; context . registerService ( IGemManager . class . getName ( ) , getGemManager ( ) , null ) ; getGemManager ( ) . addGemListener ( new GemListener ( ) { public void managerInitialized ( ) { if ( getGemManager ( ) . gemInstalled ( "" ) ) { setRubyDebugUp ( ) ; } } private void setRubyDebugUp ( ) { setRubyDebugAsDefault ( ) ; removeListener ( this ) ; } public void gemsRefreshed ( ) { if ( getGemManager ( ) . gemInstalled ( "" ) ) { setRubyDebugUp ( ) ; } } public void gemUpdated ( Gem gem ) { } public void gemRemoved ( Gem gem ) { } public void gemAdded ( Gem gem ) { } } ) ; Job job = new RubyGemsInitializer ( ) ; job . setSystem ( true ) ; job . setPriority ( Job . SHORT ) ; job . schedule ( ) ; gemManagersTracker = new ServiceTracker ( context , IGemManager . class . getName ( ) , null ) ; gemManagersTracker . open ( true ) ; } private void initializePreferences ( ) { preferencesLookup [ PREF_INSTANCE ] = new InstanceScope ( ) . getNode ( PLUGIN_ID ) ; preferencesLookup [ PREF_DEFAULT ] = new DefaultScope ( ) . getNode ( PLUGIN_ID ) ; IEclipsePreferences . INodeChangeListener listener = new IEclipsePreferences . INodeChangeListener ( ) { public void added ( IEclipsePreferences . NodeChangeEvent event ) { } public void removed ( IEclipsePreferences . NodeChangeEvent event ) { if ( event . getChild ( ) == preferencesLookup [ PREF_INSTANCE ] ) { preferencesLookup [ PREF_INSTANCE ] = new InstanceScope ( ) . getNode ( PLUGIN_ID ) ; preferencesLookup [ PREF_INSTANCE ] . addPreferenceChangeListener ( new EclipsePreferencesListener ( ) ) ; } } } ; ( ( IEclipsePreferences ) preferencesLookup [ PREF_INSTANCE ] . parent ( ) ) . addNodeChangeListener ( listener ) ; preferencesLookup [ PREF_INSTANCE ] . addPreferenceChangeListener ( new EclipsePreferencesListener ( ) ) ; listener = new IEclipsePreferences . INodeChangeListener ( ) { public void added ( IEclipsePreferences . NodeChangeEvent event ) { } public void removed ( IEclipsePreferences . NodeChangeEvent event ) { if ( event . getChild ( ) == preferencesLookup [ PREF_DEFAULT ] ) { preferencesLookup [ PREF_DEFAULT ] = new DefaultScope ( ) . getNode ( PLUGIN_ID ) ; } } } ; ( ( IEclipsePreferences ) preferencesLookup [ PREF_DEFAULT ] . parent ( ) ) . addNodeChangeListener ( listener ) ; } protected void setRubyDebugAsDefault ( ) { new InstanceScope ( ) . getNode ( LaunchingPlugin . PLUGIN_ID ) . putBoolean ( org . rubypeople . rdt . internal . launching . PreferenceConstants . USE_RUBY_DEBUG , true ) ; } protected void removeListener ( GemListener listener ) { Job job = new RubyDebugGemListener ( listener ) ; job . schedule ( ) ; } public void stop ( BundleContext context ) throws Exception { gemManagersTracker . close ( ) ; super . stop ( context ) ; plugin = null ; } public IGemManager [ ] getGemManagers ( ) { Object [ ] raw = gemManagersTracker . getServices ( ) ; if ( raw == null || raw . length == ) return new IGemManager [ ] ; List < IGemManager > gemManagers = new ArrayList < IGemManager > ( ) ; for ( int i = ; i < raw . length ; i ++ ) { gemManagers . add ( ( IGemManager ) raw [ i ] ) ; } if ( gemManagers . contains ( getGemManager ( ) ) ) { gemManagers . remove ( getGemManager ( ) ) ; } gemManagers . add ( , getGemManager ( ) ) ; return gemManagers . toArray ( new IGemManager [ gemManagers . size ( ) ] ) ; } public static AptanaRDTPlugin getDefault ( ) { return plugin ; } public static File getFileInPlugin ( IPath path ) { try { URL installURL = new URL ( getDefault ( ) . getBundle ( ) . getEntry ( "" ) , path . toString ( ) ) ; URL localURL = FileLocator . toFileURL ( installURL ) ; return new File ( localURL . getFile ( ) ) ; } catch ( IOException ioe ) { return null ; } } public static void log ( Throwable e ) { log ( new Status ( IStatus . ERROR , getPluginId ( ) , - , AptanaRDTMessages . RubyRedPlugin_internal_error , e ) ) ; } public static void log ( IStatus status ) { if ( getDefault ( ) != null && getDefault ( ) . getLog ( ) != null ) { getDefault ( ) . getLog ( ) . log ( status ) ; } else { System . out . println ( status . getMessage ( ) ) ; } } public static String getPluginId ( ) { return PLUGIN_ID ; } public Hashtable < String , String > getOptions ( ) { Hashtable < String , String > options = new Hashtable < String , String > ( ) ; IPreferencesService service = Platform . getPreferencesService ( ) ; Iterator < String > iterator = optionNames . iterator ( ) ; while ( iterator . hasNext ( ) ) { String propertyName = ( String ) iterator . next ( ) ; String propertyValue = service . get ( propertyName , null , this . preferencesLookup ) ; if ( propertyValue != null ) { options . put ( propertyName , propertyValue ) ; } } this . optionsCache = new Hashtable < String , String > ( options ) ; return options ; } public IGemManager getGemManager ( ) { return GemManager . getInstance ( ) ; } public static IPath findGem ( String string ) { IGemManager gemManager = getDefault ( ) . getGemManager ( ) ; if ( gemManager == null ) return null ; IPath path = gemManager . getGemPath ( string ) ; if ( path == null ) return null ; IPath [ ] rubyLibPaths = RubyCore . getLoadpathVariable ( IGemRuntime . GEMLIB_VARIABLE ) ; IPath rubyLibPath = null ; for ( int i = ; i < rubyLibPaths . length ; i ++ ) { if ( rubyLibPaths [ i ] . isPrefixOf ( path ) ) { rubyLibPath = rubyLibPaths [ i ] ; break ; } } if ( rubyLibPath == null ) return null ; IPath resPath = new Path ( IGemRuntime . GEMLIB_VARIABLE ) ; for ( int k = rubyLibPath . segmentCount ( ) ; k < path . segmentCount ( ) ; k ++ ) { resPath = resPath . append ( path . segment ( k ) ) ; } return resPath ; } public static void log ( String string ) { log ( new Status ( Status . INFO , PLUGIN_ID , - , string , null ) ) ; } public static void addGemLoadPath ( IRubyProject rubyProject , Gem originalGem , IProgressMonitor monitor ) throws RubyModelException { List < ILoadpathEntry > list = new ArrayList < ILoadpathEntry > ( ) ; ILoadpathEntry [ ] original = rubyProject . getRawLoadpath ( ) ; list . addAll ( Arrays . asList ( original ) ) ; Set < Gem > gems = new HashSet < Gem > ( ) ; gems . add ( originalGem ) ; Set < GemRequirement > dependencies = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . getDependencies ( originalGem ) ; for ( GemRequirement dependency : dependencies ) { Gem gem = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . findGem ( dependency ) ; if ( gem != null ) gems . add ( gem ) ; } for ( Gem gem : gems ) { IPath gemPath = AptanaRDTPlugin . findGem ( gem . getName ( ) + "" + gem . getVersion ( ) ) ; if ( gemPath != null ) { ILoadpathEntry newEntry = RubyCore . newVariableEntry ( gemPath ) ; if ( ! list . contains ( newEntry ) ) list . add ( newEntry ) ; } } if ( list . size ( ) == original . length ) return ; if ( rubyProject . getRawLoadpath ( ) . length != original . length ) { System . out . println ( "" ) ; } rubyProject . setRawLoadpath ( ( ILoadpathEntry [ ] ) list . toArray ( new ILoadpathEntry [ list . size ( ) ] ) , monitor ) ; } public static IPath checkBinDir ( String command ) { List < IPath > paths = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . getGemInstallPaths ( ) ; if ( paths == null ) return null ; for ( IPath path : paths ) { if ( path == null ) continue ; IPath possible = path . removeLastSegments ( ) . append ( BIN ) . append ( command ) ; if ( possible . toFile ( ) . exists ( ) ) return possible ; } return null ; } public static IPath checkGemBinDir ( String gemName , String command ) { IPath path = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . getGemPath ( gemName ) ; if ( path == null ) return null ; path = path . append ( BIN ) . append ( command ) ; if ( path . toFile ( ) . exists ( ) ) { return path ; } return null ; } public IProxyService getProxyService ( ) { if ( proxyTracker == null ) { proxyTracker = new ServiceTracker ( getBundle ( ) . getBundleContext ( ) , IProxyService . class . getName ( ) , null ) ; proxyTracker . open ( ) ; } return ( IProxyService ) proxyTracker . getService ( ) ; } } package com . aptana . rdt ; import org . eclipse . osgi . util . NLS ; public class AptanaRDTMessages extends NLS { private static final String BUNDLE_NAME = AptanaRDTMessages . class . getName ( ) ; public static String RubyRedPlugin_internal_error ; static { NLS . initializeMessages ( BUNDLE_NAME , AptanaRDTMessages . class ) ; } } package com . aptana . rdt . core . rspec ; import java . util . ArrayList ; import java . util . List ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . SourceRange ; public class Behavior implements ISourceReference { private String className ; private List < Example > examples = new ArrayList < Example > ( ) ; private int offset ; private int length ; Behavior ( String className , int offset , int length ) { this . className = className ; this . offset = offset ; this . length = length ; } void addExample ( Example example ) { example . setParent ( this ) ; examples . add ( example ) ; } public Object [ ] getExamples ( ) { return examples . toArray ( new Object [ examples . size ( ) ] ) ; } public String getClassName ( ) { return className ; } public String getSource ( ) throws RubyModelException { return getClassName ( ) ; } public ISourceRange getSourceRange ( ) throws RubyModelException { return new SourceRange ( offset , length ) ; } } package com . aptana . rdt . core . rspec ; import java . util . ArrayList ; import java . util . List ; import org . jruby . ast . FCallNode ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; public class RSpecStructureCreator extends InOrderVisitor { private List < Behavior > behaviors = new ArrayList < Behavior > ( ) ; public Object visitFCallNode ( FCallNode visited ) { if ( visited . getName ( ) . equals ( "" ) ) { List < String > args = ASTUtil . getArgumentsFromFunctionCall ( visited ) ; String className = args . get ( ) ; int start = visited . getPosition ( ) . getStartOffset ( ) ; push ( visited , className , start ) ; } else if ( visited . getName ( ) . equals ( "" ) ) { List < String > args = ASTUtil . getArgumentsFromFunctionCall ( visited ) ; String description = args . get ( ) ; if ( description . startsWith ( "" ) || description . startsWith ( "" ) ) description = description . substring ( ) ; if ( description . endsWith ( "" ) || description . endsWith ( "" ) ) description = new String ( description . substring ( , description . length ( ) - ) ) ; int start = visited . getPosition ( ) . getStartOffset ( ) ; peek ( ) . addExample ( new Example ( description , start , visited . getPosition ( ) . getEndOffset ( ) - start ) ) ; } else if ( visited . getName ( ) . equals ( "" ) ) { List < String > args = ASTUtil . getArgumentsFromFunctionCall ( visited ) ; String description = args . get ( ) ; int start = visited . getPosition ( ) . getStartOffset ( ) ; push ( visited , description , start ) ; } return super . visitFCallNode ( visited ) ; } private Behavior peek ( ) { return behaviors . get ( behaviors . size ( ) - ) ; } private void push ( FCallNode visited , String className , int start ) { behaviors . add ( new Behavior ( className , start , visited . getPosition ( ) . getEndOffset ( ) - start ) ) ; } public Object [ ] getBehaviors ( ) { return behaviors . toArray ( new Object [ behaviors . size ( ) ] ) ; } } package com . aptana . rdt . core . rspec ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . SourceRange ; public class Example implements ISourceReference { private String description ; private Behavior parent ; private int offset ; private int length ; Example ( String description , int offset , int length ) { this . description = description ; this . offset = offset ; this . length = length ; } void setParent ( Behavior parent ) { this . parent = parent ; } public Behavior getBehavior ( ) { return parent ; } public String getDescription ( ) { return description ; } public String getSource ( ) throws RubyModelException { return getDescription ( ) ; } public ISourceRange getSourceRange ( ) throws RubyModelException { return new SourceRange ( offset , length ) ; } } package com . aptana . rdt . core . preferences ; public interface IPreferenceConstants { public static final String GEM_SCRIPT_PATH = "" ; } package com . aptana . rdt . core . gems ; public class GemRequirement { private String name ; private String versionDependency ; public GemRequirement ( String name , String versionDependency ) { this . name = name ; this . versionDependency = versionDependency ; } private String getRule ( ) { return versionDependency . split ( "" ) [ ] ; } private Version getVersion ( ) { String raw = versionDependency . split ( "" ) [ ] ; if ( raw . endsWith ( "" ) ) { raw = new String ( raw . substring ( , raw . length ( ) - ) ) ; } return new Version ( raw ) ; } public String toString ( ) { return name + "" + versionDependency + "" ; } public String getName ( ) { return name ; } public boolean meetsRequirements ( String version ) { Version gemVersion = new Version ( version ) ; if ( getRule ( ) . equals ( "" ) ) { return gemVersion . equals ( getVersion ( ) ) ; } else if ( getRule ( ) . equals ( "" ) ) { return gemVersion . isGreaterThanOrEqualTo ( getVersion ( ) ) ; } else if ( getRule ( ) . equals ( "" ) ) { return gemVersion . isLessThanOrEqualTo ( getVersion ( ) ) ; } else if ( getRule ( ) . equals ( ">" ) ) { return gemVersion . isGreaterThan ( getVersion ( ) ) ; } else if ( getRule ( ) . equals ( "" ) ) { return gemVersion . isLessThan ( getVersion ( ) ) ; } return false ; } } package com . aptana . rdt . core . gems ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Comparator ; import java . util . List ; import java . util . SortedSet ; import java . util . StringTokenizer ; import java . util . TreeSet ; public class LogicalGem extends Gem { private Collection < Gem > gems ; private LogicalGem ( Collection < Gem > gems , String name , String version , String description ) { super ( name , version , description ) ; this . gems = gems ; } public static LogicalGem create ( Collection < Gem > gems ) { if ( gems == null || gems . isEmpty ( ) ) throw new IllegalArgumentException ( "" ) ; String name = null ; String description = null ; String version = "" ; for ( Gem gem : gems ) { if ( name == null ) name = gem . getName ( ) ; if ( description == null ) description = gem . getDescription ( ) ; version += gem . getVersion ( ) + "" ; } version = new String ( version . substring ( , version . length ( ) - ) ) ; version += '' ; return new LogicalGem ( gems , name , version , description ) ; } public SortedSet < String > getVersions ( ) { String raw = new String ( getVersion ( ) . substring ( , getVersion ( ) . length ( ) - ) ) ; SortedSet < String > version = new TreeSet < String > ( new VersionComparator ( ) ) ; StringTokenizer tokenizer = new StringTokenizer ( raw , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) { version . add ( tokenizer . nextToken ( ) . trim ( ) ) ; } return version ; } private class VersionComparator implements Comparator < String > { public int compare ( String v1 , String v2 ) { List < Integer > v1Parts = getParts ( v1 ) ; List < Integer > v2Parts = getParts ( v2 ) ; int blah = Math . min ( v1Parts . size ( ) , v2Parts . size ( ) ) ; for ( int i = ; i < blah ; i ++ ) { Integer one = v1Parts . get ( i ) ; Integer two = v2Parts . get ( i ) ; int result = one . compareTo ( two ) ; if ( result != ) return result ; } if ( v1Parts . size ( ) > v2Parts . size ( ) ) { return ; } else if ( v2Parts . size ( ) > v1Parts . size ( ) ) { return - ; } return ; } private List < Integer > getParts ( String version ) { StringTokenizer tokenizer = new StringTokenizer ( version , "" ) ; List < Integer > parts = new ArrayList < Integer > ( ) ; while ( tokenizer . hasMoreTokens ( ) ) { parts . add ( Integer . parseInt ( tokenizer . nextToken ( ) ) ) ; } return parts ; } } public Collection < Gem > getGems ( ) { return gems ; } } package com . aptana . rdt . core . gems ; public class Version extends org . osgi . framework . Version { public Version ( String version ) { super ( version ) ; } public boolean isGreaterThan ( Version other ) { int result = compareTo ( other ) ; return result > ; } public boolean isEqualTo ( Version other ) { int result = compareTo ( other ) ; return result == ; } public boolean isGreaterThanOrEqualTo ( Version other ) { int result = compareTo ( other ) ; return result >= ; } public boolean isLessThan ( Version other ) { int result = compareTo ( other ) ; return result < ; } public boolean isLessThanOrEqualTo ( Version other ) { int result = compareTo ( other ) ; return result <= ; } public int getBugfix ( ) { return getMicro ( ) ; } public int getRevision ( ) { String qualifier = getQualifier ( ) ; if ( qualifier == null ) return ; return Integer . parseInt ( qualifier ) ; } public boolean isGreaterThanOrEqualTo ( String string ) { return isGreaterThanOrEqualTo ( new Version ( string ) ) ; } public boolean isLessThanOrEqualTo ( String string ) { return isLessThanOrEqualTo ( new Version ( string ) ) ; } public boolean isLessThan ( String string ) { return isLessThan ( new Version ( string ) ) ; } } package com . aptana . rdt . core . gems ; import java . util . ArrayList ; import java . util . List ; import java . util . StringTokenizer ; public class Gem implements Comparable < Gem > { private String name ; private String version ; private String description ; private String platform ; private boolean compiles = false ; private boolean forceUpdates ; public static final String RUBY_PLATFORM = "" ; public static final String MSWIN32_PLATFORM = "" ; public static final String JRUBY_PLATFORM = "" ; public static final String ANY_VERSION = "" ; public Gem ( String name , String version , String description ) { this ( name , version , description , RUBY_PLATFORM ) ; } public Gem ( String name , String version , String description , String platform ) { if ( name == null ) throw new IllegalArgumentException ( "" ) ; if ( version == null ) throw new IllegalArgumentException ( "" ) ; if ( version . indexOf ( "" ) != - ) { if ( ! ( this instanceof LogicalGem ) ) throw new IllegalArgumentException ( "" ) ; } if ( platform == null ) throw new IllegalArgumentException ( "" ) ; this . name = name ; this . version = version ; this . description = description ; this . platform = platform ; } public String getName ( ) { return name ; } public String getVersion ( ) { return version ; } public Version getVersionObject ( ) { return new Version ( version ) ; } public String getDescription ( ) { return description ; } public String getPlatform ( ) { return platform ; } public boolean equals ( Object arg0 ) { if ( ! ( arg0 instanceof Gem ) ) return false ; Gem other = ( Gem ) arg0 ; return getName ( ) . equals ( other . getName ( ) ) && getVersion ( ) . equals ( other . getVersion ( ) ) && getPlatform ( ) . equals ( other . getPlatform ( ) ) ; } public int hashCode ( ) { return ( getName ( ) . hashCode ( ) * ) + getVersion ( ) . hashCode ( ) ; } public int compareTo ( Gem other ) { return toString ( ) . compareTo ( other . toString ( ) ) ; } public String toString ( ) { return getName ( ) . toLowerCase ( ) + "" + getVersion ( ) + "" + getPlatform ( ) ; } public boolean hasMultipleVersions ( ) { return version != null && version . indexOf ( "" ) != - ; } public List < String > versions ( ) { List < String > versions = new ArrayList < String > ( ) ; if ( version == null ) return versions ; StringTokenizer tokenizer = new StringTokenizer ( version , "" ) ; while ( tokenizer . hasMoreTokens ( ) ) { versions . add ( tokenizer . nextToken ( ) . trim ( ) ) ; } return versions ; } public String getAbsolutePath ( ) { return null ; } public boolean isLocal ( ) { return false ; } public void delete ( ) { } public boolean meetsRequirements ( GemRequirement requirement ) { if ( ! getName ( ) . equals ( requirement . getName ( ) ) ) return false ; return ( requirement . meetsRequirements ( getVersion ( ) ) ) ; } public void setCompiles ( boolean compiles ) { this . compiles = compiles ; } public boolean compiles ( ) { return compiles ; } public boolean forceUpdates ( ) { return forceUpdates ; } public void setForceUpdate ( boolean forceUpdate ) { this . forceUpdates = forceUpdate ; } public boolean isInstallable ( ) { return true ; } } package com . aptana . rdt . core . gems ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; public interface ILocalGemManager extends IGemManager { public ILaunchConfiguration run ( String args ) throws CoreException ; } package com . aptana . rdt . core . gems ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import org . rubypeople . rdt . core . util . Util ; import com . aptana . rdt . AptanaRDTPlugin ; public class LocalFileGem extends Gem { private URL url ; private Set < String > dependencies ; private File file ; public LocalFileGem ( URL url , String name , String version , String description , String platform ) { super ( name , version , description , platform ) ; this . url = url ; this . dependencies = new HashSet < String > ( ) ; } public static LocalFileGem create ( URL file ) { String [ ] fileNameParts = file . getPath ( ) . split ( "" ) ; String name = fileNameParts [ fileNameParts . length - ] ; String [ ] parts = name . split ( "" ) ; String version = "" ; String platform = RUBY_PLATFORM ; if ( parts != null && parts . length > ) { name = parts [ ] ; version = parts [ ] ; if ( parts . length > ) platform = parts [ ] ; } if ( version . endsWith ( "" ) ) version = new String ( version . substring ( , version . length ( ) - ) ) ; if ( platform . endsWith ( "" ) ) platform = new String ( platform . substring ( , platform . length ( ) - ) ) ; return new LocalFileGem ( file , name , version , "" , platform ) ; } public boolean isLocal ( ) { return true ; } public String getAbsolutePath ( ) { if ( file == null ) file = copyFile ( url ) ; return file . getAbsolutePath ( ) ; } public void addDependency ( String name ) { dependencies . add ( name ) ; } public void delete ( ) { if ( file == null ) return ; if ( ! file . delete ( ) ) file . deleteOnExit ( ) ; } public Set < String > getDependencies ( ) { return Collections . unmodifiableSet ( dependencies ) ; } private File copyFile ( URL url ) { byte [ ] contents = getFileContents ( url ) ; String [ ] fileNameParts = url . getPath ( ) . split ( "" ) ; String filename = fileNameParts [ fileNameParts . length - ] ; return writeContents ( contents , filename ) ; } private File writeContents ( byte [ ] contents , String filename ) { File tempGemLocation = AptanaRDTPlugin . getDefault ( ) . getStateLocation ( ) . toFile ( ) ; File file = new File ( tempGemLocation , filename ) ; FileOutputStream outputStream = null ; try { outputStream = new FileOutputStream ( file ) ; outputStream . write ( contents ) ; } catch ( IOException e ) { AptanaRDTPlugin . log ( e ) ; } finally { try { if ( outputStream != null ) outputStream . close ( ) ; } catch ( IOException e ) { } } return file ; } private byte [ ] getFileContents ( URL url ) { InputStream stream = null ; try { stream = url . openStream ( ) ; return Util . getInputStreamAsByteArray ( stream , - ) ; } catch ( IOException e ) { AptanaRDTPlugin . log ( e ) ; } finally { try { if ( stream != null ) stream . close ( ) ; } catch ( IOException e ) { } } return new byte [ ] ; } } package com . aptana . rdt . core . gems ; public interface GemListener { public void gemsRefreshed ( ) ; public void gemAdded ( Gem gem ) ; public void gemRemoved ( Gem gem ) ; public void managerInitialized ( ) ; public void gemUpdated ( Gem gem ) ; } package com . aptana . rdt . core . gems ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . debug . core . ILaunchConfiguration ; public interface IGemManager { public static final String DEFAULT_GEM_HOST = "" ; public ILaunchConfiguration run ( String args ) throws CoreException ; public Set < Gem > getGems ( ) ; public Set < Gem > getRemoteGems ( ) ; public IStatus installGem ( Gem gem , IProgressMonitor monitor ) ; public IStatus installGem ( Gem gem , boolean includeDependencies , IProgressMonitor monitor ) ; public IStatus installGem ( Gem gem , String sourceURL , IProgressMonitor monitor ) ; public IStatus removeGem ( Gem gem , IProgressMonitor monitor ) ; public IStatus update ( Gem gem , IProgressMonitor monitor ) ; public IStatus updateAll ( IProgressMonitor monitor ) ; public boolean gemInstalled ( String gemName ) ; public IStatus refresh ( IProgressMonitor monitor ) ; public void addGemListener ( GemListener listener ) ; public void removeGemListener ( GemListener listener ) ; public List < IPath > getGemInstallPaths ( ) ; public IPath getGemPath ( String gemName ) ; public IPath getGemPath ( String gemName , String version ) ; public boolean isRubyGemsInstalled ( ) ; public void initialize ( ) ; public boolean isInitialized ( ) ; public IStatus cleanup ( IProgressMonitor monitor ) ; public Set < Gem > getRemoteGems ( String sourceURL , IProgressMonitor monitor ) ; public Set < String > getSourceURLs ( ) ; public Set < GemRequirement > getDependencies ( Gem gem ) ; public Gem findGem ( GemRequirement dependency ) ; public List < Version > getVersions ( String gemName ) ; public String getName ( ) ; public Version getVersion ( ) ; public IStatus updateSystem ( IProgressMonitor monitor ) ; } package com . aptana . rdt . core . gems ; import java . net . URL ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IConfigurationElement ; import org . eclipse . core . runtime . IExtensionPoint ; import org . eclipse . core . runtime . InvalidRegistryObjectException ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . osgi . framework . Bundle ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . AptanaRDTPlugin ; public class ContributedGemRegistry { private static Collection < Gem > fContributed ; private ContributedGemRegistry ( ) { } public static Collection < Gem > getContributedGems ( ) { if ( fContributed == null ) { Collection < Gem > gems = new ArrayList < Gem > ( ) ; IExtensionPoint extensionPoint = Platform . getExtensionRegistry ( ) . getExtensionPoint ( AptanaRDTPlugin . PLUGIN_ID , AptanaRDTPlugin . EXTENSION_POINT_GEMS ) ; IConfigurationElement [ ] configs = extensionPoint . getConfigurationElements ( ) ; for ( int i = ; i < configs . length ; i ++ ) { IConfigurationElement element = configs [ i ] ; if ( ! "" . equals ( element . getName ( ) ) ) continue ; try { Gem gem = createGem ( element ) ; if ( gem == null ) continue ; gems . add ( gem ) ; } catch ( InvalidRegistryObjectException e ) { AptanaRDTPlugin . log ( e ) ; } } fContributed = gems ; } return fContributed ; } private static Gem createGem ( IConfigurationElement element ) { boolean install = false ; String autoInstall = element . getAttribute ( "" ) ; if ( autoInstall != null && autoInstall . trim ( ) . length ( ) > ) { install = Boolean . parseBoolean ( autoInstall ) ; } if ( ! install ) return null ; String name = element . getAttribute ( "" ) ; Gem gem = null ; String path = element . getAttribute ( "" ) ; if ( path == null || path . trim ( ) . length ( ) == ) { gem = new Gem ( name , getVersion ( element ) , null ) ; } else { gem = createLocalGem ( name , path , element ) ; } String compiles = element . getAttribute ( "" ) ; gem . setCompiles ( Boolean . parseBoolean ( compiles ) ) ; boolean forceUpdate = false ; String forceUpdateRaw = element . getAttribute ( "" ) ; if ( forceUpdateRaw != null && forceUpdateRaw . trim ( ) . length ( ) > ) { forceUpdate = Boolean . parseBoolean ( forceUpdateRaw ) ; } gem . setForceUpdate ( forceUpdate ) ; return gem ; } private static Gem createLocalGem ( String name , String path , IConfigurationElement element ) { Bundle bundle = Platform . getBundle ( element . getContributor ( ) . getName ( ) ) ; URL url = FileLocator . find ( bundle , new Path ( path ) , null ) ; if ( url == null ) { AptanaRDTPlugin . log ( "" + path + "" + element . getContributor ( ) . getName ( ) + "" ) ; return null ; } Gem gem = null ; if ( name == null || name . trim ( ) . length ( ) == ) gem = LocalFileGem . create ( url ) ; else { String platform = element . getAttribute ( "" ) ; if ( platform == null || platform . trim ( ) . length ( ) == ) platform = Gem . RUBY_PLATFORM ; gem = new LocalFileGem ( url , name , getVersion ( element ) , "" , platform ) ; } IConfigurationElement [ ] dependencies = element . getChildren ( "" ) ; for ( int j = ; j < dependencies . length ; j ++ ) { String dependency = dependencies [ j ] . getAttribute ( "" ) ; ( ( LocalFileGem ) gem ) . addDependency ( dependency ) ; } return gem ; } private static String getVersion ( IConfigurationElement element ) { String version = element . getAttribute ( "" ) ; if ( version != null ) return version ; return Gem . ANY_VERSION ; } public static Gem getGem ( String name ) { Collection < Gem > gems = filterByPlatform ( getContributedGems ( ) ) ; for ( Gem gem : gems ) { if ( gem . getName ( ) . equals ( name ) ) { return gem ; } } return null ; } public static Collection < Gem > filterByPlatform ( Collection < Gem > gems ) { Map < String , Gem > map = new HashMap < String , Gem > ( ) ; for ( Gem gem : gems ) { if ( map . containsKey ( gem . getName ( ) ) ) { if ( RubyRuntime . currentVMIsJRuby ( ) && gem . getPlatform ( ) . equals ( Gem . JRUBY_PLATFORM ) ) { map . put ( gem . getName ( ) , gem ) ; } if ( ! RubyRuntime . currentVMIsJRuby ( ) && Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) && gem . getPlatform ( ) . equals ( Gem . MSWIN32_PLATFORM ) ) { if ( RubyRuntime . currentVMIsCygwin ( ) ) continue ; map . put ( gem . getName ( ) , gem ) ; } } else { if ( gem . getPlatform ( ) . equals ( Gem . MSWIN32_PLATFORM ) ) { if ( ! Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) continue ; if ( RubyRuntime . currentVMIsJRuby ( ) ) continue ; if ( RubyRuntime . currentVMIsCygwin ( ) ) continue ; } if ( ! RubyRuntime . currentVMIsJRuby ( ) && gem . getPlatform ( ) . equals ( Gem . JRUBY_PLATFORM ) ) continue ; if ( gem instanceof LocalFileGem ) { LocalFileGem localGem = ( LocalFileGem ) gem ; if ( RubyRuntime . currentVMIsJRuby ( ) && ! gem . getPlatform ( ) . equals ( Gem . JRUBY_PLATFORM ) && localGem . compiles ( ) ) continue ; } map . put ( gem . getName ( ) , gem ) ; } } return map . values ( ) ; } public static List < Gem > sortByDependency ( Collection < Gem > gems ) { gems = new ArrayList < Gem > ( gems ) ; List < Gem > sorted = new ArrayList < Gem > ( ) ; while ( sorted . size ( ) < gems . size ( ) ) { for ( Gem gem : gems ) { if ( sorted . size ( ) == gems . size ( ) ) return sorted ; if ( sorted . contains ( gem ) ) continue ; boolean add = true ; if ( gem instanceof LocalFileGem ) { LocalFileGem local = ( LocalFileGem ) gem ; Set < String > dependencies = local . getDependencies ( ) ; for ( String dependency : dependencies ) { if ( getGemManager ( ) . gemInstalled ( dependency ) ) continue ; if ( ! contains ( sorted , dependency ) ) { add = false ; if ( ! contains ( gems , dependency ) ) { AptanaRDTPlugin . log ( "" + local . toString ( ) + "" ) ; gems . remove ( gem ) ; } break ; } } } if ( add ) sorted . add ( gem ) ; } } return sorted ; } private static boolean contains ( Collection < Gem > gems , String name ) { for ( Gem gem : gems ) { if ( gem . getName ( ) . equals ( name ) ) return true ; } return false ; } private static IGemManager getGemManager ( ) { return AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) ; } } package com . aptana . rdt . core . gems ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfiguration ; public abstract class AbstractGemManager implements IGemManager { protected Set < GemListener > listeners ; protected AbstractGemManager ( ) { listeners = new HashSet < GemListener > ( ) ; } public synchronized void addGemListener ( GemListener listener ) { listeners . add ( listener ) ; } public synchronized void removeGemListener ( GemListener listener ) { listeners . remove ( listener ) ; } public ILaunchConfiguration run ( String args ) throws CoreException { return null ; } } package com . aptana . rdt . internal . ui . infoviews ; import com . aptana . rdt . ui . BrowserView ; public class RubyStdLibAPIView extends BrowserView { static final String URL = "" ; @ Override protected String getURL ( ) { return URL ; } } package com . aptana . rdt . internal . ui . infoviews ; import com . aptana . rdt . ui . BrowserView ; public class RubyCoreAPIView extends BrowserView { private static final String URL = "" ; @ Override protected String getURL ( ) { return URL ; } } package com . aptana . rdt . internal . ui ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . MessageDialogWithToggle ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . debug . ui . InstallDeveloperToolsDialog ; import org . rubypeople . rdt . internal . debug . ui . launcher . InstallGemsJob ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; import org . rubypeople . rdt . internal . ui . RubyInstalledDetector ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . ContributedGemRegistry ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . GemListener ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . core . gems . Version ; import com . aptana . rdt . ui . AptanaRDTUIPlugin ; import com . aptana . rdt . ui . preferences . IPreferenceConstants ; public class GemAutoInstallDialogJob extends UIJob implements GemListener , IVMInstallChangedListener { private static class SerialRule implements ISchedulingRule { public SerialRule ( ) { } public boolean contains ( ISchedulingRule rule ) { return rule == this ; } public boolean isConflicting ( ISchedulingRule rule ) { return rule instanceof SerialRule ; } } private boolean rescheduleOnRefresh ; public GemAutoInstallDialogJob ( ) { super ( "" ) ; setRule ( new SerialRule ( ) ) ; AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . addGemListener ( this ) ; RubyRuntime . addVMInstallChangedListener ( this ) ; } public boolean shouldRun ( ) { return ! PlatformUI . getWorkbench ( ) . isClosing ( ) && AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . isInitialized ( ) ; } @ Override public IStatus runInUIThread ( IProgressMonitor monitor ) { if ( ! usingIncludedJRuby ( ) && rubyNotInstalled ( ) ) { if ( RubyInstalledDetector . isFinished ( ) ) { return Status . CANCEL_STATUS ; } schedule ( ) ; return Status . OK_STATUS ; } if ( ! getGemManager ( ) . isRubyGemsInstalled ( ) ) { String key = "" ; String dontBug = AptanaRDTUIPlugin . getDefault ( ) . getPreferenceStore ( ) . getString ( key ) ; if ( dontBug != null && dontBug . equals ( MessageDialogWithToggle . ALWAYS ) ) { return Status . OK_STATUS ; } MessageDialogWithToggle . openWarning ( RubyPlugin . getActiveWorkbenchShell ( ) , "" , "" , "" , false , AptanaRDTUIPlugin . getDefault ( ) . getPreferenceStore ( ) , key ) ; return Status . OK_STATUS ; } if ( ! Platform . getPreferencesService ( ) . getBoolean ( AptanaRDTUIPlugin . PLUGIN_ID , IPreferenceConstants . PROMPT_TO_AUTO_INSTALL_GEMS , true , null ) ) { return Status . OK_STATUS ; } monitor . beginTask ( "" , ) ; monitor . subTask ( "" ) ; Collection < Gem > gems = getContributedGems ( ) ; monitor . worked ( ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; monitor . subTask ( "" ) ; gems = filterByPlatform ( gems ) ; monitor . worked ( ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; monitor . subTask ( "" ) ; gems = filterOutInstalled ( gems ) ; monitor . worked ( ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; monitor . subTask ( "" ) ; gems = filterOutIgnored ( gems ) ; monitor . worked ( ) ; gems = filterActiveResource ( gems ) ; if ( gems . isEmpty ( ) ) { monitor . done ( ) ; return Status . OK_STATUS ; } if ( hasGemsWhichCompile ( gems ) && InstallDeveloperToolsDialog . shouldShow ( ) ) { InstallDeveloperToolsDialog installToolsDialog = new InstallDeveloperToolsDialog ( RubyPlugin . getActiveWorkbenchShell ( ) ) ; installToolsDialog . open ( ) ; return Status . CANCEL_STATUS ; } GemAutoInstallDialog dialog = new GemAutoInstallDialog ( RubyPlugin . getActiveWorkbenchShell ( ) , gems ) ; if ( PlatformUI . getWorkbench ( ) . isClosing ( ) ) { return Status . CANCEL_STATUS ; } int code = dialog . open ( ) ; if ( code == Dialog . CANCEL ) { monitor . setCanceled ( true ) ; return Status . CANCEL_STATUS ; } Collection < Gem > finalGems = dialog . getSelectedGems ( ) ; if ( finalGems . isEmpty ( ) ) { monitor . done ( ) ; return Status . OK_STATUS ; } Job job = new InstallGemsJob ( finalGems ) ; job . setSystem ( true ) ; job . schedule ( ) ; monitor . done ( ) ; return Status . OK_STATUS ; } private boolean usingIncludedJRuby ( ) { return Platform . getPreferencesService ( ) . getBoolean ( LaunchingPlugin . PLUGIN_ID , LaunchingPlugin . USING_INCLUDED_JRUBY , false , null ) ; } private boolean rubyNotInstalled ( ) { IVMInstall [ ] cRubyInstalls = RubyRuntime . getVMInstallType ( IRubyLaunchConfigurationConstants . ID_STANDARD_VM_TYPE ) . getVMInstalls ( ) ; return cRubyInstalls == null || cRubyInstalls . length == ; } private Collection < Gem > filterByPlatform ( Collection < Gem > gems ) { return ContributedGemRegistry . filterByPlatform ( gems ) ; } private Collection < Gem > filterActiveResource ( Collection < Gem > gems ) { if ( ! contains ( gems , "" ) ) return gems ; if ( ! getGemManager ( ) . gemInstalled ( "" ) ) { return gems ; } boolean containsRails2 = false ; List < Version > versions = getGemManager ( ) . getVersions ( "" ) ; for ( Version version : versions ) { if ( version . isGreaterThanOrEqualTo ( "" ) ) { containsRails2 = true ; break ; } } if ( ! containsRails2 ) { return remove ( gems , "" ) ; } return gems ; } private Collection < Gem > remove ( Collection < Gem > gems , String name ) { Gem toRemove = get ( gems , name ) ; if ( toRemove == null ) return gems ; Collection < Gem > copy = new ArrayList < Gem > ( gems ) ; copy . remove ( toRemove ) ; return copy ; } private boolean contains ( Collection < Gem > gems , String name ) { return get ( gems , name ) != null ; } private Gem get ( Collection < Gem > gems , String name ) { for ( Gem gem : gems ) { if ( gem . getName ( ) . equals ( name ) ) { return gem ; } } return null ; } private boolean hasGemsWhichCompile ( Collection < Gem > finalGems ) { for ( Gem gem : finalGems ) { if ( gem . compiles ( ) ) return true ; } return false ; } private static Collection < Gem > filterOutIgnored ( Collection < Gem > gems ) { Collection < Gem > filtered = new ArrayList < Gem > ( ) ; for ( Gem gem : gems ) { if ( Platform . getPreferencesService ( ) . getBoolean ( AptanaRDTPlugin . PLUGIN_ID , GemAutoInstallDialog . getIgnorePrefKey ( gem ) , false , null ) ) continue ; filtered . add ( gem ) ; } return filtered ; } private Collection < Gem > filterOutInstalled ( Collection < Gem > gems ) { Collection < Gem > filtered = new ArrayList < Gem > ( ) ; for ( Gem gem : gems ) { if ( getGemManager ( ) . gemInstalled ( gem . getName ( ) ) ) { if ( ! gem . forceUpdates ( ) ) continue ; if ( newerVersionInstalled ( gem ) ) continue ; } filtered . add ( gem ) ; } return filtered ; } private boolean newerVersionInstalled ( Gem gem ) { List < Version > versions = getGemManager ( ) . getVersions ( gem . getName ( ) ) ; for ( Version version : versions ) { if ( version . isGreaterThanOrEqualTo ( gem . getVersionObject ( ) ) ) { return true ; } } return false ; } private IGemManager getGemManager ( ) { return AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) ; } private Collection < Gem > getContributedGems ( ) { return ContributedGemRegistry . getContributedGems ( ) ; } public void managerInitialized ( ) { schedule ( ) ; } public void gemsRefreshed ( ) { if ( rescheduleOnRefresh ) { schedule ( ) ; rescheduleOnRefresh = false ; } } public void gemRemoved ( Gem gem ) { } public void gemAdded ( Gem gem ) { } public void gemUpdated ( Gem gem ) { } public void vmRemoved ( IVMInstall removedVm ) { } public void vmChanged ( PropertyChangeEvent event ) { } public void vmAdded ( IVMInstall newVm ) { } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { if ( current == null ) return ; rescheduleOnRefresh = true ; } } package com . aptana . rdt . internal . ui . actions ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPart ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . ui . gems . GemsMessages ; import com . aptana . rdt . ui . gems . GemsView ; import com . aptana . rdt . ui . gems . RemoveGemDialog ; public class RemoveGemActionDelegate implements IObjectActionDelegate , IViewActionDelegate { private GemsView view ; private Gem selectedGem ; public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { } public void run ( IAction action ) { if ( selectedGem == null ) return ; boolean okay = MessageDialog . openConfirm ( view . getViewSite ( ) . getShell ( ) , null , GemsMessages . bind ( GemsMessages . RemoveGemDialog_msg , selectedGem . getName ( ) ) ) ; if ( ! okay ) return ; Job job = null ; if ( selectedGem . hasMultipleVersions ( ) ) { final int [ ] result = new int [ ] ; final String [ ] version = new String [ ] ; Display . getDefault ( ) . syncExec ( new Runnable ( ) { public void run ( ) { RemoveGemDialog dialog = new RemoveGemDialog ( Display . getDefault ( ) . getActiveShell ( ) , selectedGem . versions ( ) ) ; result [ ] = dialog . open ( ) ; version [ ] = dialog . getVersion ( ) ; } } ) ; if ( result [ ] != RemoveGemDialog . OK ) return ; job = new Job ( "" ) { protected IStatus run ( org . eclipse . core . runtime . IProgressMonitor monitor ) { return getGemManager ( ) . removeGem ( new Gem ( selectedGem . getName ( ) , version [ ] , selectedGem . getDescription ( ) ) , monitor ) ; } } ; } else { job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { return getGemManager ( ) . removeGem ( selectedGem , monitor ) ; } } ; } if ( job != null ) { job . setUser ( true ) ; job . schedule ( ) ; } } protected IGemManager getGemManager ( ) { return view . getGemManager ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { if ( selection == null || selection . isEmpty ( ) ) { action . setEnabled ( false ) ; return ; } if ( ! ( selection instanceof IStructuredSelection ) ) { action . setEnabled ( false ) ; return ; } IStructuredSelection sel = ( IStructuredSelection ) selection ; Object element = sel . getFirstElement ( ) ; if ( ! ( element instanceof Gem ) ) { action . setEnabled ( false ) ; return ; } this . selectedGem = ( Gem ) element ; action . setEnabled ( true ) ; } public void init ( IViewPart view ) { this . view = ( GemsView ) view ; } } package com . aptana . rdt . internal . ui . actions ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPart ; import com . aptana . rdt . AptanaRDTPlugin ; public class UpdateAllActionDelegate implements IObjectActionDelegate , IViewActionDelegate { public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { } public void run ( IAction action ) { Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { return AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . updateAll ( monitor ) ; } } ; job . setUser ( true ) ; job . schedule ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { } public void init ( IViewPart view ) { } } package com . aptana . rdt . internal . ui . actions ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . progress . UIJob ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . ui . gems . GemsView ; public class RefreshGemsActionDelegate implements IObjectActionDelegate , IViewActionDelegate { private GemsView gemsView ; public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { } public void run ( IAction action ) { UIJob job = new UIJob ( "" ) { @ Override public IStatus runInUIThread ( IProgressMonitor monitor ) { return getGemManager ( ) . refresh ( monitor ) ; } } ; job . setUser ( true ) ; job . schedule ( ) ; } protected IGemManager getGemManager ( ) { return gemsView . getGemManager ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { } public void init ( IViewPart view ) { this . gemsView = ( GemsView ) view ; } } package com . aptana . rdt . internal . ui . actions ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPart ; import org . eclipse . ui . PlatformUI ; import com . aptana . rdt . AptanaRDTPlugin ; public class CleanupGemsActionDelegate implements IObjectActionDelegate , IViewActionDelegate { private IWorkbenchPart targetPart ; public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { this . targetPart = targetPart ; } public void run ( IAction action ) { Shell shell = null ; if ( targetPart != null && targetPart . getSite ( ) != null ) shell = targetPart . getSite ( ) . getShell ( ) ; if ( shell == null ) shell = PlatformUI . getWorkbench ( ) . getDisplay ( ) . getActiveShell ( ) ; boolean doIt = MessageDialog . openConfirm ( shell , "" , "" ) ; if ( ! doIt ) return ; Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { return AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . cleanup ( monitor ) ; } } ; job . setUser ( true ) ; job . schedule ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { } public void init ( IViewPart view ) { } } package com . aptana . rdt . internal . ui . actions ; import java . text . MessageFormat ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPart ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . GemListener ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . ui . gems . GemsView ; import com . aptana . rdt . ui . gems . InstallGemDialog ; public class InstallGemActionDelegate implements IObjectActionDelegate , IViewActionDelegate , GemListener { private IAction action ; private GemsView gemsView ; private IGemManager gemManager ; public InstallGemActionDelegate ( ) { } public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { this . action = action ; } public void run ( IAction action ) { InstallGemDialog dialog = new InstallGemDialog ( Display . getCurrent ( ) . getActiveShell ( ) ) ; if ( dialog . open ( ) != Dialog . OK ) return ; final Gem gem = dialog . getGem ( ) ; if ( gem == null || gem . getName ( ) == null || gem . getName ( ) . length ( ) == || ! gem . isInstallable ( ) ) return ; final String sourceURL = dialog . getSourceURL ( ) ; Job job = new Job ( MessageFormat . format ( "" , gem . getName ( ) ) ) { @ Override public IStatus run ( IProgressMonitor monitor ) { return getGemManager ( ) . installGem ( gem , sourceURL , monitor ) ; } } ; job . setUser ( true ) ; job . schedule ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { this . action = action ; if ( getGemManager ( ) != this . gemManager ) { this . gemManager . removeGemListener ( this ) ; getGemManager ( ) . addGemListener ( this ) ; this . gemManager = getGemManager ( ) ; } action . setEnabled ( isEnabled ( ) ) ; } private boolean isEnabled ( ) { return getGemManager ( ) . isRubyGemsInstalled ( ) && getGemManager ( ) . isInitialized ( ) ; } public void init ( IViewPart view ) { this . gemsView = ( GemsView ) view ; this . gemManager = getGemManager ( ) ; getGemManager ( ) . addGemListener ( this ) ; } private IGemManager getGemManager ( ) { return gemsView . getGemManager ( ) ; } public void gemAdded ( Gem gem ) { } public void gemRemoved ( Gem gem ) { } public void gemsRefreshed ( ) { } public void gemUpdated ( Gem gem ) { } public void managerInitialized ( ) { if ( action == null ) return ; action . setEnabled ( isEnabled ( ) ) ; } } package com . aptana . rdt . internal . ui . actions ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; import org . eclipse . ui . IWorkbenchPart ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . ui . gems . GemsView ; public class UpdateGemActionDelegate implements IObjectActionDelegate , IViewActionDelegate { private IViewPart view ; private Gem selectedGem ; public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { } public void run ( IAction action ) { Job job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { return AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . update ( selectedGem , monitor ) ; } } ; job . setUser ( true ) ; job . schedule ( ) ; } public void selectionChanged ( IAction action , ISelection selection ) { if ( view instanceof GemsView ) { if ( selection != null && ! selection . isEmpty ( ) ) { if ( selection instanceof IStructuredSelection ) { IStructuredSelection sel = ( IStructuredSelection ) selection ; Object element = sel . getFirstElement ( ) ; if ( element instanceof Gem ) { this . selectedGem = ( Gem ) element ; } } } } } public void init ( IViewPart view ) { this . view = view ; } } package com . aptana . rdt . internal . ui ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . StatusDialog ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . viewers . CheckStateChangedEvent ; import org . eclipse . jface . viewers . CheckboxTableViewer ; import org . eclipse . jface . viewers . ICheckStateListener ; import org . eclipse . jface . viewers . ILabelProviderListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . swt . widgets . TableItem ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . util . CollectionContentProvider ; import org . rubypeople . rdt . ui . TableViewerSorter ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . core . gems . LocalFileGem ; import com . aptana . rdt . ui . AptanaRDTUIPlugin ; import com . aptana . rdt . ui . preferences . IPreferenceConstants ; public class GemAutoInstallDialog extends StatusDialog { private CheckboxTableViewer gemViewer ; private IStructuredContentProvider contentProvider ; private Collection < Gem > input ; protected List < Gem > selected ; private Button dontPromptButton ; protected GemAutoInstallDialog ( Shell shell , Collection < Gem > gems ) { super ( shell ) ; contentProvider = new CollectionContentProvider ( ) ; selected = new ArrayList < Gem > ( ) ; this . input = gems ; } protected Control createDialogArea ( Composite parent ) { getShell ( ) . setText ( "" ) ; Composite control = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; control . setLayout ( layout ) ; GridData data = new GridData ( GridData . FILL_BOTH ) ; data . widthHint = ; control . setLayoutData ( data ) ; Label sourceLabel = new Label ( control , SWT . LEFT | SWT . WRAP ) ; sourceLabel . setText ( "" ) ; sourceLabel . setLayoutData ( data ) ; Table gemsTable = new Table ( parent , SWT . SINGLE | SWT . FULL_SELECTION | SWT . CHECK ) ; gemViewer = new CheckboxTableViewer ( gemsTable ) ; gemsTable . setHeaderVisible ( true ) ; gemsTable . setLinesVisible ( false ) ; data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . heightHint = ; gemsTable . setLayoutData ( data ) ; TableColumn nameColumn = new TableColumn ( gemsTable , SWT . LEFT ) ; nameColumn . setText ( "" ) ; nameColumn . setWidth ( ) ; TableColumn versionColumn = new TableColumn ( gemsTable , SWT . LEFT ) ; versionColumn . setText ( "" ) ; versionColumn . setWidth ( ) ; TableColumn descriptionColumn = new TableColumn ( gemsTable , SWT . LEFT ) ; descriptionColumn . setText ( "" ) ; descriptionColumn . setWidth ( ) ; gemViewer . setLabelProvider ( new ITableLabelProvider ( ) { public void removeListener ( ILabelProviderListener listener ) { } public boolean isLabelProperty ( Object element , String property ) { return false ; } public void dispose ( ) { } public void addListener ( ILabelProviderListener listener ) { } public String getColumnText ( Object element , int columnIndex ) { Gem gem = ( Gem ) element ; switch ( columnIndex ) { case : return gem . getName ( ) ; case : return gem . getVersion ( ) ; case : return gem . getPlatform ( ) ; default : break ; } return null ; } public Image getColumnImage ( Object element , int columnIndex ) { return null ; } } ) ; gemViewer . setContentProvider ( contentProvider ) ; gemViewer . setInput ( input ) ; TableViewerSorter . bind ( gemViewer , ) ; gemViewer . addCheckStateListener ( new ICheckStateListener ( ) { public void checkStateChanged ( CheckStateChangedEvent event ) { Object [ ] checked = gemViewer . getCheckedElements ( ) ; selected . clear ( ) ; for ( int i = ; i < checked . length ; i ++ ) { selected . add ( ( Gem ) checked [ i ] ) ; } checkDependencies ( ) ; } } ) ; gemViewer . setAllChecked ( true ) ; Composite dontPromptComp = new Composite ( parent , SWT . NONE ) ; dontPromptComp . setLayout ( new GridLayout ( , false ) ) ; dontPromptButton = new Button ( dontPromptComp , SWT . CHECK ) ; dontPromptButton . setSelection ( ! Platform . getPreferencesService ( ) . getBoolean ( AptanaRDTUIPlugin . PLUGIN_ID , IPreferenceConstants . PROMPT_TO_AUTO_INSTALL_GEMS , true , null ) ) ; Label dontPromptLabel = new Label ( dontPromptComp , SWT . NONE ) ; dontPromptLabel . setText ( "" ) ; selected = new ArrayList < Gem > ( input ) ; setImage ( RubyPluginImages . get ( RubyPluginImages . IMG_CTOOLS_RUBY ) ) ; return control ; } @ Override protected void cancelPressed ( ) { storeDontPromptValue ( ) ; super . cancelPressed ( ) ; } @ Override protected void okPressed ( ) { storeDontPromptValue ( ) ; super . okPressed ( ) ; } private void storeDontPromptValue ( ) { new InstanceScope ( ) . getNode ( AptanaRDTUIPlugin . PLUGIN_ID ) . putBoolean ( IPreferenceConstants . PROMPT_TO_AUTO_INSTALL_GEMS , ! dontPromptButton . getSelection ( ) ) ; } protected void createButtonsForButtonBar ( Composite parent ) { super . createButtonsForButtonBar ( parent ) ; Control [ ] children = parent . getChildren ( ) ; for ( int i = ; i < children . length ; i ++ ) { if ( children [ i ] instanceof Button ) { Button button = ( Button ) children [ i ] ; Object data = button . getData ( ) ; if ( data instanceof Integer ) { Integer value = ( Integer ) data ; if ( value . intValue ( ) == IDialogConstants . OK_ID ) { button . setText ( "" ) ; } else if ( value . intValue ( ) == IDialogConstants . CANCEL_ID ) { button . setText ( "" ) ; } } } } Button dontAsk = createButton ( parent , , "" , false ) ; dontAsk . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { IPreferenceStore prefs = AptanaRDTUIPlugin . getDefault ( ) . getPreferenceStore ( ) ; Collection < Gem > selectedGems = getSelectedGems ( ) ; for ( Gem gem : selectedGems ) { prefs . setValue ( getIgnorePrefKey ( gem ) , true ) ; } Collection < Gem > toRemove = new ArrayList < Gem > ( ) ; TableItem [ ] items = gemViewer . getTable ( ) . getItems ( ) ; for ( int x = ; x < items . length ; x ++ ) { if ( items [ x ] . getChecked ( ) ) { items [ x ] . setChecked ( false ) ; items [ x ] . setGrayed ( true ) ; toRemove . add ( ( Gem ) items [ x ] . getData ( ) ) ; } } gemViewer . remove ( toRemove . toArray ( new Gem [ toRemove . size ( ) ] ) ) ; selected . clear ( ) ; super . widgetSelected ( e ) ; } } ) ; } static String getIgnorePrefKey ( Gem gem ) { return "" + gem . getName ( ) + "" + gem . getVersion ( ) ; } protected void checkDependencies ( ) { StringBuffer buffer = new StringBuffer ( ) ; for ( Gem gem : selected ) { LocalFileGem local = ( LocalFileGem ) gem ; Set < String > dependencies = local . getDependencies ( ) ; for ( String dependency : dependencies ) { if ( getGemManager ( ) . gemInstalled ( dependency ) ) continue ; if ( ! contains ( selected , dependency ) ) { if ( buffer . length ( ) > ) buffer . append ( "" ) ; buffer . append ( local . getName ( ) + "" + dependency ) ; } } } if ( buffer . length ( ) > ) updateStatus ( new Status ( Status . WARNING , AptanaRDTUIPlugin . PLUGIN_ID , - , buffer . toString ( ) , null ) ) ; else updateStatus ( Status . OK_STATUS ) ; } private IGemManager getGemManager ( ) { return AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) ; } private boolean contains ( Collection < Gem > gems , String name ) { for ( Gem gem : gems ) { if ( gem . getName ( ) . equals ( name ) ) return true ; } return false ; } public Collection < Gem > getSelectedGems ( ) { return selected ; } } package com . aptana . rdt . internal . ui . text ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . text . BadLocationException ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . core . IMethod ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . search . CollectingSearchRequestor ; import org . rubypeople . rdt . core . search . IRubySearchConstants ; import org . rubypeople . rdt . core . search . IRubySearchScope ; import org . rubypeople . rdt . core . search . SearchEngine ; import org . rubypeople . rdt . core . search . SearchMatch ; import org . rubypeople . rdt . core . search . SearchParticipant ; import org . rubypeople . rdt . core . search . SearchPattern ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; import org . rubypeople . rdt . internal . ti . util . OffsetNodeLocator ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . internal . ui . text . ruby . RubyContentAssistInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . RubyCompletionProposalComputer ; import com . aptana . rdt . AptanaRDTPlugin ; public class HashKeyHeuristicProposalComputer extends RubyCompletionProposalComputer { public HashKeyHeuristicProposalComputer ( ) { super ( ) ; } @ Override protected List < CompletionProposal > doComputeCompletionProposals ( RubyContentAssistInvocationContext context , IProgressMonitor monitor ) { return computeHashKeySuggestions ( ) ; } private List < CompletionProposal > computeHashKeySuggestions ( ) { List < CompletionProposal > proposals = new ArrayList < CompletionProposal > ( ) ; String methodCall = getMethodName ( ) ; String args = getArgumentsToMethodCall ( ) ; int argIndex = calculateArgIndex ( args ) ; List < IRubyElement > methods = search ( IRubyElement . METHOD , methodCall , IRubySearchConstants . DECLARATIONS , SearchPattern . R_EXACT_MATCH ) ; for ( IRubyElement element : methods ) { IMethod method = ( IMethod ) element ; try { String [ ] parameters = method . getParameterNames ( ) ; if ( parameters == null || parameters . length == ) continue ; if ( parameters . length <= argIndex ) { argIndex = parameters . length - ; } String param = parameters [ argIndex ] ; if ( ! param . endsWith ( "" ) ) continue ; RootNode ast = ASTProvider . getASTProvider ( ) . getAST ( method . getRubyScript ( ) , ASTProvider . WAIT_YES , new NullProgressMonitor ( ) ) ; Node methodDefNode = OffsetNodeLocator . Instance ( ) . getNodeAtOffset ( ast , method . getSourceRange ( ) . getOffset ( ) ) ; String variableName = param . substring ( , param . indexOf ( '' ) ) ; ValidOptionVisitor visitor = new ValidOptionVisitor ( variableName ) ; methodDefNode . accept ( visitor ) ; Set < String > options = visitor . getValidOptions ( ) ; for ( String option : options ) { CompletionProposal proposal = new CompletionProposal ( CompletionProposal . KEYWORD , option , ) ; proposal . setName ( option ) ; int start = fContext . getInvocationOffset ( ) ; proposal . setReplaceRange ( start , start + option . length ( ) ) ; proposals . add ( proposal ) ; } } catch ( RubyModelException e ) { AptanaRDTPlugin . log ( e ) ; } } return proposals ; } protected List < IRubyElement > search ( int type , String patternString , int limitTo , int matchRule ) { List < IRubyElement > elements = new ArrayList < IRubyElement > ( ) ; try { SearchEngine engine = new SearchEngine ( ) ; SearchPattern pattern = SearchPattern . createPattern ( type , patternString , limitTo , matchRule ) ; SearchParticipant [ ] participants = new SearchParticipant [ ] { SearchEngine . getDefaultSearchParticipant ( ) } ; IRubySearchScope scope = null ; if ( fContext . getRubyScript ( ) == null ) { scope = SearchEngine . createWorkspaceScope ( ) ; } else { scope = SearchEngine . createRubySearchScope ( new IRubyElement [ ] { fContext . getRubyScript ( ) . getRubyProject ( ) } ) ; } CollectingSearchRequestor requestor = new CollectingSearchRequestor ( ) ; engine . search ( pattern , participants , scope , requestor , new NullProgressMonitor ( ) ) ; List < SearchMatch > matches = requestor . getResults ( ) ; for ( SearchMatch match : matches ) { elements . add ( ( IRubyElement ) match . getElement ( ) ) ; } } catch ( CoreException e ) { AptanaRDTPlugin . log ( e ) ; } return elements ; } private String getArgumentsToMethodCall ( ) { String prefix = getStatementPrefix ( ) ; String methodCall = getMethodName ( ) ; String args = prefix . trim ( ) . substring ( methodCall . length ( ) ) ; if ( args . startsWith ( "" ) ) args = args . substring ( ) ; return args ; } private String getMethodName ( ) { String prefix = getStatementPrefix ( ) ; String methodCall = prefix . trim ( ) ; int space = methodCall . indexOf ( "" ) ; if ( space != - ) { methodCall = methodCall . substring ( , space ) ; } space = methodCall . indexOf ( "" ) ; if ( space != - ) { methodCall = methodCall . substring ( , space ) ; } return methodCall ; } private String getStatementPrefix ( ) { try { return fContext . computeStatementPrefix ( ) . toString ( ) ; } catch ( BadLocationException e ) { AptanaRDTPlugin . log ( e ) ; return "" ; } } private int calculateArgIndex ( String prefix ) { String [ ] args = prefix . split ( "" ) ; if ( args . length == ) { if ( prefix . indexOf ( "" ) == - ) return ; return ; } return args . length ; } private static class ValidOptionVisitor extends InOrderVisitor { private Set < String > options = new HashSet < String > ( ) ; private String variableName ; private boolean stringify = false ; public ValidOptionVisitor ( String variableName ) { this . variableName = variableName ; } public Set < String > getValidOptions ( ) { if ( stringify ) { Set < String > symbols = new HashSet < String > ( ) ; for ( String option : options ) { if ( option . startsWith ( "" ) || option . startsWith ( "" ) ) { symbols . add ( "" + option . substring ( , option . length ( ) - ) + "" ) ; } } return symbols ; } return options ; } @ Override public Object visitCallNode ( CallNode iVisited ) { String methodName = iVisited . getName ( ) ; if ( methodName . equals ( "" ) ) { Node receiver = iVisited . getReceiverNode ( ) ; if ( ASTUtil . getNameReflectively ( receiver ) . equals ( variableName ) ) { ArrayNode arguments = ( ArrayNode ) iVisited . getArgsNode ( ) ; Node arg = arguments . get ( ) ; String value = ASTUtil . stringRepresentation ( arg ) ; if ( value != null ) { options . add ( value + "" ) ; } } } else if ( methodName . equals ( "" ) ) { Node receiver = iVisited . getReceiverNode ( ) ; if ( ASTUtil . getNameReflectively ( receiver ) . equals ( variableName ) ) { stringify = true ; } } return super . visitCallNode ( iVisited ) ; } } } package com . aptana . rdt . internal . ui . text . correction ; import java . util . Collection ; import org . eclipse . swt . graphics . Image ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . correction . CorrectionProposal ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class LocalCorrectionsSubProcessor { public static void addReplacementProposal ( String replacement , String display , IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) { addReplacementProposal ( problem . getOffset ( ) , problem . getLength ( ) , replacement , display , proposals ) ; } public static void addReplacementProposal ( int offset , int length , String replacement , String display , Collection < IRubyCompletionProposal > proposals ) { Image image = RubyUI . getSharedImages ( ) . getImage ( org . rubypeople . rdt . ui . ISharedImages . IMG_OBJS_CORRECTION_CHANGE ) ; CorrectionProposal proposal = new CorrectionProposal ( replacement , offset , length , image , display , ) ; proposals . add ( proposal ) ; } } package com . aptana . rdt . internal . ui . text . correction ; import org . eclipse . jface . text . IDocument ; import org . rubypeople . rdt . refactoring . action . RefactoringAction ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . RubyRefactoring ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalRefactoring ; import org . rubypeople . rdt . ui . RubyUI ; import org . rubypeople . rdt . ui . text . correction . ChangeCorrectionProposal ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; public class RefactoringCorrectionProposal extends ChangeCorrectionProposal { private IProblemLocation problem ; private String name ; public RefactoringCorrectionProposal ( String name , Class < ? extends RubyRefactoring > refactoringClass , IProblemLocation problem ) { super ( name , null , , RubyUI . getSharedImages ( ) . getImage ( org . rubypeople . rdt . ui . ISharedImages . IMG_OBJS_CORRECTION_CHANGE ) ) ; this . problem = problem ; this . name = name ; } @ Override public void apply ( IDocument document ) { IRefactoringContext provider = new RefactoringContext ( problem . getOffset ( ) , problem . getOffset ( ) + problem . getLength ( ) , problem . getOffset ( ) , null ) ; RefactoringAction action = new RefactoringAction ( RenameLocalRefactoring . class , name , provider ) ; action . run ( ) ; } } package com . aptana . rdt . internal . ui . text . correction ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; import org . rubypeople . rdt . ui . text . ruby . IQuickAssistProcessor ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; public class QuickAssistProcessor implements IQuickAssistProcessor { public IRubyCompletionProposal [ ] getAssists ( IInvocationContext context , IProblemLocation [ ] locations ) throws CoreException { if ( ! hasAssists ( context ) ) return new IRubyCompletionProposal [ ] ; IRubyCompletionProposal modifier = new StatementModifierAssist ( context ) ; return new IRubyCompletionProposal [ ] { modifier } ; } public boolean hasAssists ( IInvocationContext context ) throws CoreException { return StatementModifierAssist . enabled ( context ) ; } } package com . aptana . rdt . internal . ui . text . correction ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashSet ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . ModuleNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . core . formatter . EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . FormatHelper ; import org . rubypeople . rdt . core . formatter . Indents ; import org . rubypeople . rdt . core . formatter . ReWriteVisitor ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . internal . ti . util . ClosestSpanningNodeLocator ; import org . rubypeople . rdt . internal . ti . util . INodeAcceptor ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . refactoring . core . NodeFactory ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalRefactoring ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IProblemLocation ; import org . rubypeople . rdt . ui . text . ruby . IQuickFixProcessor ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; import com . aptana . rdt . IProblem ; import com . aptana . rdt . ui . AptanaRDTUIPlugin ; public class QuickFixProcessor implements IQuickFixProcessor { private static final String NEWLINE = "" ; public IRubyCompletionProposal [ ] getCorrections ( IInvocationContext context , IProblemLocation [ ] locations ) throws CoreException { if ( locations == null || locations . length == ) { return null ; } HashSet < Integer > handledProblems = new HashSet < Integer > ( locations . length ) ; ArrayList < IRubyCompletionProposal > resultingCollections = new ArrayList < IRubyCompletionProposal > ( ) ; for ( int i = ; i < locations . length ; i ++ ) { IProblemLocation curr = locations [ i ] ; Integer id = Integer . valueOf ( curr . getProblemId ( ) ) ; if ( handledProblems . add ( id ) ) { process ( context , curr , resultingCollections ) ; } } return ( IRubyCompletionProposal [ ] ) resultingCollections . toArray ( new IRubyCompletionProposal [ resultingCollections . size ( ) ] ) ; } public boolean hasCorrections ( IRubyScript unit , int problemId ) { switch ( problemId ) { case IProblem . MisspelledConstructor : case IProblem . ConstantNamingConvention : case IProblem . MethodMissingWithoutRespondTo : case IProblem . LocalAndMethodNamingConvention : case IProblem . ComparableInclusionMissingCompareMethod : case IProblem . EnumerableInclusionMissingEachMethod : case IProblem . PossibleAccidentalBooleanAssignment : case IProblem . DeprecatedRequireGem : case IProblem . DynamicVariableAliasesLocal : return true ; default : return false ; } } private void process ( IInvocationContext context , final IProblemLocation problem , Collection < IRubyCompletionProposal > proposals ) throws CoreException { int id = problem . getProblemId ( ) ; if ( id == ) { return ; } switch ( id ) { case IProblem . DeprecatedRequireGem : LocalCorrectionsSubProcessor . addReplacementProposal ( problem . getOffset ( ) , "" . length ( ) , "" , "" , proposals ) ; break ; case IProblem . MisspelledConstructor : LocalCorrectionsSubProcessor . addReplacementProposal ( "" , "" , problem , proposals ) ; break ; case IProblem . ConstantNamingConvention : String constName = getProblemSource ( context , problem ) ; String fixed = Util . camelCaseToUnderscores ( constName ) . toUpperCase ( ) ; LocalCorrectionsSubProcessor . addReplacementProposal ( fixed , "" , problem , proposals ) ; break ; case IProblem . LocalVariablePossibleAttributeAccess : String local = getProblemSource ( context , problem ) ; fixed = "" + local ; LocalCorrectionsSubProcessor . addReplacementProposal ( fixed , "" + fixed + "" , problem , proposals ) ; RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal ( "" , RenameLocalRefactoring . class , problem ) ; proposals . add ( proposal ) ; break ; case IProblem . LocalAndMethodNamingConvention : String name = getProblemSource ( context , problem ) ; fixed = Util . camelCaseToUnderscores ( name ) . toLowerCase ( ) ; LocalCorrectionsSubProcessor . addReplacementProposal ( fixed , "" , problem , proposals ) ; break ; case IProblem . MethodMissingWithoutRespondTo : int offset = getOffsetOfFirstLineInsideType ( context , problem ) ; String text = insertedMethodText ( context , offset , "" , new String [ ] { "" , "" } ) ; LocalCorrectionsSubProcessor . addReplacementProposal ( offset , , text , "" , proposals ) ; break ; case IProblem . ComparableInclusionMissingCompareMethod : offset = getOffsetOfFirstLineInsideType ( context , problem ) ; text = insertedMethodText ( context , offset , "" , new String [ ] { "" } ) ; LocalCorrectionsSubProcessor . addReplacementProposal ( offset , , text , "" , proposals ) ; break ; case IProblem . EnumerableInclusionMissingEachMethod : offset = getOffsetOfFirstLineInsideType ( context , problem ) ; text = insertedMethodText ( context , offset , "" , new String [ ] { } ) ; LocalCorrectionsSubProcessor . addReplacementProposal ( offset , , text , "" , proposals ) ; break ; case IProblem . PossibleAccidentalBooleanAssignment : name = getProblemSource ( context , problem ) ; fixed = name . replace ( "" , "" ) ; LocalCorrectionsSubProcessor . addReplacementProposal ( fixed , "" , problem , proposals ) ; break ; case IProblem . DynamicVariableAliasesLocal : RefactoringCorrectionProposal prop = new RefactoringCorrectionProposal ( "" , RenameLocalRefactoring . class , problem ) ; proposals . add ( prop ) ; default : } } private String insertedMethodText ( IInvocationContext context , int offset , String methodName , String [ ] args ) { IRubyScript script = context . getRubyScript ( ) ; String src = "" ; try { src = script . getSource ( ) ; } catch ( RubyModelException e ) { AptanaRDTUIPlugin . log ( e ) ; } DefnNode methodNode = NodeFactory . createMethodNode ( methodName , args , null ) ; Node insert = NodeFactory . createBlockNode ( true , NodeFactory . createNewLineNode ( methodNode ) ) ; String text = ReWriteVisitor . createCodeFromNode ( insert , src , getFormatHelper ( ) ) ; StringBuffer buffer = new StringBuffer ( text ) ; int index = text . indexOf ( NEWLINE , ) ; buffer . insert ( index + , "" ) ; String indent = findIndent ( offset , script , src ) ; buffer . insert ( , indent ) ; buffer . append ( NEWLINE ) ; text = buffer . toString ( ) ; text = text . replaceAll ( "" , NEWLINE + indent ) ; return text ; } private String findIndent ( int offset , IRubyScript script , String src ) { if ( src == null || src . length ( ) == ) return "" ; int index = src . indexOf ( NEWLINE , offset ) ; if ( index < || index > src . length ( ) ) return "" ; String line = src . substring ( , index ) ; index = line . lastIndexOf ( NEWLINE ) ; Map options = script . getRubyProject ( ) . getOptions ( true ) ; if ( index == - || ( ( index + ) >= line . length ( ) ) ) return Indents . extractIndentString ( line , options ) ; line = line . substring ( index + ) ; return Indents . extractIndentString ( line , options ) ; } private int getOffsetOfFirstLineInsideType ( IInvocationContext context , IProblemLocation problem ) { IRubyScript script = context . getRubyScript ( ) ; int offset = - ; Node rootNode = ASTProvider . getASTProvider ( ) . getAST ( script , ASTProvider . WAIT_YES , null ) ; Node typeNode = ClosestSpanningNodeLocator . Instance ( ) . findClosestSpanner ( rootNode , problem . getOffset ( ) , new INodeAcceptor ( ) { public boolean doesAccept ( Node node ) { return node instanceof ClassNode || node instanceof ModuleNode ; } } ) ; if ( typeNode instanceof ClassNode ) { ClassNode classNode = ( ClassNode ) typeNode ; offset = classNode . getBodyNode ( ) . getPosition ( ) . getStartOffset ( ) ; } else if ( typeNode instanceof ModuleNode ) { ModuleNode classNode = ( ModuleNode ) typeNode ; offset = classNode . getBodyNode ( ) . getPosition ( ) . getStartOffset ( ) ; } return offset ; } private String getProblemSource ( IInvocationContext context , IProblemLocation problem ) throws RubyModelException { IRubyScript script = context . getRubyScript ( ) ; String src = script . getSource ( ) ; return src . substring ( problem . getOffset ( ) , problem . getOffset ( ) + problem . getLength ( ) ) ; } protected FormatHelper getFormatHelper ( ) { EditableFormatHelper helper = new EditableFormatHelper ( ) ; helper . setAlwaysParanthesizeMethodCalls ( true ) ; helper . setAlwaysParanthesizeMethodDefs ( true ) ; return helper ; } } package com . aptana . rdt . internal . ui . text . correction ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . IContextInformation ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . jruby . ast . IfNode ; import org . jruby . ast . Node ; import org . rubypeople . rdt . ui . text . ruby . IInvocationContext ; import org . rubypeople . rdt . ui . text . ruby . IRubyCompletionProposal ; import com . aptana . rdt . AptanaRDTPlugin ; public class StatementModifierAssist implements IRubyCompletionProposal { private static final String UNLESS = "" ; private static final String IF = "" ; private IInvocationContext context ; public StatementModifierAssist ( IInvocationContext context ) { this . context = context ; } public int getRelevance ( ) { return ; } public void apply ( IDocument document ) { try { IfNode ifNode = ( IfNode ) context . getCoveredNode ( ) ; String conditionText = getConditionText ( document , ifNode . getCondition ( ) ) ; Node statement = getStatement ( ) ; String statementText = document . get ( statement . getPosition ( ) . getStartOffset ( ) , getLength ( statement ) ) . trim ( ) ; String replacement = statementText + getModifierText ( ) + conditionText ; int start = ifNode . getPosition ( ) . getStartOffset ( ) ; int length = ifNode . getPosition ( ) . getEndOffset ( ) - start ; document . replace ( start , length , replacement ) ; } catch ( BadLocationException e ) { AptanaRDTPlugin . log ( e ) ; } } private Node getStatement ( ) { IfNode ifNode = ( IfNode ) context . getCoveredNode ( ) ; if ( isUnless ( context ) ) return ifNode . getElseBody ( ) ; return ifNode . getThenBody ( ) ; } private String getModifierText ( ) { String modifier = "" ; if ( isUnless ( context ) ) modifier += UNLESS ; else modifier += IF ; modifier += "" ; return modifier ; } private String getConditionText ( IDocument document , Node node ) throws BadLocationException { return document . get ( node . getPosition ( ) . getStartOffset ( ) , getLength ( node ) ) . trim ( ) ; } private int getLength ( Node node ) { int start = node . getPosition ( ) . getStartOffset ( ) ; return node . getPosition ( ) . getEndOffset ( ) - start ; } public String getAdditionalProposalInfo ( ) { return null ; } public IContextInformation getContextInformation ( ) { return null ; } public String getDisplayString ( ) { return "" ; } public Image getImage ( ) { return null ; } public Point getSelection ( IDocument document ) { return null ; } public static boolean enabled ( IInvocationContext context ) { Node covered = context . getCoveredNode ( ) ; if ( ! ( covered instanceof IfNode ) ) return false ; IfNode ifNode = ( IfNode ) covered ; if ( isUnless ( context ) ) return ifNode . getThenBody ( ) == null ; return ifNode . getElseBody ( ) == null ; } private static boolean isUnless ( IInvocationContext context ) { IfNode ifNode = ( IfNode ) context . getCoveredNode ( ) ; try { String src = context . getRubyScript ( ) . getSource ( ) . substring ( ifNode . getPosition ( ) . getStartOffset ( ) , ifNode . getPosition ( ) . getEndOffset ( ) ) ; return src . startsWith ( UNLESS ) ; } catch ( Exception e ) { } return false ; } } package com . aptana . rdt . internal . ui . rspec ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyOutlinePage ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . rubyeditor . ICustomRubyOutlinePage ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; import com . aptana . rdt . core . rspec . Behavior ; import com . aptana . rdt . core . rspec . Example ; import com . aptana . rdt . core . rspec . RSpecStructureCreator ; import com . aptana . rdt . ui . AptanaRDTUIPlugin ; public class RSpecOutlinePage extends RubyOutlinePage implements ICustomRubyOutlinePage { private static final String SPEC_FILENAME_SUFFIX = "" ; protected ITreeContentProvider getContentProvider ( ) { return new RSpecChildrenProvider ( ) ; } @ Override protected IBaseLabelProvider getLabelProvider ( ) { return new LabelProvider ( ) { public String getText ( Object element ) { if ( element instanceof Example ) { return ( ( Example ) element ) . getDescription ( ) ; } if ( element instanceof Behavior ) { return ( ( Behavior ) element ) . getClassName ( ) ; } if ( element instanceof IRubyElement ) { return RubyElementLabels . getTextLabel ( element , ) ; } return super . getText ( element ) ; } public Image getImage ( Object element ) { ImageDescriptorRegistry registry = RubyPlugin . getImageDescriptorRegistry ( ) ; ImageDescriptor descriptor = null ; if ( element instanceof Example ) { descriptor = RubyElementImageProvider . getMethodImageDescriptor ( ) ; } else if ( element instanceof Behavior ) { descriptor = RubyElementImageProvider . getTypeImageDescriptor ( false , false , false ) ; } else if ( element instanceof IRubyElement ) { descriptor = new RubyElementImageProvider ( ) . getRubyImageDescriptor ( ( IRubyElement ) element , ) ; } if ( descriptor != null ) { return registry . get ( descriptor ) ; } return super . getImage ( element ) ; } } ; } class RSpecChildrenProvider extends ChildrenProvider { public Object [ ] getElements ( Object inputElement ) { IRubyScript script = ( IRubyScript ) inputElement ; RootNode root = ASTProvider . getASTProvider ( ) . getAST ( script , ASTProvider . WAIT_YES , new NullProgressMonitor ( ) ) ; RSpecStructureCreator rspecCreator = new RSpecStructureCreator ( ) ; rspecCreator . acceptNode ( root ) ; Object [ ] behaviors = rspecCreator . getBehaviors ( ) ; Object [ ] all = new Object [ behaviors . length + ] ; all [ ] = script . getImportContainer ( ) ; System . arraycopy ( behaviors , , all , , behaviors . length ) ; return all ; } public boolean hasChildren ( Object element ) { if ( element instanceof IRubyScript ) return true ; if ( element instanceof Behavior ) return true ; if ( element instanceof Example ) return false ; if ( element instanceof IImportContainer ) return true ; return false ; } public Object getParent ( Object element ) { if ( element instanceof IRubyScript ) return null ; if ( element instanceof Example ) return ( ( Example ) element ) . getBehavior ( ) ; return null ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof Behavior ) return ( ( Behavior ) parentElement ) . getExamples ( ) ; try { if ( parentElement instanceof IParent ) return ( ( IParent ) parentElement ) . getChildren ( ) ; } catch ( RubyModelException e ) { AptanaRDTUIPlugin . log ( e ) ; } return new Object [ ] ; } } public boolean isEnabled ( IRubyElement inputElement ) { if ( inputElement == null ) return false ; IPath path = inputElement . getPath ( ) ; if ( path == null ) return false ; String name = path . lastSegment ( ) ; return name . endsWith ( SPEC_FILENAME_SUFFIX ) ; } } package com . aptana . rdt . internal . ui . preferences ; import org . eclipse . osgi . util . NLS ; public class PreferencesMessages extends NLS { private static final String BUNDLE_NAME = PreferencesMessages . class . getName ( ) ; public static String LicenseConfigurationBlock_company_name_label ; public static String LicenseConfigurationBlock_email_label ; public static String LicenseConfigurationBlock_description ; public static String LicenseConfigurationBlock_license_key_label ; public static String LicenseConfigurationBlock_valid_license_label ; public static String LicenseConfigurationBlock_invalid_license_label ; static { NLS . initializeMessages ( BUNDLE_NAME , PreferencesMessages . class ) ; } } package com . aptana . rdt . internal . ui . preferences ; import org . eclipse . core . runtime . preferences . AbstractPreferenceInitializer ; import org . eclipse . core . runtime . preferences . DefaultScope ; import com . aptana . rdt . ui . AptanaRDTUIPlugin ; import com . aptana . rdt . ui . preferences . IPreferenceConstants ; public class PreferenceInitializer extends AbstractPreferenceInitializer { @ Override public void initializeDefaultPreferences ( ) { new DefaultScope ( ) . getNode ( AptanaRDTUIPlugin . PLUGIN_ID ) . putBoolean ( IPreferenceConstants . PROMPT_TO_AUTO_INSTALL_GEMS , true ) ; } } package com . aptana . rdt . internal . ui . preferences ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . eclipse . jface . preference . BooleanFieldEditor ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . jface . preference . FileFieldEditor ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . StringButtonFieldEditor ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . rubypeople . rdt . ui . EclipsePreferencesAdapter ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . ui . AptanaRDTUIPlugin ; import com . aptana . rdt . ui . preferences . IPreferenceConstants ; public class GemPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { private FileFieldEditor gemScriptEditor ; private EclipsePreferencesAdapter store ; public GemPreferencePage ( ) { super ( GRID ) ; setPreferenceStore ( AptanaRDTUIPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; setDescription ( "" ) ; } public void createFieldEditors ( ) { gemScriptEditor = new FileFieldEditor ( com . aptana . rdt . core . preferences . IPreferenceConstants . GEM_SCRIPT_PATH , "" , true , StringButtonFieldEditor . VALIDATE_ON_KEY_STROKE , getFieldEditorParent ( ) ) ; addField ( gemScriptEditor ) ; addField ( new BooleanFieldEditor ( IPreferenceConstants . PROMPT_TO_AUTO_INSTALL_GEMS , "" , getFieldEditorParent ( ) ) ) ; } @ Override protected void initialize ( ) { super . initialize ( ) ; store = new EclipsePreferencesAdapter ( new InstanceScope ( ) , AptanaRDTPlugin . PLUGIN_ID ) ; gemScriptEditor . setPreferenceStore ( store ) ; gemScriptEditor . load ( ) ; } @ Override public boolean performOk ( ) { boolean ret = super . performOk ( ) ; store . flush ( ) ; store = null ; return ret ; } public void init ( IWorkbench workbench ) { } } package com . aptana . rdt . internal . ui . preferences ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . eclipse . jface . preference . BooleanFieldEditor ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . jface . preference . IntegerFieldEditor ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . util . CoreUtility ; import org . rubypeople . rdt . ui . EclipsePreferencesAdapter ; import com . aptana . rdt . AptanaRDTPlugin ; public class DuplicateCodePreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public DuplicateCodePreferencePage ( ) { super ( GRID ) ; setPreferenceStore ( new EclipsePreferencesAdapter ( new InstanceScope ( ) , AptanaRDTPlugin . PLUGIN_ID ) ) ; setDescription ( "" ) ; } public void createFieldEditors ( ) { addField ( new BooleanFieldEditor ( AptanaRDTPlugin . DUPLICATE_CODE_CHECK_ENABLED , "" , getFieldEditorParent ( ) ) ) ; IntegerFieldEditor intFieldEditor = new IntegerFieldEditor ( AptanaRDTPlugin . DUPLICATE_CODE_MASS_THRESHOLD , "" , getFieldEditorParent ( ) ) ; intFieldEditor . setValidRange ( , ) ; addField ( intFieldEditor ) ; } public void init ( IWorkbench workbench ) { } @ Override public boolean performOk ( ) { IProject [ ] rubyProjects = RubyCore . getRubyProjects ( ) ; if ( rubyProjects != null ) { for ( IProject project : rubyProjects ) { CoreUtility . startBuildInBackground ( project ) ; } } return super . performOk ( ) ; } } package com . aptana . rdt . ui ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; import org . rubypeople . rdt . core . RubyModelException ; import com . aptana . rdt . internal . ui . GemAutoInstallDialogJob ; public class AptanaRDTUIPlugin extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static AptanaRDTUIPlugin plugin ; public AptanaRDTUIPlugin ( ) { super ( ) ; } public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; scheduleGemAutoInstall ( ) ; } private void scheduleGemAutoInstall ( ) { new GemAutoInstallDialogJob ( ) . schedule ( ) ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static AptanaRDTUIPlugin getDefault ( ) { return plugin ; } public static void log ( RubyModelException e ) { getDefault ( ) . getLog ( ) . log ( e . getStatus ( ) ) ; } } package com . aptana . rdt . ui . gems ; import org . eclipse . jface . action . Action ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IMenuCreator ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . Menu ; import org . rubypeople . rdt . ui . IHasImageDescriptor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . ui . AptanaRDTUIPlugin ; class GemManagerSelectionAction extends Action implements IMenuCreator { private Menu fMenu ; private GemsView gemsView ; GemManagerSelectionAction ( GemsView gemsView ) { this . gemsView = gemsView ; setEnabled ( getGemManagers ( ) . length > ) ; setToolTipText ( "" ) ; setImageDescriptor ( AptanaRDTUIPlugin . imageDescriptorFromPlugin ( AptanaRDTUIPlugin . PLUGIN_ID , "" ) ) ; setMenuCreator ( this ) ; } private IGemManager [ ] getGemManagers ( ) { return AptanaRDTPlugin . getDefault ( ) . getGemManagers ( ) ; } public void dispose ( ) { } public Menu getMenu ( Control parent ) { if ( fMenu != null && ! fMenu . isDisposed ( ) ) { fMenu . dispose ( ) ; } fMenu = new Menu ( parent ) ; int accel = ; IGemManager [ ] gemManagers = getGemManagers ( ) ; for ( IGemManager gemManager : gemManagers ) { String label = gemManager . getName ( ) ; ImageDescriptor image = null ; if ( gemManager instanceof IHasImageDescriptor ) { image = ( ( IHasImageDescriptor ) gemManager ) . getImageDescriptor ( ) ; } addActionToMenu ( fMenu , new GemManagerAction ( label , image , gemManager ) , accel ) ; accel ++ ; } return fMenu ; } public Menu getMenu ( Menu parent ) { return null ; } private void addActionToMenu ( Menu parent , Action action , int accelerator ) { if ( accelerator < ) { StringBuffer label = new StringBuffer ( ) ; label . append ( '' ) ; label . append ( accelerator ) ; label . append ( '' ) ; label . append ( action . getText ( ) ) ; action . setText ( label . toString ( ) ) ; } ActionContributionItem item = new ActionContributionItem ( action ) ; item . fill ( parent , - ) ; } private class GemManagerAction extends Action { private IGemManager gemManager ; public GemManagerAction ( String label , ImageDescriptor image , IGemManager gemManager ) { setText ( label ) ; if ( image != null ) { setImageDescriptor ( image ) ; } this . gemManager = gemManager ; } public void run ( ) { if ( gemsView != null ) { gemsView . setGemManager ( gemManager ) ; } } public void runWithEvent ( Event event ) { run ( ) ; } } } package com . aptana . rdt . ui . gems ; import java . util . HashSet ; import java . util . Set ; import java . util . SortedSet ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . TraverseEvent ; import org . eclipse . swt . events . TraverseListener ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . internal . ui . RubyPluginImages ; import org . rubypeople . rdt . internal . ui . util . CollectionContentProvider ; import org . rubypeople . rdt . ui . TableViewerSorter ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . IGemManager ; import com . aptana . rdt . core . gems . LogicalGem ; public class InstallGemDialog extends Dialog { private static final Gem LOADING_GEM = new Gem ( "" , "" , "" ) { public boolean isInstallable ( ) { return false ; } } ; private Text nameText ; private Combo versionCombo ; private String name ; private String version ; private boolean filterByText = true ; private TableViewer gemViewer ; private IStructuredContentProvider contentProvider ; private Combo sourceURLCombo ; private String sourceURL = IGemManager . DEFAULT_GEM_HOST ; private Set < Gem > gems ; private Job gemJob ; private Button sourceButton ; private Image refreshImage ; public InstallGemDialog ( Shell parentShell ) { super ( parentShell ) ; setShellStyle ( getShellStyle ( ) | SWT . RESIZE ) ; contentProvider = new CollectionContentProvider ( ) ; } protected Control createDialogArea ( Composite parent ) { getShell ( ) . setText ( GemsMessages . InstallGemDialog_dialog_title ) ; Composite control = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; control . setLayout ( layout ) ; Label sourceLabel = new Label ( control , SWT . LEFT ) ; sourceLabel . setText ( "" ) ; sourceURLCombo = new Combo ( control , SWT . DROP_DOWN ) ; GridData sourceTextData = new GridData ( ) ; sourceTextData . widthHint = ; sourceTextData . horizontalSpan = ; sourceURLCombo . setLayoutData ( sourceTextData ) ; updateSourceURLs ( ) ; sourceURLCombo . setText ( sourceURL ) ; sourceURLCombo . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { sourceURL = sourceURLCombo . getText ( ) ; } } ) ; sourceURLCombo . addTraverseListener ( new TraverseListener ( ) { public void keyTraversed ( TraverseEvent e ) { if ( e . keyCode == SWT . CR ) { loadSourceURL ( ) ; e . doit = false ; } } } ) ; sourceButton = new Button ( control , SWT . NONE ) ; sourceButton . setToolTipText ( "" ) ; refreshImage = RubyPluginImages . TOOLBAR_REFRESH . createImage ( ) ; sourceButton . setImage ( refreshImage ) ; sourceButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { loadSourceURL ( ) ; } } ) ; Label nameLabel = new Label ( control , SWT . LEFT ) ; nameLabel . setText ( GemsMessages . InstallGemDialog_name_label ) ; nameText = new Text ( control , SWT . BORDER | SWT . SEARCH ) ; GridData nameTextData = new GridData ( ) ; nameTextData . widthHint = ; nameText . setLayoutData ( nameTextData ) ; nameText . setEnabled ( false ) ; nameText . setMessage ( "" ) ; Label versionLabel = new Label ( control , SWT . RIGHT ) ; versionLabel . setLayoutData ( new GridData ( SWT . RIGHT , SWT . CENTER , false , false ) ) ; versionLabel . setText ( GemsMessages . InstallGemDialog_version_label ) ; versionCombo = new Combo ( control , SWT . DROP_DOWN | SWT . READ_ONLY | SWT . BORDER ) ; GridData versionComboData = new GridData ( ) ; versionComboData . widthHint = ; versionCombo . setLayoutData ( versionComboData ) ; versionCombo . setEnabled ( false ) ; gems = new HashSet < Gem > ( ) ; gems . add ( LOADING_GEM ) ; final Table gemsTable = new Table ( parent , SWT . VIRTUAL | SWT . SINGLE | SWT . FULL_SELECTION ) ; gemsTable . setItemCount ( gems . size ( ) ) ; nameText . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { if ( filterByText ) { getShell ( ) . getDisplay ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { Set < Gem > filtered = filter ( nameText . getText ( ) , gems ) ; gemsTable . setItemCount ( filtered . size ( ) ) ; gemsTable . clearAll ( ) ; gemViewer . setInput ( filtered ) ; } private Set < Gem > filter ( String filter , Set < Gem > gems ) { Set < Gem > filtered = new HashSet < Gem > ( ) ; for ( Gem gem : gems ) { if ( gem . getName ( ) . toLowerCase ( ) . startsWith ( filter ) ) filtered . add ( gem ) ; } return filtered ; } } ) ; } filterByText = true ; } } ) ; gemViewer = new TableViewer ( gemsTable ) ; gemsTable . setHeaderVisible ( true ) ; gemsTable . setLinesVisible ( false ) ; GridData data = new GridData ( GridData . FILL_HORIZONTAL ) ; data . heightHint = ; gemsTable . setLayoutData ( data ) ; TableColumn nameColumn = new TableColumn ( gemsTable , SWT . LEFT ) ; nameColumn . setText ( GemsMessages . GemsView_NameColumn_label ) ; nameColumn . setWidth ( ) ; TableColumn versionColumn = new TableColumn ( gemsTable , SWT . LEFT ) ; versionColumn . setText ( GemsMessages . GemsView_VersionColumn_label ) ; versionColumn . setWidth ( ) ; TableColumn descriptionColumn = new TableColumn ( gemsTable , SWT . LEFT ) ; descriptionColumn . setText ( GemsMessages . GemsView_DescriptionColumn_label ) ; descriptionColumn . setWidth ( ) ; gemViewer . setLabelProvider ( new GemLabelProvider ( ) ) ; gemViewer . setContentProvider ( contentProvider ) ; TableViewerSorter . bind ( gemViewer ) ; gemViewer . setInput ( gems ) ; gemViewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { public void selectionChanged ( SelectionChangedEvent event ) { ISelection selection = event . getSelection ( ) ; if ( selection instanceof IStructuredSelection ) { IStructuredSelection structured = ( IStructuredSelection ) selection ; Gem gem = ( Gem ) structured . getFirstElement ( ) ; if ( gem == null ) { versionCombo . removeAll ( ) ; return ; } filterByText = false ; nameText . setText ( gem . getName ( ) ) ; versionCombo . removeAll ( ) ; String lastVersion = null ; if ( gem instanceof LogicalGem ) { LogicalGem logical = ( LogicalGem ) gem ; SortedSet < String > versions = logical . getVersions ( ) ; for ( String version : versions ) { versionCombo . add ( version ) ; lastVersion = version ; } } else { versionCombo . add ( gem . getVersion ( ) ) ; lastVersion = gem . getVersion ( ) ; } versionCombo . setText ( lastVersion ) ; } } } ) ; setGems ( IGemManager . DEFAULT_GEM_HOST ) ; return control ; } private void updateTable ( ) { gemViewer . setInput ( gems ) ; gemViewer . getTable ( ) . setItemCount ( gems . size ( ) ) ; gemViewer . refresh ( ) ; } protected void setGems ( final String url ) { if ( gemJob != null ) { gemJob . cancel ( ) ; } gemJob = new Job ( "" ) { protected IStatus run ( IProgressMonitor gemJobMonitor ) { if ( gemJobMonitor != null && gemJobMonitor . isCanceled ( ) ) { return Status . CANCEL_STATUS ; } gems = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . getRemoteGems ( url , gemJobMonitor ) ; if ( gemJobMonitor != null && gemJobMonitor . isCanceled ( ) ) { return Status . CANCEL_STATUS ; } UIJob updatingTable = new UIJob ( "" ) { public IStatus runInUIThread ( IProgressMonitor monitor ) { if ( monitor != null && monitor . isCanceled ( ) ) { return Status . CANCEL_STATUS ; } if ( gemViewer != null && ! gemViewer . getTable ( ) . isDisposed ( ) ) { updateTable ( ) ; } if ( nameText != null && ! nameText . isDisposed ( ) ) { nameText . setEnabled ( true ) ; } if ( versionCombo != null && ! versionCombo . isDisposed ( ) ) { versionCombo . setEnabled ( true ) ; } return Status . OK_STATUS ; } } ; updatingTable . schedule ( ) ; return Status . OK_STATUS ; } } ; gemJob . schedule ( ) ; } protected void updateSourceURLs ( ) { sourceURLCombo . removeAll ( ) ; Set < String > urls = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) . getSourceURLs ( ) ; for ( String url : urls ) { sourceURLCombo . add ( url ) ; } } @ Override protected void okPressed ( ) { name = nameText . getText ( ) ; version = versionCombo . getText ( ) ; super . okPressed ( ) ; } public Gem getGem ( ) { return new Gem ( name , version , "" ) ; } public String getSourceURL ( ) { return sourceURL ; } @ Override public boolean close ( ) { if ( refreshImage != null ) refreshImage . dispose ( ) ; return super . close ( ) ; } private void loadSourceURL ( ) { String curr = sourceURLCombo . getText ( ) ; gems = new HashSet < Gem > ( ) ; gems . add ( LOADING_GEM ) ; updateTable ( ) ; nameText . setEnabled ( false ) ; versionCombo . setEnabled ( false ) ; setGems ( sourceURL ) ; updateSourceURLs ( ) ; sourceURLCombo . setText ( curr ) ; } } package com . aptana . rdt . ui . gems ; import org . eclipse . osgi . util . NLS ; public class GemsMessages extends NLS { private static final String BUNDLE_NAME = GemsMessages . class . getName ( ) ; public static String GemsView_NameColumn_label ; public static String GemsView_VersionColumn_label ; public static String GemsView_DescriptionColumn_label ; public static String InstallGemDialog_dialog_title ; public static String InstallGemDialog_version_label ; public static String InstallGemDialog_name_label ; public static String GemManager_loading_local_gems ; public static String GemManager_loading_remote_gems ; public static String RemoveGemDialog_msg ; public static String RemoveGemDialog_dialog_title ; public static String RemoveGemDialog_version_label ; static { NLS . initializeMessages ( BUNDLE_NAME , GemsMessages . class ) ; } } package com . aptana . rdt . ui . gems ; import java . util . List ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; public class RemoveGemDialog extends Dialog { private Combo versionCombo ; private String version ; private List < String > versions ; public RemoveGemDialog ( Shell parentShell , List < String > versions ) { super ( parentShell ) ; this . versions = versions ; } @ Override protected Control createDialogArea ( Composite parent ) { getShell ( ) . setText ( GemsMessages . RemoveGemDialog_dialog_title ) ; Composite control = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = ; control . setLayout ( layout ) ; Label versionLabel = new Label ( control , SWT . LEFT ) ; versionLabel . setText ( GemsMessages . RemoveGemDialog_version_label ) ; versionCombo = new Combo ( control , SWT . DROP_DOWN ) ; GridData versionComboData = new GridData ( ) ; versionComboData . widthHint = ; versionCombo . setLayoutData ( versionComboData ) ; if ( versions != null && ! versions . isEmpty ( ) ) { for ( String version : versions ) { versionCombo . add ( version ) ; } versionCombo . select ( versions . size ( ) - ) ; } return control ; } public void buttonPressed ( int buttonId ) { if ( buttonId == IDialogConstants . OK_ID ) { version = versionCombo . getText ( ) ; okPressed ( ) ; } else if ( buttonId == IDialogConstants . CANCEL_ID ) { cancelPressed ( ) ; } } public String getVersion ( ) { return version ; } } package com . aptana . rdt . ui . gems ; import org . eclipse . jface . viewers . ITableLabelProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import com . aptana . rdt . core . gems . Gem ; public class GemLabelProvider extends LabelProvider implements ITableLabelProvider { private static final int NAME_COLUMN = ; private static final int VERSION_COLUMN = ; private static final int DESCRIPTION_COLUMN = ; public Image getColumnImage ( Object element , int columnIndex ) { return null ; } public String getColumnText ( Object element , int columnIndex ) { Gem server = ( Gem ) element ; switch ( columnIndex ) { case NAME_COLUMN : return server . getName ( ) ; case VERSION_COLUMN : return server . getVersion ( ) ; case DESCRIPTION_COLUMN : return server . getDescription ( ) ; default : return "" ; } } } package com . aptana . rdt . ui . gems ; import java . util . Collections ; import java . util . Set ; import java . util . TreeSet ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IContributionItem ; import org . eclipse . jface . action . IMenuListener ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . jface . viewers . TableViewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . swt . widgets . TableItem ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . part . ViewPart ; import org . rubypeople . rdt . internal . ui . util . CollectionContentProvider ; import org . rubypeople . rdt . ui . TableViewerSorter ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . GemListener ; import com . aptana . rdt . core . gems . IGemManager ; public class GemsView extends ViewPart implements GemListener { private TableViewer gemViewer ; private GemManagerSelectionAction gemManagerSelectionAction ; private IGemManager gemManager ; @ Override public void createPartControl ( Composite parent ) { parent . setLayout ( new GridLayout ( ) ) ; gemViewer = new TableViewer ( parent , SWT . SINGLE | SWT . FULL_SELECTION ) ; final Table gemTable = gemViewer . getTable ( ) ; gemTable . setHeaderVisible ( true ) ; gemTable . setLinesVisible ( true ) ; gemTable . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; gemTable . addKeyListener ( new KeyListener ( ) { public void keyReleased ( KeyEvent e ) { } public void keyPressed ( KeyEvent e ) { if ( e . keyCode == SWT . DEL ) { TableItem item = gemTable . getItem ( gemTable . getSelectionIndex ( ) ) ; final Gem gem = ( Gem ) item . getData ( ) ; if ( MessageDialog . openConfirm ( gemTable . getShell ( ) , null , GemsMessages . bind ( GemsMessages . RemoveGemDialog_msg , gem . getName ( ) ) ) ) { Job job = null ; if ( gem . hasMultipleVersions ( ) ) { final RemoveGemDialog dialog = new RemoveGemDialog ( Display . getDefault ( ) . getActiveShell ( ) , gem . versions ( ) ) ; if ( dialog . open ( ) == RemoveGemDialog . OK ) { job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { return getGemManager ( ) . removeGem ( new Gem ( gem . getName ( ) , dialog . getVersion ( ) , gem . getDescription ( ) ) , monitor ) ; } } ; } } else { job = new Job ( "" ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { return getGemManager ( ) . removeGem ( gem , monitor ) ; } } ; } if ( job != null ) { job . setUser ( true ) ; job . schedule ( ) ; } } } } } ) ; TableColumn nameColumn = new TableColumn ( gemTable , SWT . LEFT ) ; nameColumn . setText ( GemsMessages . GemsView_NameColumn_label ) ; nameColumn . setWidth ( ) ; TableColumn versionColumn = new TableColumn ( gemTable , SWT . LEFT ) ; versionColumn . setText ( GemsMessages . GemsView_VersionColumn_label ) ; versionColumn . setWidth ( ) ; TableColumn descriptionColumn = new TableColumn ( gemTable , SWT . LEFT ) ; descriptionColumn . setText ( GemsMessages . GemsView_DescriptionColumn_label ) ; descriptionColumn . setWidth ( ) ; gemViewer . setLabelProvider ( new GemLabelProvider ( ) ) ; gemViewer . setContentProvider ( new CollectionContentProvider ( ) ) ; TableViewerSorter . bind ( gemViewer ) ; getSite ( ) . setSelectionProvider ( gemViewer ) ; gemViewer . setInput ( getSortedGems ( ) ) ; createPopupMenu ( ) ; getGemManager ( ) . addGemListener ( this ) ; gemManagerSelectionAction = new GemManagerSelectionAction ( this ) ; IActionBars bars = getViewSite ( ) . getActionBars ( ) ; bars . getToolBarManager ( ) . add ( gemManagerSelectionAction ) ; } public IGemManager getGemManager ( ) { if ( gemManager == null ) { gemManager = AptanaRDTPlugin . getDefault ( ) . getGemManager ( ) ; } return gemManager ; } @ Override public void dispose ( ) { getGemManager ( ) . removeGemListener ( this ) ; super . dispose ( ) ; } @ Override public void setFocus ( ) { gemViewer . getTable ( ) . setFocus ( ) ; } private void createPopupMenu ( ) { MenuManager menuMgr = new MenuManager ( "" ) ; menuMgr . setRemoveAllWhenShown ( true ) ; menuMgr . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager manager ) { IContributionItem [ ] items = getViewSite ( ) . getActionBars ( ) . getToolBarManager ( ) . getItems ( ) ; for ( int i = ; i < items . length ; i ++ ) { if ( items [ i ] instanceof ActionContributionItem ) { ActionContributionItem aci = ( ActionContributionItem ) items [ i ] ; manager . add ( aci . getAction ( ) ) ; } } } } ) ; menuMgr . add ( new Separator ( IWorkbenchActionConstants . MB_ADDITIONS ) ) ; Menu menu = menuMgr . createContextMenu ( gemViewer . getControl ( ) ) ; gemViewer . getControl ( ) . setMenu ( menu ) ; getSite ( ) . registerContextMenu ( menuMgr , gemViewer ) ; } public void gemsRefreshed ( ) { doRefresh ( ) ; } public void gemUpdated ( Gem gem ) { } private void doRefresh ( ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { gemViewer . setInput ( getSortedGems ( ) ) ; gemViewer . refresh ( ) ; } } ) ; } private Set < Gem > getSortedGems ( ) { return Collections . unmodifiableSortedSet ( new TreeSet < Gem > ( getGemManager ( ) . getGems ( ) ) ) ; } public void gemAdded ( final Gem gem ) { doRefresh ( ) ; } public void gemRemoved ( final Gem gem ) { doRefresh ( ) ; } public void managerInitialized ( ) { } public void setGemManager ( IGemManager gemManager ) { this . gemManager = gemManager ; doRefresh ( ) ; } } package com . aptana . rdt . ui . preferences ; public interface IPreferenceConstants { public static final String PROMPT_TO_AUTO_INSTALL_GEMS = "" ; } package com . aptana . rdt . ui ; import java . net . MalformedURLException ; import java . net . URL ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . browser . IWebBrowser ; import org . eclipse . ui . browser . IWorkbenchBrowserSupport ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . ui . progress . UIJob ; import org . rubypeople . rdt . core . RubyCore ; public abstract class BrowserView extends ViewPart { public BrowserView ( ) { super ( ) ; } @ Override public void createPartControl ( Composite parent ) { try { IWorkbenchBrowserSupport browserSupport = PlatformUI . getWorkbench ( ) . getBrowserSupport ( ) ; IWebBrowser browser = browserSupport . getExternalBrowser ( ) ; browser . openURL ( new URL ( getURL ( ) ) ) ; } catch ( PartInitException e ) { RubyCore . log ( e ) ; } catch ( MalformedURLException e ) { RubyCore . log ( e ) ; } final ViewPart self = this ; Job job = new UIJob ( "" ) { @ Override public IStatus runInUIThread ( IProgressMonitor monitor ) { self . getSite ( ) . getPage ( ) . hideView ( self ) ; self . dispose ( ) ; return Status . OK_STATUS ; } } ; job . setSystem ( true ) ; job . setPriority ( Job . INTERACTIVE ) ; job . schedule ( ) ; } abstract protected String getURL ( ) ; @ Override public void setFocus ( ) { } } package com . aptana . rdt . internal . rake ; import java . io . File ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceProxy ; import org . eclipse . core . resources . IResourceProxyVisitor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; class RakeFileFinder implements IResourceProxyVisitor { private File workingDirectory ; public boolean visit ( IResourceProxy proxy ) throws CoreException { if ( proxy . getType ( ) == IResource . FILE ) { IPath path = proxy . requestFullPath ( ) ; if ( path . lastSegment ( ) . equalsIgnoreCase ( "" ) ) { workingDirectory = path . removeLastSegments ( ) . toFile ( ) ; } } return workingDirectory == null && ( proxy . getType ( ) == IResource . FOLDER || proxy . getType ( ) == IResource . PROJECT || proxy . getType ( ) == IResource . ROOT ) ; } public File getWorkingDirectory ( ) { return workingDirectory ; } } package com . aptana . rdt . internal . rake ; import java . util . ArrayList ; import java . util . List ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . IArgumentNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . StrNode ; import org . rubypeople . rdt . internal . core . parser . InOrderVisitor ; import org . rubypeople . rdt . internal . core . util . ASTUtil ; public class RakeStructureCreator extends InOrderVisitor { private static final String TASK = "" ; private static final String NAMESPACE = "" ; private List < Namespace > namespaces = new ArrayList < Namespace > ( ) ; public Object visitFCallNode ( FCallNode visited ) { if ( visited . getName ( ) . equals ( TASK ) ) { String name = getFirstArgument ( visited ) ; Task task = new Task ( name , getStart ( visited ) , getLength ( visited ) ) ; Namespace curNamespace = namespaces . get ( namespaces . size ( ) - ) ; curNamespace . addChild ( task ) ; } else if ( visited . getName ( ) . equals ( NAMESPACE ) ) { String namespaceName = getFirstArgument ( visited ) ; Namespace namespace = new Namespace ( namespaceName , getStart ( visited ) , getLength ( visited ) ) ; Namespace curNamespace = namespaces . get ( namespaces . size ( ) - ) ; curNamespace . addChild ( namespace ) ; namespaces . add ( namespace ) ; Object ins = super . visitFCallNode ( visited ) ; namespaces . remove ( namespaces . size ( ) - ) ; return ins ; } return super . visitFCallNode ( visited ) ; } public Object visitCallNode ( CallNode visited ) { if ( visited . getName ( ) . equals ( "" ) ) { String receiver = ASTUtil . stringRepresentation ( visited . getReceiverNode ( ) ) ; if ( receiver . equals ( "" ) || receiver . equals ( "" ) ) { String name = getFirstArgument ( visited ) ; Task task = new Task ( name , getStart ( visited ) , getLength ( visited ) ) ; Namespace curNamespace = namespaces . get ( namespaces . size ( ) - ) ; curNamespace . addChild ( task ) ; } } return super . visitCallNode ( visited ) ; } private String getFirstArgument ( IArgumentNode visited ) { List < String > args = ASTUtil . getArgumentsFromFunctionCall ( visited ) ; Node arguments = visited . getArgsNode ( ) ; String name = args . get ( ) ; if ( arguments instanceof ArrayNode ) { ArrayNode array = ( ArrayNode ) arguments ; Node firstArg = array . get ( ) ; if ( firstArg instanceof HashNode ) { HashNode hash = ( HashNode ) firstArg ; Node firstHashMember = hash . getListNode ( ) . get ( ) ; name = ASTUtil . getNameReflectively ( firstHashMember ) ; } if ( firstArg instanceof StrNode ) { name = ( ( StrNode ) firstArg ) . getValue ( ) . toString ( ) ; } else { String newName = ASTUtil . getNameReflectively ( firstArg ) ; if ( newName != null ) { name = newName ; } } } return name ; } public Object visitRootNode ( RootNode visited ) { namespaces . add ( new Namespace ( "" , getStart ( visited ) , getLength ( visited ) ) ) ; return super . visitRootNode ( visited ) ; } private int getLength ( Node visited ) { return getEnd ( visited ) - getStart ( visited ) + ; } private int getEnd ( Node visited ) { return visited . getPosition ( ) . getEndOffset ( ) ; } private int getStart ( Node visited ) { return visited . getPosition ( ) . getStartOffset ( ) ; } public Object [ ] getTasks ( ) { return namespaces . get ( namespaces . size ( ) - ) . getChildren ( ) ; } } package com . aptana . rdt . internal . rake . preferences ; import org . eclipse . jface . preference . FieldEditorPreferencePage ; import org . eclipse . jface . preference . FileFieldEditor ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; import com . aptana . rdt . rake . PreferenceConstants ; import com . aptana . rdt . rake . RakePlugin ; public class ConfigurationPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public ConfigurationPreferencePage ( ) { super ( GRID ) ; setPreferenceStore ( RakePlugin . getDefault ( ) . getPreferenceStore ( ) ) ; StringBuffer desc = new StringBuffer ( ) ; desc . append ( "" ) ; desc . append ( "" ) ; desc . append ( "" ) ; desc . append ( "" ) ; desc . append ( "" ) ; setDescription ( desc . toString ( ) ) ; } protected void createFieldEditors ( ) { addField ( new FileFieldEditor ( PreferenceConstants . PREF_RAKE_PATH , "" , getFieldEditorParent ( ) ) ) ; } public void init ( IWorkbench workbench ) { } } package com . aptana . rdt . internal . rake ; import java . util . ArrayList ; import java . util . List ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . SourceRange ; public class Namespace implements ISourceReference { private List < Object > children = new ArrayList < Object > ( ) ; private String name ; private int offset ; private int length ; public Namespace ( String name , int offset , int length ) { this . name = name ; this . offset = offset ; this . length = length ; } public void addChild ( Object child ) { children . add ( child ) ; } public Object [ ] getChildren ( ) { return children . toArray ( new Object [ children . size ( ) ] ) ; } public String toString ( ) { return name ; } public String getSource ( ) throws RubyModelException { return name ; } public ISourceRange getSourceRange ( ) throws RubyModelException { return new SourceRange ( offset , length ) ; } } package com . aptana . rdt . internal . rake ; import org . rubypeople . rdt . core . ISourceRange ; import org . rubypeople . rdt . core . ISourceReference ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . SourceRange ; public class Task implements ISourceReference { private String className ; private int offset ; private int length ; Task ( String className , int offset , int length ) { this . className = className ; this . offset = offset ; this . length = length ; } public String getName ( ) { return className ; } public String getSource ( ) throws RubyModelException { return getName ( ) ; } public ISourceRange getSourceRange ( ) throws RubyModelException { return new SourceRange ( offset , length ) ; } } package com . aptana . rdt . internal . rake ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . jface . viewers . IBaseLabelProvider ; import org . eclipse . jface . viewers . ITreeContentProvider ; import org . eclipse . jface . viewers . LabelProvider ; import org . eclipse . swt . graphics . Image ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . core . IImportContainer ; import org . rubypeople . rdt . core . ILocalVariable ; import org . rubypeople . rdt . core . IParent ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . RubyBlock ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . rubyeditor . ASTProvider ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyOutlinePage ; import org . rubypeople . rdt . internal . ui . viewsupport . RubyElementImageProvider ; import org . rubypeople . rdt . ui . RubyElementLabels ; import org . rubypeople . rdt . ui . rubyeditor . ICustomRubyOutlinePage ; import org . rubypeople . rdt . ui . viewsupport . ImageDescriptorRegistry ; import com . aptana . rdt . rake . RakePlugin ; public class RakeOutlinePage extends RubyOutlinePage implements ICustomRubyOutlinePage { protected ITreeContentProvider getContentProvider ( ) { return new RakeChildrenProvider ( ) ; } @ Override protected IBaseLabelProvider getLabelProvider ( ) { return new LabelProvider ( ) { public String getText ( Object element ) { if ( element instanceof Task ) { return ( ( Task ) element ) . getName ( ) ; } if ( element instanceof Namespace ) { return ( ( Namespace ) element ) . toString ( ) ; } if ( element instanceof IRubyElement ) { return RubyElementLabels . getTextLabel ( element , ) ; } return super . getText ( element ) ; } public Image getImage ( Object element ) { ImageDescriptorRegistry registry = RubyPlugin . getImageDescriptorRegistry ( ) ; ImageDescriptor descriptor = null ; if ( element instanceof Task ) { descriptor = RakePlugin . imageDescriptorFromPlugin ( RakePlugin . PLUGIN_ID , "" ) ; } else if ( element instanceof Namespace ) { descriptor = RakePlugin . imageDescriptorFromPlugin ( RakePlugin . PLUGIN_ID , "" ) ; } else if ( element instanceof IRubyElement ) { descriptor = new RubyElementImageProvider ( ) . getRubyImageDescriptor ( ( IRubyElement ) element , ) ; } if ( descriptor != null ) { return registry . get ( descriptor ) ; } return super . getImage ( element ) ; } } ; } class RakeChildrenProvider extends ChildrenProvider { public Object [ ] getElements ( Object inputElement ) { IRubyScript script = ( IRubyScript ) inputElement ; RootNode root = ASTProvider . getASTProvider ( ) . getAST ( script , ASTProvider . WAIT_YES , new NullProgressMonitor ( ) ) ; RakeStructureCreator rakeCreator = new RakeStructureCreator ( ) ; rakeCreator . acceptNode ( root ) ; try { Object [ ] tasks = rakeCreator . getTasks ( ) ; Object [ ] scriptChildren = filter ( script . getChildren ( ) ) ; Object [ ] all = new Object [ tasks . length + scriptChildren . length ] ; System . arraycopy ( scriptChildren , , all , , scriptChildren . length ) ; System . arraycopy ( tasks , , all , scriptChildren . length , tasks . length ) ; return all ; } catch ( RubyModelException e ) { RakePlugin . log ( e ) ; } return rakeCreator . getTasks ( ) ; } public boolean hasChildren ( Object element ) { if ( element instanceof IRubyScript ) return true ; if ( element instanceof Namespace ) return true ; if ( element instanceof Task ) return false ; if ( element instanceof IImportContainer ) return true ; return false ; } public Object getParent ( Object element ) { if ( element instanceof IRubyScript ) return null ; return null ; } private Object [ ] filter ( Object [ ] original ) { List < Object > filtered = new ArrayList < Object > ( ) ; for ( int i = ; i < original . length ; i ++ ) { if ( ( original [ i ] instanceof ILocalVariable ) || ( original [ i ] instanceof RubyBlock ) ) { continue ; } filtered . add ( original [ i ] ) ; } return filtered . toArray ( new Object [ filtered . size ( ) ] ) ; } public Object [ ] getChildren ( Object parentElement ) { if ( parentElement instanceof Namespace ) { return ( ( Namespace ) parentElement ) . getChildren ( ) ; } try { if ( parentElement instanceof IParent ) return filter ( ( ( IParent ) parentElement ) . getChildren ( ) ) ; } catch ( RubyModelException e ) { RakePlugin . log ( e ) ; } return new Object [ ] ; } } public boolean isEnabled ( IRubyElement inputElement ) { if ( inputElement == null ) return false ; IPath path = inputElement . getPath ( ) ; if ( path == null ) return false ; String name = path . lastSegment ( ) ; return name . endsWith ( "" ) || name . equals ( "" ) ; } } package com . aptana . rdt . internal . rake ; import java . io . BufferedReader ; import java . io . File ; import java . io . IOException ; import java . io . StringReader ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchManager ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . rake . IRakeHelper ; import com . aptana . rdt . rake . RakePlugin ; public class RakeTasksHelper implements IRakeHelper { private Map < String , String > fCachedTasks ; private IProject fLastProject ; private static RakeTasksHelper fgInstance ; private RakeTasksHelper ( ) { } public static IRakeHelper getInstance ( ) { if ( fgInstance == null ) { fgInstance = new RakeTasksHelper ( ) ; } return fgInstance ; } public void runRakeTask ( IProject project , String task , String parameters , IProgressMonitor monitor ) { if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; if ( monitor . isCanceled ( ) ) return ; try { ILaunchConfiguration config = run ( project , task , parameters ) ; if ( monitor . isCanceled ( ) ) return ; config . launch ( ILaunchManager . RUN_MODE , monitor ) ; } catch ( CoreException e ) { RakePlugin . log ( "" , e ) ; } } public ILaunchConfiguration run ( IProject project , String task , String parameters ) { Map < String , String > envMap = new HashMap < String , String > ( ) ; if ( parameters . contains ( "" ) ) { String value = parameters . substring ( parameters . indexOf ( "" ) + ) ; if ( value . indexOf ( '' ) != - ) { value = value . substring ( , value . indexOf ( '' ) ) ; } envMap . put ( "" , value ) ; } String command = task + "" + parameters ; try { ILaunchConfigurationWorkingCopy wc = RubyRuntime . createBasicLaunch ( RakePlugin . getDefault ( ) . getRakePath ( ) , command , project , getWorkingDirectory ( project ) ) ; Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( IRubyLaunchConfigurationConstants . ATTR_RUBY_COMMAND , "" ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_INSTALL_TYPE_SPECIFIC_ATTRS_MAP , map ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_TERMINAL_COMMAND , "" + command ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_USE_TERMINAL , "" ) ; if ( envMap != null && ! envMap . isEmpty ( ) ) { wc . setAttribute ( ILaunchManager . ATTR_APPEND_ENVIRONMENT_VARIABLES , true ) ; wc . setAttribute ( ILaunchManager . ATTR_ENVIRONMENT_VARIABLES , envMap ) ; } return wc . doSave ( ) ; } catch ( CoreException e ) { RakePlugin . log ( "" , e ) ; } return null ; } private static String getWorkingDirectory ( IProject project ) { if ( project == null ) return null ; try { RakeFileFinder finder = new RakeFileFinder ( ) ; project . accept ( finder , IResource . NONE ) ; File workingDir = finder . getWorkingDirectory ( ) ; if ( workingDir != null ) return workingDir . getAbsolutePath ( ) ; } catch ( CoreException e ) { RakePlugin . log ( e ) ; } return project . getLocation ( ) . toOSString ( ) ; } public Map < String , String > getTasks ( IProject project , IProgressMonitor monitor ) { return getTasks ( project , false , monitor ) ; } public Map < String , String > getTasks ( IProject project , boolean force , IProgressMonitor monitor ) { if ( ! force && projectHasntChanged ( project ) && haveCachedTasks ( ) ) { return fCachedTasks ; } if ( monitor == null ) monitor = new NullProgressMonitor ( ) ; fLastProject = project ; fCachedTasks = null ; try { if ( monitor . isCanceled ( ) ) return Collections . emptyMap ( ) ; BufferedReader bufReader = new BufferedReader ( new StringReader ( getTasksText ( project , getWorkingDirectory ( project ) ) ) ) ; Pattern pat = Pattern . compile ( "" ) ; String line = null ; Map < String , String > tasks = new HashMap < String , String > ( ) ; while ( ( line = bufReader . readLine ( ) ) != null ) { Matcher mat = pat . matcher ( line ) ; if ( mat . matches ( ) ) { tasks . put ( mat . group ( ) , mat . group ( ) ) ; } } if ( tasks . isEmpty ( ) ) return new HashMap < String , String > ( ) ; fCachedTasks = Collections . unmodifiableMap ( tasks ) ; return fCachedTasks ; } catch ( IOException e ) { RakePlugin . log ( "" , e ) ; } return new HashMap < String , String > ( ) ; } private boolean haveCachedTasks ( ) { return ( fCachedTasks != null && ! fCachedTasks . isEmpty ( ) ) ; } private boolean projectHasntChanged ( IProject selected ) { return selected != null && selected . equals ( fLastProject ) ; } private static String getTasksText ( IProject project , String workingDirectory ) { try { String rakePath = RakePlugin . getDefault ( ) . getRakePath ( ) ; if ( project != null && rakePath != null && rakePath . trim ( ) . length ( ) > ) { ILaunchConfigurationWorkingCopy wc = RubyRuntime . createBasicLaunch ( rakePath , "" , project , workingDirectory ) ; File file = getRakeTasksFile ( project ) ; String result = RubyRuntime . launchInBackgroundAndRead ( wc . doSave ( ) , file ) ; if ( result == null ) return "" ; return result ; } } catch ( CoreException e ) { RakePlugin . log ( "" , e ) ; } return "" ; } private static File getRakeTasksFile ( IProject proj ) { File file = RakePlugin . getDefault ( ) . getStateLocation ( ) . append ( "" ) . append ( proj . getName ( ) + "" ) . toFile ( ) ; try { file . getParentFile ( ) . mkdirs ( ) ; file . createNewFile ( ) ; } catch ( IOException e ) { } return file ; } } package com . aptana . rdt . internal . rake . actions ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . action . IContributionItem ; import org . eclipse . jface . action . IMenuCreator ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . swt . events . MenuAdapter ; import org . eclipse . swt . events . MenuEvent ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Menu ; import org . eclipse . swt . widgets . MenuItem ; import org . eclipse . ui . IObjectActionDelegate ; import org . eclipse . ui . IWorkbenchPart ; import com . aptana . rdt . rake . IRakeHelper ; import com . aptana . rdt . rake . RakePlugin ; public class RakeAction implements IObjectActionDelegate , IMenuCreator { private static final String RAKE_NAMESPACE_DELIMETER = "" ; private boolean fFillMenu ; private IAction fDelegateAction ; private IStructuredSelection fSelection ; private HashMap < String , MenuManager > fNamespaces ; private Menu menu ; public RakeAction ( ) { super ( ) ; } public void setActivePart ( IAction action , IWorkbenchPart targetPart ) { } public void run ( IAction action ) { } public void selectionChanged ( IAction action , ISelection selection ) { if ( selection instanceof IStructuredSelection ) { fFillMenu = true ; if ( fDelegateAction != action ) { fDelegateAction = action ; fDelegateAction . setMenuCreator ( this ) ; } fSelection = ( IStructuredSelection ) selection ; action . setEnabled ( true ) ; return ; } action . setEnabled ( false ) ; } public void dispose ( ) { if ( menu != null ) menu . dispose ( ) ; menu = null ; } public Menu getMenu ( Control parent ) { return null ; } public Menu getMenu ( Menu parent ) { menu = new Menu ( parent ) ; menu . addMenuListener ( new MenuAdapter ( ) { public void menuShown ( MenuEvent e ) { if ( fFillMenu ) { Menu m = ( Menu ) e . widget ; MenuItem [ ] items = m . getItems ( ) ; for ( int i = ; i < items . length ; i ++ ) { items [ i ] . dispose ( ) ; } fillMenu ( m ) ; fFillMenu = false ; } } } ) ; return menu ; } protected void fillMenu ( Menu menu ) { if ( fSelection == null ) { return ; } IResource resource = ( IResource ) fSelection . getFirstElement ( ) ; IProject project = resource . getProject ( ) ; Map < String , String > tasks = getRakeHelper ( ) . getTasks ( project , new NullProgressMonitor ( ) ) ; fNamespaces = new HashMap < String , MenuManager > ( ) ; List < String > values = new ArrayList < String > ( tasks . keySet ( ) ) ; Collections . sort ( values ) ; for ( String task : values ) { String [ ] paths = task . split ( RAKE_NAMESPACE_DELIMETER ) ; if ( paths . length == ) { IAction action = new RunRakeAction ( project , task , tasks . get ( task ) ) ; ActionContributionItem item = new ActionContributionItem ( action ) ; item . fill ( menu , - ) ; } else { MenuManager manager = getOrCreate ( paths ) ; manager . add ( new RunRakeAction ( project , task , tasks . get ( task ) ) ) ; } } values = new ArrayList < String > ( fNamespaces . keySet ( ) ) ; Collections . sort ( values ) ; Collections . reverse ( values ) ; for ( String path : values ) { MenuManager manager = fNamespaces . get ( path ) ; String [ ] parts = path . split ( RAKE_NAMESPACE_DELIMETER ) ; if ( parts . length == ) { int index = getInsertIndex ( menu , manager ) ; manager . fill ( menu , index ) ; } else { MenuManager parent = getParent ( parts ) ; if ( parent != null ) { int index = getInsertIndex ( parent , manager ) ; parent . insert ( index , manager ) ; } else { int index = getInsertIndex ( menu , manager ) ; manager . fill ( menu , index ) ; } } } } private int getInsertIndex ( MenuManager parent , MenuManager item ) { if ( parent == null || item == null ) return ; String text = item . getMenuText ( ) ; if ( text == null ) return ; IContributionItem [ ] items = parent . getItems ( ) ; if ( items == null ) return ; int index = ; for ( int i = ; i < items . length ; i ++ ) { if ( items [ i ] == null ) continue ; if ( items [ i ] instanceof ActionContributionItem ) { ActionContributionItem actionItem = ( ActionContributionItem ) items [ i ] ; IAction action = actionItem . getAction ( ) ; if ( action == null ) continue ; String other = action . getText ( ) ; if ( text . compareTo ( other ) >= ) { index = i + ; } else { break ; } } } return index ; } private int getInsertIndex ( Menu parent , MenuManager item ) { String text = item . getMenuText ( ) ; MenuItem [ ] items = parent . getItems ( ) ; int index = ; for ( int i = ; i < items . length ; i ++ ) { String other = items [ i ] . getText ( ) ; if ( text . compareTo ( other ) >= ) { index = i + ; } else { break ; } } return index ; } protected IRakeHelper getRakeHelper ( ) { return RakePlugin . getDefault ( ) . getRakeHelper ( ) ; } private MenuManager getParent ( String [ ] parts ) { String [ ] part = stripLastItem ( parts ) ; return fNamespaces . get ( join ( part ) ) ; } private String join ( String [ ] part ) { StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < part . length ; i ++ ) { if ( i != ) buffer . append ( RAKE_NAMESPACE_DELIMETER ) ; buffer . append ( part [ i ] ) ; } return buffer . toString ( ) ; } private MenuManager getOrCreate ( String [ ] paths ) { String [ ] part = stripLastItem ( paths ) ; MenuManager manager = fNamespaces . get ( join ( part ) ) ; if ( manager == null ) { manager = new MenuManager ( part [ part . length - ] ) ; fNamespaces . put ( join ( part ) , manager ) ; } return manager ; } private String [ ] stripLastItem ( String [ ] paths ) { String [ ] part = new String [ paths . length - ] ; System . arraycopy ( paths , , part , , part . length ) ; return part ; } } package com . aptana . rdt . internal . rake . actions ; import java . text . MessageFormat ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . jface . action . Action ; import com . aptana . rdt . rake . IRakeHelper ; import com . aptana . rdt . rake . RakePlugin ; public class RunRakeAction extends Action { private IProject project ; private String task ; private String description ; public RunRakeAction ( IProject project , String task , String description ) { this . project = project ; this . task = task ; this . description = description ; } @ Override public void run ( ) { Job job = new Job ( MessageFormat . format ( "" , task ) ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { getRakeHelper ( ) . runRakeTask ( project , task , "" , monitor ) ; return Status . OK_STATUS ; } } ; job . setUser ( true ) ; job . schedule ( ) ; } protected IRakeHelper getRakeHelper ( ) { return RakePlugin . getDefault ( ) . getRakeHelper ( ) ; } @ Override public String getText ( ) { String [ ] parts = task . split ( "" ) ; return parts [ parts . length - ] ; } @ Override public String getToolTipText ( ) { return description ; } } package com . aptana . rdt . internal . rake . view ; import java . text . MessageFormat ; import java . util . Collection ; import java . util . Map ; import java . util . TreeSet ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . Preferences . IPropertyChangeListener ; import org . eclipse . core . runtime . Preferences . PropertyChangeEvent ; import org . eclipse . core . runtime . jobs . Job ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . StackLayout ; import org . eclipse . swt . events . DisposeEvent ; import org . eclipse . swt . events . DisposeListener ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . KeyListener ; import org . eclipse . swt . events . MouseAdapter ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . Cursor ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . graphics . Image ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . IActionBars ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . ViewPart ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . ui . RubyExplorerTracker ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . RubyProjectSelectionAction ; import org . rubypeople . rdt . internal . ui . RubyExplorerTracker . IRubyProjectListener ; import org . rubypeople . rdt . internal . ui . text . RubyColorManager ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . rake . IRakeHelper ; import com . aptana . rdt . rake . PreferenceConstants ; import com . aptana . rdt . rake . RakePlugin ; public class RakeTasksView extends ViewPart implements IVMInstallChangedListener , IPropertyChangeListener , IRubyProjectListener { private static final String PROJECT = "" ; private StackLayout fViewLayout ; private Composite fRakeTasksView ; private RubyProjectSelectionAction projectSelectionAction ; private Label fSpecifyRakePath ; private Label fSelectRailsProjectView ; private Composite fParent ; private Composite basicControls ; private Label projectNameLabel ; private Composite tasksComp ; private Label tasksLabel ; private Combo fTasksCombo ; private Label paramLabel ; private Text fParamText ; private Button genButton ; private Label descriptionLabel ; private Label fDescripText ; private RubyColorManager fColorManager ; private Map < String , String > fTasks ; private IProject project ; private Job updateRakeTasksJob ; private Cursor hand ; private Button pretendButton ; private Button quietButton ; private Button backtraceButton ; private Button systemButton ; private Image fRunIcon ; private Image fMaximizeIcon ; private Image fMinimizeIcon ; public RakeTasksView ( ) { super ( ) ; } public void createPartControl ( Composite parent ) { fColorManager = new RubyColorManager ( true ) ; fParent = parent ; hand = new Cursor ( parent . getDisplay ( ) , SWT . CURSOR_HAND ) ; fViewLayout = new StackLayout ( ) ; parent . setLayout ( fViewLayout ) ; fRakeTasksView = new Composite ( parent , SWT . NONE ) ; fRakeTasksView . setLayout ( new GridLayout ( , true ) ) ; fRakeTasksView . setLayoutData ( new GridData ( GridData . FILL_BOTH ) ) ; createRakeControls ( fRakeTasksView ) ; createAdvancedSection ( fRakeTasksView ) ; fSpecifyRakePath = new Label ( parent , SWT . NULL ) ; fSpecifyRakePath . setText ( RakeViewMessages . SpecifyRakePath_message ) ; fSelectRailsProjectView = new Label ( parent , SWT . NULL ) ; fSelectRailsProjectView . setText ( RakeViewMessages . SelectRubyProject_message ) ; if ( emptyRakePath ( ) ) { fViewLayout . topControl = fSpecifyRakePath ; } else { if ( getSelectedRubyProject ( ) != null ) { fViewLayout . topControl = fRakeTasksView ; } else { fViewLayout . topControl = fSelectRailsProjectView ; } } parent . layout ( ) ; getProjectTracker ( ) . addProjectListener ( this ) ; RubyRuntime . addVMInstallChangedListener ( this ) ; RakePlugin . getDefault ( ) . getPluginPreferences ( ) . addPropertyChangeListener ( this ) ; projectSelectionAction = new RubyProjectSelectionAction ( ) ; projectSelectionAction . setListener ( this ) ; IActionBars bars = getViewSite ( ) . getActionBars ( ) ; bars . getToolBarManager ( ) . add ( projectSelectionAction ) ; IProject project = getProjectTracker ( ) . getSelectedRubyProject ( ) ; IProject [ ] projects = RubyCore . getRubyProjects ( ) ; if ( project != null ) { this . projectSelected ( project ) ; } else if ( projects != null && projects . length > ) { this . projectSelected ( projects [ ] ) ; } } protected Composite createRakeControls ( Composite parent ) { basicControls = new Composite ( parent , SWT . NULL ) ; basicControls . setLayout ( new GridLayout ( , false ) ) ; basicControls . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . CENTER , true , false ) ) ; projectNameLabel = new Label ( basicControls , SWT . LEFT ) ; projectNameLabel . setText ( PROJECT ) ; projectNameLabel . setForeground ( fColorManager . getColor ( new RGB ( , , ) ) ) ; GridData pnlData = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; pnlData . horizontalSpan = ; projectNameLabel . setLayoutData ( pnlData ) ; tasksComp = new Composite ( basicControls , SWT . LEFT ) ; tasksComp . setLayout ( new GridLayout ( , false ) ) ; tasksLabel = new Label ( tasksComp , SWT . LEFT ) ; tasksLabel . setText ( "" ) ; fTasksCombo = new Combo ( tasksComp , SWT . DROP_DOWN | SWT . READ_ONLY ) ; fTasksCombo . setVisibleItemCount ( ) ; fTasksCombo . addSelectionListener ( new SelectionListener ( ) { public void widgetDefaultSelected ( SelectionEvent e ) { } public void widgetSelected ( SelectionEvent e ) { setCurrentSelectedTaskDescription ( ) ; } } ) ; Composite paramsComp = new Composite ( basicControls , SWT . LEFT ) ; paramsComp . setLayout ( new GridLayout ( , false ) ) ; paramsComp . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , false ) ) ; paramLabel = new Label ( paramsComp , SWT . LEFT ) ; paramLabel . setText ( "" ) ; fParamText = new Text ( paramsComp , SWT . BORDER ) ; GridData paramTextData = new GridData ( GridData . FILL_HORIZONTAL ) ; paramTextData . widthHint = ; fParamText . setLayoutData ( paramTextData ) ; fParamText . addKeyListener ( new KeyListener ( ) { public void keyPressed ( KeyEvent e ) { } public void keyReleased ( KeyEvent e ) { if ( e . character == SWT . CR ) { runRakeTask ( ) ; } } } ) ; genButton = new Button ( basicControls , SWT . PUSH ) ; genButton . setToolTipText ( "" ) ; genButton . setImage ( getRunIcon ( ) ) ; genButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { runRakeTask ( ) ; } } ) ; Composite descripComp = new Composite ( basicControls , SWT . LEFT ) ; descripComp . setLayout ( new GridLayout ( , false ) ) ; GridData gd = new GridData ( ) ; gd . horizontalSpan = ; gd . verticalAlignment = SWT . TOP ; gd . grabExcessHorizontalSpace = false ; descripComp . setLayoutData ( gd ) ; descriptionLabel = new Label ( descripComp , SWT . LEFT ) ; descriptionLabel . setText ( "" ) ; fDescripText = new Label ( descripComp , SWT . WRAP ) ; return basicControls ; } private Composite createAdvancedSection ( final Composite parent ) { final Composite advanced = new Composite ( parent , SWT . NONE ) ; GridLayout layout = new GridLayout ( , false ) ; layout . marginHeight = ; layout . marginWidth = ; advanced . setLayout ( layout ) ; GridData advancedData = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; advancedData . horizontalSpan = ; advanced . setLayoutData ( advancedData ) ; final Font boldFont = new Font ( advanced . getDisplay ( ) , boldFont ( advanced . getFont ( ) ) ) ; advanced . addDisposeListener ( new DisposeListener ( ) { public void widgetDisposed ( DisposeEvent e ) { if ( hand != null && ! hand . isDisposed ( ) ) { hand . dispose ( ) ; } if ( boldFont != null && ! boldFont . isDisposed ( ) ) { boldFont . dispose ( ) ; } } } ) ; final Label advancedIcon = new Label ( advanced , SWT . LEFT ) ; advancedIcon . setImage ( getMaximizeIcon ( ) ) ; advancedIcon . setCursor ( hand ) ; advancedIcon . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , false , false ) ) ; Label advancedLabel = new Label ( advanced , SWT . LEFT ) ; advancedLabel . setText ( "" ) ; advancedLabel . setCursor ( hand ) ; advancedLabel . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; advancedLabel . setFont ( boldFont ) ; final Composite advancedOptions = new Composite ( advanced , SWT . NONE ) ; layout = new GridLayout ( ) ; layout . marginLeft = ; advancedOptions . setLayout ( layout ) ; GridData gridData = new GridData ( SWT . FILL , SWT . FILL , true , false ) ; gridData . horizontalSpan = ; gridData . exclude = true ; advancedOptions . setLayoutData ( gridData ) ; advancedOptions . setVisible ( false ) ; MouseAdapter expander = new MouseAdapter ( ) { public void mouseDown ( MouseEvent e ) { if ( advancedOptions . isVisible ( ) ) { advancedOptions . setVisible ( false ) ; advancedIcon . setImage ( getMaximizeIcon ( ) ) ; ( ( GridData ) advancedOptions . getLayoutData ( ) ) . exclude = true ; } else { advancedOptions . setVisible ( true ) ; advancedIcon . setImage ( getMinimizeIcon ( ) ) ; ( ( GridData ) advancedOptions . getLayoutData ( ) ) . exclude = false ; } parent . pack ( true ) ; parent . layout ( true , true ) ; } } ; advancedIcon . addMouseListener ( expander ) ; advancedLabel . addMouseListener ( expander ) ; Group optionsGroup = new Group ( advancedOptions , SWT . NULL ) ; optionsGroup . setLayout ( new GridLayout ( , false ) ) ; optionsGroup . setText ( "" ) ; pretendButton = new Button ( optionsGroup , SWT . CHECK ) ; pretendButton . setText ( "" ) ; quietButton = new Button ( optionsGroup , SWT . CHECK ) ; quietButton . setText ( "" ) ; backtraceButton = new Button ( optionsGroup , SWT . CHECK ) ; backtraceButton . setText ( "" ) ; systemButton = new Button ( optionsGroup , SWT . CHECK ) ; systemButton . setText ( "" ) ; return advanced ; } private Image getRunIcon ( ) { if ( fRunIcon == null ) { fRunIcon = RakePlugin . imageDescriptorFromPlugin ( RakePlugin . PLUGIN_ID , "" ) . createImage ( ) ; } return fRunIcon ; } private Image getMaximizeIcon ( ) { if ( fMaximizeIcon == null ) { fMaximizeIcon = RakePlugin . imageDescriptorFromPlugin ( RakePlugin . PLUGIN_ID , "" ) . createImage ( ) ; } return fMaximizeIcon ; } private Image getMinimizeIcon ( ) { if ( fMinimizeIcon == null ) { fMinimizeIcon = RakePlugin . imageDescriptorFromPlugin ( RakePlugin . PLUGIN_ID , "" ) . createImage ( ) ; } return fMinimizeIcon ; } private static FontData [ ] boldFont ( Font font ) { FontData [ ] datas = font . getFontData ( ) ; if ( datas . length > ) { for ( int i = ; i < datas . length ; i ++ ) { FontData data = datas [ i ] ; data . setStyle ( data . getStyle ( ) | SWT . BOLD ) ; } } return datas ; } public void dispose ( ) { super . dispose ( ) ; disposeIcon ( fMaximizeIcon ) ; disposeIcon ( fMinimizeIcon ) ; disposeIcon ( fRunIcon ) ; fColorManager . dispose ( ) ; getProjectTracker ( ) . removeProjectListener ( this ) ; RubyRuntime . removeVMInstallChangedListener ( this ) ; RakePlugin . getDefault ( ) . getPluginPreferences ( ) . removePropertyChangeListener ( this ) ; } private void disposeIcon ( Image icon ) { if ( icon == null ) return ; icon . dispose ( ) ; icon = null ; } private RubyExplorerTracker getProjectTracker ( ) { return RubyPlugin . getDefault ( ) . getProjectTracker ( ) ; } private void runRakeTask ( ) { final IProject project = getSelectedRubyProject ( ) ; if ( project == null ) return ; final String task = fTasksCombo . getText ( ) ; final String args = getArgs ( ) ; Job job = new Job ( MessageFormat . format ( "" , task , args ) ) { @ Override protected IStatus run ( IProgressMonitor monitor ) { getRakeTasksHelper ( ) . runRakeTask ( project , task , args , monitor ) ; return Status . OK_STATUS ; } } ; job . setUser ( true ) ; job . schedule ( ) ; } private String getArgs ( ) { String args = "" ; if ( pretendButton . getSelection ( ) ) args += "" ; if ( quietButton . getSelection ( ) ) args += "" ; if ( backtraceButton . getSelection ( ) ) args += "" ; if ( systemButton . getSelection ( ) ) args += "" ; return args + fParamText . getText ( ) ; } private IProject getSelectedRubyProject ( ) { return this . project ; } private IRakeHelper getRakeTasksHelper ( ) { return RakePlugin . getDefault ( ) . getRakeHelper ( ) ; } protected void updateRakeTasks ( final boolean force ) { fTasksCombo . removeAll ( ) ; if ( project == null ) return ; if ( updateRakeTasksJob != null ) { updateRakeTasksJob . cancel ( ) ; } updateRakeTasksJob = new Job ( "" ) { protected IStatus run ( IProgressMonitor monitor ) { if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; monitor . beginTask ( "" , ) ; PlatformUI . getWorkbench ( ) . getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { if ( fDescripText != null && ! fDescripText . isDisposed ( ) ) { fDescripText . setText ( "" ) ; } } } ) ; monitor . worked ( ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; fTasks = getRakeTasksHelper ( ) . getTasks ( getSelectedRubyProject ( ) , force , monitor ) ; if ( monitor . isCanceled ( ) ) return Status . CANCEL_STATUS ; PlatformUI . getWorkbench ( ) . getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { if ( fTasks . isEmpty ( ) ) { if ( ! fDescripText . isDisposed ( ) ) { fDescripText . redraw ( ) ; setTaskDescription ( "" ) ; } setEnabled ( false ) ; return ; } Collection < String > sortedItems = new TreeSet < String > ( fTasks . keySet ( ) ) ; if ( ! fTasksCombo . isDisposed ( ) ) { fTasksCombo . setItems ( sortedItems . toArray ( new String [ sortedItems . size ( ) ] ) ) ; fTasksCombo . pack ( true ) ; if ( fTasks != null && ! fTasks . isEmpty ( ) ) fTasksCombo . select ( ) ; setCurrentSelectedTaskDescription ( ) ; } if ( ! genButton . isDisposed ( ) ) genButton . setEnabled ( true ) ; } } ) ; monitor . worked ( ) ; monitor . done ( ) ; return Status . OK_STATUS ; } } ; updateRakeTasksJob . schedule ( ) ; } public void setFocus ( ) { fTasksCombo . setFocus ( ) ; setCurrentSelectedTaskDescription ( ) ; } public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { handlePossibleRakeChange ( getRakePath ( ) ) ; } private String getRakePath ( ) { return RakePlugin . getDefault ( ) . getRakePath ( ) ; } public void vmAdded ( IVMInstall newVm ) { } public void vmChanged ( org . rubypeople . rdt . launching . PropertyChangeEvent event ) { } public void vmRemoved ( IVMInstall removedVm ) { } public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( PreferenceConstants . PREF_RAKE_PATH ) ) { handlePossibleRakeChange ( event . getNewValue ( ) ) ; } } private void handlePossibleRakeChange ( final Object value ) { if ( ! fParent . isDisposed ( ) ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { if ( value == null || value . equals ( "" ) ) { fViewLayout . topControl = fSpecifyRakePath ; } else { fViewLayout . topControl = fRakeTasksView ; } fParent . layout ( ) ; } } ) ; } } public void setEnabled ( boolean enabled ) { fTasksCombo . setEnabled ( enabled ) ; fParamText . setEnabled ( enabled ) ; genButton . setEnabled ( enabled ) ; } public void projectSelected ( IProject project ) { if ( fParent . isDisposed ( ) ) { return ; } if ( project != null && RubyCore . isRubyProject ( project ) && project . exists ( ) && project . isOpen ( ) ) { projectNameLabel . setText ( PROJECT + project . getName ( ) ) ; this . project = project ; setEnabled ( true ) ; updateRakeTasks ( false ) ; } else { fViewLayout . topControl = fSelectRailsProjectView ; projectNameLabel . setText ( PROJECT + "" ) ; setEnabled ( false ) ; this . project = null ; clear ( ) ; fDescripText . setText ( "" ) ; } if ( emptyRakePath ( ) ) { fViewLayout . topControl = fSpecifyRakePath ; } else { fViewLayout . topControl = fRakeTasksView ; } fParent . layout ( ) ; } private void clear ( ) { fTasksCombo . removeAll ( ) ; fParamText . setText ( "" ) ; fDescripText . setText ( "" ) ; } private boolean emptyRakePath ( ) { return getRakePath ( ) == null || getRakePath ( ) . equals ( "" ) ; } private void setCurrentSelectedTaskDescription ( ) { if ( fTasks == null || fTasks . isEmpty ( ) || fTasksCombo == null ) return ; String descrip = fTasks . get ( fTasksCombo . getText ( ) ) ; if ( descrip == null ) return ; setTaskDescription ( descrip ) ; } private void setTaskDescription ( String descrip ) { Point size = this . fParent . getSize ( ) ; fDescripText . setText ( descrip ) ; GridData gd = ( GridData ) fDescripText . getParent ( ) . getLayoutData ( ) ; gd . widthHint = size . x - ; fTasksCombo . setToolTipText ( descrip ) ; fDescripText . pack ( true ) ; gd = new GridData ( ) ; gd . widthHint = size . x - ; fDescripText . setLayoutData ( gd ) ; fDescripText . getParent ( ) . pack ( true ) ; fRakeTasksView . pack ( true ) ; fRakeTasksView . layout ( true , true ) ; } } package com . aptana . rdt . internal . rake . view ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . ui . IViewActionDelegate ; import org . eclipse . ui . IViewPart ; public class RefreshRakeTasksActionDelegate implements IViewActionDelegate { private IViewPart fView ; public void init ( IViewPart view ) { fView = view ; } public void run ( IAction action ) { RakeTasksView rtv = ( RakeTasksView ) fView ; rtv . updateRakeTasks ( true ) ; } public void selectionChanged ( IAction action , ISelection selection ) { } } package com . aptana . rdt . internal . rake . view ; import org . eclipse . osgi . util . NLS ; public class RakeViewMessages extends NLS { private static final String BUNDLE_NAME = RakeViewMessages . class . getName ( ) ; public static String SpecifyRakePath_message ; public static String SelectRubyProject_message ; static { NLS . initializeMessages ( BUNDLE_NAME , RakeViewMessages . class ) ; } } package com . aptana . rdt . rake ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Status ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . launching . RubyRuntime ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . internal . rake . RakeTasksHelper ; public class RakePlugin extends AbstractUIPlugin { public static final String PLUGIN_ID = "" ; private static final String RAKE = "" ; private static RakePlugin plugin ; private IRakeHelper rakeHelper ; public RakePlugin ( ) { super ( ) ; } public void start ( BundleContext context ) throws Exception { plugin = this ; super . start ( context ) ; rakeHelper = RakeTasksHelper . getInstance ( ) ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static RakePlugin getDefault ( ) { return plugin ; } public String getRakePath ( ) { String path = getSavedPath ( PreferenceConstants . PREF_RAKE_PATH ) ; if ( path != null && path . trim ( ) . length ( ) > ) return path ; return buildBinExecutablePath ( RAKE ) ; } private String getSavedPath ( String prefKey ) { String path = getPreferenceStore ( ) . getString ( prefKey ) ; if ( path == null || path . trim ( ) . length ( ) == ) return null ; if ( path . endsWith ( "" ) || path . endsWith ( "" ) ) { return path . substring ( , path . length ( ) - ) ; } return path ; } private String buildBinExecutablePath ( String command ) { IPath path = RubyRuntime . checkInterpreterBin ( command ) ; if ( path != null && path . toFile ( ) . exists ( ) ) return path . toOSString ( ) ; path = AptanaRDTPlugin . checkBinDir ( command ) ; if ( path != null && path . toFile ( ) . exists ( ) ) return path . toOSString ( ) ; path = RubyCore . checkSystemPath ( command ) ; if ( path != null && path . toFile ( ) . exists ( ) ) return path . toOSString ( ) ; return null ; } public static void log ( String message , Exception e ) { getDefault ( ) . getLog ( ) . log ( new Status ( Status . ERROR , PLUGIN_ID , - , message , e ) ) ; } public static void log ( Exception e ) { log ( e . getMessage ( ) , e ) ; } public IRakeHelper getRakeHelper ( ) { return rakeHelper ; } } package com . aptana . rdt . rake ; import java . util . Map ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . debug . core . ILaunchConfiguration ; public interface IRakeHelper { public void runRakeTask ( IProject project , String task , String arguments , IProgressMonitor monitor ) ; public ILaunchConfiguration run ( IProject project , String task , String arguments ) ; public Map < String , String > getTasks ( IProject project , IProgressMonitor monitor ) ; public Map < String , String > getTasks ( IProject project , boolean force , IProgressMonitor monitor ) ; } package com . aptana . rdt . rake ; public interface IRakeUIConstants { String ID_RAKE_VIEW = "" ; } package com . aptana . rdt . rake ; public class PreferenceConstants { public static final String PREF_RAKE_PATH = "" ; } package org . jruby . lexer . yacc ; import java . io . IOException ; import java . io . InputStream ; import java . io . Reader ; import java . util . List ; import org . jruby . parser . ParserConfiguration ; import org . jruby . util . ByteList ; public class ReaderLexerSource extends LexerSource { private static final int INITIAL_PUSHBACK_SIZE = ; private final Reader in ; private char buf [ ] = new char [ INITIAL_PUSHBACK_SIZE ] ; private int bufLength = - ; private int oneAgo = '' ; private int twoAgo = ; public ReaderLexerSource ( String sourceName , Reader in , List < String > list , int line , boolean extraPositionInformation ) { super ( sourceName , list , line , extraPositionInformation ) ; this . in = in ; } public int read ( ) throws IOException { int c ; if ( bufLength >= ) { c = buf [ bufLength -- ] ; } else { c = wrappedRead ( ) ; if ( c == - ) return RubyYaccLexer . EOF ; } twoAgo = oneAgo ; oneAgo = c ; offset ++ ; if ( c == '' ) line ++ ; return c ; } public void unread ( int c ) { if ( c == RubyYaccLexer . EOF ) return ; offset -- ; oneAgo = twoAgo ; twoAgo = ; if ( c == '' ) line -- ; buf [ ++ bufLength ] = ( char ) c ; if ( bufLength + == buf . length ) { char [ ] newBuf = new char [ buf . length + INITIAL_PUSHBACK_SIZE ] ; System . arraycopy ( buf , , newBuf , , buf . length ) ; buf = newBuf ; } } public boolean peek ( int to ) throws IOException { int captureTwoAgo = twoAgo ; int c = read ( ) ; unread ( c ) ; twoAgo = captureTwoAgo ; return c == to ; } private int wrappedRead ( ) throws IOException { int c = in . read ( ) ; if ( c == '' ) { if ( ( c = in . read ( ) ) != '' ) { unread ( ( char ) c ) ; c = '' ; } else { offset ++ ; } } captureFeature ( c ) ; return c ; } public static LexerSource getSource ( String name , InputStream content , List < String > list , ParserConfiguration configuration ) { return new InputStreamLexerSource ( name , content , list , configuration . getLineNumber ( ) , configuration . hasExtraPositionInformation ( ) ) ; } @ Override public ByteList readLineBytes ( ) throws IOException { ByteList bytelist = new ByteList ( ) ; for ( int c = read ( ) ; c != '' && c != RubyYaccLexer . EOF ; c = read ( ) ) { bytelist . append ( c ) ; } return bytelist ; } @ Override public int skipUntil ( int c ) throws IOException { for ( c = read ( ) ; c != '' && c != RubyYaccLexer . EOF ; c = read ( ) ) { } return c ; } public void unreadMany ( CharSequence buffer ) { int length = buffer . length ( ) ; for ( int i = length - ; i >= ; i -- ) { unread ( buffer . charAt ( i ) ) ; } } @ Override public boolean matchMarker ( ByteList match , boolean indent , boolean checkNewline ) throws IOException { int length = match . length ( ) ; ByteList buffer = new ByteList ( length + ) ; if ( indent ) { int c ; while ( ( c = read ( ) ) != RubyYaccLexer . EOF ) { if ( ! Character . isWhitespace ( c ) || c == '' ) { unread ( c ) ; break ; } buffer . append ( c ) ; } } int c ; for ( int i = ; i < length ; i ++ ) { c = read ( ) ; buffer . append ( c ) ; if ( match . charAt ( i ) != c ) { unreadMany ( buffer ) ; return false ; } } if ( ! checkNewline ) return true ; c = read ( ) ; if ( c == RubyYaccLexer . EOF || c == '' ) return true ; buffer . append ( c ) ; unreadMany ( buffer ) ; return false ; } public boolean wasBeginOfLine ( ) { return twoAgo == '' ; } public boolean lastWasBeginOfLine ( ) { return oneAgo == '' ; } public String toString ( ) { try { ByteList buffer = new ByteList ( ) ; buffer . append ( twoAgo ) ; buffer . append ( oneAgo ) ; buffer . append ( new byte [ ] { '' , '>' } ) ; int i = ; for ( ; i < ; i ++ ) { int c = read ( ) ; if ( c == ) { i -- ; break ; } buffer . append ( c ) ; } for ( ; i >= ; i ++ ) { unread ( buffer . charAt ( i ) ) ; } buffer . append ( new byte [ ] { '' , '' , '' , '' } ) ; return buffer . toString ( ) ; } catch ( Exception e ) { return null ; } } @ Override public ByteList readUntil ( char marker ) throws IOException { ByteList list = new ByteList ( ) ; int c ; for ( c = read ( ) ; c != marker && c != RubyYaccLexer . EOF ; c = read ( ) ) { list . append ( c ) ; } if ( c == RubyYaccLexer . EOF ) return null ; unread ( c ) ; return list ; } } package org . rubypeople . eclipse . shams . runtime ; import java . io . File ; import org . eclipse . core . runtime . IPath ; public class ShamIPath implements IPath { protected String path ; public ShamIPath ( String thePath ) { path = thePath ; } public IPath addFileExtension ( String extension ) { throw new RuntimeException ( "" ) ; } public IPath addTrailingSeparator ( ) { throw new RuntimeException ( "" ) ; } public IPath append ( String path ) { throw new RuntimeException ( "" ) ; } public IPath append ( IPath path ) { throw new RuntimeException ( "" ) ; } public Object clone ( ) { throw new RuntimeException ( "" ) ; } public String getDevice ( ) { throw new RuntimeException ( "" ) ; } public String getFileExtension ( ) { throw new RuntimeException ( "" ) ; } public boolean hasTrailingSeparator ( ) { throw new RuntimeException ( "" ) ; } public boolean isAbsolute ( ) { throw new RuntimeException ( "" ) ; } public boolean isEmpty ( ) { throw new RuntimeException ( "" ) ; } public boolean isPrefixOf ( IPath anotherPath ) { throw new RuntimeException ( "" ) ; } public boolean isRoot ( ) { throw new RuntimeException ( "" ) ; } public boolean isUNC ( ) { throw new RuntimeException ( "" ) ; } public boolean isValidPath ( String path ) { throw new RuntimeException ( "" ) ; } public boolean isValidSegment ( String segment ) { throw new RuntimeException ( "" ) ; } public String lastSegment ( ) { throw new RuntimeException ( "" ) ; } public IPath makeAbsolute ( ) { throw new RuntimeException ( "" ) ; } public IPath makeRelative ( ) { throw new RuntimeException ( "" ) ; } public IPath makeUNC ( boolean toUNC ) { throw new RuntimeException ( "" ) ; } public int matchingFirstSegments ( IPath anotherPath ) { throw new RuntimeException ( "" ) ; } public IPath removeFileExtension ( ) { throw new RuntimeException ( "" ) ; } public IPath removeFirstSegments ( int count ) { throw new RuntimeException ( "" ) ; } public IPath removeLastSegments ( int count ) { throw new RuntimeException ( "" ) ; } public IPath removeTrailingSeparator ( ) { throw new RuntimeException ( "" ) ; } public String segment ( int index ) { throw new RuntimeException ( "" ) ; } public int segmentCount ( ) { throw new RuntimeException ( "" ) ; } public String [ ] segments ( ) { throw new RuntimeException ( "" ) ; } public IPath setDevice ( String device ) { throw new RuntimeException ( "" ) ; } public File toFile ( ) { throw new RuntimeException ( "" ) ; } public String toOSString ( ) { throw new RuntimeException ( "" ) ; } public IPath uptoSegment ( int count ) { throw new RuntimeException ( "" ) ; } public String toString ( ) { return path ; } public String toPortableString ( ) { throw new RuntimeException ( "" ) ; } public IPath makeRelativeTo ( IPath base ) { return null ; } } package org . rubypeople . eclipse . shams . runtime ; public class ShamException extends RuntimeException { private static final long serialVersionUID = ; } package org . rubypeople . eclipse . shams . runtime ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . core . runtime . preferences . IEclipsePreferences ; import org . eclipse . core . runtime . preferences . IPreferenceNodeVisitor ; import org . osgi . service . prefs . BackingStoreException ; import org . osgi . service . prefs . Preferences ; public class ShamPreferences implements IEclipsePreferences { private Map data = new HashMap ( ) ; public void addNodeChangeListener ( INodeChangeListener listener ) { throw new ShamException ( ) ; } public void removeNodeChangeListener ( INodeChangeListener listener ) { throw new ShamException ( ) ; } public void addPreferenceChangeListener ( IPreferenceChangeListener listener ) { throw new ShamException ( ) ; } public void removePreferenceChangeListener ( IPreferenceChangeListener listener ) { throw new ShamException ( ) ; } public void removeNode ( ) throws BackingStoreException { throw new ShamException ( ) ; } public Preferences node ( String path ) { throw new ShamException ( ) ; } public void accept ( IPreferenceNodeVisitor visitor ) throws BackingStoreException { throw new ShamException ( ) ; } public void put ( String key , String value ) { data . put ( key , value ) ; } public String get ( String key , String def ) { Object value = data . get ( key ) ; if ( value == null ) return def ; return ( String ) value ; } public void remove ( String key ) { throw new ShamException ( ) ; } public void clear ( ) throws BackingStoreException { throw new ShamException ( ) ; } public void putInt ( String key , int value ) { throw new ShamException ( ) ; } public int getInt ( String key , int def ) { throw new ShamException ( ) ; } public void putLong ( String key , long value ) { throw new ShamException ( ) ; } public long getLong ( String key , long def ) { throw new ShamException ( ) ; } public void putBoolean ( String key , boolean value ) { throw new ShamException ( ) ; } public boolean getBoolean ( String key , boolean def ) { throw new ShamException ( ) ; } public void putFloat ( String key , float value ) { throw new ShamException ( ) ; } public float getFloat ( String key , float def ) { throw new ShamException ( ) ; } public void putDouble ( String key , double value ) { throw new ShamException ( ) ; } public double getDouble ( String key , double def ) { throw new ShamException ( ) ; } public void putByteArray ( String key , byte [ ] value ) { throw new ShamException ( ) ; } public byte [ ] getByteArray ( String key , byte [ ] def ) { throw new ShamException ( ) ; } public String [ ] keys ( ) throws BackingStoreException { throw new ShamException ( ) ; } public String [ ] childrenNames ( ) throws BackingStoreException { throw new ShamException ( ) ; } public Preferences parent ( ) { throw new ShamException ( ) ; } public boolean nodeExists ( String pathName ) throws BackingStoreException { throw new ShamException ( ) ; } public String name ( ) { throw new ShamException ( ) ; } public String absolutePath ( ) { throw new ShamException ( ) ; } public void flush ( ) throws BackingStoreException { throw new ShamException ( ) ; } public void sync ( ) throws BackingStoreException { throw new ShamException ( ) ; } } package org . rubypeople . eclipse . shams . debug . core ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchDelegate ; public class ShamLaunchConfiguration implements ILaunchConfiguration { public ShamLaunchConfiguration ( ) { super ( ) ; } public ILaunch launch ( String mode , IProgressMonitor monitor ) throws CoreException { return null ; } public boolean supportsMode ( String mode ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getName ( ) { throw new RuntimeException ( "" ) ; } public IPath getLocation ( ) { throw new RuntimeException ( "" ) ; } public boolean exists ( ) { throw new RuntimeException ( "" ) ; } public int getAttribute ( String attributeName , int defaultValue ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getAttribute ( String attributeName , String defaultValue ) throws CoreException { return defaultValue ; } public boolean getAttribute ( String attributeName , boolean defaultValue ) throws CoreException { throw new RuntimeException ( "" ) ; } public List getAttribute ( String attributeName , List defaultValue ) throws CoreException { throw new RuntimeException ( "" ) ; } public Map getAttribute ( String attributeName , Map defaultValue ) throws CoreException { throw new RuntimeException ( "" ) ; } public IFile getFile ( ) { throw new RuntimeException ( "" ) ; } public ILaunchConfigurationType getType ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean isLocal ( ) { throw new RuntimeException ( "" ) ; } public ILaunchConfigurationWorkingCopy getWorkingCopy ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public ILaunchConfigurationWorkingCopy copy ( String name ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean isWorkingCopy ( ) { throw new RuntimeException ( "" ) ; } public void delete ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getMemento ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean contentsEqual ( ILaunchConfiguration configuration ) { throw new RuntimeException ( "" ) ; } public Object getAdapter ( Class adapter ) { throw new RuntimeException ( "" ) ; } public String getCategory ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public Map getAttributes ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public ILaunch launch ( String mode , IProgressMonitor monitor , boolean build ) throws CoreException { throw new RuntimeException ( "" ) ; } public ILaunch launch ( String mode , IProgressMonitor monitor , boolean build , boolean register ) throws CoreException { throw new RuntimeException ( "" ) ; } public IResource [ ] getMappedResources ( ) throws CoreException { return null ; } public boolean isMigrationCandidate ( ) throws CoreException { return false ; } public void migrate ( ) throws CoreException { } public Set getAttribute ( String attributeName , Set defaultValue ) throws CoreException { return null ; } public Set getModes ( ) throws CoreException { return null ; } public ILaunchDelegate getPreferredDelegate ( Set modes ) throws CoreException { return null ; } public boolean hasAttribute ( String attributeName ) throws CoreException { return false ; } public boolean isReadOnly ( ) { return false ; } } package org . rubypeople . eclipse . shams . debug . core ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchDelegate ; public class ShamLaunchConfigurationWorkingCopy implements ILaunchConfigurationWorkingCopy { protected Map attributes = new HashMap ( ) ; public ShamLaunchConfigurationWorkingCopy ( ) { super ( ) ; } public boolean isDirty ( ) { throw new RuntimeException ( "" ) ; } public ILaunchConfiguration doSave ( ) throws CoreException { return new ShamLaunchConfiguration ( ) ; } public void setAttribute ( String attributeName , int value ) { throw new RuntimeException ( "" ) ; } public void setAttribute ( String attributeName , String value ) { attributes . put ( attributeName , value ) ; } public void setAttribute ( String attributeName , List value ) { throw new RuntimeException ( "" ) ; } public void setAttribute ( String attributeName , Map value ) { throw new RuntimeException ( "" ) ; } public void setAttribute ( String attributeName , boolean value ) { throw new RuntimeException ( "" ) ; } public ILaunchConfiguration getOriginal ( ) { throw new RuntimeException ( "" ) ; } public void rename ( String name ) { throw new RuntimeException ( "" ) ; } public void setContainer ( IContainer container ) { throw new RuntimeException ( "" ) ; } public ILaunch launch ( String mode , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean supportsMode ( String mode ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getName ( ) { throw new RuntimeException ( "" ) ; } public IPath getLocation ( ) { throw new RuntimeException ( "" ) ; } public boolean exists ( ) { throw new RuntimeException ( "" ) ; } public int getAttribute ( String attributeName , int defaultValue ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getAttribute ( String attributeName , String defaultValue ) throws CoreException { String value = ( String ) attributes . get ( attributeName ) ; return value == null ? defaultValue : value ; } public boolean getAttribute ( String attributeName , boolean defaultValue ) throws CoreException { throw new RuntimeException ( "" ) ; } public List getAttribute ( String attributeName , List defaultValue ) throws CoreException { throw new RuntimeException ( "" ) ; } public Map getAttribute ( String attributeName , Map defaultValue ) throws CoreException { throw new RuntimeException ( "" ) ; } public IFile getFile ( ) { throw new RuntimeException ( "" ) ; } public ILaunchConfigurationType getType ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean isLocal ( ) { throw new RuntimeException ( "" ) ; } public ILaunchConfigurationWorkingCopy getWorkingCopy ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public ILaunchConfigurationWorkingCopy copy ( String name ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean isWorkingCopy ( ) { throw new RuntimeException ( "" ) ; } public void delete ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getMemento ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean contentsEqual ( ILaunchConfiguration configuration ) { throw new RuntimeException ( "" ) ; } public Object getAdapter ( Class adapter ) { throw new RuntimeException ( "" ) ; } public void setAttributes ( Map attributes ) { throw new RuntimeException ( "" ) ; } public String getCategory ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public Map getAttributes ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public ILaunch launch ( String mode , IProgressMonitor monitor , boolean build ) throws CoreException { throw new RuntimeException ( "" ) ; } public ILaunch launch ( String mode , IProgressMonitor monitor , boolean build , boolean register ) throws CoreException { throw new RuntimeException ( "" ) ; } public void setMappedResources ( IResource [ ] resources ) { } public IResource [ ] getMappedResources ( ) throws CoreException { return null ; } public boolean isMigrationCandidate ( ) throws CoreException { return false ; } public void migrate ( ) throws CoreException { } public void addModes ( Set modes ) { } public ILaunchConfigurationWorkingCopy getParent ( ) { return null ; } public Object removeAttribute ( String attributeName ) { return null ; } public void removeModes ( Set modes ) { } public void setModes ( Set modes ) { } public void setPreferredLaunchDelegate ( Set modes , String delegateId ) { } public Set getAttribute ( String attributeName , Set defaultValue ) throws CoreException { return null ; } public Set getModes ( ) throws CoreException { return null ; } public ILaunchDelegate getPreferredDelegate ( Set modes ) throws CoreException { return null ; } public boolean hasAttribute ( String attributeName ) throws CoreException { return false ; } public boolean isReadOnly ( ) { return false ; } public void setAttribute ( String attributeName , Set value ) { } } package org . rubypeople . eclipse . shams . debug . core ; import java . util . ArrayList ; import java . util . Date ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationListener ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchListener ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . core . ILaunchMode ; import org . eclipse . debug . core . ILaunchesListener ; import org . eclipse . debug . core . model . IDebugTarget ; import org . eclipse . debug . core . model . IPersistableSourceLocator ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . core . sourcelookup . ISourceContainerType ; import org . eclipse . debug . core . sourcelookup . ISourcePathComputer ; public class ShamLaunchManager implements ILaunchManager { protected List launches = new ArrayList ( ) ; protected ILaunchConfigurationType launchConfigurationType = new ShamLaunchConfigurationType ( ) ; public ShamLaunchManager ( ) { super ( ) ; } public void addLaunchListener ( ILaunchListener listener ) { throw new RuntimeException ( "" ) ; } public void removeLaunch ( ILaunch launch ) { throw new RuntimeException ( "" ) ; } public IDebugTarget [ ] getDebugTargets ( ) { throw new RuntimeException ( "" ) ; } public ILaunch [ ] getLaunches ( ) { return ( ILaunch [ ] ) launches . toArray ( new ILaunch [ launches . size ( ) ] ) ; } public IProcess [ ] getProcesses ( ) { throw new RuntimeException ( "" ) ; } public void addLaunch ( ILaunch launch ) { launches . add ( launch ) ; } public void removeLaunchListener ( ILaunchListener listener ) { throw new RuntimeException ( "" ) ; } public ILaunchConfiguration [ ] getLaunchConfigurations ( ) throws CoreException { List configurations = new ArrayList ( ) ; for ( Iterator iter = launches . iterator ( ) ; iter . hasNext ( ) ; ) { ILaunch aLaunch = ( ILaunch ) iter . next ( ) ; configurations . add ( aLaunch . getLaunchConfiguration ( ) ) ; } return ( ILaunchConfiguration [ ] ) configurations . toArray ( new ILaunchConfiguration [ configurations . size ( ) ] ) ; } public ILaunchConfiguration [ ] getLaunchConfigurations ( ILaunchConfigurationType type ) throws CoreException { return getLaunchConfigurations ( ) ; } public ILaunchConfiguration getLaunchConfiguration ( IFile file ) { throw new RuntimeException ( "" ) ; } public ILaunchConfiguration getLaunchConfiguration ( String memento ) throws CoreException { throw new RuntimeException ( "" ) ; } public ILaunchConfigurationType [ ] getLaunchConfigurationTypes ( ) { throw new RuntimeException ( "" ) ; } public ILaunchConfigurationType getLaunchConfigurationType ( String id ) { return launchConfigurationType ; } public void addLaunchConfigurationListener ( ILaunchConfigurationListener listener ) { throw new RuntimeException ( "" ) ; } public void removeLaunchConfigurationListener ( ILaunchConfigurationListener listener ) { throw new RuntimeException ( "" ) ; } public boolean isExistingLaunchConfigurationName ( String name ) throws CoreException { throw new RuntimeException ( "" ) ; } public String generateUniqueLaunchConfigurationNameFrom ( String namePrefix ) { return namePrefix + new Date ( ) . toString ( ) ; } public IPersistableSourceLocator newSourceLocator ( String identifier ) throws CoreException { throw new RuntimeException ( "" ) ; } public void addLaunches ( ILaunch [ ] launches ) { throw new RuntimeException ( "" ) ; } public void addLaunchListener ( ILaunchesListener listener ) { throw new RuntimeException ( "" ) ; } public void removeLaunches ( ILaunch [ ] launches ) { throw new RuntimeException ( "" ) ; } public void removeLaunchListener ( ILaunchesListener listener ) { throw new RuntimeException ( "" ) ; } public ILaunchConfiguration getMovedFrom ( ILaunchConfiguration addedConfiguration ) { throw new RuntimeException ( "" ) ; } public ILaunchConfiguration getMovedTo ( ILaunchConfiguration removedConfiguration ) { throw new RuntimeException ( "" ) ; } public String [ ] getEnvironment ( ILaunchConfiguration configuration ) throws CoreException { return null ; } public String getLaunchModeLabel ( String mode ) { return null ; } public ILaunchMode [ ] getLaunchModes ( ) { return null ; } public ISourcePathComputer newSourcePathComputer ( ILaunchConfiguration configuration ) throws CoreException { throw new RuntimeException ( "" ) ; } public Map getNativeEnvironment ( ) { throw new RuntimeException ( "" ) ; } public ILaunchMode getLaunchMode ( String mode ) { throw new RuntimeException ( "" ) ; } public ISourcePathComputer getSourcePathComputer ( ILaunchConfiguration configuration ) throws CoreException { throw new RuntimeException ( "" ) ; } public ISourcePathComputer getSourcePathComputer ( String id ) { throw new RuntimeException ( "" ) ; } public ISourceContainerType [ ] getSourceContainerTypes ( ) { throw new RuntimeException ( "" ) ; } public ISourceContainerType getSourceContainerType ( String id ) { throw new RuntimeException ( "" ) ; } public boolean isRegistered ( ILaunch launch ) { throw new RuntimeException ( "" ) ; } public Map getNativeEnvironmentCasePreserved ( ) { throw new RuntimeException ( "" ) ; } public ILaunchConfiguration [ ] getMigrationCandidates ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getEncoding ( ILaunchConfiguration configuration ) throws CoreException { return null ; } public String generateLaunchConfigurationName ( String namePrefix ) { return null ; } public boolean isValidLaunchConfigurationName ( String configname ) throws IllegalArgumentException { return false ; } } package org . rubypeople . eclipse . shams . debug . core ; import java . util . Set ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchDelegate ; import org . eclipse . debug . core . model . ILaunchConfigurationDelegate ; import org . eclipse . debug . core . sourcelookup . ISourcePathComputer ; public class ShamLaunchConfigurationType implements ILaunchConfigurationType { protected boolean newInstanceCreated ; public ShamLaunchConfigurationType ( ) { super ( ) ; } public boolean supportsMode ( String mode ) { return false ; } public ISourcePathComputer getSourcePathComputer ( ) { return null ; } public String getName ( ) { return null ; } public String getIdentifier ( ) { return null ; } public boolean isPublic ( ) { return false ; } public ILaunchConfigurationWorkingCopy newInstance ( IContainer container , String name ) throws CoreException { newInstanceCreated = true ; return new ShamLaunchConfigurationWorkingCopy ( ) ; } public ILaunchConfigurationDelegate getDelegate ( ) throws CoreException { return null ; } public boolean wasNewInstanceCreated ( ) { boolean temp = newInstanceCreated ; newInstanceCreated = false ; return temp ; } public Object getAdapter ( Class adapter ) { return null ; } public String getCategory ( ) { return null ; } public String getAttribute ( String attributeName ) { return null ; } public ILaunchConfigurationDelegate getDelegate ( String mode ) throws CoreException { return null ; } public String getSourceLocatorId ( ) { return null ; } public String getPluginIdentifier ( ) { return null ; } public Set getSupportedModes ( ) { return null ; } public String getContributorName ( ) { return null ; } public ILaunchDelegate [ ] getDelegates ( Set modes ) throws CoreException { return null ; } public ILaunchDelegate getPreferredDelegate ( Set modes ) throws CoreException { return null ; } public Set getSupportedModeCombinations ( ) { return null ; } public void setPreferredDelegate ( Set modes , ILaunchDelegate delegate ) throws CoreException { } public boolean supportsModeCombination ( Set modes ) { return false ; } } package org . rubypeople . eclipse . shams . resources ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . FileInfoMatcherDescription ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IPathVariableManager ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceFilterDescription ; import org . eclipse . core . resources . IResourceProxyVisitor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; public class ShamContainer extends ShamResource implements IContainer { protected List childResources = new ArrayList ( ) ; public ShamContainer ( IPath path ) { super ( path ) ; } public void accept ( IResourceProxyVisitor visitor , int flags ) throws CoreException { for ( Iterator iter = childResources . iterator ( ) ; iter . hasNext ( ) ; ) { IResource resource = ( IResource ) iter . next ( ) ; visitor . visit ( new ShamResourceProxy ( resource ) ) ; if ( resource instanceof IContainer ) { IContainer container = ( IContainer ) resource ; container . accept ( visitor , flags ) ; } } } public boolean exists ( IPath path ) { throw new RuntimeException ( "" ) ; } public IResource findMember ( String name ) { throw new RuntimeException ( "" ) ; } public IResource findMember ( String name , boolean includePhantoms ) { throw new RuntimeException ( "" ) ; } public IResource findMember ( IPath path ) { throw new RuntimeException ( "" ) ; } public IResource findMember ( IPath path , boolean includePhantoms ) { throw new RuntimeException ( "" ) ; } public String getDefaultCharset ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getDefaultCharset ( boolean checkImplicit ) throws CoreException { throw new RuntimeException ( "" ) ; } public IFile getFile ( IPath path ) { throw new RuntimeException ( "" ) ; } public IFolder getFolder ( IPath path ) { throw new RuntimeException ( "" ) ; } public IResource [ ] members ( ) throws CoreException { return ( IResource [ ] ) childResources . toArray ( new IResource [ ] ) ; } public IResource [ ] members ( boolean includePhantoms ) throws CoreException { throw new RuntimeException ( "" ) ; } public IResource [ ] members ( int memberFlags ) throws CoreException { throw new RuntimeException ( "" ) ; } public IFile [ ] findDeletedMembersWithHistory ( int depth , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void setDefaultCharset ( String charset ) throws CoreException { throw new RuntimeException ( "" ) ; } public void setDefaultCharset ( String charset , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void addResource ( IResource resource ) { childResources . add ( resource ) ; } public IPathVariableManager getPathVariableManager ( ) { return null ; } public boolean isVirtual ( ) { return false ; } public void setDerived ( boolean isDerived , IProgressMonitor monitor ) throws CoreException { } public IResourceFilterDescription createFilter ( int type , FileInfoMatcherDescription matcherDescription , int updateFlags , IProgressMonitor monitor ) throws CoreException { return null ; } public IResourceFilterDescription [ ] getFilters ( ) throws CoreException { return null ; } } package org . rubypeople . eclipse . shams . resources ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceProxy ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . QualifiedName ; public class ShamResourceProxy implements IResourceProxy { private IResource resource ; public ShamResourceProxy ( IResource resource ) { this . resource = resource ; } public long getModificationStamp ( ) { return resource . getModificationStamp ( ) ; } public boolean isAccessible ( ) { return resource . isAccessible ( ) ; } public boolean isDerived ( ) { return resource . isDerived ( ) ; } public boolean isLinked ( ) { return resource . isLinked ( ) ; } public boolean isPhantom ( ) { return resource . isPhantom ( ) ; } public boolean isTeamPrivateMember ( ) { return resource . isTeamPrivateMember ( ) ; } public String getName ( ) { return resource . getName ( ) ; } public Object getSessionProperty ( QualifiedName key ) { try { return resource . getSessionProperty ( key ) ; } catch ( CoreException e ) { throw new RuntimeException ( e ) ; } } public int getType ( ) { return resource . getType ( ) ; } public IPath requestFullPath ( ) { return resource . getFullPath ( ) ; } public IResource requestResource ( ) { return resource ; } public boolean isHidden ( ) { return false ; } } package org . rubypeople . eclipse . shams . resources ; import java . net . URI ; import java . util . Map ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IPathVariableManager ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceProxy ; import org . eclipse . core . resources . IResourceProxyVisitor ; import org . eclipse . core . resources . IResourceVisitor ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourceAttributes ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . QualifiedName ; import org . eclipse . core . runtime . jobs . ISchedulingRule ; public class ShamResource implements IResource { protected IPath path ; public ShamResource ( IPath aPath ) { path = aPath ; } public boolean equals ( Object obj ) { if ( obj instanceof ShamResource ) { ShamResource that = ( ShamResource ) obj ; return path . equals ( that . path ) ; } return false ; } public void accept ( IResourceVisitor visitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void accept ( IResourceVisitor visitor , int depth , boolean includePhantoms ) throws CoreException { throw new RuntimeException ( "" ) ; } public void accept ( IResourceVisitor visitor , int depth , int memberFlags ) throws CoreException { throw new RuntimeException ( "" ) ; } public void clearHistory ( IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void copy ( IProjectDescription description , boolean force , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void copy ( IPath destination , boolean force , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void copy ( IProjectDescription description , int updateFlags , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void copy ( IPath destination , int updateFlags , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public IMarker createMarker ( String type ) { throw new RuntimeException ( "" ) ; } public void delete ( boolean force , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void delete ( int updateFlags , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void deleteMarkers ( String type , boolean includeSubtypes , int depth ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean exists ( ) { throw new RuntimeException ( "" ) ; } public IMarker findMarker ( long id ) throws CoreException { throw new RuntimeException ( "" ) ; } public IMarker [ ] findMarkers ( String type , boolean includeSubtypes , int depth ) throws CoreException { throw new RuntimeException ( "" ) ; } public String getFileExtension ( ) { return path . getFileExtension ( ) ; } public IPath getFullPath ( ) { return path ; } public IPath getLocation ( ) { return path ; } public IMarker getMarker ( long id ) { throw new RuntimeException ( "" ) ; } public long getModificationStamp ( ) { throw new RuntimeException ( "" ) ; } public String getName ( ) { return path . lastSegment ( ) ; } public IContainer getParent ( ) { throw new RuntimeException ( "" ) ; } public String getPersistentProperty ( QualifiedName key ) throws CoreException { throw new RuntimeException ( "" ) ; } public IProject getProject ( ) { throw new RuntimeException ( "" ) ; } public IPath getProjectRelativePath ( ) { throw new RuntimeException ( "" ) ; } public Object getSessionProperty ( QualifiedName key ) throws CoreException { throw new RuntimeException ( "" ) ; } public int getType ( ) { throw new RuntimeException ( "" ) ; } public IWorkspace getWorkspace ( ) { throw new RuntimeException ( "" ) ; } public boolean isAccessible ( ) { throw new RuntimeException ( "" ) ; } public boolean isLocal ( int depth ) { throw new RuntimeException ( "" ) ; } public boolean isPhantom ( ) { throw new RuntimeException ( "" ) ; } public boolean isReadOnly ( ) { throw new RuntimeException ( "" ) ; } public boolean isSynchronized ( int depth ) { throw new RuntimeException ( "" ) ; } public void move ( IProjectDescription description , boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void move ( IPath destination , boolean force , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void move ( IProjectDescription description , int updateFlags , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void move ( IPath destination , int updateFlags , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void refreshLocal ( int depth , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void setLocal ( boolean flag , int depth , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void setPersistentProperty ( QualifiedName key , String value ) throws CoreException { throw new RuntimeException ( "" ) ; } public void setReadOnly ( boolean readOnly ) { throw new RuntimeException ( "" ) ; } public void setSessionProperty ( QualifiedName key , Object value ) throws CoreException { throw new RuntimeException ( "" ) ; } public void touch ( IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean isDerived ( ) { throw new RuntimeException ( "" ) ; } public void setDerived ( boolean isDerived ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean isTeamPrivateMember ( ) { throw new RuntimeException ( "" ) ; } public void setTeamPrivateMember ( boolean isTeamPrivate ) throws CoreException { throw new RuntimeException ( "" ) ; } public Object getAdapter ( Class adapter ) { if ( adapter . isAssignableFrom ( getClass ( ) ) ) return this ; return null ; } public IPath getRawLocation ( ) { throw new RuntimeException ( "" ) ; } public boolean isLinked ( ) { throw new RuntimeException ( "" ) ; } public void accept ( IResourceProxyVisitor visitor , int flags ) throws CoreException { throw new RuntimeException ( "" ) ; } public long getLocalTimeStamp ( ) { throw new RuntimeException ( "" ) ; } public long setLocalTimeStamp ( long value ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean contains ( ISchedulingRule rule ) { throw new RuntimeException ( "" ) ; } public boolean isConflicting ( ISchedulingRule rule ) { throw new RuntimeException ( "" ) ; } public ResourceAttributes getResourceAttributes ( ) { throw new RuntimeException ( "" ) ; } public void revertModificationStamp ( long value ) throws CoreException { throw new RuntimeException ( "" ) ; } public void setResourceAttributes ( ResourceAttributes attributes ) throws CoreException { throw new RuntimeException ( "" ) ; } public String toString ( ) { return "" + path + "" ; } public URI getLocationURI ( ) { return path . toFile ( ) . toURI ( ) ; } public URI getRawLocationURI ( ) { return null ; } public boolean isLinked ( int options ) { return false ; } public IResourceProxy createProxy ( ) { return null ; } public int findMaxProblemSeverity ( String type , boolean includeSubtypes , int depth ) throws CoreException { return ; } public Map getPersistentProperties ( ) throws CoreException { return null ; } public Map getSessionProperties ( ) throws CoreException { return null ; } public boolean isDerived ( int options ) { return false ; } public boolean isHidden ( ) { return false ; } public void setHidden ( boolean isHidden ) throws CoreException { } public boolean isHidden ( int options ) { return false ; } public boolean isTeamPrivateMember ( int options ) { return false ; } public IPathVariableManager getPathVariableManager ( ) { return null ; } public boolean isVirtual ( ) { return false ; } public void setDerived ( boolean isDerived , IProgressMonitor monitor ) throws CoreException { } } package org . rubypeople . eclipse . shams . resources ; import java . io . ByteArrayInputStream ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . io . Reader ; import java . net . URI ; import java . nio . charset . Charset ; import junit . framework . Assert ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFileState ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IResourceVisitor ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourceAttributes ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . QualifiedName ; import org . eclipse . core . runtime . content . IContentDescription ; import org . eclipse . core . runtime . content . IContentType ; public class ShamFile extends ShamResource implements IFile { public static final String WORKSPACE_ROOT = "" ; protected String contents = "" ; protected boolean readContentFromFile ; private InputStream inputStream ; private IProject project ; public void setCharset ( String newCharset , IProgressMonitor monitor ) throws CoreException { } public ShamFile ( String fullPath ) { this ( fullPath , false ) ; } public ShamFile ( IPath aPath ) { this ( aPath , false ) ; } public String getCharset ( ) throws CoreException { return Charset . defaultCharset ( ) . name ( ) ; } public ShamFile ( String fullPath , boolean readContentFromFile ) { this ( new Path ( fullPath ) , readContentFromFile ) ; } public ShamFile ( IPath aPath , boolean readContentFromFile ) { super ( aPath ) ; this . readContentFromFile = readContentFromFile ; project = new ShamProject ( "" ) ; } public void appendContents ( InputStream source , boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { } public void appendContents ( InputStream source , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void create ( InputStream source , boolean force , IProgressMonitor monitor ) throws CoreException { } public void create ( InputStream source , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void delete ( boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { } public InputStream getContents ( ) throws CoreException { if ( readContentFromFile ) { try { return openStream ( new FileInputStream ( this . path . toString ( ) ) ) ; } catch ( FileNotFoundException e ) { throw new RuntimeException ( e . toString ( ) ) ; } } return openStream ( new ByteArrayInputStream ( contents . getBytes ( ) ) ) ; } private InputStream openStream ( InputStream newStream ) { Assert . assertNull ( "" , inputStream ) ; inputStream = new MonitoredInputStream ( newStream ) ; return inputStream ; } public void assertContentStreamClosed ( ) { Assert . assertNull ( "" , inputStream ) ; } public InputStream getContents ( boolean force ) throws CoreException { return getContents ( ) ; } public int getEncoding ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public IFileState [ ] getHistory ( IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean isReadOnly ( ) { throw new RuntimeException ( "" ) ; } public void move ( IPath destination , boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { } public void setContents ( InputStream source , boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { } public void setContents ( IFileState source , boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { } public void setContents ( InputStream source , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void setContents ( IFileState source , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void setContents ( String shamContents ) { this . contents = shamContents ; } public void accept ( IResourceVisitor visitor ) throws CoreException { } public void accept ( IResourceVisitor visitor , int depth , boolean includePhantoms ) throws CoreException { } public void accept ( IResourceVisitor visitor , int depth , int memberFlags ) throws CoreException { } public void clearHistory ( IProgressMonitor monitor ) throws CoreException { } public void copy ( IProjectDescription description , boolean force , IProgressMonitor monitor ) throws CoreException { } public void copy ( IPath destination , boolean force , IProgressMonitor monitor ) { } public void copy ( IProjectDescription description , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void copy ( IPath destination , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public IMarker createMarker ( String type ) { throw new RuntimeException ( "" ) ; } public void delete ( boolean force , IProgressMonitor monitor ) throws CoreException { } public void delete ( int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void deleteMarkers ( String type , boolean includeSubtypes , int depth ) throws CoreException { } public boolean exists ( ) { return true ; } public IMarker findMarker ( long id ) throws CoreException { throw new RuntimeException ( "" ) ; } public IMarker [ ] findMarkers ( String type , boolean includeSubtypes , int depth ) throws CoreException { throw new RuntimeException ( "" ) ; } public IPath getLocation ( ) { return new Path ( WORKSPACE_ROOT ) . append ( getFullPath ( ) ) ; } public IMarker getMarker ( long id ) { throw new RuntimeException ( "" ) ; } public long getModificationStamp ( ) { throw new RuntimeException ( "" ) ; } public IContainer getParent ( ) { throw new RuntimeException ( "" ) ; } public String getPersistentProperty ( QualifiedName key ) throws CoreException { throw new RuntimeException ( "" ) ; } public IProject getProject ( ) { return project ; } public IPath getProjectRelativePath ( ) { return new Path ( "" ) ; } public Object getSessionProperty ( QualifiedName key ) throws CoreException { throw new RuntimeException ( "" ) ; } public int getType ( ) { return FILE ; } public IWorkspace getWorkspace ( ) { throw new RuntimeException ( "" ) ; } public boolean isAccessible ( ) { throw new RuntimeException ( "" ) ; } public boolean isLocal ( int depth ) { throw new RuntimeException ( "" ) ; } public boolean isPhantom ( ) { throw new RuntimeException ( "" ) ; } public boolean isSynchronized ( int depth ) { throw new RuntimeException ( "" ) ; } public void move ( IProjectDescription description , boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { } public void move ( IPath destination , boolean force , IProgressMonitor monitor ) throws CoreException { } public void move ( IProjectDescription description , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void move ( IPath destination , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void refreshLocal ( int depth , IProgressMonitor monitor ) throws CoreException { } public void setLocal ( boolean flag , int depth , IProgressMonitor monitor ) throws CoreException { } public void setPersistentProperty ( QualifiedName key , String value ) throws CoreException { } public void setReadOnly ( boolean readOnly ) { } public void setSessionProperty ( QualifiedName key , Object value ) throws CoreException { } public void touch ( IProgressMonitor monitor ) throws CoreException { } public boolean isDerived ( ) { throw new RuntimeException ( "" ) ; } public void setDerived ( boolean isDerived ) throws CoreException { } public boolean isTeamPrivateMember ( ) { throw new RuntimeException ( "" ) ; } public void setTeamPrivateMember ( boolean isTeamPrivate ) throws CoreException { } public Object getAdapter ( Class adapter ) { throw new RuntimeException ( "" ) ; } public void createLink ( IPath localLocation , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public IPath getRawLocation ( ) { return null ; } public boolean isLinked ( ) { return false ; } public void setCharset ( String newCharset ) throws CoreException { } public String getCharset ( boolean checkImplicit ) throws CoreException { return getCharset ( ) ; } public IContentDescription getContentDescription ( ) throws CoreException { return new ShamContentDescription ( ) ; } public String getCharsetFor ( Reader reader ) throws CoreException { return null ; } public ResourceAttributes getResourceAttributes ( ) { return null ; } public void revertModificationStamp ( long value ) throws CoreException { } public void setResourceAttributes ( ResourceAttributes attributes ) throws CoreException { } public void setProject ( IProject project ) { this . project = project ; } private final class ShamContentDescription implements IContentDescription { public boolean isRequested ( QualifiedName key ) { return false ; } public String getCharset ( ) { return null ; } public IContentType getContentType ( ) { return null ; } public Object getProperty ( QualifiedName key ) { return null ; } public void setProperty ( QualifiedName key , Object value ) { } } private class MonitoredInputStream extends InputStream { private final InputStream inputStream ; public MonitoredInputStream ( InputStream inputStream ) { this . inputStream = inputStream ; } public int read ( ) throws IOException { return inputStream . read ( ) ; } public void close ( ) throws IOException { super . close ( ) ; ShamFile . this . inputStream = null ; } } public void createLink ( URI location , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public URI getRawLocationURI ( ) { return null ; } public boolean isLinked ( int options ) { return false ; } } package org . rubypeople . eclipse . shams . resources ; import java . net . URI ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IMarker ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IProjectNature ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceVisitor ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourceAttributes ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IPluginDescriptor ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . QualifiedName ; import org . eclipse . core . runtime . content . IContentTypeMatcher ; public class ShamProject extends ShamContainer implements IProject , IContainer { protected String projectName ; protected List natures = new ArrayList ( ) ; public ShamProject ( String theProjectName ) { this ( new Path ( "" + theProjectName ) , theProjectName ) ; } public void setDefaultCharset ( String charset , IProgressMonitor monitor ) throws CoreException { } public ShamProject ( IPath aPath , String theProjectName ) { super ( aPath ) ; projectName = theProjectName ; } public void build ( int kind , String builderName , Map args , IProgressMonitor monitor ) throws CoreException { } public void build ( int kind , IProgressMonitor monitor ) throws CoreException { } public void close ( IProgressMonitor monitor ) throws CoreException { } public void create ( IProjectDescription description , IProgressMonitor monitor ) throws CoreException { } public void create ( IProgressMonitor monitor ) throws CoreException { } public void delete ( boolean deleteContent , boolean force , IProgressMonitor monitor ) throws CoreException { } public IProjectDescription getDescription ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public IFile getFile ( String name ) { return new ShamFile ( getFullPath ( ) . append ( name ) ) ; } public IFolder getFolder ( String name ) { return new ShamFolder ( getFullPath ( ) . append ( name ) ) ; } public IProjectNature getNature ( String natureId ) throws CoreException { throw new RuntimeException ( "" ) ; } public IPath getPluginWorkingLocation ( IPluginDescriptor plugin ) { throw new RuntimeException ( "" ) ; } public IProject [ ] getReferencedProjects ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public IProject [ ] getReferencingProjects ( ) { throw new RuntimeException ( "" ) ; } public boolean hasNature ( String natureId ) throws CoreException { return natures . contains ( natureId ) ; } public boolean isNatureEnabled ( String natureId ) throws CoreException { throw new RuntimeException ( "" ) ; } public boolean isOpen ( ) { throw new RuntimeException ( "" ) ; } public void move ( IProjectDescription description , boolean force , IProgressMonitor monitor ) throws CoreException { } public void open ( IProgressMonitor monitor ) throws CoreException { } public void setDescription ( IProjectDescription description , IProgressMonitor monitor ) throws CoreException { } public void setDescription ( IProjectDescription description , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public boolean exists ( IPath path ) { throw new RuntimeException ( "" ) ; } public IResource findMember ( String name ) { throw new RuntimeException ( "" ) ; } public IResource findMember ( String name , boolean includePhantoms ) { throw new RuntimeException ( "" ) ; } public IResource findMember ( IPath path ) { throw new RuntimeException ( "" ) ; } public IResource findMember ( IPath path , boolean includePhantoms ) { throw new RuntimeException ( "" ) ; } public IFile getFile ( IPath path ) { throw new RuntimeException ( "" ) ; } public IFolder getFolder ( IPath path ) { throw new RuntimeException ( "" ) ; } public IResource [ ] members ( ) throws CoreException { return ( IResource [ ] ) childResources . toArray ( new IResource [ ] ) ; } public IResource [ ] members ( boolean includePhantoms ) throws CoreException { throw new RuntimeException ( "" ) ; } public IResource [ ] members ( int memberFlags ) throws CoreException { throw new RuntimeException ( "" ) ; } public IFile [ ] findDeletedMembersWithHistory ( int depth , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void accept ( IResourceVisitor visitor ) throws CoreException { } public void accept ( IResourceVisitor visitor , int depth , boolean includePhantoms ) throws CoreException { } public void accept ( IResourceVisitor visitor , int depth , int memberFlags ) throws CoreException { } public void clearHistory ( IProgressMonitor monitor ) throws CoreException { } public void copy ( IProjectDescription description , boolean force , IProgressMonitor monitor ) throws CoreException { } public void copy ( IPath destination , boolean force , IProgressMonitor monitor ) throws CoreException { } public void copy ( IProjectDescription description , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void copy ( IPath destination , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public IMarker createMarker ( String type ) { throw new RuntimeException ( "" ) ; } public void delete ( boolean force , IProgressMonitor monitor ) throws CoreException { } public void delete ( int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void deleteMarkers ( String type , boolean includeSubtypes , int depth ) throws CoreException { } public boolean exists ( ) { throw new RuntimeException ( "" ) ; } public IMarker findMarker ( long id ) throws CoreException { throw new RuntimeException ( "" ) ; } public IMarker [ ] findMarkers ( String type , boolean includeSubtypes , int depth ) throws CoreException { throw new RuntimeException ( "" ) ; } public IMarker getMarker ( long id ) { throw new RuntimeException ( "" ) ; } public long getModificationStamp ( ) { throw new RuntimeException ( "" ) ; } public String getName ( ) { return projectName ; } public IContainer getParent ( ) { throw new RuntimeException ( "" ) ; } public String getPersistentProperty ( QualifiedName key ) throws CoreException { throw new RuntimeException ( "" ) ; } public IProject getProject ( ) { throw new RuntimeException ( "" ) ; } public IPath getProjectRelativePath ( ) { throw new RuntimeException ( "" ) ; } public Object getSessionProperty ( QualifiedName key ) throws CoreException { throw new RuntimeException ( "" ) ; } public int getType ( ) { return IResource . PROJECT ; } public IWorkspace getWorkspace ( ) { throw new RuntimeException ( "" ) ; } public boolean isAccessible ( ) { throw new RuntimeException ( "" ) ; } public boolean isLocal ( int depth ) { throw new RuntimeException ( "" ) ; } public boolean isPhantom ( ) { throw new RuntimeException ( "" ) ; } public boolean isReadOnly ( ) { throw new RuntimeException ( "" ) ; } public boolean isSynchronized ( int depth ) { throw new RuntimeException ( "" ) ; } public void move ( IProjectDescription description , boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { } public void move ( IPath destination , boolean force , IProgressMonitor monitor ) throws CoreException { } public void move ( IProjectDescription description , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void move ( IPath destination , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void refreshLocal ( int depth , IProgressMonitor monitor ) throws CoreException { } public void setLocal ( boolean flag , int depth , IProgressMonitor monitor ) throws CoreException { } public void setPersistentProperty ( QualifiedName key , String value ) throws CoreException { } public void setReadOnly ( boolean readOnly ) { } public void setSessionProperty ( QualifiedName key , Object value ) throws CoreException { } public void touch ( IProgressMonitor monitor ) throws CoreException { } public boolean isDerived ( ) { throw new RuntimeException ( "" ) ; } public void setDerived ( boolean isDerived ) throws CoreException { } public boolean isTeamPrivateMember ( ) { throw new RuntimeException ( "" ) ; } public void setTeamPrivateMember ( boolean isTeamPrivate ) throws CoreException { } public void addNature ( String string ) { natures . add ( string ) ; } public String getDefaultCharset ( ) throws CoreException { throw new RuntimeException ( "" ) ; } public void setDefaultCharset ( String charset ) throws CoreException { throw new RuntimeException ( "" ) ; } public IPath getWorkingLocation ( String id ) { throw new RuntimeException ( "" ) ; } public String getDefaultCharset ( boolean checkImplicit ) throws CoreException { throw new RuntimeException ( "" ) ; } public void open ( int updateFlags , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public IContentTypeMatcher getContentTypeMatcher ( ) throws CoreException { return null ; } public ResourceAttributes getResourceAttributes ( ) { return null ; } public void revertModificationStamp ( long value ) throws CoreException { } public void setResourceAttributes ( ResourceAttributes attributes ) throws CoreException { } public void create ( IProjectDescription description , int updateFlags , IProgressMonitor monitor ) throws CoreException { } public void loadSnapshot ( int options , URI snapshotLocation , IProgressMonitor monitor ) throws CoreException { } public void saveSnapshot ( int options , URI snapshotLocation , IProgressMonitor monitor ) throws CoreException { } } package org . rubypeople . eclipse . shams . resources ; import java . net . URI ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . Path ; public class ShamFolder extends ShamContainer implements IFolder { public ShamFolder ( String aPathString ) { super ( new Path ( aPathString ) ) ; } public ShamFolder ( IPath aPath ) { super ( aPath ) ; } public void setDefaultCharset ( String charset , IProgressMonitor monitor ) throws CoreException { } public int getType ( ) { return FOLDER ; } public void create ( boolean force , boolean local , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void create ( int updateFlags , boolean local , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void createLink ( IPath localLocation , int updateFlags , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void delete ( boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public IFile getFile ( String name ) { throw new RuntimeException ( "" ) ; } public IFolder getFolder ( String name ) { throw new RuntimeException ( "" ) ; } public void move ( IPath destination , boolean force , boolean keepHistory , IProgressMonitor monitor ) throws CoreException { throw new RuntimeException ( "" ) ; } public void createLink ( URI location , int updateFlags , IProgressMonitor monitor ) throws CoreException { } } package org . rubypeople . eclipse . testutils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; public class ResourceTools { public static IProject createProject ( String name ) throws CoreException { IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; IWorkspaceRoot root = workspace . getRoot ( ) ; IProject project = root . getProject ( name ) ; if ( ! project . exists ( ) ) { IProjectDescription desc = workspace . newProjectDescription ( project . getName ( ) ) ; project . create ( desc , null ) ; } if ( ! project . isOpen ( ) ) project . open ( null ) ; return project ; } } package org . rubypeople . rdt . debug . core . tests ; import java . io . File ; import org . eclipse . core . runtime . IStatus ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . debug . core . SuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . commands . AbstractDebuggerConnection ; import org . rubypeople . rdt . internal . debug . core . commands . ClassicDebuggerConnection ; import org . rubypeople . rdt . internal . debug . core . model . RubyVariable ; import org . rubypeople . rdt . internal . debug . core . model . ThreadInfo ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; public class FTC_ClassicDebuggerCommunicationTest extends FTC_AbstractDebuggerCommunicationTest { public static junit . framework . TestSuite suite ( ) { junit . framework . TestSuite suite = new junit . framework . TestSuite ( ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; return suite ; } public FTC_ClassicDebuggerCommunicationTest ( String arg0 ) { super ( arg0 ) ; } public void startRubyProcess ( ) throws Exception { String cmd = FTC_ClassicDebuggerCommunicationTest . RUBY_INTERPRETER + "" + createIncludeDir ( ) + "" + getTmpDir ( ) . replace ( '' , '' ) + "" + getRubyTestFilename ( ) ; System . out . println ( "" + cmd ) ; process = Runtime . getRuntime ( ) . exec ( cmd ) ; rubyStderrRedirectorThread = new OutputRedirectorThread ( process . getErrorStream ( ) ) ; rubyStderrRedirectorThread . start ( ) ; rubyStdoutRedirectorThread = new OutputRedirectorThread ( process . getInputStream ( ) ) ; rubyStdoutRedirectorThread . start ( ) ; } private String createIncludeDir ( ) { String includeDir ; if ( LaunchingPlugin . getDefault ( ) != null ) { includeDir = RubyCore . getOSDirectory ( LaunchingPlugin . getDefault ( ) ) + "" ; } else { includeDir = getClass ( ) . getResource ( "" ) . getFile ( ) ; includeDir += "" ; if ( includeDir . startsWith ( "" ) && File . separatorChar == '' ) { includeDir = includeDir . substring ( ) ; } } if ( includeDir . indexOf ( "" ) == - ) { return includeDir ; } else { return '' + includeDir + '' ; } } public void testThreads ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" } ) ; sendRuby ( "" ) ; sendRuby ( "" ) ; sendRuby ( "" ) ; SuspensionPoint point1 = getSuspensionReader ( ) . readSuspension ( ) ; sendRuby ( "" ) ; ThreadInfo [ ] threadInfos = getThreadInfoReader ( ) . readThreads ( ) ; assertEquals ( , threadInfos . length ) ; sendRuby ( "" ) ; SuspensionPoint point2 = getSuspensionReader ( ) . readSuspension ( ) ; sendRuby ( "" ) ; threadInfos = getThreadInfoReader ( ) . readThreads ( ) ; assertEquals ( , threadInfos . length ) ; assertNotSame ( Integer . valueOf ( point1 . getThreadId ( ) ) , Integer . valueOf ( point2 . getThreadId ( ) ) ) ; } public void testThreadIdsAndResume ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; sendRuby ( "" ) ; sendRuby ( "" ) ; sendRuby ( "" ) ; sendRuby ( "" ) ; getSuspensionReader ( ) . readSuspension ( ) ; getSuspensionReader ( ) . readSuspension ( ) ; getSuspensionReader ( ) . readSuspension ( ) ; sendRuby ( "" ) ; ThreadInfo [ ] threads = getThreadInfoReader ( ) . readThreads ( ) ; assertEquals ( , threads . length ) ; int threadId1 = threads [ ] . getId ( ) ; int threadId2 = threads [ ] . getId ( ) ; int threadId3 = threads [ ] . getId ( ) ; sendRuby ( "" + threadId2 + "" ) ; sendRuby ( "" ) ; threads = getThreadInfoReader ( ) . readThreads ( ) ; assertEquals ( , threads . length ) ; assertEquals ( threadId1 , threads [ ] . getId ( ) ) ; assertEquals ( threadId3 , threads [ ] . getId ( ) ) ; sendRuby ( "" + threadId3 + "" ) ; sendRuby ( "" ) ; threads = getThreadInfoReader ( ) . readThreads ( ) ; assertEquals ( , threads . length ) ; assertEquals ( threadId1 , threads [ ] . getId ( ) ) ; } public void testReloadAndInspect ( ) throws Exception { String [ ] lines = new String [ ] { "" , "" , "" , "" , "" , "" , "" } ; createSocket ( lines ) ; runToLine ( ) ; lines [ ] = "" ; writeFile ( "" , lines ) ; sendRuby ( "" + getTmpDir ( ) + "" ) ; IStatus loadResult = this . getLoadResultReader ( ) . readLoadResult ( ) ; assertTrue ( "" , loadResult . isOK ( ) ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , , variables . length ) ; assertEquals ( "" , "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; } public void testReloadAndStep ( ) throws Exception { String [ ] lines = new String [ ] { "" , "" , "" } ; createSocket ( lines ) ; runToLine ( ) ; lines = new String [ ] { "" , "" , "" } ; writeFile ( "" , lines ) ; sendRuby ( "" + getTmpDir ( ) + "" ) ; this . getLoadResultReader ( ) . readLoadResult ( ) ; sendRuby ( "" ) ; SuspensionPoint info = getSuspensionReader ( ) . readSuspension ( ) ; assertEquals ( , info . getLine ( ) ) ; } public void testReloadWithException ( ) throws Exception { createSocket ( new String [ ] { "" } ) ; runToLine ( ) ; String [ ] lines = new String [ ] { "" } ; writeFile ( "" , lines ) ; sendRuby ( "" + getTmpDir ( ) + "" ) ; IStatus loadResult = this . getLoadResultReader ( ) . readLoadResult ( ) ; assertFalse ( "" , loadResult . isOK ( ) ) ; assertTrue ( loadResult . getMessage ( ) . startsWith ( "" ) ) ; } public void testReloadInRequire ( ) throws Exception { String [ ] lines = new String [ ] { "" , "" , "" } ; writeFile ( "" , lines ) ; createSocket ( new String [ ] { "" , "" , "" , "" } ) ; sendRuby ( "" ) ; lines [ ] = "" ; writeFile ( "" , lines ) ; sendRuby ( "" + getTmpDir ( ) + "" ) ; IStatus loadResult = this . getLoadResultReader ( ) . readLoadResult ( ) ; assertTrue ( "" , loadResult . isOK ( ) ) ; } public void testReloadInStackFrame ( ) throws Exception { String [ ] lines = new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" } ; createSocket ( lines ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] localVariables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , localVariables [ ] . getValue ( ) . getValueString ( ) ) ; lines [ ] = "" ; writeFile ( "" , lines ) ; sendRuby ( "" + getTmpDir ( ) + "" ) ; IStatus loadResult = this . getLoadResultReader ( ) . readLoadResult ( ) ; assertTrue ( "" , loadResult . isOK ( ) ) ; runToLine ( ) ; sendRuby ( "" ) ; localVariables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , localVariables [ ] . getValue ( ) . getValueString ( ) ) ; runToLine ( ) ; runToLine ( ) ; sendRuby ( "" ) ; localVariables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , localVariables [ ] . getValue ( ) . getValueString ( ) ) ; } @ Override protected AbstractDebuggerConnection createDebuggerConnection ( ) { return new ClassicDebuggerConnection ( ) ; } } package org . rubypeople . rdt . debug . core . tests ; import org . eclipse . debug . core . DebugEvent ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . ThreadInfo ; import junit . framework . TestCase ; public class TC_RubyDebugTarget extends TestCase { public void testThread ( ) { RubyDebugTarget target = new RubyDebugTarget ( null , RubyDebugTarget . DEFAULT_PORT ) ; ThreadInfo [ ] initial = new ThreadInfo [ ] { new ThreadInfo ( , "" ) } ; DebugEvent [ ] events = target . updateThreadsInternal ( initial ) ; assertEquals ( , events . length ) ; assertEquals ( DebugEvent . CREATE , events [ ] . getKind ( ) ) ; ThreadInfo [ ] threadAdded = new ThreadInfo [ ] { new ThreadInfo ( , "" ) , new ThreadInfo ( , "" ) } ; events = target . updateThreadsInternal ( threadAdded ) ; assertEquals ( , events . length ) ; assertEquals ( DebugEvent . CREATE , events [ ] . getKind ( ) ) ; events = target . updateThreadsInternal ( initial ) ; assertEquals ( , events . length ) ; assertEquals ( DebugEvent . TERMINATE , events [ ] . getKind ( ) ) ; ThreadInfo [ ] changed = new ThreadInfo [ ] { new ThreadInfo ( , "" ) } ; events = target . updateThreadsInternal ( changed ) ; assertEquals ( , events . length ) ; assertEquals ( DebugEvent . CHANGE , events [ ] . getKind ( ) ) ; ThreadInfo [ ] addAndRemove = new ThreadInfo [ ] { new ThreadInfo ( , "" ) } ; events = target . updateThreadsInternal ( addAndRemove ) ; assertEquals ( , events . length ) ; assertEquals ( DebugEvent . CREATE , events [ ] . getKind ( ) ) ; assertEquals ( DebugEvent . TERMINATE , events [ ] . getKind ( ) ) ; } } package org . rubypeople . rdt . debug . core . tests ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . io . PipedInputStream ; import java . io . PipedOutputStream ; import java . io . PrintWriter ; import java . util . HashMap ; import junit . framework . TestCase ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . debug . core . RdtDebugModel ; import org . rubypeople . rdt . debug . core . model . IRubyExceptionBreakpoint ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserFactory ; public class FTC_DebuggerProxyTest extends TestCase { private PrintWriter writer ; private RubyDebuggerProxy proxy ; private TestRubyDebugTarget target ; private BufferedReader proxyOutputReader ; public FTC_DebuggerProxyTest ( String name ) { super ( name ) ; } protected PrintWriter getPrintWriter ( ) { return writer ; } public RubyDebuggerProxy getProxy ( ) { return proxy ; } public TestRubyDebugTarget getTarget ( ) { return target ; } public void writeToDebuggerProxy ( String text ) throws Exception { getPrintWriter ( ) . println ( text ) ; getPrintWriter ( ) . flush ( ) ; } public String getLineFromDebuggerProxy ( ) throws IOException { return proxyOutputReader . readLine ( ) ; } public void setUp ( ) throws Exception { target = new TestRubyDebugTarget ( ) ; proxy = new RubyDebuggerProxy ( target , false ) ; PipedInputStream pipedInputStream = new PipedInputStream ( ) ; PipedOutputStream pipedOutputStream = new PipedOutputStream ( pipedInputStream ) ; XmlPullParserFactory factory = XmlPullParserFactory . newInstance ( "" , null ) ; XmlPullParser xpp = factory . newPullParser ( ) ; PipedOutputStream outputStream = new PipedOutputStream ( ) ; PipedInputStream inputStream = new PipedInputStream ( outputStream ) ; xpp . setInput ( new InputStreamReader ( inputStream ) ) ; proxy . startRubyLoop ( ) ; writer = new PrintWriter ( new OutputStreamWriter ( outputStream ) ) ; proxyOutputReader = new BufferedReader ( new InputStreamReader ( pipedInputStream ) ) ; } public void testMultipleBreakpoints ( ) throws Exception { writeToDebuggerProxy ( "" ) ; Thread . sleep ( ) ; assertNotNull ( getTarget ( ) . getLastSuspensionPoint ( ) ) ; assertEquals ( , getTarget ( ) . getLastSuspensionPoint ( ) . getLine ( ) ) ; new Thread ( ) { public void run ( ) { try { Thread . sleep ( ) ; writeToDebuggerProxy ( "" ) ; writeToDebuggerProxy ( "" ) ; } catch ( Exception ex ) { fail ( ) ; } } } . start ( ) ; Thread . sleep ( ) ; assertEquals ( , getTarget ( ) . getLastSuspensionPoint ( ) . getLine ( ) ) ; } public void testExceptionBreakpoint ( ) throws IOException , CoreException { IResource resource = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IRubyExceptionBreakpoint rubyExceptionBreakpoint = RdtDebugModel . createExceptionBreakpoint ( resource , "" , true , new HashMap ( ) ) ; proxy . addBreakpoint ( rubyExceptionBreakpoint ) ; assertEquals ( "" , this . getLineFromDebuggerProxy ( ) ) ; assertEquals ( "" , this . getLineFromDebuggerProxy ( ) ) ; } } package org . rubypeople . rdt . debug . core . tests ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IMarkerDelta ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . debug . core . DebugException ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . model . IBreakpoint ; import org . eclipse . debug . core . model . IDebugTarget ; import org . eclipse . debug . core . model . IMemoryBlock ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . core . model . IThread ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . SuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . model . IRubyDebugTarget ; public class TestRubyDebugTarget implements IRubyDebugTarget { private List < SuspensionPoint > suspensionPoints = new ArrayList < SuspensionPoint > ( ) ; public SuspensionPoint getLastSuspensionPoint ( ) { if ( suspensionPoints . isEmpty ( ) ) { return null ; } return suspensionPoints . get ( suspensionPoints . size ( ) - ) ; } public void setRubyDebuggerProxy ( RubyDebuggerProxy rubyDebuggerProxy ) { } public void suspensionOccurred ( SuspensionPoint suspensionPoint ) { suspensionPoints . add ( suspensionPoint ) ; } public void terminate ( ) { } public void updateThreads ( ) { } public String getName ( ) throws DebugException { return null ; } public IProcess getProcess ( ) { return null ; } public IThread [ ] getThreads ( ) throws DebugException { return null ; } public boolean hasThreads ( ) throws DebugException { return false ; } public boolean supportsBreakpoint ( IBreakpoint breakpoint ) { return false ; } public IDebugTarget getDebugTarget ( ) { return null ; } public ILaunch getLaunch ( ) { return null ; } public String getModelIdentifier ( ) { return null ; } public boolean canTerminate ( ) { return false ; } public boolean isTerminated ( ) { return false ; } public boolean canResume ( ) { return false ; } public boolean canSuspend ( ) { return false ; } public boolean isSuspended ( ) { return false ; } public void resume ( ) throws DebugException { } public void suspend ( ) throws DebugException { } public void breakpointAdded ( IBreakpoint breakpoint ) { } public void breakpointChanged ( IBreakpoint breakpoint , IMarkerDelta delta ) { } public void breakpointRemoved ( IBreakpoint breakpoint , IMarkerDelta delta ) { } public boolean canDisconnect ( ) { return false ; } public void disconnect ( ) throws DebugException { } public boolean isDisconnected ( ) { return false ; } public IMemoryBlock getMemoryBlock ( long startAddress , long length ) throws DebugException { return null ; } public boolean supportsStorageRetrieval ( ) { return false ; } public Object getAdapter ( Class arg0 ) { return null ; } public int getPort ( ) { return - ; } public String getHost ( ) { return "" ; } public RubyDebuggerProxy getRubyDebuggerProxy ( ) { return null ; } public IStatus load ( String filename ) { return null ; } } package org . rubypeople . rdt . debug . core . tests ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_UnitTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_RubyDebugTarget . class ) ; return suite ; } } package org . rubypeople . rdt . debug . core . tests ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; public class OutputRedirectorThread extends Thread { private InputStream inputStream ; private String lastLine = "" ; public OutputRedirectorThread ( InputStream aInputStream ) { inputStream = aInputStream ; } public void run ( ) { System . out . println ( "" ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; String line ; try { while ( ( line = br . readLine ( ) ) != null ) { System . out . println ( "" + line ) ; lastLine = line ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } System . out . println ( "" ) ; } public String getLastLine ( ) { return lastLine ; } } package org . rubypeople . rdt . debug . core . tests ; import java . io . BufferedReader ; import java . io . File ; import java . io . InputStreamReader ; import java . io . PrintWriter ; import java . net . Socket ; import java . text . DecimalFormat ; import java . text . DecimalFormatSymbols ; import java . util . Locale ; public class NonBlockingSocketReader { private Socket socket ; private PrintWriter out ; private BufferedReader reader ; private Process process ; private OutputRedirectorThread rubyStdoutRedirectorThread ; public void setUp ( ) throws Exception { String binDir = this . getClass ( ) . getResource ( "" ) . getFile ( ) ; if ( binDir . startsWith ( "" ) && File . separatorChar == '' ) { binDir = binDir . substring ( ) ; } String cmd = "" + binDir + "" ; System . out . println ( "" + cmd ) ; process = Runtime . getRuntime ( ) . exec ( cmd ) ; rubyStdoutRedirectorThread = new OutputRedirectorThread ( process . getInputStream ( ) ) ; rubyStdoutRedirectorThread . start ( ) ; rubyStdoutRedirectorThread = new OutputRedirectorThread ( process . getErrorStream ( ) ) ; rubyStdoutRedirectorThread . start ( ) ; Thread . sleep ( ) ; socket = new Socket ( "" , ) ; out = new PrintWriter ( socket . getOutputStream ( ) , true ) ; reader = new BufferedReader ( new InputStreamReader ( socket . getInputStream ( ) ) ) ; } protected void tearDown ( ) throws Exception { socket . close ( ) ; process . destroy ( ) ; rubyStdoutRedirectorThread . join ( ) ; } public void printBaseOperationsPerSecond ( ) throws Exception { int operationsPerSecond = Integer . parseInt ( reader . readLine ( ) ) ; System . out . println ( "" + operationsPerSecond ) ; } public void testOperationsPerSecond ( double sleepTime , double blockingTime ) throws Exception { DecimalFormat format = new DecimalFormat ( ) ; format . setMaximumFractionDigits ( ) ; format . setDecimalFormatSymbols ( new DecimalFormatSymbols ( Locale . US ) ) ; out . println ( "" + format . format ( sleepTime ) ) ; out . println ( "" + format . format ( blockingTime ) ) ; out . println ( "" ) ; Thread . sleep ( ) ; out . println ( "" ) ; Thread . sleep ( ) ; int operationsPerSecond = Integer . parseInt ( reader . readLine ( ) ) ; System . out . println ( "" + format . format ( sleepTime ) + "" + format . format ( blockingTime ) + "" + operationsPerSecond ) ; } public static void main ( String [ ] args ) throws Exception { NonBlockingSocketReader test = new NonBlockingSocketReader ( ) ; test . setUp ( ) ; test . printBaseOperationsPerSecond ( ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . testOperationsPerSecond ( , ) ; test . tearDown ( ) ; } } package org . rubypeople . rdt . debug . core . tests ; import junit . framework . Test ; import junit . framework . TestSuite ; public class FTS_Debug { public static Test suite ( ) { TestSuite suite = new TestSuite ( ) ; suite . addTestSuite ( FTC_ClassicDebuggerCommunicationTest . class ) ; suite . addTestSuite ( FTC_DebuggerProxyTest . class ) ; suite . addTestSuite ( FTC_ReadStrategyTest . class ) ; suite . addTestSuite ( FTC_DebuggerLaunch . class ) ; return suite ; } } package org . rubypeople . rdt . debug . core . tests ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . internal . debug . core . commands . AbstractDebuggerConnection ; import org . rubypeople . rdt . internal . debug . core . commands . RubyDebugConnection ; import org . rubypeople . rdt . internal . launching . LaunchingPlugin ; public class FTC_RubyDebugCommunicationTest extends FTC_ClassicDebuggerCommunicationTest { public static junit . framework . TestSuite suite ( ) { junit . framework . TestSuite suite = new junit . framework . TestSuite ( ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; return suite ; } public FTC_RubyDebugCommunicationTest ( String arg0 ) { super ( arg0 ) ; } @ Override public void startRubyProcess ( ) throws Exception { String cmd = "" + getTmpDir ( ) . replace ( '' , '' ) + "" + getRubyTestFilename ( ) ; System . out . println ( "" + cmd ) ; process = Runtime . getRuntime ( ) . exec ( cmd ) ; rubyStderrRedirectorThread = new OutputRedirectorThread ( process . getErrorStream ( ) ) ; rubyStderrRedirectorThread . start ( ) ; rubyStdoutRedirectorThread = new OutputRedirectorThread ( process . getInputStream ( ) ) ; rubyStdoutRedirectorThread . start ( ) ; } protected String getDirectoryOfRubyDebuggerFile ( ) { String result = null ; if ( RubyCore . getPlugin ( ) != null ) { result = RubyCore . getOSDirectory ( LaunchingPlugin . getDefault ( ) ) + "" ; } else { result = LaunchingPlugin . class . getResource ( "" ) . getPath ( ) + "" ; } return result ; } @ Override protected AbstractDebuggerConnection createDebuggerConnection ( ) { return new RubyDebugConnection ( "" , ) ; } } package org . rubypeople . rdt . debug . core . tests ; import junit . framework . Assert ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . XmlStreamReader ; import org . xmlpull . v1 . XmlPullParser ; public class WasteReader extends XmlStreamReader { private String name ; public WasteReader ( XmlPullParser xpp ) { super ( xpp ) ; } public WasteReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } @ Override protected boolean processStartElement ( XmlPullParser xpp ) { name = xpp . getName ( ) ; if ( name . equals ( "" ) ) { String exceptionType = xpp . getAttributeValue ( "" , "" ) ; String exceptionMessage = xpp . getAttributeValue ( "" , "" ) ; Assert . fail ( "" + exceptionType + "" + exceptionMessage ) ; } return checkNAme ( ) ; } private boolean checkNAme ( ) { return name . equals ( "" ) || name . equals ( "" ) || name . equals ( "" ) ; } @ Override public void processContent ( String text ) { if ( name . equals ( "" ) ) { throw new RuntimeException ( "" + text ) ; } } @ Override protected boolean processEndElement ( XmlPullParser xpp ) { name = xpp . getName ( ) ; return checkNAme ( ) ; } } package org . rubypeople . rdt . debug . core . tests ; import org . eclipse . core . runtime . Plugin ; public class RdtDebugTestsPlugin extends Plugin { private static RdtDebugTestsPlugin plugin ; public RdtDebugTestsPlugin ( ) { super ( ) ; plugin = this ; } public static Plugin getDefault ( ) { return plugin ; } } package org . rubypeople . rdt . debug . core . tests ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . PrintWriter ; import junit . framework . TestCase ; import org . rubypeople . rdt . internal . debug . core . ExceptionSuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . StepSuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . SuspensionPoint ; import org . rubypeople . rdt . internal . debug . core . commands . AbstractCommand ; import org . rubypeople . rdt . internal . debug . core . commands . AbstractDebuggerConnection ; import org . rubypeople . rdt . internal . debug . core . commands . BreakpointCommand ; import org . rubypeople . rdt . internal . debug . core . commands . GenericCommand ; import org . rubypeople . rdt . internal . debug . core . commands . StepCommand ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . rubypeople . rdt . internal . debug . core . model . RubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyThread ; import org . rubypeople . rdt . internal . debug . core . model . RubyVariable ; import org . rubypeople . rdt . internal . debug . core . model . ThreadInfo ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . BreakpointModificationReader ; import org . rubypeople . rdt . internal . debug . core . parsing . EvalReader ; import org . rubypeople . rdt . internal . debug . core . parsing . FramesReader ; import org . rubypeople . rdt . internal . debug . core . parsing . LoadResultReader ; import org . rubypeople . rdt . internal . debug . core . parsing . SuspensionReader ; import org . rubypeople . rdt . internal . debug . core . parsing . ThreadInfoReader ; import org . rubypeople . rdt . internal . debug . core . parsing . VariableReader ; public abstract class FTC_AbstractDebuggerCommunicationTest extends TestCase { private static final boolean VERBOSE = false ; private static String tmpDir ; protected static String getTmpDir ( ) { if ( tmpDir == null ) { tmpDir = System . getProperty ( "" ) ; if ( tmpDir . charAt ( tmpDir . length ( ) - ) != File . separatorChar ) { tmpDir = tmpDir + File . separator ; } } return tmpDir ; } public static String RUBY_INTERPRETER ; static { RUBY_INTERPRETER = System . getProperty ( "" ) ; if ( RUBY_INTERPRETER == null ) { RUBY_INTERPRETER = "" ; } } private static long TIMEOUT_MS = ; protected Process process ; protected OutputRedirectorThread rubyStdoutRedirectorThread ; protected OutputRedirectorThread rubyStderrRedirectorThread ; private AbstractDebuggerConnection debuggerConnection ; private Thread mainThread ; private Thread timeoutThread ; private AbstractReadStrategy readStrategy ; public FTC_AbstractDebuggerCommunicationTest ( String arg0 ) { super ( arg0 ) ; } public static void main ( String [ ] args ) { junit . textui . TestRunner . run ( FTC_ClassicDebuggerCommunicationTest . class ) ; } protected String getTestFilename ( ) { return getTmpDir ( ) + "" ; } protected String getRubyTestFilename ( ) { return getTestFilename ( ) . replace ( '' , '' ) ; } protected SuspensionReader getSuspensionReader ( ) throws Exception { return new SuspensionReader ( readStrategy ) ; } protected VariableReader getVariableReader ( ) throws Exception { return new VariableReader ( readStrategy ) ; } protected EvalReader getEvalExceptionReader ( ) throws Exception { return new EvalReader ( readStrategy ) ; } protected FramesReader getFramesReader ( ) throws Exception { return new FramesReader ( readStrategy ) ; } protected ThreadInfoReader getThreadInfoReader ( ) throws Exception { return new ThreadInfoReader ( readStrategy ) ; } protected LoadResultReader getLoadResultReader ( ) throws Exception { return new LoadResultReader ( readStrategy ) ; } protected EvalReader getEvalReader ( ) throws Exception { return new EvalReader ( readStrategy ) ; } protected BreakpointModificationReader getBreakpointAddedReader ( ) throws Exception { return new BreakpointModificationReader ( readStrategy ) ; } protected String getOSIndependent ( String path ) { return path . replace ( '' , '' ) ; } public void setUp ( ) throws Exception { if ( ! new File ( getTmpDir ( ) ) . exists ( ) || ! new File ( getTmpDir ( ) ) . isDirectory ( ) ) { throw new RuntimeException ( "" + getTmpDir ( ) ) ; } mainThread = Thread . currentThread ( ) ; timeoutThread = new Thread ( ) { public void run ( ) { try { while ( true ) { log ( "" ) ; Thread . sleep ( TIMEOUT_MS ) ; log ( "" ) ; mainThread . interrupt ( ) ; } } catch ( InterruptedException e ) { log ( "" ) ; } } } ; timeoutThread . start ( ) ; log ( "" ) ; } public void tearDown ( ) { log ( "" ) ; timeoutThread . interrupt ( ) ; if ( process == null ) { return ; } try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } try { debuggerConnection . exit ( ) ; } catch ( IOException e ) { log ( "" ) ; e . printStackTrace ( ) ; } try { if ( process . exitValue ( ) != ) { log ( "" + process . exitValue ( ) ) ; } } catch ( IllegalThreadStateException ex ) { process . destroy ( ) ; log ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { log ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e1 ) { log ( "" ) ; } } } log ( "" ) ; try { rubyStdoutRedirectorThread . join ( ) ; } catch ( InterruptedException e ) { log ( "" ) ; e . printStackTrace ( ) ; } log ( "" ) ; log ( "" ) ; try { rubyStderrRedirectorThread . join ( ) ; } catch ( InterruptedException e ) { log ( "" ) ; e . printStackTrace ( ) ; } log ( "" ) ; } protected void writeFile ( String name , String [ ] content ) throws Exception { PrintWriter writer = new PrintWriter ( new FileOutputStream ( getTmpDir ( ) + name ) ) ; for ( int i = ; i < content . length ; i ++ ) { writer . println ( content [ i ] ) ; } writer . close ( ) ; } protected abstract AbstractDebuggerConnection createDebuggerConnection ( ) ; protected abstract void startRubyProcess ( ) throws Exception ; protected void createSocket ( String [ ] lines ) throws Exception { writeFile ( "" , lines ) ; startRubyProcess ( ) ; Thread . sleep ( ) ; debuggerConnection = createDebuggerConnection ( ) ; debuggerConnection . connect ( ) ; } protected SuspensionReader startDebugger ( ) throws Exception { return debuggerConnection . start ( ) ; } protected void sendCommand ( AbstractCommand command ) throws Exception { command . execute ( debuggerConnection ) ; } protected void sendRuby ( String debuggerCommand ) throws Exception { try { process . exitValue ( ) ; throw new RuntimeException ( "" ) ; } catch ( IllegalThreadStateException ex ) { GenericCommand command = new GenericCommand ( debuggerCommand , false ) ; command . execute ( debuggerConnection ) ; readStrategy = command . getReadStrategy ( ) ; } } protected void runToLine ( int lineNumber ) throws Exception { runTo ( "" , lineNumber ) ; } private void runTo ( String filename , int lineNumber ) throws Exception { setBreakpoint ( filename , lineNumber ) ; SuspensionReader reader ; if ( ! debuggerConnection . isStarted ( ) ) { reader = debuggerConnection . start ( ) ; } else { StepCommand stepCommand = new StepCommand ( "" ) ; stepCommand . execute ( debuggerConnection ) ; reader = stepCommand . getSuspensionReader ( ) ; } SuspensionPoint hit = reader . readSuspension ( ) ; assertNotNull ( hit ) ; assertTrue ( hit . isBreakpoint ( ) ) ; assertEquals ( lineNumber , hit . getLine ( ) ) ; } private void setBreakpoint ( String filename , int line ) throws Exception { String command = "" + filename + "" + line ; new BreakpointCommand ( command ) . executeWithResult ( debuggerConnection ) ; } private void setBreakpoint ( int line ) throws Exception { setBreakpoint ( "" , line ) ; } public void testBreakpointOnFirstLine ( ) throws Exception { createSocket ( new String [ ] { "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; } public void testBreakpointAddAndRemove ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" } ) ; int breakpointId1 = new BreakpointCommand ( "" ) . executeWithResult ( debuggerConnection ) ; assertEquals ( , breakpointId1 ) ; int breakpointId2 = new BreakpointCommand ( "" ) . executeWithResult ( debuggerConnection ) ; assertEquals ( , breakpointId2 ) ; SuspensionPoint hit1 = startDebugger ( ) . readSuspension ( ) ; assertBreakpoint ( hit1 , "" , ) ; SuspensionPoint hit2 = new StepCommand ( "" ) . readSuspension ( debuggerConnection ) ; assertBreakpoint ( hit2 , "" , ) ; SuspensionPoint hit3 = new StepCommand ( "" ) . readSuspension ( debuggerConnection ) ; assertBreakpoint ( hit3 , "" , ) ; int idDeleted = new BreakpointCommand ( "" ) . executeWithResult ( debuggerConnection ) ; assertEquals ( - , idDeleted ) ; idDeleted = new BreakpointCommand ( "" ) . executeWithResult ( debuggerConnection ) ; assertEquals ( , idDeleted ) ; SuspensionPoint hit4 = new StepCommand ( "" ) . readSuspension ( debuggerConnection ) ; assertBreakpoint ( hit4 , "" , ) ; SuspensionPoint hit5 = new StepCommand ( "" ) . readSuspension ( debuggerConnection ) ; assertNull ( "" + hit5 , hit5 ) ; } public void testSimpleCycleSteppingWorks ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" } ) ; int breakpointId1 = new BreakpointCommand ( "" ) . executeWithResult ( debuggerConnection ) ; assertEquals ( , breakpointId1 ) ; int breakpointId2 = new BreakpointCommand ( "" ) . executeWithResult ( debuggerConnection ) ; assertEquals ( , breakpointId2 ) ; SuspensionReader reader = startDebugger ( ) ; assertBreakpoint ( reader . readSuspension ( ) , "" , ) ; sendRuby ( "" ) ; assertBreakpoint ( getSuspensionReader ( ) . readSuspension ( ) , "" , ) ; sendRuby ( "" ) ; assertBreakpoint ( getSuspensionReader ( ) . readSuspension ( ) , "" , ) ; sendRuby ( "" ) ; SuspensionPoint hit = getSuspensionReader ( ) . readSuspension ( ) ; assertNull ( "" + hit , hit ) ; } public void testStoppingOnOneLineTwice ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" } ) ; sendRuby ( "" ) ; assertEquals ( , getBreakpointAddedReader ( ) . readBreakpointNo ( ) ) ; sendRuby ( "" ) ; assertEquals ( , getBreakpointAddedReader ( ) . readBreakpointNo ( ) ) ; sendRuby ( "" ) ; assertBreakpoint ( getSuspensionReader ( ) . readSuspension ( ) , "" , ) ; sendRuby ( "" ) ; assertBreakpoint ( getSuspensionReader ( ) . readSuspension ( ) , "" , ) ; sendRuby ( "" ) ; assertBreakpoint ( getSuspensionReader ( ) . readSuspension ( ) , "" , ) ; sendRuby ( "" ) ; assertBreakpoint ( getSuspensionReader ( ) . readSuspension ( ) , "" , ) ; sendRuby ( "" ) ; assertBreakpoint ( getSuspensionReader ( ) . readSuspension ( ) , "" , ) ; sendRuby ( "" ) ; SuspensionPoint hit = getSuspensionReader ( ) . readSuspension ( ) ; assertNull ( "" + hit , hit ) ; } public void assertBreakpoint ( SuspensionPoint hit , String file , int line ) { assertNotNull ( hit ) ; assertTrue ( hit . isBreakpoint ( ) ) ; assertEquals ( line , hit . getLine ( ) ) ; assertEquals ( file , hit . getFile ( ) ) ; } public void testException ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; GenericCommand catchCommand = new GenericCommand ( "" , true ) ; catchCommand . execute ( debuggerConnection ) ; SuspensionPoint hit = startDebugger ( ) . readSuspension ( ) ; assertNotNull ( hit ) ; assertEquals ( , hit . getLine ( ) ) ; assertEquals ( getOSIndependent ( getTmpDir ( ) + "" ) , hit . getFile ( ) ) ; assertTrue ( hit . isException ( ) ) ; assertEquals ( "" , ( ( ExceptionSuspensionPoint ) hit ) . getExceptionMessage ( ) ) ; assertEquals ( "" , ( ( ExceptionSuspensionPoint ) hit ) . getExceptionType ( ) ) ; sendRuby ( "" ) ; sendRuby ( "" ) ; } public void testExceptionsIgnoredByDefault ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; SuspensionPoint hit = startDebugger ( ) . readSuspension ( ) ; assertNull ( hit ) ; } public void testExceptionHierarchy ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" } ) ; GenericCommand catchCommand = new GenericCommand ( "" , true ) ; catchCommand . execute ( debuggerConnection ) ; SuspensionPoint hit = startDebugger ( ) . readSuspension ( ) ; assertNotNull ( hit ) ; assertEquals ( , hit . getLine ( ) ) ; assertEquals ( "" , ( ( ExceptionSuspensionPoint ) hit ) . getExceptionType ( ) ) ; sendRuby ( "" ) ; hit = getSuspensionReader ( ) . readSuspension ( ) ; assertNull ( hit ) ; } public void testBreakpointNeverReached ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; new BreakpointCommand ( "" ) . executeWithResult ( debuggerConnection ) ; log ( "" ) ; SuspensionPoint hit = startDebugger ( ) . readSuspension ( ) ; assertNull ( hit ) ; } private void log ( String string ) { if ( VERBOSE ) System . out . println ( string ) ; } public void testStepOver ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; BreakpointCommand breakpointCommand = new BreakpointCommand ( "" ) ; sendCommand ( breakpointCommand ) ; breakpointCommand . getBreakpointAddedReader ( ) . readBreakpointNo ( ) ; startDebugger ( ) . readSuspension ( ) ; SuspensionPoint info = new StepCommand ( "" ) . readSuspension ( debuggerConnection ) ; assertEquals ( , info . getLine ( ) ) ; assertEquals ( getOSIndependent ( getTmpDir ( ) + "" ) , info . getFile ( ) ) ; assertTrue ( info . isStep ( ) ) ; assertEquals ( , ( ( StepSuspensionPoint ) info ) . getFramesNumber ( ) ) ; info = new StepCommand ( "" ) . readSuspension ( debuggerConnection ) ; assertNull ( info ) ; } public void testStepOverFrames ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; writeFile ( "" , new String [ ] { "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; SuspensionPoint info = getSuspensionReader ( ) . readSuspension ( ) ; assertEquals ( , info . getLine ( ) ) ; assertEquals ( getOSIndependent ( getTmpDir ( ) + "" ) , info . getFile ( ) ) ; assertTrue ( info . isStep ( ) ) ; assertEquals ( , ( ( StepSuspensionPoint ) info ) . getFramesNumber ( ) ) ; sendRuby ( "" ) ; info = getSuspensionReader ( ) . readSuspension ( ) ; assertNull ( info ) ; } public void testStepOverInDifferentFrame ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; writeFile ( "" , new String [ ] { "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; SuspensionPoint info = getSuspensionReader ( ) . readSuspension ( ) ; assertEquals ( , info . getLine ( ) ) ; assertEquals ( getOSIndependent ( getTmpDir ( ) + "" ) , info . getFile ( ) ) ; assertTrue ( info . isStep ( ) ) ; assertEquals ( , ( ( StepSuspensionPoint ) info ) . getFramesNumber ( ) ) ; sendRuby ( "" ) ; } public void testStepReturn ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; writeFile ( "" , new String [ ] { "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; SuspensionPoint info = getSuspensionReader ( ) . readSuspension ( ) ; assertEquals ( , info . getLine ( ) ) ; assertEquals ( getOSIndependent ( getTmpDir ( ) + "" ) , info . getFile ( ) ) ; assertTrue ( info . isStep ( ) ) ; assertEquals ( , ( ( StepSuspensionPoint ) info ) . getFramesNumber ( ) ) ; sendRuby ( "" ) ; } public void testHitBreakpointWhileSteppingOver ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; writeFile ( "" , new String [ ] { "" , "" , "" , "" , "" , "" } ) ; new BreakpointCommand ( "" ) . executeWithResult ( debuggerConnection ) ; runTo ( "" , ) ; sendRuby ( "" ) ; SuspensionPoint info = getSuspensionReader ( ) . readSuspension ( ) ; assertEquals ( , info . getLine ( ) ) ; assertEquals ( "" , info . getFile ( ) ) ; assertTrue ( info . isBreakpoint ( ) ) ; sendRuby ( "" ) ; } public void testStepInto ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; writeFile ( "" , new String [ ] { "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; SuspensionPoint info = getSuspensionReader ( ) . readSuspension ( ) ; assertEquals ( , info . getLine ( ) ) ; assertEquals ( getOSIndependent ( getTmpDir ( ) + "" ) , info . getFile ( ) ) ; assertTrue ( info . isStep ( ) ) ; assertEquals ( , ( ( StepSuspensionPoint ) info ) . getFramesNumber ( ) ) ; sendRuby ( "" ) ; } protected RubyStackFrame createStackFrame ( ) throws Exception { RubyStackFrame stackFrame = new RubyStackFrame ( null , "" , , ) ; return stackFrame ; } public void testCommandList ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , , variables . length ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; } public void testVariableNil ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( null , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testVariableWithXmlContent ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertTrue ( variables [ ] . isLocal ( ) ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; sendRuby ( "" ) ; } public void testVariableInObject ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( ! variables [ ] . isStatic ( ) ) ; assertTrue ( ! variables [ ] . isLocal ( ) ) ; assertTrue ( variables [ ] . isInstance ( ) ) ; assertTrue ( ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testStaticVariables ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertTrue ( variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( variables [ ] . isStatic ( ) ) ; assertTrue ( ! variables [ ] . isLocal ( ) ) ; assertTrue ( ! variables [ ] . isInstance ( ) ) ; assertTrue ( ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testSingletonStaticVariables ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( variables [ ] . isStatic ( ) ) ; assertTrue ( ! variables [ ] . isLocal ( ) ) ; assertTrue ( ! variables [ ] . isInstance ( ) ) ; assertTrue ( ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testConstants ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( variables [ ] . isConstant ( ) ) ; assertTrue ( ! variables [ ] . isStatic ( ) ) ; assertTrue ( ! variables [ ] . isLocal ( ) ) ; assertTrue ( ! variables [ ] . isInstance ( ) ) ; assertTrue ( ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testConstantDefinedInBothClassAndSuperclass ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( variables [ ] . isConstant ( ) ) ; assertTrue ( ! variables [ ] . isStatic ( ) ) ; assertTrue ( ! variables [ ] . isLocal ( ) ) ; assertTrue ( ! variables [ ] . isInstance ( ) ) ; assertTrue ( ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testVariableString ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testVariableLocal ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] localVariables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , localVariables . length ) ; RubyVariable userVariable = localVariables [ ] ; sendRuby ( "" + userVariable . getObjectId ( ) ) ; RubyVariable [ ] userVariables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , userVariables . length ) ; assertEquals ( "" , userVariables [ ] . getName ( ) ) ; assertEquals ( "" , userVariables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , userVariables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( ! userVariables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testVariableInstance ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; writeFile ( "" , new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertTrue ( ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testVariableArray ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertTrue ( "" , variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; RubyVariable [ ] elements = getVariableReader ( ) . readVariables ( variables [ ] ) ; assertEquals ( , elements . length ) ; assertEquals ( "" , elements [ ] . getName ( ) ) ; assertEquals ( "" , elements [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , elements [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertEquals ( "" , elements [ ] . getQualifiedName ( ) ) ; sendRuby ( "" ) ; } public void testVariableHashWithStringKeys ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertTrue ( "" , variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; RubyVariable [ ] elements = getVariableReader ( ) . readVariables ( variables [ ] ) ; assertEquals ( , elements . length ) ; assertEquals ( "" , elements [ ] . getName ( ) ) ; assertEquals ( "" , elements [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , elements [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertEquals ( "" , elements [ ] . getQualifiedName ( ) ) ; sendRuby ( "" ) ; } public void testVariableHashWithObjectKeys ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertTrue ( "" , variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" + variables [ ] . getObjectId ( ) ) ; RubyVariable [ ] elements = getVariableReader ( ) . readVariables ( variables [ ] ) ; assertEquals ( , elements . length ) ; assertEquals ( "" , elements [ ] . getName ( ) ) ; assertEquals ( "" , elements [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; sendRuby ( "" + elements [ ] . getObjectId ( ) ) ; RubyVariable [ ] values = getVariableReader ( ) . readVariables ( variables [ ] ) ; assertEquals ( , values . length ) ; assertEquals ( "" , values [ ] . getName ( ) ) ; assertEquals ( "" , values [ ] . getValue ( ) . getReferenceTypeName ( ) ) ; assertEquals ( "" , values [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; } public void testVariableArrayEmpty ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertTrue ( "" , ! variables [ ] . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testVariableInstanceNested ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; RubyVariable test2Variable = variables [ ] ; assertEquals ( "" , test2Variable . getName ( ) ) ; assertEquals ( "" , test2Variable . getQualifiedName ( ) ) ; sendRuby ( "" + test2Variable . getQualifiedName ( ) ) ; variables = getVariableReader ( ) . readVariables ( test2Variable ) ; assertEquals ( , variables . length ) ; RubyVariable privateTestVariable = variables [ ] ; assertEquals ( "" , privateTestVariable . getName ( ) ) ; assertEquals ( "" , privateTestVariable . getQualifiedName ( ) ) ; assertTrue ( privateTestVariable . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" + privateTestVariable . getQualifiedName ( ) ) ; variables = getVariableReader ( ) . readVariables ( privateTestVariable ) ; assertEquals ( , variables . length ) ; RubyVariable privateTestprivateTestVariable = variables [ ] ; assertEquals ( "" , privateTestprivateTestVariable . getName ( ) ) ; assertEquals ( "" , privateTestprivateTestVariable . getQualifiedName ( ) ) ; assertEquals ( "" , privateTestprivateTestVariable . getValue ( ) . getValueString ( ) ) ; assertTrue ( ! privateTestprivateTestVariable . getValue ( ) . hasVariables ( ) ) ; sendRuby ( "" ) ; } public void testInspect ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , , variables . length ) ; assertEquals ( "" , "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , , variables . length ) ; assertEquals ( "" , "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , , variables . length ) ; assertEquals ( "" , "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; } public void testInspectTemporaryArray ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , , variables . length ) ; sendRuby ( "" ) ; RubyVariable [ ] gcResult = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , , gcResult . length ) ; sendRuby ( "" + variables [ ] . getObjectId ( ) ) ; RubyVariable [ ] elements = getVariableReader ( ) . readVariables ( variables [ ] ) ; assertEquals ( "" , , elements . length ) ; sendRuby ( "" ) ; } public void testInspectNil ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( "" , , variables . length ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; } public void testSendCommandWithSpecialCharacters ( ) throws Exception { sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; sendRuby ( "" ) ; } public void testInspectError ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; try { getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; fail ( "" ) ; } catch ( RubyProcessingException e ) { assertNotNull ( e . getMessage ( ) ) ; assertFalse ( e . getMessage ( ) . indexOf ( "" ) > - ) ; sendRuby ( "" ) ; } } public void testInspectTimeout ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; try { getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; fail ( "" ) ; } catch ( RubyProcessingException e ) { assertTrue ( e . getMessage ( ) . indexOf ( "" ) > - ) ; sendRuby ( "" ) ; } } public void testEvalError ( ) throws Exception { createSocket ( new String [ ] { "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; try { getEvalReader ( ) . readEvalResult ( ) ; } catch ( RubyProcessingException e ) { assertNotNull ( e . getMessage ( ) ) ; sendRuby ( "" ) ; return ; } fail ( "" ) ; } public void testStaticVariableInstanceNested ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" } ) ; runToLine ( ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertTrue ( "" , variables [ ] . getValue ( ) . hasVariables ( ) ) ; } public void testVariablesInFrames ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" } ) ; writeFile ( "" , new String [ ] { "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; sendRuby ( "" ) ; variables = getVariableReader ( ) . readVariables ( createStackFrame ( ) ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getValue ( ) . getValueString ( ) ) ; } public void testFrames ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" } ) ; writeFile ( "" , new String [ ] { "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; sendRuby ( "" ) ; getBreakpointAddedReader ( ) . readBreakpointNo ( ) ; sendRuby ( "" ) ; RubyThread thread = new RubyThread ( null , , "" ) ; getFramesReader ( ) . readFrames ( thread ) ; assertEquals ( , thread . getStackFrames ( ) . length ) ; RubyStackFrame frame1 = ( RubyStackFrame ) thread . getStackFrames ( ) [ ] ; assertEquals ( getOSIndependent ( getTmpDir ( ) + "" ) , frame1 . getFileName ( ) ) ; assertEquals ( , frame1 . getIndex ( ) ) ; assertEquals ( , frame1 . getLineNumber ( ) ) ; RubyStackFrame frame2 = ( RubyStackFrame ) thread . getStackFrames ( ) [ ] ; assertEquals ( getOSIndependent ( getTmpDir ( ) + "" ) , frame2 . getFileName ( ) ) ; assertEquals ( , frame2 . getIndex ( ) ) ; assertEquals ( , frame2 . getLineNumber ( ) ) ; sendRuby ( "" ) ; getSuspensionReader ( ) . readSuspension ( ) ; sendRuby ( "" ) ; getFramesReader ( ) . readFrames ( thread ) ; assertEquals ( , thread . getStackFramesSize ( ) ) ; sendRuby ( "" ) ; } public void testFramesWhenThreadSpawned ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" , "" } ) ; runTo ( "" , ) ; RubyThread thread = new RubyThread ( null , , "" ) ; sendRuby ( "" ) ; getFramesReader ( ) . readFrames ( thread ) ; assertEquals ( , thread . getStackFramesSize ( ) ) ; } public void testThreadFramesAndVariables ( ) throws Exception { createSocket ( new String [ ] { "" , "" , "" , "" , "" , "" , "" } ) ; setBreakpoint ( ) ; runToLine ( ) ; sendRuby ( "" ) ; ThreadInfo [ ] threads = getThreadInfoReader ( ) . readThreads ( ) ; sendRuby ( "" ) ; getSuspensionReader ( ) . readSuspension ( ) ; getSuspensionReader ( ) . readSuspension ( ) ; sendRuby ( "" ) ; threads = getThreadInfoReader ( ) . readThreads ( ) ; assertEquals ( , threads . length ) ; sendRuby ( "" + threads [ ] . getId ( ) + "" ) ; RubyStackFrame [ ] stackFrames = getFramesReader ( ) . readFrames ( new RubyThread ( null , , "" ) ) ; assertEquals ( , stackFrames . length ) ; assertEquals ( , stackFrames [ ] . getLineNumber ( ) ) ; sendRuby ( "" + threads [ ] . getId ( ) + "" ) ; RubyVariable [ ] variables = getVariableReader ( ) . readVariables ( stackFrames [ ] ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; sendRuby ( "" + threads [ ] . getId ( ) + "" ) ; stackFrames = getFramesReader ( ) . readFrames ( new RubyThread ( null , , "" ) ) ; assertEquals ( , stackFrames . length ) ; assertEquals ( , stackFrames [ ] . getLineNumber ( ) ) ; sendRuby ( "" + threads [ ] . getId ( ) + "" ) ; variables = getVariableReader ( ) . readVariables ( stackFrames [ ] ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; sendRuby ( "" ) ; getSuspensionReader ( ) . readSuspension ( ) ; sendRuby ( "" + threads [ ] . getId ( ) + "" ) ; variables = getVariableReader ( ) . readVariables ( stackFrames [ ] ) ; assertEquals ( , variables . length ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; assertEquals ( "" , variables [ ] . getName ( ) ) ; } } package org . rubypeople . rdt . debug . core . tests ; import org . rubypeople . rdt . internal . debug . core . parsing . AbstractReadStrategy ; import org . rubypeople . rdt . internal . debug . core . parsing . XmlStreamReader ; import org . xmlpull . v1 . XmlPullParser ; public class TestXmlStreamReader extends XmlStreamReader { private int tagReadCount = ; private String tag ; public TestXmlStreamReader ( XmlPullParser xpp ) { super ( xpp ) ; } public TestXmlStreamReader ( AbstractReadStrategy readStrategy ) { super ( readStrategy ) ; } protected boolean processStartElement ( XmlPullParser xpp ) { System . out . println ( "" + xpp . getName ( ) ) ; if ( xpp . getName ( ) . equals ( tag ) ) { tagReadCount += ; return true ; } return false ; } public boolean isTagRead ( ) { return tagReadCount >= ; } public void resetTagReadCount ( ) { this . tagReadCount = ; } public int getTagReadCount ( ) { return this . tagReadCount ; } public String getTag ( ) { return tag ; } public void acceptTag ( String tag ) { this . tag = tag ; } } package org . rubypeople . rdt . debug . core . tests ; import junit . framework . TestSuite ; public class FTC_Single extends TestSuite { public static junit . framework . TestSuite suite ( ) { TestSuite suite = new TestSuite ( ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; return suite ; } public static TestSuite classicSuite ( ) { TestSuite suite = new TestSuite ( ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_ClassicDebuggerCommunicationTest ( "" ) ) ; return suite ; } public static TestSuite rdebugSuite ( ) { TestSuite suite = new TestSuite ( ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; suite . addTest ( new FTC_RubyDebugCommunicationTest ( "" ) ) ; return suite ; } } package org . rubypeople . rdt . debug . core . tests ; import java . io . ByteArrayInputStream ; import java . io . File ; import java . util . HashMap ; import junit . framework . TestCase ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . model . IProcess ; import org . rubypeople . eclipse . testutils . ResourceTools ; import org . rubypeople . rdt . debug . core . RdtDebugModel ; import org . rubypeople . rdt . internal . launching . RubyLaunchConfigurationAttribute ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; public class FTC_DebuggerLaunch extends TestCase { private static final String RUBY_INTERPRETER_ID = "" ; private static final String VM_TYPE_ID = "" ; private static final boolean VERBOSE = false ; private IVMInstallType vmType ; public void setUp ( ) { vmType = RubyRuntime . getVMInstallType ( VM_TYPE_ID ) ; String rubyInterpreterPath = FTC_ClassicDebuggerCommunicationTest . RUBY_INTERPRETER ; log ( "" + rubyInterpreterPath ) ; VMStandin standin = new VMStandin ( vmType , RUBY_INTERPRETER_ID ) ; standin . setInstallLocation ( new File ( rubyInterpreterPath ) ) ; standin . convertToRealVM ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; vmType . disposeVMInstall ( RUBY_INTERPRETER_ID ) ; } protected void log ( String label , ILaunch launch ) throws Exception { log ( "" + label + "" ) ; IProcess process = launch . getProcesses ( ) [ ] ; if ( process . isTerminated ( ) ) { log ( "" + process . getExitValue ( ) ) ; } else { log ( "" ) ; } String error = process . getStreamsProxy ( ) . getErrorStreamMonitor ( ) . getContents ( ) ; if ( error != null && error . length ( ) > ) { log ( "" + error ) ; } String stdout = process . getStreamsProxy ( ) . getOutputStreamMonitor ( ) . getContents ( ) ; if ( stdout != null && stdout . length ( ) > ) { log ( "" + stdout ) ; } } private void log ( String message ) { if ( VERBOSE ) System . out . println ( message ) ; } public void testTwoSessions ( ) throws Exception { ILaunchConfigurationType lcT = DebugPlugin . getDefault ( ) . getLaunchManager ( ) . getLaunchConfigurationType ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ; ILaunchConfigurationWorkingCopy wc = lcT . newInstance ( null , "" ) ; IProject project = ResourceTools . createProject ( "" ) ; IFile rubyFile = project . getFile ( "" ) ; rubyFile . create ( new ByteArrayInputStream ( "" . getBytes ( ) ) , true , new NullProgressMonitor ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , rubyFile . getProject ( ) . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , rubyFile . getProjectRelativePath ( ) . toString ( ) ) ; wc . setAttribute ( RubyLaunchConfigurationAttribute . SELECTED_INTERPRETER , RUBY_INTERPRETER_ID ) ; ILaunchConfiguration lc = wc . doSave ( ) ; RdtDebugModel . createLineBreakpoint ( rubyFile , rubyFile . getName ( ) , "" , , true , new HashMap ( ) ) ; ILaunch launch = lc . launch ( "" , new NullProgressMonitor ( ) ) ; Thread . sleep ( ) ; this . log ( "" , launch ) ; assertNotNull ( "" , launch . getDebugTarget ( ) ) ; assertNotNull ( "" , launch . getDebugTarget ( ) . getThreads ( ) ) ; assertTrue ( "" , launch . getDebugTarget ( ) . getThreads ( ) . length > ) ; assertTrue ( "" , launch . getDebugTarget ( ) . getThreads ( ) [ ] . isSuspended ( ) ) ; RdtDebugModel . createLineBreakpoint ( rubyFile , rubyFile . getName ( ) , "" , , true , new HashMap ( ) ) ; ILaunch secondlaunch = lc . launch ( "" , new NullProgressMonitor ( ) ) ; Thread . sleep ( ) ; this . log ( "" , secondlaunch ) ; assertNotNull ( "" , secondlaunch . getDebugTarget ( ) ) ; assertNotNull ( "" , secondlaunch . getDebugTarget ( ) . getThreads ( ) ) ; assertTrue ( "" , secondlaunch . getDebugTarget ( ) . getThreads ( ) . length > ) ; assertFalse ( "" , secondlaunch . getProcesses ( ) [ ] . isTerminated ( ) ) ; assertTrue ( "" , secondlaunch . getDebugTarget ( ) . getThreads ( ) [ ] . isSuspended ( ) ) ; } } package org . rubypeople . rdt . debug . core . tests ; import java . io . InputStreamReader ; import java . io . OutputStreamWriter ; import java . io . PipedInputStream ; import java . io . PipedOutputStream ; import java . io . PrintWriter ; import junit . framework . TestCase ; import org . rubypeople . rdt . internal . debug . core . parsing . MultiReaderStrategy ; import org . xmlpull . v1 . XmlPullParser ; import org . xmlpull . v1 . XmlPullParserFactory ; public class FTC_ReadStrategyTest extends TestCase { protected PrintWriter writer ; protected XmlPullParser xpp ; public FTC_ReadStrategyTest ( String name ) { super ( name ) ; } public void setUp ( ) throws Exception { XmlPullParserFactory factory = XmlPullParserFactory . newInstance ( "" , null ) ; xpp = factory . newPullParser ( ) ; PipedOutputStream outputStream = new PipedOutputStream ( ) ; PipedInputStream inputStream = new PipedInputStream ( outputStream ) ; xpp . setInput ( new InputStreamReader ( inputStream ) ) ; writer = new PrintWriter ( new OutputStreamWriter ( outputStream ) ) ; } public void testSingleReaderStrategy ( ) throws Exception { final TestXmlStreamReader reader = new TestXmlStreamReader ( xpp ) ; reader . acceptTag ( "" ) ; Thread testTagReaderThread = new Thread ( ) { public void run ( ) { try { reader . read ( ) ; } catch ( Exception ex ) { } } } ; testTagReaderThread . start ( ) ; writer . println ( "" ) ; writer . flush ( ) ; testTagReaderThread . join ( ) ; assertTrue ( "" , reader . isTagRead ( ) ) ; } public void testMultiReaderStrategy ( ) throws Exception { MultiReaderStrategy multiReaderStrategy = new MultiReaderStrategy ( xpp ) ; final TestXmlStreamReader testTagReader = new TestXmlStreamReader ( multiReaderStrategy ) ; testTagReader . acceptTag ( "" ) ; Thread testTagReaderThread = new Thread ( ) { public void run ( ) { try { testTagReader . read ( ) ; } catch ( Exception ex ) { } } } ; testTagReaderThread . start ( ) ; final TestXmlStreamReader breakpointReader = new TestXmlStreamReader ( multiReaderStrategy ) ; breakpointReader . acceptTag ( "" ) ; Thread breakpointReaderThread = new Thread ( ) { public void run ( ) { try { breakpointReader . read ( ) ; } catch ( Exception ex ) { } } } ; breakpointReaderThread . start ( ) ; Thread . sleep ( ) ; assertTrue ( testTagReaderThread . isAlive ( ) ) ; assertTrue ( breakpointReaderThread . isAlive ( ) ) ; writer . println ( "" ) ; writer . flush ( ) ; testTagReaderThread . join ( ) ; assertTrue ( "" , testTagReader . isTagRead ( ) ) ; assertTrue ( "" , ! breakpointReader . isTagRead ( ) ) ; assertTrue ( "" , breakpointReaderThread . isAlive ( ) ) ; writer . println ( "" ) ; writer . flush ( ) ; breakpointReaderThread . join ( ) ; assertTrue ( "" , breakpointReader . isTagRead ( ) ) ; } public void testMultiReaderStrategyWithMultipleTags ( ) throws Exception { MultiReaderStrategy multiReaderStrategy = new MultiReaderStrategy ( xpp ) ; final TestXmlStreamReader testTagReader = new TestXmlStreamReader ( multiReaderStrategy ) ; testTagReader . acceptTag ( "" ) ; Thread testTagReaderThread = new Thread ( ) { public void run ( ) { try { testTagReader . read ( ) ; } catch ( Exception ex ) { } } } ; testTagReaderThread . start ( ) ; Thread . sleep ( ) ; writer . println ( "" ) ; writer . flush ( ) ; testTagReaderThread . join ( ) ; assertEquals ( "" , , testTagReader . getTagReadCount ( ) ) ; } public void testMultiReaderStrategyDontMissTag ( ) throws Exception { writer . println ( "" ) ; writer . flush ( ) ; MultiReaderStrategy multiReaderStrategy = new MultiReaderStrategy ( xpp ) ; final TestXmlStreamReader testTagReader = new TestXmlStreamReader ( multiReaderStrategy ) ; testTagReader . acceptTag ( "" ) ; Thread testTagReaderThread = new Thread ( ) { public void run ( ) { try { testTagReader . read ( ) ; } catch ( Exception ex ) { fail ( ) ; } } } ; Thread . sleep ( ) ; testTagReaderThread . start ( ) ; Thread . sleep ( ) ; testTagReaderThread . join ( ) ; assertEquals ( "" , , testTagReader . getTagReadCount ( ) ) ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . IOException ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . model . IRubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMRunner ; public class TestVMDebugger extends StandardVMDebugger implements IVMRunner { public TestVMDebugger ( IVMInstall vmInstance ) { super ( ) ; setVMInstall ( vmInstance ) ; } @ Override protected Process exec ( String [ ] cmdLine , File workingDirectory , String [ ] envp ) throws CoreException { return new ShamProcess ( ) ; } @ Override protected RubyDebuggerProxy getDebugProxy ( RubyDebugTarget debugTarget ) { return new TestDebuggerProxy ( debugTarget , false ) ; } private static class TestDebuggerProxy extends RubyDebuggerProxy { public TestDebuggerProxy ( IRubyDebugTarget debugTarget , boolean isRubyDebug ) { super ( debugTarget , isRubyDebug ) ; } @ Override public void start ( ) throws RubyProcessingException , IOException { } } } package org . rubypeople . rdt . internal . launching ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . InputStream ; import java . io . OutputStream ; public class ShamProcess extends Process { public void destroy ( ) { } public int exitValue ( ) { return ; } public InputStream getErrorStream ( ) { return new ByteArrayInputStream ( new byte [ ] ) ; } public InputStream getInputStream ( ) { return new ByteArrayInputStream ( new byte [ ] ) ; } public OutputStream getOutputStream ( ) { return new ByteArrayOutputStream ( ) ; } public int waitFor ( ) throws InterruptedException { return ; } } package org . rubypeople . rdt . internal . launching ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_InternalLaunching { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_RubyInterpreter . class ) ; suite . addTestSuite ( TC_RubyRuntime . class ) ; suite . addTestSuite ( TC_RunnerLaunching . class ) ; return suite ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import java . io . IOException ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . internal . debug . core . RubyDebuggerProxy ; import org . rubypeople . rdt . internal . debug . core . model . IRubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . internal . debug . core . model . RubyProcessingException ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMRunner ; public class TestRubyDebugDebugger extends RDebugVMDebugger implements IVMRunner { public TestRubyDebugDebugger ( IVMInstall vmInstance ) { super ( ) ; setVMInstall ( vmInstance ) ; } @ Override protected Process exec ( String [ ] cmdLine , File workingDirectory , String [ ] envp ) throws CoreException { return new ShamProcess ( ) ; } @ Override protected RubyDebuggerProxy getDebugProxy ( RubyDebugTarget debugTarget ) { return new TestDebuggerProxy ( debugTarget , true ) ; } private static class TestDebuggerProxy extends RubyDebuggerProxy { public TestDebuggerProxy ( IRubyDebugTarget debugTarget , boolean isRubyDebug ) { super ( debugTarget , isRubyDebug ) ; } @ Override public void start ( ) throws RubyProcessingException , IOException { } } } package org . rubypeople . rdt . internal . launching ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . io . PrintWriter ; public class EvaluateRubyProcessOutput implements Runnable { private byte [ ] inBuffer = new byte [ ] ; private byte [ ] errBuffer = new byte [ ] ; private Process process ; private InputStream pErrorStream ; private InputStream pInputStream ; private OutputStream pOutputStream ; private PrintWriter outputWriter ; private Thread inReadThread ; private Thread errReadThread ; public EvaluateRubyProcessOutput ( Process p ) { process = p ; pErrorStream = process . getErrorStream ( ) ; pInputStream = process . getInputStream ( ) ; pOutputStream = process . getOutputStream ( ) ; inReadThread = new Thread ( this ) ; errReadThread = new Thread ( this ) ; outputWriter = new PrintWriter ( pOutputStream , true ) ; new Thread ( ) { public void run ( ) { try { process . waitFor ( ) ; System . out . println ( "" ) ; } catch ( InterruptedException ex ) { ex . printStackTrace ( ) ; } } } . start ( ) ; inReadThread . start ( ) ; errReadThread . start ( ) ; } private void processNewInput ( String input ) { System . out . println ( input ) ; } private void processNewError ( String error ) { } public void sendOutput ( String output ) { outputWriter . println ( output ) ; } public void run ( ) { if ( inReadThread == Thread . currentThread ( ) ) { try { for ( int i = ; i > - ; i = pInputStream . read ( inBuffer ) ) { processNewInput ( new String ( inBuffer , , i ) ) ; } } catch ( IOException ex ) { ex . printStackTrace ( ) ; } } else if ( errReadThread == Thread . currentThread ( ) ) { try { for ( int i = ; i > - ; i = pErrorStream . read ( errBuffer ) ) { processNewError ( new String ( errBuffer , , i ) ) ; } } catch ( IOException ex ) { ex . printStackTrace ( ) ; } } } public static void main ( String [ ] args ) throws Exception { Process p = Runtime . getRuntime ( ) . exec ( "" ) ; EvaluateRubyProcessOutput erpo = new EvaluateRubyProcessOutput ( p ) ; String in = new BufferedReader ( new InputStreamReader ( System . in ) ) . readLine ( ) ; erpo . sendOutput ( in ) ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . debug . core . Launch ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . internal . core . LaunchConfigurationWorkingCopy ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; import org . rubypeople . rdt . internal . debug . core . model . RubyDebugTarget ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; public class TC_RunnerLaunching extends ModifyingResourceTest { private final static String PROJECT_NAME = "" ; private final static String RUBY_LIB_DIR = "" ; private final static String RUBY_FILE_NAME = "" ; private final static String INTERPRETER_ARGUMENTS = "" ; private final static String PROGRAM_ARGUMENTS = "" ; private static final String VM_TYPE_ID = "" ; private IVMInstallType vmType ; private IVMInstall interpreter ; private IRubyProject project ; public TC_RunnerLaunching ( String name ) { super ( name ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; project = createRubyProject ( '' + PROJECT_NAME ) ; IFolder location = createFolder ( '' + PROJECT_NAME + "" ) ; createFolder ( '' + PROJECT_NAME + "" ) ; createFolder ( '' + PROJECT_NAME + "" ) ; createFile ( '' + PROJECT_NAME + "" , "" ) ; createFolder ( '' + PROJECT_NAME + "" + RUBY_LIB_DIR ) ; createFile ( '' + PROJECT_NAME + "" + RUBY_LIB_DIR + "" + RUBY_FILE_NAME , "" ) ; vmType = RubyRuntime . getVMInstallType ( VM_TYPE_ID ) ; VMStandin standin = new VMStandin ( vmType , "" ) ; standin . setName ( "" ) ; standin . setInstallLocation ( location . getLocation ( ) . toFile ( ) ) ; interpreter = standin . convertToRealVM ( ) ; RubyRuntime . setDefaultVMInstall ( interpreter , null , true ) ; LaunchingPlugin . getDefault ( ) . getPluginPreferences ( ) . setValue ( PreferenceConstants . USE_RUBY_DEBUG , false ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; deleteProject ( '' + PROJECT_NAME ) ; vmType . disposeVMInstall ( interpreter . getId ( ) ) ; } protected ILaunchManager getLaunchManager ( ) { return DebugPlugin . getDefault ( ) . getLaunchManager ( ) ; } protected String getCommandLine ( IProject project , String debugFile , boolean debug ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; buffer . append ( new Path ( interpreter . getInstallLocation ( ) . getAbsolutePath ( ) ) . append ( "" ) . append ( "" ) . toOSString ( ) ) ; buffer . append ( "" ) ; buffer . append ( INTERPRETER_ARGUMENTS ) ; addSyncArgs ( buffer ) ; if ( debug ) { buffer . append ( "" ) ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) buffer . append ( "" ) ; buffer . append ( new Path ( StandardVMDebugger . getDirectoryOfRubyDebuggerFile ( ) ) . toOSString ( ) ) ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) buffer . append ( "" ) ; } if ( debug ) { buffer . append ( "" ) ; buffer . append ( debugFile ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; IFile file = project . getFile ( RUBY_LIB_DIR + File . separator + RUBY_FILE_NAME ) ; buffer . append ( file . getLocation ( ) . toOSString ( ) ) ; buffer . append ( "" ) ; buffer . append ( PROGRAM_ARGUMENTS ) ; return buffer . toString ( ) ; } private void addSyncArgs ( StringBuffer buffer ) { buffer . append ( "" ) ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) buffer . append ( "" ) ; buffer . append ( LaunchingPlugin . getFileInPlugin ( new Path ( "" ) . append ( "" ) . append ( StandardVMRunner . STREAM_FLUSH_SCRIPT ) ) . getParent ( ) ) ; if ( Platform . getOS ( ) . equals ( Platform . OS_WIN32 ) ) buffer . append ( "" ) ; buffer . append ( "" + StandardVMRunner . STREAM_FLUSH_SCRIPT ) ; } public void testDebugEnabled ( ) throws Exception { ILaunchConfigurationType launchConfigurationType = getLaunchManager ( ) . getLaunchConfigurationType ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ; assertEquals ( "" , launchConfigurationType . getName ( ) ) ; assertTrue ( "" , launchConfigurationType . supportsMode ( ILaunchManager . DEBUG_MODE ) ) ; } public void launch ( boolean debug ) throws Exception { LaunchConfigurationWorkingCopy configuration = new LaunchConfigurationWorkingCopy ( null , "" , null ) { } ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , PROJECT_NAME ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , RUBY_LIB_DIR + File . separator + RUBY_FILE_NAME ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , '' + PROJECT_NAME ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROGRAM_ARGUMENTS , PROGRAM_ARGUMENTS ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_VM_ARGUMENTS , INTERPRETER_ARGUMENTS ) ; ILaunch launch = new Launch ( configuration , debug ? ILaunchManager . DEBUG_MODE : ILaunchManager . RUN_MODE , null ) ; ILaunchConfigurationType launchConfigurationType = getLaunchManager ( ) . getLaunchConfigurationType ( IRubyLaunchConfigurationConstants . ID_RUBY_APPLICATION ) ; launchConfigurationType . getDelegate ( debug ? ILaunchManager . DEBUG_MODE : ILaunchManager . RUN_MODE ) . launch ( configuration , debug ? ILaunchManager . DEBUG_MODE : ILaunchManager . RUN_MODE , launch , null ) ; RubyDebugTarget debugTarget = ( RubyDebugTarget ) launch . getDebugTarget ( ) ; String debugFile = "" ; if ( debug ) { debugFile = debugTarget . getDebugParameterFile ( ) . getAbsolutePath ( ) ; } assertEquals ( "" , , launch . getProcesses ( ) . length ) ; IProcess process = launch . getProcesses ( ) [ ] ; String expected = getCommandLine ( project . getProject ( ) , debugFile , debug ) ; assertEquals ( expected , process . getAttribute ( IProcess . ATTR_CMDLINE ) ) ; } public void testRunInDebugMode ( ) throws Exception { launch ( true ) ; } public void testRunInRunMode ( ) throws Exception { launch ( false ) ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . debug . core . ILaunchManager ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . IVMRunner ; public class TestVM extends StandardVM implements IVMInstall { public TestVM ( IVMInstallType type , String id ) { super ( type , id ) ; } @ Override public IVMRunner getVMRunner ( String mode ) { if ( ILaunchManager . RUN_MODE . equals ( mode ) ) { return new TestVMRunner ( this ) ; } else if ( ILaunchManager . DEBUG_MODE . equals ( mode ) ) { if ( useRDebug ( ) ) { return new TestRubyDebugDebugger ( this ) ; } return new TestVMDebugger ( this ) ; } return null ; } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import junit . framework . TestCase ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; public class TC_RubyInterpreter extends TestCase { private static final String VM_TYPE_ID = "" ; private IVMInstallType vmType ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; vmType = RubyRuntime . getVMInstallType ( VM_TYPE_ID ) ; } public void testEquals ( ) { IVMInstall interpreterOne = new StandardVM ( vmType , "" ) ; interpreterOne . setInstallLocation ( new File ( "" ) ) ; IVMInstall similarInterpreterOne = new StandardVM ( vmType , "" ) ; similarInterpreterOne . setInstallLocation ( new File ( "" ) ) ; assertTrue ( "" , interpreterOne . equals ( similarInterpreterOne ) ) ; IVMInstall interpreterTwo = new StandardVM ( vmType , "" ) ; interpreterTwo . setInstallLocation ( new File ( "" ) ) ; assertTrue ( "" , ! interpreterOne . equals ( interpreterTwo ) ) ; } } package org . rubypeople . rdt . internal . launching ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallChangedListener ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . PropertyChangeEvent ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; public class TC_RubyRuntime extends ModifyingResourceTest { private static final String VM_TYPE_ID = "" ; private IVMInstallType vmType ; private IFolder folderOne ; private IFolder folderTwo ; public TC_RubyRuntime ( String name ) { super ( name ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; vmType = RubyRuntime . getVMInstallType ( VM_TYPE_ID ) ; IVMInstall [ ] installs = vmType . getVMInstalls ( ) ; for ( int i = ; i < installs . length ; i ++ ) { vmType . disposeVMInstall ( installs [ i ] . getId ( ) ) ; } LaunchingPlugin . getDefault ( ) . setIgnoreVMDefPropertyChangeEvents ( true ) ; createProject ( "" ) ; folderOne = createFolder ( "" ) ; createFolder ( "" ) ; createFolder ( "" ) ; createFile ( "" , "" ) ; folderTwo = createFolder ( "" ) ; createFolder ( "" ) ; createFolder ( "" ) ; createFile ( "" , "" ) ; } @ Override protected void tearDown ( ) throws Exception { RubyRuntime . setDefaultVMInstall ( null , null , true ) ; IVMInstall [ ] installs = vmType . getVMInstalls ( ) ; for ( int i = ; i < installs . length ; i ++ ) { vmType . disposeVMInstall ( installs [ i ] . getId ( ) ) ; } vmType = null ; RubyRuntime . getPreferences ( ) . setValue ( RubyRuntime . PREF_VM_XML , "" ) ; deleteProject ( "" ) ; super . tearDown ( ) ; } public void testGetInstalledInterpreters ( ) { String vmOneName = "" ; String vmOneId = vmOneName ; String vmTwoName = "" ; String vmTwoId = vmTwoName ; try { VMStandin standin = new VMStandin ( vmType , vmOneId ) ; standin . setInstallLocation ( folderOne . getLocation ( ) . toFile ( ) ) ; standin . setName ( vmOneName ) ; standin . convertToRealVM ( ) ; VMStandin standin2 = new VMStandin ( vmType , vmTwoId ) ; standin2 . setInstallLocation ( folderTwo . getLocation ( ) . toFile ( ) ) ; standin2 . setName ( vmTwoName ) ; standin2 . convertToRealVM ( ) ; IVMInstall [ ] installs = vmType . getVMInstalls ( ) ; assertEquals ( , installs . length ) ; assertEquals ( vmOneName , installs [ ] . getName ( ) ) ; assertEquals ( vmTwoName , installs [ ] . getName ( ) ) ; } finally { vmType . disposeVMInstall ( vmOneId ) ; vmType . disposeVMInstall ( vmTwoId ) ; } } public void testSetDefaultVM ( ) throws Exception { String vmOneName = "" ; String vmOneId = vmOneName ; try { VMStandin standin = new VMStandin ( vmType , vmOneId ) ; standin . setInstallLocation ( folderOne . getLocation ( ) . toFile ( ) ) ; standin . setName ( vmOneName ) ; IVMInstall vm = standin . convertToRealVM ( ) ; final boolean [ ] receivedDefaultVMInstallChangedEvent = new boolean [ ] ; RubyRuntime . addVMInstallChangedListener ( new IVMInstallChangedListener ( ) { public void defaultVMInstallChanged ( IVMInstall previous , IVMInstall current ) { receivedDefaultVMInstallChangedEvent [ ] = true ; } public void vmAdded ( IVMInstall newVm ) { } public void vmChanged ( PropertyChangeEvent event ) { } public void vmRemoved ( IVMInstall removedVm ) { } } ) ; RubyRuntime . setDefaultVMInstall ( vm , new NullProgressMonitor ( ) , false ) ; assertEquals ( vm , RubyRuntime . getDefaultVMInstall ( ) ) ; assertTrue ( receivedDefaultVMInstallChangedEvent [ ] ) ; } finally { vmType . disposeVMInstall ( vmOneId ) ; } } public void testCheckInterpreterBin ( ) throws Exception { String vmOneName = "" ; String vmOneId = vmOneName ; try { VMStandin standin = new VMStandin ( vmType , vmOneId ) ; standin . setInstallLocation ( folderOne . getLocation ( ) . toFile ( ) ) ; standin . setName ( vmOneName ) ; IVMInstall vm = standin . convertToRealVM ( ) ; RubyRuntime . setDefaultVMInstall ( vm , new NullProgressMonitor ( ) , false ) ; IPath path = RubyRuntime . checkInterpreterBin ( "" ) ; assertNotNull ( path ) ; path = RubyRuntime . checkInterpreterBin ( "" ) ; assertNull ( path ) ; } finally { vmType . disposeVMInstall ( vmOneId ) ; } } } package org . rubypeople . rdt . internal . launching ; import java . io . File ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMRunner ; public class TestVMRunner extends StandardVMRunner implements IVMRunner { public TestVMRunner ( IVMInstall vmInstance ) { super ( ) ; setVMInstall ( vmInstance ) ; } @ Override protected Process exec ( String [ ] cmdLine , File workingDirectory , String [ ] envp ) throws CoreException { return new ShamProcess ( ) ; } } package org . rubypeople . rdt . internal . launching ; import org . rubypeople . rdt . launching . IVMInstall ; public class TestVMType extends StandardVMType { @ Override protected IVMInstall doCreateVMInstall ( String id ) { return new TestVM ( this , id ) ; } } package org . rubypeople . rdt . launching . tests ; import org . rubypeople . rdt . internal . launching . TS_InternalLaunching ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_Launching { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( TS_InternalLaunching . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . ui . tests ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . internal . corext . util . RDocUtiltest ; import org . rubypeople . rdt . internal . ui . TS_InternalUi ; import org . rubypeople . rdt . internal . ui . rubyeditor . TS_InternalUiRubyEditor ; import org . rubypeople . rdt . internal . ui . search . TS_InternalUiRubySearch ; import org . rubypeople . rdt . internal . ui . text . TS_InternalUiText ; public class TS_Ui { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( RDocUtiltest . class ) ; suite . addTest ( TS_InternalUi . suite ( ) ) ; suite . addTest ( TS_InternalUiRubyEditor . suite ( ) ) ; suite . addTest ( TS_InternalUiText . suite ( ) ) ; suite . addTest ( TS_InternalUiRubySearch . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . internal . corext . util ; import org . rubypeople . rdt . internal . corext . util . RDocUtil ; import junit . framework . TestCase ; public class RDocUtiltest extends TestCase { public void testHTML ( ) throws Exception { String input = "" + "" + "" + "" + "" + "" + "" + "" ; String html = RDocUtil . getHTMLDocumentation ( input ) ; String expected = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; assertEquals ( expected , html ) ; } } package org . rubypeople . rdt . internal . ui ; import org . rubypeople . eclipse . shams . resources . ShamProject ; import org . rubypeople . rdt . internal . ui . util . StackTraceLine ; import junit . framework . TestCase ; public class TC_StackTraceLine extends TestCase { private static final String BACKSLASH_FILE_PATH = "" ; private static final String RUBY_CONSOLE_TEST_FAILURE = "" ; private static final String TEST_UNIT_VIEW_BACKTRACE = "" ; private static final String BACKTRACE_WITH_IN = "" ; private static final String WITH_FROM = "" ; private static final String ODD_WITH_FROM = "" ; private static final String WITH_OUT_FROM = "" ; private static final String WITH_TRAILING_SPACE = "" ; private static final String LOOKS_ABSOLUTE = "" ; public void testWithFrom ( ) { assertFalse ( "" , StackTraceLine . isTraceLine ( WITH_TRAILING_SPACE ) ) ; } public void testRelativePathWithPeriod ( ) { assertTrue ( "" , StackTraceLine . isTraceLine ( "" ) ) ; } public void testRelativePathWithoutPeriod ( ) { assertTrue ( "" , StackTraceLine . isTraceLine ( "" ) ) ; } public void testWithTrailingSpace ( ) { assertTrue ( "" , StackTraceLine . isTraceLine ( WITH_FROM ) ) ; StackTraceLine traceLine = new StackTraceLine ( WITH_FROM ) ; assertEquals ( "" , "" , traceLine . getFilename ( ) ) ; assertEquals ( "" , , traceLine . getLineNumber ( ) ) ; assertEquals ( "" , , traceLine . offset ( ) ) ; assertEquals ( "" , , traceLine . length ( ) ) ; } public void testWithOutFrom ( ) { assertTrue ( "" , StackTraceLine . isTraceLine ( WITH_OUT_FROM ) ) ; StackTraceLine traceLine = new StackTraceLine ( WITH_OUT_FROM ) ; assertEquals ( "" , "" , traceLine . getFilename ( ) ) ; assertEquals ( "" , , traceLine . getLineNumber ( ) ) ; assertEquals ( "" , , traceLine . offset ( ) ) ; assertEquals ( "" , , traceLine . length ( ) ) ; } public void testOddWithFrom ( ) { assertTrue ( "" , StackTraceLine . isTraceLine ( ODD_WITH_FROM ) ) ; StackTraceLine traceLine = new StackTraceLine ( ODD_WITH_FROM ) ; assertEquals ( "" , "" , traceLine . getFilename ( ) ) ; assertEquals ( "" , , traceLine . getLineNumber ( ) ) ; assertEquals ( "" , , traceLine . offset ( ) ) ; assertEquals ( "" , , traceLine . length ( ) ) ; } public void testBacktraceWithInTestFailure ( ) { assertTrue ( "" , StackTraceLine . isTraceLine ( BACKTRACE_WITH_IN ) ) ; StackTraceLine traceLine = new StackTraceLine ( BACKTRACE_WITH_IN ) ; assertEquals ( "" , "" , traceLine . getFilename ( ) ) ; assertEquals ( "" , , traceLine . getLineNumber ( ) ) ; assertEquals ( "" , , traceLine . offset ( ) ) ; assertEquals ( "" , , traceLine . length ( ) ) ; } public void testConsoleTestFailure ( ) { assertTrue ( StackTraceLine . isTraceLine ( RUBY_CONSOLE_TEST_FAILURE ) ) ; StackTraceLine traceLine = new StackTraceLine ( RUBY_CONSOLE_TEST_FAILURE ) ; assertEquals ( "" , "" , traceLine . getFilename ( ) ) ; assertEquals ( "" , , traceLine . getLineNumber ( ) ) ; assertEquals ( "" , , traceLine . offset ( ) ) ; assertEquals ( "" , , traceLine . length ( ) ) ; } public void testTestUnitViewBackTrace ( ) { StackTraceLine traceLine = new StackTraceLine ( TEST_UNIT_VIEW_BACKTRACE ) ; assertEquals ( "" , "" , traceLine . getFilename ( ) ) ; assertEquals ( "" , , traceLine . getLineNumber ( ) ) ; assertEquals ( "" , , traceLine . offset ( ) ) ; assertEquals ( "" , , traceLine . length ( ) ) ; } public void testLooksAbsoluteButIsRelativeToProject ( ) { StackTraceLine traceLine = new StackTraceLine ( LOOKS_ABSOLUTE , new ShamProject ( "" ) ) ; assertEquals ( "" , "" , traceLine . getFilename ( ) ) ; assertEquals ( "" , , traceLine . getLineNumber ( ) ) ; assertEquals ( "" , , traceLine . offset ( ) ) ; assertEquals ( "" , , traceLine . length ( ) ) ; } public void testBackslashInFilePath ( ) { StackTraceLine traceLine = new StackTraceLine ( BACKSLASH_FILE_PATH , new ShamProject ( "" ) ) ; assertEquals ( "" , "" , traceLine . getFilename ( ) ) ; assertEquals ( "" , , traceLine . getLineNumber ( ) ) ; assertEquals ( "" , , traceLine . offset ( ) ) ; assertEquals ( "" , , traceLine . length ( ) ) ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . ui . plugin . AbstractUIPlugin ; public class RdtUiTestsPlugin extends AbstractUIPlugin { private static RdtUiTestsPlugin plugin ; public RdtUiTestsPlugin ( ) { super ( ) ; plugin = this ; } public static RdtUiTestsPlugin getDefault ( ) { return plugin ; } public static IWorkspace getWorkspace ( ) { return ResourcesPlugin . getWorkspace ( ) ; } } package org . rubypeople . rdt . internal . ui . util ; import java . util . Comparator ; import junit . framework . TestCase ; import org . eclipse . core . runtime . AssertionFailedException ; public class TwoArrayQuickSorterTest extends TestCase { public void testSortStringIgnoringCase ( ) throws Exception { String [ ] keys = new String [ ] { "" , "" , "" , "" } ; String [ ] values = new String [ ] { "" , "" , "" , "" } ; TwoArrayQuickSorter sorter = new TwoArrayQuickSorter ( true ) ; sorter . sort ( keys , values ) ; int i = ; assertEquals ( "" , keys [ i ++ ] ) ; assertEquals ( "" , keys [ i ++ ] ) ; assertEquals ( "" , keys [ i ++ ] ) ; assertEquals ( "" , keys [ i ++ ] ) ; i = ; assertEquals ( "" , values [ i ++ ] ) ; assertEquals ( "" , values [ i ++ ] ) ; assertEquals ( "" , values [ i ++ ] ) ; assertEquals ( "" , values [ i ++ ] ) ; } public void testSortIntegerKeysStringValues ( ) throws Exception { Integer [ ] keys = new Integer [ ] { , , , } ; String [ ] values = new String [ ] { "" , "" , "" , "" } ; Comparator comparator = new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { if ( o1 instanceof Integer ) { return ( ( Integer ) o1 ) . compareTo ( ( Integer ) o2 ) ; } if ( o1 instanceof String ) { return ( ( String ) o1 ) . compareTo ( ( String ) o2 ) ; } return ; } } ; TwoArrayQuickSorter sorter = new TwoArrayQuickSorter ( comparator ) ; sorter . sort ( keys , values ) ; int i = ; assertEquals ( new Integer ( ) , keys [ i ++ ] ) ; assertEquals ( new Integer ( ) , keys [ i ++ ] ) ; assertEquals ( new Integer ( ) , keys [ i ++ ] ) ; assertEquals ( new Integer ( ) , keys [ i ++ ] ) ; i = ; assertEquals ( "" , values [ i ++ ] ) ; assertEquals ( "" , values [ i ++ ] ) ; assertEquals ( "" , values [ i ++ ] ) ; assertEquals ( "" , values [ i ++ ] ) ; } public void testSortNullKeysThrowsException ( ) throws Exception { try { TwoArrayQuickSorter sorter = new TwoArrayQuickSorter ( true ) ; sorter . sort ( null , new String [ ] ) ; fail ( "" ) ; } catch ( AssertionFailedException e ) { assertTrue ( true ) ; } } public void testSortNullValuesThrowsException ( ) throws Exception { try { TwoArrayQuickSorter sorter = new TwoArrayQuickSorter ( true ) ; sorter . sort ( new String [ ] , null ) ; fail ( "" ) ; } catch ( AssertionFailedException e ) { assertTrue ( true ) ; } } public void testSortEmptyArrays ( ) throws Exception { String [ ] keys = new String [ ] ; String [ ] values = new String [ ] ; TwoArrayQuickSorter sorter = new TwoArrayQuickSorter ( true ) ; sorter . sort ( new String [ ] , new String [ ] ) ; assertEquals ( , keys . length ) ; assertEquals ( , values . length ) ; } } package org . rubypeople . rdt . internal . ui . util ; import junit . framework . TestCase ; import org . rubypeople . rdt . internal . ui . util . StringMatcher . Position ; public class StringMatcherTest extends TestCase { public void testStartAfterEnd ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , true , false ) ; assertNull ( matcher . find ( "" , , ) ) ; assertFalse ( matcher . match ( "" , , ) ) ; } public void testNullPattern ( ) { try { new StringMatcher ( null , true , false ) ; fail ( "" ) ; } catch ( IllegalArgumentException e ) { assertTrue ( true ) ; } } public void testFindWithNullText ( ) { StringMatcher matcher = new StringMatcher ( "" , true , false ) ; try { matcher . find ( null , , ) ; fail ( "" ) ; } catch ( IllegalArgumentException e ) { assertTrue ( true ) ; } } public void testMatchWithNullText ( ) { StringMatcher matcher = new StringMatcher ( "" , true , false ) ; try { matcher . match ( null ) ; fail ( "" ) ; } catch ( IllegalArgumentException e ) { assertTrue ( true ) ; } } public void testMatchWithStartAndEndWithNullText ( ) { StringMatcher matcher = new StringMatcher ( "" , true , false ) ; try { matcher . match ( null , , ) ; fail ( "" ) ; } catch ( IllegalArgumentException e ) { assertTrue ( true ) ; } } public void testFindWithEmptyTextString ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , true , false ) ; assertNull ( matcher . find ( "" , , "" . length ( ) ) ) ; pattern = "" ; matcher = new StringMatcher ( pattern , true , false ) ; assertNull ( matcher . find ( "" , , "" . length ( ) ) ) ; pattern = "" ; matcher = new StringMatcher ( pattern , true , false ) ; assertNull ( matcher . find ( "" , , "" . length ( ) ) ) ; } public void testFindWithEmptyPattern ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , false , false ) ; String text = "" ; Position pos = matcher . find ( text , , text . length ( ) ) ; assertNotNull ( pos ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; } public void testFindIgnoringCase ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , true , false ) ; String text = "" ; Position pos = matcher . find ( text , , text . length ( ) ) ; assertNotNull ( pos ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; } public void testMatchIgnoringCase ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , true , false ) ; assertTrue ( matcher . match ( "" ) ) ; assertTrue ( matcher . match ( "" ) ) ; assertFalse ( matcher . match ( "" ) ) ; } public void testMatchNotIgnoringCase ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , false , false ) ; assertFalse ( matcher . match ( "" ) ) ; assertTrue ( matcher . match ( "" ) ) ; assertFalse ( matcher . match ( "" ) ) ; } public void testFindNotIgnoringCase ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , false , false ) ; String text = "" ; Position pos = matcher . find ( text , , text . length ( ) ) ; assertNotNull ( pos ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; text = "" ; pos = matcher . find ( text , , text . length ( ) ) ; assertNull ( pos ) ; } public void testFindStarInPatternIgnoringWildcards ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , false , true ) ; String text = "" ; Position pos = matcher . find ( text , , text . length ( ) ) ; assertNull ( pos ) ; text = "" ; pos = matcher . find ( text , , text . length ( ) ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; } public void testFindQuestionMarkInPatternIgnoringWildcards ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , false , true ) ; String text = "" ; Position pos = matcher . find ( text , , text . length ( ) ) ; assertNull ( pos ) ; text = "" ; pos = matcher . find ( text , , text . length ( ) ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; } public void testFindWithSingleCharWildcard ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , false , false ) ; String text = "" ; Position pos = matcher . find ( text , , text . length ( ) ) ; assertNotNull ( pos ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; text = "" ; pos = matcher . find ( text , , text . length ( ) ) ; assertNull ( pos ) ; } public void testFindWithStarWildcard ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , false , false ) ; String text = "" ; Position pos = matcher . find ( text , , text . length ( ) ) ; assertNotNull ( pos ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; text = "" ; pos = matcher . find ( text , , text . length ( ) ) ; assertNotNull ( pos ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; } public void testFindWithOpenEndedWildcardAtEnd ( ) { String pattern = "" ; StringMatcher matcher = new StringMatcher ( pattern , false , false ) ; String text = "" ; Position pos = matcher . find ( text , , text . length ( ) ) ; assertNotNull ( pos ) ; assertEquals ( , pos . getStart ( ) ) ; assertEquals ( , pos . getEnd ( ) ) ; } } package org . rubypeople . rdt . internal . ui . util ; import junit . framework . Test ; import junit . framework . TestSuite ; public class InternalUIUtilTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TwoArrayQuickSorterTest . class ) ; suite . addTestSuite ( StringMatcherTest . class ) ; return suite ; } } package org . rubypeople . rdt . internal . ui ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; import org . rubypeople . rdt . internal . core . RubyProject ; import org . rubypeople . rdt . internal . core . RubyScript ; public class TC_ResourceAdapterFactory extends ModifyingResourceTest { private static final String PROJECT_NAME = "" ; private ResourceAdapterFactory factory ; private IProject project ; public TC_ResourceAdapterFactory ( String name ) { super ( name ) ; } protected void setUp ( ) throws Exception { super . setUp ( ) ; this . project = createProject ( PROJECT_NAME ) ; factory = new ResourceAdapterFactory ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; deleteProject ( PROJECT_NAME ) ; } public void testGetAdapterForRBFile ( ) throws CoreException { IFile file = createFile ( PROJECT_NAME + "" , "" ) ; assertEquals ( RubyScript . class , factory . getAdapter ( file , IRubyElement . class ) . getClass ( ) ) ; assertTrue ( factory . getAdapter ( file , IRubyElement . class ) instanceof IRubyScript ) ; } public void testGetAdapterForRBWFile ( ) throws CoreException { IFile file = createFile ( PROJECT_NAME + "" , "" ) ; assertEquals ( RubyScript . class , factory . getAdapter ( file , IRubyElement . class ) . getClass ( ) ) ; assertTrue ( factory . getAdapter ( file , IRubyElement . class ) instanceof IRubyScript ) ; } public void testGetAdapterForProject ( ) throws CoreException { addRubyNature ( PROJECT_NAME ) ; assertEquals ( RubyProject . class , factory . getAdapter ( project , IRubyElement . class ) . getClass ( ) ) ; assertTrue ( factory . getAdapter ( project , IRubyElement . class ) instanceof IRubyProject ) ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import junit . framework . TestSuite ; public class TS_InternalUiRubyEditor { public static TestSuite suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_TabConverter . class ) ; return suite ; } } package org . rubypeople . rdt . internal . ui . rubyeditor ; import junit . framework . TestCase ; import org . eclipse . jface . text . DefaultLineTracker ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . DocumentCommand ; import org . rubypeople . rdt . internal . ui . rubyeditor . RubyEditor . TabConverter ; public class TC_TabConverter extends TestCase { private static final String TEST_TEXT = "" ; private static class TestDocumentCommand extends DocumentCommand { public TestDocumentCommand ( int offset ) { this . offset = offset ; } } public void testSpacesForTab ( ) { verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; } public void testSubsequentLines ( ) { verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; } public void testSpacesOneSpacePerTab ( ) { verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; } public void testSpacesZeroSpacPerTab ( ) { verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; verifyTabExpansion ( , , ) ; } private void verifyTabExpansion ( int spacesPerTab , int currentOffset , int expectedCountOfTabs ) { TabConverter converter = new TabConverter ( ) ; converter . setNumberOfSpacesPerTab ( spacesPerTab ) ; TestDocumentCommand command = new TestDocumentCommand ( currentOffset ) ; command . text = "" ; Document document = new Document ( TEST_TEXT ) ; DefaultLineTracker tracker = new DefaultLineTracker ( ) ; converter . setLineTracker ( tracker ) ; converter . customizeDocumentCommand ( document , command ) ; String message = "" + currentOffset + "" + spacesPerTab ; if ( spacesPerTab == ) assertEquals ( message , "" , command . text ) ; else assertEquals ( message , "" . substring ( , expectedCountOfTabs ) , command . text ) ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import junit . framework . TestCase ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . DocumentCommand ; import org . eclipse . jface . text . IDocument ; import org . rubypeople . rdt . internal . ui . text . TestDocumentCommand ; public class TC_RubyAutoIndentStrategy extends TestCase { private IDocument d ; public void testInsertsIndentAndEndAfterClassDefinitionLine ( ) throws Exception { DocumentCommand c = addNewline ( "" ) ; assertEquals ( , c . caretOffset ) ; assertEquals ( false , c . shiftsCaret ) ; assertEquals ( "" , c . text ) ; } public void testInsertsIndentAndEndAfterMethodDefinitionLine ( ) throws Exception { DocumentCommand c = addNewline ( "" ) ; assertEquals ( , c . caretOffset ) ; assertEquals ( false , c . shiftsCaret ) ; assertEquals ( "" , c . text ) ; } public void testHandlesReturnAfterEndOfClosedCaseWithProperIndents ( ) throws Exception { DocumentCommand c = addNewline ( "" + "" + "" + "" + "" + "" + "" + "" , ) ; assertEquals ( "" , c . text ) ; assertEquals ( "" + "" + "" + "" + "" + "" + "" + "" + "" , d . get ( ) ) ; } public void testHandlesReturnAfterEndOfClosedCaseWithBadEndIndent ( ) throws Exception { DocumentCommand c = addNewline ( "" + "" + "" + "" + "" + "" + "" + "" , ) ; assertEquals ( "" , c . text ) ; assertEquals ( "" + "" + "" + "" + "" + "" + "" + "" + "" , d . get ( ) ) ; } public void testHandlesElsifAfterIfProperly ( ) throws Exception { DocumentCommand c = addNewline ( "" + "" + "" + "" + "" , ) ; assertEquals ( "" , c . text ) ; assertEquals ( "" + "" + "" + "" + "" , d . get ( ) ) ; } private DocumentCommand addNewline ( String source , int offset ) { RubyAutoIndentStrategy strategy = new RubyAutoIndentStrategy ( null , null ) ; DocumentCommand c = createNewLineCommandAt ( offset ) ; d = new Document ( source ) ; strategy . customizeDocumentCommand ( d , c ) ; return c ; } private DocumentCommand addNewline ( String source ) { return addNewline ( source , source . length ( ) ) ; } private DocumentCommand createNewLineCommandAt ( int offset ) { DocumentCommand c = new TestDocumentCommand ( ) ; c . text = "" ; c . length = ; c . doit = true ; c . caretOffset = - ; c . offset = offset ; c . shiftsCaret = true ; return c ; } } package org . rubypeople . rdt . internal . ui . text . ruby ; import junit . framework . TestCase ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . rules . IToken ; import org . eclipse . jface . text . rules . Token ; import org . rubypeople . rdt . internal . ui . RubyPlugin ; import org . rubypeople . rdt . internal . ui . text . IRubyColorConstants ; import org . rubypeople . rdt . internal . ui . text . RubyColorManager ; public class TC_RubyTokenScanner extends TestCase { private RubyColoringTokenScanner fScanner ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; RubyColorManager colorManager = new RubyColorManager ( false ) ; fScanner = new RubyColoringTokenScanner ( colorManager , RubyPlugin . getDefault ( ) . getPreferenceStore ( ) ) { @ Override public Token getToken ( String key ) { return new Token ( key ) ; } } ; } private void setUpScanner ( String code ) { setUpScanner ( code , , code . length ( ) ) ; } private void setUpScanner ( String code , int offset , int length ) { Document doc = new Document ( code ) ; fScanner . setRange ( doc , offset , length ) ; } private void assertToken ( String color , int offset , int length ) { IToken token = fScanner . nextToken ( ) ; assertEquals ( "" , offset , fScanner . getTokenOffset ( ) ) ; assertEquals ( "" , length , fScanner . getTokenLength ( ) ) ; assertEquals ( "" , color , token . getData ( ) ) ; } public void testSimpleClassDefinition ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_KEYWORD , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_KEYWORD , , ) ; } public void testSymbolAtEndOfLine ( ) { String code = "" + "" + "" + "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_KEYWORD , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; } public void testSymbolInsideBrackets ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; } public void testSymbolInsideParentheses ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; } public void testAliasWithTwoSymbols ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_KEYWORD , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; } public void testSymbolInsideBracketsTwo ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_INSTANCE_VARIABLE , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; } public void testTertiaryConditional ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_KEYWORD , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; } public void testWhen ( ) { String code = "" + "" + "" + "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_KEYWORD , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_KEYWORD , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_FIXNUM , , ) ; } public void testAppendSymbol ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; } public void testDollarDollarSymbol ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_SYMBOL , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; } public void testTertiaryConditionalWithNoSpaces ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; } public void testClassVariable ( ) { String code = "" ; setUpScanner ( code ) ; assertToken ( IRubyColorConstants . RUBY_CLASS_VARIABLE , , ) ; assertToken ( IRubyColorConstants . RUBY_DEFAULT , , ) ; assertToken ( IRubyColorConstants . RUBY_FIXNUM , , ) ; } } package org . rubypeople . rdt . internal . ui . text ; import junit . framework . TestCase ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . rules . FastPartitioner ; import org . eclipse . jface . text . rules . IToken ; import org . rubypeople . rdt . internal . ui . text . RubyPartitionScanner . EndBraceFinder ; public class TC_RubyPartitionScanner extends TestCase { private void assertContentType ( String contentType , String code , int offset ) { assertEquals ( "" + code . charAt ( offset ) , contentType , getContentType ( code , offset ) ) ; } private String getContentType ( String content , int offset ) { IDocument doc = new Document ( content ) ; FastPartitioner partitioner = new FastPartitioner ( new MergingPartitionScanner ( ) , RubyPartitionScanner . LEGAL_CONTENT_TYPES ) ; partitioner . connect ( doc ) ; return partitioner . getContentType ( offset ) ; } public void testUnclosedInterpolationDoesntInfinitelyLoop ( ) { getContentType ( "" , ) ; assert ( true ) ; } public void testBug5730 ( ) { getContentType ( "" + "" + "" + "" , ) ; assert ( true ) ; } public void testBug6052 ( ) { getContentType ( "" + "" + "" + "" + "" + "" + "" + "" + "" + "" , ) ; assert ( true ) ; } public void testPartitioningOfSingleLineComment ( ) { String source = "" ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , source , ) ; } public void testRecognizeSpecialCase ( ) { String source = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; } public void testMultilineComment ( ) { String source = "" ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , source , ) ; source = "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , source , source . length ( ) / ) ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , source , source . length ( ) - ) ; } public void testMultilineCommentNotOnFirstColumn ( ) { String source = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; } public void testRecognizeDivision ( ) { String source = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , source , ) ; } public void testRecognizeOddballCharacters ( ) { String source = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , source , ) ; source = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , source , ) ; source = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , source , ) ; } public void testPoundCharacterIsntAComment ( ) { String source = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , source , ) ; } public void testSinglelineCommentJustAfterMultilineComment ( ) { String source = "" ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , source , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , source , source . length ( ) - ) ; } public void testMultipleCommentsInARow ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; } public void testCommentAfterEnd ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; } public void testCommentAfterEndWhileEditing ( ) { String code = "" + "" + "" + "" + "" + "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; } public void testCommentAtEndOfLineWithStringAtBeginning ( ) { String code = "" + "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; } public void testLinesWithJustSpaceBeforeComment ( ) { String code = "" + "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; } public void testCommentsWithAlotOfPrecedingSpaces ( ) { String code = "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; } public void testCodeWithinString ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testCodeWithinSingleQuoteString ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testVariableSubstitutionWithinString ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testStringWithinCodeWithinString ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testStringWithEndBraceWithinCodeWithinString ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testRegex ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_REGULAR_EXPRESSION , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_REGULAR_EXPRESSION , code , ) ; } public void testRegexWithDynamicCode ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_REGULAR_EXPRESSION , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; } public void testEscapedCharactersAndSingleQuoteInsideDoubleQuote ( ) { String code = "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_REGULAR_EXPRESSION , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , code . length ( ) - ) ; } public void testSingleQuotedString ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testCommands ( ) { String code = "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; } public void testPercentXCommand ( ) { String code = "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; } public void testHeredocInArgumentList ( ) { String code = "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testScaryString ( ) { String code = "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; } public void testBraceFinderHandlesWeirdGlobal ( ) { EndBraceFinder finder = new EndBraceFinder ( "" ) ; assertEquals ( , finder . find ( ) ) ; } public void testNestedHeredocs ( ) { String code = "" + "" + "" + "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; } public void testBug5448 ( ) { String code = "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , code , ) ; } public void testBug5208 ( ) { String code = "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_MULTI_LINE_COMMENT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testROR255 ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testROR950 ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testROR975 ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testROR1278 ( ) { String code = "" + "" + "" + "" ; RubyPartitionScanner scanner = new RubyPartitionScanner ( ) ; IDocument document = new Document ( code ) ; scanner . setPartialRange ( document , , , RubyPartitionScanner . RUBY_DEFAULT , ) ; IToken token = scanner . nextToken ( ) ; assertEquals ( RubyPartitionScanner . RUBY_DEFAULT , token . getData ( ) ) ; } public void testCGILib ( ) { String code = "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_REGULAR_EXPRESSION , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_REGULAR_EXPRESSION , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testROR1307StringSymbols ( ) { String code = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testROR1248 ( ) { String code = "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_COMMAND , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , code , ) ; } public void testCGI ( ) { String src = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_SINGLE_LINE_COMMENT , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_STRING , src , ) ; assertContentType ( RubyPartitionScanner . RUBY_DEFAULT , src , ) ; } } package org . rubypeople . rdt . internal . ui . text . spelling ; import java . util . Locale ; import java . util . Set ; import junit . framework . TestCase ; public class SpellCheckEngineTest extends TestCase { public void testUSDictionaryIncluded ( ) throws Exception { Set < Locale > locales = SpellCheckEngine . getAvailableLocales ( ) ; assertNotNull ( locales ) ; assertTrue ( locales . contains ( Locale . US ) ) ; } } package org . rubypeople . rdt . internal . ui . text ; import org . eclipse . jface . text . DocumentCommand ; public class TestDocumentCommand extends DocumentCommand { public TestDocumentCommand ( ) { super ( ) ; } } package org . rubypeople . rdt . internal . ui . text ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . internal . ui . text . ruby . TC_RubyTokenScanner ; public class TS_InternalUiText { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_RubyPartitionScanner . class ) ; suite . addTestSuite ( TC_RubyWordFinder . class ) ; suite . addTestSuite ( TC_RubyTokenScanner . class ) ; return suite ; } } package org . rubypeople . rdt . internal . ui . text ; import junit . framework . TestCase ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IRegion ; public class TC_RubyWordFinder extends TestCase { private static final String document = "" + "" + "" ; private IRegion findWord ( int offset ) { return RubyWordFinder . findWord ( new Document ( document ) , offset ) ; } private boolean regionEquals ( IRegion region , int length ) { return region . getLength ( ) == length && region . getLength ( ) == length ; } private boolean isWordAtPosition ( String word , int cursorPosition ) { return regionEquals ( findWord ( cursorPosition ) , word . length ( ) ) ; } public void testFindFirstWord ( ) { assertTrue ( isWordAtPosition ( "" , ) ) ; assertTrue ( isWordAtPosition ( "" , ) ) ; assertTrue ( isWordAtPosition ( "" , ) ) ; assertFalse ( isWordAtPosition ( "" , ) ) ; assertNull ( findWord ( - ) ) ; } public void testFindWord ( ) { assertTrue ( isWordAtPosition ( "" , ) ) ; assertFalse ( isWordAtPosition ( "" , ) ) ; assertTrue ( isWordAtPosition ( "" , ) ) ; assertTrue ( isWordAtPosition ( "" , ) ) ; assertTrue ( isWordAtPosition ( "" , ) ) ; } public void testFindLastWord ( ) { assertTrue ( isWordAtPosition ( "" , document . length ( ) - ) ) ; assertTrue ( isWordAtPosition ( "" , document . length ( ) - ) ) ; assertTrue ( isWordAtPosition ( "" , document . length ( ) - ) ) ; assertFalse ( isWordAtPosition ( "" , document . length ( ) - ) ) ; assertNull ( findWord ( document . length ( ) ) ) ; } } package org . rubypeople . rdt . internal . ui ; import junit . framework . TestCase ; import org . rubypeople . eclipse . shams . resources . ShamFile ; public class TC_RubyFileMatcher extends TestCase { private RubyFileMatcher matcher ; protected void setUp ( ) throws Exception { super . setUp ( ) ; matcher = new RubyFileMatcher ( ) ; } public void testHasRubyEditorAssociationIfContainsRubyShebang ( ) { ShamFile file = new ShamFile ( "" , false ) ; file . setContents ( "" ) ; assertTrue ( matcher . hasRubyEditorAssociation ( file ) ) ; } public void testRakefileHasRubyEditorAssociation ( ) { ShamFile file = new ShamFile ( "" , false ) ; assertTrue ( matcher . hasRubyEditorAssociation ( file ) ) ; } public void testGemHasRubyEditorAssociation ( ) { ShamFile file = new ShamFile ( "" , false ) ; assertTrue ( matcher . hasRubyEditorAssociation ( file ) ) ; } public void testGemspecHasRubyEditorAssociation ( ) { ShamFile file = new ShamFile ( "" , false ) ; assertTrue ( matcher . hasRubyEditorAssociation ( file ) ) ; } public void testYAMLHasRubyEditorAssociation ( ) { ShamFile file = new ShamFile ( "" , false ) ; assertTrue ( matcher . hasRubyEditorAssociation ( file ) ) ; } public void testRHTMLHasRubyEditorAssociation ( ) { ShamFile file = new ShamFile ( "" , false ) ; assertTrue ( matcher . hasRubyEditorAssociation ( file ) ) ; } } package org . rubypeople . rdt . internal . ui ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . internal . ui . util . InternalUIUtilTests ; public class TS_InternalUi { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_StackTraceLine . class ) ; suite . addTestSuite ( TC_ResourceAdapterFactory . class ) ; suite . addTestSuite ( TC_RubyFileMatcher . class ) ; suite . addTest ( InternalUIUtilTests . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . Hashtable ; import java . util . List ; import java . util . Map ; import org . eclipse . jface . viewers . AbstractTreeViewer ; import org . eclipse . swt . events . TreeListener ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Item ; import org . eclipse . swt . widgets . Widget ; public class MockTreeViewer extends AbstractTreeViewer { private Map < Object , Object > hashtable = new Hashtable < Object , Object > ( ) ; public void add ( Object parentElement , Object childElement ) { hashtable . put ( parentElement , childElement ) ; } public boolean isParentAdded ( Object parentElement ) { return hashtable . containsKey ( parentElement ) ; } public Object childFrom ( Object parentElement ) { return hashtable . get ( parentElement ) ; } protected void addTreeListener ( Control control , TreeListener listener ) { } protected void doUpdateItem ( Item item , Object element ) { } protected Item [ ] getChildren ( Widget widget ) { return new Item [ ] ; } protected boolean getExpanded ( Item item ) { return false ; } protected int getItemCount ( Control control ) { return ; } protected int getItemCount ( Item item ) { return ; } protected Item [ ] getItems ( Item item ) { return null ; } protected Item getParentItem ( Item item ) { return null ; } protected Item [ ] getSelection ( Control control ) { return null ; } protected Item newItem ( Widget parent , int style , int index ) { return null ; } protected void removeAll ( Control control ) { } protected void setExpanded ( Item item , boolean expand ) { } protected void setSelection ( List items ) { } protected void showItem ( Item item ) { } public Control getControl ( ) { return null ; } } package org . rubypeople . rdt . internal . ui . search ; import java . util . List ; import junit . framework . TestCase ; import org . eclipse . jface . text . Position ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . ui . search . OccurrencesFinder ; public class MarkOccurrencesTest extends TestCase { private IOccurrencesFinder occurrencesFinder ; public void setUp ( ) { occurrencesFinder = new OccurrencesFinder ( ) ; occurrencesFinder . setFMarkConstantOccurrences ( true ) ; occurrencesFinder . setFMarkFieldOccurrences ( true ) ; occurrencesFinder . setFMarkLocalVariableOccurrences ( true ) ; occurrencesFinder . setFMarkMethodExitPoints ( true ) ; occurrencesFinder . setFMarkMethodOccurrences ( true ) ; occurrencesFinder . setFMarkOccurrenceAnnotations ( true ) ; occurrencesFinder . setFMarkTypeOccurrences ( true ) ; occurrencesFinder . setFStickyOccurrenceAnnotations ( true ) ; } private void assertOccurrencesEqual ( String source , int offset , String matchName , int [ ] [ ] offsets ) { RubyParser parser = new RubyParser ( ) ; occurrencesFinder . initialize ( parser . parse ( source ) . getAST ( ) , offset , ) ; List < Position > occurrences = occurrencesFinder . perform ( ) ; assertEquals ( offsets . length , occurrences . size ( ) ) ; for ( int i = ; i < offsets . length ; i ++ ) { int start = occurrences . get ( i ) . getOffset ( ) ; int length = occurrences . get ( i ) . getLength ( ) ; int end = occurrences . get ( i ) . getOffset ( ) + length ; Position testPosition = new Position ( start , length ) ; assertTrue ( occurrences . contains ( testPosition ) ) ; assertEquals ( matchName , source . substring ( start , end ) ) ; } } public void testLocalVariableMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testArgMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testLocalVariablesInKernelDefnScope ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testLocalVariablesInKernelScope ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testInstanceVariableMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testInstanceVariableMatchInReopenedClass ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testLocalVariableMatchesIntoBlockScope ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testGlobalVariableMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testSymbolMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testTypeMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testConstNodeToClassDeclNode ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testBlockArguments ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testClassVariableMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } public void testClassVariableMatchInReopenedClass ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } } ; assertOccurrencesEqual ( source , , "" , offsets ) ; } } package org . rubypeople . rdt . internal . ui . search ; import junit . framework . TestSuite ; public class TS_InternalUiRubySearch { public static TestSuite suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( MarkOccurrencesTest . class ) ; return suite ; } } package com . aptana . rdt . core . rspec ; import junit . framework . TestCase ; import org . jruby . ast . Node ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; public class RSpecStructureCreatorTest extends TestCase { public void testEmptySource ( ) throws Exception { String src = "" ; Node ast = new RubyParser ( ) . parse ( src ) . getAST ( ) ; RSpecStructureCreator creator = new RSpecStructureCreator ( ) ; creator . acceptNode ( ast ) ; assertEquals ( , creator . getBehaviors ( ) . length ) ; } public void testOneBehaviorNoExamples ( ) throws Exception { String src = "" ; Node ast = new RubyParser ( ) . parse ( src ) . getAST ( ) ; RSpecStructureCreator creator = new RSpecStructureCreator ( ) ; creator . acceptNode ( ast ) ; assertEquals ( , creator . getBehaviors ( ) . length ) ; Behavior behavior = ( Behavior ) creator . getBehaviors ( ) [ ] ; assertEquals ( "" , behavior . getClassName ( ) ) ; assertEquals ( "" , behavior . getSource ( ) ) ; assertEquals ( , behavior . getSourceRange ( ) . getOffset ( ) ) ; assertEquals ( src . length ( ) , behavior . getSourceRange ( ) . getLength ( ) ) ; assertEquals ( , behavior . getExamples ( ) . length ) ; } public void testOneBehaviorOneExample ( ) throws Exception { String src = "" ; Node ast = new RubyParser ( ) . parse ( src ) . getAST ( ) ; RSpecStructureCreator creator = new RSpecStructureCreator ( ) ; creator . acceptNode ( ast ) ; assertEquals ( , creator . getBehaviors ( ) . length ) ; Behavior behavior = ( Behavior ) creator . getBehaviors ( ) [ ] ; assertEquals ( "" , behavior . getClassName ( ) ) ; assertEquals ( "" , behavior . getSource ( ) ) ; assertEquals ( , behavior . getSourceRange ( ) . getOffset ( ) ) ; assertEquals ( src . length ( ) , behavior . getSourceRange ( ) . getLength ( ) ) ; assertEquals ( , behavior . getExamples ( ) . length ) ; Example example = ( Example ) behavior . getExamples ( ) [ ] ; assertEquals ( behavior , example . getBehavior ( ) ) ; assertEquals ( "" , example . getDescription ( ) ) ; assertEquals ( "" , example . getSource ( ) ) ; assertEquals ( , example . getSourceRange ( ) . getOffset ( ) ) ; assertEquals ( , example . getSourceRange ( ) . getLength ( ) ) ; } } package com . aptana . rdt ; import java . io . File ; import java . io . IOException ; import java . net . URL ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Plugin ; public class AptanaRDTTests extends Plugin { private static AptanaRDTTests plugin ; public AptanaRDTTests ( ) { super ( ) ; plugin = this ; } public static File getFileInPlugin ( IPath path ) { try { URL installURL = new URL ( getDefault ( ) . getBundle ( ) . getEntry ( "" ) , path . toString ( ) ) ; URL localURL = FileLocator . toFileURL ( installURL ) ; return new File ( localURL . getFile ( ) ) ; } catch ( IOException ioe ) { return null ; } } public static AptanaRDTTests getDefault ( ) { return plugin ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . List ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . AbstractRubyLintVisitorTestCase ; import com . aptana . rdt . IProblem ; import com . aptana . rdt . internal . parser . warnings . ControlCouple ; public class ControlCoupleTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new ControlCouple ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testControlCouple ( ) { String src = "" + "" + "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . ControlCouple , problems . get ( ) . getID ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . Map ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . internal . parser . warnings . TooManyArgumentsVisitor ; public class TC_CodeComplexityTooManyArguments extends WarningVisitorTest { private static final int MAX_ARGS ; static { Map < String , String > options = AptanaRDTPlugin . getDefault ( ) . getOptions ( ) ; int max ; try { max = Integer . parseInt ( ( String ) options . get ( AptanaRDTPlugin . COMPILER_PB_MAX_ARGUMENTS ) ) ; } catch ( NumberFormatException e ) { max = TooManyArgumentsVisitor . DEFAULT_MAX_ARGS ; } MAX_ARGS = max ; } @ Override protected RubyLintVisitor createVisitor ( String code ) { return new TooManyArgumentsVisitor ( code ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testTooManyArgs ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_ARGS + ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; if ( i < MAX_ARGS + ) { buffer . append ( '' ) ; } } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testEqualToMaxArgs ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_ARGS ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; if ( i < MAX_ARGS ) { buffer . append ( "" ) ; } } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testLessThanMaxArgs ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_ARGS - ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; if ( i < MAX_ARGS - ) { buffer . append ( '' ) ; } } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . Map ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . internal . parser . warnings . TooManyLinesVisitor ; import com . aptana . rdt . internal . parser . warnings . TooManyLocalsVisitor ; public class TC_CodeComplexityMaxLocals extends WarningVisitorTest { private static final int MAX_LOCALS ; static { Map < String , String > options = AptanaRDTPlugin . getDefault ( ) . getOptions ( ) ; int max ; try { max = Integer . parseInt ( ( String ) options . get ( AptanaRDTPlugin . COMPILER_PB_MAX_LOCALS ) ) ; } catch ( NumberFormatException e ) { max = TooManyLocalsVisitor . DEFAULT_MAX_LOCALS ; } MAX_LOCALS = max ; } @ Override protected RubyLintVisitor createVisitor ( String code ) { return new TooManyLocalsVisitor ( code ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testTooManyLocals ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_LOCALS + ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testEqualToMaxLocals ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_LOCALS ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testLessThanMaxLocals ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_LOCALS - ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . Map ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . internal . parser . warnings . TooManyArgumentsVisitor ; import com . aptana . rdt . internal . parser . warnings . TooManyReturnsVisitor ; public class TC_CodeComplexityTooManyReturns extends WarningVisitorTest { private static final int MAX_RETURNS ; static { Map < String , String > options = AptanaRDTPlugin . getDefault ( ) . getOptions ( ) ; int max ; try { max = Integer . parseInt ( ( String ) options . get ( AptanaRDTPlugin . COMPILER_PB_MAX_RETURNS ) ) ; } catch ( NumberFormatException e ) { max = TooManyReturnsVisitor . DEFAULT_MAX_RETURNS ; } MAX_RETURNS = max ; } @ Override protected RubyLintVisitor createVisitor ( String code ) { return new TooManyReturnsVisitor ( code ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testTooManyReturns ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_RETURNS + ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testEqualToMaxReturns ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_RETURNS ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testLessThanMaxReturns ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_RETURNS - ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . internal . parser . warnings . UnecessaryElseVisitor ; public class TC_UnecessaryElseVisitor extends WarningVisitorTest { @ Override protected RubyLintVisitor createVisitor ( String code ) { return new UnecessaryElseVisitor ( code ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testSimpleIfElse ( ) throws Exception { parse ( "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testIfWithNoElseDoesntGetMarked ( ) throws Exception { parse ( "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testIfElseWithNoExplicitReturnDoesntGetMarked ( ) throws Exception { parse ( "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testNestedIfs ( ) throws Exception { parse ( "" + "" + "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testNestedIfsB ( ) throws Exception { parse ( "" + "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testNestedIfsAllWithExplicitReturns ( ) throws Exception { parse ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testIfModifierIsntProblem ( ) throws Exception { parse ( "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testUnlessModifierIsntProblem ( ) throws Exception { parse ( "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testUnlessWithEachCanHaveProblem ( ) throws Exception { parse ( "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testSwitchInsideIfWithAllExplicitReturns ( ) throws Exception { parse ( "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testSwitchInsideIfWithoutAllHavingExplicitReturns ( ) throws Exception { parse ( "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testSwitchInsideUnlessWithAllExplicitReturns ( ) throws Exception { parse ( "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testSwitchInsideUnlessWithoutAllHavingExplicitReturns ( ) throws Exception { parse ( "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_ParserWarnings { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_SimilarVariableNameVisitor . class ) ; suite . addTestSuite ( TC_UnecessaryElseVisitor . class ) ; suite . addTestSuite ( TC_CodeComplexity . class ) ; suite . addTestSuite ( TC_CodeComplexityTooManyArguments . class ) ; suite . addTestSuite ( TC_CodeComplexityMaxLocals . class ) ; suite . addTestSuite ( TC_CodeComplexityTooManyReturns . class ) ; suite . addTestSuite ( TC_ComparableInclusionVisitor . class ) ; suite . addTestSuite ( TC_EnumerableInclusionVisitor . class ) ; suite . addTestSuite ( ControlCoupleTest . class ) ; suite . addTestSuite ( FeatureEnvyTest . class ) ; suite . addTestSuite ( UncommunicativeNameTest . class ) ; suite . addTestSuite ( LocalsMaskingMethodsVisitorTest . class ) ; suite . addTestSuite ( DynamicVariableAliasesLocalTest . class ) ; suite . addTestSuite ( ConstantNamingConventionTest . class ) ; suite . addTestSuite ( AccidentalBooleanAssignmentVisitorTest . class ) ; return suite ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . List ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . AbstractRubyLintVisitorTestCase ; import com . aptana . rdt . IProblem ; import com . aptana . rdt . internal . parser . warnings . AccidentalBooleanAssignmentVisitor ; public class AccidentalBooleanAssignmentVisitorTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new AccidentalBooleanAssignmentVisitor ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testSimpleLocalVarAsgnInIfCondition ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . PossibleAccidentalBooleanAssignment , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testSimpleLocalVarAsgnInIfConditionDoesntGenerateWarningIfLocalVarNotAssignedToBefore ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } public void testSimpleLocalVarAsgnWithIfModifier ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . PossibleAccidentalBooleanAssignment , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testSimpleLocalVarAsgnInUnlessCondition ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . PossibleAccidentalBooleanAssignment , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testSimpleLocalVarAsgnWithUnlessModifier ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . PossibleAccidentalBooleanAssignment , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testConstantAssignmentInIfCondition ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . PossibleAccidentalBooleanAssignment , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testInstanceVariableAssignmentInIfCondition ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . PossibleAccidentalBooleanAssignment , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testClassVariableAssignmentInIfCondition ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . PossibleAccidentalBooleanAssignment , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testSimpleLocalVarAsgnInWhenExpression ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . PossibleAccidentalBooleanAssignment , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testNoFalsePositive ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . internal . parser . warnings . EnumerableInclusionVisitor ; public class TC_EnumerableInclusionVisitor extends WarningVisitorTest { @ Override protected RubyLintVisitor createVisitor ( String code ) { return new EnumerableInclusionVisitor ( code ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testBasicCase ( ) { parse ( "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testNoFalsePositive ( ) { parse ( "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . Map ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . AptanaRDTPlugin ; import com . aptana . rdt . internal . parser . warnings . TooManyLinesVisitor ; public class TC_CodeComplexity extends WarningVisitorTest { private static final int MAX_LINES ; static { Map < String , String > options = AptanaRDTPlugin . getDefault ( ) . getOptions ( ) ; int max ; try { max = Integer . parseInt ( ( String ) options . get ( AptanaRDTPlugin . COMPILER_PB_MAX_LINES ) ) ; } catch ( NumberFormatException e ) { max = TooManyLinesVisitor . DEFAULT_MAX_LINES ; } MAX_LINES = max ; } @ Override protected RubyLintVisitor createVisitor ( String code ) { return new TooManyLinesVisitor ( code ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testTooManyLines ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_LINES + ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testEqualToMaxLines ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_LINES ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testLessThanMaxLines ( ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "" ) ; for ( int i = ; i <= MAX_LINES - ; i ++ ) { buffer . append ( "" ) ; buffer . append ( i ) ; buffer . append ( "" ) ; } buffer . append ( "" ) ; parse ( buffer . toString ( ) ) ; assertEquals ( , numberOfProblems ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . internal . parser . warnings . ComparableInclusionVisitor ; public class TC_ComparableInclusionVisitor extends WarningVisitorTest { @ Override protected RubyLintVisitor createVisitor ( String code ) { return new ComparableInclusionVisitor ( code ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testBasicCase ( ) { parse ( "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testNoFalsePositive ( ) { parse ( "" + "" + "" + "" + "" + "" ) ; assertEquals ( , numberOfProblems ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . List ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . AbstractRubyLintVisitorTestCase ; import com . aptana . rdt . IProblem ; import com . aptana . rdt . internal . parser . warnings . ConstantNamingConvention ; public class ConstantNamingConventionTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new ConstantNamingConvention ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testCamelCaseConstantNameGeneratesWarning ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . ConstantNamingConvention , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testNoFalsePositive ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . Collections ; import java . util . Comparator ; import java . util . List ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . AbstractRubyLintVisitorTestCase ; import com . aptana . rdt . IProblem ; import com . aptana . rdt . internal . parser . warnings . LocalsMaskingMethodsVisitor ; public class LocalsMaskingMethodsVisitorTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new LocalsMaskingMethodsVisitor ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testLocalVariableMatchesMethodName ( ) { String src = "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . LocalMaskingMethod , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testLocalVariableMatchesAttrAccessor ( ) { String src = "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . LocalMaskingMethod , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testAssigningToAttrWithWriterProducesNoWarning ( ) { String src = "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } public void testOnlyWarnsOnFirstAssignmentInScope ( ) { String src = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . LocalMaskingMethod , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testOnlyWarnsOnFirstAssignmentPerScope ( ) { String src = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; Collections . sort ( problems , new Comparator < CategorizedProblem > ( ) { public int compare ( CategorizedProblem o1 , CategorizedProblem o2 ) { return o1 . getSourceStart ( ) - o2 . getSourceStart ( ) ; } } ) ; assertEquals ( IProblem . LocalMaskingMethod , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; assertEquals ( IProblem . LocalMaskingMethod , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . List ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . AbstractRubyLintVisitorTestCase ; import com . aptana . rdt . IProblem ; import com . aptana . rdt . internal . parser . warnings . DynamicVariableAliasesLocal ; public class DynamicVariableAliasesLocalTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new DynamicVariableAliasesLocal ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testDynamicVarMatchesLocalVarNameInScope ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . DynamicVariableAliasesLocal , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testNoFalsePositiveForNewDynamicVarName ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } public void testOneDynamicVarInListOfVarsMatchesLocalVarNameInScope ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . DynamicVariableAliasesLocal , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } public void testMultipleDynamicVarInListOfVarsMatchesLocalVarNameInScope ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . DynamicVariableAliasesLocal , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; assertEquals ( IProblem . DynamicVariableAliasesLocal , problems . get ( ) . getID ( ) ) ; assertEquals ( , problems . get ( ) . getSourceStart ( ) ) ; assertEquals ( , problems . get ( ) . getSourceEnd ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . List ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . AbstractRubyLintVisitorTestCase ; import com . aptana . rdt . IProblem ; import com . aptana . rdt . internal . parser . warnings . UncommunicativeName ; public class UncommunicativeNameTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new UncommunicativeName ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testOneCharDefnName ( ) { String src = "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharWithDigitDefnName ( ) { String src = "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharDefsName ( ) { String src = "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharWithDigitDefsName ( ) { String src = "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharBlockVarName ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharWithDigitBlockVarName ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharInstanceVarName ( ) { String src = "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharWithDigitInstanceVarName ( ) { String src = "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOnlyWarnsOnceAboutInstanceVariablesWithShortNames ( ) { String src = "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOnlyWarnsOnceAboutClassVariablesWithShortNames ( ) { String src = "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharClassVarName ( ) { String src = "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharWithDigitClassVarName ( ) { String src = "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharClassName ( ) { String src = "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharWithDigitClassName ( ) { String src = "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharModuleName ( ) { String src = "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } public void testOneCharWithDigitModuleName ( ) { String src = "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . UncommunicativeName , problems . get ( ) . getID ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . List ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . warnings . AbstractRubyLintVisitorTestCase ; import com . aptana . rdt . IProblem ; import com . aptana . rdt . internal . parser . warnings . FeatureEnvy ; public class FeatureEnvyTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new FeatureEnvy ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testEnvyOfAnotherReceiver ( ) { String src = "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; assertEquals ( IProblem . FeatureEnvy , problems . get ( ) . getID ( ) ) ; } public void testNoEnvyIfJustOneReferenceByDefault ( ) { String src = "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } public void testNoEnvyofImplicitSelf ( ) { String src = "" + "" + "" + "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; src = "" + "" + "" + "" + "" ; problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } public void testNoEnvyofDynamicVars ( ) { String src = "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } public void testNoEnvyofExplicitSelf ( ) { String src = "" + "" + "" + "" + "" + "" + "" ; List < CategorizedProblem > problems = getProblems ( src ) ; assertEquals ( , problems . size ( ) ) ; } } package com . aptana . rdt . internal . core . parser . warnings ; import java . util . HashSet ; import java . util . Set ; import org . rubypeople . rdt . core . IProblemRequestor ; import org . rubypeople . rdt . core . compiler . IProblem ; public class MockProblemRequestor implements IProblemRequestor { private boolean active ; private Set < IProblem > problems = new HashSet < IProblem > ( ) ; public void acceptProblem ( IProblem problem ) { problems . add ( problem ) ; } public void beginReporting ( ) { active = true ; } public void endReporting ( ) { active = false ; } public boolean isActive ( ) { return active ; } public int numberOfProblems ( ) { return problems . size ( ) ; } public IProblem getProblemAtLine ( int i ) { for ( IProblem problem : problems ) { if ( problem . getSourceLineNumber ( ) == i ) return problem ; } return null ; } } package com . aptana . rdt . internal . core . parser . warnings ; import junit . framework . TestCase ; import org . jruby . ast . Node ; import org . rubypeople . rdt . core . compiler . IProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; public abstract class WarningVisitorTest extends TestCase { private RubyParser parser ; private RubyLintVisitor visitor ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; parser = new RubyParser ( ) ; } protected void parse ( String code ) { Node root = parser . parse ( code ) . getAST ( ) ; visitor = createVisitor ( code ) ; root . accept ( visitor ) ; } public int numberOfProblems ( ) { return visitor . getProblems ( ) . size ( ) ; } protected IProblem getProblemAtLine ( int i ) { return visitor . getProblems ( ) . get ( i ) ; } abstract protected RubyLintVisitor createVisitor ( String code ) ; } package com . aptana . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import com . aptana . rdt . internal . parser . warnings . SimilarVariableNameVisitor ; public class TC_SimilarVariableNameVisitor extends WarningVisitorTest { @ Override protected RubyLintVisitor createVisitor ( String code ) { return new SimilarVariableNameVisitor ( code ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testEmptyHasNoProblems ( ) throws Exception { String code = "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testReferToLocalWithSimilarName ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testTranspositionDoesntPushSmallVariablesAboveThreshold ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testLocalDoesntClashWithInstance ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testLocalDoesntClashWithClassVar ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testInstanceDoesntClashWithClassVar ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testReallySmallVariablesDontTriggerProblem ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testReallySmallClassVariablesDontTriggerProblem ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testTooDisimilarNameWontTriggerProblem ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testReferToInstanceVarWithSimilarName ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testReferToClassVarWithSimilarName ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testHandleInstanceVariableToClassScoping ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } public void testHandleVarsOutsideMethods ( ) throws Exception { String code = "" + "" + "" + "" + "" + "" + "" + "" + "" ; parse ( code ) ; assertEquals ( , numberOfProblems ( ) ) ; } } package com . aptana . rdt . internal . core . gems ; import java . util . Set ; import com . aptana . rdt . core . gems . Gem ; public class ShortListingGemParserTest extends AbstractGemParserTestCase { @ Override protected IGemParser getParser ( ) { return new ShortListingGemParser ( ) ; } public void testBlah ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } } package com . aptana . rdt . internal . core . gems ; import java . io . File ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . runtime . IProgressMonitor ; import junit . framework . TestCase ; import com . aptana . rdt . core . gems . Gem ; public class GemManagerTest extends TestCase { public void testRemoteGemCacheCompressedToLogicalGems ( ) throws Exception { GemManager manager = new GemManager ( ) { protected Set < Gem > loadRemoteGems ( String gemIndexUrl , IProgressMonitor monitor ) { Set < Gem > gems = new HashSet < Gem > ( ) ; gems . add ( new Gem ( "" , "" , "" , "" ) ) ; gems . add ( new Gem ( "" , "" , "" , "" ) ) ; return gems ; } protected File getConfigFile ( String fileName ) { return null ; } protected Set < String > loadSourceURLs ( ) { return new HashSet < String > ( ) ; } protected void addSourceURL ( String sourceURL ) { } } ; Set < Gem > gems = manager . getRemoteGems ( ) ; assertEquals ( , gems . size ( ) ) ; } } package com . aptana . rdt . internal . core . gems ; import java . util . Set ; import com . aptana . rdt . core . gems . Gem ; public class GemParserTest extends AbstractGemParserTestCase { public void testParsingLocalGems ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } public void testEndsWithTwoLineDescription ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } public void testMattsBrokenList ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } public void testJavaHomeErrorFromJRuby ( ) throws GemParseException { String contents = "" ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } public void testUpdating ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } protected IGemParser getParser ( ) { return new LegacyGemParser ( "" ) ; } } package com . aptana . rdt . internal . core . gems ; import java . util . Set ; import com . aptana . rdt . core . gems . Gem ; public class GemOnePointTwoParserTest extends AbstractGemParserTestCase { public void testParsingLocalGems ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } public void testRubygems1dot3 ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } public void testRubygems1dot3Remote ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } protected LegacyGemParser getParser ( ) { return new GemOnePointTwoParser ( "" ) ; } } package com . aptana . rdt . internal . core . gems ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileReader ; import java . io . IOException ; import java . io . InputStream ; import junit . framework . TestCase ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . util . Util ; import com . aptana . rdt . AptanaRDTTests ; public abstract class AbstractGemParserTestCase extends TestCase { public AbstractGemParserTestCase ( ) { super ( ) ; } public AbstractGemParserTestCase ( String name ) { super ( name ) ; } protected abstract IGemParser getParser ( ) ; protected String getContents ( String path ) { String result = tryResourceAsStream ( path ) ; if ( result != null ) return result ; File file = grabFile ( path ) ; if ( file == null ) fail ( "" + path ) ; return readFile ( file ) ; } private String readFile ( File file ) { BufferedReader reader = null ; StringBuffer buffer ; try { reader = new BufferedReader ( new FileReader ( file ) ) ; String line = null ; buffer = new StringBuffer ( ) ; while ( ( line = reader . readLine ( ) ) != null ) { buffer . append ( line ) ; buffer . append ( "" ) ; } buffer . deleteCharAt ( buffer . length ( ) - ) ; return buffer . toString ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { try { if ( reader != null ) reader . close ( ) ; } catch ( IOException e ) { } } return null ; } private File grabFile ( String path ) { File file = null ; try { file = AptanaRDTTests . getFileInPlugin ( new Path ( path ) ) ; } catch ( Throwable e ) { File dir = new File ( "" ) ; try { file = new File ( dir . getCanonicalFile ( ) , "" + File . separator + path ) ; } catch ( IOException e1 ) { } } return file ; } private String tryResourceAsStream ( String path ) { try { IPath thing = new Path ( path ) ; String fileName = thing . lastSegment ( ) ; InputStream stream = this . getClass ( ) . getResourceAsStream ( fileName ) ; if ( stream != null ) { return new String ( Util . getInputStreamAsCharArray ( stream , - , null ) ) ; } } catch ( IOException e ) { } return null ; } } package com . aptana . rdt . internal . core . gems ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( GemParserTest . class ) ; suite . addTestSuite ( GemOnePointTwoParserTest . class ) ; suite . addTestSuite ( ShortListingGemParserTest . class ) ; suite . addTestSuite ( HybridGemParserTest . class ) ; suite . addTestSuite ( GemManagerTest . class ) ; return suite ; } } package com . aptana . rdt . internal . core . gems ; import java . util . Set ; import com . aptana . rdt . core . gems . Gem ; import com . aptana . rdt . core . gems . Version ; public class HybridGemParserTest extends GemParserTest { public void testOneDotTwo ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } public void testRubygems1dot3 ( ) throws GemParseException { String contents = getContents ( "" ) ; Set < Gem > gems = getParser ( ) . parse ( contents ) ; assertEquals ( , gems . size ( ) ) ; } protected IGemParser getParser ( ) { return new HybridGemParser ( new Version ( "" ) ) ; } } package com . aptana . rdt ; import junit . framework . Test ; import junit . framework . TestSuite ; import com . aptana . rdt . core . rspec . RSpecStructureCreatorTest ; import com . aptana . rdt . internal . core . gems . AllTests ; import com . aptana . rdt . internal . core . parser . warnings . TS_ParserWarnings ; public class TS_Aptana { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( TS_ParserWarnings . suite ( ) ) ; suite . addTestSuite ( RSpecStructureCreatorTest . class ) ; suite . addTest ( AllTests . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests ; import java . util . Collection ; import java . util . Map ; import org . rubypeople . rdt . refactoring . core . IRefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; public abstract class RefactoringConditionTestCase extends RefactoringTestCase { private String name ; protected abstract void createEditProviderAndSetUserInput ( ) ; public RefactoringConditionTestCase ( String name ) { super ( name ) ; this . name = name ; } protected void checkConditions ( RefactoringConditionChecker checker , FilePropertyData testData ) { checkInitialConditionCheckResult ( checker , testData ) ; if ( checker . shouldPerform ( ) ) { createEditProviderAndSetUserInput ( ) ; checkFinalConditionCheckResult ( checker , testData ) ; } else { Collection < String > expectedWarnings = getExpectedStrings ( testData , "" ) ; Collection < String > expectedErrors = getExpectedStrings ( testData , "" ) ; assertEquals ( , expectedWarnings . size ( ) ) ; assertEquals ( , expectedErrors . size ( ) ) ; } } protected void assertStringCollection ( Collection < String > expectedCollection , Collection < String > collection ) { if ( expectedCollection . size ( ) != collection . size ( ) ) { printArrays ( expectedCollection , collection ) ; fail ( "" ) ; } for ( String aktExpected : expectedCollection ) { if ( collection . contains ( aktExpected ) ) { collection . remove ( expectedCollection ) ; } else { printArrays ( expectedCollection , collection ) ; fail ( "" + aktExpected + "" ) ; } } } private void printArrays ( Collection < String > expectedCollection , Collection < String > collection ) { System . err . println ( "" + name ) ; System . err . println ( "" + expectedCollection . size ( ) + "" ) ; for ( String expectedString : expectedCollection ) { System . err . println ( expectedString ) ; } System . err . println ( ) ; System . err . println ( "" + collection . size ( ) + "" ) ; for ( String aktString : collection ) { System . err . println ( aktString ) ; } System . err . println ( ) ; } private void checkInitialConditionCheckResult ( IRefactoringConditionChecker conditionChecker , FilePropertyData testData ) { Map < String , Collection < String > > messages = conditionChecker . getInitialMessages ( ) ; checkConditionCheckResult ( messages , testData , "" ) ; } private void checkFinalConditionCheckResult ( IRefactoringConditionChecker conditionChecker , FilePropertyData testData ) { Map < String , Collection < String > > messages = conditionChecker . getFinalMessages ( ) ; checkConditionCheckResult ( messages , testData , "" ) ; } private void checkConditionCheckResult ( Map < String , Collection < String > > messages , FilePropertyData testData , String propertyNameSufix ) { Collection < String > warnings = messages . get ( IRefactoringConditionChecker . WARNING ) ; Collection < String > errors = messages . get ( IRefactoringConditionChecker . ERRORS ) ; Collection < String > expectedWarnings = getExpectedStrings ( testData , propertyNameSufix + "" ) ; Collection < String > expectedErrors = getExpectedStrings ( testData , propertyNameSufix + "" ) ; assertStringCollection ( expectedWarnings , warnings ) ; assertStringCollection ( expectedErrors , errors ) ; } private Collection < String > getExpectedStrings ( FilePropertyData testData , String propertyName ) { return testData . getNumberedProperty ( propertyName ) ; } } package org . rubypeople . rdt . refactoring . tests ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . util . FileHelper ; public abstract class FileTestCase extends RefactoringTestCase { public FileTestCase ( String name ) { super ( name ) ; } protected String getSource ( String file ) { return FileHelper . getFileContent ( TestsPlugin . getFile ( file ) ) ; } protected RootNode getRootNode ( String fileName ) { return NodeProvider . getRootNode ( "" , getSource ( fileName ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core ; import java . util . Collection ; import org . jruby . ast . ConstNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . rubypeople . rdt . refactoring . core . ModuleNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ModuleNodeWrapper ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; public class TC_ModuleNodeProvider extends FileTestCase { public TC_ModuleNodeProvider ( ) { super ( "" ) ; } private ModuleNodeWrapper findModule ( String file , int position ) { return ModuleNodeProvider . getSelectedModuleNode ( getRootNode ( file ) , position ) ; } private Collection < ModuleNodeWrapper > findModules ( String file , ModuleNodeWrapper moduleNode ) { return ModuleNodeProvider . findOtherParts ( new StringDocumentProvider ( "" , getSource ( file ) ) , moduleNode ) ; } public void testSimpleModule ( ) { ModuleNodeWrapper moduleNode = findModule ( "" , ) ; assertNull ( moduleNode . getParentModule ( ) ) ; assertNotNull ( moduleNode . getWrappedNode ( ) ) ; assertEquals ( "" , moduleNode . getName ( ) ) ; assertEquals ( "" , moduleNode . getFullName ( ) ) ; } public void testModuleWithParent ( ) { ModuleNodeWrapper moduleNode = findModule ( "" , ) ; assertNotNull ( moduleNode . getParentModule ( ) ) ; assertNotNull ( moduleNode . getParentModule ( ) . getWrappedNode ( ) ) ; assertNull ( moduleNode . getParentModule ( ) . getParentModule ( ) ) ; assertNotNull ( moduleNode . getWrappedNode ( ) ) ; assertEquals ( "" , moduleNode . getName ( ) ) ; assertEquals ( "" , moduleNode . getFullName ( ) ) ; } public void testModuleWithMultipleParents ( ) { ModuleNodeWrapper moduleNode = findModule ( "" , ) ; assertEquals ( "" , moduleNode . getName ( ) ) ; assertEquals ( "" , moduleNode . getFullName ( ) ) ; } public void testTwoSimpleModules ( ) { ModuleNodeWrapper [ ] nodeWrappers = getModules ( "" , ) . toArray ( new ModuleNodeWrapper [ ] { } ) ; assertEquals ( , nodeWrappers . length ) ; assertEquals ( "" , nodeWrappers [ ] . getFullName ( ) ) ; assertEquals ( "" , nodeWrappers [ ] . getFullName ( ) ) ; } private Collection < ModuleNodeWrapper > getModules ( String fileName , int pos ) { ModuleNodeWrapper moduleNode = findModule ( fileName , pos ) ; return findModules ( fileName , moduleNode ) ; } public void testFindSingleMethod ( ) { Collection < ModuleNodeWrapper > modules = getModules ( "" , ) ; ConstNode [ ] nodes = ModuleNodeProvider . getAllModuleMethodDefinitions ( modules ) . toArray ( new ConstNode [ ] { } ) ; assertEquals ( , nodes . length ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( new IDESourcePosition ( "" , , , , ) , nodes [ ] . getPosition ( ) ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( new IDESourcePosition ( "" , , , , ) , nodes [ ] . getPosition ( ) ) ; } public void testFindMultipleMethods ( ) { Collection < ModuleNodeWrapper > modules = getModules ( "" , ) ; ConstNode [ ] nodes = ModuleNodeProvider . getAllModuleMethodDefinitions ( modules ) . toArray ( new ConstNode [ ] { } ) ; assertEquals ( , nodes . length ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( new IDESourcePosition ( "" , , , , ) , nodes [ ] . getPosition ( ) ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( new IDESourcePosition ( "" , , , , ) , nodes [ ] . getPosition ( ) ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( new IDESourcePosition ( "" , , , , ) , nodes [ ] . getPosition ( ) ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( new IDESourcePosition ( "" , , , , ) , nodes [ ] . getPosition ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . extractmethod ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractMethodConfig ; import org . rubypeople . rdt . refactoring . core . extractmethod . MethodExtractor ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class ExtractMethodTester extends FileTestCase { public ExtractMethodTester ( String fileName ) { super ( fileName ) ; } private VisibilityNodeWrapper . METHOD_VISIBILITY getVisibility ( FileTestData data ) { if ( ! data . hasProperty ( "" ) ) { return METHOD_VISIBILITY . NONE ; } String v = data . getProperty ( "" ) ; if ( v . equals ( "" ) ) { return METHOD_VISIBILITY . PUBLIC ; } else if ( v . equals ( "" ) ) { return METHOD_VISIBILITY . PROTECTED ; } else if ( v . equals ( "" ) ) { return METHOD_VISIBILITY . PRIVATE ; } else { return METHOD_VISIBILITY . NONE ; } } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData testData = new FileTestData ( getName ( ) , "" , "" ) ; IRefactoringContext selection = new RefactoringContext ( testData . getIntProperty ( "" ) , testData . getIntProperty ( "" ) , testData . getIntProperty ( "" ) , "" ) ; ExtractMethodConfig config = new ExtractMethodConfig ( testData , selection ) ; ExtractMethodConditionChecker checker = new ExtractMethodConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } MethodExtractor methodExtractor = new MethodExtractor ( config ) ; config . getHelper ( ) . setMethodName ( testData . getProperty ( "" ) ) ; config . getHelper ( ) . setVisibility ( getVisibility ( testData ) ) ; if ( testData . hasProperty ( "" ) ) { for ( String orderInstruction : testData . getCommaSeparatedStringArray ( "" ) ) { String [ ] instruction = orderInstruction . split ( "" ) ; assertEquals ( , instruction . length ) ; int index = Integer . parseInt ( instruction [ ] ) ; if ( instruction [ ] . equals ( "" ) ) { config . getHelper ( ) . changeParameter ( index , index - ) ; } else if ( instruction [ ] . equals ( "" ) ) { config . getHelper ( ) . changeParameter ( index , index + ) ; } } } if ( testData . hasProperty ( "" ) ) { String [ ] names = testData . getCommaSeparatedStringArray ( "" ) ; assertEquals ( names . length , names . length ) ; for ( int i = ; i < names . length ; i ++ ) { config . getHelper ( ) . changeParameter ( i , names [ i ] ) ; } } createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , methodExtractor ) ; } } package org . rubypeople . rdt . refactoring . tests . core . extractmethod ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . extractmethod . conditionchecks . TS_ExtractMethodChecks ; public class TS_ExtractMethod extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , ExtractMethodTester . class ) ; suite . addTest ( TS_ExtractMethodChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . extractmethod . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_ExtractMethodChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , ExtractMethodConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . extractmethod . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . extractmethod . ExtractMethodConfig ; import org . rubypeople . rdt . refactoring . core . extractmethod . MethodExtractor ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class ExtractMethodConditionTester extends RefactoringConditionTestCase { private FilePropertyData testData ; private ExtractMethodConfig config ; public ExtractMethodConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; IRefactoringContext selection = new RefactoringContext ( testData . getIntProperty ( "" ) , testData . getIntProperty ( "" ) , "" ) ; config = new ExtractMethodConfig ( testData , selection ) ; ExtractMethodConditionChecker checker = new ExtractMethodConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new MethodExtractor ( config ) ; config . getHelper ( ) . setMethodName ( testData . getProperty ( "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinelocal ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . inlinelocal . conditionchecks . TS_InlineLocalConditionChecks ; public class TS_InlineLocal extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , LocalInlinerTester . class ) ; suite . addTest ( TS_InlineLocalConditionChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinelocal ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . inlinelocal . InlineLocalConditionChecker ; import org . rubypeople . rdt . refactoring . core . inlinelocal . InlineLocalConfig ; import org . rubypeople . rdt . refactoring . core . inlinelocal . LocalVariableInliner ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class LocalInlinerTester extends RefactoringTestCase { public LocalInlinerTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData data = new FileTestData ( getName ( ) ) ; InlineLocalConfig config = new InlineLocalConfig ( data , data . getIntProperty ( "" ) ) ; InlineLocalConditionChecker checker = new InlineLocalConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } LocalVariableInliner inliner = new LocalVariableInliner ( config ) ; config . setReplaceTempWithQuery ( data . getBoolProperty ( "" ) ) ; config . setNewMethodName ( data . getProperty ( "" ) ) ; createEditAndCompareResult ( data . getActiveFileContent ( ) , data . getExpectedResult ( ) , inliner ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinelocal . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . inlinelocal . InlineLocalConditionChecker ; import org . rubypeople . rdt . refactoring . core . inlinelocal . InlineLocalConfig ; import org . rubypeople . rdt . refactoring . core . inlinelocal . LocalVariableInliner ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class InlineLocalConditionTester extends RefactoringConditionTestCase { private InlineLocalConfig config ; private FileTestData testData ; public InlineLocalConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; config = new InlineLocalConfig ( testData , testData . getIntProperty ( "" ) ) ; InlineLocalConditionChecker checker = new InlineLocalConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new LocalVariableInliner ( config ) ; if ( testData . hasProperty ( "" ) ) { config . setReplaceTempWithQuery ( true ) ; config . setNewMethodName ( testData . getProperty ( "" ) ) ; } } } package org . rubypeople . rdt . refactoring . tests . core . inlinelocal . conditionchecks ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_InlineLocalConditionChecks extends FileTestSuite { public static TestSuite suite ( ) { return createSuite ( "" , "" , InlineLocalConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . mergeclasspartsinfile ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . mergeclasspartsinfile . conditionchecks . TS_MergeClassPartsInFileChecks ; public class TS_MergeClassPartsInFile extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , ClassPartSelectorTester . class ) ; suite . addTest ( TS_MergeClassPartsInFileChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . mergeclasspartsinfile . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_MergeClassPartsInFileChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , MergeInFileConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . mergeclasspartsinfile . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . InFileClassPartsMerger ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . MergeClassPartInFileConfig ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . MergeClassPartsInFileConditionChecker ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class MergeInFileConditionTester extends RefactoringConditionTestCase { private MergeClassPartInFileConfig config ; public MergeInFileConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { FilePropertyData testData = new FileTestData ( getName ( ) , "" , "" ) ; config = new MergeClassPartInFileConfig ( testData ) ; RefactoringConditionChecker checker = new MergeClassPartsInFileConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new InFileClassPartsMerger ( config ) ; } } package org . rubypeople . rdt . refactoring . tests . core . mergeclasspartsinfile ; import java . util . ArrayList ; import java . util . Collection ; import java . util . StringTokenizer ; import java . util . Vector ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . InFileClassPartsMerger ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . MergeClassPartInFileConfig ; import org . rubypeople . rdt . refactoring . core . mergeclasspartsinfile . MergeClassPartsInFileConditionChecker ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class ClassPartSelectorTester extends RefactoringTestCase { private FileTestData testData ; public ClassPartSelectorTester ( String fileName ) { super ( fileName ) ; } private Collection < PartialClassNodeWrapper > getCheckedParts ( ClassNodeWrapper classNode ) { Collection < Integer > checkedClassPartNumbers = getCheckedPartNumbers ( ) ; ArrayList < PartialClassNodeWrapper > checkedParts = new ArrayList < PartialClassNodeWrapper > ( ) ; PartialClassNodeWrapper [ ] classParts = classNode . getPartialClassNodes ( ) . toArray ( new PartialClassNodeWrapper [ ] ) ; for ( int currentPartNumber : checkedClassPartNumbers ) { checkedParts . add ( classParts [ currentPartNumber - ] ) ; } return checkedParts ; } private Collection < Integer > getCheckedPartNumbers ( ) { String partsProperty = testData . getProperty ( "" ) ; StringTokenizer tokenizer = new StringTokenizer ( partsProperty , "" ) ; Vector < Integer > intValues = new Vector < Integer > ( ) ; while ( tokenizer . hasMoreElements ( ) ) { intValues . add ( Integer . valueOf ( tokenizer . nextToken ( ) . trim ( ) ) ) ; } return intValues ; } private PartialClassNodeWrapper getPart ( ClassNodeWrapper selectedClass , int selectedClassPartNumber ) { Collection < PartialClassNodeWrapper > selectableClassNodes = selectedClass . getPartialClassNodes ( ) ; PartialClassNodeWrapper [ ] partArray = selectableClassNodes . toArray ( new PartialClassNodeWrapper [ ] ) ; return partArray [ selectedClassPartNumber - ] ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; testData = new FileTestData ( getName ( ) ) ; } @ Override protected void tearDown ( ) throws Exception { testData = null ; super . tearDown ( ) ; } @ Override public void runTest ( ) throws Exception { MergeClassPartInFileConfig config = new MergeClassPartInFileConfig ( testData ) ; MergeClassPartsInFileConditionChecker checker = new MergeClassPartsInFileConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } InFileClassPartsMerger selector = new InFileClassPartsMerger ( config ) ; String source = testData . getActiveFileContent ( ) ; String expected = testData . getExpectedResult ( ) ; int selectedClassPartNumber = testData . getIntProperty ( "" ) ; ClassNodeWrapper selectedClass = config . getClassNode ( testData . getProperty ( "" ) ) ; PartialClassNodeWrapper selectedPart = getPart ( selectedClass , selectedClassPartNumber ) ; Collection < PartialClassNodeWrapper > checkedParts = getCheckedParts ( selectedClass ) ; config . setCheckedClassParts ( checkedParts ) ; config . setSelectedClassPart ( selectedPart ) ; createEditAndCompareResult ( source , expected , selector ) ; } } package org . rubypeople . rdt . refactoring . tests . core . mergewithexternalclassparts ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . mergewithexternalclassparts . conditionchecks . TS_MergetWitExternalChecks ; public class TS_MergeWithExternalClassParts extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , MergeWithExternalClassPartsTester . class ) ; suite . addTest ( TS_MergetWitExternalChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . mergewithexternalclassparts . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_MergetWitExternalChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , MergeWithExternalConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . mergewithexternalclassparts . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . ExternalClassPartsMerger ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . MergeWithExternalClassPartConfig ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . MergeWithExternalClassPartsConditionChecker ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class MergeWithExternalConditionTester extends RefactoringConditionTestCase { private MergeWithExternalClassPartConfig config ; public MergeWithExternalConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) ) ; config = new MergeWithExternalClassPartConfig ( testData ) ; MergeWithExternalClassPartsConditionChecker checker = new MergeWithExternalClassPartsConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new ExternalClassPartsMerger ( config ) ; } } package org . rubypeople . rdt . refactoring . tests . core . mergewithexternalclassparts ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . ArrayList ; import java . util . StringTokenizer ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . ClassPartTreeItem ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . ExternalClassPartsMerger ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . MergeWithExternalClassPartConfig ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . MergeWithExternalClassPartsConditionChecker ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . ExternalClassPartsMerger . MergeTreeClassItem ; import org . rubypeople . rdt . refactoring . core . mergewithexternalclassparts . ExternalClassPartsMerger . MergeTreeFileItem ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class MergeWithExternalClassPartsTester extends RefactoringTestCase { public MergeWithExternalClassPartsTester ( String testName ) { super ( testName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) ) ; MergeWithExternalClassPartConfig config = new MergeWithExternalClassPartConfig ( testData ) ; MergeWithExternalClassPartsConditionChecker checker = new MergeWithExternalClassPartsConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } ExternalClassPartsMerger merger = new ExternalClassPartsMerger ( config ) ; ArrayList < ClassPartTreeItem > selection = initSelection ( testData , merger ) ; merger . setSelectedItems ( selection . toArray ( ) ) ; checkMultiFileEdits ( merger , testData ) ; } private ArrayList < ClassPartTreeItem > initSelection ( MultiFileTestData testContext , ExternalClassPartsMerger merger ) { ArrayList < ClassPartTreeItem > selection = new ArrayList < ClassPartTreeItem > ( ) ; ArrayList < MergeTreeClassItem > classItems = merger . getTreeItems ( ) ; int sourceClassPartNumber = testContext . getIntProperty ( "" ) ; for ( MergeTreeClassItem currentItem : classItems ) { if ( currentItem . toString ( ) . equals ( testContext . getProperty ( "" ) ) ) { if ( -- sourceClassPartNumber == ) { addClassToSelection ( testContext , selection , currentItem ) ; } } } return selection ; } private void addClassToSelection ( MultiFileTestData testContext , ArrayList < ClassPartTreeItem > selection , MergeTreeClassItem currentItem ) { selection . add ( currentItem ) ; for ( String currentFileName : testContext . getIncludedFileNames ( ) ) { addClassPartsToSelection ( testContext , selection , currentItem , currentFileName ) ; } } private void addClassPartsToSelection ( MultiFileTestData testContext , ArrayList < ClassPartTreeItem > selection , MergeTreeClassItem currentItem , String currentFileName ) { int currentFilePartNumber = getDestinationClassPartNumber ( currentFileName , testContext ) ; for ( MergeTreeFileItem currentFileItem : currentItem . getClassParts ( ) ) { if ( currentFileItem . toString ( ) . equals ( currentFileName ) ) { if ( -- currentFilePartNumber == ) { selection . add ( currentFileItem ) ; } } } } private int getDestinationClassPartNumber ( String fileName , MultiFileTestData testContext ) { ArrayList < Integer > partNumbers = new ArrayList < Integer > ( ) ; String [ ] destFiles = testContext . getIncludedFileNames ( ) ; String destPartNumbers = testContext . getProperty ( "" ) ; StringTokenizer tokenizer = new StringTokenizer ( destPartNumbers , "" , false ) ; for ( String currentFileName : destFiles ) { Integer currentPart = new Integer ( tokenizer . nextToken ( ) . trim ( ) ) ; if ( currentFileName . equals ( fileName ) ) { partNumbers . add ( currentPart ) ; } } return partNumbers . get ( ) . intValue ( ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlineclass ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . inlineclass . conditionchecks . TS_InlineClassChecks ; public class TS_InlineClass extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , ClassInlinerTester . class ) ; suite . addTest ( TS_InlineClassChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . inlineclass . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_InlineClassChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , InlineClassConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlineclass . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . inlineclass . ClassInliner ; import org . rubypeople . rdt . refactoring . core . inlineclass . InlineClassConditionChecker ; import org . rubypeople . rdt . refactoring . core . inlineclass . InlineClassConfig ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class InlineClassConditionTester extends RefactoringConditionTestCase { private InlineClassConfig config ; private FilePropertyData testData ; public InlineClassConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; config = new InlineClassConfig ( testData , testData . getIntProperty ( "" ) ) ; InlineClassConditionChecker checker = new InlineClassConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new ClassInliner ( config ) ; config . setTargetClassPart ( getTargetClassPart ( testData . getProperty ( "" ) , testData . getIntProperty ( "" ) ) ) ; } private PartialClassNodeWrapper getTargetClassPart ( String fileName , int classPos ) { Node rootNode = testData . getRootNode ( fileName ) ; try { return SelectionNodeProvider . getSelectedClassNode ( rootNode , classPos ) . getFirstPartialClassNode ( ) ; } catch ( NoClassNodeException e ) { assertTrue ( false ) ; return null ; } } } package org . rubypeople . rdt . refactoring . tests . core . inlineclass ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . core . inlineclass . ClassInliner ; import org . rubypeople . rdt . refactoring . core . inlineclass . InlineClassConditionChecker ; import org . rubypeople . rdt . refactoring . core . inlineclass . InlineClassConfig ; import org . rubypeople . rdt . refactoring . exception . NoClassNodeException ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class ClassInlinerTester extends RefactoringTestCase { private MultiFileTestData testData ; public ClassInlinerTester ( String fileName ) { super ( fileName ) ; } private PartialClassNodeWrapper getTargetClassPart ( String fileName , int classPos ) { Node rootNode = testData . getRootNode ( fileName ) ; try { return SelectionNodeProvider . getSelectedClassNode ( rootNode , classPos ) . getFirstPartialClassNode ( ) ; } catch ( NoClassNodeException e ) { assertTrue ( false ) ; return null ; } } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { testData = new MultiFileTestData ( getName ( ) ) ; int caretPosition = testData . getIntProperty ( "" ) ; InlineClassConfig config = new InlineClassConfig ( testData , caretPosition ) ; InlineClassConditionChecker checker = new InlineClassConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } ClassInliner inliner = new ClassInliner ( config ) ; PartialClassNodeWrapper targetClassPart = getTargetClassPart ( testData . getProperty ( "" ) , testData . getIntProperty ( "" ) ) ; config . setTargetClassPart ( targetClassPart ) ; checkMultiFileEdits ( inliner , testData ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemethod . selection ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . Collection ; import org . eclipse . jface . text . BadLocationException ; import org . jruby . ast . SymbolNode ; import org . rubypeople . rdt . refactoring . core . renamemethod . MethodRenamer ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConfig ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class RenameMethodSelectionTester extends RefactoringTestCase { public RenameMethodSelectionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) ) ; int caretPosition = testData . getIntProperty ( "" ) ; RenameMethodConfig config = new RenameMethodConfig ( testData , caretPosition ) ; new RenameMethodConditionChecker ( config ) ; MethodRenamer renamer = new MethodRenamer ( config ) ; config . setNewName ( testData . getProperty ( "" ) ) ; Collection < INodeWrapper > calls = renamer . getCallCandidatesInClass ( ) ; calls . addAll ( renamer . getSubsequentCalls ( ) ) ; config . setSelectedCalls ( calls ) ; Collection < SymbolNode > symbols = renamer . getSymbolCandidatesInClass ( ) ; config . setRenamedSymbols ( symbols ) ; checkMultiFileEdits ( renamer , testData ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemethod . selection ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_RenameMethodSelection extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , RenameMethodSelectionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemethod ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collection ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . IRefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemethod . MethodRenamer ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConfig ; import org . rubypeople . rdt . refactoring . nodewrapper . INodeWrapper ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class MethodRenamerTester extends RefactoringTestCase { public MethodRenamerTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) ) ; int caretPosition = testData . getIntProperty ( "" ) ; RenameMethodConfig config = new RenameMethodConfig ( testData , caretPosition ) ; IRefactoringConditionChecker checker = new RenameMethodConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } MethodRenamer renamer = new MethodRenamer ( config ) ; config . setNewName ( testData . getProperty ( "" ) ) ; if ( testData . getBoolProperty ( "" ) ) { Collection < INodeWrapper > renamedCalls = new ArrayList < INodeWrapper > ( ) ; if ( testData . getBoolProperty ( "" ) ) { renamedCalls . addAll ( config . getPossibleCalls ( ) ) ; } else { renamedCalls . addAll ( renamer . getCallCandidatesInClass ( ) ) ; renamedCalls . addAll ( renamer . getSubsequentCalls ( ) ) ; } config . setSelectedCalls ( renamedCalls ) ; System . out . println ( ) ; } checkMultiFileEdits ( renamer , testData ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemethod ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . renamemethod . conditioncheck . TS_RenameMethodChecks ; import org . rubypeople . rdt . refactoring . tests . core . renamemethod . selection . TS_RenameMethodSelection ; public class TS_RenameMethod extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , MethodRenamerTester . class ) ; suite . addTest ( TS_RenameMethodChecks . suite ( ) ) ; suite . addTest ( TS_RenameMethodSelection . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemethod . conditioncheck ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . renamemethod . MethodRenamer ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemethod . RenameMethodConfig ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class RenameMethodConditionTester extends RefactoringConditionTestCase { private RenameMethodConfig config ; private FilePropertyData testData ; public RenameMethodConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; config = new RenameMethodConfig ( testData , testData . getIntProperty ( "" ) ) ; RenameMethodConditionChecker checker = new RenameMethodConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new MethodRenamer ( config ) ; config . setNewName ( testData . getProperty ( "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemethod . conditioncheck ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_RenameMethodChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , RenameMethodConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemodule ; import org . rubypeople . rdt . refactoring . core . renamemodule . ModuleIncludeFinder ; import org . rubypeople . rdt . refactoring . core . renamemodule . ModuleSpecifierWrapper ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; public class TC_ModuleInclusionFinder extends FileTestCase { public TC_ModuleInclusionFinder ( ) { super ( "" ) ; } public void testSingleDirectInclude ( ) { IDocumentProvider document = getDocument ( "" ) ; ModuleSpecifierWrapper [ ] includes = new ModuleIncludeFinder ( document ) . find ( "" ) . toArray ( new ModuleSpecifierWrapper [ ] { } ) ; assertEquals ( , includes . length ) ; assertNotNull ( includes [ ] . getWrappedNode ( ) ) ; assertEquals ( "" , includes [ ] . getFullName ( ) ) ; } public void testMultipleDirectIncludes ( ) { IDocumentProvider document = getDocument ( "" ) ; ModuleSpecifierWrapper [ ] includes = new ModuleIncludeFinder ( document ) . find ( "" ) . toArray ( new ModuleSpecifierWrapper [ ] { } ) ; assertEquals ( , includes . length ) ; assertEquals ( "" , includes [ ] . getFullName ( ) ) ; assertEquals ( "" , includes [ ] . getFullName ( ) ) ; } public void testIncludeWithNamespace ( ) { IDocumentProvider document = getDocument ( "" ) ; ModuleSpecifierWrapper [ ] includes = new ModuleIncludeFinder ( document ) . find ( "" ) . toArray ( new ModuleSpecifierWrapper [ ] { } ) ; assertEquals ( , includes . length ) ; assertEquals ( "" , includes [ ] . getFullName ( ) ) ; } public void testIncludeFromWithinSameNamespace ( ) { IDocumentProvider document = getDocument ( "" ) ; ModuleSpecifierWrapper [ ] includes = new ModuleIncludeFinder ( document ) . find ( "" ) . toArray ( new ModuleSpecifierWrapper [ ] { } ) ; assertEquals ( , includes . length ) ; assertEquals ( "" , includes [ ] . getFullName ( ) ) ; assertEquals ( "" , includes [ ] . getFullName ( ) ) ; } public void testModulesWithEqualNamesInDifferentNamespaces ( ) { IDocumentProvider document = getDocument ( "" ) ; ModuleSpecifierWrapper [ ] includes = new ModuleIncludeFinder ( document ) . find ( "" ) . toArray ( new ModuleSpecifierWrapper [ ] { } ) ; assertEquals ( , includes . length ) ; assertEquals ( "" , includes [ ] . getFullName ( ) ) ; } public void testNoIncludes ( ) { IDocumentProvider document = getDocument ( "" ) ; ModuleSpecifierWrapper [ ] includes = new ModuleIncludeFinder ( document ) . find ( "" ) . toArray ( new ModuleSpecifierWrapper [ ] { } ) ; assertEquals ( , includes . length ) ; } private IDocumentProvider getDocument ( String name ) { return new StringDocumentProvider ( name , getSource ( name ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemodule . conditionchecker ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleConfig ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleEditProvider ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class RenameModuleConditionTester extends RefactoringConditionTestCase { private FilePropertyData testData ; private RenameModuleConfig renameModuleConfig ; public RenameModuleConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; renameModuleConfig = new RenameModuleConfig ( testData , testData . getIntProperty ( "" ) ) ; RenameModuleConditionChecker checker = new RenameModuleConditionChecker ( renameModuleConfig ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new RenameModuleEditProvider ( renameModuleConfig ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemodule . conditionchecker ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_RenameModuleChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , RenameModuleConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemodule ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . renamemodule . conditionchecker . TS_RenameModuleChecks ; public class TS_RenameModule extends FileTestSuite { public static TestSuite suite ( ) { TestSuite suite = createSuite ( "" , "" , ModuleRenameTester . class ) ; suite . addTestSuite ( TC_ModuleInclusionFinder . class ) ; suite . addTest ( TS_RenameModuleChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . renamemodule ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleConfig ; import org . rubypeople . rdt . refactoring . core . renamemodule . RenameModuleEditProvider ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; public class ModuleRenameTester extends FileTestCase { public ModuleRenameTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) ) ; int caretPosition = testData . getIntProperty ( "" ) ; RenameModuleConfig renameModuleConfig = new RenameModuleConfig ( testData , caretPosition ) ; new RenameModuleConditionChecker ( renameModuleConfig ) ; renameModuleConfig . setNewName ( testData . getProperty ( "" ) ) ; RenameModuleEditProvider editProvider = new RenameModuleEditProvider ( renameModuleConfig ) ; checkMultiFileEdits ( editProvider , testData ) ; } } package org . rubypeople . rdt . refactoring . tests . core . extractconstant ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . extractconstant . ConstantExtractor ; import org . rubypeople . rdt . refactoring . core . extractconstant . ExtractConstantConditionChecker ; import org . rubypeople . rdt . refactoring . core . extractconstant . ExtractConstantConfig ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class ExtractConstantTester extends FileTestCase { public ExtractConstantTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData testData = new FileTestData ( getName ( ) , "" , "" ) ; IRefactoringContext selection = new RefactoringContext ( testData . getIntProperty ( "" ) , testData . getIntProperty ( "" ) , "" ) ; ExtractConstantConfig renameModuleConfig = new ExtractConstantConfig ( testData , selection ) ; new ExtractConstantConditionChecker ( renameModuleConfig ) ; renameModuleConfig . setConstantName ( testData . getProperty ( "" ) ) ; ConstantExtractor editProvider = new ConstantExtractor ( renameModuleConfig ) ; createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , editProvider ) ; } } package org . rubypeople . rdt . refactoring . tests . core . extractconstant . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . extractconstant . ConstantExtractor ; import org . rubypeople . rdt . refactoring . core . extractconstant . ExtractConstantConditionChecker ; import org . rubypeople . rdt . refactoring . core . extractconstant . ExtractConstantConfig ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class ExtractConstantConditionTester extends RefactoringConditionTestCase { private FilePropertyData testData ; private ExtractConstantConfig config ; public ExtractConstantConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; IRefactoringContext selection = new RefactoringContext ( testData . getIntProperty ( "" ) , testData . getIntProperty ( "" ) , "" ) ; config = new ExtractConstantConfig ( testData , selection ) ; ExtractConstantConditionChecker checker = new ExtractConstantConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new ConstantExtractor ( config ) ; config . setConstantName ( testData . getProperty ( "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . extractconstant . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_ExtractConstantChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , ExtractConstantConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . extractconstant ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . extractconstant . conditionchecks . TS_ExtractConstantChecks ; public class TS_ExtractConstant extends FileTestSuite { public static TestSuite suite ( ) { TestSuite suite = createSuite ( "" , "" , ExtractConstantTester . class ) ; suite . addTest ( TS_ExtractConstantChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . regex . Pattern ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class MultipleDocumentsInOneProvider extends DocumentProvider { private StringBuffer activeSection ; private HashMap < String , StringBuffer > sections ; private String fileName ; private String partName ; public MultipleDocumentsInOneProvider ( String baseFile , Class < ? > resource ) { this . fileName = baseFile ; FileTestData doc = null ; try { doc = new FileTestData ( baseFile , "" , "" ) ; } catch ( FileNotFoundException e ) { assert false : "" + e ; return ; } catch ( IOException e ) { assert false : "" + e ; return ; } String [ ] strings = doc . getActiveFileContent ( ) . split ( "" ) ; sections = new HashMap < String , StringBuffer > ( ) ; StringBuffer active = new StringBuffer ( ) ; for ( String string : strings ) { if ( Pattern . compile ( "" ) . matcher ( string ) . matches ( ) ) { active = new StringBuffer ( ) ; sections . put ( string . replaceFirst ( "" , "" ) , active ) ; } else { if ( active . length ( ) > ) active . append ( "" ) ; active . append ( string ) ; } } } public DocumentProvider setActive ( String part ) { this . partName = part ; activeSection = sections . get ( part ) ; return this ; } public String getActiveFileContent ( ) { return activeSection . toString ( ) ; } public String getActiveFileName ( ) { return fileName + "" + partName ; } public String getFileContent ( String currentFileName ) { return getActiveFileContent ( ) ; } public Collection < String > getFileNames ( ) { return new ArrayList < String > ( ) ; } } package org . rubypeople . rdt . refactoring . tests . core . movefield ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldConfig ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldEditProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class MoveFieldTester extends RefactoringTestCase { public MoveFieldTester ( String testName ) { super ( testName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) + "" , "" , "" , getName ( ) + "" ) ; MoveFieldConfig config = new MoveFieldConfig ( new DocumentWithIncluding ( testData ) , testData . getIntProperty ( "" ) ) ; new MoveFieldConditionChecker ( config ) ; config . setTargetClass ( testData . getProperty ( "" ) ) ; config . setTargetReference ( testData . getProperty ( "" ) ) ; MoveFieldEditProvider editProvider = new MoveFieldEditProvider ( config ) ; checkMultiFileEdits ( editProvider , testData ) ; } } package org . rubypeople . rdt . refactoring . tests . core . movefield . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_MoveFieldChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , MoveFieldConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . movefield . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldConfig ; import org . rubypeople . rdt . refactoring . core . movefield . MoveFieldEditProvider ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class MoveFieldConditionTester extends RefactoringConditionTestCase { private MoveFieldConfig config ; private FilePropertyData testData ; public MoveFieldConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; int caretPosition = testData . getIntProperty ( "" ) ; config = new MoveFieldConfig ( new DocumentWithIncluding ( testData ) , caretPosition ) ; MoveFieldConditionChecker checker = new MoveFieldConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new MoveFieldEditProvider ( config ) ; } } package org . rubypeople . rdt . refactoring . tests . core . movefield ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . movefield . conditionchecks . TS_MoveFieldChecks ; public class TS_MoveField extends FileTestSuite { public static TestSuite suite ( ) { TestSuite suite = createSuite ( "" , "" , MoveFieldTester . class ) ; suite . addTest ( TS_MoveFieldChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . generateconstructor ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . Collection ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . text . edits . MalformedTreeException ; import org . rubypeople . rdt . refactoring . core . generateconstructor . ConstructorsGenerator ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . TwoLayerTreeEditProviderTester ; public class ConstructorGeneratorTester extends TwoLayerTreeEditProviderTester { public ConstructorGeneratorTester ( String fileName ) { super ( fileName , true ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , MalformedTreeException , BadLocationException { FileTestData testData = new FileTestData ( getName ( ) ) ; ConstructorsGenerator generator = new ConstructorsGenerator ( testData ) ; Collection < String > strSelections = testData . getNumberedProperty ( "" ) ; for ( String aktSelection : strSelections ) { String [ ] selection = FilePropertyData . seperateString ( aktSelection ) ; if ( selection . length == ) { addSelection ( selection [ ] , selection [ ] ) ; } else if ( selection . length == ) { addSelection ( selection [ ] ) ; } else { fail ( ) ; } } createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , generator ) ; } } package org . rubypeople . rdt . refactoring . tests . core . generateconstructor ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_GenerateConstructor extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , ConstructorGeneratorTester . class ) ; suite . addTestSuite ( TC_ConstructorGeneratorTreeTest . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . generateconstructor ; import org . rubypeople . rdt . refactoring . core . generateconstructor . ConstructorsGenerator ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . TreeProviderTester ; public class TC_ConstructorGeneratorTreeTest extends TreeProviderTester { private final static String TEST_DOCUMENT_SIMPLE = "" + "" + "" + "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_NO_ATTRS = "" + "" + "" + "" ; private final static String TEST_DOCUMENT_ALL_ATTR_DEFINITION = "" + "" + "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_SCLASS_NODE = "" + "" + "" + "" + "" + "" + "" + "" ; public void testSimpleDocument ( ) { addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; validate ( new ConstructorsGenerator ( new StringDocumentProvider ( "" , TEST_DOCUMENT_SIMPLE ) ) ) ; } public void testDocumentNoAttrs ( ) { addContent ( new String [ ] { "" } ) ; validate ( new ConstructorsGenerator ( new StringDocumentProvider ( "" , TEST_DOCUMENT_NO_ATTRS ) ) ) ; } public void testAllAttrTypes ( ) { addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; validate ( new ConstructorsGenerator ( new StringDocumentProvider ( "" , TEST_DOCUMENT_ALL_ATTR_DEFINITION ) ) ) ; } public void testSClassNode ( ) { addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; validate ( new ConstructorsGenerator ( new StringDocumentProvider ( "" , TEST_DOCUMENT_SCLASS_NODE ) ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core ; import java . util . ArrayList ; import java . util . Iterator ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . core . IRefactoringContext ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . RefactoringContext ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class TC_SelectionNodeProvider extends FileTestCase { public TC_SelectionNodeProvider ( String fileName ) { super ( fileName ) ; } private String [ ] getEnclosingNodeClasses ( FileTestData data , IRefactoringContext selection ) { Node selected = SelectionNodeProvider . getSelectedNodes ( data . getActiveFileRootNode ( ) , selection ) ; ArrayList < String > classes = new ArrayList < String > ( ) ; Iterator < Node > it = NodeProvider . getAllNodes ( selected ) . iterator ( ) ; while ( it . hasNext ( ) ) { classes . add ( it . next ( ) . getClass ( ) . getSimpleName ( ) ) ; } return classes . toArray ( new String [ ] { } ) ; } private void assertLists ( String [ ] found , String [ ] expected ) { StringBuilder expectedStr = new StringBuilder ( ) , foundStr = new StringBuilder ( ) ; for ( String s : expected ) { expectedStr . append ( s + '' ) ; } for ( String s : found ) { foundStr . append ( s + '' ) ; } assertEquals ( expectedStr . toString ( ) , foundStr . toString ( ) ) ; } @ Override protected void runTest ( ) throws Throwable { FileTestData data = new FileTestData ( getName ( ) , "" , "" ) ; IRefactoringContext selection = new RefactoringContext ( data . getIntProperty ( "" ) , data . getIntProperty ( "" ) , "" ) ; assertLists ( getEnclosingNodeClasses ( data , selection ) , data . getCommaSeparatedStringArray ( "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . convertlocaltofield ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . convertlocaltofield . conditionchecks . TS_LocalToFieldChecks ; public class TS_LocalToField extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , LocalToFieldTester . class ) ; suite . addTest ( TS_LocalToFieldChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . convertlocaltofield . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . LocalToFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . LocalToFieldConfig ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . LocalToFieldConverter ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class LocalToFieldConditionTester extends RefactoringConditionTestCase { private FilePropertyData testData ; private LocalToFieldConfig config ; public LocalToFieldConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; config = new LocalToFieldConfig ( testData , testData . getIntProperty ( "" ) ) ; LocalToFieldConditionChecker checker = new LocalToFieldConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { LocalToFieldConverter converter = new LocalToFieldConverter ( config ) ; converter . setIsClassField ( testData . getBoolProperty ( "" ) ) ; converter . setNewName ( testData . getProperty ( "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . convertlocaltofield . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_LocalToFieldChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , LocalToFieldConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . convertlocaltofield ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . LocalToFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . LocalToFieldConfig ; import org . rubypeople . rdt . refactoring . core . convertlocaltofield . LocalToFieldConverter ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class LocalToFieldTester extends RefactoringTestCase { public LocalToFieldTester ( String fileName ) { super ( fileName ) ; } protected int getInitPlace ( String initPlace ) { if ( initPlace . equalsIgnoreCase ( "" ) ) { return LocalToFieldConverter . INIT_IN_METHOD ; } else if ( initPlace . equalsIgnoreCase ( "" ) ) { return LocalToFieldConverter . INIT_IN_CONSTRUCTOR ; } else { fail ( ) ; return ; } } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData data = new FileTestData ( getName ( ) ) ; LocalToFieldConfig config = new LocalToFieldConfig ( data , data . getIntProperty ( "" ) ) ; LocalToFieldConditionChecker checker = new LocalToFieldConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } LocalToFieldConverter converter = new LocalToFieldConverter ( config ) ; converter . setInitPlace ( getInitPlace ( data . getProperty ( "" ) ) ) ; converter . setIsClassField ( data . getBoolProperty ( "" ) ) ; converter . setNewName ( data . getProperty ( "" ) ) ; createEditAndCompareResult ( data . getSource ( ) , data . getExpectedResult ( ) , converter ) ; } } package org . rubypeople . rdt . refactoring . tests . core . overridemethod ; import org . rubypeople . rdt . refactoring . core . overridemethod . MethodsOverrider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . TwoLayerTreeEditProviderTester ; public class TC_OverridenMethodEditTest extends TwoLayerTreeEditProviderTester { private static int test_count = ; public TC_OverridenMethodEditTest ( ) { super ( "" , true ) ; } private final static String BASE_DOCUMENT_SIMPLE = "" + "" ; private final static String BASE_DOCUMENT_MESSY = "" + "" + "" + "" + "" + "" + "" + "" + "" ; private final static String SUPER_CLASS_EMPTY = "" + "" ; private final static String SUPER_CLASS_NO_CONSTRUCTOR_ARGS = "" + "" + "" + "" + "" ; private final static String SUPER_CLASS_ONE_CONSTRUCTOR_ARGS = "" + "" + "" + "" + "" ; private final static String SUPER_CLASS_TWO_CONSTRUCTOR_ARGS = "" + "" + "" + "" + "" ; private final static String SUPER_CLASS_ONE_METHOD = "" + "" + "" + "" + "" ; private final static String SUPER_CLASS_TWO_METHODS = "" + "" + "" + "" + "" + "" + "" + "" + "" ; private final static String SUPER_CLASS_TWO_METHODS_AND_CONSTRUCTOR = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; public void testSuperClassWithNoConstructors ( ) { check ( BASE_DOCUMENT_SIMPLE , SUPER_CLASS_EMPTY , "" ) ; } public void testSuperClassWithSimpleConstructor ( ) { addSelection ( "" ) ; check ( BASE_DOCUMENT_SIMPLE , SUPER_CLASS_NO_CONSTRUCTOR_ARGS , "" ) ; } public void testSuperClassWithOneConstructorArgs ( ) { addSelection ( "" ) ; check ( BASE_DOCUMENT_SIMPLE , SUPER_CLASS_ONE_CONSTRUCTOR_ARGS , "" ) ; } public void testSuperClassWithTwoConstructorArgs ( ) { addSelection ( "" ) ; check ( BASE_DOCUMENT_SIMPLE , SUPER_CLASS_TWO_CONSTRUCTOR_ARGS , "" ) ; } public void testSuperClassWithOneMethod ( ) { addSelection ( "" ) ; check ( BASE_DOCUMENT_SIMPLE , SUPER_CLASS_ONE_METHOD , "" ) ; } public void testSuperClassWithTwoMethods ( ) { addSelection ( "" ) ; check ( BASE_DOCUMENT_SIMPLE , SUPER_CLASS_TWO_METHODS , "" ) ; } public void testSuperClassWithTwoMethodsOneSelected ( ) { addSelection ( "" , "" ) ; check ( BASE_DOCUMENT_SIMPLE , SUPER_CLASS_TWO_METHODS , "" ) ; } public void testSuperClassWithTwoMethodsAndConstructor ( ) { addSelection ( "" ) ; check ( BASE_DOCUMENT_SIMPLE , SUPER_CLASS_TWO_METHODS_AND_CONSTRUCTOR , "" + "" + "" + "" + "" ) ; } public void testSuperClassWithTwoMethodsAndConstructorMessyBase ( ) { addSelection ( "" ) ; check ( BASE_DOCUMENT_MESSY , SUPER_CLASS_TWO_METHODS_AND_CONSTRUCTOR , "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; } private void check ( String classDocument , String superClassDocument , String expectedDocument ) { StringDocumentProvider docProvider = new StringDocumentProvider ( "" + ++ test_count , classDocument ) ; if ( superClassDocument != null ) { docProvider . addFile ( "" , superClassDocument ) ; } check ( new MethodsOverrider ( docProvider ) , classDocument , expectedDocument ) ; } } package org . rubypeople . rdt . refactoring . tests . core . overridemethod ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_OverrideMethod extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , OverrideMethodTester . class ) ; suite . addTestSuite ( TC_MethodOverriderTreeTest . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . overridemethod ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . Collection ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . text . edits . MalformedTreeException ; import org . rubypeople . rdt . refactoring . core . overridemethod . MethodsOverrider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . TwoLayerTreeEditProviderTester ; public class OverrideMethodTester extends TwoLayerTreeEditProviderTester { public OverrideMethodTester ( String fileName ) { super ( fileName , true ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , MalformedTreeException , BadLocationException { FileTestData testData ; testData = new FileTestData ( getName ( ) ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( testData . getFileName ( ) , testData . getActiveFileContent ( ) ) ; String superClassFileName = testData . getProperty ( "" ) ; docProvider . addFile ( superClassFileName , testData . getFileContent ( superClassFileName ) ) ; MethodsOverrider overrider = new MethodsOverrider ( docProvider ) ; Collection < String > strSelections = testData . getNumberedProperty ( "" ) ; for ( String aktSelection : strSelections ) { String [ ] selection = FilePropertyData . seperateString ( aktSelection ) ; if ( selection . length == ) { addSelection ( selection [ ] , selection [ ] ) ; } else if ( selection . length == ) { addSelection ( selection [ ] ) ; } else { fail ( ) ; } } createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , overrider ) ; } } package org . rubypeople . rdt . refactoring . tests . core . overridemethod ; import org . rubypeople . rdt . refactoring . core . overridemethod . MethodsOverrider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . TreeProviderTester ; public class TC_MethodOverriderTreeTest extends TreeProviderTester { private static final String superFileName = "" ; private final static String A_EXTENDS_X_DOCUMENT = "" + superFileName + "" + "" + "" ; private final static String TWO_CLASSES = "" + superFileName + "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_SIMPLE = "" + "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_NO_CONSTRUCTOR_ARGS = "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_ONE_CONSTRUCTOR_ARG = "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_TREE_ONSTRUCTOR_ARGS = "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_TWO_CLASSES = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String TEST_DOCUMENT_METHOD_AND_CONSTRUCTOR = "" + "" + "" + "" + "" + "" + "" + "" + "" ; private static final String TEST_DOCUMENT_TWO_METHOD_AND_TWO_CONSTRUCTOR = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; public void testDocumentOneMethod ( ) { addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , A_EXTENDS_X_DOCUMENT ) ; docProvider . addFile ( superFileName , TEST_DOCUMENT_SIMPLE ) ; validate ( new MethodsOverrider ( docProvider ) ) ; } public void testDocumentNoConstructorArgs ( ) { addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , A_EXTENDS_X_DOCUMENT ) ; docProvider . addFile ( superFileName , TEST_DOCUMENT_NO_CONSTRUCTOR_ARGS ) ; validate ( new MethodsOverrider ( docProvider ) ) ; } public void testDocumentOneConstructorArg ( ) { addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , A_EXTENDS_X_DOCUMENT ) ; docProvider . addFile ( superFileName , TEST_DOCUMENT_ONE_CONSTRUCTOR_ARG ) ; validate ( new MethodsOverrider ( docProvider ) ) ; } public void testDocumentTreeConstructorArgs ( ) { addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , A_EXTENDS_X_DOCUMENT ) ; docProvider . addFile ( superFileName , TEST_DOCUMENT_TREE_ONSTRUCTOR_ARGS ) ; validate ( new MethodsOverrider ( docProvider ) ) ; } public void testDocumentTwoClasses ( ) { addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , TWO_CLASSES ) ; docProvider . addFile ( superFileName , TEST_DOCUMENT_TWO_CLASSES ) ; validate ( new MethodsOverrider ( docProvider ) ) ; } public void testDocumentMethodAndConstructor ( ) { addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , A_EXTENDS_X_DOCUMENT ) ; docProvider . addFile ( superFileName , TEST_DOCUMENT_METHOD_AND_CONSTRUCTOR ) ; validate ( new MethodsOverrider ( docProvider ) ) ; } public void testDocumentMethodsAndTwoConstructors ( ) { addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , A_EXTENDS_X_DOCUMENT ) ; docProvider . addFile ( superFileName , TEST_DOCUMENT_TWO_METHOD_AND_TWO_CONSTRUCTOR ) ; validate ( new MethodsOverrider ( docProvider ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . pushdown ; import org . rubypeople . rdt . refactoring . core . pushdown . MethodDownPusher ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . TreeProviderTester ; public class TC_MethodDownPusherTreeTest extends TreeProviderTester { private final static String ONE_DOCUMENT_PUSHDOWN = "" + "" + "" + "" + "" + "" + "" ; private final static String ONE_DOCUMENT_PUSHDOWN_MULTIPLE = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private final static String DOCUMENT_A_EXTENDS_X = "" + "" + "" ; private final static String DOCUMENT_B_EXTENDS_X = "" + "" + "" ; private final static String DOCUMENT_X = "" + "" + "" + "" + "" ; public void testSimpleOneDocumentPushDown ( ) { addContent ( new String [ ] { "" , "" } ) ; DocumentProvider docProvider = new StringDocumentProvider ( "" , ONE_DOCUMENT_PUSHDOWN ) ; validate ( new MethodDownPusher ( docProvider ) ) ; } public void testOneDocumentPushDown ( ) { addContent ( new String [ ] { "" , "" } ) ; addContent ( new String [ ] { "" , "" } ) ; DocumentProvider docProvider = new StringDocumentProvider ( "" , ONE_DOCUMENT_PUSHDOWN_MULTIPLE ) ; validate ( new MethodDownPusher ( docProvider ) ) ; } public void testTwoDocumentPushDown ( ) { addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , DOCUMENT_X ) ; docProvider . addFile ( "" , DOCUMENT_A_EXTENDS_X ) ; validate ( new MethodDownPusher ( docProvider ) ) ; } public void testTreeDocumentPushDown ( ) { addContent ( new String [ ] { "" , "" } ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( "" , DOCUMENT_X ) ; docProvider . addFile ( "" , DOCUMENT_A_EXTENDS_X ) ; docProvider . addFile ( "" , DOCUMENT_B_EXTENDS_X ) ; validate ( new MethodDownPusher ( docProvider ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . pushdown ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . Collection ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . text . edits . MalformedTreeException ; import org . rubypeople . rdt . refactoring . core . pushdown . MethodDownPusher ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . TwoLayerTreeEditProviderTester ; public class PushDownTester extends TwoLayerTreeEditProviderTester { public PushDownTester ( String fileName ) { super ( fileName , true ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , MalformedTreeException , BadLocationException { FileTestData testData ; testData = new FileTestData ( getName ( ) ) ; StringDocumentProvider docProvider = new StringDocumentProvider ( testData . getFileName ( ) , testData . getActiveFileContent ( ) ) ; Collection < String > projectFileNames = testData . getNumberedProperty ( "" ) ; for ( String projectFileName : projectFileNames ) { docProvider . addFile ( projectFileName , testData . getFileContent ( projectFileName ) ) ; } MethodDownPusher downPusher = new MethodDownPusher ( docProvider ) ; Collection < String > strSelections = testData . getNumberedProperty ( "" ) ; for ( String aktSelection : strSelections ) { String [ ] selection = FilePropertyData . seperateString ( aktSelection ) ; if ( selection . length == ) { addSelection ( selection [ ] , selection [ ] ) ; } else if ( selection . length == ) { addSelection ( selection [ ] ) ; } else { fail ( ) ; } } createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , downPusher ) ; } } package org . rubypeople . rdt . refactoring . tests . core . pushdown ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_PushDown extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , PushDownTester . class ) ; suite . addTestSuite ( TC_MethodDownPusherTreeTest . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . nodewrapper ; import junit . framework . TestCase ; import org . jruby . ast . ClassVarNode ; import org . jruby . ast . InstVarNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . rubypeople . rdt . refactoring . nodewrapper . FieldNodeWrapper ; public class TC_FieldNodeWrapper extends TestCase { public void testGetNameWithoutAtsInst ( ) { assertEquals ( "" , new FieldNodeWrapper ( new InstVarNode ( new IDESourcePosition ( ) , "" ) ) . getNameWithoutAts ( ) ) ; assertEquals ( "" , new FieldNodeWrapper ( new InstVarNode ( new IDESourcePosition ( ) , "" ) ) . getNameWithoutAts ( ) ) ; assertEquals ( "" , new FieldNodeWrapper ( new InstVarNode ( new IDESourcePosition ( ) , "" ) ) . getNameWithoutAts ( ) ) ; assertEquals ( "" , new FieldNodeWrapper ( new InstVarNode ( new IDESourcePosition ( ) , "" ) ) . getNameWithoutAts ( ) ) ; } public void testGetNameWithoutAtsClass ( ) { assertEquals ( "" , new FieldNodeWrapper ( new ClassVarNode ( new IDESourcePosition ( ) , "" ) ) . getNameWithoutAts ( ) ) ; assertEquals ( "" , new FieldNodeWrapper ( new ClassVarNode ( new IDESourcePosition ( ) , "" ) ) . getNameWithoutAts ( ) ) ; assertEquals ( "" , new FieldNodeWrapper ( new ClassVarNode ( new IDESourcePosition ( ) , "" ) ) . getNameWithoutAts ( ) ) ; assertEquals ( "" , new FieldNodeWrapper ( new ClassVarNode ( new IDESourcePosition ( ) , "" ) ) . getNameWithoutAts ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . nodewrapper ; import junit . framework . TestCase ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . RootNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . lexer . yacc . ISourcePosition ; import org . jruby . parser . LocalStaticScope ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . RealClassNodeWrapper ; public class TC_MethodNodeWrapper extends TestCase { private static final ISourcePosition EMPTY_POSITION = new IDESourcePosition ( ) ; ClassNodeWrapper klass ; public void setUp ( ) { RootNode rootNode = new StringDocumentProvider ( "" , "" ) . getRootNode ( "" ) ; klass = new ClassNodeWrapper ( new RealClassNodeWrapper ( ( ( NewlineNode ) rootNode . getBodyNode ( ) ) . getNextNode ( ) ) ) ; } private MethodNodeWrapper createReaderMethod ( String name ) { MethodNodeWrapper wrapper = new MethodNodeWrapper ( new DefnNode ( EMPTY_POSITION , new ArgumentNode ( EMPTY_POSITION , name ) , new ArgsNode ( EMPTY_POSITION , null , null , null , null , null ) , new LocalStaticScope ( null ) , null ) , klass ) ; return wrapper ; } private MethodNodeWrapper createWriterMethod ( String name ) { MethodNodeWrapper wrapper = new MethodNodeWrapper ( new DefnNode ( EMPTY_POSITION , new ArgumentNode ( EMPTY_POSITION , name ) , new ArgsNode ( EMPTY_POSITION , new ArrayNode ( EMPTY_POSITION , new ArgumentNode ( EMPTY_POSITION , "" ) ) , null , null , null , null ) , new LocalStaticScope ( null ) , null ) , klass ) ; return wrapper ; } private MethodNodeWrapper createInvalidWriterMethod ( String name ) { MethodNodeWrapper wrapper = new MethodNodeWrapper ( new DefnNode ( EMPTY_POSITION , new ArgumentNode ( EMPTY_POSITION , name ) , new ArgsNode ( EMPTY_POSITION , new ArrayNode ( EMPTY_POSITION , new ArgumentNode ( EMPTY_POSITION , "" ) ) . add ( new ArgumentNode ( EMPTY_POSITION , "" ) ) , null , null , null , null ) , new LocalStaticScope ( null ) , null ) , klass ) ; return wrapper ; } public void testIsNotAccessor ( ) { MethodNodeWrapper wrapper = createReaderMethod ( "" ) ; assertFalse ( wrapper . isAccessor ( ) ) ; wrapper = createReaderMethod ( "" ) ; assertFalse ( wrapper . isAccessor ( ) ) ; } public void testIsAccessor ( ) { MethodNodeWrapper wrapper = createReaderMethod ( "" ) ; assertTrue ( wrapper . isAccessor ( ) ) ; wrapper = createReaderMethod ( "" ) ; assertTrue ( wrapper . isAccessor ( ) ) ; wrapper = createReaderMethod ( "" ) ; assertTrue ( wrapper . isAccessor ( ) ) ; } public void testIsWriter ( ) { MethodNodeWrapper wrapper = createWriterMethod ( "" ) ; assertTrue ( wrapper . isAccessor ( ) ) ; wrapper = createWriterMethod ( "" ) ; assertTrue ( wrapper . isAccessor ( ) ) ; wrapper = createWriterMethod ( "" ) ; assertTrue ( wrapper . isAccessor ( ) ) ; } public void testIsNotWriter ( ) { MethodNodeWrapper wrapper = createWriterMethod ( "" ) ; assertFalse ( wrapper . isAccessor ( ) ) ; wrapper = createWriterMethod ( "" ) ; assertFalse ( wrapper . isAccessor ( ) ) ; wrapper = createWriterMethod ( "" ) ; assertFalse ( wrapper . isAccessor ( ) ) ; wrapper = createInvalidWriterMethod ( "" ) ; assertFalse ( wrapper . isAccessor ( ) ) ; } public void testWithoutClass ( ) { MethodNodeWrapper nodeWrapper = new MethodNodeWrapper ( null , null ) ; assertFalse ( nodeWrapper . isAccessor ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . nodewrapper ; import junit . framework . TestSuite ; public class TS_NodeWrapper { public static TestSuite suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_FieldNodeWrapper . class ) ; suite . addTestSuite ( TC_MethodNodeWrapper . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . encapsulatefield ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . encapsulatefield . conditionchecks . TS_EncapsulateFieldChecks ; public class TS_EncapsulateField extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , EncapsulateFieldTester . class ) ; suite . addTest ( TS_EncapsulateFieldChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . encapsulatefield ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . EncapsulateFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . EncapsulateFieldConfig ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . FieldEncapsulator ; import org . rubypeople . rdt . refactoring . nodewrapper . VisibilityNodeWrapper . METHOD_VISIBILITY ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class EncapsulateFieldTester extends RefactoringTestCase { public EncapsulateFieldTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData testData = new FileTestData ( getName ( ) ) ; EncapsulateFieldConfig config = new EncapsulateFieldConfig ( testData , testData . getIntProperty ( "" ) ) ; EncapsulateFieldConditionChecker checker = new EncapsulateFieldConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } FieldEncapsulator encapsulator = new FieldEncapsulator ( config ) ; if ( testData . hasProperty ( "" ) && encapsulator . isReaderGenerationOptional ( ) ) { encapsulator . setReaderDisabled ( ! testData . getBoolProperty ( "" ) ) ; } if ( testData . hasProperty ( "" ) && encapsulator . isWriterGenerationOptional ( ) ) { encapsulator . setWriterDisabled ( ! testData . getBoolProperty ( "" ) ) ; } if ( testData . hasProperty ( "" ) && ! config . isReaderGenerationDisabled ( ) ) { encapsulator . setReaderVisibility ( getVisibility ( testData . getProperty ( "" ) ) ) ; } if ( testData . hasProperty ( "" ) && ! config . isWriterGenerationDisabled ( ) ) { encapsulator . setWriterVisibility ( getVisibility ( testData . getProperty ( "" ) ) ) ; } createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , encapsulator ) ; } private METHOD_VISIBILITY getVisibility ( String visibility ) { if ( visibility . equals ( "" ) ) { return METHOD_VISIBILITY . PUBLIC ; } if ( visibility . equals ( "" ) ) { return METHOD_VISIBILITY . PROTECTED ; } if ( visibility . equals ( "" ) ) { return METHOD_VISIBILITY . PRIVATE ; } fail ( ) ; return METHOD_VISIBILITY . NONE ; } } package org . rubypeople . rdt . refactoring . tests . core . encapsulatefield . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . EncapsulateFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . EncapsulateFieldConfig ; import org . rubypeople . rdt . refactoring . core . encapsulatefield . FieldEncapsulator ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class EncapsulateFieldConditionTester extends RefactoringConditionTestCase { private EncapsulateFieldConfig config ; public EncapsulateFieldConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { FilePropertyData testData = new FileTestData ( getName ( ) , "" , "" ) ; config = new EncapsulateFieldConfig ( testData , testData . getIntProperty ( "" ) ) ; EncapsulateFieldConditionChecker checker = new EncapsulateFieldConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new FieldEncapsulator ( config ) ; } } package org . rubypeople . rdt . refactoring . tests . core . encapsulatefield . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_EncapsulateFieldChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , EncapsulateFieldConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . nodewrapper . TS_NodeWrapper ; public class TS_Core extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , TC_SelectionNodeProvider . class ) ; suite . addTestSuite ( TC_NodeProvider . class ) ; suite . addTestSuite ( TC_ModuleNodeProvider . class ) ; suite . addTest ( TS_NodeWrapper . suite ( ) ) ; suite . addTestSuite ( TC_RefactoringConditionChecker . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core ; import junit . framework . TestCase ; import org . rubypeople . rdt . refactoring . core . IRefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . IRefactoringConfig ; import org . rubypeople . rdt . refactoring . core . RefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; public class TC_RefactoringConditionChecker extends TestCase { private final class TestConditionChecker extends RefactoringConditionChecker { private TestConditionChecker ( final IDocumentProvider provider ) { super ( getDefaultConfig ( provider ) ) ; } @ Override public void init ( IRefactoringConfig configObj ) { } @ Override protected void checkInitialConditions ( ) { } } public void testSyntaxErrors ( ) { RefactoringConditionChecker checker = new TestConditionChecker ( new StringDocumentProvider ( "" , "" ) ) ; assertEquals ( , checker . getInitialMessages ( ) . get ( IRefactoringConditionChecker . ERRORS ) . size ( ) ) ; assertEquals ( , checker . getInitialMessages ( ) . get ( IRefactoringConditionChecker . WARNING ) . size ( ) ) ; } public void testSyntaxErrorsInIncludes ( ) { StringDocumentProvider stringDocumentProvider = new StringDocumentProvider ( "" , "" ) ; stringDocumentProvider . addFile ( "" , "" ) ; RefactoringConditionChecker checker = new TestConditionChecker ( stringDocumentProvider ) ; assertEquals ( , checker . getInitialMessages ( ) . get ( IRefactoringConditionChecker . ERRORS ) . size ( ) ) ; assertEquals ( , checker . getInitialMessages ( ) . get ( IRefactoringConditionChecker . WARNING ) . size ( ) ) ; assertEquals ( , checker . getFinalMessages ( ) . get ( IRefactoringConditionChecker . ERRORS ) . size ( ) ) ; assertEquals ( , checker . getFinalMessages ( ) . get ( IRefactoringConditionChecker . WARNING ) . size ( ) ) ; } private static IRefactoringConfig getDefaultConfig ( final IDocumentProvider provider ) { return new IRefactoringConfig ( ) { public IDocumentProvider getDocumentProvider ( ) { return provider ; } public void setDocumentProvider ( IDocumentProvider doc ) { } } ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import org . rubypeople . rdt . refactoring . core . inlinemethod . RenameDuplicatedVariables ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . core . MultipleDocumentsInOneProvider ; public class TC_RenameDuplicatedVariables extends FinderTestsBase { public void testRenameVarious ( ) { rename ( , new String [ ] { "" , "" , "" , "" } ) ; } public void testRenameSame ( ) { rename ( , new String [ ] { "" } ) ; } public void testRenameMultiAsgn ( ) { rename ( , new String [ ] { "" , "" } ) ; } public void testRenameHigherNumbers ( ) { rename ( , new String [ ] { "" , "" } ) ; } private void rename ( int testno , String [ ] localNames ) { IDocumentProvider result = new RenameDuplicatedVariables ( ) . rename ( doc . setActive ( "" + String . valueOf ( testno ) ) , localNames ) ; assertEquals ( doc . setActive ( "" + String . valueOf ( testno ) ) . getActiveFileContent ( ) , result . getActiveFileContent ( ) ) ; } @ Override protected void setUp ( ) throws Exception { doc = new MultipleDocumentsInOneProvider ( "" , this . getClass ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . tests . core . MultipleDocumentsInOneProvider ; public class TC_SelectedCallFinder extends FinderTestsBase { public void testFindSelectedCall4 ( ) { MethodCallNodeWrapper node = findSelected ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNotNull ( node . getArgsNode ( ) ) ; assertNotNull ( node . getWrappedNode ( ) ) ; assertNull ( node . getReceiverNode ( ) ) ; } public void testFindSelectedCall3 ( ) { MethodCallNodeWrapper node = findSelected ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNull ( node . getArgsNode ( ) ) ; assertNotNull ( node . getWrappedNode ( ) ) ; assertNull ( node . getReceiverNode ( ) ) ; } public void testFindSelectedCall2 ( ) { MethodCallNodeWrapper node = findSelected ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNull ( node . getArgsNode ( ) ) ; assertNotNull ( node . getWrappedNode ( ) ) ; assertNotNull ( node . getReceiverNode ( ) ) ; } public void testFindSelectedCall1 ( ) { MethodCallNodeWrapper node = findSelected ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNotNull ( node . getArgsNode ( ) ) ; assertNotNull ( node . getWrappedNode ( ) ) ; assertNotNull ( node . getReceiverNode ( ) ) ; } @ Override protected void setUp ( ) throws Exception { doc = new MultipleDocumentsInOneProvider ( "" , this . getClass ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import org . jruby . ast . MethodDefNode ; import org . rubypeople . rdt . refactoring . core . inlinemethod . MethodFinder ; import org . rubypeople . rdt . refactoring . tests . core . MultipleDocumentsInOneProvider ; public class TC_MethodFinder extends FinderTestsBase { public void testFind ( ) { MethodDefNode node = findDefinition ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNotNull ( node . getNameNode ( ) ) ; assertNotNull ( node . getArgsNode ( ) ) ; assertNotNull ( node . getBodyNode ( ) ) ; } public void testFind2 ( ) { MethodDefNode node = findDefinition ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNotNull ( node . getNameNode ( ) ) ; assertNotNull ( node . getArgsNode ( ) ) ; assertNotNull ( node . getBodyNode ( ) ) ; } public void testFind3 ( ) { MethodDefNode node = findDefinition ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNotNull ( node . getNameNode ( ) ) ; assertNotNull ( node . getArgsNode ( ) ) ; assertNotNull ( node . getBodyNode ( ) ) ; } public void testFindInherited ( ) { MethodDefNode node = findDefinition ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNotNull ( node . getNameNode ( ) ) ; assertNotNull ( node . getArgsNode ( ) ) ; assertNull ( node . getBodyNode ( ) ) ; } public void testFindSimplyInherited ( ) { MethodDefNode node = findDefinition ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertNotNull ( node . getNameNode ( ) ) ; assertNotNull ( node . getArgsNode ( ) ) ; assertNull ( node . getBodyNode ( ) ) ; } public void testFindUnknownClass ( ) { doc . setActive ( "" ) ; assertNull ( new MethodFinder ( ) . find ( "" , "" , doc ) ) ; } public void testFindUnknownMethod ( ) { doc . setActive ( "" ) ; assertNull ( new MethodFinder ( ) . find ( "" , "" , doc ) ) ; } @ Override protected void setUp ( ) throws Exception { doc = new MultipleDocumentsInOneProvider ( "" , this . getClass ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . inlinemethod . InlineAndRemoveEditProvider ; import org . rubypeople . rdt . refactoring . core . inlinemethod . InlineMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . inlinemethod . InlineMethodConfig ; import org . rubypeople . rdt . refactoring . core . inlinemethod . TargetClassFinder ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class InlineMethodTester extends FileTestCase { public InlineMethodTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData testData = new FileTestData ( getName ( ) , "" , "" ) ; int caretPosition = testData . getIntProperty ( "" ) ; InlineMethodConfig inlineMethodConfig = new InlineMethodConfig ( testData , caretPosition , new TargetClassFinder ( ) ) ; InlineMethodConditionChecker checker = new InlineMethodConditionChecker ( inlineMethodConfig ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } InlineAndRemoveEditProvider editProvider = new InlineAndRemoveEditProvider ( inlineMethodConfig ) ; if ( testData . hasProperty ( "" ) ) { editProvider . setRemove ( testData . getBoolProperty ( "" ) ) ; } createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , editProvider ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . rubypeople . rdt . refactoring . core . inlinemethod . ReturnStatementReplacer ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . core . MultipleDocumentsInOneProvider ; public class TC_ReturnStatementReplacer extends FinderTestsBase { public void testMultipleReturns ( ) { doc . setActive ( "" ) ; assertFalse ( new ReturnStatementReplacer ( ) . singleReturnOnLastLine ( doc ) ) ; } public void testSingleReturn ( ) { doc . setActive ( "" ) ; assertTrue ( new ReturnStatementReplacer ( ) . singleReturnOnLastLine ( doc ) ) ; } public void testReturnNotAtTheEnd ( ) { doc . setActive ( "" ) ; assertFalse ( new ReturnStatementReplacer ( ) . singleReturnOnLastLine ( doc ) ) ; } public void testReturnLastLine ( ) { doc . setActive ( "" ) ; assertTrue ( new ReturnStatementReplacer ( ) . singleReturnOnLastLine ( doc ) ) ; } public void testExplicitReturn ( ) { doc . setActive ( "" ) ; IDocumentProvider resultDocument = new ReturnStatementReplacer ( ) . replaceReturn ( doc , new LocalAsgnNode ( new IDESourcePosition ( ) , "" , , null ) ) ; assertEquals ( "" , lastLine ( resultDocument ) ) ; } public void testImplicitReturn ( ) { doc . setActive ( "" ) ; IDocumentProvider resultDocument = new ReturnStatementReplacer ( ) . replaceReturn ( doc , new LocalAsgnNode ( new IDESourcePosition ( ) , "" , , null ) ) ; assertEquals ( "" , lastLine ( resultDocument ) ) ; } public void testFactorialReturn ( ) { doc . setActive ( "" ) ; IDocumentProvider resultDocument = new ReturnStatementReplacer ( ) . replaceReturn ( doc , new LocalAsgnNode ( new IDESourcePosition ( ) , "" , , null ) ) ; assertEquals ( "" , lastLine ( resultDocument ) ) ; } public void testReturnFixnum ( ) { doc . setActive ( "" ) ; IDocumentProvider resultDocument = new ReturnStatementReplacer ( ) . replaceReturn ( doc , new LocalAsgnNode ( new IDESourcePosition ( ) , "" , , null ) ) ; assertEquals ( "" , lastLine ( resultDocument ) ) ; } public void testErroneousDocument ( ) { doc . setActive ( "" ) ; IDocumentProvider resultDocument = new ReturnStatementReplacer ( ) . replaceReturn ( doc , new LocalAsgnNode ( new IDESourcePosition ( ) , "" , , null ) ) ; assertNull ( resultDocument ) ; } public void testNullAssignment ( ) { doc . setActive ( "" ) ; IDocumentProvider resultDocument = new ReturnStatementReplacer ( ) . replaceReturn ( doc , null ) ; assertNull ( resultDocument ) ; } private String lastLine ( IDocumentProvider document ) { String [ ] lines = document . getActiveFileContent ( ) . split ( "" ) ; return lines [ lines . length - ] ; } @ Override protected void setUp ( ) throws Exception { doc = new MultipleDocumentsInOneProvider ( "" , this . getClass ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod . conditions ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . inlinemethod . InlineMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . inlinemethod . InlineMethodConfig ; import org . rubypeople . rdt . refactoring . core . inlinemethod . TargetClassFinder ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class InlineMethodConditionTester extends RefactoringConditionTestCase { public InlineMethodConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { FilePropertyData testData = new FileTestData ( getName ( ) , "" , "" ) ; InlineMethodConfig methodContext = new InlineMethodConfig ( testData , testData . getIntProperty ( "" ) , new TargetClassFinder ( ) ) ; InlineMethodConditionChecker checker = new InlineMethodConditionChecker ( methodContext ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod . conditions ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_InlineMethodChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , InlineMethodConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . CallNode ; import org . jruby . ast . FixnumNode ; import org . jruby . ast . HashNode ; import org . jruby . ast . InstAsgnNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . StrNode ; import org . jruby . ast . ZArrayNode ; import org . rubypeople . rdt . refactoring . core . inlinemethod . TargetClassFinder ; import org . rubypeople . rdt . refactoring . tests . core . MultipleDocumentsInOneProvider ; public class TC_TargetClassFinder extends FinderTestsBase { public void testFindTargetClass ( ) { assertEquals ( "" , findTargetClass ( , "" ) ) ; } public void testFindTargetClass2 ( ) { assertEquals ( "" , findTargetClass ( , "" ) ) ; } public void testFindTargetClass3 ( ) { assertEquals ( "" , findTargetClass ( , "" ) ) ; } public void testFindTargetClass4 ( ) { assertEquals ( "" , findTargetClass ( , "" ) ) ; } public void testFindTargetClass5 ( ) { assertEquals ( "" , findTargetClass ( , "" ) ) ; } public void testFindTargetClass6 ( ) { assertEquals ( "" , findTargetClass ( , "" ) ) ; } public void testFindTargetClassInModule ( ) { assertEquals ( "" , findTargetClass ( , "" ) ) ; } public void testFindTargetClassInModules ( ) { assertEquals ( "" , findTargetClass ( , "" ) ) ; } public void testInstVarFromCall ( ) { InstAsgnNode node = findInstAsgnNode ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertEquals ( FixnumNode . class , node . getValueNode ( ) . getClass ( ) ) ; } public void testInstVarFromCall2 ( ) { InstAsgnNode node = findInstAsgnNode ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertEquals ( ArrayNode . class , node . getValueNode ( ) . getClass ( ) ) ; } public void testInstVarFromCall3 ( ) { InstAsgnNode node = findInstAsgnNode ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertEquals ( ArrayNode . class , node . getValueNode ( ) . getClass ( ) ) ; } public void testLocalAsgnFromLocalVar ( ) { LocalAsgnNode node = findLocalAsgnNode ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; } public void testLocalAsgnFromLocalVar2 ( ) { LocalAsgnNode node = findLocalAsgnNode ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertEquals ( HashNode . class , node . getValueNode ( ) . getClass ( ) ) ; node = findLocalAsgnNode ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertEquals ( StrNode . class , node . getValueNode ( ) . getClass ( ) ) ; } public void testLocalAsgnFromLocalVar3 ( ) { LocalAsgnNode node = findLocalAsgnNode ( , "" ) ; assertEquals ( "" , node . getName ( ) ) ; assertEquals ( ZArrayNode . class , node . getValueNode ( ) . getClass ( ) ) ; } private LocalAsgnNode findLocalAsgnNode ( int pos , String file ) { TargetClassFinder finder = new TargetClassFinder ( ) ; return finder . localAsgnFromLocalVar ( ( LocalVarNode ) ( ( CallNode ) findSelected ( pos , file ) . getWrappedNode ( ) ) . getReceiverNode ( ) , doc ) ; } private InstAsgnNode findInstAsgnNode ( int pos , String file ) { TargetClassFinder finder = new TargetClassFinder ( ) ; return finder . instVarFromCall ( ( InstVarNode ) ( ( CallNode ) findSelected ( pos , file ) . getWrappedNode ( ) ) . getReceiverNode ( ) , doc ) ; } private String findTargetClass ( int pos , String file ) { return new TargetClassFinder ( ) . findTargetClass ( findSelected ( pos , file ) , doc ) ; } @ Override protected void setUp ( ) throws Exception { doc = new MultipleDocumentsInOneProvider ( "" , this . getClass ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . inlinemethod . conditions . TS_InlineMethodChecks ; public class TS_InlineMethod extends FileTestSuite { public static TestSuite suite ( ) { TestSuite suite = createSuite ( "" , "" , InlineMethodTester . class ) ; suite . addTest ( createSuite ( "" , "" , TC_ParameterReplacer . class ) ) ; suite . addTestSuite ( TC_SelectedCallFinder . class ) ; suite . addTestSuite ( TC_TargetClassFinder . class ) ; suite . addTestSuite ( TC_MethodFinder . class ) ; suite . addTestSuite ( TC_ReturnStatementReplacer . class ) ; suite . addTest ( TS_InlineMethodChecks . suite ( ) ) ; suite . addTestSuite ( TC_MethodBodyStatementReplacer . class ) ; suite . addTestSuite ( TC_RenameDuplicatedVariables . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import java . util . ArrayList ; import org . rubypeople . rdt . refactoring . core . inlinemethod . MethodBodyStatementReplacer ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . core . MultipleDocumentsInOneProvider ; public class TC_MethodBodyStatementReplacer extends FinderTestsBase { public void testReplaceOneSelf ( ) { replace ( "" , "" , "" ) ; } public void testReplaceTwoSelfs ( ) { replace ( "" , "" , "" ) ; } public void testReplaceSelfInCall ( ) { replace ( "" , "" , "" ) ; } public void testReturnStatement ( ) { replaceReturn ( "" , "" ) ; } public void testReturnStatementFac ( ) { replaceReturn ( "" , "" ) ; } public void testReturnCallToMember ( ) { replaceCallToMember ( "" , "" , "" ) ; } private void replace ( String testName , String newName , String resultName ) { IDocumentProvider result = new MethodBodyStatementReplacer ( ) . replaceSelfWithObject ( doc . setActive ( testName ) , newName ) ; compareResults ( resultName , result ) ; } private void replaceReturn ( String testName , String resultName ) { IDocumentProvider result = new MethodBodyStatementReplacer ( ) . removeReturnStatements ( doc . setActive ( testName ) ) ; compareResults ( resultName , result ) ; } private void replaceCallToMember ( String testName , String resultName , String objName ) { IDocumentProvider result = new MethodBodyStatementReplacer ( ) . replaceVarsWithAccessor ( doc . setActive ( testName ) , objName , new ArrayList < String > ( ) ) ; compareResults ( resultName , result ) ; } private void compareResults ( String resultName , IDocumentProvider result ) { assertEquals ( doc . setActive ( resultName ) . getActiveFileContent ( ) , result . getActiveFileContent ( ) ) ; } @ Override protected void setUp ( ) throws Exception { doc = new MultipleDocumentsInOneProvider ( "" , this . getClass ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . jruby . ast . MethodDefNode ; import org . rubypeople . rdt . refactoring . core . inlinemethod . MethodFinder ; import org . rubypeople . rdt . refactoring . core . inlinemethod . ParameterReplacer ; import org . rubypeople . rdt . refactoring . core . inlinemethod . SelectedCallFinder ; import org . rubypeople . rdt . refactoring . core . inlinemethod . TargetClassFinder ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class TC_ParameterReplacer extends FinderTestsBase { public TC_ParameterReplacer ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { FileTestData testData = new FileTestData ( getName ( ) , "" , "" ) ; int caretPosition = testData . getIntProperty ( "" ) ; SelectedCallFinder finder = new SelectedCallFinder ( ) ; MethodCallNodeWrapper node = finder . findSelectedCall ( caretPosition , testData ) ; String className = new TargetClassFinder ( ) . findTargetClass ( node , testData ) ; MethodDefNode definitionNode = new MethodFinder ( ) . find ( className , node . getName ( ) , testData ) ; IDocumentProvider document = new ParameterReplacer ( ) . replace ( testData , node , definitionNode ) ; assertNotNull ( document ) ; assertEquals ( testData . getExpectedResult ( ) . trim ( ) , document . getActiveFileContent ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . inlinemethod ; import org . jruby . ast . MethodDefNode ; import org . rubypeople . rdt . refactoring . core . inlinemethod . MethodFinder ; import org . rubypeople . rdt . refactoring . core . inlinemethod . SelectedCallFinder ; import org . rubypeople . rdt . refactoring . core . inlinemethod . TargetClassFinder ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodCallNodeWrapper ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . core . MultipleDocumentsInOneProvider ; public abstract class FinderTestsBase extends FileTestCase { protected MultipleDocumentsInOneProvider doc ; public FinderTestsBase ( ) { super ( "" ) ; } public FinderTestsBase ( String fileName ) { super ( fileName ) ; } protected MethodCallNodeWrapper findSelected ( int pos , String file ) { SelectedCallFinder finder = new SelectedCallFinder ( ) ; doc . setActive ( file ) ; return finder . findSelectedCall ( pos , doc ) ; } protected MethodDefNode findDefinition ( int pos , String file ) { MethodCallNodeWrapper methodCallNode = findSelected ( pos , file ) ; return findDefinition ( methodCallNode ) ; } protected MethodDefNode findDefinition ( MethodCallNodeWrapper methodCallNode ) { String className = new TargetClassFinder ( ) . findTargetClass ( methodCallNode , doc ) ; return new MethodFinder ( ) . find ( className , methodCallNode . getName ( ) , doc ) ; } } package org . rubypeople . rdt . refactoring . tests . core . movemethod ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . movemethod . conditionchecks . TS_MoveMethodChecks ; public class TS_MoveMethod extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , MoveMethodTester . class ) ; suite . addTest ( TS_MoveMethodChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . movemethod ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . movemethod . MethodMover ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodConfig ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class MoveMethodTester extends RefactoringTestCase { public MoveMethodTester ( String testName ) { super ( testName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) ) ; MoveMethodConfig config = new MoveMethodConfig ( testData , testData . getIntProperty ( "" ) ) ; MoveMethodConditionChecker checker = new MoveMethodConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( "" ) ; } MethodMover mover = new MethodMover ( config ) ; if ( config . canCreateDelegateMethod ( ) ) { config . setLeaveDelegateMethodInSource ( testData . getBoolProperty ( "" ) ) ; } else { if ( testData . hasProperty ( "" ) ) { fail ( "" ) ; } } config . setDestinationClassNode ( testData . getProperty ( "" ) ) ; if ( config . needsSecondPage ( ) ) { if ( testData . hasProperty ( "" ) ) { config . setFieldInSourceClassOfTypeDestinationClass ( testData . getProperty ( "" ) ) ; } else { fail ( "" ) ; } } checkMultiFileEdits ( mover , testData ) ; } } package org . rubypeople . rdt . refactoring . tests . core . movemethod . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_MoveMethodChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , MoveMethodConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . movemethod . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . movemethod . MethodMover ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodConditionChecker ; import org . rubypeople . rdt . refactoring . core . movemethod . MoveMethodConfig ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class MoveMethodConditionTester extends RefactoringConditionTestCase { private MoveMethodConfig config ; private FilePropertyData testData ; public MoveMethodConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; int caretPosition = testData . getIntProperty ( "" ) ; config = new MoveMethodConfig ( testData , caretPosition ) ; MoveMethodConditionChecker checker = new MoveMethodConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new MethodMover ( config ) ; if ( config . canCreateDelegateMethod ( ) ) { config . setLeaveDelegateMethodInSource ( testData . getBoolProperty ( "" ) ) ; } else { if ( testData . hasProperty ( "" ) ) { fail ( "" ) ; } } config . setDestinationClassNode ( testData . getProperty ( "" ) ) ; if ( config . needsSecondPage ( ) ) { if ( testData . hasProperty ( "" ) ) { config . setFieldInSourceClassOfTypeDestinationClass ( testData . getProperty ( "" ) ) ; } else { fail ( "" ) ; } } } } package org . rubypeople . rdt . refactoring . tests . core . rename ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . rename . RenameConditionChecker ; import org . rubypeople . rdt . refactoring . core . rename . RenameConfig ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class RenameTester extends RefactoringTestCase { private static final String NONE = "" ; private static final String RENAME_CLASS = "" ; private static final String RENAME_MODULE = "" ; private static final String RENAME_METHOD = "" ; private static final String RENAME_FIELD = "" ; private static final String RENAME_LOCAL = "" ; public RenameTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { FileTestData testData = new FileTestData ( getName ( ) , "" , "" ) ; RenameConfig config = new RenameConfig ( testData , testData . getIntProperty ( "" ) ) ; RenameConditionChecker checker = new RenameConditionChecker ( config ) ; String delegateRenameRefactoring = testData . getProperty ( "" ) ; assertTrue ( isValidParam ( delegateRenameRefactoring ) ) ; check ( ! checker . shouldPerform ( ) , delegateRenameRefactoring . equals ( NONE ) ) ; check ( checker . shouldRenameClass ( ) , delegateRenameRefactoring . equals ( RENAME_CLASS ) ) ; check ( checker . shouldRenameModule ( ) , delegateRenameRefactoring . equals ( RENAME_MODULE ) ) ; check ( checker . shouldRenameMethod ( ) , delegateRenameRefactoring . equals ( RENAME_METHOD ) ) ; check ( checker . shouldRenameField ( ) , delegateRenameRefactoring . equals ( RENAME_FIELD ) ) ; check ( checker . shouldRenameLocal ( ) , delegateRenameRefactoring . equals ( RENAME_LOCAL ) ) ; } private void check ( boolean shouldPerform , boolean isRightRefactoring ) { if ( isRightRefactoring ) { assertTrue ( shouldPerform ) ; } } private boolean isValidParam ( String paramName ) { return paramName . equals ( NONE ) || paramName . equals ( RENAME_CLASS ) || paramName . equals ( RENAME_MODULE ) || paramName . equals ( RENAME_METHOD ) || paramName . equals ( RENAME_FIELD ) || paramName . equals ( RENAME_LOCAL ) ; } } package org . rubypeople . rdt . refactoring . tests . core . rename ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_Rename extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , RenameTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamefield . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . renamefield . FieldRenamer ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConfig ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class RenameFieldConditionTester extends RefactoringConditionTestCase { private FilePropertyData testData ; private RenameFieldConfig config ; public RenameFieldConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; config = new RenameFieldConfig ( testData , testData . getIntProperty ( "" ) ) ; RenameFieldConditionChecker checker = new RenameFieldConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new FieldRenamer ( config ) ; config . setNewName ( testData . getProperty ( "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamefield . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_RenameFieldChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , RenameFieldConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamefield ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . IRefactoringConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamefield . FieldRenamer ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamefield . RenameFieldConfig ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class FieldRenamerTester extends RefactoringTestCase { public FieldRenamerTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) ) ; int caretPosition = testData . getIntProperty ( "" ) ; RenameFieldConfig config = new RenameFieldConfig ( testData , caretPosition ) ; IRefactoringConditionChecker checker = new RenameFieldConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } FieldRenamer renamer = new FieldRenamer ( config ) ; config . setNewName ( testData . getProperty ( "" ) ) ; config . setDoRenameAccessorMethods ( testData . getBoolProperty ( "" ) ) ; checkMultiFileEdits ( renamer , testData ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamefield ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . renamefield . conditionchecks . TS_RenameFieldChecks ; public class TS_RenameField extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , FieldRenamerTester . class ) ; suite . addTest ( TS_RenameFieldChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . renamelocal . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_RenameLocalCondition extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , RenameLocalConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamelocal . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalConfig ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class RenameLocalConditionTester extends RefactoringConditionTestCase { public RenameLocalConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { FilePropertyData testData = new FileTestData ( getName ( ) , "" , "" ) ; RenameLocalConfig config = new RenameLocalConfig ( testData , testData . getIntProperty ( "" ) ) ; RenameLocalConditionChecker checker = new RenameLocalConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { } } package org . rubypeople . rdt . refactoring . tests . core . renamelocal ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalEditProvider ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalConditionChecker ; import org . rubypeople . rdt . refactoring . core . renamelocal . RenameLocalConfig ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class RenameLocalTester extends FileTestCase { public RenameLocalTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData testData = new FileTestData ( getName ( ) , "" , "" ) ; int caretPosition = testData . getIntProperty ( "" ) ; RenameLocalConfig config = new RenameLocalConfig ( testData , caretPosition ) ; RenameLocalConditionChecker checker = new RenameLocalConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } new RenameLocalEditProvider ( config ) ; config . getRenameEditProvider ( ) . setSelectedVariableName ( config . getSelectedNodeName ( ) ) ; config . getRenameEditProvider ( ) . setNewVariableName ( testData . getProperty ( "" ) ) ; createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , config . getRenameEditProvider ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renamelocal ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . renamelocal . conditionchecks . TS_RenameLocalCondition ; public class TS_RenameLocal extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , RenameLocalTester . class ) ; suite . addTest ( TS_RenameLocalCondition . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . splitlocal ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitLocalConditionChecker ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitLocalConfig ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitTempEditProvider ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class SplitLocalTester extends FileTestCase { public SplitLocalTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData testData = new FileTestData ( getName ( ) , "" , "" ) ; SplitLocalConfig config = new SplitLocalConfig ( testData , testData . getIntProperty ( "" ) ) ; SplitLocalConditionChecker checker = new SplitLocalConditionChecker ( config ) ; if ( ! checker . shouldPerform ( ) ) { fail ( ) ; } SplitTempEditProvider splitTempEditProvider = new SplitTempEditProvider ( config ) ; String [ ] names = testData . getCommaSeparatedStringArray ( "" ) ; assertEquals ( "" , splitTempEditProvider . getLocalUsages ( ) . size ( ) , names . length ) ; splitTempEditProvider . setNewNames ( names ) ; createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , splitTempEditProvider ) ; } } package org . rubypeople . rdt . refactoring . tests . core . splitlocal ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . Collection ; import junit . framework . TestCase ; import org . jruby . ast . DAsgnNode ; import org . jruby . ast . DVarNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . rubypeople . rdt . refactoring . core . renamelocal . SingleLocalVariableEdit ; import org . rubypeople . rdt . refactoring . core . splitlocal . LocalVarFinder ; import org . rubypeople . rdt . refactoring . core . splitlocal . LocalVarUsage ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplittedVariableRenamer ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class TC_SplittedVariableRenamer extends TestCase { private SingleLocalVariableEdit [ ] getEdits ( String name , int pos ) throws FileNotFoundException , IOException { LocalVarFinder finder = new LocalVarFinder ( ) ; Collection < LocalVarUsage > variables = finder . findLocalUsages ( new FileTestData ( name , "" , "" ) , pos ) ; SplittedVariableRenamer variableRenamer = new SplittedVariableRenamer ( finder . getScopeNode ( ) ) ; return variableRenamer . rename ( variables ) . toArray ( new SingleLocalVariableEdit [ ] ) ; } public void testRename_1 ( ) throws FileNotFoundException , IOException { SingleLocalVariableEdit [ ] edits = getEdits ( "" , ) ; assertEquals ( , edits . length ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; } public void testRename_2 ( ) throws FileNotFoundException , IOException { SingleLocalVariableEdit [ ] edits = getEdits ( "" , ) ; assertEquals ( , edits . length ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; } public void testRename_3 ( ) throws FileNotFoundException , IOException { SingleLocalVariableEdit [ ] edits = getEdits ( "" , ) ; assertEquals ( , edits . length ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; } public void testRename_4 ( ) throws FileNotFoundException , IOException { SingleLocalVariableEdit [ ] edits = getEdits ( "" , ) ; assertEquals ( , edits . length ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; } public void testRename_5 ( ) throws FileNotFoundException , IOException { SingleLocalVariableEdit [ ] edits = getEdits ( "" , ) ; assertEquals ( , edits . length ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; } public void testRename_6 ( ) throws FileNotFoundException , IOException { SingleLocalVariableEdit [ ] edits = getEdits ( "" , ) ; assertEquals ( , edits . length ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( LocalAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; } public void testRename_7 ( ) throws FileNotFoundException , IOException { SingleLocalVariableEdit [ ] edits = getEdits ( "" , ) ; assertEquals ( , edits . length ) ; assertEquals ( DAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( DVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( DAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( DAsgnNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; assertEquals ( DVarNode . class , edits [ ] . getNode ( ) . getClass ( ) ) ; assertEquals ( , edits [ ] . getOffsetLength ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . splitlocal ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . Collection ; import junit . framework . TestCase ; import org . rubypeople . rdt . refactoring . core . splitlocal . LocalVarFinder ; import org . rubypeople . rdt . refactoring . core . splitlocal . LocalVarUsage ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; public class TC_LocalVarFinder extends TestCase { private Collection < LocalVarUsage > find ( String name , int pos ) throws FileNotFoundException , IOException { LocalVarFinder finder = new LocalVarFinder ( ) ; Collection < LocalVarUsage > variables = finder . findLocalUsages ( new FileTestData ( name , "" , "" ) , pos ) ; return variables ; } public void testFindLocalUsages_1 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; LocalVarUsage found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; assertEquals ( "" , found . getName ( ) ) ; assertEquals ( , found . getFromPosition ( ) ) ; assertEquals ( , found . getToPosition ( ) ) ; } public void testFindLocalUsages_2 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; LocalVarUsage found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; assertEquals ( "" , found . getName ( ) ) ; assertEquals ( , found . getFromPosition ( ) ) ; assertEquals ( , found . getToPosition ( ) ) ; found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; assertEquals ( "" , found . getName ( ) ) ; assertEquals ( , found . getFromPosition ( ) ) ; assertEquals ( , found . getToPosition ( ) ) ; } public void testFindLocalUsages_3 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; LocalVarUsage found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; assertEquals ( "" , found . getName ( ) ) ; assertEquals ( , found . getFromPosition ( ) ) ; assertEquals ( , found . getToPosition ( ) ) ; found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; assertEquals ( "" , found . getName ( ) ) ; assertEquals ( , found . getFromPosition ( ) ) ; assertEquals ( , found . getToPosition ( ) ) ; } public void testFindLocalUsages_4 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; LocalVarUsage found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; assertEquals ( "" , found . getName ( ) ) ; assertEquals ( , found . getFromPosition ( ) ) ; assertEquals ( , found . getToPosition ( ) ) ; } public void testFindLocalUsages_5 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; LocalVarUsage found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; assertEquals ( "" , found . getName ( ) ) ; assertEquals ( , found . getFromPosition ( ) ) ; assertEquals ( , found . getToPosition ( ) ) ; } public void testFindLocalUsages_6 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; } public void testFindLocalUsages_7 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; LocalVarUsage found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; } public void testFindLocalUsages_8 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; LocalVarUsage found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; } public void testFindLocalUsages_9 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNotNull ( variables ) ; assertEquals ( , variables . size ( ) ) ; LocalVarUsage found = ( LocalVarUsage ) variables . toArray ( ) [ ] ; assertNotNull ( found . getNode ( ) ) ; } public void testFindLocalUsages_10 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNull ( variables ) ; } public void testFindLocalUsages_11 ( ) throws FileNotFoundException , IOException { Collection < LocalVarUsage > variables = find ( "" , ) ; assertNull ( variables ) ; } } package org . rubypeople . rdt . refactoring . tests . core . splitlocal . conditionchecks ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_SplitLocalChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , SplitLocalConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . splitlocal . conditionchecks ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitLocalConditionChecker ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitLocalConfig ; import org . rubypeople . rdt . refactoring . core . splitlocal . SplitTempEditProvider ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class SplitLocalConditionTester extends RefactoringConditionTestCase { private FilePropertyData testData ; private SplitLocalConfig config ; public SplitLocalConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; int caretPosition = testData . getIntProperty ( "" ) ; config = new SplitLocalConfig ( testData , caretPosition ) ; SplitLocalConditionChecker checker = new SplitLocalConditionChecker ( config ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new SplitTempEditProvider ( config ) ; } } package org . rubypeople . rdt . refactoring . tests . core . splitlocal ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . splitlocal . conditionchecks . TS_SplitLocalChecks ; public class TS_SplitLocal extends FileTestSuite { public static TestSuite suite ( ) { TestSuite suite = createSuite ( "" , "" , SplitLocalTester . class ) ; suite . addTestSuite ( TC_LocalVarFinder . class ) ; suite . addTestSuite ( TC_SplittedVariableRenamer . class ) ; suite . addTest ( TS_SplitLocalChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . renameclass ; import java . io . FileNotFoundException ; import java . io . IOException ; import junit . framework . TestCase ; import org . rubypeople . rdt . refactoring . core . renameclass . ClassInstanciationFinder ; import org . rubypeople . rdt . refactoring . core . renameclass . ConstructorCall ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; public class TC_ClassInstanciationFinder extends TestCase { public void testFind1 ( ) throws FileNotFoundException , IOException { ConstructorCall [ ] calls = getConstructorCalls ( "" , "" ) ; assertEquals ( , calls . length ) ; for ( ConstructorCall call : calls ) { assertEquals ( "" , call . getClassName ( ) ) ; assertNull ( call . getArgs ( ) ) ; assertNotNull ( call . getNode ( ) ) ; } } public void testFind2 ( ) throws FileNotFoundException , IOException { ConstructorCall [ ] calls = getConstructorCalls ( "" , "" ) ; assertEquals ( , calls . length ) ; } public void testFind3 ( ) throws FileNotFoundException , IOException { ConstructorCall [ ] calls = getConstructorCalls ( "" , "" ) ; assertEquals ( , calls . length ) ; for ( ConstructorCall call : calls ) { assertEquals ( "" , call . getClassName ( ) ) ; assertNull ( call . getArgs ( ) ) ; assertNotNull ( call . getNode ( ) ) ; } } private ConstructorCall [ ] getConstructorCalls ( String testName , String className ) throws FileNotFoundException , IOException { IDocumentProvider doc = getDoc ( testName ) ; return new ClassInstanciationFinder ( ) . findAll ( doc , className , null ) . toArray ( new ConstructorCall [ ] { } ) ; } private IDocumentProvider getDoc ( String testFile ) throws FileNotFoundException , IOException { return new DocumentWithIncluding ( new MultiFileTestData ( "" , "" , "" , testFile + "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renameclass ; import java . io . FileNotFoundException ; import java . io . IOException ; import junit . framework . TestCase ; import org . jruby . ast . ClassNode ; import org . rubypeople . rdt . refactoring . core . renameclass . ClassFinder ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentWithIncluding ; import org . rubypeople . rdt . refactoring . documentprovider . IDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; public class TC_ClassFinder extends TestCase { public void testFindAll1 ( ) throws FileNotFoundException , IOException { IDocumentProvider doc = getDoc ( "" ) ; ClassNode [ ] classNodes = new ClassFinder ( doc , "" , "" ) . findParts ( ) . toArray ( new ClassNode [ ] { } ) ; assertEquals ( , classNodes . length ) ; for ( ClassNode node : classNodes ) { assertEquals ( "" , node . getCPath ( ) . getName ( ) ) ; } } private IDocumentProvider getDoc ( String testFile ) throws FileNotFoundException , IOException { return new DocumentWithIncluding ( new MultiFileTestData ( "" , "" , "" , testFile + "" ) ) ; } public void testFindAll2 ( ) throws FileNotFoundException , IOException { IDocumentProvider doc = getDoc ( "" ) ; ClassNode [ ] classNodes = new ClassFinder ( doc , "" , "" ) . findParts ( ) . toArray ( new ClassNode [ ] { } ) ; assertEquals ( , classNodes . length ) ; } public void testFindAll3 ( ) throws FileNotFoundException , IOException { IDocumentProvider doc = getDoc ( "" ) ; ClassNode [ ] classNodes = new ClassFinder ( doc , "" , "" ) . findParts ( ) . toArray ( new ClassNode [ ] { } ) ; assertEquals ( , classNodes . length ) ; } public void testFindAllWithModule ( ) throws FileNotFoundException , IOException { IDocumentProvider doc = getDoc ( "" ) ; ClassNode [ ] classNodes = new ClassFinder ( doc , "" , "" ) . findParts ( ) . toArray ( new ClassNode [ ] { } ) ; assertEquals ( , classNodes . length ) ; for ( ClassNode node : classNodes ) { assertEquals ( "" , node . getCPath ( ) . getName ( ) ) ; } } public void testFindChildren ( ) throws FileNotFoundException , IOException { IDocumentProvider doc = getDoc ( "" ) ; ClassNode [ ] classNodes = new ClassFinder ( doc , "" , "" ) . findChildren ( ) . toArray ( new ClassNode [ ] { } ) ; assertEquals ( , classNodes . length ) ; assertEquals ( "" , classNodes [ ] . getCPath ( ) . getName ( ) ) ; assertEquals ( "" , classNodes [ ] . getCPath ( ) . getName ( ) ) ; assertEquals ( "" , classNodes [ ] . getCPath ( ) . getName ( ) ) ; assertEquals ( "" , classNodes [ ] . getCPath ( ) . getName ( ) ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renameclass . conditionchecker ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassConditionChecker ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassConfig ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassEditProvider ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringConditionTestCase ; public class RenameClassConditionTester extends RefactoringConditionTestCase { private FilePropertyData testData ; private RenameClassConfig renameClassConfig ; public RenameClassConditionTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException { testData = new FileTestData ( getName ( ) , "" , "" ) ; renameClassConfig = new RenameClassConfig ( testData , testData . getIntProperty ( "" ) ) ; RenameClassConditionChecker checker = new RenameClassConditionChecker ( renameClassConfig ) ; checkConditions ( checker , testData ) ; } @ Override protected void createEditProviderAndSetUserInput ( ) { new RenameClassEditProvider ( renameClassConfig ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renameclass . conditionchecker ; import junit . framework . Test ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_RenameClassChecks extends FileTestSuite { public static Test suite ( ) { return createSuite ( "" , "" , RenameClassConditionTester . class ) ; } } package org . rubypeople . rdt . refactoring . tests . core . renameclass ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; import org . rubypeople . rdt . refactoring . tests . core . renameclass . conditionchecker . TS_RenameClassChecks ; public class TS_RenameClass extends FileTestSuite { public static TestSuite suite ( ) { TestSuite suite = createSuite ( "" , "" , ClassRenameTester . class ) ; suite . addTestSuite ( TC_ClassFinder . class ) ; suite . addTestSuite ( TC_ClassInstanciationFinder . class ) ; suite . addTest ( TS_RenameClassChecks . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . renameclass ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassConditionChecker ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassConfig ; import org . rubypeople . rdt . refactoring . core . renameclass . RenameClassEditProvider ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . tests . MultiFileTestData ; public class ClassRenameTester extends FileTestCase { public ClassRenameTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { MultiFileTestData testData = new MultiFileTestData ( getName ( ) ) ; int caretPosition = testData . getIntProperty ( "" ) ; RenameClassConfig renameClassConfig = new RenameClassConfig ( testData , caretPosition ) ; new RenameClassConditionChecker ( renameClassConfig ) ; renameClassConfig . setNewName ( testData . getProperty ( "" ) ) ; RenameClassEditProvider editProvider = new RenameClassEditProvider ( renameClassConfig ) ; checkMultiFileEdits ( editProvider , testData ) ; } } package org . rubypeople . rdt . refactoring . tests . core ; import java . util . Collection ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . Colon2Node ; import org . jruby . ast . CommentNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . FCallNode ; import org . jruby . ast . LocalAsgnNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . NewlineNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . ast . SymbolNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . parser . LocalStaticScope ; import org . rubypeople . rdt . core . util . Util ; import org . rubypeople . rdt . internal . core . parser . ClosestNodeLocator ; import org . rubypeople . rdt . refactoring . core . NodeProvider ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class TC_NodeProvider extends FileTestCase { public TC_NodeProvider ( ) { super ( "" ) ; } public void testGetAllNodes ( ) { Node rootNode = getRootNode ( "" ) ; Node [ ] allNodes = NodeProvider . getAllNodes ( rootNode ) . toArray ( new Node [ ] { } ) ; assertEquals ( , allNodes . length ) ; assertTrue ( NodeUtil . nodeAssignableFrom ( allNodes [ ] , BlockNode . class ) ) ; assertTrue ( NodeUtil . nodeAssignableFrom ( allNodes [ ] , NewlineNode . class ) ) ; assertTrue ( NodeUtil . nodeAssignableFrom ( allNodes [ ] , ClassNode . class ) ) ; assertTrue ( NodeUtil . nodeAssignableFrom ( allNodes [ ] , Colon2Node . class ) ) ; assertTrue ( NodeUtil . nodeAssignableFrom ( allNodes [ ] , ConstNode . class ) ) ; } public void testGetSelectedNodeOfType ( ) { Node rootNode = getRootNode ( "" ) ; Node defnNode = SelectionNodeProvider . getSelectedNodeOfType ( rootNode , , DefnNode . class ) ; assertEquals ( DefnNode . class , defnNode . getClass ( ) ) ; Node argumentNode = SelectionNodeProvider . getSelectedNodeOfType ( rootNode , , ArgumentNode . class ) ; assertEquals ( ArgumentNode . class , argumentNode . getClass ( ) ) ; Node nullNode = SelectionNodeProvider . getSelectedNodeOfType ( rootNode , , ArgumentNode . class ) ; assertNull ( nullNode ) ; Node localAsgnNode = SelectionNodeProvider . getSelectedNodeOfType ( rootNode , , LocalAsgnNode . class ) ; assertEquals ( LocalAsgnNode . class , localAsgnNode . getClass ( ) ) ; } public void testNodeAssignableFrom ( ) { ArgsNode args = new ArgsNode ( null , null , null , null , null , null ) ; assertTrue ( NodeUtil . nodeAssignableFrom ( new DefnNode ( null , null , args , new LocalStaticScope ( null ) , null ) , DefnNode . class ) ) ; assertTrue ( NodeUtil . nodeAssignableFrom ( new LocalVarNode ( null , , "" ) , LocalVarNode . class ) ) ; } public void testNodeContainsCaretPosition ( ) { assertTrue ( SelectionNodeProvider . nodeContainsPosition ( new ArgumentNode ( new IDESourcePosition ( "" , , , , ) , "" ) , ) ) ; assertTrue ( SelectionNodeProvider . nodeContainsPosition ( new ArgumentNode ( new IDESourcePosition ( "" , , , , ) , "" ) , ) ) ; assertFalse ( SelectionNodeProvider . nodeContainsPosition ( new ArgumentNode ( new IDESourcePosition ( "" , , , , ) , "" ) , ) ) ; assertFalse ( SelectionNodeProvider . nodeContainsPosition ( new ArgumentNode ( new IDESourcePosition ( "" , , , , ) , "" ) , ) ) ; } public void testGatherLocalAsgnNodes ( ) { RootNode rootNode = getRootNode ( "" ) ; LocalAsgnNode [ ] nodes = NodeProvider . gatherLocalAsgnNodes ( rootNode . getBodyNode ( ) ) . toArray ( new LocalAsgnNode [ ] { } ) ; assertEquals ( , nodes . length ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( , nodes [ ] . getIndex ( ) ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( , nodes [ ] . getIndex ( ) ) ; assertEquals ( "" , nodes [ ] . getName ( ) ) ; assertEquals ( , nodes [ ] . getIndex ( ) ) ; } public void testCommentAssociation ( ) throws Exception { String fileName = "" ; String source = new String ( Util . getInputStreamAsCharArray ( getClass ( ) . getResourceAsStream ( fileName ) , - , null ) ) ; RootNode root = NodeProvider . getRootNode ( fileName , source ) ; assertNodeHasTypeAndComments ( root , , ClassNode . class , ) ; assertNodeHasTypeAndComments ( root , , FCallNode . class , ) ; assertNodeHasTypeAndComments ( root , , SymbolNode . class , ) ; } private void assertNodeHasTypeAndComments ( Node ast , int offset , Class < ? extends Node > expectedClass , int commentCount ) { Node node = getNode ( ast , offset ) ; assertNotNull ( node ) ; assertTrue ( expectedClass . isAssignableFrom ( node . getClass ( ) ) ) ; Collection < CommentNode > comments = node . getComments ( ) ; assertNotNull ( comments ) ; assertEquals ( commentCount , comments . size ( ) ) ; } private Node getNode ( Node root , int offset ) { return new ClosestNodeLocator ( ) . getClosestNodeAtOffset ( root , offset ) ; } } package org . rubypeople . rdt . refactoring . tests . core . generateaccessors ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . core . generateaccessors . AccessorsGenerator ; import org . rubypeople . rdt . refactoring . core . generateaccessors . GeneratedAccessor ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . tests . TreeProviderTester ; public class TC_AccessorsGeneratorTreeTest extends TreeProviderTester { private final static String TEST_DOCUMENT_SIMPLE = "" + "" + "" + "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_WITH_SIMPLE_ACCESSOR = "" + "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_WITH_METHOD_ACCESSOR = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_WITH_SIMPLE_WRITER = "" + "" + "" + "" + "" + "" ; private final static String TEST_DOCUMENT_WITH_METHOD_READER = "" + "" + "" + "" + "" + "" + "" + "" ; public void testSimpleDocument ( ) { DocumentProvider docProvider = new StringDocumentProvider ( "" , TEST_DOCUMENT_SIMPLE ) ; AccessorsGenerator provider = new AccessorsGenerator ( docProvider , GeneratedAccessor . TYPE_SIMPLE_ACCESSOR ) ; addContentWithBothAccessors ( new String [ ] { "" , "" } ) ; addContentWithBothAccessors ( new String [ ] { "" , "" } ) ; validate ( provider ) ; provider . setType ( GeneratedAccessor . TYPE_METHOD_ACCESSOR ) ; validate ( provider ) ; } public void testDocumentWithSimpleAccessorSelectedTypeSimple ( ) { DocumentProvider docProvider = new StringDocumentProvider ( "" , TEST_DOCUMENT_WITH_SIMPLE_ACCESSOR ) ; validate ( new AccessorsGenerator ( docProvider , GeneratedAccessor . TYPE_SIMPLE_ACCESSOR ) ) ; } public void testDocumentWithSimpleAccessorSelectedTypeMethod ( ) { addContentWithBothAccessors ( new String [ ] { "" , "" } ) ; DocumentProvider docProvider = new StringDocumentProvider ( "" , TEST_DOCUMENT_WITH_SIMPLE_ACCESSOR ) ; validate ( new AccessorsGenerator ( docProvider , GeneratedAccessor . TYPE_METHOD_ACCESSOR ) ) ; } public void testDocumentWithMethodAccessorSelectedTypeSimple ( ) { addContentWithBothAccessors ( new String [ ] { "" , "" } ) ; DocumentProvider docProvider = new StringDocumentProvider ( "" , TEST_DOCUMENT_WITH_METHOD_ACCESSOR ) ; validate ( new AccessorsGenerator ( docProvider , GeneratedAccessor . TYPE_SIMPLE_ACCESSOR ) ) ; } public void testDocumentWithMethodAccessorSelectedTypeMethod ( ) { DocumentProvider docProvider = new StringDocumentProvider ( "" , TEST_DOCUMENT_WITH_METHOD_ACCESSOR ) ; validate ( new AccessorsGenerator ( docProvider , GeneratedAccessor . TYPE_METHOD_ACCESSOR ) ) ; } public void testDocumentWithSimpleWriter ( ) { addContent ( new String [ ] { "" , "" , AccessorsGenerator . READER } ) ; DocumentProvider docProvider = new StringDocumentProvider ( "" , TEST_DOCUMENT_WITH_SIMPLE_WRITER ) ; validate ( new AccessorsGenerator ( docProvider , GeneratedAccessor . TYPE_SIMPLE_ACCESSOR ) ) ; } public void testDocumentWithMethodReader ( ) { addContent ( new String [ ] { "" , "" , AccessorsGenerator . WRITER } ) ; DocumentProvider docProvider = new StringDocumentProvider ( "" , TEST_DOCUMENT_WITH_METHOD_READER ) ; validate ( new AccessorsGenerator ( docProvider , GeneratedAccessor . TYPE_METHOD_ACCESSOR ) ) ; } private void addContentWithBothAccessors ( String [ ] content ) { addContent ( addToArray ( content , AccessorsGenerator . READER ) ) ; addContent ( addToArray ( content , AccessorsGenerator . WRITER ) ) ; } private String [ ] addToArray ( String [ ] content , String additionalContent ) { Collection < String > contentList = new ArrayList < String > ( Arrays . asList ( content ) ) ; contentList . add ( additionalContent ) ; return contentList . toArray ( new String [ ] { } ) ; } } package org . rubypeople . rdt . refactoring . tests . core . generateaccessors ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . FileTestSuite ; public class TS_GenerateAccessors extends FileTestSuite { public static Test suite ( ) { TestSuite suite = createSuite ( "" , "" , GenerateAccessorTester . class ) ; suite . addTestSuite ( TC_AccessorsGeneratorTreeTest . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . core . generateaccessors ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collection ; import org . eclipse . jface . text . BadLocationException ; import org . rubypeople . rdt . refactoring . core . generateaccessors . AccessorsGenerator ; import org . rubypeople . rdt . refactoring . core . generateaccessors . GeneratedAccessor ; import org . rubypeople . rdt . refactoring . core . generateaccessors . AccessorsGenerator . TreeClass ; import org . rubypeople . rdt . refactoring . core . generateaccessors . AccessorsGenerator . TreeClass . TreeAttribute ; import org . rubypeople . rdt . refactoring . core . generateaccessors . AccessorsGenerator . TreeClass . TreeAttribute . TreeAccessor ; import org . rubypeople . rdt . refactoring . tests . FilePropertyData ; import org . rubypeople . rdt . refactoring . tests . FileTestData ; import org . rubypeople . rdt . refactoring . tests . RefactoringTestCase ; public class GenerateAccessorTester extends RefactoringTestCase { private AccessorsGenerator accessorsGenerator ; private Collection < AccessorSelection > selections = new ArrayList < AccessorSelection > ( ) ; public GenerateAccessorTester ( String fileName ) { super ( fileName ) ; } @ Override public void runTest ( ) throws FileNotFoundException , IOException , BadLocationException { FileTestData testData ; testData = new FileTestData ( getName ( ) ) ; int type = getAccessorType ( testData ) ; accessorsGenerator = new AccessorsGenerator ( testData , type ) ; Collection < String > strSelections = testData . getNumberedProperty ( "" ) ; for ( String aktSelection : strSelections ) { String [ ] selection = FilePropertyData . seperateString ( aktSelection ) ; addSelection ( selection [ ] , selection [ ] , FilePropertyData . getBoolValue ( selection [ ] ) , FilePropertyData . getBoolValue ( selection [ ] ) ) ; } setSelection ( selections ) ; createEditAndCompareResult ( testData . getSource ( ) , testData . getExpectedResult ( ) , accessorsGenerator ) ; } private int getAccessorType ( FileTestData testData ) { String typeStr = testData . getProperty ( "" ) ; if ( "" . equals ( typeStr ) ) { return GeneratedAccessor . TYPE_METHOD_ACCESSOR ; } else if ( "" . equals ( typeStr ) ) { return GeneratedAccessor . TYPE_SIMPLE_ACCESSOR ; } fail ( ) ; return - ; } protected void addSelection ( String name , String attributeName , boolean readerSelected , boolean writerSelected ) { selections . add ( new AccessorSelection ( name , attributeName , readerSelected , writerSelected ) ) ; } private void setSelection ( Collection < AccessorSelection > selections ) { Collection < TreeAccessor > selection = new ArrayList < TreeAccessor > ( ) ; for ( AccessorSelection sel : selections ) { selection . addAll ( getTreeAccessors ( sel ) ) ; } accessorsGenerator . setSelectedItems ( selection . toArray ( ) ) ; } private Collection < TreeAccessor > getTreeAccessors ( AccessorSelection selection ) { for ( Object o : accessorsGenerator . getElements ( null ) ) { if ( o instanceof TreeClass ) { TreeClass aktClass = ( TreeClass ) o ; if ( aktClass . toString ( ) . equals ( selection . getClassName ( ) ) ) return getTreeAccessors ( selection , aktClass ) ; } } return new ArrayList < TreeAccessor > ( ) ; } private Collection < TreeAccessor > getTreeAccessors ( AccessorSelection selection , TreeClass klass ) { for ( Object o : klass . getChildren ( ) ) { if ( o instanceof TreeAttribute ) { TreeAttribute aktAttr = ( TreeAttribute ) o ; if ( aktAttr . toString ( ) . equals ( selection . getAttributeName ( ) ) ) return getTreeAccessors ( selection , aktAttr ) ; } } return new ArrayList < TreeAccessor > ( ) ; } private Collection < TreeAccessor > getTreeAccessors ( AccessorSelection selection , TreeAttribute attr ) { Collection < TreeAccessor > result = new ArrayList < TreeAccessor > ( ) ; for ( Object o : attr . getChildren ( ) ) { if ( o instanceof TreeAccessor ) { TreeAccessor aktAccessor = ( TreeAccessor ) o ; if ( aktAccessor . isReader ( ) && selection . isReaderSelected ( ) ) { result . add ( aktAccessor ) ; attr . setReaderSelected ( ) ; } if ( aktAccessor . isWriter ( ) && selection . isWriterSelected ( ) ) { result . add ( aktAccessor ) ; attr . setWriterSelected ( ) ; } } } return result ; } private static class AccessorSelection { private String className ; private String attributeName ; private boolean readerSelected ; private boolean writerSelected ; public AccessorSelection ( String className , String attributeName , boolean readerSelected , boolean writerSelected ) { this . className = className ; this . attributeName = attributeName ; this . readerSelected = readerSelected ; this . writerSelected = writerSelected ; } String getAttributeName ( ) { return attributeName ; } String getClassName ( ) { return className ; } boolean isReaderSelected ( ) { return readerSelected ; } boolean isWriterSelected ( ) { return writerSelected ; } } } package org . rubypeople . rdt . refactoring . tests . core . generateaccessors ; public class AccessorSelection { private String className ; private String attributeName ; private boolean readerSelected ; private boolean writerSelected ; public AccessorSelection ( String className , String attributeName , boolean readerSelected , boolean writerSelected ) { this . className = className ; this . attributeName = attributeName ; this . readerSelected = readerSelected ; this . writerSelected = writerSelected ; } public String getAttributeName ( ) { return attributeName ; } public String getClassName ( ) { return className ; } public boolean isReaderSelected ( ) { return readerSelected ; } public boolean isWriterSelected ( ) { return writerSelected ; } } package org . rubypeople . rdt . refactoring . tests . classnodeprovider ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . classnodeprovider . AllFilesClassNodeProvider ; import org . rubypeople . rdt . refactoring . classnodeprovider . ClassNodeProvider ; import org . rubypeople . rdt . refactoring . documentprovider . StringDocumentProvider ; import org . rubypeople . rdt . refactoring . nodewrapper . ClassNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . MethodNodeWrapper ; import org . rubypeople . rdt . refactoring . nodewrapper . PartialClassNodeWrapper ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; public abstract class ClassNodeProviderTester extends FileTestCase { private Collection < String > expectedMethodSignatures ; private Collection < String > expectedClasses ; private StringDocumentProvider docProvider ; public ClassNodeProviderTester ( ) { super ( "" ) ; init ( ) ; } protected void init ( ) { docProvider = new StringDocumentProvider ( "" , "" ) ; expectedMethodSignatures = new ArrayList < String > ( ) ; expectedClasses = new ArrayList < String > ( ) ; } public void addTestRubyFile ( String fileName ) { docProvider . addFile ( fileName , getSource ( fileName ) ) ; } public void addExpectedMethod ( String signature ) { expectedMethodSignatures . add ( signature ) ; } public void addExpectedClass ( String name ) { expectedClasses . add ( name ) ; } public void validateClasses ( ) { ClassNodeProvider provider = new AllFilesClassNodeProvider ( docProvider ) ; Collection < ClassNodeWrapper > classes = provider . getAllClassNodes ( ) ; ClassNodeWrapper [ ] classesArray = classes . toArray ( new ClassNodeWrapper [ ] ) ; String [ ] expectedClassesArray = expectedClasses . toArray ( new String [ ] ) ; ArrayList < String > availableClasses = new ArrayList < String > ( ) ; for ( int i = ; i < classesArray . length ; i ++ ) { Collection < PartialClassNodeWrapper > partialClassNodes = classesArray [ i ] . getPartialClassNodes ( ) ; for ( PartialClassNodeWrapper partialClass : partialClassNodes ) { availableClasses . add ( partialClass . getClassName ( ) ) ; } } for ( int i = ; i < expectedClassesArray . length ; i ++ ) { assertEquals ( expectedClassesArray [ i ] , availableClasses . get ( i ) ) ; } } public void validateMethods ( String className ) { ClassNodeProvider provider = new AllFilesClassNodeProvider ( docProvider ) ; Collection < MethodNodeWrapper > methods = provider . getClassNode ( className ) . getMethods ( ) ; assertEquals ( expectedMethodSignatures . size ( ) , methods . size ( ) ) ; MethodNodeWrapper [ ] methodsArray = methods . toArray ( new MethodNodeWrapper [ ] ) ; String [ ] expectedMethodNodeSignaturesArray = expectedMethodSignatures . toArray ( new String [ ] ) ; for ( int i = ; i < methodsArray . length ; i ++ ) { assertEquals ( expectedMethodNodeSignaturesArray [ i ] , methodsArray [ i ] . getSignature ( ) . getNameWithArgs ( ) ) ; } } } package org . rubypeople . rdt . refactoring . tests . classnodeprovider ; public class TC_IncludedClassesProvider extends ClassNodeProviderTester { @ Override protected void setUp ( ) throws Exception { init ( ) ; } public void testSimpleClass ( ) { addTestRubyFile ( "" ) ; addExpectedClass ( "" ) ; addExpectedClass ( "" ) ; addExpectedClass ( "" ) ; validateClasses ( ) ; } public void testSimpleModule ( ) { addTestRubyFile ( "" ) ; addExpectedClass ( "" ) ; addExpectedClass ( "" ) ; addExpectedClass ( "" ) ; addExpectedClass ( "" ) ; validateClasses ( ) ; } } package org . rubypeople . rdt . refactoring . tests . classnodeprovider ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_ClassNodeProvider extends TestSuite { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_ClassNodeProvider . class ) ; suite . addTestSuite ( TC_IncludedClassesProvider . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . classnodeprovider ; public class TC_ClassNodeProvider extends ClassNodeProviderTester { public void testClassNodeProviderOneFileMultiplePartialClasses ( ) { addTestRubyFile ( "" ) ; addExpectedMethod ( "" ) ; addExpectedMethod ( "" ) ; addExpectedMethod ( "" ) ; validateMethods ( "" ) ; } } package org . rubypeople . rdt . refactoring . tests . util ; import java . util . ArrayList ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . rubypeople . rdt . refactoring . core . SelectionNodeProvider ; import org . rubypeople . rdt . refactoring . tests . FileTestCase ; import org . rubypeople . rdt . refactoring . util . NameHelper ; public class TC_NameHelper extends FileTestCase { public TC_NameHelper ( ) { super ( "" ) ; } public void testCreateName ( ) { assertEquals ( "" , NameHelper . createName ( "" ) ) ; assertEquals ( "" , NameHelper . createName ( "" ) ) ; assertEquals ( "" , NameHelper . createName ( "" ) ) ; assertEquals ( "" , NameHelper . createName ( "" ) ) ; assertEquals ( "" , NameHelper . createName ( "" ) ) ; assertEquals ( "" , NameHelper . createName ( "" ) ) ; assertEquals ( "" , NameHelper . createName ( "" ) ) ; } public void testFindDuplicates1 ( ) { String [ ] first = new String [ ] { "" , "" , "" } ; String [ ] second = new String [ ] { "" , "" , "" } ; assertEqualContent ( new String [ ] { "" , "" , "" } , NameHelper . findDuplicates ( first , second ) ) ; } public void testFindDuplicates2 ( ) { String [ ] first = new String [ ] { "" , "" , "" } ; String [ ] second = new String [ ] { "" , "" } ; assertEqualContent ( new String [ ] { "" , "" } , NameHelper . findDuplicates ( first , second ) ) ; } public void testFindDuplicates3 ( ) { String [ ] first = new String [ ] { "" , "" , "" } ; String [ ] second = new String [ ] { } ; assertEqualContent ( new String [ ] { } , NameHelper . findDuplicates ( first , second ) ) ; } private static void assertEqualContent ( String [ ] first , ArrayList < String > name ) { assertEquals ( first . length , name . size ( ) ) ; for ( int i = ; i < first . length ; i ++ ) { assertEquals ( first [ i ] , name . get ( i ) ) ; } } public void testModulePrefix ( ) { final RootNode rootNode = getRootNode ( "" ) ; Node node = getLastNode ( , rootNode ) ; assertEquals ( "" , NameHelper . getEncosingModulePrefix ( rootNode , node ) ) ; node = getLastNode ( , rootNode ) ; assertEquals ( "" , NameHelper . getEncosingModulePrefix ( rootNode , node ) ) ; node = getLastNode ( , rootNode ) ; assertEquals ( "" , NameHelper . getEncosingModulePrefix ( rootNode , node ) ) ; node = getLastNode ( , rootNode ) ; assertEquals ( "" , NameHelper . getEncosingModulePrefix ( rootNode , node ) ) ; } private Node getLastNode ( int pos , RootNode rootNode ) { Node [ ] nodes = SelectionNodeProvider . getSelectedNodesOfType ( rootNode , pos , Node . class ) . toArray ( new Node [ ] { } ) ; assertTrue ( nodes . length > ) ; return nodes [ nodes . length - ] ; } } package org . rubypeople . rdt . refactoring . tests . util ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_Util extends TestSuite { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_HSRFormatter . class ) ; suite . addTestSuite ( TC_NameValidator . class ) ; suite . addTestSuite ( TC_StringHelper . class ) ; suite . addTestSuite ( TC_NameHelper . class ) ; suite . addTestSuite ( TC_NodeUtil . class ) ; suite . addTestSuite ( TC_FileHelper . class ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests . util ; import junit . framework . TestCase ; import org . jruby . ast . ArgsNode ; import org . jruby . ast . BlockNode ; import org . jruby . ast . ClassNode ; import org . jruby . ast . DefnNode ; import org . jruby . ast . DefsNode ; import org . jruby . ast . InstVarNode ; import org . jruby . ast . IterNode ; import org . jruby . ast . Node ; import org . jruby . ast . RootNode ; import org . jruby . parser . BlockStaticScope ; import org . jruby . parser . LocalStaticScope ; import org . jruby . parser . StaticScope ; import org . jruby . runtime . DynamicScope ; import org . rubypeople . rdt . refactoring . util . NodeUtil ; public class TC_NodeUtil extends TestCase { public void testHasScope_RootNode ( ) { assertTrue ( NodeUtil . hasScope ( new RootNode ( null , DynamicScope . newDynamicScope ( new BlockStaticScope ( null ) , null ) , null ) ) ) ; } public void testHasScope_DefnNode ( ) { assertTrue ( NodeUtil . hasScope ( new DefnNode ( null , null , createArgsNode ( ) , createStaticScope ( ) , null ) ) ) ; } public void testHasScope_DefsNode ( ) { assertTrue ( NodeUtil . hasScope ( new DefsNode ( null , null , null , createArgsNode ( ) , createStaticScope ( ) , null ) ) ) ; } public void testHasScope_IterNode ( ) { assertTrue ( NodeUtil . hasScope ( new IterNode ( null , ( Node ) null , ( StaticScope ) null , ( Node ) null ) ) ) ; } public void testHasScope_ClassNode ( ) { assertTrue ( NodeUtil . hasScope ( new ClassNode ( null , null , null , null , null ) ) ) ; } public void testHasNoScope_BlockNode ( ) { assertFalse ( NodeUtil . hasScope ( new BlockNode ( null ) ) ) ; } public void testHasNoScope_VarNode ( ) { assertFalse ( NodeUtil . hasScope ( new InstVarNode ( null , "" ) ) ) ; } private ArgsNode createArgsNode ( ) { return new ArgsNode ( null , null , null , null , null , null ) ; } private StaticScope createStaticScope ( ) { return new LocalStaticScope ( null ) ; } } package org . rubypeople . rdt . refactoring . tests . util ; import junit . framework . TestCase ; import org . rubypeople . rdt . refactoring . util . HsrFormatter ; public class TC_HSRFormatter extends TestCase { private final static String TEST_DOCUMENT_ONLY_NEEDED_NL = "" ; private final static String TEST_DOCUMENT_ONLY_NEEDED_NL_AND_SPACES = "" ; private final static String TEST_DOCUMENT_ADITIONAL_NL = "" ; private final static String TEST_DOCUMENT_ADITIONAL_NL_AND_SPACES = "" ; private final static String IN = "" ; private final static String OUT = "" ; public void testDumbIdeas ( ) { validate ( "" , "" , , "" ) ; validate ( "" , IN , , "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" , , "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" , , "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" , TEST_DOCUMENT_ONLY_NEEDED_NL . length ( ) , "" ) ; } public void testDumbNewlineIdeas ( ) { validate ( "" , "" , , "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" , , "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" , , "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" , , "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" , , "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" , , "" ) ; } public void testOnlyNeededNL ( ) { validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" + IN , , "" + OUT ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , IN + "" , , OUT + "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" + IN + "" , , "" + OUT + "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL , "" + IN + "" , , "" + OUT + "" ) ; } public void testOnlyNeededNLWithSpaceds ( ) { validate ( TEST_DOCUMENT_ONLY_NEEDED_NL_AND_SPACES , "" + IN , , "" + OUT ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL_AND_SPACES , IN + "" , , OUT + "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL_AND_SPACES , "" + IN + "" , , "" + OUT + "" ) ; validate ( TEST_DOCUMENT_ONLY_NEEDED_NL_AND_SPACES , "" + IN + "" , , "" + OUT + "" ) ; } public void testAdditionalNL ( ) { validate ( TEST_DOCUMENT_ADITIONAL_NL , "" + IN , , "" + OUT ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL , IN , , OUT ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL , IN + "" , , OUT + "" ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL , "" + IN + "" , , "" + OUT + "" ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL , "" + IN + "" , , "" + OUT + "" ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL , "" + IN + "" , , "" + OUT + "" ) ; } public void testAdditionalNLWithSpaceds ( ) { validate ( TEST_DOCUMENT_ADITIONAL_NL_AND_SPACES , "" + IN , , "" + OUT ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL_AND_SPACES , IN , , OUT ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL_AND_SPACES , IN + "" , , OUT + "" ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL_AND_SPACES , "" + IN + "" , , "" + OUT + "" ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL_AND_SPACES , "" + IN + "" , , "" + OUT + "" ) ; validate ( TEST_DOCUMENT_ADITIONAL_NL_AND_SPACES , "" + IN + "" , , "" + OUT + "" ) ; } public void testInsertIntoEmptyDocument ( ) { validate ( "" , "" , , TEST_DOCUMENT_ONLY_NEEDED_NL ) ; } private void validate ( String document , String insertText , int offset , String expectedFormatedInsertTextResult ) { String formattedInsertString = HsrFormatter . format ( document , insertText , offset ) ; assertEquals ( expectedFormatedInsertTextResult , formattedInsertString ) ; } } package org . rubypeople . rdt . refactoring . tests . util ; import org . rubypeople . rdt . refactoring . util . FileHelper ; import junit . framework . TestCase ; public class TC_FileHelper extends TestCase { private static final String LF = "" ; private static final String CR = "" ; private static final String EMPTY_DOCUMENT = "" ; private static final String TEST_DOCUMENT_LF = "" ; private static final String TEST_DOCUMENT_CR = "" ; private static final String TEST_DOCUMENT_CRLF = "" ; private static final String TEST_DOCUMENT_MIXED = "" ; public void testGetLineDelimiter ( ) { testDelimiter ( EMPTY_DOCUMENT , FileHelper . DEFAULT_LINE_DELIMITER ) ; testDelimiter ( TEST_DOCUMENT_LF , LF ) ; testDelimiter ( TEST_DOCUMENT_CR , CR ) ; testDelimiter ( TEST_DOCUMENT_CRLF , CR + LF ) ; testDelimiter ( TEST_DOCUMENT_MIXED , CR + LF ) ; } private void testDelimiter ( String document , String expectedDelimiter ) { String resultDelimiter = FileHelper . getLineDelimiter ( document ) ; assertEquals ( expectedDelimiter , resultDelimiter ) ; } } package org . rubypeople . rdt . refactoring . tests . util ; import org . rubypeople . rdt . refactoring . util . NameValidator ; import junit . framework . TestCase ; public class TC_NameValidator extends TestCase { public void testIsValidLocalVariableName ( ) { assertTrue ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertTrue ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertTrue ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertTrue ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertTrue ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertTrue ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertTrue ( NameValidator . isValidLocalVariableName ( "" ) ) ; } public void testIsinvalidLocalVariableName ( ) { assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; } public void testIsValidClassName ( ) { assertTrue ( NameValidator . isValidConstName ( "" ) ) ; assertTrue ( NameValidator . isValidConstName ( "" ) ) ; assertTrue ( NameValidator . isValidConstName ( "" ) ) ; assertTrue ( NameValidator . isValidConstName ( "" ) ) ; assertTrue ( NameValidator . isValidConstName ( "" ) ) ; } public void testIsInvalidClassName ( ) { assertFalse ( NameValidator . isValidConstName ( "" ) ) ; assertFalse ( NameValidator . isValidConstName ( "" ) ) ; assertFalse ( NameValidator . isValidConstName ( "" ) ) ; assertFalse ( NameValidator . isValidConstName ( "" ) ) ; assertFalse ( NameValidator . isValidConstName ( "" ) ) ; assertFalse ( NameValidator . isValidConstName ( "" ) ) ; assertFalse ( NameValidator . isValidConstName ( "" ) ) ; assertFalse ( NameValidator . isValidConstName ( "" ) ) ; assertFalse ( NameValidator . isValidConstName ( "" ) ) ; } public void testIsValidMethodName ( ) { assertTrue ( NameValidator . isValidMethodName ( "" ) ) ; assertTrue ( NameValidator . isValidMethodName ( "" ) ) ; assertTrue ( NameValidator . isValidMethodName ( "" ) ) ; assertTrue ( NameValidator . isValidMethodName ( "" ) ) ; assertTrue ( NameValidator . isValidMethodName ( "" ) ) ; assertTrue ( NameValidator . isValidMethodName ( "" ) ) ; assertTrue ( NameValidator . isValidMethodName ( "" ) ) ; } public void testIsInvalidMethodName ( ) { assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; assertFalse ( NameValidator . isValidLocalVariableName ( "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests . util ; import junit . framework . TestCase ; import org . rubypeople . rdt . refactoring . util . StringHelper ; public class TC_StringHelper extends TestCase { public void testNumberOfOccurences ( ) { assertEquals ( , StringHelper . numberOfOccurences ( '' , "" ) ) ; assertEquals ( , StringHelper . numberOfOccurences ( '' , "" ) ) ; assertEquals ( , StringHelper . numberOfOccurences ( '' , "" ) ) ; assertEquals ( , StringHelper . numberOfOccurences ( '' , "" ) ) ; } } package org . rubypeople . rdt . refactoring . tests ; import java . io . File ; import java . io . IOException ; import java . net . URL ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Enumeration ; import java . util . HashMap ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class TestsPlugin extends AbstractUIPlugin { private static TestsPlugin plugin ; public TestsPlugin ( ) { plugin = this ; } @ Override public void start ( BundleContext context ) throws Exception { super . start ( context ) ; } @ Override public void stop ( BundleContext context ) throws Exception { super . stop ( context ) ; plugin = null ; } public static TestsPlugin getDefault ( ) { return plugin ; } private static HashMap < String , String > files ; private static void initializeFiles ( ) { files = new HashMap < String , String > ( ) ; Enumeration enumeration = getDefault ( ) . getBundle ( ) . findEntries ( "" , null , true ) ; while ( enumeration != null && enumeration . hasMoreElements ( ) ) { URL file = ( URL ) enumeration . nextElement ( ) ; if ( file . getFile ( ) . matches ( "" ) ) { continue ; } String [ ] segments = file . getPath ( ) . split ( "" ) ; String fileName = segments [ segments . length - ] ; try { files . put ( fileName , FileLocator . resolve ( file ) . getFile ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; continue ; } } } public static String getFile ( String name ) { if ( files == null ) { initializeFiles ( ) ; } return files . get ( name ) ; } protected static Collection < File > getFiles ( final String filter ) throws IOException { ArrayList < File > files = new ArrayList < File > ( ) ; Enumeration enumeration = TestsPlugin . getDefault ( ) . getBundle ( ) . findEntries ( "" , filter , true ) ; while ( enumeration . hasMoreElements ( ) ) { URL url = FileLocator . resolve ( ( URL ) enumeration . nextElement ( ) ) ; files . add ( new File ( url . getFile ( ) ) ) ; } return files ; } public static ImageDescriptor getImageDescriptor ( String path ) { return AbstractUIPlugin . imageDescriptorFromPlugin ( "" , path ) ; } } package org . rubypeople . rdt . refactoring . tests ; import java . util . Collection ; import junit . framework . TestCase ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . refactoring . editprovider . FileMultiEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IEditProvider ; import org . rubypeople . rdt . refactoring . editprovider . IMultiFileEditProvider ; import org . rubypeople . rdt . refactoring . util . HsrFormatter ; public abstract class RefactoringTestCase extends TestCase { public RefactoringTestCase ( String name ) { super ( name ) ; } protected void createEditAndCompareResult ( String document , String expectedDocument , IEditProvider editProvider ) throws BadLocationException { String result ; if ( editProvider != null ) { TextEdit edit = editProvider . getEdit ( document ) ; Document doc = new Document ( document ) ; edit . apply ( doc ) ; result = doc . get ( ) ; result = formatText ( result ) ; expectedDocument = formatText ( expectedDocument ) ; } else { result = document ; } assertEquals ( expectedDocument , result ) ; } private String formatText ( String expectedText ) { String formatted = HsrFormatter . format ( "" , expectedText , ) ; formatted = formatted . replaceAll ( "" , "" ) ; return formatted ; } protected void checkMultiFileEdits ( IMultiFileEditProvider multiFileEditProvider , MultiFileTestData testData ) throws BadLocationException { Collection < FileMultiEditProvider > editProviders = multiFileEditProvider . getFileEditProviders ( ) ; for ( String aktFileName : testData . getFileNames ( ) ) { String sourceDocument = testData . getSource ( aktFileName ) ; String resultDocument = testData . getResult ( aktFileName ) ; FileMultiEditProvider aktEditProvider = findEditProvider ( editProviders , aktFileName ) ; createEditAndCompareResult ( sourceDocument , resultDocument , aktEditProvider ) ; } } private FileMultiEditProvider findEditProvider ( Collection < FileMultiEditProvider > editProviders , String aktFileName ) { for ( FileMultiEditProvider aktEditProvider : editProviders ) { if ( aktEditProvider . getFileName ( ) . equals ( aktFileName ) ) { return aktEditProvider ; } } return null ; } } package org . rubypeople . rdt . refactoring . tests ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collection ; import org . rubypeople . rdt . refactoring . util . FileHelper ; public class FileTestData extends FilePropertyData { private String fileName ; private String source ; private String expectedResult ; private final String sourceSuffix ; private final String resultSuffix ; public FileTestData ( String fileName , String sourceSuffix , String resultSuffix ) throws FileNotFoundException , IOException { super ( fileName + "" ) ; this . fileName = fileName ; this . sourceSuffix = sourceSuffix ; this . resultSuffix = resultSuffix ; source = initSourceFile ( ) ; expectedResult = initExpectedFile ( ) ; } public String getFileName ( ) { return fileName ; } public FileTestData ( String fileName ) throws FileNotFoundException , IOException { this ( fileName , "" , "" ) ; } private String initSourceFile ( ) { return FileHelper . getFileContent ( TestsPlugin . getFile ( fileName + sourceSuffix ) ) ; } private String initExpectedFile ( ) { return FileHelper . getFileContent ( TestsPlugin . getFile ( fileName + resultSuffix ) ) ; } public String getSource ( ) { return source ; } public String getExpectedResult ( ) { return expectedResult ; } public String getActiveFileContent ( ) { return getSource ( ) ; } public String getActiveFileName ( ) { return fileName + sourceSuffix ; } public String getFileContent ( String currentFileName ) { return FileHelper . getFileContent ( TestsPlugin . getFile ( currentFileName ) ) ; } public Collection < String > getFileNames ( ) { Collection < String > names = new ArrayList < String > ( ) ; names . add ( getActiveFileName ( ) ) ; return names ; } } package org . rubypeople . rdt . refactoring . tests ; import java . util . HashMap ; import java . util . Map ; import org . eclipse . jface . viewers . ITreeContentProvider ; public abstract class TreeProviderTester extends RefactoringTestCase { public TreeProviderTester ( ) { this ( "" ) ; } public TreeProviderTester ( String fileName ) { super ( fileName ) ; } private Map < String , Entry > elements ; private ITreeContentProvider provider ; @ Override public void setUp ( ) { elements = new HashMap < String , Entry > ( ) ; } public void addContent ( String [ ] content ) { Map < String , Entry > aktMap = elements ; for ( String str : content ) { if ( ! aktMap . containsKey ( str ) ) { aktMap . put ( str , new Entry ( str ) ) ; } aktMap = aktMap . get ( str ) . getChilds ( ) ; } } public void validate ( ITreeContentProvider provider ) { this . provider = provider ; checkElements ( elements , provider . getElements ( null ) ) ; } private void checkElements ( Map < String , Entry > expectedElements , Object [ ] elements ) { assertNotNull ( elements ) ; assertEquals ( expectedElements . size ( ) , elements . length ) ; for ( Object aktElement : elements ) { assertTrue ( expectedElements . containsKey ( aktElement . toString ( ) ) ) ; Entry aktEntry = expectedElements . get ( aktElement . toString ( ) ) ; if ( provider . hasChildren ( aktElement ) ) { checkElements ( aktEntry . getChilds ( ) , provider . getChildren ( aktElement ) ) ; } else { assertEquals ( , aktEntry . getChilds ( ) . size ( ) ) ; } } } static class Entry { private String name ; private Map < String , Entry > childs ; public Entry ( String name ) { this . name = name ; childs = new HashMap < String , Entry > ( ) ; } public String getName ( ) { return name ; } public void addChild ( Entry child ) { childs . put ( child . getName ( ) , child ) ; } public Map < String , Entry > getChilds ( ) { return childs ; } } } package org . rubypeople . rdt . refactoring . tests ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . refactoring . tests . classnodeprovider . TS_ClassNodeProvider ; import org . rubypeople . rdt . refactoring . tests . core . TS_Core ; import org . rubypeople . rdt . refactoring . tests . core . convertlocaltofield . TS_LocalToField ; import org . rubypeople . rdt . refactoring . tests . core . encapsulatefield . TS_EncapsulateField ; import org . rubypeople . rdt . refactoring . tests . core . extractconstant . TS_ExtractConstant ; import org . rubypeople . rdt . refactoring . tests . core . extractmethod . TS_ExtractMethod ; import org . rubypeople . rdt . refactoring . tests . core . generateaccessors . TS_GenerateAccessors ; import org . rubypeople . rdt . refactoring . tests . core . generateconstructor . TS_GenerateConstructor ; import org . rubypeople . rdt . refactoring . tests . core . inlineclass . TS_InlineClass ; import org . rubypeople . rdt . refactoring . tests . core . inlinelocal . TS_InlineLocal ; import org . rubypeople . rdt . refactoring . tests . core . inlinemethod . TS_InlineMethod ; import org . rubypeople . rdt . refactoring . tests . core . mergeclasspartsinfile . TS_MergeClassPartsInFile ; import org . rubypeople . rdt . refactoring . tests . core . mergewithexternalclassparts . TS_MergeWithExternalClassParts ; import org . rubypeople . rdt . refactoring . tests . core . movefield . TS_MoveField ; import org . rubypeople . rdt . refactoring . tests . core . movemethod . TS_MoveMethod ; import org . rubypeople . rdt . refactoring . tests . core . nodewrapper . TS_NodeWrapper ; import org . rubypeople . rdt . refactoring . tests . core . overridemethod . TS_OverrideMethod ; import org . rubypeople . rdt . refactoring . tests . core . pushdown . TS_PushDown ; import org . rubypeople . rdt . refactoring . tests . core . rename . TS_Rename ; import org . rubypeople . rdt . refactoring . tests . core . renameclass . TS_RenameClass ; import org . rubypeople . rdt . refactoring . tests . core . renamefield . TS_RenameField ; import org . rubypeople . rdt . refactoring . tests . core . renamelocal . TS_RenameLocal ; import org . rubypeople . rdt . refactoring . tests . core . renamemethod . TS_RenameMethod ; import org . rubypeople . rdt . refactoring . tests . core . renamemodule . TS_RenameModule ; import org . rubypeople . rdt . refactoring . tests . core . splitlocal . TS_SplitLocal ; import org . rubypeople . rdt . refactoring . tests . util . TS_Util ; public class TS_All { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( TS_GenerateAccessors . suite ( ) ) ; suite . addTest ( TS_GenerateConstructor . suite ( ) ) ; suite . addTest ( TS_OverrideMethod . suite ( ) ) ; suite . addTest ( TS_PushDown . suite ( ) ) ; suite . addTest ( TS_RenameLocal . suite ( ) ) ; suite . addTest ( TS_Util . suite ( ) ) ; suite . addTest ( TS_ClassNodeProvider . suite ( ) ) ; suite . addTest ( TS_LocalToField . suite ( ) ) ; suite . addTest ( TS_Core . suite ( ) ) ; suite . addTest ( TS_ExtractMethod . suite ( ) ) ; suite . addTest ( TS_ExtractConstant . suite ( ) ) ; suite . addTest ( TS_MergeWithExternalClassParts . suite ( ) ) ; suite . addTest ( TS_MergeClassPartsInFile . suite ( ) ) ; suite . addTest ( TS_InlineLocal . suite ( ) ) ; suite . addTest ( TS_SplitLocal . suite ( ) ) ; suite . addTest ( TS_EncapsulateField . suite ( ) ) ; suite . addTest ( TS_InlineMethod . suite ( ) ) ; suite . addTest ( TS_RenameField . suite ( ) ) ; suite . addTest ( TS_RenameClass . suite ( ) ) ; suite . addTest ( TS_RenameMethod . suite ( ) ) ; suite . addTest ( TS_RenameModule . suite ( ) ) ; suite . addTest ( TS_InlineClass . suite ( ) ) ; suite . addTest ( TS_MoveMethod . suite ( ) ) ; suite . addTest ( TS_MoveField . suite ( ) ) ; suite . addTest ( TS_Rename . suite ( ) ) ; suite . addTest ( TS_NodeWrapper . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . refactoring . tests ; import java . io . File ; import java . io . IOException ; import java . lang . reflect . Constructor ; import java . lang . reflect . InvocationTargetException ; import junit . framework . TestSuite ; public class FileTestSuite extends TestSuite { protected static String getTestName ( File f ) { return f . getName ( ) . substring ( , f . getName ( ) . indexOf ( '' ) ) ; } protected static TestSuite createSuite ( String name , String pattern , Class < ? extends RefactoringTestCase > klass ) { TestSuite suite = new TestSuite ( name ) ; try { for ( File file : TestsPlugin . getFiles ( pattern ) ) { try { Constructor < ? extends RefactoringTestCase > constructor = klass . getConstructor ( new Class [ ] { String . class } ) ; suite . addTest ( constructor . newInstance ( getTestName ( file ) ) ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; } return suite ; } } package org . rubypeople . rdt . refactoring . tests ; import java . util . ArrayList ; import java . util . Collection ; import java . util . StringTokenizer ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . text . edits . MalformedTreeException ; import org . rubypeople . rdt . refactoring . editprovider . EditAndTreeContentProvider ; import org . rubypeople . rdt . refactoring . exception . UnknownClassNameException ; import org . rubypeople . rdt . refactoring . ui . CheckableItem ; import org . rubypeople . rdt . refactoring . ui . IChildrenProvider ; import org . rubypeople . rdt . refactoring . ui . IItemSelectionReceiver ; public abstract class TwoLayerTreeEditProviderTester extends RefactoringTestCase { private EditAndTreeContentProvider provider ; private Collection < ItemSelection > selections ; private boolean autoCheckChildrenOnParentCheck ; public TwoLayerTreeEditProviderTester ( String fileName , boolean autoCheckChildrenOnParentCheck ) { super ( fileName ) ; this . autoCheckChildrenOnParentCheck = autoCheckChildrenOnParentCheck ; selections = new ArrayList < ItemSelection > ( ) ; } protected void check ( EditAndTreeContentProvider provider , String document , String expectedDocument ) { this . provider = provider ; setSelections ( ) ; try { createEditAndCompareResult ( document , expectedDocument , provider ) ; } catch ( MalformedTreeException e ) { fail ( ) ; } catch ( BadLocationException e ) { fail ( ) ; } } protected void addSelection ( String className ) { addSelection ( className , null ) ; } protected void addSelection ( String className , String childName ) { selections . add ( new ItemSelection ( className , childName ) ) ; } private void setSelections ( ) { assertNotNull ( provider . getElements ( null ) ) ; if ( provider instanceof IItemSelectionReceiver ) { IItemSelectionReceiver itemSelectionReceiver = ( IItemSelectionReceiver ) provider ; setSelections ( itemSelectionReceiver ) ; } else { selectCheckableItems ( ) ; } } private void selectCheckableItems ( ) { for ( ItemSelection selection : selections ) { selectChekableItem ( selection ) ; } } private void selectChekableItem ( ItemSelection selection ) { for ( Object aktClass : provider . getElements ( null ) ) { if ( aktClass . toString ( ) . equals ( selection . getClassName ( ) ) ) { ( ( CheckableItem ) aktClass ) . setChecked ( true ) ; if ( selection . hasChild ( ) && autoCheckChildrenOnParentCheck ) selectChild ( ( IChildrenProvider ) aktClass , selection . getChildName ( ) ) ; break ; } } } private void setSelections ( IItemSelectionReceiver itemSelectionReceiver ) { Collection < Object > selectedObjects = new ArrayList < Object > ( ) ; try { for ( ItemSelection selection : selections ) { Object klass = getClass ( selection . getClassName ( ) ) ; selectedObjects . add ( klass ) ; if ( selection . hasChild ( ) ) { selectedObjects . add ( getSelectedObject ( selection . getClassName ( ) , selection . getChildName ( ) ) ) ; } else if ( autoCheckChildrenOnParentCheck ) { addAllClassChilds ( selectedObjects , selection , klass ) ; } } } catch ( UnknownClassNameException e ) { e . printStackTrace ( ) ; fail ( ) ; } itemSelectionReceiver . setSelectedItems ( selectedObjects . toArray ( ) ) ; } private Object getSelectedObject ( String className , String childName ) throws UnknownClassNameException { Object klass = getClass ( className ) ; StringTokenizer tokanizer = new StringTokenizer ( childName ) ; childName = tokanizer . nextToken ( ) ; for ( Object child : provider . getChildren ( klass ) ) { tokanizer = new StringTokenizer ( child . toString ( ) ) ; String methodName = tokanizer . nextToken ( ) ; if ( methodName . equals ( childName ) ) { return child ; } } throw new UnknownClassNameException ( ) ; } private void addAllClassChilds ( Collection < Object > selectedObjects , ItemSelection selection , Object klass ) throws UnknownClassNameException { Object [ ] childs = provider . getChildren ( klass ) ; for ( Object child : childs ) { selectedObjects . add ( getSelectedObject ( selection . getClassName ( ) , child . toString ( ) ) ) ; } } private Object getClass ( String className ) throws UnknownClassNameException { for ( Object object : provider . getElements ( null ) ) { if ( object . toString ( ) . equals ( className ) ) return object ; } throw new UnknownClassNameException ( ) ; } private void selectChild ( IChildrenProvider klass , String childName ) { for ( Object child : provider . getChildren ( klass ) ) { if ( child . toString ( ) . equals ( childName ) ) { ( ( CheckableItem ) child ) . setChecked ( true ) ; } } } protected void createEditAndCompareResult ( String document , String expectedDocument , EditAndTreeContentProvider provider ) throws MalformedTreeException , BadLocationException { this . provider = provider ; setSelections ( ) ; super . createEditAndCompareResult ( document , expectedDocument , provider ) ; } private static class ItemSelection { private String className ; private String childName ; public ItemSelection ( String className , String childName ) { this . className = className ; this . childName = childName ; } public String getClassName ( ) { return className ; } public String getChildName ( ) { return childName ; } public boolean hasChild ( ) { return childName != null && ! childName . equals ( "" ) ; } } } package org . rubypeople . rdt . refactoring . tests ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Properties ; import org . rubypeople . rdt . refactoring . documentprovider . DocumentProvider ; public abstract class FilePropertyData extends DocumentProvider { protected Properties properties ; public FilePropertyData ( String fileName ) throws FileNotFoundException , IOException { if ( TestsPlugin . getFile ( fileName ) != null ) { properties = initProperties ( fileName ) ; } } public static Properties initProperties ( String propertyFileName ) throws FileNotFoundException , IOException { Properties properties = new Properties ( ) ; FileInputStream fileInputStream = null ; try { fileInputStream = new FileInputStream ( TestsPlugin . getFile ( propertyFileName ) ) ; properties . load ( fileInputStream ) ; } finally { if ( fileInputStream != null ) fileInputStream . close ( ) ; } return properties ; } public static boolean getBoolValue ( String value ) { return "" . equalsIgnoreCase ( value ) || "" . equalsIgnoreCase ( value ) ; } public boolean hasProperty ( String propertyName ) { return properties . containsKey ( propertyName ) ; } public String getProperty ( String propertyName ) { return properties . getProperty ( propertyName ) ; } public boolean getBoolProperty ( String propertyName ) { return getBoolValue ( properties . getProperty ( propertyName ) ) ; } public static String [ ] seperateString ( String value ) { return value . split ( "" ) ; } public int getIntProperty ( String propertyName ) { if ( hasProperty ( propertyName ) ) { return Integer . parseInt ( properties . getProperty ( propertyName ) ) ; } return ; } public String [ ] getCommaSeparatedStringArray ( String propertyName ) { return seperateString ( properties . getProperty ( propertyName ) ) ; } public int [ ] getCommaSeparatedIntArray ( String propertyName ) { String [ ] strings = properties . getProperty ( propertyName ) . split ( "" ) ; int [ ] ints = new int [ strings . length ] ; for ( int i = ; i < strings . length ; i ++ ) { ints [ i ] = Integer . parseInt ( strings [ i ] ) ; } return ints ; } public Collection < String > getNumberedProperty ( String propertyName ) { Collection < String > properties = new ArrayList < String > ( ) ; int propCount = ; while ( hasProperty ( propertyName + propCount ) ) { properties . add ( getProperty ( propertyName + propCount ) ) ; propCount ++ ; } return properties ; } } package org . rubypeople . rdt . refactoring . tests ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collection ; import java . util . StringTokenizer ; import org . jruby . ast . Node ; import org . rubypeople . rdt . refactoring . util . FileHelper ; public class MultiFileTestData extends FilePropertyData { private String testName ; private String sourceSuffix ; private String resultSuffix ; public MultiFileTestData ( String testName ) throws FileNotFoundException , IOException { this ( testName + "" , "" , "" , testName + "" ) ; } public MultiFileTestData ( String testName , String sourceSuffix , String resultSuffix , String propertyFile ) throws FileNotFoundException , IOException { super ( propertyFile ) ; this . testName = testName ; this . sourceSuffix = sourceSuffix ; this . resultSuffix = resultSuffix ; } public String getFileContent ( String fileName ) { String sourceName = getSourceName ( fileName ) ; return FileHelper . getFileContent ( TestsPlugin . getFile ( sourceName ) ) ; } public String getSource ( String fileName ) { return getFileContent ( fileName ) ; } public String getSourceName ( String fileName ) { return testName + fileName + sourceSuffix ; } public String getResult ( String fileName ) { return FileHelper . getFileContent ( TestsPlugin . getFile ( getResultName ( fileName ) ) ) ; } public String getResultName ( String fileName ) { return testName + fileName + resultSuffix ; } public String getActiveFileName ( ) { return properties . getProperty ( "" ) ; } public String [ ] getIncludedFileNames ( ) { ArrayList < String > destFileNames = new ArrayList < String > ( ) ; if ( ! hasProperty ( "" ) ) { return new String [ ] ; } String destFilesProperty = properties . getProperty ( "" ) ; StringTokenizer tokenizer = new StringTokenizer ( destFilesProperty , "" , false ) ; while ( tokenizer . hasMoreElements ( ) ) { String destFile = tokenizer . nextToken ( ) ; destFileNames . add ( destFile . trim ( ) ) ; } return destFileNames . toArray ( new String [ ] ) ; } public String getActiveFileContent ( ) { return getFileContent ( getActiveFileName ( ) ) ; } public Collection < String > getFileNames ( ) { ArrayList < String > files = new ArrayList < String > ( ) ; files . add ( properties . getProperty ( "" ) ) ; files . addAll ( Arrays . asList ( getIncludedFileNames ( ) ) ) ; return files ; } @ Override public Collection < Node > getAllNodes ( ) { ArrayList < Node > allNodes = new ArrayList < Node > ( ) ; for ( String currentFileName : getFileNames ( ) ) { allNodes . addAll ( getAllNodes ( currentFileName ) ) ; } return allNodes ; } } package org . rubypeople . rdt . debug . ui . tests ; import org . rubypeople . rdt . internal . debug . ui . TS_InternalDebugUi ; import org . rubypeople . rdt . internal . debug . ui . launcher . TS_InternalDebugUiLauncher ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_DebugUi { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( TS_InternalDebugUi . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . debug . ui . tests ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . Plugin ; import org . eclipse . ui . plugin . AbstractUIPlugin ; public class RdtDebugUiTestsPlugin extends AbstractUIPlugin { private static RdtDebugUiTestsPlugin plugin ; public RdtDebugUiTestsPlugin ( ) { super ( ) ; plugin = this ; } public static Plugin getDefault ( ) { return plugin ; } public static IWorkspace getWorkspace ( ) { return ResourcesPlugin . getWorkspace ( ) ; } } package org . rubypeople . rdt . internal . debug . ui ; import java . io . ByteArrayInputStream ; import java . io . File ; import junit . framework . TestCase ; import org . eclipse . core . internal . resources . Project ; import org . eclipse . core . internal . resources . Workspace ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . internal . core . LaunchConfiguration ; import org . eclipse . debug . internal . core . LaunchConfigurationWorkingCopy ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . PartInitException ; import org . eclipse . ui . PlatformUI ; import org . rubypeople . rdt . internal . debug . core . model . RubyStackFrame ; import org . rubypeople . rdt . internal . debug . core . model . RubyThread ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class TC_RubySourceLocator extends TestCase { public TC_RubySourceLocator ( String name ) { super ( name ) ; } protected void setUp ( ) { } public void testWorkspaceInternalFile ( ) throws Exception { createProject ( "" ) ; createEmptyFile ( "" ) ; String fullPath = getWorkspaceRoot ( ) . getLocation ( ) . toOSString ( ) + File . separator + "" ; RubyStackFrame rubyStackFrame = new RubyStackFrame ( new RubyThread ( null , , "" ) , fullPath , , ) ; assertCanOpen ( rubyStackFrame ) ; } public void testWorkspaceExternalFile ( ) throws Exception { File tmpFile = File . createTempFile ( "" , null ) ; RubyStackFrame rubyStackFrame = new RubyStackFrame ( new RubyThread ( null , , "" ) , tmpFile . getAbsolutePath ( ) , , ) ; assertCanOpen ( rubyStackFrame ) ; createProject ( "" ) ; RubySourceLocator sourceLocator = new RubySourceLocator ( ) ; LaunchConfigurationWorkingCopy configuration = new LaunchConfigurationWorkingCopy ( null , "" , null ) { } ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , getWorkspaceRoot ( ) . getLocation ( ) . toOSString ( ) + File . separator + "" ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , "" ) ; sourceLocator . initializeDefaults ( configuration ) ; assertCanOpen ( sourceLocator , rubyStackFrame ) ; String workspacePath = getWorkspaceRoot ( ) . getLocation ( ) . toOSString ( ) ; File externalFile = new File ( workspacePath + File . separator + "" ) ; assertTrue ( externalFile . createNewFile ( ) ) ; rubyStackFrame = new RubyStackFrame ( new RubyThread ( null , , "" ) , "" , , ) ; assertCanOpen ( sourceLocator , rubyStackFrame ) ; } public void testNotExistingFile ( ) throws Exception { RubyStackFrame rubyStackFrame = new RubyStackFrame ( new RubyThread ( null , , "" ) , "" , , ) ; assertCantOpen ( rubyStackFrame ) ; } public void testTracTicket5158 ( ) throws Exception { final String projectName = "" ; createProject ( projectName ) ; createFolder ( "" + projectName + "" ) ; createFolder ( "" + projectName + "" ) ; createFolder ( "" + projectName + "" ) ; createFolder ( "" + projectName + "" ) ; createEmptyFile ( "" + projectName + "" ) ; String fullPath = "" ; RubyStackFrame rubyStackFrame = new RubyStackFrame ( new RubyThread ( null , , "" ) , fullPath , , ) ; RubySourceLocator sourceLocator = new RubySourceLocator ( ) ; LaunchConfigurationWorkingCopy configuration = new LaunchConfigurationWorkingCopy ( null , "" , null ) { } ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , getWorkspaceRoot ( ) . getLocation ( ) . toOSString ( ) + File . separator + projectName ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , projectName ) ; sourceLocator . initializeDefaults ( configuration ) ; assertCanOpen ( sourceLocator , rubyStackFrame ) ; } private void assertCanOpen ( RubyStackFrame rubyStackFrame ) throws PartInitException { assertCanOpen ( new RubySourceLocator ( ) , rubyStackFrame ) ; } private void assertCanOpen ( RubySourceLocator sourceLocator , RubyStackFrame rubyStackFrame ) throws PartInitException { Object sourceElement = sourceLocator . getSourceElement ( rubyStackFrame ) ; IEditorInput input = sourceLocator . getEditorInput ( sourceElement ) ; assertNotNull ( input ) ; assertTrue ( input . exists ( ) ) ; PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . openEditor ( input , sourceLocator . getEditorId ( input , sourceElement ) ) ; } private void assertCantOpen ( RubyStackFrame rubyStackFrame ) { RubySourceLocator sourceLocator = new RubySourceLocator ( ) ; Object sourceElement = sourceLocator . getSourceElement ( rubyStackFrame ) ; IEditorInput input = sourceLocator . getEditorInput ( sourceElement ) ; assertNull ( input ) ; } private IFile createEmptyFile ( String path ) throws CoreException { IFile file = getWorkspaceRoot ( ) . getFile ( new Path ( path ) ) ; file . create ( new ByteArrayInputStream ( new byte [ ] ) , true , null ) ; return file ; } private IWorkspaceRoot getWorkspaceRoot ( ) { return RdtDebugUiPlugin . getWorkspace ( ) . getRoot ( ) ; } private Project createProject ( String name ) throws CoreException { Workspace workspace = ( Workspace ) RdtDebugUiPlugin . getWorkspace ( ) ; Project p = new TestProject ( "" + name , workspace ) ; p . create ( null ) ; p . open ( null ) ; return p ; } private IFolder createFolder ( String path ) throws CoreException { IFolder folder = getWorkspaceRoot ( ) . getFolder ( new Path ( path ) ) ; folder . create ( true , true , null ) ; return folder ; } public class TestProject extends Project { public TestProject ( String aName , Workspace aWorkspace ) { super ( new Path ( aName ) , aWorkspace ) ; } } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . debug . core . ILaunch ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . model . ILaunchConfigurationDelegate ; public class ShamApplicationLaunchConfigurationDelegate implements ILaunchConfigurationDelegate { private static int launches ; public void launch ( ILaunchConfiguration configuration , String mode , ILaunch launch , IProgressMonitor monitor ) throws CoreException { launches += ; } public static int getLaunches ( ) { return launches ; } public static void resetLaunches ( ) { launches = ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_InternalDebugUiLauncher { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_RubyArgumentsTab . class ) ; suite . addTestSuite ( TC_RubyApplicationShortcut . class ) ; suite . addTestSuite ( TC_RubyEntryPointTab . class ) ; suite . addTestSuite ( TC_RubyEnvironmentTab . class ) ; return suite ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import java . io . File ; import java . util . HashSet ; import java . util . Set ; import junit . framework . Assert ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . debug . core . DebugPlugin ; import org . eclipse . debug . core . ILaunchConfiguration ; import org . eclipse . debug . core . ILaunchConfigurationType ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . debug . core . ILaunchManager ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . ui . IEditorInput ; import org . eclipse . ui . IEditorPart ; import org . eclipse . ui . PlatformUI ; import org . eclipse . ui . part . FileEditorInput ; import org . rubypeople . rdt . core . IRubyElement ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; import org . rubypeople . rdt . debug . ui . RdtDebugUiConstants ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiPlugin ; import org . rubypeople . rdt . internal . debug . ui . RubySourceLocator ; import org . rubypeople . rdt . internal . launching . RubyLaunchConfigurationAttribute ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; import org . rubypeople . rdt . launching . IVMInstall ; import org . rubypeople . rdt . launching . IVMInstallType ; import org . rubypeople . rdt . launching . RubyRuntime ; import org . rubypeople . rdt . launching . VMStandin ; import org . rubypeople . rdt . ui . RubyUI ; public class TC_RubyApplicationShortcut extends ModifyingResourceTest { private static final String VM_TYPE_ID = "" ; protected ShamRubyApplicationShortcut shortcut ; protected IFile rubyFile , nonRubyFile ; private static String SHAM_LAUNCH_CONFIG_TYPE = "" ; private Set configurations = new HashSet ( ) ; public TC_RubyApplicationShortcut ( String name ) { super ( name ) ; } protected ILaunchConfiguration createConfiguration ( IFile pFile ) { ILaunchConfiguration config = null ; try { ILaunchConfigurationType configType = DebugPlugin . getDefault ( ) . getLaunchManager ( ) . getLaunchConfigurationType ( SHAM_LAUNCH_CONFIG_TYPE ) ; ILaunchConfigurationWorkingCopy wc = configType . newInstance ( null , pFile . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , pFile . getProject ( ) . getName ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , pFile . getProjectRelativePath ( ) . toString ( ) ) ; wc . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , "" ) ; wc . setAttribute ( RubyLaunchConfigurationAttribute . SELECTED_INTERPRETER , RubyRuntime . getCompositeIdFromVM ( RubyRuntime . getDefaultVMInstall ( ) ) ) ; wc . setAttribute ( ILaunchConfiguration . ATTR_SOURCE_LOCATOR_ID , RdtDebugUiConstants . RUBY_SOURCE_LOCATOR ) ; config = wc . doSave ( ) ; } catch ( CoreException ce ) { } return config ; } protected ILaunchConfiguration [ ] getLaunchConfigurations ( ) throws CoreException { return ( ILaunchConfiguration [ ] ) configurations . toArray ( new ILaunchConfiguration [ configurations . size ( ) ] ) ; } private IVMInstallType vmType ; private IVMInstall vm ; protected void setUp ( ) throws Exception { super . setUp ( ) ; shortcut = new ShamRubyApplicationShortcut ( ) ; createRubyProject ( "" ) ; createFolder ( "" ) ; nonRubyFile = createFile ( "" , "" ) ; rubyFile = createFile ( "" , "" ) ; ILaunchConfiguration [ ] configs = this . getLaunchConfigurations ( ) ; for ( int i = ; i < configs . length ; i ++ ) { configs [ i ] . delete ( ) ; } Assert . assertEquals ( "" , , this . getLaunchConfigurations ( ) . length ) ; ShamApplicationLaunchConfigurationDelegate . resetLaunches ( ) ; vmType = RubyRuntime . getVMInstallType ( VM_TYPE_ID ) ; VMStandin standin = new VMStandin ( vmType , "" ) ; IFolder location = createFolder ( "" ) ; createFolder ( "" ) ; createFolder ( "" ) ; createFile ( "" , "" ) ; standin . setInstallLocation ( location . getLocation ( ) . toFile ( ) ) ; standin . setName ( "" ) ; vm = standin . convertToRealVM ( ) ; RubyRuntime . setDefaultVMInstall ( vm , null , true ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; vmType . disposeVMInstall ( vm . getId ( ) ) ; deleteProject ( "" ) ; configurations . clear ( ) ; } public void testNoInterpreterInstalled ( ) throws Exception { vmType . disposeVMInstall ( vm . getId ( ) ) ; RubyRuntime . setDefaultVMInstall ( null , null , true ) ; ISelection selection = new StructuredSelection ( rubyFile ) ; shortcut . launch ( selection , ILaunchManager . RUN_MODE ) ; assertTrue ( "" , shortcut . didShowDialog ) ; } public void testLaunchWithSelectedRubyFile ( ) throws Exception { ISelection selection = new StructuredSelection ( rubyFile ) ; shortcut . launch ( selection , ILaunchManager . RUN_MODE ) ; assertEquals ( "" , , getLaunchConfigurations ( ) . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; assertTrue ( "" , ! shortcut . didLog ( ) ) ; } public void testLaunchWithSelectedNonRubyFile ( ) throws Exception { ISelection selection = new StructuredSelection ( nonRubyFile ) ; shortcut . launch ( selection , ILaunchManager . RUN_MODE ) ; assertEquals ( "" , , this . getLaunchConfigurations ( ) . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; assertTrue ( "" , shortcut . didLog ( ) ) ; } public void testLaunchWithSelectionMultipleConfigurationsExist ( ) throws Exception { createConfiguration ( rubyFile ) ; createConfiguration ( rubyFile ) ; ISelection selection = new StructuredSelection ( rubyFile ) ; shortcut . launch ( selection , ILaunchManager . RUN_MODE ) ; assertEquals ( "" , , this . getLaunchConfigurations ( ) . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; } public void testLaunchWithSelectionMultipleSelections ( ) throws Exception { ISelection selection = new StructuredSelection ( new Object [ ] { rubyFile , createFile ( "" , "" ) } ) ; shortcut . launch ( selection , ILaunchManager . RUN_MODE ) ; ILaunchConfiguration [ ] configurations = this . getLaunchConfigurations ( ) ; assertEquals ( "" , , configurations . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; assertTrue ( "" , ! shortcut . didLog ( ) ) ; String launchedFileName = configurations [ ] . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , "" ) ; assertEquals ( "" , launchedFileName ) ; } public void testLaunchWithSelectionTwice ( ) throws Exception { ISelection selection = new StructuredSelection ( rubyFile ) ; shortcut . launch ( selection , ILaunchManager . RUN_MODE ) ; shortcut . launch ( selection , ILaunchManager . RUN_MODE ) ; assertEquals ( "" , , this . getLaunchConfigurations ( ) . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; assertTrue ( "" , ! shortcut . didLog ( ) ) ; } public void testLaunchWithSelectionWhenFileNamesSameInDifferentDirectory ( ) throws Exception { IFile anotherRubyFileWithSameNameInDifferentFolder = createFile ( "" , "" ) ; ISelection selection = new StructuredSelection ( rubyFile ) ; shortcut . launch ( selection , ILaunchManager . RUN_MODE ) ; ILaunchConfiguration [ ] configurations = this . getLaunchConfigurations ( ) ; assertEquals ( "" , , configurations . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; assertTrue ( "" , ! shortcut . didLog ( ) ) ; String launchedFileName = configurations [ ] . getAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , "" ) ; assertEquals ( "" , launchedFileName ) ; } public void testLaunchFromEditorWithRubyFile ( ) throws Exception { IFile file = createFile ( "" , "" ) ; RubySourceLocator sourceLocator = new RubySourceLocator ( ) ; String fullPath = RdtDebugUiPlugin . getWorkspace ( ) . getRoot ( ) . getLocation ( ) . toOSString ( ) + File . separator + file . getFullPath ( ) . toOSString ( ) ; Object sourceElement = sourceLocator . getSourceElement ( fullPath ) ; IEditorInput input = sourceLocator . getEditorInput ( sourceElement ) ; IEditorPart rubyEditor = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . openEditor ( input , RubyUI . ID_RUBY_EDITOR ) ; shortcut . launch ( rubyEditor , ILaunchManager . RUN_MODE ) ; assertEquals ( "" , , this . getLaunchConfigurations ( ) . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; assertTrue ( "" , ! shortcut . didLog ( ) ) ; } public void testLaunchFromEditorWithTxtFile ( ) throws Exception { IFile file = createFile ( "" , "" ) ; IEditorInput input = new FileEditorInput ( file ) ; IEditorPart txtEditor = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . openEditor ( input , "" ) ; shortcut . launch ( txtEditor , ILaunchManager . RUN_MODE ) ; assertEquals ( "" , , this . getLaunchConfigurations ( ) . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; assertTrue ( "" , shortcut . didLog ( ) ) ; } public void testLaunchFromExternalRubyFileEditor ( ) throws Exception { File tmpFile = File . createTempFile ( "" , null ) ; RubySourceLocator sourceLocator = new RubySourceLocator ( ) ; Object sourceElement = sourceLocator . getSourceElement ( tmpFile . getAbsolutePath ( ) ) ; IEditorInput input = sourceLocator . getEditorInput ( sourceElement ) ; IEditorPart rubyExternalEditor = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) . getActivePage ( ) . openEditor ( input , RubyUI . ID_EXTERNAL_EDITOR ) ; shortcut . launch ( rubyExternalEditor , ILaunchManager . RUN_MODE ) ; assertEquals ( "" , , this . getLaunchConfigurations ( ) . length ) ; assertEquals ( "" , , shortcut . launchCount ( ) ) ; assertTrue ( "" , shortcut . didLog ( ) ) ; } protected class ShamRubyApplicationShortcut extends RubyApplicationShortcut { protected boolean didLog ; protected boolean didShowDialog = false ; private boolean expectingException ; private int launches = ; protected void log ( String message ) { didLog = true ; } public void expectException ( ) { expectingException = true ; } protected void log ( Throwable t ) { if ( ! expectingException ) throw new RuntimeException ( "" + t . getMessage ( ) , t ) ; didLog = true ; } protected boolean didLog ( ) { return didLog ; } protected void doLaunch ( IRubyElement rubyElement , String mode ) throws CoreException { ILaunchConfiguration config = findOrCreateLaunchConfiguration ( rubyElement , mode ) ; if ( config != null ) { configurations . add ( config ) ; launches ++ ; } } public int launchCount ( ) { return launches ; } protected ILaunchConfigurationType getRubyLaunchConfigType ( ) { return DebugPlugin . getDefault ( ) . getLaunchManager ( ) . getLaunchConfigurationType ( SHAM_LAUNCH_CONFIG_TYPE ) ; } protected void showNoInterpreterDialog ( ) { didShowDialog = true ; } } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import junit . framework . TestCase ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . rubypeople . eclipse . shams . debug . core . ShamLaunchConfigurationWorkingCopy ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class TC_RubyArgumentsTab extends TestCase { public TC_RubyArgumentsTab ( String name ) { super ( name ) ; } public void testIsValid ( ) { RubyArgumentsTab tab = new RubyArgumentsTab ( ) ; ILaunchConfigurationWorkingCopy configuration = new ShamLaunchConfigurationWorkingCopy ( ) ; String errorMessage = tab . getErrorMessage ( ) ; assertNull ( "" , errorMessage ) ; assertTrue ( "" , ! tab . isValid ( configuration ) ) ; errorMessage = RdtDebugUiMessages . LaunchConfigurationTab_RubyArguments_working_dir_error_message ; assertEquals ( "" , errorMessage , tab . getErrorMessage ( ) ) ; configuration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_WORKING_DIRECTORY , "" ) ; assertTrue ( "" , tab . isValid ( configuration ) ) ; assertNull ( "" , tab . getErrorMessage ( ) ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import junit . framework . TestCase ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . rubypeople . eclipse . shams . debug . core . ShamLaunchConfigurationWorkingCopy ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . internal . debug . ui . launcher . RubyEnvironmentTab ; import org . rubypeople . rdt . internal . launching . RubyLaunchConfigurationAttribute ; public class TC_RubyEnvironmentTab extends TestCase { public TC_RubyEnvironmentTab ( String name ) { super ( name ) ; } public void testIsValid ( ) { RubyEnvironmentTab tab = new RubyEnvironmentTab ( ) ; ILaunchConfigurationWorkingCopy configuration = new ShamLaunchConfigurationWorkingCopy ( ) ; String errorMessage = tab . getErrorMessage ( ) ; assertNull ( "" , errorMessage ) ; assertTrue ( "" , ! tab . isValid ( configuration ) ) ; errorMessage = RdtDebugUiMessages . LaunchConfigurationTab_RubyEnvironment_interpreter_not_selected_error_message ; assertEquals ( "" , errorMessage , tab . getErrorMessage ( ) ) ; configuration . setAttribute ( RubyLaunchConfigurationAttribute . SELECTED_INTERPRETER , "" ) ; assertTrue ( "" , tab . isValid ( configuration ) ) ; assertNull ( "" , tab . getErrorMessage ( ) ) ; } } package org . rubypeople . rdt . internal . debug . ui . launcher ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Path ; import org . eclipse . debug . core . ILaunchConfigurationWorkingCopy ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Display ; import org . rubypeople . eclipse . shams . debug . core . ShamLaunchConfigurationWorkingCopy ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; import org . rubypeople . rdt . internal . debug . ui . RdtDebugUiMessages ; import org . rubypeople . rdt . launching . IRubyLaunchConfigurationConstants ; public class TC_RubyEntryPointTab extends ModifyingResourceTest { private static final String PROJECT_NAME = "" ; private RubyEntryPointTab fTab ; private ILaunchConfigurationWorkingCopy fConfiguration ; public TC_RubyEntryPointTab ( String name ) { super ( name ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; fTab = createTab ( ) ; fConfiguration = new ShamLaunchConfigurationWorkingCopy ( ) ; } public void testEmptyConfigurationIsInvalid ( ) { String errorMessage = fTab . getErrorMessage ( ) ; assertNull ( "" , errorMessage ) ; assertTrue ( "" , ! fTab . isValid ( fConfiguration ) ) ; assertEquals ( "" , RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidProjectSelectionMessage , fTab . getErrorMessage ( ) ) ; } public void testNonexistantProjectIsInvalid ( ) { fConfiguration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , PROJECT_NAME ) ; assertTrue ( "" , ! fTab . isValid ( fConfiguration ) ) ; assertEquals ( "" , RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidProjectSelectionMessage , fTab . getErrorMessage ( ) ) ; } public void testNoFilenameIsInvalid ( ) throws CoreException { try { createRubyProject ( PROJECT_NAME ) ; fConfiguration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , PROJECT_NAME ) ; assertTrue ( "" , ! fTab . isValid ( fConfiguration ) ) ; assertEquals ( "" , RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidFileSelectionMessage , fTab . getErrorMessage ( ) ) ; } finally { deleteProject ( PROJECT_NAME ) ; } } public void testValidConfiguration ( ) throws CoreException { IFile file ; String path = null ; try { IRubyProject project = createRubyProject ( PROJECT_NAME ) ; path = new Path ( PROJECT_NAME ) . append ( "" ) . toPortableString ( ) ; createFile ( path , "" ) ; fConfiguration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , PROJECT_NAME ) ; fConfiguration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , "" ) ; assertTrue ( "" , fTab . isValid ( fConfiguration ) ) ; assertNull ( "" , fTab . getErrorMessage ( ) ) ; } finally { deleteProject ( PROJECT_NAME ) ; if ( path != null ) deleteFile ( path ) ; } } public void testNonexistantFileIsInvalid ( ) throws CoreException { try { createRubyProject ( PROJECT_NAME ) ; fConfiguration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_PROJECT_NAME , PROJECT_NAME ) ; fConfiguration . setAttribute ( IRubyLaunchConfigurationConstants . ATTR_FILE_NAME , "" ) ; assertTrue ( "" , ! fTab . isValid ( fConfiguration ) ) ; assertEquals ( "" , RdtDebugUiMessages . LaunchConfigurationTab_RubyEntryPoint_invalidFileSelectionMessage , fTab . getErrorMessage ( ) ) ; } finally { deleteProject ( PROJECT_NAME ) ; } } private RubyEntryPointTab createTab ( ) { RubyEntryPointTab tab = new RubyEntryPointTab ( ) ; tab . createControl ( new Composite ( Display . getDefault ( ) . getActiveShell ( ) , SWT . NULL ) ) ; return tab ; } } package org . rubypeople . rdt . internal . debug . ui ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_InternalDebugUi { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_RubyConsoleTracker . class ) ; suite . addTestSuite ( TC_RubySourceLocator . class ) ; return suite ; } } package org . rubypeople . rdt . internal . debug . ui ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . eclipse . core . resources . IProject ; import org . eclipse . debug . core . model . IProcess ; import org . eclipse . debug . core . model . IStreamMonitor ; import org . eclipse . debug . core . model . IStreamsProxy ; import org . eclipse . debug . ui . console . IConsole ; import org . eclipse . debug . ui . console . IConsoleHyperlink ; import org . eclipse . jface . text . AbstractDocument ; import org . eclipse . jface . text . DefaultLineTracker ; import org . eclipse . jface . text . GapTextStore ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . ui . console . IOConsoleOutputStream ; import org . eclipse . ui . console . IPatternMatchListener ; import org . rubypeople . rdt . internal . debug . ui . console . RubyConsoleTracker ; import org . rubypeople . rdt . internal . debug . ui . console . RubyStackTraceHyperlink ; import org . rubypeople . rdt . internal . debug . ui . console . RubyConsoleTracker . FileExistanceChecker ; public class TC_RubyConsoleTracker extends TestCase { private static final String SYNTAX_IN_REQUIRE = "" ; private TestConsole console ; private MockFileExistanceChecker fileChecker ; public void setUp ( ) throws Exception { fileChecker = new MockFileExistanceChecker ( ) ; console = new TestConsole ( fileChecker ) ; } public void testCorrect ( ) throws Exception { fileChecker . addKnownFile ( "" ) ; fileChecker . addKnownFile ( "" ) ; console . lineAppend ( "" ) ; console . lineAppend ( "" ) ; console . lineAppend ( "" ) ; console . assertLink ( , , "" , , ) ; console . assertLink ( , , "" , , ) ; console . assertLinkCount ( ) ; } public void testSyntaxErrorInRequire ( ) throws Exception { fileChecker . addKnownFile ( "" ) ; fileChecker . addKnownFile ( "" ) ; console . lineAppend ( SYNTAX_IN_REQUIRE ) ; console . assertLinkCount ( ) ; console . assertLink ( , , "" , , ) ; console . assertLink ( , , "" , , ) ; } public void testSecondWithoutFirst ( ) throws Exception { fileChecker . addKnownFile ( "" ) ; console . lineAppend ( "" ) ; console . assertLink ( , , "" , , ) ; } public void testInCorrect ( ) throws Exception { fileChecker . addKnownFile ( "" ) ; console . lineAppend ( "" ) ; console . lineAppend ( "" ) ; console . assertLinkCount ( ) ; } public void testBackslashesInFilePath ( ) throws Exception { fileChecker . addKnownFile ( "" ) ; console . lineAppend ( "" ) ; console . assertLinkCount ( ) ; console . assertLink ( , , "" , , ) ; } public void testWorkspaceRelativeStartingWithSlash ( ) throws Exception { fileChecker . addKnownFile ( "" ) ; console . lineAppend ( "" ) ; console . assertLinkCount ( ) ; console . assertLink ( , , "" , , ) ; } private final class MockFileExistanceChecker implements RubyConsoleTracker . FileExistanceChecker { private List knownFiles = new ArrayList ( ) ; public void addKnownFile ( String filename ) { knownFiles . add ( filename ) ; } public boolean fileExists ( String filename ) { return knownFiles . contains ( filename ) ; } } public class TestConsole implements IConsole { private class MetaLink { public RubyStackTraceHyperlink link ; public int offset ; public int length ; } private List metaLinks = new ArrayList ( ) ; SimpleDocument doc = new SimpleDocument ( ) ; RubyConsoleTracker tracker ; public TestConsole ( FileExistanceChecker fileChecker ) throws Exception { tracker = new RubyConsoleTracker ( fileChecker ) { @ Override protected IProject getProject ( ) { return null ; } } ; tracker . init ( this ) ; } public void assertLinkCount ( int expectedLinkCount ) { assertEquals ( expectedLinkCount , metaLinks . size ( ) ) ; } public void assertLink ( int expectedOffset , int expectedLength , String expectedFilename , int expectedLineNumber , int linkIndex ) { try { MetaLink metaLink = ( MetaLink ) metaLinks . get ( linkIndex ) ; assertNotNull ( metaLink ) ; assertEquals ( "" + linkIndex + "" , expectedOffset , metaLink . offset ) ; assertEquals ( expectedLength , metaLink . length ) ; assertEquals ( expectedFilename , metaLink . link . getFilename ( ) ) ; assertEquals ( expectedLineNumber , metaLink . link . getLineNumber ( ) ) ; } catch ( IndexOutOfBoundsException e ) { fail ( "" + linkIndex + "" ) ; } } public void addLink ( IConsoleHyperlink pLink , int pOffset , int pLength ) { } public void addLink ( org . eclipse . ui . console . IHyperlink pLink , int pOffset , int pLength ) { MetaLink metaLink = new MetaLink ( ) ; metaLink . link = ( RubyStackTraceHyperlink ) pLink ; metaLink . offset = pOffset ; metaLink . length = pLength ; metaLinks . add ( metaLink ) ; } public void connect ( IStreamMonitor streamMonitor , String streamIdentifer ) { throw new RuntimeException ( "" ) ; } public void connect ( IStreamsProxy streamsProxy ) { throw new RuntimeException ( "" ) ; } public IDocument getDocument ( ) { return doc ; } public IProcess getProcess ( ) { throw new RuntimeException ( "" ) ; } public IRegion getRegion ( IConsole link ) { throw new RuntimeException ( "" ) ; } public void lineAppend ( String pLine ) throws Exception { doc . set ( pLine ) ; tracker . lineAppended ( doc . getLineInformationOfOffset ( ) ) ; } public IRegion getRegion ( IConsoleHyperlink link ) { return null ; } public IRegion getRegion ( org . eclipse . ui . console . IHyperlink link ) { return null ; } public void addPatternMatchListener ( IPatternMatchListener matchListener ) { } public void removePatternMatchListener ( IPatternMatchListener matchListener ) { } public IOConsoleOutputStream getStream ( String streamIdentifier ) { return null ; } } public class SimpleDocument extends AbstractDocument { public SimpleDocument ( ) { this . setTextStore ( new GapTextStore ( , ) ) ; setLineTracker ( new DefaultLineTracker ( ) ) ; completeInitialization ( ) ; } } } package org . rubypeople . rdt . tests . all ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . TS_RdtCore ; import org . rubypeople . rdt . debug . ui . tests . TS_DebugUi ; import org . rubypeople . rdt . internal . launching . TS_InternalLaunching ; import org . rubypeople . rdt . internal . ui . TS_InternalUi ; import org . rubypeople . rdt . refactoring . tests . TS_All ; import com . aptana . rdt . TS_Aptana ; public class TS_RdtAllUnitTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( TS_RdtCore . suite ( ) ) ; suite . addTest ( TS_InternalLaunching . suite ( ) ) ; suite . addTest ( TS_InternalUi . suite ( ) ) ; suite . addTest ( TS_DebugUi . suite ( ) ) ; suite . addTest ( TS_Aptana . suite ( ) ) ; suite . addTest ( TS_All . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . tests . all ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . debug . core . tests . FTS_Debug ; public class TS_RdtAllFunctionalTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( FTS_Debug . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . core . tests . util ; import java . io . File ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; public class Util { private static int DELETE_MAX_TIME = ; public static boolean DELETE_DEBUG = false ; public static int DELETE_MAX_WAIT = ; public static String convertToIndependantLineDelimiter ( String source ) { if ( source . indexOf ( '' ) == - && source . indexOf ( '' ) == - ) return source ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = , length = source . length ( ) ; i < length ; i ++ ) { char car = source . charAt ( i ) ; if ( car == '' ) { buffer . append ( '' ) ; if ( i < length - && source . charAt ( i + ) == '' ) { i ++ ; } } else { buffer . append ( car ) ; } } return buffer . toString ( ) ; } public static boolean delete ( IResource resource ) { try { resource . delete ( true , null ) ; if ( isResourceDeleted ( resource ) ) { return true ; } } catch ( CoreException e ) { } return waitUntilResourceDeleted ( resource ) ; } public static boolean isResourceDeleted ( IResource resource ) { return ! resource . isAccessible ( ) && getParentChildResource ( resource ) == null ; } private static IResource getParentChildResource ( IResource resource ) { IContainer parent = resource . getParent ( ) ; if ( parent == null || ! parent . exists ( ) ) return null ; try { IResource [ ] members = parent . members ( ) ; int length = members == null ? : members . length ; if ( length > ) { for ( int i = ; i < length ; i ++ ) { if ( members [ i ] == resource ) { return members [ i ] ; } else if ( members [ i ] . equals ( resource ) ) { return members [ i ] ; } else if ( members [ i ] . getFullPath ( ) . equals ( resource . getFullPath ( ) ) ) { return members [ i ] ; } } } } catch ( CoreException ce ) { } return null ; } private static boolean waitUntilResourceDeleted ( IResource resource ) { File file = resource . getLocation ( ) . toFile ( ) ; if ( DELETE_DEBUG ) { System . out . println ( ) ; System . out . println ( "" + getTestName ( ) ) ; System . out . println ( "" + resource ) ; printRdtCoreStackTrace ( null , ) ; printFileInfo ( file . getParentFile ( ) , , - ) ; System . out . print ( "" + DELETE_MAX_WAIT + "" ) ; } int count = ; int delay = ; int maxRetry = DELETE_MAX_WAIT / delay ; int time = ; while ( count < maxRetry ) { try { count ++ ; Thread . sleep ( delay ) ; time += delay ; if ( time > DELETE_MAX_TIME ) DELETE_MAX_TIME = time ; if ( DELETE_DEBUG ) System . out . print ( '' ) ; if ( resource . isAccessible ( ) ) { try { resource . delete ( true , null ) ; if ( isResourceDeleted ( resource ) && isFileDeleted ( file ) ) { if ( DELETE_DEBUG ) { System . out . println ( ) ; System . out . println ( "" + time + "" + DELETE_MAX_TIME + "" ) ; System . out . println ( ) ; } return true ; } } catch ( CoreException e ) { } } if ( isResourceDeleted ( resource ) && isFileDeleted ( file ) ) { if ( DELETE_DEBUG ) { System . out . println ( ) ; System . out . println ( "" + time + "" + DELETE_MAX_TIME + "" ) ; System . out . println ( ) ; } return true ; } if ( count >= && delay <= ) { count = ; delay *= ; maxRetry = DELETE_MAX_WAIT / delay ; if ( ( DELETE_MAX_WAIT % delay ) != ) { maxRetry ++ ; } } } catch ( InterruptedException ie ) { break ; } } if ( ! DELETE_DEBUG ) { System . out . println ( ) ; System . out . println ( "" + getTestName ( ) ) ; System . out . println ( "" + resource ) ; printRdtCoreStackTrace ( null , ) ; printFileInfo ( file . getParentFile ( ) , , - ) ; } System . out . println ( ) ; System . out . println ( "" + resource + "" + DELETE_MAX_TIME + "" ) ; System . out . println ( ) ; return false ; } private static String getTestName ( ) { StackTraceElement [ ] elements = new Exception ( ) . getStackTrace ( ) ; int idx = , length = elements . length ; while ( idx < length && ! elements [ idx ++ ] . getClassName ( ) . startsWith ( "" ) ) { } if ( idx < length ) { StackTraceElement testElement = null ; while ( idx < length && elements [ idx ] . getClassName ( ) . startsWith ( "" ) ) { testElement = elements [ idx ++ ] ; } if ( testElement != null ) { return testElement . getClassName ( ) + "" + testElement . getMethodName ( ) ; } } return "" ; } public static boolean isFileDeleted ( File file ) { return ! file . exists ( ) && getParentChildFile ( file ) == null ; } private static File getParentChildFile ( File file ) { File parent = file . getParentFile ( ) ; if ( parent == null || ! parent . exists ( ) ) return null ; File [ ] files = parent . listFiles ( ) ; int length = files == null ? : files . length ; if ( length > ) { for ( int i = ; i < length ; i ++ ) { if ( files [ i ] == file ) { return files [ i ] ; } else if ( files [ i ] . equals ( file ) ) { return files [ i ] ; } else if ( files [ i ] . getPath ( ) . equals ( file . getPath ( ) ) ) { return files [ i ] ; } } } return null ; } private static void printFileInfo ( File file , int indent , int recurse ) { String tab = "" ; for ( int i = ; i < indent ; i ++ ) tab += "" ; System . out . print ( tab + "" + file . getName ( ) + "" ) ; String sep = "" ; if ( file . canRead ( ) ) { System . out . print ( "" ) ; sep = "" ; } if ( file . canWrite ( ) ) { System . out . print ( sep + "" ) ; sep = "" ; } if ( file . exists ( ) ) { System . out . print ( sep + "" ) ; sep = "" ; } if ( file . isDirectory ( ) ) { System . out . print ( sep + "" ) ; sep = "" ; } if ( file . isFile ( ) ) { System . out . print ( sep + "" ) ; sep = "" ; } if ( file . isHidden ( ) ) { System . out . print ( sep + "" ) ; sep = "" ; } System . out . println ( ) ; File [ ] files = file . listFiles ( ) ; int length = files == null ? : files . length ; if ( length > ) { boolean children = recurse < ; System . out . print ( tab + "" ) ; if ( children ) System . out . println ( ) ; for ( int i = ; i < length ; i ++ ) { if ( children ) { printFileInfo ( files [ i ] , indent + , - ) ; } else { if ( i > ) System . out . print ( "" ) ; System . out . print ( files [ i ] . getName ( ) ) ; if ( files [ i ] . isDirectory ( ) ) System . out . print ( "" ) ; else if ( files [ i ] . isFile ( ) ) System . out . print ( "" ) ; else System . out . print ( "" ) ; } } if ( ! children ) System . out . println ( ) ; } if ( recurse > ) { File parent = file . getParentFile ( ) ; if ( parent != null ) printFileInfo ( parent , indent + , recurse - ) ; } } private static void printRdtCoreStackTrace ( Exception exception , int indent ) { String tab = "" ; for ( int i = ; i < indent ; i ++ ) tab += "" ; StackTraceElement [ ] elements = ( exception == null ? new Exception ( ) : exception ) . getStackTrace ( ) ; int idx = , length = elements . length ; while ( idx < length && ! elements [ idx ++ ] . getClassName ( ) . startsWith ( "" ) ) { } if ( idx < length ) { System . out . print ( tab + "" ) ; if ( exception == null ) System . out . println ( "" ) ; else System . out . println ( "" + exception + "" ) ; while ( idx < length && elements [ idx ] . getClassName ( ) . startsWith ( "" ) ) { StackTraceElement testElement = elements [ idx ++ ] ; System . out . println ( tab + "" + testElement ) ; } } else { exception . printStackTrace ( System . out ) ; } } public static String displayString ( String inputString , int indent ) { return displayString ( inputString , indent , false ) ; } public static String displayString ( String inputString ) { return displayString ( inputString , ) ; } public static String displayString ( String inputString , int indent , boolean shift ) { if ( inputString == null ) return "" ; int length = inputString . length ( ) ; StringBuffer buffer = new StringBuffer ( length ) ; java . util . StringTokenizer tokenizer = new java . util . StringTokenizer ( inputString , "" , true ) ; for ( int i = ; i < indent ; i ++ ) buffer . append ( "" ) ; if ( shift ) indent ++ ; buffer . append ( "" ) ; while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) ; if ( token . equals ( "" ) ) { buffer . append ( "" ) ; if ( tokenizer . hasMoreTokens ( ) ) { token = tokenizer . nextToken ( ) ; if ( token . equals ( "" ) ) { buffer . append ( "" ) ; if ( tokenizer . hasMoreTokens ( ) ) { buffer . append ( "" ) ; for ( int i = ; i < indent ; i ++ ) buffer . append ( "" ) ; buffer . append ( "" ) ; } continue ; } buffer . append ( "" ) ; for ( int i = ; i < indent ; i ++ ) buffer . append ( "" ) ; buffer . append ( "" ) ; } else { continue ; } } else if ( token . equals ( "" ) ) { buffer . append ( "" ) ; if ( tokenizer . hasMoreTokens ( ) ) { buffer . append ( "" ) ; for ( int i = ; i < indent ; i ++ ) buffer . append ( "" ) ; buffer . append ( "" ) ; } continue ; } StringBuffer tokenBuffer = new StringBuffer ( ) ; for ( int i = ; i < token . length ( ) ; i ++ ) { char c = token . charAt ( i ) ; switch ( c ) { case '' : tokenBuffer . append ( "" ) ; break ; case '' : tokenBuffer . append ( "" ) ; break ; case '' : tokenBuffer . append ( "" ) ; break ; case '' : tokenBuffer . append ( "" ) ; break ; case '' : tokenBuffer . append ( "" ) ; break ; case '' : tokenBuffer . append ( "" ) ; break ; case '' : tokenBuffer . append ( "" ) ; break ; case '' : tokenBuffer . append ( "" ) ; break ; default : tokenBuffer . append ( c ) ; } } buffer . append ( tokenBuffer . toString ( ) ) ; } buffer . append ( "" ) ; return buffer . toString ( ) ; } public static boolean delete ( File file ) { if ( file . isDirectory ( ) ) { flushDirectoryContent ( file ) ; } file . delete ( ) ; if ( isFileDeleted ( file ) ) { return true ; } return waitUntilFileDeleted ( file ) ; } public static void flushDirectoryContent ( File dir ) { File [ ] files = dir . listFiles ( ) ; if ( files == null ) return ; for ( int i = , max = files . length ; i < max ; i ++ ) { delete ( files [ i ] ) ; } } private static boolean waitUntilFileDeleted ( File file ) { if ( DELETE_DEBUG ) { System . out . println ( ) ; System . out . println ( "" + getTestName ( ) ) ; System . out . println ( "" + file ) ; printRdtCoreStackTrace ( null , ) ; printFileInfo ( file . getParentFile ( ) , , - ) ; System . out . print ( "" + DELETE_MAX_WAIT + "" ) ; } int count = ; int delay = ; int maxRetry = DELETE_MAX_WAIT / delay ; int time = ; while ( count < maxRetry ) { try { count ++ ; Thread . sleep ( delay ) ; time += delay ; if ( time > DELETE_MAX_TIME ) DELETE_MAX_TIME = time ; if ( DELETE_DEBUG ) System . out . print ( '' ) ; if ( file . exists ( ) ) { if ( file . delete ( ) ) { if ( DELETE_DEBUG ) { System . out . println ( ) ; System . out . println ( "" + time + "" + DELETE_MAX_TIME + "" ) ; System . out . println ( ) ; } return true ; } } if ( isFileDeleted ( file ) ) { if ( DELETE_DEBUG ) { System . out . println ( ) ; System . out . println ( "" + time + "" + DELETE_MAX_TIME + "" ) ; System . out . println ( ) ; } return true ; } if ( count >= && delay <= ) { count = ; delay *= ; maxRetry = DELETE_MAX_WAIT / delay ; if ( ( DELETE_MAX_WAIT % delay ) != ) { maxRetry ++ ; } } } catch ( InterruptedException ie ) { break ; } } if ( ! DELETE_DEBUG ) { System . out . println ( ) ; System . out . println ( "" + getTestName ( ) ) ; System . out . println ( "" + file ) ; printRdtCoreStackTrace ( null , ) ; printFileInfo ( file . getParentFile ( ) , , - ) ; } System . out . println ( ) ; System . out . println ( "" + file + "" + DELETE_MAX_TIME + "" ) ; System . out . println ( ) ; return false ; } } package org . rubypeople . rdt . core . tests . model ; import java . util . ArrayList ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . rdt . core . BufferChangedEvent ; import org . rubypeople . rdt . core . IBuffer ; import org . rubypeople . rdt . core . IBufferChangedListener ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; public class BufferTests extends ModifyingResourceTest implements IBufferChangedListener { protected ArrayList events = null ; public BufferTests ( String name ) { super ( name ) ; } public void bufferChanged ( BufferChangedEvent bufferChangedEvent ) { this . events . add ( bufferChangedEvent ) ; } protected IBuffer createBuffer ( String path , String content ) throws CoreException { waitUntilIndexesReady ( ) ; this . createFile ( path , content ) ; IRubyScript cu = this . getRubyScript ( path ) ; IBuffer buffer = cu . getBuffer ( ) ; buffer . addBufferChangedListener ( this ) ; this . events = new ArrayList ( ) ; return buffer ; } protected void deleteBuffer ( IBuffer buffer ) throws CoreException { buffer . removeBufferChangedListener ( this ) ; IResource resource = buffer . getUnderlyingResource ( ) ; if ( resource != null ) { deleteResource ( resource ) ; } } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; try { this . createRubyProject ( "" , new String [ ] { "" } ) ; this . createFolder ( "" ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; this . deleteProject ( "" ) ; } public void testAppend ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { int oldLength = buffer . getLength ( ) ; buffer . append ( "" ) ; assertBufferEvent ( oldLength , , "" ) ; assertSourceEquals ( "" , "" + "" + "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testClose ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { buffer . close ( ) ; assertBufferEvent ( , , null ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testGetUnderlyingResource ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; IRubyScript copy = null ; try { IFile file = this . getFile ( "" ) ; assertEquals ( "" , file , buffer . getUnderlyingResource ( ) ) ; copy = this . getRubyScript ( "" ) . getWorkingCopy ( null ) ; assertEquals ( "" , file , copy . getBuffer ( ) . getUnderlyingResource ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; if ( copy != null ) { copy . discardWorkingCopy ( ) ; } } } public void testDeleteBeginning ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { buffer . replace ( , , "" ) ; assertBufferEvent ( , , null ) ; assertSourceEquals ( "" , "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testDeleteMiddle ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { buffer . replace ( , , "" ) ; assertBufferEvent ( , , null ) ; assertSourceEquals ( "" , "" + "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testDeleteEnd ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { buffer . replace ( , , "" ) ; assertBufferEvent ( , , null ) ; assertSourceEquals ( "" , "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testGetChar ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { assertEquals ( "" , '' , buffer . getChar ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testGetChar2 ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; buffer . close ( ) ; try { assertEquals ( "" , Character . MIN_VALUE , buffer . getChar ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testGetLength ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { assertEquals ( "" , , buffer . getLength ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testGetText ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { assertSourceEquals ( "" , "" , buffer . getText ( , ) ) ; assertSourceEquals ( "" , "" , buffer . getText ( , ) ) ; assertSourceEquals ( "" , "" , buffer . getText ( , ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testInsertBeginning ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { buffer . replace ( , , "" ) ; assertBufferEvent ( , , "" ) ; assertSourceEquals ( "" , "" + "" + "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testReplaceBeginning ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { buffer . replace ( , , "" ) ; assertBufferEvent ( , , "" ) ; assertSourceEquals ( "" , "" + "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testReplaceMiddle ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { buffer . replace ( , , "" ) ; assertBufferEvent ( , , "" ) ; assertSourceEquals ( "" , "" + "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testReplaceEnd ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { int end = buffer . getLength ( ) ; buffer . replace ( end - , , "" ) ; assertBufferEvent ( end - , , "" ) ; assertSourceEquals ( "" , "" + "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testInsertMiddle ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { buffer . replace ( , , "" ) ; assertBufferEvent ( , , "" ) ; assertSourceEquals ( "" , "" + "" + "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } public void testInsertEnd ( ) throws CoreException { IBuffer buffer = this . createBuffer ( "" , "" + "" + "" ) ; try { int end = buffer . getLength ( ) ; buffer . replace ( end , , "" ) ; assertBufferEvent ( end , , "" ) ; assertSourceEquals ( "" , "" + "" + "" + "" , buffer . getContents ( ) ) ; assertTrue ( "" , buffer . hasUnsavedChanges ( ) ) ; } finally { this . deleteBuffer ( buffer ) ; } } protected void assertBufferEvent ( int offset , int length , String text ) { assertTrue ( "" , this . events != null ) ; assertTrue ( "" , ! this . events . isEmpty ( ) ) ; BufferChangedEvent event = ( BufferChangedEvent ) this . events . get ( ) ; assertEquals ( "" , offset , event . getOffset ( ) ) ; assertEquals ( "" , length , event . getLength ( ) ) ; if ( text == null ) { assertTrue ( "" , event . getText ( ) == null ) ; } else { assertSourceEquals ( "" , text , event . getText ( ) ) ; } } protected void assertBufferEvents ( String expected ) { StringBuffer buffer = new StringBuffer ( ) ; if ( this . events == null ) buffer . append ( "" ) ; else { for ( int i = , length = this . events . size ( ) ; i < length ; i ++ ) { BufferChangedEvent event = ( BufferChangedEvent ) this . events . get ( i ) ; buffer . append ( '' ) ; buffer . append ( event . getOffset ( ) ) ; buffer . append ( "" ) ; buffer . append ( event . getLength ( ) ) ; buffer . append ( "" ) ; buffer . append ( event . getText ( ) ) ; if ( i < length - ) buffer . append ( "" ) ; } } assertSourceEquals ( "" , expected , buffer . toString ( ) ) ; } } package org . rubypeople . rdt . core . tests ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . io . InputStream ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . Path ; public abstract class ModifyingResourceTest extends AbstractRubyModelTest { public ModifyingResourceTest ( String name ) { super ( name ) ; } protected IFile editFile ( String path , String content ) throws CoreException { IFile file = this . getFile ( path ) ; InputStream input = new ByteArrayInputStream ( content . getBytes ( ) ) ; file . setContents ( input , IResource . FORCE , null ) ; return file ; } protected IFolder createFolder ( String path ) throws CoreException { return createFolder ( new Path ( path ) ) ; } protected IFile createFile ( String path , String content ) throws CoreException { return createFile ( path , content . getBytes ( ) ) ; } protected IFile createFile ( String path , byte [ ] content ) throws CoreException { return createFile ( path , new ByteArrayInputStream ( content ) ) ; } protected IFile createFile ( String path , InputStream content ) throws CoreException { IFile file = getFile ( path ) ; file . create ( content , true , null ) ; try { content . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return file ; } protected void deleteFile ( String filePath ) throws CoreException { deleteResource ( this . getFile ( filePath ) ) ; } protected void deleteFolder ( String folderPath ) throws CoreException { deleteFolder ( new Path ( folderPath ) ) ; } } package org . rubypeople . rdt . core . tests ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . net . URL ; import junit . framework . TestCase ; import org . eclipse . core . resources . IContainer ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IFolder ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IProjectDescription ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IStorage ; import org . eclipse . core . resources . IWorkspace ; import org . eclipse . core . resources . IWorkspaceDescription ; import org . eclipse . core . resources . IWorkspaceRoot ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . FileLocator ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Path ; import org . eclipse . core . runtime . Platform ; import org . eclipse . core . runtime . jobs . Job ; import org . rubypeople . rdt . core . ILoadpathEntry ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . ISourceFolder ; import org . rubypeople . rdt . core . ISourceFolderRoot ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . RubyModelException ; import org . rubypeople . rdt . internal . core . LoadpathEntry ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import org . rubypeople . rdt . internal . core . util . Util ; public abstract class AbstractRubyModelTest extends TestCase { protected IRubyProject currentProject ; protected String endChar = "" ; public AbstractRubyModelTest ( String name ) { super ( name ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; IWorkspaceDescription description = getWorkspace ( ) . getDescription ( ) ; if ( description . isAutoBuilding ( ) ) { description . setAutoBuilding ( false ) ; getWorkspace ( ) . setDescription ( description ) ; } } protected IRubyProject setUpRubyProject ( final String projectName ) throws CoreException , IOException { this . currentProject = setUpRubyProject ( projectName , "" ) ; return this . currentProject ; } protected String getPluginDirectoryPath ( ) { try { URL platformURL = Platform . getBundle ( "" ) . getEntry ( "" ) ; return new File ( FileLocator . toFileURL ( platformURL ) . getFile ( ) ) . getAbsolutePath ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return null ; } public String getSourceWorkspacePath ( ) { return getPluginDirectoryPath ( ) + java . io . File . separator + "" ; } public IWorkspace getWorkspace ( ) { return ResourcesPlugin . getWorkspace ( ) ; } public IWorkspaceRoot getWorkspaceRoot ( ) { return getWorkspace ( ) . getRoot ( ) ; } public void copy ( File src , File dest ) throws IOException { byte [ ] srcBytes = this . read ( src ) ; if ( convertToIndependantLineDelimiter ( src ) ) { String contents = new String ( srcBytes ) ; contents = org . rubypeople . rdt . core . tests . util . Util . convertToIndependantLineDelimiter ( contents ) ; srcBytes = contents . getBytes ( ) ; } FileOutputStream out = new FileOutputStream ( dest ) ; out . write ( srcBytes ) ; out . close ( ) ; } public byte [ ] read ( java . io . File file ) throws java . io . IOException { int fileLength ; byte [ ] fileBytes = new byte [ fileLength = ( int ) file . length ( ) ] ; java . io . FileInputStream stream = new java . io . FileInputStream ( file ) ; int bytesRead = ; int lastReadSize = ; while ( ( lastReadSize != - ) && ( bytesRead != fileLength ) ) { lastReadSize = stream . read ( fileBytes , bytesRead , fileLength - bytesRead ) ; bytesRead += lastReadSize ; } stream . close ( ) ; return fileBytes ; } public boolean convertToIndependantLineDelimiter ( File file ) { return file . getName ( ) . endsWith ( "" ) || file . getName ( ) . endsWith ( "" ) ; } protected void copyDirectory ( File source , File target ) throws IOException { if ( ! target . exists ( ) ) { target . mkdirs ( ) ; } File [ ] files = source . listFiles ( ) ; if ( files == null ) return ; for ( int i = ; i < files . length ; i ++ ) { File sourceChild = files [ i ] ; String name = sourceChild . getName ( ) ; if ( name . equals ( "" ) ) continue ; File targetChild = new File ( target , name ) ; if ( sourceChild . isDirectory ( ) ) { copyDirectory ( sourceChild , targetChild ) ; } else { copy ( sourceChild , targetChild ) ; } } } protected IRubyProject setUpRubyProject ( final String projectName , String compliance ) throws CoreException , IOException { String sourceWorkspacePath = getSourceWorkspacePath ( ) ; String targetWorkspacePath = getWorkspaceRoot ( ) . getLocation ( ) . toFile ( ) . getCanonicalPath ( ) ; copyDirectory ( new File ( sourceWorkspacePath , projectName ) , new File ( targetWorkspacePath , projectName ) ) ; final IProject project = getWorkspaceRoot ( ) . getProject ( projectName ) ; IWorkspaceRunnable populate = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { project . create ( null ) ; project . open ( null ) ; } } ; getWorkspace ( ) . run ( populate , null ) ; IRubyProject rubyProject = RubyCore . create ( project ) ; return rubyProject ; } protected void deleteProjects ( final String [ ] projectNames ) throws CoreException { ResourcesPlugin . getWorkspace ( ) . run ( new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { if ( projectNames != null ) { for ( int i = , max = projectNames . length ; i < max ; i ++ ) { if ( projectNames [ i ] != null ) deleteProject ( projectNames [ i ] ) ; } } } } , null ) ; } protected void deleteProject ( String projectName ) throws CoreException { IProject project = this . getProject ( projectName ) ; if ( project . exists ( ) && ! project . isOpen ( ) ) { project . open ( null ) ; } deleteResource ( project ) ; } public void deleteResource ( IResource resource ) throws CoreException { int retryCount = ; while ( ++ retryCount <= ) { if ( ! org . rubypeople . rdt . core . tests . util . Util . delete ( resource ) ) { System . gc ( ) ; } } } protected IProject getProject ( String project ) { return getWorkspaceRoot ( ) . getProject ( project ) ; } public static void waitForAutoBuild ( ) { boolean wasInterrupted = false ; do { try { Job . getJobManager ( ) . join ( ResourcesPlugin . FAMILY_AUTO_BUILD , null ) ; wasInterrupted = false ; } catch ( OperationCanceledException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { wasInterrupted = true ; } } while ( wasInterrupted ) ; } protected void assertResourcesEqual ( String message , String expected , Object [ ] resources ) { sortResources ( resources ) ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = , length = resources . length ; i < length ; i ++ ) { if ( resources [ i ] instanceof IResource ) { buffer . append ( ( ( IResource ) resources [ i ] ) . getFullPath ( ) . toString ( ) ) ; } else if ( resources [ i ] instanceof IStorage ) { buffer . append ( ( ( IStorage ) resources [ i ] ) . getFullPath ( ) . toString ( ) ) ; } else if ( resources [ i ] == null ) { buffer . append ( "" ) ; } if ( i != length - ) buffer . append ( "" ) ; } if ( ! expected . equals ( buffer . toString ( ) ) ) { System . out . print ( org . rubypeople . rdt . core . tests . util . Util . displayString ( buffer . toString ( ) , ) ) ; System . out . println ( this . endChar ) ; } assertEquals ( message , expected , buffer . toString ( ) ) ; } protected void sortResources ( Object [ ] resources ) { Util . Comparer comparer = new Util . Comparer ( ) { public int compare ( Object a , Object b ) { IResource resourceA = ( IResource ) a ; IResource resourceB = ( IResource ) b ; return resourceA . getFullPath ( ) . toString ( ) . compareTo ( resourceB . getFullPath ( ) . toString ( ) ) ; } } ; Util . sort ( resources , comparer ) ; } protected IFile getFile ( String path ) { return getWorkspaceRoot ( ) . getFile ( new Path ( path ) ) ; } protected IRubyProject createRubyProject ( String projectName ) throws CoreException { return this . createRubyProject ( projectName , new String [ ] { "" } , new String [ ] { "" , "" } ) ; } protected IRubyProject createRubyProject ( String projectName , String [ ] sourceFolders ) throws CoreException { return this . createRubyProject ( projectName , sourceFolders , null , null , null , null , null , null , null , null , null ) ; } protected IRubyProject createRubyProject ( String projectName , String [ ] sourceFolders , String [ ] libraries ) throws CoreException { return this . createRubyProject ( projectName , sourceFolders , libraries , null , null , null , null , null , null , null , null ) ; } protected IRubyProject createRubyProject ( String projectName , String [ ] sourceFolders , String [ ] libraries , String [ ] projects , boolean [ ] exportedProject ) throws CoreException { return this . createRubyProject ( projectName , sourceFolders , libraries , null , null , projects , null , null , exportedProject , null , null ) ; } protected IRubyProject createRubyProject ( String projectName , String [ ] sourceFolders , String [ ] libraries , String [ ] projects ) throws CoreException { return createRubyProject ( projectName , sourceFolders , libraries , null , null , projects , null , null , null , null , null ) ; } protected IRubyProject createRubyProject ( final String projectName , final String [ ] sourceFolders , final String [ ] libraries , final String [ ] projects , final boolean [ ] exportedProjects , final String [ ] [ ] inclusionPatterns , final String [ ] [ ] exclusionPatterns ) throws CoreException { return this . createRubyProject ( projectName , sourceFolders , libraries , null , null , projects , null , null , exportedProjects , inclusionPatterns , exclusionPatterns ) ; } protected IRubyProject createRubyProject ( final String projectName , final String [ ] sourceFolders , final String [ ] libraries , final String [ ] [ ] librariesInclusionPatterns , final String [ ] [ ] librariesExclusionPatterns , final String [ ] projects , final String [ ] [ ] projectsInclusionPatterns , final String [ ] [ ] projectsExclusionPatterns , final boolean [ ] exportedProjects , final String [ ] [ ] inclusionPatterns , final String [ ] [ ] exclusionPatterns ) throws CoreException { final IRubyProject [ ] result = new IRubyProject [ ] ; IWorkspaceRunnable create = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { createProject ( projectName ) ; addRubyNature ( projectName ) ; IProject project = getWorkspaceRoot ( ) . getProject ( projectName ) ; IPath projectPath = project . getFullPath ( ) ; int sourceLength = sourceFolders == null ? : sourceFolders . length ; int libLength = libraries == null ? : libraries . length ; int projectLength = projects == null ? : projects . length ; ILoadpathEntry [ ] entries = new ILoadpathEntry [ sourceLength + libLength + projectLength ] ; for ( int i = ; i < sourceLength ; i ++ ) { IPath sourcePath = new Path ( sourceFolders [ i ] ) ; int segmentCount = sourcePath . segmentCount ( ) ; if ( segmentCount > ) { IContainer container = project ; for ( int j = ; j < segmentCount ; j ++ ) { IFolder folder = container . getFolder ( new Path ( sourcePath . segment ( j ) ) ) ; if ( ! folder . exists ( ) ) { folder . create ( true , true , null ) ; } container = folder ; } } IPath [ ] inclusionPaths ; if ( inclusionPatterns == null ) { inclusionPaths = new IPath [ ] ; } else { String [ ] patterns = inclusionPatterns [ i ] ; int length = patterns . length ; inclusionPaths = new IPath [ length ] ; for ( int j = ; j < length ; j ++ ) { String inclusionPattern = patterns [ j ] ; inclusionPaths [ j ] = new Path ( inclusionPattern ) ; } } IPath [ ] exclusionPaths ; if ( exclusionPatterns == null ) { exclusionPaths = new IPath [ ] ; } else { String [ ] patterns = exclusionPatterns [ i ] ; int length = patterns . length ; exclusionPaths = new IPath [ length ] ; for ( int j = ; j < length ; j ++ ) { String exclusionPattern = patterns [ j ] ; exclusionPaths [ j ] = new Path ( exclusionPattern ) ; } } entries [ i ] = RubyCore . newSourceEntry ( projectPath . append ( sourcePath ) , inclusionPaths , exclusionPaths , LoadpathEntry . NO_EXTRA_ATTRIBUTES ) ; } for ( int i = ; i < libLength ; i ++ ) { String lib = libraries [ i ] ; IPath [ ] accessibleFiles ; if ( librariesInclusionPatterns == null ) { accessibleFiles = new IPath [ ] ; } else { String [ ] patterns = librariesInclusionPatterns [ i ] ; int length = patterns . length ; accessibleFiles = new IPath [ length ] ; for ( int j = ; j < length ; j ++ ) { String inclusionPattern = patterns [ j ] ; accessibleFiles [ j ] = new Path ( inclusionPattern ) ; } } IPath [ ] nonAccessibleFiles ; if ( librariesExclusionPatterns == null ) { nonAccessibleFiles = new IPath [ ] ; } else { String [ ] patterns = librariesExclusionPatterns [ i ] ; int length = patterns . length ; nonAccessibleFiles = new IPath [ length ] ; for ( int j = ; j < length ; j ++ ) { String exclusionPattern = patterns [ j ] ; nonAccessibleFiles [ j ] = new Path ( exclusionPattern ) ; } } if ( lib . indexOf ( File . separatorChar ) == - && lib . charAt ( ) != '' && lib . equals ( lib . toUpperCase ( ) ) ) { char [ ] [ ] vars = CharOperation . splitOn ( '' , lib . toCharArray ( ) ) ; entries [ sourceLength + i ] = RubyCore . newVariableEntry ( new Path ( new String ( vars [ ] ) ) , false ) ; } else if ( lib . startsWith ( "" ) ) { entries [ sourceLength + i ] = RubyCore . newContainerEntry ( new Path ( lib ) , false ) ; } else { IPath libPath = new Path ( lib ) ; if ( ! libPath . isAbsolute ( ) && libPath . segmentCount ( ) > && libPath . getFileExtension ( ) == null ) { project . getFolder ( libPath ) . create ( true , true , null ) ; libPath = projectPath . append ( libPath ) ; } entries [ sourceLength + i ] = RubyCore . newLibraryEntry ( libPath , false ) ; } } for ( int i = ; i < projectLength ; i ++ ) { boolean isExported = exportedProjects != null && exportedProjects . length > i && exportedProjects [ i ] ; IPath [ ] accessibleFiles ; if ( projectsInclusionPatterns == null ) { accessibleFiles = new IPath [ ] ; } else { String [ ] patterns = projectsInclusionPatterns [ i ] ; int length = patterns . length ; accessibleFiles = new IPath [ length ] ; for ( int j = ; j < length ; j ++ ) { String inclusionPattern = patterns [ j ] ; accessibleFiles [ j ] = new Path ( inclusionPattern ) ; } } IPath [ ] nonAccessibleFiles ; if ( projectsExclusionPatterns == null ) { nonAccessibleFiles = new IPath [ ] ; } else { String [ ] patterns = projectsExclusionPatterns [ i ] ; int length = patterns . length ; nonAccessibleFiles = new IPath [ length ] ; for ( int j = ; j < length ; j ++ ) { String exclusionPattern = patterns [ j ] ; nonAccessibleFiles [ j ] = new Path ( exclusionPattern ) ; } } entries [ sourceLength + libLength + i ] = RubyCore . newProjectEntry ( new Path ( projects [ i ] ) , isExported ) ; } IRubyProject javaProject = RubyCore . create ( project ) ; javaProject . setRawLoadpath ( entries , null , null ) ; result [ ] = javaProject ; } } ; getWorkspace ( ) . run ( create , null ) ; return result [ ] ; } protected IProject createProject ( final String projectName ) throws CoreException { final IProject project = getProject ( projectName ) ; IWorkspaceRunnable create = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { project . create ( null ) ; project . open ( null ) ; } } ; getWorkspace ( ) . run ( create , null ) ; return project ; } protected void addRubyNature ( String projectName ) throws CoreException { IProject project = getWorkspaceRoot ( ) . getProject ( projectName ) ; IProjectDescription description = project . getDescription ( ) ; description . setNatureIds ( new String [ ] { RubyCore . NATURE_ID } ) ; project . setDescription ( description , null ) ; } public IRubyScript getRubyScript ( String projectName , String rootPath , String packageName , String cuName ) throws RubyModelException { ISourceFolder pkg = getSourceFolder ( projectName , rootPath , packageName ) ; if ( pkg == null ) { return null ; } return pkg . getRubyScript ( cuName ) ; } public ISourceFolder getSourceFolder ( String projectName , String rootPath , String packageName ) throws RubyModelException { ISourceFolderRoot root = getSourceFolderRoot ( projectName , rootPath ) ; if ( root == null ) { return null ; } return root . getSourceFolder ( packageName ) ; } public ISourceFolderRoot getSourceFolderRoot ( String projectName , String rootPath ) throws RubyModelException { IRubyProject project = getRubyProject ( projectName ) ; if ( project == null ) { return null ; } IPath path = new Path ( rootPath ) ; if ( path . isAbsolute ( ) ) { IWorkspaceRoot workspaceRoot = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) ; IResource resource = workspaceRoot . findMember ( path ) ; ISourceFolderRoot root ; if ( resource == null ) { root = project . getSourceFolderRoot ( rootPath ) ; } else { root = project . getSourceFolderRoot ( resource ) ; } return root ; } else { ISourceFolderRoot [ ] roots = project . getSourceFolderRoots ( ) ; if ( roots == null || roots . length == ) { return null ; } for ( int i = ; i < roots . length ; i ++ ) { ISourceFolderRoot root = roots [ i ] ; if ( ! root . isExternal ( ) && root . getUnderlyingResource ( ) . getProjectRelativePath ( ) . equals ( path ) ) { return root ; } } } return null ; } public IRubyProject getRubyProject ( String name ) { IProject project = getProject ( name ) ; return RubyCore . create ( project ) ; } protected void assertSourceEquals ( String message , String expected , String actual ) { if ( actual == null ) { assertEquals ( message , expected , null ) ; return ; } actual = org . rubypeople . rdt . core . tests . util . Util . convertToIndependantLineDelimiter ( actual ) ; if ( ! actual . equals ( expected ) ) { System . out . print ( org . rubypeople . rdt . core . tests . util . Util . displayString ( actual . toString ( ) , ) ) ; System . out . println ( this . endChar ) ; } assertEquals ( message , expected , actual ) ; } protected IFolder createFolder ( IPath path ) throws CoreException { final IFolder folder = getWorkspaceRoot ( ) . getFolder ( path ) ; getWorkspace ( ) . run ( new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { IContainer parent = folder . getParent ( ) ; if ( parent instanceof IFolder && ! parent . exists ( ) ) { createFolder ( parent . getFullPath ( ) ) ; } folder . create ( true , true , null ) ; } } , null ) ; return folder ; } protected IRubyScript getRubyScript ( String path ) { return RubyCore . create ( getFile ( path ) ) ; } public static void waitUntilIndexesReady ( ) { } public void deleteFile ( File file ) { int retryCount = ; while ( ++ retryCount <= ) { if ( org . rubypeople . rdt . core . tests . util . Util . delete ( file ) ) { break ; } } } protected void deleteFolder ( IPath folderPath ) throws CoreException { deleteResource ( getFolder ( folderPath ) ) ; } protected IFolder getFolder ( IPath path ) { return getWorkspaceRoot ( ) . getFolder ( path ) ; } } package org . rubypeople . rdt . core . formatter . rewriter ; import junit . framework . TestCase ; public class TestBooleanStateStack extends TestCase { protected void setUp ( ) throws Exception { super . setUp ( ) ; } protected void tearDown ( ) throws Exception { super . tearDown ( ) ; } public void testBooleanStateStack ( ) { BooleanStateStack s = new BooleanStateStack ( true , true ) ; assertTrue ( s . isTrue ( ) ) ; s . revert ( ) ; assertTrue ( s . isTrue ( ) ) ; s = new BooleanStateStack ( false , false ) ; assertFalse ( s . isTrue ( ) ) ; s . revert ( ) ; assertFalse ( s . isTrue ( ) ) ; } public void testSet ( ) { BooleanStateStack s = new BooleanStateStack ( true , true ) ; assertTrue ( s . isTrue ( ) ) ; s . set ( false ) ; assertFalse ( s . isTrue ( ) ) ; s . revert ( ) ; assertTrue ( s . isTrue ( ) ) ; } } package org . rubypeople . rdt . core . formatter ; import java . io . BufferedReader ; import java . io . FileOutputStream ; import java . io . FileReader ; import java . io . IOException ; import java . io . StringWriter ; import junit . framework . TestCase ; import org . jruby . ast . ArgumentNode ; import org . jruby . ast . ArrayNode ; import org . jruby . ast . ConstNode ; import org . jruby . ast . LocalVarNode ; import org . jruby . ast . Node ; import org . jruby . ast . PostExeNode ; import org . jruby . ast . RegexpNode ; import org . jruby . lexer . yacc . IDESourcePosition ; import org . jruby . util . ByteList ; public class TestReWriteVisitor extends TestCase { static final IDESourcePosition emptyPosition = new IDESourcePosition ( "" , , , , ) ; private String visitNode ( Node n ) { StringWriter out = new StringWriter ( ) ; ReWriteVisitor visitor = new ReWriteVisitor ( out , "" ) ; n . accept ( visitor ) ; visitor . flushStream ( ) ; return out . getBuffer ( ) . toString ( ) ; } public void testVisitRegexpNode ( ) { RegexpNode n = new RegexpNode ( new IDESourcePosition ( "" , , , , ) , ByteList . create ( "" ) , ) ; assertEquals ( "" , visitNode ( n ) ) ; } public void testGetLocalVarIndex ( ) { assertEquals ( ReWriteVisitor . getLocalVarIndex ( new LocalVarNode ( emptyPosition , , "" ) ) , ) ; assertEquals ( ReWriteVisitor . getLocalVarIndex ( new LocalVarNode ( emptyPosition , , "" ) ) , ) ; assertEquals ( ReWriteVisitor . getLocalVarIndex ( null ) , - ) ; } private ReWriteVisitor getVisitor ( ) { return new ReWriteVisitor ( new StringWriter ( ) , "" ) ; } public void testVisitPostExeNode ( ) { assertNull ( getVisitor ( ) . visitPostExeNode ( new PostExeNode ( emptyPosition , null ) ) ) ; } public void testUnwrapSingleArrayNode ( ) { ArrayNode arrayNode = new ArrayNode ( emptyPosition ) ; ConstNode constNode = new ConstNode ( emptyPosition , "" ) ; ConstNode anotherConstNode = new ConstNode ( emptyPosition , "" ) ; arrayNode . add ( constNode ) ; assertEquals ( ReWriteVisitor . unwrapSingleArrayNode ( arrayNode ) , constNode ) ; assertEquals ( ReWriteVisitor . unwrapSingleArrayNode ( constNode ) , constNode ) ; arrayNode . add ( anotherConstNode ) ; assertEquals ( ReWriteVisitor . unwrapSingleArrayNode ( arrayNode ) , arrayNode ) ; } public void testUnescapeChar ( ) { assertEquals ( ReWriteVisitor . unescapeChar ( '' ) , "" ) ; assertEquals ( ReWriteVisitor . unescapeChar ( '' ) , "" ) ; assertEquals ( ReWriteVisitor . unescapeChar ( '' ) , "" ) ; assertEquals ( ReWriteVisitor . unescapeChar ( '' ) , null ) ; } public void testArgumentNode ( ) { Node node = new ArgumentNode ( new IDESourcePosition ( ) , "" ) ; assertEquals ( "" , ReWriteVisitor . createCodeFromNode ( node , "" ) ) ; } public void testFileOutputStream ( ) throws IOException { String fileName = "" ; try { String testString = "" ; FileOutputStream stream = new FileOutputStream ( fileName ) ; ReWriteVisitor visitor = new ReWriteVisitor ( stream , "" ) ; ConstNode node = new ConstNode ( emptyPosition , testString ) ; node . accept ( visitor ) ; visitor . flushStream ( ) ; stream . close ( ) ; BufferedReader reader = new BufferedReader ( new FileReader ( fileName ) ) ; assertEquals ( reader . readLine ( ) , testString ) ; reader . close ( ) ; } finally { new java . io . File ( fileName ) . delete ( ) ; } } } package org . rubypeople . rdt . core . formatter ; import java . io . PrintWriter ; import java . io . StringWriter ; import junit . framework . TestCase ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; import org . rubypeople . rdt . internal . core . parser . RubyParserWithComments ; public class TC_EditableFormatHelper extends TestCase { private EditableFormatHelper formatter ; @ Override public void setUp ( ) { formatter = new EditableFormatHelper ( "" ) ; } private String format ( String original ) { StringWriter writer = new StringWriter ( ) ; ReWriterFactory factory = new ReWriterFactory ( new ReWriterContext ( new PrintWriter ( writer ) , original , formatter ) ) ; RubyParser parser = new RubyParserWithComments ( ) ; ReWriteVisitor visitor = factory . createReWriteVisitor ( ) ; parser . parse ( original ) . getAST ( ) . accept ( visitor ) ; visitor . flushStream ( ) ; return writer . getBuffer ( ) . toString ( ) ; } private void assertEqualSource ( String expectedResult , String toBeFormatted ) { assertEquals ( expectedResult , format ( toBeFormatted ) ) ; } public void testBeforeAndAfterAssignment ( ) { formatter . setSpacesBeforeAndAfterAssignments ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpacesBeforeAndAfterAssignments ( true ) ; assertEqualSource ( "" , "" ) ; } public void testMatchOperator ( ) { formatter . setSpacesBeforeAndAfterAssignments ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpacesBeforeAndAfterAssignments ( true ) ; assertEqualSource ( "" , "" ) ; } public void testBeforeAndAfterCallArguments ( ) { formatter . setAlwaysParanthesizeMethodCalls ( false ) ; assertEqualSource ( "" , "" ) ; assertEqualSource ( "" , "" ) ; formatter . setAlwaysParanthesizeMethodCalls ( true ) ; assertEqualSource ( "" , "" ) ; assertEqualSource ( "" , "" ) ; } public void testBeforeAndAfterHashContent ( ) { formatter . setSpacesBeforeAndAfterHashContent ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpacesBeforeAndAfterHashContent ( true ) ; assertEqualSource ( "" , "" ) ; } public void testBeforeIterVars ( ) { formatter . setSpaceAfterIterVars ( false ) ; formatter . setSpaceBeforeClosingIterBrackets ( false ) ; formatter . setSpaceBeforeIterVars ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpaceBeforeIterVars ( true ) ; assertEqualSource ( "" , "" ) ; } public void testAfterIterVars ( ) { formatter . setSpaceBeforeIterVars ( false ) ; formatter . setSpaceBeforeClosingIterBrackets ( false ) ; formatter . setSpaceAfterIterVars ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpaceAfterIterVars ( true ) ; assertEqualSource ( "" , "" ) ; } public void testBeforeAndAfterMethodArguments ( ) { formatter . setAlwaysParanthesizeMethodDefs ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setAlwaysParanthesizeMethodDefs ( true ) ; assertEqualSource ( "" , "" ) ; } public void testBeforeIterBrackets ( ) { formatter . setSpaceBeforeIterVars ( false ) ; formatter . setSpaceAfterIterVars ( false ) ; formatter . setSpaceBeforeClosingIterBrackets ( false ) ; formatter . setSpaceBeforeIterBrackets ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpaceBeforeIterBrackets ( true ) ; assertEqualSource ( "" , "" ) ; } public void testBeforeClosingIterBrackets ( ) { formatter . setSpaceBeforeIterVars ( false ) ; formatter . setSpaceAfterIterVars ( false ) ; formatter . setSpaceBeforeClosingIterBrackets ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpaceBeforeClosingIterBrackets ( true ) ; assertEqualSource ( "" , "" ) ; } public void testClassBodyElementsSeparator ( ) { formatter . setNewlineBetweenClassBodyElements ( false ) ; assertEqualSource ( "" + "" + "" + "" + "" + "" , "" + "" + "" + "" + "" + "" ) ; formatter . setNewlineBetweenClassBodyElements ( true ) ; assertEqualSource ( "" + "" + "" + "" + "" + "" + "" , "" + "" + "" + "" + "" + "" ) ; } public void testGetListSeparator ( ) { formatter . setSpaceAfterCommaInListings ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpaceAfterCommaInListings ( true ) ; assertEqualSource ( "" , "" ) ; } public void testHashAssignment ( ) { formatter . setSpacesAroundHashAssignment ( false ) ; assertEqualSource ( "" , "" ) ; formatter . setSpacesAroundHashAssignment ( true ) ; assertEqualSource ( "" , "" ) ; } public void testIndentationSteps ( ) { formatter . setIndentationSteps ( ) ; assertEqualSource ( "" + "" + "" + "" , "" + "" + "" + "" ) ; formatter . setIndentationSteps ( ) ; assertEqualSource ( "" + "" + "" + "" , "" + "" + "" + "" ) ; } public void testIndentationChar ( ) { formatter . setTabInsteadOfSpaces ( false ) ; assertEqualSource ( "" + "" + "" + "" , "" + "" + "" + "" ) ; formatter . setTabInsteadOfSpaces ( true ) ; formatter . setIndentationSteps ( ) ; assertEqualSource ( "" + "" + "" + "" , "" + "" + "" + "" ) ; } } package org . rubypeople . rdt . core . util ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_CoreUtil { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( UtilTest . class ) ; return suite ; } } package org . rubypeople . rdt . core . util ; import java . io . File ; import java . io . FileOutputStream ; import java . io . FileWriter ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . rubypeople . rdt . core . util . Util . Displayable ; public class UtilTest extends TestCase { public void testGetFileByteContent ( ) throws Exception { byte [ ] content = new byte [ ] { , } ; File file = File . createTempFile ( "" , "" ) ; try { FileOutputStream out = null ; try { out = new FileOutputStream ( file ) ; out . write ( content ) ; } finally { if ( out != null ) out . close ( ) ; } assertArrayContentsEquals ( content , Util . getFileByteContent ( file ) ) ; } finally { file . delete ( ) ; } } private void assertArrayContentsEquals ( byte [ ] expected , byte [ ] actual ) { if ( expected == null ) { assertNull ( actual ) ; return ; } assertEquals ( expected . length , actual . length ) ; int length = expected . length ; for ( int i = ; i < length ; i ++ ) { assertEquals ( expected [ i ] , actual [ i ] ) ; } } private void assertArrayContentsEquals ( char [ ] expected , char [ ] actual ) { if ( expected == null ) { assertNull ( actual ) ; return ; } assertEquals ( expected . length , actual . length ) ; int length = expected . length ; for ( int i = ; i < length ; i ++ ) { assertEquals ( expected [ i ] , actual [ i ] ) ; } } public void testToStringObjectArrayDisplayable ( ) { assertEquals ( "" , Util . toString ( new Object [ ] { , null , } , new Displayable ( ) { public String displayString ( Object o ) { if ( o == null ) return "" ; return o . toString ( ) ; } } ) ) ; } public void testToStringObjectArray ( ) { assertEquals ( "" , Util . toString ( new Object [ ] { , , } ) ) ; assertEquals ( "" , Util . toString ( new Object [ ] { , null , } ) ) ; assertEquals ( "" , Util . toString ( null ) ) ; assertEquals ( "" , Util . toString ( new Object [ ] { , "" , true , } ) ) ; } public void testGetFileCharContent ( ) throws Exception { char [ ] content = new char [ ] { '' , '' } ; File file = File . createTempFile ( "" , "" ) ; try { FileWriter out = null ; try { out = new FileWriter ( file ) ; out . write ( content ) ; } finally { if ( out != null ) out . close ( ) ; } assertArrayContentsEquals ( content , Util . getFileCharContent ( file , null ) ) ; } finally { file . delete ( ) ; } } public void testCamelCaseToUnderscores ( ) { assertEquals ( "" , Util . camelCaseToUnderscores ( "" ) ) ; assertEquals ( "" , Util . camelCaseToUnderscores ( "" ) ) ; assertEquals ( "" , Util . camelCaseToUnderscores ( "" ) ) ; } public void testUnderscoresToCamelCase ( ) { assertEquals ( "" , Util . underscoresToCamelCase ( "" ) ) ; assertEquals ( "" , Util . underscoresToCamelCase ( "" ) ) ; } public void testIsOperator ( ) { assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( ">" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertTrue ( Util . isOperator ( "" ) ) ; assertFalse ( Util . isOperator ( "" ) ) ; assertFalse ( Util . isOperator ( "" ) ) ; assertFalse ( Util . isOperator ( "" ) ) ; assertFalse ( Util . isOperator ( "" ) ) ; } public void testIsKeyword ( ) { assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertTrue ( Util . isKeyword ( "" ) ) ; assertFalse ( Util . isKeyword ( null ) ) ; assertFalse ( Util . isKeyword ( "" ) ) ; assertFalse ( Util . isKeyword ( "" ) ) ; } public void testFindFileWithOptionalSuffix ( ) throws Exception { List < File > filesToCleanUp = new ArrayList < File > ( ) ; String tmpDir = System . getProperty ( "" ) ; File dirToUse = new File ( tmpDir , "" ) ; dirToUse . mkdir ( ) ; File exeFile = new File ( dirToUse , "" ) ; filesToCleanUp . add ( exeFile ) ; File binFile = new File ( dirToUse , "" ) ; filesToCleanUp . add ( binFile ) ; File txtFile = new File ( dirToUse , "" ) ; filesToCleanUp . add ( txtFile ) ; for ( File file : filesToCleanUp ) { file . createNewFile ( ) ; } filesToCleanUp . add ( dirToUse ) ; try { assertEquals ( exeFile . getAbsolutePath ( ) , Util . findFileWithOptionalSuffix ( dirToUse . getAbsolutePath ( ) + File . separator + "" ) . getAbsolutePath ( ) ) ; assertEquals ( txtFile . getAbsolutePath ( ) , Util . findFileWithOptionalSuffix ( dirToUse . getAbsolutePath ( ) + File . separator + "" ) . getAbsolutePath ( ) ) ; assertEquals ( binFile . getAbsolutePath ( ) , Util . findFileWithOptionalSuffix ( dirToUse . getAbsolutePath ( ) + File . separator + "" ) . getAbsolutePath ( ) ) ; } finally { for ( File file : filesToCleanUp ) { if ( ! file . delete ( ) ) { file . deleteOnExit ( ) ; } } } } } package org . rubypeople . rdt . internal ; import org . rubypeople . rdt . internal . codeassist . TS_InternalCodeAssist ; import org . rubypeople . rdt . internal . core . TS_InternalCore ; import org . rubypeople . rdt . internal . formatter . TS_InternalFormatter ; import org . rubypeople . rdt . internal . ti . TS_TypeInference ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_Internal { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTest ( TS_InternalCore . suite ( ) ) ; suite . addTest ( TS_InternalCodeAssist . suite ( ) ) ; suite . addTest ( TS_InternalFormatter . suite ( ) ) ; suite . addTest ( TS_TypeInference . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . internal . ti ; public class DataFlowTypeInferrerTest extends CombinedTypeInferrerTest { protected ITypeInferrer createTypeInferrer ( ) { return new DataFlowTypeInferrer ( ) ; } public void testLocalVariableAfterAssignmentWithOverwrite ( ) throws Exception { assertInfersTypeFiftyFifty ( inferrer . infer ( "" , ) , "" , "" ) ; } public void testClassVarAssignment ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testInstVarAssignmentInDifferentClassesWithSameName ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testGlobalVarAssignmentInDifferentClassesWithSameName ( ) throws Exception { assertInfersTypeFiftyFifty ( inferrer . infer ( "" , ) , "" , "" ) ; } public void testArg ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testArgTwoDegree ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testArgTwoWay ( ) throws Exception { assertInfersTypeFiftyFifty ( inferrer . infer ( "" , ) , "" , "" ) ; } public void testMethodRetval ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; } public void testInstanceObjectMethodRetval ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; } public void testMethodRetvalIsTypeCovariantWithArgument ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; } public void testFactoryMethod ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; } public void testSimpleMethodImplicitRetval ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; } public void testBranchingMethodImplicitRetvalSameType ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , script . length ( ) - ) , "" ) ; } public void testBranchingMethodImplicitRetvalDifferentTypes ( ) throws Exception { String script = "" ; assertInfersTypeFiftyFifty ( inferrer . infer ( script , script . length ( ) - ) , "" , "" ) ; } } package org . rubypeople . rdt . internal . ti ; public abstract class CombinedTypeInferrerTest extends TypeInferrerTestCase { public void testFixnum ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testArrayLiteral ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testString ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testFixnumAssignment ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testLocalVariableAfterAssignment ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testLocalVariableAfterAssignmentInsideScope ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testNamespacedClass ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" + "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( src , src . length ( ) - ) , "" ) ; } public void testLocalVariableAssignmentToLocalVariable ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; } public void testLocalVariableAssignmentToLocalVariableTwice ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; } public void testLocalVariableAssignmentToWellKnownMethodCall ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testLocalVariableAssignmentToClassInstantiation ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testInfiniteLoop ( ) throws Exception { inferrer . infer ( "" , ) ; assertTrue ( true ) ; } public void testInstVarAssignment ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testGlobalVarAssignment ( ) throws Exception { assertInfersTypeWithoutDoubt ( inferrer . infer ( "" , ) , "" ) ; } public void testLocalVariableAssignmentWithSameNameAcrossTwoScopes ( ) throws Exception { String script = "" ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; assertInfersTypeWithoutDoubt ( inferrer . infer ( script , ) , "" ) ; } } package org . rubypeople . rdt . internal . ti ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_TypeInference { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( DataFlowTypeInferrerTest . class ) ; suite . addTestSuite ( ReferenceMatchTest . class ) ; suite . addTestSuite ( TypeInferrerTest . class ) ; return suite ; } } package org . rubypeople . rdt . internal . ti ; public class TypeInferrerTest extends CombinedTypeInferrerTest { protected ITypeInferrer createTypeInferrer ( ) { return new DefaultTypeInferrer ( ) ; } } package org . rubypeople . rdt . internal . ti ; import java . util . Collection ; import junit . framework . TestCase ; public abstract class TypeInferrerTestCase extends TestCase { protected ITypeInferrer inferrer ; public TypeInferrerTestCase ( ) { super ( ) ; } public void setUp ( ) { inferrer = createTypeInferrer ( ) ; } protected void assertInfersTypeWithoutDoubt ( Collection < ITypeGuess > guesses , String type ) { assertEquals ( , guesses . size ( ) ) ; ITypeGuess guess = guesses . iterator ( ) . next ( ) ; assertEquals ( type , guess . getType ( ) ) ; assertEquals ( , guess . getConfidence ( ) ) ; } protected void assertInfersTypeFiftyFifty ( Collection < ITypeGuess > guesses , String type1 , String type2 ) { assertEquals ( , guesses . size ( ) ) ; ITypeGuess guess1 = findGuess ( guesses , type1 ) ; assertNotNull ( "" + type1 , guess1 ) ; assertEquals ( guess1 . getConfidence ( ) , ) ; ITypeGuess guess2 = findGuess ( guesses , type2 ) ; assertNotNull ( "" + type2 , guess2 ) ; assertEquals ( guess2 . getConfidence ( ) , ) ; } private ITypeGuess findGuess ( Collection < ITypeGuess > guesses , String type1 ) { for ( ITypeGuess typeGuess : guesses ) { if ( typeGuess . getType ( ) . equals ( type1 ) ) { return typeGuess ; } } return null ; } protected abstract ITypeInferrer createTypeInferrer ( ) ; } package org . rubypeople . rdt . internal . ti ; import java . util . List ; import org . jruby . lexer . yacc . ISourcePosition ; import junit . framework . TestCase ; public class ReferenceMatchTest extends TestCase { private IReferenceFinder referenceFinder ; public void setUp ( ) { referenceFinder = new DefaultReferenceFinder ( ) ; } private void assertReferencesEquals ( String source , int offset , String matchName , int [ ] [ ] offsets ) { List < ISourcePosition > references = referenceFinder . findReferences ( source , offset ) ; assertEquals ( offsets . length , references . size ( ) ) ; for ( int i = ; i < offsets . length ; i ++ ) { assertEquals ( offsets [ i ] [ ] , references . get ( i ) . getStartOffset ( ) ) ; assertEquals ( offsets [ i ] [ ] , references . get ( i ) . getEndOffset ( ) ) ; assertEquals ( matchName , source . substring ( references . get ( i ) . getStartOffset ( ) , references . get ( i ) . getEndOffset ( ) ) ) ; } } public void testLocalVariableMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } , { , } } ; assertReferencesEquals ( source , , "" , offsets ) ; } public void testLocalVariablesInKernelDefnScope ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } } ; assertReferencesEquals ( source , , "" , offsets ) ; } public void testLocalVariablesInKernelScope ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } , { , } } ; assertReferencesEquals ( source , , "" , offsets ) ; } public void testInstanceVariableMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } } ; assertReferencesEquals ( source , , "" , offsets ) ; } public void testInstanceVariableMatchInReopenedClass ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } } ; assertReferencesEquals ( source , , "" , offsets ) ; } public void testLocalVariableMatchesIntoBlockScope ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } } ; assertReferencesEquals ( source , , "" , offsets ) ; } public void testGlobalVariableMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } , { , } } ; assertReferencesEquals ( source , , "" , offsets ) ; } public void testTypeMatches ( ) { String source = "" ; int [ ] [ ] offsets = { { , } , { , } , { , } } ; assertReferencesEquals ( source , , "" , offsets ) ; } } package org . rubypeople . rdt . internal . codeassist ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_InternalCodeAssist { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( CompletionEngineTest . class ) ; suite . addTestSuite ( CompletionContextTest . class ) ; return suite ; } } package org . rubypeople . rdt . internal . codeassist ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IncrementalProjectBuilder ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . rubypeople . rdt . core . CompletionProposal ; import org . rubypeople . rdt . core . CompletionRequestor ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; public class CompletionEngineTest extends ModifyingResourceTest { private IRubyProject rubyProject ; private TestCompletionRequestor requestor ; public CompletionEngineTest ( String name ) { super ( name ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; rubyProject = createRubyProject ( "" ) ; requestor = new TestCompletionRequestor ( ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; deleteProject ( rubyProject . getElementName ( ) ) ; rubyProject = null ; } public void testArrayLiteral ( ) throws Exception { createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , "" ) ; final boolean [ ] isDone = new boolean [ ] ; IProgressMonitor monitor = new NullProgressMonitor ( ) { @ Override public void done ( ) { isDone [ ] = true ; super . done ( ) ; } } ; rubyProject . getProject ( ) . build ( IncrementalProjectBuilder . CLEAN_BUILD , monitor ) ; String src = "" ; IRubyScript script = createScript ( src ) ; long start = System . currentTimeMillis ( ) ; while ( ! isDone [ ] ) { Thread . yield ( ) ; if ( System . currentTimeMillis ( ) > start + ) fail ( "" ) ; } script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . METHOD_REF , "" , "" ) ) ; } public void testUserClass ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( src . length ( ) - , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . METHOD_REF , "" , "" ) ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . METHOD_REF , "" , "" ) ) ; } public void testSuggestsConstructorForExplicitMethodInvokationOnConstant ( ) throws Exception { String src = "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( src . length ( ) - , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . METHOD_REF , "" , "" ) ) ; } public void testClassIncludesModules ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( src . length ( ) - , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . METHOD_REF , "" , "" ) ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . METHOD_REF , "" , "" ) ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . METHOD_REF , "" , "" ) ) ; } public void testConstantInBrokenScript ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( src . length ( ) - , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . METHOD_REF , "" , "" ) ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . CONSTANT_REF , "" , "" ) ) ; } private IRubyScript createScript ( String src ) throws CoreException { IFile file = createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , src ) ; IRubyScript script = RubyCore . create ( file ) ; return script ; } public void testSuggestInstanceVariablesDefinedInAttrMethodCalls ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . INSTANCE_VARIABLE_REF , null , "" ) ) ; } public void testSuggestInstanceVariablesDefinedInAttrMethodCallsWithPrefix ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . INSTANCE_VARIABLE_REF , null , "" ) ) ; } public void testSuggestClassVariablesDefinedInAttrMethodCalls ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . CLASS_VARIABLE_REF , null , "" ) ) ; } public void testSuggestClassVariablesDefinedInAttrMethodCallsWithPrefix ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . CLASS_VARIABLE_REF , null , "" ) ) ; } public void testDontSuggestVariableWereCurrentlyTyping ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . INSTANCE_VARIABLE_REF , null , "" ) ) ; assertFalse ( requestor . containsProposal ( CompletionProposal . INSTANCE_VARIABLE_REF , null , "" ) ) ; } public void testDoesSuggestVariableWereCurrentlyTypingIfPreviouslyDefined ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . INSTANCE_VARIABLE_REF , null , "" ) ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . INSTANCE_VARIABLE_REF , null , "" ) ) ; } public void testDontSuggestClassVariableWereCurrentlyTyping ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . CLASS_VARIABLE_REF , null , "" ) ) ; assertFalse ( requestor . containsProposal ( CompletionProposal . CLASS_VARIABLE_REF , null , "" ) ) ; } public void testDontSuggestLocalVariableWereCurrentlyTyping ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . LOCAL_VARIABLE_REF , null , "" ) ) ; assertFalse ( requestor . containsProposal ( CompletionProposal . LOCAL_VARIABLE_REF , null , "" ) ) ; } public void testConstant ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IRubyScript script = createScript ( src ) ; script . codeComplete ( , requestor ) ; assertTrue ( requestor . containsProposal ( CompletionProposal . CONSTANT_REF , null , "" ) ) ; } private static class TestCompletionRequestor extends CompletionRequestor { private List < CompletionProposal > proposals = new ArrayList < CompletionProposal > ( ) ; @ Override public void accept ( CompletionProposal proposal ) { proposals . add ( proposal ) ; } public boolean containsProposal ( int completionType , String declaringType , String name ) { for ( CompletionProposal proposal : proposals ) { if ( proposal . getKind ( ) != completionType ) continue ; if ( ! proposal . getName ( ) . equals ( name ) ) continue ; if ( declaringType == null && proposal . getDeclaringType ( ) . length ( ) > ) continue ; if ( declaringType != null && ! declaringType . equals ( proposal . getDeclaringType ( ) ) ) continue ; return true ; } return false ; } public int proposalCount ( ) { return proposals . size ( ) ; } } ; } package org . rubypeople . rdt . internal . codeassist ; import org . eclipse . core . resources . IFile ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; public class CompletionContextTest extends ModifyingResourceTest { private IRubyProject rubyProject ; public CompletionContextTest ( String name ) { super ( name ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; rubyProject = createRubyProject ( "" ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; deleteProject ( rubyProject . getElementName ( ) ) ; rubyProject = null ; } public void testCorrectsSourceAndOffsetofCodeCompletionAfterArrayLiteral ( ) throws Exception { IFile file = createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , "" ) ; IRubyScript script = RubyCore . create ( file ) ; CompletionContext context = new CompletionContext ( script , ) ; assertEquals ( "" , context . getCorrectedSource ( ) ) ; assertEquals ( , context . getOffset ( ) ) ; } public void testCompletionOnStringLiteral ( ) throws Exception { IFile file = createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , "" ) ; IRubyScript script = RubyCore . create ( file ) ; CompletionContext context = new CompletionContext ( script , ) ; assertEquals ( "" , context . getCorrectedSource ( ) ) ; assertEquals ( , context . getOffset ( ) ) ; assertFalse ( context . isConstant ( ) ) ; assertFalse ( context . fullPrefixIsConstant ( ) ) ; assertEquals ( "" , context . getPartialPrefix ( ) ) ; } public void testCompletionOnNamespacedConstants ( ) throws Exception { IFile file = createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , "" ) ; IRubyScript script = RubyCore . create ( file ) ; CompletionContext context = new CompletionContext ( script , ) ; assertEquals ( "" , context . getCorrectedSource ( ) ) ; assertEquals ( , context . getOffset ( ) ) ; assertTrue ( context . isDoubleSemiColon ( ) ) ; assertFalse ( context . isConstant ( ) ) ; assertTrue ( context . fullPrefixIsConstant ( ) ) ; assertEquals ( "" , context . getFullPrefix ( ) ) ; assertEquals ( "" , context . getPartialPrefix ( ) ) ; } public void testCompletionOnNamespacedConstantsSecondPortionStarted ( ) throws Exception { IFile file = createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , "" ) ; IRubyScript script = RubyCore . create ( file ) ; CompletionContext context = new CompletionContext ( script , ) ; assertEquals ( "" , context . getCorrectedSource ( ) ) ; assertEquals ( , context . getOffset ( ) ) ; assertTrue ( context . isDoubleSemiColon ( ) ) ; assertTrue ( context . isConstant ( ) ) ; assertTrue ( context . fullPrefixIsConstant ( ) ) ; assertEquals ( "" , context . getFullPrefix ( ) ) ; assertEquals ( "" , context . getPartialPrefix ( ) ) ; } public void testCompletionOnClassVarPrefix ( ) throws Exception { IFile file = createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , "" ) ; IRubyScript script = RubyCore . create ( file ) ; CompletionContext context = new CompletionContext ( script , ) ; assertEquals ( "" , context . getCorrectedSource ( ) ) ; assertEquals ( , context . getOffset ( ) ) ; assertFalse ( context . emptyPrefix ( ) ) ; assertFalse ( context . isConstant ( ) ) ; assertFalse ( context . fullPrefixIsConstant ( ) ) ; assertEquals ( "" , context . getFullPrefix ( ) ) ; assertEquals ( "" , context . getPartialPrefix ( ) ) ; } public void testCompletionOnInstanceVariablePrefix ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" ; IFile file = createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , src ) ; IRubyScript script = RubyCore . create ( file ) ; CompletionContext context = new CompletionContext ( script , ) ; assertEquals ( src , context . getCorrectedSource ( ) ) ; assertEquals ( , context . getOffset ( ) ) ; assertFalse ( context . emptyPrefix ( ) ) ; assertFalse ( context . hasReceiver ( ) ) ; assertFalse ( context . inComment ( ) ) ; assertFalse ( context . isBroken ( ) ) ; assertFalse ( context . isConstant ( ) ) ; assertFalse ( context . fullPrefixIsConstant ( ) ) ; assertFalse ( context . isClassVariable ( ) ) ; assertTrue ( context . isInstanceVariable ( ) ) ; assertEquals ( "" , context . getFullPrefix ( ) ) ; assertEquals ( "" , context . getPartialPrefix ( ) ) ; } public void testCompletionOnInstanceOrClassVariablePrefix ( ) throws Exception { String src = "" + "" + "" + "" + "" + "" + "" ; IFile file = createFile ( rubyProject . getPath ( ) . append ( "" ) . toPortableString ( ) , src ) ; IRubyScript script = RubyCore . create ( file ) ; CompletionContext context = new CompletionContext ( script , ) ; assertEquals ( new StringBuilder ( src ) . deleteCharAt ( ) . toString ( ) , context . getCorrectedSource ( ) ) ; assertEquals ( , context . getOffset ( ) ) ; assertFalse ( context . emptyPrefix ( ) ) ; assertFalse ( context . hasReceiver ( ) ) ; assertFalse ( context . inComment ( ) ) ; assertTrue ( context . isBroken ( ) ) ; assertFalse ( context . isConstant ( ) ) ; assertFalse ( context . isInstanceVariable ( ) ) ; assertFalse ( context . isClassVariable ( ) ) ; assertTrue ( context . isInstanceOrClassVariable ( ) ) ; assertFalse ( context . fullPrefixIsConstant ( ) ) ; assertEquals ( "" , context . getFullPrefix ( ) ) ; assertEquals ( "" , context . getPartialPrefix ( ) ) ; } } package org . rubypeople . rdt . internal . core ; import junit . framework . TestCase ; import org . eclipse . core . runtime . Path ; import org . rubypeople . rdt . core . RubyCore ; public class TC_LoadPathEntry extends TestCase { public TC_LoadPathEntry ( String name ) { super ( name ) ; } public void testToXml ( ) { LoadpathEntry entry = ( LoadpathEntry ) RubyCore . newProjectEntry ( new Path ( "" ) ) ; String expected = "" ; assertEquals ( expected , entry . toXML ( ) ) ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; public class ConstantReassignmentVisitorTest extends AbstractRubyLintVisitorTestCase { public void testCreatesProblemForReassignedConstantInSameNamespace ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testHandlesNestedNamespaceAndExplicitNamespaceForWrappingClass ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testHandlesNestedNamespaceAndExplicitNamespace ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testHandlesExplicitGlobalNamespace ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntCreateProblemForReassignedConstantInDifferentNamespace ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } @ Override protected RubyLintVisitor createVisitor ( String src ) { return new ConstantReassignmentVisitor ( src ) ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_InternalCoreParserWarnings { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( Ruby19WhenStatementsTest . class ) ; suite . addTestSuite ( ConstantReassignmentVisitorTest . class ) ; suite . addTestSuite ( CoreClassReOpeningTest . class ) ; suite . addTestSuite ( Ruby19HashCommaSyntaxTest . class ) ; suite . addTestSuite ( EmptyStatementVisitorTest . class ) ; return suite ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; public class Ruby19HashCommaSyntaxTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new Ruby19HashCommaSyntax ( src ) ; } public void testComplainsAboutCommaSeparatingKeyAndValue ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutArrowSeparatingKeyAndValue ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import java . util . List ; import junit . framework . TestCase ; import org . jruby . ast . Node ; import org . jruby . parser . RubyParserResult ; import org . rubypeople . rdt . core . compiler . CategorizedProblem ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; public abstract class AbstractRubyLintVisitorTestCase extends TestCase { public AbstractRubyLintVisitorTestCase ( ) { super ( ) ; } public AbstractRubyLintVisitorTestCase ( String name ) { super ( name ) ; } protected List < CategorizedProblem > getProblems ( String src ) { RubyParser parser = new RubyParser ( ) ; RubyParserResult result = parser . parse ( src ) ; RubyLintVisitor visitor = createVisitor ( src ) ; Node ast = result . getAST ( ) ; ast . accept ( visitor ) ; return visitor . getProblems ( ) ; } protected abstract RubyLintVisitor createVisitor ( String src ) ; } package org . rubypeople . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; public class CoreClassReOpeningTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new CoreClassReOpening ( null , src ) { @ Override protected boolean methodExistsOnType ( String typeName , String methodName ) { return typeName . equals ( "" ) && methodName . equals ( "" ) ; } @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testRedefiningCoreClassMethod ( ) throws Exception { String src = "" + "" + "" + "" + "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testAddingNewMethodToCoreClassIsntAProblem ( ) throws Exception { String src = "" + "" + "" + "" + "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; public class Ruby19WhenStatementsTest extends AbstractRubyLintVisitorTestCase { public void testCreatesProblemForColonInsteadOfThen ( ) throws Exception { String src = "" + "" + "" + "" + "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testCreatesNoProblemForThen ( ) throws Exception { String src = "" + "" + "" + "" + "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } @ Override protected RubyLintVisitor createVisitor ( String src ) { return new Ruby19WhenStatements ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } } package org . rubypeople . rdt . internal . core . parser . warnings ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . parser . warnings . RubyLintVisitor ; public class EmptyStatementVisitorTest extends AbstractRubyLintVisitorTestCase { @ Override protected RubyLintVisitor createVisitor ( String src ) { return new EmptyStatementVisitor ( src ) { @ Override protected String getSeverity ( ) { return RubyCore . WARNING ; } } ; } public void testComplainsAboutEmptyMethod ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutMethodWithBody ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testComplainsAboutEmptySingletonMethod ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutSingletonMethodWithBody ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testComplainsAboutEmptyIfBody ( ) throws Exception { String src = "" + "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutIfWithBody ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testComplainsAboutEmptyUnlessBody ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutUnlessWithBody ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testComplainsAboutEmptyBlock ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutBlockWithBody ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testComplainsAboutEmptyWhen ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutWhenWithBody ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutIfWithBodyContainingUnless ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesComplainAboutIfWithNoBodyElseContainingUnless ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesComplainAboutUnlessWithNoBodyElseContainingUnless ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } public void testDoesntComplainAboutUnlessWithBodyContainingUnless ( ) throws Exception { String src = "" ; assertEquals ( , getProblems ( src ) . size ( ) ) ; } } package org . rubypeople . rdt . internal . core . parser ; import junit . framework . TestCase ; import org . jruby . ast . Node ; import org . jruby . lexer . yacc . LexerSource ; import org . jruby . parser . DefaultRubyParser ; import org . jruby . parser . ParserConfiguration ; import org . jruby . parser . RubyParserResult ; import org . rubypeople . eclipse . shams . resources . ShamFile ; public class TC_RubyParser extends TestCase { public void testParse ( ) throws Exception { ShamDefaultRubyParser defaultRubyParser = new ShamDefaultRubyParser ( ) ; RubyParserResult rubyParserResult = new RubyParserResult ( ) ; Node rootNode = new ShamNode ( ) ; rubyParserResult . setAST ( rootNode ) ; defaultRubyParser . setParserResult ( rubyParserResult ) ; TestRubyParser parser = new TestRubyParser ( ) ; parser . setDefaultRubyParser ( defaultRubyParser ) ; ShamFile file = new ShamFile ( "" ) ; file . setContents ( "" ) ; Node node = parser . parse ( file ) ; assertEquals ( rootNode , node ) ; file . assertContentStreamClosed ( ) ; } private static class TestRubyParser extends RubyParser { private DefaultRubyParser defaultRubyParser ; protected DefaultRubyParser getDefaultRubyParser ( ParserConfiguration config ) { return defaultRubyParser ; } public void setDefaultRubyParser ( DefaultRubyParser defaultRubyParser ) { this . defaultRubyParser = defaultRubyParser ; } @ Override protected void returnBorrowedParser ( @ SuppressWarnings ( "" ) DefaultRubyParser parser ) { } } private static class ShamDefaultRubyParser extends DefaultRubyParser { private RubyParserResult result ; public RubyParserResult parse ( ParserConfiguration config , LexerSource source ) { return result ; } public void setParserResult ( RubyParserResult rubyParserResult ) { result = rubyParserResult ; } } } package org . rubypeople . rdt . internal . core . parser ; import org . rubypeople . rdt . internal . core . parser . warnings . TS_InternalCoreParserWarnings ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_InternalCoreParser { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_TaskParser . class ) ; suite . addTestSuite ( TC_RubyParser . class ) ; suite . addTest ( TS_InternalCoreParserWarnings . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . internal . core . parser ; import java . util . List ; import org . jruby . ast . Node ; import org . jruby . ast . NodeType ; import org . jruby . ast . visitor . NodeVisitor ; import org . jruby . lexer . yacc . IDESourcePosition ; public class ShamNode extends Node { private static final long serialVersionUID = ; public ShamNode ( ) { super ( new IDESourcePosition ( ) ) ; } public Object accept ( NodeVisitor visitor ) { return null ; } public List < Node > childNodes ( ) { return null ; } public String toString ( ) { return "" ; } @ Override public NodeType getNodeType ( ) { return NodeType . SCOPENODE ; } } package org . rubypeople . rdt . internal . core . parser ; import java . io . StringReader ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import junit . framework . TestCase ; import org . eclipse . core . resources . IMarker ; import org . rubypeople . rdt . core . RubyCore ; public class TC_TaskParser extends TestCase { private static final String BASIC_MESSAGE = "" ; private static final String BASIC_MESSAGE_EXPECTED = "" ; private static final String ALTERNATE_MESSAGE = "" ; private static final String ALTERNATE_MESSAGE_EXPECTED = "" ; private Map preferences ; private TaskParser parser ; public void setUp ( ) { preferences = new HashMap ( ) ; preferences . put ( RubyCore . COMPILER_TASK_TAGS , "" ) ; parser = new TaskParser ( preferences ) ; } public void testSimpleTag ( ) { List tasks = parseTasks ( "" , BASIC_MESSAGE ) ; assertEquals ( , tasks . size ( ) ) ; assertTask ( BASIC_MESSAGE_EXPECTED , , , IMarker . PRIORITY_NORMAL , ( TaskTag ) tasks . get ( ) ) ; } public void testIndentedTag ( ) { List tasks = parseTasks ( "" , "" + BASIC_MESSAGE ) ; assertEquals ( , tasks . size ( ) ) ; assertTask ( BASIC_MESSAGE_EXPECTED , , , IMarker . PRIORITY_NORMAL , ( TaskTag ) tasks . get ( ) ) ; } public void testCaseInsensitive ( ) { preferences . put ( RubyCore . COMPILER_TASK_CASE_SENSITIVE , RubyCore . DISABLED ) ; List tasks = parseTasks ( "" , "" + BASIC_MESSAGE . toLowerCase ( ) ) ; assertEquals ( , tasks . size ( ) ) ; assertTask ( BASIC_MESSAGE_EXPECTED . toLowerCase ( ) , , , IMarker . PRIORITY_NORMAL , ( TaskTag ) tasks . get ( ) ) ; } public void testLineEndingCRLF ( ) { List tasks = parseTasks ( "" , "" + BASIC_MESSAGE ) ; assertEquals ( , tasks . size ( ) ) ; assertTask ( BASIC_MESSAGE_EXPECTED , , , IMarker . PRIORITY_NORMAL , ( TaskTag ) tasks . get ( ) ) ; } public void testLineEndingLF ( ) { List tasks = parseTasks ( "" , "" + BASIC_MESSAGE ) ; assertEquals ( , tasks . size ( ) ) ; assertTask ( BASIC_MESSAGE_EXPECTED , , , IMarker . PRIORITY_NORMAL , ( TaskTag ) tasks . get ( ) ) ; } public void testLineEndingCR ( ) { List tasks = parseTasks ( "" , "" + BASIC_MESSAGE ) ; assertEquals ( , tasks . size ( ) ) ; assertTask ( BASIC_MESSAGE_EXPECTED , , , IMarker . PRIORITY_NORMAL , ( TaskTag ) tasks . get ( ) ) ; } public void testLoadFromReader ( ) throws Exception { StringReader reader = new StringReader ( BASIC_MESSAGE + '' ) ; preferences . put ( RubyCore . COMPILER_TASK_TAGS , "" ) ; parser = new TaskParser ( preferences ) ; List tasks = parser . getTasks ( reader ) ; assertEquals ( , tasks . size ( ) ) ; assertTask ( "" , , , IMarker . PRIORITY_NORMAL , ( TaskTag ) tasks . get ( ) ) ; } public void testDifferentTag ( ) { List tasks = parseTasks ( "" , ALTERNATE_MESSAGE ) ; assertEquals ( , tasks . size ( ) ) ; assertTask ( ALTERNATE_MESSAGE_EXPECTED , , , IMarker . PRIORITY_HIGH , ( TaskTag ) tasks . get ( ) ) ; } public void testDoNotMatch ( ) { final String LINE = "" ; List tasks = parseTasks ( "" , LINE ) ; assertEquals ( "" + LINE , , tasks . size ( ) ) ; } private List parseTasks ( String validTags , String input ) { preferences . put ( RubyCore . COMPILER_TASK_TAGS , validTags ) ; parser = new TaskParser ( preferences ) ; List tasks = parser . getTasks ( input ) ; return tasks ; } private void assertTask ( String expectedMessage , int expectedStart , int expectedLineNumber , int expectedPriority , TaskTag actualTask ) { assertEquals ( "" , expectedMessage , actualTask . getMessage ( ) ) ; assertEquals ( "" , expectedStart , actualTask . getSourceStart ( ) ) ; assertEquals ( "" , expectedStart + expectedMessage . length ( ) , actualTask . getSourceEnd ( ) ) ; assertEquals ( "" , expectedLineNumber , actualTask . getSourceLineNumber ( ) ) ; assertEquals ( "" , expectedPriority , actualTask . getPriority ( ) ) ; } } package org . rubypeople . rdt . internal . core . search ; import org . rubypeople . rdt . internal . core . util . CharOperation ; import junit . framework . TestCase ; public class MethodPatternParserTest extends TestCase { public void testSelectorOnly ( ) { MethodPatternParser parser = new MethodPatternParser ( ) ; parser . parse ( "" ) ; assertStringEqualsCharArray ( "" , parser . getSelector ( ) ) ; assertNull ( parser . getTypeSimpleName ( ) ) ; assertNull ( parser . getQualifiedTypeName ( ) ) ; assertNull ( parser . getParameterNames ( ) ) ; } public void testSimpleTypeNameWithSelector ( ) { MethodPatternParser parser = new MethodPatternParser ( ) ; parser . parse ( "" ) ; assertStringEqualsCharArray ( "" , parser . getSelector ( ) ) ; assertStringEqualsCharArray ( "" , parser . getTypeSimpleName ( ) ) ; assertStringEqualsCharArray ( "" , parser . getQualifiedTypeName ( ) ) ; assertNull ( parser . getParameterNames ( ) ) ; } public void testQualifiedTypeNameWithSelector ( ) { MethodPatternParser parser = new MethodPatternParser ( ) ; parser . parse ( "" ) ; assertStringEqualsCharArray ( "" , parser . getSelector ( ) ) ; assertStringEqualsCharArray ( "" , parser . getTypeSimpleName ( ) ) ; assertStringEqualsCharArray ( "" , parser . getQualifiedTypeName ( ) ) ; assertNull ( parser . getParameterNames ( ) ) ; } public void testQualifiedTypeNameWithSelectorAndParameters ( ) { MethodPatternParser parser = new MethodPatternParser ( ) ; parser . parse ( "" ) ; assertStringEqualsCharArray ( "" , parser . getSelector ( ) ) ; assertStringEqualsCharArray ( "" , parser . getTypeSimpleName ( ) ) ; assertStringEqualsCharArray ( "" , parser . getQualifiedTypeName ( ) ) ; assertTrue ( CharOperation . equals ( new char [ ] [ ] { "" . toCharArray ( ) , "" . toCharArray ( ) } , parser . getParameterNames ( ) ) ) ; } private void assertStringEqualsCharArray ( String string , char [ ] selector ) { assertTrue ( CharOperation . equals ( string . toCharArray ( ) , selector ) ) ; } } package org . rubypeople . rdt . internal . core . search ; import junit . framework . Test ; import junit . framework . TestSuite ; public class AllTests { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( MethodPatternParserTest . class ) ; return suite ; } } package org . rubypeople . rdt . internal . core ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . internal . core . builder . TS_InternalCoreBuilder ; import org . rubypeople . rdt . internal . core . parser . TS_InternalCoreParser ; import org . rubypeople . rdt . internal . core . search . AllTests ; import org . rubypeople . rdt . internal . core . util . TS_Util ; public class TS_InternalCore { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_RubyCore . class ) ; suite . addTestSuite ( TC_RubyProject . class ) ; suite . addTestSuite ( TC_LoadPathEntry . class ) ; suite . addTest ( TS_InternalCoreBuilder . suite ( ) ) ; suite . addTest ( TS_InternalCoreParser . suite ( ) ) ; suite . addTest ( AllTests . suite ( ) ) ; suite . addTest ( TS_Util . suite ( ) ) ; return suite ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IWorkspaceRunnable ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . rubypeople . rdt . core . IRubyProject ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; public class TC_RubyProject extends ModifyingResourceTest { public TC_RubyProject ( String name ) { super ( name ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; setUpRubyProject ( "" ) ; } @ Override protected void tearDown ( ) throws Exception { deleteProject ( "" ) ; super . tearDown ( ) ; } public void testGetRequiredProjectNames ( ) throws CoreException { try { IRubyProject p2 = createRubyProject ( "" ) ; waitForAutoBuild ( ) ; editFile ( "" , "" ) ; waitForAutoBuild ( ) ; String [ ] required = p2 . getRequiredProjectNames ( ) ; assertEquals ( , required . length ) ; assertEquals ( "" , required [ ] ) ; assertEquals ( "" , required [ ] ) ; } finally { deleteProject ( "" ) ; } } public void testAddProjectPrerequisite ( ) throws CoreException { try { createRubyProject ( "" ) ; createRubyProject ( "" ) ; waitForAutoBuild ( ) ; editFile ( "" , "" + "" + "" + "" ) ; waitForAutoBuild ( ) ; IProject [ ] referencedProjects = getProject ( "" ) . getReferencedProjects ( ) ; assertResourcesEqual ( "" , "" , referencedProjects ) ; } finally { deleteProjects ( new String [ ] { "" , "" } ) ; } } public void testRubyScriptCorrespondingResource ( ) throws CoreException { addRubyNature ( "" ) ; createFolder ( "" ) ; createFile ( "" , "" ) ; IRubyScript element = getRubyScript ( "" , "" , "" , "" ) ; IResource corr = element . getCorrespondingResource ( ) ; IResource res = getWorkspace ( ) . getRoot ( ) . getProject ( "" ) . getFolder ( "" ) . getFile ( "" ) ; assertTrue ( "" , corr . equals ( res ) ) ; assertEquals ( "" , "" , corr . getProject ( ) . getName ( ) ) ; } public void testProjectOpen ( ) throws CoreException { try { createRubyProject ( "" ) ; createRubyProject ( "" , new String [ ] , new String [ ] , new String [ ] { "" } ) ; IProject p2 = getProject ( "" ) ; p2 . close ( null ) ; p2 . open ( null ) ; IProject [ ] references = p2 . getDescription ( ) . getDynamicReferences ( ) ; assertResourcesEqual ( "" , "" , references ) ; } finally { deleteProjects ( new String [ ] { "" , "" } ) ; } } public void testProjectImport ( ) throws CoreException { try { createRubyProject ( "" ) ; IWorkspaceRunnable runnable = new IWorkspaceRunnable ( ) { public void run ( IProgressMonitor monitor ) throws CoreException { createRubyProject ( "" ) ; editFile ( "" , "" + "" + "" + "" ) ; } } ; getWorkspace ( ) . run ( runnable , null ) ; waitForAutoBuild ( ) ; IProject [ ] referencedProjects = getProject ( "" ) . getReferencedProjects ( ) ; assertResourcesEqual ( "" , "" , referencedProjects ) ; } finally { deleteProjects ( new String [ ] { "" , "" } ) ; } } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . rubypeople . eclipse . testutils . ResourceTools ; import org . rubypeople . rdt . core . IRubyScript ; import org . rubypeople . rdt . core . RubyCore ; import org . rubypeople . rdt . core . tests . ModifyingResourceTest ; public class TC_RubyCore extends ModifyingResourceTest { public TC_RubyCore ( String name ) { super ( name ) ; } @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; try { this . createRubyProject ( "" , new String [ ] { "" } ) ; this . createFolder ( "" ) ; } catch ( CoreException e ) { e . printStackTrace ( ) ; } } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; this . deleteProject ( "" ) ; } public void testCreate ( ) throws CoreException { IFile file = createFile ( "" , "" ) ; IRubyScript rubyFile = RubyCore . create ( file ) ; assertNotNull ( "" , rubyFile ) ; assertEquals ( "" , file , rubyFile . getUnderlyingResource ( ) ) ; file = createFile ( "" , "" ) ; assertNull ( "" , RubyCore . create ( file ) ) ; } public void testAddRubyNature ( ) throws Exception { IProject project = ResourceTools . createProject ( "" ) ; RubyCore . addRubyNature ( project , null ) ; assertTrue ( project . hasNature ( RubyCore . NATURE_ID ) ) ; } } package org . rubypeople . rdt . internal . core ; import org . eclipse . core . resources . IMarkerDelta ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceChangeEvent ; import org . eclipse . core . resources . IResourceDelta ; import org . rubypeople . eclipse . shams . resources . ShamProject ; public class ShamResourceChangeEvent implements IResourceChangeEvent { public static ShamResourceChangeEvent forClose ( ShamProject project ) { return new ShamResourceChangeEvent ( PRE_CLOSE , project ) ; } public static ShamResourceChangeEvent forDelete ( ShamProject project ) { return new ShamResourceChangeEvent ( PRE_DELETE , project ) ; } private final int type ; private final IResourceDelta delta ; private final IResource resource ; public ShamResourceChangeEvent ( int type , IResourceDelta delta ) { this . type = type ; this . delta = delta ; this . resource = null ; } public ShamResourceChangeEvent ( int type , IResource resource ) { this . type = type ; this . resource = resource ; this . delta = null ; } public IMarkerDelta [ ] findMarkerDeltas ( String type , boolean includeSubtypes ) { return null ; } public int getBuildKind ( ) { return ; } public IResourceDelta getDelta ( ) { return delta ; } public IResource getResource ( ) { return resource ; } public Object getSource ( ) { return null ; } public int getType ( ) { return type ; } } package org . rubypeople . rdt . internal . core . util ; import junit . framework . TestCase ; import org . jruby . ast . Node ; import org . rubypeople . rdt . internal . core . parser . ClosestNodeLocator ; import org . rubypeople . rdt . internal . core . parser . RubyParser ; public class ASTUtilTest extends TestCase { public void testNamespace ( ) { RubyParser parser = new RubyParser ( ) ; String src = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Node root = parser . parse ( src ) . getAST ( ) ; assertEquals ( "" , ASTUtil . getNamespace ( root , ) ) ; assertEquals ( "" , ASTUtil . getNamespace ( root , ) ) ; assertEquals ( "" , ASTUtil . getNamespace ( root , ) ) ; assertEquals ( "" , ASTUtil . getNamespace ( root , ) ) ; } public void testFullyQualifiedTypename ( ) { RubyParser parser = new RubyParser ( ) ; String src = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Node root = parser . parse ( src ) . getAST ( ) ; assertEquals ( "" , ASTUtil . getFullyQualifiedTypeName ( root , new ClosestNodeLocator ( ) . getClosestNodeAtOffset ( root , ) ) ) ; } public void testFullyQualifiedTypenameOfTypeAtOffsetZero ( ) { RubyParser parser = new RubyParser ( ) ; String src = "" ; Node root = parser . parse ( src ) . getAST ( ) ; assertEquals ( "" , ASTUtil . getFullyQualifiedTypeName ( root , new ClosestNodeLocator ( ) . getClosestNodeAtOffset ( root , ) ) ) ; } } package org . rubypeople . rdt . internal . core . util ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_Util extends TestSuite { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( ASTUtilTest . class ) ; return suite ; } } package org . rubypeople . rdt . internal . core ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . eclipse . core . resources . IMarkerDelta ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . resources . IResourceDelta ; import org . eclipse . core . resources . IResourceDeltaVisitor ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IPath ; public class ShamResourceDelta implements IResourceDelta { private List children = new ArrayList ( ) ; private IResource resource ; private int kind ; private int flags ; public void accept ( IResourceDeltaVisitor visitor ) throws CoreException { if ( visitor . visit ( this ) ) { for ( Iterator iter = children . iterator ( ) ; iter . hasNext ( ) ; ) { IResourceDelta delta = ( IResourceDelta ) iter . next ( ) ; delta . accept ( visitor ) ; } } } public void accept ( IResourceDeltaVisitor visitor , boolean includePhantoms ) throws CoreException { } public void accept ( IResourceDeltaVisitor visitor , int memberFlags ) throws CoreException { } public IResourceDelta findMember ( IPath path ) { return null ; } public IResourceDelta [ ] getAffectedChildren ( ) { return ( IResourceDelta [ ] ) children . toArray ( new IResourceDelta [ ] ) ; } public IResourceDelta [ ] getAffectedChildren ( int kindMask ) { return null ; } public IResourceDelta [ ] getAffectedChildren ( int kindMask , int memberFlags ) { return null ; } public int getFlags ( ) { return flags ; } public IPath getFullPath ( ) { return resource . getFullPath ( ) ; } public int getKind ( ) { return kind ; } public IMarkerDelta [ ] getMarkerDeltas ( ) { return null ; } public IPath getMovedFromPath ( ) { return null ; } public IPath getMovedToPath ( ) { return null ; } public IPath getProjectRelativePath ( ) { return null ; } public IResource getResource ( ) { return resource ; } public Object getAdapter ( Class adapter ) { return null ; } public void setResource ( IResource resource ) { this . resource = resource ; } public void addChildren ( IResourceDelta delta ) { children . add ( delta ) ; } public void setKind ( int kind ) { this . kind = kind ; } public void setFlags ( int flags ) { this . flags = flags ; } } package org . rubypeople . rdt . internal . core . builder ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_InternalCoreBuilder { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; return suite ; } } package org . rubypeople . rdt . internal . formatter ; import java . io . IOException ; import java . io . InputStream ; import javax . xml . parsers . FactoryConfigurationError ; import javax . xml . parsers . ParserConfigurationException ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . xml . sax . SAXException ; public class TC_CodeFormatter extends AbstractCodeFormatterTestCase { public TC_CodeFormatter ( String name ) throws SAXException , IOException , ParserConfigurationException , FactoryConfigurationError { super ( name ) ; } protected CodeFormatter getCodeFormatter ( ) { return new OldCodeFormatter ( ) ; } protected InputStream getInputDataStream ( ) { return this . getClass ( ) . getResourceAsStream ( "" ) ; } public void testBeginRescueWithParenthesesInsideBeginBlock ( ) { doTest ( "" ) ; } public void testHashKeysLineUpAcrossMultipleLines ( ) { doTest ( "" ) ; } public void testMethodDefBadIndent ( ) { doTest ( "" ) ; } } package org . rubypeople . rdt . internal . formatter ; import java . io . IOException ; import java . io . InputStream ; import javax . xml . parsers . FactoryConfigurationError ; import javax . xml . parsers . ParserConfigurationException ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . xml . sax . SAXException ; public class TC_ASTBasedCodeFormatter extends AbstractCodeFormatterTestCase { public TC_ASTBasedCodeFormatter ( String name ) throws SAXException , IOException , ParserConfigurationException , FactoryConfigurationError { super ( name ) ; } @ Override protected CodeFormatter getCodeFormatter ( ) { return new ASTBasedCodeFormatter ( ) ; } @ Override protected InputStream getInputDataStream ( ) { return this . getClass ( ) . getResourceAsStream ( "" ) ; } public void testMethodDefBadIndent ( ) { doTest ( "" ) ; } } package org . rubypeople . rdt . internal . formatter ; import junit . framework . Test ; import junit . framework . TestSuite ; public class TS_InternalFormatter { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( TC_CodeFormatter . class ) ; suite . addTestSuite ( TC_ASTBasedCodeFormatter . class ) ; return suite ; } } package org . rubypeople . rdt . internal . formatter ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Hashtable ; import java . util . List ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . FactoryConfigurationError ; import javax . xml . parsers . ParserConfigurationException ; import junit . framework . Assert ; import junit . framework . TestCase ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . TextEdit ; import org . rubypeople . rdt . core . formatter . CodeFormatter ; import org . w3c . dom . Document ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . SAXException ; public abstract class AbstractCodeFormatterTestCase extends TestCase { private static class TestData { public TestData ( String formattedText , String unformattedText , String assertionMessage ) { this . formattedText = formattedText ; this . unformattedText = unformattedText ; this . assertionMessage = assertionMessage ; } public String formattedText ; public String unformattedText ; public String assertionMessage ; } private static final boolean VERBOSE = false ; private Hashtable < String , List < TestData > > testMap ; public AbstractCodeFormatterTestCase ( String name ) throws SAXException , IOException , ParserConfigurationException , FactoryConfigurationError { super ( name ) ; testMap = new Hashtable < String , List < TestData > > ( ) ; this . parseXmlConfiguration ( ) ; } private String stripFirstNewLine ( String input ) { return input . substring ( input . indexOf ( "" ) + ) ; } private void parseXmlConfiguration ( ) throws SAXException , IOException , ParserConfigurationException , FactoryConfigurationError { Document document = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . parse ( getInputDataStream ( ) ) ; NodeList tests = document . getElementsByTagName ( "" ) ; for ( int i = ; i < tests . getLength ( ) ; i ++ ) { Node test = tests . item ( i ) ; String name = test . getAttributes ( ) . getNamedItem ( "" ) . getNodeValue ( ) ; List < TestData > partList = new ArrayList < TestData > ( ) ; NodeList nl = test . getChildNodes ( ) ; createTestData ( partList , nl ) ; for ( int j = ; j < nl . getLength ( ) ; j ++ ) { Node partNode = nl . item ( j ) ; if ( partNode . getNodeName ( ) . equals ( "" ) ) { createTestData ( partList , partNode . getChildNodes ( ) ) ; } } testMap . put ( name , partList ) ; } } private void createTestData ( List < TestData > partList , NodeList partNodes ) { String formattedText = null ; String unformattedText = null ; String assertionMessage = null ; for ( int k = ; k < partNodes . getLength ( ) ; k ++ ) { Node node = partNodes . item ( k ) ; if ( node . getNodeName ( ) . equals ( "" ) ) { formattedText = this . stripFirstNewLine ( node . getFirstChild ( ) . getNodeValue ( ) ) ; } else if ( node . getNodeName ( ) . equals ( "" ) ) { unformattedText = this . stripFirstNewLine ( node . getFirstChild ( ) . getNodeValue ( ) ) ; } else if ( node . getNodeName ( ) . equals ( "" ) ) { assertionMessage = node . getFirstChild ( ) . getNodeValue ( ) . trim ( ) ; } } if ( formattedText != null && unformattedText != null ) { partList . add ( new TestData ( formattedText , unformattedText , assertionMessage ) ) ; } } protected void doTest ( String name ) { ArrayList < TestData > partList = ( ArrayList < TestData > ) testMap . get ( name ) ; for ( int i = ; i < partList . size ( ) ; i ++ ) { TestData data = ( TestData ) partList . get ( i ) ; TextEdit edit = getCodeFormatter ( ) . format ( - , data . unformattedText , , data . unformattedText . length ( ) , , "" ) ; IDocument doc = new org . eclipse . jface . text . Document ( data . unformattedText ) ; try { edit . apply ( doc ) ; } catch ( MalformedTreeException e ) { fail ( e . getMessage ( ) ) ; } catch ( BadLocationException e ) { fail ( e . getMessage ( ) ) ; } String formatted = doc . get ( ) ; log ( "" + data . assertionMessage + "" ) ; log ( data . unformattedText ) ; log ( "" ) ; log ( formatted ) ; Assert . assertEquals ( data . assertionMessage , data . formattedText , formatted ) ; } } protected abstract CodeFormatter getCodeFormatter ( ) ; protected abstract InputStream getInputDataStream ( ) ; private void log ( String formatted ) { if ( VERBOSE ) System . out . println ( formatted ) ; } public void testSimple ( ) { this . doTest ( "" ) ; } public void testBlockWithBrackets ( ) { this . doTest ( "" ) ; } public void testBlocks ( ) { this . doTest ( "" ) ; } public void testParameters ( ) { this . doTest ( "" ) ; } public void testLiterals ( ) { this . doTest ( "" ) ; } public void testLiteralsStartingWithPercentSign ( ) { this . doTest ( "" ) ; } public void testNegativeIndentation ( ) { this . doTest ( "" ) ; } public void testRescueModifier ( ) { doTest ( "" ) ; } public void testParen ( ) { doTest ( "" ) ; } public void testCaseWithWhens ( ) { doTest ( "" ) ; } } package org . rubypeople . rdt ; import junit . framework . Test ; import junit . framework . TestSuite ; import org . rubypeople . rdt . core . formatter . TC_EditableFormatHelper ; import org . rubypeople . rdt . core . formatter . TestReWriteVisitor ; import org . rubypeople . rdt . core . formatter . rewriter . TestBooleanStateStack ; import org . rubypeople . rdt . core . tests . model . BufferTests ; import org . rubypeople . rdt . core . util . TS_CoreUtil ; import org . rubypeople . rdt . internal . TS_Internal ; public class TS_RdtCore { public static Test suite ( ) { TestSuite suite = new TestSuite ( "" ) ; suite . addTestSuite ( BufferTests . class ) ; suite . addTest ( TS_CoreUtil . suite ( ) ) ; suite . addTest ( TS_Internal . suite ( ) ) ; suite . addTestSuite ( TestBooleanStateStack . class ) ; suite . addTestSuite ( TC_EditableFormatHelper . class ) ; suite . addTestSuite ( TestReWriteVisitor . class ) ; return suite ; } } package org . oddjob . tools ; import java . io . BufferedReader ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . io . OutputStreamWriter ; import java . io . PrintWriter ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . oddjob . tools . includes . JavaCodeFileLoader ; import org . oddjob . tools . includes . XMLFileLoader ; import org . oddjob . tools . includes . XMLResourceLoader ; public class DocPostProcessor implements Runnable { private File baseDir ; private InputStream input ; private OutputStream output ; @ Override public void run ( ) { Injector injector1 = new JavaCodeInjector ( ) ; Injector injector2 = new XMLResourceInjector ( ) ; Injector injector3 = new XMLFileInjector ( ) ; try { BufferedReader reader = new BufferedReader ( new InputStreamReader ( input ) ) ; PrintWriter writer = new PrintWriter ( new OutputStreamWriter ( output ) ) ; while ( true ) { String line = reader . readLine ( ) ; if ( line == null ) { break ; } if ( ! injector1 . parse ( line , writer ) && ! injector2 . parse ( line , writer ) && ! injector3 . parse ( line , writer ) ) { writer . println ( line ) ; } } reader . close ( ) ; writer . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } public File getBaseDir ( ) { return baseDir ; } public void setBaseDir ( File baseDir ) { this . baseDir = baseDir ; } public InputStream getInput ( ) { return input ; } public void setInput ( InputStream input ) { this . input = input ; } public OutputStream getOutput ( ) { return output ; } public void setOutput ( OutputStream output ) { this . output = output ; } interface Injector { public boolean parse ( String line , PrintWriter out ) ; } class JavaCodeInjector implements Injector { final Pattern pattern = Pattern . compile ( "" + JavaCodeFileLoader . JAVA_FILE_TAG + "" ) ; @ Override public boolean parse ( String line , PrintWriter out ) { Matcher matcher = pattern . matcher ( line ) ; if ( ! matcher . find ( ) ) { return false ; } out . println ( new JavaCodeFileLoader ( baseDir ) . load ( matcher . group ( ) ) ) ; return true ; } } static class XMLResourceInjector implements Injector { final Pattern pattern = Pattern . compile ( "" + XMLResourceLoader . XML_RESOURCE_TAG + "" ) ; @ Override public boolean parse ( String line , PrintWriter out ) { Matcher matcher = pattern . matcher ( line ) ; if ( ! matcher . find ( ) ) { return false ; } out . println ( new XMLResourceLoader ( ) . load ( matcher . group ( ) ) ) ; return true ; } } class XMLFileInjector implements Injector { final Pattern pattern = Pattern . compile ( "" + XMLFileLoader . XML_FILE_TAG + "" ) ; @ Override public boolean parse ( String line , PrintWriter out ) { Matcher matcher = pattern . matcher ( line ) ; if ( ! matcher . find ( ) ) { return false ; } out . println ( new XMLFileLoader ( baseDir ) . load ( matcher . group ( ) ) ) ; return true ; } } } package org . oddjob . tools . doclet . utils ; import org . oddjob . tools . includes . XMLResourceLoader ; import com . sun . javadoc . Tag ; public class XMLResourceTagProcessor implements TagProcessor { @ Override public String process ( Tag tag ) { if ( ! tag . name ( ) . equals ( XMLResourceLoader . XML_RESOURCE_TAG ) ) { return null ; } String path = tag . text ( ) ; return new XMLResourceLoader ( ) . load ( path ) ; } } package org . oddjob . tools . doclet . utils ; import com . sun . javadoc . Tag ; public class InlineTagsProcessor implements TagsProcessor { @ Override public String process ( Tag [ ] tags ) { StringBuilder builder = new StringBuilder ( ) ; TagProcessor tagProcessor = new CompositeTagProcessor ( new SeeTagProcessor ( ) , new XMLResourceTagProcessor ( ) , new FallbackTagProcessor ( ) ) ; for ( Tag tag : tags ) { String snippet = tagProcessor . process ( tag ) ; if ( snippet != null ) { builder . append ( snippet ) ; } } return builder . toString ( ) ; } } package org . oddjob . tools . doclet . utils ; import com . sun . javadoc . ClassDoc ; import com . sun . javadoc . SeeTag ; import com . sun . javadoc . Tag ; public class SeeTagProcessor implements TagProcessor { @ Override public String process ( Tag tag ) { if ( ! ( tag instanceof SeeTag ) ) { return null ; } SeeTag seeTag = ( SeeTag ) tag ; ClassDoc referencedClassDoc = seeTag . referencedClass ( ) ; String simpleClassName = referencedClassDoc . name ( ) ; String referencedClassName = seeTag . referencedClassName ( ) ; String fileName = referencedClassName . replace ( '' , '' ) + "" ; String rootDir = new ClassDocUtils ( seeTag . holder ( ) ) . getRelativeRootDir ( ) ; return ( "" + rootDir + "" + fileName + "" + simpleClassName + "" ) ; } } package org . oddjob . tools . doclet . utils ; import com . sun . javadoc . Tag ; public class CompositeTagProcessor implements TagProcessor { private final TagProcessor [ ] processors ; public CompositeTagProcessor ( TagProcessor ... processors ) { this . processors = processors ; } @ Override public String process ( Tag tag ) { for ( TagProcessor processor : processors ) { String snipet = processor . process ( tag ) ; if ( snipet != null ) { return snipet ; } } return null ; } } package org . oddjob . tools . doclet . utils ; import com . sun . javadoc . Tag ; public interface TagsProcessor { public String process ( Tag [ ] tags ) ; } package org . oddjob . tools . doclet . utils ; import com . sun . javadoc . ClassDoc ; import com . sun . javadoc . Doc ; import com . sun . javadoc . FieldDoc ; import com . sun . javadoc . MethodDoc ; public class ClassDocUtils { private final ClassDoc classDoc ; public ClassDocUtils ( Doc doc ) { if ( doc instanceof ClassDoc ) { classDoc = ( ClassDoc ) doc ; } else if ( doc instanceof MethodDoc ) { classDoc = ( ( MethodDoc ) doc ) . containingClass ( ) ; } else if ( doc instanceof FieldDoc ) { classDoc = ( ( FieldDoc ) doc ) . containingClass ( ) ; } else { throw new IllegalArgumentException ( "" + doc . getClass ( ) + "" ) ; } } public String getRelativeRootDir ( ) { String [ ] packages = classDoc . containingPackage ( ) . name ( ) . split ( ( "" ) ) ; String rootDir = "" ; for ( int i = ; i < packages . length ; ++ i ) { rootDir = rootDir + ( i == ? "" : "" ) + "" ; } return rootDir ; } } package org . oddjob . tools . doclet . utils ; import com . sun . javadoc . Tag ; public interface TagProcessor { public String process ( Tag tag ) ; } package org . oddjob . tools . doclet . utils ; import com . sun . javadoc . Tag ; public class FallbackTagProcessor implements TagProcessor { @ Override public String process ( Tag tag ) { return tag . text ( ) ; } } package org . oddjob . tools . taglet ; import java . util . Map ; import org . oddjob . doclet . CustomTagNames ; import com . sun . tools . doclets . Taglet ; public class ExampleTaglet extends BaseBlockTaglet { public static void register ( Map < String , Taglet > tagletMap ) { tagletMap . put ( CustomTagNames . EXAMPLE_TAG_NAME , new ExampleTaglet ( ) ) ; } @ Override public boolean inType ( ) { return true ; } @ Override public boolean inField ( ) { return false ; } @ Override public boolean inMethod ( ) { return false ; } @ Override public String getName ( ) { return CustomTagNames . EXAMPLE_TAG_NAME ; } @ Override public String getTitle ( ) { return "" ; } } package org . oddjob . tools . taglet ; import java . util . Map ; import org . oddjob . doclet . CustomTagNames ; import com . sun . tools . doclets . Taglet ; public class PropertyTaglet extends BaseBlockTaglet { public static void register ( Map < String , Taglet > tagletMap ) { tagletMap . put ( CustomTagNames . PROPERTY_TAG_NAME , new PropertyTaglet ( ) ) ; } @ Override public boolean inField ( ) { return true ; } @ Override public boolean inMethod ( ) { return true ; } @ Override public boolean inType ( ) { return false ; } @ Override public String getName ( ) { return CustomTagNames . PROPERTY_TAG_NAME ; } @ Override public String getTitle ( ) { return "" ; } } package org . oddjob . tools . taglet ; import java . util . Map ; import org . oddjob . doclet . CustomTagNames ; import com . sun . tools . doclets . Taglet ; public class DescriptionTaglet extends BaseBlockTaglet { public static void register ( Map < String , Taglet > tagletMap ) { tagletMap . put ( CustomTagNames . DESCRIPTION_TAG_NAME , new DescriptionTaglet ( ) ) ; } @ Override public boolean inType ( ) { return true ; } @ Override public boolean inField ( ) { return true ; } @ Override public boolean inMethod ( ) { return true ; } @ Override public String getName ( ) { return CustomTagNames . DESCRIPTION_TAG_NAME ; } @ Override public String getTitle ( ) { return "" ; } } package org . oddjob . tools . taglet ; import org . oddjob . tools . doclet . utils . InlineTagsProcessor ; import com . sun . javadoc . ClassDoc ; import com . sun . javadoc . Tag ; import com . sun . tools . doclets . Taglet ; abstract public class BaseBlockTaglet implements Taglet { @ Override final public boolean inConstructor ( ) { return false ; } @ Override final public boolean inOverview ( ) { return false ; } @ Override final public boolean inPackage ( ) { return false ; } @ Override final public boolean isInlineTag ( ) { return false ; } @ Override public String toString ( Tag tag ) { String text = new InlineTagsProcessor ( ) . process ( tag . inlineTags ( ) ) ; if ( tag . holder ( ) instanceof ClassDoc ) { return "" + getTitle ( ) + "" + text ; } else { return "" + getTitle ( ) + "" + text ; } } @ Override public String toString ( Tag [ ] tags ) { StringBuilder builder = new StringBuilder ( ) ; for ( Tag tag : tags ) { builder . append ( toString ( tag ) ) ; } return builder . toString ( ) ; } abstract public String getTitle ( ) ; } package org . oddjob . tools . taglet ; import java . util . Map ; import org . oddjob . doclet . CustomTagNames ; import com . sun . tools . doclets . Taglet ; public class RequiredTaglet extends BaseBlockTaglet { public static void register ( Map < String , Taglet > tagletMap ) { tagletMap . put ( CustomTagNames . REQUIRED_TAG_NAME , new RequiredTaglet ( ) ) ; } @ Override public boolean inField ( ) { return true ; } @ Override public boolean inMethod ( ) { return true ; } @ Override public boolean inType ( ) { return false ; } @ Override public String getName ( ) { return CustomTagNames . REQUIRED_TAG_NAME ; } @ Override public String getTitle ( ) { return "" ; } } package org . oddjob . tools . includes ; import java . io . IOException ; import java . io . PrintWriter ; import java . io . Reader ; import java . io . StringReader ; import java . io . StringWriter ; import java . util . ArrayList ; import java . util . List ; public class Java2HTML { private static final String keywords [ ] = { "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" } ; private static List < String > keyw = new ArrayList < String > ( keywords . length ) ; static { for ( int i = ; i < keywords . length ; i ++ ) keyw . add ( keywords [ i ] ) ; } private int tabsize = ; private String kwcolor = "" , cmcolor = "" , c2color = "" , stcolor = "" ; public String convert ( String input ) throws IOException { Reader in = new StringReader ( input ) ; StringWriter string = new StringWriter ( ) ; PrintWriter out = new PrintWriter ( string ) ; out . println ( "" ) ; StringBuffer buf = new StringBuffer ( ) ; int c = , kwl = , bufl = ; int nexttolast = ; char ch = , lastch = ; int s_normal = ; int s_string = ; int s_char = ; int s_comline = ; int s_comment = ; int state = s_normal ; while ( c != - ) { c = in . read ( ) ; nexttolast = lastch ; lastch = ch ; ch = c >= ? ( char ) c : ; if ( state == s_normal ) if ( kwl == && Character . isJavaIdentifierStart ( ch ) && ! Character . isJavaIdentifierPart ( lastch ) || kwl > && Character . isJavaIdentifierPart ( ch ) ) { buf . append ( ch ) ; bufl ++ ; kwl ++ ; continue ; } else if ( kwl > ) { String kw = buf . toString ( ) . substring ( buf . length ( ) - kwl ) ; if ( keyw . contains ( kw ) ) { buf . insert ( buf . length ( ) - kwl , "" + kwcolor + "" ) ; buf . append ( "" ) ; } kwl = ; } switch ( ch ) { case '' : buf . append ( "" ) ; bufl ++ ; break ; case '' : buf . append ( "" ) ; bufl ++ ; if ( state == s_normal ) { state = s_string ; buf . insert ( buf . length ( ) - "" . length ( ) , "" + stcolor + "" ) ; } else if ( state == s_string && ( ( lastch != '' ) || ( lastch == '' && nexttolast == '' ) ) ) { buf . append ( "" ) ; state = s_normal ; } break ; case '' : buf . append ( "" ) ; bufl ++ ; if ( state == s_normal ) state = s_char ; else if ( state == s_char && lastch != '' ) state = s_normal ; break ; case '' : buf . append ( "" ) ; bufl ++ ; if ( lastch == '' ) nexttolast = '' ; if ( lastch == '' && ( state == s_string || state == s_char ) ) ; break ; case '' : buf . append ( "" ) ; bufl ++ ; if ( state == s_string || state == s_comline ) break ; if ( state == s_comment && lastch == '' ) { buf . append ( "" ) ; state = s_normal ; } if ( state == s_comment ) break ; if ( lastch == '' ) { buf . insert ( buf . length ( ) - , "" + cmcolor + "" ) ; state = s_comline ; } break ; case '' : buf . append ( "" ) ; bufl ++ ; if ( state == s_normal && lastch == '' ) { buf . insert ( buf . length ( ) - , "" + c2color + "" ) ; state = s_comment ; } break ; case '' : buf . append ( "" ) ; bufl ++ ; break ; case '>' : buf . append ( "" ) ; bufl ++ ; break ; case '' : int n = bufl / tabsize * tabsize + tabsize ; while ( bufl < n ) { buf . append ( '' ) ; bufl ++ ; } break ; case '' : case '' : if ( state == s_comline ) { buf . append ( "" ) ; state = s_normal ; } buf . append ( ch ) ; if ( buf . length ( ) >= ) { out . write ( buf . toString ( ) ) ; buf . setLength ( ) ; } bufl = ; if ( kwl != ) kwl = ; if ( state != s_normal && state != s_comment ) state = s_normal ; break ; case : if ( c < ) { if ( state == s_comline ) { buf . append ( "" ) ; state = s_normal ; } out . write ( buf . toString ( ) ) ; buf . setLength ( ) ; bufl = ; if ( state == s_comment ) { buf . append ( "" ) ; state = s_normal ; } break ; } default : bufl ++ ; buf . append ( ch ) ; } } out . println ( "" ) ; in . close ( ) ; out . close ( ) ; return string . toString ( ) ; } public int getTabsize ( ) { return tabsize ; } public void setTabsize ( int tabsize ) { this . tabsize = tabsize ; } public String getKwcolor ( ) { return kwcolor ; } public void setKwcolor ( String kwcolor ) { this . kwcolor = kwcolor ; } public String getCmcolor ( ) { return cmcolor ; } public void setCmcolor ( String cmcolor ) { this . cmcolor = cmcolor ; } public String getC2color ( ) { return c2color ; } public void setC2color ( String c2color ) { this . c2color = c2color ; } public String getStcolor ( ) { return stcolor ; } public void setStcolor ( String stcolor ) { this . stcolor = stcolor ; } } package org . oddjob . tools . includes ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . InputStream ; import org . apache . log4j . Logger ; import org . oddjob . doclet . CustomTagNames ; import org . oddjob . jobs . XSLTJob ; public class XMLFileLoader implements IncludeLoader , CustomTagNames { private static final Logger logger = Logger . getLogger ( XMLFileLoader . class ) ; private static final String EOL = System . getProperty ( "" ) ; private final File base ; public XMLFileLoader ( File base ) { this . base = base ; } @ Override public boolean canLoad ( String tag ) { return XML_FILE_TAG . equals ( tag ) ; } @ Override public String load ( String fileName ) { try { FilterFactory filterFactory = new FilterFactory ( fileName ) ; File file = new File ( base , filterFactory . getResourcePath ( ) ) ; logger . info ( "" + file ) ; InputStream input = new FileInputStream ( file ) ; String xml = filterFactory . getTextLoader ( ) . load ( input ) ; InputStream stylesheet = getClass ( ) . getResourceAsStream ( "" ) ; ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; XSLTJob transform = new XSLTJob ( ) ; transform . setStylesheet ( stylesheet ) ; transform . setInput ( new ByteArrayInputStream ( xml . getBytes ( ) ) ) ; transform . setOutput ( result ) ; transform . run ( ) ; return "" + EOL + new String ( result . toByteArray ( ) ) + "" + EOL ; } catch ( Exception e ) { return "" + e . toString ( ) + "" + EOL ; } } } package org . oddjob . tools . includes ; public interface IncludeLoader { public boolean canLoad ( String tag ) ; public String load ( String path ) ; } package org . oddjob . tools . includes ; import java . util . HashMap ; import java . util . Map ; public class CompositeLoader implements IncludeLoader { private Map < String , IncludeLoader > loaders = new HashMap < String , IncludeLoader > ( ) ; private IncludeLoader selected ; public CompositeLoader ( ) { loaders . put ( JavaCodeResourceLoader . TAG , new JavaCodeResourceLoader ( ) ) ; loaders . put ( XMLResourceLoader . XML_RESOURCE_TAG , new XMLResourceLoader ( ) ) ; } @ Override public boolean canLoad ( String tag ) { selected = loaders . get ( tag ) ; return selected != null ; } @ Override public String load ( String path ) { if ( selected == null ) { throw new IllegalStateException ( "" ) ; } return selected . load ( path ) ; } } package org . oddjob . tools . includes ; import java . io . File ; import java . io . FileInputStream ; import org . apache . log4j . Logger ; import org . oddjob . doclet . CustomTagNames ; public class JavaCodeFileLoader implements IncludeLoader , CustomTagNames { private static final Logger logger = Logger . getLogger ( JavaCodeFileLoader . class ) ; private static final String EOL = System . getProperty ( "" ) ; private final File base ; public JavaCodeFileLoader ( File base ) { this . base = base ; } @ Override public boolean canLoad ( String tag ) { return JAVA_FILE_TAG . equals ( tag ) ; } public String load ( String path ) { try { FilterFactory filterFactory = new FilterFactory ( path ) ; File file = new File ( base , filterFactory . getResourcePath ( ) ) ; logger . info ( "" + file ) ; String result = filterFactory . getTextLoader ( ) . load ( new FileInputStream ( file ) ) ; Java2HTML java2html = new Java2HTML ( ) ; return java2html . convert ( result ) ; } catch ( Exception e ) { return "" + e . toString ( ) + "" + EOL ; } } } package org . oddjob . tools . includes ; import java . io . InputStream ; import org . apache . log4j . Logger ; import org . oddjob . io . ResourceType ; public class JavaCodeResourceLoader implements IncludeLoader { private static final Logger logger = Logger . getLogger ( JavaCodeResourceLoader . class ) ; private static final String EOL = System . getProperty ( "" ) ; public static final String TAG = "" ; @ Override public boolean canLoad ( String tag ) { return TAG . equals ( tag ) ; } public String load ( String path ) { try { FilterFactory filterFactory = new FilterFactory ( path ) ; String resource = filterFactory . getResourcePath ( ) ; InputStream input = new ResourceType ( resource ) . toInputStream ( ) ; logger . info ( "" + resource ) ; String result = filterFactory . getTextLoader ( ) . load ( input ) ; Java2HTML java2html = new Java2HTML ( ) ; return java2html . convert ( result ) ; } catch ( Exception e ) { return "" + e . toString ( ) + "" + EOL ; } } } package org . oddjob . tools . includes ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class SnippetFilter implements StreamToText { private final Pattern start ; private final Pattern end ; public SnippetFilter ( String filter ) { start = Pattern . compile ( "" + Pattern . quote ( filter ) + "" ) ; end = Pattern . compile ( "" + Pattern . quote ( filter ) + "" ) ; } @ Override public String load ( InputStream input ) throws IOException { BufferedReader reader = new BufferedReader ( new InputStreamReader ( input ) ) ; StringWriter buff = new StringWriter ( ) ; PrintWriter writer = new PrintWriter ( buff ) ; boolean record = false ; while ( true ) { String line = reader . readLine ( ) ; if ( line == null ) { break ; } if ( record ) { Matcher matcher = end . matcher ( line ) ; if ( matcher . find ( ) ) { record = false ; } else { writer . println ( line ) ; } } else { Matcher matcher = start . matcher ( line ) ; if ( matcher . find ( ) ) { record = true ; } } } reader . close ( ) ; writer . close ( ) ; return buff . toString ( ) ; } } package org . oddjob . tools . includes ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . InputStream ; import org . oddjob . doclet . CustomTagNames ; import org . oddjob . io . ResourceType ; import org . oddjob . jobs . XSLTJob ; public class XMLResourceLoader implements IncludeLoader , CustomTagNames { private static final String EOL = System . getProperty ( "" ) ; @ Override public boolean canLoad ( String tag ) { return XML_RESOURCE_TAG . equals ( tag ) ; } @ Override public String load ( String resource ) { try { FilterFactory filterFactory = new FilterFactory ( resource ) ; InputStream input = new ResourceType ( filterFactory . getResourcePath ( ) ) . toInputStream ( ) ; String xml = filterFactory . getTextLoader ( ) . load ( input ) ; InputStream stylesheet = getClass ( ) . getResourceAsStream ( "" ) ; ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; XSLTJob transform = new XSLTJob ( ) ; transform . setStylesheet ( stylesheet ) ; transform . setInput ( new ByteArrayInputStream ( xml . getBytes ( ) ) ) ; transform . setOutput ( result ) ; transform . run ( ) ; return "" + EOL + new String ( result . toByteArray ( ) ) + "" + EOL ; } catch ( Exception e ) { return "" + e . toString ( ) + "" + EOL ; } } } package org . oddjob . tools . includes ; import java . io . IOException ; import java . io . InputStream ; public interface StreamToText { public String load ( InputStream input ) throws IOException ; } package org . oddjob . tools . includes ; import java . io . BufferedInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import org . oddjob . util . IO ; public class PlainStreamToText implements StreamToText { @ Override public String load ( InputStream input ) throws IOException { BufferedInputStream in = new BufferedInputStream ( input ) ; ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; IO . copy ( in , result ) ; in . close ( ) ; result . close ( ) ; return result . toString ( ) ; } } package org . oddjob . tools . includes ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class FilterFactory { public final static Pattern PATTERN = Pattern . compile ( "" ) ; private final StreamToText textLoader ; private final String resourcePath ; public FilterFactory ( String path ) { Matcher matcher = PATTERN . matcher ( path ) ; if ( ! matcher . matches ( ) ) { throw new IllegalArgumentException ( "" + path ) ; } this . resourcePath = matcher . group ( ) ; String snippet = matcher . group ( ) ; if ( snippet == null ) { textLoader = new PlainStreamToText ( ) ; } else { textLoader = new SnippetFilter ( snippet ) ; } } public StreamToText getTextLoader ( ) { return textLoader ; } public String getResourcePath ( ) { return resourcePath ; } } package org . oddjob . doclet ; public class IndexLine { private final String className ; private final String name ; private final String firstSentence ; public IndexLine ( String className , String name , String firstLine ) { this . className = className ; this . name = name ; this . firstSentence = firstLine ; } public String getClassName ( ) { return className ; } public String getName ( ) { return name ; } public String getFirstSentence ( ) { return firstSentence ; } } package org . oddjob . doclet ; import java . io . File ; import org . oddjob . Oddjob ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . beandocs . SessionArooaDocFactory ; import org . oddjob . arooa . beandocs . WriteableArooaDoc ; import org . oddjob . arooa . convert . convertlets . FileConvertlets ; import org . oddjob . arooa . deploy . ClassPathDescriptorFactory ; import org . oddjob . arooa . deploy . LinkedDescriptor ; import org . oddjob . arooa . standard . BaseArooaDescriptor ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . util . URLClassLoaderType ; import com . sun . javadoc . ClassDoc ; import com . sun . javadoc . DocErrorReporter ; import com . sun . javadoc . RootDoc ; public class ManualDoclet { private final JobsAndTypes jats ; private final Archiver archiver ; public ManualDoclet ( String classPath , String descriptorResource ) { SessionArooaDocFactory docsFactory ; ClassPathDescriptorFactory factory = new ClassPathDescriptorFactory ( ) ; if ( descriptorResource != null ) { factory . setResource ( descriptorResource ) ; } if ( classPath == null ) { ArooaDescriptor descriptor = factory . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; docsFactory = new SessionArooaDocFactory ( new StandardArooaSession ( descriptor ) ) ; } else { File [ ] files = new FileConvertlets ( ) . pathToFiles ( classPath ) ; URLClassLoaderType classLoaderType = new URLClassLoaderType ( ) ; classLoaderType . setFiles ( files ) ; classLoaderType . setParent ( getClass ( ) . getClassLoader ( ) ) ; factory . setExcludeParent ( true ) ; ClassLoader classLoader = classLoaderType . toValue ( ) ; ArooaDescriptor thisDescriptor = factory . createDescriptor ( classLoader ) ; if ( thisDescriptor == null ) { throw new NullPointerException ( "" + classPath ) ; } ArooaDescriptor descriptor = new LinkedDescriptor ( thisDescriptor , new BaseArooaDescriptor ( classLoader ) ) ; docsFactory = new SessionArooaDocFactory ( new StandardArooaSession ( ) , descriptor ) ; } WriteableArooaDoc jobs = docsFactory . createBeanDocs ( ArooaType . COMPONENT ) ; WriteableArooaDoc types = docsFactory . createBeanDocs ( ArooaType . VALUE ) ; this . jats = new JobsAndTypes ( jobs , types ) ; this . archiver = new Archiver ( jats ) ; } JobsAndTypes jobsAndTypes ( ) { return jats ; } void process ( ClassDoc cd ) { archiver . archive ( cd ) ; } void process ( RootDoc rootDoc , String destination , String title ) { ClassDoc [ ] cd = rootDoc . classes ( ) ; System . out . println ( "" + cd . length + "" ) ; for ( int i = ; i < cd . length ; ++ i ) { process ( cd [ i ] ) ; } ManualWriter w = new ManualWriter ( destination , title ) ; w . createManual ( archiver ) ; } public static boolean start ( RootDoc rootDoc ) { System . out . println ( "" ) ; ClassLoader loader = ManualDoclet . class . getClassLoader ( ) ; System . out . println ( "" ) ; for ( ClassLoader next = loader ; next != null ; next = next . getParent ( ) ) { System . out . println ( "" + next ) ; } Oddjob test = new Oddjob ( ) ; System . out . println ( test ) ; Options options = readOptions ( rootDoc . options ( ) ) ; ManualDoclet md = new ManualDoclet ( options . getDescriptorPath ( ) , options . getResource ( ) ) ; md . process ( rootDoc , options . getDestination ( ) , options . getTitle ( ) ) ; return true ; } private static Options readOptions ( String [ ] [ ] options ) { Options result = new Options ( ) ; for ( int i = ; i < options . length ; i ++ ) { String [ ] opt = options [ i ] ; if ( opt [ ] . equals ( "" ) ) { result . setDestination ( opt [ ] ) ; } else if ( opt [ ] . equals ( "" ) ) { result . setDescriptorPath ( opt [ ] ) ; } else if ( opt [ ] . equals ( "" ) ) { result . setResource ( opt [ ] ) ; } else if ( opt [ ] . equals ( "" ) ) { result . setTitle ( opt [ ] ) ; } } return result ; } public static int optionLength ( String option ) { if ( option . equals ( "" ) ) { return ; } if ( option . equals ( "" ) ) { return ; } if ( option . equals ( "" ) ) { return ; } if ( option . equals ( "" ) ) { return ; } return ; } public static boolean validOptions ( String options [ ] [ ] , DocErrorReporter reporter ) { boolean foundDestination = false ; boolean foundPath = false ; boolean foundResource = false ; boolean foundTitle = false ; boolean ok = true ; for ( int i = ; i < options . length ; i ++ ) { String [ ] opt = options [ i ] ; if ( opt [ ] . equals ( "" ) ) { if ( foundDestination ) { reporter . printError ( "" ) ; ok = false ; } else { foundDestination = true ; } } if ( opt [ ] . equals ( "" ) ) { if ( foundPath ) { reporter . printError ( "" ) ; ok = false ; } else { foundPath = true ; } } if ( opt [ ] . equals ( "" ) ) { if ( foundResource ) { reporter . printError ( "" ) ; ok = false ; } else { foundResource = true ; } } if ( opt [ ] . equals ( "" ) ) { if ( foundTitle ) { reporter . printError ( "" ) ; ok = false ; } else { foundTitle = true ; } } } if ( ! foundDestination ) { ok = false ; } if ( ! ok ) { reporter . printError ( "" + "" + "" + "" + "" ) ; } return ok ; } private static class Options { private String destination ; private String descriptorPath ; private String resource ; private String title ; public String getDestination ( ) { return destination ; } public void setDestination ( String destination ) { this . destination = destination ; } public String getDescriptorPath ( ) { return descriptorPath ; } public void setDescriptorPath ( String resource ) { this . descriptorPath = resource ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } public String getResource ( ) { return resource ; } public void setResource ( String resource ) { this . resource = resource ; } } } package org . oddjob . doclet ; import java . util . HashMap ; import java . util . LinkedHashMap ; import java . util . Map ; import org . oddjob . arooa . beandocs . BeanDoc ; import org . oddjob . arooa . beandocs . WriteableArooaDoc ; import org . oddjob . arooa . beandocs . WriteableBeanDoc ; public class JobsAndTypes { private final Map < String , BeanDoc > jobDocs = new LinkedHashMap < String , BeanDoc > ( ) ; private final Map < String , BeanDoc > typeDocs = new LinkedHashMap < String , BeanDoc > ( ) ; private final Map < String , WriteableBeanDoc > docsByName = new HashMap < String , WriteableBeanDoc > ( ) ; public JobsAndTypes ( WriteableArooaDoc jobDocs , WriteableArooaDoc typeDocs ) { loadProps ( jobDocs , this . jobDocs ) ; loadProps ( typeDocs , this . typeDocs ) ; } void loadProps ( WriteableArooaDoc doc , Map < String , BeanDoc > into ) { WriteableBeanDoc [ ] beanDocs = doc . getBeanDocs ( ) ; for ( WriteableBeanDoc beanDoc : beanDocs ) { String className = beanDoc . getClassName ( ) ; WriteableBeanDoc list = docsByName . get ( className ) ; if ( list == null ) { list = beanDoc ; docsByName . put ( className , list ) ; } into . put ( beanDoc . getName ( ) , list ) ; } } public WriteableBeanDoc docFor ( String fqcn ) { return docsByName . get ( fqcn ) ; } public Iterable < String > types ( ) { return typeDocs . keySet ( ) ; } public BeanDoc docForType ( String name ) { return typeDocs . get ( name ) ; } public Iterable < String > jobs ( ) { return jobDocs . keySet ( ) ; } public BeanDoc docForJob ( String name ) { return jobDocs . get ( name ) ; } public Iterable < ? extends BeanDoc > all ( ) { return docsByName . values ( ) ; } } package org . oddjob . doclet ; public class Property { private final String name ; private String description ; private String required ; public Property ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } this . name = name ; } public String getName ( ) { return name ; } public void setDescription ( String description ) { this . description = description ; } public String getDescription ( ) { return description ; } public void setRequired ( String required ) { this . required = required ; } public String getRequired ( ) { return required ; } } package org . oddjob . doclet ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . PrintWriter ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . beandocs . BeanDoc ; import org . oddjob . arooa . beandocs . ExampleDoc ; import org . oddjob . arooa . beandocs . PropertyDoc ; public class ManualWriter { private final File directory ; private final String title ; public ManualWriter ( String directory , String title ) { this . directory = new File ( directory ) ; this . title = title == null ? "" : title ; } public void writePage ( BeanDoc beanDoc ) { PrintWriter out = null ; try { File file = new File ( directory , getFileName ( beanDoc . getClassName ( ) ) ) ; file . getParentFile ( ) . mkdirs ( ) ; out = new PrintWriter ( new FileOutputStream ( file ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" + title + "" + beanDoc . getName ( ) + "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" + getIndexFile ( beanDoc . getClassName ( ) ) + "" ) ; out . println ( "" + beanDoc . getName ( ) + "" ) ; if ( beanDoc . getAllText ( ) != null ) { out . println ( "" ) ; out . println ( beanDoc . getAllText ( ) ) ; } PropertyDoc [ ] propertyDocs = beanDoc . getPropertyDocs ( ) ; if ( propertyDocs . length > ) { out . println ( "" ) ; out . println ( "" ) ; out . println ( "" + "" ) ; int i = ; for ( PropertyDoc elem : propertyDocs ) { if ( ConfiguredHow . HIDDEN == elem . getConfiguredHow ( ) ) { continue ; } out . println ( "" ) ; out . println ( "" + ++ i + "" + elem . getPropertyName ( ) + "" ) ; out . println ( "" + ( elem . getFirstSentence ( ) == null ? "" : elem . getFirstSentence ( ) ) + "" ) ; out . println ( "" ) ; } out . println ( "" ) ; } ExampleDoc [ ] exampleDocs = beanDoc . getExampleDocs ( ) ; if ( exampleDocs . length > ) { out . println ( "" ) ; out . println ( "" ) ; out . println ( "" + "" ) ; int i = ; for ( ExampleDoc elem : exampleDocs ) { out . println ( "" ) ; out . println ( "" + ++ i + "" + i + "" ) ; out . println ( "" + ( elem . getFirstSentence ( ) == null ? "" : elem . getFirstSentence ( ) ) + "" ) ; out . println ( "" ) ; } out . println ( "" ) ; } if ( propertyDocs . length > ) { out . println ( "" ) ; out . println ( "" ) ; int i = ; for ( PropertyDoc elem : propertyDocs ) { if ( ConfiguredHow . HIDDEN == elem . getConfiguredHow ( ) ) { continue ; } out . println ( "" + ++ i + "" + elem . getPropertyName ( ) + "" ) ; out . println ( "" ) ; if ( elem . getAccess ( ) != PropertyDoc . Access . READ_ONLY ) { out . println ( "" + elem . getConfiguredHow ( ) + "" ) ; } out . println ( "" + elem . getAccess ( ) + "" ) ; String required = elem . getRequired ( ) ; if ( required != null ) { out . println ( "" + required + "" ) ; } out . println ( "" ) ; out . println ( "" ) ; out . println ( elem . getAllText ( ) == null ? "" : elem . getAllText ( ) ) ; out . println ( "" ) ; } } if ( exampleDocs . length > ) { out . println ( "" ) ; out . println ( "" ) ; int i = ; for ( ExampleDoc example : exampleDocs ) { out . println ( "" + ++ i + "" + i + "" ) ; out . println ( "" ) ; out . println ( example . getAllText ( ) ) ; out . println ( "" ) ; } } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . close ( ) ; } public void writeIndex ( IndexLine [ ] jobs , IndexLine [ ] types ) { PrintWriter out = null ; try { out = new PrintWriter ( new FileOutputStream ( new File ( directory , "" ) ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" + title + "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" + title + "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; for ( int i = ; i < jobs . length ; ++ i ) { IndexLine beanDoc = jobs [ i ] ; out . println ( "" ) ; out . println ( "" + getFileName ( beanDoc . getClassName ( ) ) + "" + beanDoc . getName ( ) + "" + beanDoc . getFirstSentence ( ) ) ; out . println ( "" ) ; } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; for ( int i = ; i < types . length ; ++ i ) { IndexLine beanDoc = types [ i ] ; out . println ( "" ) ; out . println ( "" + getFileName ( beanDoc . getClassName ( ) ) + "" + beanDoc . getName ( ) + "" + beanDoc . getFirstSentence ( ) ) ; out . println ( "" ) ; } out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . close ( ) ; } public void writeAll ( Iterable < ? extends BeanDoc > all ) { for ( BeanDoc beanDoc : all ) { writePage ( beanDoc ) ; } } public void createManual ( Archiver archiver ) { writeIndex ( archiver . getJobData ( ) , archiver . getTypeData ( ) ) ; writeAll ( archiver . getAll ( ) ) ; } public String getFileName ( String className ) { return className . replace ( '' , '' ) + "" ; } public static String getIndexFile ( String className ) { String path = "" ; int start = ; while ( ( start = className . indexOf ( '' , start ) + ) > ) { path = path + "" ; } return path + "" ; } } package org . oddjob . doclet ; public interface CustomTagNames { public static final String DESCRIPTION_TAG_NAME = "" ; public static final String DESCRIPTION_TAG = "" + DESCRIPTION_TAG_NAME ; public static final String PROPERTY_TAG_NAME = "" ; public static final String PROPERTY_TAG = "" + PROPERTY_TAG_NAME ; public static final String REQUIRED_TAG_NAME = "" ; public static final String REQUIRED_TAG = "" + REQUIRED_TAG_NAME ; public static final String EXAMPLE_TAG_NAME = "" ; public static final String EXAMPLE_TAG = "" + EXAMPLE_TAG_NAME ; public static final String XML_RESOURCE_TAG_NAME = "" ; public static final String XML_RESOURCE_TAG = "" + XML_RESOURCE_TAG_NAME ; public static final String JAVA_FILE_TAG_NAME = "" ; public static final String JAVA_FILE_TAG = "" + JAVA_FILE_TAG_NAME ; public static final String XML_FILE_TAG_NAME = "" ; public static final String XML_FILE_TAG = "" ; } package org . oddjob . doclet ; import org . oddjob . arooa . beandocs . BeanDoc ; import org . oddjob . arooa . beandocs . WriteableBeanDoc ; import org . oddjob . arooa . beandocs . WriteableExampleDoc ; import org . oddjob . arooa . beandocs . WriteablePropertyDoc ; import org . oddjob . tools . includes . CompositeLoader ; import org . oddjob . tools . includes . IncludeLoader ; import com . sun . javadoc . ClassDoc ; import com . sun . javadoc . Doc ; import com . sun . javadoc . FieldDoc ; import com . sun . javadoc . MethodDoc ; import com . sun . javadoc . SeeTag ; import com . sun . javadoc . Tag ; public class Processor implements CustomTagNames { private final ClassDoc classDoc ; private final String rootDir ; private final JobsAndTypes jats ; public Processor ( JobsAndTypes jats , ClassDoc classDoc ) { this . jats = jats ; this . classDoc = classDoc ; String [ ] packages = classDoc . containingPackage ( ) . name ( ) . split ( ( "" ) ) ; String rootDir = "" ; for ( int i = ; i < packages . length ; ++ i ) { rootDir = rootDir + ( i == ? "" : "" ) + "" ; } this . rootDir = rootDir ; } String processSingleTextTag ( Tag [ ] tags , String replacement ) { if ( tags . length == ) { return null ; } if ( tags . length > ) { System . err . println ( "" + replacement + "" ) ; } String text = tags [ ] . text ( ) ; if ( text == null || text . trim ( ) . equals ( "" ) ) { return replacement ; } return text ; } void processFieldOrMethod ( WriteableBeanDoc beanDoc , Doc doc ) { Tag [ ] propertyTags = doc . tags ( PROPERTY_TAG ) ; String propertyText = processSingleTextTag ( propertyTags , doc . name ( ) ) ; if ( propertyText == null ) { return ; } WriteablePropertyDoc prop = beanDoc . propertyDocFor ( propertyText ) ; if ( prop == null ) { System . err . println ( "" + propertyText ) ; return ; } Tag [ ] descriptionTags = doc . tags ( DESCRIPTION_TAG ) ; prop . setAllText ( processMajorTags ( descriptionTags ) ) ; prop . setFirstSentence ( processFirstLine ( descriptionTags , this . rootDir ) ) ; Tag [ ] rtags = doc . tags ( REQUIRED_TAG ) ; if ( rtags . length != ) { prop . setRequired ( rtags [ ] . text ( ) ) ; } } String processInlineTags ( Tag [ ] inlines , String rootDir ) { StringBuffer buffer = new StringBuffer ( ) ; for ( int i = ; i < inlines . length ; ++ i ) { Tag inlineTag = inlines [ i ] ; if ( inlineTag instanceof SeeTag ) { SeeTag seeTag = ( SeeTag ) inlineTag ; String ref = seeTag . referencedClassName ( ) ; String fileName = ref . replace ( '' , '' ) + "" ; BeanDoc beanDoc = jats . docFor ( ref ) ; if ( beanDoc != null ) { buffer . append ( "" + rootDir + "" + fileName + "" + beanDoc . getName ( ) + "" ) ; } else if ( ref . startsWith ( "" ) ) { buffer . append ( "" + getApiDirFrom ( rootDir ) + "" + fileName + "" + ref + "" ) ; } else { buffer . append ( "" + ref + "" ) ; } } else { IncludeLoader loader = new CompositeLoader ( ) ; if ( loader . canLoad ( inlineTag . name ( ) ) ) { buffer . append ( loader . load ( inlineTag . text ( ) ) ) ; } else { buffer . append ( inlineTag . text ( ) ) ; } } } return buffer . toString ( ) ; } String processMajorTags ( Tag [ ] tags ) { if ( tags == null ) { return null ; } StringBuffer result = new StringBuffer ( ) ; for ( int i = ; i < tags . length ; ++ i ) { result . append ( processInlineTags ( tags [ i ] . inlineTags ( ) , this . rootDir ) ) ; } return result . toString ( ) ; } String processFirstLine ( Tag [ ] tags , String rootDir ) { if ( tags == null ) { return null ; } if ( tags . length == ) { return null ; } return processInlineTags ( tags [ ] . firstSentenceTags ( ) , rootDir ) ; } void processAllMembers ( WriteableBeanDoc pageData , ClassDoc classDoc ) { if ( classDoc == null ) { return ; } processAllMembers ( pageData , classDoc . superclass ( ) ) ; FieldDoc [ ] fds = classDoc . fields ( ) ; for ( int i = ; i < fds . length ; ++ i ) { processFieldOrMethod ( pageData , fds [ i ] ) ; } MethodDoc [ ] mds = classDoc . methods ( ) ; for ( int i = ; i < mds . length ; ++ i ) { processFieldOrMethod ( pageData , mds [ i ] ) ; } } public BeanDoc process ( ) { String fqcn = classDoc . qualifiedName ( ) ; WriteableBeanDoc beanDoc = jats . docFor ( fqcn ) ; System . out . println ( "" + beanDoc . getName ( ) ) ; Tag [ ] descriptionTags = classDoc . tags ( DESCRIPTION_TAG ) ; String firstLine = processFirstLine ( descriptionTags , "" ) ; if ( firstLine == null ) { System . err . println ( "" + fqcn ) ; } beanDoc . setFirstSentence ( firstLine ) ; beanDoc . setAllText ( processMajorTags ( descriptionTags ) ) ; Tag [ ] exampleTags = classDoc . tags ( EXAMPLE_TAG ) ; for ( int i = ; i < exampleTags . length ; ++ i ) { WriteableExampleDoc exampleDoc = new WriteableExampleDoc ( ) ; exampleDoc . setAllText ( processInlineTags ( exampleTags [ i ] . inlineTags ( ) , this . rootDir ) ) ; exampleDoc . setFirstSentence ( processFirstLine ( new Tag [ ] { exampleTags [ i ] } , this . rootDir ) ) ; beanDoc . addExampleDoc ( exampleDoc ) ; } processAllMembers ( beanDoc , classDoc ) ; return beanDoc ; } public static String fqcnFor ( ClassDoc classDoc ) { return classDoc . containingPackage ( ) . name ( ) + "" + classDoc . name ( ) ; } private String getApiDirFrom ( String rootDir ) { return rootDir + "" ; } } package org . oddjob . doclet ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . parsing . QTag ; public class PageData { private final QTag name ; private final String fileName ; private String firstSentence ; private String description ; private final List < String > examples = new ArrayList < String > ( ) ; private final List < Property > attributes = new ArrayList < Property > ( ) ; private final List < Property > elements = new ArrayList < Property > ( ) ; public PageData ( QTag name , String filename ) { this . name = name ; this . fileName = filename ; } public QTag getName ( ) { return name ; } public void setFirstSentence ( String firstSentence ) { this . firstSentence = firstSentence ; } public String getFirstSentence ( ) { return firstSentence ; } public void setDescription ( String description ) { this . description = description ; } public String getDescription ( ) { return description ; } public void addAttribute ( Property attribute ) { attributes . add ( attribute ) ; } public List < Property > getAttributes ( ) { return attributes ; } public void addElement ( Property element ) { elements . add ( element ) ; } public List < Property > getElements ( ) { return elements ; } public void addExample ( String example ) { examples . add ( example ) ; } public List < String > getExamples ( ) { return examples ; } public String getFileName ( ) { return fileName ; } } package org . oddjob . doclet ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . beandocs . BeanDoc ; import org . oddjob . arooa . beandocs . WriteableBeanDoc ; import com . sun . javadoc . ClassDoc ; public class Archiver { private final JobsAndTypes jats ; public Archiver ( JobsAndTypes jats ) { this . jats = jats ; } public void archive ( ClassDoc classDoc ) { String fqcn = Processor . fqcnFor ( classDoc ) ; WriteableBeanDoc beanDoc = jats . docFor ( fqcn ) ; if ( beanDoc == null ) { return ; } Processor processor = new Processor ( jats , classDoc ) ; processor . process ( ) ; } public IndexLine [ ] getJobData ( ) { List < IndexLine > lines = new ArrayList < IndexLine > ( ) ; for ( String name : jats . jobs ( ) ) { BeanDoc beanDoc = jats . docForJob ( name ) ; lines . add ( new IndexLine ( beanDoc . getClassName ( ) , name , beanDoc . getFirstSentence ( ) ) ) ; } return lines . toArray ( new IndexLine [ lines . size ( ) ] ) ; } public IndexLine [ ] getTypeData ( ) { List < IndexLine > lines = new ArrayList < IndexLine > ( ) ; for ( String name : jats . types ( ) ) { BeanDoc beanDoc = jats . docForType ( name ) ; lines . add ( new IndexLine ( beanDoc . getClassName ( ) , name , beanDoc . getFirstSentence ( ) ) ) ; } return lines . toArray ( new IndexLine [ lines . size ( ) ] ) ; } public Iterable < ? extends BeanDoc > getAll ( ) { return jats . all ( ) ; } } package org . oddjob . logging . log4j ; import org . apache . log4j . AppenderSkeleton ; import org . apache . log4j . Layout ; import org . apache . log4j . spi . LoggingEvent ; import org . oddjob . logging . LoggingConstants ; import org . oddjob . logging . cache . LogArchiverCache ; public class ArchiveAppender extends AppenderSkeleton implements LoggingConstants { private final LogArchiverCache logArchiver ; public ArchiveAppender ( LogArchiverCache logArchiver , Layout layout ) { this . logArchiver = logArchiver ; this . layout = layout ; } public void close ( ) { } public void append ( LoggingEvent event ) { String archive = event . getLoggerName ( ) ; if ( ! logArchiver . hasArchive ( archive ) ) { archive = ( String ) event . getMDC ( MDC_LOGGER ) ; } if ( ! logArchiver . hasArchive ( archive ) ) { return ; } StringBuffer text = new StringBuffer ( ) ; text . append ( this . layout . format ( event ) ) ; if ( layout . ignoresThrowable ( ) ) { String [ ] s = event . getThrowableStrRep ( ) ; if ( s != null ) { int len = s . length ; for ( int i = ; i < len ; i ++ ) { text . append ( s [ i ] ) ; text . append ( Layout . LINE_SEP ) ; } } } logArchiver . addEvent ( archive , Log4jArchiver . convertLevel ( event . getLevel ( ) ) , text . toString ( ) ) ; } public boolean requiresLayout ( ) { return false ; } } package org . oddjob . logging . log4j ; import org . apache . log4j . Appender ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . apache . log4j . PatternLayout ; import org . apache . log4j . Priority ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogHelper ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . cache . LogArchiverCache ; import org . oddjob . logging . cache . StructuralArchiverCache ; public class Log4jArchiver implements LogArchiver { private final LogArchiverCache logArchiver ; private final Appender appender ; public Log4jArchiver ( Object root , String pattern ) { logArchiver = new StructuralArchiverCache ( root , new ArchiveNameResolver ( ) { public String resolveName ( Object component ) { return LogHelper . getLogger ( component ) ; } } ) ; appender = new ArchiveAppender ( logArchiver , new PatternLayout ( pattern ) ) ; appender . setName ( this . toString ( ) ) ; Logger . getRootLogger ( ) . addAppender ( appender ) ; } public boolean hasArchive ( String archive ) { return logArchiver . hasArchive ( archive ) ; } public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int history ) { logArchiver . addLogListener ( l , component , level , last , history ) ; } public void removeLogListener ( LogListener l , Object component ) { logArchiver . removeLogListener ( l , component ) ; } public void onDestroy ( ) { Logger . getRootLogger ( ) . removeAppender ( appender ) ; logArchiver . destroy ( ) ; } @ SuppressWarnings ( "" ) public static LogLevel convertLevel ( Level level ) { if ( level == Level . ALL ) { return LogLevel . TRACE ; } else if ( level == Level . TRACE ) { return LogLevel . TRACE ; } else if ( level == Level . DEBUG || level == Priority . DEBUG ) { return LogLevel . DEBUG ; } else if ( level == Level . INFO || level == Priority . INFO ) { return LogLevel . INFO ; } else if ( level == Level . WARN || level == Priority . WARN ) { return LogLevel . WARN ; } else if ( level == Level . ERROR || level == Priority . ERROR ) { return LogLevel . ERROR ; } else if ( level == Level . FATAL || level == Priority . FATAL ) { return LogLevel . FATAL ; } else if ( level == Level . OFF ) { return LogLevel . FATAL ; } else { throw new IllegalArgumentException ( "" + level + "" ) ; } } } package org . oddjob . logging . log4j ; import java . io . OutputStream ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . types . ValueFactory ; public class LogoutType implements ValueFactory < OutputStream > { private String logger ; private String level ; @ Override public OutputStream toValue ( ) throws ArooaConversionException { String logName = this . logger ; if ( logName == null ) { logName = LogoutType . class . getName ( ) ; } Logger logger = Logger . getLogger ( logName ) ; Level level = Level . toLevel ( this . level == null ? "" : this . level ) ; return new Log4jPrintStream ( logger , level ) ; } public String getLogger ( ) { return logger ; } public void setLogger ( String logger ) { this . logger = logger ; } public String getLevel ( ) { return level ; } public void setLevel ( String level ) { this . level = level ; } } package org . oddjob . logging . log4j ; import java . io . OutputStream ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . apache . log4j . Priority ; import org . oddjob . logging . AbstractLoggingOutput ; public class Log4jPrintStream extends AbstractLoggingOutput { private final Logger logger ; private final Priority priority ; public Log4jPrintStream ( Logger logger , Level level ) { this ( null , logger , level ) ; } public Log4jPrintStream ( OutputStream existing , Logger logger , Level level ) { super ( existing ) ; this . logger = logger ; this . priority = level ; } @ Override protected void dispatch ( String message ) { logger . log ( priority , message . trim ( ) ) ; } } package org . oddjob . logging ; public interface ConsoleArchiver { public void addConsoleListener ( LogListener l , Object component , long last , int max ) ; public void removeConsoleListener ( LogListener l , Object component ) ; public String consoleIdFor ( Object component ) ; } package org . oddjob . logging ; public interface ConsoleOwner { public LogArchive consoleLog ( ) ; } package org . oddjob . logging . cache ; import org . oddjob . logging . LogEvent ; public interface LogEventSource { public LogEvent [ ] retrieveEvents ( Object component , long from , int max ) ; } package org . oddjob . logging . cache ; import org . oddjob . Oddjob ; import org . oddjob . logging . ConsoleOwner ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchive ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class LocalConsoleArchiver implements ConsoleArchiver { public void addConsoleListener ( LogListener l , Object component , long last , int history ) { archiveFor ( component ) . addListener ( l , LogLevel . DEBUG , last , history ) ; } public void removeConsoleListener ( LogListener l , Object component ) { archiveFor ( component ) . removeListener ( l ) ; } public String consoleIdFor ( Object component ) { return archiveFor ( component ) . getArchive ( ) ; } private LogArchive archiveFor ( Object component ) { if ( component instanceof ConsoleOwner ) { return ( ( ConsoleOwner ) component ) . consoleLog ( ) ; } else { return Oddjob . CONSOLE ; } } public void onDestroy ( ) { } } package org . oddjob . logging . cache ; import java . util . HashMap ; import java . util . Map ; import org . apache . log4j . Logger ; import org . oddjob . Stateful ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . LogArchive ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . state . StateListener ; import org . oddjob . state . StateEvent ; abstract public class AbstractArchiverCache implements LogArchiverCache { private static final Logger logger = Logger . getLogger ( AbstractArchiverCache . class ) ; private final Map < String , LogArchiveImpl > archives = new HashMap < String , LogArchiveImpl > ( ) ; private final SimpleCounter counter = new SimpleCounter ( ) ; private final int maxHistory ; private final ArchiveNameResolver resolver ; private final StateListener stateListener = new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { if ( event . getState ( ) . isDestroyed ( ) ) { removeArchive ( event . getSource ( ) ) ; } } } ; public AbstractArchiverCache ( ArchiveNameResolver resolver ) { this ( resolver , LogArchiver . MAX_HISTORY ) ; } public AbstractArchiverCache ( ArchiveNameResolver resolver , int maxHistory ) { this . resolver = resolver ; this . maxHistory = maxHistory ; } public int getMaxHistory ( ) { return maxHistory ; } public long getLastMessageNumber ( String archive ) { LogArchive logArchive = archives . get ( archive ) ; if ( logArchive == null ) { throw new IllegalArgumentException ( "" + archive + "" ) ; } return logArchive . getLastMessageNumber ( ) ; } public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int history ) { String archive = resolver . resolveName ( component ) ; LogArchive logArchive = archives . get ( archive ) ; if ( logArchive == null ) { l . logEvent ( LogArchiver . NO_LOG_AVAILABLE ) ; return ; } logger . debug ( "" + l + "" + logArchive . getArchive ( ) + "" ) ; logArchive . addListener ( l , level , last , history ) ; } public void removeLogListener ( LogListener l , Object component ) { String archive = resolver . resolveName ( component ) ; LogArchive logArchive = archives . get ( archive ) ; if ( logArchive == null ) { return ; } logger . debug ( "" + l + "" + logArchive . getArchive ( ) + "" ) ; logArchive . removeListener ( l ) ; } public boolean hasArchive ( String archive ) { return archives . containsKey ( archive ) ; } protected boolean hasArchiveFor ( Object component ) { return hasArchive ( resolver . resolveName ( component ) ) ; } protected ArchiveNameResolver getResolver ( ) { return resolver ; } protected void addArchive ( Object component ) { final String archiveName = resolver . resolveName ( component ) ; if ( archiveName == null ) { return ; } logger . debug ( "" + archiveName + "" + component + "" ) ; counter . add ( archiveName , new Runnable ( ) { public void run ( ) { LogArchiveImpl logArchive = new LogArchiveImpl ( archiveName , getMaxHistory ( ) ) ; archives . put ( archiveName , logArchive ) ; logger . debug ( "" + archiveName + "" ) ; } } ) ; if ( component instanceof Stateful ) { ( ( Stateful ) component ) . addStateListener ( stateListener ) ; } } protected void removeArchive ( Object component ) { final String archiveName = resolver . resolveName ( component ) ; if ( archiveName == null ) { return ; } logger . debug ( "" + archiveName + "" + component + "" ) ; counter . remove ( archiveName , new Runnable ( ) { public void run ( ) { logger . debug ( "" + archiveName + "" ) ; archives . remove ( archiveName ) ; } } ) ; } public void addEvent ( String archive , LogLevel level , String message ) { LogArchiveImpl logArchive = archives . get ( archive ) ; if ( logArchive == null ) { throw new IllegalArgumentException ( "" + archive + "" ) ; } logArchive . addEvent ( level , message ) ; } public abstract void destroy ( ) ; } package org . oddjob . logging . cache ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class LazyArchiverCache extends AbstractArchiverCache { public LazyArchiverCache ( ArchiveNameResolver resolver ) { this ( LogArchiver . MAX_HISTORY , resolver ) ; } public LazyArchiverCache ( int maxHistory , ArchiveNameResolver resolver ) { super ( resolver , maxHistory ) ; } @ Override synchronized public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int history ) { if ( ! hasArchiveFor ( component ) ) { addArchive ( component ) ; } super . addLogListener ( l , component , level , last , history ) ; } @ Override synchronized public void removeLogListener ( LogListener l , Object component ) { super . removeLogListener ( l , component ) ; } public void destroy ( ) { } } package org . oddjob . logging . cache ; import java . util . HashMap ; import java . util . Map ; public class SimpleCounter { private Map < Object , Integer > counter = new HashMap < Object , Integer > ( ) ; public void add ( Object key ) { add ( key , null ) ; } synchronized public void add ( Object key , Runnable newAction ) { Integer count = ( Integer ) counter . get ( key ) ; if ( count == null ) { count = new Integer ( ) ; if ( newAction != null ) { newAction . run ( ) ; } } else { count = new Integer ( count . intValue ( ) + ) ; } counter . put ( key , count ) ; } public void remove ( Object key ) throws IllegalStateException { remove ( key , null ) ; } synchronized public void remove ( Object key , Runnable emptyAction ) throws IllegalStateException { Integer count = ( Integer ) counter . get ( key ) ; if ( count == null ) { return ; } int c = count . intValue ( ) ; if ( c == ) { counter . remove ( key ) ; if ( emptyAction != null ) { emptyAction . run ( ) ; } } else { count = new Integer ( c - ) ; } } } package org . oddjob . logging . cache ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . Structural ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class StructuralArchiverCache extends AbstractArchiverCache { private final StructuralListener structuralListener = new StructuralListener ( ) { public void childAdded ( StructuralEvent event ) { Object node = event . getChild ( ) ; addChild ( node ) ; } public void childRemoved ( StructuralEvent event ) { Object node = event . getChild ( ) ; removeChild ( node ) ; } } ; private final List < Structural > listeningTo = new ArrayList < Structural > ( ) ; public StructuralArchiverCache ( Object root , ArchiveNameResolver resolver ) { this ( root , LogArchiver . MAX_HISTORY , resolver ) ; } public StructuralArchiverCache ( Object root , int maxHistory , ArchiveNameResolver resolver ) { super ( resolver , maxHistory ) ; addChild ( root ) ; } void addChild ( Object node ) { addArchive ( node ) ; if ( node instanceof LogArchiver ) { return ; } if ( node instanceof Structural ) { ( ( Structural ) node ) . addStructuralListener ( structuralListener ) ; listeningTo . add ( ( Structural ) node ) ; } } void removeChild ( Object node ) { removeArchive ( node ) ; if ( node instanceof Structural ) { ( ( Structural ) node ) . removeStructuralListener ( structuralListener ) ; listeningTo . remove ( node ) ; } } public void destroy ( ) { while ( listeningTo . size ( ) > ) { removeChild ( listeningTo . get ( ) ) ; } } } package org . oddjob . logging . cache ; import org . oddjob . logging . LogArchive ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public interface LogArchiverCache { public boolean hasArchive ( String archive ) ; public long getLastMessageNumber ( String archive ) ; public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int history ) ; public void removeLogListener ( LogListener l , Object component ) ; public int getMaxHistory ( ) ; public void addEvent ( String archive , LogLevel level , String message ) ; public abstract void destroy ( ) ; } package org . oddjob . logging . cache ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import org . apache . log4j . Logger ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class PollingLogArchiver implements LogArchiver { private static final Logger logger = Logger . getLogger ( PollingLogArchiver . class ) ; private final LogArchiverCache cache ; private final Map < Object , String > components = new HashMap < Object , String > ( ) ; private final Map < String , Long > lastMessageNumbers = new HashMap < String , Long > ( ) ; private SimpleCounter listenerCounter = new SimpleCounter ( ) ; private final LogEventSource source ; private final ArchiveNameResolver resolver ; public PollingLogArchiver ( ArchiveNameResolver resolver , LogEventSource source ) { this ( LogArchiver . MAX_HISTORY , resolver , source ) ; } public PollingLogArchiver ( int history , ArchiveNameResolver resolver , LogEventSource source ) { this . source = source ; this . resolver = resolver ; this . cache = new LazyArchiverCache ( history , resolver ) ; } public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int max ) { String archive = resolver . resolveName ( component ) ; logger . debug ( "" + archive + "" ) ; if ( archive == null ) { l . logEvent ( LogArchiver . NO_LOG_AVAILABLE ) ; return ; } synchronized ( components ) { components . put ( component , archive ) ; listenerCounter . add ( component ) ; cache . addLogListener ( l , component , level , last , max ) ; poll ( ) ; } } public void removeLogListener ( LogListener l , final Object component ) { synchronized ( components ) { final String archiveName = ( String ) components . get ( component ) ; if ( archiveName == null ) { return ; } cache . removeLogListener ( l , component ) ; listenerCounter . remove ( component , new Runnable ( ) { public void run ( ) { components . remove ( component ) ; } } ) ; } } public void poll ( ) { synchronized ( components ) { Set < Object > polled = new HashSet < Object > ( ) ; Set < Map . Entry < Object , String > > copy = new HashSet < Map . Entry < Object , String > > ( components . entrySet ( ) ) ; for ( Map . Entry < Object , String > entry : copy ) { Object component = entry . getKey ( ) ; String archiveName = entry . getValue ( ) ; if ( polled . contains ( archiveName ) ) { continue ; } Long lastMessageNumber = lastMessageNumbers . get ( archiveName ) ; if ( lastMessageNumber == null ) { lastMessageNumber = - ; } LogEvent [ ] events = null ; try { events = source . retrieveEvents ( component , lastMessageNumber , cache . getMaxHistory ( ) ) ; } catch ( Exception e ) { logger . debug ( "" + component + "" , e ) ; components . remove ( component ) ; continue ; } for ( int i = ; i < events . length ; ++ i ) { cache . addEvent ( archiveName , events [ i ] . getLevel ( ) , events [ i ] . getMessage ( ) ) ; } if ( events . length > ) { lastMessageNumbers . put ( archiveName , events [ events . length - ] . getNumber ( ) ) ; } polled . add ( archiveName ) ; } } } public void onDestroy ( ) { cache . destroy ( ) ; } } package org . oddjob . logging . cache ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Stack ; import org . oddjob . logging . LogArchive ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogEventSink ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class LogArchiveImpl implements LogArchive , LogEventSink { private final int maxHistory ; private final String archive ; private final LinkedList < LogEvent > events = new LinkedList < LogEvent > ( ) ; private final Map < LogListener , LogLevel > listeners = new HashMap < LogListener , LogLevel > ( ) ; public LogArchiveImpl ( String archive , int maxHistory ) { if ( archive == null ) { throw new NullPointerException ( "" ) ; } this . archive = archive ; this . maxHistory = maxHistory ; } public long getLastMessageNumber ( ) { synchronized ( events ) { if ( events . size ( ) == ) { return - ; } LogEvent logEvent = ( LogEvent ) events . getFirst ( ) ; return logEvent . getNumber ( ) ; } } public void addEvent ( LogLevel level , String line ) { synchronized ( events ) { LogEvent event = new LogEvent ( archive , getLastMessageNumber ( ) + , level , line ) ; events . addFirst ( event ) ; while ( events . size ( ) > maxHistory ) { events . removeLast ( ) ; } for ( Map . Entry < LogListener , LogLevel > entry : listeners . entrySet ( ) ) { LogListener listener = ( LogListener ) entry . getKey ( ) ; LogLevel listenerLevel = ( LogLevel ) entry . getValue ( ) ; if ( level . isLessThan ( listenerLevel ) ) { continue ; } listener . logEvent ( event ) ; } } } public LogEvent [ ] retrieveEvents ( long from , int max ) { synchronized ( events ) { List < LogEvent > missed = new ArrayList < LogEvent > ( ) ; int count = ; for ( Iterator < LogEvent > it = events . iterator ( ) ; it . hasNext ( ) && count < max ; count ++ ) { LogEvent event = it . next ( ) ; if ( event . getNumber ( ) == from ) { break ; } missed . add ( event ) ; } Collections . reverse ( missed ) ; return ( LogEvent [ ] ) missed . toArray ( new LogEvent [ ] ) ; } } public void addListener ( LogListener l , LogLevel level , long last , int history ) { synchronized ( events ) { Stack < LogEvent > missed = new Stack < LogEvent > ( ) ; int count = ; for ( Iterator < LogEvent > it = events . iterator ( ) ; it . hasNext ( ) && count < history ; count ++ ) { LogEvent event = it . next ( ) ; if ( event . getNumber ( ) <= last ) { break ; } if ( event . getLevel ( ) . isLessThan ( level ) ) { continue ; } missed . push ( event ) ; } while ( ! missed . empty ( ) ) { LogEvent event = ( LogEvent ) missed . pop ( ) ; l . logEvent ( event ) ; } listeners . put ( l , level ) ; } } public boolean removeListener ( LogListener l ) { synchronized ( events ) { return ! ( listeners . remove ( l ) == null ) ; } } public String getArchive ( ) { return archive ; } public int getMaxHistory ( ) { return maxHistory ; } } package org . oddjob . logging ; public interface LogArchiver { public static final int MAX_HISTORY = ; public static final LogEvent NO_LOG_AVAILABLE = new LogEvent ( "" , , LogLevel . INFO , "" ) ; public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int max ) ; public void removeLogListener ( LogListener l , Object component ) ; } package org . oddjob . logging ; import java . util . Stack ; import org . apache . log4j . MDC ; public class OddjobNDC implements LoggingConstants { private static InheritableThreadLocal < Stack < LoggerAndJob > > local = new InheritableThreadLocal < Stack < LoggerAndJob > > ( ) { protected Stack < LoggerAndJob > initialValue ( ) { return new Stack < LoggerAndJob > ( ) ; } @ SuppressWarnings ( "" ) protected Stack < LoggerAndJob > childValue ( Stack < LoggerAndJob > parentValue ) { if ( parentValue != null ) { return ( Stack < LoggerAndJob > ) parentValue . clone ( ) ; } else { return null ; } } } ; private OddjobNDC ( ) { } public static LoggerAndJob pop ( ) { Stack < LoggerAndJob > stack = local . get ( ) ; LoggerAndJob result = stack . pop ( ) ; if ( stack . isEmpty ( ) ) { MDC . remove ( MDC_LOGGER ) ; MDC . remove ( MDC_JOB_NAME ) ; } else { LoggerAndJob peek = stack . peek ( ) ; MDC . put ( MDC_LOGGER , peek . getLogger ( ) ) ; MDC . put ( MDC_JOB_NAME , peek . getJob ( ) . toString ( ) ) ; } return result ; } public static LoggerAndJob peek ( ) { Stack < LoggerAndJob > stack = local . get ( ) ; if ( stack . isEmpty ( ) ) { return null ; } return stack . peek ( ) ; } public static void push ( String loggerName , Object job ) { if ( loggerName == null ) { throw new NullPointerException ( "" ) ; } if ( job == null ) { throw new NullPointerException ( "" ) ; } Stack < LoggerAndJob > stack = local . get ( ) ; stack . push ( new LoggerAndJob ( loggerName , job ) ) ; MDC . put ( MDC_LOGGER , loggerName ) ; MDC . put ( MDC_JOB_NAME , job . toString ( ) ) ; } public static class LoggerAndJob implements Cloneable { private final String logger ; private final Object job ; public LoggerAndJob ( String logger , Object job ) { this . logger = logger ; this . job = job ; } public Object getJob ( ) { return job ; } public String getLogger ( ) { return logger ; } public Object clone ( ) throws CloneNotSupportedException { return super . clone ( ) ; } } } package org . oddjob . logging ; import java . io . OutputStream ; import java . io . PrintStream ; public class LoggingPrintStream extends PrintStream { public LoggingPrintStream ( OutputStream existing , LogLevel level , LogEventSink consoleArchiver ) { super ( new LoggingOutputStream ( existing , level , consoleArchiver ) ) ; } } package org . oddjob . logging ; import java . io . Serializable ; public class LogEvent implements Serializable { private static final long serialVersionUID = ; private final long number ; private final LogLevel level ; private final String logger ; private final String message ; public LogEvent ( String logger , long number , LogLevel level , String message ) { if ( logger == null ) { throw new NullPointerException ( "" ) ; } if ( number < ) { throw new IllegalArgumentException ( "" ) ; } if ( level == null ) { throw new NullPointerException ( "" ) ; } if ( message == null ) { throw new NullPointerException ( "" ) ; } this . number = number ; this . level = level ; this . logger = logger ; this . message = message ; } public LogLevel getLevel ( ) { return level ; } public String getLogger ( ) { return logger ; } public String getMessage ( ) { return message ; } public long getNumber ( ) { return number ; } } package org . oddjob . logging ; public interface LogArchive { public long getLastMessageNumber ( ) ; public LogEvent [ ] retrieveEvents ( long from , int max ) ; public void addListener ( LogListener logListener , LogLevel level , long last , int history ) ; public boolean removeListener ( LogListener l ) ; public String getArchive ( ) ; public int getMaxHistory ( ) ; } package org . oddjob . logging ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . OutputStream ; abstract public class AbstractLoggingOutput extends OutputStream { private ByteArrayOutputStream buffer ; private final OutputStream existing ; public AbstractLoggingOutput ( OutputStream existing ) { this . buffer = new ByteArrayOutputStream ( ) ; this . existing = existing ; } public void write ( int c ) throws IOException { add ( new byte [ ] { ( byte ) c } , , ) ; if ( existing != null ) existing . write ( c ) ; } public void write ( byte [ ] b ) throws IOException { add ( b , , b . length ) ; if ( existing != null ) existing . write ( b ) ; } public void write ( byte [ ] buf , int off , int len ) throws IOException { add ( buf , off , len ) ; if ( existing != null ) existing . write ( buf , off , len ) ; } @ Override public void flush ( ) throws IOException { if ( existing != null ) { existing . flush ( ) ; } } public void close ( ) throws IOException { next ( ) ; if ( existing != null ) existing . close ( ) ; } void add ( byte [ ] buf , int off , int length ) { synchronized ( buffer ) { for ( int i = off ; i < off + length ; ++ i ) { if ( buf [ i ] == '' ) { buffer . write ( buf , off , i - off + ) ; next ( ) ; add ( buf , i + , length - ( i - off + ) ) ; return ; } } buffer . write ( buf , off , length ) ; } } void next ( ) { String message = null ; synchronized ( buffer ) { if ( buffer . size ( ) == ) { return ; } message = buffer . toString ( ) ; buffer . reset ( ) ; } dispatch ( message ) ; } abstract protected void dispatch ( String message ) ; } package org . oddjob . logging ; import java . io . OutputStream ; public class LoggingOutputStream extends AbstractLoggingOutput { private final LogLevel level ; private final LogEventSink consoleArchiver ; public LoggingOutputStream ( OutputStream existing , LogLevel level , LogEventSink consoleArchiver ) { super ( existing ) ; this . level = level ; this . consoleArchiver = consoleArchiver ; } @ Override protected void dispatch ( String message ) { consoleArchiver . addEvent ( level , message ) ; } } package org . oddjob . logging ; public enum LogLevel { TRACE , DEBUG , INFO , WARN , ERROR , FATAL , ; public boolean isLessThan ( LogLevel other ) { return this . ordinal ( ) < other . ordinal ( ) ; } } package org . oddjob . logging ; public interface LogEventSink { public void addEvent ( LogLevel level , String line ) ; } package org . oddjob . logging ; import java . util . HashMap ; import java . util . Map ; public class LogHelper { private static final Map < String , Integer > loggers = new HashMap < String , Integer > ( ) ; public static String uniqueLoggerName ( Object component ) { String className = component . getClass ( ) . getName ( ) ; synchronized ( loggers ) { Integer count = ( Integer ) loggers . get ( className ) ; int c = ; if ( count != null ) { c = count . intValue ( ) ; } loggers . put ( className , new Integer ( c + ) ) ; return className + "" + c ; } } public static String getLogger ( Object component ) { if ( component instanceof LogEnabled ) { return ( ( LogEnabled ) component ) . loggerName ( ) ; } return null ; } } package org . oddjob . logging ; public interface LogEnabled { public String loggerName ( ) ; } package org . oddjob . logging ; public interface LoggingConstants { public static final String MDC_LOGGER = "" ; public static final String MDC_JOB_NAME = "" ; } package org . oddjob . logging ; public interface ArchiveNameResolver { public String resolveName ( Object component ) ; } package org . oddjob . logging ; public interface LogListener { public void logEvent ( LogEvent logEvent ) ; } package org . oddjob ; public enum OddjobInheritance { NONE , PROPERTIES , SHARED , } package org . oddjob ; import java . util . Map ; public interface Describeable { public Map < String , String > describe ( ) ; } package org . oddjob . describe ; import java . util . Map ; public interface Describer { public Map < String , String > describe ( Object bean ) ; } package org . oddjob . describe ; import java . util . Map ; import java . util . TreeMap ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . deploy . ArooaAnnotation ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . reflect . PropertyAccessor ; public class AccessorDescriber implements Describer { private final ArooaSession session ; public AccessorDescriber ( ArooaSession session ) { if ( session == null ) { throw new NullPointerException ( "" ) ; } this . session = session ; } @ Override public Map < String , String > describe ( Object bean ) { PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; ArooaClass arooaClass = accessor . getClassName ( bean ) ; BeanOverview overview = arooaClass . getBeanOverview ( accessor ) ; ArooaAnnotations annotations = session . getArooaDescriptor ( ) . getBeanDescriptor ( arooaClass , accessor ) . getAnnotations ( ) ; Map < String , String > description = new TreeMap < String , String > ( ) ; String [ ] properties = overview . getProperties ( ) ; for ( String property : properties ) { if ( overview . hasReadableProperty ( property ) && ! overview . isIndexed ( property ) && ! overview . isMapped ( property ) ) { ArooaAnnotation annotation = annotations . annotationForProperty ( property , NoDescribe . class . getName ( ) ) ; if ( annotation != null ) { continue ; } Object value = accessor . getProperty ( bean , property ) ; if ( value == null ) { description . put ( property , null ) ; } else { description . put ( property , value . toString ( ) ) ; } } } return description ; } } package org . oddjob . describe ; import java . util . Map ; import org . oddjob . Describeable ; public class DescribeableDescriber implements Describer { @ Override public Map < String , String > describe ( Object bean ) { if ( bean instanceof Describeable ) { return ( ( Describeable ) bean ) . describe ( ) ; } else { return null ; } } } package org . oddjob . describe ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . METHOD ) public @ interface DescribeWith { } package org . oddjob . describe ; import java . lang . reflect . Method ; import java . util . Map ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . reflect . PropertyAccessor ; public class AnnotationDescriber implements Describer { private final ArooaSession session ; public AnnotationDescriber ( ArooaSession session ) { if ( session == null ) { throw new NullPointerException ( "" ) ; } this . session = session ; } @ SuppressWarnings ( "" ) @ Override public Map < String , String > describe ( Object bean ) { PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; ArooaBeanDescriptor descriptor = session . getArooaDescriptor ( ) . getBeanDescriptor ( accessor . getClassName ( bean ) , accessor ) ; Method method = descriptor . getAnnotations ( ) . methodFor ( DescribeWith . class . getName ( ) ) ; if ( method == null ) { return null ; } try { return ( Map < String , String > ) method . invoke ( bean ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } package org . oddjob . describe ; import java . util . Map ; import org . oddjob . arooa . ArooaSession ; public class UniversalDescriber implements Describer { private final Describer [ ] describers ; public UniversalDescriber ( ArooaSession session ) { describers = new Describer [ ] { new DescribeableDescriber ( ) , new AnnotationDescriber ( session ) , new AccessorDescriber ( session ) } ; } @ Override public Map < String , String > describe ( Object bean ) { for ( int i = ; i < describers . length ; ++ i ) { Map < String , String > description = describers [ i ] . describe ( bean ) ; if ( description != null ) { return description ; } } return null ; } } package org . oddjob . describe ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( { ElementType . FIELD , ElementType . METHOD } ) public @ interface NoDescribe { } package org . oddjob . io ; import java . io . IOException ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . types . ValueFactory ; public class TeeType implements ValueFactory < OutputStream > { private final List < OutputStream > outputs = new ArrayList < OutputStream > ( ) ; public void setOutputs ( int index , OutputStream output ) { if ( output == null ) { outputs . remove ( index ) ; } else { outputs . add ( index , output ) ; } } @ Override public OutputStream toValue ( ) throws ArooaConversionException { return new OutputStream ( ) { @ Override public void write ( int b ) throws IOException { for ( OutputStream output : outputs ) { output . write ( b ) ; } } @ Override public void write ( byte [ ] b ) throws IOException { for ( OutputStream output : outputs ) { output . write ( b ) ; } } @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { for ( OutputStream output : outputs ) { output . write ( b , off , len ) ; } } @ Override public void flush ( ) throws IOException { for ( OutputStream output : outputs ) { output . flush ( ) ; } } @ Override public void close ( ) throws IOException { for ( OutputStream output : outputs ) { output . close ( ) ; } } } ; } } package org . oddjob . io ; import java . io . File ; import java . io . Serializable ; import org . apache . log4j . Logger ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; public class RenameJob implements Runnable , Serializable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( RenameJob . class ) ; private String name ; private File from ; private File to ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public File getFrom ( ) { return from ; } @ ArooaAttribute public void setFrom ( File file ) { this . from = file ; } public File getTo ( ) { return to ; } @ ArooaAttribute public void setTo ( File file ) { this . to = file ; } public void run ( ) { if ( from == null ) { throw new NullPointerException ( "" ) ; } if ( to == null ) { throw new NullPointerException ( "" ) ; } if ( ! from . exists ( ) ) { throw new RuntimeException ( "" + from + "" ) ; } if ( ! from . renameTo ( to ) ) { throw new RuntimeException ( "" + from + "" + to + "" ) ; } else { logger . info ( "" + from + "" + to ) ; } } public String toString ( ) { if ( name == null ) { return "" ; } return name ; } } package org . oddjob . io ; import java . io . File ; import java . io . IOException ; import java . io . Serializable ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; public class MkdirJob implements Runnable , Serializable { private static final Logger logger = Logger . getLogger ( MkdirJob . class ) ; private static final long serialVersionUID = ; private String name ; private File dir ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public File getDir ( ) { return dir ; } @ ArooaAttribute public void setDir ( File file ) { this . dir = file ; } public void run ( ) { if ( dir == null ) { throw new IllegalStateException ( "" ) ; } try { if ( dir . exists ( ) ) { if ( dir . isDirectory ( ) ) { logger . info ( "" + dir + "" ) ; } else { throw new IllegalArgumentException ( "" + dir + "" ) ; } } else { FileUtils . forceMkdir ( dir ) ; logger . info ( "" + dir + "" ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } public String toString ( ) { if ( name == null ) { return "" ; } return name ; } } package org . oddjob . io ; import java . io . FilterInputStream ; import java . io . IOException ; import java . io . InputStream ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . types . ValueFactory ; public class StdinType implements ValueFactory < InputStream > { @ Override public InputStream toValue ( ) throws ArooaConversionException { return new FilterInputStream ( System . in ) { @ Override public void close ( ) throws IOException { } } ; } } package org . oddjob . io ; import java . io . File ; import java . io . IOException ; import java . io . Serializable ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; public class FileType implements ArooaValue , Serializable { private static final long serialVersionUID = ; public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( FileType . class , File . class , new Convertlet < FileType , File > ( ) { public File convert ( FileType from ) throws ConvertletException { try { return from . toCanonicalFile ( ) ; } catch ( IOException e ) { throw new ConvertletException ( "" + from . file + "" , e ) ; } } } ) ; registry . register ( FileType . class , File [ ] . class , new Convertlet < FileType , File [ ] > ( ) { public File [ ] convert ( FileType from ) throws ConvertletException { File file = null ; try { file = from . toCanonicalFile ( ) ; } catch ( IOException e ) { throw new ConvertletException ( "" , e ) ; } if ( file == null ) { return null ; } else { return new File [ ] { file } ; } } } ) ; } } private File file ; public File getFile ( ) { return file ; } public File toCanonicalFile ( ) throws IOException { return file == null ? null : file . getCanonicalFile ( ) ; } @ ArooaAttribute public void setFile ( File file ) { this . file = file ; } public String toString ( ) { return "" + getFile ( ) ; } } package org . oddjob . io ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . Serializable ; import org . apache . commons . io . FileUtils ; import org . apache . commons . io . IOUtils ; import org . apache . log4j . Logger ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . util . OddjobConfigException ; public class CopyJob implements Runnable , Serializable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( CopyJob . class ) ; private String name ; private File [ ] from ; private File to ; private transient InputStream input ; private transient OutputStream output ; private int filesCopied ; private int directoriesCopied ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } synchronized public File [ ] getFrom ( ) { return from ; } synchronized public void setFrom ( File [ ] file ) { this . from = file ; } synchronized public File getTo ( ) { return to ; } @ ArooaAttribute synchronized public void setTo ( File file ) { this . to = file ; } synchronized public void setInput ( InputStream in ) { this . input = in ; } synchronized public void setOutput ( OutputStream out ) { this . output = out ; } public int getFilesCopied ( ) { return filesCopied ; } public int getDirectoriesCopied ( ) { return directoriesCopied ; } public void run ( ) { try { CopyCommand command = command ( ) ; if ( command == null ) { throw new NullPointerException ( "" ) ; } logger . info ( "" + command . toString ( ) ) ; CopyStats stats = new CopyStats ( ) ; command . copy ( stats ) ; logger . info ( "" + stats . files + "" + stats . directories + "" ) ; this . filesCopied = stats . files ; this . directoriesCopied = stats . directories ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } private CopyCommand command ( ) throws IOException { if ( input != null ) { if ( output != null ) { return new StreamCopy ( input , output ) ; } else { return new StreamCopy ( input , to ) ; } } if ( from == null ) { throw new RuntimeException ( "" ) ; } File [ ] possiblyMany = Files . expand ( from ) ; Files . verifyReadable ( possiblyMany ) ; File singleFrom = null ; if ( possiblyMany . length == ) { throw new RuntimeException ( "" ) ; } if ( possiblyMany . length == ) { singleFrom = possiblyMany [ ] ; } if ( singleFrom != null ) { if ( output != null ) { return new StreamCopy ( singleFrom , output ) ; } else if ( singleFrom . isDirectory ( ) ) { return new DirectoryCopy ( singleFrom , to ) ; } else { return new FileCopy ( singleFrom , to ) ; } } return new MultiFileCopy ( possiblyMany , to ) ; } public InputStream getInput ( ) { return input ; } public OutputStream getOutput ( ) { return output ; } public String toString ( ) { if ( name == null ) { return "" ; } return name ; } interface CopyCommand { public void copy ( CopyStats stats ) throws IOException ; } static class StreamCopy implements CopyCommand { private final InputStream in ; private final OutputStream out ; StreamCopy ( InputStream in , OutputStream out ) { this . in = in ; this . out = out ; } StreamCopy ( InputStream in , File to ) throws IOException { this . in = in ; if ( to == null ) { throw new RuntimeException ( "" ) ; } if ( to . isDirectory ( ) ) { throw new OddjobConfigException ( "" ) ; } this . out = new FileOutputStream ( to ) ; } StreamCopy ( File from , OutputStream out ) throws IOException { this . in = new FileInputStream ( from ) ; this . out = out ; } @ Override public void copy ( CopyStats stats ) throws IOException { IOUtils . copy ( in , out ) ; in . close ( ) ; out . close ( ) ; stats . files ++ ; } @ Override public String toString ( ) { return "" ; } } static class FileCopy implements CopyCommand { private final File from ; private final File to ; FileCopy ( File from , File to ) { this . from = from ; this . to = to ; } @ Override public void copy ( CopyStats stats ) throws IOException { if ( to . isDirectory ( ) ) { FileUtils . copyFileToDirectory ( from , to ) ; } else { FileUtils . copyFile ( from , to ) ; } stats . files ++ ; } @ Override public String toString ( ) { return "" + from + "" + to ; } } static class DirectoryCopy implements CopyCommand { private final File fromDir ; private final File toDir ; DirectoryCopy ( File from , File to ) { this . fromDir = from ; if ( to == null ) { throw new RuntimeException ( "" ) ; } if ( to . exists ( ) ) { if ( ! to . isDirectory ( ) ) { throw new OddjobConfigException ( "" ) ; } this . toDir = new File ( to , from . getName ( ) ) ; } else { this . toDir = to ; } } @ Override public void copy ( CopyStats stats ) throws IOException { FileUtils . copyDirectory ( fromDir , toDir ) ; stats . directories ++ ; } @ Override public String toString ( ) { return "" + fromDir + "" + toDir ; } } static class MultiFileCopy implements CopyCommand { private final File [ ] files ; private final File toDir ; MultiFileCopy ( File [ ] files , File toDir ) { this . files = files ; if ( toDir == null ) { throw new RuntimeException ( "" ) ; } if ( ! toDir . isDirectory ( ) ) { throw new RuntimeException ( "" ) ; } this . toDir = toDir ; } @ Override public void copy ( CopyStats stats ) throws IOException { for ( int i = ; i < files . length ; ++ i ) { CopyCommand command ; if ( files [ i ] . isDirectory ( ) ) { command = new DirectoryCopy ( files [ i ] , toDir ) ; } else { command = new FileCopy ( files [ i ] , toDir ) ; } command . copy ( stats ) ; } } @ Override public String toString ( ) { return "" + files . length + "" + toDir ; } } class CopyStats { int files ; int directories ; } } package org . oddjob . io ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . ClassResolver ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaSessionAware ; public class ResourceType implements ArooaValue , ArooaSessionAware { public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( ResourceType . class , InputStream . class , new Convertlet < ResourceType , InputStream > ( ) { public InputStream convert ( ResourceType from ) throws ConvertletException { try { return from . toInputStream ( ) ; } catch ( IOException e ) { throw new ConvertletException ( e ) ; } } } ) ; registry . register ( ResourceType . class , String . class , new Convertlet < ResourceType , String > ( ) { public String convert ( ResourceType from ) throws ConvertletException { return from . resource ; } } ) ; } } private String resource ; private ArooaSession session ; public ResourceType ( ) { } public ResourceType ( String resource ) { this . resource = resource ; } @ Override @ ArooaHidden public void setArooaSession ( ArooaSession session ) { this . session = session ; } public InputStream toInputStream ( ) throws IOException { URL url = null ; if ( session == null ) { url = getClass ( ) . getClassLoader ( ) . getResource ( resource ) ; } else { ClassResolver resolver = session . getArooaDescriptor ( ) . getClassResolver ( ) ; url = resolver . getResource ( resource ) ; } if ( url == null ) { throw new IOException ( "" + resource ) ; } return url . openStream ( ) ; } public void setResource ( String resource ) { this . resource = resource ; } public String toString ( ) { return resource ; } } package org . oddjob . io ; import java . io . File ; import java . io . FileFilter ; import java . util . Arrays ; import java . util . LinkedList ; import java . util . Set ; import java . util . TreeSet ; import org . apache . commons . io . FilenameUtils ; public class WildcardSpec { private File file ; public WildcardSpec ( String spec ) { this ( new File ( spec ) ) ; } public WildcardSpec ( File file ) { this . file = file ; } public File [ ] findFiles ( ) { DirectorySplit split = new DirectorySplit ( file ) ; return findFiles ( split ) ; } public File [ ] findFiles ( final DirectorySplit split ) { Set < File > results = new TreeSet < File > ( ) ; if ( split . getParentFile ( ) == null ) { results . add ( new File ( split . getName ( ) ) ) ; } else { File [ ] matching = split . getParentFile ( ) . listFiles ( new FileFilter ( ) { public boolean accept ( File pathname ) { return FilenameUtils . wildcardMatchOnSystem ( pathname . getName ( ) , split . getName ( ) ) ; } } ) ; for ( int i = ; matching != null && i < matching . length ; ++ i ) { if ( ! split . isBottom ( ) ) { if ( matching [ i ] . isDirectory ( ) ) { File [ ] more = findFiles ( split . next ( matching [ i ] . getName ( ) ) ) ; results . addAll ( Arrays . asList ( more ) ) ; } } else { results . add ( matching [ i ] ) ; } } } return ( File [ ] ) results . toArray ( new File [ ] ) ; } static class DirectorySplit { LinkedList < AboveAndBelow > split = new LinkedList < AboveAndBelow > ( ) ; private DirectorySplit ( ) { } DirectorySplit ( File file ) { for ( AboveAndBelow ab = new AboveAndBelow ( file ) ; true ; ab = new AboveAndBelow ( ab ) ) { split . add ( ab ) ; if ( ab . top ) { break ; } if ( ab . parent . getPath ( ) . indexOf ( '' ) < && ab . parent . getPath ( ) . indexOf ( '' ) < ) { break ; } } } File getParentFile ( ) { File parent = ( ( AboveAndBelow ) split . getLast ( ) ) . parent ; return parent ; } String getName ( ) { return ( ( AboveAndBelow ) split . getLast ( ) ) . name ; } boolean isBottom ( ) { return ( ( AboveAndBelow ) split . getLast ( ) ) . below == null ; } int getSize ( ) { return split . size ( ) ; } DirectorySplit next ( String name ) { if ( split . size ( ) == ) { return null ; } DirectorySplit next = new DirectorySplit ( ) ; next . split = new LinkedList < AboveAndBelow > ( split ) ; next . split . removeLast ( ) ; ( ( AboveAndBelow ) next . split . getLast ( ) ) . parent = new File ( getParentFile ( ) , name ) ; return next ; } } static class AboveAndBelow { File parent ; String name ; File below ; boolean top ; AboveAndBelow ( AboveAndBelow previous ) { if ( previous . top ) { throw new IllegalStateException ( "" ) ; } if ( previous . parent == null ) { throw new IllegalStateException ( "" ) ; } parent = previous . parent . getParentFile ( ) ; if ( parent == null ) { if ( previous . parent . isAbsolute ( ) ) { throw new IllegalStateException ( "" ) ; } parent = previous . parent . getAbsoluteFile ( ) . getParentFile ( ) ; top = true ; } else { if ( parent . getAbsoluteFile ( ) . getParentFile ( ) == null ) { top = true ; } } name = previous . parent . getName ( ) ; if ( previous . below == null ) { below = new File ( previous . name ) ; } else { below = new File ( previous . name , previous . below . getPath ( ) ) ; } } AboveAndBelow ( File first ) { parent = first . getParentFile ( ) ; if ( parent == null ) { parent = first . getAbsoluteFile ( ) . getParentFile ( ) ; top = true ; } name = first . getName ( ) ; below = null ; } } public static boolean match ( String pattern , String str , boolean isCaseSensitive ) { char [ ] patArr = pattern . toCharArray ( ) ; char [ ] strArr = str . toCharArray ( ) ; int patIdxStart = ; int patIdxEnd = patArr . length - ; int strIdxStart = ; int strIdxEnd = strArr . length - ; char ch ; boolean containsStar = false ; for ( int i = ; i < patArr . length ; i ++ ) { if ( patArr [ i ] == '' ) { containsStar = true ; break ; } } if ( ! containsStar ) { if ( patIdxEnd != strIdxEnd ) { return false ; } for ( int i = ; i <= patIdxEnd ; i ++ ) { ch = patArr [ i ] ; if ( ch != '' ) { if ( isCaseSensitive && ch != strArr [ i ] ) { return false ; } if ( ! isCaseSensitive && Character . toUpperCase ( ch ) != Character . toUpperCase ( strArr [ i ] ) ) { return false ; } } } return true ; } if ( patIdxEnd == ) { return true ; } while ( ( ch = patArr [ patIdxStart ] ) != '' && strIdxStart <= strIdxEnd ) { if ( ch != '' ) { if ( isCaseSensitive && ch != strArr [ strIdxStart ] ) { return false ; } if ( ! isCaseSensitive && Character . toUpperCase ( ch ) != Character . toUpperCase ( strArr [ strIdxStart ] ) ) { return false ; } } patIdxStart ++ ; strIdxStart ++ ; } if ( strIdxStart > strIdxEnd ) { for ( int i = patIdxStart ; i <= patIdxEnd ; i ++ ) { if ( patArr [ i ] != '' ) { return false ; } } return true ; } while ( ( ch = patArr [ patIdxEnd ] ) != '' && strIdxStart <= strIdxEnd ) { if ( ch != '' ) { if ( isCaseSensitive && ch != strArr [ strIdxEnd ] ) { return false ; } if ( ! isCaseSensitive && Character . toUpperCase ( ch ) != Character . toUpperCase ( strArr [ strIdxEnd ] ) ) { return false ; } } patIdxEnd -- ; strIdxEnd -- ; } if ( strIdxStart > strIdxEnd ) { for ( int i = patIdxStart ; i <= patIdxEnd ; i ++ ) { if ( patArr [ i ] != '' ) { return false ; } } return true ; } while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) { int patIdxTmp = - ; for ( int i = patIdxStart + ; i <= patIdxEnd ; i ++ ) { if ( patArr [ i ] == '' ) { patIdxTmp = i ; break ; } } if ( patIdxTmp == patIdxStart + ) { patIdxStart ++ ; continue ; } int patLength = ( patIdxTmp - patIdxStart - ) ; int strLength = ( strIdxEnd - strIdxStart + ) ; int foundIdx = - ; strLoop : for ( int i = ; i <= strLength - patLength ; i ++ ) { for ( int j = ; j < patLength ; j ++ ) { ch = patArr [ patIdxStart + j + ] ; if ( ch != '' ) { if ( isCaseSensitive && ch != strArr [ strIdxStart + i + j ] ) { continue strLoop ; } if ( ! isCaseSensitive && Character . toUpperCase ( ch ) != Character . toUpperCase ( strArr [ strIdxStart + i + j ] ) ) { continue strLoop ; } } } foundIdx = strIdxStart + i ; break ; } if ( foundIdx == - ) { return false ; } patIdxStart = patIdxTmp ; strIdxStart = foundIdx + patLength ; } for ( int i = patIdxStart ; i <= patIdxEnd ; i ++ ) { if ( patArr [ i ] != '' ) { return false ; } } return true ; } } package org . oddjob . io ; import java . io . FilterOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . types . ValueFactory ; public class StdoutType implements ValueFactory < OutputStream > { @ Override public OutputStream toValue ( ) throws ArooaConversionException { return new FilterOutputStream ( System . out ) { @ Override public void close ( ) throws IOException { super . flush ( ) ; } } ; } } package org . oddjob . io ; import java . io . File ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; public class FilesType implements ArooaValue , Serializable { private static final long serialVersionUID = ; public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( FilesType . class , File [ ] . class , new Convertlet < FilesType , File [ ] > ( ) { public File [ ] convert ( FilesType from ) throws ConvertletException { return from . toFiles ( ) ; } } ) ; } } private String files ; private final List < File [ ] > list = new ArrayList < File [ ] > ( ) ; public void setFiles ( String files ) { this . files = files ; } public String getFiles ( ) { return files ; } public void setList ( int index , File [ ] files ) { if ( files == null ) { list . remove ( index ) ; } else { list . add ( index , files ) ; } } public File [ ] toFiles ( ) { List < File > all = new ArrayList < File > ( ) ; if ( files != null ) { addFileArray ( all , Files . expand ( new File [ ] { new File ( files ) } ) ) ; } for ( File [ ] files : list ) { addFileArray ( all , files ) ; } return all . toArray ( new File [ all . size ( ) ] ) ; } private void addFileArray ( List < File > list , File [ ] array ) { for ( File file : array ) { if ( list . contains ( file ) ) { continue ; } list . add ( file ) ; } } public String toString ( ) { return "" ; } } package org . oddjob . io ; import java . io . FilterOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . types . ValueFactory ; public class StderrType implements ValueFactory < OutputStream > { @ Override public OutputStream toValue ( ) throws ArooaConversionException { return new FilterOutputStream ( System . err ) { @ Override public void close ( ) throws IOException { super . flush ( ) ; } } ; } } package org . oddjob . io ; import java . io . File ; import java . util . Arrays ; import java . util . SortedSet ; import java . util . TreeSet ; public class Files { public static File [ ] expand ( File [ ] files ) { SortedSet < File > results = new TreeSet < File > ( ) ; for ( int i = ; i < files . length ; ++ i ) { results . addAll ( Arrays . asList ( new WildcardSpec ( files [ i ] ) . findFiles ( ) ) ) ; } return ( File [ ] ) results . toArray ( new File [ ] ) ; } public static void verifyReadable ( File [ ] files ) throws RuntimeException { for ( int i = ; i < files . length ; ++ i ) { if ( ! files [ i ] . exists ( ) ) { throw new RuntimeException ( "" + files [ i ] + "" ) ; } if ( ! files [ i ] . canRead ( ) ) { throw new RuntimeException ( "" + files [ i ] + "" ) ; } } } public static void verifyWrite ( File [ ] files ) throws RuntimeException { for ( int i = ; i < files . length ; ++ i ) { if ( ! files [ i ] . exists ( ) ) { throw new RuntimeException ( "" + files [ i ] + "" ) ; } if ( ! files [ i ] . canWrite ( ) ) { throw new RuntimeException ( "" + files [ i ] + "" ) ; } } } } package org . oddjob . io ; import java . io . File ; import java . io . IOException ; import java . io . Serializable ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; public class DeleteJob implements Runnable , Serializable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( DeleteJob . class ) ; private String name ; private File [ ] files ; private boolean force ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public File [ ] getFiles ( ) { return files ; } public void setFiles ( File [ ] files ) { this . files = files ; } public boolean getForce ( ) { return force ; } public void setForce ( boolean force ) { this . force = force ; } public void run ( ) { if ( files == null ) { throw new IllegalStateException ( "" ) ; } File [ ] toDelete = Files . expand ( files ) ; Files . verifyWrite ( toDelete ) ; int fileCount = ; int dirCount = ; for ( int i = ; i < toDelete . length ; ++ i ) { if ( toDelete [ i ] . isDirectory ( ) ) { ++ dirCount ; } else { ++ fileCount ; } if ( force ) { try { FileUtils . forceDelete ( toDelete [ i ] ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } else { if ( ! toDelete [ i ] . delete ( ) ) { throw new RuntimeException ( "" + toDelete [ i ] ) ; } } logger . debug ( "" + toDelete [ i ] ) ; } logger . info ( "" + fileCount + "" + dirCount + "" ) ; } public String toString ( ) { if ( name == null ) { return "" ; } else { return name ; } } } package org . oddjob . io ; import java . io . BufferedReader ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . io . PrintStream ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . deploy . annotations . ArooaText ; import org . oddjob . arooa . life . ArooaLifeAware ; public class BufferType implements ArooaValue , ArooaLifeAware { public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( BufferType . class , String . class , new Convertlet < BufferType , String > ( ) { public String convert ( BufferType from ) { return from . getText ( ) ; } } ) ; registry . register ( BufferType . class , InputStream . class , new Convertlet < BufferType , InputStream > ( ) { public InputStream convert ( BufferType from ) { return from . toInputStream ( ) ; } } ) ; registry . register ( BufferType . class , OutputStream . class , new Convertlet < BufferType , OutputStream > ( ) { public OutputStream convert ( BufferType from ) { return from . toOutputStream ( ) ; } } ) ; registry . register ( BufferType . class , String [ ] . class , new Convertlet < BufferType , String [ ] > ( ) { public String [ ] convert ( BufferType from ) { return from . getLines ( ) ; } } ) ; } } private volatile ByteArrayOutputStream buffer ; private volatile String text ; private volatile String [ ] lines ; public InputStream toInputStream ( ) { if ( buffer == null ) { return null ; } else { return new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; } } public OutputStream toOutputStream ( ) { return buffer ; } @ ArooaText public void setText ( String text ) throws IOException { this . text = text ; } public String getText ( ) { if ( buffer == null ) { return null ; } else { return new String ( buffer . toByteArray ( ) ) ; } } public String [ ] getLines ( ) { try { InputStream inputStream = toInputStream ( ) ; if ( inputStream == null ) { return null ; } BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; List < String > lines = new ArrayList < String > ( ) ; while ( true ) { String line = reader . readLine ( ) ; if ( line == null ) { break ; } lines . add ( line ) ; } return lines . toArray ( new String [ lines . size ( ) ] ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } public void setLines ( String [ ] lines ) { this . lines = lines ; } @ Override public void initialised ( ) { } @ Override public void configured ( ) { buffer = new ByteArrayOutputStream ( ) ; if ( text != null ) { try { buffer . write ( text . getBytes ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } if ( lines != null ) { PrintStream print = new PrintStream ( buffer ) ; for ( String line : lines ) { print . println ( line ) ; } print . flush ( ) ; } } @ Override public void destroy ( ) { buffer = null ; } public String toString ( ) { return "" + ( buffer == null ? "" : buffer . size ( ) + "" ) + "" ; } } package org . oddjob . io ; import java . io . File ; import java . io . Serializable ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; public class ExistsJob implements Runnable , Serializable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( ExistsJob . class ) ; private String name ; private File file ; private File [ ] exists ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public File getFile ( ) { return file ; } @ ArooaAttribute public void setFile ( File file ) { this . file = file ; } public File [ ] getExists ( ) { return exists ; } public int getResult ( ) { if ( exists == null ) { return - ; } return exists . length > ? : ; } public void run ( ) { if ( file == null ) { throw new IllegalStateException ( "" ) ; } logger . info ( "" + file ) ; WildcardSpec wild = new WildcardSpec ( file ) ; exists = wild . findFiles ( ) ; if ( exists . length == ) { logger . info ( "" ) ; } for ( File found : exists ) { logger . info ( "" + found ) ; } } public long getSize ( ) { File [ ] exists = this . exists ; if ( exists == null || exists . length != ) { return - ; } return exists [ ] . length ( ) ; } public Date getLastModified ( ) { File [ ] exists = this . exists ; if ( exists == null || exists . length != ) { return null ; } return new Date ( exists [ ] . lastModified ( ) ) ; } public String toString ( ) { if ( name == null ) { return "" ; } return name ; } } package org . oddjob . io ; import java . io . BufferedOutputStream ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . OutputStream ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public class AppendType implements ArooaValue { public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( AppendType . class , OutputStream . class , new Convertlet < AppendType , OutputStream > ( ) { public OutputStream convert ( AppendType from ) throws ConvertletException { try { return new BufferedOutputStream ( new FileOutputStream ( from . file , true ) ) ; } catch ( FileNotFoundException e ) { throw new ConvertletException ( e ) ; } } } ) ; } } private File file ; public File getFile ( ) { return file ; } public void setFile ( File file ) { this . file = file ; } public String toString ( ) { return "" + file . toString ( ) ; } } package org . oddjob ; public interface Loadable { public void load ( ) ; public void unload ( ) ; public boolean isLoadable ( ) ; } package org . oddjob ; import javax . swing . ImageIcon ; import org . oddjob . images . IconListener ; public interface Iconic { public ImageIcon iconForId ( String id ) ; public void addIconListener ( IconListener listener ) ; public void removeIconListener ( IconListener listener ) ; } package org . oddjob . monitor ; import java . awt . event . ActionEvent ; import java . awt . event . KeyEvent ; import javax . swing . KeyStroke ; public class Standards extends org . oddjob . arooa . design . view . Standards { public static final Integer NEW_MNEMONIC_KEY = new Integer ( KeyEvent . VK_N ) ; public static final KeyStroke NEW_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_N , ActionEvent . CTRL_MASK ) ; public static final Integer OPEN_MNEMONIC_KEY = new Integer ( KeyEvent . VK_O ) ; public static final KeyStroke OPEN_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_O , ActionEvent . CTRL_MASK ) ; public static final Integer CLOSE_MNEMONIC_KEY = new Integer ( KeyEvent . VK_C ) ; public static final KeyStroke CLOSE_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_F4 , ActionEvent . CTRL_MASK ) ; public static final Integer RELOAD_MNEMONIC_KEY = new Integer ( KeyEvent . VK_R ) ; public static final KeyStroke RELOAD_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_L , ActionEvent . CTRL_MASK ) ; public static final Integer SAVE_MNEMONIC_KEY = new Integer ( KeyEvent . VK_S ) ; public static final KeyStroke SAVE_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_S , ActionEvent . CTRL_MASK ) ; public static final Integer SAVEAS_MNEMONIC_KEY = new Integer ( KeyEvent . VK_A ) ; public static final KeyStroke SAVEAS_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_A , ActionEvent . CTRL_MASK ) ; public static final Integer RUN_MNEMONIC_KEY = new Integer ( KeyEvent . VK_R ) ; public static final KeyStroke RUN_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_R , ActionEvent . CTRL_MASK ) ; public static final Integer SOFT_RESET_MNEMONIC_KEY = new Integer ( KeyEvent . VK_S ) ; public static final KeyStroke SOFT_RESET_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_J , ActionEvent . CTRL_MASK ) ; public static final Integer HARD_RESET_MNEMONIC_KEY = new Integer ( KeyEvent . VK_H ) ; public static final KeyStroke HARD_RESET_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_H , ActionEvent . CTRL_MASK ) ; public static final Integer STOP_MNEMONIC_KEY = new Integer ( KeyEvent . VK_T ) ; public static final KeyStroke STOP_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_T , ActionEvent . CTRL_MASK ) ; public static final Integer FORCE_MNEMONIC_KEY = new Integer ( KeyEvent . VK_F ) ; public static final Integer PROPERTY_MNEMONIC_KEY = new Integer ( KeyEvent . VK_P ) ; public static final KeyStroke PROPERTY_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_P , ActionEvent . CTRL_MASK ) ; public static final Integer LOAD_MNEMONIC_KEY = new Integer ( KeyEvent . VK_L ) ; public static final KeyStroke LOAD_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_L , ActionEvent . CTRL_MASK ) ; public static final Integer UNLOAD_MNEMONIC_KEY = new Integer ( KeyEvent . VK_U ) ; public static final KeyStroke UNLOAD_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_D , ActionEvent . CTRL_MASK ) ; public static final Integer DESIGNER_MNEMONIC_KEY = new Integer ( KeyEvent . VK_D ) ; public static final KeyStroke DESIGNER_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_G , ActionEvent . CTRL_MASK ) ; public static final Integer DESIGN_INSIDE_MNEMONIC_KEY = new Integer ( KeyEvent . VK_I ) ; public static final KeyStroke DESIGNER_INSIDE_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_I , ActionEvent . CTRL_MASK ) ; public static final Integer ADD_JOB_MNEMONIC_KEY = new Integer ( KeyEvent . VK_B ) ; public static final KeyStroke ADD_JOB_ACCELERATOR_KEY = KeyStroke . getKeyStroke ( KeyEvent . VK_B , ActionEvent . CTRL_MASK ) ; } package org . oddjob . monitor ; import java . awt . event . ActionEvent ; import java . awt . event . ComponentAdapter ; import java . awt . event . ComponentEvent ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import java . beans . PropertyVetoException ; import java . beans . VetoableChangeListener ; import java . beans . VetoableChangeSupport ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . PrintWriter ; import java . util . ArrayList ; import java . util . Collection ; import java . util . LinkedHashSet ; import java . util . List ; import java . util . Set ; import javax . inject . Inject ; import javax . swing . AbstractAction ; import javax . swing . Action ; import javax . swing . JFileChooser ; import javax . swing . JFrame ; import javax . swing . JMenu ; import javax . swing . JMenuItem ; import javax . swing . JOptionPane ; import javax . swing . JSeparator ; import javax . swing . JTree ; import javax . swing . SwingUtilities ; import javax . swing . UIManager ; import javax . swing . WindowConstants ; import javax . swing . event . TreeModelEvent ; import javax . swing . event . TreeModelListener ; import javax . swing . event . TreeSelectionEvent ; import javax . swing . event . TreeSelectionListener ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobServices ; import org . oddjob . OddjobShutdownThread ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . design . view . ScreenPresence ; import org . oddjob . arooa . design . view . Standards ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ConfigOwnerEvent ; import org . oddjob . arooa . parsing . ConfigSessionEvent ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . ElementConfiguration ; import org . oddjob . arooa . parsing . OwnerStateListener ; import org . oddjob . arooa . parsing . SessionStateListener ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . framework . SerializableJob ; import org . oddjob . monitor . context . AncestorSearch ; import org . oddjob . monitor . control . PropertyPolling ; import org . oddjob . monitor . model . ConfigContextInialiser ; import org . oddjob . monitor . model . ExplorerModel ; import org . oddjob . monitor . model . ExplorerModelImpl ; import org . oddjob . monitor . model . FileHistory ; import org . oddjob . monitor . model . JobTreeNode ; import org . oddjob . monitor . view . ExplorerComponent ; import org . oddjob . monitor . view . MonitorMenuBar ; import org . oddjob . state . State ; import org . oddjob . swing . SwingInputHandler ; import org . oddjob . util . SimpleThreadManager ; import org . oddjob . util . ThreadManager ; public class OddjobExplorer extends SerializableJob implements Stoppable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( OddjobExplorer . class ) ; public static final String ODDJOB_PROPERTY = "" ; public static final String DEFAULT_TITLE = "" ; protected transient VetoableChangeSupport vetoableChangeSupport ; private File dir ; private transient volatile Oddjob oddjob ; private transient ConfigurationSession focus ; private long pollingInterval = ; private transient String logFormat ; private File file ; private volatile transient JFrame frame ; private transient Action newExplorerAction ; private transient Action newAction ; private transient Action openAction ; private transient Action saveAction ; private transient Action saveAsAction ; private transient Action closeAction ; private transient Action exitAction ; private transient JMenu fileMenu ; private transient ExplorerModel explorerModel ; private transient ExplorerComponent explorerComponent ; private transient MonitorMenuBar menuBar ; private transient PropertyPolling propertyPolling ; private transient ThreadManager threadManager ; private transient OddjobServices oddjobServices ; private FileHistory fileHistory ; private ScreenPresence screen ; transient private Set < ConfigurationOwner > owners ; public OddjobExplorer ( ) { fileHistory = new FileHistory ( ) ; ScreenPresence whole = ScreenPresence . wholeScreen ( ) ; screen = whole . smaller ( ) ; completeConstruction ( ) ; } public OddjobExplorer ( MultiViewController controller , ScreenPresence screen , FileHistory sharedFileHistory ) { this . screen = screen ; this . fileHistory = sharedFileHistory ; this . newExplorerAction = new NewExplorerAction ( controller ) ; completeConstruction ( ) ; } private void completeConstruction ( ) { vetoableChangeSupport = new VetoableChangeSupport ( this ) ; owners = new LinkedHashSet < ConfigurationOwner > ( ) ; newAction = new NewAction ( ) ; openAction = new OpenAction ( ) ; saveAction = new SaveAction ( ) ; saveAsAction = new SaveAsAction ( ) ; closeAction = new CloseAction ( ) ; exitAction = new ExitAction ( ) ; fileHistory . addChangeAction ( new Runnable ( ) { @ Override public void run ( ) { if ( frame == null ) { fileHistory . removeChangeAction ( this ) ; } else { SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { updateFileMenu ( ) ; } } ) ; } } } ) ; } protected ExplorerComponent getExplorerComponent ( ) { return explorerComponent ; } @ Inject public void setOddjobServices ( OddjobServices oddjobServices ) { this . oddjobServices = oddjobServices ; } @ Override public void setArooaSession ( ArooaSession session ) { super . setArooaSession ( session ) ; propertyPolling = new PropertyPolling ( this , session ) ; } public void setOddjob ( Oddjob oddjob ) throws PropertyVetoException { if ( this . oddjob == oddjob ) { return ; } Object oldValue = this . oddjob ; vetoableChangeSupport . fireVetoableChange ( ODDJOB_PROPERTY , oldValue , oddjob ) ; if ( this . oddjob != null ) { addFileHistory ( this . oddjob . getFile ( ) ) ; this . oddjob . destroy ( ) ; } this . oddjob = oddjob ; if ( oddjob != null && oddjob . getDir ( ) != null ) { this . dir = oddjob . getDir ( ) ; } firePropertyChange ( ODDJOB_PROPERTY , oldValue , this . oddjob ) ; } public Oddjob getOddjob ( ) { return oddjob ; } @ ArooaAttribute public void setDir ( File dir ) { this . dir = dir ; } public File getDir ( ) { return dir ; } public String getTitle ( ) { return frame . getTitle ( ) ; } void addFileHistory ( File file ) { if ( file == null ) { return ; } fileHistory . addHistory ( file ) ; } void updateFileMenu ( ) { fileMenu . removeAll ( ) ; if ( newExplorerAction != null ) { fileMenu . add ( new JMenuItem ( newExplorerAction ) ) ; } fileMenu . add ( new JMenuItem ( newAction ) ) ; fileMenu . add ( new JMenuItem ( openAction ) ) ; fileMenu . add ( new JMenuItem ( saveAction ) ) ; fileMenu . add ( new JMenuItem ( saveAsAction ) ) ; fileMenu . add ( new JMenuItem ( closeAction ) ) ; fileMenu . add ( new JSeparator ( ) ) ; Action a [ ] = new Action [ fileHistory . size ( ) ] ; for ( int i = ; i < fileHistory . size ( ) ; ++ i ) { a [ fileHistory . size ( ) - i - ] = new HistoryAction ( fileHistory . size ( ) - i , ( File ) fileHistory . get ( i ) ) ; } boolean hasHistory = false ; for ( int i = ; i < a . length ; ++ i ) { hasHistory = true ; fileMenu . add ( new JMenuItem ( a [ i ] ) ) ; } if ( hasHistory ) { fileMenu . add ( new JSeparator ( ) ) ; } fileMenu . add ( new JMenuItem ( exitAction ) ) ; } public void show ( ) { if ( frame == null ) { throw new IllegalStateException ( "" ) ; } frame . toFront ( ) ; } class CheckOddjobStopped implements VetoableChangeListener { public void vetoableChange ( PropertyChangeEvent evt ) throws PropertyVetoException { if ( ! ODDJOB_PROPERTY . equals ( evt . getPropertyName ( ) ) ) { return ; } Oddjob oddjob = ( Oddjob ) evt . getOldValue ( ) ; if ( oddjob == null ) { return ; } State state = oddjob . lastStateEvent ( ) . getState ( ) ; if ( state . isStoppable ( ) ) { String message = "" + state ; JOptionPane . showMessageDialog ( frame , message , "" , JOptionPane . ERROR_MESSAGE ) ; throw new PropertyVetoException ( message , evt ) ; } String [ ] active = threadManager . activeDescriptions ( ) ; if ( active . length > ) { StringBuilder message = new StringBuilder ( ) ; message . append ( "" ) ; for ( int i = ; i < active . length ; ++ i ) { message . append ( active [ i ] ) ; message . append ( '' ) ; } message . append ( '' ) ; JOptionPane . showMessageDialog ( frame , message , "" , JOptionPane . ERROR_MESSAGE ) ; throw new PropertyVetoException ( message . toString ( ) , evt ) ; } } } class TrackConfigurationOwners implements TreeModelListener { public void treeNodesChanged ( TreeModelEvent e ) { } public void treeStructureChanged ( TreeModelEvent e ) { } public void treeNodesInserted ( TreeModelEvent event ) { for ( Object child : event . getChildren ( ) ) { Object component = ( ( JobTreeNode ) child ) . getComponent ( ) ; if ( component instanceof ConfigurationOwner ) { owners . add ( ( ConfigurationOwner ) component ) ; } } } public void treeNodesRemoved ( TreeModelEvent event ) { for ( Object child : event . getChildren ( ) ) { Object component = ( ( JobTreeNode ) child ) . getComponent ( ) ; owners . remove ( component ) ; } } } private boolean saveAs = false ; class CheckConfigurationsSaved implements VetoableChangeListener { public void vetoableChange ( PropertyChangeEvent evt ) throws PropertyVetoException { if ( ! ODDJOB_PROPERTY . equals ( evt . getPropertyName ( ) ) ) { return ; } Oddjob oldOddjob = ( Oddjob ) evt . getOldValue ( ) ; if ( oldOddjob != null ) { List < ConfigurationOwner > modified = new ArrayList < ConfigurationOwner > ( ) ; for ( ConfigurationOwner owner : owners ) { if ( saveAs && owner == oldOddjob ) { continue ; } ConfigurationSession session = owner . provideConfigurationSession ( ) ; if ( session != null && session . isModified ( ) ) { modified . add ( owner ) ; } } if ( ! modified . isEmpty ( ) && ! canClose ( modified ) ) { throw new PropertyVetoException ( "" , evt ) ; } } owners . clear ( ) ; Oddjob newOddjob = ( Oddjob ) evt . getNewValue ( ) ; if ( newOddjob != null ) { owners . add ( newOddjob ) ; } } boolean canClose ( Collection < ConfigurationOwner > modified ) { StringBuilder message = new StringBuilder ( ) ; message . append ( "" ) ; for ( ConfigurationOwner owner : modified ) { message . append ( owner . toString ( ) ) ; message . append ( '' ) ; } message . append ( '' ) ; int option = JOptionPane . showConfirmDialog ( explorerComponent , message . toString ( ) , "" , JOptionPane . OK_CANCEL_OPTION , JOptionPane . WARNING_MESSAGE ) ; if ( option == JOptionPane . OK_OPTION ) { return true ; } else { return false ; } } } private transient String name ; private transient boolean modified ; private transient ConfigurationOwner current ; class ChangeFocus implements PropertyChangeListener , TreeSelectionListener , OwnerStateListener , SessionStateListener { public void propertyChange ( PropertyChangeEvent evt ) { if ( ! ODDJOB_PROPERTY . equals ( evt . getPropertyName ( ) ) ) { return ; } Oddjob newJob = ( Oddjob ) evt . getNewValue ( ) ; setOwner ( newJob ) ; } public void valueChanged ( TreeSelectionEvent e ) { JobTreeNode selected = ( JobTreeNode ) ( ( JTree ) e . getSource ( ) ) . getLastSelectedPathComponent ( ) ; if ( selected == null ) { setOwner ( oddjob ) ; } else { AncestorSearch search = new AncestorSearch ( selected . getExplorerContext ( ) ) ; ConfigurationOwner configOwner = ( ConfigurationOwner ) search . getValue ( ConfigContextInialiser . CONFIG_OWNER ) ; setOwner ( configOwner ) ; } } public void sessionChanged ( ConfigOwnerEvent event ) { updateSession ( event . getSource ( ) . provideConfigurationSession ( ) ) ; writeTitle ( ) ; } public void sessionModifed ( ConfigSessionEvent event ) { modified = true ; writeTitle ( ) ; } public void sessionSaved ( ConfigSessionEvent event ) { modified = false ; writeTitle ( ) ; } void setOwner ( ConfigurationOwner owner ) { if ( current == owner ) { return ; } if ( current != null ) { current . removeOwnerStateListener ( this ) ; } if ( owner == null ) { name = null ; modified = false ; updateSession ( null ) ; } else { name = owner . toString ( ) ; updateSession ( owner . provideConfigurationSession ( ) ) ; owner . addOwnerStateListener ( this ) ; } current = owner ; writeTitle ( ) ; } void updateSession ( ConfigurationSession session ) { if ( focus != null ) { focus . removeSessionStateListener ( this ) ; } focus = session ; if ( focus == null ) { modified = false ; } else { focus . addSessionStateListener ( this ) ; modified = focus . isModified ( ) ; } } void writeTitle ( ) { if ( frame == null ) { return ; } String title = DEFAULT_TITLE ; if ( name != null ) { title += "" + name + ( modified ? "" : "" ) ; } frame . setTitle ( title ) ; } } class ChangeView implements PropertyChangeListener { public void propertyChange ( PropertyChangeEvent evt ) { if ( ! ODDJOB_PROPERTY . equals ( evt . getPropertyName ( ) ) ) { return ; } Oddjob oldJob = ( Oddjob ) evt . getOldValue ( ) ; Oddjob newJob = ( Oddjob ) evt . getNewValue ( ) ; if ( oldJob != null ) { menuBar . noSession ( ) ; explorerComponent . destroy ( ) ; explorerModel . destroy ( ) ; frame . getContentPane ( ) . removeAll ( ) ; } if ( newJob != null ) { ExplorerModelImpl explorerModel = new ExplorerModelImpl ( new StandardArooaSession ( ) ) ; explorerModel . setThreadManager ( threadManager ) ; explorerModel . setLogFormat ( logFormat ) ; explorerModel . setOddjob ( newJob ) ; OddjobExplorer . this . explorerModel = explorerModel ; explorerComponent = new ExplorerComponent ( explorerModel , propertyPolling ) ; explorerComponent . bindTo ( menuBar ) ; JTree tree = explorerComponent . getTree ( ) ; tree . addTreeSelectionListener ( new ChangeFocus ( ) ) ; tree . getModel ( ) . addTreeModelListener ( new TrackConfigurationOwners ( ) ) ; frame . getContentPane ( ) . add ( explorerComponent ) ; explorerComponent . balance ( ) ; } frame . validate ( ) ; frame . repaint ( ) ; } } void createView ( ) { menuBar = new MonitorMenuBar ( ) ; fileMenu = menuBar . getFileMenu ( ) ; updateFileMenu ( ) ; frame = new JFrame ( ) ; screen . fit ( frame ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { maybeCloseWindow ( ) ; } public void windowClosed ( WindowEvent e ) { logger . debug ( "" ) ; } } ) ; frame . setDefaultCloseOperation ( WindowConstants . DO_NOTHING_ON_CLOSE ) ; frame . setJMenuBar ( menuBar ) ; frame . setTitle ( DEFAULT_TITLE ) ; } protected int execute ( ) throws Exception { threadManager = new SimpleThreadManager ( ) ; UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; createView ( ) ; final Oddjob oddjob = this . oddjob ; this . oddjob = null ; VetoableChangeListener checkStop = new CheckOddjobStopped ( ) ; VetoableChangeListener checkSaved = new CheckConfigurationsSaved ( ) ; PropertyChangeListener changeTitle = new ChangeFocus ( ) ; PropertyChangeListener changeView = new ChangeView ( ) ; vetoableChangeSupport . addVetoableChangeListener ( checkStop ) ; vetoableChangeSupport . addVetoableChangeListener ( checkSaved ) ; addPropertyChangeListener ( changeView ) ; addPropertyChangeListener ( changeTitle ) ; frame . setVisible ( true ) ; frame . addComponentListener ( new ComponentAdapter ( ) { @ Override public void componentMoved ( ComponentEvent e ) { screen = new ScreenPresence ( e . getComponent ( ) ) ; } @ Override public void componentResized ( ComponentEvent e ) { screen = new ScreenPresence ( e . getComponent ( ) ) ; } } ) ; SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { try { if ( oddjob != null ) { setOddjob ( oddjob ) ; } else if ( getFile ( ) != null ) { open ( getFile ( ) ) ; } } catch ( PropertyVetoException e ) { } } } ) ; while ( ! stop ) { try { if ( propertyPolling == null ) { logger ( ) . info ( "" ) ; } else { propertyPolling . poll ( ) ; } } catch ( RuntimeException e ) { logger ( ) . error ( "" , e ) ; } synchronized ( this ) { try { wait ( pollingInterval ) ; } catch ( InterruptedException e ) { break ; } } } vetoableChangeSupport . removeVetoableChangeListener ( checkStop ) ; vetoableChangeSupport . removeVetoableChangeListener ( checkSaved ) ; removePropertyChangeListener ( changeView ) ; removePropertyChangeListener ( changeTitle ) ; threadManager . close ( ) ; return ; } private void maybeCloseWindow ( ) { try { setOddjob ( null ) ; } catch ( PropertyVetoException e ) { logger . info ( "" + e . getMessage ( ) ) ; return ; } closeWindow ( ) ; } private void closeWindow ( ) { stop = true ; synchronized ( OddjobExplorer . this ) { OddjobExplorer . this . notifyAll ( ) ; } final JFrame frame = this . frame ; if ( frame != null ) { if ( ! ( Thread . currentThread ( ) instanceof OddjobShutdownThread ) ) { frame . dispose ( ) ; } this . frame = null ; } logger ( ) . debug ( "" ) ; } public void onStop ( ) throws FailedToStopException { closeWindow ( ) ; Oddjob oddjob = this . oddjob ; if ( oddjob != null ) { oddjob . stop ( ) ; try { setOddjob ( null ) ; } catch ( PropertyVetoException e ) { this . oddjob = null ; } } } private Oddjob newOddjob ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setArooaSession ( getArooaSession ( ) ) ; oddjob . setOddjobServices ( oddjobServices ) ; oddjob . setInputHandler ( new SwingInputHandler ( frame ) ) ; return oddjob ; } class NewExplorerAction extends AbstractAction { private static final long serialVersionUID = ; private final MultiViewController multiViewController ; NewExplorerAction ( MultiViewController multiViewController ) { this . multiViewController = multiViewController ; putValue ( Action . NAME , "" ) ; putValue ( Action . MNEMONIC_KEY , Standards . NEW_EXPLORER_MNEMONIC_KEY ) ; putValue ( Action . ACCELERATOR_KEY , Standards . NEW_EXPLORER_ACCELERATOR_KEY ) ; } @ Override public void actionPerformed ( ActionEvent e ) { multiViewController . launchNewExplorer ( OddjobExplorer . this ) ; } } class NewAction extends AbstractAction { private static final long serialVersionUID = ; NewAction ( ) { putValue ( Action . NAME , "" ) ; putValue ( Action . MNEMONIC_KEY , Standards . NEW_MNEMONIC_KEY ) ; putValue ( Action . ACCELERATOR_KEY , Standards . NEW_ACCELERATOR_KEY ) ; } public void actionPerformed ( final ActionEvent e ) { try { Oddjob newJob = newOddjob ( ) ; ArooaConfiguration saveAsConfig = new ArooaConfiguration ( ) { public ConfigurationHandle parse ( ArooaContext parentContext ) throws ArooaParseException { final ConfigurationHandle handle = new ElementConfiguration ( Oddjob . ODDJOB_ELEMENT ) . parse ( parentContext ) ; return new ConfigurationHandle ( ) { public ArooaContext getDocumentContext ( ) { return handle . getDocumentContext ( ) ; } ; public void save ( ) throws ArooaParseException { saveAsAction . actionPerformed ( e ) ; } ; } ; } } ; newJob . setConfiguration ( saveAsConfig ) ; newJob . load ( ) ; setOddjob ( newJob ) ; } catch ( PropertyVetoException e1 ) { } catch ( RuntimeException ex ) { logger ( ) . warn ( "" , ex ) ; JOptionPane . showMessageDialog ( frame , ex . getMessage ( ) , "" , JOptionPane . ERROR_MESSAGE ) ; } } } class SaveAction extends AbstractAction { private static final long serialVersionUID = ; SaveAction ( ) { putValue ( Action . NAME , "" ) ; putValue ( Action . MNEMONIC_KEY , Standards . SAVE_MNEMONIC_KEY ) ; putValue ( Action . ACCELERATOR_KEY , Standards . SAVE_ACCELERATOR_KEY ) ; OddjobExplorer . this . addPropertyChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent evt ) { setEnabled ( oddjob != null ) ; } } ) ; } public void actionPerformed ( ActionEvent e ) { if ( focus == null ) { return ; } try { focus . save ( ) ; } catch ( Exception exception ) { logger . error ( "" , exception ) ; JOptionPane . showMessageDialog ( frame . getContentPane ( ) , exception . getMessage ( ) , "" , JOptionPane . ERROR_MESSAGE ) ; return ; } } } class SaveAsAction extends AbstractAction { private static final long serialVersionUID = ; SaveAsAction ( ) { putValue ( Action . NAME , "" ) ; putValue ( Action . MNEMONIC_KEY , Standards . SAVEAS_MNEMONIC_KEY ) ; putValue ( Action . ACCELERATOR_KEY , Standards . SAVEAS_ACCELERATOR_KEY ) ; OddjobExplorer . this . addPropertyChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent evt ) { setEnabled ( oddjob != null ) ; } } ) ; } public void actionPerformed ( ActionEvent e ) { ConfigurationSession config = oddjob . provideConfigurationSession ( ) ; if ( config == null ) { JOptionPane . showMessageDialog ( frame . getContentPane ( ) , "" , "" , JOptionPane . INFORMATION_MESSAGE ) ; return ; } JFileChooser chooser = new JFileChooser ( ) ; if ( dir != null ) { chooser . setCurrentDirectory ( dir ) ; } int option = chooser . showSaveDialog ( frame ) ; if ( option != JFileChooser . APPROVE_OPTION ) { return ; } File file = chooser . getSelectedFile ( ) ; try { XMLArooaParser parser = new XMLArooaParser ( ) ; ArooaConfiguration oddjobConfiguration = config . dragPointFor ( oddjob ) ; parser . parse ( oddjobConfiguration ) ; PrintWriter printWriter = new PrintWriter ( new FileWriter ( file ) ) ; printWriter . print ( parser . getXml ( ) ) ; printWriter . close ( ) ; addFileHistory ( oddjob . getFile ( ) ) ; Oddjob newJob = newOddjob ( ) ; newJob . setFile ( file ) ; newJob . load ( ) ; saveAs = true ; setOddjob ( newJob ) ; } catch ( PropertyVetoException e1 ) { } catch ( Exception exception ) { logger . error ( "" , exception ) ; JOptionPane . showMessageDialog ( frame . getContentPane ( ) , exception . getMessage ( ) , "" , JOptionPane . ERROR_MESSAGE ) ; return ; } finally { saveAs = false ; } } } class OpenAction extends AbstractAction { private static final long serialVersionUID = ; OpenAction ( ) { putValue ( Action . NAME , "" ) ; putValue ( Action . MNEMONIC_KEY , Standards . OPEN_MNEMONIC_KEY ) ; putValue ( Action . ACCELERATOR_KEY , Standards . OPEN_ACCELERATOR_KEY ) ; } public void actionPerformed ( ActionEvent e ) { JFileChooser chooser = new JFileChooser ( ) ; if ( dir != null ) { chooser . setCurrentDirectory ( dir ) ; } int option = chooser . showOpenDialog ( frame ) ; if ( option != JFileChooser . APPROVE_OPTION ) { return ; } open ( chooser . getSelectedFile ( ) ) ; } } class CloseAction extends AbstractAction { private static final long serialVersionUID = ; CloseAction ( ) { putValue ( Action . NAME , "" ) ; putValue ( Action . MNEMONIC_KEY , Standards . CLOSE_MNEMONIC_KEY ) ; putValue ( Action . ACCELERATOR_KEY , Standards . CLOSE_ACCELERATOR_KEY ) ; OddjobExplorer . this . addPropertyChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent evt ) { setEnabled ( oddjob != null ) ; } } ) ; } public void actionPerformed ( ActionEvent e ) { try { setOddjob ( null ) ; } catch ( PropertyVetoException e1 ) { } catch ( RuntimeException ex ) { logger ( ) . warn ( "" , ex ) ; JOptionPane . showMessageDialog ( frame , ex . getMessage ( ) , "" , JOptionPane . ERROR_MESSAGE ) ; } } } class ExitAction extends AbstractAction { private static final long serialVersionUID = ; ExitAction ( ) { putValue ( Action . NAME , "" ) ; putValue ( Action . MNEMONIC_KEY , Standards . EXIT_MNEMONIC_KEY ) ; } public void actionPerformed ( ActionEvent e ) { maybeCloseWindow ( ) ; } } class HistoryAction extends AbstractAction { private static final long serialVersionUID = ; private final File file ; HistoryAction ( int number , File file ) { putValue ( Action . NAME , "" + number + "" + file . getName ( ) + "" + file . getAbsoluteFile ( ) . getParent ( ) + "" ) ; putValue ( Action . MNEMONIC_KEY , new Integer ( + number ) ) ; this . file = file ; } public void actionPerformed ( ActionEvent e ) { try { Oddjob newJob = newOddjob ( ) ; newJob . setFile ( file ) ; newJob . load ( ) ; setOddjob ( newJob ) ; } catch ( PropertyVetoException e1 ) { } catch ( RuntimeException ex ) { logger ( ) . warn ( "" + file + "" , ex ) ; JOptionPane . showMessageDialog ( frame , ex . getMessage ( ) , "" , JOptionPane . ERROR_MESSAGE ) ; } } } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; completeConstruction ( ) ; } public synchronized long getPollingInterval ( ) { return pollingInterval ; } public synchronized void setPollingInterval ( long pollingInterval ) { this . pollingInterval = pollingInterval ; } public int getFileHistorySize ( ) { return fileHistory . size ( ) ; } public void setFileHistorySize ( int fileHistorySize ) { this . fileHistory . setListSize ( fileHistorySize ) ; } public ScreenPresence getScreen ( ) { return screen ; } public String getLogFormat ( ) { return logFormat ; } public void setLogFormat ( String logFormat ) { this . logFormat = logFormat ; } private void open ( File file ) { try { Oddjob newJob = newOddjob ( ) ; newJob . setFile ( file ) ; newJob . load ( ) ; setOddjob ( newJob ) ; } catch ( PropertyVetoException e1 ) { logger . info ( "" ) ; } catch ( RuntimeException ex ) { logger ( ) . warn ( "" + file + "" , ex ) ; JOptionPane . showMessageDialog ( frame , ex . getMessage ( ) , "" , JOptionPane . ERROR_MESSAGE ) ; } } public File getFile ( ) { return file ; } @ ArooaAttribute public void setFile ( File file ) { this . file = file ; } } package org . oddjob . monitor ; import java . io . File ; import javax . inject . Inject ; import org . oddjob . OddjobServices ; import org . oddjob . Stoppable ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . design . view . ScreenPresence ; import org . oddjob . framework . StructuralJob ; import org . oddjob . monitor . model . FileHistory ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; public class MultiExplorerLauncher extends StructuralJob < Runnable > implements Stoppable { private static final long serialVersionUID = ; @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } private transient OddjobServices oddjobServices ; private File dir ; private File file ; private long pollingInterval = ; private transient String logFormat ; private FileHistory fileHistory ; private ScreenPresence screen ; public MultiExplorerLauncher ( ) { fileHistory = new FileHistory ( ) ; ScreenPresence whole = ScreenPresence . wholeScreen ( ) ; screen = whole . smaller ( ) ; } @ Inject public void setOddjobServices ( OddjobServices oddjobServices ) { this . oddjobServices = oddjobServices ; } protected void execute ( ) throws InterruptedException { if ( oddjobServices == null ) { throw new NullPointerException ( "" ) ; } MultiViewController controller = new MultiViewController ( ) { @ Override public synchronized void launchNewExplorer ( OddjobExplorer original ) { if ( original != null ) { dir = original . getDir ( ) ; screen = original . getScreen ( ) ; } OddjobExplorer explorer = new OddjobExplorer ( this , screen , fileHistory ) ; explorer . setDir ( MultiExplorerLauncher . this . dir ) ; explorer . setPollingInterval ( pollingInterval ) ; explorer . setLogFormat ( logFormat ) ; explorer . setOddjobServices ( oddjobServices ) ; explorer . setArooaSession ( getArooaSession ( ) ) ; if ( original == null ) { explorer . setFile ( getFile ( ) ) ; } childHelper . insertChild ( childHelper . size ( ) , explorer ) ; oddjobServices . getOddjobExecutors ( ) . getPoolExecutor ( ) . execute ( explorer ) ; } } ; controller . launchNewExplorer ( null ) ; } @ Override protected void onReset ( ) { super . onReset ( ) ; childHelper . removeAllChildren ( ) ; } public File getDir ( ) { return dir ; } @ ArooaAttribute public void setDir ( File dir ) { this . dir = dir ; } public File getFile ( ) { return file ; } @ ArooaAttribute public void setFile ( File file ) { this . file = file ; } public long getPollingInterval ( ) { return pollingInterval ; } public void setPollingInterval ( long pollingInterval ) { this . pollingInterval = pollingInterval ; } public int getFileHistorySize ( ) { return fileHistory . getListSize ( ) ; } public void setFileHistorySize ( int fileHistorySize ) { this . fileHistory . setListSize ( fileHistorySize ) ; } public String getLogFormat ( ) { return logFormat ; } public void setLogFormat ( String logFormat ) { this . logFormat = logFormat ; } } package org . oddjob . monitor . model ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . monitor . actions . FormAction ; abstract public class JobFormAction extends JobAction implements FormAction { @ Override public final Form form ( ) { if ( checkPrepare ( ) ) { return doForm ( ) ; } else { return null ; } } abstract protected Form doForm ( ) ; } package org . oddjob . monitor . model ; import java . util . concurrent . Executor ; import javax . swing . event . TreeModelListener ; import javax . swing . tree . TreeModel ; import javax . swing . tree . TreeNode ; import javax . swing . tree . TreePath ; public class JobTreeModel implements TreeModel { private final TreeEventDispatcher eventDispatcher ; private JobTreeNode root ; public JobTreeModel ( ) { this ( new ExecutorTreeEventDispatcher ( new EventThreadOnlyDispatcher ( ) ) ) ; } public JobTreeModel ( Executor executor ) { this ( new ExecutorTreeEventDispatcher ( executor ) ) ; } public JobTreeModel ( TreeEventDispatcher eventDispatcher ) { if ( eventDispatcher == null ) { throw new NullPointerException ( "" ) ; } this . eventDispatcher = eventDispatcher ; } public void setRootTreeNode ( JobTreeNode node ) { this . root = node ; } public void addTreeModelListener ( TreeModelListener tml ) { eventDispatcher . addTreeModelListener ( tml ) ; } public void removeTreeModelListener ( TreeModelListener tml ) { eventDispatcher . removeTreeModelListener ( tml ) ; } public Object getChild ( Object parent , int index ) { return ( ( JobTreeNode ) parent ) . getChildAt ( index ) ; } public boolean isLeaf ( Object node ) { return ( ( JobTreeNode ) node ) . isLeaf ( ) ; } public int getChildCount ( Object parent ) { return ( ( JobTreeNode ) parent ) . getChildCount ( ) ; } public int getIndexOfChild ( Object parent , Object child ) { return ( ( JobTreeNode ) parent ) . getIndex ( ( JobTreeNode ) child ) ; } public Object getRoot ( ) { return root ; } public void valueForPathChanged ( TreePath path , Object newValue ) { throw new UnsupportedOperationException ( "" ) ; } public void fireTreeNodesChanged ( TreeNode changed ) { eventDispatcher . fireTreeNodesChanged ( changed ) ; } public void fireTreeNodesInserted ( TreeNode changed , JobTreeNode child , int index ) { eventDispatcher . fireTreeNodesInserted ( changed , child , index ) ; } public void fireTreeNodesRemoved ( TreeNode changed , JobTreeNode child , int index ) { eventDispatcher . fireTreeNodesRemoved ( changed , child , index ) ; } } package org . oddjob . monitor . model ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; public class LogContextInialiser implements ContextInitialiser { public static String LOG_ARCHIVER = "" ; public static String CONSOLE_ARCHIVER = "" ; private final ExplorerModel explorerModel ; public LogContextInialiser ( ExplorerModel explorerModel ) { this . explorerModel = explorerModel ; } public void initialise ( ExplorerContext context ) { LogArchiver logArchiver ; ConsoleArchiver consoleArchiver ; ExplorerContext parent = context . getParent ( ) ; if ( parent == null ) { logArchiver = explorerModel . getLogArchiver ( ) ; consoleArchiver = explorerModel . getConsoleArchiver ( ) ; } else { if ( parent . getThisComponent ( ) instanceof LogArchiver ) { logArchiver = ( ( LogArchiver ) parent . getThisComponent ( ) ) ; } else { logArchiver = ( LogArchiver ) parent . getValue ( LOG_ARCHIVER ) ; } if ( parent . getThisComponent ( ) instanceof ConsoleArchiver ) { consoleArchiver = ( ( ConsoleArchiver ) parent . getThisComponent ( ) ) ; } else { consoleArchiver = ( ConsoleArchiver ) parent . getValue ( CONSOLE_ARCHIVER ) ; } } context . setValue ( LOG_ARCHIVER , logArchiver ) ; context . setValue ( CONSOLE_ARCHIVER , consoleArchiver ) ; } } package org . oddjob . monitor . model ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; public class ConfigContextInialiser implements ContextInitialiser { public static String CONFIG_OWNER = "" ; private final ExplorerModel explorerModel ; public ConfigContextInialiser ( ExplorerModel explorerModel ) { this . explorerModel = explorerModel ; } public void initialise ( ExplorerContext context ) { ConfigurationOwner configOwner = null ; ExplorerContext parent = context . getParent ( ) ; if ( parent == null ) { configOwner = explorerModel . getOddjob ( ) ; } else { if ( context . getThisComponent ( ) instanceof ConfigurationOwner ) { configOwner = ( ConfigurationOwner ) context . getThisComponent ( ) ; } } if ( configOwner != null ) { context . setValue ( CONFIG_OWNER , configOwner ) ; } } } package org . oddjob . monitor . model ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . OJConstants ; import org . oddjob . Oddjob ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . cache . LocalConsoleArchiver ; import org . oddjob . logging . log4j . Log4jArchiver ; import org . oddjob . monitor . actions . ExplorerAction ; import org . oddjob . monitor . actions . ResourceActionProvider ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . util . ThreadManager ; public class ExplorerModelImpl implements ExplorerModel { private Oddjob oddjob ; private String logFormat ; private ThreadManager threadManager ; private Log4jArchiver logArchiver ; private LocalConsoleArchiver consoleArchiver ; private final ContextInitialiser [ ] contextInitialisers ; private final ExplorerAction [ ] explorerActions ; public ExplorerModelImpl ( ArooaSession session ) { explorerActions = new ResourceActionProvider ( session ) . getExplorerActions ( ) ; List < ContextInitialiser > initialisers = new ArrayList < ContextInitialiser > ( ) ; initialisers . add ( new LogContextInialiser ( this ) ) ; initialisers . add ( new ConfigContextInialiser ( this ) ) ; for ( ExplorerAction action : explorerActions ) { if ( action instanceof ContextInitialiser ) { initialisers . add ( ( ContextInitialiser ) action ) ; } } contextInitialisers = initialisers . toArray ( new ContextInitialiser [ initialisers . size ( ) ] ) ; } public void setOddjob ( Oddjob rootNode ) { this . oddjob = rootNode ; logArchiver = new Log4jArchiver ( rootNode , logFormat == null ? OJConstants . DEFAULT_LOG_FORMAT : logFormat ) ; consoleArchiver = new LocalConsoleArchiver ( ) ; } public Oddjob getOddjob ( ) { return oddjob ; } public void setThreadManager ( ThreadManager threadManager ) { this . threadManager = threadManager ; } public ThreadManager getThreadManager ( ) { return threadManager ; } public void destroy ( ) { logArchiver . onDestroy ( ) ; consoleArchiver . onDestroy ( ) ; } public String getLogFormat ( ) { return logFormat ; } public void setLogFormat ( String logFormat ) { this . logFormat = logFormat ; } public LogArchiver getLogArchiver ( ) { return logArchiver ; } public ConsoleArchiver getConsoleArchiver ( ) { return consoleArchiver ; } public ContextInitialiser [ ] getContextInitialisers ( ) { return contextInitialisers ; } public ExplorerAction [ ] getExplorerActions ( ) { return explorerActions ; } } package org . oddjob . monitor . model ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import java . beans . PropertyChangeSupport ; import org . oddjob . monitor . actions . ExplorerAction ; import org . oddjob . monitor . context . ExplorerContext ; abstract public class JobAction implements ExplorerAction { private final PropertyChangeSupport propertySupport = new PropertyChangeSupport ( this ) ; private boolean enabled = false ; private boolean visible = false ; private boolean prepared = false ; private ExplorerContext explorerContext ; final public boolean isEnabled ( ) { return enabled ; } protected void setEnabled ( boolean enabled ) { if ( this . enabled == enabled ) { return ; } PropertyChangeEvent event = new PropertyChangeEvent ( this , ENABLED_PROPERTY , this . enabled , enabled ) ; this . enabled = enabled ; propertySupport . firePropertyChange ( event ) ; } final public boolean isVisible ( ) { return visible ; } protected void setVisible ( boolean visible ) { if ( this . visible == visible ) { return ; } PropertyChangeEvent event = new PropertyChangeEvent ( this , VISIBLE_PROPERTY , this . visible , visible ) ; this . visible = visible ; propertySupport . firePropertyChange ( event ) ; } public void addPropertyChangeListener ( PropertyChangeListener listener ) { propertySupport . addPropertyChangeListener ( listener ) ; } public void removePropertyChangeListener ( PropertyChangeListener listener ) { propertySupport . removePropertyChangeListener ( listener ) ; } @ Override public final void setSelectedContext ( ExplorerContext explorerContext ) { if ( this . explorerContext != null ) { if ( prepared ) { doFree ( this . explorerContext ) ; } this . explorerContext = null ; } if ( explorerContext == null ) { setVisible ( false ) ; setEnabled ( false ) ; } else { setVisible ( true ) ; setEnabled ( true ) ; } this . prepared = false ; this . explorerContext = explorerContext ; } @ Override public final void prepare ( ) { if ( explorerContext == null ) { throw new NullPointerException ( "" ) ; } doPrepare ( explorerContext ) ; prepared = true ; } protected ExplorerContext getExplorerContext ( ) { return explorerContext ; } protected boolean isPrepared ( ) { return prepared ; } abstract protected void doAction ( ) throws Exception ; protected final boolean checkPrepare ( ) { if ( ! prepared ) { doPrepare ( explorerContext ) ; prepared = true ; } return enabled ; } @ Override public final void action ( ) throws Exception { if ( checkPrepare ( ) ) { doAction ( ) ; } } protected void doPrepare ( ExplorerContext explorerContext ) { } protected void doFree ( ExplorerContext explorerContext ) { } } package org . oddjob . monitor . model ; import org . oddjob . logging . LogLevel ; public interface LogEventProcessor { public void onClear ( ) ; public void onUnavailable ( ) ; public void onEvent ( String text , LogLevel level ) ; } package org . oddjob . monitor . model ; import org . oddjob . Oddjob ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . monitor . actions . ExplorerAction ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . util . ThreadManager ; public interface ExplorerModel { public Oddjob getOddjob ( ) ; public ThreadManager getThreadManager ( ) ; public String getLogFormat ( ) ; public LogArchiver getLogArchiver ( ) ; public ConsoleArchiver getConsoleArchiver ( ) ; public ContextInitialiser [ ] getContextInitialisers ( ) ; public ExplorerAction [ ] getExplorerActions ( ) ; public void destroy ( ) ; } package org . oddjob . monitor . model ; import java . util . concurrent . Executor ; import javax . swing . SwingUtilities ; public class EventThreadOnlyDispatcher implements Executor { @ Override public void execute ( Runnable command ) { if ( ! SwingUtilities . isEventDispatchThread ( ) ) { throw new IllegalStateException ( "" ) ; } command . run ( ) ; } } package org . oddjob . monitor . model ; import java . util . Observable ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogListener ; public class LogModel extends Observable implements LogListener { public void setUnAvailable ( ) { LogAction e = new UnavailableEvent ( ) ; setChanged ( ) ; notifyObservers ( e ) ; } public void setClear ( ) { LogAction e = new ClearEvent ( ) ; setChanged ( ) ; notifyObservers ( e ) ; } public void logEvent ( LogEvent event ) { LogAction e = new MessageEvent ( event . getMessage ( ) , event . getLevel ( ) ) ; setChanged ( ) ; notifyObservers ( e ) ; } } package org . oddjob . monitor . model ; import org . oddjob . monitor . context . ExplorerContext ; public interface SelectedContextAware { public void setSelectedContext ( ExplorerContext context ) ; public void prepare ( ) ; } package org . oddjob . monitor . model ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import java . beans . PropertyChangeSupport ; import java . util . Observable ; import org . oddjob . Stateful ; import org . oddjob . framework . JobDestroyedException ; import org . oddjob . framework . PropertyChangeNotifier ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogLevel ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class DetailModel implements PropertyChangeNotifier { public static final String SELECTED_CONTEXT_PROPERTY = "" ; public static final String TAB_SELECTED_PROPERTY = "" ; public static final int STATE_TAB = ; public static final int CONSOLE_TAB = ; public static final int LOG_TAB = ; public static final int PROPERTIES_TAB = ; private int tabSelected = STATE_TAB ; private ExplorerContext selectedContext ; private final LogModel consoleModel = new LogModel ( ) ; private final LogModel logModel = new LogModel ( ) ; private PropertyModel propertyModel = new PropertyModel ( ) ; private final StateModel stateModel = new StateModel ( ) ; private final StateListener stateListener = new StateListener ( ) { public void jobStateChange ( StateEvent event ) { stateModel . change ( event ) ; } } ; private final PropertyChangeSupport propertySupport = new PropertyChangeSupport ( this ) ; public LogModel getConsoleModel ( ) { return consoleModel ; } public LogModel getLogModel ( ) { return logModel ; } public PropertyModel getPropertyModel ( ) { return propertyModel ; } public void setTabSelected ( int tabSelected ) { if ( this . tabSelected == tabSelected ) { return ; } if ( selectedContext != null ) { freeTab ( this . tabSelected ) ; } PropertyChangeEvent event = new PropertyChangeEvent ( this , TAB_SELECTED_PROPERTY , new Integer ( this . tabSelected ) , new Integer ( tabSelected ) ) ; this . tabSelected = tabSelected ; if ( selectedContext != null ) { try { engageTab ( tabSelected ) ; } catch ( JobDestroyedException e ) { } } propertySupport . firePropertyChange ( event ) ; } public int getTabSelected ( ) { return tabSelected ; } private void freeTab ( int index ) { Object selectedJob = selectedContext . getThisComponent ( ) ; switch ( index ) { case STATE_TAB : stateModel . clear ( ) ; if ( selectedJob instanceof Stateful ) { ( ( Stateful ) selectedJob ) . removeStateListener ( stateListener ) ; } break ; case CONSOLE_TAB : ConsoleArchiver consoleArchiver = ( ConsoleArchiver ) selectedContext . getValue ( LogContextInialiser . CONSOLE_ARCHIVER ) ; consoleArchiver . removeConsoleListener ( consoleModel , selectedJob ) ; consoleModel . setClear ( ) ; break ; case LOG_TAB : LogArchiver logArchiver = ( LogArchiver ) selectedContext . getValue ( LogContextInialiser . LOG_ARCHIVER ) ; logArchiver . removeLogListener ( logModel , selectedJob ) ; logModel . setClear ( ) ; break ; case PROPERTIES_TAB : break ; default : throw new IllegalArgumentException ( "" + index + "" ) ; } } private void engageTab ( int index ) throws JobDestroyedException { Object selectedJob = selectedContext . getThisComponent ( ) ; switch ( index ) { case STATE_TAB : if ( selectedJob instanceof Stateful ) { ( ( Stateful ) selectedJob ) . addStateListener ( stateListener ) ; } break ; case CONSOLE_TAB : ConsoleArchiver consoleArchiver = ( ConsoleArchiver ) selectedContext . getValue ( LogContextInialiser . CONSOLE_ARCHIVER ) ; consoleArchiver . addConsoleListener ( consoleModel , selectedJob , - , ) ; break ; case LOG_TAB : LogArchiver logArchiver = ( LogArchiver ) selectedContext . getValue ( LogContextInialiser . LOG_ARCHIVER ) ; logArchiver . addLogListener ( logModel , selectedJob , LogLevel . DEBUG , - , ) ; break ; case PROPERTIES_TAB : break ; default : throw new IllegalArgumentException ( "" + index + "" ) ; } } public void setSelectedContext ( ExplorerContext newContext ) { if ( selectedContext == newContext ) { return ; } if ( selectedContext != null ) { freeTab ( tabSelected ) ; } ExplorerContext oldContext = selectedContext ; selectedContext = newContext ; if ( selectedContext != null ) { try { engageTab ( tabSelected ) ; } catch ( JobDestroyedException e ) { selectedContext = null ; } } PropertyChangeEvent event = new PropertyChangeEvent ( this , SELECTED_CONTEXT_PROPERTY , oldContext , selectedContext ) ; propertySupport . firePropertyChange ( event ) ; } public Object getSelectedJob ( ) { if ( selectedContext == null ) { return null ; } return selectedContext . getThisComponent ( ) ; } public Observable getStateModel ( ) { return stateModel ; } public void addPropertyChangeListener ( PropertyChangeListener listener ) { propertySupport . addPropertyChangeListener ( listener ) ; } public void removePropertyChangeListener ( PropertyChangeListener listener ) { propertySupport . removePropertyChangeListener ( listener ) ; } } package org . oddjob . monitor . model ; import java . io . File ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . List ; public class FileHistory implements Serializable { private static final long serialVersionUID = ; private transient List < Runnable > changeActions ; private int listSize = ; private List < File > fileHistory = new ArrayList < File > ( ) ; public synchronized void addChangeAction ( Runnable action ) { if ( changeActions == null ) { changeActions = new ArrayList < Runnable > ( ) ; } changeActions . add ( action ) ; } public synchronized void removeChangeAction ( Runnable action ) { if ( changeActions == null ) { return ; } changeActions . remove ( action ) ; } public synchronized void addHistory ( File file ) { fileHistory . remove ( file ) ; fileHistory . add ( file ) ; while ( fileHistory . size ( ) > listSize ) { fileHistory . remove ( ) ; } List < Runnable > copyActions = new ArrayList < Runnable > ( changeActions ) ; for ( Runnable action : copyActions ) { action . run ( ) ; } } public int size ( ) { return fileHistory . size ( ) ; } public File get ( int i ) { return fileHistory . get ( i ) ; } public int getListSize ( ) { return listSize ; } public void setListSize ( int listSize ) { this . listSize = listSize ; } } package org . oddjob . monitor . model ; import java . util . LinkedList ; import java . util . List ; import java . util . concurrent . CopyOnWriteArrayList ; import java . util . concurrent . Executor ; import javax . swing . event . TreeModelEvent ; import javax . swing . event . TreeModelListener ; import javax . swing . tree . TreeNode ; public class ExecutorTreeEventDispatcher implements TreeEventDispatcher { private final List < TreeModelListener > listeners = new CopyOnWriteArrayList < TreeModelListener > ( ) ; private final Executor executor ; public ExecutorTreeEventDispatcher ( Executor executor ) { this . executor = executor ; } @ Override public synchronized void addTreeModelListener ( TreeModelListener tml ) { listeners . add ( tml ) ; } @ Override public synchronized void removeTreeModelListener ( TreeModelListener tml ) { listeners . remove ( tml ) ; } private Object [ ] pathToRoot ( TreeNode changed ) { LinkedList < TreeNode > list = new LinkedList < TreeNode > ( ) ; for ( TreeNode i = changed ; i != null ; i = i . getParent ( ) ) { list . addFirst ( i ) ; } return list . toArray ( new Object [ list . size ( ) ] ) ; } public synchronized void fireTreeNodesChanged ( TreeNode changed ) { final TreeModelEvent event = new TreeModelEvent ( changed , pathToRoot ( changed ) ) ; Runnable runnable = new Runnable ( ) { public void run ( ) { for ( final TreeModelListener tml : listeners ) { tml . treeNodesChanged ( event ) ; } } } ; executor . execute ( runnable ) ; } public synchronized void fireTreeNodesInserted ( TreeNode changed , JobTreeNode child , int index ) { int childIndecies [ ] = { index } ; Object children [ ] = { child } ; final TreeModelEvent event = new TreeModelEvent ( changed , pathToRoot ( changed ) , childIndecies , children ) ; Runnable runnable = new Runnable ( ) { public void run ( ) { for ( final TreeModelListener tml : listeners ) { tml . treeNodesInserted ( event ) ; } } } ; executor . execute ( runnable ) ; } public synchronized void fireTreeNodesRemoved ( TreeNode changed , JobTreeNode child , int index ) { int childIndecies [ ] = { index } ; Object children [ ] = { child } ; final TreeModelEvent event = new TreeModelEvent ( changed , pathToRoot ( changed ) , childIndecies , children ) ; Runnable runnable = new Runnable ( ) { public void run ( ) { for ( final TreeModelListener tml : listeners ) { tml . treeNodesRemoved ( event ) ; } } } ; executor . execute ( runnable ) ; } } package org . oddjob . monitor . model ; import java . util . concurrent . Executor ; import javax . swing . SwingUtilities ; public class EventThreadLaterExecutor implements Executor { @ Override public void execute ( final Runnable command ) { if ( SwingUtilities . isEventDispatchThread ( ) ) { command . run ( ) ; } else { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { command . run ( ) ; } } ) ; } } } package org . oddjob . monitor . model ; import javax . swing . event . TreeModelListener ; import javax . swing . tree . TreeNode ; public interface TreeEventDispatcher { public void addTreeModelListener ( TreeModelListener tml ) ; public void removeTreeModelListener ( TreeModelListener tml ) ; public void fireTreeNodesChanged ( TreeNode changed ) ; public void fireTreeNodesInserted ( TreeNode changed , JobTreeNode child , int index ) ; public void fireTreeNodesRemoved ( TreeNode changed , JobTreeNode child , int index ) ; } package org . oddjob . monitor . model ; import org . oddjob . monitor . context . ExplorerContext ; public interface ExplorerContextFactory { public ExplorerContext createFrom ( ExplorerModel explorerModel ) ; } package org . oddjob . monitor . model ; import org . oddjob . logging . LogLevel ; abstract public class LogAction { abstract public void accept ( LogEventProcessor processor ) ; } class MessageEvent extends LogAction { private final String text ; private final LogLevel level ; public MessageEvent ( String text , LogLevel level ) { this . text = text ; this . level = level ; } public void accept ( LogEventProcessor processor ) { processor . onEvent ( text , level ) ; } } class ClearEvent extends LogAction { public void accept ( LogEventProcessor processor ) { processor . onClear ( ) ; } } class UnavailableEvent extends LogAction { public void accept ( LogEventProcessor processor ) { processor . onUnavailable ( ) ; } } package org . oddjob . monitor . model ; import java . io . PrintWriter ; import java . io . StringWriter ; import java . util . Observable ; import org . oddjob . state . StateEvent ; public class StateModel extends Observable { private String state ; private String time ; private String exception ; public void change ( StateEvent event ) { state = event . getState ( ) . toString ( ) ; time = event . getTime ( ) . toString ( ) ; StringWriter stackBuffer = new StringWriter ( ) ; Throwable t = event . getException ( ) ; if ( t != null ) { PrintWriter writer = new PrintWriter ( stackBuffer ) ; t . printStackTrace ( writer ) ; exception = stackBuffer . toString ( ) ; } else { exception = "" ; } setChanged ( ) ; notifyObservers ( ) ; } public String getException ( ) { return exception ; } public String getState ( ) { return state ; } public String getTime ( ) { return time ; } public void clear ( ) { state = "" ; time = "" ; exception = "" ; setChanged ( ) ; notifyObservers ( ) ; } } package org . oddjob . monitor . model ; import java . util . Enumeration ; import java . util . HashMap ; import java . util . Map ; import java . util . Vector ; import java . util . concurrent . Executor ; import javax . swing . ImageIcon ; import javax . swing . tree . TreeNode ; import org . apache . log4j . Logger ; import org . oddjob . Iconic ; import org . oddjob . Structural ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class JobTreeNode implements TreeNode { private static final Logger logger = Logger . getLogger ( JobTreeNode . class ) ; private final Executor executor ; private final Vector < JobTreeNode > nodeList = new Vector < JobTreeNode > ( ) ; private final Vector < JobTreeNode > currentList = new Vector < JobTreeNode > ( ) ; final private JobTreeNode parent ; final private JobTreeModel model ; private final OurIconListener iconListener = new OurIconListener ( ) ; private volatile ImageIcon iconTip = IconHelper . nullIcon ; final private Object component ; final private ExplorerContext explorerContext ; private String nodeName ; private boolean visible ; private boolean listening ; private final StructuralListener structuralListner = new StructuralListener ( ) { public synchronized void childAdded ( final StructuralEvent e ) { final int index = e . getIndex ( ) ; Object childJob = e . getChild ( ) ; final JobTreeNode childNode = new JobTreeNode ( JobTreeNode . this , childJob ) ; logger . debug ( "" + childNode . getComponent ( ) + "" ) ; if ( visible ) { childNode . setVisible ( true ) ; } currentList . add ( index , childNode ) ; executor . execute ( new Runnable ( ) { public void run ( ) { logger . debug ( "" + childNode . getComponent ( ) + "" ) ; nodeList . add ( index , childNode ) ; model . fireTreeNodesInserted ( JobTreeNode . this , childNode , index ) ; } } ) ; } public synchronized void childRemoved ( final StructuralEvent e ) { final int index = e . getIndex ( ) ; final JobTreeNode child = currentList . remove ( index ) ; logger . debug ( "" + child . getComponent ( ) + "" ) ; child . destroy ( ) ; executor . execute ( new Runnable ( ) { public void run ( ) { logger . debug ( "" + child . getComponent ( ) + "" ) ; JobTreeNode child = nodeList . remove ( index ) ; model . fireTreeNodesRemoved ( JobTreeNode . this , child , index ) ; } } ) ; } } ; public JobTreeNode ( ExplorerModel explorerModel , JobTreeModel model ) { this ( explorerModel , model , new EventThreadLaterExecutor ( ) , ExplorerContextImpl . FACTORY ) ; } public JobTreeNode ( ExplorerModel explorerModel , JobTreeModel model , Executor executor , ExplorerContextFactory contextFactory ) { this . parent = null ; this . model = model ; this . component = explorerModel . getOddjob ( ) ; this . explorerContext = contextFactory . createFrom ( explorerModel ) ; this . executor = executor ; } public JobTreeNode ( JobTreeNode parent , Object node ) { if ( parent == null ) { throw new NullPointerException ( "" ) ; } this . parent = parent ; this . model = parent . model ; this . component = node ; this . explorerContext = parent . explorerContext . addChild ( node ) ; this . executor = parent . executor ; } public void setVisible ( boolean visible ) { if ( this . visible == visible ) { return ; } if ( visible ) { if ( ! listening && component instanceof Structural ) { ( ( Structural ) component ) . addStructuralListener ( structuralListner ) ; listening = true ; } iconListener . listen ( ) ; } else { iconListener . dont ( ) ; } this . visible = visible ; } public boolean isVisible ( ) { return visible ; } void setIcon ( ImageIcon icon ) { synchronized ( this ) { this . iconTip = icon ; } executor . execute ( new Runnable ( ) { @ Override public void run ( ) { model . fireTreeNodesChanged ( JobTreeNode . this ) ; } } ) ; } public Object getComponent ( ) { return component ; } public Enumeration < JobTreeNode > children ( ) { return nodeList . elements ( ) ; } public boolean getAllowsChildren ( ) { return true ; } public TreeNode getChildAt ( int index ) { return nodeList . get ( index ) ; } public int getChildCount ( ) { return nodeList . size ( ) ; } public boolean isLeaf ( ) { return nodeList . size ( ) == ? true : false ; } public int getIndex ( TreeNode child ) { return nodeList . indexOf ( child ) ; } public TreeNode getParent ( ) { return parent ; } public String toString ( ) { if ( nodeName == null ) { nodeName = component . toString ( ) ; } return nodeName ; } synchronized public ImageIcon getIcon ( ) { return iconTip ; } public JobTreeNode [ ] getChildren ( ) { synchronized ( nodeList ) { return ( JobTreeNode [ ] ) nodeList . toArray ( new JobTreeNode [ ] ) ; } } public void destroy ( ) { logger . debug ( "" + getComponent ( ) + "" ) ; if ( component instanceof Structural ) { ( ( Structural ) component ) . removeStructuralListener ( structuralListner ) ; } iconListener . dont ( ) ; for ( int i = currentList . size ( ) ; i > ; -- i ) { final int index = i - ; final JobTreeNode child = currentList . remove ( index ) ; child . destroy ( ) ; executor . execute ( new Runnable ( ) { public void run ( ) { logger . debug ( "" + child . getComponent ( ) + "" ) ; JobTreeNode child = nodeList . remove ( index ) ; model . fireTreeNodesRemoved ( JobTreeNode . this , child , index ) ; } } ) ; } } class OurIconListener implements IconListener { private boolean listening ; private final Map < String , ImageIcon > icons = new HashMap < String , ImageIcon > ( ) ; void listen ( ) { if ( listening ) { return ; } if ( component instanceof Iconic ) { ( ( Iconic ) component ) . addIconListener ( this ) ; } listening = true ; } public void iconEvent ( IconEvent event ) { String iconId = event . getIconId ( ) ; ImageIcon it = icons . get ( iconId ) ; if ( it == null ) { it = ( ( Iconic ) component ) . iconForId ( iconId ) ; if ( it == null ) { throw new NullPointerException ( "" + iconId ) ; } icons . put ( iconId , it ) ; } setIcon ( it ) ; } public void dont ( ) { if ( component instanceof Iconic ) { ( ( Iconic ) component ) . removeIconListener ( this ) ; } listening = false ; } } public ExplorerContext getExplorerContext ( ) { return explorerContext ; } } package org . oddjob . monitor . model ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . monitor . context . AncestorSearch ; import org . oddjob . monitor . context . ExplorerContext ; public class ConfigContextSearch { public ConfigurationSession sessionFor ( ExplorerContext context ) { ConfigurationOwner configOwner = null ; if ( context . getParent ( ) == null ) { configOwner = ( ConfigurationOwner ) context . getValue ( ConfigContextInialiser . CONFIG_OWNER ) ; } else { AncestorSearch search = new AncestorSearch ( context . getParent ( ) ) ; configOwner = ( ConfigurationOwner ) search . getValue ( ConfigContextInialiser . CONFIG_OWNER ) ; } if ( configOwner != null ) { return configOwner . provideConfigurationSession ( ) ; } return null ; } public DragPoint dragPointFor ( ExplorerContext context ) { ConfigurationSession session = sessionFor ( context ) ; if ( session != null ) { return session . dragPointFor ( context . getThisComponent ( ) ) ; } return null ; } } package org . oddjob . monitor . model ; import java . util . HashMap ; import java . util . Map ; import org . oddjob . monitor . context . CompositeContextInitialiser ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . util . ThreadManager ; public class ExplorerContextImpl implements ExplorerContext { public static final ExplorerContextFactory FACTORY = new ExplorerContextFactory ( ) { @ Override public ExplorerContext createFrom ( ExplorerModel explorerModel ) { return new ExplorerContextImpl ( explorerModel ) ; } } ; private final ContextInitialiser initialiser ; private final Object component ; private final Map < String , Object > values = new HashMap < String , Object > ( ) ; private final ExplorerContext parent ; private final ThreadManager threadManager ; public ExplorerContextImpl ( ExplorerModel explorerModel ) { this . component = explorerModel . getOddjob ( ) ; if ( component == null ) { throw new NullPointerException ( "" ) ; } this . parent = null ; this . threadManager = explorerModel . getThreadManager ( ) ; this . initialiser = new CompositeContextInitialiser ( explorerModel . getContextInitialisers ( ) ) ; this . initialiser . initialise ( this ) ; } private ExplorerContextImpl ( Object component , ExplorerContextImpl parent ) { if ( component == null ) { throw new NullPointerException ( "" ) ; } if ( parent == null ) { throw new NullPointerException ( "" ) ; } this . component = component ; this . parent = parent ; this . threadManager = parent . getThreadManager ( ) ; this . initialiser = parent . initialiser ; this . initialiser . initialise ( this ) ; } public ExplorerContext addChild ( Object child ) { return new ExplorerContextImpl ( child , this ) ; } public Object getThisComponent ( ) { return component ; } public ThreadManager getThreadManager ( ) { return threadManager ; } public ExplorerContext getParent ( ) { return parent ; } public Object getValue ( String key ) { return values . get ( key ) ; } public void setValue ( String key , Object value ) { values . put ( key , value ) ; } } package org . oddjob . monitor . model ; import java . util . Map ; import java . util . Observable ; public class PropertyModel extends Observable { private Map < String , String > properties ; public void setProperties ( Map < String , String > properties ) { this . properties = properties ; setChanged ( ) ; notifyObservers ( ) ; } public Map < String , String > getProperties ( ) { return properties ; } } package org . oddjob . monitor . view ; import java . awt . BorderLayout ; import java . awt . GridBagConstraints ; import java . awt . GridBagLayout ; import java . awt . Insets ; import java . util . Observable ; import java . util . Observer ; import javax . swing . JLabel ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JTextArea ; import javax . swing . JTextField ; import javax . swing . SwingUtilities ; import org . oddjob . monitor . model . StateModel ; public class StatePanel extends JPanel implements Observer { private static final long serialVersionUID = ; private final JTextField stateField = new JTextField ( ) ; private final JTextField timeField = new JTextField ( ) ; private final JTextArea exceptionField = new JTextArea ( ) ; public StatePanel ( ) { stateField . setEditable ( false ) ; timeField . setEditable ( false ) ; exceptionField . setEditable ( false ) ; exceptionField . setLineWrap ( false ) ; JPanel main = new JPanel ( ) ; JLabel l1 = new JLabel ( "" , JLabel . TRAILING ) ; JLabel l2 = new JLabel ( "" , JLabel . TRAILING ) ; JLabel l3 = new JLabel ( "" , JLabel . TRAILING ) ; JScrollPane scl = new JScrollPane ( ) ; scl . setViewportView ( exceptionField ) ; main . setLayout ( new GridBagLayout ( ) ) ; GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTH ; c . insets = new Insets ( , , , ) ; c . gridx = ; c . gridy = ; main . add ( l1 , c ) ; c . gridx = ; c . gridy = ; main . add ( l2 , c ) ; c . gridx = ; c . gridy = ; main . add ( l3 , c ) ; c . insets = new Insets ( , , , ) ; c . weightx = ; c . gridx = ; c . gridy = ; main . add ( stateField , c ) ; c . gridx = ; c . gridy = ; main . add ( timeField , c ) ; c . fill = GridBagConstraints . BOTH ; c . weighty = ; c . gridx = ; c . gridy = ; main . add ( scl , c ) ; JScrollPane formScroll = new JScrollPane ( ) ; formScroll . setViewportView ( main ) ; setLayout ( new BorderLayout ( ) ) ; add ( formScroll , BorderLayout . CENTER ) ; } public void update ( Observable o , Object arg ) { final StateModel model = ( StateModel ) o ; SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { stateField . setText ( model . getState ( ) ) ; timeField . setText ( model . getTime ( ) ) ; exceptionField . setText ( model . getException ( ) ) ; } } ) ; } } package org . oddjob . monitor . view ; import java . awt . event . KeyEvent ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import javax . swing . JMenu ; import javax . swing . JMenuBar ; import javax . swing . JPopupMenu ; import javax . swing . event . MenuEvent ; import javax . swing . event . MenuListener ; import javax . swing . event . PopupMenuEvent ; import javax . swing . event . PopupMenuListener ; import org . oddjob . arooa . design . actions . ConfigurableMenus ; import org . oddjob . arooa . design . designer . PopupMenuProvider ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . DetailModel ; import org . oddjob . monitor . model . SelectedContextAware ; public class MonitorMenuBar extends JMenuBar implements PopupMenuProvider { private static final long serialVersionUID = ; public static final String JOB_MENU_ID = "" ; private final JMenu fileMenu ; private JMenu [ ] lastFormMenus ; private JPopupMenu popupMenu ; private MenuSelection selectionListener ; private DetailModel detailModel ; public MonitorMenuBar ( ) { fileMenu = new JMenu ( "" ) ; fileMenu . setMnemonic ( KeyEvent . VK_F ) ; this . add ( fileMenu ) ; } public JMenu getFileMenu ( ) { return fileMenu ; } public JPopupMenu getPopupMenu ( ) { return popupMenu ; } public void setSession ( final ExplorerJobActions jobActions , DetailModel model ) { if ( detailModel != null ) { throw new IllegalStateException ( "" ) ; } detailModel = model ; ConfigurableMenus formMenus = new ConfigurableMenus ( ) ; final ExplorerEditActions editActions = new ExplorerEditActions ( ) ; editActions . contributeTo ( formMenus ) ; jobActions . contributeTo ( formMenus ) ; selectionListener = new MenuSelection ( new SelectedContextAware ( ) { public void setSelectedContext ( ExplorerContext context ) { editActions . setSelectedContext ( context ) ; jobActions . setSelectedContext ( context ) ; } @ Override public void prepare ( ) { editActions . prepare ( ) ; jobActions . prepare ( ) ; } } ) ; detailModel . addPropertyChangeListener ( selectionListener ) ; lastFormMenus = formMenus . getJMenuBar ( ) ; lastFormMenus [ ] . addMenuListener ( selectionListener ) ; lastFormMenus [ ] . addMenuListener ( selectionListener ) ; popupMenu = formMenus . getPopupMenu ( ) ; popupMenu . addPopupMenuListener ( selectionListener ) ; for ( JMenu menu : lastFormMenus ) { this . add ( menu ) ; } this . validate ( ) ; this . repaint ( ) ; } public void noSession ( ) { if ( detailModel != null ) { detailModel . removePropertyChangeListener ( selectionListener ) ; detailModel = null ; } selectionListener = null ; if ( lastFormMenus != null ) { for ( JMenu menu : lastFormMenus ) { this . remove ( menu ) ; } lastFormMenus = null ; this . validate ( ) ; this . repaint ( ) ; } } class MenuSelection implements PropertyChangeListener , PopupMenuListener , MenuListener { private SelectedContextAware selectionAware ; private ExplorerContext context ; MenuSelection ( SelectedContextAware jobActions ) { this . selectionAware = jobActions ; } public void propertyChange ( PropertyChangeEvent evt ) { if ( DetailModel . SELECTED_CONTEXT_PROPERTY . equals ( evt . getPropertyName ( ) ) ) { context = ( ExplorerContext ) evt . getNewValue ( ) ; selectionAware . setSelectedContext ( context ) ; } } public void menuSelected ( MenuEvent e ) { menuSelect ( ) ; } public void menuCanceled ( MenuEvent e ) { } public void menuDeselected ( MenuEvent e ) { } public void popupMenuCanceled ( PopupMenuEvent e ) { } public void popupMenuWillBecomeInvisible ( PopupMenuEvent e ) { } public void popupMenuWillBecomeVisible ( PopupMenuEvent e ) { menuSelect ( ) ; } void menuSelect ( ) { if ( context == null ) { return ; } selectionAware . prepare ( ) ; } } } package org . oddjob . monitor . view ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import javax . swing . event . TableModelEvent ; import javax . swing . table . AbstractTableModel ; public class PropertyTableModel extends AbstractTableModel { private static final long serialVersionUID = ; private List < String > keys = new ArrayList < String > ( ) ; private List < String > values = new ArrayList < String > ( ) ; private final String colNames [ ] = { "" , "" } ; public void update ( Map < String , String > props ) { keys = new ArrayList < String > ( props . keySet ( ) ) ; values = new ArrayList < String > ( props . values ( ) ) ; fireTableChanged ( new TableModelEvent ( this ) ) ; } public int getRowCount ( ) { return keys . size ( ) ; } public int getColumnCount ( ) { return ; } public String getColumnName ( int columnIndex ) { return colNames [ columnIndex ] ; } public Object getValueAt ( int rowIndex , int columnIndex ) { if ( columnIndex == ) { return keys . get ( rowIndex ) ; } else { return values . get ( rowIndex ) ; } } } package org . oddjob . monitor . view ; import java . awt . BorderLayout ; import java . awt . Component ; import java . util . Observable ; import java . util . Observer ; import javax . swing . JComponent ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JTable ; import javax . swing . table . TableCellRenderer ; import org . oddjob . monitor . model . PropertyModel ; public class PropertyPanel extends JPanel implements Observer { private static final long serialVersionUID = ; private int screenWidth = ( int ) java . awt . Toolkit . getDefaultToolkit ( ) . getScreenSize ( ) . getWidth ( ) / ; private PropertyTableModel tableModel ; public PropertyPanel ( PropertyModel propertyModel ) { propertyModel . addObserver ( this ) ; tableModel = new PropertyTableModel ( ) ; JTable propTable = new JTable ( tableModel ) ; propTable . setCellSelectionEnabled ( true ) ; TableCellRenderer defaultRenderer = propTable . getDefaultRenderer ( String . class ) ; propTable . setDefaultRenderer ( Object . class , new PropertyRenderer ( defaultRenderer ) ) ; JScrollPane formScroll = new JScrollPane ( ) ; formScroll . setViewportView ( propTable ) ; setLayout ( new BorderLayout ( ) ) ; add ( formScroll , BorderLayout . CENTER ) ; } class PropertyRenderer implements TableCellRenderer { private final TableCellRenderer defaultRenderer ; public PropertyRenderer ( TableCellRenderer defaultRenderer ) { this . defaultRenderer = defaultRenderer ; } @ Override public Component getTableCellRendererComponent ( JTable table , Object value , boolean isSelected , boolean hasFocus , int row , int column ) { JComponent component = ( JComponent ) defaultRenderer . getTableCellRendererComponent ( table , value , isSelected , hasFocus , row , column ) ; String text = ( String ) value ; if ( text != null && text . length ( ) > screenWidth ) { text = text . substring ( , screenWidth ) + "" ; } component . setToolTipText ( text ) ; return component ; } } public void update ( Observable o , Object arg ) { PropertyModel propertyModel = ( PropertyModel ) o ; tableModel . update ( propertyModel . getProperties ( ) ) ; } } package org . oddjob . monitor . view ; import java . awt . event . KeyEvent ; import javax . swing . ActionMap ; import javax . swing . InputMap ; import javax . swing . JComponent ; import javax . swing . KeyStroke ; import org . oddjob . arooa . design . actions . ActionContributor ; import org . oddjob . arooa . design . actions . ActionMenu ; import org . oddjob . arooa . design . actions . ActionRegistry ; import org . oddjob . monitor . actions . ExplorerAction ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . SelectedContextAware ; public class ExplorerJobActions implements ActionContributor , SelectedContextAware { private final JobSwingAction [ ] swingActions ; private final ExplorerAction [ ] actions ; public ExplorerJobActions ( ExplorerAction [ ] actions ) { this . actions = actions ; this . swingActions = new JobSwingAction [ actions . length ] ; for ( int i = ; i < actions . length ; ++ i ) { this . swingActions [ i ] = new JobSwingAction ( actions [ i ] ) ; } } public void setSelectedContext ( ExplorerContext context ) { for ( ExplorerAction action : actions ) { action . setSelectedContext ( context ) ; } } @ Override public void prepare ( ) { for ( ExplorerAction action : actions ) { action . prepare ( ) ; } } public void contributeTo ( ActionRegistry actionRegistry ) { actionRegistry . addMainMenu ( new ActionMenu ( MonitorMenuBar . JOB_MENU_ID , "" , KeyEvent . VK_J ) ) ; for ( int i = ; i < actions . length ; ++ i ) { actionRegistry . addMenuItem ( MonitorMenuBar . JOB_MENU_ID , actions [ i ] . getGroup ( ) , swingActions [ i ] ) ; actionRegistry . addContextMenuItem ( actions [ i ] . getGroup ( ) , swingActions [ i ] ) ; } } public void addKeyStrokes ( JComponent component ) { ActionMap actionMap = component . getActionMap ( ) ; InputMap inputMap = component . getInputMap ( JComponent . WHEN_IN_FOCUSED_WINDOW ) ; for ( int i = ; i < actions . length ; ++ i ) { actionMap . put ( actions [ i ] . getName ( ) , swingActions [ i ] ) ; KeyStroke keyStroke = actions [ i ] . getAcceleratorKey ( ) ; if ( keyStroke != null ) { inputMap . put ( keyStroke , actions [ i ] . getName ( ) ) ; } } } } package org . oddjob . monitor . view ; import java . awt . Component ; import javax . swing . ImageIcon ; import javax . swing . JTree ; import javax . swing . tree . DefaultTreeCellRenderer ; import org . oddjob . monitor . model . JobTreeNode ; public class JobTreeCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = ; public Component getTreeCellRendererComponent ( JTree tree , Object value , boolean sel , boolean expanded , boolean leaf , int row , boolean hasFocus ) { super . getTreeCellRendererComponent ( tree , value , sel , expanded , leaf , row , hasFocus ) ; JobTreeNode node = ( JobTreeNode ) value ; ImageIcon icon = node . getIcon ( ) ; if ( icon != null ) { setIcon ( icon ) ; setToolTipText ( icon . getDescription ( ) ) ; } return this ; } } package org . oddjob . monitor . view ; import java . util . Observable ; import java . util . Observer ; import javax . swing . JTabbedPane ; import org . oddjob . monitor . model . DetailModel ; public class DetailView extends JTabbedPane implements Observer { private static final long serialVersionUID = ; private final StatePanel statePanel ; private final LogTextPanel consolePanel ; private final LogTextPanel logPanel ; private PropertyPanel propertyPanel ; public DetailView ( DetailModel model ) { statePanel = new StatePanel ( ) ; model . getStateModel ( ) . addObserver ( statePanel ) ; this . consolePanel = new LogTextPanel ( model . getConsoleModel ( ) ) ; this . logPanel = new LogTextPanel ( model . getLogModel ( ) ) ; propertyPanel = new PropertyPanel ( model . getPropertyModel ( ) ) ; add ( "" , statePanel ) ; add ( "" , consolePanel ) ; add ( "" , logPanel ) ; add ( "" , propertyPanel ) ; } public void update ( Observable o , Object arg ) { } } package org . oddjob . monitor . view ; import org . oddjob . arooa . design . actions . EditActionsContributor ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextSearch ; import org . oddjob . monitor . model . SelectedContextAware ; public class ExplorerEditActions extends EditActionsContributor implements SelectedContextAware { private ExplorerContext context ; public void setSelectedContext ( ExplorerContext context ) { this . context = context ; if ( context == null ) { setCutEnabled ( false ) ; setCopyEnabled ( false ) ; setPasteEnabled ( false ) ; setDeleteEnabled ( false ) ; } } @ Override public void prepare ( ) { DragPoint dragPoint = null ; ConfigContextSearch search = new ConfigContextSearch ( ) ; dragPoint = search . dragPointFor ( context ) ; if ( dragPoint == null ) { setCutEnabled ( false ) ; setCopyEnabled ( false ) ; setPasteEnabled ( false ) ; setDeleteEnabled ( false ) ; } else { if ( ! dragPoint . supportsCut ( ) ) { setCutEnabled ( false ) ; setDeleteEnabled ( false ) ; } else { setCutEnabled ( true ) ; setDeleteEnabled ( true ) ; } setCopyEnabled ( true ) ; if ( dragPoint . supportsPaste ( ) ) { setPasteEnabled ( true ) ; } else { setPasteEnabled ( false ) ; } } } } package org . oddjob . monitor . view ; import java . awt . BorderLayout ; import java . awt . Color ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . util . Enumeration ; import java . util . Hashtable ; import java . util . Observable ; import java . util . Observer ; import java . util . StringTokenizer ; import javax . swing . JCheckBox ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JTextPane ; import javax . swing . text . BadLocationException ; import javax . swing . text . MutableAttributeSet ; import javax . swing . text . SimpleAttributeSet ; import javax . swing . text . StyleConstants ; import javax . swing . text . StyledDocument ; import org . oddjob . logging . LogLevel ; import org . oddjob . monitor . model . LogAction ; import org . oddjob . monitor . model . LogEventProcessor ; public class LogTextPanel extends JPanel implements Observer , LogEventProcessor { private static final long serialVersionUID = ; private static final int MAX_DOC_LENGTH = ; private JTextPane textPane ; private JCheckBox cbxTail ; private StyledDocument doc ; private Hashtable < LogLevel , MutableAttributeSet > fontAttributes ; public LogTextPanel ( Observable model ) { model . addObserver ( this ) ; constructComponents ( ) ; createDefaultFontAttributes ( ) ; } private void constructComponents ( ) { this . setLayout ( new BorderLayout ( ) ) ; cbxTail = new JCheckBox ( ) ; cbxTail . setSelected ( true ) ; cbxTail . setText ( "" ) ; cbxTail . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { if ( cbxTail . isSelected ( ) ) { textPane . setCaretPosition ( doc . getLength ( ) ) ; } } } ) ; JPanel bottomPanel = new JPanel ( ) ; bottomPanel . add ( cbxTail , null ) ; textPane = new JTextPane ( ) { private static final long serialVersionUID = ; @ Override public boolean getScrollableTracksViewportWidth ( ) { return false ; } } ; textPane . setEditable ( false ) ; textPane . setText ( "" ) ; doc = textPane . getStyledDocument ( ) ; JScrollPane scroll = new JScrollPane ( ) ; scroll . setViewportView ( textPane ) ; scroll . getViewport ( ) . setBackground ( Color . white ) ; this . add ( bottomPanel , BorderLayout . SOUTH ) ; this . add ( scroll , BorderLayout . CENTER ) ; } public void setTextBackground ( Color color ) { textPane . setBackground ( color ) ; } public void setTextBackground ( String v ) { textPane . setBackground ( parseColor ( v ) ) ; } private void createDefaultFontAttributes ( ) { LogLevel [ ] prio = new LogLevel [ ] { LogLevel . FATAL , LogLevel . ERROR , LogLevel . WARN , LogLevel . INFO , LogLevel . DEBUG } ; fontAttributes = new Hashtable < LogLevel , MutableAttributeSet > ( ) ; for ( int i = ; i < prio . length ; i ++ ) { MutableAttributeSet att = new SimpleAttributeSet ( ) ; fontAttributes . put ( prio [ i ] , att ) ; } setTextColor ( LogLevel . FATAL , Color . red ) ; setTextColor ( LogLevel . ERROR , Color . magenta . darker ( ) ) ; setTextColor ( LogLevel . WARN , Color . orange . darker ( ) ) ; setTextColor ( LogLevel . INFO , Color . blue ) ; setTextColor ( LogLevel . DEBUG , Color . black ) ; setTextFontName ( "" ) ; } private Color parseColor ( String v ) { StringTokenizer st = new StringTokenizer ( v , "" ) ; int val [ ] = { , , , } ; int i = ; while ( st . hasMoreTokens ( ) ) { val [ i ] = Integer . parseInt ( st . nextToken ( ) ) ; i ++ ; } return new Color ( val [ ] , val [ ] , val [ ] , val [ ] ) ; } void setTextColor ( LogLevel l , String v ) { StyleConstants . setForeground ( ( MutableAttributeSet ) fontAttributes . get ( l ) , parseColor ( v ) ) ; } void setTextColor ( LogLevel l , Color c ) { StyleConstants . setForeground ( ( MutableAttributeSet ) fontAttributes . get ( l ) , c ) ; } void setTextFontSize ( int size ) { Enumeration < ? > e = fontAttributes . elements ( ) ; while ( e . hasMoreElements ( ) ) { StyleConstants . setFontSize ( ( MutableAttributeSet ) e . nextElement ( ) , size ) ; } return ; } void setTextFontName ( String name ) { Enumeration < ? > e = fontAttributes . elements ( ) ; while ( e . hasMoreElements ( ) ) { StyleConstants . setFontFamily ( ( MutableAttributeSet ) e . nextElement ( ) , name ) ; } return ; } public void onClear ( ) { try { doc . remove ( , doc . getLength ( ) ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } } public void onUnavailable ( ) { textPane . setText ( ( "" ) ) ; } public void onEvent ( final String text , final LogLevel level ) { try { doc . insertString ( doc . getLength ( ) , text , ( MutableAttributeSet ) fontAttributes . get ( level ) ) ; int overflow = doc . getLength ( ) - MAX_DOC_LENGTH ; if ( overflow > ) { doc . remove ( , overflow ) ; if ( ! cbxTail . isSelected ( ) ) { int position = textPane . getCaretPosition ( ) ; if ( position - overflow < ) { position = ; } textPane . setCaretPosition ( position ) ; } } if ( cbxTail . isSelected ( ) ) { textPane . setCaretPosition ( doc . getLength ( ) ) ; } } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } } public void update ( Observable o , Object arg ) { LogAction a = ( LogAction ) arg ; a . accept ( this ) ; } } package org . oddjob . monitor . view ; import java . awt . BorderLayout ; import javax . swing . DropMode ; import javax . swing . JOptionPane ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JSplitPane ; import javax . swing . JTree ; import javax . swing . ToolTipManager ; import javax . swing . event . AncestorEvent ; import javax . swing . event . AncestorListener ; import javax . swing . tree . TreePath ; import javax . swing . tree . TreeSelectionModel ; import org . oddjob . arooa . design . designer . ArooaTransferHandler ; import org . oddjob . arooa . design . designer . ArooaTree ; import org . oddjob . arooa . design . designer . TransferEvent ; import org . oddjob . arooa . design . designer . TransferEventListener ; import org . oddjob . arooa . design . view . TreeChangeFollower ; import org . oddjob . arooa . design . view . TreePopup ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . monitor . control . DetailController ; import org . oddjob . monitor . control . NodeControl ; import org . oddjob . monitor . control . PropertyPolling ; import org . oddjob . monitor . model . ConfigContextSearch ; import org . oddjob . monitor . model . DetailModel ; import org . oddjob . monitor . model . ExplorerModel ; import org . oddjob . monitor . model . JobTreeModel ; import org . oddjob . monitor . model . JobTreeNode ; public class ExplorerComponent extends JPanel { private static final long serialVersionUID = ; private final JTree tree ; private final JScrollPane treeScroll ; private MonitorMenuBar menuBar ; private final DetailModel detailModel ; private final ExplorerModel explorerModel ; private final PropertyPolling propertyPolling ; private final JSplitPane split ; private final TreeChangeFollower treeChangeFollower ; public ExplorerComponent ( ExplorerModel explorerModel , PropertyPolling propertyPolling ) { this . propertyPolling = propertyPolling ; this . explorerModel = explorerModel ; detailModel = new DetailModel ( ) ; DetailView detailView = new DetailView ( detailModel ) ; propertyPolling . setPropertyModel ( detailModel . getPropertyModel ( ) ) ; detailModel . addPropertyChangeListener ( propertyPolling ) ; DetailController detailControl = new DetailController ( detailModel , detailView ) ; JobTreeModel treeModel = new JobTreeModel ( ) ; JobTreeNode rootTreeNode = new JobTreeNode ( explorerModel , treeModel ) ; treeModel . setRootTreeNode ( rootTreeNode ) ; tree = new ArooaTree ( treeModel ) { private static final long serialVersionUID = ; @ Override public DragPoint getDragPoint ( Object treeNode ) { JobTreeNode jobTreeNode = ( JobTreeNode ) treeNode ; ConfigContextSearch search = new ConfigContextSearch ( ) ; return search . dragPointFor ( jobTreeNode . getExplorerContext ( ) ) ; } } ; NodeControl nodeControl = new NodeControl ( ) ; tree . addTreeWillExpandListener ( nodeControl ) ; tree . setShowsRootHandles ( true ) ; tree . getSelectionModel ( ) . setSelectionMode ( TreeSelectionModel . SINGLE_TREE_SELECTION ) ; tree . addTreeSelectionListener ( detailControl ) ; tree . setCellRenderer ( new JobTreeCellRenderer ( ) ) ; ToolTipManager . sharedInstance ( ) . registerComponent ( tree ) ; tree . setDragEnabled ( true ) ; tree . setDropMode ( DropMode . ON_OR_INSERT ) ; treeChangeFollower = new TreeChangeFollower ( tree ) ; tree . addAncestorListener ( new AncestorListener ( ) { @ Override public void ancestorRemoved ( AncestorEvent event ) { tree . removeAncestorListener ( this ) ; } @ Override public void ancestorMoved ( AncestorEvent event ) { } @ Override public void ancestorAdded ( AncestorEvent event ) { tree . setSelectionPath ( new TreePath ( tree . getModel ( ) . getRoot ( ) ) ) ; tree . requestFocusInWindow ( ) ; } } ) ; ArooaTransferHandler transferHandler = new ArooaTransferHandler ( ) ; transferHandler . addTransferEventListener ( new TransferEventListener ( ) { public void transferException ( TransferEvent event , String message , Exception exception ) { String text = message + "" + "" + exception . getMessage ( ) ; JOptionPane . showMessageDialog ( tree , text , "" , JOptionPane . ERROR_MESSAGE ) ; } } ) ; tree . setTransferHandler ( transferHandler ) ; rootTreeNode . setVisible ( true ) ; setLayout ( new BorderLayout ( ) ) ; treeScroll = new JScrollPane ( ) ; treeScroll . setViewportView ( tree ) ; split = new JSplitPane ( JSplitPane . HORIZONTAL_SPLIT , treeScroll , detailView ) ; add ( split ) ; } public void bindTo ( MonitorMenuBar monitorMenuBar ) { if ( this . menuBar != null ) { throw new IllegalStateException ( "" ) ; } this . menuBar = monitorMenuBar ; ExplorerJobActions jobActions = new ExplorerJobActions ( explorerModel . getExplorerActions ( ) ) ; menuBar . setSession ( jobActions , detailModel ) ; jobActions . addKeyStrokes ( this ) ; new TreePopup ( tree , menuBar ) ; } public void destroy ( ) { detailModel . removePropertyChangeListener ( propertyPolling ) ; treeChangeFollower . close ( ) ; } public void balance ( ) { split . setDividerLocation ( ( int ) ( * split . getPreferredSize ( ) . getWidth ( ) ) ) ; } public JTree getTree ( ) { return tree ; } } package org . oddjob . monitor . view ; import java . awt . Component ; import java . awt . event . ActionEvent ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import java . util . concurrent . Callable ; import javax . swing . Action ; import org . oddjob . arooa . design . actions . AbstractArooaAction ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . view . DialogueHelper ; import org . oddjob . arooa . design . view . SwingFormFactory ; import org . oddjob . arooa . design . view . ValueDialog ; import org . oddjob . monitor . actions . ExplorerAction ; import org . oddjob . monitor . actions . FormAction ; public class JobSwingAction extends AbstractArooaAction { private static final long serialVersionUID = ; private final ExplorerAction jobAction ; public JobSwingAction ( ExplorerAction jobAction ) { super ( jobAction . getName ( ) ) ; putValue ( Action . MNEMONIC_KEY , jobAction . getMnemonicKey ( ) ) ; putValue ( Action . ACCELERATOR_KEY , jobAction . getAcceleratorKey ( ) ) ; setEnabled ( jobAction . isEnabled ( ) ) ; setVisible ( jobAction . isVisible ( ) ) ; jobAction . addPropertyChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent evt ) { String propertyName = evt . getPropertyName ( ) ; if ( ExplorerAction . ENABLED_PROPERTY . equals ( propertyName ) ) { JobSwingAction . this . setEnabled ( ( Boolean ) evt . getNewValue ( ) ) ; } else if ( ExplorerAction . VISIBLE_PROPERTY . equals ( propertyName ) ) { JobSwingAction . this . setVisible ( ( Boolean ) evt . getNewValue ( ) ) ; } } } ) ; this . jobAction = jobAction ; } public void actionPerformed ( ActionEvent e ) { Component parent = ( Component ) e . getSource ( ) ; if ( jobAction instanceof FormAction ) { Form designDefinition = ( ( FormAction ) jobAction ) . form ( ) ; if ( designDefinition != null ) { Component form = SwingFormFactory . create ( designDefinition ) . dialog ( ) ; ValueDialog dialog = new ValueDialog ( form , new Callable < Boolean > ( ) { @ Override public Boolean call ( ) throws Exception { jobAction . action ( ) ; return true ; } } ) ; dialog . showDialog ( parent ) ; } } else { try { jobAction . action ( ) ; } catch ( Exception ex ) { DialogueHelper . showExceptionMessage ( parent , ex ) ; } } } } package org . oddjob . monitor . actions ; public class ActionProviderBean implements ActionProvider { private ExplorerAction [ ] actions ; public void setExplorerActions ( ExplorerAction [ ] actions ) { this . actions = actions ; } public ExplorerAction [ ] getExplorerActions ( ) { return actions ; } } package org . oddjob . monitor . actions ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; public class AccumulatingActionProvider implements ActionProvider { private List < ActionProvider > providers = new ArrayList < ActionProvider > ( ) ; public void addProvider ( ActionProvider provider ) { providers . add ( provider ) ; } public ExplorerAction [ ] getExplorerActions ( ) { List < ExplorerAction > results = new ArrayList < ExplorerAction > ( ) ; for ( ActionProvider provider : providers ) { results . addAll ( Arrays . asList ( provider . getExplorerActions ( ) ) ) ; } return results . toArray ( new ExplorerAction [ results . size ( ) ] ) ; } } package org . oddjob . monitor . actions ; import org . oddjob . arooa . design . screem . Form ; public interface FormAction extends ExplorerAction { public Form form ( ) ; } package org . oddjob . monitor . actions ; import java . net . URL ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . xml . XMLConfiguration ; public class URLActionProvider implements ActionProvider { private final URL [ ] urls ; private final ArooaSession session ; public URLActionProvider ( URL [ ] urls , ArooaSession session ) { this . urls = urls ; this . session = session ; } public ExplorerAction [ ] getExplorerActions ( ) { if ( urls . length == ) { return null ; } AccumulatingActionProvider accumulator = new AccumulatingActionProvider ( ) ; try { for ( URL url : urls ) { XMLConfiguration config = new XMLConfiguration ( url . toString ( ) , url . openStream ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . parse ( config ) ; ActionProvider provider = ( ActionProvider ) parser . getRoot ( ) ; accumulator . addProvider ( provider ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return accumulator . getExplorerActions ( ) ; } } package org . oddjob . monitor . actions ; public interface ActionProvider { public ExplorerAction [ ] getExplorerActions ( ) ; } package org . oddjob . monitor . actions ; import javax . swing . KeyStroke ; import org . oddjob . framework . PropertyChangeNotifier ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . SelectedContextAware ; public interface ExplorerAction extends PropertyChangeNotifier , SelectedContextAware { public static final String ENABLED_PROPERTY = "" ; public static final String VISIBLE_PROPERTY = "" ; public static final String JOB_GROUP = "" ; public static final String PROPERTY_GROUP = "" ; public static final String DESIGN_GROUP = "" ; public String getName ( ) ; public String getGroup ( ) ; public Integer getMnemonicKey ( ) ; public KeyStroke getAcceleratorKey ( ) ; public void setSelectedContext ( ExplorerContext eContext ) ; public void action ( ) throws Exception ; public void prepare ( ) ; public boolean isEnabled ( ) ; public boolean isVisible ( ) ; } package org . oddjob . monitor . actions ; import java . net . URL ; import org . oddjob . arooa . ArooaSession ; public class ResourceActionProvider implements ActionProvider { public static final String ACTION_FILE = "" ; private final ArooaSession session ; public ResourceActionProvider ( ArooaSession session ) { this . session = session ; } public ExplorerAction [ ] getExplorerActions ( ) { URL [ ] urls = session . getArooaDescriptor ( ) . getClassResolver ( ) . getResources ( ACTION_FILE ) ; return new URLActionProvider ( urls , session ) . getExplorerActions ( ) ; } } package org . oddjob . monitor . action ; import java . awt . Component ; import java . awt . GridBagConstraints ; import java . awt . GridBagLayout ; import java . awt . Insets ; import java . util . SortedSet ; import java . util . TreeSet ; import javax . swing . JPanel ; import javax . swing . KeyStroke ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . FormItem ; import org . oddjob . arooa . design . screem . LabelledComboBox ; import org . oddjob . arooa . design . view . Looks ; import org . oddjob . arooa . design . view . SwingFormFactory ; import org . oddjob . arooa . design . view . SwingFormView ; import org . oddjob . arooa . design . view . SwingItemFactory ; import org . oddjob . arooa . design . view . SwingItemView ; import org . oddjob . arooa . design . view . ViewHelper ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . parsing . QTag ; import org . oddjob . arooa . parsing . QTagConfiguration ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . actions . FormAction ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextSearch ; import org . oddjob . monitor . model . JobFormAction ; public class AddJobAction extends JobFormAction implements FormAction { static { SwingFormFactory . register ( AddJobForm . class , new SwingFormFactory < AddJobForm > ( ) { public SwingFormView onCreate ( AddJobForm form ) { return new AddJobFormView ( form ) ; } } ) ; } private LabelledComboBox < QTag > comboBox ; private Form form ; private ConfigurationSession configurationSession ; private DragPoint dragPoint ; private Object component ; public String getName ( ) { return "" ; } public String getGroup ( ) { return DESIGN_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . ADD_JOB_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . ADD_JOB_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { component = explorerContext . getThisComponent ( ) ; ConfigContextSearch search = new ConfigContextSearch ( ) ; configurationSession = search . sessionFor ( explorerContext ) ; dragPoint = null ; if ( configurationSession != null ) { dragPoint = configurationSession . dragPointFor ( component ) ; } if ( dragPoint == null || ! dragPoint . supportsPaste ( ) ) { setEnabled ( false ) ; setVisible ( false ) ; return ; } ArooaDescriptor descriptor = configurationSession . getArooaDescriptor ( ) ; InstantiationContext context = new InstantiationContext ( ArooaType . COMPONENT , new SimpleArooaClass ( Object . class ) ) ; ArooaElement [ ] elements = descriptor . getElementMappings ( ) . elementsFor ( context ) ; SortedSet < QTag > sortedTags = new TreeSet < QTag > ( ) ; for ( ArooaElement element : elements ) { String prefix = descriptor . getPrefixFor ( element . getUri ( ) ) ; sortedTags . add ( new QTag ( prefix , element ) ) ; } QTag [ ] allOptions = new QTag [ elements . length + ] ; allOptions [ ] = QTag . NULL_TAG ; System . arraycopy ( sortedTags . toArray ( ) , , allOptions , , sortedTags . size ( ) ) ; comboBox = new LabelledComboBox < QTag > ( allOptions , "" ) ; form = new AddJobForm ( comboBox ) ; setVisible ( true ) ; setEnabled ( true ) ; } @ Override protected void doFree ( ExplorerContext explorerContext ) { } @ Override protected Form doForm ( ) { return form ; } @ Override protected void doAction ( ) throws Exception { QTag selected = comboBox . getSelected ( ) ; if ( selected == null || selected == QTag . NULL_TAG ) { return ; } QTagConfiguration config = new QTagConfiguration ( selected ) ; XMLArooaParser parser = new XMLArooaParser ( ) ; parser . parse ( config ) ; DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; try { dragPoint . paste ( - , parser . getXml ( ) ) ; trn . commit ( ) ; } catch ( Exception e ) { trn . rollback ( ) ; throw e ; } } class AddJobForm implements Form { FormItem formItem ; public AddJobForm ( FormItem item ) { this . formItem = item ; } @ Override public String getTitle ( ) { return "" ; } public FormItem getFormItem ( ) { return formItem ; } } static class AddJobFormView implements SwingFormView { private final AddJobForm standardForm ; public AddJobFormView ( AddJobForm form ) { this . standardForm = form ; } public Component cell ( ) { return ViewHelper . createDetailButton ( standardForm ) ; } public Component dialog ( ) { JPanel form = new JPanel ( ) ; form . setLayout ( new GridBagLayout ( ) ) ; GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTHWEST ; c . insets = new Insets ( Looks . DETAIL_FORM_BORDER , Looks . DETAIL_FORM_BORDER , Looks . DETAIL_FORM_BORDER , Looks . DETAIL_FORM_BORDER ) ; c . gridx = ; c . gridy = ; int items = ; for ( int i = ; i < items ; ++ i ) { c . gridx = ; c . gridy = i + ; JPanel panel = new JPanel ( ) ; panel . setLayout ( new GridBagLayout ( ) ) ; SwingItemView itemView = SwingItemFactory . create ( standardForm . getFormItem ( ) ) ; itemView . inline ( panel , , , false ) ; form . add ( panel , c ) ; } c . weighty = ; form . add ( new JPanel ( ) , c ) ; return form ; } } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . oddjob . Stateful ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . util . ThreadManager ; public class ExecuteAction extends JobAction implements StateListener { private Object job = null ; private ThreadManager threadManager ; public String getName ( ) { return "" ; } public String getGroup ( ) { return JOB_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . RUN_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . RUN_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { if ( isPrepared ( ) ) { return ; } Object component = explorerContext . getThisComponent ( ) ; if ( ! ( component instanceof Runnable ) ) { this . job = null ; setEnabled ( false ) ; } else { this . job = component ; this . threadManager = explorerContext . getThreadManager ( ) ; if ( job instanceof Stateful ) { ( ( Stateful ) job ) . addStateListener ( this ) ; } else { setEnabled ( true ) ; } } } @ Override protected void doFree ( ExplorerContext explorerContext ) { if ( job != null && job instanceof Stateful ) { ( ( Stateful ) job ) . removeStateListener ( this ) ; } job = null ; } @ Override protected void doAction ( ) throws Exception { threadManager . run ( ( ( Runnable ) job ) , "" + job ) ; } public void jobStateChange ( StateEvent event ) { if ( event . getState ( ) . isReady ( ) ) { setEnabled ( true ) ; } else { setEnabled ( false ) ; } } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . oddjob . Resetable ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . util . ThreadManager ; public class SoftResetAction extends JobAction { private Object job = null ; private ThreadManager threadManager ; public String getName ( ) { return "" ; } public String getGroup ( ) { return JOB_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . SOFT_RESET_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . SOFT_RESET_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { Object component = explorerContext . getThisComponent ( ) ; if ( ! ( component instanceof Resetable ) ) { this . job = null ; setEnabled ( false ) ; } else { this . job = component ; setEnabled ( true ) ; this . threadManager = explorerContext . getThreadManager ( ) ; } } @ Override protected void doFree ( ExplorerContext explorerContext ) { job = null ; } @ Override protected void doAction ( ) throws Exception { threadManager . run ( new Runnable ( ) { public void run ( ) { ( ( Resetable ) job ) . softReset ( ) ; } } , "" + job ) ; } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . designer . ArooaDesignerForm ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . actions . FormAction ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . JobFormAction ; public class DesignInsideAction extends JobFormAction implements FormAction { private ArooaConfiguration config ; private DesignParser parser ; private ConfigurationHandle configHandle ; public String getName ( ) { return "" ; } public String getGroup ( ) { return DESIGN_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . DESIGN_INSIDE_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . DESIGNER_INSIDE_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext context ) { ConfigurationOwner configOwner = null ; if ( context . getThisComponent ( ) instanceof ConfigurationOwner ) { configOwner = ( ConfigurationOwner ) context . getThisComponent ( ) ; } if ( configOwner == null || configOwner . rootDesignFactory ( ) == null ) { setEnabled ( false ) ; setVisible ( false ) ; } else { setVisible ( true ) ; ConfigurationSession configSession = configOwner . provideConfigurationSession ( ) ; if ( configSession == null ) { setEnabled ( false ) ; } else { config = configSession . dragPointFor ( context . getThisComponent ( ) ) ; if ( config == null ) { setEnabled ( false ) ; } else { ArooaDescriptor descriptor = configOwner . provideConfigurationSession ( ) . getArooaDescriptor ( ) ; ArooaSession session = new StandardArooaSession ( descriptor ) ; parser = new DesignParser ( session , configOwner . rootDesignFactory ( ) ) ; parser . setExpectedDoucmentElement ( configOwner . rootElement ( ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; setEnabled ( true ) ; } } } } @ Override protected void doFree ( ExplorerContext explorerContext ) { } @ Override protected void doAction ( ) throws Exception { configHandle . save ( ) ; } @ Override protected Form doForm ( ) { try { configHandle = parser . parse ( config ) ; } catch ( ArooaParseException e ) { throw new RuntimeException ( e ) ; } return new ArooaDesignerForm ( parser ) ; } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . oddjob . Loadable ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . util . ThreadManager ; public class UnloadAction extends JobAction { private Loadable job = null ; private ThreadManager threadManager ; public String getName ( ) { return "" ; } public String getGroup ( ) { return JOB_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . UNLOAD_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . UNLOAD_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { Object component = explorerContext . getThisComponent ( ) ; if ( component instanceof Loadable ) { this . job = ( Loadable ) component ; this . threadManager = explorerContext . getThreadManager ( ) ; setEnabled ( ! this . job . isLoadable ( ) ) ; setVisible ( true ) ; } else { setEnabled ( false ) ; setVisible ( false ) ; } } @ Override protected void doFree ( ExplorerContext explorerContext ) { job = null ; threadManager = null ; } @ Override protected void doAction ( ) throws Exception { Runnable runnable = new Runnable ( ) { public void run ( ) { job . unload ( ) ; } } ; threadManager . run ( runnable , "" + job ) ; } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Stoppable ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . util . ThreadManager ; public class StopAction extends JobAction { private static final Logger logger = Logger . getLogger ( StopAction . class ) ; private Object job = null ; private ThreadManager threadManager ; public String getName ( ) { return "" ; } public String getGroup ( ) { return JOB_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . STOP_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . STOP_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { if ( isPrepared ( ) ) { return ; } Object component = explorerContext . getThisComponent ( ) ; if ( component instanceof Stoppable ) { this . job = component ; setEnabled ( true ) ; this . threadManager = explorerContext . getThreadManager ( ) ; } else { setEnabled ( false ) ; } } @ Override protected void doFree ( ExplorerContext explorerContext ) { job = null ; } @ Override protected void doAction ( ) throws Exception { threadManager . run ( new Runnable ( ) { public void run ( ) { try { ( ( Stoppable ) job ) . stop ( ) ; } catch ( FailedToStopException e ) { logger . warn ( e ) ; } } } , "" + job ) ; } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . designer . ArooaDesignerForm ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . actions . FormAction ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextSearch ; import org . oddjob . monitor . model . JobFormAction ; public class DesignerAction extends JobFormAction implements FormAction { private ArooaConfiguration config ; private ArooaDescriptor descriptor ; private ConfigurationHandle configHandle ; public String getName ( ) { return "" ; } public String getGroup ( ) { return DESIGN_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . DESIGNER_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . DESIGNER_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { if ( explorerContext . getParent ( ) == null ) { setVisible ( false ) ; setEnabled ( false ) ; } else { setVisible ( true ) ; ConfigContextSearch search = new ConfigContextSearch ( ) ; ConfigurationSession configSession = search . sessionFor ( explorerContext ) ; if ( configSession == null ) { setEnabled ( false ) ; } else { config = configSession . dragPointFor ( explorerContext . getThisComponent ( ) ) ; if ( config == null ) { setEnabled ( false ) ; } else { descriptor = configSession . getArooaDescriptor ( ) ; setEnabled ( true ) ; } } } } @ Override protected void doFree ( ExplorerContext explorerContext ) { } @ Override protected void doAction ( ) throws Exception { configHandle . save ( ) ; } @ Override protected Form doForm ( ) { ArooaSession session = new StandardArooaSession ( descriptor ) ; DesignParser parser = new DesignParser ( session ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; try { configHandle = parser . parse ( config ) ; } catch ( ArooaParseException e ) { throw new RuntimeException ( e ) ; } return new ArooaDesignerForm ( parser ) ; } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . oddjob . Loadable ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . util . ThreadManager ; public class LoadAction extends JobAction { private Loadable job = null ; private ThreadManager threadManager ; public String getName ( ) { return "" ; } public String getGroup ( ) { return JOB_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . LOAD_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . LOAD_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { Object component = explorerContext . getThisComponent ( ) ; if ( component instanceof Loadable ) { this . job = ( Loadable ) component ; this . threadManager = explorerContext . getThreadManager ( ) ; setEnabled ( this . job . isLoadable ( ) ) ; setVisible ( true ) ; } else { setEnabled ( false ) ; setVisible ( false ) ; } } @ Override protected void doFree ( ExplorerContext explorerContext ) { job = null ; threadManager = null ; } @ Override protected void doAction ( ) throws Exception { Runnable runnable = new Runnable ( ) { public void run ( ) { job . load ( ) ; } } ; threadManager . run ( runnable , "" + job ) ; } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . apache . commons . beanutils . DynaBean ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignSeedContext ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TextField ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . runtime . ConfigurationNode ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . actions . FormAction ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextSearch ; import org . oddjob . monitor . model . JobFormAction ; public class SetPropertyAction extends JobFormAction implements FormAction { private static final Logger logger = Logger . getLogger ( SetPropertyAction . class ) ; private Object job = null ; private PropertyForm propertyForm ; private ConfigurationSession sessionLite ; public String getName ( ) { return "" ; } public String getGroup ( ) { return PROPERTY_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . PROPERTY_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . PROPERTY_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { if ( explorerContext . getParent ( ) != null ) { setVisible ( true ) ; Object component = explorerContext . getThisComponent ( ) ; if ( component instanceof RemoteOddjobBean && ! ( component instanceof DynaBean ) ) { setEnabled ( false ) ; } else { ConfigContextSearch search = new ConfigContextSearch ( ) ; sessionLite = search . sessionFor ( explorerContext ) ; if ( sessionLite == null ) { setEnabled ( false ) ; } else { job = component ; DesignSeedContext context = new DesignSeedContext ( ArooaType . VALUE , new StandardArooaSession ( sessionLite . getArooaDescriptor ( ) ) ) ; propertyForm = new PropertyForm ( new ArooaElement ( "" ) , context ) ; setEnabled ( true ) ; } } } else { setVisible ( false ) ; setEnabled ( false ) ; } } @ Override protected void doFree ( ExplorerContext explorerContext ) { } @ Override public Form doForm ( ) { return propertyForm . detail ( ) ; } @ Override protected void doAction ( ) throws Exception { ConfigurationNode valueConfiguration = propertyForm . getArooaContext ( ) . getConfigurationNode ( ) ; if ( logger . isDebugEnabled ( ) ) { XMLArooaParser xml = new XMLArooaParser ( ) ; xml . parse ( valueConfiguration ) ; logger . debug ( "" + xml . getXml ( ) ) ; } PropertyCapture propertyCapture = new PropertyCapture ( ) ; ArooaSession session = new StandardArooaSession ( sessionLite . getArooaDescriptor ( ) ) ; StandardArooaParser parser = new StandardArooaParser ( propertyCapture , session ) ; try { parser . parse ( valueConfiguration ) ; } catch ( ArooaParseException ex ) { throw new RuntimeException ( ex ) ; } session . getComponentPool ( ) . configure ( propertyCapture ) ; String name = propertyCapture . getName ( ) ; if ( name == null || "" . equals ( name . trim ( ) ) ) { logger . debug ( "" ) ; return ; } PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) . accessorWithConversions ( session . getTools ( ) . getArooaConverter ( ) ) ; accessor . setSimpleProperty ( job , name , propertyCapture . getValue ( ) ) ; } class PropertyForm extends DesignValueBase { SimpleTextAttribute name ; SimpleDesignProperty value ; public PropertyForm ( ArooaElement element , ArooaContext parentContext ) { super ( element , new SimpleArooaClass ( PropertyCapture . class ) , parentContext ) ; name = new SimpleTextAttribute ( "" , this ) ; value = new SimpleDesignProperty ( "" , Object . class , ArooaType . VALUE , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , value } ; } public Form detail ( ) { return new StandardForm ( "" , this ) . addFormItem ( new BorderedGroup ( "" ) . add ( new TextField ( "" , name ) ) . add ( value . view ( ) . setTitle ( "" ) ) ) ; } } public class PropertyCapture { private String name ; private Object value ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public Object getValue ( ) { return value ; } public void setValue ( Object value ) { this . value = value ; } } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . oddjob . Resetable ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . util . ThreadManager ; public class HardResetAction extends JobAction { private Object job = null ; private ThreadManager threadManager ; public String getName ( ) { return "" ; } public String getGroup ( ) { return JOB_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . HARD_RESET_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return Standards . HARD_RESET_ACCELERATOR_KEY ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { Object component = explorerContext . getThisComponent ( ) ; if ( ! ( component instanceof Resetable ) ) { this . job = null ; setEnabled ( false ) ; } else { this . job = component ; setEnabled ( true ) ; this . threadManager = explorerContext . getThreadManager ( ) ; } } @ Override protected void doFree ( ExplorerContext explorerContext ) { job = null ; } @ Override protected void doAction ( ) throws Exception { threadManager . run ( new Runnable ( ) { public void run ( ) { ( ( Resetable ) job ) . hardReset ( ) ; } } , "" + job ) ; } } package org . oddjob . monitor . action ; import javax . swing . KeyStroke ; import org . oddjob . Forceable ; import org . oddjob . monitor . Standards ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . util . ThreadManager ; public class ForceAction extends JobAction { private Forceable job = null ; private ThreadManager threadManager ; public String getName ( ) { return "" ; } public String getGroup ( ) { return JOB_GROUP ; } public Integer getMnemonicKey ( ) { return Standards . FORCE_MNEMONIC_KEY ; } public KeyStroke getAcceleratorKey ( ) { return null ; } @ Override protected void doPrepare ( ExplorerContext explorerContext ) { Object component = explorerContext . getThisComponent ( ) ; if ( component instanceof Forceable ) { this . job = ( Forceable ) component ; this . threadManager = explorerContext . getThreadManager ( ) ; setEnabled ( true ) ; setVisible ( true ) ; } else { setEnabled ( false ) ; setVisible ( false ) ; } } @ Override protected void doFree ( ExplorerContext explorerContext ) { job = null ; threadManager = null ; } @ Override protected void doAction ( ) throws Exception { Runnable runnable = new Runnable ( ) { public void run ( ) { job . force ( ) ; } } ; threadManager . run ( runnable , "" + job ) ; } } package org . oddjob . monitor . control ; import java . beans . PropertyChangeListener ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . HashMap ; import java . util . Map ; import org . apache . log4j . Logger ; public class PropertyChangeHelper { private static final Logger logger = Logger . getLogger ( PropertyChangeHelper . class ) ; private static final Map < Class < ? > , PropertyChangeHelper > helpers = new HashMap < Class < ? > , PropertyChangeHelper > ( ) ; private Method addPropListenerMethod ; private Method removePropListenerMethod ; private PropertyChangeHelper ( Class < ? > bean ) { Class < ? > beanClass = bean . getClass ( ) ; Class < ? > [ ] argClasses = { PropertyChangeListener . class } ; try { addPropListenerMethod = beanClass . getMethod ( "" , argClasses ) ; removePropListenerMethod = beanClass . getMethod ( "" , argClasses ) ; } catch ( SecurityException e ) { logger . debug ( e ) ; } catch ( NoSuchMethodException e ) { } } private static PropertyChangeHelper lookup ( Class < ? > bean ) { synchronized ( helpers ) { PropertyChangeHelper helper = helpers . get ( bean ) ; if ( helper == null ) { helper = new PropertyChangeHelper ( bean ) ; helpers . put ( bean , helper ) ; } return helper ; } } public static void addPropertyChangeListener ( Object obj , PropertyChangeListener l ) { PropertyChangeHelper helper = lookup ( obj . getClass ( ) ) ; if ( helper . addPropListenerMethod == null ) { return ; } Object [ ] args = { obj } ; try { helper . addPropListenerMethod . invoke ( obj , args ) ; } catch ( IllegalArgumentException e ) { logger . debug ( e ) ; } catch ( IllegalAccessException e ) { logger . debug ( e ) ; } catch ( InvocationTargetException e ) { logger . debug ( e ) ; } } public static void removePropertyChangeListener ( Object obj , PropertyChangeListener l ) { PropertyChangeHelper helper = lookup ( obj . getClass ( ) ) ; if ( helper . removePropListenerMethod == null ) { return ; } Object [ ] args = { obj } ; try { helper . removePropListenerMethod . invoke ( obj , args ) ; } catch ( IllegalArgumentException e ) { logger . debug ( e ) ; } catch ( IllegalAccessException e ) { logger . debug ( e ) ; } catch ( InvocationTargetException e ) { logger . debug ( e ) ; } } } package org . oddjob . monitor . control ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import java . util . HashMap ; import java . util . Map ; import org . apache . log4j . Logger ; import org . oddjob . Stateful ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . monitor . model . DetailModel ; import org . oddjob . monitor . model . PropertyModel ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class PropertyPolling implements PropertyChangeListener { private static final Logger logger = Logger . getLogger ( PropertyPolling . class ) ; private Object subject ; private Object kick ; private PropertyModel propertyModel ; private final UniversalDescriber describer ; private final PropertyChangeListener subjectListener = new PropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent e ) { synchronized ( kick ) { kick . notifyAll ( ) ; } } } ; private final StateListener stateListener = new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { synchronized ( kick ) { kick . notifyAll ( ) ; } } } ; public PropertyPolling ( Object kick , ArooaSession session ) { this . describer = new UniversalDescriber ( session ) ; this . kick = kick ; } public void poll ( ) { Object subject = getSubject ( ) ; if ( subject == null ) { if ( propertyModel != null ) { propertyModel . setProperties ( new HashMap < String , String > ( ) ) ; } } else { Map < String , String > props = null ; props = describer . describe ( subject ) ; propertyModel . setProperties ( props ) ; } } public synchronized Object getSubject ( ) { return subject ; } public synchronized void setSubject ( Object subject ) { if ( this . subject == subject ) { return ; } logger . debug ( "" + subject + "" ) ; if ( this . subject != null ) { PropertyChangeHelper . removePropertyChangeListener ( this . subject , subjectListener ) ; if ( this . subject instanceof Stateful ) { ( ( Stateful ) this . subject ) . removeStateListener ( stateListener ) ; } } this . subject = subject ; if ( this . subject != null ) { PropertyChangeHelper . addPropertyChangeListener ( this . subject , subjectListener ) ; if ( this . subject instanceof Stateful ) { ( ( Stateful ) this . subject ) . addStateListener ( stateListener ) ; } } synchronized ( kick ) { kick . notifyAll ( ) ; } } public synchronized PropertyModel getPropertyModel ( ) { return propertyModel ; } public synchronized void setPropertyModel ( PropertyModel propertyModel ) { this . propertyModel = propertyModel ; } public void propertyChange ( PropertyChangeEvent evt ) { DetailModel explorerModel = ( DetailModel ) evt . getSource ( ) ; if ( explorerModel . getTabSelected ( ) != DetailModel . PROPERTIES_TAB || explorerModel . getSelectedJob ( ) == null ) { setSubject ( null ) ; return ; } setSubject ( explorerModel . getSelectedJob ( ) ) ; } } package org . oddjob . monitor . control ; import javax . swing . event . TreeExpansionEvent ; import javax . swing . event . TreeWillExpandListener ; import javax . swing . tree . ExpandVetoException ; import org . apache . log4j . Logger ; import org . oddjob . monitor . model . JobTreeNode ; public class NodeControl implements TreeWillExpandListener { private static final Logger logger = Logger . getLogger ( NodeControl . class ) ; public void treeWillCollapse ( TreeExpansionEvent event ) throws ExpandVetoException { JobTreeNode node = ( JobTreeNode ) event . getPath ( ) . getLastPathComponent ( ) ; JobTreeNode [ ] children = node . getChildren ( ) ; for ( int i = ; i < children . length ; ++ i ) { logger . debug ( "" + children [ i ] . getComponent ( ) + "" ) ; children [ i ] . setVisible ( false ) ; } } public void treeWillExpand ( TreeExpansionEvent event ) throws ExpandVetoException { JobTreeNode node = ( JobTreeNode ) event . getPath ( ) . getLastPathComponent ( ) ; JobTreeNode [ ] children = node . getChildren ( ) ; for ( int i = ; i < children . length ; ++ i ) { logger . debug ( "" + children [ i ] . getComponent ( ) + "" ) ; children [ i ] . setVisible ( true ) ; } } } package org . oddjob . monitor . control ; import javax . swing . JTree ; import javax . swing . event . ChangeEvent ; import javax . swing . event . ChangeListener ; import javax . swing . event . TreeSelectionEvent ; import javax . swing . event . TreeSelectionListener ; import org . oddjob . monitor . model . DetailModel ; import org . oddjob . monitor . model . JobTreeNode ; import org . oddjob . monitor . view . DetailView ; public class DetailController implements TreeSelectionListener { private final DetailModel detailModel ; private final DetailView detailView ; private JobTreeNode currentNode ; public DetailController ( DetailModel detailModel , DetailView detailView ) { this . detailModel = detailModel ; this . detailView = detailView ; detailView . addChangeListener ( new ChangeListener ( ) { public void stateChanged ( ChangeEvent e ) { if ( currentNode != null ) { DetailController . this . detailModel . setTabSelected ( DetailController . this . detailView . getSelectedIndex ( ) ) ; } } } ) ; } public void valueChanged ( TreeSelectionEvent event ) { JTree tree = ( JTree ) event . getSource ( ) ; currentNode = ( JobTreeNode ) tree . getLastSelectedPathComponent ( ) ; if ( currentNode == null ) { detailModel . setSelectedContext ( null ) ; } else { detailModel . setSelectedContext ( currentNode . getExplorerContext ( ) ) ; } } } package org . oddjob . monitor . context ; public interface ContextInitialiser { public void initialise ( ExplorerContext context ) ; } package org . oddjob . monitor . context ; import org . oddjob . util . ThreadManager ; public interface ExplorerContext { public Object getThisComponent ( ) ; public ExplorerContext addChild ( Object child ) ; public ThreadManager getThreadManager ( ) ; public ExplorerContext getParent ( ) ; public void setValue ( String key , Object value ) ; public Object getValue ( String key ) ; } package org . oddjob . monitor . context ; public class CompositeContextInitialiser implements ContextInitialiser { private final ContextInitialiser [ ] initialisers ; public CompositeContextInitialiser ( ContextInitialiser [ ] initialisers ) { this . initialisers = initialisers ; } public void initialise ( ExplorerContext context ) { for ( ContextInitialiser initialiser : initialisers ) { initialiser . initialise ( context ) ; } } } package org . oddjob . monitor . context ; public class AncestorSearch { private final ExplorerContext start ; public AncestorSearch ( ExplorerContext start ) { this . start = start ; } public Object getValue ( String key ) { if ( start == null ) { return null ; } Object value = start . getValue ( key ) ; if ( value == null ) { return new AncestorSearch ( start . getParent ( ) ) . getValue ( key ) ; } return value ; } } package org . oddjob . monitor ; public interface MultiViewController { public void launchNewExplorer ( OddjobExplorer original ) ; } package org . oddjob ; public abstract class OddjobShutdownThread extends Thread { } package org . oddjob ; import org . oddjob . arooa . registry . Services ; import org . oddjob . input . InputHandler ; public interface OddjobServices extends Services { public static final String ODDJOB_SERVICES = "" ; public static final String CLASSLOADER_SERVICE = "" ; public static final String SCHEDULED_EXECUTOR = "" ; public static final String POOL_EXECUTOR = "" ; public static final String INPUT_HANDLER = "" ; public ClassLoader getClassLoader ( ) ; public OddjobExecutors getOddjobExecutors ( ) ; public InputHandler getInputHandler ( ) ; } package org . oddjob . values ; import java . util . LinkedHashMap ; import java . util . Map ; import org . apache . commons . beanutils . expression . DefaultResolver ; import org . apache . commons . beanutils . expression . Resolver ; import org . oddjob . arooa . ArooaException ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . framework . SimpleJob ; public class SetJob extends SimpleJob { private final Map < String , ArooaValue > values = new LinkedHashMap < String , ArooaValue > ( ) ; public void setValues ( String name , ArooaValue value ) { values . put ( name , value ) ; } protected int execute ( ) throws Exception { for ( Map . Entry < String , ArooaValue > entry : values . entrySet ( ) ) { String name = entry . getKey ( ) ; ArooaValue value = entry . getValue ( ) ; logger ( ) . info ( "" + name + "" + value + "" ) ; setProperty ( name , value ) ; } return ; } private void setProperty ( String property , ArooaValue value ) throws ArooaPropertyException { Resolver resolver = new DefaultResolver ( ) ; String compName = resolver . next ( property ) ; String propertyExpression = resolver . remove ( property ) ; if ( propertyExpression == null ) { throw new ArooaException ( "" ) ; } Object component = getArooaSession ( ) . getBeanRegistry ( ) . lookup ( compName ) ; if ( component == null ) { throw new ArooaException ( "" + compName + "" ) ; } PropertyAccessor propertyAccessor = getArooaSession ( ) . getTools ( ) . getPropertyAccessor ( ) ; propertyAccessor = propertyAccessor . accessorWithConversions ( getArooaSession ( ) . getTools ( ) . getArooaConverter ( ) ) ; propertyAccessor . setProperty ( component , propertyExpression , value ) ; } } package org . oddjob . values ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . apache . commons . beanutils . ConversionException ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . DynaProperty ; import org . apache . commons . beanutils . LazyDynaBean ; import org . apache . commons . beanutils . LazyDynaMap ; import org . apache . commons . beanutils . MutableDynaClass ; import org . oddjob . arooa . ArooaConstants ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . beanutils . BeanUtilsPropertyAccessor ; import org . oddjob . framework . SimpleJob ; public class VariablesJob extends SimpleJob implements DynaBean { private final Map < String , Object > values = new LinkedHashMap < String , Object > ( ) ; private final LazyDynaBean dynaBean = new LazyDynaMap ( values ) ; private final MutableDynaClass dynaClass = new VariablesDynaClass ( dynaBean ) ; public void setValue ( String name , ArooaValue value ) { logger ( ) . debug ( "" + name + "" + value + "" ) ; dynaBean . set ( name , value ) ; } protected int execute ( ) throws Exception { return ; } @ Override protected void onReset ( ) { List < String > keySet = new ArrayList < String > ( values . keySet ( ) ) ; for ( String name : keySet ) { if ( ArooaConstants . ID_PROPERTY . equals ( name ) ) { continue ; } values . remove ( name ) ; dynaClass . remove ( name ) ; } } public boolean contains ( String name , String key ) { return dynaBean . contains ( name , key ) ; } public Object get ( String name ) { return dynaBean . get ( name ) ; } public Object get ( String name , int index ) { return dynaBean . get ( name , index ) ; } public Object get ( String name , String key ) { return dynaBean . get ( name , key ) ; } public DynaClass getDynaClass ( ) { return dynaClass ; } public void remove ( String name , String key ) { dynaBean . remove ( name , key ) ; } public void set ( String name , Object value ) { logger ( ) . debug ( "" + name + "" + value + "" ) ; BeanUtilsPropertyAccessor . validateSimplePropertyName ( name ) ; dynaBean . set ( name , value ) ; } public void set ( String name , int index , Object value ) { logger ( ) . debug ( "" + name + "" + index + "" + value + "" ) ; dynaBean . set ( name , index , value ) ; } public void set ( String name , String key , Object value ) { logger ( ) . debug ( "" + name + "" + key + "" + value + "" ) ; dynaBean . set ( name , key , value ) ; } @ Override public String toString ( ) { return "" + get ( ArooaConstants . ID_PROPERTY ) ; } static class VariablesDynaClass implements MutableDynaClass , Serializable { private static final long serialVersionUID = ; private final MutableDynaClass delegate ; VariablesDynaClass ( DynaBean dynaBean ) { this . delegate = ( MutableDynaClass ) dynaBean . getDynaClass ( ) ; } public DynaProperty getDynaProperty ( String name ) { DynaProperty dynaProperty = delegate . getDynaProperty ( name ) ; if ( dynaProperty == null ) { throw new NullPointerException ( "" ) ; } if ( dynaProperty . getContentType ( ) != null && ArooaValue . class . isAssignableFrom ( dynaProperty . getContentType ( ) ) ) { return dynaProperty ; } return new DynaProperty ( dynaProperty . getName ( ) , ArooaValue . class , dynaProperty . getContentType ( ) ) ; } public DynaProperty [ ] getDynaProperties ( ) { return delegate . getDynaProperties ( ) ; } public String getName ( ) { return delegate . getName ( ) ; } public DynaBean newInstance ( ) throws IllegalAccessException , InstantiationException { throw new UnsupportedOperationException ( ) ; } public void add ( String name ) { delegate . add ( name ) ; } public void add ( String name , Class type ) { delegate . add ( name , type ) ; } public void add ( String name , Class type , boolean readable , boolean writeable ) { delegate . add ( name , type , readable , writeable ) ; } public boolean isRestricted ( ) { return delegate . isRestricted ( ) ; } public void remove ( String name ) { delegate . remove ( name ) ; } public void setRestricted ( boolean restricted ) { delegate . setRestricted ( restricted ) ; } } } package org . oddjob . values ; import java . util . Iterator ; import java . util . LinkedList ; import org . oddjob . jobs . structural . ForEachJob ; public class ValueQueueService { private final LinkedList < Object > queue = new LinkedList < Object > ( ) ; private boolean started ; private String name ; public void start ( ) { synchronized ( queue ) { started = true ; } } public void stop ( ) { started = false ; synchronized ( queue ) { queue . notifyAll ( ) ; } } class BlockerIterator implements Iterator < Object > { private Object next ; @ Override public boolean hasNext ( ) { while ( started ) { synchronized ( queue ) { if ( queue . isEmpty ( ) ) { try { queue . wait ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; return false ; } } else { next = queue . removeFirst ( ) ; return true ; } } } return false ; } @ Override public Object next ( ) { return next ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } public Iterable < Object > getValues ( ) { return new Iterable < Object > ( ) { @ Override public Iterator < Object > iterator ( ) { return new BlockerIterator ( ) ; } } ; } public void setValue ( Object object ) { synchronized ( queue ) { if ( ! started ) { throw new IllegalStateException ( this + "" ) ; } queue . add ( object ) ; queue . notifyAll ( ) ; } } public int getSize ( ) { synchronized ( queue ) { return queue . size ( ) ; } } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } @ Override public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } else { return name ; } } } package org . oddjob . values . properties ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . IndexedDesignProperty ; import org . oddjob . arooa . design . MappedDesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . FormItem ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TabGroup ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . designer . components . BaseDC ; public class PropertiesDesFa implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { switch ( parentContext . getArooaType ( ) ) { case COMPONENT : return new PropertiesJobDesign ( element , parentContext ) ; case VALUE : return new PropertiesTypeDesign ( element , parentContext ) ; } throw new IllegalStateException ( "" ) ; } } class PropertiesJobDesign extends BaseDC { final private PropertiesDesign delegate ; private final SimpleTextAttribute override ; private final SimpleTextAttribute environment ; public PropertiesJobDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; override = new SimpleTextAttribute ( "" , this ) ; environment = new SimpleTextAttribute ( "" , this ) ; this . delegate = new PropertiesDesign ( element , parentContext , this ) ; } @ Override public Form detail ( ) { FormItem detail = delegate . detail ( ) ; return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new FieldGroup ( ) . add ( override . view ( ) . setTitle ( "" ) ) . add ( environment . view ( ) . setTitle ( "" ) ) ) . addFormItem ( detail ) ; } @ Override public DesignProperty [ ] children ( ) { DesignProperty [ ] delegates = delegate . children ( ) ; DesignProperty [ ] all = new DesignProperty [ delegates . length + ] ; all [ ] = name ; all [ ] = override ; all [ ] = environment ; System . arraycopy ( delegates , , all , , delegates . length ) ; return all ; } } class PropertiesTypeDesign extends DesignValueBase { final private PropertiesDesign delegate ; public PropertiesTypeDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; this . delegate = new PropertiesDesign ( element , parentContext , this ) ; } @ Override public Form detail ( ) { FormItem detail = delegate . detail ( ) ; return new StandardForm ( this ) . addFormItem ( detail ) ; } @ Override public DesignProperty [ ] children ( ) { return delegate . children ( ) ; } } class PropertiesDesign { private final MappedDesignProperty values ; private final IndexedDesignProperty sets ; private final SimpleTextAttribute fromXML ; private final SimpleTextAttribute substitute ; private final SimpleDesignProperty input ; private final SimpleTextAttribute extract ; private final SimpleTextAttribute prefix ; public PropertiesDesign ( ArooaElement element , ArooaContext parentContext , DesignInstance owner ) { values = new MappedDesignProperty ( "" , owner ) ; sets = new IndexedDesignProperty ( "" , owner ) ; substitute = new SimpleTextAttribute ( "" , owner ) ; fromXML = new SimpleTextAttribute ( "" , owner ) ; input = new SimpleDesignProperty ( "" , owner ) ; extract = new SimpleTextAttribute ( "" , owner ) ; prefix = new SimpleTextAttribute ( "" , owner ) ; } FormItem detail ( ) { return new TabGroup ( "" ) . add ( values . view ( ) . setTitle ( "" ) ) . add ( sets . view ( ) . setTitle ( "" ) ) . add ( new FieldGroup ( "" ) . add ( substitute . view ( ) . setTitle ( "" ) ) . add ( input . view ( ) . setTitle ( "" ) ) . add ( fromXML . view ( ) . setTitle ( "" ) ) ) . add ( new FieldGroup ( "" ) . add ( extract . view ( ) . setTitle ( "" ) ) . add ( prefix . view ( ) . setTitle ( "" ) ) ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { values , sets , fromXML , substitute , input } ; } } package org . oddjob . values . properties ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . ParsingInterceptor ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . life . ComponentProxyResolver ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . SessionOverrideContext ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . runtime . PropertyManager ; import org . oddjob . arooa . standard . StandardPropertyManager ; public class PropertiesInterceptor implements ParsingInterceptor { @ Override public ArooaContext intercept ( ArooaContext suggestedContext ) throws ArooaConfigurationException { if ( ! ( suggestedContext . getSession ( ) instanceof Session ) ) { return new SessionOverrideContext ( suggestedContext , new Session ( suggestedContext . getSession ( ) ) ) ; } else { return suggestedContext ; } } public static class Session implements ArooaSession { private final PropertyManager propertyManager ; private final ArooaSession session ; public Session ( ArooaSession session ) { this . propertyManager = new StandardPropertyManager ( session . getPropertyManager ( ) ) ; this . session = session ; } @ Override public ArooaDescriptor getArooaDescriptor ( ) { return session . getArooaDescriptor ( ) ; } @ Override public ComponentPool getComponentPool ( ) { return session . getComponentPool ( ) ; } @ Override public BeanRegistry getBeanRegistry ( ) { return session . getBeanRegistry ( ) ; } @ Override public PropertyManager getPropertyManager ( ) { return propertyManager ; } @ Override public ArooaTools getTools ( ) { return session . getTools ( ) ; } @ Override public ComponentPersister getComponentPersister ( ) { return session . getComponentPersister ( ) ; } @ Override public ComponentProxyResolver getComponentProxyResolver ( ) { return session . getComponentProxyResolver ( ) ; } } } package org . oddjob . values . properties ; import java . io . IOException ; import java . io . InputStream ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . TreeMap ; import java . util . TreeSet ; import org . oddjob . Describeable ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . runtime . PropertyLookup ; import org . oddjob . arooa . runtime . PropertySource ; public class PropertiesJob extends PropertiesJobBase implements Describeable { private static final long serialVersionUID = ; private transient PropertiesBase delegate ; private transient ArooaSession session ; private transient PropertyLookup lookup ; private String environment ; private boolean override ; public PropertiesJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { delegate = new PropertiesBase ( ) ; } @ Override public void setArooaContext ( ArooaContext context ) { super . setArooaContext ( context ) ; delegate . setArooaContext ( context ) ; session = ( ( PropertiesConfigurationSession ) context . getSession ( ) ) . getOriginal ( ) ; } @ Override protected ArooaSession getArooaSession ( ) { return session ; } protected void createPropertyLookup ( ) { super . createPropertyLookup ( ) ; if ( environment != null ) { lookup = new CompositeLookup ( new EnvVarPropertyLookup ( environment ) , super . getLookup ( ) ) ; } } @ Override protected PropertyLookup getLookup ( ) { if ( lookup == null ) { return super . getLookup ( ) ; } else { return lookup ; } } @ Override protected int execute ( ) throws IOException , ArooaConversionException { setProperties ( delegate . toProperties ( ) ) ; addPropertyLookup ( ) ; return ; } @ Override public Map < String , String > describe ( ) { PropertyLookup lookup = getLookup ( ) ; Map < String , String > description = new TreeMap < String , String > ( ) ; if ( lookup == null ) { return description ; } PropertyLookup managers = session . getPropertyManager ( ) ; Set < String > names = lookup . propertyNames ( ) ; if ( names . isEmpty ( ) ) { for ( String name : managers . propertyNames ( ) ) { String value = managers . lookup ( name ) ; PropertySource source = managers . sourceFor ( name ) ; value += "" + source + "" ; description . put ( name , value ) ; } } else { for ( String name : names ) { String value = lookup . lookup ( name ) ; PropertySource local = lookup . sourceFor ( name ) ; PropertySource actual = managers . sourceFor ( name ) ; if ( ! local . equals ( actual ) ) { value += "" + managers . lookup ( name ) + "" + actual + "" ; } description . put ( name , value ) ; } } return description ; } @ Override protected void onReset ( ) { super . onReset ( ) ; lookup = null ; } public String getEnvironment ( ) { return environment ; } public void setEnvironment ( String environment ) { this . environment = environment ; } public void setInput ( InputStream input ) { this . delegate . setInput ( input ) ; } public void setFromXML ( boolean fromXML ) { this . delegate . setFromXML ( fromXML ) ; } public boolean isFromXML ( ) { return this . delegate . isFromXML ( ) ; } public void setValues ( String key , String value ) { this . delegate . setValues ( key , value ) ; } public void setSets ( int index , Properties props ) { this . delegate . setSets ( index , props ) ; } public Properties getSets ( int index ) { return this . delegate . getSets ( index ) ; } public void setSubstitute ( boolean substitute ) { this . delegate . setSubstitute ( substitute ) ; } public boolean isSubstitute ( ) { return delegate . isSubstitute ( ) ; } public String getExtract ( ) { return delegate . getExtract ( ) ; } public void setExtract ( String extract ) { this . delegate . setExtract ( extract ) ; } public String getPrefix ( ) { return this . delegate . getPrefix ( ) ; } public void setPrefix ( String prefix ) { this . delegate . setPrefix ( prefix ) ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; completeConstruction ( ) ; } public boolean isOverride ( ) { return override ; } public void setOverride ( boolean override ) { this . override = override ; } private class CompositeLookup implements PropertyLookup { private final PropertySource propertySource = new PropertySource ( ) { public String toString ( ) { return PropertiesJob . this . toString ( ) ; } } ; private final PropertyLookup environment ; private final PropertyLookup loaded ; CompositeLookup ( PropertyLookup first , PropertyLookup second ) { if ( first == null ) { throw new NullPointerException ( "" ) ; } if ( second == null ) { throw new NullPointerException ( "" ) ; } this . environment = first ; this . loaded = second ; } @ Override public String lookup ( String propertyName ) { String value = null ; value = environment . lookup ( propertyName ) ; if ( value == null ) { value = loaded . lookup ( propertyName ) ; } return value ; } @ Override public Set < String > propertyNames ( ) { Set < String > names = new TreeSet < String > ( ) ; names . addAll ( environment . propertyNames ( ) ) ; names . addAll ( loaded . propertyNames ( ) ) ; return names ; } @ Override public PropertySource sourceFor ( String propertyName ) { if ( lookup ( propertyName ) != null ) { return propertySource ; } return null ; } } } package org . oddjob . values . properties ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . parsing . SessionDelegate ; import org . oddjob . arooa . runtime . PropertyManager ; import org . oddjob . arooa . standard . StandardPropertyManager ; import org . oddjob . values . types . PropertyType ; public class PropertiesConfigurationSession extends SessionDelegate implements ArooaSession { private final PropertyManager propertyManager ; public PropertiesConfigurationSession ( ArooaSession original ) { super ( original ) ; this . propertyManager = new StandardPropertyManager ( original . getPropertyManager ( ) ) ; } @ Override public PropertyManager getPropertyManager ( ) { return propertyManager ; } } package org . oddjob . values . properties ; import java . util . Map ; import java . util . Set ; import java . util . TreeSet ; import org . oddjob . arooa . runtime . PropertyLookup ; import org . oddjob . arooa . runtime . PropertySource ; public class EnvVarPropertyLookup implements PropertyLookup { final PropertySource SOURCE = new PropertySource ( ) { public String toString ( ) { return "" ; } } ; private final String prefixPlusDot ; public EnvVarPropertyLookup ( String prefix ) { this . prefixPlusDot = prefix + "" ; } @ Override public String lookup ( String propertyName ) { if ( ! propertyName . startsWith ( prefixPlusDot ) ) { return null ; } String envVar = propertyName . substring ( prefixPlusDot . length ( ) ) ; return System . getenv ( envVar ) ; } @ Override public Set < String > propertyNames ( ) { Map < String , String > all = System . getenv ( ) ; Set < String > names = new TreeSet < String > ( ) ; for ( String key : all . keySet ( ) ) { names . add ( prefixPlusDot + key ) ; } return names ; } @ Override public PropertySource sourceFor ( String propertyName ) { if ( lookup ( propertyName ) != null ) { return SOURCE ; } else { return null ; } } } package org . oddjob . values . properties ; public class PropertiesJobArooa extends PropertiesBaseArooa { } package org . oddjob . values . properties ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . ParsingInterceptor ; import org . oddjob . arooa . deploy . NoAnnotations ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . SessionOverrideContext ; public class PropertiesBaseArooa implements ArooaBeanDescriptor { @ Override public ParsingInterceptor getParsingInterceptor ( ) { return new ParsingInterceptor ( ) { @ Override public ArooaContext intercept ( ArooaContext suggestedContext ) throws ArooaConfigurationException { return new SessionOverrideContext ( suggestedContext , new PropertiesConfigurationSession ( suggestedContext . getSession ( ) ) ) ; } } ; } @ Override public String getComponentProperty ( ) { return null ; } @ Override public ConfiguredHow getConfiguredHow ( String property ) { if ( "" . equals ( property ) ) { return ConfiguredHow . HIDDEN ; } if ( "" . equals ( property ) ) { return ConfiguredHow . HIDDEN ; } return null ; } @ Override public String getFlavour ( String property ) { return null ; } @ Override public String getTextProperty ( ) { return null ; } @ Override public boolean isAuto ( String property ) { return false ; } @ Override public ArooaAnnotations getAnnotations ( ) { return new NoAnnotations ( ) ; } } package org . oddjob . values . properties ; public class PropertiesTypeArooa extends PropertiesBaseArooa { } package org . oddjob . values . properties ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . Properties ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . runtime . PropertyLookup ; import org . oddjob . arooa . runtime . PropertyManager ; import org . oddjob . arooa . runtime . RuntimeEvent ; import org . oddjob . arooa . runtime . RuntimeListener ; import org . oddjob . arooa . standard . StandardPropertyLookup ; import org . oddjob . framework . SerializableJob ; import org . oddjob . state . JobState ; abstract public class PropertiesJobBase extends SerializableJob { private static final long serialVersionUID = ; private Properties properties ; private transient PropertyLookup lookup ; @ Override @ ArooaHidden public void setArooaContext ( ArooaContext context ) { super . setArooaContext ( context ) ; context . getRuntime ( ) . addRuntimeListener ( new RuntimeListener ( ) { @ Override public void beforeInit ( RuntimeEvent event ) throws ArooaConfigurationException { } @ Override public void beforeDestroy ( RuntimeEvent event ) throws ArooaConfigurationException { } @ Override public void beforeConfigure ( RuntimeEvent event ) throws ArooaConfigurationException { } @ Override public void afterInit ( RuntimeEvent event ) throws ArooaConfigurationException { if ( stateHandler . getState ( ) == JobState . COMPLETE ) { if ( properties == null ) { throw new NullPointerException ( "" ) ; } addPropertyLookup ( ) ; } } @ Override public void afterDestroy ( RuntimeEvent event ) throws ArooaConfigurationException { } @ Override public void afterConfigure ( RuntimeEvent event ) throws ArooaConfigurationException { } } ) ; } protected void createPropertyLookup ( ) { lookup = new StandardPropertyLookup ( properties , this . toString ( ) ) ; } protected final void addPropertyLookup ( ) { createPropertyLookup ( ) ; ArooaSession session = getArooaSession ( ) ; if ( session == null ) { throw new NullPointerException ( "" ) ; } if ( isOverride ( ) ) { session . getPropertyManager ( ) . addPropertyOverride ( getLookup ( ) ) ; } else { session . getPropertyManager ( ) . addPropertyLookup ( getLookup ( ) ) ; } } protected PropertyLookup getLookup ( ) { return lookup ; } @ Override protected void onReset ( ) { getArooaSession ( ) . getPropertyManager ( ) . removePropertyLookup ( getLookup ( ) ) ; lookup = null ; } @ Override public void onDestroy ( ) { super . onDestroy ( ) ; onReset ( ) ; } protected void setProperties ( Properties properties ) { this . properties = properties ; } public Properties getProperties ( ) { return properties ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; } abstract protected boolean isOverride ( ) ; } package org . oddjob . values . properties ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import java . util . TreeSet ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . deploy . annotations . ArooaInterceptor ; import org . oddjob . arooa . life . ArooaContextAware ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . runtime . ExpressionParser ; import org . oddjob . arooa . runtime . ParsedExpression ; import org . oddjob . arooa . runtime . PropertyLookup ; import org . oddjob . arooa . runtime . PropertySource ; import org . oddjob . arooa . utils . ListSetterHelper ; @ ArooaInterceptor ( "" ) public class PropertiesBase implements ArooaContextAware { private static final Logger logger = Logger . getLogger ( PropertiesBase . class ) ; private InputStream input ; private boolean fromXML ; private List < Properties > list = new ArrayList < Properties > ( ) ; private Map < String , String > values = new LinkedHashMap < String , String > ( ) ; private boolean substitute ; private String extract ; private String prefix ; private ArooaSession session ; private PropertySource source ; @ Override public void setArooaContext ( final ArooaContext context ) { session = context . getSession ( ) ; final PropertyLookup propertyLookup = new PropertyLookup ( ) { @ Override public String lookup ( String propertyName ) { String value = values . get ( propertyName ) ; if ( value != null ) { return value ; } for ( Properties props : list ) { if ( props == null ) { continue ; } value = props . getProperty ( propertyName ) ; if ( value != null ) { return value ; } } return null ; } @ Override public Set < String > propertyNames ( ) { Set < String > names = new TreeSet < String > ( ) ; names . addAll ( values . keySet ( ) ) ; for ( Properties props : list ) { if ( props == null ) { continue ; } names . addAll ( props . stringPropertyNames ( ) ) ; } return names ; } @ Override public PropertySource sourceFor ( String propertyName ) { if ( lookup ( propertyName ) != null ) { return source ; } return null ; } } ; session . getPropertyManager ( ) . addPropertyLookup ( propertyLookup ) ; } protected Properties toProperties ( ) throws IOException , ArooaConversionException { Properties props = new Properties ( ) ; load ( values , props ) ; Properties [ ] sets = list . toArray ( new Properties [ list . size ( ) ] ) ; for ( int i = ; i < sets . length ; ++ i ) { if ( sets [ i ] == null ) { throw new ArooaConversionException ( "" + i + "" ) ; } load ( sets [ i ] , props ) ; } if ( input != null ) { load ( loadInput ( ) , props ) ; } return props ; } private void load ( Map < ? , ? > properties , Properties into ) throws ArooaConversionException { for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { String name = entry . getKey ( ) . toString ( ) ; String value = entry . getValue ( ) . toString ( ) ; if ( extract != null ) { String extractWithDot = extract + "" ; if ( ! name . startsWith ( extractWithDot ) ) { continue ; } name = name . substring ( extractWithDot . length ( ) ) ; } if ( prefix != null ) { name = prefix + "" + name ; } if ( substitute ) { ExpressionParser parser = session . getTools ( ) . getExpressionParser ( ) ; ParsedExpression expression = parser . parse ( value ) ; value = expression . evaluate ( session , String . class ) ; } if ( value == null ) { logger . info ( name + "" ) ; continue ; } into . setProperty ( name , value ) ; } } private Properties loadInput ( ) throws IOException { Properties props = new Properties ( ) ; try { if ( fromXML ) { props . loadFromXML ( input ) ; } else { props . load ( input ) ; } return props ; } finally { input . close ( ) ; } } public void setInput ( InputStream input ) { this . input = input ; } public void setFromXML ( boolean fromXml ) { this . fromXML = fromXml ; } public boolean isFromXML ( ) { return fromXML ; } public void setValues ( String key , String value ) { if ( value == null ) { values . remove ( key ) ; } else { values . put ( key , value ) ; } } public void setSets ( int index , Properties props ) { new ListSetterHelper < Properties > ( list ) . set ( index , props ) ; } public Properties getSets ( int index ) { return list . get ( index ) ; } public void setSubstitute ( boolean substitute ) { this . substitute = substitute ; } public boolean isSubstitute ( ) { return substitute ; } public String getExtract ( ) { return extract ; } public void setExtract ( String extract ) { this . extract = extract ; } public String getPrefix ( ) { return prefix ; } public void setPrefix ( String prefix ) { this . prefix = prefix ; } public PropertySource getSource ( ) { return source ; } public void setSource ( PropertySource source ) { this . source = source ; } } package org . oddjob . values . properties ; import java . util . Properties ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public class PropertiesType extends PropertiesBase implements ArooaValue { public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( PropertiesType . class , Properties . class , new Convertlet < PropertiesType , Properties > ( ) { public Properties convert ( PropertiesType from ) throws ConvertletException { try { return from . toProperties ( ) ; } catch ( Exception e ) { throw new ConvertletException ( e ) ; } } } ) ; } } @ Override public String toString ( ) { return "" ; } } package org . oddjob . values . types ; import java . text . ParseException ; import java . util . Arrays ; import java . util . List ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . utils . ArooaTokenizer ; import org . oddjob . arooa . utils . FlexibleTokenizerFactory ; public class TokenizerType implements ArooaValue { public static final ArooaElement ELEMENT = new ArooaElement ( "" ) ; public static final String DEFAULT_DELIMITER_REGEXP = "" ; public static class Conversions implements ConversionProvider { @ SuppressWarnings ( "" ) public void registerWith ( ConversionRegistry registry ) { registry . register ( TokenizerType . class , List . class , new Convertlet < TokenizerType , List > ( ) { @ Override public List convert ( TokenizerType from ) throws ConvertletException { try { return Arrays . asList ( from . parse ( ) ) ; } catch ( ParseException e ) { throw new ConvertletException ( e ) ; } } } ) ; registry . register ( TokenizerType . class , String [ ] . class , new Convertlet < TokenizerType , String [ ] > ( ) { @ Override public String [ ] convert ( TokenizerType from ) throws ConvertletException { try { return from . parse ( ) ; } catch ( ParseException e ) { throw new ConvertletException ( e ) ; } } } ) ; } } private String delimiter ; private String regexp ; private Character escape ; private Character quote ; private String text ; public String [ ] parse ( ) throws ParseException { if ( text == null ) { return null ; } String regexp = this . regexp ; if ( regexp == null && delimiter == null ) { regexp = DEFAULT_DELIMITER_REGEXP ; } FlexibleTokenizerFactory tokenizerFactory = new FlexibleTokenizerFactory ( ) ; tokenizerFactory . setDelimiter ( delimiter ) ; tokenizerFactory . setRegexp ( regexp ) ; tokenizerFactory . setEscape ( escape ) ; tokenizerFactory . setQuote ( quote ) ; ArooaTokenizer tokenizer = tokenizerFactory . newTokenizer ( ) ; return tokenizer . parse ( text ) ; } public String getDelimiter ( ) { return delimiter ; } public void setDelimiter ( String delimiter ) { this . delimiter = delimiter ; } public String getRegexp ( ) { return regexp ; } public void setRegexp ( String regexp ) { this . regexp = regexp ; } public Character getEscape ( ) { return escape ; } public void setEscape ( Character escape ) { this . escape = escape ; } public Character getQuote ( ) { return quote ; } public void setQuote ( Character quote ) { this . quote = quote ; } public String getText ( ) { return text ; } public void setText ( String text ) { this . text = text ; } } package org . oddjob . values . types ; import java . io . Serializable ; import java . util . HashMap ; import java . util . Map ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaProperty ; import org . apache . commons . beanutils . MutableDynaClass ; public class PropertyTypeDynaClass implements MutableDynaClass , Serializable { private static final long serialVersionUID = ; private final Map < String , DynaProperty > propertiesMap = new HashMap < String , DynaProperty > ( ) ; private final String name ; public PropertyTypeDynaClass ( String name ) { this . name = name ; } public boolean isRestricted ( ) { return false ; } public void setRestricted ( boolean restricted ) { throw new UnsupportedOperationException ( "" ) ; } public void add ( String name ) { add ( new DynaProperty ( name , String . class ) ) ; } public void add ( String name , Class type ) { if ( ! ( String . class . isAssignableFrom ( type ) ) ) { throw new IllegalArgumentException ( "" ) ; } add ( new DynaProperty ( name , type ) ) ; } public void add ( String name , Class type , boolean readable , boolean writeable ) { throw new java . lang . UnsupportedOperationException ( "" ) ; } protected void add ( DynaProperty property ) { if ( property . getName ( ) == null ) { throw new IllegalArgumentException ( "" ) ; } if ( propertiesMap . get ( property . getName ( ) ) != null ) { return ; } propertiesMap . put ( property . getName ( ) , property ) ; } public void remove ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } if ( propertiesMap . get ( name ) == null ) { return ; } propertiesMap . remove ( name ) ; } public DynaProperty getDynaProperty ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } DynaProperty dynaProperty = propertiesMap . get ( name ) ; if ( dynaProperty == null ) { dynaProperty = new DynaProperty ( name , String . class ) ; } return dynaProperty ; } public DynaProperty [ ] getDynaProperties ( ) { return ( DynaProperty [ ] ) propertiesMap . values ( ) . toArray ( new DynaProperty [ ] ) ; } public String getName ( ) { return name ; } public DynaBean newInstance ( ) throws IllegalAccessException , InstantiationException { throw new UnsupportedOperationException ( "" ) ; } } package org . oddjob . values . types ; import java . io . Serializable ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . MutableDynaClass ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . values . properties . PropertiesJob ; public class PropertyType implements DynaBean , Serializable { private static final long serialVersionUID = ; public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( PropertyType . class , String . class , new Convertlet < PropertyType , String > ( ) { public String convert ( PropertyType from ) throws ConvertletException { return from . value ; } } ) ; registry . register ( PropertyType . class , Properties . class , new Convertlet < PropertyType , Properties > ( ) { public Properties convert ( PropertyType from ) throws ConvertletException { return from . toProperties ( ) ; } } ) ; } } private final Map < String , PropertyType > props = new HashMap < String , PropertyType > ( ) ; private final MutableDynaClass dynaClass = new PropertyTypeDynaClass ( PropertyTypeDynaClass . class . getName ( ) ) ; private String value ; private final String name ; public PropertyType ( ) { this . name = null ; } private PropertyType ( String name ) { this . name = name ; } void properties ( Properties result , String stem ) { String propertyName = "" ; String nextStem = "" ; if ( name != null ) { propertyName = stem + name ; nextStem = propertyName + "" ; } if ( value != null ) { result . setProperty ( propertyName , value ) ; } for ( String childName : props . keySet ( ) ) { PropertyType child = props . get ( childName ) ; child . properties ( result , nextStem ) ; } } public Properties toProperties ( ) { Properties props = new Properties ( ) ; properties ( props , "" ) ; return props ; } public int size ( ) { return props . size ( ) ; } public boolean contains ( String name , String key ) { throw new UnsupportedOperationException ( "" ) ; } public Object get ( String name ) { PropertyType prop = props . get ( name ) ; if ( prop == null ) { prop = new PropertyType ( name ) ; props . put ( prop . name , prop ) ; dynaClass . add ( name ) ; } return prop ; } public Object get ( String name , int index ) { throw new UnsupportedOperationException ( "" ) ; } public Object get ( String name , String key ) { throw new UnsupportedOperationException ( "" ) ; } public DynaClass getDynaClass ( ) { return dynaClass ; } public void remove ( String name , String key ) { throw new UnsupportedOperationException ( "" ) ; } public void set ( String name , int index , Object value ) { throw new UnsupportedOperationException ( "" ) ; } public void set ( String name , Object value ) { PropertyType prop = ( PropertyType ) props . get ( name ) ; if ( prop == null ) { prop = new PropertyType ( name ) ; props . put ( prop . name , prop ) ; dynaClass . add ( name ) ; } prop . value = ( String ) value ; } public void set ( String name , String key , Object value ) { throw new UnsupportedOperationException ( "" ) ; } public String toString ( ) { if ( value != null ) { return "" + name + "" + value ; } else if ( name != null ) { return "" + name + "" + size ( ) + "" ; } else { return "" + size ( ) + "" ; } } } package org . oddjob . values . types ; import java . io . Serializable ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . arooa . utils . DateHelper ; public class DateType implements ArooaValue , Serializable { private static final long serialVersionUID = ; public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( DateType . class , Date . class , new Convertlet < DateType , Date > ( ) { public Date convert ( DateType from ) throws ConvertletException { try { return from . toDate ( ) ; } catch ( ParseException e ) { throw new ConvertletException ( e ) ; } } } ) ; registry . register ( DateType . class , Calendar . class , new Convertlet < DateType , Calendar > ( ) { public Calendar convert ( DateType from ) throws ConvertletException { try { return from . toCalandar ( ) ; } catch ( ParseException e ) { throw new ConvertletException ( e ) ; } } } ) ; } } private String date ; private String format ; private String timeZone ; public Calendar toCalandar ( ) throws ParseException { Date date = toDate ( ) ; if ( date == null ) { return null ; } TimeZone tz = TimeZone . getDefault ( ) ; if ( timeZone != null ) { tz = TimeZone . getTimeZone ( timeZone ) ; } Calendar cal = Calendar . getInstance ( tz ) ; cal . setTime ( date ) ; return cal ; } public Date toDate ( ) throws ParseException { if ( date == null ) { return null ; } if ( format == null ) { return DateHelper . parseDateTime ( date , timeZone ) ; } SimpleDateFormat sdf = new SimpleDateFormat ( format ) ; if ( timeZone != null ) { sdf . setTimeZone ( TimeZone . getTimeZone ( timeZone ) ) ; } return sdf . parse ( date ) ; } public void setDate ( String date ) { this . date = date ; } public String getDate ( ) { return date ; } public String getFormat ( ) { return format ; } public void setFormat ( String format ) { this . format = format ; } public void setTimeZone ( String timeZoneId ) { this . timeZone = timeZoneId ; } public String getTimeZone ( ) { return timeZone ; } public String toString ( ) { return "" + date ; } } package org . oddjob . values . types ; import java . io . Serializable ; import java . text . DateFormat ; import java . text . DecimalFormat ; import java . text . NumberFormat ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . TimeZone ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; public class FormatType implements ArooaValue , Serializable { private static final long serialVersionUID = ; public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( FormatType . class , String . class , new Convertlet < FormatType , String > ( ) { public String convert ( FormatType from ) throws ConvertletException { return from . toFormattedString ( ) ; } } ) ; } } private String format ; private TimeZone timeZone ; private Date date ; private Number number ; String toFormattedString ( ) { if ( format == null ) { return null ; } if ( date != null ) { DateFormat dateFormat = new SimpleDateFormat ( format ) ; if ( timeZone != null ) { dateFormat . setTimeZone ( timeZone ) ; } return dateFormat . format ( date ) ; } if ( number != null ) { NumberFormat numberFormat = new DecimalFormat ( format ) ; return numberFormat . format ( number ) ; } return null ; } @ ArooaAttribute public void setDate ( Date date ) { if ( date == null ) { this . date = null ; } else { this . date = new Date ( date . getTime ( ) ) ; } } public void setFormat ( String format ) { this . format = format ; } public void setTimeZone ( String timeZoneId ) { this . timeZone = TimeZone . getTimeZone ( timeZoneId ) ; } public void setNumber ( Number number ) { this . number = number ; } public String toString ( ) { StringBuilder string = new StringBuilder ( ) ; if ( format == null ) { string . append ( "" ) ; } else { string . append ( "" + format . toString ( ) + "" ) ; } if ( date != null ) { string . append ( date . toString ( ) ) ; } else if ( number != null ) { string . append ( number . toString ( ) ) ; } else { string . append ( "" ) ; } return string . toString ( ) ; } } package org . oddjob . values ; import java . net . URI ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ClassResolver ; import org . oddjob . arooa . ElementMappings ; import org . oddjob . arooa . beandocs . MappingsContents ; import org . oddjob . arooa . beanutils . DynaArooaClass ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . deploy . ArooaDescriptorFactory ; import org . oddjob . arooa . deploy . MappingsSwitch ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . ArooaClassFactory ; import org . oddjob . arooa . reflect . ArooaClasses ; import org . oddjob . arooa . reflect . ArooaInstantiationException ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . designer . components . VariablesDC ; public class VariablesJobDescriptorFactory implements ArooaDescriptorFactory { public static final ArooaElement VARIABLES = new ArooaElement ( "" ) ; static { ArooaClasses . register ( VariablesJob . class , new ArooaClassFactory < VariablesJob > ( ) { @ Override public ArooaClass classFor ( VariablesJob instance ) { return new VariablesArooaClass ( instance ) ; } } ) ; } @ Override public ArooaDescriptor createDescriptor ( ClassLoader classLoader ) { return new ArooaDescriptor ( ) { @ Override public ArooaBeanDescriptor getBeanDescriptor ( ArooaClass forClass , PropertyAccessor accessor ) { return null ; } @ Override public String getPrefixFor ( URI namespace ) { return null ; } @ Override public ElementMappings getElementMappings ( ) { return new MappingsSwitch ( new ElementMappings ( ) { @ Override public ArooaClass mappingFor ( ArooaElement element , InstantiationContext parentContext ) { if ( VARIABLES . equals ( element ) ) { return new VariablesArooaClass ( new VariablesJob ( ) ) ; } else { return null ; } } @ Override public ArooaElement [ ] elementsFor ( InstantiationContext propertyContext ) { return new ArooaElement [ ] { VARIABLES } ; } @ Override public DesignFactory designFor ( ArooaElement element , InstantiationContext parentContext ) { if ( VARIABLES . equals ( element ) ) { return new VariablesDC ( ) ; } return null ; } @ Override public MappingsContents getBeanDoc ( ArooaType arooaType ) { return new MappingsContents ( ) { @ Override public ArooaClass documentClass ( ArooaElement element ) { if ( VARIABLES . equals ( element ) ) { return new VariablesArooaClass ( new VariablesJob ( ) ) ; } return null ; } @ Override public ArooaElement [ ] allElements ( ) { return new ArooaElement [ ] { VARIABLES } ; } } ; } } , null ) ; } @ Override public ConversionProvider getConvertletProvider ( ) { return null ; } @ Override public ClassResolver getClassResolver ( ) { return null ; } } ; } static class VariablesArooaClass extends DynaArooaClass { private final VariablesJob variablesJob ; public VariablesArooaClass ( VariablesJob variablesJob ) { super ( variablesJob . getDynaClass ( ) , VariablesJob . class ) ; this . variablesJob = variablesJob ; } @ Override public Object newInstance ( ) throws ArooaInstantiationException { return variablesJob ; } } } package org . oddjob . values ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaConstants ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . ParsingInterceptor ; import org . oddjob . arooa . deploy . NoAnnotations ; public class VariablesJobArooa implements ArooaBeanDescriptor { public String getComponentProperty ( ) { return null ; } public ParsingInterceptor getParsingInterceptor ( ) { return null ; } public String getTextProperty ( ) { return null ; } public ConfiguredHow getConfiguredHow ( String property ) { if ( ArooaConstants . ID_PROPERTY . equals ( property ) ) { return ConfiguredHow . ATTRIBUTE ; } return ConfiguredHow . ELEMENT ; } public boolean isAuto ( String property ) { return false ; } public String getFlavour ( String property ) { return null ; } @ Override public ArooaAnnotations getAnnotations ( ) { return new NoAnnotations ( ) ; } } package org . oddjob ; public class FailedToStopException extends Exception { private static final long serialVersionUID = ; private final Object failedToStop ; public FailedToStopException ( Stateful failedToStop ) { super ( "" + failedToStop + "" + failedToStop . lastStateEvent ( ) . getState ( ) + "" ) ; this . failedToStop = failedToStop ; } public FailedToStopException ( Object failedToStop , String message ) { super ( message ) ; this . failedToStop = failedToStop ; } public FailedToStopException ( Object failedToStop , Throwable cause ) { super ( cause ) ; this . failedToStop = failedToStop ; } public FailedToStopException ( Object failedToStop , String message , Throwable cause ) { super ( message , cause ) ; this . failedToStop = failedToStop ; } public Object getFailedToStop ( ) { return failedToStop ; } } package org . oddjob . jmx ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . types . ValueFactory ; import org . oddjob . jmx . handlers . VanillaServerHandlerFactory ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; public class VanillaInterfaceHandler < T > implements ValueFactory < ServerInterfaceHandlerFactory < T , T > > , ArooaSessionAware { private ArooaSession session ; private String className ; public void setArooaSession ( ArooaSession session ) { this . session = session ; } public String getClassName ( ) { return className ; } public void setClassName ( String className ) { this . className = className ; } @ SuppressWarnings ( "" ) public ServerInterfaceHandlerFactory < T , T > toValue ( ) { Class < T > cl = ( Class < T > ) session . getArooaDescriptor ( ) . getClassResolver ( ) . findClass ( className ) ; return new VanillaServerHandlerFactory < T > ( cl ) ; } } package org . oddjob . jmx ; import java . io . NotSerializableException ; import java . io . Serializable ; import org . oddjob . framework . Exportable ; import org . oddjob . framework . Transportable ; public class Utils { public static String [ ] classArray2StringArray ( Class < ? > [ ] classes ) { String [ ] strings = new String [ classes . length ] ; for ( int i = ; i < classes . length ; ++ i ) { strings [ i ] = classes [ i ] . getName ( ) ; } return strings ; } public static Serializable [ ] export ( Object [ ] objects ) throws NotSerializableException { if ( objects == null ) { return null ; } Serializable [ ] results = new Serializable [ objects . length ] ; for ( int i = ; i < objects . length ; ++ i ) { results [ i ] = export ( objects [ i ] ) ; } return results ; } public static Serializable export ( Object object ) throws NotSerializableException { if ( object == null ) { return null ; } if ( object instanceof Exportable ) { return ( ( Exportable ) object ) . exportTransportable ( ) ; } else if ( object instanceof Serializable ) { return ( Serializable ) object ; } else { throw new NotSerializableException ( object . getClass ( ) . getName ( ) ) ; } } public static Object [ ] importResolve ( Object [ ] objects , ObjectNames names ) { if ( objects == null ) { return null ; } Object [ ] results = new Object [ objects . length ] ; for ( int i = ; i < objects . length ; ++ i ) { results [ i ] = importResolve ( objects [ i ] , names ) ; } return results ; } public static Object importResolve ( Object object , ObjectNames names ) { if ( object == null ) { return null ; } if ( object instanceof Transportable ) { return ( ( Transportable ) object ) . importResolve ( names ) ; } else { return object ; } } } package org . oddjob . jmx ; import java . net . MalformedURLException ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import javax . management . remote . JMXServiceURL ; public class JMXServiceURLHelper { private static final String URL_START = "" ; private static final Pattern URL_END = Pattern . compile ( "" ) ; public JMXServiceURL parse ( String url ) throws MalformedURLException { if ( url . startsWith ( URL_START ) ) { return new JMXServiceURL ( url ) ; } Matcher matcher = URL_END . matcher ( url ) ; if ( ! matcher . matches ( ) ) { throw new MalformedURLException ( "" + url + "" ) ; } String hostName = matcher . group ( ) ; String port = matcher . group ( ) ; String lastBit = matcher . group ( ) ; if ( port == null ) { port = "" ; } if ( lastBit == null ) { lastBit = "" ; } String path = "" + hostName + port + lastBit ; return new JMXServiceURL ( "" , "" , , path ) ; } } package org . oddjob . jmx ; import java . io . IOException ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . TimeUnit ; import javax . management . MBeanServerConnection ; import org . oddjob . Structural ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; import org . oddjob . jmx . general . DomainNode ; import org . oddjob . jmx . general . MBeanDirectory ; import org . oddjob . jmx . general . SimpleDomainNode ; import org . oddjob . jmx . general . SimpleMBeanSession ; import org . oddjob . script . InvokeJob ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class JMXServiceJob extends ClientBase implements Structural , BeanDirectoryOwner { private ChildHelper < DomainNode > childHelper = new ChildHelper < DomainNode > ( this ) ; private BeanDirectory beanDirectory ; @ Override protected void doStart ( final MBeanServerConnection mbsc , ScheduledExecutorService notificationProcessor ) throws IOException { SimpleMBeanSession session = new SimpleMBeanSession ( getArooaSession ( ) , mbsc ) ; String [ ] domains = mbsc . getDomains ( ) ; for ( String domain : domains ) { DomainNode node = new SimpleDomainNode ( domain , session ) ; childHelper . addChild ( node ) ; node . initialise ( ) ; } beanDirectory = new MBeanDirectory ( session ) ; notificationProcessor . scheduleAtFixedRate ( new Runnable ( ) { public void run ( ) { try { int count = mbsc . getMBeanCount ( ) ; logger ( ) . debug ( "" + count ) ; } catch ( Exception e ) { try { doStop ( WhyStop . HEARTBEAT_FAILURE , e ) ; } catch ( Exception e1 ) { logger ( ) . error ( "" , e1 ) ; } } } @ Override public String toString ( ) { return "" ; } } , getHeartbeat ( ) , getHeartbeat ( ) , TimeUnit . MILLISECONDS ) ; } @ Override protected void onStop ( WhyStop why ) { while ( childHelper . size ( ) > ) { DomainNode node = childHelper . removeChildAt ( ) ; node . destroy ( ) ; } this . beanDirectory = null ; } @ Override public BeanDirectory provideBeanDirectory ( ) { return beanDirectory ; } @ Override public void addStructuralListener ( StructuralListener listener ) { childHelper . addStructuralListener ( listener ) ; } @ Override public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanOperationInfo ; import org . oddjob . jmx . RemoteOperation ; abstract public class JMXOperation < T > extends RemoteOperation < T > { abstract public MBeanOperationInfo getOpInfo ( ) ; } package org . oddjob . jmx . server ; import org . oddjob . OJConstants ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . jmx . RemoteDirectory ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . cache . LocalConsoleArchiver ; import org . oddjob . logging . log4j . Log4jArchiver ; public class ServerContextImpl implements ServerContext { private final Object node ; private final ServerModel model ; private final BeanDirectory beanDirectory ; private final LogArchiver logArchiver ; private final ConsoleArchiver consoleArchiver ; private final ServerId serverId ; private final String id ; private final Path path ; public ServerContextImpl ( Object root , ServerModel model , BeanDirectory componentRegistry ) { this . model = model ; this . node = root ; String logFormat = model . getLogFormat ( ) ; logArchiver = new Log4jArchiver ( root , logFormat == null ? OJConstants . DEFAULT_LOG_FORMAT : logFormat ) ; consoleArchiver = new LocalConsoleArchiver ( ) ; this . beanDirectory = componentRegistry ; this . id = beanDirectory . getIdFor ( node ) ; this . serverId = model . getServerId ( ) ; this . path = new Path ( ) ; } private ServerContextImpl ( Object node , ServerContextImpl parent ) throws ServerLoopBackException { this . model = parent . getModel ( ) ; this . node = node ; if ( parent . node instanceof LogArchiver ) { logArchiver = ( LogArchiver ) parent . node ; } else { logArchiver = parent . getLogArchiver ( ) ; } if ( parent . node instanceof ConsoleArchiver ) { consoleArchiver = ( ConsoleArchiver ) parent . node ; } else { consoleArchiver = parent . getConsoleArchiver ( ) ; } ServerId serverId = parent . getServerId ( ) ; if ( parent . node instanceof BeanDirectoryOwner ) { this . beanDirectory = ( ( BeanDirectoryOwner ) parent . node ) . provideBeanDirectory ( ) ; if ( beanDirectory == null ) { throw new IllegalStateException ( "" + parent . node + "" ) ; } if ( beanDirectory instanceof RemoteDirectory ) { serverId = ( ( RemoteDirectory ) beanDirectory ) . getServerId ( ) ; if ( serverId . equals ( model . getServerId ( ) ) ) { throw new ServerLoopBackException ( serverId ) ; } } if ( ! serverId . equals ( parent . serverId ) ) { path = new Path ( ) ; } else if ( parent . path != null && parent . id != null ) { path = parent . path . addId ( parent . id ) ; } else { path = null ; } } else { this . path = parent . path ; this . beanDirectory = parent . beanDirectory ; } this . serverId = serverId ; this . id = beanDirectory . getIdFor ( node ) ; } public ServerContext addChild ( Object child ) throws ServerLoopBackException { return new ServerContextImpl ( child , this ) ; } public Object getComponent ( ) { return node ; } public ServerModel getModel ( ) { return model ; } public LogArchiver getLogArchiver ( ) { return logArchiver ; } public ConsoleArchiver getConsoleArchiver ( ) { return consoleArchiver ; } public ServerId getServerId ( ) { return serverId ; } public Address getAddress ( ) { if ( id != null && path != null ) { return new Address ( serverId , path . addId ( id ) ) ; } else { return null ; } } public BeanDirectory getBeanDirectory ( ) { return beanDirectory ; } } package org . oddjob . jmx . server ; import javax . management . JMException ; import javax . management . ObjectName ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . jmx . ObjectNames ; public interface ServerSession extends ObjectNames { public ObjectName createMBeanFor ( Object child , ServerContext childContext ) throws JMException ; public void destroy ( ObjectName childName ) throws JMException ; public ArooaSession getArooaSession ( ) ; } package org . oddjob . jmx . server ; import java . io . NotSerializableException ; import java . rmi . RemoteException ; import javax . management . Attribute ; import javax . management . AttributeList ; import javax . management . DynamicMBean ; import javax . management . MBeanException ; import javax . management . MBeanInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . Notification ; import javax . management . NotificationBroadcasterSupport ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import org . apache . log4j . Logger ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . jmx . Utils ; public class OddjobMBean extends NotificationBroadcasterSupport implements DynamicMBean { private static final Logger logger = Logger . getLogger ( OddjobMBean . class ) ; private final Object node ; private final ServerContext srvcon ; private int sequenceNumber = ; private final ObjectName objectName ; private final ServerSession factory ; private final ServerInterfaceManager serverInterfaceManager ; private final Object resyncLock = new Object ( ) ; public OddjobMBean ( Object node , ServerSession factory , ServerContext srvcon ) { if ( node == null ) { throw new NullPointerException ( "" ) ; } if ( srvcon == null ) { throw new NullPointerException ( "" ) ; } this . node = node ; this . factory = factory ; this . srvcon = srvcon ; this . objectName = factory . nameFor ( node ) ; ServerInterfaceManagerFactory imf = srvcon . getModel ( ) . getInterfaceManagerFactory ( ) ; serverInterfaceManager = imf . create ( node , new Toolkit ( ) ) ; } public Object getNode ( ) { return node ; } public Object getAttribute ( String attribute ) throws ReflectionException , MBeanException { logger . debug ( "" + attribute + "" ) ; return invoke ( "" , new Object [ ] { attribute } , new String [ ] { String . class . getName ( ) } ) ; } public void setAttribute ( Attribute attribute ) throws ReflectionException , MBeanException { logger . debug ( "" + attribute . getName ( ) + "" ) ; invoke ( "" , new Object [ ] { attribute . getClass ( ) , attribute . getValue ( ) } , new String [ ] { String . class . getName ( ) , Object . class . getName ( ) } ) ; } public AttributeList getAttributes ( String [ ] attributes ) { AttributeList al = new AttributeList ( ) ; for ( int i = ; i < attributes . length ; ++ i ) { String attribute = attributes [ i ] ; Attribute attr ; try { attr = new Attribute ( attribute , getAttribute ( attribute ) ) ; al . add ( attr ) ; } catch ( ReflectionException e ) { logger . debug ( e ) ; } catch ( MBeanException e ) { logger . debug ( e ) ; } } return al ; } public AttributeList setAttributes ( AttributeList attributes ) { AttributeList al = new AttributeList ( ) ; for ( Attribute attribute : attributes . asList ( ) ) { try { setAttribute ( attribute ) ; al . add ( attribute ) ; } catch ( ReflectionException e ) { logger . debug ( e ) ; } catch ( MBeanException e ) { logger . debug ( e ) ; } } return al ; } static String methodDescription ( final String actionName , String [ ] signature ) { StringBuffer buf = new StringBuffer ( ) ; buf . append ( actionName ) ; buf . append ( '' ) ; for ( int j = ; j < signature . length ; ++ j ) { buf . append ( j == ? "" : "" ) ; buf . append ( signature [ j ] ) ; } buf . append ( "" ) ; return buf . toString ( ) ; } public Object invoke ( final String actionName , final Object [ ] params , String [ ] signature ) throws MBeanException , ReflectionException { String methodDescription = methodDescription ( actionName , signature ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "" + methodDescription + "" + node + "" ) ; } Object [ ] imported = Utils . importResolve ( params , factory ) ; if ( imported == null ) { imported = new Object [ ] ; } Object result = serverInterfaceManager . invoke ( actionName , imported , signature ) ; try { return Utils . export ( result ) ; } catch ( NotSerializableException e ) { throw new MBeanException ( e , "" + actionName + "" ) ; } } public MBeanInfo getMBeanInfo ( ) { return serverInterfaceManager . getMBeanInfo ( ) ; } public MBeanNotificationInfo [ ] getNotificationInfo ( ) { return serverInterfaceManager . getMBeanInfo ( ) . getNotifications ( ) ; } public void destroy ( ) { logger . debug ( "" + node + "" ) ; serverInterfaceManager . destroy ( ) ; } class Remote implements RemoteOddjobBean { public ServerInfo serverInfo ( ) { return new ServerInfo ( srvcon . getAddress ( ) , serverInterfaceManager . allClientInfo ( ) ) ; } public void noop ( ) { } } class Toolkit implements ServerSideToolkit { public void sendNotification ( Notification notification ) { OddjobMBean . this . sendNotification ( notification ) ; } public Notification createNotification ( String type ) { synchronized ( resyncLock ) { return new Notification ( type , objectName , sequenceNumber ++ ) ; } } public void runSynchronized ( Runnable runnable ) { synchronized ( resyncLock ) { runnable . run ( ) ; } } public ServerContext getContext ( ) { return srvcon ; } public RemoteOddjobBean getRemoteBean ( ) { return new Remote ( ) ; } public ServerSession getServerSession ( ) { return factory ; } } } package org . oddjob . jmx . server ; import org . oddjob . Structural ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class ServerMainBean implements BeanDirectoryOwner , Structural { private final ChildHelper < Object > childHelper = new ChildHelper < Object > ( this ) ; private final BeanDirectory beanDirectory ; public ServerMainBean ( Object root , BeanDirectory beanDirectory ) { this . childHelper . insertChild ( , root ) ; this . beanDirectory = beanDirectory ; } public BeanDirectory provideBeanDirectory ( ) { return new BeanDirectory ( ) { public Object lookup ( String path ) throws ArooaPropertyException { return beanDirectory . lookup ( path ) ; } public < T > T lookup ( String path , Class < T > required ) throws ArooaPropertyException , ArooaConversionException { return beanDirectory . lookup ( path , required ) ; } public < T > Iterable < T > getAllByType ( Class < T > type ) { return beanDirectory . getAllByType ( type ) ; } public String getIdFor ( Object bean ) { return beanDirectory . getIdFor ( bean ) ; } } ; } public void addStructuralListener ( StructuralListener listener ) { childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } } package org . oddjob . jmx . server ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; public class AccumulatingFactoryProvider implements HandlerFactoryProvider { private List < HandlerFactoryProvider > providers = new ArrayList < HandlerFactoryProvider > ( ) ; public void addProvider ( HandlerFactoryProvider provider ) { providers . add ( provider ) ; } public ServerInterfaceHandlerFactory < ? , ? > [ ] getHandlerFactories ( ) { List < ServerInterfaceHandlerFactory < ? , ? > > results = new ArrayList < ServerInterfaceHandlerFactory < ? , ? > > ( ) ; for ( HandlerFactoryProvider provider : providers ) { results . addAll ( Arrays . asList ( provider . getHandlerFactories ( ) ) ) ; } return results . toArray ( new ServerInterfaceHandlerFactory < ? , ? > [ results . size ( ) ] ) ; } } package org . oddjob . jmx . server ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . util . ThreadManager ; public class ServerModelImpl implements ServerModel { private final ThreadManager threadManager ; private final ServerInterfaceManagerFactory imf ; private final ServerId serverId ; private String logFormat ; public ServerModelImpl ( ServerId serverId , ThreadManager threadManager , ServerInterfaceManagerFactory imf ) { if ( serverId == null ) { throw new NullPointerException ( "" ) ; } if ( threadManager == null ) { throw new NullPointerException ( "" ) ; } if ( imf == null ) { throw new NullPointerException ( "" ) ; } this . serverId = serverId ; this . threadManager = threadManager ; this . imf = imf ; } public ServerId getServerId ( ) { return serverId ; } public ThreadManager getThreadManager ( ) { return threadManager ; } public ServerInterfaceManagerFactory getInterfaceManagerFactory ( ) { return imf ; } public String getLogFormat ( ) { return logFormat ; } public void setLogFormat ( String logFormat ) { this . logFormat = logFormat ; } } package org . oddjob . jmx . server ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; public interface ServerContext { public ServerContext addChild ( Object child ) throws ServerLoopBackException ; public ServerModel getModel ( ) ; public LogArchiver getLogArchiver ( ) ; public ConsoleArchiver getConsoleArchiver ( ) ; public BeanDirectory getBeanDirectory ( ) ; public Address getAddress ( ) ; public ServerId getServerId ( ) ; } package org . oddjob . jmx . server ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import org . oddjob . jmx . client . ClientHandlerResolver ; public interface ServerInterfaceHandlerFactory < S , T > { public Class < S > interfaceClass ( ) ; public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) ; public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) ; public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) ; public ServerInterfaceHandler createServerHandler ( S target , ServerSideToolkit toolkit ) ; public ClientHandlerResolver < T > clientHandlerFactory ( ) ; } package org . oddjob . jmx . server ; public interface ServerInterfaceManagerFactory { public ServerInterfaceManager create ( Object target , ServerSideToolkit serverSideToolkit ) ; } package org . oddjob . jmx . server ; import java . util . ArrayList ; import java . util . List ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanParameterInfo ; public class JMXOperationPlus < T > extends JMXOperation < T > { private final String actionName ; private final Class < T > returnType ; private final String description ; private final int impact ; private final List < Param > params = new ArrayList < Param > ( ) ; public JMXOperationPlus ( String actionName , String description , Class < T > returnType , int impact ) { this . actionName = actionName ; this . returnType = returnType ; this . description = description ; this . impact = impact ; } public String getActionName ( ) { return actionName ; } public String [ ] getSignature ( ) { String [ ] signature = new String [ params . size ( ) ] ; int i = ; for ( Param param : params ) { signature [ i ++ ] = param . type . getName ( ) ; } return signature ; } public MBeanOperationInfo getOpInfo ( ) { MBeanParameterInfo [ ] paramInfos = new MBeanParameterInfo [ params . size ( ) ] ; int i = ; for ( Param param : params ) { paramInfos [ i ++ ] = new MBeanParameterInfo ( param . name , param . type . getName ( ) , param . description ) ; } return new MBeanOperationInfo ( actionName , description , paramInfos , returnType . getName ( ) , impact ) ; } public JMXOperationPlus < T > addParam ( String name , Class < ? > type , String description ) { params . add ( new Param ( name , type , description ) ) ; return this ; } class Param { final String name ; final Class < ? > type ; final String description ; Param ( String name , Class < ? > type , String description ) { this . name = name ; this . type = type ; this . description = description ; } } } package org . oddjob . jmx . server ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class LogArchiverHelper { static class LL implements LogListener { final List < LogEvent > events = new ArrayList < LogEvent > ( ) ; public void logEvent ( LogEvent logEvent ) { events . add ( logEvent ) ; } } public static LogEvent [ ] retrieveLogEvents ( Object component , LogArchiver archiver , Long last , Integer max ) { if ( archiver == null ) { throw new NullPointerException ( "" ) ; } LL ll = new LL ( ) ; archiver . addLogListener ( ll , component , LogLevel . DEBUG , last . longValue ( ) , max . intValue ( ) ) ; archiver . removeLogListener ( ll , component ) ; return ( LogEvent [ ] ) ll . events . toArray ( new LogEvent [ ] ) ; } public static String consoleId ( Object component , ConsoleArchiver archiver ) { String consoleId = archiver . consoleIdFor ( component ) ; if ( consoleId == null ) { throw new NullPointerException ( "" + component + "" ) ; } return consoleId ; } public static LogEvent [ ] retrieveConsoleEvents ( Object component , ConsoleArchiver archiver , Long last , Integer max ) { LL ll = new LL ( ) ; if ( archiver == null ) { throw new NullPointerException ( "" ) ; } archiver . addConsoleListener ( ll , component , last . longValue ( ) , max . intValue ( ) ) ; archiver . removeConsoleListener ( ll , component ) ; return ( LogEvent [ ] ) ll . events . toArray ( new LogEvent [ ] ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanException ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOperation ; public interface ServerInterfaceHandler { public Object invoke ( RemoteOperation < ? > operation , final Object [ ] params ) throws MBeanException , ReflectionException ; public void destroy ( ) ; } package org . oddjob . jmx . server ; import javax . management . MBeanOperationInfo ; public interface OddjobJMXAccessController { public boolean isAccessable ( MBeanOperationInfo opInfo ) ; } package org . oddjob . jmx . server ; import java . text . DecimalFormat ; import java . text . NumberFormat ; import java . util . HashMap ; import java . util . Map ; import javax . management . JMException ; import javax . management . MBeanServer ; import javax . management . MalformedObjectNameException ; import javax . management . ObjectName ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; public class OddjobMBeanFactory implements ServerSession { private static final Logger logger = Logger . getLogger ( OddjobMBeanFactory . class ) ; private final MBeanServer server ; private final ArooaSession session ; private int serial = ; private final Map < ObjectName , OddjobMBean > mBeans = new HashMap < ObjectName , OddjobMBean > ( ) ; private final Map < Object , ObjectName > names = new HashMap < Object , ObjectName > ( ) ; public OddjobMBeanFactory ( MBeanServer server , ArooaSession session ) { this . server = server ; this . session = session ; } public ObjectName createMBeanFor ( Object obj , ServerContext context ) throws JMException { ObjectName objName = null ; synchronized ( this ) { objName = objectName ( serial ++ ) ; } names . put ( obj , objName ) ; OddjobMBean ojmb = new OddjobMBean ( obj , this , context ) ; server . registerMBean ( ojmb , objName ) ; mBeans . put ( objName , ojmb ) ; logger . debug ( "" + obj + "" + objName . toString ( ) + "" ) ; return objName ; } public void destroy ( ObjectName objName ) throws JMException { server . unregisterMBean ( objName ) ; OddjobMBean ojmb = mBeans . remove ( objName ) ; names . remove ( ojmb . getNode ( ) ) ; ojmb . destroy ( ) ; logger . debug ( "" + objName . toString ( ) + "" ) ; } public static ObjectName objectName ( int sequence ) { try { NumberFormat f = new DecimalFormat ( "" ) ; String uid = f . format ( sequence ) ; return new ObjectName ( "" , "" , uid ) ; } catch ( MalformedObjectNameException ex ) { throw new RuntimeException ( ex ) ; } } public ObjectName nameFor ( Object object ) { return names . get ( object ) ; } public Object objectFor ( ObjectName objectName ) { OddjobMBean mBean = mBeans . get ( objectName ) ; return mBean . getNode ( ) ; } @ Override public ArooaSession getArooaSession ( ) { return session ; } } package org . oddjob . jmx . server ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . util . ThreadManager ; public interface ServerModel { public ServerId getServerId ( ) ; public ThreadManager getThreadManager ( ) ; public ServerInterfaceManagerFactory getInterfaceManagerFactory ( ) ; public String getLogFormat ( ) ; } package org . oddjob . jmx . server ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . jmx . handlers . BeanDirectoryHandlerFactory ; import org . oddjob . jmx . handlers . ObjectInterfaceHandlerFactory ; import org . oddjob . jmx . handlers . RemoteOddjobHandlerFactory ; import org . oddjob . jmx . handlers . StructuralHandlerFactory ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . util . ThreadManager ; public class ServerContextMain implements ServerContext { private final ServerModel model ; private final BeanDirectory beanDirectory ; private final ServerId serverId ; public ServerContextMain ( ServerModel model , BeanDirectory componentRegistry ) { this . model = model ; this . beanDirectory = componentRegistry ; this . serverId = model . getServerId ( ) ; } public ServerContext addChild ( Object child ) throws ServerLoopBackException { return new ServerContextImpl ( child , model , beanDirectory ) ; } public ServerModel getModel ( ) { return new MainModel ( ) ; } public LogArchiver getLogArchiver ( ) { return null ; } public ConsoleArchiver getConsoleArchiver ( ) { return null ; } public ServerId getServerId ( ) { return serverId ; } public Address getAddress ( ) { return null ; } public BeanDirectory getBeanDirectory ( ) { return beanDirectory ; } class MainModel implements ServerModel { public ServerInterfaceManagerFactory getInterfaceManagerFactory ( ) { return new ServerInterfaceManagerFactoryImpl ( new ServerInterfaceHandlerFactory < ? , ? > [ ] { new RemoteOddjobHandlerFactory ( ) , new ObjectInterfaceHandlerFactory ( ) , new BeanDirectoryHandlerFactory ( ) , new StructuralHandlerFactory ( ) } ) ; } public String getLogFormat ( ) { return model . getLogFormat ( ) ; } public ServerId getServerId ( ) { return model . getServerId ( ) ; } public ThreadManager getThreadManager ( ) { return model . getThreadManager ( ) ; } } } package org . oddjob . jmx . server ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanParameterInfo ; import org . oddjob . jmx . RemoteOperation ; public class OperationInfoOperation extends JMXOperation < Object > { private final String actionName ; private final String [ ] signature ; private final MBeanOperationInfo opInfo ; public OperationInfoOperation ( MBeanOperationInfo opInfo ) { this . actionName = opInfo . getName ( ) ; signature = new String [ opInfo . getSignature ( ) . length ] ; int i = ; for ( MBeanParameterInfo param : opInfo . getSignature ( ) ) { signature [ i ++ ] = param . getType ( ) ; } this . opInfo = opInfo ; } public String getActionName ( ) { return actionName ; } public String [ ] getSignature ( ) { return signature ; } public MBeanOperationInfo getOpInfo ( ) { return opInfo ; } } package org . oddjob . jmx . server ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . oddjob . jmx . JMXServerJob ; import org . oddjob . jmx . SharedConstants ; public class ServerInterfaceManagerFactoryImpl implements ServerInterfaceManagerFactory { private Set < ServerInterfaceHandlerFactory < ? , ? > > serverHandlerFactories = new HashSet < ServerInterfaceHandlerFactory < ? , ? > > ( ) ; private OddjobJMXAccessController accessController ; public ServerInterfaceManagerFactoryImpl ( ) { this . serverHandlerFactories . addAll ( Arrays . asList ( SharedConstants . DEFAULT_SERVER_HANDLER_FACTORIES ) ) ; } public ServerInterfaceManagerFactoryImpl ( ServerInterfaceHandlerFactory < ? , ? > [ ] serverHandlerFactories ) { this . serverHandlerFactories . addAll ( Arrays . asList ( serverHandlerFactories ) ) ; } public ServerInterfaceManagerFactoryImpl ( Map < String , ? > env ) throws IOException { this ( env , SharedConstants . DEFAULT_SERVER_HANDLER_FACTORIES ) ; } public ServerInterfaceManagerFactoryImpl ( Map < String , ? > env , ServerInterfaceHandlerFactory < ? , ? > [ ] serverHandlerFactories ) throws IOException { this . serverHandlerFactories . addAll ( Arrays . asList ( serverHandlerFactories ) ) ; if ( env != null ) { Object accessFile = env . get ( JMXServerJob . ACCESS_FILE_PROPERTY ) ; if ( accessFile != null ) { accessController = new OddjobJMXFileAccessController ( accessFile . toString ( ) ) ; } } } public void addServerHandlerFactories ( ServerInterfaceHandlerFactory < ? , ? > [ ] serverHandlerFactories ) { if ( serverHandlerFactories == null ) { return ; } this . serverHandlerFactories . addAll ( Arrays . asList ( serverHandlerFactories ) ) ; } public ServerInterfaceManager create ( Object target , ServerSideToolkit serverSideToolkit ) { List < ServerInterfaceHandlerFactory < ? , ? > > handlers = new ArrayList < ServerInterfaceHandlerFactory < ? , ? > > ( ) ; for ( Iterator < ServerInterfaceHandlerFactory < ? , ? > > it = serverHandlerFactories . iterator ( ) ; it . hasNext ( ) ; ) { ServerInterfaceHandlerFactory < ? , ? > interfaceHandler = it . next ( ) ; Class < ? > handles = interfaceHandler . interfaceClass ( ) ; if ( handles . isInstance ( target ) ) { handlers . add ( interfaceHandler ) ; } } ServerInterfaceManagerImpl imImpl = new ServerInterfaceManagerImpl ( target , serverSideToolkit , ( ServerInterfaceHandlerFactory [ ] ) handlers . toArray ( new ServerInterfaceHandlerFactory [ ] ) , accessController ) ; return imImpl ; } } package org . oddjob . jmx . server ; import java . net . URL ; import org . oddjob . arooa . ArooaSession ; public class ResourceFactoryProvider implements HandlerFactoryProvider { public static final String ACTION_FILE = "" ; private final ArooaSession session ; public ResourceFactoryProvider ( ArooaSession session ) { this . session = session ; } public ServerInterfaceHandlerFactory < ? , ? > [ ] getHandlerFactories ( ) { URL [ ] urls = session . getArooaDescriptor ( ) . getClassResolver ( ) . getResources ( ACTION_FILE ) ; return new URLFactoryProvider ( urls , session ) . getHandlerFactories ( ) ; } } package org . oddjob . jmx . server ; 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 javax . management . MBeanAttributeInfo ; import javax . management . MBeanConstructorInfo ; import javax . management . MBeanException ; import javax . management . MBeanInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; public class ServerInterfaceManagerImpl implements ServerInterfaceManager { private final MBeanInfo mBeanInfo ; private final Map < ClientHandlerResolver < ? > , MBeanOperationInfo [ ] > clientResolvers = new LinkedHashMap < ClientHandlerResolver < ? > , MBeanOperationInfo [ ] > ( ) ; private final ServerInterfaceHandler [ ] handlers ; private final Map < RemoteOperation < ? > , ServerInterfaceHandler > operations = new LinkedHashMap < RemoteOperation < ? > , ServerInterfaceHandler > ( ) ; private final Map < RemoteOperation < ? > , MBeanOperationInfo > opInfos = new HashMap < RemoteOperation < ? > , MBeanOperationInfo > ( ) ; private final OddjobJMXAccessController accessController ; public ServerInterfaceManagerImpl ( Object target , ServerSideToolkit ojmb , ServerInterfaceHandlerFactory < ? , ? > [ ] serverHandlerFactories ) { this ( target , ojmb , serverHandlerFactories , null ) ; } public ServerInterfaceManagerImpl ( Object target , ServerSideToolkit ojmb , ServerInterfaceHandlerFactory < ? , ? > [ ] serverHandlerFactories , OddjobJMXAccessController accessController ) { List < MBeanAttributeInfo > attributeInfo = new ArrayList < MBeanAttributeInfo > ( ) ; List < MBeanOperationInfo > operationInfo = new ArrayList < MBeanOperationInfo > ( ) ; List < MBeanNotificationInfo > notificationInfo = new ArrayList < MBeanNotificationInfo > ( ) ; handlers = new ServerInterfaceHandler [ serverHandlerFactories . length ] ; for ( int i = ; i < serverHandlerFactories . length ; ++ i ) { ServerInterfaceHandlerFactory < ? , ? > serverHandlerFactory = serverHandlerFactories [ i ] ; ServerInterfaceHandler interfaceHandler = create ( target , ojmb , serverHandlerFactory ) ; handlers [ i ] = interfaceHandler ; attributeInfo . addAll ( Arrays . asList ( serverHandlerFactory . getMBeanAttributeInfo ( ) ) ) ; MBeanOperationInfo [ ] oInfo = serverHandlerFactory . getMBeanOperationInfo ( ) ; clientResolvers . put ( serverHandlerFactory . clientHandlerFactory ( ) , oInfo ) ; for ( MBeanOperationInfo opInfo : oInfo ) { operationInfo . add ( opInfo ) ; RemoteOperation < ? > remoteOp = new OperationInfoOperation ( opInfo ) ; operations . put ( remoteOp , interfaceHandler ) ; opInfos . put ( remoteOp , opInfo ) ; } notificationInfo . addAll ( Arrays . asList ( serverHandlerFactory . getMBeanNotificationInfo ( ) ) ) ; } mBeanInfo = new MBeanInfo ( target . toString ( ) , "" + target . toString ( ) , ( MBeanAttributeInfo [ ] ) attributeInfo . toArray ( new MBeanAttributeInfo [ ] ) , new MBeanConstructorInfo [ ] , ( MBeanOperationInfo [ ] ) operationInfo . toArray ( new MBeanOperationInfo [ ] ) , ( MBeanNotificationInfo [ ] ) notificationInfo . toArray ( new MBeanNotificationInfo [ ] ) ) ; if ( accessController == null ) { this . accessController = new OddjobJMXAccessController ( ) { @ Override public boolean isAccessable ( MBeanOperationInfo opInfo ) { return true ; } } ; } else { this . accessController = accessController ; } } private < S > ServerInterfaceHandler create ( Object target , ServerSideToolkit ojmb , ServerInterfaceHandlerFactory < S , ? > factory ) { Class < S > type = factory . interfaceClass ( ) ; if ( ! type . isInstance ( target ) ) { throw new ClassCastException ( "" + target + "" + type . getName ( ) ) ; } ServerInterfaceHandler interfaceHandler = factory . createServerHandler ( type . cast ( target ) , ojmb ) ; return interfaceHandler ; } public ClientHandlerResolver < ? > [ ] allClientInfo ( ) { List < ClientHandlerResolver < ? > > resolvers = new ArrayList < ClientHandlerResolver < ? > > ( ) ; resolver : for ( Map . Entry < ClientHandlerResolver < ? > , MBeanOperationInfo [ ] > entry : clientResolvers . entrySet ( ) ) { for ( MBeanOperationInfo opInfo : entry . getValue ( ) ) { if ( ! accessController . isAccessable ( opInfo ) ) { continue resolver ; } } resolvers . add ( entry . getKey ( ) ) ; } return resolvers . toArray ( new ClientHandlerResolver [ resolvers . size ( ) ] ) ; } public MBeanInfo getMBeanInfo ( ) { return mBeanInfo ; } public Object invoke ( String actionName , Object [ ] params , String [ ] signature ) throws MBeanException , ReflectionException { RemoteOperation < Object > op = new MBeanOperation ( actionName , signature ) ; ServerInterfaceHandler interfaceHandler = operations . get ( op ) ; if ( interfaceHandler == null ) { throw new IllegalArgumentException ( "" + op + "" ) ; } MBeanOperationInfo opInfo = this . opInfos . get ( op ) ; if ( opInfo == null ) { throw new RuntimeException ( "" + op + "" ) ; } if ( ! accessController . isAccessable ( opInfo ) ) { throw new SecurityException ( "" + op ) ; } return interfaceHandler . invoke ( op , params ) ; } public void destroy ( ) { for ( int i = ; i < handlers . length ; ++ i ) { handlers [ i ] . destroy ( ) ; handlers [ i ] = null ; } } } package org . oddjob . jmx . server ; import java . io . File ; import java . util . HashMap ; import java . util . Map ; import javax . management . remote . rmi . RMIConnectorServer ; import javax . rmi . ssl . SslRMIClientSocketFactory ; import javax . rmi . ssl . SslRMIServerSocketFactory ; import org . oddjob . arooa . types . ValueFactory ; import org . oddjob . jmx . JMXServerJob ; public class SimpleServerSecurity implements ValueFactory < Map < String , ? > > { private File passwordFile ; private File accessFile ; private boolean useSSL ; public Map < String , ? > toValue ( ) { Map < String , Object > env = new HashMap < String , Object > ( ) ; if ( useSSL ) { SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory ( ) ; SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory ( ) ; env . put ( RMIConnectorServer . RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE , csf ) ; env . put ( RMIConnectorServer . RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE , ssf ) ; } if ( passwordFile != null ) { env . put ( "" , passwordFile . getAbsolutePath ( ) ) ; } if ( accessFile != null ) { env . put ( JMXServerJob . ACCESS_FILE_PROPERTY , accessFile . getAbsolutePath ( ) ) ; } return env ; } public File getPasswordFile ( ) { return passwordFile ; } public void setPasswordFile ( File passwordFile ) { this . passwordFile = passwordFile ; } public File getAccessFile ( ) { return accessFile ; } public void setAccessFile ( File accessFile ) { this . accessFile = accessFile ; } public boolean isUseSSL ( ) { return useSSL ; } public void setUseSSL ( boolean useSSL ) { this . useSSL = useSSL ; } } package org . oddjob . jmx . server ; import javax . management . MBeanException ; import javax . management . MBeanInfo ; import javax . management . ReflectionException ; import org . oddjob . jmx . client . ClientHandlerResolver ; public interface ServerInterfaceManager { public ClientHandlerResolver < ? > [ ] allClientInfo ( ) ; public MBeanInfo getMBeanInfo ( ) ; public Object invoke ( String actionName , Object [ ] params , String [ ] signature ) throws MBeanException , ReflectionException ; public void destroy ( ) ; } package org . oddjob . jmx . server ; import org . oddjob . arooa . registry . ServerId ; public class ServerLoopBackException extends Exception { private static final long serialVersionUID = ; private final ServerId serverId ; public ServerLoopBackException ( ServerId serverId ) { super ( "" + serverId ) ; this . serverId = serverId ; } public ServerId getServerId ( ) { return serverId ; } } package org . oddjob . jmx . server ; public interface HandlerFactoryProvider { public ServerInterfaceHandlerFactory < ? , ? > [ ] getHandlerFactories ( ) ; } package org . oddjob . jmx . server ; public class HandlerFactoryBean implements HandlerFactoryProvider { private ServerInterfaceHandlerFactory < ? , ? > [ ] handlerFactories ; public ServerInterfaceHandlerFactory < ? , ? > [ ] getHandlerFactories ( ) { return handlerFactories ; } public void setHandlerFactories ( ServerInterfaceHandlerFactory < ? , ? > [ ] serverHandlers ) { this . handlerFactories = serverHandlers ; } } package org . oddjob . jmx . server ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . HashMap ; import java . util . Map ; import javax . management . MBeanException ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . MethodOperation ; public class ServerAllOperationsHandler < T > implements ServerInterfaceHandler { private final Object target ; private final Map < RemoteOperation < ? > , Method > methods = new HashMap < RemoteOperation < ? > , Method > ( ) ; public ServerAllOperationsHandler ( Class < T > cl , T target ) { this . target = target ; for ( Method m : cl . getMethods ( ) ) { methods . put ( new MethodOperation ( m ) , m ) ; } } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { Method m = methods . get ( operation ) ; if ( m == null ) { throw new ReflectionException ( new NoSuchMethodException ( operation . toString ( ) ) ) ; } try { return m . invoke ( target , params ) ; } catch ( IllegalArgumentException e1 ) { throw new ReflectionException ( e1 , operation . toString ( ) ) ; } catch ( IllegalAccessException e1 ) { throw new ReflectionException ( e1 , operation . toString ( ) ) ; } catch ( InvocationTargetException e1 ) { throw new ReflectionException ( e1 , operation . toString ( ) ) ; } } public void destroy ( ) { } } package org . oddjob . jmx . server ; import java . lang . reflect . Method ; import javax . management . MBeanOperationInfo ; import org . oddjob . jmx . RemoteOperation ; public class JMXOperationFactory { private final Class < ? > cl ; public JMXOperationFactory ( Class < ? > cl ) { this . cl = cl ; } public < T > JMXOperation < T > operationFor ( String methodName , int impact ) { return operationFor ( methodName , null , impact ) ; } public < T > JMXOperation < T > operationFor ( String methodName , String description , int impact , Class < ? > ... args ) { Method method = null ; try { method = cl . getMethod ( methodName , args ) ; } catch ( SecurityException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } return operationFor ( method , description , impact ) ; } public < T > JMXOperation < T > operationFor ( Method method , int impact ) { return operationFor ( method , null , MBeanOperationInfo . UNKNOWN ) ; } @ SuppressWarnings ( "" ) public < T > JMXOperation < T > operationFor ( Method method , String description , int impact ) { if ( description == null ) { description = method . getName ( ) + "" + cl . getName ( ) ; } Class < T > returnType = ( Class < T > ) method . getReturnType ( ) ; JMXOperationPlus < T > op = new JMXOperationPlus < T > ( method . getName ( ) , description , returnType , impact ) ; int i = ; for ( Class < ? > arg : method . getParameterTypes ( ) ) { op = op . addParam ( "" + i ++ , arg , "" ) ; } return op ; } } package org . oddjob . jmx . server ; import javax . management . Notification ; import org . oddjob . jmx . RemoteOddjobBean ; public interface ServerSideToolkit { public void sendNotification ( Notification notification ) ; public Notification createNotification ( String type ) ; public void runSynchronized ( Runnable runnable ) ; public ServerContext getContext ( ) ; public RemoteOddjobBean getRemoteBean ( ) ; public ServerSession getServerSession ( ) ; } package org . oddjob . jmx . server ; import java . io . Serializable ; import org . oddjob . arooa . registry . Address ; import org . oddjob . jmx . client . ClientHandlerResolver ; public class ServerInfo implements Serializable { private static final long serialVersionUID = ; private final Address address ; private final ClientHandlerResolver < ? > [ ] clientResolvers ; public ServerInfo ( Address address , ClientHandlerResolver < ? > [ ] resolvers ) { if ( resolvers == null ) { throw new NullPointerException ( "" ) ; } this . address = address ; this . clientResolvers = resolvers ; } public String getId ( ) { return address . getPath ( ) . getId ( ) ; } public ClientHandlerResolver < ? > [ ] getClientResolvers ( ) { return clientResolvers ; } public Address getAddress ( ) { return address ; } } package org . oddjob . jmx . server ; import java . net . URL ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . xml . XMLConfiguration ; public class URLFactoryProvider implements HandlerFactoryProvider { private final URL [ ] urls ; private final ArooaSession session ; public URLFactoryProvider ( URL [ ] urls , ArooaSession session ) { this . urls = urls ; this . session = session ; } public ServerInterfaceHandlerFactory < ? , ? > [ ] getHandlerFactories ( ) { if ( urls . length == ) { return null ; } AccumulatingFactoryProvider accumulator = new AccumulatingFactoryProvider ( ) ; try { for ( URL url : urls ) { XMLConfiguration config = new XMLConfiguration ( url . toString ( ) , url . openStream ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . parse ( config ) ; HandlerFactoryProvider provider = ( HandlerFactoryProvider ) parser . getRoot ( ) ; accumulator . addProvider ( provider ) ; } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return accumulator . getHandlerFactories ( ) ; } } package org . oddjob . jmx . server ; import java . io . FileInputStream ; import java . io . IOException ; import java . security . AccessControlContext ; import java . security . AccessController ; import java . security . Principal ; import java . security . PrivilegedAction ; import java . util . Collection ; import java . util . Iterator ; import java . util . Properties ; import java . util . Set ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanServer ; import javax . security . auth . Subject ; public class OddjobJMXFileAccessController implements OddjobJMXAccessController { public static final String READONLY = "" ; public static final String READWRITE = "" ; public OddjobJMXFileAccessController ( String accessFileName ) throws IOException { super ( ) ; this . accessFileName = accessFileName ; props = propertiesFromFile ( accessFileName ) ; checkValues ( props ) ; } public OddjobJMXFileAccessController ( Properties accessFileProps ) throws IOException { super ( ) ; if ( accessFileProps == null ) throw new IllegalArgumentException ( "" ) ; originalProps = accessFileProps ; props = ( Properties ) accessFileProps . clone ( ) ; checkValues ( props ) ; } @ Override public boolean isAccessable ( MBeanOperationInfo opInfo ) { if ( opInfo . getImpact ( ) == MBeanOperationInfo . INFO ) { return checkAccessLevel ( READONLY ) ; } else { return checkAccessLevel ( READWRITE ) ; } } public void refresh ( ) throws IOException { synchronized ( props ) { if ( accessFileName == null ) props = ( Properties ) originalProps . clone ( ) ; else props = propertiesFromFile ( accessFileName ) ; checkValues ( props ) ; } } private static Properties propertiesFromFile ( String fname ) throws IOException { FileInputStream fin = new FileInputStream ( fname ) ; Properties p = new Properties ( ) ; p . load ( fin ) ; fin . close ( ) ; return p ; } private boolean checkAccessLevel ( String accessLevel ) { final AccessControlContext acc = AccessController . getContext ( ) ; final Subject s = ( Subject ) AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { return Subject . getSubject ( acc ) ; } } ) ; if ( s == null ) return true ; final Set < Principal > principals = s . getPrincipals ( ) ; for ( Iterator < Principal > i = principals . iterator ( ) ; i . hasNext ( ) ; ) { final Principal p = ( Principal ) i . next ( ) ; String grantedAccessLevel ; synchronized ( props ) { grantedAccessLevel = props . getProperty ( p . getName ( ) ) ; } if ( grantedAccessLevel != null ) { if ( accessLevel . equals ( READONLY ) && ( grantedAccessLevel . equals ( READONLY ) || grantedAccessLevel . equals ( READWRITE ) ) ) return true ; if ( accessLevel . equals ( READWRITE ) && grantedAccessLevel . equals ( READWRITE ) ) return true ; } } return false ; } private void checkValues ( Properties props ) { Collection < Object > c = props . values ( ) ; for ( Iterator < Object > i = c . iterator ( ) ; i . hasNext ( ) ; ) { final String accessLevel = ( String ) i . next ( ) ; if ( ! accessLevel . equals ( READONLY ) && ! accessLevel . equals ( READWRITE ) ) { throw new IllegalArgumentException ( "" + accessLevel + "" ) ; } } } private Properties props ; private Properties originalProps ; private String accessFileName ; } package org . oddjob . jmx . server ; import org . oddjob . jmx . RemoteOperation ; public class MBeanOperation extends RemoteOperation < Object > { private final String actionName ; private final String [ ] signature ; public MBeanOperation ( String actionName , String [ ] signature ) { this . actionName = actionName ; this . signature = signature ; } public String getActionName ( ) { return actionName ; } public String [ ] getSignature ( ) { return signature ; } } package org . oddjob . jmx . general ; import javax . management . MBeanServerConnection ; import org . oddjob . arooa . ArooaSession ; public class SimpleMBeanSession implements MBeanSession { private final ArooaSession arooaSession ; private final MBeanCache mBeanCache ; public SimpleMBeanSession ( ArooaSession arooaSession , MBeanServerConnection mBeanServer ) { this . arooaSession = arooaSession ; this . mBeanCache = new MBeanCacheMap ( mBeanServer , getArooaSession ( ) . getArooaDescriptor ( ) . getClassResolver ( ) ) ; } @ Override public ArooaSession getArooaSession ( ) { return arooaSession ; } @ Override public MBeanCache getMBeanCache ( ) { return mBeanCache ; } } package org . oddjob . jmx . general ; import org . oddjob . arooa . ArooaSession ; public interface MBeanSession { public ArooaSession getArooaSession ( ) ; public MBeanCache getMBeanCache ( ) ; } package org . oddjob . jmx . general ; import java . text . ParseException ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class MBeanDirectoryPathParser { public static final String QUOTE = "" ; public static final String DELIMITER = Pattern . quote ( "" ) ; private final static Pattern pattern = Pattern . compile ( "" + QUOTE + "" + QUOTE + "" + DELIMITER + "" ) ; private String name ; private String property ; public void parse ( String expression ) throws ParseException { name = null ; property = null ; Matcher matcher = pattern . matcher ( expression ) ; if ( ! matcher . matches ( ) ) { throw new ParseException ( "" + expression , ) ; } name = matcher . group ( ) ; if ( name == null ) { name = matcher . group ( ) ; } property = matcher . group ( ) ; } public String getName ( ) { return name ; } public String getProperty ( ) { return property ; } } package org . oddjob . jmx . general ; import org . apache . commons . beanutils . DynaBean ; import org . oddjob . jmx . client . Destroyable ; import org . oddjob . script . Invoker ; public interface MBeanNode extends DynaBean , Invoker , Destroyable { public void initialise ( ) ; } package org . oddjob . jmx . general ; import java . io . IOException ; import java . util . HashMap ; import java . util . Map ; import java . util . Set ; import javax . management . InstanceNotFoundException ; import javax . management . IntrospectionException ; import javax . management . MBeanServerConnection ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import org . oddjob . arooa . ClassResolver ; public class MBeanCacheMap implements MBeanCache { private final MBeanServerConnection mBeanServer ; private final ClassResolver classRresolver ; private final Map < ObjectName , MBeanNode > beans = new HashMap < ObjectName , MBeanNode > ( ) ; public MBeanCacheMap ( MBeanServerConnection mBeanServer , ClassResolver classResolver ) { this . mBeanServer = mBeanServer ; this . classRresolver = classResolver ; } public MBeanNode findBean ( ObjectName objectName ) throws IntrospectionException , InstanceNotFoundException , ReflectionException , IOException { MBeanNode bean = beans . get ( objectName ) ; if ( bean == null ) { MBeanNode [ ] beans = findBeans ( objectName ) ; if ( beans . length == ) { throw new IllegalArgumentException ( "" + objectName ) ; } if ( beans . length > ) { throw new IllegalArgumentException ( "" + objectName ) ; } bean = beans [ ] ; } return bean ; } public MBeanNode [ ] findBeans ( ObjectName objectName ) throws IntrospectionException , InstanceNotFoundException , ReflectionException , IOException { Set < ObjectName > names = mBeanServer . queryNames ( objectName , null ) ; MBeanNode [ ] wrappers = new MBeanNode [ names . size ( ) ] ; int i = ; for ( ObjectName name : names ) { MBeanNode wrapper = beans . get ( name ) ; if ( wrapper == null ) { wrapper = new SimpleMBeanNode ( name , mBeanServer , classRresolver ) ; beans . put ( name , wrapper ) ; } wrappers [ i ++ ] = wrapper ; } return wrappers ; } } package org . oddjob . jmx . general ; import java . util . concurrent . atomic . AtomicInteger ; import javax . management . ObjectName ; import javax . swing . ImageIcon ; import org . apache . log4j . Logger ; import org . oddjob . Iconic ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . logging . LogEnabled ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class SimpleDomainNode implements DomainNode , Iconic , LogEnabled { private static final AtomicInteger instanceCount = new AtomicInteger ( ) ; private final static ImageIcon icon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; private final Logger logger = Logger . getLogger ( getClass ( ) . getName ( ) + "" + instanceCount . incrementAndGet ( ) ) ; private final String domain ; private final MBeanSession mBeanSession ; private final ChildHelper < MBeanNode > childHelper = new ChildHelper < MBeanNode > ( this ) ; public SimpleDomainNode ( String domain , MBeanSession mBeanSession ) { this . domain = domain ; this . mBeanSession = mBeanSession ; } @ Override public String loggerName ( ) { return logger . getName ( ) ; } @ Override public void initialise ( ) { logger . info ( "" + domain ) ; MBeanCache cache = mBeanSession . getMBeanCache ( ) ; try { MBeanNode [ ] children = cache . findBeans ( new ObjectName ( domain + "" ) ) ; for ( MBeanNode child : children ) { childHelper . addChild ( child ) ; child . initialise ( ) ; } } catch ( Exception e ) { logger . error ( "" , e ) ; } } @ Override public void addStructuralListener ( StructuralListener listener ) { childHelper . addStructuralListener ( listener ) ; } @ Override public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } public ImageIcon iconForId ( String iconId ) { return icon ; } public void addIconListener ( IconListener listener ) { listener . iconEvent ( new IconEvent ( this , "" ) ) ; } public void removeIconListener ( IconListener listener ) { } public void destroy ( ) { while ( childHelper . size ( ) > ) { MBeanNode node = childHelper . removeChildAt ( ) ; node . destroy ( ) ; } } @ Override public String toString ( ) { return domain ; } } package org . oddjob . jmx . general ; import java . awt . Image ; import java . io . IOException ; import java . io . Serializable ; import java . util . Arrays ; import java . util . HashMap ; import java . util . LinkedHashMap ; import java . util . Map ; import java . util . concurrent . atomic . AtomicInteger ; import javax . management . Attribute ; import javax . management . InstanceNotFoundException ; import javax . management . IntrospectionException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanInfo ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanParameterInfo ; import javax . management . MBeanServerConnection ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import javax . management . openmbean . CompositeData ; import javax . swing . ImageIcon ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . DynaProperty ; import org . apache . log4j . Logger ; import org . oddjob . Describeable ; import org . oddjob . Iconic ; import org . oddjob . arooa . ClassResolver ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconListener ; import org . oddjob . logging . LogEnabled ; import org . oddjob . script . InvokerArguments ; public class SimpleMBeanNode implements MBeanNode , Describeable , LogEnabled , Iconic { private static final AtomicInteger instanceCount = new AtomicInteger ( ) ; private static final ImageIcon icon = new ImageIcon ( new ImageIcon ( SimpleDomainNode . class . getResource ( "" ) ) . getImage ( ) . getScaledInstance ( , , Image . SCALE_SMOOTH ) ) ; private final Logger logger = Logger . getLogger ( getClass ( ) . getName ( ) + "" + instanceCount . incrementAndGet ( ) ) ; private final ObjectName objectName ; private final MBeanServerConnection mBeanServer ; private final ClassResolver classResolver ; private final MBeanInfo info ; private final ThisDynaClass dynaClass ; public SimpleMBeanNode ( ObjectName objectName , MBeanServerConnection mBeanServer , ClassResolver classResolver ) throws IntrospectionException , InstanceNotFoundException , ReflectionException , IOException { this . objectName = objectName ; this . mBeanServer = mBeanServer ; this . classResolver = classResolver ; this . info = mBeanServer . getMBeanInfo ( objectName ) ; dynaClass = new ThisDynaClass ( info . getAttributes ( ) ) ; } @ Override public void initialise ( ) { logger . info ( "" + objectName ) ; logger . info ( "" ) ; MBeanAttributeInfo [ ] attributeInfo = info . getAttributes ( ) ; for ( MBeanAttributeInfo attr : attributeInfo ) { logger . info ( "" + attr . getName ( ) + "" + attr . getType ( ) ) ; } logger . info ( "" ) ; MBeanOperationInfo [ ] operationInfo = info . getOperations ( ) ; for ( MBeanOperationInfo op : operationInfo ) { StringBuilder params = new StringBuilder ( ) ; for ( MBeanParameterInfo param : op . getSignature ( ) ) { if ( params . length ( ) > ) { params . append ( "" ) ; } params . append ( param . getType ( ) ) ; } logger . info ( "" + op . getName ( ) + "" + params . toString ( ) + "" + op . getReturnType ( ) ) ; } } @ Override public String loggerName ( ) { return logger . getName ( ) ; } @ Override public Object invoke ( String name , InvokerArguments args ) { MBeanOperationInfo [ ] opInfos = info . getOperations ( ) ; MBeanOperationInfo match = null ; for ( MBeanOperationInfo info : opInfos ) { if ( name . equals ( info . getName ( ) ) && args . size ( ) == info . getSignature ( ) . length ) { if ( match != null ) { throw new IllegalArgumentException ( "" + name + "" + args . size ( ) + "" ) ; } match = info ; } } if ( match == null ) { throw new IllegalArgumentException ( "" + name + "" + args . size ( ) + "" ) ; } MBeanParameterInfo [ ] paramInfo = match . getSignature ( ) ; String [ ] signature = new String [ paramInfo . length ] ; Object [ ] converted = new Object [ signature . length ] ; for ( int i = ; i < signature . length ; ++ i ) { signature [ i ] = paramInfo [ i ] . getType ( ) ; Class < ? > type = classResolver . findClass ( signature [ i ] ) ; if ( type == null ) { throw new RuntimeException ( "" + signature [ i ] + "" + i ) ; } try { converted [ i ] = args . getArgument ( i , type ) ; } catch ( ArooaConversionException e ) { throw new IllegalArgumentException ( "" + i , e ) ; } } try { logger . info ( "" + name + "" + Arrays . toString ( converted ) ) ; Object result = mBeanServer . invoke ( objectName , name , converted , signature ) ; logger . info ( "" + name + "" + result ) ; return result ; } catch ( Exception e ) { logger . warn ( "" + name + "" + Arrays . toString ( converted ) ) ; throw new RuntimeException ( e ) ; } } private static final String MBEAN_ICON = "" ; @ Override public void addIconListener ( IconListener listener ) { listener . iconEvent ( new IconEvent ( this , MBEAN_ICON ) ) ; } @ Override public ImageIcon iconForId ( String id ) { return icon ; } @ Override public void removeIconListener ( IconListener listener ) { } @ Override public String toString ( ) { return objectName . toString ( ) ; } @ Override public boolean contains ( String arg0 , String arg1 ) { return false ; } @ Override public Object get ( String name ) { try { Object result = mBeanServer . getAttribute ( objectName , name ) ; if ( result instanceof CompositeData ) { return new CompositeDataDynaBean ( ( CompositeData ) result ) ; } else { return result ; } } catch ( Exception e ) { throw new RuntimeException ( "" + name , e ) ; } } @ Override public Object get ( String arg0 , int arg1 ) { throw new RuntimeException ( "" ) ; } @ Override public Object get ( String arg0 , String arg1 ) { throw new RuntimeException ( "" ) ; } @ Override public DynaClass getDynaClass ( ) { return dynaClass ; } @ Override public void remove ( String arg0 , String arg1 ) { throw new RuntimeException ( "" ) ; } @ Override public void set ( String name , Object value ) { try { logger . info ( "" + name + "" + value ) ; mBeanServer . setAttribute ( objectName , new Attribute ( name , value ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "" + name , e ) ; } } @ Override public void set ( String arg0 , int arg1 , Object arg2 ) { throw new RuntimeException ( "" ) ; } @ Override public void set ( String arg0 , String arg1 , Object arg2 ) { throw new RuntimeException ( "" ) ; } @ Override public Map < String , String > describe ( ) { Map < String , String > description = new LinkedHashMap < String , String > ( ) ; DynaProperty [ ] props = dynaClass . getDynaProperties ( ) ; for ( DynaProperty prop : props ) { Object value = get ( prop . getName ( ) ) ; description . put ( prop . getName ( ) , value == null ? null : value . toString ( ) ) ; } return description ; } @ Override public void destroy ( ) { } private class ThisDynaClass implements Serializable , DynaClass { private static final long serialVersionUID = ; private final AttributeDynaProperty [ ] properties ; private final Map < String , AttributeDynaProperty > map = new HashMap < String , AttributeDynaProperty > ( ) ; public ThisDynaClass ( MBeanAttributeInfo [ ] attributes ) { this . properties = new AttributeDynaProperty [ attributes . length ] ; for ( int i = ; i < properties . length ; ++ i ) { MBeanAttributeInfo info = attributes [ i ] ; AttributeDynaProperty property = new AttributeDynaProperty ( info ) ; properties [ i ] = property ; map . put ( property . getName ( ) , property ) ; } } @ Override public DynaProperty [ ] getDynaProperties ( ) { return properties ; } @ Override public DynaProperty getDynaProperty ( String name ) { return map . get ( name ) ; } @ Override public String getName ( ) { return SimpleMBeanNode . this . toString ( ) ; } @ Override public DynaBean newInstance ( ) throws IllegalAccessException , InstantiationException { throw new InstantiationException ( "" + getName ( ) ) ; } } private class AttributeDynaProperty extends DynaProperty { private static final long serialVersionUID = ; private final MBeanAttributeInfo info ; public AttributeDynaProperty ( MBeanAttributeInfo info ) { super ( info . getName ( ) ) ; this . info = info ; } @ SuppressWarnings ( "" ) @ Override public Class getType ( ) { return classResolver . findClass ( info . getType ( ) ) ; } } } package org . oddjob . jmx . general ; import java . text . ParseException ; import javax . management . ObjectName ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . registry . BeanDirectory ; public class MBeanDirectory implements BeanDirectory { private final PropertyAccessor accessor ; private final ArooaConverter converter ; private final MBeanCache cache ; public MBeanDirectory ( MBeanSession session ) { ArooaTools tools = session . getArooaSession ( ) . getTools ( ) ; this . converter = tools . getArooaConverter ( ) ; this . accessor = tools . getPropertyAccessor ( ) . accessorWithConversions ( converter ) ; this . cache = session . getMBeanCache ( ) ; } private Object mBeanLookup ( MBeanDirectoryPathParser parser , String path ) throws ArooaPropertyException { try { parser . parse ( path ) ; } catch ( ParseException e ) { throw new IllegalArgumentException ( "" + path , e ) ; } if ( parser . getName ( ) == null ) { return null ; } try { ObjectName objectName = new ObjectName ( parser . getName ( ) ) ; return cache . findBean ( objectName ) ; } catch ( Exception e ) { throw new ArooaPropertyException ( path , "" , e ) ; } } @ Override public Object lookup ( String path ) throws ArooaPropertyException { MBeanDirectoryPathParser parser = new MBeanDirectoryPathParser ( ) ; Object bean = mBeanLookup ( parser , path ) ; if ( parser . getProperty ( ) == null ) { return bean ; } return accessor . getProperty ( bean , parser . getProperty ( ) ) ; } @ Override public < T > T lookup ( String path , Class < T > required ) throws ArooaPropertyException , ArooaConversionException { MBeanDirectoryPathParser parser = new MBeanDirectoryPathParser ( ) ; Object bean = mBeanLookup ( parser , path ) ; if ( parser . getProperty ( ) == null ) { return converter . convert ( bean , required ) ; } return accessor . getProperty ( bean , parser . getProperty ( ) , required ) ; } @ Override public String getIdFor ( Object bean ) { return null ; } @ Override public < T > Iterable < T > getAllByType ( Class < T > type ) { throw new UnsupportedOperationException ( "" ) ; } } package org . oddjob . jmx . general ; import java . io . Serializable ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map ; import java . util . Set ; import javax . management . openmbean . CompositeData ; import javax . management . openmbean . CompositeType ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . DynaProperty ; public class CompositeDataDynaBean implements DynaBean { private final CompositeData data ; private final ThisDynaClass dynaClass ; public CompositeDataDynaBean ( CompositeData data ) { this . data = data ; this . dynaClass = new ThisDynaClass ( data . getCompositeType ( ) ) ; } @ Override public boolean contains ( String arg0 , String arg1 ) { return false ; } @ Override public Object get ( String name ) { Object result = data . get ( name ) ; if ( result instanceof CompositeData ) { return new CompositeDataDynaBean ( ( CompositeData ) result ) ; } else { return result ; } } @ Override public Object get ( String arg0 , int arg1 ) { throw new RuntimeException ( "" ) ; } @ Override public Object get ( String arg0 , String arg1 ) { throw new RuntimeException ( "" ) ; } @ Override public DynaClass getDynaClass ( ) { return dynaClass ; } @ Override public void remove ( String arg0 , String arg1 ) { throw new RuntimeException ( "" ) ; } @ Override public void set ( String name , Object value ) { throw new RuntimeException ( "" + name + "" ) ; } @ Override public void set ( String arg0 , int arg1 , Object arg2 ) { throw new RuntimeException ( "" ) ; } @ Override public void set ( String arg0 , String arg1 , Object arg2 ) { throw new RuntimeException ( "" ) ; } @ Override public String toString ( ) { return "" + Arrays . toString ( dynaClass . propertyNames ) ; } private class ThisDynaClass implements Serializable , DynaClass { private static final long serialVersionUID = ; private final String [ ] propertyNames ; private final DynaProperty [ ] properties ; private final Map < String , DynaProperty > map = new HashMap < String , DynaProperty > ( ) ; public ThisDynaClass ( CompositeType type ) { Set < String > keySet = type . keySet ( ) ; this . propertyNames = new String [ keySet . size ( ) ] ; this . properties = new DynaProperty [ keySet . size ( ) ] ; int i = ; for ( String key : keySet ) { propertyNames [ i ] = key ; DynaProperty property = new DynaProperty ( key , Object . class ) ; properties [ i ] = property ; map . put ( property . getName ( ) , property ) ; ++ i ; } } @ Override public DynaProperty [ ] getDynaProperties ( ) { return properties ; } @ Override public DynaProperty getDynaProperty ( String name ) { return map . get ( name ) ; } @ Override public String getName ( ) { return CompositeDataDynaBean . this . toString ( ) ; } @ Override public DynaBean newInstance ( ) throws IllegalAccessException , InstantiationException { throw new InstantiationException ( "" + getName ( ) ) ; } } } package org . oddjob . jmx . general ; import java . io . IOException ; import javax . management . InstanceNotFoundException ; import javax . management . IntrospectionException ; import javax . management . ObjectName ; import javax . management . ReflectionException ; public interface MBeanCache { public MBeanNode findBean ( ObjectName objectName ) throws IntrospectionException , InstanceNotFoundException , ReflectionException , IOException ; public MBeanNode [ ] findBeans ( ObjectName objectName ) throws IntrospectionException , InstanceNotFoundException , ReflectionException , IOException ; } package org . oddjob . jmx . general ; import org . oddjob . Structural ; import org . oddjob . jmx . client . Destroyable ; public interface DomainNode extends Structural , Destroyable { public void initialise ( ) ; } package org . oddjob . jmx ; public abstract class RemoteOperation < T > { abstract public String getActionName ( ) ; abstract public String [ ] getSignature ( ) ; @ Override public boolean equals ( Object obj ) { if ( obj == this ) { return true ; } if ( ! ( obj instanceof RemoteOperation < ? > ) ) { return false ; } RemoteOperation < ? > other = ( RemoteOperation < ? > ) obj ; if ( ! getActionName ( ) . equals ( other . getActionName ( ) ) ) { return false ; } String [ ] signature = getSignature ( ) ; String [ ] otherSig = other . getSignature ( ) ; if ( signature . length != otherSig . length ) { return false ; } for ( int i = ; i < signature . length ; ++ i ) { if ( ! signature [ i ] . equals ( otherSig [ i ] ) ) { return false ; } } return true ; } @ Override public int hashCode ( ) { return getActionName ( ) . hashCode ( ) + getSignature ( ) . length ; } public String toString ( ) { StringBuffer buf = new StringBuffer ( ) ; String [ ] sig = getSignature ( ) ; buf . append ( '' ) ; for ( int i = ; i < sig . length ; ++ i ) { if ( i > ) { buf . append ( "" ) ; } buf . append ( sig [ i ] ) ; } buf . append ( '' ) ; return "" + getActionName ( ) + buf . toString ( ) ; } } package org . oddjob . jmx ; import java . lang . reflect . Method ; public class MethodInvocationException extends Exception { private static final long serialVersionUID = ; public MethodInvocationException ( String componentName , Method method , Object [ ] args , Throwable cause ) { super ( "" + method . toString ( ) + "" + componentName + "" + args ( args ) , cause ) ; } static String args ( Object [ ] args ) { StringBuffer buf = new StringBuffer ( ) ; buf . append ( '' ) ; for ( int i = ; i < args . length ; ++ i ) { if ( i > ) { buf . append ( "" ) ; } buf . append ( '' ) ; buf . append ( args [ i ] == null ? "" : args [ i ] ) ; buf . append ( '' ) ; } buf . append ( '' ) ; return buf . toString ( ) ; } } package org . oddjob . jmx ; import org . oddjob . jmx . handlers . DescribeableHandlerFactory ; import org . oddjob . jmx . handlers . DynaBeanHandlerFactory ; import org . oddjob . jmx . handlers . LogEnabledHandlerFactory ; import org . oddjob . jmx . handlers . LogPollableHandlerFactory ; import org . oddjob . jmx . handlers . ObjectInterfaceHandlerFactory ; import org . oddjob . jmx . handlers . RemoteOddjobHandlerFactory ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; public class SharedConstants { public static final String RETRIEVE_LOG_EVENTS_METHOD = "" ; public static final String RETRIEVE_CONSOLE_EVENTS_METHOD = "" ; public static final String TO_STRING_METHOD = "" ; public static final String GET_LOGGER_METHOD = "" ; public static final ServerInterfaceHandlerFactory < ? , ? > [ ] DEFAULT_SERVER_HANDLER_FACTORIES = { new DynaBeanHandlerFactory ( ) , new LogEnabledHandlerFactory ( ) , new LogPollableHandlerFactory ( ) , new ObjectInterfaceHandlerFactory ( ) , new DescribeableHandlerFactory ( ) , new RemoteOddjobHandlerFactory ( ) , } ; } package org . oddjob . jmx . handlers ; import java . lang . reflect . UndeclaredThrowableException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . SharedConstants ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . LogPollable ; import org . oddjob . jmx . client . SimpleHandlerResolver ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . LogArchiverHelper ; import org . oddjob . jmx . server . ServerContext ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; import org . oddjob . logging . LogEvent ; public class LogPollableHandlerFactory implements ServerInterfaceHandlerFactory < Object , LogPollable > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; private static final JMXOperationPlus < String > CONSOLE_ID = new JMXOperationPlus < String > ( "" , "" , String . class , MBeanOperationInfo . INFO ) ; private static final JMXOperationPlus < String > URL = new JMXOperationPlus < String > ( "" , "" , String . class , MBeanOperationInfo . INFO ) ; private static final JMXOperationPlus < LogEvent [ ] > RETRIEVE_CONSOLE_EVENTS = new JMXOperationPlus < LogEvent [ ] > ( SharedConstants . RETRIEVE_CONSOLE_EVENTS_METHOD , "" , LogEvent [ ] . class , MBeanOperationInfo . INFO ) . addParam ( "" , Long . TYPE , "" ) . addParam ( "" , Integer . TYPE , "" ) ; private static final JMXOperationPlus < LogEvent [ ] > RETRIEVE_LOG_EVENTS = new JMXOperationPlus < LogEvent [ ] > ( SharedConstants . RETRIEVE_LOG_EVENTS_METHOD , "" , LogEvent [ ] . class , MBeanOperationInfo . INFO ) . addParam ( "" , Long . TYPE , "" ) . addParam ( "" , Integer . TYPE , "" ) ; public Class < Object > interfaceClass ( ) { return Object . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { CONSOLE_ID . getOpInfo ( ) , URL . getOpInfo ( ) , RETRIEVE_CONSOLE_EVENTS . getOpInfo ( ) , RETRIEVE_LOG_EVENTS . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Object target , ServerSideToolkit ojmb ) { return new ServerLogPollableHandler ( target , ojmb ) ; } public ClientHandlerResolver < LogPollable > clientHandlerFactory ( ) { return new SimpleHandlerResolver < LogPollable > ( ClientLogPollableHandlerFactory . class . getName ( ) , VERSION ) ; } public static class ClientLogPollableHandlerFactory implements ClientInterfaceHandlerFactory < LogPollable > { public Class < LogPollable > interfaceClass ( ) { return LogPollable . class ; } public HandlerVersion getVersion ( ) { return VERSION ; } public LogPollable createClientHandler ( LogPollable ignored , ClientSideToolkit toolkit ) { return new ClientLogPollableHandler ( toolkit ) ; } } static class ClientLogPollableHandler implements LogPollable { private final String consoleId ; private final String url ; private final ClientSideToolkit toolkit ; ClientLogPollableHandler ( ClientSideToolkit toolkit ) { this . toolkit = toolkit ; try { consoleId = ( String ) toolkit . invoke ( CONSOLE_ID ) ; url = ( String ) toolkit . invoke ( URL ) ; } catch ( Throwable t ) { throw new UndeclaredThrowableException ( t ) ; } } public String consoleId ( ) { return consoleId ; } public String url ( ) { return url ; } public LogEvent [ ] retrieveConsoleEvents ( long from , int max ) { try { return toolkit . invoke ( RETRIEVE_CONSOLE_EVENTS , new Object [ ] { new Long ( from ) , new Integer ( max ) } ) ; } catch ( Throwable t ) { throw new UndeclaredThrowableException ( t ) ; } } public LogEvent [ ] retrieveLogEvents ( long from , int max ) { try { return toolkit . invoke ( RETRIEVE_LOG_EVENTS , new Object [ ] { new Long ( from ) , new Integer ( max ) } ) ; } catch ( Throwable t ) { throw new UndeclaredThrowableException ( t ) ; } } } class ServerLogPollableHandler implements ServerInterfaceHandler { private final Object node ; private final ServerContext srvcon ; ServerLogPollableHandler ( Object object , ServerSideToolkit ojmb ) { this . node = object ; this . srvcon = ojmb . getContext ( ) ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( CONSOLE_ID . equals ( operation ) ) { return LogArchiverHelper . consoleId ( node , srvcon . getConsoleArchiver ( ) ) ; } else if ( URL . equals ( operation ) ) { return srvcon . getServerId ( ) . toString ( ) ; } else if ( RETRIEVE_LOG_EVENTS . equals ( operation ) ) { return LogArchiverHelper . retrieveLogEvents ( node , srvcon . getLogArchiver ( ) , ( Long ) params [ ] , ( Integer ) params [ ] ) ; } else if ( RETRIEVE_CONSOLE_EVENTS . equals ( operation ) ) { return LogArchiverHelper . retrieveConsoleEvents ( node , srvcon . getConsoleArchiver ( ) , ( Long ) params [ ] , ( Integer ) params [ ] ) ; } else { throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } } public void destroy ( ) { } } } package org . oddjob . jmx . handlers ; import java . io . Serializable ; import java . lang . reflect . UndeclaredThrowableException ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . management . ReflectionException ; import javax . swing . ImageIcon ; import org . oddjob . Iconic ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . SimpleHandlerResolver ; import org . oddjob . jmx . client . Synchronizer ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class IconicHandlerFactory implements ServerInterfaceHandlerFactory < Iconic , Iconic > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; public static final String ICON_CHANGED_NOTIF_TYPE = "" ; static final JMXOperationPlus < Notification [ ] > SYNCHRONIZE = new JMXOperationPlus < Notification [ ] > ( "" , "" , Notification [ ] . class , MBeanOperationInfo . INFO ) ; static final JMXOperationPlus < ImageIcon > ICON_FOR = new JMXOperationPlus < ImageIcon > ( "" , "" , ImageIcon . class , MBeanOperationInfo . INFO ) . addParam ( "" , String . class , "" ) ; public Class < Iconic > interfaceClass ( ) { return Iconic . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { SYNCHRONIZE . getOpInfo ( ) , ICON_FOR . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] { new MBeanNotificationInfo ( new String [ ] { ICON_CHANGED_NOTIF_TYPE } , Notification . class . getName ( ) , "" ) } ; } public ServerInterfaceHandler createServerHandler ( Iconic iconic , ServerSideToolkit ojmb ) { ServerIconicHelper iconicHelper = new ServerIconicHelper ( iconic , ojmb ) ; iconic . addIconListener ( iconicHelper ) ; return iconicHelper ; } public ClientHandlerResolver < Iconic > clientHandlerFactory ( ) { return new SimpleHandlerResolver < Iconic > ( ClientIconicHandlerFactory . class . getName ( ) , VERSION ) ; } public static class ClientIconicHandlerFactory implements ClientInterfaceHandlerFactory < Iconic > { public Class < Iconic > interfaceClass ( ) { return Iconic . class ; } public HandlerVersion getVersion ( ) { return VERSION ; } public Iconic createClientHandler ( Iconic proxy , ClientSideToolkit toolkit ) { return new ClientIconicHandler ( proxy , toolkit ) ; } } static class ClientIconicHandler implements Iconic { private IconEvent lastEvent ; private final List < IconListener > listeners = new ArrayList < IconListener > ( ) ; private final Iconic owner ; private final ClientSideToolkit toolkit ; private Synchronizer synchronizer ; ClientIconicHandler ( Iconic proxy , ClientSideToolkit toolkit ) { this . owner = proxy ; this . toolkit = toolkit ; lastEvent = new IconEvent ( owner , IconHelper . NULL ) ; } public ImageIcon iconForId ( String id ) { try { return toolkit . invoke ( ICON_FOR , new Object [ ] { id } ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } void iconEvent ( IconData event ) { IconEvent iconEvent = new IconEvent ( owner , event . getIconId ( ) ) ; lastEvent = iconEvent ; synchronized ( listeners ) { for ( Iterator < IconListener > it = listeners . iterator ( ) ; it . hasNext ( ) ; ) { it . next ( ) . iconEvent ( iconEvent ) ; } } } public void addIconListener ( IconListener listener ) { synchronized ( this ) { if ( synchronizer == null ) { synchronizer = new Synchronizer ( new NotificationListener ( ) { public void handleNotification ( Notification notification , Object arg1 ) { IconData ie = ( IconData ) notification . getUserData ( ) ; iconEvent ( ie ) ; } } ) ; toolkit . registerNotificationListener ( ICON_CHANGED_NOTIF_TYPE , synchronizer ) ; Notification [ ] lastNotifications = null ; try { lastNotifications = toolkit . invoke ( SYNCHRONIZE ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } synchronizer . synchronize ( lastNotifications ) ; } IconEvent nowEvent = lastEvent ; synchronized ( listeners ) { listener . iconEvent ( nowEvent ) ; listeners . add ( listener ) ; } } } public void removeIconListener ( IconListener listener ) { synchronized ( this ) { listeners . remove ( listener ) ; if ( listeners . size ( ) == ) { toolkit . removeNotificationListener ( ICON_CHANGED_NOTIF_TYPE , synchronizer ) ; synchronizer = null ; } } } } class ServerIconicHelper implements IconListener , ServerInterfaceHandler { private final Iconic iconic ; private final ServerSideToolkit toolkit ; private Notification lastNotification ; ServerIconicHelper ( Iconic iconic , ServerSideToolkit ojmb ) { this . iconic = iconic ; this . toolkit = ojmb ; } public void iconEvent ( final IconEvent event ) { toolkit . runSynchronized ( new Runnable ( ) { public void run ( ) { IconData newEvent = new IconData ( event . getIconId ( ) ) ; Notification notification = toolkit . createNotification ( ICON_CHANGED_NOTIF_TYPE ) ; notification . setUserData ( newEvent ) ; toolkit . sendNotification ( notification ) ; lastNotification = notification ; } } ) ; } public Notification [ ] getLastNotifications ( ) { return null ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( ICON_FOR . equals ( operation ) ) { return iconic . iconForId ( ( String ) params [ ] ) ; } if ( SYNCHRONIZE . equals ( operation ) ) { return new Notification [ ] { lastNotification } ; } throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } public void destroy ( ) { iconic . removeIconListener ( this ) ; } } public static class IconData implements Serializable { private static final long serialVersionUID = ; final private String id ; public IconData ( String iconId ) { this . id = iconId ; } public String getIconId ( ) { return id ; } } } package org . oddjob . jmx . handlers ; import java . io . Serializable ; import java . lang . reflect . UndeclaredThrowableException ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import javax . management . InstanceNotFoundException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . management . ReflectionException ; import org . oddjob . Stateful ; import org . oddjob . framework . JobDestroyedException ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientDestroyed ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . Destroyable ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . SimpleHandlerResolver ; import org . oddjob . jmx . client . Synchronizer ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; import org . oddjob . state . JobState ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class StatefulHandlerFactory implements ServerInterfaceHandlerFactory < Stateful , Stateful > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; public static final String STATE_CHANGE_NOTIF_TYPE = "" ; static final JMXOperationPlus < Notification [ ] > SYNCHRONIZE = new JMXOperationPlus < Notification [ ] > ( "" , "" , Notification [ ] . class , MBeanOperationInfo . INFO ) ; public Class < Stateful > interfaceClass ( ) { return Stateful . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { SYNCHRONIZE . getOpInfo ( ) , } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { MBeanNotificationInfo [ ] nInfo = new MBeanNotificationInfo [ ] { new MBeanNotificationInfo ( new String [ ] { STATE_CHANGE_NOTIF_TYPE } , Notification . class . getName ( ) , "" ) } ; return nInfo ; } public ServerInterfaceHandler createServerHandler ( Stateful stateful , ServerSideToolkit ojmb ) { ServerStateHandler stateHelper = new ServerStateHandler ( stateful , ojmb ) ; try { stateful . addStateListener ( stateHelper ) ; } catch ( JobDestroyedException e ) { stateHelper . jobStateChange ( stateful . lastStateEvent ( ) ) ; } return stateHelper ; } public ClientHandlerResolver < Stateful > clientHandlerFactory ( ) { return new SimpleHandlerResolver < Stateful > ( ClientStatefulHandlerFactory . class . getName ( ) , VERSION ) ; } public static class ClientStatefulHandlerFactory implements ClientInterfaceHandlerFactory < Stateful > { public Class < Stateful > interfaceClass ( ) { return Stateful . class ; } public HandlerVersion getVersion ( ) { return VERSION ; } public Stateful createClientHandler ( Stateful proxy , ClientSideToolkit toolkit ) { return new ClientStatefulHandler ( proxy , toolkit ) ; } } static class ClientStatefulHandler implements Stateful , Destroyable { private StateEvent lastEvent ; private final List < StateListener > listeners = new ArrayList < StateListener > ( ) ; private final ClientSideToolkit toolkit ; private final Stateful owner ; private Synchronizer synchronizer ; public ClientStatefulHandler ( Stateful owner , ClientSideToolkit toolkit ) { this . owner = owner ; this . toolkit = toolkit ; lastEvent = new StateEvent ( this . owner , JobState . READY , null ) ; } void jobStateChange ( StateData data ) { StateEvent newEvent = new StateEvent ( owner , data . getJobState ( ) , data . getDate ( ) , data . getThrowable ( ) ) ; lastEvent = newEvent ; List < StateListener > copy = null ; synchronized ( listeners ) { copy = new ArrayList < StateListener > ( listeners ) ; } for ( StateListener listener : copy ) { listener . jobStateChange ( newEvent ) ; } } public void addStateListener ( StateListener listener ) throws JobDestroyedException { synchronized ( this ) { if ( synchronizer == null ) { synchronizer = new Synchronizer ( new NotificationListener ( ) { public void handleNotification ( Notification notification , Object arg1 ) { StateData stateData = ( StateData ) notification . getUserData ( ) ; jobStateChange ( stateData ) ; } } ) ; toolkit . registerNotificationListener ( STATE_CHANGE_NOTIF_TYPE , synchronizer ) ; Notification [ ] lastNotifications = null ; try { lastNotifications = ( Notification [ ] ) toolkit . invoke ( SYNCHRONIZE ) ; } catch ( InstanceNotFoundException e ) { throw new JobDestroyedException ( owner ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } synchronizer . synchronize ( lastNotifications ) ; } if ( lastEvent . getState ( ) . isDestroyed ( ) ) { throw new JobDestroyedException ( owner ) ; } StateEvent nowEvent = lastEvent ; listener . jobStateChange ( nowEvent ) ; listeners . add ( listener ) ; } } public void removeStateListener ( StateListener listener ) { synchronized ( this ) { listeners . remove ( listener ) ; if ( listeners . size ( ) == ) { toolkit . removeNotificationListener ( STATE_CHANGE_NOTIF_TYPE , synchronizer ) ; synchronizer = null ; } } } @ Override public StateEvent lastStateEvent ( ) { return lastEvent ; } @ Override public void destroy ( ) { jobStateChange ( new StateData ( new ClientDestroyed ( ) , new Date ( ) , null ) ) ; } } class ServerStateHandler implements StateListener , ServerInterfaceHandler { private final Stateful stateful ; private final ServerSideToolkit toolkit ; private Notification lastNotification ; ServerStateHandler ( Stateful stateful , ServerSideToolkit ojmb ) { this . stateful = stateful ; this . toolkit = ojmb ; } public void jobStateChange ( final StateEvent event ) { toolkit . runSynchronized ( new Runnable ( ) { public void run ( ) { StateData newEvent = new StateData ( event . getState ( ) , event . getTime ( ) , event . getException ( ) ) ; Notification notification = toolkit . createNotification ( STATE_CHANGE_NOTIF_TYPE ) ; notification . setUserData ( newEvent ) ; toolkit . sendNotification ( notification ) ; lastNotification = notification ; } } ) ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( SYNCHRONIZE . equals ( operation ) ) { return new Notification [ ] { lastNotification } ; } throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } public void destroy ( ) { stateful . removeStateListener ( this ) ; } } public static class StateData implements Serializable { private static final long serialVersionUID = ; private final State jobState ; private final Date date ; private final Throwable throwable ; public StateData ( State state , Date date , Throwable throwable ) { this . jobState = state ; this . date = date ; if ( throwable == null ) { this . throwable = null ; } else { this . throwable = new OddjobTransportableException ( throwable ) ; } } public State getJobState ( ) { return jobState ; } public Date getDate ( ) { return date ; } public Throwable getThrowable ( ) { return throwable ; } } } package org . oddjob . jmx . handlers ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanParameterInfo ; import org . oddjob . Resetable ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . VanillaHandlerResolver ; import org . oddjob . jmx . server . ServerAllOperationsHandler ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class ResetableHandlerFactory implements ServerInterfaceHandlerFactory < Resetable , Resetable > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; public Class < Resetable > interfaceClass ( ) { return Resetable . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { new MBeanOperationInfo ( "" , "" , new MBeanParameterInfo [ ] , Void . TYPE . getName ( ) , MBeanOperationInfo . ACTION ) , new MBeanOperationInfo ( "" , "" , new MBeanParameterInfo [ ] , Void . TYPE . getName ( ) , MBeanOperationInfo . ACTION ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Resetable target , ServerSideToolkit ojmb ) { return new ServerAllOperationsHandler < Resetable > ( Resetable . class , target ) ; } public ClientHandlerResolver < Resetable > clientHandlerFactory ( ) { return new VanillaHandlerResolver < Resetable > ( Resetable . class . getName ( ) ) ; } } package org . oddjob . jmx . handlers ; import java . io . Serializable ; import java . lang . reflect . UndeclaredThrowableException ; import javax . management . InstanceNotFoundException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . management . ReflectionException ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . ConfigOwnerEvent ; import org . oddjob . arooa . parsing . ConfigSessionEvent ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationOwnerSupport ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . ConfigurationSessionSupport ; import org . oddjob . arooa . parsing . CutAndPasteSupport ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . parsing . OwnerStateListener ; import org . oddjob . arooa . parsing . SessionStateListener ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . SimpleHandlerResolver ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class ComponentOwnerHandlerFactory implements ServerInterfaceHandlerFactory < ConfigurationOwner , ConfigurationOwner > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; public static final String MODIFIED_NOTIF_TYPE = "" ; public static final String CHANGE_NOTIF_TYPE = "" ; private static final JMXOperationPlus < Integer > SESSION_AVAILABLE = new JMXOperationPlus < Integer > ( "" , "" , Integer . class , MBeanOperationInfo . INFO ) ; private static final JMXOperationPlus < DragPointInfo > DRAG_POINT_INFO = new JMXOperationPlus < DragPointInfo > ( "" , "" , DragPointInfo . class , MBeanOperationInfo . INFO ) . addParam ( "" , Object . class , "" ) ; private static final JMXOperationPlus < Void > CUT = new JMXOperationPlus < Void > ( "" , "" , Void . TYPE , MBeanOperationInfo . ACTION_INFO ) . addParam ( "" , Object . class , "" ) ; private static final JMXOperationPlus < String > PASTE = new JMXOperationPlus < String > ( "" , "" , String . class , MBeanOperationInfo . ACTION ) . addParam ( "" , Object . class , "" ) . addParam ( "" , Integer . TYPE , "" ) . addParam ( "" , String . class , "" ) ; private static final JMXOperationPlus < Boolean > IS_MODIFIED = new JMXOperationPlus < Boolean > ( "" , "" , Boolean . class , MBeanOperationInfo . INFO ) ; private static final JMXOperationPlus < String > SAVE = new JMXOperationPlus < String > ( "" , "" , String . class , MBeanOperationInfo . ACTION ) ; private static final JMXOperationPlus < Void > REPLACE = new JMXOperationPlus < Void > ( "" , "" , Void . TYPE , MBeanOperationInfo . INFO ) . addParam ( "" , Object . class , "" ) ; private static final JMXOperationPlus < ComponentOwnerInfo > INFO = new JMXOperationPlus < ComponentOwnerInfo > ( "" , "" , ComponentOwnerInfo . class , MBeanOperationInfo . INFO ) ; public Class < ConfigurationOwner > interfaceClass ( ) { return ConfigurationOwner . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { INFO . getOpInfo ( ) , SESSION_AVAILABLE . getOpInfo ( ) , DRAG_POINT_INFO . getOpInfo ( ) , CUT . getOpInfo ( ) , PASTE . getOpInfo ( ) , SAVE . getOpInfo ( ) , IS_MODIFIED . getOpInfo ( ) , REPLACE . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { MBeanNotificationInfo [ ] nInfo = new MBeanNotificationInfo [ ] { new MBeanNotificationInfo ( new String [ ] { MODIFIED_NOTIF_TYPE } , Notification . class . getName ( ) , "" ) } ; return nInfo ; } public ServerInterfaceHandler createServerHandler ( ConfigurationOwner target , ServerSideToolkit ojmb ) { return new ServerComponentOwnerHandler ( target , ojmb ) ; } public ClientHandlerResolver < ConfigurationOwner > clientHandlerFactory ( ) { return new SimpleHandlerResolver < ConfigurationOwner > ( ClientConfigurationOwnerHandlerFactory . class . getName ( ) , VERSION ) ; } public static class ClientConfigurationOwnerHandlerFactory implements ClientInterfaceHandlerFactory < ConfigurationOwner > { public Class < ConfigurationOwner > interfaceClass ( ) { return ConfigurationOwner . class ; } public HandlerVersion getVersion ( ) { return VERSION ; } public ConfigurationOwner createClientHandler ( ConfigurationOwner proxy , ClientSideToolkit toolkit ) { return new ClientCompontOwnerHandler ( proxy , toolkit ) ; } } static class ClientCompontOwnerHandler implements ConfigurationOwner { private final ClientSideToolkit clientToolkit ; private final ConfigurationOwnerSupport ownerSupport ; private final DesignFactory rootDesignFactory ; private final ArooaElement rootElement ; private volatile boolean listening ; private final NotificationListener listener = new NotificationListener ( ) { public void handleNotification ( Notification notification , Object handback ) { updateSession ( ( ConfigOwnerEvent . Change ) notification . getUserData ( ) ) ; } ; } ; ClientCompontOwnerHandler ( ConfigurationOwner proxy , final ClientSideToolkit toolkit ) { this . clientToolkit = toolkit ; ownerSupport = new ConfigurationOwnerSupport ( proxy ) ; updateSession ( null ) ; ownerSupport . setOnFirst ( new Runnable ( ) { public void run ( ) { updateSession ( null ) ; toolkit . registerNotificationListener ( CHANGE_NOTIF_TYPE , listener ) ; listening = true ; } } ) ; ownerSupport . setOnEmpty ( new Runnable ( ) { public void run ( ) { listening = false ; toolkit . removeNotificationListener ( CHANGE_NOTIF_TYPE , listener ) ; } } ) ; try { ComponentOwnerInfo info = clientToolkit . invoke ( INFO ) ; rootDesignFactory = info . rootDesignFactory ; rootElement = info . rootElement ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public ConfigurationSession provideConfigurationSession ( ) { if ( ! listening ) { updateSession ( null ) ; } return ownerSupport . provideConfigurationSession ( ) ; } private void updateSession ( ConfigOwnerEvent . Change change ) { if ( change == null || change == ConfigOwnerEvent . Change . SESSION_CREATED ) { Integer newId = null ; try { newId = clientToolkit . invoke ( SESSION_AVAILABLE ) ; } catch ( InstanceNotFoundException e ) { newId = null ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } if ( newId == null ) { ownerSupport . setConfigurationSession ( null ) ; } else { ClientConfigurationSessionHandler existing = ( ClientConfigurationSessionHandler ) ownerSupport . provideConfigurationSession ( ) ; if ( existing == null || existing . id != newId . intValue ( ) ) { ownerSupport . setConfigurationSession ( null ) ; ownerSupport . setConfigurationSession ( new ClientConfigurationSessionHandler ( clientToolkit , newId . intValue ( ) ) ) ; } } } else { ownerSupport . setConfigurationSession ( null ) ; } } public void addOwnerStateListener ( OwnerStateListener listener ) { ownerSupport . addOwnerStateListener ( listener ) ; } public void removeOwnerStateListener ( OwnerStateListener listener ) { ownerSupport . removeOwnerStateListener ( listener ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return rootDesignFactory ; } @ Override public ArooaElement rootElement ( ) { return rootElement ; } } static class ClientConfigurationSessionHandler implements ConfigurationSession { private final ClientSideToolkit clientToolkit ; private final ConfigurationSessionSupport sessionSupport ; private final int id ; private final NotificationListener listener = new NotificationListener ( ) { public void handleNotification ( Notification notification , Object handback ) { Boolean modified = ( Boolean ) notification . getUserData ( ) ; if ( modified ) { sessionSupport . modified ( ) ; } else { sessionSupport . saved ( ) ; } } } ; public ClientConfigurationSessionHandler ( final ClientSideToolkit clientToolkit , int id ) { this . id = id ; this . clientToolkit = clientToolkit ; sessionSupport = new ConfigurationSessionSupport ( this ) ; sessionSupport . setOnFirst ( new Runnable ( ) { public void run ( ) { clientToolkit . registerNotificationListener ( MODIFIED_NOTIF_TYPE , listener ) ; } } ) ; sessionSupport . setOnEmpty ( new Runnable ( ) { public void run ( ) { clientToolkit . removeNotificationListener ( MODIFIED_NOTIF_TYPE , listener ) ; } } ) ; } public DragPoint dragPointFor ( Object component ) { if ( component == null ) { throw new NullPointerException ( "" ) ; } try { final DragPointInfo dragPointInfo = ( DragPointInfo ) clientToolkit . invoke ( DRAG_POINT_INFO , new Object [ ] { component } ) ; return createDragPoint ( component , dragPointInfo ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public void save ( ) throws ArooaParseException { try { clientToolkit . invoke ( SAVE ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public boolean isModified ( ) { try { return clientToolkit . invoke ( IS_MODIFIED ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public void addSessionStateListener ( SessionStateListener listener ) { sessionSupport . addSessionStateListener ( listener ) ; } public void removeSessionStateListener ( SessionStateListener listener ) { sessionSupport . removeSessionStateListener ( listener ) ; } public ArooaDescriptor getArooaDescriptor ( ) { return clientToolkit . getClientSession ( ) . getArooaSession ( ) . getArooaDescriptor ( ) ; } private DragPoint createDragPoint ( final Object component , final DragPointInfo dragPointInfo ) { if ( dragPointInfo == null ) { return null ; } return new DragPoint ( ) { public boolean supportsCut ( ) { return dragPointInfo . supportsCut ; } public boolean supportsPaste ( ) { return dragPointInfo . supportsPaste ; } public DragTransaction beginChange ( ChangeHow how ) { return new DragTransaction ( ) { @ Override public void rollback ( ) { } @ Override public void commit ( ) { } } ; } public String copy ( ) { return dragPointInfo . copy ; } public void cut ( ) { try { clientToolkit . invoke ( CUT , new Object [ ] { component } ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public ConfigurationHandle parse ( ArooaContext parentContext ) throws ArooaParseException { try { final XMLConfiguration config = new XMLConfiguration ( "" , dragPointInfo . copy ) ; final ConfigurationHandle handle = config . parse ( parentContext ) ; return new ConfigurationHandle ( ) { public ArooaContext getDocumentContext ( ) { return handle . getDocumentContext ( ) ; } public void save ( ) throws ArooaParseException { config . setSaveHandler ( new XMLConfiguration . SaveHandler ( ) { @ Override public void acceptXML ( String xml ) { try { if ( xml . equals ( dragPointInfo . copy ) ) { return ; } clientToolkit . invoke ( REPLACE , new Object [ ] { component , xml } ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } } ) ; handle . save ( ) ; } } ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public void paste ( int index , String config ) throws ArooaParseException { try { clientToolkit . invoke ( PASTE , new Object [ ] { component , index , config } ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } } ; } } class ServerComponentOwnerHandler implements ServerInterfaceHandler { private final ConfigurationOwner configurationOwner ; private final ServerSideToolkit toolkit ; private ConfigurationSession configurationSession ; private final SessionStateListener modifiedListener = new SessionStateListener ( ) { public void sessionModifed ( ConfigSessionEvent event ) { send ( true ) ; } public void sessionSaved ( ConfigSessionEvent event ) { send ( false ) ; } void send ( final boolean modified ) { toolkit . runSynchronized ( new Runnable ( ) { public void run ( ) { Notification notification = toolkit . createNotification ( MODIFIED_NOTIF_TYPE ) ; notification . setUserData ( new Boolean ( modified ) ) ; toolkit . sendNotification ( notification ) ; } } ) ; } } ; private final OwnerStateListener configurationListener = new OwnerStateListener ( ) { public void sessionChanged ( final ConfigOwnerEvent event ) { configurationSession = configurationOwner . provideConfigurationSession ( ) ; if ( configurationSession != null ) { configurationSession . addSessionStateListener ( modifiedListener ) ; } toolkit . runSynchronized ( new Runnable ( ) { public void run ( ) { Notification notification = toolkit . createNotification ( CHANGE_NOTIF_TYPE ) ; notification . setUserData ( event . getChange ( ) ) ; toolkit . sendNotification ( notification ) ; } } ) ; } } ; ServerComponentOwnerHandler ( ConfigurationOwner configurationOwner , ServerSideToolkit serverToolkit ) { this . configurationOwner = configurationOwner ; this . toolkit = serverToolkit ; configurationOwner . addOwnerStateListener ( configurationListener ) ; configurationSession = configurationOwner . provideConfigurationSession ( ) ; if ( configurationSession != null ) { configurationSession . addSessionStateListener ( modifiedListener ) ; } } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( INFO . equals ( operation ) ) { return new ComponentOwnerInfo ( configurationOwner ) ; } if ( SESSION_AVAILABLE . equals ( operation ) ) { if ( configurationSession == null ) { return null ; } else { return new Integer ( System . identityHashCode ( configurationSession ) ) ; } } if ( configurationSession == null ) { throw new MBeanException ( new IllegalStateException ( "" + operation + "" ) ) ; } if ( SAVE . equals ( operation ) ) { try { configurationSession . save ( ) ; return null ; } catch ( ArooaParseException e ) { throw new MBeanException ( e ) ; } } if ( IS_MODIFIED . equals ( operation ) ) { return configurationSession . isModified ( ) ; } DragPoint dragPoint = null ; if ( params != null && params . length > ) { Object component = params [ ] ; dragPoint = configurationSession . dragPointFor ( component ) ; } if ( DRAG_POINT_INFO . equals ( operation ) ) { if ( dragPoint == null ) { return null ; } else { return new DragPointInfo ( dragPoint ) ; } } if ( dragPoint == null ) { throw new MBeanException ( new IllegalStateException ( "" + operation + "" ) ) ; } if ( CUT . equals ( operation ) ) { DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; dragPoint . cut ( ) ; try { trn . commit ( ) ; } catch ( ArooaParseException e ) { trn . rollback ( ) ; throw new MBeanException ( e ) ; } return null ; } else if ( PASTE . equals ( operation ) ) { Integer index = ( Integer ) params [ ] ; String config = ( String ) params [ ] ; DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; try { dragPoint . paste ( index , config ) ; trn . commit ( ) ; } catch ( Exception e ) { trn . rollback ( ) ; throw new MBeanException ( e ) ; } return null ; } else if ( REPLACE . equals ( operation ) ) { String config = ( String ) params [ ] ; try { XMLArooaParser parser = new XMLArooaParser ( ) ; ConfigurationHandle handle = parser . parse ( dragPoint ) ; ArooaContext documentContext = handle . getDocumentContext ( ) ; CutAndPasteSupport . replace ( documentContext . getParent ( ) , documentContext , new XMLConfiguration ( "" , config ) ) ; handle . save ( ) ; } catch ( ArooaParseException e ) { throw new MBeanException ( e ) ; } return null ; } else { throw new ReflectionException ( new IllegalStateException ( "" + operation . toString ( ) + "" ) , operation . toString ( ) ) ; } } public void destroy ( ) { configurationOwner . removeOwnerStateListener ( configurationListener ) ; if ( configurationSession != null ) { configurationSession . removeSessionStateListener ( modifiedListener ) ; } } } } class DragPointInfo implements Serializable { private static final long serialVersionUID = ; final boolean supportsCut ; final boolean supportsPaste ; final String copy ; DragPointInfo ( DragPoint serverDragPoint ) { this . supportsCut = serverDragPoint . supportsCut ( ) ; this . supportsPaste = serverDragPoint . supportsPaste ( ) ; this . copy = serverDragPoint . copy ( ) ; } } class ComponentOwnerInfo implements Serializable { private static final long serialVersionUID = ; final DesignFactory rootDesignFactory ; final ArooaElement rootElement ; ComponentOwnerInfo ( ConfigurationOwner serverConfigOwner ) { this . rootDesignFactory = serverConfigOwner . rootDesignFactory ( ) ; this . rootElement = serverConfigOwner . rootElement ( ) ; } } package org . oddjob . jmx . handlers ; public class OddjobTransportableException extends Exception { private static final long serialVersionUID = ; private final String originalExcpetionClassName ; public OddjobTransportableException ( Throwable t ) { super ( t . getMessage ( ) ) ; this . originalExcpetionClassName = t . getClass ( ) . getName ( ) ; setStackTrace ( t . getStackTrace ( ) ) ; if ( t . getCause ( ) != null ) { initCause ( new OddjobTransportableException ( t . getCause ( ) ) ) ; } } public String getOriginalExcpetionClassName ( ) { return originalExcpetionClassName ; } @ Override public String toString ( ) { String message = getMessage ( ) ; return ( message != null ) ? ( originalExcpetionClassName + "" + message ) : originalExcpetionClassName ; } } package org . oddjob . jmx . handlers ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . ReflectionException ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . PropertyUtils ; import org . oddjob . framework . WrapDynaClass ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . VanillaHandlerResolver ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class DynaBeanHandlerFactory implements ServerInterfaceHandlerFactory < Object , DynaBean > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; private static final JMXOperationPlus < Boolean > CONTAINS = new JMXOperationPlus < Boolean > ( "" , "" , Boolean . TYPE , MBeanOperationInfo . INFO ) . addParam ( "" , String . class , "" ) . addParam ( "" , String . class , "" ) ; private static final JMXOperationPlus < Object > GET_SIMPLE = new JMXOperationPlus < Object > ( "" , "" , Object . class , MBeanOperationInfo . INFO ) . addParam ( "" , String . class , "" ) ; private static final JMXOperationPlus < Object > GET_INDEXED = new JMXOperationPlus < Object > ( "" , "" , Object . class , MBeanOperationInfo . INFO ) . addParam ( "" , String . class , "" ) . addParam ( "" , Integer . TYPE , "" ) ; private static final JMXOperationPlus < Object > GET_MAPPED = new JMXOperationPlus < Object > ( "" , "" , Object . class , MBeanOperationInfo . INFO ) . addParam ( "" , String . class , "" ) . addParam ( "" , String . class , "" ) ; private static final JMXOperationPlus < DynaClass > GET_DYNACLASS = new JMXOperationPlus < DynaClass > ( "" , "" , DynaClass . class , MBeanOperationInfo . INFO ) ; private static final JMXOperationPlus < Void > REMOVE = new JMXOperationPlus < Void > ( "" , "" , Void . TYPE , MBeanOperationInfo . ACTION ) . addParam ( "" , String . class , "" ) . addParam ( "" , String . class , "" ) ; private static final JMXOperationPlus < Void > SET_SIMPLE = new JMXOperationPlus < Void > ( "" , "" , Void . TYPE , MBeanOperationInfo . ACTION ) . addParam ( "" , String . class , "" ) . addParam ( "" , Object . class , "" ) ; private static final JMXOperationPlus < Void > SET_INDEXED = new JMXOperationPlus < Void > ( "" , "" , Void . TYPE , MBeanOperationInfo . ACTION ) . addParam ( "" , String . class , "" ) . addParam ( "" , Integer . TYPE , "" ) . addParam ( "" , Object . class , "" ) ; private static final JMXOperationPlus < Void > SET_MAPPED = new JMXOperationPlus < Void > ( "" , "" , Void . TYPE , MBeanOperationInfo . ACTION ) . addParam ( "" , String . class , "" ) . addParam ( "" , String . class , "" ) . addParam ( "" , Object . class , "" ) ; public Class < Object > interfaceClass ( ) { return Object . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { CONTAINS . getOpInfo ( ) , GET_SIMPLE . getOpInfo ( ) , GET_INDEXED . getOpInfo ( ) , SET_MAPPED . getOpInfo ( ) , GET_DYNACLASS . getOpInfo ( ) , REMOVE . getOpInfo ( ) , SET_SIMPLE . getOpInfo ( ) , SET_INDEXED . getOpInfo ( ) , SET_MAPPED . getOpInfo ( ) , } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Object target , ServerSideToolkit serverSideToolkit ) { return new DynaBeanServerHandler ( target ) ; } public ClientHandlerResolver < DynaBean > clientHandlerFactory ( ) { return new VanillaHandlerResolver < DynaBean > ( DynaBean . class . getName ( ) ) ; } class DynaBeanServerHandler implements ServerInterfaceHandler { private final Object bean ; DynaBeanServerHandler ( Object bean ) { this . bean = bean ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( CONTAINS . equals ( operation ) ) { try { return Boolean . valueOf ( ! ( PropertyUtils . getMappedProperty ( bean , ( String ) params [ ] , ( String ) params [ ] ) == null ) ) ; } catch ( Exception e ) { throw new MBeanException ( e ) ; } } else if ( GET_SIMPLE . equals ( operation ) ) { String property = ( String ) params [ ] ; try { return PropertyUtils . getProperty ( bean , property ) ; } catch ( Exception e ) { throw new MBeanException ( e ) ; } } else if ( GET_INDEXED . equals ( operation ) ) { try { return PropertyUtils . getIndexedProperty ( bean , ( String ) params [ ] , ( ( Integer ) params [ ] ) . intValue ( ) ) ; } catch ( Exception e ) { throw new MBeanException ( e ) ; } } else if ( GET_MAPPED . equals ( operation ) ) { try { return PropertyUtils . getMappedProperty ( bean , ( String ) params [ ] , ( String ) params [ ] ) ; } catch ( Exception e ) { throw new MBeanException ( e ) ; } } else if ( GET_DYNACLASS . equals ( operation ) ) { if ( bean instanceof DynaBean ) { return ( ( DynaBean ) bean ) . getDynaClass ( ) ; } else { return WrapDynaClass . createDynaClass ( bean . getClass ( ) ) ; } } else if ( REMOVE . equals ( operation ) ) { try { PropertyUtils . setMappedProperty ( bean , ( String ) params [ ] , ( String ) params [ ] , null ) ; } catch ( Exception e ) { throw new MBeanException ( e ) ; } return Void . TYPE ; } else if ( SET_INDEXED . equals ( operation ) ) { try { PropertyUtils . setIndexedProperty ( bean , ( String ) params [ ] , ( ( Integer ) params [ ] ) . intValue ( ) , params [ ] ) ; } catch ( Exception e ) { throw new MBeanException ( e ) ; } return Void . TYPE ; } else if ( SET_SIMPLE . equals ( operation ) ) { try { PropertyUtils . setProperty ( bean , ( String ) params [ ] , params [ ] ) ; } catch ( Exception e ) { throw new MBeanException ( e ) ; } return Void . TYPE ; } else if ( SET_MAPPED . equals ( operation ) ) { try { PropertyUtils . setMappedProperty ( bean , ( String ) params [ ] , ( String ) params [ ] , params [ ] ) ; } catch ( Exception e ) { throw new MBeanException ( e ) ; } return Void . TYPE ; } else { throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } } public void destroy ( ) { } } } package org . oddjob . jmx . handlers ; import java . lang . reflect . UndeclaredThrowableException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . SimpleHandlerResolver ; import org . oddjob . jmx . server . JMXOperation ; import org . oddjob . jmx . server . JMXOperationFactory ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogHelper ; public class LogEnabledHandlerFactory implements ServerInterfaceHandlerFactory < Object , LogEnabled > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; private static final JMXOperation < String > GET_LOGGER = new JMXOperationFactory ( LogEnabled . class ) . operationFor ( "" , MBeanOperationInfo . INFO ) ; public Class < Object > interfaceClass ( ) { return Object . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { GET_LOGGER . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Object target , ServerSideToolkit ojmb ) { return new LogEnabledServerHandler ( target , ojmb ) ; } public ClientHandlerResolver < LogEnabled > clientHandlerFactory ( ) { return new SimpleHandlerResolver < LogEnabled > ( ClientLogPollableHandlerFactory . class . getName ( ) , VERSION ) ; } public static class ClientLogPollableHandlerFactory implements ClientInterfaceHandlerFactory < LogEnabled > { public LogEnabled createClientHandler ( LogEnabled ignored , ClientSideToolkit toolkit ) { return new ClientLogEnabledHandler ( toolkit ) ; } public HandlerVersion getVersion ( ) { return VERSION ; } public Class < LogEnabled > interfaceClass ( ) { return LogEnabled . class ; } } static class ClientLogEnabledHandler implements LogEnabled { private final String remoteLoggerName ; ClientLogEnabledHandler ( ClientSideToolkit toolkit ) { try { remoteLoggerName = toolkit . invoke ( GET_LOGGER ) ; } catch ( Throwable t ) { throw new UndeclaredThrowableException ( t ) ; } } public String loggerName ( ) { return remoteLoggerName ; } } class LogEnabledServerHandler implements ServerInterfaceHandler { private final String loggerName ; LogEnabledServerHandler ( Object object , ServerSideToolkit ojmb ) { this . loggerName = LogHelper . getLogger ( object ) ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( GET_LOGGER . equals ( operation ) ) { return loggerName ; } else { throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } } public void destroy ( ) { } } } package org . oddjob . jmx . handlers ; import java . util . Map ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . ReflectionException ; import org . oddjob . Describeable ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . describe . Describer ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . VanillaHandlerResolver ; import org . oddjob . jmx . server . JMXOperation ; import org . oddjob . jmx . server . JMXOperationFactory ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class DescribeableHandlerFactory implements ServerInterfaceHandlerFactory < Object , Describeable > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; private static final JMXOperation < Map < String , String > > DESCRIBE = new JMXOperationFactory ( Describeable . class ) . operationFor ( "" , "" , MBeanOperationInfo . INFO ) ; public Class < Object > interfaceClass ( ) { return Object . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { DESCRIBE . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Object target , ServerSideToolkit ojmb ) { return new ServerDescribeableHandler ( target , ojmb . getServerSession ( ) . getArooaSession ( ) ) ; } public ClientHandlerResolver < Describeable > clientHandlerFactory ( ) { return new VanillaHandlerResolver < Describeable > ( Describeable . class . getName ( ) ) ; } class ServerDescribeableHandler implements ServerInterfaceHandler { private final Object object ; private final Describer describer ; ServerDescribeableHandler ( Object object , ArooaSession session ) { this . object = object ; this . describer = new UniversalDescriber ( session ) ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( DESCRIBE . equals ( operation ) ) { return describer . describe ( object ) ; } else { throw new ReflectionException ( new IllegalStateException ( "" ) , operation . getActionName ( ) ) ; } } public void destroy ( ) { } } } package org . oddjob . jmx . handlers ; import java . io . Serializable ; import java . lang . reflect . UndeclaredThrowableException ; import java . util . ArrayList ; import java . util . List ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . Notification ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . jmx . RemoteDirectory ; import org . oddjob . jmx . RemoteDirectoryOwner ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . SimpleHandlerResolver ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class BeanDirectoryHandlerFactory implements ServerInterfaceHandlerFactory < BeanDirectoryOwner , RemoteDirectoryOwner > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; private static final JMXOperationPlus < ServerId > SERVER_ID = new JMXOperationPlus < ServerId > ( "" , "" , ServerId . class , MBeanOperationInfo . INFO ) ; private static final JMXOperationPlus < ObjectName [ ] > LIST = new JMXOperationPlus < ObjectName [ ] > ( "" , "" , ObjectName [ ] . class , MBeanOperationInfo . INFO ) ; private static final JMXOperationPlus < String > ID_FOR = new JMXOperationPlus < String > ( "" , "" , String . class , MBeanOperationInfo . INFO ) . addParam ( "" , ObjectName . class , "" ) ; private static final JMXOperationPlus < Object > LOOKUP = new JMXOperationPlus < Object > ( "" , "" , Object . class , MBeanOperationInfo . INFO ) . addParam ( "" , String . class , "" ) ; private static final JMXOperationPlus < Object > LOOKUP_TYPE = new JMXOperationPlus < Object > ( "" , "" , Object . class , MBeanOperationInfo . INFO ) . addParam ( "" , String . class , "" ) . addParam ( "" , Class . class , "" ) ; public Class < BeanDirectoryOwner > interfaceClass ( ) { return BeanDirectoryOwner . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { SERVER_ID . getOpInfo ( ) , LIST . getOpInfo ( ) , ID_FOR . getOpInfo ( ) , LOOKUP . getOpInfo ( ) , LOOKUP_TYPE . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ClientHandlerResolver < RemoteDirectoryOwner > clientHandlerFactory ( ) { return new SimpleHandlerResolver < RemoteDirectoryOwner > ( ClientBeanDirectoryHandlerFactory . class . getName ( ) , VERSION ) ; } public static class ClientBeanDirectoryHandlerFactory implements ClientInterfaceHandlerFactory < RemoteDirectoryOwner > { public Class < RemoteDirectoryOwner > interfaceClass ( ) { return RemoteDirectoryOwner . class ; } public HandlerVersion getVersion ( ) { return VERSION ; } public RemoteDirectoryOwner createClientHandler ( RemoteDirectoryOwner ignored , ClientSideToolkit toolkit ) { return new ClientBeanDirectoryHandler ( toolkit ) ; } } static class ClientBeanDirectoryHandler implements RemoteDirectoryOwner { private final ClientSideToolkit toolkit ; ClientBeanDirectoryHandler ( ClientSideToolkit toolkit ) { this . toolkit = toolkit ; } public RemoteDirectory provideBeanDirectory ( ) { return new RemoteDirectory ( ) { private ServerId serverId ; public Object lookup ( String path ) { try { Object result = toolkit . invoke ( LOOKUP , new Object [ ] { path } ) ; if ( result instanceof Carrier ) { return toolkit . getClientSession ( ) . create ( ( ( Carrier ) result ) . getObjectName ( ) ) ; } else { return result ; } } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public < T > T lookup ( String path , Class < T > required ) throws ArooaConversionException { try { Object result = toolkit . invoke ( LOOKUP_TYPE , new Object [ ] { path , required } ) ; if ( result instanceof Carrier ) { result = toolkit . getClientSession ( ) . create ( ( ( Carrier ) result ) . getObjectName ( ) ) ; } return required . cast ( result ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public String getIdFor ( Object bean ) { ObjectName objectName = toolkit . getClientSession ( ) . nameFor ( bean ) ; if ( objectName == null ) { return null ; } try { return toolkit . invoke ( ID_FOR , new Object [ ] { objectName } ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public < T > Iterable < T > getAllByType ( Class < T > type ) { try { ObjectName [ ] names = toolkit . invoke ( LIST , new Object [ ] { type } ) ; if ( names == null ) { return new ArrayList < T > ( ) ; } List < T > results = new ArrayList < T > ( ) ; for ( ObjectName objectName : names ) { Object object = toolkit . getClientSession ( ) . create ( objectName ) ; if ( object == null ) { continue ; } results . add ( type . cast ( object ) ) ; } return results ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } public ServerId getServerId ( ) { if ( serverId == null ) { try { this . serverId = toolkit . invoke ( SERVER_ID , new Object [ ] { } ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } } return serverId ; } } ; } } public ServerInterfaceHandler createServerHandler ( BeanDirectoryOwner directory , ServerSideToolkit serverToolkit ) { ServerBeanDirectoryHandler handler = new ServerBeanDirectoryHandler ( directory , serverToolkit ) ; return handler ; } class ServerBeanDirectoryHandler implements ServerInterfaceHandler { private final BeanDirectoryOwner directoryOwner ; private final ServerSideToolkit serverToolkit ; ServerBeanDirectoryHandler ( BeanDirectoryOwner directory , ServerSideToolkit ojmb ) { this . directoryOwner = directory ; this . serverToolkit = ojmb ; } public Notification [ ] getLastNotifications ( ) { return null ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException , ArooaPropertyException { if ( SERVER_ID . equals ( operation ) ) { return serverToolkit . getContext ( ) . getServerId ( ) ; } BeanDirectory directory = directoryOwner . provideBeanDirectory ( ) ; if ( directory == null ) { return null ; } if ( LIST . equals ( operation ) ) { Class < ? > type = ( Class < ? > ) params [ ] ; Iterable < ? > all = directory . getAllByType ( type ) ; List < ObjectName > names = new ArrayList < ObjectName > ( ) ; for ( Object object : all ) { ObjectName name = serverToolkit . getServerSession ( ) . nameFor ( object ) ; if ( name != null ) { names . add ( name ) ; } } return names . toArray ( new ObjectName [ ] ) ; } if ( ID_FOR . equals ( operation ) ) { ObjectName objectName = ( ObjectName ) params [ ] ; Object object = serverToolkit . getServerSession ( ) . objectFor ( objectName ) ; String id = directory . getIdFor ( object ) ; return id ; } if ( LOOKUP . equals ( operation ) ) { String path = ( String ) params [ ] ; Object object = directory . lookup ( path ) ; if ( object == null ) { return null ; } ObjectName objectName = serverToolkit . getServerSession ( ) . nameFor ( object ) ; if ( objectName != null ) { return new Carrier ( objectName ) ; } else { return object ; } } if ( LOOKUP_TYPE . equals ( operation ) ) { String path = ( String ) params [ ] ; Class < ? > type = ( Class < ? > ) params [ ] ; Object object = null ; try { object = directory . lookup ( path , type ) ; } catch ( ArooaConversionException e ) { throw new MBeanException ( e ) ; } if ( object == null ) { return null ; } ObjectName objectName = serverToolkit . getServerSession ( ) . nameFor ( object ) ; if ( objectName != null ) { return new Carrier ( objectName ) ; } else { return object ; } } throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } public void destroy ( ) { } } static class Carrier implements Serializable { private static final long serialVersionUID = ; private final ObjectName objectName ; Carrier ( ObjectName objectName ) { this . objectName = objectName ; } ObjectName getObjectName ( ) { return objectName ; } } } package org . oddjob . jmx . handlers ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . VanillaHandlerResolver ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class RunnableHandlerFactory implements ServerInterfaceHandlerFactory < Runnable , Runnable > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; private static final JMXOperationPlus < Void > RUN = new JMXOperationPlus < Void > ( "" , "" , Void . TYPE , MBeanOperationInfo . ACTION ) ; public Class < Runnable > interfaceClass ( ) { return Runnable . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { RUN . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Runnable target , ServerSideToolkit ojmb ) { return new RunnableServerHandler ( target , ojmb ) ; } public ClientHandlerResolver < Runnable > clientHandlerFactory ( ) { return new VanillaHandlerResolver < Runnable > ( Runnable . class . getName ( ) ) ; } class RunnableServerHandler implements ServerInterfaceHandler { private final Runnable runnable ; private final ServerSideToolkit ojmb ; RunnableServerHandler ( Runnable runnable , ServerSideToolkit ojmb ) { this . runnable = runnable ; this . ojmb = ojmb ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( RUN . equals ( operation ) ) { ojmb . getContext ( ) . getModel ( ) . getThreadManager ( ) . run ( runnable , "" ) ; return null ; } else { throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } } public void destroy ( ) { } } } package org . oddjob . jmx . handlers ; import java . lang . reflect . Proxy ; import org . oddjob . framework . Exportable ; import org . oddjob . framework . Transportable ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . HandlerVersion ; public class ExportableHandlerFactory implements ClientInterfaceHandlerFactory < Exportable > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; public Class < Exportable > interfaceClass ( ) { return Exportable . class ; } public HandlerVersion getVersion ( ) { return VERSION ; } public Exportable createClientHandler ( Exportable proxy , ClientSideToolkit toolkit ) { return new ClientExportableHandler ( proxy ) ; } class ClientExportableHandler implements Exportable { private final Exportable invocationHandler ; ClientExportableHandler ( Exportable proxy ) { invocationHandler = ( Exportable ) Proxy . getInvocationHandler ( proxy ) ; } public Transportable exportTransportable ( ) { return invocationHandler . exportTransportable ( ) ; } } } package org . oddjob . jmx . handlers ; import java . lang . reflect . Proxy ; import java . lang . reflect . UndeclaredThrowableException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . Notification ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . SimpleHandlerResolver ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class ObjectInterfaceHandlerFactory implements ServerInterfaceHandlerFactory < Object , Object > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; private static final JMXOperationPlus < String > TO_STRING = new JMXOperationPlus < String > ( "" , "" , String . class , MBeanOperationInfo . INFO ) ; public Class < Object > interfaceClass ( ) { return Object . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { TO_STRING . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Object target , ServerSideToolkit ojmb ) { return new ServerObjectHandler ( target ) ; } public ClientHandlerResolver < Object > clientHandlerFactory ( ) { return new SimpleHandlerResolver < Object > ( ClientObjectHandlerFactory . class . getName ( ) , VERSION ) ; } public static class ClientObjectHandlerFactory implements ClientInterfaceHandlerFactory < Object > { public Class < Object > interfaceClass ( ) { return Object . class ; } public HandlerVersion getVersion ( ) { return VERSION ; } ; public Object createClientHandler ( Object proxy , ClientSideToolkit toolkit ) { return new ClientObjectHandler ( proxy , toolkit ) ; } } static class ClientObjectHandler { private final ClientSideToolkit toolkit ; private final Object proxy ; private String toString ; ClientObjectHandler ( Object proxy , ClientSideToolkit toolkit ) { this . proxy = proxy ; this . toolkit = toolkit ; } public String toString ( ) { if ( toString == null ) { try { toString = toolkit . invoke ( TO_STRING ) ; } catch ( Throwable t ) { throw new UndeclaredThrowableException ( t ) ; } if ( toString == null ) { toString = "" ; } } return toString ; } public boolean equals ( Object other ) { return ( other == proxy ) ; } @ Override public int hashCode ( ) { return Proxy . getInvocationHandler ( proxy ) . hashCode ( ) ; } } class ServerObjectHandler implements ServerInterfaceHandler { private final Object object ; ServerObjectHandler ( Object object ) { this . object = object ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( TO_STRING . equals ( operation ) ) { return object . toString ( ) ; } else { throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } } public Notification [ ] getLastNotifications ( ) { return null ; } public void destroy ( ) { } } } package org . oddjob . jmx . handlers ; import java . io . Serializable ; import java . lang . reflect . UndeclaredThrowableException ; import java . util . ArrayList ; import java . util . LinkedList ; import java . util . List ; import javax . management . JMException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import org . apache . log4j . Logger ; import org . oddjob . Structural ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSideToolkit ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . SimpleHandlerResolver ; import org . oddjob . jmx . client . Synchronizer ; import org . oddjob . jmx . server . JMXOperationPlus ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerLoopBackException ; import org . oddjob . jmx . server . ServerSideToolkit ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . ChildMatch ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class StructuralHandlerFactory implements ServerInterfaceHandlerFactory < Structural , Structural > { private static final Logger logger = Logger . getLogger ( StructuralHandlerFactory . class ) ; public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; public static final String STRUCTURAL_NOTIF_TYPE = "" ; static final JMXOperationPlus < Notification [ ] > SYNCHRONIZE = new JMXOperationPlus < Notification [ ] > ( "" , "" , Notification [ ] . class , MBeanOperationInfo . INFO ) ; public Class < Structural > interfaceClass ( ) { return Structural . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { SYNCHRONIZE . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { MBeanNotificationInfo [ ] nInfo = new MBeanNotificationInfo [ ] { new MBeanNotificationInfo ( new String [ ] { STRUCTURAL_NOTIF_TYPE } , Notification . class . getName ( ) , "" ) } ; return nInfo ; } public ServerInterfaceHandler createServerHandler ( Structural structural , ServerSideToolkit ojmb ) { ServerStructuralHelper structuralHelper = new ServerStructuralHelper ( structural , ojmb ) ; return structuralHelper ; } public ClientHandlerResolver < Structural > clientHandlerFactory ( ) { return new SimpleHandlerResolver < Structural > ( ClientStructuralHandlerFactory . class . getName ( ) , VERSION ) ; } public static class ClientStructuralHandlerFactory implements ClientInterfaceHandlerFactory < Structural > { public Class < Structural > interfaceClass ( ) { return Structural . class ; } public HandlerVersion getVersion ( ) { return VERSION ; } public Structural createClientHandler ( Structural proxy , ClientSideToolkit toolkit ) { return new ClientStructuralHandler ( proxy , toolkit ) ; } } static class ClientStructuralHandler implements Structural { private final Structural proxy ; private ChildHelper < Object > structuralHelper ; private final ClientSideToolkit toolkit ; private Synchronizer synchronizer ; private List < ObjectName > childNames ; ClientStructuralHandler ( Structural proxy , ClientSideToolkit toolkit ) { this . proxy = proxy ; this . toolkit = toolkit ; } public void addStructuralListener ( StructuralListener listener ) { synchronized ( this ) { if ( structuralHelper == null ) { this . structuralHelper = new ChildHelper < Object > ( proxy ) ; this . childNames = new ArrayList < ObjectName > ( ) ; synchronizer = new Synchronizer ( new NotificationListener ( ) { public void handleNotification ( Notification notification , Object arg1 ) { ChildData childData = ( ChildData ) notification . getUserData ( ) ; new ChildMatch < ObjectName > ( childNames ) { protected void insertChild ( int index , ObjectName childName ) { Object childProxy = toolkit . getClientSession ( ) . create ( childName ) ; structuralHelper . insertChild ( index , childProxy ) ; } ; @ Override protected void removeChildAt ( int index ) { Object child = structuralHelper . removeChildAt ( index ) ; toolkit . getClientSession ( ) . destroy ( child ) ; } } . match ( childData . getChildObjectNames ( ) ) ; } } ) ; toolkit . registerNotificationListener ( STRUCTURAL_NOTIF_TYPE , synchronizer ) ; Notification [ ] lastNotifications = null ; try { lastNotifications = toolkit . invoke ( SYNCHRONIZE ) ; } catch ( Throwable e ) { throw new UndeclaredThrowableException ( e ) ; } synchronizer . synchronize ( lastNotifications ) ; } } structuralHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { synchronized ( this ) { if ( structuralHelper != null ) { structuralHelper . removeStructuralListener ( listener ) ; if ( structuralHelper . isNoListeners ( ) ) { toolkit . removeNotificationListener ( STRUCTURAL_NOTIF_TYPE , synchronizer ) ; synchronizer = null ; structuralHelper = null ; } } } } } class ServerStructuralHelper implements ServerInterfaceHandler { private final Structural structural ; private final ServerSideToolkit toolkit ; private boolean duplicate ; private final LinkedList < ObjectName > children = new LinkedList < ObjectName > ( ) ; private final StructuralListener listener = new StructuralListener ( ) { public void childAdded ( final StructuralEvent e ) { final ObjectName child ; Object childComponent = e . getChild ( ) ; try { child = toolkit . getServerSession ( ) . createMBeanFor ( childComponent , toolkit . getContext ( ) . addChild ( childComponent ) ) ; } catch ( ServerLoopBackException e1 ) { logger . info ( "" ) ; duplicate = true ; return ; } catch ( JMException e2 ) { logger . error ( "" + childComponent + "" , e2 ) ; return ; } final int index = e . getIndex ( ) ; ChildData newEvent = null ; synchronized ( children ) { children . add ( index , child ) ; newEvent = new ChildData ( children . toArray ( new ObjectName [ children . size ( ) ] ) ) ; } final Notification notification = toolkit . createNotification ( STRUCTURAL_NOTIF_TYPE ) ; notification . setUserData ( newEvent ) ; toolkit . runSynchronized ( new Runnable ( ) { public void run ( ) { toolkit . sendNotification ( notification ) ; } } ) ; logger . debug ( "" + e . getChild ( ) . toString ( ) + "" + e . getIndex ( ) + "" ) ; } public void childRemoved ( final StructuralEvent e ) { if ( duplicate ) { return ; } final int index = e . getIndex ( ) ; ObjectName child = null ; ChildData newEvent = null ; synchronized ( children ) { child = children . get ( index ) ; children . remove ( index ) ; newEvent = new ChildData ( children . toArray ( new ObjectName [ children . size ( ) ] ) ) ; } final Notification notification = toolkit . createNotification ( STRUCTURAL_NOTIF_TYPE ) ; notification . setUserData ( newEvent ) ; toolkit . runSynchronized ( new Runnable ( ) { public void run ( ) { toolkit . sendNotification ( notification ) ; } } ) ; try { toolkit . getServerSession ( ) . destroy ( child ) ; } catch ( JMException e1 ) { logger . error ( "" + e . getChild ( ) + "" , e1 ) ; } logger . debug ( "" + e . getChild ( ) . toString ( ) + "" + e . getIndex ( ) + "" ) ; } } ; ServerStructuralHelper ( Structural structural , ServerSideToolkit ojmb ) { this . structural = structural ; this . toolkit = ojmb ; structural . addStructuralListener ( listener ) ; } private Notification [ ] lastNotifications ( ) { final Notification [ ] lastNotifications = new Notification [ ] ; toolkit . runSynchronized ( new Runnable ( ) { public void run ( ) { ChildData newEvent = new ChildData ( children . toArray ( new ObjectName [ children . size ( ) ] ) ) ; Notification notification = toolkit . createNotification ( STRUCTURAL_NOTIF_TYPE ) ; notification . setUserData ( newEvent ) ; lastNotifications [ ] = notification ; } } ) ; return lastNotifications ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( SYNCHRONIZE . equals ( operation ) ) { return lastNotifications ( ) ; } throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } public void destroy ( ) { structural . removeStructuralListener ( listener ) ; while ( children . size ( ) > ) { StructuralEvent dummyEvent = new StructuralEvent ( structural , new Object ( ) , children . size ( ) - ) ; listener . childRemoved ( dummyEvent ) ; } } } static class ChildData implements Serializable { private static final long serialVersionUID = ; private final ObjectName [ ] objectNames ; public ChildData ( ObjectName [ ] objectName ) { this . objectNames = objectName ; } public ObjectName [ ] getChildObjectNames ( ) { return objectNames ; } } } package org . oddjob . jmx . handlers ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . Notification ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . VanillaHandlerResolver ; import org . oddjob . jmx . server . JMXOperation ; import org . oddjob . jmx . server . ServerInfo ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; import org . oddjob . jmx . server . JMXOperationFactory ; public class RemoteOddjobHandlerFactory implements ServerInterfaceHandlerFactory < Object , RemoteOddjobBean > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; private static final JMXOperation < ServerInfo > SERVER_INFO = new JMXOperationFactory ( RemoteOddjobBean . class ) . operationFor ( "" , "" , MBeanOperationInfo . INFO ) ; private static final JMXOperation < Void > NOOP = new JMXOperationFactory ( RemoteOddjobBean . class ) . operationFor ( "" , MBeanOperationInfo . INFO ) ; public Class < Object > interfaceClass ( ) { return Object . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { SERVER_INFO . getOpInfo ( ) , NOOP . getOpInfo ( ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Object ignored , ServerSideToolkit toolkit ) { return new RemoteOddjobServerHandler ( toolkit . getRemoteBean ( ) ) ; } public ClientHandlerResolver < RemoteOddjobBean > clientHandlerFactory ( ) { return new VanillaHandlerResolver < RemoteOddjobBean > ( RemoteOddjobBean . class . getName ( ) ) ; } class RemoteOddjobServerHandler implements ServerInterfaceHandler { private final RemoteOddjobBean ojmb ; RemoteOddjobServerHandler ( RemoteOddjobBean ojmb ) { this . ojmb = ojmb ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( SERVER_INFO . equals ( operation ) ) { return ojmb . serverInfo ( ) ; } if ( NOOP . equals ( operation ) ) { ojmb . noop ( ) ; return null ; } throw new ReflectionException ( new IllegalStateException ( "" ) , operation . toString ( ) ) ; } public Notification [ ] getLastNotifications ( ) { return null ; } public void destroy ( ) { } } } package org . oddjob . jmx . handlers ; import java . lang . reflect . Method ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . VanillaHandlerResolver ; import org . oddjob . jmx . server . JMXOperation ; import org . oddjob . jmx . server . JMXOperationFactory ; import org . oddjob . jmx . server . ServerAllOperationsHandler ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class VanillaServerHandlerFactory < T > implements ServerInterfaceHandlerFactory < T , T > { private final Class < T > cl ; private final MBeanOperationInfo [ ] opInfo ; public VanillaServerHandlerFactory ( Class < T > cl ) { this . cl = cl ; Method [ ] ms = cl . getMethods ( ) ; opInfo = new MBeanOperationInfo [ ms . length ] ; for ( int i = ; i < opInfo . length ; ++ i ) { Method m = ms [ i ] ; JMXOperation < ? > op = new JMXOperationFactory ( cl ) . operationFor ( m , MBeanOperationInfo . UNKNOWN ) ; opInfo [ i ] = op . getOpInfo ( ) ; } } public Class < T > interfaceClass ( ) { return cl ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return opInfo ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( T target , ServerSideToolkit ojmb ) { return new ServerAllOperationsHandler < T > ( cl , target ) ; } public ClientHandlerResolver < T > clientHandlerFactory ( ) { return new VanillaHandlerResolver < T > ( cl . getName ( ) ) ; } } package org . oddjob . jmx . handlers ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanParameterInfo ; import org . oddjob . Stoppable ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . HandlerVersion ; import org . oddjob . jmx . client . VanillaHandlerResolver ; import org . oddjob . jmx . server . ServerAllOperationsHandler ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerSideToolkit ; public class StoppableHandlerFactory implements ServerInterfaceHandlerFactory < Stoppable , Stoppable > { public static final HandlerVersion VERSION = new HandlerVersion ( , ) ; public Class < Stoppable > interfaceClass ( ) { return Stoppable . class ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { new MBeanOperationInfo ( "" , "" , new MBeanParameterInfo [ ] , Void . TYPE . getName ( ) , MBeanOperationInfo . ACTION ) } ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public ServerInterfaceHandler createServerHandler ( Stoppable target , ServerSideToolkit ojmb ) { return new ServerAllOperationsHandler < Stoppable > ( Stoppable . class , target ) ; } public ClientHandlerResolver < Stoppable > clientHandlerFactory ( ) { return new VanillaHandlerResolver < Stoppable > ( Stoppable . class . getName ( ) ) ; } } package org . oddjob . jmx ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; public interface RemoteDirectoryOwner extends BeanDirectoryOwner { public RemoteDirectory provideBeanDirectory ( ) ; } package org . oddjob . jmx ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . TimeUnit ; import javax . management . MBeanServerConnection ; import org . oddjob . Structural ; import org . oddjob . jmx . client . ClientSession ; import org . oddjob . jmx . client . ClientSessionImpl ; import org . oddjob . jmx . client . RemoteLogPoller ; import org . oddjob . jmx . client . ServerView ; import org . oddjob . jmx . server . OddjobMBeanFactory ; import org . oddjob . jobs . job . StopJob ; import org . oddjob . jobs . structural . ServiceManager ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class JMXClientJob extends ClientBase implements Structural , LogArchiver , ConsoleArchiver , RemoteDirectoryOwner { public static final long DEFAULT_LOG_POLLING_INTERVAL = ; private RemoteLogPoller logPoller ; private ChildHelper < Object > childHelper = new ChildHelper < Object > ( this ) ; private ClientSession clientSession ; private ServerView serverView ; private int maxLoggerLines = LogArchiver . MAX_HISTORY ; private int maxConsoleLines = LogArchiver . MAX_HISTORY ; private long logPollingInterval = ; @ Deprecated public void setUrl ( String url ) { setConnection ( url ) ; } @ Override public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int history ) { stateHandler . assertAlive ( ) ; if ( logPoller == null ) { throw new NullPointerException ( "" ) ; } logPoller . addLogListener ( l , component , level , last , history ) ; synchronized ( logPoller ) { logPoller . notifyAll ( ) ; } } @ Override public void removeLogListener ( LogListener l , Object component ) { if ( logPoller == null ) { return ; } logPoller . removeLogListener ( l , component ) ; } @ Override public void addConsoleListener ( LogListener l , Object component , long last , int max ) { stateHandler . assertAlive ( ) ; if ( logPoller == null ) { throw new NullPointerException ( "" ) ; } logPoller . addConsoleListener ( l , component , last , max ) ; synchronized ( this ) { notifyAll ( ) ; } } @ Override public void removeConsoleListener ( LogListener l , Object component ) { if ( logPoller == null ) { return ; } logPoller . removeConsoleListener ( l , component ) ; } @ Override public String consoleIdFor ( Object component ) { return logPoller . consoleIdFor ( component ) ; } @ Override public void onInitialised ( ) { if ( maxConsoleLines == ) { maxConsoleLines = LogArchiver . MAX_HISTORY ; } if ( maxLoggerLines == ) { maxLoggerLines = LogArchiver . MAX_HISTORY ; } if ( logPollingInterval == ) { logPollingInterval = DEFAULT_LOG_POLLING_INTERVAL ; } } @ Override protected void doStart ( MBeanServerConnection mbsc , ScheduledExecutorService notificationProcessor ) throws Exception { clientSession = new ClientSessionImpl ( mbsc , notificationProcessor , getArooaSession ( ) , logger ( ) ) ; Object serverMain = clientSession . create ( OddjobMBeanFactory . objectName ( ) ) ; if ( serverMain == null ) { throw new NullPointerException ( "" ) ; } serverView = new ServerView ( serverMain ) ; this . logPoller = new RemoteLogPoller ( serverMain , maxConsoleLines , maxLoggerLines ) ; serverView . startStructural ( childHelper ) ; notificationProcessor . scheduleAtFixedRate ( new Runnable ( ) { public void run ( ) { try { serverView . noop ( ) ; } catch ( RuntimeException e ) { try { doStop ( WhyStop . HEARTBEAT_FAILURE , e ) ; } catch ( Exception e1 ) { logger ( ) . error ( "" , e1 ) ; } } } @ Override public String toString ( ) { return "" ; } } , getHeartbeat ( ) , getHeartbeat ( ) , TimeUnit . MILLISECONDS ) ; logPoller . setLogPollingInterval ( logPollingInterval ) ; Thread t = new Thread ( logPoller ) ; t . start ( ) ; } @ Override protected void onStop ( final WhyStop why ) { logPoller . stop ( ) ; if ( why == WhyStop . STOP_REQUEST ) { clientSession . destroy ( serverView . getProxy ( ) ) ; } childHelper . removeAllChildren ( ) ; clientSession . destroyAll ( ) ; logPoller = null ; } @ Override public RemoteDirectory provideBeanDirectory ( ) { if ( serverView == null ) { return null ; } return serverView . provideBeanDirectory ( ) ; } @ Override public void addStructuralListener ( StructuralListener listener ) { childHelper . addStructuralListener ( listener ) ; } @ Override public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } public int getMaxConsoleLines ( ) { return maxConsoleLines ; } public void setMaxConsoleLines ( int maxConsoleLines ) { this . maxConsoleLines = maxConsoleLines ; } public int getMaxLoggerLines ( ) { return maxLoggerLines ; } public void setMaxLoggerLines ( int maxLoggerLines ) { this . maxLoggerLines = maxLoggerLines ; } public long getLogPollingInterval ( ) { return logPollingInterval ; } public void setLogPollingInterval ( long logPollingInterval ) { this . logPollingInterval = logPollingInterval ; } } package org . oddjob . jmx ; import java . io . IOException ; import java . net . MalformedURLException ; import java . util . Map ; import javax . management . JMException ; import javax . management . MBeanServer ; import javax . management . ObjectName ; import javax . management . remote . JMXConnectorServer ; import org . apache . log4j . Logger ; import org . oddjob . OddjobException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . jmx . server . HandlerFactoryProvider ; import org . oddjob . jmx . server . OddjobMBeanFactory ; import org . oddjob . jmx . server . ResourceFactoryProvider ; import org . oddjob . jmx . server . ServerContextMain ; import org . oddjob . jmx . server . ServerInterfaceManagerFactoryImpl ; import org . oddjob . jmx . server . ServerLoopBackException ; import org . oddjob . jmx . server . ServerMainBean ; import org . oddjob . jmx . server . ServerModelImpl ; import org . oddjob . jmx . server . SimpleServerSecurity ; import org . oddjob . util . SimpleThreadManager ; import org . oddjob . util . ThreadManager ; public class JMXServerJob implements ArooaSessionAware { private static final Logger logger = Logger . getLogger ( JMXServerJob . class ) ; public static final String ACCESS_FILE_PROPERTY = "" ; private String name ; private Object root ; private String url ; private String logFormat ; private HandlerFactoryProvider handlerFactories ; private ThreadManager threadManager ; private String address ; private ArooaSession session ; private OddjobMBeanFactory factory ; private ObjectName mainName ; private JMXConnectorServer cntorServer ; private Map < String , ? > environment ; @ ArooaHidden public void setArooaSession ( ArooaSession session ) { this . session = session ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } @ ArooaAttribute public void setRoot ( Object rootNode ) { this . root = rootNode ; } public Object getRoot ( ) { return this . root ; } public String getAddress ( ) { return address ; } public void setUrl ( String bindAs ) { this . url = bindAs ; } public String getUrl ( ) { return url ; } public void start ( ) throws JMException , MalformedURLException , IOException , ServerLoopBackException { if ( root == null ) { throw new OddjobException ( "" ) ; } ServerStrategy serverStrategy = ServerStrategy . stratagyFor ( url ) ; MBeanServer server = serverStrategy . findServer ( ) ; threadManager = new SimpleThreadManager ( ) ; ServerInterfaceManagerFactoryImpl imf = new ServerInterfaceManagerFactoryImpl ( environment ) ; imf . addServerHandlerFactories ( new ResourceFactoryProvider ( session ) . getHandlerFactories ( ) ) ; if ( handlerFactories != null ) { imf . addServerHandlerFactories ( handlerFactories . getHandlerFactories ( ) ) ; } BeanDirectory registry = session . getBeanRegistry ( ) ; ServerModelImpl model = new ServerModelImpl ( new ServerId ( serverStrategy . serverIdText ( ) ) , threadManager , imf ) ; model . setLogFormat ( logFormat ) ; factory = new OddjobMBeanFactory ( server , session ) ; ServerMainBean serverBean = new ServerMainBean ( root , registry ) ; mainName = factory . createMBeanFor ( serverBean , new ServerContextMain ( model , registry ) ) ; this . cntorServer = serverStrategy . startConnector ( environment ) ; this . address = serverStrategy . getAddress ( ) ; } public void stop ( ) throws Exception { logger . debug ( "" ) ; threadManager . close ( ) ; logger . debug ( "" ) ; try { factory . destroy ( mainName ) ; } catch ( JMException e ) { logger . error ( "" , e ) ; } if ( cntorServer != null ) { logger . debug ( "" ) ; this . address = null ; cntorServer . stop ( ) ; } } public String toString ( ) { if ( name == null ) { return "" ; } return name ; } public String getLogFormat ( ) { return logFormat ; } public void setLogFormat ( String logFormat ) { this . logFormat = logFormat ; } public HandlerFactoryProvider getHandlerFactories ( ) { return handlerFactories ; } public void setHandlerFactories ( HandlerFactoryProvider handlerFactories ) { this . handlerFactories = handlerFactories ; } public Map < String , ? > getEnvironment ( ) { return environment ; } public void setEnvironment ( Map < String , ? > environment ) { this . environment = environment ; } } package org . oddjob . jmx ; import java . io . IOException ; import java . lang . management . ManagementFactory ; import java . util . Map ; import java . util . concurrent . Executors ; import java . util . concurrent . ScheduledExecutorService ; import javax . management . JMException ; import javax . management . MBeanServerConnection ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . management . ObjectName ; import javax . management . relation . MBeanServerNotificationFilter ; import javax . management . remote . JMXConnector ; import javax . management . remote . JMXConnectorFactory ; import javax . management . remote . JMXServiceURL ; import org . oddjob . FailedToStopException ; import org . oddjob . framework . SimpleService ; import org . oddjob . jmx . server . OddjobMBeanFactory ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . ServiceState ; abstract public class ClientBase extends SimpleService { protected enum WhyStop { STOP_REQUEST , SERVER_STOPPED , HEARTBEAT_FAILURE } private volatile ScheduledExecutorService notificationProcessor ; private String connection ; private volatile JMXConnector cntor ; private long heartbeat = ; private volatile ServerStoppedListener serverStoppedListener ; private Map < String , ? > environment ; public ClientBase ( ) { } protected void onStart ( ) throws Exception { MBeanServerConnection mbsc ; if ( connection == null ) { logger ( ) . info ( "" ) ; mbsc = ManagementFactory . getPlatformMBeanServer ( ) ; } else { logger ( ) . info ( "" + connection + "" ) ; JMXServiceURL address = new JMXServiceURLHelper ( ) . parse ( connection ) ; cntor = JMXConnectorFactory . connect ( address , environment ) ; mbsc = cntor . getMBeanServerConnection ( ) ; } serverStoppedListener = new ServerStoppedListener ( mbsc ) ; notificationProcessor = Executors . newSingleThreadScheduledExecutor ( ) ; doStart ( mbsc , notificationProcessor ) ; } abstract protected void doStart ( MBeanServerConnection mbsc , ScheduledExecutorService notificationProcessor ) throws Exception ; @ Override protected void onStop ( ) throws FailedToStopException { doStop ( WhyStop . STOP_REQUEST , null ) ; } protected void doStop ( final WhyStop why , final Exception cause ) { ServerStoppedListener serverStoppedListener ; synchronized ( this ) { serverStoppedListener = this . serverStoppedListener ; if ( serverStoppedListener == null ) { return ; } this . serverStoppedListener = null ; } if ( why == WhyStop . STOP_REQUEST ) { serverStoppedListener . remove ( ) ; } onStop ( why ) ; notificationProcessor . shutdownNow ( ) ; notificationProcessor = null ; if ( why == WhyStop . STOP_REQUEST && cntor != null ) { try { cntor . close ( ) ; } catch ( IOException e ) { logger ( ) . debug ( "" + e ) ; } } cntor = null ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { switch ( why ) { case HEARTBEAT_FAILURE : getStateChanger ( ) . setStateException ( cause ) ; logger ( ) . error ( "" , cause ) ; break ; case SERVER_STOPPED : getStateChanger ( ) . setStateException ( new Exception ( "" ) ) ; logger ( ) . info ( "" ) ; break ; default : getStateChanger ( ) . setState ( ServiceState . COMPLETE ) ; logger ( ) . info ( "" ) ; } } } ) ; } abstract protected void onStop ( WhyStop why ) ; public void setConnection ( String lookup ) { this . connection = lookup ; } public String getConnection ( ) { return connection ; } public Map < String , ? > getEnvironment ( ) { return environment ; } public void setEnvironment ( Map < String , ? > environment ) { this . environment = environment ; } public long getHeartbeat ( ) { return heartbeat ; } public void setHeartbeat ( long heartbeat ) { this . heartbeat = heartbeat ; } private class ServerStoppedListener implements NotificationListener { private final MBeanServerConnection mbsc ; public ServerStoppedListener ( MBeanServerConnection mbsc ) throws JMException , IOException { this . mbsc = mbsc ; MBeanServerNotificationFilter serverFilter = new MBeanServerNotificationFilter ( ) ; serverFilter . disableAllObjectNames ( ) ; serverFilter . enableObjectName ( OddjobMBeanFactory . objectName ( ) ) ; mbsc . addNotificationListener ( new ObjectName ( "" ) , this , serverFilter , null ) ; } public void handleNotification ( Notification notification , Object handback ) { if ( "" . equals ( notification . getType ( ) ) ) { logger ( ) . debug ( "" ) ; try { doStop ( WhyStop . SERVER_STOPPED , null ) ; } catch ( Exception e1 ) { logger ( ) . error ( "" , e1 ) ; } } } public void remove ( ) { try { mbsc . removeNotificationListener ( new ObjectName ( "" ) , this ) ; } catch ( Exception e ) { logger ( ) . debug ( "" + e ) ; } } } } package org . oddjob . jmx . client ; public interface ClientInterfaceHandlerFactory < T > { public HandlerVersion getVersion ( ) ; public Class < T > interfaceClass ( ) ; public T createClientHandler ( T proxy , ClientSideToolkit toolkit ) ; } package org . oddjob . jmx . client ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ClassResolver ; public class VanillaHandlerResolver < T > implements ClientHandlerResolver < T > { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( VanillaHandlerResolver . class ) ; private final String className ; public VanillaHandlerResolver ( String className ) { this ( className , null ) ; } public VanillaHandlerResolver ( String className , String prefix ) { if ( className == null ) { throw new NullPointerException ( "" ) ; } this . className = className ; } public String getClassName ( ) { return className ; } @ SuppressWarnings ( "" ) public ClientInterfaceHandlerFactory < T > resolve ( ClassResolver classResolver ) { Class < T > cl = ( Class < T > ) classResolver . findClass ( className ) ; if ( cl == null ) { logger . info ( "" + className ) ; return null ; } return new DirectInvocationClientFactory < T > ( cl ) ; } } package org . oddjob . jmx . client ; import org . oddjob . logging . LogEvent ; public interface LogPollable { public String url ( ) ; public String consoleId ( ) ; public LogEvent [ ] retrieveLogEvents ( long from , int max ) ; public LogEvent [ ] retrieveConsoleEvents ( long from , int max ) ; } package org . oddjob . jmx . client ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; class ClientInterfaceManagerFactory { private final Set < Class < ? > > interfaces = new HashSet < Class < ? > > ( ) ; private final Set < ClientInterfaceHandlerFactory < ? > > clientHandlerFactories = new HashSet < ClientInterfaceHandlerFactory < ? > > ( ) ; public ClientInterfaceManagerFactory ( ClientInterfaceHandlerFactory < ? > [ ] clientHandlerFactories ) { for ( int i = ; clientHandlerFactories != null && i < clientHandlerFactories . length ; ++ i ) { ClientInterfaceHandlerFactory < ? > handlerFactory = clientHandlerFactories [ i ] ; addHandlerFactory ( handlerFactory ) ; } } public void addHandlerFactory ( ClientInterfaceHandlerFactory < ? > handlerFactory ) { this . clientHandlerFactories . add ( handlerFactory ) ; if ( handlerFactory . interfaceClass ( ) . isInterface ( ) ) { interfaces . add ( handlerFactory . interfaceClass ( ) ) ; } } public Class < ? > [ ] interfaces ( ) { return ( Class [ ] ) interfaces . toArray ( new Class [ ] ) ; } public ClientInterfaceManager create ( Object source , ClientSideToolkit csToolkit ) { final Map < Method , Operation < ? > > operations = new LinkedHashMap < Method , Operation < ? > > ( ) ; final List < Destroyable > destroyables = new ArrayList < Destroyable > ( ) ; for ( ClientInterfaceHandlerFactory < ? > clientHandlerFactory : clientHandlerFactories ) { Object handler = createOperations ( source , csToolkit , clientHandlerFactory , operations ) ; if ( handler instanceof Destroyable ) { destroyables . add ( ( Destroyable ) handler ) ; } } return new ClientInterfaceManager ( ) { public Object invoke ( Method method , Object [ ] args ) throws Throwable { Operation < ? > op = ( Operation < ? > ) operations . get ( method ) ; if ( op == null ) { throw new IllegalArgumentException ( "" + method + "" ) ; } Object interfaceHandler = op . getHandler ( ) ; try { return method . invoke ( interfaceHandler , args ) ; } catch ( InvocationTargetException e ) { throw e . getTargetException ( ) ; } } @ Override public void destroy ( ) { for ( Destroyable destroyable : destroyables ) { destroyable . destroy ( ) ; } } } ; } private < T > T createOperations ( Object source , ClientSideToolkit csToolkit , ClientInterfaceHandlerFactory < T > factory , Map < Method , Operation < ? > > operations ) { Class < T > cl = factory . interfaceClass ( ) ; T interfaceHandler = factory . createClientHandler ( cl . cast ( source ) , csToolkit ) ; Method [ ] methods = cl . getMethods ( ) ; for ( int j = ; j < methods . length ; ++ j ) { Method m = methods [ j ] ; Operation < ? > op = operations . get ( m ) ; if ( op != null ) { throw new IllegalArgumentException ( "" + m + "" + op . getFactory ( ) . interfaceClass ( ) . getName ( ) ) ; } operations . put ( m , new Operation < T > ( interfaceHandler , factory ) ) ; } return interfaceHandler ; } class Operation < T > { private final T handler ; private final ClientInterfaceHandlerFactory < T > factory ; Operation ( T handler , ClientInterfaceHandlerFactory < T > factory ) { this . handler = handler ; this . factory = factory ; } T getHandler ( ) { return handler ; } ClientInterfaceHandlerFactory < T > getFactory ( ) { return factory ; } } } package org . oddjob . jmx . client ; import javax . management . ObjectName ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . jmx . ObjectNames ; public interface ClientSession extends ObjectNames { public Object create ( ObjectName objectName ) ; public void destroy ( Object proxy ) ; public ArooaSession getArooaSession ( ) ; public Logger logger ( ) ; public void destroyAll ( ) ; } package org . oddjob . jmx . client ; import java . lang . reflect . Method ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . Utils ; public class MethodOperation extends RemoteOperation < Object > { private final String actionName ; private final String [ ] signature ; public MethodOperation ( Method method ) { actionName = method . getName ( ) ; signature = Utils . classArray2StringArray ( method . getParameterTypes ( ) ) ; } public String getActionName ( ) { return actionName ; } public String [ ] getSignature ( ) { return signature ; } } package org . oddjob . jmx . client ; import java . util . LinkedList ; import javax . management . Notification ; import javax . management . NotificationListener ; public class Synchronizer implements NotificationListener { private final NotificationListener listener ; private LinkedList < Notification > pending = new LinkedList < Notification > ( ) ; public Synchronizer ( NotificationListener listener ) { this . listener = listener ; } public void handleNotification ( Notification notification , Object handback ) { synchronized ( this ) { if ( pending != null ) { pending . addLast ( notification ) ; return ; } } listener . handleNotification ( notification , null ) ; } public void synchronize ( Notification [ ] last ) { long seq = ; for ( Notification notification : last ) { listener . handleNotification ( notification , null ) ; seq = notification . getSequenceNumber ( ) ; } while ( true ) { Notification notification = null ; synchronized ( this ) { if ( pending . isEmpty ( ) ) { pending = null ; return ; } notification = pending . removeFirst ( ) ; if ( notification . getSequenceNumber ( ) < seq ) { continue ; } } listener . handleNotification ( notification , null ) ; } } } package org . oddjob . jmx . client ; import org . oddjob . state . State ; public class ClientDestroyed implements State { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return true ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) ; } } package org . oddjob . jmx . client ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; import java . rmi . RemoteException ; import javax . management . ObjectName ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ClassResolver ; import org . oddjob . framework . Exportable ; import org . oddjob . framework . Transportable ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . jmx . handlers . ExportableHandlerFactory ; import org . oddjob . jmx . server . ServerInfo ; import org . oddjob . util . ClassLoaderSorter ; public class ClientNode implements InvocationHandler , Exportable { private static final Logger logger = Logger . getLogger ( ClientNode . class ) ; private final ObjectName objectName ; private final Object proxy ; private final ClientInterfaceManager interfaceManager ; private ClientNode ( ObjectName objectName , ClientSideToolkit toolkit ) { this . objectName = objectName ; RemoteOddjobBean remote = new DirectInvocationClientFactory < RemoteOddjobBean > ( RemoteOddjobBean . class ) . createClientHandler ( null , toolkit ) ; ServerInfo serverInfo = remote . serverInfo ( ) ; ClassResolver classResolver = toolkit . getClientSession ( ) . getArooaSession ( ) . getArooaDescriptor ( ) . getClassResolver ( ) ; ClientInterfaceManagerFactory managerFactory = new ClientInterfaceManagerFactory ( new ResolverHelper ( classResolver ) . resolveAll ( serverInfo . getClientResolvers ( ) ) ) ; managerFactory . addHandlerFactory ( new ExportableHandlerFactory ( ) ) ; Class < ? > [ ] interfaces = managerFactory . interfaces ( ) ; this . proxy = Proxy . newProxyInstance ( new ClassLoaderSorter ( ) . getTopLoader ( interfaces ) , interfaces , this ) ; interfaceManager = managerFactory . create ( proxy , toolkit ) ; logger . debug ( "" + proxy . toString ( ) + "" + objectName ) ; } public static Handle createProxyFor ( ObjectName objectName , ClientSideToolkit toolkit ) { ClientNode client = new ClientNode ( objectName , toolkit ) ; return client . new Handle ( ) ; } public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return interfaceManager . invoke ( method , args ) ; } public String toString ( ) { return "" + objectName ; } public Transportable exportTransportable ( ) { logger . debug ( "" + proxy + "" + objectName + "" ) ; ComponentTransportable transportable = new ComponentTransportable ( objectName ) ; return transportable ; } public class Handle { public Object getproxy ( ) { return proxy ; } public Destroyable getDestroyer ( ) { return interfaceManager ; } } } package org . oddjob . jmx . client ; import org . oddjob . Structural ; import org . oddjob . jmx . RemoteDirectory ; import org . oddjob . jmx . RemoteDirectoryOwner ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . jmx . server . ServerInfo ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class ServerView implements RemoteDirectoryOwner , RemoteOddjobBean { private final RemoteDirectoryOwner remoteDirectoryOwner ; private final RemoteOddjobBean remoteBean ; public ServerView ( Object serverMainProxy ) { this . remoteDirectoryOwner = ( RemoteDirectoryOwner ) serverMainProxy ; this . remoteBean = ( RemoteOddjobBean ) serverMainProxy ; } public void startStructural ( final ChildHelper < Object > childHelper ) { Structural structural = ( Structural ) remoteDirectoryOwner ; structural . addStructuralListener ( new StructuralListener ( ) { public void childAdded ( StructuralEvent event ) { childHelper . insertChild ( event . getIndex ( ) , event . getChild ( ) ) ; } public void childRemoved ( StructuralEvent event ) { childHelper . removeChildAt ( event . getIndex ( ) ) ; } } ) ; } public RemoteDirectory provideBeanDirectory ( ) { return remoteDirectoryOwner . provideBeanDirectory ( ) ; } public Object getProxy ( ) { return remoteDirectoryOwner ; } public ServerInfo serverInfo ( ) { return remoteBean . serverInfo ( ) ; } public void noop ( ) { remoteBean . noop ( ) ; } } package org . oddjob . jmx . client ; import java . io . IOException ; import java . util . LinkedHashMap ; import java . util . Map ; import javax . management . InstanceNotFoundException ; import javax . management . JMException ; import javax . management . MBeanException ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import org . apache . log4j . Logger ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . Utils ; class ClientSideToolkitImpl implements ClientSideToolkit { private static final Logger logger = Logger . getLogger ( ClientSideToolkitImpl . class ) ; private final static int ACTIVE = ; private final static int DESTROYED = ; private volatile int phase = ACTIVE ; private final ClientSessionImpl clientSession ; private ObjectName objectName ; private final Map < String , NotificationListener > notifications = new LinkedHashMap < String , NotificationListener > ( ) ; private final ClientListener clientListener ; public ClientSideToolkitImpl ( ObjectName objectName , ClientSessionImpl clientSession ) throws InstanceNotFoundException , IOException { this . clientSession = clientSession ; this . objectName = objectName ; clientListener = new ClientListener ( ) ; clientSession . getServerConnection ( ) . addNotificationListener ( objectName , clientListener , null , null ) ; } @ SuppressWarnings ( "" ) public < T > T invoke ( RemoteOperation < T > remote , Object ... args ) throws Throwable { Object [ ] exported = Utils . export ( args ) ; Object result = null ; try { result = clientSession . getServerConnection ( ) . invoke ( objectName , remote . getActionName ( ) , exported , remote . getSignature ( ) ) ; } catch ( ReflectionException e ) { throw e . getTargetException ( ) ; } catch ( MBeanException e ) { throw e . getTargetException ( ) ; } return ( T ) Utils . importResolve ( result , clientSession ) ; } public void registerNotificationListener ( String eventType , NotificationListener notificationListener ) { notifications . put ( eventType , notificationListener ) ; } public void removeNotificationListener ( String eventType , NotificationListener notificationListener ) { notifications . remove ( eventType ) ; } public ClientSession getClientSession ( ) { return clientSession ; } void destroy ( ) { phase = DESTROYED ; try { if ( clientListener != null ) { clientSession . getServerConnection ( ) . removeNotificationListener ( objectName , clientListener ) ; } } catch ( JMException e ) { logger . debug ( e ) ; } catch ( IOException e ) { logger . debug ( e ) ; } logger . debug ( "" + toString ( ) + "" ) ; } @ Override public String toString ( ) { return "" + objectName ; } class ClientListener implements NotificationListener { public void handleNotification ( final Notification notification , final Object object ) { String type = notification . getType ( ) ; logger . debug ( "" + type + "" + notification . getSequenceNumber ( ) + "" + ClientSideToolkitImpl . this . toString ( ) + "" ) ; if ( phase == DESTROYED ) { logger . debug ( "" + ClientSideToolkitImpl . this . toString ( ) + "" ) ; return ; } final NotificationListener listener = ( NotificationListener ) notifications . get ( type ) ; if ( listener != null ) { Runnable r = new Runnable ( ) { public void run ( ) { try { listener . handleNotification ( notification , object ) ; } catch ( Exception e ) { logger . debug ( e ) ; } } } ; clientSession . getNotificationProcessor ( ) . submit ( r ) ; } } @ Override public String toString ( ) { return ClientSideToolkitImpl . this . toString ( ) ; } } } package org . oddjob . jmx . client ; import javax . management . NotificationListener ; import org . oddjob . jmx . RemoteOperation ; public interface ClientSideToolkit { public ClientSession getClientSession ( ) ; public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable ; public void registerNotificationListener ( String eventType , NotificationListener notificationListener ) ; public void removeNotificationListener ( String eventType , NotificationListener notificationListener ) ; } package org . oddjob . jmx . client ; import java . lang . reflect . Method ; public interface ClientInterfaceManager extends Destroyable { public Object invoke ( Method method , Object [ ] args ) throws Throwable ; } package org . oddjob . jmx . client ; public interface Destroyable { public void destroy ( ) ; } package org . oddjob . jmx . client ; import javax . management . ObjectName ; import org . apache . log4j . Logger ; import org . oddjob . framework . Transportable ; import org . oddjob . jmx . ObjectNames ; public class ComponentTransportable implements Transportable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( ComponentTransportable . class ) ; private ObjectName name ; public ComponentTransportable ( ObjectName name ) { this . name = name ; } public Object importResolve ( ObjectNames names ) { Object resolved = names . objectFor ( name ) ; logger . debug ( "" + resolved + "" + name + "" ) ; return resolved ; } public String toString ( ) { return "" + name ; } } package org . oddjob . jmx . client ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . ClassResolver ; public class ResolverHelper { private final ClassResolver classResolver ; public ResolverHelper ( ClassResolver classResolver ) { this . classResolver = classResolver ; } public ClientInterfaceHandlerFactory < ? > [ ] resolveAll ( ClientHandlerResolver < ? > [ ] resolvers ) { List < ClientInterfaceHandlerFactory < ? > > results = new ArrayList < ClientInterfaceHandlerFactory < ? > > ( ) ; for ( ClientHandlerResolver < ? > resolver : resolvers ) { ClientInterfaceHandlerFactory < ? > factory = resolver . resolve ( classResolver ) ; if ( factory != null ) { results . add ( factory ) ; } } return results . toArray ( new ClientInterfaceHandlerFactory < ? > [ results . size ( ) ] ) ; } } package org . oddjob . jmx . client ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; public class DirectInvocationClientFactory < T > implements ClientInterfaceHandlerFactory < T > { private final Class < T > type ; public DirectInvocationClientFactory ( Class < T > type ) { this . type = type ; } public HandlerVersion getVersion ( ) { return new HandlerVersion ( , ) ; } public T createClientHandler ( T ignored , final ClientSideToolkit toolkit ) { Object delegate = Proxy . newProxyInstance ( type . getClassLoader ( ) , new Class < ? > [ ] { type } , new InvocationHandler ( ) { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return toolkit . invoke ( new MethodOperation ( method ) , args ) ; } } ) ; return type . cast ( delegate ) ; } public Class < T > interfaceClass ( ) { return type ; } } package org . oddjob . jmx . client ; import java . io . Serializable ; import org . oddjob . arooa . ClassResolver ; public interface ClientHandlerResolver < T > extends Serializable { public ClientInterfaceHandlerFactory < T > resolve ( ClassResolver classResolver ) ; } package org . oddjob . jmx . client ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . concurrent . ScheduledExecutorService ; import javax . management . MBeanServerConnection ; import javax . management . ObjectName ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; public class ClientSessionImpl implements ClientSession { private final Logger logger ; private final Map < Object , ObjectName > names = new HashMap < Object , ObjectName > ( ) ; private final Map < ObjectName , Object > proxies = new HashMap < ObjectName , Object > ( ) ; private final Map < Object , Destroyable > destroyers = new HashMap < Object , Destroyable > ( ) ; private final ArooaSession arooaSession ; private final MBeanServerConnection serverConnection ; private final ScheduledExecutorService notificationProcessor ; public ClientSessionImpl ( MBeanServerConnection serverConnection , ScheduledExecutorService notificationProcessor , ArooaSession arooaSession , Logger logger ) { this . serverConnection = serverConnection ; this . notificationProcessor = notificationProcessor ; this . arooaSession = arooaSession ; this . logger = logger ; } public Object create ( ObjectName objectName ) { Object childProxy = proxies . get ( objectName ) ; if ( childProxy != null ) { return childProxy ; } try { ClientSideToolkitImpl toolkit = new ClientSideToolkitImpl ( objectName , this ) ; ClientNode . Handle handle = ClientNode . createProxyFor ( objectName , toolkit ) ; childProxy = handle . getproxy ( ) ; destroyers . put ( childProxy , handle . getDestroyer ( ) ) ; } catch ( Exception e ) { logger . error ( "" + objectName + "" , e ) ; return null ; } names . put ( childProxy , objectName ) ; proxies . put ( objectName , childProxy ) ; return childProxy ; } @ Override public ObjectName nameFor ( Object proxy ) { return names . get ( proxy ) ; } @ Override public Object objectFor ( ObjectName name ) { return proxies . get ( name ) ; } @ Override public void destroy ( Object proxy ) { Destroyable destroyer = destroyers . get ( proxy ) ; destroyer . destroy ( ) ; ObjectName name = names . remove ( proxy ) ; proxies . remove ( name ) ; } @ Override public ArooaSession getArooaSession ( ) { return arooaSession ; } @ Override public Logger logger ( ) { return logger ; } public MBeanServerConnection getServerConnection ( ) { return serverConnection ; } public ScheduledExecutorService getNotificationProcessor ( ) { return notificationProcessor ; } @ Override public void destroyAll ( ) { List < Object > proxies = new ArrayList < Object > ( names . keySet ( ) ) ; for ( Object proxy : proxies ) { destroy ( proxy ) ; } } } package org . oddjob . jmx . client ; import java . util . HashMap ; import java . util . Map ; import org . oddjob . arooa . types . ValueFactory ; import org . oddjob . jmx . JMXClientJob ; public class UsernamePassword implements ValueFactory < Map < String , ? > > { private String username ; private String password ; public Map < String , ? > toValue ( ) { Map < String , Object > env = new HashMap < String , Object > ( ) ; String [ ] credentials = new String [ ] { username , password } ; env . put ( "" , credentials ) ; return env ; } public String getUsername ( ) { return username ; } public void setUsername ( String username ) { this . username = username ; } public String getPassword ( ) { return password ; } public void setPassword ( String password ) { this . password = password ; } } package org . oddjob . jmx . client ; import java . io . Serializable ; public class HandlerVersion implements Serializable { private static final long serialVersionUID = ; private final int major ; private final int minor ; public HandlerVersion ( int major , int minor ) { this . major = major ; this . minor = minor ; } public int getMajor ( ) { return major ; } public int getMinor ( ) { return minor ; } public String getVersionAsText ( ) { return + major + "" + minor ; } @ Override public String toString ( ) { return "" + getVersionAsText ( ) ; } } package org . oddjob . jmx . client ; import org . apache . log4j . Logger ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogHelper ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . cache . LogEventSource ; import org . oddjob . logging . cache . PollingLogArchiver ; public class RemoteLogPoller implements Runnable , LogArchiver , ConsoleArchiver { private static final Logger logger = Logger . getLogger ( RemoteLogPoller . class ) ; private final PollingLogArchiver consoleArchiver ; private final PollingLogArchiver loggerArchiver ; private long logPollingInterval = ; private volatile boolean stop ; public RemoteLogPoller ( Object root , final int consoleHistoryLines , final int logHistoryLines ) { if ( root == null ) { throw new NullPointerException ( "" ) ; } if ( consoleHistoryLines < ) { throw new IllegalArgumentException ( "" ) ; } if ( logHistoryLines < ) { throw new IllegalArgumentException ( "" ) ; } consoleArchiver = new PollingLogArchiver ( consoleHistoryLines , new ArchiveNameResolver ( ) { public String resolveName ( Object component ) { if ( component instanceof LogPollable ) { return consoleArchiveFor ( ( LogPollable ) component ) ; } else { return null ; } } } , new LogEventSource ( ) { public LogEvent [ ] retrieveEvents ( Object component , long last , int max ) { logger . debug ( "" + component + "" ) ; LogPollable pollable = ( LogPollable ) component ; return pollable . retrieveConsoleEvents ( last , max ) ; } } ) ; loggerArchiver = new PollingLogArchiver ( logHistoryLines , new ArchiveNameResolver ( ) { public String resolveName ( Object component ) { if ( component instanceof LogPollable ) { return logArchiveFor ( ( LogPollable ) component ) ; } else { return null ; } } } , new LogEventSource ( ) { public LogEvent [ ] retrieveEvents ( Object component , long last , int max ) { LogPollable pollable = ( LogPollable ) component ; LogEvent [ ] results = pollable . retrieveLogEvents ( last , max ) ; logger . debug ( "" + results . length + "" + component + "" ) ; return results ; } } ) ; } static String logArchiveFor ( LogPollable component ) { String url = component . url ( ) ; if ( url == null ) { throw new NullPointerException ( "" + component + "" ) ; } String archive = LogHelper . getLogger ( component ) ; if ( archive == null ) { return null ; } return url + "" + archive ; } static String consoleArchiveFor ( LogPollable component ) { String url = component . url ( ) ; if ( url == null ) { throw new NullPointerException ( "" + component + "" ) ; } String consoleId = component . consoleId ( ) ; if ( consoleId == null ) { throw new NullPointerException ( "" + component + "" ) ; } return url + "" + consoleId ; } public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int max ) { loggerArchiver . addLogListener ( l , component , level , last , max ) ; synchronized ( this ) { notifyAll ( ) ; } } public void removeLogListener ( LogListener l , Object component ) { loggerArchiver . removeLogListener ( l , component ) ; } public void addConsoleListener ( LogListener l , Object component , long last , int max ) { consoleArchiver . addLogListener ( l , component , LogLevel . DEBUG , last , max ) ; synchronized ( this ) { notifyAll ( ) ; } } public void removeConsoleListener ( LogListener l , Object component ) { consoleArchiver . removeLogListener ( l , component ) ; } public String consoleIdFor ( Object component ) { return consoleArchiveFor ( ( LogPollable ) component ) ; } public long getLogPollingInterval ( ) { return logPollingInterval ; } public void setLogPollingInterval ( long logPollingInterval ) { if ( logPollingInterval == ) { throw new IllegalArgumentException ( "" ) ; } this . logPollingInterval = logPollingInterval ; } public void poll ( ) { consoleArchiver . poll ( ) ; loggerArchiver . poll ( ) ; } public void run ( ) { while ( ! stop ) { poll ( ) ; synchronized ( this ) { try { wait ( logPollingInterval ) ; } catch ( InterruptedException e ) { return ; } } } consoleArchiver . onDestroy ( ) ; loggerArchiver . onDestroy ( ) ; } public void stop ( ) { stop = true ; synchronized ( this ) { notifyAll ( ) ; } } public void onDestroy ( ) { } } package org . oddjob . jmx . client ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ClassResolver ; public class SimpleHandlerResolver < T > implements ClientHandlerResolver < T > { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( SimpleHandlerResolver . class ) ; private final String className ; private final HandlerVersion remoteVersion ; public SimpleHandlerResolver ( String className , HandlerVersion version ) { if ( className == null ) { throw new NullPointerException ( "" ) ; } if ( version == null ) { throw new NullPointerException ( "" ) ; } this . className = className ; this . remoteVersion = version ; } public String getClassName ( ) { return className ; } public HandlerVersion getRemoteVersion ( ) { return remoteVersion ; } @ SuppressWarnings ( "" ) public ClientInterfaceHandlerFactory < T > resolve ( ClassResolver classResolver ) { Class < ClientInterfaceHandlerFactory < T > > cl = ( Class < ClientInterfaceHandlerFactory < T > > ) classResolver . findClass ( className ) ; if ( cl == null ) { logger . info ( "" + className ) ; return null ; } ClientInterfaceHandlerFactory < T > factory = null ; try { factory = cl . newInstance ( ) ; } catch ( Exception e ) { logger . error ( "" + className , e ) ; return null ; } HandlerVersion localVersion = factory . getVersion ( ) ; if ( remoteVersion . getMajor ( ) != localVersion . getMajor ( ) ) { logger . warn ( "" + localVersion . getVersionAsText ( ) + "" + remoteVersion . getVersionAsText ( ) + "" + className + "" + "" + factory . interfaceClass ( ) . getName ( ) + "" ) ; return null ; } if ( remoteVersion . getMinor ( ) != localVersion . getMinor ( ) ) { logger . info ( "" + localVersion . getVersionAsText ( ) + "" + remoteVersion . getVersionAsText ( ) + "" + className + "" + "" + factory . interfaceClass ( ) . getName ( ) + "" ) ; } return factory ; } } package org . oddjob . jmx ; import java . io . IOException ; import java . lang . management . ManagementFactory ; import java . net . MalformedURLException ; import java . util . Map ; import javax . management . JMException ; import javax . management . MBeanServer ; import javax . management . MBeanServerFactory ; import javax . management . ObjectName ; import javax . management . remote . JMXConnectorServer ; import javax . management . remote . JMXConnectorServerFactory ; import javax . management . remote . JMXServiceURL ; import org . apache . log4j . Logger ; abstract public class ServerStrategy { public static ServerStrategy stratagyFor ( String url ) throws MalformedURLException { if ( url == null ) { return new PlatformMBeanServerStrategy ( ) ; } else { return new ConnectorServerStrategy ( url ) ; } } public abstract MBeanServer findServer ( ) ; public abstract String serverIdText ( ) throws JMException ; public abstract JMXConnectorServer startConnector ( Map < String , ? > environment ) throws IOException ; public abstract String getAddress ( ) ; } class ConnectorServerStrategy extends ServerStrategy { private static final Logger logger = Logger . getLogger ( ConnectorServerStrategy . class ) ; private final JMXServiceURL serviceURL ; private MBeanServer server ; private String address ; public ConnectorServerStrategy ( String url ) throws MalformedURLException { serviceURL = new JMXServiceURL ( url ) ; } @ Override public MBeanServer findServer ( ) { server = MBeanServerFactory . createMBeanServer ( ) ; return server ; } @ Override public String serverIdText ( ) { return serviceURL . getURLPath ( ) ; } @ Override public JMXConnectorServer startConnector ( Map < String , ? > environment ) throws IOException { JMXConnectorServer cntorServer = JMXConnectorServerFactory . newJMXConnectorServer ( serviceURL , environment , server ) ; cntorServer . start ( ) ; address = cntorServer . getAddress ( ) . toString ( ) ; logger . info ( "" + address ) ; return cntorServer ; } @ Override public String getAddress ( ) { return address ; } } class PlatformMBeanServerStrategy extends ServerStrategy { private static final Logger logger = Logger . getLogger ( PlatformMBeanServerStrategy . class ) ; @ Override public MBeanServer findServer ( ) { return ManagementFactory . getPlatformMBeanServer ( ) ; } @ Override public String serverIdText ( ) throws JMException { return ( String ) findServer ( ) . getAttribute ( new ObjectName ( "" ) , "" ) ; } @ Override public JMXConnectorServer startConnector ( Map < String , ? > environment ) { logger . info ( "" ) ; return null ; } @ Override public String getAddress ( ) { return null ; } } package org . oddjob . jmx ; import javax . management . ObjectName ; public interface ObjectNames { ObjectName nameFor ( Object object ) ; Object objectFor ( ObjectName objectName ) ; } package org . oddjob . jmx ; import org . oddjob . jmx . server . ServerInfo ; public interface RemoteOddjobBean { public ServerInfo serverInfo ( ) ; public void noop ( ) ; } package org . oddjob . jmx ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . ServerId ; public interface RemoteDirectory extends BeanDirectory { public ServerId getServerId ( ) ; } package org . oddjob . jmx ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . registry . ServerId ; public class RemoteRegistryCrawler { private final BeanDirectory registry ; public RemoteRegistryCrawler ( BeanDirectory registry ) { this . registry = registry ; } public BeanDirectory registryForServer ( ServerId serverId ) { if ( registry instanceof RemoteDirectory ) { if ( ( ( RemoteDirectory ) registry ) . getServerId ( ) . equals ( serverId ) ) { return ( RemoteDirectory ) registry ; } if ( ServerId . local ( ) . equals ( serverId ) ) { return null ; } } else { if ( ServerId . local ( ) . equals ( serverId ) ) { return registry ; } } for ( BeanDirectoryOwner owner : registry . getAllByType ( BeanDirectoryOwner . class ) ) { BeanDirectory child = owner . provideBeanDirectory ( ) ; if ( child == null ) { continue ; } RemoteRegistryCrawler next = new RemoteRegistryCrawler ( child ) ; BeanDirectory result = next . registryForServer ( serverId ) ; if ( result != null ) { return result ; } } return null ; } public Object objectForAddress ( Address address ) throws ArooaPropertyException { if ( address == null ) { return null ; } BeanDirectory registry = registryForServer ( address . getServerId ( ) ) ; if ( registry == null ) { return null ; } return registry . lookup ( address . getPath ( ) . toString ( ) ) ; } Address addressFor ( Object component , Path path ) { if ( registry instanceof RemoteDirectory ) { return null ; } String id = registry . getIdFor ( component ) ; if ( id != null ) { return new Address ( ServerId . local ( ) , path . addId ( id ) ) ; } for ( BeanDirectoryOwner owner : registry . getAllByType ( BeanDirectoryOwner . class ) ) { String childId = registry . getIdFor ( owner ) ; if ( childId == null ) { continue ; } BeanDirectory child = owner . provideBeanDirectory ( ) ; if ( child == null ) { continue ; } Address result = new RemoteRegistryCrawler ( child ) . addressFor ( component , path ) ; if ( result != null ) { return result ; } } return null ; } public Address addressFor ( Object component ) { if ( component instanceof RemoteOddjobBean ) { return ( ( RemoteOddjobBean ) component ) . serverInfo ( ) . getAddress ( ) ; } return addressFor ( component , new Path ( ) ) ; } } package org . oddjob . structural ; import java . util . List ; abstract public class ChildMatch < T > { private final List < T > children ; public ChildMatch ( List < T > children ) { this . children = children ; } public void match ( T [ ] match ) { for ( int i = ; i < match . length ; ++ i ) { T other = match [ i ] ; if ( children . size ( ) <= i ) { trackInsertChild ( i , other ) ; continue ; } Object ours = children . get ( i ) ; if ( ours . equals ( other ) ) { continue ; } if ( children . contains ( other ) ) { trackRemoveChildAt ( i ) ; -- i ; } else { trackInsertChild ( i , other ) ; } } while ( children . size ( ) > match . length ) { trackRemoveChildAt ( match . length ) ; } } private void trackInsertChild ( int index , T child ) { children . add ( index , child ) ; insertChild ( index , child ) ; } private void trackRemoveChildAt ( int index ) { children . remove ( index ) ; removeChildAt ( index ) ; } abstract protected void insertChild ( int index , T child ) ; abstract protected void removeChildAt ( int index ) ; } package org . oddjob . structural ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . oddjob . FailedToStopException ; import org . oddjob . Resetable ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; public class ChildHelper < E > implements Structural , Iterable < E > , ChildList < E > { private final List < E > jobList = new ArrayList < E > ( ) ; private final List < StructuralListener > listeners = new ArrayList < StructuralListener > ( ) ; private final Set < List < ChildAction > > missed = new HashSet < List < ChildAction > > ( ) ; private final Structural source ; public ChildHelper ( Structural source ) { this . source = source ; } @ Override public void insertChild ( int index , E child ) { if ( child == null ) { throw new NullPointerException ( "" ) ; } StructuralEvent event = null ; synchronized ( missed ) { jobList . add ( index , child ) ; event = new StructuralEvent ( source , child , index ) ; for ( List < ChildAction > missing : missed ) { missing . add ( new ChildAdded ( event ) ) ; } } notifyChildAdded ( event ) ; } @ Override public int addChild ( E child ) { if ( child == null ) { throw new NullPointerException ( "" ) ; } int index = - ; StructuralEvent event = null ; synchronized ( missed ) { index = jobList . size ( ) ; jobList . add ( index , child ) ; event = new StructuralEvent ( source , child , index ) ; for ( List < ChildAction > missing : missed ) { missing . add ( new ChildAdded ( event ) ) ; } } notifyChildAdded ( event ) ; return index ; } @ Override public E removeChildAt ( int index ) throws IndexOutOfBoundsException { E child = null ; StructuralEvent event ; synchronized ( missed ) { child = jobList . remove ( index ) ; event = new StructuralEvent ( source , child , index ) ; for ( List < ChildAction > missing : missed ) { missing . add ( new ChildRemoved ( event ) ) ; } } notifyChildRemoved ( event ) ; return child ; } @ Override public int removeChild ( Object child ) throws IllegalStateException { int index = - ; StructuralEvent event ; synchronized ( missed ) { index = jobList . indexOf ( child ) ; if ( index < ) { throw new IllegalStateException ( "" + child + "" ) ; } jobList . remove ( child ) ; event = new StructuralEvent ( source , child , index ) ; for ( List < ChildAction > missing : missed ) { missing . add ( new ChildRemoved ( event ) ) ; } } notifyChildRemoved ( event ) ; return index ; } public void removeAllChildren ( ) { while ( true ) { int size = jobList . size ( ) ; if ( size == ) { break ; } removeChildAt ( size - ) ; } } public void stopChildren ( ) throws FailedToStopException { Object [ ] children = getChildren ( ) ; FailedToStopException failed = null ; for ( int i = children . length - ; i > - ; -- i ) { Object child = children [ i ] ; if ( child instanceof Stoppable ) { try { ( ( Stoppable ) child ) . stop ( ) ; } catch ( FailedToStopException e ) { failed = e ; } catch ( RuntimeException e ) { failed = new FailedToStopException ( child , "" + child + "" , e ) ; } } } if ( failed != null ) { throw failed ; } } public void softResetChildren ( ) { Object [ ] children = getChildren ( ) ; for ( int i = ; i < children . length ; ++ i ) { if ( children [ i ] instanceof Resetable ) { ( ( Resetable ) children [ i ] ) . softReset ( ) ; } } } public void hardResetChildren ( ) { Object [ ] children = getChildren ( ) ; for ( int i = ; i < children . length ; ++ i ) { if ( children [ i ] instanceof Resetable ) { ( ( Resetable ) children [ i ] ) . hardReset ( ) ; } } } public Object [ ] getChildren ( ) { synchronized ( missed ) { return jobList . toArray ( new Object [ jobList . size ( ) ] ) ; } } public E [ ] getChildren ( E [ ] array ) { synchronized ( missed ) { return jobList . toArray ( array ) ; } } public E getChildAt ( int index ) { synchronized ( missed ) { return jobList . get ( index ) ; } } public E getChild ( ) { synchronized ( missed ) { if ( jobList . size ( ) == ) { return null ; } if ( jobList . size ( ) > ) { throw new IllegalStateException ( "" ) ; } return jobList . get ( ) ; } } public boolean contains ( E child ) { synchronized ( missed ) { return jobList . contains ( child ) ; } } @ Override public Iterator < E > iterator ( ) { return new Iterator < E > ( ) { int index ; E next ; @ Override public boolean hasNext ( ) { synchronized ( missed ) { if ( next != null ) { int last = jobList . indexOf ( next ) ; if ( last >= ) { index = last + ; } } if ( index < jobList . size ( ) ) { next = jobList . get ( index ) ; } else { next = null ; } } return next != null ; } @ Override public E next ( ) { synchronized ( missed ) { return next ; } } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } public void addStructuralListener ( StructuralListener listener ) { List < ChildAction > ours = new ArrayList < ChildAction > ( ) ; synchronized ( missed ) { for ( int i = ; i < jobList . size ( ) ; ++ i ) { StructuralEvent event = new StructuralEvent ( source , jobList . get ( i ) , i ) ; ours . add ( new ChildAdded ( event ) ) ; } missed . add ( ours ) ; } while ( true ) { ChildAction action = null ; synchronized ( missed ) { if ( ours . isEmpty ( ) ) { missed . remove ( ours ) ; listeners . add ( listener ) ; break ; } else { action = ours . remove ( ) ; } } if ( action != null ) { action . dispatch ( listener ) ; } } } public void removeStructuralListener ( StructuralListener listener ) { synchronized ( missed ) { listeners . remove ( listener ) ; } } public boolean isNoListeners ( ) { synchronized ( missed ) { return listeners . isEmpty ( ) ; } } public int size ( ) { synchronized ( missed ) { return jobList . size ( ) ; } } abstract class ChildAction { protected final StructuralEvent event ; ChildAction ( StructuralEvent event ) { this . event = event ; } abstract public void dispatch ( StructuralListener listener ) ; } class ChildAdded extends ChildAction { public ChildAdded ( StructuralEvent event ) { super ( event ) ; } @ Override public void dispatch ( StructuralListener listener ) { listener . childAdded ( event ) ; } } class ChildRemoved extends ChildAction { public ChildRemoved ( StructuralEvent event ) { super ( event ) ; } @ Override public void dispatch ( StructuralListener listener ) { listener . childRemoved ( event ) ; } } private void notifyChildAdded ( StructuralEvent event ) { List < StructuralListener > copy = null ; synchronized ( missed ) { copy = new ArrayList < StructuralListener > ( listeners ) ; } for ( StructuralListener l : copy ) { l . childAdded ( event ) ; } } private void notifyChildRemoved ( StructuralEvent event ) { List < StructuralListener > copy = null ; synchronized ( missed ) { copy = new ArrayList < StructuralListener > ( listeners ) ; } for ( StructuralListener l : copy ) { l . childRemoved ( event ) ; } } public static Object [ ] getChildren ( Structural structural ) { class ChildCatcher implements StructuralListener { List < Object > results = new ArrayList < Object > ( ) ; public void childAdded ( StructuralEvent event ) { synchronized ( results ) { results . add ( event . getIndex ( ) , event . getChild ( ) ) ; } } public void childRemoved ( StructuralEvent event ) { synchronized ( results ) { results . remove ( event . getIndex ( ) ) ; } } } ChildCatcher cc = new ChildCatcher ( ) ; structural . addStructuralListener ( cc ) ; structural . removeStructuralListener ( cc ) ; return cc . results . toArray ( ) ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + source ; } } package org . oddjob . structural ; import org . oddjob . OddjobException ; public class OddjobChildException extends OddjobException { private static final long serialVersionUID = ; private final Throwable childException ; private final String childName ; public OddjobChildException ( Throwable childException , String childName ) { super ( "" + childName + "" ) ; this . childException = childException ; this . childName = childName ; } public Throwable getChildException ( ) { return childException ; } public String getChildName ( ) { return childName ; } } package org . oddjob . structural ; import java . io . Serializable ; import java . util . EventObject ; import org . oddjob . Structural ; public class StructuralEvent extends EventObject implements Serializable { private static final long serialVersionUID = ; private final Object child ; private final int index ; public StructuralEvent ( Structural source , Object child , int index ) { super ( source ) ; this . child = child ; this . index = index ; } public Object getChild ( ) { return this . child ; } public int getIndex ( ) { return this . index ; } @ Override public String toString ( ) { return super . toString ( ) + "" + child + "" + index + "" ; } } package org . oddjob . structural ; public interface StructuralListener { public void childAdded ( StructuralEvent event ) ; public void childRemoved ( StructuralEvent event ) ; } package org . oddjob ; public interface Resetable { public boolean softReset ( ) ; public boolean hardReset ( ) ; } package org . oddjob ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . deploy . ArooaDescriptorFactory ; import org . oddjob . arooa . deploy . ClassPathDescriptorFactory ; public class OddjobDescriptorFactory implements ArooaDescriptorFactory { @ Override public ArooaDescriptor createDescriptor ( ClassLoader classLoader ) { if ( classLoader == null ) { classLoader = getClass ( ) . getClassLoader ( ) ; } ClassPathDescriptorFactory factory = new ClassPathDescriptorFactory ( ) ; ArooaDescriptor descriptor = factory . createDescriptor ( classLoader ) ; if ( descriptor == null ) { throw new NullPointerException ( "" + classLoader ) ; } return descriptor ; } } package org . oddjob ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; public class OddjobLookup { private final BeanDirectoryOwner dirOwner ; public OddjobLookup ( BeanDirectoryOwner owner ) { this . dirOwner = owner ; } public Object lookup ( String fullPath ) throws ArooaPropertyException { BeanDirectory directory = dirOwner . provideBeanDirectory ( ) ; if ( directory == null ) { return null ; } return directory . lookup ( fullPath ) ; } public < T > T lookup ( String fullPath , Class < T > type ) throws ArooaPropertyException , ArooaConversionException { BeanDirectory directory = dirOwner . provideBeanDirectory ( ) ; if ( directory == null ) { return null ; } return directory . lookup ( fullPath , type ) ; } } package org . oddjob ; import java . io . File ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . LinkedHashMap ; import java . util . Map ; import java . util . Properties ; import javax . inject . Inject ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . ParsingInterceptor ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . deploy . ArooaDescriptorBean ; import org . oddjob . arooa . deploy . ArooaDescriptorFactory ; import org . oddjob . arooa . deploy . ListDescriptorBean ; import org . oddjob . arooa . deploy . NoAnnotations ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . ConfigConfigurationSession ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationOwnerSupport ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . HandleConfigurationSession ; import org . oddjob . arooa . parsing . OwnerStateListener ; import org . oddjob . arooa . parsing . SessionStateListener ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; import org . oddjob . arooa . registry . ServiceProvider ; import org . oddjob . arooa . registry . Services ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . arooa . types . XMLConfigurationType ; import org . oddjob . arooa . utils . RootConfigurationFileCreator ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . designer . components . RootDC ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . framework . StructuralJob ; import org . oddjob . input . InputHandler ; import org . oddjob . jobs . EchoJob ; import org . oddjob . logging . LogArchive ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogEventSink ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LoggingPrintStream ; import org . oddjob . logging . cache . LogArchiveImpl ; import org . oddjob . oddballs . OddballsDescriptorFactory ; import org . oddjob . persist . FilePersister ; import org . oddjob . persist . OddjobPersister ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . scheduling . OddjobServicesBean ; import org . oddjob . sql . SQLPersisterService ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsNotExecuting ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; import org . oddjob . util . OddjobConfigException ; import org . oddjob . util . URLClassLoaderType ; import org . oddjob . values . properties . PropertiesType ; public class Oddjob extends StructuralJob < Object > implements Loadable , ConfigurationOwner , BeanDirectoryOwner { private static final long serialVersionUID = ; public static final String VERSION = "" ; public static final LogArchive CONSOLE = new LogArchiveImpl ( "" , LogArchiver . MAX_HISTORY ) ; static { System . setOut ( new LoggingPrintStream ( System . out , LogLevel . INFO , ( LogEventSink ) CONSOLE ) ) ; System . setErr ( new LoggingPrintStream ( System . err , LogLevel . ERROR , ( LogEventSink ) CONSOLE ) ) ; } public static final ArooaElement ODDJOB_ELEMENT = new ArooaElement ( "" ) ; private File file ; private transient boolean restored ; private transient ArooaConfiguration configuration ; private transient ConfigurationOwnerSupport configurationOwnerSupport ; private transient OddjobPersister persister ; private String [ ] args ; private transient ClassLoader classLoader ; private transient ArooaDescriptorFactory descriptorFactory ; private transient ArooaSession ourSession ; private transient Object oddjobRoot ; private transient DefaultExecutors internalExecutors ; private transient OddjobExecutors oddjobExecutors ; private transient OddjobServices oddjobServices ; private transient Map < String , ArooaValue > export ; private Properties properties ; private OddjobInheritance inheritance ; enum Reset { SOFT , HARD ; } private Reset lastReset ; private transient InputHandler inputHandler ; public Oddjob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { configurationOwnerSupport = new ConfigurationOwnerSupport ( this ) ; } @ ArooaAttribute public void setFile ( File file ) { if ( restored ) { return ; } this . file = file ; if ( file == null ) { configuration = null ; } } public File getFile ( ) { if ( file == null ) { return null ; } return file . getAbsoluteFile ( ) ; } public void setConfiguration ( ArooaConfiguration config ) { if ( restored ) { return ; } this . configuration = config ; } public void setClassLoader ( ClassLoader classLoader ) { this . classLoader = classLoader ; } public ClassLoader getClassLoader ( ) { return this . classLoader ; } @ Override public ConfigurationSession provideConfigurationSession ( ) { return configurationOwnerSupport . provideConfigurationSession ( ) ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { configurationOwnerSupport . addOwnerStateListener ( listener ) ; } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { configurationOwnerSupport . removeOwnerStateListener ( listener ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return new RootDC ( ) ; } @ Override public ArooaElement rootElement ( ) { return ODDJOB_ELEMENT ; } @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } private void setOurSession ( ArooaSession session ) { this . ourSession = session ; } private OddjobServices preLoadInitialisation ( ) { if ( file != null ) { new RootConfigurationFileCreator ( ODDJOB_ELEMENT ) . createIfNone ( file ) ; configuration = new XMLConfiguration ( file ) ; } if ( configuration == null ) { throw new IllegalStateException ( "" ) ; } ClassLoader classLoader = this . classLoader ; if ( classLoader == null ) { if ( oddjobServices == null ) { classLoader = getClass ( ) . getClassLoader ( ) ; } else { classLoader = oddjobServices . getClassLoader ( ) ; } } OddjobExecutors oddjobExecutors = this . oddjobExecutors ; if ( oddjobExecutors == null ) { if ( oddjobServices == null ) { internalExecutors = new DefaultExecutors ( ) ; oddjobExecutors = internalExecutors ; } else { oddjobExecutors = oddjobServices . getOddjobExecutors ( ) ; } } InputHandler inputHandler = this . inputHandler ; if ( inputHandler == null && oddjobServices != null ) { inputHandler = oddjobServices . getInputHandler ( ) ; } OddjobServicesBean services = new OddjobServicesBean ( ) ; services . setClassLoader ( classLoader ) ; services . setOddjobExecutors ( oddjobExecutors ) ; services . setInputHandler ( inputHandler ) ; OddjobSessionFactory sessionFactory = new OddjobSessionFactory ( ) ; sessionFactory . setExistingSession ( getArooaSession ( ) ) ; sessionFactory . setClassLoader ( classLoader ) ; sessionFactory . setDescriptorFactory ( descriptorFactory ) ; sessionFactory . setOddjobPersister ( persister ) ; sessionFactory . setProperties ( properties ) ; sessionFactory . setInherit ( inheritance ) ; ArooaSession newSession = sessionFactory . createSession ( this ) ; if ( export != null ) { ArooaConverter converter = newSession . getTools ( ) . getArooaConverter ( ) ; for ( Map . Entry < String , ArooaValue > entry : export . entrySet ( ) ) { String name = entry . getKey ( ) ; ArooaValue value = entry . getValue ( ) ; try { ArooaObject object = converter . convert ( value , ArooaObject . class ) ; if ( object == null ) { logger ( ) . info ( "" + name + "" ) ; } else { newSession . getBeanRegistry ( ) . register ( name , object . toValue ( ) ) ; } } catch ( ArooaConversionException e ) { newSession . getBeanRegistry ( ) . register ( name , value ) ; } } } setOurSession ( newSession ) ; return services ; } private void doLoad ( OddjobServices oddjobServices ) throws Exception { logger ( ) . info ( "" + configuration ) ; oddjobRoot = new OddjobRoot ( oddjobServices ) ; StandardArooaParser parser = new StandardArooaParser ( oddjobRoot , ourSession ) ; parser . setExpectedDocumentElement ( ODDJOB_ELEMENT ) ; try { ConfigurationHandle configHandle = parser . parse ( configuration ) ; configurationOwnerSupport . setConfigurationSession ( new OddjobConfigurationSession ( new HandleConfigurationSession ( ourSession , configHandle ) ) ) ; } catch ( Exception e ) { configurationOwnerSupport . setConfigurationSession ( new ConfigConfigurationSession ( ourSession , configuration ) ) ; setOurSession ( null ) ; throw e ; } logger ( ) . debug ( "" ) ; } @ Override public boolean isLoadable ( ) { return ourSession == null ; } @ Override public void load ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { stateHandler . waitToWhen ( new IsNotExecuting ( ) , new Runnable ( ) { public void run ( ) { try { if ( ourSession != null ) { return ; } configure ( ) ; OddjobServices services = preLoadInitialisation ( ) ; doLoad ( services ) ; } catch ( Exception e ) { logger ( ) . error ( "" , e ) ; getStateChanger ( ) . setStateException ( e ) ; } } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override protected void execute ( ) throws Exception { if ( ourSession == null ) { OddjobServices services = preLoadInitialisation ( ) ; doLoad ( services ) ; if ( lastReset != null ) { switch ( lastReset ) { case SOFT : logger ( ) . debug ( "" ) ; childHelper . softResetChildren ( ) ; break ; case HARD : logger ( ) . debug ( "" ) ; childHelper . hardResetChildren ( ) ; break ; } lastReset = null ; } } Object child = childHelper . getChild ( ) ; if ( child != null && child instanceof Runnable ) { ( ( Runnable ) child ) . run ( ) ; } } @ Override public void unload ( ) { reset ( ) ; } private void reset ( ) { if ( ourSession == null ) { return ; } configurationOwnerSupport . setConfigurationSession ( null ) ; try { childHelper . stopChildren ( ) ; } catch ( FailedToStopException e ) { logger ( ) . warn ( "" , e ) ; } ComponentPersister persister = ourSession . getComponentPersister ( ) ; if ( persister != null ) { persister . close ( ) ; } ArooaContext oddjobContext = ourSession . getComponentPool ( ) . contextFor ( oddjobRoot ) ; if ( oddjobContext != null ) { oddjobContext . getRuntime ( ) . destroy ( ) ; } oddjobRoot = null ; setOurSession ( null ) ; } void stopExecutors ( ) { DefaultExecutors executors = internalExecutors ; if ( executors != null ) { executors . stop ( ) ; internalExecutors = null ; } } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; reset ( ) ; stopExecutors ( ) ; } @ Override public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; if ( ourSession == null ) { if ( lastReset == null ) { lastReset = Reset . SOFT ; if ( ! saveLastReset ( ) ) { return ; } } } else { lastReset = null ; } superSoftReset ( ) ; restored = false ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } private void superSoftReset ( ) { super . softReset ( ) ; } private boolean saveLastReset ( ) { if ( stateHandler . getState ( ) != ParentState . READY ) { return true ; } try { save ( ) ; } catch ( ComponentPersistException e ) { getStateChanger ( ) . setStateException ( e ) ; return false ; } return true ; } public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; if ( ourSession == null ) { lastReset = Reset . HARD ; if ( ! saveLastReset ( ) ) { return ; } } else { lastReset = null ; } childStateReflector . stop ( ) ; childHelper . hardResetChildren ( ) ; reset ( ) ; stop = false ; restored = false ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public OddjobPersister getPersister ( ) { return persister ; } public void setPersister ( OddjobPersister persister ) { this . persister = persister ; } @ Override public BeanDirectory provideBeanDirectory ( ) { if ( ourSession == null ) { return null ; } return ourSession . getBeanRegistry ( ) ; } public Reset getLastReset ( ) { return lastReset ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; String config = null ; ConfigurationSession session = provideConfigurationSession ( ) ; if ( session != null ) { DragPoint root = session . dragPointFor ( this ) ; if ( root != null ) { config = root . copy ( ) ; } } s . writeObject ( config ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; String config = ( String ) s . readObject ( ) ; if ( config != null ) { this . configuration = new XMLConfiguration ( "" , config ) ; this . restored = true ; } completeConstruction ( ) ; } public String [ ] getArgs ( ) { return args ; } public void setArgs ( String [ ] args ) { this . args = args ; } public ArooaValue getExport ( String key ) { return export . get ( key ) ; } public void setExport ( String key , ArooaValue value ) { if ( export == null ) { export = new LinkedHashMap < String , ArooaValue > ( ) ; } if ( value == null && export . containsKey ( key ) ) { export . remove ( key ) ; } else { ComponentBoundry . push ( loggerName ( ) , this ) ; try { logger ( ) . debug ( "" + key + "" + value ) ; export . put ( key , value ) ; } finally { ComponentBoundry . pop ( ) ; } } } public Properties getProperties ( ) { return properties ; } public void setProperties ( Properties properties ) { this . properties = properties ; } public OddjobInheritance getInheritance ( ) { return inheritance ; } public void setInheritance ( OddjobInheritance inheritance ) { this . inheritance = inheritance ; } public File getDir ( ) { if ( file == null ) { return null ; } return file . getAbsoluteFile ( ) . getParentFile ( ) ; } public String getVersion ( ) { return VERSION ; } public class OddjobRoot implements Stateful , ServiceProvider { private final OddjobServices oddjobServices ; OddjobRoot ( OddjobServices services ) { this . oddjobServices = services ; } public void setJob ( Object child ) { if ( child == null ) { logger ( ) . debug ( "" ) ; childHelper . removeChildAt ( ) ; } else { logger ( ) . debug ( "" + child + "" ) ; if ( Oddjob . this . childHelper . getChild ( ) != null ) { throw new OddjobConfigException ( "" ) ; } childHelper . insertChild ( , child ) ; } } public void addStateListener ( StateListener listener ) { Oddjob . this . addStateListener ( listener ) ; } public void removeStateListener ( StateListener listener ) { Oddjob . this . removeStateListener ( listener ) ; } @ Override public StateEvent lastStateEvent ( ) { return Oddjob . this . lastStateEvent ( ) ; } public File getFile ( ) { if ( file == null ) { return null ; } return file . getAbsoluteFile ( ) ; } public File getDir ( ) { if ( file == null ) { return null ; } return file . getAbsoluteFile ( ) . getParentFile ( ) ; } public Object [ ] getArgs ( ) { if ( args == null ) { return new String [ ] ; } else { return args ; } } public Services getServices ( ) { return oddjobServices ; } public ClassLoader getClassLoader ( ) { return oddjobServices . getClassLoader ( ) ; } } public static class OddjobRootArooa implements ArooaBeanDescriptor { public ParsingInterceptor getParsingInterceptor ( ) { return null ; } public String getTextProperty ( ) { return null ; } public String getComponentProperty ( ) { return "" ; } public ConfiguredHow getConfiguredHow ( String property ) { return ConfiguredHow . ELEMENT ; } public String getFlavour ( String property ) { return null ; } public boolean isAuto ( String property ) { return false ; } @ Override public ArooaAnnotations getAnnotations ( ) { return new NoAnnotations ( ) ; } } public ArooaDescriptorFactory getDescriptorFactory ( ) { return descriptorFactory ; } public void setDescriptorFactory ( ArooaDescriptorFactory descriptorFactory ) { this . descriptorFactory = descriptorFactory ; } public OddjobExecutors getOddjobExecutors ( ) { return oddjobExecutors ; } public void setOddjobExecutors ( OddjobExecutors executors ) { this . oddjobExecutors = executors ; } public OddjobServices getOddjobServices ( ) { return oddjobServices ; } @ Inject public void setOddjobServices ( OddjobServices oddjobServices ) { this . oddjobServices = oddjobServices ; } @ Override public String toString ( ) { String name = getName ( ) ; if ( name != null ) { return name ; } if ( file != null ) { return "" + file . getName ( ) ; } return getClass ( ) . getSimpleName ( ) ; } class OddjobConfigurationSession implements ConfigurationSession { private final ConfigurationSession delegate ; public OddjobConfigurationSession ( ConfigurationSession delegate ) { this . delegate = delegate ; } public DragPoint dragPointFor ( Object component ) { if ( component == Oddjob . this ) { component = Oddjob . this . oddjobRoot ; } return delegate . dragPointFor ( component ) ; } public ArooaDescriptor getArooaDescriptor ( ) { return delegate . getArooaDescriptor ( ) ; } public void save ( ) throws ArooaParseException { delegate . save ( ) ; } public boolean isModified ( ) { return delegate . isModified ( ) ; } public void addSessionStateListener ( SessionStateListener listener ) { delegate . addSessionStateListener ( listener ) ; } public void removeSessionStateListener ( SessionStateListener listener ) { delegate . removeSessionStateListener ( listener ) ; } } public InputHandler getInputHandler ( ) { return inputHandler ; } public void setInputHandler ( InputHandler inputHandler ) { this . inputHandler = inputHandler ; } } package org . oddjob . input ; import java . util . Properties ; public interface InputHandler { public Properties handleInput ( InputRequest [ ] requests ) ; } package org . oddjob . input ; import java . util . Properties ; public class ConsoleInputHandler implements InputHandler { @ Override public Properties handleInput ( InputRequest [ ] requests ) { if ( System . console ( ) == null ) { throw new IllegalStateException ( "" ) ; } Properties properties = new Properties ( ) ; for ( int i = ; i < requests . length ; ++ i ) { ConsoleInputMedium console = new ConsoleInputMedium ( ) ; requests [ i ] . render ( console ) ; String value = console . getValue ( ) ; if ( value == null ) { return null ; } String property = requests [ i ] . getProperty ( ) ; if ( property == null ) { continue ; } properties . setProperty ( property , value ) ; } return properties ; } static class ConsoleInputMedium extends TerminalInput { @ Override protected String doPrompt ( String prompt ) { return System . console ( ) . readLine ( prompt ) ; } @ Override protected String doPassword ( String prompt ) { char [ ] password = System . console ( ) . readPassword ( prompt ) ; if ( password == null ) { return null ; } else { return new String ( password ) ; } } } } package org . oddjob . input ; public interface InputRequest { public void render ( InputMedium medium ) ; public String getProperty ( ) ; } package org . oddjob . input ; import org . oddjob . arooa . design . screem . FileSelectionOptions ; public interface InputMedium { public void prompt ( String prompt , String defaultValue ) ; public void password ( String prompt ) ; public void confirm ( String message , Boolean defaultValue ) ; public void message ( String message ) ; public void file ( String message , String defaultValue , FileSelectionOptions options ) ; } package org . oddjob . input ; import java . io . FilterInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Properties ; public class StdInInputHandler implements InputHandler { @ Override public Properties handleInput ( InputRequest [ ] requests ) { if ( System . in == null ) { throw new IllegalStateException ( "" ) ; } LineReader in = new LineReader ( System . in ) ; Properties properties = new Properties ( ) ; for ( int i = ; i < requests . length ; ++ i ) { StdInInputMedium console = new StdInInputMedium ( in ) ; requests [ i ] . render ( console ) ; String value = console . getValue ( ) ; if ( value == null ) { return null ; } String property = requests [ i ] . getProperty ( ) ; if ( property == null ) { continue ; } properties . setProperty ( property , value ) ; System . out . println ( ) ; } return properties ; } class StdInInputMedium extends TerminalInput { private final LineReader in ; public StdInInputMedium ( LineReader in ) { this . in = in ; } @ Override protected String doPrompt ( String prompt ) { System . out . print ( prompt ) ; try { return in . readLine ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } @ Override protected String doPassword ( String prompt ) { return doPrompt ( prompt ) ; } } static class LineReader extends FilterInputStream { public LineReader ( InputStream in ) { super ( in ) ; } String readLine ( ) throws IOException { StringBuilder s = new StringBuilder ( ) ; while ( true ) { int c = read ( ) ; if ( c < ) { return null ; } if ( c == '' ) { continue ; } if ( c == '' ) { return s . toString ( ) ; } s . append ( ( char ) c ) ; } } } } package org . oddjob . input ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . ArrayList ; import java . util . List ; import java . util . Properties ; import javax . inject . Inject ; import org . apache . log4j . Logger ; import org . oddjob . arooa . utils . ListSetterHelper ; import org . oddjob . values . properties . PropertiesJobBase ; public class InputJob extends PropertiesJobBase { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( InputJob . class ) ; private transient InputHandler inputHandler ; private transient List < InputRequest > requests ; public InputJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { requests = new ArrayList < InputRequest > ( ) ; } @ Override protected int execute ( ) { if ( inputHandler == null ) { throw new NullPointerException ( "" ) ; } Properties props = null ; InputRequest [ ] requestsArray = requests . toArray ( new InputRequest [ requests . size ( ) ] ) ; props = inputHandler . handleInput ( requestsArray ) ; if ( props == null ) { logger . info ( "" ) ; return ; } else { logger . info ( "" + props . size ( ) + "" ) ; setProperties ( props ) ; addPropertyLookup ( ) ; return ; } } public InputHandler getInputHandler ( ) { return inputHandler ; } @ Inject public void setInputHandler ( InputHandler inputHandler ) { this . inputHandler = inputHandler ; } public InputRequest getRequests ( int index ) { return requests . get ( index ) ; } public void setRequests ( int index , InputRequest request ) { new ListSetterHelper < InputRequest > ( requests ) . set ( index , request ) ; } @ Override protected boolean isOverride ( ) { return true ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; completeConstruction ( ) ; } } package org . oddjob . input . requests ; import java . io . File ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . design . screem . FileSelectionOptions ; import org . oddjob . arooa . design . screem . FileSelectionOptions . SelectionMode ; import org . oddjob . input . InputMedium ; public class InputFile extends BaseInputRequest { private String prompt ; private String defaultName ; private final FileSelectionOptions options = new FileSelectionOptions ( ) ; @ Override public void render ( InputMedium medium ) { medium . file ( prompt , defaultName , options ) ; } public String getPrompt ( ) { return prompt ; } public void setPrompt ( String prompt ) { this . prompt = prompt ; } public String getDefault ( ) { return defaultName ; } @ ArooaAttribute public void setDefault ( String defaultValue ) { this . defaultName = defaultValue ; } public File getCurrentDirectory ( ) { return options . getCurrentDirectory ( ) ; } @ ArooaAttribute public void setCurrentDirectory ( File currentDirectory ) { options . setCurrentDirectory ( currentDirectory ) ; } public SelectionMode getSelectionMode ( ) { return options . getSelectionMode ( ) ; } public void setSelectionMode ( SelectionMode selectionMode ) { options . setSelectionMode ( selectionMode ) ; } public String getFileFilterDescription ( ) { return options . getFileFilterDescription ( ) ; } public void setFileFilterDescription ( String fileFilterDescription ) { options . setFileFilterDescription ( fileFilterDescription ) ; } public String [ ] getFileFilterExtensions ( ) { return options . getFileFilterExtensions ( ) ; } @ ArooaAttribute public void setFileFilterExtensions ( String [ ] fileFilterExtensions ) { options . setFileFilterExtensions ( fileFilterExtensions ) ; } } package org . oddjob . input . requests ; import org . oddjob . input . InputMedium ; public class InputConfirm extends BaseInputRequest { private String prompt ; private Boolean defaultValue ; @ Override public void render ( InputMedium medium ) { medium . confirm ( prompt , defaultValue ) ; } public String getPrompt ( ) { return prompt ; } public void setPrompt ( String prompt ) { this . prompt = prompt ; } public Boolean getDefault ( ) { return defaultValue ; } public void setDefault ( Boolean defaultValue ) { this . defaultValue = defaultValue ; } } package org . oddjob . input . requests ; import org . oddjob . input . InputRequest ; abstract public class BaseInputRequest implements InputRequest { private String property ; public String getProperty ( ) { return property ; } public void setProperty ( String property ) { this . property = property ; } } package org . oddjob . input . requests ; import org . oddjob . arooa . deploy . annotations . ArooaText ; import org . oddjob . input . InputMedium ; import org . oddjob . input . InputRequest ; public class InputMessage implements InputRequest { private String message ; @ Override public void render ( InputMedium medium ) { medium . message ( message ) ; } public String getMessage ( ) { return message ; } @ ArooaText public void setMessage ( String prompt ) { this . message = prompt ; } @ Override public String getProperty ( ) { return null ; } } package org . oddjob . input . requests ; import org . oddjob . input . InputMedium ; public class InputText extends BaseInputRequest { private String prompt ; private String defaultValue ; @ Override public void render ( InputMedium medium ) { medium . prompt ( prompt , defaultValue ) ; } public String getPrompt ( ) { return prompt ; } public void setPrompt ( String prompt ) { this . prompt = prompt ; } public String getDefault ( ) { return defaultValue ; } public void setDefault ( String defaultValue ) { this . defaultValue = defaultValue ; } } package org . oddjob . input . requests ; import org . oddjob . input . InputMedium ; public class InputPassword extends BaseInputRequest { private String prompt ; @ Override public void render ( InputMedium medium ) { medium . password ( prompt ) ; } public String getPrompt ( ) { return prompt ; } public void setPrompt ( String prompt ) { this . prompt = prompt ; } } package org . oddjob . input ; import java . io . File ; import java . io . IOException ; import org . oddjob . arooa . design . screem . FileSelectionOptions ; abstract class TerminalInput implements InputMedium { private String value ; @ Override public void prompt ( String prompt , String defaultValue ) { StringBuilder promptBuilder = new StringBuilder ( ) ; if ( prompt != null ) { promptBuilder . append ( prompt ) ; } promptBuilder . append ( "" ) ; if ( defaultValue != null ) { promptBuilder . append ( "" + defaultValue + "" ) ; } String value = doPrompt ( promptBuilder . toString ( ) ) ; if ( value == null ) { this . value = null ; } else if ( value . length ( ) == && defaultValue != null ) { this . value = defaultValue ; } else { this . value = value ; } } @ Override public void password ( String prompt ) { StringBuilder promptBuilder = new StringBuilder ( ) ; if ( prompt != null ) { promptBuilder . append ( prompt ) ; } promptBuilder . append ( "" ) ; this . value = doPassword ( promptBuilder . toString ( ) ) ; } @ Override public void confirm ( String message , Boolean defaultValue ) { StringBuilder promptBuilder = new StringBuilder ( ) ; if ( message != null ) { promptBuilder . append ( message ) ; promptBuilder . append ( '' ) ; } promptBuilder . append ( "" ) ; promptBuilder . append ( "" ) ; if ( defaultValue != null ) { promptBuilder . append ( "" + ( defaultValue ? "" : "" ) + "" ) ; } do { String value = doPrompt ( promptBuilder . toString ( ) ) ; if ( value == null ) { this . value = null ; break ; } else if ( value . length ( ) == && defaultValue != null ) { this . value = defaultValue . toString ( ) ; } else { if ( value . toUpperCase ( ) . matches ( "" ) ) { this . value = Boolean . TRUE . toString ( ) ; } else if ( value . toUpperCase ( ) . matches ( "" ) ) { this . value = Boolean . FALSE . toString ( ) ; } } } while ( this . value == null ) ; } @ Override public void message ( String message ) { this . value = doPrompt ( ( message == null ? "" : message ) + "" ) ; } @ Override public void file ( String prompt , String defaultValue , FileSelectionOptions options ) { while ( true ) { StringBuilder promptBuilder = new StringBuilder ( ) ; if ( prompt != null ) { promptBuilder . append ( prompt ) ; } promptBuilder . append ( "" ) ; if ( defaultValue != null ) { promptBuilder . append ( "" + defaultValue + "" ) ; } String value = doPrompt ( promptBuilder . toString ( ) ) ; File file ; if ( value == null ) { file = null ; } else if ( value . length ( ) == && defaultValue != null ) { file = new File ( options . getCurrentDirectory ( ) , defaultValue ) ; } else { file = new File ( options . getCurrentDirectory ( ) , value ) ; } if ( file == null ) { this . value = null ; break ; } else { try { this . value = file . getCanonicalPath ( ) ; break ; } catch ( IOException e ) { System . err . println ( e . toString ( ) ) ; } } } } protected abstract String doPrompt ( String prompt ) ; protected abstract String doPassword ( String prompt ) ; public String getValue ( ) { return value ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class CountScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new CountScheduleDesign ( element , parentContext ) ; } } class CountScheduleDesign extends ParentSchedule { private final SimpleTextAttribute count ; private final SimpleTextAttribute identifier ; public CountScheduleDesign ( ArooaElement element , ArooaContext context ) { super ( element , context ) ; count = new SimpleTextAttribute ( "" , this ) ; identifier = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( ) . add ( count . view ( ) . setTitle ( "" ) ) . add ( identifier . view ( ) . setTitle ( "" ) ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { count , identifier , getRefinement ( ) } ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class AfterScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new AfterScheduleDesign ( element , parentContext ) ; } } class AfterScheduleDesign extends ParentSchedule { private final SimpleDesignProperty schedule ; public AfterScheduleDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; schedule = new SimpleDesignProperty ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { getRefinement ( ) , schedule } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( ) . add ( schedule . view ( ) . setTitle ( "" ) ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class DateScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new DateScheduleDesign ( element , parentContext ) ; } } class DateScheduleDesign extends ParentSchedule { private final SimpleTextAttribute on ; private final SimpleTextAttribute from ; private final SimpleTextAttribute to ; public DateScheduleDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; on = new SimpleTextAttribute ( "" , this ) ; from = new SimpleTextAttribute ( "" , this ) ; to = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( from . view ( ) . setTitle ( "" ) ) . add ( to . view ( ) . setTitle ( "" ) ) ) . add ( on . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { on , from , to , getRefinement ( ) } ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class DailyScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new DailyScheduleDesign ( element , parentContext ) ; } } class DailyScheduleDesign extends ParentSchedule { private final SimpleTextAttribute at ; private final SimpleTextAttribute from ; private final SimpleTextAttribute to ; public DailyScheduleDesign ( ArooaElement element , ArooaContext context ) { super ( element , context ) ; at = new SimpleTextAttribute ( "" , this ) ; from = new SimpleTextAttribute ( "" , this ) ; to = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( from . view ( ) . setTitle ( "" ) ) . add ( to . view ( ) . setTitle ( "" ) ) ) . add ( at . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { at , from , to , getRefinement ( ) } ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class TimeScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new TimeScheduleDesign ( element , parentContext ) ; } } class TimeScheduleDesign extends ParentSchedule { private final SimpleTextAttribute at ; private final SimpleTextAttribute from ; private final SimpleTextAttribute to ; private final SimpleTextAttribute toLast ; public TimeScheduleDesign ( ArooaElement element , ArooaContext context ) { super ( element , context ) ; at = new SimpleTextAttribute ( "" , this ) ; from = new SimpleTextAttribute ( "" , this ) ; to = new SimpleTextAttribute ( "" , this ) ; toLast = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( from . view ( ) . setTitle ( "" ) ) . add ( to . view ( ) . setTitle ( "" ) ) . add ( toLast . view ( ) . setTitle ( "" ) ) ) . add ( at . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { at , from , to , toLast , getRefinement ( ) } ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; abstract public class ParentSchedule extends DesignValueBase { private final SimpleDesignProperty refinement ; public ParentSchedule ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; refinement = new SimpleDesignProperty ( "" , this ) ; } protected DesignProperty getRefinement ( ) { return refinement ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class DayOfWeekScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new DayOfWeekScheduleDesign ( element , parentContext ) ; } } class DayOfWeekScheduleDesign extends ParentSchedule { private final SimpleTextAttribute on ; private final SimpleTextAttribute from ; private final SimpleTextAttribute to ; public DayOfWeekScheduleDesign ( ArooaElement element , ArooaContext context ) { super ( element , context ) ; on = new SimpleTextAttribute ( "" , this ) ; from = new SimpleTextAttribute ( "" , this ) ; to = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( from . view ( ) . setTitle ( "" ) ) . add ( to . view ( ) . setTitle ( "" ) ) ) . add ( on . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { on , from , to , getRefinement ( ) } ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class BrokenScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new BrokenScheduleDesign ( element , parentContext ) ; } } class BrokenScheduleDesign extends DesignValueBase { private final SimpleDesignProperty schedule ; private final SimpleDesignProperty breaks ; private final SimpleDesignProperty alternative ; public BrokenScheduleDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; schedule = new SimpleDesignProperty ( "" , this ) ; breaks = new SimpleDesignProperty ( "" , this ) ; alternative = new SimpleDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( ) . add ( schedule . view ( ) . setTitle ( "" ) ) . add ( breaks . view ( ) . setTitle ( "" ) ) . add ( alternative . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { schedule , breaks , alternative } ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class OccurrenceScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new OccurrenceScheduleDesign ( element , parentContext ) ; } } class OccurrenceScheduleDesign extends ParentSchedule { private final SimpleTextAttribute occurrence ; public OccurrenceScheduleDesign ( ArooaElement element , ArooaContext context ) { super ( element , context ) ; occurrence = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( toString ( ) ) . add ( occurrence . view ( ) . setTitle ( "" ) ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { occurrence , getRefinement ( ) } ; } public String toString ( ) { return "" + occurrence . attribute ( ) == null ? "" : occurrence . attribute ( ) ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class MonthlyScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new MonthlyScheduleDesign ( element , parentContext ) ; } } class MonthlyScheduleDesign extends ParentSchedule { private final SimpleTextAttribute onDay ; private final SimpleTextAttribute fromDay ; private final SimpleTextAttribute toDay ; private final SimpleTextAttribute inWeek ; private final SimpleTextAttribute fromWeek ; private final SimpleTextAttribute toWeek ; private final SimpleTextAttribute onDayOfWeek ; private final SimpleTextAttribute fromDayOfWeek ; private final SimpleTextAttribute toDayOfWeek ; public MonthlyScheduleDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; onDay = new SimpleTextAttribute ( "" , this ) ; fromDay = new SimpleTextAttribute ( "" , this ) ; toDay = new SimpleTextAttribute ( "" , this ) ; inWeek = new SimpleTextAttribute ( "" , this ) ; fromWeek = new SimpleTextAttribute ( "" , this ) ; toWeek = new SimpleTextAttribute ( "" , this ) ; onDayOfWeek = new SimpleTextAttribute ( "" , this ) ; fromDayOfWeek = new SimpleTextAttribute ( "" , this ) ; toDayOfWeek = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( fromDay . view ( ) . setTitle ( "" ) ) . add ( toDay . view ( ) . setTitle ( "" ) ) ) . add ( onDay . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( fromWeek . view ( ) . setTitle ( "" ) ) . add ( toWeek . view ( ) . setTitle ( "" ) ) ) . add ( inWeek . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( fromDayOfWeek . view ( ) . setTitle ( "" ) ) . add ( toDayOfWeek . view ( ) . setTitle ( "" ) ) ) . add ( onDayOfWeek . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { onDay , fromDay , toDay , inWeek , fromWeek , toWeek , onDayOfWeek , fromDayOfWeek , toDayOfWeek , getRefinement ( ) } ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class LastScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new LastScheduleDesign ( element , parentContext ) ; } } class LastScheduleDesign extends ParentSchedule { public LastScheduleDesign ( ArooaElement element , ArooaContext context ) { super ( element , context ) ; } public String toString ( ) { return "" ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { getRefinement ( ) } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class IntervalScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new IntervalScheduleDesign ( element , parentContext ) ; } } class IntervalScheduleDesign extends DesignValueBase { private final SimpleTextAttribute interval ; public IntervalScheduleDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; interval = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( ) . add ( interval . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { interval } ; } } package org . oddjob . designer . elements . schedule ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class YearlyScheduleDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new YearlyScheduleDesign ( element , parentContext ) ; } } class YearlyScheduleDesign extends ParentSchedule { private final SimpleTextAttribute onDate ; private final SimpleTextAttribute fromDate ; private final SimpleTextAttribute toDate ; private final SimpleTextAttribute inMonth ; private final SimpleTextAttribute fromMonth ; private final SimpleTextAttribute toMonth ; public YearlyScheduleDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; onDate = new SimpleTextAttribute ( "" , this ) ; fromDate = new SimpleTextAttribute ( "" , this ) ; toDate = new SimpleTextAttribute ( "" , this ) ; inMonth = new SimpleTextAttribute ( "" , this ) ; fromMonth = new SimpleTextAttribute ( "" , this ) ; toMonth = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( fromDate . view ( ) . setTitle ( "" ) ) . add ( toDate . view ( ) . setTitle ( "" ) ) ) . add ( onDate . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( new FieldGroup ( ) . add ( fromMonth . view ( ) . setTitle ( "" ) ) . add ( toMonth . view ( ) . setTitle ( "" ) ) ) . add ( inMonth . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( ) . add ( getRefinement ( ) . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { onDate , fromDate , toDate , inMonth , fromMonth , toMonth , getRefinement ( ) } ; } } package org . oddjob . designer . elements ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . IndexedDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class FilesDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new FilesDesign ( element , parentContext ) ; } } class FilesDesign extends DesignValueBase { private final SimpleTextAttribute files ; private final IndexedDesignProperty list ; public FilesDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; files = new SimpleTextAttribute ( "" , this ) ; list = new IndexedDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( files . view ( ) . setTitle ( "" ) ) . add ( list . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { files , list } ; } } package org . oddjob . designer . elements ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class FormatDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new FormatDesign ( element , parentContext ) ; } } class FormatDesign extends DesignValueBase { private final SimpleTextAttribute format ; private final SimpleTextAttribute timeZone ; private final SimpleTextAttribute date ; private final SimpleTextAttribute number ; public FormatDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; format = new SimpleTextAttribute ( "" , this ) ; timeZone = new SimpleTextAttribute ( "" , this ) ; date = new SimpleTextAttribute ( "" , this ) ; number = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( toString ( ) ) . add ( format . view ( ) . setTitle ( "" ) ) . add ( new FieldSelection ( ) . add ( new BorderedGroup ( "" ) . add ( date . view ( ) . setTitle ( "" ) ) . add ( timeZone . view ( ) . setTitle ( "" ) ) ) . add ( number . view ( ) . setTitle ( "" ) ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { format , timeZone , date , number } ; } public String toString ( ) { return "" ; } } package org . oddjob . designer . elements ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . etc . FileAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . io . FileType ; public class FileOutputDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new FileDesign ( element , parentContext ) ; } } class FileOutputDesign extends DesignValueBase { private final FileAttribute file ; private final SimpleTextAttribute append ; public FileOutputDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; file = new FileAttribute ( "" , this ) ; append = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( file . view ( ) . setTitle ( "" ) ) . add ( append . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { file , append } ; } } package org . oddjob . designer . elements ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class EnvironmentDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new EnvironmentDesign ( element , parentContext ) ; } } class EnvironmentDesign extends DesignValueBase { private SimpleTextAttribute name ; public EnvironmentDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; name = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( name . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name } ; } } package org . oddjob . designer . elements ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class ConnectionDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ConnectionDesign ( element , parentContext ) ; } } class ConnectionDesign extends DesignValueBase { private final SimpleTextAttribute driver = new SimpleTextAttribute ( "" , this ) ; private final SimpleTextAttribute url = new SimpleTextAttribute ( "" , this ) ; private final SimpleTextAttribute username = new SimpleTextAttribute ( "" , this ) ; private final SimpleTextAttribute password = new SimpleTextAttribute ( "" , this ) ; private final SimpleDesignProperty classLoader = new SimpleDesignProperty ( "" , this ) ; public ConnectionDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { driver , url , username , password , classLoader } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( driver . view ( ) . setTitle ( "" ) ) . add ( url . view ( ) . setTitle ( "" ) ) . add ( username . view ( ) . setTitle ( "" ) ) . add ( password . view ( ) . setTitle ( "" ) ) . add ( classLoader . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . designer . elements ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . etc . FileAttribute ; import org . oddjob . arooa . design . screem . FileSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class FileDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new FileDesign ( element , parentContext ) ; } } class FileDesign extends DesignValueBase { private FileAttribute file ; public FileDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; file = new FileAttribute ( "" , this ) ; } public Form detail ( ) { return new FileSelection ( "" , file ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { file } ; } } package org . oddjob . designer . elements ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . DesignValueBase ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class DateDE implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new DateDesign ( element , parentContext ) ; } } class DateDesign extends DesignValueBase { private final SimpleTextAttribute date ; private final SimpleTextAttribute format ; private final SimpleTextAttribute timeZone ; public DateDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; date = new SimpleTextAttribute ( "" , this ) ; format = new SimpleTextAttribute ( "" , this ) ; timeZone = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( date . view ( ) . setTitle ( "" ) ) . add ( format . view ( ) . setTitle ( "" ) ) . add ( timeZone . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { date , format , timeZone } ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . jmx . JMXClientJob ; public class ClientDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ClientDesign ( element , parentContext ) ; } } class ClientDesign extends BaseDC { private final SimpleTextAttribute connection ; private final SimpleDesignProperty environment ; private final SimpleTextAttribute heartbeat ; private final SimpleTextAttribute maxLoggerLines ; private final SimpleTextAttribute maxConsoleLines ; private final SimpleTextAttribute logPollingInterval ; public ClientDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; connection = new SimpleTextAttribute ( "" , this ) ; environment = new SimpleDesignProperty ( "" , this ) ; heartbeat = new SimpleTextAttribute ( "" , this ) ; maxLoggerLines = new SimpleTextAttribute ( "" , this ) ; maxConsoleLines = new SimpleTextAttribute ( "" , this ) ; logPollingInterval = new SimpleTextAttribute ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , connection , environment , heartbeat , maxLoggerLines , maxConsoleLines , logPollingInterval } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( connection . view ( ) . setTitle ( "" ) ) . add ( environment . view ( ) . setTitle ( "" ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( heartbeat . view ( ) . setTitle ( "" ) ) . add ( maxLoggerLines . view ( ) . setTitle ( "" ) ) . add ( maxConsoleLines . view ( ) . setTitle ( "" ) ) . add ( logPollingInterval . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TextField ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class RenameDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new RenameDesign ( element , parentContext ) ; } } class RenameDesign extends BaseDC { private final SimpleTextAttribute from ; private final SimpleTextAttribute to ; public RenameDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; from = new SimpleTextAttribute ( "" , this ) ; to = new SimpleTextAttribute ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , from , to } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new TextField ( "" , from ) ) . add ( new TextField ( "" , to ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . IndexedDesignProperty ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class FolderDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new FolderDesign ( element , parentContext ) ; } } class FolderDesign extends BaseDC { private final IndexedDesignProperty jobs ; public FolderDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; jobs = new IndexedDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( jobs . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , jobs } ; } } package org . oddjob . designer . components ; import java . io . Serializable ; import org . oddjob . Oddjob ; import org . oddjob . arooa . design . DesignComponentBase ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class RootDC implements DesignFactory , Serializable { private static final long serialVersionUID = ; public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new RootDesign ( element , parentContext ) ; } } class RootDesign extends DesignComponentBase { private final SimpleDesignProperty job ; public RootDesign ( ArooaElement element , ArooaContext context ) { super ( element , new SimpleArooaClass ( Oddjob . OddjobRoot . class ) , context ) ; job = new SimpleDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( job . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { job } ; } public String toString ( ) { return "" ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . IndexedDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TextField ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class SequentialDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new SequentialDesign ( element , parentContext ) ; } } class SequentialDesign extends BaseDC { private final SimpleTextAttribute independent ; private final IndexedDesignProperty jobs ; public SequentialDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; jobs = new IndexedDesignProperty ( "" , this ) ; independent = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( jobs . view ( ) . setTitle ( "" ) ) ) ; } @ Override public BorderedGroup basePanel ( ) { BorderedGroup bg = super . basePanel ( ) ; bg . add ( new TextField ( "" , independent ) ) ; return bg ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , independent , jobs } ; } } package org . oddjob . designer . components ; import java . awt . Component ; import java . awt . Container ; import java . awt . GridBagConstraints ; import java . awt . Insets ; import java . util . ArrayList ; import java . util . List ; import java . util . TreeSet ; import org . oddjob . arooa . ArooaConstants ; import org . oddjob . arooa . ArooaException ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . ElementMappings ; import org . oddjob . arooa . design . DesignComponent ; import org . oddjob . arooa . design . DesignElementProperty ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignListener ; import org . oddjob . arooa . design . DesignStructureEvent ; import org . oddjob . arooa . design . InstanceSupport ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . FormItem ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . view . DesignViewException ; import org . oddjob . arooa . design . view . SwingFormFactory ; import org . oddjob . arooa . design . view . SwingItemFactory ; import org . oddjob . arooa . design . view . SwingItemView ; import org . oddjob . arooa . design . view . multitype . AbstractMultiTypeModel ; import org . oddjob . arooa . design . view . multitype . EditableValue ; import org . oddjob . arooa . design . view . multitype . MultiTypeRow ; import org . oddjob . arooa . design . view . multitype . MultiTypeStrategy ; import org . oddjob . arooa . design . view . multitype . MultiTypeTableWidget ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . AbstractConfigurationNode ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . ArooaHandler ; import org . oddjob . arooa . parsing . CutAndPasteSupport ; import org . oddjob . arooa . parsing . PrefixMappings ; import org . oddjob . arooa . parsing . QTag ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . runtime . AbstractRuntimeConfiguration ; import org . oddjob . arooa . runtime . ConfigurationNode ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . values . VariablesJob ; public class VariablesDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new VariablesDesign ( element , parentContext ) ; } } class VariablesDesign implements DesignComponent { final List < PropertyValuePair > properties = new ArrayList < PropertyValuePair > ( ) ; private String id ; private ArooaContext context ; private ArooaElement element ; private List < VariablesListener > listeners = new ArrayList < VariablesListener > ( ) ; public VariablesDesign ( ArooaElement element , ArooaContext parentContext ) { this . element = element ; this . id = element . getAttributes ( ) . get ( ArooaConstants . ID_PROPERTY ) ; this . context = new VariablesDesignContext ( this , parentContext ) ; } public ArooaElement element ( ) { return element ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( new VariablesGrid ( this ) ) ) ; } @ Override public String getId ( ) { return id ; } @ Override public void setId ( String id ) { this . id = id ; } public void addStructuralListener ( DesignListener listener ) { } public void removeStructuralListener ( DesignListener listener ) { } public ArooaContext getArooaContext ( ) { return context ; } @ Override public String toString ( ) { if ( id == null ) { return "" ; } return id ; } void addVariablesListener ( VariablesListener listener ) { synchronized ( listeners ) { for ( int i = ; i < properties . size ( ) ; ++ i ) { listener . variableAdded ( i ) ; } listeners . add ( listener ) ; } } void addProperty ( int index , VariablesDesignProperty property ) { synchronized ( listeners ) { properties . add ( index , new PropertyValuePair ( property ) ) ; for ( VariablesListener listener : listeners ) { listener . variableAdded ( index ) ; } } } void removeProperty ( int index ) { synchronized ( listeners ) { properties . remove ( index ) ; for ( VariablesListener listener : listeners ) { listener . variableRemoved ( index ) ; } } } DesignInstance instanceAt ( int index ) { return properties . get ( index ) . getValue ( ) ; } VariablesDesignProperty propertyAt ( int index ) { return properties . get ( index ) . getProperty ( ) ; } int propertyCount ( ) { return properties . size ( ) ; } } class PropertyValuePair { private final VariablesDesignProperty property ; private DesignInstance value ; PropertyValuePair ( VariablesDesignProperty property ) { this . property = property ; property . addDesignListener ( new DesignListener ( ) { public void childAdded ( DesignStructureEvent event ) { value = event . getChild ( ) ; } public void childRemoved ( DesignStructureEvent event ) { value = null ; } } ) ; } VariablesDesignProperty getProperty ( ) { return property ; } DesignInstance getValue ( ) { return value ; } } interface VariablesListener { void variableAdded ( int index ) ; void variableRemoved ( int index ) ; } class VariablesDesignProperty extends SimpleDesignProperty { private String property ; public VariablesDesignProperty ( String property , Class < ? > propertyClass , ArooaType type , DesignInstance parent ) { super ( null , propertyClass , type , parent ) ; this . property = property ; } @ Override public String property ( ) { return property ; } void changePropertyName ( String name ) { this . property = name ; } } class VariablesDesignContext implements ArooaContext { private final ArooaContext parent ; private final VariablesDesign variables ; private final ConfigurationNode configurationNode = new AbstractConfigurationNode ( ) { public ArooaContext getContext ( ) { return VariablesDesignContext . this ; } public void addText ( String text ) { String trimmedText = text . trim ( ) ; if ( trimmedText . length ( ) > ) { throw new ArooaException ( "" + trimmedText ) ; } } public ConfigurationHandle parse ( ArooaContext parentContext ) throws ArooaParseException { ArooaElement element = new ArooaElement ( variables . element ( ) . getUri ( ) , variables . element ( ) . getTag ( ) ) ; String id = variables . getId ( ) ; if ( id != null && id . length ( ) > ) { element = element . addAttribute ( ArooaConstants . ID_PROPERTY , id ) ; } ArooaContext nextContext = parentContext . getArooaHandler ( ) . onStartElement ( element , parentContext ) ; for ( int i = ; i < variables . propertyCount ( ) ; ++ i ) { DesignElementProperty property = variables . propertyAt ( i ) ; property . getArooaContext ( ) . getConfigurationNode ( ) . parse ( nextContext ) ; } int index = parentContext . getConfigurationNode ( ) . insertChild ( nextContext . getConfigurationNode ( ) ) ; try { nextContext . getRuntime ( ) . init ( ) ; } catch ( RuntimeException e ) { parentContext . getConfigurationNode ( ) . removeChild ( index ) ; throw e ; } return new ChainingConfigurationHandle ( getContext ( ) , parentContext , index ) ; } } ; private final RuntimeConfiguration runtime = new AbstractRuntimeConfiguration ( ) { public void init ( ) { fireBeforeInit ( ) ; RuntimeConfiguration parentRuntime = parent . getRuntime ( ) ; if ( parentRuntime != null ) { int index = parent . getConfigurationNode ( ) . indexOf ( configurationNode ) ; if ( index < ) { throw new IllegalStateException ( "" ) ; } parentRuntime . setIndexedProperty ( null , index , variables ) ; } fireAfterInit ( ) ; } public void configure ( ) { fireBeforeConfigure ( ) ; fireAfterConfigure ( ) ; } public void destroy ( ) { fireBeforeDestroy ( ) ; RuntimeConfiguration parentRuntime = parent . getRuntime ( ) ; if ( parentRuntime != null ) { int index = parent . getConfigurationNode ( ) . indexOf ( configurationNode ) ; if ( index < ) { throw new IllegalStateException ( "" ) ; } parentRuntime . setIndexedProperty ( null , index , null ) ; } fireAfterDestroy ( ) ; } public void setProperty ( String name , Object value ) throws ArooaException { throw new UnsupportedOperationException ( "" ) ; } public void setIndexedProperty ( String name , int index , Object value ) throws ArooaException { if ( value == null ) { variables . removeProperty ( index ) ; } else { variables . addProperty ( index , ( VariablesDesignProperty ) value ) ; } } public void setMappedProperty ( String name , String key , Object value ) throws ArooaException { throw new UnsupportedOperationException ( "" ) ; } public ArooaClass getClassIdentifier ( ) { return new SimpleArooaClass ( VariablesJob . class ) ; } } ; VariablesDesignContext ( VariablesDesign variables , ArooaContext parent ) { this . parent = parent ; this . variables = variables ; } public ArooaType getArooaType ( ) { return ArooaType . VALUE ; } public ArooaContext getParent ( ) { return parent ; } public RuntimeConfiguration getRuntime ( ) { return runtime ; } public PrefixMappings getPrefixMappings ( ) { return parent . getPrefixMappings ( ) ; } public ArooaSession getSession ( ) { return parent . getSession ( ) ; } public ConfigurationNode getConfigurationNode ( ) { return configurationNode ; } public ArooaHandler getArooaHandler ( ) { return new ArooaHandler ( ) { public ArooaContext onStartElement ( ArooaElement element , ArooaContext parentContext ) throws ArooaException { if ( variables . properties . contains ( element . getTag ( ) ) ) { throw new ArooaException ( "" + element ) ; } if ( element . getAttributes ( ) . getAttributNames ( ) . length > ) { throw new ArooaException ( "" + element . getAttributes ( ) . getAttributNames ( ) [ ] ) ; } VariablesDesignProperty property = new VariablesDesignProperty ( element . getTag ( ) , Object . class , ArooaType . VALUE , variables ) ; return property . getArooaContext ( ) ; } } ; } } class VariablesGrid implements FormItem { static { SwingItemFactory . register ( VariablesGrid . class , new SwingItemFactory < VariablesGrid > ( ) { public SwingItemView onCreate ( VariablesGrid viewModel ) { return new VariablesTableView ( viewModel ) ; } } ) ; } private String title ; private final VariablesDesign variables ; public VariablesGrid ( VariablesDesign variables ) { this . variables = variables ; } public VariablesDesign getVariables ( ) { return variables ; } public String getTitle ( ) { return title ; } public boolean isPopulated ( ) { return true ; } public FormItem setTitle ( String title ) { this . title = title ; return this ; } } class VariablesModel extends AbstractMultiTypeModel { public static final QTag NULL_TAG = new QTag ( "" ) ; private final QTag [ ] supportedTypes ; private final List < VariableRow > variableRows = new ArrayList < VariableRow > ( ) ; private final VariablesDesign variables ; public VariablesModel ( VariablesGrid variablesGrid ) { this . variables = variablesGrid . getVariables ( ) ; variables . addVariablesListener ( new VariablesListener ( ) { @ Override public void variableAdded ( final int index ) { final VariableRow variableRow = new VariableRow ( index ) ; variableRows . add ( index , variableRow ) ; fireRowInserted ( index ) ; variables . propertyAt ( index ) . addDesignListener ( new DesignListener ( ) { public void childAdded ( DesignStructureEvent event ) { variableRow . setInstance ( event . getChild ( ) ) ; fireRowChanged ( index ) ; } public void childRemoved ( DesignStructureEvent event ) { variableRow . setInstance ( null ) ; fireRowChanged ( index ) ; } } ) ; } public void variableRemoved ( int index ) { variableRows . remove ( index ) ; fireRowRemoved ( index ) ; } } ) ; ArooaContext context = variables . getArooaContext ( ) ; ElementMappings mappings = context . getSession ( ) . getArooaDescriptor ( ) . getElementMappings ( ) ; InstantiationContext instantiationContext = new InstantiationContext ( ArooaType . VALUE , new SimpleArooaClass ( ArooaValue . class ) ) ; ArooaElement [ ] supportedElements = mappings . elementsFor ( instantiationContext ) ; TreeSet < QTag > sortedTypes = new TreeSet < QTag > ( ) ; for ( ArooaElement element : supportedElements ) { sortedTypes . add ( new QTag ( element , context ) ) ; } this . supportedTypes = sortedTypes . toArray ( new QTag [ sortedTypes . size ( ) ] ) ; } @ Override public Object getDeleteOption ( ) { return NULL_TAG ; } @ Override public Object [ ] getTypeOptions ( ) { return supportedTypes ; } @ Override public void createRow ( Object creator , int row ) { insertProperty ( row , ( String ) creator ) ; } @ Override public void swapRow ( int from , int direction ) { ArooaContext propertyContext = variables . propertyAt ( from ) . getArooaContext ( ) ; ArooaContext parentContext = propertyContext . getParent ( ) ; CutAndPasteSupport . cut ( parentContext , propertyContext ) ; int to = from + direction ; try { CutAndPasteSupport . paste ( parentContext , to , propertyContext . getConfigurationNode ( ) ) ; } catch ( ArooaParseException e ) { throw new DesignViewException ( e ) ; } } @ Override public void removeRow ( int index ) { removeProperty ( variables . propertyAt ( index ) ) ; } @ Override public MultiTypeRow getRow ( int index ) { return variableRows . get ( index ) ; } @ Override public int getRowCount ( ) { return variableRows . size ( ) ; } void removeProperty ( DesignElementProperty property ) { property . getArooaContext ( ) . getRuntime ( ) . destroy ( ) ; ConfigurationNode configurationNode = variables . getArooaContext ( ) . getConfigurationNode ( ) ; int index = configurationNode . indexOf ( property . getArooaContext ( ) . getConfigurationNode ( ) ) ; if ( index < ) { throw new IllegalStateException ( "" ) ; } configurationNode . removeChild ( index ) ; } void insertProperty ( int index , String property ) { variables . getArooaContext ( ) . getConfigurationNode ( ) . setInsertPosition ( index ) ; ArooaContext nextContext = variables . getArooaContext ( ) . getArooaHandler ( ) . onStartElement ( new ArooaElement ( property ) , variables . getArooaContext ( ) ) ; variables . getArooaContext ( ) . getConfigurationNode ( ) . setInsertPosition ( index ) ; int i = variables . getArooaContext ( ) . getConfigurationNode ( ) . insertChild ( nextContext . getConfigurationNode ( ) ) ; try { nextContext . getRuntime ( ) . init ( ) ; } catch ( ArooaException e ) { variables . getArooaContext ( ) . getConfigurationNode ( ) . removeChild ( i ) ; } } class VariableRow implements MultiTypeRow { private final VariablesDesignProperty designProperty ; private DesignInstance instance ; private Component component ; public VariableRow ( int index ) { this . designProperty = variables . propertyAt ( index ) ; } void setInstance ( DesignInstance instance ) { this . instance = instance ; if ( instance == null ) { component = null ; } else { Form designDefintion = instance . detail ( ) ; this . component = SwingFormFactory . create ( designDefintion ) . cell ( ) ; } } @ Override public String getName ( ) { return designProperty . property ( ) ; } @ Override public void setName ( String name ) { designProperty . changePropertyName ( name ) ; } @ Override public void setType ( Object value ) { InstanceSupport support = new InstanceSupport ( designProperty ) ; QTag newType = ( QTag ) value ; QTag oldType ; if ( instance == null ) { oldType = NULL_TAG ; } else { oldType = InstanceSupport . tagFor ( instance ) ; } if ( newType . equals ( oldType ) ) { return ; } else if ( ! NULL_TAG . equals ( oldType ) ) { support . removeInstance ( instance ) ; } if ( NULL_TAG . equals ( newType ) ) { return ; } try { support . insertTag ( , newType ) ; } catch ( ArooaParseException e ) { throw new DesignViewException ( e ) ; } } @ Override public Object getType ( ) { if ( instance != null ) { return InstanceSupport . tagFor ( instance ) ; } else { return NULL_TAG ; } } @ Override public EditableValue getValue ( ) { if ( instance == null ) { return null ; } else { return new EditableValue ( ) { @ Override public Component getEditor ( ) { return component ; } @ Override public void commit ( ) { } @ Override public void abort ( ) { } } ; } } } } class VariablesTableView implements SwingItemView { private Component component ; public VariablesTableView ( VariablesGrid variablesGrid ) { this . component = new MultiTypeTableWidget ( new VariablesModel ( variablesGrid ) , MultiTypeStrategy . Strategies . NAMED ) ; } public int inline ( Container container , int row , int column , boolean selectionInGroup ) { GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTHWEST ; c . gridx = column ; c . gridy = row ; c . gridwidth = GridBagConstraints . REMAINDER ; c . insets = new Insets ( , , , ) ; container . add ( component , c ) ; return row + ; } public void setEnabled ( boolean enabled ) { component . setEnabled ( enabled ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class RepeatDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new RepeatDesign ( element , parentContext ) ; } } class RepeatDesign extends BaseDC { private final SimpleTextAttribute until ; private final SimpleTextAttribute times ; private final SimpleDesignProperty job ; public RepeatDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; until = new SimpleTextAttribute ( "" , this ) ; times = new SimpleTextAttribute ( "" , this ) ; job = new SimpleDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( job . view ( ) . setTitle ( "" ) ) . add ( until . view ( ) . setTitle ( "" ) ) . add ( times . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , until , times , job } ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class ServerDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ServerDesign ( element , parentContext ) ; } } class ServerDesign extends BaseDC { private final SimpleTextAttribute root ; private final SimpleTextAttribute url ; private final SimpleDesignProperty environment ; private final SimpleTextAttribute logFormat ; private final SimpleDesignProperty handlerFactories ; public ServerDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; root = new SimpleTextAttribute ( "" , this ) ; url = new SimpleTextAttribute ( "" , this ) ; environment = new SimpleDesignProperty ( "" , this ) ; logFormat = new SimpleTextAttribute ( "" , this ) ; handlerFactories = new SimpleDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( root . view ( ) . setTitle ( "" ) ) . add ( url . view ( ) . setTitle ( "" ) ) . add ( environment . view ( ) . setTitle ( "" ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( logFormat . view ( ) . setTitle ( "" ) ) . add ( handlerFactories . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , root , url , environment , logFormat , handlerFactories } ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . jmx . JMXServiceJob ; public class JMXServiceDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new JMXServiceDesign ( element , parentContext ) ; } } class JMXServiceDesign extends BaseDC { private final SimpleTextAttribute connection ; private final SimpleDesignProperty environment ; private final SimpleTextAttribute heartbeat ; public JMXServiceDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; connection = new SimpleTextAttribute ( "" , this ) ; environment = new SimpleDesignProperty ( "" , this ) ; heartbeat = new SimpleTextAttribute ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , connection , environment , heartbeat } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( connection . view ( ) . setTitle ( "" ) ) . add ( environment . view ( ) . setTitle ( "" ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( heartbeat . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . MappedDesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . etc . FileAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TabGroup ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class OddjobDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new OddjobDesign ( element , parentContext ) ; } } class OddjobDesign extends BaseDC { private final FileAttribute file ; private final SimpleDesignProperty configuration ; private final SimpleDesignProperty args ; private final MappedDesignProperty export ; private final SimpleDesignProperty properties ; private final SimpleTextAttribute inheritance ; private final SimpleDesignProperty descriptorFactory ; private final SimpleDesignProperty classLoader ; private final SimpleDesignProperty persister ; OddjobDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; file = new FileAttribute ( "" , this ) ; configuration = new SimpleDesignProperty ( "" , this ) ; args = new SimpleDesignProperty ( "" , this ) ; export = new MappedDesignProperty ( "" , this ) ; properties = new SimpleDesignProperty ( "" , this ) ; inheritance = new SimpleTextAttribute ( "" , this ) ; descriptorFactory = new SimpleDesignProperty ( "" , this ) ; classLoader = new SimpleDesignProperty ( "" , this ) ; persister = new SimpleDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( file . view ( ) . setTitle ( "" ) ) . add ( configuration . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new TabGroup ( ) . add ( new FieldGroup ( "" ) . add ( args . view ( ) . setTitle ( "" ) ) . add ( properties . view ( ) . setTitle ( "" ) ) . add ( inheritance . view ( ) . setTitle ( "" ) ) . add ( export . view ( ) . setTitle ( "" ) ) ) . add ( new FieldGroup ( "" ) . add ( descriptorFactory . view ( ) . setTitle ( "" ) ) . add ( classLoader . view ( ) . setTitle ( "" ) ) . add ( persister . view ( ) . setTitle ( "" ) ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , file , configuration , args , properties , inheritance , export , descriptorFactory , classLoader , persister } ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class DeleteDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new DeleteDesign ( element , parentContext ) ; } } class DeleteDesign extends BaseDC { private final SimpleDesignProperty files ; private final SimpleTextAttribute force ; public DeleteDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; files = new SimpleDesignProperty ( "" , this ) ; force = new SimpleTextAttribute ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , files , force } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( files . view ( ) . setTitle ( "" ) ) . add ( force . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . designer . components ; import java . io . Serializable ; import org . oddjob . arooa . design . DesignComponentBase ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . jobs . structural . ForEachJob ; public class ForEachRootDC implements DesignFactory , Serializable { private static final long serialVersionUID = ; public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ForEachRootDesign ( element , parentContext ) ; } } class ForEachRootDesign extends DesignComponentBase { private final SimpleDesignProperty job ; public ForEachRootDesign ( ArooaElement element , ArooaContext context ) { super ( element , new SimpleArooaClass ( ForEachJob . LocalBean . class ) , context ) ; job = new SimpleDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( new BorderedGroup ( "" ) . add ( job . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { job } ; } public String toString ( ) { return "" ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . etc . ReferenceAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class WaitDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new WaitDesign ( element , parentContext ) ; } } class WaitDesign extends BaseDC { private final SimpleTextAttribute pause ; private final ReferenceAttribute forProperty ; private final SimpleTextAttribute state ; public WaitDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; pause = new SimpleTextAttribute ( "" , this ) ; forProperty = new ReferenceAttribute ( "" , this ) ; state = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( pause . view ( ) . setTitle ( "" ) ) . add ( forProperty . view ( ) . setTitle ( "" ) ) . add ( state . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , pause , forProperty , state } ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TextField ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class ResetJobDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ResetJobDesign ( element , parentContext ) ; } } class ResetJobDesign extends BaseDC { private final SimpleTextAttribute job ; private final SimpleTextAttribute level ; ResetJobDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; job = new SimpleTextAttribute ( "" , this ) ; level = new SimpleTextAttribute ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , job , level } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new TextField ( "" , job ) ) . add ( new TextField ( "" , level ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . IndexedDesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TabGroup ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . sql . SQLJob ; public class SqlDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new SqlDesign ( element , parentContext ) ; } } class SqlDesign extends BaseDC { private final SimpleDesignProperty connection ; private final SimpleDesignProperty input ; private final IndexedDesignProperty parameters ; private final SimpleTextAttribute autocommit ; private final SimpleTextAttribute callable ; private final SimpleTextAttribute escapeProcessing ; private final SimpleTextAttribute onError ; private final SimpleDesignProperty results ; private final SimpleTextAttribute expandProperties ; private final SimpleTextAttribute encoding ; private final SimpleTextAttribute delimiter ; private final SimpleTextAttribute delimiterType ; private final SimpleTextAttribute keepFormat ; public SqlDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; connection = new SimpleDesignProperty ( "" , this ) ; input = new SimpleDesignProperty ( "" , this ) ; parameters = new IndexedDesignProperty ( "" , this ) ; autocommit = new SimpleTextAttribute ( "" , this ) ; callable = new SimpleTextAttribute ( "" , this ) ; escapeProcessing = new SimpleTextAttribute ( "" , this ) ; onError = new SimpleTextAttribute ( "" , this ) ; results = new SimpleDesignProperty ( "" , this ) ; expandProperties = new SimpleTextAttribute ( "" , this ) ; encoding = new SimpleTextAttribute ( "" , this ) ; delimiter = new SimpleTextAttribute ( "" , this ) ; delimiterType = new SimpleTextAttribute ( "" , this ) ; keepFormat = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( connection . view ( ) . setTitle ( "" ) ) . add ( input . view ( ) . setTitle ( "" ) ) ) . addFormItem ( new TabGroup ( ) . add ( new FieldGroup ( "" ) . add ( parameters . view ( ) . setTitle ( "" ) ) . add ( autocommit . view ( ) . setTitle ( "" ) ) . add ( callable . view ( ) . setTitle ( "" ) ) . add ( escapeProcessing . view ( ) . setTitle ( "" ) ) . add ( onError . view ( ) . setTitle ( "" ) ) . add ( results . view ( ) . setTitle ( "" ) ) ) . add ( new FieldGroup ( "" ) . add ( expandProperties . view ( ) . setTitle ( "" ) ) . add ( delimiter . view ( ) . setTitle ( "" ) ) . add ( delimiterType . view ( ) . setTitle ( "" ) ) . add ( keepFormat . view ( ) . setTitle ( "" ) ) . add ( encoding . view ( ) . setTitle ( "" ) ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , connection , input , parameters , autocommit , callable , escapeProcessing , onError , results , expandProperties , delimiter , delimiterType , keepFormat , encoding } ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . etc . FileAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TabGroup ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class ForEachDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ForEachDesign ( element , parentContext ) ; } } class ForEachDesign extends BaseDC { private final SimpleDesignProperty values ; private final FileAttribute file ; private final SimpleDesignProperty configuration ; private final SimpleTextAttribute parallel ; private final SimpleDesignProperty executorService ; private final SimpleTextAttribute preLoad ; private final SimpleTextAttribute purgeAfter ; ForEachDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; values = new SimpleDesignProperty ( "" , this ) ; file = new FileAttribute ( "" , this ) ; configuration = new SimpleDesignProperty ( "" , this ) ; parallel = new SimpleTextAttribute ( "" , this ) ; executorService = new SimpleDesignProperty ( "" , this ) ; preLoad = new SimpleTextAttribute ( "" , this ) ; purgeAfter = new SimpleTextAttribute ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( values . view ( ) . setTitle ( "" ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( file . view ( ) . setTitle ( "" ) ) . add ( configuration . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new TabGroup ( ) . add ( new FieldGroup ( "" ) . add ( parallel . view ( ) . setTitle ( "" ) ) . add ( executorService . view ( ) . setTitle ( "" ) ) ) . add ( new FieldGroup ( "" ) . add ( preLoad . view ( ) . setTitle ( "" ) ) . add ( purgeAfter . view ( ) . setTitle ( "" ) ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , values , file , configuration , parallel , executorService , preLoad , purgeAfter } ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TextField ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class JustJobDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new JustJobDesign ( element , parentContext ) ; } } class JustJobDesign extends BaseDC { private final SimpleTextAttribute job ; public JustJobDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; job = new SimpleTextAttribute ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , job } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new TextField ( "" , job ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextProperty ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class EchoDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new EchoDesign ( element , parentContext ) ; } } class EchoDesign extends BaseDC { private final SimpleTextProperty text ; private final SimpleDesignProperty lines ; private final SimpleDesignProperty output ; public EchoDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; text = new SimpleTextProperty ( "" ) ; lines = new SimpleDesignProperty ( "" , this ) ; output = new SimpleDesignProperty ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , text , lines , output } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( text . view ( ) . setTitle ( "" ) ) . add ( lines . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( output . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . etc . FileAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class CopyDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new CopyDesign ( element , parentContext ) ; } } class CopyDesign extends BaseDC { private final SimpleDesignProperty from ; private final FileAttribute to ; private final SimpleDesignProperty input ; private final SimpleDesignProperty output ; public CopyDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; from = new SimpleDesignProperty ( "" , this ) ; to = new FileAttribute ( "" , this ) ; input = new SimpleDesignProperty ( "" , this ) ; output = new SimpleDesignProperty ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , from , to , input , output } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( from . view ( ) . setTitle ( "" ) ) . add ( input . view ( ) . setTitle ( "" ) ) ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FieldSelection ( ) . add ( to . view ( ) . setTitle ( "" ) ) . add ( output . view ( ) . setTitle ( "" ) ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignComponent ; import org . oddjob . arooa . design . DesignComponentBase ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . TextField ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . QTag ; public abstract class BaseDC extends DesignComponentBase implements DesignComponent { private final String toString ; protected final SimpleTextAttribute name ; public BaseDC ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; this . toString = new QTag ( element , parentContext ) . toString ( ) ; name = new SimpleTextAttribute ( "" , this ) ; } public BorderedGroup basePanel ( ) { BorderedGroup fg = new BorderedGroup ( "" ) ; fg . add ( new TextField ( "" , name ) ) ; return fg ; } @ Override public String toString ( ) { if ( name . attribute ( ) == null ) { return toString ; } else { return name . attribute ( ) ; } } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class EmptyDC extends BaseDC { public EmptyDC ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . IndexedDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class IfDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new IfDesign ( element , parentContext ) ; } } class IfDesign extends BaseDC { private final SimpleTextAttribute state ; private final SimpleTextAttribute not ; private final IndexedDesignProperty jobs ; public IfDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; state = new SimpleTextAttribute ( "" , this ) ; not = new SimpleTextAttribute ( "" , this ) ; jobs = new IndexedDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( state . view ( ) . setTitle ( "" ) ) . add ( not . view ( ) . setTitle ( "" ) ) . add ( jobs . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , state , not , jobs } ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . etc . FileAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FileSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class MkdirDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new MkdirDesign ( element , parentContext ) ; } } class MkdirDesign extends BaseDC { private final FileAttribute dir ; public MkdirDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; dir = new FileAttribute ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , dir } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FileSelection ( "" , dir ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . MappedDesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . SimpleTextProperty ; import org . oddjob . arooa . design . screem . FieldGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TabGroup ; import org . oddjob . arooa . design . screem . TextField ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class ExecDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ExecDesign ( element , parentContext ) ; } } class ExecDesign extends BaseDC { private final SimpleTextProperty command ; private final SimpleDesignProperty args ; private final SimpleTextAttribute dir ; private final SimpleTextAttribute newEnvironment ; private final MappedDesignProperty environment ; private final SimpleTextAttribute redirectStderr ; private final SimpleDesignProperty stdin ; private final SimpleDesignProperty stdout ; private final SimpleDesignProperty stderr ; public ExecDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; command = new SimpleTextProperty ( "" ) ; args = new SimpleDesignProperty ( "" , this ) ; dir = new SimpleTextAttribute ( "" , this ) ; newEnvironment = new SimpleTextAttribute ( "" , this ) ; environment = new MappedDesignProperty ( "" , this ) ; redirectStderr = new SimpleTextAttribute ( "" , this ) ; stdin = new SimpleDesignProperty ( "" , this ) ; stdout = new SimpleDesignProperty ( "" , this ) ; stderr = new SimpleDesignProperty ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , dir , command , args , newEnvironment , environment , redirectStderr , stdin , stdout , stderr } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new TabGroup ( ) . add ( new FieldGroup ( "" ) . add ( new FieldSelection ( ) . add ( command . view ( ) . setTitle ( "" ) ) . add ( args . view ( ) . setTitle ( "" ) ) ) . add ( new TextField ( "" , dir ) ) ) . add ( new FieldGroup ( "" ) . add ( newEnvironment . view ( ) . setTitle ( "" ) ) . add ( environment . view ( ) . setTitle ( "" ) ) ) . add ( new FieldGroup ( "" ) . add ( redirectStderr . view ( ) . setTitle ( "" ) ) . add ( stdin . view ( ) . setTitle ( "" ) ) . add ( stdout . view ( ) . setTitle ( "" ) ) . add ( stderr . view ( ) . setTitle ( "" ) ) ) ) ; } } package org . oddjob . designer . components ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . etc . FileAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FileSelection ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; public class ExistsDC implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ExistsDesign ( element , parentContext ) ; } } class ExistsDesign extends BaseDC { private final FileAttribute file ; public ExistsDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; file = new FileAttribute ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , file } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new FileSelection ( "" , file ) ) ) ; } } package org . oddjob . designer ; import java . awt . Component ; import java . awt . Font ; import java . awt . GridBagConstraints ; import java . awt . GridBagLayout ; import java . awt . Insets ; import javax . swing . JLabel ; import javax . swing . JPanel ; import javax . swing . SwingConstants ; import javax . swing . border . Border ; import javax . swing . border . CompoundBorder ; import javax . swing . border . EmptyBorder ; import javax . swing . border . TitledBorder ; public class Looks { public static final int DESIGNER_TREE_WIDTH = ; public static final int DETAIL_FORM_WIDTH = ; public static final int DETAIL_FORM_BORDER = ; public static final int GROUP_BORDER = ; public static final int DETAIL_USABLE_WIDTH = DETAIL_FORM_WIDTH - * GROUP_BORDER - * DETAIL_FORM_BORDER ; public static final int TEXT_FIELD_SIZE = ; public static final int LABEL_SIZE = ; public static final int LIST_ROWS = ; public static final int DESIGNER_HEIGHT = ; public static final int DESIGNER_WIDTH = DESIGNER_TREE_WIDTH + DETAIL_FORM_WIDTH ; public static Border groupBorder ( String title ) { return new CompoundBorder ( new TitledBorder ( title ) , new EmptyBorder ( GROUP_BORDER , GROUP_BORDER , GROUP_BORDER , GROUP_BORDER ) ) ; } public static Component typePanel ( String tag ) { JPanel typePanel = new JPanel ( new GridBagLayout ( ) ) ; GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTHWEST ; c . insets = new Insets ( , , , ) ; typePanel . setBorder ( Looks . groupBorder ( "" ) ) ; JLabel typeLabel = new JLabel ( tag , SwingConstants . CENTER ) ; typeLabel . setFont ( typeLabel . getFont ( ) . deriveFont ( Font . BOLD , typeLabel . getFont ( ) . getSize ( ) * ) ) ; typePanel . add ( typeLabel , c ) ; return typePanel ; } } package org . oddjob . beanbus ; import java . util . List ; public class Batcher < T > implements Destination < T > , BusAware { private int batchSize ; private Destination < List < T > > next ; private List < T > batch ; private int count ; private BadBeanHandler < List < ? super T > > badBeanHandler ; public void accept ( T bean ) throws CrashBusException { batch . add ( bean ) ; if ( ++ count == batchSize ) { dispatch ( ) ; } } protected void dispatch ( ) throws CrashBusException { if ( count == ) { return ; } count = ; try { next . accept ( batch ) ; } catch ( BadBeanException e ) { if ( badBeanHandler == null ) { throw new CrashBusException ( "" , e ) ; } else { badBeanHandler . handle ( batch , e ) ; } } batch . clear ( ) ; } @ Override public void setBus ( BeanBus driver ) { driver . addBusListener ( new BusListener ( ) { @ Override public void busStarting ( BusEvent event ) { } @ Override public void busStopping ( BusEvent event ) throws CrashBusException { dispatch ( ) ; } @ Override public void busCrashed ( BusEvent event , BusException e ) { } @ Override public void busTerminated ( BusEvent event ) { event . getSource ( ) . removeBusListener ( this ) ; } } ) ; if ( next instanceof BusAware ) { ( ( BusAware ) next ) . setBus ( driver ) ; } } public int getBatchSize ( ) { return batchSize ; } public void setBatchSize ( int batchSize ) { this . batchSize = batchSize ; } public Destination < List < T > > getNext ( ) { return next ; } public void setNext ( Destination < List < T > > next ) { this . next = next ; } public BadBeanHandler < List < ? super T > > getBadBeanHandler ( ) { return badBeanHandler ; } public void setBadBeanHandler ( BadBeanHandler < List < ? super T > > badBeanHandler ) { this . badBeanHandler = badBeanHandler ; } } package org . oddjob . beanbus ; import java . util . EventListener ; public interface BusListener extends EventListener { void busStarting ( BusEvent event ) throws CrashBusException ; void busStopping ( BusEvent event ) throws CrashBusException ; void busTerminated ( BusEvent event ) ; void busCrashed ( BusEvent event , BusException e ) ; } package org . oddjob . beanbus ; public interface StageNotifier { public void addStageListener ( StageListener listener ) ; public void removeStageListener ( StageListener listener ) ; } package org . oddjob . beanbus ; import java . util . Iterator ; public class IterableDriver < T > implements Driver < T > , BusAware { private Iterable < T > iterable ; private Destination < ? super T > to ; private volatile boolean stop ; @ Override public void go ( ) throws BusException { stop = false ; Iterator < T > current = iterable . iterator ( ) ; while ( ! stop && current . hasNext ( ) ) { to . accept ( current . next ( ) ) ; } } @ Override public void setBus ( BeanBus driver ) { if ( to instanceof BusAware ) { ( ( BusAware ) to ) . setBus ( driver ) ; } } public void setTo ( Destination < ? super T > to ) { this . to = to ; } ; @ Override public void stop ( ) { this . stop = true ; } public Iterable < T > getIterable ( ) { return iterable ; } public void setIterable ( Iterable < T > iterable ) { this . iterable = iterable ; } } package org . oddjob . beanbus ; abstract public class BusException extends Exception { private static final long serialVersionUID = ; public BusException ( ) { super ( ) ; } public BusException ( String message , Throwable cause ) { super ( message , cause ) ; } public BusException ( String message ) { super ( message ) ; } public BusException ( Throwable cause ) { super ( cause ) ; } } package org . oddjob . beanbus ; public interface BeanBus extends Runnable , BusNotifier , StageNotifier { public void stop ( ) ; } package org . oddjob . beanbus ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . oddjob . arooa . types . ValueFactory ; public class BeanTrap < T > implements Destination < T > , Iterable < T > , ValueFactory < List < T > > , BusAware { private final List < T > trapped = new ArrayList < T > ( ) ; public void accept ( T bean ) { trapped . add ( bean ) ; } ; @ Override public void setBus ( BeanBus driver ) { driver . addBusListener ( new BusListener ( ) { @ Override public void busStarting ( BusEvent event ) { trapped . clear ( ) ; } @ Override public void busStopping ( BusEvent event ) throws CrashBusException { } @ Override public void busTerminated ( BusEvent event ) { event . getSource ( ) . removeBusListener ( this ) ; } @ Override public void busCrashed ( BusEvent event , BusException e ) { } } ) ; } @ Override public Iterator < T > iterator ( ) { return toValue ( ) . iterator ( ) ; } @ Override public List < T > toValue ( ) { return new ArrayList < T > ( trapped ) ; } } package org . oddjob . beanbus ; public interface Destination < T > { public void accept ( T bean ) throws BadBeanException , CrashBusException ; } package org . oddjob . beanbus ; import java . util . EventObject ; public class BusEvent extends EventObject { private static final long serialVersionUID = ; public BusEvent ( BeanBus source ) { super ( source ) ; } @ Override public BeanBus getSource ( ) { return ( BeanBus ) super . getSource ( ) ; } } package org . oddjob . beanbus ; public class BadBeanFilter < T > implements Section < T , T > , BusAware { private BadBeanHandler < ? super T > badBeanHandler ; private Destination < ? super T > to ; public void accept ( T bean ) throws CrashBusException { try { to . accept ( bean ) ; } catch ( BadBeanException e ) { badBeanHandler . handle ( bean , e ) ; } } ; @ Override public void setTo ( Destination < ? super T > to ) { this . to = to ; } @ Override public void setBus ( BeanBus driver ) { driver . addBusListener ( new BusListener ( ) { @ Override public void busStarting ( BusEvent event ) throws CrashBusException { if ( badBeanHandler == null ) { throw new CrashBusException ( "" ) ; } } @ Override public void busStopping ( BusEvent event ) throws CrashBusException { } @ Override public void busCrashed ( BusEvent event , BusException e ) { } @ Override public void busTerminated ( BusEvent event ) { event . getSource ( ) . removeBusListener ( this ) ; } } ) ; if ( badBeanHandler instanceof BusAware ) { ( ( BusAware ) badBeanHandler ) . setBus ( driver ) ; } if ( to instanceof BusAware ) { ( ( BusAware ) to ) . setBus ( driver ) ; } } public BadBeanHandler < ? super T > getBadBeanHandler ( ) { return badBeanHandler ; } public void setBadBeanHandler ( BadBeanHandler < ? super T > badBeanHandler ) { this . badBeanHandler = badBeanHandler ; } } package org . oddjob . beanbus ; public class FilterSection < F , T > implements Section < F , T > , BusAware { private Filter < ? super F , ? extends T > filter ; private Destination < ? super T > to ; public void accept ( F bean ) throws BadBeanException , CrashBusException { T filtered = filter . filter ( bean ) ; if ( filtered == null ) { return ; } to . accept ( filtered ) ; } ; public Filter < ? super F , ? extends T > getFilter ( ) { return filter ; } public void setFilter ( Filter < ? super F , ? extends T > filter ) { this . filter = filter ; } public Destination < ? super T > getTo ( ) { return to ; } public void setTo ( Destination < ? super T > receiver ) { this . to = receiver ; } @ Override public void setBus ( BeanBus driver ) { if ( to instanceof BusAware ) { ( ( BusAware ) to ) . setBus ( driver ) ; } } } package org . oddjob . beanbus ; public interface Driver < T > { public void setTo ( Destination < ? super T > to ) ; public void go ( ) throws BusException ; public void stop ( ) ; } package org . oddjob . beanbus ; public interface BusAware { public void setBus ( BeanBus bus ) ; } package org . oddjob . beanbus ; import java . io . IOException ; import java . io . OutputStream ; import java . io . PrintStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . reflect . BeanView ; import org . oddjob . arooa . reflect . BeanViews ; import org . oddjob . arooa . reflect . FallbackBeanView ; import org . oddjob . arooa . reflect . PropertyAccessor ; public class BeanSheet implements Destination < Iterable < ? > > , BusAware , ArooaSessionAware { private static final Logger logger = Logger . getLogger ( BeanSheet . class ) ; private static final char PADDING = '' ; private static final String COLUMN_SPACE = pad ( PADDING , ) ; private static final char UNDERLINE = '' ; private OutputStream output ; private boolean noHeaders ; private PropertyAccessor accessor ; private ArooaConverter converter ; private BeanViews beanViews ; @ ArooaHidden @ Override public void setArooaSession ( ArooaSession session ) { this . accessor = session . getTools ( ) . getPropertyAccessor ( ) ; this . converter = session . getTools ( ) . getArooaConverter ( ) ; } @ Override public void accept ( Iterable < ? > beans ) { if ( beans == null ) { throw new NullPointerException ( "" ) ; } PrintStream out = new PrintStream ( output ) ; List < Row > rows = new ArrayList < Row > ( ) ; Header header = null ; int count = ; for ( Object bean : beans ) { if ( header == null ) { header = new Header ( bean ) ; rows . add ( header ) ; } Line line = header . process ( bean ) ; rows . add ( line ) ; ++ count ; } logger . info ( "" + count + "" ) ; for ( Row row : rows ) { row . printTo ( out ) ; } out . flush ( ) ; } @ Override public void setBus ( BeanBus bus ) { bus . addBusListener ( new BusListener ( ) { @ Override public void busStarting ( BusEvent event ) throws CrashBusException { if ( output == null ) { throw new CrashBusException ( "" ) ; } } @ Override public void busStopping ( BusEvent event ) throws CrashBusException { } @ Override public void busCrashed ( BusEvent event , BusException e ) { } @ Override public void busTerminated ( BusEvent event ) { event . getSource ( ) . removeBusListener ( this ) ; try { if ( output != null ) { output . close ( ) ; } } catch ( IOException ioe ) { logger . error ( "" , ioe ) ; } } } ) ; } interface Row { void printTo ( PrintStream out ) ; } class Line implements Row { String [ ] values ; Header header ; Line ( String [ ] values , Header header ) { this . values = values ; this . header = header ; } @ Override public void printTo ( PrintStream out ) { for ( int i = ; i < values . length ; ++ i ) { if ( i != ) { out . print ( COLUMN_SPACE ) ; } out . print ( values [ i ] ) ; if ( i != values . length - ) { out . print ( pad ( PADDING , header . widths [ i ] - values [ i ] . length ( ) ) ) ; } } out . println ( ) ; } } class Header implements Row { private final String [ ] properties ; private final String [ ] headings ; private final int [ ] widths ; Header ( Object bean ) { ArooaClass arooaClass = accessor . getClassName ( bean ) ; BeanView view = null ; if ( beanViews != null ) { view = beanViews . beanViewFor ( arooaClass ) ; } if ( view == null ) { view = new FallbackBeanView ( accessor , bean ) ; } String [ ] allProperties = view . getProperties ( ) ; List < String > readables = new ArrayList < String > ( ) ; BeanOverview overview = arooaClass . getBeanOverview ( accessor ) ; for ( String property : allProperties ) { if ( "" . equals ( property ) ) { continue ; } if ( overview . hasReadableProperty ( property ) ) { readables . add ( property ) ; } } this . properties = readables . toArray ( new String [ readables . size ( ) ] ) ; this . headings = new String [ properties . length ] ; this . widths = new int [ properties . length ] ; for ( int i = ; i < properties . length ; ++ i ) { headings [ i ] = view . titleFor ( properties [ i ] ) ; widths [ i ] = headings [ i ] . length ( ) ; } logger . info ( "" + Arrays . toString ( headings ) ) ; } @ Override public void printTo ( PrintStream out ) { if ( noHeaders ) { return ; } for ( int i = ; i < headings . length ; ++ i ) { if ( i != ) { out . print ( COLUMN_SPACE ) ; } out . print ( headings [ i ] ) ; if ( i != headings . length - ) out . print ( pad ( PADDING , widths [ i ] - headings [ i ] . length ( ) ) ) ; } out . println ( ) ; for ( int i = ; i < headings . length ; ++ i ) { if ( i != ) { out . print ( COLUMN_SPACE ) ; } out . print ( pad ( UNDERLINE , widths [ i ] ) ) ; } out . println ( ) ; } Line process ( Object bean ) { String [ ] values = new String [ properties . length ] ; for ( int i = ; i < properties . length ; ++ i ) { String property = properties [ i ] ; Object value = accessor . getProperty ( bean , property ) ; String string = null ; try { string = converter . convert ( value , String . class ) ; } catch ( ArooaConversionException e ) { string = pad ( '' , widths [ i ] ) ; } if ( string == null ) { string = "" ; } if ( widths [ i ] < string . length ( ) ) { widths [ i ] = string . length ( ) ; } values [ i ] = string ; } return new Line ( values , this ) ; } } public OutputStream getOutput ( ) { return output ; } public void setOutput ( OutputStream output ) { this . output = output ; } public boolean isNoHeaders ( ) { return noHeaders ; } public void setNoHeaders ( boolean noHeaders ) { this . noHeaders = noHeaders ; } public BeanViews getBeanViews ( ) { return beanViews ; } public void setBeanViews ( BeanViews beanViews ) { this . beanViews = beanViews ; } private static String pad ( char padding , int size ) { if ( size < ) { return new String ( "" ) ; } char [ ] buff = new char [ size ] ; Arrays . fill ( buff , padding ) ; return new String ( buff ) ; } } package org . oddjob . beanbus ; import java . util . ArrayList ; import java . util . List ; import org . apache . log4j . Logger ; public class SimpleBus < T > implements BeanBus { private static final Logger logger = Logger . getLogger ( SimpleBus . class ) ; private Driver < ? extends T > driver ; private StageNotifier conductor ; private List < BusListener > busListeners = new ArrayList < BusListener > ( ) ; @ Override public void run ( ) { if ( driver == null ) { throw new NullPointerException ( "" ) ; } if ( driver instanceof BusAware ) { ( ( BusAware ) driver ) . setBus ( this ) ; } try { fireBusStarting ( ) ; driver . go ( ) ; fireBusStopping ( ) ; } catch ( BusException e ) { fireBusCrashed ( e ) ; throw new RuntimeException ( e ) ; } finally { fireBusTerminated ( ) ; } } @ Override public void stop ( ) { driver . stop ( ) ; } public Driver < ? extends T > getDriver ( ) { return driver ; } public void setDriver ( Driver < ? extends T > from ) { this . driver = from ; if ( conductor == null && driver instanceof StageNotifier ) { conductor = ( ( StageNotifier ) driver ) ; } } @ Override public void addBusListener ( BusListener listener ) { busListeners . add ( listener ) ; } @ Override public void removeBusListener ( BusListener listener ) { busListeners . remove ( listener ) ; } @ Override public void addStageListener ( StageListener listener ) { if ( conductor != null ) { conductor . addStageListener ( listener ) ; } } @ Override public void removeStageListener ( StageListener listener ) { if ( conductor != null ) { conductor . removeStageListener ( listener ) ; } } protected void fireBusStarting ( ) throws CrashBusException { List < BusListener > copy = new ArrayList < BusListener > ( busListeners ) ; BusEvent event = new BusEvent ( this ) ; for ( BusListener listener : copy ) { listener . busStarting ( event ) ; } } protected void fireBusStopping ( ) throws CrashBusException { List < BusListener > copy = new ArrayList < BusListener > ( busListeners ) ; BusEvent event = new BusEvent ( this ) ; for ( BusListener listener : copy ) { listener . busStopping ( event ) ; } } protected void fireBusTerminated ( ) { List < BusListener > copy = new ArrayList < BusListener > ( busListeners ) ; BusEvent event = new BusEvent ( this ) ; for ( BusListener listener : copy ) { try { listener . busTerminated ( event ) ; } catch ( Throwable t ) { logger . info ( "" + listener + "" , t ) ; } } } protected void fireBusCrashed ( BusException e ) { List < BusListener > copy = new ArrayList < BusListener > ( busListeners ) ; BusEvent event = new BusEvent ( this ) ; for ( BusListener listener : copy ) { try { listener . busCrashed ( event , e ) ; } catch ( Throwable t ) { logger . info ( "" + listener + "" , t ) ; } } } public StageNotifier getConductor ( ) { return conductor ; } public void setConductor ( StageNotifier conductor ) { this . conductor = conductor ; } } package org . oddjob . beanbus ; public class EmptyDestination < T > implements Destination < T > { public void accept ( T bean ) { } ; } package org . oddjob . beanbus ; public interface BusNotifier { public void addBusListener ( BusListener listener ) ; public void removeBusListener ( BusListener listener ) ; } package org . oddjob . beanbus ; public class CrashBusException extends BusException { private static final long serialVersionUID = ; public CrashBusException ( ) { super ( ) ; } public CrashBusException ( String message , Throwable cause ) { super ( message , cause ) ; } public CrashBusException ( String message ) { super ( message ) ; } public CrashBusException ( Throwable cause ) { super ( cause ) ; } } package org . oddjob . beanbus ; public interface Section < F , T > extends Destination < F > { public void setTo ( Destination < ? super T > to ) ; } package org . oddjob . beanbus ; import java . util . EventObject ; public class StageEvent extends EventObject { private static final long serialVersionUID = ; private final String description ; private final Object data ; public StageEvent ( StageNotifier source , String description ) { this ( source , description , null ) ; } public StageEvent ( StageNotifier source , String description , Object data ) { super ( source ) ; this . description = description ; this . data = data ; } public String getDescription ( ) { return description ; } public Object getData ( ) { return data ; } @ Override public StageNotifier getSource ( ) { return ( StageNotifier ) super . getSource ( ) ; } } package org . oddjob . beanbus ; public class BadBeanException extends BusException { private static final long serialVersionUID = ; private final Object badBean ; public BadBeanException ( Object badBean ) { super ( ) ; this . badBean = badBean ; } public BadBeanException ( Object badBean , String message , Throwable cause ) { super ( message , cause ) ; this . badBean = badBean ; } public BadBeanException ( Object badBean , String message ) { super ( message ) ; this . badBean = badBean ; } public BadBeanException ( Object badBean , Throwable cause ) { super ( cause ) ; this . badBean = badBean ; } public Object getBadBean ( ) { return badBean ; } } package org . oddjob . beanbus ; public interface Filter < F , T > { public T filter ( F from ) ; } package org . oddjob . beanbus ; import java . util . ArrayList ; import java . util . List ; import java . util . Stack ; public class StageSupport implements StageNotifier { private List < StageListener > batchListeners = new ArrayList < StageListener > ( ) ; private final StageNotifier source ; private final Stack < StageEvent > events = new Stack < StageEvent > ( ) ; public StageSupport ( StageNotifier source ) { this . source = source ; } public void fireStageStarting ( String description ) { fireStageStarting ( description , null ) ; } public void fireStageStarting ( String description , Object data ) { List < StageListener > copy = new ArrayList < StageListener > ( batchListeners ) ; StageEvent event = new StageEvent ( source , description , data ) ; events . push ( event ) ; for ( StageListener listener : copy ) { listener . stageStarting ( event ) ; } } public void fireStageComplete ( ) { List < StageListener > copy = new ArrayList < StageListener > ( batchListeners ) ; StageEvent event = events . pop ( ) ; for ( StageListener listener : copy ) { listener . stageComplete ( event ) ; } } @ Override public void addStageListener ( StageListener listener ) { batchListeners . add ( listener ) ; } @ Override public void removeStageListener ( StageListener listener ) { batchListeners . remove ( listener ) ; } } package org . oddjob . beanbus ; public interface BadBeanHandler < T > { public void handle ( T originalBean , BadBeanException e ) throws CrashBusException ; } package org . oddjob . beanbus ; import java . util . EventListener ; public interface StageListener extends EventListener { public void stageStarting ( StageEvent event ) ; public void stageComplete ( StageEvent event ) ; } package org . oddjob . jobs ; import java . io . OutputStream ; import java . io . PrintStream ; import java . io . Serializable ; import org . oddjob . arooa . deploy . annotations . ArooaText ; public class EchoJob implements Runnable , Serializable { private static final long serialVersionUID = ; private String name ; private String text ; private String [ ] lines ; private transient OutputStream output ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getText ( ) { return text ; } @ ArooaText public void setText ( String text ) { this . text = text ; } public String [ ] getLines ( ) { return lines ; } public void setLines ( String [ ] lines ) { this . lines = lines ; } public OutputStream getOutput ( ) { return output ; } public void setOutput ( OutputStream output ) { this . output = output ; } public void run ( ) { PrintStream out = null ; if ( output != null ) { out = new PrintStream ( output ) ; } if ( out == null ) { out = System . out ; } if ( text != null ) { out . println ( text ) ; } else if ( lines != null ) { for ( String line : lines ) { out . println ( line ) ; } } else { out . println ( ) ; } if ( output != null ) { out . close ( ) ; } } public String toString ( ) { if ( name == null ) { return "" ; } return name ; } } package org . oddjob . jobs . structural ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . framework . StructuralJob ; import org . oddjob . state . SequentialHelper ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; public class SequentialJob extends StructuralJob < Object > implements Structural , Stoppable { private static final long serialVersionUID = ; private boolean independent ; @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } @ ArooaComponent public void setJobs ( int index , Object child ) { if ( child == null ) { childHelper . removeChildAt ( index ) ; } else { childHelper . insertChild ( index , child ) ; } } public void execute ( ) throws Exception { for ( Object child : childHelper ) { if ( stop ) { stop = false ; break ; } if ( ! ( child instanceof Runnable ) ) { logger ( ) . info ( "" + child + "" ) ; } else { Runnable job = ( Runnable ) child ; logger ( ) . info ( "" + job + "" ) ; job . run ( ) ; } if ( ! ( independent || new SequentialHelper ( ) . canContinueAfter ( child ) ) ) { logger ( ) . info ( "" + child + "" ) ; break ; } } } public boolean isIndependent ( ) { return independent ; } public void setIndependent ( boolean independent ) { this . independent = independent ; } } package org . oddjob . jobs . structural ; import java . io . File ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . concurrent . Callable ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Future ; import javax . inject . Inject ; import org . oddjob . FailedToStopException ; import org . oddjob . Loadable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . life . ComponentProxyResolver ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . ConfigConfigurationSession ; import org . oddjob . arooa . parsing . ConfigSessionEvent ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationOwnerSupport ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . HandleConfigurationSession ; import org . oddjob . arooa . parsing . OwnerStateListener ; import org . oddjob . arooa . parsing . SessionStateListener ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . registry . SimpleComponentPool ; import org . oddjob . arooa . runtime . PropertyManager ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . standard . StandardPropertyManager ; import org . oddjob . arooa . utils . ListenerSupportBase ; import org . oddjob . arooa . utils . RootConfigurationFileCreator ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . designer . components . ForEachRootDC ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . framework . ExecutionWatcher ; import org . oddjob . framework . StructuralJob ; import org . oddjob . io . ExistsJob ; import org . oddjob . scheduling . ExecutorThrottleType ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsNotExecuting ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . ParentState ; import org . oddjob . state . SequentialHelper ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; public class ForEachJob extends StructuralJob < Runnable > implements Stoppable , Loadable , ConfigurationOwner { private static final long serialVersionUID = ; public static final ArooaElement FOREACH_ELEMENT = new ArooaElement ( "" ) ; private transient Iterable < ? extends Object > values ; private transient Iterator < ? extends Object > iterator ; private int preLoad ; private int purgeAfter ; private transient ArooaConfiguration configuration ; private File file ; private transient ConfigurationOwnerSupport configurationOwnerSupport ; private transient Object current ; private transient int index ; private transient Map < Object , ConfigurationHandle > configurationHandles ; private transient LinkedList < Runnable > ready ; private transient LinkedList < Stateful > complete ; private transient boolean parallel ; private transient ExecutorService executorService ; private transient Map < Runnable , Future < ? > > jobThreads ; public ForEachJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { configurationOwnerSupport = new ConfigurationOwnerSupport ( this ) ; } @ Inject public void setExecutorService ( ExecutorService executorService ) { this . executorService = executorService ; } public Object getCurrent ( ) { return current ; } public void setValues ( Iterable < ? extends Object > values ) { this . values = values ; } @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } @ Override public ConfigurationSession provideConfigurationSession ( ) { return configurationOwnerSupport . provideConfigurationSession ( ) ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { configurationOwnerSupport . addOwnerStateListener ( listener ) ; } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { configurationOwnerSupport . removeOwnerStateListener ( listener ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return new ForEachRootDC ( ) ; } @ Override public ArooaElement rootElement ( ) { return FOREACH_ELEMENT ; } protected Runnable loadConfigFor ( Object value ) throws ArooaParseException { logger ( ) . debug ( "" + value + "" ) ; ArooaSession existingSession = getArooaSession ( ) ; PseudoRegistry psudoRegistry = new PseudoRegistry ( existingSession . getBeanRegistry ( ) , existingSession . getTools ( ) . getPropertyAccessor ( ) , existingSession . getTools ( ) . getArooaConverter ( ) ) ; RegistryOverrideSession session = new RegistryOverrideSession ( existingSession , psudoRegistry ) ; LocalBean seed = new LocalBean ( index ++ , value ) ; StandardArooaParser parser = new StandardArooaParser ( seed , session ) ; parser . setExpectedDocumentElement ( FOREACH_ELEMENT ) ; ConfigurationHandle handle = parser . parse ( configuration ) ; Runnable root = seed . job ; if ( root == null ) { logger ( ) . info ( "" ) ; return null ; } if ( root instanceof Stateful ) { ( ( Stateful ) root ) . addStateListener ( new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { Stateful source = event . getSource ( ) ; State state = event . getState ( ) ; if ( state . isReady ( ) ) { ready . add ( ( Runnable ) source ) ; } if ( state . isComplete ( ) ) { ready . remove ( source ) ; complete . add ( source ) ; } } } ) ; } else { throw new UnsupportedOperationException ( "" + root + "" ) ; } configurationHandles . put ( root , handle ) ; seed . session . getComponentPool ( ) . configure ( root ) ; childHelper . addChild ( root ) ; return root ; } private void remove ( Object child ) { ConfigurationHandle handle = configurationHandles . get ( child ) ; handle . getDocumentContext ( ) . getRuntime ( ) . destroy ( ) ; } protected void preLoad ( ) throws ArooaParseException { if ( configuration == null ) { throw new IllegalStateException ( "" ) ; } if ( getArooaSession ( ) == null ) { throw new NullPointerException ( "" ) ; } if ( configurationHandles != null ) { return ; } configurationOwnerSupport . setConfigurationSession ( new ForeachConfigurationSession ( ) ) ; logger ( ) . debug ( "" ) ; configurationHandles = new HashMap < Object , ConfigurationHandle > ( ) ; ready = new LinkedList < Runnable > ( ) ; complete = new LinkedList < Stateful > ( ) ; jobThreads = new HashMap < Runnable , Future < ? > > ( ) ; if ( values == null ) { logger ( ) . info ( "" ) ; iterator = Collections . emptyList ( ) . iterator ( ) ; } else { iterator = values . iterator ( ) ; } while ( ( preLoad < || ready . size ( ) < preLoad ) && ( loadNext ( ) != null ) ) ; } private Runnable loadNext ( ) throws ArooaParseException { if ( iterator . hasNext ( ) ) { return loadConfigFor ( iterator . next ( ) ) ; } else { return null ; } } @ Override public void load ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { stateHandler . waitToWhen ( new IsNotExecuting ( ) , new Runnable ( ) { public void run ( ) { try { if ( configurationHandles != null ) { return ; } configure ( ) ; preLoad ( ) ; } catch ( Exception e ) { logger ( ) . error ( "" , e ) ; getStateChanger ( ) . setStateException ( e ) ; } } } ) ; } finally { ComponentBoundry . pop ( ) ; } } ; @ Override public void unload ( ) { reset ( ) ; } @ Override public boolean isLoadable ( ) { return configurationHandles == null ; } protected void execute ( ) throws Exception { preLoad ( ) ; ExecutionWatcher executionWatcher = new ExecutionWatcher ( new Runnable ( ) { public void run ( ) { stop = false ; ForEachJob . super . startChildStateReflector ( ) ; } } ) ; List < Runnable > readyNow = new ArrayList < Runnable > ( ready ) ; for ( int i = ; i < readyNow . size ( ) && ! stop ; ++ i ) { Runnable job = readyNow . get ( i ) ; if ( parallel ) { parallelRun ( executionWatcher , job ) ; } else { final Runnable runnable = executionWatcher . addJob ( job ) ; runnable . run ( ) ; if ( ! new SequentialHelper ( ) . canContinueAfter ( job ) ) { logger ( ) . info ( "" + job + "" ) ; break ; } Runnable next = purgeAndLoad ( ) ; if ( next != null ) { readyNow . add ( next ) ; } } } if ( ! stop ) { if ( parallel ) { stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ParentState . ACTIVE ) ; } } ) ; } } executionWatcher . start ( ) ; } private synchronized void parallelRun ( final ExecutionWatcher executionWatcher , final Runnable job ) { Runnable runnable = new Runnable ( ) { public void run ( ) { job . run ( ) ; if ( stop ) { return ; } try { Runnable next = purgeAndLoad ( ) ; if ( next != null ) { parallelRun ( executionWatcher , next ) ; } } catch ( ArooaParseException e ) { logger ( ) . error ( e ) ; } } } ; Runnable toSubmit = executionWatcher . addJob ( runnable ) ; Future < ? > future = executorService . submit ( toSubmit ) ; jobThreads . put ( job , future ) ; } private synchronized Runnable purgeAndLoad ( ) throws ArooaParseException { while ( purgeAfter > && complete . size ( ) > purgeAfter ) { remove ( complete . removeFirst ( ) ) ; } return loadNext ( ) ; } @ Override protected void startChildStateReflector ( ) { } @ Override protected void onStop ( ) throws FailedToStopException { super . onStop ( ) ; Map < Runnable , Future < ? > > jobThreads = this . jobThreads ; if ( jobThreads == null ) { return ; } for ( Map . Entry < Runnable , Future < ? > > future : jobThreads . entrySet ( ) ) { future . getValue ( ) . cancel ( false ) ; } super . startChildStateReflector ( ) ; } public int getIndex ( ) { return index ; } public class LocalBean implements ArooaSessionAware { private final int index ; private final Object current ; private ArooaSession session ; private Runnable job ; private int structuralPosition = - ; private ConfigurationHandle handle ; LocalBean ( int index , Object value ) { this . index = index ; this . current = value ; } @ Override public void setArooaSession ( ArooaSession session ) { this . session = session ; } public Object getCurrent ( ) { return current ; } public int getIndex ( ) { return index ; } @ ArooaComponent public void setJob ( final Runnable child ) { stateHandler . callLocked ( new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { if ( child == null ) { structuralPosition = childHelper . removeChild ( job ) ; handle = configurationHandles . remove ( job ) ; jobThreads . remove ( job ) ; ready . remove ( job ) ; } else { if ( structuralPosition != - ) { session . getComponentPool ( ) . configure ( child ) ; childHelper . insertChild ( structuralPosition , child ) ; configurationHandles . put ( child , handle ) ; } } job = child ; return null ; } } ) ; } } class RegistryOverrideSession implements ArooaSession { private final ArooaSession existingSession ; private final BeanRegistry beanDirectory ; private final ComponentPool componentPool ; private final PropertyManager propertyManager ; public RegistryOverrideSession ( ArooaSession exsitingSession , BeanRegistry registry ) { this . existingSession = exsitingSession ; this . beanDirectory = registry ; this . componentPool = new PseudoComponentPool ( exsitingSession . getComponentPool ( ) ) ; this . propertyManager = new StandardPropertyManager ( existingSession . getPropertyManager ( ) ) ; } @ Override public ArooaDescriptor getArooaDescriptor ( ) { return existingSession . getArooaDescriptor ( ) ; } @ Override public ComponentPool getComponentPool ( ) { return componentPool ; } @ Override public BeanRegistry getBeanRegistry ( ) { return beanDirectory ; } @ Override public PropertyManager getPropertyManager ( ) { return propertyManager ; } @ Override public ComponentProxyResolver getComponentProxyResolver ( ) { return existingSession . getComponentProxyResolver ( ) ; } @ Override public ComponentPersister getComponentPersister ( ) { return null ; } @ Override public ArooaTools getTools ( ) { return existingSession . getTools ( ) ; } } class PseudoRegistry extends SimpleBeanRegistry { private final BeanDirectory existingDirectory ; PseudoRegistry ( BeanDirectory existingDirectory , PropertyAccessor propertyAccessor , ArooaConverter converter ) { super ( propertyAccessor , converter ) ; this . existingDirectory = existingDirectory ; } public Object lookup ( String path ) { Object component = super . lookup ( path ) ; if ( component == null ) { return existingDirectory . lookup ( path ) ; } return component ; } @ Override public < T > T lookup ( String path , Class < T > required ) throws ArooaConversionException { T component = super . lookup ( path , required ) ; if ( component == null ) { return existingDirectory . lookup ( path , required ) ; } return component ; } public String getIdFor ( Object component ) { return null ; } @ Override public synchronized < T > Iterable < T > getAllByType ( Class < T > type ) { List < T > results = new ArrayList < T > ( ) ; for ( T t : super . getAllByType ( type ) ) { results . add ( t ) ; } for ( T t : existingDirectory . getAllByType ( type ) ) { results . add ( t ) ; } return results ; } } class PseudoComponentPool extends SimpleComponentPool { private final ComponentPool existingPool ; public PseudoComponentPool ( ComponentPool existingPool ) { this . existingPool = existingPool ; } @ Override public Iterable < ComponentTrinity > allTrinities ( ) { List < ComponentTrinity > results = new ArrayList < ComponentTrinity > ( ) ; for ( ComponentTrinity t : super . allTrinities ( ) ) { results . add ( t ) ; } for ( ComponentTrinity t : existingPool . allTrinities ( ) ) { results . add ( t ) ; } return results ; } } private void reset ( ) { if ( configurationHandles == null ) { return ; } configurationOwnerSupport . setConfigurationSession ( null ) ; try { childHelper . stopChildren ( ) ; } catch ( FailedToStopException e ) { logger ( ) . warn ( e ) ; } Object [ ] children = childHelper . getChildren ( ) ; for ( Object child : children ) { remove ( child ) ; } this . configurationHandles = null ; this . ready = null ; this . complete = null ; this . index = ; this . stop = false ; this . jobThreads = null ; } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; reset ( ) ; } public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { childStateReflector . stop ( ) ; reset ( ) ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ ArooaAttribute public void setFile ( File file ) { this . file = file ; if ( file == null ) { this . file = null ; configuration = null ; } else { new RootConfigurationFileCreator ( FOREACH_ELEMENT ) . createIfNone ( file ) ; this . file = file ; configuration = new XMLConfiguration ( file ) ; } } public File getFile ( ) { if ( file == null ) { return null ; } return file . getAbsoluteFile ( ) ; } public ArooaConfiguration getConfiguration ( ) { return configuration ; } public void setConfiguration ( ArooaConfiguration configuration ) { this . configuration = configuration ; } public int getPreLoad ( ) { return preLoad ; } public void setPreLoad ( int preLoad ) { this . preLoad = preLoad ; } public int getPurgeAfter ( ) { return purgeAfter ; } public void setPurgeAfter ( int purgeAfter ) { this . purgeAfter = purgeAfter ; } public boolean isParallel ( ) { return parallel ; } public void setParallel ( boolean parallel ) { this . parallel = parallel ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; completeConstruction ( ) ; } class ForeachConfigurationSession extends ListenerSupportBase < SessionStateListener > implements ConfigurationSession { private final ConfigurationSession mainSession ; private ConfigurationSession lastModifiedChildSession ; public ForeachConfigurationSession ( ) { this . mainSession = new ConfigConfigurationSession ( getArooaSession ( ) , configuration ) ; } public DragPoint dragPointFor ( Object component ) { if ( component == ForEachJob . this ) { return mainSession . dragPointFor ( component ) ; } else { for ( ConfigurationHandle configHandle : configurationHandles . values ( ) ) { ConfigurationSession confSession = new HandleConfigurationSession ( configHandle ) ; DragPoint dragPoint = confSession . dragPointFor ( component ) ; if ( dragPoint != null ) { confSession . addSessionStateListener ( new SessionStateListener ( ) { @ Override public void sessionSaved ( ConfigSessionEvent event ) { lastModifiedChildSession = null ; Iterable < SessionStateListener > listeners = copy ( ) ; for ( SessionStateListener listener : listeners ) { listener . sessionSaved ( event ) ; } } @ Override public void sessionModifed ( ConfigSessionEvent event ) { lastModifiedChildSession = event . getSource ( ) ; Iterable < SessionStateListener > listeners = copy ( ) ; for ( SessionStateListener listener : listeners ) { listener . sessionModifed ( event ) ; } } } ) ; return dragPoint ; } } return null ; } } public ArooaDescriptor getArooaDescriptor ( ) { return mainSession . getArooaDescriptor ( ) ; } public void save ( ) throws ArooaParseException { if ( lastModifiedChildSession != null ) { lastModifiedChildSession . save ( ) ; } else { mainSession . save ( ) ; } } public boolean isModified ( ) { return lastModifiedChildSession != null || mainSession . isModified ( ) ; } public void addSessionStateListener ( SessionStateListener listener ) { super . addListener ( listener ) ; mainSession . addSessionStateListener ( listener ) ; } public void removeSessionStateListener ( SessionStateListener listener ) { super . removeListener ( listener ) ; mainSession . removeSessionStateListener ( listener ) ; } } } package org . oddjob . jobs . structural ; import javax . swing . ImageIcon ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Iconic ; import org . oddjob . Structural ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class JobFolder implements Structural , Iconic { private static final Logger logger = Logger . getLogger ( JobFolder . class ) ; private static final ImageIcon icon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; protected ChildHelper < Object > childHelper = new ChildHelper < Object > ( this ) ; private String name ; protected transient volatile boolean destroyed ; synchronized public void setName ( String name ) { if ( destroyed ) { throw new IllegalStateException ( "" + this + "" ) ; } this . name = name ; } synchronized public String getName ( ) { return name ; } public void setJobs ( int index , Object child ) { if ( child == null ) { childHelper . removeChildAt ( index ) ; } else { childHelper . insertChild ( index , child ) ; } } public void addStructuralListener ( StructuralListener listener ) { if ( destroyed ) { throw new IllegalStateException ( "" + this + "" ) ; } childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } else { return name ; } } public ImageIcon iconForId ( String iconId ) { return icon ; } public void addIconListener ( IconListener listener ) { if ( destroyed ) { throw new IllegalStateException ( "" + this + "" ) ; } listener . iconEvent ( new IconEvent ( this , "" ) ) ; } public void removeIconListener ( IconListener listener ) { } public void initialised ( ) { } public void configured ( ) { } public void destroy ( ) { if ( destroyed ) { throw new IllegalStateException ( "" + this + "" ) ; } try { childHelper . stopChildren ( ) ; } catch ( FailedToStopException e ) { logger . warn ( e ) ; } destroyed = true ; } } package org . oddjob . jobs . structural ; import org . oddjob . framework . SimultaneousStructural ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; public class ParallelJob extends SimultaneousStructural { private static final long serialVersionUID = ; @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } } package org . oddjob . jobs . structural ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . framework . StructuralJob ; import org . oddjob . framework . Transient ; import org . oddjob . state . SequentialHelper ; import org . oddjob . state . ServiceManagerStateOp ; import org . oddjob . state . StateOperator ; public class ServiceManager extends StructuralJob < Object > implements Structural , Stoppable , Transient { private static final long serialVersionUID = ; @ Override protected StateOperator getStateOp ( ) { return new ServiceManagerStateOp ( ) ; } @ ArooaComponent public void setJobs ( int index , Object child ) { if ( child == null ) { childHelper . removeChildAt ( index ) ; } else { childHelper . insertChild ( index , child ) ; } } public void execute ( ) throws Exception { for ( Object child : childHelper ) { if ( stop ) { stop = false ; break ; } if ( ! ( child instanceof Runnable ) ) { logger ( ) . info ( "" + child + "" ) ; } else { Runnable job = ( Runnable ) child ; logger ( ) . info ( "" + job + "" ) ; job . run ( ) ; } if ( ! ( new SequentialHelper ( ) . canContinueAfter ( child ) ) ) { logger ( ) . info ( "" + child + "" ) ; break ; } } } } package org . oddjob . jobs . structural ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . framework . StructuralJob ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . State ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; import org . oddjob . structural . OddjobChildException ; public class RepeatJob extends StructuralJob < Runnable > implements Stoppable { private static final long serialVersionUID = ; private boolean until ; private int count ; private int times ; @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } @ ArooaComponent public void setJob ( Runnable child ) { if ( child == null ) { childHelper . removeChildAt ( ) ; } else { if ( childHelper . size ( ) > ) { throw new IllegalArgumentException ( "" ) ; } childHelper . insertChild ( , child ) ; } } protected void execute ( ) { Runnable job = childHelper . getChild ( ) ; if ( job == null ) { return ; } while ( ! stop && ! until && ( times == || count < times ) ) { ++ count ; boolean softReset = false ; if ( job instanceof Stateful && new IsSoftResetable ( ) . test ( ( ( Stateful ) job ) . lastStateEvent ( ) . getState ( ) ) ) { softReset = true ; } if ( job instanceof Resetable ) { if ( softReset ) { ( ( Resetable ) job ) . softReset ( ) ; } else { ( ( Resetable ) job ) . hardReset ( ) ; } } try { job . run ( ) ; } finally { } State state = null ; Throwable throwable = null ; if ( job instanceof Stateful ) { state = ( ( Stateful ) job ) . lastStateEvent ( ) . getState ( ) ; throwable = ( ( Stateful ) job ) . lastStateEvent ( ) . getException ( ) ; } if ( state == null ) { continue ; } if ( state . isException ( ) ) { logger ( ) . debug ( "" + job + "" ) ; throw new OddjobChildException ( throwable , job . toString ( ) ) ; } else if ( new IsStoppable ( ) . test ( state ) ) { logger ( ) . debug ( "" + job + "" + state + "" ) ; break ; } } stop = false ; } @ Override protected void onReset ( ) { count = ; until = false ; } public boolean isUntil ( ) { return until ; } public void setUntil ( boolean until ) { this . until = until ; } public int getTimes ( ) { return times ; } public void setTimes ( int times ) { this . times = times ; } public int getCount ( ) { return count ; } } package org . oddjob . jobs ; import java . io . BufferedInputStream ; import java . io . BufferedOutputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . HashMap ; import java . util . Map ; import javax . xml . transform . Transformer ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . stream . StreamResult ; import javax . xml . transform . stream . StreamSource ; import org . apache . log4j . Logger ; public class XSLTJob implements Runnable { private static final Logger logger = Logger . getLogger ( XSLTJob . class ) ; private String name ; private File [ ] from ; private File to ; private InputStream stylesheet ; private InputStream input ; private OutputStream output ; private final Map < String , Object > parameters = new HashMap < String , Object > ( ) ; private Transformer transformer ; public void run ( ) { InputStream input = this . input ; OutputStream output = this . output ; try { if ( from != null ) { if ( from . length == ) { String info = "" + from [ ] ; input = new BufferedInputStream ( new FileInputStream ( from [ ] ) ) ; if ( to != null ) { info += "" + to ; output = new BufferedOutputStream ( new FileOutputStream ( to ) ) ; } logger . info ( info ) ; } else { if ( to == null ) { throw new RuntimeException ( "" + "" ) ; } if ( ! to . isDirectory ( ) ) { throw new RuntimeException ( "" + "" ) ; } for ( File file : from ) { File outputFile = new File ( to , file . getName ( ) ) ; logger . info ( "" + file + "" + outputFile ) ; input = new BufferedInputStream ( new FileInputStream ( file ) ) ; output = new BufferedOutputStream ( new FileOutputStream ( outputFile ) ) ; transform ( input , output ) ; } return ; } } if ( input == null ) { throw new NullPointerException ( "" ) ; } if ( output == null ) { throw new NullPointerException ( "" ) ; } transform ( input , output ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { transformer = null ; try { if ( stylesheet != null ) { stylesheet . close ( ) ; } } catch ( IOException e ) { } try { if ( input != null ) { input . close ( ) ; } } catch ( IOException e ) { } try { if ( output != null ) { output . close ( ) ; } } catch ( IOException e ) { } } } protected void transform ( InputStream input , OutputStream output ) throws TransformerException , IOException { if ( transformer == null ) { if ( stylesheet == null ) { transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; } else { transformer = TransformerFactory . newInstance ( ) . newTransformer ( new StreamSource ( stylesheet ) ) ; } } for ( Map . Entry < String , Object > entry : parameters . entrySet ( ) ) { transformer . setParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } transformer . transform ( new StreamSource ( input ) , new StreamResult ( output ) ) ; } public void setStylesheet ( InputStream stylesheet ) { this . stylesheet = stylesheet ; } public void setInput ( InputStream from ) { this . input = from ; } public void setOutput ( OutputStream to ) { this . output = to ; } public Object getParameters ( String name ) { return parameters . get ( name ) ; } public void setParameters ( String name , Object value ) { this . parameters . put ( name , value ) ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public File [ ] getFrom ( ) { return from ; } public void setFrom ( File [ ] from ) { this . from = from ; } public File getTo ( ) { return to ; } public void setTo ( File to ) { this . to = to ; } @ Override public String toString ( ) { if ( name == null ) { return getClass ( ) . getName ( ) ; } else { return name ; } } } package org . oddjob . jobs ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . util . Date ; import org . oddjob . FailedToStopException ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . framework . BasePrimary ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . framework . JobDestroyedException ; import org . oddjob . framework . StopWait ; import org . oddjob . images . IconHelper ; import org . oddjob . images . StateIcons ; import org . oddjob . persist . Persistable ; import org . oddjob . scheduling . Keeper ; import org . oddjob . scheduling . LoosingOutcome ; import org . oddjob . scheduling . Outcome ; import org . oddjob . scheduling . WinningOutcome ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsDone ; import org . oddjob . state . IsExecutable ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . JobState ; import org . oddjob . state . JobStateChanger ; import org . oddjob . state . JobStateConverter ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateListener ; import org . oddjob . state . OrderedStateChanger ; import org . oddjob . state . State ; import org . oddjob . state . StateChanger ; import org . oddjob . state . StateEvent ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class GrabJob extends BasePrimary implements Runnable , Serializable , Stoppable , Resetable , Stateful , Structural { private static final long serialVersionUID = ; private transient JobStateHandler stateHandler ; private transient JobStateChanger stateChanger ; protected transient volatile boolean stop ; public enum LoosingAction { COMPLETE , INCOMPLETE , WAIT , } private transient LoosingAction onLoosing ; private transient ChildHelper < Runnable > childHelper ; private transient Keeper keeper ; private String identifier ; private Object instance ; private String winner ; private transient GrabListener listener ; public GrabJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { stateHandler = new JobStateHandler ( this ) ; childHelper = new ChildHelper < Runnable > ( this ) ; stateChanger = new JobStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override protected JobStateHandler stateHandler ( ) { return stateHandler ; } protected StateChanger < JobState > getStateChanger ( ) { return stateChanger ; } public final void run ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { if ( listener != null ) { listener . stop ( ) ; } getStateChanger ( ) . setState ( JobState . EXECUTING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; try { configure ( ) ; execute ( ) ; } catch ( final Throwable e ) { logger ( ) . error ( "" , e ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setStateException ( e ) ; } } ) ; } logger ( ) . info ( "" ) ; } finally { ComponentBoundry . pop ( ) ; } } private void execute ( ) { Runnable childJob = childHelper . getChild ( ) ; if ( childJob == null ) { throw new NullPointerException ( "" ) ; } Stateful statefulChild = ( Stateful ) childJob ; if ( keeper == null ) { throw new NullPointerException ( "" ) ; } final Outcome outcome = keeper . grab ( identifier , instance ) ; winner = outcome . getWinner ( ) ; if ( outcome . isWon ( ) ) { listener = new ChildWatcher ( statefulChild , ( WinningOutcome ) outcome ) ; childJob . run ( ) ; } else { LoosingAction loosingAction = this . onLoosing ; if ( loosingAction == null ) { loosingAction = LoosingAction . COMPLETE ; } switch ( loosingAction ) { case COMPLETE : stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( JobState . COMPLETE ) ; } } ) ; break ; case INCOMPLETE : stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( JobState . INCOMPLETE ) ; } } ) ; break ; case WAIT : listener = new StandBackAndWatch ( ( LoosingOutcome ) outcome ) ; break ; default : throw new IllegalStateException ( "" ) ; } } } class StandBackAndWatch implements StateListener , GrabListener { private final LoosingOutcome outcome ; StandBackAndWatch ( LoosingOutcome outcome ) { this . outcome = outcome ; outcome . addStateListener ( this ) ; } @ Override public void jobStateChange ( StateEvent event ) { final State state = event . getState ( ) ; if ( new IsDone ( ) . test ( state ) ) { outcome . removeStateListener ( this ) ; listener = null ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( new JobStateConverter ( ) . toJobState ( state ) ) ; } } ) ; } } synchronized public void stop ( ) { stopListening ( ) ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( JobState . INCOMPLETE ) ; } } ) ; } @ Override public void stopListening ( ) { outcome . removeStateListener ( this ) ; listener = null ; } } interface GrabListener { public void stop ( ) ; public void stopListening ( ) ; } class ChildWatcher implements GrabListener , StateListener { private final StateChanger < JobState > stateChanger = new OrderedStateChanger < JobState > ( getStateChanger ( ) , stateHandler ) ; private final Stateful child ; private final WinningOutcome outcome ; ChildWatcher ( Stateful child , WinningOutcome outcome ) { this . child = child ; this . outcome = outcome ; child . addStateListener ( this ) ; } @ Override public void jobStateChange ( StateEvent event ) { State state = event . getState ( ) ; Date time = event . getTime ( ) ; if ( state . isReady ( ) ) { stateChanger . setState ( JobState . READY , time ) ; checkStop ( ) ; } else if ( state . isStoppable ( ) ) { stateChanger . setState ( JobState . EXECUTING , time ) ; } else if ( state . isComplete ( ) ) { stateChanger . setState ( JobState . COMPLETE , time ) ; outcome . complete ( ) ; checkStop ( ) ; } else if ( state . isIncomplete ( ) ) { stateChanger . setState ( JobState . INCOMPLETE , time ) ; checkStop ( ) ; } else if ( state . isException ( ) ) { stateChanger . setStateException ( event . getException ( ) , time ) ; checkStop ( ) ; } else { stateChanger . setStateException ( new JobDestroyedException ( child ) , time ) ; checkStop ( ) ; } } private void checkStop ( ) { if ( stop ) { stopListening ( ) ; } } @ Override public void stopListening ( ) { child . removeStateListener ( this ) ; listener = null ; } synchronized public void stop ( ) { if ( child instanceof GrabListener ) { ( ( GrabListener ) child ) . stop ( ) ; } } } @ Override public void stop ( ) throws FailedToStopException { stateHandler . assertAlive ( ) ; ComponentBoundry . push ( loggerName ( ) , this ) ; try { logger ( ) . debug ( "" ) ; if ( ! stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { stop = true ; } } ) ) { logger ( ) . debug ( "" ) ; return ; } logger ( ) . info ( "" ) ; iconHelper . changeIcon ( IconHelper . STOPPING ) ; try { if ( listener != null ) { listener . stop ( ) ; listener = null ; } childHelper . stopChildren ( ) ; new StopWait ( this ) . run ( ) ; } catch ( FailedToStopException e ) { iconHelper . changeIcon ( IconHelper . EXECUTING ) ; throw e ; } logger ( ) . info ( "" ) ; } finally { ComponentBoundry . pop ( ) ; } } public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; if ( listener != null ) { listener . stopListening ( ) ; } childHelper . softResetChildren ( ) ; reset ( ) ; getStateChanger ( ) . setState ( JobState . READY ) ; stop = false ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; if ( listener != null ) { listener . stopListening ( ) ; } childHelper . hardResetChildren ( ) ; reset ( ) ; getStateChanger ( ) . setState ( JobState . READY ) ; stop = false ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } private void reset ( ) { stop = false ; winner = null ; } public void addStructuralListener ( StructuralListener listener ) { stateHandler . assertAlive ( ) ; childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } @ ArooaComponent public void setJob ( Runnable job ) { if ( job == null ) { childHelper . removeChildAt ( ) ; } else { childHelper . insertChild ( , job ) ; } } public void setKeeper ( Keeper keeper ) { this . keeper = keeper ; } public String getIdentifier ( ) { return identifier ; } public void setIdentifier ( String identifier ) { this . identifier = identifier ; } public Object getInstance ( ) { return instance ; } public void setInstance ( Object instance ) { this . instance = instance ; } public String getWinner ( ) { return winner ; } public LoosingAction getOnLoosing ( ) { return onLoosing ; } public void setOnLoosing ( LoosingAction loosingAction ) { this . onLoosing = loosingAction ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; s . writeObject ( getName ( ) ) ; if ( loggerName ( ) . startsWith ( getClass ( ) . getName ( ) ) ) { s . writeObject ( null ) ; } else { s . writeObject ( loggerName ( ) ) ; } s . writeObject ( stateHandler . lastStateEvent ( ) ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; String name = ( String ) s . readObject ( ) ; logger ( ( String ) s . readObject ( ) ) ; StateEvent savedEvent = ( StateEvent ) s . readObject ( ) ; completeConstruction ( ) ; setName ( name ) ; stateHandler . restoreLastJobStateEvent ( savedEvent ) ; iconHelper . changeIcon ( StateIcons . iconFor ( stateHandler . getState ( ) ) ) ; } protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( JobState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + GrabJob . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . jobs ; import java . io . Serializable ; import org . apache . log4j . Logger ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; public class SequenceJob implements Runnable , Serializable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( SequenceJob . class ) ; private transient String name ; private volatile Integer current ; private int from ; private transient Object watch ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public Integer getCurrent ( ) { return current ; } public void setCurrent ( Integer current ) { logger . info ( "" + current + "" ) ; this . current = current ; } public void setFrom ( int from ) { this . from = from ; } public int getFrom ( ) { return from ; } public synchronized void run ( ) { if ( current == null ) { current = new Integer ( from ) ; } else { current = new Integer ( current . intValue ( ) + ) ; ; } logger . info ( "" + current ) ; } @ ArooaAttribute public void setWatch ( Object watch ) { if ( this . watch == null ) { if ( watch == null ) { return ; } else { current = null ; } } else if ( ! this . watch . equals ( watch ) ) { current = null ; } this . watch = watch ; } public Object getWatch ( ) { return watch ; } public String toString ( ) { if ( name == null ) { return "" ; } return name ; } } package org . oddjob . jobs ; import java . io . Serializable ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaSessionAware ; public class CheckJob implements Runnable , Serializable , ArooaSessionAware { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( CheckJob . class ) ; private int result ; private transient boolean null_ ; private transient Object value ; private transient ArooaValue eq ; private transient ArooaValue ne ; private transient ArooaValue lt ; private transient ArooaValue le ; private transient ArooaValue gt ; private transient ArooaValue ge ; private transient ArooaSession session ; private transient String name ; @ SuppressWarnings ( "" ) public void run ( ) { result = ; Check [ ] checks = new Check [ ] { new Check ( ) { @ Override public boolean required ( ) { return true ; } @ Override public boolean check ( ) { return ! ( value == null ^ null_ ) ; } @ Override public String toString ( ) { return "" + value + "" + ( null_ ? "" : "" ) + "" ; } } , new Check ( ) { @ Override public boolean required ( ) { return eq != null ; } @ Override public boolean check ( ) { return value != null && value . equals ( convert ( eq ) ) ; } @ Override public String toString ( ) { return "" + value + "" + eq + "" ; } } , new Check ( ) { @ Override public boolean required ( ) { return ne != null ; } @ Override public boolean check ( ) { return value != null && ! value . equals ( convert ( ne ) ) ; } @ Override public String toString ( ) { return "" + value + "" + ne + "" ; } } , new Check ( ) { @ Override public boolean required ( ) { return lt != null ; } @ SuppressWarnings ( "" ) @ Override public boolean check ( ) { return value != null && ( ( Comparable ) value ) . compareTo ( convert ( lt ) ) < ; } @ Override public String toString ( ) { return "" + value + "" + lt + "" ; } } , new Check ( ) { @ Override public boolean required ( ) { return le != null ; } @ Override @ SuppressWarnings ( "" ) public boolean check ( ) { return value != null && ( ( Comparable ) value ) . compareTo ( convert ( le ) ) <= ; } @ Override public String toString ( ) { return "" + value + "" + le + "" ; } } , new Check ( ) { @ Override public boolean required ( ) { return gt != null ; } @ Override @ SuppressWarnings ( "" ) public boolean check ( ) { return value != null && ( ( Comparable ) value ) . compareTo ( convert ( gt ) ) > ; } @ Override public String toString ( ) { return "" + value + "" + gt + "" ; } } , new Check ( ) { @ Override public boolean required ( ) { return ge != null ; } @ Override @ SuppressWarnings ( "" ) public boolean check ( ) { return value != null && ( ( Comparable ) value ) . compareTo ( convert ( ge ) ) >= ; } @ Override public String toString ( ) { return "" + value + "" + ge + "" ; } } } ; for ( Check check : checks ) { if ( ! check . required ( ) ) { continue ; } if ( check . check ( ) ) { logger . debug ( "" + check + "" ) ; } else { logger . info ( "" + check + "" ) ; result = ; return ; } } logger . info ( "" ) ; } interface Check { boolean required ( ) ; boolean check ( ) ; } Object convert ( ArooaValue rhs ) { ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; try { return converter . convert ( rhs , value . getClass ( ) ) ; } catch ( NoConversionAvailableException e ) { throw new RuntimeException ( e ) ; } catch ( ConversionFailedException e ) { throw new RuntimeException ( e ) ; } } @ ArooaHidden public void setArooaSession ( ArooaSession session ) { this . session = session ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public boolean getNull ( ) { return null_ ; } @ ArooaAttribute public void setNull ( boolean value ) { this . null_ = value ; } public Object getValue ( ) { return value ; } @ ArooaAttribute public void setValue ( Object value ) { this . value = value ; } public ArooaValue getEq ( ) { return eq ; } @ ArooaAttribute public void setEq ( ArooaValue eq ) { this . eq = eq ; } public ArooaValue getNe ( ) { return ne ; } @ ArooaAttribute public void setNe ( ArooaValue ne ) { this . ne = ne ; } public ArooaValue getLt ( ) { return lt ; } @ ArooaAttribute public void setLt ( ArooaValue lt ) { this . lt = lt ; } public ArooaValue getGt ( ) { return gt ; } @ ArooaAttribute public void setGt ( ArooaValue gt ) { this . gt = gt ; } public ArooaValue getLe ( ) { return le ; } @ ArooaAttribute public void setLe ( ArooaValue le ) { this . le = le ; } public ArooaValue getGe ( ) { return ge ; } @ ArooaAttribute public void setGe ( ArooaValue ge ) { this . ge = ge ; } public int getResult ( ) { return result ; } @ Override public String toString ( ) { return name == null ? CheckJob . class . getSimpleName ( ) : name ; } } package org . oddjob . jobs ; import java . util . LinkedList ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . framework . SimpleJob ; import org . oddjob . scheduling . ExecutorThrottleType ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . State ; import org . oddjob . state . StateCondition ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class WaitJob extends SimpleJob implements Stoppable { private static final long DEFAULT_WAIT_SLEEP = ; private long pause ; private Object forProperty ; private boolean forSet ; private StateCondition state ; public void setPause ( long delay ) { this . pause = delay ; } public long getPause ( ) { return pause ; } public int execute ( ) throws Exception { if ( state != null ) { if ( forProperty == null ) { throw new IllegalStateException ( "" ) ; } if ( ! ( forProperty instanceof Stateful ) ) { throw new IllegalStateException ( "" ) ; } waitForState ( ) ; } else if ( forSet ) { logger ( ) . debug ( "" ) ; waitFor ( ) ; } else { simpleWait ( ) ; } return ; } protected void simpleWait ( ) { sleep ( pause ) ; } protected void waitFor ( ) { long sleep = pause ; if ( sleep == ) { sleep = DEFAULT_WAIT_SLEEP ; } while ( ! stop ) { stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { configure ( ) ; } } ) ; if ( forProperty != null ) { break ; } sleep ( sleep ) ; } } protected void waitForState ( ) { final long waitBetweenChecks ; if ( pause == ) { waitBetweenChecks = DEFAULT_WAIT_SLEEP ; } else { waitBetweenChecks = pause ; } final LinkedList < State > states = new LinkedList < State > ( ) ; StateListener listener = new StateListener ( ) { synchronized public void jobStateChange ( StateEvent event ) { synchronized ( states ) { states . add ( event . getState ( ) ) ; stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler . wake ( ) ; } } ) ; } } } ; ( ( Stateful ) forProperty ) . addStateListener ( listener ) ; while ( ! stop ) { State now = null ; synchronized ( states ) { if ( ! states . isEmpty ( ) ) { now = states . removeFirst ( ) ; logger ( ) . debug ( "" + now ) ; } } if ( now != null && state . test ( now ) ) { logger ( ) . debug ( "" + state ) ; break ; } logger ( ) . debug ( "" + state ) ; sleep ( waitBetweenChecks ) ; } ( ( Stateful ) forProperty ) . removeStateListener ( listener ) ; } public Object getFor ( ) { return forProperty ; } @ ArooaAttribute public void setFor ( Object forProperty ) { this . forProperty = forProperty ; this . forSet = true ; } public StateCondition getState ( ) { return state ; } @ ArooaAttribute public void setState ( StateCondition state ) { this . state = state ; } } package org . oddjob . jobs ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . OutputStream ; import java . util . HashMap ; import java . util . Map ; import org . oddjob . Stoppable ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . deploy . annotations . ArooaText ; import org . oddjob . arooa . utils . ArooaTokenizer ; import org . oddjob . arooa . utils . QuoteTokenizerFactory ; import org . oddjob . framework . SerializableJob ; import org . oddjob . logging . ConsoleOwner ; import org . oddjob . logging . LogArchive ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LoggingOutputStream ; import org . oddjob . logging . cache . LogArchiveImpl ; import org . oddjob . util . IO ; import org . oddjob . util . OddjobConfigException ; public class ExecJob extends SerializableJob implements Stoppable , ConsoleOwner { private static final long serialVersionUID = ; private static int consoleCount ; private static String uniqueConsoleId ( ) { synchronized ( ExecJob . class ) { return ( "" + consoleCount ++ ) ; } } private transient LogArchiveImpl consoleArchive ; private void completeConstruction ( ) { consoleArchive = new LogArchiveImpl ( uniqueConsoleId ( ) , LogArchiver . MAX_HISTORY ) ; this . environment = new HashMap < String , String > ( ) ; } private File dir ; private String command ; private String [ ] args ; private boolean newEnvironment ; private Map < String , String > environment ; private boolean redirectStderr ; private transient InputStream stdin ; private transient OutputStream stdout ; private transient OutputStream stderr ; private transient volatile Process proc ; private transient volatile Thread thread ; private int exitValue ; public ExecJob ( ) { completeConstruction ( ) ; } public void setArgs ( String [ ] args ) { this . args = args ; } @ ArooaText public void setCommand ( String command ) { this . command = command ; } public String getCommand ( ) { return command ; } @ ArooaAttribute public void setDir ( File dir ) { this . dir = dir ; } public void setNewEnvironment ( boolean explicitEnvironment ) { this . newEnvironment = explicitEnvironment ; } public boolean isNewEnvironment ( ) { return newEnvironment ; } public void setEnvironment ( String name , String value ) { if ( value == null ) { this . environment . remove ( name ) ; } else { this . environment . put ( name , value ) ; } } public String getEnvironment ( String name ) { return this . environment . get ( name ) ; } public void setRedirectStderr ( boolean redirectErrorStream ) { this . redirectStderr = redirectErrorStream ; } public boolean isRedirectStderr ( ) { return this . redirectStderr ; } public void setStdin ( InputStream stdin ) { this . stdin = stdin ; } public InputStream getStdin ( ) { return stdin ; } public void setStdout ( OutputStream stdout ) { this . stdout = stdout ; } public OutputStream getStdout ( ) { return stdout ; } public void setStderr ( OutputStream stderr ) { this . stderr = stderr ; } public OutputStream getStderr ( ) { return stderr ; } public ArooaTokenizer commandTokenizer ( ) { return new QuoteTokenizerFactory ( "" , '' , '' ) . newTokenizer ( ) ; } protected int execute ( ) throws Exception { ProcessBuilder processBuilder ; String [ ] theArgs = args ; if ( theArgs == null && command != null ) { theArgs = commandTokenizer ( ) . parse ( command . trim ( ) ) ; logger ( ) . info ( "" + command ) ; } if ( theArgs == null || theArgs . length == ) { throw new OddjobConfigException ( "" ) ; } logger ( ) . info ( "" + displayArgs ( theArgs ) ) ; processBuilder = new ProcessBuilder ( theArgs ) ; if ( dir == null ) { dir = processBuilder . directory ( ) ; } else { processBuilder . directory ( dir ) ; } Map < String , String > env = processBuilder . environment ( ) ; if ( newEnvironment ) { env . clear ( ) ; } if ( environment != null ) { for ( Map . Entry < String , String > entry : environment . entrySet ( ) ) { env . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } processBuilder . redirectErrorStream ( redirectStderr ) ; proc = processBuilder . start ( ) ; final InputStream processStdOut = proc . getInputStream ( ) ; Thread outT = new Thread ( new Runnable ( ) { public void run ( ) { try { BufferedInputStream bis = new BufferedInputStream ( processStdOut ) ; OutputStream os = new LoggingOutputStream ( stdout , LogLevel . INFO , consoleArchive ) ; IO . copy ( bis , os ) ; os . close ( ) ; bis . close ( ) ; } catch ( IOException e ) { logger ( ) . error ( "" , e ) ; } } } ) ; outT . start ( ) ; Thread errT = null ; if ( ! redirectStderr ) { final InputStream processStdErr = proc . getErrorStream ( ) ; errT = new Thread ( new Runnable ( ) { public void run ( ) { try { BufferedInputStream bis = new BufferedInputStream ( processStdErr ) ; OutputStream os = new LoggingOutputStream ( stderr , LogLevel . ERROR , consoleArchive ) ; IO . copy ( bis , os ) ; os . close ( ) ; bis . close ( ) ; } catch ( IOException e ) { logger ( ) . error ( "" , e ) ; } } } ) ; errT . start ( ) ; } if ( stdin != null ) { OutputStream processStdIn = proc . getOutputStream ( ) ; IO . copy ( stdin , processStdIn ) ; stdin . close ( ) ; processStdIn . close ( ) ; } thread = Thread . currentThread ( ) ; try { logger ( ) . debug ( "" ) ; exitValue = proc . waitFor ( ) ; logger ( ) . debug ( "" + exitValue ) ; } finally { thread = null ; proc . destroy ( ) ; proc = null ; synchronized ( this ) { notifyAll ( ) ; } } return exitValue ; } public void onStop ( ) { Process proc = this . proc ; if ( proc == null ) { return ; } proc . destroy ( ) ; for ( int i = ; i < && thread != null ; ++ i ) { synchronized ( this ) { try { logger ( ) . debug ( "" ) ; wait ( ) ; } catch ( InterruptedException e ) { return ; } } } Thread thread = this . thread ; if ( thread != null ) { logger ( ) . warn ( "" ) ; thread . interrupt ( ) ; } } public File getDir ( ) { return dir ; } public int getExitValue ( ) { return exitValue ; } public LogArchive consoleLog ( ) { return consoleArchive ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; completeConstruction ( ) ; } private static String displayArgs ( String [ ] args ) { StringBuilder builder = new StringBuilder ( ) ; for ( String arg : args ) { if ( builder . length ( ) > ) { builder . append ( '' ) ; } builder . append ( '' ) ; builder . append ( arg ) ; builder . append ( '' ) ; } return builder . toString ( ) ; } } package org . oddjob . jobs . job ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . framework . SerializableJob ; import org . oddjob . state . MirrorState ; import org . oddjob . util . OddjobConfigException ; public class StartJob extends SerializableJob { private static final long serialVersionUID = ; private transient Runnable job ; @ ArooaAttribute synchronized public void setJob ( Runnable node ) { this . job = node ; } synchronized public Runnable getJob ( ) { return this . job ; } protected int execute ( ) throws Exception { if ( job == null ) { throw new OddjobConfigException ( "" ) ; } job . run ( ) ; return ; } } package org . oddjob . jobs . job ; import org . oddjob . Resetable ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . framework . SimpleJob ; import org . oddjob . persist . FilePersister ; public class ResetJob extends SimpleJob { private transient Resetable job ; private transient String level ; @ ArooaAttribute synchronized public void setJob ( Resetable node ) { if ( node == null ) { throw new NullPointerException ( "" ) ; } this . job = node ; } synchronized public Resetable getJob ( ) { return this . job ; } protected int execute ( ) throws Exception { if ( job == null ) { throw new NullPointerException ( "" ) ; } String level = this . level . toLowerCase ( ) ; if ( level == null ) { level = "" ; } if ( ! "" . equals ( level ) && ! "" . equals ( level ) ) { throw new IllegalArgumentException ( "" ) ; } logger ( ) . info ( "" + level + "" + job + "" ) ; if ( level . equals ( "" ) ) { ( ( Resetable ) job ) . softReset ( ) ; } else { ( ( Resetable ) job ) . hardReset ( ) ; } return ; } public String getLevel ( ) { return level ; } public void setLevel ( String level ) { this . level = level ; } } package org . oddjob . jobs . job ; import java . util . LinkedList ; import org . oddjob . OddjobComponentResolver ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . OwnerStateListener ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . framework . SimpleJob ; import org . oddjob . framework . StructuralJob ; import org . oddjob . images . IconHelper ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . ParentState ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; import org . oddjob . util . OddjobConfigException ; public class RunJob extends StructuralJob < Object > implements Structural , Stoppable , ConfigurationOwner { private static final long serialVersionUID = ; private transient Object job ; @ ArooaAttribute synchronized public void setJob ( Object node ) { this . job = node ; } synchronized public Object getJob ( ) { return this . job ; } @ Override protected StateOperator getStateOp ( ) { return new StateOperator ( ) { @ Override public ParentState evaluate ( State ... states ) { if ( states . length > && states [ ] . isDestroyed ( ) ) { if ( childStateReflector . isRunning ( ) ) { ComponentBoundry . push ( loggerName ( ) , RunJob . this ) ; try { childStateReflector . stop ( ) ; childHelper . removeAllChildren ( ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { if ( stateHandler . lastStateEvent ( ) . getState ( ) . isStoppable ( ) ) { logger ( ) . info ( "" ) ; getStateChanger ( ) . setState ( ParentState . COMPLETE ) ; } else { logger ( ) . info ( "" ) ; } } } ) ; } finally { ComponentBoundry . pop ( ) ; } } return ParentState . READY ; } else { return new WorstStateOp ( ) . evaluate ( states ) ; } } } ; } protected void execute ( ) throws Exception { if ( job == null ) { throw new OddjobConfigException ( "" ) ; } Object proxy ; if ( childHelper . size ( ) == ) { OddjobComponentResolver resolver = new OddjobComponentResolver ( ) ; proxy = resolver . resolve ( job , getArooaSession ( ) ) ; if ( proxy != job && proxy instanceof ArooaSessionAware ) { ( ( ArooaSessionAware ) proxy ) . setArooaSession ( getArooaSession ( ) ) ; } childHelper . addChild ( proxy ) ; } else { proxy = childHelper . getChild ( ) ; } final LinkedList < State > states = new LinkedList < State > ( ) ; StateListener listener = null ; if ( job instanceof Stateful ) { listener = new StateListener ( ) { public void jobStateChange ( StateEvent event ) { synchronized ( states ) { states . add ( event . getState ( ) ) ; states . notifyAll ( ) ; } } } ; ( ( Stateful ) job ) . addStateListener ( listener ) ; } if ( proxy instanceof Runnable ) { Runnable runnable = ( Runnable ) proxy ; runnable . run ( ) ; } if ( job instanceof Stateful ) { boolean executed = false ; try { while ( ! stop ) { State now = null ; synchronized ( states ) { if ( ! states . isEmpty ( ) ) { now = states . removeFirst ( ) ; logger ( ) . debug ( "" + now ) ; } else { logger ( ) . debug ( "" ) ; iconHelper . changeIcon ( IconHelper . SLEEPING ) ; try { states . wait ( ) ; } catch ( InterruptedException e ) { logger ( ) . debug ( "" ) ; Thread . currentThread ( ) . interrupt ( ) ; } if ( ! stop ) { iconHelper . changeIcon ( IconHelper . EXECUTING ) ; } } } if ( now != null ) { if ( now . isDestroyed ( ) ) { childHelper . removeAllChildren ( ) ; throw new IllegalStateException ( "" ) ; } if ( now . isStoppable ( ) ) { executed = true ; } if ( now . isPassable ( ) && ( executed || ! now . isReady ( ) ) ) { logger ( ) . debug ( "" + now ) ; break ; } continue ; } } } finally { ( ( Stateful ) job ) . removeStateListener ( listener ) ; } } } protected void sleep ( final long waitTime ) { stateHandler ( ) . assertAlive ( ) ; if ( ! stateHandler ( ) . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { if ( stop ) { logger ( ) . debug ( "" ) ; return ; } logger ( ) . debug ( "" + ( waitTime == ? "" : "" + waitTime + "" ) + "" ) ; iconHelper . changeIcon ( IconHelper . SLEEPING ) ; try { stateHandler ( ) . sleep ( waitTime ) ; } catch ( InterruptedException e ) { logger ( ) . debug ( "" ) ; Thread . currentThread ( ) . interrupt ( ) ; } if ( ! stop ) { iconHelper . changeIcon ( IconHelper . EXECUTING ) ; } } } ) ) { throw new IllegalStateException ( "" ) ; } } public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; childStateReflector . stop ( ) ; childHelper . removeAllChildren ( ) ; stop = false ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; childStateReflector . stop ( ) ; childHelper . removeAllChildren ( ) ; stop = false ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { } @ Override public ConfigurationSession provideConfigurationSession ( ) { return null ; } @ Override public DesignFactory rootDesignFactory ( ) { return null ; } @ Override public ArooaElement rootElement ( ) { return null ; } } package org . oddjob . jobs . job ; import org . oddjob . FailedToStopException ; import org . oddjob . Stoppable ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . framework . SerializableJob ; import org . oddjob . jmx . JMXClientJob ; public class StopJob extends SerializableJob implements Stoppable { private static final long serialVersionUID = ; private transient Stoppable job ; private transient volatile Thread thread ; @ ArooaAttribute public void setJob ( Stoppable node ) { this . job = node ; } public Stoppable getJob ( ) { return this . job ; } protected int execute ( ) throws Exception { if ( job == null ) { throw new NullPointerException ( "" ) ; } logger ( ) . info ( "" + job + "" ) ; thread = Thread . currentThread ( ) ; try { job . stop ( ) ; } finally { thread = null ; } return ; } @ Override protected void onStop ( ) throws FailedToStopException { if ( thread == Thread . currentThread ( ) ) { throw new FailedToStopException ( this , "" + "" ) ; } } } package org . oddjob . jobs . job ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . framework . SimpleJob ; import org . oddjob . state . JobState ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . state . StateMemory ; import org . oddjob . util . OddjobConfigException ; public class DependsJob extends SimpleJob implements Stoppable , StateListener { private static final long serialVersionUID = ; private transient Stateful job ; private transient volatile StateEvent event ; public DependsJob ( ) { logger ( ) . warn ( "" ) ; } @ ArooaAttribute synchronized public void setJob ( Stateful node ) { this . job = node ; } synchronized public Stateful getJob ( ) { return this . job ; } protected int execute ( ) throws Throwable { if ( job == null ) { throw new OddjobConfigException ( "" ) ; } try { job . addStateListener ( this ) ; while ( ! stop ) { State state = event . getState ( ) ; logger ( ) . debug ( "" + state + "" ) ; long sleep = ; if ( state == JobState . READY ) { if ( job instanceof Runnable ) { StateMemory remember = new StateMemory ( ) ; remember . run ( ( Runnable ) job ) ; if ( remember . getJobState ( ) . isComplete ( ) ) { return ; } else if ( remember . getJobState ( ) . isIncomplete ( ) ) { return ; } else if ( remember . getJobState ( ) . isException ( ) ) { throw remember . getThrowable ( ) ; } } else { sleep = ; } } else if ( state . isComplete ( ) ) { return ; } else if ( state . isIncomplete ( ) ) { return ; } else if ( state . isException ( ) ) { throw event . getException ( ) ; } else { logger ( ) . debug ( "" + job + "" ) ; sleep = ; } sleep ( sleep ) ; } return ; } finally { job . removeStateListener ( this ) ; } } @ Override public void jobStateChange ( StateEvent event ) { this . event = event ; synchronized ( this ) { notifyAll ( ) ; } } } package org . oddjob . jobs ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import org . oddjob . launch . Launcher ; public class LaunchJob implements Runnable , Serializable { private static final long serialVersionUID = ; private String name ; private transient Launcher launcher ; public LaunchJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { launcher = new Launcher ( ) ; } @ Override public void run ( ) { launcher . run ( ) ; } public ClassLoader getClassLoader ( ) { return launcher . getClassLoader ( ) ; } public void setClassLoader ( ClassLoader classLoader ) { launcher . setClassLoader ( classLoader ) ; } public String getClassName ( ) { return launcher . getClassName ( ) ; } public void setClassName ( String className ) { launcher . setClassName ( className ) ; } public String [ ] getArgs ( ) { return launcher . getArgs ( ) ; } public void setArgs ( String [ ] args ) { launcher . setArgs ( args ) ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; completeConstruction ( ) ; } @ Override public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } else { return name ; } } } package org . oddjob . jobs ; import java . io . OutputStream ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . BeanView ; import org . oddjob . arooa . reflect . BeanViews ; import org . oddjob . beanbus . BeanSheet ; import org . oddjob . beanbus . BusException ; import org . oddjob . beanbus . Destination ; import org . oddjob . beanbus . Driver ; import org . oddjob . beanbus . SimpleBus ; public class BeanReportJob implements Runnable , ArooaSessionAware { private String name ; private Iterable < ? > beans ; private OutputStream output ; private boolean noHeaders ; private ArooaSession session ; private BeanView beanView ; @ ArooaHidden @ Override public void setArooaSession ( ArooaSession session ) { this . session = session ; } @ Override public void run ( ) { if ( beans == null ) { throw new NullPointerException ( "" ) ; } if ( output == null ) { throw new NullPointerException ( "" ) ; } final BeanSheet sheet = new BeanSheet ( ) ; sheet . setArooaSession ( session ) ; sheet . setOutput ( output ) ; sheet . setNoHeaders ( noHeaders ) ; sheet . setBeanViews ( new BeanViews ( ) { @ Override public BeanView beanViewFor ( ArooaClass arooaClass ) { return beanView ; } } ) ; SimpleBus < Iterable < Object > > bus = new SimpleBus < Iterable < Object > > ( ) ; bus . setDriver ( new Driver < Iterable < Object > > ( ) { @ Override public void go ( ) throws BusException { sheet . accept ( beans ) ; } @ Override public void setTo ( Destination < ? super Iterable < Object > > to ) { } @ Override public void stop ( ) { } } ) ; bus . run ( ) ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public Iterable < ? > getBeans ( ) { return beans ; } public void setBeans ( Iterable < ? > beans ) { this . beans = beans ; } public OutputStream getOutput ( ) { return output ; } public void setOutput ( OutputStream output ) { this . output = output ; } public boolean isNoHeaders ( ) { return noHeaders ; } public void setNoHeaders ( boolean noHeader ) { this . noHeaders = noHeader ; } public BeanView getBeanView ( ) { return beanView ; } public void setBeanView ( BeanView beanExtraProvider ) { this . beanView = beanExtraProvider ; } @ Override public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } return name ; } } package org . oddjob ; public interface Forceable { public void force ( ) ; } package org . oddjob . state ; public class AssertNonDestroyed implements StateOperator { @ Override public ParentState evaluate ( State ... states ) throws IllegalStateException { for ( int i = ; i < states . length ; ++ i ) { if ( states [ i ] . isDestroyed ( ) ) { throw new IllegalStateException ( "" + i + "" ) ; } } return null ; } } package org . oddjob . state ; public interface StateCondition { public boolean test ( State state ) ; } package org . oddjob . state ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . framework . StructuralJob ; public class IfJob extends StructuralJob < Object > implements Runnable , Stateful , Resetable , Structural , Stoppable { private static final long serialVersionUID = ; private StateCondition state = StateConditions . COMPLETE ; private volatile boolean then ; public StateCondition getState ( ) { return state ; } @ ArooaAttribute public void setState ( StateCondition state ) { this . state = state ; } @ ArooaComponent public void setJobs ( int index , Runnable job ) { if ( job == null ) { childHelper . removeChildAt ( index ) ; } else { childHelper . insertChild ( index , job ) ; } } @ Override protected StateOperator getStateOp ( ) { return new StateOperator ( ) { public ParentState evaluate ( State ... states ) { if ( states . length < ) { return ParentState . READY ; } then = state . test ( states [ ] ) ; if ( then ) { if ( states . length > ) { return new ParentStateConverter ( ) . toStructuralState ( states [ ] ) ; } } else { if ( states . length > ) { return new ParentStateConverter ( ) . toStructuralState ( states [ ] ) ; } } return ParentState . COMPLETE ; } } ; } protected void execute ( ) { if ( childHelper . size ( ) < ) { return ; } Stateful depends = ( Stateful ) childHelper . getChildAt ( ) ; ( ( Runnable ) depends ) . run ( ) ; if ( stop ) { stop = false ; return ; } if ( then ) { if ( childHelper . size ( ) < ) { return ; } Runnable job = ( Runnable ) childHelper . getChildAt ( ) ; job . run ( ) ; } else { if ( childHelper . size ( ) < ) { return ; } Runnable job = ( Runnable ) childHelper . getChildAt ( ) ; job . run ( ) ; } } } package org . oddjob . state ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . framework . StructuralJob ; public class EqualsState extends StructuralJob < Stateful > implements Stoppable { private static final long serialVersionUID = ; private StateCondition state = StateConditions . COMPLETE ; public StateCondition getState ( ) { return state ; } @ ArooaAttribute public void setState ( StateCondition state ) { this . state = state ; } @ Override protected StateOperator getStateOp ( ) { return new StateOperator ( ) { public ParentState evaluate ( State ... states ) { if ( states . length == ) { return ParentState . READY ; } State state = states [ ] ; if ( EqualsState . this . state . test ( state ) ) { return ParentState . COMPLETE ; } else { return ParentState . INCOMPLETE ; } } } ; } @ ArooaComponent public synchronized void setJob ( Stateful job ) { if ( job == null ) { childHelper . removeChildAt ( ) ; } else { childHelper . insertChild ( , job ) ; } } @ Override protected void execute ( ) throws Throwable { Stateful job = childHelper . getChild ( ) ; if ( job == null ) { throw new NullPointerException ( "" ) ; } if ( job instanceof Runnable ) { ( ( Runnable ) job ) . run ( ) ; } } } package org . oddjob . state ; import org . oddjob . Stateful ; public interface State { public boolean isReady ( ) ; public boolean isStoppable ( ) ; public boolean isPassable ( ) ; public boolean isComplete ( ) ; public boolean isIncomplete ( ) ; public boolean isException ( ) ; public boolean isDestroyed ( ) ; } package org . oddjob . state ; import java . util . Date ; import org . oddjob . Stateful ; import org . oddjob . framework . JobDestroyedException ; public class StateExchange { private final StateChanger < ParentState > recipient ; private final Stateful source ; private boolean running ; private final StateListener stateListener = new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { ParentState state = ( ParentState ) event . getState ( ) ; Date time = event . getTime ( ) ; switch ( state ) { case DESTROYED : break ; case EXCEPTION : Throwable throwable = event . getException ( ) ; recipient . setStateException ( throwable , time ) ; break ; default : recipient . setState ( state , time ) ; break ; } } } ; public StateExchange ( Stateful source , StateChanger < ParentState > recipient ) { this . source = source ; this . recipient = recipient ; } public void start ( ) throws JobDestroyedException { synchronized ( this ) { if ( running ) { return ; } running = true ; } source . addStateListener ( stateListener ) ; } public void stop ( ) { synchronized ( this ) { running = false ; } source . removeStateListener ( stateListener ) ; } public boolean isRunning ( ) { synchronized ( this ) { return running ; } } } package org . oddjob . state ; import org . oddjob . Structural ; public interface StateOperator { public ParentState evaluate ( State ... states ) ; } package org . oddjob . state ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public enum StateConditions implements StateCondition { READY ( ) { @ Override public boolean test ( State state ) { return state . isReady ( ) ; } } , RUNNING ( ) { @ Override public boolean test ( State state ) { return state . isStoppable ( ) ; } } , INCOMPLETE ( ) { @ Override public boolean test ( State state ) { return state . isIncomplete ( ) ; } } , COMPLETE ( ) { @ Override public boolean test ( State state ) { return state . isComplete ( ) ; } } , EXCEPTION ( ) { @ Override public boolean test ( State state ) { return state . isException ( ) ; } } , DESTROYED ( ) { @ Override public boolean test ( State state ) { return state . isDestroyed ( ) ; } } , FAILURE ( ) { @ Override public boolean test ( State state ) { return state . isIncomplete ( ) || state . isException ( ) ; } } , FINISHED ( ) { @ Override public boolean test ( State state ) { return state . isComplete ( ) || state . isIncomplete ( ) || state . isException ( ) ; } } , EXECUTING ( ) { @ Override public boolean test ( State state ) { return state == JobState . EXECUTING || state == ParentState . EXECUTING || state == ServiceState . STARTING ; } } , STARTED ( ) { @ Override public boolean test ( State state ) { return state == ServiceState . STARTED ; } } , ; public static class Conversions implements ConversionProvider { @ Override public void registerWith ( ConversionRegistry registry ) { registry . register ( String . class , StateCondition . class , new Convertlet < String , StateCondition > ( ) { @ Override public StateCondition convert ( String from ) throws ConvertletException { if ( from . startsWith ( "" ) ) { return new IsNot ( StateConditions . valueOf ( from . substring ( ) . toUpperCase ( ) ) ) ; } else { return StateConditions . valueOf ( from . toUpperCase ( ) ) ; } } } ) ; } } } package org . oddjob . state ; public class IsStoppable implements StateCondition { @ Override public boolean test ( State state ) { return state . isStoppable ( ) ; } } package org . oddjob . state ; public class IsAnyState implements StateCondition { public boolean test ( State state ) { return true ; } } package org . oddjob . state ; public class IsDone implements StateCondition { @ Override public boolean test ( State state ) { if ( state . isComplete ( ) || state . isIncomplete ( ) || state . isException ( ) ) { return true ; } else { return false ; } } } package org . oddjob . state ; import org . oddjob . FailedToStopException ; import org . oddjob . framework . SimultaneousStructural ; abstract public class StateReflector extends SimultaneousStructural { private static final long serialVersionUID = ; public void stop ( ) throws FailedToStopException { if ( ! childStateReflector . isRunning ( ) ) { return ; } logger ( ) . info ( "" ) ; childHelper . stopChildren ( ) ; logger ( ) . info ( "" ) ; } } package org . oddjob . state ; import org . oddjob . Stateful ; public class StateMemory implements StateListener { private volatile State jobState ; private volatile Throwable t ; @ Override public void jobStateChange ( StateEvent event ) { if ( jobState == null || jobState == JobState . READY || jobState == JobState . EXECUTING ) { jobState = event . getState ( ) ; t = event . getException ( ) ; } } public State getJobState ( ) { return jobState ; } public Throwable getThrowable ( ) { return t ; } public void run ( Runnable job ) { if ( job instanceof Stateful ) { ( ( Stateful ) job ) . addStateListener ( this ) ; } else { jobState = JobState . COMPLETE ; } try { job . run ( ) ; } finally { if ( job instanceof Stateful ) { ( ( Stateful ) job ) . removeStateListener ( this ) ; } } } } package org . oddjob . state ; import org . oddjob . Stateful ; public class ServiceStateHandler extends StateHandler < ServiceState > { public ServiceStateHandler ( Stateful source ) { super ( source , ServiceState . READY ) ; } } package org . oddjob . state ; public class AndStateOp implements StateOperator { public ParentState evaluate ( State ... states ) { new AssertNonDestroyed ( ) . evaluate ( states ) ; ParentState state = ParentState . READY ; if ( states . length > ) { state = new ParentStateConverter ( ) . toStructuralState ( states [ ] ) ; for ( int i = ; i < states . length ; ++ i ) { State next = states [ i ] ; if ( state . isStoppable ( ) || next . isStoppable ( ) ) { state = ParentState . ACTIVE ; } else if ( state . isException ( ) || next . isException ( ) ) { state = ParentState . EXCEPTION ; } else if ( state . isIncomplete ( ) && next . isIncomplete ( ) ) { state = ParentState . INCOMPLETE ; } else if ( state . isComplete ( ) && next . isComplete ( ) ) { state = ParentState . COMPLETE ; } else { state = ParentState . READY ; } } } return state ; } } package org . oddjob . state ; public class IsSoftResetable implements StateCondition { @ Override public boolean test ( State state ) { return state . isReady ( ) || state . isIncomplete ( ) || state . isException ( ) ; } } package org . oddjob . state ; public class JobStateConverter { public JobState toJobState ( State state ) { if ( state . isReady ( ) ) { return JobState . READY ; } else if ( state . isStoppable ( ) ) { return JobState . EXECUTING ; } else if ( state . isIncomplete ( ) ) { return JobState . INCOMPLETE ; } else if ( state . isComplete ( ) ) { return JobState . COMPLETE ; } else if ( state . isException ( ) ) { return JobState . EXCEPTION ; } else if ( state . isDestroyed ( ) ) { return JobState . DESTROYED ; } else { throw new IllegalStateException ( "" + state ) ; } } } package org . oddjob . state ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . util . Date ; import java . util . EventObject ; import org . oddjob . Stateful ; import org . oddjob . util . IO ; public class StateEvent extends EventObject implements Serializable { private static final long serialVersionUID = ; static final String REPLACEMENT_EXCEPTION_TEXT = "" ; private State state ; private Date time ; private Throwable exception ; class ExceptionReplacement extends Exception { private static final long serialVersionUID = ; public ExceptionReplacement ( Throwable replacing ) { super ( REPLACEMENT_EXCEPTION_TEXT + replacing . getMessage ( ) ) ; super . setStackTrace ( exception . getStackTrace ( ) ) ; } } public StateEvent ( Stateful job , State jobState , Date time , Throwable exception ) { super ( job ) ; if ( jobState == null ) { throw new NullPointerException ( "" ) ; } this . state = jobState ; this . time = time ; this . exception = exception ; } public StateEvent ( Stateful job , State jobState , Throwable exception ) { this ( job , jobState , new Date ( ) , exception ) ; } public StateEvent ( Stateful job , State jobState ) { this ( job , jobState , null ) ; } @ Override public Stateful getSource ( ) { return ( Stateful ) super . getSource ( ) ; } public State getState ( ) { return state ; } public Throwable getException ( ) { return exception ; } public Date getTime ( ) { return time ; } public String toString ( ) { return "" + getSource ( ) + "" + state ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . writeObject ( state ) ; s . writeObject ( time ) ; if ( IO . canSerialize ( exception ) ) { s . writeObject ( exception ) ; } else { s . writeObject ( new ExceptionReplacement ( exception ) ) ; } } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { state = ( State ) s . readObject ( ) ; time = ( Date ) s . readObject ( ) ; exception = ( Throwable ) s . readObject ( ) ; } } package org . oddjob . state ; import java . util . Date ; import org . oddjob . framework . JobDestroyedException ; public interface StateChanger < S extends State > { public void setState ( S state ) throws JobDestroyedException ; public void setState ( S state , Date date ) throws JobDestroyedException ; public void setStateException ( Throwable t ) throws JobDestroyedException ; public void setStateException ( Throwable t , Date date ) throws JobDestroyedException ; } package org . oddjob . state ; public class IsExecutable implements StateCondition { @ Override public boolean test ( State state ) { return state . isReady ( ) ; } } package org . oddjob . state ; public class OrStateOp implements StateOperator { @ Override public ParentState evaluate ( State ... states ) { new AssertNonDestroyed ( ) . evaluate ( states ) ; ParentState state = ParentState . READY ; for ( int i = ; i < states . length ; ++ i ) { State next = states [ i ] ; if ( state . isStoppable ( ) || next . isStoppable ( ) ) { state = ParentState . ACTIVE ; } else if ( state . isException ( ) || next . isException ( ) ) { state = ParentState . EXCEPTION ; } else if ( state . isComplete ( ) || next . isComplete ( ) ) { state = ParentState . COMPLETE ; } else if ( state . isIncomplete ( ) || next . isIncomplete ( ) ) { state = ParentState . INCOMPLETE ; } } return state ; } } package org . oddjob . state ; import org . oddjob . Stateful ; public class ParentStateHandler extends StateHandler < ParentState > { public ParentStateHandler ( Stateful source ) { super ( source , ParentState . READY ) ; } } package org . oddjob . state ; import org . oddjob . Structural ; public class ServiceManagerStateOp implements StateOperator { @ Override public ParentState evaluate ( State ... states ) { new AssertNonDestroyed ( ) . evaluate ( states ) ; ParentState state = ParentState . READY ; if ( states . length > ) { state = new ParentStateConverter ( ) . toStructuralState ( states [ ] ) ; if ( state . isStoppable ( ) ) { state = ParentState . COMPLETE ; } for ( int i = ; i < states . length ; ++ i ) { State next = states [ i ] ; if ( state . isException ( ) || next . isException ( ) ) { state = ParentState . EXCEPTION ; } else if ( state . isIncomplete ( ) || next . isIncomplete ( ) ) { state = ParentState . INCOMPLETE ; } else if ( state . isReady ( ) || next . isReady ( ) ) { state = ParentState . READY ; } else { state = ParentState . COMPLETE ; } } } return state ; } } package org . oddjob . state ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . Callable ; import org . oddjob . Stateful ; import org . oddjob . Structural ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class StructuralStateHelper implements Stateful { private final Structural structural ; private final ParentStateHandler stateHandler = new ParentStateHandler ( this ) ; private final List < StateHolder > states = new ArrayList < StateHolder > ( ) ; private final List < StateListener > listeners = new ArrayList < StateListener > ( ) ; private final StateOperator operator ; class StateHolder { private State state = ParentState . COMPLETE ; } class ChildStateListener implements StateListener { private final StateHolder holder ; public ChildStateListener ( StateHolder holder ) { this . holder = holder ; } @ Override public synchronized void jobStateChange ( StateEvent event ) { holder . state = event . getState ( ) ; checkStates ( ) ; } ; @ Override public String toString ( ) { return getClass ( ) . getName ( ) + "" + structural + "" ; } } ; public StructuralStateHelper ( Structural structural , StateOperator operator ) { this . structural = structural ; this . operator = operator ; structural . addStructuralListener ( new StructuralListener ( ) { @ Override public void childAdded ( final StructuralEvent event ) { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { int index = event . getIndex ( ) ; Object child = event . getChild ( ) ; StateHolder stateHolder = new StateHolder ( ) ; ChildStateListener listener = new ChildStateListener ( stateHolder ) ; listeners . add ( index , listener ) ; states . add ( index , stateHolder ) ; if ( child instanceof Stateful ) { ( ( Stateful ) child ) . addStateListener ( listener ) ; } else { checkStates ( ) ; } } } ) ; } @ Override public void childRemoved ( final StructuralEvent event ) { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { int index = event . getIndex ( ) ; Object child = event . getChild ( ) ; StateListener listener = listeners . remove ( index ) ; if ( child instanceof Stateful ) { ( ( Stateful ) child ) . removeStateListener ( listener ) ; } states . remove ( index ) ; checkStates ( ) ; } } ) ; } } ) ; } public void addStateListener ( StateListener listener ) { stateHandler . addStateListener ( listener ) ; } public void removeStateListener ( StateListener listener ) { stateHandler . removeStateListener ( listener ) ; } private void checkStates ( ) { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { State [ ] stateArgs = new State [ states . size ( ) ] ; int i = ; for ( StateHolder holder : states ) { stateArgs [ i ++ ] = holder . state ; } ParentState state = operator . evaluate ( stateArgs ) ; if ( state == stateHandler . getState ( ) ) { return ; } stateHandler . setState ( state ) ; stateHandler . fireEvent ( ) ; } } ) ; } @ Override public StateEvent lastStateEvent ( ) { return stateHandler . lastStateEvent ( ) ; } public State [ ] getChildStates ( ) { return stateHandler . callLocked ( new Callable < State [ ] > ( ) { @ Override public State [ ] call ( ) throws Exception { State [ ] array = new State [ states . size ( ) ] ; int i = ; for ( StateHolder holder : states ) { array [ i ++ ] = holder . state ; } return array ; } } ) ; } } package org . oddjob . state ; import org . oddjob . Structural ; public enum ParentState implements State { READY ( ) { @ Override public boolean isReady ( ) { return true ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return true ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , EXECUTING ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return true ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , ACTIVE ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return true ; } @ Override public boolean isPassable ( ) { return true ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , INCOMPLETE ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return true ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , COMPLETE ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return true ; } @ Override public boolean isComplete ( ) { return true ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , EXCEPTION ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return true ; } @ Override public boolean isDestroyed ( ) { return false ; } } , DESTROYED ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return true ; } } , ; } package org . oddjob . state ; import org . oddjob . Stateful ; import org . oddjob . jobs . structural . SequentialJob ; public class SequentialHelper { public boolean canContinueAfter ( Object child ) { State state = JobState . COMPLETE ; if ( child instanceof Stateful ) { state = ( ( Stateful ) child ) . lastStateEvent ( ) . getState ( ) ; } return state . isPassable ( ) ; } } package org . oddjob . state ; public class IsHardResetable implements StateCondition { @ Override public boolean test ( State state ) { return state . isReady ( ) || state . isComplete ( ) || state . isIncomplete ( ) || state . isException ( ) ; } } package org . oddjob . state ; import org . oddjob . images . IconHelper ; import org . oddjob . persist . Persistable ; public class ServiceStateChanger extends BaseStateChanger < ServiceState > { public ServiceStateChanger ( ServiceStateHandler stateHandler , IconHelper iconHelper , Persistable persistable ) { super ( stateHandler , iconHelper , persistable , ServiceState . EXCEPTION ) ; } } package org . oddjob . state ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . framework . StructuralJob ; import org . oddjob . io . ExistsJob ; public class Resets extends StructuralJob < Object > { private static final long serialVersionUID = ; private boolean harden ; private boolean soften ; @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } @ Override protected void execute ( ) throws Throwable { Object job = childHelper . getChild ( ) ; if ( job != null && job instanceof Runnable ) { ( ( Runnable ) job ) . run ( ) ; } } public boolean isHarden ( ) { return harden ; } public void setHarden ( boolean harden ) { this . harden = harden ; } public boolean isSoften ( ) { return soften ; } public void setSoften ( boolean soften ) { this . soften = soften ; } @ ArooaComponent public synchronized void setJob ( Object job ) { if ( job == null ) { childHelper . removeChildAt ( ) ; } else { childHelper . insertChild ( , job ) ; } } @ Override public boolean hardReset ( ) { if ( soften ) { return super . softReset ( ) ; } else { return super . hardReset ( ) ; } } @ Override public boolean softReset ( ) { if ( harden ) { return super . hardReset ( ) ; } else { return super . softReset ( ) ; } } } package org . oddjob . state ; import org . oddjob . Stateful ; public class JobStateHandler extends StateHandler < JobState > { public JobStateHandler ( Stateful source ) { super ( source , JobState . READY ) ; } } package org . oddjob . state ; public class CompleteOrNotOp implements StateOperator { public ParentState evaluate ( State ... states ) { new AssertNonDestroyed ( ) . evaluate ( states ) ; for ( State state : states ) { if ( state . isStoppable ( ) ) { return ParentState . ACTIVE ; } if ( state . isReady ( ) ) { return ParentState . COMPLETE ; } if ( ! state . isComplete ( ) ) { return ParentState . INCOMPLETE ; } } return ParentState . COMPLETE ; } } package org . oddjob . state ; import java . util . Date ; public class OrderedStateChanger < S extends State > implements StateChanger < S > { private final StateChanger < S > stateChanger ; private final StateLock stateLock ; public OrderedStateChanger ( StateChanger < S > stateChanger , StateLock stateLock ) { this . stateChanger = stateChanger ; this . stateLock = stateLock ; } public void setStateException ( final Throwable t , final Date date ) { runLocked ( new Runnable ( ) { public void run ( ) { stateChanger . setStateException ( t , date ) ; } } ) ; } public void setStateException ( final Throwable t ) { runLocked ( new Runnable ( ) { public void run ( ) { stateChanger . setStateException ( t ) ; } } ) ; } public void setState ( final S state , final Date date ) { runLocked ( new Runnable ( ) { public void run ( ) { stateChanger . setState ( state , date ) ; } } ) ; } public void setState ( final S state ) { runLocked ( new Runnable ( ) { public void run ( ) { stateChanger . setState ( state ) ; } } ) ; } private void runLocked ( Runnable runnable ) { stateLock . waitToWhen ( new IsAnyState ( ) , runnable ) ; } } package org . oddjob . state ; public class IsNot implements StateCondition { private final StateCondition condition ; public IsNot ( StateCondition condition ) { this . condition = condition ; } @ Override public boolean test ( State state ) { return ! condition . test ( state ) ; } @ Override public String toString ( ) { return "" + condition ; } } package org . oddjob . state ; import org . oddjob . images . IconHelper ; import org . oddjob . persist . Persistable ; public class JobStateChanger extends BaseStateChanger < JobState > { public JobStateChanger ( JobStateHandler stateHandler , IconHelper iconHelper , Persistable persistable ) { super ( stateHandler , iconHelper , persistable , JobState . EXCEPTION ) ; } } package org . oddjob . state ; public interface StateListener { public void jobStateChange ( StateEvent event ) ; } package org . oddjob . state ; import java . util . concurrent . atomic . AtomicReference ; import org . oddjob . Stateful ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . framework . StructuralJob ; import org . oddjob . util . OddjobConfigException ; public class JoinJob extends StructuralJob < Runnable > { private static final long serialVersionUID = ; @ ArooaComponent public void setJob ( Runnable child ) { if ( child == null ) { logger ( ) . debug ( "" ) ; childHelper . removeAllChildren ( ) ; } else { logger ( ) . debug ( "" + child + "" ) ; if ( childHelper . getChild ( ) != null ) { throw new OddjobConfigException ( "" ) ; } childHelper . insertChild ( , child ) ; } } protected void execute ( ) throws InterruptedException { Runnable child = childHelper . getChild ( ) ; if ( child == null ) { return ; } child . run ( ) ; final AtomicReference < State > state = new AtomicReference < State > ( ) ; StateListener listener = new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { state . set ( event . getState ( ) ) ; synchronized ( JoinJob . this ) { JoinJob . this . notifyAll ( ) ; } } } ; ( ( Stateful ) child ) . addStateListener ( listener ) ; try { while ( ! stop && state . get ( ) . isStoppable ( ) ) { synchronized ( this ) { wait ( ) ; } } } finally { removeStateListener ( listener ) ; } stop = false ; } @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } } package org . oddjob . state ; public class IsContinueable implements StateCondition { @ Override public boolean test ( State state ) { return state . isPassable ( ) ; } } package org . oddjob . state ; public class AndState extends StateReflector { private static final long serialVersionUID = ; @ Override protected StateOperator getStateOp ( ) { return new AndStateOp ( ) ; } } package org . oddjob . state ; import org . oddjob . util . OddjobLockedException ; public interface StateLock { public boolean tryToWhen ( StateCondition when , Runnable runnable ) throws OddjobLockedException ; public boolean waitToWhen ( StateCondition when , Runnable runnable ) ; } package org . oddjob . state ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . framework . SerializableJob ; public class FlagState extends SerializableJob { private static final long serialVersionUID = ; private JobState state ; public FlagState ( ) { state = JobState . COMPLETE ; } public FlagState ( JobState state ) { this . state = state ; } protected int execute ( ) throws Exception { if ( state == null ) { throw new IllegalStateException ( "" ) ; } if ( state . equals ( JobState . COMPLETE ) ) { return ; } if ( state . equals ( JobState . INCOMPLETE ) ) { return ; } if ( state . equals ( JobState . EXCEPTION ) ) { throw new Exception ( "" ) ; } else { throw new IllegalStateException ( "" + state ) ; } } public JobState getState ( ) { return state ; } @ ArooaAttribute public void setState ( JobState desired ) { this . state = desired ; } } package org . oddjob . state ; public class IsSaveable implements StateCondition { @ Override public boolean test ( State state ) { return state . isReady ( ) || state . isComplete ( ) || state . isIncomplete ( ) || state . isException ( ) ; } } package org . oddjob . state ; public enum ServiceState implements State { READY ( ) { @ Override public boolean isReady ( ) { return true ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , STARTING ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return true ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , STARTED ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return true ; } @ Override public boolean isPassable ( ) { return true ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , COMPLETE ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return true ; } @ Override public boolean isComplete ( ) { return true ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , EXCEPTION ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return true ; } @ Override public boolean isDestroyed ( ) { return false ; } } , DESTROYED ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return true ; } } , ; public static ServiceState stateFor ( String state ) { state = state . toUpperCase ( ) ; return valueOf ( state ) ; } } package org . oddjob . state ; import org . oddjob . images . IconHelper ; import org . oddjob . persist . Persistable ; public class ParentStateChanger extends BaseStateChanger < ParentState > { public ParentStateChanger ( StateHandler < ParentState > stateHandler , IconHelper iconHelper , Persistable persistable ) { super ( stateHandler , iconHelper , persistable , ParentState . EXCEPTION ) ; } } package org . oddjob . state ; import org . oddjob . Structural ; public class WorstStateOp implements StateOperator { @ Override public ParentState evaluate ( State ... states ) { new AssertNonDestroyed ( ) . evaluate ( states ) ; ParentState state = ParentState . READY ; if ( states . length > ) { state = new ParentStateConverter ( ) . toStructuralState ( states [ ] ) ; for ( int i = ; i < states . length ; ++ i ) { State next = states [ i ] ; if ( state . isStoppable ( ) || next . isStoppable ( ) ) { state = ParentState . ACTIVE ; } else if ( state . isException ( ) || next . isException ( ) ) { state = ParentState . EXCEPTION ; } else if ( state . isIncomplete ( ) || next . isIncomplete ( ) ) { state = ParentState . INCOMPLETE ; } else if ( state . isReady ( ) || next . isReady ( ) ) { state = ParentState . READY ; } else { state = ParentState . COMPLETE ; } } } return state ; } } package org . oddjob . state ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . concurrent . Callable ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . locks . Condition ; import java . util . concurrent . locks . ReentrantLock ; import org . apache . log4j . Logger ; import org . oddjob . Stateful ; import org . oddjob . framework . JobDestroyedException ; import org . oddjob . util . OddjobLockedException ; public class StateHandler < S extends State > implements Stateful , StateLock { private static final Logger logger = Logger . getLogger ( StateHandler . class ) ; private final S readyState ; private final Stateful source ; private transient ArrayList < StateListener > listeners = new ArrayList < StateListener > ( ) ; private volatile StateEvent lastEvent ; private transient boolean fireing ; private final ReentrantLock lock = new ReentrantLock ( true ) { private static final long serialVersionUID = ; public String toString ( ) { Thread o = getOwner ( ) ; return "" + source + "" + ( ( o == null ) ? "" : "" + o . getName ( ) + "" ) ; } } ; private final Condition alarm = lock . newCondition ( ) ; public StateHandler ( Stateful source , S readyState ) { this . source = source ; lastEvent = new StateEvent ( source , readyState , null ) ; this . readyState = readyState ; } @ Override public StateEvent lastStateEvent ( ) { return callLocked ( new Callable < StateEvent > ( ) { @ Override public StateEvent call ( ) { return lastEvent ; } } ) ; } public void restoreLastJobStateEvent ( StateEvent savedEvent ) { if ( savedEvent . getState ( ) . isStoppable ( ) ) { lastEvent = new StateEvent ( source , readyState ) ; } else { lastEvent = new StateEvent ( source , savedEvent . getState ( ) , savedEvent . getTime ( ) , savedEvent . getException ( ) ) ; } } public void setState ( S state , Date date ) throws JobDestroyedException { setLastJobStateEvent ( new StateEvent ( source , state , date , null ) ) ; } public void setState ( S state ) throws JobDestroyedException { setLastJobStateEvent ( new StateEvent ( source , state , null ) ) ; } public void setStateException ( S state , Throwable t , Date date ) throws JobDestroyedException { setLastJobStateEvent ( new StateEvent ( source , state , date , t ) ) ; } public void setStateException ( State state , Throwable ex ) throws JobDestroyedException { setLastJobStateEvent ( new StateEvent ( source , state , ex ) ) ; } private void setLastJobStateEvent ( StateEvent event ) throws JobDestroyedException { assertAlive ( ) ; assertLockHeld ( ) ; if ( fireing ) { throw new IllegalStateException ( "" ) ; } lastEvent = event ; } public State getState ( ) { return callLocked ( new Callable < State > ( ) { @ Override public State call ( ) throws Exception { return lastEvent . getState ( ) ; } } ) ; } public void assertAlive ( ) throws JobDestroyedException { if ( lastEvent . getState ( ) . isDestroyed ( ) ) { throw new JobDestroyedException ( source ) ; } } public void assertLockHeld ( ) { if ( ! lock . isHeldByCurrentThread ( ) ) { throw new IllegalStateException ( "" + source + "" + Thread . currentThread ( ) . getName ( ) + "" ) ; } } public boolean tryToWhen ( StateCondition when , Runnable runnable ) throws OddjobLockedException { if ( ! lock . tryLock ( ) ) { throw new OddjobLockedException ( lock . toString ( ) ) ; } try { return doWhen ( when , runnable ) ; } finally { lock . unlock ( ) ; } } public boolean waitToWhen ( StateCondition when , Runnable runnable ) { lock . lock ( ) ; try { return doWhen ( when , runnable ) ; } finally { lock . unlock ( ) ; } } private boolean doWhen ( StateCondition when , Runnable runnable ) { if ( when . test ( lastEvent . getState ( ) ) ) { runnable . run ( ) ; return true ; } else { return false ; } } public < T > T callLocked ( Callable < T > callable ) { lock . lock ( ) ; try { return callable . call ( ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { lock . unlock ( ) ; } } public void sleep ( long time ) throws InterruptedException { assertLockHeld ( ) ; if ( time == ) { alarm . await ( ) ; } else { alarm . await ( time , TimeUnit . MILLISECONDS ) ; } } public void wake ( ) { assertLockHeld ( ) ; alarm . signalAll ( ) ; } public void addStateListener ( final StateListener listener ) throws JobDestroyedException { assertAlive ( ) ; waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { listeners . add ( listener ) ; fireing = true ; try { listener . jobStateChange ( lastEvent ) ; } finally { fireing = false ; } } } ) ; } public void removeStateListener ( final StateListener listener ) { waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { listeners . remove ( listener ) ; } } ) ; } public int listenerCount ( ) { return callLocked ( new Callable < Integer > ( ) { @ Override public Integer call ( ) throws Exception { return listeners . size ( ) ; } } ) . intValue ( ) ; } public String toString ( ) { return "" + lastEvent . getState ( ) + "" ; } public void fireEvent ( ) { assertLockHeld ( ) ; if ( fireing ) { throw new IllegalStateException ( "" ) ; } fireing = true ; try { doFireEvent ( lastEvent ) ; } finally { fireing = false ; } } private void doFireEvent ( StateEvent event ) { if ( event == null ) { throw new NullPointerException ( "" ) ; } List < StateListener > copy = new ArrayList < StateListener > ( listeners ) ; for ( StateListener listener : copy ) { try { listener . jobStateChange ( event ) ; } catch ( Throwable t ) { logger . error ( "" + listener + "" + event + "" , t ) ; } } } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; listeners = new ArrayList < StateListener > ( ) ; } } package org . oddjob . state ; public class OrState extends StateReflector { private static final long serialVersionUID = ; @ Override protected StateOperator getStateOp ( ) { return new OrStateOp ( ) ; } } package org . oddjob . state ; public class IsNotExecuting implements StateCondition { @ Override public boolean test ( State state ) { return ! state . isStoppable ( ) ; } } package org . oddjob . state ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . images . IconHelper ; import org . oddjob . images . StateIcons ; import org . oddjob . persist . Persistable ; public class BaseStateChanger < S extends State > implements StateChanger < S > { private static final Logger logger = Logger . getLogger ( BaseStateChanger . class ) ; private final StateHandler < S > stateHandler ; private final IconHelper iconHelper ; private final Persistable persistable ; private final S exceptionState ; public BaseStateChanger ( StateHandler < S > stateHandler , IconHelper iconHelper , Persistable persistable , S exceptionState ) { this . stateHandler = stateHandler ; this . iconHelper = iconHelper ; this . persistable = persistable ; this . exceptionState = exceptionState ; } public void setState ( S state ) { setState ( state , new Date ( ) ) ; } public void setState ( S state , Date date ) { if ( state == stateHandler . getState ( ) ) { return ; } stateHandler . setState ( state , date ) ; iconHelper . changeIcon ( StateIcons . iconFor ( state ) ) ; try { if ( new IsSaveable ( ) . test ( state ) ) { persistable . persist ( ) ; } stateHandler . fireEvent ( ) ; } catch ( ComponentPersistException e ) { logger . error ( "" + state , e ) ; setStateException ( e ) ; } } public void setStateException ( Throwable t ) { setStateException ( t , new Date ( ) ) ; } public void setStateException ( Throwable t , Date date ) { if ( exceptionState == stateHandler . getState ( ) ) { return ; } stateHandler . setStateException ( exceptionState , t , date ) ; iconHelper . changeIcon ( IconHelper . EXCEPTION ) ; if ( new IsSaveable ( ) . test ( exceptionState ) && ! ( t instanceof ComponentPersistException ) ) { try { persistable . persist ( ) ; } catch ( ComponentPersistException e ) { logger . error ( "" + exceptionState , e ) ; stateHandler . setStateException ( exceptionState , e , date ) ; } } stateHandler . fireEvent ( ) ; } } package org . oddjob . state ; public class ParentStateConverter { public ParentState toStructuralState ( State state ) { if ( state . isReady ( ) ) { return ParentState . READY ; } else if ( state . isStoppable ( ) ) { return ParentState . ACTIVE ; } else if ( state . isIncomplete ( ) ) { return ParentState . INCOMPLETE ; } else if ( state . isComplete ( ) ) { return ParentState . COMPLETE ; } else if ( state . isException ( ) ) { return ParentState . EXCEPTION ; } else if ( state . isDestroyed ( ) ) { return ParentState . DESTROYED ; } else { throw new IllegalStateException ( "" + state ) ; } } } package org . oddjob . state ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . framework . BasePrimary ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . framework . JobDestroyedException ; import org . oddjob . persist . Persistable ; public class MirrorState extends BasePrimary implements Runnable , Stoppable , Resetable { private final JobStateHandler stateHandler ; private final JobStateChanger stateChanger ; private Stateful job ; private StateListener listener ; public MirrorState ( ) { stateHandler = new JobStateHandler ( this ) ; stateChanger = new JobStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override protected JobStateHandler stateHandler ( ) { return stateHandler ; } protected StateChanger < JobState > getStateChanger ( ) { return stateChanger ; } @ ArooaAttribute public synchronized void setJob ( Stateful job ) { this . job = job ; } synchronized public void run ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { if ( listener != null ) { return ; } logger ( ) . info ( "" ) ; try { configure ( ) ; } catch ( ArooaConfigurationException e ) { getStateChanger ( ) . setStateException ( e ) ; logger ( ) . error ( "" , e ) ; return ; } if ( job == null ) { getStateChanger ( ) . setStateException ( new NullPointerException ( "" ) ) ; return ; } logger ( ) . info ( "" + job + "" ) ; listener = new MirrorListener ( ) ; job . addStateListener ( listener ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } class MirrorListener implements StateListener { @ Override public synchronized void jobStateChange ( final StateEvent event ) { logger ( ) . info ( "" + event . getState ( ) + "" + event . getTime ( ) + "" ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { State state = event . getState ( ) ; if ( state . isDestroyed ( ) ) { logger ( ) . info ( "" ) ; getStateChanger ( ) . setStateException ( new JobDestroyedException ( job ) ) ; stop ( ) ; } else { if ( state . isException ( ) ) { getStateChanger ( ) . setStateException ( event . getException ( ) , event . getTime ( ) ) ; } else { getStateChanger ( ) . setState ( new JobStateConverter ( ) . toJobState ( state ) , event . getTime ( ) ) ; } } } } ) ; } } public synchronized void stop ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( listener != null ) { job . removeStateListener ( listener ) ; listener = null ; logger ( ) . info ( "" + job + "" ) ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( JobState . READY ) ; } } ) ; job = null ; } } finally { ComponentBoundry . pop ( ) ; } } private synchronized boolean reset ( ) { stop ( ) ; return stateHandler . waitToWhen ( new StateCondition ( ) { @ Override public boolean test ( State state ) { return JobState . READY != state ; } } , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( JobState . READY ) ; } } ) ; } public boolean hardReset ( ) { return reset ( ) ; } public boolean softReset ( ) { return reset ( ) ; } @ Override public void onDestroy ( ) { stop ( ) ; super . onDestroy ( ) ; } protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( JobState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + MirrorState . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . state ; import java . util . Iterator ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Future ; import java . util . concurrent . atomic . AtomicBoolean ; import javax . inject . Inject ; import org . oddjob . Stateful ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . framework . ExecutionWatcher ; import org . oddjob . framework . StructuralJob ; import org . oddjob . jobs . structural . SequentialJob ; public class CascadeJob extends StructuralJob < Object > { private static final long serialVersionUID = ; private volatile transient ExecutorService executors ; private transient Future < ? > future ; @ Inject @ ArooaHidden public void setExecutorService ( ExecutorService executor ) { this . executors = executor ; } @ ArooaComponent public synchronized void setJobs ( int index , Object child ) { if ( child == null ) { childHelper . removeChildAt ( index ) ; } else { if ( child instanceof Runnable ^ child instanceof Stateful ) { throw new IllegalArgumentException ( "" ) ; } childHelper . insertChild ( index , child ) ; } } protected void execute ( ) throws InterruptedException { if ( executors == null ) { throw new NullPointerException ( "" ) ; } final Iterator < Object > children = childHelper . iterator ( ) ; final ExecutionWatcher executionWatcher = new ExecutionWatcher ( new Runnable ( ) { public void run ( ) { CascadeJob . super . startChildStateReflector ( ) ; } } ) ; final AtomicBoolean first = new AtomicBoolean ( true ) ; new Runnable ( ) { @ Override public void run ( ) { Runnable next = null ; while ( children . hasNext ( ) ) { Object child = children . next ( ) ; if ( child instanceof Runnable ) { next = ( Runnable ) child ; break ; } } if ( next == null || stop ) { stop = false ; executionWatcher . start ( ) ; return ; } final Runnable _this = this ; ( ( Stateful ) next ) . addStateListener ( new StateListener ( ) { public void jobStateChange ( StateEvent event ) { if ( ! new IsDone ( ) . test ( event . getState ( ) ) ) { return ; } event . getSource ( ) . removeStateListener ( this ) ; if ( event . getState ( ) . isPassable ( ) ) { _this . run ( ) ; } else { executionWatcher . start ( ) ; } } } ) ; Runnable wrapper = executionWatcher . addJob ( next ) ; if ( first . get ( ) ) { first . set ( false ) ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ParentState . ACTIVE ) ; } } ) ; } future = executors . submit ( wrapper ) ; } } . run ( ) ; } @ Override protected void onStop ( ) { Future < ? > future = null ; synchronized ( this ) { future = this . future ; this . future = null ; } if ( future != null ) { future . cancel ( false ) ; } super . startChildStateReflector ( ) ; } @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } @ Override protected void startChildStateReflector ( ) { } } package org . oddjob . state ; public enum JobState implements State { READY ( ) { @ Override public boolean isReady ( ) { return true ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return true ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , EXECUTING ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return true ; } @ Override public boolean isPassable ( ) { return true ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , INCOMPLETE ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return true ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , COMPLETE ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return true ; } @ Override public boolean isComplete ( ) { return true ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return false ; } } , EXCEPTION ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return true ; } @ Override public boolean isDestroyed ( ) { return false ; } } , DESTROYED ( ) { @ Override public boolean isReady ( ) { return false ; } @ Override public boolean isStoppable ( ) { return false ; } @ Override public boolean isPassable ( ) { return false ; } @ Override public boolean isComplete ( ) { return false ; } @ Override public boolean isIncomplete ( ) { return false ; } @ Override public boolean isException ( ) { return false ; } @ Override public boolean isDestroyed ( ) { return true ; } } , ; public static JobState stateFor ( String state ) { state = state . toUpperCase ( ) ; return valueOf ( state ) ; } } package org . oddjob . sql ; import java . sql . Connection ; import java . sql . SQLException ; import org . apache . log4j . Logger ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . registry . Path ; import org . oddjob . persist . OddjobPersister ; import org . oddjob . persist . PersisterBase ; public class SQLPersisterService { private static final Logger logger = Logger . getLogger ( SQLPersisterService . class ) ; private Connection connection ; private String name ; private SQLSerializationFactory serializationFactory ; private volatile SQLSerialization serialization ; public void start ( ) throws SQLException { if ( serializationFactory == null ) { serializationFactory = new HSQLSerializationFactory ( ) ; } serialization = serializationFactory . createSerialization ( connection ) ; } public void stop ( ) throws SQLException { if ( serialization != null ) { serialization . close ( ) ; serialization = null ; } } public void setConnection ( Connection connection ) throws SQLException { this . connection = connection ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public SQLSerializationFactory getSerializationFactory ( ) { return serializationFactory ; } public void setSerializationFactory ( SQLSerializationFactory serializationFactory ) { this . serializationFactory = serializationFactory ; } public OddjobPersister getPersister ( String path ) { return new SQLPersister ( path ) ; } @ Override public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } else { return name ; } } class SQLPersister extends PersisterBase { public SQLPersister ( String path ) { super ( path == null ? null : new Path ( path ) ) ; } @ Override protected void persist ( Path path , String id , Object o ) throws ComponentPersistException { if ( serialization == null ) { throw new IllegalStateException ( "" ) ; } try { serialization . persist ( path , id , o ) ; logger . debug ( "" + o + "" + id + "" ) ; } catch ( SQLException e ) { throw new ComponentPersistException ( "" + id + "" + o . getClass ( ) . getName ( ) + "" + o + "" , e ) ; } } @ Override protected Object restore ( Path path , String id , ClassLoader classLoader ) throws ComponentPersistException { if ( serialization == null ) { throw new IllegalStateException ( "" ) ; } try { return serialization . restore ( path , id , classLoader ) ; } catch ( SQLException e ) { throw new ComponentPersistException ( "" , e ) ; } } @ Override protected String [ ] list ( Path path ) throws ComponentPersistException { if ( serialization == null ) { throw new IllegalStateException ( "" ) ; } try { return serialization . children ( path ) ; } catch ( SQLException e ) { throw new ComponentPersistException ( "" , e ) ; } } @ Override protected void remove ( Path path , String id ) throws ComponentPersistException { if ( serialization == null ) { throw new IllegalStateException ( "" ) ; } try { serialization . remove ( path , id ) ; } catch ( SQLException e ) { throw new ComponentPersistException ( "" , e ) ; } } @ Override protected void clear ( Path path ) throws ComponentPersistException { if ( serialization == null ) { throw new IllegalStateException ( "" ) ; } try { serialization . clear ( path ) ; } catch ( SQLException e ) { throw new ComponentPersistException ( "" , e ) ; } } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) ; } } } package org . oddjob . sql ; import java . sql . Connection ; import java . sql . SQLException ; public interface SQLSerializationFactory { public SQLSerialization createSerialization ( Connection connection ) throws SQLException ; } package org . oddjob . sql ; import java . io . Serializable ; import java . sql . Connection ; import java . sql . Driver ; import java . sql . SQLException ; import java . util . Properties ; import javax . inject . Inject ; import org . apache . log4j . Logger ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . types . ValueFactory ; public class ConnectionType implements ValueFactory < Connection > , Serializable { private final static long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( ConnectionType . class ) ; private String driver ; private String url ; private String username ; private String password ; private ClassLoader classLoader ; public Connection toValue ( ) throws ArooaConversionException { if ( driver == null ) { throw new NullPointerException ( "" ) ; } if ( url == null ) { throw new NullPointerException ( "" ) ; } ClassLoader loader = classLoader ; if ( loader == null ) { loader = getClass ( ) . getClassLoader ( ) ; } Class < ? > driverClass ; try { driverClass = Class . forName ( driver , true , loader ) ; } catch ( ClassNotFoundException e ) { throw new ArooaConversionException ( e ) ; } Driver theDriver ; try { theDriver = ( Driver ) driverClass . newInstance ( ) ; } catch ( Exception e ) { throw new ArooaConversionException ( e ) ; } Properties info = new Properties ( ) ; if ( username != null ) { info . put ( "" , username ) ; } if ( password != null ) { info . put ( "" , password ) ; } try { Connection connection = theDriver . connect ( url , info ) ; if ( connection == null ) { throw new ArooaConversionException ( "" + url + "" ) ; } return connection ; } catch ( SQLException e ) { logger . warn ( "" + url , e ) ; for ( SQLException ce = e . getNextException ( ) ; ce != null ; ce = ce . getNextException ( ) ) { logger . warn ( "" , ce ) ; } throw new ArooaConversionException ( e ) ; } } public String getDriver ( ) { return driver ; } public void setDriver ( String driver ) { this . driver = driver ; } public String getPassword ( ) { return password ; } public void setPassword ( String password ) { this . password = password ; } public String getUrl ( ) { return url ; } public void setUrl ( String url ) { this . url = url ; } public String getUsername ( ) { return username ; } public void setUsername ( String username ) { this . username = username ; } public ClassLoader getClassLoader ( ) { return classLoader ; } @ Inject public void setClassLoader ( ClassLoader classLoader ) { this . classLoader = classLoader ; } public String toString ( ) { return "" + url + "" + username ; } } package org . oddjob . sql ; import org . apache . log4j . Logger ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . BadBeanHandler ; import org . oddjob . beanbus . BeanBus ; import org . oddjob . beanbus . BusAware ; import org . oddjob . beanbus . CrashBusException ; import org . oddjob . sql . SQLJob . OnError ; public class BadSQLHandler implements BadBeanHandler < String > , BusAware { private static final Logger logger = Logger . getLogger ( BadSQLHandler . class ) ; private SQLJob . OnError onError = null ; private BeanBus bus ; @ Override public void setBus ( BeanBus bus ) { this . bus = bus ; } @ Override public void handle ( String sql , BadBeanException e ) throws CrashBusException { logger . info ( "" + sql + "" + e . getCause ( ) . getMessage ( ) ) ; OnError onError = this . onError ; if ( onError == null ) { onError = OnError . ABORT ; } switch ( onError ) { case CONTINUE : break ; case STOP : bus . stop ( ) ; break ; case ABORT : logger . error ( "" ) ; throw new CrashBusException ( e ) ; } } public SQLJob . OnError getOnError ( ) { return onError ; } public void setOnError ( SQLJob . OnError onError ) { this . onError = onError ; } } package org . oddjob . sql ; public class UpdateCount { private final int count ; public UpdateCount ( int count ) { this . count = count ; } public int getCount ( ) { return count ; } } package org . oddjob . sql ; import java . sql . ResultSet ; import java . sql . ResultSetMetaData ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . atomic . AtomicInteger ; import org . oddjob . arooa . beanutils . MagicBeanDefinition ; import org . oddjob . arooa . beanutils . MagicBeanProperty ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . reflect . PropertyAccessor ; public class ResultSetBeanFactory { private static AtomicInteger instance = new AtomicInteger ( ) ; private final ResultSet resultSet ; private final ArooaClass arooaClass ; private final PropertyAccessor accessor ; public ResultSetBeanFactory ( ResultSet resultSet , PropertyAccessor accessor , ClassLoader loader ) throws SQLException , ClassNotFoundException { this . accessor = accessor ; MagicBeanDefinition magicDef = new MagicBeanDefinition ( ) ; magicDef . setName ( "" + instance . getAndIncrement ( ) ) ; ResultSetMetaData metaData = resultSet . getMetaData ( ) ; for ( int i = ; i <= metaData . getColumnCount ( ) ; ++ i ) { MagicBeanProperty prop = new MagicBeanProperty ( ) ; prop . setName ( metaData . getColumnName ( i ) ) ; prop . setType ( metaData . getColumnClassName ( i ) ) ; magicDef . setProperties ( i - , prop ) ; } this . resultSet = resultSet ; this . arooaClass = magicDef . createMagic ( loader ) ; } public Object next ( ) throws SQLException { if ( ! resultSet . next ( ) ) { return null ; } Object bean = arooaClass . newInstance ( ) ; BeanOverview overview = arooaClass . getBeanOverview ( accessor ) ; String [ ] properties = overview . getProperties ( ) ; for ( int i = ; i < properties . length ; ++ i ) { accessor . setProperty ( bean , properties [ i ] , resultSet . getObject ( i + ) ) ; } return bean ; } public List < Object > all ( ) throws SQLException { List < Object > all = new ArrayList < Object > ( ) ; for ( Object next = next ( ) ; next != null ; next = next ( ) ) { all . add ( next ) ; } return all ; } } package org . oddjob . sql ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . BeanBus ; import org . oddjob . beanbus . BusAware ; import org . oddjob . beanbus . BusEvent ; import org . oddjob . beanbus . BusException ; import org . oddjob . beanbus . BusListener ; import org . oddjob . beanbus . CrashBusException ; public class SQLResultsBean implements SQLResultsProcessor , BusAware { private final List < List < ? > > rowSets = new ArrayList < List < ? > > ( ) ; private final List < Integer > updateCounts = new ArrayList < Integer > ( ) ; private int rowCount ; private int updateCount ; @ ArooaHidden @ Override public void setBus ( BeanBus bus ) { bus . addBusListener ( new BusListener ( ) { @ Override public void busStarting ( BusEvent event ) throws CrashBusException { rowSets . clear ( ) ; updateCounts . clear ( ) ; rowCount = ; updateCount = ; } @ Override public void busStopping ( BusEvent event ) throws CrashBusException { } @ Override public void busCrashed ( BusEvent event , BusException e ) { } @ Override public void busTerminated ( BusEvent event ) { event . getSource ( ) . removeBusListener ( this ) ; } } ) ; } @ Override public void accept ( Object bean ) throws BadBeanException , CrashBusException { if ( bean instanceof List < ? > ) { List < ? > beans = ( List < ? > ) bean ; rowSets . add ( beans ) ; rowCount += beans . size ( ) ; } else if ( bean instanceof UpdateCount ) { UpdateCount updateCount = ( UpdateCount ) bean ; updateCounts . add ( new Integer ( updateCount . getCount ( ) ) ) ; this . updateCount += updateCount . getCount ( ) ; } else { throw new BadBeanException ( bean , "" + bean . getClass ( ) ) ; } } public int getRowCount ( ) { return rowCount ; } public int getRowSetCount ( ) { return rowSets . size ( ) ; } public Object [ ] [ ] getRowSets ( ) { Object [ ] [ ] allSets = new Object [ rowSets . size ( ) ] [ ] ; int i = ; for ( List < ? > rows : rowSets ) { if ( rows == null ) { allSets [ i ++ ] = null ; } else { allSets [ i ++ ] = rows . toArray ( new Object [ rows . size ( ) ] ) ; } } return allSets ; } public Object [ ] getRows ( ) { if ( rowSets . size ( ) > ) { throw new UnsupportedOperationException ( "" + rowSets . size ( ) + "" ) ; } if ( rowSets . size ( ) == ) { return null ; } List < ? > rows = rowSets . get ( ) ; if ( rows == null ) { return null ; } return rows . toArray ( new Object [ rows . size ( ) ] ) ; } public Object getRow ( ) { Object [ ] rows = getRows ( ) ; if ( rows == null ) { return null ; } if ( rows . length > ) { throw new UnsupportedOperationException ( "" + rows . length + "" ) ; } if ( rows . length == ) { return null ; } return rows [ ] ; } public Integer [ ] getUpdateCounts ( ) { return updateCounts . toArray ( new Integer [ updateCounts . size ( ) ] ) ; } public int getUpdateCount ( ) { return updateCount ; } } package org . oddjob . sql ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . Date ; import org . oddjob . util . Clock ; public class SQLClock { public static final String DEFAULT_SQL = "" ; private String name ; private Connection connection ; private String sql ; private PreparedStatement statement ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public void start ( ) throws SQLException { if ( sql == null ) { sql = DEFAULT_SQL ; } if ( connection == null ) { throw new NullPointerException ( "" ) ; } statement = connection . prepareStatement ( sql ) ; } public void stop ( ) throws SQLException { try { if ( statement != null ) { statement . close ( ) ; } } finally { if ( connection != null ) { connection . close ( ) ; } } } public Clock getClock ( ) { return new Clock ( ) { public Date getDate ( ) { try { ResultSet rs = statement . executeQuery ( ) ; rs . next ( ) ; Date date = rs . getDate ( ) ; rs . close ( ) ; return date ; } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } } @ Override public String toString ( ) { return "" ; } } ; } public void setSql ( String sql ) { this . sql = sql ; } public void setConnection ( Connection connection ) { this . connection = connection ; } public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } return name ; } } package org . oddjob . sql ; import java . io . FilterOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . BeanBus ; import org . oddjob . beanbus . BeanSheet ; import org . oddjob . beanbus . BusAware ; import org . oddjob . beanbus . BusEvent ; import org . oddjob . beanbus . BusException ; import org . oddjob . beanbus . BusListener ; import org . oddjob . beanbus . CrashBusException ; import org . oddjob . beanbus . StageEvent ; import org . oddjob . beanbus . StageListener ; import org . oddjob . io . StdoutType ; import org . oddjob . util . StreamPrinter ; public class SQLResultsSheet implements SQLResultsProcessor , ArooaSessionAware , BusAware { private static final Logger logger = Logger . getLogger ( SQLResultsSheet . class ) ; private OutputStream output ; private boolean dataOnly ; private ArooaSession session ; private long elapsedTime = System . currentTimeMillis ( ) ; @ Override @ ArooaHidden public void setArooaSession ( ArooaSession session ) { this . session = session ; } @ Override public void accept ( Object bean ) throws BadBeanException { elapsedTime = System . currentTimeMillis ( ) - elapsedTime ; if ( output == null ) { return ; } if ( bean instanceof List < ? > ) { List < ? > iterable = ( List < ? > ) bean ; BeanSheet sheet = new BeanSheet ( ) ; sheet . setOutput ( new FilterOutputStream ( output ) { public void close ( ) throws IOException { } ; { } } ) ; sheet . setArooaSession ( session ) ; sheet . setNoHeaders ( dataOnly ) ; sheet . accept ( iterable ) ; if ( ! dataOnly ) { new StreamPrinter ( output ) . println ( ) ; new StreamPrinter ( output ) . println ( "" + iterable . size ( ) + "" + elapsedTime + "" ) ; } } else if ( bean instanceof UpdateCount ) { if ( ! dataOnly ) { UpdateCount updateCount = ( UpdateCount ) bean ; new StreamPrinter ( output ) . println ( "" + updateCount . getCount ( ) + "" + elapsedTime + "" ) ; } } else { throw new BadBeanException ( bean , "" ) ; } } public OutputStream getOutput ( ) { return output ; } public void setOutput ( OutputStream output ) { this . output = output ; } public boolean isDataOnly ( ) { return dataOnly ; } public void setDataOnly ( boolean dataOnly ) { this . dataOnly = dataOnly ; } @ Override @ ArooaHidden public void setBus ( BeanBus bus ) { final StageListener stageListener = new StageListener ( ) { @ Override public void stageStarting ( StageEvent event ) { elapsedTime = System . currentTimeMillis ( ) ; } @ Override public void stageComplete ( StageEvent event ) { if ( ! dataOnly ) { new StreamPrinter ( output ) . println ( ) ; } } } ; bus . addBusListener ( new BusListener ( ) { @ Override public void busStarting ( BusEvent event ) throws CrashBusException { if ( output == null ) { try { output = new StdoutType ( ) . toValue ( ) ; } catch ( ArooaConversionException e ) { throw new CrashBusException ( e ) ; } } } @ Override public void busStopping ( BusEvent event ) throws CrashBusException { } @ Override public void busCrashed ( BusEvent event , BusException e ) { } @ Override public void busTerminated ( BusEvent event ) { event . getSource ( ) . removeBusListener ( this ) ; event . getSource ( ) . removeStageListener ( stageListener ) ; try { if ( output != null ) { output . close ( ) ; } } catch ( IOException ioe ) { logger . error ( "" , ioe ) ; } } } ) ; bus . addStageListener ( stageListener ) ; } } package org . oddjob . sql ; import java . sql . Statement ; import java . sql . CallableStatement ; import java . sql . Connection ; import java . sql . ParameterMetaData ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . SQLWarning ; import java . util . ArrayList ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . BeanBus ; import org . oddjob . beanbus . BusAware ; import org . oddjob . beanbus . BusEvent ; import org . oddjob . beanbus . BusException ; import org . oddjob . beanbus . BusListener ; import org . oddjob . beanbus . CrashBusException ; public class ParameterisedExecutor implements ArooaSessionAware , SQLExecutor , BusAware { private static final Logger logger = Logger . getLogger ( SQLJob . class ) ; private Connection connection ; private transient List < ValueType > parameters ; private boolean callable ; private int successfulSQLCount = ; private int executedSQLCount = ; private SQLResultsProcessor resultProcessor ; private PreparedStatement statement ; private boolean escapeProcessing = true ; private boolean autocommit = false ; private transient ArooaSession session ; @ Override public void setArooaSession ( ArooaSession session ) { this . session = session ; } @ Override public void accept ( String sql ) throws BadBeanException { try { execute ( sql ) ; } catch ( BadBeanException e ) { throw e ; } catch ( Exception e ) { throw new BadBeanException ( sql , e ) ; } } public void execute ( String sql ) throws SQLException , NoConversionAvailableException , ConversionFailedException , BusException , ClassNotFoundException { logger . info ( "" + sql ) ; ++ executedSQLCount ; if ( callable ) { statement = connection . prepareCall ( sql ) ; } else { statement = connection . prepareStatement ( sql ) ; } statement . setEscapeProcessing ( escapeProcessing ) ; ParameterMetaData paramMetaData = statement . getParameterMetaData ( ) ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; ArooaDescriptor descriptor = session . getArooaDescriptor ( ) ; int paramCount = paramMetaData . getParameterCount ( ) ; if ( ( parameters == null ? : parameters . size ( ) ) < paramCount ) { throw new IllegalStateException ( "" + paramCount ) ; } for ( int i = ; i <= paramCount ; ++ i ) { int mode = paramMetaData . getParameterMode ( i ) ; if ( mode == ParameterMetaData . parameterModeIn || mode == ParameterMetaData . parameterModeInOut ) { ArooaValue value = parameters . get ( i - ) . getValue ( ) ; String className = paramMetaData . getParameterClassName ( i ) ; Class < ? > required = descriptor . getClassResolver ( ) . findClass ( className ) ; Object converted = converter . convert ( value , required ) ; logger . info ( "" + i + "" + converted + "" ) ; if ( converted == null ) { statement . setNull ( i , paramMetaData . getParameterType ( i ) ) ; } else { statement . setObject ( i , converted ) ; } } else { logger . info ( "" + i + "" ) ; ( ( CallableStatement ) statement ) . registerOutParameter ( i , paramMetaData . getParameterType ( i ) ) ; } } try { statement . execute ( ) ; SQLWarning warnings = statement . getWarnings ( ) ; while ( warnings != null ) { logger . warn ( warnings . getMessage ( ) ) ; warnings = warnings . getNextWarning ( ) ; } if ( statement instanceof CallableStatement ) { CallableStatement callable = ( CallableStatement ) statement ; for ( int i = ; i <= paramCount ; ++ i ) { int mode = paramMetaData . getParameterMode ( i ) ; if ( mode == ParameterMetaData . parameterModeOut || mode == ParameterMetaData . parameterModeInOut ) { Object out = callable . getObject ( i ) ; logger . info ( "" + i + "" + out + "" ) ; ArooaValue value = converter . convert ( out , ArooaValue . class ) ; parameters . get ( i - ) . setValue ( value ) ; } } } ResultSet results = statement . getResultSet ( ) ; if ( results != null ) { PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) . accessorWithConversions ( session . getTools ( ) . getArooaConverter ( ) ) ; ResultSetBeanFactory beanFactory = new ResultSetBeanFactory ( results , accessor , getClass ( ) . getClassLoader ( ) ) ; List < ? > rows = beanFactory . all ( ) ; logger . info ( "" + rows . size ( ) + "" ) ; resultProcessor . accept ( rows ) ; } else { int updateCount = statement . getUpdateCount ( ) ; logger . info ( "" + updateCount + "" ) ; resultProcessor . accept ( new UpdateCount ( updateCount ) ) ; } ++ successfulSQLCount ; } finally { statement . close ( ) ; statement = null ; } } public void stop ( ) { Statement stmt = this . statement ; if ( stmt != null ) { try { stmt . cancel ( ) ; } catch ( SQLException e ) { logger . debug ( "" , e ) ; } } } @ Override public void setBus ( BeanBus bus ) { bus . addBusListener ( new BusListener ( ) { @ Override public void busStarting ( BusEvent event ) throws CrashBusException { if ( connection == null ) { throw new CrashBusException ( "" ) ; } try { connection . setAutoCommit ( autocommit ) ; logger . info ( "" + autocommit ) ; } catch ( SQLException e ) { throw new CrashBusException ( e ) ; } successfulSQLCount = ; executedSQLCount = ; } @ Override public void busStopping ( BusEvent event ) throws CrashBusException { if ( ! isAutocommit ( ) ) { try { connection . commit ( ) ; logger . info ( "" ) ; } catch ( SQLException e ) { throw new CrashBusException ( "" , e ) ; } } } @ Override public void busCrashed ( BusEvent event , BusException e ) { if ( connection != null && ! isAutocommit ( ) ) { try { connection . rollback ( ) ; logger . info ( "" ) ; } catch ( SQLException e1 ) { logger . error ( "" , e1 ) ; } } } @ Override public void busTerminated ( BusEvent event ) { event . getSource ( ) . removeBusListener ( this ) ; if ( connection != null ) { try { connection . close ( ) ; } catch ( SQLException e ) { logger . error ( "" , e ) ; } } logger . info ( successfulSQLCount + "" + executedSQLCount + "" ) ; } } ) ; if ( resultProcessor instanceof BusAware ) { ( ( BusAware ) resultProcessor ) . setBus ( bus ) ; } } public void setResultProcessor ( SQLResultsProcessor processor ) { this . resultProcessor = processor ; } public void setConnection ( Connection connection ) { this . connection = connection ; } public void setAutocommit ( boolean autocommit ) { this . autocommit = autocommit ; } public boolean isAutocommit ( ) { return autocommit ; } public boolean isEscapeProcessing ( ) { return escapeProcessing ; } public void setEscapeProcessing ( boolean escapeProcessing ) { this . escapeProcessing = escapeProcessing ; } public ValueType getParameters ( int index ) throws IndexOutOfBoundsException { if ( parameters == null ) { return null ; } else { return parameters . get ( index ) ; } } public void setParameters ( int index , ValueType parameter ) throws IndexOutOfBoundsException { if ( parameters == null ) { parameters = new ArrayList < ValueType > ( ) ; } if ( parameter == null ) { this . parameters . remove ( index ) ; } else { this . parameters . add ( index , parameter ) ; } } public boolean isCallable ( ) { return callable ; } public void setCallable ( boolean callable ) { this . callable = callable ; } public int getExecutedSQLCount ( ) { return executedSQLCount ; } public int getSuccessfulSQLCount ( ) { return successfulSQLCount ; } } package org . oddjob . sql ; public class SQLBuilder { public static final String LF_REGEX = "" ; private final StringBuilder builder = new StringBuilder ( ) ; public void append ( String sql ) { String noLFs = sql . replaceAll ( LF_REGEX , "" ) ; if ( builder . length ( ) > ) { builder . append ( '' ) ; } builder . append ( noLFs . trim ( ) ) ; } @ Override public String toString ( ) { return builder . toString ( ) ; } } package org . oddjob . sql ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public class SQLConversions implements ConversionProvider { @ Override public void registerWith ( ConversionRegistry registry ) { registry . register ( java . util . Date . class , java . sql . Date . class , new Convertlet < java . util . Date , java . sql . Date > ( ) { @ Override public java . sql . Date convert ( java . util . Date from ) throws ConvertletException { return new java . sql . Date ( from . getTime ( ) ) ; } } ) ; registry . register ( java . util . Date . class , java . sql . Time . class , new Convertlet < java . util . Date , java . sql . Time > ( ) { @ Override public java . sql . Time convert ( java . util . Date from ) throws ConvertletException { return new java . sql . Time ( from . getTime ( ) ) ; } } ) ; registry . register ( java . util . Date . class , java . sql . Timestamp . class , new Convertlet < java . util . Date , java . sql . Timestamp > ( ) { @ Override public java . sql . Timestamp convert ( java . util . Date from ) throws ConvertletException { return new java . sql . Timestamp ( from . getTime ( ) ) ; } } ) ; } } package org . oddjob . sql ; import org . oddjob . beanbus . Destination ; public interface SQLResultsProcessor extends Destination < Object > { } package org . oddjob . sql ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . concurrent . Future ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . TimeUnit ; import javax . inject . Inject ; import org . apache . log4j . Logger ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . schedules . IntervalSchedule ; import org . oddjob . scheduling . Keeper ; import org . oddjob . scheduling . LoosingOutcome ; import org . oddjob . scheduling . Outcome ; import org . oddjob . scheduling . WinningOutcome ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateListener ; public class SQLKeeperService { private static final Logger logger = Logger . getLogger ( SQLKeeperService . class ) ; public static final String TABLE_NAME = "" ; private String name ; private Connection connection ; private String table ; private ScheduledExecutorService scheduler ; private Schedule pollSchedule ; private volatile boolean running ; private final List < ALoosingOutcome > loosers = new ArrayList < ALoosingOutcome > ( ) ; { pollSchedule = new IntervalSchedule ( ) ; } public void start ( ) throws SQLException { if ( connection == null ) { throw new NullPointerException ( "" ) ; } if ( table == null ) { table = TABLE_NAME ; } running = true ; } public void stop ( ) throws SQLException { running = false ; while ( true ) { ALoosingOutcome looser = null ; synchronized ( loosers ) { if ( loosers . size ( ) > ) { looser = loosers . remove ( ) ; } } if ( looser == null ) { break ; } looser . stop ( ) ; } if ( connection != null ) { connection . close ( ) ; } } public Keeper getKeeper ( final String keeperKey ) { if ( keeperKey == null ) { throw new NullPointerException ( "" ) ; } return new Keeper ( ) { @ Override public Outcome grab ( String ourIdentifier , Object instanceIdentifier ) { if ( ! running ) { throw new IllegalStateException ( "" ) ; } if ( ourIdentifier == null ) { throw new NullPointerException ( "" ) ; } if ( instanceIdentifier == null ) { throw new NullPointerException ( "" ) ; } try { PreparedStatement insertStmt = createInsertStatementFor ( connection , keeperKey , ourIdentifier , instanceIdentifier ) ; try { insertStmt . execute ( ) ; logger . info ( ourIdentifier + "" + instanceIdentifier ) ; return new AWinningOutcome ( ourIdentifier , keeperKey , instanceIdentifier ) ; } catch ( SQLException e ) { logger . info ( ourIdentifier + "" + instanceIdentifier ) ; logger . debug ( "" + e . toString ( ) ) ; } finally { insertStmt . close ( ) ; } Query query = new Query ( keeperKey , instanceIdentifier ) ; query . query ( ) ; if ( ourIdentifier . equals ( query . getWinner ( ) ) && ! query . isComplete ( ) ) { return new AWinningOutcome ( ourIdentifier , keeperKey , instanceIdentifier ) ; } ALoosingOutcome looser = new ALoosingOutcome ( query . getWinner ( ) , keeperKey , instanceIdentifier ) ; return looser ; } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } } @ Override public String toString ( ) { return "" + keeperKey ; } } ; } class AWinningOutcome implements WinningOutcome { private final String winner ; private final String keeperKey ; private final Object instanceIdentifier ; public AWinningOutcome ( String winner , String keeperKey , Object instanceIdentifier ) { this . winner = winner ; this . keeperKey = keeperKey ; this . instanceIdentifier = instanceIdentifier ; } @ Override public boolean isWon ( ) { return true ; } @ Override public String getWinner ( ) { return winner ; } @ Override public void complete ( ) { try { PreparedStatement updateStmt = createUpdateStatementFor ( connection , keeperKey , instanceIdentifier ) ; int count = updateStmt . executeUpdate ( ) ; logger . info ( "" + count + "" ) ; updateStmt . close ( ) ; } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } } } class Query { private boolean complete ; private String winner ; private final String keeperKey ; private final Object instanceIdentifier ; public Query ( String keeperKey , Object instanceIdentifier ) { this . keeperKey = keeperKey ; this . instanceIdentifier = instanceIdentifier ; } void query ( ) throws SQLException { PreparedStatement queryStmt = createQueryStatementFor ( connection , keeperKey , instanceIdentifier ) ; ResultSet rs = queryStmt . executeQuery ( ) ; if ( ! rs . next ( ) ) { throw new IllegalStateException ( "" + keeperKey + "" + instanceIdentifier ) ; } winner = rs . getString ( ) ; complete = rs . getBoolean ( ) ; queryStmt . close ( ) ; } public String getWinner ( ) { return winner ; } public boolean isComplete ( ) { return complete ; } } class Poll implements Runnable { private final ALoosingOutcome loosing ; private final String keeperKey ; private final Object instanceIdentifier ; private volatile Future < ? > future ; private volatile ScheduleContext scheduleContext = new ScheduleContext ( new Date ( ) ) ; public Poll ( ALoosingOutcome loosing , String keeperKey , Object instanceIdentifier ) { this . loosing = loosing ; this . keeperKey = keeperKey ; this . instanceIdentifier = instanceIdentifier ; } @ Override public void run ( ) { synchronized ( loosers ) { loosers . remove ( loosing ) ; } try { Query query = new Query ( keeperKey , instanceIdentifier ) ; query . query ( ) ; if ( query . isComplete ( ) ) { loosing . stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { loosing . stateHandler . setState ( JobState . COMPLETE ) ; loosing . stateHandler . fireEvent ( ) ; } } ) ; } else { ScheduleResult nextDue = pollSchedule . nextDue ( scheduleContext ) ; if ( nextDue == null ) { loosing . stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { loosing . stateHandler . setStateException ( JobState . EXCEPTION , new Exception ( "" + "" ) ) ; loosing . stateHandler . fireEvent ( ) ; } } ) ; } else { scheduleContext = scheduleContext . move ( new IntervalTo ( nextDue ) . getToDate ( ) ) ; long delay = nextDue . getToDate ( ) . getTime ( ) - new Date ( ) . getTime ( ) ; if ( delay <= ) { delay = ; } synchronized ( loosers ) { if ( running ) { this . future = scheduler . schedule ( this , delay , TimeUnit . MILLISECONDS ) ; loosers . add ( loosing ) ; } } } } } catch ( SQLException e ) { logger . error ( "" , e ) ; } } private void stop ( ) { if ( future != null ) { future . cancel ( false ) ; future = null ; } } } class ALoosingOutcome implements LoosingOutcome { private final String winner ; private final JobStateHandler stateHandler = new JobStateHandler ( this ) ; private final Poll poll ; public ALoosingOutcome ( String winner , String keeperKey , Object instanceIdentifier ) { this . winner = winner ; poll = new Poll ( this , keeperKey , instanceIdentifier ) ; } @ Override public void addStateListener ( StateListener listener ) { if ( stateHandler . listenerCount ( ) == ) { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { stateHandler . setState ( JobState . EXECUTING ) ; } } ) ; poll . run ( ) ; } stateHandler . addStateListener ( listener ) ; } @ Override public void removeStateListener ( StateListener listener ) { stateHandler . removeStateListener ( listener ) ; if ( stateHandler . listenerCount ( ) == ) { synchronized ( loosers ) { loosers . remove ( this ) ; } poll . stop ( ) ; } } @ Override public StateEvent lastStateEvent ( ) { return stateHandler . lastStateEvent ( ) ; } private void stop ( ) { poll . stop ( ) ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { stateHandler . setState ( JobState . INCOMPLETE ) ; stateHandler . fireEvent ( ) ; } } ) ; } @ Override public String getWinner ( ) { return winner ; } @ Override public boolean isWon ( ) { return false ; } } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public void setConnection ( Connection connection ) throws SQLException { this . connection = connection ; } public int getPollerCount ( ) { return loosers . size ( ) ; } protected PreparedStatement createInsertStatementFor ( Connection connection , String keeperKey , String ourIdentifier , Object instanceIdentifier ) throws SQLException { PreparedStatement insertStmt = connection . prepareStatement ( "" + getTable ( ) + "" + "" ) ; insertStmt . setString ( , keeperKey ) ; insertStmt . setObject ( , instanceIdentifier ) ; insertStmt . setString ( , ourIdentifier ) ; return insertStmt ; } protected PreparedStatement createQueryStatementFor ( Connection connection , String keeperKey , Object instanceIdentifier ) throws SQLException { PreparedStatement queryStmt = connection . prepareStatement ( "" + getTable ( ) + "" ) ; queryStmt . setString ( , keeperKey ) ; queryStmt . setObject ( , instanceIdentifier ) ; return queryStmt ; } protected PreparedStatement createUpdateStatementFor ( Connection connection , String keeperKey , Object instanceIdentifier ) throws SQLException { PreparedStatement updateStmt = connection . prepareStatement ( "" + getTable ( ) + "" ) ; updateStmt . setString ( , keeperKey ) ; updateStmt . setObject ( , instanceIdentifier ) ; return updateStmt ; } public String getTable ( ) { return table ; } public void setTable ( String table ) { this . table = table ; } public Schedule getPollSchedule ( ) { return pollSchedule ; } public void setPollSchedule ( Schedule schedule ) { this . pollSchedule = schedule ; } @ Inject public void setScheduleExecutorService ( ScheduledExecutorService scheduler ) { this . scheduler = scheduler ; } @ Override public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } return name ; } } package org . oddjob . sql ; import java . sql . SQLException ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . Destination ; public interface SQLExecutor extends Destination < String > { public void accept ( String sql ) throws BadBeanException ; } package org . oddjob . sql ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . io . UnsupportedEncodingException ; import java . util . StringTokenizer ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . runtime . ExpressionParser ; import org . oddjob . arooa . runtime . ParsedExpression ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . BeanBus ; import org . oddjob . beanbus . BusAware ; import org . oddjob . beanbus . BusEvent ; import org . oddjob . beanbus . BusException ; import org . oddjob . beanbus . BusListener ; import org . oddjob . beanbus . CrashBusException ; import org . oddjob . beanbus . Destination ; import org . oddjob . beanbus . Driver ; import org . oddjob . beanbus . StageListener ; import org . oddjob . beanbus . StageNotifier ; import org . oddjob . beanbus . StageSupport ; import org . oddjob . sql . SQLJob . DelimiterType ; public class ScriptParser implements ArooaSessionAware , Driver < String > , BusAware , StageNotifier { private static final Logger logger = Logger . getLogger ( ScriptParser . class ) ; private boolean keepFormat ; private boolean expandProperties ; private DelimiterType delimiterType = DelimiterType . NORMAL ; private String delimiter = "" ; private String encoding = null ; private ArooaSession session ; private InputStream input ; private Destination < ? super String > to ; private final StageSupport stageSupport = new StageSupport ( this ) ; private volatile boolean stop ; @ Override public void setArooaSession ( ArooaSession session ) { this . session = session ; } public boolean isKeepFormat ( ) { return keepFormat ; } public void setKeepFormat ( boolean keepformat ) { this . keepFormat = keepformat ; } public boolean isExpandProperties ( ) { return expandProperties ; } public void setExpandProperties ( boolean expandProperties ) { this . expandProperties = expandProperties ; } public DelimiterType getDelimiterType ( ) { return delimiterType ; } public void setDelimiterType ( DelimiterType delimiterType ) { this . delimiterType = delimiterType ; } public String getDelimiter ( ) { return delimiter ; } public void setDelimiter ( String delimiter ) { this . delimiter = delimiter ; } public String getEncoding ( ) { return encoding ; } public void setEncoding ( String encoding ) { this . encoding = encoding ; } @ Override public void go ( ) throws BusException { stop = false ; StringBuffer sql = new StringBuffer ( ) ; BufferedReader in = null ; try { if ( encoding == null ) { in = new BufferedReader ( new InputStreamReader ( input ) ) ; } else { in = new BufferedReader ( new InputStreamReader ( input , encoding ) ) ; } } catch ( UnsupportedEncodingException e1 ) { throw new CrashBusException ( e1 ) ; } while ( ! stop ) { String line ; try { line = in . readLine ( ) ; } catch ( IOException e ) { throw new CrashBusException ( e ) ; } if ( line == null ) { break ; } if ( ! keepFormat ) { line = line . trim ( ) ; } if ( expandProperties ) { try { line = replaceProperties ( line ) ; } catch ( ArooaConversionException e ) { throw new BadBeanException ( line , e ) ; } } if ( ! keepFormat ) { if ( line . startsWith ( "" ) ) { continue ; } if ( line . startsWith ( "" ) ) { continue ; } StringTokenizer st = new StringTokenizer ( line ) ; if ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) ; if ( "" . equalsIgnoreCase ( token ) ) { continue ; } } } sql . append ( keepFormat ? "" : "" ) . append ( line ) ; if ( ! keepFormat && line . indexOf ( "" ) >= ) { sql . append ( "" ) ; } if ( ( delimiterType . equals ( DelimiterType . NORMAL ) && line . lastIndexOf ( delimiter ) == line . length ( ) - delimiter . length ( ) ) || ( delimiterType . equals ( DelimiterType . ROW ) && line . equalsIgnoreCase ( delimiter ) ) ) { String text = sql . substring ( , sql . length ( ) - delimiter . length ( ) ) . trim ( ) ; if ( text . length ( ) > ) { dispatch ( text ) ; } sql . replace ( , sql . length ( ) , "" ) ; } } String text = sql . toString ( ) . trim ( ) ; if ( text . length ( ) > ) { dispatch ( text . toString ( ) ) ; } } private void dispatch ( String sql ) throws BadBeanException , CrashBusException { stageSupport . fireStageStarting ( "" , sql ) ; to . accept ( sql ) ; stageSupport . fireStageComplete ( ) ; } String replaceProperties ( String line ) throws ArooaConversionException { ExpressionParser lineParser = session . getTools ( ) . getExpressionParser ( ) ; ParsedExpression parsed = lineParser . parse ( line ) ; return parsed . evaluate ( session , String . class ) ; } @ Override public void setBus ( BeanBus bus ) { bus . addBusListener ( new BusListener ( ) { @ Override public void busTerminated ( BusEvent event ) { } @ Override public void busStopping ( BusEvent event ) throws CrashBusException { event . getSource ( ) . removeBusListener ( this ) ; try { input . close ( ) ; } catch ( IOException e ) { throw new CrashBusException ( e ) ; } } @ Override public void busStarting ( BusEvent event ) throws CrashBusException { } @ Override public void busCrashed ( BusEvent event , BusException e ) { event . getSource ( ) . removeBusListener ( this ) ; try { input . close ( ) ; } catch ( IOException ioe ) { logger . error ( ioe ) ; } } } ) ; if ( to instanceof BusAware ) { ( ( BusAware ) to ) . setBus ( bus ) ; } } @ Override public void addStageListener ( StageListener listener ) { stageSupport . addStageListener ( listener ) ; } @ Override public void removeStageListener ( StageListener listener ) { stageSupport . removeStageListener ( listener ) ; } @ Override public void setTo ( Destination < ? super String > to ) { this . to = to ; } @ Override public void stop ( ) { stop = true ; } public InputStream getInput ( ) { return input ; } public void setInput ( InputStream input ) { this . input = input ; } } package org . oddjob . sql ; import java . io . IOException ; import java . io . InputStream ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . sql . Connection ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . types . IdentifiableValueType ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . BadBeanFilter ; import org . oddjob . beanbus . CrashBusException ; import org . oddjob . beanbus . SimpleBus ; import org . oddjob . io . BufferType ; import org . oddjob . io . FileType ; public class SQLJob implements Runnable , Serializable , ArooaSessionAware , Stoppable { private static final long serialVersionUID = ; public enum DelimiterType { NORMAL , ROW , } public enum OnError { CONTINUE , STOP , ABORT ; } private transient ScriptParser parser ; private transient BadSQLHandler errorHandler ; private transient ParameterisedExecutor executor ; private String name ; private transient SQLResultsProcessor results ; private transient ArooaSession session ; public SQLJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { executor = new ParameterisedExecutor ( ) ; parser = new ScriptParser ( ) ; errorHandler = new BadSQLHandler ( ) ; } @ Override @ ArooaHidden public void setArooaSession ( ArooaSession session ) { this . session = session ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public void run ( ) { if ( results == null ) { executor . setResultProcessor ( new SQLResultsProcessor ( ) { @ Override public void accept ( Object bean ) throws BadBeanException , CrashBusException { } } ) ; } else { executor . setResultProcessor ( results ) ; } parser . setArooaSession ( session ) ; executor . setArooaSession ( session ) ; BadBeanFilter < String > errorFilter = new BadBeanFilter < String > ( ) ; errorFilter . setBadBeanHandler ( errorHandler ) ; parser . setTo ( errorFilter ) ; errorFilter . setTo ( executor ) ; SimpleBus < String > bus = new SimpleBus < String > ( ) ; bus . setDriver ( parser ) ; bus . run ( ) ; } @ Override public void stop ( ) { parser . stop ( ) ; executor . stop ( ) ; } public SQLResultsProcessor getResults ( ) { return results ; } public void setResults ( SQLResultsProcessor results ) { this . results = results ; } public void setInput ( InputStream sql ) { parser . setInput ( sql ) ; } public void setExpandProperties ( boolean expandProperties ) { this . parser . setExpandProperties ( expandProperties ) ; } public boolean getExpandProperties ( ) { return this . parser . isExpandProperties ( ) ; } public void setEncoding ( String encoding ) { this . parser . setEncoding ( encoding ) ; } public String getEncoding ( ) { return this . parser . getEncoding ( ) ; } public void setDelimiter ( String delimiter ) { this . parser . setDelimiter ( delimiter ) ; } public String getDelimiter ( ) { return this . parser . getDelimiter ( ) ; } public void setDelimiterType ( DelimiterType delimiterType ) { this . parser . setDelimiterType ( delimiterType ) ; } public DelimiterType getDelimiterType ( ) { return this . parser . getDelimiterType ( ) ; } public void setKeepFormat ( boolean keepformat ) { this . parser . setKeepFormat ( keepformat ) ; } public boolean isKeepFormat ( ) { return this . parser . isKeepFormat ( ) ; } public void setConnection ( Connection connection ) { executor . setConnection ( connection ) ; } public void setAutocommit ( boolean autocommit ) { executor . setAutocommit ( autocommit ) ; } public boolean isAutocommit ( ) { return executor . isAutocommit ( ) ; } public ValueType getParameters ( int index ) { return executor . getParameters ( index ) ; } public void setParameters ( int index , ValueType parameter ) { executor . setParameters ( index , parameter ) ; } public void setCallable ( boolean callable ) { executor . setCallable ( callable ) ; } public boolean isCallable ( ) { return executor . isCallable ( ) ; } public void setEscapeProcessing ( boolean enable ) { executor . setEscapeProcessing ( enable ) ; } public boolean isEscapeProcessing ( ) { return executor . isEscapeProcessing ( ) ; } public void setOnError ( OnError action ) { this . errorHandler . setOnError ( action ) ; } public OnError getOnError ( ) { return this . errorHandler . getOnError ( ) ; } public int getExecutedSQLCount ( ) { return this . executor . getExecutedSQLCount ( ) ; } public int getSuccessfulSQLCount ( ) { return this . executor . getSuccessfulSQLCount ( ) ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; completeConstruction ( ) ; } public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } else { return name ; } } } package org . oddjob . sql ; import java . sql . SQLException ; import org . oddjob . arooa . registry . Path ; public interface SQLSerialization { public void persist ( Path path , String id , Object o ) throws SQLException ; public Object restore ( Path path , String id , ClassLoader classLoader ) throws SQLException ; public void remove ( Path path , String id ) throws SQLException ; public String [ ] children ( Path path ) throws SQLException ; public void clear ( Path path ) throws SQLException ; public void close ( ) throws SQLException ; } package org . oddjob . sql ; import java . io . InputStream ; import java . sql . Blob ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . arooa . registry . Path ; import org . oddjob . persist . SerializeWithBinaryStream ; import org . oddjob . persist . SerializeWithBytes ; public class HSQLSerializationFactory implements SQLSerializationFactory { private String table ; @ Override public SQLSerialization createSerialization ( Connection connection ) throws SQLException { return new HSQLSerialization ( connection , table ) ; } public void setTable ( String tableName ) { this . table = tableName ; } public String getTable ( ) { return table ; } } class HSQLSerialization implements SQLSerialization { private static final Logger logger = Logger . getLogger ( HSQLSerialization . class ) ; private final Connection connection ; private final PreparedStatement updateStmt ; private final PreparedStatement insertStmt ; private final PreparedStatement selectStmt ; private final PreparedStatement deleteStmt ; private final PreparedStatement clearStmt ; private final PreparedStatement listStmt ; HSQLSerialization ( Connection connection , String tableName ) throws SQLException { this . connection = connection ; String table = tableName ; if ( table == null ) { table = "" ; } try { String insertSQL = "" + table + "" ; logger . debug ( "" + insertSQL ) ; this . insertStmt = connection . prepareStatement ( insertSQL ) ; String updateSQL = "" + table + "" ; logger . debug ( "" + updateSQL ) ; this . updateStmt = connection . prepareStatement ( updateSQL ) ; String selectSQL = "" + table + "" ; logger . debug ( "" + selectSQL ) ; this . selectStmt = connection . prepareStatement ( selectSQL ) ; String deleteSQL = "" + table + "" ; logger . debug ( "" + deleteSQL ) ; this . deleteStmt = connection . prepareStatement ( deleteSQL ) ; String clearSQL = "" + table + "" ; logger . debug ( "" + clearSQL ) ; this . clearStmt = connection . prepareStatement ( clearSQL ) ; String listSQL = "" + table + "" ; logger . debug ( "" + listSQL ) ; this . listStmt = connection . prepareStatement ( listSQL ) ; } catch ( SQLException e ) { try { close ( ) ; } catch ( SQLException e2 ) { } throw e ; } } @ Override public synchronized void close ( ) throws SQLException { SQLException ex = null ; if ( updateStmt != null ) { try { updateStmt . close ( ) ; } catch ( SQLException e ) { ex = e ; } } if ( insertStmt != null ) { try { insertStmt . close ( ) ; } catch ( SQLException e ) { ex = e ; } } if ( selectStmt != null ) { try { selectStmt . close ( ) ; } catch ( SQLException e ) { ex = e ; } } if ( deleteStmt != null ) { try { deleteStmt . close ( ) ; } catch ( SQLException e ) { ex = e ; } } if ( clearStmt != null ) { try { clearStmt . close ( ) ; } catch ( SQLException e ) { ex = e ; } } if ( listStmt != null ) { try { listStmt . close ( ) ; } catch ( SQLException e ) { ex = e ; } } if ( connection != null ) { try { connection . close ( ) ; } catch ( SQLException e ) { ex = e ; } } if ( ex != null ) { throw ex ; } } @ Override public void persist ( Path path , String id , Object o ) throws SQLException { synchronized ( updateStmt ) { byte [ ] bytes = new SerializeWithBytes ( ) . toBytes ( o ) ; logger . debug ( "" + path + "" + id + "" + bytes . length + "" ) ; updateStmt . setBytes ( , bytes ) ; updateStmt . setString ( , path . toString ( ) ) ; updateStmt . setString ( , id ) ; int count = updateStmt . executeUpdate ( ) ; if ( count == ) { return ; } insertStmt . setString ( , path . toString ( ) ) ; insertStmt . setString ( , id ) ; insertStmt . setBytes ( , bytes ) ; insertStmt . execute ( ) ; } } @ Override public Object restore ( Path path , String id , ClassLoader classLoader ) throws SQLException { synchronized ( selectStmt ) { selectStmt . setString ( , path . toString ( ) ) ; selectStmt . setString ( , id ) ; ResultSet rs = selectStmt . executeQuery ( ) ; try { if ( ! rs . next ( ) ) { return null ; } logger . debug ( "" + path + "" + id + "" ) ; Blob blob = rs . getBlob ( ) ; InputStream is = blob . getBinaryStream ( ) ; return new SerializeWithBinaryStream ( ) . fromStream ( is , classLoader ) ; } finally { rs . close ( ) ; } } } @ Override public void remove ( Path path , String id ) throws SQLException { synchronized ( deleteStmt ) { deleteStmt . setString ( , path . toString ( ) ) ; deleteStmt . setString ( , id ) ; deleteStmt . executeUpdate ( ) ; } } @ Override public void clear ( Path path ) throws SQLException { synchronized ( clearStmt ) { clearStmt . setString ( , path . toString ( ) ) ; clearStmt . executeUpdate ( ) ; } } @ Override public String [ ] children ( Path path ) throws SQLException { synchronized ( listStmt ) { listStmt . setString ( , path . toString ( ) ) ; ResultSet rs = listStmt . executeQuery ( ) ; try { List < String > results = new ArrayList < String > ( ) ; while ( rs . next ( ) ) { results . add ( rs . getString ( ) ) ; } return results . toArray ( new String [ results . size ( ) ] ) ; } finally { rs . close ( ) ; } } } } package org . oddjob . util ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Stoppable ; public class SimpleThreadManager implements ThreadManager { private static final Logger logger = Logger . getLogger ( SimpleThreadManager . class ) ; private final Map < Runnable , Remember > active = new HashMap < Runnable , Remember > ( ) ; private final ExecutorService executors ; public SimpleThreadManager ( ) { this ( Executors . newCachedThreadPool ( ) ) ; } public SimpleThreadManager ( ExecutorService executors ) { this . executors = executors ; } public void run ( final Runnable runnable , final String description ) { Runnable wrapper = new Runnable ( ) { public void run ( ) { try { runnable . run ( ) ; } catch ( Throwable t ) { logger . error ( "" + description + "" , t ) ; } finally { synchronized ( active ) { active . remove ( runnable ) ; } } } @ Override public String toString ( ) { return "" + description ; } } ; synchronized ( active ) { Future < ? > future = executors . submit ( wrapper ) ; active . put ( runnable , new Remember ( description , future ) ) ; } } public String [ ] activeDescriptions ( ) { List < String > results = new ArrayList < String > ( ) ; synchronized ( active ) { for ( Remember remember : active . values ( ) ) { results . add ( remember . description ) ; } return ( String [ ] ) results . toArray ( new String [ ] ) ; } } public String toString ( ) { return "" + active . size ( ) + "" ; } public void close ( ) { synchronized ( active ) { for ( Map . Entry < Runnable , Remember > entry : active . entrySet ( ) ) { Runnable runnable = entry . getKey ( ) ; Remember remember = entry . getValue ( ) ; if ( runnable instanceof Stoppable ) { try { ( ( Stoppable ) runnable ) . stop ( ) ; } catch ( FailedToStopException e ) { logger . warn ( e ) ; } } else { remember . future . cancel ( true ) ; } } } executors . shutdownNow ( ) ; } class Remember { private final String description ; private final Future < ? > future ; Remember ( String description , Future < ? > runnable ) { this . description = description ; this . future = runnable ; } } } package org . oddjob . util ; import java . io . File ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import javax . inject . Inject ; import org . apache . log4j . Logger ; import org . oddjob . arooa . types . ValueFactory ; public class URLClassLoaderType implements ValueFactory < ClassLoader > { private static final Logger logger = Logger . getLogger ( URLClassLoaderType . class ) ; private ClassLoader parent ; private URL [ ] urls ; private File [ ] files ; private boolean noInherit ; public ClassLoader toValue ( ) { final StringBuilder toString = new StringBuilder ( ) ; List < URL > allUrls = new ArrayList < URL > ( ) ; if ( urls != null ) { logger . debug ( "" ) ; for ( URL url : urls ) { logger . debug ( "" + url ) ; toString . append ( ( toString . length ( ) == ? "" : "" ) + url ) ; allUrls . add ( url ) ; } } if ( files != null ) { logger . debug ( "" ) ; for ( File file : files ) { logger . debug ( "" + file ) ; toString . append ( ( toString . length ( ) == ? "" : "" ) + file ) ; try { allUrls . add ( file . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } } ClassLoader parentLoader = parent ; if ( noInherit ) { parentLoader = null ; } return new URLClassLoader ( allUrls . toArray ( new URL [ allUrls . size ( ) ] ) , parentLoader ) { public String toString ( ) { return "" + toString . toString ( ) ; } } ; } public URL [ ] getUrls ( ) { return urls ; } public void setUrls ( URL [ ] urls ) { this . urls = urls ; } public File [ ] getFiles ( ) { return files ; } public void setFiles ( File [ ] files ) { this . files = files ; } public boolean isNoInherit ( ) { return noInherit ; } public void setNoInherit ( boolean noInherit ) { this . noInherit = noInherit ; } public ClassLoader getParent ( ) { return parent ; } @ Inject public void setParent ( ClassLoader parent ) { this . parent = parent ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + ( files == null ? "" : Arrays . toString ( files ) ) + ( urls == null ? "" : Arrays . toString ( urls ) ) ; } } package org . oddjob . util ; import java . util . Date ; public interface Clock { public Date getDate ( ) ; } package org . oddjob . util ; import java . util . Date ; public class DefaultClock implements Clock { public Date getDate ( ) { return new Date ( ) ; } public String toString ( ) { return "" + new Date ( ) ; } } package org . oddjob . util ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . ObjectOutputStream ; import java . io . OutputStream ; import java . io . Serializable ; public class IO { public static void copy ( InputStream in , OutputStream out ) throws IOException { byte b [ ] = new byte [ ] ; int i ; while ( ( i = in . read ( b ) ) != - ) { out . write ( b , , i ) ; } } public static boolean canSerialize ( Object o ) { if ( o == null ) { return true ; } if ( ! ( o instanceof Serializable ) ) { return false ; } ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; try { ObjectOutputStream s = new ObjectOutputStream ( os ) ; s . writeObject ( o ) ; } catch ( IOException e ) { return false ; } return true ; } } package org . oddjob . util ; import java . net . URL ; import org . apache . log4j . Logger ; public class ClassLoaderDiagnostics implements Runnable { private static final Logger logger = Logger . getLogger ( ClassLoaderDiagnostics . class ) ; private String name ; private String className ; private String resource ; private ClassLoader classLoader ; private String location ; public void run ( ) { location = null ; ClassLoader classLoader = this . classLoader ; if ( classLoader == null ) { classLoader = getClass ( ) . getClassLoader ( ) ; } logClassLoaderStack ( classLoader ) ; if ( className != null ) { resource = className . replace ( '' , '' ) + "" ; } if ( resource == null ) { return ; } if ( resource . startsWith ( "" ) ) { resource = resource . substring ( ) ; } URL url = classLoader . getResource ( resource ) ; if ( url != null ) { location = url . toExternalForm ( ) ; logger . info ( "" + resource + "" + location ) ; } else { logger . info ( "" + resource + "" ) ; } } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public String getResource ( ) { return resource ; } public void setResource ( String resource ) { this . resource = resource ; } public String getClassName ( ) { return className ; } public void setClassName ( String classname ) { this . className = classname ; } public ClassLoader getClassLoader ( ) { return classLoader ; } public void setClassLoader ( ClassLoader classLoader ) { this . classLoader = classLoader ; } public String getLocation ( ) { return location ; } @ Override public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } else { return name ; } } public static void logClassLoaderStack ( ClassLoader loader ) { if ( logger . isInfoEnabled ( ) ) { logger . info ( "" ) ; for ( ClassLoader next = loader ; next != null ; next = next . getParent ( ) ) { logger . info ( "" + next ) ; } } } } package org . oddjob . util ; public interface ThreadManager { public void run ( Runnable runnable , String description ) ; public String [ ] activeDescriptions ( ) ; public void close ( ) ; } package org . oddjob . util ; import org . oddjob . OddjobException ; import org . oddjob . arooa . parsing . Location ; public class OddjobConfigException extends OddjobException { private static final long serialVersionUID = ; public OddjobConfigException ( String msg ) { super ( msg ) ; } public OddjobConfigException ( String msg , Location location ) { super ( msg + "" + location . toString ( ) ) ; } } package org . oddjob . util ; public class OddjobLockedException extends Exception { private static final long serialVersionUID = ; public OddjobLockedException ( String msg ) { super ( msg ) ; } } package org . oddjob . util ; import java . lang . management . ManagementFactory ; import java . lang . management . MemoryMXBean ; import java . lang . management . RuntimeMXBean ; import java . util . Date ; public class ManagementDiagnostics implements Runnable { private String jvmName ; private Date startTime ; private String heapMemory ; private String nonHeapMemory ; @ Override public void run ( ) { RuntimeMXBean runtime = ManagementFactory . getRuntimeMXBean ( ) ; jvmName = runtime . getName ( ) ; startTime = new Date ( runtime . getStartTime ( ) ) ; MemoryMXBean memory = ManagementFactory . getMemoryMXBean ( ) ; heapMemory = memory . getHeapMemoryUsage ( ) . toString ( ) ; nonHeapMemory = memory . getNonHeapMemoryUsage ( ) . toString ( ) ; } public String getJvmName ( ) { return jvmName ; } public Date getStartTime ( ) { return startTime ; } public String getHeapMemory ( ) { return heapMemory ; } public String getNonHeapMemory ( ) { return nonHeapMemory ; } } package org . oddjob . util ; import java . io . IOException ; import java . io . OutputStream ; public class StreamPrinter { private static final byte [ ] EOL = System . getProperty ( "" ) . getBytes ( ) ; private final OutputStream out ; public StreamPrinter ( OutputStream out ) { if ( out == null ) { throw new NullPointerException ( "" ) ; } this . out = out ; } public void println ( ) { try { out . write ( EOL ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } public void println ( String s ) { try { out . write ( s . getBytes ( ) ) ; out . write ( EOL ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } package org . oddjob . util ; public class OddjobConstantException extends RuntimeException { private static final long serialVersionUID = ; public OddjobConstantException ( String msg ) { super ( msg ) ; } } package org . oddjob . util ; public class ClassLoaderSorter { public ClassLoader getTopLoader ( Class < ? > [ ] forClasses ) { ClassLoader topLoader = ClassLoader . getSystemClassLoader ( ) ; for ( Class < ? > cl : forClasses ) { for ( ClassLoader checkLoader = cl . getClassLoader ( ) ; checkLoader != null ; checkLoader = checkLoader . getParent ( ) ) { if ( checkLoader == topLoader ) { topLoader = cl . getClassLoader ( ) ; break ; } } } return topLoader ; } } package org . oddjob ; public class OJConstants { public static final String SUBSTITUTION_POLICY_STRICT = "" ; public static final String SUBSTITUTION_POLICY_ANTLIKE = "" ; public static final String DEFAULT_LOG_FORMAT = "" ; } package org . oddjob . launch ; import java . io . File ; import java . io . IOException ; import java . lang . reflect . Method ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; public class Launcher implements Runnable { public static final String ODDJOB_HOME_PROPERTY = "" ; public static final String ODDJOB_RUN_JAR_PROPERTY = "" ; public static final String ODDJOB_MAIN_CLASS = "" ; private ClassLoader classLoader ; private String className ; private String [ ] args ; public void run ( ) { if ( classLoader == null ) { throw new NullPointerException ( "" ) ; } if ( className == null ) { throw new NullPointerException ( "" ) ; } ClassLoader currentLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; try { Class < ? > mainClass = classLoader . loadClass ( className ) ; Method method = mainClass . getMethod ( "" , new Class [ ] { String [ ] . class } ) ; method . invoke ( null , ( Object ) args ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( currentLoader ) ; } } static ClassLoader getClassLoader ( ClassLoader currentLoader , String [ ] classpath ) throws IOException { File sourceJar = Locator . getClassSource ( Launcher . class ) ; File jarDir = sourceJar . getParentFile ( ) ; System . setProperty ( ODDJOB_HOME_PROPERTY , jarDir . getCanonicalPath ( ) ) ; System . setProperty ( ODDJOB_RUN_JAR_PROPERTY , sourceJar . getCanonicalPath ( ) ) ; List < File > classPathList = new ArrayList < File > ( ) ; classPathList . add ( sourceJar ) ; for ( String entry : classpath ) { File [ ] entryFiles = new FileSpec ( new File ( entry ) ) . getFiles ( ) ; classPathList . addAll ( Arrays . asList ( entryFiles ) ) ; } File [ ] libFiles = new FileSpec ( new File ( new File ( jarDir , "" ) , "" ) ) . getFiles ( ) ; classPathList . addAll ( Arrays . asList ( libFiles ) ) ; classPathList . add ( new File ( jarDir , "" ) ) ; File [ ] optFiles = new FileSpec ( new File ( new File ( jarDir , "" ) , "" ) ) . getFiles ( ) ; classPathList . addAll ( Arrays . asList ( optFiles ) ) ; ClassPathHelper classPathHelper = new ClassPathHelper ( classPathList . toArray ( new File [ classPathList . size ( ) ] ) ) ; URL [ ] urls = classPathHelper . toURLs ( ) ; classPathHelper . appendToJavaClassPath ( ) ; final String classPath = classPathHelper . toString ( ) ; ClassLoader cl = new URLClassLoader ( urls , currentLoader ) { @ Override public String toString ( ) { return "" + classPath ; } } ; return cl ; } public ClassLoader getClassLoader ( ) { return classLoader ; } public void setClassLoader ( ClassLoader classLoader ) { this . classLoader = classLoader ; } public String getClassName ( ) { return className ; } public void setClassName ( String className ) { this . className = className ; } public String [ ] getArgs ( ) { return args ; } public void setArgs ( String [ ] args ) { this . args = args ; } public static void main ( String ... args ) throws IOException { args = new SystemPropertyArgParser ( ) . processArgs ( args ) ; PathParser path = new PathParser ( ) ; args = path . processArgs ( args ) ; ClassLoader loader = getClassLoader ( Thread . currentThread ( ) . getContextClassLoader ( ) , path . getElements ( ) ) ; Launcher launcher = new Launcher ( ) ; launcher . setArgs ( args ) ; launcher . setClassLoader ( loader ) ; launcher . setClassName ( ODDJOB_MAIN_CLASS ) ; launcher . run ( ) ; } } package org . oddjob . launch ; import java . util . ArrayList ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class SystemPropertyArgParser { private final Pattern pattern ; public SystemPropertyArgParser ( ) { pattern = Pattern . compile ( "" ) ; } public String [ ] processArgs ( String [ ] args ) { List < String > returned = new ArrayList < String > ( ) ; boolean ignore = false ; for ( int i = ; i < args . length ; ++ i ) { if ( "" . equals ( args [ i ] ) ) { ignore = true ; } if ( ignore ) { returned . add ( args [ i ] ) ; continue ; } Matcher match = pattern . matcher ( args [ i ] ) ; if ( ! match . matches ( ) ) { returned . add ( args [ i ] ) ; continue ; } String property = match . group ( ) ; String value = match . group ( ) ; System . setProperty ( property , value ) ; } return returned . toArray ( new String [ returned . size ( ) ] ) ; } } package org . oddjob . launch ; import java . io . File ; import java . io . FilenameFilter ; import java . net . MalformedURLException ; import java . net . URL ; import java . text . CharacterIterator ; import java . text . StringCharacterIterator ; public final class Locator { private Locator ( ) { } public static File getClassSource ( Class c ) { String classResource = c . getName ( ) . replace ( '' , '' ) + "" ; return getResourceSource ( c . getClassLoader ( ) , classResource ) ; } public static File getResourceSource ( ClassLoader c , String resource ) { if ( c == null ) { c = Locator . class . getClassLoader ( ) ; } URL url = c . getResource ( resource ) ; if ( url != null ) { String u = url . toString ( ) ; if ( u . startsWith ( "" ) ) { int pling = u . indexOf ( "" ) ; String jarName = u . substring ( , pling ) ; return new File ( fromURI ( jarName ) ) ; } else if ( u . startsWith ( "" ) ) { int tail = u . indexOf ( resource ) ; String dirName = u . substring ( , tail ) ; return new File ( fromURI ( dirName ) ) ; } } return null ; } public static String fromURI ( String uri ) { if ( ! uri . startsWith ( "" ) ) { throw new IllegalArgumentException ( "" ) ; } if ( uri . startsWith ( "" ) ) { uri = uri . substring ( ) ; } else { uri = uri . substring ( ) ; } uri = uri . replace ( '' , File . separatorChar ) ; if ( File . pathSeparatorChar == '' && uri . startsWith ( "" ) && uri . length ( ) > && Character . isLetter ( uri . charAt ( ) ) && uri . lastIndexOf ( '' ) > - ) { uri = uri . substring ( ) ; } StringBuffer sb = new StringBuffer ( ) ; CharacterIterator iter = new StringCharacterIterator ( uri ) ; for ( char c = iter . first ( ) ; c != CharacterIterator . DONE ; c = iter . next ( ) ) { if ( c == '' ) { char c1 = iter . next ( ) ; if ( c1 != CharacterIterator . DONE ) { int i1 = Character . digit ( c1 , ) ; char c2 = iter . next ( ) ; if ( c2 != CharacterIterator . DONE ) { int i2 = Character . digit ( c2 , ) ; sb . append ( ( char ) ( ( i1 << ) + i2 ) ) ; } } } else { sb . append ( c ) ; } } String path = sb . toString ( ) ; return path ; } public static File getToolsJar ( ) { boolean toolsJarAvailable = false ; try { Class . forName ( "" ) ; toolsJarAvailable = true ; } catch ( Exception e ) { try { Class . forName ( "" ) ; toolsJarAvailable = true ; } catch ( Exception e2 ) { } } if ( toolsJarAvailable ) { return null ; } String javaHome = System . getProperty ( "" ) ; if ( javaHome . endsWith ( "" ) ) { javaHome = javaHome . substring ( , javaHome . length ( ) - ) ; } File toolsJar = new File ( javaHome + "" ) ; if ( ! toolsJar . exists ( ) ) { System . out . println ( "" + "" + toolsJar . getPath ( ) ) ; return null ; } return toolsJar ; } public static URL [ ] getLocationURLs ( File location ) throws MalformedURLException { return getLocationURLs ( location , new String [ ] { "" } ) ; } public static URL [ ] getLocationURLs ( File location , final String [ ] extensions ) throws MalformedURLException { URL [ ] urls = new URL [ ] ; if ( ! location . exists ( ) ) { return urls ; } if ( ! location . isDirectory ( ) ) { urls = new URL [ ] ; String path = location . getPath ( ) ; for ( int i = ; i < extensions . length ; ++ i ) { if ( path . toLowerCase ( ) . endsWith ( extensions [ i ] ) ) { urls [ ] = location . toURL ( ) ; break ; } } return urls ; } File [ ] matches = location . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { for ( int i = ; i < extensions . length ; ++ i ) { if ( name . toLowerCase ( ) . endsWith ( extensions [ i ] ) ) { return true ; } } return false ; } } ) ; urls = new URL [ matches . length ] ; for ( int i = ; i < matches . length ; ++ i ) { urls [ i ] = matches [ i ] . toURL ( ) ; } return urls ; } } package org . oddjob . launch ; import java . io . File ; import java . io . IOException ; import java . net . URL ; class ClassPathHelper { static final String CLASS_PATH_PROPERTY = "" ; private final File [ ] files ; public ClassPathHelper ( File [ ] files ) { this . files = files ; } public URL [ ] toURLs ( ) { URL [ ] urls = new URL [ files . length ] ; for ( int i = ; i < urls . length ; ++ i ) { try { urls [ i ] = files [ i ] . toURI ( ) . toURL ( ) ; } catch ( IOException e ) { throw new RuntimeException ( "" + files [ i ] + "" , e ) ; } } return urls ; } public void appendToJavaClassPath ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( System . getProperty ( CLASS_PATH_PROPERTY ) ) ; for ( int i = ; i < files . length ; ++ i ) { if ( builder . length ( ) > ) { builder . append ( File . pathSeparator ) ; } try { builder . append ( files [ i ] . getCanonicalPath ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( "" + files [ i ] + "" , e ) ; } } System . setProperty ( CLASS_PATH_PROPERTY , builder . toString ( ) ) ; } public String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = ; i < files . length ; ++ i ) { if ( builder . length ( ) > ) { builder . append ( File . pathSeparator ) ; } builder . append ( files [ i ] ) ; } return builder . toString ( ) ; } } package org . oddjob . launch ; import java . io . File ; import java . io . FileFilter ; public class FileSpec { private final File filespec ; private final boolean caseSensative ; public FileSpec ( File filespec ) { this ( filespec , false ) ; } public FileSpec ( File filespec , boolean caseSensative ) { this . filespec = filespec ; this . caseSensative = caseSensative ; } public File [ ] getFiles ( ) { if ( filespec . isDirectory ( ) ) { return new File [ ] { filespec } ; } File parentDir = filespec . getParentFile ( ) ; if ( parentDir == null ) { parentDir = new File ( System . getProperty ( "" ) ) ; } File [ ] result = parentDir . listFiles ( new FileFilter ( ) { public boolean accept ( File pathname ) { return match ( filespec . getName ( ) , pathname . getName ( ) , caseSensative ) ; } } ) ; if ( result == null ) { return new File [ ] ; } if ( filespec . getParentFile ( ) == null ) { for ( int i = ; i < result . length ; ++ i ) { result [ i ] = new File ( result [ i ] . getName ( ) ) ; } } return result ; } public static boolean match ( String pattern , String str , boolean isCaseSensitive ) { char [ ] patArr = pattern . toCharArray ( ) ; char [ ] strArr = str . toCharArray ( ) ; int patIdxStart = ; int patIdxEnd = patArr . length - ; int strIdxStart = ; int strIdxEnd = strArr . length - ; char ch ; boolean containsStar = false ; for ( int i = ; i < patArr . length ; i ++ ) { if ( patArr [ i ] == '' ) { containsStar = true ; break ; } } if ( ! containsStar ) { if ( patIdxEnd != strIdxEnd ) { return false ; } for ( int i = ; i <= patIdxEnd ; i ++ ) { ch = patArr [ i ] ; if ( ch != '' ) { if ( isCaseSensitive && ch != strArr [ i ] ) { return false ; } if ( ! isCaseSensitive && Character . toUpperCase ( ch ) != Character . toUpperCase ( strArr [ i ] ) ) { return false ; } } } return true ; } if ( patIdxEnd == ) { return true ; } while ( ( ch = patArr [ patIdxStart ] ) != '' && strIdxStart <= strIdxEnd ) { if ( ch != '' ) { if ( isCaseSensitive && ch != strArr [ strIdxStart ] ) { return false ; } if ( ! isCaseSensitive && Character . toUpperCase ( ch ) != Character . toUpperCase ( strArr [ strIdxStart ] ) ) { return false ; } } patIdxStart ++ ; strIdxStart ++ ; } if ( strIdxStart > strIdxEnd ) { for ( int i = patIdxStart ; i <= patIdxEnd ; i ++ ) { if ( patArr [ i ] != '' ) { return false ; } } return true ; } while ( ( ch = patArr [ patIdxEnd ] ) != '' && strIdxStart <= strIdxEnd ) { if ( ch != '' ) { if ( isCaseSensitive && ch != strArr [ strIdxEnd ] ) { return false ; } if ( ! isCaseSensitive && Character . toUpperCase ( ch ) != Character . toUpperCase ( strArr [ strIdxEnd ] ) ) { return false ; } } patIdxEnd -- ; strIdxEnd -- ; } if ( strIdxStart > strIdxEnd ) { for ( int i = patIdxStart ; i <= patIdxEnd ; i ++ ) { if ( patArr [ i ] != '' ) { return false ; } } return true ; } while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) { int patIdxTmp = - ; for ( int i = patIdxStart + ; i <= patIdxEnd ; i ++ ) { if ( patArr [ i ] == '' ) { patIdxTmp = i ; break ; } } if ( patIdxTmp == patIdxStart + ) { patIdxStart ++ ; continue ; } int patLength = ( patIdxTmp - patIdxStart - ) ; int strLength = ( strIdxEnd - strIdxStart + ) ; int foundIdx = - ; strLoop : for ( int i = ; i <= strLength - patLength ; i ++ ) { for ( int j = ; j < patLength ; j ++ ) { ch = patArr [ patIdxStart + j + ] ; if ( ch != '' ) { if ( isCaseSensitive && ch != strArr [ strIdxStart + i + j ] ) { continue strLoop ; } if ( ! isCaseSensitive && Character . toUpperCase ( ch ) != Character . toUpperCase ( strArr [ strIdxStart + i + j ] ) ) { continue strLoop ; } } } foundIdx = strIdxStart + i ; break ; } if ( foundIdx == - ) { return false ; } patIdxStart = patIdxTmp ; strIdxStart = foundIdx + patLength ; } for ( int i = patIdxStart ; i <= patIdxEnd ; i ++ ) { if ( patArr [ i ] != '' ) { return false ; } } return true ; } } package org . oddjob . launch ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; public class PathParser { private String [ ] elements ; public String [ ] getElements ( ) { return elements ; } public String [ ] processArgs ( String [ ] args ) { List < String > returned = new ArrayList < String > ( ) ; String classpath = null ; boolean ignoreRemaining = false ; for ( int i = ; i < args . length ; ++ i ) { if ( "" . equals ( args [ i ] ) ) { ignoreRemaining = true ; } if ( ignoreRemaining ) { returned . add ( args [ i ] ) ; continue ; } if ( "" . equals ( args [ i ] ) || "" . equals ( args [ i ] ) ) { if ( ++ i == args . length ) { throw new IllegalArgumentException ( "" ) ; } classpath = args [ i ] ; ignoreRemaining = true ; } else { returned . add ( args [ i ] ) ; } } if ( classpath != null ) { elements = classpath . split ( File . pathSeparator ) ; } else { elements = new String [ ] ; } return returned . toArray ( new String [ returned . size ( ) ] ) ; } } package org . oddjob . schedules ; public class CalendarUnit { private final int field ; private final int value ; public CalendarUnit ( int field , int value ) { this . field = field ; this . value = value ; } public int getField ( ) { return field ; } public int getValue ( ) { return value ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + field + "" + value ; } } package org . oddjob . schedules ; import java . util . Date ; import org . oddjob . schedules . schedules . AfterSchedule ; public interface ScheduleResult extends Interval { public Date getUseNext ( ) ; } package org . oddjob . schedules ; import java . util . Date ; public interface ScheduleListener { public void initialised ( Date scheduleDate ) ; public void complete ( Date scheduleDate , ScheduleResult lastComplete ) ; public void retry ( Date scheduleDate , Date retryDate ) ; public void failed ( Date scheduleDate ) ; } package org . oddjob . schedules ; import java . util . Calendar ; import java . util . Date ; import java . util . GregorianCalendar ; import java . util . TimeZone ; public class DateUtils { private DateUtils ( ) { } public static Date startOfDay ( Date inDate , TimeZone timeZone ) { GregorianCalendar c1 = new GregorianCalendar ( ) ; c1 . setTimeZone ( timeZone ) ; c1 . setTime ( inDate ) ; GregorianCalendar c2 = new GregorianCalendar ( c1 . get ( Calendar . YEAR ) , c1 . get ( Calendar . MONTH ) , c1 . get ( Calendar . DATE ) ) ; c2 . setTimeZone ( timeZone ) ; return c2 . getTime ( ) ; } public static Date endOfDay ( Date inDate , TimeZone timeZone ) { Calendar inCalendar = new GregorianCalendar ( ) ; inCalendar . setTimeZone ( timeZone ) ; inCalendar . setTime ( inDate ) ; Calendar nextDay = new GregorianCalendar ( inCalendar . get ( Calendar . YEAR ) , inCalendar . get ( Calendar . MONTH ) , inCalendar . get ( Calendar . DAY_OF_MONTH ) + ) ; nextDay . setTimeZone ( timeZone ) ; return new Date ( nextDay . getTime ( ) . getTime ( ) ) ; } public static int dayOfWeek ( Date inDate , TimeZone timeZone ) { Calendar calendar = Calendar . getInstance ( timeZone ) ; calendar . setTime ( inDate ) ; return calendar . get ( Calendar . DAY_OF_WEEK ) ; } public static int month ( Date inDate , TimeZone timeZone ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeZone ( timeZone ) ; calendar . setTime ( inDate ) ; return calendar . get ( Calendar . MONTH ) ; } public static int dayOfMonth ( Date inDate , TimeZone timeZone ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeZone ( timeZone ) ; calendar . setTime ( inDate ) ; return calendar . get ( Calendar . DAY_OF_MONTH ) ; } public static int dayOfYear ( Date forDate , TimeZone timeZone ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeZone ( timeZone ) ; calendar . setTime ( forDate ) ; return calendar . get ( Calendar . DAY_OF_YEAR ) ; } public static Date oneMillisAfter ( Date date ) { if ( date . equals ( Interval . END_OF_TIME ) ) { return null ; } return new Date ( date . getTime ( ) + ) ; } public static Date oneMillisBefore ( Date date ) { return new Date ( date . getTime ( ) - ) ; } public static int compare ( Calendar c1 , Calendar c2 ) { long m1 = c1 . getTime ( ) . getTime ( ) ; long m2 = c2 . getTime ( ) . getTime ( ) ; if ( m1 < m2 ) { return - ; } if ( m1 > m2 ) { return ; } return ; } } package org . oddjob . schedules ; public class IntervalHelper { private final IntervalTo interval ; public IntervalHelper ( Interval interval ) { this . interval = new IntervalTo ( interval ) ; } public boolean isBefore ( Interval other ) { return interval . isBefore ( new IntervalTo ( other ) ) ; } public Interval limit ( Interval other ) { return interval . limit ( other ) ; } public boolean isPoint ( ) { return interval . isPoint ( ) ; } } package org . oddjob . schedules . units ; import java . util . Arrays ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public interface DayOfWeek { enum Days implements DayOfWeek { MONDAY { @ Override public int getDayNumber ( ) { return ; } } , TUESDAY { @ Override public int getDayNumber ( ) { return ; } } , WEDNESDAY { @ Override public int getDayNumber ( ) { return ; } } , THURSDAY { @ Override public int getDayNumber ( ) { return ; } } , FRIDAY { @ Override public int getDayNumber ( ) { return ; } } , SATURDAY { @ Override public int getDayNumber ( ) { return ; } } , SUNDAY { @ Override public int getDayNumber ( ) { return ; } } } public static class Conversions implements ConversionProvider { @ Override public void registerWith ( ConversionRegistry registry ) { registry . register ( String . class , DayOfWeek . class , new Convertlet < String , DayOfWeek > ( ) { @ Override public DayOfWeek convert ( String from ) throws ConvertletException { try { final int day = Integer . parseInt ( from ) ; return Days . values ( ) [ day - ] ; } catch ( IndexOutOfBoundsException e ) { throw new ConvertletException ( "" + from + "" + Arrays . asList ( Days . values ( ) ) + "" ) ; } catch ( NumberFormatException e ) { try { return Days . valueOf ( from . toUpperCase ( ) ) ; } catch ( IllegalArgumentException enumEx ) { throw new ConvertletException ( "" + from + "" + Arrays . asList ( Days . values ( ) ) + "" ) ; } } } } ) ; } } public int getDayNumber ( ) ; } package org . oddjob . schedules . units ; import java . util . Arrays ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public interface DayOfMonth { enum Shorthands implements DayOfMonth { LAST { @ Override public int getDayNumber ( ) { return ; } } , PENULTIMATE { @ Override public int getDayNumber ( ) { return - ; } } , } public static class Number implements DayOfMonth { private final int dayNumber ; public Number ( int dayNumber ) { this . dayNumber = dayNumber ; } @ Override public int getDayNumber ( ) { return dayNumber ; } @ Override public String toString ( ) { return "" + dayNumber ; } @ Override public int hashCode ( ) { return dayNumber ; } @ Override public boolean equals ( Object obj ) { if ( ! ( obj instanceof DayOfMonth ) ) { return false ; } return dayNumber == ( ( DayOfMonth ) obj ) . getDayNumber ( ) ; } } public static class Conversions implements ConversionProvider { @ Override public void registerWith ( ConversionRegistry registry ) { registry . register ( String . class , DayOfMonth . class , new Convertlet < String , DayOfMonth > ( ) { @ Override public DayOfMonth convert ( String from ) throws ConvertletException { try { final int day = Integer . parseInt ( from ) ; return new Number ( day ) ; } catch ( NumberFormatException e ) { try { return Shorthands . valueOf ( from . toUpperCase ( ) ) ; } catch ( IllegalArgumentException enumEx ) { throw new ConvertletException ( "" + from + "" + Arrays . asList ( Shorthands . values ( ) ) + "" ) ; } } } } ) ; } } public int getDayNumber ( ) ; } package org . oddjob . schedules . units ; import java . util . Arrays ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public interface WeekOfMonth { enum Weeks implements WeekOfMonth { FIRST { @ Override public int getWeekNumber ( ) { return ; } } , SECOND { @ Override public int getWeekNumber ( ) { return ; } } , THIRD { @ Override public int getWeekNumber ( ) { return ; } } , FOURTH { @ Override public int getWeekNumber ( ) { return ; } } , FIFTH { @ Override public int getWeekNumber ( ) { return ; } } , LAST { @ Override public int getWeekNumber ( ) { return - ; } } , PENULTIMATE { @ Override public int getWeekNumber ( ) { return - ; } } , } public static class Number implements WeekOfMonth { private final int weekNumber ; public Number ( int weekNumber ) { this . weekNumber = weekNumber ; } @ Override public int getWeekNumber ( ) { return weekNumber ; } @ Override public String toString ( ) { return "" + weekNumber ; } } public static class Conversions implements ConversionProvider { @ Override public void registerWith ( ConversionRegistry registry ) { registry . register ( String . class , WeekOfMonth . class , new Convertlet < String , WeekOfMonth > ( ) { @ Override public WeekOfMonth convert ( String from ) throws ConvertletException { try { final int week = Integer . parseInt ( from ) ; return new Number ( week ) ; } catch ( NumberFormatException e ) { try { return Weeks . valueOf ( from . toUpperCase ( ) ) ; } catch ( IllegalArgumentException enumEx ) { throw new ConvertletException ( "" + from + "" + Arrays . asList ( Weeks . values ( ) ) + "" ) ; } } } } ) ; } } public int getWeekNumber ( ) ; } package org . oddjob . schedules . units ; import java . util . Arrays ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public interface Month { public enum Months implements Month { JANUARY { @ Override public int getMonthNumber ( ) { return ; } } , FEBRUARY { @ Override public int getMonthNumber ( ) { return ; } } , MARCH { @ Override public int getMonthNumber ( ) { return ; } } , APRIL { @ Override public int getMonthNumber ( ) { return ; } } , MAY { @ Override public int getMonthNumber ( ) { return ; } } , JUNE { @ Override public int getMonthNumber ( ) { return ; } } , JULY { @ Override public int getMonthNumber ( ) { return ; } } , AUGUST { @ Override public int getMonthNumber ( ) { return ; } } , SEPTEMBER { @ Override public int getMonthNumber ( ) { return ; } } , OCTOBER { @ Override public int getMonthNumber ( ) { return ; } } , NOVEMBER { @ Override public int getMonthNumber ( ) { return ; } } , DECEMBER { @ Override public int getMonthNumber ( ) { return ; } } , } public static class Conversions implements ConversionProvider { @ Override public void registerWith ( ConversionRegistry registry ) { registry . register ( String . class , Month . class , new Convertlet < String , Month > ( ) { @ Override public Month convert ( String from ) throws ConvertletException { try { int month = Integer . parseInt ( from ) ; return Months . values ( ) [ month - ] ; } catch ( IndexOutOfBoundsException e ) { throw new ConvertletException ( "" + from + "" + Arrays . asList ( Months . values ( ) ) + "" ) ; } catch ( NumberFormatException e ) { try { return Months . valueOf ( from . toUpperCase ( ) ) ; } catch ( IllegalArgumentException enumEx ) { throw new ConvertletException ( "" + from + "" + Arrays . asList ( Months . values ( ) ) + "" ) ; } } } } ) ; } } public int getMonthNumber ( ) ; } package org . oddjob . schedules ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import org . oddjob . schedules . units . DayOfMonth ; import org . oddjob . schedules . units . DayOfWeek ; import org . oddjob . schedules . units . WeekOfMonth ; public class CalendarUtils { private final Calendar baseCalendar ; public CalendarUtils ( Date inDate , TimeZone timeZone ) { baseCalendar = Calendar . getInstance ( timeZone ) ; baseCalendar . setTime ( inDate ) ; } public CalendarUtils ( Calendar baseCalendar ) { this ( baseCalendar . getTime ( ) , baseCalendar . getTimeZone ( ) ) ; } public Calendar forDate ( Date date ) { Calendar c2 = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; c2 . setTime ( date ) ; return c2 ; } public Calendar startOfDay ( ) { Calendar c2 = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; c2 . clear ( ) ; c2 . set ( baseCalendar . get ( Calendar . YEAR ) , baseCalendar . get ( Calendar . MONTH ) , baseCalendar . get ( Calendar . DATE ) ) ; return c2 ; } public Calendar endOfDay ( ) { Calendar c2 = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; c2 . clear ( ) ; c2 . set ( baseCalendar . get ( Calendar . YEAR ) , baseCalendar . get ( Calendar . MONTH ) , baseCalendar . get ( Calendar . DATE ) + ) ; return c2 ; } public static void setEndOfDay ( Calendar calendar ) { calendar . add ( Calendar . DATE , ) ; calendar . set ( Calendar . HOUR_OF_DAY , ) ; calendar . set ( Calendar . MINUTE , ) ; calendar . set ( Calendar . SECOND , ) ; calendar . set ( Calendar . MILLISECOND , ) ; } public static void setEndOfMonth ( Calendar calendar ) { calendar . set ( Calendar . MONTH , calendar . get ( Calendar . MONTH ) + ) ; calendar . set ( Calendar . DAY_OF_MONTH , ) ; calendar . set ( Calendar . HOUR_OF_DAY , ) ; calendar . set ( Calendar . MINUTE , ) ; calendar . set ( Calendar . SECOND , ) ; calendar . set ( Calendar . MILLISECOND , ) ; } public Calendar startOfMonth ( ) { Calendar c2 = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; c2 . clear ( ) ; c2 . set ( baseCalendar . get ( Calendar . YEAR ) , baseCalendar . get ( Calendar . MONTH ) , ) ; return c2 ; } public Calendar endOfMonth ( ) { Calendar c2 = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; c2 . clear ( ) ; c2 . set ( baseCalendar . get ( Calendar . YEAR ) , baseCalendar . get ( Calendar . MONTH ) + , ) ; return c2 ; } public Calendar dayOfMonth ( DayOfMonth dayOfMonth ) { int day = dayOfMonth . getDayNumber ( ) ; int month = day > ? baseCalendar . get ( Calendar . MONTH ) : baseCalendar . get ( Calendar . MONTH ) + ; Calendar c2 = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; c2 . clear ( ) ; c2 . set ( baseCalendar . get ( Calendar . YEAR ) , month , day ) ; return c2 ; } public Calendar startOfWeekOfMonth ( WeekOfMonth week ) { int weekNumber = week . getWeekNumber ( ) ; Calendar result = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; result . clear ( ) ; result . setFirstDayOfWeek ( Calendar . MONDAY ) ; result . setMinimalDaysInFirstWeek ( ) ; result . set ( Calendar . YEAR , baseCalendar . get ( Calendar . YEAR ) ) ; if ( weekNumber < ) { result . set ( Calendar . MONTH , baseCalendar . get ( Calendar . MONTH ) + ) ; } else { result . set ( Calendar . MONTH , baseCalendar . get ( Calendar . MONTH ) ) ; } result . set ( Calendar . WEEK_OF_MONTH , weekNumber ) ; return result ; } public Calendar endOfWeekOfMonth ( WeekOfMonth week ) { Calendar result = startOfWeekOfMonth ( week ) ; result . add ( Calendar . DATE , ) ; return result ; } public Calendar dayOfWeekInMonth ( DayOfWeek dayOfWeek , WeekOfMonth week ) { int weekNumber = week . getWeekNumber ( ) ; int javaDay = javaDayOfWeek ( dayOfWeek ) ; Calendar result = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; result . clear ( ) ; result . set ( Calendar . YEAR , baseCalendar . get ( Calendar . YEAR ) ) ; result . set ( Calendar . MONTH , baseCalendar . get ( Calendar . MONTH ) ) ; result . set ( Calendar . DAY_OF_WEEK_IN_MONTH , weekNumber ) ; result . set ( Calendar . DAY_OF_WEEK , javaDay ) ; return result ; } public static Calendar startOfWeek ( Date inDate , TimeZone timeZone ) { Calendar c1 = Calendar . getInstance ( timeZone ) ; c1 . setTime ( inDate ) ; Calendar c2 = Calendar . getInstance ( timeZone ) ; c2 . clear ( ) ; int daysBefore = isoDayOfWeek ( c1 . get ( Calendar . DAY_OF_WEEK ) ) - ; c2 . set ( c1 . get ( Calendar . YEAR ) , c1 . get ( Calendar . MONTH ) , c1 . get ( Calendar . DAY_OF_MONTH ) - daysBefore ) ; return c2 ; } public static Calendar endOfWeek ( Date inDate , TimeZone timeZone ) { Calendar c1 = Calendar . getInstance ( timeZone ) ; c1 . setTime ( inDate ) ; Calendar c2 = Calendar . getInstance ( timeZone ) ; c2 . clear ( ) ; int daysToAdd = - isoDayOfWeek ( c1 . get ( Calendar . DAY_OF_WEEK ) ) ; c2 . set ( c1 . get ( Calendar . YEAR ) , c1 . get ( Calendar . MONTH ) , c1 . get ( Calendar . DAY_OF_MONTH ) + daysToAdd ) ; return c2 ; } private static int isoDayOfWeek ( int javaDayOfWeek ) { switch ( javaDayOfWeek ) { case Calendar . MONDAY : return ; case Calendar . TUESDAY : return ; case Calendar . WEDNESDAY : return ; case Calendar . THURSDAY : return ; case Calendar . FRIDAY : return ; case Calendar . SATURDAY : return ; case Calendar . SUNDAY : return ; default : throw new IllegalArgumentException ( "" + javaDayOfWeek ) ; } } private static int javaDayOfWeek ( DayOfWeek isoDayOfWeek ) { switch ( isoDayOfWeek . getDayNumber ( ) ) { case : return Calendar . MONDAY ; case : return Calendar . TUESDAY ; case : return Calendar . WEDNESDAY ; case : return Calendar . THURSDAY ; case : return Calendar . FRIDAY ; case : return Calendar . SATURDAY ; case : return Calendar . SUNDAY ; default : throw new IllegalArgumentException ( "" + isoDayOfWeek ) ; } } public Calendar dayOfWeek ( DayOfWeek dayOfWeek ) { int day = dayOfWeek . getDayNumber ( ) ; Calendar c2 = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; c2 . clear ( ) ; c2 . set ( baseCalendar . get ( Calendar . YEAR ) , baseCalendar . get ( Calendar . MONTH ) , baseCalendar . get ( Calendar . DAY_OF_MONTH ) ) ; int offset = day - isoDayOfWeek ( baseCalendar . get ( Calendar . DAY_OF_WEEK ) ) ; c2 . add ( Calendar . DATE , offset ) ; return c2 ; } public static Calendar startOfYear ( Date referenceDate , TimeZone timeZone ) { Calendar c1 = Calendar . getInstance ( timeZone ) ; c1 . setTime ( referenceDate ) ; Calendar c2 = Calendar . getInstance ( timeZone ) ; c2 . clear ( ) ; c2 . set ( c1 . get ( Calendar . YEAR ) , , ) ; return c2 ; } public static Calendar endOfYear ( Date referenceDate , TimeZone timeZone ) { Calendar c1 = Calendar . getInstance ( timeZone ) ; c1 . setTime ( referenceDate ) ; Calendar c2 = Calendar . getInstance ( ) ; c2 . clear ( ) ; c2 . set ( c1 . get ( Calendar . YEAR ) + , , ) ; c2 . setTimeZone ( timeZone ) ; return c2 ; } public Calendar dayOfYear ( int dayOfMonth , int month ) { Calendar c2 = Calendar . getInstance ( baseCalendar . getTimeZone ( ) ) ; c2 . clear ( ) ; c2 . set ( Calendar . YEAR , baseCalendar . get ( Calendar . YEAR ) ) ; c2 . set ( Calendar . DATE , dayOfMonth ) ; c2 . set ( Calendar . MONTH , month - ) ; return c2 ; } public static Calendar monthOfYear ( Date referenceDate , int month , TimeZone timeZone ) { Calendar c1 = Calendar . getInstance ( timeZone ) ; c1 . setTime ( referenceDate ) ; Calendar c2 = Calendar . getInstance ( timeZone ) ; c2 . clear ( ) ; c2 . set ( c1 . get ( Calendar . YEAR ) , month - , ) ; return c2 ; } } package org . oddjob . schedules ; import java . util . Date ; import org . oddjob . arooa . utils . DateHelper ; public class IntervalTo extends IntervalBase implements ScheduleResult { private static final long serialVersionUID = ; public IntervalTo ( Date on ) { super ( on ) ; } public IntervalTo ( Date from , Date upTo ) { super ( from . getTime ( ) , upTo . getTime ( ) - ) ; } public IntervalTo ( Interval interval ) { super ( interval . getFromDate ( ) . getTime ( ) , interval . getToDate ( ) . getTime ( ) - ) ; } public Date getToDate ( ) { return new Date ( getEndDate ( ) . getTime ( ) + ) ; } public Interval limit ( Interval limit ) { if ( limit == null ) { return null ; } if ( limit . getFromDate ( ) . compareTo ( this . getFromDate ( ) ) < ) { return null ; } if ( limit . getFromDate ( ) . compareTo ( this . getEndDate ( ) ) > ) { return null ; } Date newStart ; if ( this . getFromDate ( ) . compareTo ( limit . getFromDate ( ) ) < ) { newStart = limit . getFromDate ( ) ; } else { newStart = this . getFromDate ( ) ; } return new IntervalTo ( newStart , limit . getToDate ( ) ) ; } public int hashCode ( ) { return getFromDate ( ) . hashCode ( ) + getToDate ( ) . hashCode ( ) ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Interval ) ) { return false ; } if ( other instanceof ScheduleResult && ! getUseNext ( ) . equals ( ( ( ScheduleResult ) other ) . getUseNext ( ) ) ) { return false ; } else { Interval interval = ( Interval ) other ; return this . getToDate ( ) . equals ( interval . getToDate ( ) ) && this . getFromDate ( ) . equals ( interval . getFromDate ( ) ) ; } } public String toString ( ) { if ( getFromDate ( ) . equals ( getEndDate ( ) ) ) { return "" + DateHelper . formatDateTimeInteligently ( getFromDate ( ) ) ; } else { return DateHelper . formatDateTimeInteligently ( getFromDate ( ) ) + "" + DateHelper . formatDateTimeInteligently ( getToDate ( ) ) ; } } @ Override public Date getUseNext ( ) { return getToDate ( ) ; } } package org . oddjob . schedules ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import org . apache . log4j . Logger ; import org . oddjob . schedules . schedules . ParentChildSchedule ; abstract public class ConstrainedSchedule extends AbstractSchedule { private static final long serialVersionUID = ; private static Logger logger = Logger . getLogger ( ConstrainedSchedule . class ) ; abstract protected Calendar fromCalendar ( Date referenceDate , TimeZone timeZone ) ; abstract protected Calendar toCalendar ( Date referenceDate , TimeZone timeZone ) ; protected abstract CalendarUnit intervalBetween ( ) ; protected final Interval nextInterval ( ScheduleContext context ) { Calendar fromCal = fromCalendar ( context . getDate ( ) , context . getTimeZone ( ) ) ; Calendar toCal = toCalendar ( context . getDate ( ) , context . getTimeZone ( ) ) ; Calendar nowCal = Calendar . getInstance ( context . getTimeZone ( ) ) ; nowCal . setTime ( context . getDate ( ) ) ; if ( toCal . before ( fromCal ) ) { if ( nowCal . before ( toCal ) ) { fromCal = shiftFromCalendar ( fromCal , - ) ; } } else { if ( nowCal . compareTo ( toCal ) >= ) { fromCal = shiftFromCalendar ( fromCal , ) ; } } if ( nowCal . compareTo ( toCal ) >= ) { toCal = shiftToCalendar ( toCal , ) ; } return new SimpleInterval ( fromCal . getTime ( ) , toCal . getTime ( ) ) ; } protected final Interval lastInterval ( ScheduleContext context ) { Calendar fromCal = fromCalendar ( context . getDate ( ) , context . getTimeZone ( ) ) ; Calendar toCal = toCalendar ( context . getDate ( ) , context . getTimeZone ( ) ) ; Calendar nowCal = Calendar . getInstance ( context . getTimeZone ( ) ) ; nowCal . setTime ( context . getDate ( ) ) ; if ( toCal . before ( fromCal ) ) { if ( nowCal . before ( toCal ) ) { fromCal = shiftFromCalendar ( fromCal , - ) ; } else { fromCal = shiftFromCalendar ( fromCal , - ) ; } } else { if ( nowCal . before ( toCal ) ) { fromCal = shiftFromCalendar ( fromCal , - ) ; } } if ( nowCal . before ( toCal ) ) { toCal = shiftToCalendar ( toCal , - ) ; } return new SimpleInterval ( fromCal . getTime ( ) , toCal . getTime ( ) ) ; } protected Calendar shiftFromCalendar ( Calendar calendar , int intervals ) { calendar = shiftCalendar ( calendar , intervals ) ; return fromCalendar ( calendar . getTime ( ) , calendar . getTimeZone ( ) ) ; } protected Calendar shiftToCalendar ( Calendar calendar , int intervals ) { calendar = shiftCalendar ( calendar , intervals ) ; calendar . add ( Calendar . MILLISECOND , - ) ; return toCalendar ( calendar . getTime ( ) , calendar . getTimeZone ( ) ) ; } private Calendar shiftCalendar ( Calendar calendar , int intervals ) { CalendarUnit unit = intervalBetween ( ) ; calendar . add ( unit . getField ( ) , intervals * unit . getValue ( ) ) ; return calendar ; } public ScheduleResult nextDue ( ScheduleContext context ) { Date now = context . getDate ( ) ; if ( now == null ) { return null ; } ParentChildSchedule parentChild = new ParentChildSchedule ( new Schedule ( ) { public ScheduleResult nextDue ( ScheduleContext context ) { return new SimpleScheduleResult ( nextInterval ( context ) ) ; } } , getRefinement ( ) ) ; ScheduleResult nextResult = parentChild . nextDue ( context ) ; if ( nextResult == null ) { return null ; } if ( now . before ( nextResult . getFromDate ( ) ) ) { parentChild = new ParentChildSchedule ( new Schedule ( ) { public ScheduleResult nextDue ( ScheduleContext context ) { return new SimpleScheduleResult ( lastInterval ( context ) ) ; } } , getRefinement ( ) ) ; ScheduleResult previous = parentChild . nextDue ( context ) ; if ( previous != null && now . before ( previous . getToDate ( ) ) ) { nextResult = previous ; } } logger . debug ( ConstrainedSchedule . this + "" + now + "" + nextResult ) ; return nextResult ; } public abstract String toString ( ) ; } package org . oddjob . schedules ; import java . io . Serializable ; abstract public class AbstractSchedule implements Serializable , RefineableSchedule { private static final long serialVersionUID = ; private Schedule childSchedule ; public void setRefinement ( Schedule childSchedule ) { this . childSchedule = childSchedule ; } public Schedule getRefinement ( ) { return childSchedule ; } } package org . oddjob . schedules ; import java . io . Serializable ; import java . util . Date ; import org . oddjob . arooa . utils . DateHelper ; public class SimpleScheduleResult implements ScheduleResult , Serializable { private static final long serialVersionUID = ; private final Interval interval ; private final Date useNext ; public SimpleScheduleResult ( Interval interval ) { this ( interval , interval . getToDate ( ) ) ; } public SimpleScheduleResult ( Interval interval , Date useNext ) { if ( interval == null ) { throw new NullPointerException ( "" ) ; } this . interval = new SimpleInterval ( interval ) ; this . useNext = useNext ; } @ Override public Date getFromDate ( ) { return interval . getFromDate ( ) ; } @ Override public Date getToDate ( ) { return interval . getToDate ( ) ; } @ Override public Date getUseNext ( ) { return useNext ; } public int hashCode ( ) { return interval . hashCode ( ) ; } public boolean equals ( Object other ) { if ( other == null ) { return false ; } if ( ! ( other instanceof ScheduleResult ) ) { return other . equals ( this ) ; } ScheduleResult result = ( ScheduleResult ) other ; if ( useNext == null ) { if ( result . getUseNext ( ) != null ) { return false ; } } else { if ( ! useNext . equals ( result . getUseNext ( ) ) ) { return false ; } } return interval . getToDate ( ) . equals ( result . getToDate ( ) ) && interval . getFromDate ( ) . equals ( result . getFromDate ( ) ) ; } @ Override public String toString ( ) { String useNextText = "" ; if ( ! interval . getToDate ( ) . equals ( useNext ) ) { useNextText = "" + DateHelper . formatDateTimeInteligently ( useNext ) ; } return interval . toString ( ) + useNextText ; } } package org . oddjob . schedules ; import java . util . ArrayList ; import java . util . Date ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . TimeZone ; import org . apache . log4j . Logger ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . NowSchedule ; import org . oddjob . util . Clock ; public class ScheduleCalculator { private static final Logger logger = Logger . getLogger ( ScheduleCalculator . class ) ; private final Schedule normalSchedule ; private final Schedule retrySchedule ; private Schedule currentSchedule ; private ScheduleResult currentInterval ; private ScheduleResult normalInterval ; private boolean initialised ; private final List < ScheduleListener > listeners = new ArrayList < ScheduleListener > ( ) ; private ScheduleContext normalContext ; private ScheduleContext retryContext ; private final TimeZone timeZone ; private final Clock clock ; public ScheduleCalculator ( Clock clock , Schedule schedule ) { this ( clock , schedule , null , null ) ; } public ScheduleCalculator ( Clock clock , Schedule schedule , TimeZone timeZone ) { this ( clock , schedule , null , timeZone ) ; } public ScheduleCalculator ( Clock clock , Schedule schedule , Schedule retry ) { this ( clock , schedule , retry , null ) ; } public ScheduleCalculator ( Clock clock , Schedule schedule , Schedule retry , TimeZone timeZone ) { if ( clock == null ) { throw new IllegalStateException ( "" ) ; } if ( schedule == null ) { schedule = defaultSchedule ( ) ; } this . clock = clock ; this . normalSchedule = schedule ; this . retrySchedule = retry ; this . timeZone = timeZone ; } public Schedule getSchedule ( ) { return this . normalSchedule ; } public Schedule getRetry ( ) { return this . retrySchedule ; } public void initialise ( ) { initialise ( null , new HashMap < Object , Object > ( ) ) ; } synchronized public void initialise ( ScheduleResult lastComplete , Map < Object , Object > contextData ) { if ( initialised ) { throw new IllegalStateException ( "" ) ; } Date nowTime = clock . getDate ( ) ; logger . debug ( "" + nowTime + "" + lastComplete + "" ) ; currentSchedule ( normalSchedule ) ; if ( lastComplete != null && lastComplete . getUseNext ( ) != null ) { Date useTime = lastComplete . getUseNext ( ) ; normalContext = new ScheduleContext ( useTime , timeZone , contextData ) ; currentInterval = currentSchedule . nextDue ( normalContext ) ; normalInterval = currentInterval ; fireInitialised ( ) ; } else { logger . debug ( "" ) ; normalContext = new ScheduleContext ( nowTime , timeZone , contextData ) ; currentInterval = currentSchedule . nextDue ( normalContext ) ; normalInterval = currentInterval ; fireInitialised ( ) ; } initialised = true ; } private void currentSchedule ( Schedule schedule ) { this . currentSchedule = schedule ; } synchronized public String getCurrentScheduleType ( ) { if ( currentSchedule == normalSchedule ) { return "" ; } else if ( currentSchedule == retrySchedule ) { return "" ; } else { return "" ; } } synchronized public void calculateComplete ( ) { logger . debug ( "" ) ; currentSchedule ( normalSchedule ) ; ScheduleResult lastComplete = normalInterval ; normalContext = normalContext . move ( currentInterval . getToDate ( ) ) ; currentInterval = currentSchedule . nextDue ( normalContext ) ; normalInterval = currentInterval ; fireComplete ( lastComplete ) ; } synchronized public void calculateRetry ( ) { logger . debug ( "" ) ; if ( currentSchedule == normalSchedule ) { if ( retrySchedule != null ) { logger . debug ( "" ) ; normalInterval = currentInterval ; currentSchedule ( retrySchedule ) ; retryContext = new ScheduleContext ( clock . getDate ( ) , timeZone ) ; if ( ! new IntervalHelper ( normalInterval ) . isPoint ( ) ) { retryContext = retryContext . spawn ( normalInterval ) ; } retryAndFail ( ) ; } else { normalContext = normalContext . move ( normalInterval . getToDate ( ) ) ; currentInterval = normalSchedule . nextDue ( normalContext ) ; normalInterval = currentInterval ; fireFailed ( ) ; } } else { retryContext = retryContext . move ( currentInterval . getToDate ( ) ) ; retryAndFail ( ) ; } logger . debug ( "" + currentInterval + "" ) ; } private void retryAndFail ( ) { currentInterval = retrySchedule . nextDue ( retryContext ) ; if ( currentInterval != null ) { Interval retryInterval = currentInterval ; IntervalHelper helper = new IntervalHelper ( retryInterval ) ; if ( ! helper . isPoint ( ) ) { retryInterval = helper . limit ( currentInterval ) ; } fireRetry ( retryInterval ) ; } else { currentSchedule ( normalSchedule ) ; normalContext = normalContext . move ( normalInterval . getUseNext ( ) ) ; currentInterval = normalSchedule . nextDue ( normalContext ) ; normalInterval = currentInterval ; logger . debug ( "" + currentInterval + "" ) ; fireFailed ( ) ; } } synchronized public void addScheduleListener ( ScheduleListener l ) { listeners . add ( l ) ; } synchronized public void removeScheduleListener ( ScheduleListener l ) { listeners . remove ( l ) ; } protected void fireInitialised ( ) { Date scheduleDate ; if ( normalInterval == null ) { scheduleDate = null ; } else { scheduleDate = normalInterval . getFromDate ( ) ; } for ( Iterator < ScheduleListener > it = listeners . iterator ( ) ; it . hasNext ( ) ; ) { ScheduleListener l = ( ScheduleListener ) it . next ( ) ; l . initialised ( scheduleDate ) ; } } protected void fireComplete ( ScheduleResult lastComplete ) { Date scheduleDate ; if ( normalInterval == null ) { scheduleDate = null ; } else { scheduleDate = normalInterval . getFromDate ( ) ; } for ( Iterator < ScheduleListener > it = listeners . iterator ( ) ; it . hasNext ( ) ; ) { ScheduleListener l = ( ScheduleListener ) it . next ( ) ; l . complete ( scheduleDate , lastComplete ) ; } } protected void fireRetry ( Interval limits ) { if ( normalInterval == null ) { throw new IllegalStateException ( "" ) ; } if ( limits == null ) { throw new IllegalStateException ( "" ) ; } Date scheduleDate = normalInterval . getFromDate ( ) ; Date retryDate = limits . getToDate ( ) ; for ( Iterator < ScheduleListener > it = listeners . iterator ( ) ; it . hasNext ( ) ; ) { ScheduleListener l = ( ScheduleListener ) it . next ( ) ; l . retry ( scheduleDate , retryDate ) ; } } protected void fireFailed ( ) { Date scheduleDate ; if ( normalInterval == null ) { scheduleDate = null ; } else { scheduleDate = normalInterval . getFromDate ( ) ; } for ( Iterator < ScheduleListener > it = listeners . iterator ( ) ; it . hasNext ( ) ; ) { ScheduleListener l = ( ScheduleListener ) it . next ( ) ; l . failed ( scheduleDate ) ; } } private Schedule defaultSchedule ( ) { CountSchedule count = new CountSchedule ( ) ; count . setCount ( ) ; count . setRefinement ( new NowSchedule ( ) ) ; return count ; } } package org . oddjob . schedules ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Date ; import java . util . List ; import org . apache . log4j . Logger ; final public class ScheduleList implements Serializable , Schedule { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( ScheduleList . class ) ; private final List < Schedule > schedules = new ArrayList < Schedule > ( ) ; public void setSchedules ( int index , Schedule schedule ) { if ( schedule == null ) { schedules . remove ( index ) ; } else { schedules . add ( index , schedule ) ; } } public Schedule getSchedules ( int index ) { return schedules . get ( index ) ; } public void setSchedules ( Schedule [ ] schedules ) { this . schedules . clear ( ) ; this . schedules . addAll ( Arrays . asList ( schedules ) ) ; } public Schedule [ ] getSchedules ( ) { return this . schedules . toArray ( new Schedule [ ] ) ; } public int size ( ) { return schedules . size ( ) ; } public ScheduleResult nextDue ( ScheduleContext context ) { Date now = context . getDate ( ) ; logger . debug ( this + "" + now ) ; if ( schedules == null || schedules . size ( ) == ) { return null ; } ScheduleResult candidate = null ; int i = ; for ( Schedule schedule : schedules ) { logger . debug ( this + "" + i ++ + "" + schedule + "" ) ; ScheduleResult nextDue = schedule . nextDue ( context ) ; if ( nextDue != null ) { if ( candidate == null || new IntervalHelper ( nextDue ) . isBefore ( candidate ) ) { candidate = nextDue ; } } } logger . debug ( this + "" + candidate ) ; return candidate ; } public String toString ( ) { return "" + size ( ) ; } } package org . oddjob . schedules ; import java . io . Serializable ; import java . util . Date ; import org . oddjob . arooa . utils . DateHelper ; public class SimpleInterval implements Interval , Serializable { private static final long serialVersionUID = ; private final Date fromDate ; private final Date toDate ; public SimpleInterval ( Date on ) { this ( on . getTime ( ) , on . getTime ( ) + ) ; } public SimpleInterval ( Date from , Date to ) { this ( from . getTime ( ) , to . getTime ( ) ) ; } public SimpleInterval ( long fromTime , long toTime ) { fromDate = new Date ( fromTime ) ; toDate = new Date ( toTime ) ; if ( toTime <= fromTime ) { throw new IllegalStateException ( "" + this + "" ) ; } } public SimpleInterval ( Interval other ) { this ( other . getFromDate ( ) . getTime ( ) , other . getToDate ( ) . getTime ( ) ) ; } @ Override public Date getFromDate ( ) { return fromDate ; } @ Override public Date getToDate ( ) { return toDate ; } public int hashCode ( ) { return fromDate . hashCode ( ) + toDate . hashCode ( ) ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Interval ) ) { return false ; } Interval interval = ( Interval ) other ; return this . toDate . equals ( interval . getToDate ( ) ) && this . fromDate . equals ( interval . getFromDate ( ) ) ; } public String toString ( ) { if ( toDate . getTime ( ) - fromDate . getTime ( ) == ) { return "" + DateHelper . formatDateTimeInteligently ( getFromDate ( ) ) ; } else { return DateHelper . formatDateTimeInteligently ( getFromDate ( ) ) + "" + DateHelper . formatDateTimeInteligently ( getToDate ( ) ) ; } } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . schedules . CalendarUnit ; import org . oddjob . schedules . CalendarUtils ; import org . oddjob . schedules . ConstrainedSchedule ; import org . oddjob . schedules . units . DayOfMonth ; import org . oddjob . schedules . units . DayOfWeek ; import org . oddjob . schedules . units . WeekOfMonth ; final public class MonthlySchedule extends ConstrainedSchedule implements Serializable { private static final long serialVersionUID = ; private DayOfMonth fromDay ; private DayOfMonth toDay ; private DayOfWeek fromDayOfWeek ; private DayOfWeek toDayOfWeek ; private WeekOfMonth fromWeek ; private WeekOfMonth toWeek ; @ ArooaAttribute public void setFromDay ( DayOfMonth day ) { fromDay = day ; } public DayOfMonth getFromDay ( ) { return fromDay ; } @ ArooaAttribute public void setToDay ( DayOfMonth to ) { this . toDay = to ; } public DayOfMonth getToDay ( ) { return toDay ; } @ ArooaAttribute public void setOnDay ( DayOfMonth on ) { this . setFromDay ( on ) ; this . setToDay ( on ) ; } public DayOfWeek getFromDayOfWeek ( ) { return fromDayOfWeek ; } @ ArooaAttribute public void setFromDayOfWeek ( DayOfWeek fromDayOfWeek ) { this . fromDayOfWeek = fromDayOfWeek ; } public DayOfWeek getToDayOfWeek ( ) { return toDayOfWeek ; } @ ArooaAttribute public void setToDayOfWeek ( DayOfWeek toDayOfWeek ) { this . toDayOfWeek = toDayOfWeek ; } @ ArooaAttribute public void setOnDayOfWeek ( DayOfWeek onDayOfWeek ) { this . setFromDayOfWeek ( onDayOfWeek ) ; this . setToDayOfWeek ( onDayOfWeek ) ; } public WeekOfMonth getFromWeek ( ) { return fromWeek ; } @ ArooaAttribute public void setFromWeek ( WeekOfMonth fromWeek ) { this . fromWeek = fromWeek ; } public WeekOfMonth getToWeek ( ) { return toWeek ; } @ ArooaAttribute public void setToWeek ( WeekOfMonth toWeek ) { this . toWeek = toWeek ; } @ ArooaAttribute public void setInWeek ( WeekOfMonth inWeek ) { this . setFromWeek ( inWeek ) ; this . setToWeek ( inWeek ) ; } @ Override protected CalendarUnit intervalBetween ( ) { return new CalendarUnit ( Calendar . MONTH , ) ; } protected Calendar fromCalendar ( Date referenceDate , TimeZone timeZone ) { CalendarUtils helper = new CalendarUtils ( referenceDate , timeZone ) ; if ( fromDay != null ) { return helper . dayOfMonth ( fromDay ) ; } else if ( fromWeek != null ) { if ( fromDayOfWeek == null ) { return helper . startOfWeekOfMonth ( fromWeek ) ; } else { return helper . dayOfWeekInMonth ( fromDayOfWeek , fromWeek ) ; } } else { return helper . startOfMonth ( ) ; } } protected Calendar toCalendar ( Date referenceDate , TimeZone timeZone ) { CalendarUtils helper = new CalendarUtils ( referenceDate , timeZone ) ; if ( toDay != null ) { Calendar cal = helper . dayOfMonth ( toDay ) ; CalendarUtils . setEndOfDay ( cal ) ; return cal ; } else if ( toWeek != null ) { if ( toDayOfWeek == null ) { return helper . startOfWeekOfMonth ( toWeek ) ; } else { Calendar cal = helper . dayOfWeekInMonth ( toDayOfWeek , toWeek ) ; CalendarUtils . setEndOfDay ( cal ) ; return cal ; } } else { return helper . endOfMonth ( ) ; } } @ Override protected Calendar shiftFromCalendar ( Calendar calendar , int intervals ) { calendar = super . shiftFromCalendar ( calendar , intervals ) ; if ( fromWeek == null ) { return calendar ; } else { CalendarUtils helper = new CalendarUtils ( calendar . getTime ( ) , calendar . getTimeZone ( ) ) ; if ( fromDayOfWeek == null ) { return helper . startOfWeekOfMonth ( fromWeek ) ; } else { return helper . dayOfWeekInMonth ( fromDayOfWeek , fromWeek ) ; } } } @ Override protected Calendar shiftToCalendar ( Calendar calendar , int intervals ) { calendar = super . shiftToCalendar ( calendar , intervals ) ; if ( toWeek == null ) { return calendar ; } else { CalendarUtils helper = new CalendarUtils ( calendar . getTime ( ) , calendar . getTimeZone ( ) ) ; if ( toDayOfWeek == null ) { return helper . startOfWeekOfMonth ( toWeek ) ; } else { Calendar cal = helper . dayOfWeekInMonth ( toDayOfWeek , toWeek ) ; CalendarUtils . setEndOfDay ( cal ) ; return cal ; } } } public String toString ( ) { String from = null ; if ( fromDay != null ) { from = "" + fromDay . toString ( ) ; } else if ( fromWeek != null ) { if ( fromDayOfWeek == null ) { from = "" + fromWeek . toString ( ) ; } else { from = "" + fromWeek . toString ( ) + "" + fromDayOfWeek . toString ( ) ; } } else { from = "" ; } String to = null ; if ( toDay != null ) { to = "" + toDay . toString ( ) ; } else if ( toWeek != null ) { if ( toDayOfWeek == null ) { to = "" + toWeek . toString ( ) ; } else { to = "" + toWeek . toString ( ) + "" + toDayOfWeek . toString ( ) ; } } else { to = "" ; } StringBuilder description = new StringBuilder ( ) ; if ( from . equals ( to ) ) { description . append ( "" ) ; description . append ( from ) ; } else { description . append ( "" ) ; description . append ( from ) ; description . append ( "" ) ; description . append ( to ) ; } if ( getRefinement ( ) != null ) { description . append ( "" ) ; description . append ( getRefinement ( ) . toString ( ) ) ; } return "" + description . toString ( ) ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . text . ParseException ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import org . apache . log4j . Logger ; import org . oddjob . OddjobException ; import org . oddjob . arooa . utils . SpringSafeCalendar ; import org . oddjob . arooa . utils . TimeParser ; import org . oddjob . schedules . AbstractSchedule ; import org . oddjob . schedules . CalendarUnit ; import org . oddjob . schedules . ConstrainedSchedule ; import org . oddjob . schedules . DateUtils ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleInterval ; import org . oddjob . schedules . SimpleScheduleResult ; import org . oddjob . scheduling . Timer ; final public class TimeSchedule extends AbstractSchedule implements Serializable { private static Logger logger = Logger . getLogger ( ConstrainedSchedule . class ) ; private static final long serialVersionUID = ; private String from ; private String to ; private String toLast ; public void setFrom ( String from ) { this . from = from ; } public String getFrom ( ) { return from ; } public void setTo ( String to ) { this . to = to ; } public String getTo ( ) { return to ; } public void setAt ( String at ) { this . setFrom ( at ) ; this . setTo ( at ) ; } public String getToLast ( ) { return toLast ; } public void setToLast ( String toLast ) { this . toLast = toLast ; } protected CalendarUnit intervalBetween ( ) { return new CalendarUnit ( Calendar . DATE , ) ; } static Date parseTime ( String textField , Date referenceDate , TimeZone timeZone , String fieldName ) { TimeParser timeFormatter = new TimeParser ( new SpringSafeCalendar ( referenceDate , timeZone ) ) ; try { Date now = timeFormatter . parse ( textField ) ; return now ; } catch ( ParseException e ) { throw new OddjobException ( "" + fieldName + "" + textField + "" ) ; } } protected Calendar fromCalendar ( ScheduleContext context ) { TimeZone timeZone = context . getTimeZone ( ) ; Calendar fromCal = Calendar . getInstance ( timeZone ) ; Interval parentInterval = context . getParentInterval ( ) ; if ( from == null ) { if ( parentInterval == null ) { fromCal . setTime ( Interval . START_OF_TIME ) ; } else { fromCal . setTime ( DateUtils . startOfDay ( parentInterval . getFromDate ( ) , timeZone ) ) ; } } else { if ( parentInterval == null ) { fromCal . setTime ( parseTime ( from , context . getDate ( ) , timeZone , "" ) ) ; } else { fromCal . setTime ( parseTime ( from , parentInterval . getFromDate ( ) , timeZone , "" ) ) ; } } return fromCal ; } protected Calendar toCalendar ( ScheduleContext context ) { TimeZone timeZone = context . getTimeZone ( ) ; Calendar toCal = Calendar . getInstance ( timeZone ) ; Interval parentInterval = context . getParentInterval ( ) ; if ( toLast != null ) { if ( parentInterval == null ) { toCal . setTime ( parseTime ( to , context . getDate ( ) , timeZone , "" ) ) ; } else { toCal . setTime ( parseTime ( to , DateUtils . oneMillisBefore ( parentInterval . getToDate ( ) ) , timeZone , "" ) ) ; } } if ( to != null ) { if ( parentInterval == null ) { toCal . setTime ( parseTime ( to , context . getDate ( ) , timeZone , "" ) ) ; } else { toCal . setTime ( parseTime ( to , parentInterval . getFromDate ( ) , timeZone , "" ) ) ; } } else { if ( parentInterval == null ) { toCal . setTime ( Interval . END_OF_TIME ) ; } else { toCal . setTime ( DateUtils . endOfDay ( DateUtils . oneMillisBefore ( parentInterval . getToDate ( ) ) , timeZone ) ) ; } ; } return toCal ; } protected Calendar nowCalendar ( ScheduleContext context ) { Calendar nowCal = Calendar . getInstance ( context . getTimeZone ( ) ) ; nowCal . setTime ( context . getDate ( ) ) ; Interval parentInterval = context . getParentInterval ( ) ; if ( parentInterval != null ) { if ( parentInterval . getToDate ( ) . compareTo ( context . getDate ( ) ) <= ) { nowCal . setTime ( DateUtils . oneMillisBefore ( parentInterval . getToDate ( ) ) ) ; } else if ( parentInterval . getFromDate ( ) . compareTo ( context . getDate ( ) ) > ) { nowCal . setTime ( parentInterval . getFromDate ( ) ) ; } } return nowCal ; } protected final Interval nextInterval ( ScheduleContext context ) { Calendar fromCal = fromCalendar ( context ) ; Calendar toCal = toCalendar ( context ) ; if ( fromCal . getTime ( ) . equals ( toCal . getTime ( ) ) ) { toCal . add ( Calendar . MILLISECOND , ) ; } Calendar nowCal = nowCalendar ( context ) ; if ( fromCal . after ( toCal ) ) { toCal = shiftFromCalendar ( toCal , ) ; } if ( nowCal . compareTo ( toCal ) >= ) { return null ; } return new SimpleInterval ( fromCal . getTime ( ) , toCal . getTime ( ) ) ; } protected final Interval lastInterval ( ScheduleContext context ) { Calendar fromCal = fromCalendar ( context ) ; Calendar toCal = toCalendar ( context ) ; if ( fromCal . getTime ( ) . equals ( toCal . getTime ( ) ) ) { toCal . add ( Calendar . MILLISECOND , ) ; } Calendar nowCal = nowCalendar ( context ) ; if ( fromCal . after ( toCal ) ) { fromCal = shiftFromCalendar ( fromCal , - ) ; } if ( nowCal . compareTo ( toCal ) < ) { return null ; } return new SimpleInterval ( fromCal . getTime ( ) , toCal . getTime ( ) ) ; } protected Calendar shiftFromCalendar ( Calendar calendar , int intervals ) { if ( calendar . getTime ( ) . equals ( Interval . START_OF_TIME ) ) { return calendar ; } else { return shiftCalendar ( calendar , intervals ) ; } } protected Calendar shiftToCalendar ( Calendar calendar , int intervals ) { if ( calendar . getTime ( ) . equals ( Interval . END_OF_TIME ) ) { return calendar ; } else { return shiftCalendar ( calendar , intervals ) ; } } private Calendar shiftCalendar ( Calendar calendar , int intervals ) { CalendarUnit unit = intervalBetween ( ) ; calendar . add ( unit . getField ( ) , intervals * unit . getValue ( ) ) ; return calendar ; } public ScheduleResult nextDue ( ScheduleContext context ) { Date now = context . getDate ( ) ; if ( now == null ) { return null ; } final Interval thisNextInterval = nextInterval ( context ) ; Interval thisInterval = thisNextInterval ; ScheduleResult nextResult = null ; if ( thisNextInterval != null ) { ParentChildSchedule parentChild = new ParentChildSchedule ( new Schedule ( ) { public ScheduleResult nextDue ( ScheduleContext context ) { return new SimpleScheduleResult ( thisNextInterval ) ; } } , getRefinement ( ) ) ; nextResult = parentChild . nextDue ( context ) ; } if ( ( nextResult == null || now . before ( nextResult . getFromDate ( ) ) ) && ( to != null && getRefinement ( ) != null ) ) { final Interval thisPreviousInterval = lastInterval ( context ) ; if ( thisPreviousInterval != null ) { ParentChildSchedule parentChild = new ParentChildSchedule ( new Schedule ( ) { public ScheduleResult nextDue ( ScheduleContext context ) { return new SimpleScheduleResult ( thisPreviousInterval ) ; } } , getRefinement ( ) ) ; ScheduleResult previous = parentChild . nextDue ( context ) ; if ( previous != null && now . before ( previous . getToDate ( ) ) ) { nextResult = previous ; thisInterval = thisPreviousInterval ; } } } if ( nextResult == null ) { return null ; } if ( ! thisInterval . getToDate ( ) . after ( nextResult . getToDate ( ) ) ) { nextResult = new SimpleScheduleResult ( nextResult , null ) ; } logger . debug ( this + "" + now + "" + nextResult ) ; return nextResult ; } public String toString ( ) { String from ; if ( this . from == null ) { from = null ; } else { from = this . from ; } String to ; if ( this . toLast != null ) { to = "" + this . toLast ; } if ( this . to != null ) { to = this . to ; } else { to = null ; } StringBuilder description = new StringBuilder ( ) ; if ( from != null && from . equals ( to ) ) { description . append ( "" ) ; description . append ( from ) ; } else { if ( from != null ) { description . append ( "" ) ; description . append ( from ) ; } if ( to != null ) { description . append ( "" ) ; description . append ( to ) ; } } if ( getRefinement ( ) != null ) { description . append ( "" ) ; description . append ( getRefinement ( ) . toString ( ) ) ; } return "" + description ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . schedules . CalendarUnit ; import org . oddjob . schedules . CalendarUtils ; import org . oddjob . schedules . ConstrainedSchedule ; import org . oddjob . schedules . units . DayOfWeek ; final public class WeeklySchedule extends ConstrainedSchedule implements Serializable { private static final long serialVersionUID = ; private DayOfWeek from ; private DayOfWeek to ; @ ArooaAttribute public void setFrom ( DayOfWeek from ) { this . from = from ; } public DayOfWeek getFrom ( ) { return from ; } @ ArooaAttribute public void setTo ( DayOfWeek to ) { this . to = to ; } public DayOfWeek getTo ( ) { return to ; } @ ArooaAttribute public void setOn ( DayOfWeek on ) { setFrom ( on ) ; setTo ( on ) ; } @ Override protected CalendarUnit intervalBetween ( ) { return new CalendarUnit ( Calendar . DATE , ) ; } protected Calendar fromCalendar ( Date referenceDate , TimeZone timeZone ) { if ( from == null ) { return CalendarUtils . startOfWeek ( referenceDate , timeZone ) ; } else { return new CalendarUtils ( referenceDate , timeZone ) . dayOfWeek ( from ) ; } } protected Calendar toCalendar ( Date referenceDate , TimeZone timeZone ) { if ( to == null ) { return CalendarUtils . endOfWeek ( referenceDate , timeZone ) ; } else { Calendar cal = new CalendarUtils ( referenceDate , timeZone ) . dayOfWeek ( to ) ; CalendarUtils . setEndOfDay ( cal ) ; return cal ; } } public String toString ( ) { String from ; if ( this . from == null ) { from = "" ; } else { from = this . from . toString ( ) ; } String to ; if ( this . to == null ) { to = "" ; } else { to = this . to . toString ( ) ; } StringBuilder description = new StringBuilder ( ) ; if ( from . equals ( to ) ) { description . append ( "" ) ; description . append ( from ) ; } else { description . append ( "" ) ; description . append ( from ) ; description . append ( "" ) ; description . append ( to ) ; } if ( getRefinement ( ) != null ) { description . append ( "" ) ; description . append ( getRefinement ( ) . toString ( ) ) ; } return "" + description ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . text . ParseException ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import org . oddjob . OddjobException ; import org . oddjob . arooa . utils . SpringSafeCalendar ; import org . oddjob . arooa . utils . TimeParser ; import org . oddjob . schedules . CalendarUnit ; import org . oddjob . schedules . ConstrainedSchedule ; import org . oddjob . schedules . DateUtils ; import org . oddjob . scheduling . Timer ; final public class DailySchedule extends ConstrainedSchedule implements Serializable { private static final long serialVersionUID = ; private String from ; private String to ; public void setFrom ( String from ) { this . from = from ; } public String getFrom ( ) { return from ; } public void setTo ( String to ) { this . to = to ; } public String getTo ( ) { return to ; } public void setAt ( String at ) { this . setFrom ( at ) ; this . setTo ( at ) ; } @ Override protected CalendarUnit intervalBetween ( ) { return new CalendarUnit ( Calendar . DATE , ) ; } static Date parseTime ( String textField , Date referenceDate , TimeZone timeZone , String fieldName ) { TimeParser timeFormatter = new TimeParser ( new SpringSafeCalendar ( referenceDate , timeZone ) ) ; try { Date now = timeFormatter . parse ( textField ) ; return now ; } catch ( ParseException e ) { throw new OddjobException ( "" + fieldName + "" + textField + "" ) ; } } protected Calendar fromCalendar ( Date referenceDate , TimeZone timeZone ) { Calendar fromCal = Calendar . getInstance ( timeZone ) ; if ( from == null ) { fromCal . setTime ( DateUtils . startOfDay ( referenceDate , timeZone ) ) ; } else { fromCal . setTime ( parseTime ( from , referenceDate , timeZone , "" ) ) ; } return fromCal ; } protected Calendar toCalendar ( Date referenceDate , TimeZone timeZone ) { Calendar toCal = Calendar . getInstance ( timeZone ) ; if ( to == null ) { toCal . setTime ( DateUtils . endOfDay ( referenceDate , timeZone ) ) ; } else { toCal . setTime ( parseTime ( to , referenceDate , timeZone , "" ) ) ; } Calendar fromCal = fromCalendar ( referenceDate , timeZone ) ; if ( toCal . equals ( fromCal ) ) { toCal . add ( Calendar . MILLISECOND , ) ; } return toCal ; } public String toString ( ) { String from ; if ( this . from == null ) { from = "" ; } else { from = this . from ; } String to ; if ( this . to == null ) { to = "" ; } else { to = this . to ; } StringBuilder description = new StringBuilder ( ) ; if ( from . equals ( to ) ) { description . append ( "" ) ; description . append ( from ) ; } else { description . append ( "" ) ; description . append ( from ) ; description . append ( "" ) ; description . append ( to ) ; } if ( getRefinement ( ) != null ) { description . append ( "" ) ; description . append ( getRefinement ( ) . toString ( ) ) ; } return "" + description ; } } package org . oddjob . schedules . schedules ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalHelper ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleType ; import org . oddjob . schedules . SimpleScheduleResult ; public class NowSchedule implements Schedule { public ScheduleResult nextDue ( ScheduleContext context ) { IntervalTo now = new IntervalTo ( context . getDate ( ) ) ; Interval parentInterval = context . getParentInterval ( ) ; if ( parentInterval == null ) { return now ; } Interval limited = new IntervalHelper ( parentInterval ) . limit ( now ) ; if ( limited == null ) { return null ; } else { return new SimpleScheduleResult ( limited ) ; } } public String toString ( ) { return "" ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . LinkedHashMap ; import java . util . Map ; import org . apache . log4j . Logger ; import org . oddjob . schedules . AbstractSchedule ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleInterval ; final public class CountSchedule extends AbstractSchedule implements Serializable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( CountSchedule . class ) ; private static final String COUNT_KEY = "" ; private int countTo ; private String identifier ; public CountSchedule ( ) { } public CountSchedule ( int countTo ) { this . countTo = countTo ; } public void setCount ( int count ) { this . countTo = count ; } public int getCount ( ) { return countTo ; } public String getIdentifier ( ) { return identifier ; } public void setIdentifier ( String key ) { this . identifier = key ; } public ScheduleResult nextDue ( ScheduleContext context ) { if ( context . getDate ( ) == null ) { return null ; } Schedule child = getRefinement ( ) ; if ( child == null ) { child = new NowSchedule ( ) ; } String countKey = COUNT_KEY ; if ( identifier != null ) { countKey += identifier ; } IntervalCounts storedCount = ( IntervalCounts ) context . getData ( countKey ) ; if ( storedCount == null ) { storedCount = new IntervalCounts ( ) ; context . putData ( countKey , storedCount ) ; } Interval parent = context . getParentInterval ( ) ; int counted = storedCount . retrieve ( parent ) ; logger . debug ( this + "" + counted ) ; ++ counted ; storedCount . store ( parent , counted ) ; if ( counted <= countTo ) { return child . nextDue ( context ) ; } else { return null ; } } public String toString ( ) { return "" + countTo ; } private static class IntervalCounts implements Serializable { private static final long serialVersionUID = ; private final static Interval NULL_INTERVAL = new SimpleInterval ( Interval . START_OF_TIME , Interval . END_OF_TIME ) ; private final Map < Interval , Integer > counts = new LinkedHashMap < Interval , Integer > ( ) ; void store ( Interval interval , int count ) { if ( interval == null ) { interval = NULL_INTERVAL ; } counts . put ( interval , new Integer ( count ) ) ; if ( counts . size ( ) > ) { Interval first = counts . keySet ( ) . iterator ( ) . next ( ) ; counts . remove ( first ) ; } } int retrieve ( Interval interval ) { if ( interval == null ) { interval = NULL_INTERVAL ; } Integer retrieved = counts . get ( interval ) ; if ( retrieved == null ) { return ; } else { return retrieved . intValue ( ) ; } } } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . schedules . AbstractSchedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; final public class OccurrenceSchedule extends AbstractSchedule implements Serializable { private static final long serialVersionUID = ; private final static Logger logger = Logger . getLogger ( OccurrenceSchedule . class ) ; private int occurrence ; public void setOccurrence ( String occurrence ) { this . occurrence = Integer . parseInt ( occurrence ) ; } public String getOccurrence ( ) { return Integer . toString ( occurrence ) ; } public ScheduleResult nextDue ( ScheduleContext context ) { Date now = context . getDate ( ) ; if ( getRefinement ( ) == null ) { throw new IllegalStateException ( "" ) ; } logger . debug ( this + "" + now ) ; Date use = now ; if ( context . getParentInterval ( ) != null ) { use = context . getParentInterval ( ) . getFromDate ( ) ; } ScheduleResult candidate = null ; for ( int i = ; i < occurrence && use != null ; ++ i ) { logger . debug ( this + "" + use ) ; candidate = getRefinement ( ) . nextDue ( context . move ( use ) ) ; if ( candidate != null ) { use = candidate . getToDate ( ) ; } else { use = null ; } } return candidate ; } public String toString ( ) { return "" + getOccurrence ( ) ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . Calendar ; import java . util . Date ; import java . util . GregorianCalendar ; import org . oddjob . schedules . AbstractSchedule ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleScheduleResult ; public class DayBeforeSchedule extends AbstractSchedule implements Serializable { private static final long serialVersionUID = ; public ScheduleResult nextDue ( ScheduleContext context ) { Date use = null ; Date useNext = null ; Interval interval = context . getParentInterval ( ) ; if ( interval != null ) { use = interval . getFromDate ( ) ; useNext = interval . getToDate ( ) ; } else { use = context . getDate ( ) ; useNext = use ; } if ( use == null ) { return null ; } Calendar useCal = Calendar . getInstance ( context . getTimeZone ( ) ) ; useCal . setTime ( use ) ; Calendar startCal = Calendar . getInstance ( context . getTimeZone ( ) ) ; startCal . clear ( ) ; startCal . set ( useCal . get ( Calendar . YEAR ) , useCal . get ( Calendar . MONTH ) , useCal . get ( Calendar . DATE ) - ) ; Calendar endCal = new GregorianCalendar ( ) ; endCal . clear ( ) ; endCal . set ( useCal . get ( Calendar . YEAR ) , useCal . get ( Calendar . MONTH ) , useCal . get ( Calendar . DATE ) ) ; Interval newInterval = new IntervalTo ( startCal . getTime ( ) , endCal . getTime ( ) ) ; Interval result ; if ( getRefinement ( ) != null ) { ScheduleContext shiftedContext = context . spawn ( startCal . getTime ( ) , newInterval ) ; result = getRefinement ( ) . nextDue ( shiftedContext ) ; } else { result = newInterval ; } if ( result == null ) { return null ; } return new SimpleScheduleResult ( result , useNext ) ; } public String toString ( ) { String description = "" ; if ( getRefinement ( ) != null ) { description = "" + getRefinement ( ) ; } return "" + description ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . schedules . AbstractSchedule ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleScheduleResult ; final public class AfterSchedule extends AbstractSchedule implements Serializable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( AfterSchedule . class ) ; private Schedule schedule ; public ScheduleResult nextDue ( ScheduleContext context ) { if ( schedule == null ) { throw new IllegalStateException ( "" ) ; } Date now = context . getDate ( ) ; logger . debug ( this + "" + now ) ; ScheduleResult next = schedule . nextDue ( context ) ; if ( next == null ) { return null ; } Date from = next . getToDate ( ) ; ScheduleResult following = schedule . nextDue ( context . move ( from ) ) ; Date to ; if ( following == null ) { to = Interval . END_OF_TIME ; } else { to = following . getToDate ( ) ; } IntervalTo afterInterval = new IntervalTo ( from , to ) ; Schedule refinement = getRefinement ( ) ; Interval result ; if ( refinement == null ) { result = afterInterval ; } else { result = refinement . nextDue ( context . spawn ( afterInterval . getFromDate ( ) , afterInterval ) ) ; } if ( result == null ) { return null ; } return new SimpleScheduleResult ( result , from ) ; } public Schedule getSchedule ( ) { return schedule ; } public void setSchedule ( Schedule schedule ) { this . schedule = schedule ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . text . ParseException ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . schedules . CalendarUnit ; import org . oddjob . schedules . CalendarUtils ; import org . oddjob . schedules . ConstrainedSchedule ; import org . oddjob . schedules . units . Month ; final public class YearlySchedule extends ConstrainedSchedule implements Serializable { private static final long serialVersionUID = ; public static final Pattern DAY_FORMAT = Pattern . compile ( "" ) ; private Month fromMonth ; private Month toMonth ; @ ArooaAttribute public void setFromMonth ( Month from ) { this . fromMonth = from ; } public Month getFromMonth ( ) { return fromMonth ; } @ ArooaAttribute public void setToMonth ( Month to ) { this . toMonth = to ; } public Month getToMonth ( ) { return toMonth ; } @ ArooaAttribute public void setInMonth ( Month in ) { this . setFromMonth ( in ) ; this . setToMonth ( in ) ; } private String fromDate ; private String toDate ; public void setFromDate ( String from ) { this . fromDate = from ; } public String getFromDate ( ) { return fromDate ; } public void setToDate ( String to ) { this . toDate = to ; } public String getToDate ( ) { return toDate ; } public void setOnDate ( String on ) { this . setFromDate ( on ) ; this . setToDate ( on ) ; } @ Override protected CalendarUnit intervalBetween ( ) { return new CalendarUnit ( Calendar . YEAR , ) ; } static Calendar parseDay ( String text , Date referenceDate , TimeZone timeZone ) throws ParseException { Matcher matcher = DAY_FORMAT . matcher ( text ) ; if ( ! matcher . matches ( ) ) { throw new ParseException ( text , ) ; } int month = Integer . parseInt ( matcher . group ( ) ) ; int day = Integer . parseInt ( matcher . group ( ) ) ; CalendarUtils calendarUtils = new CalendarUtils ( referenceDate , timeZone ) ; return calendarUtils . dayOfYear ( day , month ) ; } protected Calendar fromCalendar ( Date referenceDate , TimeZone timeZone ) { if ( fromDate != null ) { try { return parseDay ( fromDate , referenceDate , timeZone ) ; } catch ( ParseException e ) { throw new RuntimeException ( "" , e ) ; } } else if ( fromMonth != null ) { return CalendarUtils . monthOfYear ( referenceDate , fromMonth . getMonthNumber ( ) , timeZone ) ; } else { return CalendarUtils . startOfYear ( referenceDate , timeZone ) ; } } protected Calendar toCalendar ( Date referenceDate , TimeZone timeZone ) { if ( toDate != null ) { try { Calendar cal = parseDay ( toDate , referenceDate , timeZone ) ; CalendarUtils . setEndOfDay ( cal ) ; return cal ; } catch ( ParseException e ) { throw new RuntimeException ( "" , e ) ; } } else if ( toMonth != null ) { Calendar toCal = CalendarUtils . monthOfYear ( referenceDate , toMonth . getMonthNumber ( ) , timeZone ) ; CalendarUtils . setEndOfMonth ( toCal ) ; return toCal ; } else { return CalendarUtils . endOfYear ( referenceDate , timeZone ) ; } } public String toString ( ) { return this . getClass ( ) . getSimpleName ( ) + "" + getFromDate ( ) + "" + getToDate ( ) ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . schedules . AbstractSchedule ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; final public class LastSchedule extends AbstractSchedule implements Serializable { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( LastSchedule . class ) ; public ScheduleResult nextDue ( ScheduleContext context ) { Date now = context . getDate ( ) ; if ( now == null ) { return null ; } if ( getRefinement ( ) == null ) { throw new IllegalStateException ( "" ) ; } logger . debug ( this + "" + now ) ; ScheduleResult last = null ; Date use = now ; Schedule child = getRefinement ( ) ; while ( true ) { logger . debug ( this + "" + use ) ; ScheduleResult candidate = child . nextDue ( context . move ( use ) ) ; if ( candidate == null ) { break ; } if ( last == null || candidate . getFromDate ( ) . after ( last . getFromDate ( ) ) ) { last = candidate ; } use = last . getUseNext ( ) ; if ( use == null ) { break ; } } return last ; } public String toString ( ) { return "" ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalHelper ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleType ; import org . oddjob . schedules . SimpleScheduleResult ; public class BrokenSchedule implements Serializable , Schedule { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( BrokenSchedule . class ) ; private Schedule schedule ; private Schedule breaks ; private Schedule alternative ; public void setSchedule ( Schedule schedule ) { this . schedule = schedule ; } public Schedule getSchedule ( ) { return this . schedule ; } public void setBreaks ( Schedule breaks ) { this . breaks = breaks ; } public Schedule getBreaks ( ) { return this . breaks ; } public Schedule getAlternative ( ) { return alternative ; } public void setAlternative ( Schedule alternative ) { this . alternative = alternative ; } public ScheduleResult nextDue ( ScheduleContext context ) { Date now = context . getDate ( ) ; logger . debug ( this + "" + now ) ; if ( schedule == null ) { return null ; } if ( breaks == null ) { return schedule . nextDue ( context ) ; } Date use = now ; while ( true ) { if ( use == null ) { return null ; } ScheduleResult next = schedule . nextDue ( context . move ( use ) ) ; if ( next == null ) { return null ; } Interval exclude = mergeBreaks ( context . move ( next . getFromDate ( ) ) ) ; if ( exclude == null ) { return next ; } if ( new IntervalHelper ( next ) . isBefore ( exclude ) ) { return next ; } Date lastUse = use ; if ( next . getUseNext ( ) == null ) { use = null ; } else { if ( exclude . getToDate ( ) . after ( next . getUseNext ( ) ) ) { use = exclude . getToDate ( ) ; } else { use = next . getUseNext ( ) ; } } if ( alternative != null ) { if ( lastUse . before ( exclude . getFromDate ( ) ) ) { lastUse = exclude . getFromDate ( ) ; } ScheduleResult alternativeResult = alternative . nextDue ( context . spawn ( lastUse , exclude ) ) ; if ( alternativeResult != null ) { return new SimpleScheduleResult ( alternativeResult , use ) ; } } } } private Interval mergeBreaks ( ScheduleContext context ) { ScheduleContext useContext = context ; Interval merged = null ; while ( true ) { Interval exclude = breaks . nextDue ( useContext ) ; if ( exclude == null ) { return merged ; } if ( merged == null ) { merged = exclude ; } else { if ( exclude . getFromDate ( ) . after ( merged . getToDate ( ) ) ) { return merged ; } merged = new IntervalTo ( merged . getFromDate ( ) , exclude . getToDate ( ) ) ; } useContext = useContext . move ( merged . getToDate ( ) ) ; } } public String toString ( ) { return "" + schedule + "" + breaks ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . text . ParseException ; import java . util . Date ; import java . util . TimeZone ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . AbstractSchedule ; import org . oddjob . schedules . DateUtils ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . util . OddjobConfigException ; final public class DateSchedule extends AbstractSchedule implements Serializable { private static final long serialVersionUID = ; private String startDate ; private String endDate ; public void setFrom ( String startDateString ) { startDate = startDateString ; } public String getFrom ( ) { return startDate ; } public void setTo ( String endDateString ) { endDate = endDateString ; } public String getTo ( ) { return endDate ; } public void setOn ( String on ) { setFrom ( on ) ; setTo ( on ) ; } Date getStartDate ( ScheduleContext context ) { if ( startDate == null ) { return Interval . START_OF_TIME ; } TimeZone timeZone = context . getTimeZone ( ) ; try { return DateHelper . parseDate ( startDate , timeZone ) ; } catch ( ParseException e ) { throw new OddjobConfigException ( "" + startDate + "" ) ; } } Date getEndDate ( ScheduleContext context ) { if ( endDate == null ) { return Interval . END_OF_TIME ; } TimeZone timeZone = context . getTimeZone ( ) ; try { return DateUtils . endOfDay ( DateHelper . parseDate ( endDate , timeZone ) , timeZone ) ; } catch ( ParseException e ) { throw new OddjobConfigException ( "" + endDate + "" ) ; } } class ThisSchedule implements Schedule { public IntervalTo nextDue ( ScheduleContext context ) { Date now = context . getDate ( ) ; if ( now == null ) { return null ; } if ( now . compareTo ( getEndDate ( context ) ) >= ) { return null ; } return new IntervalTo ( new IntervalTo ( getStartDate ( context ) , getEndDate ( context ) ) ) ; } } public ScheduleResult nextDue ( ScheduleContext context ) { ParentChildSchedule parentChild = new ParentChildSchedule ( new ThisSchedule ( ) , getRefinement ( ) ) ; return parentChild . nextDue ( context ) ; } public String toString ( ) { return this . getClass ( ) . getName ( ) + "" + getFrom ( ) + "" + getTo ( ) ; } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . text . ParseException ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalHelper ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleScheduleResult ; public class IntervalSchedule implements Schedule , Serializable { private static final long serialVersionUID = ; private static Logger logger = Logger . getLogger ( IntervalSchedule . class ) ; private long intervalMillis ; public IntervalSchedule ( ) { } public IntervalSchedule ( long millis ) { intervalMillis = millis ; } public void setInterval ( String interval ) throws ParseException { intervalMillis = DateHelper . parseTime ( interval ) ; } public ScheduleResult nextDue ( ScheduleContext context ) { if ( intervalMillis == ) { throw new IllegalStateException ( "" ) ; } Date now = context . getDate ( ) ; Interval parentInterval = context . getParentInterval ( ) ; Interval nextInterval = null ; if ( parentInterval == null ) { nextInterval = new IntervalTo ( now , new Date ( now . getTime ( ) + intervalMillis ) ) ; } else { Date start = parentInterval . getFromDate ( ) ; if ( ! ( start . before ( now ) ) ) { nextInterval = new IntervalTo ( start , new Date ( start . getTime ( ) + intervalMillis ) ) ; } else { long sinceStart = now . getTime ( ) - start . getTime ( ) ; long intervals = sinceStart / intervalMillis ; long lastBegin = start . getTime ( ) + intervals * intervalMillis ; nextInterval = new IntervalTo ( new Date ( lastBegin ) , new Date ( lastBegin + intervalMillis ) ) ; } nextInterval = new IntervalHelper ( parentInterval ) . limit ( nextInterval ) ; } logger . debug ( this + "" + now + "" + nextInterval ) ; if ( nextInterval == null ) { return null ; } else { return new SimpleScheduleResult ( nextInterval ) ; } } @ Override public String toString ( ) { return "" + intervalMillis + "" ; } } package org . oddjob . schedules . schedules ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalHelper ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleScheduleResult ; public class ParentChildSchedule implements Schedule { private final Schedule parent ; private final Schedule child ; public ParentChildSchedule ( Schedule parent , Schedule child ) { this . parent = parent ; this . child = child ; } public ScheduleResult nextDue ( ScheduleContext context ) { ScheduleResult parentResult = limitedParentResult ( context ) ; if ( parentResult == null ) { return null ; } if ( child == null ) { return parentResult ; } ScheduleResult childResult = childResult ( context , parentResult ) ; if ( childResult != null ) { if ( childResult . getUseNext ( ) == null ) { return new SimpleScheduleResult ( childResult , childResult . getToDate ( ) ) ; } else { return childResult ; } } parentResult = limitedParentResult ( context . move ( parentResult . getToDate ( ) ) ) ; if ( parentResult == null ) { return null ; } childResult = childResult ( context , parentResult ) ; if ( childResult != null && childResult . getUseNext ( ) == null ) { return new SimpleScheduleResult ( childResult , childResult . getToDate ( ) ) ; } else { return childResult ; } } private ScheduleResult limitedParentResult ( ScheduleContext context ) { ScheduleResult parentInterval = parent . nextDue ( context ) ; if ( parentInterval == null ) { return null ; } if ( context . getParentInterval ( ) != null ) { IntervalHelper contextParentIntervalHelper = new IntervalHelper ( context . getParentInterval ( ) ) ; if ( contextParentIntervalHelper . limit ( parentInterval ) == null ) { parentInterval = parent . nextDue ( context . move ( parentInterval . getToDate ( ) ) ) ; if ( parentInterval == null ) { return null ; } if ( contextParentIntervalHelper . limit ( parentInterval ) == null ) { return null ; } } } return parentInterval ; } private ScheduleResult childResult ( ScheduleContext context , Interval parentInterval ) { if ( context . getDate ( ) . compareTo ( parentInterval . getFromDate ( ) ) < ) { return child . nextDue ( context . spawn ( parentInterval . getFromDate ( ) , parentInterval ) ) ; } else { return child . nextDue ( context . spawn ( parentInterval ) ) ; } } } package org . oddjob . schedules . schedules ; import java . io . Serializable ; import java . util . Calendar ; import java . util . Date ; import java . util . GregorianCalendar ; import org . oddjob . schedules . AbstractSchedule ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; public class DayAfterSchedule extends AbstractSchedule implements Serializable { private static final long serialVersionUID = ; public ScheduleResult nextDue ( ScheduleContext context ) { Date use = null ; Interval interval = context . getParentInterval ( ) ; if ( interval != null ) { use = new Date ( interval . getToDate ( ) . getTime ( ) - ) ; } else { use = context . getDate ( ) ; } if ( use == null ) { return null ; } Calendar useCal = Calendar . getInstance ( context . getTimeZone ( ) ) ; useCal . setTime ( use ) ; Calendar startCal = Calendar . getInstance ( context . getTimeZone ( ) ) ; startCal . clear ( ) ; startCal . set ( useCal . get ( Calendar . YEAR ) , useCal . get ( Calendar . MONTH ) , useCal . get ( Calendar . DATE ) + ) ; Calendar endCal = new GregorianCalendar ( ) ; endCal . clear ( ) ; endCal . set ( useCal . get ( Calendar . YEAR ) , useCal . get ( Calendar . MONTH ) , useCal . get ( Calendar . DATE ) + ) ; IntervalTo newInterval = new IntervalTo ( startCal . getTime ( ) , endCal . getTime ( ) ) ; if ( getRefinement ( ) != null ) { ScheduleContext shiftedContext = context . spawn ( startCal . getTime ( ) , newInterval ) ; return getRefinement ( ) . nextDue ( shiftedContext ) ; } else { return newInterval ; } } public String toString ( ) { String description = "" ; if ( getRefinement ( ) != null ) { description = "" + getRefinement ( ) ; } return "" + description ; } } package org . oddjob . schedules ; import java . util . Date ; import java . util . TimeZone ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . life . ArooaLifeAware ; import org . oddjob . arooa . utils . DateHelper ; public class ScheduleType implements ArooaValue , ArooaLifeAware { private static final Logger logger = Logger . getLogger ( ScheduleType . class ) ; public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( ScheduleType . class , Interval . class , new Convertlet < ScheduleType , Interval > ( ) { public Interval convert ( ScheduleType from ) throws ConvertletException { return from . result ; } } ) ; registry . register ( ScheduleType . class , Date . class , new Convertlet < ScheduleType , Date > ( ) { public Date convert ( ScheduleType from ) throws ConvertletException { Interval interval = from . result ; if ( interval == null ) { return null ; } else { return interval . getFromDate ( ) ; } } } ) ; } } private Date date ; private TimeZone timeZone ; private Schedule schedule ; private volatile ScheduleResult result ; public ScheduleResult getResult ( ) { return result ; } public Schedule getSchedule ( ) { return schedule ; } public void setSchedule ( Schedule schedule ) { this . schedule = schedule ; } public Date getDate ( ) { return date ; } public void setDate ( Date clock ) { this . date = clock ; } public String getTimeZone ( ) { if ( timeZone == null ) { return null ; } return timeZone . getID ( ) ; } public void setTimeZone ( String timeZoneId ) { if ( timeZoneId == null ) { this . timeZone = null ; } else { this . timeZone = TimeZone . getTimeZone ( timeZoneId ) ; } } @ Override public void initialised ( ) { } @ Override public void configured ( ) { if ( schedule == null ) { throw new IllegalStateException ( "" ) ; } Date date = this . date ; if ( date == null ) { date = new Date ( ) ; } ScheduleContext context = new ScheduleContext ( date , timeZone ) ; result = schedule . nextDue ( context ) ; logger . info ( "" + result + "" + date ) ; } @ Override public void destroy ( ) { result = null ; } @ Override public String toString ( ) { String interval = "" ; if ( result != null ) { interval = "" + DateHelper . formatDateTimeInteligently ( result . getFromDate ( ) ) ; } return getClass ( ) . getSimpleName ( ) + interval ; } } package org . oddjob . schedules ; import java . io . Serializable ; import java . text . SimpleDateFormat ; import java . util . Date ; class IntervalBase implements Serializable { private static final long serialVersionUID = ; private final Date fromDate ; private final Date toDate ; public IntervalBase ( Date on ) { this ( on . getTime ( ) , on . getTime ( ) ) ; } public IntervalBase ( Date from , Date to ) { this ( from . getTime ( ) , to . getTime ( ) ) ; } public IntervalBase ( long fromTime , long toTime ) { fromDate = new Date ( fromTime ) ; toDate = new Date ( toTime ) ; if ( toTime < fromTime ) { throw new IllegalStateException ( "" + toDate + "" + fromDate + "" ) ; } } public IntervalBase ( IntervalBase other ) { this ( other . fromDate . getTime ( ) , other . toDate . getTime ( ) ) ; } public Date getFromDate ( ) { return fromDate ; } protected Date getEndDate ( ) { return toDate ; } public boolean isBefore ( IntervalBase other ) { if ( other == null ) { return true ; } return this . fromDate . getTime ( ) < other . fromDate . getTime ( ) ; } public boolean isPast ( IntervalBase other ) { if ( other == null ) { return true ; } return this . fromDate . getTime ( ) > other . toDate . getTime ( ) ; } public boolean isPoint ( ) { return fromDate . equals ( toDate ) ; } public String toString ( ) { String fromString ; if ( fromDate . getTime ( ) % == ) { fromString = new SimpleDateFormat ( "" ) . format ( fromDate ) ; } else { fromString = new SimpleDateFormat ( "" ) . format ( fromDate ) ; } String toString ; if ( toDate . getTime ( ) + % == ) { toString = new SimpleDateFormat ( "" ) . format ( toDate ) ; } else { toString = new SimpleDateFormat ( "" ) . format ( toDate ) ; } return fromString + "" + toString ; } } package org . oddjob . schedules ; import java . util . Date ; import java . util . HashMap ; import java . util . Map ; import java . util . TimeZone ; public class ScheduleContext { private final Date date ; private final TimeZone timeZone ; private final Map < Object , Object > data ; private final Interval parentInterval ; public ScheduleContext ( Date now ) { this ( now , null , null , null ) ; } public ScheduleContext ( Date use , TimeZone timeZone ) { this ( use , timeZone , null , null ) ; } public ScheduleContext ( Date now , TimeZone timeZone , Map < Object , Object > data ) { this ( now , timeZone , data , null ) ; } public ScheduleContext ( Date now , TimeZone timeZone , Map < Object , Object > data , Interval parentInterval ) { if ( now == null ) { throw new NullPointerException ( "" ) ; } if ( timeZone == null ) { timeZone = TimeZone . getDefault ( ) ; } if ( data == null ) { data = new HashMap < Object , Object > ( ) ; } this . date = now ; this . timeZone = timeZone ; this . data = data ; this . parentInterval = parentInterval ; } public Date getDate ( ) { return date ; } public TimeZone getTimeZone ( ) { return timeZone ; } public void putData ( Object key , Object value ) { data . put ( key , value ) ; } public Object getData ( Object key ) { return data . get ( key ) ; } public Interval getParentInterval ( ) { return parentInterval ; } public ScheduleContext spawn ( Interval parentInterval ) { ScheduleContext newContext = new ScheduleContext ( this . date , this . timeZone , this . data , parentInterval ) ; return newContext ; } public ScheduleContext spawn ( Date date , Interval parentInterval ) { ScheduleContext newContext = new ScheduleContext ( date , this . timeZone , this . data , parentInterval ) ; return newContext ; } public ScheduleContext move ( Date date ) { ScheduleContext newContext = new ScheduleContext ( date , this . timeZone , this . data , this . parentInterval ) ; return newContext ; } public String toString ( ) { return "" + date + ( parentInterval == null ? "" : "" + parentInterval + "" ) + ( timeZone == null ? "" : "" + timeZone . getID ( ) ) ; } } package org . oddjob . schedules ; public interface RefineableSchedule extends Schedule { public void setRefinement ( Schedule refinement ) ; } package org . oddjob . schedules ; public interface Schedule { public ScheduleResult nextDue ( ScheduleContext context ) ; } package org . oddjob . schedules ; import java . util . Date ; public interface Interval { public static final Date END_OF_TIME = new Date ( ) ; public static final Date START_OF_TIME = new Date ( - ) ; public Date getFromDate ( ) ; public Date getToDate ( ) ; } package org . oddjob . persist ; import org . oddjob . arooa . life . ComponentPersistException ; public interface Persistable { public void persist ( ) throws ComponentPersistException ; } package org . oddjob . persist ; import java . io . IOException ; import java . io . InputStream ; import java . io . ObjectInputStream ; import java . io . ObjectStreamClass ; import java . lang . reflect . Proxy ; public class OddjobObjectInputStream extends ObjectInputStream { private final ClassLoader classLoader ; public OddjobObjectInputStream ( InputStream inputStream , ClassLoader classLoader ) throws IOException { super ( inputStream ) ; this . classLoader = classLoader ; } @ Override protected Class < ? > resolveClass ( ObjectStreamClass desc ) throws IOException , ClassNotFoundException { String className = desc . getName ( ) ; return Class . forName ( className , true , classLoader ) ; } @ Override protected Class < ? > resolveProxyClass ( String [ ] interfaces ) throws IOException , ClassNotFoundException { Class < ? > [ ] classObjs = new Class [ interfaces . length ] ; for ( int i = ; i < interfaces . length ; i ++ ) { Class < ? > cl = Class . forName ( interfaces [ i ] , false , classLoader ) ; classObjs [ i ] = cl ; } return Proxy . getProxyClass ( classLoader , classObjs ) ; } } package org . oddjob . persist ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . ObjectInput ; import java . io . ObjectOutput ; import java . io . ObjectOutputStream ; public class SerializeWithBytes { public byte [ ] toBytes ( Object object ) { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; try { ObjectOutput oo = new ObjectOutputStream ( os ) ; oo . writeObject ( object ) ; oo . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return os . toByteArray ( ) ; } public Object fromBytes ( byte [ ] bytes , ClassLoader classLoader ) { ByteArrayInputStream is = new ByteArrayInputStream ( bytes ) ; try { ObjectInput oi = new OddjobObjectInputStream ( is , classLoader ) ; Object o = oi . readObject ( ) ; oi . close ( ) ; return o ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } package org . oddjob . persist ; import java . util . HashMap ; import java . util . Map ; import java . util . TreeMap ; import org . apache . log4j . Logger ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . registry . Path ; public class MapPersister extends PersisterBase { private static final Logger logger = Logger . getLogger ( MapPersister . class ) ; private final Map < Path , Map < String , byte [ ] > > cache ; public MapPersister ( ) { this ( new HashMap < Path , Map < String , byte [ ] > > ( ) ) ; } public MapPersister ( Map < Path , Map < String , byte [ ] > > store ) { this . cache = store ; } @ Override protected void persist ( Path path , String id , Object proxy ) { logger . info ( "" + path + "" + id + "" ) ; Map < String , byte [ ] > inner = cache . get ( path ) ; if ( inner == null ) { inner = new TreeMap < String , byte [ ] > ( ) ; cache . put ( path , inner ) ; } inner . put ( id , new SerializeWithBytes ( ) . toBytes ( proxy ) ) ; } @ Override protected Object restore ( Path path , String id , ClassLoader classLoader ) { Map < String , byte [ ] > inner = cache . get ( path ) ; if ( inner == null ) { logger . info ( "" + path + "" ) ; return null ; } byte [ ] buffer = inner . get ( id ) ; if ( buffer == null ) { logger . info ( "" + path + "" + id + "" ) ; return null ; } logger . info ( "" + path + "" + id + "" ) ; return new SerializeWithBytes ( ) . fromBytes ( buffer , classLoader ) ; } @ Override protected String [ ] list ( Path path ) throws ComponentPersistException { Map < String , byte [ ] > inner = cache . get ( path ) ; if ( inner == null ) { return null ; } return inner . keySet ( ) . toArray ( new String [ inner . size ( ) ] ) ; } @ Override protected void remove ( Path path , String id ) { logger . info ( "" + path + "" + id ) ; Map < String , byte [ ] > inner = cache . get ( path ) ; if ( inner == null ) { return ; } inner . remove ( id ) ; } @ Override protected void clear ( Path path ) { logger . info ( "" + path ) ; cache . remove ( path ) ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + cache . size ( ) + "" ; } } package org . oddjob . persist ; import java . io . File ; public class PersistRequest { private final Object toPersist ; private final String id ; private final File directory ; private boolean persisted = false ; private final Object waitOn = new Object ( ) ; public PersistRequest ( Object toPersist , String id , File directory ) { this . toPersist = toPersist ; this . id = id ; this . directory = directory ; } public Object getToPersist ( ) { return toPersist ; } public String getId ( ) { return id ; } public File getDirectory ( ) { return directory ; } public void persisted ( ) { synchronized ( waitOn ) { persisted = true ; waitOn . notifyAll ( ) ; } } public void waitPerist ( ) { synchronized ( waitOn ) { while ( ! persisted ) { try { waitOn . wait ( ) ; } catch ( InterruptedException e ) { } } } } } package org . oddjob . persist ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . ObjectInput ; import java . io . ObjectOutput ; import java . io . ObjectOutputStream ; public class SerializeWithBinaryStream { public InputStream toStream ( Object object ) { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; try { ObjectOutput oo = new ObjectOutputStream ( os ) ; oo . writeObject ( object ) ; oo . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return new ByteArrayInputStream ( os . toByteArray ( ) ) ; } public Object fromStream ( InputStream stream , ClassLoader classLoader ) { try { ObjectInput oi = new OddjobObjectInputStream ( stream , classLoader ) ; Object o = oi . readObject ( ) ; oi . close ( ) ; return o ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } package org . oddjob . persist ; import java . io . Serializable ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import javax . swing . ImageIcon ; import org . oddjob . Describeable ; import org . oddjob . Iconic ; import org . oddjob . Stateful ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconListener ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class SilhouetteFactory { public Object create ( Object subject , ArooaSession session ) { String name = subject . toString ( ) ; Map < String , String > description = new UniversalDescriber ( session ) . describe ( subject ) ; List < Class < ? > > interfaces = new ArrayList < Class < ? > > ( ) ; interfaces . add ( Describeable . class ) ; StateEvent lastJobStateEvent = null ; if ( subject instanceof Stateful ) { Stateful stateful = ( Stateful ) subject ; lastJobStateEvent = stateful . lastStateEvent ( ) ; interfaces . add ( Stateful . class ) ; } Object [ ] children = null ; if ( subject instanceof Structural && session != null ) { Structural structural = ( Structural ) subject ; ChildCatcher childCatcher = new ChildCatcher ( session ) ; structural . addStructuralListener ( childCatcher ) ; structural . removeStructuralListener ( childCatcher ) ; children = childCatcher . getChildren ( ) ; interfaces . add ( Structural . class ) ; } IconInfo iconInfo = null ; if ( subject instanceof Iconic ) { Iconic iconic = ( Iconic ) subject ; IconCapture capture = new IconCapture ( ) ; iconic . addIconListener ( capture ) ; iconic . removeIconListener ( capture ) ; iconInfo = capture . getIconInfo ( ) ; interfaces . add ( Iconic . class ) ; } Silhouette silhouette = new Silhouette ( name , description ) ; Object proxy = Proxy . newProxyInstance ( this . getClass ( ) . getClassLoader ( ) , interfaces . toArray ( new Class [ interfaces . size ( ) ] ) , silhouette ) ; if ( lastJobStateEvent != null ) { silhouette . setLastJobStateEvent ( new StateEvent ( ( Stateful ) proxy , lastJobStateEvent . getState ( ) , lastJobStateEvent . getTime ( ) , lastJobStateEvent . getException ( ) ) ) ; } if ( children != null ) { StructuralEvent [ ] structuralEvents = new StructuralEvent [ children . length ] ; for ( int i = ; i < structuralEvents . length ; ++ i ) { StructuralEvent event = new StructuralEvent ( ( Structural ) proxy , children [ i ] , i ) ; structuralEvents [ i ] = event ; } silhouette . setChildren ( structuralEvents ) ; } if ( iconInfo != null ) { silhouette . setIconInfo ( new IconEvent ( ( Iconic ) proxy , iconInfo . getIconId ( ) ) , iconInfo . getIcon ( ) ) ; } return proxy ; } } class Silhouette implements InvocationHandler , Serializable , Describeable , Structural , Stateful , Iconic { private static final long serialVersionUID = ; private final Map < String , String > description ; private final String name ; private StructuralEvent [ ] structuralEvents ; private StateEvent lastJobStateEvent ; private IconEvent iconEvent ; private ImageIcon iconTip ; Silhouette ( String name , Map < String , String > description ) { this . name = name ; this . description = description ; } void setChildren ( StructuralEvent [ ] children ) { this . structuralEvents = children ; } void setLastJobStateEvent ( StateEvent lastJobStateEvent ) { this . lastJobStateEvent = lastJobStateEvent ; } void setIconInfo ( IconEvent iconEvent , ImageIcon iconTip ) { this . iconEvent = iconEvent ; this . iconTip = iconTip ; } @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { Method ourMethod = getClass ( ) . getMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; return ourMethod . invoke ( this , args ) ; } @ Override public Map < String , String > describe ( ) { return description ; } @ Override public void addStateListener ( StateListener listener ) { listener . jobStateChange ( lastJobStateEvent ) ; } @ Override public void removeStateListener ( StateListener listener ) { } @ Override public StateEvent lastStateEvent ( ) { return lastJobStateEvent ; } @ Override public void addStructuralListener ( StructuralListener listener ) { for ( int i = ; i < structuralEvents . length ; ++ i ) { listener . childAdded ( structuralEvents [ i ] ) ; } } @ Override public void removeStructuralListener ( StructuralListener listener ) { } @ Override public void addIconListener ( IconListener listener ) { listener . iconEvent ( iconEvent ) ; } @ Override public void removeIconListener ( IconListener listener ) { } @ Override public ImageIcon iconForId ( String id ) { return iconTip ; } @ Override public String toString ( ) { return name ; } public boolean equals ( Object other ) { if ( ! ( other instanceof Proxy ) ) { return false ; } return this == Proxy . getInvocationHandler ( other ) ; } } class ChildCatcher implements StructuralListener { private final ArooaSession session ; private final List < Object > childHelper = new ArrayList < Object > ( ) ; private boolean childNotOurs ; public ChildCatcher ( ArooaSession session ) { this . session = session ; } Object [ ] getChildren ( ) { if ( childNotOurs ) { return new Object [ ] ; } else { return childHelper . toArray ( new Object [ childHelper . size ( ) ] ) ; } } @ Override public void childAdded ( StructuralEvent event ) { Object child = event . getChild ( ) ; if ( session . getComponentPool ( ) . contextFor ( child ) == null ) { childNotOurs = true ; } else { Object childSilhouette = new SilhouetteFactory ( ) . create ( child , session ) ; childHelper . add ( event . getIndex ( ) , childSilhouette ) ; } } @ Override public void childRemoved ( StructuralEvent event ) { childHelper . remove ( event . getIndex ( ) ) ; } } class IconInfo { private final String iconId ; private final ImageIcon icon ; IconInfo ( String iconId , ImageIcon iconTip ) { this . iconId = iconId ; this . icon = iconTip ; } public String getIconId ( ) { return iconId ; } public ImageIcon getIcon ( ) { return icon ; } } class IconCapture implements IconListener { private IconInfo iconInfo ; @ Override public void iconEvent ( IconEvent e ) { iconInfo = new IconInfo ( e . getIconId ( ) , e . getSource ( ) . iconForId ( e . getIconId ( ) ) ) ; } public IconInfo getIconInfo ( ) { return iconInfo ; } } package org . oddjob . persist ; import java . io . File ; import org . apache . log4j . Logger ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . registry . Path ; public class FilePersister extends PersisterBase { private static final Logger logger = Logger . getLogger ( FilePersister . class ) ; private File directory ; @ ArooaAttribute public void setDir ( File dir ) { this . directory = dir ; } public File getDir ( ) { return this . directory ; } protected void persist ( Path path , String id , Object o ) throws ComponentPersistException { new SerializeWithFile ( ) . toFile ( directoryFor ( path ) , id , o ) ; } protected void remove ( Path path , String id ) throws ComponentPersistException { new SerializeWithFile ( ) . remove ( directoryFor ( path ) , id ) ; } protected Object restore ( Path path , String id , ClassLoader classLoader ) throws ComponentPersistException { return new SerializeWithFile ( ) . fromFile ( directoryFor ( path ) , id , classLoader ) ; } @ Override protected String [ ] list ( Path path ) throws ComponentPersistException { return new SerializeWithFile ( ) . list ( directoryFor ( path ) ) ; } @ Override protected void clear ( Path path ) { new SerializeWithFile ( ) . clear ( new File ( directory , path . toString ( ) ) ) ; } File directoryFor ( Path path ) throws ComponentPersistException { if ( directory == null && ( path == null || path . size ( ) == ) ) { throw new NullPointerException ( "" ) ; } if ( directory != null && ! directory . exists ( ) ) { throw new ComponentPersistException ( "" + directory ) ; } File dir = new File ( directory , path . toString ( ) ) ; if ( ! dir . exists ( ) ) { dir . mkdirs ( ) ; logger . debug ( "" + dir + "" ) ; } return dir ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + ( directory == null ? "" : "" + directory . getAbsolutePath ( ) ) ; } } package org . oddjob . persist ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . registry . Path ; import org . oddjob . framework . Transient ; abstract public class PersisterBase implements OddjobPersister { private static final Logger logger = Logger . getLogger ( PersisterBase . class ) ; private List < String > include ; private List < String > exclude ; private Path ourPath ; public PersisterBase ( ) { } protected PersisterBase ( Path path ) { this . ourPath = path ; } public void setPath ( String path ) { ourPath = new Path ( path ) ; } public ComponentPersister persisterFor ( String id ) { Path path ; if ( ourPath == null ) { path = new Path ( id ) ; } else { path = ourPath . addId ( id ) ; } logger . info ( "" + id + "" ) ; return new InnerPersister ( path ) ; } private class InnerPersister implements OddjobPersister , ComponentPersister { private final Path path ; private boolean closed ; private List < InnerPersister > children = new ArrayList < InnerPersister > ( ) ; public InnerPersister ( Path path ) { this . path = path ; } @ Override public ComponentPersister persisterFor ( String id ) { if ( id == null ) { throw new NullPointerException ( "" ) ; } InnerPersister child = new InnerPersister ( this . path . addId ( id ) ) { public void close ( ) { super . close ( ) ; children . remove ( this ) ; } } ; children . add ( child ) ; return child ; } @ Override public void persist ( String id , Object proxy , ArooaSession session ) throws ComponentPersistException { if ( closed ) { return ; } if ( ! ( proxy instanceof Serializable ) ) { logger . debug ( "" + proxy + "" ) ; return ; } if ( ( proxy instanceof Transient ) ) { logger . debug ( "" + proxy + "" ) ; return ; } if ( include != null && ! include . contains ( id ) ) { logger . debug ( "" + proxy + "" + id + "" ) ; return ; } if ( exclude != null && exclude . contains ( id ) ) { logger . debug ( "" + proxy + "" + id + "" ) ; return ; } PersisterBase . this . persist ( path , id , proxy ) ; } @ Override public Object restore ( String id , ClassLoader classLoader , ArooaSession session ) throws ComponentPersistException { if ( closed ) { return null ; } return PersisterBase . this . restore ( path , id , classLoader ) ; } @ Override public void remove ( String id , ArooaSession session ) throws ComponentPersistException { if ( closed ) { return ; } PersisterBase . this . remove ( path , id ) ; } @ Override public String [ ] list ( ) throws ComponentPersistException { return PersisterBase . this . list ( path ) ; } @ Override public void clear ( ) throws ComponentPersistException { if ( closed ) { return ; } List < ComponentPersister > copy = new ArrayList < ComponentPersister > ( children ) ; for ( ComponentPersister child : copy ) { child . clear ( ) ; } logger . debug ( "" + path + "" ) ; PersisterBase . this . clear ( path ) ; } @ Override public void close ( ) { closed = true ; } @ Override public String toString ( ) { return PersisterBase . this . toString ( ) + "" + path ; } } abstract protected void persist ( Path path , String id , Object component ) throws ComponentPersistException ; abstract protected Object restore ( Path path , String id , ClassLoader classLoader ) throws ComponentPersistException ; abstract protected String [ ] list ( Path path ) throws ComponentPersistException ; abstract protected void remove ( Path path , String id ) throws ComponentPersistException ; abstract protected void clear ( Path path ) throws ComponentPersistException ; } package org . oddjob . persist ; import java . io . File ; import java . io . FileFilter ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . ObjectInput ; import java . io . ObjectOutput ; import java . io . ObjectOutputStream ; import java . io . OutputStream ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . arooa . life . ComponentPersistException ; public class SerializeWithFile { private static final Logger logger = Logger . getLogger ( SerializeWithFile . class ) ; private final static String EXTENSION = "" ; public void toFile ( File dir , String name , Object o ) throws ComponentPersistException { File inProgress = new File ( dir , name + "" + EXTENSION ) ; File old = new File ( dir , "" + name + EXTENSION ) ; File finished = new File ( dir , name + EXTENSION ) ; ObjectOutput oo = null ; try { OutputStream os = new FileOutputStream ( inProgress ) ; oo = new ObjectOutputStream ( os ) ; } catch ( FileNotFoundException e ) { throw new ComponentPersistException ( "" , e ) ; } catch ( IOException e ) { throw new ComponentPersistException ( "" + inProgress + "" , e ) ; } try { oo . writeObject ( o ) ; } catch ( IOException e ) { throw new ComponentPersistException ( "" + name + "" + o . getClass ( ) . getName ( ) + "" + o + "" , e ) ; } finally { try { oo . close ( ) ; } catch ( IOException e ) { } } if ( finished . exists ( ) ) { if ( ! finished . renameTo ( old ) ) { logger . warn ( "" + finished + "" + old ) ; } } if ( ! inProgress . renameTo ( finished ) ) { throw new ComponentPersistException ( "" + inProgress + "" + finished ) ; } if ( old . exists ( ) ) { if ( ! old . delete ( ) ) { logger . warn ( "" + old ) ; } } logger . debug ( "" + o + "" + name + "" + finished + "" ) ; } public void remove ( File dir , String name ) { File f = new File ( dir , name + EXTENSION ) ; if ( f . exists ( ) ) { boolean result = f . delete ( ) ; if ( result ) { logger . debug ( "" + f + "" ) ; } else { logger . debug ( "" + f + "" ) ; } } } public Object fromFile ( File dir , String name , ClassLoader classLoader ) throws ComponentPersistException { File f = new File ( dir , name + EXTENSION ) ; if ( ! f . exists ( ) ) { return null ; } ObjectInput oi = null ; try { InputStream is = new FileInputStream ( f ) ; oi = new OddjobObjectInputStream ( is , classLoader ) ; } catch ( IOException e ) { throw new ComponentPersistException ( "" + f + "" , e ) ; } try { Object o = oi . readObject ( ) ; logger . debug ( "" + o + "" + f + "" ) ; return o ; } catch ( Exception e ) { throw new ComponentPersistException ( "" + f , e ) ; } finally { try { oi . close ( ) ; } catch ( IOException e ) { } } } public void clear ( File dir ) { if ( dir . exists ( ) ) { try { FileUtils . forceDelete ( dir ) ; logger . debug ( "" + dir + "" ) ; } catch ( IOException e ) { throw new RuntimeException ( "" + dir + "" , e ) ; } } } public String [ ] list ( File dir ) { File [ ] files = dir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { if ( pathname . isFile ( ) && pathname . getName ( ) . endsWith ( EXTENSION ) ) { return true ; } else { return false ; } } } ) ; String [ ] names = new String [ files . length ] ; for ( int i = ; i < names . length ; ++ i ) { String nameWithExtension = files [ i ] . getName ( ) ; names [ i ] = nameWithExtension . substring ( , nameWithExtension . length ( ) - EXTENSION . length ( ) ) ; } logger . debug ( "" + names . length + "" + dir + "" ) ; return names ; } public String [ ] children ( File dir ) { File [ ] files = dir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { if ( pathname . isDirectory ( ) ) { return true ; } else { return false ; } } } ) ; String [ ] names = new String [ files . length ] ; for ( int i = ; i < names . length ; ++ i ) { names [ i ] = files [ i ] . getName ( ) ; } logger . debug ( "" + names . length + "" + dir + "" ) ; return names ; } } package org . oddjob . persist ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import org . oddjob . FailedToStopException ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . framework . BasePrimary ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . framework . StopWait ; import org . oddjob . images . IconHelper ; import org . oddjob . images . StateIcons ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsDone ; import org . oddjob . state . IsExecutable ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . ParentState ; import org . oddjob . state . ParentStateChanger ; import org . oddjob . state . ParentStateConverter ; import org . oddjob . state . ParentStateHandler ; import org . oddjob . state . State ; import org . oddjob . state . StateChanger ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class ArchiveJob extends BasePrimary implements Runnable , Serializable , Stoppable , Resetable , Stateful , Structural { private transient ParentStateHandler stateHandler ; private transient ParentStateChanger stateChanger ; private static final long serialVersionUID = ; private transient ChildHelper < Runnable > childHelper ; private Object archiveIdentifier ; private String archiveName ; private transient OddjobPersister archiver ; private volatile transient PersistingStateListener listener ; protected transient volatile boolean stop ; public ArchiveJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { stateHandler = new ParentStateHandler ( this ) ; childHelper = new ChildHelper < Runnable > ( this ) ; stateChanger = new ParentStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override protected ParentStateHandler stateHandler ( ) { return stateHandler ; } protected StateChanger < ParentState > getStateChanger ( ) { return stateChanger ; } public final void run ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ParentState . EXECUTING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; try { configure ( ) ; execute ( ) ; } catch ( final Throwable e ) { logger ( ) . error ( "" , e ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setStateException ( e ) ; } } ) ; } logger ( ) . info ( "" ) ; } finally { ComponentBoundry . pop ( ) ; } } private class PersistingStateListener implements StateListener { private final Stateful child ; private final ComponentPersister componentPersister ; private volatile StateEvent event ; private volatile boolean reflect ; public PersistingStateListener ( Stateful child , ComponentPersister componentPersister ) { this . child = child ; this . componentPersister = componentPersister ; } void startReflecting ( ) { reflect = true ; reflectState ( ) ; } void reflectState ( ) { if ( event . getState ( ) . isDestroyed ( ) ) { stopListening ( event . getSource ( ) ) ; } else { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { if ( event . getState ( ) . isException ( ) ) { getStateChanger ( ) . setStateException ( event . getException ( ) ) ; } else { getStateChanger ( ) . setState ( new ParentStateConverter ( ) . toStructuralState ( event . getState ( ) ) ) ; } } } ) ; } } @ Override public void jobStateChange ( final StateEvent event ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { this . event = event ; if ( reflect ) { reflectState ( ) ; } if ( stop ) { return ; } State state = event . getState ( ) ; if ( new IsDone ( ) . test ( state ) ) { if ( ! stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . info ( "" + event . getSource ( ) + "" + archiveIdentifier + "" + event . getState ( ) + "" ) ; try { persist ( event . getSource ( ) ) ; } catch ( ComponentPersistException e ) { logger ( ) . error ( "" , e ) ; getStateChanger ( ) . setStateException ( e ) ; } } } ) ) { } } } finally { ComponentBoundry . pop ( ) ; } } private void persist ( Stateful source ) throws ComponentPersistException { ComponentBoundry . push ( loggerName ( ) , this ) ; try { Object silhouette = new SilhouetteFactory ( ) . create ( child , ArchiveJob . this . getArooaSession ( ) ) ; componentPersister . persist ( archiveIdentifier . toString ( ) , silhouette , getArooaSession ( ) ) ; } finally { ComponentBoundry . pop ( ) ; } } } protected void execute ( ) throws Throwable { OddjobPersister archiver = this . archiver ; if ( archiver == null ) { ComponentPersister persister = getArooaSession ( ) . getComponentPersister ( ) ; if ( persister != null && persister instanceof OddjobPersister ) { archiver = ( ( OddjobPersister ) persister ) ; } } if ( archiver == null ) { throw new NullPointerException ( "" ) ; } if ( archiveIdentifier == null ) { throw new NullPointerException ( "" ) ; } final ComponentPersister componentPersister = archiver . persisterFor ( archiveName ) ; if ( componentPersister == null ) { throw new NullPointerException ( "" + archiveName + "" ) ; } Runnable child = childHelper . getChild ( ) ; if ( child == null ) { return ; } if ( ! ( child instanceof Stateful ) ) { throw new IllegalArgumentException ( "" ) ; } if ( listener == null ) { listener = new PersistingStateListener ( ( Stateful ) child , componentPersister ) ; ( ( Stateful ) child ) . addStateListener ( listener ) ; } child . run ( ) ; listener . startReflecting ( ) ; } public void stop ( ) throws FailedToStopException { stateHandler . assertAlive ( ) ; ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { stop = true ; } } ) ) { return ; } logger ( ) . info ( "" ) ; iconHelper . changeIcon ( IconHelper . STOPPING ) ; try { childHelper . stopChildren ( ) ; } catch ( RuntimeException e ) { iconHelper . changeIcon ( IconHelper . EXECUTING ) ; throw e ; } synchronized ( this ) { notifyAll ( ) ; } new StopWait ( this ) . run ( ) ; stopListening ( ( Stateful ) childHelper . getChild ( ) ) ; logger ( ) . info ( "" ) ; } finally { ComponentBoundry . pop ( ) ; } } public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; stopListening ( ( Stateful ) childHelper . getChild ( ) ) ; childHelper . softResetChildren ( ) ; stop = false ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; stopListening ( ( Stateful ) childHelper . getChild ( ) ) ; childHelper . hardResetChildren ( ) ; stop = false ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } private void stopListening ( Stateful to ) { if ( to == null ) { return ; } StateListener listener = this . listener ; this . listener = null ; if ( listener != null ) { to . removeStateListener ( listener ) ; logger ( ) . debug ( "" ) ; } } public Object getArchiveIdentifier ( ) { return archiveIdentifier ; } public void setArchiveIdentifier ( Object archive ) { this . archiveIdentifier = archive ; } public String getArchiveName ( ) { return archiveName ; } public void setArchiveName ( String path ) { this . archiveName = path ; } public OddjobPersister getArchiver ( ) { return archiver ; } public void setArchiver ( OddjobPersister archiver ) { this . archiver = archiver ; } public void addStructuralListener ( StructuralListener listener ) { stateHandler . assertAlive ( ) ; childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } @ ArooaComponent public void setJob ( Runnable job ) { if ( job == null ) { childHelper . removeAllChildren ( ) ; } else { childHelper . insertChild ( , job ) ; } } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; s . writeObject ( getName ( ) ) ; if ( loggerName ( ) . startsWith ( getClass ( ) . getName ( ) ) ) { s . writeObject ( null ) ; } else { s . writeObject ( loggerName ( ) ) ; } s . writeObject ( stateHandler . lastStateEvent ( ) ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; String name = ( String ) s . readObject ( ) ; logger ( ( String ) s . readObject ( ) ) ; StateEvent savedEvent = ( StateEvent ) s . readObject ( ) ; completeConstruction ( ) ; setName ( name ) ; stateHandler . restoreLastJobStateEvent ( savedEvent ) ; iconHelper . changeIcon ( StateIcons . iconFor ( stateHandler . getState ( ) ) ) ; } protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( ParentState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + ArchiveJob . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . persist ; import org . oddjob . arooa . life . ComponentPersister ; public interface OddjobPersister { public ComponentPersister persisterFor ( String id ) ; } package org . oddjob . persist ; import java . io . Serializable ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . life . ComponentPersister ; public class RestoreBundle implements Serializable { private static final long serialVersionUID = ; private final ArooaConfiguration configuration ; private final ComponentPersister archivePersister ; public RestoreBundle ( ArooaConfiguration configuration , ComponentPersister archivePersister ) { this . archivePersister = archivePersister ; this . configuration = configuration ; } public ArooaConfiguration getConfiguration ( ) { return configuration ; } public ComponentPersister getArchivePersister ( ) { return archivePersister ; } } package org . oddjob . persist ; import org . oddjob . Structural ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . framework . SimpleJob ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class ArchiveBrowserJob extends SimpleJob implements Structural { protected ChildHelper < Object > childHelper = new ChildHelper < Object > ( this ) ; private String archiveName ; private OddjobPersister archiver ; @ Override protected int execute ( ) throws Throwable { OddjobPersister oddjobPersister = this . archiver ; if ( oddjobPersister == null ) { ComponentPersister sessionPersister = getArooaSession ( ) . getComponentPersister ( ) ; if ( sessionPersister != null && sessionPersister instanceof OddjobPersister ) { oddjobPersister = ( OddjobPersister ) sessionPersister ; } } if ( oddjobPersister == null ) { throw new NullPointerException ( "" ) ; } ComponentPersister persister = oddjobPersister . persisterFor ( archiveName ) ; Object [ ] archives = persister . list ( ) ; int index = ; for ( Object archive : archives ) { childHelper . insertChild ( index ++ , new Restore ( archive . toString ( ) , persister ) ) ; } return ; } @ Override protected void onReset ( ) { childHelper . removeAllChildren ( ) ; } @ Override public void addStructuralListener ( StructuralListener listener ) { childHelper . addStructuralListener ( listener ) ; } @ Override public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } class Restore extends SimpleJob implements Structural { private final String archive ; protected ChildHelper < Object > childHelper = new ChildHelper < Object > ( this ) ; private final ComponentPersister archiver ; public Restore ( String archive , ComponentPersister archiver ) { this . archive = archive ; this . archiver = archiver ; } @ Override protected int execute ( ) throws Throwable { Object restored = archiver . restore ( archive , getClass ( ) . getClassLoader ( ) , ArchiveBrowserJob . this . getArooaSession ( ) ) ; childHelper . insertChild ( , restored ) ; return ; } @ Override protected void onReset ( ) { childHelper . removeAllChildren ( ) ; } @ Override public void addStructuralListener ( StructuralListener listener ) { childHelper . addStructuralListener ( listener ) ; } @ Override public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } @ Override public String toString ( ) { return archive ; } } public String getArchiveName ( ) { return archiveName ; } public void setArchiveName ( String path ) { this . archiveName = path ; } public OddjobPersister getArchiver ( ) { return archiver ; } public void setArchiver ( OddjobPersister archiver ) { this . archiver = archiver ; } } package org . oddjob ; import org . oddjob . structural . StructuralListener ; public interface Structural { public void addStructuralListener ( StructuralListener listener ) ; public void removeStructuralListener ( StructuralListener listener ) ; } package org . oddjob ; import org . oddjob . arooa . ArooaConstants ; public class Reserved { public static final String ID_PROPERTY = ArooaConstants . ID_PROPERTY ; public static final String TRANSIENT_PROPERTY = "" ; public static final String LOGGER_PROPERTY = "" ; public static final String RESULT_PROPERTY = "" ; public static final String ZOOM_POINT_PROPERTY = "" ; } package org . oddjob . swing ; import java . io . File ; import javax . swing . JFileChooser ; import javax . swing . JFrame ; import javax . swing . UIManager ; import org . oddjob . framework . SerializableJob ; public class ChooseFile extends SerializableJob { private static final long serialVersionUID = ; private File chosen ; private File dir ; public File getChosen ( ) { return chosen ; } public void setDir ( File dir ) { this . dir = dir ; } public int execute ( ) throws Exception { UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; JFrame f = new JFrame ( ) ; JFileChooser chooser = new JFileChooser ( ) ; if ( dir != null ) { chooser . setCurrentDirectory ( dir ) ; } int option = chooser . showOpenDialog ( f ) ; f . dispose ( ) ; if ( option == JFileChooser . APPROVE_OPTION ) { chosen = chooser . getSelectedFile ( ) ; logger ( ) . debug ( "" + chosen . getAbsolutePath ( ) ) ; return ; } else { chosen = null ; return ; } } } package org . oddjob . swing ; import java . awt . BorderLayout ; import java . awt . Container ; import java . awt . GridLayout ; import java . awt . event . ActionEvent ; import java . awt . event . ComponentAdapter ; import java . awt . event . ComponentEvent ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Future ; import javax . inject . Inject ; import javax . swing . AbstractAction ; import javax . swing . BorderFactory ; import javax . swing . JButton ; import javax . swing . JComponent ; import javax . swing . JFrame ; import javax . swing . JLabel ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . WindowConstants ; import javax . swing . border . EtchedBorder ; import org . oddjob . FailedToStopException ; import org . oddjob . Iconic ; import org . oddjob . Oddjob ; import org . oddjob . OddjobServices ; import org . oddjob . OddjobShutdownThread ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . arooa . design . view . ScreenPresence ; import org . oddjob . arooa . registry . ServiceProvider ; import org . oddjob . arooa . registry . Services ; import org . oddjob . framework . SimpleService ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconListener ; import org . oddjob . input . InputHandler ; import org . oddjob . state . StateConditions ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class OddjobPanel extends SimpleService implements ServiceProvider , Services , Serializable , Stoppable , Structural { private static final long serialVersionUID = ; protected transient ChildHelper < Runnable > childHelper ; private volatile transient ExecutorService executorService ; private volatile transient List < JobButtonAction > actions ; private ScreenPresence screen ; private int columns = ; private volatile transient FrameWithStatus frame ; public OddjobPanel ( ) { completeConstruction ( ) ; ScreenPresence whole = ScreenPresence . wholeScreen ( ) ; screen = whole . smaller ( ) ; } private void completeConstruction ( ) { childHelper = new ChildHelper < Runnable > ( this ) ; } @ Inject public void setExecutorService ( ExecutorService executorService ) { this . executorService = executorService ; } protected JComponent createPanel ( ) { actions = new ArrayList < JobButtonAction > ( ) ; Runnable [ ] jobs = childHelper . getChildren ( new Runnable [ ] ) ; int rows = ( int ) Math . ceil ( ( double ) jobs . length / columns ) ; JPanel panel = new JPanel ( new GridLayout ( rows , columns , , ) ) ; for ( final Runnable job : jobs ) { JobButtonAction action = new JobButtonAction ( job ) ; actions . add ( action ) ; JButton button = new JButton ( action ) ; panel . add ( button ) ; if ( job instanceof Stateful ) { ( ( Stateful ) job ) . addStateListener ( new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { if ( StateConditions . FINISHED . test ( event . getState ( ) ) ) { String status = job . toString ( ) + "" + event . getState ( ) ; if ( event . getException ( ) != null ) { status += "" + event . getException ( ) ; } frame . setStatus ( status ) ; } } } ) ; } } JPanel padding = new JPanel ( ) ; padding . add ( panel ) ; return padding ; } @ Override protected void onStart ( ) throws Throwable { if ( executorService == null ) { throw new NullPointerException ( "" ) ; } JComponent panel = createPanel ( ) ; JScrollPane scroll = new JScrollPane ( panel ) ; frame = new FrameWithStatus ( ) ; screen . fit ( frame ) ; frame . addComponentListener ( new ComponentAdapter ( ) { @ Override public void componentMoved ( ComponentEvent e ) { screen = new ScreenPresence ( e . getComponent ( ) ) ; } @ Override public void componentResized ( ComponentEvent e ) { screen = new ScreenPresence ( e . getComponent ( ) ) ; } } ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { try { stop ( ) ; } catch ( FailedToStopException e1 ) { logger ( ) . error ( e ) ; } } public void windowClosed ( WindowEvent e ) { logger ( ) . debug ( "" ) ; } } ) ; frame . setDefaultCloseOperation ( WindowConstants . DO_NOTHING_ON_CLOSE ) ; frame . setTitle ( this . toString ( ) ) ; scroll . setBorder ( BorderFactory . createEtchedBorder ( EtchedBorder . RAISED ) ) ; frame . getContentPane ( ) . add ( scroll , BorderLayout . CENTER ) ; frame . setVisible ( true ) ; logger ( ) . debug ( "" ) ; } @ Override protected void onStop ( ) throws FailedToStopException { final JFrame frame = this . frame ; if ( frame != null ) { if ( ! ( Thread . currentThread ( ) instanceof OddjobShutdownThread ) ) { frame . dispose ( ) ; } this . frame = null ; } for ( JobButtonAction action : actions ) { action . externalStop ( ) ; } logger ( ) . debug ( "" ) ; } public void addStructuralListener ( StructuralListener listener ) { stateHandler . assertAlive ( ) ; childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } @ ArooaComponent public void setJobs ( int index , Runnable child ) { if ( child == null ) { childHelper . removeChildAt ( index ) ; } else { childHelper . insertChild ( index , child ) ; } } @ Override public Services getServices ( ) { return this ; } @ Override public Object getService ( String serviceName ) throws IllegalArgumentException { if ( OddjobServices . INPUT_HANDLER . equals ( serviceName ) ) { if ( frame == null ) { return null ; } else { return new SwingInputHandler ( frame ) ; } } else { throw new IllegalArgumentException ( "" + serviceName ) ; } } @ Override public String serviceNameFor ( Class < ? > theClass , String flavour ) { if ( theClass . isAssignableFrom ( InputHandler . class ) ) { return OddjobServices . INPUT_HANDLER ; } else { return null ; } } class JobButtonAction extends AbstractAction { private final static long serialVersionUID = ; private final Runnable job ; private volatile Future < ? > future ; private volatile Runnable clickTask ; private volatile Runnable stopTask ; JobButtonAction ( Runnable job ) { super ( job . toString ( ) ) ; this . job = job ; if ( job instanceof Iconic ) { ( ( Iconic ) job ) . addIconListener ( new IconListener ( ) { @ Override public void iconEvent ( IconEvent e ) { putValue ( SMALL_ICON , e . getSource ( ) . iconForId ( e . getIconId ( ) ) ) ; } } ) ; } resetActions ( ) ; } void resetActions ( ) { clickTask = new RunAction ( ) ; stopTask = new NoopAction ( ) ; } @ Override public void actionPerformed ( ActionEvent e ) { clickTask . run ( ) ; } void externalStop ( ) { stopTask . run ( ) ; } class RunAction implements Runnable { @ Override public void run ( ) { future = executorService . submit ( new Runnable ( ) { @ Override public void run ( ) { if ( job instanceof Resetable ) { ( ( Resetable ) job ) . hardReset ( ) ; } job . run ( ) ; synchronized ( RunAction . this ) { resetActions ( ) ; } } } ) ; synchronized ( this ) { if ( clickTask == this ) { clickTask = new Stop ( ) ; stopTask = clickTask ; } } } } class NoopAction implements Runnable { @ Override public void run ( ) { } } class Stop implements Runnable { @ Override public void run ( ) { if ( future != null ) { future . cancel ( false ) ; } if ( job instanceof Stoppable ) { try { ( ( Stoppable ) job ) . stop ( ) ; } catch ( FailedToStopException e ) { logger ( ) . error ( e ) ; } } } } } public int getColumns ( ) { return columns ; } public void setColumns ( int cols ) { this . columns = cols ; } public ScreenPresence getScreen ( ) { return screen ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; completeConstruction ( ) ; } static class FrameWithStatus extends JFrame { private static final long serialVersionUID = ; private final JLabel status = new JLabel ( "" + Oddjob . VERSION ) ; public FrameWithStatus ( ) { Container container = getContentPane ( ) ; container . setLayout ( new BorderLayout ( ) ) ; container . add ( status , BorderLayout . SOUTH ) ; } public void setStatus ( String status ) { this . status . setText ( status ) ; } } } package org . oddjob . swing ; import javax . swing . JOptionPane ; import javax . swing . UIManager ; import org . oddjob . framework . SerializableJob ; public class ConfirmationJob extends SerializableJob { private static final long serialVersionUID = ; private volatile String title ; private volatile String message ; @ Override protected int execute ( ) throws Throwable { UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; int result = JOptionPane . showConfirmDialog ( null , message , title , JOptionPane . YES_NO_OPTION ) ; return result ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } public String getMessage ( ) { return message ; } public void setMessage ( String message ) { this . message = message ; } } package org . oddjob . swing ; import java . awt . Component ; import java . awt . Container ; import java . awt . GridBagConstraints ; import java . awt . GridBagLayout ; import java . awt . Insets ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import java . util . Properties ; import java . util . concurrent . Callable ; import java . util . concurrent . atomic . AtomicReference ; import javax . swing . JCheckBox ; import javax . swing . JLabel ; import javax . swing . JPanel ; import javax . swing . JPasswordField ; import javax . swing . JTextField ; import org . oddjob . arooa . design . screem . FileSelectionOptions ; import org . oddjob . arooa . design . view . DialogueHelper ; import org . oddjob . arooa . design . view . FileSelectionWidget ; import org . oddjob . arooa . design . view . Looks ; import org . oddjob . input . InputHandler ; import org . oddjob . input . InputMedium ; import org . oddjob . input . InputRequest ; public class SwingInputHandler implements InputHandler { private Component parent ; public SwingInputHandler ( Component owner ) { this . parent = owner ; } @ Override public Properties handleInput ( InputRequest [ ] requests ) { InputDialogue form = new InputDialogue ( ) ; List < AtomicReference < String > > refs = new ArrayList < AtomicReference < String > > ( ) ; final List < Callable < Boolean > > validations = new ArrayList < Callable < Boolean > > ( ) ; Properties properties = new Properties ( ) ; for ( InputRequest request : requests ) { AtomicReference < String > ref = new AtomicReference < String > ( ) ; refs . add ( ref ) ; FieldBuilder medium = new FieldBuilder ( ref ) ; request . render ( medium ) ; FormWriter formWriter = medium . getFormWriter ( ) ; form . accept ( formWriter ) ; validations . add ( medium . getValidator ( ) ) ; } DialogManager dialogManager = new DialogManager ( ) ; dialogManager . showDialog ( form . getForm ( ) , new Callable < Boolean > ( ) { @ Override public Boolean call ( ) throws Exception { for ( Callable < Boolean > validator : validations ) { if ( validator == null ) { continue ; } if ( ! validator . call ( ) ) { return Boolean . FALSE ; } } return Boolean . TRUE ; } } ) ; if ( dialogManager . isChosen ( ) ) { int i = ; for ( AtomicReference < String > ref : refs ) { String property = requests [ i ++ ] . getProperty ( ) ; if ( property == null ) { continue ; } if ( ref . get ( ) == null ) { continue ; } properties . setProperty ( property , ref . get ( ) ) ; } return properties ; } else { return null ; } } class InputDialogue { private final JPanel form = new JPanel ( ) ; private int row ; public InputDialogue ( ) { form . setLayout ( new GridBagLayout ( ) ) ; GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTHWEST ; c . insets = new Insets ( Looks . DETAIL_FORM_BORDER , Looks . DETAIL_FORM_BORDER , Looks . DETAIL_FORM_BORDER , Looks . DETAIL_FORM_BORDER ) ; c . gridx = ; c . gridy = ; } public void accept ( FormWriter formWriter ) { row = formWriter . writeTo ( form , row ) ; } public JPanel getForm ( ) { return form ; } } interface FormWriter { public int writeTo ( Container container , int row ) ; } class FieldBuilder implements InputMedium { private final AtomicReference < String > reference ; private FormWriter formWriter ; private Callable < Boolean > validator ; public FieldBuilder ( AtomicReference < String > reference ) { this . reference = reference ; } @ Override public void confirm ( String message , Boolean defaultValue ) { final JLabel label = new JLabel ( formatLabelText ( message ) ) ; final JCheckBox toggle = new JCheckBox ( ) ; if ( defaultValue != null ) { toggle . setSelected ( defaultValue . booleanValue ( ) ) ; } formWriter = new FormWriter ( ) { @ Override public int writeTo ( Container container , int row ) { GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTHWEST ; c . gridx = ; c . gridy = row ; c . insets = new Insets ( , , , ) ; container . add ( label , c ) ; c . weightx = ; c . fill = GridBagConstraints . NONE ; c . anchor = GridBagConstraints . WEST ; c . gridx = ; c . gridwidth = GridBagConstraints . REMAINDER ; c . insets = new Insets ( , , , ) ; container . add ( toggle , c ) ; return row + ; } } ; validator = new Callable < Boolean > ( ) { @ Override public Boolean call ( ) throws Exception { reference . set ( new Boolean ( toggle . isSelected ( ) ) . toString ( ) ) ; return true ; } } ; } @ Override public void password ( String prompt ) { final JLabel label = new JLabel ( formatLabelText ( prompt ) ) ; final JPasswordField text = new JPasswordField ( Looks . TEXT_FIELD_SIZE ) ; formWriter = new FormWriter ( ) { @ Override public int writeTo ( Container container , int row ) { GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTHWEST ; c . gridx = ; c . gridy = row ; c . insets = new Insets ( , , , ) ; container . add ( label , c ) ; c . weightx = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . WEST ; c . gridx = ; c . gridwidth = GridBagConstraints . REMAINDER ; c . insets = new Insets ( , , , ) ; container . add ( text , c ) ; return row + ; } } ; validator = new Callable < Boolean > ( ) { @ Override public Boolean call ( ) throws Exception { reference . set ( new String ( text . getPassword ( ) ) ) ; return true ; } } ; } @ Override public void prompt ( String prompt , String defaultValue ) { final JLabel label = new JLabel ( formatLabelText ( prompt ) ) ; final JTextField text = new JTextField ( Looks . TEXT_FIELD_SIZE ) ; text . setText ( defaultValue ) ; reference . set ( defaultValue ) ; formWriter = new FormWriter ( ) { @ Override public int writeTo ( Container container , int row ) { GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTHWEST ; c . gridx = ; c . gridy = row ; c . insets = new Insets ( , , , ) ; container . add ( label , c ) ; c . weightx = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . WEST ; c . gridx = ; c . gridwidth = GridBagConstraints . REMAINDER ; c . insets = new Insets ( , , , ) ; container . add ( text , c ) ; return row + ; } } ; validator = new Callable < Boolean > ( ) { @ Override public Boolean call ( ) throws Exception { reference . set ( new String ( text . getText ( ) ) ) ; return true ; } } ; } public void message ( String message ) { final JLabel label = new JLabel ( formatLabelText ( message ) ) ; label . setAlignmentY ( ) ; formWriter = new FormWriter ( ) { @ Override public int writeTo ( Container container , int row ) { GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTH ; c . gridx = ; c . gridy = row ; c . gridwidth = GridBagConstraints . REMAINDER ; c . insets = new Insets ( , , , ) ; container . add ( label , c ) ; return row + ; } } ; } @ Override public void file ( final String prompt , String defaultValue , final FileSelectionOptions options ) { final JLabel label = new JLabel ( formatLabelText ( prompt ) ) ; final FileSelectionWidget chooser = new FileSelectionWidget ( ) ; if ( defaultValue != null ) { chooser . setSelectedFile ( defaultValue ) ; } chooser . setOptions ( options ) ; formWriter = new FormWriter ( ) { @ Override public int writeTo ( Container container , int row ) { GridBagConstraints c = new GridBagConstraints ( ) ; c . weightx = ; c . weighty = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . NORTHWEST ; c . gridx = ; c . gridy = row ; c . insets = new Insets ( , , , ) ; container . add ( label , c ) ; c . weightx = ; c . fill = GridBagConstraints . HORIZONTAL ; c . anchor = GridBagConstraints . WEST ; c . gridx = ; c . gridwidth = GridBagConstraints . REMAINDER ; c . insets = new Insets ( , , , ) ; container . add ( chooser , c ) ; return row + ; } } ; validator = new Callable < Boolean > ( ) { @ Override public Boolean call ( ) throws Exception { String chosen = chooser . getSelectedFile ( ) ; if ( chosen == null ) { reference . set ( null ) ; } else { reference . set ( new File ( chosen ) . getCanonicalPath ( ) ) ; } return Boolean . TRUE ; } } ; } public FormWriter getFormWriter ( ) { return formWriter ; } public Callable < Boolean > getValidator ( ) { return validator ; } } class DialogManager { private boolean chosen ; public boolean isChosen ( ) { return chosen ; } public void showDialog ( Component form , Callable < Boolean > okAction ) { chosen = DialogueHelper . showOKCancelDialogue ( parent , form , okAction ) ; } } static String formatLabelText ( String labelText ) { if ( labelText . contains ( "" ) ) { return "" + labelText . replaceAll ( "" , "" ) + "" ; } else { return labelText ; } } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) ; } } package org . oddjob . swing ; import java . awt . Component ; import java . io . Serializable ; import java . util . concurrent . Callable ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . DesignSeedContext ; import org . oddjob . arooa . design . GenericDesignFactory ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . view . SwingFormFactory ; import org . oddjob . arooa . design . view . ValueDialog ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ConfigureBeanJob implements Serializable , Runnable , ArooaSessionAware { private static final long serialVersionUID = ; private transient Object bean ; private transient ArooaSession session ; private String beanConfig ; @ Override public void setArooaSession ( ArooaSession session ) { this . session = session ; } @ Override public void run ( ) { final Object bean = this . bean ; if ( bean == null ) { throw new NullPointerException ( "" ) ; } DesignInstance design = null ; PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; ArooaContext parentContext = new DesignSeedContext ( ArooaType . VALUE , session ) ; GenericDesignFactory designFactory = new GenericDesignFactory ( accessor . getClassName ( bean ) ) ; if ( beanConfig == null ) { ArooaElement element = new ArooaElement ( "" ) ; design = designFactory . createDesign ( element , parentContext ) ; } else { DesignParser parser = new DesignParser ( designFactory ) ; try { parser . parse ( new XMLConfiguration ( "" , beanConfig ) ) ; } catch ( ArooaParseException e ) { throw new RuntimeException ( e ) ; } design = parser . getDesign ( ) ; } Form form = design . detail ( ) ; Component view = SwingFormFactory . create ( form ) . dialog ( ) ; final DesignInstance finalDesign = design ; ValueDialog dialog = new ValueDialog ( view , new Callable < Boolean > ( ) { @ Override public Boolean call ( ) throws Exception { StandardArooaParser parser = new StandardArooaParser ( bean , session ) ; try { parser . parse ( finalDesign . getArooaContext ( ) . getConfigurationNode ( ) ) ; } catch ( ArooaParseException e ) { throw new RuntimeException ( e ) ; } XMLArooaParser xmlParser = new XMLArooaParser ( ) ; try { xmlParser . parse ( finalDesign . getArooaContext ( ) . getConfigurationNode ( ) ) ; } catch ( ArooaParseException e ) { throw new RuntimeException ( e ) ; } beanConfig = xmlParser . getXml ( ) ; return null ; } } ) ; dialog . showDialog ( null ) ; } public Object getBean ( ) { return bean ; } public void setBean ( Object bean ) { if ( this . bean == null ) { this . bean = bean ; } } } package org . oddjob ; import org . apache . log4j . Logger ; import org . oddjob . framework . StopWait ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateEvent ; public class OddjobRunner { private static final Logger logger = Logger . getLogger ( OddjobRunner . class ) ; public static final String KILLER_TIMEOUT_PROPERTY = "" ; public static final long DEFAULT_KILLER_TIMEOUT = ; private final Oddjob oddjob ; private volatile boolean destroying = false ; private final long killerTimeout ; public OddjobRunner ( Oddjob oddjob ) { this . oddjob = oddjob ; String timeoutProperty = System . getProperty ( KILLER_TIMEOUT_PROPERTY ) ; if ( timeoutProperty == null ) { killerTimeout = DEFAULT_KILLER_TIMEOUT ; } else { killerTimeout = Long . parseLong ( timeoutProperty ) ; } } public Oddjob getOddjob ( ) { return oddjob ; } public void run ( ) { logger . info ( "" + oddjob . getVersion ( ) ) ; Runtime . getRuntime ( ) . addShutdownHook ( new ShutdownHook ( ) ) ; try { oddjob . run ( ) ; if ( destroying ) { logger . debug ( "" ) ; } else { logger . debug ( "" ) ; new StopWait ( oddjob , Long . MAX_VALUE ) . run ( ) ; oddjob . stopExecutors ( ) ; } } catch ( Throwable t ) { logger . fatal ( "" , t ) ; Runtime . getRuntime ( ) . halt ( ) ; } } class ShutdownHook extends OddjobShutdownThread { private Thread killer ; public void run ( ) { logger . info ( "" ) ; killer = new Thread ( new Runnable ( ) { public void run ( ) { logger . debug ( "" + killerTimeout + "" ) ; try { Thread . sleep ( killerTimeout ) ; } catch ( InterruptedException e ) { logger . debug ( "" ) ; return ; } logger . error ( "" ) ; Runtime . getRuntime ( ) . halt ( - ) ; } } ) ; logger . debug ( "" ) ; killer . setDaemon ( true ) ; killer . start ( ) ; StateEvent lastStateEvent = oddjob . lastStateEvent ( ) ; if ( lastStateEvent . getState ( ) . isStoppable ( ) ) { try { oddjob . stop ( ) ; lastStateEvent = oddjob . lastStateEvent ( ) ; } catch ( FailedToStopException e ) { logger . error ( "" , e ) ; lastStateEvent = new StateEvent ( oddjob , ParentState . EXCEPTION , e ) ; } } logger . debug ( "" ) ; destroying = true ; oddjob . destroy ( ) ; killer . interrupt ( ) ; org . oddjob . state . State state = lastStateEvent . getState ( ) ; if ( state . isException ( ) ) { logger . error ( "" + state + "" , lastStateEvent . getException ( ) ) ; Runtime . getRuntime ( ) . halt ( - ) ; } else if ( state . isIncomplete ( ) ) { logger . info ( "" + state + "" ) ; Runtime . getRuntime ( ) . halt ( ) ; } else { logger . info ( "" + state + "" ) ; } } } } package org . oddjob ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . lang . reflect . Array ; import java . util . Enumeration ; import java . util . Properties ; import org . apache . log4j . ConsoleAppender ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . apache . log4j . PatternLayout ; import org . apache . log4j . PropertyConfigurator ; import org . oddjob . arooa . convert . convertlets . FileConvertlets ; import org . oddjob . input . ConsoleInputHandler ; import org . oddjob . input . StdInInputHandler ; import org . oddjob . oddballs . OddballsDescriptorFactory ; import org . oddjob . oddballs . OddballsDirDescriptorFactory ; public class Main { private static Logger logger ; private static Logger logger ( ) { if ( logger == null ) { logger = Logger . getLogger ( Main . class ) ; } return logger ; } public static final String ODDBALLS_DIR = "" ; public static final String USER_PROPERTIES = "" ; public OddjobRunner init ( String args [ ] ) throws IOException { Properties props = processUserProperties ( ) ; String oddjobFile = null ; String name = null ; String logConfig = null ; File oddballsDir = null ; String oddballsPath = null ; String oddjobHome = System . getProperty ( "" ) ; if ( oddjobHome != null ) { oddballsDir = new File ( oddjobHome , ODDBALLS_DIR ) ; } int startArg = ; for ( int i = ; i < args . length ; i ++ ) { String arg = args [ i ] ; if ( arg . equals ( "" ) || arg . equals ( "" ) ) { usage ( ) ; return null ; } else if ( arg . equals ( "" ) || arg . equals ( "" ) ) { version ( ) ; return null ; } else if ( arg . equals ( "" ) || arg . equals ( "" ) ) { name = args [ ++ i ] ; startArg += ; } else if ( arg . equals ( "" ) || arg . equals ( "" ) ) { logConfig = args [ ++ i ] ; startArg += ; } else if ( arg . equals ( "" ) || arg . equals ( "" ) ) { oddjobFile = args [ ++ i ] ; startArg += ; } else if ( arg . equals ( "" ) || arg . equals ( "" ) ) { oddballsDir = null ; startArg += ; } else if ( arg . equals ( "" ) || arg . equals ( "" ) ) { oddballsDir = new File ( args [ ++ i ] ) ; startArg += ; } else if ( arg . equals ( "" ) || arg . equals ( "" ) ) { oddballsPath = args [ ++ i ] ; startArg += ; } else if ( arg . equals ( "" ) ) { startArg += ; break ; } else { break ; } } if ( logConfig != null ) { configureLog ( logConfig ) ; } Enumeration < ? > enumeration = Logger . getRootLogger ( ) . getAllAppenders ( ) ; boolean hasAppenders = enumeration . hasMoreElements ( ) ; if ( ! hasAppenders ) { Logger . getRootLogger ( ) . addAppender ( new ConsoleAppender ( new PatternLayout ( "" ) ) ) ; Logger . getRootLogger ( ) . setLevel ( Level . ERROR ) ; } final Oddjob oddjob = new Oddjob ( ) ; oddjob . setFile ( findFileToUse ( oddjobFile , oddjobHome ) ) ; oddjob . setName ( name ) ; if ( oddballsPath != null ) { oddjob . setDescriptorFactory ( new OddballsDescriptorFactory ( new FileConvertlets ( ) . pathToFiles ( oddballsPath ) ) ) ; } else if ( oddballsDir != null ) { oddjob . setDescriptorFactory ( new OddballsDirDescriptorFactory ( oddballsDir ) ) ; } if ( System . console ( ) == null ) { oddjob . setInputHandler ( new StdInInputHandler ( ) ) ; } else { oddjob . setInputHandler ( new ConsoleInputHandler ( ) ) ; } oddjob . setProperties ( props ) ; Object newArray = Array . newInstance ( String . class , args . length - startArg ) ; System . arraycopy ( args , startArg , newArray , , args . length - startArg ) ; oddjob . setArgs ( ( String [ ] ) newArray ) ; return new OddjobRunner ( oddjob ) ; } public void configureLog ( String logConfigFileName ) { System . setProperty ( "" , "" ) ; PropertyConfigurator . configure ( logConfigFileName ) ; logger ( ) . info ( "" + logConfigFileName + "" ) ; } public void usage ( ) { System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; System . out . println ( "" ) ; } public void version ( ) { System . out . println ( "" + new Oddjob ( ) . getVersion ( ) ) ; } public File findFileToUse ( String oddjobFile , String oddjobHome ) throws FileNotFoundException { File theFile ; if ( oddjobFile == null ) { theFile = new File ( "" ) ; if ( ! theFile . exists ( ) && oddjobHome != null ) { theFile = new File ( oddjobHome , "" ) ; } if ( ! theFile . exists ( ) ) { throw new FileNotFoundException ( "" ) ; } } else { theFile = new File ( oddjobFile ) ; if ( ! theFile . exists ( ) ) { throw new FileNotFoundException ( oddjobFile ) ; } } return theFile ; } protected Properties processUserProperties ( ) throws IOException { String homeDir = System . getProperty ( "" ) ; if ( homeDir == null ) { return null ; } File userProperties = new File ( homeDir , USER_PROPERTIES ) ; if ( ! userProperties . exists ( ) ) { return null ; } Properties props = new Properties ( ) ; InputStream input = new FileInputStream ( userProperties ) ; props . load ( input ) ; input . close ( ) ; return props ; } public static void main ( String [ ] args ) throws IOException { Main ojm = new Main ( ) ; OddjobRunner runner = ojm . init ( args ) ; if ( runner == null ) { return ; } runner . run ( ) ; } } package org . oddjob . script ; import javax . script . Invocable ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; public class ScriptInvoker implements Invoker { public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( Invocable . class , Invoker . class , new Convertlet < Invocable , Invoker > ( ) { public Invoker convert ( Invocable from ) { return new ScriptInvoker ( from ) ; } } ) ; } } private final Invocable invocable ; public ScriptInvoker ( Invocable invocable ) { if ( invocable == null ) { throw new NullPointerException ( "" ) ; } this . invocable = invocable ; } @ Override public Object invoke ( String name , InvokerArguments arguments ) { Object args [ ] = new Object [ arguments . size ( ) ] ; for ( int i = ; i < args . length ; ++ i ) { try { args [ i ] = arguments . getArgument ( i , Object . class ) ; } catch ( ArooaConversionException e ) { throw new RuntimeException ( "" + i , e ) ; } } try { return invocable . invokeFunction ( name , args ) ; } catch ( Exception e ) { throw new RuntimeException ( "" + name , e ) ; } } } package org . oddjob . script ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . NoConversionAvailableException ; public class ConvertableArguments implements InvokerArguments { private final ArooaConverter converter ; private final Object [ ] args ; public ConvertableArguments ( ArooaConverter converter , Object ... args ) { this . converter = converter ; this . args = args ; } @ Override public int size ( ) { return args . length ; } @ Override public < T > T getArgument ( int index , Class < T > type ) throws NoConversionAvailableException , ConversionFailedException { return converter . convert ( args [ index ] , type ) ; } } package org . oddjob . script ; import java . io . Reader ; import javax . script . Compilable ; import javax . script . CompiledScript ; import javax . script . Invocable ; import javax . script . ScriptEngine ; import javax . script . ScriptEngineManager ; import javax . script . ScriptException ; public class ScriptCompiler { private String language ; private Invocable invocable ; public Evaluatable compileScript ( Reader reader ) { if ( language == null ) { throw new RuntimeException ( "" ) ; } try { ScriptEngineManager manager = new ScriptEngineManager ( ) ; ScriptEngine engine = manager . getEngineByName ( language ) ; if ( engine instanceof Invocable ) { invocable = ( Invocable ) engine ; } if ( engine instanceof Compilable ) { CompiledScript compiled = ( ( Compilable ) engine ) . compile ( reader ) ; return new PreCompiled ( engine , compiled ) ; } else { return new NotPreCompiled ( engine , reader ) ; } } catch ( ScriptException be ) { throw new RuntimeException ( be ) ; } } public void setLanguage ( String language ) { this . language = language ; } public String getLanguage ( ) { return language ; } public Invocable getInvocable ( ) { return invocable ; } } package org . oddjob . script ; import javax . script . CompiledScript ; import javax . script . ScriptEngine ; import javax . script . ScriptException ; public class PreCompiled implements Evaluatable { private final ScriptEngine engine ; private final CompiledScript compiled ; public PreCompiled ( ScriptEngine engine , CompiledScript compiled ) { this . engine = engine ; this . compiled = compiled ; } @ Override public Object eval ( ) throws ScriptException { return compiled . eval ( ) ; } @ Override public Object get ( String key ) { return engine . get ( key ) ; } @ Override public void put ( String key , Object value ) { engine . put ( key , value ) ; } } package org . oddjob . script ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . util . HashMap ; import java . util . Map ; import javax . script . Invocable ; import org . apache . log4j . Logger ; import org . oddjob . framework . SerializableJob ; import org . oddjob . util . OddjobConfigException ; public class ScriptJob extends SerializableJob { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( ScriptJob . class ) ; private transient String language ; private transient Map < String , Object > beans ; private transient InputStream input ; private String resultVariable ; private Object result ; private boolean resultForState ; private transient Invocable invocable ; private transient Evaluatable evaluatable ; protected int execute ( ) throws IOException { ScriptCompiler compiler = new ScriptCompiler ( ) ; compiler . setLanguage ( language ) ; if ( input == null ) { throw new OddjobConfigException ( "" ) ; } evaluatable = compiler . compileScript ( new InputStreamReader ( input ) ) ; logger . info ( "" ) ; invocable = compiler . getInvocable ( ) ; ScriptRunner runner = new ScriptRunner ( resultVariable ) ; if ( beans != null ) { runner . addBeans ( beans ) ; } result = runner . executeScript ( evaluatable ) ; logger . info ( "" + result ) ; if ( resultForState ) { if ( this . result instanceof Number ) { return ( ( Number ) this . result ) . intValue ( ) ; } } return ; } public void setLanguage ( String language ) { this . language = language ; } public String getLanguage ( ) { return language ; } public Object getBeans ( String name ) { if ( beans == null ) { return null ; } return beans . get ( name ) ; } public void setBeans ( String name , Object value ) { if ( beans == null ) { beans = new HashMap < String , Object > ( ) ; } logger ( ) . debug ( "" + name + "" + value + "" ) ; beans . put ( name , value ) ; } public InputStream getInput ( ) { return input ; } public void setInput ( InputStream input ) { this . input = input ; } public Invocable getInvocable ( ) { return invocable ; } public Object getVariables ( String key ) { return evaluatable . get ( key ) ; } public String getResultVariable ( ) { return resultVariable ; } public void setResultVariable ( String resultVariable ) { this . resultVariable = resultVariable ; } public boolean isResultForState ( ) { return resultForState ; } public void setResultForState ( boolean resultForState ) { this . resultForState = resultForState ; } public Object getResult ( ) { return result ; } } package org . oddjob . script ; import javax . script . ScriptEngine ; import javax . script . ScriptException ; public interface Evaluatable { public Object eval ( ) throws ScriptException ; public Object get ( String key ) ; public void put ( String key , Object value ) ; } package org . oddjob . script ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . framework . SerializableJob ; import org . oddjob . jmx . JMXServiceJob ; public class InvokeJob extends SerializableJob { private static final long serialVersionUID = ; private transient Invoker source ; private String function ; private transient List < ArooaValue > parameters ; private transient Object result ; public InvokeJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { parameters = new ArrayList < ArooaValue > ( ) ; } @ Override protected int execute ( ) throws Throwable { InvokeType delegate = new InvokeType ( ) ; delegate . setArooaSession ( getArooaSession ( ) ) ; delegate . setFunction ( function ) ; delegate . setSource ( source ) ; for ( int i = ; i < parameters . size ( ) ; ++ i ) { delegate . setParameters ( i , parameters . get ( i ) ) ; } result = delegate . toValue ( ) ; return ; } @ Override protected void onReset ( ) { result = null ; } public Invoker getSource ( ) { return source ; } public void setSource ( Invoker source ) { this . source = source ; } public String getFunction ( ) { return function ; } public void setFunction ( String function ) { this . function = function ; } public ArooaValue getParameters ( int index ) { return parameters . get ( index ) ; } public void setParameters ( int index , ArooaValue parameter ) { if ( parameter == null ) { parameters . remove ( index ) ; } else { parameters . add ( index , parameter ) ; } } public Object getResult ( ) { return result ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; if ( result instanceof Serializable ) { s . writeObject ( result ) ; } else { s . writeObject ( null ) ; } } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; result = s . readObject ( ) ; completeConstruction ( ) ; } } package org . oddjob . script ; import java . lang . reflect . Method ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; public class MethodInvoker implements Invoker { public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( Object . class , Invoker . class , new Convertlet < Object , Invoker > ( ) { public Invoker convert ( Object from ) { return new MethodInvoker ( from ) ; } } ) ; } } private final Object target ; public MethodInvoker ( Object target ) { if ( target == null ) { throw new NullPointerException ( "" ) ; } this . target = target ; } @ Override public Object invoke ( String name , InvokerArguments parameters ) { Class < ? > cl ; MethodName methodName = new MethodName ( name ) ; Object object = this . target ; if ( methodName . staticMethod && object instanceof Class < ? > ) { cl = ( Class < ? > ) object ; object = null ; } else { cl = object . getClass ( ) ; } Method [ ] ms = cl . getMethods ( ) ; Method found = null ; Object [ ] args = null ; for ( Method m : ms ) { if ( ! m . getName ( ) . equals ( methodName . method ) ) { continue ; } if ( parameters . size ( ) != m . getParameterTypes ( ) . length ) { continue ; } args = new Object [ parameters . size ( ) ] ; try { for ( int i = ; i < args . length ; ++ i ) { args [ i ] = parameters . getArgument ( i , m . getParameterTypes ( ) [ i ] ) ; } } catch ( ArooaConversionException e ) { continue ; } found = m ; break ; } if ( found == null ) { throw new IllegalArgumentException ( "" + target + "" + name ) ; } try { return found . invoke ( object , args ) ; } catch ( Exception e ) { throw new RuntimeException ( "" + name , e ) ; } } class MethodName { final String method ; final boolean staticMethod ; public MethodName ( String name ) { Pattern pattern = Pattern . compile ( "" ) ; Matcher matcher = pattern . matcher ( name ) ; if ( ! matcher . matches ( ) ) { throw new IllegalArgumentException ( "" + name ) ; } staticMethod = matcher . group ( ) != null ; method = matcher . group ( ) ; } } } package org . oddjob . script ; import java . io . Reader ; import javax . script . ScriptEngine ; import javax . script . ScriptException ; public class NotPreCompiled implements Evaluatable { private final ScriptEngine engine ; private final Reader reader ; public NotPreCompiled ( ScriptEngine engine , Reader reader ) { this . engine = engine ; this . reader = reader ; } @ Override public Object eval ( ) throws ScriptException { return engine . eval ( reader ) ; } @ Override public Object get ( String key ) { return engine . get ( key ) ; } @ Override public void put ( String key , Object value ) { engine . put ( key , value ) ; } } package org . oddjob . script ; import org . oddjob . arooa . convert . ArooaConversionException ; public interface InvokerArguments { public int size ( ) ; public < T > T getArgument ( int index , Class < T > type ) throws ArooaConversionException ; } package org . oddjob . script ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionLookup ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . ConversionStep ; import org . oddjob . arooa . convert . Joker ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaSessionAware ; public class InvokeType implements ArooaValue , ArooaSessionAware { private static final Logger logger = Logger . getLogger ( InvokeType . class ) ; private Invoker source ; private String function ; private List < ArooaValue > parameters = new ArrayList < ArooaValue > ( ) ; private ArooaConverter converter ; public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . registerJoker ( InvokeType . class , new Joker < InvokeType > ( ) { public < T > ConversionStep < InvokeType , T > lastStep ( Class < ? extends InvokeType > from , final Class < T > to , ConversionLookup conversions ) { return new ConversionStep < InvokeType , T > ( ) { public Class < InvokeType > getFromClass ( ) { return InvokeType . class ; } public Class < T > getToClass ( ) { return to ; } public T convert ( InvokeType from , ArooaConverter converter ) throws ArooaConversionException { return converter . convert ( from . toValue ( ) , to ) ; } } ; } } ) ; } } @ ArooaHidden @ Override public void setArooaSession ( ArooaSession session ) { converter = session . getTools ( ) . getArooaConverter ( ) ; } public Object toValue ( ) throws ArooaConversionException { if ( source == null ) { throw new ArooaConversionException ( "" ) ; } Object [ ] paramArray = parameters . toArray ( ) ; logger . info ( "" + function + "" + Arrays . toString ( paramArray ) ) ; Object result = source . invoke ( function , new ConvertableArguments ( converter , paramArray ) ) ; logger . info ( "" + function + "" + result ) ; return result ; } public Invoker getSource ( ) { return source ; } public void setSource ( Invoker source ) { this . source = source ; } public String getFunction ( ) { return function ; } public void setFunction ( String function ) { this . function = function ; } public ArooaValue getParameters ( int index ) { return parameters . get ( index ) ; } public void setParameters ( int index , ArooaValue parameter ) { if ( parameter == null ) { parameters . remove ( index ) ; } else { parameters . add ( index , parameter ) ; } } @ Override public String toString ( ) { return "" + function ; } } package org . oddjob . script ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import javax . script . ScriptException ; public class ScriptRunner { private final String resultVariable ; private Map < String , Object > beans = new HashMap < String , Object > ( ) ; public ScriptRunner ( String resultVariable ) { this . resultVariable = resultVariable ; } public void addBeans ( Map < String , Object > dictionary ) { for ( Iterator < String > i = dictionary . keySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { String key = ( String ) i . next ( ) ; Object val = dictionary . get ( key ) ; addBean ( key , val ) ; } } public void addBean ( String key , Object bean ) { boolean isValid = key . length ( ) > && Character . isJavaIdentifierStart ( key . charAt ( ) ) ; for ( int i = ; isValid && i < key . length ( ) ; i ++ ) { isValid = Character . isJavaIdentifierPart ( key . charAt ( i ) ) ; } if ( isValid ) { beans . put ( key , bean ) ; } } public Object executeScript ( Evaluatable evaluatable ) { try { for ( Iterator < String > i = beans . keySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { String key = ( String ) i . next ( ) ; Object value = beans . get ( key ) ; evaluatable . put ( key , value ) ; } Object result = evaluatable . eval ( ) ; if ( resultVariable != null ) { return evaluatable . get ( resultVariable ) ; } else { return result ; } } catch ( ScriptException be ) { throw new RuntimeException ( be ) ; } } } package org . oddjob . script ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . MappedDesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . designer . components . BaseDC ; public class ScriptDesFa implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new ScriptDesign ( element , parentContext ) ; } } class ScriptDesign extends BaseDC { private final SimpleTextAttribute language ; private final SimpleTextAttribute resultVariable ; private final SimpleTextAttribute resultForState ; private final SimpleDesignProperty input ; private final MappedDesignProperty beans ; public ScriptDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; language = new SimpleTextAttribute ( "" , this ) ; resultVariable = new SimpleTextAttribute ( "" , this ) ; resultForState = new SimpleTextAttribute ( "" , this ) ; input = new SimpleDesignProperty ( "" , this ) ; beans = new MappedDesignProperty ( "" , this ) ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( language . view ( ) . setTitle ( "" ) ) . add ( input . view ( ) . setTitle ( "" ) ) . add ( beans . view ( ) . setTitle ( "" ) ) . add ( resultVariable . view ( ) . setTitle ( "" ) ) . add ( resultForState . view ( ) . setTitle ( "" ) ) ) ; } @ Override public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , language , input , beans , resultVariable , resultForState } ; } } package org . oddjob . script ; public interface Invoker { public Object invoke ( String name , InvokerArguments parameters ) ; } package org . oddjob ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . ScheduledExecutorService ; public interface OddjobExecutors { public ScheduledExecutorService getScheduledExecutor ( ) ; public ExecutorService getPoolExecutor ( ) ; } package org . oddjob ; public interface Stoppable { public void stop ( ) throws FailedToStopException ; } package org . oddjob . scheduling ; public interface Outcome { public boolean isWon ( ) ; public String getWinner ( ) ; } package org . oddjob . scheduling ; import java . util . List ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledThreadPoolExecutor ; import org . apache . log4j . Logger ; import org . oddjob . OddjobExecutors ; public class DefaultExecutors implements OddjobExecutors { private static final Logger logger = Logger . getLogger ( DefaultExecutors . class ) ; public static final String POOL_SIZE_PROPERTY = "" ; private int poolSize ; private ExecutorService poolExecutorService ; private ScheduledExecutorService scheduledExecutorService ; public DefaultExecutors ( ) { String poolSizeString = System . getProperty ( POOL_SIZE_PROPERTY ) ; if ( poolSizeString == null ) { poolSize = Runtime . getRuntime ( ) . availableProcessors ( ) + ; } else { poolSize = Integer . parseInt ( poolSizeString ) ; } } public synchronized void stop ( ) { ExecutorService scheduledExecutor ; ExecutorService poolExecutor ; synchronized ( this ) { scheduledExecutor = scheduledExecutorService ; scheduledExecutorService = null ; poolExecutor = poolExecutorService ; poolExecutorService = null ; } if ( poolExecutor != null ) { logger . info ( "" ) ; List < Runnable > running = poolExecutor . shutdownNow ( ) ; logger . info ( "" + running . size ( ) + "" ) ; } if ( scheduledExecutor != null ) { logger . info ( "" ) ; List < Runnable > running = scheduledExecutor . shutdownNow ( ) ; logger . info ( "" + running . size ( ) + "" ) ; } } public ScheduledExecutorService getScheduledExecutor ( ) { return startTimerOnFirstRequest ( ) ; } public ExecutorService getPoolExecutor ( ) { return startPoolExecutorOnFirstRequest ( ) ; } private synchronized ScheduledExecutorService startTimerOnFirstRequest ( ) { if ( scheduledExecutorService == null ) { logger . info ( "" + poolSize + "" ) ; scheduledExecutorService = new ScheduledThreadPoolExecutor ( poolSize ) ; } return scheduledExecutorService ; } private synchronized ExecutorService startPoolExecutorOnFirstRequest ( ) { if ( poolExecutorService == null ) { logger . info ( "" ) ; poolExecutorService = Executors . newCachedThreadPool ( ) ; } return poolExecutorService ; } public int getPoolSize ( ) { return poolSize ; } public void setPoolSize ( int poolSize ) { this . poolSize = poolSize ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + ( poolExecutorService == null ? "" : "" ) + "" ; } } package org . oddjob . scheduling ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import java . util . concurrent . Callable ; import java . util . concurrent . Delayed ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . Future ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import org . apache . log4j . Logger ; public class TrackingExecutor implements ScheduledExecutorService { static final Logger logger = Logger . getLogger ( TrackingExecutor . class ) ; private final ScheduledExecutorService executor ; private final List < Wrapper > running = new ArrayList < Wrapper > ( ) ; public int getTaskCount ( ) { synchronized ( running ) { return running . size ( ) ; } } public void waitForNothingOutstanding ( ) throws InterruptedException { synchronized ( running ) { while ( running . size ( ) > && ! executor . isShutdown ( ) ) { running . wait ( ) ; } } } public TrackingExecutor ( ScheduledExecutorService scheduler ) { this . executor = scheduler ; } public ScheduledFuture < ? > schedule ( Runnable command , long delay , TimeUnit unit ) { RunnableWrapper wrapper = wrapperFor ( command ) ; return scheduledFuture ( executor . schedule ( wrapper , delay , unit ) , wrapper ) ; } public < V > ScheduledFuture < V > schedule ( Callable < V > callable , long delay , TimeUnit unit ) { CallableWrapper < V > wrapper = wrapperFor ( callable ) ; return scheduledFuture ( executor . schedule ( wrapper , delay , unit ) , wrapper ) ; } public ScheduledFuture < ? > scheduleAtFixedRate ( Runnable command , long initialDelay , long period , TimeUnit unit ) { RunnableWrapper wrapper = wrapperFor ( command ) ; return scheduledFuture ( executor . scheduleAtFixedRate ( wrapper , initialDelay , period , unit ) , wrapper ) ; } public ScheduledFuture < ? > scheduleWithFixedDelay ( Runnable command , long initialDelay , long delay , TimeUnit unit ) { RunnableWrapper wrapper = wrapperFor ( command ) ; return scheduledFuture ( executor . scheduleWithFixedDelay ( wrapper , initialDelay , delay , unit ) , wrapper ) ; } public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { return executor . awaitTermination ( timeout , unit ) ; } public < T > List < Future < T > > invokeAll ( Collection < ? extends Callable < T > > tasks ) throws InterruptedException { throw new UnsupportedOperationException ( "" ) ; } public < T > List < Future < T > > invokeAll ( Collection < ? extends Callable < T > > tasks , long timeout , TimeUnit unit ) throws InterruptedException { throw new UnsupportedOperationException ( "" ) ; } public < T > T invokeAny ( Collection < ? extends Callable < T > > tasks ) throws InterruptedException , ExecutionException { throw new UnsupportedOperationException ( "" ) ; } public < T > T invokeAny ( Collection < ? extends Callable < T > > tasks , long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { throw new UnsupportedOperationException ( "" ) ; } public boolean isShutdown ( ) { return executor . isShutdown ( ) ; } public boolean isTerminated ( ) { return executor . isTerminated ( ) ; } public void shutdown ( ) { executor . shutdown ( ) ; synchronized ( running ) { running . notifyAll ( ) ; } } public List < Runnable > shutdownNow ( ) { List < Runnable > outstanding = executor . shutdownNow ( ) ; synchronized ( running ) { running . notifyAll ( ) ; } return outstanding ; } public < T > Future < T > submit ( Callable < T > task ) { CallableWrapper < T > wrapper = wrapperFor ( task ) ; return future ( executor . submit ( wrapper ) , wrapper ) ; } public Future < ? > submit ( Runnable task ) { RunnableWrapper wrapper = wrapperFor ( task ) ; return future ( executor . submit ( wrapper ) , wrapper ) ; } public < T > Future < T > submit ( Runnable task , T result ) { RunnableWrapper wrapper = wrapperFor ( task ) ; return future ( executor . submit ( wrapper , result ) , wrapper ) ; } public void execute ( Runnable command ) { executor . execute ( wrapperFor ( command ) ) ; } private RunnableWrapper wrapperFor ( Runnable command ) { synchronized ( running ) { RunnableWrapper wrapper = new RunnableWrapper ( command ) ; running . add ( wrapper ) ; return wrapper ; } } private < X > CallableWrapper < X > wrapperFor ( Callable < X > callable ) { synchronized ( running ) { CallableWrapper < X > wrapper = new CallableWrapper < X > ( callable ) ; running . add ( wrapper ) ; return wrapper ; } } interface Wrapper { } class RunnableWrapper implements Runnable , Wrapper { private final Runnable runnable ; public RunnableWrapper ( Runnable runnable ) { this . runnable = runnable ; } public void run ( ) { try { runnable . run ( ) ; } finally { synchronized ( running ) { running . remove ( this ) ; running . notifyAll ( ) ; } } } } class CallableWrapper < V > implements Callable < V > , Wrapper { private final Callable < V > callable ; public CallableWrapper ( Callable < V > callable ) { this . callable = callable ; } public V call ( ) throws Exception { try { return callable . call ( ) ; } finally { synchronized ( running ) { running . remove ( this ) ; running . notifyAll ( ) ; } } } } private < T > Future < T > future ( Future < T > wrapping , Wrapper wrapper ) { return new FutureWrapper < T > ( wrapping , wrapper ) ; } class FutureWrapper < V > implements Future < V > { private final Future < V > wrapping ; private final Wrapper wrapper ; public FutureWrapper ( Future < V > wrapping , Wrapper wrapper ) { this . wrapping = wrapping ; this . wrapper = wrapper ; } public boolean cancel ( boolean mayInterruptIfRunning ) { if ( wrapping . cancel ( mayInterruptIfRunning ) ) { synchronized ( running ) { running . remove ( wrapper ) ; } return true ; } else { return false ; } } public V get ( ) throws InterruptedException , ExecutionException { return wrapping . get ( ) ; } public V get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { return wrapping . get ( timeout , unit ) ; } public boolean isCancelled ( ) { return wrapping . isCancelled ( ) ; } public boolean isDone ( ) { return wrapping . isDone ( ) ; } } private < T > ScheduledFuture < T > scheduledFuture ( ScheduledFuture < T > wrapping , Wrapper wrapper ) { return new ScheduledFutureWrapper < T > ( wrapping , wrapper ) ; } class ScheduledFutureWrapper < V > extends FutureWrapper < V > implements ScheduledFuture < V > { private final ScheduledFuture < V > wrapping ; public ScheduledFutureWrapper ( ScheduledFuture < V > wrapping , Wrapper wrapper ) { super ( wrapping , wrapper ) ; this . wrapping = wrapping ; } public int compareTo ( Delayed o ) { return wrapping . compareTo ( o ) ; } public long getDelay ( TimeUnit unit ) { return wrapping . getDelay ( unit ) ; } } } package org . oddjob . scheduling ; import java . util . concurrent . ExecutorService ; import javax . inject . Inject ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . types . ValueFactory ; public class ExecutorThrottleType implements ValueFactory < ExecutorService > { private int limit ; private ExecutorService original ; @ Override public ExecutorService toValue ( ) throws ArooaConversionException { if ( original == null ) { throw new ArooaConversionException ( "" ) ; } if ( limit < ) { throw new ArooaConversionException ( "" ) ; } return new ExecutorServiceThrottle ( original , limit ) ; } public int getLimit ( ) { return limit ; } public void setLimit ( int max ) { this . limit = max ; } public ExecutorService getOriginal ( ) { return original ; } @ Inject public void setOriginal ( ExecutorService original ) { this . original = original ; } @ Override public String toString ( ) { return "" + limit ; } } package org . oddjob . scheduling ; import java . util . Collections ; import java . util . Date ; import java . util . HashMap ; import java . util . Map ; import java . util . TimeZone ; import java . util . concurrent . Future ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . TimeUnit ; import javax . inject . Inject ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . images . IconHelper ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . ParentState ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . util . Clock ; import org . oddjob . util . DefaultClock ; abstract public class TimerBase extends ScheduleBase { private static final long serialVersionUID = ; private transient Schedule schedule ; private transient TimeZone timeZone ; private transient Clock clock ; private transient volatile Future < ? > future ; private transient ScheduledExecutorService scheduler ; protected final Map < Object , Object > contextData = Collections . synchronizedMap ( new HashMap < Object , Object > ( ) ) ; private volatile transient Date nextDue ; private volatile ScheduleResult current ; private Date lastDue ; @ ArooaHidden @ Inject public void setScheduleExecutorService ( ScheduledExecutorService scheduler ) { this . scheduler = scheduler ; } @ Override protected void begin ( ) throws ComponentPersistException { if ( schedule == null ) { throw new NullPointerException ( "" ) ; } if ( scheduler == null ) { throw new NullPointerException ( "" ) ; } if ( clock == null ) { clock = new DefaultClock ( ) ; } } protected void onStop ( ) { super . onStop ( ) ; Future < ? > future = this . future ; if ( future != null ) { future . cancel ( false ) ; future = null ; } } @ Override protected void postStop ( ) { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { getStateChanger ( ) . setState ( ParentState . READY ) ; } } ) ; } protected void onReset ( ) { contextData . clear ( ) ; nextDue = null ; current = null ; lastDue = null ; } public String getTimeZone ( ) { if ( timeZone == null ) { return null ; } return timeZone . getID ( ) ; } public void setTimeZone ( String timeZoneId ) { if ( timeZoneId == null ) { this . timeZone = null ; } else { this . timeZone = TimeZone . getTimeZone ( timeZoneId ) ; } } public void setSchedule ( Schedule schedule ) { this . schedule = schedule ; } public Schedule getSchedule ( ) { return schedule ; } @ ArooaHidden public void setReschedule ( Date reSchedule ) throws ComponentPersistException { if ( future != null ) { future . cancel ( true ) ; future = null ; } scheduleFrom ( reSchedule ) ; } protected void scheduleFrom ( Date date ) throws ComponentPersistException { logger ( ) . debug ( "" + date + "" ) ; if ( date == null ) { setNextDue ( null ) ; } else { ScheduleContext context = new ScheduleContext ( date , timeZone , contextData , getLimits ( ) ) ; current = schedule . nextDue ( context ) ; if ( current == null ) { setNextDue ( null ) ; } else { setNextDue ( current . getFromDate ( ) ) ; } } } public Clock getClock ( ) { if ( clock == null ) { clock = new DefaultClock ( ) ; } return clock ; } public void setClock ( Clock clock ) { this . clock = clock ; } public Date getNextDue ( ) { return nextDue ; } protected void setNextDue ( Date nextDue ) throws ComponentPersistException { Date oldNextDue = this . nextDue ; this . nextDue = nextDue ; firePropertyChange ( "" , oldNextDue , nextDue ) ; if ( nextDue == null ) { logger ( ) . info ( "" ) ; childStateReflector . start ( ) ; return ; } iconHelper . changeIcon ( IconHelper . SLEEPING ) ; save ( ) ; long delay = nextDue . getTime ( ) - getClock ( ) . getDate ( ) . getTime ( ) ; if ( delay < ) { delay = ; } future = scheduler . schedule ( new Execution ( ) , delay , TimeUnit . MILLISECONDS ) ; logger ( ) . info ( "" + nextDue + "" + DateHelper . formatMilliseconds ( delay ) + "" ) ; } public ScheduleResult getCurrent ( ) { return current ; } public Date getLastDue ( ) { return lastDue ; } @ ArooaComponent public synchronized void setJob ( Runnable job ) { if ( job == null ) { childHelper . removeChildAt ( ) ; } else { childHelper . insertChild ( , job ) ; } } abstract protected Interval getLimits ( ) ; abstract protected void rescheduleOn ( State state ) throws ComponentPersistException ; abstract protected void reset ( Resetable job ) ; class RescheduleStateListener implements StateListener { private final Thread executionThread ; private State state ; RescheduleStateListener ( Thread executionThread ) { this . executionThread = executionThread ; } synchronized void changeToActive ( ) { if ( state . isStoppable ( ) ) { iconHelper . changeIcon ( IconHelper . ACTIVE ) ; } } @ Override public void jobStateChange ( StateEvent event ) { state = event . getState ( ) ; if ( stop ) { event . getSource ( ) . removeStateListener ( this ) ; return ; } if ( state . isReady ( ) ) { return ; } if ( state . isStoppable ( ) ) { iconHelper . changeIcon ( IconHelper . EXECUTING ) ; return ; } synchronized ( this ) { if ( Thread . currentThread ( ) != executionThread ) { iconHelper . changeIcon ( IconHelper . ACTIVE ) ; } } event . getSource ( ) . removeStateListener ( this ) ; logger ( ) . debug ( "" + state + "" ) ; try { rescheduleOn ( state ) ; } catch ( final ComponentPersistException e ) { stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { getStateChanger ( ) . setStateException ( e ) ; } } ) ; } } } class Execution implements Runnable { public void run ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { Runnable job = childHelper . getChild ( ) ; if ( stop ) { logger ( ) . info ( "" + job + "" ) ; return ; } logger ( ) . info ( "" + job + "" + nextDue ) ; lastDue = nextDue ; if ( job != null ) { try { RescheduleStateListener rescheduleListner = new RescheduleStateListener ( Thread . currentThread ( ) ) ; if ( job instanceof Resetable ) { reset ( ( Resetable ) job ) ; } if ( job instanceof Stateful ) { ( ( Stateful ) job ) . addStateListener ( rescheduleListner ) ; } job . run ( ) ; rescheduleListner . changeToActive ( ) ; logger ( ) . info ( "" + job + "" ) ; } catch ( final Exception t ) { logger ( ) . error ( "" , t ) ; stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setStateException ( t ) ; } } ) ; } } else { logger ( ) . warn ( "" ) ; } } finally { ComponentBoundry . pop ( ) ; } } @ Override public String toString ( ) { return TimerBase . this . toString ( ) ; } } } package org . oddjob . scheduling ; import java . util . Date ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledThreadPoolExecutor ; import java . util . concurrent . TimeUnit ; import org . apache . log4j . Logger ; import org . oddjob . OddjobExecutors ; public class OddjobTimerService implements OddjobExecutors { private static final long serialVersionUID = ; private static final Logger logger = Logger . getLogger ( OddjobTimerService . class ) ; private transient String name ; private transient ScheduledExecutorService scheduler ; private int poolSize = ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public ExecutorService getPoolExecutor ( ) { return new UnstoppableExecutor ( scheduler ) ; } public ScheduledExecutorService getScheduledExecutor ( ) { return new UnstoppableExecutor ( scheduler ) ; } public void start ( ) { scheduler = new ScheduledThreadPoolExecutor ( poolSize ) ; } public void stop ( ) { logger . debug ( "" ) ; scheduler . shutdownNow ( ) ; try { while ( ! scheduler . awaitTermination ( , TimeUnit . SECONDS ) ) { logger . debug ( "" ) ; } } catch ( InterruptedException e ) { logger . warn ( "" ) ; } scheduler = null ; } public Date getTimeNow ( ) { return new Date ( ) ; } public int getPoolSize ( ) { return poolSize ; } public void setPoolSize ( int poolSize ) { this . poolSize = poolSize ; } public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } return name ; } } package org . oddjob . scheduling ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . designer . components . BaseDC ; public class RetryDesFa implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new RetryDesign ( element , parentContext ) ; } } class RetryDesign extends BaseDC { private final SimpleDesignProperty schedule ; private final SimpleTextAttribute timeZone ; private final SimpleTextAttribute limits ; private final SimpleTextAttribute clock ; private final SimpleDesignProperty job ; public RetryDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; schedule = new SimpleDesignProperty ( "" , this ) ; timeZone = new SimpleTextAttribute ( "" , this ) ; limits = new SimpleTextAttribute ( "" , this ) ; clock = new SimpleTextAttribute ( "" , this ) ; job = new SimpleDesignProperty ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , schedule , timeZone , limits , clock , job } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( schedule . view ( ) . setTitle ( "" ) ) . add ( timeZone . view ( ) . setTitle ( "" ) ) . add ( limits . view ( ) . setTitle ( "" ) ) . add ( clock . view ( ) . setTitle ( "" ) ) . add ( job . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . scheduling ; import java . util . Date ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Future ; import javax . inject . Inject ; import org . oddjob . Stateful ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . framework . JobDestroyedException ; import org . oddjob . images . IconHelper ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateListener ; import org . oddjob . state . StateCondition ; import org . oddjob . state . StateConditions ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; public class Trigger extends ScheduleBase { private static final long serialVersionUID = ; private transient Stateful on ; private StateCondition state = StateConditions . COMPLETE ; private StateCondition cancelWhen ; private Date lastTime ; private boolean newOnly ; private transient ExecutorService executors ; private transient Future < ? > future ; private transient StateListener listener ; @ ArooaHidden @ Inject public void setExecutorService ( ExecutorService executor ) { this . executors = executor ; } @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } @ Override protected void begin ( ) { if ( on == null ) { throw new NullPointerException ( "" ) ; } if ( executors == null ) { throw new NullPointerException ( "" ) ; } listener = new TriggerStateListener ( ) ; on . addStateListener ( listener ) ; logger ( ) . info ( "" + on + "" + state + "" ) ; } @ Override protected void onStop ( ) { Future < ? > future = null ; synchronized ( this ) { future = this . future ; this . future = null ; } if ( future != null ) { future . cancel ( false ) ; } removeListener ( ) ; } @ Override protected void postStop ( ) { childStateReflector . start ( ) ; } private void removeListener ( ) { StateListener listener = null ; synchronized ( this ) { listener = this . listener ; this . listener = null ; } if ( listener != null ) { on . removeStateListener ( listener ) ; } } @ ArooaComponent public synchronized void setJob ( Runnable job ) { if ( job == null ) { childHelper . removeChildAt ( ) ; } else { childHelper . insertChild ( , job ) ; } } public StateCondition getState ( ) { return state ; } @ ArooaAttribute public void setState ( StateCondition state ) { this . state = state ; } public StateCondition getCancelWhen ( ) { return cancelWhen ; } @ ArooaAttribute public void setCancelWhen ( StateCondition cancelWhen ) { this . cancelWhen = cancelWhen ; } public boolean isNewOnly ( ) { return newOnly ; } public void setNewOnly ( boolean newEventOnly ) { this . newOnly = newEventOnly ; } public Stateful getOn ( ) { return on ; } @ ArooaAttribute public void setOn ( Stateful triggerOn ) { this . on = triggerOn ; } class Execution implements Runnable { public void run ( ) { ComponentBoundry . push ( loggerName ( ) , Trigger . this ) ; try { logger ( ) . info ( "" ) ; on . lastStateEvent ( ) ; iconHelper . changeIcon ( IconHelper . EXECUTING ) ; Runnable job = childHelper . getChild ( ) ; if ( job != null ) { try { job . run ( ) ; save ( ) ; } catch ( Throwable t ) { logger ( ) . error ( "" , t ) ; } } childStateReflector . start ( ) ; } finally { ComponentBoundry . pop ( ) ; } } } class TriggerStateListener implements StateListener { @ Override public synchronized void jobStateChange ( StateEvent event ) { logger ( ) . debug ( "" + on + "" + event . getState ( ) + "" + event . getTime ( ) ) ; if ( event . getState ( ) . isDestroyed ( ) ) { stateHandler ( ) . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { @ Override public void run ( ) { getStateChanger ( ) . setStateException ( new JobDestroyedException ( on ) ) ; } } ) ; on = null ; } if ( ! state . test ( event . getState ( ) ) && ( cancelWhen == null || ! cancelWhen . test ( event . getState ( ) ) ) ) { logger ( ) . debug ( "" ) ; return ; } if ( newOnly && event . getTime ( ) . equals ( lastTime ) ) { logger ( ) . info ( "" + event . getTime ( ) + "" ) ; return ; } lastTime = event . getTime ( ) ; removeListener ( ) ; if ( state . test ( event . getState ( ) ) ) { logger ( ) . debug ( "" + childHelper . getChild ( ) + "" ) ; future = executors . submit ( new Execution ( ) ) ; } else { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ParentState . COMPLETE ) ; } } ) ; } } ; } } package org . oddjob . scheduling ; import java . io . IOException ; import java . io . NotSerializableException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryCrawler ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . Path ; public class JobToken implements Serializable { private static final long serialVersionUID = ; private final transient Object job ; private final String path ; private JobToken ( String path , Object job ) { this . path = path ; this . job = job ; } public static JobToken create ( BeanRegistry registry , Object job ) { if ( job == null ) { throw new NullPointerException ( "" ) ; } if ( registry == null ) { return new JobToken ( null , job ) ; } BeanDirectoryCrawler crawler = new BeanDirectoryCrawler ( registry ) ; Path path = crawler . pathForObject ( job ) ; if ( path == null ) { throw new NullPointerException ( "" + job + "" ) ; } return new JobToken ( path . toString ( ) , job ) ; } public static Object retrieve ( BeanDirectory registry , JobToken token ) throws ArooaPropertyException { if ( token . path != null ) { return registry . lookup ( token . path ) ; } return token . job ; } private void writeObject ( ObjectOutputStream s ) throws IOException { if ( path == null ) { throw new NotSerializableException ( "" ) ; } s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; } public String toString ( ) { if ( path != null ) { return "" + path ; } else { return job . toString ( ) ; } } } package org . oddjob . scheduling ; import java . util . concurrent . CancellationException ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . Future ; import org . apache . log4j . Logger ; class SimpleFuture { private static final Logger logger = Logger . getLogger ( SimpleFuture . class ) ; private final RunnableWrapper wrapper ; private final Future < ? > future ; SimpleFuture ( RunnableWrapper wrapper , Future < ? > future ) { this . wrapper = wrapper ; this . future = future ; } public void cancel ( ) { if ( wrapper . isRunning ( ) ) { for ( int i = ; i < ; ++ i ) { if ( ! wrapper . interrupt ( ) ) { logger . info ( "" + wrapper + "" ) ; break ; } logger . info ( "" + wrapper + "" ) ; synchronized ( this ) { try { wait ( ) ; } catch ( InterruptedException e ) { logger . warn ( "" + wrapper + "" ) ; } } } if ( wrapper . isRunning ( ) ) { logger . warn ( "" + wrapper + "" ) ; } } else { if ( ! future . isDone ( ) ) { future . cancel ( true ) ; logger . info ( "" + wrapper + "" ) ; } } } public void waitFor ( ) { try { future . get ( ) ; } catch ( InterruptedException e ) { logger . info ( "" + wrapper + "" ) ; } catch ( CancellationException e ) { logger . info ( "" + wrapper + "" ) ; } catch ( ExecutionException e ) { logger . error ( "" + wrapper + "" , e ) ; } } } package org . oddjob . scheduling ; import java . io . Serializable ; import java . util . LinkedHashMap ; import java . util . Map ; public class ScheduleSummary implements Serializable { private static final long serialVersionUID = ; private String id ; private Map < String , String > description = new LinkedHashMap < String , String > ( ) ; public String getId ( ) { return id ; } public void setId ( String id ) { this . id = id ; } public Map < String , String > getDescription ( ) { return description ; } public void setDescription ( Map < String , String > description ) { this . description = description ; } } package org . oddjob . scheduling ; public interface WinningOutcome extends Outcome { public void complete ( ) ; } package org . oddjob . scheduling ; import java . util . Date ; import org . oddjob . Resetable ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . schedules . Interval ; import org . oddjob . state . CompleteOrNotOp ; import org . oddjob . state . State ; import org . oddjob . state . StateOperator ; public class Retry extends TimerBase { private static final long serialVersionUID = ; private Interval limits ; @ Override protected StateOperator getStateOp ( ) { return new CompleteOrNotOp ( ) ; } @ Override protected void begin ( ) throws ComponentPersistException { super . begin ( ) ; contextData . clear ( ) ; Date use = getClock ( ) . getDate ( ) ; if ( getLimits ( ) != null && use . compareTo ( getLimits ( ) . getToDate ( ) ) >= ) { use = getLimits ( ) . getFromDate ( ) ; } scheduleFrom ( use ) ; } @ ArooaAttribute public void setLimits ( Interval limits ) { this . limits = limits ; } @ Override public Interval getLimits ( ) { return limits ; } @ Override protected void rescheduleOn ( State state ) throws ComponentPersistException { State completeOrNot = new CompleteOrNotOp ( ) . evaluate ( state ) ; if ( completeOrNot . isComplete ( ) ) { setNextDue ( null ) ; } else { Date use = getCurrent ( ) . getUseNext ( ) ; Date now = getClock ( ) . getDate ( ) ; if ( use != null && use . before ( now ) ) { use = now ; } scheduleFrom ( use ) ; } } @ Override protected void reset ( Resetable job ) { logger ( ) . debug ( "" + job + "" ) ; job . softReset ( ) ; } } package org . oddjob . scheduling ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . etc . ReferenceAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TextField ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . designer . components . BaseDC ; public class TriggerDesFa implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new TriggerDesign ( element , parentContext ) ; } } class TriggerDesign extends BaseDC { private final ReferenceAttribute on ; ; private final SimpleTextAttribute state ; private final SimpleTextAttribute cancelWhen ; private final SimpleTextAttribute newOnly ; private final SimpleDesignProperty job ; public TriggerDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; on = new ReferenceAttribute ( "" , this ) ; state = new SimpleTextAttribute ( "" , this ) ; cancelWhen = new SimpleTextAttribute ( "" , this ) ; newOnly = new SimpleTextAttribute ( "" , this ) ; job = new SimpleDesignProperty ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , on , state , cancelWhen , newOnly , job } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( new TextField ( "" , on ) ) . add ( new TextField ( "" , state ) ) . add ( new TextField ( "" , cancelWhen ) ) . add ( new TextField ( "" , newOnly ) ) . add ( job . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . scheduling ; import java . util . Date ; import org . oddjob . Resetable ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . jobs . GrabJob ; import org . oddjob . persist . ArchiveJob ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . schedules . BrokenSchedule ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . DailySchedule ; import org . oddjob . schedules . schedules . DateSchedule ; import org . oddjob . schedules . schedules . DayAfterSchedule ; import org . oddjob . schedules . schedules . DayBeforeSchedule ; import org . oddjob . schedules . schedules . IntervalSchedule ; import org . oddjob . schedules . schedules . MonthlySchedule ; import org . oddjob . schedules . schedules . TimeSchedule ; import org . oddjob . schedules . schedules . WeeklySchedule ; import org . oddjob . schedules . schedules . YearlySchedule ; import org . oddjob . state . CompleteOrNotOp ; import org . oddjob . state . State ; import org . oddjob . state . StateOperator ; public class Timer extends TimerBase { private static final long serialVersionUID = ; private boolean haltOnFailure ; private boolean skipMissedRuns ; @ Override protected StateOperator getStateOp ( ) { return new CompleteOrNotOp ( ) ; } @ Override protected void begin ( ) throws ComponentPersistException { super . begin ( ) ; Date currentTime = getClock ( ) . getDate ( ) ; Interval currentInterval = getCurrent ( ) ; if ( currentInterval != null && ( ! skipMissedRuns || skipMissedRuns && currentTime . before ( currentInterval . getToDate ( ) ) ) ) { logger ( ) . info ( "" ) ; setNextDue ( currentInterval . getFromDate ( ) ) ; } else { logger ( ) . info ( "" ) ; scheduleFrom ( currentTime ) ; } } public void setHaltOnFailure ( boolean haltOnFailure ) { this . haltOnFailure = true ; } public boolean isHaltOnFailure ( ) { return haltOnFailure ; } public boolean isSkipMissedRuns ( ) { return skipMissedRuns ; } public void setSkipMissedRuns ( boolean skipMissedRuns ) { this . skipMissedRuns = skipMissedRuns ; } @ Override protected IntervalTo getLimits ( ) { return null ; } @ Override protected void rescheduleOn ( State state ) throws ComponentPersistException { State completeOrNot = new CompleteOrNotOp ( ) . evaluate ( state ) ; if ( ! ( completeOrNot . isComplete ( ) ) && haltOnFailure ) { setNextDue ( null ) ; } else { Date use = getCurrent ( ) . getUseNext ( ) ; Date now = getClock ( ) . getDate ( ) ; if ( use != null && skipMissedRuns && use . before ( now ) ) { use = now ; } scheduleFrom ( use ) ; } } protected void reset ( Resetable job ) { logger ( ) . debug ( "" + job + "" ) ; job . hardReset ( ) ; } } package org . oddjob . scheduling ; class RunnableWrapper implements Runnable { private final Runnable runnable ; private Thread t ; public RunnableWrapper ( Runnable runnable ) { this . runnable = runnable ; } public void run ( ) { synchronized ( this ) { t = Thread . currentThread ( ) ; } try { runnable . run ( ) ; } finally { synchronized ( this ) { t = null ; } } } public boolean interrupt ( ) { synchronized ( this ) { if ( t != null ) { t . interrupt ( ) ; return true ; } return false ; } } public boolean isRunning ( ) { synchronized ( this ) { return ( t != null ) ; } } @ Override public String toString ( ) { return runnable . toString ( ) ; } } package org . oddjob . scheduling ; import java . util . Collection ; import java . util . List ; import java . util . concurrent . Callable ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . Future ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; public class ScheduledExecutorServiceAdaptor implements ScheduledExecutorService { private final ScheduledExecutorService delegate ; public ScheduledExecutorServiceAdaptor ( ScheduledExecutorService delegate ) { this . delegate = delegate ; } public ScheduledFuture < ? > schedule ( Runnable command , long delay , TimeUnit unit ) { return delegate . schedule ( command , delay , unit ) ; } public < V > ScheduledFuture < V > schedule ( Callable < V > callable , long delay , TimeUnit unit ) { return delegate . schedule ( callable , delay , unit ) ; } public ScheduledFuture < ? > scheduleAtFixedRate ( Runnable command , long initialDelay , long period , TimeUnit unit ) { return delegate . scheduleAtFixedRate ( command , initialDelay , period , unit ) ; } public ScheduledFuture < ? > scheduleWithFixedDelay ( Runnable command , long initialDelay , long delay , TimeUnit unit ) { return delegate . scheduleWithFixedDelay ( command , initialDelay , delay , unit ) ; } public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { return delegate . awaitTermination ( timeout , unit ) ; } public < T > List < Future < T > > invokeAll ( Collection < ? extends Callable < T > > tasks ) throws InterruptedException { return delegate . invokeAll ( tasks ) ; } public < T > List < Future < T > > invokeAll ( Collection < ? extends Callable < T > > tasks , long timeout , TimeUnit unit ) throws InterruptedException { return delegate . invokeAll ( tasks , timeout , unit ) ; } public < T > T invokeAny ( Collection < ? extends Callable < T > > tasks ) throws InterruptedException , ExecutionException { return delegate . invokeAny ( tasks ) ; } public < T > T invokeAny ( Collection < ? extends Callable < T > > tasks , long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { return delegate . invokeAny ( tasks , timeout , unit ) ; } public boolean isShutdown ( ) { return delegate . isShutdown ( ) ; } public boolean isTerminated ( ) { return delegate . isTerminated ( ) ; } public void shutdown ( ) { delegate . shutdown ( ) ; } public List < Runnable > shutdownNow ( ) { return delegate . shutdownNow ( ) ; } public < T > Future < T > submit ( Callable < T > task ) { return delegate . submit ( task ) ; } public Future < ? > submit ( Runnable task ) { return delegate . submit ( task ) ; } public < T > Future < T > submit ( Runnable task , T result ) { return delegate . submit ( task , result ) ; } public void execute ( Runnable command ) { delegate . execute ( command ) ; } } package org . oddjob . scheduling ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . util . concurrent . atomic . AtomicReference ; import org . oddjob . FailedToStopException ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . framework . BasePrimary ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . framework . StopWait ; import org . oddjob . images . IconHelper ; import org . oddjob . images . StateIcons ; import org . oddjob . persist . Persistable ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsExecutable ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . OrderedStateChanger ; import org . oddjob . state . ParentState ; import org . oddjob . state . ParentStateChanger ; import org . oddjob . state . ParentStateHandler ; import org . oddjob . state . StateChanger ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateExchange ; import org . oddjob . state . StateOperator ; import org . oddjob . state . StructuralStateHelper ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public abstract class ScheduleBase extends BasePrimary implements Runnable , Stoppable , Serializable , Resetable , Stateful , Structural { private static final long serialVersionUID = ; protected transient ParentStateHandler stateHandler ; private transient ParentStateChanger stateChanger ; protected transient ChildHelper < Runnable > childHelper ; protected transient StructuralStateHelper structuralState ; protected transient StateExchange childStateReflector ; protected transient volatile boolean stop ; public ScheduleBase ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { stateHandler = new ParentStateHandler ( this ) ; childHelper = new ChildHelper < Runnable > ( this ) ; structuralState = new StructuralStateHelper ( childHelper , getStateOp ( ) ) ; stateChanger = new ParentStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; childStateReflector = new StateExchange ( structuralState , new OrderedStateChanger < ParentState > ( stateChanger , stateHandler ) ) ; } @ Override protected ParentStateHandler stateHandler ( ) { return stateHandler ; } protected StateChanger < ParentState > getStateChanger ( ) { return stateChanger ; } abstract protected StateOperator getStateOp ( ) ; abstract protected void begin ( ) throws ComponentPersistException ; public final void run ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { stop = false ; childStateReflector . stop ( ) ; getStateChanger ( ) . setState ( ParentState . EXECUTING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; try { configure ( ) ; iconHelper . changeIcon ( IconHelper . SLEEPING ) ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { stateHandler . setState ( ParentState . ACTIVE ) ; stateHandler . fireEvent ( ) ; } } ) ; begin ( ) ; } catch ( final Throwable e ) { logger ( ) . warn ( "" , e ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setStateException ( e ) ; } } ) ; } } finally { ComponentBoundry . pop ( ) ; } } public final void stop ( ) throws FailedToStopException { stateHandler . assertAlive ( ) ; ComponentBoundry . push ( loggerName ( ) , this ) ; try { final AtomicReference < String > lastIcon = new AtomicReference < String > ( ) ; if ( ! stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { @ Override public void run ( ) { stop = true ; stateHandler . wake ( ) ; lastIcon . set ( iconHelper . currentId ( ) ) ; iconHelper . changeIcon ( IconHelper . STOPPING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; onStop ( ) ; try { childHelper . stopChildren ( ) ; postStop ( ) ; new StopWait ( this ) . run ( ) ; } catch ( FailedToStopException e ) { iconHelper . changeIcon ( lastIcon . get ( ) ) ; logger ( ) . warn ( e ) ; } logger ( ) . info ( "" ) ; } finally { ComponentBoundry . pop ( ) ; } } protected void onStop ( ) { } protected void postStop ( ) { } public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; childStateReflector . stop ( ) ; childHelper . softResetChildren ( ) ; onReset ( ) ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; childStateReflector . stop ( ) ; childHelper . hardResetChildren ( ) ; onReset ( ) ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } protected void onReset ( ) { } public void addStructuralListener ( StructuralListener listener ) { stateHandler . assertAlive ( ) ; childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; s . writeObject ( getName ( ) ) ; if ( loggerName ( ) . startsWith ( getClass ( ) . getName ( ) ) ) { s . writeObject ( null ) ; } else { s . writeObject ( loggerName ( ) ) ; } s . writeObject ( stateHandler . lastStateEvent ( ) ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; String name = ( String ) s . readObject ( ) ; logger ( ( String ) s . readObject ( ) ) ; StateEvent savedEvent = ( StateEvent ) s . readObject ( ) ; completeConstruction ( ) ; setName ( name ) ; stateHandler . restoreLastJobStateEvent ( savedEvent ) ; iconHelper . changeIcon ( StateIcons . iconFor ( stateHandler . getState ( ) ) ) ; } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; try { stop ( ) ; } catch ( FailedToStopException e ) { logger ( ) . warn ( e ) ; } childStateReflector . stop ( ) ; } protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( ParentState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + ScheduleBase . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . scheduling ; import org . oddjob . Stateful ; public interface LoosingOutcome extends Outcome , Stateful { } package org . oddjob . scheduling ; import java . util . List ; import java . util . concurrent . ScheduledExecutorService ; public class UnstoppableExecutor extends ScheduledExecutorServiceAdaptor { public UnstoppableExecutor ( ScheduledExecutorService delegate ) { super ( delegate ) ; } @ Override public void shutdown ( ) { throw new UnsupportedOperationException ( "" ) ; } @ Override public List < Runnable > shutdownNow ( ) { throw new UnsupportedOperationException ( "" ) ; } } package org . oddjob . scheduling ; import java . util . LinkedList ; import java . util . List ; import java . util . concurrent . AbstractExecutorService ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . atomic . AtomicInteger ; public class ExecutorServiceThrottle extends AbstractExecutorService { private final ExecutorService executor ; private final LinkedList < Runnable > work = new LinkedList < Runnable > ( ) ; private final int threads ; private final AtomicInteger count = new AtomicInteger ( ) ; public ExecutorServiceThrottle ( ExecutorService delegate , int threads ) { this . executor = delegate ; this . threads = threads ; } @ Override public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { throw new UnsupportedOperationException ( ) ; } @ Override public boolean isShutdown ( ) { return executor . isShutdown ( ) ; } @ Override public boolean isTerminated ( ) { return executor . isTerminated ( ) ; } @ Override public void shutdown ( ) { throw new UnsupportedOperationException ( ) ; } @ Override public List < Runnable > shutdownNow ( ) { throw new UnsupportedOperationException ( ) ; } @ Override public void execute ( final Runnable command ) { synchronized ( work ) { work . add ( new Runnable ( ) { @ Override public void run ( ) { try { command . run ( ) ; } finally { count . decrementAndGet ( ) ; submit ( ) ; } } } ) ; } submit ( ) ; } private void submit ( ) { synchronized ( work ) { if ( work . isEmpty ( ) ) { return ; } if ( executor . isShutdown ( ) ) { work . clear ( ) ; return ; } if ( count . get ( ) < threads ) { count . incrementAndGet ( ) ; Runnable command = work . removeFirst ( ) ; executor . execute ( command ) ; } } } } package org . oddjob . scheduling ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignProperty ; import org . oddjob . arooa . design . SimpleDesignProperty ; import org . oddjob . arooa . design . SimpleTextAttribute ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . designer . components . BaseDC ; public class TimerDesFa implements DesignFactory { public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) { return new TimerDesign ( element , parentContext ) ; } } class TimerDesign extends BaseDC { private final SimpleDesignProperty schedule ; private final SimpleTextAttribute timeZone ; private final SimpleTextAttribute haltOnFailure ; private final SimpleTextAttribute skipMissedRuns ; private final SimpleTextAttribute clock ; private final SimpleDesignProperty job ; public TimerDesign ( ArooaElement element , ArooaContext parentContext ) { super ( element , parentContext ) ; schedule = new SimpleDesignProperty ( "" , this ) ; timeZone = new SimpleTextAttribute ( "" , this ) ; haltOnFailure = new SimpleTextAttribute ( "" , this ) ; skipMissedRuns = new SimpleTextAttribute ( "" , this ) ; clock = new SimpleTextAttribute ( "" , this ) ; job = new SimpleDesignProperty ( "" , this ) ; } public DesignProperty [ ] children ( ) { return new DesignProperty [ ] { name , schedule , timeZone , haltOnFailure , skipMissedRuns , clock , job } ; } public Form detail ( ) { return new StandardForm ( this ) . addFormItem ( basePanel ( ) ) . addFormItem ( new BorderedGroup ( "" ) . add ( schedule . view ( ) . setTitle ( "" ) ) . add ( timeZone . view ( ) . setTitle ( "" ) ) . add ( haltOnFailure . view ( ) . setTitle ( "" ) ) . add ( skipMissedRuns . view ( ) . setTitle ( "" ) ) . add ( clock . view ( ) . setTitle ( "" ) ) . add ( job . view ( ) . setTitle ( "" ) ) ) ; } } package org . oddjob . scheduling ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . ScheduledExecutorService ; import org . oddjob . OddjobExecutors ; import org . oddjob . OddjobServices ; import org . oddjob . input . InputHandler ; public class OddjobServicesBean implements OddjobServices { private ClassLoader classLoader ; private OddjobExecutors oddjobExecutors ; private InputHandler inputHandler ; @ Override public Object getService ( String serviceName ) { if ( CLASSLOADER_SERVICE . equals ( serviceName ) ) { return classLoader ; } if ( SCHEDULED_EXECUTOR . equals ( serviceName ) && oddjobExecutors != null ) { return oddjobExecutors . getScheduledExecutor ( ) ; } else if ( POOL_EXECUTOR . equals ( serviceName ) && oddjobExecutors != null ) { return oddjobExecutors . getPoolExecutor ( ) ; } else if ( INPUT_HANDLER . equals ( serviceName ) ) { return inputHandler ; } else if ( ODDJOB_SERVICES . equals ( serviceName ) ) { return this ; } throw new IllegalArgumentException ( "" + serviceName ) ; } @ Override public String serviceNameFor ( Class < ? > theClass , String flavour ) { if ( theClass . isAssignableFrom ( ClassLoader . class ) ) { return CLASSLOADER_SERVICE ; } else if ( theClass . isAssignableFrom ( ExecutorService . class ) ) { return POOL_EXECUTOR ; } else if ( theClass . isAssignableFrom ( ScheduledExecutorService . class ) ) { return SCHEDULED_EXECUTOR ; } else if ( theClass . isAssignableFrom ( InputHandler . class ) ) { return INPUT_HANDLER ; } else if ( theClass . isAssignableFrom ( OddjobServices . class ) ) { return ODDJOB_SERVICES ; } else { return null ; } } @ Override public ClassLoader getClassLoader ( ) { return classLoader ; } public void setClassLoader ( ClassLoader classLoader ) { this . classLoader = classLoader ; } @ Override public OddjobExecutors getOddjobExecutors ( ) { return oddjobExecutors ; } public void setOddjobExecutors ( OddjobExecutors oddjobExecutors ) { this . oddjobExecutors = oddjobExecutors ; } public InputHandler getInputHandler ( ) { return inputHandler ; } public void setInputHandler ( InputHandler inputHandler ) { this . inputHandler = inputHandler ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) ; } } package org . oddjob . scheduling ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledThreadPoolExecutor ; import org . oddjob . OddjobExecutors ; public class TrackingServices implements OddjobExecutors { private final TrackingExecutor executor ; public TrackingServices ( int poolSize ) { executor = new TrackingExecutor ( new ScheduledThreadPoolExecutor ( poolSize ) ) ; } public ExecutorService getPoolExecutor ( ) { return executor ; } public ScheduledExecutorService getScheduledExecutor ( ) { return executor ; } public void stop ( ) throws InterruptedException { executor . waitForNothingOutstanding ( ) ; executor . shutdown ( ) ; } } package org . oddjob . scheduling ; import org . oddjob . jobs . GrabJob ; public interface Keeper { public Outcome grab ( String ourIdentifier , Object instanceIdentifier ) ; } package org . oddjob ; import java . util . Properties ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . deploy . ArooaDescriptorFactory ; import org . oddjob . arooa . deploy . EmptyDescriptor ; import org . oddjob . arooa . deploy . LinkedDescriptor ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . life . ComponentProxyResolver ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . registry . SimpleComponentPool ; import org . oddjob . arooa . runtime . PropertyManager ; import org . oddjob . arooa . standard . ExtendedTools ; import org . oddjob . arooa . standard . StandardArooaDescriptor ; import org . oddjob . arooa . standard . StandardPropertyManager ; import org . oddjob . arooa . standard . StandardTools ; import org . oddjob . persist . OddjobPersister ; public class OddjobSessionFactory { private ArooaSession existingSession ; private ClassLoader classLoader ; private ArooaDescriptorFactory descriptorFactory ; private OddjobPersister oddjobPersister ; private Properties properties ; private OddjobInheritance inherit ; public ArooaSession createSession ( ) { return createSession ( null ) ; } public ArooaSession createSession ( Object oddjob ) { String propertySourceName = "" ; if ( oddjob != null ) { propertySourceName = oddjob . toString ( ) ; } ComponentProxyResolver componentProxyResolver = null ; ClassLoader classLoader = this . classLoader ; if ( classLoader == null ) { classLoader = getClass ( ) . getClassLoader ( ) ; } ArooaDescriptor descriptor = null ; if ( descriptorFactory != null ) { descriptor = descriptorFactory . createDescriptor ( classLoader ) ; } ComponentPersister componentPersister = null ; String oddjobId = null ; if ( existingSession != null ) { oddjobId = existingSession . getBeanRegistry ( ) . getIdFor ( oddjob ) ; } if ( oddjobPersister != null ) { componentPersister = oddjobPersister . persisterFor ( oddjobId ) ; } ArooaTools tools = null ; PropertyManager propertyManager = null ; BeanRegistry beanRegistry = null ; if ( existingSession == null ) { ArooaDescriptor mainDescriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( classLoader ) ; ArooaDescriptor oddjobDescriptor = new LinkedDescriptor ( mainDescriptor , new StandardArooaDescriptor ( ) ) ; if ( descriptor == null ) { descriptor = oddjobDescriptor ; } else { descriptor = new LinkedDescriptor ( descriptor , oddjobDescriptor ) ; } tools = new ExtendedTools ( new StandardTools ( ) , descriptor ) ; } else { tools = existingSession . getTools ( ) ; if ( this . classLoader != null && descriptor == null ) { descriptor = new EmptyDescriptor ( classLoader ) ; } if ( descriptor == null ) { descriptor = existingSession . getArooaDescriptor ( ) ; if ( descriptor == null ) { throw new NullPointerException ( "" ) ; } } else { descriptor = new LinkedDescriptor ( descriptor , existingSession . getArooaDescriptor ( ) ) ; tools = new ExtendedTools ( tools , descriptor ) ; } componentProxyResolver = existingSession . getComponentProxyResolver ( ) ; if ( componentPersister == null && oddjobId != null ) { componentPersister = existingSession . getComponentPersister ( ) ; if ( componentPersister instanceof OddjobPersister ) { componentPersister = ( ( OddjobPersister ) componentPersister ) . persisterFor ( oddjobId ) ; } } if ( inherit == null ) { inherit = OddjobInheritance . PROPERTIES ; } switch ( inherit ) { case NONE : propertyManager = new StandardPropertyManager ( properties , propertySourceName ) ; break ; case PROPERTIES : propertyManager = new StandardPropertyManager ( existingSession . getPropertyManager ( ) , properties , propertySourceName ) ; break ; case SHARED : propertyManager = existingSession . getPropertyManager ( ) ; beanRegistry = existingSession . getBeanRegistry ( ) ; break ; } } if ( componentProxyResolver == null ) { componentProxyResolver = new OddjobComponentResolver ( ) ; } if ( propertyManager == null ) { propertyManager = new StandardPropertyManager ( properties , propertySourceName ) ; } if ( beanRegistry == null ) { beanRegistry = new SimpleBeanRegistry ( tools . getPropertyAccessor ( ) , tools . getArooaConverter ( ) ) ; } final ArooaDescriptor finalDescriptor = descriptor ; final ComponentPool finalComponentPool = new SimpleComponentPool ( ) ; final ArooaTools finalTools = tools ; final BeanRegistry finalBeanRegistry = beanRegistry ; final ComponentPersister finalComponentPersister = componentPersister ; final ComponentProxyResolver finalComponentProxyResolver = componentProxyResolver ; final PropertyManager finalPropertyManager = propertyManager ; return new ArooaSession ( ) { @ Override public ArooaDescriptor getArooaDescriptor ( ) { return finalDescriptor ; } @ Override public ComponentPool getComponentPool ( ) { return finalComponentPool ; } @ Override public BeanRegistry getBeanRegistry ( ) { return finalBeanRegistry ; } @ Override public PropertyManager getPropertyManager ( ) { return finalPropertyManager ; } @ Override public ArooaTools getTools ( ) { return finalTools ; } @ Override public ComponentPersister getComponentPersister ( ) { return finalComponentPersister ; } @ Override public ComponentProxyResolver getComponentProxyResolver ( ) { return finalComponentProxyResolver ; } } ; } public ArooaSession getExistingSession ( ) { return existingSession ; } public void setExistingSession ( ArooaSession existingSession ) { this . existingSession = existingSession ; } public ClassLoader getClassLoader ( ) { return classLoader ; } public void setClassLoader ( ClassLoader classLoader ) { this . classLoader = classLoader ; } public ArooaDescriptorFactory getDescriptorFactory ( ) { return descriptorFactory ; } public void setDescriptorFactory ( ArooaDescriptorFactory descriptorFactory ) { this . descriptorFactory = descriptorFactory ; } public OddjobPersister getOddjobPersister ( ) { return oddjobPersister ; } public void setOddjobPersister ( OddjobPersister oddjobPersister ) { this . oddjobPersister = oddjobPersister ; } public Properties getProperties ( ) { return properties ; } public void setProperties ( Properties properties ) { this . properties = properties ; } public OddjobInheritance isInherit ( ) { return inherit ; } public void setInherit ( OddjobInheritance inherit ) { this . inherit = inherit ; } } package org . oddjob ; import org . oddjob . framework . JobDestroyedException ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public interface Stateful { public void addStateListener ( StateListener listener ) throws JobDestroyedException ; public void removeStateListener ( StateListener listener ) ; public StateEvent lastStateEvent ( ) ; } package org . oddjob ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . Proxy ; import java . util . concurrent . Callable ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . ComponentProxyResolver ; import org . oddjob . framework . CallableProxyGenerator ; import org . oddjob . framework . ServiceStrategies ; import org . oddjob . framework . RunnableProxyGenerator ; import org . oddjob . framework . ServiceAdaptor ; import org . oddjob . framework . ServiceProxyGenerator ; import org . oddjob . framework . WrapperInvocationHandler ; public class OddjobComponentResolver implements ComponentProxyResolver { @ Override public Object resolve ( final Object component , ArooaSession session ) { Object proxy ; if ( component instanceof Stateful ) { proxy = component ; } else if ( component instanceof Callable ) { proxy = new CallableProxyGenerator ( ) . generate ( ( Callable < ? > ) component , component . getClass ( ) . getClassLoader ( ) ) ; } else if ( component instanceof Runnable ) { proxy = new RunnableProxyGenerator ( ) . generate ( ( Runnable ) component , component . getClass ( ) . getClassLoader ( ) ) ; } else { ServiceAdaptor service = new ServiceStrategies ( ) . serviceFor ( component , session ) ; if ( service != null ) { proxy = new ServiceProxyGenerator ( ) . generate ( service , component . getClass ( ) . getClassLoader ( ) ) ; } else { proxy = component ; } } return proxy ; } @ Override public Object restore ( Object proxy , ArooaSession session ) { Object component ; if ( ! Proxy . isProxyClass ( proxy . getClass ( ) ) ) { component = proxy ; } else { InvocationHandler handler = Proxy . getInvocationHandler ( proxy ) ; component = ( ( WrapperInvocationHandler ) handler ) . getWrappedComponent ( ) ; } return component ; } } package org . oddjob . images ; public interface IconListener { public void iconEvent ( IconEvent e ) ; } package org . oddjob . images ; import java . io . Serializable ; import java . util . EventObject ; import org . oddjob . Iconic ; public class IconEvent extends EventObject implements Serializable { private static final long serialVersionUID = ; final private String id ; public IconEvent ( Iconic source , String iconId ) { super ( source ) ; this . id = iconId ; } public String getIconId ( ) { return id ; } @ Override public Iconic getSource ( ) { return ( Iconic ) super . getSource ( ) ; } } package org . oddjob . images ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import javax . swing . ImageIcon ; import org . oddjob . Iconic ; public class IconHelper implements Iconic { public static final String NULL = "" ; public static final String INITIALIZING = "" ; public static final String READY = "" ; public static final String EXECUTING = "" ; public static final String COMPLETE = "" ; public static final String NOT_COMPLETE = "" ; public static final String EXCEPTION = "" ; public static final String SLEEPING = "" ; public static final String STOPPING = "" ; public static final String STOPPED = "" ; public static final String STARTED = "" ; public static final String ACTIVE = "" ; public static final String INVALID = "" ; public static final ImageIcon nullIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon initializingIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon readyIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon executingIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon completeIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon notCompleteIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon stoppingIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon stoppedIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon sleepingIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon invalidIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon exceptionIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon startedIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; public static final ImageIcon activeIcon = new ImageIcon ( IconHelper . class . getResource ( "" ) , "" ) ; private static Map < String , ImageIcon > defaultIconMap = new HashMap < String , ImageIcon > ( ) ; static { defaultIconMap . put ( NULL , nullIcon ) ; defaultIconMap . put ( INITIALIZING , initializingIcon ) ; defaultIconMap . put ( READY , readyIcon ) ; defaultIconMap . put ( EXECUTING , executingIcon ) ; defaultIconMap . put ( COMPLETE , completeIcon ) ; defaultIconMap . put ( NOT_COMPLETE , notCompleteIcon ) ; defaultIconMap . put ( SLEEPING , sleepingIcon ) ; defaultIconMap . put ( STOPPING , stoppingIcon ) ; defaultIconMap . put ( STOPPED , stoppedIcon ) ; defaultIconMap . put ( INVALID , invalidIcon ) ; defaultIconMap . put ( EXCEPTION , exceptionIcon ) ; defaultIconMap . put ( STARTED , startedIcon ) ; defaultIconMap . put ( ACTIVE , activeIcon ) ; } private final Iconic source ; private volatile IconEvent lastEvent ; private List < IconListener > listeners = new ArrayList < IconListener > ( ) ; private final Map < String , ImageIcon > iconMap ; public IconHelper ( Iconic source ) { this ( source , defaultIconMap ) ; } public IconHelper ( Iconic source , Map < String , ImageIcon > iconMap ) { this . source = source ; lastEvent = new IconEvent ( source , READY ) ; this . iconMap = iconMap ; } @ Override public ImageIcon iconForId ( String iconId ) { return iconMap . get ( iconId ) ; } public void changeIcon ( String iconId ) { if ( iconId . equals ( lastEvent . getIconId ( ) ) ) { return ; } if ( ! iconMap . containsKey ( iconId ) ) { throw new IllegalArgumentException ( "" + iconId ) ; } IconEvent localEvent = new IconEvent ( source , iconId ) ; IconListener [ ] la = null ; synchronized ( listeners ) { lastEvent = localEvent ; la = ( IconListener [ ] ) listeners . toArray ( new IconListener [ ] ) ; } for ( int i = ; i < la . length ; ++ i ) { la [ i ] . iconEvent ( localEvent ) ; } } public String currentId ( ) { return lastEvent . getIconId ( ) ; } public void addIconListener ( IconListener listener ) { if ( lastEvent == null ) { throw new IllegalStateException ( "" + source ) ; } listener . iconEvent ( lastEvent ) ; synchronized ( listeners ) { listeners . add ( listener ) ; } } public void removeIconListener ( IconListener listener ) { synchronized ( listeners ) { listeners . remove ( listener ) ; } } } package org . oddjob . images ; import java . util . HashMap ; import java . util . Map ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; import org . oddjob . state . State ; public class StateIcons { private static final Map < State , String > iconIds = new HashMap < State , String > ( ) ; static { iconIds . put ( JobState . READY , IconHelper . READY ) ; iconIds . put ( JobState . EXECUTING , IconHelper . EXECUTING ) ; iconIds . put ( JobState . INCOMPLETE , IconHelper . NOT_COMPLETE ) ; iconIds . put ( JobState . COMPLETE , IconHelper . COMPLETE ) ; iconIds . put ( JobState . EXCEPTION , IconHelper . EXCEPTION ) ; iconIds . put ( JobState . DESTROYED , IconHelper . INVALID ) ; iconIds . put ( ParentState . READY , IconHelper . READY ) ; iconIds . put ( ParentState . EXECUTING , IconHelper . EXECUTING ) ; iconIds . put ( ParentState . ACTIVE , IconHelper . ACTIVE ) ; iconIds . put ( ParentState . INCOMPLETE , IconHelper . NOT_COMPLETE ) ; iconIds . put ( ParentState . COMPLETE , IconHelper . COMPLETE ) ; iconIds . put ( ParentState . EXCEPTION , IconHelper . EXCEPTION ) ; iconIds . put ( ParentState . DESTROYED , IconHelper . INVALID ) ; iconIds . put ( ServiceState . READY , IconHelper . READY ) ; iconIds . put ( ServiceState . STARTING , IconHelper . EXECUTING ) ; iconIds . put ( ServiceState . STARTED , IconHelper . STARTED ) ; iconIds . put ( ServiceState . COMPLETE , IconHelper . COMPLETE ) ; iconIds . put ( ServiceState . EXCEPTION , IconHelper . EXCEPTION ) ; iconIds . put ( ServiceState . DESTROYED , IconHelper . INVALID ) ; } public static String iconFor ( State state ) { String iconId = iconIds . get ( state ) ; if ( iconId == null ) { return IconHelper . NULL ; } return iconId ; } } package org . oddjob . oddballs ; import java . io . File ; public interface OddballFactory { public Oddball createFrom ( File file , ClassLoader parentLoader ) ; } package org . oddjob . oddballs ; import java . io . File ; import java . io . FilenameFilter ; import java . io . IOException ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLClassLoader ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . deploy . ClassPathDescriptorFactory ; import org . oddjob . arooa . deploy . ClassesOnlyDescriptor ; public class DirectoryOddball implements OddballFactory { private static final Logger logger = Logger . getLogger ( DirectoryOddball . class ) ; public Oddball createFrom ( final File file , ClassLoader parentLoader ) { if ( ! file . isDirectory ( ) ) { return null ; } URL [ ] urls = null ; try { urls = classpathURLs ( file ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } if ( urls . length == ) { return null ; } logger . info ( "" + file . getPath ( ) + "" ) ; final URLClassLoader classLoader = new URLClassLoader ( urls , parentLoader ) { @ Override public String toString ( ) { return "" + file . getPath ( ) ; } } ; ClassPathDescriptorFactory descriptorFactory = new ClassPathDescriptorFactory ( ) ; descriptorFactory . setExcludeParent ( true ) ; ArooaDescriptor maybeDescriptor = descriptorFactory . createDescriptor ( classLoader ) ; if ( maybeDescriptor == null ) { logger . debug ( "" ) ; maybeDescriptor = new ClassesOnlyDescriptor ( classLoader ) ; } final ArooaDescriptor descriptor = maybeDescriptor ; return new Oddball ( ) { public ClassLoader getClassLoader ( ) { return classLoader ; } public ArooaDescriptor getArooaDescriptor ( ) { return descriptor ; } } ; } URL [ ] classpathURLs ( File parent ) throws IOException { File [ ] jars = new File ( parent , "" ) . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( "" ) ; } } ) ; if ( jars == null ) { jars = new File [ ] ; } int offset ; URL [ ] urls ; File classesDir = new File ( parent , "" ) ; if ( classesDir . exists ( ) ) { urls = new URL [ jars . length + ] ; urls [ ] = classesDir . getCanonicalFile ( ) . toURI ( ) . toURL ( ) ; offset = ; } else { urls = new URL [ jars . length ] ; offset = ; } for ( int i = ; i < jars . length ; ++ i ) { urls [ i + offset ] = jars [ i ] . getCanonicalFile ( ) . toURI ( ) . toURL ( ) ; } return urls ; } } package org . oddjob . oddballs ; import java . io . File ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . deploy . ArooaDescriptorFactory ; public class OddballsDirDescriptorFactory implements ArooaDescriptorFactory { private static final Logger logger = Logger . getLogger ( OddballsDirDescriptorFactory . class ) ; private File baseDir ; private OddballFactory oddballFactory ; public OddballsDirDescriptorFactory ( ) { } public OddballsDirDescriptorFactory ( File baseDir ) { this . baseDir = baseDir ; } public File getBaseDir ( ) { return baseDir ; } public void setBaseDir ( File baseDir ) { this . baseDir = baseDir ; } public OddballFactory getOddballFactory ( ) { return oddballFactory ; } public void setOddballFactory ( OddballFactory oddballFactory ) { this . oddballFactory = oddballFactory ; } public ArooaDescriptor createDescriptor ( ClassLoader classLoader ) { if ( baseDir == null ) { throw new NullPointerException ( "" ) ; } logger . info ( "" + baseDir . getPath ( ) + "" ) ; File [ ] entries = baseDir . listFiles ( ) ; if ( entries == null ) { return null ; } return new OddballsDescriptorFactory ( entries , oddballFactory ) . createDescriptor ( classLoader ) ; } } package org . oddjob . oddballs ; import java . io . File ; import java . util . Arrays ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . deploy . ArooaDescriptorBean ; import org . oddjob . arooa . deploy . ArooaDescriptorFactory ; import org . oddjob . arooa . deploy . ListDescriptor ; public class OddballsDescriptorFactory implements ArooaDescriptorFactory { private static final Logger logger = Logger . getLogger ( OddballsDescriptorFactory . class ) ; private File [ ] files ; private OddballFactory oddballFactory ; public OddballsDescriptorFactory ( ) { this ( null , null ) ; } public OddballsDescriptorFactory ( File [ ] files ) { this ( files , null ) ; } public OddballsDescriptorFactory ( File [ ] files , OddballFactory oddballFactory ) { this . files = files ; this . oddballFactory = oddballFactory ; } public File [ ] getFiles ( ) { return files ; } public void setFiles ( File [ ] baseDir ) { this . files = baseDir ; } public OddballFactory getOddballFactory ( ) { return oddballFactory ; } public void setOddballFactory ( OddballFactory oddballFactory ) { this . oddballFactory = oddballFactory ; } public ArooaDescriptor createDescriptor ( ClassLoader classLoader ) { if ( files == null ) { throw new NullPointerException ( "" ) ; } OddballFactory oddballFactory = this . oddballFactory ; if ( oddballFactory == null ) { oddballFactory = new DirectoryOddball ( ) ; } ListDescriptor descriptor = new ListDescriptor ( ) ; for ( File file : files ) { Oddball oddball = oddballFactory . createFrom ( file , classLoader ) ; if ( oddball == null ) { continue ; } descriptor . addDescriptor ( oddball . getArooaDescriptor ( ) ) ; } if ( descriptor . size ( ) == ) { logger . info ( "" ) ; return null ; } else { return descriptor ; } } public String toString ( ) { return getClass ( ) . getName ( ) + "" + ( files == null ? "" : "" + Arrays . toString ( files ) ) ; } } package org . oddjob . oddballs ; import org . oddjob . arooa . ArooaDescriptor ; public interface Oddball { public ClassLoader getClassLoader ( ) ; public ArooaDescriptor getArooaDescriptor ( ) ; } package org . oddjob ; public class OddjobException extends RuntimeException { private static final long serialVersionUID = ; public OddjobException ( ) { super ( ) ; } public OddjobException ( String s , Throwable t ) { super ( s , t ) ; } public OddjobException ( Throwable t ) { super ( t ) ; } public OddjobException ( String s ) { super ( s ) ; } } package org . oddjob . rmi ; import java . rmi . registry . LocateRegistry ; import java . rmi . server . ExportException ; import org . oddjob . framework . SimpleJob ; public class RMIRegistryJob extends SimpleJob { public static final int DEFAULT_PORT = ; private int port = DEFAULT_PORT ; synchronized public void setPort ( int port ) { this . port = port ; } synchronized public int getPort ( ) { return this . port ; } public int execute ( ) throws Exception { try { LocateRegistry . createRegistry ( getPort ( ) ) ; } catch ( ExportException e ) { logger ( ) . info ( "" + e . getMessage ( ) ) ; } return ; } } package org . oddjob . framework ; import java . util . LinkedHashMap ; import java . util . Map ; import org . oddjob . arooa . registry . ServiceProvider ; import org . oddjob . arooa . registry . Services ; import org . oddjob . arooa . types . IsType ; public class ServicesJob extends SimpleJob implements ServiceProvider { private final Map < String , ServiceDefinition > services = new LinkedHashMap < String , ServiceDefinition > ( ) ; @ Override protected int execute ( ) throws Throwable { return ; } @ Override protected void onReset ( ) { services . clear ( ) ; } @ Override public Services getServices ( ) { return new Services ( ) { @ Override public Object getService ( String serviceName ) throws IllegalArgumentException { ServiceDefinition def = services . get ( serviceName ) ; if ( def == null ) { return null ; } return def . getService ( ) ; } @ Override public String serviceNameFor ( Class < ? > theClass , String flavour ) { String best = null ; for ( Map . Entry < String , ServiceDefinition > entry : services . entrySet ( ) ) { ServiceDefinition def = entry . getValue ( ) ; if ( theClass . isInstance ( def . getService ( ) ) ) { if ( flavour == null ) { if ( def . getQualifier ( ) == null || ! def . isIntransigent ( ) ) { return entry . getKey ( ) ; } else { continue ; } } if ( flavour . equals ( def . getQualifier ( ) ) ) { return entry . getKey ( ) ; } if ( ! def . isIntransigent ( ) ) { best = entry . getKey ( ) ; } } } return best ; } @ Override public String toString ( ) { return "" + services . size ( ) ; } } ; } public void setRegisteredServices ( int index , ServiceDefinition serviceDef ) { if ( serviceDef == null ) { return ; } Object service = serviceDef . getService ( ) ; if ( service == null ) { throw new NullPointerException ( "" ) ; } Object qualifier = serviceDef . getQualifier ( ) ; String serviceName = service . toString ( ) + ( qualifier == null ? "" : "" + qualifier . toString ( ) ) ; logger ( ) . info ( "" + serviceName + "" + service . getClass ( ) . getName ( ) ) ; services . put ( serviceName , serviceDef ) ; } public static class ServiceDefinition { private Object service ; private Object qualifier ; private boolean intransigent ; public Object getService ( ) { return service ; } public void setService ( Object service ) { this . service = service ; } public Object getQualifier ( ) { return qualifier ; } public void setQualifier ( Object qualifier ) { this . qualifier = qualifier ; } public boolean isIntransigent ( ) { return intransigent ; } public void setIntransigent ( boolean constrained ) { this . intransigent = constrained ; } } } package org . oddjob . framework ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import org . oddjob . Resetable ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . METHOD ) public @ interface SoftReset { } package org . oddjob . framework ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . logging . LogEnabled ; public abstract class BasePrimary extends BaseComponent implements LogEnabled { private static int instanceCount ; private Logger theLogger ; private String name ; protected Logger logger ( ) { if ( theLogger == null ) { int count = ; synchronized ( BaseComponent . class ) { count = instanceCount ++ ; } theLogger = Logger . getLogger ( this . getClass ( ) . getName ( ) + "" + count ) ; } return theLogger ; } protected void configure ( ) throws ArooaConfigurationException { configure ( this ) ; } protected void save ( ) throws ComponentPersistException { save ( this ) ; } synchronized public void setName ( String name ) { stateHandler ( ) . assertAlive ( ) ; String old = this . name ; this . name = name ; firePropertyChange ( "" , old , name ) ; } public String getName ( ) { return name ; } public String loggerName ( ) { return logger ( ) . getName ( ) ; } protected void logger ( String logger ) { if ( logger == null ) { return ; } if ( theLogger != null ) { theLogger . debug ( "" + logger + "" ) ; } theLogger = Logger . getLogger ( logger ) ; } public String toString ( ) { if ( getName ( ) == null ) { return getClass ( ) . getSimpleName ( ) ; } else { return getName ( ) ; } } } package org . oddjob . framework ; import java . lang . reflect . Method ; import org . oddjob . FailedToStopException ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . reflect . PropertyAccessor ; public class ServiceStrategies implements ServiceStrategy { @ Override public ServiceAdaptor serviceFor ( Object component , ArooaSession session ) { ServiceAdaptor adaptor = isServiceAlreadyStrategy ( ) . serviceFor ( component , session ) ; if ( adaptor == null ) { adaptor = hasServiceAnnotationsStrategy ( ) . serviceFor ( component , session ) ; } if ( adaptor == null ) { adaptor = hasServiceMethodsStrategy ( ) . serviceFor ( component , session ) ; } return adaptor ; } public ServiceStrategy isServiceAlreadyStrategy ( ) { return new ServiceStrategy ( ) { @ Override public ServiceAdaptor serviceFor ( Object component , ArooaSession session ) { if ( component instanceof Service ) { final Service service = ( Service ) component ; return new ServiceAdaptor ( ) { @ Override public void start ( ) throws Exception { service . start ( ) ; } @ Override public void stop ( ) throws FailedToStopException { service . stop ( ) ; } @ Override public Object getComponent ( ) { return service ; } } ; } else { return null ; } } } ; } public ServiceStrategy hasServiceMethodsStrategy ( ) { return new ServiceStrategy ( ) { @ Override public ServiceMethodAdaptor serviceFor ( Object component , ArooaSession session ) { Class < ? > cl = component . getClass ( ) ; try { Method startMethod = cl . getDeclaredMethod ( "" , new Class [ ] ) ; if ( startMethod . getReturnType ( ) != Void . TYPE ) { return null ; } Method stopMethod = cl . getDeclaredMethod ( "" , new Class [ ] ) ; if ( startMethod . getReturnType ( ) != Void . TYPE ) { return null ; } return new ServiceMethodAdaptor ( component , startMethod , stopMethod ) ; } catch ( Exception e ) { return null ; } } } ; } public ServiceStrategy hasServiceAnnotationsStrategy ( ) { return new ServiceStrategy ( ) { @ Override public ServiceAdaptor serviceFor ( Object component , ArooaSession session ) { PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; ArooaBeanDescriptor beanDescriptor = session . getArooaDescriptor ( ) . getBeanDescriptor ( accessor . getClassName ( component ) , accessor ) ; ArooaAnnotations annotations = beanDescriptor . getAnnotations ( ) ; Method startMethod = annotations . methodFor ( Start . class . getName ( ) ) ; Method stopMethod = annotations . methodFor ( Stop . class . getName ( ) ) ; if ( startMethod == null && stopMethod == null ) { return null ; } if ( startMethod != null && stopMethod != null ) { return new ServiceMethodAdaptor ( component , startMethod , stopMethod ) ; } throw new IllegalStateException ( "" + component . getClass ( ) . getName ( ) + "" ) ; } } ; } } package org . oddjob . framework ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . lang . reflect . Method ; import java . util . HashMap ; import java . util . Map ; public class DefaultInvocationHandler implements WrapperInvocationHandler , Serializable { private static final long serialVersionUID = ; private transient Map < Method , Object > methods ; private ComponentWrapper wrapper ; private Class < ? > [ ] wrappingInterfaces ; private Object wrapped ; private Class < ? > [ ] wrappedInterfaces ; public void initialise ( ComponentWrapper wrapper , Class < ? > [ ] wrappingInterfaces , Object wrapped , Class < ? > [ ] wrappedInterfaces ) { this . wrapper = wrapper ; this . wrappingInterfaces = wrappingInterfaces ; this . wrapped = wrapped ; this . wrappedInterfaces = wrappedInterfaces ; initialiseMethods ( ) ; } private void initialiseMethods ( ) { this . methods = new HashMap < Method , Object > ( ) ; { Class < ? > [ ] interfaces = wrappedInterfaces ; for ( int i = ; i < interfaces . length ; ++ i ) { addMethods ( interfaces [ i ] , wrapped ) ; } } { Class < ? > [ ] interfaces = wrappingInterfaces ; for ( int i = ; i < interfaces . length ; ++ i ) { addMethods ( interfaces [ i ] , wrapper ) ; } } } private void addMethods ( Class < ? > from , Object destination ) { Method [ ] ms = from . getDeclaredMethods ( ) ; for ( int i = ; i < ms . length ; ++ i ) { methods . put ( ms [ i ] , destination ) ; } } @ Override public Object getWrappedComponent ( ) { return wrapped ; } @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { Object destination = methods . get ( method ) ; if ( destination == null ) { throw new IllegalStateException ( "" + method ) ; } return method . invoke ( destination , args ) ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; initialiseMethods ( ) ; } } package org . oddjob . framework ; import java . util . concurrent . atomic . AtomicInteger ; import org . apache . commons . beanutils . DynaBean ; import org . oddjob . FailedToStopException ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . persist . Persistable ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsExecutable ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . ServiceState ; import org . oddjob . state . ServiceStateChanger ; import org . oddjob . state . ServiceStateHandler ; public class ServiceWrapper extends BaseWrapper implements ComponentWrapper { private final ServiceStateHandler stateHandler ; private final ServiceStateChanger stateChanger ; private final ServiceAdaptor service ; private Object wrapped ; private transient DynaBean dynaBean ; private final Object proxy ; public ServiceWrapper ( ServiceAdaptor service , Object proxy ) { this . service = service ; this . proxy = proxy ; this . wrapped = service . getComponent ( ) ; this . dynaBean = new WrapDynaBean ( wrapped ) ; stateHandler = new ServiceStateHandler ( this ) ; stateChanger = new ServiceStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override protected ServiceStateHandler stateHandler ( ) { return stateHandler ; } protected ServiceStateChanger getStateChanger ( ) { return stateChanger ; } public Object getWrapped ( ) { return wrapped ; } protected DynaBean getDynaBean ( ) { return dynaBean ; } protected Object getProxy ( ) { return proxy ; } @ Override protected void save ( Object compoonent ) { } public void run ( ) { ComponentBoundry . push ( loggerName ( ) , wrapped ) ; try { if ( ! stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . STARTING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; try { configure ( ) ; service . start ( ) ; logger ( ) . info ( "" ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . STARTED ) ; } } ) ; } catch ( final Throwable t ) { logger ( ) . error ( "" , t ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setStateException ( t ) ; } } ) ; } } finally { ComponentBoundry . pop ( ) ; } } public void onStop ( ) throws FailedToStopException { stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { } } ) ; final AtomicInteger result = new AtomicInteger ( ) ; ComponentBoundry . push ( loggerName ( ) , wrapped ) ; try { service . stop ( ) ; result . set ( getResult ( null ) ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new FailedToStopException ( service , e ) ; } finally { ComponentBoundry . pop ( ) ; } stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . COMPLETE ) ; } } ) ; } public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , wrapped ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , wrapped ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( ServiceState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + ServiceWrapper . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . framework ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . LinkedBlockingQueue ; import java . util . concurrent . TimeUnit ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Stateful ; import org . oddjob . logging . LogEnabled ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . StateListener ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; public class StopWait { private final Stateful stateful ; private final Logger logger ; private final long timeout ; public StopWait ( Stateful stateful ) { this ( stateful , ) ; } public StopWait ( Stateful stateful , long timeout ) { this . stateful = stateful ; if ( stateful instanceof LogEnabled ) { logger = Logger . getLogger ( ( ( LogEnabled ) stateful ) . loggerName ( ) ) ; } else { logger = Logger . getLogger ( stateful . getClass ( ) ) ; } this . timeout = timeout ; } public void run ( ) throws FailedToStopException { if ( new IsStoppable ( ) . test ( stateful . lastStateEvent ( ) . getState ( ) ) ) { doWait ( ) ; } } private void doWait ( ) throws FailedToStopException { final BlockingQueue < State > handoff = new LinkedBlockingQueue < State > ( ) ; class StopListener implements StateListener { @ Override public void jobStateChange ( StateEvent event ) { handoff . add ( event . getState ( ) ) ; } } ; StopListener listener = new StopListener ( ) ; stateful . addStateListener ( listener ) ; try { while ( true ) { State state = handoff . poll ( timeout , TimeUnit . MILLISECONDS ) ; if ( state == null ) { throw new FailedToStopException ( stateful ) ; } if ( ! state . isStoppable ( ) ) { return ; } logger . debug ( "" + stateful + "" + state + "" ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } finally { stateful . removeStateListener ( listener ) ; } } } package org . oddjob . framework ; public interface Transient { } package org . oddjob . framework ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import org . oddjob . images . StateIcons ; import org . oddjob . state . StateEvent ; abstract public class SerializableJob extends SimpleJob implements Serializable { private static final long serialVersionUID = ; public SerializableJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; s . writeObject ( getName ( ) ) ; if ( loggerName ( ) . startsWith ( getClass ( ) . getName ( ) ) ) { s . writeObject ( null ) ; } else { s . writeObject ( loggerName ( ) ) ; } s . writeObject ( stateHandler . lastStateEvent ( ) ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; String name = ( String ) s . readObject ( ) ; logger ( ( String ) s . readObject ( ) ) ; StateEvent savedEvent = ( StateEvent ) s . readObject ( ) ; completeConstruction ( ) ; setName ( name ) ; stateHandler . restoreLastJobStateEvent ( savedEvent ) ; iconHelper . changeIcon ( StateIcons . iconFor ( stateHandler . getState ( ) ) ) ; } } package org . oddjob . framework ; import java . lang . reflect . Method ; import org . oddjob . FailedToStopException ; public class ServiceMethodAdaptor implements ServiceAdaptor { private final Method startMethod ; private final Method stopMethod ; private final Object component ; public ServiceMethodAdaptor ( Object component , Method startMethod , Method stopMethod ) { this . component = component ; this . startMethod = startMethod ; this . stopMethod = stopMethod ; } public void start ( ) throws Exception { startMethod . invoke ( component , new Object [ ] ) ; } public void stop ( ) throws FailedToStopException { try { stopMethod . invoke ( component , new Object [ ] ) ; } catch ( Exception e ) { throw new FailedToStopException ( this , "" , e ) ; } } public Object getComponent ( ) { return component ; } } package org . oddjob . framework ; import org . apache . commons . beanutils . ConversionException ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaProperty ; import org . apache . commons . beanutils . PropertyUtils ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . ArooaClassFactory ; import org . oddjob . arooa . reflect . ArooaClasses ; public class WrapDynaBean implements DynaBean { static { ArooaClasses . register ( WrapDynaBean . class , new ArooaClassFactory < WrapDynaBean > ( ) { @ Override public ArooaClass classFor ( WrapDynaBean instance ) { return new WrapDynaArooaClass ( instance . getDynaClass ( ) , instance . getClass ( ) ) ; } } ) ; } public WrapDynaBean ( Object instance ) { super ( ) ; this . instance = instance ; this . dynaClass = WrapDynaClass . createDynaClass ( instance . getClass ( ) ) ; } protected WrapDynaClass dynaClass = null ; protected Object instance = null ; public boolean contains ( String name , String key ) { throw new UnsupportedOperationException ( "" ) ; } public Object get ( String name ) { if ( ! dynaClass . isReadable ( name ) ) { return null ; } Object value = null ; try { value = PropertyUtils . getSimpleProperty ( instance , name ) ; } catch ( Throwable t ) { throw new RuntimeException ( "" + name , t ) ; } return ( value ) ; } public Object get ( String name , int index ) { if ( ! dynaClass . isReadable ( name ) ) { return null ; } Object value = null ; try { value = PropertyUtils . getIndexedProperty ( instance , name , index ) ; } catch ( IndexOutOfBoundsException e ) { throw e ; } catch ( Throwable t ) { throw new IllegalArgumentException ( "" + name + "" ) ; } return ( value ) ; } public Object get ( String name , String key ) { if ( ! dynaClass . isReadable ( name ) ) { return null ; } Object value = null ; try { value = PropertyUtils . getMappedProperty ( instance , name , key ) ; } catch ( Throwable t ) { throw new IllegalArgumentException ( "" + name + "" ) ; } return ( value ) ; } public WrapDynaClass getDynaClass ( ) { return ( this . dynaClass ) ; } public void remove ( String name , String key ) { throw new UnsupportedOperationException ( "" ) ; } public void set ( String name , Object value ) { try { PropertyUtils . setSimpleProperty ( instance , name , value ) ; } catch ( Throwable t ) { throw new IllegalArgumentException ( "" + name + "" ) ; } } public void set ( String name , int index , Object value ) { try { PropertyUtils . setIndexedProperty ( instance , name , index , value ) ; } catch ( IndexOutOfBoundsException e ) { throw e ; } catch ( Throwable t ) { throw new IllegalArgumentException ( "" + name + "" ) ; } } public void set ( String name , String key , Object value ) { try { PropertyUtils . setMappedProperty ( instance , name , key , value ) ; } catch ( Throwable t ) { throw new IllegalArgumentException ( "" + name + "" ) ; } } public Object getInstance ( ) { return instance ; } protected DynaProperty getDynaProperty ( String name ) { DynaProperty descriptor = getDynaClass ( ) . getDynaProperty ( name ) ; if ( descriptor == null ) { throw new IllegalArgumentException ( "" + name + "" ) ; } return ( descriptor ) ; } } package org . oddjob . framework ; import org . oddjob . arooa . ArooaSession ; public interface ServiceStrategy { public ServiceAdaptor serviceFor ( Object component , ArooaSession session ) ; } package org . oddjob . framework ; import org . apache . commons . beanutils . DynaProperty ; import org . oddjob . arooa . reflect . ArooaNoPropertyException ; import org . oddjob . arooa . reflect . BeanOverview ; public class WrapDynaBeanOverview implements BeanOverview { private WrapDynaClass dynaClass ; public WrapDynaBeanOverview ( WrapDynaClass dynaClass ) { this . dynaClass = dynaClass ; } public String [ ] getProperties ( ) { DynaProperty [ ] properties = dynaClass . getDynaProperties ( ) ; String [ ] names = new String [ properties . length ] ; for ( int i = ; i < properties . length ; ++ i ) { names [ i ] = properties [ i ] . getName ( ) ; } return names ; } public Class < ? > getPropertyType ( String property ) throws ArooaNoPropertyException { DynaProperty dynaProperty = dynaClass . getDynaProperty ( property ) ; if ( dynaProperty == null ) { throw new ArooaNoPropertyException ( property , dynaClass . getClass ( ) ) ; } Class < ? > propertyType ; if ( dynaProperty . isIndexed ( ) || dynaProperty . isMapped ( ) ) { propertyType = dynaProperty . getContentType ( ) ; } else { propertyType = dynaProperty . getType ( ) ; } if ( propertyType == null ) { return null ; } return propertyType ; } public boolean hasReadableProperty ( String property ) { if ( dynaClass . getDynaProperty ( property ) == null ) { return false ; } return dynaClass . isReadable ( property ) ; } public boolean hasWriteableProperty ( String property ) { if ( dynaClass . getDynaProperty ( property ) == null ) { return false ; } return dynaClass . isWritable ( property ) ; } public boolean isIndexed ( String property ) throws ArooaNoPropertyException { DynaProperty dynaProperty = dynaClass . getDynaProperty ( property ) ; if ( dynaProperty == null ) { throw new ArooaNoPropertyException ( property , dynaClass . getClass ( ) ) ; } return dynaProperty . isIndexed ( ) ; } public boolean isMapped ( String property ) throws ArooaNoPropertyException { DynaProperty dynaProperty = dynaClass . getDynaProperty ( property ) ; if ( dynaProperty == null ) { throw new ArooaNoPropertyException ( property , dynaClass . getClass ( ) ) ; } return dynaProperty . isMapped ( ) ; } } package org . oddjob . framework ; public class RunnableProxyGenerator extends ProxyGenerator < Runnable > { public Object generate ( Runnable runnable , ClassLoader classLoader ) { return generate ( runnable , new BaseWrapperFactory < Runnable > ( ) { @ Override public ComponentWrapper wrapperFor ( Runnable wrapped , Object proxy ) { RunnableWrapper runnable = new RunnableWrapper ( wrapped , proxy ) ; return runnable ; } } , classLoader ) ; } } package org . oddjob . framework ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import org . oddjob . Resetable ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . reflect . PropertyAccessor ; public class ResetableAdaptorFactory { public Resetable resetableFor ( final Object component , ArooaSession session ) { if ( component instanceof Resetable ) { return ( Resetable ) component ; } PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; ArooaBeanDescriptor beanDescriptor = session . getArooaDescriptor ( ) . getBeanDescriptor ( new SimpleArooaClass ( component . getClass ( ) ) , accessor ) ; ArooaAnnotations annotations = beanDescriptor . getAnnotations ( ) ; final Method softResetMethod = annotations . methodFor ( SoftReset . class . getName ( ) ) ; final Method hardResetMethod = annotations . methodFor ( HardReset . class . getName ( ) ) ; return new Resetable ( ) { @ Override public boolean softReset ( ) { invoke ( component , softResetMethod ) ; return true ; } @ Override public boolean hardReset ( ) { invoke ( component , hardResetMethod ) ; return true ; } } ; } private void invoke ( Object component , Method m ) { if ( m == null ) { return ; } try { m . invoke ( component ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } } } package org . oddjob . framework ; import java . io . Serializable ; import java . util . HashSet ; import java . util . Set ; import java . util . concurrent . Callable ; import org . apache . commons . beanutils . DynaBean ; import org . oddjob . Describeable ; import org . oddjob . Forceable ; import org . oddjob . Iconic ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . life . ArooaContextAware ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . logging . LogEnabled ; abstract public class BaseWrapperFactory < T > implements WrapperFactory < T > { @ Override public Class < ? > [ ] wrappingInterfacesFor ( T wrapped ) { Set < Class < ? > > interfaces = new HashSet < Class < ? > > ( ) ; interfaces . add ( Object . class ) ; interfaces . add ( ArooaSessionAware . class ) ; interfaces . add ( ArooaContextAware . class ) ; interfaces . add ( Stateful . class ) ; interfaces . add ( Resetable . class ) ; interfaces . add ( Forceable . class ) ; interfaces . add ( DynaBean . class ) ; interfaces . add ( Stoppable . class ) ; interfaces . add ( Iconic . class ) ; interfaces . add ( Runnable . class ) ; interfaces . add ( LogEnabled . class ) ; interfaces . add ( Describeable . class ) ; if ( ! ( wrapped instanceof Serializable ) ) { interfaces . add ( Transient . class ) ; } return ( Class [ ] ) interfaces . toArray ( new Class [ ] ) ; } } package org . oddjob . framework ; import java . io . Serializable ; import org . oddjob . jmx . ObjectNames ; public interface Transportable extends Serializable { public Object importResolve ( ObjectNames names ) ; } package org . oddjob . framework ; public interface ServiceAdaptor extends Service , Adaptor { @ Override public Object getComponent ( ) ; } package org . oddjob . framework ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . log4j . Logger ; import org . oddjob . Describeable ; import org . oddjob . FailedToStopException ; import org . oddjob . Reserved ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . images . IconHelper ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogHelper ; import org . oddjob . state . IsStoppable ; abstract public class BaseWrapper extends BaseComponent implements Runnable , Stateful , Resetable , DynaBean , Stoppable , LogEnabled , Describeable { private transient Logger theLogger ; abstract public Object getWrapped ( ) ; abstract protected DynaBean getDynaBean ( ) ; abstract protected Object getProxy ( ) ; protected Logger logger ( ) { if ( theLogger == null ) { String logger = LogHelper . getLogger ( getWrapped ( ) ) ; if ( logger == null ) { logger = LogHelper . uniqueLoggerName ( getWrapped ( ) ) ; } theLogger = Logger . getLogger ( logger ) ; } return theLogger ; } public String loggerName ( ) { return logger ( ) . getName ( ) ; } protected void configure ( ) throws ArooaConfigurationException { configure ( getProxy ( ) ) ; } protected void save ( ) throws ComponentPersistException { save ( getProxy ( ) ) ; } public boolean equals ( Object other ) { return other == getProxy ( ) ; } public String toString ( ) { return getWrapped ( ) . toString ( ) ; } public boolean contains ( String name , String key ) { return getDynaBean ( ) . contains ( name , key ) ; } public Object get ( String name ) { return getDynaBean ( ) . get ( name ) ; } public Object get ( String name , int index ) { return getDynaBean ( ) . get ( name , index ) ; } public Object get ( String name , String key ) { return getDynaBean ( ) . get ( name , key ) ; } public DynaClass getDynaClass ( ) { return getDynaBean ( ) . getDynaClass ( ) ; } public void remove ( String name , String key ) { getDynaBean ( ) . remove ( name , key ) ; } public void set ( String name , int index , Object value ) { getDynaBean ( ) . set ( name , index , value ) ; } public void set ( String name , Object value ) { getDynaBean ( ) . set ( name , value ) ; } public void set ( String name , String key , Object value ) { getDynaBean ( ) . set ( name , key , value ) ; } public final void stop ( ) throws FailedToStopException { stateHandler ( ) . assertAlive ( ) ; ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler ( ) . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { } } ) ) { return ; } logger ( ) . info ( "" ) ; String icon = iconHelper . currentId ( ) ; iconHelper . changeIcon ( IconHelper . STOPPING ) ; try { onStop ( ) ; new StopWait ( this ) . run ( ) ; logger ( ) . info ( "" ) ; } catch ( RuntimeException e ) { iconHelper . changeIcon ( icon ) ; throw e ; } catch ( FailedToStopException e ) { iconHelper . changeIcon ( icon ) ; throw e ; } } finally { ComponentBoundry . pop ( ) ; } } protected void onStop ( ) throws FailedToStopException { } protected int getResult ( Object callableResult ) throws ArooaPropertyException , ArooaConversionException { ArooaSession session = getArooaSession ( ) ; if ( session == null ) { return ; } Integer result ; if ( callableResult != null ) { result = session . getTools ( ) . getArooaConverter ( ) . convert ( callableResult , Integer . class ) ; } else { PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; BeanOverview overview = accessor . getBeanOverview ( getWrapped ( ) . getClass ( ) ) ; if ( ! overview . hasReadableProperty ( Reserved . RESULT_PROPERTY ) ) { return ; } ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; result = converter . convert ( accessor . getProperty ( getWrapped ( ) , Reserved . RESULT_PROPERTY ) , Integer . class ) ; } if ( result == null ) { return ; } return result . intValue ( ) ; } @ Override public Map < String , String > describe ( ) { return new UniversalDescriber ( getArooaSession ( ) ) . describe ( getWrapped ( ) ) ; } @ Override public void onDestroy ( ) { super . onDestroy ( ) ; try { stop ( ) ; } catch ( FailedToStopException e ) { logger ( ) . warn ( e ) ; } } public static Class < ? > [ ] interfacesFor ( Object object ) { List < Class < ? > > results = new ArrayList < Class < ? > > ( ) ; for ( Class < ? > cl = object . getClass ( ) ; cl != null ; cl = cl . getSuperclass ( ) ) { results . addAll ( Arrays . asList ( ( Class < ? > [ ] ) cl . getInterfaces ( ) ) ) ; } return ( Class [ ] ) results . toArray ( new Class [ results . size ( ) ] ) ; } } package org . oddjob . framework ; import java . util . HashSet ; import java . util . Set ; import org . apache . commons . beanutils . DynaBean ; import org . oddjob . Describeable ; import org . oddjob . Forceable ; import org . oddjob . Iconic ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . life . ArooaContextAware ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . logging . LogEnabled ; public class ServiceProxyGenerator extends ProxyGenerator < ServiceAdaptor > { public Object generate ( ServiceAdaptor service , ClassLoader classLoader ) { return generate ( service , new WrapperFactory < ServiceAdaptor > ( ) { @ Override public Class < ? > [ ] wrappingInterfacesFor ( ServiceAdaptor wrapped ) { Set < Class < ? > > interfaces = new HashSet < Class < ? > > ( ) ; interfaces . add ( Object . class ) ; interfaces . add ( ArooaSessionAware . class ) ; interfaces . add ( ArooaContextAware . class ) ; interfaces . add ( Stateful . class ) ; interfaces . add ( Resetable . class ) ; interfaces . add ( Forceable . class ) ; interfaces . add ( DynaBean . class ) ; interfaces . add ( Stoppable . class ) ; interfaces . add ( Iconic . class ) ; interfaces . add ( Runnable . class ) ; interfaces . add ( LogEnabled . class ) ; interfaces . add ( Transient . class ) ; interfaces . add ( Describeable . class ) ; return ( Class [ ] ) interfaces . toArray ( new Class [ interfaces . size ( ) ] ) ; } @ Override public ComponentWrapper wrapperFor ( ServiceAdaptor wrapped , Object proxy ) { ServiceWrapper wrapper = new ServiceWrapper ( wrapped , proxy ) ; return wrapper ; } } , classLoader ) ; } } package org . oddjob . framework ; public class OddjobRemoteException extends Exception { private static final long serialVersionUID = ; public OddjobRemoteException ( String msg ) { super ( msg ) ; } public OddjobRemoteException ( String msg , Throwable cause ) { super ( msg , cause ) ; } } package org . oddjob . framework ; import java . beans . PropertyChangeListener ; import java . beans . PropertyChangeSupport ; import javax . swing . ImageIcon ; import org . apache . log4j . Logger ; import org . oddjob . Iconic ; import org . oddjob . Stateful ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . ArooaException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . deploy . annotations . ArooaHidden ; import org . oddjob . arooa . life . ArooaContextAware ; import org . oddjob . arooa . life . ArooaLifeAware ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . runtime . RuntimeEvent ; import org . oddjob . arooa . runtime . RuntimeListenerAdaptor ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateHandler ; import org . oddjob . state . StateListener ; public abstract class BaseComponent implements Iconic , Stateful , ArooaSessionAware , ArooaContextAware , PropertyChangeNotifier { private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport ( this ) ; protected final IconHelper iconHelper = new IconHelper ( this ) ; private ArooaSession session ; abstract protected StateHandler < ? > stateHandler ( ) ; @ Override @ ArooaHidden public void setArooaSession ( ArooaSession session ) { this . session = session ; } protected ArooaSession getArooaSession ( ) { return this . session ; } @ Override @ ArooaHidden public void setArooaContext ( ArooaContext context ) { if ( this instanceof ArooaLifeAware ) { throw new IllegalStateException ( getClass ( ) . getName ( ) + "" + ArooaLifeAware . class . getName ( ) + "" ) ; } context . getRuntime ( ) . addRuntimeListener ( new RuntimeListenerAdaptor ( ) { @ Override public void afterInit ( RuntimeEvent event ) throws ArooaException { onInitialised ( ) ; stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { } } ) ; } @ Override public void afterConfigure ( RuntimeEvent event ) throws ArooaException { onConfigured ( ) ; } @ Override public void beforeDestroy ( RuntimeEvent event ) throws ArooaException { stateHandler ( ) . assertAlive ( ) ; ComponentBoundry . push ( logger ( ) . getName ( ) , BaseComponent . this ) ; try { logger ( ) . debug ( "" ) ; onDestroy ( ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override public void afterDestroy ( RuntimeEvent event ) throws ArooaException { ComponentBoundry . push ( logger ( ) . getName ( ) , BaseComponent . this ) ; try { fireDestroyedState ( ) ; } finally { ComponentBoundry . pop ( ) ; } } } ) ; } protected abstract Logger logger ( ) ; protected void save ( ) throws ComponentPersistException { } protected void configure ( Object component ) throws ArooaConfigurationException { if ( session != null ) { logger ( ) . debug ( "" ) ; session . getComponentPool ( ) . configure ( component ) ; } } protected void save ( final Object o ) throws ComponentPersistException { if ( session != null ) { session . getComponentPool ( ) . save ( o ) ; } } @ Override public StateEvent lastStateEvent ( ) { return stateHandler ( ) . lastStateEvent ( ) ; } @ Override public void addStateListener ( StateListener listener ) { stateHandler ( ) . addStateListener ( listener ) ; } @ Override public void removeStateListener ( StateListener listener ) { stateHandler ( ) . removeStateListener ( listener ) ; } @ Override public void addPropertyChangeListener ( PropertyChangeListener l ) { stateHandler ( ) . assertAlive ( ) ; propertyChangeSupport . addPropertyChangeListener ( l ) ; } @ Override public void removePropertyChangeListener ( PropertyChangeListener l ) { propertyChangeSupport . removePropertyChangeListener ( l ) ; } protected void firePropertyChange ( String propertyName , Object oldValue , Object newValue ) { propertyChangeSupport . firePropertyChange ( propertyName , oldValue , newValue ) ; } @ Override public ImageIcon iconForId ( String iconId ) { return iconHelper . iconForId ( iconId ) ; } @ Override public void addIconListener ( IconListener listener ) { stateHandler ( ) . assertAlive ( ) ; iconHelper . addIconListener ( listener ) ; } @ Override public void removeIconListener ( IconListener listener ) { iconHelper . removeIconListener ( listener ) ; } public void initialise ( ) throws JobDestroyedException { stateHandler ( ) . assertAlive ( ) ; ComponentBoundry . push ( logger ( ) . getName ( ) , this ) ; try { onInitialised ( ) ; onConfigured ( ) ; } finally { ComponentBoundry . pop ( ) ; } } public void destroy ( ) throws JobDestroyedException { stateHandler ( ) . assertAlive ( ) ; ComponentBoundry . push ( logger ( ) . getName ( ) , this ) ; try { onDestroy ( ) ; fireDestroyedState ( ) ; } finally { ComponentBoundry . pop ( ) ; } } protected void onInitialised ( ) { } protected void onConfigured ( ) { } protected void onDestroy ( ) { } abstract protected void fireDestroyedState ( ) ; } package org . oddjob . framework ; import java . lang . reflect . InvocationHandler ; public interface WrapperInvocationHandler extends InvocationHandler { public Object getWrappedComponent ( ) ; } package org . oddjob . framework ; public class JobDestroyedException extends RuntimeException { private static final long serialVersionUID = ; public JobDestroyedException ( Object job ) { super ( "" + job . toString ( ) ) ; } } package org . oddjob . framework ; import java . beans . IndexedPropertyDescriptor ; import java . beans . PropertyDescriptor ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . lang . reflect . Method ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . DynaProperty ; import org . apache . commons . beanutils . MethodUtils ; import org . apache . commons . beanutils . PropertyUtils ; public class WrapDynaClass implements DynaClass , Serializable { private static final long serialVersionUID = ; private WrapDynaClass ( Class < ? > beanClass ) { this . beanClassName = beanClass . getName ( ) ; introspect ( beanClass ) ; } private final String beanClassName ; private DynaProperty properties [ ] = null ; private HashMap < String , DynaProperty > propertiesMap = new HashMap < String , DynaProperty > ( ) ; private Set < String > readableProperties = new HashSet < String > ( ) ; private Set < String > writableProperties = new HashSet < String > ( ) ; private static HashMap < Class < ? > , WrapDynaClass > dynaClasses = new HashMap < Class < ? > , WrapDynaClass > ( ) ; public String getName ( ) { return ( this . beanClassName ) ; } public DynaProperty getDynaProperty ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "" ) ; } return ( ( DynaProperty ) propertiesMap . get ( name ) ) ; } public DynaProperty [ ] getDynaProperties ( ) { return ( properties ) ; } public DynaBean newInstance ( ) throws UnsupportedOperationException { throw new UnsupportedOperationException ( "" ) ; } public boolean isReadable ( String propertyName ) { if ( ! propertiesMap . containsKey ( propertyName ) ) { throw new IllegalArgumentException ( "" + propertyName ) ; } return readableProperties . contains ( propertyName ) ; } public boolean isWritable ( String propertyName ) { if ( ! propertiesMap . containsKey ( propertyName ) ) { throw new IllegalArgumentException ( "" + propertyName ) ; } return writableProperties . contains ( propertyName ) ; } public static void clear ( ) { synchronized ( dynaClasses ) { dynaClasses . clear ( ) ; } } public static WrapDynaClass createDynaClass ( Class < ? > beanClass ) { synchronized ( dynaClasses ) { WrapDynaClass dynaClass = ( WrapDynaClass ) dynaClasses . get ( beanClass ) ; if ( dynaClass == null ) { dynaClass = new WrapDynaClass ( beanClass ) ; dynaClasses . put ( beanClass , dynaClass ) ; } return ( dynaClass ) ; } } protected void introspect ( Class < ? > beanClass ) { Set < String > mismatched = new HashSet < String > ( ) ; PropertyDescriptor [ ] descriptors = PropertyUtils . getPropertyDescriptors ( beanClass ) ; for ( int i = ; i < descriptors . length ; ++ i ) { PropertyDescriptor descriptor = descriptors [ i ] ; String propertyName = descriptor . getName ( ) ; DynaProperty dynaProperty ; if ( descriptor instanceof IndexedPropertyDescriptor ) { dynaProperty = new DynaProperty ( propertyName , descriptor . getPropertyType ( ) , ( ( IndexedPropertyDescriptor ) descriptor ) . getIndexedPropertyType ( ) ) ; } else { dynaProperty = new DynaProperty ( propertyName , descriptor . getPropertyType ( ) ) ; } propertiesMap . put ( propertyName , dynaProperty ) ; if ( MethodUtils . getAccessibleMethod ( descriptor . getReadMethod ( ) ) != null ) { readableProperties . add ( propertyName ) ; } if ( MethodUtils . getAccessibleMethod ( descriptor . getWriteMethod ( ) ) != null ) { writableProperties . add ( propertyName ) ; } } Method [ ] methods = beanClass . getMethods ( ) ; for ( int i = ; i < methods . length ; ++ i ) { Method method = methods [ i ] ; if ( ! method . getName ( ) . startsWith ( "" ) && ! method . getName ( ) . startsWith ( "" ) ) { continue ; } String propertyName = method . getName ( ) . substring ( ) ; if ( propertyName . length ( ) == ) { continue ; } propertyName = propertyName . substring ( , ) . toLowerCase ( ) + propertyName . substring ( ) ; Class < ? > [ ] args = method . getParameterTypes ( ) ; DynaProperty dynaProperty = null ; boolean readable = false ; boolean writable = false ; if ( method . getName ( ) . startsWith ( "" ) && Void . TYPE != method . getReturnType ( ) && args . length == && args [ ] == String . class ) { DynaProperty existing = ( DynaProperty ) propertiesMap . get ( propertyName ) ; if ( existing != null && ! existing . isMapped ( ) ) { mismatched . add ( propertyName ) ; continue ; } dynaProperty = new DynaProperty ( propertyName , Map . class , method . getReturnType ( ) ) ; readable = true ; } else if ( args . length == && args [ ] == String . class && Void . TYPE == method . getReturnType ( ) ) { DynaProperty existing = ( DynaProperty ) propertiesMap . get ( propertyName ) ; if ( existing != null && ! existing . isMapped ( ) ) { mismatched . add ( propertyName ) ; continue ; } dynaProperty = new DynaProperty ( propertyName , Map . class , args [ ] ) ; writable = true ; } else { continue ; } propertiesMap . put ( propertyName , dynaProperty ) ; if ( readable ) { readableProperties . add ( propertyName ) ; } if ( writable ) { writableProperties . add ( propertyName ) ; } } for ( String element : mismatched ) { propertiesMap . remove ( element ) ; readableProperties . remove ( element ) ; writableProperties . remove ( element ) ; } properties = ( DynaProperty [ ] ) propertiesMap . values ( ) . toArray ( new DynaProperty [ ] ) ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; } } package org . oddjob . framework ; import java . lang . reflect . Proxy ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; public class ProxyGenerator < T > { public Object generate ( T wrapped , WrapperFactory < T > wrapperFactory , ClassLoader classLoader ) { Object component ; if ( wrapped instanceof Adaptor ) { component = ( ( Adaptor ) wrapped ) . getComponent ( ) ; } else { component = wrapped ; } Class < ? > [ ] wrappedInterfaces = interfacesFor ( component ) ; Class < ? > [ ] wrappingInterfaces = wrapperFactory . wrappingInterfacesFor ( wrapped ) ; Set < Class < ? > > proxyInterfaces = new HashSet < Class < ? > > ( ) ; proxyInterfaces . addAll ( Arrays . asList ( wrappedInterfaces ) ) ; proxyInterfaces . addAll ( Arrays . asList ( wrappingInterfaces ) ) ; proxyInterfaces . remove ( Object . class ) ; Class < ? > [ ] interfaceArray = ( Class [ ] ) proxyInterfaces . toArray ( new Class [ proxyInterfaces . size ( ) ] ) ; DefaultInvocationHandler handler = new DefaultInvocationHandler ( ) ; Object proxy = Proxy . newProxyInstance ( classLoader , interfaceArray , handler ) ; ComponentWrapper wrapper = wrapperFactory . wrapperFor ( wrapped , proxy ) ; handler . initialise ( wrapper , wrappingInterfaces , component , wrappedInterfaces ) ; return proxy ; } public static Class < ? > [ ] interfacesFor ( Object object ) { List < Class < ? > > results = new ArrayList < Class < ? > > ( ) ; for ( Class < ? > cl = object . getClass ( ) ; cl != null ; cl = cl . getSuperclass ( ) ) { results . addAll ( Arrays . asList ( ( Class < ? > [ ] ) cl . getInterfaces ( ) ) ) ; } return ( Class [ ] ) results . toArray ( new Class [ ] ) ; } } package org . oddjob . framework ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import org . oddjob . Resetable ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . METHOD ) public @ interface HardReset { } package org . oddjob . framework ; import java . util . concurrent . atomic . AtomicInteger ; import java . util . concurrent . atomic . AtomicReference ; import org . oddjob . FailedToStopException ; import org . oddjob . Forceable ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . images . IconHelper ; import org . oddjob . persist . Persistable ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsExecutable ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . JobState ; import org . oddjob . state . JobStateChanger ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateChanger ; public abstract class SimpleJob extends BasePrimary implements Runnable , Resetable , Stateful , Forceable { protected transient JobStateHandler stateHandler ; private final JobStateChanger stateChanger ; protected transient volatile boolean stop ; protected SimpleJob ( ) { stateHandler = new JobStateHandler ( this ) ; stateChanger = new JobStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override protected JobStateHandler stateHandler ( ) { return stateHandler ; } protected StateChanger < JobState > getStateChanger ( ) { return stateChanger ; } abstract protected int execute ( ) throws Throwable ; public final void run ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( JobState . EXECUTING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; final AtomicInteger result = new AtomicInteger ( ) ; final AtomicReference < Throwable > exception = new AtomicReference < Throwable > ( ) ; try { configure ( ) ; result . set ( execute ( ) ) ; logger ( ) . info ( "" + result . get ( ) ) ; } catch ( Throwable e ) { logger ( ) . error ( "" , e ) ; exception . set ( e ) ; } stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { if ( exception . get ( ) != null ) { getStateChanger ( ) . setStateException ( exception . get ( ) ) ; } else if ( result . get ( ) == ) { getStateChanger ( ) . setState ( JobState . COMPLETE ) ; } else { getStateChanger ( ) . setState ( JobState . INCOMPLETE ) ; } } } ) ; } finally { ComponentBoundry . pop ( ) ; } } protected void sleep ( final long waitTime ) { stateHandler ( ) . assertAlive ( ) ; if ( ! stateHandler ( ) . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { if ( stop ) { logger ( ) . debug ( "" ) ; return ; } logger ( ) . debug ( "" + ( waitTime == ? "" : "" + waitTime + "" ) + "" ) ; iconHelper . changeIcon ( IconHelper . SLEEPING ) ; try { stateHandler ( ) . sleep ( waitTime ) ; } catch ( InterruptedException e ) { logger ( ) . debug ( "" ) ; Thread . currentThread ( ) . interrupt ( ) ; } if ( ! stop ) { iconHelper . changeIcon ( IconHelper . EXECUTING ) ; } } } ) ) { throw new IllegalStateException ( "" ) ; } } public final void stop ( ) throws FailedToStopException { stateHandler . assertAlive ( ) ; ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { stop = true ; stateHandler . wake ( ) ; iconHelper . changeIcon ( IconHelper . STOPPING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; try { onStop ( ) ; new StopWait ( this ) . run ( ) ; logger ( ) . info ( "" ) ; } catch ( RuntimeException e ) { iconHelper . changeIcon ( IconHelper . EXECUTING ) ; throw e ; } catch ( FailedToStopException e ) { iconHelper . changeIcon ( IconHelper . EXECUTING ) ; throw e ; } } finally { ComponentBoundry . pop ( ) ; } } protected void onStop ( ) throws FailedToStopException { } @ Override public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { onReset ( ) ; getStateChanger ( ) . setState ( JobState . READY ) ; stop = false ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { onReset ( ) ; getStateChanger ( ) . setState ( JobState . READY ) ; stop = false ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } protected void onReset ( ) { } @ Override public void force ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . info ( "" ) ; getStateChanger ( ) . setState ( JobState . COMPLETE ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; try { stop ( ) ; } catch ( FailedToStopException e ) { logger ( ) . warn ( e ) ; } } protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( JobState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + SimpleJob . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . framework ; import java . util . Stack ; public class ContextClassloaders { private static InheritableThreadLocal < Stack < ClassLoader > > local = new InheritableThreadLocal < Stack < ClassLoader > > ( ) { @ Override protected Stack < ClassLoader > initialValue ( ) { return new Stack < ClassLoader > ( ) ; } @ Override @ SuppressWarnings ( "" ) protected Stack < ClassLoader > childValue ( Stack < ClassLoader > parentValue ) { return ( Stack < ClassLoader > ) parentValue . clone ( ) ; } } ; private ContextClassloaders ( ) { } public static void pop ( ) { Stack < ClassLoader > stack = local . get ( ) ; ClassLoader last = stack . pop ( ) ; Thread . currentThread ( ) . setContextClassLoader ( last ) ; } public static void push ( Object component ) { if ( component == null ) { throw new NullPointerException ( "" ) ; } Stack < ClassLoader > stack = local . get ( ) ; stack . push ( Thread . currentThread ( ) . getContextClassLoader ( ) ) ; Thread . currentThread ( ) . setContextClassLoader ( component . getClass ( ) . getClassLoader ( ) ) ; } } package org . oddjob . framework ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . METHOD ) public @ interface Stop { } package org . oddjob . framework ; public interface WrapperFactory < T > { public Class < ? > [ ] wrappingInterfacesFor ( T wrapped ) ; public ComponentWrapper wrapperFor ( T wrapped , Object proxy ) ; } package org . oddjob . framework ; public interface ComponentWrapper { } package org . oddjob . framework ; import java . util . concurrent . Callable ; public class CallableProxyGenerator extends ProxyGenerator < Callable < ? > > { public Object generate ( Callable < ? > callable , ClassLoader classLoader ) { return generate ( callable , new BaseWrapperFactory < Callable < ? > > ( ) { @ Override public ComponentWrapper wrapperFor ( Callable < ? > wrapped , Object proxy ) { RunnableWrapper wrapper = new RunnableWrapper ( wrapped , proxy ) ; return wrapper ; } } , classLoader ) ; } } package org . oddjob . framework ; import java . beans . PropertyChangeListener ; public interface PropertyChangeNotifier { public void addPropertyChangeListener ( PropertyChangeListener listener ) ; public void removePropertyChangeListener ( PropertyChangeListener listener ) ; } package org . oddjob . framework ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import org . oddjob . FailedToStopException ; import org . oddjob . Forceable ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . images . IconHelper ; import org . oddjob . images . StateIcons ; import org . oddjob . persist . Persistable ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsExecutable ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . OrderedStateChanger ; import org . oddjob . state . ParentState ; import org . oddjob . state . ParentStateChanger ; import org . oddjob . state . ParentStateHandler ; import org . oddjob . state . StateChanger ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateExchange ; import org . oddjob . state . StateOperator ; import org . oddjob . state . StructuralStateHelper ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public abstract class StructuralJob < E > extends BasePrimary implements Runnable , Serializable , Stoppable , Resetable , Stateful , Forceable , Structural { private static final long serialVersionUID = ; protected transient ParentStateHandler stateHandler ; protected transient ChildHelper < E > childHelper ; protected transient StructuralStateHelper structuralState ; protected transient StateExchange childStateReflector ; private transient ParentStateChanger stateChanger ; protected transient volatile boolean stop ; public StructuralJob ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { stateHandler = new ParentStateHandler ( this ) ; childHelper = new ChildHelper < E > ( this ) ; structuralState = new StructuralStateHelper ( childHelper , getStateOp ( ) ) ; stateChanger = new ParentStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; childStateReflector = new StateExchange ( structuralState , new OrderedStateChanger < ParentState > ( stateChanger , stateHandler ) ) ; } @ Override protected ParentStateHandler stateHandler ( ) { return stateHandler ; } protected StateChanger < ParentState > getStateChanger ( ) { return stateChanger ; } abstract protected StateOperator getStateOp ( ) ; abstract protected void execute ( ) throws Throwable ; public final void run ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { childStateReflector . stop ( ) ; getStateChanger ( ) . setState ( ParentState . EXECUTING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; try { configure ( ) ; execute ( ) ; startChildStateReflector ( ) ; } catch ( final Throwable e ) { logger ( ) . error ( "" , e ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setStateException ( e ) ; } } ) ; } logger ( ) . info ( "" ) ; } finally { ComponentBoundry . pop ( ) ; } } protected void startChildStateReflector ( ) { childStateReflector . start ( ) ; } public void stop ( ) throws FailedToStopException { stateHandler . assertAlive ( ) ; ComponentBoundry . push ( loggerName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stop = true ; logger ( ) . info ( "" ) ; stateHandler . wake ( ) ; iconHelper . changeIcon ( IconHelper . STOPPING ) ; } } ) ) { throw new IllegalStateException ( ) ; } FailedToStopException failedToStopException = null ; try { onStop ( ) ; childHelper . stopChildren ( ) ; } catch ( FailedToStopException e ) { failedToStopException = e ; } catch ( RuntimeException e ) { failedToStopException = new FailedToStopException ( StructuralJob . this , "" , e ) ; } try { if ( failedToStopException == null ) { new StopWait ( this ) . run ( ) ; logger ( ) . info ( "" ) ; } else { throw failedToStopException ; } } finally { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { iconHelper . changeIcon ( StateIcons . iconFor ( stateHandler . getState ( ) ) ) ; stop = false ; } } ) ; } } finally { ComponentBoundry . pop ( ) ; } } protected void onStop ( ) throws FailedToStopException { } public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; childStateReflector . stop ( ) ; childHelper . softResetChildren ( ) ; stop = false ; onReset ( ) ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . debug ( "" ) ; childStateReflector . stop ( ) ; childHelper . hardResetChildren ( ) ; stop = false ; onReset ( ) ; getStateChanger ( ) . setState ( ParentState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } protected void onReset ( ) { } @ Override public void force ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . info ( "" ) ; childStateReflector . stop ( ) ; getStateChanger ( ) . setState ( ParentState . COMPLETE ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public void addStructuralListener ( StructuralListener listener ) { stateHandler . assertAlive ( ) ; childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } public boolean isStop ( ) { return stop ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; s . writeObject ( getName ( ) ) ; if ( loggerName ( ) . startsWith ( getClass ( ) . getName ( ) ) ) { s . writeObject ( null ) ; } else { s . writeObject ( loggerName ( ) ) ; } s . writeObject ( stateHandler . lastStateEvent ( ) ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; String name = ( String ) s . readObject ( ) ; logger ( ( String ) s . readObject ( ) ) ; StateEvent savedEvent = ( StateEvent ) s . readObject ( ) ; completeConstruction ( ) ; setName ( name ) ; stateHandler . restoreLastJobStateEvent ( savedEvent ) ; iconHelper . changeIcon ( StateIcons . iconFor ( stateHandler . getState ( ) ) ) ; } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; try { stop ( ) ; } catch ( FailedToStopException e ) { logger ( ) . warn ( "" , e ) ; } childStateReflector . stop ( ) ; } protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( ParentState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + StructuralJob . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . framework ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Future ; import javax . inject . Inject ; import org . oddjob . FailedToStopException ; import org . oddjob . Stoppable ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . ParentState ; abstract public class SimultaneousStructural extends StructuralJob < Runnable > implements Stoppable { private static final long serialVersionUID = ; private volatile transient ExecutorService executorService ; private volatile transient List < Future < ? > > jobThreads ; @ Inject public void setExecutorService ( ExecutorService executorService ) { this . executorService = executorService ; } @ ArooaComponent public void setJobs ( int index , Runnable child ) { logger ( ) . debug ( "" + child + "" + index + "" ) ; if ( child == null ) { childHelper . removeChildAt ( index ) ; } else { childHelper . insertChild ( index , child ) ; } } protected void execute ( ) throws InterruptedException { if ( executorService == null ) { throw new NullPointerException ( "" ) ; } ExecutionWatcher executionWatcher = new ExecutionWatcher ( new Runnable ( ) { public void run ( ) { SimultaneousStructural . super . startChildStateReflector ( ) ; } } ) ; jobThreads = new ArrayList < Future < ? > > ( ) ; for ( Runnable child : childHelper ) { if ( stop ) { break ; } Future < ? > future = executorService . submit ( executionWatcher . addJob ( child ) ) ; jobThreads . add ( future ) ; } if ( stop ) { stop = false ; } else { if ( jobThreads . size ( ) > ) { stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ParentState . ACTIVE ) ; } } ) ; } executionWatcher . start ( ) ; } } @ Override protected void onStop ( ) throws FailedToStopException { super . onStop ( ) ; Iterable < Future < ? > > jobThreads = this . jobThreads ; if ( jobThreads == null ) { return ; } for ( Future < ? > future : jobThreads ) { future . cancel ( false ) ; } super . startChildStateReflector ( ) ; } @ Override protected void startChildStateReflector ( ) { } } package org . oddjob . framework ; public interface Exportable { public Transportable exportTransportable ( ) ; } package org . oddjob . framework ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( ElementType . METHOD ) public @ interface Start { } package org . oddjob . framework ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . util . concurrent . Callable ; import java . util . concurrent . atomic . AtomicReference ; import org . apache . commons . beanutils . DynaBean ; import org . oddjob . FailedToStopException ; import org . oddjob . Forceable ; import org . oddjob . Resetable ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . images . StateIcons ; import org . oddjob . persist . Persistable ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsExecutable ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . JobState ; import org . oddjob . state . JobStateChanger ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateEvent ; public class RunnableWrapper extends BaseWrapper implements ComponentWrapper , Serializable , Forceable { private static final long serialVersionUID = ; private transient JobStateHandler stateHandler ; private transient JobStateChanger stateChanger ; private Object wrapped ; private transient DynaBean dynaBean ; private volatile transient Thread thread ; private final Object proxy ; private transient Resetable resetableAdaptor ; public RunnableWrapper ( Object wrapped , Object proxy ) { this . wrapped = wrapped ; this . proxy = proxy ; completeConstruction ( ) ; } private void completeConstruction ( ) { this . dynaBean = new WrapDynaBean ( wrapped ) ; stateHandler = new JobStateHandler ( this ) ; stateChanger = new JobStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override public void setArooaSession ( ArooaSession session ) { super . setArooaSession ( session ) ; resetableAdaptor = new ResetableAdaptorFactory ( ) . resetableFor ( wrapped , session ) ; } @ Override protected JobStateHandler stateHandler ( ) { return stateHandler ; } protected JobStateChanger getStateChanger ( ) { return stateChanger ; } public Object getWrapped ( ) { return wrapped ; } protected DynaBean getDynaBean ( ) { return dynaBean ; } protected Object getProxy ( ) { return proxy ; } @ Override public void run ( ) { ComponentBoundry . push ( loggerName ( ) , wrapped ) ; try { if ( ! stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( JobState . EXECUTING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; final AtomicReference < Throwable > exception = new AtomicReference < Throwable > ( ) ; final AtomicReference < Object > callableResult = new AtomicReference < Object > ( ) ; thread = Thread . currentThread ( ) ; try { configure ( ) ; Object result ; if ( wrapped instanceof Callable < ? > ) { result = ( ( Callable < ? > ) wrapped ) . call ( ) ; } else { ( ( Runnable ) wrapped ) . run ( ) ; result = null ; } callableResult . set ( result ) ; } catch ( Throwable t ) { logger ( ) . error ( "" , t ) ; exception . set ( t ) ; } finally { if ( Thread . interrupted ( ) ) { logger ( ) . debug ( "" ) ; } thread = null ; } logger ( ) . info ( "" ) ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { if ( exception . get ( ) != null ) { getStateChanger ( ) . setStateException ( exception . get ( ) ) ; } else { int result ; try { result = getResult ( callableResult . get ( ) ) ; if ( result == ) { getStateChanger ( ) . setState ( JobState . COMPLETE ) ; } else { getStateChanger ( ) . setState ( JobState . INCOMPLETE ) ; } } catch ( Exception e ) { getStateChanger ( ) . setStateException ( e ) ; } } } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override public void onStop ( ) throws FailedToStopException { if ( wrapped instanceof Stoppable ) { ( ( Stoppable ) wrapped ) . stop ( ) ; } else { Thread t = thread ; if ( t != null ) { t . interrupt ( ) ; } } } @ Override public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { if ( resetableAdaptor == null ) { throw new NullPointerException ( "" + "" ) ; } resetableAdaptor . softReset ( ) ; getStateChanger ( ) . setState ( JobState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { if ( resetableAdaptor == null ) { throw new NullPointerException ( "" + "" ) ; } resetableAdaptor . hardReset ( ) ; getStateChanger ( ) . setState ( JobState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override public void force ( ) { stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { logger ( ) . info ( "" ) ; getStateChanger ( ) . setState ( JobState . COMPLETE ) ; } } ) ; } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; s . writeObject ( stateHandler . lastStateEvent ( ) ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; StateEvent savedEvent = ( StateEvent ) s . readObject ( ) ; completeConstruction ( ) ; stateHandler . restoreLastJobStateEvent ( savedEvent ) ; iconHelper . changeIcon ( StateIcons . iconFor ( stateHandler . getState ( ) ) ) ; } protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( JobState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + RunnableWrapper . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . framework ; import java . util . concurrent . atomic . AtomicInteger ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . images . IconHelper ; import org . oddjob . logging . LogEnabled ; import org . oddjob . persist . Persistable ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsExecutable ; import org . oddjob . state . IsHardResetable ; import org . oddjob . state . IsSoftResetable ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . ServiceState ; import org . oddjob . state . ServiceStateChanger ; import org . oddjob . state . ServiceStateHandler ; abstract public class SimpleService extends BaseComponent implements Runnable , Stateful , Resetable , Stoppable , LogEnabled { private static final AtomicInteger instanceCount = new AtomicInteger ( ) ; private final Logger logger = Logger . getLogger ( getClass ( ) . getName ( ) + "" + instanceCount . incrementAndGet ( ) ) ; protected final ServiceStateHandler stateHandler ; private final ServiceStateChanger stateChanger ; private String name ; public SimpleService ( ) { stateHandler = new ServiceStateHandler ( this ) ; stateChanger = new ServiceStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override protected Logger logger ( ) { return logger ; } @ Override public String loggerName ( ) { return logger . getName ( ) ; } @ Override protected ServiceStateHandler stateHandler ( ) { return stateHandler ; } protected ServiceStateChanger getStateChanger ( ) { return stateChanger ; } public void run ( ) { ComponentBoundry . push ( logger ( ) . getName ( ) , this ) ; try { if ( ! stateHandler . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . STARTING ) ; } } ) ) { return ; } logger ( ) . info ( "" ) ; try { configure ( SimpleService . this ) ; onStart ( ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . STARTED ) ; } } ) ; } catch ( final Throwable e ) { logger ( ) . warn ( "" , e ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setStateException ( e ) ; } } ) ; } } finally { ComponentBoundry . pop ( ) ; } } abstract protected void onStart ( ) throws Throwable ; @ Override public void stop ( ) throws FailedToStopException { ComponentBoundry . push ( logger ( ) . getName ( ) , this ) ; try { logger ( ) . debug ( "" ) ; if ( ! stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { iconHelper . changeIcon ( IconHelper . STOPPING ) ; } } ) ) { logger ( ) . debug ( "" ) ; return ; } logger ( ) . info ( "" ) ; try { onStop ( ) ; logger ( ) . info ( "" ) ; stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . COMPLETE ) ; } } ) ; } catch ( final Exception e ) { logger ( ) . warn ( "" , e ) ; stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setStateException ( e ) ; } } ) ; } } finally { ComponentBoundry . pop ( ) ; } } protected void onStop ( ) throws FailedToStopException { } @ Override public boolean softReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsSoftResetable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } @ Override public boolean hardReset ( ) { ComponentBoundry . push ( loggerName ( ) , this ) ; try { return stateHandler . waitToWhen ( new IsHardResetable ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( ServiceState . READY ) ; logger ( ) . info ( "" ) ; } } ) ; } finally { ComponentBoundry . pop ( ) ; } } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } @ Override public String toString ( ) { if ( name == null ) { return getClass ( ) . getSimpleName ( ) ; } else { return name ; } } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; try { stop ( ) ; } catch ( FailedToStopException e ) { logger ( ) . warn ( e ) ; } } @ Override protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler ( ) . setState ( ServiceState . DESTROYED ) ; stateHandler ( ) . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" + SimpleService . this + "" ) ; } logger ( ) . debug ( "" + this + "" ) ; } } package org . oddjob . framework ; import org . oddjob . Stoppable ; public interface Service extends Stoppable { public void start ( ) throws Exception ; } package org . oddjob . framework ; import org . oddjob . arooa . beanutils . DynaArooaClass ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . reflect . PropertyAccessor ; public class WrapDynaArooaClass extends DynaArooaClass { public WrapDynaArooaClass ( WrapDynaClass dynaClass , Class < ? > forClass ) { super ( dynaClass , forClass ) ; } @ Override public WrapDynaClass getDynaClass ( ) { return ( WrapDynaClass ) super . getDynaClass ( ) ; } @ Override public BeanOverview getBeanOverview ( PropertyAccessor accessor ) { return new WrapDynaBeanOverview ( getDynaClass ( ) ) ; } } package org . oddjob . framework ; import org . oddjob . logging . OddjobNDC ; public class ComponentBoundry { public static void push ( String loggerName , Object component ) { OddjobNDC . push ( loggerName , component ) ; ContextClassloaders . push ( component ) ; } public static void pop ( ) { ContextClassloaders . pop ( ) ; OddjobNDC . pop ( ) ; } } package org . oddjob . framework ; import java . util . concurrent . atomic . AtomicInteger ; public class ExecutionWatcher { private final Runnable action ; private final AtomicInteger added = new AtomicInteger ( ) ; private final AtomicInteger executed = new AtomicInteger ( ) ; private boolean started ; public ExecutionWatcher ( Runnable action ) { this . action = action ; } public Runnable addJob ( final Runnable job ) { added . incrementAndGet ( ) ; return new Runnable ( ) { @ Override public void run ( ) { job . run ( ) ; executed . incrementAndGet ( ) ; boolean perform ; synchronized ( ExecutionWatcher . this ) { perform = check ( ) ; } if ( perform ) { action . run ( ) ; } } } ; } public void start ( ) { boolean perform ; synchronized ( this ) { started = true ; perform = check ( ) ; } if ( perform ) { action . run ( ) ; } } private boolean check ( ) { if ( started && added . get ( ) == executed . get ( ) ) { return true ; } else { return false ; } } } package org . oddjob . framework ; public interface Adaptor { public Object getComponent ( ) ; } package org . oddjob . logging . log4j ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . apache . log4j . SimpleLayout ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . cache . MockLogArchiverCache ; public class ArchiveAppenderTest extends TestCase { private static final Logger logger = Logger . getLogger ( ArchiveAppenderTest . class ) ; private class OurArchiver extends MockLogArchiverCache { Map < LogLevel , String > messages = new HashMap < LogLevel , String > ( ) ; @ Override public void addEvent ( String archive , LogLevel level , String message ) { assertEquals ( ArchiveAppenderTest . class . getName ( ) , archive ) ; messages . put ( level , message ) ; } @ Override public boolean hasArchive ( String archive ) { assertEquals ( ArchiveAppenderTest . class . getName ( ) , archive ) ; return true ; } } public void testAppender ( ) { OurArchiver archiver = new OurArchiver ( ) ; ArchiveAppender test = new ArchiveAppender ( archiver , new SimpleLayout ( ) ) ; logger . setLevel ( Level . TRACE ) ; logger . addAppender ( test ) ; logger . trace ( "" ) ; logger . debug ( "" ) ; logger . info ( "" ) ; logger . warn ( "" ) ; logger . error ( "" ) ; logger . fatal ( "" ) ; logger . removeAppender ( test ) ; assertEquals ( "" , archiver . messages . get ( LogLevel . TRACE ) . trim ( ) ) ; assertEquals ( "" , archiver . messages . get ( LogLevel . DEBUG ) . trim ( ) ) ; assertEquals ( "" , archiver . messages . get ( LogLevel . INFO ) . trim ( ) ) ; assertEquals ( "" , archiver . messages . get ( LogLevel . WARN ) . trim ( ) ) ; assertEquals ( "" , archiver . messages . get ( LogLevel . ERROR ) . trim ( ) ) ; assertEquals ( "" , archiver . messages . get ( LogLevel . FATAL ) . trim ( ) ) ; } } package org . oddjob . logging . log4j ; import junit . framework . TestCase ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . oddjob . Structural ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . MockLogArchiver ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class Log4jArchiverTest extends TestCase { private class X implements LogEnabled { public String loggerName ( ) { return "" ; } } private class TestListener implements LogListener { LogEvent le ; public void logEvent ( LogEvent logEvent ) { le = logEvent ; } } public void testSimpleLogOutputCaptured ( ) { X x = new X ( ) ; Log4jArchiver archiver = new Log4jArchiver ( x , "" ) ; Logger logger = Logger . getLogger ( "" ) ; logger . setLevel ( Level . DEBUG ) ; logger . debug ( "" ) ; TestListener tl = new TestListener ( ) ; archiver . addLogListener ( tl , x , LogLevel . DEBUG , - , ) ; assertEquals ( "" , "" , tl . le . getMessage ( ) ) ; } private class OurStructural implements Structural { ChildHelper < Object > children = new ChildHelper < Object > ( this ) ; @ Override public void addStructuralListener ( StructuralListener listener ) { children . addStructuralListener ( listener ) ; } @ Override public void removeStructuralListener ( StructuralListener listener ) { children . removeStructuralListener ( listener ) ; } } public void testChildLogOutputCaptured ( ) { X x = new X ( ) ; OurStructural root = new OurStructural ( ) ; root . children . insertChild ( , x ) ; Log4jArchiver archiver = new Log4jArchiver ( root , "" ) ; Logger logger = Logger . getLogger ( "" ) ; logger . setLevel ( Level . DEBUG ) ; logger . debug ( "" ) ; TestListener tl = new TestListener ( ) ; archiver . addLogListener ( tl , x , LogLevel . DEBUG , - , ) ; assertEquals ( "" , "" , tl . le . getMessage ( ) ) ; } private class OurArchiver extends MockLogArchiver implements LogEnabled { public String loggerName ( ) { return "" ; } } public void testLogArchiverChildLogOutputCaptured ( ) { OurArchiver x = new OurArchiver ( ) ; OurStructural root = new OurStructural ( ) ; root . children . insertChild ( , x ) ; Log4jArchiver archiver = new Log4jArchiver ( root , "" ) ; Logger logger = Logger . getLogger ( "" ) ; logger . setLevel ( Level . DEBUG ) ; logger . debug ( "" ) ; TestListener tl = new TestListener ( ) ; archiver . addLogListener ( tl , x , LogLevel . DEBUG , - , ) ; assertEquals ( "" , "" , tl . le . getMessage ( ) ) ; } } package org . oddjob . logging . log4j ; import java . io . IOException ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . apache . log4j . AppenderSkeleton ; import org . apache . log4j . Logger ; import org . apache . log4j . spi . LoggingEvent ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class LogoutTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( LogoutTypeTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; } private class Results extends AppenderSkeleton { List < Object > messages = new ArrayList < Object > ( ) ; @ Override protected void append ( LoggingEvent arg0 ) { messages . add ( arg0 . getMessage ( ) ) ; } @ Override public void close ( ) { } @ Override public boolean requiresLayout ( ) { return false ; } } String EOL = System . getProperty ( "" ) ; String logName = "" ; public void testSimple ( ) throws ArooaConversionException , IOException { Results results = new Results ( ) ; Logger . getLogger ( logName ) . addAppender ( results ) ; LogoutType logout = new LogoutType ( ) ; logout . setLogger ( logName ) ; OutputStream test = logout . toValue ( ) ; test . write ( ( "" + EOL ) . getBytes ( ) ) ; test . close ( ) ; Logger . getLogger ( logName ) . removeAppender ( results ) ; assertEquals ( , results . messages . size ( ) ) ; assertEquals ( "" , results . messages . get ( ) ) ; } public void testLogoutInOddjob ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + EOL + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + EOL + "" + "" + "" + "" + logName + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; Results results = new Results ( ) ; Logger logger = Logger . getLogger ( logName ) ; ; logger . addAppender ( results ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; logger . removeAppender ( results ) ; String sanityCheck = new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ; assertEquals ( "" , sanityCheck . trim ( ) ) ; oddjob . destroy ( ) ; assertTrue ( results . messages . get ( ) . toString ( ) . contains ( "" ) ) ; } public void testExample ( ) { OurDirs dirs = new OurDirs ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; Results results = new Results ( ) ; Logger logger = Logger . getLogger ( LogoutType . class ) ; ; logger . addAppender ( results ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; assertTrue ( results . messages . get ( ) . toString ( ) . trim ( ) . equals ( "" ) ) ; } } package org . oddjob . logging ; public class MockLogArchiver implements LogArchiver { public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int max ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void onDestroy ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeLogListener ( LogListener l , Object component ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . logging ; public class MockConsoleArchiver implements ConsoleArchiver { public void addConsoleListener ( LogListener l , Object component , long last , int max ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeConsoleListener ( LogListener l , Object component ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public String consoleIdFor ( Object component ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void onDestroy ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . logging ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . framework . ComponentBoundry ; import org . oddjob . logging . log4j . Log4jArchiver ; public class OddjobNDCTest extends TestCase implements LogEnabled { private static final Logger logger = Logger . getLogger ( OddjobNDCTest . class ) ; public void testAll ( ) { String loggerName1 = "" ; String loggerName2 = "" ; Object job1 = new Object ( ) ; Object job2 = new Object ( ) ; ComponentBoundry . push ( loggerName1 , job1 ) ; assertEquals ( loggerName1 , OddjobNDC . peek ( ) . getLogger ( ) ) ; assertEquals ( job1 , OddjobNDC . peek ( ) . getJob ( ) ) ; ComponentBoundry . push ( loggerName2 , job2 ) ; assertEquals ( loggerName2 , OddjobNDC . peek ( ) . getLogger ( ) ) ; assertEquals ( job2 , OddjobNDC . peek ( ) . getJob ( ) ) ; assertEquals ( loggerName2 , OddjobNDC . pop ( ) . getLogger ( ) ) ; assertEquals ( loggerName1 , OddjobNDC . pop ( ) . getLogger ( ) ) ; } public void testEmptyPeek ( ) { assertEquals ( null , OddjobNDC . peek ( ) ) ; } class MyLL implements LogListener { String message ; public void logEvent ( LogEvent logEvent ) { message = logEvent . getMessage ( ) ; } } public String loggerName ( ) { return "" ; } public void testWithArchiver ( ) { Log4jArchiver archiver = new Log4jArchiver ( this , "" ) ; MyLL ll = new MyLL ( ) ; archiver . addLogListener ( ll , this , LogLevel . INFO , - , ) ; logger . info ( "" ) ; assertNull ( ll . message ) ; OddjobNDC . push ( loggerName ( ) , new Object ( ) ) ; logger . info ( "" ) ; assertEquals ( "" + Helper . LS , ll . message ) ; OddjobNDC . pop ( ) ; } public void testChildThread ( ) throws InterruptedException { String job = "" ; Log4jArchiver archiver = new Log4jArchiver ( this , "" ) ; MyLL ll = new MyLL ( ) ; archiver . addLogListener ( ll , this , LogLevel . INFO , - , ) ; OddjobNDC . push ( loggerName ( ) , job ) ; Thread t = new Thread ( new Runnable ( ) { public void run ( ) { logger . info ( "" ) ; } } ) ; OddjobNDC . pop ( ) ; t . start ( ) ; t . join ( ) ; assertEquals ( "" + Helper . LS , ll . message ) ; } } package org . oddjob . logging . polling ; import junit . framework . TestCase ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . cache . LogEventSource ; import org . oddjob . logging . cache . PollingLogArchiver ; public class PollingLogArchiverTest extends TestCase { private class OurLogEventSource implements LogEventSource { Object component ; long from ; int max ; public LogEvent [ ] retrieveEvents ( Object component , long from , int max ) { this . component = component ; this . from = from ; this . max = max ; if ( from < ) { return new LogEvent [ ] { new LogEvent ( "" , , LogLevel . INFO , "" ) } ; } else { return new LogEvent [ ] ; } } } private class OurArchiveNameResolver implements ArchiveNameResolver { Object component ; public String resolveName ( Object component ) { this . component = component ; return "" ; } } private class OurLogListener implements LogListener { LogEvent e ; public void logEvent ( LogEvent logEvent ) { this . e = logEvent ; } } public void testPoll ( ) { OurLogEventSource source = new OurLogEventSource ( ) ; OurArchiveNameResolver resolver = new OurArchiveNameResolver ( ) ; Object component = new Object ( ) ; PollingLogArchiver test = new PollingLogArchiver ( resolver , source ) ; OurLogListener l = new OurLogListener ( ) ; test . addLogListener ( l , component , LogLevel . INFO , - , ) ; assertEquals ( "" , component , source . component ) ; assertEquals ( "" , - , source . from ) ; assertEquals ( "" , LogArchiver . MAX_HISTORY , source . max ) ; assertEquals ( "" , component , resolver . component ) ; assertNotNull ( "" , l . e ) ; assertEquals ( "" , "" , l . e . getMessage ( ) ) ; l . e = null ; test . poll ( ) ; assertEquals ( "" , , source . from ) ; assertEquals ( "" , LogArchiver . MAX_HISTORY , source . max ) ; assertNull ( "" , l . e ) ; } } package org . oddjob . logging . polling ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . jmx . client . MockLogPollable ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . cache . LogEventSource ; import org . oddjob . logging . cache . PollingLogArchiver ; public class PollingLogArchiver2Test extends TestCase { Object expected ; class OurEventSource implements LogEventSource { LogEvent [ ] logEvents = { new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) } ; public LogEvent [ ] retrieveEvents ( Object component , long from , int max ) { assertEquals ( expected , component ) ; if ( from < ) { from = ; } long num = Math . min ( max , - from ) ; LogEvent [ ] out = new LogEvent [ ( int ) num ] ; System . arraycopy ( logEvents , ( int ) from - , out , , ( int ) num ) ; return out ; } } class LL implements LogListener { List < LogEvent > results = new ArrayList < LogEvent > ( ) ; public void logEvent ( LogEvent logEvent ) { results . add ( logEvent ) ; } } class OurResolver implements ArchiveNameResolver { public String resolveName ( Object component ) { assertEquals ( expected , component ) ; return "" ; } } public void testSimpleLogEvents ( ) { MockLogPollable root = new MockLogPollable ( ) ; this . expected = root ; PollingLogArchiver test = new PollingLogArchiver ( , new OurResolver ( ) , new OurEventSource ( ) ) ; LL results = new LL ( ) ; test . addLogListener ( results , root , LogLevel . DEBUG , - , ) ; assertEquals ( , results . results . size ( ) ) ; assertEquals ( "" , results . results . get ( ) . getMessage ( ) ) ; test . poll ( ) ; assertEquals ( , results . results . size ( ) ) ; assertEquals ( "" , results . results . get ( ) . getMessage ( ) ) ; test . poll ( ) ; assertEquals ( , results . results . size ( ) ) ; assertEquals ( "" , results . results . get ( ) . getMessage ( ) ) ; } public void testReAddingListener ( ) { MockLogPollable root = new MockLogPollable ( ) ; this . expected = root ; PollingLogArchiver test = new PollingLogArchiver ( , new OurResolver ( ) , new OurEventSource ( ) ) ; LL results = new LL ( ) ; assertEquals ( , results . results . size ( ) ) ; test . poll ( ) ; test . addLogListener ( results , root , LogLevel . DEBUG , - , ) ; assertEquals ( , results . results . size ( ) ) ; assertEquals ( "" , results . results . get ( ) . getMessage ( ) ) ; test . removeLogListener ( results , root ) ; test . addLogListener ( results , root , LogLevel . DEBUG , , ) ; assertEquals ( , results . results . size ( ) ) ; assertEquals ( "" , results . results . get ( ) . getMessage ( ) ) ; test . poll ( ) ; assertEquals ( , results . results . size ( ) ) ; assertEquals ( "" , results . results . get ( ) . getMessage ( ) ) ; test . removeLogListener ( results , root ) ; } } package org . oddjob . logging . cache ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class MockLogArchiverCache implements LogArchiverCache { @ Override public void addEvent ( String archive , LogLevel level , String message ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int history ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void destroy ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public long getLastMessageNumber ( String archive ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public int getMaxHistory ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public boolean hasArchive ( String archive ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void removeLogListener ( LogListener l , Object component ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . logging . cache ; import junit . framework . TestCase ; import org . oddjob . Structural ; import org . oddjob . logging . ArchiveNameResolver ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogHelper ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . cache . StructuralArchiverCache ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class StructuralArchiverCacheTest extends TestCase { public class Thing implements LogEnabled { public String loggerName ( ) { return "" ; } } class MyLL implements LogListener { LogEvent lev ; int count ; public void logEvent ( LogEvent logEvent ) { count ++ ; lev = logEvent ; } } class R implements ArchiveNameResolver { public String resolveName ( Object component ) { return LogHelper . getLogger ( component ) ; } } public void testAddEvent ( ) { Thing thing = new Thing ( ) ; StructuralArchiverCache test = new StructuralArchiverCache ( thing , new R ( ) ) ; assertEquals ( - , test . getLastMessageNumber ( "" ) ) ; MyLL ll = new MyLL ( ) ; test . addLogListener ( ll , thing , LogLevel . DEBUG , - , ) ; assertNull ( ll . lev ) ; test . addEvent ( "" , LogLevel . DEBUG , "" ) ; assertEquals ( "" , ll . lev . getMessage ( ) ) ; assertEquals ( , ll . lev . getNumber ( ) ) ; } public void testBadAddListeners ( ) { Thing thing = new Thing ( ) ; StructuralArchiverCache test = new StructuralArchiverCache ( thing , new R ( ) ) ; MyLL ll = new MyLL ( ) ; test . addLogListener ( ll , thing , LogLevel . DEBUG , - , ) ; assertNull ( ll . lev ) ; test . removeLogListener ( ll , thing ) ; test . addLogListener ( ll , thing , LogLevel . DEBUG , , - ) ; assertNull ( ll . lev ) ; test . removeLogListener ( ll , thing ) ; } public void TestAddListenLater ( ) { Thing t = new Thing ( ) ; StructuralArchiverCache lai = new StructuralArchiverCache ( t , new R ( ) ) ; lai . addEvent ( "" , LogLevel . DEBUG , "" ) ; lai . addEvent ( "" , LogLevel . DEBUG , "" ) ; lai . addEvent ( "" , LogLevel . DEBUG , "" ) ; assertEquals ( , lai . getLastMessageNumber ( "" ) ) ; MyLL ll = new MyLL ( ) ; lai . addLogListener ( ll , "" , LogLevel . DEBUG , - , ) ; assertEquals ( "" , ll . lev . getMessage ( ) ) ; assertEquals ( , ll . count ) ; assertEquals ( , ll . lev . getNumber ( ) ) ; } class S implements Structural { public void addStructuralListener ( StructuralListener listener ) { listener . childAdded ( new StructuralEvent ( this , new Thing ( ) , ) ) ; listener . childAdded ( new StructuralEvent ( this , new Thing ( ) , ) ) ; listener . childRemoved ( new StructuralEvent ( this , new Thing ( ) , ) ) ; listener . childRemoved ( new StructuralEvent ( this , new Thing ( ) , ) ) ; } public void removeStructuralListener ( StructuralListener listener ) { } } public void TestSameArchiveName ( ) { S s = new S ( ) ; StructuralArchiverCache lai = new StructuralArchiverCache ( s , new R ( ) ) ; assertFalse ( lai . hasArchive ( "" ) ) ; } } package org . oddjob . logging ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . LazyDynaBean ; import org . oddjob . Reserved ; import org . oddjob . arooa . beanutils . BeanUtilsPropertyAccessor ; import org . oddjob . arooa . reflect . ArooaPropertyException ; public class LogHelperTest extends TestCase { public static class AnyDynaBean implements DynaBean { DynaBean delegate = new LazyDynaBean ( ) ; public boolean contains ( String name , String key ) { return delegate . contains ( name , key ) ; } public Object get ( String name ) { return delegate . get ( name ) ; } public Object get ( String name , int index ) { return delegate . get ( name , index ) ; } public Object get ( String name , String key ) { return delegate . get ( name , key ) ; } public DynaClass getDynaClass ( ) { return delegate . getDynaClass ( ) ; } public void remove ( String name , String key ) { delegate . remove ( name , key ) ; } public void set ( String name , int index , Object value ) { delegate . set ( name , index , value ) ; } public void set ( String name , Object value ) { delegate . set ( name , value ) ; } public void set ( String name , String key , Object value ) { delegate . set ( name , key , value ) ; } public String loggerName ( ) { return "" ; } } public void testTheProblem ( ) throws ArooaPropertyException { String loggerName = ( String ) new BeanUtilsPropertyAccessor ( ) . getProperty ( new AnyDynaBean ( ) , Reserved . LOGGER_PROPERTY ) ; assertNull ( "" , loggerName ) ; } class TheSolution extends AnyDynaBean implements LogEnabled { } public void testTheSolution ( ) { String loggerName = LogHelper . getLogger ( new TheSolution ( ) ) ; assertEquals ( "" , "" , loggerName ) ; } } package org . oddjob . logging . console ; import junit . framework . TestCase ; import org . oddjob . logging . ConsoleOwner ; import org . oddjob . logging . LogArchive ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . cache . LocalConsoleArchiver ; import org . oddjob . logging . cache . LogArchiveImpl ; public class LocalConsoleArchiverTest extends TestCase { static final String LS = System . getProperty ( "" ) ; class MyLL implements LogListener { String text ; long num ; public synchronized void logEvent ( LogEvent logEvent ) { text = logEvent . getMessage ( ) ; num = logEvent . getNumber ( ) ; } } public void testArchiveAndRetrieve ( ) { LocalConsoleArchiver test = new LocalConsoleArchiver ( ) ; System . out . println ( "" ) ; MyLL ll = new MyLL ( ) ; test . addConsoleListener ( ll , new Object ( ) , - , ) ; synchronized ( ll ) { System . out . println ( "" ) ; long before = ll . num ; assertEquals ( "" + LS , ll . text ) ; System . out . println ( "" ) ; assertEquals ( before + , ll . num ) ; assertEquals ( "" + LS , ll . text ) ; test . removeConsoleListener ( ll , new Object ( ) ) ; System . out . println ( "" ) ; assertEquals ( before + , ll . num ) ; assertEquals ( "" + System . getProperty ( "" ) , ll . text ) ; } } public void testConsoleArchive ( ) { class CA implements ConsoleOwner { LogArchiveImpl la = new LogArchiveImpl ( "" , ) ; public LogArchive consoleLog ( ) { return la ; } } CA ca = new CA ( ) ; LocalConsoleArchiver test = new LocalConsoleArchiver ( ) ; MyLL ll = new MyLL ( ) ; test . addConsoleListener ( ll , ca , - , ) ; ca . la . addEvent ( LogLevel . INFO , "" ) ; assertEquals ( , ll . num ) ; assertEquals ( "" , ll . text ) ; ca . la . addEvent ( LogLevel . INFO , "" ) ; assertEquals ( , ll . num ) ; assertEquals ( "" , ll . text ) ; test . removeConsoleListener ( ll , ca ) ; ca . la . addEvent ( LogLevel . WARN , "" ) ; assertEquals ( , ll . num ) ; assertEquals ( "" , ll . text ) ; } } package org . oddjob . logging ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . util . IO ; public class LoggingOutputStreamTest extends TestCase { private static final Logger logger = Logger . getLogger ( LoggingOutputStreamTest . class ) ; OutputStream test ; final List < String > text = new ArrayList < String > ( ) ; LogLevel level ; class OurLogEventSink implements LogEventSink { public void addEvent ( LogLevel level , String line ) { LoggingOutputStreamTest . this . level = level ; text . add ( line ) ; } } protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; test = new LoggingOutputStream ( null , LogLevel . WARN , new OurLogEventSink ( ) ) ; level = null ; } public void testByteArray ( ) throws IOException { test . write ( "" . getBytes ( ) ) ; assertEquals ( , text . size ( ) ) ; assertEquals ( "" , text . get ( ) ) ; test . close ( ) ; assertEquals ( , text . size ( ) ) ; assertEquals ( "" , text . get ( ) ) ; } public void testByteArray2 ( ) throws IOException { test . write ( "" . getBytes ( ) , , ) ; assertEquals ( , text . size ( ) ) ; assertEquals ( "" , text . get ( ) ) ; test . close ( ) ; assertEquals ( , text . size ( ) ) ; assertEquals ( "" , text . get ( ) ) ; } public void testAdd ( ) throws IOException { class LA implements LogEventSink { String [ ] expected = { "" , "" } ; String [ ] results = new String [ expected . length ] ; int count = ; public void addEvent ( LogLevel level , String line ) { results [ count ++ ] = line ; } } LA la = new LA ( ) ; ByteArrayOutputStream dummy = new ByteArrayOutputStream ( ) ; LoggingOutputStream test = new LoggingOutputStream ( dummy , LogLevel . DEBUG , la ) ; byte ba [ ] = new byte [ ] { '' , '' , '' } ; test . add ( ba , , ba . length ) ; for ( int i = ; i < la . results . length ; ++ i ) { assertEquals ( la . expected [ i ] , la . results [ i ] ) ; } } public void testWindowsBytes ( ) throws IOException { byte [ ] bytes = { , , , , , , , , , , , , , , , } ; IO . copy ( new ByteArrayInputStream ( bytes ) , test ) ; test . close ( ) ; assertEquals ( , text . size ( ) ) ; assertEquals ( "" , text . get ( ) ) ; assertEquals ( "" , text . get ( ) ) ; } } package org . oddjob . logging ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . logging . cache . LogArchiveImpl ; public class LogArchiveImplTest extends TestCase { public void testFullArchive ( ) { class MyL implements LogListener { String previous ; String message ; public void logEvent ( LogEvent logEvent ) { previous = message ; message = logEvent . getMessage ( ) ; } } MyL l = new MyL ( ) ; LogArchiveImpl test = new LogArchiveImpl ( "" , ) ; test . addListener ( l , LogLevel . DEBUG , , ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; assertEquals ( "" , l . message ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; assertEquals ( "" , l . message ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; assertEquals ( "" , l . message ) ; MyL l2 = new MyL ( ) ; test . addListener ( l2 , LogLevel . DEBUG , , ) ; assertEquals ( "" , l2 . message ) ; assertNull ( l2 . previous ) ; } public void testOneMessage ( ) { class MyL implements LogListener { List < LogEvent > results = new ArrayList < LogEvent > ( ) ; public void logEvent ( LogEvent logEvent ) { results . add ( logEvent ) ; } } LogArchiveImpl test = new LogArchiveImpl ( "" , ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; MyL l = new MyL ( ) ; test . addListener ( l , LogLevel . DEBUG , - , ) ; assertEquals ( , l . results . size ( ) ) ; assertEquals ( , l . results . get ( ) . getNumber ( ) ) ; MyL l2 = new MyL ( ) ; test . addListener ( l2 , LogLevel . DEBUG , , ) ; assertEquals ( , l2 . results . size ( ) ) ; } public void testFromMessage ( ) { class MyL implements LogListener { List < LogEvent > results = new ArrayList < LogEvent > ( ) ; public void logEvent ( LogEvent logEvent ) { results . add ( logEvent ) ; } } LogArchiveImpl test = new LogArchiveImpl ( "" , ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; MyL l = new MyL ( ) ; test . addListener ( l , LogLevel . DEBUG , , ) ; assertEquals ( , l . results . size ( ) ) ; assertEquals ( "" , l . results . get ( ) . getMessage ( ) ) ; MyL l2 = new MyL ( ) ; test . addListener ( l2 , LogLevel . DEBUG , , ) ; assertEquals ( , l2 . results . size ( ) ) ; test . removeListener ( l2 ) ; test . addListener ( l2 , LogLevel . DEBUG , , ) ; assertEquals ( , l2 . results . size ( ) ) ; } public void testLevel ( ) { class MyL implements LogListener { List < LogEvent > results = new ArrayList < LogEvent > ( ) ; public void logEvent ( LogEvent logEvent ) { results . add ( logEvent ) ; } } LogArchiveImpl test = new LogArchiveImpl ( "" , ) ; test . addEvent ( LogLevel . DEBUG , "" ) ; test . addEvent ( LogLevel . INFO , "" ) ; test . addEvent ( LogLevel . WARN , "" ) ; test . addEvent ( LogLevel . ERROR , "" ) ; test . addEvent ( LogLevel . FATAL , "" ) ; MyL l = new MyL ( ) ; test . addListener ( l , LogLevel . DEBUG , - , ) ; assertEquals ( , l . results . size ( ) ) ; assertEquals ( "" , l . results . get ( ) . getMessage ( ) ) ; MyL l2 = new MyL ( ) ; test . addListener ( l2 , LogLevel . INFO , - , ) ; assertEquals ( , l2 . results . size ( ) ) ; assertEquals ( "" , l2 . results . get ( ) . getMessage ( ) ) ; MyL l3 = new MyL ( ) ; test . addListener ( l3 , LogLevel . WARN , - , ) ; assertEquals ( , l3 . results . size ( ) ) ; assertEquals ( "" , l3 . results . get ( ) . getMessage ( ) ) ; MyL l4 = new MyL ( ) ; test . addListener ( l4 , LogLevel . ERROR , - , ) ; assertEquals ( , l4 . results . size ( ) ) ; assertEquals ( "" , l4 . results . get ( ) . getMessage ( ) ) ; MyL l5 = new MyL ( ) ; test . addListener ( l5 , LogLevel . FATAL , - , ) ; assertEquals ( , l5 . results . size ( ) ) ; assertEquals ( "" , l5 . results . get ( ) . getMessage ( ) ) ; } } package org . oddjob . logging ; import java . io . IOException ; import java . io . PrintStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . logging . cache . LogArchiveImpl ; public class LoggingPrintStreamTest extends TestCase { PrintStream test ; final List < String > text = new ArrayList < String > ( ) ; LogLevel level ; class MyLL implements LogListener { public void logEvent ( LogEvent logEvent ) { level = logEvent . getLevel ( ) ; text . add ( logEvent . getMessage ( ) ) ; } } protected void setUp ( ) { LogArchiveImpl logArchive = new LogArchiveImpl ( "" , ) ; test = new LoggingPrintStream ( System . out , LogLevel . WARN , logArchive ) ; level = null ; logArchive . addListener ( new MyLL ( ) , LogLevel . DEBUG , - , ) ; } public void testPrintlnString ( ) { test . println ( "" ) ; assertEquals ( , text . size ( ) ) ; assertEquals ( "" + System . getProperty ( "" ) , text . get ( ) ) ; assertEquals ( LogLevel . WARN , level ) ; } public void testLn ( ) throws IOException { test . print ( "" ) ; assertEquals ( , text . size ( ) ) ; test . println ( ) ; assertEquals ( , text . size ( ) ) ; assertEquals ( "" + System . getProperty ( "" ) , text . get ( ) ) ; } } package org . oddjob ; import java . io . IOException ; import java . io . Serializable ; import junit . framework . TestCase ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . framework . Service ; public class OddjobComponentResolverTest extends TestCase { public void testRunnable ( ) { OddjobComponentResolver test = new OddjobComponentResolver ( ) ; Runnable runnable = new Runnable ( ) { public void run ( ) { } } ; Object proxy = test . resolve ( runnable , new MockArooaSession ( ) ) ; assertTrue ( proxy instanceof Runnable ) ; } public static class OurService implements Service { public void start ( ) { } public void stop ( ) { } } public void testService ( ) { OddjobComponentResolver test = new OddjobComponentResolver ( ) ; Object proxy = test . resolve ( new OurService ( ) , new MockArooaSession ( ) ) ; assertTrue ( proxy instanceof Runnable ) ; } static class OurSerializableRunnable implements Runnable , Serializable { private static final long serialVersionUID = ; String colour = "" ; public void run ( ) { } } public void testRestore ( ) throws IOException , ClassNotFoundException { OddjobComponentResolver test = new OddjobComponentResolver ( ) ; Object job = new OurSerializableRunnable ( ) ; Object proxy = test . resolve ( job , new MockArooaSession ( ) ) ; Object restoredProxy = Helper . copy ( proxy ) ; Object restoredJob = test . restore ( restoredProxy , new MockArooaSession ( ) ) ; assertEquals ( OurSerializableRunnable . class , restoredJob . getClass ( ) ) ; assertEquals ( ( ( OurSerializableRunnable ) job ) . colour , "" ) ; } } package org . oddjob . describe ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import org . oddjob . Describeable ; public class DescribeableDescriberTest extends TestCase implements Describeable { public Map < String , String > describe ( ) { Map < String , String > description = new HashMap < String , String > ( ) ; description . put ( "" , "" ) ; return description ; } public void testDescribeableDescriberMethod ( ) { Describer test = new DescribeableDescriber ( ) ; Map < String , String > result = test . describe ( this ) ; assertEquals ( , result . size ( ) ) ; assertEquals ( "" , result . get ( "" ) ) ; } } package org . oddjob . describe ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardArooaSession ; public class AnnotationDescriberTest extends TestCase { @ DescribeWith public Map < String , String > myDescription ( ) { Map < String , String > description = new HashMap < String , String > ( ) ; description . put ( "" , "" ) ; return description ; } public void testAnnotedDescriberMethod ( ) { ArooaSession session = new StandardArooaSession ( ) ; Describer test = new AnnotationDescriber ( session ) ; Map < String , String > result = test . describe ( this ) ; assertEquals ( , result . size ( ) ) ; assertEquals ( "" , result . get ( "" ) ) ; } } package org . oddjob . describe ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . LazyDynaMap ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . beanutils . MagicBeanDefinition ; import org . oddjob . arooa . beanutils . MagicBeanProperty ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . framework . WrapDynaBean ; public class AccessorDescriberTest extends TestCase { public static class SimpleBean { public String getFruit ( ) { return "" ; } @ NoDescribe public String getColour ( ) { return "" ; } } public void testSimpleBean ( ) { ArooaSession session = new StandardArooaSession ( ) ; Describer test = new AccessorDescriber ( session ) ; Map < String , String > description = test . describe ( new SimpleBean ( ) ) ; assertEquals ( , description . size ( ) ) ; assertEquals ( "" , description . get ( "" ) ) ; } public static class SetterOnlyBean { public void setFruit ( String fruit ) { } } public void testDynaBean ( ) { ArooaSession session = new StandardArooaSession ( ) ; WrapDynaBean wrap = new WrapDynaBean ( new SetterOnlyBean ( ) ) ; Describer test = new AccessorDescriber ( session ) ; Map < String , String > description = test . describe ( wrap ) ; assertEquals ( , description . size ( ) ) ; assertEquals ( SetterOnlyBean . class . toString ( ) , description . get ( "" ) ) ; } public void testCapitalPropertiesDynaBean ( ) { ArooaSession session = new StandardArooaSession ( ) ; LazyDynaMap bean = new LazyDynaMap ( ) ; bean . set ( "" , "" ) ; Describer test = new AccessorDescriber ( session ) ; Map < String , String > description = test . describe ( bean ) ; assertEquals ( , description . size ( ) ) ; assertEquals ( "" , description . get ( "" ) ) ; } public void testMagicDynaBean ( ) { ArooaSession session = new StandardArooaSession ( ) ; MagicBeanDefinition def = new MagicBeanDefinition ( ) ; def . setName ( "" ) ; MagicBeanProperty prop0 = new MagicBeanProperty ( ) ; prop0 . setName ( "" ) ; prop0 . setType ( String . class . getName ( ) ) ; def . setProperties ( , prop0 ) ; ArooaClass arooaClass = def . createMagic ( getClass ( ) . getClassLoader ( ) ) ; DynaBean bean = ( DynaBean ) arooaClass . newInstance ( ) ; bean . set ( "" , "" ) ; Describer test = new AccessorDescriber ( session ) ; Map < String , String > description = test . describe ( bean ) ; assertEquals ( , description . size ( ) ) ; assertEquals ( "" , description . get ( "" ) ) ; } } package org . oddjob . io ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . oddjob . ConverterHelper ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . MockArooaBeanDescriptor ; import org . oddjob . arooa . ParsingInterceptor ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . deploy . NoAnnotations ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class FileTypeTest extends TestCase { File ourFile ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; OurDirs dirs = new OurDirs ( ) ; ourFile = dirs . relative ( "" ) ; } public static class Bean implements Runnable { File file ; File [ ] files ; InputStream is ; OutputStream os ; public void setFile ( File file ) { this . file = file ; } public File getFile ( ) { return file ; } public void setFiles ( File [ ] files ) { this . files = files ; } public File [ ] getFiles ( ) { return files ; } public void setIs ( InputStream is ) { this . is = is ; } public InputStream getIs ( ) { return is ; } public void setOs ( OutputStream os ) { this . os = os ; } public OutputStream getOs ( ) { return os ; } public void run ( ) { } } public static class BeanArooa extends MockArooaBeanDescriptor { @ Override public ParsingInterceptor getParsingInterceptor ( ) { return null ; } @ Override public ConfiguredHow getConfiguredHow ( String property ) { return ConfiguredHow . ATTRIBUTE ; } @ Override public String getComponentProperty ( ) { return null ; } @ Override public boolean isAuto ( String property ) { return false ; } @ Override public ArooaAnnotations getAnnotations ( ) { return new NoAnnotations ( ) ; } } public void testFileManefestation ( ) throws Exception { FileType test = new FileType ( ) ; test . setFile ( ourFile ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; Object v = converter . convert ( test , File . class ) ; assertTrue ( v instanceof File ) ; } public void testInputStream ( ) throws Exception { ourFile . createNewFile ( ) ; FileType test = new FileType ( ) ; test . setFile ( ourFile ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; Object result = converter . convert ( test , InputStream . class ) ; assertTrue ( result instanceof InputStream ) ; } public void testOutputStream ( ) throws Exception { FileType test = new FileType ( ) ; test . setFile ( ourFile ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; Object result = converter . convert ( test , OutputStream . class ) ; assertTrue ( result instanceof OutputStream ) ; } public void testInOddjob ( ) throws IOException { ourFile . delete ( ) ; ourFile . createNewFile ( ) ; String xml = "" + "" + "" + "" + "" + "" + "" + ourFile . getPath ( ) + "" + "" + "" + "" + Bean . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; DynaBean bean = ( DynaBean ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( ourFile , bean . get ( "" ) ) ; File [ ] files = ( File [ ] ) bean . get ( "" ) ; assertEquals ( , files . length ) ; assertEquals ( ourFile , files [ ] ) ; OutputStream os = ( OutputStream ) bean . get ( "" ) ; os . write ( '' ) ; os . flush ( ) ; os . close ( ) ; InputStream is = ( InputStream ) bean . get ( "" ) ; char c = ( char ) is . read ( ) ; assertEquals ( '' , c ) ; is . close ( ) ; } public void testNullFile ( ) throws Exception { FileType test = new FileType ( ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; Object result = converter . convert ( test , File . class ) ; assertNull ( result ) ; } public void testNullInOddjob ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Properties props = lookup . lookup ( "" , Properties . class ) ; assertEquals ( null , props . getProperty ( "" ) ) ; oddjob . destroy ( ) ; } public void testInvalidFileName ( ) { FileType test = new FileType ( ) ; test . setFile ( new File ( "" ) ) ; try { test . toCanonicalFile ( ) ; fail ( "" ) ; } catch ( IOException e ) { } } public void testSerialisation ( ) throws IOException , ClassNotFoundException { FileType test = new FileType ( ) ; test . setFile ( new File ( "" ) ) ; FileType copy = Helper . copy ( test ) ; assertEquals ( copy . toCanonicalFile ( ) , test . toCanonicalFile ( ) ) ; } } package org . oddjob . io ; import java . io . File ; import java . lang . reflect . InvocationTargetException ; import org . apache . commons . beanutils . PropertyUtils ; import org . oddjob . FragmentHelper ; import org . oddjob . arooa . ArooaParseException ; import junit . framework . TestCase ; public class StdinTypeTest extends TestCase { public void testExample ( ) throws ArooaParseException , IllegalAccessException , InvocationTargetException , NoSuchMethodException { FragmentHelper helper = new FragmentHelper ( ) ; Object copy = helper . createComponentFromResource ( "" ) ; assertEquals ( new File ( "" ) , PropertyUtils . getProperty ( copy , "" ) ) ; } } package org . oddjob . io ; import java . io . IOException ; import java . io . OutputStream ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FragmentHelper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . logging . LoggingPrintStream ; public class StdoutTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( StdoutTypeTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; } String EOL = System . getProperty ( "" ) ; public void testSimple ( ) throws ArooaConversionException , IOException { ConsoleCapture results = new ConsoleCapture ( ) ; results . capture ( Oddjob . CONSOLE ) ; OutputStream output = System . out ; assertEquals ( LoggingPrintStream . class . getName ( ) , output . getClass ( ) . getName ( ) ) ; OutputStream test = new StdoutType ( ) . toValue ( ) ; test . write ( ( "" + EOL ) . getBytes ( ) ) ; test . close ( ) ; results . close ( ) ; results . dump ( logger ) ; assertEquals ( "" + EOL , results . getAll ( ) ) ; } public void testStdoutInOddjob ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + EOL + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + EOL + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; ConsoleCapture results = new ConsoleCapture ( ) ; results . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; results . close ( ) ; String sanityCheck = new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ; assertEquals ( "" , sanityCheck . trim ( ) ) ; oddjob . destroy ( ) ; results . dump ( logger ) ; String [ ] lines = results . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; } public void testExample ( ) throws ArooaParseException { OurDirs dirs = new OurDirs ( ) ; Properties properties = new Properties ( ) ; properties . setProperty ( "" , dirs . relative ( "" ) . getPath ( ) ) ; FragmentHelper helper = new FragmentHelper ( ) ; helper . setProperties ( properties ) ; Runnable copy = ( Runnable ) helper . createComponentFromResource ( "" ) ; ConsoleCapture results = new ConsoleCapture ( ) ; results . capture ( Oddjob . CONSOLE ) ; copy . run ( ) ; results . close ( ) ; String [ ] lines = results . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; } } package org . oddjob . io ; import java . io . File ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OurDirs ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class DeleteJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( DeleteJobTest . class ) ; File dir ; public void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; OurDirs dirs = new OurDirs ( ) ; dir = dirs . relative ( "" ) ; if ( dir . exists ( ) ) { FileUtils . forceDelete ( dir ) ; } } public void testDeleteFile ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; FileUtils . touch ( new File ( dir , "" ) ) ; WildcardSpec wild = new WildcardSpec ( new File ( dir , "" ) ) ; File [ ] found = wild . findFiles ( ) ; assertEquals ( , found . length ) ; String xml = "" + "" + "" + "" + "" + dir . getPath ( ) + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; found = wild . findFiles ( ) ; assertEquals ( , found . length ) ; } public void testDeleteFiles ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; FileUtils . touch ( new File ( dir , "" ) ) ; FileUtils . touch ( new File ( dir , "" ) ) ; FileUtils . touch ( new File ( dir , "" ) ) ; WildcardSpec wild = new WildcardSpec ( new File ( dir , "" ) ) ; File [ ] found = wild . findFiles ( ) ; assertEquals ( , found . length ) ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . setArgs ( new String [ ] { dir . getPath ( ) . toString ( ) } ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; found = wild . findFiles ( ) ; assertEquals ( , found . length ) ; } public void testDeleteDir ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; String xml = "" + "" + "" + "" + "" + dir . getPath ( ) + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; assertFalse ( dir . exists ( ) ) ; } public void testDeleteFullDir ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; FileUtils . touch ( new File ( dir , "" ) ) ; FileUtils . touch ( new File ( dir , "" ) ) ; FileUtils . touch ( new File ( dir , "" ) ) ; String xml = "" + "" + "" + "" + "" + dir . getPath ( ) + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . EXCEPTION , oj . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( dir . exists ( ) ) ; xml = "" + "" + "" + "" + "" + dir . getPath ( ) + "" + "" + "" + "" + "" ; oj . hardReset ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; assertFalse ( dir . exists ( ) ) ; oj . destroy ( ) ; } public void testSerialize ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; assertTrue ( dir . exists ( ) ) ; DeleteJob test = new DeleteJob ( ) ; test . setFiles ( new File [ ] { dir } ) ; Runnable copy = ( Runnable ) Helper . copy ( test ) ; copy . run ( ) ; assertFalse ( dir . exists ( ) ) ; } } package org . oddjob . io ; import java . io . File ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OurDirs ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class MkdirJobTest extends TestCase { File dir ; public void setUp ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; dir = dirs . relative ( "" ) ; if ( dir . exists ( ) ) { FileUtils . forceDelete ( dir ) ; } } public void testSimple ( ) { MkdirJob test = new MkdirJob ( ) ; test . setDir ( dir ) ; test . run ( ) ; assertTrue ( dir . exists ( ) ) ; } public void testFileExists ( ) throws Exception { FileUtils . touch ( dir ) ; MkdirJob test = new MkdirJob ( ) ; test . setDir ( dir ) ; try { test . run ( ) ; fail ( "" ) ; } catch ( Exception e ) { } assertTrue ( dir . isFile ( ) ) ; } public void testDirExists ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; MkdirJob test = new MkdirJob ( ) ; test . setDir ( dir ) ; test . run ( ) ; assertTrue ( dir . isDirectory ( ) ) ; } public void testMissingParents ( ) throws Exception { File create = new File ( dir , "" ) ; MkdirJob test = new MkdirJob ( ) ; test . setDir ( create ) ; test . run ( ) ; assertTrue ( create . exists ( ) ) ; } public void testInOddjob ( ) { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . setArgs ( new String [ ] { dir . getPath ( ) } ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( new File ( dir , "" ) . exists ( ) ) ; } public void testSerailize ( ) throws Exception { MkdirJob test = new MkdirJob ( ) ; test . setDir ( dir ) ; Runnable copy = ( Runnable ) Helper . copy ( test ) ; copy . run ( ) ; assertTrue ( dir . exists ( ) ) ; } } package org . oddjob . io ; import java . io . File ; import java . io . FileInputStream ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . oddjob . Oddjob ; import org . oddjob . OurDirs ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class AppendTypeTest extends TestCase { File outputDir ; public void setUp ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; outputDir = new File ( dirs . base ( ) , "" ) ; if ( outputDir . exists ( ) ) { FileUtils . forceDelete ( outputDir ) ; } } public void testExample ( ) throws Exception { FileUtils . forceMkdir ( outputDir ) ; Oddjob oj = new Oddjob ( ) ; oj . setArgs ( new String [ ] { outputDir . toString ( ) } ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; File resultFile = new File ( outputDir , "" ) ; assertTrue ( resultFile . exists ( ) ) ; BufferType buffer = new BufferType ( ) ; buffer . configured ( ) ; CopyJob copy = new CopyJob ( ) ; copy . setInput ( new FileInputStream ( resultFile ) ) ; copy . setOutput ( buffer . toOutputStream ( ) ) ; copy . run ( ) ; String [ ] lines = buffer . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] ) ; assertEquals ( "" , lines [ ] ) ; } } package org . oddjob . io ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; import org . oddjob . io . WildcardSpec . AboveAndBelow ; import org . oddjob . io . WildcardSpec . DirectorySplit ; public class WildcardSpecTest extends TestCase { public void testAboveAndBelow ( ) throws IOException { File f = new File ( "" ) ; AboveAndBelow ab1 = new AboveAndBelow ( f ) ; assertEquals ( new File ( "" ) , ab1 . parent ) ; assertEquals ( "" , ab1 . name ) ; assertNull ( ab1 . below ) ; assertFalse ( ab1 . top ) ; AboveAndBelow ab2 = new AboveAndBelow ( ab1 ) ; assertEquals ( new File ( "" ) , ab2 . parent ) ; assertEquals ( "" , ab2 . name ) ; assertEquals ( new File ( "" ) , ab2 . below ) ; assertFalse ( ab2 . top ) ; AboveAndBelow ab3 = new AboveAndBelow ( ab2 ) ; assertEquals ( new File ( "" ) , ab3 . parent ) ; assertEquals ( "" , ab3 . name ) ; assertEquals ( new File ( "" ) , ab3 . below ) ; assertFalse ( ab3 . top ) ; AboveAndBelow ab4 = new AboveAndBelow ( ab3 ) ; assertEquals ( new File ( "" ) , ab4 . parent ) ; assertEquals ( "" , ab4 . name ) ; assertEquals ( new File ( "" ) , ab4 . below ) ; assertFalse ( ab4 . top ) ; AboveAndBelow ab5 = new AboveAndBelow ( ab4 ) ; assertEquals ( new File ( "" ) . getAbsoluteFile ( ) . getParentFile ( ) , ab5 . parent ) ; assertEquals ( "" , ab5 . name ) ; assertEquals ( new File ( "" ) , ab5 . below ) ; assertTrue ( ab5 . top ) ; } public void testAboveAndBelow2 ( ) throws IOException { File f = new File ( "" ) ; AboveAndBelow ab1 = new AboveAndBelow ( f ) ; assertNull ( ab1 . parent ) ; assertEquals ( "" , ab1 . name ) ; assertNull ( ab1 . below ) ; assertTrue ( ab1 . top ) ; } public void testAboveAndBelow3 ( ) throws IOException { File f = new File ( "" ) ; AboveAndBelow ab1 = new AboveAndBelow ( f ) ; assertEquals ( new File ( "" ) , ab1 . parent ) ; assertEquals ( "" , ab1 . name ) ; assertNull ( ab1 . below ) ; assertFalse ( ab1 . top ) ; AboveAndBelow ab2 = new AboveAndBelow ( ab1 ) ; assertEquals ( new File ( "" ) , ab2 . parent ) ; assertEquals ( "" , ab2 . name ) ; assertEquals ( new File ( "" ) , ab2 . below ) ; assertTrue ( ab2 . top ) ; } public void testSplitRelative ( ) { DirectorySplit test = new DirectorySplit ( new File ( "" ) ) ; assertEquals ( , test . getSize ( ) ) ; assertEquals ( new File ( "" ) , test . getParentFile ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; test = test . next ( "" ) ; assertEquals ( new File ( "" ) , test . getParentFile ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; test = test . next ( "" ) ; assertEquals ( new File ( "" ) , test . getParentFile ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertNull ( test . next ( "" ) ) ; } public void testSplitAbsolute ( ) { DirectorySplit test = new DirectorySplit ( new File ( "" ) ) ; assertEquals ( , test . getSize ( ) ) ; assertEquals ( new File ( "" ) , test . getParentFile ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; test = test . next ( "" ) ; assertEquals ( new File ( "" ) , test . getParentFile ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; test = test . next ( "" ) ; assertEquals ( new File ( "" ) , test . getParentFile ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertNull ( test . next ( "" ) ) ; } public void testSimple ( ) { OurDirs dirs = new OurDirs ( ) ; WildcardSpec test = new WildcardSpec ( dirs . base ( ) + "" ) ; File [ ] result = test . findFiles ( ) ; assertEquals ( , result . length ) ; Set < File > set = new HashSet < File > ( Arrays . asList ( result ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) + "" ) ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) + "" ) ) ) ; } public void testHarder ( ) { OurDirs dirs = new OurDirs ( ) ; WildcardSpec test = new WildcardSpec ( dirs . base ( ) + "" ) ; File [ ] result = test . findFiles ( ) ; assertEquals ( , result . length ) ; Set < File > set = new HashSet < File > ( Arrays . asList ( result ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) + "" ) ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) + "" ) ) ) ; } public void testHarder2 ( ) { OurDirs dirs = new OurDirs ( ) ; WildcardSpec test = new WildcardSpec ( new File ( dirs . base ( ) , "" ) . getPath ( ) ) ; File [ ] result = test . findFiles ( ) ; assertEquals ( , result . length ) ; Set < File > set = new HashSet < File > ( Arrays . asList ( result ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) , "" ) ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) , "" ) ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) , "" ) ) ) ; } } package org . oddjob . io ; import java . io . File ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class CopyJobTest extends TestCase { File reference ; File dir ; public void setUp ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; reference = new File ( dirs . base ( ) , "" ) ; dir = new File ( dirs . base ( ) , "" ) ; if ( dir . exists ( ) ) { FileUtils . forceDelete ( dir ) ; } } public void testCopyFile ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; OurDirs dirs = new OurDirs ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( new File ( dir , "" ) . exists ( ) ) ; } public void testCopyFiles ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; OurDirs dirs = new OurDirs ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , new WildcardSpec ( new File ( dir , "" ) ) . findFiles ( ) . length ) ; } public void testCopyDirectory ( ) throws Exception { FileUtils . forceMkdir ( dir ) ; OurDirs dirs = new OurDirs ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( new File ( dir , "" ) . exists ( ) ) ; } public void testCopyDirectory2 ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( new File ( dir , "" ) . exists ( ) ) ; } public void testSerialize ( ) throws Exception { dir . mkdir ( ) ; OurDirs dirs = new OurDirs ( ) ; CopyJob test = new CopyJob ( ) ; test . setFrom ( new File [ ] { new File ( dirs . base ( ) , "" ) } ) ; test . setTo ( new File ( dirs . base ( ) , "" ) ) ; Runnable copy = ( Runnable ) Helper . copy ( test ) ; copy . run ( ) ; assertTrue ( new File ( dir , "" ) . exists ( ) ) ; } public void testCopyBuffer ( ) throws ArooaPropertyException , ArooaConversionException { OurDirs dirs = new OurDirs ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; String result = new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ; assertEquals ( "" , result . trim ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . io ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . ConverterHelper ; import org . oddjob . FragmentHelper ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . ElementMappings ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . ConversionPath ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . arooa . design . DesignElementProperty ; import org . oddjob . arooa . design . InstanceSupport ; import org . oddjob . arooa . design . model . MockDesignElementProperty ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . parsing . QTag ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . types . ListType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . state . ParentState ; public class FilesTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( FilesTypeTest . class ) ; public void testPattern ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; FilesType test = new FilesType ( ) ; test . setFiles ( dirs . base ( ) + "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; File [ ] fs = converter . convert ( test , File [ ] . class ) ; assertTrue ( fs . length > ) ; for ( int i = ; i < fs . length ; ++ i ) { System . out . println ( fs [ i ] ) ; } ConversionPath < FilesType , String [ ] > path = converter . findConversion ( FilesType . class , String [ ] . class ) ; assertEquals ( "" , path . toString ( ) ) ; String [ ] strings = converter . convert ( test , String [ ] . class ) ; assertTrue ( strings . length > ) ; } public void testNestedFileList ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; FilesType f = new FilesType ( ) ; f . setFiles ( dirs . base ( ) + "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; File [ ] fs = ( File [ ] ) converter . convert ( f , File [ ] . class ) ; assertTrue ( fs . length > ) ; for ( int i = ; i < fs . length ; ++ i ) { System . out . println ( fs [ i ] ) ; } } public void testXMLCreate ( ) throws Exception { String xml = "" ; FilesType ft = ( FilesType ) Helper . createTypeFromXml ( xml ) ; assertEquals ( "" , ft . getFiles ( ) ) ; } public void testXMLCreate2 ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; String xml = "" + "" + "" + dirs . base ( ) + "" + "" + dirs . base ( ) + "" + "" + "" ; ListType listType = ( ListType ) Helper . createTypeFromXml ( xml ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; File [ ] files = converter . convert ( listType , File [ ] . class ) ; for ( int i = ; i < files . length ; ++ i ) { logger . debug ( files [ i ] ) ; } assertEquals ( , files . length ) ; Set < File > set = new HashSet < File > ( Arrays . asList ( files ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) , "" ) ) ) ; } public void testXMLCreate3 ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; String xml = "" + dirs . base ( ) + "" ; FilesType ft = ( FilesType ) Helper . createTypeFromXml ( xml ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; File [ ] files = converter . convert ( ft , File [ ] . class ) ; assertEquals ( , files . length ) ; logger . debug ( files [ ] ) ; logger . debug ( files [ ] ) ; Set < File > set = new HashSet < File > ( Arrays . asList ( files ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) , "" ) ) ) ; } public static class MyFiles extends SimpleJob { File [ ] files ; public void setFiles ( File [ ] files ) { if ( files == null ) { this . files = null ; } else { this . files = Files . expand ( files ) ; } } public int execute ( ) { return ; } } public void testInOddjob ( ) { OurDirs dirs = new OurDirs ( ) ; String xml = "" + "" + "" + MyFiles . class . getName ( ) + "" + "" + "" + dirs . base ( ) + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; MyFiles mine = ( MyFiles ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertTrue ( mine . files . length > ) ; oj . destroy ( ) ; } public void testInOddjob2 ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; String xml = "" + "" + "" + "" + "" + "" + "" + dirs . base ( ) + "" + "" + dirs . base ( ) + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oj ) ; File [ ] files = lookup . lookup ( "" , File [ ] . class ) ; assertEquals ( , files . length ) ; oj . destroy ( ) ; } public void testSupports ( ) throws ArooaParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; ElementMappings mappings = session . getArooaDescriptor ( ) . getElementMappings ( ) ; assertTrue ( checkElements ( mappings . elementsFor ( new InstantiationContext ( ArooaType . VALUE , new SimpleArooaClass ( Object . class ) , converter ) ) ) ) ; assertTrue ( checkElements ( mappings . elementsFor ( new InstantiationContext ( ArooaType . VALUE , new SimpleArooaClass ( ArooaValue . class ) , converter ) ) ) ) ; assertTrue ( checkElements ( mappings . elementsFor ( new InstantiationContext ( ArooaType . VALUE , new SimpleArooaClass ( File . class ) , converter ) ) ) ) ; assertTrue ( checkElements ( mappings . elementsFor ( new InstantiationContext ( ArooaType . VALUE , new SimpleArooaClass ( File [ ] . class ) , converter ) ) ) ) ; } public void testSupports2 ( ) throws ArooaParseException { final ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; final ArooaContext context = new MockArooaContext ( ) { @ Override public ArooaSession getSession ( ) { return session ; } @ Override public ArooaType getArooaType ( ) { return ArooaType . VALUE ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public ArooaClass getClassIdentifier ( ) { return new SimpleArooaClass ( File [ ] . class ) ; } } ; } } ; DesignElementProperty property = new MockDesignElementProperty ( ) { @ Override public ArooaContext getArooaContext ( ) { return context ; } } ; InstanceSupport support = new InstanceSupport ( property ) ; QTag tags [ ] = support . getTags ( ) ; Set < QTag > results = new HashSet < QTag > ( Arrays . asList ( tags ) ) ; assertTrue ( results . contains ( new QTag ( "" ) ) ) ; } private boolean checkElements ( ArooaElement elements [ ] ) { return new HashSet < ArooaElement > ( Arrays . asList ( elements ) ) . contains ( new ArooaElement ( "" ) ) ; } public void testFileListToString ( ) throws NoConversionAvailableException , ConversionFailedException , ArooaParseException { OurDirs dirs = new OurDirs ( ) ; FilesType files1 = new FilesType ( ) ; files1 . setFiles ( dirs . base ( ) + "" ) ; FilesType files2 = new FilesType ( ) ; files2 . setFiles ( dirs . base ( ) + "" ) ; ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; File [ ] set1 = converter . convert ( files1 , File [ ] . class ) ; File [ ] set2 = converter . convert ( files2 , File [ ] . class ) ; FilesType list = new FilesType ( ) ; list . setList ( , set1 ) ; list . setList ( , set2 ) ; String result = converter . convert ( list , String . class ) ; assertEquals ( new File ( dirs . base ( ) , "" ) . getPath ( ) + File . pathSeparator + new File ( dirs . base ( ) , "" ) . getPath ( ) + File . pathSeparator + new File ( dirs . base ( ) , "" ) . getPath ( ) , result ) ; } public void testMixedTypesExample ( ) throws IOException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { "" , "" } ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( new File ( "" ) . getCanonicalPath ( ) , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob . destroy ( ) ; } public void testSimpleExamples ( ) throws ArooaParseException { FragmentHelper helper = new FragmentHelper ( ) ; helper . createValueFromResource ( "" ) ; helper . createValueFromResource ( "" ) ; helper . createValueFromResource ( "" ) ; } } package org . oddjob . io ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . io . PrintStream ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . ConverterHelper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . Resetable ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class BufferTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( BufferTypeTest . class ) ; public void testConversions ( ) throws NoConversionAvailableException , ConversionFailedException , IOException { ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; BufferType test = new BufferType ( ) ; test . setText ( "" ) ; test . configured ( ) ; String string = converter . convert ( test , String . class ) ; assertEquals ( "" , string ) ; } public void testOutputInputStream ( ) throws Exception { BufferType bt = new BufferType ( ) ; bt . configured ( ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; OutputStream os = converter . convert ( bt , OutputStream . class ) ; os . write ( '' ) ; os . close ( ) ; assertEquals ( "" , converter . convert ( bt , String . class ) ) ; InputStream is = converter . convert ( bt , InputStream . class ) ; int i = is . read ( ) ; assertEquals ( , i ) ; is . close ( ) ; } public void testAppend ( ) throws Exception { BufferType bt = new BufferType ( ) ; bt . configured ( ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; OutputStream os = converter . convert ( bt , OutputStream . class ) ; PrintStream out = new PrintStream ( os ) ; out . print ( "" ) ; out . close ( ) ; os = converter . convert ( bt , OutputStream . class ) ; out = new PrintStream ( os ) ; out . print ( "" ) ; out . close ( ) ; String result = converter . convert ( bt , String . class ) ; assertEquals ( "" , result ) ; } public void testBufferAppendExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Object jobs = new OddjobLookup ( oddjob ) . lookup ( "" ) ; ( ( Resetable ) jobs ) . hardReset ( ) ; ( ( Runnable ) jobs ) . run ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob . destroy ( ) ; } public void testFileWritingAndCaptureExamples ( ) { OurDirs dirs = new OurDirs ( ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oddjob1 . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob1 . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; oddjob1 . destroy ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oddjob2 . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob2 . run ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob2 . destroy ( ) ; } public void testByIdInOddjob ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String result = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , result ) ; oj . destroy ( ) ; } public void testTextToOutputStreamInOddjob ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String result = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , result ) ; oj . destroy ( ) ; } public void testToStringArray ( ) throws IOException { BufferType test = new BufferType ( ) ; test . setText ( String . format ( "" ) ) ; test . configured ( ) ; String [ ] result = test . getLines ( ) ; assertEquals ( "" , result [ ] ) ; assertEquals ( "" , result [ ] ) ; } public void testBufferAsLinesExample ( ) throws ArooaPropertyException , ArooaConversionException { OurDirs dirs = new OurDirs ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oj . run ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oj . destroy ( ) ; } public void testLinesInOddjob ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String result = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( String . format ( "" ) , result ) ; } public void testCapturingXML ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String result = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( String . format ( "" ) , result ) ; } } package org . oddjob . io ; import java . io . File ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class RenameJobTest extends TestCase { File dir ; public void setUp ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; dir = dirs . relative ( "" ) ; if ( dir . exists ( ) ) { FileUtils . forceDelete ( dir ) ; } FileUtils . forceMkdir ( dir ) ; } public void testSimple ( ) throws Exception { File a = new File ( dir , "" ) ; File b = new File ( dir , "" ) ; FileUtils . touch ( a ) ; assertFalse ( b . exists ( ) ) ; assertTrue ( a . exists ( ) ) ; RenameJob test = new RenameJob ( ) ; test . setFrom ( a ) ; test . setTo ( b ) ; test . run ( ) ; assertTrue ( b . exists ( ) ) ; assertFalse ( a . exists ( ) ) ; } public void testDir ( ) throws Exception { File a = new File ( dir , "" ) ; File b = new File ( dir , "" ) ; FileUtils . forceMkdir ( a ) ; RenameJob test = new RenameJob ( ) ; test . setFrom ( a ) ; test . setTo ( b ) ; test . run ( ) ; assertTrue ( b . exists ( ) ) ; assertFalse ( a . exists ( ) ) ; } public void testExample ( ) throws Exception { File a = new File ( dir , "" ) ; File b = new File ( dir , "" ) ; FileUtils . touch ( a ) ; Properties properties = new Properties ( ) ; properties . setProperty ( "" , dir . getPath ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setProperties ( properties ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Runnable rename1 = lookup . lookup ( "" , Runnable . class ) ; rename1 . run ( ) ; assertFalse ( a . exists ( ) ) ; assertTrue ( b . exists ( ) ) ; Runnable rename2 = lookup . lookup ( "" , Runnable . class ) ; rename2 . run ( ) ; oddjob . destroy ( ) ; assertTrue ( a . exists ( ) ) ; assertFalse ( b . exists ( ) ) ; } public void testSerialize ( ) throws Exception { File a = new File ( dir , "" ) ; File b = new File ( dir , "" ) ; FileUtils . touch ( a ) ; assertFalse ( b . exists ( ) ) ; assertTrue ( a . exists ( ) ) ; RenameJob test = new RenameJob ( ) ; test . setFrom ( a ) ; test . setTo ( b ) ; Runnable copy = ( Runnable ) Helper . copy ( test ) ; copy . run ( ) ; assertTrue ( b . exists ( ) ) ; assertFalse ( a . exists ( ) ) ; } } package org . oddjob . io ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FragmentHelper ; import org . oddjob . Oddjob ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . xml . XMLConfiguration ; public class StderrTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( StderrTypeTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; } String EOL = System . getProperty ( "" ) ; public void testStderrInOddjob ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + EOL + "" + "" + "" + "" + "" + "" + "" + "" + "" + EOL + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; ConsoleCapture results = new ConsoleCapture ( ) ; results . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; results . close ( ) ; oddjob . destroy ( ) ; results . dump ( logger ) ; String [ ] lines = results . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; } public void testExample ( ) throws ArooaParseException { FragmentHelper helper = new FragmentHelper ( ) ; Runnable copy = ( Runnable ) helper . createComponentFromResource ( "" ) ; ConsoleCapture results = new ConsoleCapture ( ) ; results . capture ( Oddjob . CONSOLE ) ; copy . run ( ) ; results . close ( ) ; String [ ] lines = results . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; } } package org . oddjob . io ; import java . io . File ; import java . io . IOException ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . StateSteps ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . structural . SequentialJob ; import org . oddjob . state . ParentState ; public class ExistsJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( ExistsJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testFile ( ) { OurDirs dirs = new OurDirs ( ) ; ExistsJob test = new ExistsJob ( ) ; test . setFile ( new File ( dirs . base ( ) , "" ) ) ; assertEquals ( - , test . getSize ( ) ) ; assertNull ( test . getLastModified ( ) ) ; assertEquals ( - , test . getResult ( ) ) ; test . run ( ) ; assertTrue ( test . getSize ( ) > ) ; assertNotNull ( test . getLastModified ( ) ) ; assertEquals ( , test . getResult ( ) ) ; } public void testWild ( ) { OurDirs dirs = new OurDirs ( ) ; ExistsJob test = new ExistsJob ( ) ; test . setFile ( new File ( dirs . base ( ) , "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; assertEquals ( , test . getExists ( ) . length ) ; assertEquals ( - , test . getSize ( ) ) ; assertNull ( test . getLastModified ( ) ) ; } public void testInOddjob ( ) { OurDirs dirs = new OurDirs ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testInOddjob2 ( ) { String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . INCOMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testExistsResultsExample ( ) { String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . INCOMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testExistsWithFilesExample ( ) { OurDirs dirs = new OurDirs ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; console . close ( ) ; console . dump ( logger ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , console . getLines ( ) . length ) ; oddjob . destroy ( ) ; } public void testExistsFilePollingExample ( ) throws IOException , ArooaPropertyException , ArooaConversionException , InterruptedException { OurDirs dirs = new OurDirs ( ) ; File workDir = dirs . relative ( "" ) ; workDir . mkdir ( ) ; File flagFile = new File ( workDir , "" ) ; if ( flagFile . exists ( ) ) { FileUtils . forceDelete ( flagFile ) ; } Properties properties = new Properties ( ) ; properties . setProperty ( "" , workDir . getPath ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setProperties ( properties ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . load ( ) ; SequentialJob sequential = new OddjobLookup ( oddjob ) . lookup ( "" , SequentialJob . class ) ; StateSteps sequentialStates = new StateSteps ( sequential ) ; sequentialStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . INCOMPLETE ) ; oddjob . run ( ) ; sequentialStates . checkWait ( ) ; StateSteps oddjobStates = new StateSteps ( oddjob ) ; oddjobStates . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; FileUtils . touch ( flagFile ) ; oddjobStates . checkWait ( ) ; console . close ( ) ; console . dump ( logger ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , console . getLines ( ) . length ) ; oddjob . destroy ( ) ; } public void testSerialize ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; ExistsJob test = new ExistsJob ( ) ; test . setFile ( new File ( dirs . base ( ) , "" ) ) ; ExistsJob copy = ( ExistsJob ) Helper . copy ( test ) ; copy . run ( ) ; assertEquals ( , copy . getResult ( ) ) ; } } package org . oddjob . io ; import java . io . BufferedReader ; import java . io . InputStream ; import java . io . InputStreamReader ; import junit . framework . TestCase ; import org . oddjob . ConverterHelper ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . deploy . ClassesOnlyDescriptor ; public class ResourceTypeTest extends TestCase { public void test1 ( ) throws Exception { ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; ResourceType test = new ResourceType ( ) ; test . setResource ( "" ) ; test . setArooaSession ( new MockArooaSession ( ) { @ Override public ArooaDescriptor getArooaDescriptor ( ) { return new ClassesOnlyDescriptor ( getClass ( ) . getClassLoader ( ) ) ; } } ) ; InputStream in = converter . convert ( test , InputStream . class ) ; assertNotNull ( in ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; String line = reader . readLine ( ) ; assertEquals ( "" , line ) ; reader . close ( ) ; } } package org . oddjob . tools ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import javax . tools . Diagnostic ; import javax . tools . DiagnosticCollector ; import javax . tools . JavaCompiler ; import javax . tools . JavaFileObject ; import javax . tools . StandardJavaFileManager ; import javax . tools . ToolProvider ; import javax . tools . JavaCompiler . CompilationTask ; public class CompileJob implements Runnable { private File dest ; private File [ ] files ; private int result ; @ Override public void run ( ) { if ( files == null ) { throw new IllegalStateException ( "" ) ; } List < String > options = new ArrayList < String > ( ) ; if ( dest != null ) { options . add ( "" ) ; options . add ( dest . getPath ( ) ) ; } JavaCompiler compiler = ToolProvider . getSystemJavaCompiler ( ) ; if ( compiler == null ) { throw new IllegalStateException ( "" ) ; } StandardJavaFileManager fileManager = compiler . getStandardFileManager ( null , null , null ) ; Iterable < ? extends JavaFileObject > compilationUnits = fileManager . getJavaFileObjects ( files ) ; DiagnosticCollector < JavaFileObject > diagnostics = new DiagnosticCollector < JavaFileObject > ( ) ; CompilationTask task = compiler . getTask ( null , fileManager , diagnostics , options , null , compilationUnits ) ; if ( task . call ( ) ) { result = ; } else { result = ; } for ( Diagnostic < ? > diagnostic : diagnostics . getDiagnostics ( ) ) { System . out . format ( "" , diagnostic . getLineNumber ( ) , diagnostic . getSource ( ) ) ; } try { fileManager . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } public File getDest ( ) { return dest ; } public void setDest ( File dest ) { this . dest = dest ; } public File [ ] getFiles ( ) { return files ; } public void setFiles ( File [ ] files ) { this . files = files ; } public int getResult ( ) { return result ; } } package org . oddjob . tools ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . custommonkey . xmlunit . XMLTestCase ; import org . oddjob . OurDirs ; import org . oddjob . io . BufferType ; import org . oddjob . util . IO ; import org . xml . sax . SAXException ; public class DocPostProcessorTest extends XMLTestCase { String EOL = System . getProperty ( "" ) ; public void testJavaFilePattern ( ) { Pattern test = new DocPostProcessor ( ) . new JavaCodeInjector ( ) . pattern ; Matcher matcher = test . matcher ( "" + "" ) ; assertTrue ( matcher . find ( ) ) ; assertEquals ( "" , matcher . group ( ) ) ; } public void testxMLResourcePattern ( ) { Pattern test = new DocPostProcessor . XMLResourceInjector ( ) . pattern ; Matcher matcher = test . matcher ( "" + "" ) ; assertTrue ( matcher . find ( ) ) ; assertEquals ( "" , matcher . group ( ) ) ; } public void testInsertFile ( ) throws SAXException , IOException { OurDirs dirs = new OurDirs ( ) ; DocPostProcessor test = new DocPostProcessor ( ) ; test . setBaseDir ( dirs . base ( ) ) ; String input = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; test . setInput ( new ByteArrayInputStream ( input . getBytes ( ) ) ) ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; test . setOutput ( output ) ; test . run ( ) ; BufferType buffer = new BufferType ( ) ; buffer . configured ( ) ; InputStream expected = new FileInputStream ( dirs . relative ( "" ) ) ; assertNotNull ( expected ) ; IO . copy ( expected , buffer . toOutputStream ( ) ) ; String result = new String ( output . toByteArray ( ) ) ; System . out . println ( result ) ; assertXMLEqual ( buffer . getText ( ) , result ) ; } } package org . oddjob . tools ; public class SomeJavaCode { } package org . oddjob . tools . doclet . utils ; import junit . framework . TestCase ; import org . mockito . Mockito ; import org . oddjob . Helper ; import com . sun . javadoc . ClassDoc ; import com . sun . javadoc . PackageDoc ; import com . sun . javadoc . Tag ; public class XMLResourceTagProcessorTest extends TestCase { public void testProcessTag ( ) { PackageDoc packageDoc = Mockito . mock ( PackageDoc . class ) ; Mockito . when ( packageDoc . name ( ) ) . thenReturn ( "" ) ; ClassDoc classDoc = Mockito . mock ( ClassDoc . class ) ; Mockito . when ( classDoc . containingPackage ( ) ) . thenReturn ( packageDoc ) ; ClassDoc referencedClassDock = Mockito . mock ( ClassDoc . class ) ; Mockito . when ( referencedClassDock . name ( ) ) . thenReturn ( "" ) ; Tag tag = Mockito . mock ( Tag . class ) ; Mockito . when ( tag . text ( ) ) . thenReturn ( "" ) ; Mockito . when ( tag . name ( ) ) . thenReturn ( "" ) ; XMLResourceTagProcessor test = new XMLResourceTagProcessor ( ) ; String result = test . process ( tag ) ; assertEquals ( "" + Helper . LS + "" + Helper . LS , result ) ; } } package org . oddjob . tools . doclet . utils ; import junit . framework . TestCase ; import org . mockito . Mockito ; import com . sun . javadoc . ClassDoc ; import com . sun . javadoc . PackageDoc ; import com . sun . javadoc . SeeTag ; public class SeeTagProcessorTest extends TestCase { public void testProcessSeeTag ( ) { PackageDoc packageDoc = Mockito . mock ( PackageDoc . class ) ; Mockito . when ( packageDoc . name ( ) ) . thenReturn ( "" ) ; ClassDoc classDoc = Mockito . mock ( ClassDoc . class ) ; Mockito . when ( classDoc . containingPackage ( ) ) . thenReturn ( packageDoc ) ; ClassDoc referencedClassDock = Mockito . mock ( ClassDoc . class ) ; Mockito . when ( referencedClassDock . name ( ) ) . thenReturn ( "" ) ; SeeTag seeTag = Mockito . mock ( SeeTag . class ) ; Mockito . when ( seeTag . holder ( ) ) . thenReturn ( classDoc ) ; Mockito . when ( seeTag . referencedClassName ( ) ) . thenReturn ( "" ) ; Mockito . when ( seeTag . referencedClass ( ) ) . thenReturn ( referencedClassDock ) ; SeeTagProcessor test = new SeeTagProcessor ( ) ; String result = test . process ( seeTag ) ; assertEquals ( "" + "" + "" , result ) ; } } package org . oddjob . tools . taglet ; import java . io . File ; import java . io . IOException ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . OurDirs ; public class TagletsTest extends TestCase { private static final Logger logger = Logger . getLogger ( TagletsTest . class ) ; OurDirs dirs = new OurDirs ( ) ; File dest = new File ( dirs . base ( ) , "" ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; for ( int i = ; ; ++ i ) { if ( dest . exists ( ) ) { logger . info ( "" + dest ) ; try { FileUtils . forceDelete ( dest ) ; } catch ( IOException e ) { if ( i < ) { logger . error ( "" + dest , e ) ; Thread . sleep ( ) ; continue ; } else { throw e ; } } } break ; } logger . info ( "" + dest ) ; if ( ! dest . mkdir ( ) ) { throw new RuntimeException ( "" + dest ) ; } } public void testOne ( ) { File index = new File ( dest , "" ) ; File oddjob = new File ( dest , "" ) ; int result = com . sun . tools . javadoc . Main . execute ( new String [ ] { "" , dirs . base ( ) + "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , dest . toString ( ) , "" } ) ; assertEquals ( , result ) ; assertTrue ( index . exists ( ) ) ; assertTrue ( oddjob . exists ( ) ) ; } } package org . oddjob . tools . includes ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; public class SnippetFilterTest extends TestCase { public void testFilter ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; File file = new File ( dirs . base ( ) , "" ) ; InputStream input = new FileInputStream ( file ) ; SnippetFilter test = new SnippetFilter ( "" ) ; String result = test . load ( input ) ; assertEquals ( "" , result . trim ( ) ) ; } } package org . oddjob . tools . includes ; import junit . framework . TestCase ; public class FilterFactoryTest extends TestCase { public void testForSnippet ( ) { FilterFactory test = new FilterFactory ( "" ) ; assertEquals ( "" , test . getResourcePath ( ) ) ; assertEquals ( SnippetFilter . class , test . getTextLoader ( ) . getClass ( ) ) ; } public void testForNoneSnippet ( ) { FilterFactory test = new FilterFactory ( "" ) ; assertEquals ( "" , test . getResourcePath ( ) ) ; assertEquals ( PlainStreamToText . class , test . getTextLoader ( ) . getClass ( ) ) ; } } package org . oddjob ; import java . io . File ; import java . io . IOException ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . Enumeration ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . beanutils . BeanUtilsPropertyAccessor ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . reflect . ArooaNoPropertyException ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . types . XMLConfigurationType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . oddballs . BuildOddballs ; import org . oddjob . state . ParentState ; public class OddjobModulesTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddjobModulesTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; new BuildOddballs ( ) . run ( ) ; } public void testClassLoaderAssumptions ( ) throws MalformedURLException , ClassNotFoundException , ArooaNoPropertyException { OurDirs dirs = new OurDirs ( ) ; File file = new File ( dirs . base ( ) , "" ) ; URL [ ] urls = { file . toURI ( ) . toURL ( ) } ; URLClassLoader test = new URLClassLoader ( urls ) ; BeanUtilsPropertyAccessor propertyAccessor = new BeanUtilsPropertyAccessor ( ) ; Class < ? > appleClass = Class . forName ( "" , true , test ) ; BeanOverview overview = new SimpleArooaClass ( appleClass ) . getBeanOverview ( propertyAccessor ) ; Class < ? > colourType = overview . getPropertyType ( "" ) ; assertEquals ( "" , colourType . getName ( ) ) ; } public void testClassLoaderAssumptions2 ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; File file = new File ( dirs . base ( ) , "" ) ; URL [ ] urls = { file . toURI ( ) . toURL ( ) } ; URLClassLoader test = new URLClassLoader ( urls ) ; Enumeration < URL > allResourses = test . getResources ( "" ) ; Enumeration < URL > parentResourses = test . getParent ( ) . getResources ( "" ) ; Set < URL > results = toSet ( allResourses ) ; results . removeAll ( toSet ( parentResourses ) ) ; assertEquals ( , results . size ( ) ) ; assertTrue ( results . contains ( new File ( dirs . base ( ) , "" ) . getAbsoluteFile ( ) . toURI ( ) . toURL ( ) ) ) ; } private < T > Set < T > toSet ( Enumeration < T > enumeration ) { Set < T > set = new HashSet < T > ( ) ; while ( enumeration . hasMoreElements ( ) ) { T next = enumeration . nextElement ( ) ; set . add ( next ) ; } return set ; } public void testOneModule ( ) { OurDirs dirs = new OurDirs ( ) ; String inner = "" + "" + "" + "" + "" + "" + "" + "" + "" ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + dirs . base ( ) + "" + "" + "" + "" + "" + "" + dirs . base ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; XMLConfigurationType configType = new XMLConfigurationType ( ) ; configType . setXml ( inner ) ; oddjob . setExport ( "" , configType ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob ; import org . oddjob . input . InputHandler ; public class MockOddjobServices implements OddjobServices { public Object getService ( String serviceName ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public String serviceNameFor ( Class < ? > theClass , String flavour ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public ClassLoader getClassLoader ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public OddjobExecutors getOddjobExecutors ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public InputHandler getInputHandler ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . doclet ; import junit . framework . TestCase ; public class ManualWriterTest extends TestCase { public void testIndexFileWithPackage ( ) { String result = ManualWriter . getIndexFile ( "" ) ; assertEquals ( "" , result ) ; } public void testIndexFileWithSmallNames ( ) { String result = ManualWriter . getIndexFile ( "" ) ; assertEquals ( "" , result ) ; } public void testIndexFileNoPackage ( ) { String result = ManualWriter . getIndexFile ( "" ) ; assertEquals ( "" , result ) ; } public void testIndexFileNoClass ( ) { String result = ManualWriter . getIndexFile ( "" ) ; assertEquals ( "" , result ) ; } } package org . oddjob . doclet ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; import org . oddjob . arooa . convert . convertlets . FileConvertlets ; import org . oddjob . oddballs . BuildOddballs ; public class ManualDocletBasicTest extends TestCase { OurDirs dirs = new OurDirs ( ) ; public void testJobsAndTypes ( ) { new BuildOddballs ( ) . run ( ) ; String descriptorPath = new FileConvertlets ( ) . filesToPath ( new File [ ] { dirs . relative ( "" ) , dirs . relative ( "" ) } ) ; ManualDoclet test = new ManualDoclet ( descriptorPath , null ) ; JobsAndTypes jats = test . jobsAndTypes ( ) ; List < String > types = new ArrayList < String > ( ) ; for ( String type : jats . types ( ) ) { types . add ( type ) ; } assertEquals ( , types . size ( ) ) ; assertTrue ( types . contains ( "" ) ) ; assertTrue ( types . contains ( "" ) ) ; List < String > jobs = new ArrayList < String > ( ) ; for ( String type : jats . jobs ( ) ) { jobs . add ( type ) ; } assertEquals ( , jobs . size ( ) ) ; assertTrue ( jobs . contains ( "" ) ) ; assertTrue ( jobs . contains ( "" ) ) ; } } package org . oddjob . doclet ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . beandocs . BeanDoc ; import org . oddjob . arooa . beandocs . SessionArooaDocFactory ; import org . oddjob . arooa . beandocs . WriteableArooaDoc ; import org . oddjob . arooa . beandocs . WriteableBeanDoc ; import org . oddjob . arooa . standard . StandardArooaSession ; public class JobsAndTypesTest extends TestCase { public void testTypes ( ) { StandardArooaSession session = new StandardArooaSession ( ) ; SessionArooaDocFactory factory = new SessionArooaDocFactory ( session ) ; WriteableArooaDoc jobs = factory . createBeanDocs ( ArooaType . COMPONENT ) ; WriteableArooaDoc types = factory . createBeanDocs ( ArooaType . VALUE ) ; JobsAndTypes test = new JobsAndTypes ( jobs , types ) ; assertNotNull ( test . docFor ( "" ) ) ; } public void testDuplicateType ( ) { StandardArooaSession session = new StandardArooaSession ( ) ; SessionArooaDocFactory factory = new SessionArooaDocFactory ( session ) ; WriteableArooaDoc jobs = factory . createBeanDocs ( ArooaType . COMPONENT ) ; WriteableArooaDoc types = factory . createBeanDocs ( ArooaType . VALUE ) ; JobsAndTypes test = new JobsAndTypes ( jobs , types ) ; WriteableBeanDoc instance = test . docFor ( "" ) ; BeanDoc jobDoc = test . docForJob ( "" ) ; BeanDoc typeDoc = test . docForType ( "" ) ; assertSame ( instance , jobDoc ) ; assertSame ( instance , typeDoc ) ; } } package org . oddjob . doclet ; import java . io . File ; import java . io . IOException ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . OurDirs ; import org . oddjob . arooa . convert . convertlets . FileConvertlets ; import org . oddjob . doclet . ManualDoclet ; import org . oddjob . oddballs . BuildOddballs ; import junit . framework . TestCase ; public class ManualDocletTest extends TestCase { private static final Logger logger = Logger . getLogger ( ManualDocletTest . class ) ; OurDirs dirs = new OurDirs ( ) ; File dest = new File ( dirs . base ( ) , "" ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; for ( int i = ; ; ++ i ) { if ( dest . exists ( ) ) { logger . info ( "" + dest ) ; try { FileUtils . forceDelete ( dest ) ; } catch ( IOException e ) { if ( i < ) { logger . error ( "" + dest , e ) ; Thread . sleep ( ) ; continue ; } else { throw e ; } } } break ; } logger . info ( "" + dest ) ; if ( ! dest . mkdir ( ) ) { throw new RuntimeException ( "" + dest ) ; } } public void testStart ( ) { File index = new File ( dest , "" ) ; File oddjob = new File ( dest , "" ) ; int result = com . sun . tools . javadoc . Main . execute ( new String [ ] { "" , ManualDoclet . class . getName ( ) , "" , dirs . base ( ) + "" , "" , dest . toString ( ) , "" , "" } ) ; assertEquals ( , result ) ; assertTrue ( index . exists ( ) ) ; assertTrue ( oddjob . exists ( ) ) ; } public void testIstType ( ) { File src = new File ( dirs . base ( ) , "" ) ; if ( ! src . exists ( ) ) { return ; } File index = new File ( dest , "" ) ; File is = new File ( dest , "" ) ; int result = com . sun . tools . javadoc . Main . execute ( new String [ ] { "" , ManualDoclet . class . getName ( ) , "" , dirs . base ( ) + "" , "" , dest . toString ( ) , "" } ) ; assertEquals ( , result ) ; assertTrue ( index . exists ( ) ) ; assertTrue ( is . exists ( ) ) ; } public void testDescriptorPath ( ) { OurDirs dirs = new OurDirs ( ) ; File src = new File ( dirs . base ( ) , "" ) ; if ( ! src . exists ( ) ) { return ; } new BuildOddballs ( ) . run ( ) ; File index = new File ( dest , "" ) ; File apple = new File ( dest , "" ) ; File is = new File ( dest , "" ) ; String sourcePath = new FileConvertlets ( ) . filesToPath ( new File [ ] { dirs . relative ( "" ) , dirs . relative ( "" ) } ) ; String descriptorPath = new FileConvertlets ( ) . filesToPath ( new File [ ] { dirs . relative ( "" ) , dirs . relative ( "" ) } ) ; int result = com . sun . tools . javadoc . Main . execute ( new String [ ] { "" , ManualDoclet . class . getName ( ) , "" , sourcePath , "" , dest . toString ( ) , "" , descriptorPath , "" } ) ; assertEquals ( , result ) ; assertTrue ( index . exists ( ) ) ; assertTrue ( apple . exists ( ) ) ; assertFalse ( is . exists ( ) ) ; } } package org . oddjob ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . deploy . NullArooaDescriptor ; import org . oddjob . arooa . deploy . annotations . ArooaElement ; import org . oddjob . arooa . life . ArooaContextAware ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . runtime . RuntimeEvent ; import org . oddjob . arooa . runtime . RuntimeListener ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . ValueFactory ; import org . oddjob . arooa . xml . XMLConfiguration ; public class OddjobLifecycleTest extends TestCase { public static class MyValue implements ValueFactory < String > { private int count = ; @ Override public String toValue ( ) throws ArooaConversionException { ++ count ; return "" + count ; } } public static class MyJob implements Runnable , ArooaContextAware { private List < String > events = new ArrayList < String > ( ) ; @ Override public void setArooaContext ( ArooaContext context ) { events . add ( "" ) ; context . getRuntime ( ) . addRuntimeListener ( new RuntimeListener ( ) { @ Override public void beforeInit ( RuntimeEvent event ) throws ArooaConfigurationException { events . add ( "" ) ; } @ Override public void beforeDestroy ( RuntimeEvent event ) throws ArooaConfigurationException { events . add ( "" ) ; } @ Override public void beforeConfigure ( RuntimeEvent event ) throws ArooaConfigurationException { events . add ( "" ) ; } @ Override public void afterInit ( RuntimeEvent event ) throws ArooaConfigurationException { events . add ( "" ) ; } @ Override public void afterDestroy ( RuntimeEvent event ) throws ArooaConfigurationException { events . add ( "" ) ; } @ Override public void afterConfigure ( RuntimeEvent event ) throws ArooaConfigurationException { events . add ( "" ) ; } } ) ; } private String value ; @ Override public void run ( ) { events . add ( "" ) ; } public String getValue ( ) { return value ; } @ ArooaElement public void setValue ( String value ) { events . add ( "" + value ) ; this . value = value ; } public List < String > getEvents ( ) { return events ; } } public void testOddjobConfiguresThingsOnce ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + MyJob . class . getName ( ) + "" + "" + "" + MyValue . class . getName ( ) + "" + "" + "" + "" + "" ; StandardArooaSession parentSession = new StandardArooaSession ( new NullArooaDescriptor ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setArooaSession ( parentSession ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( "" , lookup . lookup ( "" ) ) ; List < ? > list = lookup . lookup ( "" , List . class ) ; oddjob . destroy ( ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( "" , list . get ( ) ) ; assertEquals ( , list . size ( ) ) ; } } package org . oddjob ; import java . util . ArrayList ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . logging . LogArchive ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class ConsoleCapture { private int dumped ; private int logged ; class Console implements LogListener { List < String > lines = new ArrayList < String > ( ) ; public synchronized void logEvent ( LogEvent logEvent ) { lines . add ( logEvent . getMessage ( ) ) ; } } private final Console console = new Console ( ) ; private LogArchive archive ; public void capture ( LogArchive archive ) { if ( this . archive != null ) { throw new IllegalStateException ( "" + archive ) ; } this . archive = archive ; archive . addListener ( console , LogLevel . INFO , - , ) ; } public void close ( ) { if ( archive != null ) { archive . removeListener ( console ) ; } archive = null ; } public String [ ] getLines ( ) { return console . lines . toArray ( new String [ console . lines . size ( ) ] ) ; } public String getAll ( ) { StringBuilder builder = new StringBuilder ( ) ; for ( String line : console . lines ) { builder . append ( line ) ; } return builder . toString ( ) ; } public int size ( ) { return console . lines . size ( ) ; } public void dump ( ) { System . out . println ( "" ) ; for ( ; dumped < console . lines . size ( ) ; ++ dumped ) { System . out . print ( console . lines . get ( dumped ) ) ; } System . out . println ( "" ) ; } public void dump ( Logger logger ) { logger . info ( "" ) ; for ( ; logged < console . lines . size ( ) ; ++ logged ) { logger . info ( console . lines . get ( logged ) . replaceFirst ( "" , "" ) ) ; } logger . info ( "" ) ; } } package org . oddjob ; import java . io . IOException ; import java . util . concurrent . atomic . AtomicReference ; import org . apache . log4j . Logger ; import org . custommonkey . xmlunit . XMLTestCase ; import org . custommonkey . xmlunit . XMLUnit ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . MockConfigurationHandle ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . runtime . ConfigurationNode ; import org . oddjob . arooa . runtime . ConfigurationNodeListener ; import org . oddjob . arooa . runtime . MockConfigurationNode ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . EchoJob ; import org . xml . sax . SAXException ; public class OddjobConfigurationTest extends XMLTestCase { private static final Logger logger = Logger . getLogger ( OddjobConfigurationTest . class ) ; public void testCopy ( ) throws SAXException , IOException { XMLUnit . setIgnoreWhitespace ( true ) ; String xml = "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; DragPoint dragPoint = oddjob . provideConfigurationSession ( ) . dragPointFor ( oddjob ) ; String result = dragPoint . copy ( ) ; logger . debug ( "" + result ) ; assertXMLEqual ( xml , result ) ; } public void testPaste ( ) throws SAXException , IOException , ArooaParseException { XMLUnit . setIgnoreWhitespace ( true ) ; String xml = "" ; XMLConfiguration config = new XMLConfiguration ( "" , xml ) ; final AtomicReference < String > savedXML = new AtomicReference < String > ( ) ; config . setSaveHandler ( new XMLConfiguration . SaveHandler ( ) { @ Override public void acceptXML ( String xml ) { savedXML . set ( xml ) ; } } ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . load ( ) ; DragPoint dragPoint = oddjob . provideConfigurationSession ( ) . dragPointFor ( oddjob ) ; String paste = "" ; DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; dragPoint . paste ( , paste ) ; trn . commit ( ) ; oddjob . provideConfigurationSession ( ) . save ( ) ; String expected = "" + "" + "" + "" + "" ; String result = savedXML . get ( ) ; logger . debug ( "" + result ) ; assertXMLEqual ( expected , result ) ; } private class OurConfig implements ArooaConfiguration { public ConfigurationHandle parse ( final ArooaContext parentContext ) throws ArooaParseException { return new MockConfigurationHandle ( ) { @ Override public ArooaContext getDocumentContext ( ) { return new MockArooaContext ( ) { @ Override public ConfigurationNode getConfigurationNode ( ) { return new MockConfigurationNode ( ) { @ Override public void addNodeListener ( ConfigurationNodeListener listener ) { } } ; } @ Override public ArooaContext getParent ( ) { return parentContext ; } } ; } } ; } } public void testConfigurationSession ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new OurConfig ( ) ) ; oddjob . load ( ) ; ArooaDescriptor descriptor = oddjob . provideConfigurationSession ( ) . getArooaDescriptor ( ) ; ArooaClass cl = descriptor . getElementMappings ( ) . mappingFor ( new ArooaElement ( "" ) , new InstantiationContext ( ArooaType . COMPONENT , null ) ) ; assertEquals ( cl , new SimpleArooaClass ( EchoJob . class ) ) ; } } package org . oddjob . arooa . types ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class IdentifiableValueTypeExampleTest extends TestCase { public void testExample ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ArooaValue result = lookup . lookup ( "" , ArooaValue . class ) ; assertEquals ( ValueType . class , result . getClass ( ) ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . arooa . types ; import java . io . IOException ; import org . custommonkey . xmlunit . XMLTestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; import org . xml . sax . SAXException ; public class XMLTypeExamplesTest extends XMLTestCase { public void testExample ( ) throws ArooaPropertyException , ArooaConversionException , SAXException , IOException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; String result = lookup . lookup ( "" , String . class ) ; assertXMLEqual ( "" , result ) ; oddjob . destroy ( ) ; } } package org . oddjob . arooa . types ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Oddjob ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ListTypeExamplesTest extends TestCase { private static final Logger logger = Logger . getLogger ( ListTypeExamplesTest . class ) ; public void testFruitExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { "" , "" } ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob . destroy ( ) ; } public void testTestConvertExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } } package org . oddjob . arooa . types ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ImportTypeExamplesTest extends TestCase { private static final Logger logger = Logger . getLogger ( ImportTypeExamplesTest . class ) ; public void testFruitExample ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; String pathA = lookup . lookup ( "" , String . class ) ; String pathB = lookup . lookup ( "" , String . class ) ; logger . info ( pathA ) ; logger . info ( pathB ) ; assertEquals ( pathA , pathB ) ; oddjob . destroy ( ) ; } } package org . oddjob . arooa . types ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Oddjob ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ConvertTypeExamplesTest extends TestCase { private static final Logger logger = Logger . getLogger ( ConvertTypeExamplesTest . class ) ; public void testFruitExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } } package org . oddjob . monitor . contexts ; import org . oddjob . monitor . context . AncestorSearch ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . MockExplorerContext ; import junit . framework . TestCase ; public class AncestorSearchTest extends TestCase { class Context1 extends MockExplorerContext { @ Override public Object getValue ( String key ) { assertEquals ( "" , key ) ; return "" ; } } public void testInFirstLevel ( ) { AncestorSearch test = new AncestorSearch ( new Context1 ( ) ) ; Object result = test . getValue ( "" ) ; assertEquals ( "" , result ) ; } class Context2 extends MockExplorerContext { @ Override public Object getValue ( String key ) { assertEquals ( "" , key ) ; return null ; } @ Override public ExplorerContext getParent ( ) { return new Context1 ( ) ; } } public void testInParent ( ) { AncestorSearch test = new AncestorSearch ( new Context2 ( ) ) ; Object result = test . getValue ( "" ) ; assertEquals ( "" , result ) ; } } package org . oddjob . monitor . contexts ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ExplorerContextImpl ; import org . oddjob . monitor . model . MockExplorerModel ; import org . oddjob . util . ThreadManager ; public class ContextInitializerTest extends TestCase { class OurInitialiser implements ContextInitialiser { public void initialise ( ExplorerContext context ) { if ( context . getParent ( ) == null ) { context . setValue ( "" , "" ) ; } else { context . setValue ( "" , "" ) ; } } } class OurModel extends MockExplorerModel { @ Override public Oddjob getOddjob ( ) { return new Oddjob ( ) ; } @ Override public ThreadManager getThreadManager ( ) { return null ; } @ Override public ContextInitialiser [ ] getContextInitialisers ( ) { return new ContextInitialiser [ ] { new OurInitialiser ( ) } ; } } public void testInFirstLevel ( ) { ExplorerContext context = new ExplorerContextImpl ( new OurModel ( ) ) ; assertEquals ( "" , context . getValue ( "" ) ) ; } public void testSecondLevel ( ) { ExplorerContext context = new ExplorerContextImpl ( new OurModel ( ) ) ; ExplorerContext next = context . addChild ( new Object ( ) ) ; assertEquals ( "" , next . getValue ( "" ) ) ; } } package org . oddjob . monitor . model ; import org . oddjob . Oddjob ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . monitor . actions . ExplorerAction ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . util . ThreadManager ; public class MockExplorerModel implements ExplorerModel { public void destroy ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ConsoleArchiver getConsoleArchiver ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public LogArchiver getLogArchiver ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public String getLogFormat ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Oddjob getOddjob ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ThreadManager getThreadManager ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ContextInitialiser [ ] getContextInitialisers ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ExplorerAction [ ] getExplorerActions ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . monitor . model ; import java . util . Observable ; import java . util . Observer ; import junit . framework . TestCase ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; public class LogModelTest extends TestCase implements LogEventProcessor { String message ; public void testMessage ( ) { class MyOb implements Observer { public void update ( Observable o , Object arg ) { ( ( LogAction ) arg ) . accept ( LogModelTest . this ) ; } } MyOb ob = new MyOb ( ) ; LogModel test = new LogModel ( ) ; test . addObserver ( ob ) ; test . logEvent ( new LogEvent ( "" , , LogLevel . DEBUG , "" ) ) ; assertEquals ( "" , message ) ; } public void onClear ( ) { } public void onEvent ( String text , LogLevel level ) { message = text ; } public void onUnavailable ( ) { } } package org . oddjob . monitor . model ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import javax . swing . KeyStroke ; import org . oddjob . monitor . context . ExplorerContext ; import junit . framework . TestCase ; public class JobActionTest extends TestCase { public void testEnabledPropertyNotification ( ) { class MyAction extends JobAction { @ Override protected void doPrepare ( ExplorerContext explorerContext ) { } @ Override protected void doFree ( ExplorerContext explorerContext ) { } @ Override protected void doAction ( ) throws Exception { } public String getName ( ) { return null ; } public String getGroup ( ) { return null ; } public Integer getMnemonicKey ( ) { throw new RuntimeException ( "" ) ; } public KeyStroke getAcceleratorKey ( ) { throw new RuntimeException ( "" ) ; } } class MyPropertyListner implements PropertyChangeListener { boolean enabled ; public void propertyChange ( PropertyChangeEvent evt ) { String propertyName = evt . getPropertyName ( ) ; if ( JobAction . ENABLED_PROPERTY . equals ( propertyName ) ) { enabled = ( Boolean ) evt . getNewValue ( ) ; } } } MyPropertyListner listener = new MyPropertyListner ( ) ; MyAction test = new MyAction ( ) ; test . setEnabled ( false ) ; test . addPropertyChangeListener ( listener ) ; assertFalse ( listener . enabled ) ; test . setEnabled ( true ) ; assertTrue ( listener . enabled ) ; } } package org . oddjob . monitor . model ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . util . ThreadManager ; public class MockExplorerContext implements ExplorerContext { public ExplorerContext addChild ( Object child ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object getThisComponent ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ThreadManager getThreadManager ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ExplorerContext getParent ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object getValue ( String key ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void setValue ( String key , Object value ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . monitor . model ; import java . io . IOException ; import org . custommonkey . xmlunit . XMLTestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . util . ThreadManager ; import org . xml . sax . SAXException ; public class ConfigContextSearchTest extends XMLTestCase { class OurModel extends MockExplorerModel { Oddjob oddjob ; @ Override public Oddjob getOddjob ( ) { return oddjob ; } @ Override public ContextInitialiser [ ] getContextInitialisers ( ) { return new ContextInitialiser [ ] { new ConfigContextInialiser ( this ) } ; } @ Override public ThreadManager getThreadManager ( ) { return null ; } } public void testOddjobDragPoint ( ) throws SAXException , IOException { String xml = "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; OurModel model = new OurModel ( ) ; model . oddjob = oddjob ; ExplorerContext context = new ExplorerContextImpl ( model ) ; Object nested = new OddjobLookup ( oddjob ) . lookup ( "" ) ; ExplorerContext nestedContext = context . addChild ( nested ) ; DragPoint result = new ConfigContextSearch ( ) . dragPointFor ( nestedContext ) ; assertNotNull ( result ) ; String copy = result . copy ( ) ; assertXMLEqual ( "" , copy ) ; oddjob . destroy ( ) ; } } package org . oddjob . monitor . model ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . MockLogArchiver ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . util . ThreadManager ; public class LogContextInitialiserTest extends TestCase { class OurModel extends MockExplorerModel { LogArchiver logArchiver = new MockLogArchiver ( ) ; @ Override public Oddjob getOddjob ( ) { return new Oddjob ( ) ; } @ Override public ConsoleArchiver getConsoleArchiver ( ) { return null ; } @ Override public ThreadManager getThreadManager ( ) { return null ; } @ Override public LogArchiver getLogArchiver ( ) { return logArchiver ; } @ Override public ContextInitialiser [ ] getContextInitialisers ( ) { return new ContextInitialiser [ ] { new LogContextInialiser ( this ) } ; } } public void testNextLevelLogArchiver ( ) { OurModel model = new OurModel ( ) ; ExplorerContext context = new ExplorerContextImpl ( model ) ; ExplorerContext context2 = context . addChild ( new Object ( ) ) ; assertEquals ( model . logArchiver , context2 . getValue ( LogContextInialiser . LOG_ARCHIVER ) ) ; } public void testNextLevelIsALogArchiver ( ) { OurModel model = new OurModel ( ) ; ExplorerContext context = new ExplorerContextImpl ( model ) ; ExplorerContext context2 = context . addChild ( new MockLogArchiver ( ) ) ; assertEquals ( model . logArchiver , context2 . getValue ( LogContextInialiser . LOG_ARCHIVER ) ) ; } } package org . oddjob . monitor . model ; import java . util . concurrent . Executor ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; public class JobTreeNodeTest extends TestCase { class OurModel extends MockExplorerModel { Oddjob oddjob ; @ Override public Oddjob getOddjob ( ) { return oddjob ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) ; } @ Override public ContextInitialiser [ ] getContextInitialisers ( ) { return new ContextInitialiser [ ] ; } } class InlineExecutor implements Executor { @ Override public void execute ( Runnable command ) { command . run ( ) ; } } class OurContextFactory implements ExplorerContextFactory { @ Override public ExplorerContext createFrom ( ExplorerModel explorerModel ) { return new MockExplorerContext ( ) { @ Override public ExplorerContext addChild ( Object child ) { return this ; } } ; } } public void testChildren ( ) { String xml = "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; OurModel explorerModel = new OurModel ( ) ; explorerModel . oddjob = oddjob ; JobTreeModel treeModel = new JobTreeModel ( new InlineExecutor ( ) ) ; JobTreeNode test = new JobTreeNode ( explorerModel , treeModel , new InlineExecutor ( ) , new OurContextFactory ( ) ) ; assertEquals ( , test . getChildCount ( ) ) ; test . setVisible ( true ) ; assertEquals ( , test . getChildCount ( ) ) ; test . setVisible ( false ) ; assertEquals ( , test . getChildCount ( ) ) ; test . setVisible ( true ) ; assertEquals ( , test . getChildCount ( ) ) ; test . destroy ( ) ; } } package org . oddjob . monitor . model ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . util . ThreadManager ; public class ExplorerContextImplTest extends TestCase { class OurModel extends MockExplorerModel { @ Override public Oddjob getOddjob ( ) { return new Oddjob ( ) ; } @ Override public ThreadManager getThreadManager ( ) { return null ; } @ Override public ContextInitialiser [ ] getContextInitialisers ( ) { return new ContextInitialiser [ ] ; } } public void testChildComponent ( ) { ExplorerContext test = new ExplorerContextImpl ( new OurModel ( ) ) ; Object child = new Object ( ) ; ExplorerContext next = test . addChild ( child ) ; assertEquals ( child , next . getThisComponent ( ) ) ; } public void testComponentOwnerForNestedOddjob ( ) throws ArooaParseException { Oddjob oddjob = new Oddjob ( ) ; ExplorerModelImpl em = new ExplorerModelImpl ( new OddjobSessionFactory ( ) . createSession ( ) ) ; em . setOddjob ( oddjob ) ; ExplorerContext ec1 = new ExplorerContextImpl ( em ) ; Oddjob nestedOddjob = new Oddjob ( ) ; ExplorerContext ec2 = ec1 . addChild ( nestedOddjob ) ; assertEquals ( nestedOddjob , ec2 . getValue ( ConfigContextInialiser . CONFIG_OWNER ) ) ; } public void testComponentOwner ( ) throws ArooaParseException { Oddjob oddjob = new Oddjob ( ) ; ExplorerModelImpl em = new ExplorerModelImpl ( new OddjobSessionFactory ( ) . createSession ( ) ) ; em . setOddjob ( oddjob ) ; ExplorerContext test = new ExplorerContextImpl ( em ) ; ConfigurationOwner configOwner = ( ConfigurationOwner ) test . getValue ( ConfigContextInialiser . CONFIG_OWNER ) ; assertNull ( configOwner . provideConfigurationSession ( ) ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , "" ) ) ; oddjob . run ( ) ; assertNotNull ( configOwner . provideConfigurationSession ( ) . dragPointFor ( oddjob ) ) ; } } package org . oddjob . monitor . model ; import java . util . Observable ; import java . util . Observer ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . MockStateful ; import org . oddjob . Oddjob ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogHelper ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . cache . LocalConsoleArchiver ; import org . oddjob . state . StateListener ; public class DetailModelTest extends TestCase { private static final Logger logger = Logger . getLogger ( DetailModelTest . class ) ; class OurExplorerContext extends MockExplorerContext { ConsoleArchiver consoleArchiver ; LogArchiver logArchiver ; Object component ; @ Override public Object getThisComponent ( ) { return component ; } @ Override public Object getValue ( String key ) { if ( LogContextInialiser . LOG_ARCHIVER . equals ( key ) ) { return logArchiver ; } if ( LogContextInialiser . CONSOLE_ARCHIVER . equals ( key ) ) { return consoleArchiver ; } throw new RuntimeException ( key ) ; } } class MyLA implements LogArchiver { boolean removed ; public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int max ) { logger . debug ( "" + LogHelper . getLogger ( component ) ) ; assertEquals ( LogLevel . DEBUG , level ) ; assertEquals ( - , last ) ; assertEquals ( , max ) ; } public void removeLogListener ( LogListener l , Object component ) { removed = true ; logger . debug ( "" ) ; } public void onDestroy ( ) { throw new RuntimeException ( "" ) ; } } class MyJob extends MockStateful { public String getLogger ( ) { return "" ; } boolean added ; boolean removed ; public void addStateListener ( StateListener listener ) { logger . debug ( "" ) ; added = true ; } public void removeStateListener ( StateListener listener ) { logger . debug ( "" ) ; removed = true ; } } Observable observable ; Object ar ; class MyO implements Observer { public void update ( Observable o , Object arg ) { observable = o ; ar = arg ; } } public void testSelect ( ) { MyLA la = new MyLA ( ) ; MyJob myJob = new MyJob ( ) ; DetailModel detailModel = new DetailModel ( ) ; OurExplorerContext context = new OurExplorerContext ( ) ; context . component = myJob ; context . logArchiver = la ; context . consoleArchiver = new LocalConsoleArchiver ( ) ; Oddjob . class . getName ( ) ; System . out . println ( "" ) ; detailModel . setTabSelected ( DetailModel . CONSOLE_TAB ) ; logger . debug ( "" ) ; Observable consoleModel = detailModel . getConsoleModel ( ) ; consoleModel . addObserver ( new MyO ( ) ) ; detailModel . setSelectedContext ( context ) ; detailModel . setTabSelected ( DetailModel . LOG_TAB ) ; logger . debug ( "" ) ; logger . debug ( "" ) ; detailModel . setSelectedContext ( null ) ; assertTrue ( la . removed ) ; la . removed = false ; detailModel . setTabSelected ( DetailModel . STATE_TAB ) ; logger . debug ( "" ) ; detailModel . setSelectedContext ( context ) ; assertTrue ( myJob . added ) ; logger . debug ( "" ) ; detailModel . setSelectedContext ( null ) ; assertTrue ( myJob . removed ) ; } } package org . oddjob . monitor . view ; import java . awt . Component ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import javax . swing . JMenu ; import javax . swing . JMenuItem ; import javax . swing . JSeparator ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . design . actions . ConfigurableMenus ; import org . oddjob . arooa . design . designer . MenuProvider ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . MockConfigurationOwner ; import org . oddjob . arooa . parsing . MockConfigurationSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextInialiser ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; import org . xml . sax . SAXException ; public class ExplorerEditActionsTest extends TestCase { private static final Logger logger = Logger . getLogger ( ExplorerEditActionsTest . class ) ; class ParentContext extends MockExplorerContext { ConfigurationSession session ; @ Override public Object getValue ( String key ) { if ( ConfigContextInialiser . CONFIG_OWNER . equals ( key ) ) { return new MockConfigurationOwner ( ) { public ConfigurationSession provideConfigurationSession ( ) { return session ; } } ; } throw new RuntimeException ( "" + key ) ; } } class OurExplorerContext extends MockExplorerContext { Object thisComponent ; ParentContext parent = new ParentContext ( ) ; @ Override public Object getThisComponent ( ) { return thisComponent ; } @ Override public ExplorerContext getParent ( ) { return parent ; } } class NoDragPointSession extends MockConfigurationSession { @ Override public DragPoint dragPointFor ( Object component ) { return null ; } } public void testNoDragPoint ( ) throws ArooaParseException { Object object = new Object ( ) ; OurExplorerContext econ = new OurExplorerContext ( ) ; econ . parent . session = new NoDragPointSession ( ) ; econ . thisComponent = object ; final ExplorerEditActions test = new ExplorerEditActions ( ) ; ConfigurableMenus menus = new ConfigurableMenus ( ) ; test . contributeTo ( menus ) ; test . setSelectedContext ( econ ) ; test . prepare ( ) ; List < JMenuItem > menuItems = extractMenuItems ( menus ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; } public void testNormalSelction ( ) throws ArooaParseException , SAXException , IOException { String xml = "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; Object object = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertNotNull ( object ) ; OurExplorerContext econ = new OurExplorerContext ( ) ; econ . parent . session = oddjob . provideConfigurationSession ( ) ; econ . thisComponent = object ; final ExplorerEditActions test = new ExplorerEditActions ( ) ; ConfigurableMenus menus = new ConfigurableMenus ( ) ; test . contributeTo ( menus ) ; test . setSelectedContext ( econ ) ; test . prepare ( ) ; List < JMenuItem > menuItems = extractMenuItems ( menus ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertTrue ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertTrue ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertTrue ( menuItems . get ( ) . isEnabled ( ) ) ; } public void testNestedOddjob ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; Object object = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertNotNull ( object ) ; OurExplorerContext econ = new OurExplorerContext ( ) ; econ . parent . session = oddjob . provideConfigurationSession ( ) ; econ . thisComponent = object ; final ExplorerEditActions test = new ExplorerEditActions ( ) ; ConfigurableMenus menus = new ConfigurableMenus ( ) ; test . contributeTo ( menus ) ; test . setSelectedContext ( econ ) ; test . prepare ( ) ; List < JMenuItem > menuItems = extractMenuItems ( menus ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertTrue ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertTrue ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertTrue ( menuItems . get ( ) . isEnabled ( ) ) ; } class RootContext extends MockExplorerContext { Oddjob thisComponent ; @ Override public Object getThisComponent ( ) { return thisComponent ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) { } ; } @ Override public Object getValue ( String key ) { if ( ConfigContextInialiser . CONFIG_OWNER . equals ( key ) ) { return thisComponent ; } throw new RuntimeException ( "" + key ) ; } @ Override public ExplorerContext getParent ( ) { return null ; } } public void testSelectOddjob ( ) throws ArooaParseException { Oddjob oj = new Oddjob ( ) ; RootContext econ = new RootContext ( ) ; econ . thisComponent = oj ; final ExplorerEditActions test = new ExplorerEditActions ( ) ; ConfigurableMenus menus = new ConfigurableMenus ( ) ; test . contributeTo ( menus ) ; test . setSelectedContext ( econ ) ; test . prepare ( ) ; List < JMenuItem > menuItems = extractMenuItems ( menus ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( ) . isVisible ( ) ) ; oj . setConfiguration ( new XMLConfiguration ( "" , "" ) ) ; oj . load ( ) ; test . setSelectedContext ( econ ) ; test . prepare ( ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertTrue ( menuItems . get ( ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertTrue ( menuItems . get ( ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ) . getText ( ) ) ; assertFalse ( menuItems . get ( ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( ) . isVisible ( ) ) ; } private static List < JMenuItem > extractMenuItems ( MenuProvider menus ) { JMenu menu = menus . getJMenuBar ( ) [ ] ; Component [ ] components = menu . getMenuComponents ( ) ; List < JMenuItem > menuItems = new ArrayList < JMenuItem > ( ) ; for ( Component component : components ) { if ( component instanceof JMenuItem ) { JMenuItem menuItem = ( JMenuItem ) component ; logger . debug ( menuItem . getText ( ) + "" + menuItem . isEnabled ( ) ) ; menuItems . add ( menuItem ) ; } else if ( component instanceof JSeparator ) { logger . debug ( "" ) ; } else { logger . debug ( component . getClass ( ) ) ; } } return menuItems ; } } package org . oddjob . monitor . view ; import java . awt . Component ; import java . util . ArrayList ; import java . util . List ; import javax . swing . JMenu ; import javax . swing . JMenuItem ; import javax . swing . JSeparator ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . design . actions . ConfigurableMenus ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . MockConfigurationOwner ; import org . oddjob . arooa . parsing . MockConfigurationSession ; import org . oddjob . arooa . standard . StandardArooaDescriptor ; import org . oddjob . monitor . actions . ExplorerAction ; import org . oddjob . monitor . actions . ResourceActionProvider ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextInialiser ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; public class ActionModelTest extends TestCase { private static final Logger logger = Logger . getLogger ( ActionModelTest . class ) ; class OurSessionLite extends MockConfigurationSession { ArooaDescriptor descriptor = new StandardArooaDescriptor ( ) ; @ Override public ArooaDescriptor getArooaDescriptor ( ) { return descriptor ; } @ Override public DragPoint dragPointFor ( Object component ) { return null ; } } class ParentContext extends MockExplorerContext { ConfigurationSession session = new OurSessionLite ( ) ; @ Override public Object getValue ( String key ) { if ( ConfigContextInialiser . CONFIG_OWNER . equals ( key ) ) { return new MockConfigurationOwner ( ) { public ConfigurationSession provideConfigurationSession ( ) { return session ; } } ; } throw new RuntimeException ( "" + key ) ; } } class OurExplorerContext extends MockExplorerContext { Object thisComponent ; @ Override public Object getThisComponent ( ) { return thisComponent ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) { } ; } @ Override public ExplorerContext getParent ( ) { return new ParentContext ( ) ; } } public void testSelectObject ( ) throws ArooaParseException { Object object = new Object ( ) ; OurExplorerContext econ = new OurExplorerContext ( ) ; econ . thisComponent = object ; ExplorerAction [ ] actions = new ResourceActionProvider ( new OddjobSessionFactory ( ) . createSession ( ) ) . getExplorerActions ( ) ; final ExplorerJobActions test = new ExplorerJobActions ( actions ) ; ConfigurableMenus menus = new ConfigurableMenus ( ) ; test . contributeTo ( menus ) ; test . setSelectedContext ( econ ) ; test . prepare ( ) ; JMenu menu = menus . getJMenuBar ( ) [ ] ; Component [ ] components = menu . getMenuComponents ( ) ; List < JMenuItem > menuItems = new ArrayList < JMenuItem > ( ) ; for ( Component component : components ) { if ( component instanceof JMenuItem ) { JMenuItem menuItem = ( JMenuItem ) component ; logger . debug ( menuItem . getText ( ) + "" + menuItem . isEnabled ( ) ) ; menuItems . add ( menuItem ) ; } else if ( component instanceof JSeparator ) { logger . debug ( "" ) ; } else { logger . debug ( component . getClass ( ) ) ; } } int i = ; assertEquals ( "" , menuItems . get ( i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertFalse ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertFalse ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertTrue ( menuItems . get ( i ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertFalse ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertFalse ( menuItems . get ( i ) . isVisible ( ) ) ; } class RootContext extends MockExplorerContext { Oddjob thisComponent ; @ Override public Object getThisComponent ( ) { return thisComponent ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) { } ; } @ Override public Object getValue ( String key ) { if ( ConfigContextInialiser . CONFIG_OWNER . equals ( key ) ) { return thisComponent ; } throw new RuntimeException ( "" + key ) ; } @ Override public ExplorerContext getParent ( ) { return null ; } } public void testSelectOddjob ( ) throws ArooaParseException { Oddjob oj = new Oddjob ( ) ; RootContext econ = new RootContext ( ) ; econ . thisComponent = oj ; ExplorerAction [ ] actions = new ResourceActionProvider ( new OddjobSessionFactory ( ) . createSession ( ) ) . getExplorerActions ( ) ; final ExplorerJobActions test = new ExplorerJobActions ( actions ) ; ConfigurableMenus menus = new ConfigurableMenus ( ) ; test . contributeTo ( menus ) ; test . setSelectedContext ( econ ) ; test . prepare ( ) ; JMenu menu = menus . getJMenuBar ( ) [ ] ; Component [ ] components = menu . getMenuComponents ( ) ; List < JMenuItem > menuItems = new ArrayList < JMenuItem > ( ) ; for ( Component component : components ) { if ( component instanceof JMenuItem ) { JMenuItem menuItem = ( JMenuItem ) component ; logger . debug ( menuItem . getText ( ) + "" + menuItem . isEnabled ( ) ) ; menuItems . add ( menuItem ) ; } else if ( component instanceof JSeparator ) { logger . debug ( "" ) ; } else { logger . debug ( component . getClass ( ) ) ; } } int i = ; assertEquals ( "" , menuItems . get ( i ) . getText ( ) ) ; assertTrue ( menuItems . get ( i ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertTrue ( menuItems . get ( i ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertTrue ( menuItems . get ( i ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertTrue ( menuItems . get ( i ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertTrue ( menuItems . get ( i ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertTrue ( menuItems . get ( i ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertFalse ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertFalse ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertTrue ( menuItems . get ( i ) . isVisible ( ) ) ; assertEquals ( "" , menuItems . get ( ++ i ) . getText ( ) ) ; assertFalse ( menuItems . get ( i ) . isEnabled ( ) ) ; assertFalse ( menuItems . get ( i ) . isVisible ( ) ) ; } } package org . oddjob . monitor . view ; import java . awt . GraphicsEnvironment ; import javax . swing . JMenu ; import junit . framework . TestCase ; import org . oddjob . monitor . action . HardResetAction ; import org . oddjob . monitor . actions . ExplorerAction ; import org . oddjob . monitor . model . DetailModel ; public class MonitorMenuBarTest extends TestCase { public void testSetSession ( ) { if ( GraphicsEnvironment . isHeadless ( ) ) { return ; } MonitorMenuBar test = new MonitorMenuBar ( ) ; DetailModel detailModel = new DetailModel ( ) ; ExplorerJobActions jobActions = new ExplorerJobActions ( new ExplorerAction [ ] { new HardResetAction ( ) } ) ; test . setSession ( jobActions , detailModel ) ; assertEquals ( , test . getMenuCount ( ) ) ; JMenu jobMenu = test . getMenu ( ) ; assertEquals ( "" , jobMenu . getActionCommand ( ) ) ; assertEquals ( , jobMenu . getMenuComponentCount ( ) ) ; } } package org . oddjob . monitor . view ; import java . util . ArrayList ; import java . util . List ; import javax . swing . Action ; import junit . framework . TestCase ; import org . oddjob . arooa . design . actions . ActionMenu ; import org . oddjob . arooa . design . actions . ArooaAction ; import org . oddjob . arooa . design . actions . MockActionRegistry ; import org . oddjob . monitor . action . ExecuteAction ; import org . oddjob . monitor . action . StopAction ; import org . oddjob . monitor . actions . ExplorerAction ; public class ExplorerJobActionsTest extends TestCase { class OurRegistry extends MockActionRegistry { ActionMenu mainMenu ; List < String > names = new ArrayList < String > ( ) ; List < String > commands = new ArrayList < String > ( ) ; @ Override public void addMainMenu ( ActionMenu menu ) { this . mainMenu = menu ; } @ Override public void addMenuItem ( String menuId , String group , ArooaAction action ) { names . add ( ( String ) action . getValue ( Action . NAME ) ) ; commands . add ( ( String ) action . getValue ( Action . ACTION_COMMAND_KEY ) ) ; } @ Override public void addContextMenuItem ( String group , ArooaAction action ) { } } public void testActionName ( ) { ExplorerAction [ ] actions = new ExplorerAction [ ] { new ExecuteAction ( ) , new StopAction ( ) } ; ExplorerJobActions test = new ExplorerJobActions ( actions ) ; OurRegistry actionRegistry = new OurRegistry ( ) ; test . contributeTo ( actionRegistry ) ; assertEquals ( "" , actionRegistry . mainMenu . getId ( ) ) ; assertEquals ( "" , actionRegistry . names . get ( ) ) ; assertEquals ( "" , actionRegistry . names . get ( ) ) ; } } package org . oddjob . monitor ; import java . awt . GraphicsEnvironment ; import java . beans . PropertyVetoException ; import java . io . IOException ; import java . lang . reflect . InvocationTargetException ; import java . util . Collection ; import java . util . concurrent . atomic . AtomicReference ; import javax . swing . Action ; import javax . swing . JTree ; import javax . swing . SwingUtilities ; import org . apache . log4j . Logger ; import org . custommonkey . xmlunit . XMLTestCase ; import org . custommonkey . xmlunit . XMLUnit ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . design . designer . ArooaTree ; import org . oddjob . arooa . parsing . ConfigSessionEvent ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . parsing . MockConfigurationOwner ; import org . oddjob . arooa . parsing . MockConfigurationSession ; import org . oddjob . arooa . parsing . OwnerStateListener ; import org . oddjob . arooa . parsing . SessionStateListener ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . model . JobTreeNode ; import org . oddjob . monitor . view . ExplorerComponent ; import org . xml . sax . SAXException ; public class OddjobExplorerTest extends XMLTestCase { private Logger logger = Logger . getLogger ( OddjobExplorerTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testSave ( ) throws SAXException , IOException , PropertyVetoException { if ( GraphicsEnvironment . isHeadless ( ) ) { return ; } XMLUnit . setIgnoreWhitespace ( true ) ; String xml = "" + "" + "" + "" + "" ; XMLConfiguration config = new XMLConfiguration ( "" , xml ) ; final AtomicReference < String > savedXML = new AtomicReference < String > ( ) ; config . setSaveHandler ( new XMLConfiguration . SaveHandler ( ) { @ Override public void acceptXML ( String xml ) { savedXML . set ( xml ) ; } } ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . load ( ) ; OddjobExplorer test = new OddjobExplorer ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . createView ( ) ; test . addPropertyChangeListener ( test . new ChangeFocus ( ) ) ; test . addPropertyChangeListener ( test . new ChangeView ( ) ) ; test . setOddjob ( oddjob ) ; ExplorerComponent component = test . getExplorerComponent ( ) ; component . getTree ( ) . setSelectionRow ( ) ; assertNull ( savedXML . get ( ) ) ; Action action = test . new SaveAction ( ) ; action . actionPerformed ( null ) ; assertXMLEqual ( xml , savedXML . get ( ) ) ; } public static class OurConfigOwner extends MockConfigurationOwner { SessionStateListener listener ; public ConfigurationSession provideConfigurationSession ( ) { return new MockConfigurationSession ( ) { @ Override public boolean isModified ( ) { return false ; } @ Override public void addSessionStateListener ( SessionStateListener listener ) { assertNull ( OurConfigOwner . this . listener ) ; OurConfigOwner . this . listener = listener ; } @ Override public void removeSessionStateListener ( SessionStateListener listener ) { assertEquals ( OurConfigOwner . this . listener , listener ) ; OurConfigOwner . this . listener = null ; } } ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { } @ Override public String toString ( ) { return "" ; } } public void testTitle ( ) throws Exception { if ( GraphicsEnvironment . isHeadless ( ) ) { return ; } XMLUnit . setIgnoreWhitespace ( true ) ; String xml = "" + "" + "" + OurConfigOwner . class . getName ( ) + "" + "" + "" ; XMLConfiguration config = new XMLConfiguration ( "" , xml ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setName ( "" ) ; oddjob . setConfiguration ( config ) ; oddjob . load ( ) ; OddjobExplorer test = new OddjobExplorer ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . createView ( ) ; test . addPropertyChangeListener ( test . new ChangeFocus ( ) ) ; test . addPropertyChangeListener ( test . new ChangeView ( ) ) ; assertEquals ( "" , test . getTitle ( ) ) ; test . setOddjob ( oddjob ) ; ExplorerComponent component = test . getExplorerComponent ( ) ; assertEquals ( "" , test . getTitle ( ) ) ; final JTree tree = component . getTree ( ) ; assertEquals ( false , tree . isExpanded ( ) ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { tree . expandRow ( ) ; tree . setSelectionRow ( ) ; } } ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { } } ) ; assertEquals ( false , tree . isSelectionEmpty ( ) ) ; assertEquals ( "" , test . getTitle ( ) ) ; OurConfigOwner owner = ( OurConfigOwner ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; owner . listener . sessionModifed ( new ConfigSessionEvent ( new MockConfigurationSession ( ) ) ) ; assertEquals ( "" , test . getTitle ( ) ) ; final DragPoint dragPoint = oddjob . provideConfigurationSession ( ) . dragPointFor ( owner ) ; final AtomicReference < Exception > er = new AtomicReference < Exception > ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; dragPoint . cut ( ) ; try { trn . commit ( ) ; } catch ( ArooaParseException e ) { trn . rollback ( ) ; er . set ( e ) ; } } } ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { } } ) ; if ( er . get ( ) != null ) { throw er . get ( ) ; } assertEquals ( "" , test . getTitle ( ) ) ; } public void testNewOddjob ( ) throws SAXException , IOException , PropertyVetoException , ArooaParseException , InterruptedException , InvocationTargetException { if ( GraphicsEnvironment . isHeadless ( ) ) { return ; } XMLUnit . setIgnoreWhitespace ( true ) ; OddjobExplorer test = new OddjobExplorer ( ) ; test . setArooaSession ( new OddjobSessionFactory ( ) . createSession ( ) ) ; test . createView ( ) ; test . addPropertyChangeListener ( test . new ChangeFocus ( ) ) ; test . addPropertyChangeListener ( test . new ChangeView ( ) ) ; assertEquals ( "" , test . getTitle ( ) ) ; test . new NewAction ( ) . actionPerformed ( null ) ; assertEquals ( "" , test . getTitle ( ) ) ; final ArooaTree tree = ( ArooaTree ) test . getExplorerComponent ( ) . getTree ( ) ; tree . setSelectionRow ( ) ; final JobTreeNode node = ( JobTreeNode ) tree . getSelectionPath ( ) . getLastPathComponent ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { DragPoint dragPoint = tree . getDragPoint ( node ) ; try { DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; dragPoint . paste ( , "" ) ; trn . commit ( ) ; } catch ( ArooaParseException e ) { throw new RuntimeException ( e ) ; } } } ) ; assertEquals ( "" , test . getTitle ( ) ) ; } public void testResetOddjob ( ) throws PropertyVetoException , ArooaParseException { if ( GraphicsEnvironment . isHeadless ( ) ) { return ; } String xml = "" ; XMLConfiguration config = new XMLConfiguration ( "" , xml ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setName ( "" ) ; oddjob . setConfiguration ( config ) ; oddjob . load ( ) ; OddjobExplorer test = new OddjobExplorer ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . createView ( ) ; test . addPropertyChangeListener ( test . new ChangeFocus ( ) ) ; test . addPropertyChangeListener ( test . new ChangeView ( ) ) ; test . setOddjob ( oddjob ) ; assertEquals ( "" , test . getTitle ( ) ) ; DragPoint dragPoint = oddjob . provideConfigurationSession ( ) . dragPointFor ( oddjob ) ; DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; dragPoint . paste ( , "" ) ; trn . commit ( ) ; assertEquals ( "" , test . getTitle ( ) ) ; oddjob . hardReset ( ) ; assertEquals ( "" , test . getTitle ( ) ) ; } public void testCheckModifications ( ) throws PropertyVetoException , ArooaParseException , InterruptedException , InvocationTargetException { if ( GraphicsEnvironment . isHeadless ( ) ) { return ; } final OddjobExplorer test = new OddjobExplorer ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . createView ( ) ; final boolean [ ] checked = new boolean [ ] ; test . addPropertyChangeListener ( test . new ChangeView ( ) ) ; test . vetoableChangeSupport . addVetoableChangeListener ( test . new CheckConfigurationsSaved ( ) { @ Override boolean canClose ( Collection < ConfigurationOwner > modified ) { assertEquals ( , modified . size ( ) ) ; checked [ ] = true ; return true ; } } ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { test . new NewAction ( ) . actionPerformed ( null ) ; Oddjob oddjob = test . getOddjob ( ) ; DragPoint dragPoint = oddjob . provideConfigurationSession ( ) . dragPointFor ( oddjob ) ; try { DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; dragPoint . paste ( , "" ) ; trn . commit ( ) ; } catch ( ArooaParseException e ) { throw new RuntimeException ( e ) ; } } } ) ; test . setOddjob ( null ) ; assertTrue ( checked [ ] ) ; } public void testModifiedOnCloseAction ( ) throws SAXException , IOException , PropertyVetoException , ArooaParseException , InterruptedException , InvocationTargetException { if ( GraphicsEnvironment . isHeadless ( ) ) { return ; } String xml = "" + "" + "" + "" + "" ; XMLConfiguration config = new XMLConfiguration ( "" , xml ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . load ( ) ; OddjobExplorer test = new OddjobExplorer ( ) ; test . setArooaSession ( new OddjobSessionFactory ( ) . createSession ( ) ) ; test . createView ( ) ; test . addPropertyChangeListener ( test . new ChangeFocus ( ) ) ; test . addPropertyChangeListener ( test . new ChangeView ( ) ) ; assertEquals ( "" , test . getTitle ( ) ) ; test . setOddjob ( oddjob ) ; assertEquals ( "" , test . getTitle ( ) ) ; test . new CloseAction ( ) . actionPerformed ( null ) ; assertEquals ( "" , test . getTitle ( ) ) ; } } package org . oddjob . monitor . actions ; import junit . framework . TestCase ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . monitor . action . AddJobAction ; import org . oddjob . monitor . action . DesignInsideAction ; import org . oddjob . monitor . action . DesignerAction ; import org . oddjob . monitor . action . ExecuteAction ; import org . oddjob . monitor . action . ForceAction ; import org . oddjob . monitor . action . HardResetAction ; import org . oddjob . monitor . action . LoadAction ; import org . oddjob . monitor . action . SetPropertyAction ; import org . oddjob . monitor . action . SoftResetAction ; import org . oddjob . monitor . action . StopAction ; import org . oddjob . monitor . action . UnloadAction ; public class ResourceActionProviderTest extends TestCase { public void testActions ( ) throws ArooaParseException { ExplorerAction [ ] results = new ResourceActionProvider ( new OddjobSessionFactory ( ) . createSession ( ) ) . getExplorerActions ( ) ; assertEquals ( , results . length ) ; assertEquals ( LoadAction . class , results [ ] . getClass ( ) ) ; assertEquals ( UnloadAction . class , results [ ] . getClass ( ) ) ; assertEquals ( ExecuteAction . class , results [ ] . getClass ( ) ) ; assertEquals ( SoftResetAction . class , results [ ] . getClass ( ) ) ; assertEquals ( HardResetAction . class , results [ ] . getClass ( ) ) ; assertEquals ( StopAction . class , results [ ] . getClass ( ) ) ; assertEquals ( ForceAction . class , results [ ] . getClass ( ) ) ; assertEquals ( SetPropertyAction . class , results [ ] . getClass ( ) ) ; assertEquals ( DesignerAction . class , results [ ] . getClass ( ) ) ; assertEquals ( DesignInsideAction . class , results [ ] . getClass ( ) ) ; assertEquals ( AddJobAction . class , results [ ] . getClass ( ) ) ; } } package org . oddjob . monitor . actions ; import java . beans . PropertyChangeListener ; import javax . swing . KeyStroke ; import org . oddjob . monitor . context . ExplorerContext ; public class MockExplorerAction implements ExplorerAction { @ Override public String getName ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public String getGroup ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public Integer getMnemonicKey ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public KeyStroke getAcceleratorKey ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void setSelectedContext ( ExplorerContext eContext ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void addPropertyChangeListener ( PropertyChangeListener listener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void removePropertyChangeListener ( PropertyChangeListener listener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void prepare ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void action ( ) throws Exception { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public boolean isEnabled ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public boolean isVisible ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . monitor . action ; import javax . inject . Inject ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ExplorerContextImpl ; import org . oddjob . monitor . model . ExplorerModelImpl ; import org . oddjob . util . SimpleThreadManager ; public class ExecuteActionTest2 extends TestCase { class MyClassLoader extends ClassLoader { } public static class ClassLoaderCapture implements Runnable { ClassLoader context ; ClassLoader result ; public void run ( ) { context = Thread . currentThread ( ) . getContextClassLoader ( ) ; } @ Inject public void setResult ( ClassLoader result ) { this . result = result ; } public ClassLoader getResult ( ) { return result ; } public ClassLoader getContext ( ) { return context ; } } public void testClassLoader ( ) throws Exception { ClassLoader startLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; String xml = "" + "" + "" + "" + ClassLoaderCapture . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; MyClassLoader loader = new MyClassLoader ( ) ; ExecuteAction test = new ExecuteAction ( ) ; ExplorerModelImpl eModel = new ExplorerModelImpl ( new StandardArooaSession ( ) ) ; eModel . setThreadManager ( new SimpleThreadManager ( ) ) ; eModel . setOddjob ( oddjob ) ; ExplorerContextImpl rootContext = new ExplorerContextImpl ( eModel ) ; oddjob . setClassLoader ( loader ) ; oddjob . run ( ) ; assertTrue ( startLoader == Thread . currentThread ( ) . getContextClassLoader ( ) ) ; Object capture = new OddjobLookup ( oddjob ) . lookup ( "" ) ; ( ( Resetable ) capture ) . hardReset ( ) ; ExplorerContext ourContext = rootContext . addChild ( capture ) ; test . setSelectedContext ( ourContext ) ; test . action ( ) ; ClassLoader result = ( ClassLoader ) PropertyUtils . getProperty ( capture , "" ) ; assertEquals ( loader , result ) ; ClassLoader context = ( ClassLoader ) PropertyUtils . getProperty ( capture , "" ) ; assertEquals ( startLoader , context ) ; } } package org . oddjob . monitor . action ; import junit . framework . TestCase ; import org . oddjob . Loadable ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; public class LoadActionTest extends TestCase { private class OurLoadable implements Loadable { boolean loadable = true ; public boolean isLoadable ( ) { return loadable ; } public void load ( ) { setLoadable ( false ) ; } @ Override public void unload ( ) { throw new RuntimeException ( "" ) ; } void setLoadable ( boolean loadable ) { this . loadable = loadable ; } } class OurEContext extends MockExplorerContext { OurLoadable loadable = new OurLoadable ( ) ; @ Override public Object getThisComponent ( ) { return loadable ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) { @ Override public void run ( Runnable runnable , String description ) { runnable . run ( ) ; } } ; } } public void testCycle ( ) throws Exception { LoadAction test = new LoadAction ( ) ; assertFalse ( test . isEnabled ( ) ) ; assertFalse ( test . isVisible ( ) ) ; OurEContext eContext = new OurEContext ( ) ; test . setSelectedContext ( eContext ) ; test . prepare ( ) ; assertTrue ( test . isEnabled ( ) ) ; assertTrue ( test . isVisible ( ) ) ; assertTrue ( eContext . loadable . loadable ) ; test . action ( ) ; test . prepare ( ) ; assertFalse ( eContext . loadable . loadable ) ; assertFalse ( test . isEnabled ( ) ) ; assertTrue ( test . isVisible ( ) ) ; test . setSelectedContext ( null ) ; assertFalse ( test . isEnabled ( ) ) ; assertFalse ( test . isVisible ( ) ) ; } } package org . oddjob . monitor . action ; import java . awt . Component ; import java . awt . KeyboardFocusManager ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import javax . swing . JFrame ; import javax . swing . WindowConstants ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . view . SwingFormFactory ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . input . StdInInputHandler ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextInialiser ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . state . ParentState ; public class DesignerActionTest extends TestCase { private class RootContext extends MockExplorerContext { @ Override public ExplorerContext getParent ( ) { return null ; } } public void testRoot ( ) { DesignerAction test = new DesignerAction ( ) ; test . setSelectedContext ( new RootContext ( ) ) ; test . prepare ( ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; test . setSelectedContext ( null ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; test . setSelectedContext ( null ) ; } private class ParentContext extends MockExplorerContext { ConfigurationOwner configOwner ; @ Override public Object getValue ( String key ) { assertEquals ( ConfigContextInialiser . CONFIG_OWNER , key ) ; return configOwner ; } } private class OurExplorerContext extends MockExplorerContext { Object component ; ParentContext parent = new ParentContext ( ) ; @ Override public Object getThisComponent ( ) { return component ; } @ Override public ExplorerContext getParent ( ) { return parent ; } } XMLConfiguration config ; DesignerAction test = new DesignerAction ( ) ; public void testGoodConfig ( ) { String xml = "" + "" + "" + "" + "" ; config = new XMLConfiguration ( "" , xml ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . setInputHandler ( new StdInInputHandler ( ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Object sequentialJob = new OddjobLookup ( oddjob ) . lookup ( "" ) ; OurExplorerContext explorerContext = new OurExplorerContext ( ) ; explorerContext . parent . configOwner = oddjob ; explorerContext . component = sequentialJob ; test . setSelectedContext ( explorerContext ) ; test . prepare ( ) ; assertTrue ( test . isEnabled ( ) ) ; Form form = test . form ( ) ; assertNotNull ( form ) ; } public static void main ( String ... args ) throws Exception { final DesignerActionTest test = new DesignerActionTest ( ) ; test . testGoodConfig ( ) ; test . config . setSaveHandler ( new XMLConfiguration . SaveHandler ( ) { @ Override public void acceptXML ( String xml ) { System . out . println ( xml ) ; } } ) ; Component view = SwingFormFactory . create ( test . test . form ( ) ) . dialog ( ) ; KeyboardFocusManager focusManager = KeyboardFocusManager . getCurrentKeyboardFocusManager ( ) ; focusManager . addPropertyChangeListener ( new PropertyChangeListener ( ) { @ Override public void propertyChange ( PropertyChangeEvent evt ) { System . out . println ( evt . getPropertyName ( ) + "" + evt . getNewValue ( ) ) ; } } ) ; JFrame frame = new JFrame ( ) ; frame . getContentPane ( ) . add ( view ) ; frame . pack ( ) ; frame . setVisible ( true ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosed ( WindowEvent e ) { try { test . test . action ( ) ; } catch ( Exception e1 ) { throw new RuntimeException ( e1 ) ; } } } ) ; frame . setDefaultCloseOperation ( WindowConstants . DISPOSE_ON_CLOSE ) ; } } package org . oddjob . monitor . action ; import junit . framework . TestCase ; import org . oddjob . Stoppable ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; public class StopActionTest extends TestCase { class OurExplorerContext extends MockExplorerContext { Object component ; @ Override public Object getThisComponent ( ) { return component ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) { @ Override public void run ( Runnable runnable , String description ) { runnable . run ( ) ; } } ; } } public void testPerform ( ) throws Exception { class MyS implements Stoppable { boolean stopped = false ; public void stop ( ) { stopped = true ; } } MyS sample = new MyS ( ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = sample ; JobAction test = new StopAction ( ) ; test . setSelectedContext ( ec ) ; assertTrue ( test . isEnabled ( ) ) ; test . action ( ) ; assertTrue ( sample . stopped ) ; } public void testWithObject ( ) { OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = new Object ( ) ; JobAction test = new StopAction ( ) ; test . setSelectedContext ( ec ) ; test . prepare ( ) ; assertFalse ( test . isEnabled ( ) ) ; } } package org . oddjob . monitor . action ; import java . awt . Component ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import javax . swing . JFrame ; import javax . swing . WindowConstants ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . view . SwingFormFactory ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . state . ParentState ; public class DesignInsideActionTest extends TestCase { class OurExplorerContext extends MockExplorerContext { Object object ; @ Override public Object getThisComponent ( ) { return object ; } @ Override public ExplorerContext getParent ( ) { return null ; } } XMLConfiguration config ; DesignInsideAction test = new DesignInsideAction ( ) ; public void testBadRootConfig ( ) throws Exception { config = new XMLConfiguration ( "" , "" ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . run ( ) ; assertEquals ( ParentState . EXCEPTION , oddjob . lastStateEvent ( ) . getState ( ) ) ; OurExplorerContext explorerContext = new OurExplorerContext ( ) ; explorerContext . object = oddjob ; test . setSelectedContext ( explorerContext ) ; test . prepare ( ) ; assertTrue ( test . isVisible ( ) ) ; assertTrue ( test . isEnabled ( ) ) ; Form form = test . form ( ) ; assertNotNull ( form ) ; test . setSelectedContext ( null ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; } public void testGoodRootConfig ( ) throws Exception { config = new XMLConfiguration ( "" , "" ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . run ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OurExplorerContext explorerContext = new OurExplorerContext ( ) ; explorerContext . object = oddjob ; test . setSelectedContext ( explorerContext ) ; test . prepare ( ) ; assertTrue ( test . isVisible ( ) ) ; assertTrue ( test . isEnabled ( ) ) ; Form form = test . form ( ) ; assertNotNull ( form ) ; test . setSelectedContext ( null ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; } public void testNonConfigurationOwner ( ) { String xml = "" + "" + "" + "" + "" ; config = new XMLConfiguration ( "" , xml ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . run ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OurExplorerContext explorerContext = new OurExplorerContext ( ) ; explorerContext . object = new OddjobLookup ( oddjob ) . lookup ( "" ) ; test . setSelectedContext ( explorerContext ) ; test . prepare ( ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; test . setSelectedContext ( null ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; } public void testNestedOddjobNoConfig ( ) { String xml = "" + "" + "" + "" + "" ; config = new XMLConfiguration ( "" , xml ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OurExplorerContext explorerContext = new OurExplorerContext ( ) ; explorerContext . object = new OddjobLookup ( oddjob ) . lookup ( "" ) ; test . setSelectedContext ( explorerContext ) ; test . prepare ( ) ; assertTrue ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; test . setSelectedContext ( null ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; } public void testNestedOddjob ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; config = new XMLConfiguration ( "" , xml ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . run ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OurExplorerContext explorerContext = new OurExplorerContext ( ) ; explorerContext . object = new OddjobLookup ( oddjob ) . lookup ( "" ) ; test . setSelectedContext ( explorerContext ) ; assertTrue ( test . isVisible ( ) ) ; assertTrue ( test . isEnabled ( ) ) ; test . setSelectedContext ( null ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; } public static void main ( String ... args ) throws Exception { final DesignInsideActionTest test = new DesignInsideActionTest ( ) ; test . testNestedOddjob ( ) ; test . config . setSaveHandler ( new XMLConfiguration . SaveHandler ( ) { @ Override public void acceptXML ( String xml ) { System . out . println ( xml ) ; } } ) ; Component view = SwingFormFactory . create ( test . test . form ( ) ) . dialog ( ) ; JFrame frame = new JFrame ( ) ; frame . getContentPane ( ) . add ( view ) ; frame . pack ( ) ; frame . setVisible ( true ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosed ( WindowEvent e ) { try { test . test . action ( ) ; } catch ( Exception e1 ) { throw new RuntimeException ( e1 ) ; } } } ) ; frame . setDefaultCloseOperation ( WindowConstants . DISPOSE_ON_CLOSE ) ; } } package org . oddjob . monitor . action ; import junit . framework . TestCase ; import org . oddjob . MockStateful ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; public class ExecuteActionTest extends TestCase { class OurThreadManager extends MockThreadManager { public void run ( Runnable runnable , String description ) { runnable . run ( ) ; } } class OurExplorerContext extends MockExplorerContext { final OurThreadManager threadManager = new OurThreadManager ( ) ; Object component ; @ Override public Object getThisComponent ( ) { return component ; } public ThreadManager getThreadManager ( ) { return threadManager ; } } public void testPerform ( ) throws Exception { class MyR implements Runnable { boolean ran = false ; public void run ( ) { ran = true ; } } MyR sample = new MyR ( ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = sample ; JobAction test = new ExecuteAction ( ) ; test . setSelectedContext ( ec ) ; test . action ( ) ; assertTrue ( sample . ran ) ; } public void testEnabled ( ) { class MySR extends MockStateful implements Runnable { boolean removed ; public void run ( ) { } public void addStateListener ( StateListener listener ) { listener . jobStateChange ( new StateEvent ( this , JobState . READY ) ) ; } public void removeStateListener ( StateListener listener ) { removed = true ; } } MySR sample = new MySR ( ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = sample ; JobAction test = new ExecuteAction ( ) ; test . setSelectedContext ( ec ) ; test . prepare ( ) ; assertTrue ( test . isEnabled ( ) ) ; test . setSelectedContext ( null ) ; assertTrue ( sample . removed ) ; } public void testDisabled ( ) { class MySR extends MockStateful implements Runnable { boolean removed ; public void run ( ) { } public void addStateListener ( StateListener listener ) { listener . jobStateChange ( new StateEvent ( this , JobState . COMPLETE ) ) ; } public void removeStateListener ( StateListener listener ) { removed = true ; } } MySR sample = new MySR ( ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = sample ; JobAction test = new ExecuteAction ( ) ; test . setSelectedContext ( ec ) ; test . prepare ( ) ; assertFalse ( test . isEnabled ( ) ) ; test . setSelectedContext ( null ) ; assertTrue ( sample . removed ) ; } public void testWithObject ( ) { OurExplorerContext explorerContext = new OurExplorerContext ( ) ; explorerContext . component = new Object ( ) ; JobAction test = new ExecuteAction ( ) ; test . setSelectedContext ( explorerContext ) ; test . prepare ( ) ; assertFalse ( test . isEnabled ( ) ) ; } } package org . oddjob . monitor . action ; import junit . framework . TestCase ; import org . oddjob . Loadable ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; public class UnloadActionTest extends TestCase { private class OurLoadable implements Loadable { boolean loadable = false ; public boolean isLoadable ( ) { return loadable ; } public void load ( ) { throw new RuntimeException ( "" ) ; } @ Override public void unload ( ) { setLoadable ( true ) ; } void setLoadable ( boolean loadable ) { this . loadable = loadable ; } } class OurEContext extends MockExplorerContext { OurLoadable loadable = new OurLoadable ( ) ; @ Override public Object getThisComponent ( ) { return loadable ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) { @ Override public void run ( Runnable runnable , String description ) { runnable . run ( ) ; } } ; } } public void testCycle ( ) throws Exception { UnloadAction test = new UnloadAction ( ) ; assertFalse ( test . isEnabled ( ) ) ; assertFalse ( test . isVisible ( ) ) ; OurEContext eContext = new OurEContext ( ) ; test . setSelectedContext ( eContext ) ; assertTrue ( test . isEnabled ( ) ) ; assertTrue ( test . isVisible ( ) ) ; assertFalse ( eContext . loadable . loadable ) ; test . action ( ) ; test . setSelectedContext ( eContext ) ; test . prepare ( ) ; assertTrue ( eContext . loadable . loadable ) ; assertFalse ( test . isEnabled ( ) ) ; assertTrue ( test . isVisible ( ) ) ; test . setSelectedContext ( null ) ; } } package org . oddjob . monitor . action ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . MockConfigurationOwner ; import org . oddjob . arooa . parsing . MockConfigurationSession ; import org . oddjob . arooa . parsing . QTag ; import org . oddjob . arooa . standard . StandardArooaDescriptor ; import org . oddjob . designer . view . DummyDialogue ; import org . oddjob . designer . view . DummyFormViewFactory ; import org . oddjob . designer . view . SelectionWidget ; import org . oddjob . designer . view . TextWidget ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextInialiser ; import org . oddjob . monitor . model . MockExplorerContext ; public class SetPropertyActionTest extends TestCase { class RootContext extends MockExplorerContext { @ Override public ExplorerContext getParent ( ) { return null ; } } public void testRootContext ( ) { SetPropertyAction test = new SetPropertyAction ( ) ; test . setSelectedContext ( new RootContext ( ) ) ; test . prepare ( ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; test . setSelectedContext ( null ) ; assertFalse ( test . isVisible ( ) ) ; assertFalse ( test . isEnabled ( ) ) ; } private class ParentContext extends MockExplorerContext { StandardArooaDescriptor descriptor = new StandardArooaDescriptor ( ) ; @ Override public Object getValue ( String key ) { assertEquals ( ConfigContextInialiser . CONFIG_OWNER , key ) ; return new MockConfigurationOwner ( ) { public ConfigurationSession provideConfigurationSession ( ) { return new MockConfigurationSession ( ) { @ Override public ArooaDescriptor getArooaDescriptor ( ) { return descriptor ; } } ; } } ; } } class OurExplorerContext extends MockExplorerContext { Object component ; @ Override public Object getThisComponent ( ) { return component ; } @ Override public ExplorerContext getParent ( ) { return new ParentContext ( ) ; } } public static class Component { String fruit ; public void setFruit ( String fruit ) { this . fruit = fruit ; } } public void testSetProperty ( ) throws Exception { Component component = new Component ( ) ; SetPropertyAction test = new SetPropertyAction ( ) ; assertFalse ( test . isEnabled ( ) ) ; assertFalse ( test . isVisible ( ) ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = component ; test . setSelectedContext ( ec ) ; test . prepare ( ) ; assertTrue ( test . isEnabled ( ) ) ; Form form = test . form ( ) ; DummyDialogue dv = DummyFormViewFactory . create ( form ) . dialogue ( ) ; ( ( TextWidget ) dv . get ( "" ) ) . setText ( "" ) ; SelectionWidget selection = ( SelectionWidget ) dv . get ( "" ) ; DesignInstance value = selection . setSelected ( new QTag ( "" ) ) ; DummyDialogue valueDialog = DummyFormViewFactory . create ( value . detail ( ) ) . dialogue ( ) ; ( ( TextWidget ) valueDialog . get ( null ) ) . setText ( "" ) ; test . action ( ) ; assertEquals ( "" , component . fruit ) ; } } package org . oddjob . monitor . action ; import java . util . concurrent . Callable ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . view . SwingFormFactory ; import org . oddjob . arooa . design . view . SwingFormView ; import org . oddjob . arooa . design . view . ValueDialog ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . ConfigContextInialiser ; import org . oddjob . monitor . model . MockExplorerContext ; public class AddJobActionTest extends TestCase { ConfigurationOwner configOwner ; private class ParentContext extends MockExplorerContext { @ Override public Object getValue ( String key ) { assertEquals ( ConfigContextInialiser . CONFIG_OWNER , key ) ; return configOwner ; } } private class OurExplorerContext extends MockExplorerContext { Object component ; ParentContext parent = new ParentContext ( ) ; @ Override public Object getThisComponent ( ) { return component ; } @ Override public ExplorerContext getParent ( ) { return parent ; } } XMLConfiguration config ; AddJobAction test = new AddJobAction ( ) ; SwingFormView view ; public void testAll ( ) { String xml = "" + "" + "" + "" + "" ; config = new XMLConfiguration ( "" , xml ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( config ) ; oddjob . run ( ) ; Object sequentialJob = new OddjobLookup ( oddjob ) . lookup ( "" ) ; OurExplorerContext explorerContext = new OurExplorerContext ( ) ; configOwner = oddjob ; explorerContext . component = sequentialJob ; test . setSelectedContext ( explorerContext ) ; test . prepare ( ) ; assertTrue ( test . isEnabled ( ) ) ; Form form = test . form ( ) ; assertNotNull ( form ) ; view = SwingFormFactory . create ( form ) ; assertNotNull ( view ) ; } public static void main ( String ... args ) throws Exception { final AddJobActionTest test = new AddJobActionTest ( ) ; test . testAll ( ) ; test . config . setSaveHandler ( new XMLConfiguration . SaveHandler ( ) { @ Override public void acceptXML ( String xml ) { System . out . println ( xml ) ; } } ) ; ValueDialog dialog = new ValueDialog ( test . view . dialog ( ) , new Callable < Boolean > ( ) { @ Override public Boolean call ( ) throws Exception { test . test . action ( ) ; test . configOwner . provideConfigurationSession ( ) . save ( ) ; return true ; } } ) ; dialog . showDialog ( null ) ; } } package org . oddjob . monitor . action ; import junit . framework . TestCase ; import org . oddjob . Resetable ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; public class HardResetActionTest extends TestCase { class OurExplorerContext extends MockExplorerContext { Object component ; @ Override public Object getThisComponent ( ) { return component ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) { @ Override public void run ( Runnable runnable , String description ) { runnable . run ( ) ; } } ; } } public void testPerform ( ) throws Exception { class MyR implements Resetable { boolean reset = false ; public boolean softReset ( ) { throw new RuntimeException ( "" ) ; } public boolean hardReset ( ) { reset = true ; return true ; } } MyR sample = new MyR ( ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = sample ; JobAction test = new HardResetAction ( ) ; test . setSelectedContext ( ec ) ; test . action ( ) ; assertTrue ( sample . reset ) ; } public void testWithObject ( ) { OurExplorerContext eContext = new OurExplorerContext ( ) ; eContext . component = new Object ( ) ; JobAction test = new HardResetAction ( ) ; test . setSelectedContext ( eContext ) ; test . prepare ( ) ; assertFalse ( test . isEnabled ( ) ) ; } } package org . oddjob . monitor . action ; import junit . framework . TestCase ; import org . oddjob . Resetable ; import org . oddjob . monitor . model . JobAction ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . util . MockThreadManager ; import org . oddjob . util . ThreadManager ; public class SoftResetActionTest extends TestCase { class OurExplorerContext extends MockExplorerContext { Object component ; @ Override public Object getThisComponent ( ) { return component ; } @ Override public ThreadManager getThreadManager ( ) { return new MockThreadManager ( ) { @ Override public void run ( Runnable runnable , String description ) { runnable . run ( ) ; } } ; } } public void testPerform ( ) throws Exception { class MyR implements Resetable { boolean reset = false ; public boolean softReset ( ) { reset = true ; return true ; } public boolean hardReset ( ) { throw new RuntimeException ( "" ) ; } } MyR sample = new MyR ( ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = sample ; JobAction test = new SoftResetAction ( ) ; test . setSelectedContext ( ec ) ; test . action ( ) ; assertTrue ( sample . reset ) ; } public void testWithObject ( ) { OurExplorerContext ec = new OurExplorerContext ( ) ; ec . component = new Object ( ) ; JobAction test = new SoftResetAction ( ) ; test . setSelectedContext ( ec ) ; test . prepare ( ) ; assertFalse ( test . isEnabled ( ) ) ; } } package org . oddjob . monitor . control ; import java . awt . Component ; import java . util . concurrent . atomic . AtomicReference ; import javax . swing . JFrame ; import javax . swing . JTree ; import javax . swing . SwingUtilities ; import javax . swing . WindowConstants ; import javax . swing . tree . TreePath ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . model . DetailModel ; import org . oddjob . monitor . model . JobTreeModel ; import org . oddjob . monitor . model . JobTreeNode ; import org . oddjob . monitor . model . MockExplorerModel ; import org . oddjob . monitor . view . DetailView ; import org . oddjob . util . ThreadManager ; public class DetailControllerTest extends TestCase { Component comp ; class OurExplorerModel extends MockExplorerModel { Oddjob oddjob ; @ Override public Oddjob getOddjob ( ) { return oddjob ; } @ Override public ThreadManager getThreadManager ( ) { return null ; } @ Override public ContextInitialiser [ ] getContextInitialisers ( ) { return new ContextInitialiser [ ] ; } } public void testSelectionOnCut ( ) throws Exception { OurExplorerModel explorerModel = new OurExplorerModel ( ) ; Oddjob oddjob = new Oddjob ( ) ; String xml = "" + "" + "" + "" + "" ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; explorerModel . oddjob = oddjob ; JobTreeModel model = new JobTreeModel ( ) ; JobTreeNode root = new JobTreeNode ( explorerModel , model ) ; model . setRootTreeNode ( root ) ; final JTree tree = new JTree ( model ) ; tree . setShowsRootHandles ( true ) ; DetailModel detailModel = new DetailModel ( ) ; DetailController test = new DetailController ( detailModel , new DetailView ( detailModel ) ) ; tree . addTreeSelectionListener ( test ) ; root . setVisible ( true ) ; assertNull ( detailModel . getSelectedJob ( ) ) ; assertEquals ( false , tree . isExpanded ( ) ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { tree . expandRow ( ) ; tree . setSelectionRow ( ) ; } } ) ; Object x = detailModel . getSelectedJob ( ) ; assertNotNull ( x ) ; final DragPoint xDrag = oddjob . provideConfigurationSession ( ) . dragPointFor ( x ) ; final AtomicReference < Exception > er = new AtomicReference < Exception > ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { DragTransaction trn = xDrag . beginChange ( ChangeHow . FRESH ) ; xDrag . cut ( ) ; try { trn . commit ( ) ; } catch ( ArooaParseException e ) { trn . rollback ( ) ; er . set ( e ) ; } } } ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { } } ) ; if ( er . get ( ) != null ) { throw er . get ( ) ; } TreePath path = tree . getSelectionPath ( ) ; assertNull ( path ) ; assertNull ( detailModel . getSelectedJob ( ) ) ; assertEquals ( false , tree . isExpanded ( ) ) ; comp = tree ; } public static void main ( String [ ] args ) throws Exception { DetailControllerTest test = new DetailControllerTest ( ) ; test . testSelectionOnCut ( ) ; JFrame frame = new JFrame ( ) ; frame . setDefaultCloseOperation ( WindowConstants . DISPOSE_ON_CLOSE ) ; frame . getContentPane ( ) . add ( test . comp ) ; frame . pack ( ) ; frame . setVisible ( true ) ; } } package org . oddjob . monitor . control ; import java . util . Map ; import junit . framework . TestCase ; import org . oddjob . Stateful ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . monitor . model . DetailModel ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . monitor . model . PropertyModel ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class PropertyPollingTest extends TestCase { private class OurExplorerContext extends MockExplorerContext { @ Override public Object getThisComponent ( ) { return new Comp ( ) ; } } public static class Comp { public String getFruit ( ) { return "" ; } } public void testSelected ( ) { ArooaSession session = new StandardArooaSession ( ) ; PropertyModel model = new PropertyModel ( ) ; PropertyPolling test = new PropertyPolling ( this , session ) ; test . setPropertyModel ( model ) ; DetailModel detailModel = new DetailModel ( ) ; detailModel . addPropertyChangeListener ( test ) ; detailModel . setTabSelected ( DetailModel . PROPERTIES_TAB ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; detailModel . setSelectedContext ( ec ) ; test . poll ( ) ; String result = ( String ) model . getProperties ( ) . get ( "" ) ; assertEquals ( "" , result ) ; } public void testNotSelected ( ) { ArooaSession session = new StandardArooaSession ( ) ; PropertyModel model = new PropertyModel ( ) ; PropertyPolling test = new PropertyPolling ( this , session ) ; test . setPropertyModel ( model ) ; DetailModel detailModel = new DetailModel ( ) ; detailModel . addPropertyChangeListener ( test ) ; OurExplorerContext ec = new OurExplorerContext ( ) ; detailModel . setSelectedContext ( ec ) ; test . poll ( ) ; Map < String , String > props = model . getProperties ( ) ; assertEquals ( , props . size ( ) ) ; } public class OurStateful implements Stateful { private StateListener listener ; @ Override public void addStateListener ( StateListener listener ) { assertNotNull ( listener ) ; assertNull ( this . listener ) ; this . listener = listener ; } @ Override public StateEvent lastStateEvent ( ) { throw new RuntimeException ( "" ) ; } @ Override public void removeStateListener ( StateListener listener ) { assertNotNull ( listener ) ; assertSame ( this . listener , listener ) ; this . listener = null ; } } private class OurExplorerContext2 extends MockExplorerContext { OurStateful stateful = new OurStateful ( ) ; @ Override public Object getThisComponent ( ) { return stateful ; } } public void testSelectedStateful ( ) { ArooaSession session = new StandardArooaSession ( ) ; PropertyModel model = new PropertyModel ( ) ; PropertyPolling test = new PropertyPolling ( this , session ) ; test . setPropertyModel ( model ) ; DetailModel detailModel = new DetailModel ( ) ; detailModel . addPropertyChangeListener ( test ) ; detailModel . setTabSelected ( DetailModel . PROPERTIES_TAB ) ; OurExplorerContext2 ec = new OurExplorerContext2 ( ) ; detailModel . setSelectedContext ( ec ) ; assertNotNull ( ec . stateful . listener ) ; ec . stateful . listener . jobStateChange ( new StateEvent ( ec . stateful , JobState . COMPLETE ) ) ; detailModel . setSelectedContext ( null ) ; assertNull ( ec . stateful . listener ) ; } } package org . oddjob . monitor . control ; import java . awt . Component ; import java . awt . Toolkit ; import java . lang . reflect . InvocationTargetException ; import java . util . concurrent . atomic . AtomicReference ; import javax . swing . ImageIcon ; import javax . swing . JFrame ; import javax . swing . JTree ; import javax . swing . SwingUtilities ; import javax . swing . WindowConstants ; import javax . swing . tree . TreePath ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconListener ; import org . oddjob . monitor . context . ContextInitialiser ; import org . oddjob . monitor . model . JobTreeModel ; import org . oddjob . monitor . model . JobTreeNode ; import org . oddjob . monitor . model . MockExplorerModel ; import org . oddjob . state . ParentState ; import org . oddjob . util . ThreadManager ; public class NodeControlTest extends TestCase { Component comp ; class OurExplorerModel extends MockExplorerModel { Oddjob oddjob ; @ Override public Oddjob getOddjob ( ) { return oddjob ; } @ Override public ThreadManager getThreadManager ( ) { return null ; } @ Override public ContextInitialiser [ ] getContextInitialisers ( ) { return new ContextInitialiser [ ] ; } } public static class OurIconic extends SimpleJob { String icon = "" ; IconListener listener ; @ Override protected int execute ( ) throws Throwable { return ; } public void addIconListener ( IconListener listener ) { if ( this . listener != null ) { throw new RuntimeException ( "" ) ; } this . listener = listener ; listener . iconEvent ( new IconEvent ( this , "" ) ) ; } public ImageIcon iconForId ( String id ) { assertEquals ( "" , id ) ; return new ImageIcon ( new byte [ ] , "" ) ; } public void removeIconListener ( IconListener listener ) { assertEquals ( this . listener , listener ) ; this . listener = null ; } } public void testIconsOKonOddjobStart ( ) throws InterruptedException , InvocationTargetException { OurExplorerModel explorerModel = new OurExplorerModel ( ) ; Oddjob oddjob = new Oddjob ( ) ; String xml = "" + "" + "" + OurIconic . class . getName ( ) + "" + "" + "" ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; explorerModel . oddjob = oddjob ; JobTreeModel model = new JobTreeModel ( ) ; JobTreeNode root = new JobTreeNode ( explorerModel , model ) ; model . setRootTreeNode ( root ) ; final JTree tree = new JTree ( model ) ; tree . setShowsRootHandles ( true ) ; NodeControl test = new NodeControl ( ) ; root . setVisible ( true ) ; tree . addTreeWillExpandListener ( test ) ; assertEquals ( false , tree . isExpanded ( ) ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { tree . expandRow ( ) ; } } ) ; TreePath path = tree . getPathForRow ( ) ; JobTreeNode result = ( JobTreeNode ) path . getLastPathComponent ( ) ; assertEquals ( "" , result . getIcon ( ) . getDescription ( ) ) ; this . comp = tree ; } public void testIconListenerRemovedFromCutNode ( ) throws Exception { OurExplorerModel explorerModel = new OurExplorerModel ( ) ; final Oddjob oddjob = new Oddjob ( ) ; explorerModel . oddjob = oddjob ; JobTreeModel model = new JobTreeModel ( ) ; JobTreeNode root = new JobTreeNode ( explorerModel , model ) ; model . setRootTreeNode ( root ) ; root . setVisible ( true ) ; JTree tree = new JTree ( model ) ; NodeControl test = new NodeControl ( ) ; tree . addTreeWillExpandListener ( test ) ; String xml = "" + "" + "" + OurIconic . class . getName ( ) + "" + "" + "" ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; Toolkit . getDefaultToolkit ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { oddjob . run ( ) ; } } ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { } } ) ; assertEquals ( false , tree . isExpanded ( ) ) ; tree . expandRow ( ) ; TreePath path = tree . getPathForRow ( ) ; JobTreeNode result = ( JobTreeNode ) path . getLastPathComponent ( ) ; assertEquals ( "" , result . getIcon ( ) . getDescription ( ) ) ; OurIconic component = ( OurIconic ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; final DragPoint drag = oddjob . provideConfigurationSession ( ) . dragPointFor ( component ) ; final AtomicReference < Exception > er = new AtomicReference < Exception > ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { DragTransaction trn = drag . beginChange ( ChangeHow . FRESH ) ; drag . cut ( ) ; try { trn . commit ( ) ; } catch ( ArooaParseException e ) { trn . rollback ( ) ; er . set ( e ) ; } } } ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { } } ) ; if ( er . get ( ) != null ) { throw er . get ( ) ; } assertEquals ( null , component . listener ) ; this . comp = tree ; } public void testPasteIntoAnAlreadyExpandedNode ( ) throws InterruptedException , InvocationTargetException { OurExplorerModel explorerModel = new OurExplorerModel ( ) ; final Oddjob oddjob = new Oddjob ( ) ; explorerModel . oddjob = oddjob ; JobTreeModel model = new JobTreeModel ( ) ; JobTreeNode root = new JobTreeNode ( explorerModel , model ) ; model . setRootTreeNode ( root ) ; root . setVisible ( true ) ; JTree tree = new JTree ( model ) ; tree . setShowsRootHandles ( true ) ; NodeControl test = new NodeControl ( ) ; tree . addTreeWillExpandListener ( test ) ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; Toolkit . getDefaultToolkit ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { oddjob . run ( ) ; } } ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { } } ) ; tree . expandRow ( ) ; tree . expandRow ( ) ; Object seqential = new OddjobLookup ( oddjob ) . lookup ( "" ) ; final DragPoint drag = oddjob . provideConfigurationSession ( ) . dragPointFor ( seqential ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { try { DragTransaction trn = drag . beginChange ( ChangeHow . FRESH ) ; drag . paste ( , "" + OurIconic . class . getName ( ) + "" ) ; trn . commit ( ) ; } catch ( ArooaParseException e ) { throw new RuntimeException ( e ) ; } } } ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { public void run ( ) { } } ) ; TreePath path = tree . getPathForRow ( ) ; JobTreeNode result = ( JobTreeNode ) path . getLastPathComponent ( ) ; assertEquals ( "" , result . getIcon ( ) . getDescription ( ) ) ; this . comp = tree ; } public static void main ( String [ ] args ) throws Exception { NodeControlTest test = new NodeControlTest ( ) ; test . testPasteIntoAnAlreadyExpandedNode ( ) ; JFrame frame = new JFrame ( ) ; frame . setDefaultCloseOperation ( WindowConstants . DISPOSE_ON_CLOSE ) ; frame . getContentPane ( ) . add ( test . comp ) ; frame . pack ( ) ; frame . setVisible ( true ) ; } } package org . oddjob . values ; import java . util . concurrent . BlockingQueue ; import java . util . concurrent . LinkedBlockingQueue ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ValueQueueServiceTest extends TestCase { public void testQueueWithTwoConsumers ( ) throws InterruptedException { final BlockingQueue < Object > results = new LinkedBlockingQueue < Object > ( ) ; final ValueQueueService test = new ValueQueueService ( ) ; class Puller implements Runnable { @ Override public void run ( ) { for ( Object value : test . getValues ( ) ) { results . add ( value ) ; } } } test . start ( ) ; Thread t1 = new Thread ( new Puller ( ) ) ; Thread t2 = new Thread ( new Puller ( ) ) ; t1 . start ( ) ; t2 . start ( ) ; test . setValue ( "" ) ; assertEquals ( "" , results . take ( ) ) ; test . setValue ( "" ) ; assertEquals ( "" , results . take ( ) ) ; test . stop ( ) ; t1 . join ( ) ; t2 . join ( ) ; } public void testInOddjobWithFor ( ) throws FailedToStopException , InterruptedException { Oddjob server = new Oddjob ( ) ; server . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; server . load ( ) ; OddjobLookup lookup = new OddjobLookup ( server ) ; Object jobs = lookup . lookup ( "" ) ; StateSteps serverState = new StateSteps ( ( Stateful ) jobs ) ; serverState . startCheck ( ParentState . READY , ParentState . EXECUTING ) ; Thread t = new Thread ( server ) ; t . start ( ) ; serverState . checkWait ( ) ; Oddjob client1 = new Oddjob ( ) ; client1 . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; client1 . setArgs ( new String [ ] { "" } ) ; client1 . run ( ) ; assertEquals ( ParentState . COMPLETE , client1 . lastStateEvent ( ) . getState ( ) ) ; client1 . destroy ( ) ; Oddjob client2 = new Oddjob ( ) ; client2 . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; client2 . setArgs ( new String [ ] { "" } ) ; client2 . run ( ) ; assertEquals ( ParentState . COMPLETE , client2 . lastStateEvent ( ) . getState ( ) ) ; client2 . destroy ( ) ; Object foreach = lookup . lookup ( "" ) ; assertEquals ( , Helper . getChildren ( foreach ) . length ) ; server . stop ( ) ; t . join ( ) ; server . destroy ( ) ; } } package org . oddjob . values ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . DynaProperty ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . MockArooaBeanDescriptor ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . ParsingInterceptor ; import org . oddjob . arooa . deploy . NoAnnotations ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . arooa . standard . StandardTools ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; public class SetJobTest extends TestCase { public static class SimpleBean { String prop ; public void setProp ( String prop ) { this . prop = prop ; } } private class OurSession extends MockArooaSession { Object bean ; @ Override public BeanRegistry getBeanRegistry ( ) { return new MockBeanRegistry ( ) { @ Override public Object lookup ( String path ) { assertEquals ( "" , path ) ; return bean ; } } ; } @ Override public ComponentPool getComponentPool ( ) { return new MockComponentPool ( ) { @ Override public void configure ( Object component ) { } @ Override public void save ( Object component ) throws ComponentPersistException { } } ; } @ Override public ArooaTools getTools ( ) { return new StandardTools ( ) ; } } public void testSetValue ( ) { final SimpleBean obj = new SimpleBean ( ) ; OurSession session = new OurSession ( ) ; session . bean = obj ; SetJob test = new SetJob ( ) ; test . setArooaSession ( session ) ; ValueType value = new ValueType ( ) ; value . setValue ( new ArooaObject ( "" ) ) ; test . setValues ( "" , value ) ; test . run ( ) ; assertEquals ( "" , obj . prop ) ; } public void testBasic ( ) { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getResourceAsStream ( "" ) ) ) ; oj . run ( ) ; CheckBasicSetters check = ( CheckBasicSetters ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( check ) ; assertEquals ( "" , JobState . COMPLETE , Helper . getJobState ( check ) ) ; } public static class MappedPropertyBean { private Map < String , Object > map = new HashMap < String , Object > ( ) ; public void setMapped ( String name , Object value ) { map . put ( name , value ) ; } public Object getMapped ( String name ) { return map . get ( name ) ; } } public void testSetMapped ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + MappedPropertyBean . class . getName ( ) + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; Object o = new OddjobLookup ( oddjob ) . lookup ( "" ) ; MappedPropertyBean b = ( MappedPropertyBean ) o ; assertEquals ( b . getMapped ( "" ) , "" ) ; } static class MockDynaClass implements DynaClass { DynaProperty id = new DynaProperty ( "" , String . class ) ; DynaProperty simple = new DynaProperty ( "" , String . class ) ; DynaProperty indexed = new DynaProperty ( "" , String [ ] . class , String . class ) ; DynaProperty mapped = new DynaProperty ( "" , Map . class , String . class ) ; public DynaProperty [ ] getDynaProperties ( ) { return new DynaProperty [ ] { id , simple , indexed , mapped } ; } public DynaProperty getDynaProperty ( String name ) { if ( ( "" ) . equals ( name ) ) { return id ; } if ( ( "" ) . equals ( name ) ) { return simple ; } if ( ( "" ) . equals ( name ) ) { return indexed ; } if ( ( "" ) . equals ( name ) ) { return mapped ; } return null ; } public String getName ( ) { return toString ( ) ; } public DynaBean newInstance ( ) throws IllegalAccessException , InstantiationException { throw new RuntimeException ( "" ) ; } } public static class MockDynaBean implements DynaBean { String simple ; Map < String , Object > mapped = new HashMap < String , Object > ( ) ; String [ ] indexed = new String [ ] ; DynaClass dynaClass = new MockDynaClass ( ) ; public boolean contains ( String name , String key ) { throw new RuntimeException ( "" ) ; } public Object get ( String name ) { throw new RuntimeException ( "" ) ; } public Object get ( String name , int index ) { throw new RuntimeException ( "" ) ; } public Object get ( String name , String key ) { throw new RuntimeException ( "" ) ; } public DynaClass getDynaClass ( ) { return dynaClass ; } public void remove ( String name , String key ) { throw new RuntimeException ( "" ) ; } public void set ( String name , int index , Object value ) { if ( ! "" . equals ( name ) ) { throw new RuntimeException ( "" ) ; } indexed [ index ] = ( String ) value ; } public void set ( String name , Object value ) { if ( "" . equals ( name ) ) { return ; } if ( ! "" . equals ( name ) ) { throw new RuntimeException ( "" ) ; } simple = ( String ) value ; } public void set ( String name , String key , Object value ) { if ( ! "" . equals ( name ) ) { throw new RuntimeException ( "" ) ; } mapped . put ( key , value ) ; } } public static class MockDynaBeanArooa extends MockArooaBeanDescriptor { @ Override public ParsingInterceptor getParsingInterceptor ( ) { return null ; } @ Override public ConfiguredHow getConfiguredHow ( String property ) { assertEquals ( "" , property ) ; return ConfiguredHow . ATTRIBUTE ; } @ Override public String getComponentProperty ( ) { return null ; } @ Override public ArooaAnnotations getAnnotations ( ) { return new NoAnnotations ( ) ; } } public void testSetDynaBean ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + MockDynaBean . class . getName ( ) + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; Object o = new OddjobLookup ( oddjob ) . lookup ( "" ) ; MockDynaBean b = ( MockDynaBean ) o ; assertEquals ( b . simple , "" ) ; assertEquals ( b . indexed [ ] , "" ) ; assertEquals ( b . mapped . get ( "" ) , "" ) ; } } package org . oddjob . values . types ; import java . text . ParseException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Oddjob ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class TokenizerTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( TokenizerTypeTest . class ) ; public void testSimpelCSV ( ) throws ParseException { TokenizerType test = new TokenizerType ( ) ; test . setText ( "" ) ; String [ ] result = test . parse ( ) ; assertEquals ( "" , result [ ] ) ; assertEquals ( "" , result [ ] ) ; assertEquals ( "" , result [ ] ) ; } public void testExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } } package org . oddjob . values . types ; import java . text . ParseException ; import java . util . Date ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConverterHelper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; public class FormatTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( FormatTypeTest . class ) ; @ Override protected void tearDown ( ) throws Exception { TimeZone . setDefault ( null ) ; } public void testLocalDate ( ) throws Exception { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; Date date = DateHelper . parseDateTime ( "" ) ; FormatType ft = new FormatType ( ) ; ft . setDate ( date ) ; ft . setFormat ( "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; String result = converter . convert ( ft , String . class ) ; assertEquals ( "" , result ) ; } public void testTimeZoneDate ( ) throws Exception { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; Date date = DateHelper . parseDateTime ( "" , "" ) ; logger . debug ( date ) ; FormatType ft = new FormatType ( ) ; ft . setDate ( date ) ; ft . setFormat ( "" ) ; ft . setTimeZone ( "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; String result = converter . convert ( ft , String . class ) ; assertEquals ( "" , result ) ; } public void testNumberFormat ( ) throws Exception { FormatType ft = new FormatType ( ) ; ft . setNumber ( new Integer ( ) ) ; ft . setFormat ( "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; String result = converter . convert ( ft , String . class ) ; assertEquals ( "" , result ) ; } public void testInOddjob ( ) throws ArooaConversionException , ParseException { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; String result = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , result ) ; } } package org . oddjob . values . types ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . oddjob . ConverterHelper ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . standard . StandardArooaSession ; public class PropertyTypeTest extends TestCase { public void testValueForString ( ) throws Exception { PropertyType test = new PropertyType ( ) ; test . set ( "" , "" ) ; Object result = test . get ( "" ) ; assertNotNull ( result ) ; assertEquals ( PropertyType . class , result . getClass ( ) ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; assertEquals ( "" , converter . convert ( result , String . class ) ) ; } public void testAddingNull ( ) throws Exception { ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; PropertyType p = new PropertyType ( ) ; PropertyUtils . setProperty ( p , "" , null ) ; String value = converter . convert ( PropertyUtils . getProperty ( p , "" ) , String . class ) ; assertEquals ( null , value ) ; value = converter . convert ( PropertyUtils . getProperty ( p , "" ) , String . class ) ; assertEquals ( null , value ) ; Properties props = p . toProperties ( ) ; assertEquals ( , props . size ( ) ) ; } public void testAddingNestedPropertyFails ( ) throws Exception { PropertyType p = new PropertyType ( ) ; PropertyUtils . setProperty ( p , "" , "" ) ; PropertyType result = ( PropertyType ) PropertyUtils . getProperty ( p , "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; assertEquals ( "" , converter . convert ( result , String . class ) ) ; } public void testSettingProperties ( ) throws Exception { PropertyType p = new PropertyType ( ) ; PropertyUtils . setProperty ( p , "" , null ) ; PropertyUtils . setProperty ( p , "" , "" ) ; PropertyUtils . setProperty ( p , "" , "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; assertEquals ( "" , converter . convert ( PropertyUtils . getProperty ( p , "" ) , String . class ) ) ; assertEquals ( "" , converter . convert ( PropertyUtils . getProperty ( p , "" ) , String . class ) ) ; } public void testGetProperties ( ) throws Exception { PropertyType p = new PropertyType ( ) ; PropertyUtils . setProperty ( p , "" , null ) ; PropertyUtils . setProperty ( p , "" , "" ) ; PropertyUtils . setProperty ( p , "" , "" ) ; Properties result = new Properties ( ) ; p . properties ( result , "" ) ; assertEquals ( "" , result . get ( "" ) ) ; assertEquals ( "" , result . get ( "" ) ) ; } public void getPropertyType ( ) throws Exception { PropertyType test = new PropertyType ( ) ; Class < ? > type = PropertyUtils . getPropertyType ( test , "" ) ; assertEquals ( String . class , type ) ; } public void testUsingBeanUtilsBeanHelper ( ) throws Exception { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; ArooaSession session = new StandardArooaSession ( descriptor ) ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; PropertyType test = new PropertyType ( ) ; PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; accessor . setProperty ( test , "" , "" ) ; PropertyUtils . setProperty ( test , "" , "" ) ; PropertyType result = ( PropertyType ) accessor . getProperty ( test , "" ) ; Properties props = result . toProperties ( ) ; assertEquals ( "" , props . getProperty ( "" ) ) ; assertEquals ( "" , props . getProperty ( "" ) ) ; PropertyType result2 = ( PropertyType ) accessor . getProperty ( result , "" ) ; assertEquals ( "" , converter . convert ( result2 , String . class ) ) ; } public void testSerialize ( ) throws Exception { PropertyType p = new PropertyType ( ) ; PropertyUtils . setProperty ( p , "" , "" ) ; PropertyUtils . setProperty ( p , "" , "" ) ; PropertyType copy = Helper . copy ( p ) ; Properties results = copy . toProperties ( ) ; assertEquals ( "" , results . getProperty ( "" ) ) ; assertEquals ( "" , results . getProperty ( "" ) ) ; } } package org . oddjob . values . types ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . ConverterHelper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; public class DateTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( DateTypeTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testConversions ( ) throws Exception { DateType dt = new DateType ( ) ; dt . setDate ( "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; Date date = converter . convert ( dt , Date . class ) ; assertEquals ( "" , new SimpleDateFormat ( "" ) . parse ( "" ) , date ) ; Calendar calendar = converter . convert ( dt , Calendar . class ) ; Calendar expectedCal = Calendar . getInstance ( ) ; expectedCal . clear ( ) ; expectedCal . set ( , , ) ; assertEquals ( "" , expectedCal , calendar ) ; String string = converter . convert ( dt , String . class ) ; assertEquals ( "" , DateHelper . formatDateTime ( DateHelper . parseDate ( "" ) ) , string ) ; } public void testTimeZone ( ) throws Exception { DateType dt = new DateType ( ) ; dt . setDate ( "" ) ; dt . setTimeZone ( "" ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; Calendar calendar = converter . convert ( dt , Calendar . class ) ; Calendar expectedCal = Calendar . getInstance ( TimeZone . getTimeZone ( "" ) ) ; expectedCal . clear ( ) ; expectedCal . set ( , , ) ; assertEquals ( expectedCal . getTime ( ) , calendar . getTime ( ) ) ; } public void testInOddjob ( ) throws ArooaConversionException , ParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Date result = new OddjobLookup ( oj ) . lookup ( "" , Date . class ) ; assertEquals ( DateHelper . parseDate ( "" ) , result ) ; Date result2 = new OddjobLookup ( oj ) . lookup ( "" , Date . class ) ; assertEquals ( DateHelper . parseDate ( "" , TimeZone . getTimeZone ( "" ) ) , result2 ) ; } public void testInvalidTimeZone ( ) throws ParseException { DateType test = new DateType ( ) ; test . setDate ( "" ) ; test . setFormat ( "" ) ; test . setTimeZone ( "" ) ; Date result = test . toDate ( ) ; assertEquals ( DateHelper . parseDate ( "" , "" ) , result ) ; } public void testSimpleDateExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; DateType date = ( DateType ) parser . getRoot ( ) ; Date expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , date . toDate ( ) ) ; } public void testFormatExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; DateType date = ( DateType ) parser . getRoot ( ) ; Date expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , date . toDate ( ) ) ; } public void testDateTimezoneExample ( ) throws ParseException { logger . debug ( TimeZone . getDefault ( ) ) ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oj . run ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; Date there = DateHelper . parseDateTime ( "" , "" ) ; assertEquals ( "" + DateHelper . formatDateTime ( there ) + "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oj . destroy ( ) ; } } package org . oddjob . values ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . ElementMappings ; import org . oddjob . arooa . beandocs . MappingsContents ; import org . oddjob . arooa . beanutils . BeanUtilsPropertyAccessor ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class VariablesJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( VariablesJobTest . class ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } public void testSimple ( ) throws Exception { ValueType vt = new ValueType ( ) ; vt . setValue ( new ArooaObject ( "" ) ) ; VariablesJob test = new VariablesJob ( ) ; PropertyUtils . setProperty ( test , "" , vt ) ; PropertyUtils . setProperty ( test , "" , vt ) ; ArooaValue result = ( ArooaValue ) PropertyUtils . getProperty ( test , "" ) ; assertNotNull ( result ) ; Map < String , String > description = new UniversalDescriber ( new StandardArooaSession ( ) ) . describe ( test ) ; assertTrue ( description . containsKey ( "" ) ) ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; ArooaSession session = new StandardArooaSession ( descriptor ) ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; assertEquals ( "" , converter . convert ( result , Object . class ) ) ; assertTrue ( test . hardReset ( ) ) ; assertNull ( PropertyUtils . getProperty ( test , "" ) ) ; description = new UniversalDescriber ( new StandardArooaSession ( ) ) . describe ( test ) ; assertFalse ( description . containsKey ( "" ) ) ; } public void testTypesForSetting ( ) { ArooaDescriptor descriptor = new VariablesJobDescriptorFactory ( ) . createDescriptor ( null ) ; InstantiationContext instantiationContext = new InstantiationContext ( ArooaType . COMPONENT , null ) ; ArooaClass arooaClass = descriptor . getElementMappings ( ) . mappingFor ( new ArooaElement ( "" ) , instantiationContext ) ; VariablesJob vj = ( VariablesJob ) arooaClass . newInstance ( ) ; vj . set ( "" , new ValueType ( ) ) ; PropertyAccessor propertyAccessor = new BeanUtilsPropertyAccessor ( ) ; BeanOverview beanOverview = arooaClass . getBeanOverview ( propertyAccessor ) ; assertEquals ( ArooaValue . class , beanOverview . getPropertyType ( "" ) ) ; assertEquals ( ArooaValue . class , beanOverview . getPropertyType ( "" ) ) ; } public static class SessionCapture implements ArooaSessionAware { ArooaSession arooaSession ; public void setArooaSession ( ArooaSession session ) { this . arooaSession = session ; } public ArooaSession getArooaSession ( ) { return arooaSession ; } } public void testArooaDescriptor ( ) throws ArooaConversionException { String xml = "" + "" + "" + SessionCapture . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; ArooaSession session = new OddjobLookup ( oddjob ) . lookup ( "" , ArooaSession . class ) ; InstantiationContext instantiationContext = new InstantiationContext ( ArooaType . COMPONENT , null ) ; ArooaClass classId = session . getArooaDescriptor ( ) . getElementMappings ( ) . mappingFor ( VariablesJobDescriptorFactory . VARIABLES , instantiationContext ) ; ArooaBeanDescriptor beanDescriptor = session . getArooaDescriptor ( ) . getBeanDescriptor ( classId , session . getTools ( ) . getPropertyAccessor ( ) ) ; assertEquals ( ConfiguredHow . ELEMENT , beanDescriptor . getConfiguredHow ( "" ) ) ; assertEquals ( ConfiguredHow . ATTRIBUTE , beanDescriptor . getConfiguredHow ( "" ) ) ; Object instance = classId . newInstance ( ) ; assertEquals ( VariablesJob . class , instance . getClass ( ) ) ; } public void testDescriptorBeanDoc ( ) { VariablesJobDescriptorFactory test = new VariablesJobDescriptorFactory ( ) ; ArooaDescriptor descriptor = test . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; ElementMappings mappings = descriptor . getElementMappings ( ) ; MappingsContents contents = mappings . getBeanDoc ( ArooaType . COMPONENT ) ; ArooaElement [ ] elements = contents . allElements ( ) ; assertEquals ( , elements . length ) ; assertEquals ( VariablesJobDescriptorFactory . VARIABLES , elements [ ] ) ; ArooaClass arooaClass = contents . documentClass ( elements [ ] ) ; BeanOverview overview = arooaClass . getBeanOverview ( new BeanUtilsPropertyAccessor ( ) ) ; String [ ] properties = overview . getProperties ( ) ; assertEquals ( , properties . length ) ; } public void testGetValues ( ) throws Exception { PropertyAccessor propertyAccessor = new BeanUtilsPropertyAccessor ( ) ; SimpleBeanRegistry cr = new SimpleBeanRegistry ( ) ; VariablesJob j = new VariablesJob ( ) ; cr . register ( "" , j ) ; propertyAccessor . setSimpleProperty ( j , "" , new Boolean ( true ) ) ; propertyAccessor . setSimpleProperty ( j , "" , new Short ( ( short ) ) ) ; Object o1 = cr . lookup ( "" ) ; Object r1 = new DefaultConverter ( ) . convert ( o1 , Boolean . TYPE ) ; assertEquals ( Boolean . class , r1 . getClass ( ) ) ; assertEquals ( new Boolean ( true ) , r1 ) ; Object o2 = cr . lookup ( "" ) ; Object r2 = new DefaultConverter ( ) . convert ( o2 , Short . TYPE ) ; assertEquals ( Short . class , r2 . getClass ( ) ) ; assertEquals ( new Short ( ( short ) ) , r2 ) ; } public void testNullValue ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; DynaBean b = ( DynaBean ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( b ) ; ValueType result = ( ValueType ) b . get ( "" ) ; assertNotNull ( result ) ; assertNull ( result . getValue ( ) ) ; } public void testSelfUse ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , new OddjobLookup ( oj ) . lookup ( "" , String . class ) ) ; oj . destroy ( ) ; } public void testInOddjob ( ) { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getResourceAsStream ( "" ) ) ) ; oj . run ( ) ; CheckBasicSetters check = ( CheckBasicSetters ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( "" , JobState . COMPLETE , Helper . getJobState ( check ) ) ; } public void testExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } } package org . oddjob . values . properties ; import junit . framework . TestCase ; public class EnvVarPropertyLookupTest extends TestCase { public void testLookup ( ) { EnvVarPropertyLookup test = new EnvVarPropertyLookup ( "" ) ; String path = test . lookup ( "" ) ; assertNotNull ( path ) ; path = test . lookup ( "" ) ; assertNotNull ( path ) ; path = test . lookup ( "" ) ; assertNotNull ( path ) ; } } package org . oddjob . values . properties ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . values . properties . PropertiesJob ; public class PropertiesJobDesFaTest extends TestCase { DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; PropertiesJob test = ( PropertiesJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getEnvironment ( ) ) ; test . run ( ) ; assertEquals ( "" , test . getProperties ( ) . get ( "" ) ) ; assertEquals ( "" , test . getProperties ( ) . get ( "" ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { PropertiesJobDesFaTest test = new PropertiesJobDesFaTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . values . properties ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . xml . XMLConfiguration ; public class PropertiesJobSystemTest extends TestCase { private static final Logger logger = Logger . getLogger ( PropertiesJobSystemTest . class ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; if ( System . getProperty ( "" ) != null ) { throw new IllegalStateException ( "" ) ; } System . setProperty ( "" , "" ) ; } @ Override protected void tearDown ( ) throws Exception { System . getProperties ( ) . remove ( "" ) ; } public void testSystemPropertyInOddjob ( ) throws Exception { String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String result = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , result ) ; oj . destroy ( ) ; } public void testSettingAllInOddjob ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oj ) ; String result = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , result ) ; assertEquals ( "" , lookup . lookup ( "" ) ) ; oj . destroy ( ) ; } } package org . oddjob . values . properties ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Describeable ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . arooa . xml . XMLConfiguration ; public class PropertiesEnvironmentTest extends TestCase { private static final Logger logger = Logger . getLogger ( PropertiesEnvironmentTest . class ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } public void testInOddjob ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object echo = lookup . lookup ( "" ) ; ( ( Runnable ) echo ) . run ( ) ; String text = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , text ) ; ( ( Resetable ) echo ) . hardReset ( ) ; oddjob . run ( ) ; text = lookup . lookup ( "" , String . class ) ; assertEquals ( "" + System . getenv ( "" ) , text ) ; Object test = lookup . lookup ( "" ) ; Map < String , String > description = ( ( Describeable ) test ) . describe ( ) ; assertTrue ( description . size ( ) > ) ; ( ( Resetable ) test ) . hardReset ( ) ; ( ( Resetable ) echo ) . hardReset ( ) ; ( ( Runnable ) echo ) . run ( ) ; text = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , text ) ; oddjob . destroy ( ) ; } } package org . oddjob . values . properties ; import java . io . IOException ; import java . util . Map ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . persist . MapPersister ; import org . oddjob . state . JobState ; public class PropertiesJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( PropertiesJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; } public void testSimpleSetGet ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; Resetable properties = lookup . lookup ( "" , Resetable . class ) ; properties . hardReset ( ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( null , lookup . lookup ( "" ) ) ; oddjob . destroy ( ) ; } public void testPropertiesFromValues ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; oddjob . destroy ( ) ; } public void testSetFromInput ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; oddjob . destroy ( ) ; } public static class MyComp extends SimpleJob { Properties props ; public void setProps ( Properties props ) { this . props = props ; } @ Override protected int execute ( ) throws Throwable { return ; } } public void testSetPropertiesFromFile ( ) { OurDirs dirs = new OurDirs ( ) ; String xml = "" + "" + "" + "" + "" + "" + "" + dirs . base ( ) + "" + "" + "" + "" + MyComp . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; MyComp myComp = ( MyComp ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertNotNull ( myComp ) ; assertEquals ( "" , myComp . props . get ( "" ) ) ; } public void testSetFromPrevious ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + MyComp . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; MyComp myComp = ( MyComp ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertNotNull ( myComp ) ; assertEquals ( "" , myComp . props . get ( "" ) ) ; } public void testSettingSelfFromPrevious ( ) throws ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; Properties properties = lookup . lookup ( "" , Properties . class ) ; assertEquals ( , properties . size ( ) ) ; assertEquals ( "" , properties . getProperty ( "" ) ) ; assertEquals ( "" , properties . getProperty ( "" ) ) ; assertEquals ( "" , properties . getProperty ( "" ) ) ; assertEquals ( "" , properties . getProperty ( "" ) ) ; oddjob . destroy ( ) ; } public void testMergeFiles ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String result = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , result ) ; oj . destroy ( ) ; } public void testSerialzation ( ) throws IOException , ClassNotFoundException , ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; MapPersister persister = new MapPersister ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setPersister ( persister ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful test1 = lookup . lookup ( "" , Stateful . class ) ; assertEquals ( JobState . COMPLETE , test1 . lastStateEvent ( ) . getState ( ) ) ; String r1 = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , r1 ) ; Oddjob second = new Oddjob ( ) ; second . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; second . setPersister ( persister ) ; second . load ( ) ; lookup = new OddjobLookup ( second ) ; Stateful test2 = lookup . lookup ( "" , Stateful . class ) ; assertEquals ( JobState . COMPLETE , test2 . lastStateEvent ( ) . getState ( ) ) ; String r2 = lookup . lookup ( "" , String . class ) ; assertNull ( "" , r2 ) ; Runnable vars = lookup . lookup ( "" , Runnable . class ) ; vars . run ( ) ; String r3 = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , r3 ) ; oddjob . destroy ( ) ; } public void testOverridingProperties ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; oddjob . destroy ( ) ; } public void testDescribeable ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; PropertiesJob props1 = lookup . lookup ( "" , PropertiesJob . class ) ; PropertiesJob props2 = lookup . lookup ( "" , PropertiesJob . class ) ; PropertiesJob props3 = lookup . lookup ( "" , PropertiesJob . class ) ; Map < String , String > description1 ; Map < String , String > description2 ; Map < String , String > description3 ; description1 = props1 . describe ( ) ; description2 = props2 . describe ( ) ; description3 = props3 . describe ( ) ; assertEquals ( , description1 . size ( ) ) ; assertEquals ( , description2 . size ( ) ) ; assertEquals ( , description3 . size ( ) ) ; props1 . run ( ) ; description1 = props1 . describe ( ) ; description2 = props2 . describe ( ) ; description3 = props3 . describe ( ) ; assertEquals ( , description1 . size ( ) ) ; assertEquals ( , description2 . size ( ) ) ; assertEquals ( , description3 . size ( ) ) ; assertEquals ( "" , description1 . get ( "" ) ) ; props2 . run ( ) ; description1 = props1 . describe ( ) ; description2 = props2 . describe ( ) ; description3 = props3 . describe ( ) ; assertEquals ( , description1 . size ( ) ) ; assertEquals ( , description2 . size ( ) ) ; assertEquals ( , description3 . size ( ) ) ; assertEquals ( "" , description1 . get ( "" ) ) ; assertEquals ( "" , description2 . get ( "" ) ) ; props1 . hardReset ( ) ; description1 = props1 . describe ( ) ; description2 = props2 . describe ( ) ; description3 = props3 . describe ( ) ; assertEquals ( , description1 . size ( ) ) ; assertEquals ( , description2 . size ( ) ) ; assertEquals ( , description3 . size ( ) ) ; assertEquals ( "" , description2 . get ( "" ) ) ; props3 . run ( ) ; description1 = props1 . describe ( ) ; description2 = props2 . describe ( ) ; description3 = props3 . describe ( ) ; assertEquals ( , description1 . size ( ) ) ; assertEquals ( , description2 . size ( ) ) ; assertEquals ( , description3 . size ( ) ) ; assertEquals ( "" , description2 . get ( "" ) ) ; assertEquals ( "" , description3 . get ( "" ) ) ; props1 . run ( ) ; props3 . hardReset ( ) ; description1 = props1 . describe ( ) ; description2 = props2 . describe ( ) ; description3 = props3 . describe ( ) ; assertEquals ( , description1 . size ( ) ) ; assertEquals ( , description2 . size ( ) ) ; assertEquals ( , description3 . size ( ) ) ; assertEquals ( "" , description1 . get ( "" ) ) ; assertEquals ( "" , description2 . get ( "" ) ) ; oddjob . destroy ( ) ; } public void testDescribeAll ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; System . setProperty ( "" , "" ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; PropertiesJob props1 = lookup . lookup ( "" , PropertiesJob . class ) ; PropertiesJob props2 = lookup . lookup ( "" , PropertiesJob . class ) ; Map < String , String > description1 ; Map < String , String > description2 ; description1 = props1 . describe ( ) ; description2 = props2 . describe ( ) ; assertEquals ( , description1 . size ( ) ) ; assertTrue ( description2 . size ( ) > ) ; assertEquals ( "" , description2 . get ( "" ) ) ; assertEquals ( "" , description2 . get ( "" ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . values . properties ; import java . io . IOException ; import java . util . Properties ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; public class PropertiesTypeTest extends TestCase { public void testSimpleSetGet ( ) throws Exception { PropertiesType test = new PropertiesType ( ) ; test . setValues ( "" , "" ) ; Properties results = test . toProperties ( ) ; assertEquals ( "" , results . getProperty ( "" ) ) ; assertEquals ( "" , results . get ( "" ) ) ; } public static class MyComp extends SimpleJob { Properties props ; public void setProps ( Properties props ) { this . props = props ; } @ Override protected int execute ( ) throws Throwable { return ; } } public void testSetInOddjob ( ) { String xml = "" + "" + "" + MyComp . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; MyComp myComp = ( MyComp ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( myComp ) ; assertEquals ( "" , myComp . props . get ( "" ) ) ; } public static class ThingWithGetters { public Long getLong ( ) { return new Long ( ) ; } } public void testNonStringValue ( ) throws IOException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + ThingWithGetters . class . getName ( ) + "" + "" + MyComp . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; MyComp myComp = ( MyComp ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( myComp ) ; assertEquals ( "" , myComp . props . getProperty ( "" ) ) ; } public void testMerge ( ) { String xml = "" + "" + "" + MyComp . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; MyComp myComp = ( MyComp ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( myComp ) ; assertEquals ( "" , myComp . props . get ( "" ) ) ; assertEquals ( "" , myComp . props . get ( "" ) ) ; } public void testMergeFiles ( ) { String xml = "" + "" + "" + MyComp . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; MyComp myComp = ( MyComp ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( myComp ) ; assertEquals ( "" , myComp . props . get ( "" ) ) ; assertEquals ( "" , myComp . props . get ( "" ) ) ; } public void testExtractAndPrefix ( ) throws IOException , ArooaConversionException { Properties props = new Properties ( ) ; props . setProperty ( "" , "" ) ; props . setProperty ( "" , "" ) ; PropertiesType test = new PropertiesType ( ) ; test . setExtract ( "" ) ; test . setPrefix ( "" ) ; test . setSets ( , props ) ; Properties results = test . toProperties ( ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . getProperty ( "" ) ) ; } public void testNullValue ( ) throws IOException , ArooaConversionException { PropertiesType test = new PropertiesType ( ) ; test . setValues ( "" , null ) ; Properties results = test . toProperties ( ) ; assertEquals ( , results . size ( ) ) ; } } package org . oddjob . values ; import java . text . SimpleDateFormat ; import java . util . Date ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . framework . SimpleJob ; public class CheckBasicSetters extends SimpleJob { boolean checkBoolean ; byte checkByte ; char checkChar ; Date checkDate ; double checkDouble ; float checkFloat ; int checkInt ; long checkLong ; short checkShort ; String checkString ; public int execute ( ) { if ( checkBoolean != true ) { throw new IllegalStateException ( "" ) ; } if ( checkByte != ) { throw new IllegalStateException ( "" ) ; } if ( checkChar != '' ) { throw new IllegalStateException ( "" ) ; } if ( ! new SimpleDateFormat ( "" ) . format ( checkDate ) . equals ( "" ) ) { throw new IllegalStateException ( "" ) ; } if ( checkDouble != ) { throw new IllegalStateException ( "" ) ; } if ( checkFloat != ) { throw new IllegalStateException ( "" ) ; } if ( checkInt != ) { throw new IllegalStateException ( "" ) ; } if ( checkLong != ) { throw new IllegalStateException ( "" ) ; } if ( checkShort != ) { throw new IllegalStateException ( "" ) ; } if ( ! checkString . equals ( "" ) ) { throw new IllegalStateException ( "" ) ; } return ; } public void setCheckBoolean ( boolean checkBoolean ) { this . checkBoolean = checkBoolean ; } public void setCheckByte ( byte checkByte ) { this . checkByte = checkByte ; } public void setCheckChar ( char checkChar ) { this . checkChar = checkChar ; } @ ArooaAttribute public void setCheckDate ( Date checkDate ) { this . checkDate = checkDate ; } public void setCheckDouble ( double checkDouble ) { this . checkDouble = checkDouble ; } public void setCheckFloat ( float checkFloat ) { this . checkFloat = checkFloat ; } public void setCheckInt ( int checkInt ) { this . checkInt = checkInt ; } public void setCheckLong ( long checkLong ) { this . checkLong = checkLong ; } public void setCheckShort ( short checkShort ) { this . checkShort = checkShort ; } public void setCheckString ( String checkString ) { this . checkString = checkString ; } } package org . oddjob ; public class MockRunnable implements Runnable { public void run ( ) { System . out . println ( "" ) ; } } package org . oddjob . jmx ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import junit . framework . TestCase ; public class StatefulTest extends TestCase { class Result implements StateListener { StateEvent event ; public void jobStateChange ( StateEvent event ) { this . event = event ; synchronized ( this ) { notifyAll ( ) ; } } } public void testState ( ) throws ArooaConversionException , InterruptedException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; String address = new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( address ) ; client . run ( ) ; RemoteDirectory remote = client . provideBeanDirectory ( ) ; Stateful fruit = ( Stateful ) remote . lookup ( "" , Stateful . class ) ; assertNotNull ( fruit ) ; Result result = new Result ( ) ; fruit . addStateListener ( result ) ; assertEquals ( JobState . COMPLETE , result . event . getState ( ) ) ; Resetable resetable = ( Resetable ) fruit ; resetable . hardReset ( ) ; synchronized ( result ) { result . wait ( ) ; } assertEquals ( JobState . READY , result . event . getState ( ) ) ; client . destroy ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . jmx ; import java . util . HashMap ; import java . util . Map ; import javax . management . MBeanServerConnection ; import javax . management . remote . JMXConnector ; import javax . management . remote . JMXConnectorFactory ; import javax . management . remote . JMXServiceURL ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . WaitJob ; import org . oddjob . state . IsNotExecuting ; import org . oddjob . state . ParentState ; import org . oddjob . state . State ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class JMXServerJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( JMXServerJobTest . class ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } int unique ; Map < Object , String > ids = new HashMap < Object , String > ( ) ; private class OurEmptyRegistrySession extends StandardArooaSession { @ Override public BeanRegistry getBeanRegistry ( ) { return new MockBeanRegistry ( ) { @ Override public String getIdFor ( Object component ) { assertNotNull ( component ) ; String id = ids . get ( component ) ; if ( id == null ) { id = "" + unique ++ ; ids . put ( component , id ) ; } return id ; } } ; } } public void testServerMBeans ( ) throws Exception { Object root = new Object ( ) { public String toString ( ) { return "" ; } } ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( root ) ; server . setArooaSession ( new StandardArooaSession ( ) ) ; server . setUrl ( "" ) ; server . start ( ) ; JMXServiceURL address = new JMXServiceURL ( server . getAddress ( ) ) ; JMXConnector cntor = JMXConnectorFactory . connect ( address ) ; MBeanServerConnection mBeanServer = cntor . getMBeanServerConnection ( ) ; assertEquals ( new Integer ( ) , mBeanServer . getMBeanCount ( ) ) ; cntor . close ( ) ; server . stop ( ) ; } public void testRun ( ) throws Exception { Object root = new Object ( ) { public String toString ( ) { return "" ; } } ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( root ) ; server . setArooaSession ( new StandardArooaSession ( ) ) ; server . setUrl ( "" ) ; server . start ( ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setConnection ( server . getAddress ( ) ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . run ( ) ; Object [ ] children = Helper . getChildren ( client ) ; assertEquals ( , children . length ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; client . stop ( ) ; server . stop ( ) ; } public static class Component { public String getFruit ( ) { return "" ; } } private class OurSession extends StandardArooaSession { SimpleBeanRegistry registry = new SimpleBeanRegistry ( ) ; @ Override public BeanRegistry getBeanRegistry ( ) { return registry ; } } public void testLinkedServers ( ) throws Exception { ArooaSession server2Session = new OurSession ( ) ; Component comp1 = new Component ( ) ; server2Session . getBeanRegistry ( ) . register ( "" , comp1 ) ; JMXServerJob server2 = new JMXServerJob ( ) ; server2 . setRoot ( comp1 ) ; server2 . setArooaSession ( server2Session ) ; server2 . setUrl ( "" ) ; server2 . start ( ) ; OurSession server1Session = new OurSession ( ) ; JMXClientJob client = new JMXClientJob ( ) ; server1Session . registry . register ( "" , client ) ; client . setArooaSession ( server1Session ) ; client . setConnection ( server2 . getAddress ( ) ) ; client . run ( ) ; JMXServerJob server1 = new JMXServerJob ( ) ; server1 . setRoot ( client ) ; server1 . setUrl ( "" ) ; server1 . setArooaSession ( new OurEmptyRegistrySession ( ) ) ; server1 . start ( ) ; Object o = server1Session . registry . lookup ( "" ) ; assertNotNull ( o ) ; DynaBean db = ( DynaBean ) o ; assertEquals ( "" , db . get ( "" ) ) ; client . stop ( ) ; server1 . stop ( ) ; server2 . stop ( ) ; } public void testNestedOddjob ( ) throws Exception { String EOL = System . getProperty ( "" ) ; final String xml = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; final Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertNotNull ( new OddjobLookup ( oj ) . lookup ( "" ) ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( ( String ) new OddjobLookup ( oj ) . lookup ( "" ) ) ; client . run ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Object o = new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( o ) ; while ( new OddjobLookup ( client ) . lookup ( "" ) == null ) { try { Thread . sleep ( ) ; } catch ( Exception e ) { } Thread . yield ( ) ; } assertNotNull ( "" , new OddjobLookup ( client ) . lookup ( "" ) . toString ( ) ) ; client . stop ( ) ; oj . stop ( ) ; } private class MyFolder implements Structural { final int level ; final int number ; final BeanRegistry registry ; MyFolder ( int number , int level , BeanRegistry registry ) { this . number = number ; this . level = level ; this . registry = registry ; registry . register ( "" + unique ++ , this ) ; } ChildHelper < MyFolder > childHelper = new ChildHelper < MyFolder > ( this ) ; public void addStructuralListener ( StructuralListener listener ) { childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } private void addChildren ( final int number , final int levels , final int level ) { if ( levels == ) { return ; } for ( int i = ; i < number ; ++ i ) { final MyFolder child = new MyFolder ( i , level , registry ) ; childHelper . insertChild ( i , child ) ; child . addChildren ( number , levels - , level + ) ; } } void addChildren ( int number , int levels ) { addChildren ( number , levels , level ) ; } void removeChildren ( ) { for ( MyFolder child : childHelper . getChildren ( new MyFolder [ ] ) ) { child . removeChildren ( ) ; } childHelper . removeAllChildren ( ) ; } public String toString ( ) { return ( "" + number + "" + level + "" ) ; } } public void testLotsOfStructural ( ) throws Exception { OurSession session = new OurSession ( ) ; MyFolder folder = new MyFolder ( , , session . registry ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( folder ) ; server . setUrl ( "" ) ; server . setArooaSession ( session ) ; server . start ( ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( server . getAddress ( ) ) ; client . run ( ) ; Object proxy = ChildHelper . getChildren ( client ) [ ] ; folder . addChildren ( , ) ; WaitForChildren w = new WaitForChildren ( proxy ) ; w . waitFor ( ) ; folder . removeChildren ( ) ; w . waitFor ( ) ; client . stop ( ) ; server . stop ( ) ; } public void testDestroyServer ( ) throws Exception { OurSession session = new OurSession ( ) ; MyFolder folder = new MyFolder ( , , session . registry ) ; folder . addChildren ( , ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( folder ) ; server . setUrl ( "" ) ; server . setArooaSession ( session ) ; server . start ( ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( server . getAddress ( ) ) ; client . run ( ) ; Object proxy = ChildHelper . getChildren ( client ) [ ] ; WaitForChildren w = new WaitForChildren ( proxy ) ; w . waitFor ( ) ; server . stop ( ) ; WaitJob wj = new WaitJob ( ) ; wj . setState ( new IsNotExecuting ( ) ) ; wj . setFor ( client ) ; wj . run ( ) ; State last = client . lastStateEvent ( ) . getState ( ) ; if ( last . isIncomplete ( ) ) { } else if ( last . isException ( ) ) { } else { fail ( "" + client . lastStateEvent ( ) . getState ( ) ) ; } } public void testBounceOddjob ( ) throws Exception { String EOL = System . getProperty ( "" ) ; final String xml = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Oddjob innerOddjob = ( Oddjob ) new OddjobLookup ( oj ) . lookup ( "" ) ; innerOddjob . hardReset ( ) ; innerOddjob . run ( ) ; oj . stop ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . jmx ; import javax . swing . ImageIcon ; import junit . framework . TestCase ; import org . oddjob . Iconic ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; public class IconicTest extends TestCase { class Result implements IconListener { IconEvent event ; public void iconEvent ( IconEvent e ) { this . event = e ; synchronized ( this ) { notifyAll ( ) ; } } } public void testState ( ) throws ArooaConversionException , InterruptedException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; String address = new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( address ) ; client . run ( ) ; RemoteDirectory remote = client . provideBeanDirectory ( ) ; Iconic fruit = ( Iconic ) remote . lookup ( "" , Iconic . class ) ; assertNotNull ( fruit ) ; Result result = new Result ( ) ; fruit . addIconListener ( result ) ; String iconId = result . event . getIconId ( ) ; assertEquals ( IconHelper . COMPLETE , iconId ) ; ImageIcon tip = fruit . iconForId ( iconId ) ; assertEquals ( "" , tip . getDescription ( ) ) ; Resetable resetable = ( Resetable ) fruit ; resetable . hardReset ( ) ; synchronized ( result ) { result . wait ( ) ; } assertEquals ( IconHelper . READY , result . event . getIconId ( ) ) ; client . destroy ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . jmx ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaProperty ; import org . oddjob . framework . WrapDynaClass ; public class WrapDynaClassTest extends TestCase { public class Bean { public String getFruit ( ) { return "" ; } } public void testSerialize ( ) throws IOException , ClassNotFoundException { WrapDynaClass dc = WrapDynaClass . createDynaClass ( Bean . class ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( out ) ; oos . writeObject ( dc ) ; ByteArrayInputStream in = new ByteArrayInputStream ( out . toByteArray ( ) ) ; ObjectInputStream ois = new ObjectInputStream ( in ) ; WrapDynaClass dc2 = ( WrapDynaClass ) ois . readObject ( ) ; Map < String , Class < ? > > props = new HashMap < String , Class < ? > > ( ) ; DynaProperty [ ] dps = dc2 . getDynaProperties ( ) ; for ( int i = ; i < dps . length ; ++ i ) { props . put ( dps [ i ] . getName ( ) , dps [ i ] . getType ( ) ) ; } assertEquals ( String . class , props . get ( "" ) ) ; } } package org . oddjob . jmx ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; import org . oddjob . arooa . types . XMLConfigurationType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogListener ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . scheduling . TrackingServices ; import org . oddjob . state . ParentState ; import org . oddjob . values . VariablesJob ; public class TogetherTest extends TestCase { private static final Logger logger = Logger . getLogger ( TogetherTest . class ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } String EOL = System . getProperty ( "" ) ; public void testMultipleClientServers ( ) throws NoConversionAvailableException , ConversionFailedException , Exception { DefaultExecutors services = new DefaultExecutors ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setOddjobExecutors ( services ) ; oj . setConfiguration ( new XMLConfiguration ( "" , this . getClass ( ) . getResourceAsStream ( "" ) ) ) ; oj . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oj ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; class LL implements LogListener { String message ; public void logEvent ( LogEvent logEvent ) { message = logEvent . getMessage ( ) ; } } ConsoleArchiver archiver1 = ( ConsoleArchiver ) new OddjobLookup ( oj ) . lookup ( "" ) ; Object fruit1 = new OddjobLookup ( oj ) . lookup ( "" ) ; LL results1 = new LL ( ) ; archiver1 . addConsoleListener ( results1 , fruit1 , - , ) ; assertEquals ( "" + EOL , results1 . message ) ; archiver1 . removeConsoleListener ( results1 , fruit1 ) ; ConsoleArchiver archiver2 = ( ConsoleArchiver ) new OddjobLookup ( oj ) . lookup ( "" ) ; Object fruit2 = new OddjobLookup ( oj ) . lookup ( "" ) ; LL results2 = new LL ( ) ; archiver2 . addConsoleListener ( results2 , fruit2 , - , ) ; assertEquals ( "" + EOL , results2 . message ) ; archiver2 . removeConsoleListener ( results2 , fruit2 ) ; Runnable stopAll = ( Runnable ) new OddjobLookup ( oj ) . lookup ( "" ) ; stopAll . run ( ) ; oj . destroy ( ) ; services . stop ( ) ; } public void test2 ( ) throws Exception { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , this . getClass ( ) . getResourceAsStream ( "" ) ) ) ; oj . run ( ) ; VariablesJob result = ( VariablesJob ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( result ) ; Object o = new DefaultConverter ( ) . convert ( result . get ( "" ) , Object . class ) ; assertEquals ( "" , o ) ; } public void testServingNestedOddjob ( ) throws Exception { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; XMLConfigurationType configType = new XMLConfigurationType ( ) ; configType . setResource ( "" ) ; oj . setExport ( "" , configType ) ; oj . run ( ) ; VariablesJob result = ( VariablesJob ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( result ) ; Object o = new DefaultConverter ( ) . convert ( result . get ( "" ) , Object . class ) ; assertEquals ( "" , o ) ; } public void testClientServerLoopback ( ) throws Exception { TrackingServices services = new TrackingServices ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setOddjobExecutors ( services ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , this . getClass ( ) . getResourceAsStream ( "" ) ) ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; state . checkWait ( ) ; Object test1 = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( test1 , "" ) ) ; Object test2 = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( test2 , "" ) ) ; services . stop ( ) ; oddjob . destroy ( ) ; } public interface Foo { public String foo ( ) ; } public static class FooImpl implements Foo { public String foo ( ) { return "" ; } } public void testAnyInterface ( ) { String serverXml = "" + "" + "" + "" + "" + "" + "" + FooImpl . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + VanillaInterfaceHandler . class . getName ( ) + "" + Foo . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob serverOddjob = new Oddjob ( ) ; serverOddjob . setConfiguration ( new XMLConfiguration ( "" , serverXml ) ) ; serverOddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , serverOddjob . lastStateEvent ( ) . getState ( ) ) ; String serverAddress = ( String ) new OddjobLookup ( serverOddjob ) . lookup ( "" ) ; String clientXml = "" + "" + "" + "" + "" ; Oddjob clientOddjob = new Oddjob ( ) ; clientOddjob . setConfiguration ( new XMLConfiguration ( "" , clientXml ) ) ; clientOddjob . setArgs ( new String [ ] { serverAddress } ) ; clientOddjob . run ( ) ; Foo foo = ( Foo ) new OddjobLookup ( clientOddjob ) . lookup ( "" ) ; String result = foo . foo ( ) ; assertEquals ( "" , result ) ; clientOddjob . destroy ( ) ; serverOddjob . destroy ( ) ; } public void testForEachConfigurationOwner ( ) throws FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Object client = new OddjobLookup ( oddjob ) . lookup ( "" ) ; Object foreach = new OddjobLookup ( ( BeanDirectoryOwner ) client ) . lookup ( "" ) ; assertTrue ( foreach instanceof ConfigurationOwner ) ; ConfigurationSession configurationSession = ( ( ConfigurationOwner ) foreach ) . provideConfigurationSession ( ) ; assertNotNull ( configurationSession ) ; ArooaConfiguration config = configurationSession . dragPointFor ( foreach ) ; assertNotNull ( config ) ; ( ( Stoppable ) client ) . stop ( ) ; oddjob . stop ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . jmx ; import java . io . File ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . FragmentHelper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; public class JMXExamplesTest extends TestCase { private static final Logger logger = Logger . getLogger ( JMXExamplesTest . class ) ; Oddjob serverOddjob ; Oddjob clientOddjob ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } @ Override protected void tearDown ( ) throws Exception { super . tearDown ( ) ; if ( clientOddjob != null ) { clientOddjob . destroy ( ) ; } if ( serverOddjob != null ) { serverOddjob . destroy ( ) ; } } public void testSimpleClientServerExample ( ) throws ArooaParseException , FailedToStopException { Properties props = new Properties ( ) ; props . setProperty ( "" , "" ) ; OurDirs dirs = new OurDirs ( ) ; File testDir = dirs . relative ( "" ) ; serverOddjob = new Oddjob ( ) ; serverOddjob . setFile ( new File ( testDir , "" ) ) ; serverOddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , serverOddjob . lastStateEvent ( ) . getState ( ) ) ; FragmentHelper helper = new FragmentHelper ( ) ; helper . setProperties ( props ) ; JMXClientJob client = ( JMXClientJob ) helper . createComponentFromResource ( "" ) ; StateSteps clientSteps = new StateSteps ( client ) ; clientSteps . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; client . run ( ) ; clientSteps . checkNow ( ) ; client . stop ( ) ; } public void testClientRunsServerJobExample ( ) throws InterruptedException , ArooaPropertyException , ArooaConversionException { Properties props = new Properties ( ) ; props . setProperty ( "" , "" ) ; OurDirs dirs = new OurDirs ( ) ; File testDir = dirs . relative ( "" ) ; serverOddjob = new Oddjob ( ) ; serverOddjob . setProperties ( props ) ; serverOddjob . setFile ( new File ( testDir , "" ) ) ; serverOddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , serverOddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup serverLookup = new OddjobLookup ( serverOddjob ) ; Stateful serverJob = serverLookup . lookup ( "" , Stateful . class ) ; clientOddjob = new Oddjob ( ) ; clientOddjob . setProperties ( props ) ; clientOddjob . setFile ( new File ( testDir , "" ) ) ; StateSteps steps = new StateSteps ( serverJob ) ; steps . startCheck ( JobState . READY , JobState . EXECUTING , JobState . COMPLETE ) ; clientOddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , clientOddjob . lastStateEvent ( ) . getState ( ) ) ; steps . checkWait ( ) ; } public void testClientTriggersOnServerJobExample ( ) throws InterruptedException , ArooaPropertyException , ArooaConversionException { Properties props = new Properties ( ) ; props . setProperty ( "" , "" ) ; OurDirs dirs = new OurDirs ( ) ; File testDir = dirs . relative ( "" ) ; serverOddjob = new Oddjob ( ) ; serverOddjob . setProperties ( props ) ; serverOddjob . setFile ( new File ( testDir , "" ) ) ; serverOddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , serverOddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup serverLookup = new OddjobLookup ( serverOddjob ) ; Runnable serverJob = serverLookup . lookup ( "" , Runnable . class ) ; clientOddjob = new Oddjob ( ) ; clientOddjob . setProperties ( props ) ; clientOddjob . setFile ( new File ( testDir , "" ) ) ; clientOddjob . run ( ) ; OddjobLookup clientLookup = new OddjobLookup ( clientOddjob ) ; Stateful localJob = clientLookup . lookup ( "" , Stateful . class ) ; assertEquals ( ParentState . ACTIVE , clientOddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , localJob . lastStateEvent ( ) . getState ( ) ) ; StateSteps state = new StateSteps ( clientOddjob ) ; state . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; serverJob . run ( ) ; state . checkWait ( ) ; } } package org . oddjob . jmx ; import java . util . concurrent . atomic . AtomicReference ; import org . custommonkey . xmlunit . XMLTestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . CutAndPasteSupport ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ServerDragTest extends XMLTestCase { XMLConfiguration configuration = new XMLConfiguration ( "" , "" + "" + "" + "" + "" ) ; final AtomicReference < String > savedXML = new AtomicReference < String > ( ) ; { configuration . setSaveHandler ( new XMLConfiguration . SaveHandler ( ) { @ Override public void acceptXML ( String xml ) { savedXML . set ( xml ) ; } } ) ; } JMXServerJob server ; JMXClientJob client ; ConfigurationOwner remoteOddjob ; class OurContext extends MockArooaContext { ArooaSession session ; public OurContext ( ArooaSession session ) { this . session = session ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void configure ( ) { } } ; } @ Override public ArooaSession getSession ( ) { return session ; } } @ Override protected void setUp ( ) throws Exception { ArooaSession serverSession = new OddjobSessionFactory ( ) . createSession ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( configuration ) ; ComponentPool serverPool = serverSession . getComponentPool ( ) ; serverPool . registerComponent ( new ComponentTrinity ( oddjob , oddjob , new OurContext ( serverSession ) ) , "" ) ; oddjob . setArooaSession ( serverSession ) ; oddjob . run ( ) ; server = new JMXServerJob ( ) ; server . setArooaSession ( serverSession ) ; server . setUrl ( "" ) ; server . setRoot ( oddjob ) ; server . start ( ) ; ArooaSession clientSession = new StandardArooaSession ( ) ; client = new JMXClientJob ( ) ; client . setConnection ( server . getAddress ( ) ) ; client . setArooaSession ( clientSession ) ; ComponentPool clientPool = clientSession . getComponentPool ( ) ; clientPool . registerComponent ( new ComponentTrinity ( client , client , new OurContext ( clientSession ) ) , null ) ; client . run ( ) ; remoteOddjob = ( ConfigurationOwner ) new OddjobLookup ( client ) . lookup ( "" ) ; } @ Override protected void tearDown ( ) throws Exception { client . stop ( ) ; server . stop ( ) ; } String EOL = System . getProperty ( "" ) ; public void testCutLeaf ( ) throws Exception { assertNotNull ( remoteOddjob ) ; Object toCut = new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( toCut ) ; DragPoint dragPoint = remoteOddjob . provideConfigurationSession ( ) . dragPointFor ( toCut ) ; DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; dragPoint . cut ( ) ; trn . commit ( ) ; remoteOddjob . provideConfigurationSession ( ) . save ( ) ; String expected = "" + EOL ; assertXMLEqual ( expected , savedXML . get ( ) ) ; } public void testEditRoot ( ) throws Exception { assertNotNull ( remoteOddjob ) ; Object toEdit = new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( toEdit ) ; DragPoint dragPoint = remoteOddjob . provideConfigurationSession ( ) . dragPointFor ( toEdit ) ; XMLArooaParser parser = new XMLArooaParser ( ) ; ConfigurationHandle handle = parser . parse ( dragPoint ) ; String replacement = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; CutAndPasteSupport . replace ( handle . getDocumentContext ( ) . getParent ( ) , handle . getDocumentContext ( ) , new XMLConfiguration ( "" , replacement ) ) ; handle . save ( ) ; assertNull ( savedXML . get ( ) ) ; remoteOddjob . provideConfigurationSession ( ) . save ( ) ; assertXMLEqual ( replacement , savedXML . get ( ) ) ; } public void testPaste ( ) throws Exception { testCutLeaf ( ) ; Object pastePoint = new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( pastePoint ) ; DragPoint dragPoint = remoteOddjob . provideConfigurationSession ( ) . dragPointFor ( pastePoint ) ; String paste = "" ; DragTransaction trn = dragPoint . beginChange ( ChangeHow . FRESH ) ; dragPoint . paste ( , paste ) ; trn . commit ( ) ; remoteOddjob . provideConfigurationSession ( ) . save ( ) ; String expected = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; assertXMLEqual ( expected , savedXML . get ( ) ) ; } public void testFailedPaste ( ) throws ArooaParseException { Object pastePoint = new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( pastePoint ) ; DragPoint dragPoint = remoteOddjob . provideConfigurationSession ( ) . dragPointFor ( pastePoint ) ; String paste = "" + "" ; try { dragPoint . paste ( , paste ) ; fail ( "" ) ; } catch ( Exception e ) { } } } package org . oddjob . jmx ; import java . net . MalformedURLException ; import javax . management . remote . JMXServiceURL ; import junit . framework . TestCase ; public class JMXServiceURLHelperTest extends TestCase { public void testFullURL ( ) throws MalformedURLException { JMXServiceURLHelper test = new JMXServiceURLHelper ( ) ; String url = "" ; JMXServiceURL result = test . parse ( url ) ; assertEquals ( url , result . toString ( ) ) ; } public void testClientJMXServiceURL ( ) throws MalformedURLException { JMXServiceURLHelper test = new JMXServiceURLHelper ( ) ; JMXServiceURL result ; result = test . parse ( "" ) ; assertEquals ( "" , result . toString ( ) ) ; result = test . parse ( "" ) ; assertEquals ( "" , result . toString ( ) ) ; result = test . parse ( "" ) ; assertEquals ( "" , result . toString ( ) ) ; result = test . parse ( "" ) ; assertEquals ( "" , result . toString ( ) ) ; } } package org . oddjob . jmx . general ; import static org . mockito . Mockito . * ; import java . util . Set ; import java . util . TreeSet ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanConstructorInfo ; import javax . management . MBeanInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanServerConnection ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . oddjob . arooa . life . ClassLoaderClassResolver ; public class MBeanCacheMapTest extends TestCase { public void testFindMany ( ) throws Exception { ObjectName objectName1 = new ObjectName ( "" ) ; ObjectName objectName2 = new ObjectName ( "" ) ; Set < ObjectName > objectNames = new TreeSet < ObjectName > ( ) ; objectNames . add ( objectName1 ) ; objectNames . add ( objectName2 ) ; MBeanInfo info = new MBeanInfo ( "" , "" , new MBeanAttributeInfo [ ] , new MBeanConstructorInfo [ ] , new MBeanOperationInfo [ ] , new MBeanNotificationInfo [ ] ) ; MBeanServerConnection mbsc = mock ( MBeanServerConnection . class ) ; when ( mbsc . queryNames ( new ObjectName ( "" ) , null ) ) . thenReturn ( objectNames ) ; when ( mbsc . getMBeanInfo ( any ( ObjectName . class ) ) ) . thenReturn ( info ) ; MBeanCacheMap test = new MBeanCacheMap ( mbsc , new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; Object [ ] object = test . findBeans ( new ObjectName ( "" ) ) ; assertEquals ( , object . length ) ; assertEquals ( "" , object [ ] . toString ( ) ) ; assertEquals ( "" , object [ ] . toString ( ) ) ; Object findAgain = test . findBean ( new ObjectName ( "" ) ) ; assertEquals ( object [ ] , findAgain ) ; } public void testFindOne ( ) throws Exception { ObjectName objectName = new ObjectName ( "" ) ; Set < ObjectName > objectNames = new TreeSet < ObjectName > ( ) ; objectNames . add ( objectName ) ; MBeanInfo info = new MBeanInfo ( "" , "" , new MBeanAttributeInfo [ ] , new MBeanConstructorInfo [ ] , new MBeanOperationInfo [ ] , new MBeanNotificationInfo [ ] ) ; MBeanServerConnection mbsc = mock ( MBeanServerConnection . class ) ; when ( mbsc . queryNames ( new ObjectName ( "" ) , null ) ) . thenReturn ( objectNames ) ; when ( mbsc . getMBeanInfo ( any ( ObjectName . class ) ) ) . thenReturn ( info ) ; MBeanCacheMap test = new MBeanCacheMap ( mbsc , new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; Object object = test . findBean ( new ObjectName ( "" ) ) ; assertEquals ( "" , object . toString ( ) ) ; Object findAgain = test . findBean ( new ObjectName ( "" ) ) ; assertEquals ( object , findAgain ) ; } } package org . oddjob . jmx . general ; import java . util . Date ; public interface VendorMBean { public double quote ( String fruit , Date delivery , int quantity ) ; public String getFarm ( ) ; public void setRating ( double rating ) ; public double getRating ( ) ; } package org . oddjob . jmx . general ; import java . lang . management . ManagementFactory ; import javax . management . MBeanServer ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . oddjob . arooa . beanutils . BeanUtilsPropertyAccessor ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . life . ClassLoaderClassResolver ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . log4j . Log4jArchiver ; import org . oddjob . script . ConvertableArguments ; import org . oddjob . script . InvokerArguments ; public class SimpleMBeanNodeTest extends TestCase { ObjectName objectName ; MBeanServer mBeanServer ; Vendor simple = new Vendor ( "" ) ; protected void setUp ( ) throws Exception { objectName = new ObjectName ( "" ) ; mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; mBeanServer . registerMBean ( simple , objectName ) ; } @ Override protected void tearDown ( ) throws Exception { mBeanServer . unregisterMBean ( objectName ) ; } public void testInvoking ( ) throws Exception { SimpleMBeanNode test = new SimpleMBeanNode ( objectName , mBeanServer , new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; InvokerArguments arguments = new ConvertableArguments ( new DefaultConverter ( ) , "" , "" , ) ; double result = ( Double ) test . invoke ( "" , arguments ) ; assertEquals ( , result , ) ; assertEquals ( "" , simple . fruit ) ; assertEquals ( DateHelper . parseDate ( "" ) , simple . delivery ) ; assertEquals ( , simple . quantity ) ; } public void testGetProperty ( ) throws Exception { SimpleMBeanNode test = new SimpleMBeanNode ( objectName , mBeanServer , new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; PropertyAccessor accessor = new BeanUtilsPropertyAccessor ( ) ; String result = accessor . getProperty ( test , "" , String . class ) ; assertEquals ( "" , result ) ; accessor . setProperty ( test , "" , ) ; assertEquals ( , simple . rating , ) ; } public void testLogEnabled ( ) throws Exception { final StringBuilder builder = new StringBuilder ( ) ; class TestListener implements LogListener { public void logEvent ( LogEvent logEvent ) { builder . append ( logEvent . getMessage ( ) + "" ) ; } } SimpleMBeanNode test = new SimpleMBeanNode ( objectName , mBeanServer , new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; Log4jArchiver archiver = new Log4jArchiver ( test , "" ) ; archiver . addLogListener ( new TestListener ( ) , test , LogLevel . DEBUG , - , ) ; test . initialise ( ) ; System . out . println ( builder . toString ( ) ) ; assertTrue ( builder . length ( ) > ) ; } public void testGetMemory ( ) throws Exception { SimpleMBeanNode test = new SimpleMBeanNode ( new ObjectName ( "" ) , mBeanServer , new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; BeanUtilsPropertyAccessor accessor = new BeanUtilsPropertyAccessor ( ) ; Object heapMemory = accessor . getProperty ( test , "" ) ; assertEquals ( "" , heapMemory . toString ( ) ) ; Long used = accessor . getProperty ( test , "" , Long . class ) ; assertTrue ( used . longValue ( ) > ) ; } } package org . oddjob . jmx . general ; import java . util . Date ; public class Vendor implements VendorMBean { String fruit ; Date delivery ; int quantity ; double rating ; final String farm ; public Vendor ( String farm ) { this . farm = farm ; } public double quote ( String fruit , Date delivery , int quantity ) { this . fruit = fruit ; this . delivery = delivery ; this . quantity = quantity ; return ; } @ Override public String getFarm ( ) { return farm ; } @ Override public void setRating ( double rating ) { this . rating = rating ; } @ Override public double getRating ( ) { return rating ; } } package org . oddjob . jmx . general ; import static org . mockito . Mockito . mock ; import static org . mockito . Mockito . when ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . DynaProperty ; import org . mockito . Mockito ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . beanutils . BeanUtilsPropertyAccessor ; public class MBeanDirectoryTest extends TestCase { public static class Vendor { public String getName ( ) { return "" ; } } public void testLookup ( ) throws Exception { DynaProperty prop = new DynaProperty ( "" ) ; DynaClass dynaClass = mock ( DynaClass . class ) ; when ( dynaClass . getDynaProperty ( "" ) ) . thenReturn ( prop ) ; MBeanNode node = mock ( MBeanNode . class ) ; when ( node . get ( "" ) ) . thenReturn ( new Vendor ( ) ) ; when ( node . getDynaClass ( ) ) . thenReturn ( dynaClass ) ; MBeanCache cache = mock ( MBeanCache . class ) ; when ( cache . findBean ( new ObjectName ( "" ) ) ) . thenReturn ( node ) ; BeanUtilsPropertyAccessor accessor = new BeanUtilsPropertyAccessor ( ) ; ArooaTools tools = mock ( ArooaTools . class ) ; when ( tools . getPropertyAccessor ( ) ) . thenReturn ( accessor ) ; ArooaSession arooaSession = mock ( ArooaSession . class ) ; when ( arooaSession . getTools ( ) ) . thenReturn ( tools ) ; MBeanSession session = Mockito . mock ( MBeanSession . class ) ; when ( session . getArooaSession ( ) ) . thenReturn ( arooaSession ) ; when ( session . getMBeanCache ( ) ) . thenReturn ( cache ) ; MBeanDirectory test = new MBeanDirectory ( session ) ; Object result = test . lookup ( "" ) ; Mockito . verify ( node ) . get ( "" ) ; assertEquals ( "" , result ) ; } } package org . oddjob . jmx . general ; import java . text . ParseException ; import org . oddjob . jmx . general . MBeanDirectoryPathParser ; import junit . framework . TestCase ; public class MBeanDirectoryPathParserTest extends TestCase { public void testSimpleType ( ) throws ParseException { String path = "" ; MBeanDirectoryPathParser test = new MBeanDirectoryPathParser ( ) ; test . parse ( path ) ; assertEquals ( path , test . getName ( ) ) ; assertEquals ( null , test . getProperty ( ) ) ; } public void testSimpleAttribute ( ) throws ParseException { String path = "" ; MBeanDirectoryPathParser test = new MBeanDirectoryPathParser ( ) ; test . parse ( path ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( "" , test . getProperty ( ) ) ; } public void testQuotedName ( ) throws ParseException { String path = "" ; MBeanDirectoryPathParser test = new MBeanDirectoryPathParser ( ) ; test . parse ( path ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( "" , test . getProperty ( ) ) ; } public void testQuotedAll ( ) throws ParseException { String path = "" ; MBeanDirectoryPathParser test = new MBeanDirectoryPathParser ( ) ; test . parse ( path ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( null , test . getProperty ( ) ) ; } public void testQuotedAttributeToo ( ) throws ParseException { String path = "" ; MBeanDirectoryPathParser test = new MBeanDirectoryPathParser ( ) ; test . parse ( path ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( "" , test . getProperty ( ) ) ; } public void testMisquotedName ( ) { String path = "" ; MBeanDirectoryPathParser test = new MBeanDirectoryPathParser ( ) ; try { test . parse ( path ) ; fail ( "" ) ; } catch ( ParseException e ) { } } } package org . oddjob . jmx ; import java . util . HashSet ; import java . util . Set ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . atomic . AtomicInteger ; import javax . management . Attribute ; import javax . management . AttributeList ; import javax . management . AttributeNotFoundException ; import javax . management . DynamicMBean ; import javax . management . InvalidAttributeValueException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanConstructorInfo ; import javax . management . MBeanException ; import javax . management . MBeanInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanServer ; import javax . management . MBeanServerConnection ; import javax . management . MBeanServerFactory ; import javax . management . Notification ; import javax . management . NotificationBroadcasterSupport ; import javax . management . NotificationListener ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import javax . management . remote . JMXConnector ; import javax . management . remote . JMXConnectorFactory ; import javax . management . remote . JMXConnectorServer ; import javax . management . remote . JMXConnectorServerFactory ; import javax . management . remote . JMXServiceURL ; import org . apache . log4j . Logger ; import junit . framework . TestCase ; public class JMXAssumptionsTest extends TestCase { private static final Logger logger = Logger . getLogger ( JMXAssumptionsTest . class ) ; public class OurMBean extends NotificationBroadcasterSupport implements DynamicMBean { @ Override public Object getAttribute ( String attribute ) throws AttributeNotFoundException , MBeanException , ReflectionException { throw new RuntimeException ( "" ) ; } @ Override public AttributeList getAttributes ( String [ ] attributes ) { throw new RuntimeException ( "" ) ; } @ Override public MBeanInfo getMBeanInfo ( ) { return new MBeanInfo ( OurMBean . class . getName ( ) , "" , new MBeanAttributeInfo [ ] , new MBeanConstructorInfo [ ] , new MBeanOperationInfo [ ] , new MBeanNotificationInfo [ ] { new MBeanNotificationInfo ( new String [ ] { "" } , Notification . class . getName ( ) , "" ) , new MBeanNotificationInfo ( new String [ ] { "" } , Notification . class . getName ( ) , "" ) } ) ; } @ Override public Object invoke ( String actionName , Object [ ] params , String [ ] signature ) throws MBeanException , ReflectionException { throw new RuntimeException ( "" ) ; } @ Override public void setAttribute ( Attribute attribute ) throws AttributeNotFoundException , InvalidAttributeValueException , MBeanException , ReflectionException { throw new RuntimeException ( "" ) ; } @ Override public AttributeList setAttributes ( AttributeList attributes ) { throw new RuntimeException ( "" ) ; } } class OurListener implements NotificationListener { Set < Thread > threads = new HashSet < Thread > ( ) ; AtomicInteger count = new AtomicInteger ( ) ; long last = - ; boolean badSequence ; @ Override public void handleNotification ( Notification notification , Object handback ) { synchronized ( threads ) { threads . add ( Thread . currentThread ( ) ) ; } logger . debug ( "" + notification . getSequenceNumber ( ) ) ; if ( notification . getSequenceNumber ( ) != last + ) { badSequence = true ; } ++ last ; count . incrementAndGet ( ) ; } public int getNumThreades ( ) { synchronized ( threads ) { return threads . size ( ) ; } } } public void testStructuralNotificaitonAssumptions ( ) throws Exception { JMXServiceURL address = new JMXServiceURL ( "" ) ; MBeanServer server = MBeanServerFactory . createMBeanServer ( ) ; JMXConnectorServer cntorServer = JMXConnectorServerFactory . newJMXConnectorServer ( address , null , server ) ; cntorServer . start ( ) ; final OurMBean ourMBean = new OurMBean ( ) ; ObjectName name = new ObjectName ( "" , "" , "" ) ; server . registerMBean ( ourMBean , name ) ; JMXConnector cntor = JMXConnectorFactory . connect ( cntorServer . getAddress ( ) ) ; MBeanServerConnection mbsc = cntor . getMBeanServerConnection ( ) ; OurListener listener = new OurListener ( ) ; mbsc . addNotificationListener ( name , listener , null , null ) ; ExecutorService executorService = Executors . newFixedThreadPool ( ) ; for ( int i = ; i < ; ++ i ) { final Notification n1 = new Notification ( "" , name , i ) ; final Notification n2 = new Notification ( "" , name , i ) ; Runnable r1 = new Runnable ( ) { @ Override public void run ( ) { ourMBean . sendNotification ( n1 ) ; } } ; Runnable r2 = new Runnable ( ) { @ Override public void run ( ) { ourMBean . sendNotification ( n2 ) ; } } ; executorService . submit ( r1 ) ; executorService . submit ( r2 ) ; } executorService . shutdown ( ) ; assertTrue ( executorService . awaitTermination ( , TimeUnit . HOURS ) ) ; while ( listener . count . get ( ) < ) { synchronized ( this ) { wait ( ) ; } } assertEquals ( , listener . getNumThreades ( ) ) ; cntor . close ( ) ; cntorServer . stop ( ) ; } } package org . oddjob . jmx . server ; import java . util . ArrayList ; import java . util . List ; import javax . management . JMException ; import javax . management . MBeanServer ; import javax . management . MBeanServerFactory ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . DynaProperty ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . MockStateful ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . SharedConstants ; import org . oddjob . jmx . handlers . StatefulHandlerFactory ; import org . oddjob . jmx . handlers . StructuralHandlerFactory ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogEvent ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; import org . oddjob . util . MockThreadManager ; public class OddjobMBeanTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddjobMBeanTest . class ) ; private ServerModel sm ; private int unique ; private class OurHierarchicalRegistry extends MockBeanRegistry { @ Override public String getIdFor ( Object component ) { assertNotNull ( component ) ; return "" + unique ++ ; } } public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; ServerInterfaceManagerFactoryImpl imf = new ServerInterfaceManagerFactoryImpl ( ) ; imf . addServerHandlerFactories ( new ResourceFactoryProvider ( new StandardArooaSession ( ) ) . getHandlerFactories ( ) ) ; sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , imf ) ; } private class OurServerSession extends MockServerSession { ArooaSession session = new StandardArooaSession ( ) ; @ Override public ObjectName nameFor ( Object object ) { return OddjobMBeanFactory . objectName ( ) ; } @ Override public ArooaSession getArooaSession ( ) { return session ; } } public void testRegister ( ) throws Exception { Runnable myJob = new Runnable ( ) { public void run ( ) { } } ; ServerContext serverContext = new ServerContextImpl ( myJob , sm , new OurHierarchicalRegistry ( ) ) ; OddjobMBean ojmb = new OddjobMBean ( myJob , new OurServerSession ( ) , serverContext ) ; ObjectName on = new ObjectName ( "" ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; mbs . registerMBean ( ojmb , on ) ; assertTrue ( mbs . isRegistered ( on ) ) ; mbs . unregisterMBean ( on ) ; } public void testNotifyState ( ) throws Exception { class MyStateful extends MockStateful { StateListener jsl ; public void addStateListener ( StateListener listener ) { jsl = listener ; listener . jobStateChange ( new StateEvent ( this , JobState . READY , null ) ) ; } public void removeStateListener ( StateListener listener ) { } public void foo ( ) { jsl . jobStateChange ( new StateEvent ( this , JobState . COMPLETE , null ) ) ; } } ; MyStateful myJob = new MyStateful ( ) ; MyNotLis myNotLis = new MyNotLis ( ) ; ServerContext serverContext = new ServerContextImpl ( myJob , sm , new OurHierarchicalRegistry ( ) ) ; OddjobMBean ojmb = new OddjobMBean ( myJob , new OurServerSession ( ) , serverContext ) ; ObjectName on = OddjobMBeanFactory . objectName ( ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; mbs . registerMBean ( ojmb , on ) ; mbs . addNotificationListener ( on , myNotLis , null , null ) ; assertEquals ( "" , , myNotLis . getNum ( ) ) ; myJob . foo ( ) ; assertEquals ( "" , , myNotLis . getNum ( ) ) ; assertEquals ( "" , on , myNotLis . getNotification ( ) . getSource ( ) ) ; assertEquals ( "" , StatefulHandlerFactory . STATE_CHANGE_NOTIF_TYPE , myNotLis . getNotification ( ) . getType ( ) ) ; mbs . unregisterMBean ( on ) ; } public void testNotifyStructure ( ) throws JMException { final Object myChild = new Object ( ) { public String toString ( ) { return "" ; } } ; class MyStructural implements Structural { StructuralListener jsl ; boolean foo = false ; public void addStructuralListener ( StructuralListener listener ) { jsl = listener ; } public void removeStructuralListener ( StructuralListener listener ) { } public void foo ( ) { if ( foo ) { jsl . childRemoved ( new StructuralEvent ( this , myChild , ) ) ; } else { jsl . childAdded ( new StructuralEvent ( this , myChild , ) ) ; } foo = ! foo ; } } ; MyStructural myJob = new MyStructural ( ) ; MyNotLis myNotLis = new MyNotLis ( ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; OddjobMBeanFactory f = new OddjobMBeanFactory ( mbs , new StandardArooaSession ( ) ) ; ServerContext serverContext = new ServerContextImpl ( myJob , sm , new OurHierarchicalRegistry ( ) ) ; ObjectName on = f . createMBeanFor ( myJob , serverContext ) ; mbs . addNotificationListener ( on , myNotLis , null , null ) ; Notification [ ] notifications = ( Notification [ ] ) mbs . invoke ( on , "" , new Object [ ] , new String [ ] ) ; assertEquals ( , notifications . length ) ; myJob . foo ( ) ; assertEquals ( "" , , myNotLis . getNum ( ) ) ; assertEquals ( "" , on , myNotLis . getNotification ( ) . getSource ( ) ) ; assertEquals ( "" , StructuralHandlerFactory . STRUCTURAL_NOTIF_TYPE , myNotLis . getNotification ( ) . getType ( ) ) ; myJob . foo ( ) ; assertEquals ( "" , , myNotLis . getNum ( ) ) ; assertEquals ( "" , on , myNotLis . getNotification ( ) . getSource ( ) ) ; assertEquals ( "" , StructuralHandlerFactory . STRUCTURAL_NOTIF_TYPE , myNotLis . getNotification ( ) . getType ( ) ) ; mbs . unregisterMBean ( on ) ; } public static class MyBean { public String getFruit ( ) { return "" ; } } public void testGetDynaClass ( ) throws Exception { MyBean sampleBean = new MyBean ( ) ; ServerContext serverContext = new ServerContextImpl ( sampleBean , sm , new OurHierarchicalRegistry ( ) ) ; OddjobMBean test = new OddjobMBean ( sampleBean , new OurServerSession ( ) , serverContext ) ; DynaClass dc = ( DynaClass ) test . invoke ( "" , new Object [ ] { } , new String [ ] { } ) ; assertNotNull ( dc ) ; DynaProperty dp = dc . getDynaProperty ( "" ) ; assertEquals ( String . class , dp . getType ( ) ) ; } public static class LoggingBean implements LogEnabled { public String loggerName ( ) { return "" ; } } public void testLogging ( ) throws Exception { LoggingBean bean = new LoggingBean ( ) ; ( ( ServerModelImpl ) sm ) . setLogFormat ( "" ) ; ServerContext serverContext = new ServerContextImpl ( bean , sm , new OurHierarchicalRegistry ( ) ) ; OddjobMBean ojmb = new OddjobMBean ( bean , new OurServerSession ( ) , serverContext ) ; Logger testLogger = Logger . getLogger ( bean . loggerName ( ) ) ; testLogger . setLevel ( Level . DEBUG ) ; testLogger . info ( "" ) ; LogEvent [ ] events = ( LogEvent [ ] ) ojmb . invoke ( SharedConstants . RETRIEVE_LOG_EVENTS_METHOD , new Object [ ] { new Long ( - ) , new Integer ( ) } , new String [ ] { Long . TYPE . getName ( ) , Integer . TYPE . getName ( ) } ) ; assertEquals ( "" , , events . length ) ; assertEquals ( "" , "" , events [ ] . getMessage ( ) ) ; } } class MyNotLis implements NotificationListener { private static final Logger logger = Logger . getLogger ( MyNotLis . class ) ; private class Pair { private final Notification notification ; private final Object handback ; Pair ( Notification notification , Object handback ) { this . notification = notification ; this . handback = handback ; } } private final List < Pair > notifications = new ArrayList < Pair > ( ) ; public void handleNotification ( Notification arg0 , Object arg1 ) { try { if ( ! ( arg0 . getSource ( ) instanceof ObjectName ) ) { throw new ClassCastException ( "" ) ; } Notification copy = Helper . copy ( arg0 ) ; if ( ! ( copy . getSource ( ) instanceof ObjectName ) ) { throw new ClassCastException ( "" ) ; } } catch ( Exception e ) { logger . error ( "" , e ) ; throw new RuntimeException ( e ) ; } Pair p = new Pair ( arg0 , arg1 ) ; notifications . add ( p ) ; } int getNum ( ) { return notifications . size ( ) ; } Notification getNotification ( int i ) { Pair p = ( Pair ) notifications . get ( i ) ; return p . notification ; } Object getHandback ( int i ) { Pair p = ( Pair ) notifications . get ( i ) ; return p . handback ; } } ; package org . oddjob . jmx . server ; import junit . framework . TestCase ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class LogArhiverHelperTest extends TestCase { public static class MockLogArchiver implements LogArchiver { boolean removed ; Object component ; LogLevel level ; long last ; int max ; public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int max ) { this . component = component ; this . level = level ; this . last = last ; this . max = max ; l . logEvent ( new LogEvent ( "" , , LogLevel . INFO , "" ) ) ; } public void removeLogListener ( LogListener l , Object component ) { assertEquals ( this . component , component ) ; removed = true ; } public void onDestroy ( ) { } } public void testRetrieveLogEvents ( ) { Object bean = new Object ( ) ; MockLogArchiver archiver = new MockLogArchiver ( ) ; LogEvent [ ] events = LogArchiverHelper . retrieveLogEvents ( bean , archiver , new Long ( ) , new Integer ( ) ) ; assertEquals ( "" , bean , archiver . component ) ; assertEquals ( "" , LogLevel . DEBUG , archiver . level ) ; assertEquals ( "" , , archiver . last ) ; assertEquals ( "" , , archiver . max ) ; assertTrue ( "" , archiver . removed ) ; assertEquals ( "" , , events . length ) ; assertEquals ( "" , "" , events [ ] . getMessage ( ) ) ; } } package org . oddjob . jmx . server ; import junit . framework . TestCase ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . InvalidIdException ; import org . oddjob . arooa . registry . MockBeanDirectoryOwner ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . jmx . RemoteDirectory ; import org . oddjob . jmx . RemoteDirectoryOwner ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . util . MockThreadManager ; public class ServerContextImplTest extends TestCase { public void testSimple ( ) throws InvalidIdException { Object comp = new Object ( ) ; SimpleBeanRegistry cr1 = new SimpleBeanRegistry ( ) ; cr1 . register ( "" , comp ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new MockServerInterfaceManagerFactory ( ) ) ; ServerContext test = new ServerContextImpl ( comp , sm , cr1 ) ; assertEquals ( sm , test . getModel ( ) ) ; assertEquals ( new Address ( new ServerId ( "" ) , new Path ( "" ) ) , test . getAddress ( ) ) ; } class OurOwner extends MockBeanDirectoryOwner { BeanDirectory beanDirectory ; public BeanDirectory provideBeanDirectory ( ) { return beanDirectory ; } } public void testTopChildRegistry ( ) throws ServerLoopBackException { OurOwner client = new OurOwner ( ) ; SimpleBeanRegistry cr1 = new SimpleBeanRegistry ( ) ; cr1 . register ( "" , client ) ; SimpleBeanRegistry cr2 = new SimpleBeanRegistry ( ) ; client . beanDirectory = cr2 ; Object node = new Object ( ) ; cr2 . register ( "" , node ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new MockServerInterfaceManagerFactory ( ) ) ; ServerContext sc1 = new ServerContextImpl ( client , sm , cr1 ) ; Address address1 = new Address ( new ServerId ( "" ) , new Path ( "" ) ) ; assertEquals ( address1 , sc1 . getAddress ( ) ) ; ServerContext sc2 = sc1 . addChild ( node ) ; assertTrue ( sc1 . getBeanDirectory ( ) != sc2 . getBeanDirectory ( ) ) ; Address address = new Address ( new ServerId ( "" ) , new Path ( "" ) ) ; assertEquals ( address , sc2 . getAddress ( ) ) ; } public void testChildRegistry ( ) throws ServerLoopBackException { Object top = new Object ( ) ; SimpleBeanRegistry cr1 = new SimpleBeanRegistry ( ) ; cr1 . register ( "" , top ) ; OurOwner node = new OurOwner ( ) ; cr1 . register ( "" , node ) ; SimpleBeanRegistry cr2 = new SimpleBeanRegistry ( ) ; node . beanDirectory = cr2 ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new MockServerInterfaceManagerFactory ( ) ) ; ServerContext sc1 = new ServerContextImpl ( top , sm , cr1 ) ; ServerContext sc2 = sc1 . addChild ( node ) ; Object inner = new Object ( ) ; cr2 . register ( "" , inner ) ; ServerContext sc3 = sc2 . addChild ( inner ) ; assertEquals ( new Address ( new ServerId ( "" ) , new Path ( "" ) ) , sc3 . getAddress ( ) ) ; } public void testChildRegistryNoPath ( ) throws ServerLoopBackException { SimpleBeanRegistry cr1 = new SimpleBeanRegistry ( ) ; OurOwner top = new OurOwner ( ) ; SimpleBeanRegistry cr2 = new SimpleBeanRegistry ( ) ; top . beanDirectory = cr2 ; OurOwner node = new OurOwner ( ) ; cr2 . register ( "" , node ) ; SimpleBeanRegistry cr3 = new SimpleBeanRegistry ( ) ; node . beanDirectory = cr3 ; Object inner = new Object ( ) ; cr3 . register ( "" , inner ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new MockServerInterfaceManagerFactory ( ) ) ; ServerContext sc1 = new ServerContextImpl ( top , sm , cr1 ) ; ServerContext sc2 = sc1 . addChild ( node ) ; ServerContext sc3 = sc2 . addChild ( inner ) ; assertNull ( sc3 . getAddress ( ) ) ; } class OurRemote extends MockBeanDirectoryOwner implements RemoteDirectoryOwner { BeanDirectory beanDirectory ; ServerId serverId ; public RemoteDirectory provideBeanDirectory ( ) { return new RemoteDirectory ( ) { public ServerId getServerId ( ) { return serverId ; } public < T > Iterable < T > getAllByType ( Class < T > type ) { return beanDirectory . getAllByType ( type ) ; } public String getIdFor ( Object bean ) { return beanDirectory . getIdFor ( bean ) ; } public Object lookup ( String path ) { return beanDirectory . lookup ( path ) ; } public < T > T lookup ( String path , Class < T > required ) throws ArooaConversionException { return lookup ( path , required ) ; } } ; } } public void testDifferentServers ( ) throws ServerLoopBackException { OurRemote top = new OurRemote ( ) ; SimpleBeanRegistry cr1 = new SimpleBeanRegistry ( ) ; cr1 . register ( "" , top ) ; SimpleBeanRegistry cr2 = new SimpleBeanRegistry ( ) ; top . serverId = new ServerId ( "" ) ; top . beanDirectory = cr2 ; Object inner = new Object ( ) ; cr2 . register ( "" , inner ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new MockServerInterfaceManagerFactory ( ) ) ; ServerContext sc1 = new ServerContextImpl ( top , sm , cr1 ) ; Address address1 = new Address ( new ServerId ( "" ) , new Path ( "" ) ) ; assertEquals ( address1 , sc1 . getAddress ( ) ) ; ServerContext sc2 = sc1 . addChild ( inner ) ; Address address2 = new Address ( new ServerId ( "" ) , new Path ( "" ) ) ; assertEquals ( address2 , sc2 . getAddress ( ) ) ; } public void testDuplicateServers ( ) throws ServerLoopBackException { OurRemote top = new OurRemote ( ) ; SimpleBeanRegistry cr1 = new SimpleBeanRegistry ( ) ; cr1 . register ( "" , top ) ; SimpleBeanRegistry cr2 = new SimpleBeanRegistry ( ) ; top . serverId = new ServerId ( "" ) ; top . beanDirectory = cr2 ; Object inner = new Object ( ) ; cr2 . register ( "" , inner ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new MockServerInterfaceManagerFactory ( ) ) ; ServerContext sc1 = new ServerContextImpl ( top , sm , cr1 ) ; Address address1 = new Address ( new ServerId ( "" ) , new Path ( "" ) ) ; assertEquals ( address1 , sc1 . getAddress ( ) ) ; try { sc1 . addChild ( inner ) ; fail ( "" ) ; } catch ( ServerLoopBackException e ) { } } public void testLogArchiver ( ) throws ServerLoopBackException { final Object node = new Object ( ) ; class OurArchiver implements LogArchiver { public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int max ) { throw new RuntimeException ( "" ) ; } public void removeLogListener ( LogListener l , Object component ) { throw new RuntimeException ( "" ) ; } } SimpleBeanRegistry cr1 = new SimpleBeanRegistry ( ) ; OurArchiver top = new OurArchiver ( ) ; cr1 . register ( "" , top ) ; cr1 . register ( "" , node ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new MockServerInterfaceManagerFactory ( ) ) ; ServerContext sc1 = new ServerContextImpl ( top , sm , cr1 ) ; ServerContext sc2 = sc1 . addChild ( node ) ; assertEquals ( top , sc2 . getLogArchiver ( ) ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanException ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanParameterInfo ; import javax . management . ReflectionException ; import junit . framework . TestCase ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; public class InterfaceManagerImplTest extends TestCase { interface MockI { } class MockInterfaceInfo implements ServerInterfaceHandlerFactory < MockI , MockI > { boolean destroyed ; public ServerInterfaceHandler createServerHandler ( MockI target , ServerSideToolkit ojmb ) { return new ServerInterfaceHandler ( ) { public void destroy ( ) { destroyed = true ; } public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { if ( "" . equals ( operation . getActionName ( ) ) ) { return "" ; } else if ( "" . equals ( operation . getActionName ( ) ) ) { return "" ; } else throw new RuntimeException ( "" ) ; } } ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] { new MBeanOperationInfo ( "" , "" , new MBeanParameterInfo [ ] , String . class . getName ( ) , MBeanOperationInfo . INFO ) , new MBeanOperationInfo ( "" , "" , new MBeanParameterInfo [ ] , String . class . getName ( ) , MBeanOperationInfo . ACTION_INFO ) } ; } public Class < MockI > interfaceClass ( ) { return MockI . class ; } public ClientHandlerResolver < MockI > clientHandlerFactory ( ) { return null ; } } public void testAllClientInfo ( ) throws MBeanException , ReflectionException { MockI target = new MockI ( ) { } ; ServerInterfaceManager test = new ServerInterfaceManagerImpl ( target , null , new ServerInterfaceHandlerFactory [ ] { new MockInterfaceInfo ( ) } ) ; ClientHandlerResolver < ? > [ ] result = test . allClientInfo ( ) ; assertEquals ( , result . length ) ; } public void testAllClientInfoReadOnly ( ) throws MBeanException , ReflectionException { MockI target = new MockI ( ) { } ; ServerInterfaceManager test = new ServerInterfaceManagerImpl ( target , null , new ServerInterfaceHandlerFactory [ ] { new MockInterfaceInfo ( ) } , new OddjobJMXAccessController ( ) { @ Override public boolean isAccessable ( MBeanOperationInfo opInfo ) { return opInfo . getImpact ( ) == MBeanOperationInfo . INFO ; } } ) ; ClientHandlerResolver < ? > [ ] result = test . allClientInfo ( ) ; assertEquals ( , result . length ) ; } public void testInvoke ( ) throws MBeanException , ReflectionException { MockI target = new MockI ( ) { } ; ServerInterfaceManager test = new ServerInterfaceManagerImpl ( target , null , new ServerInterfaceHandlerFactory [ ] { new MockInterfaceInfo ( ) } ) ; Object result = test . invoke ( "" , new Object [ ] , new String [ ] ) ; assertEquals ( "" , result ) ; result = test . invoke ( "" , new Object [ ] , new String [ ] ) ; assertEquals ( "" , result ) ; } public void testInvokeWithAccessController ( ) throws MBeanException , ReflectionException { MockI target = new MockI ( ) { } ; ServerInterfaceManager test = new ServerInterfaceManagerImpl ( target , null , new ServerInterfaceHandlerFactory [ ] { new MockInterfaceInfo ( ) } , new OddjobJMXAccessController ( ) { @ Override public boolean isAccessable ( MBeanOperationInfo opInfo ) { return opInfo . getImpact ( ) == MBeanOperationInfo . INFO ; } } ) ; Object result = test . invoke ( "" , new Object [ ] , new String [ ] ) ; assertEquals ( "" , result ) ; try { test . invoke ( "" , new Object [ ] , new String [ ] ) ; fail ( "" ) ; } catch ( SecurityException e ) { } } public void testDestory ( ) { MockI target = new MockI ( ) { } ; MockInterfaceInfo factory = new MockInterfaceInfo ( ) ; ServerInterfaceManager test = new ServerInterfaceManagerImpl ( target , null , new ServerInterfaceHandlerFactory [ ] { factory } ) ; test . destroy ( ) ; assertTrue ( factory . destroyed ) ; } } package org . oddjob . jmx . server ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . util . ThreadManager ; public class MockServerModel implements ServerModel { public ServerInterfaceManagerFactory getInterfaceManagerFactory ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public String getLogFormat ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ThreadManager getThreadManager ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ServerId getServerId ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . server ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; public class MockServerContext implements ServerContext { public ServerContext addChild ( Object child ) throws ServerLoopBackException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ServerId getServerId ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ConsoleArchiver getConsoleArchiver ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public LogArchiver getLogArchiver ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ServerModel getModel ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeChild ( Object child ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Address getAddress ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public BeanDirectory getBeanDirectory ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . server ; import junit . framework . TestCase ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . util . MockThreadManager ; public class ServerModelTest extends TestCase { class LL implements LogListener { LogEvent e ; public void logEvent ( LogEvent logEvent ) { this . e = logEvent ; } } public static class LoggingBean implements LogEnabled { public String loggerName ( ) { return "" ; } } class OurRegistry extends MockBeanRegistry { @ Override public String getIdFor ( Object component ) { return "" ; } } public void testLogArchiver ( ) throws Exception { LoggingBean bean = new LoggingBean ( ) ; ServerModelImpl sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new MockServerInterfaceManagerFactory ( ) ) ; sm . setLogFormat ( "" ) ; Logger testLogger = Logger . getLogger ( bean . loggerName ( ) ) ; LL ll = new LL ( ) ; ServerContext serverContext = new ServerContextImpl ( bean , sm , new OurRegistry ( ) ) ; testLogger . setLevel ( Level . DEBUG ) ; testLogger . info ( "" ) ; serverContext . getLogArchiver ( ) . addLogListener ( ll , bean , LogLevel . DEBUG , - , ) ; assertNotNull ( "" , ll . e ) ; assertEquals ( "" , "" , ll . e . getMessage ( ) ) ; } } package org . oddjob . jmx . server ; public class MockServerInterfaceManagerFactory implements ServerInterfaceManagerFactory { public ServerInterfaceManager create ( Object target , ServerSideToolkit serverSideToolkit ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . server ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import javax . management . MalformedObjectNameException ; import javax . management . Notification ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . MockClassResolver ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . MockRemoteOddjobBean ; import org . oddjob . jmx . RemoteDirectoryOwner ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . jmx . client . ClientHandlerResolver ; public class ServerMainBeanTest extends TestCase { private class OurModel extends MockServerModel { ServerInterfaceManagerFactory simf ; @ Override public ServerInterfaceManagerFactory getInterfaceManagerFactory ( ) { return simf ; } @ Override public String getLogFormat ( ) { return null ; } @ Override public ServerId getServerId ( ) { return new ServerId ( "" ) ; } } ObjectName childName ; { try { childName = new ObjectName ( "" , "" , "" ) ; } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( e ) ; } } private class OurServerToolkit extends MockServerSideToolkit { ArooaSession session = new StandardArooaSession ( ) ; Object child ; List < Notification > sent = new ArrayList < Notification > ( ) ; ServerContext context ; @ Override public ServerContext getContext ( ) { return context ; } @ Override public RemoteOddjobBean getRemoteBean ( ) { return new MockRemoteOddjobBean ( ) ; } @ Override public void runSynchronized ( Runnable runnable ) { runnable . run ( ) ; } @ Override public Notification createNotification ( String type ) { return new Notification ( "" , this , ) ; } @ Override public void sendNotification ( Notification notification ) { sent . add ( notification ) ; } @ Override public ServerSession getServerSession ( ) { return new MockServerSession ( ) { @ Override public ObjectName createMBeanFor ( Object theChild , ServerContext childContext ) { child = theChild ; return childName ; } @ Override public void destroy ( ObjectName childName ) { assertEquals ( ServerMainBeanTest . this . childName , childName ) ; child = null ; } @ Override public ArooaSession getArooaSession ( ) { return session ; } } ; } } private class OurClassResolver extends MockClassResolver { @ Override public Class < ? > findClass ( String className ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } } public void testInterfaces ( ) { BeanDirectory beanDirectory = new MockBeanRegistry ( ) { @ Override public String getIdFor ( Object component ) { return null ; } } ; Object child = new Object ( ) ; ServerMainBean test = new ServerMainBean ( child , beanDirectory ) ; ServerInterfaceManagerFactoryImpl simf = new ServerInterfaceManagerFactoryImpl ( ) ; simf . addServerHandlerFactories ( new ResourceFactoryProvider ( new StandardArooaSession ( ) ) . getHandlerFactories ( ) ) ; OurModel model = new OurModel ( ) ; model . simf = simf ; ServerContextImpl context = new ServerContextImpl ( test , model , beanDirectory ) ; OurServerToolkit toolkit = new OurServerToolkit ( ) ; toolkit . context = context ; ServerInterfaceManager serverInterfaceManager = simf . create ( test , toolkit ) ; assertEquals ( child , toolkit . child ) ; assertEquals ( , toolkit . sent . size ( ) ) ; ClientHandlerResolver < ? > [ ] clientFactories = serverInterfaceManager . allClientInfo ( ) ; Set < Class < ? > > interfaces = new HashSet < Class < ? > > ( ) ; for ( ClientHandlerResolver < ? > clientFactory : clientFactories ) { interfaces . add ( clientFactory . resolve ( new OurClassResolver ( ) ) . interfaceClass ( ) ) ; } assertTrue ( interfaces . contains ( Object . class ) ) ; assertTrue ( interfaces . contains ( RemoteOddjobBean . class ) ) ; assertTrue ( interfaces . contains ( RemoteDirectoryOwner . class ) ) ; assertTrue ( interfaces . contains ( Structural . class ) ) ; serverInterfaceManager . destroy ( ) ; assertNull ( toolkit . child ) ; assertEquals ( , toolkit . sent . size ( ) ) ; } public void testStructural ( ) throws ServerLoopBackException { Object root = new Object ( ) ; BeanDirectory beanDir = new MockBeanRegistry ( ) { @ Override public String getIdFor ( Object component ) { return null ; } } ; ServerMainBean test = new ServerMainBean ( root , beanDir ) ; OurModel model = new OurModel ( ) ; ServerContext context = new ServerContextImpl ( test , model , beanDir ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; assertEquals ( root , children [ ] ) ; ServerContext childContext = context . addChild ( root ) ; assertEquals ( model . getServerId ( ) , childContext . getServerId ( ) ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanOperationInfo ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . logging . LogEnabled ; import junit . framework . TestCase ; public class JMXOperationFactoryTest extends TestCase { public void testNoArgsOpInfo ( ) throws SecurityException , NoSuchMethodException { JMXOperationFactory test = new JMXOperationFactory ( LogEnabled . class ) ; RemoteOperation < ? > expected = new OperationInfoOperation ( new MBeanOperationInfo ( "" , LogEnabled . class . getMethod ( "" ) ) ) ; assertEquals ( expected , test . operationFor ( LogEnabled . class . getMethod ( "" ) , MBeanOperationInfo . INFO ) ) ; assertEquals ( expected , test . operationFor ( LogEnabled . class . getMethod ( "" ) , "" , MBeanOperationInfo . INFO ) ) ; assertEquals ( expected , test . operationFor ( "" , MBeanOperationInfo . INFO ) ) ; assertEquals ( expected , test . operationFor ( "" , "" , MBeanOperationInfo . INFO ) ) ; } } package org . oddjob . jmx . server ; import javax . management . JMException ; import javax . management . MBeanServer ; import javax . management . MBeanServerFactory ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . oddjob . arooa . registry . Address ; import org . oddjob . jmx . handlers . StructuralHandlerFactory ; import org . oddjob . jobs . structural . JobFolder ; public class OddjobMBeanFactoryTest extends TestCase { private class OurServerContext extends MockServerContext { ServerInterfaceManagerFactory simf ; @ Override public ServerContext addChild ( Object child ) throws ServerLoopBackException { return this ; } @ Override public ServerModel getModel ( ) { return new MockServerModel ( ) { @ Override public ServerInterfaceManagerFactory getInterfaceManagerFactory ( ) { return simf ; } } ; } @ Override public Address getAddress ( ) { return null ; } } public void testStruture ( ) throws JMException { JobFolder folder = new JobFolder ( ) ; Object c1 = new Object ( ) ; Object c2 = new Object ( ) ; folder . setJobs ( , c1 ) ; folder . setJobs ( , c2 ) ; MBeanServer server = MBeanServerFactory . createMBeanServer ( ) ; OddjobMBeanFactory test = new OddjobMBeanFactory ( server , null ) ; ServerInterfaceManagerFactoryImpl simf = new ServerInterfaceManagerFactoryImpl ( new ServerInterfaceHandlerFactory < ? , ? > [ ] { new StructuralHandlerFactory ( ) } ) ; OurServerContext context = new OurServerContext ( ) ; context . simf = simf ; ObjectName root = test . createMBeanFor ( folder , context ) ; assertEquals ( new Integer ( ) , server . getMBeanCount ( ) ) ; assertEquals ( folder , test . objectFor ( OddjobMBeanFactory . objectName ( ) ) ) ; assertEquals ( c1 , test . objectFor ( OddjobMBeanFactory . objectName ( ) ) ) ; assertEquals ( c2 , test . objectFor ( OddjobMBeanFactory . objectName ( ) ) ) ; test . destroy ( root ) ; assertEquals ( new Integer ( ) , server . getMBeanCount ( ) ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanException ; import javax . management . ReflectionException ; import junit . framework . TestCase ; public class ServerAllOperationsHandlerTest extends TestCase { interface Fruit { String getColour ( ) ; } class MyFruit implements Fruit { public String getColour ( ) { return "" ; } } public void testInvoke ( ) throws MBeanException , ReflectionException { ServerAllOperationsHandler < Fruit > test = new ServerAllOperationsHandler < Fruit > ( Fruit . class , new MyFruit ( ) ) ; Object result = test . invoke ( new MBeanOperation ( "" , new String [ ] ) , new Object [ ] ) ; assertEquals ( "" , result ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import org . oddjob . jmx . client . ClientHandlerResolver ; public class MockServerInterfaceHandlerFactory < X , Y > implements ServerInterfaceHandlerFactory < X , Y > { public ClientHandlerResolver < Y > clientHandlerFactory ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ServerInterfaceHandler createServerHandler ( X target , ServerSideToolkit ojmb ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Class < X > interfaceClass ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . Notification ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . MockClientHandlerResolver ; public class OddjobMBeanToolkitTest extends TestCase { private class OurServerSession extends MockServerSession { @ Override public ObjectName nameFor ( Object object ) { return OddjobMBeanFactory . objectName ( ) ; } } private class OurServerContext extends MockServerContext { OurSIMF simf = new OurSIMF ( ) ; @ Override public ServerModel getModel ( ) { return new MockServerModel ( ) { @ Override public ServerInterfaceManagerFactory getInterfaceManagerFactory ( ) { return new ServerInterfaceManagerFactoryImpl ( new ServerInterfaceHandlerFactory < ? , ? > [ ] { simf } ) ; } } ; } } private interface Gold { } private class OurSIMF extends MockServerInterfaceHandlerFactory < Object , Gold > { ServerSideToolkit toolkit ; @ Override public ServerInterfaceHandler createServerHandler ( Object target , ServerSideToolkit toolkit ) { this . toolkit = toolkit ; return new MockServerInterfaceHandler ( ) ; } @ Override public Class < Object > interfaceClass ( ) { return Object . class ; } @ Override public ClientHandlerResolver < Gold > clientHandlerFactory ( ) { return new MockClientHandlerResolver < Gold > ( ) ; } @ Override public MBeanAttributeInfo [ ] getMBeanAttributeInfo ( ) { return new MBeanAttributeInfo [ ] ; } @ Override public MBeanNotificationInfo [ ] getMBeanNotificationInfo ( ) { return new MBeanNotificationInfo [ ] ; } @ Override public MBeanOperationInfo [ ] getMBeanOperationInfo ( ) { return new MBeanOperationInfo [ ] ; } } public void testNotification ( ) throws Exception { Object node = new Object ( ) ; OurServerSession session = new OurServerSession ( ) ; OurServerContext context = new OurServerContext ( ) ; new OddjobMBean ( node , session , context ) ; ServerSideToolkit toolkit = context . simf . toolkit ; Notification n = toolkit . createNotification ( "" ) ; assertEquals ( , n . getSequenceNumber ( ) ) ; assertEquals ( OddjobMBeanFactory . objectName ( ) , n . getSource ( ) ) ; Helper . copy ( n ) ; } } package org . oddjob . jmx . server ; import javax . management . Notification ; import org . oddjob . jmx . RemoteOddjobBean ; public class MockServerSideToolkit implements ServerSideToolkit { public ServerContext getContext ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Notification createNotification ( String type ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void runSynchronized ( Runnable runnable ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void sendNotification ( Notification notification ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public RemoteOddjobBean getRemoteBean ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ServerSession getServerSession ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . server ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ResourceFactoryProviderTest extends TestCase { public void testProvideFactories ( ) throws ArooaParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ResourceFactoryProvider test = new ResourceFactoryProvider ( session ) ; ServerInterfaceHandlerFactory < ? , ? > [ ] handlerFactories = test . getHandlerFactories ( ) ; assertEquals ( , handlerFactories . length ) ; } public static class HandlerCounter implements Runnable , ArooaSessionAware { int count ; ArooaSession session ; public void setArooaSession ( ArooaSession session ) { this . session = session ; } public void run ( ) { ResourceFactoryProvider test = new ResourceFactoryProvider ( session ) ; ServerInterfaceHandlerFactory < ? , ? > [ ] handlerFactories = test . getHandlerFactories ( ) ; count = handlerFactories . length ; } public int getCount ( ) { return count ; } } public void testFactoriesInOddjob ( ) throws ArooaParseException , ArooaConversionException { String xml = "" + "" + "" + HandlerCounter . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; int count = new OddjobLookup ( oddjob ) . lookup ( "" , int . class ) ; assertEquals ( , count ) ; } } package org . oddjob . jmx . server ; import javax . management . Notification ; import javax . management . ObjectName ; import javax . swing . ImageIcon ; import junit . framework . TestCase ; import org . oddjob . Iconic ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . jmx . handlers . IconicHandlerFactory ; import org . oddjob . util . MockThreadManager ; public class IconicInfoTest extends TestCase { private class OurHierarchicalRegistry extends MockBeanRegistry { @ Override public String getIdFor ( Object component ) { assertNotNull ( component ) ; return "" ; } } private class OurServerSession extends MockServerSession { ArooaSession session = new StandardArooaSession ( ) ; @ Override public ObjectName nameFor ( Object object ) { return OddjobMBeanFactory . objectName ( ) ; } @ Override public ArooaSession getArooaSession ( ) { return session ; } } private class MyIconic implements Iconic { IconListener l ; public void addIconListener ( IconListener listener ) { l = listener ; } public ImageIcon iconForId ( String id ) { return IconHelper . completeIcon ; } public void removeIconListener ( IconListener listener ) { l = null ; } } public void testIconForId ( ) throws Exception { MyIconic iconic = new MyIconic ( ) ; ServerInterfaceManagerFactoryImpl imf = new ServerInterfaceManagerFactoryImpl ( ) ; imf . addServerHandlerFactories ( new ServerInterfaceHandlerFactory [ ] { new IconicHandlerFactory ( ) } ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , imf ) ; ServerContext serverContext = new ServerContextImpl ( iconic , sm , new OurHierarchicalRegistry ( ) ) ; OddjobMBean ojmb = new OddjobMBean ( iconic , new OurServerSession ( ) , serverContext ) ; iconic . l . iconEvent ( new IconEvent ( iconic , "" ) ) ; Notification [ ] notifications = ( Notification [ ] ) ojmb . invoke ( "" , new Object [ ] { } , new String [ ] { } ) ; Notification n = notifications [ ] ; assertEquals ( IconicHandlerFactory . ICON_CHANGED_NOTIF_TYPE , n . getType ( ) ) ; ImageIcon it = ( ImageIcon ) ojmb . invoke ( "" , new Object [ ] { "" } , new String [ ] { String . class . getName ( ) } ) ; assertEquals ( "" , it . getDescription ( ) ) ; } } package org . oddjob . jmx . server ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; import java . util . HashSet ; import java . util . Set ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . MockClassResolver ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . jmx . Utils ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . handlers . RunnableHandlerFactory ; import org . oddjob . util . MockThreadManager ; public class ObjectMBeanServerInfoTest extends TestCase { private class OurClassResolver extends MockClassResolver { @ Override public Class < ? > findClass ( String className ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } } private class OurServerSession extends MockServerSession { ArooaSession session = new StandardArooaSession ( ) ; @ Override public ObjectName nameFor ( Object object ) { return OddjobMBeanFactory . objectName ( ) ; } @ Override public ArooaSession getArooaSession ( ) { return session ; } } private class OurDirectory extends MockBeanRegistry { @ Override public String getIdFor ( Object component ) { return "" ; } } public void testServerInfo ( ) throws Exception { Runnable myJob = new Runnable ( ) { public void run ( ) { } } ; ServerInterfaceManagerFactoryImpl imf = new ServerInterfaceManagerFactoryImpl ( ) ; imf . addServerHandlerFactories ( new ServerInterfaceHandlerFactory [ ] { new RunnableHandlerFactory ( ) } ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , imf ) ; ServerContext serverContext = new ServerContextImpl ( myJob , sm , new OurDirectory ( ) ) ; final OddjobMBean ojmb = new OddjobMBean ( myJob , new OurServerSession ( ) , serverContext ) ; RemoteOddjobBean rob = ( RemoteOddjobBean ) Proxy . newProxyInstance ( getClass ( ) . getClassLoader ( ) , new Class [ ] { RemoteOddjobBean . class } , new InvocationHandler ( ) { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return ojmb . invoke ( method . getName ( ) , args , Utils . classArray2StringArray ( method . getParameterTypes ( ) ) ) ; } } ) ; ServerInfo info = rob . serverInfo ( ) ; assertEquals ( "" , "" , info . getAddress ( ) . toString ( ) ) ; Set < Class < ? > > interfaces = new HashSet < Class < ? > > ( ) ; for ( int i = ; i < info . getClientResolvers ( ) . length ; ++ i ) { ClientHandlerResolver < ? > resolver = info . getClientResolvers ( ) [ i ] ; interfaces . add ( resolver . resolve ( new OurClassResolver ( ) ) . interfaceClass ( ) ) ; } assertTrue ( "" , interfaces . contains ( Runnable . class ) ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanException ; import javax . management . Notification ; import javax . management . ReflectionException ; import org . oddjob . jmx . RemoteOperation ; public class MockServerInterfaceHandler implements ServerInterfaceHandler { public Object invoke ( RemoteOperation < ? > operation , Object [ ] params ) throws MBeanException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public Notification [ ] getLastNotifications ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void destroy ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . server ; import javax . management . ObjectName ; import org . oddjob . arooa . ArooaSession ; public class MockServerSession implements ServerSession { public ObjectName nameFor ( Object object ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object objectFor ( ObjectName objectName ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectName createMBeanFor ( Object child , ServerContext childContext ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void destroy ( ObjectName childName ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public ArooaSession getArooaSession ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . server ; import javax . management . MBeanException ; import javax . management . MBeanInfo ; import javax . management . Notification ; import javax . management . ReflectionException ; import org . oddjob . jmx . client . ClientHandlerResolver ; public class MockServerInterfaceManager implements ServerInterfaceManager { public void destroy ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Notification [ ] getLastNotifications ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public MBeanInfo getMBeanInfo ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ClientHandlerResolver < ? > [ ] allClientInfo ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object invoke ( String actionName , Object [ ] params , String [ ] signature ) throws MBeanException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobComponentResolver ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . EchoJob ; import org . oddjob . state . ParentState ; public class PlatformMBeanServerTest extends TestCase { private static final Logger logger = Logger . getLogger ( PlatformMBeanServerTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; } public void testClientServer ( ) throws Exception { Object echo = new OddjobComponentResolver ( ) . resolve ( new EchoJob ( ) , null ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( echo ) ; server . setArooaSession ( new StandardArooaSession ( ) ) ; server . start ( ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . run ( ) ; Object [ ] children = Helper . getChildren ( client ) ; assertEquals ( , children . length ) ; client . stop ( ) ; server . stop ( ) ; } public void testInOddjob ( ) { Oddjob server = new Oddjob ( ) ; server . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; server . run ( ) ; Oddjob client = new Oddjob ( ) ; client . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; client . run ( ) ; console . close ( ) ; assertEquals ( ParentState . COMPLETE , client . lastStateEvent ( ) . getState ( ) ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; client . destroy ( ) ; server . destroy ( ) ; } } package org . oddjob . jmx ; import org . oddjob . jmx . server . ServerInfo ; public class MockRemoteOddjobBean implements RemoteOddjobBean { public void noop ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ServerInfo serverInfo ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx ; import java . io . File ; import javax . security . auth . DestroyFailedException ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . FragmentHelper ; import org . oddjob . Helper ; import org . oddjob . Iconic ; import org . oddjob . OddjobComponentResolver ; import org . oddjob . OurDirs ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . client . UsernamePassword ; import org . oddjob . jmx . server . SimpleServerSecurity ; import org . oddjob . jobs . EchoJob ; import org . oddjob . rmi . RMIRegistryJob ; import org . oddjob . state . ServiceState ; public class SimpleSecurityTest extends TestCase { private static final Logger logger = Logger . getLogger ( SimpleSecurityTest . class ) ; static final String SECURITY_CONFIG_PARAM = "" ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . debug ( "" + getName ( ) + "" ) ; } boolean useSSL ; public void testSimpleOKExample ( ) throws Exception { String param = System . getProperty ( SECURITY_CONFIG_PARAM ) ; if ( param == null ) { logger . info ( SECURITY_CONFIG_PARAM + "" ) ; return ; } else { logger . info ( SECURITY_CONFIG_PARAM + "" + param ) ; } File config = new File ( param ) ; assertTrue ( config . exists ( ) ) ; Object root = new Object ( ) { public String toString ( ) { return "" ; } } ; SimpleServerSecurity security = new SimpleServerSecurity ( ) ; security . setPasswordFile ( new File ( config , "" ) ) ; security . setAccessFile ( new File ( config , "" ) ) ; security . setUseSSL ( useSSL ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( root ) ; server . setArooaSession ( new StandardArooaSession ( ) ) ; server . setUrl ( "" ) ; server . setEnvironment ( security . toValue ( ) ) ; server . start ( ) ; UsernamePassword credentials = new UsernamePassword ( ) ; credentials . setUsername ( "" ) ; credentials . setPassword ( "" ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setConnection ( server . getAddress ( ) ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setEnvironment ( credentials . toValue ( ) ) ; client . run ( ) ; Object [ ] children = Helper . getChildren ( client ) ; assertEquals ( , children . length ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; client . stop ( ) ; server . stop ( ) ; } public void testSslOKExample ( ) throws Exception { String param = System . getProperty ( "" ) ; if ( param == null ) { return ; } useSSL = true ; System . setProperty ( "" , param + "" ) ; System . setProperty ( "" , "" ) ; System . setProperty ( "" , param + "" ) ; System . setProperty ( "" , "" ) ; testSimpleOKExample ( ) ; } public void testReadonlyAccess ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; File config = dirs . relative ( "" ) ; assertTrue ( config . exists ( ) ) ; EchoJob echo = new EchoJob ( ) ; echo . setText ( "" ) ; Object root = new OddjobComponentResolver ( ) . resolve ( echo , null ) ; SimpleServerSecurity security = new SimpleServerSecurity ( ) ; security . setPasswordFile ( new File ( config , "" ) ) ; security . setAccessFile ( new File ( config , "" ) ) ; security . setUseSSL ( useSSL ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( root ) ; server . setArooaSession ( new StandardArooaSession ( ) ) ; server . setUrl ( "" ) ; server . setEnvironment ( security . toValue ( ) ) ; server . start ( ) ; UsernamePassword credentials = new UsernamePassword ( ) ; credentials . setUsername ( "" ) ; credentials . setPassword ( "" ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setConnection ( server . getAddress ( ) ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setEnvironment ( credentials . toValue ( ) ) ; client . run ( ) ; Object [ ] children = Helper . getChildren ( client ) ; assertEquals ( , children . length ) ; Object child = children [ ] ; assertEquals ( "" , child . toString ( ) ) ; assertEquals ( false , child instanceof Runnable ) ; assertEquals ( true , child instanceof Stateful ) ; assertEquals ( true , child instanceof Iconic ) ; assertEquals ( false , child instanceof Resetable ) ; assertEquals ( false , child instanceof DynaBean ) ; assertEquals ( true , child instanceof RemoteOddjobBean ) ; client . stop ( ) ; server . stop ( ) ; } public void testClientAndServerExamples ( ) throws ArooaParseException , DestroyFailedException , FailedToStopException { FragmentHelper helper = new FragmentHelper ( ) ; Object server = helper . createComponentFromResource ( "" ) ; helper . getSession ( ) . getBeanRegistry ( ) . register ( "" , new Object ( ) ) ; JMXClientJob client = ( JMXClientJob ) helper . createComponentFromResource ( "" ) ; String param = System . getProperty ( "" ) ; if ( param == null ) { return ; } RMIRegistryJob registry = new RMIRegistryJob ( ) ; registry . run ( ) ; StateSteps serverStates = new StateSteps ( ( Stateful ) server ) ; serverStates . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; ( ( Runnable ) server ) . run ( ) ; serverStates . checkNow ( ) ; StateSteps clientStates = new StateSteps ( client ) ; clientStates . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; client . run ( ) ; clientStates . checkNow ( ) ; client . destroy ( ) ; ( ( Stoppable ) server ) . stop ( ) ; } } package org . oddjob . jmx ; import java . lang . management . ManagementFactory ; import java . util . HashMap ; import java . util . Map ; import javax . management . MBeanServer ; import javax . management . ObjectName ; import javax . management . remote . JMXConnectorServer ; import javax . management . remote . JMXConnectorServerFactory ; import javax . management . remote . JMXServiceURL ; import javax . management . remote . rmi . RMIConnectorServer ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Structural ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jmx . general . Vendor ; import org . oddjob . rmi . RMIRegistryJob ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class JMXServiceJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( JMXServiceJobTest . class ) ; ObjectName objectName ; MBeanServer mBeanServer ; JMXConnectorServer cntorServer ; Vendor simple = new Vendor ( "" ) ; protected void createServer ( Map < String , ? > environment ) throws Exception { RMIRegistryJob rmi = new RMIRegistryJob ( ) ; rmi . setPort ( ) ; rmi . run ( ) ; JMXServiceURL serviceURL = new JMXServiceURL ( "" ) ; objectName = new ObjectName ( "" ) ; mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; mBeanServer . registerMBean ( simple , objectName ) ; cntorServer = JMXConnectorServerFactory . newJMXConnectorServer ( serviceURL , environment , mBeanServer ) ; cntorServer . start ( ) ; String address = cntorServer . getAddress ( ) . toString ( ) ; logger . info ( "" + address ) ; } @ Override protected void tearDown ( ) throws Exception { mBeanServer . unregisterMBean ( objectName ) ; cntorServer . stop ( ) ; } private class ChildCatcher implements StructuralListener { final Map < String , Object > children = new HashMap < String , Object > ( ) ; public void childAdded ( StructuralEvent event ) { Object child = event . getChild ( ) ; String name = child . toString ( ) ; if ( children . containsKey ( name ) ) { throw new IllegalStateException ( ) ; } children . put ( name , child ) ; } public void childRemoved ( StructuralEvent event ) { children . remove ( event . getChild ( ) . toString ( ) ) ; } } public void testExample ( ) throws Exception { createServer ( null ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object test = lookup . lookup ( "" ) ; String farm = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , farm ) ; assertEquals ( , lookup . lookup ( "" , double . class ) , ) ; assertEquals ( , lookup . lookup ( "" , double . class ) , ) ; ChildCatcher domainsCatcher = new ChildCatcher ( ) ; ( ( Structural ) test ) . addStructuralListener ( domainsCatcher ) ; assertTrue ( domainsCatcher . children . containsKey ( "" ) ) ; Structural fruitDomain = ( Structural ) domainsCatcher . children . get ( "" ) ; ChildCatcher fruitCatcher = new ChildCatcher ( ) ; fruitDomain . addStructuralListener ( fruitCatcher ) ; assertTrue ( fruitCatcher . children . size ( ) == ) ; oddjob . stop ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , fruitCatcher . children . size ( ) ) ; assertEquals ( , domainsCatcher . children . size ( ) ) ; Object sequential = lookup . lookup ( "" ) ; ( ( Resetable ) sequential ) . hardReset ( ) ; assertEquals ( ParentState . READY , ( ( Stateful ) sequential ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Runnable ) sequential ) . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , lookup . lookup ( "" , double . class ) , ) ; oddjob . stop ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testHeartBeat ( ) throws Exception { Map < String , Object > env = new HashMap < String , Object > ( ) ; FailableSocketFactory ssf = new FailableSocketFactory ( ) ; env . put ( RMIConnectorServer . RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE , ssf ) ; createServer ( env ) ; JMXServiceJob client = new JMXServiceJob ( ) ; client . setConnection ( "" ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setHeartbeat ( ) ; StateSteps clientStates = new StateSteps ( client ) ; clientStates . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; client . run ( ) ; clientStates . checkNow ( ) ; clientStates . startCheck ( ServiceState . STARTED , ServiceState . EXCEPTION ) ; Thread . sleep ( ) ; logger . info ( "" ) ; ssf . setFail ( true ) ; clientStates . checkWait ( ) ; ssf . setFail ( false ) ; clientStates . startCheck ( ServiceState . EXCEPTION , ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; logger . debug ( "" ) ; client . hardReset ( ) ; client . run ( ) ; clientStates . checkNow ( ) ; client . stop ( ) ; } public static void main ( String ... args ) throws Exception { JMXServiceJobTest test = new JMXServiceJobTest ( ) ; test . createServer ( null ) ; System . in . read ( ) ; test . tearDown ( ) ; } } package org . oddjob . jmx . handlers ; import java . util . HashSet ; import java . util . Set ; import javax . management . MBeanOperationInfo ; import junit . framework . TestCase ; import org . oddjob . jmx . client . LogPollable ; public class VanillaServerHandlerFactoryTest extends TestCase { public void testOpInfoForClass ( ) { VanillaServerHandlerFactory < LogPollable > test = new VanillaServerHandlerFactory < LogPollable > ( LogPollable . class ) ; MBeanOperationInfo [ ] results = test . getMBeanOperationInfo ( ) ; assertEquals ( , results . length ) ; Set < String > set = new HashSet < String > ( ) ; for ( MBeanOperationInfo result : results ) { set . add ( result . getName ( ) ) ; } assertTrue ( set . contains ( "" ) ) ; } } package org . oddjob . jmx . handlers ; import junit . framework . TestCase ; import org . oddjob . Loadable ; import org . oddjob . arooa . life . ClassLoaderClassResolver ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . HandlerFactoryProvider ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ResourceFactoryProvider ; import org . oddjob . jmx . server . ServerInterfaceManager ; import org . oddjob . jmx . server . ServerInterfaceManagerFactory ; import org . oddjob . jmx . server . ServerInterfaceManagerFactoryImpl ; public class LoadableHandlerFactoryTest extends TestCase { public class MyLoadable implements Loadable { boolean loaded ; @ Override public boolean isLoadable ( ) { return ! loaded ; } @ Override public void load ( ) { loaded = true ; } @ Override public void unload ( ) { loaded = false ; } } private class OurClientToolkit extends MockClientSideToolkit { ServerInterfaceManager serverManager ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) serverManager . invoke ( remoteOperation . getActionName ( ) , args , remoteOperation . getSignature ( ) ) ; } } public void testCreation ( ) { HandlerFactoryProvider provider = new ResourceFactoryProvider ( new StandardArooaSession ( ) ) ; ServerInterfaceManagerFactory managerFactory = new ServerInterfaceManagerFactoryImpl ( provider . getHandlerFactories ( ) ) ; MyLoadable loadable = new MyLoadable ( ) ; ServerInterfaceManager manager = managerFactory . create ( loadable , new MockServerSideToolkit ( ) ) ; ClientHandlerResolver < ? > [ ] resolvers = manager . allClientInfo ( ) ; assertEquals ( , resolvers . length ) ; ClientInterfaceHandlerFactory < ? > clientFactory = resolvers [ ] . resolve ( new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; clientToolkit . serverManager = manager ; Loadable proxy = ( Loadable ) clientFactory . createClientHandler ( null , clientToolkit ) ; assertEquals ( true , proxy . isLoadable ( ) ) ; proxy . load ( ) ; assertEquals ( false , proxy . isLoadable ( ) ) ; } } package org . oddjob . jmx . handlers ; import junit . framework . TestCase ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . LogPollable ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . MockServerContext ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ServerContext ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . MockConsoleArchiver ; public class LogPollableHandlerFactoryTest extends TestCase { class OurServerSideToolkit extends MockServerSideToolkit { @ Override public ServerContext getContext ( ) { return new MockServerContext ( ) { @ Override public ServerId getServerId ( ) { return new ServerId ( "" ) ; } @ Override public ConsoleArchiver getConsoleArchiver ( ) { return new MockConsoleArchiver ( ) { @ Override public String consoleIdFor ( Object component ) { return "" ; } } ; } } ; } } class OurClientToolkit extends MockClientSideToolkit { ServerInterfaceHandler handler ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) handler . invoke ( remoteOperation , args ) ; } } public void testIds ( ) { Object component = new Object ( ) ; ServerInterfaceHandlerFactory < Object , LogPollable > test = new LogPollableHandlerFactory ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( component , new OurServerSideToolkit ( ) ) ; OurClientToolkit toolkit = new OurClientToolkit ( ) ; toolkit . handler = serverHandler ; LogPollable client = ( LogPollable ) new LogPollableHandlerFactory . ClientLogPollableHandlerFactory ( ) . createClientHandler ( null , toolkit ) ; String consoleId = client . consoleId ( ) ; assertEquals ( "" , consoleId ) ; } class SecondServerSideToolkit extends MockServerSideToolkit { LogArchiver archiver ; @ Override public ServerContext getContext ( ) { return new MockServerContext ( ) { @ Override public LogArchiver getLogArchiver ( ) { return archiver ; } @ Override public ConsoleArchiver getConsoleArchiver ( ) { return new MockConsoleArchiver ( ) { @ Override public String consoleIdFor ( Object component ) { return "" ; } } ; } @ Override public ServerId getServerId ( ) { return new ServerId ( "" ) ; } } ; } } class OurArchiver implements LogArchiver { LogListener l ; LogEvent [ ] logEvents = { new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) } ; public void addLogListener ( LogListener l , Object component , LogLevel level , long last , int max ) { this . l = l ; for ( long seq = last ; seq < && seq < last + max ; ++ seq ) { l . logEvent ( logEvents [ ( int ) seq ] ) ; } } public void removeLogListener ( LogListener l , Object component ) { this . l = null ; } public void onDestroy ( ) { throw new RuntimeException ( "" ) ; } } public void testRetrieveLogEvents ( ) { OurArchiver archiver = new OurArchiver ( ) ; ServerInterfaceHandlerFactory < Object , LogPollable > test = new LogPollableHandlerFactory ( ) ; SecondServerSideToolkit serverKit = new SecondServerSideToolkit ( ) ; serverKit . archiver = archiver ; ServerInterfaceHandler serverHandler = test . createServerHandler ( null , serverKit ) ; OurClientToolkit toolkit = new OurClientToolkit ( ) ; toolkit . handler = serverHandler ; LogPollable client = ( LogPollable ) new LogPollableHandlerFactory . ClientLogPollableHandlerFactory ( ) . createClientHandler ( null , toolkit ) ; LogEvent [ ] results = client . retrieveLogEvents ( , ) ; assertEquals ( , results . length ) ; assertEquals ( "" , results [ ] . getMessage ( ) ) ; results = client . retrieveLogEvents ( , ) ; assertEquals ( , results . length ) ; assertEquals ( "" , results [ ] . getMessage ( ) ) ; results = client . retrieveLogEvents ( , ) ; assertEquals ( , results . length ) ; assertNull ( archiver . l ) ; } class ThirdServerSideToolkit extends MockServerSideToolkit { ConsoleArchiver archiver ; @ Override public ServerContext getContext ( ) { return new MockServerContext ( ) { @ Override public ConsoleArchiver getConsoleArchiver ( ) { return archiver ; } @ Override public ServerId getServerId ( ) { return new ServerId ( "" ) ; } } ; } } class OurConsoleArchiver implements ConsoleArchiver { LogListener l ; LogEvent [ ] logEvents = { new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) , new LogEvent ( "" , , LogLevel . DEBUG , "" ) } ; public void addConsoleListener ( LogListener l , Object component , long last , int max ) { this . l = l ; for ( long seq = last ; seq < && seq < last + max ; ++ seq ) { l . logEvent ( logEvents [ ( int ) seq ] ) ; } } public void removeConsoleListener ( LogListener l , Object component ) { this . l = null ; } public String consoleIdFor ( Object component ) { return "" ; } public void onDestroy ( ) { throw new RuntimeException ( "" ) ; } } public void testRetrieveConsoleEvents ( ) { OurConsoleArchiver archiver = new OurConsoleArchiver ( ) ; ServerInterfaceHandlerFactory < Object , LogPollable > test = new LogPollableHandlerFactory ( ) ; ThirdServerSideToolkit serverKit = new ThirdServerSideToolkit ( ) ; serverKit . archiver = archiver ; ServerInterfaceHandler serverHandler = test . createServerHandler ( null , serverKit ) ; OurClientToolkit toolkit = new OurClientToolkit ( ) ; toolkit . handler = serverHandler ; LogPollable client = ( LogPollable ) new LogPollableHandlerFactory . ClientLogPollableHandlerFactory ( ) . createClientHandler ( null , toolkit ) ; LogEvent [ ] results = client . retrieveConsoleEvents ( , ) ; assertEquals ( , results . length ) ; assertEquals ( "" , results [ ] . getMessage ( ) ) ; results = client . retrieveConsoleEvents ( , ) ; assertEquals ( , results . length ) ; assertEquals ( "" , results [ ] . getMessage ( ) ) ; results = client . retrieveConsoleEvents ( , ) ; assertEquals ( , results . length ) ; assertNull ( archiver . l ) ; } } package org . oddjob . jmx . handlers ; import javax . management . Notification ; import javax . management . NotificationListener ; import junit . framework . TestCase ; import org . oddjob . MockStateful ; import org . oddjob . Stateful ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class StatefulHandlerFactoryTest extends TestCase { class OurStateful extends MockStateful { StateListener l ; public void addStateListener ( StateListener listener ) { assertNull ( l ) ; l = listener ; l . jobStateChange ( new StateEvent ( this , JobState . READY ) ) ; } public void removeStateListener ( StateListener listener ) { assertNotNull ( l ) ; l = null ; } } class OurClientToolkit extends MockClientSideToolkit { ServerInterfaceHandler server ; NotificationListener listener ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) server . invoke ( remoteOperation , args ) ; } public void registerNotificationListener ( String eventType , NotificationListener notificationListener ) { if ( listener != null ) { throw new RuntimeException ( "" ) ; } assertEquals ( StatefulHandlerFactory . STATE_CHANGE_NOTIF_TYPE , eventType ) ; this . listener = notificationListener ; } @ Override public void removeNotificationListener ( String eventType , NotificationListener notificationListener ) { if ( listener == null ) { throw new RuntimeException ( "" ) ; } assertEquals ( StatefulHandlerFactory . STATE_CHANGE_NOTIF_TYPE , eventType ) ; assertEquals ( this . listener , notificationListener ) ; this . listener = null ; } } class OurServerSideToolkit extends MockServerSideToolkit { long seq = ; NotificationListener listener ; public void runSynchronized ( Runnable runnable ) { runnable . run ( ) ; } @ Override public Notification createNotification ( String type ) { return new Notification ( type , this , seq ++ ) ; } public void sendNotification ( Notification notification ) { if ( listener != null ) { listener . handleNotification ( notification , null ) ; } } } class Result implements StateListener { StateEvent event ; public void jobStateChange ( StateEvent event ) { this . event = event ; } } public void testAddRemoveListener ( ) throws Exception { StatefulHandlerFactory test = new StatefulHandlerFactory ( ) ; assertEquals ( , test . getMBeanNotificationInfo ( ) . length ) ; OurStateful stateful = new OurStateful ( ) ; OurServerSideToolkit serverToolkit = new OurServerSideToolkit ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( stateful , serverToolkit ) ; assertNotNull ( "" , stateful . l ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; Stateful local = new StatefulHandlerFactory . ClientStatefulHandlerFactory ( ) . createClientHandler ( new MockStateful ( ) , clientToolkit ) ; clientToolkit . server = serverHandler ; Result result = new Result ( ) ; local . addStateListener ( result ) ; assertEquals ( "" , JobState . READY , result . event . getState ( ) ) ; Result result2 = new Result ( ) ; local . addStateListener ( result2 ) ; assertEquals ( "" , JobState . READY , result2 . event . getState ( ) ) ; serverToolkit . listener = clientToolkit . listener ; stateful . l . jobStateChange ( new StateEvent ( stateful , JobState . COMPLETE ) ) ; assertEquals ( "" , JobState . COMPLETE , result . event . getState ( ) ) ; assertEquals ( "" , JobState . COMPLETE , result2 . event . getState ( ) ) ; local . removeStateListener ( result ) ; assertNotNull ( clientToolkit . listener ) ; local . removeStateListener ( result2 ) ; assertNull ( clientToolkit . listener ) ; } } package org . oddjob . jmx . handlers ; import java . util . ArrayList ; import java . util . List ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . MockBeanDirectoryOwner ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . jmx . RemoteDirectory ; import org . oddjob . jmx . RemoteDirectoryOwner ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientSession ; import org . oddjob . jmx . client . MockClientSession ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . MockServerContext ; import org . oddjob . jmx . server . MockServerSession ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ServerContext ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerSession ; public class BeanDirectoryHandlerFactoryTest extends TestCase { class ServerSideOwner1 extends MockBeanDirectoryOwner { public BeanDirectory provideBeanDirectory ( ) { return null ; } } class OurServerToolkit1 extends MockServerSideToolkit { @ Override public ServerContext getContext ( ) { return new MockServerContext ( ) { @ Override public ServerId getServerId ( ) { return new ServerId ( "" ) ; } } ; } } class OurClientToolkit extends MockClientSideToolkit { ServerInterfaceHandler handler ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) handler . invoke ( remoteOperation , args ) ; } } public void testGetServerId ( ) { ServerSideOwner1 target = new ServerSideOwner1 ( ) ; BeanDirectoryHandlerFactory test = new BeanDirectoryHandlerFactory ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( target , new OurServerToolkit1 ( ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; clientToolkit . handler = serverHandler ; RemoteDirectoryOwner client = new BeanDirectoryHandlerFactory . ClientBeanDirectoryHandlerFactory ( ) . createClientHandler ( null , clientToolkit ) ; RemoteDirectory remote = client . provideBeanDirectory ( ) ; ServerId id = remote . getServerId ( ) ; assertEquals ( "" , id . toString ( ) ) ; } class ServerSideOwner2 extends MockBeanDirectoryOwner { String lookup ; public BeanDirectory provideBeanDirectory ( ) { return new MockBeanRegistry ( ) { @ Override public Object lookup ( String path ) { lookup = path ; return "" ; } } ; } } class OurServerToolkit2 extends MockServerSideToolkit { @ Override public ServerSession getServerSession ( ) { return new MockServerSession ( ) { @ Override public ObjectName nameFor ( Object object ) { assertEquals ( "" , object ) ; return null ; } } ; } } public void testLookup ( ) { ServerSideOwner2 target = new ServerSideOwner2 ( ) ; BeanDirectoryHandlerFactory test = new BeanDirectoryHandlerFactory ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( target , new OurServerToolkit2 ( ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; clientToolkit . handler = serverHandler ; RemoteDirectoryOwner client = new BeanDirectoryHandlerFactory . ClientBeanDirectoryHandlerFactory ( ) . createClientHandler ( null , clientToolkit ) ; SimpleBeanRegistry registry = new SimpleBeanRegistry ( ) ; registry . register ( "" , client ) ; Object result = registry . lookup ( "" ) ; assertEquals ( "" , result ) ; assertEquals ( "" , target . lookup ) ; } class ServerSideOwner3 extends MockBeanDirectoryOwner { SimpleBeanRegistry registry = new SimpleBeanRegistry ( ) ; { registry . register ( "" , "" ) ; } public BeanDirectory provideBeanDirectory ( ) { return new MockBeanRegistry ( ) { @ Override public < T > Iterable < T > getAllByType ( Class < T > type ) { return registry . getAllByType ( type ) ; } } ; } } ObjectName dogName ; { try { dogName = new ObjectName ( "" , "" , "" ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } class OurServerToolkit3 extends MockServerSideToolkit { @ Override public ServerSession getServerSession ( ) { return new MockServerSession ( ) { @ Override public ObjectName nameFor ( Object object ) { assertEquals ( "" , object ) ; return dogName ; } } ; } } class OurClientToolkit3 extends MockClientSideToolkit { ServerInterfaceHandler handler ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) handler . invoke ( remoteOperation , args ) ; } @ Override public ClientSession getClientSession ( ) { return new MockClientSession ( ) { @ Override public Object create ( ObjectName objectName ) { assertEquals ( dogName , objectName ) ; return "" ; } } ; } } public void testGetAllByType ( ) { ServerSideOwner3 target = new ServerSideOwner3 ( ) ; BeanDirectoryHandlerFactory test = new BeanDirectoryHandlerFactory ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( target , new OurServerToolkit3 ( ) ) ; OurClientToolkit3 clientToolkit = new OurClientToolkit3 ( ) ; clientToolkit . handler = serverHandler ; RemoteDirectoryOwner client = new BeanDirectoryHandlerFactory . ClientBeanDirectoryHandlerFactory ( ) . createClientHandler ( null , clientToolkit ) ; Iterable < Object > iterable = client . provideBeanDirectory ( ) . getAllByType ( Object . class ) ; List < Object > results = new ArrayList < Object > ( ) ; for ( Object o : iterable ) { results . add ( o ) ; } assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( ) ) ; } } package org . oddjob . jmx . handlers ; import java . util . concurrent . atomic . AtomicReference ; import javax . management . Notification ; import javax . management . NotificationListener ; import org . custommonkey . xmlunit . XMLTestCase ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . design . DesignFactory ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . life . ClassLoaderClassResolver ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . ConfigOwnerEvent ; import org . oddjob . arooa . parsing . ConfigSessionEvent ; import org . oddjob . arooa . parsing . ConfigurationOwner ; import org . oddjob . arooa . parsing . ConfigurationSession ; import org . oddjob . arooa . parsing . CutAndPasteSupport ; import org . oddjob . arooa . parsing . DragContext ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . parsing . MockConfigurationOwner ; import org . oddjob . arooa . parsing . MockConfigurationSession ; import org . oddjob . arooa . parsing . OwnerStateListener ; import org . oddjob . arooa . parsing . SessionStateListener ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ServerInterfaceHandler ; public class ComponentOwnerHandlerFactoryTest extends XMLTestCase { private class MySessionLite extends MockConfigurationSession { Object component ; boolean cut ; int pasteIndex ; String pasteText ; boolean commited ; boolean saved ; @ Override public DragPoint dragPointFor ( Object component ) { this . component = component ; return new DragPoint ( ) { public DragTransaction beginChange ( ChangeHow how ) { return new DragTransaction ( ) { @ Override public void rollback ( ) { } @ Override public void commit ( ) { commited = true ; } } ; } public boolean supportsCut ( ) { return true ; } public boolean supportsPaste ( ) { return true ; } public String copy ( ) { return "" ; } public void cut ( ) { cut = true ; } public ConfigurationHandle parse ( ArooaContext parentContext ) throws ArooaParseException { throw new RuntimeException ( "" ) ; } public void paste ( int index , String config ) throws ArooaParseException { pasteIndex = index ; pasteText = config ; } } ; } public void save ( ) throws ArooaParseException { saved = true ; } @ Override public void addSessionStateListener ( SessionStateListener listener ) { } @ Override public void removeSessionStateListener ( SessionStateListener listener ) { } } private class OurDesignFactory implements DesignFactory { @ Override public DesignInstance createDesign ( ArooaElement element , ArooaContext parentContext ) throws ArooaPropertyException { throw new RuntimeException ( "" ) ; } } private class MyComponentOwner extends MockConfigurationOwner { MySessionLite sess = new MySessionLite ( ) ; public ConfigurationSession provideConfigurationSession ( ) { return sess ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { } @ Override public ArooaElement rootElement ( ) { return new ArooaElement ( "" ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return new OurDesignFactory ( ) ; } } private class OurServerSideToolkit extends MockServerSideToolkit { } private class OurClientToolkit extends MockClientSideToolkit { ServerInterfaceHandler handler ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) handler . invoke ( remoteOperation , args ) ; } } public void testBasicInfo ( ) { ComponentOwnerHandlerFactory test = new ComponentOwnerHandlerFactory ( ) ; MyComponentOwner compO = new MyComponentOwner ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( compO , new OurServerSideToolkit ( ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; clientToolkit . handler = serverHandler ; ClientHandlerResolver < ConfigurationOwner > clientResolver = test . clientHandlerFactory ( ) ; ClientInterfaceHandlerFactory < ConfigurationOwner > cihf = clientResolver . resolve ( new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; ConfigurationOwner clientHandler = cihf . createClientHandler ( new MockConfigurationOwner ( ) , clientToolkit ) ; assertEquals ( new ArooaElement ( "" ) , clientHandler . rootElement ( ) ) ; assertEquals ( OurDesignFactory . class , clientHandler . rootDesignFactory ( ) . getClass ( ) ) ; } public void testDragPointOperations ( ) throws ArooaParseException { ComponentOwnerHandlerFactory test = new ComponentOwnerHandlerFactory ( ) ; MyComponentOwner compO = new MyComponentOwner ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( compO , new OurServerSideToolkit ( ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; clientToolkit . handler = serverHandler ; ConfigurationOwner clientHandler = new ComponentOwnerHandlerFactory . ClientConfigurationOwnerHandlerFactory ( ) . createClientHandler ( new MockConfigurationOwner ( ) , clientToolkit ) ; Object ourComponent = new Object ( ) ; DragPoint local = clientHandler . provideConfigurationSession ( ) . dragPointFor ( ourComponent ) ; assertTrue ( local . supportsCut ( ) ) ; assertTrue ( local . supportsPaste ( ) ) ; assertSame ( ourComponent , compO . sess . component ) ; DragTransaction trn = local . beginChange ( ChangeHow . FRESH ) ; local . cut ( ) ; trn . commit ( ) ; assertTrue ( compO . sess . commited ) ; assertTrue ( compO . sess . cut ) ; assertEquals ( "" , local . copy ( ) ) ; local . paste ( , "" ) ; assertEquals ( , compO . sess . pasteIndex ) ; assertEquals ( "" , compO . sess . pasteText ) ; clientHandler . provideConfigurationSession ( ) . save ( ) ; assertTrue ( compO . sess . saved ) ; } private class OurComponentOwner2 extends MockConfigurationOwner { DragPoint drag ; ConfigurationHandle handle ; public ConfigurationSession provideConfigurationSession ( ) { return new MockConfigurationSession ( ) { @ Override public DragPoint dragPointFor ( Object component ) { return drag ; } @ Override public void save ( ) throws ArooaParseException { handle . save ( ) ; } @ Override public void addSessionStateListener ( SessionStateListener listener ) { } @ Override public void removeSessionStateListener ( SessionStateListener listener ) { } } ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { } @ Override public ArooaElement rootElement ( ) { return new ArooaElement ( "" ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return new OurDesignFactory ( ) ; } } public void testEditOperations ( ) throws Exception { Object root = new Object ( ) ; XMLConfiguration config = new XMLConfiguration ( "" , "" ) ; final AtomicReference < String > savedXML = new AtomicReference < String > ( ) ; config . setSaveHandler ( new XMLConfiguration . SaveHandler ( ) { @ Override public void acceptXML ( String xml ) { savedXML . set ( xml ) ; } } ) ; StandardArooaParser parser = new StandardArooaParser ( root ) ; final ConfigurationHandle handle = parser . parse ( config ) ; DragContext drag = new DragContext ( handle . getDocumentContext ( ) ) ; ComponentOwnerHandlerFactory test = new ComponentOwnerHandlerFactory ( ) ; OurComponentOwner2 compO = new OurComponentOwner2 ( ) ; compO . drag = drag ; compO . handle = handle ; ServerInterfaceHandler serverHandler = test . createServerHandler ( compO , new OurServerSideToolkit ( ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; clientToolkit . handler = serverHandler ; ConfigurationOwner clientHandler = new ComponentOwnerHandlerFactory . ClientConfigurationOwnerHandlerFactory ( ) . createClientHandler ( new MockConfigurationOwner ( ) , clientToolkit ) ; DragPoint local = clientHandler . provideConfigurationSession ( ) . dragPointFor ( root ) ; XMLArooaParser parser2 = new XMLArooaParser ( ) ; ConfigurationHandle handle2 = parser2 . parse ( local ) ; ArooaContext context = handle2 . getDocumentContext ( ) ; XMLConfiguration replacement = new XMLConfiguration ( "" , "" ) ; CutAndPasteSupport . replace ( context . getParent ( ) , context , replacement ) ; handle2 . save ( ) ; clientHandler . provideConfigurationSession ( ) . save ( ) ; String expected = "" + System . getProperty ( "" ) ; assertXMLEqual ( expected , savedXML . get ( ) ) ; } private class NullConfigurationOwner extends MockConfigurationOwner { public ConfigurationSession provideConfigurationSession ( ) { return null ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { } @ Override public ArooaElement rootElement ( ) { return new ArooaElement ( "" ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return new OurDesignFactory ( ) ; } } public void testNullConfiguration ( ) { ComponentOwnerHandlerFactory test = new ComponentOwnerHandlerFactory ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( new NullConfigurationOwner ( ) , new OurServerSideToolkit ( ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; clientToolkit . handler = serverHandler ; ConfigurationOwner clientHandler = new ComponentOwnerHandlerFactory . ClientConfigurationOwnerHandlerFactory ( ) . createClientHandler ( new MockConfigurationOwner ( ) , clientToolkit ) ; ConfigurationSession configurationSession = clientHandler . provideConfigurationSession ( ) ; assertNull ( configurationSession ) ; } private class NullDropPointOwner extends MockConfigurationOwner { public ConfigurationSession provideConfigurationSession ( ) { return new MockConfigurationSession ( ) { public DragPoint dragPointFor ( Object component ) { return null ; } @ Override public void addSessionStateListener ( SessionStateListener listener ) { } @ Override public void removeSessionStateListener ( SessionStateListener listener ) { } } ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { } @ Override public ArooaElement rootElement ( ) { return new ArooaElement ( "" ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return new OurDesignFactory ( ) ; } } public void testNullDropPointConfiguration ( ) { ComponentOwnerHandlerFactory test = new ComponentOwnerHandlerFactory ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( new NullDropPointOwner ( ) , new OurServerSideToolkit ( ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; clientToolkit . handler = serverHandler ; ConfigurationOwner clientHandler = new ComponentOwnerHandlerFactory . ClientConfigurationOwnerHandlerFactory ( ) . createClientHandler ( new MockConfigurationOwner ( ) , clientToolkit ) ; ConfigurationSession configurationSession = clientHandler . provideConfigurationSession ( ) ; assertNotNull ( configurationSession ) ; DragPoint dragPoint = configurationSession . dragPointFor ( clientHandler ) ; assertNull ( dragPoint ) ; } private class ModifiedNotifySession extends MockConfigurationSession { SessionStateListener listener ; @ Override public void addSessionStateListener ( SessionStateListener listener ) { assertNull ( this . listener ) ; this . listener = listener ; } @ Override public void removeSessionStateListener ( SessionStateListener listener ) { assertEquals ( this . listener , listener ) ; this . listener = null ; } void modified ( ) { this . listener . sessionModifed ( new ConfigSessionEvent ( this ) ) ; } void saved ( ) { this . listener . sessionSaved ( new ConfigSessionEvent ( this ) ) ; } } private class ModifiedOwner extends MockConfigurationOwner { final ModifiedNotifySession session = new ModifiedNotifySession ( ) ; public ConfigurationSession provideConfigurationSession ( ) { return session ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { } @ Override public ArooaElement rootElement ( ) { return new ArooaElement ( "" ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return new OurDesignFactory ( ) ; } } private class SessionResultListener implements SessionStateListener { ConfigSessionEvent event ; boolean modified ; public void sessionModifed ( ConfigSessionEvent event ) { this . event = event ; modified = true ; } public void sessionSaved ( ConfigSessionEvent event ) { this . event = event ; modified = false ; } } private class ModifiedClientToolkit extends OurClientToolkit { ModifiedServerSideToolkit serverToolkit ; @ Override public void registerNotificationListener ( String eventType , NotificationListener notificationListener ) { assertEquals ( ComponentOwnerHandlerFactory . MODIFIED_NOTIF_TYPE , eventType ) ; assertNull ( serverToolkit . listener ) ; serverToolkit . listener = notificationListener ; } @ Override public void removeNotificationListener ( String eventType , NotificationListener notificationListener ) { assertEquals ( serverToolkit . listener , notificationListener ) ; serverToolkit . listener = null ; } } private class ModifiedServerSideToolkit extends MockServerSideToolkit { NotificationListener listener ; @ Override public Notification createNotification ( String type ) { assertEquals ( ComponentOwnerHandlerFactory . MODIFIED_NOTIF_TYPE , type ) ; return new Notification ( type , this , ) ; } @ Override public void sendNotification ( Notification notification ) { if ( listener != null ) { listener . handleNotification ( notification , null ) ; } } @ Override public void runSynchronized ( Runnable runnable ) { runnable . run ( ) ; } } public void testSessionStateNotification ( ) { ComponentOwnerHandlerFactory test = new ComponentOwnerHandlerFactory ( ) ; ModifiedOwner owner = new ModifiedOwner ( ) ; ModifiedServerSideToolkit serverToolkit = new ModifiedServerSideToolkit ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( owner , serverToolkit ) ; ModifiedClientToolkit clientToolkit = new ModifiedClientToolkit ( ) ; clientToolkit . handler = serverHandler ; clientToolkit . serverToolkit = serverToolkit ; ConfigurationOwner clientHandler = new ComponentOwnerHandlerFactory . ClientConfigurationOwnerHandlerFactory ( ) . createClientHandler ( new MockConfigurationOwner ( ) , clientToolkit ) ; SessionResultListener results = new SessionResultListener ( ) ; clientHandler . provideConfigurationSession ( ) . addSessionStateListener ( results ) ; assertEquals ( false , results . modified ) ; assertNull ( results . event ) ; owner . session . modified ( ) ; assertEquals ( true , results . modified ) ; assertNotNull ( results . event ) ; owner . session . saved ( ) ; assertEquals ( false , results . modified ) ; assertNotNull ( results . event ) ; clientHandler . provideConfigurationSession ( ) . removeSessionStateListener ( results ) ; owner . session . modified ( ) ; assertNotNull ( results . event ) ; assertEquals ( false , results . modified ) ; } private class NotifyingOwner extends MockConfigurationOwner { OwnerStateListener listener ; ConfigurationSession session ; public ConfigurationSession provideConfigurationSession ( ) { return session ; } public void setSession ( ConfigurationSession session ) { assertNotNull ( session ) ; this . session = session ; this . listener . sessionChanged ( new ConfigOwnerEvent ( this , ConfigOwnerEvent . Change . SESSION_CREATED ) ) ; } @ Override public void addOwnerStateListener ( OwnerStateListener listener ) { assertNull ( this . listener ) ; this . listener = listener ; } @ Override public void removeOwnerStateListener ( OwnerStateListener listener ) { assertEquals ( this . listener , listener ) ; this . listener = null ; } @ Override public ArooaElement rootElement ( ) { return new ArooaElement ( "" ) ; } @ Override public DesignFactory rootDesignFactory ( ) { return new OurDesignFactory ( ) ; } } private class ResultListener implements OwnerStateListener { ConfigOwnerEvent event ; int count ; public void sessionChanged ( ConfigOwnerEvent event ) { this . event = event ; ++ count ; } } private class NotifyClientToolkit extends OurClientToolkit { NotifyServerSideToolkit serverToolkit ; @ Override public void registerNotificationListener ( String eventType , NotificationListener notificationListener ) { assertEquals ( ComponentOwnerHandlerFactory . CHANGE_NOTIF_TYPE , eventType ) ; assertNull ( serverToolkit . listener ) ; serverToolkit . listener = notificationListener ; } @ Override public void removeNotificationListener ( String eventType , NotificationListener notificationListener ) { assertEquals ( serverToolkit . listener , notificationListener ) ; serverToolkit . listener = null ; } } private class NotifyServerSideToolkit extends MockServerSideToolkit { NotificationListener listener ; @ Override public Notification createNotification ( String type ) { assertEquals ( ComponentOwnerHandlerFactory . CHANGE_NOTIF_TYPE , type ) ; return new Notification ( type , this , ) ; } @ Override public void sendNotification ( Notification notification ) { if ( listener != null ) { listener . handleNotification ( notification , null ) ; } } @ Override public void runSynchronized ( Runnable runnable ) { runnable . run ( ) ; } } public void testSessionChangeNotification ( ) { ComponentOwnerHandlerFactory test = new ComponentOwnerHandlerFactory ( ) ; NotifyingOwner owner = new NotifyingOwner ( ) ; NotifyServerSideToolkit serverToolkit = new NotifyServerSideToolkit ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( owner , serverToolkit ) ; NotifyClientToolkit clientToolkit = new NotifyClientToolkit ( ) ; clientToolkit . handler = serverHandler ; clientToolkit . serverToolkit = serverToolkit ; ConfigurationOwner clientProxy = new MockConfigurationOwner ( ) ; ConfigurationOwner clientHandler = new ComponentOwnerHandlerFactory . ClientConfigurationOwnerHandlerFactory ( ) . createClientHandler ( clientProxy , clientToolkit ) ; ResultListener results = new ResultListener ( ) ; clientHandler . addOwnerStateListener ( results ) ; assertEquals ( , results . count ) ; ConfigurationSession clientSession = clientHandler . provideConfigurationSession ( ) ; assertNull ( clientSession ) ; owner . setSession ( new ModifiedNotifySession ( ) ) ; assertEquals ( clientProxy , results . event . getSource ( ) ) ; assertEquals ( , results . count ) ; clientSession = clientHandler . provideConfigurationSession ( ) ; assertNotNull ( clientSession ) ; clientHandler . removeOwnerStateListener ( results ) ; owner . setSession ( new ModifiedNotifySession ( ) ) ; assertEquals ( , results . count ) ; } } package org . oddjob . jmx . handlers ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import junit . framework . TestCase ; public class OddjobTransportableExceptionTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddjobTransportableExceptionTest . class ) ; public void testCreate ( ) throws Exception { Exception e = new Exception ( "" , new Exception ( "" , new Exception ( "" ) ) ) ; OddjobTransportableException test = new OddjobTransportableException ( e ) ; OddjobTransportableException copy1 = Helper . copy ( test ) ; logger . info ( "" , copy1 ) ; assertEquals ( "" , copy1 . toString ( ) ) ; Throwable copy2 = copy1 . getCause ( ) ; assertEquals ( "" , copy2 . toString ( ) ) ; Throwable copy3 = copy2 . getCause ( ) ; assertEquals ( "" , copy3 . toString ( ) ) ; } public void testNullMessage ( ) { Exception e = new Exception ( ) ; OddjobTransportableException test = new OddjobTransportableException ( e ) ; assertNull ( test . getMessage ( ) ) ; } } package org . oddjob . jmx . handlers ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . server . MockServerSession ; import org . oddjob . jmx . server . OddjobMBean ; import org . oddjob . jmx . server . OddjobMBeanFactory ; import org . oddjob . jmx . server . ServerContext ; import org . oddjob . jmx . server . ServerContextImpl ; import org . oddjob . jmx . server . ServerInterfaceManagerFactory ; import org . oddjob . jmx . server . ServerInterfaceManagerFactoryImpl ; import org . oddjob . jmx . server . ServerModel ; import org . oddjob . jmx . server . ServerModelImpl ; import org . oddjob . logging . LogEnabled ; import org . oddjob . util . MockThreadManager ; public class LogEnabledHandlerFactoryTest extends TestCase { private class MockLogEnabled implements LogEnabled { public String loggerName ( ) { return "" ; } } private class OurHierarchicalRegistry extends MockBeanRegistry { @ Override public String getIdFor ( Object component ) { assertNotNull ( component ) ; return "" ; } } private class OurServerSession extends MockServerSession { ArooaSession session = new StandardArooaSession ( ) ; @ Override public ObjectName nameFor ( Object object ) { return OddjobMBeanFactory . objectName ( ) ; } @ Override public ArooaSession getArooaSession ( ) { return session ; } } public void testLoggerName ( ) throws Exception { MockLogEnabled target = new MockLogEnabled ( ) ; ServerInterfaceManagerFactory imf = new ServerInterfaceManagerFactoryImpl ( ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , imf ) ; ServerContext serverContext = new ServerContextImpl ( target , sm , new OurHierarchicalRegistry ( ) ) ; OddjobMBean ojmb = new OddjobMBean ( target , new OurServerSession ( ) , serverContext ) ; String loggerName = ( String ) ojmb . invoke ( "" , new Object [ ] , new String [ ] ) ; assertEquals ( "" , "" , loggerName ) ; } } package org . oddjob . jmx . handlers ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import javax . management . MBeanException ; import javax . management . MalformedObjectNameException ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import junit . framework . TestCase ; import org . oddjob . Structural ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . ClientSession ; import org . oddjob . jmx . client . MockClientSession ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . MockServerContext ; import org . oddjob . jmx . server . MockServerSession ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ServerContext ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerLoopBackException ; import org . oddjob . jmx . server . ServerSession ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class StructuralHandlerFactoryTest extends TestCase { int unique ; class OurHierarchicalRegistry extends MockBeanRegistry { @ Override public String getIdFor ( Object component ) { assertNotNull ( component ) ; return "" + unique ++ ; } } class OurServerSideToolkit extends MockServerSideToolkit { List < Notification > notifications = new ArrayList < Notification > ( ) ; Map < ObjectName , Object > children = new HashMap < ObjectName , Object > ( ) ; String name = "" ; int seq = ; @ Override public void sendNotification ( Notification notification ) { notifications . add ( notification ) ; } @ Override public void runSynchronized ( Runnable runnable ) { runnable . run ( ) ; } @ Override public ServerSession getServerSession ( ) { return new MockServerSession ( ) { @ Override public ObjectName createMBeanFor ( Object child , ServerContext childContext ) { try { ObjectName on = new ObjectName ( "" + name ) ; children . put ( on , child ) ; name = name + "" ; return on ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } @ Override public void destroy ( ObjectName childName ) { Object child = children . remove ( childName ) ; assertNotNull ( child ) ; } } ; } @ Override public ServerContext getContext ( ) { return new MockServerContext ( ) { @ Override public ServerContext addChild ( Object child ) throws ServerLoopBackException { return new MockServerContext ( ) ; } } ; } @ Override public Notification createNotification ( String type ) { return new Notification ( type , new Object ( ) , seq ++ ) ; } } class MyStructural implements Structural { ChildHelper < Object > helper = new ChildHelper < Object > ( this ) ; public void addStructuralListener ( StructuralListener listener ) { helper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { helper . removeStructuralListener ( listener ) ; } } public void testServerSide ( ) throws MBeanException , ReflectionException , MalformedObjectNameException , NullPointerException { MyStructural structural = new MyStructural ( ) ; structural . helper . insertChild ( , new Object ( ) ) ; OurServerSideToolkit toolkit = new OurServerSideToolkit ( ) ; StructuralHandlerFactory test = new StructuralHandlerFactory ( ) ; ServerInterfaceHandler handler = test . createServerHandler ( structural , toolkit ) ; assertEquals ( , toolkit . notifications . size ( ) ) ; Notification [ ] last = ( Notification [ ] ) handler . invoke ( StructuralHandlerFactory . SYNCHRONIZE , new Object [ ] ) ; assertEquals ( , last . length ) ; Notification last0 = last [ ] ; assertEquals ( , last0 . getSequenceNumber ( ) ) ; StructuralHandlerFactory . ChildData lastData0 = ( StructuralHandlerFactory . ChildData ) last0 . getUserData ( ) ; assertEquals ( , lastData0 . getChildObjectNames ( ) . length ) ; assertEquals ( new ObjectName ( "" ) , lastData0 . getChildObjectNames ( ) [ ] ) ; Object child = new Object ( ) ; structural . helper . insertChild ( , child ) ; assertEquals ( , toolkit . notifications . size ( ) ) ; Notification n0 = toolkit . notifications . get ( ) ; assertEquals ( , n0 . getSequenceNumber ( ) ) ; StructuralHandlerFactory . ChildData childData0 = ( StructuralHandlerFactory . ChildData ) n0 . getUserData ( ) ; assertEquals ( , childData0 . getChildObjectNames ( ) . length ) ; assertEquals ( new ObjectName ( "" ) , lastData0 . getChildObjectNames ( ) [ ] ) ; Notification n1 = toolkit . notifications . get ( ) ; assertEquals ( , n1 . getSequenceNumber ( ) ) ; assertEquals ( StructuralHandlerFactory . STRUCTURAL_NOTIF_TYPE , n1 . getType ( ) ) ; structural . helper . insertChild ( , new Object ( ) ) ; assertEquals ( , toolkit . notifications . size ( ) ) ; Notification n2 = toolkit . notifications . get ( ) ; assertEquals ( , n2 . getSequenceNumber ( ) ) ; StructuralHandlerFactory . ChildData childData2 = ( StructuralHandlerFactory . ChildData ) n2 . getUserData ( ) ; assertEquals ( , childData2 . getChildObjectNames ( ) . length ) ; assertEquals ( new ObjectName ( "" ) , childData2 . getChildObjectNames ( ) [ ] ) ; assertEquals ( new ObjectName ( "" ) , childData2 . getChildObjectNames ( ) [ ] ) ; assertEquals ( new ObjectName ( "" ) , childData2 . getChildObjectNames ( ) [ ] ) ; structural . helper . removeChildAt ( ) ; assertEquals ( , toolkit . notifications . size ( ) ) ; Notification n3 = toolkit . notifications . get ( ) ; assertEquals ( , n3 . getSequenceNumber ( ) ) ; StructuralHandlerFactory . ChildData childData3 = ( StructuralHandlerFactory . ChildData ) n3 . getUserData ( ) ; assertEquals ( , childData3 . getChildObjectNames ( ) . length ) ; assertEquals ( new ObjectName ( "" ) , childData3 . getChildObjectNames ( ) [ ] ) ; assertEquals ( new ObjectName ( "" ) , childData3 . getChildObjectNames ( ) [ ] ) ; handler . destroy ( ) ; assertTrue ( structural . helper . isNoListeners ( ) ) ; } class OurClientToolkit extends MockClientSideToolkit { boolean subscribed ; NotificationListener handler ; Map < ObjectName , Object > created = new HashMap < ObjectName , Object > ( ) ; Map < Object , ObjectName > toNames = new HashMap < Object , ObjectName > ( ) ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { if ( StructuralHandlerFactory . SYNCHRONIZE . equals ( remoteOperation ) ) { subscribed = true ; return ( T ) new Notification [ ] ; } return null ; } public void registerNotificationListener ( String eventType , NotificationListener notificationListener ) { if ( StructuralHandlerFactory . STRUCTURAL_NOTIF_TYPE . equals ( eventType ) ) { if ( handler != null ) { throw new RuntimeException ( "" ) ; } this . handler = notificationListener ; } else { throw new RuntimeException ( "" ) ; } } @ Override public ClientSession getClientSession ( ) { return new MockClientSession ( ) { public Object create ( ObjectName objectName ) { Object child = new Object ( ) ; created . put ( objectName , child ) ; toNames . put ( child , objectName ) ; return child ; } @ Override public void destroy ( Object proxy ) { ObjectName objectName = toNames . remove ( proxy ) ; created . remove ( objectName ) ; } } ; } } class ResultListener implements StructuralListener { List < Object > children = new ArrayList < Object > ( ) ; public void childAdded ( StructuralEvent event ) { children . add ( event . getIndex ( ) , event . getChild ( ) ) ; } public void childRemoved ( StructuralEvent event ) { children . remove ( event . getIndex ( ) ) ; } } class OurStructural implements Structural { public void addStructuralListener ( StructuralListener listener ) { } public void removeStructuralListener ( StructuralListener listener ) { } } public void testClientSide ( ) throws MalformedObjectNameException , NullPointerException { ClientInterfaceHandlerFactory < Structural > clientFactory = new StructuralHandlerFactory . ClientStructuralHandlerFactory ( ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; OurStructural proxy = new OurStructural ( ) ; Structural handler = clientFactory . createClientHandler ( proxy , clientToolkit ) ; ResultListener results = new ResultListener ( ) ; ( ( Structural ) handler ) . addStructuralListener ( results ) ; StructuralHandlerFactory . ChildData data1 = new StructuralHandlerFactory . ChildData ( new ObjectName [ ] { new ObjectName ( "" ) } ) ; Notification n1 = new Notification ( "" , new Object ( ) , ) ; n1 . setUserData ( data1 ) ; clientToolkit . handler . handleNotification ( n1 , null ) ; assertEquals ( , results . children . size ( ) ) ; Object child1 = results . children . get ( ) ; assertEquals ( clientToolkit . created . get ( new ObjectName ( "" ) ) , child1 ) ; StructuralHandlerFactory . ChildData data2 = new StructuralHandlerFactory . ChildData ( new ObjectName [ ] { new ObjectName ( "" ) , new ObjectName ( "" ) } ) ; Notification n2 = new Notification ( "" , new Object ( ) , ) ; n2 . setUserData ( data2 ) ; clientToolkit . handler . handleNotification ( n2 , null ) ; assertEquals ( , results . children . size ( ) ) ; Object child2 = results . children . get ( ) ; assertEquals ( clientToolkit . created . get ( new ObjectName ( "" ) ) , child2 ) ; StructuralHandlerFactory . ChildData data3 = new StructuralHandlerFactory . ChildData ( new ObjectName [ ] { new ObjectName ( "" ) , new ObjectName ( "" ) , new ObjectName ( "" ) } ) ; Notification n3 = new Notification ( "" , new Object ( ) , ) ; n3 . setUserData ( data3 ) ; clientToolkit . handler . handleNotification ( n3 , null ) ; assertEquals ( , results . children . size ( ) ) ; Object child3 = results . children . get ( ) ; assertEquals ( clientToolkit . created . get ( new ObjectName ( "" ) ) , child3 ) ; StructuralHandlerFactory . ChildData data4 = new StructuralHandlerFactory . ChildData ( new ObjectName [ ] { new ObjectName ( "" ) , new ObjectName ( "" ) } ) ; Notification n4 = new Notification ( "" , new Object ( ) , ) ; n4 . setUserData ( data4 ) ; clientToolkit . handler . handleNotification ( n4 , null ) ; assertEquals ( , results . children . size ( ) ) ; Object child4 = results . children . get ( ) ; assertEquals ( clientToolkit . created . get ( new ObjectName ( "" ) ) , child4 ) ; } } package org . oddjob . jmx . handlers ; import java . util . Map ; import junit . framework . TestCase ; import org . oddjob . Describeable ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . ClassLoaderClassResolver ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . MockServerSession ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ServerInterfaceHandler ; import org . oddjob . jmx . server . ServerSession ; public class DescribeableHandlerFactoryTest extends TestCase { private class OurClientToolkit extends MockClientSideToolkit { ServerInterfaceHandler serverHandler ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) serverHandler . invoke ( remoteOperation , args ) ; } } private class OurServerToolkit extends MockServerSideToolkit { ArooaSession session = new StandardArooaSession ( ) ; @ Override public ServerSession getServerSession ( ) { return new MockServerSession ( ) { @ Override public ArooaSession getArooaSession ( ) { return session ; } } ; } } public class Apple { public String getColour ( ) { return "" ; } protected String getType ( ) { return "" ; } } public void testAllOperations ( ) { DescribeableHandlerFactory test = new DescribeableHandlerFactory ( ) ; ClientHandlerResolver < Describeable > resolver = test . clientHandlerFactory ( ) ; ClientInterfaceHandlerFactory < Describeable > clientFactory = resolver . resolve ( new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; OurServerToolkit serverToolkit = new OurServerToolkit ( ) ; clientToolkit . serverHandler = test . createServerHandler ( new Apple ( ) , serverToolkit ) ; Describeable proxy = clientFactory . createClientHandler ( null , clientToolkit ) ; Map < String , String > results = proxy . describe ( ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( "" ) ) ; assertEquals ( Apple . class . toString ( ) , results . get ( "" ) ) ; } } package org . oddjob . jmx . handlers ; import javax . management . MBeanOperationInfo ; import junit . framework . TestCase ; import org . oddjob . arooa . life . ClassLoaderClassResolver ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . client . ClientInterfaceHandlerFactory ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ServerInfo ; import org . oddjob . jmx . server . ServerInterfaceHandler ; public class RemoteOddjobHandlerFactoryTest extends TestCase { private class OurClientToolkit extends MockClientSideToolkit { ServerInterfaceHandler serverHandler ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) serverHandler . invoke ( remoteOperation , args ) ; } } private class OurServerToolkit extends MockServerSideToolkit { boolean noop ; @ Override public RemoteOddjobBean getRemoteBean ( ) { return new RemoteOddjobBean ( ) { public ServerInfo serverInfo ( ) { return null ; } public void noop ( ) { noop = true ; } } ; } } public void testAllOperations ( ) { RemoteOddjobHandlerFactory test = new RemoteOddjobHandlerFactory ( ) ; ClientHandlerResolver < RemoteOddjobBean > resolver = test . clientHandlerFactory ( ) ; ClientInterfaceHandlerFactory < RemoteOddjobBean > clientFactory = resolver . resolve ( new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; OurClientToolkit clientToolkit = new OurClientToolkit ( ) ; OurServerToolkit serverToolkit = new OurServerToolkit ( ) ; clientToolkit . serverHandler = test . createServerHandler ( null , serverToolkit ) ; RemoteOddjobBean proxy = clientFactory . createClientHandler ( null , clientToolkit ) ; assertFalse ( serverToolkit . noop ) ; proxy . noop ( ) ; assertTrue ( serverToolkit . noop ) ; ServerInfo serverInfo = proxy . serverInfo ( ) ; assertNull ( serverInfo ) ; } public void testOperationInfo ( ) { RemoteOddjobHandlerFactory test = new RemoteOddjobHandlerFactory ( ) ; MBeanOperationInfo [ ] opInfo = test . getMBeanOperationInfo ( ) ; assertEquals ( , opInfo . length ) ; MBeanOperationInfo opInfo0 = opInfo [ ] ; assertEquals ( "" , opInfo0 . getName ( ) ) ; } } package org . oddjob . jmx . handlers ; import javax . management . Notification ; import javax . management . NotificationListener ; import javax . swing . ImageIcon ; import junit . framework . TestCase ; import org . oddjob . Iconic ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . jmx . RemoteOperation ; import org . oddjob . jmx . client . MockClientSideToolkit ; import org . oddjob . jmx . server . MockServerSideToolkit ; import org . oddjob . jmx . server . ServerInterfaceHandler ; public class IconicHandlerFactoryTest extends TestCase { class OurIconic implements Iconic { IconHelper helper = new IconHelper ( this ) ; { helper . changeIcon ( IconHelper . EXECUTING ) ; } public void addIconListener ( IconListener listener ) { helper . addIconListener ( listener ) ; } public void removeIconListener ( IconListener listener ) { helper . removeIconListener ( listener ) ; } public ImageIcon iconForId ( String iconId ) { return helper . iconForId ( iconId ) ; } } class OurClientToolkit extends MockClientSideToolkit { ServerInterfaceHandler server ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) server . invoke ( remoteOperation , args ) ; } } class OurServerToolkit extends MockServerSideToolkit { long seq = ; @ Override public void runSynchronized ( Runnable runnable ) { runnable . run ( ) ; } @ Override public Notification createNotification ( String type ) { return new Notification ( type , this , seq ++ ) ; } @ Override public void sendNotification ( Notification notification ) { } } public void testClientIconFor ( ) { OurIconic iconic = new OurIconic ( ) ; IconicHandlerFactory test = new IconicHandlerFactory ( ) ; OurServerToolkit serverToolkit = new OurServerToolkit ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( iconic , serverToolkit ) ; OurClientToolkit toolkit = new OurClientToolkit ( ) ; toolkit . server = serverHandler ; Iconic h = new IconicHandlerFactory . ClientIconicHandlerFactory ( ) . createClientHandler ( iconic , toolkit ) ; ImageIcon result = h . iconForId ( IconHelper . EXECUTING ) ; assertEquals ( "" , result . getDescription ( ) ) ; } class OurClientToolkit2 extends MockClientSideToolkit { ServerInterfaceHandler server ; NotificationListener listener ; @ SuppressWarnings ( "" ) @ Override public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { return ( T ) server . invoke ( remoteOperation , args ) ; } public void registerNotificationListener ( String eventType , NotificationListener notificationListener ) { if ( listener != null ) { throw new RuntimeException ( "" ) ; } assertEquals ( IconicHandlerFactory . ICON_CHANGED_NOTIF_TYPE , eventType ) ; this . listener = notificationListener ; } @ Override public void removeNotificationListener ( String eventType , NotificationListener notificationListener ) { if ( listener == null ) { throw new RuntimeException ( "" ) ; } assertEquals ( IconicHandlerFactory . ICON_CHANGED_NOTIF_TYPE , eventType ) ; assertEquals ( this . listener , notificationListener ) ; this . listener = null ; } } class OurServerToolkit2 extends MockServerSideToolkit { long seq = ; NotificationListener listener ; @ Override public void runSynchronized ( Runnable runnable ) { runnable . run ( ) ; } @ Override public Notification createNotification ( String type ) { return new Notification ( type , this , seq ++ ) ; } @ Override public void sendNotification ( Notification notification ) { if ( listener != null ) { listener . handleNotification ( notification , null ) ; } } } class Result implements IconListener { IconEvent event ; public void iconEvent ( IconEvent e ) { event = e ; } } public void testIconListeners ( ) { OurIconic iconic = new OurIconic ( ) ; IconicHandlerFactory test = new IconicHandlerFactory ( ) ; OurServerToolkit2 serverToolkit = new OurServerToolkit2 ( ) ; ServerInterfaceHandler serverHandler = test . createServerHandler ( iconic , serverToolkit ) ; OurClientToolkit2 clientToolkit = new OurClientToolkit2 ( ) ; clientToolkit . server = serverHandler ; Iconic local = new IconicHandlerFactory . ClientIconicHandlerFactory ( ) . createClientHandler ( iconic , clientToolkit ) ; Result result = new Result ( ) ; local . addIconListener ( result ) ; assertEquals ( IconHelper . EXECUTING , result . event . getIconId ( ) ) ; Result result2 = new Result ( ) ; local . addIconListener ( result2 ) ; assertEquals ( IconHelper . EXECUTING , result2 . event . getIconId ( ) ) ; serverToolkit . listener = clientToolkit . listener ; iconic . helper . changeIcon ( IconHelper . COMPLETE ) ; assertEquals ( IconHelper . COMPLETE , result . event . getIconId ( ) ) ; assertEquals ( IconHelper . COMPLETE , result2 . event . getIconId ( ) ) ; local . removeIconListener ( result2 ) ; assertNotNull ( clientToolkit . listener ) ; local . removeIconListener ( result ) ; assertNull ( clientToolkit . listener ) ; } } package org . oddjob . jmx ; import java . io . FilterInputStream ; import java . io . FilterOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . Socket ; import java . net . SocketException ; import java . net . SocketImpl ; import java . net . UnknownHostException ; import org . apache . log4j . Logger ; public class FailableSocket extends Socket { private static final Logger logger = Logger . getLogger ( FailableSocket . class ) ; volatile boolean fail ; public FailableSocket ( String host , int port ) throws UnknownHostException , IOException { super ( host , port ) ; } public FailableSocket ( SocketImpl impl ) throws SocketException { super ( impl ) ; } @ Override public InputStream getInputStream ( ) throws IOException { return new FailableInputStream ( super . getInputStream ( ) ) ; } @ Override public OutputStream getOutputStream ( ) throws IOException { return new FailableOutputStream ( super . getOutputStream ( ) ) ; } class FailableInputStream extends FilterInputStream { public FailableInputStream ( InputStream in ) { super ( in ) ; } @ Override public int read ( ) throws IOException { assertOK ( ) ; return super . read ( ) ; } @ Override public int read ( byte [ ] b ) throws IOException { assertOK ( ) ; return super . read ( b ) ; } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { assertOK ( ) ; return super . read ( b , off , len ) ; } } class FailableOutputStream extends FilterOutputStream { public FailableOutputStream ( OutputStream out ) { super ( out ) ; } @ Override public void write ( int b ) throws IOException { assertOK ( ) ; super . write ( b ) ; } @ Override public void write ( byte [ ] b ) throws IOException { assertOK ( ) ; super . write ( b ) ; } @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { assertOK ( ) ; super . write ( b , off , len ) ; } } public void setFail ( boolean fail ) { this . fail = fail ; } void assertOK ( ) throws IOException { if ( fail ) { IOException e = new IOException ( "" ) ; logger . error ( "" , e ) ; throw e ; } } } package org . oddjob . jmx ; import java . net . MalformedURLException ; import javax . management . remote . JMXServiceURL ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class TogetherLookupTest extends TestCase { public void testSameRegistry ( ) throws ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; String address = new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( address ) ; client . run ( ) ; RemoteDirectory remote = client . provideBeanDirectory ( ) ; assertEquals ( "" , remote . getServerId ( ) . toString ( ) ) ; Object fruit = remote . lookup ( "" ) ; assertNotNull ( fruit ) ; RemoteRegistryCrawler crawler = new RemoteRegistryCrawler ( remote ) ; assertEquals ( new Address ( remote . getServerId ( ) , new Path ( "" ) ) , crawler . addressFor ( fruit ) ) ; client . destroy ( ) ; oddjob . destroy ( ) ; } public void testDifferentRegistrySameServer ( ) throws ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; String address = new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( address ) ; client . run ( ) ; RemoteDirectory remote = client . provideBeanDirectory ( ) ; Object apples = remote . lookup ( "" ) ; assertNotNull ( apples ) ; RemoteRegistryCrawler crawler = new RemoteRegistryCrawler ( remote ) ; assertEquals ( new Address ( remote . getServerId ( ) , new Path ( "" ) ) , crawler . addressFor ( apples ) ) ; client . destroy ( ) ; oddjob . destroy ( ) ; } public void testDifferentServer ( ) throws ArooaConversionException , MalformedURLException { String xml2 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setConfiguration ( new XMLConfiguration ( "" , xml2 ) ) ; oddjob2 . run ( ) ; String xml1 = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String address2 = new OddjobLookup ( oddjob2 ) . lookup ( "" , String . class ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setConfiguration ( new XMLConfiguration ( "" , xml1 ) ) ; oddjob1 . setArgs ( new String [ ] { address2 } ) ; oddjob1 . run ( ) ; String address1 = new OddjobLookup ( oddjob1 ) . lookup ( "" , String . class ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( address1 ) ; client . run ( ) ; RemoteDirectory remote = client . provideBeanDirectory ( ) ; Object apples = remote . lookup ( "" ) ; assertNotNull ( apples ) ; RemoteRegistryCrawler crawler = new RemoteRegistryCrawler ( remote ) ; JMXServiceURL url = new JMXServiceURL ( address2 ) ; assertEquals ( new Address ( new ServerId ( url . getURLPath ( ) ) , new Path ( "" ) ) . toString ( ) , crawler . addressFor ( apples ) . toString ( ) ) ; client . destroy ( ) ; oddjob1 . destroy ( ) ; oddjob2 . destroy ( ) ; } } package org . oddjob . jmx ; import java . io . IOException ; import java . net . ServerSocket ; import java . net . SocketException ; import java . net . SocketImpl ; public class FailableServerSocket extends ServerSocket { public FailableServerSocket ( int port ) throws IOException { super ( port ) ; } public FailableSocket accept ( ) throws IOException { if ( isClosed ( ) ) throw new SocketException ( "" ) ; if ( ! isBound ( ) ) throw new SocketException ( "" ) ; FailableSocket s = new FailableSocket ( ( SocketImpl ) null ) ; implAccept ( s ) ; return s ; } } package org . oddjob . jmx . client ; import junit . framework . TestCase ; public class ClientInterfaceManagerFactoryTest extends TestCase { interface Foo { public void foo ( ) ; } public void testInvoke ( ) throws Throwable { class MockFoo implements Foo { boolean invoked ; public void foo ( ) { invoked = true ; } } MockFoo foo = new MockFoo ( ) ; class FooClientHandlerFactory extends MockClientInterfaceHandlerFactory < Foo > { private static final long serialVersionUID = ; public Foo createClientHandler ( Foo proxy , ClientSideToolkit toolkit ) { return proxy ; } ; public Class < Foo > interfaceClass ( ) { return Foo . class ; } ; } ClientInterfaceManagerFactory test = new ClientInterfaceManagerFactory ( new ClientInterfaceHandlerFactory [ ] { new FooClientHandlerFactory ( ) } ) ; ClientInterfaceManager cim = test . create ( foo , null ) ; cim . invoke ( Foo . class . getMethod ( "" , ( Class < ? > [ ] ) null ) , null ) ; assertTrue ( foo . invoked ) ; } public void testNoFactory ( ) throws Throwable { class MockFoo implements Foo { boolean invoked ; public void foo ( ) { invoked = true ; } } MockFoo foo = new MockFoo ( ) ; ClientInterfaceManagerFactory test = new ClientInterfaceManagerFactory ( null ) ; ClientInterfaceManager cim = test . create ( foo , null ) ; try { cim . invoke ( Foo . class . getMethod ( "" , ( Class < ? > [ ] ) null ) , null ) ; fail ( "" ) ; } catch ( IllegalArgumentException e ) { } assertFalse ( foo . invoked ) ; } public void testForObject ( ) throws Throwable { class MockFoo implements Foo { public void foo ( ) { } } MockFoo foo = new MockFoo ( ) ; class FooClientHandlerFactory extends MockClientInterfaceHandlerFactory < Foo > { private static final long serialVersionUID = ; public Foo createClientHandler ( Foo proxy , ClientSideToolkit toolkit ) { return proxy ; } ; public Class < Foo > interfaceClass ( ) { return Foo . class ; } ; } class OClientHandlerFactory extends MockClientInterfaceHandlerFactory < Object > { private static final long serialVersionUID = ; public Object createClientHandler ( final Object proxy , ClientSideToolkit toolkit ) { return new Object ( ) { public String toString ( ) { return "" ; } } ; } ; public Class < Object > interfaceClass ( ) { return Object . class ; } ; } ClientInterfaceManagerFactory test = new ClientInterfaceManagerFactory ( new ClientInterfaceHandlerFactory [ ] { new OClientHandlerFactory ( ) , new FooClientHandlerFactory ( ) } ) ; ClientInterfaceManager cim = test . create ( foo , null ) ; Object result = cim . invoke ( Object . class . getMethod ( "" , ( Class < ? > [ ] ) null ) , null ) ; assertEquals ( "" , result ) ; } } package org . oddjob . jmx . client ; import java . io . Serializable ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import javax . management . Attribute ; import javax . management . AttributeList ; import javax . management . AttributeNotFoundException ; import javax . management . DynamicMBean ; import javax . management . InstanceNotFoundException ; import javax . management . IntrospectionException ; import javax . management . InvalidAttributeValueException ; import javax . management . MBeanAttributeInfo ; import javax . management . MBeanConstructorInfo ; import javax . management . MBeanException ; import javax . management . MBeanInfo ; import javax . management . MBeanNotificationInfo ; import javax . management . MBeanOperationInfo ; import javax . management . MBeanServer ; import javax . management . MBeanServerFactory ; import javax . management . NotificationBroadcasterSupport ; import javax . management . ObjectName ; import javax . management . ReflectionException ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaClass ; import org . apache . commons . beanutils . DynaProperty ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ClassResolver ; import org . oddjob . arooa . MockArooaDescriptor ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . MockClassResolver ; import org . oddjob . arooa . beanutils . BeanUtilsPropertyAccessor ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . jmx . RemoteOddjobBean ; import org . oddjob . jmx . handlers . DynaBeanHandlerFactory ; import org . oddjob . jmx . handlers . LogPollableHandlerFactory ; import org . oddjob . jmx . handlers . ObjectInterfaceHandlerFactory ; import org . oddjob . jmx . handlers . RemoteOddjobHandlerFactory ; import org . oddjob . jmx . handlers . RunnableHandlerFactory ; import org . oddjob . jmx . server . MockServerSession ; import org . oddjob . jmx . server . OddjobMBean ; import org . oddjob . jmx . server . OddjobMBeanFactory ; import org . oddjob . jmx . server . ServerContext ; import org . oddjob . jmx . server . ServerContextImpl ; import org . oddjob . jmx . server . ServerInfo ; import org . oddjob . jmx . server . ServerInterfaceManagerFactoryImpl ; import org . oddjob . jmx . server . ServerModel ; import org . oddjob . jmx . server . ServerModelImpl ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . util . MockThreadManager ; public class ClientNodeTest extends TestCase { public static final Logger logger = Logger . getLogger ( ClientNodeTest . class ) ; public interface OJMBeanInternals extends RemoteOddjobBean { public String toString ( ) ; } int unique ; public abstract class BaseMockOJMBean extends NotificationBroadcasterSupport implements OJMBeanInternals { int instance = unique ++ ; protected final Set < ClientHandlerResolver < ? > > handlerFactories = new HashSet < ClientHandlerResolver < ? > > ( ) ; { handlerFactories . add ( new RemoteOddjobHandlerFactory ( ) . clientHandlerFactory ( ) ) ; handlerFactories . add ( new ObjectInterfaceHandlerFactory ( ) . clientHandlerFactory ( ) ) ; } public ServerInfo serverInfo ( ) { return new ServerInfo ( new Address ( new ServerId ( url ( ) ) , new Path ( id ( ) ) ) , ( ClientHandlerResolver [ ] ) handlerFactories . toArray ( new ClientHandlerResolver [ ] ) ) ; } public void noop ( ) { } protected String url ( ) { return "" ; } protected String id ( ) { return "" + instance ; } public String toString ( ) { return "" ; } public String loggerName ( ) { return "" ; } } public interface SimpleMBean extends OJMBeanInternals { } public class Simple extends BaseMockOJMBean implements SimpleMBean { public String toString ( ) { return "" ; } } private class OurArooaSession extends MockArooaSession { @ Override public ArooaDescriptor getArooaDescriptor ( ) { return new MockArooaDescriptor ( ) { @ Override public ClassResolver getClassResolver ( ) { return new MockClassResolver ( ) { @ Override public Class < ? > findClass ( String className ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } } ; } } ; } } public void testSimple ( ) throws Exception { Simple mb = new Simple ( ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; ObjectName on = new ObjectName ( "" ) ; mbs . registerMBean ( mb , on ) ; ClientSessionImpl clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object proxy = clientSession . create ( on ) ; assertEquals ( "" , proxy . toString ( ) ) ; } public void testEquals ( ) throws Exception { Simple mb = new Simple ( ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; ObjectName on = new ObjectName ( "" ) ; mbs . registerMBean ( mb , on ) ; ClientSessionImpl clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object proxy = clientSession . create ( on ) ; assertEquals ( proxy , proxy ) ; assertEquals ( proxy . hashCode ( ) , proxy . hashCode ( ) ) ; } public interface MockRunnableMBean extends Runnable , OJMBeanInternals { } public class MockRunnable extends BaseMockOJMBean implements MockRunnableMBean { boolean ran ; public MockRunnable ( ) { handlerFactories . add ( new RunnableHandlerFactory ( ) . clientHandlerFactory ( ) ) ; } public void run ( ) { ran = true ; } } private BeanRegistry cr ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; System . setProperty ( "" , "" ) ; cr = new SimpleBeanRegistry ( ) ; cr . register ( "" , this ) ; } public void testRunnable ( ) throws Exception { MockRunnable mb = new MockRunnable ( ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; ObjectName on = new ObjectName ( "" ) ; mbs . registerMBean ( mb , on ) ; ClientSessionImpl clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object proxy = clientSession . create ( on ) ; assertTrue ( "" , proxy instanceof Runnable ) ; ( ( Runnable ) proxy ) . run ( ) ; assertTrue ( "" , mb . ran ) ; } public static class Fred implements Serializable { private static final long serialVersionUID = ; public String getFruit ( ) { return "" ; } } public class MyDC implements DynaClass , Serializable { private static final long serialVersionUID = ; public DynaProperty [ ] getDynaProperties ( ) { return new DynaProperty [ ] { new DynaProperty ( "" , Fred . class ) , } ; } public DynaProperty getDynaProperty ( String arg0 ) { return new DynaProperty ( arg0 ) ; } public String getName ( ) { return "" ; } public DynaBean newInstance ( ) throws IllegalAccessException , InstantiationException { throw new UnsupportedOperationException ( "" ) ; } } public class Bean implements DynaBean , LogEnabled { public boolean contains ( String name , String key ) { logger . debug ( "" + name + "" + key + "" ) ; return false ; } public Object get ( String name ) { logger . debug ( "" + name + "" ) ; if ( "" . equals ( name ) ) { return new Fred ( ) ; } else if ( "" . equals ( name ) ) { Map < Object , Object > m = new HashMap < Object , Object > ( ) ; m . put ( "" , "" ) ; return m ; } return null ; } public Object get ( String name , int index ) { logger . debug ( "" + name + "" + index + "" ) ; return null ; } public Object get ( String name , String key ) { logger . debug ( "" + name + "" + key + "" ) ; return null ; } public DynaClass getDynaClass ( ) { logger . debug ( "" ) ; return new MyDC ( ) ; } public void remove ( String name , String key ) { logger . debug ( "" + name + "" + key + "" ) ; } public void set ( String name , int index , Object value ) { logger . debug ( "" + name + "" + index + "" + value + "" ) ; } public void set ( String name , Object value ) { logger . debug ( "" + name + "" + value + "" ) ; } public void set ( String name , String key , Object value ) { logger . debug ( "" + name + "" + key + "" + value + "" ) ; } public String loggerName ( ) { return "" ; } } public class MyDynamicMBean extends NotificationBroadcasterSupport implements DynamicMBean { public Object getAttribute ( String attribute ) throws AttributeNotFoundException , MBeanException , ReflectionException { logger . debug ( "" + attribute + "" ) ; throw new UnsupportedOperationException ( ) ; } public AttributeList getAttributes ( String [ ] attributes ) { return null ; } public MBeanInfo getMBeanInfo ( ) { return new MBeanInfo ( this . getClass ( ) . getName ( ) , "" , new MBeanAttributeInfo [ ] , new MBeanConstructorInfo [ ] , new MBeanOperationInfo [ ] , new MBeanNotificationInfo [ ] ) ; } public Object invoke ( String actionName , Object [ ] arguments , String [ ] signature ) throws MBeanException , ReflectionException { logger . debug ( "" + actionName + "" ) ; if ( "" . equals ( actionName ) ) { return "" ; } else if ( "" . equals ( actionName ) ) { return new ServerInfo ( new Address ( new ServerId ( "" ) , new Path ( "" ) ) , new ClientHandlerResolver [ ] { new ObjectInterfaceHandlerFactory ( ) . clientHandlerFactory ( ) , new RemoteOddjobHandlerFactory ( ) . clientHandlerFactory ( ) , new DynaBeanHandlerFactory ( ) . clientHandlerFactory ( ) } ) ; } else if ( "" . equals ( actionName ) ) { return "" ; } else if ( "" . equals ( actionName ) ) { return "" ; } else if ( "" . equals ( actionName ) ) { return new MyDC ( ) ; } else if ( "" . equals ( actionName ) ) { return new Fred ( ) ; } else { throw new MBeanException ( new UnsupportedOperationException ( "" + actionName + "" ) ) ; } } public void setAttribute ( Attribute attribute ) throws AttributeNotFoundException , InvalidAttributeValueException , MBeanException , ReflectionException { throw new UnsupportedOperationException ( ) ; } public AttributeList setAttributes ( AttributeList attributes ) { throw new UnsupportedOperationException ( ) ; } } public void testSimpleGet ( ) throws Exception { MyDynamicMBean firstBean = new MyDynamicMBean ( ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; ObjectName on = new ObjectName ( "" ) ; mbs . registerMBean ( firstBean , on ) ; ClientSessionImpl clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object proxy = clientSession . create ( on ) ; assertNotNull ( proxy ) ; BeanUtilsPropertyAccessor propertyAccessor = new BeanUtilsPropertyAccessor ( ) ; String fruit = ( String ) propertyAccessor . getProperty ( proxy , "" ) ; assertEquals ( "" , fruit ) ; MyDynamicMBean nestedBean = new MyDynamicMBean ( ) ; ObjectName on2 = new ObjectName ( "" ) ; mbs . registerMBean ( nestedBean , on2 ) ; } private class OurHierarchicalRegistry extends MockBeanRegistry { @ Override public String getIdFor ( Object component ) { assertNotNull ( component ) ; return "" ; } } private class OurServerSession extends MockServerSession { ArooaSession session = new StandardArooaSession ( ) ; @ Override public ObjectName nameFor ( Object object ) { return OddjobMBeanFactory . objectName ( ) ; } @ Override public ArooaSession getArooaSession ( ) { return session ; } } public void testBean ( ) throws Exception { Object o = new Bean ( ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , new ServerInterfaceManagerFactoryImpl ( ) ) ; ServerContext srvcon = new ServerContextImpl ( o , sm , new OurHierarchicalRegistry ( ) ) ; Object mb = new OddjobMBean ( o , new OurServerSession ( ) , srvcon ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; ObjectName on = new ObjectName ( "" ) ; mbs . registerMBean ( mb , on ) ; ClientSessionImpl clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object proxy = clientSession . create ( on ) ; assertNotNull ( proxy ) ; ArooaSession session = new StandardArooaSession ( ) ; Map < String , String > map = new UniversalDescriber ( session ) . describe ( proxy ) ; assertNotNull ( map ) ; BeanUtilsPropertyAccessor bubh = new BeanUtilsPropertyAccessor ( ) ; Object gotten = bubh . getProperty ( proxy , "" ) ; assertEquals ( "" , gotten ) ; } public interface MockLoggingMBean extends OJMBeanInternals , LogPollable { } public class MockLogging extends BaseMockOJMBean implements MockLoggingMBean { public MockLogging ( ) { handlerFactories . add ( new LogPollableHandlerFactory ( ) . clientHandlerFactory ( ) ) ; } public LogEvent [ ] retrieveLogEvents ( long from , int max ) { return new LogEvent [ ] { new LogEvent ( "" , , LogLevel . DEBUG , "" ) } ; } public LogEvent [ ] retrieveConsoleEvents ( long from , int max ) { throw new RuntimeException ( "" ) ; } public String consoleId ( ) { return "" ; } public String url ( ) { return super . url ( ) ; } } public void testLogging ( ) throws Exception { MockLogging mb = new MockLogging ( ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; ObjectName on = new ObjectName ( "" ) ; mbs . registerMBean ( mb , on ) ; beanDump ( mbs , on ) ; ClientSessionImpl clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object proxy = clientSession . create ( on ) ; assertTrue ( "" , proxy instanceof LogPollable ) ; LogPollable test = ( LogPollable ) proxy ; assertEquals ( "" , "" , test . url ( ) ) ; LogEvent [ ] events = test . retrieveLogEvents ( - , ) ; assertEquals ( "" , , events . length ) ; assertEquals ( "" , "" , events [ ] . getMessage ( ) ) ; } static void beanDump ( MBeanServer mbs , ObjectName on ) throws ReflectionException , InstanceNotFoundException , IntrospectionException { MBeanInfo info = mbs . getMBeanInfo ( on ) ; MBeanOperationInfo [ ] opInfo = info . getOperations ( ) ; for ( int i = ; i < opInfo . length ; ++ i ) { logger . debug ( "" + opInfo [ i ] . getName ( ) ) ; } MBeanAttributeInfo [ ] atInfo = info . getAttributes ( ) ; for ( int i = ; i < atInfo . length ; ++ i ) { logger . debug ( "" + atInfo [ i ] . getName ( ) ) ; } } } package org . oddjob . jmx . client ; import javax . management . MBeanServer ; import javax . management . MBeanServerFactory ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ClassResolver ; import org . oddjob . arooa . MockArooaDescriptor ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . MockClassResolver ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . server . MockServerContext ; import org . oddjob . jmx . server . MockServerModel ; import org . oddjob . jmx . server . MockServerSession ; import org . oddjob . jmx . server . OddjobMBean ; import org . oddjob . jmx . server . OddjobMBeanFactory ; import org . oddjob . jmx . server . ServerInterfaceManagerFactory ; import org . oddjob . jmx . server . ServerInterfaceManagerFactoryImpl ; import org . oddjob . jmx . server . ServerModel ; import org . oddjob . logging . ConsoleArchiver ; import org . oddjob . logging . LogArchiver ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogHelper ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class RemoteLogPollerTest extends TestCase { private static final Logger logger = Logger . getLogger ( RemoteLogPollerTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; System . setProperty ( "" , "" ) ; } private class LL implements LogListener { String text ; public void logEvent ( LogEvent logEvent ) { text = logEvent . getMessage ( ) ; } } private class OurLogPollable implements LogEnabled , LogPollable { long expectedFrom ; int expectedMax ; public String loggerName ( ) { return ( "" ) ; } public String consoleId ( ) { return "" ; } public LogEvent [ ] retrieveConsoleEvents ( long from , int max ) { assertEquals ( "" , expectedFrom , from ) ; assertEquals ( "" , expectedMax , max ) ; return new LogEvent [ ] { new LogEvent ( "" , , LogLevel . INFO , "" ) } ; } public LogEvent [ ] retrieveLogEvents ( long from , int max ) { assertEquals ( "" , expectedFrom , from ) ; assertEquals ( "" , expectedMax , max ) ; return new LogEvent [ ] { new LogEvent ( "" , , LogLevel . INFO , "" ) } ; } public String url ( ) { return "" ; } } public void testPoll ( ) { OurLogPollable pollable = new OurLogPollable ( ) ; RemoteLogPoller test = new RemoteLogPoller ( pollable , , ) ; pollable . expectedFrom = - ; pollable . expectedMax = ; LL consoleListener = new LL ( ) ; LL logListener = new LL ( ) ; test . addConsoleListener ( consoleListener , pollable , - , ) ; test . addLogListener ( logListener , pollable , LogLevel . INFO , - , ) ; assertEquals ( "" , "" , consoleListener . text ) ; assertEquals ( "" , "" , logListener . text ) ; } private class LogThing implements LogEnabled { public String loggerName ( ) { return "" ; } } private class NoLogThing { } private class MockArchivers implements LogArchiver , ConsoleArchiver { public void addLogListener ( LogListener l , Object component , LogLevel level , long from , int max ) { l . logEvent ( new LogEvent ( "" , , LogLevel . INFO , "" ) ) ; } public void removeLogListener ( LogListener l , Object component ) { } public void addConsoleListener ( LogListener l , Object compoennt , long from , int max ) { l . logEvent ( new LogEvent ( "" , , LogLevel . INFO , "" ) ) ; } public void removeConsoleListener ( LogListener l , Object component ) { } public String consoleIdFor ( Object component ) { return "" ; } } ; private class OurHierarchicalRegistry extends MockBeanRegistry { @ Override public String getIdFor ( Object component ) { assertNotNull ( component ) ; return "" ; } } private class OurArooaSession extends MockArooaSession { @ Override public ArooaDescriptor getArooaDescriptor ( ) { return new MockArooaDescriptor ( ) { @ Override public ClassResolver getClassResolver ( ) { return new MockClassResolver ( ) { @ Override public Class < ? > findClass ( String className ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } } ; } } ; } } private class MyServerContext extends MockServerContext { ServerInterfaceManagerFactory simf ; MockArchivers archivers = new MockArchivers ( ) ; public ConsoleArchiver getConsoleArchiver ( ) { return archivers ; } public LogArchiver getLogArchiver ( ) { return archivers ; } @ Override public ServerModel getModel ( ) { return new MockServerModel ( ) { @ Override public ServerInterfaceManagerFactory getInterfaceManagerFactory ( ) { return simf ; } } ; } @ Override public BeanDirectory getBeanDirectory ( ) { return new OurHierarchicalRegistry ( ) ; } @ Override public Address getAddress ( ) { return null ; } @ Override public ServerId getServerId ( ) { return new ServerId ( "" ) ; } } private class OurServerSession extends MockServerSession { ArooaSession session = new StandardArooaSession ( ) ; @ Override public ObjectName nameFor ( Object object ) { return OddjobMBeanFactory . objectName ( ) ; } @ Override public ArooaSession getArooaSession ( ) { return session ; } } public void testLoggingUsingMBean ( ) throws Exception { LogThing component = new LogThing ( ) ; ServerInterfaceManagerFactoryImpl imf = new ServerInterfaceManagerFactoryImpl ( ) ; MyServerContext serverContext = new MyServerContext ( ) ; serverContext . simf = imf ; OddjobMBean mb = new OddjobMBean ( component , new OurServerSession ( ) , serverContext ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; ObjectName on = new ObjectName ( "" ) ; mbs . registerMBean ( mb , on ) ; ClientSession clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object proxy = clientSession . create ( on ) ; assertTrue ( proxy instanceof LogEnabled ) ; assertEquals ( "" , LogHelper . getLogger ( proxy ) ) ; assertEquals ( "" , ( ( LogPollable ) proxy ) . consoleId ( ) ) ; RemoteLogPoller poller = new RemoteLogPoller ( ( LogPollable ) proxy , , ) ; LL cl = new LL ( ) ; LL ll = new LL ( ) ; poller . addConsoleListener ( cl , proxy , - , ) ; poller . addLogListener ( ll , proxy , LogLevel . DEBUG , - , ) ; poller . poll ( ) ; assertEquals ( "" , ll . text ) ; assertEquals ( "" , cl . text ) ; } public void testNotLoggingUsingMBean ( ) throws Exception { NoLogThing component = new NoLogThing ( ) ; ServerInterfaceManagerFactoryImpl imf = new ServerInterfaceManagerFactoryImpl ( ) ; MyServerContext serverContext = new MyServerContext ( ) ; serverContext . simf = imf ; OddjobMBean mb = new OddjobMBean ( component , new OurServerSession ( ) , serverContext ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; ObjectName on = new ObjectName ( "" ) ; mbs . registerMBean ( mb , on ) ; ClientSession clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object proxy = clientSession . create ( on ) ; assertTrue ( proxy instanceof LogEnabled ) ; assertEquals ( null , LogHelper . getLogger ( proxy ) ) ; assertEquals ( "" , ( ( LogPollable ) proxy ) . consoleId ( ) ) ; RemoteLogPoller poller = new RemoteLogPoller ( ( LogPollable ) proxy , , ) ; LL cl = new LL ( ) ; LL ll = new LL ( ) ; poller . addConsoleListener ( cl , proxy , - , ) ; poller . addLogListener ( ll , proxy , LogLevel . DEBUG , - , ) ; poller . poll ( ) ; assertEquals ( "" , ll . text ) ; assertEquals ( "" , cl . text ) ; } } package org . oddjob . jmx . client ; import javax . management . NotificationListener ; import org . oddjob . jmx . RemoteOperation ; public class MockClientSideToolkit implements ClientSideToolkit { public < T > T invoke ( RemoteOperation < T > remoteOperation , Object ... args ) throws Throwable { throw new RuntimeException ( "" + getClass ( ) ) ; } public ClientSession getClientSession ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void registerNotificationListener ( String eventType , NotificationListener notificationListener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeNotificationListener ( String eventType , NotificationListener notificationListener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . client ; import org . oddjob . arooa . ClassResolver ; public class MockClientHandlerResolver < T > implements ClientHandlerResolver < T > { private static final long serialVersionUID = ; public ClientInterfaceHandlerFactory < T > resolve ( ClassResolver classResolver ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . client ; import java . util . ArrayList ; import java . util . List ; import javax . management . Notification ; import javax . management . NotificationListener ; import junit . framework . TestCase ; public class SynchronizerTest extends TestCase { class OurListener implements NotificationListener { List < Notification > notifications = new ArrayList < Notification > ( ) ; public void handleNotification ( Notification notification , Object handback ) { notifications . add ( notification ) ; } } String type = "" ; public void testSynch ( ) { Notification n0 = new Notification ( type , this , ) ; Notification n1 = new Notification ( type , this , ) ; Notification n2 = new Notification ( type , this , ) ; Notification n3 = new Notification ( type , this , ) ; OurListener results = new OurListener ( ) ; Synchronizer test = new Synchronizer ( results ) ; test . handleNotification ( n0 , null ) ; test . handleNotification ( n1 , null ) ; test . handleNotification ( n3 , null ) ; assertEquals ( , results . notifications . size ( ) ) ; test . synchronize ( new Notification [ ] { n1 , n2 } ) ; assertEquals ( , results . notifications . size ( ) ) ; assertEquals ( n1 , results . notifications . get ( ) ) ; assertEquals ( n2 , results . notifications . get ( ) ) ; assertEquals ( n3 , results . notifications . get ( ) ) ; test . handleNotification ( n3 , null ) ; assertEquals ( n3 , results . notifications . get ( ) ) ; } } package org . oddjob . jmx . client ; import java . io . ObjectInputStream ; import java . util . Set ; import javax . management . Attribute ; import javax . management . AttributeList ; import javax . management . AttributeNotFoundException ; import javax . management . InstanceAlreadyExistsException ; import javax . management . InstanceNotFoundException ; import javax . management . IntrospectionException ; import javax . management . InvalidAttributeValueException ; import javax . management . ListenerNotFoundException ; import javax . management . MBeanException ; import javax . management . MBeanInfo ; import javax . management . MBeanRegistrationException ; import javax . management . MBeanServer ; import javax . management . NotCompliantMBeanException ; import javax . management . NotificationFilter ; import javax . management . NotificationListener ; import javax . management . ObjectInstance ; import javax . management . ObjectName ; import javax . management . OperationsException ; import javax . management . QueryExp ; import javax . management . ReflectionException ; import javax . management . loading . ClassLoaderRepository ; public class MockMBeanServer implements MBeanServer { public void addNotificationListener ( ObjectName name , NotificationListener listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public void addNotificationListener ( ObjectName name , ObjectName listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInstance createMBean ( String className , ObjectName name ) throws ReflectionException , InstanceAlreadyExistsException , MBeanRegistrationException , MBeanException , NotCompliantMBeanException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInstance createMBean ( String className , ObjectName name , ObjectName loaderName ) throws ReflectionException , InstanceAlreadyExistsException , MBeanRegistrationException , MBeanException , NotCompliantMBeanException , InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInstance createMBean ( String className , ObjectName name , Object [ ] params , String [ ] signature ) throws ReflectionException , InstanceAlreadyExistsException , MBeanRegistrationException , MBeanException , NotCompliantMBeanException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInstance createMBean ( String className , ObjectName name , ObjectName loaderName , Object [ ] params , String [ ] signature ) throws ReflectionException , InstanceAlreadyExistsException , MBeanRegistrationException , MBeanException , NotCompliantMBeanException , InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInputStream deserialize ( ObjectName name , byte [ ] data ) throws InstanceNotFoundException , OperationsException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInputStream deserialize ( String className , byte [ ] data ) throws OperationsException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInputStream deserialize ( String className , ObjectName loaderName , byte [ ] data ) throws InstanceNotFoundException , OperationsException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object getAttribute ( ObjectName name , String attribute ) throws MBeanException , AttributeNotFoundException , InstanceNotFoundException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public AttributeList getAttributes ( ObjectName name , String [ ] attributes ) throws InstanceNotFoundException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ClassLoader getClassLoader ( ObjectName loaderName ) throws InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ClassLoader getClassLoaderFor ( ObjectName mbeanName ) throws InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ClassLoaderRepository getClassLoaderRepository ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public String getDefaultDomain ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public String [ ] getDomains ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Integer getMBeanCount ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public MBeanInfo getMBeanInfo ( ObjectName name ) throws InstanceNotFoundException , IntrospectionException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInstance getObjectInstance ( ObjectName name ) throws InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object instantiate ( String className ) throws ReflectionException , MBeanException { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object instantiate ( String className , ObjectName loaderName ) throws ReflectionException , MBeanException , InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object instantiate ( String className , Object [ ] params , String [ ] signature ) throws ReflectionException , MBeanException { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object instantiate ( String className , ObjectName loaderName , Object [ ] params , String [ ] signature ) throws ReflectionException , MBeanException , InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object invoke ( ObjectName name , String operationName , Object [ ] params , String [ ] signature ) throws InstanceNotFoundException , MBeanException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public boolean isInstanceOf ( ObjectName name , String className ) throws InstanceNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public boolean isRegistered ( ObjectName name ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Set < ObjectInstance > queryMBeans ( ObjectName name , QueryExp query ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Set < ObjectName > queryNames ( ObjectName name , QueryExp query ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ObjectInstance registerMBean ( Object object , ObjectName name ) throws InstanceAlreadyExistsException , MBeanRegistrationException , NotCompliantMBeanException { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeNotificationListener ( ObjectName name , ObjectName listener ) throws InstanceNotFoundException , ListenerNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeNotificationListener ( ObjectName name , NotificationListener listener ) throws InstanceNotFoundException , ListenerNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeNotificationListener ( ObjectName name , ObjectName listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException , ListenerNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeNotificationListener ( ObjectName name , NotificationListener listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException , ListenerNotFoundException { throw new RuntimeException ( "" + getClass ( ) ) ; } public void setAttribute ( ObjectName name , Attribute attribute ) throws InstanceNotFoundException , AttributeNotFoundException , InvalidAttributeValueException , MBeanException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public AttributeList setAttributes ( ObjectName name , AttributeList attributes ) throws InstanceNotFoundException , ReflectionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public void unregisterMBean ( ObjectName name ) throws InstanceNotFoundException , MBeanRegistrationException { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . client ; import org . apache . log4j . Logger ; import org . oddjob . arooa . life . ClassLoaderClassResolver ; import junit . framework . TestCase ; public class SimpleHandlerResolverTest extends TestCase { private static final Logger logger = Logger . getLogger ( SimpleHandlerResolverTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public static class MyHandlerFactory implements ClientInterfaceHandlerFactory < Object > { @ Override public Object createClientHandler ( Object proxy , ClientSideToolkit toolkit ) { throw new RuntimeException ( "" ) ; } @ Override public HandlerVersion getVersion ( ) { return new HandlerVersion ( , ) ; } @ Override public Class < Object > interfaceClass ( ) { return Object . class ; } } public void testResolveForMinorVersionDiferences ( ) { SimpleHandlerResolver < Object > test = new SimpleHandlerResolver < Object > ( MyHandlerFactory . class . getName ( ) , new HandlerVersion ( , ) ) ; ClientInterfaceHandlerFactory < Object > result = test . resolve ( new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; assertNotNull ( result ) ; } public void testResolveNullForMajorVersionDiferences ( ) { SimpleHandlerResolver < Object > test = new SimpleHandlerResolver < Object > ( MyHandlerFactory . class . getName ( ) , new HandlerVersion ( , ) ) ; ClientInterfaceHandlerFactory < Object > result = test . resolve ( new ClassLoaderClassResolver ( getClass ( ) . getClassLoader ( ) ) ) ; assertNull ( result ) ; } } package org . oddjob . jmx . client ; public class MockClientInterfaceHandlerFactory < T > implements ClientInterfaceHandlerFactory < T > { public T createClientHandler ( T proxy , ClientSideToolkit toolkit ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public HandlerVersion getVersion ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Class < T > interfaceClass ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . client ; import javax . management . ObjectName ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; public class MockClientSession implements ClientSession { @ Override public Object create ( ObjectName objectName ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void destroy ( Object proxy ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public ArooaSession getArooaSession ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public ObjectName nameFor ( Object object ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public Object objectFor ( ObjectName objectName ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public Logger logger ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void destroyAll ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . client ; import org . oddjob . logging . LogEvent ; public class MockLogPollable implements LogPollable { public String consoleId ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public LogEvent [ ] retrieveConsoleEvents ( long from , int max ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public LogEvent [ ] retrieveLogEvents ( long from , int max ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public String url ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx . client ; import javax . management . MBeanServer ; import javax . management . MBeanServerFactory ; import javax . management . MalformedObjectNameException ; import javax . management . ObjectName ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ClassResolver ; import org . oddjob . arooa . MockArooaDescriptor ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . MockClassResolver ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . jmx . handlers . StructuralHandlerFactory ; import org . oddjob . jmx . server . OddjobMBeanFactory ; import org . oddjob . jmx . server . ServerContext ; import org . oddjob . jmx . server . ServerContextImpl ; import org . oddjob . jmx . server . ServerInterfaceHandlerFactory ; import org . oddjob . jmx . server . ServerInterfaceManagerFactoryImpl ; import org . oddjob . jmx . server . ServerModel ; import org . oddjob . jmx . server . ServerModelImpl ; import org . oddjob . jobs . structural . JobFolder ; import org . oddjob . util . MockThreadManager ; public class TransportableComponentTest extends TestCase { private static final Logger logger = Logger . getLogger ( TransportableComponentTest . class ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; System . setProperty ( "" , "" ) ; } public static class MyComponent { MyComponent another ; public void setAnother ( MyComponent another ) { this . another = another ; } public MyComponent getAnother ( ) { return another ; } public Object getAnotherReally ( ) throws MalformedObjectNameException , NullPointerException { return new ComponentTransportable ( OddjobMBeanFactory . objectName ( ) ) ; } } private class OurArooaSession extends MockArooaSession { @ Override public ArooaDescriptor getArooaDescriptor ( ) { return new MockArooaDescriptor ( ) { @ Override public ClassResolver getClassResolver ( ) { return new MockClassResolver ( ) { @ Override public Class < ? > findClass ( String className ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } } ; } } ; } } public void testRoundTrip ( ) throws Exception { MyComponent c1 = new MyComponent ( ) ; MyComponent c2 = new MyComponent ( ) ; JobFolder folder = new JobFolder ( ) ; folder . setJobs ( , c1 ) ; folder . setJobs ( , c2 ) ; ServerInterfaceManagerFactoryImpl imf = new ServerInterfaceManagerFactoryImpl ( ) ; imf . addServerHandlerFactories ( new ServerInterfaceHandlerFactory < ? , ? > [ ] { new StructuralHandlerFactory ( ) } ) ; ServerModel sm = new ServerModelImpl ( new ServerId ( "" ) , new MockThreadManager ( ) , imf ) ; ServerContext serverContext = new ServerContextImpl ( folder , sm , new SimpleBeanRegistry ( ) ) ; MBeanServer mbs = MBeanServerFactory . createMBeanServer ( ) ; OddjobMBeanFactory factory = new OddjobMBeanFactory ( mbs , new StandardArooaSession ( ) ) ; ObjectName on = factory . createMBeanFor ( folder , serverContext ) ; ClientSession clientSession = new ClientSessionImpl ( mbs , new DummyNotificationProcessor ( ) , new OurArooaSession ( ) , logger ) ; Object folderProxy = clientSession . create ( on ) ; assertNotNull ( folderProxy ) ; Object [ ] children = Helper . getChildren ( ( Structural ) folderProxy ) ; Object c1Proxy = children [ ] ; assertNotNull ( c1Proxy ) ; Object c2Proxy = children [ ] ; assertNotNull ( c2Proxy ) ; PropertyUtils . setProperty ( c1Proxy , "" , c2Proxy ) ; Object result = PropertyUtils . getProperty ( c1Proxy , "" ) ; assertEquals ( c2Proxy , result ) ; } } package org . oddjob . jmx . client ; import java . util . concurrent . Future ; import org . oddjob . scheduling . MockScheduledExecutorService ; import org . oddjob . scheduling . MockScheduledFuture ; public class DummyNotificationProcessor extends MockScheduledExecutorService { @ Override public Future < ? > submit ( Runnable task ) { task . run ( ) ; return new MockScheduledFuture < Void > ( ) ; } } package org . oddjob . jmx . client ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; import javax . security . auth . Destroyable ; import junit . framework . TestCase ; public class ProxyAssumptionsTest extends TestCase { public void testToString ( ) { class H implements InvocationHandler { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { assertEquals ( Object . class . getMethod ( "" ) , method ) ; return "" ; } } H h = new H ( ) ; Object p = Proxy . newProxyInstance ( null , new Class [ ] , h ) ; String result = p . toString ( ) ; assertEquals ( "" , result ) ; } public void testAnyMethod ( ) throws Exception { class H implements InvocationHandler { boolean destroyed ; public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { if ( method . getName ( ) . equals ( "" ) ) { destroyed = true ; } else { fail ( "" ) ; } return null ; } public void foo ( ) { } } H h = new H ( ) ; Object p = Proxy . newProxyInstance ( this . getClass ( ) . getClassLoader ( ) , new Class [ ] { Destroyable . class } , h ) ; Method m = p . getClass ( ) . getMethod ( "" ) ; m = p . getClass ( ) . getMethod ( "" ) ; m . invoke ( p ) ; assertTrue ( h . destroyed ) ; try { m = p . getClass ( ) . getMethod ( "" ) ; fail ( "" ) ; } catch ( NoSuchMethodException e ) { } h . foo ( ) ; } } package org . oddjob . jmx ; import java . util . HashSet ; import java . util . Set ; import javax . swing . SwingUtilities ; import javax . swing . event . TreeModelEvent ; import javax . swing . event . TreeModelListener ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . MockBeanDirectoryOwner ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jmx . client . ComponentTransportable ; import org . oddjob . jmx . server . OddjobMBeanFactory ; import org . oddjob . jobs . structural . ForEachJobTest ; import org . oddjob . jobs . structural . JobFolder ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogHelper ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . EventThreadLaterExecutor ; import org . oddjob . monitor . model . ExplorerContextFactory ; import org . oddjob . monitor . model . ExplorerModel ; import org . oddjob . monitor . model . JobTreeModel ; import org . oddjob . monitor . model . JobTreeNode ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . monitor . model . MockExplorerModel ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class JMXClientJobTest extends TestCase { static final Logger logger = Logger . getLogger ( JMXClientJobTest . class ) ; public class ServerChild implements Structural { ChildHelper < Object > childHelper = new ChildHelper < Object > ( this ) ; String name ; ServerChild ( String name ) { this . name = name ; } public String toString ( ) { return name ; } public void addStructuralListener ( StructuralListener listener ) { childHelper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { childHelper . removeStructuralListener ( listener ) ; } } public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } private class OurSession extends StandardArooaSession { SimpleBeanRegistry registry = new SimpleBeanRegistry ( ) ; @ Override public BeanRegistry getBeanRegistry ( ) { return registry ; } } JMXServerJob createServer ( ) { OurSession session = new OurSession ( ) ; ServerChild c1 = new ServerChild ( "" ) ; session . registry . register ( "" , c1 ) ; ServerChild test1 = new ServerChild ( "" ) ; session . registry . register ( "" , test1 ) ; ServerChild test2 = new ServerChild ( "" ) ; session . registry . register ( "" , test2 ) ; ServerChild test3 = new ServerChild ( "" ) ; session . registry . register ( "" , test3 ) ; c1 . childHelper . insertChild ( , test1 ) ; c1 . childHelper . insertChild ( , test2 ) ; c1 . childHelper . insertChild ( , test3 ) ; session . registry . register ( "" , new Object ( ) ) ; JMXServerJob j = new JMXServerJob ( ) ; j . setRoot ( c1 ) ; j . setArooaSession ( session ) ; j . setUrl ( "" ) ; return j ; } public void testRun ( ) throws Exception { JMXServerJob server = createServer ( ) ; server . start ( ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( server . getAddress ( ) ) ; client . run ( ) ; Object [ ] children = Helper . getChildren ( client ) ; assertEquals ( "" , "" , children [ ] . toString ( ) ) ; Object [ ] children2 = Helper . getChildren ( ( Structural ) children [ ] ) ; assertEquals ( , children2 . length ) ; client . stop ( ) ; server . stop ( ) ; assertEquals ( ServiceState . COMPLETE , client . lastStateEvent ( ) . getState ( ) ) ; } public void testPrinciplesOfNextTest ( ) throws ArooaConversionException , FailedToStopException { String xml = "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String address = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertNotNull ( address ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( address ) ; client . run ( ) ; Object [ ] children = Helper . getChildren ( client ) ; assertEquals ( , children . length ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; client . stop ( ) ; client . hardReset ( ) ; client . run ( ) ; children = Helper . getChildren ( client ) ; assertEquals ( , children . length ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; client . destroy ( ) ; oj . destroy ( ) ; } public void testRunLotsOfClients ( ) throws Exception { String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String address = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertNotNull ( address ) ; Thread [ ] threads = new Thread [ ] ; final boolean [ ] ok = new boolean [ ] ; for ( int i = ; i < ; i ++ ) { logger . debug ( "" + i + "" ) ; final JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( address ) ; final int index = i ; Thread t2 = new Thread ( new Runnable ( ) { public void run ( ) { client . run ( ) ; WaitForChildren wait = new WaitForChildren ( client ) ; wait . waitFor ( ) ; try { client . stop ( ) ; } catch ( FailedToStopException e ) { throw new RuntimeException ( e ) ; } if ( Helper . getJobState ( client ) == ServiceState . COMPLETE ) { ok [ index ] = true ; } } } ) ; threads [ i ] = t2 ; t2 . start ( ) ; } for ( int i = ; i < ; ++ i ) { threads [ i ] . join ( ) ; } logger . debug ( "" ) ; oj . stop ( ) ; for ( int i = ; i < ; ++ i ) { if ( ! ok [ i ] ) { fail ( "" + i + "" ) ; } } } public void testLookup ( ) throws Exception { Oddjob server = new Oddjob ( ) ; server . setConfiguration ( new XMLConfiguration ( "" , this . getClass ( ) . getResourceAsStream ( "" ) ) ) ; server . run ( ) ; String address = new OddjobLookup ( server ) . lookup ( "" , String . class ) ; assertNotNull ( address ) ; Oddjob client = new Oddjob ( ) ; client . setConfiguration ( new XMLConfiguration ( "" , this . getClass ( ) . getResourceAsStream ( "" ) ) ) ; client . setArgs ( new String [ ] { address } ) ; client . run ( ) ; client . stop ( ) ; server . stop ( ) ; assertEquals ( ParentState . COMPLETE , client . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , server . lastStateEvent ( ) . getState ( ) ) ; } public static class Echo { Object echo ; public Object getEchoWrapped ( ) { logger . debug ( "" + echo + "" ) ; return new ComponentTransportable ( OddjobMBeanFactory . objectName ( ) ) ; } public void setEcho ( Object echo ) { logger . debug ( "" + echo + "" ) ; this . echo = echo ; } } public void testHostRelative ( ) throws Exception { OurSession serverSession = new OurSession ( ) ; Echo e = new Echo ( ) ; serverSession . registry . register ( "" , e ) ; final JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( e ) ; server . setArooaSession ( serverSession ) ; server . setUrl ( "" ) ; OurSession clientSession = new OurSession ( ) ; JMXClientJob client = new JMXClientJob ( ) ; clientSession . registry . register ( "" , client ) ; client . setArooaSession ( clientSession ) ; server . start ( ) ; client . setConnection ( server . getAddress ( ) ) ; client . run ( ) ; DynaBean bean = ( DynaBean ) clientSession . registry . lookup ( "" ) ; assertNotNull ( bean ) ; bean . set ( "" , bean ) ; Object echo = bean . get ( "" ) ; assertEquals ( bean , echo ) ; client . stop ( ) ; server . stop ( ) ; assertEquals ( ServiceState . COMPLETE , client . lastStateEvent ( ) . getState ( ) ) ; } class Owner extends MockBeanDirectoryOwner implements Structural { SimpleBeanRegistry beanRegistry = new SimpleBeanRegistry ( ) ; ChildHelper < Object > helper = new ChildHelper < Object > ( this ) ; public BeanDirectory provideBeanDirectory ( ) { return beanRegistry ; } public String toString ( ) { return "" ; } public void addStructuralListener ( StructuralListener listener ) { helper . addStructuralListener ( listener ) ; } public void removeStructuralListener ( StructuralListener listener ) { helper . removeStructuralListener ( listener ) ; } } public void testRemoteNestedRegistry ( ) throws Exception { OurSession serverSession = new OurSession ( ) ; Owner comp1 = new Owner ( ) ; serverSession . registry . register ( "" , comp1 ) ; Object comp2 = new Object ( ) { @ Override public String toString ( ) { return "" ; } } ; comp1 . helper . insertChild ( , comp2 ) ; comp1 . beanRegistry . register ( "" , comp2 ) ; JobFolder folder = new JobFolder ( ) ; folder . setJobs ( , comp1 ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( folder ) ; server . setArooaSession ( serverSession ) ; server . setUrl ( "" ) ; server . start ( ) ; OurSession localSession = new OurSession ( ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( localSession ) ; client . setConnection ( server . getAddress ( ) ) ; client . run ( ) ; BeanDirectory mirrorCR1 = client . provideBeanDirectory ( ) ; RemoteDirectoryOwner comp1Proxy = ( RemoteDirectoryOwner ) mirrorCR1 . lookup ( "" ) ; assertNotNull ( comp1Proxy ) ; assertEquals ( "" , comp1Proxy . toString ( ) ) ; Object comp2Proxy = mirrorCR1 . lookup ( "" ) ; assertNotNull ( comp2Proxy ) ; assertEquals ( "" , comp2Proxy . toString ( ) ) ; RemoteDirectory mirrorCR2 = comp1Proxy . provideBeanDirectory ( ) ; assertNotNull ( mirrorCR2 ) ; assertEquals ( comp2Proxy , mirrorCR2 . lookup ( "" ) ) ; client . stop ( ) ; server . stop ( ) ; } class ResultHolder { Object result ; } public void testRegistryManagement ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setName ( "" ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , this . getClass ( ) . getResourceAsStream ( "" ) ) ) ; oddjob . setExport ( "" , new ArooaObject ( JMXClientJobTest . class . getResourceAsStream ( "" ) ) ) ; oddjob . setExport ( "" , new ArooaObject ( JMXClientJobTest . class . getResourceAsStream ( "" ) ) ) ; oddjob . run ( ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; Object server = new OddjobLookup ( oddjob ) . lookup ( "" ) ; client . setConnection ( ( String ) PropertyUtils . getProperty ( server , "" ) ) ; client . run ( ) ; Object firstoj = new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( firstoj ) ; Object seq = new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( seq ) ; Resetable nested = ( Resetable ) new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( nested ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( nested ) ) ; Object echoJob = new OddjobLookup ( client ) . lookup ( "" ) ; assertNotNull ( echoJob ) ; StateSteps steps = new StateSteps ( ( Stateful ) nested ) ; steps . startCheck ( ParentState . COMPLETE , ParentState . READY ) ; nested . hardReset ( ) ; steps . checkWait ( ) ; assertNull ( new OddjobLookup ( client ) . lookup ( "" ) ) ; logger . info ( "" ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; ( ( Runnable ) nested ) . run ( ) ; steps . checkWait ( ) ; while ( new OddjobLookup ( client ) . lookup ( "" ) == null ) { Thread . sleep ( ) ; Thread . yield ( ) ; } steps . startCheck ( ParentState . COMPLETE , ParentState . READY ) ; nested . hardReset ( ) ; steps . checkWait ( ) ; assertNull ( new OddjobLookup ( client ) . lookup ( "" ) ) ; logger . info ( "" ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; ( ( Runnable ) nested ) . run ( ) ; while ( new OddjobLookup ( client ) . lookup ( "" ) == null ) { Thread . sleep ( ) ; Thread . yield ( ) ; } steps . checkWait ( ) ; client . stop ( ) ; ( ( Stoppable ) server ) . stop ( ) ; oddjob . destroy ( ) ; } public static class ThingWithLogger implements LogEnabled { public String loggerName ( ) { return "" ; } } class MockLogListener implements LogListener { LogEvent e ; synchronized public void logEvent ( LogEvent logEvent ) { this . e = logEvent ; notifyAll ( ) ; } } public void testLogArchiver ( ) throws Exception { OurSession session = new OurSession ( ) ; ThingWithLogger serverNode = new ThingWithLogger ( ) ; session . registry . register ( "" , serverNode ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setArooaSession ( session ) ; server . setRoot ( serverNode ) ; server . setLogFormat ( "" ) ; server . setUrl ( "" ) ; server . start ( ) ; Logger ourLogger = Logger . getLogger ( serverNode . loggerName ( ) ) ; ourLogger . setLevel ( Level . DEBUG ) ; ourLogger . info ( "" ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setConnection ( server . getAddress ( ) ) ; client . run ( ) ; Object [ ] children = Helper . getChildren ( client ) ; Object proxy = children [ ] ; assertEquals ( "" , "" , LogHelper . getLogger ( proxy ) ) ; MockLogListener ll = new MockLogListener ( ) ; client . addLogListener ( ll , proxy , LogLevel . DEBUG , - , ) ; while ( ll . e == null ) { synchronized ( ll ) { ll . wait ( ) ; } } assertNotNull ( "" , ll . e ) ; assertEquals ( "" , "" , ll . e . getMessage ( ) ) ; client . stop ( ) ; server . stop ( ) ; } private static class JobCounter implements StructuralListener { private Set < Object > jobs = new HashSet < Object > ( ) ; @ Override public void childAdded ( StructuralEvent event ) { Object child = event . getChild ( ) ; jobs . add ( child ) ; logger . info ( "" + child ) ; if ( child instanceof Structural ) { ( ( Structural ) child ) . addStructuralListener ( this ) ; } } @ Override public void childRemoved ( StructuralEvent event ) { Object child = event . getChild ( ) ; jobs . remove ( child ) ; logger . info ( "" + child ) ; } } private static class NodeCounter implements TreeModelListener { private Set < Object > jobs = new HashSet < Object > ( ) ; @ Override public void treeNodesChanged ( TreeModelEvent e ) { } @ Override public void treeStructureChanged ( TreeModelEvent e ) { throw new RuntimeException ( "" ) ; } @ Override public synchronized void treeNodesInserted ( TreeModelEvent e ) { assertEquals ( , e . getChildren ( ) . length ) ; JobTreeNode child = ( JobTreeNode ) e . getChildren ( ) [ ] ; child . setVisible ( true ) ; jobs . add ( child ) ; logger . info ( "" + child ) ; } @ Override public synchronized void treeNodesRemoved ( TreeModelEvent e ) { assertEquals ( , e . getChildren ( ) . length ) ; Object child = e . getChildren ( ) [ ] ; jobs . remove ( child ) ; logger . info ( "" + child ) ; } } public void testDestroyWithComplicatedStructure ( ) throws Exception { String serverConfig = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob serverOddjob = new Oddjob ( ) ; serverOddjob . setConfiguration ( new XMLConfiguration ( "" , serverConfig ) ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( serverOddjob ) ; server . setArooaSession ( new OurSession ( ) ) ; server . setUrl ( "" ) ; server . start ( ) ; serverOddjob . run ( ) ; String clientConfig = "" + "" + "" + "" + "" + "" ; final Oddjob clientOddjob = new Oddjob ( ) ; clientOddjob . setConfiguration ( new XMLConfiguration ( "" , clientConfig ) ) ; clientOddjob . setExport ( "" , new ArooaObject ( server . getAddress ( ) ) ) ; clientOddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , clientOddjob . lastStateEvent ( ) . getState ( ) ) ; JobTreeModel model = new JobTreeModel ( ) ; NodeCounter nodeCounter = new NodeCounter ( ) ; model . addTreeModelListener ( nodeCounter ) ; JobTreeNode root = new JobTreeNode ( new MockExplorerModel ( ) { @ Override public Oddjob getOddjob ( ) { return clientOddjob ; } } , model , new EventThreadLaterExecutor ( ) , new ExplorerContextFactory ( ) { @ Override public ExplorerContext createFrom ( ExplorerModel explorerModel ) { return new MockExplorerContext ( ) { @ Override public ExplorerContext addChild ( Object child ) { return this ; } } ; } } ) ; root . setVisible ( true ) ; JobCounter jobCounter = new JobCounter ( ) ; clientOddjob . addStructuralListener ( jobCounter ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { logger . info ( "" ) ; } } ) ; logger . info ( "" ) ; assertEquals ( , jobCounter . jobs . size ( ) ) ; assertEquals ( , nodeCounter . jobs . size ( ) ) ; logger . info ( "" ) ; JMXClientJob client = new OddjobLookup ( clientOddjob ) . lookup ( "" , JMXClientJob . class ) ; client . stop ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { logger . info ( "" ) ; } } ) ; assertEquals ( , jobCounter . jobs . size ( ) ) ; assertEquals ( , nodeCounter . jobs . size ( ) ) ; serverOddjob . destroy ( ) ; server . stop ( ) ; clientOddjob . destroy ( ) ; } } package org . oddjob . jmx ; import java . io . IOException ; import java . net . ServerSocket ; import java . net . Socket ; import java . rmi . server . RMISocketFactory ; import java . util . HashSet ; import java . util . Set ; import org . apache . log4j . Logger ; public class FailableSocketFactory extends RMISocketFactory { private static final Logger logger = Logger . getLogger ( FailableSocketFactory . class ) ; private boolean fail ; final Set < FailableSocket > sockets = new HashSet < FailableSocket > ( ) ; @ Override public ServerSocket createServerSocket ( int port ) throws IOException { logger . info ( "" + port ) ; return new FailableServerSocket ( port ) { @ Override public FailableSocket accept ( ) throws IOException { FailableSocket socket = super . accept ( ) ; synchronized ( sockets ) { socket . setFail ( fail ) ; sockets . add ( socket ) ; } return socket ; } } ; } @ Override public Socket createSocket ( String host , int port ) throws IOException { logger . info ( "" + host + "" + port ) ; throw new RuntimeException ( "" ) ; } public void setFail ( boolean fail ) { synchronized ( sockets ) { this . fail = fail ; for ( FailableSocket socket : sockets ) { socket . setFail ( fail ) ; } } } } package org . oddjob . jmx ; import java . util . HashMap ; import java . util . Map ; import javax . management . remote . rmi . RMIConnectorServer ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ServiceState ; public class NetworkFailureTest extends TestCase { private static final Logger logger = Logger . getLogger ( NetworkFailureTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . debug ( "" + getName ( ) + "" ) ; } public void testSimpleExample ( ) throws Exception { FlagState root = new FlagState ( ) ; root . setName ( "" ) ; Map < String , Object > env = new HashMap < String , Object > ( ) ; FailableSocketFactory ssf = new FailableSocketFactory ( ) ; env . put ( RMIConnectorServer . RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE , ssf ) ; JMXServerJob server = new JMXServerJob ( ) ; server . setRoot ( root ) ; server . setArooaSession ( new StandardArooaSession ( ) ) ; server . setUrl ( "" ) ; server . setEnvironment ( env ) ; server . start ( ) ; JMXClientJob client = new JMXClientJob ( ) ; client . setConnection ( server . getAddress ( ) ) ; client . setArooaSession ( new StandardArooaSession ( ) ) ; client . setHeartbeat ( ) ; StateSteps clientStates = new StateSteps ( client ) ; clientStates . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; client . run ( ) ; clientStates . checkNow ( ) ; Object [ ] children = Helper . getChildren ( client ) ; assertEquals ( , children . length ) ; Stateful child = ( Stateful ) children [ ] ; assertEquals ( "" , child . toString ( ) ) ; clientStates . startCheck ( ServiceState . STARTED , ServiceState . EXCEPTION ) ; ssf . setFail ( true ) ; logger . debug ( "" ) ; root . run ( ) ; clientStates . checkWait ( ) ; ssf . setFail ( false ) ; clientStates . startCheck ( ServiceState . EXCEPTION , ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; logger . debug ( "" ) ; client . hardReset ( ) ; client . run ( ) ; clientStates . checkNow ( ) ; children = Helper . getChildren ( client ) ; assertEquals ( , children . length ) ; child = ( Stateful ) children [ ] ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( child ) ) ; assertEquals ( "" , child . toString ( ) ) ; client . stop ( ) ; server . stop ( ) ; } } package org . oddjob . jmx ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . Structural ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class WaitForChildren implements StructuralListener { private static final Logger logger = Logger . getLogger ( WaitForChildren . class ) ; private final Structural structural ; private List < Object > children ; private final int retry = ; public WaitForChildren ( Object o ) { structural = ( Structural ) o ; } public void waitFor ( int count ) { children = new ArrayList < Object > ( ) ; structural . addStructuralListener ( this ) ; try { synchronized ( this ) { for ( int i = ; i < retry && children . size ( ) != count ; ++ i ) { logger . debug ( "" + structural + "" + count + "" + children . size ( ) + "" ) ; wait ( ) ; } if ( children . size ( ) != count ) { throw new RuntimeException ( "" + structural + "" + count + "" + Arrays . toString ( children . toArray ( new Object [ children . size ( ) ] ) ) ) ; } } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } finally { structural . removeStructuralListener ( this ) ; } } synchronized public Object [ ] children ( ) { return children . toArray ( ) ; } synchronized public void childAdded ( StructuralEvent event ) { logger . debug ( "" + event . getIndex ( ) + "" + event . getChild ( ) + "" ) ; try { children . add ( event . getIndex ( ) , event . getChild ( ) ) ; } catch ( IndexOutOfBoundsException e ) { throw new IndexOutOfBoundsException ( "" + structural + "" + e . getMessage ( ) ) ; } notifyAll ( ) ; } synchronized public void childRemoved ( StructuralEvent event ) { logger . debug ( "" + event . getIndex ( ) + "" + event . getChild ( ) + "" ) ; try { children . remove ( event . getIndex ( ) ) ; } catch ( IndexOutOfBoundsException e ) { throw new IndexOutOfBoundsException ( "" + structural + "" + e . getMessage ( ) ) ; } notifyAll ( ) ; } } package org . oddjob . jmx ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . registry . ServerId ; public class MockRemoteDirectory implements RemoteDirectory { public ServerId getServerId ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public < T > Iterable < T > getAllByType ( Class < T > type ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public String getIdFor ( Object bean ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public Object lookup ( String path ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public < T > T lookup ( String path , Class < T > required ) throws ArooaConversionException { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . jmx ; import junit . framework . TestCase ; import org . oddjob . arooa . registry . Address ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryCrawler ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . MockBeanDirectoryOwner ; import org . oddjob . arooa . registry . MockBeanRegistry ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . registry . ServerId ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . jmx . client . ClientHandlerResolver ; import org . oddjob . jmx . server . ServerInfo ; public class RemoteRegistryCrawlerTest extends TestCase { class ServerRegistry extends SimpleBeanRegistry implements RemoteDirectory { ServerId serverId ; public ServerRegistry ( ServerId serverId ) { this . serverId = serverId ; } public ServerId getServerId ( ) { return serverId ; } } class OurRemote extends MockRemoteOddjobBean { public ServerInfo serverInfo ( ) { return new ServerInfo ( new Address ( new ServerId ( "" ) , new Path ( "" ) ) , new ClientHandlerResolver [ ] ) ; } } public void testRemoteBean ( ) { RemoteRegistryCrawler test = new RemoteRegistryCrawler ( new MockBeanRegistry ( ) ) ; OurRemote remote = new OurRemote ( ) ; Address address = test . addressFor ( remote ) ; assertEquals ( "" , address . toString ( ) ) ; } public void testSingle ( ) { Object comp = new Object ( ) ; BeanRegistry cr = new SimpleBeanRegistry ( ) ; cr . register ( "" , comp ) ; RemoteRegistryCrawler test = new RemoteRegistryCrawler ( cr ) ; Address address = test . addressFor ( comp ) ; assertNotNull ( address ) ; assertEquals ( ServerId . local ( ) , address . getServerId ( ) ) ; assertEquals ( new Path ( "" ) , address . getPath ( ) ) ; assertEquals ( comp , test . objectForAddress ( address ) ) ; } class Component extends MockBeanDirectoryOwner { final String name ; BeanDirectory directory ; Component ( String name ) { this . name = name ; } public String toString ( ) { return name ; } public BeanDirectory provideBeanDirectory ( ) { return directory ; } } public void testSameServer ( ) { Component comp1 = new Component ( "" ) ; ServerRegistry cr1 = new ServerRegistry ( new ServerId ( "" ) ) ; cr1 . register ( "" , comp1 ) ; ServerRegistry cr2 = new ServerRegistry ( new ServerId ( "" ) ) ; OurRemote comp2 = new OurRemote ( ) ; comp1 . directory = cr2 ; cr2 . register ( "" , comp2 ) ; assertEquals ( comp2 , cr1 . lookup ( "" ) ) ; RemoteRegistryCrawler test = new RemoteRegistryCrawler ( cr1 ) ; Address address = test . addressFor ( comp2 ) ; assertNotNull ( address ) ; assertEquals ( "" , address . toString ( ) ) ; assertEquals ( comp2 , test . objectForAddress ( address ) ) ; } public void testDifferentServer ( ) { Component comp1 = new Component ( "" ) ; ServerRegistry cr1 = new ServerRegistry ( new ServerId ( "" ) ) ; cr1 . register ( "" , comp1 ) ; ServerRegistry cr2 = new ServerRegistry ( new ServerId ( "" ) ) ; comp1 . directory = cr2 ; OurRemote comp2 = new OurRemote ( ) ; cr2 . register ( "" , comp2 ) ; assertEquals ( "" , new BeanDirectoryCrawler ( cr1 ) . pathForObject ( comp2 ) . toString ( ) ) ; assertEquals ( comp2 , cr1 . lookup ( "" ) ) ; RemoteRegistryCrawler test = new RemoteRegistryCrawler ( cr1 ) ; RemoteDirectory checkCR = ( RemoteDirectory ) test . registryForServer ( new ServerId ( "" ) ) ; assertNotNull ( checkCR ) ; assertEquals ( comp2 , test . objectForAddress ( new Address ( new ServerId ( "" ) , new Path ( "" ) ) ) ) ; } public void testTwoFaced ( ) { Component comp1 = new Component ( "" ) ; ServerRegistry cr1 = new ServerRegistry ( new ServerId ( "" ) ) ; cr1 . register ( "" , comp1 ) ; ServerRegistry cr2 = new ServerRegistry ( new ServerId ( "" ) ) ; comp1 . directory = cr2 ; cr2 . register ( "" , comp1 ) ; assertEquals ( "" , new BeanDirectoryCrawler ( cr1 ) . pathForObject ( comp1 ) . toString ( ) ) ; assertEquals ( comp1 , cr1 . lookup ( "" ) ) ; RemoteRegistryCrawler test = new RemoteRegistryCrawler ( cr2 ) ; assertEquals ( comp1 , test . objectForAddress ( new Address ( new ServerId ( "" ) , new Path ( "" ) ) ) ) ; } public void testNoServerFor ( ) { Component comp1 = new Component ( "" ) ; SimpleBeanRegistry cr1 = new SimpleBeanRegistry ( ) ; cr1 . register ( "" , comp1 ) ; ServerRegistry cr2 = new ServerRegistry ( new ServerId ( "" ) ) ; comp1 . directory = cr2 ; RemoteRegistryCrawler test = new RemoteRegistryCrawler ( cr1 ) ; assertNull ( test . registryForServer ( new ServerId ( "" ) ) ) ; assertEquals ( cr1 , test . registryForServer ( ServerId . local ( ) ) ) ; } } package org . oddjob ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . ScheduledExecutorService ; public class MockOddjobExecutors implements OddjobExecutors { @ Override public ExecutorService getPoolExecutor ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public ScheduledExecutorService getScheduledExecutor ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob ; import java . beans . PropertyVetoException ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . life . MockComponentPersister ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . persist . MapPersister ; import org . oddjob . persist . OddjobPersister ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateEvent ; public class OddjobPersisterTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddjobPersisterTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; } private class OurPersister implements OddjobPersister { private final Path rootPath ; private Map < String , InnerPersister > persisters = new HashMap < String , InnerPersister > ( ) ; private List < String > persisterIds = new ArrayList < String > ( ) ; public OurPersister ( String rootPath ) { this . rootPath = new Path ( rootPath ) ; } public ComponentPersister persisterFor ( String persisterId ) { persisterIds . add ( persisterId ) ; String path = persisterId ; if ( path == null ) { path = rootPath . toString ( ) ; } InnerPersister inner = persisters . get ( path ) ; if ( inner == null ) { inner = new InnerPersister ( path ) ; persisters . put ( path , inner ) ; logger . debug ( "" + path ) ; } else { logger . debug ( "" + path ) ; } return inner ; } private class InnerPersister extends MockComponentPersister implements OddjobPersister { private final String path ; private boolean closed ; Map < String , Object > store = new HashMap < String , Object > ( ) ; public InnerPersister ( String path ) { this . path = path ; } @ Override public ComponentPersister persisterFor ( String id ) { return OurPersister . this . persisterFor ( new Path ( this . path ) . addId ( id ) . toString ( ) ) ; } @ Override public void close ( ) { closed = true ; } @ Override public void persist ( String id , Object proxy , ArooaSession session ) { if ( closed ) { return ; } try { store . put ( id , Helper . copy ( proxy ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } @ Override public Object restore ( String id , ClassLoader classLoader , ArooaSession session ) { return store . remove ( id ) ; } @ Override public void remove ( String id , ArooaSession session ) { if ( closed ) { return ; } store . remove ( id ) ; logger . info ( "" + id ) ; } } } public void testPersist ( ) throws PropertyVetoException { String xml = "" + "" + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; OurPersister persister = new OurPersister ( "" ) ; test . setPersister ( persister ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; assertEquals ( , persister . persisters . size ( ) ) ; test . run ( ) ; OurPersister . InnerPersister inner = persister . persisters . get ( "" ) ; assertEquals ( , inner . store . size ( ) ) ; assertTrue ( inner . store . containsKey ( "" ) ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( new OddjobLookup ( test ) . lookup ( "" ) ) ) ; test . destroy ( ) ; } String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; public void testNestedPersisterResets ( ) throws PropertyVetoException , ArooaPropertyException , ArooaConversionException { Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; OurPersister persister = new OurPersister ( "" ) ; test . setPersister ( persister ) ; logger . debug ( "" ) ; test . run ( ) ; OurPersister . InnerPersister outer = persister . persisters . get ( "" ) ; OurPersister . InnerPersister middle = persister . persisters . get ( "" ) ; OurPersister . InnerPersister inner = persister . persisters . get ( "" ) ; assertNotNull ( inner ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( new OddjobLookup ( test ) . lookup ( "" ) ) ) ; assertEquals ( , outer . store . size ( ) ) ; assertEquals ( , middle . store . size ( ) ) ; assertEquals ( , inner . store . size ( ) ) ; assertTrue ( outer . store . containsKey ( "" ) ) ; assertTrue ( middle . store . containsKey ( "" ) ) ; assertTrue ( inner . store . containsKey ( "" ) ) ; assertEquals ( , persister . persisterIds . size ( ) ) ; assertEquals ( null , persister . persisterIds . get ( ) ) ; assertEquals ( "" , persister . persisterIds . get ( ) ) ; assertEquals ( "" , persister . persisterIds . get ( ) ) ; logger . debug ( "" ) ; test . hardReset ( ) ; logger . debug ( "" ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( new OddjobLookup ( test ) . lookup ( "" ) ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; logger . debug ( "" ) ; Resetable middleOj = new OddjobLookup ( test ) . lookup ( "" , Resetable . class ) ; middleOj . hardReset ( ) ; logger . debug ( "" ) ; ( ( Runnable ) middleOj ) . run ( ) ; logger . debug ( "" ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . destroy ( ) ; assertEquals ( ParentState . DESTROYED , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNestedPersisterRestore ( ) throws PropertyVetoException , ArooaPropertyException , ArooaConversionException { Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; OurPersister persister = new OurPersister ( "" ) ; test . setPersister ( persister ) ; logger . debug ( "" ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( new OddjobLookup ( test ) . lookup ( "" ) ) ) ; logger . debug ( "" ) ; test . destroy ( ) ; Oddjob copy = new Oddjob ( ) ; copy . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; copy . setPersister ( persister ) ; logger . debug ( "" ) ; copy . load ( ) ; assertEquals ( ParentState . READY , copy . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup copyLookup = new OddjobLookup ( copy ) ; Object middleOj = copyLookup . lookup ( "" ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( middleOj ) ) ; assertEquals ( null , copyLookup . lookup ( "" ) ) ; logger . debug ( "" ) ; ( ( Oddjob ) middleOj ) . load ( ) ; Object innerOj = copyLookup . lookup ( "" ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( innerOj ) ) ; logger . debug ( "" ) ; ( ( Oddjob ) innerOj ) . load ( ) ; Object echo = copyLookup . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( echo ) ) ; logger . debug ( "" ) ; copy . destroy ( ) ; assertEquals ( ParentState . DESTROYED , copy . lastStateEvent ( ) . getState ( ) ) ; } public void testResetsBeforeLoad ( ) throws PropertyVetoException , ArooaPropertyException , ArooaConversionException { Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; OurPersister persister = new OurPersister ( "" ) ; test . setPersister ( persister ) ; logger . debug ( "" ) ; test . run ( ) ; StateEvent jse1 = test . lastStateEvent ( ) ; assertEquals ( ParentState . COMPLETE , jse1 . getState ( ) ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( new OddjobLookup ( test ) . lookup ( "" ) ) ) ; logger . debug ( "" ) ; test . destroy ( ) ; Oddjob copy = new Oddjob ( ) ; copy . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; copy . setPersister ( persister ) ; logger . debug ( "" ) ; copy . hardReset ( ) ; copy . run ( ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( copy . lastStateEvent ( ) . getTime ( ) . getTime ( ) > jse1 . getTime ( ) . getTime ( ) ) ; OddjobLookup copyLookup = new OddjobLookup ( copy ) ; Object middleOj = copyLookup . lookup ( "" ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( middleOj ) ) ; Object innerOj = copyLookup . lookup ( "" ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( innerOj ) ) ; Object echo = copyLookup . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( echo ) ) ; logger . debug ( "" ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; copy . destroy ( ) ; assertEquals ( ParentState . DESTROYED , copy . lastStateEvent ( ) . getState ( ) ) ; } public static class FailOnce implements Runnable , Serializable { private static final long serialVersionUID = ; boolean ok ; @ Override public void run ( ) { if ( ! ok ) { ok = true ; throw new RuntimeException ( "" ) ; } } } String failureXml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + FailOnce . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; public void testSoftResetsBeforeLoad ( ) { Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , failureXml ) ) ; OurPersister persister = new OurPersister ( "" ) ; test . setPersister ( persister ) ; logger . debug ( "" ) ; test . run ( ) ; assertEquals ( ParentState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . EXCEPTION , Helper . getJobState ( new OddjobLookup ( test ) . lookup ( "" ) ) ) ; logger . debug ( "" ) ; test . destroy ( ) ; Oddjob copy = new Oddjob ( ) ; copy . setConfiguration ( new XMLConfiguration ( "" , failureXml ) ) ; copy . setPersister ( persister ) ; logger . debug ( "" ) ; copy . softReset ( ) ; copy . run ( ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( new OddjobLookup ( copy ) . lookup ( "" ) ) ) ; logger . debug ( "" ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; copy . destroy ( ) ; assertEquals ( ParentState . DESTROYED , copy . lastStateEvent ( ) . getState ( ) ) ; } public void testResetBeforeLoadPersister ( ) throws ComponentPersistException { MapPersister persister = new MapPersister ( ) ; final ComponentPersister compPersister = persister . persisterFor ( null ) ; ArooaSession session = new StandardArooaSession ( ) { public ComponentPersister getComponentPersister ( ) { return compPersister ; } } ; Oddjob oddjob = new Oddjob ( ) ; Helper . register ( oddjob , session , "" ) ; oddjob . setArooaSession ( session ) ; oddjob . hardReset ( ) ; Object copy = persister . persisterFor ( null ) . restore ( "" , getClass ( ) . getClassLoader ( ) , session ) ; assertNotNull ( copy ) ; } } package org . oddjob . structural ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import java . util . concurrent . CountDownLatch ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . atomic . AtomicInteger ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . MockStructural ; public class ChildHelperTest extends TestCase { private static final Logger logger = Logger . getLogger ( ChildHelperTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; } public void testReplaceChild ( ) { class MyL implements StructuralListener { int added ; int removed ; public void childAdded ( StructuralEvent event ) { added = event . getIndex ( ) ; } public void childRemoved ( StructuralEvent event ) { removed = event . getIndex ( ) ; } } Object o1 = new Object ( ) ; Object o2 = new Object ( ) ; Object o3 = new Object ( ) ; ChildHelper < Object > test = new ChildHelper < Object > ( new MockStructural ( ) ) ; MyL l = new MyL ( ) ; test . addStructuralListener ( l ) ; test . insertChild ( , o1 ) ; test . insertChild ( , o2 ) ; test . removeChildAt ( ) ; test . insertChild ( , o3 ) ; assertEquals ( "" , o3 , test . getChildren ( ) [ ] ) ; assertEquals ( "" , , l . removed ) ; assertEquals ( "" , , l . added ) ; } public void testDeadlockOnNotify ( ) throws InterruptedException { final ExecutorService executor = Executors . newFixedThreadPool ( ) ; final ChildHelper < Object > test = new ChildHelper < Object > ( new MockStructural ( ) ) ; test . insertChild ( , new Object ( ) ) ; test . insertChild ( , new Object ( ) ) ; test . insertChild ( , new Object ( ) ) ; test . insertChild ( , new Object ( ) ) ; test . insertChild ( , new Object ( ) ) ; class LoopbackListener implements StructuralListener { ChildHelper < Object > copies = new ChildHelper < Object > ( new MockStructural ( ) ) ; AtomicInteger events = new AtomicInteger ( ) ; CountDownLatch finished = new CountDownLatch ( ) ; public void childAdded ( StructuralEvent event ) { copies . insertChild ( event . getIndex ( ) , event . getChild ( ) ) ; onEvent ( event ) ; } public void childRemoved ( StructuralEvent event ) { copies . removeChildAt ( event . getIndex ( ) ) ; onEvent ( event ) ; } private void onEvent ( StructuralEvent event ) { int events = this . events . incrementAndGet ( ) ; logger . debug ( "" + events ) ; if ( events < ) { executor . submit ( new Runnable ( ) { public void run ( ) { logger . debug ( "" ) ; test . insertChild ( , new Object ( ) ) ; } } ) ; } else if ( events < ) { executor . submit ( new Runnable ( ) { public void run ( ) { logger . debug ( "" ) ; test . removeChildAt ( ) ; } } ) ; } finished . countDown ( ) ; } } LoopbackListener listener = new LoopbackListener ( ) ; logger . debug ( "" ) ; test . addStructuralListener ( listener ) ; logger . debug ( "" ) ; listener . finished . await ( ) ; assertEquals ( , listener . copies . size ( ) ) ; logger . debug ( "" ) ; executor . shutdown ( ) ; } private class StructureAlteringListener implements StructuralListener { ChildHelper < String > test ; List < String > children = new ArrayList < String > ( ) ; @ Override public void childAdded ( StructuralEvent event ) { children . add ( event . getIndex ( ) , ( String ) event . getChild ( ) ) ; if ( children . size ( ) == ) { test . insertChild ( , "" ) ; } if ( children . size ( ) == ) { test . removeChildAt ( ) ; } } @ Override public void childRemoved ( StructuralEvent event ) { children . remove ( event . getIndex ( ) ) ; } } public void testNoMissedEvent ( ) { ChildHelper < String > test = new ChildHelper < String > ( new MockStructural ( ) ) ; test . insertChild ( , "" ) ; StructureAlteringListener listener = new StructureAlteringListener ( ) ; listener . test = test ; test . addStructuralListener ( listener ) ; assertEquals ( , listener . children . size ( ) ) ; assertEquals ( "" , listener . children . get ( ) ) ; } private enum Type { ADDED , REMOVED } private class SimpleListener implements StructuralListener { private List < Type > types = new ArrayList < Type > ( ) ; private List < StructuralEvent > events = new ArrayList < StructuralEvent > ( ) ; @ Override public void childAdded ( StructuralEvent event ) { types . add ( Type . ADDED ) ; events . add ( event ) ; } @ Override public void childRemoved ( StructuralEvent event ) { types . add ( Type . REMOVED ) ; events . add ( event ) ; } } public void testAddAndRemove ( ) { ChildHelper < Object > test = new ChildHelper < Object > ( new MockStructural ( ) ) ; SimpleListener listener = new SimpleListener ( ) ; test . addStructuralListener ( listener ) ; Object o1 = new Object ( ) ; Object o2 = new Object ( ) ; Object o3 = new Object ( ) ; Object o4 = new Object ( ) ; test . addChild ( o1 ) ; assertEquals ( , listener . types . size ( ) ) ; assertEquals ( Type . ADDED , listener . types . get ( ) ) ; assertEquals ( o1 , listener . events . get ( ) . getChild ( ) ) ; assertEquals ( , listener . events . get ( ) . getIndex ( ) ) ; test . addChild ( o2 ) ; assertEquals ( , listener . types . size ( ) ) ; assertEquals ( Type . ADDED , listener . types . get ( ) ) ; assertEquals ( o2 , listener . events . get ( ) . getChild ( ) ) ; assertEquals ( , listener . events . get ( ) . getIndex ( ) ) ; test . addChild ( o3 ) ; assertEquals ( , listener . types . size ( ) ) ; assertEquals ( Type . ADDED , listener . types . get ( ) ) ; assertEquals ( o3 , listener . events . get ( ) . getChild ( ) ) ; assertEquals ( , listener . events . get ( ) . getIndex ( ) ) ; test . removeChild ( o2 ) ; assertEquals ( , listener . types . size ( ) ) ; assertEquals ( Type . REMOVED , listener . types . get ( ) ) ; assertEquals ( o2 , listener . events . get ( ) . getChild ( ) ) ; assertEquals ( , listener . events . get ( ) . getIndex ( ) ) ; test . removeChild ( o1 ) ; assertEquals ( , listener . types . size ( ) ) ; assertEquals ( Type . REMOVED , listener . types . get ( ) ) ; assertEquals ( o1 , listener . events . get ( ) . getChild ( ) ) ; assertEquals ( , listener . events . get ( ) . getIndex ( ) ) ; test . addChild ( o4 ) ; assertEquals ( , listener . types . size ( ) ) ; assertEquals ( Type . ADDED , listener . types . get ( ) ) ; assertEquals ( o4 , listener . events . get ( ) . getChild ( ) ) ; assertEquals ( , listener . events . get ( ) . getIndex ( ) ) ; test . removeChild ( o3 ) ; assertEquals ( , listener . types . size ( ) ) ; assertEquals ( Type . REMOVED , listener . types . get ( ) ) ; assertEquals ( o3 , listener . events . get ( ) . getChild ( ) ) ; assertEquals ( , listener . events . get ( ) . getIndex ( ) ) ; try { test . removeChild ( o1 ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } assertEquals ( , listener . types . size ( ) ) ; } public void testIterable ( ) { ChildHelper < String > test = new ChildHelper < String > ( new MockStructural ( ) ) ; test . insertChild ( , "" ) ; test . insertChild ( , "" ) ; test . insertChild ( , "" ) ; Iterator < String > iterator = test . iterator ( ) ; assertEquals ( true , iterator . hasNext ( ) ) ; assertEquals ( "" , iterator . next ( ) ) ; assertEquals ( true , iterator . hasNext ( ) ) ; assertEquals ( "" , iterator . next ( ) ) ; test . removeChild ( "" ) ; test . insertChild ( , "" ) ; assertEquals ( true , iterator . hasNext ( ) ) ; assertEquals ( "" , iterator . next ( ) ) ; assertEquals ( true , iterator . hasNext ( ) ) ; assertEquals ( "" , iterator . next ( ) ) ; test . removeChild ( "" ) ; test . insertChild ( , "" ) ; assertEquals ( true , iterator . hasNext ( ) ) ; assertEquals ( "" , iterator . next ( ) ) ; assertEquals ( false , iterator . hasNext ( ) ) ; } public void testIterableInFor ( ) { ChildHelper < String > test = new ChildHelper < String > ( new MockStructural ( ) ) ; test . insertChild ( , "" ) ; test . insertChild ( , "" ) ; test . insertChild ( , "" ) ; List < String > results = new ArrayList < String > ( ) ; for ( String next : test ) { results . add ( next ) ; } assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( , results . size ( ) ) ; } } package org . oddjob . structural ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . MockStructural ; public class ChildMatchTest extends TestCase { private static final Logger logger = Logger . getLogger ( ChildMatchTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . debug ( "" + getName ( ) + "" ) ; } private class OurListener implements StructuralListener { List < String > events = new ArrayList < String > ( ) ; private boolean started ; @ Override public void childAdded ( StructuralEvent event ) { if ( ! started ) { return ; } String text = "" + event . getChild ( ) + "" + event . getIndex ( ) ; events . add ( text ) ; logger . debug ( text ) ; } @ Override public void childRemoved ( StructuralEvent event ) { if ( ! started ) { return ; } String text = "" + event . getChild ( ) + "" + event . getIndex ( ) ; events . add ( text ) ; logger . debug ( text ) ; } public void start ( ) { started = true ; } } private class OurChildMatch extends ChildMatch < String > { private final ChildHelper < String > childHelper ; public OurChildMatch ( ChildHelper < String > childHelper ) { super ( new ArrayList < String > ( Arrays . asList ( childHelper . getChildren ( new String [ ] ) ) ) ) ; this . childHelper = childHelper ; } @ Override protected void insertChild ( int index , String child ) { childHelper . insertChild ( index , child ) ; } @ Override protected void removeChildAt ( int index ) { childHelper . removeChildAt ( index ) ; } } public void testExactMatch ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" , "" } ; test . match ( desired ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testReversed ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testInsertedAtBeginning ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" , "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testInsertedInMiddle ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" , "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testInsertedAtEnd ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" , "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testRemoveFromBeginning ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testRemoveFromMiddle ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testRemoveFromEnd ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = new String [ ] { "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testCompletelyDifferent ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testNothingToStartWith ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { "" , "" } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testNothingToEndWith ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; childHelper . insertChild ( , "" ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { } ; test . match ( desired ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( "" , listener . events . get ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } public void testNothingAndNothing ( ) { ChildHelper < String > childHelper = new ChildHelper < String > ( new MockStructural ( ) ) ; OurListener listener = new OurListener ( ) ; childHelper . addStructuralListener ( listener ) ; listener . start ( ) ; ChildMatch < String > test = new OurChildMatch ( childHelper ) ; String [ ] desired = { } ; test . match ( desired ) ; assertEquals ( , listener . events . size ( ) ) ; childHelper . removeStructuralListener ( listener ) ; assertMatches ( childHelper , desired ) ; } private void assertMatches ( ChildHelper < String > childHelper , String [ ] match ) { List < String > children = new ArrayList < String > ( Arrays . asList ( childHelper . getChildren ( new String [ ] ) ) ) ; class CheckMatch extends ChildMatch < String > { boolean failed ; public CheckMatch ( List < String > children ) { super ( children ) ; } @ Override protected void insertChild ( int index , String child ) { failed = true ; } @ Override protected void removeChildAt ( int index ) { failed = true ; } } CheckMatch check = new CheckMatch ( children ) ; check . match ( match ) ; assertFalse ( "" , check . failed ) ; } } package org . oddjob . structural ; import java . util . Arrays ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . BeanDirectoryOwner ; public class DumpRegistryJob implements Runnable , ArooaSessionAware { private ArooaSession session ; public void setArooaSession ( ArooaSession session ) { this . session = session ; } public void run ( ) { BeanDirectory reg = session . getBeanRegistry ( ) ; dump ( , reg ) ; } void dump ( int level , BeanDirectory reg ) { for ( Object component : reg . getAllByType ( Object . class ) ) { System . out . println ( spaces ( level ) + reg . getIdFor ( component ) + "" + component ) ; if ( component instanceof BeanDirectoryOwner ) { BeanDirectory child = ( ( BeanDirectoryOwner ) component ) . provideBeanDirectory ( ) ; dump ( level + , child ) ; } } } String spaces ( int number ) { char [ ] spaces = new char [ number ] ; Arrays . fill ( spaces , '' ) ; return new String ( spaces ) ; } } package org . oddjob ; import java . io . File ; import java . net . URISyntaxException ; import java . net . URL ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . ConversionPath ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . FileType ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . values . properties . PropertiesJob ; public class OddjobNestedTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddjobNestedTest . class ) ; public void testNestedOddjob ( ) throws ArooaParseException , URISyntaxException { URL url = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; File file = new File ( url . toURI ( ) . getPath ( ) ) ; Oddjob oj = new Oddjob ( ) ; oj . setFile ( file ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; Oddjob test = ( Oddjob ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( "" , test ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testSetNestedWithArg ( ) throws URISyntaxException { URL url = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; File file = new File ( url . toURI ( ) . getPath ( ) ) ; Oddjob oj = new Oddjob ( ) ; oj . setFile ( file ) ; oj . run ( ) ; assertEquals ( "" , new OddjobLookup ( oj ) . lookup ( "" ) ) ; assertEquals ( "" , new OddjobLookup ( oj ) . lookup ( "" ) ) ; oj . destroy ( ) ; } public void testNestedPassingProperties ( ) throws Exception { URL url = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; File file = new File ( url . toURI ( ) . getPath ( ) ) ; Oddjob oj = new Oddjob ( ) ; oj . setFile ( file ) ; oj . run ( ) ; assertEquals ( "" , new OddjobLookup ( oj ) . lookup ( "" ) ) ; oj . destroy ( ) ; } public void testExportJob ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful stateful = lookup . lookup ( "" , Stateful . class ) ; assertEquals ( JobState . COMPLETE , stateful . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; oddjob . destroy ( ) ; } public void testExportInOddjob ( ) throws Exception { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . run ( ) ; String fruit = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , fruit ) ; oj . destroy ( ) ; } public void testArooaValueConversionAssumptionTest ( ) throws NoConversionAvailableException , ConversionFailedException { ArooaConverter converter = new DefaultConverter ( ) ; ConversionPath < ValueType , ArooaObject > path = converter . findConversion ( ValueType . class , ArooaObject . class ) ; assertEquals ( "" , path . toString ( ) ) ; ValueType value1 = new ValueType ( ) ; value1 . setValue ( new ArooaObject ( "" ) ) ; ArooaObject result1 = converter . convert ( value1 , ArooaObject . class ) ; assertEquals ( "" , result1 . toValue ( ) ) ; ValueType value2 = new ValueType ( ) ; FileType fileType = new FileType ( ) ; fileType . setFile ( new File ( "" ) ) ; value2 . setValue ( fileType ) ; try { converter . convert ( value2 , ArooaObject . class ) ; fail ( "" ) ; } catch ( ConversionFailedException e ) { } ValueType value3 = new ValueType ( ) ; value3 . setValue ( null ) ; ArooaObject result = converter . convert ( value3 , ArooaObject . class ) ; assertNull ( result ) ; } public void testExportBean ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; String text1 = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , text1 ) ; String text2 = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , text2 ) ; String text3 = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , text3 ) ; String text4 = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , text4 ) ; oddjob . destroy ( ) ; } public void testSharedInheritance ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oj ) ; String snackText = lookup . lookup ( "" , String . class ) ; String connectionText = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , snackText ) ; assertEquals ( "" , connectionText ) ; Oddjob inner = lookup . lookup ( "" , Oddjob . class ) ; inner . unload ( ) ; Resetable snackEcho = lookup . lookup ( "" , Resetable . class ) ; Resetable connectionEcho = lookup . lookup ( "" , Resetable . class ) ; snackEcho . hardReset ( ) ; connectionEcho . hardReset ( ) ; ( ( Runnable ) snackEcho ) . run ( ) ; ( ( Runnable ) connectionEcho ) . run ( ) ; snackText = lookup . lookup ( "" , String . class ) ; connectionText = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , snackText ) ; assertEquals ( "" , connectionText ) ; oj . destroy ( ) ; } public void testExportedProperty ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; PropertiesJob props1 = lookup . lookup ( "" , PropertiesJob . class ) ; PropertiesJob props2 = lookup . lookup ( "" , PropertiesJob . class ) ; Map < String , String > description1 = props1 . describe ( ) ; Map < String , String > description2 = props2 . describe ( ) ; assertEquals ( , description1 . size ( ) ) ; assertEquals ( , description2 . size ( ) ) ; assertEquals ( "" , description1 . get ( "" ) ) ; assertEquals ( "" , description2 . get ( "" ) ) ; oddjob . destroy ( ) ; } } package org . oddjob ; import java . io . File ; import java . util . concurrent . Exchanger ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . io . BufferType ; import org . oddjob . jobs . ExecJob ; import org . oddjob . jobs . WaitJob ; import org . oddjob . state . JobState ; import org . oddjob . state . State ; import org . oddjob . state . StateConditions ; public class MainShutdownTest extends TestCase { private static final Logger logger = Logger . getLogger ( MainTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; } public static class OurSimpleJob extends SimpleJob implements Stoppable { boolean stopped ; Thread t ; Exchanger < Void > exchanger = new Exchanger < Void > ( ) ; @ Override protected synchronized int execute ( ) throws Throwable { t = Thread . currentThread ( ) ; exchanger . exchange ( null ) ; try { while ( true ) { wait ( ) ; } } catch ( InterruptedException e ) { logger . debug ( "" ) ; } return ; } public synchronized void onStop ( ) { stopped = true ; t . interrupt ( ) ; } } public void testShutdownHook ( ) throws Exception { String xml = "" + "" + "" + OurSimpleJob . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; OurSimpleJob r = ( OurSimpleJob ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertNotNull ( r ) ; Thread t = new Thread ( oddjob ) ; t . start ( ) ; logger . info ( "" ) ; r . exchanger . exchange ( null ) ; OddjobRunner . ShutdownHook hook = new OddjobRunner ( oddjob ) . new ShutdownHook ( ) ; hook . run ( ) ; assertTrue ( r . stopped ) ; } public static class NaughtyJob implements Runnable { @ Override public void run ( ) { WaitJob wait = new WaitJob ( ) { @ Override public int execute ( ) throws Exception { System . out . println ( "" ) ; return super . execute ( ) ; } } ; new Thread ( wait ) . start ( ) ; } } public void testKillerThread ( ) throws FailedToStopException , InterruptedException { OurDirs dirs = new OurDirs ( ) ; File testClasses = dirs . relative ( "" ) ; if ( ! testClasses . exists ( ) ) { testClasses = dirs . relative ( "" ) ; } if ( ! testClasses . exists ( ) ) { fail ( "" ) ; } ConsoleCapture console = new ConsoleCapture ( ) ; ExecJob exec = new ExecJob ( ) ; exec . setArgs ( new String [ ] { "" , "" + OddjobRunner . KILLER_TIMEOUT_PROPERTY + "" , "" , dirs . relative ( "" ) . getPath ( ) , "" , testClasses . getPath ( ) , "" , dirs . relative ( "" ) . getPath ( ) } ) ; console . capture ( exec . consoleLog ( ) ) ; new Thread ( exec ) . start ( ) ; console . dump ( logger ) ; WaitJob wait = new WaitJob ( ) ; wait . setFor ( exec ) ; wait . setState ( StateConditions . EXECUTING ) ; wait . run ( ) ; while ( true ) { Thread . sleep ( ) ; BufferType buffer = new BufferType ( ) ; buffer . setLines ( console . getLines ( ) ) ; buffer . configured ( ) ; State jobState = exec . lastStateEvent ( ) . getState ( ) ; if ( buffer . getText ( ) . contains ( "" ) ) { break ; } else { if ( JobState . EXECUTING != jobState ) { console . dump ( logger ) ; fail ( "" ) ; } } logger . info ( "" ) ; } exec . stop ( ) ; console . dump ( logger ) ; assertEquals ( , exec . getExitValue ( ) ) ; assertEquals ( JobState . INCOMPLETE , exec . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; } } package org . oddjob ; import java . util . Arrays ; import org . apache . log4j . Logger ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconListener ; public class IconSteps { private static final Logger logger = Logger . getLogger ( IconSteps . class ) ; private Iconic iconic ; private Listener listener ; private long timeout = ; public IconSteps ( Iconic iconic ) { if ( iconic == null ) { throw new NullPointerException ( "" ) ; } this . iconic = iconic ; } class Listener implements IconListener { private final String [ ] steps ; private int index ; private boolean done ; private String failureMessage ; public Listener ( String [ ] steps ) { this . steps = steps ; } @ Override public void iconEvent ( IconEvent event ) { String position ; if ( failureMessage != null ) { position = "" ; } else { position = "" + index + "" ; } logger . info ( "" + event . getIconId ( ) + "" + position + "" + event . getSource ( ) + "" ) ; if ( index >= steps . length ) { failureMessage = "" + event . getIconId ( ) + "" + index + "" ; } else { if ( event . getIconId ( ) == steps [ index ] ) { if ( ++ index == steps . length ) { done = true ; synchronized ( this ) { notifyAll ( ) ; } } } else { done = true ; failureMessage = "" + steps [ index ] + "" + event . getIconId ( ) + "" + index + "" ; synchronized ( this ) { notifyAll ( ) ; } } } } } ; public void startCheck ( String ... steps ) { if ( listener != null ) { throw new IllegalStateException ( "" ) ; } if ( steps == null || steps . length == ) { throw new IllegalStateException ( "" ) ; } this . listener = new Listener ( steps ) ; iconic . addIconListener ( listener ) ; } public void checkNow ( ) { try { if ( listener . done ) { if ( listener . failureMessage != null ) { throw new IllegalStateException ( listener . failureMessage ) ; } } else { throw new IllegalStateException ( "" + listener . steps . length + "" + Arrays . toString ( listener . steps ) + "" + listener . index + "" ) ; } } finally { iconic . removeIconListener ( listener ) ; listener = null ; } } public void checkWait ( ) throws InterruptedException { if ( listener == null ) { throw new IllegalStateException ( "" ) ; } logger . info ( "" + "" + iconic + "" + Arrays . toString ( listener . steps ) ) ; if ( ! listener . done ) { synchronized ( listener ) { listener . wait ( timeout ) ; } } checkNow ( ) ; logger . info ( "" ) ; } public long getTimeout ( ) { return timeout ; } public void setTimeout ( long timeout ) { this . timeout = timeout ; } } package org . oddjob ; abstract public class WaitHelper implements Runnable { static final long INTERVAL = ; static final int RETRIES = ; private final int retries ; private final long interval ; public WaitHelper ( ) { this ( INTERVAL , RETRIES ) ; } public WaitHelper ( int retries ) { this ( INTERVAL , retries ) ; } public WaitHelper ( long interval , int retries ) { this . interval = interval ; this . retries = retries ; } public abstract boolean condition ( ) throws Exception ; public void onRetry ( ) { } @ Override public final void run ( ) { int retries = this . retries ; while ( true ) { try { if ( condition ( ) ) { break ; } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } if ( -- retries < ) { throw new RuntimeException ( "" ) ; } onRetry ( ) ; try { Thread . sleep ( interval ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; break ; } } } } package org . oddjob ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaException ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . types . XMLConfigurationType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateListener ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; import org . oddjob . util . URLClassLoaderType ; public class OddjobLoadTest extends TestCase { public void testReset ( ) { class MyL implements StructuralListener { int count ; public void childAdded ( StructuralEvent event ) { count ++ ; } public void childRemoved ( StructuralEvent event ) { count -- ; } } class MySL implements StateListener { List < State > states = new ArrayList < State > ( ) ; public void jobStateChange ( StateEvent event ) { states . add ( event . getState ( ) ) ; } } String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; MyL childListener = new MyL ( ) ; oj . addStructuralListener ( childListener ) ; assertEquals ( , childListener . count ) ; oj . load ( ) ; Stateful flag = ( Stateful ) new OddjobLookup ( oj ) . lookup ( "" ) ; MySL stateListener = new MySL ( ) ; flag . addStateListener ( stateListener ) ; assertEquals ( , stateListener . states . size ( ) ) ; assertEquals ( JobState . READY , stateListener . states . get ( ) ) ; assertEquals ( , childListener . count ) ; oj . hardReset ( ) ; assertEquals ( , stateListener . states . size ( ) ) ; assertEquals ( JobState . DESTROYED , stateListener . states . get ( ) ) ; assertEquals ( , childListener . count ) ; oj . load ( ) ; assertEquals ( , stateListener . states . size ( ) ) ; assertEquals ( , childListener . count ) ; oj . hardReset ( ) ; assertEquals ( , childListener . count ) ; oj . load ( ) ; assertEquals ( , childListener . count ) ; oj . destroy ( ) ; } public void testSoftReset ( ) { class MyL implements StructuralListener { int count ; public void childAdded ( StructuralEvent event ) { count ++ ; } public void childRemoved ( StructuralEvent event ) { count -- ; } } String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; MyL l = new MyL ( ) ; oj . addStructuralListener ( l ) ; assertEquals ( , l . count ) ; oj . load ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . softReset ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . load ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . softReset ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . load ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testSoftResetOnFailure ( ) { String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . EXCEPTION , oj . lastStateEvent ( ) . getState ( ) ) ; String xml2 = "" + "" + "" + "" + "" ; oj . setConfiguration ( new XMLConfiguration ( "" , xml2 ) ) ; oj . load ( ) ; assertEquals ( ParentState . EXCEPTION , oj . lastStateEvent ( ) . getState ( ) ) ; oj . softReset ( ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testLoadNoChild ( ) throws ArooaParseException { String config = "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; test . load ( ) ; Object root = new OddjobLookup ( test ) . lookup ( "" ) ; assertEquals ( Oddjob . OddjobRoot . class , root . getClass ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; test . load ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . destroy ( ) ; } public void testLoadNoFile ( ) { OurDirs ourDirs = new OurDirs ( ) ; File file = ourDirs . relative ( "" ) ; file . delete ( ) ; Oddjob test = new Oddjob ( ) ; test . setFile ( file ) ; test . load ( ) ; assertEquals ( ParentState . READY , Helper . getJobState ( test ) ) ; assertTrue ( file . exists ( ) ) ; test . destroy ( ) ; } public void testLoadNestedOddjob ( ) throws ArooaParseException { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . load ( ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; Oddjob test = ( Oddjob ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( "" , test ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; test . load ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testLoadOddjobClassloader ( ) throws ArooaConversionException { String config = "" + "" + "" + "" + "" + URLClassLoaderType . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . load ( ) ; String nestedConf = "" ; Oddjob test = new OddjobLookup ( oj ) . lookup ( "" , Oddjob . class ) ; test . setConfiguration ( new XMLConfiguration ( "" , nestedConf ) ) ; test . load ( ) ; assertNotNull ( "" , test . getClassLoader ( ) ) ; oj . destroy ( ) ; } public void testLookup ( ) throws Exception { String nested = "" + "" + "" + "" + "" ; String config = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; XMLConfigurationType configType = new XMLConfigurationType ( ) ; configType . setXml ( nested ) ; oj . setExport ( "" , configType ) ; assertTrue ( oj . isLoadable ( ) ) ; oj . load ( ) ; assertFalse ( oj . isLoadable ( ) ) ; Loadable loadable = ( Loadable ) new OddjobLookup ( oj ) . lookup ( "" ) ; loadable . load ( ) ; String fruit = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , fruit ) ; oj . destroy ( ) ; assertTrue ( oj . isLoadable ( ) ) ; } public void testArgs ( ) throws Exception { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . setArgs ( new String [ ] { "" } ) ; oj . load ( ) ; Runnable variables = ( Runnable ) new OddjobLookup ( oj ) . lookup ( "" ) ; variables . run ( ) ; String fruit = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , fruit ) ; oj . destroy ( ) ; } public void testSetArgs ( ) { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . load ( ) ; Loadable loadable = ( Loadable ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertTrue ( loadable . isLoadable ( ) ) ; loadable . load ( ) ; assertFalse ( loadable . isLoadable ( ) ) ; assertEquals ( "" , new OddjobLookup ( oj ) . lookup ( "" ) ) ; oj . destroy ( ) ; } public void testExport ( ) throws Exception { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . load ( ) ; Loadable loadable = ( Loadable ) new OddjobLookup ( oj ) . lookup ( "" ) ; loadable . load ( ) ; Runnable runnable = ( Runnable ) new OddjobLookup ( oj ) . lookup ( "" ) ; runnable . run ( ) ; String fruit = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , fruit ) ; oj . destroy ( ) ; } public void testRegistryManagement ( ) throws ArooaParseException { final ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; class OurContext extends MockArooaContext { @ Override public ArooaSession getSession ( ) { return session ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void configure ( ) throws ArooaException { } } ; } } Oddjob oj = new Oddjob ( ) ; oj . setArooaSession ( session ) ; ComponentPool pool = session . getComponentPool ( ) ; pool . registerComponent ( new ComponentTrinity ( oj , oj , new OurContext ( ) ) , "" ) ; String xml = "" + "" + "" + "" + "" ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; BeanDirectory dir = session . getBeanRegistry ( ) ; assertEquals ( null , dir . lookup ( "" ) ) ; oj . load ( ) ; assertNotNull ( dir . lookup ( "" ) ) ; oj . hardReset ( ) ; assertEquals ( null , dir . lookup ( "" ) ) ; oj . load ( ) ; assertNotNull ( dir . lookup ( "" ) ) ; oj . destroy ( ) ; } public static class ReluctantToDie extends SimpleJob { boolean die ; @ Override protected int execute ( ) throws Throwable { return ; } @ Override public void onDestroy ( ) { super . onDestroy ( ) ; if ( ! die ) { die = true ; throw new IllegalStateException ( "" ) ; } } } public void testFailedDestroy ( ) { String xml = "" + "" + "" + ReluctantToDie . class . getName ( ) + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . load ( ) ; try { test . destroy ( ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } assertFalse ( test . isLoadable ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . destroy ( ) ; assertEquals ( ParentState . DESTROYED , test . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . deploy . LinkedDescriptor ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . life . ComponentProxyResolver ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . CutAndPasteSupport ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . arooa . standard . ExtendedTools ; import org . oddjob . arooa . standard . StandardArooaDescriptor ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . standard . StandardTools ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class OddjobTest2 extends TestCase { class OurStructuralListener implements StructuralListener { List < Object > children = new ArrayList < Object > ( ) ; public void childAdded ( StructuralEvent event ) { children . add ( event . getChild ( ) ) ; } public void childRemoved ( StructuralEvent event ) { children . add ( null ) ; } } public void testBadSave ( ) throws ArooaParseException , ArooaConversionException { OurStructuralListener structure = new OurStructuralListener ( ) ; String xml = "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . addStructuralListener ( structure ) ; oddjob . run ( ) ; Integer i = new OddjobLookup ( oddjob ) . lookup ( "" , Integer . class ) ; assertEquals ( new Integer ( ) , i ) ; Object sequence = new OddjobLookup ( oddjob ) . lookup ( "" ) ; DragPoint point = oddjob . provideConfigurationSession ( ) . dragPointFor ( sequence ) ; XMLArooaParser xmlParser = new XMLArooaParser ( ) ; ConfigurationHandle handle = xmlParser . parse ( point ) ; ArooaContext xmlDoc = handle . getDocumentContext ( ) ; CutAndPasteSupport . replace ( xmlDoc . getParent ( ) , xmlDoc , new XMLConfiguration ( "" , "" ) ) ; try { handle . save ( ) ; fail ( "" ) ; } catch ( Exception e ) { } OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object sequence2 = lookup . lookup ( "" ) ; Integer i2 = lookup . lookup ( "" , Integer . class ) ; assertEquals ( null , i2 ) ; assertEquals ( structure . children . size ( ) , ) ; assertEquals ( sequence , structure . children . get ( ) ) ; assertEquals ( null , structure . children . get ( ) ) ; assertEquals ( sequence2 , structure . children . get ( ) ) ; oddjob . run ( ) ; Integer i3 = lookup . lookup ( "" , Integer . class ) ; assertEquals ( new Integer ( ) , i3 ) ; oddjob . destroy ( ) ; } class OurComponentPool extends MockComponentPool { Map < String , ArooaContext > contexts = new HashMap < String , ArooaContext > ( ) ; List < Object > components = new ArrayList < Object > ( ) ; List < String > actions = new ArrayList < String > ( ) ; @ Override public void registerComponent ( ComponentTrinity trinity , String id ) { components . add ( trinity . getTheProxy ( ) ) ; contexts . put ( id , trinity . getTheContext ( ) ) ; actions . add ( "" ) ; } @ Override public void remove ( Object component ) { components . add ( component ) ; actions . add ( "" ) ; } @ Override public void configure ( Object component ) { } } class OurSession extends MockArooaSession { OurComponentPool pool = new OurComponentPool ( ) ; ArooaDescriptor descriptor ; ArooaTools tools ; public OurSession ( ArooaDescriptor descriptor ) { this . descriptor = descriptor ; this . tools = new ExtendedTools ( new StandardTools ( ) , descriptor ) ; } @ Override public ArooaDescriptor getArooaDescriptor ( ) { return descriptor ; } @ Override public ComponentPool getComponentPool ( ) { return pool ; } @ Override public ArooaTools getTools ( ) { return tools ; } @ Override public ComponentPersister getComponentPersister ( ) { return null ; } @ Override public ComponentProxyResolver getComponentProxyResolver ( ) { return null ; } } public void testBadSave2 ( ) throws ArooaParseException { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; OurSession session = new OurSession ( new LinkedDescriptor ( descriptor , new StandardArooaDescriptor ( ) ) ) ; String xml = "" + "" + "" + "" + "" ; OddjobServices services = new MockOddjobServices ( ) { @ Override public ClassLoader getClassLoader ( ) { return getClass ( ) . getClassLoader ( ) ; } } ; Oddjob . OddjobRoot root = new Oddjob ( ) . new OddjobRoot ( services ) ; StandardArooaParser parser = new StandardArooaParser ( root , session ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; ArooaContext context = session . pool . contexts . get ( "" ) ; XMLArooaParser xmlParser = new XMLArooaParser ( ) ; ConfigurationHandle handle = xmlParser . parse ( context . getConfigurationNode ( ) ) ; ArooaContext xmlDoc = handle . getDocumentContext ( ) ; CutAndPasteSupport . replace ( xmlDoc . getParent ( ) , xmlDoc , new XMLConfiguration ( "" , "" ) ) ; try { handle . save ( ) ; fail ( "" ) ; } catch ( Exception e ) { } session . pool . contexts . get ( "" ) . getRuntime ( ) . destroy ( ) ; assertEquals ( , session . pool . actions . size ( ) ) ; assertEquals ( "" , session . pool . actions . get ( ) ) ; assertEquals ( "" , session . pool . actions . get ( ) ) ; assertEquals ( "" , session . pool . actions . get ( ) ) ; assertEquals ( "" , session . pool . actions . get ( ) ) ; assertEquals ( "" , session . pool . actions . get ( ) ) ; assertEquals ( "" , session . pool . actions . get ( ) ) ; assertEquals ( session . pool . components . get ( ) , session . pool . components . get ( ) ) ; assertEquals ( session . pool . components . get ( ) , session . pool . components . get ( ) ) ; assertTrue ( session . pool . components . get ( ) != session . pool . components . get ( ) ) ; } } package org . oddjob . input ; import java . io . IOException ; import java . util . Properties ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobInheritance ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . Resetable ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . runtime . PropertyLookup ; import org . oddjob . arooa . standard . MockPropertyLookup ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . persist . MapPersister ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class InputJobTest extends TestCase { private class OurInputHandler implements InputHandler { @ Override public Properties handleInput ( InputRequest [ ] requests ) { Properties properties = new Properties ( ) ; properties . setProperty ( "" , "" ) ; return properties ; } } public void testFullLifeCycle ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" ; OddjobSessionFactory sessionFactory = new OddjobSessionFactory ( ) ; ArooaSession session = sessionFactory . createSession ( ) ; session . getPropertyManager ( ) . addPropertyLookup ( new MockPropertyLookup ( ) { @ Override public String lookup ( String propertyName ) { assertEquals ( "" , propertyName ) ; return "" ; } } ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setArooaSession ( session ) ; oddjob . setInheritance ( OddjobInheritance . SHARED ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setInputHandler ( new OurInputHandler ( ) ) ; PropertyLookup lookup = session . getPropertyManager ( ) ; assertEquals ( "" , lookup . lookup ( "" ) ) ; oddjob . run ( ) ; assertEquals ( "" , lookup . lookup ( "" ) ) ; Resetable resetable = session . getBeanRegistry ( ) . lookup ( "" , Resetable . class ) ; resetable . hardReset ( ) ; assertEquals ( "" , lookup . lookup ( "" ) ) ; oddjob . run ( ) ; assertEquals ( "" , lookup . lookup ( "" ) ) ; oddjob . destroy ( ) ; assertEquals ( "" , lookup . lookup ( "" ) ) ; } public void testSerialisable ( ) throws IOException , ClassNotFoundException , ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; MapPersister persister = new MapPersister ( ) ; OddjobSessionFactory sessionFactory = new OddjobSessionFactory ( ) ; ArooaSession session1 = sessionFactory . createSession ( ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setArooaSession ( session1 ) ; oddjob1 . setInheritance ( OddjobInheritance . SHARED ) ; oddjob1 . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob1 . setInputHandler ( new OurInputHandler ( ) ) ; oddjob1 . setPersister ( persister ) ; oddjob1 . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; oddjob1 . destroy ( ) ; ArooaSession session2 = sessionFactory . createSession ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setArooaSession ( session2 ) ; oddjob2 . setInheritance ( OddjobInheritance . SHARED ) ; oddjob2 . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob2 . setInputHandler ( new OurInputHandler ( ) ) ; oddjob2 . setPersister ( persister ) ; oddjob2 . load ( ) ; InputJob test = new OddjobLookup ( oddjob2 ) . lookup ( "" , InputJob . class ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; PropertyLookup lookup = session2 . getPropertyManager ( ) ; assertEquals ( "" , lookup . lookup ( "" ) ) ; test . hardReset ( ) ; oddjob2 . run ( ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; oddjob2 . destroy ( ) ; } } package org . oddjob . input ; import java . io . ByteArrayInputStream ; import java . io . File ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . OurDirs ; import org . oddjob . jobs . ExecJob ; import org . oddjob . state . JobState ; public class ConsoleInputHandlerTest extends TestCase { private static final Logger logger = Logger . getLogger ( ConsoleInputHandlerTest . class ) ; public void testMultiplePrompts ( ) { OurDirs dirs = new OurDirs ( ) ; File example = dirs . relative ( "" ) ; String command = "" + dirs . relative ( "" ) . getPath ( ) + "" + example + "" ; String input = "" + "" + "" + "" + "" + "" ; ExecJob exec = new ExecJob ( ) ; exec . setCommand ( command ) ; exec . setStdin ( new ByteArrayInputStream ( input . getBytes ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( exec . consoleLog ( ) ) ; exec . run ( ) ; console . close ( ) ; console . dump ( logger ) ; assertEquals ( JobState . COMPLETE , exec . lastStateEvent ( ) . getState ( ) ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; exec . destroy ( ) ; } } package org . oddjob . input ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import junit . framework . TestCase ; public class StdInInputHandlerTest extends TestCase { public void testLineReader ( ) throws IOException { String s = "" + "" + "" + "" ; StdInInputHandler . LineReader test = new StdInInputHandler . LineReader ( new ByteArrayInputStream ( s . getBytes ( ) ) ) ; assertEquals ( "" , test . readLine ( ) ) ; assertEquals ( "" , test . readLine ( ) ) ; assertEquals ( "" , test . readLine ( ) ) ; assertEquals ( "" , test . readLine ( ) ) ; assertEquals ( null , test . readLine ( ) ) ; } } package org . oddjob ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . MockConfigurationHandle ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . registry . SimpleComponentPool ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . state . ParentState ; public class OddjobArooaTest extends TestCase { public void testInnerJobDescriptor ( ) throws ArooaParseException { OddjobServices services = new MockOddjobServices ( ) { @ Override public ClassLoader getClassLoader ( ) { return getClass ( ) . getClassLoader ( ) ; } } ; Oddjob . OddjobRoot rootOddjob = new Oddjob ( ) . new OddjobRoot ( services ) ; StandardArooaParser parser = new StandardArooaParser ( rootOddjob ) ; parser . parse ( new ArooaConfiguration ( ) { public ConfigurationHandle parse ( ArooaContext parentContext ) throws ArooaParseException { ArooaElement element = new ArooaElement ( "" ) ; element = element . addAttribute ( "" , "" ) ; parentContext . getArooaHandler ( ) . onStartElement ( element , parentContext ) ; return new MockConfigurationHandle ( ) ; } } ) ; ArooaSession session = parser . getSession ( ) ; ArooaDescriptor descriptor = session . getArooaDescriptor ( ) ; ArooaBeanDescriptor bd = descriptor . getBeanDescriptor ( new SimpleArooaClass ( Oddjob . OddjobRoot . class ) , session . getTools ( ) . getPropertyAccessor ( ) ) ; assertNotNull ( bd ) ; assertEquals ( "" , bd . getComponentProperty ( ) ) ; assertNull ( bd . getParsingInterceptor ( ) ) ; } public static class SessionCapture implements ArooaSessionAware { ArooaSession session ; public void setArooaSession ( ArooaSession session ) { this . session = session ; } } public void testInnerSession ( ) { String xml = "" + "" + "" + SessionCapture . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; SessionCapture sc = ( SessionCapture ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; ArooaDescriptor descriptor = sc . session . getArooaDescriptor ( ) ; assertEquals ( new SimpleArooaClass ( Oddjob . class ) , descriptor . getElementMappings ( ) . mappingFor ( new ArooaElement ( "" ) , new InstantiationContext ( ArooaType . COMPONENT , null ) ) ) ; } private class OurSession extends StandardArooaSession { SimpleComponentPool componentPool = new SimpleComponentPool ( ) ; BeanRegistry beanRegistry = new SimpleBeanRegistry ( ) ; @ Override public ComponentPool getComponentPool ( ) { return componentPool ; } @ Override public BeanRegistry getBeanRegistry ( ) { return beanRegistry ; } } private class OurContext extends MockArooaContext { ArooaSession session ; public OurContext ( ArooaSession session ) { this . session = session ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void configure ( ) { } } ; } @ Override public ArooaSession getSession ( ) { return session ; } } public void testHierarchicalRegistry ( ) { OurSession existingSession = new OurSession ( ) ; String xml = "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setArooaSession ( existingSession ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; ComponentPool pool = existingSession . getComponentPool ( ) ; pool . registerComponent ( new ComponentTrinity ( oddjob , oddjob , new OurContext ( existingSession ) ) , "" ) ; oddjob . run ( ) ; Object result = existingSession . getBeanRegistry ( ) . lookup ( "" ) ; assertNotNull ( result ) ; } public static class MyEcho extends SimpleJob { @ Override protected int execute ( ) throws Throwable { return ; } } String xml = "" + "" + "" + "" + "" + "" + "" + MyEcho . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; public void testDescriptorOverride ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; Object echo = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( MyEcho . class , echo . getClass ( ) ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; assertEquals ( ParentState . DESTROYED , oddjob . lastStateEvent ( ) . getState ( ) ) ; } public void testNestedDescriptorOverride ( ) throws ArooaParseException { String moreXml = "" + "" + "" + "" + "" + "" + "" + xml + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , moreXml ) ) ; oddjob . run ( ) ; Object echo = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( MyEcho . class , echo . getClass ( ) ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; assertEquals ( ParentState . DESTROYED , oddjob . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . designer . elements . schedule ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . WeeklySchedule ; import org . oddjob . schedules . units . DayOfWeek ; public class WeeklyScheduleDETest extends TestCase { private static final Logger logger = Logger . getLogger ( WeeklyScheduleDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( DayOfWeekScheduleDesign . class , design . getClass ( ) ) ; WeeklySchedule test = ( WeeklySchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( DayOfWeek . Days . TUESDAY , test . getFrom ( ) ) ; assertEquals ( DayOfWeek . Days . THURSDAY , test . getTo ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { WeeklyScheduleDETest test = new WeeklyScheduleDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements . schedule ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . IntervalSchedule ; public class CountScheduleDETest extends TestCase { private static final Logger logger = Logger . getLogger ( CountScheduleDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( CountScheduleDesign . class , design . getClass ( ) ) ; CountSchedule test = ( CountSchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( IntervalSchedule . class , test . getRefinement ( ) . getClass ( ) ) ; assertEquals ( , test . getCount ( ) ) ; assertEquals ( "" , test . getIdentifier ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { CountScheduleDETest test = new CountScheduleDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements . schedule ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . TimeSchedule ; public class TimeScheduleDETest extends TestCase { private static final Logger logger = Logger . getLogger ( TimeScheduleDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( TimeScheduleDesign . class , design . getClass ( ) ) ; TimeSchedule test = ( TimeSchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( CountSchedule . class , test . getRefinement ( ) . getClass ( ) ) ; assertEquals ( "" , test . getFrom ( ) ) ; assertEquals ( "" , test . getToLast ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { TimeScheduleDETest test = new TimeScheduleDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements . schedule ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . AfterSchedule ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . IntervalSchedule ; public class AfterScheduleDETest extends TestCase { private static final Logger logger = Logger . getLogger ( AfterScheduleDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( AfterScheduleDesign . class , design . getClass ( ) ) ; AfterSchedule test = ( AfterSchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( IntervalSchedule . class , test . getSchedule ( ) . getClass ( ) ) ; assertEquals ( CountSchedule . class , test . getRefinement ( ) . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { AfterScheduleDETest test = new AfterScheduleDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements . schedule ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . MonthlySchedule ; import org . oddjob . schedules . units . DayOfMonth ; import org . oddjob . schedules . units . DayOfWeek ; import org . oddjob . schedules . units . WeekOfMonth ; public class MonthlyScheduleDETest extends TestCase { private static final Logger logger = Logger . getLogger ( MonthlyScheduleDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreateByDay ( ) throws ArooaParseException { String xml = "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( MonthlyScheduleDesign . class , design . getClass ( ) ) ; MonthlySchedule test = ( MonthlySchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( new DayOfMonth . Number ( ) , test . getFromDay ( ) ) ; assertEquals ( DayOfMonth . Shorthands . LAST , test . getToDay ( ) ) ; } public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( MonthlyScheduleDesign . class , design . getClass ( ) ) ; MonthlySchedule test = ( MonthlySchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( DayOfWeek . Days . TUESDAY , test . getFromDayOfWeek ( ) ) ; assertEquals ( DayOfWeek . Days . WEDNESDAY , test . getToDayOfWeek ( ) ) ; assertEquals ( WeekOfMonth . Weeks . SECOND , test . getFromWeek ( ) ) ; assertEquals ( WeekOfMonth . Weeks . SECOND , test . getToWeek ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { MonthlyScheduleDETest test = new MonthlyScheduleDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements . schedule ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . BrokenSchedule ; import org . oddjob . schedules . schedules . DateSchedule ; import org . oddjob . schedules . schedules . IntervalSchedule ; import org . oddjob . schedules . schedules . NowSchedule ; public class BrokenScheduleDETest extends TestCase { private static final Logger logger = Logger . getLogger ( BrokenScheduleDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( BrokenScheduleDesign . class , design . getClass ( ) ) ; BrokenSchedule test = ( BrokenSchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( IntervalSchedule . class , test . getSchedule ( ) . getClass ( ) ) ; assertEquals ( DateSchedule . class , test . getBreaks ( ) . getClass ( ) ) ; assertEquals ( NowSchedule . class , test . getAlternative ( ) . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { BrokenScheduleDETest test = new BrokenScheduleDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements . schedule ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . DailySchedule ; public class DailyScheduleDETest extends TestCase { private static final Logger logger = Logger . getLogger ( DailyScheduleDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( DailyScheduleDesign . class , design . getClass ( ) ) ; DailySchedule test = ( DailySchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( CountSchedule . class , test . getRefinement ( ) . getClass ( ) ) ; assertEquals ( "" , test . getFrom ( ) ) ; assertEquals ( "" , test . getTo ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { DailyScheduleDETest test = new DailyScheduleDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements . schedule ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . YearlySchedule ; import org . oddjob . schedules . units . Month ; public class YearlyScheduleDETest extends TestCase { private static final Logger logger = Logger . getLogger ( YearlyScheduleDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( YearlyScheduleDesign . class , design . getClass ( ) ) ; YearlySchedule test = ( YearlySchedule ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( Month . Months . JANUARY , test . getFromMonth ( ) ) ; assertEquals ( Month . Months . MARCH , test . getToMonth ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { YearlyScheduleDETest test = new YearlyScheduleDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements ; import java . io . File ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . FileType ; public class FileDETest extends TestCase { private static final Logger logger = Logger . getLogger ( FileDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( FileDesign . class , design . getClass ( ) ) ; FileType test = ( FileType ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( new File ( "" ) , test . getFile ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { FileDETest test = new FileDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . elements ; import java . io . File ; import java . io . IOException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . AppendType ; public class FileOutputDETest extends TestCase { private static final Logger logger = Logger . getLogger ( FileOutputDETest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException , IOException { String xml = "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; AppendType test = ( AppendType ) Helper . createTypeFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( new File ( "" ) . getCanonicalFile ( ) , test . getFile ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException , IOException { FileOutputDETest test = new FileOutputDETest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . DesignSeedContext ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . parsing . CutAndPasteSupport ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class RootDCTest extends TestCase { public void testPasteAndCut ( ) throws ArooaParseException { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignSeedContext context = new DesignSeedContext ( ArooaType . COMPONENT , ( new StandardArooaSession ( descriptor ) ) ) ; DesignInstance design = new RootDC ( ) . createDesign ( new ArooaElement ( "" ) , context ) ; String paste = "" + "" + "" + "" + "" ; CutAndPasteSupport cutAndPaste = new CutAndPasteSupport ( design . getArooaContext ( ) ) ; assertTrue ( cutAndPaste . supportsPaste ( ) ) ; cutAndPaste . paste ( , new XMLConfiguration ( "" , paste ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; oddjob . run ( ) ; assertNotNull ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) , new RootDC ( ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( RootDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { RootDCTest test = new RootDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ExistsDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( ExistsDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( ExistsDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { ExistsDCTest test = new ExistsDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . job . RunJob ; import org . oddjob . jobs . job . StopJob ; public class JustJobDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( JustJobDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testRun ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( JustJobDesign . class , design . getClass ( ) ) ; RunJob test = ( RunJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( test , test . getJob ( ) ) ; } public void testStop ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( JustJobDesign . class , design . getClass ( ) ) ; StopJob test = ( StopJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( test , test . getJob ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { JustJobDCTest test = new JustJobDCTest ( ) ; test . testRun ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import java . io . File ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . EchoJob ; public class EchoDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( EchoDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { OurDirs dirs = new OurDirs ( ) ; File testFile = dirs . relative ( "" ) ; String xml = "" + "" + "" + testFile . getPath ( ) + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( EchoDesign . class , design . getClass ( ) ) ; EchoJob test = ( EchoJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( "" , test . getText ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { EchoDCTest test = new EchoDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ForEachDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( ForEachDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( ForEachDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { ForEachDCTest test = new ForEachDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import java . io . File ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . OddjobInheritance ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class OddjobDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddjobDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { OurDirs dirs = new OurDirs ( ) ; File testFile = dirs . relative ( "" ) ; String xml = "" + testFile . getPath ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( OddjobDesign . class , design . getClass ( ) ) ; Oddjob test = ( Oddjob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( testFile , test . getFile ( ) ) ; assertEquals ( OddjobInheritance . SHARED , test . getInheritance ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { OddjobDCTest test = new OddjobDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . structural . SequentialJob ; public class SequentialDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( SequentialDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( SequentialDesign . class , design . getClass ( ) ) ; SequentialJob test = ( SequentialJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( true , test . isIndependent ( ) ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; } public static void main ( String args [ ] ) throws ArooaParseException { SequentialDCTest test = new SequentialDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class DeleteDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( DeleteDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( DeleteDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { DeleteDCTest test = new DeleteDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class IfDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( IfDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( IfDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { IfDCTest test = new IfDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jmx . JMXClientJob ; public class ClientDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( ClientDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( ClientDesign . class , design . getClass ( ) ) ; JMXClientJob test = ( JMXClientJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( "" , test . getConnection ( ) ) ; assertEquals ( , test . getHeartbeat ( ) ) ; assertEquals ( , test . getLogPollingInterval ( ) ) ; assertEquals ( , test . getMaxConsoleLines ( ) ) ; assertEquals ( , test . getMaxLoggerLines ( ) ) ; Map < String , ? > env = test . getEnvironment ( ) ; String [ ] credentials = ( String [ ] ) env . get ( "" ) ; assertEquals ( "" , credentials [ ] ) ; assertEquals ( "" , credentials [ ] ) ; } public static void main ( String args [ ] ) throws ArooaParseException { ClientDCTest test = new ClientDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . structural . JobFolder ; public class FolderDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( FolderDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( FolderDesign . class , design . getClass ( ) ) ; JobFolder test = ( JobFolder ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; } public static void main ( String args [ ] ) throws ArooaParseException { FolderDCTest test = new FolderDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class CopyDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( CopyDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( CopyDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { CopyDCTest test = new CopyDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ResetDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( ResetDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( ResetJobDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { ResetDCTest test = new ResetDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ServerDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( ServerDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( ServerDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { ServerDCTest test = new ServerDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class MkDirDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( MkDirDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( MkdirDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { MkDirDCTest test = new MkDirDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class RenameDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( RenameDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( RenameDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { RenameDCTest test = new RenameDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class WaitDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( WaitDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( WaitDesign . class , design . getClass ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { WaitDCTest test = new WaitDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . sql . SQLJob ; public class SQLJobDesFaTest extends TestCase { DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = ( SqlDesign ) parser . getDesign ( ) ; assertEquals ( SqlDesign . class , design . getClass ( ) ) ; SQLJob test = ( SQLJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( true , test . isCallable ( ) ) ; assertEquals ( true , test . isAutocommit ( ) ) ; assertEquals ( true , test . isEscapeProcessing ( ) ) ; assertEquals ( "" , test . getDelimiter ( ) ) ; assertEquals ( SQLJob . DelimiterType . ROW , test . getDelimiterType ( ) ) ; assertEquals ( SQLJob . OnError . CONTINUE , test . getOnError ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { SQLJobDesFaTest test = new SQLJobDesFaTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . ExecJob ; public class ExecDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( ExecDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( ExecDesign . class , design . getClass ( ) ) ; ExecJob test = ( ExecJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( "" , test . getEnvironment ( "" ) ) ; assertNotNull ( test . getStderr ( ) ) ; assertNotNull ( test . getStdout ( ) ) ; assertNotNull ( test . getStdin ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { ExecDCTest test = new ExecDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jmx . JMXServiceJob ; public class JMXServiceDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( JMXServiceDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( JMXServiceDesign . class , design . getClass ( ) ) ; JMXServiceJob test = ( JMXServiceJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( "" , test . getConnection ( ) ) ; assertEquals ( , test . getHeartbeat ( ) ) ; Map < String , ? > env = test . getEnvironment ( ) ; String [ ] credentials = ( String [ ] ) env . get ( "" ) ; assertEquals ( "" , credentials [ ] ) ; assertEquals ( "" , credentials [ ] ) ; } public static void main ( String args [ ] ) throws ArooaParseException { JMXServiceDCTest test = new JMXServiceDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . structural . RepeatJob ; public class RepeatDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( RepeatDCTest . class ) ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( RepeatDesign . class , design . getClass ( ) ) ; RepeatJob test = ( RepeatJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getName ( ) ) ; assertEquals ( true , test . isUntil ( ) ) ; assertEquals ( , test . getTimes ( ) ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; } public static void main ( String args [ ] ) throws ArooaParseException { RepeatDCTest test = new RepeatDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . components ; import org . apache . log4j . Logger ; import org . custommonkey . xmlunit . XMLTestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . parsing . CutAndPasteSupport ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; public class VariablesDCTest extends XMLTestCase { private static final Logger logger = Logger . getLogger ( VariablesDCTest . class ) ; DesignInstance design ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } public void testCreate ( ) throws Exception { String xml = "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; String paste = "" + "" + "" ; CutAndPasteSupport . paste ( design . getArooaContext ( ) , , new XMLConfiguration ( "" , paste ) ) ; XMLArooaParser xmlParser = new XMLArooaParser ( ) ; xmlParser . parse ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; String EOL = System . getProperty ( "" ) ; String expected = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; assertXMLEqual ( expected , xmlParser . getXml ( ) ) ; } public void testParseRubbish ( ) throws Exception { String xml = "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; XMLArooaParser xmlParser = new XMLArooaParser ( ) ; xmlParser . parse ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; String EOL = System . getProperty ( "" ) ; String expected = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; assertXMLEqual ( expected , xmlParser . getXml ( ) ) ; } public void testParseNoValue ( ) throws Exception { String xml = "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( VariablesDesign . class , design . getClass ( ) ) ; XMLArooaParser xmlParser = new XMLArooaParser ( ) ; xmlParser . parse ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; String EOL = System . getProperty ( "" ) ; String expected = "" + EOL ; assertXMLEqual ( expected , xmlParser . getXml ( ) ) ; } public static void main ( String args [ ] ) throws Exception { VariablesDCTest test = new VariablesDCTest ( ) ; test . testParseNoValue ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . designer . view ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FormItem ; public class FieldGroupDummy implements DummyItemView { private final BorderedGroup fieldGroup ; public FieldGroupDummy ( BorderedGroup fieldGroup ) { this . fieldGroup = fieldGroup ; } public void inline ( DummyDialogue form ) { for ( int i = ; i < fieldGroup . size ( ) ; ++ i ) { FormItem formField = fieldGroup . get ( i ) ; DummyItemView itemView = DummyItemViewFactory . create ( formField ) ; itemView . inline ( form ) ; } } } package org . oddjob . designer . view ; import org . oddjob . arooa . design . screem . TextPseudoForm ; public class TextPseudoFormDummy implements DummyFormView { private TextPseudoForm textForm ; public TextPseudoFormDummy ( TextPseudoForm textForm ) { this . textForm = textForm ; } public DummyDialogue dialogue ( ) { return new DummyDialogue ( ) { public void addField ( DummyWidget widget ) { throw new UnsupportedOperationException ( ) ; } public DummyWidget get ( String title ) { return new TextWidget ( ) { public String getName ( ) { throw new UnsupportedOperationException ( ) ; } public String getText ( ) { return textForm . getAttribute ( ) . attribute ( ) ; } public void setText ( String text ) { textForm . getAttribute ( ) . attribute ( text ) ; } } ; } } ; } } package org . oddjob . designer . view ; public interface DummyFormView { public DummyDialogue dialogue ( ) ; } package org . oddjob . designer . view ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . parsing . QTag ; public interface SelectionWidget extends DummyWidget { public DesignInstance getSelected ( ) ; public DesignInstance setSelected ( QTag tag ) ; } package org . oddjob . designer . view ; public interface TextWidget extends DummyWidget { public String getText ( ) ; public void setText ( String text ) ; } package org . oddjob . designer . view ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignListener ; import org . oddjob . arooa . design . DesignStructureEvent ; import org . oddjob . arooa . design . InstanceSupport ; import org . oddjob . arooa . design . screem . SingleTypeSelection ; import org . oddjob . arooa . design . view . DesignViewException ; import org . oddjob . arooa . parsing . QTag ; public class TypeSelectionDummy implements DummyItemView { SingleTypeSelection typeSelection ; DesignInstance instance ; public TypeSelectionDummy ( SingleTypeSelection typeSelection ) { this . typeSelection = typeSelection ; typeSelection . getDesignElementProperty ( ) . addDesignListener ( new DesignListener ( ) { public void childAdded ( DesignStructureEvent event ) { if ( event . getIndex ( ) != ) { throw new RuntimeException ( "" ) ; } instance = event . getChild ( ) ; } public void childRemoved ( DesignStructureEvent event ) { if ( event . getIndex ( ) != ) { throw new RuntimeException ( "" ) ; } instance = null ; } } ) ; } public void inline ( DummyDialogue form ) { form . addField ( new SelectionWidget ( ) { public String getName ( ) { return typeSelection . getTitle ( ) ; } public DesignInstance getSelected ( ) { return instance ; } public DesignInstance setSelected ( QTag tag ) { InstanceSupport support = new InstanceSupport ( typeSelection . getDesignElementProperty ( ) ) ; if ( instance != null ) { support . removeInstance ( instance ) ; } try { support . insertTag ( , tag ) ; } catch ( ArooaParseException e ) { throw new DesignViewException ( e ) ; } return instance ; } } ) ; } } package org . oddjob . designer . view ; public interface DummyDialogue { public void addField ( DummyWidget widget ) ; public DummyWidget get ( String title ) ; } package org . oddjob . designer . view ; public interface DummyItemView { public void inline ( DummyDialogue form ) ; } package org . oddjob . designer . view ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . design . DesignElementProperty ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignListener ; import org . oddjob . arooa . design . DesignStructureEvent ; import org . oddjob . arooa . design . InstanceSupport ; import org . oddjob . arooa . design . screem . MultiTypeTable ; import org . oddjob . arooa . design . view . DesignViewException ; import org . oddjob . arooa . parsing . QTag ; public class MultiTypeTableDummy implements DummyItemView { private MultiTypeTable multiTypeTable ; private List < DesignInstance > instances = new ArrayList < DesignInstance > ( ) ; public MultiTypeTableDummy ( MultiTypeTable multiTypeTable ) { this . multiTypeTable = multiTypeTable ; DesignElementProperty de = multiTypeTable . getDesignProperty ( ) ; de . addDesignListener ( new DesignListener ( ) { public void childAdded ( DesignStructureEvent event ) { instances . add ( event . getIndex ( ) , event . getChild ( ) ) ; } public void childRemoved ( DesignStructureEvent event ) { instances . remove ( event . getIndex ( ) ) ; } } ) ; } public void inline ( DummyDialogue form ) { form . addField ( new TableWidget ( ) { public DesignInstance getInstanceAt ( int index ) { return instances . get ( index ) ; } public String getName ( ) { return multiTypeTable . getTitle ( ) ; } public void setInstanceAt ( int index , QTag tag ) { try { create ( index , tag ) ; } catch ( ArooaParseException e ) { throw new DesignViewException ( e ) ; } } } ) ; } private void create ( int index , QTag type ) throws ArooaParseException { if ( multiTypeTable . isKeyed ( ) ) { throw new RuntimeException ( "" ) ; } DesignElementProperty designProperty = multiTypeTable . getDesignProperty ( ) ; InstanceSupport support = new InstanceSupport ( designProperty ) ; if ( index < instances . size ( ) ) { support . removeInstance ( instances . get ( index ) ) ; } support . insertTag ( index , type ) ; } private void create ( int index , String name , QTag type ) throws ArooaParseException { if ( multiTypeTable . isKeyed ( ) ) { throw new RuntimeException ( "" ) ; } DesignElementProperty designProperty = multiTypeTable . getDesignProperty ( ) ; InstanceSupport support = new InstanceSupport ( designProperty ) ; if ( index < instances . size ( ) ) { support . removeInstance ( instances . get ( index ) ) ; } support . insertTag ( index , type ) ; } } package org . oddjob . designer . view ; import org . oddjob . arooa . design . screem . Form ; import org . oddjob . arooa . design . screem . StandardForm ; import org . oddjob . arooa . design . screem . TextPseudoForm ; public class DummyFormViewFactory { public static DummyFormView create ( Form form ) { if ( form instanceof StandardForm ) { return new DummyStandardFormView ( ( StandardForm ) form ) ; } else if ( form instanceof TextPseudoForm ) { return new TextPseudoFormDummy ( ( TextPseudoForm ) form ) ; } throw new RuntimeException ( "" + form ) ; } } package org . oddjob . designer . view ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . FormItem ; public class FieldSelectionDummy implements DummyItemView { private final FieldSelection fieldSelection ; public FieldSelectionDummy ( FieldSelection fieldSelection ) { this . fieldSelection = fieldSelection ; } public void inline ( DummyDialogue form ) { for ( int i = ; i < fieldSelection . size ( ) ; ++ i ) { FormItem formField = fieldSelection . get ( i ) ; DummyItemView itemView = DummyItemViewFactory . create ( formField ) ; itemView . inline ( form ) ; } } } package org . oddjob . designer . view ; public interface DummyWidget { public String getName ( ) ; } package org . oddjob . designer . view ; import org . oddjob . arooa . design . screem . TextInput ; public class TextInputDummy implements DummyItemView { private TextInput textInput ; public TextInputDummy ( TextInput textInput ) { this . textInput = textInput ; } public void inline ( DummyDialogue form ) { form . addField ( new TextWidget ( ) { public String getName ( ) { return textInput . getTitle ( ) ; } public String getText ( ) { return textInput . getText ( ) ; } public void setText ( String text ) { textInput . setText ( text ) ; } } ) ; } } package org . oddjob . designer . view ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . Map ; import org . oddjob . arooa . design . screem . StandardForm ; public class DummyStandardFormView implements DummyFormView { private final Map < String , DummyWidget > widgets = new LinkedHashMap < String , DummyWidget > ( ) ; private DummyStandardDialog dialogue = new DummyStandardDialog ( ) ; public DummyStandardFormView ( StandardForm form ) { for ( int i = ; i < form . size ( ) ; ++ i ) { DummyItemView itemView = DummyItemViewFactory . create ( form . getFormItem ( i ) ) ; itemView . inline ( dialogue ) ; } } private String options ( ) { String options = "" ; for ( Iterator < String > it = widgets . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { options = options + "" + it . next ( ) + "" ; } return options ; } public DummyDialogue dialogue ( ) { return dialogue ; } class DummyStandardDialog implements DummyDialogue { public void addField ( DummyWidget widget ) { widgets . put ( widget . getName ( ) , widget ) ; } public DummyWidget get ( String title ) { DummyWidget child = widgets . get ( title ) ; if ( child == null ) { throw new IllegalArgumentException ( "" + title + "" + options ( ) ) ; } return child ; } } } package org . oddjob . designer . view ; import org . oddjob . arooa . design . screem . BorderedGroup ; import org . oddjob . arooa . design . screem . FieldSelection ; import org . oddjob . arooa . design . screem . FormItem ; import org . oddjob . arooa . design . screem . MultiTypeTable ; import org . oddjob . arooa . design . screem . SingleTypeSelection ; import org . oddjob . arooa . design . screem . TextField ; public class DummyItemViewFactory { public static DummyItemView create ( FormItem item ) { if ( item instanceof BorderedGroup ) { return new FieldGroupDummy ( ( BorderedGroup ) item ) ; } else if ( item instanceof SingleTypeSelection ) { return new TypeSelectionDummy ( ( SingleTypeSelection ) item ) ; } else if ( item instanceof MultiTypeTable ) { return new MultiTypeTableDummy ( ( MultiTypeTable ) item ) ; } else if ( item instanceof TextField ) { return new TextFieldDummy ( ( TextField ) item ) ; } else if ( item instanceof FieldSelection ) { return new FieldSelectionDummy ( ( FieldSelection ) item ) ; } throw new RuntimeException ( "" + item ) ; } } package org . oddjob . designer . view ; import org . oddjob . arooa . design . screem . TextField ; public class TextFieldDummy implements DummyItemView { private TextField textField ; public TextFieldDummy ( TextField textField ) { this . textField = textField ; } public void inline ( DummyDialogue form ) { form . addField ( new TextWidget ( ) { public String getName ( ) { return textField . getTitle ( ) ; } public String getText ( ) { return textField . getAttribute ( ) . attribute ( ) ; } public void setText ( String text ) { textField . getAttribute ( ) . attribute ( text ) ; } } ) ; } } package org . oddjob . designer . view ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . parsing . QTag ; public interface TableWidget extends DummyWidget { public DesignInstance getInstanceAt ( int index ) ; public void setInstanceAt ( int index , QTag tag ) ; } package org . oddjob ; import java . util . Arrays ; import org . apache . log4j . Logger ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . state . State ; public class StateSteps { private static final Logger logger = Logger . getLogger ( StateSteps . class ) ; private Stateful stateful ; private Listener listener ; private long timeout = ; public StateSteps ( Stateful stateful ) { if ( stateful == null ) { throw new NullPointerException ( "" ) ; } this . stateful = stateful ; } class Listener implements StateListener { private final State [ ] steps ; private int index ; private boolean done ; private String failureMessage ; public Listener ( State [ ] steps ) { this . steps = steps ; } @ Override public synchronized void jobStateChange ( StateEvent event ) { String position ; if ( failureMessage != null ) { position = "" ; } else { position = "" + index + "" ; } logger . info ( "" + event . getState ( ) + "" + position + "" + event . getSource ( ) + "" ) ; if ( index >= steps . length ) { failureMessage = "" + event . getState ( ) + "" + index + "" ; } else { if ( event . getState ( ) == steps [ index ] ) { if ( ++ index == steps . length ) { done = true ; notifyAll ( ) ; } } else { done = true ; failureMessage = "" + steps [ index ] + "" + event . getState ( ) + "" + index + "" ; notifyAll ( ) ; } } } public synchronized boolean isDone ( ) { return done ; } } ; public void startCheck ( final State ... steps ) { if ( listener != null ) { throw new IllegalStateException ( "" ) ; } if ( steps == null || steps . length == ) { throw new IllegalStateException ( "" ) ; } this . listener = new Listener ( steps ) ; stateful . addStateListener ( listener ) ; } public void checkNow ( ) { try { if ( listener . isDone ( ) ) { if ( listener . failureMessage != null ) { throw new IllegalStateException ( listener . failureMessage ) ; } } else { throw new IllegalStateException ( "" + stateful + "" + listener . steps . length + "" + Arrays . toString ( listener . steps ) + "" + listener . index + "" ) ; } } catch ( IllegalStateException e ) { logger . error ( e ) ; throw e ; } finally { stateful . removeStateListener ( listener ) ; listener = null ; } } public void checkWait ( ) throws InterruptedException { if ( listener == null ) { throw new IllegalStateException ( "" ) ; } logger . info ( "" + "" + stateful + "" + Arrays . toString ( listener . steps ) ) ; synchronized ( listener ) { if ( ! listener . isDone ( ) ) { listener . wait ( timeout ) ; logger . info ( "" + "" + stateful + "" + Arrays . toString ( listener . steps ) ) ; } } checkNow ( ) ; logger . info ( "" + stateful + "" ) ; } public long getTimeout ( ) { return timeout ; } public void setTimeout ( long timeout ) { this . timeout = timeout ; } } package org . oddjob ; import java . io . IOException ; import junit . framework . TestCase ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class OddjobSerializeTest extends TestCase { public void testSerializeAndReRun ( ) throws IOException , ClassNotFoundException { String xml = "" + "" + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , new OddjobLookup ( test ) . lookup ( "" ) ) ; Oddjob copy = Helper . copy ( test ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( null , new OddjobLookup ( copy ) . lookup ( "" ) ) ; copy . load ( ) ; OddjobLookup copyLookup = new OddjobLookup ( copy ) ; assertEquals ( "" , copyLookup . lookup ( "" ) ) ; Object echo = copyLookup . lookup ( "" ) ; assertEquals ( JobState . READY , Helper . getJobState ( echo ) ) ; } public void testSerializeWhenReset ( ) throws IOException , ClassNotFoundException { String xml = "" + "" + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; Oddjob copy = Helper . copy ( test ) ; copy . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; assertEquals ( ParentState . READY , copy . lastStateEvent ( ) . getState ( ) ) ; copy . run ( ) ; OddjobLookup copyLookup = new OddjobLookup ( copy ) ; assertEquals ( "" , copyLookup . lookup ( "" ) ) ; Object echo = copyLookup . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( echo ) ) ; } public void testSerializeNoConfig ( ) throws IOException , ClassNotFoundException { Oddjob test = new Oddjob ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; Oddjob copy = Helper . copy ( test ) ; assertEquals ( ParentState . READY , copy . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . IOException ; import org . apache . log4j . Logger ; public class OddjobSrc { private static final Logger logger = Logger . getLogger ( OddjobSrc . class ) ; private final File oddjobSrc ; public OddjobSrc ( ) throws IOException { String baseDir = System . getProperty ( "" ) ; if ( baseDir != null ) { oddjobSrc = new File ( baseDir ) . getCanonicalFile ( ) ; logger . info ( "" + oddjobSrc . toString ( ) ) ; } else { File pwd = new File ( "" ) . getCanonicalFile ( ) ; if ( "" . equals ( pwd . getName ( ) ) ) { logger . info ( "" ) ; oddjobSrc = new File ( "" ) ; } else { logger . info ( "" ) ; oddjobSrc = new OurDirs ( ) . relative ( "" ) . getCanonicalFile ( ) ; } } if ( ! oddjobSrc . exists ( ) ) { throw new FileNotFoundException ( oddjobSrc + "" ) ; } } public File oddjobSrcBase ( ) { return oddjobSrc ; } } package org . oddjob . beanbus ; import java . io . ByteArrayOutputStream ; import java . util . Arrays ; import junit . framework . TestCase ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . BeanView ; import org . oddjob . arooa . reflect . BeanViews ; import org . oddjob . arooa . standard . StandardArooaSession ; public class BeanSheetTest extends TestCase { public static class Fruit { private String type ; private String variety ; private String colour ; private double size ; public String getType ( ) { return type ; } public void setType ( String type ) { this . type = type ; } public String getVariety ( ) { return variety ; } public void setVariety ( String variety ) { this . variety = variety ; } public String getColour ( ) { return colour ; } public void setColour ( String colour ) { this . colour = colour ; } public double getSize ( ) { return size ; } public void setSize ( double size ) { this . size = size ; } } private class OurViews implements BeanViews { @ Override public BeanView beanViewFor ( ArooaClass arooaClass ) { return new BeanView ( ) { @ Override public String titleFor ( String property ) { if ( "" . equals ( property ) ) { return "" ; } return property ; } @ Override public String [ ] getProperties ( ) { return new String [ ] { "" , "" , "" , "" } ; } } ; } } String EOL = System . getProperty ( "" ) ; private Object [ ] createFruit ( ) { Fruit fruit1 = new Fruit ( ) ; fruit1 . setType ( "" ) ; fruit1 . setVariety ( "" ) ; fruit1 . setColour ( "" ) ; fruit1 . setSize ( ) ; Fruit fruit2 = new Fruit ( ) ; fruit2 . setType ( "" ) ; fruit2 . setVariety ( "" ) ; fruit2 . setColour ( "" ) ; fruit2 . setSize ( ) ; return new Object [ ] { fruit1 , fruit2 } ; } public void testFruitReport ( ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Object [ ] values = createFruit ( ) ; BeanSheet test = new BeanSheet ( ) ; test . setOutput ( out ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setBeanViews ( new OurViews ( ) ) ; test . accept ( Arrays . asList ( values ) ) ; test . accept ( Arrays . asList ( values ) ) ; String expected = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; assertEquals ( expected , out . toString ( ) ) ; } public void testNoHeaders ( ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Object [ ] values = createFruit ( ) ; BeanSheet test = new BeanSheet ( ) ; test . setOutput ( out ) ; test . setNoHeaders ( true ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setBeanViews ( new OurViews ( ) ) ; test . accept ( Arrays . asList ( values ) ) ; String expected = "" + EOL + "" + EOL ; assertEquals ( expected , out . toString ( ) ) ; } } package org . oddjob . beanbus ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; public class SimpleBusDriverTest extends TestCase { private interface Food { } private interface Fruit extends Food { } private class Apple implements Fruit { } private class Results implements Destination < Food > { List < Food > list = new ArrayList < Food > ( ) ; public void accept ( Food bean ) { list . add ( bean ) ; } ; } public void testSimpleRun ( ) { List < Apple > fruit = new ArrayList < Apple > ( ) ; fruit . add ( new Apple ( ) ) ; fruit . add ( new Apple ( ) ) ; SimpleBus < Fruit > test = new SimpleBus < Fruit > ( ) ; IterableDriver < Apple > driver = new IterableDriver < Apple > ( ) ; driver . setIterable ( fruit ) ; test . setDriver ( driver ) ; Results results = new Results ( ) ; driver . setTo ( results ) ; test . run ( ) ; assertEquals ( , results . list . size ( ) ) ; } } package org . oddjob . examples ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; public class PricingJob implements Runnable { private Object priceService ; public Object getPriceService ( ) { return priceService ; } @ ArooaAttribute public void setPriceService ( Object priceService ) { this . priceService = priceService ; } @ Override public void run ( ) { if ( priceService == null ) { throw new NullPointerException ( "" ) ; } } } package org . oddjob . examples ; import org . oddjob . FailedToStopException ; import org . oddjob . framework . Service ; public class CachingPriceService implements Service { @ Override public void start ( ) throws Exception { } @ Override public void stop ( ) throws FailedToStopException { } } package org . oddjob . examples ; import org . oddjob . FailedToStopException ; import org . oddjob . framework . Service ; public class NonCachingPriceService implements Service { @ Override public void start ( ) throws Exception { } @ Override public void stop ( ) throws FailedToStopException { } } package org . oddjob . jobs ; import java . io . IOException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Oddjob ; import org . oddjob . OurDirs ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . launch . Launcher ; import org . oddjob . state . ParentState ; public class LaunchJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( LaunchJobTest . class ) ; public void testLaunchAsjobInOddjob ( ) throws IOException { ClassLoader existingContext = Thread . currentThread ( ) . getContextClassLoader ( ) ; Thread . currentThread ( ) . setContextClassLoader ( null ) ; OurDirs dirs = new OurDirs ( ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) , Launcher . ODDJOB_MAIN_CLASS } ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertTrue ( lines [ ] . startsWith ( "" ) ) ; oddjob . destroy ( ) ; Thread . currentThread ( ) . setContextClassLoader ( existingContext ) ; } } package org . oddjob . jobs . structural ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobComponentResolver ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . MirrorState ; import org . oddjob . state . ParentState ; public class SequentialJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( SequentialJobTest . class ) ; public static class OurJob extends SimpleJob { @ Override protected int execute ( ) throws Throwable { return ; } } public void testEmpty ( ) { SequentialJob test = new SequentialJob ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testObject ( ) { SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , ( new Object ( ) ) ) ; test . setJobs ( , ( new Object ( ) ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testTriggers ( ) { OurJob j1 = new OurJob ( ) ; MirrorState t1 = new MirrorState ( ) ; t1 . setJob ( ( Stateful ) j1 ) ; t1 . run ( ) ; OurJob j2 = new OurJob ( ) ; MirrorState t2 = new MirrorState ( ) ; t2 . setJob ( ( Stateful ) j2 ) ; t2 . run ( ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , t1 ) ; test . setJobs ( , t2 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; ( ( Runnable ) j1 ) . run ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; ( ( Runnable ) j2 ) . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; ( ( Resetable ) j2 ) . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testRunnable ( ) { OurJob j1 = new OurJob ( ) ; OurJob j2 = new OurJob ( ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , j1 ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; ( ( Resetable ) j2 ) . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testMixture ( ) { OurJob j1 = new OurJob ( ) ; Object j2 = new OurJob ( ) ; MirrorState t2 = new MirrorState ( ) ; t2 . setJob ( ( Stateful ) j2 ) ; t2 . run ( ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , j1 ) ; test . setJobs ( , t2 ) ; test . setJobs ( , new Object ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; ( ( Runnable ) j2 ) . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNotComplete ( ) { FlagState j1 = new FlagState ( ) ; j1 . setState ( JobState . COMPLETE ) ; FlagState j2 = new FlagState ( ) ; j2 . setState ( JobState . INCOMPLETE ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , j1 ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testDependentProgression ( ) { FlagState j1 = new FlagState ( ) ; j1 . setState ( JobState . INCOMPLETE ) ; FlagState j2 = new FlagState ( ) ; j2 . setState ( JobState . COMPLETE ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , j1 ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , j1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , j2 . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testIndependentProgression ( ) { FlagState j1 = new FlagState ( ) ; j1 . setState ( JobState . INCOMPLETE ) ; FlagState j2 = new FlagState ( ) ; j2 . setState ( JobState . COMPLETE ) ; SequentialJob test = new SequentialJob ( ) ; test . setIndependent ( true ) ; test . setJobs ( , j1 ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , j1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , j2 . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testException ( ) { FlagState j1 = new FlagState ( ) ; j1 . setState ( JobState . COMPLETE ) ; FlagState j2 = new FlagState ( ) ; j2 . setState ( JobState . EXCEPTION ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , j1 ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testDestroyed ( ) { FlagState j1 = new FlagState ( ) ; j1 . setState ( JobState . COMPLETE ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , j1 ) ; StateSteps sequentialState = new StateSteps ( test ) ; sequentialState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; test . run ( ) ; sequentialState . checkNow ( ) ; sequentialState . startCheck ( ParentState . COMPLETE , ParentState . DESTROYED ) ; test . destroy ( ) ; sequentialState . checkNow ( ) ; } public void testStatesWhenOddjobDestroyed ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; Stateful sequential = new OddjobLookup ( oddjob ) . lookup ( "" , Stateful . class ) ; StateSteps state = new StateSteps ( sequential ) ; state . startCheck ( ParentState . COMPLETE , ParentState . DESTROYED ) ; oddjob . destroy ( ) ; state . checkNow ( ) ; } public static class MyService { public void start ( ) { } public void stop ( ) { } } public void testService ( ) throws FailedToStopException { Object service = new OddjobComponentResolver ( ) . resolve ( new MyService ( ) , new StandardArooaSession ( ) ) ; FlagState job = new FlagState ( ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , service ) ; test . setJobs ( , job ) ; StateSteps states = new StateSteps ( test ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; states . checkNow ( ) ; assertEquals ( JobState . COMPLETE , job . lastStateEvent ( ) . getState ( ) ) ; states . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; test . stop ( ) ; states . checkNow ( ) ; } public void testNestedSequentials ( ) throws FailedToStopException { Object service = new OddjobComponentResolver ( ) . resolve ( new MyService ( ) , new StandardArooaSession ( ) ) ; FlagState job1 = new FlagState ( ) ; SequentialJob sequential1 = new SequentialJob ( ) ; sequential1 . setJobs ( , service ) ; sequential1 . setJobs ( , job1 ) ; SequentialJob sequential2 = new SequentialJob ( ) ; FlagState job2 = new FlagState ( ) ; sequential2 . setJobs ( , job2 ) ; SequentialJob test = new SequentialJob ( ) ; test . setJobs ( , sequential1 ) ; test . setJobs ( , sequential2 ) ; StateSteps states = new StateSteps ( sequential1 ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; states . checkNow ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; states . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; test . stop ( ) ; states . checkNow ( ) ; } public void testExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; StateSteps steps = new StateSteps ( oddjob ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oddjob . run ( ) ; steps . checkNow ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . structural ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Iterator ; import java . util . List ; import java . util . concurrent . Exchanger ; import java . util . concurrent . Future ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Loadable ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . Configured ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . scheduling . MockExecutorService ; import org . oddjob . scheduling . MockScheduledFuture ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class ForEachParallelTest extends TestCase { private static final Logger logger = Logger . getLogger ( ForEachParallelTest . class ) ; public void testSimpleParallel ( ) throws InterruptedException { DefaultExecutors defaultServices = new DefaultExecutors ( ) ; String xml = "" + "" + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; test . setExecutorService ( defaultServices . getPoolExecutor ( ) ) ; ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; test . setArooaSession ( session ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( , , , , , , , , , ) ) ; test . setParallel ( true ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; state . checkWait ( ) ; test . destroy ( ) ; defaultServices . stop ( ) ; } public void testStop ( ) throws InterruptedException , FailedToStopException { DefaultExecutors defaultServices = new DefaultExecutors ( ) ; String xml = "" + "" + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; test . setExecutorService ( defaultServices . getPoolExecutor ( ) ) ; ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; test . setArooaSession ( session ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( , , , , , , , , , ) ) ; test . setParallel ( true ) ; test . load ( ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; StateSteps [ ] childChecks = new StateSteps [ ] ; for ( int i = ; i < ; ++ i ) { childChecks [ i ] = new StateSteps ( ( Stateful ) children [ i ] ) ; childChecks [ i ] . startCheck ( JobState . READY , JobState . EXECUTING ) ; } test . run ( ) ; state . checkNow ( ) ; for ( int i = ; i < ; ++ i ) { childChecks [ i ] . checkWait ( ) ; } state . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; test . stop ( ) ; state . checkNow ( ) ; test . destroy ( ) ; defaultServices . stop ( ) ; } private static class MyExecutor extends MockExecutorService { List < Runnable > jobs = new ArrayList < Runnable > ( ) ; int cancels ; @ Override public Future < ? > submit ( Runnable task ) { jobs . add ( task ) ; return new MockScheduledFuture < Void > ( ) { @ Override public boolean cancel ( boolean mayInterruptIfRunning ) { ++ cancels ; return false ; } } ; } } public void testStopWithSlowStartingChild ( ) throws InterruptedException , FailedToStopException { MyExecutor executor = new MyExecutor ( ) ; String xml = "" + "" + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; test . setExecutorService ( executor ) ; ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; test . setArooaSession ( session ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( , , , , , , , , , ) ) ; test . setParallel ( true ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; state . checkNow ( ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; assertEquals ( , executor . jobs . size ( ) ) ; for ( int i = ; i < ; ++ i ) { executor . jobs . get ( i ) . run ( ) ; } state . startCheck ( ParentState . ACTIVE , ParentState . READY ) ; test . stop ( ) ; state . checkNow ( ) ; assertEquals ( , executor . cancels ) ; test . destroy ( ) ; } public void testExampleInOddjob ( ) throws InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; Object foreach = Helper . getChildren ( oddjob ) [ ] ; ( ( Loadable ) foreach ) . load ( ) ; Object [ ] children = Helper . getChildren ( foreach ) ; StateSteps wait1 = new StateSteps ( ( Stateful ) children [ ] ) ; StateSteps wait2 = new StateSteps ( ( Stateful ) children [ ] ) ; StateSteps wait3 = new StateSteps ( ( Stateful ) children [ ] ) ; wait1 . startCheck ( JobState . READY , JobState . EXECUTING ) ; wait2 . startCheck ( JobState . READY , JobState . EXECUTING ) ; wait3 . startCheck ( JobState . READY , JobState . EXECUTING ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; wait1 . checkWait ( ) ; wait2 . checkWait ( ) ; wait3 . checkWait ( ) ; oddjob . stop ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } static final int BIG_LIST_SIZE = ; public static class BigList implements Iterable < Integer > { private int listSize = BIG_LIST_SIZE ; List < Integer > theList = new ArrayList < Integer > ( ) ; @ Configured public void afterConfigure ( ) { for ( int i = ; i < listSize ; ++ i ) { theList . add ( new Integer ( i ) ) ; } } @ Override public Iterator < Integer > iterator ( ) { return theList . iterator ( ) ; } public int getListSize ( ) { return listSize ; } public void setListSize ( int listSize ) { this . listSize = listSize ; } } private class ChildTracker implements StructuralListener { List < Object > children = new ArrayList < Object > ( ) ; Exchanger < Stateful > lastChild ; @ Override public void childAdded ( StructuralEvent event ) { children . add ( event . getIndex ( ) , event . getChild ( ) ) ; if ( lastChild != null ) { try { logger . info ( "" + event . getChild ( ) . toString ( ) ) ; lastChild . exchange ( ( Stateful ) event . getChild ( ) ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } } @ Override public void childRemoved ( StructuralEvent event ) { children . remove ( event . getIndex ( ) ) ; } } public void testParallelWithWindow ( ) throws FailedToStopException , ArooaPropertyException , ArooaConversionException , InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; StateSteps oddjobState = new StateSteps ( oddjob ) ; oddjobState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Structural foreach = lookup . lookup ( "" , Structural . class ) ; int preLoad = lookup . lookup ( "" , int . class ) ; ChildTracker tracker = new ChildTracker ( ) ; foreach . addStructuralListener ( tracker ) ; List < ? > children = tracker . children ; assertEquals ( preLoad , children . size ( ) ) ; while ( ( ( Stateful ) children . get ( children . size ( ) - preLoad ) ) . lastStateEvent ( ) . getState ( ) != JobState . EXECUTING ) { Thread . sleep ( ) ; } tracker . lastChild = new Exchanger < Stateful > ( ) ; for ( int index = ; index < BIG_LIST_SIZE - ; ++ index ) { if ( index < ) { for ( int i = ; i < index ; ++ i ) { assertEquals ( "" + i , children . get ( i ) . toString ( ) ) ; } } else if ( index < ) { for ( int i = index - ; i < index ; ++ i ) { assertEquals ( "" + i , children . get ( i - ( index - ) ) . toString ( ) ) ; } } ( ( Stoppable ) children . get ( children . size ( ) - ) ) . stop ( ) ; logger . info ( "" + index ) ; Stateful lastChild = tracker . lastChild . exchange ( null ) ; while ( lastChild . lastStateEvent ( ) . getState ( ) != JobState . EXECUTING ) { Thread . sleep ( ) ; } } ( ( Stoppable ) children . get ( children . size ( ) - ) ) . stop ( ) ; ( ( Stoppable ) children . get ( children . size ( ) - ) ) . stop ( ) ; oddjobState . checkWait ( ) ; oddjob . destroy ( ) ; } public void testParallelWithWindowStop ( ) throws FailedToStopException , ArooaPropertyException , ArooaConversionException , InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; Stateful foreach = new OddjobLookup ( oddjob ) . lookup ( "" , Stateful . class ) ; ( ( Loadable ) foreach ) . load ( ) ; Object [ ] children = Helper . getChildren ( foreach ) ; assertEquals ( , children . length ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; StateSteps wait1States = new StateSteps ( ( Stateful ) children [ ] ) ; StateSteps wait2States = new StateSteps ( ( Stateful ) children [ ] ) ; wait1States . startCheck ( JobState . READY , JobState . EXECUTING ) ; wait2States . startCheck ( JobState . READY , JobState . EXECUTING ) ; oddjob . run ( ) ; wait1States . checkWait ( ) ; wait2States . checkWait ( ) ; ( ( Stoppable ) foreach ) . stop ( ) ; assertEquals ( ParentState . COMPLETE , ( ( Stateful ) foreach ) . lastStateEvent ( ) . getState ( ) ) ; children = Helper . getChildren ( foreach ) ; assertEquals ( , children . length ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . structural ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ConfigurationHandle ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . parsing . ArooaContext ; import org . oddjob . arooa . parsing . CutAndPasteSupport ; import org . oddjob . arooa . parsing . CutAndPasteSupport . ReplaceResult ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . xml . XMLArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class SequentialJobTest2 extends TestCase { public static class ResultsJob implements Runnable { public String value ; public List < String > results ; public void run ( ) { results . add ( value ) ; } @ ArooaAttribute public void setResults ( List < String > results ) { this . results = results ; } public void setValue ( String value ) { this . value = value ; } @ Override public String toString ( ) { return "" + value ; } } class ChildCatcher implements StructuralListener { final List < Object > children = new ArrayList < Object > ( ) ; public void childAdded ( StructuralEvent event ) { children . add ( event . getIndex ( ) , event . getChild ( ) ) ; } public void childRemoved ( StructuralEvent event ) { children . remove ( event . getIndex ( ) ) ; } } String xml = "" + "" + "" + "" + "" ; String red = "" + ResultsJob . class . getName ( ) + "" + "" ; String amber = "" + ResultsJob . class . getName ( ) + "" + "" + "" ; String green = "" + ResultsJob . class . getName ( ) + "" + "" ; public void testCutAndPaste ( ) throws ArooaParseException { List < String > results = new ArrayList < String > ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setExport ( "" , new ArooaObject ( results ) ) ; oddjob . run ( ) ; SequentialJob test = ( SequentialJob ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; ChildCatcher childCatcher = new ChildCatcher ( ) ; test . addStructuralListener ( childCatcher ) ; assertEquals ( , childCatcher . children . size ( ) ) ; DragPoint point = oddjob . provideConfigurationSession ( ) . dragPointFor ( test ) ; DragTransaction trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( - , green ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , red ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , amber ) ; trn . commit ( ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; results . clear ( ) ; DragPoint amberPoint = oddjob . provideConfigurationSession ( ) . dragPointFor ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; DragTransaction transaction = amberPoint . beginChange ( ChangeHow . FRESH ) ; point . paste ( , amberPoint . copy ( ) ) ; amberPoint . cut ( ) ; transaction . commit ( ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; results . clear ( ) ; amberPoint = oddjob . provideConfigurationSession ( ) . dragPointFor ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; trn = amberPoint . beginChange ( ChangeHow . FRESH ) ; amberPoint . cut ( ) ; trn . commit ( ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( , childCatcher . children . size ( ) ) ; oddjob . destroy ( ) ; } public void testBadSave ( ) throws ArooaParseException { List < String > results = new ArrayList < String > ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setExport ( "" , new ArooaObject ( results ) ) ; oddjob . run ( ) ; SequentialJob test = ( SequentialJob ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; DragPoint point = oddjob . provideConfigurationSession ( ) . dragPointFor ( test ) ; DragTransaction trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( - , green ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , red ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , amber ) ; trn . commit ( ) ; DragPoint amber = oddjob . provideConfigurationSession ( ) . dragPointFor ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; XMLArooaParser xmlParser = new XMLArooaParser ( ) ; ConfigurationHandle handle = xmlParser . parse ( amber ) ; ArooaContext xmlDoc = handle . getDocumentContext ( ) ; CutAndPasteSupport . replace ( xmlDoc . getParent ( ) , xmlDoc , new XMLConfiguration ( "" , "" ) ) ; try { handle . save ( ) ; fail ( "" ) ; } catch ( Exception e ) { } test . hardReset ( ) ; test . run ( ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; oddjob . destroy ( ) ; } public void testBadSave2 ( ) throws ArooaParseException { List < String > results = new ArrayList < String > ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setExport ( "" , new ArooaObject ( results ) ) ; oddjob . run ( ) ; SequentialJob test = ( SequentialJob ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; DragPoint point = oddjob . provideConfigurationSession ( ) . dragPointFor ( test ) ; DragTransaction trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( - , green ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , red ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , amber ) ; trn . commit ( ) ; DragPoint sequential = oddjob . provideConfigurationSession ( ) . dragPointFor ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; XMLArooaParser xmlParser = new XMLArooaParser ( ) ; ConfigurationHandle handle = xmlParser . parse ( sequential ) ; ArooaContext xmlDoc = handle . getDocumentContext ( ) ; CutAndPasteSupport . ReplaceResult result = CutAndPasteSupport . replace ( xmlDoc . getParent ( ) , xmlDoc , new XMLConfiguration ( "" , "" ) ) ; if ( result . getException ( ) != null ) { throw result . getException ( ) ; } try { handle . save ( ) ; fail ( "" ) ; } catch ( Exception e ) { e . printStackTrace ( System . out ) ; } test = ( SequentialJob ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; oddjob . destroy ( ) ; } public void testBadSave3 ( ) throws ArooaParseException { List < String > results = new ArrayList < String > ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setExport ( "" , new ArooaObject ( results ) ) ; oddjob . run ( ) ; SequentialJob test = ( SequentialJob ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; DragPoint point = oddjob . provideConfigurationSession ( ) . dragPointFor ( test ) ; DragTransaction trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( - , green ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , red ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , amber ) ; trn . commit ( ) ; DragPoint sequential = oddjob . provideConfigurationSession ( ) . dragPointFor ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; XMLArooaParser xmlParser = new XMLArooaParser ( ) ; ConfigurationHandle handle = xmlParser . parse ( sequential ) ; ArooaContext xmlDoc = handle . getDocumentContext ( ) ; String badXml = "" + "" + "" + ResultsJob . class . getName ( ) + "" + "" + "" + "" + "" + ResultsJob . class . getName ( ) + "" + "" + "" + "" + "" + "" ; ReplaceResult result = CutAndPasteSupport . replace ( xmlDoc . getParent ( ) , xmlDoc , new XMLConfiguration ( "" , badXml ) ) ; if ( result . getException ( ) != null ) { throw result . getException ( ) ; } Object amber = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertNotNull ( amber ) ; try { handle . save ( ) ; fail ( "" ) ; } catch ( Exception e ) { } Object red = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertNotNull ( red ) ; test = ( SequentialJob ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( , results . size ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . structural ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Stateful ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . framework . StopWait ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class RepeatJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( RepeatJobTest . class ) ; volatile boolean stop ; RepeatJob job ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; stop = false ; job = new RepeatJob ( ) ; job . setName ( "" ) ; } public void testSimpleRepeat3Times ( ) { Counter childJob = new Counter ( ) ; job . setJob ( childJob ) ; job . setTimes ( ) ; job . run ( ) ; assertEquals ( "" , , childJob . count ) ; } public void testSimpleUntil ( ) { Runnable childJob = new SimpleJob ( ) { @ Override protected int execute ( ) throws Throwable { job . setUntil ( true ) ; return ; } } ; job . setJob ( childJob ) ; job . run ( ) ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) childJob ) . lastStateEvent ( ) . getState ( ) ) ; } public void testInOddjob ( ) throws FailedToStopException { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . run ( ) ; new StopWait ( oj ) . run ( ) ; assertEquals ( "" , ParentState . COMPLETE , Helper . getJobState ( oj ) ) ; } public static class Counter extends SimpleJob { int count ; @ Override protected int execute ( ) throws Throwable { count ++ ; return ; } public int getCount ( ) { return count ; } } public void testSimpleCountOJ ( ) throws Exception { String xml = "" + "" + "" + "" + "" + Counter . class . getName ( ) + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Object c = new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( new Integer ( ) , PropertyUtils . getProperty ( c , "" ) ) ; } public static class ExceptionJob implements Runnable { public void run ( ) { throw new RuntimeException ( "" ) ; } } public void testSimpleFailOJ ( ) throws Exception { String xml = "" + "" + "" + "" + "" + ExceptionJob . class . getName ( ) + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Stateful repeat = new OddjobLookup ( oj ) . lookup ( "" , Stateful . class ) ; assertEquals ( ParentState . EXCEPTION , repeat . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . EXCEPTION , oj . lastStateEvent ( ) . getState ( ) ) ; } public void testRepeatExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . structural ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; public class SequentialJobInOddjobTest extends TestCase { public static class OurService { public void start ( ) { } public void stop ( ) { } } public void testException ( ) throws FailedToStopException { String xml = "" + "" + "" + "" + "" + OurService . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( ServiceState . STARTED , Helper . getJobState ( lookup . lookup ( "" ) ) ) ; assertEquals ( JobState . EXCEPTION , Helper . getJobState ( lookup . lookup ( "" ) ) ) ; assertEquals ( JobState . READY , Helper . getJobState ( lookup . lookup ( "" ) ) ) ; assertEquals ( ParentState . ACTIVE , Helper . getJobState ( lookup . lookup ( "" ) ) ) ; oddjob . stop ( ) ; assertEquals ( ParentState . EXCEPTION , Helper . getJobState ( lookup . lookup ( "" ) ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . structural ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . WaitJob ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class OverridingExecutorServiceTest extends TestCase { public static class ExecutorProvider { private int threads = ; private ExecutorService service ; public void start ( ) { if ( service != null ) { throw new IllegalStateException ( "" ) ; } service = Executors . newFixedThreadPool ( threads ) ; } public void stop ( ) throws InterruptedException , FailedToStopException { if ( service == null ) { throw new IllegalStateException ( "" ) ; } service . shutdownNow ( ) ; if ( ! service . awaitTermination ( , TimeUnit . SECONDS ) ) { throw new FailedToStopException ( this , "" ) ; } service = null ; } public int getThreads ( ) { return threads ; } public void setThreads ( int threads ) { this . threads = threads ; } public ExecutorService getService ( ) { return service ; } } public void testExample ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; StateSteps oddjobStates = new StateSteps ( oddjob ) ; oddjobStates . startCheck ( ParentState . READY , ParentState . EXECUTING ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; WaitJob wait1 = lookup . lookup ( "" , WaitJob . class ) ; WaitJob wait2 = lookup . lookup ( "" , WaitJob . class ) ; WaitJob wait3 = lookup . lookup ( "" , WaitJob . class ) ; WaitJob wait4 = lookup . lookup ( "" , WaitJob . class ) ; StateSteps states1 = new StateSteps ( wait1 ) ; StateSteps states2 = new StateSteps ( wait2 ) ; StateSteps states3 = new StateSteps ( wait3 ) ; StateSteps states4 = new StateSteps ( wait4 ) ; states1 . startCheck ( JobState . READY , JobState . EXECUTING ) ; states2 . startCheck ( JobState . READY , JobState . EXECUTING ) ; states3 . startCheck ( JobState . READY , JobState . EXECUTING ) ; states4 . startCheck ( JobState . READY , JobState . EXECUTING ) ; Thread t = new Thread ( oddjob ) ; t . start ( ) ; oddjobStates . checkWait ( ) ; oddjobStates . startCheck ( ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; states1 . checkWait ( ) ; states2 . checkWait ( ) ; wait1 . stop ( ) ; states3 . checkWait ( ) ; wait2 . stop ( ) ; states4 . checkWait ( ) ; wait3 . stop ( ) ; wait4 . stop ( ) ; oddjob . stop ( ) ; oddjobStates . checkNow ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . structural ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . Service ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; import org . oddjob . state . StateEvent ; public class ServiceManagerTest extends TestCase { private static final Logger logger = Logger . getLogger ( ServiceManagerTest . class ) ; public static class Lights implements Service { String are = "" ; @ Override public void start ( ) throws Exception { are = "" ; } @ Override public void stop ( ) throws FailedToStopException { are = "" ; } public String getAre ( ) { return are ; } @ Override public String toString ( ) { return "" ; } } public static class MachineThatGoes implements Service { String goes ; @ Override public void start ( ) throws Exception { } @ Override public void stop ( ) throws FailedToStopException { goes = "" ; } public void setGoes ( String goes ) { this . goes = goes ; } public String getGoes ( ) { return goes ; } @ Override public String toString ( ) { return "" ; } } public static class MachineThatBreaks implements Service { @ Override public void start ( ) throws Exception { throw new UnsupportedOperationException ( "" ) ; } @ Override public void stop ( ) throws FailedToStopException { } @ Override public String toString ( ) { return "" ; } } public void testExample ( ) throws FailedToStopException , ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; StateSteps steps = new StateSteps ( oddjob ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oddjob . run ( ) ; steps . checkNow ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ServiceManager test = lookup . lookup ( "" , ServiceManager . class ) ; Object lights = lookup . lookup ( "" ) ; Object machine = lookup . lookup ( "" ) ; StateEvent testState = test . lastStateEvent ( ) ; assertEquals ( ParentState . COMPLETE , testState . getState ( ) ) ; StateSteps lightsState = new StateSteps ( ( Stateful ) lights ) ; lightsState . startCheck ( ServiceState . STARTED , ServiceState . COMPLETE ) ; StateSteps machineState = new StateSteps ( ( Stateful ) machine ) ; machineState . startCheck ( ServiceState . STARTED , ServiceState . COMPLETE ) ; oddjob . stop ( ) ; lightsState . checkNow ( ) ; machineState . checkNow ( ) ; assertEquals ( testState , test . lastStateEvent ( ) ) ; lightsState . startCheck ( ServiceState . COMPLETE , ServiceState . READY ) ; ( ( Resetable ) lights ) . hardReset ( ) ; lightsState . checkNow ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; lightsState . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; ( ( Runnable ) lights ) . run ( ) ; lightsState . checkNow ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testException ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; StateSteps steps = new StateSteps ( oddjob ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . EXCEPTION ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ServiceManager test = lookup . lookup ( "" , ServiceManager . class ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . EXCEPTION ) ; oddjob . run ( ) ; steps . checkNow ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; Object lights = lookup . lookup ( "" ) ; Object machine = lookup . lookup ( "" ) ; testState . checkNow ( ) ; StateEvent lightsState = ( ( Stateful ) lights ) . lastStateEvent ( ) ; assertEquals ( ServiceState . STARTED , lightsState . getState ( ) ) ; StateSteps machineState = new StateSteps ( ( Stateful ) machine ) ; machineState . startCheck ( ServiceState . EXCEPTION , ServiceState . READY , ServiceState . STARTING , ServiceState . EXCEPTION ) ; testState . startCheck ( ParentState . EXCEPTION , ParentState . READY , ParentState . EXECUTING , ParentState . EXCEPTION ) ; ( ( Resetable ) machine ) . softReset ( ) ; test . run ( ) ; machineState . checkNow ( ) ; testState . checkNow ( ) ; oddjob . destroy ( ) ; } public void testOneJob ( ) throws ArooaPropertyException , ArooaConversionException , FailedToStopException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; StateSteps steps = new StateSteps ( oddjob ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ServiceManager test = lookup . lookup ( "" , ServiceManager . class ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oddjob . run ( ) ; steps . checkNow ( ) ; testState . checkNow ( ) ; Object lights = lookup . lookup ( "" ) ; assertEquals ( ServiceState . STARTED , ( ( Stateful ) lights ) . lastStateEvent ( ) . getState ( ) ) ; testState . startCheck ( ParentState . COMPLETE , ParentState . READY ) ; test . stop ( ) ; assertEquals ( ServiceState . COMPLETE , ( ( Stateful ) lights ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Resetable ) lights ) . hardReset ( ) ; assertEquals ( ServiceState . READY , ( ( Stateful ) lights ) . lastStateEvent ( ) . getState ( ) ) ; testState . checkNow ( ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; test . run ( ) ; assertEquals ( ServiceState . STARTED , ( ( Stateful ) lights ) . lastStateEvent ( ) . getState ( ) ) ; testState . checkNow ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . structural ; import junit . framework . TestCase ; import org . oddjob . FragmentHelper ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class JobFolderTest extends TestCase { public void testInOddjob ( ) { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( oddjob ) ) ; assertNotNull ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; assertNotNull ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; } String xml = "" + "" + "" + "" + "" ; String job = "" ; public void testCutAndPaste ( ) throws ArooaParseException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; DragPoint point = oddjob . provideConfigurationSession ( ) . dragPointFor ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; DragTransaction trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , job ) ; trn . commit ( ) ; assertNotNull ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; oddjob . destroy ( ) ; } public void testCutFolder ( ) throws ArooaParseException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; DragPoint point = oddjob . provideConfigurationSession ( ) . dragPointFor ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; DragTransaction trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , "" ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . paste ( , "" ) ; trn . commit ( ) ; trn = point . beginChange ( ChangeHow . FRESH ) ; point . cut ( ) ; trn . commit ( ) ; assertNull ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; oddjob . destroy ( ) ; } public void testExample ( ) throws ArooaParseException { FragmentHelper helper = new FragmentHelper ( ) ; helper . createComponentFromResource ( "" ) ; } } package org . oddjob . jobs . structural ; import java . io . File ; import java . io . IOException ; import java . lang . reflect . InvocationTargetException ; import java . text . ParseException ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . concurrent . Executor ; import javax . swing . SwingUtilities ; import javax . swing . event . TreeModelEvent ; import javax . swing . event . TreeModelListener ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . OurDirs ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . XMLConfigurationType ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . monitor . context . ExplorerContext ; import org . oddjob . monitor . model . EventThreadLaterExecutor ; import org . oddjob . monitor . model . ExplorerContextFactory ; import org . oddjob . monitor . model . ExplorerModel ; import org . oddjob . monitor . model . JobTreeModel ; import org . oddjob . monitor . model . JobTreeNode ; import org . oddjob . monitor . model . MockExplorerContext ; import org . oddjob . monitor . model . MockExplorerModel ; import org . oddjob . persist . MockPersisterBase ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class ForEachJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( ForEachJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public static class OurJob extends SimpleJob { Object stuff ; int index ; boolean ran ; @ Override protected int execute ( ) throws Throwable { ran = true ; return ; } @ ArooaAttribute public void setStuff ( Object stuff ) { this . stuff = stuff ; } public void setIndex ( int index ) { this . index = index ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + index ; } } private class ChildCatcher implements StructuralListener { final List < Object > children = new ArrayList < Object > ( ) ; public void childAdded ( StructuralEvent event ) { children . add ( event . getIndex ( ) , event . getChild ( ) ) ; } public void childRemoved ( StructuralEvent event ) { children . remove ( event . getIndex ( ) ) ; } } public void testOneJobTwoValues ( ) throws ArooaParseException { String xml = "" + "" + "" + OurJob . class . getName ( ) + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; test . setArooaSession ( new OddjobSessionFactory ( ) . createSession ( ) ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( "" , "" ) ) ; ChildCatcher children = new ChildCatcher ( ) ; test . addStructuralListener ( children ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , children . children . size ( ) ) ; OurJob job1 = ( OurJob ) children . children . get ( ) ; OurJob job2 = ( OurJob ) children . children . get ( ) ; assertEquals ( "" , job1 . stuff ) ; assertEquals ( , job1 . index ) ; assertTrue ( job1 . ran ) ; assertEquals ( "" , job2 . stuff ) ; assertEquals ( , job2 . index ) ; assertTrue ( job2 . ran ) ; } public void testWithEmptyList ( ) { String xml = "" ; ForEachJob test = new ForEachJob ( ) ; test . setArooaSession ( new OddjobSessionFactory ( ) . createSession ( ) ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Collections . emptyList ( ) ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . READY ) ; test . run ( ) ; state . checkNow ( ) ; } public void testLoadOnJobTwoValues ( ) throws ArooaParseException { String xml = "" + "" + "" + OurJob . class . getName ( ) + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; test . setArooaSession ( new OddjobSessionFactory ( ) . createSession ( ) ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( "" , "" ) ) ; ChildCatcher children = new ChildCatcher ( ) ; test . addStructuralListener ( children ) ; assertTrue ( test . isLoadable ( ) ) ; test . load ( ) ; assertFalse ( test . isLoadable ( ) ) ; assertEquals ( , children . children . size ( ) ) ; OurJob job1 = ( OurJob ) children . children . get ( ) ; OurJob job2 = ( OurJob ) children . children . get ( ) ; assertEquals ( "" , job1 . stuff ) ; assertEquals ( , job1 . index ) ; assertFalse ( job1 . ran ) ; assertEquals ( "" , job2 . stuff ) ; assertEquals ( , job2 . index ) ; assertFalse ( job2 . ran ) ; } public static class RegistryCheck extends SimpleJob { ArooaSession session ; protected int execute ( ) throws Throwable { session = getArooaSession ( ) ; return ; } } private class OurContext extends MockArooaContext { ArooaSession session ; OurContext ( ArooaSession session ) { this . session = session ; } @ Override public ArooaSession getSession ( ) { return session ; } } public void testPseudoRegistry ( ) { String findMe = new String ( "" ) ; StandardArooaSession session = new StandardArooaSession ( ) ; session . getBeanRegistry ( ) . register ( "" , findMe ) ; String xml = "" + "" + "" + RegistryCheck . class . getName ( ) + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; test . setValues ( Arrays . asList ( "" ) ) ; test . setArooaSession ( session ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; ComponentPool pool = session . getComponentPool ( ) ; pool . registerComponent ( new ComponentTrinity ( test , test , new OurContext ( session ) { @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void configure ( ) { } } ; } } ) , "" ) ; test . run ( ) ; ChildCatcher child = new ChildCatcher ( ) ; test . addStructuralListener ( child ) ; RegistryCheck instance = ( RegistryCheck ) child . children . get ( ) ; BeanRegistry crRecovered = instance . session . getBeanRegistry ( ) ; Object bean = crRecovered . lookup ( "" ) ; assertNotNull ( bean ) ; assertEquals ( ForEachJob . LocalBean . class , bean . getClass ( ) ) ; ForEachJob . LocalBean lb = ( ForEachJob . LocalBean ) bean ; int index = lb . getIndex ( ) ; assertEquals ( , index ) ; String current = ( String ) lb . getCurrent ( ) ; assertEquals ( "" , current ) ; } public void testBasic ( ) throws ParseException { checks = new Object [ ] { new String ( "" ) , DateHelper . parseDate ( "" ) , null , new File ( "" ) } ; executed = ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; Check check = ( Check ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertNull ( check ) ; assertEquals ( , executed ) ; oj . destroy ( ) ; } static Object [ ] checks ; static int executed ; public static class Check extends SimpleJob { Object o ; int i ; @ ArooaAttribute public void setObject ( Object o ) { this . o = o ; } public void setIndex ( int i ) { this . i = i ; } protected int execute ( ) { executed ++ ; logger . debug ( "" + o + "" ) ; assertEquals ( checks [ i ] , o ) ; return ; } } public void testReset ( ) throws Exception { ChildCatcher childs = new ChildCatcher ( ) ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + FlagState . class . getName ( ) + "" + "" + "" + "" + "" + "" ; ForEachJob test = ( ForEachJob ) Helper . createComponentFromXml ( xml ) ; test . addStructuralListener ( childs ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( childs . children . get ( ) ) ) ; assertEquals ( JobState . INCOMPLETE , Helper . getJobState ( childs . children . get ( ) ) ) ; assertEquals ( JobState . READY , Helper . getJobState ( childs . children . get ( ) ) ) ; assertEquals ( ParentState . INCOMPLETE , Helper . getJobState ( test ) ) ; test . softReset ( ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( childs . children . get ( ) ) ) ; assertEquals ( JobState . READY , Helper . getJobState ( childs . children . get ( ) ) ) ; assertEquals ( JobState . READY , Helper . getJobState ( childs . children . get ( ) ) ) ; assertEquals ( ParentState . READY , Helper . getJobState ( test ) ) ; test . run ( ) ; Stateful child1 = ( Stateful ) childs . children . get ( ) ; Stateful child2 = ( Stateful ) childs . children . get ( ) ; assertEquals ( JobState . COMPLETE , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , test . getIndex ( ) ) ; test . hardReset ( ) ; assertEquals ( , test . getIndex ( ) ) ; assertEquals ( JobState . DESTROYED , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . DESTROYED , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , childs . children . size ( ) ) ; test . run ( ) ; child1 = ( Stateful ) childs . children . get ( ) ; child2 = ( Stateful ) childs . children . get ( ) ; assertEquals ( JobState . COMPLETE , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . destroy ( ) ; assertEquals ( , childs . children . size ( ) ) ; assertEquals ( JobState . DESTROYED , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . DESTROYED , child2 . lastStateEvent ( ) . getState ( ) ) ; } public void testIdenticalIdInForEachConfig ( ) throws Exception { String config = "" + "" + "" + "" + "" ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; XMLConfigurationType configType = new XMLConfigurationType ( ) ; configType . setXml ( config ) ; oddjob . setExport ( "" , configType ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; } public void testSerializeForEach ( ) throws IOException , ClassNotFoundException { String xml = "" + "" + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; test . setArooaSession ( new OddjobSessionFactory ( ) . createSession ( ) ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( "" , "" ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; ForEachJob copy = Helper . copy ( test ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; } private class OurPersister extends MockPersisterBase { @ Override protected void persist ( Path path , String id , Object component ) { assertEquals ( new Path ( "" ) , path ) ; assertEquals ( "" , id ) ; try { Helper . copy ( component ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } @ Override protected Object restore ( Path path , String id , ClassLoader classLoader ) { assertEquals ( new Path ( "" ) , path ) ; assertEquals ( "" , id ) ; return null ; } } public void testForEachPersistenceButNoChildren ( ) throws Exception { String config = "" + "" + "" + "" + "" ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; XMLConfigurationType configType = new XMLConfigurationType ( ) ; configType . setXml ( config ) ; oddjob . setExport ( "" , configType ) ; OurPersister persister = new OurPersister ( ) ; persister . setPath ( "" ) ; oddjob . setPersister ( persister ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; } public void testFileCopyExample ( ) { OurDirs dirs = new OurDirs ( ) ; File toDir = dirs . relative ( "" ) ; if ( toDir . exists ( ) ) { toDir . delete ( ) ; } toDir . mkdirs ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . getPath ( ) } ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; assertTrue ( new File ( toDir , "" ) . exists ( ) ) ; assertTrue ( new File ( toDir , "" ) . exists ( ) ) ; assertTrue ( new File ( toDir , "" ) . exists ( ) ) ; } public void testWithIds ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Structural foreach = lookup . lookup ( "" , Structural . class ) ; ChildCatcher catcher = new ChildCatcher ( ) ; foreach . addStructuralListener ( catcher ) ; assertEquals ( , catcher . children . size ( ) ) ; assertEquals ( "" , catcher . children . get ( ) . toString ( ) ) ; assertEquals ( "" , catcher . children . get ( ) . toString ( ) ) ; assertEquals ( "" , catcher . children . get ( ) . toString ( ) ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob . destroy ( ) ; } public void testPropertiesInChildren ( ) { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; XMLConfigurationType configType = new XMLConfigurationType ( ) ; configType . setXml ( config ) ; oddjob . setExport ( "" , configType ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob . destroy ( ) ; } public void testStop ( ) { String xml = "" + "" + "" + "" + "" ; final ForEachJob test = new ForEachJob ( ) ; test . setArooaSession ( new OddjobSessionFactory ( ) . createSession ( ) ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( "" , "" ) ) ; test . addStructuralListener ( new StructuralListener ( ) { @ Override public void childRemoved ( StructuralEvent event ) { } @ Override public void childAdded ( StructuralEvent event ) { Stateful child = ( Stateful ) event . getChild ( ) ; child . addStateListener ( new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { if ( event . getState ( ) . isStoppable ( ) ) { new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { test . stop ( ) ; } catch ( FailedToStopException e ) { throw new RuntimeException ( e ) ; } } } ) . start ( ) ; } } } ) ; } } ) ; test . run ( ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( children [ ] ) ) ; assertEquals ( JobState . READY , Helper . getJobState ( children [ ] ) ) ; } public void testAutoInject ( ) { String forEachConfig = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String ojConfig = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + forEachConfig + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , ojConfig ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } private static class RunNowExecutor implements Executor { @ Override public void execute ( Runnable command ) { command . run ( ) ; } } public static class SlowToDestroyJob extends SimpleJob { @ Override protected int execute ( ) throws Throwable { return ; } @ Override protected void onDestroy ( ) { try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } } private static class JobCounter implements StructuralListener { private Set < Object > jobs = new HashSet < Object > ( ) ; @ Override public void childAdded ( StructuralEvent event ) { Object child = event . getChild ( ) ; jobs . add ( child ) ; if ( child instanceof Structural ) { ( ( Structural ) child ) . addStructuralListener ( this ) ; } } @ Override public void childRemoved ( StructuralEvent event ) { Object child = event . getChild ( ) ; jobs . remove ( child ) ; } } private static class NodeCounter implements TreeModelListener { private Set < Object > jobs = new HashSet < Object > ( ) ; @ Override public void treeNodesChanged ( TreeModelEvent e ) { } @ Override public void treeStructureChanged ( TreeModelEvent e ) { throw new RuntimeException ( "" ) ; } @ Override public void treeNodesInserted ( TreeModelEvent e ) { assertEquals ( , e . getChildren ( ) . length ) ; jobs . add ( e . getChildren ( ) [ ] ) ; } @ Override public void treeNodesRemoved ( TreeModelEvent e ) { assertEquals ( , e . getChildren ( ) . length ) ; jobs . remove ( e . getChildren ( ) [ ] ) ; } } public void testDestroyWithComplicateStructure ( ) throws InterruptedException , InvocationTargetException { String forEachConfig = "" + "" + "" + "" + "" + SlowToDestroyJob . class . getName ( ) + "" + "" + SlowToDestroyJob . class . getName ( ) + "" + "" + SlowToDestroyJob . class . getName ( ) + "" + "" + SlowToDestroyJob . class . getName ( ) + "" + "" + SlowToDestroyJob . class . getName ( ) + "" + "" + "" + "" + "" ; String ojConfig = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + forEachConfig + "" + "" + "" + "" + "" + "" + "" ; final Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , ojConfig ) ) ; JobCounter jobCounter = new JobCounter ( ) ; oddjob . addStructuralListener ( jobCounter ) ; JobTreeModel model = new JobTreeModel ( new RunNowExecutor ( ) ) ; NodeCounter nodeCounter = new NodeCounter ( ) ; model . addTreeModelListener ( nodeCounter ) ; JobTreeNode root = new JobTreeNode ( new MockExplorerModel ( ) { @ Override public Oddjob getOddjob ( ) { return oddjob ; } } , model , new EventThreadLaterExecutor ( ) , new ExplorerContextFactory ( ) { @ Override public ExplorerContext createFrom ( ExplorerModel explorerModel ) { return new MockExplorerContext ( ) { @ Override public ExplorerContext addChild ( Object child ) { return this ; } } ; } } ) ; root . setVisible ( true ) ; oddjob . run ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { } } ) ; assertEquals ( , jobCounter . jobs . size ( ) ) ; assertEquals ( , nodeCounter . jobs . size ( ) ) ; oddjob . destroy ( ) ; SwingUtilities . invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { } } ) ; assertEquals ( , jobCounter . jobs . size ( ) ) ; assertEquals ( , nodeCounter . jobs . size ( ) ) ; } public static class EvenNumberHater extends SimpleJob { private int number ; private boolean failedOnce ; @ Override protected int execute ( ) throws Throwable { if ( number % == && ! failedOnce ) { failedOnce = true ; return ; } System . out . println ( number ) ; return ; } public void setNumber ( int number ) { this . number = number ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + number ; } } public void testRetryRetriesFromCorrectValue ( ) { ChildCatcher childs = new ChildCatcher ( ) ; String xml = "" + "" + "" + EvenNumberHater . class . getName ( ) + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( , , ) ) ; test . addStructuralListener ( childs ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; test . run ( ) ; Stateful child1 = ( Stateful ) childs . children . get ( ) ; Stateful child2 = ( Stateful ) childs . children . get ( ) ; Stateful child3 = ( Stateful ) childs . children . get ( ) ; assertEquals ( JobState . INCOMPLETE , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , child3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . softReset ( ) ; assertEquals ( JobState . READY , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , child3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , child3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . softReset ( ) ; assertEquals ( JobState . COMPLETE , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , child3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , child1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , child3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; test . destroy ( ) ; } } package org . oddjob . jobs . structural ; import java . util . Arrays ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ForEachWindowsTest extends TestCase { private static final Logger logger = Logger . getLogger ( ForEachWindowsTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testPreLoad ( ) { String xml = "" + "" + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; test . setArooaSession ( session ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( , , , , , , , , , ) ) ; test . setPreLoad ( ) ; test . load ( ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; test . run ( ) ; children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; test . destroy ( ) ; } public void testPurgeAfter ( ) { String xml = "" + "" + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; test . setArooaSession ( session ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( , , , , , , , , , ) ) ; test . setPurgeAfter ( ) ; test . load ( ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; test . run ( ) ; children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; test . destroy ( ) ; } public void testPreLoadAndPurgeAfter ( ) { String xml = "" + "" + "" + "" + "" ; ForEachJob test = new ForEachJob ( ) ; ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; test . setArooaSession ( session ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setValues ( Arrays . asList ( , , , , , , , , , ) ) ; test . setPreLoad ( ) ; test . setPurgeAfter ( ) ; test . load ( ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; test . run ( ) ; children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; test . destroy ( ) ; } public void testForEachWithExecutionWindowExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Object [ ] children = Helper . getChildren ( Helper . getChildren ( oddjob ) [ ] ) ; assertEquals ( , children . length ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . structural ; import java . util . HashSet ; import java . util . Set ; import java . util . concurrent . Future ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FailedToStopException ; import org . oddjob . MockStateful ; import org . oddjob . Oddjob ; import org . oddjob . OddjobComponentResolver ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . Service ; import org . oddjob . jobs . WaitJob ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . scheduling . MockScheduledExecutorService ; import org . oddjob . scheduling . MockScheduledFuture ; import org . oddjob . state . FlagState ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . JobState ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; import org . oddjob . state . StateListener ; public class ParallelJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( ParallelJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } private class LaterExecutor extends MockScheduledExecutorService { private Runnable runnable ; public Future < ? > submit ( Runnable runnable ) { this . runnable = runnable ; return new MockScheduledFuture < Void > ( ) ; } } public void testStepByStepOneJob ( ) { FlagState job1 = new FlagState ( JobState . COMPLETE ) ; LaterExecutor executor = new LaterExecutor ( ) ; ParallelJob test = new ParallelJob ( ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . setExecutorService ( executor ) ; test . setJobs ( , job1 ) ; test . run ( ) ; steps . checkNow ( ) ; assertNotNull ( executor . runnable ) ; steps . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; executor . runnable . run ( ) ; steps . checkNow ( ) ; } public void testThreeJobs ( ) throws InterruptedException { FlagState job1 = new FlagState ( JobState . COMPLETE ) ; FlagState job2 = new FlagState ( JobState . COMPLETE ) ; FlagState job3 = new FlagState ( JobState . COMPLETE ) ; DefaultExecutors defaultServices = new DefaultExecutors ( ) ; ParallelJob test = new ParallelJob ( ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . setExecutorService ( defaultServices . getPoolExecutor ( ) ) ; test . setJobs ( , job1 ) ; test . setJobs ( , job2 ) ; test . setJobs ( , job3 ) ; test . run ( ) ; steps . checkWait ( ) ; assertEquals ( JobState . COMPLETE , job3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; steps . startCheck ( ParentState . COMPLETE , ParentState . READY ) ; test . hardReset ( ) ; assertEquals ( JobState . READY , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job3 . lastStateEvent ( ) . getState ( ) ) ; steps . checkNow ( ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; steps . checkWait ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job3 . lastStateEvent ( ) . getState ( ) ) ; defaultServices . stop ( ) ; } public void testThrottledExecution ( ) throws InterruptedException { FlagState job1 = new FlagState ( JobState . COMPLETE ) ; FlagState job2 = new FlagState ( JobState . COMPLETE ) ; FlagState job3 = new FlagState ( JobState . COMPLETE ) ; DefaultExecutors defaultServices = new DefaultExecutors ( ) ; defaultServices . setPoolSize ( ) ; ParallelJob test = new ParallelJob ( ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . setExecutorService ( defaultServices . getPoolExecutor ( ) ) ; test . setJobs ( , job1 ) ; test . setJobs ( , job2 ) ; test . setJobs ( , job3 ) ; test . run ( ) ; steps . checkWait ( ) ; assertEquals ( JobState . COMPLETE , job3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; } public void testStop ( ) throws InterruptedException , FailedToStopException { DefaultExecutors defaultServices = new DefaultExecutors ( ) ; ParallelJob test = new ParallelJob ( ) ; test . setExecutorService ( defaultServices . getPoolExecutor ( ) ) ; WaitJob job = new WaitJob ( ) ; test . setJobs ( , job ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; StateSteps waitState = new StateSteps ( job ) ; waitState . startCheck ( JobState . READY , JobState . EXECUTING ) ; test . run ( ) ; steps . checkWait ( ) ; waitState . checkWait ( ) ; steps . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; test . stop ( ) ; steps . checkNow ( ) ; test . destroy ( ) ; defaultServices . stop ( ) ; } private class NowExecutor extends MockScheduledExecutorService { public Future < ? > submit ( Runnable runnable ) { runnable . run ( ) ; return new MockScheduledFuture < Void > ( ) ; } } private class DestroyJob extends MockStateful implements Runnable { JobStateHandler handler = new JobStateHandler ( this ) ; public void addStateListener ( StateListener listener ) { handler . addStateListener ( listener ) ; } public void removeStateListener ( StateListener listener ) { handler . removeStateListener ( listener ) ; } public void run ( ) { handler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { handler . setState ( JobState . COMPLETE ) ; handler . fireEvent ( ) ; } } ) ; } void destroy ( ) { handler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { handler . setState ( JobState . DESTROYED ) ; handler . fireEvent ( ) ; } } ) ; } } public void testChildDestroyed ( ) throws InterruptedException { ParallelJob test = new ParallelJob ( ) ; test . setExecutorService ( new NowExecutor ( ) ) ; DestroyJob destroy = new DestroyJob ( ) ; test . setJobs ( , destroy ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; steps . checkWait ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; steps . startCheck ( ParentState . COMPLETE , ParentState . DESTROYED ) ; test . destroy ( ) ; test . setJobs ( , null ) ; destroy . destroy ( ) ; steps . checkNow ( ) ; } public void testInOddjob ( ) throws InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; StateSteps steps = new StateSteps ( oddjob ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; steps . checkWait ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; Set < String > results = new HashSet < String > ( ) ; results . add ( lines [ ] . trim ( ) ) ; results . add ( lines [ ] . trim ( ) ) ; assertTrue ( results . contains ( "" ) ) ; assertTrue ( results . contains ( "" ) ) ; oddjob . destroy ( ) ; } public void testStopInOddjob ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; StateSteps oddjobState = new StateSteps ( oddjob ) ; oddjobState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; StateSteps wait1State = new StateSteps ( new OddjobLookup ( oddjob ) . lookup ( "" , Stateful . class ) ) ; wait1State . startCheck ( JobState . READY , JobState . EXECUTING ) ; StateSteps wait2State = new StateSteps ( new OddjobLookup ( oddjob ) . lookup ( "" , Stateful . class ) ) ; wait2State . startCheck ( JobState . READY , JobState . EXECUTING ) ; Thread t = new Thread ( oddjob ) ; t . start ( ) ; wait1State . checkWait ( ) ; wait2State . checkWait ( ) ; oddjobState . checkWait ( ) ; oddjobState . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . stop ( ) ; oddjobState . checkNow ( ) ; oddjob . destroy ( ) ; } public static class MyService implements Service { public void start ( ) { } public void stop ( ) { } } public void testParallelServices ( ) throws FailedToStopException , InterruptedException { DefaultExecutors defaultServices = new DefaultExecutors ( ) ; ParallelJob test = new ParallelJob ( ) ; test . setExecutorService ( defaultServices . getPoolExecutor ( ) ) ; Object service1 = new OddjobComponentResolver ( ) . resolve ( new MyService ( ) , null ) ; Object service2 = new OddjobComponentResolver ( ) . resolve ( new MyService ( ) , null ) ; test . setJobs ( , ( Runnable ) service1 ) ; test . setJobs ( , ( Runnable ) service2 ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; StateSteps service1State = new StateSteps ( ( Stateful ) service1 ) ; service1State . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; StateSteps service2State = new StateSteps ( ( Stateful ) service2 ) ; service2State . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED ) ; test . run ( ) ; steps . checkNow ( ) ; service1State . checkWait ( ) ; service2State . checkWait ( ) ; steps . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; test . stop ( ) ; steps . checkNow ( ) ; defaultServices . stop ( ) ; } public void testEmpty ( ) throws InterruptedException { ParallelJob test = new ParallelJob ( ) ; test . setExecutorService ( new NowExecutor ( ) ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . READY ) ; test . run ( ) ; steps . checkWait ( ) ; test . destroy ( ) ; } } package org . oddjob . jobs ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import org . custommonkey . xmlunit . XMLTestCase ; import org . oddjob . io . BufferType ; import org . xml . sax . SAXException ; public class XSLTJobTest extends XMLTestCase { String EOL = System . getProperty ( "" ) ; public void testIdentity ( ) throws SAXException , IOException { String xml = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; BufferType result = new BufferType ( ) ; result . configured ( ) ; XSLTJob test = new XSLTJob ( ) ; test . setStylesheet ( getClass ( ) . getResourceAsStream ( "" ) ) ; test . setInput ( new ByteArrayInputStream ( xml . getBytes ( ) ) ) ; test . setOutput ( result . toOutputStream ( ) ) ; test . run ( ) ; assertXMLEqual ( xml , result . getText ( ) ) ; } public void testParmeter ( ) throws SAXException , IOException { String xml = "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; BufferType result = new BufferType ( ) ; result . configured ( ) ; XSLTJob test = new XSLTJob ( ) ; test . setStylesheet ( getClass ( ) . getResourceAsStream ( "" ) ) ; test . setInput ( new ByteArrayInputStream ( xml . getBytes ( ) ) ) ; test . setOutput ( result . toOutputStream ( ) ) ; test . setParameters ( "" , "" ) ; test . run ( ) ; assertXMLEqual ( xml , result . getText ( ) ) ; } } package org . oddjob . jobs ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class ExecJobBatTest extends TestCase { class Console implements LogListener { List < String > lines = new ArrayList < String > ( ) ; public void logEvent ( LogEvent logEvent ) { lines . add ( logEvent . getMessage ( ) ) ; } } public void testConsole ( ) throws IOException { if ( ! System . getProperty ( "" ) . startsWith ( "" ) ) { return ; } ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; ExecJob test = new ExecJob ( ) ; test . setStdout ( out ) ; test . setDir ( new OurDirs ( ) . relative ( "" ) ) ; test . setCommand ( "" ) ; test . run ( ) ; assertEquals ( "" , out . toString ( ) ) ; Console console = new Console ( ) ; test . consoleLog ( ) . addListener ( console , LogLevel . DEBUG , - , ) ; dump ( console . lines ) ; assertEquals ( , console . lines . size ( ) ) ; assertEquals ( "" + System . getProperty ( "" ) , console . lines . get ( ) ) ; } void dump ( List < String > lines ) { System . out . println ( "" ) ; for ( String line : lines ) { System . out . print ( line ) ; } } } package org . oddjob . jobs ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . MockArooaTools ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class CheckJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( CheckJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; } public void testNoValue ( ) { CheckJob test = new CheckJob ( ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setNull ( true ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } class OurSession extends MockArooaSession { @ Override public ArooaTools getTools ( ) { return new MockArooaTools ( ) { @ Override public ArooaConverter getArooaConverter ( ) { return new DefaultConverter ( ) ; } } ; } } public void testIntegerEq ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( new Integer ( ) ) ; test . setEq ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setEq ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setEq ( new ArooaObject ( new Float ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testIntegerNe ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( new Integer ( ) ) ; test . setNe ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setNe ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setNe ( new ArooaObject ( new Float ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testIntegerLt ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( new Integer ( ) ) ; test . setLt ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setLt ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setLt ( new ArooaObject ( new Float ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testIntegerLe ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( new Integer ( ) ) ; test . setLe ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setLe ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setLe ( new ArooaObject ( new Float ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testIntegerGt ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( new Integer ( ) ) ; test . setGt ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setGt ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setGt ( new ArooaObject ( new Float ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testIntegerGe ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( new Integer ( ) ) ; test . setGe ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setGe ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setGe ( new ArooaObject ( new Float ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testStringEq ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( "" ) ; test . setEq ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setEq ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testStringNe ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( "" ) ; test . setNe ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setNe ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testStringLt ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( "" ) ; test . setLt ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setLt ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setLt ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testStringGt ( ) { CheckJob test = new CheckJob ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . setValue ( "" ) ; test . setGt ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setGt ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setGt ( new ArooaObject ( "" ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; test . setValue ( "" ) ; test . setGt ( new ArooaObject ( new Integer ( ) ) ) ; test . run ( ) ; assertEquals ( , test . getResult ( ) ) ; } public void testTextExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testTextIncompleteExample ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . INCOMPLETE ) ; oddjob . run ( ) ; state . checkNow ( ) ; Structural structural = new OddjobLookup ( oddjob ) . lookup ( "" , Structural . class ) ; Object [ ] children = Helper . getChildren ( structural ) ; for ( Object child : children ) { assertEquals ( JobState . INCOMPLETE , ( ( Stateful ) child ) . lastStateEvent ( ) . getState ( ) ) ; } oddjob . destroy ( ) ; } public void testNumberExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testExistsExample ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . INCOMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , new OddjobLookup ( oddjob ) . lookup ( "" , Stateful . class ) . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , new OddjobLookup ( oddjob ) . lookup ( "" , Stateful . class ) . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs ; import java . io . IOException ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . jobs . GrabJob . LoosingAction ; import org . oddjob . scheduling . Keeper ; import org . oddjob . scheduling . LoosingOutcome ; import org . oddjob . scheduling . Outcome ; import org . oddjob . scheduling . WinningOutcome ; import org . oddjob . state . FlagState ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class GrabJobTest extends TestCase { class WinnerKeeper implements Keeper { boolean complete ; @ Override public Outcome grab ( final String name , Object instance ) { return new WinningOutcome ( ) { @ Override public boolean isWon ( ) { return true ; } @ Override public String getWinner ( ) { return name ; } @ Override public void complete ( ) { complete = true ; } } ; } } public void testAsWinner ( ) throws IOException , ClassNotFoundException { GrabJob test = new GrabJob ( ) ; FlagState flag = new FlagState ( JobState . COMPLETE ) ; WinnerKeeper keeper = new WinnerKeeper ( ) ; test . setKeeper ( keeper ) ; test . setIdentifier ( "" ) ; test . setJob ( flag ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , flag . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , test . getWinner ( ) ) ; assertEquals ( true , keeper . complete ) ; GrabJob copy = Helper . copy ( test ) ; assertEquals ( JobState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , copy . getWinner ( ) ) ; } class LooserKeeper implements Keeper { StateListener listener ; @ Override public Outcome grab ( String ourIdentifier , Object ourInstance ) { return new LoosingOutcome ( ) { @ Override public void removeStateListener ( StateListener l ) { if ( listener == null ) { throw new IllegalStateException ( "" ) ; } assertEquals ( listener , l ) ; listener = null ; } @ Override public void addStateListener ( StateListener l ) { if ( listener != null ) { throw new IllegalStateException ( "" ) ; } listener = l ; } @ Override public StateEvent lastStateEvent ( ) { throw new RuntimeException ( "" ) ; } @ Override public boolean isWon ( ) { return false ; } @ Override public String getWinner ( ) { return "" ; } } ; } } public void testNotWinner ( ) { GrabJob test = new GrabJob ( ) ; FlagState flag = new FlagState ( JobState . COMPLETE ) ; LooserKeeper keeper = new LooserKeeper ( ) ; test . setKeeper ( keeper ) ; test . setIdentifier ( "" ) ; test . setJob ( flag ) ; test . setOnLoosing ( LoosingAction . WAIT ) ; test . run ( ) ; assertEquals ( JobState . READY , flag . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; keeper . listener . jobStateChange ( new StateEvent ( flag , JobState . COMPLETE ) ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , Helper . getIconId ( test ) ) ; assertEquals ( "" , test . getWinner ( ) ) ; } public void testStopAsLooser ( ) throws FailedToStopException { GrabJob test = new GrabJob ( ) ; FlagState flag = new FlagState ( JobState . COMPLETE ) ; LooserKeeper keeper = new LooserKeeper ( ) ; test . setKeeper ( keeper ) ; test . setIdentifier ( "" ) ; test . setJob ( flag ) ; test . setOnLoosing ( LoosingAction . WAIT ) ; test . run ( ) ; assertEquals ( JobState . READY , flag . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; test . stop ( ) ; assertEquals ( JobState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertNull ( keeper . listener ) ; assertEquals ( "" , test . getWinner ( ) ) ; } public void testStopAsWinner ( ) throws FailedToStopException , InterruptedException { GrabJob test = new GrabJob ( ) ; WaitJob wait = new WaitJob ( ) ; WinnerKeeper keeper = new WinnerKeeper ( ) ; test . setKeeper ( keeper ) ; test . setIdentifier ( "" ) ; test . setJob ( wait ) ; Thread t = new Thread ( test ) ; t . start ( ) ; WaitJob checkExecuting = new WaitJob ( ) ; checkExecuting . setFor ( wait ) ; checkExecuting . setState ( new IsStoppable ( ) ) ; checkExecuting . run ( ) ; test . stop ( ) ; t . join ( ) ; assertEquals ( JobState . COMPLETE , wait . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testSerialize ( ) throws IOException , ClassNotFoundException { GrabJob test = new GrabJob ( ) ; FlagState flag = new FlagState ( JobState . COMPLETE ) ; WinnerKeeper keeper = new WinnerKeeper ( ) ; test . setKeeper ( keeper ) ; test . setIdentifier ( "" ) ; test . setJob ( flag ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , flag . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; GrabJob copy = Helper . copy ( test ) ; assertEquals ( JobState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , test . getWinner ( ) ) ; copy . setJob ( flag ) ; copy . hardReset ( ) ; assertEquals ( JobState . READY , flag . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , copy . lastStateEvent ( ) . getState ( ) ) ; assertNull ( copy . getWinner ( ) ) ; copy . setKeeper ( new WinnerKeeper ( ) ) ; copy . run ( ) ; assertEquals ( JobState . COMPLETE , flag . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , copy . getWinner ( ) ) ; } } package org . oddjob . jobs ; import java . beans . PropertyVetoException ; import java . lang . reflect . InvocationTargetException ; import junit . framework . TestCase ; import org . apache . commons . beanutils . BeanUtils ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . FragmentHelper ; import org . oddjob . Helper ; import org . oddjob . IconSteps ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . structural . SequentialJob ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . state . FlagState ; import org . oddjob . state . IsNot ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateConditions ; public class WaitJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( WaitJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; } public void testInOddjob ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , this . getClass ( ) . getResourceAsStream ( "" ) ) ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; state . checkWait ( ) ; Object result = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( result , "" ) ) ; oddjob . destroy ( ) ; } public void testStateWait ( ) { FlagState sample = new FlagState ( ) ; sample . setState ( JobState . COMPLETE ) ; WaitJob wait = new WaitJob ( ) ; wait . setPause ( ) ; SequentialJob sequential = new SequentialJob ( ) ; sequential . setJobs ( , wait ) ; sequential . setJobs ( , sample ) ; Thread t = new Thread ( sequential ) ; WaitJob test = new WaitJob ( ) ; test . setFor ( sample ) ; test . setState ( StateConditions . COMPLETE ) ; t . start ( ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , sample . lastStateEvent ( ) . getState ( ) ) ; } public void testStopStateWait ( ) throws InterruptedException , FailedToStopException { FlagState sample = new FlagState ( ) ; sample . setState ( JobState . COMPLETE ) ; WaitJob test = new WaitJob ( ) ; test . setFor ( sample ) ; test . setState ( StateConditions . INCOMPLETE ) ; test . setPause ( ) ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( "" , "" , "" ) ; Thread t = new Thread ( test ) ; t . start ( ) ; icons . checkWait ( ) ; icons . startCheck ( "" , "" , "" ) ; sample . run ( ) ; icons . checkWait ( ) ; test . stop ( ) ; icons . startCheck ( "" , "" , "" ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testStateWaitInOJ ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , WaitJobTest . class . getResourceAsStream ( "" ) ) ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; state . checkWait ( ) ; Object result = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( result , "" ) ) ; oddjob . destroy ( ) ; } public void testNotStateWait ( ) { FlagState sample = new FlagState ( ) ; sample . setState ( JobState . COMPLETE ) ; WaitJob test = new WaitJob ( ) ; test . setFor ( sample ) ; test . setState ( new IsNot ( StateConditions . COMPLETE ) ) ; assertEquals ( JobState . READY , sample . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; } public void testSimpleStop ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; DefaultExecutors services = new DefaultExecutors ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setOddjobExecutors ( services ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; state . checkWait ( ) ; oddjob . destroy ( ) ; services . stop ( ) ; } public void testStateStop ( ) throws PropertyVetoException , InterruptedException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; state . checkWait ( ) ; assertNotNull ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; oddjob . destroy ( ) ; } public void testWaitExample ( ) throws InterruptedException , IllegalAccessException , InvocationTargetException , NoSuchMethodException , ArooaParseException { FragmentHelper helper = new FragmentHelper ( ) ; Object sequential = helper . createComponentFromResource ( "" ) ; Object [ ] children = Helper . getChildren ( sequential ) ; Object wait = children [ ] ; StateSteps waitStates = new StateSteps ( ( Stateful ) wait ) ; waitStates . startCheck ( JobState . READY , JobState . EXECUTING ) ; new Thread ( ( Runnable ) sequential ) . start ( ) ; waitStates . checkWait ( ) ; StateSteps echoStates = new StateSteps ( ( Stateful ) children [ ] ) ; echoStates . startCheck ( JobState . READY , JobState . EXECUTING , JobState . COMPLETE ) ; BeanUtils . setProperty ( children [ ] , "" , "" ) ; echoStates . setTimeout ( ) ; echoStates . checkWait ( ) ; String text = ( String ) BeanUtils . getProperty ( children [ ] , "" ) ; assertEquals ( "" , text ) ; } } package org . oddjob . jobs ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . log4j . AppenderSkeleton ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . apache . log4j . spi . LoggingEvent ; import org . oddjob . ConsoleCapture ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . logging . log4j . LogoutType ; import org . oddjob . state . ParentState ; public class ExecJobExamplesTest extends TestCase { private static final Logger logger = Logger . getLogger ( ExecJobExamplesTest . class ) ; public void testSimpleExamples ( ) throws ArooaParseException { Helper . createComponentFromConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Helper . createComponentFromConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; } public void testEnvironmentExample ( ) throws ArooaPropertyException , ArooaConversionException { String envCommand ; String os = System . getProperty ( "" ) . toLowerCase ( ) ; if ( os . matches ( "" ) ) { envCommand = "" ; } else { envCommand = "" ; } Properties properties = new Properties ( ) ; properties . put ( "" , envCommand ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setProperties ( properties ) ; oddjob . load ( ) ; ExecJob exec = new OddjobLookup ( oddjob ) . lookup ( "" , ExecJob . class ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( exec . consoleLog ( ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; boolean found = false ; for ( String line : lines ) { if ( line . contains ( "" ) ) { found = true ; } } assertTrue ( found ) ; oddjob . destroy ( ) ; } public void testWithStdInExample ( ) throws ArooaPropertyException , ArooaConversionException , IOException { OurDirs dirs = new OurDirs ( ) ; File runJar = dirs . relative ( "" ) ; Properties properties = new Properties ( ) ; properties . put ( "" , runJar . getCanonicalPath ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setFile ( dirs . relative ( "" ) ) ; oddjob . setProperties ( properties ) ; oddjob . load ( ) ; ExecJob exec = new OddjobLookup ( oddjob ) . lookup ( "" , ExecJob . class ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( exec . consoleLog ( ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } public void testWithRedirectToFileExample ( ) throws ArooaPropertyException , ArooaConversionException , IOException { OurDirs dirs = new OurDirs ( ) ; File runJar = dirs . relative ( "" ) ; File workDir = dirs . relative ( "" ) ; File output = new File ( workDir , "" ) ; if ( output . exists ( ) ) { output . delete ( ) ; } Properties properties = new Properties ( ) ; properties . put ( "" , runJar . getCanonicalPath ( ) ) ; properties . put ( "" , workDir . getCanonicalPath ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setFile ( dirs . relative ( "" ) ) ; oddjob . setProperties ( properties ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } private class Results extends AppenderSkeleton { List < Object > info = new ArrayList < Object > ( ) ; List < Object > warn = new ArrayList < Object > ( ) ; @ Override protected void append ( LoggingEvent arg0 ) { if ( arg0 . getLevel ( ) . equals ( Level . INFO ) ) { info . add ( arg0 . getMessage ( ) ) ; } if ( arg0 . getLevel ( ) . equals ( Level . WARN ) ) { warn . add ( arg0 . getMessage ( ) ) ; } } @ Override public void close ( ) { } @ Override public boolean requiresLayout ( ) { return false ; } } public void testWithRedirectToLogExample ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; File runJar = dirs . relative ( "" ) ; Properties properties = new Properties ( ) ; properties . put ( "" , runJar . getCanonicalPath ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setProperties ( properties ) ; Results results = new Results ( ) ; Logger logger = Logger . getLogger ( LogoutType . class ) ; ; logger . addAppender ( results ) ; oddjob . run ( ) ; assertEquals ( ParentState . INCOMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( results . info . size ( ) == ) ; assertTrue ( results . warn . size ( ) > ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . IOException ; import java . text . ParseException ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConverterHelper ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . utils . ArooaTokenizer ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . BufferType ; import org . oddjob . io . FilesType ; import org . oddjob . logging . ConsoleOwner ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . structural . ChildHelper ; public class ExecJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( ExecJobTest . class ) ; String catCmd ; String echoCmd ; String [ ] setFruitCmd ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; if ( System . getProperty ( "" ) . startsWith ( "" ) ) { catCmd = "" ; echoCmd = "" ; setFruitCmd = new String [ ] { "" , "" , "" , "" } ; } else { catCmd = "" ; echoCmd = "" ; setFruitCmd = new String [ ] { "" , "" , "" , "" } ; } } public void testCreate ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Object [ ] children = ChildHelper . getChildren ( oj ) ; assertNotNull ( "" , children [ ] ) ; assertEquals ( "" , JobState . COMPLETE , Helper . getJobState ( ( Stateful ) children [ ] ) ) ; } public void testCommand ( ) { ExecJob job = new ExecJob ( ) ; job . setCommand ( "" ) ; job . run ( ) ; assertEquals ( "" , JobState . COMPLETE , job . lastStateEvent ( ) . getState ( ) ) ; } public void testStop ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; BufferType buf = new BufferType ( ) ; buf . configured ( ) ; final ExecJob job = new ExecJob ( ) ; ArooaConverter converter = new ConverterHelper ( ) . getConverter ( ) ; FilesType files = new FilesType ( ) ; files . setFiles ( new File ( dirs . base ( ) , "" ) . toString ( ) ) ; File [ ] cpFiles = files . toFiles ( ) ; String classPath = converter . convert ( cpFiles , String . class ) ; job . setCommand ( "" + classPath + "" + dirs . relative ( "" ) . getPath ( ) + "" ) ; job . setStdout ( buf . toOutputStream ( ) ) ; job . setRedirectStderr ( true ) ; Thread t = new Thread ( new Runnable ( ) { public void run ( ) { try { job . run ( ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; fail ( ) ; } } } ) ; t . start ( ) ; String [ ] lines = null ; for ( int i = ; i < ; ++ i ) { lines = buf . getLines ( ) ; if ( lines . length > ) { break ; } else { Thread . sleep ( ) ; } } job . stop ( ) ; t . join ( ) ; logger . debug ( "" + buf . getText ( ) ) ; assertEquals ( , lines . length ) ; assertEquals ( JobState . INCOMPLETE , job . lastStateEvent ( ) . getState ( ) ) ; } public void testFailure ( ) { ExecJob job = new ExecJob ( ) ; job . setCommand ( "" ) ; job . run ( ) ; assertEquals ( JobState . INCOMPLETE , job . lastStateEvent ( ) . getState ( ) ) ; } public void testOutput ( ) throws IOException { ExecJob ej = new ExecJob ( ) ; ej . setCommand ( echoCmd + "" ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; ej . setStdout ( os ) ; ej . run ( ) ; byte [ ] bytes = os . toByteArray ( ) ; assertEquals ( "" + System . getProperty ( "" ) , new String ( bytes ) ) ; } public void testConsole1 ( ) throws IOException { ExecJob ej = new ExecJob ( ) ; ej . setCommand ( echoCmd + "" ) ; ej . run ( ) ; LL ll = new LL ( ) ; ej . consoleLog ( ) . addListener ( ll , LogLevel . DEBUG , - , ) ; String result = ll . getLines ( ) [ ] ; logger . debug ( result ) ; assertEquals ( "" + System . getProperty ( "" ) , result ) ; } public void testChained ( ) throws IOException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + echoCmd + "" + "" + "" + "" + "" + "" + catCmd + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; ConsoleOwner ca = ( ConsoleOwner ) new OddjobLookup ( oj ) . lookup ( "" ) ; LL ll = new LL ( ) ; ca . consoleLog ( ) . addListener ( ll , LogLevel . DEBUG , - , ) ; String result = ll . getLines ( ) [ ] ; System . out . println ( result ) ; assertEquals ( "" + System . getProperty ( "" ) , result ) ; } class LL implements LogListener { List < String > list = new ArrayList < String > ( ) ; public void logEvent ( LogEvent logEvent ) { list . add ( logEvent . getMessage ( ) ) ; } String [ ] getLines ( ) { return ( String [ ] ) list . toArray ( new String [ ] ) ; } } public void testEnvironment ( ) throws IOException , InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder ( setFruitCmd ) ; Process process = processBuilder . start ( ) ; int returned = process . waitFor ( ) ; assertEquals ( , returned ) ; Map < String , String > env = processBuilder . environment ( ) ; assertNull ( env . get ( "" ) ) ; } public void testSplitCommand ( ) throws ParseException { ArooaTokenizer tokenizer = new ExecJob ( ) . commandTokenizer ( ) ; String [ ] result ; result = tokenizer . parse ( "" ) ; assertArray ( new String [ ] { "" , "" } , result ) ; result = tokenizer . parse ( "" ) ; assertArray ( new String [ ] { "" , "" } , result ) ; result = tokenizer . parse ( "" ) ; assertArray ( new String [ ] { "" } , result ) ; result = tokenizer . parse ( "" ) ; assertArray ( new String [ ] { "" , "" } , result ) ; } private void assertArray ( String [ ] expected , String [ ] result ) { if ( expected . length != result . length ) { throw new RuntimeException ( "" + expected . length + "" + result . length ) ; } for ( int i = ; i < expected . length ; ++ i ) { if ( ! expected [ i ] . equals ( result [ i ] ) ) { throw new RuntimeException ( "" + expected [ i ] + "" + result [ i ] ) ; } } } public void testEnvironmentInOddjob ( ) throws Exception { String envCommand ; String os = System . getProperty ( "" ) . toLowerCase ( ) ; if ( os . matches ( "" ) ) { envCommand = "" ; } else { envCommand = "" ; } String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + envCommand + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; String output = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; logger . debug ( output ) ; assertTrue ( output . contains ( "" ) ) ; } public void testSerialize ( ) throws IOException , ClassNotFoundException { ExecJob test = new ExecJob ( ) ; test . setCommand ( "" ) ; ExecJob copy = Helper . copy ( test ) ; assertNotNull ( copy ) ; } } package org . oddjob . jobs ; import java . io . ByteArrayOutputStream ; import java . util . Arrays ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . reflect . BeanView ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class BeanReportTest extends TestCase { public static class Fruit { private String type ; private String variety ; private String colour ; private double size ; public String getType ( ) { return type ; } public void setType ( String type ) { this . type = type ; } public String getVariety ( ) { return variety ; } public void setVariety ( String variety ) { this . variety = variety ; } public String getColour ( ) { return colour ; } public void setColour ( String colour ) { this . colour = colour ; } public double getSize ( ) { return size ; } public void setSize ( double size ) { this . size = size ; } } private class OurView implements BeanView { @ Override public String titleFor ( String property ) { if ( "" . equals ( property ) ) { return "" ; } return property ; } @ Override public String [ ] getProperties ( ) { return new String [ ] { "" , "" , "" , "" } ; } } String EOL = System . getProperty ( "" ) ; private Object [ ] createFruit ( ) { Fruit fruit1 = new Fruit ( ) ; fruit1 . setType ( "" ) ; fruit1 . setVariety ( "" ) ; fruit1 . setColour ( "" ) ; fruit1 . setSize ( ) ; Fruit fruit2 = new Fruit ( ) ; fruit2 . setType ( "" ) ; fruit2 . setVariety ( "" ) ; fruit2 . setColour ( "" ) ; fruit2 . setSize ( ) ; return new Object [ ] { fruit1 , fruit2 } ; } public void testFruitReport ( ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Object [ ] values = createFruit ( ) ; BeanReportJob test = new BeanReportJob ( ) ; test . setOutput ( out ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setBeans ( Arrays . asList ( values ) ) ; test . setBeanView ( new OurView ( ) ) ; test . run ( ) ; String expected = "" + EOL + "" + EOL + "" + EOL + "" + EOL ; assertEquals ( expected , out . toString ( ) ) ; } public void testInOddjob ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; String expected = "" + EOL + "" + EOL + "" + EOL + "" + EOL ; String results = new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ; assertEquals ( expected , results ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class EchoJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( EchoJobTest . class ) ; public void testInOddjob1 ( ) throws Exception { String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Object test = new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( test ) ) ; assertEquals ( "" , PropertyUtils . getProperty ( test , "" ) ) ; } public void testInOddjob2 ( ) throws Exception { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; Object test = new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( test ) ) ; assertEquals ( "" , PropertyUtils . getProperty ( test , "" ) ) ; } public void testLines ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . getPath ( ) } ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } public void testExample1 ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } public void testExample2 ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs ; import java . io . File ; import java . io . IOException ; import java . util . Date ; import java . util . Map ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . framework . RunnableProxyGenerator ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class SequenceJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( SequenceJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; } public void testSerialize ( ) throws Exception { SequenceJob test = new SequenceJob ( ) ; test . setFrom ( ) ; test . run ( ) ; assertEquals ( new Integer ( ) , test . getCurrent ( ) ) ; SequenceJob copy = ( SequenceJob ) Helper . copy ( test ) ; assertEquals ( new Integer ( ) , copy . getCurrent ( ) ) ; } public void testSerializedByWrapper ( ) throws Exception { SequenceJob test = new SequenceJob ( ) ; test . setFrom ( ) ; Runnable proxy = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) test , getClass ( ) . getClassLoader ( ) ) ; proxy . run ( ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( proxy ) ) ; Object copy = Helper . copy ( proxy ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( copy ) ) ; } public void testDescribe ( ) { SequenceJob test = new SequenceJob ( ) ; test . run ( ) ; Map < String , String > m = new UniversalDescriber ( new StandardArooaSession ( ) ) . describe ( test ) ; String current = ( String ) m . get ( "" ) ; assertEquals ( "" , current ) ; } public void testSequenceExample ( ) throws IOException , ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException { OurDirs dirs = new OurDirs ( ) ; File workDir = dirs . relative ( "" ) ; if ( workDir . exists ( ) ) { FileUtils . forceDelete ( workDir ) ; } workDir . mkdir ( ) ; Properties properties = new Properties ( ) ; properties . setProperty ( "" , workDir . getPath ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setProperties ( properties ) ; oddjob . run ( ) ; Date now = new Date ( new Date ( ) . getTime ( ) + ) ; while ( true ) { Date next = ( Date ) new OddjobLookup ( oddjob ) . lookup ( "" , Date . class ) ; if ( next . after ( now ) ) { break ; } logger . info ( "" ) ; Thread . sleep ( ) ; } oddjob . stop ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( new File ( workDir , "" ) . exists ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs ; import junit . framework . TestCase ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class JobStateTest extends TestCase { JobState jobState ; String iconId ; StateListener stateListener = new StateListener ( ) { public void jobStateChange ( StateEvent event ) { JobStateTest . this . jobState = ( JobState ) event . getState ( ) ; } } ; IconListener iconListener = new IconListener ( ) { public void iconEvent ( IconEvent event ) { JobStateTest . this . iconId = event . getIconId ( ) ; } } ; public void testException ( ) { final FlagState j = new FlagState ( ) ; j . setName ( "" ) ; j . setState ( JobState . EXCEPTION ) ; j . addStateListener ( stateListener ) ; j . addIconListener ( iconListener ) ; assertTrue ( "" , jobState == JobState . READY ) ; j . run ( ) ; assertTrue ( "" , jobState == JobState . EXCEPTION ) ; assertTrue ( "" , iconId . equals ( IconHelper . EXCEPTION ) ) ; } public void testNotComplete ( ) { final FlagState j = new FlagState ( ) ; j . setName ( "" ) ; j . setState ( JobState . INCOMPLETE ) ; j . addStateListener ( stateListener ) ; j . addIconListener ( iconListener ) ; assertTrue ( "" , jobState == JobState . READY ) ; j . run ( ) ; assertTrue ( "" , jobState == JobState . INCOMPLETE ) ; assertTrue ( "" , iconId . equals ( IconHelper . NOT_COMPLETE ) ) ; } public void testComplete ( ) { final FlagState j = new FlagState ( ) ; j . setName ( "" ) ; j . setState ( JobState . COMPLETE ) ; j . addStateListener ( stateListener ) ; j . addIconListener ( iconListener ) ; assertTrue ( "" , jobState == JobState . READY ) ; j . run ( ) ; assertTrue ( "" , jobState == JobState . COMPLETE ) ; assertTrue ( "" , iconId . equals ( IconHelper . COMPLETE ) ) ; } } package org . oddjob . jobs . job ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class StartJobTest extends TestCase { public static class OurRunnable implements Runnable { boolean ran ; public void run ( ) { ran = true ; } public boolean isRan ( ) { return ran ; } } public void testCode ( ) { OurRunnable r = new OurRunnable ( ) ; StartJob j = new StartJob ( ) ; j . setJob ( r ) ; j . run ( ) ; assertEquals ( JobState . COMPLETE , j . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( r . ran ) ; } public void testInOddjob ( ) throws Exception { String xml = "" + "" + "" + "" + "" + OurRunnable . class . getName ( ) + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Object r = new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( new Boolean ( true ) , PropertyUtils . getProperty ( r , "" ) ) ; } public void testExample ( ) { Properties properties = new Properties ( ) ; properties . setProperty ( "" , "" ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setProperties ( properties ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( lookup . lookup ( "" ) , lookup . lookup ( "" ) ) ; } } package org . oddjob . jobs . job ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . Stoppable ; import org . oddjob . state . JobState ; public class StopJobTest extends TestCase { private class MyStoppable implements Stoppable { boolean stopped ; @ Override public void stop ( ) throws FailedToStopException { this . stopped = true ; } } public void testSimpleStop ( ) { MyStoppable stoppable = new MyStoppable ( ) ; StopJob test = new StopJob ( ) ; test . setJob ( stoppable ) ; test . run ( ) ; assertEquals ( true , stoppable . stopped ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testLoopbackStop ( ) { StopJob test = new StopJob ( ) ; test . setJob ( test ) ; test . run ( ) ; assertEquals ( JobState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( FailedToStopException . class , test . lastStateEvent ( ) . getException ( ) . getClass ( ) ) ; } } package org . oddjob . jobs . job ; import java . beans . PropertyVetoException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . IconSteps ; import org . oddjob . Iconic ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . images . IconHelper ; import org . oddjob . jobs . WaitJob ; import org . oddjob . jobs . structural . SequentialJob ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateHandler ; import org . oddjob . state . StateListener ; import org . oddjob . util . OddjobLockedException ; public class RunJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( RunJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public static class OurRunnable implements Runnable { int ran ; public void run ( ) { ++ ran ; } public int getRan ( ) { return ran ; } } public void testCode ( ) { StandardArooaSession session = new StandardArooaSession ( ) ; OurRunnable r = new OurRunnable ( ) ; RunJob test = new RunJob ( ) ; test . setArooaSession ( session ) ; test . setJob ( r ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , r . ran ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , r . ran ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; Object proxy = children [ ] ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) proxy ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Resetable ) proxy ) . hardReset ( ) ; assertEquals ( JobState . READY , ( ( Stateful ) proxy ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Runnable ) proxy ) . run ( ) ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) proxy ) . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , r . ran ) ; } public void testInOddjob ( ) throws Exception { String xml = "" + "" + "" + "" + "" + OurRunnable . class . getName ( ) + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( , lookup . lookup ( "" ) ) ; RunJob test = lookup . lookup ( "" , RunJob . class ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( , lookup . lookup ( "" ) ) ; oddjob . destroy ( ) ; } public void testDestroyAfterRunning ( ) throws InterruptedException , ArooaPropertyException , ArooaConversionException , ArooaParseException , FailedToStopException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Iconic wait = lookup . lookup ( "" , Iconic . class ) ; IconSteps icons = new IconSteps ( wait ) ; icons . startCheck ( "" , "" , "" ) ; Thread t = new Thread ( oddjob ) ; t . start ( ) ; icons . checkWait ( ) ; ( ( Stoppable ) wait ) . stop ( ) ; t . join ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; logger . info ( "" ) ; DragPoint dp = oddjob . provideConfigurationSession ( ) . dragPointFor ( lookup . lookup ( "" ) ) ; DragTransaction trn = dp . beginChange ( ChangeHow . FRESH ) ; dp . cut ( ) ; trn . commit ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; logger . info ( "" ) ; oddjob . destroy ( ) ; } private class MyStateful implements Stateful , Runnable { StateHandler < ServiceState > states = new StateHandler < ServiceState > ( this , ServiceState . READY ) ; void fireJobState ( final ServiceState state ) { try { states . tryToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { states . setState ( state ) ; states . fireEvent ( ) ; } } ) ; } catch ( OddjobLockedException e ) { fail ( e . getMessage ( ) ) ; } } @ Override public void addStateListener ( StateListener listener ) { states . addStateListener ( listener ) ; } @ Override public void removeStateListener ( StateListener listener ) { states . removeStateListener ( listener ) ; } @ Override public StateEvent lastStateEvent ( ) { throw new RuntimeException ( "" ) ; } @ Override public void run ( ) { fireJobState ( ServiceState . STARTING ) ; } } public void testDestroyedWhileActive ( ) throws InterruptedException { MyStateful job = new MyStateful ( ) ; RunJob test = new RunJob ( ) ; test . setJob ( job ) ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . SLEEPING ) ; StateSteps states = new StateSteps ( test ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; Thread t = new Thread ( test ) ; t . start ( ) ; icons . checkWait ( ) ; icons . startCheck ( IconHelper . SLEEPING , IconHelper . EXECUTING , IconHelper . ACTIVE ) ; job . fireJobState ( ServiceState . STARTED ) ; icons . checkWait ( ) ; t . join ( ) ; states . checkNow ( ) ; states . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; job . fireJobState ( ServiceState . DESTROYED ) ; states . checkNow ( ) ; } private class MyStateful2 extends MyStateful { @ Override public void run ( ) { fireJobState ( ServiceState . STARTING ) ; fireJobState ( ServiceState . DESTROYED ) ; } } public void testDestroyedWhileExecuting ( ) throws InterruptedException { MyStateful2 job = new MyStateful2 ( ) ; RunJob test = new RunJob ( ) ; test . setJob ( job ) ; StateSteps states = new StateSteps ( test ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . EXCEPTION ) ; test . run ( ) ; states . checkNow ( ) ; } public void testRunRemoteJob ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException , PropertyVetoException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Iconic test = lookup . lookup ( "" , Iconic . class ) ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( "" , "" , "" ) ; StateSteps states = new StateSteps ( oddjob ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; Thread t = new Thread ( oddjob ) ; t . start ( ) ; icons . checkWait ( ) ; logger . info ( "" ) ; Stoppable wait = lookup . lookup ( "" , Stoppable . class ) ; wait . stop ( ) ; t . join ( ) ; states . checkNow ( ) ; states . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; logger . info ( "" ) ; oddjob . stop ( ) ; states . checkNow ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; logger . info ( "" ) ; oddjob . destroy ( ) ; } public void testStopAndReset ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; WaitJob wait1 = lookup . lookup ( "" , WaitJob . class ) ; IconSteps icons1 = new IconSteps ( wait1 ) ; icons1 . startCheck ( "" , "" , "" ) ; Thread t = new Thread ( oddjob ) ; t . start ( ) ; icons1 . checkWait ( ) ; icons1 . startCheck ( "" , "" , "" ) ; RunJob test = lookup . lookup ( "" , RunJob . class ) ; test . stop ( ) ; t . join ( ) ; icons1 . checkNow ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; WaitJob wait2 = lookup . lookup ( "" , WaitJob . class ) ; IconSteps icons2 = new IconSteps ( wait2 ) ; icons2 . startCheck ( "" , "" , "" ) ; t = new Thread ( test ) ; t . start ( ) ; icons2 . checkWait ( ) ; icons2 . startCheck ( "" , "" , "" ) ; wait2 . stop ( ) ; t . join ( ) ; icons2 . checkNow ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; SequentialJob sequential = lookup . lookup ( "" , SequentialJob . class ) ; assertEquals ( ParentState . COMPLETE , sequential . lastStateEvent ( ) . getState ( ) ) ; logger . info ( "" ) ; oddjob . destroy ( ) ; } } package org . oddjob . jobs . job ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . MockStateful ; import org . oddjob . framework . SimpleJob ; import org . oddjob . state . JobState ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateListener ; import org . oddjob . state . State ; import org . oddjob . state . StateCondition ; public class DependsJobTest extends TestCase { class TestJob extends SimpleJob { boolean ran ; public int execute ( ) { ran = true ; return ; } } public void testReady ( ) { TestJob testJob = new TestJob ( ) ; DependsJob j = new DependsJob ( ) ; j . setJob ( testJob ) ; j . run ( ) ; assertTrue ( testJob . ran ) ; assertEquals ( "" , JobState . COMPLETE , Helper . getJobState ( j ) ) ; } public void testAlreadyComplete ( ) { TestJob testJob = new TestJob ( ) ; testJob . run ( ) ; testJob . ran = false ; assertEquals ( JobState . COMPLETE , testJob . lastStateEvent ( ) . getState ( ) ) ; DependsJob j = new DependsJob ( ) ; j . setJob ( testJob ) ; j . run ( ) ; assertFalse ( testJob . ran ) ; assertEquals ( "" , JobState . COMPLETE , Helper . getJobState ( j ) ) ; } private void setState ( final JobStateHandler handler , final JobState state ) { boolean ran = handler . waitToWhen ( new StateCondition ( ) { public boolean test ( State state ) { return true ; } } , new Runnable ( ) { public void run ( ) { handler . setState ( state ) ; handler . fireEvent ( ) ; } } ) ; assertTrue ( ran ) ; } public void testExecuting ( ) throws InterruptedException { class Executing extends MockStateful { JobStateHandler h = new JobStateHandler ( this ) ; public void addStateListener ( StateListener listener ) { h . addStateListener ( listener ) ; } public void removeStateListener ( StateListener listener ) { h . removeStateListener ( listener ) ; } } Executing testJob = new Executing ( ) ; setState ( testJob . h , JobState . EXECUTING ) ; DependsJob j = new DependsJob ( ) ; j . setJob ( testJob ) ; Thread t = new Thread ( j ) ; t . start ( ) ; while ( JobState . EXECUTING != Helper . getJobState ( j ) ) { Thread . yield ( ) ; } setState ( testJob . h , JobState . INCOMPLETE ) ; t . join ( ) ; assertEquals ( JobState . INCOMPLETE , Helper . getJobState ( j ) ) ; } } package org . oddjob ; import javax . swing . ImageIcon ; import org . oddjob . images . IconListener ; public class MockIconic implements Iconic { public ImageIcon iconForId ( String id ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void addIconListener ( IconListener listener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeIconListener ( IconListener listener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class StructuralStateConverterTest extends TestCase { public void testConvert ( ) { ParentStateConverter test = new ParentStateConverter ( ) ; assertEquals ( ParentState . READY , test . toStructuralState ( JobState . READY ) ) ; assertEquals ( ParentState . ACTIVE , test . toStructuralState ( JobState . EXECUTING ) ) ; assertEquals ( ParentState . COMPLETE , test . toStructuralState ( JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . toStructuralState ( JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . toStructuralState ( JobState . EXCEPTION ) ) ; assertEquals ( ParentState . DESTROYED , test . toStructuralState ( JobState . DESTROYED ) ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class ResetsTest extends TestCase { public void testReverse ( ) { Resets test = new Resets ( ) ; test . setSoften ( true ) ; test . setHarden ( true ) ; FlagState job = new FlagState ( JobState . COMPLETE ) ; test . setJob ( job ) ; test . run ( ) ; test . hardReset ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . softReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNormal ( ) { Resets test = new Resets ( ) ; test . setSoften ( false ) ; test . setHarden ( false ) ; FlagState job = new FlagState ( JobState . COMPLETE ) ; test . setJob ( job ) ; test . run ( ) ; test . softReset ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . state ; import java . util . concurrent . atomic . AtomicBoolean ; import junit . framework . TestCase ; import org . oddjob . MockStateful ; import org . oddjob . util . OddjobLockedException ; public class StateSupportLockTest extends TestCase { class IsLocked implements Runnable { boolean locked ; final JobStateHandler state ; IsLocked ( JobStateHandler state ) { this . state = state ; } public void run ( ) { try { boolean condition = state . tryToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { } } ) ; assertTrue ( condition ) ; locked = false ; } catch ( OddjobLockedException e ) { locked = true ; } } } public void testAsIfExecuting ( ) throws InterruptedException { final JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; final IsLocked check = new IsLocked ( test ) ; boolean succeeded = test . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { Thread t ; t = new Thread ( check ) ; t . start ( ) ; try { t . join ( ) ; } catch ( InterruptedException e ) { fail ( "" ) ; } assertTrue ( check . locked ) ; test . setState ( JobState . COMPLETE ) ; test . fireEvent ( ) ; } } ) ; assertTrue ( succeeded ) ; Thread t = new Thread ( check ) ; t . start ( ) ; t . join ( ) ; assertFalse ( check . locked ) ; assertEquals ( JobState . COMPLETE , test . getState ( ) ) ; } public void testWaitFor ( ) throws InterruptedException { final JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; final IsLocked check = new IsLocked ( test ) ; boolean succeeded = test . waitToWhen ( new IsExecutable ( ) , new Runnable ( ) { public void run ( ) { Thread t ; t = new Thread ( check ) ; t . start ( ) ; try { t . join ( ) ; } catch ( InterruptedException e ) { fail ( "" ) ; } assertTrue ( check . locked ) ; test . setState ( JobState . COMPLETE ) ; test . fireEvent ( ) ; } } ) ; assertTrue ( succeeded ) ; Thread t = new Thread ( check ) ; t . start ( ) ; t . join ( ) ; assertFalse ( check . locked ) ; assertEquals ( JobState . COMPLETE , test . getState ( ) ) ; } public void testInturruptedFlag ( ) { JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; Thread . currentThread ( ) . interrupt ( ) ; final AtomicBoolean ran = new AtomicBoolean ( ) ; test . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { ran . set ( true ) ; } } ) ; assertTrue ( ran . get ( ) ) ; assertTrue ( Thread . interrupted ( ) ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . MockStateful ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . scheduling . DefaultExecutors ; public class MirrorStateTest extends TestCase { private static final Logger logger = Logger . getLogger ( MirrorStateTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; } private class Result implements StateListener { JobState result ; public void jobStateChange ( StateEvent event ) { result = ( JobState ) event . getState ( ) ; } } private class Icon implements IconListener { String iconId ; public void iconEvent ( IconEvent e ) { iconId = e . getIconId ( ) ; } } public void testComplete ( ) { MirrorState test = new MirrorState ( ) ; Result listener = new Result ( ) ; Icon icon = new Icon ( ) ; test . addStateListener ( listener ) ; test . addIconListener ( icon ) ; assertEquals ( JobState . READY , listener . result ) ; assertEquals ( IconHelper . READY , icon . iconId ) ; FlagState job = new FlagState ( JobState . COMPLETE ) ; test . setJob ( job ) ; assertEquals ( JobState . READY , listener . result ) ; test . run ( ) ; assertEquals ( JobState . READY , listener . result ) ; job . run ( ) ; assertEquals ( JobState . COMPLETE , listener . result ) ; assertEquals ( IconHelper . COMPLETE , icon . iconId ) ; test . stop ( ) ; job . hardReset ( ) ; assertEquals ( JobState . READY , job . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , listener . result ) ; test . hardReset ( ) ; test . setJob ( job ) ; test . run ( ) ; assertEquals ( JobState . READY , listener . result ) ; } public void testReset ( ) { MirrorState test = new MirrorState ( ) ; FlagState job = new FlagState ( JobState . COMPLETE ) ; test . setJob ( job ) ; job . run ( ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . softReset ( ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . setJob ( job ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . stop ( ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } private class ExecutingThing extends MockStateful { StateListener listener ; @ Override public void addStateListener ( StateListener listener ) { assertNull ( this . listener ) ; assertNotNull ( listener ) ; this . listener = listener ; } @ Override public void removeStateListener ( StateListener listener ) { assertNotNull ( this . listener ) ; assertEquals ( listener , this . listener ) ; this . listener = null ; } } public void testStop ( ) { MirrorState test = new MirrorState ( ) ; ExecutingThing job = new ExecutingThing ( ) ; test . setJob ( job ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; job . listener . jobStateChange ( new StateEvent ( job , JobState . EXECUTING ) ) ; assertEquals ( JobState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; test . stop ( ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; assertNull ( job . listener ) ; } private class OurStateful extends MockStateful { JobStateHandler state = new JobStateHandler ( this ) ; public void addStateListener ( StateListener listener ) { state . addStateListener ( listener ) ; } public void removeStateListener ( StateListener listener ) { state . removeStateListener ( listener ) ; } void startRunning ( ) { state . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { state . setState ( JobState . EXECUTING ) ; state . fireEvent ( ) ; } } ) ; } void destroy ( ) { state . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { state . setState ( JobState . DESTROYED ) ; state . fireEvent ( ) ; } } ) ; } } public void testDestroyed ( ) { MirrorState test = new MirrorState ( ) ; OurStateful job = new OurStateful ( ) ; test . setJob ( job ) ; test . run ( ) ; job . destroy ( ) ; assertEquals ( JobState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; } public void testInOddjob ( ) throws InterruptedException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; state . checkWait ( ) ; oddjob . destroy ( ) ; } public void testMirroredJobCut ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; DefaultExecutors services = new DefaultExecutors ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setOddjobExecutors ( services ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; Object on = new OddjobLookup ( oddjob ) . lookup ( "" ) ; DragPoint drag = oddjob . provideConfigurationSession ( ) . dragPointFor ( on ) ; DragTransaction trn = drag . beginChange ( ChangeHow . FRESH ) ; drag . cut ( ) ; try { trn . commit ( ) ; } catch ( ArooaParseException e ) { trn . rollback ( ) ; throw e ; } assertEquals ( ParentState . EXCEPTION , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; services . stop ( ) ; assertEquals ( ParentState . DESTROYED , oddjob . lastStateEvent ( ) . getState ( ) ) ; } public void testStopWhenRunning ( ) { OurStateful running = new OurStateful ( ) ; running . startRunning ( ) ; MirrorState test = new MirrorState ( ) ; test . setJob ( running ) ; test . run ( ) ; assertEquals ( JobState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; test . stop ( ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testStopWhenRunningInOddjob ( ) { OurStateful running = new OurStateful ( ) ; running . startRunning ( ) ; String xml = "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setExport ( "" , new ArooaObject ( running ) ) ; StateSteps steps = new StateSteps ( oddjob ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; oddjob . run ( ) ; steps . checkNow ( ) ; steps . startCheck ( ParentState . ACTIVE , ParentState . READY , ParentState . DESTROYED ) ; oddjob . destroy ( ) ; steps . checkNow ( ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class IsContineableTest extends TestCase { public void testAllStates ( ) { IsContinueable test = new IsContinueable ( ) ; assertTrue ( test . test ( JobState . READY ) ) ; assertTrue ( test . test ( JobState . EXECUTING ) ) ; assertTrue ( test . test ( JobState . COMPLETE ) ) ; assertFalse ( test . test ( JobState . INCOMPLETE ) ) ; assertFalse ( test . test ( JobState . EXCEPTION ) ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class FlagStateTest extends TestCase { public void testSettingStateDestoyed ( ) { FlagState test = new FlagState ( ) ; test . setState ( JobState . DESTROYED ) ; test . run ( ) ; assertEquals ( JobState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class WorstStateOpTest extends TestCase { public void testEvaluateSingleOp ( ) { WorstStateOp test = new WorstStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . READY ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE ) ) ; } public void testEvaluateTwoOps ( ) { WorstStateOp test = new WorstStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . READY , JobState . READY ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . READY , JobState . EXECUTING ) ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . READY , JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . READY , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . READY , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING , JobState . READY ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING , JobState . EXECUTING ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING , JobState . COMPLETE ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE , JobState . READY ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . INCOMPLETE , JobState . EXECUTING ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE , JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . INCOMPLETE , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . COMPLETE , JobState . READY ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . COMPLETE , JobState . EXECUTING ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE , JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . COMPLETE , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . COMPLETE , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . READY ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXCEPTION , JobState . EXECUTING ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . EXCEPTION ) ) ; } public void testDestroyed ( ) { WorstStateOp test = new WorstStateOp ( ) ; try { assertEquals ( JobState . DESTROYED , test . evaluate ( JobState . DESTROYED , JobState . DESTROYED ) ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } } } package org . oddjob . state ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . ObjectInput ; import java . io . ObjectInputStream ; import java . io . ObjectOutput ; import java . io . ObjectOutputStream ; import java . util . Date ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . MockStateful ; import org . oddjob . OddjobException ; public class JobStateEventTest extends TestCase { private static final Logger logger = Logger . getLogger ( StateEvent . class ) ; String message = "" ; class NotSerializable { } class OurStateful extends MockStateful { public void addStateListener ( StateListener listener ) { throw new RuntimeException ( "" ) ; } public void removeStateListener ( StateListener listener ) { throw new RuntimeException ( "" ) ; } } class NotSerializableException extends Exception { private static final long serialVersionUID = ; public NotSerializableException ( ) { super ( message ) ; } NotSerializable ns = new NotSerializable ( ) ; } public void testSerialize1 ( ) throws IOException , ClassNotFoundException { OurStateful source = new OurStateful ( ) ; StateEvent event = new StateEvent ( source , JobState . EXCEPTION , new Date ( ) , new OddjobException ( message ) ) ; StateEvent event2 = ( StateEvent ) outAndBack ( event ) ; logger . debug ( event2 ) ; assertNull ( event2 . getSource ( ) ) ; assertEquals ( JobState . EXCEPTION , event2 . getState ( ) ) ; assertEquals ( , event2 . getTime ( ) . getTime ( ) ) ; assertEquals ( message , event2 . getException ( ) . getMessage ( ) ) ; } public void testSerialize2 ( ) throws IOException , ClassNotFoundException { OurStateful source = new OurStateful ( ) ; StateEvent event = new StateEvent ( source , JobState . EXCEPTION , new Date ( ) , new NotSerializableException ( ) ) ; StateEvent event2 = ( StateEvent ) outAndBack ( event ) ; logger . debug ( event2 ) ; logger . debug ( "" , event2 . getException ( ) ) ; assertNull ( event2 . getSource ( ) ) ; assertEquals ( JobState . EXCEPTION , event2 . getState ( ) ) ; assertEquals ( , event2 . getTime ( ) . getTime ( ) ) ; assertEquals ( StateEvent . REPLACEMENT_EXCEPTION_TEXT + message , event2 . getException ( ) . getMessage ( ) ) ; } public void testSerializeComplete ( ) throws IOException , ClassNotFoundException { OurStateful source = new OurStateful ( ) ; StateEvent event = new StateEvent ( source , JobState . COMPLETE , new Date ( ) , null ) ; StateEvent event2 = ( StateEvent ) outAndBack ( event ) ; logger . debug ( event2 ) ; assertNull ( event2 . getSource ( ) ) ; assertEquals ( JobState . COMPLETE , event2 . getState ( ) ) ; assertEquals ( , event2 . getTime ( ) . getTime ( ) ) ; assertEquals ( null , event2 . getException ( ) ) ; } Object outAndBack ( Object object ) throws IOException , ClassNotFoundException { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; ObjectOutput oo = new ObjectOutputStream ( os ) ; oo . writeObject ( object ) ; oo . close ( ) ; ByteArrayInputStream in = new ByteArrayInputStream ( os . toByteArray ( ) ) ; ObjectInput oi = new ObjectInputStream ( in ) ; Object o = oi . readObject ( ) ; return o ; } } package org . oddjob . state ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; public class JobStateConvertletProviderTest extends TestCase { public static class OurBean { JobState jobState ; @ ArooaAttribute public void setJobState ( JobState jobState ) { this . jobState = jobState ; } } public void testConversions ( ) throws ArooaParseException { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; OurBean bean = new OurBean ( ) ; StandardArooaParser parser = new StandardArooaParser ( bean , descriptor ) ; parser . parse ( new XMLConfiguration ( "" , "" ) ) ; assertEquals ( JobState . COMPLETE , bean . jobState ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class ServiceManagerStateOpTest extends TestCase { public void testEvaluateSingleOp ( ) { ServiceManagerStateOp test = new ServiceManagerStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . READY ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . EXECUTING ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE ) ) ; } public void testEvaluateSingleOpService ( ) { ServiceManagerStateOp test = new ServiceManagerStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( ServiceState . READY ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( ServiceState . STARTING ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( ServiceState . STARTED ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( ServiceState . EXCEPTION ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( ServiceState . COMPLETE ) ) ; } public void testEvaluateTwoOps ( ) { ServiceManagerStateOp test = new ServiceManagerStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . READY , JobState . READY ) ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . READY , JobState . EXECUTING ) ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . READY , JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . READY , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . READY , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . EXECUTING , JobState . READY ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . EXECUTING , JobState . EXECUTING ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . EXECUTING , JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . EXECUTING , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXECUTING , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE , JobState . READY ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE , JobState . EXECUTING ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE , JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . INCOMPLETE , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . COMPLETE , JobState . READY ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE , JobState . EXECUTING ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE , JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . COMPLETE , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . COMPLETE , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . READY ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . EXECUTING ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION , JobState . EXCEPTION ) ) ; } public void testEvaluateTwoOpsService ( ) { ServiceManagerStateOp test = new ServiceManagerStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( ServiceState . READY , ServiceState . READY ) ) ; assertEquals ( ParentState . READY , test . evaluate ( ServiceState . READY , ServiceState . STARTED ) ) ; assertEquals ( ParentState . READY , test . evaluate ( ServiceState . READY , ServiceState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( ServiceState . READY , ServiceState . EXCEPTION ) ) ; assertEquals ( ParentState . READY , test . evaluate ( ServiceState . STARTING , ServiceState . READY ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( ServiceState . STARTING , ServiceState . STARTED ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( ServiceState . STARTING , ServiceState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( ServiceState . STARTED , ServiceState . EXCEPTION ) ) ; assertEquals ( ParentState . READY , test . evaluate ( ServiceState . COMPLETE , ServiceState . READY ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( ServiceState . COMPLETE , ServiceState . STARTED ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( ServiceState . COMPLETE , ServiceState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( ServiceState . COMPLETE , ServiceState . EXCEPTION ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( ServiceState . EXCEPTION , ServiceState . READY ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( ServiceState . EXCEPTION , ServiceState . STARTED ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( ServiceState . EXCEPTION , ServiceState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( ServiceState . EXCEPTION , ServiceState . EXCEPTION ) ) ; } public void testDestroyed ( ) { ServiceManagerStateOp test = new ServiceManagerStateOp ( ) ; try { assertEquals ( JobState . DESTROYED , test . evaluate ( JobState . DESTROYED , JobState . DESTROYED ) ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } } } package org . oddjob . state ; import junit . framework . TestCase ; import org . oddjob . MockStateful ; public class SequentialHelperTest extends TestCase { private class OurStateful extends MockStateful { private final JobState jobState ; public OurStateful ( JobState jobState ) { this . jobState = jobState ; } @ Override public StateEvent lastStateEvent ( ) { return new StateEvent ( this , jobState ) ; } } public void testAllStates ( ) { SequentialHelper test = new SequentialHelper ( ) ; OurStateful flag = new OurStateful ( JobState . READY ) ; assertTrue ( test . canContinueAfter ( flag ) ) ; assertTrue ( test . canContinueAfter ( new OurStateful ( JobState . EXECUTING ) ) ) ; assertTrue ( test . canContinueAfter ( new OurStateful ( JobState . COMPLETE ) ) ) ; assertFalse ( test . canContinueAfter ( new OurStateful ( JobState . INCOMPLETE ) ) ) ; assertFalse ( test . canContinueAfter ( new OurStateful ( JobState . EXCEPTION ) ) ) ; assertTrue ( test . canContinueAfter ( new Object ( ) ) ) ; } } package org . oddjob . state ; import java . io . File ; import java . io . IOException ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OurDirs ; import org . oddjob . StateSteps ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . jobs . WaitJob ; public class IfJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( IfJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testIfOnlyJobComplete ( ) { FlagState child = new FlagState ( ) ; child . setState ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , child ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testIfOnlyJobNotComplete ( ) { FlagState child = new FlagState ( ) ; child . setState ( JobState . INCOMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , child ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testIfOnlyJobException ( ) { FlagState child = new FlagState ( ) ; child . setState ( JobState . EXCEPTION ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , child ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } class OurJob extends SimpleJob { private JobState desired ; private int count ; protected int execute ( ) throws Exception { ++ count ; if ( desired . equals ( JobState . COMPLETE ) ) { return ; } if ( desired . equals ( JobState . INCOMPLETE ) ) { return ; } throw new Exception ( "" ) ; } public void setDesired ( JobState desired ) { this . desired = desired ; } } public void testThen1 ( ) throws IOException , ClassNotFoundException { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . COMPLETE ) ; depends . run ( ) ; OurJob then = new OurJob ( ) ; then . setDesired ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , then . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; IfJob copy = ( IfJob ) Helper . copy ( test ) ; copy . setJobs ( , depends ) ; copy . setJobs ( , then ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; copy . hardReset ( ) ; copy . run ( ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , then . count ) ; then . hardReset ( ) ; assertEquals ( ParentState . READY , copy . lastStateEvent ( ) . getState ( ) ) ; } public void testThen2 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . COMPLETE ) ; depends . run ( ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . INCOMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testThen3 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . COMPLETE ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . EXCEPTION ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( ParentState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; then . softReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , depends . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , then . lastStateEvent ( ) . getState ( ) ) ; depends . hardReset ( ) ; assertEquals ( JobState . READY , depends . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNotThen ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . COMPLETE ) ; depends . run ( ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . EXCEPTION ) ; IfJob test = new IfJob ( ) ; test . setState ( new IsNot ( StateConditions . COMPLETE ) ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , depends . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , then . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNotThen2 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . COMPLETE ) ; depends . run ( ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . EXCEPTION ) ; IfJob test = new IfJob ( ) ; test . setState ( StateConditions . INCOMPLETE ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , depends . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , then . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testElse1 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . INCOMPLETE ) ; depends . setName ( "" ) ; FlagState then = new FlagState ( JobState . EXCEPTION ) ; then . setName ( "" ) ; OurJob elze = new OurJob ( ) ; elze . setDesired ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . setJobs ( , elze ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; elze . setDesired ( JobState . INCOMPLETE ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , elze . count ) ; test . softReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , elze . lastStateEvent ( ) . getState ( ) ) ; } public void testElse2 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . INCOMPLETE ) ; depends . run ( ) ; FlagState then = new FlagState ( JobState . EXCEPTION ) ; then . setName ( "" ) ; FlagState elze = new FlagState ( ) ; elze . setState ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . setJobs ( , elze ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testElse3 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . EXCEPTION ) ; depends . run ( ) ; FlagState then = new FlagState ( JobState . COMPLETE ) ; then . setName ( "" ) ; FlagState elze = new FlagState ( ) ; elze . setState ( JobState . EXCEPTION ) ; IfJob test = new IfJob ( ) ; test . setState ( StateConditions . INCOMPLETE ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . setJobs ( , elze ) ; test . run ( ) ; assertEquals ( ParentState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNoElse ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . COMPLETE ) ; depends . run ( ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . EXCEPTION ) ; IfJob test = new IfJob ( ) ; test . setState ( StateConditions . INCOMPLETE ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testException1 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . EXCEPTION ) ; depends . run ( ) ; OurJob then = new OurJob ( ) ; then . setDesired ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setState ( StateConditions . EXCEPTION ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , then . count ) ; } public void testException2 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . EXCEPTION ) ; depends . run ( ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . INCOMPLETE ) ; IfJob test = new IfJob ( ) ; test . setState ( StateConditions . EXCEPTION ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testException3 ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . EXCEPTION ) ; depends . run ( ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . EXCEPTION ) ; IfJob test = new IfJob ( ) ; test . setState ( StateConditions . EXCEPTION ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( ParentState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNotException ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . INCOMPLETE ) ; depends . run ( ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . EXCEPTION ) ; IfJob test = new IfJob ( ) ; test . setState ( StateConditions . EXCEPTION ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNotExceptionWithElse ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . INCOMPLETE ) ; depends . run ( ) ; FlagState then = new FlagState ( ) ; then . setState ( JobState . EXCEPTION ) ; FlagState elze = new FlagState ( ) ; elze . setState ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setState ( StateConditions . EXCEPTION ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . setJobs ( , elze ) ; test . run ( ) ; assertEquals ( JobState . READY , then . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , elze . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testInOddjob ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , IfJobTest . class . getResourceAsStream ( "" ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testNotComplete ( ) throws IOException , ClassNotFoundException { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . INCOMPLETE ) ; OurJob then = new OurJob ( ) ; then . setDesired ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . setState ( new IsNot ( StateConditions . COMPLETE ) ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , then . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNotNotComplete ( ) throws IOException , ClassNotFoundException { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . COMPLETE ) ; OurJob then = new OurJob ( ) ; then . setDesired ( JobState . EXCEPTION ) ; StateSteps thenState = new StateSteps ( then ) ; thenState . startCheck ( JobState . READY ) ; IfJob test = new IfJob ( ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; test . setState ( new IsNot ( StateConditions . COMPLETE ) ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . run ( ) ; thenState . checkNow ( ) ; testState . checkNow ( ) ; } public void testNotInComplete ( ) throws IOException , ClassNotFoundException { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . INCOMPLETE ) ; depends . run ( ) ; OurJob then = new OurJob ( ) ; then . setDesired ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . setState ( new IsNot ( StateConditions . INCOMPLETE ) ) ; test . run ( ) ; assertEquals ( JobState . READY , then . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testReset ( ) { FlagState depends = new FlagState ( ) ; depends . setState ( JobState . COMPLETE ) ; depends . run ( ) ; OurJob then = new OurJob ( ) ; then . setDesired ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; test . hardReset ( ) ; assertEquals ( JobState . READY , then . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testStop ( ) throws IOException , ClassNotFoundException , FailedToStopException , InterruptedException { WaitJob depends = new WaitJob ( ) ; OurJob then = new OurJob ( ) ; then . setDesired ( JobState . COMPLETE ) ; IfJob test = new IfJob ( ) ; test . setJobs ( , depends ) ; test . setJobs ( , then ) ; StateSteps dependsState = new StateSteps ( depends ) ; dependsState . startCheck ( JobState . READY , JobState . EXECUTING ) ; Thread t = new Thread ( test ) ; t . start ( ) ; dependsState . checkWait ( ) ; test . stop ( ) ; t . join ( ) ; assertEquals ( JobState . READY , then . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testIfFileExists ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; File workDir = dirs . relative ( "" ) ; workDir . mkdir ( ) ; File theFile = new File ( workDir , "" ) ; if ( theFile . exists ( ) ) { FileUtils . forceDelete ( theFile ) ; } Properties properties = new Properties ( ) ; properties . setProperty ( "" , workDir . getPath ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setProperties ( properties ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , console . getLines ( ) . length ) ; oddjob . destroy ( ) ; } } package org . oddjob . state ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . CountDownLatch ; import java . util . concurrent . Exchanger ; import java . util . concurrent . atomic . AtomicBoolean ; import junit . framework . TestCase ; import org . oddjob . MockStateful ; import org . oddjob . Stateful ; public class JobStateHandlerTest extends TestCase { private void setState ( final JobStateHandler handler , final JobState state ) { boolean ran = handler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { handler . setState ( state ) ; handler . fireEvent ( ) ; } } ) ; assertTrue ( ran ) ; } private void setException ( final JobStateHandler handler , final Exception e ) { boolean ran = handler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { handler . setStateException ( JobState . EXCEPTION , e ) ; handler . fireEvent ( ) ; } } ) ; assertTrue ( ran ) ; } public void testAllStates ( ) { JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; assertEquals ( JobState . READY , test . getState ( ) ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; setState ( test , JobState . EXECUTING ) ; assertEquals ( JobState . EXECUTING , test . getState ( ) ) ; assertEquals ( JobState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; setState ( test , JobState . COMPLETE ) ; assertEquals ( JobState . COMPLETE , test . getState ( ) ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; setState ( test , JobState . INCOMPLETE ) ; assertEquals ( JobState . INCOMPLETE , test . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; setException ( test , new Exception ( ) ) ; assertEquals ( JobState . EXCEPTION , test . getState ( ) ) ; assertEquals ( JobState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; setState ( test , JobState . READY ) ; assertEquals ( JobState . READY , test . getState ( ) ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } private class RecordingStateListener implements StateListener { List < StateEvent > events = new ArrayList < StateEvent > ( ) ; public synchronized void jobStateChange ( StateEvent event ) { events . add ( event ) ; } } public void testListenersNotified ( ) { Stateful source = new MockStateful ( ) ; JobStateHandler test = new JobStateHandler ( source ) ; RecordingStateListener l = new RecordingStateListener ( ) ; test . addStateListener ( l ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . READY , l . events . get ( ) . getState ( ) ) ; assertEquals ( source , l . events . get ( ) . getSource ( ) ) ; setState ( test , JobState . EXECUTING ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . EXECUTING , l . events . get ( ) . getState ( ) ) ; setState ( test , JobState . COMPLETE ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . COMPLETE , l . events . get ( ) . getState ( ) ) ; setState ( test , JobState . INCOMPLETE ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . INCOMPLETE , l . events . get ( ) . getState ( ) ) ; Exception e = new Exception ( ) ; setException ( test , e ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . EXCEPTION , l . events . get ( ) . getState ( ) ) ; assertEquals ( e , l . events . get ( ) . getException ( ) ) ; setState ( test , JobState . READY ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . READY , l . events . get ( ) . getState ( ) ) ; setState ( test , JobState . DESTROYED ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . DESTROYED , l . events . get ( ) . getState ( ) ) ; } public void testDuplicateEventsNotified ( ) { Stateful source = new MockStateful ( ) ; JobStateHandler test = new JobStateHandler ( source ) ; RecordingStateListener l = new RecordingStateListener ( ) ; test . addStateListener ( l ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . READY , l . events . get ( ) . getState ( ) ) ; assertEquals ( source , l . events . get ( ) . getSource ( ) ) ; setState ( test , JobState . READY ) ; assertEquals ( , l . events . size ( ) ) ; setState ( test , JobState . EXECUTING ) ; assertEquals ( , l . events . size ( ) ) ; setState ( test , JobState . EXECUTING ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . EXECUTING , l . events . get ( ) . getState ( ) ) ; setState ( test , JobState . COMPLETE ) ; assertEquals ( , l . events . size ( ) ) ; assertEquals ( JobState . COMPLETE , l . events . get ( ) . getState ( ) ) ; } public void testManyListeners ( ) throws Exception { RecordingStateListener l1 = new RecordingStateListener ( ) ; RecordingStateListener l2 = new RecordingStateListener ( ) ; RecordingStateListener l3 = new RecordingStateListener ( ) ; final JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; Thread t = new Thread ( new Runnable ( ) { public void run ( ) { setState ( test , JobState . COMPLETE ) ; } } ) ; test . addStateListener ( l1 ) ; test . addStateListener ( l2 ) ; test . addStateListener ( l3 ) ; t . start ( ) ; t . join ( ) ; assertEquals ( , l1 . events . size ( ) ) ; assertEquals ( , l2 . events . size ( ) ) ; assertEquals ( , l3 . events . size ( ) ) ; assertEquals ( JobState . COMPLETE , l1 . events . get ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , l2 . events . get ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , l3 . events . get ( ) . getState ( ) ) ; } public void testListenerConcurrentModification ( ) { final JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; test . addStateListener ( new StateListener ( ) { public void jobStateChange ( StateEvent event ) { if ( event . getState ( ) == JobState . COMPLETE ) { test . removeStateListener ( this ) ; } } } ) ; assertEquals ( , test . listenerCount ( ) ) ; test . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { test . setState ( JobState . COMPLETE ) ; test . fireEvent ( ) ; } } ) ; assertEquals ( , test . listenerCount ( ) ) ; } public void testThatAttemptsToChangeState ( ) { final JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; StateListener listener = new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { test . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { test . setState ( JobState . COMPLETE ) ; test . fireEvent ( ) ; } } ) ; } } ; try { test . addStateListener ( listener ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } final AtomicBoolean failed = new AtomicBoolean ( ) ; StateListener listener2 = new StateListener ( ) { @ Override public void jobStateChange ( final StateEvent event ) { if ( JobState . INCOMPLETE == event . getState ( ) ) { try { test . setState ( JobState . COMPLETE ) ; test . fireEvent ( ) ; } catch ( IllegalStateException e ) { failed . set ( true ) ; } } } } ; test . addStateListener ( listener2 ) ; test . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { test . setState ( JobState . INCOMPLETE ) ; test . fireEvent ( ) ; } } ) ; assertTrue ( failed . get ( ) ) ; assertEquals ( JobState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testListenerNotificationOrder ( ) throws InterruptedException { final JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; final Exchanger < Void > exchanger = new Exchanger < Void > ( ) ; test . addStateListener ( new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { try { if ( event . getState ( ) == JobState . COMPLETE ) { exchanger . exchange ( null ) ; exchanger . exchange ( null ) ; } } catch ( InterruptedException e ) { throw new RuntimeException ( "" , e ) ; } } } ) ; final List < State > events = new ArrayList < State > ( ) ; StateListener listener = new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { events . add ( event . getState ( ) ) ; } } ; new Thread ( ) { @ Override public void run ( ) { test . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { test . setState ( JobState . COMPLETE ) ; test . fireEvent ( ) ; } } ) ; } } . start ( ) ; exchanger . exchange ( null ) ; exchanger . exchange ( null ) ; test . addStateListener ( listener ) ; assertEquals ( JobState . COMPLETE , events . get ( ) ) ; assertEquals ( , events . size ( ) ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testSleep ( ) throws InterruptedException { final CountDownLatch latch = new CountDownLatch ( ) ; final JobStateHandler test = new JobStateHandler ( new MockStateful ( ) ) ; final List < State > events = new ArrayList < State > ( ) ; StateListener listener = new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { events . add ( event . getState ( ) ) ; } } ; test . addStateListener ( listener ) ; Thread t1 = new Thread ( new Runnable ( ) { @ Override public void run ( ) { test . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { latch . countDown ( ) ; try { test . sleep ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } test . setState ( JobState . COMPLETE ) ; test . fireEvent ( ) ; } } ) ; } } ) ; Thread t2 = new Thread ( ) { @ Override public void run ( ) { try { latch . await ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } test . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { test . setState ( JobState . INCOMPLETE ) ; test . fireEvent ( ) ; test . wake ( ) ; } } ) ; } } ; t1 . start ( ) ; t2 . start ( ) ; t1 . join ( ) ; t2 . join ( ) ; assertEquals ( JobState . READY , events . get ( ) ) ; assertEquals ( JobState . INCOMPLETE , events . get ( ) ) ; assertEquals ( JobState . COMPLETE , events . get ( ) ) ; assertEquals ( , events . size ( ) ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class AndStateOpTest extends TestCase { public void testAndNoStates ( ) { AndStateOp test = new AndStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( ) ) ; } public void testAndOneStates ( ) { AndStateOp test = new AndStateOp ( ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING ) ) ; } public void testAndTwoStates ( ) { AndStateOp test = new AndStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . COMPLETE , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE , JobState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . COMPLETE , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . COMPLETE , JobState . EXECUTING ) ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class CompleteOrNotOpTest extends TestCase { public void testVariousStates ( ) { CompleteOrNotOp test = new CompleteOrNotOp ( ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE , JobState . COMPLETE , JobState . COMPLETE ) ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . COMPLETE , JobState . INCOMPLETE , JobState . COMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . READY ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING ) ) ; try { test . evaluate ( JobState . DESTROYED ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } } } package org . oddjob . state ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . IntervalSchedule ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . scheduling . Timer ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; public class JoinJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( JoinJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } private static class OurJob extends SimpleJob { int ran ; @ Override protected int execute ( ) throws Throwable { ++ ran ; return ; } } public void testEmpty ( ) { JoinJob test = new JoinJob ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testSimpleRunnable ( ) throws FailedToStopException , InterruptedException { OurJob job1 = new OurJob ( ) ; JoinJob test = new JoinJob ( ) ; test . setJob ( job1 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; test . run ( ) ; testState . checkNow ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , job1 . ran ) ; ( ( Resetable ) job1 ) . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job1 . lastStateEvent ( ) . getState ( ) ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; test . run ( ) ; testState . checkNow ( ) ; assertEquals ( , job1 . ran ) ; } public void testNotComplete ( ) throws FailedToStopException { FlagState job1 = new FlagState ( ) ; job1 . setState ( JobState . INCOMPLETE ) ; JoinJob test = new JoinJob ( ) ; test . setJob ( job1 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; job1 . setState ( JobState . COMPLETE ) ; job1 . hardReset ( ) ; job1 . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; } public void testAsynchronous ( ) throws FailedToStopException , InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; FlagState job1 = new FlagState ( ) ; job1 . setState ( JobState . COMPLETE ) ; Timer timer = new Timer ( ) ; CountSchedule count = new CountSchedule ( ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; count . setRefinement ( interval ) ; timer . setSchedule ( count ) ; timer . setJob ( job1 ) ; timer . setScheduleExecutorService ( executors . getScheduledExecutor ( ) ) ; JoinJob test = new JoinJob ( ) ; test . setJob ( timer ) ; StateSteps testStates = new StateSteps ( test ) ; testStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; test . run ( ) ; testStates . checkNow ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; executors . stop ( ) ; } public void testAsynchronousStop ( ) throws FailedToStopException , InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; FlagState job1 = new FlagState ( ) ; job1 . setState ( JobState . COMPLETE ) ; Timer timer = new Timer ( ) ; CountSchedule count = new CountSchedule ( ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; count . setRefinement ( interval ) ; timer . setSchedule ( count ) ; timer . setJob ( job1 ) ; timer . setScheduleExecutorService ( executors . getScheduledExecutor ( ) ) ; final JoinJob test = new JoinJob ( ) ; test . setJob ( timer ) ; StateSteps testStates = new StateSteps ( test ) ; testStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; executors . getScheduledExecutor ( ) . schedule ( new Runnable ( ) { @ Override public void run ( ) { try { test . stop ( ) ; } catch ( FailedToStopException e ) { throw new RuntimeException ( e ) ; } } } , , TimeUnit . MILLISECONDS ) ; test . run ( ) ; testStates . checkNow ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; executors . stop ( ) ; } public void testDestroyed ( ) throws FailedToStopException { FlagState job1 = new FlagState ( ) ; job1 . setState ( JobState . COMPLETE ) ; JoinJob test = new JoinJob ( ) ; test . setJob ( job1 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; StateSteps testStates = new StateSteps ( test ) ; testStates . startCheck ( ParentState . COMPLETE , ParentState . DESTROYED ) ; test . destroy ( ) ; testStates . checkNow ( ) ; } public void testInOddjob ( ) throws InterruptedException , ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful test = lookup . lookup ( "" , Stateful . class ) ; StateSteps state = new StateSteps ( test ) ; Thread t = new Thread ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING ) ; t . start ( ) ; state . checkWait ( ) ; assertEquals ( ParentState . EXECUTING , oddjob . lastStateEvent ( ) . getState ( ) ) ; Stateful lastJob = lookup . lookup ( "" , Stateful . class ) ; assertEquals ( JobState . READY , lastJob . lastStateEvent ( ) . getState ( ) ) ; Object applesFlag = lookup . lookup ( "" ) ; Object orangesFlag = lookup . lookup ( "" ) ; ( ( Runnable ) applesFlag ) . run ( ) ; ( ( Runnable ) orangesFlag ) . run ( ) ; t . join ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , lastJob . lastStateEvent ( ) . getState ( ) ) ; ( ( Resetable ) test ) . hardReset ( ) ; ( ( Resetable ) lastJob ) . hardReset ( ) ; Thread t2 = new Thread ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING ) ; t2 . start ( ) ; state . checkWait ( ) ; assertEquals ( JobState . READY , lastJob . lastStateEvent ( ) . getState ( ) ) ; ( ( Resetable ) applesFlag ) . hardReset ( ) ; ( ( Resetable ) orangesFlag ) . hardReset ( ) ; ( ( Runnable ) applesFlag ) . run ( ) ; ( ( Runnable ) orangesFlag ) . run ( ) ; t2 . join ( ) ; assertEquals ( JobState . COMPLETE , lastJob . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . state ; import java . io . File ; import java . io . IOException ; import java . util . Properties ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . StateSteps ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . structural . SequentialJob ; public class EqualsStateTest extends TestCase { public void testComplete ( ) { EqualsState test = new EqualsState ( ) ; FlagState job = new FlagState ( JobState . INCOMPLETE ) ; test . setJob ( job ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; job . setState ( JobState . COMPLETE ) ; test . softReset ( ) ; assertEquals ( JobState . READY , job . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNotComplete ( ) { EqualsState test = new EqualsState ( ) ; test . setState ( new IsNot ( StateConditions . COMPLETE ) ) ; FlagState job = new FlagState ( JobState . INCOMPLETE ) ; test . setJob ( job ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; job . setState ( JobState . COMPLETE ) ; job . softReset ( ) ; job . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNotException ( ) { EqualsState test = new EqualsState ( ) ; test . setState ( new IsNot ( StateConditions . EXCEPTION ) ) ; FlagState job = new FlagState ( JobState . INCOMPLETE ) ; test . setJob ( job ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; job . setState ( JobState . EXCEPTION ) ; job . softReset ( ) ; job . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testInOddjob ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; } public void testExample ( ) throws InterruptedException , IOException , ArooaPropertyException , ArooaConversionException { OurDirs dirs = new OurDirs ( ) ; File pretendLockFile = dirs . relative ( "" ) ; pretendLockFile . createNewFile ( ) ; Properties properties = new Properties ( ) ; properties . setProperty ( "" , pretendLockFile . getPath ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setProperties ( properties ) ; oddjob . load ( ) ; SequentialJob sequential = new OddjobLookup ( oddjob ) . lookup ( "" , SequentialJob . class ) ; StateSteps sequentialStates = new StateSteps ( sequential ) ; sequentialStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . INCOMPLETE ) ; oddjob . run ( ) ; sequentialStates . checkWait ( ) ; StateSteps oddjobStates = new StateSteps ( oddjob ) ; oddjobStates . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; pretendLockFile . delete ( ) ; oddjobStates . checkWait ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; public class OrStateOpTest extends TestCase { public void testOrNoStates ( ) { OrStateOp test = new OrStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( ) ) ; } public void testOrOneStates ( ) { OrStateOp test = new OrStateOp ( ) ; assertEquals ( ParentState . INCOMPLETE , test . evaluate ( JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . EXCEPTION ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . EXECUTING ) ) ; } public void testOr ( ) { OrStateOp test = new OrStateOp ( ) ; assertEquals ( ParentState . READY , test . evaluate ( JobState . READY , JobState . READY ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE , JobState . INCOMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , test . evaluate ( JobState . COMPLETE , JobState . READY ) ) ; assertEquals ( ParentState . EXCEPTION , test . evaluate ( JobState . COMPLETE , JobState . EXCEPTION ) ) ; assertEquals ( ParentState . ACTIVE , test . evaluate ( JobState . COMPLETE , JobState . EXECUTING ) ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . xml . XMLConfiguration ; public class StateBehaviourTest extends TestCase { private static final Logger logger = Logger . getLogger ( StateBehaviourTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testEmptyParentState ( ) throws ArooaParseException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object sequential = lookup . lookup ( "" ) ; Object echo = lookup . lookup ( "" ) ; StateSteps checker = new StateSteps ( ( Stateful ) sequential ) ; checker . startCheck ( ParentState . READY ) ; DragPoint dp = oddjob . provideConfigurationSession ( ) . dragPointFor ( echo ) ; DragTransaction t = dp . beginChange ( ChangeHow . FRESH ) ; dp . cut ( ) ; t . commit ( ) ; checker . checkNow ( ) ; oddjob . destroy ( ) ; } public void testEmptySequential ( ) throws ArooaParseException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object echo = lookup . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) echo ) . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testExecutingSequential ( ) throws ArooaParseException , InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object sequential = lookup . lookup ( "" ) ; Object echo = lookup . lookup ( "" ) ; StateSteps checker = new StateSteps ( ( Stateful ) sequential ) ; checker . startCheck ( ParentState . READY , ParentState . EXECUTING ) ; new Thread ( ( Runnable ) sequential ) . start ( ) ; checker . checkWait ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , ( ( Stateful ) echo ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Stoppable ) sequential ) . stop ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public static class OurService { public void start ( ) { } public void stop ( ) { } } public void testActiveSequential ( ) throws ArooaParseException , InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object sequential = lookup . lookup ( "" ) ; Object service = lookup . lookup ( "" ) ; Object echo = lookup . lookup ( "" ) ; StateSteps checker = new StateSteps ( ( Stateful ) sequential ) ; checker . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; ( ( Runnable ) sequential ) . run ( ) ; checker . checkNow ( ) ; assertEquals ( ServiceState . STARTED , ( ( Stateful ) service ) . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) echo ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Stoppable ) sequential ) . stop ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testServiceActiveSequential ( ) throws ArooaParseException , InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object sequential = lookup . lookup ( "" ) ; Object service = lookup . lookup ( "" ) ; Object echo = lookup . lookup ( "" ) ; ( ( Runnable ) service ) . run ( ) ; assertEquals ( ServiceState . STARTED , ( ( Stateful ) service ) . lastStateEvent ( ) . getState ( ) ) ; StateSteps checker = new StateSteps ( ( Stateful ) sequential ) ; checker . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; ( ( Runnable ) sequential ) . run ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . run ( ) ; checker . checkNow ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) echo ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Stoppable ) sequential ) . stop ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testRunningChildren ( ) throws ArooaParseException , InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object sequential = lookup . lookup ( "" ) ; Object wait1 = lookup . lookup ( "" ) ; Object wait2 = lookup . lookup ( "" ) ; Object echo = lookup . lookup ( "" ) ; StateSteps checker = new StateSteps ( ( Stateful ) wait2 ) ; checker . startCheck ( JobState . READY , JobState . EXECUTING ) ; new Thread ( ( Runnable ) wait2 ) . start ( ) ; checker . checkWait ( ) ; StateSteps checker2 = new StateSteps ( ( Stateful ) wait1 ) ; checker2 . startCheck ( JobState . READY , JobState . EXECUTING ) ; new Thread ( ( Runnable ) sequential ) . start ( ) ; checker2 . checkWait ( ) ; assertEquals ( ParentState . EXECUTING , ( ( Stateful ) sequential ) . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , ( ( Stateful ) echo ) . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , ( ( Stateful ) echo ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Stoppable ) sequential ) . stop ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; checker . startCheck ( JobState . COMPLETE , JobState . READY , JobState . EXECUTING ) ; ( ( Resetable ) wait2 ) . hardReset ( ) ; new Thread ( ( Runnable ) wait2 ) . start ( ) ; checker . checkWait ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; ( ( Stoppable ) sequential ) . stop ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . state ; import java . io . File ; import java . util . Properties ; import java . util . concurrent . Future ; import junit . framework . TestCase ; import org . oddjob . FragmentHelper ; import org . oddjob . OurDirs ; import org . oddjob . StateSteps ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . framework . ServicesJob ; import org . oddjob . scheduling . MockScheduledExecutorService ; import org . oddjob . scheduling . MockScheduledFuture ; public class AndStateTest extends TestCase { private class Result implements StateListener { State result ; public void jobStateChange ( StateEvent event ) { result = event . getState ( ) ; } } private class UnusedServices extends MockScheduledExecutorService { } public void testComplete ( ) { AndState test = new AndState ( ) ; test . setExecutorService ( new UnusedServices ( ) ) ; test . run ( ) ; Result listener = new Result ( ) ; test . addStateListener ( listener ) ; assertEquals ( ParentState . READY , listener . result ) ; FlagState j1 = new FlagState ( JobState . COMPLETE ) ; test . setJobs ( , j1 ) ; assertEquals ( ParentState . READY , listener . result ) ; j1 . run ( ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; FlagState j2 = new FlagState ( JobState . COMPLETE ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . READY , listener . result ) ; j2 . run ( ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . READY , listener . result ) ; } public void testException ( ) { AndState test = new AndState ( ) ; test . setExecutorService ( new UnusedServices ( ) ) ; test . run ( ) ; Result listener = new Result ( ) ; test . addStateListener ( listener ) ; assertEquals ( ParentState . READY , listener . result ) ; FlagState j1 = new FlagState ( JobState . COMPLETE ) ; test . setJobs ( , j1 ) ; assertEquals ( ParentState . READY , listener . result ) ; j1 . run ( ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; FlagState j2 = new FlagState ( JobState . EXCEPTION ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . READY , listener . result ) ; j2 . run ( ) ; assertEquals ( ParentState . EXCEPTION , listener . result ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . EXCEPTION , listener . result ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . READY , listener . result ) ; } public void testManyComplete ( ) { AndState test = new AndState ( ) ; test . setExecutorService ( new UnusedServices ( ) ) ; test . run ( ) ; Result listener = new Result ( ) ; test . addStateListener ( listener ) ; assertEquals ( ParentState . READY , listener . result ) ; FlagState j1 = new FlagState ( JobState . COMPLETE ) ; FlagState j2 = new FlagState ( JobState . COMPLETE ) ; FlagState j3 = new FlagState ( JobState . COMPLETE ) ; FlagState j4 = new FlagState ( JobState . COMPLETE ) ; j1 . run ( ) ; j2 . run ( ) ; j3 . run ( ) ; j4 . run ( ) ; test . setJobs ( , j1 ) ; test . setJobs ( , j2 ) ; test . setJobs ( , j3 ) ; test . setJobs ( , j4 ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; } private class NowExecutor extends MockScheduledExecutorService { public Future < ? > submit ( Runnable runnable ) { runnable . run ( ) ; return new MockScheduledFuture < Void > ( ) ; } } public void testExample ( ) throws ArooaParseException { OurDirs dirs = new OurDirs ( ) ; File file1 = dirs . relative ( "" ) ; File file2 = dirs . relative ( "" ) ; Properties properties = new Properties ( ) ; properties . setProperty ( "" , file1 . getPath ( ) ) ; properties . setProperty ( "" , file2 . getPath ( ) ) ; FragmentHelper helper = new FragmentHelper ( ) ; helper . setProperties ( properties ) ; AndState test = ( AndState ) helper . createComponentFromResource ( "" ) ; ArooaSession session = helper . getSession ( ) ; ServicesJob . ServiceDefinition def = new ServicesJob . ServiceDefinition ( ) ; def . setService ( new NowExecutor ( ) ) ; ServicesJob services = new ServicesJob ( ) ; services . setRegisteredServices ( , def ) ; session . getBeanRegistry ( ) . register ( "" , services ) ; StateSteps states = new StateSteps ( test ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; states . checkNow ( ) ; } } package org . oddjob . state ; import junit . framework . TestCase ; import org . oddjob . MockStateful ; import org . oddjob . Structural ; import org . oddjob . structural . ChildHelper ; import org . oddjob . structural . StructuralListener ; public class StructuralStateHelperTest extends TestCase { State state ; class OurStateListener implements StateListener { public void jobStateChange ( StateEvent event ) { state = event . getState ( ) ; } } class DummyStructural implements Structural { public void addStructuralListener ( StructuralListener listener ) { throw new RuntimeException ( "" ) ; } public void removeStructuralListener ( StructuralListener listener ) { throw new RuntimeException ( "" ) ; } } public void testManyDifferentChildren ( ) { FlagState j1 = new FlagState ( JobState . COMPLETE ) ; Object j2 = new Object ( ) ; Object j3 = new FlagState ( JobState . COMPLETE ) ; Object j4 = new FlagState ( JobState . EXCEPTION ) ; FlagState j5 = new FlagState ( JobState . INCOMPLETE ) ; ChildHelper < Object > childHelper = new ChildHelper < Object > ( new DummyStructural ( ) ) ; StructuralStateHelper test = new StructuralStateHelper ( childHelper , new WorstStateOp ( ) ) ; test . addStateListener ( new OurStateListener ( ) ) ; assertEquals ( ParentState . READY , state ) ; childHelper . insertChild ( , j1 ) ; childHelper . insertChild ( , j2 ) ; childHelper . insertChild ( , j3 ) ; childHelper . insertChild ( , j4 ) ; childHelper . insertChild ( , j5 ) ; assertEquals ( ParentState . READY , state ) ; j1 . run ( ) ; assertEquals ( ParentState . READY , state ) ; ( ( Runnable ) childHelper . getChildAt ( ) ) . run ( ) ; assertEquals ( ParentState . READY , state ) ; ( ( Runnable ) childHelper . getChildAt ( ) ) . run ( ) ; assertEquals ( ParentState . EXCEPTION , state ) ; childHelper . removeChildAt ( ) ; j5 . run ( ) ; assertEquals ( ParentState . INCOMPLETE , state ) ; childHelper . removeChildAt ( ) ; j1 . hardReset ( ) ; j1 . run ( ) ; assertEquals ( ParentState . COMPLETE , state ) ; childHelper . removeChildAt ( ) ; childHelper . insertChild ( , j5 ) ; j5 . hardReset ( ) ; j5 . run ( ) ; assertEquals ( ParentState . INCOMPLETE , state ) ; childHelper . softResetChildren ( ) ; assertEquals ( ParentState . READY , state ) ; } public void testLikeFolder ( ) { Object j1 = new Object ( ) ; ChildHelper < Object > childHelper = new ChildHelper < Object > ( new DummyStructural ( ) ) ; StructuralStateHelper test = new StructuralStateHelper ( childHelper , new WorstStateOp ( ) ) ; test . addStateListener ( new OurStateListener ( ) ) ; childHelper . insertChild ( , j1 ) ; assertEquals ( ParentState . COMPLETE , state ) ; } public void testTwo ( ) { Object j1 = new Object ( ) ; Object j2 = new FlagState ( JobState . COMPLETE ) ; ChildHelper < Object > childHelper = new ChildHelper < Object > ( new DummyStructural ( ) ) ; StructuralStateHelper test = new StructuralStateHelper ( childHelper , new WorstStateOp ( ) ) ; test . addStateListener ( new OurStateListener ( ) ) ; childHelper . insertChild ( , j1 ) ; childHelper . insertChild ( , j2 ) ; assertEquals ( ParentState . READY , state ) ; ( ( Runnable ) childHelper . getChildAt ( ) ) . run ( ) ; assertEquals ( ParentState . COMPLETE , state ) ; } public void testEmpty ( ) { ChildHelper < Object > childHelper = new ChildHelper < Object > ( new DummyStructural ( ) ) ; StructuralStateHelper h = new StructuralStateHelper ( childHelper , new WorstStateOp ( ) ) ; h . addStateListener ( new OurStateListener ( ) ) ; assertEquals ( ParentState . READY , state ) ; } private class OurStateful extends MockStateful { StateListener listener ; public void addStateListener ( StateListener listener ) { assertNull ( this . listener ) ; this . listener = listener ; } public void removeStateListener ( StateListener listener ) { assertEquals ( this . listener , listener ) ; this . listener = null ; } } public void testDestroyed ( ) { ChildHelper < Object > childHelper = new ChildHelper < Object > ( new DummyStructural ( ) ) ; StructuralStateHelper test = new StructuralStateHelper ( childHelper , new WorstStateOp ( ) ) ; OurStateful job = new OurStateful ( ) ; childHelper . insertChild ( , new FlagState ( JobState . COMPLETE ) ) ; childHelper . insertChild ( , job ) ; assertNotNull ( job . listener ) ; try { job . listener . jobStateChange ( new StateEvent ( job , JobState . DESTROYED ) ) ; fail ( "" ) ; } catch ( Exception e ) { } childHelper . removeChildAt ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . state ; import java . io . IOException ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . StateSteps ; import org . oddjob . framework . SimpleJob ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . scheduling . MockScheduledExecutorService ; public class OrStateTest extends TestCase { private class Result implements StateListener { State result ; public void jobStateChange ( StateEvent event ) { result = event . getState ( ) ; } } private class UnusedServices extends MockScheduledExecutorService { } public void testComplete ( ) { OrState test = new OrState ( ) ; test . setExecutorService ( new UnusedServices ( ) ) ; test . run ( ) ; Result listener = new Result ( ) ; test . addStateListener ( listener ) ; assertEquals ( ParentState . READY , listener . result ) ; FlagState j1 = new FlagState ( JobState . COMPLETE ) ; test . setJobs ( , j1 ) ; assertEquals ( ParentState . READY , listener . result ) ; j1 . run ( ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; FlagState j2 = new FlagState ( JobState . COMPLETE ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; j2 . run ( ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . READY , listener . result ) ; } public void testException ( ) { OrState test = new OrState ( ) ; test . setExecutorService ( new UnusedServices ( ) ) ; test . run ( ) ; Result listener = new Result ( ) ; test . addStateListener ( listener ) ; assertEquals ( ParentState . READY , listener . result ) ; FlagState j1 = new FlagState ( JobState . COMPLETE ) ; test . setJobs ( , j1 ) ; assertEquals ( ParentState . READY , listener . result ) ; j1 . run ( ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; FlagState j2 = new FlagState ( JobState . EXCEPTION ) ; test . setJobs ( , j2 ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; j2 . run ( ) ; assertEquals ( ParentState . EXCEPTION , listener . result ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . EXCEPTION , listener . result ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . READY , listener . result ) ; } public void testManyComplete ( ) { OrState test = new OrState ( ) ; test . setExecutorService ( new UnusedServices ( ) ) ; test . run ( ) ; Result listener = new Result ( ) ; test . addStateListener ( listener ) ; assertEquals ( ParentState . READY , listener . result ) ; FlagState j1 = new FlagState ( JobState . INCOMPLETE ) ; FlagState j2 = new FlagState ( JobState . INCOMPLETE ) ; FlagState j3 = new FlagState ( JobState . COMPLETE ) ; FlagState j4 = new FlagState ( JobState . INCOMPLETE ) ; j1 . run ( ) ; j2 . run ( ) ; j3 . run ( ) ; j4 . run ( ) ; test . setJobs ( , j1 ) ; test . setJobs ( , j2 ) ; test . setJobs ( , j3 ) ; test . setJobs ( , j4 ) ; assertEquals ( ParentState . COMPLETE , listener . result ) ; } public void testSerialize ( ) throws IOException , ClassNotFoundException , InterruptedException { DefaultExecutors services = new DefaultExecutors ( ) ; SimpleJob notSerializable = new SimpleJob ( ) { @ Override protected int execute ( ) throws Throwable { return ; } } ; OrState test = new OrState ( ) ; test . setExecutorService ( services . getPoolExecutor ( ) ) ; test . setJobs ( , notSerializable ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; state . checkWait ( ) ; services . stop ( ) ; OrState copy = ( OrState ) Helper . copy ( test ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . state ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . MockStateful ; public class StateExchangeTest extends TestCase { private class OurStateful extends MockStateful { StateListener listener ; public void addStateListener ( StateListener listener ) { assertNull ( this . listener ) ; this . listener = listener ; } public void removeStateListener ( StateListener listener ) { assertEquals ( this . listener , listener ) ; this . listener = null ; } } private class OurChanger extends MockStateChanger { ParentState state ; @ Override public void setState ( ParentState state , Date date ) { this . state = state ; } } public void testDestroyedState ( ) { OurStateful stateful = new OurStateful ( ) ; OurChanger changer = new OurChanger ( ) ; StateExchange test = new StateExchange ( stateful , changer ) ; assertNull ( stateful . listener ) ; test . start ( ) ; assertNotNull ( stateful . listener ) ; assertNull ( changer . state ) ; stateful . listener . jobStateChange ( new StateEvent ( stateful , ParentState . COMPLETE ) ) ; assertEquals ( ParentState . COMPLETE , changer . state ) ; stateful . listener . jobStateChange ( new StateEvent ( stateful , ParentState . DESTROYED ) ) ; assertEquals ( ParentState . COMPLETE , changer . state ) ; test . stop ( ) ; assertNull ( stateful . listener ) ; } } package org . oddjob . state ; import java . util . Date ; public class MockStateChanger implements StateChanger < ParentState > { public void setState ( ParentState state ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void setState ( ParentState state , Date date ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void setStateException ( Throwable t ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void setStateException ( Throwable t , Date date ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . state ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . framework . StopWait ; import org . oddjob . jobs . WaitJob ; import org . oddjob . jobs . structural . JobFolder ; import org . oddjob . scheduling . DefaultExecutors ; public class CascadeJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( CascadeJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } private static class OurJob extends SimpleJob { int ran ; @ Override protected int execute ( ) throws Throwable { ++ ran ; return ; } } public void testEmpty ( ) throws InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . READY ) ; test . run ( ) ; steps . checkWait ( ) ; executors . stop ( ) ; } public void testSimpleRunnables ( ) throws FailedToStopException , InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; OurJob job1 = new OurJob ( ) ; OurJob job2 = new OurJob ( ) ; OurJob job3 = new OurJob ( ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; test . setJobs ( , job1 ) ; test . setJobs ( , job2 ) ; test . setJobs ( , job3 ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; testState . checkWait ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , job1 . ran ) ; assertEquals ( , job2 . ran ) ; assertEquals ( , job3 . ran ) ; ( ( Resetable ) job2 ) . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job3 . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job3 . lastStateEvent ( ) . getState ( ) ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; testState . checkWait ( ) ; assertEquals ( , job1 . ran ) ; assertEquals ( , job2 . ran ) ; assertEquals ( , job3 . ran ) ; executors . stop ( ) ; } public void testNotComplete ( ) throws FailedToStopException , InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; FlagState job1 = new FlagState ( ) ; job1 . setState ( JobState . INCOMPLETE ) ; FlagState job2 = new FlagState ( ) ; job2 . setState ( JobState . INCOMPLETE ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; test . setJobs ( , job1 ) ; test . setJobs ( , job2 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; StateSteps testStates = new StateSteps ( test ) ; testStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . INCOMPLETE ) ; test . run ( ) ; testStates . checkWait ( ) ; assertEquals ( JobState . INCOMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job2 . lastStateEvent ( ) . getState ( ) ) ; job1 . setState ( JobState . COMPLETE ) ; testStates . startCheck ( ParentState . INCOMPLETE , ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . INCOMPLETE ) ; test . softReset ( ) ; test . run ( ) ; testStates . checkWait ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , job2 . lastStateEvent ( ) . getState ( ) ) ; executors . stop ( ) ; } public void testException ( ) throws FailedToStopException , InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; FlagState job1 = new FlagState ( ) ; job1 . setState ( JobState . COMPLETE ) ; FlagState job2 = new FlagState ( ) ; job2 . setState ( JobState . EXCEPTION ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; test . setJobs ( , job1 ) ; test . setJobs ( , job2 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; StateSteps job2Check = new StateSteps ( job2 ) ; job2Check . startCheck ( JobState . READY , JobState . EXECUTING , JobState . EXCEPTION ) ; test . run ( ) ; job2Check . checkWait ( ) ; new StopWait ( test ) . run ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . EXCEPTION , job2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; job2Check . startCheck ( JobState . EXCEPTION , JobState . READY , JobState . EXECUTING , JobState . COMPLETE ) ; job2 . setState ( JobState . COMPLETE ) ; job2 . softReset ( ) ; job2 . run ( ) ; job2Check . checkWait ( ) ; assertEquals ( JobState . COMPLETE , job1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job2 . lastStateEvent ( ) . getState ( ) ) ; executors . stop ( ) ; } public void testDestroyed ( ) throws FailedToStopException , InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; FlagState job1 = new FlagState ( ) ; job1 . setState ( JobState . COMPLETE ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; test . setJobs ( , job1 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; state . checkWait ( ) ; final List < State > results = new ArrayList < State > ( ) ; class OurListener implements StateListener { public void jobStateChange ( StateEvent event ) { results . add ( event . getState ( ) ) ; } } OurListener l = new OurListener ( ) ; test . addStateListener ( l ) ; assertEquals ( ParentState . COMPLETE , results . get ( ) ) ; assertEquals ( , results . size ( ) ) ; test . destroy ( ) ; assertEquals ( ParentState . DESTROYED , results . get ( ) ) ; assertEquals ( , results . size ( ) ) ; executors . stop ( ) ; } public void testWithFoldersMixedIn ( ) throws InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; FlagState job1 = new FlagState ( JobState . COMPLETE ) ; FlagState job2 = new FlagState ( JobState . COMPLETE ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . setJobs ( , new JobFolder ( ) ) ; test . setJobs ( , job1 ) ; test . setJobs ( , new JobFolder ( ) ) ; test . setJobs ( , job2 ) ; test . setJobs ( , new JobFolder ( ) ) ; test . run ( ) ; testState . checkWait ( ) ; executors . stop ( ) ; } public void testRemovingAndInserting ( ) throws InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; FlagState job1 = new FlagState ( JobState . COMPLETE ) ; FlagState job2 = new FlagState ( JobState . COMPLETE ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . setJobs ( , job1 ) ; test . setJobs ( , job2 ) ; test . run ( ) ; testState . checkWait ( ) ; test . setJobs ( , null ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; testState . startCheck ( ParentState . COMPLETE , ParentState . EXECUTING , ParentState . COMPLETE ) ; FlagState job3 = new FlagState ( JobState . COMPLETE ) ; StateSteps job3State = new StateSteps ( job3 ) ; job3State . startCheck ( JobState . READY ) ; test . setJobs ( , job3 ) ; job3State . checkNow ( ) ; FlagState job4 = new FlagState ( JobState . COMPLETE ) ; test . setJobs ( , job4 ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , job4 . lastStateEvent ( ) . getState ( ) ) ; executors . stop ( ) ; } public void testInsertingWhileRuning ( ) throws InterruptedException , FailedToStopException { DefaultExecutors executors = new DefaultExecutors ( ) ; WaitJob job1 = new WaitJob ( ) ; job1 . setName ( "" ) ; WaitJob job2 = new WaitJob ( ) ; job2 . setName ( "" ) ; WaitJob job3 = new WaitJob ( ) ; job3 . setName ( "" ) ; WaitJob job4 = new WaitJob ( ) ; job4 . setName ( "" ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; test . setJobs ( , job1 ) ; test . setJobs ( , job2 ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; StateSteps job1State = new StateSteps ( job1 ) ; job1State . startCheck ( JobState . READY , JobState . EXECUTING ) ; StateSteps job2State = new StateSteps ( job2 ) ; job2State . startCheck ( JobState . READY ) ; test . run ( ) ; StateSteps job3State = new StateSteps ( job3 ) ; job3State . startCheck ( JobState . READY , JobState . EXECUTING ) ; test . setJobs ( , null ) ; test . setJobs ( , job3 ) ; job1State . checkWait ( ) ; job1State . startCheck ( JobState . EXECUTING , JobState . COMPLETE ) ; job1 . stop ( ) ; job1State . checkWait ( ) ; job2State . checkNow ( ) ; job3State . checkWait ( ) ; StateSteps job4State = new StateSteps ( job4 ) ; job4State . startCheck ( JobState . READY , JobState . EXECUTING ) ; test . setJobs ( , job4 ) ; new Thread ( job4 ) . start ( ) ; job4State . checkWait ( ) ; job3State . startCheck ( JobState . EXECUTING , JobState . COMPLETE ) ; job4State . startCheck ( JobState . EXECUTING , JobState . COMPLETE ) ; job3 . stop ( ) ; job3State . checkWait ( ) ; test . stop ( ) ; job4State . checkNow ( ) ; testState . checkNow ( ) ; executors . stop ( ) ; } public void testInOddjob ( ) throws InterruptedException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; StateSteps oddjobStates = new StateSteps ( oddjob ) ; oddjobStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; oddjobStates . checkWait ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; } public void testStop ( ) throws InterruptedException , FailedToStopException { DefaultExecutors executors = new DefaultExecutors ( ) ; CascadeJob test = new CascadeJob ( ) ; test . setExecutorService ( executors . getPoolExecutor ( ) ) ; WaitJob wait1 = new WaitJob ( ) ; WaitJob wait2 = new WaitJob ( ) ; test . setJobs ( , wait1 ) ; test . setJobs ( , wait2 ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; StateSteps wait1State = new StateSteps ( wait1 ) ; StateSteps wait2State = new StateSteps ( wait2 ) ; wait1State . startCheck ( JobState . READY , JobState . EXECUTING ) ; test . run ( ) ; testState . checkNow ( ) ; wait1State . checkWait ( ) ; testState . startCheck ( ParentState . ACTIVE , ParentState . READY ) ; test . stop ( ) ; testState . checkNow ( ) ; assertEquals ( JobState . READY , wait2 . lastStateEvent ( ) . getState ( ) ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; wait2State . startCheck ( JobState . READY , JobState . EXECUTING ) ; test . softReset ( ) ; test . run ( ) ; testState . checkNow ( ) ; wait2State . checkWait ( ) ; testState . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; test . stop ( ) ; testState . checkNow ( ) ; executors . stop ( ) ; } public void testExample ( ) throws InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; StateSteps oddjobStates = new StateSteps ( oddjob ) ; oddjobStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; oddjobStates . checkWait ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . sql ; import java . io . ByteArrayInputStream ; import java . sql . Connection ; import java . util . List ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . BufferType ; import org . oddjob . io . StdoutType ; import org . oddjob . jobs . BeanReportJob ; import org . oddjob . state . ParentState ; public class SQLJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( SQLJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testSql ( ) throws Exception { ConnectionType ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; SQLJob test = new SQLJob ( ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; SQLResultsBean beans = new SQLResultsBean ( ) ; test . setResults ( beans ) ; test . setConnection ( ct . toValue ( ) ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . run ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . run ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . run ( ) ; logger . debug ( "" + beans . getUpdateCount ( ) ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . run ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . run ( ) ; assertEquals ( "" , ( ( DynaBean ) beans . getRows ( ) [ ] ) . get ( "" ) ) ; assertEquals ( "" , ( ( DynaBean ) beans . getRows ( ) [ ] ) . get ( "" ) ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . run ( ) ; assertEquals ( null , beans . getRows ( ) ) ; } public void testInOddjob ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; List < ? > o = new OddjobLookup ( oddjob ) . lookup ( "" , List . class ) ; BeanReportJob rep = new BeanReportJob ( ) ; rep . setOutput ( new StdoutType ( ) . toValue ( ) ) ; rep . setArooaSession ( new StandardArooaSession ( ) ) ; rep . setBeans ( o ) ; rep . run ( ) ; Integer result = new OddjobLookup ( oddjob ) . lookup ( "" , Integer . class ) ; assertEquals ( new Integer ( ) , result ) ; oddjob . destroy ( ) ; } public void testFirstExample ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; Connection connection = new OddjobLookup ( oddjob ) . lookup ( "" , Connection . class ) ; SQLJob shutdown = new SQLJob ( ) ; shutdown . setArooaSession ( new StandardArooaSession ( ) ) ; shutdown . setConnection ( connection ) ; shutdown . setInput ( new ByteArrayInputStream ( "" . getBytes ( ) ) ) ; shutdown . run ( ) ; } public void testInOddjobEmptyResultSet ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; List < ? > o = lookup . lookup ( "" , List . class ) ; assertNotNull ( o ) ; int rows = lookup . lookup ( "" , int . class ) ; assertEquals ( , rows ) ; oddjob . destroy ( ) ; } public void testMultipleStatements ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; String [ ] rows = lookup . lookup ( "" , String [ ] . class ) ; assertEquals ( , rows . length ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; oddjob . destroy ( ) ; } public void testContinueOnFailure ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { "" , "" } ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; String [ ] rows = lookup . lookup ( "" , String [ ] . class ) ; assertEquals ( , rows . length ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testStopOnFailure ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { "" , "" } ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; String [ ] rows = lookup . lookup ( "" , String [ ] . class ) ; assertEquals ( , rows . length ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testAbortOnFailure ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { "" , "" } ) ; oddjob . run ( ) ; assertEquals ( ParentState . EXCEPTION , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; String [ ] rows = lookup . lookup ( "" , String [ ] . class ) ; assertEquals ( , rows . length ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( ParentState . EXCEPTION , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testAbortOnFailureWithAutocommit ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { "" , "" } ) ; oddjob . run ( ) ; assertEquals ( ParentState . EXCEPTION , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; String [ ] rows = lookup . lookup ( "" , String [ ] . class ) ; assertEquals ( , rows . length ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( ParentState . EXCEPTION , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . sql ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . io . BufferType ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . scheduling . LoosingOutcome ; import org . oddjob . scheduling . MockScheduledExecutorService ; import org . oddjob . scheduling . MockScheduledFuture ; import org . oddjob . scheduling . Outcome ; import org . oddjob . scheduling . WinningOutcome ; import org . oddjob . state . JobState ; import org . oddjob . state . StateListener ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; public class SQLKeeperTest extends TestCase { ConnectionType ct ; @ Override protected void setUp ( ) throws Exception { ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" + "" + "" + "" + "" + "" ) ; buffer . configured ( ) ; SQLJob sql = new SQLJob ( ) ; sql . setArooaSession ( new StandardArooaSession ( ) ) ; sql . setInput ( buffer . toInputStream ( ) ) ; sql . setConnection ( ct . toValue ( ) ) ; sql . run ( ) ; } @ Override protected void tearDown ( ) throws Exception { BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; SQLJob sql = new SQLJob ( ) ; sql . setArooaSession ( new StandardArooaSession ( ) ) ; sql . setInput ( buffer . toInputStream ( ) ) ; sql . setConnection ( ct . toValue ( ) ) ; sql . run ( ) ; } private class OurListener implements StateListener { List < State > states = new ArrayList < State > ( ) ; @ Override public void jobStateChange ( StateEvent event ) { states . add ( event . getState ( ) ) ; } } private class OurFuture extends MockScheduledFuture < Void > { boolean canceled ; @ Override public boolean cancel ( boolean mayInterruptIfRunning ) { this . canceled = true ; return true ; } } private class OurExcecutor extends MockScheduledExecutorService { Runnable runnable ; OurFuture future = new OurFuture ( ) ; @ Override public ScheduledFuture < ? > schedule ( Runnable command , long delay , TimeUnit unit ) { this . runnable = command ; return future ; } } public void testFreshRun ( ) throws SQLException , ArooaConversionException { OurExcecutor executor = new OurExcecutor ( ) ; SQLKeeperService test = new SQLKeeperService ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setScheduleExecutorService ( executor ) ; test . start ( ) ; Outcome first = test . getKeeper ( "" ) . grab ( "" , "" ) ; assertTrue ( first . isWon ( ) ) ; assertEquals ( "" , first . getWinner ( ) ) ; Outcome second = test . getKeeper ( "" ) . grab ( "" , "" ) ; assertFalse ( second . isWon ( ) ) ; assertEquals ( "" , second . getWinner ( ) ) ; OurListener listener = new OurListener ( ) ; ( ( LoosingOutcome ) second ) . addStateListener ( listener ) ; assertEquals ( , listener . states . size ( ) ) ; assertEquals ( JobState . EXECUTING , listener . states . get ( ) ) ; ( ( WinningOutcome ) first ) . complete ( ) ; Runnable runnable = executor . runnable ; runnable . run ( ) ; assertEquals ( , listener . states . size ( ) ) ; assertEquals ( JobState . COMPLETE , listener . states . get ( ) ) ; assertTrue ( executor . runnable == runnable ) ; test . stop ( ) ; } public void testFreshStop ( ) throws SQLException , ArooaConversionException { OurExcecutor executor = new OurExcecutor ( ) ; SQLKeeperService test = new SQLKeeperService ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setScheduleExecutorService ( executor ) ; test . start ( ) ; Outcome first = test . getKeeper ( "" ) . grab ( "" , "" ) ; assertTrue ( first . isWon ( ) ) ; assertEquals ( "" , first . getWinner ( ) ) ; Outcome second = test . getKeeper ( "" ) . grab ( "" , "" ) ; assertFalse ( second . isWon ( ) ) ; assertEquals ( "" , second . getWinner ( ) ) ; OurListener listener = new OurListener ( ) ; ( ( LoosingOutcome ) second ) . addStateListener ( listener ) ; assertEquals ( , listener . states . size ( ) ) ; assertEquals ( JobState . EXECUTING , listener . states . get ( ) ) ; assertNotNull ( executor . runnable ) ; ( ( LoosingOutcome ) second ) . removeStateListener ( listener ) ; test . stop ( ) ; assertTrue ( executor . future . canceled ) ; } public void testTimeout ( ) throws SQLException , ArooaConversionException { OurExcecutor executor = new OurExcecutor ( ) ; CountSchedule count = new CountSchedule ( ) ; SQLKeeperService test = new SQLKeeperService ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setScheduleExecutorService ( executor ) ; test . setPollSchedule ( count ) ; test . start ( ) ; Outcome first = test . getKeeper ( "" ) . grab ( "" , "" ) ; assertTrue ( first . isWon ( ) ) ; assertEquals ( "" , first . getWinner ( ) ) ; Outcome second = test . getKeeper ( "" ) . grab ( "" , "" ) ; assertFalse ( second . isWon ( ) ) ; assertEquals ( "" , second . getWinner ( ) ) ; OurListener listener = new OurListener ( ) ; ( ( LoosingOutcome ) second ) . addStateListener ( listener ) ; assertEquals ( , listener . states . size ( ) ) ; assertEquals ( JobState . EXECUTING , listener . states . get ( ) ) ; assertNotNull ( executor . runnable ) ; executor . runnable . run ( ) ; assertEquals ( JobState . EXCEPTION , listener . states . get ( ) ) ; assertEquals ( , listener . states . size ( ) ) ; test . stop ( ) ; } } package org . oddjob . sql ; import java . io . ByteArrayOutputStream ; import java . util . Arrays ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Oddjob ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . BeanBus ; import org . oddjob . beanbus . BeanSheetTest . Fruit ; import org . oddjob . beanbus . BusEvent ; import org . oddjob . beanbus . BusListener ; import org . oddjob . beanbus . CrashBusException ; import org . oddjob . beanbus . StageEvent ; import org . oddjob . beanbus . StageListener ; import org . oddjob . beanbus . StageNotifier ; import org . oddjob . io . BufferType ; import org . oddjob . io . CopyJob ; import org . oddjob . state . ParentState ; public class SQLResultsSheetTest extends TestCase { private static final Logger logger = Logger . getLogger ( SQLResultsSheetTest . class ) ; String EOL = System . getProperty ( "" ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } private class OurBus implements BeanBus { BusListener busListener ; StageListener stageListener ; @ Override public void addBusListener ( BusListener listener ) { assertNull ( this . busListener ) ; assertNotNull ( listener ) ; this . busListener = listener ; } @ Override public void addStageListener ( StageListener listener ) { assertNull ( this . stageListener ) ; assertNotNull ( listener ) ; this . stageListener = listener ; } @ Override public void removeBusListener ( BusListener listener ) { assertEquals ( this . busListener , listener ) ; assertNotNull ( listener ) ; this . busListener = null ; } @ Override public void removeStageListener ( StageListener listener ) { assertEquals ( this . stageListener , listener ) ; assertNotNull ( listener ) ; this . stageListener = null ; } @ Override public void run ( ) { throw new RuntimeException ( "" ) ; } @ Override public void stop ( ) { throw new RuntimeException ( "" ) ; } } private class OurStage implements StageNotifier { @ Override public void addStageListener ( StageListener listener ) { throw new RuntimeException ( "" ) ; } @ Override public void removeStageListener ( StageListener listener ) { throw new RuntimeException ( "" ) ; } } public void testNoHeaders ( ) throws BadBeanException , CrashBusException { SQLResultsSheet test = new SQLResultsSheet ( ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Object [ ] values = createFruit ( ) ; test . setOutput ( out ) ; test . setDataOnly ( true ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; OurBus bus = new OurBus ( ) ; OurStage stage = new OurStage ( ) ; test . setBus ( bus ) ; bus . busListener . busStarting ( new BusEvent ( bus ) ) ; bus . stageListener . stageStarting ( new StageEvent ( stage , "" ) ) ; test . accept ( Arrays . asList ( values ) ) ; bus . stageListener . stageComplete ( new StageEvent ( stage , "" ) ) ; bus . busListener . busStopping ( new BusEvent ( bus ) ) ; bus . busListener . busTerminated ( new BusEvent ( bus ) ) ; String expected = "" + EOL + "" + EOL ; assertEquals ( expected , out . toString ( ) ) ; assertNull ( bus . busListener ) ; assertNull ( bus . stageListener ) ; } private Object [ ] createFruit ( ) { Fruit fruit1 = new Fruit ( ) ; fruit1 . setType ( "" ) ; fruit1 . setVariety ( "" ) ; fruit1 . setColour ( "" ) ; fruit1 . setSize ( ) ; Fruit fruit2 = new Fruit ( ) ; fruit2 . setType ( "" ) ; fruit2 . setVariety ( "" ) ; fruit2 . setColour ( "" ) ; fruit2 . setSize ( ) ; return new Object [ ] { fruit1 , fruit2 } ; } public void testExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; BufferType buffer = new BufferType ( ) ; buffer . configured ( ) ; CopyJob copy = new CopyJob ( ) ; copy . setInput ( getClass ( ) . getResourceAsStream ( "" ) ) ; copy . setOutput ( buffer . toOutputStream ( ) ) ; copy . run ( ) ; String [ ] expected = buffer . getLines ( ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( expected . length , lines . length ) ; for ( int i = ; i < expected . length ; ++ i ) { assertTrue ( expected [ i ] + "" + lines [ i ] , lines [ i ] . trim ( ) . matches ( expected [ i ] . trim ( ) ) ) ; } oddjob . destroy ( ) ; } } package org . oddjob . sql ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . SimpleArooaClass ; public class ConnectionTypeTest extends TestCase { public void testSerialize ( ) throws Exception { ConnectionType test = new ConnectionType ( ) ; test . setUrl ( "" ) ; ConnectionType copy = ( ConnectionType ) Helper . copy ( test ) ; assertEquals ( "" , copy . getUrl ( ) ) ; } public void testIsClassLoaderAuto ( ) throws ArooaParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ArooaBeanDescriptor descriptor = session . getArooaDescriptor ( ) . getBeanDescriptor ( new SimpleArooaClass ( ConnectionType . class ) , session . getTools ( ) . getPropertyAccessor ( ) ) ; assertTrue ( descriptor . isAuto ( "" ) ) ; } public void testBadUrl ( ) { ConnectionType test = new ConnectionType ( ) ; test . setDriver ( "" ) ; test . setUrl ( "" ) ; test . setUsername ( "" ) ; test . setPassword ( "" ) ; try { test . toValue ( ) ; fail ( "" ) ; } catch ( ArooaConversionException e ) { assertTrue ( e . getMessage ( ) . startsWith ( "" ) ) ; } } public void testBadUrl2 ( ) { ConnectionType test = new ConnectionType ( ) ; test . setDriver ( "" ) ; test . setUrl ( "" ) ; test . setUsername ( "" ) ; test . setPassword ( "" ) ; try { test . toValue ( ) ; fail ( "" ) ; } catch ( ArooaConversionException e ) { assertTrue ( e . getMessage ( ) . startsWith ( "" ) ) ; } } } package org . oddjob . sql ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class DB2Test extends TestCase { public void testCallable ( ) throws ArooaPropertyException , ArooaConversionException { if ( System . getProperty ( "" ) == null ) { return ; } Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . sql ; import java . math . BigDecimal ; import java . sql . ResultSet ; import java . sql . ResultSetMetaData ; import java . sql . SQLException ; import java . sql . Statement ; import java . util . List ; import junit . framework . AssertionFailedError ; import junit . framework . TestCase ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . CrashBusException ; public class ParameterisedExecutorText extends TestCase { public void testHSQLDataTypes ( ) throws SQLException , ClassNotFoundException , ArooaConversionException { ConnectionType ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; Statement stmt = ct . toValue ( ) . createStatement ( ) ; String create = "" + "" + "" + "" + "" + "" + "" ; stmt . execute ( create ) ; String insert = "" ; stmt . execute ( insert ) ; String select = "" ; ResultSet rs = stmt . executeQuery ( select ) ; ResultSetMetaData md = rs . getMetaData ( ) ; int c = md . getColumnCount ( ) ; rs . next ( ) ; try { for ( int i = ; i <= c ; ++ i ) { assertEquals ( md . getColumnName ( i ) , Class . forName ( md . getColumnClassName ( i ) ) , rs . getObject ( i ) . getClass ( ) ) ; } } catch ( AssertionFailedError e ) { } stmt . execute ( "" ) ; } private class Results implements SQLResultsProcessor { Object last ; @ Override public void accept ( Object bean ) throws BadBeanException , CrashBusException { last = bean ; } } @ SuppressWarnings ( "" ) public void testBeanTypes ( ) throws BadBeanException , ArooaConversionException { ConnectionType ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; ParameterisedExecutor test = new ParameterisedExecutor ( ) ; test . setConnection ( ct . toValue ( ) ) ; StandardArooaSession session = new StandardArooaSession ( ) ; test . setArooaSession ( session ) ; Results results = new Results ( ) ; test . setResultProcessor ( results ) ; String create = "" + "" + "" + "" + "" + "" + "" ; test . accept ( create ) ; ValueType v1 = new ValueType ( ) ; v1 . setValue ( new ArooaObject ( "" ) ) ; ValueType v2 = new ValueType ( ) ; v2 . setValue ( new ArooaObject ( "" ) ) ; ValueType v3 = new ValueType ( ) ; v3 . setValue ( new ArooaObject ( "" ) ) ; ValueType v4 = new ValueType ( ) ; v4 . setValue ( new ArooaObject ( "" ) ) ; ValueType v5 = new ValueType ( ) ; v5 . setValue ( new ArooaObject ( "" ) ) ; ValueType v6 = new ValueType ( ) ; v6 . setValue ( new ArooaObject ( "" ) ) ; test . setParameters ( , v1 ) ; test . setParameters ( , v2 ) ; test . setParameters ( , v3 ) ; test . setParameters ( , v4 ) ; test . setParameters ( , v5 ) ; test . setParameters ( , v6 ) ; String insert = "" ; test . accept ( insert ) ; String select = "" ; test . accept ( select ) ; Object bean = ( ( List < Object > ) results . last ) . get ( ) ; PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; ArooaClass arooaClass = accessor . getClassName ( bean ) ; BeanOverview beanOverview = arooaClass . getBeanOverview ( accessor ) ; String [ ] props = beanOverview . getProperties ( ) ; assertEquals ( , props . length ) ; assertEquals ( Integer . class , beanOverview . getPropertyType ( "" ) ) ; assertEquals ( Integer . class , beanOverview . getPropertyType ( "" ) ) ; assertEquals ( Integer . class , beanOverview . getPropertyType ( "" ) ) ; assertEquals ( Long . class , beanOverview . getPropertyType ( "" ) ) ; assertEquals ( BigDecimal . class , beanOverview . getPropertyType ( "" ) ) ; assertEquals ( BigDecimal . class , beanOverview . getPropertyType ( "" ) ) ; test . accept ( "" ) ; } @ SuppressWarnings ( "" ) public void testNullParameter ( ) throws BadBeanException , ArooaConversionException { ConnectionType ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; ParameterisedExecutor test = new ParameterisedExecutor ( ) ; test . setConnection ( ct . toValue ( ) ) ; StandardArooaSession session = new StandardArooaSession ( ) ; test . setArooaSession ( session ) ; Results results = new Results ( ) ; test . setResultProcessor ( results ) ; String create = "" + "" ; test . accept ( create ) ; ValueType v1 = new ValueType ( ) ; test . setParameters ( , v1 ) ; String insert = "" ; test . accept ( insert ) ; String select = "" ; test . accept ( select ) ; Object bean = ( ( List < Object > ) results . last ) . get ( ) ; PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; assertEquals ( null , accessor . getProperty ( bean , "" ) ) ; test . accept ( "" ) ; } } package org . oddjob . sql ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . WaitJob ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateConditions ; public class SQLSilhouettesWithArchiveTest extends TestCase { private static final Logger logger = Logger . getLogger ( SQLSilhouettesWithArchiveTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . debug ( "" + getName ( ) + "" ) ; } public void testSimple ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object timer1 = lookup . lookup ( "" ) ; WaitJob wait1 = new WaitJob ( ) ; wait1 . setFor ( timer1 ) ; wait1 . setState ( StateConditions . COMPLETE ) ; wait1 . run ( ) ; Object timer2 = lookup . lookup ( "" ) ; WaitJob wait2 = new WaitJob ( ) ; wait2 . setFor ( timer2 ) ; wait2 . setState ( StateConditions . COMPLETE ) ; wait2 . run ( ) ; Object browser1 = lookup . lookup ( "" ) ; ( ( Runnable ) browser1 ) . run ( ) ; Object [ ] archives1 = Helper . getChildren ( browser1 ) ; assertEquals ( , archives1 . length ) ; ( ( Runnable ) archives1 [ ] ) . run ( ) ; Object [ ] silhouettes1 = Helper . getChildren ( archives1 [ ] ) ; assertEquals ( , silhouettes1 . length ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( silhouettes1 [ ] ) ) ; Object browser2 = lookup . lookup ( "" ) ; ( ( Runnable ) browser2 ) . run ( ) ; Object [ ] archives2 = Helper . getChildren ( browser2 ) ; assertEquals ( , archives2 . length ) ; ( ( Runnable ) archives2 [ ] ) . run ( ) ; Object [ ] silhouettes2 = Helper . getChildren ( archives2 [ ] ) ; assertEquals ( , silhouettes2 . length ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( silhouettes2 [ ] ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . sql ; import java . sql . SQLException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . BufferType ; import org . oddjob . persist . OddjobPersister ; import org . oddjob . persist . SilhouetteFactory ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class SQLSilhouettesServiceTest extends TestCase { private static final Logger logger = Logger . getLogger ( SQLSilhouettesServiceTest . class ) ; ConnectionType ct ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" + "" + "" + "" + "" ) ; buffer . configured ( ) ; SQLJob sql = new SQLJob ( ) ; sql . setArooaSession ( new StandardArooaSession ( ) ) ; sql . setInput ( buffer . toInputStream ( ) ) ; sql . setConnection ( ct . toValue ( ) ) ; sql . run ( ) ; } @ Override protected void tearDown ( ) throws Exception { BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; SQLJob sql = new SQLJob ( ) ; sql . setArooaSession ( new StandardArooaSession ( ) ) ; sql . setInput ( buffer . toInputStream ( ) ) ; sql . setConnection ( ct . toValue ( ) ) ; sql . run ( ) ; } public static class SessionCapture implements ArooaSessionAware { ArooaSession arooaSession ; @ Override public void setArooaSession ( ArooaSession session ) { this . arooaSession = session ; } public ArooaSession getArooaSession ( ) { return arooaSession ; } } public void testArchiveAndRestore ( ) throws ArooaPropertyException , ArooaConversionException , SQLException , ComponentPersistException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; SQLPersisterService test = new SQLPersisterService ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . start ( ) ; OddjobPersister archiver = test . getPersister ( null ) ; ComponentPersister persister = archiver . persisterFor ( null ) ; ArooaSession session = lookup . lookup ( "" , ArooaSession . class ) ; Object silhouette = new SilhouetteFactory ( ) . create ( lookup . lookup ( "" ) , session ) ; persister . persist ( "" , silhouette , session ) ; oddjob . destroy ( ) ; ArooaSession session2 = new OddjobSessionFactory ( ) . createSession ( ) ; Object [ ] archives = persister . list ( ) ; assertEquals ( , archives . length ) ; assertEquals ( "" , archives [ ] ) ; Object restored = persister . restore ( "" , getClass ( ) . getClassLoader ( ) , session2 ) ; assertNotNull ( restored ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( restored ) ) ; Object [ ] children = Helper . getChildren ( ( Structural ) restored ) ; assertEquals ( , children . length ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( children [ ] ) ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( children [ ] ) ) ; test . stop ( ) ; } } package org . oddjob . sql ; import java . io . Serializable ; import java . sql . Blob ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . io . BufferType ; import org . oddjob . persist . SerializeWithBinaryStream ; import org . oddjob . persist . SerializeWithBytes ; public class HSQLAssumptionsTest extends TestCase { private static final Logger logger = Logger . getLogger ( HSQLAssumptionsTest . class ) ; ConnectionType ct ; @ Override protected void setUp ( ) throws Exception { ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" + "" + "" + "" + "" ) ; buffer . configured ( ) ; SQLJob sql = new SQLJob ( ) ; sql . setArooaSession ( new StandardArooaSession ( ) ) ; sql . setInput ( buffer . toInputStream ( ) ) ; sql . setConnection ( ct . toValue ( ) ) ; sql . run ( ) ; } @ Override protected void tearDown ( ) throws Exception { BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; SQLJob sql = new SQLJob ( ) ; sql . setArooaSession ( new StandardArooaSession ( ) ) ; sql . setInput ( buffer . toInputStream ( ) ) ; sql . setConnection ( ct . toValue ( ) ) ; sql . run ( ) ; } public static class BigThing implements Serializable { private static final long serialVersionUID = ; byte [ ] bigArray = new byte [ ] ; } public void testBytes ( ) throws SQLException , ArooaConversionException { Connection connection = ct . toValue ( ) ; PreparedStatement insert = connection . prepareStatement ( "" + "" ) ; Object job = new BigThing ( ) ; byte [ ] bytes = new SerializeWithBytes ( ) . toBytes ( job ) ; logger . debug ( "" + bytes . length + "" ) ; insert . setString ( , "" ) ; insert . setBlob ( , new SerializeWithBinaryStream ( ) . toStream ( job ) ) ; insert . setBytes ( , bytes ) ; insert . executeUpdate ( ) ; PreparedStatement select = connection . prepareStatement ( "" ) ; select . setString ( , "" ) ; ResultSet rs = select . executeQuery ( ) ; assertTrue ( rs . next ( ) ) ; byte [ ] bytesCopy = rs . getBytes ( ) ; Object copy1 = new SerializeWithBytes ( ) . fromBytes ( bytesCopy , getClass ( ) . getClassLoader ( ) ) ; assertNotNull ( copy1 ) ; Blob blob = rs . getBlob ( ) ; Object copy2 = new SerializeWithBinaryStream ( ) . fromStream ( blob . getBinaryStream ( ) , getClass ( ) . getClassLoader ( ) ) ; assertNotNull ( copy2 ) ; insert . close ( ) ; select . close ( ) ; connection . close ( ) ; } } package org . oddjob . sql ; import java . io . ByteArrayInputStream ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; public class SQLScriptProcessorTest extends TestCase { String EOL = System . getProperty ( "" ) ; class SqlCapture implements SQLExecutor { List < String > results = new ArrayList < String > ( ) ; @ Override public void accept ( String sql ) { String s = sql . trim ( ) ; if ( s . length ( ) > ) { results . add ( s ) ; } } } public void testStandardDelimiter ( ) throws Exception { String script = EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL + "" + EOL ; ScriptParser test = new ScriptParser ( ) ; SqlCapture capture = new SqlCapture ( ) ; test . setInput ( new ByteArrayInputStream ( script . getBytes ( ) ) ) ; test . setTo ( capture ) ; test . go ( ) ; assertEquals ( , capture . results . size ( ) ) ; assertEquals ( "" , capture . results . get ( ) ) ; assertEquals ( "" , capture . results . get ( ) ) ; } } package org . oddjob . sql ; import java . io . ByteArrayInputStream ; import java . sql . Connection ; import java . sql . SQLException ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class SQLParametersTest extends TestCase { public void testSomeInserts ( ) throws SQLException , ArooaPropertyException , ArooaConversionException { ConnectionType connection = new ConnectionType ( ) ; connection . setDriver ( "" ) ; connection . setUrl ( "" ) ; connection . setUsername ( "" ) ; Connection keepAlive = connection . toValue ( ) ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setExport ( "" , connection ) ; oddjob . setExport ( "" , new ArooaObject ( "" ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; int count = new OddjobLookup ( oddjob ) . lookup ( "" , Integer . class ) ; assertEquals ( , count ) ; keepAlive . close ( ) ; oddjob . destroy ( ) ; } public void testInsertsMultipleStatements ( ) throws SQLException , ArooaPropertyException , ArooaConversionException { ConnectionType connection = new ConnectionType ( ) ; connection . setDriver ( "" ) ; connection . setUrl ( "" ) ; connection . setUsername ( "" ) ; String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setExport ( "" , connection ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; int count = new OddjobLookup ( oddjob ) . lookup ( "" , Integer . class ) ; assertEquals ( , count ) ; int sum = new OddjobLookup ( oddjob ) . lookup ( "" , Integer . class ) ; assertEquals ( , sum ) ; oddjob . destroy ( ) ; } public void testCallable ( ) throws SQLException , ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Integer a = lookup . lookup ( "" , Integer . class ) ; Integer b = lookup . lookup ( "" , Integer . class ) ; assertEquals ( new Integer ( ) , a ) ; assertEquals ( new Integer ( ) , b ) ; a = lookup . lookup ( "" , Integer . class ) ; b = lookup . lookup ( "" , Integer . class ) ; assertNull ( a ) ; assertNull ( b ) ; Connection connection = new OddjobLookup ( oddjob ) . lookup ( "" , Connection . class ) ; SQLJob shutdown = new SQLJob ( ) ; shutdown . setArooaSession ( new StandardArooaSession ( ) ) ; shutdown . setConnection ( connection ) ; shutdown . setInput ( new ByteArrayInputStream ( "" . getBytes ( ) ) ) ; shutdown . run ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . sql ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class MySQLTest extends TestCase { public void testCallable ( ) throws ArooaPropertyException , ArooaConversionException { if ( System . getProperty ( "" ) == null ) { return ; } Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; assertEquals ( new Integer ( ) , lookup . lookup ( "" , Integer . class ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . sql ; import java . io . InputStream ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . BufferType ; import org . oddjob . io . StdoutType ; import org . oddjob . state . ParentState ; public class SQLScriptJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( SQLScriptJobTest . class ) ; protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; } String EOL = System . getProperty ( "" ) ; public void testSql ( ) throws Exception { ConnectionType ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" + EOL + "" + EOL + "" + EOL + "" ) ; buffer . configured ( ) ; SQLJob test = new SQLJob ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . run ( ) ; SQLJob results = new SQLJob ( ) ; SQLResultsBean beans = new SQLResultsBean ( ) ; results . setResults ( beans ) ; results . setArooaSession ( new StandardArooaSession ( ) ) ; results . setConnection ( ct . toValue ( ) ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; results . setInput ( buffer . toInputStream ( ) ) ; results . run ( ) ; assertEquals ( "" , ( ( DynaBean ) beans . getRows ( ) [ ] ) . get ( "" ) ) ; assertEquals ( "" , ( ( DynaBean ) beans . getRows ( ) [ ] ) . get ( "" ) ) ; } public void testInOddjob ( ) throws Exception { ConnectionType ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; SQLJob test ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test = new SQLJob ( ) ; test . setConnection ( ct . toValue ( ) ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . run ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getResourceAsStream ( "" ) ) ) ; oj . run ( ) ; test = new SQLJob ( ) ; test . setConnection ( ct . toValue ( ) ) ; buffer . setText ( "" + "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setResults ( new SQLResultsBean ( ) ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . run ( ) ; assertEquals ( new Integer ( ) , PropertyUtils . getProperty ( test , "" ) ) ; } public void testSqlResultsSheet ( ) throws Exception { StdoutType out = new StdoutType ( ) ; InputStream input = getClass ( ) . getResourceAsStream ( "" ) ; assertNotNull ( input ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , input ) ) ; oddjob . setExport ( "" , out ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . sql ; import junit . framework . TestCase ; public class SQLBuilderTest extends TestCase { String EOL = System . getProperty ( "" ) ; public void testLineFeedTest ( ) { String sql = "" + EOL + "" + EOL + "" ; SQLBuilder test = new SQLBuilder ( ) ; test . append ( sql ) ; assertEquals ( "" , test . toString ( ) ) ; } } package org . oddjob . sql ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . beanbus . BadBeanException ; import org . oddjob . beanbus . CrashBusException ; import junit . framework . TestCase ; public class SQLResultBeansTest extends TestCase { public void testRows ( ) throws BadBeanException , CrashBusException { List < String > list = new ArrayList < String > ( ) ; list . add ( "" ) ; list . add ( "" ) ; SQLResultsBean test = new SQLResultsBean ( ) ; test . accept ( list ) ; Object [ ] row = test . getRows ( ) ; assertEquals ( "" , row [ ] ) ; assertEquals ( "" , row [ ] ) ; } public void testEmptyRows ( ) throws BadBeanException , CrashBusException { List < String > list = new ArrayList < String > ( ) ; SQLResultsBean test = new SQLResultsBean ( ) ; test . accept ( list ) ; Object [ ] row = test . getRows ( ) ; assertEquals ( , row . length ) ; } } package org . oddjob . sql ; import java . text . ParseException ; import junit . framework . TestCase ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . values . types . DateType ; public class SQLConversionsTest extends TestCase { public void testDateConversions ( ) throws ArooaParseException , NoConversionAvailableException , ConversionFailedException , ParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; DateType date = new DateType ( ) ; date . setDate ( "" ) ; date . setFormat ( "" ) ; long expected = date . toDate ( ) . getTime ( ) ; java . sql . Date sqlDate = converter . convert ( date , java . sql . Date . class ) ; java . sql . Time time = converter . convert ( date , java . sql . Time . class ) ; java . sql . Timestamp timestamp = converter . convert ( date , java . sql . Timestamp . class ) ; assertEquals ( expected , sqlDate . getTime ( ) ) ; assertEquals ( expected , time . getTime ( ) ) ; assertEquals ( expected , timestamp . getTime ( ) ) ; } } package org . oddjob . sql ; import java . io . IOException ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . beanbus . BeanTrap ; import org . oddjob . beanbus . BusException ; import org . oddjob . io . BufferType ; import org . oddjob . sql . SQLJob . DelimiterType ; public class SQLScriptParserTest extends TestCase { public void testNoDelimiter ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testOneEmptyLine ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testLotsOfEmptyLines ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testWindowsLines ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testComments ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testDefaultDelimited ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testNonRowDelimiterOnSeperateLine ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; test . setDelimiter ( "" ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" + "" + "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testGoDelimiter ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; test . setDelimiter ( "" ) ; test . setDelimiterType ( DelimiterType . ROW ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testGoDelimiterWithBlankLines ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; test . setDelimiter ( "" ) ; test . setDelimiterType ( DelimiterType . ROW ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } public void testGoDelimiterWithBlankLines2 ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; test . setDelimiter ( "" ) ; test . setDelimiterType ( DelimiterType . ROW ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( , stmts . size ( ) ) ; } public void testGoDelimiterWithMultipleLines ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; test . setDelimiter ( "" ) ; test . setDelimiterType ( DelimiterType . ROW ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; assertEquals ( , stmts . size ( ) ) ; } public void testReplaceProperties ( ) throws IOException , BusException { BeanTrap < String > results = new BeanTrap < String > ( ) ; ScriptParser test = new ScriptParser ( ) ; test . setExpandProperties ( true ) ; StandardArooaSession session = new StandardArooaSession ( ) ; session . getBeanRegistry ( ) . register ( "" , "" ) ; test . setArooaSession ( session ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; test . setInput ( buffer . toInputStream ( ) ) ; test . setTo ( results ) ; test . go ( ) ; List < String > stmts = results . toValue ( ) ; assertEquals ( , stmts . size ( ) ) ; assertEquals ( "" , stmts . get ( ) ) ; } } package org . oddjob . sql ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . BufferType ; import org . oddjob . jobs . WaitJob ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . State ; import org . oddjob . state . StateConditions ; public class GrabbingWithSQLTest extends TestCase { private static final Logger logger = Logger . getLogger ( GrabbingWithSQLTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; } @ Override protected void tearDown ( ) throws Exception { ConnectionType ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; SQLJob sql = new SQLJob ( ) ; sql . setArooaSession ( new StandardArooaSession ( ) ) ; sql . setInput ( buffer . toInputStream ( ) ) ; sql . setConnection ( ct . toValue ( ) ) ; sql . run ( ) ; } public void testSimpleExample ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful grabbers = lookup . lookup ( "" , Stateful . class ) ; WaitJob wait = new WaitJob ( ) ; wait . setState ( StateConditions . COMPLETE ) ; wait . setFor ( grabbers ) ; wait . run ( ) ; Stateful echo1 = lookup . lookup ( "" , Stateful . class ) ; Stateful echo2 = lookup . lookup ( "" , Stateful . class ) ; State echo1State = echo1 . lastStateEvent ( ) . getState ( ) ; State echo2State = echo2 . lastStateEvent ( ) . getState ( ) ; assertTrue ( echo1State == JobState . COMPLETE && echo2State == JobState . READY || echo1State == JobState . READY && echo2State == JobState . COMPLETE ) ; ( ( Resetable ) grabbers ) . hardReset ( ) ; ( ( Runnable ) grabbers ) . run ( ) ; wait . hardReset ( ) ; wait . run ( ) ; echo1State = echo1 . lastStateEvent ( ) . getState ( ) ; echo2State = echo2 . lastStateEvent ( ) . getState ( ) ; assertTrue ( echo1State == JobState . READY && echo2State == JobState . READY ) ; Object sequenceJob = lookup . lookup ( "" ) ; ( ( Resetable ) sequenceJob ) . hardReset ( ) ; ( ( Runnable ) sequenceJob ) . run ( ) ; ( ( Resetable ) grabbers ) . hardReset ( ) ; ( ( Runnable ) grabbers ) . run ( ) ; wait . hardReset ( ) ; wait . run ( ) ; echo1State = echo1 . lastStateEvent ( ) . getState ( ) ; echo2State = echo2 . lastStateEvent ( ) . getState ( ) ; assertTrue ( echo1State == JobState . COMPLETE && echo2State == JobState . READY || echo1State == JobState . READY && echo2State == JobState . COMPLETE ) ; oddjob . destroy ( ) ; } public void testFailedWinner ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful grabber1 = lookup . lookup ( "" , Stateful . class ) ; Stateful grabber2 = lookup . lookup ( "" , Stateful . class ) ; Stateful winner = null ; while ( true ) { State grabber1State = grabber1 . lastStateEvent ( ) . getState ( ) ; State grabber2State = grabber2 . lastStateEvent ( ) . getState ( ) ; if ( grabber1State == JobState . INCOMPLETE && grabber2State == JobState . EXECUTING ) { winner = grabber1 ; break ; } if ( grabber2State == JobState . INCOMPLETE && grabber1State == JobState . EXECUTING ) { winner = grabber2 ; break ; } logger . info ( "" + grabber1State + "" + grabber2State ) ; Thread . sleep ( ) ; } DynaBean variables = lookup . lookup ( "" , DynaBean . class ) ; variables . set ( "" , new ArooaObject ( "" ) ) ; ( ( Resetable ) winner ) . softReset ( ) ; ( ( Runnable ) winner ) . run ( ) ; Stateful grabbers = lookup . lookup ( "" , Stateful . class ) ; WaitJob wait = new WaitJob ( ) ; wait . setState ( StateConditions . COMPLETE ) ; wait . setFor ( grabbers ) ; wait . run ( ) ; oddjob . destroy ( ) ; } public void testStoppingGrabber ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful grabber1 = lookup . lookup ( "" , Stateful . class ) ; Stateful grabber2 = lookup . lookup ( "" , Stateful . class ) ; Stateful looser = null ; while ( true ) { State grabber1State = grabber1 . lastStateEvent ( ) . getState ( ) ; State grabber2State = grabber2 . lastStateEvent ( ) . getState ( ) ; int looserPollingCount = lookup . lookup ( "" , int . class ) ; if ( grabber1State == JobState . INCOMPLETE && looserPollingCount == ) { looser = grabber2 ; break ; } if ( grabber2State == JobState . INCOMPLETE && looserPollingCount == ) { looser = grabber1 ; break ; } logger . info ( "" + grabber1State + "" + grabber2State ) ; Thread . sleep ( ) ; } assertEquals ( JobState . EXECUTING , looser . lastStateEvent ( ) . getState ( ) ) ; ( ( Stoppable ) looser ) . stop ( ) ; Stateful grabbers = lookup . lookup ( "" , Stateful . class ) ; WaitJob wait = new WaitJob ( ) ; wait . setState ( StateConditions . INCOMPLETE ) ; wait . setFor ( grabbers ) ; wait . run ( ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( JobState . INCOMPLETE , looser . lastStateEvent ( ) . getState ( ) ) ; oddjob . stop ( ) ; oddjob . destroy ( ) ; } public void testStoppingService ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful grabber1 = lookup . lookup ( "" , Stateful . class ) ; Stateful grabber2 = lookup . lookup ( "" , Stateful . class ) ; Stateful looser = null ; while ( true ) { State grabber1State = grabber1 . lastStateEvent ( ) . getState ( ) ; State grabber2State = grabber2 . lastStateEvent ( ) . getState ( ) ; int looserPollingCount = lookup . lookup ( "" , int . class ) ; if ( grabber1State == JobState . INCOMPLETE && looserPollingCount == ) { looser = grabber2 ; break ; } if ( grabber2State == JobState . INCOMPLETE && looserPollingCount == ) { looser = grabber1 ; break ; } logger . info ( "" + grabber1State + "" + grabber2State ) ; Thread . sleep ( ) ; } assertEquals ( JobState . EXECUTING , looser . lastStateEvent ( ) . getState ( ) ) ; Stoppable keeperService = lookup . lookup ( "" , Stoppable . class ) ; keeperService . stop ( ) ; Stateful grabbers = lookup . lookup ( "" , Stateful . class ) ; WaitJob wait = new WaitJob ( ) ; wait . setState ( StateConditions . INCOMPLETE ) ; wait . setFor ( grabbers ) ; wait . run ( ) ; assertEquals ( , lookup . lookup ( "" ) ) ; assertEquals ( JobState . INCOMPLETE , looser . lastStateEvent ( ) . getState ( ) ) ; oddjob . stop ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . sql ; import java . sql . Connection ; import java . sql . SQLException ; import java . util . Date ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . io . BufferType ; public class SQLClockTest extends TestCase { private static final Logger logger = Logger . getLogger ( SQLClockTest . class ) ; ConnectionType ct ; @ Override protected void setUp ( ) throws Exception { ct = new ConnectionType ( ) ; ct . setDriver ( "" ) ; ct . setUrl ( "" ) ; ct . setUsername ( "" ) ; ct . setPassword ( "" ) ; } @ Override protected void tearDown ( ) throws Exception { BufferType buffer = new BufferType ( ) ; buffer . setText ( "" ) ; buffer . configured ( ) ; SQLJob sql = new SQLJob ( ) ; sql . setArooaSession ( new StandardArooaSession ( ) ) ; sql . setInput ( buffer . toInputStream ( ) ) ; sql . setConnection ( ct . toValue ( ) ) ; sql . run ( ) ; } public void testGetTime ( ) throws SQLException , ArooaConversionException { Connection c = ct . toValue ( ) ; SQLClock test = new SQLClock ( ) ; test . setConnection ( c ) ; test . start ( ) ; Date date = test . getClock ( ) . getDate ( ) ; assertNotNull ( date ) ; logger . info ( date ) ; test . stop ( ) ; } } package org . oddjob . sql ; import java . io . File ; import java . io . Serializable ; import java . net . URL ; import java . sql . Connection ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class SQLPersisterTest extends TestCase { private static final Logger logger = Logger . getLogger ( SQLPersisterTest . class ) ; public static class Sample implements Serializable { private static final long serialVersionUID = ; String value ; } public void testSql ( ) throws Exception { Oddjob setUp = new Oddjob ( ) ; setUp . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getResourceAsStream ( "" ) ) ) ; setUp . run ( ) ; assertEquals ( ParentState . COMPLETE , setUp . lastStateEvent ( ) . getState ( ) ) ; ConnectionType connection = new OddjobLookup ( setUp ) . lookup ( "" , ConnectionType . class ) ; SQLPersisterService test = new SQLPersisterService ( ) ; test . setConnection ( connection . toValue ( ) ) ; test . start ( ) ; Sample sample = new Sample ( ) ; String text = "" ; sample . value = text ; StandardArooaSession session = new StandardArooaSession ( ) ; ComponentPersister persister = test . getPersister ( "" ) . persisterFor ( "" ) ; persister . persist ( "" , sample , session ) ; Object o = persister . restore ( "" , getClass ( ) . getClassLoader ( ) , session ) ; assertNotNull ( o ) ; assertEquals ( Sample . class , o . getClass ( ) ) ; Sample copy = ( Sample ) o ; logger . debug ( copy . value ) ; assertEquals ( text , copy . value ) ; test . stop ( ) ; Connection c = connection . toValue ( ) ; c . createStatement ( ) . execute ( "" ) ; c . close ( ) ; } public void testInOddjob ( ) throws Exception { Oddjob setUp = new Oddjob ( ) ; setUp . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getResourceAsStream ( "" ) ) ) ; setUp . run ( ) ; assertEquals ( ParentState . COMPLETE , setUp . lastStateEvent ( ) . getState ( ) ) ; URL url = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; File file = new File ( url . toURI ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setFile ( file ) ; StateSteps oddjobState = new StateSteps ( oddjob ) ; oddjobState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oddjob . run ( ) ; oddjobState . checkNow ( ) ; Object echoJob = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , PropertyUtils . getProperty ( echoJob , "" ) ) ; oddjob . destroy ( ) ; Oddjob oj2 = new Oddjob ( ) ; StateSteps oddjobState2 = new StateSteps ( oj2 ) ; oddjobState2 . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oj2 . setFile ( file ) ; oj2 . hardReset ( ) ; oj2 . run ( ) ; oddjobState2 . checkNow ( ) ; assertEquals ( "" , PropertyUtils . getProperty ( new OddjobLookup ( oj2 ) . lookup ( "" ) , "" ) ) ; oj2 . destroy ( ) ; new OddjobLookup ( setUp ) . lookup ( "" , Connection . class ) . createStatement ( ) . execute ( "" ) ; } } package org . oddjob . util ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ClassLoaderDiagnosticsTest extends TestCase { public void testResource ( ) { ClassLoaderDiagnostics test = new ClassLoaderDiagnostics ( ) ; test . setResource ( "" ) ; test . run ( ) ; assertTrue ( test . getLocation ( ) . contains ( "" ) ) ; } public void testClassName ( ) { ClassLoaderDiagnostics test = new ClassLoaderDiagnostics ( ) ; test . setClassName ( Oddjob . class . getName ( ) ) ; test . run ( ) ; assertTrue ( test . getLocation ( ) . contains ( "" ) ) ; } public void testExample ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; String loc1 = lookup . lookup ( "" , String . class ) ; String loc2 = lookup . lookup ( "" , String . class ) ; assertNotNull ( loc1 ) ; assertNotNull ( loc2 ) ; } } package org . oddjob . util ; public class MockThreadManager implements ThreadManager { public String [ ] activeDescriptions ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public ClassLoader getClassLoader ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void run ( Runnable runnable , String description ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void setClassLoader ( ClassLoader classLoader ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void close ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . util ; import java . io . File ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLClassLoader ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; import org . oddjob . Structural ; import org . oddjob . oddballs . BuildOddballs ; public class ClassLoaderSorterTest extends TestCase { class OurInvocationHandler implements InvocationHandler { @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return new RuntimeException ( "" ) ; } } public void testLoad ( ) throws MalformedURLException , ClassNotFoundException , SecurityException , NoSuchMethodException , IllegalArgumentException , IllegalAccessException , InvocationTargetException { new BuildOddballs ( ) . run ( ) ; OurDirs dirs = new OurDirs ( ) ; URLClassLoader specialLoader = new URLClassLoader ( new URL [ ] { new File ( dirs . base ( ) + "" ) . toURI ( ) . toURL ( ) } ) ; Class < ? > fruitClass = Class . forName ( "" , true , specialLoader ) ; ClassLoader test = new ClassLoaderSorter ( ) . getTopLoader ( new Class < ? > [ ] { String . class , fruitClass , Structural . class } ) ; Class < ? > result = Class . forName ( "" , true , test ) ; assertEquals ( specialLoader , result . getClassLoader ( ) ) ; Object proxy = Proxy . newProxyInstance ( test , new Class < ? > [ ] { fruitClass , Structural . class } , new OurInvocationHandler ( ) ) ; assertTrue ( fruitClass . isInstance ( proxy ) ) ; } public void testStructural ( ) throws MalformedURLException , ClassNotFoundException { ClassLoader test = new ClassLoaderSorter ( ) . getTopLoader ( new Class < ? > [ ] { Structural . class } ) ; Object proxy = Proxy . newProxyInstance ( test , new Class < ? > [ ] { Structural . class } , new OurInvocationHandler ( ) ) ; assertTrue ( Structural . class . isInstance ( proxy ) ) ; } } package org . oddjob . util ; import java . io . File ; import java . io . IOException ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . net . URISyntaxException ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . io . FilesType ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . tools . CompileJob ; public class URLClassLoaderTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( URLClassLoaderTypeTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . debug ( "" + getName ( ) + "" ) ; logger . debug ( "" + ClassLoader . getSystemClassLoader ( ) + "" + Thread . currentThread ( ) . getContextClassLoader ( ) ) ; ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( cl instanceof URLClassLoader ) { URL [ ] urls = ( ( URLClassLoader ) cl ) . getURLs ( ) ; logger . debug ( "" + Arrays . toString ( urls ) ) ; } } public void testLoadMixedJob ( ) throws Exception { ClassLoader existingContextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; OurDirs dirs = new OurDirs ( ) ; File check = dirs . relative ( "" ) ; if ( ! check . exists ( ) ) { compileSample ( dirs ) ; } URLClassLoaderType test = new URLClassLoaderType ( ) ; test . setFiles ( new File [ ] { dirs . relative ( "" ) } ) ; test . setParent ( getClass ( ) . getClassLoader ( ) ) ; assertEquals ( "" + dirs . relative ( "" ) . toString ( ) + "" , test . toString ( ) ) ; ClassLoader classLoader = test . toValue ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setClassLoader ( classLoader ) ; String xml = "" + "" + "" + "" + "" ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ClassLoader classLoaderWhenRunning = lookup . lookup ( "" , ClassLoader . class ) ; ClassLoader jobClassLoader = lookup . lookup ( "" , ClassLoader . class ) ; assertEquals ( classLoader , jobClassLoader ) ; assertEquals ( classLoader , classLoaderWhenRunning ) ; assertEquals ( existingContextClassLoader , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; } static public void compileSample ( final OurDirs dirs ) { File dir = dirs . relative ( "" ) ; if ( new File ( dir , "" ) . exists ( ) ) { return ; } FilesType sources = new FilesType ( ) ; sources . setFiles ( dirs . relative ( "" ) . getPath ( ) + File . separator + "" ) ; CompileJob compile = new CompileJob ( ) ; compile . setFiles ( sources . toFiles ( ) ) ; compile . run ( ) ; if ( compile . getResult ( ) != ) { throw new RuntimeException ( "" ) ; } } public void testInOddjob ( ) throws URISyntaxException { OurDirs dirs = new OurDirs ( ) ; compileSample ( dirs ) ; URL url = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; File file = new File ( url . toURI ( ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . getAbsolutePath ( ) } ) ; oddjob . setFile ( file ) ; oddjob . run ( ) ; Object aJob = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( "" , aJob . getClass ( ) . getName ( ) ) ; } public void testNoParent ( ) { URLClassLoaderType test = new URLClassLoaderType ( ) ; test . setFiles ( new File [ ] { } ) ; test . setNoInherit ( true ) ; ClassLoader loader = test . toValue ( ) ; assertNull ( loader . getParent ( ) ) ; } class LogCatcher implements LogListener { List < String > lines = new ArrayList < String > ( ) ; public void logEvent ( LogEvent logEvent ) { lines . add ( logEvent . getMessage ( ) ) ; } } static String EOL = System . getProperty ( "" ) ; public void testFromLaunchJar ( ) throws SecurityException , NoSuchMethodException , ClassNotFoundException , IllegalArgumentException , IllegalAccessException , InvocationTargetException , IOException { OurDirs dirs = new OurDirs ( ) ; File check = dirs . relative ( "" ) ; if ( ! check . exists ( ) ) { compileSample ( dirs ) ; } File oddjobFile = dirs . relative ( "" ) ; URLClassLoaderType first = new URLClassLoaderType ( ) ; first . setFiles ( new File [ ] { dirs . relative ( "" ) } ) ; first . setNoInherit ( true ) ; ClassLoader loader = first . toValue ( ) ; Class < ? > launcher = loader . loadClass ( "" ) ; Method m = launcher . getMethod ( "" , String [ ] . class ) ; String [ ] args = new String [ ] { "" , oddjobFile . getCanonicalPath ( ) } ; LogCatcher log = new LogCatcher ( ) ; Oddjob . CONSOLE . addListener ( log , LogLevel . INFO , - , ) ; m . invoke ( null , ( Object ) args ) ; Oddjob . CONSOLE . removeListener ( log ) ; System . out . println ( "" ) ; for ( String line : log . lines ) { System . out . print ( line ) ; } System . out . println ( "" ) ; assertEquals ( "" + EOL , log . lines . get ( ) ) ; } } package org . oddjob . util ; import java . util . concurrent . Exchanger ; import java . util . concurrent . atomic . AtomicInteger ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; public class SimpleThreadManagerTest extends TestCase { private static final Logger logger = Logger . getLogger ( SimpleThreadManagerTest . class ) ; class OurThing implements Runnable { Exchanger < Void > exchanger = new Exchanger < Void > ( ) ; boolean interrupted ; public void meet ( ) throws InterruptedException { exchanger . exchange ( null ) ; } @ Override public void run ( ) { try { meet ( ) ; meet ( ) ; } catch ( InterruptedException e ) { interrupted = true ; Thread . currentThread ( ) . interrupt ( ) ; } } } public void testSimpleRun ( ) throws InterruptedException { SimpleThreadManager test = new SimpleThreadManager ( ) ; OurThing thing = new OurThing ( ) ; test . run ( thing , "" ) ; String [ ] descriptions = test . activeDescriptions ( ) ; assertEquals ( , descriptions . length ) ; assertEquals ( "" , descriptions [ ] ) ; thing . meet ( ) ; thing . meet ( ) ; while ( test . activeDescriptions ( ) . length > ) { logger . info ( "" ) ; Thread . sleep ( ) ; } test . close ( ) ; assertFalse ( thing . interrupted ) ; } public void testStopAll ( ) throws InterruptedException { SimpleThreadManager test = new SimpleThreadManager ( ) ; OurThing thing = new OurThing ( ) ; test . run ( thing , "" ) ; String [ ] descriptions = test . activeDescriptions ( ) ; assertEquals ( , descriptions . length ) ; assertEquals ( "" , descriptions [ ] ) ; thing . meet ( ) ; test . close ( ) ; while ( test . activeDescriptions ( ) . length > ) { logger . info ( "" ) ; Thread . sleep ( ) ; } assertTrue ( thing . interrupted ) ; } public void testLotsOfThings ( ) throws InterruptedException { final SimpleThreadManager test = new SimpleThreadManager ( ) ; final AtomicInteger ran = new AtomicInteger ( ) ; for ( int i = ; i < ; ++ i ) { final int fi = i ; test . run ( new Runnable ( ) { @ Override public void run ( ) { test . run ( new Runnable ( ) { @ Override public void run ( ) { ran . incrementAndGet ( ) ; } } , "" + fi ) ; } } , "" + i ) ; } while ( true ) { String [ ] descriptions = test . activeDescriptions ( ) ; if ( descriptions . length == ) { break ; } for ( int i = ; i < descriptions . length ; ++ i ) { logger . info ( "" + descriptions [ i ] ) ; } Thread . sleep ( ) ; } assertEquals ( , ran . intValue ( ) ) ; test . close ( ) ; } } package org . oddjob . launch ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . logging . ConsoleOwner ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class PathParserLaunchTest extends TestCase { final static String RUN_JAR = "" ; @ Override protected void setUp ( ) throws Exception { File built = new File ( new OurDirs ( ) . base ( ) , RUN_JAR ) ; assertTrue ( built . exists ( ) ) ; } public static class Test implements Runnable { public void run ( ) { System . out . println ( "" ) ; } } private class LogCatcher implements LogListener { List < String > lines = new ArrayList < String > ( ) ; public void logEvent ( LogEvent logEvent ) { lines . add ( logEvent . getMessage ( ) ) ; } } static String EOL = System . getProperty ( "" ) ; public void testWithLaunch ( ) throws ArooaConversionException , IOException { OurDirs dirs = new OurDirs ( ) ; File buildTest = new File ( dirs . base ( ) , "" ) ; assertTrue ( "" , buildTest . exists ( ) ) ; String xml = "" + "" + "" + "" + new File ( dirs . base ( ) , RUN_JAR ) . getPath ( ) + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . toString ( ) } ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; ConsoleOwner archive = new OddjobLookup ( oddjob ) . lookup ( "" , ConsoleOwner . class ) ; LogCatcher log = new LogCatcher ( ) ; archive . consoleLog ( ) . addListener ( log , LogLevel . INFO , - , ) ; System . out . println ( "" ) ; for ( String line : log . lines ) { System . out . print ( line ) ; } assertTrue ( log . lines . get ( ) . contains ( new File ( dirs . base ( ) , "" ) . getCanonicalPath ( ) ) ) ; assertEquals ( dirs . base ( ) . toString ( ) , log . lines . get ( ) . trim ( ) ) ; assertEquals ( "" + EOL , log . lines . get ( ) ) ; } } package org . oddjob . launch ; import java . io . File ; import java . io . IOException ; import java . util . Arrays ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; public class FileSpecTest extends TestCase { private static final Logger logger = Logger . getLogger ( FileSpecTest . class ) ; public void testMatch ( ) { assertEquals ( true , FileSpec . match ( "" , "" , false ) ) ; assertEquals ( true , FileSpec . match ( "" , "" , false ) ) ; assertEquals ( true , FileSpec . match ( "" , "" , false ) ) ; assertEquals ( true , FileSpec . match ( "" , "" , false ) ) ; assertEquals ( true , FileSpec . match ( "" , "" , false ) ) ; assertEquals ( false , FileSpec . match ( "" , "" , false ) ) ; assertEquals ( false , FileSpec . match ( "" , "" , false ) ) ; assertEquals ( true , FileSpec . match ( "" , "" , false ) ) ; } public void testGetFilesNoParent ( ) throws IOException { logger . info ( "" + System . getProperty ( "" ) ) ; FileSpec test = new FileSpec ( new File ( "" ) ) ; File [ ] files = test . getFiles ( ) ; logger . info ( Arrays . toString ( files ) ) ; assertNotNull ( files ) ; for ( int i = ; i < files . length ; ++ i ) { if ( files [ i ] . isDirectory ( ) ) { FileSpec test2 = new FileSpec ( files [ i ] ) ; File [ ] files2 = test2 . getFiles ( ) ; logger . info ( Arrays . toString ( files2 ) ) ; assertEquals ( , files2 . length ) ; assertEquals ( files [ i ] , files2 [ ] ) ; } } } } package org . oddjob . launch ; import java . io . File ; import java . io . IOException ; import java . net . URL ; import junit . framework . TestCase ; public class ClassPathHelperTest extends TestCase { public void testAll ( ) throws IOException { File a = new File ( "" ) ; File b = new File ( "" ) ; ClassPathHelper test = new ClassPathHelper ( new File [ ] { a , b } ) ; String cp = System . getProperty ( ClassPathHelper . CLASS_PATH_PROPERTY ) ; test . appendToJavaClassPath ( ) ; assertTrue ( cp . length ( ) > ) ; assertEquals ( cp + File . pathSeparator + b . getCanonicalPath ( ) , System . getProperty ( ClassPathHelper . CLASS_PATH_PROPERTY ) ) ; System . setProperty ( ClassPathHelper . CLASS_PATH_PROPERTY , cp ) ; URL [ ] urls = test . toURLs ( ) ; assertEquals ( a . toURI ( ) . toURL ( ) , urls [ ] ) ; assertEquals ( b . toURI ( ) . toURL ( ) , urls [ ] ) ; String asString = test . toString ( ) ; assertEquals ( "" + File . pathSeparator + "" , asString ) ; } } package org . oddjob . launch ; import junit . framework . TestCase ; public class SystemPropertyArgParserTest extends TestCase { public void testArgs ( ) { SystemPropertyArgParser test = new SystemPropertyArgParser ( ) ; String before = System . getProperty ( "" ) ; String [ ] after = test . processArgs ( new String [ ] { "" , "" } ) ; assertEquals ( , after . length ) ; assertEquals ( "" , System . getProperty ( "" ) ) ; if ( before == null ) { System . getProperties ( ) . remove ( "" ) ; } else { System . setProperty ( "" , before ) ; } } public void testContinue ( ) { SystemPropertyArgParser test = new SystemPropertyArgParser ( ) ; String [ ] after = test . processArgs ( new String [ ] { "" , "" } ) ; assertEquals ( , after . length ) ; } public void testNoneMatches ( ) { SystemPropertyArgParser test = new SystemPropertyArgParser ( ) ; String [ ] after = test . processArgs ( new String [ ] { "" , "" } ) ; assertEquals ( , after . length ) ; } } package org . oddjob . launch ; import java . io . File ; import org . apache . log4j . Logger ; import junit . framework . TestCase ; public class PathParserTest extends TestCase { private static final Logger logger = Logger . getLogger ( PathParserTest . class ) ; String pathToParse = null ; String result1 = null ; String result2 = null ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } void pathSetUp ( ) { if ( "" . equals ( File . pathSeparator ) ) { logger . info ( "" ) ; pathToParse = "" ; result1 = "" ; result2 = "" ; } else if ( "" . equals ( File . pathSeparator ) ) { logger . info ( "" ) ; pathToParse = "" ; result1 = "" ; result2 = "" ; } else { logger . info ( "" ) ; } } public void testPathParse ( ) { pathSetUp ( ) ; if ( pathToParse == null ) { return ; } PathParser test = new PathParser ( ) ; String [ ] after = test . processArgs ( new String [ ] { "" , "" , pathToParse , "" } ) ; assertEquals ( , after . length ) ; assertEquals ( "" , after [ ] ) ; assertEquals ( "" , after [ ] ) ; String [ ] results = test . getElements ( ) ; assertEquals ( , results . length ) ; assertEquals ( result1 , results [ ] ) ; assertEquals ( result2 , results [ ] ) ; } public void testArgButNoPath ( ) { PathParser test = new PathParser ( ) ; try { test . processArgs ( new String [ ] { "" , "" } ) ; fail ( "" ) ; } catch ( IllegalArgumentException e ) { } } public void testContinue ( ) { PathParser test = new PathParser ( ) ; String [ ] after = test . processArgs ( new String [ ] { "" , "" } ) ; assertEquals ( "" , after [ ] ) ; assertEquals ( "" , after [ ] ) ; assertEquals ( , after . length ) ; } public void testTwoClassPathsContinue ( ) { PathParser test = new PathParser ( ) ; String [ ] after = test . processArgs ( new String [ ] { "" , "" , "" } ) ; assertEquals ( "" , after [ ] ) ; assertEquals ( , after . length ) ; } } package org . oddjob . launch ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . IOException ; import java . net . URISyntaxException ; import java . net . URL ; import java . net . URLClassLoader ; import java . util . HashSet ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Main ; import org . oddjob . OurDirs ; import org . oddjob . io . CopyJob ; import org . oddjob . util . URLClassLoaderType ; public class LauncherTest extends TestCase { private static final Logger logger = Logger . getLogger ( LauncherTest . class ) ; String oddjobHome ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; oddjobHome = System . getProperty ( "" ) ; } @ Override protected void tearDown ( ) throws Exception { if ( oddjobHome == null ) { System . getProperties ( ) . remove ( "" ) ; } else { System . setProperty ( "" , oddjobHome ) ; } } public void testGetClassLoader ( ) throws IOException , URISyntaxException { OurDirs dirs = new OurDirs ( ) ; File f = dirs . relative ( "" ) ; ClassLoader cl = Launcher . getClassLoader ( LauncherTest . class . getClassLoader ( ) , new String [ ] { f . getPath ( ) } ) ; assertNotNull ( "" , cl ) ; URL [ ] urls = ( ( URLClassLoader ) cl ) . getURLs ( ) ; HashSet < String > results = new HashSet < String > ( ) ; for ( int i = ; i < urls . length ; ++ i ) { results . add ( new File ( urls [ i ] . toURI ( ) ) . getCanonicalPath ( ) ) ; System . out . println ( urls [ i ] ) ; } assertTrue ( results . contains ( f . getCanonicalPath ( ) ) ) ; assertTrue ( System . getProperty ( "" ) . contains ( f . getCanonicalPath ( ) ) ) ; assertEquals ( Thread . currentThread ( ) . getContextClassLoader ( ) , ClassLoader . getSystemClassLoader ( ) ) ; } public void testInitOddjob ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; File result = new File ( dirs . base ( ) , "" ) ; result . delete ( ) ; System . setProperty ( "" , new File ( "" ) . getCanonicalPath ( ) ) ; Launcher test = new Launcher ( ) ; String args [ ] = { "" , "" , dirs . base ( ) + "" , dirs . base ( ) . toString ( ) } ; test . setArgs ( args ) ; test . setClassLoader ( Main . class . getClassLoader ( ) ) ; test . setClassName ( Launcher . ODDJOB_MAIN_CLASS ) ; test . run ( ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; CopyJob copy = new CopyJob ( ) ; copy . setFrom ( new File [ ] { result } ) ; copy . setOutput ( out ) ; copy . run ( ) ; assertEquals ( "" , out . toString ( ) . trim ( ) ) ; assertEquals ( new File ( "" ) . getCanonicalPath ( ) , System . getProperty ( "" ) ) ; assertEquals ( Thread . currentThread ( ) . getContextClassLoader ( ) , ClassLoader . getSystemClassLoader ( ) ) ; } public void testLaunchAsJob ( ) throws Exception { OurDirs dirs = new OurDirs ( ) ; File result = new File ( dirs . base ( ) , "" ) ; result . delete ( ) ; System . setProperty ( "" , "" ) ; File runJar = dirs . relative ( "" ) ; URLClassLoaderType classLoader = new URLClassLoaderType ( ) ; classLoader . setFiles ( new File [ ] { runJar } ) ; classLoader . setNoInherit ( true ) ; ClassLoader context = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( null ) ; Launcher boot = new Launcher ( ) ; boot . setClassLoader ( classLoader . toValue ( ) ) ; boot . setClassName ( Launcher . class . getName ( ) ) ; boot . setArgs ( new String [ ] { "" , dirs . relative ( "" ) . getPath ( ) } ) ; boot . run ( ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( context ) ; } ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; CopyJob copy = new CopyJob ( ) ; copy . setFrom ( new File [ ] { result } ) ; copy . setOutput ( out ) ; copy . run ( ) ; assertEquals ( "" , out . toString ( ) . trim ( ) ) ; assertEquals ( runJar . getParentFile ( ) . getCanonicalPath ( ) , System . getProperty ( "" ) ) ; assertEquals ( Thread . currentThread ( ) . getContextClassLoader ( ) , ClassLoader . getSystemClassLoader ( ) ) ; } } package org . oddjob . schedules ; import java . text . ParseException ; import java . util . Date ; import java . util . HashMap ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . schedules . IntervalSchedule ; import org . oddjob . schedules . schedules . DailySchedule ; import org . oddjob . scheduling . ManualClock ; import org . oddjob . util . Clock ; public class ScheduleCalculatorTest2 extends TestCase { class OurClock implements Clock { boolean boobyTrapped ; public Date getDate ( ) { if ( boobyTrapped ) { throw new RuntimeException ( ) ; } else { try { return DateHelper . parseDateTime ( "" ) ; } catch ( ParseException e ) { throw new RuntimeException ( e ) ; } } } } class Results implements ScheduleListener { Date scheduleDate ; Date retryDate ; boolean failed ; @ Override public void complete ( Date scheduleDate , ScheduleResult lastComplete ) { throw new RuntimeException ( "" ) ; } @ Override public void failed ( Date scheduleDate ) { this . scheduleDate = scheduleDate ; retryDate = null ; failed = true ; } @ Override public void initialised ( Date scheduleDate ) { this . scheduleDate = scheduleDate ; } @ Override public void retry ( Date scheduleDate , Date retryDate ) { if ( ! scheduleDate . equals ( this . scheduleDate ) ) { throw new RuntimeException ( ) ; } this . retryDate = retryDate ; } } public void testUserGuideScheduleExample ( ) throws ParseException { DailySchedule schedule = new DailySchedule ( ) ; schedule . setFrom ( "" ) ; DailySchedule retry = new DailySchedule ( ) ; retry . setFrom ( "" ) ; retry . setTo ( "" ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; retry . setRefinement ( interval ) ; OurClock clock = new OurClock ( ) ; ScheduleCalculator test = new ScheduleCalculator ( clock , schedule , retry ) ; Results results = new Results ( ) ; test . addScheduleListener ( results ) ; test . initialise ( null , new HashMap < Object , Object > ( ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , results . scheduleDate ) ; test . calculateRetry ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , results . retryDate ) ; clock . boobyTrapped = true ; test . calculateRetry ( ) ; assertTrue ( results . failed ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , results . scheduleDate ) ; } public void testUserGuideScheduleExampleLateStart ( ) throws ParseException { DailySchedule schedule = new DailySchedule ( ) ; schedule . setFrom ( "" ) ; DailySchedule retry = new DailySchedule ( ) ; retry . setFrom ( "" ) ; retry . setTo ( "" ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; retry . setRefinement ( interval ) ; Clock clock = new ManualClock ( "" ) ; ScheduleCalculator test = new ScheduleCalculator ( clock , schedule , retry ) ; Results results = new Results ( ) ; test . addScheduleListener ( results ) ; test . initialise ( null , new HashMap < Object , Object > ( ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , results . scheduleDate ) ; test . calculateRetry ( ) ; assertTrue ( results . failed ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , results . scheduleDate ) ; } class Results2 implements ScheduleListener { Date scheduleDate ; @ Override public void complete ( Date scheduleDate , ScheduleResult lastComplete ) { this . scheduleDate = scheduleDate ; } @ Override public void failed ( Date scheduleDate ) { throw new RuntimeException ( "" ) ; } @ Override public void initialised ( Date scheduleDate ) { this . scheduleDate = scheduleDate ; } @ Override public void retry ( Date scheduleDate , Date retryDate ) { throw new RuntimeException ( "" ) ; } } public void testClockNotUsedAfterInitialise ( ) throws ParseException { IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; OurClock clock = new OurClock ( ) ; ScheduleCalculator test = new ScheduleCalculator ( clock , interval , ( Schedule ) null ) ; Results2 results = new Results2 ( ) ; test . addScheduleListener ( results ) ; test . initialise ( null , new HashMap < Object , Object > ( ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , results . scheduleDate ) ; clock . boobyTrapped = true ; test . calculateComplete ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , results . scheduleDate ) ; test . calculateComplete ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , results . scheduleDate ) ; } } package org . oddjob . schedules ; import java . text . SimpleDateFormat ; import java . util . Date ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . ConsoleCapture ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionPath ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ScheduleTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( ScheduleTypeTest . class ) ; public void testConversion ( ) { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; ConversionPath < ScheduleType , String > path = converter . findConversion ( ScheduleType . class , String . class ) ; assertEquals ( "" , path . toString ( ) ) ; } public void testNowExample ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setExport ( "" , new ArooaObject ( DateHelper . parseDateTime ( "" ) ) ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object now = lookup . lookup ( "" , Object . class ) ; assertEquals ( IntervalTo . class , now . getClass ( ) ) ; assertEquals ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , now ) ; String typeToText = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , typeToText ) ; String timeFormatted = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , timeFormatted ) ; String echoText = lookup . lookup ( "" , String . class ) ; assertEquals ( "" + timeFormatted , echoText ) ; oddjob . destroy ( ) ; } public void testWithTimeZone ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setExport ( "" , new ArooaObject ( DateHelper . parseDateTime ( "" ) ) ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; String typeToText = lookup . lookup ( "" , String . class ) ; Date date = DateHelper . parseDate ( "" , "" ) ; assertEquals ( DateHelper . formatDateTime ( date ) , typeToText ) ; String echoText = lookup . lookup ( "" , String . class ) ; SimpleDateFormat sdf = new SimpleDateFormat ( "" ) ; assertEquals ( "" + sdf . format ( date ) + "" , echoText ) ; oddjob . destroy ( ) ; } public void testNextBusinessDateExample ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setExport ( "" , new ArooaObject ( DateHelper . parseDateTime ( "" ) ) ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; String echoText = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , echoText ) ; oddjob . destroy ( ) ; } public void testScheduleTypeForEach ( ) throws Exception { Oddjob oddjob = new Oddjob ( ) ; oddjob . setExport ( "" , new ArooaObject ( DateHelper . parseDateTime ( "" ) ) ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; console . close ( ) ; console . dump ( logger ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( , lines . length ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . schedules . WeeklySchedule ; import org . oddjob . schedules . units . DayOfWeek ; public class ConstrainedScheduleTest extends TestCase { public void testLastDayOfWeek ( ) throws ParseException { WeeklySchedule test = new WeeklySchedule ( ) ; test . setFrom ( DayOfWeek . Days . MONDAY ) ; test . setTo ( DayOfWeek . Days . FRIDAY ) ; IntervalBase expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . lastInterval ( context ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; assertEquals ( expected , result ) ; } public void testLastDayOfWeekOverllaping ( ) throws ParseException { WeeklySchedule test = new WeeklySchedule ( ) ; test . setFrom ( DayOfWeek . Days . FRIDAY ) ; test . setTo ( DayOfWeek . Days . MONDAY ) ; IntervalBase expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . lastInterval ( context ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; assertEquals ( expected , result ) ; } public void testNextDayOfWeek ( ) throws ParseException { WeeklySchedule test = new WeeklySchedule ( ) ; test . setFrom ( DayOfWeek . Days . MONDAY ) ; test . setTo ( DayOfWeek . Days . FRIDAY ) ; IntervalBase expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextInterval ( context ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextInterval ( context ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextInterval ( context ) ; assertEquals ( expected , result ) ; } public void testNextDayOfWeekOverllaping ( ) throws ParseException { WeeklySchedule test = new WeeklySchedule ( ) ; test . setFrom ( DayOfWeek . Days . FRIDAY ) ; test . setTo ( DayOfWeek . Days . MONDAY ) ; IntervalBase expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextInterval ( context ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextInterval ( context ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextInterval ( context ) ; assertEquals ( expected , result ) ; } } package org . oddjob . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; public class IntervalTest extends TestCase { public IntervalTest ( String arg0 ) { super ( arg0 ) ; } public void testEquals ( ) throws ParseException { Interval test = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval copy = new IntervalTo ( test ) ; assertTrue ( test . equals ( copy ) ) ; } public void testIsBeforeBetweenTimes ( ) throws ParseException { IntervalBase test1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; IntervalBase test2 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertTrue ( test1 . isBefore ( test2 ) ) ; } public void testIsPastBetweenTimes ( ) throws ParseException { IntervalBase test1 = new IntervalBase ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; IntervalBase test2 = new IntervalBase ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertTrue ( test2 . isPast ( test1 ) ) ; } public void testLimitSimpleRefinement ( ) throws ParseException { Interval result ; Interval i1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval i2 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = new IntervalHelper ( i1 ) . limit ( i2 ) ; assertEquals ( i2 , result ) ; } public void testLimitExtendedRefinement ( ) throws ParseException { Interval result ; Interval i1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval i2 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = new IntervalHelper ( i1 ) . limit ( i2 ) ; assertEquals ( expected , result ) ; } public void testLimitEagerRefinement ( ) throws ParseException { Interval result ; Interval i1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval i2 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = new IntervalHelper ( i1 ) . limit ( i2 ) ; assertNull ( result ) ; } public void testLimitAntiRefinement ( ) throws ParseException { Interval result ; Interval i1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval i2 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = new IntervalHelper ( i1 ) . limit ( i2 ) ; assertNull ( result ) ; } public void testLimitDisjointedAfter ( ) throws ParseException { Interval result ; Interval i1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval i2 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = new IntervalHelper ( i1 ) . limit ( i2 ) ; assertNull ( result ) ; } public void testLimitDisjointedBefore ( ) throws ParseException { Interval result ; Interval i1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval i2 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = new IntervalHelper ( i1 ) . limit ( i2 ) ; assertNull ( result ) ; } public void testLimitNull ( ) throws ParseException { Interval i1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertNull ( new IntervalHelper ( i1 ) . limit ( null ) ) ; } } package org . oddjob . schedules ; import java . util . Date ; public class ScheduleRoller { private final Schedule schedule ; private final int howMany ; public ScheduleRoller ( Schedule schedule ) { this ( schedule , ) ; } public ScheduleRoller ( Schedule schedule , int howMany ) { this . schedule = schedule ; this . howMany = howMany ; } public ScheduleResult [ ] resultsFrom ( Date date ) { ScheduleResult [ ] results = new ScheduleResult [ howMany ] ; ScheduleContext context = new ScheduleContext ( date ) ; for ( int i = ; i < howMany ; ++ i ) { ScheduleResult result = schedule . nextDue ( context ) ; if ( result == null ) { break ; } results [ i ] = result ; if ( result . getUseNext ( ) == null ) { break ; } context = context . move ( result . getUseNext ( ) ) ; } return results ; } } package org . oddjob . schedules ; import java . text . ParseException ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . units . DayOfMonth ; import org . oddjob . schedules . units . DayOfWeek ; import org . oddjob . schedules . units . WeekOfMonth ; public class CalendarUtilsTest extends TestCase { public void testAddYearAssumption ( ) throws ParseException { Calendar test = Calendar . getInstance ( ) ; test . clear ( ) ; test . set ( Calendar . DAY_OF_MONTH , ) ; test . set ( Calendar . MONTH , ) ; test . set ( Calendar . YEAR , ) ; assertEquals ( DateHelper . parseDate ( "" ) , test . getTime ( ) ) ; test . add ( Calendar . YEAR , ) ; assertEquals ( DateHelper . parseDate ( "" ) , test . getTime ( ) ) ; test . clear ( ) ; test . set ( Calendar . DAY_OF_MONTH , ) ; test . set ( Calendar . MONTH , ) ; test . set ( Calendar . YEAR , ) ; assertEquals ( DateHelper . parseDate ( "" ) , test . getTime ( ) ) ; test . add ( Calendar . YEAR , ) ; assertEquals ( DateHelper . parseDate ( "" ) , test . getTime ( ) ) ; } public void testSetEndOfDay ( ) throws ParseException { Calendar test = Calendar . getInstance ( ) ; test . setTime ( DateHelper . parseDateTime ( "" ) ) ; CalendarUtils . setEndOfDay ( test ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getTime ( ) ) ; } public void testSetEndOfMonth ( ) throws ParseException { Calendar test = Calendar . getInstance ( ) ; test . setTime ( DateHelper . parseDateTime ( "" ) ) ; CalendarUtils . setEndOfMonth ( test ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getTime ( ) ) ; } public void testStartOfMonthDate ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . startOfMonth ( ) . getTime ( ) ) ; } public void testEndOfMonthDate ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . endOfMonth ( ) . getTime ( ) ) ; } public void testDayOfMonth ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Calendar result = test . dayOfMonth ( new DayOfMonth . Number ( ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , result . getTime ( ) ) ; } public void testStartOfWeekDate ( ) throws ParseException { Calendar result = CalendarUtils . startOfWeek ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Date expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , result . getTime ( ) ) ; result = CalendarUtils . startOfWeek ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , result . getTime ( ) ) ; result = CalendarUtils . startOfWeek ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , result . getTime ( ) ) ; } public void testEndOfWeekDate ( ) throws ParseException { Calendar result = CalendarUtils . endOfWeek ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Date expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , result . getTime ( ) ) ; result = CalendarUtils . endOfWeek ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , result . getTime ( ) ) ; } public void testDayOfWeek ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Calendar result = test . dayOfWeek ( DayOfWeek . Days . WEDNESDAY ) ; Date expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , result . getTime ( ) ) ; result = test . dayOfWeek ( DayOfWeek . Days . SATURDAY ) ; expected = DateHelper . parseDateTime ( "" ) ; } public void testStartOfYearDate ( ) throws ParseException { assertEquals ( DateHelper . parseDate ( "" ) , CalendarUtils . startOfYear ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) . getTime ( ) ) ; } public void testEndOfYearDate ( ) throws ParseException { assertEquals ( DateHelper . parseDateTime ( "" ) , CalendarUtils . endOfYear ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) . getTime ( ) ) ; } public void testDayOfYear ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Calendar result = test . dayOfYear ( , ) ; Date expected = DateHelper . parseDateTime ( "" ) ; assertEquals ( expected , result . getTime ( ) ) ; } public void testMonthOfYear ( ) throws ParseException { assertEquals ( DateHelper . parseDateTime ( "" ) , CalendarUtils . monthOfYear ( DateHelper . parseDateTime ( "" ) , , TimeZone . getDefault ( ) ) . getTime ( ) ) ; } public void testStartOfWeekOfMonth ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Calendar result = test . startOfWeekOfMonth ( WeekOfMonth . Weeks . SECOND ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . startOfWeekOfMonth ( WeekOfMonth . Weeks . LAST ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . startOfWeekOfMonth ( new WeekOfMonth . Number ( ) ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . startOfWeekOfMonth ( WeekOfMonth . Weeks . FOURTH ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; } public void testEndOfWeekOfMonth ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Calendar result = test . endOfWeekOfMonth ( WeekOfMonth . Weeks . SECOND ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . endOfWeekOfMonth ( WeekOfMonth . Weeks . LAST ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . endOfWeekOfMonth ( new WeekOfMonth . Number ( ) ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . endOfWeekOfMonth ( WeekOfMonth . Weeks . FOURTH ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; } public void testStartOfDayOfWeekOfMonth ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Calendar result = test . dayOfWeekInMonth ( DayOfWeek . Days . FRIDAY , WeekOfMonth . Weeks . FIRST ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . dayOfWeekInMonth ( DayOfWeek . Days . FRIDAY , WeekOfMonth . Weeks . SECOND ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . dayOfWeekInMonth ( DayOfWeek . Days . FRIDAY , WeekOfMonth . Weeks . LAST ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . dayOfWeekInMonth ( DayOfWeek . Days . FRIDAY , new WeekOfMonth . Number ( ) ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . dayOfWeekInMonth ( DayOfWeek . Days . FRIDAY , WeekOfMonth . Weeks . PENULTIMATE ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = test . dayOfWeekInMonth ( DayOfWeek . Days . FRIDAY , WeekOfMonth . Weeks . FIFTH ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; } public void testStartOfDay ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Calendar result = test . startOfDay ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , result . getTime ( ) ) ; } public void testEndOfDay ( ) throws ParseException { CalendarUtils test = new CalendarUtils ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ; Calendar result = test . endOfDay ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , result . getTime ( ) ) ; } } package org . oddjob . schedules ; import java . text . ParseException ; import java . util . Calendar ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; public class DateUtilsTest extends TestCase { public void testStartOfDayDate ( ) throws ParseException { assertEquals ( DateHelper . parseDate ( "" ) , DateUtils . startOfDay ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ) ; } public void testEndOfDayDate ( ) throws ParseException { assertEquals ( DateHelper . parseDate ( "" ) , DateUtils . endOfDay ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ) ; } public void testDayOfWeekDate ( ) throws ParseException { assertEquals ( , DateUtils . dayOfWeek ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ) ; } public void testDayOfMonthDate ( ) throws ParseException { assertEquals ( , DateUtils . dayOfMonth ( DateHelper . parseDateTime ( "" ) , TimeZone . getDefault ( ) ) ) ; } public void testCompareCalendars ( ) throws ParseException { Calendar c1 = Calendar . getInstance ( ) ; c1 . setTime ( DateHelper . parseDateTime ( "" ) ) ; Calendar c2 = Calendar . getInstance ( ) ; c2 . setTime ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( - , DateUtils . compare ( c1 , c2 ) ) ; assertEquals ( , DateUtils . compare ( c2 , c1 ) ) ; assertEquals ( , DateUtils . compare ( c1 , c1 ) ) ; } } package org . oddjob . schedules . units ; import junit . framework . TestCase ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . NoConversionAvailableException ; public class DayOfWeekTest extends TestCase { public void testBadString ( ) throws NoConversionAvailableException , ConversionFailedException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; try { converter . convert ( "" , DayOfWeek . class ) ; fail ( "" ) ; } catch ( ConversionFailedException e ) { Throwable cause = e . getCause ( ) ; assertEquals ( "" , cause . getMessage ( ) ) ; } } } package org . oddjob . schedules . regression ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . List ; import java . util . TimeZone ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ScheduleTester { private List < SingleTestSchedule > tests = new ArrayList < SingleTestSchedule > ( ) ; private TimeZone tz ; private String config ; private ArooaSession session ; public void setTest ( int index , SingleTestSchedule test ) { tests . add ( index , test ) ; } public ScheduleTester ( String configFile ) throws Exception { this ( configFile , null ) ; } public ScheduleTester ( String configFile , TimeZone timeZone ) throws Exception { this . config = configFile ; if ( "" . equals ( configFile ) ) { return ; } this . tz = timeZone ; InputStream in = this . getClass ( ) . getResourceAsStream ( configFile ) ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; StandardArooaParser parser = new StandardArooaParser ( this , descriptor ) ; parser . setExpectedDocumentElement ( new ArooaElement ( "" ) ) ; parser . parse ( new XMLConfiguration ( configFile , in ) ) ; session = parser . getSession ( ) ; session . getComponentPool ( ) . configure ( this ) ; } public void run ( ) { TimeZone . setDefault ( tz ) ; for ( SingleTestSchedule schedule : tests ) { schedule . run ( ) ; } ComponentPool pool = session . getComponentPool ( ) ; pool . contextFor ( this ) . getRuntime ( ) . destroy ( ) ; } public String toString ( ) { return config ; } } package org . oddjob . schedules . regression ; import java . util . TimeZone ; import junit . framework . TestCase ; public class ScheduleAllTest extends TestCase { @ Override protected void tearDown ( ) throws Exception { TimeZone . setDefault ( null ) ; } public void testDaily ( ) throws Exception { new ScheduleTester ( "" ) . run ( ) ; TimeZone tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; } public void testMonthly ( ) throws Exception { new ScheduleTester ( "" ) . run ( ) ; TimeZone tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; } public void testBroken ( ) throws Exception { new ScheduleTester ( "" ) . run ( ) ; TimeZone tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; } public void testWeekly ( ) throws Exception { new ScheduleTester ( "" ) . run ( ) ; TimeZone tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; } public void testYearly ( ) throws Exception { new ScheduleTester ( "" ) . run ( ) ; TimeZone tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; tz = TimeZone . getTimeZone ( "" ) ; new ScheduleTester ( "" , tz ) . run ( ) ; } } package org . oddjob . schedules . regression ; import java . text . ParseException ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; public class TestScheduleRun { private static final Logger logger = Logger . getLogger ( TestScheduleRun . class ) ; private String testDate ; private String expectedFrom ; private String expectedTo ; public void setExpectedFrom ( String from ) { this . expectedFrom = from ; } public String getExpectedFrom ( ) { return expectedFrom ; } public void setExpectedTo ( String to ) throws ParseException { this . expectedTo = to ; } public String getExpectedTo ( ) { return expectedTo ; } IntervalTo getExpected ( ) { if ( this . expectedFrom == null && this . expectedTo == null ) { return null ; } try { if ( this . expectedTo == null ) { return new IntervalTo ( DateHelper . parseDateTime ( this . expectedFrom ) ) ; } else { return new IntervalTo ( DateHelper . parseDateTime ( this . expectedFrom ) , DateHelper . parseDateTime ( this . expectedTo ) ) ; } } catch ( ParseException e ) { throw new RuntimeException ( e ) ; } } public void setDate ( String date ) { this . testDate = date ; } public String getDate ( ) { return testDate ; } public void testSchedule ( Schedule schedule ) throws Exception { Date date = null ; try { date = DateHelper . parseDateTime ( testDate ) ; } catch ( ParseException e ) { throw new RuntimeException ( e ) ; } Interval nextDue = schedule . nextDue ( new ScheduleContext ( date ) ) ; IntervalTo expected = getExpected ( ) ; logger . info ( "" + testDate + "" + nextDue + "" + expected ) ; if ( expected == null ) { return ; } if ( ! expected . getFromDate ( ) . equals ( nextDue . getFromDate ( ) ) || ! expected . getToDate ( ) . equals ( nextDue . getToDate ( ) ) ) { throw new Exception ( "" + date + "" + expected + "" + nextDue ) ; } } } package org . oddjob . schedules . regression ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import org . apache . log4j . Logger ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . schedules . Schedule ; public class SingleTestSchedule { private static Logger logger = Logger . getLogger ( SingleTestSchedule . class ) ; private Schedule schedule ; private List < TestScheduleRun > runs = new ArrayList < TestScheduleRun > ( ) ; private String name ; public void setName ( String name ) { this . name = name ; } public String getName ( ) { return this . name ; } public void setRuns ( int index , TestScheduleRun run ) throws Exception { runs . add ( run ) ; } public void setSchedule ( Schedule schedule ) throws NoConversionAvailableException , ConversionFailedException { this . schedule = schedule ; } public int countTestCases ( ) { return runs . size ( ) ; } public void run ( ) { logger . info ( "" + name ) ; for ( Iterator < TestScheduleRun > it = runs . iterator ( ) ; it . hasNext ( ) ; ) { TestScheduleRun test = it . next ( ) ; try { test . testSchedule ( schedule ) ; } catch ( Exception e ) { throw new RuntimeException ( "" + name + "" , e ) ; } } } } package org . oddjob . schedules ; import java . text . SimpleDateFormat ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ScheduleElementTest extends TestCase { public static class OurJob implements Runnable { Schedule schedule ; @ ArooaAttribute public void setSchedule ( Schedule schedule ) { this . schedule = schedule ; } public Schedule getSchedule ( ) { return schedule ; } public void run ( ) { } } public void testParse ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + OurJob . class . getName ( ) + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; Schedule schedule = ( Schedule ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; ScheduleContext context = new ScheduleContext ( new SimpleDateFormat ( "" ) . parse ( "" ) ) ; Interval nextDue = schedule . nextDue ( context ) ; assertEquals ( new SimpleDateFormat ( "" ) . parse ( "" ) , nextDue . getFromDate ( ) ) ; } } package org . oddjob . schedules ; import java . text . DateFormat ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . HashMap ; import java . util . Map ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . DailySchedule ; import org . oddjob . schedules . schedules . DateSchedule ; import org . oddjob . schedules . schedules . IntervalSchedule ; import org . oddjob . schedules . schedules . TimeSchedule ; import org . oddjob . scheduling . ManualClock ; public class ScheduleCalculatorTest extends TestCase { private static final Logger logger = Logger . getLogger ( ScheduleCalculatorTest . class ) ; DateFormat format = new SimpleDateFormat ( "" ) ; DailySchedule schedule ; Schedule retrySchedule ; String scheduleDate ; String nextDue ; ScheduleResult lastComplete ; boolean failed ; boolean retry ; class SL implements ScheduleListener { @ Override public void initialised ( Date scheduleDate ) { ScheduleCalculatorTest . this . scheduleDate = format . format ( scheduleDate ) ; ScheduleCalculatorTest . this . nextDue = format . format ( scheduleDate ) ; ScheduleCalculatorTest . this . retry = false ; ScheduleCalculatorTest . this . failed = false ; } @ Override public void complete ( Date scheduleDate , ScheduleResult lastComplete ) { if ( scheduleDate == null ) { ScheduleCalculatorTest . this . scheduleDate = null ; ScheduleCalculatorTest . this . nextDue = null ; } else { ScheduleCalculatorTest . this . scheduleDate = format . format ( scheduleDate ) ; ScheduleCalculatorTest . this . nextDue = format . format ( scheduleDate ) ; } if ( lastComplete == null ) { ScheduleCalculatorTest . this . lastComplete = null ; } else { ScheduleCalculatorTest . this . lastComplete = lastComplete ; } ScheduleCalculatorTest . this . retry = false ; ScheduleCalculatorTest . this . failed = false ; } public void retry ( Date scheduleDate , Date retryDate ) { ScheduleCalculatorTest . this . scheduleDate = format . format ( scheduleDate ) ; ScheduleCalculatorTest . this . nextDue = format . format ( retryDate ) ; ScheduleCalculatorTest . this . retry = true ; ScheduleCalculatorTest . this . failed = false ; } public void failed ( Date scheduleDate ) { ScheduleCalculatorTest . this . scheduleDate = format . format ( scheduleDate ) ; ScheduleCalculatorTest . this . nextDue = format . format ( scheduleDate ) ; ScheduleCalculatorTest . this . retry = false ; ScheduleCalculatorTest . this . failed = true ; } } public void setUp ( ) throws ParseException { logger . debug ( "" + getName ( ) + "" ) ; logger . debug ( "" + TimeZone . getDefault ( ) . getDisplayName ( ) ) ; schedule = new DailySchedule ( ) ; schedule . setFrom ( "" ) ; schedule . setTo ( "" ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; CountSchedule count = new CountSchedule ( ) ; count . setCount ( ) ; count . setRefinement ( interval ) ; retrySchedule = count ; } public void testInitialiseBeforeDue ( ) throws Exception { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testInitialiseDuringDue ( ) throws Exception { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testInitialiseAfterDue ( ) throws Exception { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testComplete ( ) throws Exception { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; schedCalc . calculateComplete ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertEquals ( "" , DateHelper . parseDateTime ( "" ) , lastComplete . getFromDate ( ) ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testCompleteComplete ( ) throws Exception { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; schedCalc . calculateComplete ( ) ; schedCalc . calculateComplete ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertEquals ( "" , DateHelper . parseDateTime ( "" ) , lastComplete . getFromDate ( ) ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testFailNoException ( ) throws Exception { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertTrue ( "" , failed ) ; } public void testCompleteFailNoException ( ) throws Exception { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; schedCalc . calculateComplete ( ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertEquals ( "" , DateHelper . parseDateTime ( "" ) , lastComplete . getFromDate ( ) ) ; assertFalse ( "" , retry ) ; assertTrue ( "" , failed ) ; } public void testExceptionScheduleOnce ( ) throws ParseException { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule , retrySchedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; clock . setDate ( "" ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertTrue ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testExceptionScheduleTwice ( ) throws ParseException { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule , retrySchedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; clock . setDate ( "" ) ; schedCalc . calculateRetry ( ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertTrue ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testExceptionScheduleThrice ( ) throws ParseException { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule , retrySchedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; clock . setDate ( "" ) ; schedCalc . calculateRetry ( ) ; schedCalc . calculateRetry ( ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertTrue ( "" , failed ) ; } public void testExceptionScheduleFourth ( ) throws ParseException { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule , retrySchedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; schedCalc . calculateRetry ( ) ; schedCalc . calculateRetry ( ) ; schedCalc . calculateRetry ( ) ; clock . setDate ( "" ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertTrue ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testCompletes ( ) throws InterruptedException , ParseException { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; DateSchedule dateSchedule = new DateSchedule ( ) ; dateSchedule . setOn ( "" ) ; TimeSchedule timeSchedule = new TimeSchedule ( ) ; timeSchedule . setAt ( "" ) ; dateSchedule . setRefinement ( timeSchedule ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , dateSchedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; schedCalc . calculateComplete ( ) ; assertNull ( "" , scheduleDate ) ; assertNull ( "" , nextDue ) ; assertEquals ( "" , DateHelper . parseDateTime ( "" ) , lastComplete . getFromDate ( ) ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testPersitence ( ) throws Exception { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; Map < Object , Object > m = new HashMap < Object , Object > ( ) ; schedCalc . initialise ( null , m ) ; schedCalc . calculateComplete ( ) ; schedCalc = new ScheduleCalculator ( clock , schedule ) ; schedCalc . initialise ( lastComplete , m ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; } public void testPersistence2 ( ) throws ParseException { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; CountSchedule countSchedule = new CountSchedule ( ) ; countSchedule . setCount ( ) ; DateSchedule dateSchedule = new DateSchedule ( ) ; dateSchedule . setOn ( "" ) ; ScheduleList scheduleList = new ScheduleList ( ) ; scheduleList . setSchedules ( new Schedule [ ] { countSchedule , dateSchedule } ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , scheduleList ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; HashMap < Object , Object > map = new HashMap < Object , Object > ( ) ; schedCalc . initialise ( null , map ) ; schedCalc = new ScheduleCalculator ( clock , scheduleList ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( new IntervalTo ( format . parse ( "" ) , format . parse ( "" ) ) , map ) ; assertEquals ( "" , nextDue ) ; } public void testLimitedRetry ( ) throws ParseException { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule , retrySchedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; schedCalc . initialise ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertTrue ( "" , retry ) ; assertFalse ( "" , failed ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertTrue ( "" , failed ) ; } public void testRetryAfterInterval ( ) throws ParseException { ManualClock clock = new ManualClock ( ) ; clock . setDate ( "" ) ; ScheduleCalculator schedCalc = new ScheduleCalculator ( clock , schedule , retrySchedule ) ; schedCalc . addScheduleListener ( new SL ( ) ) ; IntervalTo lastInterval = new IntervalTo ( format . parse ( "" ) , format . parse ( "" ) ) ; schedCalc . initialise ( lastInterval , new HashMap < Object , Object > ( ) ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertFalse ( "" , failed ) ; schedCalc . calculateRetry ( ) ; assertEquals ( "" , "" , scheduleDate ) ; assertEquals ( "" , "" , nextDue ) ; assertNull ( "" , lastComplete ) ; assertFalse ( "" , retry ) ; assertTrue ( "" , failed ) ; } } package org . oddjob . schedules ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Date ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . schedules . schedules . WeeklySchedule ; import org . oddjob . schedules . schedules . TimeSchedule ; import org . oddjob . schedules . units . DayOfWeek ; public class AdhocScheduleTest extends TestCase { private static final Logger logger = Logger . getLogger ( AdhocScheduleTest . class ) ; public void testForMeena ( ) throws ParseException { SimpleDateFormat format = new SimpleDateFormat ( "" ) ; assertTrue ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertFalse ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertFalse ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertFalse ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertFalse ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertTrue ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertFalse ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertTrue ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertFalse ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; assertFalse ( isIncluded ( DayOfWeek . Days . WEDNESDAY , "" , "" , format . parse ( "" ) ) ) ; } public static final boolean isIncluded ( DayOfWeek day , String startTime , String endTime , Date date ) throws ParseException { WeeklySchedule dws = new WeeklySchedule ( ) ; dws . setOn ( day ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setFrom ( startTime ) ; time . setTo ( endTime ) ; dws . setRefinement ( time ) ; Interval result = dws . nextDue ( new ScheduleContext ( date ) ) ; logger . debug ( "" + day + "" + startTime + "" + endTime + "" + date + "" + result ) ; return date . after ( result . getFromDate ( ) ) && date . before ( result . getToDate ( ) ) ; } } package org . oddjob . schedules ; import java . text . ParseException ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; public class SimpleIntervalTest extends TestCase { public void testOn ( ) throws ParseException { Date date = DateHelper . parseDateTime ( "" ) ; SimpleInterval test = new SimpleInterval ( date ) ; assertEquals ( date , test . getFromDate ( ) ) ; assertEquals ( DateUtils . oneMillisAfter ( date ) , test . getToDate ( ) ) ; } public void testEquals ( ) throws ParseException { Interval i1 , i2 ; i1 = new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; i2 = new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( i1 , i2 ) ; i1 = new SimpleInterval ( i2 ) ; assertEquals ( i1 , i2 ) ; } public void testNotEquals ( ) throws ParseException { Interval i1 , i2 ; i1 = new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; i2 = new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertFalse ( i1 . equals ( i2 ) ) ; } } package org . oddjob . schedules ; import java . text . ParseException ; import org . oddjob . arooa . utils . DateHelper ; import junit . framework . TestCase ; public class SimpleScheduleResultTest extends TestCase { public void testEquals ( ) throws ParseException { Object o1 , o2 ; o1 = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; o2 = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( o1 , o2 ) ; o1 = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; o2 = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( o1 , o2 ) ; } public void testNotEquals ( ) throws ParseException { Object o1 , o2 ; o1 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDate ( "" ) ) ; o2 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDate ( "" ) ) ; assertFalse ( o1 . equals ( o2 ) ) ; o1 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; o2 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDate ( "" ) ) ; assertFalse ( o1 . equals ( o2 ) ) ; } } package org . oddjob . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . DailySchedule ; import org . oddjob . schedules . schedules . WeeklySchedule ; import org . oddjob . schedules . units . DayOfWeek ; public class ScheduleListTest extends TestCase { private static final Logger logger = Logger . getLogger ( ScheduleListTest . class ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } public void testTwoTimes ( ) throws ParseException { DailySchedule s1 = new DailySchedule ( ) ; s1 . setFrom ( "" ) ; s1 . setTo ( "" ) ; DailySchedule s2 = new DailySchedule ( ) ; s2 . setFrom ( "" ) ; s2 . setTo ( "" ) ; ScheduleList test = new ScheduleList ( ) ; test . setSchedules ( new Schedule [ ] { s1 , s2 } ) ; ScheduleContext context ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalBase expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; result = test . nextDue ( context . move ( result . getToDate ( ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testTwoTimesAsRefinement ( ) throws ParseException { DailySchedule s1 = new DailySchedule ( ) ; s1 . setFrom ( "" ) ; s1 . setTo ( "" ) ; DailySchedule s2 = new DailySchedule ( ) ; s2 . setFrom ( "" ) ; s2 . setTo ( "" ) ; ScheduleList test = new ScheduleList ( ) ; test . setSchedules ( new Schedule [ ] { s1 , s2 } ) ; WeeklySchedule dayOfWeek = new WeeklySchedule ( ) ; dayOfWeek . setOn ( DayOfWeek . Days . THURSDAY ) ; dayOfWeek . setRefinement ( test ) ; ScheduleContext context ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = dayOfWeek . nextDue ( context ) ; IntervalBase expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; result = dayOfWeek . nextDue ( context . move ( result . getToDate ( ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testEmpty ( ) throws ParseException { IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; ScheduleList test = new ScheduleList ( ) ; test . setSchedules ( new Schedule [ ] { } ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; context = context . spawn ( expected ) ; assertEquals ( null , test . nextDue ( context ) ) ; } public void testListExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleList ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . SimpleInterval ; import org . oddjob . schedules . SimpleScheduleResult ; import org . oddjob . schedules . units . DayOfWeek ; import org . oddjob . schedules . units . Month ; public class DayAfterScheduleTest extends TestCase { public void testDayAfterInterval ( ) throws ParseException { DayAfterSchedule test = new DayAfterSchedule ( ) ; ScheduleContext context = new ScheduleContext ( new Date ( ) ) ; context = context . spawn ( new Date ( ) , new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; } public void testDayAfterWithRefinement ( ) throws ParseException { WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . WEDNESDAY ) ; DayAfterSchedule test = new DayAfterSchedule ( ) ; weekly . setRefinement ( test ) ; DailySchedule time = new DailySchedule ( ) ; time . setFrom ( "" ) ; test . setRefinement ( time ) ; Interval [ ] results = new ScheduleRoller ( weekly ) . resultsFrom ( DateHelper . parseDate ( "" ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testDayAfterScheduleExample ( ) throws ArooaParseException , ParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ScheduleList holidays = new ScheduleList ( ) ; YearlySchedule h1 = new YearlySchedule ( ) ; h1 . setInMonth ( Month . Months . AUGUST ) ; DateSchedule h2 = new DateSchedule ( ) ; h2 . setOn ( "" ) ; holidays . setSchedules ( , h1 ) ; holidays . setSchedules ( , h2 ) ; session . getBeanRegistry ( ) . register ( "" , holidays ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval [ ] results = new ScheduleRoller ( schedule ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . SimpleInterval ; import org . oddjob . schedules . SimpleScheduleResult ; import org . oddjob . schedules . units . DayOfMonth ; import org . oddjob . schedules . units . DayOfWeek ; public class TimeScheduleTest extends TestCase { private static final Logger logger = Logger . getLogger ( "" ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } public void testStandardIntervalDifferentStarts ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleResult result , expected ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; expected = null ; assertEquals ( expected , result ) ; } public void testForwardInterval ( ) throws ParseException { TimeSchedule s = new TimeSchedule ( ) ; s . setFrom ( "" ) ; s . setTo ( "" ) ; ScheduleResult expected , result ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; result = s . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; result = s . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , result ) ; result = s . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; } public void testOn ( ) throws ParseException { TimeSchedule s = new TimeSchedule ( ) ; s . setAt ( "" ) ; ScheduleContext context ; ScheduleResult expected , result ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , null ) ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , null ) ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; expected = null ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; } public void testWithLimits ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setAt ( "" ) ; ScheduleContext context ; ScheduleResult expected , result ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; context = context . spawn ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ) ; result = test . nextDue ( context ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , result ) ; } public void testDefaultTo ( ) throws Exception { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; logger . debug ( "" + result ) ; Interval expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , Interval . END_OF_TIME ) , null ) ; assertEquals ( expected , result ) ; } public void testDefaultFrom ( ) throws Exception { TimeSchedule s = new TimeSchedule ( ) ; s . setTo ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = s . nextDue ( context ) ; logger . debug ( "" + result ) ; Interval expected = new SimpleScheduleResult ( new IntervalTo ( Interval . START_OF_TIME , DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , result ) ; } public void testWithInterval ( ) throws Exception { TimeSchedule timeSchedule = new TimeSchedule ( ) ; timeSchedule . setFrom ( "" ) ; timeSchedule . setTo ( "" ) ; IntervalSchedule intervalSchedule = new IntervalSchedule ( ) ; intervalSchedule . setInterval ( "" ) ; timeSchedule . setRefinement ( intervalSchedule ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult result = timeSchedule . nextDue ( context ) ; logger . debug ( "" + result ) ; ScheduleResult expected = ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; result = timeSchedule . nextDue ( context . move ( result . getUseNext ( ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = timeSchedule . nextDue ( context ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = timeSchedule . nextDue ( context ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = timeSchedule . nextDue ( context ) ; expected = null ; assertEquals ( expected , result ) ; } public void testWithIntervalOverMidnight ( ) throws Exception { TimeSchedule timeSchedule = new TimeSchedule ( ) ; timeSchedule . setFrom ( "" ) ; timeSchedule . setTo ( "" ) ; IntervalSchedule intervalSchedule = new IntervalSchedule ( ) ; intervalSchedule . setInterval ( "" ) ; timeSchedule . setRefinement ( intervalSchedule ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult result = timeSchedule . nextDue ( context ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , result ) ; } public void testNextIntervalWithParent ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; context = context . spawn ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ) ; Interval result = test . nextInterval ( context ) ; Interval expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextInterval ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextInterval ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextInterval ( context ) ; expected = null ; assertEquals ( expected , result ) ; } public void testLastInterval ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; Interval expected , result ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; expected = null ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; expected = null ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testLastIntervalOverMidnight ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; Interval expected , result ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; expected = null ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . lastInterval ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testWithParent ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . MONDAY ) ; weekly . setRefinement ( test ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult result = weekly . nextDue ( context ) ; ScheduleResult expected ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; result = weekly . nextDue ( context . move ( result . getUseNext ( ) ) ) ; assertEquals ( expected , result ) ; } public void testAtWithParentWeekly ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setAt ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . MONDAY ) ; weekly . setRefinement ( test ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult result = weekly . nextDue ( context ) ; ScheduleResult expected ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) ) ; result = weekly . nextDue ( context . move ( result . getUseNext ( ) ) ) ; assertEquals ( expected , result ) ; } public void testAtWithParentMonthly ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setAt ( "" ) ; MonthlySchedule monthly = new MonthlySchedule ( ) ; monthly . setFromDay ( new DayOfMonth . Number ( ) ) ; monthly . setToDay ( new DayOfMonth . Number ( ) ) ; monthly . setRefinement ( test ) ; ScheduleResult result , expected ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = monthly . nextDue ( context ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = monthly . nextDue ( context ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) ) ; result = monthly . nextDue ( context . move ( result . getUseNext ( ) ) ) ; assertEquals ( expected , result ) ; } public void testAsChildWithInterval ( ) throws Exception { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; IntervalSchedule intervalSchedule = new IntervalSchedule ( ) ; intervalSchedule . setInterval ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . MONDAY ) ; test . setRefinement ( intervalSchedule ) ; weekly . setRefinement ( test ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult result = weekly . nextDue ( context ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getUseNext ( ) ) ; result = weekly . nextDue ( context ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; } public void testAsChildOverMidnightWithInterval ( ) throws Exception { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; IntervalSchedule intervalSchedule = new IntervalSchedule ( ) ; intervalSchedule . setInterval ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . MONDAY ) ; test . setRefinement ( intervalSchedule ) ; weekly . setRefinement ( test ) ; ScheduleResult [ ] results = new ScheduleRoller ( weekly ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult result ; result = weekly . nextDue ( context ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; } public void testTimeAfter24 ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleContext context ; Interval expected ; Interval result ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; result = test . nextDue ( context ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; result = test . nextDue ( context ) ; assertEquals ( expected , result ) ; } public void testTwoNestedTimes ( ) throws ParseException { TimeSchedule schedule = new TimeSchedule ( ) ; schedule . setFrom ( "" ) ; TimeSchedule retry = new TimeSchedule ( ) ; retry . setTo ( "" ) ; schedule . setRefinement ( retry ) ; ScheduleRoller roller = new ScheduleRoller ( schedule ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; assertNull ( results [ ] ) ; } public void testLimitedTimeAndAnInterval ( ) throws ParseException { TimeSchedule retry = new TimeSchedule ( ) ; retry . setFrom ( "" ) ; retry . setTo ( "" ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; retry . setRefinement ( interval ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; context = context . spawn ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; Interval expected ; Interval result ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; result = retry . nextDue ( context ) ; assertEquals ( expected , result ) ; result = retry . nextDue ( context . move ( expected . getToDate ( ) ) ) ; assertNull ( result ) ; } public void testDefaultTimesRollingForward ( ) throws ParseException { TimeSchedule test = new TimeSchedule ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; Interval expected = new SimpleScheduleResult ( new IntervalTo ( Interval . START_OF_TIME , Interval . END_OF_TIME ) , null ) ; assertEquals ( expected , result ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleScheduleResult ; public class ParentChildScheduleTest extends TestCase { public void testParentNoChild ( ) throws ParseException { final ScheduleResult parentResult = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; class ParentSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { return parentResult ; } } ParentChildSchedule test = new ParentChildSchedule ( new ParentSchedule ( ) , null ) ; ScheduleResult result = test . nextDue ( new ScheduleContext ( new Date ( ) ) ) ; assertEquals ( parentResult , result ) ; } public void testParentAndChildChildNotLimited ( ) throws ParseException { final ScheduleResult parentResult = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; class ParentSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { return parentResult ; } } final ScheduleResult childResult = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; class ChildSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { return childResult ; } } ParentChildSchedule test = new ParentChildSchedule ( new ParentSchedule ( ) , new ChildSchedule ( ) ) ; ScheduleResult result = test . nextDue ( new ScheduleContext ( new Date ( ) ) ) ; assertEquals ( childResult , result ) ; } public void testParentNoChildWithLimits ( ) throws ParseException { final ScheduleResult parentResult = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; class ParentSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { return parentResult ; } } ParentChildSchedule test = new ParentChildSchedule ( new ParentSchedule ( ) , null ) ; ScheduleContext context = new ScheduleContext ( new Date ( ) ) ; Interval limit = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; context = context . spawn ( limit ) ; ScheduleResult result = test . nextDue ( context ) ; assertEquals ( null , result ) ; } public void testParentWhenChildReturnsNull ( ) throws ParseException { final ScheduleResult parentResult = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; class ParentSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { return parentResult ; } } class ChildSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { return null ; } } ParentChildSchedule test = new ParentChildSchedule ( new ParentSchedule ( ) , new ChildSchedule ( ) ) ; ScheduleResult result = test . nextDue ( new ScheduleContext ( new Date ( ) ) ) ; assertEquals ( null , result ) ; } public void testParentAndChildWhenChildUseNextNull ( ) throws ParseException { final ScheduleResult parentResult = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; class ParentSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { return parentResult ; } } final ScheduleResult childResult = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) , null ) ; class ChildSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { return childResult ; } } ParentChildSchedule test = new ParentChildSchedule ( new ParentSchedule ( ) , new ChildSchedule ( ) ) ; ScheduleResult result = test . nextDue ( new ScheduleContext ( new Date ( ) ) ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) , childResult . getToDate ( ) ) ; assertEquals ( expected , result ) ; } public void testParentAndChildWhenChildUseNextNullInParentNextInterval ( ) throws ParseException { final ScheduleResult parentResult1 = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; final ScheduleResult parentResult2 = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; final Date firstDate = DateHelper . parseDate ( "" ) ; class ParentSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { if ( context . getDate ( ) . equals ( firstDate ) ) { return parentResult1 ; } else { return parentResult2 ; } } } final ScheduleResult childResult = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) , null ) ; class ChildSchedule implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { if ( context . getDate ( ) . equals ( firstDate ) ) { return null ; } else { return childResult ; } } } ParentChildSchedule test = new ParentChildSchedule ( new ParentSchedule ( ) , new ChildSchedule ( ) ) ; ScheduleResult result = test . nextDue ( new ScheduleContext ( firstDate ) ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) , childResult . getToDate ( ) ) ; assertEquals ( expected , result ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; public class DailyScheduleExamplesTest extends TestCase { public void testSimpleExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; DailySchedule schedule = ( DailySchedule ) parser . getRoot ( ) ; assertEquals ( "" , schedule . getFrom ( ) ) ; assertEquals ( "" , schedule . getTo ( ) ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testTimeAndIntervalExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . units . DayOfWeek ; public class DayOfWeekScheduleTest extends TestCase { public void testFromAndTo ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setFrom ( DayOfWeek . Days . TUESDAY ) ; schedule . setTo ( DayOfWeek . Days . WEDNESDAY ) ; Date now1 = DateHelper . parseDateTime ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertEquals ( expected , result ) ; } public void testAfter ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setFrom ( DayOfWeek . Days . TUESDAY ) ; schedule . setTo ( DayOfWeek . Days . WEDNESDAY ) ; Date now1 = DateHelper . parseDateTime ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertEquals ( expected , result ) ; } public void testOverBoundry ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setFrom ( DayOfWeek . Days . FRIDAY ) ; schedule . setTo ( DayOfWeek . Days . MONDAY ) ; Date now1 = DateHelper . parseDateTime ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result1 = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertEquals ( expected , result1 ) ; Date now2 = DateHelper . parseDateTime ( "" ) ; Interval result2 = schedule . nextDue ( new ScheduleContext ( now2 ) ) ; assertEquals ( expected , result2 ) ; Date now3 = DateHelper . parseDateTime ( "" ) ; Interval result3 = schedule . nextDue ( new ScheduleContext ( now3 ) ) ; assertEquals ( expected , result3 ) ; } public void testWithTime ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setOn ( DayOfWeek . Days . FRIDAY ) ; DailySchedule time = new DailySchedule ( ) ; time . setAt ( "" ) ; schedule . setRefinement ( time ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; Interval nextDue = schedule . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , nextDue ) ; } public void testDefaultFrom ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setTo ( DayOfWeek . Days . TUESDAY ) ; Interval result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; assertEquals ( expected , result ) ; } public void testDefaultTo ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setFrom ( DayOfWeek . Days . TUESDAY ) ; Interval result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; assertEquals ( expected , result ) ; } public void testInclusive ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setTo ( DayOfWeek . Days . TUESDAY ) ; Interval result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testWithOverMidnightTime ( ) throws ParseException { WeeklySchedule test = new WeeklySchedule ( ) ; test . setOn ( DayOfWeek . Days . WEDNESDAY ) ; DailySchedule time = new DailySchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; test . setRefinement ( time ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; assertEquals ( expected , result ) ; } public void testOnExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testBetweenExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testToString ( ) { WeeklySchedule test = new WeeklySchedule ( ) ; test . setOn ( DayOfWeek . Days . FRIDAY ) ; String expected = "" ; assertEquals ( expected , test . toString ( ) ) ; test = new WeeklySchedule ( ) ; test . setFrom ( DayOfWeek . Days . MONDAY ) ; test . setTo ( DayOfWeek . Days . FRIDAY ) ; expected = "" ; assertEquals ( expected , test . toString ( ) ) ; test = new WeeklySchedule ( ) ; expected = "" ; assertEquals ( expected , test . toString ( ) ) ; test = new WeeklySchedule ( ) ; test . setOn ( DayOfWeek . Days . WEDNESDAY ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setAt ( "" ) ; test . setRefinement ( time ) ; expected = "" ; assertEquals ( expected , test . toString ( ) ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . utils . SpringSafeCalendar ; import org . oddjob . arooa . utils . TimeParser ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; public class DailyOverDSTBoundryTest extends TestCase { private static final Logger logger = Logger . getLogger ( DailyOverDSTBoundryTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testCalendarAssuptionsAutumn ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; Date saturday1AM_BST = DateHelper . parseDateTime ( "" ) ; Calendar cal1 = Calendar . getInstance ( TimeZone . getTimeZone ( "" ) ) ; cal1 . setTime ( saturday1AM_BST ) ; cal1 . add ( Calendar . DATE , ) ; assertEquals ( * * * , cal1 . get ( Calendar . DST_OFFSET ) ) ; Date sunday1AM_BST = new Date ( DateHelper . parseDateTime ( "" ) . getTime ( ) + ) ; logger . info ( "" + saturday1AM_BST ) ; assertEquals ( sunday1AM_BST , cal1 . getTime ( ) ) ; cal1 . add ( Calendar . HOUR , ) ; Date sunday1AM_GMT = DateHelper . parseDateTime ( "" ) ; logger . info ( "" + sunday1AM_GMT ) ; assertEquals ( sunday1AM_GMT , cal1 . getTime ( ) ) ; TimeZone . setDefault ( null ) ; } public void testCalendarAssuptionsSpring ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; Date saturday_Midnight = DateHelper . parseDateTime ( "" ) ; Calendar cal1 = Calendar . getInstance ( ) ; cal1 . setTime ( saturday_Midnight ) ; cal1 . add ( Calendar . DATE , ) ; Date sundayMidnight_GMT = DateHelper . parseDateTime ( "" ) ; assertEquals ( sundayMidnight_GMT , cal1 . getTime ( ) ) ; Date saturday1AM_GMT = DateHelper . parseDateTime ( "" ) ; Calendar cal2 = Calendar . getInstance ( ) ; cal2 . setTime ( saturday1AM_GMT ) ; cal2 . add ( Calendar . DATE , ) ; assertEquals ( sundayMidnight_GMT , cal2 . getTime ( ) ) ; assertEquals ( * * * , sundayMidnight_GMT . getTime ( ) - saturday1AM_GMT . getTime ( ) ) ; cal2 . add ( Calendar . HOUR , ) ; Date sunday_2AM_BST = DateHelper . parseDateTime ( "" ) ; logger . info ( "" + sunday_2AM_BST ) ; assertEquals ( sunday_2AM_BST , cal2 . getTime ( ) ) ; TimeZone . setDefault ( null ) ; } public void testDateParsing ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; Calendar cal = Calendar . getInstance ( ) ; Date oneAM = DateHelper . parseDateTime ( "" ) ; logger . info ( "" + oneAM ) ; cal . setTime ( oneAM ) ; assertEquals ( * * * , cal . get ( Calendar . DST_OFFSET ) ) ; assertEquals ( , cal . get ( Calendar . HOUR ) ) ; Date twoAM = DateHelper . parseDateTime ( "" ) ; cal . setTime ( twoAM ) ; assertEquals ( * * * , cal . get ( Calendar . DST_OFFSET ) ) ; assertEquals ( , cal . get ( Calendar . HOUR ) ) ; assertEquals ( oneAM , twoAM ) ; Date midnightGMT = DateHelper . parseDateTime ( "" ) ; logger . info ( "" + midnightGMT ) ; cal . setTime ( midnightGMT ) ; assertEquals ( , cal . get ( Calendar . DST_OFFSET ) ) ; assertEquals ( , cal . get ( Calendar . HOUR ) ) ; long interval = DateHelper . parseDateTime ( "" ) . getTime ( ) - DateHelper . parseDateTime ( "" ) . getTime ( ) ; assertEquals ( * * , interval ) ; interval = DateHelper . parseDateTime ( "" ) . getTime ( ) - DateHelper . parseDateTime ( "" ) . getTime ( ) ; assertEquals ( - * * , interval ) ; interval = DateHelper . parseDateTime ( "" ) . getTime ( ) - DateHelper . parseDateTime ( "" ) . getTime ( ) ; assertEquals ( * * , interval ) ; } public void testDayLightSavingInAutumnWithAtBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setAt ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithAtBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setAt ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnWithAtBoundry2 ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setAt ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithAtBoundry2 ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setAt ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnWithFromToOnBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithFromToOnBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnWithFromToSpanningBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithFromToSpanningBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnWithFromToSpanningBoundry2 ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithFromToSpanningBoundry2 ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnOverMidnightSpanningBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringOverMidnightSpanningBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleList ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . SimpleScheduleResult ; import org . oddjob . schedules . units . DayOfWeek ; import org . oddjob . schedules . units . Month ; public class DayBeforeScheduleTest extends TestCase { public void testDayBeforeInterval ( ) throws ParseException { DayBeforeSchedule test = new DayBeforeSchedule ( ) ; ScheduleContext context = new ScheduleContext ( new Date ( ) ) ; context = context . spawn ( new Date ( ) , new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ) ; Interval result = test . nextDue ( context ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; } public void testDayBeforeWithRefinement ( ) throws ParseException { WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . WEDNESDAY ) ; DayBeforeSchedule test = new DayBeforeSchedule ( ) ; weekly . setRefinement ( test ) ; DailySchedule time = new DailySchedule ( ) ; time . setFrom ( "" ) ; test . setRefinement ( time ) ; ScheduleResult [ ] results = new ScheduleRoller ( weekly ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDate ( "" ) ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDate ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testDayBeforeScheduleExample ( ) throws ArooaParseException , ParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ScheduleList holidays = new ScheduleList ( ) ; YearlySchedule h1 = new YearlySchedule ( ) ; h1 . setInMonth ( Month . Months . AUGUST ) ; DateSchedule h2 = new DateSchedule ( ) ; h2 . setOn ( "" ) ; holidays . setSchedules ( , h1 ) ; holidays . setSchedules ( , h2 ) ; session . getBeanRegistry ( ) . register ( "" , holidays ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval [ ] results = new ScheduleRoller ( schedule ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; public class DateScheduleTest extends TestCase { public void testAllOfTime ( ) throws ParseException { DateSchedule test = new DateSchedule ( ) ; ScheduleContext scheduleContext = new ScheduleContext ( new Date ( ) ) ; IntervalTo expected = new IntervalTo ( Interval . START_OF_TIME , Interval . END_OF_TIME ) ; Interval result = test . nextDue ( scheduleContext ) ; assertEquals ( expected , result ) ; } public void testNextDueSingleDayDate ( ) throws ParseException { DateSchedule test = new DateSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getToDate ( ) ) ; result = test . nextDue ( context ) ; assertNull ( result ) ; } public void testNextDueDateRange ( ) throws ParseException { DateSchedule test = new DateSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getToDate ( ) ) ; result = test . nextDue ( context ) ; assertEquals ( null , result ) ; } public void testNextDueAfterDate ( ) throws ParseException { DateSchedule test = new DateSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; Interval result = test . nextDue ( context ) ; assertNull ( result ) ; } public void testDueOnWithTimeRefinement ( ) throws ParseException { DateSchedule test = new DateSchedule ( ) ; test . setOn ( "" ) ; DailySchedule timeSchedule = new DailySchedule ( ) ; timeSchedule . setAt ( "" ) ; test . setRefinement ( timeSchedule ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getToDate ( ) ) ; result = test . nextDue ( context ) ; assertNull ( result ) ; } public void testDateScheduleExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( null , next ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleList ; import org . oddjob . schedules . units . Month ; public class LastScheduleTest extends TestCase { public void testLastChristmas ( ) throws ParseException { DateSchedule c1 = new DateSchedule ( ) ; c1 . setOn ( "" ) ; DateSchedule c2 = new DateSchedule ( ) ; c2 . setOn ( "" ) ; DateSchedule c3 = new DateSchedule ( ) ; c3 . setOn ( "" ) ; ScheduleList list = new ScheduleList ( ) ; list . setSchedules ( new Schedule [ ] { c1 , c2 , c3 } ) ; LastSchedule last = new LastSchedule ( ) ; last . setRefinement ( list ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = last . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testNever ( ) throws ParseException { DateSchedule c1 = new DateSchedule ( ) ; c1 . setOn ( "" ) ; LastSchedule last = new LastSchedule ( ) ; last . setRefinement ( c1 ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = last . nextDue ( context ) ; assertNull ( result ) ; } public void testLastDayOfApril ( ) throws ParseException { LastSchedule test = new LastSchedule ( ) ; YearlySchedule month = new YearlySchedule ( ) ; month . setInMonth ( Month . Months . APRIL ) ; DailySchedule time = new DailySchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; month . setRefinement ( test ) ; test . setRefinement ( time ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = month . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testLastExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval next = schedule . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( context . move ( expected . getToDate ( ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . units . DayOfWeek ; public class IntervalScheduleTest extends TestCase { public void testSimple ( ) throws ParseException { IntervalSchedule test = new IntervalSchedule ( ) ; test . setInterval ( "" ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; IntervalTo expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testSimpleConstrained ( ) throws ParseException { TimeSchedule time = new TimeSchedule ( ) ; time . setFrom ( "" ) ; IntervalSchedule test = new IntervalSchedule ( ) ; test . setInterval ( "" ) ; time . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( time ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; IntervalTo expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testEvery7HoursOnWednesday ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setOn ( DayOfWeek . Days . WEDNESDAY ) ; IntervalSchedule test = new IntervalSchedule ( ) ; test . setInterval ( "" ) ; schedule . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( schedule ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; IntervalTo expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testEvery7HoursOnWednesday2 ( ) throws ParseException { WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setOn ( DayOfWeek . Days . WEDNESDAY ) ; IntervalSchedule test = new IntervalSchedule ( ) ; test . setInterval ( "" ) ; schedule . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( schedule ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; IntervalTo expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testOverMidnightWednesday ( ) throws ParseException { WeeklySchedule day = new WeeklySchedule ( ) ; day . setOn ( DayOfWeek . Days . WEDNESDAY ) ; DailySchedule time = new DailySchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; IntervalSchedule test = new IntervalSchedule ( ) ; test . setInterval ( "" ) ; day . setRefinement ( time ) ; time . setRefinement ( test ) ; ScheduleContext scheduleContext = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval nextDue ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; nextDue = day . nextDue ( scheduleContext ) ; assertEquals ( expected , nextDue ) ; scheduleContext = scheduleContext . move ( expected . getToDate ( ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; nextDue = day . nextDue ( scheduleContext ) ; assertEquals ( expected , nextDue ) ; scheduleContext = scheduleContext . move ( expected . getToDate ( ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; nextDue = day . nextDue ( scheduleContext ) ; assertEquals ( expected , nextDue ) ; } public void testInALargeParentInterval ( ) throws ParseException { DateSchedule date = new DateSchedule ( ) ; date . setFrom ( "" ) ; IntervalSchedule test = new IntervalSchedule ( ) ; test . setInterval ( "" ) ; date . setRefinement ( test ) ; ScheduleContext scheduleContext = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result = date . nextDue ( scheduleContext ) ; assertEquals ( expected , result ) ; } public void testIntervalExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testBadInterval ( ) throws ParseException { IntervalSchedule test = new IntervalSchedule ( ) ; test . setInterval ( "" ) ; ScheduleContext scheduleContext = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; try { test . nextDue ( scheduleContext ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Date ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . SimpleInterval ; import org . oddjob . schedules . SimpleScheduleResult ; public class CountScheduleTest extends TestCase { private static class Counter implements Schedule { int count ; public IntervalTo nextDue ( ScheduleContext context ) { count ++ ; return new IntervalTo ( new Date ( ) ) ; } } public void testCount ( ) { CountSchedule test = new CountSchedule ( ) ; test . setCount ( ) ; Counter counter = new Counter ( ) ; test . setRefinement ( counter ) ; Interval nextDue = null ; ScheduleContext context = new ScheduleContext ( new Date ( ) ) ; do { context = context . move ( new Date ( context . getDate ( ) . getTime ( ) + ) ) ; nextDue = test . nextDue ( context ) ; } while ( nextDue != null ) ; assertEquals ( , counter . count ) ; nextDue = test . nextDue ( context ) ; assertEquals ( null , nextDue ) ; } public void testWithParentInterval ( ) throws ParseException { CountSchedule test = new CountSchedule ( ) ; test . setCount ( ) ; Counter counter = new Counter ( ) ; test . setRefinement ( counter ) ; Interval nextDue = null ; ScheduleContext context = new ScheduleContext ( new Date ( ) ) ; context = context . spawn ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; do { nextDue = test . nextDue ( context ) ; } while ( nextDue != null ) ; assertEquals ( , counter . count ) ; context = context . spawn ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; do { nextDue = test . nextDue ( context ) ; } while ( nextDue != null ) ; assertEquals ( , counter . count ) ; } public void testHowManyNextDues ( ) { int count = ; CountSchedule test = new CountSchedule ( ) ; ScheduleContext context = new ScheduleContext ( new Date ( ) ) ; while ( test . nextDue ( context ) != null ) { context = context . move ( new Date ( context . getDate ( ) . getTime ( ) + ) ) ; ++ count ; } assertEquals ( , count ) ; } public void testSerialize ( ) throws Exception { CountSchedule test = new CountSchedule ( ) ; test . setCount ( ) ; Date now = new Date ( ) ; Map < Object , Object > map = new HashMap < Object , Object > ( ) ; ScheduleContext context = new ScheduleContext ( now , null , map ) ; Interval interval = test . nextDue ( context ) ; assertNotNull ( interval ) ; Schedule copy = ( Schedule ) Helper . copy ( test ) ; context = new ScheduleContext ( new Date ( now . getTime ( ) + ) , null , map ) ; interval = copy . nextDue ( context ) ; assertEquals ( null , interval ) ; } public void testCountExample ( ) throws ArooaParseException , ParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval [ ] results = new ScheduleRoller ( schedule ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = null ; assertEquals ( expected , results [ ] ) ; } public void testCountDaily ( ) throws ArooaParseException , ParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval [ ] results = new ScheduleRoller ( schedule , ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; } public void testCountDifferentCounts ( ) throws ArooaParseException , ParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval [ ] results = new ScheduleRoller ( schedule , ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = null ; assertEquals ( expected , results [ ] ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . ScheduleContext ; public class NowScheduleTest extends TestCase { public void testNow ( ) throws ParseException { NowSchedule test = new NowSchedule ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; Interval expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testNowWithLimits ( ) throws ParseException { NowSchedule test = new NowSchedule ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; context = context . spawn ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ) ; Interval result = test . nextDue ( context ) ; Interval expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; context = context . spawn ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ) ; result = test . nextDue ( context ) ; expected = null ; assertEquals ( expected , result ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Date ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . units . DayOfMonth ; import org . oddjob . schedules . units . Month ; public class MonthScheduleTest extends TestCase { @ Override protected void setUp ( ) throws Exception { TimeZone . setDefault ( null ) ; } public void testFromAndTo ( ) throws ParseException { YearlySchedule schedule = new YearlySchedule ( ) ; schedule . setFromMonth ( Month . Months . FEBRUARY ) ; schedule . setToMonth ( Month . Months . APRIL ) ; Date now1 = DateHelper . parseDateTime ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertEquals ( expected , result ) ; } public void testAfter ( ) throws ParseException { YearlySchedule schedule = new YearlySchedule ( ) ; schedule . setFromMonth ( Month . Months . FEBRUARY ) ; schedule . setToMonth ( Month . Months . APRIL ) ; Date now1 = DateHelper . parseDateTime ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertEquals ( expected , result ) ; } public void testOverBoundry ( ) throws ParseException { YearlySchedule schedule = new YearlySchedule ( ) ; schedule . setFromMonth ( Month . Months . NOVEMBER ) ; schedule . setToMonth ( Month . Months . FEBRUARY ) ; Date now1 = DateHelper . parseDateTime ( "" ) ; ScheduleContext context1 = new ScheduleContext ( now1 ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result1 = schedule . nextDue ( context1 ) ; assertEquals ( expected , result1 ) ; Date now2 = DateHelper . parseDateTime ( "" ) ; ScheduleContext context2 = new ScheduleContext ( now2 ) ; Interval result2 = schedule . nextDue ( context2 ) ; assertEquals ( expected , result2 ) ; Date now3 = DateHelper . parseDateTime ( "" ) ; ScheduleContext context3 = new ScheduleContext ( now3 ) ; Interval result3 = schedule . nextDue ( context3 ) ; assertEquals ( expected , result3 ) ; } public void testWithTime ( ) throws ParseException { YearlySchedule test = new YearlySchedule ( ) ; test . setInMonth ( Month . Months . JANUARY ) ; DailySchedule time = new DailySchedule ( ) ; time . setAt ( "" ) ; test . setRefinement ( time ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testMonthExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testMonthExample2 ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testYearlyInFebuaryIncludingLeapYears ( ) throws ParseException { YearlySchedule test = new YearlySchedule ( ) ; test . setInMonth ( Month . Months . FEBRUARY ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testLastDayInFebuaryIncludingLeapYears ( ) throws ParseException { YearlySchedule test = new YearlySchedule ( ) ; test . setInMonth ( Month . Months . FEBRUARY ) ; MonthlySchedule monthly = new MonthlySchedule ( ) ; monthly . setOnDay ( DayOfMonth . Shorthands . LAST ) ; test . setRefinement ( monthly ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleList ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . SimpleInterval ; import org . oddjob . schedules . SimpleScheduleResult ; import org . oddjob . schedules . units . DayOfMonth ; import org . oddjob . schedules . units . DayOfWeek ; public class BrokenScheduleTest extends TestCase { static Schedule brokenSchedule ( ) throws ParseException , NoConversionAvailableException , ConversionFailedException { WeeklySchedule d1 = new WeeklySchedule ( ) ; d1 . setOn ( DayOfWeek . Days . MONDAY ) ; WeeklySchedule d2 = new WeeklySchedule ( ) ; d2 . setOn ( DayOfWeek . Days . WEDNESDAY ) ; ScheduleList s1 = new ScheduleList ( ) ; s1 . setSchedules ( new Schedule [ ] { d1 , d2 } ) ; YearlySchedule s2 = new YearlySchedule ( ) ; s2 . setFromDate ( "" ) ; s2 . setToDate ( "" ) ; BrokenSchedule b = new BrokenSchedule ( ) ; b . setSchedule ( s1 ) ; b . setBreaks ( s2 ) ; return b ; } public void testFromStartBeforeBreaks ( ) throws Exception { Schedule s = brokenSchedule ( ) ; IntervalTo expected ; ScheduleRoller roller = new ScheduleRoller ( s ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testFromStartOnBreak ( ) throws Exception { Schedule s = brokenSchedule ( ) ; IntervalTo expected ; ScheduleRoller roller = new ScheduleRoller ( s ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testStartAfterBreaks ( ) throws Exception { Schedule s = brokenSchedule ( ) ; IntervalTo expected ; ScheduleRoller roller = new ScheduleRoller ( s ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testScheduleSpansBreaks ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; MonthlySchedule breaks = new MonthlySchedule ( ) ; breaks . setOnDay ( new DayOfMonth . Number ( ) ) ; BrokenSchedule test = new BrokenSchedule ( ) ; test . setBreaks ( breaks ) ; test . setSchedule ( schedule ) ; ScheduleRoller roller = new ScheduleRoller ( test ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testWithTimeThatIsMaskedByBreak ( ) throws ParseException { DateSchedule date = new DateSchedule ( ) ; date . setOn ( "" ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setAt ( "" ) ; BrokenSchedule broken = new BrokenSchedule ( ) ; broken . setSchedule ( time ) ; broken . setBreaks ( date ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult result = broken . nextDue ( context ) ; assertEquals ( null , result ) ; } public void testOverlappingSchedule ( ) throws ParseException { WeeklySchedule dayOfWeekSchedule = new WeeklySchedule ( ) ; dayOfWeekSchedule . setOn ( DayOfWeek . Days . THURSDAY ) ; DailySchedule time = new DailySchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; dayOfWeekSchedule . setRefinement ( time ) ; DateSchedule aBreak = new DateSchedule ( ) ; aBreak . setFrom ( "" ) ; aBreak . setTo ( "" ) ; BrokenSchedule test = new BrokenSchedule ( ) ; test . setSchedule ( dayOfWeekSchedule ) ; test . setBreaks ( aBreak ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; ScheduleContext scheduleContext = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult result = test . nextDue ( scheduleContext ) ; assertEquals ( expected , result ) ; scheduleContext = scheduleContext . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( scheduleContext ) ; assertEquals ( expected , result ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; scheduleContext = scheduleContext . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( scheduleContext ) ; assertEquals ( expected , result ) ; scheduleContext = scheduleContext . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( scheduleContext ) ; assertEquals ( expected , result ) ; scheduleContext = scheduleContext . move ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( scheduleContext ) ; assertEquals ( expected , result ) ; } public void testOverlappingIntervalSchedule ( ) throws ParseException { WeeklySchedule dayOfWeekSchedule = new WeeklySchedule ( ) ; dayOfWeekSchedule . setOn ( DayOfWeek . Days . THURSDAY ) ; DailySchedule time = new DailySchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; dayOfWeekSchedule . setRefinement ( time ) ; time . setRefinement ( interval ) ; DateSchedule aBreak = new DateSchedule ( ) ; aBreak . setFrom ( "" ) ; aBreak . setTo ( "" ) ; BrokenSchedule test = new BrokenSchedule ( ) ; test . setSchedule ( dayOfWeekSchedule ) ; test . setBreaks ( aBreak ) ; IntervalTo expected ; ScheduleRoller roller = new ScheduleRoller ( test ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testAlternateScheduleInternals ( ) throws ParseException { final List < Interval > parentIntervals = new ArrayList < Interval > ( ) ; class Alt implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { parentIntervals . add ( context . getParentInterval ( ) ) ; DailySchedule daily = new DailySchedule ( ) ; daily . setAt ( "" ) ; return daily . nextDue ( context ) ; } } Schedule schedule = new DailySchedule ( ) ; DateSchedule holiday1 = new DateSchedule ( ) ; holiday1 . setOn ( "" ) ; DateSchedule holiday2 = new DateSchedule ( ) ; holiday2 . setOn ( "" ) ; ScheduleList holidayList = new ScheduleList ( ) ; holidayList . setSchedules ( new Schedule [ ] { holiday1 , holiday2 } ) ; BrokenSchedule test = new BrokenSchedule ( ) ; test . setSchedule ( schedule ) ; test . setBreaks ( holidayList ) ; test . setAlternative ( new Alt ( ) ) ; ScheduleResult expected ; ScheduleRoller roller = new ScheduleRoller ( test ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; assertEquals ( , parentIntervals . size ( ) ) ; assertEquals ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , parentIntervals . get ( ) ) ; assertEquals ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , parentIntervals . get ( ) ) ; } public void testAlternateScheduleOverWeekend ( ) throws ParseException { final List < Interval > parentIntervals = new ArrayList < Interval > ( ) ; class Alt implements Schedule { @ Override public ScheduleResult nextDue ( ScheduleContext context ) { parentIntervals . add ( context . getParentInterval ( ) ) ; DailySchedule daily = new DailySchedule ( ) ; daily . setAt ( "" ) ; return daily . nextDue ( context ) ; } } Schedule dailySchedule = new DailySchedule ( ) ; WeeklySchedule schedule = new WeeklySchedule ( ) ; schedule . setFrom ( DayOfWeek . Days . MONDAY ) ; schedule . setTo ( DayOfWeek . Days . FRIDAY ) ; schedule . setRefinement ( dailySchedule ) ; DateSchedule goodFriday = new DateSchedule ( ) ; goodFriday . setOn ( "" ) ; DateSchedule easterMonday = new DateSchedule ( ) ; easterMonday . setOn ( "" ) ; ScheduleList holidayList = new ScheduleList ( ) ; holidayList . setSchedules ( new Schedule [ ] { goodFriday , easterMonday } ) ; BrokenSchedule test = new BrokenSchedule ( ) ; test . setSchedule ( schedule ) ; test . setBreaks ( holidayList ) ; test . setAlternative ( new Alt ( ) ) ; ScheduleResult expected ; ScheduleRoller roller = new ScheduleRoller ( test ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; assertEquals ( , parentIntervals . size ( ) ) ; assertEquals ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , parentIntervals . get ( ) ) ; assertEquals ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , parentIntervals . get ( ) ) ; } public void testBrokenScheduleExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleResult next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testBrokenScheduleAlternative ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleResult [ ] results = new ScheduleRoller ( schedule ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . units . DayOfWeek ; public class TimeOverDSTBoundryTest extends TestCase { public void testDayLightSavingInAutumnWithAtBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setAt ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithAtBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setAt ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnWithAtBoundry2 ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setAt ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithAtBoundry2 ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setAt ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnWithFromToOnBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithFromToOnBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnWithFromToSpanningBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithFromToSpanningBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnWithFromToSpanningBoundry2 ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringWithFromToSpanningBoundry2 ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInAutumnOverMidnightSpanningBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } public void testDayLightSavingInSpringOverMidnightSpanningBoundry ( ) throws ParseException { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; TimeSchedule test = new TimeSchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; WeeklySchedule weekly = new WeeklySchedule ( ) ; weekly . setOn ( DayOfWeek . Days . SUNDAY ) ; weekly . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( weekly ) ; ScheduleResult [ ] results = roller . resultsFrom ( DateHelper . parseDate ( "" ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; TimeZone . setDefault ( null ) ; } } package org . oddjob . schedules . schedules ; import java . text . DateFormat ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . SimpleInterval ; import org . oddjob . schedules . SimpleScheduleResult ; public class AfterScheduleTest extends TestCase { static DateFormat checkFormat = new SimpleDateFormat ( "" ) ; static DateFormat inputFormat = new SimpleDateFormat ( "" ) ; public void testAfterInterval ( ) throws ParseException { AfterSchedule after = new AfterSchedule ( ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; after . setSchedule ( interval ) ; ScheduleResult [ ] results = new ScheduleRoller ( after ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testAfterEndOfSchedule ( ) throws ParseException { AfterSchedule after = new AfterSchedule ( ) ; DateSchedule interval = new DateSchedule ( ) ; interval . setOn ( "" ) ; after . setSchedule ( interval ) ; Interval [ ] results = new ScheduleRoller ( after ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , IntervalTo . END_OF_TIME ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; assertEquals ( null , results [ ] ) ; } public void testAfterExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult next = schedule . nextDue ( context ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( context . move ( DateHelper . parseDate ( "" ) ) ) ; assertEquals ( null , next ) ; } public void testAfterBusinessDays ( ) throws ArooaParseException , ParseException { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleResult [ ] results = new ScheduleRoller ( schedule ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; Interval expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Date ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . units . DayOfWeek ; public class DailyScheduleTest extends TestCase { private static final Logger logger = Logger . getLogger ( "" ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } public void testStandardIntervalDifferentStarts ( ) throws ParseException { DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testStandardIntervalRollingNext ( ) throws ParseException { DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getToDate ( ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getToDate ( ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testForwardInterval ( ) throws ParseException { DailySchedule s = new DailySchedule ( ) ; s . setFrom ( "" ) ; s . setTo ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result = s . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; result = s . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; result = s . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; } public void testSimple ( ) throws ParseException { DailySchedule s = new DailySchedule ( ) ; s . setFrom ( "" ) ; s . setTo ( "" ) ; Date on ; ScheduleContext context ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; } public void testOverMidnight ( ) throws ParseException { DailySchedule s = new DailySchedule ( ) ; s . setFrom ( "" ) ; s . setTo ( "" ) ; Date on ; ScheduleContext context ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; } public void testOn ( ) throws ParseException { DailySchedule s = new DailySchedule ( ) ; s . setAt ( "" ) ; Date on ; ScheduleContext context ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; Interval result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; result = s . nextDue ( context ) ; assertEquals ( expected , result ) ; } public void testWithLimits ( ) throws ParseException { DailySchedule test = new DailySchedule ( ) ; test . setAt ( "" ) ; Date on ; ScheduleContext context ; on = DateHelper . parseDateTime ( "" ) ; context = new ScheduleContext ( on ) ; context . spawn ( new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testDefaultTo ( ) throws Exception { DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; logger . debug ( "" + result ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getToDate ( ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; } public void testDefaultFrom ( ) throws Exception { DailySchedule s = new DailySchedule ( ) ; s . setTo ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = s . nextDue ( context ) ; logger . debug ( "" + result ) ; assertEquals ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , result ) ; } public void testWithInterval ( ) throws Exception { DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; IntervalSchedule intervalSchedule = new IntervalSchedule ( ) ; intervalSchedule . setInterval ( "" ) ; test . setRefinement ( intervalSchedule ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; logger . debug ( "" + result ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; result = test . nextDue ( context . move ( result . getToDate ( ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testAsChildWithInterval ( ) throws Exception { DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; IntervalSchedule intervalSchedule = new IntervalSchedule ( ) ; intervalSchedule . setInterval ( "" ) ; WeeklySchedule dayOfWeek = new WeeklySchedule ( ) ; dayOfWeek . setOn ( DayOfWeek . Days . MONDAY ) ; test . setRefinement ( intervalSchedule ) ; dayOfWeek . setRefinement ( test ) ; ScheduleRoller roller = new ScheduleRoller ( dayOfWeek ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; IntervalTo expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testTimeAfter24 ( ) throws ParseException { DailySchedule test = new DailySchedule ( ) ; test . setFrom ( "" ) ; test . setTo ( "" ) ; ScheduleContext context ; Interval expected ; Interval result ; context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = test . nextDue ( context ) ; assertEquals ( expected , result ) ; context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; result = test . nextDue ( context ) ; assertEquals ( expected , result ) ; } public void testTwoNestedTimes ( ) throws ParseException { DailySchedule schedule = new DailySchedule ( ) ; schedule . setFrom ( "" ) ; DailySchedule retry = new DailySchedule ( ) ; retry . setTo ( "" ) ; schedule . setRefinement ( retry ) ; ScheduleRoller roller = new ScheduleRoller ( schedule ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; assertNull ( results [ ] ) ; } public void testLimitedTimeAndAnInterval ( ) throws ParseException { DailySchedule retry = new DailySchedule ( ) ; retry . setFrom ( "" ) ; retry . setTo ( "" ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; retry . setRefinement ( interval ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; context = context . spawn ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; Interval expected ; Interval result ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; result = retry . nextDue ( context ) ; assertEquals ( expected , result ) ; result = retry . nextDue ( context . move ( expected . getToDate ( ) ) ) ; assertNull ( result ) ; } public void testDefaultTimesRollingForward ( ) throws ParseException { DailySchedule test = new DailySchedule ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getToDate ( ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleScheduleResult ; public class TimeScheduleExamplesTest extends TestCase { public void testSimpleExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; TimeSchedule schedule = ( TimeSchedule ) parser . getRoot ( ) ; assertEquals ( "" , schedule . getFrom ( ) ) ; assertEquals ( "" , schedule . getTo ( ) ) ; ScheduleResult expected , result ; result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , result ) ; result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = null ; assertEquals ( expected , result ) ; } public void testTimeAndIntervalExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; ScheduleResult expected ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , null ) ; assertEquals ( expected , next ) ; } } package org . oddjob . schedules . schedules ; import java . text . DateFormat ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Calendar ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . ScheduleRoller ; import org . oddjob . schedules . SimpleScheduleResult ; import org . oddjob . schedules . units . DayOfMonth ; import org . oddjob . schedules . units . DayOfWeek ; import org . oddjob . schedules . units . WeekOfMonth ; public class MonthlyScheduleTest extends TestCase { DateFormat checkFormat ; DateFormat inputFormat ; protected void setUp ( ) { checkFormat = new SimpleDateFormat ( "" ) ; inputFormat = new SimpleDateFormat ( "" ) ; } public void testFromAndTo ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; schedule . setFromDay ( new DayOfMonth . Number ( ) ) ; schedule . setToDay ( new DayOfMonth . Number ( ) ) ; Date now1 = inputFormat . parse ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertEquals ( expected , result ) ; } public void testAfter ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; schedule . setFromDay ( new DayOfMonth . Number ( ) ) ; schedule . setToDay ( new DayOfMonth . Number ( ) ) ; Date now1 = inputFormat . parse ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertEquals ( expected , result ) ; } public void testOverBoundry ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; schedule . setFromDay ( new DayOfMonth . Number ( ) ) ; schedule . setToDay ( new DayOfMonth . Number ( ) ) ; Date now1 = inputFormat . parse ( "" ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; Interval result1 = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertEquals ( expected , result1 ) ; Date now2 = inputFormat . parse ( "" ) ; Interval result2 = schedule . nextDue ( new ScheduleContext ( now2 ) ) ; assertEquals ( expected , result2 ) ; Date now3 = inputFormat . parse ( "" ) ; Interval result3 = schedule . nextDue ( new ScheduleContext ( now3 ) ) ; assertEquals ( expected , result3 ) ; } public void testLastDay ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; schedule . setFromDay ( new DayOfMonth . Number ( ) ) ; schedule . setToDay ( DayOfMonth . Shorthands . LAST ) ; Date now1 = inputFormat . parse ( "" ) ; Interval interval1 = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; IntervalTo expected1 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertTrue ( "" , interval1 . equals ( expected1 ) ) ; Interval interval2 = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; IntervalTo expected2 = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected2 , interval2 ) ; } public void testPenultimateDayOfMonth ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; schedule . setFromDay ( new DayOfMonth . Number ( ) ) ; schedule . setToDay ( DayOfMonth . Shorthands . PENULTIMATE ) ; ScheduleResult [ ] results = new ScheduleRoller ( schedule ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testLastDayOfMonthWithTimeOverMidnight ( ) throws ParseException { MonthlySchedule test = new MonthlySchedule ( ) ; test . setOnDay ( DayOfMonth . Shorthands . LAST ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; test . setRefinement ( time ) ; ScheduleResult [ ] results = new ScheduleRoller ( test ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; results = new ScheduleRoller ( test ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , results [ ] ) ; } public void testDefaultFrom ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; schedule . setToDay ( new DayOfMonth . Number ( ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; assertEquals ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , result ) ; } public void testDefaultTo ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; schedule . setFromDay ( new DayOfMonth . Number ( ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testInclusive ( ) throws ParseException { MonthlySchedule schedule = new MonthlySchedule ( ) ; schedule . setToDay ( new DayOfMonth . Number ( ) ) ; Interval result = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; assertEquals ( new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , result ) ; } public void testDayOfMonthExample1 ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval next = schedule . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( context . move ( expected . getToDate ( ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testDayOfMonthExample2 ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval next = schedule . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; next = schedule . nextDue ( context . move ( expected . getToDate ( ) ) ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testShiftFromCalendar ( ) throws ParseException { MonthlySchedule test = new MonthlySchedule ( ) ; test . setOnDayOfWeek ( DayOfWeek . Days . FRIDAY ) ; test . setInWeek ( WeekOfMonth . Weeks . LAST ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( , , ) ; Calendar result = test . shiftFromCalendar ( calendar , ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; } public void testDayOfWeekInMonth ( ) throws ParseException { MonthlySchedule test = new MonthlySchedule ( ) ; test . setOnDayOfWeek ( DayOfWeek . Days . FRIDAY ) ; test . setInWeek ( WeekOfMonth . Weeks . LAST ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setAt ( "" ) ; test . setRefinement ( time ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = test . nextDue ( context ) ; ScheduleResult expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , result ) ; } public void testDayOfWeekInMonthOverBoundry ( ) throws ParseException { MonthlySchedule test = new MonthlySchedule ( ) ; test . setFromDayOfWeek ( DayOfWeek . Days . FRIDAY ) ; test . setFromWeek ( WeekOfMonth . Weeks . LAST ) ; test . setToDayOfWeek ( DayOfWeek . Days . MONDAY ) ; test . setToWeek ( WeekOfMonth . Weeks . FIRST ) ; DailySchedule time = new DailySchedule ( ) ; time . setAt ( "" ) ; test . setRefinement ( time ) ; Interval [ ] results = new ScheduleRoller ( test , ) . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; assertEquals ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , results [ ] ) ; assertEquals ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , results [ ] ) ; assertEquals ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , results [ ] ) ; assertEquals ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) , results [ ] ) ; } public void testLastFridayOfMonth ( ) throws ParseException , ArooaParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleRoller roller = new ScheduleRoller ( schedule , ) ; Interval [ ] results = roller . resultsFrom ( DateHelper . parseDateTime ( "" ) ) ; ScheduleResult expected ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; expected = new SimpleScheduleResult ( new IntervalTo ( DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expected , results [ ] ) ; } public void testToString ( ) { MonthlySchedule test = new MonthlySchedule ( ) ; test . setOnDayOfWeek ( DayOfWeek . Days . FRIDAY ) ; test . setInWeek ( WeekOfMonth . Weeks . LAST ) ; String expected = "" ; assertEquals ( expected , test . toString ( ) ) ; test = new MonthlySchedule ( ) ; test . setFromDay ( new DayOfMonth . Number ( ) ) ; test . setToDay ( new DayOfMonth . Number ( ) ) ; expected = "" ; assertEquals ( expected , test . toString ( ) ) ; test = new MonthlySchedule ( ) ; expected = "" ; assertEquals ( expected , test . toString ( ) ) ; test = new MonthlySchedule ( ) ; test . setInWeek ( WeekOfMonth . Weeks . FIRST ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setAt ( "" ) ; test . setRefinement ( time ) ; expected = "" ; assertEquals ( expected , test . toString ( ) ) ; } public static void main ( String ... args ) throws ParseException { Calendar cal = Calendar . getInstance ( ) ; System . out . println ( cal . getMinimalDaysInFirstWeek ( ) ) ; System . out . println ( cal . getFirstDayOfWeek ( ) ) ; YearlySchedule test = new YearlySchedule ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; Interval month = test . nextDue ( context ) ; TimeSchedule daily = new TimeSchedule ( ) ; context = context . spawn ( month . getFromDate ( ) , month ) ; while ( true ) { Interval next = daily . nextDue ( context ) ; if ( next == null ) { break ; } cal . setTime ( next . getFromDate ( ) ) ; System . out . println ( next . getFromDate ( ) + "" + cal . get ( Calendar . DAY_OF_WEEK_IN_MONTH ) + "" + cal . get ( Calendar . DAY_OF_WEEK ) + "" + cal . get ( Calendar . WEEK_OF_MONTH ) ) ; context = context . move ( next . getToDate ( ) ) ; } } } package org . oddjob . schedules . schedules ; import java . text . DateFormat ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . units . DayOfWeek ; public class OccurenceScheduleTest extends TestCase { static DateFormat checkFormat = new SimpleDateFormat ( "" ) ; static DateFormat inputFormat = new SimpleDateFormat ( "" ) ; public void testBasic ( ) throws ParseException { OccurrenceSchedule schedule = new OccurrenceSchedule ( ) ; schedule . setOccurrence ( "" ) ; MockSchedule child = new MockSchedule ( ) ; child . setResults ( new IntervalTo [ ] { new IntervalTo ( inputFormat . parse ( "" ) , inputFormat . parse ( "" ) ) , new IntervalTo ( inputFormat . parse ( "" ) , inputFormat . parse ( "" ) ) } ) ; schedule . setRefinement ( child ) ; Date now1 = inputFormat . parse ( "" ) ; IntervalTo expected = new IntervalTo ( inputFormat . parse ( "" ) , inputFormat . parse ( "" ) ) ; Interval actual = schedule . nextDue ( new ScheduleContext ( now1 ) ) ; assertTrue ( "" + actual + "" , expected . equals ( actual ) ) ; } public void testOutsideLimits ( ) throws ParseException { OccurrenceSchedule test = new OccurrenceSchedule ( ) ; test . setOccurrence ( "" ) ; MockSchedule child = new MockSchedule ( ) ; child . setResults ( new IntervalTo [ ] { new IntervalTo ( inputFormat . parse ( "" ) , inputFormat . parse ( "" ) ) , new IntervalTo ( inputFormat . parse ( "" ) , inputFormat . parse ( "" ) ) } ) ; test . setRefinement ( child ) ; Date now1 = inputFormat . parse ( "" ) ; IntervalTo expected = null ; ScheduleContext context = new ScheduleContext ( now1 ) ; context = context . spawn ( new IntervalTo ( inputFormat . parse ( "" ) , inputFormat . parse ( "" ) ) ) ; Interval actual = test . nextDue ( context ) ; assertEquals ( expected , actual ) ; } class MockSchedule implements Schedule { IntervalTo [ ] results ; int next ; public void setResults ( IntervalTo [ ] results ) { this . results = results ; next = ; } public void setLimits ( IntervalTo limits ) { } public IntervalTo nextDue ( ScheduleContext context ) { if ( results == null ) { return null ; } if ( next < results . length ) { return results [ next ++ ] ; } return null ; } } public void testThirdWednesday ( ) throws ParseException { MonthlySchedule monthly = new MonthlySchedule ( ) ; OccurrenceSchedule occurrence = new OccurrenceSchedule ( ) ; occurrence . setOccurrence ( new Integer ( ) . toString ( ) ) ; WeeklySchedule day = new WeeklySchedule ( ) ; day . setOn ( DayOfWeek . Days . WEDNESDAY ) ; monthly . setRefinement ( occurrence ) ; occurrence . setRefinement ( day ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ; Interval result = monthly . nextDue ( context ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , result ) ; } public void testOccurenceExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } } package org . oddjob . schedules . schedules ; import java . text . ParseException ; import java . util . Calendar ; import java . util . Date ; import java . util . TimeZone ; import junit . framework . TestCase ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; public class YearlyScheduleTest extends TestCase { public void testParseDay ( ) throws ParseException { Date referenceDate = DateHelper . parseDate ( "" ) ; TimeZone timeZone = TimeZone . getDefault ( ) ; Calendar result = YearlySchedule . parseDay ( "" , referenceDate , timeZone ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = YearlySchedule . parseDay ( "" , referenceDate , timeZone ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; result = YearlySchedule . parseDay ( "" , referenceDate , timeZone ) ; assertEquals ( DateHelper . parseDate ( "" ) , result . getTime ( ) ) ; try { YearlySchedule . parseDay ( "" , referenceDate , timeZone ) ; } catch ( ParseException e ) { } } public void testNextDue1 ( ) throws ParseException { YearlySchedule test = new YearlySchedule ( ) ; test . setFromDate ( "" ) ; test . setToDate ( "" ) ; ScheduleContext c = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; Interval result = test . nextDue ( c ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; c = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; result = test . nextDue ( c ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; c = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; result = test . nextDue ( c ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; c = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; result = test . nextDue ( c ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; } public void testOverYearBoundary ( ) throws ParseException { YearlySchedule s = new YearlySchedule ( ) ; s . setFromDate ( "" ) ; s . setToDate ( "" ) ; ScheduleContext c = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; Interval result = s . nextDue ( c ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; } public void testOn ( ) throws ParseException { YearlySchedule test = new YearlySchedule ( ) ; test . setOnDate ( "" ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; ScheduleResult result = test . nextDue ( context ) ; ScheduleResult expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; context = context . move ( result . getUseNext ( ) ) ; result = test . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; } public void test29thFeb ( ) throws ParseException { YearlySchedule test = new YearlySchedule ( ) ; test . setOnDate ( "" ) ; ScheduleContext c = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; Interval result = test . nextDue ( c ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDate ( "" ) , DateHelper . parseDate ( "" ) ) ; assertEquals ( expected , result ) ; } public void testFromToExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; Interval next = schedule . nextDue ( new ScheduleContext ( DateHelper . parseDate ( "" ) ) ) ; IntervalTo expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } public void testOnExample ( ) throws ArooaParseException , ParseException { OddjobDescriptorFactory df = new OddjobDescriptorFactory ( ) ; ArooaDescriptor descriptor = df . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . parse ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; Schedule schedule = ( Schedule ) parser . getRoot ( ) ; ScheduleContext context = new ScheduleContext ( DateHelper . parseDate ( "" ) ) ; ScheduleResult next = schedule . nextDue ( context ) ; ScheduleResult expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; context = context . move ( next . getUseNext ( ) ) ; next = schedule . nextDue ( context ) ; expected = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; assertEquals ( expected , next ) ; } } package org . oddjob ; import javax . inject . Inject ; import junit . framework . TestCase ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . input . InputHandler ; import org . oddjob . state . ParentState ; public class OddjobServicesTest extends TestCase { public static class MyOddjobAware implements Runnable { OddjobServices oddjobServices ; @ Inject public void setOddjobServices ( OddjobServices oddjobServices ) { this . oddjobServices = oddjobServices ; } public OddjobServices getOddjobServices ( ) { return oddjobServices ; } public void run ( ) { } } public void testDefaultServices ( ) throws ArooaConversionException { String xml = "" + "" + "" + MyOddjobAware . class . getName ( ) + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; test . setOddjobServices ( new MyOddjobServices ( ) ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; OddjobServices result = new OddjobLookup ( test ) . lookup ( "" , OddjobServices . class ) ; assertNotNull ( result ) ; test . destroy ( ) ; } class MyOddjobServices extends MockOddjobServices { @ Override public Object getService ( String serviceName ) { assertEquals ( ODDJOB_SERVICES , serviceName ) ; return this ; } @ Override public String serviceNameFor ( Class < ? > theClass , String flavour ) { assertEquals ( OddjobServices . class , theClass ) ; return ODDJOB_SERVICES ; } @ Override public ClassLoader getClassLoader ( ) { return getClass ( ) . getClassLoader ( ) ; } @ Override public OddjobExecutors getOddjobExecutors ( ) { return null ; } @ Override public InputHandler getInputHandler ( ) { return null ; } } public void testMyServices ( ) throws ArooaConversionException { String xml = "" + "" + "" + MyOddjobAware . class . getName ( ) + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setOddjobServices ( new MyOddjobServices ( ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; OddjobServices result = new OddjobLookup ( test ) . lookup ( "" , OddjobServices . class ) ; assertNotNull ( result ) ; test . destroy ( ) ; } public void testNestedServices ( ) throws ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + MyOddjobAware . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . setOddjobServices ( new MyOddjobServices ( ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; OddjobServices result = new OddjobLookup ( test ) . lookup ( "" , OddjobServices . class ) ; assertNotNull ( result ) ; test . destroy ( ) ; } } package org . oddjob . persist ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . registry . Path ; public class MockPersisterBase extends PersisterBase { @ Override protected void clear ( Path path ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override protected void persist ( Path path , String id , Object component ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override protected String [ ] list ( Path path ) throws ComponentPersistException { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override protected void remove ( Path path , String id ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override protected Object restore ( Path path , String id , ClassLoader classLoader ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . persist ; import java . io . File ; import java . io . IOException ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . IconSteps ; import org . oddjob . Oddjob ; import org . oddjob . OurDirs ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . images . IconHelper ; import org . oddjob . jobs . WaitJob ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . scheduling . Trigger ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class ArchiveJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( ArchiveJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public void testWithSimpleJob ( ) throws ComponentPersistException { final MapPersister persister = new MapPersister ( ) ; FlagState job = new FlagState ( ) ; ArchiveJob test = new ArchiveJob ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setArchiver ( persister ) ; test . setArchiveIdentifier ( "" ) ; test . setArchiveName ( "" ) ; test . setJob ( job ) ; StateSteps states = new StateSteps ( test ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; test . run ( ) ; states . checkNow ( ) ; ComponentPersister cp = persister . persisterFor ( "" ) ; Stateful stateful = ( Stateful ) cp . restore ( "" , getClass ( ) . getClassLoader ( ) , null ) ; assertEquals ( JobState . COMPLETE , stateful . lastStateEvent ( ) . getState ( ) ) ; test . destroy ( ) ; } public void testState ( ) throws FailedToStopException , ComponentPersistException , InterruptedException { final MapPersister persister = new MapPersister ( ) ; WaitJob wait = new WaitJob ( ) ; StateSteps waitStates = new StateSteps ( wait ) ; waitStates . startCheck ( JobState . READY , JobState . EXECUTING ) ; Thread t = new Thread ( wait ) ; t . start ( ) ; waitStates . checkWait ( ) ; ArchiveJob test = new ArchiveJob ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setArchiver ( persister ) ; test . setArchiveIdentifier ( "" ) ; test . setArchiveName ( "" ) ; test . setJob ( wait ) ; test . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; wait . stop ( ) ; t . join ( ) ; ComponentPersister cp = persister . persisterFor ( "" ) ; Stateful stateful = ( Stateful ) cp . restore ( "" , getClass ( ) . getClassLoader ( ) , null ) ; assertNotNull ( stateful ) ; assertEquals ( IconHelper . COMPLETE , Helper . getIconId ( stateful ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , stateful . lastStateEvent ( ) . getState ( ) ) ; } public void testReflectsChildState ( ) throws FailedToStopException , ComponentPersistException , InterruptedException { final MapPersister persister = new MapPersister ( ) ; FlagState job = new FlagState ( JobState . INCOMPLETE ) ; ArchiveJob test = new ArchiveJob ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setArchiver ( persister ) ; test . setArchiveIdentifier ( "" ) ; test . setArchiveName ( "" ) ; test . setJob ( job ) ; StateSteps testStates = new StateSteps ( test ) ; testStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . INCOMPLETE ) ; test . run ( ) ; testStates . checkNow ( ) ; ComponentPersister cp = persister . persisterFor ( "" ) ; Stateful stateful = ( Stateful ) cp . restore ( "" , getClass ( ) . getClassLoader ( ) , null ) ; assertNotNull ( stateful ) ; assertEquals ( IconHelper . NOT_COMPLETE , Helper . getIconId ( stateful ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . INCOMPLETE , stateful . lastStateEvent ( ) . getState ( ) ) ; } public void testStop ( ) throws InterruptedException , FailedToStopException { DefaultExecutors executors = new DefaultExecutors ( ) ; final MapPersister persister = new MapPersister ( ) ; FlagState depends = new FlagState ( ) ; FlagState neverRuns = new FlagState ( ) ; Trigger trigger = new Trigger ( ) ; trigger . setExecutorService ( executors . getPoolExecutor ( ) ) ; trigger . setOn ( depends ) ; trigger . setJob ( neverRuns ) ; ArchiveJob test = new ArchiveJob ( ) ; test . setArchiver ( persister ) ; test . setArchiveIdentifier ( "" ) ; test . setArchiveName ( "" ) ; test . setJob ( trigger ) ; StateSteps testStates = new StateSteps ( test ) ; testStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; testStates . checkWait ( ) ; testStates . startCheck ( ParentState . ACTIVE , ParentState . READY ) ; test . stop ( ) ; testStates . checkNow ( ) ; } public void testInOddjob ( ) throws ComponentPersistException , IOException , InterruptedException { OurDirs dirs = new OurDirs ( ) ; File baseDir = dirs . relative ( "" ) ; if ( baseDir . exists ( ) ) { FileUtils . forceDelete ( baseDir ) ; } FileUtils . forceMkdir ( baseDir ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { baseDir . getPath ( ) } ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; state . checkWait ( ) ; oddjob . destroy ( ) ; FilePersister persister = new FilePersister ( ) ; persister . setDir ( baseDir ) ; ComponentPersister thePersister = persister . persisterFor ( "" ) ; String [ ] archives = thePersister . list ( ) ; assertEquals ( , archives . length ) ; } public void testStateChangesForAsynchronousJobs ( ) throws InterruptedException { DefaultExecutors executors = new DefaultExecutors ( ) ; FlagState depends = new FlagState ( ) ; FlagState toTrigger = new FlagState ( ) ; Trigger trigger = new Trigger ( ) ; trigger . setOn ( depends ) ; trigger . setJob ( toTrigger ) ; trigger . setExecutorService ( executors . getPoolExecutor ( ) ) ; final MapPersister persister = new MapPersister ( ) ; ArchiveJob test = new ArchiveJob ( ) ; test . setJob ( trigger ) ; test . setArchiver ( persister ) ; test . setArchiveIdentifier ( "" ) ; StateSteps states = new StateSteps ( test ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . ACTIVE ) ; test . run ( ) ; states . checkNow ( ) ; icons . checkNow ( ) ; states . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; icons . startCheck ( IconHelper . ACTIVE , IconHelper . COMPLETE ) ; depends . run ( ) ; states . checkWait ( ) ; icons . checkWait ( ) ; executors . stop ( ) ; } } package org . oddjob . persist ; import java . io . IOException ; import java . io . NotSerializableException ; import java . io . Serializable ; import junit . framework . TestCase ; import org . oddjob . Helper ; public class SerializationTutorialTest extends TestCase { static class NonSerializable { String fruit ; } static class SerializableSub extends NonSerializable implements Serializable { private static final long serialVersionUID = ; String colour ; } public void testBaseSerialization ( ) throws IOException , ClassNotFoundException { SerializableSub sub = new SerializableSub ( ) ; sub . fruit = "" ; sub . colour = "" ; SerializableSub copy = ( SerializableSub ) Helper . copy ( sub ) ; assertNull ( copy . fruit ) ; assertEquals ( "" , copy . colour ) ; } static class ThinksItsSerializable implements Serializable { private static final long serialVersionUID = ; NonSerializable memeber = new NonSerializable ( ) ; } public void testNonSerializableMemeber ( ) throws ClassNotFoundException { try { Helper . copy ( new ThinksItsSerializable ( ) ) ; fail ( "" ) ; } catch ( IOException e ) { assertTrue ( e instanceof NotSerializableException ) ; } } } package org . oddjob . persist ; import java . io . IOException ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Describeable ; import org . oddjob . Helper ; import org . oddjob . Iconic ; import org . oddjob . Stateful ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . images . IconHelper ; import org . oddjob . jobs . EchoJob ; import org . oddjob . jobs . structural . SequentialJob ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; public class SilhouetteFactoryTest extends TestCase { private static final Logger logger = Logger . getLogger ( SilhouetteFactoryTest . class ) ; @ Override protected void setUp ( ) throws Exception { if ( Thread . interrupted ( ) ) { logger . warn ( "" ) ; } } public void testEqualsAndHashCode ( ) throws IOException , ClassNotFoundException { String a = new String ( "" ) ; String b = new String ( "" ) ; ArooaSession session = new StandardArooaSession ( ) ; Object silhouetteA = Helper . copy ( new SilhouetteFactory ( ) . create ( a , session ) ) ; Object silhouetteB = Helper . copy ( new SilhouetteFactory ( ) . create ( b , session ) ) ; assertEquals ( silhouetteA , silhouetteA ) ; assertEquals ( silhouetteB , silhouetteB ) ; assertFalse ( silhouetteA . equals ( silhouetteB ) ) ; assertEquals ( silhouetteA . hashCode ( ) , silhouetteA . hashCode ( ) ) ; assertEquals ( silhouetteB . hashCode ( ) , silhouetteB . hashCode ( ) ) ; assertFalse ( silhouetteA . hashCode ( ) == silhouetteB . hashCode ( ) ) ; } public void testSimple ( ) throws IOException , ClassNotFoundException { EchoJob echo = new EchoJob ( ) ; echo . setText ( "" ) ; echo . setName ( "" ) ; echo . run ( ) ; ArooaSession session = new StandardArooaSession ( ) ; Object silhouette = Helper . copy ( new SilhouetteFactory ( ) . create ( echo , session ) ) ; assertTrue ( silhouette instanceof Describeable ) ; assertFalse ( silhouette instanceof Stateful ) ; assertFalse ( silhouette instanceof Structural ) ; assertFalse ( silhouette instanceof Iconic ) ; Map < String , String > description = new UniversalDescriber ( new StandardArooaSession ( ) ) . describe ( silhouette ) ; assertEquals ( "" , description . get ( "" ) ) ; assertEquals ( "" , silhouette . toString ( ) ) ; } public void testStateful ( ) throws IOException , ClassNotFoundException { FlagState flag = new FlagState ( ) ; flag . run ( ) ; ArooaSession session = new StandardArooaSession ( ) ; Object silhouette = Helper . copy ( new SilhouetteFactory ( ) . create ( flag , session ) ) ; assertTrue ( silhouette instanceof Stateful ) ; assertTrue ( silhouette instanceof Iconic ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( silhouette ) ) ; assertEquals ( IconHelper . COMPLETE , Helper . getIconId ( silhouette ) ) ; } public void testStructural ( ) throws IOException , ClassNotFoundException { SequentialJob sequential = new SequentialJob ( ) ; FlagState flag = new FlagState ( ) ; sequential . setJobs ( , flag ) ; sequential . run ( ) ; final ArooaSession session = new StandardArooaSession ( ) ; ComponentPool components = session . getComponentPool ( ) ; components . registerComponent ( new ComponentTrinity ( flag , flag , new MockArooaContext ( ) { @ Override public ArooaSession getSession ( ) { return session ; } } ) , null ) ; Object silhouette = Helper . copy ( new SilhouetteFactory ( ) . create ( sequential , session ) ) ; assertTrue ( silhouette instanceof Structural ) ; Object [ ] children = Helper . getChildren ( ( Structural ) silhouette ) ; assertEquals ( , children . length ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( children [ ] ) ) ; } public void testNotOurChildren ( ) throws IOException , ClassNotFoundException { SequentialJob sequential = new SequentialJob ( ) ; FlagState flag = new FlagState ( ) ; sequential . setJobs ( , flag ) ; sequential . run ( ) ; final ArooaSession session = new StandardArooaSession ( ) ; Object silhouette = Helper . copy ( new SilhouetteFactory ( ) . create ( sequential , session ) ) ; assertTrue ( silhouette instanceof Structural ) ; Object [ ] children = Helper . getChildren ( ( Structural ) silhouette ) ; assertEquals ( , children . length ) ; } } package org . oddjob . persist ; import java . io . IOException ; import java . io . Serializable ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . framework . SerializableJob ; public class PersisterBaseTest extends TestCase { public static class OurJob extends SerializableJob implements Serializable { private static final long serialVersionUID = ; @ Override protected int execute ( ) throws Throwable { return ; } } private class OurPersister extends MockPersisterBase { Path path ; String id ; Object component ; @ Override protected void persist ( Path path , String id , Object component ) { this . path = path ; this . id = id ; try { this . component = Helper . copy ( component ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } @ Override protected Object restore ( Path path , String id , ClassLoader classLoader ) { this . path = path ; this . id = id ; return component ; } @ Override protected void remove ( Path path , String id ) { throw new RuntimeException ( "" ) ; } } private class OurContext extends MockArooaContext { ArooaSession session ; OurContext ( ArooaSession session ) { this . session = session ; } @ Override public ArooaSession getSession ( ) { return session ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void configure ( ) { } } ; } } public void testInitialiseAndPersist ( ) throws Exception { final OurPersister test = new OurPersister ( ) ; ArooaSession session = new StandardArooaSession ( ) { @ Override public ComponentPersister getComponentPersister ( ) { return test . persisterFor ( "" ) ; } } ; ComponentPool components = session . getComponentPool ( ) ; OurJob j = new OurJob ( ) ; components . registerComponent ( new ComponentTrinity ( j , j , new OurContext ( session ) ) , "" ) ; j . setArooaSession ( session ) ; j . run ( ) ; assertEquals ( new Path ( "" ) , test . path ) ; assertEquals ( "" , test . id ) ; assertTrue ( test . component instanceof OurJob ) ; ComponentPersister persister = test . persisterFor ( "" ) ; Object restore = persister . restore ( "" , getClass ( ) . getClassLoader ( ) , session ) ; assertEquals ( new Path ( "" ) , test . path ) ; assertEquals ( "" , test . id ) ; assertTrue ( restore instanceof OurJob ) ; } static class OurComp implements Serializable { private static final long serialVersionUID = ; } public void testWithPath ( ) throws ComponentPersistException { OurPersister test = new OurPersister ( ) ; test . setPath ( "" ) ; ComponentPersister persister = test . persisterFor ( null ) ; persister . persist ( "" , new OurComp ( ) , new MockArooaSession ( ) ) ; assertEquals ( new Path ( "" ) , test . path ) ; test . path = null ; Object result = persister . restore ( "" , getClass ( ) . getClassLoader ( ) , new MockArooaSession ( ) ) ; assertEquals ( new Path ( "" ) , test . path ) ; assertEquals ( test . component , result ) ; try { ( ( OddjobPersister ) persister ) . persisterFor ( null ) ; fail ( "" ) ; } catch ( NullPointerException e ) { } ComponentPersister persister2 = ( ( OddjobPersister ) persister ) . persisterFor ( "" ) ; persister2 . persist ( "" , new OurComp ( ) , new MockArooaSession ( ) ) ; assertEquals ( new Path ( "" ) , test . path ) ; test . path = null ; ComponentPersister persister3 = ( ( OddjobPersister ) persister2 ) . persisterFor ( "" ) ; persister3 . persist ( "" , new OurComp ( ) , new MockArooaSession ( ) ) ; assertEquals ( new Path ( "" ) , test . path ) ; } } package org . oddjob . persist ; import java . io . File ; import java . io . Serializable ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . structural . ChildHelper ; public class OddjobPersistTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddjobPersistTest . class ) ; private File config ; private File persistIn ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; OurDirs dirs = new OurDirs ( ) ; config = new File ( dirs . base ( ) , "" ) ; persistIn = new File ( dirs . base ( ) , "" ) ; if ( persistIn . mkdir ( ) ) { logger . debug ( "" + persistIn ) ; } } public void test1Save ( ) throws Exception { FilePersister persister = new FilePersister ( ) ; persister . setDir ( persistIn ) ; persister . setPath ( "" ) ; ComponentPersister componentPersister = persister . persisterFor ( null ) ; componentPersister . clear ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setName ( "" ) ; oj . setFile ( config ) ; oj . run ( ) ; assertEquals ( "" , ParentState . COMPLETE , Helper . getJobState ( oj ) ) ; Object seqJob = new OddjobLookup ( oj ) . lookup ( "" ) ; assertTrue ( seqJob instanceof Serializable ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( ( Stateful ) seqJob ) ) ; Integer current = new OddjobLookup ( oj ) . lookup ( "" , Integer . class ) ; assertEquals ( new Integer ( ) , current ) ; sanityLoad ( ) ; } public void sanityLoad ( ) throws Exception { StandardArooaSession session = new StandardArooaSession ( ) ; FilePersister test = new FilePersister ( ) ; test . setDir ( persistIn ) ; test . setPath ( "" ) ; ComponentPersister persister = test . persisterFor ( null ) ; Object seqJob = persister . restore ( "" , getClass ( ) . getClassLoader ( ) , session ) ; assertEquals ( "" , JobState . COMPLETE , Helper . getJobState ( seqJob ) ) ; } public void test2Load ( ) throws Exception { test1Save ( ) ; Oddjob oj = new Oddjob ( ) ; oj . setName ( "" ) ; oj . setFile ( config ) ; oj . load ( ) ; Oddjob oj2 = ( Oddjob ) new OddjobLookup ( oj ) . lookup ( "" ) ; oj2 . load ( ) ; Object seqJob = new OddjobLookup ( oj ) . lookup ( "" ) ; assertNotNull ( seqJob ) ; assertEquals ( "" , JobState . COMPLETE , Helper . getJobState ( seqJob ) ) ; assertEquals ( "" , new Integer ( ) , ( ( DynaBean ) seqJob ) . get ( "" ) ) ; Object [ ] children = ChildHelper . getChildren ( oj ) ; assertEquals ( , children . length ) ; ( ( Resetable ) seqJob ) . hardReset ( ) ; assertEquals ( JobState . READY , Helper . getJobState ( seqJob ) ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; ( ( Runnable ) seqJob ) . run ( ) ; assertEquals ( "" , new Integer ( ) , PropertyUtils . getProperty ( seqJob , "" ) ) ; assertEquals ( "" , JobState . COMPLETE , Helper . getJobState ( seqJob ) ) ; } } package org . oddjob . persist ; import java . io . File ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OddjobSessionFactory ; import org . oddjob . OurDirs ; import org . oddjob . Stateful ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class FileSilhouettesTest extends TestCase { private static final Logger logger = Logger . getLogger ( FileSilhouettesTest . class ) ; File archiveDir ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; OurDirs dirs = new OurDirs ( ) ; archiveDir = new File ( dirs . base ( ) , "" ) ; if ( archiveDir . exists ( ) ) { FileUtils . forceDelete ( archiveDir ) ; logger . debug ( "" + archiveDir ) ; } FileUtils . forceMkdir ( archiveDir ) ; logger . debug ( "" + archiveDir ) ; } public static class SessionCapture implements ArooaSessionAware { ArooaSession arooaSession ; @ Override public void setArooaSession ( ArooaSession session ) { this . arooaSession = session ; } public ArooaSession getArooaSession ( ) { return arooaSession ; } } public void testArchiveAndRestore ( ) throws ArooaPropertyException , ArooaConversionException , ComponentPersistException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ArooaSession session = lookup . lookup ( "" , ArooaSession . class ) ; FilePersister test = new FilePersister ( ) ; test . setDir ( archiveDir ) ; ComponentPersister persister = test . persisterFor ( null ) ; Object silhouette = new SilhouetteFactory ( ) . create ( lookup . lookup ( "" ) , session ) ; persister . persist ( "" , silhouette , session ) ; oddjob . destroy ( ) ; assertTrue ( new File ( archiveDir , "" ) . exists ( ) ) ; ArooaSession session2 = new OddjobSessionFactory ( ) . createSession ( ) ; Object [ ] archives = persister . list ( ) ; assertEquals ( , archives . length ) ; assertEquals ( "" , archives [ ] ) ; Object restored = persister . restore ( "" , getClass ( ) . getClassLoader ( ) , session2 ) ; assertNotNull ( restored ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( restored ) ) ; Object [ ] children = Helper . getChildren ( ( Structural ) restored ) ; assertEquals ( , children . length ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( children [ ] ) ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( children [ ] ) ) ; } public void testWithNestedArchives ( ) throws ArooaPropertyException , ArooaConversionException , ComponentPersistException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setArgs ( new String [ ] { "" , "" , } ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ArooaSession session = lookup . lookup ( "" , ArooaSession . class ) ; FilePersister test = new FilePersister ( ) ; test . setDir ( archiveDir ) ; ComponentPersister persister = test . persisterFor ( null ) ; Object silhouette = new SilhouetteFactory ( ) . create ( lookup . lookup ( "" ) , session ) ; persister . persist ( "" , silhouette , session ) ; oddjob . destroy ( ) ; assertTrue ( new File ( archiveDir , "" ) . exists ( ) ) ; ArooaSession session2 = new OddjobSessionFactory ( ) . createSession ( ) ; Object [ ] archives = persister . list ( ) ; assertEquals ( , archives . length ) ; assertEquals ( "" , archives [ ] ) ; Object restored = persister . restore ( "" , getClass ( ) . getClassLoader ( ) , session2 ) ; assertNotNull ( restored ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( restored ) ) ; Object [ ] children = Helper . getChildren ( ( Structural ) restored ) ; assertEquals ( , children . length ) ; Stateful hello = ( Stateful ) children [ ] ; Stateful world = ( Stateful ) children [ ] ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( hello ) ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( world ) ) ; } } package org . oddjob . persist ; import java . io . File ; import java . net . URISyntaxException ; import java . net . URL ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . oddjob . Helper ; import org . oddjob . Loadable ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . Resetable ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . arooa . registry . Path ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . framework . SerializableJob ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class FilePersisterTest extends TestCase { File DIR ; @ Override protected void setUp ( ) throws Exception { OurDirs ourDirs = new OurDirs ( ) ; DIR = ourDirs . relative ( "" ) ; if ( DIR . exists ( ) ) { FileUtils . forceDelete ( DIR ) ; } FileUtils . forceMkdir ( DIR ) ; } public static class OurJob extends SerializableJob { private static final long serialVersionUID = ; private String name ; private String text ; public void setName ( String name ) { this . name = name ; } public void setText ( String text ) { this . text = text ; } @ Override protected int execute ( ) throws Throwable { return ; } } public void testPersistAndLoad ( ) throws ComponentPersistException { OurJob job = new OurJob ( ) ; job . setName ( "" ) ; job . setText ( "" ) ; job . run ( ) ; StandardArooaSession session = new StandardArooaSession ( ) ; FilePersister test = new FilePersister ( ) ; test . setDir ( DIR ) ; ComponentPersister persister = test . persisterFor ( null ) ; persister . persist ( "" , job , session ) ; File check = new File ( DIR , "" ) ; assertTrue ( check . exists ( ) ) ; job = ( OurJob ) persister . restore ( "" , getClass ( ) . getClassLoader ( ) , session ) ; assertEquals ( "" , job . name ) ; assertEquals ( "" , job . text ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( job ) ) ; ( ( Resetable ) job ) . hardReset ( ) ; assertEquals ( JobState . READY , Helper . getJobState ( job ) ) ; job . run ( ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( job ) ) ; } class OurSession extends MockArooaSession { @ Override public ComponentPool getComponentPool ( ) { return new MockComponentPool ( ) { } ; } } public void testFailsOnNoDirectory ( ) { FilePersister test = new FilePersister ( ) ; test . setDir ( new File ( DIR , "" ) ) ; try { test . persist ( ( Path ) null , ( String ) null , ( Object ) null ) ; fail ( ) ; } catch ( ComponentPersistException e ) { assertTrue ( e . getMessage ( ) . startsWith ( "" ) ) ; } } public void testCreatesFullPath ( ) throws ComponentPersistException { FilePersister test = new FilePersister ( ) ; test . setDir ( DIR ) ; test . persist ( new Path ( "" ) , "" , new OurJob ( ) ) ; File check = new File ( DIR , "" ) ; assertTrue ( check . exists ( ) ) ; } public void testNullDirectory ( ) throws ComponentPersistException { FilePersister persister = new FilePersister ( ) ; try { persister . directoryFor ( new Path ( ) ) ; fail ( "" ) ; } catch ( NullPointerException e ) { } } public void testPersistExample ( ) throws ArooaPropertyException , ArooaConversionException , URISyntaxException { URL url = getClass ( ) . getClassLoader ( ) . getResource ( "" ) ; File file = new File ( url . toURI ( ) . getPath ( ) ) ; Properties props = new Properties ( ) ; props . setProperty ( "" , "" ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setFile ( file ) ; oddjob1 . setArgs ( new String [ ] { DIR . getAbsolutePath ( ) } ) ; oddjob1 . setProperties ( props ) ; oddjob1 . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; oddjob1 . destroy ( ) ; assertTrue ( new File ( DIR , "" ) . exists ( ) ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setFile ( file ) ; oddjob2 . setArgs ( new String [ ] { DIR . getAbsolutePath ( ) } ) ; oddjob2 . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob2 ) ; Loadable loadable = lookup . lookup ( "" , Loadable . class ) ; loadable . load ( ) ; String text = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , text ) ; oddjob2 . destroy ( ) ; } } package org . oddjob . persist ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Structural ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . life . MockComponentPersister ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; public class ArchiveBrowserJobTest extends TestCase { public static class OurArchiver extends MockComponentPersister implements OddjobPersister { @ Override public ComponentPersister persisterFor ( String id ) { return this ; } @ Override public void persist ( String archiveIdentifier , Object component , ArooaSession session ) { throw new RuntimeException ( "" ) ; } @ Override public String [ ] list ( ) { return new String [ ] { "" , "" , "" } ; } @ Override public Object restore ( String archiveIdentifier , ClassLoader loader , ArooaSession session ) { FlagState flag = new FlagState ( JobState . INCOMPLETE ) ; flag . run ( ) ; return flag ; } } public void testBrowse ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ArchiveBrowserJob test = ( ArchiveBrowserJob ) lookup . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( test ) ) ; Object [ ] children = Helper . getChildren ( test ) ; assertEquals ( , children . length ) ; Runnable child1 = ( Runnable ) children [ ] ; assertEquals ( "" , child1 . toString ( ) ) ; assertTrue ( child1 instanceof Structural ) ; Object [ ] grandChildren = Helper . getChildren ( ( Structural ) child1 ) ; assertEquals ( , grandChildren . length ) ; child1 . run ( ) ; grandChildren = Helper . getChildren ( ( Structural ) child1 ) ; assertEquals ( , grandChildren . length ) ; Object flag1 = grandChildren [ ] ; assertEquals ( "" , flag1 . toString ( ) ) ; } } package org . oddjob . persist ; import java . io . Serializable ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class PersistAssumptionsTest extends TestCase { public static class Thing implements Runnable , Serializable { private static final long serialVersionUID = ; private Value stuff ; public Value getStuff ( ) { return stuff ; } public void setStuff ( Value stuff ) { this . stuff = stuff ; } @ Override public void run ( ) { } } public static class Value implements Serializable { private static final long serialVersionUID = ; private String value ; public String getValue ( ) { return value ; } public void setValue ( String value ) { this . value = value ; } } public static void testValues ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + Thing . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" ; MapPersister persister = new MapPersister ( ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setPersister ( persister ) ; oddjob1 . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob1 . setArgs ( new String [ ] { "" } ) ; oddjob1 . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , new OddjobLookup ( oddjob1 ) . lookup ( "" ) ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setPersister ( persister ) ; oddjob2 . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob2 . setArgs ( new String [ ] { "" } ) ; oddjob2 . load ( ) ; assertEquals ( ParentState . READY , oddjob2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , new OddjobLookup ( oddjob2 ) . lookup ( "" ) ) ; Object bean = new OddjobLookup ( oddjob2 ) . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) bean ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Resetable ) bean ) . hardReset ( ) ; assertEquals ( JobState . READY , ( ( Stateful ) bean ) . lastStateEvent ( ) . getState ( ) ) ; oddjob2 . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , new OddjobLookup ( oddjob2 ) . lookup ( "" ) ) ; } } package org . oddjob . persist ; import java . io . File ; import java . io . IOException ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; import java . net . URL ; import java . net . URLClassLoader ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; import org . oddjob . io . BufferType ; import org . oddjob . oddballs . BuildOddballs ; public class OddjobObjectInputStreamTest extends TestCase { @ Override protected void setUp ( ) throws Exception { new BuildOddballs ( ) . run ( ) ; } public void testNonSystemClassLoaderDeserialisation ( ) throws IOException , InstantiationException , IllegalAccessException , ClassNotFoundException { OurDirs dirs = new OurDirs ( ) ; File file = new File ( dirs . base ( ) , "" ) ; URL [ ] urls = { file . toURI ( ) . toURL ( ) } ; URLClassLoader test = new URLClassLoader ( urls ) ; Class < ? > appleClass = Class . forName ( "" , true , test ) ; Object apple = appleClass . newInstance ( ) ; BufferType buffer = new BufferType ( ) ; buffer . configured ( ) ; ObjectOutputStream oo = new ObjectOutputStream ( buffer . toOutputStream ( ) ) ; oo . writeObject ( apple ) ; OddjobObjectInputStream oi = new OddjobObjectInputStream ( buffer . toInputStream ( ) , test ) ; Object copy = oi . readObject ( ) ; assertEquals ( appleClass , copy . getClass ( ) ) ; } private static class OurHandler implements InvocationHandler , Serializable { private static final long serialVersionUID = ; String methodName ; public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { methodName = method . getName ( ) ; return null ; } } public void testNonSystemClassLoaderProxyDeserialisation ( ) throws IOException , InstantiationException , IllegalAccessException , ClassNotFoundException , SecurityException , NoSuchMethodException , IllegalArgumentException , InvocationTargetException { OurDirs dirs = new OurDirs ( ) ; File file = new File ( dirs . base ( ) , "" ) ; URL [ ] urls = { file . toURI ( ) . toURL ( ) } ; URLClassLoader test = new URLClassLoader ( urls ) ; Class < ? > appleClass = Class . forName ( "" , true , test ) ; Object proxy = Proxy . newProxyInstance ( test , new Class < ? > [ ] { appleClass } , new OurHandler ( ) ) ; BufferType buffer = new BufferType ( ) ; buffer . configured ( ) ; ObjectOutputStream oo = new ObjectOutputStream ( buffer . toOutputStream ( ) ) ; oo . writeObject ( proxy ) ; OddjobObjectInputStream oi = new OddjobObjectInputStream ( buffer . toInputStream ( ) , test ) ; Object copy = oi . readObject ( ) ; assertTrue ( appleClass . isInstance ( copy ) ) ; Method m = appleClass . getDeclaredMethod ( "" ) ; m . invoke ( copy ) ; OurHandler handler = ( OurHandler ) Proxy . getInvocationHandler ( copy ) ; assertEquals ( "" , handler . methodName ) ; } } package org . oddjob ; import java . io . File ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconListener ; import org . oddjob . state . State ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class Helper { public static final long TEST_TIMEOUT = ; public static final String LS = System . getProperty ( "" ) ; public static State getJobState ( Object o ) { class StateCatcher implements StateListener { State state ; public void jobStateChange ( StateEvent event ) { state = event . getState ( ) ; } } ; Stateful stateful = ( Stateful ) o ; StateCatcher listener = new StateCatcher ( ) ; stateful . addStateListener ( listener ) ; stateful . removeStateListener ( listener ) ; return listener . state ; } public static Object [ ] getChildren ( Object o ) { class ChildCatcher implements StructuralListener { List < Object > results = new ArrayList < Object > ( ) ; public void childAdded ( StructuralEvent event ) { synchronized ( results ) { results . add ( event . getIndex ( ) , event . getChild ( ) ) ; } } public void childRemoved ( StructuralEvent event ) { synchronized ( results ) { results . remove ( event . getIndex ( ) ) ; } } } Structural structural = ( Structural ) o ; ChildCatcher cc = new ChildCatcher ( ) ; structural . addStructuralListener ( cc ) ; structural . removeStructuralListener ( cc ) ; return cc . results . toArray ( ) ; } public static String getIconId ( Object object ) { class IconCatcher implements IconListener { String iconId ; public void iconEvent ( IconEvent e ) { iconId = e . getIconId ( ) ; } } Iconic iconic = ( Iconic ) object ; IconCatcher listener = new IconCatcher ( ) ; iconic . addIconListener ( listener ) ; iconic . removeIconListener ( listener ) ; return listener . iconId ; } public static < T > T copy ( T object ) throws IOException , ClassNotFoundException { return TestHelper . copy ( object ) ; } public static class Surrogate { Object value ; public void addConfiguredWhatever ( Object value ) { this . value = value ; } } public static Object createTypeFromXml ( String xml ) throws ArooaParseException { return createTypeFromConfiguration ( new XMLConfiguration ( "" , xml ) ) ; } public static Object createTypeFromConfiguration ( ArooaConfiguration config ) throws ArooaParseException { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . setArooaType ( ArooaType . VALUE ) ; parser . parse ( config ) ; return parser . getRoot ( ) ; } public static Object createComponentFromXml ( String xml ) throws IOException , ArooaParseException { return createComponentFromConfiguration ( new XMLConfiguration ( "" , xml ) ) ; } public static Object createComponentFromConfiguration ( ArooaConfiguration config ) throws ArooaParseException { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; StandardFragmentParser parser = new StandardFragmentParser ( descriptor ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( config ) ; return parser . getRoot ( ) ; } public static void register ( Object component , final ArooaSession session , String id ) { class OurContext extends MockArooaContext { @ Override public ArooaSession getSession ( ) { return session ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void configure ( ) { } } ; } } session . getComponentPool ( ) . registerComponent ( new ComponentTrinity ( component , component , new OurContext ( ) ) , id ) ; } public static File getWorkDir ( ) { File file = new File ( "" ) ; if ( ! file . exists ( ) ) { file . mkdir ( ) ; } return file ; } } package org . oddjob . swing ; public class ConfirmationJobMain { public static void main ( String ... args ) { ConfirmationJob test = new ConfirmationJob ( ) ; test . setTitle ( "" ) ; test . setMessage ( "" ) ; test . run ( ) ; System . out . println ( test . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . swing ; import org . oddjob . Oddjob ; import org . oddjob . StateSteps ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . jobs . WaitJob ; import org . oddjob . scheduling . DefaultExecutors ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; public class OddjobPanelMain { public static void main2 ( String ... args ) throws InterruptedException { DefaultExecutors defaultServices = new DefaultExecutors ( ) ; WaitJob job1 = new WaitJob ( ) ; job1 . setName ( "" ) ; FlagState job2 = new FlagState ( JobState . COMPLETE ) ; job2 . setName ( "" ) ; FlagState job3 = new FlagState ( JobState . COMPLETE ) ; job3 . setName ( "" ) ; FlagState job4 = new FlagState ( JobState . COMPLETE ) ; job4 . setName ( "" ) ; FlagState job5 = new FlagState ( JobState . COMPLETE ) ; job5 . setName ( "" ) ; OddjobPanel test = new OddjobPanel ( ) ; test . setJobs ( , job1 ) ; test . setJobs ( , job2 ) ; test . setJobs ( , job3 ) ; test . setJobs ( , job4 ) ; test . setJobs ( , job5 ) ; test . setExecutorService ( defaultServices . getPoolExecutor ( ) ) ; StateSteps states = new StateSteps ( test ) ; states . setTimeout ( ) ; states . startCheck ( ServiceState . READY , ServiceState . STARTING , ServiceState . STARTED , ServiceState . COMPLETE ) ; test . run ( ) ; states . checkWait ( ) ; defaultServices . stop ( ) ; } public static void main ( String ... args ) throws InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , OddjobPanelMain . class . getClassLoader ( ) ) ) ; StateSteps states = new StateSteps ( oddjob ) ; states . setTimeout ( ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; states . checkWait ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . swing ; import java . io . File ; import java . util . Properties ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . input . InputHandler ; import org . oddjob . input . InputJob ; import org . oddjob . input . requests . InputConfirm ; import org . oddjob . input . requests . InputFile ; import org . oddjob . input . requests . InputMessage ; import org . oddjob . input . requests . InputPassword ; import org . oddjob . input . requests . InputText ; public class SwingInputHandlerMain { public static InputJob one ( InputHandler handler ) { InputJob input = new InputJob ( ) ; input . setArooaSession ( new StandardArooaSession ( ) ) ; input . setInputHandler ( handler ) ; InputConfirm request1 = new InputConfirm ( ) ; request1 . setPrompt ( "" ) ; request1 . setProperty ( "" ) ; InputText request2 = new InputText ( ) ; request2 . setPrompt ( "" ) ; request2 . setDefault ( "" ) ; request2 . setProperty ( "" ) ; InputPassword request3 = new InputPassword ( ) ; request3 . setPrompt ( "" ) ; request3 . setProperty ( "" ) ; InputFile request4 = new InputFile ( ) ; request4 . setPrompt ( "" ) ; request4 . setProperty ( "" ) ; InputMessage request5 = new InputMessage ( ) ; request5 . setMessage ( "" + "" ) ; input . setRequests ( , request1 ) ; input . setRequests ( , request2 ) ; input . setRequests ( , request3 ) ; input . setRequests ( , request4 ) ; input . setRequests ( , request5 ) ; return input ; } public static InputJob two ( InputHandler handler ) { InputJob input = new InputJob ( ) ; input . setName ( "" ) ; input . setArooaSession ( new StandardArooaSession ( ) ) ; input . setInputHandler ( handler ) ; InputFile request1 = new InputFile ( ) ; request1 . setPrompt ( "" ) ; request1 . setCurrentDirectory ( new File ( "" ) ) ; request1 . setDefault ( "" ) ; request1 . setFileFilterExtensions ( new String [ ] { "" , "" } ) ; request1 . setProperty ( "" ) ; input . setRequests ( , request1 ) ; return input ; } public static void main ( String ... args ) { SwingInputHandler handler = new SwingInputHandler ( null ) ; InputJob [ ] inputs = new InputJob [ ] { two ( handler ) , } ; for ( InputJob input : inputs ) { System . out . println ( "" + input . getName ( ) + "" ) ; input . run ( ) ; Properties props = input . getProperties ( ) ; if ( props != null ) { for ( Object key : props . keySet ( ) ) { System . out . println ( key + "" + props . get ( key ) ) ; } } } } } package org . oddjob . swing ; import java . util . Date ; import org . oddjob . Oddjob ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . persist . MapPersister ; public class ConfigureBeanMain { public static class MyBean { private String name ; private Date dateOfBirth ; private double height ; public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public Date getDateOfBirth ( ) { return dateOfBirth ; } public void setDateOfBirth ( Date dateOfBirth ) { this . dateOfBirth = dateOfBirth ; } public double getHeight ( ) { return height ; } public void setHeight ( double height ) { this . height = height ; } } public void simpleBeanOnly ( ) { ConfigureBeanJob job = new ConfigureBeanJob ( ) ; MyBean bean = new MyBean ( ) ; job . setBean ( bean ) ; job . setArooaSession ( new StandardArooaSession ( new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ) ) ; job . run ( ) ; System . out . println ( bean . getName ( ) ) ; System . out . println ( bean . getDateOfBirth ( ) ) ; System . out . println ( bean . getHeight ( ) ) ; } public void simpleInOddjob ( ) throws ArooaPropertyException , ArooaConversionException { String inner = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; String outer = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + inner + "" + "" + "" + "" + "" + "" + "" ; MapPersister persister = new MapPersister ( ) ; persister . setPath ( "" ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , outer ) ) ; oddjob . setPersister ( persister ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; System . out . println ( lookup . lookup ( "" ) ) ; System . out . println ( lookup . lookup ( "" ) ) ; System . out . println ( lookup . lookup ( "" ) ) ; oddjob . destroy ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setConfiguration ( new XMLConfiguration ( "" , outer ) ) ; oddjob2 . setPersister ( persister ) ; oddjob2 . setName ( "" ) ; oddjob2 . load ( ) ; OddjobLookup lookup2 = new OddjobLookup ( oddjob2 ) ; Oddjob innerOddjob = lookup2 . lookup ( "" , Oddjob . class ) ; innerOddjob . load ( ) ; Object resetable = lookup2 . lookup ( "" ) ; ( ( Resetable ) resetable ) . hardReset ( ) ; ( ( Runnable ) resetable ) . run ( ) ; System . out . println ( lookup2 . lookup ( "" ) ) ; System . out . println ( lookup2 . lookup ( "" ) ) ; System . out . println ( lookup2 . lookup ( "" ) ) ; } public static void main ( String ... args ) throws ArooaParseException , ArooaPropertyException , ArooaConversionException { new ConfigureBeanMain ( ) . simpleInOddjob ( ) ; } } package org . oddjob ; import java . util . Properties ; import org . oddjob . arooa . ArooaConfiguration ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . standard . StandardFragmentParser ; import org . oddjob . arooa . xml . XMLConfiguration ; public class FragmentHelper { private Properties properties ; private ArooaSession session ; public ArooaSession getSession ( ) { return session ; } public Object createComponentFromResource ( String resource ) throws ArooaParseException { return createFromResource ( ArooaType . COMPONENT , resource ) ; } public Object createValueFromResource ( String resource ) throws ArooaParseException { return createFromResource ( ArooaType . VALUE , resource ) ; } private Object createFromResource ( ArooaType type , String resource ) throws ArooaParseException { OddjobSessionFactory sessionFactory = new OddjobSessionFactory ( ) ; sessionFactory . setProperties ( properties ) ; session = sessionFactory . createSession ( ) ; StandardFragmentParser parser = new StandardFragmentParser ( session ) ; parser . setArooaType ( type ) ; ArooaConfiguration config = new XMLConfiguration ( resource , getClass ( ) . getClassLoader ( ) ) ; parser . parse ( config ) ; return parser . getRoot ( ) ; } public Properties getProperties ( ) { return properties ; } public void setProperties ( Properties properties ) { this . properties = properties ; } } package org . oddjob ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . PrintStream ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . oddballs . OddballsDirDescriptorFactory ; import org . oddjob . state . ParentState ; public class MainTest extends TestCase { private static final Logger logger = Logger . getLogger ( MainTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . debug ( "" + getName ( ) + "" ) ; logger . debug ( System . getProperty ( "" ) ) ; } public void testInit ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; Main m = new Main ( ) ; Oddjob oj = m . init ( new String [ ] { "" , dirs . base ( ) + "" , "" } ) . getOddjob ( ) ; assertEquals ( , oj . getArgs ( ) . length ) ; assertEquals ( "" , oj . getArgs ( ) [ ] ) ; } public void testBadArg ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; Main m = new Main ( ) ; Oddjob oj = m . init ( new String [ ] { "" , dirs . base ( ) + "" , "" , "" , "" } ) . getOddjob ( ) ; assertEquals ( , oj . getArgs ( ) . length ) ; assertEquals ( "" , oj . getArgs ( ) [ ] ) ; assertEquals ( "" , oj . getArgs ( ) [ ] ) ; assertEquals ( "" , oj . getArgs ( ) [ ] ) ; } public void testPassArgs ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; Main m = new Main ( ) ; Oddjob oj = m . init ( new String [ ] { "" , dirs . base ( ) + "" , "" , "" , "" } ) . getOddjob ( ) ; assertEquals ( , oj . getArgs ( ) . length ) ; assertEquals ( "" , oj . getArgs ( ) [ ] ) ; assertEquals ( "" , oj . getArgs ( ) [ ] ) ; } public void testOddjobName ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; Main m = new Main ( ) ; Oddjob oj = m . init ( new String [ ] { "" , "" , "" , dirs . base ( ) + "" } ) . getOddjob ( ) ; assertEquals ( "" , oj . toString ( ) ) ; } public void testUsage ( ) throws IOException { Main . main ( new String [ ] { "" } ) ; } public void testVersion ( ) throws IOException { Main . main ( new String [ ] { "" } ) ; } public void testInitNoBalls ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; Main test = new Main ( ) ; Oddjob oddjob = test . init ( new String [ ] { "" , "" , "" , "" , dirs . base ( ) + "" } ) . getOddjob ( ) ; assertNull ( oddjob . getDescriptorFactory ( ) ) ; } public void testDefaultBalls ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; Main test = new Main ( ) ; System . setProperty ( "" , dirs . base ( ) . getCanonicalPath ( ) ) ; Oddjob oddjob = test . init ( new String [ ] { } ) . getOddjob ( ) ; OddballsDirDescriptorFactory result = ( OddballsDirDescriptorFactory ) oddjob . getDescriptorFactory ( ) ; assertEquals ( new File ( dirs . base ( ) , "" ) . getCanonicalPath ( ) , result . getBaseDir ( ) . getCanonicalPath ( ) ) ; } public void testWithBalls ( ) throws IOException { OurDirs dirs = new OurDirs ( ) ; Main test = new Main ( ) ; Oddjob oddjob = test . init ( new String [ ] { "" , "" , "" , "" , dirs . base ( ) + "" } ) . getOddjob ( ) ; OddballsDirDescriptorFactory result = ( OddballsDirDescriptorFactory ) oddjob . getDescriptorFactory ( ) ; assertEquals ( new File ( "" ) , result . getBaseDir ( ) ) ; } public void testBadFile ( ) { Main test = new Main ( ) ; try { test . init ( new String [ ] { "" , "" } ) ; fail ( "" ) ; } catch ( IOException e ) { } } public void testUserProperties ( ) throws IOException { File userProperties = new File ( System . getProperty ( "" ) , Main . USER_PROPERTIES ) ; File renamedFile = new File ( userProperties . getPath ( ) + "" ) ; if ( ! renamedFile . exists ( ) && userProperties . exists ( ) ) { assertTrue ( userProperties . renameTo ( renamedFile ) ) ; } PrintStream out = new PrintStream ( new FileOutputStream ( userProperties ) ) ; out . println ( "" ) ; out . println ( "" ) ; out . println ( "" ) ; out . close ( ) ; Main test = new Main ( ) ; Properties props = test . processUserProperties ( ) ; assertEquals ( "" , props . getProperty ( "" ) ) ; assertEquals ( "" , props . getProperty ( "" ) ) ; assertEquals ( "" , props . getProperty ( "" ) ) ; assertTrue ( userProperties . delete ( ) ) ; if ( renamedFile . exists ( ) ) { assertTrue ( renamedFile . renameTo ( userProperties ) ) ; } } public void testOddjobDestroyOnComplete ( ) throws IOException { File f = new OurDirs ( ) . relative ( "" ) ; Main test = new Main ( ) ; Oddjob oddjob = test . init ( new String [ ] { "" , f . toString ( ) } ) . getOddjob ( ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; } public void testOddjobDestroyOnComleteWithServices ( ) throws IOException , InterruptedException { File f = new OurDirs ( ) . relative ( "" ) ; Main test = new Main ( ) ; Oddjob oddjob = test . init ( new String [ ] { "" , f . toString ( ) } ) . getOddjob ( ) ; StateSteps state = new StateSteps ( oddjob ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oddjob . run ( ) ; state . checkWait ( ) ; } } package org . oddjob ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class MockStateful implements Stateful { public void addStateListener ( StateListener listener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeStateListener ( StateListener listener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public StateEvent lastStateEvent ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . script ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . persist . MapPersister ; import org . oddjob . persist . OddjobPersister ; import org . oddjob . state . ParentState ; public class InvokeJobTest extends TestCase { public void testMethodExample ( ) throws ArooaPropertyException , ArooaConversionException { OddjobPersister persister = new MapPersister ( ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob1 . setPersister ( persister ) ; oddjob1 . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup1 = new OddjobLookup ( oddjob1 ) ; String result1 = lookup1 . lookup ( "" , String . class ) ; assertEquals ( "" , result1 ) ; oddjob1 . destroy ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob2 . setPersister ( persister ) ; oddjob2 . load ( ) ; assertEquals ( ParentState . READY , oddjob2 . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup2 = new OddjobLookup ( oddjob2 ) ; String result2 = lookup2 . lookup ( "" , String . class ) ; assertEquals ( "" , result2 ) ; oddjob2 . destroy ( ) ; } } package org . oddjob . script ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ScriptAndInvokeTest extends TestCase { public void testVariableFromJava ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; String snack = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , snack ) ; } } package org . oddjob . script ; import java . io . StringReader ; import javax . script . Invocable ; import javax . script . ScriptException ; import junit . framework . TestCase ; public class ScriptCompilerTest extends TestCase { public void testCompile ( ) throws ScriptException { ScriptCompiler test = new ScriptCompiler ( ) ; test . setLanguage ( "" ) ; Evaluatable evaluatable = test . compileScript ( new StringReader ( "" ) ) ; assertEquals ( PreCompiled . class , evaluatable . getClass ( ) ) ; evaluatable . eval ( ) ; assertEquals ( "" , evaluatable . get ( "" ) ) ; } public void testNoVarAtComile ( ) throws ScriptException { ScriptCompiler test = new ScriptCompiler ( ) ; test . setLanguage ( "" ) ; Evaluatable evaluatable = test . compileScript ( new StringReader ( "" ) ) ; assertEquals ( PreCompiled . class , evaluatable . getClass ( ) ) ; evaluatable . put ( "" , "" ) ; evaluatable . eval ( ) ; assertEquals ( "" , evaluatable . get ( "" ) ) ; } public void testInvocable ( ) throws ScriptException , NoSuchMethodException { ScriptCompiler test = new ScriptCompiler ( ) ; test . setLanguage ( "" ) ; Evaluatable evaluatable = test . compileScript ( new StringReader ( "" ) ) ; assertNotNull ( test . getInvocable ( ) ) ; Invocable invocable = test . getInvocable ( ) ; try { invocable . invokeFunction ( "" ) ; fail ( "" ) ; } catch ( NoSuchMethodException e ) { } evaluatable . eval ( ) ; Object result = invocable . invokeFunction ( "" ) ; assertEquals ( "" , result ) ; } } package org . oddjob . script ; import java . io . File ; import java . text . ParseException ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . DefaultConversionRegistry ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class InvokeTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( InvokeTypeTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public static class Thing { public String simpleStuff ( ) { return "" ; } public Object complexStuff ( String s ) { return s ; } public Object complexStuff ( File f , File y ) { return f . toString ( ) + y . toString ( ) ; } public Object complexStuff ( int i , double d ) { return new Double ( d + i ) ; } public void nothing ( ) { } public static String staticThing ( String s ) { return s ; } } public void testSimple ( ) throws ArooaConversionException { InvokeType test = new InvokeType ( ) ; test . setFunction ( "" ) ; test . setSource ( new MethodInvoker ( new Thing ( ) ) ) ; Object result = test . toValue ( ) ; assertEquals ( "" , result ) ; } public void testStaticMethodOnObject ( ) throws ArooaConversionException { InvokeType test = new InvokeType ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setFunction ( "" ) ; test . setSource ( new MethodInvoker ( new Thing ( ) ) ) ; test . setParameters ( , new ArooaObject ( "" ) ) ; assertEquals ( "" , test . toValue ( ) ) ; } public void testClassMethodInvoke ( ) throws ArooaConversionException { InvokeType test = new InvokeType ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setFunction ( "" ) ; test . setSource ( new MethodInvoker ( Thing . class ) ) ; assertEquals ( Thing . class , test . toValue ( ) . getClass ( ) ) ; } public void testWrongParameters ( ) throws ArooaConversionException { InvokeType test = new InvokeType ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setFunction ( "" ) ; test . setSource ( new MethodInvoker ( new Thing ( ) ) ) ; test . setParameters ( , new ArooaObject ( "" ) ) ; try { test . toValue ( ) ; fail ( "" ) ; } catch ( RuntimeException e ) { } } public void testNumberToString ( ) throws ArooaConversionException { InvokeType test = new InvokeType ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setFunction ( "" ) ; test . setSource ( new MethodInvoker ( new Thing ( ) ) ) ; test . setParameters ( , new ArooaObject ( ) ) ; Object result = test . toValue ( ) ; assertEquals ( "" , result ) ; } public void testNumbers ( ) throws ArooaConversionException { InvokeType test = new InvokeType ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setFunction ( "" ) ; test . setSource ( new MethodInvoker ( new Thing ( ) ) ) ; test . setParameters ( , new ArooaObject ( ) ) ; test . setParameters ( , new ArooaObject ( ) ) ; Object result = test . toValue ( ) ; assertEquals ( new Double ( ) , result ) ; } public void testFiles ( ) throws ArooaConversionException { InvokeType test = new InvokeType ( ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; test . setFunction ( "" ) ; test . setSource ( new MethodInvoker ( new Thing ( ) ) ) ; test . setParameters ( , new ArooaObject ( "" ) ) ; test . setParameters ( , new ArooaObject ( "" ) ) ; Object result = test . toValue ( ) ; assertEquals ( "" , result ) ; } public void testConversion ( ) throws ArooaConversionException { InvokeType test = new InvokeType ( ) ; test . setFunction ( "" ) ; test . setSource ( new MethodInvoker ( new Thing ( ) ) ) ; DefaultConversionRegistry conversions = new DefaultConversionRegistry ( ) ; new InvokeType . Conversions ( ) . registerWith ( conversions ) ; ArooaConverter converter = new DefaultConverter ( conversions ) ; String result = converter . convert ( test , String . class ) ; assertEquals ( "" , result ) ; } public void testMethodExample ( ) throws ArooaPropertyException , ArooaConversionException , ParseException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setExport ( "" , new ArooaObject ( DateHelper . parseDateTime ( "" ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; String result = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , result ) ; oddjob . destroy ( ) ; } public void testStaticExample ( ) throws ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( "" , new OddjobLookup ( oddjob ) . lookup ( "" , String . class ) ) ; } } package org . oddjob . script ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . utils . DateHelper ; public class MethodInvokerTest extends TestCase { public static String echo ( String value ) { return value ; } public class Simple { Date delivery ; int quantity ; public double quote ( Date delivery , int quantity ) { this . delivery = delivery ; this . quantity = quantity ; return ; } } public void testInvoking ( ) throws Exception { Simple simple = new Simple ( ) ; MethodInvoker test = new MethodInvoker ( simple ) ; InvokerArguments args = new ConvertableArguments ( new DefaultConverter ( ) , "" , ) ; double result = ( Double ) test . invoke ( "" , args ) ; assertEquals ( , result , ) ; assertEquals ( DateHelper . parseDate ( "" ) , simple . delivery ) ; assertEquals ( , simple . quantity ) ; } public void testStatic ( ) throws Exception { MethodInvoker test = new MethodInvoker ( MethodInvokerTest . class ) ; InvokerArguments args = new ConvertableArguments ( new DefaultConverter ( ) , "" ) ; String result = ( String ) test . invoke ( "" , args ) ; assertEquals ( "" , result ) ; } } package org . oddjob . script ; import java . io . StringReader ; import javax . script . ScriptException ; import junit . framework . TestCase ; public class ScriptRunnerTest extends TestCase { public void testSimpleEval ( ) throws ScriptException , NoSuchMethodException { ScriptCompiler compiler = new ScriptCompiler ( ) ; compiler . setLanguage ( "" ) ; Evaluatable evaluatable = compiler . compileScript ( new StringReader ( "" ) ) ; ScriptRunner test = new ScriptRunner ( "" ) ; Object result = test . executeScript ( evaluatable ) ; assertEquals ( "" , result ) ; assertEquals ( "" , evaluatable . get ( "" ) ) ; } } package org . oddjob . script ; public class EchoService { public String echo ( String text ) { return text ; } } package org . oddjob . script ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class ScriptDCTest extends TestCase { private static final Logger logger = Logger . getLogger ( ScriptDCTest . class ) ; DesignInstance design ; public void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; assertEquals ( ScriptDesign . class , design . getClass ( ) ) ; ScriptJob test = ( ScriptJob ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getLanguage ( ) ) ; assertEquals ( "" , test . getBeans ( "" ) ) ; assertEquals ( "" , test . getResultVariable ( ) ) ; assertEquals ( true , test . isResultForState ( ) ) ; } public static void main ( String args [ ] ) throws ArooaParseException { ScriptDCTest test = new ScriptDCTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . script ; import java . util . Properties ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ScriptExamplesTest extends TestCase { public void testInvokeScriptFunction ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Properties props = new OddjobLookup ( oddjob ) . lookup ( "" , Properties . class ) ; assertEquals ( "" , props . getProperty ( "" ) ) ; } } package org . oddjob . script ; import java . io . IOException ; import junit . framework . TestCase ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . io . BufferType ; import org . oddjob . state . JobState ; public class ScriptInvokerTest extends TestCase { public void testInvokeScript ( ) throws IOException { BufferType buffer = new BufferType ( ) ; buffer . setText ( "" + "" ) ; buffer . configured ( ) ; ScriptJob scriptJob = new ScriptJob ( ) ; scriptJob . setLanguage ( "" ) ; scriptJob . setInput ( buffer . toInputStream ( ) ) ; scriptJob . run ( ) ; assertEquals ( JobState . COMPLETE , scriptJob . lastStateEvent ( ) . getState ( ) ) ; ScriptInvoker test = new ScriptInvoker ( scriptJob . getInvocable ( ) ) ; ConvertableArguments arguments = new ConvertableArguments ( new DefaultConverter ( ) , "" ) ; String result = ( String ) test . invoke ( "" , arguments ) ; assertEquals ( "" , result ) ; } } package org . oddjob . script ; import java . sql . Date ; import java . util . Calendar ; public class GreetingService { public String greeting ( Date date ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; int hour = cal . get ( Calendar . HOUR_OF_DAY ) ; if ( hour < ) { return "" ; } if ( hour < ) { return "" ; } return "" ; } public static String greetPerson ( String name ) { return "" + name ; } } package org . oddjob . script ; import java . util . Date ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; import org . oddjob . values . VariablesJob ; public class ScriptJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( ScriptJobTest . class ) ; public void testHelloWorld ( ) { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( oj ) ) ; } public void testVariableFromAndToJava ( ) throws ArooaPropertyException , ArooaConversionException { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( oj ) ) ; String snack = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , snack ) ; } public void testSettingOutput ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; ScriptJob sc = ( ScriptJob ) new OddjobLookup ( oj ) . lookup ( "" ) ; Map < ? , ? > results = ( Map < ? , ? > ) sc . getBeans ( "" ) ; assertEquals ( "" , results . get ( "" ) ) ; } public void testResult ( ) { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . INCOMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; } public void testSettingVariables ( ) throws Exception { Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; VariablesJob v = ( VariablesJob ) new OddjobLookup ( oj ) . lookup ( "" ) ; Object result = new DefaultConverter ( ) . convert ( v . get ( "" ) , Object . class ) ; assertNotNull ( result ) ; assertEquals ( Date . class , result . getClass ( ) ) ; Object formatted = v . get ( "" ) ; assertNotNull ( formatted ) ; logger . info ( formatted ) ; } } package org . oddjob ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . arooa . ArooaException ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ComponentTrinity ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . types . XMLConfigurationType ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . input . InputHandler ; import org . oddjob . input . InputRequest ; import org . oddjob . jobs . EchoJob ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class OddjobTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddjobTest . class ) ; public void testReset ( ) { class MyStructuralListener implements StructuralListener { int count ; public void childAdded ( StructuralEvent event ) { count ++ ; } public void childRemoved ( StructuralEvent event ) { count -- ; } } String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; StateSteps ojSteps = new StateSteps ( oj ) ; ojSteps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; MyStructuralListener childListener = new MyStructuralListener ( ) ; oj . addStructuralListener ( childListener ) ; assertEquals ( , childListener . count ) ; oj . run ( ) ; assertEquals ( , childListener . count ) ; ojSteps . checkNow ( ) ; Stateful flag = ( Stateful ) new OddjobLookup ( oj ) . lookup ( "" ) ; StateSteps flagSteps = new StateSteps ( flag ) ; flagSteps . startCheck ( JobState . COMPLETE ) ; flagSteps . checkNow ( ) ; flagSteps . startCheck ( JobState . COMPLETE , JobState . READY , JobState . DESTROYED ) ; ojSteps . startCheck ( ParentState . COMPLETE , ParentState . READY ) ; oj . hardReset ( ) ; flagSteps . checkNow ( ) ; ojSteps . checkNow ( ) ; ojSteps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oj . run ( ) ; ojSteps . checkNow ( ) ; ojSteps . startCheck ( ParentState . COMPLETE , ParentState . READY ) ; oj . hardReset ( ) ; ojSteps . checkNow ( ) ; ojSteps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; oj . run ( ) ; ojSteps . checkNow ( ) ; ojSteps . startCheck ( ParentState . COMPLETE , ParentState . DESTROYED ) ; oj . destroy ( ) ; } public void testSoftReset ( ) { class MyL implements StructuralListener { int count ; public void childAdded ( StructuralEvent event ) { count ++ ; } public void childRemoved ( StructuralEvent event ) { count -- ; } } String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; MyL l = new MyL ( ) ; oj . addStructuralListener ( l ) ; assertEquals ( , l . count ) ; oj . run ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . INCOMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; oj . softReset ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . run ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . INCOMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; oj . softReset ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . run ( ) ; assertEquals ( , l . count ) ; assertEquals ( ParentState . INCOMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testSoftResetOnFailure ( ) { String xml = "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . EXCEPTION , oj . lastStateEvent ( ) . getState ( ) ) ; String xml2 = "" + "" + "" + "" + "" ; oj . setConfiguration ( new XMLConfiguration ( "" , xml2 ) ) ; oj . softReset ( ) ; assertEquals ( ParentState . READY , oj . lastStateEvent ( ) . getState ( ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; oj . destroy ( ) ; } public void testLoadNoChild ( ) throws ArooaParseException { String config = "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; test . run ( ) ; Object root = new OddjobLookup ( test ) . lookup ( "" ) ; assertEquals ( Oddjob . OddjobRoot . class , root . getClass ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; test . run ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . destroy ( ) ; } public void testLoadOddjobClassloader ( ) { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . load ( ) ; String nestedConf = "" ; Oddjob test = ( Oddjob ) new OddjobLookup ( oj ) . lookup ( "" ) ; oj . setConfiguration ( new XMLConfiguration ( "" , nestedConf ) ) ; test . run ( ) ; assertNotNull ( "" , test . getClassLoader ( ) ) ; oj . destroy ( ) ; } public void testLookup ( ) throws Exception { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" ; String nested = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; XMLConfigurationType configType = new XMLConfigurationType ( ) ; configType . setXml ( nested ) ; oj . setExport ( "" , configType ) ; oj . run ( ) ; String fruit = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , fruit ) ; oj . destroy ( ) ; } public void testArgs ( ) throws Exception { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( test ) ; String fruit = lookup . lookup ( "" , String . class ) ; assertEquals ( null , fruit ) ; test . hardReset ( ) ; test . setArgs ( new String [ ] { "" } ) ; test . run ( ) ; fruit = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , fruit ) ; test . destroy ( ) ; } private class OurInputHandler implements InputHandler { @ Override public Properties handleInput ( InputRequest [ ] requests ) { Properties properties = new Properties ( ) ; properties . setProperty ( "" , "" ) ; return properties ; } } public void testOptionalArgumentExample ( ) { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setInputHandler ( new OurInputHandler ( ) ) ; ConsoleCapture console = new ConsoleCapture ( ) ; console . capture ( Oddjob . CONSOLE ) ; oddjob . run ( ) ; oddjob . hardReset ( ) ; oddjob . setArgs ( new String [ ] { "" } ) ; oddjob . run ( ) ; console . close ( ) ; console . dump ( logger ) ; String [ ] lines = console . getLines ( ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( "" , lines [ ] . trim ( ) ) ; assertEquals ( , lines . length ) ; oddjob . destroy ( ) ; } public void testInheritedProperties ( ) throws Exception { String config = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , config ) ) ; oj . run ( ) ; String fruit = new OddjobLookup ( oj ) . lookup ( "" , String . class ) ; assertEquals ( "" , fruit ) ; oj . destroy ( ) ; } public void testDir ( ) { OurDirs dirs = new OurDirs ( ) ; File testFile = dirs . relative ( "" ) ; Oddjob oj = new Oddjob ( ) ; oj . setFile ( testFile ) ; assertEquals ( dirs . relative ( "" ) , oj . getDir ( ) ) ; oj . destroy ( ) ; } public void testRegistryManagement ( ) throws ArooaParseException { final ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; class OurContext extends MockArooaContext { @ Override public ArooaSession getSession ( ) { return session ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void configure ( ) throws ArooaException { } } ; } } Oddjob oj = new Oddjob ( ) ; oj . setArooaSession ( session ) ; ComponentPool pool = session . getComponentPool ( ) ; pool . registerComponent ( new ComponentTrinity ( oj , oj , new OurContext ( ) ) , "" ) ; String xml = "" + "" + "" + "" + "" ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; BeanDirectory dir = session . getBeanRegistry ( ) ; assertEquals ( null , dir . lookup ( "" ) ) ; oj . run ( ) ; assertNotNull ( dir . lookup ( "" ) ) ; oj . hardReset ( ) ; assertEquals ( null , dir . lookup ( "" ) ) ; oj . run ( ) ; assertNotNull ( dir . lookup ( "" ) ) ; oj . destroy ( ) ; } public static class ReluctantToDie extends SimpleJob { boolean die ; @ Override protected int execute ( ) throws Throwable { return ; } @ Override public void onDestroy ( ) { super . onDestroy ( ) ; if ( ! die ) { die = true ; throw new IllegalStateException ( "" ) ; } } } public void testFailedDestroy ( ) { String xml = "" + "" + "" + ReluctantToDie . class . getName ( ) + "" + "" + "" ; Oddjob test = new Oddjob ( ) ; test . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; test . run ( ) ; try { test . destroy ( ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . destroy ( ) ; assertEquals ( ParentState . DESTROYED , test . lastStateEvent ( ) . getState ( ) ) ; } public void testCreateFile ( ) throws FileNotFoundException { OurDirs dirs = new OurDirs ( ) ; File testFile = dirs . relative ( "" ) ; EchoJob echo = new EchoJob ( ) ; echo . setOutput ( new FileOutputStream ( testFile ) ) ; echo . setText ( "" ) ; echo . run ( ) ; String xml = "" + "" + "" + testFile . getAbsolutePath ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; testFile . delete ( ) ; oddjob . hardReset ( ) ; oddjob . run ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertTrue ( testFile . exists ( ) ) ; } } package org . oddjob ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . ElementMappings ; import org . oddjob . arooa . MockArooaDescriptor ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionFailedException ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . convert . DefaultConversionProvider ; import org . oddjob . arooa . convert . NoConversionAvailableException ; import org . oddjob . arooa . deploy . ArooaDescriptorFactory ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . life . ComponentProxyResolver ; import org . oddjob . arooa . life . MockComponentPersister ; import org . oddjob . arooa . registry . BeanRegistry ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . InvalidIdException ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import org . oddjob . arooa . registry . SimpleComponentPool ; import org . oddjob . arooa . standard . MockPropertyLookup ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . standard . StandardTools ; import org . oddjob . persist . OddjobPersister ; public class OddjobArooaSessionTest extends TestCase { private class OurDescriptor extends MockArooaDescriptor { @ Override public ConversionProvider getConvertletProvider ( ) { return new ConversionProvider ( ) { public void registerWith ( ConversionRegistry registry ) { registry . register ( String . class , Integer . class , new Convertlet < String , Integer > ( ) { public Integer convert ( String from ) throws ConvertletException { return new Integer ( ) ; } } ) ; } } ; } @ Override public ElementMappings getElementMappings ( ) { return null ; } } public void testConversions ( ) throws ArooaParseException , ArooaConversionException , InvalidIdException { OddjobSessionFactory sessionFactory = new OddjobSessionFactory ( ) ; sessionFactory . setDescriptorFactory ( new ArooaDescriptorFactory ( ) { @ Override public ArooaDescriptor createDescriptor ( ClassLoader classLoader ) { return new OurDescriptor ( ) ; } } ) ; ArooaSession test = sessionFactory . createSession ( ) ; ArooaConverter converter = test . getTools ( ) . getArooaConverter ( ) ; assertEquals ( new Integer ( ) , converter . convert ( "" , Integer . class ) ) ; test . getBeanRegistry ( ) . register ( "" , "" ) ; Integer i = test . getBeanRegistry ( ) . lookup ( "" , Integer . class ) ; assertEquals ( new Integer ( ) , i ) ; } private class OuterSession extends MockArooaSession { ComponentPool componentPool = new SimpleComponentPool ( ) ; BeanRegistry beanRegistry = new SimpleBeanRegistry ( ) ; @ Override public ArooaDescriptor getArooaDescriptor ( ) { return new MockArooaDescriptor ( ) { @ Override public ConversionProvider getConvertletProvider ( ) { return new DefaultConversionProvider ( ) ; } @ Override public ElementMappings getElementMappings ( ) { return null ; } } ; } @ Override public ComponentProxyResolver getComponentProxyResolver ( ) { return null ; } @ Override public ComponentPersister getComponentPersister ( ) { return null ; } @ Override public ArooaTools getTools ( ) { return new StandardTools ( ) ; } @ Override public ComponentPool getComponentPool ( ) { return componentPool ; } @ Override public BeanRegistry getBeanRegistry ( ) { return beanRegistry ; } } public void testNestedConversion ( ) throws ArooaParseException , NoConversionAvailableException , ConversionFailedException { OuterSession session = new OuterSession ( ) ; Oddjob oddjob = new Oddjob ( ) ; Helper . register ( oddjob , session , null ) ; OddjobSessionFactory sessionFactory = new OddjobSessionFactory ( ) ; sessionFactory . setInherit ( OddjobInheritance . NONE ) ; sessionFactory . setExistingSession ( session ) ; sessionFactory . setDescriptorFactory ( new ArooaDescriptorFactory ( ) { @ Override public ArooaDescriptor createDescriptor ( ClassLoader classLoader ) { return new OurDescriptor ( ) ; } } ) ; ArooaSession test = sessionFactory . createSession ( oddjob ) ; ArooaConverter converter = test . getTools ( ) . getArooaConverter ( ) ; Number number = converter . convert ( "" , Integer . class ) ; assertEquals ( new Integer ( ) , number ) ; } public void testNestedPropertyManager ( ) { StandardArooaSession outerSession = new StandardArooaSession ( ) ; OddjobSessionFactory test = new OddjobSessionFactory ( ) ; test . setExistingSession ( outerSession ) ; test . setInherit ( null ) ; ArooaSession session = test . createSession ( ) ; outerSession . getPropertyManager ( ) . addPropertyLookup ( new MockPropertyLookup ( ) { @ Override public String lookup ( String propertyName ) { assertEquals ( "" , propertyName ) ; return "" ; } } ) ; assertEquals ( "" , session . getPropertyManager ( ) . lookup ( "" ) ) ; } private class OurPersister extends MockComponentPersister implements OddjobPersister { @ Override public ComponentPersister persisterFor ( final String id ) { return new MockComponentPersister ( ) { @ Override public String toString ( ) { return "" + id ; } } ; } } public void testNestedComponentPersisterNoOddjobId ( ) { StandardArooaSession outerSession = new StandardArooaSession ( ) { public ComponentPersister getComponentPersister ( ) { return new OurPersister ( ) ; } ; } ; Oddjob oddjob = new Oddjob ( ) ; OddjobSessionFactory test = new OddjobSessionFactory ( ) ; test . setExistingSession ( outerSession ) ; ArooaSession session = test . createSession ( oddjob ) ; assertNull ( session . getComponentPersister ( ) ) ; } public void testNestedComponentPersister ( ) { StandardArooaSession outerSession = new StandardArooaSession ( ) { public ComponentPersister getComponentPersister ( ) { return new OurPersister ( ) ; } ; } ; Oddjob oddjob = new Oddjob ( ) ; outerSession . getBeanRegistry ( ) . register ( "" , oddjob ) ; OddjobSessionFactory test = new OddjobSessionFactory ( ) ; test . setExistingSession ( outerSession ) ; ArooaSession session = test . createSession ( oddjob ) ; assertEquals ( "" , session . getComponentPersister ( ) . toString ( ) ) ; } } package org . oddjob . scheduling ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . StateConditions ; public class TriggerDesFaTest extends TestCase { DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; DesignParser parser = new DesignParser ( new StandardArooaSession ( descriptor ) ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; Trigger trigger = ( Trigger ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( trigger , trigger . getOn ( ) ) ; assertEquals ( StateConditions . EXCEPTION , trigger . getState ( ) ) ; assertEquals ( StateConditions . FINISHED , trigger . getCancelWhen ( ) ) ; assertEquals ( true , trigger . isNewOnly ( ) ) ; assertEquals ( , Helper . getChildren ( trigger ) . length ) ; } public static void main ( String args [ ] ) throws ArooaParseException { TriggerDesFaTest test = new TriggerDesFaTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . scheduling ; import java . text . DecimalFormat ; public class TimeDisplay { private final int days ; private final int hours ; private final int minutes ; private final int seconds ; private final int milliseconds ; public TimeDisplay ( long time ) { milliseconds = ( int ) ( time % ) ; long remainder = time / ; seconds = ( int ) remainder % ; remainder = remainder / ; minutes = ( int ) remainder % ; remainder = remainder / ; hours = ( int ) remainder % ; days = ( int ) remainder / ; } public int getDays ( ) { return days ; } public int getHours ( ) { return hours ; } public int getMinutes ( ) { return minutes ; } public int getSeconds ( ) { return seconds ; } public int getMilliseconds ( ) { return milliseconds ; } public String toString ( ) { return new DecimalFormat ( "" ) . format ( days ) + "" + new DecimalFormat ( "" ) . format ( hours ) + "" + new DecimalFormat ( "" ) . format ( minutes ) + "" + new DecimalFormat ( "" ) . format ( seconds ) + "" + new DecimalFormat ( "" ) . format ( milliseconds ) ; } } package org . oddjob . scheduling ; import java . beans . PropertyVetoException ; import java . text . ParseException ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . WaitHelper ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SerializableJob ; import org . oddjob . framework . StopWait ; import org . oddjob . persist . ArchiveBrowserJob ; import org . oddjob . persist . MapPersister ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . util . Clock ; public class TimerRetryCombinationTest extends TestCase { private static final Logger logger = Logger . getLogger ( TimerRetryCombinationTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } public static class Results extends SerializableJob { private static final long serialVersionUID = ; private int soft ; private int hard ; private int executions ; private int result ; @ Override protected int execute ( ) throws Throwable { logger . info ( "" ) ; ++ executions ; return result ; } @ Override public boolean hardReset ( ) { if ( super . hardReset ( ) ) { logger . info ( "" ) ; synchronized ( this ) { hard ++ ; } return true ; } return false ; } @ Override public boolean softReset ( ) { if ( super . softReset ( ) ) { logger . info ( "" ) ; synchronized ( this ) { soft ++ ; } return true ; } return false ; } public synchronized int getSoft ( ) { return soft ; } public synchronized int getHard ( ) { return hard ; } public int getExecutions ( ) { return executions ; } public int getResult ( ) { return result ; } public void setResult ( int result ) { this . result = result ; } } public void testContextReset ( ) throws ArooaConversionException , PropertyVetoException , InterruptedException { XMLConfiguration config = new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ; DefaultExecutors services = new DefaultExecutors ( ) ; MapPersister persister = new MapPersister ( ) ; persister . setPath ( "" ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setOddjobExecutors ( services ) ; oddjob1 . setConfiguration ( config ) ; oddjob1 . setPersister ( persister ) ; logger . info ( "" ) ; StateSteps oddjob1State = new StateSteps ( oddjob1 ) ; oddjob1State . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . INCOMPLETE ) ; oddjob1 . run ( ) ; oddjob1State . checkWait ( ) ; OddjobLookup lookup1 = new OddjobLookup ( oddjob1 ) ; int hards1 = lookup1 . lookup ( "" , Integer . TYPE ) ; int softs1 = lookup1 . lookup ( "" , Integer . TYPE ) ; int executions = lookup1 . lookup ( "" , Integer . TYPE ) ; assertEquals ( , hards1 ) ; assertEquals ( , softs1 ) ; assertEquals ( , executions ) ; oddjob1 . softReset ( ) ; hards1 = lookup1 . lookup ( "" , Integer . TYPE ) ; softs1 = lookup1 . lookup ( "" , Integer . TYPE ) ; executions = lookup1 . lookup ( "" , Integer . TYPE ) ; assertEquals ( , hards1 ) ; assertEquals ( , softs1 ) ; assertEquals ( , executions ) ; logger . info ( "" ) ; oddjob1State . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . INCOMPLETE ) ; oddjob1 . run ( ) ; oddjob1State . checkWait ( ) ; hards1 = lookup1 . lookup ( "" , Integer . TYPE ) ; softs1 = lookup1 . lookup ( "" , Integer . TYPE ) ; executions = lookup1 . lookup ( "" , Integer . TYPE ) ; assertEquals ( , hards1 ) ; assertEquals ( , softs1 ) ; assertEquals ( , executions ) ; Resetable timer = lookup1 . lookup ( "" , Resetable . class ) ; timer . hardReset ( ) ; oddjob1 . destroy ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setOddjobExecutors ( services ) ; oddjob2 . setConfiguration ( config ) ; oddjob2 . setPersister ( persister ) ; logger . info ( "" ) ; StateSteps oddjob2State = new StateSteps ( oddjob2 ) ; oddjob2State . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . INCOMPLETE ) ; oddjob2 . run ( ) ; oddjob2State . checkWait ( ) ; OddjobLookup lookup2 = new OddjobLookup ( oddjob2 ) ; int hards2 = lookup2 . lookup ( "" , Integer . TYPE ) ; int softs2 = lookup2 . lookup ( "" , Integer . TYPE ) ; int executions2 = lookup2 . lookup ( "" , Integer . TYPE ) ; assertEquals ( , hards2 ) ; assertEquals ( , softs2 ) ; assertEquals ( , executions2 ) ; oddjob2 . destroy ( ) ; services . stop ( ) ; } private class RecordingStateListener implements StateListener { final List < StateEvent > eventList = new ArrayList < StateEvent > ( ) ; public synchronized void jobStateChange ( StateEvent event ) { logger . info ( "" + event . getState ( ) + "" + event . getSource ( ) + "" + eventList . size ( ) + "" ) ; eventList . add ( event ) ; } public synchronized StateEvent get ( int index ) { return eventList . get ( index ) ; } public synchronized int size ( ) { return eventList . size ( ) ; } } public void testStateNotifications ( ) throws FailedToStopException { XMLConfiguration config = new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ; DefaultExecutors services = new DefaultExecutors ( ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setOddjobExecutors ( services ) ; oddjob1 . setConfiguration ( config ) ; RecordingStateListener ojRec = new RecordingStateListener ( ) ; oddjob1 . addStateListener ( ojRec ) ; assertEquals ( , ojRec . size ( ) ) ; assertEquals ( ParentState . READY , ojRec . get ( ) . getState ( ) ) ; oddjob1 . load ( ) ; assertEquals ( , ojRec . size ( ) ) ; Timer timer = ( Timer ) new OddjobLookup ( oddjob1 ) . lookup ( "" ) ; RecordingStateListener timerRec = new RecordingStateListener ( ) ; timer . addStateListener ( timerRec ) ; assertEquals ( , timerRec . size ( ) ) ; assertEquals ( ParentState . READY , timerRec . get ( ) . getState ( ) ) ; Retry retry = ( Retry ) new OddjobLookup ( oddjob1 ) . lookup ( "" ) ; RecordingStateListener retryRec = new RecordingStateListener ( ) ; retry . addStateListener ( retryRec ) ; assertEquals ( , retryRec . size ( ) ) ; assertEquals ( ParentState . READY , retryRec . get ( ) . getState ( ) ) ; oddjob1 . run ( ) ; new StopWait ( oddjob1 ) . run ( ) ; logger . info ( "" + oddjob1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . EXECUTING , ojRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . ACTIVE , ojRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , ojRec . get ( ) . getState ( ) ) ; assertEquals ( , ojRec . size ( ) ) ; new StopWait ( timer ) . run ( ) ; logger . info ( "" + timer . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . EXECUTING , timerRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . ACTIVE , timerRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , timerRec . get ( ) . getState ( ) ) ; assertEquals ( , timerRec . size ( ) ) ; assertEquals ( ParentState . EXECUTING , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . ACTIVE , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . EXECUTING , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . ACTIVE , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . EXECUTING , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . ACTIVE , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . EXECUTING , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . ACTIVE , retryRec . get ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , retryRec . get ( ) . getState ( ) ) ; assertEquals ( , retryRec . size ( ) ) ; logger . info ( "" ) ; oddjob1 . destroy ( ) ; assertEquals ( ParentState . DESTROYED , retryRec . get ( ) . getState ( ) ) ; assertEquals ( , retryRec . size ( ) ) ; services . stop ( ) ; } private class OurClock implements Clock { Date date ; @ Override public Date getDate ( ) { return date ; } } public void testRetriesWithCatchup ( ) throws ArooaConversionException , PropertyVetoException , ParseException , InterruptedException { XMLConfiguration config = new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ; MapPersister persister = new MapPersister ( ) ; persister . setPath ( "" ) ; OurClock clock = new OurClock ( ) ; clock . date = DateHelper . parseDateTime ( "" ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setConfiguration ( config ) ; oddjob1 . setPersister ( persister ) ; oddjob1 . setExport ( "" , new ArooaObject ( clock ) ) ; oddjob1 . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; final OddjobLookup lookup1 = new OddjobLookup ( oddjob1 ) ; final Date waitForDate1 = DateHelper . parseDateTime ( "" ) ; new WaitHelper ( ) { Date isNow ; @ Override public boolean condition ( ) throws ArooaPropertyException , ArooaConversionException { isNow = lookup1 . lookup ( "" , Date . class ) ; return waitForDate1 . equals ( isNow ) ; } @ Override public void onRetry ( ) { logger . info ( "" + waitForDate1 + "" + isNow ) ; } } . run ( ) ; int hards1 = lookup1 . lookup ( "" , Integer . TYPE ) ; int softs1 = lookup1 . lookup ( "" , Integer . TYPE ) ; int executions1 = lookup1 . lookup ( "" , Integer . TYPE ) ; assertEquals ( , hards1 ) ; assertEquals ( , softs1 ) ; assertEquals ( , executions1 ) ; oddjob1 . destroy ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setConfiguration ( config ) ; oddjob2 . setPersister ( persister ) ; oddjob2 . setExport ( "" , new ArooaObject ( clock ) ) ; clock . date = DateHelper . parseDateTime ( "" ) ; oddjob2 . run ( ) ; final OddjobLookup lookup2 = new OddjobLookup ( oddjob2 ) ; final Date waitForDate2 = DateHelper . parseDateTime ( "" ) ; new WaitHelper ( ) { Date isNow ; @ Override public boolean condition ( ) throws ArooaPropertyException , ArooaConversionException { isNow = lookup2 . lookup ( "" , Date . class ) ; return waitForDate2 . equals ( isNow ) ; } @ Override public void onRetry ( ) { logger . info ( "" + waitForDate2 + "" + isNow ) ; } } . run ( ) ; int hards2 = lookup2 . lookup ( "" , Integer . TYPE ) ; int softs2 = lookup2 . lookup ( "" , Integer . TYPE ) ; int executions2 = lookup2 . lookup ( "" , Integer . TYPE ) ; assertEquals ( , hards2 ) ; assertEquals ( , softs2 ) ; assertEquals ( , executions2 ) ; ArchiveBrowserJob browser = new ArchiveBrowserJob ( ) ; browser . setArchiver ( persister ) ; browser . setArchiveName ( "" ) ; browser . run ( ) ; Object [ ] children = Helper . getChildren ( browser ) ; assertEquals ( , children . length ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; assertEquals ( "" , children [ ] . toString ( ) ) ; oddjob2 . destroy ( ) ; } public void testSimpleTimerRetryExample ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , ParseException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Timer timer = lookup . lookup ( "" , Timer . class ) ; timer . setClock ( new ManualClock ( "" ) ) ; Stateful flagJob = lookup . lookup ( "" , Stateful . class ) ; StateSteps states = new StateSteps ( flagJob ) ; states . startCheck ( JobState . READY , JobState . EXECUTING , JobState . EXCEPTION , JobState . READY , JobState . EXECUTING , JobState . EXCEPTION ) ; oddjob . run ( ) ; states . checkWait ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , timer . getNextDue ( ) ) ; oddjob . stop ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; timer . setClock ( new ManualClock ( "" ) ) ; states . startCheck ( JobState . EXCEPTION , JobState . READY , JobState . EXECUTING , JobState . EXCEPTION , JobState . READY , JobState . EXECUTING , JobState . EXCEPTION ) ; oddjob . run ( ) ; states . checkWait ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , timer . getNextDue ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . scheduling ; import java . io . IOException ; import java . text . ParseException ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . MockOddjobServices ; import org . oddjob . MockStateful ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . framework . StopWait ; import org . oddjob . jobs . SequenceJob ; import org . oddjob . jobs . structural . ParallelJob ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . DateSchedule ; import org . oddjob . schedules . schedules . IntervalSchedule ; import org . oddjob . schedules . schedules . NowSchedule ; import org . oddjob . schedules . schedules . TimeSchedule ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . Resets ; import org . oddjob . state . StateConditions ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . util . Clock ; public class RetryTest extends TestCase { private class OurClock implements Clock { Date date ; public OurClock ( ) { } public OurClock ( String text ) throws ParseException { date = DateHelper . parseDateTime ( text ) ; } public Date getDate ( ) { return date ; } } private class OurOddjobServices extends MockOddjobServices { Runnable runnable ; long delay ; boolean canceled ; public ScheduledExecutorService getScheduledExecutor ( ) { return new MockScheduledExecutorService ( ) { public ScheduledFuture < ? > schedule ( Runnable runnable , long delay , TimeUnit unit ) { OurOddjobServices . this . delay = delay ; OurOddjobServices . this . runnable = runnable ; return new MockScheduledFuture < Void > ( ) { public boolean cancel ( boolean interrupt ) { canceled = true ; return true ; } } ; } } ; } } public void testRetry ( ) throws ParseException , FailedToStopException { FlagState job = new FlagState ( ) ; job . setState ( JobState . INCOMPLETE ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; Interval limits = time . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalSchedule retry = new IntervalSchedule ( ) ; retry . setInterval ( "" ) ; OurClock clock = new OurClock ( ) ; clock . date = DateHelper . parseDateTime ( "" ) ; Retry test = new Retry ( ) ; test . setLimits ( limits ) ; test . setSchedule ( retry ) ; test . setClock ( clock ) ; test . setJob ( job ) ; OurOddjobServices oddjobServices = new OurOddjobServices ( ) ; test . setScheduleExecutorService ( oddjobServices . getScheduledExecutor ( ) ) ; test . run ( ) ; assertNotNull ( oddjobServices . runnable ) ; assertEquals ( , oddjobServices . delay ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getNextDue ( ) ) ; oddjobServices . delay = - ; clock . date = DateHelper . parseDateTime ( "" ) ; oddjobServices . runnable . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( * * , oddjobServices . delay ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getNextDue ( ) ) ; oddjobServices . delay = - ; oddjobServices . runnable . run ( ) ; assertEquals ( - , oddjobServices . delay ) ; assertEquals ( null , test . getNextDue ( ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . stop ( ) ; assertFalse ( oddjobServices . canceled ) ; } public void testLongRetry ( ) throws ParseException , FailedToStopException { FlagState job = new FlagState ( ) ; job . setState ( JobState . INCOMPLETE ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; Interval limits = time . nextDue ( new ScheduleContext ( DateHelper . parseDateTime ( "" ) ) ) ; IntervalSchedule retry = new IntervalSchedule ( ) ; retry . setInterval ( "" ) ; OurClock clock = new OurClock ( ) ; clock . date = DateHelper . parseDateTime ( "" ) ; Retry test = new Retry ( ) ; test . setLimits ( limits ) ; test . setSchedule ( retry ) ; test . setClock ( clock ) ; test . setJob ( job ) ; OurOddjobServices oddjobServices = new OurOddjobServices ( ) ; test . setScheduleExecutorService ( oddjobServices . getScheduledExecutor ( ) ) ; test . run ( ) ; assertNotNull ( oddjobServices . runnable ) ; assertEquals ( , oddjobServices . delay ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getNextDue ( ) ) ; oddjobServices . delay = - ; clock . date = DateHelper . parseDateTime ( "" ) ; oddjobServices . runnable . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , oddjobServices . delay ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getNextDue ( ) ) ; oddjobServices . delay = - ; oddjobServices . runnable . run ( ) ; assertEquals ( - , oddjobServices . delay ) ; assertEquals ( null , test . getNextDue ( ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . stop ( ) ; assertFalse ( oddjobServices . canceled ) ; } public void testManualRetry ( ) throws ParseException , FailedToStopException { FlagState job = new FlagState ( ) ; job . setState ( JobState . INCOMPLETE ) ; IntervalSchedule schedule = new IntervalSchedule ( ) ; schedule . setInterval ( "" ) ; OurClock clock = new OurClock ( ) ; clock . date = DateHelper . parseDateTime ( "" ) ; Retry test = new Retry ( ) ; test . setSchedule ( schedule ) ; test . setClock ( clock ) ; test . setJob ( job ) ; OurOddjobServices oddjobServices = new OurOddjobServices ( ) ; test . setScheduleExecutorService ( oddjobServices . getScheduledExecutor ( ) ) ; test . run ( ) ; oddjobServices . runnable . run ( ) ; assertEquals ( * * * , oddjobServices . delay ) ; job . setState ( JobState . COMPLETE ) ; job . softReset ( ) ; job . run ( ) ; assertEquals ( * * * , oddjobServices . delay ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getNextDue ( ) ) ; oddjobServices . delay = - ; oddjobServices . runnable . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( - , oddjobServices . delay ) ; test . stop ( ) ; assertFalse ( oddjobServices . canceled ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } private class OurJob extends MockStateful implements Runnable , Resetable { boolean reset ; final List < StateListener > listeners = new ArrayList < StateListener > ( ) ; public void addStateListener ( StateListener listener ) { listeners . add ( listener ) ; listener . jobStateChange ( new StateEvent ( this , JobState . READY ) ) ; } public void removeStateListener ( StateListener listener ) { listeners . remove ( listener ) ; } public void run ( ) { List < StateListener > copy = new ArrayList < StateListener > ( listeners ) ; for ( StateListener listener : copy ) { listener . jobStateChange ( new StateEvent ( this , JobState . COMPLETE ) ) ; } } public boolean hardReset ( ) { throw new RuntimeException ( "" ) ; } public boolean softReset ( ) { reset = true ; return true ; } } public void testSimpleSchedule ( ) throws Exception { DateSchedule schedule = new DateSchedule ( ) ; schedule . setOn ( "" ) ; OurJob ourJob = new OurJob ( ) ; Retry test = new Retry ( ) ; test . setSchedule ( schedule ) ; test . setJob ( ourJob ) ; OurOddjobServices oddjobServices = new OurOddjobServices ( ) ; test . setScheduleExecutorService ( oddjobServices . getScheduledExecutor ( ) ) ; test . run ( ) ; Date expected = DateHelper . parseDate ( "" ) ; assertEquals ( expected , test . getNextDue ( ) ) ; assertEquals ( expected , test . getCurrent ( ) . getFromDate ( ) ) ; oddjobServices . delay = - ; oddjobServices . runnable . run ( ) ; assertNull ( null , test . getNextDue ( ) ) ; assertEquals ( - , oddjobServices . delay ) ; assertTrue ( ourJob . reset ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . setJob ( null ) ; test . destroy ( ) ; assertEquals ( , ourJob . listeners . size ( ) ) ; assertFalse ( oddjobServices . canceled ) ; } public void testSerializeUnserializbleSchedule ( ) throws IOException , ClassNotFoundException { Retry test = new Retry ( ) ; test . setSchedule ( new Schedule ( ) { public IntervalTo nextDue ( ScheduleContext context ) { return null ; } } ) ; Retry copy = Helper . copy ( test ) ; assertNull ( copy . getSchedule ( ) ) ; } public void testStateNotifications ( ) throws InterruptedException { FlagState incomplete = new FlagState ( JobState . INCOMPLETE ) ; DefaultExecutors defaultServices = new DefaultExecutors ( ) ; Retry test = new Retry ( ) ; StateSteps steps = new StateSteps ( test ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . INCOMPLETE ) ; CountSchedule count = new CountSchedule ( ) ; count . setCount ( ) ; count . setRefinement ( new NowSchedule ( ) ) ; test . setSchedule ( count ) ; test . setScheduleExecutorService ( defaultServices . getScheduledExecutor ( ) ) ; SequenceJob sequence = new SequenceJob ( ) ; sequence . setFrom ( ) ; Resets resets = new Resets ( ) ; resets . setHarden ( true ) ; resets . setJob ( sequence ) ; ParallelJob parallel = new ParallelJob ( ) ; parallel . setExecutorService ( defaultServices . getPoolExecutor ( ) ) ; parallel . setJobs ( , resets ) ; parallel . setJobs ( , incomplete ) ; test . setJob ( parallel ) ; test . run ( ) ; steps . checkWait ( ) ; assertEquals ( , sequence . getCurrent ( ) . intValue ( ) ) ; steps . startCheck ( ParentState . INCOMPLETE , ParentState . READY ) ; test . softReset ( ) ; steps . checkNow ( ) ; steps . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . INCOMPLETE ) ; test . run ( ) ; steps . checkWait ( ) ; assertEquals ( , sequence . getCurrent ( ) . intValue ( ) ) ; defaultServices . stop ( ) ; } private class ExecuteImmediately extends MockScheduledExecutorService { public ScheduledFuture < ? > schedule ( Runnable runnable , long delay , TimeUnit unit ) { new Thread ( runnable ) . start ( ) ; return new MockScheduledFuture < Void > ( ) ; } } ; private class LockExamineJob extends SimpleJob { int i = ; @ Override protected int execute ( ) throws Throwable { if ( i ++ == ) { return ; } return ; } @ Override public boolean hardReset ( ) { throw new RuntimeException ( "" ) ; } @ Override public boolean softReset ( ) { try { stateHandler . assertLockHeld ( ) ; fail ( "" ) ; } catch ( IllegalStateException e ) { } return super . softReset ( ) ; } } public void testLocking ( ) throws FailedToStopException { Retry test = new Retry ( ) ; test . setScheduleExecutorService ( new ExecuteImmediately ( ) ) ; test . setSchedule ( new NowSchedule ( ) ) ; test . setJob ( new LockExamineJob ( ) ) ; test . run ( ) ; new StopWait ( test ) . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } private class TestListeners extends SimpleJob { int i = ; int listeners = ; @ Override protected int execute ( ) throws Throwable { assertEquals ( , listeners ) ; if ( i ++ == ) { return ; } return ; } @ Override public boolean hardReset ( ) { throw new RuntimeException ( "" ) ; } @ Override public boolean softReset ( ) { return super . softReset ( ) ; } @ Override public void addStateListener ( StateListener listener ) { listeners ++ ; super . addStateListener ( listener ) ; } @ Override public void removeStateListener ( StateListener listener ) { listeners -- ; super . removeStateListener ( listener ) ; } } public void testListeners ( ) throws FailedToStopException { Retry test = new Retry ( ) ; test . setScheduleExecutorService ( new ExecuteImmediately ( ) ) ; test . setSchedule ( new NowSchedule ( ) ) ; test . setJob ( new TestListeners ( ) ) ; test . run ( ) ; new StopWait ( test ) . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } private class ExecuteNever extends MockScheduledExecutorService { public ScheduledFuture < ? > schedule ( Runnable runnable , long delay , TimeUnit unit ) { return new MockScheduledFuture < Void > ( ) { @ Override public boolean cancel ( boolean mayInterruptIfRunning ) { return true ; } } ; } } ; private class LaterJob extends SimpleJob { void start ( ) { stateHandler . waitToWhen ( StateConditions . READY , new Runnable ( ) { public void run ( ) { stateHandler . setState ( JobState . EXECUTING ) ; stateHandler . fireEvent ( ) ; } } ) ; } void complete ( ) { stateHandler . waitToWhen ( StateConditions . EXECUTING , new Runnable ( ) { public void run ( ) { stateHandler . setState ( JobState . COMPLETE ) ; stateHandler . fireEvent ( ) ; } } ) ; } @ Override protected int execute ( ) throws Throwable { throw new RuntimeException ( "" ) ; } @ Override public boolean hardReset ( ) { throw new RuntimeException ( "" ) ; } @ Override public boolean softReset ( ) { throw new RuntimeException ( "" ) ; } } public void testStopFirst ( ) throws FailedToStopException { Retry test = new Retry ( ) ; test . setScheduleExecutorService ( new ExecuteNever ( ) ) ; test . setSchedule ( new NowSchedule ( ) ) ; final LaterJob job = new LaterJob ( ) ; test . setJob ( job ) ; test . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; job . start ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; SimpleJob stop = new SimpleJob ( ) { @ Override protected int execute ( ) throws Throwable { job . complete ( ) ; return ; } } ; new Thread ( stop ) . start ( ) ; test . stop ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testStopLast ( ) throws FailedToStopException { Retry test = new Retry ( ) ; test . setScheduleExecutorService ( new ExecuteNever ( ) ) ; test . setSchedule ( new NowSchedule ( ) ) ; LaterJob job = new LaterJob ( ) ; test . setJob ( job ) ; test . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; job . start ( ) ; job . complete ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; test . stop ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testWithLimitsLongOverDue ( ) throws ParseException { FlagState job = new FlagState ( JobState . INCOMPLETE ) ; OurClock clock = new OurClock ( "" ) ; IntervalTo limits = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; OurOddjobServices services = new OurOddjobServices ( ) ; Schedule schedule = new IntervalSchedule ( * * ) ; Retry test = new Retry ( ) ; test . setClock ( clock ) ; test . setLimits ( limits ) ; test . setSchedule ( schedule ) ; test . setScheduleExecutorService ( services . getScheduledExecutor ( ) ) ; test . setJob ( job ) ; test . run ( ) ; assertNotNull ( services . runnable ) ; assertEquals ( , services . delay ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getNextDue ( ) ) ; services . runnable . run ( ) ; assertEquals ( null , test . getNextDue ( ) ) ; } public void testWithLimitsLongOverDueCountSchedule ( ) throws ParseException { FlagState job = new FlagState ( JobState . INCOMPLETE ) ; OurClock clock = new OurClock ( "" ) ; IntervalTo limits = new IntervalTo ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ; OurOddjobServices services = new OurOddjobServices ( ) ; CountSchedule schedule = new CountSchedule ( ) ; schedule . setRefinement ( new NowSchedule ( ) ) ; Retry test = new Retry ( ) ; test . setClock ( clock ) ; test . setLimits ( limits ) ; test . setSchedule ( schedule ) ; test . setScheduleExecutorService ( services . getScheduledExecutor ( ) ) ; test . setJob ( job ) ; test . run ( ) ; assertNotNull ( services . runnable ) ; assertEquals ( , services . delay ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getNextDue ( ) ) ; services . runnable . run ( ) ; assertEquals ( null , test . getNextDue ( ) ) ; } public void testFilePollingExample ( ) throws FailedToStopException , InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful exists = ( Stateful ) lookup . lookup ( "" ) ; StateSteps oddjobStates = new StateSteps ( oddjob ) ; oddjobStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; StateSteps existsStates = new StateSteps ( exists ) ; existsStates . startCheck ( JobState . READY , JobState . EXECUTING , JobState . INCOMPLETE ) ; oddjob . run ( ) ; oddjobStates . checkNow ( ) ; existsStates . checkWait ( ) ; oddjobStates . startCheck ( ParentState . ACTIVE , ParentState . READY ) ; oddjob . stop ( ) ; oddjobStates . checkNow ( ) ; oddjob . destroy ( ) ; } } package org . oddjob . scheduling ; import java . io . File ; import java . io . IOException ; import java . text . ParseException ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import java . util . TimeZone ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . IconSteps ; import org . oddjob . MockOddjobExecutors ; import org . oddjob . MockStateful ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . types . ArooaObject ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . images . IconHelper ; import org . oddjob . jobs . WaitJob ; import org . oddjob . persist . MapPersister ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . SimpleInterval ; import org . oddjob . schedules . SimpleScheduleResult ; import org . oddjob . schedules . schedules . CountSchedule ; import org . oddjob . schedules . schedules . DailySchedule ; import org . oddjob . schedules . schedules . DateSchedule ; import org . oddjob . schedules . schedules . IntervalSchedule ; import org . oddjob . schedules . schedules . NowSchedule ; import org . oddjob . schedules . schedules . TimeSchedule ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class TimerTest extends TestCase { private static final Logger logger = Logger . getLogger ( TimerTest . class ) ; protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } private class OurJob extends MockStateful implements Runnable , Resetable { int resets ; final List < StateListener > listeners = new ArrayList < StateListener > ( ) ; public void addStateListener ( StateListener listener ) { listeners . add ( listener ) ; listener . jobStateChange ( new StateEvent ( this , JobState . READY ) ) ; } public void removeStateListener ( StateListener listener ) { listeners . remove ( listener ) ; } public void run ( ) { List < StateListener > copy = new ArrayList < StateListener > ( listeners ) ; for ( StateListener listener : copy ) { listener . jobStateChange ( new StateEvent ( this , JobState . EXECUTING ) ) ; listener . jobStateChange ( new StateEvent ( this , JobState . COMPLETE ) ) ; } } public boolean hardReset ( ) { ++ resets ; return true ; } public boolean softReset ( ) { throw new RuntimeException ( "" ) ; } } private class OurScheduledExecutorService extends MockScheduledExecutorService { Runnable runnable ; long delay ; public ScheduledFuture < ? > schedule ( Runnable runnable , long delay , TimeUnit unit ) { OurScheduledExecutorService . this . delay = delay ; OurScheduledExecutorService . this . runnable = runnable ; return new MockScheduledFuture < Void > ( ) ; } } ; public void testSimpleNonRepeatingSchedule ( ) throws Exception { DateSchedule schedule = new DateSchedule ( ) ; schedule . setOn ( "" ) ; OurJob ourJob = new OurJob ( ) ; ManualClock clock = new ManualClock ( "" ) ; Timer test = new Timer ( ) ; test . setSchedule ( schedule ) ; test . setJob ( ourJob ) ; test . setHaltOnFailure ( true ) ; test . setClock ( clock ) ; OurScheduledExecutorService oddjobServices = new OurScheduledExecutorService ( ) ; test . setScheduleExecutorService ( oddjobServices ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . SLEEPING ) ; test . run ( ) ; state . checkNow ( ) ; icons . checkNow ( ) ; Date expected = DateHelper . parseDate ( "" ) ; assertEquals ( expected , test . getNextDue ( ) ) ; assertEquals ( expected , test . getCurrent ( ) . getFromDate ( ) ) ; assertEquals ( * * * , oddjobServices . delay ) ; state . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; icons . startCheck ( IconHelper . SLEEPING , IconHelper . EXECUTING , IconHelper . COMPLETE ) ; oddjobServices . delay = - ; oddjobServices . runnable . run ( ) ; oddjobServices . runnable = null ; assertNull ( null , test . getNextDue ( ) ) ; assertNull ( null , test . getCurrent ( ) ) ; assertEquals ( expected , test . getLastDue ( ) ) ; assertEquals ( - , oddjobServices . delay ) ; assertEquals ( , ourJob . resets ) ; state . checkNow ( ) ; icons . checkNow ( ) ; clock . setDate ( "" ) ; state . startCheck ( ParentState . COMPLETE , ParentState . READY ) ; icons . startCheck ( IconHelper . COMPLETE , IconHelper . READY ) ; test . hardReset ( ) ; state . checkNow ( ) ; icons . checkNow ( ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; icons . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . SLEEPING ) ; test . run ( ) ; state . checkNow ( ) ; icons . checkNow ( ) ; assertEquals ( expected , test . getNextDue ( ) ) ; assertEquals ( expected , test . getCurrent ( ) . getFromDate ( ) ) ; assertEquals ( , oddjobServices . delay ) ; state . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; icons . startCheck ( IconHelper . SLEEPING , IconHelper . EXECUTING , IconHelper . COMPLETE ) ; oddjobServices . delay = - ; oddjobServices . runnable . run ( ) ; oddjobServices . runnable = null ; assertNull ( null , test . getNextDue ( ) ) ; assertNull ( null , test . getCurrent ( ) ) ; assertEquals ( expected , test . getLastDue ( ) ) ; assertEquals ( - , oddjobServices . delay ) ; assertEquals ( , ourJob . resets ) ; state . checkNow ( ) ; icons . checkNow ( ) ; test . setJob ( null ) ; test . destroy ( ) ; assertEquals ( , ourJob . listeners . size ( ) ) ; } public void testRecurringScheduleWhenStopped ( ) throws ParseException { FlagState job = new FlagState ( ) ; job . setState ( JobState . COMPLETE ) ; DailySchedule time = new DailySchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; ManualClock clock = new ManualClock ( "" ) ; Timer test = new Timer ( ) ; test . setSchedule ( time ) ; test . setClock ( clock ) ; test . setJob ( job ) ; OurScheduledExecutorService oddjobServices = new OurScheduledExecutorService ( ) ; test . setScheduleExecutorService ( oddjobServices ) ; test . run ( ) ; assertNotNull ( oddjobServices . runnable ) ; assertEquals ( , oddjobServices . delay ) ; oddjobServices . runnable . run ( ) ; Date expectedNextDue = DateHelper . parseDateTime ( "" ) ; assertEquals ( expectedNextDue , test . getNextDue ( ) ) ; assertEquals ( expectedNextDue . getTime ( ) - clock . getDate ( ) . getTime ( ) , oddjobServices . delay ) ; } public void testOverdueSchedule ( ) throws ParseException { FlagState job = new FlagState ( ) ; job . setState ( JobState . COMPLETE ) ; DailySchedule time = new DailySchedule ( ) ; time . setAt ( "" ) ; ManualClock clock = new ManualClock ( "" ) ; Timer test = new Timer ( ) ; test . setSchedule ( time ) ; test . setClock ( clock ) ; test . setJob ( job ) ; OurScheduledExecutorService oddjobServices = new OurScheduledExecutorService ( ) ; test . setScheduleExecutorService ( oddjobServices ) ; test . run ( ) ; assertNotNull ( oddjobServices . runnable ) ; assertEquals ( * * * , oddjobServices . delay ) ; clock . setDate ( "" ) ; oddjobServices . runnable . run ( ) ; assertEquals ( , oddjobServices . delay ) ; clock . setDate ( "" ) ; oddjobServices . runnable . run ( ) ; assertEquals ( * * * , oddjobServices . delay ) ; } public void testSkipMissedSchedule ( ) throws ParseException { FlagState job = new FlagState ( ) ; job . setState ( JobState . COMPLETE ) ; DailySchedule time = new DailySchedule ( ) ; time . setAt ( "" ) ; ManualClock clock = new ManualClock ( "" ) ; Timer test = new Timer ( ) ; test . setSchedule ( time ) ; test . setClock ( clock ) ; test . setJob ( job ) ; test . setSkipMissedRuns ( true ) ; OurScheduledExecutorService oddjobServices = new OurScheduledExecutorService ( ) ; test . setScheduleExecutorService ( oddjobServices ) ; test . run ( ) ; assertNotNull ( oddjobServices . runnable ) ; assertEquals ( * * * , oddjobServices . delay ) ; clock . setDate ( "" ) ; oddjobServices . runnable . run ( ) ; assertEquals ( * * * , oddjobServices . delay ) ; } public void testHaltOnFailure ( ) throws ParseException { FlagState job = new FlagState ( ) ; job . setState ( JobState . INCOMPLETE ) ; TimeSchedule time = new TimeSchedule ( ) ; time . setFrom ( "" ) ; time . setTo ( "" ) ; ManualClock clock = new ManualClock ( "" ) ; Timer test = new Timer ( ) ; test . setSchedule ( time ) ; test . setClock ( clock ) ; test . setHaltOnFailure ( true ) ; test . setJob ( job ) ; OurScheduledExecutorService oddjobServices = new OurScheduledExecutorService ( ) ; test . setScheduleExecutorService ( oddjobServices ) ; test . run ( ) ; assertNotNull ( oddjobServices . runnable ) ; assertEquals ( , oddjobServices . delay ) ; oddjobServices . delay = - ; oddjobServices . runnable . run ( ) ; assertEquals ( - , oddjobServices . delay ) ; assertEquals ( null , test . getNextDue ( ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testTimeZone ( ) throws Exception { TimeZone . setDefault ( TimeZone . getTimeZone ( "" ) ) ; DateSchedule schedule = new DateSchedule ( ) ; schedule . setOn ( "" ) ; DailySchedule daily = new DailySchedule ( ) ; daily . setAt ( "" ) ; schedule . setRefinement ( daily ) ; OurJob ourJob = new OurJob ( ) ; Timer test = new Timer ( ) ; test . setSchedule ( schedule ) ; test . setJob ( ourJob ) ; test . setTimeZone ( "" ) ; OurScheduledExecutorService oddjobServices = new OurScheduledExecutorService ( ) ; test . setScheduleExecutorService ( oddjobServices ) ; test . run ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getNextDue ( ) ) ; TimeZone . setDefault ( null ) ; } public void testSerialize ( ) throws Exception { FlagState sample = new FlagState ( ) ; sample . setState ( JobState . COMPLETE ) ; Timer test = new Timer ( ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; CountSchedule count = new CountSchedule ( ) ; count . setCount ( ) ; count . setRefinement ( interval ) ; ManualClock clock = new ManualClock ( "" ) ; test . setSchedule ( count ) ; test . setJob ( sample ) ; test . setClock ( clock ) ; OurScheduledExecutorService oddjobServices = new OurScheduledExecutorService ( ) ; test . setScheduleExecutorService ( oddjobServices ) ; test . run ( ) ; assertEquals ( , oddjobServices . delay ) ; oddjobServices . runnable . run ( ) ; assertEquals ( , oddjobServices . delay ) ; Timer copy = ( Timer ) Helper . copy ( test ) ; copy . setClock ( clock ) ; copy . setScheduleExecutorService ( oddjobServices ) ; assertEquals ( , oddjobServices . delay ) ; Runnable runnable = oddjobServices . runnable ; oddjobServices . runnable = null ; runnable . run ( ) ; assertNull ( copy . getNextDue ( ) ) ; assertNull ( oddjobServices . runnable ) ; } public void testSerializeNotComplete ( ) throws Exception { FlagState sample = new FlagState ( ) ; sample . setState ( JobState . INCOMPLETE ) ; Timer test = new Timer ( ) ; ManualClock clock = new ManualClock ( "" ) ; test . setSchedule ( new NowSchedule ( ) ) ; test . setJob ( sample ) ; test . setClock ( clock ) ; OurScheduledExecutorService oddjobServices = new OurScheduledExecutorService ( ) ; test . setScheduleExecutorService ( oddjobServices ) ; test . run ( ) ; assertEquals ( , oddjobServices . delay ) ; oddjobServices . runnable . run ( ) ; Timer copy = ( Timer ) Helper . copy ( test ) ; assertEquals ( ParentState . READY , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , test . getLastDue ( ) ) ; assertEquals ( new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) ) ) , test . getCurrent ( ) ) ; } private class OurStopServices extends MockScheduledExecutorService { public ScheduledFuture < ? > schedule ( Runnable runnable , long delay , TimeUnit unit ) { if ( delay < ) { new Thread ( runnable ) . start ( ) ; } return new MockScheduledFuture < Void > ( ) { public boolean cancel ( boolean interrupt ) { return false ; } } ; } } ; public void testStop ( ) throws ParseException , InterruptedException , FailedToStopException { final Timer test = new Timer ( ) ; test . setSchedule ( new CountSchedule ( ) ) ; IntervalSchedule interval = new IntervalSchedule ( ) ; interval . setInterval ( "" ) ; final IconSteps checkFirstThreadFinished = new IconSteps ( test ) ; checkFirstThreadFinished . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . SLEEPING , IconHelper . EXECUTING , IconHelper . ACTIVE , IconHelper . SLEEPING ) ; Retry retry = new Retry ( ) ; retry . setSchedule ( interval ) ; SimpleJob child = new SimpleJob ( ) { int i ; Runnable [ ] jobs = { new FlagState ( ) , new WaitJob ( ) } ; @ Override protected int execute ( ) throws Throwable { jobs [ i ++ ] . run ( ) ; return ; } } ; retry . setJob ( child ) ; test . setJob ( retry ) ; OurStopServices services = new OurStopServices ( ) ; test . setScheduleExecutorService ( services ) ; retry . setScheduleExecutorService ( services ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . READY ) ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . SLEEPING , IconHelper . EXECUTING , IconHelper . ACTIVE , IconHelper . SLEEPING , IconHelper . STOPPING , IconHelper . READY ) ; test . run ( ) ; checkFirstThreadFinished . checkWait ( ) ; test . stop ( ) ; state . checkWait ( ) ; icons . checkNow ( ) ; test . setJob ( null ) ; retry . destroy ( ) ; test . destroy ( ) ; } public void testStopBeforeTriggered ( ) throws FailedToStopException { class Executor extends MockScheduledExecutorService { boolean canceled ; Runnable job ; @ Override public ScheduledFuture < ? > schedule ( Runnable command , long delay , TimeUnit unit ) { job = command ; return new MockScheduledFuture < Void > ( ) { @ Override public boolean cancel ( boolean mayInterruptIfRunning ) { assertEquals ( false , mayInterruptIfRunning ) ; canceled = true ; job = null ; return true ; } } ; } } Executor executor = new Executor ( ) ; Timer test = new Timer ( ) ; test . setClock ( new ManualClock ( "" ) ) ; test . setScheduleExecutorService ( executor ) ; test . setJob ( new FlagState ( ) ) ; TimeSchedule schedule = new TimeSchedule ( ) ; test . setSchedule ( schedule ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . SLEEPING ) ; test . run ( ) ; state . checkNow ( ) ; icons . checkNow ( ) ; state . startCheck ( ParentState . ACTIVE , ParentState . READY ) ; icons . startCheck ( IconHelper . SLEEPING , IconHelper . STOPPING , IconHelper . READY ) ; test . stop ( ) ; state . checkNow ( ) ; icons . checkNow ( ) ; assertEquals ( true , executor . canceled ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; state . checkNow ( ) ; state . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; executor . job . run ( ) ; state . checkNow ( ) ; test . destroy ( ) ; } public void testSerializeUnserializbleSchedule ( ) throws IOException , ClassNotFoundException { Timer test = new Timer ( ) ; test . setSchedule ( new Schedule ( ) { public IntervalTo nextDue ( ScheduleContext context ) { return null ; } } ) ; Timer copy = Helper . copy ( test ) ; assertNull ( copy . getSchedule ( ) ) ; } public void testPersistedScheduleInOddjob ( ) throws FailedToStopException , ArooaPropertyException , ArooaConversionException , InterruptedException , IOException , ParseException { OurDirs dirs = new OurDirs ( ) ; File persistDir = dirs . relative ( "" ) ; if ( persistDir . exists ( ) ) { FileUtils . forceDelete ( persistDir ) ; } Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setFile ( dirs . relative ( "" ) ) ; oddjob1 . setExport ( "" , new ArooaObject ( new ManualClock ( "" ) ) ) ; oddjob1 . setExport ( "" , new ArooaObject ( dirs . relative ( "" ) ) ) ; oddjob1 . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , new OddjobLookup ( oddjob1 ) . lookup ( "" ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , new OddjobLookup ( oddjob1 ) . lookup ( "" ) ) ; oddjob1 . stop ( ) ; assertEquals ( ParentState . READY , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; oddjob1 . destroy ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setFile ( dirs . relative ( "" ) ) ; oddjob2 . setExport ( "" , new ArooaObject ( new ManualClock ( "" ) ) ) ; oddjob2 . setExport ( "" , new ArooaObject ( dirs . relative ( "" ) ) ) ; oddjob2 . load ( ) ; Oddjob innerOddjob2 = new OddjobLookup ( oddjob2 ) . lookup ( "" , Oddjob . class ) ; innerOddjob2 . load ( ) ; Stateful scheduledJob2 = new OddjobLookup ( innerOddjob2 ) . lookup ( "" , Stateful . class ) ; StateSteps scheduledJobState2 = new StateSteps ( scheduledJob2 ) ; scheduledJobState2 . startCheck ( JobState . READY , JobState . EXECUTING , JobState . COMPLETE ) ; oddjob2 . run ( ) ; scheduledJobState2 . checkWait ( ) ; String text2 = new OddjobLookup ( oddjob2 ) . lookup ( "" , String . class ) ; assertEquals ( "" + "" , text2 ) ; oddjob2 . stop ( ) ; assertEquals ( ParentState . READY , oddjob2 . lastStateEvent ( ) . getState ( ) ) ; oddjob2 . destroy ( ) ; Oddjob oddjob3 = new Oddjob ( ) ; oddjob3 . setFile ( dirs . relative ( "" ) ) ; oddjob3 . setExport ( "" , new ArooaObject ( new ManualClock ( "" ) ) ) ; oddjob3 . setExport ( "" , new ArooaObject ( dirs . relative ( "" ) ) ) ; oddjob3 . run ( ) ; assertEquals ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) , new OddjobLookup ( oddjob3 ) . lookup ( "" ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , new OddjobLookup ( oddjob3 ) . lookup ( "" ) ) ; String text3 = new OddjobLookup ( oddjob3 ) . lookup ( "" , String . class ) ; assertEquals ( "" + "" , text3 ) ; oddjob3 . stop ( ) ; assertEquals ( ParentState . READY , oddjob3 . lastStateEvent ( ) . getState ( ) ) ; oddjob3 . destroy ( ) ; } public void testTimerExample ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException , ParseException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Timer timer = lookup . lookup ( "" , Timer . class ) ; ManualClock clock = new ManualClock ( "" ) ; timer . setClock ( clock ) ; Stateful work = lookup . lookup ( "" , Stateful . class ) ; StateSteps workState = new StateSteps ( work ) ; workState . startCheck ( JobState . READY , JobState . EXECUTING , JobState . COMPLETE ) ; oddjob . run ( ) ; workState . checkWait ( ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , timer . getNextDue ( ) ) ; String result = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , result ) ; oddjob . stop ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , work . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , timer . getNextDue ( ) ) ; oddjob . destroy ( ) ; } public void testTimerOnceExample ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . load ( ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; Timer timer = ( Timer ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; timer . setClock ( new ManualClock ( "" ) ) ; StateSteps states = new StateSteps ( oddjob ) ; states . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; oddjob . run ( ) ; states . checkWait ( ) ; oddjob . destroy ( ) ; } private class OurOddjobExecutor extends MockOddjobExecutors { OurScheduledExecutorService executor = new OurScheduledExecutorService ( ) ; @ Override public ScheduledExecutorService getScheduledExecutor ( ) { return executor ; } @ Override public ExecutorService getPoolExecutor ( ) { return null ; } } public void testTimerStopJobExample ( ) throws ArooaPropertyException , ArooaConversionException , InterruptedException , FailedToStopException { OurOddjobExecutor executors = new OurOddjobExecutor ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setOddjobExecutors ( executors ) ; oddjob . load ( ) ; Stateful wait = new OddjobLookup ( oddjob ) . lookup ( "" , Stateful . class ) ; StateSteps waitStates = new StateSteps ( wait ) ; waitStates . startCheck ( JobState . READY , JobState . EXECUTING ) ; new Thread ( oddjob ) . start ( ) ; waitStates . checkWait ( ) ; assertTrue ( executors . executor . delay > ) ; StateSteps states = new StateSteps ( oddjob ) ; states . startCheck ( ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; executors . executor . runnable . run ( ) ; states . checkWait ( ) ; oddjob . destroy ( ) ; } public void testTimerCrashPersistance ( ) { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; OurOddjobExecutor executors1 = new OurOddjobExecutor ( ) ; MapPersister persister = new MapPersister ( ) ; Oddjob oddjob1 = new Oddjob ( ) ; oddjob1 . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob1 . setExport ( "" , new ArooaObject ( new ManualClock ( "" ) ) ) ; oddjob1 . setOddjobExecutors ( executors1 ) ; oddjob1 . setPersister ( persister ) ; oddjob1 . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob1 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , executors1 . executor . delay ) ; executors1 . executor . runnable . run ( ) ; assertEquals ( * * * , executors1 . executor . delay ) ; OurOddjobExecutor executors2 = new OurOddjobExecutor ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob2 . setExport ( "" , new ArooaObject ( new ManualClock ( "" ) ) ) ; oddjob2 . setOddjobExecutors ( executors2 ) ; oddjob2 . setPersister ( persister ) ; oddjob2 . run ( ) ; assertEquals ( * * * , executors2 . executor . delay ) ; } } package org . oddjob . scheduling ; import org . oddjob . arooa . registry . SimpleBeanRegistry ; import junit . framework . TestCase ; public class JobTokenTest extends TestCase { public void test1 ( ) { Object job = new Object ( ) ; JobToken jobToken = JobToken . create ( null , job ) ; assertEquals ( job . toString ( ) , jobToken . toString ( ) ) ; } public void test2 ( ) { Object job = new Object ( ) ; SimpleBeanRegistry cr = new SimpleBeanRegistry ( ) ; cr . register ( "" , job ) ; JobToken jobToken = JobToken . create ( cr , job ) ; assertEquals ( "" , jobToken . toString ( ) ) ; } public void testNoPath ( ) { Object job = new Object ( ) ; SimpleBeanRegistry cr = new SimpleBeanRegistry ( ) ; try { JobToken . create ( cr , job ) ; fail ( "" ) ; } catch ( NullPointerException e ) { } } } package org . oddjob . scheduling ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . Structural ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; import org . oddjob . structural . StructuralEvent ; import org . oddjob . structural . StructuralListener ; public class ExecutorThrottleTypeTest extends TestCase { private static final Logger logger = Logger . getLogger ( ExecutorThrottleTypeTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; } private class Capture implements StructuralListener , StateListener { Set < Stateful > ready = new HashSet < Stateful > ( ) ; Set < Stateful > executing = new HashSet < Stateful > ( ) ; Set < Stateful > complete = new HashSet < Stateful > ( ) ; @ Override public void jobStateChange ( StateEvent event ) { logger . info ( "" + event ) ; synchronized ( this ) { switch ( ( JobState ) event . getState ( ) ) { case READY : ready . add ( event . getSource ( ) ) ; break ; case EXECUTING : ready . remove ( event . getSource ( ) ) ; executing . add ( event . getSource ( ) ) ; break ; case COMPLETE : executing . remove ( event . getSource ( ) ) ; complete . add ( event . getSource ( ) ) ; break ; default : throw new RuntimeException ( "" + event . getState ( ) ) ; } this . notifyAll ( ) ; } } @ Override public void childAdded ( StructuralEvent event ) { ( ( Stateful ) event . getChild ( ) ) . addStateListener ( this ) ; } @ Override public void childRemoved ( StructuralEvent event ) { ( ( Stateful ) event . getChild ( ) ) . removeStateListener ( this ) ; } } public void testThrottleInParallel ( ) throws InterruptedException , ArooaPropertyException , ArooaConversionException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; StateSteps oddjobState = new StateSteps ( oddjob ) ; oddjobState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; oddjob . run ( ) ; oddjobState . checkNow ( ) ; oddjobState . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Structural parallel = lookup . lookup ( "" , Structural . class ) ; Capture capture = new Capture ( ) ; parallel . addStructuralListener ( capture ) ; synchronized ( capture ) { while ( capture . executing . size ( ) < ) { logger . info ( "" ) ; capture . wait ( ) ; } } ( ( Stoppable ) capture . executing . iterator ( ) . next ( ) ) . stop ( ) ; synchronized ( capture ) { while ( capture . complete . size ( ) < ) { logger . info ( "" ) ; capture . wait ( ) ; } while ( capture . executing . size ( ) < ) { logger . info ( "" ) ; capture . wait ( ) ; } } ( ( Stoppable ) capture . executing . iterator ( ) . next ( ) ) . stop ( ) ; synchronized ( capture ) { while ( capture . complete . size ( ) < ) { logger . info ( "" ) ; capture . wait ( ) ; } while ( capture . executing . size ( ) < ) { logger . info ( "" ) ; capture . wait ( ) ; } } ( ( Stoppable ) parallel ) . stop ( ) ; synchronized ( capture ) { while ( capture . complete . size ( ) < ) { logger . info ( "" ) ; capture . wait ( ) ; } } oddjobState . checkWait ( ) ; oddjob . destroy ( ) ; } public void testStopParallel ( ) throws InterruptedException , ArooaPropertyException , ArooaConversionException , FailedToStopException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; StateSteps oddjobState = new StateSteps ( oddjob ) ; oddjobState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; oddjob . run ( ) ; oddjobState . checkNow ( ) ; oddjobState . startCheck ( ParentState . ACTIVE , ParentState . READY ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Structural parallel = lookup . lookup ( "" , Structural . class ) ; Capture capture = new Capture ( ) ; parallel . addStructuralListener ( capture ) ; synchronized ( capture ) { while ( capture . executing . size ( ) < ) { logger . info ( "" ) ; capture . wait ( ) ; } } ( ( Stoppable ) parallel ) . stop ( ) ; oddjobState . checkWait ( ) ; assertEquals ( , capture . complete . size ( ) ) ; assertEquals ( , capture . ready . size ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . scheduling ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . jobs . WaitJob ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class ExecutorServiceThrottleTest extends TestCase { private static final Logger logger = Logger . getLogger ( ExecutorServiceThrottle . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } private class ExecutingCounter implements StateListener { private final List < Stateful [ ] > exceptions = new ArrayList < Stateful [ ] > ( ) ; private final List < Stateful > executing = new ArrayList < Stateful > ( ) ; @ Override public void jobStateChange ( StateEvent event ) { synchronized ( executing ) { switch ( ( JobState ) event . getState ( ) ) { case COMPLETE : executing . remove ( event . getSource ( ) ) ; break ; case READY : break ; case EXECUTING : executing . add ( event . getSource ( ) ) ; if ( executing . size ( ) > ) { exceptions . add ( executing . toArray ( new Stateful [ executing . size ( ) ] ) ) ; } break ; default : exceptions . add ( new Stateful [ ] { event . getSource ( ) } ) ; } } } } public void testQuickJobs ( ) throws InterruptedException , ExecutionException { ExecutorService executorService = Executors . newFixedThreadPool ( ) ; ExecutingCounter counter = new ExecutingCounter ( ) ; ExecutorServiceThrottle throttle = new ExecutorServiceThrottle ( executorService , ) ; FlagState [ ] jobs = new FlagState [ ] ; Future < ? > [ ] futures = new Future < ? > [ ] ; for ( int i = ; i < ; ++ i ) { jobs [ i ] = new FlagState ( ) ; jobs [ i ] . setName ( "" + i ) ; jobs [ i ] . addStateListener ( counter ) ; futures [ i ] = throttle . submit ( jobs [ i ] ) ; } for ( int i = ; i < ; ++ i ) { futures [ i ] . get ( ) ; assertEquals ( JobState . COMPLETE , jobs [ i ] . lastStateEvent ( ) . getState ( ) ) ; } assertEquals ( , counter . exceptions . size ( ) ) ; executorService . shutdown ( ) ; } public void testSlowJobs ( ) throws InterruptedException , ExecutionException , FailedToStopException { ExecutorService executorService = Executors . newFixedThreadPool ( ) ; ExecutorServiceThrottle throttle = new ExecutorServiceThrottle ( executorService , ) ; WaitJob w1 = new WaitJob ( ) ; WaitJob w2 = new WaitJob ( ) ; WaitJob w3 = new WaitJob ( ) ; WaitJob w4 = new WaitJob ( ) ; WaitJob w5 = new WaitJob ( ) ; w1 . setName ( "" ) ; w2 . setName ( "" ) ; w3 . setName ( "" ) ; w4 . setName ( "" ) ; w5 . setName ( "" ) ; StateSteps s1 = new StateSteps ( w1 ) ; StateSteps s2 = new StateSteps ( w2 ) ; StateSteps s3 = new StateSteps ( w3 ) ; StateSteps s4 = new StateSteps ( w4 ) ; StateSteps s5 = new StateSteps ( w5 ) ; s1 . startCheck ( JobState . READY , JobState . EXECUTING ) ; s2 . startCheck ( JobState . READY , JobState . EXECUTING ) ; s3 . startCheck ( JobState . READY , JobState . EXECUTING ) ; s4 . startCheck ( JobState . READY , JobState . EXECUTING ) ; s5 . startCheck ( JobState . READY , JobState . EXECUTING ) ; throttle . submit ( w1 ) ; throttle . submit ( w2 ) ; throttle . submit ( w3 ) ; throttle . submit ( w4 ) ; throttle . submit ( w5 ) ; logger . info ( "" ) ; s1 . checkWait ( ) ; s2 . checkWait ( ) ; assertEquals ( JobState . READY , w3 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , w4 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , w5 . lastStateEvent ( ) . getState ( ) ) ; w1 . stop ( ) ; logger . info ( "" ) ; s3 . checkWait ( ) ; assertEquals ( JobState . READY , w4 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , w5 . lastStateEvent ( ) . getState ( ) ) ; w3 . stop ( ) ; logger . info ( "" ) ; s4 . checkWait ( ) ; assertEquals ( JobState . READY , w5 . lastStateEvent ( ) . getState ( ) ) ; w4 . stop ( ) ; logger . info ( "" ) ; s5 . checkWait ( ) ; w2 . stop ( ) ; w5 . stop ( ) ; executorService . shutdown ( ) ; } public void testPendingJobsWhenShutdown ( ) throws InterruptedException , ExecutionException , FailedToStopException { ExecutorService executorService = Executors . newFixedThreadPool ( ) ; ExecutorServiceThrottle throttle = new ExecutorServiceThrottle ( executorService , ) ; WaitJob wait1 = new WaitJob ( ) ; WaitJob wait2 = new WaitJob ( ) ; wait1 . setName ( "" ) ; wait2 . setName ( "" ) ; StateSteps stateCheck1 = new StateSteps ( wait1 ) ; StateSteps stateCheck2 = new StateSteps ( wait2 ) ; stateCheck1 . startCheck ( JobState . READY , JobState . EXECUTING ) ; stateCheck2 . startCheck ( JobState . READY , JobState . EXECUTING ) ; Future < ? > future1 = throttle . submit ( wait1 ) ; throttle . submit ( wait2 ) ; logger . info ( "" ) ; stateCheck1 . checkWait ( ) ; executorService . shutdown ( ) ; stateCheck1 . startCheck ( JobState . EXECUTING , JobState . COMPLETE ) ; wait1 . stop ( ) ; stateCheck1 . checkWait ( ) ; future1 . get ( ) ; executorService . awaitTermination ( , TimeUnit . HOURS ) ; assertTrue ( executorService . isTerminated ( ) ) ; assertEquals ( JobState . READY , wait2 . lastStateEvent ( ) . getState ( ) ) ; } public void testCancelledWork ( ) throws InterruptedException , ExecutionException , FailedToStopException { ExecutorService executorService = Executors . newFixedThreadPool ( ) ; ExecutorServiceThrottle throttle = new ExecutorServiceThrottle ( executorService , ) ; WaitJob w1 = new WaitJob ( ) ; WaitJob w2 = new WaitJob ( ) ; w1 . setName ( "" ) ; w2 . setName ( "" ) ; StateSteps s1 = new StateSteps ( w1 ) ; StateSteps s2 = new StateSteps ( w2 ) ; s1 . startCheck ( JobState . READY , JobState . EXECUTING ) ; s2 . startCheck ( JobState . READY , JobState . EXECUTING ) ; Future < ? > f1 = throttle . submit ( w1 ) ; Future < ? > f2 = throttle . submit ( w2 ) ; logger . info ( "" ) ; s1 . checkWait ( ) ; f2 . cancel ( false ) ; s1 . startCheck ( JobState . EXECUTING , JobState . COMPLETE ) ; w1 . stop ( ) ; s1 . checkWait ( ) ; f1 . get ( ) ; assertEquals ( JobState . READY , w2 . lastStateEvent ( ) . getState ( ) ) ; executorService . shutdown ( ) ; } } package org . oddjob . scheduling ; import java . util . List ; import java . util . concurrent . Exchanger ; import java . util . concurrent . RejectedExecutionHandler ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . ScheduledThreadPoolExecutor ; import java . util . concurrent . ThreadPoolExecutor ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; public class TrackingExecutorTest extends TestCase { private static final Logger logger = Logger . getLogger ( TrackingExecutorTest . class ) ; @ Override protected void setUp ( ) { logger . debug ( "" + getName ( ) + "" ) ; } class MockRunnable implements Runnable { public void run ( ) { throw new RuntimeException ( "" ) ; } } public void testCancel ( ) throws InterruptedException { MockRunnable runnable = new MockRunnable ( ) ; ScheduledExecutorService executor = new ScheduledThreadPoolExecutor ( ) ; TrackingExecutor test = new TrackingExecutor ( executor ) ; ScheduledFuture < ? > future = test . schedule ( runnable , , TimeUnit . HOURS ) ; assertEquals ( , test . getTaskCount ( ) ) ; future . cancel ( true ) ; assertEquals ( , test . getTaskCount ( ) ) ; future . cancel ( true ) ; assertEquals ( , test . getTaskCount ( ) ) ; executor . shutdown ( ) ; executor . awaitTermination ( , TimeUnit . SECONDS ) ; assertTrue ( executor . isTerminated ( ) ) ; } class MyRunable implements Runnable { boolean ran ; public void run ( ) { ran = true ; } } public void testCancelWhenAlreadyRun ( ) throws InterruptedException { MyRunable runnable = new MyRunable ( ) ; ScheduledExecutorService executor = new ScheduledThreadPoolExecutor ( ) ; TrackingExecutor test = new TrackingExecutor ( executor ) ; ScheduledFuture < ? > future = test . schedule ( runnable , , TimeUnit . MILLISECONDS ) ; test . waitForNothingOutstanding ( ) ; future . cancel ( true ) ; future . cancel ( true ) ; executor . shutdown ( ) ; executor . awaitTermination ( , TimeUnit . SECONDS ) ; assertTrue ( executor . isTerminated ( ) ) ; } class StubbonRunnable implements Runnable { boolean interrupted ; Exchanger < Void > exchanger = new Exchanger < Void > ( ) ; public void run ( ) { try { exchanger . exchange ( null ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } try { synchronized ( this ) { wait ( ) ; } } catch ( InterruptedException e ) { interrupted = true ; logger . debug ( "" ) ; try { exchanger . exchange ( null ) ; } catch ( InterruptedException e2 ) { throw new RuntimeException ( e2 ) ; } } } } public void testLongRunningCancel ( ) throws InterruptedException { StubbonRunnable runnable = new StubbonRunnable ( ) ; ScheduledExecutorService executor = new ScheduledThreadPoolExecutor ( , new RejectedExecutionHandler ( ) { public void rejectedExecution ( Runnable r , ThreadPoolExecutor executor ) { fail ( "" ) ; } } ) ; TrackingExecutor test = new TrackingExecutor ( executor ) ; ScheduledFuture < ? > future = test . schedule ( runnable , , TimeUnit . MILLISECONDS ) ; runnable . exchanger . exchange ( null ) ; assertEquals ( , test . getTaskCount ( ) ) ; future . cancel ( true ) ; assertEquals ( , test . getTaskCount ( ) ) ; runnable . exchanger . exchange ( null ) ; assertTrue ( runnable . interrupted ) ; List < Runnable > outstanding = test . shutdownNow ( ) ; assertEquals ( , outstanding . size ( ) ) ; executor . awaitTermination ( , TimeUnit . SECONDS ) ; assertTrue ( executor . isTerminated ( ) ) ; } } package org . oddjob . scheduling ; import java . util . Collection ; import java . util . List ; import java . util . concurrent . Callable ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Future ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; public class MockExecutorService implements ExecutorService { @ Override public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public < T > List < Future < T > > invokeAll ( Collection < ? extends Callable < T > > tasks ) throws InterruptedException { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public < T > List < Future < T > > invokeAll ( Collection < ? extends Callable < T > > tasks , long timeout , TimeUnit unit ) throws InterruptedException { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public < T > T invokeAny ( Collection < ? extends Callable < T > > tasks ) throws InterruptedException , ExecutionException { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public < T > T invokeAny ( Collection < ? extends Callable < T > > tasks , long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public boolean isShutdown ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public boolean isTerminated ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void shutdown ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public List < Runnable > shutdownNow ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public < T > Future < T > submit ( Callable < T > task ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public Future < ? > submit ( Runnable task ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public < T > Future < T > submit ( Runnable task , T result ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public void execute ( Runnable command ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . scheduling ; import java . text . ParseException ; import java . util . Date ; import java . util . concurrent . Exchanger ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . mockito . Mockito ; import org . mockito . internal . matchers . CapturingMatcher ; import org . oddjob . FailedToStopException ; import org . oddjob . StateSteps ; import org . oddjob . Stoppable ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . framework . SimpleJob ; import org . oddjob . jobs . job . StopJob ; import org . oddjob . jobs . structural . SequentialJob ; import org . oddjob . schedules . Interval ; import org . oddjob . schedules . IntervalTo ; import org . oddjob . schedules . Schedule ; import org . oddjob . schedules . ScheduleContext ; import org . oddjob . schedules . ScheduleResult ; import org . oddjob . schedules . SimpleInterval ; import org . oddjob . schedules . SimpleScheduleResult ; import org . oddjob . schedules . schedules . DailySchedule ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class TimerStopTest extends TestCase { private static final Logger logger = Logger . getLogger ( TimerStopTest . class ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; } private class NeverRan extends SimpleJob { @ Override protected int execute ( ) throws Throwable { throw new RuntimeException ( "" ) ; } } public void testStopBeforeRunning ( ) throws InterruptedException , FailedToStopException { DefaultExecutors services = new DefaultExecutors ( ) ; Timer test = new Timer ( ) ; test . setScheduleExecutorService ( services . getScheduledExecutor ( ) ) ; test . setSchedule ( new Schedule ( ) { public IntervalTo nextDue ( ScheduleContext context ) { return new IntervalTo ( Interval . END_OF_TIME ) ; } } ) ; NeverRan job = new NeverRan ( ) ; test . setJob ( job ) ; test . run ( ) ; test . stop ( ) ; assertEquals ( JobState . READY , job . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; services . stop ( ) ; } private static class RunningJob extends SimpleJob implements Stoppable { Exchanger < Void > running = new Exchanger < Void > ( ) ; @ Override protected int execute ( ) throws Throwable { running . exchange ( null ) ; synchronized ( this ) { try { logger . debug ( "" ) ; wait ( ) ; } catch ( InterruptedException e ) { logger . debug ( "" ) ; } } ; return ; } @ Override protected void onStop ( ) { synchronized ( this ) { notifyAll ( ) ; } } } public void testStopWhenRunning ( ) throws InterruptedException , FailedToStopException { DefaultExecutors services = new DefaultExecutors ( ) ; Timer test = new Timer ( ) ; test . setScheduleExecutorService ( services . getScheduledExecutor ( ) ) ; test . setSchedule ( new Schedule ( ) { public IntervalTo nextDue ( ScheduleContext context ) { return new IntervalTo ( new Date ( ) ) ; } } ) ; RunningJob job = new RunningJob ( ) ; test . setJob ( job ) ; test . run ( ) ; job . running . exchange ( null ) ; test . stop ( ) ; assertFalse ( Thread . interrupted ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , job . lastStateEvent ( ) . getState ( ) ) ; services . stop ( ) ; } private static class RunOnceJob extends SimpleJob { boolean ran ; @ Override protected int execute ( ) throws Throwable { if ( ran ) { throw new Exception ( "" ) ; } return ; } } public void testStopBetweenSchedules ( ) throws InterruptedException , Throwable { DefaultExecutors services = new DefaultExecutors ( ) ; services . setPoolSize ( ) ; final Timer test = new Timer ( ) ; test . setScheduleExecutorService ( services . getScheduledExecutor ( ) ) ; test . setSchedule ( new Schedule ( ) { public IntervalTo nextDue ( ScheduleContext context ) { if ( context . getData ( "" ) == null ) { context . putData ( "" , new Object ( ) ) ; return new IntervalTo ( new Date ( ) ) ; } else { return new IntervalTo ( Interval . END_OF_TIME ) ; } } } ) ; RunOnceJob job = new RunOnceJob ( ) ; StopJob stop = new StopJob ( ) ; stop . setJob ( test ) ; Trigger trigger = new Trigger ( ) ; trigger . setExecutorService ( services . getPoolExecutor ( ) ) ; trigger . setJob ( stop ) ; trigger . setOn ( job ) ; trigger . run ( ) ; test . setJob ( job ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . READY ) ; logger . info ( "" ) ; test . run ( ) ; state . checkWait ( ) ; assertEquals ( JobState . COMPLETE , job . lastStateEvent ( ) . getState ( ) ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; logger . info ( "" ) ; test . run ( ) ; state . checkNow ( ) ; assertEquals ( new IntervalTo ( Interval . END_OF_TIME ) , test . getCurrent ( ) ) ; test . stop ( ) ; services . stop ( ) ; } @ SuppressWarnings ( { "" , "" } ) public void testStopBetweenScheduleWithSkippedRuns ( ) throws ParseException , FailedToStopException { final ScheduledFuture < ? > future = Mockito . mock ( ScheduledFuture . class ) ; ScheduledExecutorService executor = Mockito . mock ( ScheduledExecutorService . class ) ; CapturingMatcher < Runnable > runnable = new CapturingMatcher < Runnable > ( ) ; CapturingMatcher < Long > delay = new CapturingMatcher < Long > ( ) ; Mockito . when ( executor . schedule ( Mockito . argThat ( runnable ) , Mockito . longThat ( delay ) , Mockito . eq ( TimeUnit . MILLISECONDS ) ) ) . thenReturn ( ( ScheduledFuture ) future ) ; Timer test = new Timer ( ) ; test . setSchedule ( new DailySchedule ( ) ) ; test . setClock ( new ManualClock ( "" ) ) ; test . setScheduleExecutorService ( executor ) ; test . setJob ( new RunOnceJob ( ) ) ; test . setSkipMissedRuns ( true ) ; test . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; ScheduleResult expectedCurrent1 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( new Long ( ) , delay . getLastValue ( ) ) ; assertEquals ( expectedCurrent1 , test . getCurrent ( ) ) ; runnable . getLastValue ( ) . run ( ) ; ScheduleResult expectedCurrent2 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expectedCurrent2 , test . getCurrent ( ) ) ; assertEquals ( new Long ( * * * ) , delay . getLastValue ( ) ) ; test . stop ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( expectedCurrent2 , test . getCurrent ( ) ) ; assertEquals ( new Long ( * * * ) , delay . getLastValue ( ) ) ; test . stop ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . setJob ( null ) ; test . setJob ( new RunOnceJob ( ) ) ; test . setClock ( new ManualClock ( "" ) ) ; test . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; ScheduleResult expectedCurrent3 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( new Long ( ) , delay . getLastValue ( ) ) ; assertEquals ( expectedCurrent3 , test . getCurrent ( ) ) ; runnable . getLastValue ( ) . run ( ) ; ScheduleResult expectedCurrent4 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expectedCurrent4 , test . getCurrent ( ) ) ; assertEquals ( new Long ( * * * ) , delay . getLastValue ( ) ) ; test . stop ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } @ SuppressWarnings ( { "" , "" } ) public void testWhenScheduledChildGoesToReady ( ) throws ParseException , FailedToStopException , InterruptedException { final ScheduledFuture < ? > future = Mockito . mock ( ScheduledFuture . class ) ; ScheduledExecutorService executor = Mockito . mock ( ScheduledExecutorService . class ) ; CapturingMatcher < Runnable > runnable = new CapturingMatcher < Runnable > ( ) ; CapturingMatcher < Long > delay = new CapturingMatcher < Long > ( ) ; Mockito . when ( executor . schedule ( Mockito . argThat ( runnable ) , Mockito . longThat ( delay ) , Mockito . eq ( TimeUnit . MILLISECONDS ) ) ) . thenReturn ( ( ScheduledFuture ) future ) ; Timer test = new Timer ( ) ; test . setSchedule ( new DailySchedule ( ) ) ; test . setClock ( new ManualClock ( "" ) ) ; test . setScheduleExecutorService ( executor ) ; SequentialJob child = new SequentialJob ( ) ; test . setJob ( child ) ; test . run ( ) ; Mockito . verify ( executor ) . schedule ( Mockito . argThat ( runnable ) , Mockito . longThat ( delay ) , Mockito . eq ( TimeUnit . MILLISECONDS ) ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; ScheduleResult expectedCurrent1 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( new Long ( ) , delay . getLastValue ( ) ) ; assertEquals ( expectedCurrent1 , test . getCurrent ( ) ) ; runnable . getLastValue ( ) . run ( ) ; Mockito . verifyNoMoreInteractions ( executor ) ; assertEquals ( ParentState . READY , child . lastStateEvent ( ) . getState ( ) ) ; FlagState flag = new FlagState ( ) ; child . setJobs ( , flag ) ; flag . run ( ) ; assertEquals ( ParentState . COMPLETE , child . lastStateEvent ( ) . getState ( ) ) ; Mockito . verify ( executor , Mockito . times ( ) ) . schedule ( Mockito . argThat ( runnable ) , Mockito . longThat ( delay ) , Mockito . eq ( TimeUnit . MILLISECONDS ) ) ; ScheduleResult expectedCurrent2 = new SimpleScheduleResult ( new SimpleInterval ( DateHelper . parseDateTime ( "" ) , DateHelper . parseDateTime ( "" ) ) ) ; assertEquals ( expectedCurrent2 , test . getCurrent ( ) ) ; assertEquals ( new Long ( * * * ) , delay . getLastValue ( ) ) ; test . stop ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . scheduling ; import junit . framework . TestCase ; public class TimeDisplayTest extends TestCase { public void testLotsOfTimes ( ) { assertEquals ( "" , new TimeDisplay ( * * * * ) . toString ( ) ) ; assertEquals ( "" , new TimeDisplay ( ) . toString ( ) ) ; } } package org . oddjob . scheduling ; import java . util . concurrent . Callable ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . TimeUnit ; public class MockScheduledExecutorService extends MockExecutorService implements ScheduledExecutorService { @ Override public ScheduledFuture < ? > schedule ( Runnable command , long delay , TimeUnit unit ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public < V > ScheduledFuture < V > schedule ( Callable < V > callable , long delay , TimeUnit unit ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public ScheduledFuture < ? > scheduleAtFixedRate ( Runnable command , long initialDelay , long period , TimeUnit unit ) { throw new RuntimeException ( "" + getClass ( ) ) ; } @ Override public ScheduledFuture < ? > scheduleWithFixedDelay ( Runnable command , long initialDelay , long delay , TimeUnit unit ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . scheduling ; import java . util . concurrent . CancellationException ; import java . util . concurrent . Exchanger ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . Future ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . ScheduledThreadPoolExecutor ; import java . util . concurrent . TimeUnit ; import junit . framework . TestCase ; public class JavaExecutorAssumptionsTest extends TestCase { class SimpleRunnable implements Runnable { boolean ran ; public void run ( ) { ran = true ; } } public void testCancelBeforeRun ( ) throws InterruptedException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor ( ) ; SimpleRunnable runnable = new SimpleRunnable ( ) ; ScheduledFuture < ? > future = executor . schedule ( runnable , , TimeUnit . HOURS ) ; Thread . sleep ( ) ; assertTrue ( future . getDelay ( TimeUnit . MILLISECONDS ) < ( * * * ) ) ; assertEquals ( false , future . isCancelled ( ) ) ; assertEquals ( false , future . isDone ( ) ) ; future . cancel ( true ) ; assertEquals ( true , future . isCancelled ( ) ) ; assertEquals ( true , future . isDone ( ) ) ; assertEquals ( false , runnable . ran ) ; executor . shutdown ( ) ; } public void testRunBeforeCancel ( ) throws InterruptedException , ExecutionException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor ( ) ; SimpleRunnable runnable = new SimpleRunnable ( ) ; Future < ? > future = executor . schedule ( runnable , , TimeUnit . HOURS ) ; future . get ( ) ; assertEquals ( true , runnable . ran ) ; assertEquals ( false , future . isCancelled ( ) ) ; assertEquals ( true , future . isDone ( ) ) ; future . cancel ( true ) ; assertEquals ( false , future . isCancelled ( ) ) ; executor . shutdown ( ) ; } class RunUntilInerrupted implements Runnable { Exchanger < Void > exchange = new Exchanger < Void > ( ) ; boolean ran ; boolean interrupted ; public synchronized void run ( ) { ran = true ; try { exchange . exchange ( null ) ; wait ( ) ; } catch ( InterruptedException e ) { interrupted = true ; } try { exchange . exchange ( null ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } } public void testCancelInterrupted ( ) throws InterruptedException , ExecutionException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor ( ) ; RunUntilInerrupted runnable = new RunUntilInerrupted ( ) ; Future < ? > future = executor . schedule ( runnable , , TimeUnit . HOURS ) ; assertEquals ( false , future . isCancelled ( ) ) ; assertEquals ( false , future . isDone ( ) ) ; runnable . exchange . exchange ( null ) ; future . cancel ( true ) ; try { future . get ( ) ; fail ( "" ) ; } catch ( CancellationException e ) { } runnable . exchange . exchange ( null ) ; assertEquals ( true , runnable . ran ) ; assertEquals ( true , runnable . interrupted ) ; assertEquals ( true , future . isCancelled ( ) ) ; assertEquals ( true , future . isDone ( ) ) ; executor . shutdown ( ) ; } } package org . oddjob . scheduling ; import java . net . URI ; import java . net . URISyntaxException ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . deploy . BeanDescriptorHelper ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . schedules . schedules . WeeklySchedule ; public class TimerDesFaTest extends TestCase { DesignInstance design ; public void testCreate ( ) throws ArooaParseException , URISyntaxException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; ArooaSession session = new StandardArooaSession ( descriptor ) ; ArooaDescriptor sd = session . getArooaDescriptor ( ) ; InstantiationContext instantiationContext = new InstantiationContext ( ArooaType . COMPONENT , null ) ; ArooaClass arooaClass = sd . getElementMappings ( ) . mappingFor ( new ArooaElement ( new URI ( "" ) , "" ) , instantiationContext ) ; assertEquals ( SimpleArooaClass . class , arooaClass . getClass ( ) ) ; ArooaBeanDescriptor beanDescriptor = sd . getBeanDescriptor ( arooaClass , session . getTools ( ) . getPropertyAccessor ( ) ) ; assertEquals ( "" , beanDescriptor . getComponentProperty ( ) ) ; assertEquals ( ArooaType . COMPONENT , new BeanDescriptorHelper ( beanDescriptor ) . getArooaType ( "" ) ) ; DesignParser parser = new DesignParser ( session ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; Timer timer = ( Timer ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , timer . getTimeZone ( ) ) ; assertEquals ( , ( ( WeeklySchedule ) timer . getSchedule ( ) ) . getFrom ( ) . getDayNumber ( ) ) ; assertEquals ( true , timer . isHaltOnFailure ( ) ) ; assertEquals ( true , timer . isSkipMissedRuns ( ) ) ; assertEquals ( , Helper . getChildren ( timer ) . length ) ; } public static void main ( String args [ ] ) throws ArooaParseException , URISyntaxException { TimerDesFaTest test = new TimerDesFaTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . scheduling ; import java . util . concurrent . Delayed ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ScheduledFuture ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; public class MockScheduledFuture < T > implements ScheduledFuture < T > { public boolean cancel ( boolean mayInterruptIfRunning ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public T get ( ) throws InterruptedException , ExecutionException { throw new RuntimeException ( "" + getClass ( ) ) ; } public T get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { throw new RuntimeException ( "" + getClass ( ) ) ; } public boolean isCancelled ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public boolean isDone ( ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public long getDelay ( TimeUnit unit ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public int compareTo ( Delayed o ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob . scheduling ; import junit . framework . TestCase ; import org . oddjob . framework . SimpleJob ; import org . oddjob . jobs . WaitJob ; import org . oddjob . schedules . schedules . NowSchedule ; import org . oddjob . state . StateConditions ; public class TimerRetryBulkTest extends TestCase { private static final int COUNT_TO = ; private class OurJob extends SimpleJob { int count ; @ Override protected int execute ( ) throws Throwable { if ( ++ count > COUNT_TO ) { return ; } else { return ; } } } public void testTimerManyTimes ( ) { DefaultExecutors services = new DefaultExecutors ( ) ; Timer test = new Timer ( ) ; test . setSchedule ( new NowSchedule ( ) ) ; test . setHaltOnFailure ( true ) ; test . setScheduleExecutorService ( services . getScheduledExecutor ( ) ) ; OurJob job = new OurJob ( ) ; test . setJob ( job ) ; test . run ( ) ; WaitJob wait = new WaitJob ( ) ; wait . setState ( StateConditions . INCOMPLETE ) ; wait . setFor ( test ) ; wait . run ( ) ; assertEquals ( COUNT_TO + , job . count ) ; services . stop ( ) ; } private class OurOtherJob extends SimpleJob { int count ; @ Override protected int execute ( ) throws Throwable { if ( ++ count > COUNT_TO ) { return ; } else { return ; } } } public void testRetryManyTimes ( ) { DefaultExecutors services = new DefaultExecutors ( ) ; Retry test = new Retry ( ) ; test . setSchedule ( new NowSchedule ( ) ) ; test . setScheduleExecutorService ( services . getScheduledExecutor ( ) ) ; OurOtherJob job = new OurOtherJob ( ) ; test . setJob ( job ) ; test . run ( ) ; WaitJob wait = new WaitJob ( ) ; wait . setState ( StateConditions . COMPLETE ) ; wait . setFor ( test ) ; wait . run ( ) ; assertEquals ( COUNT_TO + , job . count ) ; services . stop ( ) ; } } package org . oddjob . scheduling ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . DesignInstance ; import org . oddjob . arooa . design . DesignParser ; import org . oddjob . arooa . design . view . ViewMainHelper ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class RetryDesFaTest extends TestCase { DesignInstance design ; public void testCreate ( ) throws ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; ArooaSession session = new StandardArooaSession ( descriptor ) ; DesignParser parser = new DesignParser ( session ) ; parser . setArooaType ( ArooaType . COMPONENT ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; design = parser . getDesign ( ) ; Retry test = ( Retry ) Helper . createComponentFromConfiguration ( design . getArooaContext ( ) . getConfigurationNode ( ) ) ; assertEquals ( "" , test . getTimeZone ( ) ) ; assertNotNull ( test . getSchedule ( ) ) ; assertEquals ( , Helper . getChildren ( test ) . length ) ; } public static void main ( String args [ ] ) throws ArooaParseException { RetryDesFaTest test = new RetryDesFaTest ( ) ; test . testCreate ( ) ; ViewMainHelper view = new ViewMainHelper ( test . design ) ; view . run ( ) ; } } package org . oddjob . scheduling ; import java . util . concurrent . Exchanger ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Future ; import java . util . concurrent . RejectedExecutionException ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import junit . framework . TestCase ; public class DefaultOddjobServicesTest extends TestCase { class AJob implements Runnable { int ran ; public void run ( ) { ran ++ ; } } public void testRunAndWait ( ) throws InterruptedException , ExecutionException { DefaultExecutors test = new DefaultExecutors ( ) ; ExecutorService poolExecutor = test . getPoolExecutor ( ) ; AJob job = new AJob ( ) ; Future < ? > future = poolExecutor . submit ( job ) ; assertNull ( future . get ( ) ) ; assertEquals ( , job . ran ) ; test . stop ( ) ; } class SlowJob implements Runnable { Exchanger < Thread > exchanger = new Exchanger < Thread > ( ) ; public void run ( ) { try { exchanger . exchange ( Thread . currentThread ( ) ) ; synchronized ( this ) { wait ( ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } } public void testInterruptRunningJob ( ) throws InterruptedException , ExecutionException { DefaultExecutors test = new DefaultExecutors ( ) ; test . setPoolSize ( ) ; ExecutorService poolExecutor = test . getPoolExecutor ( ) ; SlowJob job = new SlowJob ( ) ; Future < ? > future = poolExecutor . submit ( job ) ; Thread t = job . exchanger . exchange ( null ) ; t . interrupt ( ) ; assertNull ( future . get ( ) ) ; future = poolExecutor . submit ( job ) ; t = job . exchanger . exchange ( null ) ; assertFalse ( t . isInterrupted ( ) ) ; t . interrupt ( ) ; test . stop ( ) ; } class DeadJob implements Runnable { public void run ( ) { try { synchronized ( this ) { wait ( ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } } public void testStopServices ( ) throws InterruptedException , ExecutionException { DefaultExecutors test = new DefaultExecutors ( ) ; test . setPoolSize ( ) ; ExecutorService poolExecutor = test . getPoolExecutor ( ) ; DeadJob job = new DeadJob ( ) ; Future < ? > future = poolExecutor . submit ( job ) ; test . stop ( ) ; try { assertNull ( future . get ( , TimeUnit . MILLISECONDS ) ) ; assertTrue ( future . isDone ( ) ) ; assertFalse ( future . isCancelled ( ) ) ; } catch ( TimeoutException e1 ) { assertFalse ( future . isDone ( ) ) ; assertFalse ( future . isCancelled ( ) ) ; } try { future = poolExecutor . submit ( job ) ; fail ( "" ) ; } catch ( RejectedExecutionException e ) { } } } package org . oddjob . scheduling ; import java . text . ParseException ; import java . util . Date ; import org . apache . log4j . Logger ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . util . Clock ; public class ManualClock implements Clock { private static final Logger logger = Logger . getLogger ( ManualClock . class ) ; private Date date ; public ManualClock ( String time ) { setDate ( time ) ; } public ManualClock ( ) { } public void setDate ( String time ) { logger . debug ( "" + time + "" ) ; try { date = DateHelper . parseDateTime ( time ) ; } catch ( ParseException e ) { throw new RuntimeException ( e ) ; } } public Date getDate ( ) { return date ; } @ Override public String toString ( ) { return getClass ( ) . getSimpleName ( ) + "" + date ; } } package org . oddjob . scheduling ; import java . util . Date ; import java . util . concurrent . Future ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . parsing . DragPoint ; import org . oddjob . arooa . parsing . DragTransaction ; import org . oddjob . arooa . registry . ChangeHow ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . framework . SimpleJob ; import org . oddjob . jobs . SequenceJob ; import org . oddjob . jobs . WaitJob ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateConditions ; import org . oddjob . state . StateListener ; public class TriggerTest extends TestCase { private static final Logger logger = Logger . getLogger ( TriggerTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . debug ( "" + getName ( ) + "" ) ; } private class OurDependant extends SimpleJob { private StateListener listenerCheck ; private JobState state ; public OurDependant ( ) { this ( JobState . COMPLETE ) ; } public OurDependant ( JobState state ) { this . state = state ; } @ Override protected int execute ( ) throws Throwable { switch ( state ) { case COMPLETE : return ; case INCOMPLETE : return ; default : throw new RuntimeException ( "" ) ; } } @ Override public void addStateListener ( StateListener listener ) { assertNull ( listenerCheck ) ; assertNotNull ( listener ) ; this . listenerCheck = listener ; super . addStateListener ( listener ) ; } @ Override public void removeStateListener ( StateListener listener ) { assertNotNull ( listenerCheck ) ; assertEquals ( listenerCheck , listener ) ; listenerCheck = null ; super . removeStateListener ( listener ) ; } } private class OurJob extends SimpleJob { private StateListener listenerCheck ; int ran ; private JobState state = JobState . COMPLETE ; public void setState ( JobState state ) { this . state = state ; } @ Override protected int execute ( ) throws Throwable { ran ++ ; switch ( state ) { case COMPLETE : return ; case INCOMPLETE : return ; default : throw new RuntimeException ( "" ) ; } } @ Override public void addStateListener ( StateListener listener ) { assertNull ( listenerCheck ) ; assertNotNull ( listener ) ; this . listenerCheck = listener ; super . addStateListener ( listener ) ; } @ Override public void removeStateListener ( StateListener listener ) { assertNotNull ( listenerCheck ) ; assertEquals ( listenerCheck , listener ) ; listenerCheck = null ; super . removeStateListener ( listener ) ; } } public void testSimpleTrigger ( ) throws Exception { DefaultExecutors services = new DefaultExecutors ( ) ; OurJob job = new OurJob ( ) ; OurDependant dependant = new OurDependant ( ) ; Trigger test = new Trigger ( ) ; test . setOn ( dependant ) ; test . setJob ( job ) ; test . setExecutorService ( services . getPoolExecutor ( ) ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; testState . checkNow ( ) ; testState . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; logger . info ( "" ) ; dependant . run ( ) ; testState . checkWait ( ) ; assertEquals ( , job . ran ) ; testState . startCheck ( ParentState . COMPLETE , ParentState . READY ) ; job . hardReset ( ) ; testState . checkNow ( ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; assertEquals ( , job . ran ) ; testState . checkNow ( ) ; testState . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; if ( new Date ( ) . equals ( dependant . lastStateEvent ( ) . getTime ( ) ) ) { logger . info ( "" ) ; Thread . sleep ( ) ; } logger . info ( "" ) ; dependant . hardReset ( ) ; dependant . run ( ) ; testState . checkWait ( ) ; assertEquals ( , job . ran ) ; logger . info ( "" ) ; services . stop ( ) ; } public void testTriggerReflectsChildJobState ( ) throws Exception { final DefaultExecutors services = new DefaultExecutors ( ) ; OurJob job = new OurJob ( ) ; job . setState ( JobState . EXCEPTION ) ; OurDependant depends = new OurDependant ( ) ; Trigger test = new Trigger ( ) ; test . setOn ( depends ) ; test . setJob ( job ) ; test . setExecutorService ( services . getPoolExecutor ( ) ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; testState . checkNow ( ) ; testState . startCheck ( ParentState . ACTIVE , ParentState . EXCEPTION ) ; depends . run ( ) ; testState . checkWait ( ) ; job . setState ( JobState . INCOMPLETE ) ; depends . hardReset ( ) ; test . hardReset ( ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . INCOMPLETE ) ; test . run ( ) ; Thread . sleep ( ) ; depends . run ( ) ; testState . checkWait ( ) ; services . stop ( ) ; } public void testDestroyCycle ( ) throws Exception { final DefaultExecutors services = new DefaultExecutors ( ) ; OurJob job = new OurJob ( ) ; OurDependant depends = new OurDependant ( ) ; Trigger test = new Trigger ( ) ; test . setOn ( depends ) ; test . setJob ( job ) ; test . setExecutorService ( services . getPoolExecutor ( ) ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE , ParentState . COMPLETE ) ; test . run ( ) ; depends . run ( ) ; testState . checkWait ( ) ; testState . startCheck ( ParentState . COMPLETE , ParentState . READY , ParentState . DESTROYED ) ; test . setJob ( null ) ; job . destroy ( ) ; test . destroy ( ) ; depends . destroy ( ) ; testState . checkNow ( ) ; services . stop ( ) ; } public void testStopBeforeTriggered ( ) throws FailedToStopException { class NeverRun extends SimpleJob { @ Override protected int execute ( ) throws Throwable { throw new Exception ( "" ) ; } } Trigger test = new Trigger ( ) ; test . setOn ( new NeverRun ( ) ) ; test . setJob ( new NeverRun ( ) ) ; test . setExecutorService ( new MockExecutorService ( ) ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; test . run ( ) ; state . checkNow ( ) ; state . startCheck ( ParentState . ACTIVE , ParentState . READY ) ; test . stop ( ) ; state . checkNow ( ) ; } private class OurOddjobServices extends MockScheduledExecutorService { public Future < ? > submit ( Runnable runnable ) { runnable . run ( ) ; return new MockScheduledFuture < Void > ( ) ; } } ; private class SerializeSession extends MockArooaSession { Object saved ; @ Override public ComponentPool getComponentPool ( ) { return new MockComponentPool ( ) { @ Override public void configure ( Object component ) { } @ Override public void save ( Object component ) { saved = component ; } } ; } } public void testSerialize ( ) throws Exception { FlagState sample = new FlagState ( ) ; sample . setState ( JobState . COMPLETE ) ; FlagState on = new FlagState ( ) ; on . setState ( JobState . COMPLETE ) ; SerializeSession session = new SerializeSession ( ) ; Trigger test = new Trigger ( ) ; test . setArooaSession ( session ) ; test . setExecutorService ( new OurOddjobServices ( ) ) ; test . setOn ( on ) ; test . setJob ( sample ) ; test . setNewOnly ( true ) ; test . run ( ) ; on . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( test , session . saved ) ; Trigger copy = ( Trigger ) Helper . copy ( test ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; copy . setExecutorService ( new OurOddjobServices ( ) ) ; copy . setOn ( on ) ; copy . setJob ( sample ) ; copy . hardReset ( ) ; if ( new Date ( ) . equals ( copy . lastStateEvent ( ) . getTime ( ) ) ) { logger . info ( "" ) ; Thread . sleep ( ) ; } copy . run ( ) ; assertEquals ( ParentState . ACTIVE , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , sample . lastStateEvent ( ) . getState ( ) ) ; on . hardReset ( ) ; on . run ( ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . COMPLETE , sample . lastStateEvent ( ) . getState ( ) ) ; } public void testReset ( ) throws Exception { SequenceJob sequence = new SequenceJob ( ) ; sequence . setFrom ( ) ; FlagState on = new FlagState ( ) ; on . setState ( JobState . INCOMPLETE ) ; Trigger test = new Trigger ( ) ; test . setExecutorService ( new OurOddjobServices ( ) ) ; test . setOn ( on ) ; test . setJob ( sequence ) ; test . setState ( StateConditions . INCOMPLETE ) ; test . setNewOnly ( true ) ; test . run ( ) ; assertEquals ( null , sequence . getCurrent ( ) ) ; on . run ( ) ; assertEquals ( new Integer ( ) , sequence . getCurrent ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; if ( System . currentTimeMillis ( ) == test . lastStateEvent ( ) . getTime ( ) . getTime ( ) ) { Thread . sleep ( ) ; } test . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; on . hardReset ( ) ; on . run ( ) ; assertEquals ( new Integer ( ) , sequence . getCurrent ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testNoChild ( ) throws Exception { FlagState on = new FlagState ( ) ; on . setState ( JobState . INCOMPLETE ) ; Trigger test = new Trigger ( ) ; test . setExecutorService ( new OurOddjobServices ( ) ) ; test . setOn ( on ) ; test . setState ( StateConditions . INCOMPLETE ) ; test . run ( ) ; assertEquals ( ParentState . ACTIVE , test . lastStateEvent ( ) . getState ( ) ) ; on . run ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . destroy ( ) ; } public void testInOddjob ( ) throws InterruptedException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; DefaultExecutors services = new DefaultExecutors ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setOddjobExecutors ( services ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Runnable runnable = ( Runnable ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; runnable . run ( ) ; WaitJob wj = new WaitJob ( ) ; wj . setFor ( new OddjobLookup ( oddjob ) . lookup ( "" ) ) ; wj . setState ( StateConditions . COMPLETE ) ; wj . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; services . stop ( ) ; oddjob . destroy ( ) ; } public void testCuttingTriggerJob ( ) throws InterruptedException , ArooaParseException { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; DefaultExecutors services = new DefaultExecutors ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setOddjobExecutors ( services ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Object on = new OddjobLookup ( oddjob ) . lookup ( "" ) ; DragPoint drag = oddjob . provideConfigurationSession ( ) . dragPointFor ( on ) ; DragTransaction trn = drag . beginChange ( ChangeHow . FRESH ) ; drag . cut ( ) ; try { trn . commit ( ) ; } catch ( ArooaParseException e ) { trn . rollback ( ) ; throw e ; } assertEquals ( ParentState . EXCEPTION , oddjob . lastStateEvent ( ) . getState ( ) ) ; services . stop ( ) ; oddjob . destroy ( ) ; } public void testSimpleExample ( ) throws InterruptedException { Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; StateSteps states = new StateSteps ( oddjob ) ; states . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Runnable important = ( Runnable ) lookup . lookup ( "" ) ; important . run ( ) ; states . checkWait ( ) ; oddjob . destroy ( ) ; } public void testExample ( ) throws InterruptedException { DefaultExecutors services = new DefaultExecutors ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setOddjobExecutors ( services ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful test = ( Stateful ) lookup . lookup ( "" ) ; StateSteps testStates = new StateSteps ( test ) ; testStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; testStates . checkNow ( ) ; testStates . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; Runnable thing1 = ( Runnable ) lookup . lookup ( "" ) ; thing1 . run ( ) ; Runnable thing2 = ( Runnable ) lookup . lookup ( "" ) ; thing2 . run ( ) ; testStates . checkWait ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; services . stop ( ) ; oddjob . destroy ( ) ; } public void testCancelExample ( ) throws InterruptedException { DefaultExecutors services = new DefaultExecutors ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setOddjobExecutors ( services ) ; oddjob . load ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Stateful test = ( Stateful ) lookup . lookup ( "" ) ; StateSteps testStates = new StateSteps ( test ) ; testStates . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . ACTIVE ) ; oddjob . run ( ) ; assertEquals ( ParentState . ACTIVE , oddjob . lastStateEvent ( ) . getState ( ) ) ; testStates . checkNow ( ) ; testStates . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; Runnable ourJob = ( Runnable ) lookup . lookup ( "" ) ; ourJob . run ( ) ; testStates . checkWait ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Stateful triggeredJob = ( Stateful ) lookup . lookup ( "" ) ; assertEquals ( JobState . READY , triggeredJob . lastStateEvent ( ) . getState ( ) ) ; services . stop ( ) ; oddjob . destroy ( ) ; } public void testStop ( ) throws InterruptedException , FailedToStopException { DefaultExecutors services = new DefaultExecutors ( ) ; Trigger test = new Trigger ( ) ; test . setExecutorService ( services . getPoolExecutor ( ) ) ; WaitJob wait = new WaitJob ( ) ; FlagState on = new FlagState ( ) ; test . setOn ( on ) ; test . setJob ( wait ) ; StateSteps waitState = new StateSteps ( wait ) ; waitState . startCheck ( JobState . READY , JobState . EXECUTING ) ; test . run ( ) ; on . run ( ) ; waitState . checkWait ( ) ; StateSteps testState = new StateSteps ( test ) ; testState . startCheck ( ParentState . ACTIVE , ParentState . COMPLETE ) ; test . stop ( ) ; testState . checkWait ( ) ; services . stop ( ) ; } } package org . oddjob . scheduling ; import junit . framework . TestCase ; public class TimerBulkTest extends TestCase { public void testMoreWorkThanThreads ( ) { } } package org . oddjob ; import java . net . URI ; import java . net . URL ; import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . ElementMappings ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . convert . ConversionPath ; import org . oddjob . arooa . convert . DefaultConverter ; import org . oddjob . arooa . deploy . ClassPathDescriptorFactory ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . types . ValueType ; import org . oddjob . jobs . SequenceJob ; import org . oddjob . jobs . structural . JobFolder ; public class OddjobArooaDescriptorTest extends TestCase { public void testArooaXml ( ) { URL url = getClass ( ) . getClassLoader ( ) . getResource ( ClassPathDescriptorFactory . AROOA_FILE ) ; assertNotNull ( url ) ; ClassPathDescriptorFactory factory = new ClassPathDescriptorFactory ( ) ; ArooaDescriptor test = factory . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; ElementMappings definitions = test . getElementMappings ( ) ; ArooaElement [ ] elements = definitions . elementsFor ( new InstantiationContext ( ArooaType . COMPONENT , null ) ) ; assertTrue ( elements . length > ) ; } public void testLoad ( ) throws ArooaParseException , ClassNotFoundException { ArooaDescriptor test = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; ElementMappings mappings = test . getElementMappings ( ) ; ArooaElement [ ] elements = mappings . elementsFor ( new InstantiationContext ( ArooaType . COMPONENT , null ) ) ; assertTrue ( elements . length > ) ; assertEquals ( new SimpleArooaClass ( SequenceJob . class ) , mappings . mappingFor ( new ArooaElement ( "" ) , new InstantiationContext ( ArooaType . COMPONENT , null ) ) ) ; elements = mappings . elementsFor ( new InstantiationContext ( ArooaType . VALUE , null ) ) ; assertTrue ( elements . length > ) ; assertNotNull ( test . getElementMappings ( ) . mappingFor ( new ArooaElement ( "" ) , new InstantiationContext ( ArooaType . COMPONENT , null ) ) ) ; } public void testSupports ( ) throws Exception { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ArooaElement [ ] elements = session . getArooaDescriptor ( ) . getElementMappings ( ) . elementsFor ( new InstantiationContext ( ArooaType . VALUE , new SimpleArooaClass ( Object . class ) , new DefaultConverter ( ) ) ) ; Set < ArooaElement > set = new HashSet < ArooaElement > ( ) ; set . addAll ( Arrays . asList ( elements ) ) ; assertTrue ( set . contains ( new ArooaElement ( new URI ( "" ) , "" ) ) ) ; assertTrue ( set . contains ( ValueType . ELEMENT ) ) ; } public void testSupportsArooaValue ( ) throws Exception { ArooaSession session = new OddjobSessionFactory ( ) . createSession ( ) ; ArooaElement [ ] elements = session . getArooaDescriptor ( ) . getElementMappings ( ) . elementsFor ( new InstantiationContext ( ArooaType . VALUE , new SimpleArooaClass ( ArooaValue . class ) ) ) ; Set < ArooaElement > set = new HashSet < ArooaElement > ( ) ; set . addAll ( Arrays . asList ( elements ) ) ; assertTrue ( set . contains ( new ArooaElement ( "" ) ) ) ; assertTrue ( set . contains ( ValueType . ELEMENT ) ) ; } public void testArooaBeanDescriptor ( ) { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; ArooaSession session = new StandardArooaSession ( descriptor ) ; ArooaClass arooaClass = new SimpleArooaClass ( JobFolder . class ) ; ArooaBeanDescriptor beanDescriptor = session . getArooaDescriptor ( ) . getBeanDescriptor ( arooaClass , session . getTools ( ) . getPropertyAccessor ( ) ) ; assertEquals ( "" , beanDescriptor . getComponentProperty ( ) ) ; } public void testSomeConversions ( ) { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; ArooaSession session = new StandardArooaSession ( descriptor ) ; ArooaConverter converter = session . getTools ( ) . getArooaConverter ( ) ; ConversionPath < Long , ArooaValue > path = converter . findConversion ( Long . class , ArooaValue . class ) ; assertEquals ( "" , path . toString ( ) ) ; } } package org . oddjob . images ; import java . util . ArrayList ; import java . util . List ; import javax . swing . ImageIcon ; import junit . framework . TestCase ; import org . oddjob . Iconic ; public class IconHelperTest extends TestCase { class OurListener implements IconListener { List < IconEvent > events = new ArrayList < IconEvent > ( ) ; @ Override public void iconEvent ( IconEvent e ) { events . add ( e ) ; } } class OurIconic implements Iconic { @ Override public void addIconListener ( IconListener listener ) { } @ Override public void removeIconListener ( IconListener listener ) { } @ Override public ImageIcon iconForId ( String id ) { throw new RuntimeException ( ) ; } } public void testSameIdNotFired ( ) { IconHelper test = new IconHelper ( new OurIconic ( ) ) ; OurListener listener = new OurListener ( ) ; test . addIconListener ( listener ) ; assertEquals ( "" , listener . events . get ( ) . getIconId ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; test . changeIcon ( "" ) ; assertEquals ( "" , listener . events . get ( ) . getIconId ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; test . changeIcon ( "" ) ; assertEquals ( "" , listener . events . get ( ) . getIconId ( ) ) ; assertEquals ( , listener . events . size ( ) ) ; } } package org . oddjob ; import org . oddjob . structural . StructuralListener ; public class MockStructural implements Structural { public void addStructuralListener ( StructuralListener listener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } public void removeStructuralListener ( StructuralListener listener ) { throw new RuntimeException ( "" + getClass ( ) ) ; } } package org . oddjob ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . design . designer . ArooaDesigner ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . standard . StandardArooaSession ; public class ArooaDesignerMain { public void testRun ( ) throws ArooaParseException { ArooaDesigner designer = new ArooaDesigner ( ) ; ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; final ArooaSession session = new StandardArooaSession ( descriptor ) ; designer . setArooaSession ( session ) ; designer . setDocumentElement ( new ArooaElement ( "" ) ) ; designer . setArooaType ( ArooaType . COMPONENT ) ; designer . run ( ) ; } public static void main ( String [ ] args ) throws ArooaParseException { new ArooaDesignerMain ( ) . testRun ( ) ; } } package org . oddjob ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConverter ; import org . oddjob . arooa . standard . StandardArooaSession ; public class ConverterHelper { public ArooaConverter getConverter ( ) { ArooaDescriptor descriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( null ) ; ArooaSession session = new StandardArooaSession ( descriptor ) ; return session . getTools ( ) . getArooaConverter ( ) ; } } package org . oddjob . oddballs ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . OurDirs ; import org . oddjob . jobs . ExecJob ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; public class OddballsLaunchTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddballsLaunchTest . class ) ; final static String RUN_JAR = "" ; final static String EOL = System . getProperty ( "" ) ; @ Override protected void setUp ( ) throws Exception { logger . info ( "" + getName ( ) + "" ) ; File built = new File ( new OurDirs ( ) . base ( ) , RUN_JAR ) ; assertTrue ( built . exists ( ) ) ; } class Console implements LogListener { List < String > lines = new ArrayList < String > ( ) ; public void logEvent ( LogEvent logEvent ) { lines . add ( logEvent . getMessage ( ) ) ; } } public void testOddjobFailsNoFile ( ) throws InterruptedException { Console console = new Console ( ) ; OurDirs dirs = new OurDirs ( ) ; ExecJob exec = new ExecJob ( ) ; exec . setCommand ( "" + dirs . relative ( RUN_JAR ) . getPath ( ) + "" + "" + dirs . relative ( "" ) . getPath ( ) + "" + "" + dirs . relative ( "" ) + "" ) ; exec . consoleLog ( ) . addListener ( console , LogLevel . INFO , - , ) ; exec . run ( ) ; dump ( console . lines ) ; assertEquals ( "" + EOL , console . lines . get ( ) ) ; assertEquals ( "" + EOL , console . lines . get ( ) ) ; exec . destroy ( ) ; } void dump ( List < String > lines ) { System . out . println ( "" ) ; for ( String line : lines ) { System . out . print ( line ) ; } System . out . println ( "" ) ; } } package org . oddjob . oddballs ; import java . io . File ; import java . net . URL ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Oddjob ; import org . oddjob . OddjobDescriptorFactory ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . deploy . LinkedDescriptor ; import org . oddjob . arooa . standard . StandardArooaDescriptor ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class OddballsDescriptorFactoryTest extends TestCase { private static final Logger logger = Logger . getLogger ( OddballsDescriptorFactoryTest . class ) ; public void testOddballs ( ) throws ArooaParseException { new BuildOddballs ( ) . run ( ) ; OurDirs dirs = new OurDirs ( ) ; OddballsDirDescriptorFactory test = new OddballsDirDescriptorFactory ( ) ; test . setOddballFactory ( new DirectoryOddball ( ) ) ; test . setBaseDir ( new File ( dirs . base ( ) , "" ) ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setDescriptorFactory ( test ) ; oddjob . setFile ( new File ( dirs . base ( ) , "" ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testOddballsExample ( ) throws ArooaParseException { new BuildOddballs ( ) . run ( ) ; OurDirs dirs = new OurDirs ( ) ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , getClass ( ) . getClassLoader ( ) ) ) ; oddjob . setArgs ( new String [ ] { dirs . base ( ) . getAbsolutePath ( ) } ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . destroy ( ) ; } public void testClassResolverResources ( ) { new BuildOddballs ( ) . run ( ) ; OurDirs dirs = new OurDirs ( ) ; OddballsDirDescriptorFactory test = new OddballsDirDescriptorFactory ( ) ; test . setOddballFactory ( new DirectoryOddball ( ) ) ; test . setBaseDir ( new File ( dirs . base ( ) , "" ) ) ; ArooaDescriptor descriptor = test . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; URL [ ] urls = descriptor . getClassResolver ( ) . getResources ( "" ) ; assertEquals ( , urls . length ) ; assertTrue ( urls [ ] . toExternalForm ( ) . contains ( "" ) ) ; assertTrue ( urls [ ] . toExternalForm ( ) . contains ( "" ) ) ; } public void testClassResolverClassLoaders ( ) { new BuildOddballs ( ) . run ( ) ; OurDirs dirs = new OurDirs ( ) ; OddballsDirDescriptorFactory test = new OddballsDirDescriptorFactory ( ) ; test . setOddballFactory ( new DirectoryOddball ( ) ) ; test . setBaseDir ( new File ( dirs . base ( ) , "" ) ) ; ArooaDescriptor descriptor = test . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; ArooaDescriptor mainDescriptor = new OddjobDescriptorFactory ( ) . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; ArooaDescriptor oddjobDescriptor = new LinkedDescriptor ( mainDescriptor , new StandardArooaDescriptor ( ) ) ; descriptor = new LinkedDescriptor ( descriptor , oddjobDescriptor ) ; ClassLoader [ ] classLoaders = descriptor . getClassResolver ( ) . getClassLoaders ( ) ; assertEquals ( , classLoaders . length ) ; logger . info ( "" + classLoaders [ ] . toString ( ) ) ; logger . info ( "" + classLoaders [ ] . toString ( ) ) ; logger . info ( "" + classLoaders [ ] . toString ( ) ) ; assertTrue ( classLoaders [ ] . toString ( ) . contains ( "" ) ) ; assertTrue ( classLoaders [ ] . toString ( ) . contains ( "" ) ) ; } public void testNoOddballs ( ) { OddballsDirDescriptorFactory test = new OddballsDirDescriptorFactory ( ) ; test . setBaseDir ( new File ( "" ) ) ; ArooaDescriptor descriptor = test . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; assertNull ( descriptor ) ; } } package org . oddjob . oddballs ; import java . io . File ; import java . net . URI ; import java . net . URISyntaxException ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . ElementMappings ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . reflect . ArooaClass ; public class DirectoryOddballTest extends TestCase { @ Override protected void setUp ( ) throws Exception { new BuildOddballs ( ) . run ( ) ; } public void testCreate ( ) throws URISyntaxException , ClassNotFoundException { DirectoryOddball test = new DirectoryOddball ( ) ; OurDirs dirs = new OurDirs ( ) ; Oddball result = test . createFrom ( new File ( dirs . base ( ) , "" ) , getClass ( ) . getClassLoader ( ) ) ; ArooaDescriptor descriptor = result . getArooaDescriptor ( ) ; assertNotNull ( descriptor ) ; InstantiationContext instantiationContext = new InstantiationContext ( ArooaType . COMPONENT , null ) ; ElementMappings mappings = descriptor . getElementMappings ( ) ; assertNotNull ( mappings ) ; ArooaClass appleClass = mappings . mappingFor ( new ArooaElement ( new URI ( "" ) , "" ) , instantiationContext ) ; assertEquals ( "" , ( ( SimpleArooaClass ) appleClass ) . forClass ( ) . getName ( ) ) ; ClassLoader loader = result . getClassLoader ( ) ; assertNotNull ( loader . loadClass ( "" ) ) ; } } package org . oddjob . oddballs ; import java . io . File ; import java . net . URI ; import java . net . URISyntaxException ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaType ; import org . oddjob . arooa . life . InstantiationContext ; import org . oddjob . arooa . life . SimpleArooaClass ; import org . oddjob . arooa . parsing . ArooaElement ; import org . oddjob . arooa . reflect . ArooaClass ; public class OddballDescriptorFactoryTest extends TestCase { @ Override protected void setUp ( ) throws Exception { new BuildOddballs ( ) . run ( ) ; } public void testCreate ( ) throws URISyntaxException { OurDirs dirs = new OurDirs ( ) ; OddballsDescriptorFactory test = new OddballsDescriptorFactory ( ) ; test . setFiles ( new File [ ] { new File ( dirs . base ( ) , "" ) } ) ; ArooaDescriptor descriptor = test . createDescriptor ( getClass ( ) . getClassLoader ( ) ) ; InstantiationContext instantiationContext = new InstantiationContext ( ArooaType . COMPONENT , null ) ; ArooaClass appleClass = descriptor . getElementMappings ( ) . mappingFor ( new ArooaElement ( new URI ( "" ) , "" ) , instantiationContext ) ; assertEquals ( "" , ( ( SimpleArooaClass ) appleClass ) . forClass ( ) . getName ( ) ) ; } } package org . oddjob . oddballs ; import java . io . File ; import java . io . IOException ; import java . net . URL ; import java . util . Arrays ; import java . util . HashSet ; import org . oddjob . OurDirs ; import junit . framework . TestCase ; public class DirectoryOddball2Test extends TestCase { public void testURLs ( ) throws IOException { DirectoryOddball test = new DirectoryOddball ( ) ; OurDirs dirs = new OurDirs ( ) ; URL [ ] urls = test . classpathURLs ( dirs . base ( ) ) ; HashSet < URL > set = new HashSet < URL > ( ) ; set . addAll ( Arrays . asList ( urls ) ) ; assertTrue ( set . contains ( new File ( dirs . base ( ) , "" ) . getCanonicalFile ( ) . toURI ( ) . toURL ( ) ) ) ; } } package org . oddjob . oddballs ; import java . io . File ; import org . apache . log4j . Logger ; import org . oddjob . OurDirs ; import org . oddjob . io . CopyJob ; import org . oddjob . io . FilesType ; import org . oddjob . tools . CompileJob ; public class BuildOddballs implements Runnable { private static final Logger logger = Logger . getLogger ( BuildOddballs . class ) ; public void run ( ) { build ( "" ) ; build ( "" ) ; } public void build ( String oddball ) { final OurDirs dirs = new OurDirs ( ) ; File classesDir = new File ( dirs . base ( ) , "" + oddball + "" ) ; File srcDir = new File ( dirs . base ( ) , "" + oddball + "" ) ; if ( classesDir . exists ( ) ) { logger . debug ( "" + classesDir + "" ) ; return ; } else { logger . debug ( "" + classesDir ) ; classesDir . mkdir ( ) ; } CopyJob copy = new CopyJob ( ) ; copy . setFrom ( new File [ ] { new File ( srcDir , "" ) } ) ; copy . setTo ( classesDir ) ; copy . run ( ) ; FilesType sources = new FilesType ( ) ; sources . setFiles ( dirs . relative ( "" + oddball + "" ) . getPath ( ) + File . separator + "" ) ; CompileJob compile = new CompileJob ( ) ; compile . setDest ( classesDir ) ; compile . setFiles ( sources . toFiles ( ) ) ; compile . run ( ) ; if ( compile . getResult ( ) != ) { throw new RuntimeException ( "" ) ; } } } package org . oddjob . framework ; import java . io . IOException ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import java . util . concurrent . atomic . AtomicBoolean ; import java . util . concurrent . atomic . AtomicReference ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . StateSteps ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaConfigurationException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeListener ; import org . oddjob . jobs . job . StopJob ; import org . oddjob . state . FlagState ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateOperator ; import org . oddjob . state . WorstStateOp ; public class StructuralJobTest extends TestCase { private static final Logger logger = Logger . getLogger ( StructuralJobTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } private static class OurStructural extends StructuralJob < Runnable > { private static final long serialVersionUID = ; transient Runnable runnable ; @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } void setJob ( Runnable c ) { childHelper . insertChild ( , c ) ; } protected void execute ( ) { if ( runnable != null ) { runnable . run ( ) ; } } } public void testRunComplete ( ) { final FlagState child = new FlagState ( JobState . COMPLETE ) ; final OurStructural test = new OurStructural ( ) ; test . setJob ( child ) ; test . runnable = new Runnable ( ) { public void run ( ) { child . run ( ) ; assertEquals ( ParentState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; } } ; test . onInitialised ( ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( JobState . READY , child . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testRunInComplete ( ) { final FlagState child = new FlagState ( JobState . INCOMPLETE ) ; final OurStructural test = new OurStructural ( ) ; test . setJob ( child ) ; test . runnable = new Runnable ( ) { public void run ( ) { child . run ( ) ; assertEquals ( ParentState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; } } ; test . onInitialised ( ) ; test . run ( ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; child . setState ( JobState . COMPLETE ) ; child . softReset ( ) ; child . run ( ) ; assertEquals ( JobState . COMPLETE , child . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . hardReset ( ) ; assertEquals ( JobState . READY , child . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; } public void testRunStop ( ) throws FailedToStopException , InterruptedException , ExecutionException , TimeoutException { final FlagState child = new FlagState ( JobState . INCOMPLETE ) ; final OurStructural test = new OurStructural ( ) ; test . setJob ( child ) ; final ExecutorService executor = Executors . newSingleThreadExecutor ( ) ; final StopJob stop = new StopJob ( ) ; stop . setJob ( test ) ; final AtomicReference < Future < ? > > future = new AtomicReference < Future < ? > > ( ) ; test . runnable = new Runnable ( ) { public void run ( ) { child . run ( ) ; assertEquals ( ParentState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; future . set ( executor . submit ( stop ) ) ; } } ; test . run ( ) ; future . get ( ) . get ( , TimeUnit . SECONDS ) ; assertEquals ( JobState . COMPLETE , stop . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . INCOMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; test . softReset ( ) ; stop . hardReset ( ) ; assertEquals ( JobState . READY , child . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; child . setState ( JobState . COMPLETE ) ; test . run ( ) ; future . get ( ) . get ( , TimeUnit . SECONDS ) ; assertEquals ( JobState . COMPLETE , child . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; executor . shutdown ( ) ; } public void testJustChild ( ) { final FlagState child = new FlagState ( JobState . INCOMPLETE ) ; child . run ( ) ; final OurStructural test = new OurStructural ( ) ; test . setJob ( child ) ; test . runnable = child ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . softReset ( ) ; assertEquals ( JobState . READY , child . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test . lastStateEvent ( ) . getState ( ) ) ; child . setState ( JobState . COMPLETE ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , child . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } public void testPersist ( ) throws IOException , ClassNotFoundException { FlagState child = new FlagState ( JobState . COMPLETE ) ; OurStructural test = new OurStructural ( ) ; test . setJob ( child ) ; test . run ( ) ; child . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; OurStructural copy = ( OurStructural ) Helper . copy ( test ) ; assertEquals ( ParentState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; } class OurSession extends MockArooaSession { OurStructural saved ; @ Override public ComponentPool getComponentPool ( ) { return new MockComponentPool ( ) { @ Override public void configure ( Object component ) { } @ Override public void save ( Object component ) { if ( component instanceof OurStructural ) { try { saved = ( OurStructural ) Helper . copy ( component ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } else { throw new RuntimeException ( "" ) ; } } } ; } } public void testRunCompletePersist ( ) { OurSession session = new OurSession ( ) ; final FlagState child = new FlagState ( JobState . COMPLETE ) ; final OurStructural test = new OurStructural ( ) ; test . setArooaSession ( session ) ; test . setJob ( child ) ; test . runnable = new Runnable ( ) { public void run ( ) { child . run ( ) ; assertEquals ( ParentState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; } } ; test . onInitialised ( ) ; test . run ( ) ; assertEquals ( ParentState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; OurStructural test2 = session . saved ; final FlagState child2 = new FlagState ( JobState . COMPLETE ) ; test2 . setArooaSession ( session ) ; test2 . setJob ( child2 ) ; test2 . runnable = new Runnable ( ) { public void run ( ) { child2 . run ( ) ; assertEquals ( ParentState . EXECUTING , test . lastStateEvent ( ) . getState ( ) ) ; } } ; test2 . onInitialised ( ) ; assertEquals ( ParentState . COMPLETE , test2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( JobState . READY , child2 . lastStateEvent ( ) . getState ( ) ) ; test2 . hardReset ( ) ; assertEquals ( JobState . READY , child2 . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ParentState . READY , test2 . lastStateEvent ( ) . getState ( ) ) ; } private class OurContext extends MockArooaContext { RuntimeListener listener ; @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void addRuntimeListener ( RuntimeListener listener ) { assertNull ( OurContext . this . listener ) ; assertNotNull ( listener ) ; OurContext . this . listener = listener ; } @ Override public void removeRuntimeListener ( RuntimeListener listener ) { super . removeRuntimeListener ( listener ) ; } } ; } @ Override public ArooaSession getSession ( ) { return new MockArooaSession ( ) ; } } private class SimpleStructural extends StructuralJob < Runnable > { private static final long serialVersionUID = ; void setChild ( Runnable child ) { if ( child == null ) { childHelper . removeChildAt ( ) ; } else { childHelper . insertChild ( , child ) ; } } @ Override protected void execute ( ) throws Throwable { childHelper . getChild ( ) . run ( ) ; } @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } } public void testChildDestroyed ( ) throws FailedToStopException { SimpleJob component = new SimpleJob ( ) { @ Override protected int execute ( ) throws Throwable { return ; } @ Override protected void save ( ) throws ComponentPersistException { } @ Override protected void configure ( ) throws ArooaConfigurationException { } } ; OurContext childContext = new OurContext ( ) ; component . setArooaContext ( childContext ) ; final SimpleStructural test = new SimpleStructural ( ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE , ParentState . READY ) ; test . setChild ( component ) ; test . run ( ) ; childContext . listener . beforeDestroy ( null ) ; test . setChild ( null ) ; childContext . listener . afterDestroy ( null ) ; state . checkNow ( ) ; } public void testBothDestroyed ( ) throws FailedToStopException { SimpleJob component = new SimpleJob ( ) { @ Override protected int execute ( ) throws Throwable { return ; } @ Override protected void save ( ) throws ComponentPersistException { } @ Override protected void configure ( ) throws ArooaConfigurationException { } } ; OurContext childContext = new OurContext ( ) ; component . setArooaContext ( childContext ) ; final SimpleStructural test = new SimpleStructural ( ) { private static final long serialVersionUID = ; @ Override protected void save ( ) throws ComponentPersistException { } protected void configure ( ) { } } ; OurContext structuralContext = new OurContext ( ) ; test . setArooaContext ( structuralContext ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( ParentState . READY , ParentState . EXECUTING , ParentState . COMPLETE ) ; test . setChild ( component ) ; test . run ( ) ; state . checkNow ( ) ; state . startCheck ( ParentState . COMPLETE , ParentState . DESTROYED ) ; structuralContext . listener . beforeDestroy ( null ) ; childContext . listener . beforeDestroy ( null ) ; test . setChild ( null ) ; childContext . listener . afterDestroy ( null ) ; structuralContext . listener . afterDestroy ( null ) ; state . checkNow ( ) ; } private class AnyStructural extends StructuralJob < Object > { private static final long serialVersionUID = ; void setChild ( Object child ) { childHelper . insertChild ( , child ) ; } @ Override protected void execute ( ) throws Throwable { } @ Override protected StateOperator getStateOp ( ) { return new WorstStateOp ( ) ; } } public void testChildStopped ( ) throws FailedToStopException { final AtomicBoolean stopped = new AtomicBoolean ( ) ; Object component = new Stoppable ( ) { @ Override public void stop ( ) throws FailedToStopException { stopped . set ( true ) ; } } ; AnyStructural test = new AnyStructural ( ) ; StateSteps check = new StateSteps ( test ) ; check . startCheck ( ParentState . READY ) ; test . setChild ( component ) ; test . stop ( ) ; assertEquals ( true , stopped . get ( ) ) ; check . checkNow ( ) ; } } package org . oddjob . framework ; import java . io . IOException ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . Helper ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . images . IconEvent ; import org . oddjob . images . IconHelper ; import org . oddjob . images . IconListener ; import org . oddjob . state . JobState ; public class SerializableJobTest extends TestCase { class OurSession extends MockArooaSession { int count ; @ Override public ComponentPool getComponentPool ( ) { return new MockComponentPool ( ) { @ Override public void save ( Object component ) { ++ count ; } @ Override public void configure ( Object component ) { } } ; } } static class OurJob extends SerializableJob { private static final long serialVersionUID = ; @ Override protected int execute ( ) throws Throwable { return ; } } public void testSaveOnChangeState ( ) { OurSession session = new OurSession ( ) ; OurJob test = new OurJob ( ) ; test . setArooaSession ( session ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( , session . count ) ; test . hardReset ( ) ; assertEquals ( , session . count ) ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . run ( ) ; assertEquals ( , session . count ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } class IconCatcher implements IconListener { String iconId ; public void iconEvent ( IconEvent e ) { iconId = e . getIconId ( ) ; } } public void testSerialization ( ) throws IOException , ClassNotFoundException { OurJob test = new OurJob ( ) ; test . run ( ) ; OurJob copy = Helper . copy ( test ) ; assertEquals ( JobState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; IconCatcher icon = new IconCatcher ( ) ; copy . addIconListener ( icon ) ; assertEquals ( IconHelper . COMPLETE , icon . iconId ) ; } static class OurStopJob extends SerializableJob { private static final long serialVersionUID = ; @ Override protected int execute ( ) { if ( stop ) { return ; } new Thread ( ) { public void run ( ) { try { OurStopJob . this . stop ( ) ; } catch ( FailedToStopException e ) { e . printStackTrace ( ) ; } } ; } . start ( ) ; while ( ! stop ) { try { synchronized ( this ) { wait ( ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } return ; } } public void testStopAndReset ( ) throws IOException , ClassNotFoundException { OurStopJob test = new OurStopJob ( ) ; test . run ( ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; OurStopJob copy = Helper . copy ( test ) ; assertEquals ( JobState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; copy . hardReset ( ) ; assertEquals ( JobState . READY , copy . lastStateEvent ( ) . getState ( ) ) ; copy . run ( ) ; assertEquals ( JobState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; copy . hardReset ( ) ; assertEquals ( JobState . READY , copy . lastStateEvent ( ) . getState ( ) ) ; copy . run ( ) ; assertEquals ( JobState . COMPLETE , copy . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . framework ; import java . io . File ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLClassLoader ; import junit . framework . TestCase ; import org . oddjob . OurDirs ; import org . oddjob . util . URLClassLoaderTypeTest ; public class ContextClassLoadersTest extends TestCase { public void testSimple ( ) throws ClassNotFoundException , MalformedURLException , InstantiationException , IllegalAccessException { OurDirs dirs = new OurDirs ( ) ; ClassLoader existing = Thread . currentThread ( ) . getContextClassLoader ( ) ; File check = dirs . relative ( "" ) ; if ( ! check . exists ( ) ) { URLClassLoaderTypeTest . compileSample ( dirs ) ; } URLClassLoader classLoader = new URLClassLoader ( new URL [ ] { dirs . relative ( "" ) . toURI ( ) . toURL ( ) } ) ; Object comp = Class . forName ( "" , true , classLoader ) . newInstance ( ) ; ContextClassloaders . push ( comp ) ; assertEquals ( classLoader , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; ContextClassloaders . pop ( ) ; assertEquals ( existing , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; } } package org . oddjob . framework ; import java . util . concurrent . BrokenBarrierException ; import java . util . concurrent . CyclicBarrier ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . state . JobState ; public class RunnableWrapperStopTest extends TestCase { private final class WaitingJob implements Runnable { CyclicBarrier barrier = new CyclicBarrier ( ) ; @ Override public void run ( ) { try { barrier . await ( ) ; } catch ( InterruptedException e1 ) { throw new RuntimeException ( e1 ) ; } catch ( BrokenBarrierException e1 ) { throw new RuntimeException ( e1 ) ; } synchronized ( this ) { try { wait ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } } } public void testStopViaInterrupt ( ) throws InterruptedException , BrokenBarrierException { WaitingJob job = new WaitingJob ( ) ; Runnable proxy = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) job , getClass ( ) . getClassLoader ( ) ) ; Thread t = new Thread ( proxy ) ; t . start ( ) ; job . barrier . await ( ) ; t . interrupt ( ) ; t . join ( ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( proxy ) ) ; } } package org . oddjob . framework ; import java . util . Collections ; import java . util . HashSet ; import java . util . Set ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . FailedToStopException ; import org . oddjob . Stateful ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . JobState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateListener ; import org . oddjob . util . OddjobLockedException ; public class StopWaitTest extends TestCase { private static final Logger logger = Logger . getLogger ( StopWaitTest . class ) ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; logger . info ( "" + getName ( ) + "" ) ; } private class OurStateful implements Stateful { JobStateHandler jobStateHandler = new JobStateHandler ( this ) ; Set < StateListener > listeners = Collections . synchronizedSet ( new HashSet < StateListener > ( ) ) ; @ Override public void addStateListener ( StateListener listener ) { jobStateHandler . addStateListener ( listener ) ; listeners . add ( listener ) ; } @ Override public StateEvent lastStateEvent ( ) { return jobStateHandler . lastStateEvent ( ) ; } @ Override public void removeStateListener ( StateListener listener ) { jobStateHandler . removeStateListener ( listener ) ; listeners . remove ( listener ) ; } } public void testStopWaitOnReady ( ) throws FailedToStopException { OurStateful stateful = new OurStateful ( ) ; new StopWait ( stateful ) . run ( ) ; assertEquals ( , stateful . listeners . size ( ) ) ; } public void testFailedTostop ( ) throws OddjobLockedException { final OurStateful stateful = new OurStateful ( ) ; stateful . jobStateHandler . tryToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateful . jobStateHandler . setState ( JobState . EXECUTING ) ; stateful . jobStateHandler . fireEvent ( ) ; } } ) ; try { new StopWait ( stateful , ) . run ( ) ; fail ( "" ) ; } catch ( FailedToStopException e ) { } assertEquals ( , stateful . listeners . size ( ) ) ; } public void testSlowToStop ( ) throws OddjobLockedException , FailedToStopException { final OurStateful stateful = new OurStateful ( ) ; stateful . jobStateHandler . tryToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { stateful . jobStateHandler . setState ( JobState . EXECUTING ) ; stateful . jobStateHandler . fireEvent ( ) ; } } ) ; Thread t = new Thread ( new Runnable ( ) { @ Override public void run ( ) { while ( stateful . listeners . isEmpty ( ) ) { logger . info ( "" ) ; try { Thread . sleep ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "" ) ; } } try { logger . info ( "" ) ; stateful . jobStateHandler . tryToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { stateful . jobStateHandler . setState ( JobState . COMPLETE ) ; stateful . jobStateHandler . fireEvent ( ) ; } } ) ; logger . info ( "" ) ; } catch ( OddjobLockedException e ) { throw new RuntimeException ( "" ) ; } } } ) ; t . start ( ) ; new StopWait ( stateful ) . run ( ) ; assertEquals ( , stateful . listeners . size ( ) ) ; } } package org . oddjob . framework ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateHandler ; public class BaseWrapperTest extends TestCase { public static class Result { public int getResult ( ) { return ; } } private class MockWrapper extends BaseWrapper { JobStateHandler stateHandler = new JobStateHandler ( this ) ; Object wrapped ; MockWrapper ( Object wrapped ) { this . wrapped = wrapped ; } @ Override protected StateHandler < ? > stateHandler ( ) { return stateHandler ; } public Object getWrapped ( ) { return wrapped ; } protected Object getProxy ( ) { return null ; } protected DynaBean getDynaBean ( ) { return new WrapDynaBean ( wrapped ) ; } public void run ( ) { } @ Override public boolean softReset ( ) { throw new RuntimeException ( "" ) ; } @ Override public boolean hardReset ( ) { throw new RuntimeException ( "" ) ; } @ Override protected void fireDestroyedState ( ) { throw new RuntimeException ( "" ) ; } } public void testWithResult ( ) throws ArooaPropertyException , ArooaConversionException { MockWrapper test = new MockWrapper ( new Result ( ) ) ; test . setArooaSession ( new StandardArooaSession ( ) ) ; assertEquals ( , test . getResult ( null ) ) ; } public void testNoResult ( ) throws ArooaPropertyException , ArooaConversionException { MockWrapper test = new MockWrapper ( new Object ( ) ) ; assertEquals ( , test . getResult ( null ) ) ; } public static class MockBean { public String getReadable ( ) { return "" ; } public void setWritable ( String writable ) { } public String getBoth ( ) { return "" ; } public void setBoth ( String both ) { } } public void testDescribe ( ) { ArooaSession session = new StandardArooaSession ( ) ; MockWrapper test = new MockWrapper ( new MockBean ( ) ) ; test . setArooaSession ( session ) ; Map < String , String > properties = new UniversalDescriber ( session ) . describe ( test ) ; assertEquals ( "" , "" , properties . get ( "" ) ) ; assertEquals ( "" , "" , properties . get ( "" ) ) ; assertEquals ( "" , null , properties . get ( "" ) ) ; } } package org . oddjob . framework ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaProperty ; public class WrapDynaClassTest extends TestCase { public static class MyBean { public String getSimple ( ) { return null ; } public String getMapped ( String foo ) { return null ; } public String [ ] getIndexed ( ) { return null ; } public boolean isOk ( ) { return true ; } } public void testProperties ( ) { WrapDynaClass test = WrapDynaClass . createDynaClass ( MyBean . class ) ; DynaProperty result ; result = test . getDynaProperty ( "" ) ; assertNotNull ( "" , result ) ; assertEquals ( "" , String . class , result . getType ( ) ) ; result = test . getDynaProperty ( "" ) ; assertNotNull ( "" , result ) ; assertTrue ( "" , result . isIndexed ( ) ) ; result = test . getDynaProperty ( "" ) ; assertNotNull ( "" , result ) ; assertTrue ( "" , result . isMapped ( ) ) ; result = test . getDynaProperty ( "" ) ; assertNotNull ( "" , result ) ; } public static class MixedTypes { public String getStuff ( String key ) { return "" ; } public void setStuff ( String key ) { } } public void testMixedTypes ( ) { WrapDynaClass test = WrapDynaClass . createDynaClass ( MixedTypes . class ) ; DynaProperty result ; result = test . getDynaProperty ( "" ) ; assertNull ( result ) ; } public void testSerialize ( ) throws Exception { WrapDynaClass test = WrapDynaClass . createDynaClass ( MyBean . class ) ; ByteArrayOutputStream bytes = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( bytes ) ; oos . writeObject ( test ) ; oos . close ( ) ; ObjectInputStream ois = new ObjectInputStream ( new ByteArrayInputStream ( bytes . toByteArray ( ) ) ) ; Object o = ois . readObject ( ) ; WrapDynaClass clone = ( WrapDynaClass ) o ; assertEquals ( test . getDynaProperties ( ) . length , clone . getDynaProperties ( ) . length ) ; } } package org . oddjob . framework ; import java . util . ArrayList ; import java . util . List ; import javax . inject . Inject ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . IconSteps ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . StateSteps ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . images . IconHelper ; import org . oddjob . state . JobState ; public class SimpleJobTest extends TestCase { public static class OurJob extends SimpleJob { List < String > results = new ArrayList < String > ( ) ; public void setConstantAttribute ( String value ) { results . add ( "" + value ) ; } public void setRuntimeAttribute ( String value ) { results . add ( "" + value ) ; } public void setElementProperty ( Object value ) { results . add ( "" + value ) ; } @ Inject public void setClassLoader ( ClassLoader classLoader ) { results . add ( "" + ( classLoader == null ? "" : "" ) ) ; } @ Override protected int execute ( ) throws Throwable { results . add ( "" ) ; return ; } @ Override protected void onInitialised ( ) { super . onInitialised ( ) ; results . add ( "" ) ; } @ Override protected void onDestroy ( ) { results . add ( "" ) ; } @ Override protected void onConfigured ( ) { super . onConfigured ( ) ; results . add ( "" ) ; } public String getSomeValue ( ) { return "" ; } public List < String > getResults ( ) { return results ; } } public void testFullLifeCycleInOddjob ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + "" + OurJob . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; @ SuppressWarnings ( "" ) List < String > results = ( List < String > ) new OddjobLookup ( oddjob ) . lookup ( "" , List . class ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( , results . size ( ) ) ; oddjob . destroy ( ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( "" , results . get ( ) ) ; assertEquals ( , results . size ( ) ) ; } private class SleepyJob extends SimpleJob { long sleep ; @ Override protected int execute ( ) throws Throwable { sleep ( sleep ) ; return ; } } public void testSleepAndComplete ( ) throws InterruptedException , FailedToStopException { SleepyJob test = new SleepyJob ( ) ; test . sleep = ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . SLEEPING , IconHelper . EXECUTING , IconHelper . COMPLETE ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( JobState . READY , JobState . EXECUTING , JobState . COMPLETE ) ; test . run ( ) ; state . checkNow ( ) ; icons . checkNow ( ) ; } public void testSleepAndStop ( ) throws InterruptedException , FailedToStopException { SleepyJob test = new SleepyJob ( ) ; IconSteps icons = new IconSteps ( test ) ; icons . startCheck ( IconHelper . READY , IconHelper . EXECUTING , IconHelper . SLEEPING ) ; StateSteps state = new StateSteps ( test ) ; state . startCheck ( JobState . READY , JobState . EXECUTING ) ; new Thread ( test ) . start ( ) ; state . checkWait ( ) ; icons . checkWait ( ) ; icons . startCheck ( IconHelper . SLEEPING , IconHelper . STOPPING , IconHelper . COMPLETE ) ; test . stop ( ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; icons . checkNow ( ) ; } public void testForceable ( ) { SimpleJob test = new SimpleJob ( ) { @ Override protected int execute ( ) throws Throwable { return ; } } ; assertEquals ( JobState . READY , test . lastStateEvent ( ) . getState ( ) ) ; test . force ( ) ; assertEquals ( JobState . COMPLETE , test . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . framework ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . log4j . Level ; import org . apache . log4j . Logger ; import org . oddjob . Describeable ; import org . oddjob . FailedToStopException ; import org . oddjob . Forceable ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . StateSteps ; import org . oddjob . Stateful ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . life . ArooaContextAware ; import org . oddjob . arooa . life . ArooaLifeAware ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeListener ; import org . oddjob . arooa . standard . StandardArooaDescriptor ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . standard . StandardTools ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . describe . UniversalDescriber ; import org . oddjob . logging . LogEnabled ; import org . oddjob . logging . LogEvent ; import org . oddjob . logging . LogLevel ; import org . oddjob . logging . LogListener ; import org . oddjob . logging . log4j . Log4jArchiver ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateListener ; public class RunnableWrapperTest extends TestCase { private class OurContext extends MockArooaContext { OurSession session ; @ Override public ArooaSession getSession ( ) { return session ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void addRuntimeListener ( RuntimeListener listener ) { } } ; } } private class OurSession extends MockArooaSession { Object configured ; Object saved ; ArooaDescriptor descriptor = new StandardArooaDescriptor ( ) ; @ Override public ArooaDescriptor getArooaDescriptor ( ) { return descriptor ; } @ Override public ComponentPool getComponentPool ( ) { return new MockComponentPool ( ) { @ Override public void configure ( Object component ) { configured = component ; } @ Override public void save ( Object component ) { saved = component ; } } ; } @ Override public ArooaTools getTools ( ) { return new StandardTools ( ) ; } } public static class OurRunnable implements Runnable { boolean ran ; public void run ( ) { ran = true ; } public boolean isRan ( ) { return ran ; } public String toString ( ) { return "" ; } } public void testGoodRunnable ( ) { OurSession session = new OurSession ( ) ; OurContext context = new OurContext ( ) ; context . session = session ; OurRunnable test = new OurRunnable ( ) ; Object proxy = new RunnableProxyGenerator ( ) . generate ( ( Runnable ) test , getClass ( ) . getClassLoader ( ) ) ; ( ( ArooaSessionAware ) proxy ) . setArooaSession ( session ) ; ( ( ArooaContextAware ) proxy ) . setArooaContext ( context ) ; MyStateListener stateListener = new MyStateListener ( ) ; ( ( Stateful ) proxy ) . addStateListener ( stateListener ) ; assertSame ( proxy , stateListener . lastEvent . getSource ( ) ) ; ( ( Runnable ) proxy ) . run ( ) ; assertEquals ( proxy , session . configured ) ; assertEquals ( proxy , session . saved ) ; assertTrue ( test . ran ) ; assertEquals ( "" , JobState . COMPLETE , stateListener . lastEvent . getState ( ) ) ; session . saved = null ; ( ( Resetable ) proxy ) . hardReset ( ) ; assertEquals ( "" , JobState . READY , stateListener . lastEvent . getState ( ) ) ; assertEquals ( proxy , session . saved ) ; ( ( Forceable ) proxy ) . force ( ) ; assertEquals ( "" , JobState . COMPLETE , stateListener . lastEvent . getState ( ) ) ; } public void testBadRunnable ( ) { Runnable test = new Runnable ( ) { public void run ( ) { throw new RuntimeException ( "" ) ; } } ; Object proxy = new RunnableProxyGenerator ( ) . generate ( ( Runnable ) test , getClass ( ) . getClassLoader ( ) ) ; ArooaSession session = new StandardArooaSession ( ) ; ( ( ArooaSessionAware ) proxy ) . setArooaSession ( session ) ; MyStateListener l = new MyStateListener ( ) ; ( ( Stateful ) proxy ) . addStateListener ( l ) ; ( ( Runnable ) proxy ) . run ( ) ; assertEquals ( "" , JobState . EXCEPTION , l . lastEvent . getState ( ) ) ; ( ( Resetable ) proxy ) . softReset ( ) ; assertEquals ( "" , JobState . READY , l . lastEvent . getState ( ) ) ; } private class MyStateListener implements StateListener { StateEvent lastEvent ; public void jobStateChange ( StateEvent event ) { lastEvent = event ; } } public void testStop ( ) throws InterruptedException , FailedToStopException { Runnable test = new Runnable ( ) { @ Override public void run ( ) { synchronized ( this ) { try { wait ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } } @ Override public String toString ( ) { return "" ; } } ; Runnable wrapper = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) test , getClass ( ) . getClassLoader ( ) ) ; Stateful stateful = ( Stateful ) wrapper ; StateSteps states = new StateSteps ( stateful ) ; states . startCheck ( JobState . READY , JobState . EXECUTING ) ; Thread t = new Thread ( wrapper ) ; t . start ( ) ; states . checkWait ( ) ; Stoppable stoppable = ( Stoppable ) wrapper ; states . startCheck ( JobState . EXECUTING , JobState . COMPLETE ) ; stoppable . stop ( ) ; states . checkWait ( ) ; } public void testHashCode ( ) { Runnable wrapped = new Runnable ( ) { public void run ( ) { } } ; Runnable test = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) wrapped , getClass ( ) . getClassLoader ( ) ) ; HashMap < Object , String > hashMap = new HashMap < Object , String > ( ) ; hashMap . put ( test , "" ) ; String result = hashMap . get ( test ) ; assertEquals ( "" , result ) ; } public void testEquals ( ) { Runnable wrapped = new Runnable ( ) { public void run ( ) { } } ; Runnable test = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) wrapped , getClass ( ) . getClassLoader ( ) ) ; assertTrue ( test . equals ( test ) ) ; assertEquals ( test , test ) ; } public static class Bean { String greeting ; public void setGreeting ( String greeting ) { this . greeting = greeting ; } public String getGreeting ( ) { return greeting ; } } public static class Job implements Runnable { public String result ; public void run ( ) { } public void setResult ( String result ) { this . result = result ; } public String getResult ( ) { return result ; } } public void testInOddjob ( ) throws Exception { String xml = "" + "" + "" + OurRunnable . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; Object r = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( r ) ) ; Object ran = PropertyUtils . getProperty ( r , "" ) ; assertEquals ( Boolean . class , ran . getClass ( ) ) ; assertEquals ( new Boolean ( true ) , ran ) ; Map < String , String > description = ( ( Describeable ) r ) . describe ( ) ; assertEquals ( "" , description . get ( "" ) ) ; oddjob . destroy ( ) ; } public static class LotsOfProperties implements Runnable { private Map < String , Object > map = new HashMap < String , Object > ( ) ; private String [ ] indexed = new String [ ] ; private String simple ; public void run ( ) { } public void setMapped ( String name , Object value ) { map . put ( name , value ) ; } public Object getMapped ( String name ) { return map . get ( name ) ; } public void setIndexed ( int i , String value ) { this . indexed [ i ] = value ; } public String [ ] getIndexed ( ) { return this . indexed ; } public void setSimple ( String simple ) { this . simple = simple ; } public String getSimple ( ) { return this . simple ; } } public void testPropertiesInProxy ( ) throws Exception { LotsOfProperties bean = new LotsOfProperties ( ) ; Runnable test = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) bean , getClass ( ) . getClassLoader ( ) ) ; DynaBean db = ( DynaBean ) test ; db . set ( "" , "" ) ; assertEquals ( "" , db . get ( "" ) ) ; db . set ( "" , "" , "" ) ; assertEquals ( "" , db . get ( "" , "" ) ) ; db . set ( "" , , "" ) ; assertEquals ( "" , db . get ( "" , ) ) ; PropertyUtils . setProperty ( db , "" , "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( db , "" ) ) ; PropertyUtils . setProperty ( db , "" , "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( db , "" ) ) ; PropertyUtils . setProperty ( db , "" , "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( db , "" ) ) ; } public void testProperitesInOddjob ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + LotsOfProperties . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oj ) ; assertEquals ( "" , lookup . lookup ( "" , String . class ) ) ; Map < ? , ? > map = lookup . lookup ( "" , Properties . class ) ; assertEquals ( map . get ( "" ) , "" ) ; Object [ ] array = lookup . lookup ( "" , Object [ ] . class ) ; assertEquals ( array [ ] , "" ) ; oj . destroy ( ) ; } public static class AnyLogger implements Runnable { public void run ( ) { Logger . getLogger ( "" ) . error ( "" ) ; } } public void testDefaultLogger ( ) throws Exception { class MyL implements LogListener { StringBuffer messages = new StringBuffer ( ) ; public void logEvent ( LogEvent logEvent ) { messages . append ( logEvent . getMessage ( ) ) ; } } AnyLogger l = new AnyLogger ( ) ; Runnable proxy = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) l , getClass ( ) . getClassLoader ( ) ) ; Logger . getLogger ( "" ) . setLevel ( Level . DEBUG ) ; Logger . getLogger ( ( ( LogEnabled ) proxy ) . loggerName ( ) ) . setLevel ( Level . DEBUG ) ; Log4jArchiver archiver = new Log4jArchiver ( proxy , "" ) ; MyL ll = new MyL ( ) ; archiver . addLogListener ( ll , proxy , LogLevel . DEBUG , , ) ; proxy . run ( ) ; assertTrue ( ll . messages . indexOf ( "" ) > ) ; } public static class MyLogger implements Runnable , LogEnabled { public String loggerName ( ) { return "" ; } public void run ( ) { Logger . getLogger ( loggerName ( ) ) . error ( "" ) ; } } public void testSpecificLogger ( ) throws Exception { class MyL implements LogListener { StringBuffer messages = new StringBuffer ( ) ; public void logEvent ( LogEvent logEvent ) { messages . append ( logEvent . getMessage ( ) ) ; } } MyLogger l = new MyLogger ( ) ; Runnable proxy = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) l , getClass ( ) . getClassLoader ( ) ) ; assertEquals ( "" , ( ( LogEnabled ) proxy ) . loggerName ( ) ) ; Logger . getLogger ( ( ( LogEnabled ) proxy ) . loggerName ( ) ) . setLevel ( Level . DEBUG ) ; Log4jArchiver archiver = new Log4jArchiver ( proxy , "" ) ; MyL ll = new MyL ( ) ; archiver . addLogListener ( ll , proxy , LogLevel . DEBUG , , ) ; proxy . run ( ) ; assertTrue ( ll . messages . indexOf ( "" ) > ) ; } public void testDescribe ( ) { ArooaSession session = new StandardArooaSession ( ) ; Job j = new Job ( ) ; j . setResult ( "" ) ; Runnable wrapper = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) j , getClass ( ) . getClassLoader ( ) ) ; ( ( ArooaSessionAware ) wrapper ) . setArooaSession ( session ) ; Map < String , String > m = new UniversalDescriber ( session ) . describe ( wrapper ) ; assertEquals ( "" , m . get ( "" ) ) ; } public static class Stubbon implements ArooaLifeAware { boolean ouch ; public void configured ( ) { } public void destroy ( ) { if ( ! ouch ) { ouch = true ; throw new RuntimeException ( "" ) ; } } public void initialised ( ) { } public String toString ( ) { return "" ; } } public void testDestroyInOddjob ( ) throws Exception { String xml = "" + "" + "" + "" + "" + OurRunnable . class . getName ( ) + "" + "" + Stubbon . class . getName ( ) + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . COMPLETE , Helper . getJobState ( oj ) ) ; try { oj . destroy ( ) ; fail ( "" ) ; } catch ( RuntimeException e ) { assertEquals ( "" , e . getMessage ( ) ) ; } oj . destroy ( ) ; } } package org . oddjob . framework ; import java . text . ParseException ; import java . util . Date ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . deploy . annotations . ArooaAttribute ; import org . oddjob . arooa . utils . DateHelper ; import org . oddjob . arooa . xml . XMLConfiguration ; public class BeanUtilsProviderTest extends TestCase { public static class DateBean { Date date ; @ ArooaAttribute public void setDate ( Date date ) { this . date = date ; } public Date getDate ( ) { return date ; } } public void testInOddjob ( ) throws ParseException { String xml = "" + "" + "" + DateBean . class . getName ( ) + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; DateBean bean = ( DateBean ) new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( DateHelper . parseDateTime ( "" ) , bean . getDate ( ) ) ; } } package org . oddjob . framework ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . arooa . registry . Services ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class ServicesJobTest extends TestCase { interface Snack { } interface SnackProvider { public Snack provideSnack ( ) ; } public static class Cafe implements SnackProvider { @ Override public Snack provideSnack ( ) { return new Snack ( ) { @ Override public String toString ( ) { return "" ; } } ; } @ Override public String toString ( ) { return "" ; } } public void testServiceRegisteredAndRetrieved ( ) { ServicesJob test = new ServicesJob ( ) ; ServicesJob . ServiceDefinition def = new ServicesJob . ServiceDefinition ( ) ; def . setService ( new Cafe ( ) ) ; test . setRegisteredServices ( , def ) ; Services services = test . getServices ( ) ; String serviceName = services . serviceNameFor ( SnackProvider . class , null ) ; assertNotNull ( serviceName ) ; Object service = services . getService ( serviceName ) ; assertEquals ( Cafe . class , service . getClass ( ) ) ; } public void testServiceLookup ( ) { String xml = "" + "" + "" + "" + "" + "" + Cafe . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Object service = new OddjobLookup ( oddjob ) . lookup ( "" ) ; assertEquals ( Cafe . class , service . getClass ( ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . framework ; import junit . framework . TestCase ; public class RunnableProxyGeneratorTest extends TestCase { public interface MyInterface { } public static class MyJob implements Runnable , MyInterface { @ Override public void run ( ) { } } public void testAProxyImplementsAllInterfaces ( ) { MyJob job = new MyJob ( ) ; Object proxy = new RunnableProxyGenerator ( ) . generate ( job , getClass ( ) . getClassLoader ( ) ) ; assertTrue ( proxy instanceof MyInterface ) ; } } package org . oddjob . framework ; import java . util . concurrent . Callable ; import java . util . concurrent . atomic . AtomicBoolean ; import junit . framework . TestCase ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . life . Destroy ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; public class RunnableWrapperResetTest extends TestCase { public static class Bean1 implements Runnable { boolean reset ; AtomicBoolean destroyed = new AtomicBoolean ( ) ; @ Override public void run ( ) { reset = false ; } @ HardReset @ SoftReset public void reset ( ) { reset = true ; } public boolean getReset ( ) { return reset ; } public AtomicBoolean getDestroyed ( ) { return destroyed ; } @ Destroy public void destroy ( ) { destroyed . set ( true ) ; } } public void testHardReset ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + Bean1 . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( false , lookup . lookup ( "" ) ) ; ( ( Resetable ) lookup . lookup ( "" ) ) . hardReset ( ) ; assertEquals ( true , lookup . lookup ( "" ) ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; AtomicBoolean destroyed = lookup . lookup ( "" , AtomicBoolean . class ) ; assertEquals ( false , destroyed . get ( ) ) ; oddjob . destroy ( ) ; assertEquals ( true , destroyed . get ( ) ) ; } public static class Bean2 implements Callable < Integer > { boolean reset ; @ Override public Integer call ( ) throws Exception { reset = false ; return ; } @ SoftReset public void reset ( ) { reset = true ; } public boolean getReset ( ) { return reset ; } } public void testSoftReset ( ) throws ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + Bean2 . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; assertEquals ( ParentState . INCOMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; assertEquals ( false , lookup . lookup ( "" ) ) ; ( ( Resetable ) lookup . lookup ( "" ) ) . softReset ( ) ; assertEquals ( true , lookup . lookup ( "" ) ) ; assertEquals ( ParentState . READY , oddjob . lastStateEvent ( ) . getState ( ) ) ; oddjob . run ( ) ; assertEquals ( false , lookup . lookup ( "" ) ) ; ( ( Resetable ) lookup . lookup ( "" ) ) . hardReset ( ) ; assertEquals ( false , lookup . lookup ( "" ) ) ; oddjob . destroy ( ) ; } } package org . oddjob . framework ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . CountDownLatch ; import junit . framework . TestCase ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . persist . Persistable ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . IsStoppable ; import org . oddjob . state . JobState ; import org . oddjob . state . JobStateChanger ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateListener ; import org . oddjob . state . State ; import org . oddjob . state . StateChanger ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateHandler ; public class BasePrimaryTest extends TestCase { private class OurComp extends BasePrimary { final CountDownLatch latch = new CountDownLatch ( ) ; private final JobStateHandler stateHandler = new JobStateHandler ( this ) ; private final JobStateChanger stateChanger ; protected OurComp ( ) { stateChanger = new JobStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override protected StateHandler < ? > stateHandler ( ) { return stateHandler ; } protected StateChanger < JobState > getStateChanger ( ) { return stateChanger ; } synchronized void work ( ) { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { @ Override public void run ( ) { getStateChanger ( ) . setState ( JobState . EXECUTING ) ; latch . countDown ( ) ; try { stateHandler . sleep ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "" ) ; } getStateChanger ( ) . setState ( JobState . COMPLETE ) ; } } ) ; } void wakeUp ( ) { try { latch . await ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } stateHandler . waitToWhen ( new IsStoppable ( ) , new Runnable ( ) { @ Override public void run ( ) { stateHandler . wake ( ) ; } } ) ; } @ Override protected void fireDestroyedState ( ) { throw new RuntimeException ( "" ) ; } } public void testSleep ( ) throws InterruptedException { final OurComp test = new OurComp ( ) ; final List < State > events = new ArrayList < State > ( ) ; StateListener listener = new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { events . add ( event . getState ( ) ) ; } } ; test . addStateListener ( listener ) ; Thread t1 = new Thread ( new Runnable ( ) { @ Override public void run ( ) { test . work ( ) ; } } ) ; Thread t2 = new Thread ( ) { @ Override public void run ( ) { test . wakeUp ( ) ; } } ; t1 . start ( ) ; t2 . start ( ) ; t1 . join ( ) ; t2 . join ( ) ; assertEquals ( JobState . READY , events . get ( ) ) ; assertEquals ( JobState . EXECUTING , events . get ( ) ) ; assertEquals ( JobState . COMPLETE , events . get ( ) ) ; assertEquals ( , events . size ( ) ) ; } } package org . oddjob . framework ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; import org . oddjob . Describeable ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . Stoppable ; import org . oddjob . arooa . ArooaDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ArooaTools ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . life . ArooaContextAware ; import org . oddjob . arooa . life . ArooaSessionAware ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeListener ; import org . oddjob . arooa . standard . StandardArooaDescriptor ; import org . oddjob . arooa . standard . StandardTools ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . ParentState ; import org . oddjob . state . ServiceState ; public class ServiceWrapperTest extends TestCase { private class OurContext extends MockArooaContext { OurSession session ; @ Override public ArooaSession getSession ( ) { return session ; } @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void addRuntimeListener ( RuntimeListener listener ) { } } ; } } private class OurSession extends MockArooaSession { Object configured ; Object saved ; ArooaDescriptor descriptor = new StandardArooaDescriptor ( ) ; @ Override public ArooaDescriptor getArooaDescriptor ( ) { return descriptor ; } @ Override public ComponentPool getComponentPool ( ) { return new MockComponentPool ( ) { @ Override public void configure ( Object component ) { configured = component ; } @ Override public void save ( Object component ) { saved = component ; } } ; } @ Override public ArooaTools getTools ( ) { return new StandardTools ( ) ; } } public static class MyService { boolean started ; boolean stopped ; public void start ( ) { started = true ; } public void stop ( ) { stopped = true ; } public boolean isStarted ( ) { return started ; } public boolean isStopped ( ) { return stopped ; } } public void testStartStop ( ) throws Exception { MyService myService = new MyService ( ) ; OurSession session = new OurSession ( ) ; ServiceAdaptor service = new ServiceStrategies ( ) . serviceFor ( myService , session ) ; OurContext context = new OurContext ( ) ; context . session = session ; Runnable wrapper = ( Runnable ) new ServiceProxyGenerator ( ) . generate ( service , getClass ( ) . getClassLoader ( ) ) ; ( ( ArooaSessionAware ) wrapper ) . setArooaSession ( session ) ; ( ( ArooaContextAware ) wrapper ) . setArooaContext ( context ) ; wrapper . run ( ) ; assertEquals ( wrapper , session . configured ) ; assertEquals ( ServiceState . STARTED , Helper . getJobState ( wrapper ) ) ; assertEquals ( new Boolean ( true ) , PropertyUtils . getProperty ( wrapper , "" ) ) ; ( ( Stoppable ) wrapper ) . stop ( ) ; assertEquals ( ServiceState . COMPLETE , Helper . getJobState ( wrapper ) ) ; assertEquals ( new Boolean ( true ) , PropertyUtils . getProperty ( wrapper , "" ) ) ; ( ( Resetable ) wrapper ) . hardReset ( ) ; assertNull ( session . saved ) ; assertEquals ( ServiceState . READY , Helper . getJobState ( wrapper ) ) ; } public void testInOddjob ( ) throws Exception { String xml = "" + "" + "" + MyService . class . getName ( ) + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; Object test = new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( ServiceState . STARTED , Helper . getJobState ( test ) ) ; assertEquals ( new Boolean ( true ) , PropertyUtils . getProperty ( test , "" ) ) ; oj . stop ( ) ; assertEquals ( ServiceState . COMPLETE , Helper . getJobState ( test ) ) ; assertEquals ( new Boolean ( true ) , PropertyUtils . getProperty ( test , "" ) ) ; Map < String , String > description = ( ( Describeable ) test ) . describe ( ) ; assertEquals ( "" , description . get ( "" ) ) ; assertEquals ( "" , description . get ( "" ) ) ; oj . destroy ( ) ; } public static class Bean { String greeting ; public void setGreeting ( String greeting ) { this . greeting = greeting ; } public String getGreeting ( ) { return greeting ; } } public static class MyS2 { public String result ; public void start ( ) { } public void stop ( ) { } public void setResult ( String result ) { this . result = result ; } public String getResult ( ) { return result ; } } public void testInOddjob2 ( ) throws Exception { String xml = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + MyS2 . class . getName ( ) + "" + "" + "" + "" + "" + "" ; Oddjob oj = new Oddjob ( ) ; oj . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oj . run ( ) ; assertEquals ( ParentState . ACTIVE , oj . lastStateEvent ( ) . getState ( ) ) ; Object r = new OddjobLookup ( oj ) . lookup ( "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( r , "" ) ) ; oj . stop ( ) ; assertEquals ( ParentState . COMPLETE , oj . lastStateEvent ( ) . getState ( ) ) ; } } package org . oddjob . framework ; import java . util . concurrent . Callable ; import junit . framework . TestCase ; public class CallableProxyGeneratorTest extends TestCase { public interface MyInterface { } public static class MyJob implements Callable < Integer > , MyInterface { @ Override public Integer call ( ) throws Exception { return ; } } public void testAProxyImplementsAllInterfaces ( ) { MyJob callable = new MyJob ( ) ; Object proxy = new CallableProxyGenerator ( ) . generate ( callable , getClass ( ) . getClassLoader ( ) ) ; assertTrue ( proxy instanceof MyInterface ) ; } } package org . oddjob . framework ; import java . io . File ; import java . net . MalformedURLException ; import java . util . concurrent . Callable ; import junit . framework . TestCase ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . OurDirs ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; import org . oddjob . util . URLClassLoaderType ; import org . oddjob . util . URLClassLoaderTypeTest ; public class CallableWrapperTest extends TestCase { public static class OurCallable implements Callable < Integer > { boolean ran ; int status ; public Integer call ( ) { ran = true ; return new Integer ( status ) ; } public boolean isRan ( ) { return ran ; } public void setStatus ( int status ) { this . status = status ; } public String toString ( ) { return "" ; } } public void testInOddjob ( ) throws Exception { String xml = "" + "" + "" + OurCallable . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object runnable = lookup . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( runnable ) ) ; Boolean ran = lookup . lookup ( "" , Boolean . class ) ; assertEquals ( new Boolean ( true ) , ran ) ; oddjob . destroy ( ) ; } public void testIncompleteInOddjob ( ) throws Exception { String xml = "" + "" + "" + OurCallable . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object runnable = lookup . lookup ( "" ) ; assertEquals ( JobState . INCOMPLETE , Helper . getJobState ( runnable ) ) ; Boolean ran = lookup . lookup ( "" , Boolean . class ) ; assertEquals ( new Boolean ( true ) , ran ) ; oddjob . destroy ( ) ; } public static class OurCallable2 implements Callable < Void > { boolean ran ; public Void call ( ) { ran = true ; return null ; } public boolean isRan ( ) { return ran ; } public String toString ( ) { return "" ; } } public void testVoidCallableInOddjob ( ) throws Exception { String xml = "" + "" + "" + OurCallable2 . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object runnable = lookup . lookup ( "" ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( runnable ) ) ; Boolean ran = lookup . lookup ( "" , Boolean . class ) ; assertEquals ( new Boolean ( true ) , ran ) ; oddjob . destroy ( ) ; } public static class BadCallable implements Callable < Void > { public Void call ( ) throws Exception { throw new Exception ( "" ) ; } public String toString ( ) { return "" ; } } public void testExceptionInOddjob ( ) throws Exception { String xml = "" + "" + "" + BadCallable . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . run ( ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; Object runnable = lookup . lookup ( "" ) ; assertEquals ( JobState . EXCEPTION , Helper . getJobState ( runnable ) ) ; oddjob . destroy ( ) ; } public void testConSimple ( ) throws ClassNotFoundException , MalformedURLException , InstantiationException , IllegalAccessException , ArooaPropertyException , ArooaConversionException { OurDirs dirs = new OurDirs ( ) ; ClassLoader existing = Thread . currentThread ( ) . getContextClassLoader ( ) ; File check = dirs . relative ( "" ) ; if ( ! check . exists ( ) ) { URLClassLoaderTypeTest . compileSample ( dirs ) ; } URLClassLoaderType classLoaderType = new URLClassLoaderType ( ) ; classLoaderType . setFiles ( new File [ ] { dirs . relative ( "" ) } ) ; classLoaderType . setParent ( getClass ( ) . getClassLoader ( ) ) ; ClassLoader classLoader = classLoaderType . toValue ( ) ; String xml = "" + "" + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob . setClassLoader ( classLoader ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; OddjobLookup lookup = new OddjobLookup ( oddjob ) ; ClassLoader threadClassLoader = lookup . lookup ( "" , ClassLoader . class ) ; assertEquals ( classLoader , threadClassLoader ) ; oddjob . destroy ( ) ; assertEquals ( existing , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; } } package org . oddjob . framework ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . List ; import java . util . concurrent . atomic . AtomicBoolean ; import junit . framework . TestCase ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . MockArooaSession ; import org . oddjob . arooa . life . ComponentPersistException ; import org . oddjob . arooa . parsing . MockArooaContext ; import org . oddjob . arooa . registry . ComponentPool ; import org . oddjob . arooa . registry . MockComponentPool ; import org . oddjob . arooa . runtime . MockRuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeConfiguration ; import org . oddjob . arooa . runtime . RuntimeListener ; import org . oddjob . images . StateIcons ; import org . oddjob . persist . Persistable ; import org . oddjob . state . IsAnyState ; import org . oddjob . state . JobState ; import org . oddjob . state . JobStateChanger ; import org . oddjob . state . JobStateHandler ; import org . oddjob . state . StateListener ; import org . oddjob . state . State ; import org . oddjob . state . StateChanger ; import org . oddjob . state . StateEvent ; import org . oddjob . state . StateHandler ; public class BaseComponentTest extends TestCase { private static final Logger logger = Logger . getLogger ( BaseComponentTest . class ) ; private class OurComponent extends BaseComponent { private final JobStateHandler stateHandler = new JobStateHandler ( this ) ; private final JobStateChanger stateChanger ; protected OurComponent ( ) { stateChanger = new JobStateChanger ( stateHandler , iconHelper , new Persistable ( ) { @ Override public void persist ( ) throws ComponentPersistException { save ( ) ; } } ) ; } @ Override protected StateHandler < ? > stateHandler ( ) { return stateHandler ; } protected StateChanger < JobState > getStateChanger ( ) { return stateChanger ; } @ Override protected Logger logger ( ) { return logger ; } @ Override protected void save ( ) throws ComponentPersistException { OurComponent . this . save ( OurComponent . this ) ; } void complete ( ) { stateHandler . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { getStateChanger ( ) . setState ( JobState . COMPLETE ) ; } } ) ; } @ Override protected void fireDestroyedState ( ) { throw new RuntimeException ( "" ) ; } } class OurSession extends MockArooaSession { @ Override public ComponentPool getComponentPool ( ) { return new MockComponentPool ( ) { @ Override public void save ( Object component ) throws ComponentPersistException { throw new ComponentPersistException ( "" ) ; } } ; } } public void testExceptionOnSave ( ) { final OurComponent test = new OurComponent ( ) ; test . setArooaSession ( new OurSession ( ) ) ; test . complete ( ) ; assertEquals ( JobState . EXCEPTION , test . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( ComponentPersistException . class , test . lastStateEvent ( ) . getException ( ) . getClass ( ) ) ; } private static class SerializableComponent extends BaseComponent implements Serializable { private static final long serialVersionUID = ; transient JobStateHandler stateHandler ; public SerializableComponent ( ) { completeConstruction ( ) ; } private void completeConstruction ( ) { stateHandler = new JobStateHandler ( this ) ; } @ Override protected StateHandler < ? > stateHandler ( ) { return stateHandler ; } @ Override protected Logger logger ( ) { return logger ; } @ Override protected void save ( ) throws ComponentPersistException { } private void writeObject ( ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; s . writeObject ( stateHandler . lastStateEvent ( ) ) ; } private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; assertNotNull ( iconHelper ) ; StateEvent savedEvent = ( StateEvent ) s . readObject ( ) ; completeConstruction ( ) ; stateHandler . restoreLastJobStateEvent ( savedEvent ) ; iconHelper . changeIcon ( StateIcons . iconFor ( stateHandler . getState ( ) ) ) ; } @ Override protected void fireDestroyedState ( ) { throw new RuntimeException ( "" ) ; } } public void testSerialisation ( ) throws IOException , ClassNotFoundException , InterruptedException { SerializableComponent test = new SerializableComponent ( ) ; assertNotNull ( test . stateHandler ) ; StateEvent event = test . stateHandler . lastStateEvent ( ) ; Thread . sleep ( ) ; SerializableComponent copy = Helper . copy ( test ) ; assertNotNull ( copy . stateHandler ) ; assertEquals ( event . getTime ( ) , copy . stateHandler . lastStateEvent ( ) . getTime ( ) ) ; } private class OurContext extends MockArooaContext { RuntimeListener listener ; @ Override public RuntimeConfiguration getRuntime ( ) { return new MockRuntimeConfiguration ( ) { @ Override public void addRuntimeListener ( RuntimeListener listener ) { assertNull ( OurContext . this . listener ) ; assertNotNull ( listener ) ; OurContext . this . listener = listener ; } @ Override public void removeRuntimeListener ( RuntimeListener listener ) { super . removeRuntimeListener ( listener ) ; } } ; } @ Override public ArooaSession getSession ( ) { return new MockArooaSession ( ) ; } } public void testStateNotifiedOnDestroy ( ) { final List < State > results = new ArrayList < State > ( ) ; final AtomicBoolean destroyed = new AtomicBoolean ( ) ; BasePrimary test = new BasePrimary ( ) { JobStateHandler stateHandler = new JobStateHandler ( this ) ; @ Override protected StateHandler < ? > stateHandler ( ) { return stateHandler ; } @ Override protected Logger logger ( ) { return logger ; } @ Override public void onDestroy ( ) { super . onDestroy ( ) ; destroyed . set ( true ) ; } @ Override protected void fireDestroyedState ( ) { if ( ! stateHandler ( ) . waitToWhen ( new IsAnyState ( ) , new Runnable ( ) { public void run ( ) { stateHandler . setState ( JobState . DESTROYED ) ; stateHandler . fireEvent ( ) ; } } ) ) { throw new IllegalStateException ( "" ) ; } } } ; test . addStateListener ( new StateListener ( ) { @ Override public void jobStateChange ( StateEvent event ) { results . add ( event . getState ( ) ) ; } } ) ; OurContext context = new OurContext ( ) ; test . setArooaContext ( context ) ; context . listener . beforeDestroy ( null ) ; context . listener . afterDestroy ( null ) ; assertEquals ( JobState . READY , results . get ( ) ) ; assertEquals ( JobState . DESTROYED , results . get ( ) ) ; assertEquals ( , results . size ( ) ) ; assertTrue ( destroyed . get ( ) ) ; } } package org . oddjob . framework ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardArooaSession ; public class ServiceStrategiesTest extends TestCase { ArooaSession session = new StandardArooaSession ( ) ; public static class MyService1 implements Service { boolean started ; @ Override public void start ( ) throws Exception { started = true ; } @ Override public void stop ( ) throws FailedToStopException { started = false ; } } public void testIsServiceAlreadyStrategy ( ) throws Exception { ServiceStrategy test = new ServiceStrategies ( ) . isServiceAlreadyStrategy ( ) ; MyService1 service = new MyService1 ( ) ; ServiceAdaptor adaptor = test . serviceFor ( service , session ) ; assertNotNull ( adaptor ) ; assertEquals ( service , adaptor . getComponent ( ) ) ; adaptor . start ( ) ; assertEquals ( true , service . started ) ; adaptor . stop ( ) ; assertEquals ( false , service . started ) ; assertNull ( test . serviceFor ( new Object ( ) , session ) ) ; } public static class MyService2 { boolean started ; @ Start public void begin ( ) { started = true ; } @ Stop public void end ( ) { started = false ; } } public void testHasServiceAnotationsStrategy ( ) throws Exception { ServiceStrategy test = new ServiceStrategies ( ) . hasServiceAnnotationsStrategy ( ) ; MyService2 service = new MyService2 ( ) ; ServiceAdaptor adaptor = test . serviceFor ( service , session ) ; assertNotNull ( adaptor ) ; assertEquals ( service , adaptor . getComponent ( ) ) ; adaptor . start ( ) ; assertEquals ( true , service . started ) ; adaptor . stop ( ) ; assertEquals ( false , service . started ) ; assertNull ( test . serviceFor ( new Object ( ) , session ) ) ; } public static class MyService3 { boolean started ; public void start ( ) { started = true ; } public void stop ( ) { started = false ; } } public void testHasServiceMethodsStrategy ( ) throws Exception { ServiceStrategy test = new ServiceStrategies ( ) . hasServiceMethodsStrategy ( ) ; MyService3 service = new MyService3 ( ) ; ServiceAdaptor adaptor = test . serviceFor ( service , session ) ; assertNotNull ( adaptor ) ; assertEquals ( service , adaptor . getComponent ( ) ) ; adaptor . start ( ) ; assertEquals ( true , service . started ) ; adaptor . stop ( ) ; assertEquals ( false , service . started ) ; assertNull ( test . serviceFor ( new Object ( ) , session ) ) ; } } package org . oddjob . framework ; import java . util . HashMap ; import java . util . Map ; import junit . framework . TestCase ; import org . apache . commons . beanutils . PropertyUtils ; public class WrapDynaBeanTest extends TestCase { public static class SimpleBean { private String simple ; public void setSimple ( String simple ) { this . simple = simple ; } public String getSimple ( ) { return simple ; } } public void testSimple ( ) throws Exception { SimpleBean bean = new SimpleBean ( ) ; WrapDynaBean wrap = new WrapDynaBean ( bean ) ; wrap . set ( "" , "" ) ; assertEquals ( "" , bean . getSimple ( ) ) ; assertEquals ( "" , wrap . get ( "" ) ) ; bean . setSimple ( null ) ; PropertyUtils . setProperty ( wrap , "" , "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( wrap , "" ) ) ; } public static class MappedBean { private Map < String , Object > map = new HashMap < String , Object > ( ) ; public void setMapped ( String name , Object value ) { map . put ( name , value ) ; } public Object getMapped ( String name ) { return map . get ( name ) ; } } public void testMapped ( ) throws Exception { MappedBean bean = new MappedBean ( ) ; WrapDynaBean wrap = new WrapDynaBean ( bean ) ; wrap . set ( "" , "" , "" ) ; assertEquals ( "" , bean . getMapped ( "" ) ) ; assertEquals ( "" , wrap . get ( "" , "" ) ) ; PropertyUtils . setProperty ( wrap , "" , "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( wrap , "" ) ) ; } public static class IndexedBean { private String [ ] array = new String [ ] ; public void setIndexed ( String [ ] array ) { this . array = array ; } public String [ ] getIndexed ( ) { return array ; } } public void testIndexed ( ) throws Exception { IndexedBean bean = new IndexedBean ( ) ; WrapDynaBean wrap = new WrapDynaBean ( bean ) ; wrap . set ( "" , , "" ) ; assertEquals ( "" , bean . getIndexed ( ) [ ] ) ; assertEquals ( "" , wrap . get ( "" , ) ) ; PropertyUtils . setProperty ( wrap , "" , "" ) ; assertEquals ( "" , PropertyUtils . getProperty ( wrap , "" ) ) ; } public static class InAccessableBean { private String simple ; public void setSimple ( String simple ) { this . simple = simple ; } String getSimple ( ) { return simple ; } } public void testInAccessable ( ) throws Exception { InAccessableBean bean = new InAccessableBean ( ) ; WrapDynaBean wrap = new WrapDynaBean ( bean ) ; wrap . set ( "" , "" ) ; assertEquals ( "" , bean . getSimple ( ) ) ; assertEquals ( null , wrap . get ( "" ) ) ; bean . setSimple ( null ) ; PropertyUtils . setProperty ( wrap , "" , "" ) ; assertEquals ( null , PropertyUtils . getProperty ( wrap , "" ) ) ; } public static class InAccessableMappedBean { private Map < String , Object > map = new HashMap < String , Object > ( ) ; public void setMapped ( String name , Object value ) { map . put ( name , value ) ; } Object getMapped ( String name ) { return map . get ( name ) ; } } public void testInAccessableMapped ( ) throws Exception { InAccessableMappedBean bean = new InAccessableMappedBean ( ) ; WrapDynaBean wrap = new WrapDynaBean ( bean ) ; wrap . set ( "" , "" , "" ) ; assertEquals ( "" , bean . getMapped ( "" ) ) ; assertEquals ( null , wrap . get ( "" , "" ) ) ; PropertyUtils . setProperty ( wrap , "" , "" ) ; assertEquals ( null , PropertyUtils . getProperty ( wrap , "" ) ) ; } } package org . oddjob . framework ; import junit . framework . TestCase ; import org . oddjob . FailedToStopException ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . standard . StandardArooaSession ; public class ServiceProxyGeneratorTest extends TestCase { public interface MyInterface { } public static class MyService implements MyInterface { @ Start public void start ( ) throws Exception { } @ Stop public void stop ( ) throws FailedToStopException { } } public void testAProxyImplementsAllInterfaces ( ) { ArooaSession session = new StandardArooaSession ( ) ; MyService service = new MyService ( ) ; ServiceAdaptor adaptor = new ServiceStrategies ( ) . serviceFor ( service , session ) ; Object proxy = new ServiceProxyGenerator ( ) . generate ( adaptor , getClass ( ) . getClassLoader ( ) ) ; assertTrue ( proxy instanceof MyInterface ) ; assertFalse ( proxy instanceof Service ) ; } } package org . oddjob . framework ; import java . io . Serializable ; import java . lang . reflect . Proxy ; import junit . framework . TestCase ; import org . apache . commons . beanutils . DynaBean ; import org . apache . log4j . Logger ; import org . oddjob . Helper ; import org . oddjob . Oddjob ; import org . oddjob . OddjobLookup ; import org . oddjob . Resetable ; import org . oddjob . Stateful ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . life . ComponentPersister ; import org . oddjob . arooa . life . MockComponentPersister ; import org . oddjob . arooa . xml . XMLConfiguration ; import org . oddjob . persist . OddjobPersister ; import org . oddjob . state . JobState ; import org . oddjob . state . ParentState ; public class SerializableWrapperTest extends TestCase { private static final Logger logger = Logger . getLogger ( SerializableWrapperTest . class ) ; public static class Test1 implements Runnable , Serializable { private static final long serialVersionUID = ; private String check ; public void run ( ) { if ( check != null ) { check = "" ; } else { check = "" ; } } public String getCheck ( ) { return check ; } @ Override public String toString ( ) { return "" ; } } public static class Test2 implements Runnable { public void run ( ) { } @ Override public String toString ( ) { return "" ; } } public void testSimple ( ) throws Exception { Runnable test = new Test1 ( ) ; Runnable proxy = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) test , getClass ( ) . getClassLoader ( ) ) ; proxy . run ( ) ; DynaBean copy = ( DynaBean ) Helper . copy ( proxy ) ; assertTrue ( copy instanceof Proxy ) ; assertEquals ( "" , copy . get ( "" ) ) ; } public void testNotSerializable ( ) throws Exception { Runnable test = new Test2 ( ) ; Runnable proxy = ( Runnable ) new RunnableProxyGenerator ( ) . generate ( ( Runnable ) test , getClass ( ) . getClassLoader ( ) ) ; assertTrue ( proxy instanceof Transient ) ; } private class OurPersister implements OddjobPersister { Object save ; int count ; public ComponentPersister persisterFor ( String id ) { return new MockComponentPersister ( ) { boolean closed ; @ Override public void persist ( String id , Object proxy , ArooaSession session ) { if ( closed ) { return ; } logger . info ( "" + proxy + "" + id + "" ) ; assertEquals ( "" , id ) ; try { save = Helper . copy ( proxy ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } ++ count ; } @ Override public Object restore ( String id , ClassLoader classLoader , ArooaSession session ) { assertEquals ( "" , id ) ; logger . info ( "" + id + "" ) ; return save ; } @ Override public void remove ( String id , ArooaSession session ) { if ( closed ) { return ; } save = null ; } @ Override public void close ( ) { closed = true ; } } ; } } public void testSerializeInOddjob ( ) { String xml = "" + "" + "" + Test1 . class . getName ( ) + "" + "" + "" ; Oddjob oddjob = new Oddjob ( ) ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; OurPersister persister = new OurPersister ( ) ; oddjob . setPersister ( persister ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Proxy proxy = ( Proxy ) new OddjobLookup ( oddjob ) . lookup ( "" ) ; Test1 test1 = ( Test1 ) ( ( WrapperInvocationHandler ) Proxy . getInvocationHandler ( proxy ) ) . getWrappedComponent ( ) ; assertEquals ( JobState . COMPLETE , Helper . getJobState ( proxy ) ) ; assertEquals ( "" , test1 . check ) ; oddjob . destroy ( ) ; Oddjob oddjob2 = new Oddjob ( ) ; oddjob2 . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; oddjob2 . setPersister ( persister ) ; oddjob2 . load ( ) ; assertEquals ( ParentState . READY , oddjob2 . lastStateEvent ( ) . getState ( ) ) ; proxy = ( Proxy ) new OddjobLookup ( oddjob2 ) . lookup ( "" ) ; test1 = ( Test1 ) ( ( WrapperInvocationHandler ) Proxy . getInvocationHandler ( proxy ) ) . getWrappedComponent ( ) ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) proxy ) . lastStateEvent ( ) . getState ( ) ) ; assertEquals ( "" , test1 . check ) ; assertEquals ( , persister . count ) ; ( ( Resetable ) proxy ) . hardReset ( ) ; assertEquals ( JobState . READY , ( ( Stateful ) proxy ) . lastStateEvent ( ) . getState ( ) ) ; ( ( Runnable ) proxy ) . run ( ) ; assertEquals ( JobState . COMPLETE , ( ( Stateful ) proxy ) . lastStateEvent ( ) . getState ( ) ) ; oddjob2 . destroy ( ) ; } public void testPersistCount ( ) { Oddjob oddjob = new Oddjob ( ) ; String xml = "" + "" + "" + Test1 . class . getName ( ) + "" + "" + "" ; oddjob . setConfiguration ( new XMLConfiguration ( "" , xml ) ) ; OurPersister persister = new OurPersister ( ) ; oddjob . setPersister ( persister ) ; oddjob . run ( ) ; assertEquals ( ParentState . COMPLETE , oddjob . lastStateEvent ( ) . getState ( ) ) ; Object proxy = new OddjobLookup ( oddjob ) . lookup ( "" ) ; ( ( Resetable ) proxy ) . hardReset ( ) ; ( ( Runnable ) proxy ) . run ( ) ; assertEquals ( , persister . count ) ; oddjob . destroy ( ) ; } } package org . oddjob . framework ; import java . net . URL ; import junit . framework . TestCase ; import org . oddjob . arooa . ArooaParseException ; import org . oddjob . arooa . ArooaParser ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . convert . ArooaConversionException ; import org . oddjob . arooa . deploy . annotations . ArooaComponent ; import org . oddjob . arooa . life . ComponentProxyResolver ; import org . oddjob . arooa . reflect . ArooaClass ; import org . oddjob . arooa . reflect . ArooaPropertyException ; import org . oddjob . arooa . reflect . BeanOverview ; import org . oddjob . arooa . reflect . PropertyAccessor ; import org . oddjob . arooa . registry . BeanDirectory ; import org . oddjob . arooa . standard . StandardArooaParser ; import org . oddjob . arooa . standard . StandardArooaSession ; import org . oddjob . arooa . xml . XMLConfiguration ; public class WrapDynaBeanArooaTest extends TestCase { public static class Root { @ ArooaComponent public void setStuff ( Object stuff ) { } } public static class Stuff { private String text ; private URL url ; public URL getUrl ( ) { return url ; } public void setUrl ( URL url ) { this . url = url ; } public void setText ( String text ) { this . text = text ; } ; public String getText ( ) { return text ; } } private class OurSession extends StandardArooaSession { @ Override public ComponentProxyResolver getComponentProxyResolver ( ) { return new ComponentProxyResolver ( ) { @ Override public Object resolve ( Object object , ArooaSession session ) { return new WrapDynaBean ( object ) ; } @ Override public Object restore ( Object proxy , ArooaSession session ) { throw new RuntimeException ( "" ) ; } } ; } } public void testInArooa ( ) throws ArooaParseException , ArooaPropertyException , ArooaConversionException { String xml = "" + "" + "" + Stuff . class . getName ( ) + "" + "" + "" + "" + "" + "" + "" ; ArooaSession session = new OurSession ( ) ; Root root = new Root ( ) ; ArooaParser parser = new StandardArooaParser ( root , session ) ; parser . parse ( new XMLConfiguration ( "" , xml ) ) ; BeanDirectory lookup = session . getBeanRegistry ( ) ; Object stuff = lookup . lookup ( "" ) ; session . getComponentPool ( ) . configure ( stuff ) ; assertEquals ( WrapDynaBean . class , stuff . getClass ( ) ) ; PropertyAccessor accessor = session . getTools ( ) . getPropertyAccessor ( ) ; ArooaClass arooaClass = accessor . getClassName ( stuff ) ; assertEquals ( WrapDynaArooaClass . class , arooaClass . getClass ( ) ) ; BeanOverview overview = arooaClass . getBeanOverview ( accessor ) ; assertEquals ( WrapDynaBeanOverview . class , overview . getClass ( ) ) ; assertTrue ( overview . hasReadableProperty ( "" ) ) ; String text = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , text ) ; String url = lookup . lookup ( "" , String . class ) ; assertEquals ( "" , url ) ; } } package org . oddjob . framework ; import junit . framework . TestCase ; public class ProxyGeneratorTest extends TestCase { interface Fruit { String getType ( ) ; } class Apple implements Fruit { @ Override public String getType ( ) { return "" ; } } interface Snack { public void eat ( ) ; } class FruitWrapper implements ComponentWrapper , Snack { final Fruit fruit ; int eaten ; String type ; public FruitWrapper ( Fruit fruit ) { this . fruit = fruit ; } @ Override public void eat ( ) { ++ eaten ; type = fruit . getType ( ) ; } } public void testGenerate ( ) { ProxyGenerator < Fruit > test = new ProxyGenerator < Fruit > ( ) ; final Fruit fruit = new Apple ( ) ; final FruitWrapper wrapper = new FruitWrapper ( fruit ) ; Object proxy = test . generate ( fruit , new WrapperFactory < ProxyGeneratorTest . Fruit > ( ) { @ Override public Class < ? > [ ] wrappingInterfacesFor ( Fruit wrapped ) { return new Class [ ] { Snack . class } ; } @ Override public ComponentWrapper wrapperFor ( Fruit wrapped , Object proxy ) { return wrapper ; } } , getClass ( ) . getClassLoader ( ) ) ; assertTrue ( proxy instanceof Fruit ) ; assertTrue ( proxy instanceof Snack ) ; assertEquals ( "" , ( ( Fruit ) proxy ) . getType ( ) ) ; ( ( Snack ) proxy ) . eat ( ) ; assertEquals ( , wrapper . eaten ) ; assertEquals ( "" , wrapper . type ) ; } interface Vegetable { String getColour ( ) ; } class Tomato implements Vegetable { @ Override public String getColour ( ) { return "" ; } } class VegetableAdaptor implements Fruit , Adaptor { final Vegetable vegetable ; public VegetableAdaptor ( Vegetable vegetable ) { this . vegetable = vegetable ; } @ Override public String getType ( ) { return vegetable . getClass ( ) . getSimpleName ( ) ; } @ Override public Object getComponent ( ) { return vegetable ; } } public void testGenerateAdaptor ( ) { ProxyGenerator < Fruit > test = new ProxyGenerator < Fruit > ( ) ; final Fruit fruit = new VegetableAdaptor ( new Tomato ( ) ) ; final FruitWrapper wrapper = new FruitWrapper ( fruit ) ; Object proxy = test . generate ( fruit , new WrapperFactory < ProxyGeneratorTest . Fruit > ( ) { @ Override public Class < ? > [ ] wrappingInterfacesFor ( Fruit wrapped ) { return new Class [ ] { Snack . class } ; } @ Override public ComponentWrapper wrapperFor ( Fruit wrapped , Object proxy ) { return wrapper ; } } , getClass ( ) . getClassLoader ( ) ) ; assertTrue ( proxy instanceof Vegetable ) ; assertTrue ( proxy instanceof Snack ) ; assertEquals ( "" , ( ( Vegetable ) proxy ) . getColour ( ) ) ; ( ( Snack ) proxy ) . eat ( ) ; assertEquals ( , wrapper . eaten ) ; assertEquals ( "" , wrapper . type ) ; } } import org . oddjob . framework . SimpleJob ; public class AJob extends SimpleJob { ClassLoader classLoader ; @ Override protected int execute ( ) throws Throwable { this . classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; System . out . println ( "" + getClass ( ) . getClassLoader ( ) ) ; System . out . println ( "" ) ; return ; } public ClassLoader getClassLoader ( ) { return classLoader ; } } package fruit ; import java . io . Serializable ; public class Orange implements Serializable , Runnable , Fruit { private static final long serialVersionUID = ; private Flavour flavour ; public void run ( ) { System . out . println ( "" + flavour ) ; } public void setFlavour ( Flavour colour ) { this . flavour = colour ; } public Flavour getFlavour ( ) { return flavour ; } } package fruit ; import java . io . Serializable ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; public interface Flavour extends Serializable { public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( Flavour . class , String . class , new Convertlet < Flavour , String > ( ) { public String convert ( Flavour from ) throws ConvertletException { return from . toString ( ) ; } } ) ; } } public String getDescription ( ) ; } package fruit ; public interface Fruit { public Flavour getFlavour ( ) ; } package fruit ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . ParsingInterceptor ; import org . oddjob . arooa . deploy . NoAnnotations ; public class FlavourTypeArooa implements ArooaBeanDescriptor { public String getComponentProperty ( ) { return null ; } public ConfiguredHow getConfiguredHow ( String property ) { return ConfiguredHow . ATTRIBUTE ; } public ParsingInterceptor getParsingInterceptor ( ) { return null ; } public String getTextProperty ( ) { return null ; } public boolean isAuto ( String property ) { return false ; } @ Override public String getFlavour ( String property ) { return null ; } @ Override public ArooaAnnotations getAnnotations ( ) { return new NoAnnotations ( ) ; } } package fruit ; public class FlavourType implements Flavour { private static final long serialVersionUID = ; private String description ; public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this . description = description ; } public String toString ( ) { return "" + description ; } } package fruit ; public interface Fruit { public Colour getColour ( ) ; } package fruit ; import org . oddjob . arooa . ArooaValue ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; public class ColourType implements ArooaValue { enum Colours { RED , GREEN } public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( String . class , Colours . class , new Convertlet < String , Colours > ( ) { public Colours convert ( String from ) throws ConvertletException { return Colours . valueOf ( from ) ; } } ) ; registry . register ( ColourType . class , Colour . class , new Convertlet < ColourType , Colour > ( ) { public Colour convert ( ColourType from ) throws ConvertletException { switch ( from . colour ) { case GREEN : return new Colour ( ) { public boolean isShiny ( ) { return false ; } @ Override public String toString ( ) { return "" ; } } ; case RED : return new Colour ( ) { public boolean isShiny ( ) { return true ; } @ Override public String toString ( ) { return "" ; } } ; default : throw new IllegalStateException ( "" ) ; } } } ) ; } } private boolean shiny ; private Colours colour ; public Colours getColour ( ) { return colour ; } public void setColour ( Colours colour ) { this . colour = colour ; } public boolean isShiny ( ) { return shiny ; } public void setShiny ( boolean shiny ) { this . shiny = shiny ; } } package fruit ; import java . io . Serializable ; public class Apple implements Serializable , Runnable , Fruit { private Colour colour ; public void run ( ) { System . out . println ( "" + colour ) ; } public void setColour ( Colour colour ) { this . colour = colour ; } public Colour getColour ( ) { return colour ; } } package fruit ; import java . io . Serializable ; import org . oddjob . arooa . convert . Convertlet ; import org . oddjob . arooa . convert . ConvertletException ; import org . oddjob . arooa . convert . ConversionProvider ; import org . oddjob . arooa . convert . ConversionRegistry ; import fruit . Colour ; import fruit . ColourType ; import fruit . ColourType . Colours ; public interface Colour extends Serializable { public static class Conversions implements ConversionProvider { public void registerWith ( ConversionRegistry registry ) { registry . register ( Colour . class , String . class , new Convertlet < Colour , String > ( ) { public String convert ( Colour from ) throws ConvertletException { return from . toString ( ) ; } } ) ; } } public boolean isShiny ( ) ; } package fruit ; import org . oddjob . arooa . ArooaAnnotations ; import org . oddjob . arooa . ArooaBeanDescriptor ; import org . oddjob . arooa . ArooaSession ; import org . oddjob . arooa . ConfiguredHow ; import org . oddjob . arooa . ParsingInterceptor ; import org . oddjob . arooa . deploy . NoAnnotations ; public class ColourTypeArooa implements ArooaBeanDescriptor { @ Override public String getComponentProperty ( ) { return null ; } @ Override public ConfiguredHow getConfiguredHow ( String property ) { return ConfiguredHow . ATTRIBUTE ; } @ Override public ParsingInterceptor getParsingInterceptor ( ) { return null ; } @ Override public String getTextProperty ( ) { return null ; } @ Override public boolean isAuto ( String property ) { return false ; } @ Override public String getFlavour ( String property ) { return null ; } @ Override public ArooaAnnotations getAnnotations ( ) { return new NoAnnotations ( ) ; } } package journal . io . api ; import java . io . File ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . util . concurrent . atomic . AtomicInteger ; import journal . io . util . IOHelper ; class DataFile implements Comparable < DataFile > { private final File file ; private final Integer dataFileId ; private final AtomicInteger length ; private volatile DataFile next ; DataFile ( File file , int number ) { this . file = file ; this . dataFileId = Integer . valueOf ( number ) ; this . length = new AtomicInteger ( ( int ) ( file . exists ( ) ? file . length ( ) : ) ) ; } File getFile ( ) { return file ; } Integer getDataFileId ( ) { return dataFileId ; } DataFile getNext ( ) { return next ; } void setNext ( DataFile next ) { this . next = next ; } int getLength ( ) { return this . length . get ( ) ; } void setLength ( int length ) { this . length . set ( length ) ; } void incrementLength ( int size ) { this . length . addAndGet ( size ) ; } RandomAccessFile openRandomAccessFile ( ) throws IOException { return new RandomAccessFile ( file , "" ) ; } boolean delete ( ) throws IOException { return file . delete ( ) ; } void move ( File targetDirectory ) throws IOException { IOHelper . moveFile ( file , targetDirectory ) ; } @ Override public int compareTo ( DataFile df ) { return dataFileId - df . dataFileId ; } @ Override public boolean equals ( Object o ) { boolean result = false ; if ( o instanceof DataFile ) { result = compareTo ( ( DataFile ) o ) == ; } return result ; } @ Override public int hashCode ( ) { return dataFileId ; } @ Override public String toString ( ) { return file . getName ( ) + "" + dataFileId + "" + length ; } } package journal . io . api ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . util . concurrent . CountDownLatch ; public final class Location implements Comparable < Location > { static final byte ANY_RECORD_TYPE = ; static final byte USER_RECORD_TYPE = ; static final byte BATCH_CONTROL_RECORD_TYPE = ; static final byte DELETED_RECORD_TYPE = ; static final int NOT_SET = - ; private volatile int dataFileId = NOT_SET ; private volatile int pointer = NOT_SET ; private volatile int size = NOT_SET ; private volatile byte type = ANY_RECORD_TYPE ; private volatile WriteCallback writeCallback = NoWriteCallback . INSTANCE ; private volatile byte [ ] data ; private CountDownLatch latch ; public Location ( ) { } public Location ( Location item ) { this . dataFileId = item . dataFileId ; this . pointer = item . pointer ; this . size = item . size ; this . type = item . type ; } public Location ( int dataFileId ) { this . dataFileId = dataFileId ; } public Location ( int dataFileId , int pointer ) { this . dataFileId = dataFileId ; this . pointer = pointer ; } public boolean isBatchControlRecord ( ) { return dataFileId != NOT_SET && type == Location . BATCH_CONTROL_RECORD_TYPE ; } public boolean isDeletedRecord ( ) { return dataFileId != NOT_SET && type == Location . DELETED_RECORD_TYPE ; } public boolean isUserRecord ( ) { return dataFileId != NOT_SET && type == Location . USER_RECORD_TYPE ; } public int getSize ( ) { return size ; } public int getPointer ( ) { return pointer ; } public int getDataFileId ( ) { return dataFileId ; } public byte [ ] getData ( ) { return data ; } void setSize ( int size ) { this . size = size ; } void setPointer ( int pointer ) { this . pointer = pointer ; } void setDataFileId ( int file ) { this . dataFileId = file ; } byte getType ( ) { return type ; } void setType ( byte type ) { this . type = type ; } CountDownLatch getLatch ( ) { return latch ; } void setLatch ( CountDownLatch latch ) { this . latch = latch ; } void setWriteCallback ( WriteCallback writeCallback ) { this . writeCallback = writeCallback ; } WriteCallback getWriteCallback ( ) { return writeCallback ; } void setData ( byte [ ] data ) { this . data = data ; } public String toString ( ) { return dataFileId + "" + pointer ; } public void writeExternal ( DataOutput dos ) throws IOException { dos . writeInt ( dataFileId ) ; dos . writeInt ( pointer ) ; dos . writeInt ( size ) ; dos . writeByte ( type ) ; } public void readExternal ( DataInput dis ) throws IOException { dataFileId = dis . readInt ( ) ; pointer = dis . readInt ( ) ; size = dis . readInt ( ) ; type = dis . readByte ( ) ; } public int compareTo ( Location o ) { Location l = o ; if ( dataFileId == l . dataFileId ) { int rc = pointer - l . pointer ; return rc ; } return dataFileId - l . dataFileId ; } public boolean equals ( Object o ) { boolean result = false ; if ( o instanceof Location ) { result = compareTo ( ( Location ) o ) == ; } return result ; } public int hashCode ( ) { return dataFileId ^ pointer ; } static class NoWriteCallback implements WriteCallback { public static final WriteCallback INSTANCE = new NoWriteCallback ( ) ; @ Override public void onSync ( Location syncedLocation ) { } @ Override public void onError ( Location location , Throwable error ) { } } } package journal . io . api ; import java . io . IOException ; import java . util . List ; import static journal . io . util . LogHelper . * ; public interface RecoveryErrorHandler { public static RecoveryErrorHandler ABORT = new AbortOnError ( ) ; public static RecoveryErrorHandler DELETE = new DeleteOnError ( ) ; public static RecoveryErrorHandler IGNORE = new IgnoreOnError ( ) ; void onError ( Journal journal , List < Location > locations ) throws IOException ; public static class AbortOnError implements RecoveryErrorHandler { @ Override public void onError ( Journal journal , List < Location > locations ) throws IOException { for ( Location location : locations ) { error ( "" + location ) ; } throw new IOException ( "" ) ; } } public static class DeleteOnError implements RecoveryErrorHandler { @ Override public void onError ( Journal journal , List < Location > locations ) throws IOException { for ( Location location : locations ) { warn ( "" + location ) ; journal . delete ( location ) ; } } } public static class IgnoreOnError implements RecoveryErrorHandler { @ Override public void onError ( Journal journal , List < Location > locations ) throws IOException { for ( Location location : locations ) { warn ( "" + location ) ; } } } } package journal . io . api ; import java . util . concurrent . locks . ReentrantLock ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . util . HashSet ; import java . util . Map . Entry ; import java . util . Set ; import java . util . concurrent . ConcurrentHashMap ; import java . util . concurrent . ConcurrentMap ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . locks . Lock ; import java . util . concurrent . locks . ReadWriteLock ; import java . util . concurrent . locks . ReentrantReadWriteLock ; import journal . io . api . Journal . WriteCommand ; import journal . io . util . IOHelper ; import static journal . io . util . LogHelper . * ; class DataFileAccessor { private final ConcurrentMap < Thread , ConcurrentMap < Integer , RandomAccessFile > > perThreadDataFileRafs = new ConcurrentHashMap < Thread , ConcurrentMap < Integer , RandomAccessFile > > ( ) ; private final ConcurrentMap < Thread , ConcurrentMap < Integer , Lock > > perThreadDataFileLocks = new ConcurrentHashMap < Thread , ConcurrentMap < Integer , Lock > > ( ) ; private final ReadWriteLock compactionLock = new ReentrantReadWriteLock ( ) ; private final Lock accessorLock = compactionLock . readLock ( ) ; private final Lock compactorMutex = compactionLock . writeLock ( ) ; private final Journal journal ; private volatile ScheduledExecutorService disposer ; public DataFileAccessor ( Journal journal ) { this . journal = journal ; } void updateLocation ( Location location , byte type , boolean sync ) throws IOException { Lock threadLock = getOrCreateLock ( Thread . currentThread ( ) , location . getDataFileId ( ) ) ; accessorLock . lock ( ) ; threadLock . lock ( ) ; try { journal . sync ( ) ; RandomAccessFile raf = getOrCreateRaf ( Thread . currentThread ( ) , location . getDataFileId ( ) ) ; if ( seekToLocation ( raf , location ) ) { raf . skipBytes ( Journal . RECORD_POINTER_SIZE + Journal . RECORD_LENGTH_SIZE ) ; raf . write ( type ) ; location . setType ( type ) ; if ( sync ) { IOHelper . sync ( raf . getFD ( ) ) ; } } else { throw new IOException ( "" + location ) ; } } finally { threadLock . unlock ( ) ; accessorLock . unlock ( ) ; } } byte [ ] readLocation ( Location location , boolean sync ) throws IOException { if ( location . getData ( ) != null && ! sync ) { return location . getData ( ) ; } else { Location read = readLocationDetails ( location . getDataFileId ( ) , location . getPointer ( ) ) ; if ( read != null && ! read . isDeletedRecord ( ) ) { return read . getData ( ) ; } else { throw new IOException ( "" + location ) ; } } } Location readLocationDetails ( int file , int pointer ) throws IOException { WriteCommand asyncWrite = journal . getInflightWrites ( ) . get ( new Location ( file , pointer ) ) ; if ( asyncWrite != null ) { Location location = new Location ( file , pointer ) ; location . setPointer ( asyncWrite . getLocation ( ) . getPointer ( ) ) ; location . setSize ( asyncWrite . getLocation ( ) . getSize ( ) ) ; location . setType ( asyncWrite . getLocation ( ) . getType ( ) ) ; location . setData ( asyncWrite . getData ( ) ) ; return location ; } else { Location location = new Location ( file , pointer ) ; Lock threadLock = getOrCreateLock ( Thread . currentThread ( ) , location . getDataFileId ( ) ) ; accessorLock . lock ( ) ; threadLock . lock ( ) ; try { RandomAccessFile raf = getOrCreateRaf ( Thread . currentThread ( ) , location . getDataFileId ( ) ) ; if ( seekToLocation ( raf , location ) ) { long position = raf . getFilePointer ( ) ; location . setPointer ( raf . readInt ( ) ) ; location . setSize ( raf . readInt ( ) ) ; location . setType ( raf . readByte ( ) ) ; if ( location . getSize ( ) > ) { location . setData ( readLocationData ( location , raf ) ) ; raf . seek ( position ) ; return location ; } else { raf . seek ( position ) ; return null ; } } else { return null ; } } finally { threadLock . unlock ( ) ; accessorLock . unlock ( ) ; } } } Location readNextLocationDetails ( Location start , int type ) throws IOException { Location asyncLocation = new Location ( start . getDataFileId ( ) , start . getPointer ( ) + ) ; WriteCommand asyncWrite = journal . getInflightWrites ( ) . get ( asyncLocation ) ; if ( asyncWrite != null && asyncWrite . getLocation ( ) . isBatchControlRecord ( ) && type != Location . BATCH_CONTROL_RECORD_TYPE ) { asyncLocation = new Location ( start . getDataFileId ( ) , start . getPointer ( ) + ) ; asyncWrite = journal . getInflightWrites ( ) . get ( asyncLocation ) ; } if ( asyncWrite != null ) { asyncLocation . setPointer ( asyncWrite . getLocation ( ) . getPointer ( ) ) ; asyncLocation . setSize ( asyncWrite . getLocation ( ) . getSize ( ) ) ; asyncLocation . setType ( asyncWrite . getLocation ( ) . getType ( ) ) ; asyncLocation . setData ( asyncWrite . getData ( ) ) ; return asyncLocation ; } else { Lock threadLock = getOrCreateLock ( Thread . currentThread ( ) , start . getDataFileId ( ) ) ; accessorLock . lock ( ) ; threadLock . lock ( ) ; try { RandomAccessFile raf = getOrCreateRaf ( Thread . currentThread ( ) , start . getDataFileId ( ) ) ; if ( seekToLocation ( raf , start ) && skipToNextLocation ( raf ) ) { Location next = new Location ( start . getDataFileId ( ) ) ; long position = ; do { position = raf . getFilePointer ( ) ; next . setPointer ( raf . readInt ( ) ) ; next . setSize ( raf . readInt ( ) ) ; next . setType ( raf . readByte ( ) ) ; if ( type != Location . ANY_RECORD_TYPE && next . getType ( ) != type ) { raf . skipBytes ( next . getSize ( ) - Journal . HEADER_SIZE ) ; } else { break ; } } while ( raf . length ( ) - raf . getFilePointer ( ) > Journal . HEADER_SIZE ) ; if ( type == Location . ANY_RECORD_TYPE || next . getType ( ) == type ) { next . setData ( readLocationData ( next , raf ) ) ; raf . seek ( position ) ; return next ; } else { raf . seek ( position ) ; return null ; } } else { return null ; } } finally { threadLock . unlock ( ) ; accessorLock . unlock ( ) ; } } } void dispose ( DataFile dataFile ) { for ( Entry < Thread , ConcurrentMap < Integer , RandomAccessFile > > threadRafs : perThreadDataFileRafs . entrySet ( ) ) { for ( Entry < Integer , RandomAccessFile > raf : threadRafs . getValue ( ) . entrySet ( ) ) { if ( raf . getKey ( ) . equals ( dataFile . getDataFileId ( ) ) ) { Lock lock = getOrCreateLock ( threadRafs . getKey ( ) , raf . getKey ( ) ) ; lock . lock ( ) ; try { removeRaf ( threadRafs . getKey ( ) , raf . getKey ( ) ) ; return ; } catch ( IOException ex ) { warn ( ex , ex . getMessage ( ) ) ; } finally { lock . unlock ( ) ; } } } } } void open ( ) { disposer = journal . getDisposer ( ) ; disposer . scheduleAtFixedRate ( new ResourceDisposer ( ) , journal . getDisposeInterval ( ) , journal . getDisposeInterval ( ) , TimeUnit . MILLISECONDS ) ; } void close ( ) { } void pause ( ) { compactorMutex . lock ( ) ; } void resume ( ) { compactorMutex . unlock ( ) ; } private boolean seekToLocation ( RandomAccessFile raf , Location destination ) throws IOException { long position = raf . getFilePointer ( ) ; int pointer = - ; int length = - ; int type = - ; if ( raf . length ( ) - position > Journal . HEADER_SIZE ) { pointer = raf . readInt ( ) ; length = raf . readInt ( ) ; type = raf . readByte ( ) ; } if ( pointer != destination . getPointer ( ) || type != destination . getType ( ) ) { raf . seek ( ) ; position = raf . getFilePointer ( ) ; if ( raf . length ( ) - position > Journal . HEADER_SIZE ) { pointer = raf . readInt ( ) ; while ( pointer != destination . getPointer ( ) ) { length = raf . readInt ( ) ; raf . skipBytes ( length - Journal . RECORD_POINTER_SIZE - Journal . RECORD_LENGTH_SIZE ) ; position = raf . getFilePointer ( ) ; if ( raf . length ( ) - position > Journal . HEADER_SIZE ) { pointer = raf . readInt ( ) ; } else { return false ; } } } else { return false ; } } raf . seek ( position ) ; return true ; } private boolean skipToNextLocation ( RandomAccessFile raf ) throws IOException { if ( raf . length ( ) - raf . getFilePointer ( ) > Journal . HEADER_SIZE ) { raf . skipBytes ( Journal . RECORD_POINTER_SIZE ) ; raf . skipBytes ( raf . readInt ( ) - Journal . RECORD_POINTER_SIZE - Journal . RECORD_LENGTH_SIZE ) ; if ( raf . length ( ) - raf . getFilePointer ( ) > Journal . HEADER_SIZE ) { return true ; } else { return false ; } } else { return false ; } } private byte [ ] readLocationData ( Location location , RandomAccessFile raf ) throws IOException { if ( location . isBatchControlRecord ( ) ) { int batchSize = raf . readInt ( ) ; byte [ ] data = new byte [ Journal . CHECKSUM_SIZE + batchSize ] ; raf . readFully ( data ) ; return data ; } else { byte [ ] data = new byte [ location . getSize ( ) - Journal . HEADER_SIZE ] ; raf . readFully ( data ) ; return data ; } } private RandomAccessFile getOrCreateRaf ( Thread thread , Integer file ) throws IOException { ConcurrentMap < Integer , RandomAccessFile > rafs = perThreadDataFileRafs . get ( thread ) ; if ( rafs == null ) { rafs = new ConcurrentHashMap < Integer , RandomAccessFile > ( ) ; perThreadDataFileRafs . put ( thread , rafs ) ; } RandomAccessFile raf = rafs . get ( file ) ; if ( raf == null ) { raf = journal . getDataFiles ( ) . get ( file ) . openRandomAccessFile ( ) ; rafs . put ( file , raf ) ; } return raf ; } private void removeRaf ( Thread thread , Integer file ) throws IOException { RandomAccessFile raf = perThreadDataFileRafs . get ( thread ) . remove ( file ) ; raf . close ( ) ; } private Lock getOrCreateLock ( Thread thread , Integer file ) { ConcurrentMap < Integer , Lock > locks = perThreadDataFileLocks . get ( thread ) ; if ( locks == null ) { locks = new ConcurrentHashMap < Integer , Lock > ( ) ; perThreadDataFileLocks . put ( thread , locks ) ; } Lock lock = locks . get ( file ) ; if ( lock == null ) { lock = new ReentrantLock ( ) ; locks . put ( file , lock ) ; } return lock ; } private class ResourceDisposer implements Runnable { public void run ( ) { Set < Thread > deadThreads = new HashSet < Thread > ( ) ; for ( Entry < Thread , ConcurrentMap < Integer , RandomAccessFile > > threadRafs : perThreadDataFileRafs . entrySet ( ) ) { for ( Entry < Integer , RandomAccessFile > raf : threadRafs . getValue ( ) . entrySet ( ) ) { Lock lock = getOrCreateLock ( threadRafs . getKey ( ) , raf . getKey ( ) ) ; if ( lock . tryLock ( ) ) { try { removeRaf ( threadRafs . getKey ( ) , raf . getKey ( ) ) ; if ( ! threadRafs . getKey ( ) . isAlive ( ) ) { deadThreads . add ( threadRafs . getKey ( ) ) ; } } catch ( IOException ex ) { warn ( ex , ex . getMessage ( ) ) ; } finally { lock . unlock ( ) ; } } } } for ( Thread deadThread : deadThreads ) { perThreadDataFileRafs . remove ( deadThread ) ; perThreadDataFileLocks . remove ( deadThread ) ; } } } } package journal . io . api ; import java . io . File ; import java . io . FilenameFilter ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . nio . ByteBuffer ; import java . util . Arrays ; import java . util . Collection ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map . Entry ; import java . util . NoSuchElementException ; import java . util . Queue ; import java . util . Set ; import java . util . concurrent . ConcurrentLinkedQueue ; import java . util . concurrent . ConcurrentNavigableMap ; import java . util . concurrent . ConcurrentSkipListMap ; import java . util . concurrent . CountDownLatch ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . Executor ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . Future ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ThreadFactory ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . TimeoutException ; import java . util . concurrent . atomic . AtomicLong ; import java . util . zip . Adler32 ; import java . util . zip . Checksum ; import journal . io . util . IOHelper ; import static journal . io . util . LogHelper . * ; public class Journal { static final int RECORD_POINTER_SIZE = ; static final int RECORD_LENGTH_SIZE = ; static final int TYPE_SIZE = ; static final int HEADER_SIZE = RECORD_POINTER_SIZE + RECORD_LENGTH_SIZE + TYPE_SIZE ; static final int BATCH_SIZE = ; static final int CHECKSUM_SIZE = ; static final int BATCH_CONTROL_RECORD_SIZE = HEADER_SIZE + BATCH_SIZE + CHECKSUM_SIZE ; static final String WRITER_THREAD_GROUP = "" ; static final String WRITER_THREAD = "" ; static final String DISPOSER_THREAD_GROUP = "" ; static final String DISPOSER_THREAD = "" ; static final int PRE_START_POINTER = - ; static final String DEFAULT_DIRECTORY = "" ; static final String DEFAULT_ARCHIVE_DIRECTORY = "" ; static final String DEFAULT_FILE_PREFIX = "" ; static final String DEFAULT_FILE_SUFFIX = "" ; static final int DEFAULT_MAX_FILE_LENGTH = * * ; static final int DEFAULT_DISPOSE_INTERVAL = * ; static final int MIN_FILE_LENGTH = ; static final int DEFAULT_MAX_BATCH_SIZE = DEFAULT_MAX_FILE_LENGTH ; private final ConcurrentNavigableMap < Integer , DataFile > dataFiles = new ConcurrentSkipListMap < Integer , DataFile > ( ) ; private final ConcurrentNavigableMap < Location , WriteCommand > inflightWrites = new ConcurrentSkipListMap < Location , WriteCommand > ( ) ; private final AtomicLong totalLength = new AtomicLong ( ) ; private volatile Location lastAppendLocation ; private volatile File directory = new File ( DEFAULT_DIRECTORY ) ; private volatile File directoryArchive = new File ( DEFAULT_ARCHIVE_DIRECTORY ) ; private volatile String filePrefix = DEFAULT_FILE_PREFIX ; private volatile String fileSuffix = DEFAULT_FILE_SUFFIX ; private volatile int maxWriteBatchSize = DEFAULT_MAX_BATCH_SIZE ; private volatile int maxFileLength = DEFAULT_MAX_FILE_LENGTH ; private volatile long disposeInterval = DEFAULT_DISPOSE_INTERVAL ; private volatile boolean physicalSync = false ; private volatile boolean checksum = true ; private volatile boolean managedWriter ; private volatile boolean managedDisposer ; private volatile Executor writer ; private volatile ScheduledExecutorService disposer ; private volatile DataFileAppender appender ; private volatile DataFileAccessor accessor ; private volatile boolean opened ; private volatile boolean archiveFiles ; private RecoveryErrorHandler recoveryErrorHandler ; private ReplicationTarget replicationTarget ; public synchronized void open ( ) throws IOException { if ( opened ) { return ; } if ( maxFileLength < MIN_FILE_LENGTH ) { throw new IllegalStateException ( "" + MIN_FILE_LENGTH ) ; } if ( maxWriteBatchSize > maxFileLength ) { throw new IllegalStateException ( "" + maxFileLength ) ; } if ( writer == null ) { managedWriter = true ; writer = Executors . newSingleThreadExecutor ( new JournalThreadFactory ( WRITER_THREAD_GROUP , WRITER_THREAD ) ) ; } if ( disposer == null ) { managedDisposer = true ; disposer = Executors . newSingleThreadScheduledExecutor ( new JournalThreadFactory ( DISPOSER_THREAD_GROUP , DISPOSER_THREAD ) ) ; } if ( recoveryErrorHandler == null ) { recoveryErrorHandler = RecoveryErrorHandler . ABORT ; } opened = true ; accessor = new DataFileAccessor ( this ) ; accessor . open ( ) ; appender = new DataFileAppender ( this ) ; appender . open ( ) ; File [ ] files = directory . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String n ) { return dir . equals ( directory ) && n . startsWith ( filePrefix ) && n . endsWith ( fileSuffix ) ; } } ) ; Arrays . sort ( files , new Comparator < File > ( ) { @ Override public int compare ( File f1 , File f2 ) { String name1 = f1 . getName ( ) ; int index1 = Integer . parseInt ( name1 . substring ( filePrefix . length ( ) , name1 . length ( ) - fileSuffix . length ( ) ) ) ; String name2 = f2 . getName ( ) ; int index2 = Integer . parseInt ( name2 . substring ( filePrefix . length ( ) , name2 . length ( ) - fileSuffix . length ( ) ) ) ; return index1 - index2 ; } } ) ; if ( files != null && files . length > ) { for ( int i = ; i < files . length ; i ++ ) { try { File file = files [ i ] ; String name = file . getName ( ) ; int index = Integer . parseInt ( name . substring ( filePrefix . length ( ) , name . length ( ) - fileSuffix . length ( ) ) ) ; DataFile dataFile = new DataFile ( file , index ) ; if ( ! dataFiles . isEmpty ( ) ) { dataFiles . lastEntry ( ) . getValue ( ) . setNext ( dataFile ) ; } dataFiles . put ( dataFile . getDataFileId ( ) , dataFile ) ; totalLength . addAndGet ( dataFile . getLength ( ) ) ; } catch ( NumberFormatException e ) { } } lastAppendLocation = recoveryCheck ( ) ; } else { lastAppendLocation = new Location ( , PRE_START_POINTER ) ; } } public synchronized void close ( ) throws IOException { if ( ! opened ) { return ; } opened = false ; accessor . close ( ) ; appender . close ( ) ; dataFiles . clear ( ) ; inflightWrites . clear ( ) ; if ( managedWriter ) { ( ( ExecutorService ) writer ) . shutdown ( ) ; writer = null ; } if ( managedDisposer ) { disposer . shutdown ( ) ; disposer = null ; } } public synchronized void compact ( ) throws IOException { if ( ! opened ) { return ; } else { accessor . pause ( ) ; try { for ( DataFile file : dataFiles . values ( ) ) { if ( file . getDataFileId ( ) >= lastAppendLocation . getDataFileId ( ) ) { continue ; } else { Location firstUserLocation = goToFirstLocation ( file , Location . USER_RECORD_TYPE , false ) ; if ( firstUserLocation == null ) { removeDataFile ( file ) ; } else { Location firstDeletedLocation = goToFirstLocation ( file , Location . DELETED_RECORD_TYPE , false ) ; if ( firstDeletedLocation != null ) { compactDataFile ( file , firstUserLocation ) ; } } } } } finally { accessor . resume ( ) ; } } } public void sync ( ) throws IOException { try { appender . sync ( ) . get ( ) ; if ( appender . getAsyncException ( ) != null ) { throw new IOException ( appender . getAsyncException ( ) ) ; } } catch ( Exception ex ) { throw new IllegalStateException ( ex . getMessage ( ) , ex ) ; } } public byte [ ] read ( Location location , ReadType read ) throws IOException , IllegalStateException { return accessor . readLocation ( location , read . equals ( ReadType . SYNC ) ? true : false ) ; } public Location write ( byte [ ] data , WriteType write ) throws IOException , IllegalStateException { return write ( data , write , Location . NoWriteCallback . INSTANCE ) ; } public Location write ( byte [ ] data , WriteType write , WriteCallback callback ) throws IOException , IllegalStateException { Location loc = appender . storeItem ( data , Location . USER_RECORD_TYPE , write . equals ( WriteType . SYNC ) ? true : false , callback ) ; return loc ; } public void delete ( Location location ) throws IOException , IllegalStateException { accessor . updateLocation ( location , Location . DELETED_RECORD_TYPE , true ) ; } public Iterable < Location > redo ( ) throws IOException { Entry < Integer , DataFile > firstEntry = dataFiles . firstEntry ( ) ; if ( firstEntry == null ) { return new Redo ( null ) ; } return new Redo ( goToFirstLocation ( firstEntry . getValue ( ) , Location . USER_RECORD_TYPE , true ) ) ; } public Iterable < Location > redo ( Location start ) throws IOException { return new Redo ( start ) ; } public Iterable < Location > undo ( ) throws IOException { return new Undo ( redo ( ) ) ; } public Iterable < Location > undo ( Location end ) throws IOException { return new Undo ( redo ( end ) ) ; } public Set < File > getFiles ( ) { Set < File > result = new HashSet < File > ( ) ; for ( DataFile dataFile : dataFiles . values ( ) ) { result . add ( dataFile . getFile ( ) ) ; } return result ; } public int getMaxFileLength ( ) { return maxFileLength ; } public void setMaxFileLength ( int maxFileLength ) { this . maxFileLength = maxFileLength ; } public File getDirectory ( ) { return directory ; } public void setDirectory ( File directory ) { this . directory = directory ; } public String getFilePrefix ( ) { return filePrefix ; } public void setFilePrefix ( String filePrefix ) { this . filePrefix = filePrefix ; } public File getDirectoryArchive ( ) { return directoryArchive ; } public void setDirectoryArchive ( File directoryArchive ) { this . directoryArchive = directoryArchive ; } public boolean isArchiveFiles ( ) { return archiveFiles ; } public void setArchiveFiles ( boolean archiveFiles ) { this . archiveFiles = archiveFiles ; } public void setReplicationTarget ( ReplicationTarget replicationTarget ) { this . replicationTarget = replicationTarget ; } public ReplicationTarget getReplicationTarget ( ) { return replicationTarget ; } public String getFileSuffix ( ) { return fileSuffix ; } public void setFileSuffix ( String fileSuffix ) { this . fileSuffix = fileSuffix ; } public boolean isChecksum ( ) { return checksum ; } public void setChecksum ( boolean checksumWrites ) { this . checksum = checksumWrites ; } public boolean isPhysicalSync ( ) { return physicalSync ; } public void setPhysicalSync ( boolean physicalSync ) { this . physicalSync = physicalSync ; } public int getMaxWriteBatchSize ( ) { return maxWriteBatchSize ; } public void setMaxWriteBatchSize ( int maxWriteBatchSize ) { this . maxWriteBatchSize = maxWriteBatchSize ; } public void setDisposeInterval ( long disposeInterval ) { this . disposeInterval = disposeInterval ; } public long getDisposeInterval ( ) { return disposeInterval ; } public void setWriter ( Executor writer ) { this . writer = writer ; this . managedWriter = false ; } public void setDisposer ( ScheduledExecutorService disposer ) { this . disposer = disposer ; this . managedDisposer = false ; } public void setRecoveryErrorHandler ( RecoveryErrorHandler recoveryErrorHandler ) { this . recoveryErrorHandler = recoveryErrorHandler ; } public String toString ( ) { return directory . toString ( ) ; } Executor getWriter ( ) { return writer ; } ScheduledExecutorService getDisposer ( ) { return disposer ; } ConcurrentNavigableMap < Integer , DataFile > getDataFiles ( ) { return dataFiles ; } ConcurrentNavigableMap < Location , WriteCommand > getInflightWrites ( ) { return inflightWrites ; } DataFile getCurrentWriteFile ( ) throws IOException { if ( dataFiles . isEmpty ( ) ) { rotateWriteFile ( ) ; } return dataFiles . lastEntry ( ) . getValue ( ) ; } DataFile rotateWriteFile ( ) { int nextNum = ! dataFiles . isEmpty ( ) ? dataFiles . lastEntry ( ) . getValue ( ) . getDataFileId ( ) . intValue ( ) + : ; File file = getFile ( nextNum ) ; DataFile nextWriteFile = new DataFile ( file , nextNum ) ; if ( ! dataFiles . isEmpty ( ) ) { dataFiles . lastEntry ( ) . getValue ( ) . setNext ( nextWriteFile ) ; } dataFiles . put ( nextWriteFile . getDataFileId ( ) , nextWriteFile ) ; return nextWriteFile ; } Location getLastAppendLocation ( ) { return lastAppendLocation ; } void setLastAppendLocation ( Location location ) { this . lastAppendLocation = location ; } void addToTotalLength ( int size ) { totalLength . addAndGet ( size ) ; } private Location goToFirstLocation ( DataFile file , byte type , boolean goToNextFile ) throws IOException , IllegalStateException { Location start = accessor . readLocationDetails ( file . getDataFileId ( ) , ) ; if ( start != null && ( start . getType ( ) == type || type == Location . ANY_RECORD_TYPE ) ) { return start ; } else if ( start != null ) { return goToNextLocation ( start , type , goToNextFile ) ; } else { return null ; } } private Location goToNextLocation ( Location start , byte type , boolean goToNextFile ) throws IOException { DataFile currentDataFile = getDataFile ( start ) ; Location currentLocation = new Location ( start ) ; Location result = null ; while ( result == null ) { currentLocation = accessor . readNextLocationDetails ( currentLocation , type ) ; if ( currentLocation != null ) { result = currentLocation ; } else { if ( goToNextFile ) { currentDataFile = currentDataFile . getNext ( ) ; if ( currentDataFile != null ) { result = goToFirstLocation ( currentDataFile , type , true ) ; } else { break ; } } else { break ; } } } return result ; } private File getFile ( int nextNum ) { String fileName = filePrefix + nextNum + fileSuffix ; File file = new File ( directory , fileName ) ; return file ; } private DataFile getDataFile ( Location item ) throws IOException { Integer key = Integer . valueOf ( item . getDataFileId ( ) ) ; DataFile dataFile = dataFiles . get ( key ) ; if ( dataFile == null ) { error ( "" , key , dataFiles ) ; throw new IOException ( "" + getFile ( item . getDataFileId ( ) ) ) ; } return dataFile ; } private void removeDataFile ( DataFile dataFile ) throws IOException { dataFiles . remove ( dataFile . getDataFileId ( ) ) ; totalLength . addAndGet ( - dataFile . getLength ( ) ) ; if ( archiveFiles ) { dataFile . move ( getDirectoryArchive ( ) ) ; } else { boolean deleted = dataFile . delete ( ) ; if ( ! deleted ) { warn ( "" , dataFile . getFile ( ) ) ; } } } private void compactDataFile ( DataFile currentFile , Location firstUserLocation ) throws IOException { DataFile tmpFile = new DataFile ( new File ( currentFile . getFile ( ) . getParent ( ) , filePrefix + currentFile . getDataFileId ( ) + "" + fileSuffix ) , currentFile . getDataFileId ( ) ) ; RandomAccessFile raf = tmpFile . openRandomAccessFile ( ) ; try { Location currentUserLocation = firstUserLocation ; WriteBatch batch = new WriteBatch ( tmpFile , ) ; batch . prepareBatch ( ) ; while ( currentUserLocation != null ) { byte [ ] data = accessor . readLocation ( currentUserLocation , false ) ; WriteCommand write = new WriteCommand ( currentUserLocation , data , true ) ; batch . appendBatch ( write ) ; currentUserLocation = goToNextLocation ( currentUserLocation , Location . USER_RECORD_TYPE , false ) ; } batch . perform ( raf , true , true , null ) ; } finally { if ( raf != null ) { raf . close ( ) ; } } accessor . dispose ( currentFile ) ; totalLength . addAndGet ( - currentFile . getLength ( ) ) ; totalLength . addAndGet ( tmpFile . getLength ( ) ) ; IOHelper . copyFile ( tmpFile . getFile ( ) , currentFile . getFile ( ) ) ; IOHelper . deleteFile ( tmpFile . getFile ( ) ) ; } private Location recoveryCheck ( ) throws IOException { List < Location > checksummedLocations = new LinkedList < Location > ( ) ; Location currentBatch = goToFirstLocation ( dataFiles . firstEntry ( ) . getValue ( ) , Location . BATCH_CONTROL_RECORD_TYPE , false ) ; Location lastBatch = currentBatch ; while ( currentBatch != null ) { if ( isChecksum ( ) ) { ByteBuffer currentBatchBuffer = ByteBuffer . wrap ( accessor . readLocation ( currentBatch , false ) ) ; Checksum actualChecksum = new Adler32 ( ) ; Location nextLocation = goToNextLocation ( currentBatch , Location . ANY_RECORD_TYPE , true ) ; long expectedChecksum = currentBatchBuffer . getLong ( ) ; checksummedLocations . clear ( ) ; while ( nextLocation != null && nextLocation . getType ( ) != Location . BATCH_CONTROL_RECORD_TYPE ) { byte data [ ] = accessor . readLocation ( nextLocation , false ) ; actualChecksum . update ( data , , data . length ) ; checksummedLocations . add ( nextLocation ) ; nextLocation = goToNextLocation ( nextLocation , Location . ANY_RECORD_TYPE , true ) ; } if ( expectedChecksum != actualChecksum . getValue ( ) ) { recoveryErrorHandler . onError ( this , checksummedLocations ) ; } if ( nextLocation != null ) { lastBatch = nextLocation ; } currentBatch = nextLocation ; } else { lastBatch = currentBatch ; currentBatch = goToNextLocation ( currentBatch , Location . BATCH_CONTROL_RECORD_TYPE , true ) ; } } Location currentUserRecord = lastBatch ; while ( true ) { Location next = goToNextLocation ( currentUserRecord , Location . USER_RECORD_TYPE , false ) ; if ( next != null ) { currentUserRecord = next ; } else { break ; } } return currentUserRecord ; } public static enum ReadType { SYNC , ASYNC ; } public static enum WriteType { SYNC , ASYNC ; } static class WriteBatch { private static byte [ ] EMPTY_BUFFER = new byte [ ] ; private final DataFile dataFile ; private final Queue < WriteCommand > writes = new ConcurrentLinkedQueue < WriteCommand > ( ) ; private final CountDownLatch latch = new CountDownLatch ( ) ; private volatile int offset ; private volatile int pointer ; private volatile int size ; WriteBatch ( ) { this . dataFile = null ; this . offset = - ; this . pointer = - ; } WriteBatch ( DataFile dataFile , int pointer ) throws IOException { this . dataFile = dataFile ; this . offset = dataFile . getLength ( ) ; this . pointer = pointer ; this . size = BATCH_CONTROL_RECORD_SIZE ; } boolean canBatch ( WriteCommand write , int maxWriteBatchSize , int maxFileLength ) throws IOException { int thisBatchSize = size + write . location . getSize ( ) ; int thisFileLength = offset + thisBatchSize ; if ( thisBatchSize > maxWriteBatchSize || thisFileLength > maxFileLength ) { return false ; } else { return true ; } } WriteCommand prepareBatch ( ) throws IOException { WriteCommand controlRecord = new WriteCommand ( new Location ( ) , EMPTY_BUFFER , false ) ; controlRecord . location . setType ( Location . BATCH_CONTROL_RECORD_TYPE ) ; controlRecord . location . setSize ( Journal . BATCH_CONTROL_RECORD_SIZE ) ; controlRecord . location . setDataFileId ( dataFile . getDataFileId ( ) ) ; controlRecord . location . setPointer ( pointer ) ; size = controlRecord . location . getSize ( ) ; dataFile . incrementLength ( size ) ; writes . offer ( controlRecord ) ; return controlRecord ; } void appendBatch ( WriteCommand writeRecord ) throws IOException { size += writeRecord . location . getSize ( ) ; dataFile . incrementLength ( writeRecord . location . getSize ( ) ) ; writes . offer ( writeRecord ) ; } void perform ( RandomAccessFile file , boolean checksum , boolean physicalSync , ReplicationTarget replicationTarget ) throws IOException { ByteBuffer buffer = ByteBuffer . allocate ( size ) ; Checksum adler32 = new Adler32 ( ) ; WriteCommand control = writes . peek ( ) ; buffer . putInt ( control . location . getPointer ( ) ) ; buffer . putInt ( BATCH_CONTROL_RECORD_SIZE ) ; buffer . put ( Location . BATCH_CONTROL_RECORD_TYPE ) ; buffer . putInt ( ) ; buffer . putLong ( ) ; Iterator < WriteCommand > commands = writes . iterator ( ) ; commands . next ( ) ; while ( commands . hasNext ( ) ) { WriteCommand current = commands . next ( ) ; buffer . putInt ( current . location . getPointer ( ) ) ; buffer . putInt ( current . location . getSize ( ) ) ; buffer . put ( current . location . getType ( ) ) ; buffer . put ( current . getData ( ) ) ; if ( checksum ) { adler32 . update ( current . getData ( ) , , current . getData ( ) . length ) ; } } buffer . position ( Journal . HEADER_SIZE ) ; buffer . putInt ( size - Journal . BATCH_CONTROL_RECORD_SIZE ) ; if ( checksum ) { buffer . putLong ( adler32 . getValue ( ) ) ; } file . seek ( offset ) ; file . write ( buffer . array ( ) , , size ) ; if ( physicalSync ) { IOHelper . sync ( file . getFD ( ) ) ; } try { if ( replicationTarget != null ) { replicationTarget . replicate ( control . location , buffer . array ( ) ) ; } } catch ( Throwable ex ) { warn ( "" , ex ) ; } } DataFile getDataFile ( ) { return dataFile ; } int getSize ( ) { return size ; } CountDownLatch getLatch ( ) { return latch ; } Collection < WriteCommand > getWrites ( ) { return Collections . unmodifiableCollection ( writes ) ; } boolean isEmpty ( ) { return writes . isEmpty ( ) ; } int incrementAndGetPointer ( ) { return ++ pointer ; } } static class WriteCommand { private final Location location ; private final boolean sync ; private volatile byte [ ] data ; WriteCommand ( Location location , byte [ ] data , boolean sync ) { this . location = location ; this . data = data ; this . sync = sync ; } public Location getLocation ( ) { return location ; } byte [ ] getData ( ) { return data ; } boolean isSync ( ) { return sync ; } } static class WriteFuture implements Future < Boolean > { private final CountDownLatch latch ; WriteFuture ( CountDownLatch latch ) { this . latch = latch ; } public boolean cancel ( boolean mayInterruptIfRunning ) { throw new UnsupportedOperationException ( "" ) ; } public boolean isCancelled ( ) { throw new UnsupportedOperationException ( "" ) ; } public boolean isDone ( ) { return latch . getCount ( ) == ; } public Boolean get ( ) throws InterruptedException , ExecutionException { latch . await ( ) ; return true ; } public Boolean get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { boolean success = latch . await ( timeout , unit ) ; return success ; } } private static class JournalThreadFactory implements ThreadFactory { private final String groupName ; private final String threadName ; public JournalThreadFactory ( String groupName , String threadName ) { this . groupName = groupName ; this . threadName = threadName ; } @ Override public Thread newThread ( Runnable r ) { return new Thread ( new ThreadGroup ( groupName ) , r , threadName ) ; } } private class Redo implements Iterable < Location > { private final Location start ; public Redo ( Location start ) { this . start = start ; } public Iterator < Location > iterator ( ) { return new Iterator < Location > ( ) { private Location current = null ; private Location next = start ; public boolean hasNext ( ) { return next != null ; } public Location next ( ) { if ( next != null ) { try { current = next ; next = goToNextLocation ( current , Location . USER_RECORD_TYPE , true ) ; return current ; } catch ( IOException ex ) { throw new IllegalStateException ( ex . getMessage ( ) , ex ) ; } } else { throw new NoSuchElementException ( ) ; } } public void remove ( ) { if ( current != null ) { try { delete ( current ) ; current = null ; } catch ( IOException ex ) { throw new IllegalStateException ( ex . getMessage ( ) , ex ) ; } } else { throw new IllegalStateException ( "" ) ; } } } ; } } private class Undo implements Iterable < Location > { private final Object [ ] stack ; private final int start ; public Undo ( Iterable < Location > redo ) { Object [ ] stack = new Object [ ] ; int pointer = ; Iterator < Location > itr = redo . iterator ( ) ; while ( itr . hasNext ( ) ) { Location location = itr . next ( ) ; stack [ pointer ] = location ; if ( pointer == ) { Object [ ] tmp = new Object [ ] ; tmp [ ] = stack ; stack = tmp ; pointer = ; } else { pointer -- ; } } this . start = pointer + ; this . stack = stack ; } @ Override public Iterator < Location > iterator ( ) { return new Iterator < Location > ( ) { private int pointer = start ; private Object [ ] ref = stack ; private Location current ; @ Override public boolean hasNext ( ) { return ref [ pointer ] != null ; } @ Override public Location next ( ) { Object next = ref [ pointer ] ; if ( ! ( ref [ pointer ] instanceof Location ) ) { ref = ( Object [ ] ) ref [ pointer ] ; if ( ref == null ) { throw new NoSuchElementException ( ) ; } pointer = ; return next ( ) ; } pointer ++ ; return current = ( Location ) next ; } @ Override public void remove ( ) { if ( current == null ) { throw new IllegalStateException ( "" ) ; } try { delete ( current ) ; current = null ; } catch ( IOException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } } } ; } } } package journal . io . api ; import journal . io . api . Journal . WriteBatch ; import journal . io . api . Journal . WriteCommand ; import journal . io . api . Journal . WriteFuture ; import java . io . IOException ; import java . io . InterruptedIOException ; import java . io . RandomAccessFile ; import java . util . Queue ; import java . util . concurrent . ConcurrentLinkedQueue ; import java . util . concurrent . Executor ; import java . util . concurrent . Future ; import java . util . concurrent . atomic . AtomicBoolean ; import java . util . concurrent . atomic . AtomicReference ; import static journal . io . util . LogHelper . * ; class DataFileAppender { private final int SPIN_RETRIES = ; private final int SPIN_BACKOFF = ; private final Queue < WriteBatch > batchQueue = new ConcurrentLinkedQueue < WriteBatch > ( ) ; private final AtomicReference < Exception > asyncException = new AtomicReference < Exception > ( ) ; private final AtomicBoolean batching = new AtomicBoolean ( false ) ; private final AtomicBoolean writing = new AtomicBoolean ( false ) ; private final Journal journal ; private volatile WriteBatch nextWriteBatch ; private volatile DataFile lastAppendDataFile ; private volatile RandomAccessFile lastAppendRaf ; private volatile Executor writer ; DataFileAppender ( Journal journal ) { this . journal = journal ; } Location storeItem ( byte [ ] data , byte type , boolean sync , WriteCallback callback ) throws IOException { int size = Journal . HEADER_SIZE + data . length ; Location location = new Location ( ) ; location . setSize ( size ) ; location . setType ( type ) ; location . setWriteCallback ( callback ) ; WriteCommand write = new WriteCommand ( location , data , sync ) ; location = enqueueBatch ( write ) ; if ( sync ) { try { location . getLatch ( ) . await ( ) ; } catch ( InterruptedException e ) { throw new InterruptedIOException ( ) ; } } return location ; } Future < Boolean > sync ( ) throws IOException { int spinnings = ; int limit = SPIN_RETRIES ; while ( true ) { if ( asyncException . get ( ) != null ) { throw new IOException ( asyncException . get ( ) ) ; } try { if ( batching . compareAndSet ( false , true ) ) { try { Future result = null ; if ( nextWriteBatch != null ) { result = new WriteFuture ( nextWriteBatch . getLatch ( ) ) ; batchQueue . offer ( nextWriteBatch ) ; signalBatch ( ) ; nextWriteBatch = null ; } else { result = new WriteFuture ( journal . getLastAppendLocation ( ) . getLatch ( ) ) ; } return result ; } finally { batching . set ( false ) ; } } else { if ( spinnings <= limit ) { spinnings ++ ; continue ; } else { Thread . sleep ( SPIN_BACKOFF ) ; continue ; } } } catch ( InterruptedException ex ) { throw new IllegalStateException ( ex . getMessage ( ) , ex ) ; } } } private Location enqueueBatch ( WriteCommand writeRecord ) throws IOException { WriteBatch currentBatch = null ; int spinnings = ; int limit = SPIN_RETRIES ; while ( true ) { if ( asyncException . get ( ) != null ) { throw new IOException ( asyncException . get ( ) ) ; } try { if ( batching . compareAndSet ( false , true ) ) { boolean hasNewBatch = false ; try { if ( nextWriteBatch == null ) { DataFile file = journal . getCurrentWriteFile ( ) ; boolean canBatch = false ; currentBatch = new WriteBatch ( file , journal . getLastAppendLocation ( ) . getPointer ( ) + ) ; canBatch = currentBatch . canBatch ( writeRecord , journal . getMaxWriteBatchSize ( ) , journal . getMaxFileLength ( ) ) ; if ( ! canBatch ) { file = journal . rotateWriteFile ( ) ; currentBatch = new WriteBatch ( file , ) ; } WriteCommand controlRecord = currentBatch . prepareBatch ( ) ; writeRecord . getLocation ( ) . setDataFileId ( file . getDataFileId ( ) ) ; writeRecord . getLocation ( ) . setPointer ( currentBatch . incrementAndGetPointer ( ) ) ; writeRecord . getLocation ( ) . setLatch ( currentBatch . getLatch ( ) ) ; currentBatch . appendBatch ( writeRecord ) ; if ( ! writeRecord . isSync ( ) ) { journal . getInflightWrites ( ) . put ( controlRecord . getLocation ( ) , controlRecord ) ; journal . getInflightWrites ( ) . put ( writeRecord . getLocation ( ) , writeRecord ) ; nextWriteBatch = currentBatch ; } else { batchQueue . offer ( currentBatch ) ; hasNewBatch = true ; } journal . setLastAppendLocation ( writeRecord . getLocation ( ) ) ; break ; } else { boolean canBatch = nextWriteBatch . canBatch ( writeRecord , journal . getMaxWriteBatchSize ( ) , journal . getMaxFileLength ( ) ) ; writeRecord . getLocation ( ) . setDataFileId ( nextWriteBatch . getDataFile ( ) . getDataFileId ( ) ) ; writeRecord . getLocation ( ) . setPointer ( nextWriteBatch . incrementAndGetPointer ( ) ) ; writeRecord . getLocation ( ) . setLatch ( nextWriteBatch . getLatch ( ) ) ; if ( canBatch && ! writeRecord . isSync ( ) ) { nextWriteBatch . appendBatch ( writeRecord ) ; journal . getInflightWrites ( ) . put ( writeRecord . getLocation ( ) , writeRecord ) ; journal . setLastAppendLocation ( writeRecord . getLocation ( ) ) ; break ; } else if ( canBatch && writeRecord . isSync ( ) ) { nextWriteBatch . appendBatch ( writeRecord ) ; journal . setLastAppendLocation ( writeRecord . getLocation ( ) ) ; batchQueue . offer ( nextWriteBatch ) ; nextWriteBatch = null ; hasNewBatch = true ; break ; } else { batchQueue . offer ( nextWriteBatch ) ; nextWriteBatch = null ; hasNewBatch = true ; } } } finally { batching . set ( false ) ; if ( hasNewBatch ) { signalBatch ( ) ; } } } else { if ( spinnings <= limit ) { spinnings ++ ; continue ; } else { Thread . sleep ( SPIN_BACKOFF ) ; continue ; } } } catch ( InterruptedException ex ) { throw new IllegalStateException ( ex . getMessage ( ) , ex ) ; } } return writeRecord . getLocation ( ) ; } void open ( ) { writer = journal . getWriter ( ) ; } void close ( ) throws IOException { try { while ( batching . get ( ) == true ) { Thread . sleep ( SPIN_BACKOFF ) ; } if ( nextWriteBatch != null ) { batchQueue . offer ( nextWriteBatch ) ; signalBatch ( ) ; nextWriteBatch . getLatch ( ) . await ( ) ; nextWriteBatch = null ; } journal . setLastAppendLocation ( null ) ; if ( lastAppendRaf != null ) { lastAppendRaf . close ( ) ; } } catch ( InterruptedException e ) { throw new InterruptedIOException ( ) ; } } public Exception getAsyncException ( ) { return asyncException . get ( ) ; } private void signalBatch ( ) { writer . execute ( new Runnable ( ) { @ Override public void run ( ) { while ( writing . compareAndSet ( false , true ) == false ) { try { Thread . sleep ( SPIN_BACKOFF ) ; } catch ( Exception ex ) { } } WriteBatch wb = batchQueue . poll ( ) ; try { while ( wb != null ) { if ( ! wb . isEmpty ( ) ) { boolean newOrRotated = lastAppendDataFile != wb . getDataFile ( ) ; if ( newOrRotated ) { if ( lastAppendRaf != null ) { lastAppendRaf . close ( ) ; } lastAppendDataFile = wb . getDataFile ( ) ; lastAppendRaf = lastAppendDataFile . openRandomAccessFile ( ) ; } wb . perform ( lastAppendRaf , journal . isChecksum ( ) , journal . isPhysicalSync ( ) , journal . getReplicationTarget ( ) ) ; journal . addToTotalLength ( wb . getSize ( ) ) ; for ( WriteCommand current : wb . getWrites ( ) ) { try { current . getLocation ( ) . getWriteCallback ( ) . onSync ( current . getLocation ( ) ) ; } catch ( Throwable ex ) { warn ( ex , ex . getMessage ( ) ) ; } journal . getInflightWrites ( ) . remove ( current . getLocation ( ) ) ; } wb . getLatch ( ) . countDown ( ) ; } wb = batchQueue . poll ( ) ; } } catch ( Exception ex ) { batchQueue . offer ( wb ) ; for ( WriteBatch currentBatch : batchQueue ) { for ( WriteCommand currentWrite : currentBatch . getWrites ( ) ) { try { currentWrite . getLocation ( ) . getWriteCallback ( ) . onError ( currentWrite . getLocation ( ) , ex ) ; } catch ( Throwable innerEx ) { warn ( innerEx , innerEx . getMessage ( ) ) ; } } currentBatch . getLatch ( ) . countDown ( ) ; } asyncException . compareAndSet ( null , ex ) ; } finally { writing . set ( false ) ; } } } ) ; } } package journal . io . api ; public interface WriteCallback { void onSync ( Location syncedLocation ) ; void onError ( Location location , Throwable error ) ; } package journal . io . api ; public interface ReplicationTarget { void replicate ( Location startLocation , byte [ ] data ) ; } package journal . io . util ; import java . util . logging . Level ; import java . util . logging . Logger ; public class LogHelper { private static final Logger LOG = Logger . getLogger ( LogHelper . class . getName ( ) ) ; public static void warn ( String message , Object ... args ) { if ( LOG . isLoggable ( Level . WARNING ) ) { LOG . log ( Level . WARNING , String . format ( message , args ) ) ; } } public static void warn ( Throwable e , String message ) { if ( LOG . isLoggable ( Level . WARNING ) ) { LOG . log ( Level . WARNING , message , e ) ; } } public static void warn ( Throwable e , String message , Object ... args ) { if ( LOG . isLoggable ( Level . WARNING ) ) { LOG . log ( Level . WARNING , String . format ( message , args ) , e ) ; } } public static void error ( String message , Object ... args ) { if ( LOG . isLoggable ( Level . SEVERE ) ) { LOG . log ( Level . SEVERE , String . format ( message , args ) ) ; } } public static void error ( Throwable e , String message ) { if ( LOG . isLoggable ( Level . SEVERE ) ) { LOG . log ( Level . SEVERE , message , e ) ; } } public static void error ( Throwable e , String message , Object ... args ) { if ( LOG . isLoggable ( Level . SEVERE ) ) { LOG . log ( Level . SEVERE , String . format ( message , args ) , e ) ; } } } package journal . io . util ; import java . io . File ; import java . io . FileDescriptor ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; public final class IOHelper { protected static final int MAX_DIR_NAME_LENGTH ; protected static final int MAX_FILE_NAME_LENGTH ; private static final int DEFAULT_BUFFER_SIZE = ; private IOHelper ( ) { } public static boolean deleteFile ( File fileToDelete ) { if ( fileToDelete == null || ! fileToDelete . exists ( ) ) { return true ; } boolean result = deleteChildren ( fileToDelete ) ; result &= fileToDelete . delete ( ) ; return result ; } public static boolean deleteChildren ( File parent ) { if ( parent == null || ! parent . exists ( ) ) { return false ; } boolean result = true ; if ( parent . isDirectory ( ) ) { File [ ] files = parent . listFiles ( ) ; if ( files == null ) { result = false ; } else { for ( int i = ; i < files . length ; i ++ ) { File file = files [ i ] ; if ( file . getName ( ) . equals ( "" ) || file . getName ( ) . equals ( "" ) ) { continue ; } if ( file . isDirectory ( ) ) { result &= deleteFile ( file ) ; } else { result &= file . delete ( ) ; } } } } return result ; } public static void moveFile ( File src , File targetDirectory ) throws IOException { if ( ! src . renameTo ( new File ( targetDirectory , src . getName ( ) ) ) ) { throw new IOException ( "" + src + "" + targetDirectory ) ; } } public static void copyFile ( File src , File dest ) throws IOException { FileInputStream fileSrc = new FileInputStream ( src ) ; FileOutputStream fileDest = new FileOutputStream ( dest ) ; copyInputStream ( fileSrc , fileDest ) ; } public static void copyInputStream ( InputStream in , OutputStream out ) throws IOException { byte [ ] buffer = new byte [ DEFAULT_BUFFER_SIZE ] ; int len = in . read ( buffer ) ; while ( len >= ) { out . write ( buffer , , len ) ; len = in . read ( buffer ) ; } in . close ( ) ; out . close ( ) ; } public static void sync ( FileDescriptor fd ) throws IOException { IO_STRATEGY . sync ( fd ) ; } static { MAX_DIR_NAME_LENGTH = Integer . valueOf ( System . getProperty ( "" , "" ) ) . intValue ( ) ; MAX_FILE_NAME_LENGTH = Integer . valueOf ( System . getProperty ( "" , "" ) ) . intValue ( ) ; } public interface IOStrategy { void sync ( FileDescriptor fdo ) throws IOException ; } static final IOStrategy IO_STRATEGY = createIOStrategy ( ) ; private static IOStrategy createIOStrategy ( ) { return new IOStrategy ( ) { public void sync ( FileDescriptor fd ) throws IOException { fd . sync ( ) ; } } ; } } package journal . io . api ; import java . io . File ; import java . io . IOException ; import java . util . Iterator ; import java . util . NoSuchElementException ; import java . util . concurrent . * ; import java . util . concurrent . atomic . AtomicInteger ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import static org . junit . Assert . * ; public class JournalTest { private Journal journal ; private File dir ; @ Before public void setUp ( ) throws Exception { dir = new File ( "" ) ; if ( dir . exists ( ) ) { deleteFilesInDirectory ( dir ) ; } else { dir . mkdirs ( ) ; } journal = new Journal ( ) ; journal . setDirectory ( dir ) ; configure ( journal ) ; journal . open ( ) ; } @ After public void tearDown ( ) throws Exception { journal . close ( ) ; deleteFilesInDirectory ( dir ) ; dir . delete ( ) ; } @ Test ( expected = IOException . class ) public void testAsyncSpeculativeReadWorksButSyncReadRaisesException ( ) throws Exception { Location data = journal . write ( new String ( "" ) . getBytes ( "" ) , Journal . WriteType . SYNC ) ; journal . delete ( data ) ; assertEquals ( "" , journal . read ( data , Journal . ReadType . ASYNC ) ) ; journal . read ( data , Journal . ReadType . SYNC ) ; } @ Test public void testSyncLogWritingAndRedoing ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( new String ( "" + i ) . getBytes ( "" ) , Journal . WriteType . SYNC ) ; } int i = ; for ( Location location : journal . redo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + i ++ , new String ( buffer , "" ) ) ; } } @ Test public void testSyncLogWritingAndUndoing ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( new String ( "" + i ) . getBytes ( "" ) , Journal . WriteType . SYNC ) ; } int i = ; for ( Location location : journal . undo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + -- i , new String ( buffer , "" ) ) ; } } @ Test public void testAsyncLogWritingAndRedoing ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( new String ( "" + i ) . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; } int i = ; for ( Location location : journal . redo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . SYNC ) ; assertEquals ( "" + i ++ , new String ( buffer , "" ) ) ; } } @ Test public void testAsyncLogWritingAndUndoing ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( new String ( "" + i ) . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; } int i = ; for ( Location location : journal . undo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + -- i , new String ( buffer , "" ) ) ; } } @ Test public void testMixedSyncAsyncLogWritingAndRedoing ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; } int i = ; for ( Location location : journal . redo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + i ++ , new String ( buffer , "" ) ) ; } } @ Test public void testMixedSyncAsyncLogWritingAndUndoing ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; } int i = ; for ( Location location : journal . undo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + -- i , new String ( buffer , "" ) ) ; } } @ Test public void testRedoForwardOrder ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > redo = journal . redo ( ) . iterator ( ) ; assertTrue ( redo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( redo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertTrue ( redo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( redo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertTrue ( redo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( redo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertFalse ( redo . hasNext ( ) ) ; } @ Test public void testRedoForwardOrderWithStartingLocation ( ) throws Exception { Location a = journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Location b = journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Location c = journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > redo = journal . redo ( b ) . iterator ( ) ; assertTrue ( redo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( redo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertTrue ( redo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( redo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertFalse ( redo . hasNext ( ) ) ; } @ Test public void testRedoEmptyJournal ( ) throws Exception { int iterations = ; for ( Location loc : journal . redo ( ) ) { iterations ++ ; } assertEquals ( , iterations ) ; } @ Test public void testRedoLargeChunksOfData ( ) throws Exception { byte parts = ; for ( byte i = ; i < parts ; i ++ ) { journal . write ( new byte [ ] { i } , Journal . WriteType . ASYNC ) ; } parts = ; for ( Location loc : journal . redo ( ) ) { assertArrayEquals ( new byte [ ] { parts ++ } , journal . read ( loc , Journal . ReadType . ASYNC ) ) ; } assertEquals ( , parts ) ; } @ Test public void testRedoTakesNewWritesIntoAccount ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > redo = journal . redo ( ) . iterator ( ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; assertEquals ( "" , new String ( journal . read ( redo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertEquals ( "" , new String ( journal . read ( redo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertEquals ( "" , new String ( journal . read ( redo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; } @ Test public void testRemoveThroughRedo ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > itr = journal . redo ( ) . iterator ( ) ; int iterations = ; while ( itr . hasNext ( ) ) { itr . next ( ) ; itr . remove ( ) ; iterations ++ ; } assertEquals ( , iterations ) ; iterations = ; for ( Location loc : journal . redo ( ) ) { iterations ++ ; } assertEquals ( , iterations ) ; } @ Test ( expected = NoSuchElementException . class ) public void testNoSuchElementExceptionWithRedoIterator ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > itr = journal . redo ( ) . iterator ( ) ; assertTrue ( itr . hasNext ( ) ) ; itr . next ( ) ; assertFalse ( itr . hasNext ( ) ) ; itr . next ( ) ; } @ Test ( expected = IllegalStateException . class ) public void testIllegalStateExceptionIfTheSameLocationIsRemovedThroughRedoMoreThanOnce ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > itr = journal . redo ( ) . iterator ( ) ; itr . next ( ) ; itr . remove ( ) ; itr . remove ( ) ; } @ Test ( expected = IllegalStateException . class ) public void testIllegalStateExceptionIfCallingRemoveBeforeNextWithRedo ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > itr = journal . redo ( ) . iterator ( ) ; itr . remove ( ) ; } @ Test public void testUndoBackwardOrder ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > undo = journal . undo ( ) . iterator ( ) ; assertTrue ( undo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( undo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertTrue ( undo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( undo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertTrue ( undo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( undo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertFalse ( undo . hasNext ( ) ) ; } @ Test public void testUndoBackwardOrderWithEndingLocation ( ) throws Exception { Location a = journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Location b = journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Location c = journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > undo = journal . undo ( b ) . iterator ( ) ; assertTrue ( undo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( undo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertTrue ( undo . hasNext ( ) ) ; assertEquals ( "" , new String ( journal . read ( undo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertFalse ( undo . hasNext ( ) ) ; } @ Test public void testUndoEmptyJournal ( ) throws Exception { int iterations = ; for ( Location loc : journal . undo ( ) ) { iterations ++ ; } assertEquals ( , iterations ) ; } @ Test public void testUndoLargeChunksOfData ( ) throws Exception { byte parts = ; for ( byte i = ; i < parts ; i ++ ) { journal . write ( new byte [ ] { i } , Journal . WriteType . ASYNC ) ; } parts = ; for ( Location loc : journal . undo ( ) ) { assertArrayEquals ( new byte [ ] { -- parts } , journal . read ( loc , Journal . ReadType . ASYNC ) ) ; } assertEquals ( , parts ) ; } @ Test public void testUndoDoesntTakeNewWritesIntoAccount ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > undo = journal . undo ( ) . iterator ( ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; assertEquals ( "" , new String ( journal . read ( undo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertEquals ( "" , new String ( journal . read ( undo . next ( ) , Journal . ReadType . ASYNC ) , "" ) ) ; assertFalse ( undo . hasNext ( ) ) ; } @ Test public void testRemoveThroughUndo ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > itr = journal . undo ( ) . iterator ( ) ; int iterations = ; while ( itr . hasNext ( ) ) { itr . next ( ) ; itr . remove ( ) ; iterations ++ ; } assertEquals ( , iterations ) ; iterations = ; for ( Location loc : journal . undo ( ) ) { iterations ++ ; } assertEquals ( , iterations ) ; } @ Test ( expected = NoSuchElementException . class ) public void testNoSuchElementExceptionWithUndoIterator ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > itr = journal . undo ( ) . iterator ( ) ; assertTrue ( itr . hasNext ( ) ) ; itr . next ( ) ; assertFalse ( itr . hasNext ( ) ) ; itr . next ( ) ; } @ Test ( expected = IllegalStateException . class ) public void testIllegalStateExceptionIfTheSameLocationIsRemovedThroughUndoMoreThanOnce ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > itr = journal . undo ( ) . iterator ( ) ; itr . next ( ) ; itr . remove ( ) ; itr . remove ( ) ; } @ Test ( expected = IllegalStateException . class ) public void testIllegalStateExceptionIfCallingRemoveBeforeNextWithUndo ( ) throws Exception { journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; Iterator < Location > itr = journal . undo ( ) . iterator ( ) ; itr . remove ( ) ; } @ Test public void testLogRecoveryWithFollowingWrites ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; } journal . close ( ) ; journal . open ( ) ; for ( int i = iterations ; i < iterations * ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; } int index = ; for ( Location location : journal . redo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + index ++ , new String ( buffer , "" ) ) ; } assertEquals ( iterations * , index ) ; } @ Test public void testLogRecoveryWithDeletes ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; Location written = journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; journal . delete ( written ) ; } journal . close ( ) ; journal . open ( ) ; } @ Test public void testLogRecoveryWithDeletesAndCompact ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; Location written = journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; journal . delete ( written ) ; } journal . compact ( ) ; journal . close ( ) ; journal . open ( ) ; } @ Test public void testLogSpanningMultipleFiles ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; } int i = ; for ( Location location : journal . redo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + i ++ , new String ( buffer , "" ) ) ; } } @ Test public void testLogCompaction ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations / ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; Location toDelete = journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; journal . delete ( toDelete ) ; } for ( int i = iterations / ; i < iterations ; i ++ ) { Journal . WriteType sync = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; journal . write ( new String ( "" + i ) . getBytes ( "" ) , sync ) ; } int preCleanupFiles = journal . getFiles ( ) . size ( ) ; journal . compact ( ) ; assertTrue ( journal . getFiles ( ) . size ( ) < preCleanupFiles ) ; int i = iterations / ; for ( Location location : journal . redo ( ) ) { byte [ ] buffer = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + i ++ , new String ( buffer , "" ) ) ; } } @ Test ( expected = IOException . class ) public void testCannotReadDeletedLocation ( ) throws Exception { Location location = journal . write ( "" . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; journal . delete ( location ) ; journal . read ( location , Journal . ReadType . ASYNC ) ; fail ( "" ) ; } @ Test public void testWriteCallbackOnSync ( ) throws Exception { final int iterations = ; final CountDownLatch writeLatch = new CountDownLatch ( iterations ) ; WriteCallback callback = new WriteCallback ( ) { @ Override public void onSync ( Location syncedLocation ) { writeLatch . countDown ( ) ; } @ Override public void onError ( Location location , Throwable error ) { } } ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( new byte [ ] { ( byte ) i } , Journal . WriteType . ASYNC , callback ) ; } journal . sync ( ) ; assertTrue ( writeLatch . await ( , TimeUnit . SECONDS ) ) ; } @ Test public void testWriteCallbackOnError ( ) throws Exception { final int iterations = ; final CountDownLatch writeLatch = new CountDownLatch ( iterations ) ; WriteCallback callback = new WriteCallback ( ) { @ Override public void onSync ( Location syncedLocation ) { } @ Override public void onError ( Location location , Throwable error ) { writeLatch . countDown ( ) ; } } ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( new byte [ ] { ( byte ) i } , Journal . WriteType . ASYNC , callback ) ; } deleteFilesInDirectory ( dir ) ; dir . delete ( ) ; try { journal . sync ( ) ; } catch ( Exception ex ) { } assertTrue ( writeLatch . await ( , TimeUnit . SECONDS ) ) ; } @ Test public void testSyncAndCallReplicator ( ) throws Exception { final int iterations = ; final CountDownLatch writeLatch = new CountDownLatch ( ) ; ReplicationTarget replicator = new ReplicationTarget ( ) { public void replicate ( Location startLocation , byte [ ] data ) { if ( startLocation . getDataFileId ( ) == && startLocation . getPointer ( ) == ) { writeLatch . countDown ( ) ; } } } ; journal . setReplicationTarget ( replicator ) ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( new String ( "" + i ) . getBytes ( "" ) , Journal . WriteType . ASYNC ) ; } journal . sync ( ) ; assertTrue ( writeLatch . await ( , TimeUnit . SECONDS ) ) ; } @ Test public void testBatchWriteCompletesAfterClose ( ) throws Exception { byte [ ] data = "" . getBytes ( ) ; final int iterations = ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( data , Journal . WriteType . ASYNC ) ; } journal . close ( ) ; assertTrue ( journal . getInflightWrites ( ) . isEmpty ( ) ) ; } @ Test public void testNoBatchWriteWithSync ( ) throws Exception { byte [ ] data = "" . getBytes ( ) ; final int iterations = ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( data , Journal . WriteType . SYNC ) ; assertTrue ( journal . getInflightWrites ( ) . isEmpty ( ) ) ; } } @ Test public void testConcurrentWriteAndRead ( ) throws Exception { final AtomicInteger counter = new AtomicInteger ( ) ; ExecutorService executor = Executors . newFixedThreadPool ( ) ; int iterations = ; for ( int i = ; i < iterations ; i ++ ) { final int index = i ; executor . submit ( new Runnable ( ) { public void run ( ) { try { Journal . WriteType sync = index % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; String write = new String ( "" + index ) ; Location location = journal . write ( write . getBytes ( "" ) , sync ) ; String read = new String ( journal . read ( location , Journal . ReadType . ASYNC ) , "" ) ; if ( read . equals ( "" + index ) ) { counter . incrementAndGet ( ) ; } else { System . out . println ( write ) ; System . out . println ( read ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } ) ; } executor . shutdown ( ) ; assertTrue ( executor . awaitTermination ( , TimeUnit . MINUTES ) ) ; assertEquals ( iterations , counter . get ( ) ) ; } @ Test public void testCompactionDuringConcurrentWriteAndRead ( ) throws Exception { final AtomicInteger counter = new AtomicInteger ( ) ; ExecutorService executor = Executors . newFixedThreadPool ( ) ; int iterations = ; for ( int i = ; i < iterations ; i ++ ) { final int index = i ; executor . submit ( new Runnable ( ) { public void run ( ) { try { Journal . WriteType sync = index % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; String write = new String ( "" + index ) ; Location location = journal . write ( write . getBytes ( "" ) , sync ) ; String read = new String ( journal . read ( location , Journal . ReadType . ASYNC ) , "" ) ; if ( read . equals ( "" + index ) ) { if ( index % == ) { journal . delete ( location ) ; } counter . incrementAndGet ( ) ; } else { System . out . println ( write ) ; System . out . println ( read ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } ) ; } executor . submit ( new Runnable ( ) { public void run ( ) { try { journal . compact ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } ) ; executor . shutdown ( ) ; assertTrue ( executor . awaitTermination ( , TimeUnit . MINUTES ) ) ; assertEquals ( iterations , counter . get ( ) ) ; int locations = ; for ( Location current : journal . redo ( ) ) { locations ++ ; } assertEquals ( iterations - ( iterations / ) , locations ) ; } @ Test public void testOpenAndRecoveryWithNewJournalInstanceAfterLargeNumberOfWrites ( ) throws Exception { int iterations = ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( new String ( "" + i ) . getBytes ( "" ) , Journal . WriteType . SYNC ) ; } journal . close ( ) ; Journal newJournal = new Journal ( ) ; newJournal . setDirectory ( dir ) ; configure ( newJournal ) ; newJournal . open ( ) ; int i = ; for ( Location location : newJournal . redo ( ) ) { byte [ ] buffer = newJournal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + i ++ , new String ( buffer , "" ) ) ; } assertEquals ( iterations , i ) ; } @ Test public void testJournalWithExternalExecutor ( ) throws Exception { Journal customJournal = new Journal ( ) ; customJournal . setDirectory ( dir ) ; customJournal . setWriter ( Executors . newFixedThreadPool ( ) ) ; configure ( customJournal ) ; customJournal . open ( ) ; int iterations = ; for ( int i = ; i < iterations ; i ++ ) { customJournal . write ( new String ( "" + i ) . getBytes ( "" ) , Journal . WriteType . SYNC ) ; } int i = ; for ( Location location : customJournal . redo ( ) ) { byte [ ] buffer = customJournal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + i ++ , new String ( buffer , "" ) ) ; } assertEquals ( iterations , i ) ; } @ Test public void testJournalWithExternalExecutorAndExecuteWritesWithExecutor ( ) throws Exception { final Journal customJournal = new Journal ( ) ; ExecutorService executor = Executors . newFixedThreadPool ( ) ; customJournal . setDirectory ( dir ) ; customJournal . setWriter ( executor ) ; configure ( customJournal ) ; customJournal . open ( ) ; final byte [ ] bytes = "" . getBytes ( ) ; int iterations = ; for ( int i = ; i < iterations ; i ++ ) { executor . submit ( new Callable < Location > ( ) { public Location call ( ) throws IOException { return customJournal . write ( bytes , Journal . WriteType . SYNC ) ; } } ) . get ( , TimeUnit . SECONDS ) ; } } protected void configure ( Journal journal ) { journal . setMaxFileLength ( ) ; journal . setMaxWriteBatchSize ( ) ; } private void deleteFilesInDirectory ( File directory ) { File [ ] files = directory . listFiles ( ) ; if ( files != null ) { for ( int i = ; i < files . length ; i ++ ) { File f = files [ i ] ; if ( f . isDirectory ( ) ) { deleteFilesInDirectory ( f ) ; } f . delete ( ) ; } } } } package journal . io . api ; import java . io . File ; import org . junit . After ; import org . junit . Before ; import org . junit . Ignore ; import org . junit . Test ; @ Ignore public class JournalPerformanceTest { private Journal journal ; private File dir ; @ Before public void setUp ( ) throws Exception { dir = new File ( "" ) ; if ( dir . exists ( ) ) { deleteFilesInDirectory ( dir ) ; } else { dir . mkdirs ( ) ; } journal = new Journal ( ) ; journal . setDirectory ( dir ) ; configure ( journal ) ; journal . open ( ) ; } @ After public void tearDown ( ) throws Exception { journal . close ( ) ; deleteFilesInDirectory ( dir ) ; dir . delete ( ) ; } @ Test public void testSyncPerf ( ) throws Exception { long start = System . currentTimeMillis ( ) ; int iterations = ; byte [ ] payload = new byte [ ] ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( payload , Journal . WriteType . SYNC ) ; } journal . close ( ) ; System . out . println ( "" + ( System . currentTimeMillis ( ) - start ) ) ; } @ Test public void testAsyncPerf ( ) throws Exception { long start = System . currentTimeMillis ( ) ; int iterations = ; byte [ ] payload = new byte [ ] ; for ( int i = ; i < iterations ; i ++ ) { journal . write ( payload , Journal . WriteType . ASYNC ) ; } journal . close ( ) ; System . out . println ( "" + ( System . currentTimeMillis ( ) - start ) ) ; } protected void configure ( Journal journal ) { journal . setMaxFileLength ( * * ) ; journal . setMaxWriteBatchSize ( * ) ; } private void deleteFilesInDirectory ( File directory ) { File [ ] files = directory . listFiles ( ) ; if ( files != null ) { for ( int i = ; i < files . length ; i ++ ) { File f = files [ i ] ; if ( f . isDirectory ( ) ) { deleteFilesInDirectory ( f ) ; } f . delete ( ) ; } } } } package journal . io . api ; import java . io . File ; import org . junit . Before ; import org . junit . Test ; import static org . junit . Assert . * ; public class ApiTest { private static File JOURNAL_DIR ; @ Test public void api ( ) throws Exception { Journal journal = new Journal ( ) ; journal . setDirectory ( JOURNAL_DIR ) ; journal . setArchiveFiles ( false ) ; journal . setChecksum ( true ) ; journal . setMaxFileLength ( * ) ; journal . setMaxWriteBatchSize ( * ) ; journal . open ( ) ; int iterations = ; for ( int i = ; i < iterations ; i ++ ) { Journal . WriteType writeType = i % == ? Journal . WriteType . SYNC : Journal . WriteType . ASYNC ; journal . write ( new String ( "" + i ) . getBytes ( "" ) , writeType ) ; } int i = ; for ( Location location : journal . redo ( ) ) { byte [ ] record = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + i ++ , new String ( record , "" ) ) ; } int j = ; for ( Location location : journal . undo ( ) ) { byte [ ] record = journal . read ( location , Journal . ReadType . ASYNC ) ; assertEquals ( "" + -- i , new String ( record , "" ) ) ; } journal . close ( ) ; } @ Before public void setUp ( ) throws Exception { JOURNAL_DIR = File . createTempFile ( "" , "" , null ) ; JOURNAL_DIR . delete ( ) ; JOURNAL_DIR . mkdir ( ) ; } }